{"text": "Require Import init.\n\nRequire Import nat_plus.\n\nRequire Export mult.\n\nGlobal Instance nat_mult : Mult nat := {\n    mult := fix mult a b :=\n        match a with\n            | nat_suc a' => b + mult a' b\n            | nat_zero => 0\n        end\n}.\n\nLemma nat_mult_lanni_tmp : ∀ a, 0 * a = 0.\nProof.\n    intros a.\n    unfold mult, zero at 1; cbn.\n    reflexivity.\nQed.\n\nGlobal Instance nat_one : One nat := {\n    one := nat_suc nat_zero;\n}.\nLtac nat_induction n ::=\n    induction n;\n    change nat_zero with (zero (U := nat)) in *;\n    change (nat_suc zero) with (one (U := nat)) in *.\nLtac nat_destruct n ::=\n    destruct n;\n    change nat_zero with (zero (U := nat)) in *;\n    change (nat_suc zero) with (one (U := nat)) in *.\n\nTheorem nat_one_eq : nat_suc 0 = 1.\nProof.\n    reflexivity.\nQed.\n\nGlobal Instance nat_mult_lid : MultLid nat.\nProof.\n    split.\n    intros a.\n    unfold one, mult; cbn.\n    apply plus_rid.\nQed.\n\nTheorem nat_mult_lsuc : ∀ a b, nat_suc a * b = b + a * b.\nProof.\n    reflexivity.\nQed.\nTheorem nat_mult_rsuc : ∀ a b, a * nat_suc b = a + a * b.\nProof.\n    intros a b.\n    nat_induction a.\n    -   do 2 rewrite nat_mult_lanni_tmp.\n        rewrite plus_rid.\n        reflexivity.\n    -   do 2 rewrite nat_mult_lsuc.\n        rewrite IHa.\n        do 2 rewrite plus_assoc.\n        rewrite nat_plus_lsuc.\n        rewrite (nat_plus_lsuc a b).\n        rewrite (plus_comm a b).\n        reflexivity.\nQed.\n\nGlobal Instance nat_ldist : Ldist nat.\nProof.\n    split.\n    intros a b c.\n    nat_induction a.\n    -   do 3 rewrite nat_mult_lanni_tmp.\n        rewrite plus_lid.\n        reflexivity.\n    -   do 3 rewrite nat_mult_lsuc.\n        rewrite IHa.\n        do 2 rewrite <- plus_assoc.\n        apply lplus.\n        do 2 rewrite plus_assoc.\n        apply rplus.\n        apply plus_comm.\nQed.\n\nGlobal Instance nat_mult_comm : MultComm nat.\nProof.\n    split.\n    intros a b.\n    nat_induction a.\n    -   rewrite nat_mult_lanni_tmp.\n        rewrite mult_ranni.\n        reflexivity.\n    -   rewrite nat_mult_lsuc.\n        rewrite nat_mult_rsuc.\n        rewrite IHa.\n        reflexivity.\nQed.\n\nGlobal Instance nat_mult_assoc : MultAssoc nat.\nProof.\n    split.\n    intros a b c.\n    nat_induction a.\n    -   do 3 rewrite mult_lanni.\n        reflexivity.\n    -   do 2 rewrite nat_mult_lsuc.\n        rewrite IHa.\n        rewrite rdist.\n        reflexivity.\nQed.\n\nTheorem nat_neq_suc_mult : ∀ a b, 0 ≠ nat_suc a * nat_suc b.\nProof.\n    intros a b contr.\n    rewrite nat_mult_lsuc in contr.\n    rewrite nat_plus_lsuc in contr.\n    exact (nat_zero_suc contr).\nQed.\n\nGlobal Instance nat_mult_lcancel : MultLcancel nat.\nProof.\n    split.\n    intros a b c c_neq eq.\n    nat_destruct c; [>contradiction|].\n    clear c_neq.\n    revert b eq.\n    nat_induction a; intros b eq.\n    -   nat_destruct b; [>reflexivity|].\n        exfalso.\n        rewrite mult_ranni in eq.\n        exact (nat_neq_suc_mult _ _ eq).\n    -   nat_destruct b.\n        +   exfalso; clear IHa.\n            rewrite mult_ranni in eq.\n            symmetry in eq.\n            exact (nat_neq_suc_mult _ _ eq).\n        +   apply f_equal.\n            apply IHa.\n            do 2 rewrite nat_mult_rsuc in eq.\n            apply plus_lcancel in eq.\n            exact eq.\nQed.\n\n#[refine]\nGlobal Instance nat_not_trivial_class : NotTrivial nat := {\n    not_trivial_a := 0;\n    not_trivial_b := 1;\n}.\nProof.\n    apply nat_zero_suc.\nQed.\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Number/Nat/nat_mult.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.699981687024643}}
{"text": "CoInductive CoNat : Set := \n| Zero : CoNat\n| Succ : CoNat -> CoNat.\n\nCoFixpoint plus (x: CoNat) (y: CoNat) : CoNat := \n  match x with \n    | Zero => y \n    | Succ x' => Succ (plus x' y)\n  end.\n\nCoInductive CoList : Set := \n| CoNil : CoList \n| CoCons : CoNat -> CoList -> CoList.\n\nCoFixpoint sumlen (xs : CoList) : CoNat := \n  match xs with\n    | CoNil => Zero\n    | CoCons x' xs' => Succ (f x' xs')\n  end\nwith f (n : CoNat) (xs : CoList) : CoNat :=\n  match n with \n    | Zero => sumlen xs\n    | Succ x' => Succ (f x' xs)\n  end.\n\n  sumlen [] = Zero \n  sumlen (n:xs) = Succ(f xs)\n  f Zero xs = sumlen xs\n  f (Succ x) xs = Succ(f x xs)\n\n", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/cosum3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6999816865289897}}
{"text": "Add LoadPath \".\" as OPAT.\nRequire Import OPAT.doit3 OPAT.doit5 OPAT.aula3 OPAT.aula5 OPAT.aula6 OPAT.aula7 OPAT.aula8.\n\n(** **** Exercise: 3 stars (list_exercises)  *)\n(** More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l. induction l as [ | l l' IHl'].\n  - reflexivity.\n  - simpl. rewrite IHl'. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros l1 l2. induction l1 as [ | l l1' IHl1'].\n  - simpl. rewrite app_nil_r. reflexivity.\n  - simpl. rewrite IHl1'. rewrite app_assoc. reflexivity.\nQed.\n\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l. simpl. induction l as [ | n l1' IHl1'].\n  - simpl. reflexivity.\n  - simpl. rewrite rev_app_distr. simpl. rewrite IHl1'. reflexivity.\nQed.\n\n(** There is a short solution to the next one.  If you find yourself\n    getting tangled up, step back and try to look for a simpler\n    way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros l1 l2 l3 l4. rewrite app_assoc. rewrite app_assoc. reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2. induction l1 as [ | n l1' IHl1'].\n  - reflexivity.\n  - destruct n.\n      + simpl. rewrite IHl1'. reflexivity.\n      + simpl. rewrite IHl1'. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** 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\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nCheck beq_nat.\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1 with\n  | nil => match l2 with\n           | nil => true\n           | n :: t => false\n           end\n  | n1 :: t1 => match l2 with\n                | nil => false\n                | n2 :: t2 => beq_nat n1 n2 && beq_natlist t1 t2\n                end\n  end.\n\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\nreflexivity. Qed.\n\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\nreflexivity. Qed.\n\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\nreflexivity. Qed.\n\nLemma beq_nat_refl : forall n:nat,\n  true = beq_nat n n.\nProof.\n   intros n. induction n.\n   - reflexivity.\n   - simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  intros l. induction l as [ | n l1' IHl1'].\n  - reflexivity.\n  - simpl. rewrite <- beq_nat_refl. rewrite <- IHl1'. reflexivity.\nQed.\n\n\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective)  *)\n(** Prove that the [rev] function is injective -- that is,\n\n    forall (l1 l2 : natlist), rev\n l1 = rev l2 -> l1 = l2.\n\n(There is a hard way and an easy way to do this.) *)\n\nTheorem rev_injective : forall (l1 l2 : natlist),\n    rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2 p.\n  rewrite <- rev_involutive.\n  rewrite <- p.\n  rewrite rev_involutive.\n  reflexivity.\nQed.\n\n(** [] *)\n", "meta": {"author": "bugarela", "repo": "Coq", "sha": "9f4973fec5b34ed836aa2239a009385e0549c024", "save_path": "github-repos/coq/bugarela-Coq", "path": "github-repos/coq/bugarela-Coq/Coq-9f4973fec5b34ed836aa2239a009385e0549c024/OPAT exercises/doit6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.9005297861178929, "lm_q1q2_score": 0.6999816777331125}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq fintype bigop path choice finset fingraph.\nRequire Import automata regexp misc.\n\nSet Implicit Arguments.\n\nSection RE_FA.\n  Import Automata.\n  \n  Variable char: finType.\n  Definition word:= word char.\n\n  Fixpoint re_to_dfa (r: regular_expression char): dfa char :=\n    match r with\n    | Void => dfa_void char\n    | Eps => dfa_eps char\n    | Dot => dfa_dot char\n    | Atom a => dfa_char char a\n    | Star s => nfa_star (dfa_to_nfa (re_to_dfa s))\n    | Plus s t => dfa_disj (re_to_dfa s) (re_to_dfa t)\n    | And s t => dfa_conj (re_to_dfa s) (re_to_dfa t)\n    | Conc s t => nfa_to_dfa (nfa_conc (dfa_to_nfa (re_to_dfa s)) (dfa_to_nfa (re_to_dfa t)))\n    | Not s => dfa_compl (re_to_dfa s)\n    end.\n\n  Lemma re_to_dfa_correct r: dfa_lang (re_to_dfa r) =i r.\n  Proof.\n    elim: r => [].\n\n    move => w. apply/idP/idP. exact: dfa_void_correct.\n\n    exact: dfa_eps_correct.\n    \n    move => w.\n    rewrite -topredE /= /dot.\n    exact: dfa_dot_correct.\n\n    move => a. \n    move => w. exact: dfa_char_correct.\n\n    (* Star *)\n    move => s IHs.\n    move => w.\n    rewrite nfa_star_correct.\n    apply/starP/starP.\n      move => [] vv.\n      move => H0 H1.\n      exists vv.\n      erewrite (eq_all).\n          eexact H0.\n        move => x /=.\n        apply/andP/andP; move => [] H2 H3; split => //.\n          rewrite -dfa_to_nfa_correct.\n          move: H3. by rewrite -IHs.\n        move: H3. \n        rewrite -dfa_to_nfa_correct.\n        by rewrite -IHs.\n      exact H1.\n    move => [] vv H1 H2. exists vv => //.\n    erewrite eq_all. eexact H1.\n    move => x /=.\n    apply/andb_id2l => H3.\n    by rewrite -IHs -dfa_to_nfa_correct.\n     \n        \n    move => s Hs t Ht.\n    move => w. rewrite -dfa_disj_correct in_simpl /=.\n    by rewrite Ht Hs /=.\n\n    move => s Hs t Ht.\n    move => w. rewrite -dfa_conj_correct in_simpl /=.\n    by rewrite Hs Ht /=.\n\n    move => s Hs t Ht.\n    move => w. rewrite -nfa_to_dfa_correct. \n    apply/idP/idP.\n    move/nfa_conc_aux1 => [] w1 [] w2 /andP [] /andP [] /eqP H0 H1 H2.\n    rewrite -topredE /=.\n    apply/concP.\n    exists w1. by rewrite -Hs -topredE /= dfa_to_nfa_correct' /nfa_lang /= H1.\n    exists w2. rewrite /= in H2. by rewrite -Ht dfa_to_nfa_correct in_simpl H2.\n    exact H0.\n    move/concP => [] w1. rewrite -Hs => H1 [] w2. rewrite -Ht => H2 ->.\n    apply/nfa_conc_aux2.\n      move: H1. by rewrite  dfa_to_nfa_correct /nfa_lang /=.\n    move: H2. by rewrite dfa_to_nfa_correct /nfa_lang /=.\n                 \n    move => s H.\n    move => w. by rewrite -dfa_compl_correct -topredE /= H.\n  Qed.\n\n  Definition re_equiv r s := dfa_equiv (re_to_dfa r) (re_to_dfa s).\n  \n  Lemma re_equiv_correct r s: re_equiv r s <-> r =i s.\n  Proof.\n    rewrite dfa_equiv_correct.\n    split => H w. \n      move/H: (w). by rewrite !re_to_dfa_correct.\n    by rewrite !re_to_dfa_correct.\n  Qed.\n\nEnd RE_FA.\n\n", "meta": {"author": "YaccConstructor", "repo": "YC_in_Coq", "sha": "d94a9ec10d532b86ae4f48871c38369f9ce5f1d8", "save_path": "github-repos/coq/YaccConstructor-YC_in_Coq", "path": "github-repos/coq/YaccConstructor-YC_in_Coq/YC_in_Coq-d94a9ec10d532b86ae4f48871c38369f9ce5f1d8/aut/re_fa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.6999816647871224}}
{"text": "Require Import Coq.Lists.List Program Arith NArith Lia.\nImport ListNotations.\nRequire Import SyDPaCC.Support.NList SyDPaCC.Support.List.\nSet Implicit Arguments.\nGeneralizable All Variables.\n\n(** * Tupling, pairing, compose *)\n\nDefinition id {A} (x:A) := x.\n\nDefinition tupling A B C (f:A->B)(g:A->C) := fun x => (f x, g x).\n\nDefinition pairing A B C D (f:A->B)(g:C->D) :=\n  fun (pair:A*C) => (f (fst pair), g (snd pair)).\n\nDefinition compose A B C (g : B -> C) (f : A -> B) : A->C :=\n  fun x => g (f x).\n\nDeclare Scope sydpacc_scope.\n\nInfix \"△\" := tupling (at level 41, left associativity) : sydpacc_scope.\n\nInfix \"×\" := pairing (at level 41, left associativity) : sydpacc_scope.\n\nGlobal Infix \"∘\" := compose (at level 40, left associativity) : sydpacc_scope.\n\n#[export] Hint Unfold compose pairing tupling id : sydpacc.\n\nOpen Scope sydpacc_scope.\n\n(*-----------------------------------------------------------------*)\n\n(** * Induction on Lists Seen as Join-Lists *)\n\n(** A Join-List is either:\n    - an empty list,\n    - a singleton list,\n    - the concatenation of two lists.\n    the empty list and concatenation form a monoid. *)\n\nLemma joinlist_induction :\n  forall A, forall P : list A -> Prop, \n      (P nil) ->\n      (forall a, P [a]) ->\n      (forall x y , P x -> P y -> P (x++y)) ->\n      forall l,  P l.\nProof.\n  intros A P Hnil Hsingleton Hconcat l.\n  induction l as [ | a x IH ].\n  - trivial.\n  - replace (a::x) with ([a]++x) by reflexivity.\n    now apply Hconcat.\nQed.\n\n(*-----------------------------------------------------------------*)\n\n(** * Algebraic Properties Defined as Coq Typeclasses *)\n\n(** ** Unit *)\nClass LeftNeutral A B (op: B -> A -> A) (e : B) :=\n  {\n    left_neutral  : forall a, op e a = a\n  }. \n\nClass RightNeutral A B (op: A -> B -> A) (e : B) :=\n  {\n    right_neutral : forall a, op a e =  a\n  }.\n\nClass Neutral A (op: A -> A -> A) (e : A) :=\n  {\n    neutral_left_neutral  :>  LeftNeutral  op e;\n    neutral_right_neutral :>  RightNeutral op e\n  }. \n\n(** ** Associativity  *)\nClass  Associative A (op:A->A->A) :=\n  {\n    associative : forall (x y z: A), op (op x y) z = op x (op y z)\n  }.\n\n(** ** Commutativity  *)\nClass Commutative A (op:A->A->A) :=\n  {\n    commutative : forall (x y: A), op  x y = op y x\n  }.\n\n(** ** Monoid *)\nClass Monoid A (op : A->A->A) (e : A) := \n  {\n    monoid_assoc   :> Associative op; \n    monoid_neutral :> Neutral op e\n  }.\n\n(** ** Distributivity *)\nClass Distributivity  A (otimes:A->A->A) (oplus:A->A->A) :=\n  {\n    left_distributivity :\n      forall x y z,\n        otimes x (oplus y z) =  oplus (otimes x y) (otimes x z);\n\n    right_distributivity :\n      forall x y z, \n        otimes (oplus y z) x = oplus (otimes y x) (otimes z x)\n  }.\n\n(** ** Instances *)\n\n#[export] Instance app_associative (A:Type) : Associative (@List.app A).\nProof.\n  constructor. intros.\n  now rewrite app_assoc.\nQed.\n\n#[export] Instance app_neutral (A:Type) : Neutral (@List.app A) [].\n  repeat constructor; apply app_nil_r.\nQed.\n\n#[export] Instance plus_neutral (A:Type) : Neutral plus 0.\n  repeat constructor; auto with arith.\nQed.\n\n#[export] Instance plus_associative : Associative plus.\n  constructor; auto with arith.\nQed.\n\n#[export] Instance andb_monoid: Monoid andb true.\nProof.\n  repeat constructor.\n  - intros; now rewrite Bool.andb_assoc.\n  - intros; now rewrite Bool.andb_true_r.\nQed.\n\n\n(*-----------------------------------------------------------------*)\n\n(** * Optimization of Arbitrary Functions *)\n\nClass Opt A B (f g:A->B) :=\n  {\n    opt_eq: forall a, f a = g a\n  }.\n\nClass Opt2 A B C (f g:A->B->C) :=\n  {\n    opt2_eq: forall a b, f a b = g a b\n  }.\n\n(*-----------------------------------------------------------------*)\n\n(** * Properties of Folds *)\n\nLemma fold_left_prop A (f:A->A->A) {H:Associative f} :\n  forall l (a b:A), fold_left f l (f a b) = f a (fold_left f l b).\nProof.\n  induction l as [ | x xs IH ].\n  - intros. trivial.\n  - intros a b. simpl.\n    repeat rewrite IH.\n    now rewrite <- (associative a).\nQed.\n\nLemma fold_right_prop A (f:A->A->A) {H:Associative f} : \n  forall l a b, fold_right f (f a b) l = f (fold_right f a l) b.\nProof.\n  induction l as [ | x xs IH ].\n  - trivial.\n  - intros a b. simpl.\n    rewrite IH.\n    now rewrite associative.\nQed.\n\nLemma fold_left_map_r:\n  forall A B C (f:A->B->A) (g :C->B) (l:list C) (a:A),\n    fold_left (fun a b => f a (g b)) l a = fold_left f (map g l) a.\nProof.\n  induction l as [ | a l IHl]; intro.\n  - reflexivity.\n  - simpl; rewrite IHl; reflexivity.\nQed.\n\nLemma fold_right_map_l:\n  forall A B C (f:B->A->A) (g:C->B) (l:list C) (a:A),\n    fold_right (fun a b => f (g a) b) a l = fold_right f a (map g l).\nProof.\n  induction l as [ | a l IHl]; intros.\n  - reflexivity.\n  - simpl.  f_equal; rewrite IHl; reflexivity.\nQed.\n\n(** * [fold_left2] and Properties *)\n\nFixpoint fold_left2 A B C (op:C->A*B->C) (e:C) (l1:list A) (l2:list B): C :=\n  match (l1, l2) with\n  | ([], _ ) | (_ , []) => e\n  | (h1::t1, h2::t2) =>\n    fold_left2 op (op e (h1,h2)) t1 t2\n  end.\n\nLemma fold_left2_prop1:\n  forall A B C (op:C->A*B->C) e l1 l2,\n    fold_left op (combine l1 l2) e = fold_left2 op e l1 l2.\nProof.\n  intros A B C op e l1 l2; revert e l2;\n    induction l1 as [ | h1 t1 IH1]; intros e l2; destruct l2 as [ | h2 t2 ].\n  - trivial.\n  - trivial.\n  - trivial.\n    - simpl; now rewrite IH1.\nQed.\n\nLemma fold_left2_prop2:\n  forall A A' B C op (f:A*B->A') (e:C) l1 l2,\n    fold_left op (map f (combine l1 l2)) e = fold_left2 (fun u p =>op u (f p))  e l1 l2.\nProof.\n  intros A A' B C op f e l1 l2; revert e l2;\n    induction l1 as [ | h1 t1 IH1]; intros e l2; destruct l2 as [ | h2 t2 ]; trivial.\n  simpl; now rewrite IH1.\nQed.\n\n(*-------------------------------------------------------------*)\n\n(** * Prefixes of a Lists and its Properties *)\n\nFixpoint prefix `(xs:list A) := \n  match xs with \n    | [] => [[]]\n    | x::xs => []::(map (cons x) (prefix xs))\n  end.\n\nExample prefix_informal : \n  prefix ([1;2;3])%nat =  ([[]; [1]; [1; 2]; [1; 2; 3]])%nat. \nProof. trivial. Qed.\n\nLemma prefix_snoc (A:Type) : \n  forall (xs:list A)(x:A),\n    prefix (xs++[x]) = prefix xs ++ (map (app xs) [[x]]).\nProof.\n  induction xs as [ | x' xs' IH].\n  - trivial.\n  - intro x. simpl. \n    now rewrite IH, map_app.\nQed.\n\nLemma prefix_app (A:Type) :\n  forall (l l':list A), \n    prefix (l ++ l') = prefix l ++ tl(map (app l) (prefix l')).\nProof.\n  intros l l'; revert l.\n  induction l'.\n  - intros l'. simpl; repeat rewrite app_nil_r. trivial.\n  - intros l.\n    change ( a :: l') with ([a]++l').\n    rewrite app_assoc.\n    rewrite IHl', prefix_snoc, IHl', map_app.\n    simpl.\n    rewrite <- app_assoc.\n    destruct(prefix l') eqn:Heq.\n    + trivial.\n    + simpl; rewrite map_map.\n    do 2 f_equal. apply map_ext.\n    intros. now rewrite <- app_assoc.\nQed.  \n\nLemma prefix_map:\n  forall A B (f:A->B) xs,\n    prefix(map f xs) = map (map f)(prefix xs).\nProof.\n  intros A B f; induction xs as [ | x xs IH].\n  - trivial.\n  - simpl; now rewrite IH, map_map, map_map.\nQed.\n\nLemma prefix_length (A:Type) :  \n  forall (l:list A), List.length (prefix l) = S (List.length l).\nProof.\n  induction l; simpl; try rewrite List.map_length; now f_equal.\nQed.\n\nLemma prefix_contains_nil :\n  forall `(l:list A), exists l', prefix l = [] :: l'.\nProof.\n  induction l as [ | h t IH ].\n  - now eexists.\n  - inversion IH. simpl. eexists. f_equal.\nQed.        \n\n#[export] Hint Rewrite prefix_length : length.\n\n(*-----------------------------------------------------------------*)\n\n(** * Definition and Properties of Prefix Sum Computations *)\n\nFixpoint scanl A B (op:A->B->A)(e:A)(l:list B) : list A := \n  e::match l with \n     | []   => []\n     | h::t => scanl op (op e h) t\n     end.\n\nExample scanl_example  : scanl plus 0 [1;2;3] = [0; 0+1 ; 0+1+2 ; 0+1+2+3].\nProof. reflexivity. Qed.\n\nLemma scanl_spec:\n  forall A B (op:A->B->A) (e:A) (l : list B),\n  scanl op e l =\n  map (fun l => fold_left op l e) (prefix l).\nProof.\n  intros A B op e l; revert op e ; induction l as [ | h t IH].\n  - trivial.\n  - intros op e; simpl.\n    now rewrite IH, map_map.\nQed.\n\nLemma scanl_snoc:\n  forall A B (op:A->B->A) (e:A) (l : list B) (b:B),\n    scanl op e (l ++ [ b ]) = scanl op e l ++ [ fold_left op (l++[b]) e ].\nProof.\n  intros A B op e l; revert e; induction l as [ | h t IH]; intros e b.\n  - trivial.\n  - simpl. now rewrite IH.\nQed.\n  \nFact scanl_cons:\n  forall A B (op:A->B->A) (e:A) (l : list B),\n    scanl op e l = e::tl(scanl op e l).\nProof.\n  intros A B op e l; destruct l; auto.\nQed.\n\nLemma scanl_map_gen:\n  forall A B `{Monoid A op}(xs:list B) (q:B->A) c,\n    scanl (fun s t=>op s (q t)) c xs = map (op c)(scanl (fun s t=>op s (q t)) e xs).\nProof.\n  intros A B op e H xs q c; revert e c H.\n  induction xs as [ | x' xs' IH ]; intros e c H.\n  - simpl; now rewrite right_neutral.\n  - simpl. \n    rewrite IH with (e:=e) by typeclasses eauto.\n    rewrite @right_neutral with (e:=e) by typeclasses eauto.\n    rewrite @left_neutral with (a:=q x') (e:=e) by typeclasses eauto.\n    rewrite IH with (c:=q x')(e:=e) by typeclasses eauto.\n    rewrite map_map.\n    f_equal; apply map_ext; intro; now rewrite associative.\nQed.\n\nLemma scanl_map:\n  forall `{Associative A op} e (x:A)(xs:list A),\n    scanl op (op x e) xs = map (op x)(scanl op e xs).\n  intros A op H e x xs. revert e x. induction xs as [ | x' xs' IH ].\n  - intros; simpl; do 2 f_equal.\n  - intros e x; simpl. f_equal.\n    rewrite <- IH. f_equal.\n    now rewrite associative.\nQed.\n\nLemma map_scanl:\n  forall A B `{Monoid A op}(q:B->A) a c,\n    scanl op c (map q a) =\n    scanl (fun (s : A) (t : B) => op s (q t)) c a.\nProof.\n  intros A B op e H q a c.\n  repeat rewrite scanl_spec.\n  rewrite prefix_map, map_map.\n  apply map_ext; intro x.\n  symmetry. apply fold_left_map_r.\nQed.\n  \nLemma scanl_length:\n  forall (A B:Type)(op:A->B->A)(identity:A)(l:list B),\n    List.length (scanl op identity l) = S (List.length l).\nProof.  \n  intros A B op identity l; generalize dependent identity; induction l as [ | h t IHl]; intros.\n  - trivial.\n  - simpl; now rewrite IHl.\nQed.\n\n#[export] Hint Rewrite scanl_length : length.\n\nFixpoint scanl_aux A B (op:A->B->A)(e:A)(l:list B)(res:list A) : list A :=\n  match l with\n  | [] => rev' (e::res)\n  | h::t => scanl_aux op (op e h) t (e::res)\n  end.\n\nDefinition scanl' A B (op:A->B->A)(e:A)(l:list B) : list A :=\n  scanl_aux op e l [].\n\n#[export] Hint Unfold scanl' : sydpacc.\n\nFact scanl_aux_scanl:\n  forall A B (op:A->B->A) e l l',\n    scanl_aux op e l l' =\n    rev' l' ++ scanl op e l.\nProof.\n  intros A B op e l l'; revert e l';\n    induction l as [ | h t IH ]; intros e l'.\n  - simpl. unfold rev'. simpl.\n    rewrite rev_append_rev.\n    now rewrite rev_alt.\n  - simpl; rewrite IH.\n    unfold rev'; simpl.\n    rewrite rev_append_rev.\n    now rewrite rev_alt, <- List.app_assoc.\nQed.\n \nLemma scanl_scanl':\n  forall A B (op:A->B->A) e l,\n    scanl op e l = scanl' op e l.\nProof.\n  intros A B op e l; revert e; induction l as [ | h t IH ]; intro e.\n  - trivial.\n  - autounfold with sydpacc. simpl.\n    now rewrite scanl_aux_scanl.\nQed.\n\nUnset Implicit Arguments.\n\nDefinition scan A (op:A->A->A) `{Monoid A op e} (l : list A):= scanl op e l.\n\nArguments scan [A] op {e} {_}.\n\nSet Implicit Arguments.\n\n#[export] Hint Unfold scan : sydpacc.\n\nFact scan_spec:\n  forall A `(Monoid A op e) (l : list A),\n  scan op l =\n  map (fun l => fold_left op l e) (prefix l).\nProof.\n  autounfold; intros; apply scanl_spec.\nQed.  \n\nLemma scan_length:\n  forall (A B : Type)`(Monoid A op e)(l:list A),\n    List.length (scan op l) = S(List.length l).\nProof.\n  autounfold; intros; apply scanl_length.\nQed.\n\n#[export] Hint Rewrite scan_length : length.\n\nLemma scan_map:\n  forall  `{Monoid A op e} (x:A)(xs:list A),\n    scan op (x::xs) = e::(map (op x) (scan op xs)).\nProof.\n  intros A op e H x xs.\n  autounfold with sydpacc; simpl. \n  rewrite <- scanl_map.\n  do 2 f_equal.\n  now rewrite left_neutral, right_neutral.\nQed.\n\nFixpoint scanl_last A B (op:A->B->A)(e:A)(l:list B) : list A * A := \n  match l with \n    | []   => ([], e)\n    | h::t =>\n      let result := scanl_last op (op e h) t in\n      (e::fst result, snd result)\n  end.\n\nFixpoint scanl_last_aux A B (op:A->B->A)(e:A)(l:list B) acc_l : list A * A := \n  match l with\n  | [] => (List.rev' acc_l, e)\n  | h::t => scanl_last_aux op (op e h) t (e::acc_l)\n  end.\n\nDefinition scanl_last' A B (op:A->B->A)(e:A)(l:list B) : list A * A :=\n  scanl_last_aux op e l [].\n\nLemma scanl_last_scanl_last_aux:\n  forall A B (l:list B)(op:A->B->A)(e:A) acc,\n    ((List.rev' acc)++(fst(scanl_last op e l)), snd(scanl_last op e l)) =\n    scanl_last_aux op e l acc.\nProof.\n  induction l as [ | h t IH]; intros op e acc.\n  - simpl; f_equal; now rewrite right_neutral.\n  - simpl; rewrite <- IH; unfold rev'; rewrite List.rev_append_rev; simpl;\n      rewrite List.rev_append_rev; f_equal.\n    now repeat rewrite associative.\nQed.\n\nLemma scanl_last_scanl_last':\n  forall A B (l:list B)(op:A->B->A)(e:A),\n    scanl_last op e l = scanl_last' op e l.\nProof.\n  intros A B l op e; unfold scanl_last'.\n  rewrite <- scanl_last_scanl_last_aux; simpl.\n  apply surjective_pairing.\nQed.\n    \nLemma scanl_last_fst_scanl:\n  forall (A B:Type)(op:A->B->A)(e:A)(l:list B),\n    fst (scanl_last op e l) = removelast (scanl op e l).\nProof.\n  intros A B op e l; revert e; induction l as [|x xs IH].\n  - trivial.\n  - intro e; simpl; rewrite IH.\n    destruct(scanl op (op e x) xs) eqn:H.\n    + assert (List.length(scanl op (op e x) xs) = S (List.length xs)) as Hlen\n          by apply scanl_length.\n      rewrite H in Hlen; simpl in Hlen; discriminate.\n    + trivial.\nQed.\n\nLemma scanl_scanl_last:\n  forall (A B:Type)(op:A->B->A)(e:A)(l:list B),\n    scanl op e l = (fst (scanl_last op e l))++[snd(scanl_last op e l)].\nProof.\n  intros A B op e l; revert e; induction l as [|x xs IH]; intro e.\n  - trivial.\n  - simpl; f_equal; now rewrite IH.\nQed.\n\nLemma scanl_last_snd:\n  forall (A B:Type)(op:A->B->A)(e:A)(l:list B),\n    snd (scanl_last op e l) = List.fold_left op l e.\nProof.\n  intros A B op e l; revert e; induction l as [|x xs IH].\n  - trivial.\n  - intro e; simpl; rewrite IH; trivial.\nQed.\n\nLemma list_last_scanl:\n  forall A B (op:A->B->A) e xs d,\n    last(scanl op e xs) d = snd(scanl_last op e xs).\nProof.\n  intros A B op e xs d.\n  transitivity (last(fst (scanl_last op e xs)++[snd(scanl_last op e xs)]) d).\n  - now rewrite scanl_scanl_last.\n  - apply list_last_app.\nQed.\n\nLemma scanl_not_nil: forall A B (op:A->B->A) e l, scanl op e l <> [].\nProof.\n  destruct l; autounfold with sydpacc; simpl; intros; discriminate.\nQed.\n\nLemma scanl_app_gen:\n  forall A B `{Monoid A op e} (q:B->A) c (l1 l2 : list B),\n    let op' := fun x y=>op x (q y) in\n    scanl op' c (l1++l2) =\n    removelast(scanl op' c l1) ++ map (op (List.last (scanl op' c l1) e)) (scanl op' e l2).\nProof.\n  intros A B op e H q; revert H; revert e.\n    induction l1 as [ | x xs IH ] using rev_ind; intros l2 op'.\n  - simpl; unfold op'; now rewrite scanl_map_gen with (e:=e) by typeclasses eauto.\n  - rewrite associative, IH by auto; simpl. \n    rewrite scanl_snoc, removelast_app by (intro Heq; discriminate).\n    simpl; rewrite app_nil_r, list_last_app; simpl.\n    rewrite @right_neutral with (op:=op) by typeclasses eauto.\n    rewrite app_removelast_last with (l:=scanl op' c xs)(d:=e) by (apply scanl_not_nil).\n    rewrite associative; simpl.\n    do 2 f_equal.\n    assert(List.last (scanl op' c xs) e =\n           List.fold_left op' xs c) as HH\n      by now erewrite <- scanl_last_snd, <- list_last_scanl.\n    fold op'. rewrite HH; clear HH.\n    rewrite fold_left_app; simpl.\n    generalize (fold_left op' xs e); intro a.\n    replace (op e (q x)) with (op' e x) by (now unfold op').\n    replace (op' e x) with (q x) by now (unfold op'; rewrite left_neutral).\n    assert(forall x, scanl op' x l2 = map (op x) (scanl op' e l2)) as HH.\n    {\n      induction l2; intros x0.\n      - simpl; f_equal; now rewrite  right_neutral.\n      - simpl; f_equal.\n        + now rewrite  right_neutral.\n        + rewrite IHl2 with (x:=op' e a0).\n          rewrite IHl2.\n          rewrite map_map.\n          apply map_ext; intros; unfold op'; simpl.\n          rewrite associative, @left_neutral with(e:=e) by typeclasses eauto.\n          trivial.\n    }\n    rewrite HH; rewrite map_map; apply map_ext; intro.\n    unfold op'. now rewrite associative.\nQed.\n\nLemma scanl_app:\n  forall `{Monoid A op e} (l1 l2 : list A),\n    scanl op e (l1++l2) =\n    removelast(scanl op e l1) ++ map (op (List.last (scanl op e l1) e)) (scanl op e l2).\nProof.\n  intros A op e H l1 l2.\n  now apply scanl_app_gen.\nQed.\n\nOpen Scope N_scope.\n\nLemma scanl_nlength:\n  forall (A B:Type)(op:A->B->A)(identity:A)(l:list B),\n    length (scanl op identity l) = N.succ (length l).\nProof.  \n  intros A B op identity l; generalize dependent identity; induction l; intros.\n  - trivial.\n  - simpl; rewrite IHl; simpl; trivial.\nQed.\n\nArguments scanl_nlength [A B].\n\n#[export] Hint Rewrite scanl_nlength : length.\n\nLemma scanl_fold:\n  forall (A B:Type)(op:A->B->A)(identity:A)(l:list B)(index:N)(default:A), \n    ( index < 1 + length l) ->\n    nth index (scanl op identity l) default = \n        List.fold_left op (firstn index l) identity.\nProof.\n  intros A B op identity l index default valid_index;\n    generalize dependent identity; generalize dependent index; induction l as [ | a l IHl ].\n  - intros index valid_index identity;\n      rewrite firstn_nil; simpl in *; destruct index; trivial.\n    lia.\n  - intros index valid_index identity; simpl; destruct index; simpl.\n    + trivial.\n    + rewrite IHl; trivial.\n      rewrite length_cons in valid_index.\n      rewrite N.pos_pred_spec.\n      assert(N.pred (1+ (1+length l)) = 1 + length l) as H\n        by (now rewrite N.add_1_l, N.pred_succ).\n      rewrite <- H.\n      apply N.pred_lt_mono in valid_index; auto.\n      clear; intro H; discriminate.\nQed.\n\nFixpoint scan' {A B:Type}(op:A->B->A)(identity:A)(l:list B) : list A := \n  match l with \n    | []   => []\n    | h::t =>let id := (op identity h) in id::scan' op id t\n  end.\n\nLemma scan'_length:\n  forall (A B : Type)(op:A->B->A)(identity:A)(l:list B),\n    length (scan' op identity l) = length l.\nProof.  \n  intros A B op identity l; generalize dependent identity; induction l as [ | a l IHl ].\n  - intros; trivial. \n  - intros; simpl; rewrite IHl; simpl; trivial.\nQed.\n\n#[export] Hint Rewrite scan_length : length.\n\nLemma scan_fold:\n  forall (A B:Type)(op:A->B->A)(identity:A)(l:list B)(default:A) (index:N), \n    index < length l ->\n    nth index (scan' op identity l) default = \n    List.fold_left op (firstn (1+index) l) identity.\nProof.\n  intros A B op identity l default index validIndex; \n    generalize dependent identity; generalize dependent index; induction l.\n  - intros; rewrite firstn_nil; simpl in *; destruct index; trivial;\n    lia.\n  - intros index validIndex identity; destruct index.\n    + simpl; rewrite firstn_equation; trivial.\n    + rewrite firstn_equation.\n      destruct(1 + N.pos p) eqn:Heq.\n      * lia.\n      * simpl; rewrite IHl.\n        -- repeat f_equal. repeat rewrite N.pos_pred_spec; rewrite <- Heq.\n           rewrite N.add_pred_r; auto; lia.\n        -- rewrite N.pos_pred_spec. rewrite length_cons in validIndex.\n           apply N.pred_lt_mono in validIndex; trivial.\n           rewrite N.add_1_l in validIndex.\n           now rewrite N.pred_succ in  validIndex.\n           clear; intro H; lia.\nQed.\n\n(*-----------------------------------------------------------------*)\n\n(** * Reduce on Arbitrary Lists and Properties *)\n\nDefinition reduce A (op:A -> A -> A) `{Monoid A op e} := \n  fun l => fold_left op l e.\n\nArguments reduce [A] op {e }{_}.\n\nSet Implicit Arguments.\n\nLemma reduce_eq:\n  forall A (op:A->A->A) (e:A) `{Monoid A op e} (x:A) (xs:list A),\n    reduce op (x::xs) = op x (reduce op xs).\nProof.\n  intros A op e H x xs.\n  unfold reduce; simpl.\n  replace (op e x) with (x) by now rewrite left_neutral.\n  rewrite <- fold_left_prop.\n  + f_equal; now rewrite right_neutral.\n  + typeclasses eauto.\nQed.\n\nLemma reduce_app:\n  forall A (op:A->A->A)`{m: Monoid A op e} (l1 l2:list A),\n    reduce op (l1 ++ l2) = op (reduce op l1) (reduce op l2).\nProof.\n  intros A op e m l1 l2. unfold reduce.\n  now rewrite fold_left_app, <- fold_left_prop, right_neutral\n    by typeclasses eauto.\nQed.\n\n(*-----------------------------------------------------------------*)\n\n(** * Homomorphic Functions and List Homomorphisms *)\n\nClass Homomorphic `(h:list A->B) `(op:B->B->B) := \n  { homomorphic : forall x y, h (x++y) = op (h x) (h y) }.  \n\n(** ** Image of a List Function  *)\n\nDefinition img `(h:list A->B) := { b:B | exists l, h l = b }.\n\n(*-----------------------------------------------------------------*)\n\n(** ** [h] homomorphic -> homomophism on the image of [h] *)\n\nDefinition to_img A B (h:list A->B)(xs:list A) : img h.\n  exists(h xs).\n  now eexists.\nDefined.\n\nDefinition of_img `{h:list A->B}(x:img h) : B :=\n  proj1_sig x. \n\nLemma to_img_prop : \n  forall A B {h:list A->B}(xs ys:list A),\n    xs = ys -> to_img h xs = to_img h ys.\nProof.\n  intros A B h xs ys Heq.\n  rewrite Heq.\n  reflexivity.\nQed.\n\nLemma norm : \n  forall A B {h:list A->B}(b:img h), exists xs, b = to_img h xs.\nProof.\n  intros A B h b.\n  destruct b as [b [xs Hb]].\n  exists xs.\n  rewrite <- Hb.\n  now apply to_img_prop.\nQed.\n\nLemma img_op:\n  forall A B (h:list A->B)(op:B->B->B)\n         (hom:Homomorphic h op)(b1 b2:B),\n    (exists xs1, h xs1 = b1) -> \n    (exists xs2, h xs2 = b2) -> \n    (exists xs, h xs = op b1 b2).\nProof.\n  intros A B h op hom b1 b2 \n         [xs1 Hb1] [xs2 Hb2].\n  rewrite <- Hb1, <- Hb2, <- homomorphic.\n  exists (xs1++xs2). \n  reflexivity.\nDefined.\n\n\nUnset Implicit Arguments.\nProgram Definition restrict_op `(op:B->B->B) `{Homomorphic A B h op} : \n  img h -> img h -> img h := op.\nNext Obligation.\n  destruct x as [x [lx Hx]]; destruct x0 as [y [ly Hy]].\n  apply img_op.\n  - trivial.\n  - eexists; eassumption.\n  - eexists; eassumption.\nDefined.\nSet Implicit Arguments.\n\nProgram Definition restrict `{Homomorphic A B h op} \n        `(Eq: forall a b : img h,  op' a b = proj1_sig (restrict_op op a b) ) : \n  img h -> img h -> img h := op'.\nNext Obligation.\n  destruct x as [x [lx Hx]]; destruct x0 as [y [ly Hy]].\n  rewrite Eq; simpl; apply img_op.\n  - trivial.\n  - eexists; eassumption.\n  - eexists; eassumption.\nDefined.\n\nLemma restrict_to_img:\n  forall `{hom:Homomorphic A B h op}\n         `(Eq: forall a b : img h, op' a b = proj1_sig(restrict_op op a b)) \n         (xs ys:list A),\n    restrict Eq (to_img h xs)(to_img h ys) =\n    to_img h (xs++ys).\nProof.\n  intros A B h op hom op' Eq xs ys.\n  unfold restrict, restrict_obligation_1, to_img; simpl.\n  destruct hom as [hom].\n  rewrite Eq; simpl; rewrite <- hom.\n  reflexivity.\nQed.\n\n#[export] Program Instance homomorphic_restrict_assoc `{Homomorphic A B h op}\n        `(Eq: forall a b : img h, op' a b = proj1_sig(restrict_op op a b)) : \n  Associative (restrict Eq).\nNext Obligation.\n  destruct (norm x) as [xs1 Hb1].\n  destruct (norm y) as [xs2 Hb2].\n  destruct (norm z) as [xs3 Hb3].\n  subst.\n  repeat rewrite restrict_to_img.\n  apply to_img_prop.\n  now rewrite associative.\nQed.\n\n#[export] Program Instance homomorphic_restrict_neutral `{Homomorphic A B h op}  \n        `(Eq: forall a b : img h, op' a b = proj1_sig(restrict_op op a b)) : \n  Neutral (restrict Eq) (to_img h []).\nNext Obligation.\n  constructor; intro x.\n  destruct (norm x) as [xs Hx]; subst.\n  rewrite restrict_to_img; now apply to_img_prop.\nQed.\nNext Obligation.\n  constructor; intro x.\n  destruct (norm x) as [xs Hx]; subst.\n  rewrite restrict_to_img.\n  apply to_img_prop.\n  apply app_nil_r.\nQed.\n\n#[export] Program Instance homomorphic_restrict_monoid `{Homomorphic A B h op} \n        `(Eq: forall a b : img h, op' a b = ` (restrict_op op a b)) : \n  Monoid (A:=(img h)) (restrict Eq) (h []).\n\n(** ** Optimization of Homomophisms *)\n\nUnset Implicit Arguments.\nClass Optimised_f `(h:list A->B)`{H:Homomorphic A B h op} :=\n  {\n    optimised_f_sig: { f: A->B | forall a, f a = h[a] }\n  }.\n\nClass Optimised_op `(h:list A->B)`{H:Homomorphic A B h op} :=\n  {\n    optimised_op_sig: {op':(img h)->(img h)->B|forall a b, op' a b = op (` a) (` b) }\n  }.\n\nProgram Definition optimised_f `(h:list A->B) `{Ho:Optimised_f A B h} : A -> img h :=\n  optimised_f_sig (h:=h).\nNext Obligation.\n  rewrite (proj2_sig optimised_f_sig).\n  now eexists.\nDefined.\n\nDefinition optimised_op `(h:list A->B)`{H:Optimised_op A B h}: img h -> img h -> img h.\n  intros a b.\n  apply (exist _ ((` optimised_op_sig) a b)).\n  destruct a as [a [la Ha]], b as [b [lb Hb]].\n  rewrite (proj2_sig optimised_op_sig); simpl.\n  rewrite <- Ha, <- Hb, <- homomorphic.\n  now eexists.\nDefined.\nSet Implicit Arguments.\n\n#[export] Instance non_optimised_f `{Homomorphic A B h op} : Optimised_f h.\nProof. constructor. eexists. reflexivity. Qed.\n\n#[export] Instance non_optimised_op `{Homomorphic A B h op} : Optimised_op h.\nProof. constructor. eexists. reflexivity. Qed.\n\n(*-----------------------------------------------------------------*)\n\n(** ** Homomophism Theorems *)\n\nUnset Implicit Arguments.\nDefinition hom_to_map_reduce {A B:Type}(h:list A->B)\n           `{H:Homomorphic A B h op}\n           `{@Optimised_op A B h op H}`{@Optimised_f A B h op H} :\n  list A -> img h := \n  (reduce (optimised_op h)) ∘ (List.map (optimised_f h)).\nSet Implicit Arguments.\n\n(** *** First Homomophism Theorem *)\n\nTheorem first_homomorphism_theorem:\n  forall `{H:Homomorphic A B h op}`{@Optimised_op A B h op H}`{@Optimised_f A B h op H},\n  forall l, h l = of_img (hom_to_map_reduce h l).\nProof.\n  unfold hom_to_map_reduce.\n  intros A B h op hom opt_op opt_f l; induction l as [ | x xs IH ].\n  - reflexivity.\n  - autounfold with sydpacc in *; unfold of_img in *; simpl in *.\n    replace (optimised_f h x :: map (optimised_f h) xs)\n    with ([optimised_f h x] ++ map (optimised_f h) xs) by trivial.\n    rewrite reduce_app ; simpl.\n    rewrite (proj2_sig optimised_op_sig), <- IH; simpl.\n    rewrite (proj2_sig optimised_op_sig); simpl.\n    rewrite (proj2_sig optimised_f_sig); simpl.\n    now repeat rewrite <- homomorphic.\nQed. \n\nClass Rightwards `(h:list A->B)`(op:B->A->B)`(e:B) := \n  { rightwards: forall l, h l = List.fold_left op l e }.\n\nClass Leftwards `(h:list A->B)`(op:A->B->B)`(e:B) := \n  { leftwards: forall l, h l = List.fold_right op e l }.\n\n(** *** Third Homomophism Theorem *)\n\nClass Right_inverse `(h:list A ->B)(h':B->list A) :=\n  { right_inverse: forall l, h l = h(h'(h l)) }.\n\nLemma hom_characterisation:\n  forall `(h:list A->B)`{Right_inverse A B h h'},\n    (exists op, forall x y, h (x++y) = op (h x) (h y)) <->\n    (forall x y v w, h x = h v -> h y = h w -> h(x ++ y) = h(v ++ w)).\nProof.\n  intros A B h h' Hinv. split; intro H.\n  - intros x y v w Hxv Hyw.\n    destruct H as [op Hh].\n    repeat rewrite Hh.\n    rewrite Hxv, Hyw.\n    trivial.\n  - exists(fun l r=>h((h' l)++(h' r))).\n    intros x y.\n    erewrite H; try reflexivity; apply right_inverse.\nQed.\n\n#[export] Instance third_homomorphism_theorem_right_inverse\n         `{h:list A->B}`{inv:Right_inverse A B h h'}\n         `{Hl:Leftwards A B h opl e} `{Hr:Rightwards A B h opr e} : \n  Homomorphic h (fun l r =>h( (h' l)++(h' r))).\nProof.\n  constructor; intros x y.\n  assert(exists op, forall x y, h (x++y) = op (h x) (h y)) as Hom.\n  { \n    eapply hom_characterisation; try eassumption.\n    intros x0 y0 v w H0 H1.\n    rewrite leftwards.\n    rewrite fold_right_app.\n    rewrite <- (leftwards y0), H1. rewrite (@leftwards _ _ _ _ _ Hl).\n    rewrite <- fold_right_app.\n    rewrite <- leftwards.\n    rewrite rightwards.\n    rewrite fold_left_app.\n    rewrite <-(rightwards x0), H0, (@rightwards _ _ _ _ _ Hr).\n    rewrite <- fold_left_app.\n    rewrite <- rightwards.\n    trivial.\n  }\n  destruct Hom as [op Hh].\n  repeat rewrite Hh.\n  repeat rewrite <- right_inverse.\n  trivial.\nQed.\n\n(*-----------------------------------------------------------------*)\n\n(** * A Typeclass to Characterize Empty Lists *)\n\nClass NonEmpty `(l:list A) := { non_emptiness : l<> [] }.\n\nLtac empty := \n  let H := fresh \"Hempty\" in \n  assert(H:=non_emptiness); contradict H; trivial.\n\n(** ** Instances *)\n\n#[export] Program Instance cons_non_empty \n        `(x:A)(xs:list A) : NonEmpty (x::xs).\n\n#[export] Program Instance map_non_empty \n        `(f:A->B)(xs:list A){HNE:NonEmpty xs} : \n  NonEmpty (map f xs).\nNext Obligation.\n  destruct xs.\n  - empty.\n  - intro H. discriminate.\nQed.\n\nLemma eq_non_empty :\n  forall {A:Type}{l1 l2:list A}{HNE:NonEmpty l1}(Eq:l1=l2), NonEmpty l2.\nProof. \n  constructor; intro H; subst; destruct HNE as [HNE]; now contradict HNE.\nQed.\n\n#[export] Instance app_non_empty_l \n         {A:Type}(l1 l2:list A){HNE:NonEmpty l1} : NonEmpty (l1++l2).\nProof.\n  constructor; destruct HNE as [HNE]; contradict HNE.\n  now apply app_eq_nil in HNE.\nQed.\n\n#[export] Instance app_non_empty_r \n         {A:Type}(l1 l2:list A){HNE:NonEmpty l2} : NonEmpty (l1++l2).\nProof.\n  constructor; destruct HNE as [HNE]; contradict HNE.\n  now apply app_eq_nil in HNE.\nQed.\n\nLemma non_empty_cons `{NonEmpty A xs} : \n  exists x' xs', xs = x' :: xs'.\nProof.\n  destruct xs as [ | x' xs'].\n  - empty. \n  - exists x'. now exists xs'.\nQed.\n\n#[export] Instance length_lt_0_NonEmpty `(Hlt: (0 < n)%N) `{l:{l:list A | length l = n}} :\n  NonEmpty (proj1_sig l).\nProof.\n  destruct l as [ [ | h t] Hl ]; simpl in *.\n  - lia.\n  - typeclasses eauto.\nQed.\n\n(*---------------------------------------------------------------*)\n\n(** ** Reduce on Non-empty Lists and Properties *)\n\nModule NE.\n\n  Unset Implicit Arguments.\n  Definition reduce `(op:A->A->A)`{HA:Associative A op}\n             (l:list A){HNE:NonEmpty l} : A.\n    destruct l as [|x xs].\n    - apply False_rect. now apply HNE.\n    - exact(fold_left op xs x).\n  Defined.\n  \n  Lemma reduce_app:\n    forall `(op:A->A->A)`{HA:Associative A op}\n           (l1 l2:list A){HNE1:NonEmpty l1}{HNE1:NonEmpty l2},\n      reduce op (l1++l2) = op (reduce op l1) (reduce op l2).\n  Proof.\n    intros A op Hassoc; induction l1; intros l2 HNE1 HNE2.\n    - inversion HNE1; intuition.\n    - destruct l2; simpl.\n      + inversion HNE2; intuition.\n      + rewrite fold_left_app. simpl.\n        now rewrite fold_left_prop.\n  Qed.\n  \n  Lemma reduce_pi:\n    forall `(op:A->A->A)`{HA:Associative A op}\n           (l1 l2:list A){HNE:NonEmpty l1}{HNE:NonEmpty l2}(H:l1=l2),\n      reduce op l1 = reduce op l2.\n  Proof.\n    intros A op Hassoc; induction l1; intros l2 HNE1 HNE2 H.\n    - inversion HNE1; intuition.\n    - destruct l2; inversion HNE2; intuition.\n      now inversion H; subst.\n  Qed.      \n\n  Lemma reduce_fold_left:\n    forall `(op:A->A->A)`{HA:Associative A op} x xs,\n      reduce op (x::xs) = fold_left op xs x.\n    induction xs; trivial.\n  Qed.\n  Set Implicit Arguments.\n  \nEnd NE.\n\n(*-------------------------------------------------------------*)\n\n(** ** Compositions Taking into Account Non-emptyness *)\n\nProgram Definition comp' \n        `(f:forall l:list B, NonEmpty l->C)`(g:list A->list B)\n        {HNE:forall a, NonEmpty a -> NonEmpty(g a)} : \n  forall l:list A, NonEmpty l -> C := \n  fun a H => f (g a) (HNE a H).\n\nProgram Definition comp'' \n        `(f:forall l:list B, NonEmpty l->C)`(g:A->list B)\n        {HNE:forall a, NonEmpty(g a)} : A -> C := \n  fun a => f (g a) (HNE a).\n\nInfix \"∘'\" := comp' (at level 30).\nInfix \"∘''\" := comp'' (at level 30).\n\n(** ** [last] on NonEmpty lists *)\n\nUnset Implicit Arguments.\n\nProgram Definition hd A (l:list A) `{NonEmpty A l} : A :=\n  match l with\n  | [ ] => _\n  | h::t => h\n  end.\nNext Obligation.\n  inversion H; contradiction.\nDefined.\n\nArguments hd [A] l { _ }.\n\nDefinition last A (l:list A) `{NonEmpty A l} : A :=\n  List.last l (hd l).\n\nArguments last [A] l { _ }.\n\n#[export] Hint Unfold last : sydpacc.\n\nSet Implicit Arguments.\n\n(** ** Properties of [List.last] and [last] *)\n\nLemma list_last_non_empty:\n  forall A l (d:A) d',\n    NonEmpty l ->\n    List.last l d = List.last l d'.\nProof.\n  intros A; induction l as [ | x xs IH]; intros d d' H.\n  - inversion H; contradiction.\n  - simpl; destruct xs; trivial.\n    apply IH.\n    typeclasses eauto.\nQed.\n  \nLemma list_last_app:\n  forall A (xs:list A) x d,\n    List.last (xs++[x]) d = x.\nProof.\n  intros A; induction xs; intros x d.\n  - now compute.\n  - simpl; destruct(xs ++ [x]) eqn:H; symmetry in H.\n    + apply app_cons_not_nil in H; now exfalso.\n    + destruct xs; inversion H; subst; auto.\n      rewrite app_comm_cons; apply IHxs.\nQed.\n\nLemma last_pi:\n  forall A l l' Hl Hl',\n    l = l' ->\n    @last A l Hl = @last A l' Hl'.\nProof.\n  intros A l l' Hl Hl' H.\n  autounfold with sydpacc; f_equal; auto.\n  destruct l.\n  - inversion Hl; contradiction.\n  - destruct l'.\n    + inversion Hl'; contradiction.\n    + inversion H; subst.\n      auto.\nQed.\n\nLemma last_cons_non_empty:\n  forall `{NonEmpty A xs} x,\n    last (x::xs) = last xs.\nProof.\n  intros A xs H x. revert  x.\n  induction xs; autounfold with sydpacc in *; simpl; intro x.\n  - inversion H; contradiction.\n  - simpl in IHxs. destruct xs.\n    + trivial.\n    + simpl in *. specialize (IHxs (cons_non_empty a0 xs)).\n      rewrite IHxs. symmetry. now rewrite IHxs.\nQed.\n\n\nLemma last_app:\n  forall A (xs:list A) x,\n    last (xs++[x]) = x.\nProof.\n  intros A xs x; unfold last.\n  apply list_last_app.\nQed.\n\nLemma last_map:\n  forall A B (f:A->B) `{NonEmpty A l},\n    last (map f l) = f (last l).\nProof.\n  intros A B f; induction l as [ | h t IH ]; intros H.\n  - inversion H; contradiction.\n  - destruct t; simpl.\n    + trivial.\n    + erewrite last_pi by reflexivity; rewrite last_cons_non_empty. \n      simpl in IH; specialize (IH _);\n        erewrite last_pi in IH by reflexivity.\n      rewrite IH.\n      f_equal; symmetry;\n        erewrite last_pi at 1 by reflexivity.\n      apply last_cons_non_empty.\nQed.\n\nLemma removelast_length:\n  forall A (l:list A), List.length(removelast l) = pred(List.length l).\nProof.\n  intros A l;induction l as [ | h t IH ].\n  - trivial. \n  - destruct t as [ | a t ].\n    + trivial.\n    + replace (h::a::t) with ([h]++(a::t)) by auto.\n      rewrite removelast_app by (intro HH; discriminate).\n      repeat rewrite List.app_length.\n      now rewrite IH by typeclasses eauto.\nQed.\nLemma removelast_length_N:\n  forall `(l:list A),\n    length(removelast l) = N.pred(length l).\nProof.\n  intros A; induction l as [ | h t IH ].\n  - trivial.\n  - destruct t.\n    + trivial.\n    + replace (h::a::t) with ([h]++(a::t)) by auto.\n      rewrite removelast_app by (intro HH; discriminate).\n      autorewrite with length. rewrite IH by typeclasses eauto.\n      repeat rewrite N.add_1_l; simpl.\n      now repeat rewrite N.pred_succ.\nQed.\n\n#[export] Hint Rewrite @removelast_length @removelast_length_N : length.\n\nLemma fst_scanl_last_length:\n  forall (A B:Type)(op:A->B->A)(e:A)(l:list B),\n    List.length(fst (scanl_last op e l)) = List.length l.\nProof.\n  intros A B op e l.\n  rewrite scanl_last_fst_scanl.\n  now autorewrite with length.\nQed.\n\n#[export] Hint Rewrite fst_scanl_last_length : length.\n\n#[export] Instance prefix_non_empty `(xs:list A) : NonEmpty (prefix xs).\nProof.\n  constructor; intro H; destruct xs; simpl; discriminate.\nQed.\n\nLemma prefix_last:\n  forall `(l:list A) {H: NonEmpty l}, prefix l = prefix (removelast l) ++ [l].\nProof.\n  induction l as [ | x xs IH] using rev_ind; intro HnonEmpty.\n  - empty.\n  - rewrite prefix_snoc.\n    destruct xs as [ | x' xs] using rev_ind.\n    + trivial.\n    + rewrite removelast_app by (intro H; discriminate).\n      now rewrite app_nil_r.\nQed.\n\n\nLemma scanl_removelast:\n  forall A B (op:A->B->A) e `{ NonEmpty B l},\n    removelast (scanl op e l) = scanl op e (removelast l).\nProof.\n  intros A B op e l H; revert e; induction l as [ | h t IH ]; intro e.\n  - empty.\n  - destruct t.\n    + trivial.\n    + set(t':=b::t) in *.\n      replace (scanl op e (h::t')) with ([ e ] ++ scanl op (op e h) t') by auto.\n      replace (h::t') with ([h]++t') by auto.\n      rewrite removelast_app by apply non_emptiness.\n      rewrite removelast_app by (unfold t'; apply non_emptiness).\n      now rewrite IH by (unfold t'; typeclasses eauto).\nQed.\n\n#[export] Instance scanl_non_empty A B (op:A->B->A) e l : NonEmpty (scanl op e l).\nProof. \n  constructor; now apply scanl_not_nil.\nQed.\n\nFact scanl_hd:\n  forall A B (op:A->B->A) e l,\n    hd (scanl op e l) = e.\nProof.\n  intros A B op e l; now destruct l.\nQed.\n\n#[export] Instance scanl'_non_empty A B (op:A->B->A) e l : NonEmpty (scanl' op e l).\nProof.\n  rewrite <- scanl_scanl'.\n  typeclasses eauto.\nQed.\n\n#[export] Instance scan_non_empty A `{Monoid A op e} l : NonEmpty (scan op l).\nProof.\n  destruct l; autounfold; simpl; constructor; intros; discriminate.\nQed.\n\nLemma last_scanl:\n  forall A B (op:A->B->A) e xs,\n    last(scanl op e xs) = snd(scanl_last op e xs).\nProof.\n  intros A B op e xs.\n  transitivity (last(fst (scanl_last op e xs)++[snd(scanl_last op e xs)])).\n  - apply last_pi, scanl_scanl_last.\n  - apply last_app.\nQed.\n\nClose Scope N_scope.\n\nClose Scope sydpacc_scope.\n\n", "meta": {"author": "SyDPaCC", "repo": "sydpacc", "sha": "640f0f74f21524ee203b192255ecfa9e456fb7d1", "save_path": "github-repos/coq/SyDPaCC-sydpacc", "path": "github-repos/coq/SyDPaCC-sydpacc/sydpacc-640f0f74f21524ee203b192255ecfa9e456fb7d1/Core/Bmf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.868826784729373, "lm_q1q2_score": 0.6999548244270707}}
{"text": "Require Import bool.\nRequire Import list.\nRequire Import In.\n\nFixpoint filter (a:Type) (test: a -> bool) (l:list a) : list a :=\n    match l with\n    | []        => []\n    | x::xs     => if test x then x::filter a test xs else filter a test xs\n    end.\n\nArguments filter {a} _ _.\n\nLemma filter_of_false : forall (a:Type) (test:a -> bool) (l:list a),\n    (forall x, In x l -> test x = false) -> filter test l = [].\nProof.\n    intros a test l H. revert H. induction l as [|x xs IH].\n    - intros _. reflexivity.\n    - intros H. assert (test x = false) as Hx. { apply H. left. reflexivity. }\n        simpl. rewrite Hx. apply IH. intros y H'. apply H. right. exact H'.\nQed.\n\nLemma filter_of_true : forall (a:Type) (test:a -> bool) (l:list a),\n    (forall x, In x l -> test x = true) -> filter test l = l.\nProof.\n    intros a test l H. revert H. induction l as [|x xs IH].\n    - intros _. reflexivity.\n    - intros H. assert (test x = true) as Hx. { apply H. left. reflexivity. }\n        simpl. rewrite Hx. assert (filter test xs = xs) as H0. \n            { apply IH. intros y H'. apply H. right. exact H'. }\n        rewrite H0. reflexivity.\nQed.\n\nLemma filter_all_true : forall (a:Type) (test:a -> bool) (l:list a),\n    forall x, In x (filter test l) -> test x = true.\nProof.\n    intros a test l. induction l as [|x xs IH].\n    - intros x H. inversion H.\n    - intros y H. simpl in H. destruct (test x) eqn:Hx.\n        + destruct H as [H|H].\n            { rewrite <- H. exact Hx. }\n            { apply IH. exact H. }\n        + apply IH. exact H.\nQed.\n\n\n\n\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/sf/filter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.8688267762381844, "lm_q1q2_score": 0.6999548175862957}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\nSet Implicit Arguments.\n\nRequire Export Notations.\n\nNotation \"A -> B\" := (forall (_ : A), B) : type_scope.\n\n(** * Propositional connectives *)\n\n(** [True] is the always true proposition *)\n\nInductive True : Prop :=\n  I : True.\n\n(** [False] is the always false proposition *)\nInductive False : Prop :=.\n\n(** [not A], written [~A], is the negation of [A] *)\nDefinition not (A:Prop) := A -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\n(** Create the \"core\" hint database, and set its transparent state for\n  variables and constants explicitely. *)\n\nCreate HintDb core.\nHint Variables Opaque : core.\nHint Constants Opaque : core.\n\nHint Unfold not: core.\n\n  (** [and A B], written [A /\\ B], is the conjunction of [A] and [B]\n\n      [conj p q] is a proof of [A /\\ B] as soon as\n      [p] is a proof of [A] and [q] a proof of [B]\n\n      [proj1] and [proj2] are first and second projections of a conjunction *)\n\nInductive and (A B:Prop) : Prop :=\n  conj : A -> B -> A /\\ B\n\nwhere \"A /\\ B\" := (and A B) : type_scope.\n\nSection Conjunction.\n\n  Variables A B : Prop.\n\n  Theorem proj1 : A /\\ B -> A.\n  Proof.\n    destruct 1; trivial.\n  Qed.\n\n  Theorem proj2 : A /\\ B -> B.\n  Proof.\n    destruct 1; trivial.\n  Qed.\n\nEnd Conjunction.\n\n(** [or A B], written [A \\/ B], is the disjunction of [A] and [B] *)\n\nInductive or (A B:Prop) : Prop :=\n  | or_introl : A -> A \\/ B\n  | or_intror : B -> A \\/ B\n\nwhere \"A \\/ B\" := (or A B) : type_scope.\n\nArguments or_introl [A B] _, [A] B _.\nArguments or_intror [A B] _, A [B] _.\n\n(** [iff A B], written [A <-> B], expresses the equivalence of [A] and [B] *)\n\nDefinition iff (A B:Prop) := (A -> B) /\\ (B -> A).\n\nNotation \"A <-> B\" := (iff A B) : type_scope.\n\nSection Equivalence.\n\nTheorem iff_refl : forall A:Prop, A <-> A.\n  Proof.\n    split; auto.\n  Qed.\n\nTheorem iff_trans : forall A B C:Prop, (A <-> B) -> (B <-> C) -> (A <-> C).\n  Proof.\n    intros A B C [H1 H2] [H3 H4]; split; auto.\n  Qed.\n\nTheorem iff_sym : forall A B:Prop, (A <-> B) -> (B <-> A).\n  Proof.\n    intros A B [H1 H2]; split; auto.\n  Qed.\n\nEnd Equivalence.\n\nHint Unfold iff: extcore.\n\n(** Backward direction of the equivalences above does not need assumptions *)\n\nTheorem and_iff_compat_l : forall A B C : Prop,\n  (B <-> C) -> (A /\\ B <-> A /\\ C).\nProof.\n  intros ? ? ? [Hl Hr]; split; intros [? ?]; (split; [ assumption | ]);\n  [apply Hl | apply Hr]; assumption.\nQed.\n\nTheorem and_iff_compat_r : forall A B C : Prop,\n  (B <-> C) -> (B /\\ A <-> C /\\ A).\nProof.\n  intros ? ? ? [Hl Hr]; split; intros [? ?]; (split; [ | assumption ]);\n  [apply Hl | apply Hr]; assumption.\nQed.\n\nTheorem or_iff_compat_l : forall A B C : Prop,\n  (B <-> C) -> (A \\/ B <-> A \\/ C).\nProof.\n  intros ? ? ? [Hl Hr]; split; (intros [?|?]; [left; assumption| right]);\n  [apply Hl | apply Hr]; assumption.\nQed.\n\nTheorem or_iff_compat_r : forall A B C : Prop,\n  (B <-> C) -> (B \\/ A <-> C \\/ A).\nProof.\n  intros ? ? ? [Hl Hr]; split; (intros [?|?]; [left| right; assumption]);\n  [apply Hl | apply Hr]; assumption.\nQed.\n\nTheorem imp_iff_compat_l : forall A B C : Prop,\n  (B <-> C) -> ((A -> B) <-> (A -> C)).\nProof.\n  intros ? ? ? [Hl Hr]; split; intros H ?; [apply Hl | apply Hr]; apply H; assumption.\nQed.\n\nTheorem imp_iff_compat_r : forall A B C : Prop,\n  (B <-> C) -> ((B -> A) <-> (C -> A)).\nProof.\n  intros ? ? ? [Hl Hr]; split; intros H ?; [apply H, Hr | apply H, Hl]; assumption.\nQed.\n\nTheorem not_iff_compat : forall A B : Prop,\n  (A <-> B) -> (~ A <-> ~B).\nProof.\n  intros; apply imp_iff_compat_r; assumption.\nQed.\n\n\n(** Some equivalences *)\n\nTheorem neg_false : forall A : Prop, ~ A <-> (A <-> False).\nProof.\n  intro A; unfold not; split.\n  - intro H; split; [exact H | intro H1; elim H1].\n  - intros [H _]; exact H.\nQed.\n\nTheorem and_cancel_l : forall A B C : Prop,\n  (B -> A) -> (C -> A) -> ((A /\\ B <-> A /\\ C) <-> (B <-> C)).\nProof.\n  intros A B C Hl Hr.\n  split; [ | apply and_iff_compat_l]; intros [HypL HypR]; split; intros.\n  + apply HypL; split; [apply Hl | ]; assumption.\n  + apply HypR; split; [apply Hr | ]; assumption.\nQed.\n\nTheorem and_cancel_r : forall A B C : Prop,\n  (B -> A) -> (C -> A) -> ((B /\\ A <-> C /\\ A) <-> (B <-> C)).\nProof.\n  intros A B C Hl Hr.\n  split; [ | apply and_iff_compat_r]; intros [HypL HypR]; split; intros.\n  + apply HypL; split; [ | apply Hl ]; assumption.\n  + apply HypR; split; [ | apply Hr ]; assumption.\nQed.\n\nTheorem and_comm : forall A B : Prop, A /\\ B <-> B /\\ A.\nProof.\n  intros; split; intros [? ?]; split; assumption.\nQed.\n\nTheorem and_assoc : forall A B C : Prop, (A /\\ B) /\\ C <-> A /\\ B /\\ C.\nProof.\n  intros; split; [ intros [[? ?] ?]| intros [? [? ?]]]; repeat split; assumption.\nQed.\n\nTheorem or_cancel_l : forall A B C : Prop,\n  (B -> ~ A) -> (C -> ~ A) -> ((A \\/ B <-> A \\/ C) <-> (B <-> C)).\nProof.\n  intros ? ? ? Fl Fr; split; [ | apply or_iff_compat_l]; intros [Hl Hr]; split; intros.\n  { destruct Hl; [ right | destruct Fl | ]; assumption. }\n  { destruct Hr; [ right | destruct Fr | ]; assumption. }\nQed.\n\nTheorem or_cancel_r : forall A B C : Prop,\n  (B -> ~ A) -> (C -> ~ A) -> ((B \\/ A <-> C \\/ A) <-> (B <-> C)).\nProof.\n  intros ? ? ? Fl Fr; split; [ | apply or_iff_compat_r]; intros [Hl Hr]; split; intros.\n  { destruct Hl; [ left | | destruct Fl ]; assumption. }\n  { destruct Hr; [ left | | destruct Fr ]; assumption. }\nQed.\n\nTheorem or_comm : forall A B : Prop, (A \\/ B) <-> (B \\/ A).\nProof.\n  intros; split; (intros [? | ?]; [ right | left ]; assumption).\nQed.\n\nTheorem or_assoc : forall A B C : Prop, (A \\/ B) \\/ C <-> A \\/ B \\/ C.\nProof.\n  intros; split; [ intros [[?|?]|?]| intros [?|[?|?]]].\n  + left; assumption.\n  + right; left; assumption.\n  + right; right; assumption.\n  + left; left; assumption.\n  + left; right; assumption.\n  + right; assumption.\nQed.\nLemma iff_and : forall A B : Prop, (A <-> B) -> (A -> B) /\\ (B -> A).\nProof.\n  intros A B []; split; trivial.\nQed.\n\nLemma iff_to_and : forall A B : Prop, (A <-> B) <-> (A -> B) /\\ (B -> A).\nProof.\n  intros; split; intros [Hl Hr]; (split; intros; [ apply Hl | apply Hr]); assumption.\nQed.\n\n(** [(IF_then_else P Q R)], written [IF P then Q else R] denotes\n    either [P] and [Q], or [~P] and [R] *)\n\nDefinition IF_then_else (P Q R:Prop) := P /\\ Q \\/ ~ P /\\ R.\n\nNotation \"'IF' c1 'then' c2 'else' c3\" := (IF_then_else c1 c2 c3)\n  (at level 200, right associativity) : type_scope.\n\n(** * First-order quantifiers *)\n\n(** [ex P], or simply [exists x, P x], or also [exists x:A, P x],\n    expresses the existence of an [x] of some type [A] in [Set] which\n    satisfies the predicate [P].  This is existential quantification.\n\n    [ex2 P Q], or simply [exists2 x, P x & Q x], or also\n    [exists2 x:A, P x & Q x], expresses the existence of an [x] of\n    type [A] which satisfies both predicates [P] and [Q].\n\n    Universal quantification is primitively written [forall x:A, Q]. By\n    symmetry with existential quantification, the construction [all P]\n    is provided too.\n*)\n\nInductive ex (A:Type) (P:A -> Prop) : Prop :=\n  ex_intro : forall x:A, P x -> ex (A:=A) P.\n\nInductive ex2 (A:Type) (P Q:A -> Prop) : Prop :=\n  ex_intro2 : forall x:A, P x -> Q x -> ex2 (A:=A) P Q.\n\nDefinition all (A:Type) (P:A -> Prop) := forall x:A, P x.\n\n(* Rule order is important to give printing priority to fully typed exists *)\n\nNotation \"'exists' x .. y , p\" := (ex (fun x => .. (ex (fun y => p)) ..))\n  (at level 200, x binder, right associativity,\n   format \"'[' 'exists'  '/  ' x  ..  y ,  '/  ' p ']'\")\n  : type_scope.\n\nNotation \"'exists2' x , p & q\" := (ex2 (fun x => p) (fun x => q))\n  (at level 200, x ident, p at level 200, right associativity) : type_scope.\nNotation \"'exists2' x : A , p & q\" := (ex2 (A:=A) (fun x => p) (fun x => q))\n  (at level 200, x ident, A at level 200, p at level 200, right associativity,\n    format \"'[' 'exists2'  '/  ' x  :  A ,  '/  ' '[' p  &  '/' q ']' ']'\")\n  : type_scope.\n\nNotation \"'exists2' ' x , p & q\" := (ex2 (fun x => p) (fun x => q))\n  (at level 200, x strict pattern, p at level 200, right associativity) : type_scope.\nNotation \"'exists2' ' x : A , p & q\" := (ex2 (A:=A) (fun x => p) (fun x => q))\n  (at level 200, x strict pattern, A at level 200, p at level 200, right associativity,\n    format \"'[' 'exists2'  '/  ' ' x  :  A ,  '/  ' '[' p  &  '/' q ']' ']'\")\n  : type_scope.\n\n(** Derived rules for universal quantification *)\n\nSection universal_quantification.\n\n  Variable A : Type.\n  Variable P : A -> Prop.\n\n  Theorem inst : forall x:A, all (fun x => P x) -> P x.\n  Proof.\n    unfold all; auto.\n  Qed.\n\n  Theorem gen : forall (B:Prop) (f:forall y:A, B -> P y), B -> all P.\n  Proof.\n    red; auto.\n  Qed.\n\nEnd universal_quantification.\n\n(** * Equality *)\n\n(** [eq x y], or simply [x=y] expresses the equality of [x] and\n    [y]. Both [x] and [y] must belong to the same type [A].\n    The definition is inductive and states the reflexivity of the equality.\n    The others properties (symmetry, transitivity, replacement of\n    equals by equals) are proved below. The type of [x] and [y] can be\n    made explicit using the notation [x = y :> A]. This is Leibniz equality\n    as it expresses that [x] and [y] are equal iff every property on\n    [A] which is true of [x] is also true of [y] *)\n\nInductive eq (A:Type) (x:A) : A -> Prop :=\n    eq_refl : x = x :>A\n\nwhere \"x = y :> A\" := (@eq A x y) : type_scope.\n\nNotation \"x = y\" := (x = y :>_) : type_scope.\nNotation \"x <> y  :> T\" := (~ x = y :>T) : type_scope.\nNotation \"x <> y\" := (x <> y :>_) : type_scope.\n\nArguments eq {A} x _.\nArguments eq_refl {A x} , [A] x.\n\nArguments eq_ind [A] x P _ y _.\nArguments eq_rec [A] x P _ y _.\nArguments eq_rect [A] x P _ y _.\n\nHint Resolve I conj or_introl or_intror : core.\nHint Resolve eq_refl: core.\nHint Resolve ex_intro ex_intro2: core.\n\nSection Logic_lemmas.\n\n  Theorem absurd : forall A C:Prop, A -> ~ A -> C.\n  Proof.\n    unfold not; intros A C h1 h2.\n    destruct (h2 h1).\n  Qed.\n\n  Section equality.\n    Variables A B : Type.\n    Variable f : A -> B.\n    Variables x y z : A.\n\n    Theorem eq_sym : x = y -> y = x.\n    Proof.\n      destruct 1; trivial.\n    Defined.\n\n    Theorem eq_trans : x = y -> y = z -> x = z.\n    Proof.\n      destruct 2; trivial.\n    Defined.\n\n    Theorem f_equal : x = y -> f x = f y.\n    Proof.\n      destruct 1; trivial.\n    Defined.\n\n    Theorem not_eq_sym : x <> y -> y <> x.\n    Proof.\n      red; intros h1 h2; apply h1; destruct h2; trivial.\n    Qed.\n\n  End equality.\n\n  Definition eq_ind_r :\n    forall (A:Type) (x:A) (P:A -> Prop), P x -> forall y:A, y = x -> P y.\n    intros A x P H y H0. elim eq_sym with (1 := H0); assumption.\n  Defined.\n\n  Definition eq_rec_r :\n    forall (A:Type) (x:A) (P:A -> Set), P x -> forall y:A, y = x -> P y.\n    intros A x P H y H0; elim eq_sym with (1 := H0); assumption.\n  Defined.\n\n  Definition eq_rect_r :\n    forall (A:Type) (x:A) (P:A -> Type), P x -> forall y:A, y = x -> P y.\n    intros A x P H y H0; elim eq_sym with (1 := H0); assumption.\n  Defined.\nEnd Logic_lemmas.\n\nModule EqNotations.\n  Notation \"'rew' H 'in' H'\" := (eq_rect _ _ H' _ H)\n    (at level 10, H' at level 10,\n     format \"'[' 'rew'  H  in  '/' H' ']'\").\n  Notation \"'rew' [ P ] H 'in' H'\" := (eq_rect _ P H' _ H)\n    (at level 10, H' at level 10,\n     format \"'[' 'rew'  [ P ]  '/    ' H  in  '/' H' ']'\").\n  Notation \"'rew' <- H 'in' H'\" := (eq_rect_r _ H' H)\n    (at level 10, H' at level 10,\n     format \"'[' 'rew'  <-  H  in  '/' H' ']'\").\n  Notation \"'rew' <- [ P ] H 'in' H'\" := (eq_rect_r P H' H)\n    (at level 10, H' at level 10,\n     format \"'[' 'rew'  <-  [ P ]  '/    ' H  in  '/' H' ']'\").\n  Notation \"'rew' -> H 'in' H'\" := (eq_rect _ _ H' _ H)\n    (at level 10, H' at level 10, only parsing).\n  Notation \"'rew' -> [ P ] H 'in' H'\" := (eq_rect _ P H' _ H)\n    (at level 10, H' at level 10, only parsing).\n\nEnd EqNotations.\n\nImport EqNotations.\n\nLemma rew_opp_r : forall A (P:A->Type) (x y:A) (H:x=y) (a:P y), rew H in rew <- H in a = a.\nProof.\nintros.\ndestruct H.\nreflexivity.\nDefined.\n\nLemma rew_opp_l : forall A (P:A->Type) (x y:A) (H:x=y) (a:P x), rew <- H in rew H in a = a.\nProof.\nintros.\ndestruct H.\nreflexivity.\nDefined.\n\nTheorem f_equal2 :\n  forall (A1 A2 B:Type) (f:A1 -> A2 -> B) (x1 y1:A1)\n    (x2 y2:A2), x1 = y1 -> x2 = y2 -> f x1 x2 = f y1 y2.\nProof.\n  destruct 1; destruct 1; reflexivity.\nQed.\n\nTheorem f_equal3 :\n  forall (A1 A2 A3 B:Type) (f:A1 -> A2 -> A3 -> B) (x1 y1:A1)\n    (x2 y2:A2) (x3 y3:A3),\n    x1 = y1 -> x2 = y2 -> x3 = y3 -> f x1 x2 x3 = f y1 y2 y3.\nProof.\n  destruct 1; destruct 1; destruct 1; reflexivity.\nQed.\n\nTheorem f_equal4 :\n  forall (A1 A2 A3 A4 B:Type) (f:A1 -> A2 -> A3 -> A4 -> B)\n    (x1 y1:A1) (x2 y2:A2) (x3 y3:A3) (x4 y4:A4),\n    x1 = y1 -> x2 = y2 -> x3 = y3 -> x4 = y4 -> f x1 x2 x3 x4 = f y1 y2 y3 y4.\nProof.\n  destruct 1; destruct 1; destruct 1; destruct 1; reflexivity.\nQed.\n\nTheorem f_equal5 :\n  forall (A1 A2 A3 A4 A5 B:Type) (f:A1 -> A2 -> A3 -> A4 -> A5 -> B)\n    (x1 y1:A1) (x2 y2:A2) (x3 y3:A3) (x4 y4:A4) (x5 y5:A5),\n    x1 = y1 ->\n    x2 = y2 ->\n    x3 = y3 -> x4 = y4 -> x5 = y5 -> f x1 x2 x3 x4 x5 = f y1 y2 y3 y4 y5.\nProof.\n  destruct 1; destruct 1; destruct 1; destruct 1; destruct 1; reflexivity.\nQed.\n\nTheorem f_equal_compose : forall A B C (a b:A) (f:A->B) (g:B->C) (e:a=b),\n  f_equal g (f_equal f e) = f_equal (fun a => g (f a)) e.\nProof.\n  destruct e. reflexivity.\nDefined.\n\n(** The groupoid structure of equality *)\n\nTheorem eq_trans_refl_l : forall A (x y:A) (e:x=y), eq_trans eq_refl e = e.\nProof.\n  destruct e. reflexivity.\nDefined.\n\nTheorem eq_trans_refl_r : forall A (x y:A) (e:x=y), eq_trans e eq_refl = e.\nProof.\n  destruct e. reflexivity.\nDefined.\n\nTheorem eq_sym_involutive : forall A (x y:A) (e:x=y), eq_sym (eq_sym e) = e.\nProof.\n  destruct e; reflexivity.\nDefined.\n\nTheorem eq_trans_sym_inv_l : forall A (x y:A) (e:x=y), eq_trans (eq_sym e) e = eq_refl.\nProof.\n  destruct e; reflexivity.\nDefined.\n\nTheorem eq_trans_sym_inv_r : forall A (x y:A) (e:x=y), eq_trans e (eq_sym e) = eq_refl.\nProof.\n  destruct e; reflexivity.\nDefined.\n\nTheorem eq_trans_assoc : forall A (x y z t:A) (e:x=y) (e':y=z) (e'':z=t),\n  eq_trans e (eq_trans e' e'') = eq_trans (eq_trans e e') e''.\nProof.\n  destruct e''; reflexivity.\nDefined.\n\n(** Extra properties of equality *)\n\nTheorem eq_id_comm_l : forall A (f:A->A) (Hf:forall a, a = f a), forall a, f_equal f (Hf a) = Hf (f a).\nProof.\n  intros.\n  unfold f_equal.\n  rewrite <- (eq_trans_sym_inv_l (Hf a)).\n  destruct (Hf a) at 1 2.\n  destruct (Hf a).\n  reflexivity.\nDefined.\n\nTheorem eq_id_comm_r : forall A (f:A->A) (Hf:forall a, f a = a), forall a, f_equal f (Hf a) = Hf (f a).\nProof.\n  intros.\n  unfold f_equal.\n  rewrite <- (eq_trans_sym_inv_l (Hf (f (f a)))).\n  set (Hfsymf := fun a => eq_sym (Hf a)).\n  change (eq_sym (Hf (f (f a)))) with (Hfsymf (f (f a))).\n  pattern (Hfsymf (f (f a))).\n  destruct (eq_id_comm_l f Hfsymf (f a)).\n  destruct (eq_id_comm_l f Hfsymf a).\n  unfold Hfsymf.\n  destruct (Hf a). simpl.\n  rewrite eq_trans_refl_l.\n  reflexivity.\nDefined.\n\nLemma eq_refl_map_distr : forall A B x (f:A->B), f_equal f (eq_refl x) = eq_refl (f x).\nProof.\n  reflexivity.\nQed.\n\nLemma eq_trans_map_distr : forall A B x y z (f:A->B) (e:x=y) (e':y=z), f_equal f (eq_trans e e') = eq_trans (f_equal f e) (f_equal f e').\nProof.\ndestruct e'.\nreflexivity.\nDefined.\n\nLemma eq_sym_map_distr : forall A B (x y:A) (f:A->B) (e:x=y), eq_sym (f_equal f e) = f_equal f (eq_sym e).\nProof.\ndestruct e.\nreflexivity.\nDefined.\n\nLemma eq_trans_sym_distr : forall A (x y z:A) (e:x=y) (e':y=z), eq_sym (eq_trans e e') = eq_trans (eq_sym e') (eq_sym e).\nProof.\ndestruct e, e'.\nreflexivity.\nDefined.\n\nLemma eq_trans_rew_distr : forall A (P:A -> Type) (x y z:A) (e:x=y) (e':y=z) (k:P x),\n    rew (eq_trans e e') in k = rew e' in rew e in k.\nProof.\n  destruct e, e'; reflexivity.\nQed.\n\nLemma rew_const : forall A P (x y:A) (e:x=y) (k:P),\n    rew [fun _ => P] e in k = k.\nProof.\n  destruct e; reflexivity.\nQed.\n\n\n(* Aliases *)\n\nNotation sym_eq := eq_sym (only parsing).\nNotation trans_eq := eq_trans (only parsing).\nNotation sym_not_eq := not_eq_sym (only parsing).\n\nNotation refl_equal := eq_refl (only parsing).\nNotation sym_equal := eq_sym (only parsing).\nNotation trans_equal := eq_trans (only parsing).\nNotation sym_not_equal := not_eq_sym (only parsing).\n\nHint Immediate eq_sym not_eq_sym: core.\n\n(** Basic definitions about relations and properties *)\n\nDefinition subrelation (A B : Type) (R R' : A->B->Prop) :=\n  forall x y, R x y -> R' x y.\n\nDefinition unique (A : Type) (P : A->Prop) (x:A) :=\n  P x /\\ forall (x':A), P x' -> x=x'.\n\nDefinition uniqueness (A:Type) (P:A->Prop) := forall x y, P x -> P y -> x = y.\n\n(** Unique existence *)\n\nNotation \"'exists' ! x .. y , p\" :=\n  (ex (unique (fun x => .. (ex (unique (fun y => p))) ..)))\n  (at level 200, x binder, right associativity,\n   format \"'[' 'exists'  !  '/  ' x  ..  y ,  '/  ' p ']'\")\n  : type_scope.\n\nLemma unique_existence : forall (A:Type) (P:A->Prop),\n  ((exists x, P x) /\\ uniqueness P) <-> (exists! x, P x).\nProof.\n  intros A P; split.\n  - intros ((x,Hx),Huni); exists x; red; auto.\n  - intros (x,(Hx,Huni)); split.\n    + exists x; assumption.\n    + intros x' x'' Hx' Hx''; transitivity x.\n      symmetry; auto.\n      auto.\nQed.\n\nLemma forall_exists_unique_domain_coincide :\n  forall A (P:A->Prop), (exists! x, P x) ->\n  forall Q:A->Prop, (forall x, P x -> Q x) <-> (exists x, P x /\\ Q x).\nProof.\n  intros A P (x & Hp & Huniq); split.\n  - intro; exists x; auto.\n  - intros (x0 & HPx0 & HQx0) x1 HPx1.\n    assert (H : x0 = x1) by (transitivity x; [symmetry|]; auto).\n    destruct H.\n    assumption.\nQed.\n\nLemma forall_exists_coincide_unique_domain :\n  forall A (P:A->Prop),\n  (forall Q:A->Prop, (forall x, P x -> Q x) <-> (exists x, P x /\\ Q x))\n  -> (exists! x, P x).\nProof.\n  intros A P H.\n  destruct H with (Q:=P) as ((x & Hx & _),_); [trivial|].\n  exists x. split; [trivial|].\n  destruct H with (Q:=fun x'=>x=x') as (_,Huniq).\n  apply Huniq. exists x; auto.\nQed.\n\n(** * Being inhabited *)\n\n(** The predicate [inhabited] can be used in different contexts. If [A] is\n    thought as a type, [inhabited A] states that [A] is inhabited. If [A] is\n    thought as a computationally relevant proposition, then\n    [inhabited A] weakens [A] so as to hide its computational meaning.\n    The so-weakened proof remains computationally relevant but only in\n    a propositional context.\n*)\n\nInductive inhabited (A:Type) : Prop := inhabits : A -> inhabited A.\n\nHint Resolve inhabits: core.\n\nLemma exists_inhabited : forall (A:Type) (P:A->Prop),\n  (exists x, P x) -> inhabited A.\nProof.\n  destruct 1; auto.\nQed.\n\nLemma inhabited_covariant (A B : Type) : (A -> B) -> inhabited A -> inhabited B.\nProof.\n  intros f [x];exact (inhabits (f x)).\nQed.\n\n(** Declaration of stepl and stepr for eq and iff *)\n\nLemma eq_stepl : forall (A : Type) (x y z : A), x = y -> x = z -> z = y.\nProof.\n  intros A x y z H1 H2. rewrite <- H2; exact H1.\nQed.\n\nDeclare Left Step eq_stepl.\nDeclare Right Step eq_trans.\n\nLemma iff_stepl : forall A B C : Prop, (A <-> B) -> (A <-> C) -> (C <-> B).\nProof.\n  intros ? ? ? [? ?] [? ?]; split; intros; auto.\nQed.\n\nDeclare Left Step iff_stepl.\nDeclare Right Step iff_trans.\n\nLocal Notation \"'rew' 'dependent' H 'in' H'\"\n  := (match H with\n      | eq_refl => H'\n      end)\n       (at level 10, H' at level 10,\n        format \"'[' 'rew'  'dependent'  '/    ' H  in  '/' H' ']'\").\n\n(** Equality for [ex] *)\nSection ex.\n  Local Unset Implicit Arguments.\n  Definition eq_ex_uncurried {A : Type} (P : A -> Prop) {u1 v1 : A} {u2 : P u1} {v2 : P v1}\n             (pq : exists p : u1 = v1, rew p in u2 = v2)\n  : ex_intro P u1 u2 = ex_intro P v1 v2.\n  Proof.\n    destruct pq as [p q].\n    destruct q; simpl in *.\n    destruct p; reflexivity.\n  Qed.\n\n  Definition eq_ex {A : Type} {P : A -> Prop} (u1 v1 : A) (u2 : P u1) (v2 : P v1)\n             (p : u1 = v1) (q : rew p in u2 = v2)\n  : ex_intro P u1 u2 = ex_intro P v1 v2\n    := eq_ex_uncurried P (ex_intro _ p q).\n\n  Definition eq_ex_hprop {A} {P : A -> Prop} (P_hprop : forall (x : A) (p q : P x), p = q)\n             (u1 v1 : A) (u2 : P u1) (v2 : P v1)\n             (p : u1 = v1)\n    : ex_intro P u1 u2 = ex_intro P v1 v2\n    := eq_ex u1 v1 u2 v2 p (P_hprop _ _ _).\n\n  Lemma rew_ex {A x} {P : A -> Type} (Q : forall a, P a -> Prop) (u : exists p, Q x p) {y} (H : x = y)\n  : rew [fun a => exists p, Q a p] H in u\n    = match u with\n        | ex_intro _ u1 u2\n          => ex_intro\n               (Q y)\n               (rew H in u1)\n               (rew dependent H in u2)\n      end.\n  Proof.\n    destruct H, u; reflexivity.\n  Qed.\nEnd ex.\n\n(** Equality for [ex2] *)\nSection ex2.\n  Local Unset Implicit Arguments.\n\n  Definition eq_ex2_uncurried {A : Type} (P Q : A -> Prop) {u1 v1 : A}\n             {u2 : P u1} {v2 : P v1}\n             {u3 : Q u1} {v3 : Q v1}\n             (pq : exists2 p : u1 = v1, rew p in u2 = v2 & rew p in u3 = v3)\n  : ex_intro2 P Q u1 u2 u3 = ex_intro2 P Q v1 v2 v3.\n  Proof.\n    destruct pq as [p q r].\n    destruct r, q, p; simpl in *.\n    reflexivity.\n  Qed.\n\n  Definition eq_ex2 {A : Type} {P Q : A -> Prop}\n             (u1 v1 : A)\n             (u2 : P u1) (v2 : P v1)\n             (u3 : Q u1) (v3 : Q v1)\n             (p : u1 = v1) (q : rew p in u2 = v2) (r : rew p in u3 = v3)\n  : ex_intro2 P Q u1 u2 u3 = ex_intro2 P Q v1 v2 v3\n    := eq_ex2_uncurried P Q (ex_intro2 _ _ p q r).\n\n  Definition eq_ex2_hprop {A} {P Q : A -> Prop}\n             (P_hprop : forall (x : A) (p q : P x), p = q)\n             (Q_hprop : forall (x : A) (p q : Q x), p = q)\n             (u1 v1 : A) (u2 : P u1) (v2 : P v1) (u3 : Q u1) (v3 : Q v1)\n             (p : u1 = v1)\n    : ex_intro2 P Q u1 u2 u3 = ex_intro2 P Q v1 v2 v3\n    := eq_ex2 u1 v1 u2 v2 u3 v3 p (P_hprop _ _ _) (Q_hprop _ _ _).\n\n  Lemma rew_ex2 {A x} {P : A -> Type}\n        (Q : forall a, P a -> Prop)\n        (R : forall a, P a -> Prop)\n        (u : exists2 p, Q x p & R x p) {y} (H : x = y)\n  : rew [fun a => exists2 p, Q a p & R a p] H in u\n    = match u with\n        | ex_intro2 _ _ u1 u2 u3\n          => ex_intro2\n               (Q y)\n               (R y)\n               (rew H in u1)\n               (rew dependent H in u2)\n               (rew dependent H in u3)\n      end.\n  Proof.\n    destruct H, u; reflexivity.\n  Qed.\nEnd ex2.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/theories/Init/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6999548128227023}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\nRequire Import NAxioms NSub NZDiv.\n\n(** Properties of Euclidean Division *)\n\nModule Type NDivProp (Import N : NAxiomsSig')(Import NP : NSubProp N).\n\n(** We benefit from what already exists for NZ *)\nModule Import Private_NZDiv := Nop <+ NZDivProp N N NP.\n\nLtac auto' := try rewrite <- neq_0_lt_0; auto using le_0_l.\n\n(** Let's now state again theorems, but without useless hypothesis. *)\n\nLemma mod_upper_bound : forall a b, b ~= 0 -> a mod b < b.\nProof. intros. apply mod_bound_pos; auto'. Qed.\n\n(** Another formulation of the main equation *)\n\nLemma mod_eq :\n forall a b, b~=0 -> a mod b == a - b*(a/b).\nProof.\nintros.\nsymmetry. apply add_sub_eq_l. symmetry.\nnow apply div_mod.\nQed.\n\n(** Uniqueness theorems *)\n\nTheorem div_mod_unique :\n forall b q1 q2 r1 r2, r1<b -> r2<b ->\n  b*q1+r1 == b*q2+r2 -> q1 == q2 /\\ r1 == r2.\nProof. intros. apply div_mod_unique with b; auto'. Qed.\n\nTheorem div_unique:\n forall a b q r, r<b -> a == b*q + r -> q == a/b.\nProof. intros; apply div_unique with r; auto'. Qed.\n\nTheorem mod_unique:\n forall a b q r, r<b -> a == b*q + r -> r == a mod b.\nProof. intros. apply mod_unique with q; auto'. Qed.\n\nTheorem div_unique_exact: forall a b q, b~=0 -> a == b*q -> q == a/b.\nProof. intros. apply div_unique_exact; auto'. Qed.\n\n(** A division by itself returns 1 *)\n\nLemma div_same : forall a, a~=0 -> a/a == 1.\nProof. intros. apply div_same; auto'. Qed.\n\nLemma mod_same : forall a, a~=0 -> a mod a == 0.\nProof. intros. apply mod_same; auto'. Qed.\n\n(** A division of a small number by a bigger one yields zero. *)\n\nTheorem div_small: forall a b, a<b -> a/b == 0.\nProof. intros. apply div_small; auto'. Qed.\n\n(** Same situation, in term of modulo: *)\n\nTheorem mod_small: forall a b, a<b -> a mod b == a.\nProof. intros. apply mod_small; auto'. Qed.\n\n(** * Basic values of divisions and modulo. *)\n\nLemma div_0_l: forall a, a~=0 -> 0/a == 0.\nProof. intros. apply div_0_l; auto'. Qed.\n\nLemma mod_0_l: forall a, a~=0 -> 0 mod a == 0.\nProof. intros. apply mod_0_l; auto'. Qed.\n\nLemma div_1_r: forall a, a/1 == a.\nProof. intros. apply div_1_r; auto'. Qed.\n\nLemma mod_1_r: forall a, a mod 1 == 0.\nProof. intros. apply mod_1_r; auto'. Qed.\n\nLemma div_1_l: forall a, 1<a -> 1/a == 0.\nProof. exact div_1_l. Qed.\n\nLemma mod_1_l: forall a, 1<a -> 1 mod a == 1.\nProof. exact mod_1_l. Qed.\n\nLemma div_mul : forall a b, b~=0 -> (a*b)/b == a.\nProof. intros. apply div_mul; auto'. Qed.\n\nLemma mod_mul : forall a b, b~=0 -> (a*b) mod b == 0.\nProof. intros. apply mod_mul; auto'. Qed.\n\n\n(** * Order results about mod and div *)\n\n(** A modulo cannot grow beyond its starting point. *)\n\nTheorem mod_le: forall a b, b~=0 -> a mod b <= a.\nProof. intros. apply mod_le; auto'. Qed.\n\nLemma div_str_pos : forall a b, 0<b<=a -> 0 < a/b.\nProof. exact div_str_pos. Qed.\n\nLemma div_small_iff : forall a b, b~=0 -> (a/b==0 <-> a<b).\nProof. intros. apply div_small_iff; auto'. Qed.\n\nLemma mod_small_iff : forall a b, b~=0 -> (a mod b == a <-> a<b).\nProof. intros. apply mod_small_iff; auto'. Qed.\n\nLemma div_str_pos_iff : forall a b, b~=0 -> (0<a/b <-> b<=a).\nProof. intros. apply div_str_pos_iff; auto'. Qed.\n\n\n(** As soon as the divisor is strictly greater than 1,\n    the division is strictly decreasing. *)\n\nLemma div_lt : forall a b, 0<a -> 1<b -> a/b < a.\nProof. exact div_lt. Qed.\n\n(** [le] is compatible with a positive division. *)\n\nLemma div_le_mono : forall a b c, c~=0 -> a<=b -> a/c <= b/c.\nProof. intros. apply div_le_mono; auto'. Qed.\n\nLemma mul_div_le : forall a b, b~=0 -> b*(a/b) <= a.\nProof. intros. apply mul_div_le; auto'. Qed.\n\nLemma mul_succ_div_gt: forall a b, b~=0 -> a < b*(S (a/b)).\nProof. intros; apply mul_succ_div_gt; auto'. Qed.\n\n(** The previous inequality is exact iff the modulo is zero. *)\n\nLemma div_exact : forall a b, b~=0 -> (a == b*(a/b) <-> a mod b == 0).\nProof. intros. apply div_exact; auto'. Qed.\n\n(** Some additional inequalities about div. *)\n\nTheorem div_lt_upper_bound:\n  forall a b q, b~=0 -> a < b*q -> a/b < q.\nProof. intros. apply div_lt_upper_bound; auto'. Qed.\n\nTheorem div_le_upper_bound:\n  forall a b q, b~=0 -> a <= b*q -> a/b <= q.\nProof. intros; apply div_le_upper_bound; auto'. Qed.\n\nTheorem div_le_lower_bound:\n  forall a b q, b~=0 -> b*q <= a -> q <= a/b.\nProof. intros; apply div_le_lower_bound; auto'. Qed.\n\n(** A division respects opposite monotonicity for the divisor *)\n\nLemma div_le_compat_l: forall p q r, 0<q<=r -> p/r <= p/q.\nProof. intros. apply div_le_compat_l. auto'. auto. Qed.\n\n(** * Relations between usual operations and mod and div *)\n\nLemma mod_add : forall a b c, c~=0 ->\n (a + b * c) mod c == a mod c.\nProof. intros. apply mod_add; auto'. Qed.\n\nLemma div_add : forall a b c, c~=0 ->\n (a + b * c) / c == a / c + b.\nProof. intros. apply div_add; auto'. Qed.\n\nLemma div_add_l: forall a b c, b~=0 ->\n (a * b + c) / b == a + c / b.\nProof. intros. apply div_add_l; auto'. Qed.\n\n(** Cancellations. *)\n\nLemma div_mul_cancel_r : forall a b c, b~=0 -> c~=0 ->\n (a*c)/(b*c) == a/b.\nProof. intros. apply div_mul_cancel_r; auto'. Qed.\n\nLemma div_mul_cancel_l : forall a b c, b~=0 -> c~=0 ->\n (c*a)/(c*b) == a/b.\nProof. intros. apply div_mul_cancel_l; auto'. Qed.\n\nLemma mul_mod_distr_r: forall a b c, b~=0 -> c~=0 ->\n  (a*c) mod (b*c) == (a mod b) * c.\nProof. intros. apply mul_mod_distr_r; auto'. Qed.\n\nLemma mul_mod_distr_l: forall a b c, b~=0 -> c~=0 ->\n  (c*a) mod (c*b) == c * (a mod b).\nProof. intros. apply mul_mod_distr_l; auto'. Qed.\n\n(** Operations modulo. *)\n\nTheorem mod_mod: forall a n, n~=0 ->\n (a mod n) mod n == a mod n.\nProof. intros. apply mod_mod; auto'. Qed.\n\nLemma mul_mod_idemp_l : forall a b n, n~=0 ->\n ((a mod n)*b) mod n == (a*b) mod n.\nProof. intros. apply mul_mod_idemp_l; auto'. Qed.\n\nLemma mul_mod_idemp_r : forall a b n, n~=0 ->\n (a*(b mod n)) mod n == (a*b) mod n.\nProof. intros. apply mul_mod_idemp_r; auto'. Qed.\n\nTheorem mul_mod: forall a b n, n~=0 ->\n (a * b) mod n == ((a mod n) * (b mod n)) mod n.\nProof. intros. apply mul_mod; auto'. Qed.\n\nLemma add_mod_idemp_l : forall a b n, n~=0 ->\n ((a mod n)+b) mod n == (a+b) mod n.\nProof. intros. apply add_mod_idemp_l; auto'. Qed.\n\nLemma add_mod_idemp_r : forall a b n, n~=0 ->\n (a+(b mod n)) mod n == (a+b) mod n.\nProof. intros. apply add_mod_idemp_r; auto'. Qed.\n\nTheorem add_mod: forall a b n, n~=0 ->\n (a+b) mod n == (a mod n + b mod n) mod n.\nProof. intros. apply add_mod; auto'. Qed.\n\nLemma div_div : forall a b c, b~=0 -> c~=0 ->\n (a/b)/c == a/(b*c).\nProof. intros. apply div_div; auto'. Qed.\n\nLemma mod_mul_r : forall a b c, b~=0 -> c~=0 ->\n a mod (b*c) == a mod b + b*((a/b) mod c).\nProof. intros. apply mod_mul_r; auto'. Qed.\n\n(** A last inequality: *)\n\nTheorem div_mul_le:\n forall a b c, b~=0 -> c*(a/b) <= (c*a)/b.\nProof. intros. apply div_mul_le; auto'. Qed.\n\n(** mod is related to divisibility *)\n\nLemma mod_divides : forall a b, b~=0 ->\n (a mod b == 0 <-> exists c, a == b*c).\nProof. intros. apply mod_divides; auto'. Qed.\n\nEnd NDivProp.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Numbers/Natural/Abstract/NDiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.6999548106956217}}
{"text": "Require Import Omega.\nRequire Import Wf_nat.\n\nDefinition f1_aux :\n  forall x, (forall z, z < x ->{y:nat | z=0 \\/ y < z})->{y:nat | x=0\\/ y< x}.\n intros x; case x.\n(* value for 0 *)\n intros rec; exists 0; auto.\n intros x'; case x'.\n(* value for 1 *)\n intros rec; exists 0; auto.  \n(* value for x > 1 *)\n refine\n    (fun x'' rec => \n      match rec (S x'') _ with\n      | (exist v H) =>\n        match rec (S v) _ with\n        | (exist v' H') => (exist _ (S v') _)\n        end\n      end); omega.\nDefined.\n\nDefinition f1' : forall x, {y:nat | x=0 \\/ y<x} :=\n (well_founded_induction lt_wf\n   (fun x:nat => {y:nat | x=0\\/ y<x})\n   f1_aux).\n\nDefinition f1 (x:nat): nat :=\n match f1' x with (exist v _) => v end.\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/gen-rec/SRC/exo_15_14.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.7490872243177517, "lm_q1q2_score": 0.6999434746181808}}
{"text": "Require Import List.\nRequire Import Arith.\nImport ListNotations.\n\nClass Serializer (A : Type) : Type :=\n  {\n    serialize : A -> list bool;\n    deserialize : list bool -> option (A * list bool);\n    deser_ser_identity : forall a : A, forall bools: list bool, (deserialize ((serialize a) ++ bools)) = Some (a, bools);\n  }.\n\nDefinition bool_serialize (b : bool): list bool := [b].\n\nDefinition bool_deserialize (bools : list bool): option(bool * list bool) := \n  match bools with\n  | [] => None\n  | h :: t => Some(h, t)\n  end.\n\n\nLemma bool_deser_ser_identity : forall a : bool, forall bools: list bool,\n(bool_deserialize ((bool_serialize a) ++ bools)) = Some (a, bools).\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\nInstance BoolSerializer : Serializer bool.\nProof.\nexact {| serialize := bool_serialize;\n         deserialize := bool_deserialize;\n         deser_ser_identity := bool_deser_ser_identity;\n       |}.\nDefined.\n\nInductive Binary : Type :=\n  | Z : Binary (* Zero *)\n  | T : Binary -> Binary (* Twice *)\n  | O : Binary -> Binary (* Twice plus one *)\n.\n\nFixpoint inc (b : Binary) : Binary :=\n  match b with\n  | Z => O Z\n  | T n => O n (* T (O n) *)\n  | O n => T (inc n)\n  end.\n\nFixpoint extract_last (b:Binary) :=\n  match b with\n  | Z => (Z , Z)\n  | T Z => (T Z, Z)\n  | O Z => (O Z, Z)\n  | T b => (fst (extract_last b), T (snd (extract_last b)))\n  | O b => (fst (extract_last b), O (snd (extract_last b)))\n  end.\n\nFixpoint nat2bin (n : nat) : Binary :=\n  match n with\n  | Datatypes.O => Z\n  | S n => inc (nat2bin n)\n  end.\n\nFixpoint bin2nat (b: Binary) : nat :=\n  match b with\n  | Z => Datatypes.O\n  | T b => (bin2nat b) + (bin2nat b)\n  | O b => S ((bin2nat b) + (bin2nat b))\n  end.\n\nLemma nat2bin_plus1 : forall n:nat,\n  inc (nat2bin n) = nat2bin (S n).\nProof.\n  induction n.\n  - simpl. reflexivity.\n  - simpl.\n    reflexivity.\nQed.\n\nLemma bin2nat_plus1 : forall b:Binary,\n  bin2nat (inc b) = S (bin2nat b). \nProof.\n  induction b.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl.\n    rewrite IHb.\n    rewrite plus_n_Sm.\n    rewrite <- plus_Sn_m.\n    reflexivity.\nQed.\n\nLemma nat2bin_identity : forall n: nat,\n  (bin2nat (nat2bin n)) = n.\nProof.\n  intros.\n  induction n.\n  - simpl. reflexivity.\n  - simpl.\n    rewrite bin2nat_plus1.\n    rewrite IHn.\n    reflexivity.\nQed.\n\nLemma bin2nat_invertable : forall b: Binary,\n  (nat2bin (bin2nat b)) = b.\nProof.\n  intros.\n  induction b.\n  - simpl. reflexivity.\n  - simpl.\n    unfold nat2bin.\nAbort.\n\nFixpoint binary_serialize (b : Binary) : list bool :=\n  match b with\n  | Z => [false]\n  | T b => [true; true] ++ (binary_serialize b)\n  | O b => [true; false] ++ (binary_serialize b)\n  end.\n\nFixpoint binary_deserialize (bools : list bool) : option (Binary * list bool) :=\n  match bools with\n  | true :: false :: rest => \n    match (binary_deserialize rest) with\n    | None => None\n    | Some (b, rest) => Some (O b, rest)\n    end\n  | true :: true :: rest => \n    match (binary_deserialize rest) with\n    | None => None\n    | Some (b, rest) => Some (T b, rest)\n    end\n  | false :: rest => Some (Z, rest)\n  | _ => None\n  end.\n\nLemma binary_deser_ser_identity : forall a : Binary, forall bools: list bool,\n  (binary_deserialize ((binary_serialize a) ++ bools)) = Some (a, bools).\nProof.\n  intros.\n  induction a.\n  - simpl. \n    reflexivity.\n  - simpl.\n    rewrite IHa.\n    reflexivity.\n  - simpl.\n    rewrite IHa.\n    reflexivity.\nQed.\n\nInstance BinarySerializer : Serializer Binary.\nProof.\nexact {| serialize := binary_serialize;\n         deserialize := binary_deserialize;\n         deser_ser_identity := binary_deser_ser_identity;\n       |}.\nDefined.\n\nDefinition nat_serialize (n : nat) : list bool := binary_serialize (nat2bin n).\n\nDefinition nat_deserialize (bools : list bool) : option (nat * list bool) := \n  match (binary_deserialize bools) with\n  | None => None\n  | Some (b, rest) => Some (bin2nat b, rest)\n  end.\n\nLemma nat_deser_ser_identity: forall a : nat, forall bools: list bool,\n  (nat_deserialize ((nat_serialize a) ++ bools)) = Some (a, bools).\nProof.\n  intros.\n  unfold nat_serialize, nat_deserialize.\n  rewrite binary_deser_ser_identity.\n  rewrite nat2bin_identity.\n  reflexivity.\nQed.\n\n\nInstance NatSerializer : Serializer nat.\nProof.\nexact {| serialize := nat_serialize;\n         deserialize := nat_deserialize;\n         deser_ser_identity := nat_deser_ser_identity;\n       |}.\nDefined.\n\nSection PairSerializer.\n  Variable A B : Type.\n  Variable serA : Serializer A.\n  Variable serB : Serializer B.\n\n  Definition pair_serialize (p : A * B) : list bool :=\n    serialize (fst p) ++ serialize (snd p).\n\n  Definition pair_deserialize (bools : list bool) : option ((A * B) * list bool) :=\n    match (deserialize bools) with\n    | None => None\n    | Some (a, bools) => \n      match (deserialize bools) with\n      | None => None\n      | Some (b, bools) => Some ((a,b), bools)\n      end\n    end.\n\n  Lemma pair_deser_ser_identity: forall (p : A * B) (bools: list bool),\n    pair_deserialize ((pair_serialize p) ++ bools) = Some (p, bools).\n  Proof.\n    intros.\n    unfold pair_serialize, pair_deserialize.\n    rewrite <- app_assoc.\n    rewrite deser_ser_identity.\n    rewrite deser_ser_identity.\n    rewrite <- surjective_pairing.\n    reflexivity.\n  Qed.\n\n  Global Instance PairSerializer : Serializer (A * B).\n  Proof.\n  exact {| serialize := pair_serialize;\n           deserialize := pair_deserialize;\n           deser_ser_identity := pair_deser_ser_identity;\n         |}.\n  Defined.\nEnd PairSerializer.\n\nSection SumSerializer.\n  Variable A B : Type.\n  Variable serA : Serializer A.\n  Variable serB : Serializer B.\n\n  Definition sum_serialize (s : A + B) : list bool :=\n    match s with\n    | inl a => [true] ++ serialize a\n    | inr b => [false] ++ serialize b\n    end.\n\n  Definition sum_deserialize (bools : list bool) : option ((A + B) * list bool) :=\n    match bools with\n    | true :: bools => \n      match (deserialize bools) with\n      | Some (a, bools) => Some(inl a, bools)\n      | None => None\n      end\n    | false :: bools => \n      match (deserialize bools) with\n      | Some (b, bools) => Some(inr b, bools)\n      | None => None\n      end\n    | _ => None\n    end.\n\n  Lemma sum_deser_ser_identity: forall (s: A + B) (bools: list bool),\n    sum_deserialize ((sum_serialize s) ++ bools) = Some (s, bools).\n  Proof.\n    intros.\n    destruct s.\n    - simpl.\n      rewrite deser_ser_identity.\n      reflexivity.\n    - simpl.\n      rewrite deser_ser_identity.\n      reflexivity.\n  Qed.\n\n  Global Instance SumSerializer : Serializer (A + B).\n  Proof.\n  exact {| serialize := sum_serialize;\n           deserialize := sum_deserialize;\n           deser_ser_identity := sum_deser_ser_identity;\n         |}.\n  Defined.\nEnd SumSerializer.\n\nSection OptionSerializer.\n  Variable A : Type.\n  Variable serA : Serializer A.\n\n  Definition option_serialize (o : option A) : list bool :=\n    match o with\n    | Some a => [true] ++ serialize a\n    | None => [false]\n    end.\n\n  Definition option_deserialize (bools : list bool) : option (option(A) * list bool) :=\n    match bools with\n    | false :: bools => Some(None, bools)\n    | true :: bools => \n      match (deserialize bools) with\n      | Some (a, bools) => Some(Some a, bools)\n      | None => None\n      end\n    | _ => None\n    end.\n\n  Lemma option_deser_ser_identity: forall (o : option A) (bools: list bool),\n    option_deserialize ((option_serialize o) ++ bools) = Some (o, bools).\n  Proof.\n    intros.\n    destruct o.\n    - simpl.\n      rewrite deser_ser_identity.\n      reflexivity.\n    - simpl.\n      reflexivity.\n  Qed.\n\n  Global Instance OptionSerializer : Serializer (option A).\n  Proof.\n  exact {| serialize := option_serialize;\n           deserialize := option_deserialize;\n           deser_ser_identity := option_deser_ser_identity;\n         |}.\n  Defined.\nEnd OptionSerializer.\n\nSection ListSerializer.\n  Variable A : Type.\n  Variable serA : Serializer A.\n\n  Fixpoint list_serialize (l : list A) : list bool :=\n    match l with\n    | [] => [false]\n    | a :: l => [true] ++ (list_serialize l) ++ serialize a\n    end.\n\n  Fixpoint list_deserialize (bools : list bool) : option (list A * list bool) :=\n    match bools with\n    | false :: bools => Some([], bools)\n    | true :: bools =>\n      match (list_deserialize bools) with\n      | None => None\n      | Some (list, bools) =>\n        match (deserialize bools) with\n        | None => None\n        | Some (a, bools) => Some(a :: list, bools)\n        end\n      end\n    | _ => None\n    end.\n\n  Lemma list_deser_ser_one: forall (a : A) (l : list A) (bools: list bool),\n    list_deserialize ((list_serialize (a :: l)) ++ bools) = \n      Some (a :: list_deserialize ((list_serialize l), bools)).\n  Proof.\n    intros.\n    unfold list_deserialize, list_serialize.\n    rewrite app_ass, app_ass.\n    simpl.\n  Qed.\n\n  Lemma list_deser_ser_one: forall (a : A) (l : list A) (bools: list bool),\n    list_deserialize ((list_serialize (a :: l)) ++ bools) = Some (a :: l, bools).\n  Proof.\n    intros.\n    unfold list_deserialize, list_serialize.\n    rewrite app_ass, app_ass.\n    simpl.\n  Qed.\n\n  Lemma list_deser_ser_identity: forall (l : list A) (bools: list bool),\n    list_deserialize ((list_serialize l) ++ bools) = Some (l, bools).\n  Proof.\n    intro l.\n    induction l.\n    - simpl. reflexivity.\n    - simpl.\n      intro bools.\n      rewrite <- app_assoc.\n      rewrite IHl.\n      rewrite deser_ser_identity.\n      reflexivity.\n  Qed.\n\n  Global Instance ListSerializer : Serializer (list A).\n  Proof.\n  exact {| serialize := list_serialize;\n           deserialize := list_deserialize;\n           deser_ser_identity := list_deser_ser_identity;\n         |}.\n  Defined.\nEnd ListSerializer.\n\nSection TreeSerializer.\n  Variable A : Type.\n  Variable serA : Serializer A.\n\n  Inductive tree: Type := \n  | leaf : tree\n  | stem : A -> tree -> tree -> tree.\n\n  Definition tree_prune (t: tree) :=\n    match t with\n    | leaf => leaf\n    | stem a l r => stem a leaf leaf\n    end.\n\n  Fixpoint tree_insert (into node: tree) (path: list bool): tree :=\n    match into with\n    | leaf => node\n    | stem a l r =>\n        match path with\n        | [] => node (* also not supported *)\n        | true :: path => stem a (tree_insert l node path) r\n        | false :: path => stem a l (tree_insert r node path)\n        end\n    end.\n\n  Fixpoint leaf_insertable (into: tree) (path: list bool): Prop :=\n    match into with\n    | leaf => \n        match path with\n        | [] => True (* Only if the location and tree run out at the same time should we insert *)\n        | _ => False\n        end\n    | stem a l r =>\n        match path with\n        | [] => False\n        | true :: path => (leaf_insertable l path)\n        | false :: path => (leaf_insertable r path)\n        end\n    end.\n\n  Fixpoint serialized_fold (fn : tree * list bool -> option(tree * list bool)) (bools : list bool) : option(tree * list bool) :=\n    match bools with\n    | true :: bools => \n      match (serialized_fold fn bools) with\n      | Some (t, bools) => fn (t, bools)\n      | None => None\n      end\n    | false :: bools => Some (leaf, bools)\n    | _ => None\n    end.\n\n  Fixpoint tree_size (t:tree) : nat :=\n    match t with\n    | leaf => 0\n    | stem a l r => 1 + tree_size l + tree_size r\n    end.\n\n  Definition tree_serialize_node (t: tree) (location: list bool): list bool :=\n    match t with\n      | leaf => []\n      | stem a l r => (serialize location) ++ (serialize a)\n    end.\n\n  Fixpoint tree_serialize_subtree (t: tree) (location: list bool): list bool :=\n    match t with\n      | leaf => tree_serialize_node t location\n      | stem a l r =>  tree_serialize_node t location  ++ (tree_serialize_subtree l (true :: location)) ++ \n        (tree_serialize_subtree r (false :: location))\n    end.\n\n  Fixpoint tree_serialize_header (t : tree) :=\n    match t with\n    | leaf => []\n    | stem a l r => [true] ++ tree_serialize_header l ++ tree_serialize_header r\n    end.\n\n  Definition tree_serialize (t: tree) : list bool :=\n    (nat_serialize (tree_size t)) ++ (tree_serialize_subtree t []).\n\n  Definition tree_deserialize_node (root :tree) (bools: list bool) : option (tree * list bool) :=\n    match (list_deserialize bool BoolSerializer bools) with\n    | None => None\n    | Some (location, bools) =>\n      match (deserialize bools) with\n      | None => None\n      | Some (a, bools) => Some (tree_insert root (stem a leaf leaf) (rev location), bools)\n      end\n    end.\n\n  Fixpoint tree_deserialize_impl (remaining : nat) (root : tree) (bools : list bool) : option (tree * list bool) :=\n    match remaining with\n    | S n =>\n      match tree_deserialize_node root bools with\n      | None => None\n      | Some (root, bools) => tree_deserialize_impl n root bools\n      end\n    | _ => Some (root, bools)\n    end.\n\n  Fixpoint is_subpath (parent path: list bool) : bool := \n    match parent, path with\n    | [], _ => true\n    | _, [] => false\n    | h_parent :: t_parent, h_path :: t_path => (Bool.eqb h_parent h_path) && (is_subpath t_parent t_path)\n    end.\n\n(*\n  Fixpoint tree_deserialize_subtree (remaining : nat) (root: tree) (path: list bool) (bools: list bool) : option (tree * list bool) :=\n    match remaining with\n    | S n => \n      match (tree_deserialize_subtree n root path bools) with\n      | None => None\n      | Some (root, []) => Some (root, bools)\n      | Some (root, bools) => \n        match (list_deserialize bool BoolSerializer bools) with\n        | None => None\n        | Some (location, bools) =>\n          match (is_subpath path (rev location)) with\n          | false => Some (root, bools)\n          | true => \n            match (deserialize bools) with\n            | None => None\n            | Some (a, bools) => Some (tree_insert root (stem a leaf leaf) (rev location), bools)\n            end\n          end\n        end\n      end\n    | _ => Some (root, bools)\n    end.\n*)\n\n  Fixpoint tree_deserialize_size (bools : list bool) : option (nat * list bool):=\n    match bools with\n    | true :: bools =>\n      match tree_deserialize_size bools with\n      | Some (n, bools) => Some (S n, bools)\n      | None => None\n      end\n    | false :: bools => Some (0, bools)\n    | _ => None\n    end.\n\n  Definition tree_deserialize (bools: list bool) : option (tree * list bool) :=\n    match nat_deserialize bools with \n    | Some (size, bools) => tree_deserialize_impl size leaf bools\n    | None => None\n    end.\n\n  Lemma sublocation_child_sublocation: forall location parent sublocation: list bool,\n    is_subpath (rev parent) (rev location) = true -> is_subpath (rev parent) (rev (location ++ sublocation)) = true.\n  Proof.\n    intros location parent sublocation.\n    induction sublocation.\n    - Abort.\n\n  Lemma subpath_child_subpath: forall path parent subpath: list bool,\n    is_subpath parent path = true -> is_subpath parent (path ++ subpath) = true.\n  Proof.\n    intros path parent subpath.\n    induction parent.\n    - simpl. reflexivity.\n    - intros. Abort.\n\n  Fixpoint skipped_branches (root : tree) (path : list bool) : list tree :=\n    match root, path with\n    | leaf, _ => [] (* The tree ran out before the path... probably shouldn't happen *)\n    | stem a l r, true :: path => r :: (skipped_branches l path) (* The ordering here may have to be flipped *)\n    | stem a l r, false :: path => l :: (skipped_branches r path)\n    | stem a l r, [] => [] (* Everything underneath will be seen *)\n    end.\n\n  Fixpoint unseen_branches_impl (current : tree) (path : list bool) (location: list bool) : list (tree * list bool) :=\n    match current, path with\n    | leaf, _ => [] (* The tree ran out before the path... probably shouldn't happen *)\n    | stem a l r, true :: path => (unseen_branches_impl l path (true::location)) ++ [(r, rev location)] (* The ordering here may have to be flipped *)\n    | stem a l r, false :: path => (unseen_branches_impl r path (false::location)) ++ [(l, rev location)]\n    | stem a l r, [] => [(stem a l r, location)] (* Everything underneath will be seen *)\n    end.\n\n  Definition unseen_branches (root : tree) (path : list bool) : list (tree * list bool) :=\n    unseen_branches_impl root path [].\n\n  Fixpoint skipped_branches_clean (current : tree) (path : list bool) : list (tree) :=\n    match current, path with\n    | leaf, _ => [] (* The tree ran out before the path... probably shouldn't happen *)\n    | stem a l r, true :: path => [r] ++ (skipped_branches_clean l path) (* Skpped the right *)\n    | stem a l r, false :: path => (skipped_branches_clean r path) (* Already been to the left *)\n    | stem a l r, [] => [stem a l r] (* Everything underneath will be seen *)\n    end.\n\n  Fixpoint reassemble_tree (root: tree) (path : list bool) (branches: list tree) : tree :=\n    match root, path, branches with \n    | stem a l r, [], _ => stem a l r\n    | stem a l r, true :: path, [] => stem a l r\n    | stem a l r, true :: path, branch :: branches => stem a (reassemble_tree l path branches) branch\n    | stem a l r, false :: path, _  => stem a l (reassemble_tree r path branches)\n    | leaf, _, _ => leaf\n    end.\n\n  Fixpoint seen_tree (root : tree) (path : list bool) (*{struct path}*) : tree :=\n    match root, path with\n    | leaf, _ => leaf (* The tree ran out before the path... probably shouldn't happen *)\n    | stem a l r, true :: path => stem a (seen_tree l path) leaf\n    | stem a l r, false :: path => stem a l (seen_tree r path)\n    | stem a l r, [] => stem a l r (* Everything underneath will be observed *)\n    end.\n\n  Lemma skip_reassemble_whole : forall t : tree, forall path : list bool,\n    leaf_insertable t path ->\n      reassemble_tree (seen_tree t path) path (skipped_branches_clean t path) = t.\n  Proof.\n    induction t as [|a l IHL r IHR ]; intros path InTree.\n    - simpl. reflexivity.\n    - simpl.\n      destruct path.\n      + trivial.\n      + destruct b.\n        * simpl. \n          rewrite IHL.\n          reflexivity.\n          simpl in InTree.\n          apply InTree.\n  Abort.\n\n  Lemma tree_insert_at_leaf : forall root : tree, forall path : list bool,\n    leaf_insertable root path ->\n      tree_insert root leaf path = root.\n  Proof.\n    induction root as [| a l IHL r IHR]; intros.\n    - destruct path.\n      + trivial.\n      + simpl in H. inversion H.\n    - unfold tree_insert; fold tree_insert.\n      destruct path.\n      + simpl in H. inversion H.\n      + simpl in H.\n        destruct b;\n          f_equal.\n        * apply IHL.\n          apply H.\n        * apply IHR.\n          apply H.\n  Qed.\n\n  Lemma tree_insert_into_leaf_l : forall root l r: tree, forall path: list bool, forall a: A, \n    leaf_insertable root path -> \n      tree_insert (tree_insert root (stem a leaf r) path) l (path ++ [true]) =\n      tree_insert root (stem a l r) path.\n  Proof.\n    induction root as [| a l IHL r IHR]; intros.\n    - destruct path.\n      + trivial.\n      + simpl in H. inversion H.\n    - destruct path; simpl in H. \n      + inversion H.\n      + destruct b;\n        simpl;\n        f_equal.\n        * apply IHL, H.\n        * apply IHR, H.\n  Qed.\n\n  Lemma tree_insert_into_leaf_r : forall root r l: tree, forall path: list bool, forall a: A, \n    leaf_insertable root path -> \n      tree_insert (tree_insert root (stem a l leaf) path) r (path ++ [false]) =\n      tree_insert root (stem a l r) path.\n  Proof. (* Is there a way to reuse proof reasoning, like from above? *)\n    induction root as [| a l IHL r IHR]; intros.\n    - destruct path.\n      + trivial.\n      + simpl in H. inversion H.\n    - destruct path; simpl in H. \n      + inversion H.\n      + destruct b;\n        simpl;\n        f_equal.\n        * apply IHL, H.\n        * apply IHR, H.\n  Qed.\n\n  Lemma tree_insert_into_empty : forall root l r : tree, forall path: list bool, forall a: A, \n    leaf_insertable root path -> \n      tree_insert (\n        tree_insert (tree_insert root (stem a leaf leaf) path) l \n          (path ++ [true])) r (path ++ [false]) =\n      tree_insert root (stem a l r) path.\n  Proof.\n    intros.\n    rewrite tree_insert_into_leaf_l.\n    rewrite tree_insert_into_leaf_r.\n    reflexivity.\n    apply H.\n    apply H.\n  Qed.\n\n  Lemma tree_insertable_after_r : forall (root l : tree) (a : A) (path : list bool),\n  leaf_insertable root path ->\n    leaf_insertable (tree_insert root (stem a l leaf) path) (path ++ [false]).\n  Proof.\n    induction root as [| a l IHL r IHR]; intros.\n    - simpl.\n      destruct path.\n      + trivial.\n      + simpl in H. inversion H.\n    - destruct path.\n      + simpl in H. inversion H.\n      + simpl.\n        simpl in H.\n        destruct b.\n        * apply IHL.\n          apply H.\n        * apply IHR.\n          apply H.\n  Qed.\n\n  Lemma tree_insertable_after_l : forall (root r : tree) (a : A) (path : list bool),\n  leaf_insertable root path ->\n    leaf_insertable (tree_insert root (stem a leaf r) path) (path ++ [true]).\n  Proof.\n    induction root as [| a l IHL r IHR]; intros.\n    - simpl.\n      destruct path.\n      + trivial.\n      + simpl in H. inversion H.\n    - destruct path.\n      + simpl in H. inversion H.\n      + simpl.\n        simpl in H.\n        destruct b.\n        * apply IHL.\n          apply H.\n        * apply IHR.\n          apply H.\n  Qed.\n\n  Lemma tree_deser_ser_impl : forall a root : tree, forall location : list bool, forall bs : list bool, forall n : nat,\n      leaf_insertable root (rev location) ->\n      tree_deserialize_impl (tree_size a + n) root (tree_serialize_subtree a location ++ bs) = \n        tree_deserialize_impl n (tree_insert root a (rev location)) bs.\n  induction a as [| a l IHL r IHR]; intros root location bs n InTree.\n  - simpl.\n    rewrite tree_insert_at_leaf.\n    reflexivity.\n    apply InTree.\n  - cbn - [tree_insert].\n    rewrite !app_ass.\n    unfold tree_deserialize_node.\n    rewrite list_deser_ser_identity.\n    rewrite deser_ser_identity.\n    rewrite <- plus_assoc.\n    rewrite IHL.\n    rewrite IHR.\n    f_equal.\n    rewrite tree_insert_into_empty.\n      reflexivity.\n    apply InTree.\n      rewrite tree_insert_into_leaf_l.\n      simpl.\n      apply tree_insertable_after_r.\n      apply InTree.\n      apply InTree.\n    apply tree_insertable_after_l.\n      apply InTree.\n  Qed.\n\n(* For reassemble\n  Lemma tree_deser_ser_partTree : forall seen : tree, forall location bools : list bool,\n    leaf_insertable root location ->\n      tree_deserialize ((nat_serialize (tree_size root)) ++ ) = Some (root, bools).\n\n  Lemma tree_deser_ser_subtree : forall a r : tree, forall i : list bool, forall bs : list bool, forall n : nat,\n      leaf_insertable r (rev i) ->\n      tree_deserialize_subtree n r (tree_serialize_subtree a  i ++ bs) = tree_deserialize_subtree n (tree_insert a r (rev i)) bs.\n  Proof.\n    intros a r i bs n insertable.\n    induction a as [|a L IHL R IHR].\n    - simpl. reflexivity.\n    - unfold tree_serialize_subtree.\n      rewrite app_ass, app_ass.\n      simpl. *)\n\n\n  Theorem tree_deser_ser_identity: forall t : tree, forall bools: list bool,\n    (tree_deserialize ((tree_serialize t) ++ bools)) = Some (t, bools).\n  Proof.\n    intros.\n    unfold tree_deserialize, tree_serialize.\n    rewrite app_ass.\n    rewrite nat_deser_ser_identity.\n    rewrite (plus_n_O (tree_size t)).\n    rewrite tree_deser_ser_impl.\n    simpl.\n    reflexivity.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Global Instance TreeSerializer : Serializer (tree).\n  Proof.\n  exact {| serialize := tree_serialize;\n           deserialize := tree_deserialize;\n           deser_ser_identity := tree_deser_ser_identity;\n         |}.\n  Defined.\nEnd TreeSerializer.\n\n(*Definition test_tree (t : tree nat) : Prop :=\n  Some (t, []) = tree_deserialize (tree_serialize t).*)\nCheck tree nat.\nEval compute in deserialize (serialize \n  (stem nat 1 \n    (stem nat 2 (stem nat 3 (leaf nat) (stem nat 4 (leaf nat) (leaf nat))) (leaf nat)) (leaf nat))) : option (tree nat * list bool).\n\nEval compute in deserialize (serialize (stem nat 2 (stem nat 3 (leaf nat) (stem nat 4 (leaf nat) (leaf nat))) (leaf nat))) : option (tree nat * list bool).\n\nEval compute in deserialize (serialize (stem nat 0 (leaf nat) (leaf nat))) : option (tree nat * list bool).\n\nEval compute in deserialize (serialize (leaf nat)) : option (tree nat * list bool).\n\nEval compute in deserialize (serialize (true, Z)): option ((bool* Binary) * list bool).\n\n", "meta": {"author": "pensono", "repo": "Ethan-Cheerios", "sha": "f214e92e02bbeebd93c06c44efd73782325a44fa", "save_path": "github-repos/coq/pensono-Ethan-Cheerios", "path": "github-repos/coq/pensono-Ethan-Cheerios/Ethan-Cheerios-f214e92e02bbeebd93c06c44efd73782325a44fa/cheerios.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6998666634471102}}
{"text": "(*|\n###############################################################################################\nPattern-match on type in order to implement equality for existentially typed constructor in Coq\n###############################################################################################\n\n:Link: https://stackoverflow.com/q/42140009\n|*)\n\n(*|\nQuestion\n********\n\nLet's say I have again a small problem with my datatype with an\nexistential quantified component. This time I want to define when two\nvalues of type ``ext`` are equal.\n|*)\n\nInductive ext (A : Set) :=\n| ext_ : forall (X : Set), option X -> ext A.\n\nFail Definition ext_eq (A : Set) (x y : ext A) : Prop :=\n  match x with\n  | ext_ _ ox => match y with\n                 | ext_ _ oy => (* only when they have the same types *)\n                     ox = oy\n                 end\n  end.\n\n(*|\nWhat I'd like to do is somehow distinguish between the cases where the\nexistential type is actually same and where it's not. Is this a case\nfor ``JMeq`` or is there some other way to accomplish such a case\ndistinction?\n\nI googled a lot, but unfortunately I mostly stumbled upon posts about\ndependent pattern matching.\n\nI also tried to generate a (boolean) scheme with ``Scheme Equality for\next``, but this wasn't successful because of the type argument.\n|*)\n\n(*|\nAnswer\n******\n\n    What I'd like to do is somehow distinguish between the cases where\n    the existential type is actually same and where it's not.\n\nThis is not possible as Coq's logic is compatible with the univalence\naxiom which says that isomorphic types are equal. So even though\n``(unit * unit)`` and ``unit`` are syntactically distinct, they cannot\nbe distinguished by Coq's logic.\n\nA possible work-around is to have a datatype of codes for the types\nyou are interested in and store that as an existential. Something like\nthis:\n|*)\n\nReset Initial. (* .none *)\nInductive Code : Type :=\n| Nat : Code\n| List : Code -> Code.\n\nFixpoint meaning (c : Code) :=\n  match c with\n  | Nat     => nat\n  | List c' => list (meaning c')\n  end.\n\nInductive ext (A : Set) :=\n| ext_ : forall (c : Code), option (meaning c) -> ext A.\n\nLemma Code_eq_dec : forall (c d : Code), {c = d} + {c <> d}.\nProof.\n  intros c. induction c; intros d; destruct d.\n  - left. reflexivity.\n  - right. inversion 1.\n  - right. inversion 1.\n  - destruct (IHc d).\n    + left. congruence.\n    + right. inversion 1. contradiction.\nDefined.\n\nDefinition ext_eq (A : Set) (x y : ext A) : Prop.\n  refine (match x with\n          | @ext_ _ c ox =>\n              match y with\n              | @ext_ _ d oy =>\n                  match Code_eq_dec c d with\n                  | left eq   => _\n                  | right neq => False\n                  end end end).\n  subst. exact (ox = oy).\nDefined.\n\n(*|\nHowever this obviously limits quite a lot the sort of types you can\npack in an ``ext``. Other, more powerful, languages (e.g. equipped\nwith `Induction-recursion\n<https://en.wikipedia.org/wiki/Induction-recursion>`__) would give you\nmore expressive power.\n\n----\n\n**A:** Nice workaround! Let me add a couple comments: (1)\n``Code_eq_dec`` can be *literally* defined using the ``decide\nequality`` tactic, which will really shine when we start adding more\ndata constructors into ``Code``; (2) ``ext_`` can be destructed using\nthe ``let`` expression (since it has only one constructor), which\nmakes the code a bit more concise: ``let (c,ox) := x in ...``\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/pattern-match-on-type-in-order-to-implement-equality-for-existentially-typed-con.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.6998666525064636}}
{"text": "(** Formal Reasoning About Programs <http://adam.chlipala.net/frap/>\n  * Supplementary Coq material: unification and logic programming\n  * Author: Adam Chlipala\n  * License: https://creativecommons.org/licenses/by-nc-nd/4.0/\n  * Much of the material comes from CPDT <http://adam.chlipala.net/cpdt/> by the same author. *)\n\nRequire Import Frap.\n\nSet Implicit Arguments.\n\n\n(** * Introducing Logic Programming *)\n\n(* Recall the definition of addition from the standard library. *)\n\nDefinition real_plus := Eval compute in plus.\nPrint real_plus.\n\n(* Alternatively, we can define it as a relation. *)\n\nInductive plusR : nat -> nat -> nat -> Prop :=\n| PlusO : forall m, plusR O m m\n| PlusS : forall n m r, plusR n m r\n  -> plusR (S n) m (S r).\n\n(* Let's prove the correspondence. *)\n\nTheorem plusR_plus : forall n m r,\n  plusR n m r\n  -> r = n + m.\nProof.\nAdmitted.\n\nTheorem plus_plusR : forall n m,\n  plusR n m (n + m).\nProof.\nAdmitted.\n\nExample four_plus_three : 4 + 3 = 7.\nProof.\n  reflexivity.\nQed.\n\nPrint four_plus_three.\n\nExample four_plus_three' : plusR 4 3 7.\nProof.\nAdmitted.\n\nPrint four_plus_three'.\n\nExample five_plus_three : plusR 5 3 8.\nProof.\nAdmitted.\n\n(* Demonstrating _backtracking_ *)\nExample seven_minus_three : exists x, x + 3 = 7.\nProof.\n  apply ex_intro with 0.\nAbort.\n\nExample seven_minus_three' : exists x, plusR x 3 7.\nProof.\nAdmitted.\n\n(* Backwards! *)\nExample seven_minus_four' : exists x, plusR 4 x 7.\nProof.\nAdmitted.\n\nExample seven_minus_three'' : exists x, x + 3 = 7.\nProof.\nAdmitted.\n\nExample seven_minus_four : exists x, 4 + x = 7.\nProof.\nAdmitted.\n\nExample seven_minus_four_zero : exists x, 4 + x + 0 = 7.\nProof.\nAdmitted.\n\nCheck eq_trans.\n\nSection slow.\n  Hint Resolve eq_trans.\n\n  Example zero_minus_one : exists x, 1 + x = 0.\n    Time eauto 1.\n    Time eauto 2.\n    Time eauto 3.\n    Time eauto 4.\n    Time eauto 5.\n\n    debug eauto 3.\n  Abort.\nEnd slow.\n\nExample from_one_to_zero : exists x, 1 + x = 0.\nProof.\nAdmitted.\n\nExample seven_minus_three_again : exists x, x + 3 = 7.\nProof.\nAdmitted.\n\nExample needs_trans : forall x y, 1 + x = y\n  -> y = 2\n  -> exists z, z + x = 3.\nProof.\nAdmitted.\n\n\n(** * Searching for Underconstrained Values *)\n\nPrint Datatypes.length.\n\nExample length_1_2 : length (1 :: 2 :: nil) = 2.\nProof.\nAdmitted.\n\nPrint length_1_2.\n\nExample length_is_2 : exists ls : list nat, length ls = 2.\nProof.\nAbort.\n\nPrint Forall.\n\nExample length_is_2 : exists ls : list nat, length ls = 2\n  /\\ Forall (fun n => n >= 1) ls.\nProof.\nAdmitted.\n\nPrint length_is_2.\n\nDefinition sum := fold_right plus O.\n\nExample length_and_sum : exists ls : list nat, length ls = 2\n  /\\ sum ls = O.\nProof.\nAdmitted.\n\nPrint length_and_sum.\n\nExample length_and_sum' : exists ls : list nat, length ls = 5\n  /\\ sum ls = 42.\nProof.\nAdmitted.\n\nPrint length_and_sum'.\n\nExample length_and_sum'' : exists ls : list nat, length ls = 2\n  /\\ sum ls = 3\n  /\\ Forall (fun n => n <> 0) ls.\nProof.\nAdmitted.\n\nPrint length_and_sum''.\n\n\n(** * Synthesizing Programs *)\n\nInductive exp : Set :=\n| Const (n : nat)\n| Var\n| Plus (e1 e2 : exp).\n\nInductive eval (var : nat) : exp -> nat -> Prop :=\n| EvalConst : forall n, eval var (Const n) n\n| EvalVar : eval var Var var\n| EvalPlus : forall e1 e2 n1 n2, eval var e1 n1\n  -> eval var e2 n2\n  -> eval var (Plus e1 e2) (n1 + n2).\n\nHint Constructors eval.\n\nExample eval1 : forall var, eval var (Plus Var (Plus (Const 8) Var)) (var + (8 + var)).\nProof.\n  auto.\nQed.\n\nExample eval1' : forall var, eval var (Plus Var (Plus (Const 8) Var)) (2 * var + 8).\nProof.\n  eauto.\nAbort.\n\nExample eval1' : forall var, eval var (Plus Var (Plus (Const 8) Var)) (2 * var + 8).\nProof.\nAdmitted.\n\nExample synthesize1 : exists e, forall var, eval var e (var + 7).\nProof.\nAdmitted.\n\nPrint synthesize1.\n\n(* Here are two more examples showing off our program-synthesis abilities. *)\n\nExample synthesize2 : exists e, forall var, eval var e (2 * var + 8).\nProof.\nAdmitted.\n\nPrint synthesize2.\n\nExample synthesize3 : exists e, forall var, eval var e (3 * var + 42).\nProof.\nAdmitted.\n\nPrint synthesize3.\n\nTheorem linear : forall e, exists k n,\n  forall var, eval var e (k * var + n).\nProof.\nAdmitted.\n\nSection side_effect_sideshow.\n  Variable A : Set.\n  Variables P Q : A -> Prop.\n  Variable x : A.\n\n  Hypothesis Px : P x.\n  Hypothesis Qx : Q x.\n\n  Theorem double_threat : exists y, P y /\\ Q y.\n  Proof.\n    eexists; propositional.\n    eauto.\n    eauto.\n  Qed.\nEnd side_effect_sideshow.\n\n\n(** * More on [auto] Hints *)\n\nTheorem bool_neq : true <> false.\nProof.\nAdmitted.\n\nSection forall_and.\n  Variable A : Set.\n  Variables P Q : A -> Prop.\n\n  Hypothesis both : forall x, P x /\\ Q x.\n\n  Theorem forall_and : forall z, P z.\n  Proof.\n  Admitted.\nEnd forall_and.\n\n\n(** * Rewrite Hints *)\n\nSection autorewrite.\n  Variable A : Set.\n  Variable f : A -> A.\n\n  Hypothesis f_f : forall x, f (f x) = f x.\n\n  Hint Rewrite f_f.\n\n  Lemma f_f_f : forall x, f (f (f x)) = f x.\n  Proof.\n    intros; autorewrite with core; reflexivity.\n  Qed.\n\n  Section garden_path.\n    Variable g : A -> A.\n    Hypothesis f_g : forall x, f x = g x.\n    Hint Rewrite f_g.\n\n    Lemma f_f_f' : forall x, f (f (f x)) = f x.\n    Proof.\n    Admitted.\n  End garden_path.\n\n  Lemma in_star : forall x y, f (f (f (f x))) = f (f y)\n    -> f x = f (f (f y)).\n  Proof.\n  Admitted.\n\nEnd autorewrite.\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/LogicProgramming_template.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6998666409048412}}
{"text": "Require Import Coq.Lists.ListSet.\n\nRequire Import Listkit.Sets.\n\nDefinition monomorphism A B (f:A->B) : Prop := (forall x y, f x = f y -> x = y).\n\nLemma map_monomorphism:\n  forall A B eq_dec X (f:A-> B) (x:A),\n    (monomorphism _ _ f) ->\n    (set_In x X <-> set_In (f x) (set_map eq_dec f X)).\nProof.\n unfold monomorphism.\n induction X; simpl; intros.\n  split; auto.\n split; intros.\n  destruct H0.\n   subst a.\n   apply set_add_intro.\n   auto.\n  apply set_add_intro.\n  right.\n  apply set_map_intro; auto.\n apply set_add_elim in H0.\n intuition.\n right.\n apply <- IHX; eauto.\nQed.\n", "meta": {"author": "ezrakilty", "repo": "sn-stlc-de-bruijn-coq", "sha": "08f9d7b79afde319304426fb3f82559942f51591", "save_path": "github-repos/coq/ezrakilty-sn-stlc-de-bruijn-coq", "path": "github-repos/coq/ezrakilty-sn-stlc-de-bruijn-coq/sn-stlc-de-bruijn-coq-08f9d7b79afde319304426fb3f82559942f51591/Monomorphism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705732, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6998587939441667}}
{"text": "\nFrom Undecidability.Shared Require Import FinitenessFacts.\nRequire Import List.\n\nDefinition total {X Y} (R : X -> Y -> Prop) :=\n  forall x, exists y, R x y.\n\nLemma Forall2_total {X} {Y} (R : X -> Y -> Prop) L :\n  (forall x, In x L -> exists y, R x y) -> exists L', Forall2 R L L'.\nProof.\n  intros HP. induction L.\n  - exists nil. econstructor.\n  - destruct (HP a) as [b H]. 1:firstorder.\n    destruct IHL as [L2' IH].\n    + eauto.\n    + exists (b :: L2'). econstructor; eauto.\nQed.\n\nLemma finite_choice_list {X Y} (R : X -> Y -> Prop) L (y0 : Y) :\n  (forall x1 x2 : X, {x1 = x2} + {x1 <> x2}) ->\n  (forall x, In x L -> exists y, R x y) -> \n  exists f, forall x, In x L -> R x (f x).\nProof.\n  intros D Htot.\n  induction L as [ | x L].\n  - exists (fun _ => y0). firstorder.\n  - destruct IHL as [f Hf].\n    + eauto.\n    + destruct (Htot x) as [y Hy]; [ auto | ].\n      exists (fun x' => if D x x' then y else f x').\n      intros x0 [-> | H].\n      * destruct (D x0 x0); tauto.\n      * destruct (D x x0) as [-> | Hx]; auto.\nQed.     \n\nLemma finite_choice_precond {X Y} (R : X -> Y -> Prop) (p : X -> Prop) (y0 : Y) :\n  listable p ->\n  (forall x1 x2 : X, {x1 = x2} + {x1 <> x2}) ->\n  (forall x, p x -> exists y, R x y) -> \n  exists f, forall x, p x -> R x (f x).\nProof.\n  intros [L HL]. red in HL. setoid_rewrite HL.\n  eapply finite_choice_list. exact y0.\nQed.\n\nLemma finite_choice {X Y} (R : X -> Y -> Prop) :\n  finiteᵗ X ->\n  (forall x1 x2 : X, {x1 = x2} + {x1 <> x2}) ->\n  (forall x, exists y, R x y) -> \n  exists f, forall x, R x (f x).\nProof.\n  intros [L HL] D Htot.\n  destruct L as [ | x0].\n  - unshelve eexists; intros; exfalso; firstorder.\n  - destruct (Htot x0) as [y0 _]. revert HL. generalize (x0 :: L). clear L x0. intros L HL.\n    destruct (@finite_choice_list _ _ R L y0) as [f Hf].\n    + exact D.\n    + firstorder.\n    + exists f. intros. now apply Hf.\nQed.", "meta": {"author": "uds-psl", "repo": "coq-synthetic-computability", "sha": "dc6eaeef99c76f4ff2903b8c07e2928622ee36ba", "save_path": "github-repos/coq/uds-psl-coq-synthetic-computability", "path": "github-repos/coq/uds-psl-coq-synthetic-computability/coq-synthetic-computability-dc6eaeef99c76f4ff2903b8c07e2928622ee36ba/Shared/FinChoice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.793105953629227, "lm_q1q2_score": 0.69985878717664}}
{"text": "(*COLLINET Noah Groupe C*)\n\n\nRequire Export Classical.\n(* exercice 1 *)\nParameter T : Set.\nParameters P Q : T -> Prop.\n\nGoal (exists x: T, P(x)) /\\ (forall x: T, P(x)-> Q(x)) -> (exists x: T, Q(x)).\nintros.\nelim H.\nintros.\nelim H0.\nintros.\nexists x.\napply H1.\nassumption.\nQed.\n\n\nGoal (exists x: T, P(x) /\\ Q(x)) -> (exists x: T, P(x) -> Q(x)).\nintros.\nelim H.\nintros.\nexists x.\nintros.\napply H0.\nQed.\n\n\n(* exercice 2 *)\nParameter R : Set .\nParameters zero one : R.\nParameter opp : R -> R.\nParameters plus mult : R -> R -> R.\n\nSection Commutative_ring .\n\nVariables a b c : R.\n\nAxiom ass_plus : plus ( plus a b ) c = plus a ( plus b c ).\nAxiom com_plus : plus a b = plus b a.\nAxiom com_mult : mult a b = mult b a.\nAxiom ass_mult : mult ( mult a b ) c = mult a ( mult b c ).\nAxiom dis_left : mult a ( plus b c ) = plus ( mult a b ) ( mult a c ).\nAxiom dis_right : mult ( plus b c ) a = plus ( mult b a ) ( mult c a ).\nAxiom neu_plus_r : plus a zero = a.\nAxiom neu_plus_l : plus zero a = a.\nAxiom neu_mult_r : mult a one = a.\nAxiom neu_mult_l : mult one a = a.\nAxiom opp_right : plus a ( opp a ) = zero.\nAxiom opp_left : plus ( opp a ) a = zero.\n\nEnd Commutative_ring .\n\nLemma num1: forall a b : R, (mult (plus a b)( plus one one) ) = (plus b (plus a (plus b a))).\nintros.\nrewrite dis_left.\nrewrite dis_right.\nrewrite neu_mult_r.\nrewrite neu_mult_r.\nrewrite (com_plus b a).\nrewrite <-(ass_plus b a (plus a b)).\nrewrite (com_plus b a).\nreflexivity.\nQed.\n\n\n(* exercice 3 *)\nRequire Export List.\nOpen Scope list_scope.\nImport List Notations.\n\nInductive is_length: list nat -> nat -> Prop :=\n| is_length_nil : is_length nil 0\n| is_length_cons : forall( n e : nat ) ( l : list nat ),\nis_length l n -> is_length ( e::l ) ( S n ).\n\nFixpoint length ( l : list nat ) {struct l} : nat :=\nmatch l with\n| nil => 0\n| e :: q => S ( length q )\nend .\n\nTheorem first : forall l : list nat, forall n : nat, (length l) = n -> (is_length l n).\ninduction l.\nintros.\nrewrite <- H.\nsimpl.\napply is_length_nil.\n\nintros.\nrewrite <- H.\nsimpl.\napply is_length_cons.\napply IHl.\nreflexivity.\nQed.\n\n\n\n\n\n\n", "meta": {"author": "NoahCollinet", "repo": "Verification", "sha": "12c72bb3dc7114f5418475bca83724c798895d29", "save_path": "github-repos/coq/NoahCollinet-Verification", "path": "github-repos/coq/NoahCollinet-Verification/Verification-12c72bb3dc7114f5418475bca83724c798895d29/CC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.6998176880208328}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Omega Wellfounded.\n\nSet Implicit Arguments.\n\nTheorem measure_rect X (m : X -> nat) (P : X -> Type) :\n      (forall x, (forall y, m y < m x -> P y) -> P x) -> forall x, P x.\nProof. \n  apply well_founded_induction_type, wf_inverse_image, lt_wf.\nQed.\n\nSection list_snoc_ind.\n\n  Variable (X : Type) (P : list X -> Type)\n           (HP0 : P nil) (HP1 : forall x l, P l -> P (l++x::nil)).\n           \n  Theorem list_snoc_ind : forall l, P l.\n  Proof.\n    intros l.\n    rewrite <- (rev_involutive l).\n    generalize (rev l); clear l; intros l.\n    induction l as [ | x l IHl ].\n    apply HP0.\n    simpl; apply HP1; auto.\n  Qed.\n  \nEnd list_snoc_ind.\n\nFact list_snoc_inv X l m (x y : X) : l++x::nil = m++y::nil -> l = m /\\ x = y.\nProof.\n  intros H.\n  apply f_equal with (f := @rev _) in H.\n  do 2 rewrite rev_app_distr in H; simpl in H.\n  inversion H; subst.\n  rewrite <- (rev_involutive l), H2, rev_involutive; auto.\nQed.\n\nFact list_snoc_destruct X l : { x : X & { m | l = m++x::nil } } + { l = nil }.\nProof.\n  induction l  as [ | x l _ ] using list_snoc_ind.\n  * right; auto.\n  * left; exists x, l; auto.\nQed.\n\nDefinition app_split X (l1 : list X) : forall l2 r1 r2, l1++r1 = l2++r2\n                                      -> { m | l2 = l1++m /\\ r1 = m++r2 }\n                                       + { m | l1 = l2++m /\\ r2 = m++r1 }.\nProof.\n  induction l1 as [ | x l1 Hl1 ].\n  left; exists l2; auto.\n  intros [ | y l2 ] r1 r2 H.\n  right; exists (x::l1); auto.\n  simpl in H; injection H; clear H; intros H ?; subst.\n  apply Hl1 in H.\n  destruct H as [ (m & H1 & H2) | (m & H1 & H2) ].\n  left; exists m; subst; auto.\n  right; exists m; subst; auto.\nQed.\n\nFact list_split_first_half U (ll : list U) x : x <= length ll -> { l : _ & { r | ll = l++r /\\ length l = x } }.\nProof.\n  revert ll; induction x as [ | x IHx ]; intros [ | u ll ] Hx.\n  exists nil, nil; simpl; auto.\n  exists nil, (u::ll); auto.\n  simpl in Hx; omega.\n  destruct (IHx ll) as (l & r & H1 & H2).\n  simpl in Hx; omega.\n  exists (u::l), r; simpl; split; f_equal; auto.\nQed.\n    \nFact list_split_second_half U (ll : list U) x : x <= length ll -> { l : _ & { r | ll = l++r /\\ length r = x } }.\nProof.\n  intros Hx.\n  destruct list_split_first_half with (ll := ll) (x := length ll - x)\n    as (l & r & H1 & H2).\n  omega.\n  exists l, r; split; auto.\n  apply f_equal with (f := @length _) in H1.\n  rewrite app_length in H1.\n  omega.\nQed.  \n\nSection Forall.\n\n  Variables (X : Type) (P : X -> Prop).\n\n  Fact Forall_app ll mm : Forall P (ll++mm) <-> Forall P ll /\\ Forall P mm.\n  Proof.\n    split.\n    induction ll as [ | x ll ]; split; auto.\n    constructor;\n    inversion H; auto.\n    apply IHll; auto.\n    inversion H; apply IHll; auto.\n    intros (H1 & H2).\n    induction H1; simpl; auto; constructor; auto.\n  Qed.\n\n  Fact Forall_cons_inv x ll : Forall P (x::ll) <-> P x /\\ Forall P ll.\n  Proof.\n    split.\n    inversion_clear 1; auto.\n    constructor; tauto.\n  Qed.\n  \n  Hypothesis P_dec : forall x, P x \\/ ~ P x.\n  \n  Fact Forall_l_dec l : Forall P l \\/ ~ Forall P l.\n  Proof.\n    induction l as [ | x l [ IHl | IHl ] ].\n    + left; auto.\n    + destruct (P_dec x) as [ H | H ].\n      * left; constructor; auto.\n      * right; contradict H; rewrite Forall_cons_inv in H; tauto.\n    + right; contradict IHl; rewrite Forall_cons_inv in IHl; tauto.\n  Qed.\n  \n  Fact Exists_l_dec l : (exists x, In x l /\\ P x) \\/ forall x, In x l -> ~ P x.\n  Proof.\n    induction l as [ | x l [ (y & H1 & H2) | IHl ] ].\n    + right; simpl; tauto.\n    + left; exists y; simpl; auto.\n    + destruct (P_dec x) as [ H | H ].\n      * left; exists x; simpl; auto.\n      * right; intros ? [|]; subst; auto.\n  Qed.\n\nEnd Forall.\n\n\n\n", "meta": {"author": "DmxLarchey", "repo": "Ramsey", "sha": "24510f63d4290149c4944fe68267d342345621ed", "save_path": "github-repos/coq/DmxLarchey-Ramsey", "path": "github-repos/coq/DmxLarchey-Ramsey/Ramsey-24510f63d4290149c4944fe68267d342345621ed/src/utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.6998176863720758}}
{"text": "Require Import Nat.\nRequire Import List.\nImport ListNotations.\nRequire Import Relations.\n(** MTrees are the trees we pickle into\n *)\nInductive Ntree : Type := NLeaf: nat -> Ntree | NBranch:  nat -> list Ntree -> Ntree.\n\nSection correct_ntree_ind.\n\nVariables\n  (A : Set)(P : Ntree -> Prop).\nHypotheses\n  (H : forall (a:nat)(l:list (Ntree)), (forall x, In x l -> P x) -> P (NBranch a l))\n  \n (H1 : forall t:Ntree, P t -> forall l:list (Ntree), (forall x, In x l -> P x) -> (forall x, In x (cons t l) -> P x))\n (H2: forall (n: nat), P(NLeaf n)).\nLemma  H0: forall x, In x [] -> P x.\n  intros x H4.  destruct H4.\n  Qed. \nFixpoint ntree_ind2 (t:Ntree) : P t :=\n  match t as x return P x with\n  | NBranch a l =>\n      H a l\n        (((fix l_ind (l':list (Ntree)) : (forall x, In x l' -> P x) :=\n             match l' as x return forall y, In y x -> P y with\n             | nil => H0\n             | cons t1 tl => H1 t1 (ntree_ind2 t1) tl (l_ind tl)\n             end)) l)\n  | NLeaf x => H2 x\n  end.\n\nEnd correct_ntree_ind.\nRequire Import PeanoNat. \nDefinition list_eq (A: Type) (f: A -> A -> bool) (l1 l2: list A) :=\n  let fll := fix gh (l1 l2:list A) :=\n                 match (l1, l2) with\n                   (nil ,nil) => true\n                 | (a::xr1, b::xr2) => if f a b then gh xr1 xr2 else false \n                 | _ => false end\n             in fll l1 l2.\nFixpoint ntree_eq_dec (n1 n2: Ntree) : bool :=\n  match (n1, n2) with\n    (NLeaf a ,NLeaf b) => if Nat.eq_dec a b then true else false\n  | (NBranch a xr1, NBranch b xr2) => if Nat.eq_dec a b then list_eq Ntree ntree_eq_dec xr1 xr2 else false \n  | _ => false end.\n\n(**\n   Note: I know that this proof is quite ugly, sorry :-(\n **)\nDefinition ntree_equal_dec_lemma: forall (x1 x2: Ntree), x1 = x2 <-> (ntree_eq_dec x1 x2) = true . \nProof.\n  intro.\n  induction x1 using ntree_ind2.\n  - intro x2. destruct x2.\n    split.\n    + intro. congruence.\n    + intro.   simpl ntree_eq_dec in H1.  congruence.\n    + split.\n      intro.\n      inversion H1.\n      simpl ntree_eq_dec.\n      destruct (Nat.eq_dec n n). subst l0. induction l. simpl.  reflexivity.\n      simpl list_eq. enough (ntree_eq_dec a0 a0 = true).\n      rewrite H2. apply IHl. intros x H4. apply H. right. assumption.\n      rewrite H3.\n      reflexivity.\n      apply H.\n      left. auto.\n      reflexivity.\n      congruence.\n      intro H1.\n      simpl ntree_eq_dec in H1.\n      destruct (Nat.eq_dec a n).\n      enough (l = l0).\n      subst a.  subst l. reflexivity.\n      assert (forall (l' l'': list Ntree), (forall x, In x l' -> In x l) -> list_eq Ntree ntree_eq_dec l' l'' = true <-> l' = l'').\n      intro l'.\n      induction l'.\n      *  intro l''. intro Hx. destruct l''. firstorder eauto.\n         split. intro. simpl list_eq in H2.  congruence.  intro. inversion H2.\n      *  intros l'' H2. split.\n         destruct l''.\n         intro. simpl in  H3.  congruence. \n         intro. assert (l' = l'').\n         apply IHl'. intros. apply H2. right. auto.\n         simpl in  H3. destruct (ntree_eq_dec a0 n0). auto.  congruence.\n         assert (a0 = n0).  apply H.  apply H2.  left. auto.\n         simpl in H3. destruct ( ntree_eq_dec a0 n0). reflexivity. congruence.  rewrite H4.  rewrite H5.\n         reflexivity.\n         destruct l''. \n         intro. congruence.\n         intro.\n         simpl list_eq.\n         inversion H3.\n         enough((ntree_eq_dec n0 n0) = true).\n         rewrite H4.\n         inversion H3.  rewrite<- H6.\n         apply IHl'. intros x H10. apply H2. right. auto.\n         reflexivity.\n         apply H. rewrite<- H5.\n         apply H2. left. auto.\n         reflexivity.\n      *   apply H2.   intro. auto.\n          auto.\n      *      congruence.\n  -    intro.       destruct H1.\n       subst x1_2.\n       apply IHx1_1.\n       apply H.  auto.\n  -  intro.\n     destruct x2.\n     + split.\n       intro.\n       inversion H.\n       simpl ntree_eq_dec.  destruct (Nat.eq_dec n0 n0).  reflexivity.\n       congruence.\n       simpl ntree_eq_dec. destruct (Nat.eq_dec n n0). subst n. firstorder eauto.\n       intro. congruence.\n     +  split. intro. congruence.\n        intro. simpl ntree_eq_dec in H. congruence.\nDefined.\n\n(** \n  * We can embed Ltrees / Gentrees (Ltrees are just gentrees with nat as a type)\n  * into lists of (nat * nat) + nat.\n  * The proofs of this equivalence are based on proofs from the stdpp library.\n  *)\nDefinition flatten {A: Type} (l: list (list A)) : list A :=\n  List.fold_right (@app A) [] l. \n\nFixpoint ntree_to_list (t : Ntree ) : list ((nat *  nat) + nat) :=\n  match t with\n  | NLeaf x => [inr x]\n  | NBranch n ts =>  (flatten (List.map ntree_to_list ts )) ++ [ @inl (nat*nat) nat (length ts, n) ]\n  end.\n\nFixpoint ntree_of_list \n    (k : list (Ntree)) (l : list (nat * nat + nat)) : option (Ntree) :=\n  match l with\n  | [] => head k\n  | inr x :: l => ntree_of_list (NLeaf x :: k) l\n  | inl (len,n) :: l =>\n     ntree_of_list (NBranch n (rev' (firstn len k)) :: skipn len k) l\n  end.\n\nTactic Notation \"trans\" constr(A) := transitivity A.\n\nAbout \"::\". \n\nLemma take_app_alt {A: Type} (l: list A) k :  firstn (length l) (l ++ k) = l.\nProof.\n  induction l. \n  - reflexivity. \n  - simpl firstn.  rewrite IHl. reflexivity.\nQed.\n\nLemma drop_app_alt {A: Type} (l: list A) k :  skipn (length l) (l ++ k) = k.\nProof.\n  induction l. \n  - reflexivity. \n  - simpl skipn.  rewrite IHl. reflexivity.\nQed.\nPrint rev.\n\nLemma ntree_of_to_list k l (t : Ntree) :\n  ntree_of_list k (ntree_to_list t ++ l) = ntree_of_list (t :: k) l.\nProof.\n  revert t k l. fix FIX 1. intros [|n ts] k l; simpl; auto.\n    trans (ntree_of_list (rev' ts ++ k) ([inl (length ts, n)] ++ l)).\n  -   rewrite<- app_assoc. revert k. generalize ([inl (length ts, n)] ++ l).\n      induction ts as [|t ts'' IH]; intros k ts'''; simpl; auto.\n      unfold rev. simpl rev_append.   rewrite<- app_assoc.  rewrite FIX. rewrite IH.\n      unfold rev' at 2. simpl rev_append. rewrite rev_append_rev. rewrite<- app_assoc. simpl app at 3.  repeat rewrite<- app_assoc.  unfold rev'. \n     rewrite rev_append_rev. rewrite app_nil_r . reflexivity.\n  -  simpl.\n     enough ((length ts) = length (rev' ts)).\n     rewrite H. \n     rewrite take_app_alt.\n     rewrite drop_app_alt.\n     unfold rev'. \n     rewrite rev_append_rev.\n     rewrite<- rev_alt. \n     rewrite rev_involutive. \n     enough (ts++[] = ts).\n     rewrite H1.\n     reflexivity.\n     induction ts. simpl. reflexivity. simpl. rewrite IHts.  reflexivity.\n     unfold rev'. \n     rewrite rev_append_rev.\n     enough ((rev ts)++[] = rev ts).\n     rewrite H1.\n     symmetry. apply rev_length.\n     induction (rev ts). simpl. reflexivity. simpl. rewrite IHl0.  reflexivity.\n     symmetry. unfold rev'. \n     rewrite rev_append_rev. rewrite app_nil_r .  apply rev_length.\nQed.\n\n\nRequire Import List.\nImport ListNotations.\n\nDefinition cumulative {X} (L: nat -> list X) :=\n  forall n, exists A, L (S n) = L n ++ A.\nHint Extern 0 (cumulative _) => intros ?; cbn; eauto : core.\n\nLemma cum_ge {X} {L: nat -> list X} {n m} :\n  cumulative L -> m >= n -> exists A, L m = L n ++ A.\nProof.\n  induction 2 as [|m _ IH].\n  - exists nil. now rewrite app_nil_r.\n  - destruct (H m) as (A&->), IH as [B ->].\n    exists (B ++ A). now rewrite app_assoc.\nQed.\n\nLemma cum_ge' {X} {L: nat -> list X} {x n m} :\n  cumulative L -> In x (L n) -> m >= n -> In x (L m).\nProof.\n  intros ? H [A ->] % (cum_ge (L := L)). apply in_app_iff. eauto. eauto.\nQed.\n\nDefinition list_enumerator {X} (L: nat -> list X) (p : X -> Prop) :=\n  forall x, p x <-> exists m, In x (L m).\nDefinition list_enumerable {X} (p : X -> Prop) :=\n  exists L, list_enumerator L p.\n\nDefinition list_enumerator__T' X f := forall x : X, exists n : nat, In x (f n).\nNotation list_enumerator__T f X := (list_enumerator__T' X f).\nDefinition list_enumerable__T X := exists f : nat -> list X, list_enumerator__T f X.\nDefinition inf_list_enumerable__T X := { f : nat -> list X | list_enumerator__T f X }.\n\nSection enumerator_list_enumerator.\n  Variable X : Type.\n  Variable p : X -> Prop.\n  Variables (e : nat -> option X).\n\n  Let T (n : nat) : list X :=  match e n with Some x => [x] | None => [] end.\n\n  Lemma enumerator_to_list_enumerator : forall x, (exists n, e n = Some x) <-> (exists n, In x (T n)).\n  Proof.\n    split; intros [n H].\n    - exists n. unfold T. rewrite H. firstorder.\n    - unfold T in *. destruct (e n) eqn:E. inversion H; subst. eauto. destruct H1.  destruct H. \n  Qed.\n\nEnd enumerator_list_enumerator.\n\nDefinition enumerable {X} (p : X -> Prop) := exists f, forall x, p x <-> exists n : nat, f n = Some x.\nDefinition enumerable__T X := exists f : nat -> option X, forall x, exists n, f n = Some x.\n\n\nLemma enumerable_list_enumerable {X} {p : X -> Prop} :\n  enumerable p -> list_enumerable p.\nProof.\n  intros [f Hf]. eexists.\n  unfold list_enumerator.\n  intros x. rewrite <- enumerator_to_list_enumerator.\n  eapply Hf.\nQed.\n\nLemma enumerable__T_list_enumerable {X} :\n  enumerable__T X -> list_enumerable__T X.\nProof.\n  intros [f Hf]. eexists.\n  unfold list_enumerator.\n  intros x. rewrite <- enumerator_to_list_enumerator.\n  eapply Hf.\nQed.\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.\nSection enumerator_list_enumerator.\n\n  Variable X : Type.\n  Variables (T : nat -> list X).\n\n  Let e (n : nat) : option X :=\n    let (n, m) := unembed n in\n    nth_error (T n) m.\n\n  Lemma list_enumerator_to_enumerator : forall x, (exists n, e n = Some x) <-> (exists n, In x (T n)).\n  Proof.\n    split; intros [k H].\n    - unfold e in *.\n      destruct (unembed k) as (n, m).\n      exists n. eapply (nth_error_In _ _ H).\n    - unfold e in *.\n      eapply In_nth_error in H as [m].\n      exists (embed (k, m)). now rewrite embedP, H.\n  Qed.\n\nEnd enumerator_list_enumerator.\n\nDefinition enumerator {X} (f : nat -> option X) (P : X -> Prop) : Prop :=\n\t  forall x, P x <-> exists n, f n = Some x.\n\n\nLemma list_enumerator_enumerator {X} {p : X -> Prop} {T} :\n  list_enumerator T p -> enumerator (fun n => let (n, m) := unembed n in\n    nth_error (T n) m) p.\nProof.\n  unfold list_enumerator.\n  intros H x. rewrite list_enumerator_to_enumerator. eauto.\nQed.\n\nLemma list_enumerable_enumerable {X} {p : X -> Prop} :\n  list_enumerable p -> enumerable p.\nProof.\n  intros [T HT]. eexists.\n  unfold list_enumerator.\n  intros x. rewrite list_enumerator_to_enumerator.\n  eapply HT.\nQed.\n\nLemma list_enumerable__T_enumerable {X} :\n  list_enumerable__T X -> enumerable__T X.\nProof.\n  intros [T HT]. eexists.\n  unfold list_enumerator.\n  intros x. rewrite list_enumerator_to_enumerator.\n  eapply HT.\nQed.\n\nLemma enum_enumT {X} :\n  enumerable__T X <-> list_enumerable__T X.\nProof.\n  split.\n  eapply enumerable__T_list_enumerable.\n  eapply list_enumerable__T_enumerable.\nQed.\n\nDefinition to_cumul {X} (L : nat -> list X) := fix f n :=\n  match n with 0 => [] | S n => f n ++ L n end.\n\nLemma to_cumul_cumulative {X} (L : nat -> list X) :\n  cumulative (to_cumul L).\nProof.\n  eauto.\nQed.\n\nLemma to_cumul_spec {X} (L : nat -> list X) x :\n  (exists n, In x (L n)) <-> exists n, In x (to_cumul L n).\nProof.\n  split.\n  - intros [n H].\n    exists (S n). cbn. eapply in_app_iff. eauto.\n  - intros [n H].\n    induction n; cbn in *.\n    + inversion H.\n    + eapply in_app_iff in H as [H | H]; eauto.\nQed.\n\nLemma cumul_In {X} (L : nat -> list X) x n :\n  In x (L n) -> In x (to_cumul L (S n)).\nProof.\n  intros H. cbn. eapply in_app_iff. eauto.\nQed.\n\nLemma In_cumul {X} (L : nat -> list X) x n :\n  In x (to_cumul L n) -> exists n, In x (L n).\nProof.\n  intros H. eapply to_cumul_spec. eauto.\nQed.\n\nLemma Cumul_Step {X} (L : nat -> list X) x n :\n  forall m, n < m -> In x (L n) -> In x (to_cumul L m).\nProof.\n  intros m. intros E. induction E. firstorder eauto.  apply cumul_In. assumption.\n  intro. simpl to_cumul. apply in_app_iff. left. apply IHE. assumption.\nQed.\n\nHint Resolve cumul_In In_cumul : core.\n\nLemma list_enumerator_to_cumul {X} {p : X -> Prop} {L} :\n  list_enumerator L p -> list_enumerator (to_cumul L) p. \nProof.\n  unfold list_enumerator.\n  intros. rewrite H.\n  eapply to_cumul_spec.\nQed.\n\nLemma cumul_spec__T {X} {L} :\n  list_enumerator__T L X -> list_enumerator__T (to_cumul L) X.\nProof.\n  unfold list_enumerator__T.\n  intros. now rewrite <- to_cumul_spec.\nQed.\n\nLemma cumul_spec {X} {L} {p : X -> Prop} :\n  list_enumerator L p -> list_enumerator (to_cumul L) p.\nProof.\n  unfold list_enumerator.\n  intros. now rewrite <- to_cumul_spec.\nQed.\n\nModule ListAutomationNotations.\n\n  Notation \"x 'el' L\" := (In x L) (at level 70).\n  Notation \"A '<<=' B\" := (incl A B) (at level 70).\n\n  Notation \"( A × B × .. × C )\" := (list_prod .. (list_prod A B) .. C) (at level 0, left associativity).\n\nEnd ListAutomationNotations.\nImport ListAutomationNotations.\n\n\nLtac in_app n :=\n  (match goal with\n  | [ |- In _ (_ ++ _) ] => \n    match n with\n    | 0 => idtac\n    | 1 => eapply in_app_iff; left\n    | S ?n => eapply in_app_iff; right; in_app n\n    end\n  | [ |- In _ (_ :: _) ] => match n with 0 => idtac | 1 => left | S ?n => right; in_app n end\n  end) || (repeat (try right; eapply in_app_iff; right)).\n\n\nRequire Import Lia Arith.\nLocal Set Implicit Arguments.\nLocal Unset Strict Implicit.\n\nHint Extern 4 => \nmatch goal with\n|[ H: ?x el nil |- _ ] => destruct H\nend : core.\n\nHint Extern 4 => \nmatch goal with\n|[ H: False |- _ ] => destruct H\n|[ H: true=false |- _ ] => discriminate H\n|[ H: false=true |- _ ] => discriminate H\nend : core.\nLemma incl_nil X (A : list X) :\n  nil <<= A.\nProof. intros x []. Qed.\n\nHint Rewrite <- app_assoc : list.\nHint Rewrite rev_app_distr map_app prod_length : list.\nHint Resolve in_eq in_nil in_cons in_or_app : core.\nHint Resolve incl_refl incl_tl incl_cons incl_appl incl_appr incl_app incl_nil : core.\n\nLemma app_incl_l X (A B C : list X) :\nA ++ B <<= C -> A <<= C.\nProof.\nfirstorder eauto.\nQed.\n\nLemma app_incl_R X (A B C : list X) :\nA ++ B <<= C -> B <<= C.\nProof.\nfirstorder eauto.\nQed.\n\nLemma cons_incl X (a : X) (A B : list X) : a :: A <<= B -> A <<= B.\nProof.\nintros ? ? ?. eapply H. firstorder.\nQed.\n\nLemma incl_sing X (a : X) A : a el A -> [a] <<= A.\nProof.\nnow intros ? ? [-> | [] ].\nQed.\n\nHint Resolve app_incl_l app_incl_R cons_incl incl_sing : core.\n\nHint Extern 4 (_ el map _ _) => eapply in_map_iff : core.\nHint Extern 4 (_ el filter _ _) => eapply filter_In : core.\n\nSection Inclusion.\n  Variable X : Type.\n  Implicit Types A B : list X.\n\n  Lemma incl_nil_eq A :\n    A <<= nil -> A=nil.\n\n  Proof.\n    intros D. destruct A as [|x A].\n    - reflexivity.\n    - exfalso. apply (D x). auto.\n  Qed.\n\n  Lemma incl_shift x A B :\n    A <<= B -> x::A <<= x::B.\n\n  Proof. auto. Qed.\n\n  Lemma incl_lcons x A B :\n    x::A <<= B <-> x el B /\\ A <<= B.\n  Proof. \n    split. \n    - intros D. split; hnf; auto.\n    - intros [D E] z [F|F]; subst; auto.\n  Qed.\n\n  Lemma incl_rcons x A B :\n    A <<= x::B -> ~ x el A -> A <<= B.\n\n  Proof. intros C D y E. destruct (C y E) as [F|F]; congruence. Qed.\n\n  Lemma incl_lrcons x A B :\n    x::A <<= x::B -> ~ x el A -> A <<= B.\n\n  Proof.\n    intros C D y E.\n    assert (F: y el x::B) by auto.\n    destruct F as [F|F]; congruence.\n  Qed.\n\n  Lemma incl_app_left A B C :\n    A ++ B <<= C -> A <<= C /\\ B <<= C.\n  Proof.\n    firstorder.\n  Qed.\n\nEnd Inclusion.\n\nRequire Import Setoid Morphisms.\n\nInstance incl_preorder X : \n  PreOrder (@incl X).\nProof. \n  constructor; hnf; unfold incl; auto. \nQed.\n\nDefinition equi X (A B : list X) : Prop := incl A B /\\ incl B A.\nLocal Notation \"A === B\" := (equi A B) (at level 70).\nHint Unfold equi : core.\n\nInstance equi_Equivalence X : \n  Equivalence (@equi X).\nProof. \n  constructor; hnf; firstorder. \nQed.\n\nInstance incl_equi_proper X : \n  Proper (@equi X ==> @equi X ==> iff) (@incl X).\nProof. \n  hnf. intros A B D. hnf. firstorder. \nQed.\n\nInstance cons_incl_proper X x : \n  Proper (@incl X ==> @incl X) (@cons X x).\nProof.\n  hnf. apply incl_shift.\nQed.\n\nInstance cons_equi_proper X x : \n  Proper (@equi X ==> @equi X) (@cons X x).\nProof. \n  hnf. firstorder.\nQed.\n\nInstance in_incl_proper X x : \n  Proper (@incl X ==> Basics.impl) (@In X x).\nProof.\n  intros A B D. hnf. auto.\nQed.\n\nInstance in_equi_proper X x : \n  Proper (@equi X ==> iff) (@In X x).\nProof. \n  intros A B D. firstorder. \nQed.\n\nInstance app_incl_proper X : \n  Proper (@incl X ==> @incl X ==> @incl X) (@app X).\nProof. \n  intros A B D A' B' E. auto.\nQed.\n\nInstance app_equi_proper X : \n  Proper (@equi X ==> @equi X ==> @equi X) (@app X).\nProof. \n  hnf. intros A B D. hnf. intros A' B' E.\n  destruct D, E; auto.\nQed. \nNotation cumul := (to_cumul).\n\nLtac inv H := inversion H; subst; clear H.\n\nDefinition dec (X: Prop) : Type := {X} + {~ X}.\n\nCoercion dec2bool P (d: dec P) := if d then true else false.\nDefinition is_true (b : bool) := b = true.\n\nExisting Class dec.\n\nDefinition Dec (X: Prop) (d: dec X) : dec X := d.\nArguments Dec X {d}.\n\nLemma Dec_reflect (X: Prop) (d: dec X) :\n  is_true (Dec X) <-> X.\nProof.\n  destruct d as [A|A]; cbv in *; intuition congruence.\nQed.\n\nLemma Dec_auto (X: Prop) (d: dec X) :\n  X -> is_true (Dec X).\nProof.\n  destruct d as [A|A]; cbn; intuition congruence.\nQed.\n\n(* Lemma Dec_auto_not (X: Prop) (d: dec X) : *)\n(*   ~ X -> ~ Dec X. *)\n(* Proof. *)\n(*   destruct d as [A|A]; cbn; tauto. *)\n(* Qed. *)\n\n(* Hint Resolve Dec_auto Dec_auto_not : core. *)\nHint Extern 4 =>  (* Improves type class inference *)\nmatch goal with\n  | [  |- dec ((fun _ => _) _) ] => cbn\nend : typeclass_instances.\n\nTactic Notation \"decide\" constr(p) := \n  destruct (Dec p).\nTactic Notation \"decide\" constr(p) \"as\" simple_intropattern(i) := \n  destruct (Dec p) as i.\nTactic Notation \"decide\" \"_\" :=\n  destruct (Dec _).\n\nLemma Dec_true P {H : dec P} : dec2bool (Dec P) = true -> P.\nProof.\n  decide P; cbv in *; firstorder.\nQed.\n\nLemma Dec_false P {H : dec P} : dec2bool (Dec P) = false -> ~P.\nProof.\n  decide P; cbv in *; firstorder.\nQed.\n\nHint Extern 4 =>\nmatch goal with\n  [ H : dec2bool (Dec ?P) = true  |- _ ] => apply Dec_true in  H\n| [ H : dec2bool (Dec ?P) = true |- _ ] => apply Dec_false in H\nend : core.\n\n(* Decided propositions behave classically *)\n\nLemma dec_DN X : \n  dec X -> ~~ X -> X.\nProof. \n  unfold dec; tauto. \nQed.\n\nLemma dec_DM_and X Y :  \n  dec X -> dec Y -> ~ (X /\\ Y) -> ~ X \\/ ~ Y.\nProof. \n  unfold dec; tauto. \nQed.\n\nLemma dec_DM_impl X Y :  \n  dec X -> dec Y -> ~ (X -> Y) -> X /\\ ~ Y.\nProof. \n  unfold dec; tauto. \nQed.\n\n(* Propagation rules for decisions *)\n\nFact dec_transfer P Q :\n  P <-> Q -> dec P -> dec Q.\nProof.\n  unfold dec. tauto.\nQed.\n\nInstance True_dec :\n  dec True.\nProof. \n  unfold dec; tauto. \nQed.\n\n\n\nInstance False_dec :\n  dec False.\nProof. \n  unfold dec; tauto. \nQed.\n\nInstance impl_dec (X Y : Prop) :  \n  dec X -> dec Y -> dec (X -> Y).\nProof. \n  unfold dec; tauto. \nQed.\n\nInstance and_dec (X Y : Prop) :  \n  dec X -> dec Y -> dec (X /\\ Y).\nProof. \n  unfold dec; tauto. \nQed.\n\nInstance or_dec (X Y : Prop) : \n  dec X -> dec Y -> dec (X \\/ Y).\nProof. \n  unfold dec; tauto. \nQed.\n\n(* Coq standard modules make \"not\" and \"iff\" opaque for type class inference, \n   can be seen with Print HintDb typeclass_instances. *)\n\nInstance not_dec (X : Prop) : \n  dec X -> dec (~ X).\nProof. \n  unfold not. firstorder eauto.\nQed.\n\nInstance iff_dec (X Y : Prop) : \n  dec X -> dec Y -> dec (X <-> Y).\nProof. \n  unfold iff. firstorder eauto.\nQed.\n\n(* Discrete types *)\n\nNotation \"'eq_dec' X\" := (forall x y : X, dec (x=y)) (at level 70).\n\nStructure eqType := EqType {\n  eqType_X :> Type;\n  eqType_dec : eq_dec eqType_X }.\n\nArguments EqType X {_} : rename.\n\nCanonical Structure eqType_CS X (A: eq_dec X) := EqType X.\n\nExisting Instance eqType_dec.\n\nInstance unit_eq_dec :\n  eq_dec unit.\nProof.\n  unfold dec. decide equality. \nQed.\n\nInstance bool_eq_dec : \n  eq_dec bool.\nProof.\n  unfold dec. decide equality. \nDefined.\n\nInstance nat_eq_dec : \n  eq_dec nat.\nProof.\n  unfold dec. decide equality.\nDefined.\n\nInstance prod_eq_dec X Y :  \n  eq_dec X -> eq_dec Y -> eq_dec (X * Y).\nProof.\n  unfold dec. decide equality. \nDefined.\n\nInstance list_eq_dec X :  \n  eq_dec X -> eq_dec (list X).\nProof.\n  unfold dec. decide equality. \nDefined.\n\n\nInstance sum_eq_dec X Y :  \n  eq_dec X -> eq_dec Y -> eq_dec (X + Y).\nProof.\n  unfold dec. decide equality. \nDefined.\n\nInstance option_eq_dec X :\n  eq_dec X -> eq_dec (option X).\nProof.\n  unfold dec. decide equality.\nDefined.\n\nInstance Empty_set_eq_dec:\n  eq_dec Empty_set.\nProof.\n  unfold dec. decide equality.\nQed.\n\nInstance True_eq_dec:\n  eq_dec True.\nProof.\n  intros x y. destruct x,y. now left.\nQed.\n\nInstance False_eq_dec:\n  eq_dec False.\nProof.\n  intros [].\nQed.\n\n\n  Notation \"[ s | p ∈ A ',' P ]\" :=\n    (map (fun p => s) (filter (fun p => Dec P) A)) (p pattern).\n\nSection L_list_def.\n  Context {X : Type}.\n  Variable (L : nat -> list X).\n  Print cumul.\n  Import ListAutomationNotations.\n  Notation \"( A × B × .. × C )\" := (list_prod .. (list_prod A B) .. C) (at level 0, left associativity).\n  Notation \"[ s | p ∈ A ]\" :=\n    (map (fun p => s) A) (p pattern).\n\n  Fixpoint L_list (n : nat) : list (list X) :=\n\t  match n\n\t  with\n\t  | 0 => [ [] ]\n\t  | S n => L_list n ++ [x :: L | (x,L) ∈ (cumul L n × L_list n)]\n\t  end.\n\t\n  \nEnd L_list_def.\n\nLemma L_list_cumulative {X} L : cumulative (@L_list X L).\nProof.\n  intros ?; cbn; eauto. \nQed.\n\nLtac in_collect a :=\n  eapply in_map_iff; exists a; split; [ eauto | match goal with\n                                              _ => try (rewrite !in_prod_iff; repeat split) end ].\n\n\nLemma enumerator__T_list {X} L :\n  list_enumerator__T L X -> list_enumerator__T (L_list L) (list X).\nProof.\n  intros H l.\n  induction l.\n  - exists 0. cbn. eauto.\n  - destruct IHl as [n IH].\n    destruct (cumul_spec__T H a) as [m ?].\n    exists (1 + n + m). cbn. intros. in_app 2.\n    in_collect (a,l).\n    all: eapply cum_ge'; eauto using L_list_cumulative; lia.\nQed.\n\nSection L_sum_def.\n  Context {X1 X2 : Type}.\n  Variables (L1 : nat -> list X1) (L2: nat -> list X2).\n  Print cumul.\n  Import ListAutomationNotations.\n  Notation \"( A × B × .. × C )\" := (list_prod .. (list_prod A B) .. C) (at level 0, left associativity).\n  Notation \"[ s | p ∈ A ]\" :=\n    (map (fun p => s) A) (p pattern).\n\n  Definition L_sum_list (n : nat) : list (X1+X2) :=\n\t  (List.map inl (L1 n)) ++ (List.map inr (L2 n))\n\t .\n\t\n  \nEnd L_sum_def.\n\n\nLemma enumerator_sum_list {X1 X2} L1 L2 :\n  list_enumerator__T L1 X1 -> list_enumerator__T L2 X2 -> list_enumerator__T (L_sum_list L1 L2) (X1+X2).\nProof.\n  intros H1 H2.\n  intro.\n  destruct x.\n  - destruct (H1 x) as [n1 Hn1]. \n   exists n1.  unfold L_sum_list. rewrite in_app_iff.\n    left. apply in_map_iff. exists x. firstorder eauto.\n  - destruct (H2 x).    unfold L_sum_list. exists x0. rewrite in_app_iff.\n    right. apply in_map_iff.  exists x. split; firstorder eauto.\nQed.\n\n(* Pickles X1 * X2 *)\nSection L_prod_def.\n  Context {X1 X2 : Type}.\n  Variables (L1 : nat -> list X1) (L2: nat -> list X2).\n  Print cumul.\n  Import ListAutomationNotations.\n  Notation \"( A × B × .. × C )\" := (list_prod .. (list_prod A B) .. C) (at level 0, left associativity).\n  Notation \"[ s | p ∈ A ]\" :=\n    (map (fun p => s) A) (p pattern).\n\n  Definition L_prod_list (n : nat) : list (X1*X2) :=\n\t   ((L1 n) × (L2 n)).\n\t\n  \nEnd L_prod_def.\n\n  Fact list_prod_spec X Y l m c : In c (@list_prod X Y l m) <-> In (fst c) l /\\ In (snd c) m.\n  Proof.\n    revert c; induction l as [ | x l IHl ]; intros c; simpl; try tauto.\n    rewrite in_app_iff, IHl, in_map_iff; simpl.\n    split.\n    + intros [ (y & <- & ?) | (? & ?) ]; simpl; auto.\n    + intros ([ -> | ] & ? ); destruct c; simpl; firstorder.\n  Qed.\n\n  \nSearch \"L_prod\". \nLemma enumerator_prod_list {X1 X2} L1 L2 :\n  list_enumerator__T L1 X1 -> list_enumerator__T L2 X2 -> list_enumerator__T (L_prod_list (to_cumul L1) (to_cumul L2)) (X1*X2).\nProof.\n  intros H1 H2.\n  intro.\n  destruct x as [x1 x2].\n  specialize (H1 x1). specialize (H2 x2).\n  destruct H1 as [n1 Hn1]. destruct H2 as [n2 Hn2].\n  exists (S(Nat.max n1 n2)).\n  \n  apply list_prod_spec.\n  split.\n  simpl fst.\n  apply Cumul_Step with n1.\n  lia.\n  auto.\n\n  apply Cumul_Step with n2.\n  lia.\n  exact Hn2.\nQed.\n\n\n\nLemma  enumerable_list {X} : list_enumerable__T X -> list_enumerable__T (list X).\nProof.\n  intros [L H].\n  eexists. now eapply enumerator__T_list.\nQed.\n\n\nLemma  enumerable_sum {X1 X2} : list_enumerable__T X1 -> list_enumerable__T X2 -> list_enumerable__T (X1+X2).\nProof.\n  intros [L1 H1]. intros  [L2 H2].\n  \n  eexists. now eapply enumerator_sum_list.\nQed.\n\nLemma  enumerable_prod {X1 X2} : list_enumerable__T X1 -> list_enumerable__T X2 -> list_enumerable__T (X1*X2).\nProof.\n  intros [L1 H1]. intros  [L2 H2].\n  \n  eexists. now eapply enumerator_prod_list.\nQed.\nLemma enumNatNat: enumerable__T ((nat*nat)+nat).\nProof.\n  enough (H: enumerable__T nat).\n  apply enum_enumT. \n  apply enumerable_sum.\n  apply enum_enumT.\n  apply enum_enumT.\n  \n  apply enumerable_prod. apply enum_enumT. apply H.\n  apply enum_enumT. apply H. apply enum_enumT. apply H.\n  unfold enumerable__T.\n  exists (fun x => Some x).  intro. eauto.\nDefined.\nLemma enumerableDecodeEncode (A B: Type)\n      (code: A -> B)\n      (decode: B -> option A)\n      (H1: forall a, (decode (code a)) = Some a)\n      (enumB: enumerable__T B)\n  : enumerable__T A.\nProof.\n  unfold enumerable__T.\n  destruct enumB as [fb Hb].\n  exists (fun n => match (fb n) with None => None | Some x => (decode x) end).\n  intro a. specialize (H1 a).\n  specialize (Hb (code a)).\n  destruct Hb. exists x. rewrite H. apply H1.\nDefined.\n\nPrint enumerableDecodeEncode.\nLemma enumLtree: enumerable__T Ntree. \nProof.\n  apply (@enumerableDecodeEncode Ntree (list ((nat*nat)+nat)) ntree_to_list (ntree_of_list [])  ).\n  intro.\n  pose (ntree_of_to_list [] [] a).\n  rewrite app_nil_r in e.\n  rewrite e.\n  simpl ntree_of_list.\n  reflexivity.\n  apply  enum_enumT. \n  apply enumerable_list.\n  apply enum_enumT.\n  apply enumNatNat.\nDefined.\n\n\n(** Ntrees are decidable **)\nInstance Ntree_eq_dec :\n  eq_dec Ntree.\nProof. \n  intros x y.\n  destruct ((ntree_eq_dec x y)) eqn:H.\n  left.\n  apply ntree_equal_dec_lemma.\n  auto.\n  right. intro.  apply ntree_equal_dec_lemma in H1. congruence.\nDefined.\n\n", "meta": {"author": "christ2go", "repo": "gherkin", "sha": "967483ca55cfb60c6e15a953469684a6bcc0e918", "save_path": "github-repos/coq/christ2go-gherkin", "path": "github-repos/coq/christ2go-gherkin/gherkin-967483ca55cfb60c6e15a953469684a6bcc0e918/gentree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6997915063687645}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import List.\nImport ListNotations.\nRequire Import Sorting.Permutation.\nRequire Import StructTact.StructTactics.\nRequire Import StructTact.ListTactics.\n\nSet Implicit Arguments.\n\nNotation member := (in_dec eq_nat_dec).\n\nLemma seq_range :\n  forall n a x,\n    In x (seq a n) ->\n    a <= x < a + n.\nProof.\n  induction n; intros; simpl in *.\n  - intuition.\n  - break_or_hyp; try find_apply_hyp_hyp; intuition.\nQed.\n\nLemma plus_gt_0 :\n  forall a b,\n    a + b > 0 ->\n    a > 0 \\/ b > 0.\nProof.\n  intros.\n  destruct (eq_nat_dec a 0); intuition.\nQed.\n\nSection list_util.\n  Variables A B C : Type.\n  Hypothesis A_eq_dec : forall x y : A, {x = y} + {x <> y}.\n\n  Lemma list_neq_cons :\n    forall (l : list A) x,\n      x :: l <> l.\n  Proof using.\n    intuition.\n    symmetry in H.\n    induction l;\n      now inversion H.\n  Qed.\n\n  Lemma remove_preserve :\n    forall (x y : A) xs,\n      x <> y ->\n      In y xs ->\n      In y (remove A_eq_dec x xs).\n  Proof using.\n    induction xs; intros.\n    - intuition.\n    - simpl in *.\n      concludes.\n      intuition; break_if; subst; try congruence; intuition.\n  Qed.\n\n  Lemma in_remove :\n    forall (x y : A) xs,\n      In y (remove A_eq_dec x xs) ->\n      In y xs.\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - simpl in *. break_if; simpl in *; intuition.\n  Qed.\n\n  Lemma remove_partition :\n    forall xs (p : A) ys,\n      remove A_eq_dec p (xs ++ p :: ys) = remove A_eq_dec p (xs ++ ys).\n  Proof using.\n    induction xs; intros; simpl; break_if; congruence.\n  Qed.\n\n  Lemma remove_not_in :\n    forall (x : A) xs,\n      ~ In x xs ->\n      remove A_eq_dec x xs = xs.\n  Proof using.\n    intros. induction xs; simpl in *; try break_if; intuition congruence.\n  Qed.\n\n  Lemma remove_app_comm :\n    forall a xs ys,\n      remove A_eq_dec a (xs ++ ys) = remove A_eq_dec a xs ++ remove A_eq_dec a ys.\n  Proof.\n    intros.\n    generalize dependent ys.\n    induction xs; intros.\n    - tauto.\n    - destruct (A_eq_dec a0 a);\n      simpl;\n      break_if;\n      try rewrite <- app_comm_cons;\n      rewrite IHxs; \n      congruence.\n  Qed.\n\n  Lemma filter_app : forall (f : A -> bool) xs ys,\n      filter f (xs ++ ys) = filter f xs ++ filter f ys.\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - simpl. rewrite IHxs. break_if; auto.\n  Qed.\n\n  Lemma filter_fun_ext_eq : forall f g xs,\n      (forall a : A, In a xs -> f a = g a) ->\n      filter f xs = filter g xs.\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - simpl. rewrite H by intuition. rewrite IHxs by intuition. auto.\n  Qed.\n\n  Lemma not_in_filter_false :\n    forall (f : A -> bool) l x,\n      In x l ->\n      ~ In x (filter f l) ->\n      f x = false.\n  Proof.\n    intros.\n    destruct (f x) eqn:?H; [|tauto].\n    unfold not in *; find_false.\n    now eapply filter_In.\n  Qed.\n\n  Lemma filter_length_bound :\n    forall f (l : list A),\n      length (filter f l) <= length l.\n  Proof.\n    induction l.\n    - easy.\n    - simpl.\n      break_if; simpl; omega.\n  Qed.\n\n  Lemma NoDup_map_injective : forall (f : A -> B) xs,\n      (forall x y, In x xs -> In y xs ->\n              f x = f y -> x = y) ->\n      NoDup xs -> NoDup (map f xs).\n  Proof using.\n    induction xs; intros.\n    - constructor.\n    - simpl. invc_NoDup. constructor.\n      + intro. do_in_map.\n        assert (x = a) by intuition.\n        congruence.\n      + intuition.\n  Qed.\n\n  Lemma NoDup_disjoint_append :\n    forall (l : list A) l',\n      NoDup l ->\n      NoDup l' ->\n      (forall a, In a l -> ~ In a l') ->\n      NoDup (l ++ l').\n  Proof using.\n    induction l; intros.\n    - auto.\n    - simpl. invc_NoDup. constructor.\n      + intro. do_in_app. intuition eauto with *.\n      + intuition eauto with *.\n  Qed.\n\n  Lemma NoDup_map_partition :\n    forall (f : A -> B) xs l y zs xs' y' zs',\n      NoDup (map f l) ->\n      l = xs ++ y :: zs ->\n      l = xs' ++ y' :: zs' ->\n      f y = f y' ->\n      xs = xs'.\n  Proof using.\n    induction xs; simpl; intros; destruct xs'.\n    - auto.\n    - subst. simpl in *. find_inversion.\n      invc H. exfalso. rewrite map_app in *. simpl in *.\n      repeat find_rewrite. intuition.\n    - subst. simpl in *. find_inversion.\n      invc H. exfalso. rewrite map_app in *. simpl in *.\n      repeat find_rewrite. intuition.\n    - subst. simpl in *. find_injection. intros. subst.\n      f_equal. eapply IHxs; eauto. solve_by_inversion.\n  Qed.\n\n  Lemma filter_NoDup :\n    forall p (l : list A),\n      NoDup l ->\n      NoDup (filter p l).\n  Proof using.\n    induction l; intros.\n    - auto.\n    - invc_NoDup. simpl. break_if; auto.\n      constructor; auto.\n      intro. apply filter_In in H. intuition.\n  Qed.\n\n  Lemma NoDup_map_filter :\n    forall (f : A -> B) g l,\n      NoDup (map f l) ->\n      NoDup (map f (filter g l)).\n  Proof using.\n    intros. induction l; simpl in *.\n    - constructor.\n    - invc_NoDup. concludes.\n      break_if; simpl in *; auto.\n      constructor; auto.\n      intro. do_in_map.\n      find_apply_lem_hyp filter_In. intuition.\n      match goal with | H : _ -> False |- False => apply H end.\n      apply in_map_iff. eauto.\n  Qed.\n\n  Lemma filter_true_id : forall (f : A -> bool) xs,\n      (forall x, In x xs -> f x = true) ->\n      filter f xs = xs.\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - simpl. now rewrite H, IHxs by intuition.\n  Qed.\n\n  Lemma map_of_map : forall (f : A -> B) (g : B -> C) xs,\n      map g (map f xs) = map (fun x => g (f x)) xs.\n  Proof using.\n    induction xs; simpl; auto using f_equal2.\n  Qed.\n\n  Lemma filter_except_one : forall (f g : A -> bool) x xs,\n      (forall y, In y xs ->\n            x <> y ->\n            f y = g y) ->\n      g x = false ->\n      filter f (remove A_eq_dec x xs) = filter g xs.\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - simpl.\n      break_if.\n      + subst. repeat find_rewrite. eauto with *.\n      + simpl. rewrite H by auto with *.\n        break_if; eauto using f_equal2 with *.\n  Qed.\n\n  Lemma flat_map_nil : forall (f : A -> list B) l,\n      flat_map f l = [] ->\n      l = [] \\/ (forall x, In x l -> f x = []).\n  Proof using.\n    induction l; intros.\n    - intuition.\n    - right. simpl in *.\n      apply app_eq_nil in H.\n      intuition; subst; simpl in *; intuition.\n  Qed.\n\n  Theorem NoDup_Permutation_NoDup :\n    forall (l l' : list A),\n      NoDup l ->\n      Permutation l l' ->\n      NoDup l'.\n  Proof using.\n    intros l l' Hnd Hp.\n    induction Hp; auto; invc_NoDup; constructor;\n      eauto using Permutation_in, Permutation_sym;\n      simpl in *; intuition.\n  Qed.\n\n  Theorem NoDup_append :\n    forall l (a : A),\n      NoDup (l ++ [a]) <-> NoDup (a :: l).\n  Proof using. \n    intuition eauto using NoDup_Permutation_NoDup, Permutation_sym, Permutation_cons_append.\n  Qed.\n\n  Lemma NoDup_map_elim :\n    forall (f : A -> B) xs x y,\n      f x = f y ->\n      NoDup (map f xs) ->\n      In x xs ->\n      In y xs ->\n      x = y.\n  Proof using.\n    induction xs; intros; simpl in *.\n    - intuition.\n    - invc_NoDup. intuition; subst; auto; exfalso.\n      + repeat find_rewrite. auto using in_map.\n      + repeat find_reverse_rewrite. auto using in_map.\n  Qed.\n\n  Lemma remove_length_not_in : forall (x : A) xs,\n      ~ In x xs ->\n      length (remove A_eq_dec x xs) = length xs.\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - simpl in *. intuition.\n      break_if; subst; simpl; intuition.\n  Qed.\n\n  Lemma remove_length_in : forall (x : A) xs,\n      In x xs ->\n      NoDup xs ->\n      S (length (remove A_eq_dec x xs)) = length xs.\n  Proof using.\n    induction xs; intros; simpl in *; intuition; invc_NoDup;\n      break_if; subst; intuition (simpl; try congruence).\n    now rewrite remove_length_not_in.\n  Qed.\n\n  Lemma subset_size_eq :\n    forall xs,\n      NoDup xs ->\n      forall ys,\n        NoDup ys ->\n        (forall x : A, In x xs -> In x ys) ->\n        length xs = length ys ->\n        (forall x, In x ys -> In x xs).\n  Proof using.\n    induction xs; intros.\n    - destruct ys; simpl in *; congruence.\n    - invc_NoDup. concludes.\n      assert (In a ys) by eauto with *.\n\n      find_apply_lem_hyp in_split.\n      break_exists_name l1.\n      break_exists_name l2.\n      subst.\n\n      specialize (IHxs (l1 ++ l2)).\n\n      conclude_using ltac:(eauto using NoDup_remove_1).\n\n      forward IHxs.\n      intros x' Hx'.\n      assert (In x' (l1 ++ a :: l2)) by eauto with *.\n      do_in_app. simpl in *. intuition. subst. congruence.\n      concludes.\n\n      forward IHxs.\n      rewrite app_length in *. simpl in *. omega.\n      concludes.\n\n      do_in_app. simpl in *. intuition.\n  Qed.\n\n  Lemma remove_NoDup :\n    forall (x : A) xs,\n      NoDup xs ->\n      NoDup (remove A_eq_dec x xs).\n  Proof using.\n    induction xs; intros.\n    - auto with struct_util.\n    - invc_NoDup. simpl. break_if; eauto 6 using in_remove with struct_util.\n  Qed.\n\n  Lemma remove_length_ge : forall (x : A) xs,\n      NoDup xs ->\n      length (remove A_eq_dec x xs) >= length xs - 1.\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - invc_NoDup. simpl. break_if.\n      + rewrite <- minus_n_O.\n        subst.\n        rewrite remove_length_not_in; auto.\n      + simpl. concludes. omega.\n  Qed.\n\n  Lemma remove_length_le :\n    forall (x : A) xs eq_dec,\n      length xs >= length (remove eq_dec x xs).\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - simpl in *.\n      specialize (IHxs eq_dec).\n      break_if; subst; simpl; omega.\n  Qed.\n\n  Lemma remove_length_lt :\n    forall (x : A) xs eq_dec,\n      In x xs ->\n      length xs > length (remove eq_dec x xs).\n  Proof using.\n    induction xs; intros; simpl in *; intuition.\n    - subst.\n      break_if; try congruence.\n      pose proof remove_length_le x xs eq_dec.\n      omega.\n    - specialize (IHxs ltac:(eauto) ltac:(eauto)).\n      break_if; subst; simpl; omega.\n  Qed.\n\n  Lemma subset_length :\n    forall xs ys,\n      NoDup xs ->\n      (forall x : A, In x xs -> In x ys) ->\n      length ys >= length xs.\n  Proof using A_eq_dec.\n    induction xs; intros.\n    - simpl. omega.\n    - specialize (IHxs (remove A_eq_dec a ys)).\n      invc_NoDup.\n      concludes.\n\n      forward IHxs.\n      intros.\n      apply remove_preserve; [congruence|intuition].\n      concludes.\n\n      pose proof remove_length_lt a ys A_eq_dec.\n      conclude_using intuition.\n\n      simpl. omega.\n  Qed.\n\n  Lemma app_cons_singleton_inv :\n    forall xs (y : A) zs w,\n      xs ++ y :: zs = [w] ->\n      xs = [] /\\ y = w /\\ zs = [].\n  Proof using.\n    intros.\n    destruct xs.\n    - solve_by_inversion.\n    - destruct xs; solve_by_inversion.\n  Qed.\n\n  Lemma app_cons_in :\n    forall (l : list A) xs a ys,\n      l = xs ++ a :: ys ->\n      In a l.\n  Proof using.\n    intros. subst. auto with *.\n  Qed.\n  Hint Resolve app_cons_in : struct_util.\n\n  Lemma app_cons_in_rest:\n    forall (l : list A) xs a b ys,\n      l = xs ++ a :: ys ->\n      In b (xs ++ ys) ->\n      In b l.\n  Proof using.\n    intros. subst. in_crush.\n  Qed.\n  Hint Resolve app_cons_in_rest : struct_util.\n\n  Lemma in_rest_app_cons:\n    forall (l xs ys : list A) a b,\n      l = xs ++ a :: ys ->\n      In b l ->\n      a <> b ->\n      In b (xs ++ ys).\n  Proof using.\n    intros.\n    subst_max.\n    do_in_app.\n    break_or_hyp.\n    - auto with datatypes.\n    - find_apply_lem_hyp in_inv.\n      break_or_hyp; auto using in_or_app || congruence.\n  Qed.\n  Hint Resolve in_rest_app_cons : struct_util.\n\n  Lemma remove_filter_commute :\n    forall (l : list A) A_eq_dec f x,\n      remove A_eq_dec x (filter f l) = filter f (remove A_eq_dec x l).\n  Proof using.\n    induction l; intros; simpl in *; auto.\n    repeat (break_if; subst; simpl in *; try congruence).\n  Qed.\n\n  Lemma In_filter_In :\n    forall (f : A -> bool) x l l',\n      filter f l = l' ->\n      In x l' -> In x l.\n  Proof using.\n    intros. subst.\n    eapply filter_In; eauto.\n  Qed.\n\n  Lemma filter_partition :\n    forall (l1 : list A) f l2 x l1' l2',\n      NoDup (l1 ++ x :: l2) ->\n      filter f (l1 ++ x :: l2) = (l1' ++ x :: l2') ->\n      filter f l1 = l1' /\\ filter f l2 = l2'.\n  Proof using.\n    induction l1; intros; simpl in *; break_if; simpl in *; invc_NoDup.\n    - destruct l1'; simpl in *.\n      + solve_by_inversion.\n      + find_inversion. exfalso. eauto using In_filter_In with *.\n    - exfalso. eauto using In_filter_In with *.\n    - destruct l1'; simpl in *; break_and; find_inversion.\n      + exfalso. eauto with *.\n      + find_apply_hyp_hyp. intuition auto using f_equal2.\n    - eauto.\n  Qed.\n\n  Lemma map_inverses :\n    forall (la : list A) (lb : list B)  (f : A -> B) g,\n      (forall a, g (f a) = a) ->\n      (forall b, f (g b) = b) ->\n      lb = map f la ->\n      la = map g lb.\n  Proof using.\n    destruct la; intros; simpl in *.\n    - subst. reflexivity.\n    - destruct lb; try congruence.\n      simpl in *. find_inversion.\n      find_higher_order_rewrite.\n      f_equal.\n      rewrite map_map.\n      erewrite map_ext; [symmetry; apply map_id|].\n      simpl in *. auto.\n  Qed.\n\n  Lemma In_notIn_implies_neq :\n    forall x y l,\n      In(A:=A) x l ->\n      ~ In(A:=A) y l ->\n      x <> y.\n  Proof using.\n    intuition congruence.\n  Qed.\n\n  Lemma In_cons_neq :\n    forall a x xs,\n      In(A:=A) a (x :: xs) ->\n      a <> x ->\n      In a xs.\n  Proof using.\n    simpl.\n    intuition congruence.\n  Qed.\n\n  Lemma NoDup_app3_not_in_1 :\n    forall (xs ys zs : list A) b,\n      NoDup (xs ++ ys ++ b :: zs) ->\n      In b xs ->\n      False.\n  Proof using.\n    intros.\n    rewrite <- app_ass in *.\n    find_apply_lem_hyp NoDup_remove.\n    rewrite app_ass in *.\n    intuition.\n  Qed.\n\n  Lemma NoDup_app3_not_in_2 :\n    forall (xs ys zs : list A) b,\n      NoDup (xs ++ ys ++ b :: zs) ->\n      In b ys ->\n      False.\n  Proof using.\n    intros.\n    rewrite <- app_ass in *.\n    find_apply_lem_hyp NoDup_remove_2.\n    rewrite app_ass in *.\n    auto 10 with *.\n  Qed.\n\n  Lemma NoDup_app3_not_in_3 :\n    forall (xs ys zs : list A) b,\n      NoDup (xs ++ ys ++ b :: zs) ->\n      In b zs ->\n      False.\n  Proof using.\n    intros.\n    rewrite <- app_ass in *.\n    find_apply_lem_hyp NoDup_remove_2.\n    rewrite app_ass in *.\n    auto 10 with *.\n  Qed.\n\n  Lemma In_cons_2_3 :\n    forall xs ys zs x y a,\n      In (A:=A) a (xs ++ ys ++ zs) ->\n      In a (xs ++ x :: ys ++ y :: zs).\n  Proof using.\n    intros.\n    repeat (do_in_app; intuition auto 10 with *).\n  Qed.\n\n  Lemma In_cons_2_3_neq :\n    forall a x y xs ys zs,\n      In (A:=A) a (xs ++ x :: ys ++ y :: zs) ->\n      a <> x ->\n      a <> y ->\n      In a (xs ++ ys ++ zs).\n  Proof using.\n    intros.\n    repeat (do_in_app; simpl in *; intuition (auto with *; try congruence)).\n  Qed.\n\n  Lemma in_middle_reduce :\n    forall a xs y zs,\n      In (A:=A) a (xs ++ y :: zs) ->\n      a <> y ->\n      In a (xs ++ zs).\n  Proof using.\n    intros.\n    do_in_app; simpl in *; intuition. congruence.\n  Qed.\n\n  Lemma in_middle_insert :\n    forall a xs y zs,\n      In (A:=A) a (xs ++ zs) ->\n      In a (xs ++ y :: zs).\n  Proof using.\n    intros.\n    do_in_app; simpl in *; intuition.\n  Qed.\n\n  Lemma NoDup_rev :\n    forall l,\n      NoDup (A:=A) l ->\n      NoDup (rev l).\n  Proof using.\n    induction l; intros; simpl.\n    - auto.\n    - apply NoDup_append.\n      invc_NoDup.\n      constructor; auto.\n      intuition.\n      find_apply_lem_hyp in_rev.\n      auto.\n  Qed.\n\n  Lemma NoDup_map_map :\n    forall (f : A -> B) (g : A -> C) xs,\n      (forall x y, In x xs -> In y xs -> f x = f y -> g x = g y) ->\n      NoDup (map g xs) ->\n      NoDup (map f xs).\n  Proof using.\n    induction xs; intros; simpl in *.\n    - constructor.\n    - invc_NoDup.\n      constructor; auto.\n      intro.\n      do_in_map.\n      find_apply_hyp_hyp.\n      find_reverse_rewrite.\n      auto using in_map.\n  Qed.\n\n  Lemma pigeon :\n    forall (l : list A) sub1 sub2,\n      (forall a, In a sub1 -> In a l) ->\n      (forall a, In a sub2 -> In a l) ->\n      NoDup l ->\n      NoDup sub1 ->\n      NoDup sub2 ->\n      length sub1 + length sub2 > length l ->\n      exists a, In a sub1 /\\ In a sub2.\n  Proof using A_eq_dec.\n    induction l.\n    intros.\n    + simpl in *. find_apply_lem_hyp plus_gt_0. intuition.\n      * destruct sub1; simpl in *; [omega|].\n        specialize (H a). intuition.\n      * destruct sub2; simpl in *; [omega|].\n        specialize (H0 a). intuition.\n    + intros. simpl in *.\n      destruct (in_dec A_eq_dec a sub1);\n        destruct (in_dec A_eq_dec a sub2); eauto;\n          specialize (IHl (remove A_eq_dec a sub1) (remove A_eq_dec a sub2));\n          cut (exists a0, In a0 (remove A_eq_dec a sub1) /\\ In a0 (remove A_eq_dec a sub2));\n          try solve [intros; break_exists;\n                     intuition eauto using in_remove];\n          apply IHl; try solve [\n                           intros; find_copy_apply_lem_hyp in_remove;\n                           find_apply_hyp_hyp; intuition; subst; exfalso; eapply remove_In; eauto];\n          eauto using remove_NoDup; try solve_by_inversion;\n            repeat match goal with\n                   | H : ~ In a ?sub |- _ =>\n                     assert (length (remove A_eq_dec a sub) = length sub)\n                       by eauto using remove_length_not_in; clear H\n                   | H : In a ?sub |- _ =>\n                     assert (length (remove A_eq_dec a sub) >= length sub - 1)\n                       by eauto using remove_length_ge; clear H\n                   end; omega.\n  Qed.\n\n  Lemma snoc_assoc :\n    forall (l : list A) x y,\n      l ++ [x; y] = (l ++ [x]) ++ [y].\n  Proof using.\n    induction l; intros; simpl; intuition.\n    auto using f_equal.\n  Qed.\n\n  Lemma cons_cons_app :\n    forall (x y : A),\n      [x; y] = [x] ++ [y].\n  Proof using.\n    auto.\n  Qed.\n\n  Lemma map_eq_inv :\n    forall (f : A -> B) l xs ys,\n      map f l = xs ++ ys ->\n      exists l1 l2,\n        l = l1 ++ l2 /\\\n        map f l1 = xs /\\\n        map f l2 = ys.\n  Proof using.\n    induction l; simpl; intros xs ys H.\n    - symmetry in H. apply app_eq_nil in H. break_and. subst.\n      exists [], []. auto.\n    - destruct xs; simpl in *.\n      + exists [], (a :: l). intuition.\n      + invc H. find_apply_hyp_hyp.\n        break_exists_name l1.\n        break_exists_name l2.\n        break_and.\n        exists (a :: l1), l2. subst.\n        intuition.\n  Qed.\n\n  Lemma map_partition :\n    forall p l (x : B) p' (f : A -> B),\n      map f l = (p ++ x :: p') ->\n      exists ap a ap',\n        l = ap ++ a :: ap' /\\\n        map f ap = p /\\\n        f a = x /\\\n        map f ap' = p'.\n  Proof using.\n    intros p l x p' f H_m.\n    pose proof map_eq_inv f _ _ _ H_m.\n    break_exists_name l1.\n    break_exists_name l2.\n    break_and.\n    find_rewrite.\n    destruct l2; simpl in *.\n    - match goal with H : [] = _ :: _ |- _ => contradict H end.\n      auto with datatypes.\n    - repeat find_rewrite.\n      find_inversion.\n      exists l1, a, l2. auto.\n  Qed.\n\n  Lemma map_eq_inv_eq :\n    forall (f : A -> B),\n      (forall a a', f a = f a' -> a = a') ->\n      forall l l', map f l = map f l' -> l = l'.\n  Proof using.\n    induction l; simpl; intros l' Heq; destruct l'; simpl in *; try congruence.\n    find_inversion. auto using f_equal2.\n  Qed.\n\n  Lemma map_fst_snd_id :\n    forall l, map (fun t : A * B => (fst t, snd t)) l = l.\n  Proof using.\n    intros.\n    rewrite <- map_id.\n    apply map_ext.\n    destruct a; auto.\n  Qed.\n\n  Lemma in_firstn : forall n (x : A) xs,\n      In x (firstn n xs) -> In x xs.\n  Proof using.\n    induction n; simpl; intuition; break_match; simpl in *; intuition.\n  Qed.\n\n  Lemma firstn_NoDup : forall n (xs : list A),\n    NoDup xs ->\n    NoDup (firstn n xs).\n  Proof using.\n    induction n; intros; simpl; destruct xs; auto with struct_util.\n    invc_NoDup.\n    eauto 6 using in_firstn with struct_util.\n  Qed.\n\n  Lemma NoDup_mid_not_in :\n    forall (a : A) (l l' : list A),\n    NoDup (l ++ a :: l') ->\n    ~ In a (l ++ l').\n  Proof using.\n    induction l; intros; simpl in *.\n    - invc_NoDup; auto.\n    - invc_NoDup.\n      intro.\n      break_or_hyp.\n      * match goal with H: ~ In _ _ |- _ => contradict H end.\n        apply in_or_app.\n        right; left. auto.\n      * match goal with H: In _ _ |- _ => contradict H end.\n        eauto.\n    Qed.\n\n  Lemma Permutation_split :\n    forall (ns ns' : list A) (n : A),\n      Permutation (n :: ns) ns' ->\n      exists ns0, exists ns1, ns' = ns0 ++ n :: ns1.\n  Proof using.\n    intros l l' a H_pm.\n    assert (In a (a :: l)); auto with datatypes.\n    assert (In a l'); eauto using Permutation_in.\n    find_apply_lem_hyp In_split; auto.\n  Qed.\n\n  Lemma NoDup_app_left :\n    forall (l l' : list A),\n      NoDup (l ++ l') -> NoDup l.\n  Proof using.\n    induction l; intros; simpl in *.\n    - apply NoDup_nil.\n    - invc_NoDup.\n      find_apply_hyp_hyp.\n      apply NoDup_cons; auto.\n      intro.\n      match goal with H: ~ In _ _ |- _ => contradict H end.\n      apply in_or_app.\n      left; auto.\n  Qed.\n\n  Lemma NoDup_app_right :\n    forall (l l' : list A),\n      NoDup (l ++ l') -> NoDup l'.\n  Proof using.\n    induction l; intros; simpl in *; auto.\n    invc_NoDup.\n    find_apply_hyp_hyp; auto.\n  Qed.\n\n  Lemma NoDup_in_not_in_right :\n    forall (l l' : list A) (a : A),\n      NoDup (l ++ l') -> In a l -> ~ In a l'.\n  Proof using.\n    induction l; intros; simpl in *; auto.\n    invc_NoDup.\n    break_or_hyp; eauto with datatypes.\n  Qed.\n\n  Lemma NoDup_in_not_in_left :\n    forall (l l' : list A) (a : A),\n    NoDup (l ++ l') -> In a l' -> ~ In a l.\n  Proof using.\n    intros.\n    induction l; simpl in *; auto.\n    invc_NoDup.\n    concludes.\n    intro.\n    break_or_hyp; auto with datatypes.\n  Qed.\n\n  Lemma count_occ_app :\n    forall l l' (a : A),\n      count_occ A_eq_dec (l ++ l') a = count_occ A_eq_dec l a + count_occ A_eq_dec l' a.\n  Proof using.\n    intros.\n    induction l; simpl in *; auto.\n    break_if; auto.\n    find_rewrite.\n    auto.\n  Qed.\n\n  Lemma Permutation_map_fst :\n    forall l l' : list (A * B),\n      Permutation l l' ->\n      Permutation (map fst l) (map fst l').\n  Proof using.\n    induction l; intros; simpl in *.\n    - find_apply_lem_hyp Permutation_nil.\n      find_rewrite.\n      auto.\n    - assert (In a l').\n        apply Permutation_in with (l := a :: l); auto with datatypes.\n      find_apply_lem_hyp in_split.\n      break_exists.\n      find_rewrite.\n      find_apply_lem_hyp Permutation_cons_app_inv.\n      find_apply_hyp_hyp.\n      find_rewrite.\n      rewrite map_app.\n      simpl.\n      apply Permutation_cons_app.\n      rewrite <- map_app.\n      auto.\n     Qed.\n\n  Lemma snd_eq_not_in_map :\n    forall (l : list (A * B)) n m,\n      (forall nm, In nm l -> snd nm = m) ->\n      ~ In (n, m) l ->\n      ~ In n (map fst l).\n  Proof using.\n    intros.\n    induction l; simpl in *; auto.\n    intro.\n    break_or_hyp.\n    - match goal with H: ~ _ |- _ => contradict H end.\n      left.\n      destruct a.\n      match goal with H: forall _ : A * B, _ |- _ => specialize (H (a, b)) end.\n      simpl in *.\n      intuition eauto; repeat find_rewrite; auto.\n    - match goal with H: In _ _ |- _ => contradict H end.\n      apply IHl; eauto.\n  Qed.\n\n  Lemma NoDup_map_snd_fst :\n    forall nms : list (A * B),\n      NoDup nms ->\n      (forall nm nm', In nm nms -> In nm' nms -> snd nm = snd nm') ->\n      NoDup (map fst nms).\n  Proof using.\n    intros.\n    induction nms; simpl in *.\n    - apply NoDup_nil.\n    - invc_NoDup.\n      apply NoDup_cons.\n      * assert (forall nm, In nm nms -> snd nm = snd a).\n          intuition eauto.\n        destruct a.\n        apply snd_eq_not_in_map with (m := b); auto.\n      * apply IHnms; auto.\n  Qed.\n\n  Lemma in_fold_left_by_cons_in :\n    forall (l : list B) (g : B -> A) x acc,\n      In x (fold_left (fun a b => g b :: a) l acc) ->\n      In x acc \\/ exists y, In y l /\\ x = g y.\n  Proof using A_eq_dec.\n    intros until l.\n    induction l.\n    - auto.\n    - simpl; intros.\n      destruct (A_eq_dec x (g a)); subst.\n      + right; exists a; tauto.\n      + find_apply_lem_hyp IHl.\n        break_or_hyp; [left|right].\n        * find_apply_lem_hyp In_cons_neq; tauto.\n        * break_exists_exists; tauto.\n  Qed.\n\n  Lemma fold_left_for_each_not_in :\n    forall (f : A -> B -> A) (g : A -> B -> C),\n      (forall a b b',\n          b <> b' ->\n          g (f a b') b = g a b) ->\n      forall l a b,\n        ~ In b l ->\n        g (fold_left f l a) b = g a b.\n  Proof using A B C.\n    induction l as [| b' l']; simpl in *; auto.\n    - intros. intuition.\n      rewrite IHl'; auto.\n  Qed.\n\n  Lemma fold_left_for_each_in :\n    forall (f : A -> B -> A) (g : A -> B -> C) (B_eq_dec : forall x y : B, {x = y} + {x <> y}),\n      (forall a b b',\n          b <> b' ->\n          g (f a b') b = g a b) ->\n      forall l a b,\n        In b l ->\n        exists a',\n          g (fold_left f l a) b = g (f a' b) b.\n  Proof using A B C.\n    induction l as [|b' l']; simpl in *; intuition; subst.\n    destruct (in_dec B_eq_dec b l'); intuition.\n    find_eapply_lem_hyp fold_left_for_each_not_in; eauto.\n  Qed.\n\n  Lemma hd_error_tl_exists :\n    forall (l : list A) x,\n      hd_error l = Some x ->\n      exists tl,\n        l = x :: tl.\n  Proof.\n    intros.\n    destruct l; simpl in *.\n    - congruence.\n    - eexists; solve_by_inversion.\n  Qed.\n\n  Lemma hd_error_None :\n    forall (l : list A),\n      hd_error l = None ->\n      l = [].\n  Proof.\n    now destruct l.\n  Qed.\n\nEnd list_util.\n\n(* We have to repeat these Hint Resolve commands because hints don't survive\n   past the ends of sections *)\nHint Resolve app_cons_in : struct_util.\nHint Resolve app_cons_in_rest : struct_util.\nHint Resolve in_rest_app_cons : struct_util.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/StructTact/ListUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.6997709737937025}}
{"text": "Inductive SC(T:Type): Type :=\n| Value : T -> SC T\n| Unknown : SC T.\n\nInductive Stack(T:Type): Type :=\n| Empty : Stack T\n| Push:  T -> Stack T -> Stack T.\n(* For better readability I renamed Add constructor in Ex1.v to Push *)\n\n(*Stack is parameterized over the stack element.*)\n\nDefinition pop(T:Type) (s:Stack T):(Stack T):=\nmatch s with \n| Empty => Empty T\n| Push _ xs => xs\nend.\n\nDefinition top (T:Type)(s:Stack T) : SC T :=\nmatch s with\n| Empty => Unknown T\n| Push s' _ => Value T s'\nend.\n\nDefinition isEmpty (T:Type) (s:Stack T) : bool :=\nmatch s with \n|Empty => true\n|Push _ _ => false\nend.\n\nTheorem push_post_condition : forall t x xs, (top t (Push t x xs))= Value t x.\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\nTheorem push_invariant : forall t x xs, pop t (Push t x xs) = xs.\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\nTheorem pop_post_condition : forall t x xs, pop t (Push t x xs) = xs.\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\nTheorem top_post_condition : forall t x xs, (top t (Push t x xs)) = Value t x.\nProof.\n intros.\n simpl.\n reflexivity.\nQed.\n\nTheorem isEmpty_post_condition: forall t, isEmpty t (Empty t)=true.\nProof.\nintros.\nreflexivity.\nQed.\n\n(* For arbitrary x and y, on an empty stack, we are pushing twice and popping \n   twice on the same stack. So, it is safe and doesnot crash. The final state\n   of the stack is empty.\n*)\nTheorem proof1: forall t x y, (pop t (pop t ( Push t y (Push t x (Empty t)))))= (Empty t).\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\n(* For arbitrary x and y, on an empty stack, we are pushing once and popping twice.\n   Since we wrote the contuctor for \"empty\" in pop definition, the below theorem doesnot crash.\n   Otherwise (pop (pop (push x empty)) is unsafe.\n*)\n\nTheorem proof2: forall t x, (pop t (pop t (Push t x (Empty t))))= (Empty t).\nProof.\nintros.\nsimpl.\nreflexivity.\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/Exercise2/Ex2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.6997709721225446}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Category.Composable_Chain.\nRequire Import Functor.Functor.\n\n(*\n\n(** The image of a functor is not simply the image of its object and arrow maps as\nthose may not form a category. Consider the following example.\n\n  category C:\n#\n<pre>\n             f\n       x1 ——————–> y1\n\n       x2 ——————–> y2\n             g\n</pre>\n#\n   category D:\n#\n<pre>\n             h1        h2  \n       x ——————–> y ————————> z\n\n       u ——————–> v\n            m\n</pre>\n#\n    functor F where:\n#\n<pre>\n       F _o x1 = x\n       F _o y1 = y\n       F _o x2 = y\n       F _o y2 = z\n\n       F _a f = h1\n       F _a g = h2\n</pre>\n#\n\nHere we have not drawn identity arrows and compositions of arrows in categories and\ntheir mappings by the functor as these are trivial details.\n\nIn this case, the simple image of arrow map of F has only h1 and h2 but not their\ncomposition and is hence not a category.\n\nWe define the image of a functor to be a sum category of the codomain category with\nobjects the image of object map of the functor and as morphisms image of the arrow\nmap of the functor closed under composition. That is, each morphism in the image\ncategory is a morphism that corresponds to a composable chain of morohisms in the\nimage of the arrow map of the functor.\n\n*)\nSection Functor_Image.\n  Context {C D : Category}\n          (F : (C –≻ D)%functor).\n\n  Local Open Scope morphism_scope.\n\n  Program Definition Functor_Image :=\n    SubCategory D\n                (fun a => ∃ x, (F _o x)%object = a)\n                (\n                  fun a b f =>\n                    ∃ (ch : Composable_Chain D a b),\n                      (Compose_of ch) = f\n                      ∧\n                      Forall_Links ch (\n                                     fun x y g =>\n                                     ∃ (c d : Obj) (h : c –≻ d)\n                                       (Fca : (F _o c)%object = x) (Fdb : (F _o d)%object = y),\n                                       match Fca in (_ = Z) return Z –≻ _ with\n                                         idpath =>\n                                         match Fdb in (_ = Y) return _ –≻ Y with\n                                           idpath => (F _a h)%morphism\n                                         end\n                                       end = g)\n                )\n                _ _.\n\n  Ltac destr_exists :=\n    progress\n    (repeat\n       match goal with\n         [H : ∃ x, _ |- _] =>\n         let x := fresh \"x\" in\n         let Hx := fresh \"H\" x in\n         destruct H as [x Hx]\n       end).\n  \n  Next Obligation. (* Hom_Cri_id *)\n  Proof.\n    destr_exists.\n    ElimEq.\n    exists (Single (F _a id)); simpl; split; auto.\n    do 3 eexists; do 2 exists eq_refl; reflexivity.\n  Qed.\n\n  Next Obligation. (* Hom_Cri_compose *)\n  Proof.\n    destr_exists.\n    intuition.\n    ElimEq.\n    match goal with\n        [ch1 : Composable_Chain _ ?a ?b, ch2 : Composable_Chain _ ?b ?c|- _] =>\n        exists (Chain_Compose ch1 ch2); split\n    end.\n    rewrite <- Compose_of_Chain_Compose; trivial.\n    apply Forall_Links_Chain_Compose; auto.\n  Qed.\n\nEnd Functor_Image.\n*)", "meta": {"author": "amintimany", "repo": "Categories-HoTT", "sha": "fd6018c7abd496b44fd31b1119f6b31795c251d8", "save_path": "github-repos/coq/amintimany-Categories-HoTT", "path": "github-repos/coq/amintimany-Categories-HoTT/Categories-HoTT-fd6018c7abd496b44fd31b1119f6b31795c251d8/Functor/Functor_Image.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.6997606924248088}}
{"text": "Require Import Braun.common.log Braun.common.le_util.\nRequire Import Arith Coq.Arith.Mult Arith.Even Arith.Div2 Omega.\n\n(* big_oh and big_omega definitions based on _Introduction to           *)\n(* Algorithms_, 3rd Edition by Thomas H. Cormen, Charles E. Leiserson,  *)\n(* Ronald L. Rivest, Clifford Stein                                     *)\n(*                                                                      *)\n(* but more restrictive in the big_oh case, since we allow only         *)\n(* natural number constants. In the big_omega case we effectively       *)\n(* allow rational number 'c's, but do it by asking for an explicit      *)\n(* numerator and denominator and then multiplying through by the        *)\n(* denominator to avoid needing to use rational numbers.                *)\n\nDefinition big_oh f g :=\n  exists n0 c,\n    forall n,\n      n0 <= n ->\n      f(n) <= c * g(n).\n\nDefinition big_O2 f g :=\n  exists l c,\n    forall n m,\n      l <= n -> l <= m ->\n      f n m <= c * g n m.\n\nDefinition big_omega f g :=\n  exists n0 c_num c_den,\n    c_num > 0 /\\\n    forall n,\n      n >= n0 ->\n      c_num * g(n) <= c_den * f(n).\n\nDefinition big_theta f g :=\n  big_oh f g /\\ big_omega f g.\n\nLemma big_oh_rev : \n  forall f g,\n    big_oh g f ->\n    big_omega f g.\nProof.\n  intros f g [n0 [m BIGOH_IMP]].\n  exists n0.\n  exists 1.\n  exists m.\n  split. auto.\n  intros n LT.\n  remember (BIGOH_IMP n LT) as LT2; clear HeqLT2.\n  clear LT BIGOH_IMP n0.\n  rewrite mult_1_l.\n  auto.\nQed.\n\nLemma big_oh_trans :\n  forall f g h,\n    big_oh f g ->\n    big_oh g h ->\n    big_oh f h.\nProof.\n  intros f g h [FGn [FGm FGP]] [GHn [GHm GHP]].\n  exists (FGn+GHn).\n  exists (FGm*GHm).\n  intros n LE.\n  apply (le_trans (f n)\n                  (FGm * g n)\n                  (FGm * GHm * h n)).\n  apply FGP.\n  omega.\n  rewrite <- mult_assoc.\n  apply le_mult_right.\n  apply GHP.\n  omega.\nQed.\n\nLemma big_O2_trans :\n  forall f g h,\n    big_O2 f g ->\n    big_O2 g h ->\n    big_O2 f h.\nProof.\n  intros f g h [FGn [FGm FGP]] [GHn [GHm GHP]].\n  exists (FGn+GHn).\n  exists (FGm*GHm).\n  intros n m LEn LEm.\n  apply (le_trans (f n m)\n                  (FGm * g n m)\n                  (FGm * GHm * h n m)).\n  apply FGP.\n  omega.\n  omega.\n  rewrite <- mult_assoc.\n  apply le_mult_right.\n  apply GHP.\n  omega.\n  omega.\nQed.\n\nLemma big_oh_k_1: forall k, 1 <= k -> big_oh (fun n => 1) (fun n => k).\nProof.\n  intros k LE.\n  unfold big_oh.\n  exists 0.\n  exists 1.\n  intros n.\n  omega.\nQed.\n\nLemma big_omega_k_1: forall k, 1 <= k -> big_omega (fun n => 1) (fun n => k).\nProof.\n  intros k LE.\n  unfold big_omega.\n  exists 0.\n  exists 1.\n  exists k.\n  split. auto.\n  intros n.\n  omega.\nQed.\n\nLemma big_theta_k_1: forall k, 1 <= k -> big_theta (fun n => 1) (fun n => k).\nProof.\n  intros k LE. split.\n  apply big_oh_k_1. auto.\n  apply big_omega_k_1. auto.\nQed.\n\nLemma big_oh_fl_log_plus_1 : big_oh (fun n => (fl_log n + 1)) fl_log.\nProof.\n  exists 1.\n  exists 2.\n  intros n LE.\n  destruct n; intuition.\n  destruct n; intuition.\n  rewrite <- fl_log_div2.\n  omega.\nQed.\n\nLemma big_oh_nlogn_plus_n__nlogn :\n  big_oh (fun n : nat => n * fl_log n + n) (fun n : nat => n * fl_log n).\nProof.\n  exists 2.\n  exists 2.\n  intros n L.\n  destruct n; intuition.\n  destruct n; intuition.\n  clear L.\n  replace 2 with (1+1); try omega.\n  rewrite mult_plus_distr_r.\n  unfold mult; fold mult.\n  rewrite plus_0_r.\n\n  assert (1 <= fl_log (S (S n))).\n  induction n.\n  rewrite fl_log_div2'.\n  omega.\n  apply (le_trans 1 (fl_log (S (S n))) (fl_log (S (S (S n))))); auto.\n  apply fl_log_monotone_Sn.\n\n  apply le_plus_right.\n  apply (le_trans (S (S n))\n                  (1 + 1 + n * fl_log (S (S n)))\n                  (fl_log (S (S n)) + (fl_log (S (S n)) + n * fl_log (S (S n))))); try omega.\n  apply (le_trans (S (S n))\n                  (1 + 1 + n * 1)\n                  (1 + 1 + n * fl_log (S (S n)))); try omega.\n  rewrite mult_comm.\n  apply le_plus_right.\n  rewrite mult_comm at 1.\n  apply le_mult_right.\n  assumption.\nQed.\n\nLemma big_oh_k___nlogn : \n forall k, big_oh (fun _ => k) (fun n => n * cl_log n).\nProof.\n  intros k.\n  exists k.\n  exists 1.\n  intros n LT.\n  rewrite mult_1_l.\n  apply (le_trans k n); auto.\n  clear k LT.\n  destruct n.\n  omega.\n  replace (S n) with (S n * 1) at 1;[|omega].\n  apply mult_le_compat; auto.\n  induction n.\n  unfold_sub cl_log (cl_log 1).\n  omega.\n  apply (le_trans 1 (cl_log (S n))); auto.\n  apply cl_log_monotone.\n  omega.\nQed.\n\nLemma big_oh_mult :\n  forall f g h,\n    big_oh f g ->\n    big_oh (fun x => (h x) * (f x)) (fun x => (h x) * (g x)).\nProof.\n  intros f g n [n0 [m FG]].\n  exists n0.\n  exists m.\n  intros n1 LT.\n  apply FG in LT.\n  rewrite mult_assoc.\n  replace (m * n n1) with (n n1 * m); try (apply mult_comm).\n  rewrite <- mult_assoc.\n  apply le_mult_right.\n  assumption.\nQed.\nHint Resolve big_oh_mult.\n\nLemma big_O2_mult :\n  forall f g h,\n    big_O2 f g ->\n    big_O2 (fun n m => (h n m) * (f n m)) (fun n m => (h n m) * (g n m)).\nProof.\n  intros f g h [k [l FG]].\n  exists k.\n  exists l.\n  intros n1 m1 LTN LTM.\n  apply FG with (n:=n1)(m:=m1) in LTN; auto.\n  rewrite mult_assoc.\n  replace (l* h n1 m1) with (h n1 m1 * l); try (apply mult_comm).\n  rewrite <- mult_assoc.\n  apply le_mult_right.\n  auto.\nQed.\n\nLemma big_oh_plus :\n  forall f g h,\n    big_oh f h -> big_oh g h -> big_oh (fun n => f n + g n) h.\nProof.\n  intros f g h FG GH.\n  destruct FG as [FGn [FGm FG]].\n  destruct GH as [GHn [GHm GH]].\n  exists (FGn + GHn).\n  exists (FGm + GHm).\n  intros n LT.\n  apply (le_trans (f n + g n)\n                  ((FGm * h n) + g n)\n                  ((FGm + GHm) * h n)).\n  apply le_plus_left.\n  apply FG; omega.\n  rewrite mult_plus_distr_r.\n  apply le_plus_right.\n  apply GH; omega.\nQed.\nHint Resolve big_oh_plus.\n\nLemma big_oh_plus_rev : \n  forall f g h,\n    big_oh h f -> big_oh h g -> big_oh h (fun n => f n + g n).\nProof.\n  intros f g h HF HG.\n  destruct HF as [HFn [HFm HF]].\n  destruct HG as [HGn [HGm HG]].\n  exists (HFn + HGn).\n  exists ((S HFm) * (S HGm)).\n  intros n LT.\n  repeat (rewrite mult_plus_distr_l).\n  assert (h n <= HFm * f n) as LTONE;[apply HF;omega|clear HF].\n  assert (h n <= HGm * g n) as LTTWO;[apply HG;omega|clear HG].\n  clear LT.\n  apply (le_trans (h n) (HFm * f n)); auto.\n  replace (S HFm) with (HFm + 1);[|omega].\n  rewrite mult_plus_distr_r.\n  rewrite mult_plus_distr_r.\n  apply le_plus_trans.\n  apply le_plus_trans.\n  clear LTONE LTTWO.\n  induction HGm.\n  rewrite mult_1_r.\n  auto.\n  apply (le_trans (HFm * f n) (HFm * S HGm * f n)).\n  auto.\n  apply mult_le_compat; auto.\n  apply mult_le_compat; auto.\nQed.\n\nLemma big_oh_k_linear : forall k, big_oh (fun n => k) (fun n => n).\nProof.\n  intros k.\n  exists k.\n  exists 1.\n  intros; omega.\nQed.\nHint Resolve big_oh_k_linear.\n\nLemma big_oh_n_nlogn:\n  big_oh (fun n : nat => n) (fun n : nat => n * cl_log n).\nProof.\n  exists 0.\n  exists 1.\n  intros n _.\n  replace (1 * (n * cl_log n)) with (n * cl_log n); [|omega].\n  induction n;[omega|].\n  apply le_n_S in IHn.\n  replace (S n) with (n+1) at 2; [|omega].\n  rewrite mult_plus_distr_r.\n  apply (le_trans (S n) (S (n * cl_log n))); [omega|].\n  clear IHn.\n  replace (S (n * cl_log n)) with ((n * cl_log n)+1);[|omega].\n  apply plus_le_compat.\n  apply mult_le_compat;[omega|].\n  apply cl_log_monotone; omega.\n  rewrite cl_log_div2'.\n  omega.\nQed.\n\nLemma big_oh_add_k_linear : forall k, big_oh (fun n => n + k) (fun n => n).\nProof.\n  intros k.\n  exists 1.\n  exists (S k).\n  intros. \n  destruct n; intuition.\n  replace (S k) with (k + 1); [|omega].\n  rewrite mult_plus_distr_r.\n  replace (k * S n) with (k * (n + 1)).\n  rewrite mult_plus_distr_l.\n  replace (k*1) with k;[|omega].\n  replace (1*S n) with (S n);[|omega].\n  apply (le_trans (S n + k)\n                  (0 + k + S n)\n                  (k*n + k + S n)).\n  omega.\n  apply le_plus_left.\n  apply le_plus_left.\n  apply le_0_n.\n  replace (n + 1) with (S n); [|omega].\n  omega.\nQed.\nHint Resolve big_oh_add_k_linear.\n\nLemma big_oh_mult_k_right_linear : forall k, big_oh (fun n => n*k) (fun n => n).\nProof.\n  intros.\n  exists 0.\n  exists k.\n  intros.\n  rewrite mult_comm.\n  omega.\nQed.\nHint Resolve big_oh_mult_k_right_linear.\n\nLemma big_oh_mult_k_left_linear : forall k, big_oh (fun n => k*n) (fun n => n).\nProof.\n  intros.\n  exists 1.\n  exists k.\n  intros; omega.\nQed.\nHint Resolve big_oh_mult_k_left_linear.\n\nLemma big_oh_add_k:\n  forall f g k,\n    (forall n, 0 < g n) ->\n    big_oh f g ->\n    big_oh (fun n => f n + k) g.\nProof.\n  intros f g k Gpos FG.\n  destruct FG as [N [M FG]].\n  eexists. exists (M + k).\n  intros n LE.\n  apply FG in LE.\n  rewrite mult_plus_distr_r.\n  apply le_add. auto.\n  assert (0 < g n) as Gpos'. auto.\n  destruct (g n) as [|gn].\n  omega.\n  rewrite mult_comm. simpl.\n  replace k with (k + 0); try omega.\n  apply le_add. omega.\n  apply le_0_n.\nQed.\n\nLemma big_oh_add_k_both:\n  forall f g k,\n    big_oh f g ->\n    big_oh (fun n => f n + k) (fun n => g n + k).\nProof.\n  intros f g k FG.\n  destruct FG as [N [M FG]].\n  exists N. exists (S M).\n  intros n LE.\n  apply FG in LE.\n  rewrite mult_plus_distr_l.\n  apply le_add. simpl. omega.\n  clear FG LE f g N n.\n  simpl. \n  replace k with (k + 0); try omega.\n  apply le_add. omega.\n  apply le_0_n.\nQed.\n\nLemma big_theta_mult_plus:\n  forall x y,\n    big_theta (fun n : nat => (S x) * n + y) (fun n : nat => n).\nProof.\n  unfold big_theta. split.\n  unfold big_oh.\n  exists y. exists (S (S x)).\n  intros n LE.\n  simpl. omega.\n\n  apply big_oh_rev.\n  exists 0. exists 1.\n  intros n LE. simpl.\n  replace n with (n + 0); try omega.\n  replace (n + 0 + x * (n + 0) + y + 0) with\n    (n + (0 + x * (n + 0) + y + 0)); try omega.\n  apply le_add. auto.\n  apply le_0_n.\nQed.\n\nLemma big_oh_eq:\n  forall f g,\n    (forall n, f n = g n) ->\n    big_oh f g.\nProof.\n  intros f g EQ.\n  exists 0. exists 1.\n  intros n LE. rewrite EQ. omega.\nQed.\n\nLemma big_theta_eq:\n  forall f g,\n    (forall n, f n = g n) ->\n    big_theta f g.\nProof.\n  intros f g EQ.\n  split. apply big_oh_eq. auto.\n  apply big_oh_rev. apply big_oh_eq. auto.\nQed.\n\nLemma big_omega_rev : \n  forall f g,\n    big_omega g f ->\n    big_oh f g.\nProof.\n  intros f g [n0 [m1 [m2 [GT BIGOM_IMP]]]].\n  exists n0.\n  exists m2.\n  intros n LT.\n  remember (BIGOM_IMP n LT) as LT2; clear HeqLT2.\n  clear LT BIGOM_IMP n0.\n  eapply le_trans; [| apply LT2 ].\n  destruct m1 as [|m1]. omega.\n  rewrite mult_succ_l.\n  apply le_plus_r.\nQed.\n\nLemma big_theta_trans :\n  forall f g h,\n    big_theta f g ->\n    big_theta g h ->\n    big_theta f h.\nProof.\n  intros f g h [Ofg Tfg] [Ogh Tgh].\n  split. eapply big_oh_trans. apply Ofg. auto.\n  apply big_oh_rev. eapply big_oh_trans.\n  apply big_omega_rev. apply Tgh.\n  apply big_omega_rev. apply Tfg.\nQed.\n\n(* because TT'FACT is hard to establish, this seems useless *)\nLemma recurrence_that_sums :\n  forall k k' f f' T T',\n    (forall n, T 0 n = k) ->\n    (forall n, T' 0 n = k') ->\n    (forall fuel n, T (S fuel) n = f n + T fuel (n+1) + 1) ->\n    (forall fuel n, T' (S fuel) n = f' n + T' fuel (n+1) + 1) ->\n    k <= k' ->\n    big_oh f f' ->\n    (forall fuel n k,  T fuel n <= (S k) * T' fuel n -> \n                       T fuel (n+1) <= (S k) * (T' fuel (n+1))) -> \n    exists n,\n      forall n',\n        n <= n' ->\n        big_oh (fun fuel => T fuel n') (fun fuel => T' fuel n').\nProof.\n  intros k k' f f' T T' T0 T'0 TR TR' LTkk' [fn0 [fc FF']] TT'FACT.\n  destruct fc.\n  exists fn0. intros n' NN'. exists 0. exists 1. \n  intros fuel _.\n  rewrite mult_1_l.\n  induction fuel.\n  rewrite T0.\n  rewrite T'0.\n  omega.\n\n  rewrite TR.\n  rewrite TR'.\n  repeat (apply plus_le_compat); auto.\n\n  assert (f n' <= 0);[|omega].\n  replace 0 with (0 * f' n');[|omega].\n  apply FF'.\n  omega.\n  \n  replace (T' fuel (n' + 1)) with (1*(T' fuel (n' + 1)));[|omega].\n  apply TT'FACT;omega.\n\n  exists fn0. \n  intros n' NN'. exists 0. exists (1+fc).\n  intros fuel _.\n  induction fuel.\n  rewrite T0.\n  rewrite T'0.\n  rewrite mult_plus_distr_r.\n  apply le_plus_trans.\n  omega.\n\n  rewrite TR.\n  rewrite TR'.\n  repeat (rewrite mult_plus_distr_l).\n  repeat (apply plus_le_compat); auto.\n  omega.\nQed.\n\nLemma recurrence_that_sums' :\n  forall k k' f f' T T',\n    (forall n, T 0 n = k) ->\n    (forall n, T' 0 n = k') ->\n    (forall fuel n, T (S fuel) n = f n + T fuel n) ->\n    (forall fuel n, T' (S fuel) n = f' n + T' fuel n) ->\n    k <= k' ->\n    big_oh f f' ->\n    exists n,\n      forall n',\n        n <= n' ->\n        big_oh (fun fuel => T fuel n') (fun fuel => T' fuel n').\nProof.\n  intros k k' f f' T T' T0 T'0 TR TR' LTkk' [fn0 [fc FF']].\n  destruct fc.\n  exists fn0. intros n' NN'. exists 0. exists 1. \n  intros fuel _.\n  rewrite mult_1_l.\n  induction fuel.\n  rewrite T0.\n  rewrite T'0.\n  omega.\n\n  rewrite TR.\n  rewrite TR'.\n  apply plus_le_compat; auto.\n  assert (f n' <= 0);[|omega].\n  replace 0 with (0 * f' n');[|omega].\n  apply FF'.\n  omega.\n\n  exists fn0. \n  intros n' NN'. exists 0. exists (1+fc).\n  intros fuel _.\n  induction fuel.\n  rewrite T0.\n  rewrite T'0.\n  rewrite mult_plus_distr_r.\n  apply le_plus_trans.\n  omega.\n\n  rewrite TR.\n  rewrite TR'.\n  rewrite mult_plus_distr_l.\n  apply plus_le_compat; auto.\nQed.\n\nTheorem cl_log_O_fl_log : big_oh cl_log fl_log.\nProof.\n  exists 2.\n  exists 2.\n  intros.\n  destruct n.\n  intuition.\n  rewrite <- fl_log_cl_log_relationship.\n  replace (S (fl_log n)) with (fl_log n + 1);[|omega].\n  replace (2*(fl_log (S n))) with (fl_log (S n) + fl_log (S n));[|omega].\n  apply plus_le_compat.\n  apply fl_log_monotone.\n  auto.\n  replace 1 with (fl_log 1).\n  apply fl_log_monotone.\n  omega.\n  compute.\n  auto.\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/big_oh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.6997606920135973}}
{"text": "Require Import Arith List String.\n\n(* Simple functional language *)\nInductive term :=\n  | Var: string -> term\n  | Nat : nat -> term\n  | Plus : term -> term -> term\n  | IfZero: term -> term -> term -> term\n.\n\nDefinition Env := list (string * nat).\n\nAxiom string_eq : string -> string -> bool.\nHypothesis string_eq_spec: forall s t, string_eq s t = true <-> s = t.\n\nFixpoint mem {T: Type} (env: list (string * T)) (key: string) : option T :=\n    match env with\n    | nil => None\n    | (id, val) :: tl =>\n        if string_eq key id then Some val else mem tl key\n    end.\n\nFixpoint eval (env: Env) t : option nat :=\n match t with\n | Var x => mem env x\n | Nat n => Some n\n | Plus a b => \n     match (eval env a, eval env b) with\n     | (Some u, Some v) => Some (u + v)\n     | _ => None\n     end\n | IfZero test then_branch else_branch =>\n     match eval env test with\n     | Some 0 => eval env then_branch\n     | Some _ => eval env else_branch\n     | None => None\n     end\nend.\n\nInductive ok : Env -> term -> Prop :=\n | okVar: forall env x, mem env x <> None -> ok env (Var x)\n | okNat: forall env n, ok env (Nat n)\n | okPlus: forall env a b, ok env a ->\n         ok env b ->\n         ok env (Plus a b)\n | okIfZero: forall env test then_branch else_branch,\n         ok env test ->\n         ok env then_branch ->\n         ok env else_branch ->\n         ok env (IfZero test then_branch else_branch)\n.\n\nHint Constructors ok.\n\nLemma wf: forall env t, ok env t ->\n    exists v, eval env t = Some v.\nProof.\ninduction 1 as [ env x hmem | env n | env a b ha [va hia] hb [vb hib] |\n        env t l r ht [vt hit] hl [vl hil] hr [vr hir]]; simpl in *.\n- now destruct (mem env x) as [ v | ]; [exists v | elim hmem].\n- now exists n.\n- rewrite hia, hib.\n  now exists (va + vb).\n- rewrite hit.\n  now destruct vt; [rewrite hil; exists vl | rewrite hir; exists vr].\nQed.\n", "meta": {"author": "vsiles", "repo": "random_coq_stuff", "sha": "4392a2b9d5931b0c046132f4758bdbbd3700a6e9", "save_path": "github-repos/coq/vsiles-random_coq_stuff", "path": "github-repos/coq/vsiles-random_coq_stuff/random_coq_stuff-4392a2b9d5931b0c046132f4758bdbbd3700a6e9/first_contact/2-embeddings.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.6997606871885151}}
{"text": "Require Iso.\nRequire Fin.\n\nSet Asymmetric Patterns.\n\n(** A type family which is isomorphic to Fin.t, but defined in\n    terms of simpler types by recursion, and is a little bit\n    easier to work with. *)\nFixpoint Fin (n : nat) : Set := match n with\n  | 0 => Empty_set\n  | S n' => (unit + Fin n')%type\n  end.\n\n(** Fin and Fin.t are isomorphic for every size. *)\nTheorem finIso (n : nat) : Iso.T (Fin.t n) (Fin n).\nProof.\ninduction n.\n- eapply Iso.Build_T.\n  intros a. inversion a.\n  intros b. inversion b. \n- \nrefine (\n{| Iso.to := fun x => (match x in Fin.t n'\n  return (S n = n') -> Fin (S n) with\n   | Fin.F1 _ => fun _ => inl tt\n   | Fin.FS n' x' => fun pf => inr (Iso.to IHn (eq_rect n' Fin.t x' _ (eq_sym (eq_add_S _ _ pf))))\n   end) eq_refl\n ; Iso.from := fun x => match x with\n   | inl tt => Fin.F1\n   | inr x' => Fin.FS (Iso.from IHn x')\n   end\n|}).\nintros a.\nRequire Import Program.\ndependent destruction a; simpl.\nreflexivity. rewrite Iso.from_to. reflexivity.\nintros b. destruct b. destruct u. reflexivity.\n  simpl. rewrite Iso.to_from. reflexivity.\nGrab Existential Variables.\nintros bot. contradiction.\nintros f0. inversion f0.\nDefined.\n\nLemma botNull (A : Type) : Iso.T A (A + Empty_set).\nProof.\nrefine (\n{| Iso.to   := inl\n ; Iso.from := fun x => match x with\n    | inl x' => x'\n    | inr bot => Empty_set_rect (fun _ => A) bot\n   end\n|}).\nreflexivity.\nintros b. destruct b. reflexivity. contradiction.\nQed.\n\nFixpoint split (m : nat)\n  : forall (n : nat), Fin.t (m + n) -> (Fin.t m + Fin.t n).\nrefine (\n  match m return (forall (n : nat), Fin.t (m + n) -> (Fin.t m + Fin.t n)) with\n  | 0 => fun _ => inr\n  | S m' => fun n x => (match x as x0 in Fin.t k \n    return forall (pf : k = (S m' + n)), (Fin.t (S m') + Fin.t n) with\n    | Fin.F1 _ => fun pf => inl Fin.F1\n    | Fin.FS n' x' => fun pf => _\n    end) eq_refl\n  end).\nsimpl in pf.\napply eq_add_S in pf.\nrewrite pf in x'.\nrefine (match split m' n x' with\n  | inl a => inl (Fin.FS a)\n  | inr b => inr b\n  end).\nDefined.\n\nLemma splitL : forall {m n : nat} {x : Fin.t m},\n  split m n (Fin.L n x) = inl x.\nProof.\nintros m. induction m; intros n x.\n- inversion x.\n- dependent destruction x; simpl.\n  + reflexivity.\n  + rewrite (IHm n x). reflexivity.\nQed.\n\nLemma splitR : forall {m n : nat} {x : Fin.t n},\n  split m n (Fin.R m x) = inr x.\nProof.\nintros m. induction m; intros n x; simpl.\n- reflexivity.\n- rewrite (IHm n x). reflexivity.\nQed.\n\nLemma splitInj : forall {m n : nat} {x y : Fin.t (m + n)},\n  split m n x = split m n y -> x = y.\nProof.\nintros m; induction m; intros n x y Heq.\n- inversion Heq. reflexivity.\n- dependent destruction x; dependent destruction y.\n  + reflexivity.\n  + simpl in Heq. destruct (split m n y); inversion Heq.\n  + simpl in Heq. destruct (split m n x); inversion Heq.\n  + apply f_equal. simpl in Heq. apply IHm.\n    destruct (split m n x) eqn:sx;\n    destruct (split m n y) eqn:sy.\n    apply f_equal. \n    assert (forall (A B : Type) (x y : A), @inl A B x = @inl A B y -> x = y).\n    intros A B x0 y0 Heqn. inversion Heqn. reflexivity.\n    apply H in Heq. apply Fin.FS_inj in Heq. assumption.\n    inversion Heq. inversion Heq. apply f_equal. injection Heq. trivial.\nQed.\n\nFixpoint splitMult (m : nat)\n  : forall (n : nat), Fin.t (m * n) -> (Fin.t m * Fin.t n) \n  := match m return (forall (n : nat), Fin.t (m * n) -> (Fin.t m * Fin.t n)) with\n  | 0 => fun _ => Fin.case0 _\n  | S m' => fun n x => match split n (m' * n) x with\n    | inl a => (Fin.F1, a)\n    | inr b => match splitMult m' n b with\n      | (x, y) => (Fin.FS x, y)\n      end\n    end\n  end.\n\n\nLemma finPlus : forall {m n : nat},\n  Iso.T (Fin.t m + Fin.t n) (Fin.t (m + n)).\nProof.\nintros m n.\nrefine (\n{| Iso.to := fun x => match x with\n   | inl a => Fin.L n a\n   | inr b => Fin.R m b\n   end\n ; Iso.from := split m n\n|}).\nintros. destruct a; simpl. induction m; simpl.\n- inversion t.\nRequire Import Program.\n- dependent destruction t; simpl.\n  + reflexivity.\n  + rewrite IHm. reflexivity.\n- induction m; simpl. reflexivity. rewrite IHm. reflexivity.\n- induction m; intros; simpl.\n  + reflexivity.\n  + dependent destruction b; simpl. reflexivity.\n     pose proof (IHm b).\n     destruct (split m n b) eqn:seqn;\n     simpl; rewrite H; reflexivity.\nQed.\n\nLemma finMult : forall {m n : nat},\n  Iso.T (Fin.t m * Fin.t n) (Fin.t (m * n)).\nProof.\nintros m n.\nrefine (\n{| Iso.to := fun x => match x with (a, b) => Fin.depair a b end\n ; Iso.from := splitMult m n\n|}).\nintros p. destruct p.\ninduction m; simpl.\n- inversion t.\n- dependent destruction t; simpl.\n  + rewrite splitL. reflexivity.\n  + rewrite splitR. rewrite (IHm t). reflexivity.\n\n- induction m; intros b; simpl.\n  + inversion b.\n  + destruct (split n (m * n) b) eqn:seqn.\n    * simpl. rewrite <- splitL in seqn. \n      apply splitInj in seqn. symmetry. assumption.\n    * pose proof (IHm t). assert (b = Fin.R n t).\n      apply (@splitInj n (m * n)). \n      rewrite seqn. symmetry. apply splitR.\n      rewrite H0. simpl.\n      destruct (splitMult m n t) eqn:smeqn.\n      simpl. rewrite <- H. reflexivity.\nDefined.\n\nFixpoint pow (b e : nat) : nat := match e with\n  | 0 => 1\n  | S e' => b * pow b e'\n  end.\n\nTheorem finPow : forall {e b : nat},\n  Iso.T (Fin.t (pow b e)) (Fin.t e -> Fin.t b).\nProof.\nintros e. induction e; intros n; simpl.\n- eapply Iso.Trans. apply finIso. simpl. eapply Iso.Trans.\n  eapply Iso.Sym. apply botNull. eapply Iso.Trans. Focus 2.\n  eapply Iso.FuncCong. eapply Iso.Sym. apply finIso. apply Iso.Refl.\n  simpl. apply Iso.Sym. apply Iso.FFunc.\n- eapply Iso.Trans. eapply Iso.Sym. apply finMult.\n  eapply Iso.Trans. Focus 2. eapply Iso.FuncCong.\n  eapply Iso.Sym. apply finIso. apply Iso.Refl.\n  simpl. eapply Iso.Trans. Focus 2. eapply Iso.Sym. eapply Iso.PlusFunc.\n  apply Iso.TFunc. eapply Iso.Trans. eapply Iso.FuncCong.\n  eapply Iso.Sym. apply finIso. apply Iso.Refl. eapply Iso.Sym.\n  apply IHe. apply Iso.Refl.\nQed.\n\n(** A universe of codes for finite types. *)\nInductive U : Set :=\n  | U0    : U\n  | U1    : U\n  | UPlus : U -> U -> U\n  | UTimes : U -> U -> U\n  | UFunc : U -> U -> U\n  | UFint : nat -> U\n  | UFin : nat -> U.\n\n(** The types which the codes of U represent. *)\nFixpoint ty (t : U) : Set := match t with\n  | U0 => Empty_set\n  | U1 => unit\n  | UPlus a b => (ty a + ty b)%type\n  | UTimes a b => (ty a * ty b)%type\n  | UFunc a b => ty a -> ty b\n  | UFint n => Fin.t n\n  | UFin n => Fin n\n  end.\n\n(** For every code for a finite type, we give its cardinality as\n    a natural number. *)\nFixpoint card (t : U) : nat := match t with\n  | U0 => 0\n  | U1 => 1\n  | UPlus a b => card a + card b\n  | UTimes a b => card a * card b\n  | UFunc a b => pow (card b) (card a)\n  | UFint n => n\n  | UFin n => n\n  end.\n    \n(** Each type in the finite universe is isomorphic to the Fin.t\n    family whose size is determined by the cardinality function above. *)\nTheorem finChar (t : U) : Iso.T (ty t) (Fin.t (card t)).\nProof.\ninduction t; simpl.\n- apply Iso.Sym. apply (finIso 0).\n- apply Iso.Sym. apply (@Iso.Trans _ (Fin 1)). apply (finIso 1).\n  apply Iso.Sym. apply botNull.\n- eapply Iso.Trans. eapply Iso.PlusCong. eassumption.\n  eassumption.\n  apply finPlus.\n- eapply Iso.Trans. eapply Iso.TimesCong; try eassumption.\n  apply finMult.\n- eapply Iso.Trans. eapply Iso.FuncCong; try eassumption.\n  apply Iso.Sym. apply finPow.\n- apply Iso.Refl.\n- apply Iso.Sym. apply finIso.\nQed.\n\n(** A type for evidence that a type is finite: a type is finite if\n    any of the following hold:\n    a) it is unit\n    b) it is Empty_set\n    c) it is a sum of finite types\n    d) it is isomorphic to a finite type\n\n    This is not minimal. We could have replaced b) and c) with the condition\n    e) it is the sum of unit with a finite type\n       (this is the analog of Successor)\n    But this definition is simple so I like it.\n*)\n\nInductive T : Type -> Type :=\n  | F0 : T Empty_set\n  | FS : forall {A}, T A -> T (unit + A)\n  | FIso : forall {A B}, T A -> Iso.T A B -> T B\n.\n\nDefinition fin (n : nat) : T (Fin.t n).\nProof. eapply FIso. Focus 2. eapply Iso.Sym. eapply finIso.\ninduction n; simpl.\n- apply F0.\n- apply FS. assumption.\nQed.\n\nDefinition finU (A : U) : T (ty A).\nProof. \neapply FIso. Focus 2. eapply Iso.Sym. apply finChar.\napply fin.\nQed.\n\nDefinition iso {A : Type} : T A -> sigT (fun n => Iso.T A (Fin.t n)).\nProof.\nintros. induction X.\n-  exists 0. apply (finChar U0).\n- destruct IHX. exists (S x). apply Iso.Sym. eapply Iso.Trans. \n  apply finIso. simpl. apply Iso.PlusCong. apply Iso.Refl.\n  eapply Iso.Trans. eapply Iso.Sym. apply finIso. apply Iso.Sym.\n  assumption.\n- destruct IHX. exists x. eapply Iso.Trans. eapply Iso.Sym. eassumption.\n  assumption. \nQed.\n\nDefinition true : T unit := finU U1.\n\nDefinition plus {A B : Type} (fa : T A) (fb : T B) : T (A + B).\nProof.\ndestruct (iso fa), (iso fb).\neapply (@FIso (Fin.t (x + x0))). apply (finU (UFint (x + x0))).\neapply Iso.Trans. eapply Iso.Sym. apply finPlus.\neapply Iso.PlusCong; eapply Iso.Sym; eassumption.\nQed.\n\nLemma finiteSig {A : Type} (fa : T A)\n  : forall {B : A -> Type}, \n  (forall (x : A), T (B x))\n  -> sigT (fun S => (T S * Iso.T (sigT B) S)%type).\nProof.\ninduction fa; intros b fb.\n- exists Empty_set. split. constructor. apply Iso.FSig.\n- pose proof (IHfa (fun x => b (inr x)) (fun x => fb (inr x))).\n  destruct X. destruct p.\n  exists (b (inl tt) + x)%type. constructor. apply plus. apply fb.\n  assumption.\n  apply Iso.PlusSig. apply (@Iso.TSig (fun x => b (inl x))). \n  assumption.\n- pose (Iso.Sym t).\n  pose proof (IHfa (fun x => b (Iso.from t0 x))\n                   (fun x => fb (Iso.from t0 x))).\n  destruct X. destruct p.\n  exists x. split. assumption.\n  eapply Iso.Trans. Focus 2. apply t2.\n  admit.\n  (* Here we need Iso.sigmaProp, which we have yet to prove,\n     so we cannot finish the proof here. *)\n  (*apply Iso.sigmaProp.*)\nAdmitted.\n\n(** Sigma types are closed under finiteness. *)\nTheorem sig {A : Type} {B : A -> Type} \n  : T A \n  -> (forall (x : A), T (B x))\n  -> T (sigT B).\nProof.\nintros fA fB.\npose proof (finiteSig fA fB).\ndestruct X. destruct p.\neapply FIso. apply t.\napply Iso.Sym. assumption.\nDefined.\n\n(** Product types are closed under finiteness. *)\nTheorem times {A B : Type} : T A -> T B -> T (A * B).\nProof.\nintros fa fb.\neapply FIso. Focus 2. eapply Iso.Sym. eapply Iso.sigTimes.\napply sig. assumption. apply (fun _ => fb).\nDefined.\n\nLemma finiteMapped {A : Type} (fa : T A)\n  : forall {B : Type}, T B -> sigT (fun S => (T S * Iso.T (A -> B) S)%type).\nProof.\ninduction fa.\n- intros. exists unit. apply (true, Iso.FFunc).\n- intros B fb.\n  destruct (IHfa B fb).\n  exists (B * x)%type.\n  destruct p.\n  apply (times fb t , Iso.PlusFunc Iso.TFunc t0).\n- intros B1 fb.\n  destruct (IHfa B1 fb).\n  destruct p.\n  exists x.\n  split.\n  assumption.  \n  eapply Iso.Trans.\n  eapply Iso.Sym.\n  apply (Iso.FuncCong t (Iso.Refl B1)).\n  assumption.\nDefined.\n\n(** Functions are closed under finiteness. *)\nTheorem func {A B : Type} : T A -> T B -> T (A -> B).\nProof.\nintros FA FB.\npose proof (finiteMapped FA FB).\ndestruct X.\ndestruct p.\neapply FIso.\neassumption.\napply Iso.Sym.\nassumption.\nDefined.\n\n(** Any finite type has decidable equality. *)\nTheorem eq_dec {A : Type} : T A -> forall a b : A, {a = b} + {a <> b}.\nProof.\nintros finite.\ninduction finite; intros; try (decide equality).\n- destruct a0, u; auto.\n- eapply Iso.eq_dec; eassumption.\nQed.", "meta": {"author": "tchajed", "repo": "cardinality", "sha": "9ba233ed1c0b927a19865e60abf65328def49405", "save_path": "github-repos/coq/tchajed-cardinality", "path": "github-repos/coq/tchajed-cardinality/cardinality-9ba233ed1c0b927a19865e60abf65328def49405/Finite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.699722066003624}}
{"text": "(* -*- coding: utf-8 -*- *)\n(************************************************************************)\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 BinPos PeanoNat.\n\n(** Properties of the injection from binary positive numbers\n    to Peano natural numbers *)\n\n(** Original development by Pierre Crégut, CNET, Lannion, France *)\n\nLocal Open Scope positive_scope.\nLocal Open Scope nat_scope.\n\nModule Pos2Nat.\n Import Pos.\n\n(** [Pos.to_nat] is a morphism for successor, addition, multiplication *)\n\nLemma inj_succ p : to_nat (succ p) = S (to_nat p).\nProof.\n unfold to_nat. rewrite iter_op_succ. trivial.\n apply Nat.add_assoc.\nQed.\n\nTheorem inj_add p q : to_nat (p + q) = to_nat p + to_nat q.\nProof.\n revert q. induction p using peano_ind; intros q.\n now rewrite add_1_l, inj_succ.\n now rewrite add_succ_l, !inj_succ, IHp.\nQed.\n\nTheorem inj_mul p q : to_nat (p * q) = to_nat p * to_nat q.\nProof.\n revert q. induction p using peano_ind; simpl; intros; trivial.\n now rewrite mul_succ_l, inj_add, IHp, inj_succ.\nQed.\n\n(** Mapping of xH, xO and xI through [Pos.to_nat] *)\n\nLemma inj_1 : to_nat 1 = 1.\nProof.\n reflexivity.\nQed.\n\nLemma inj_xO p : to_nat (xO p) = 2 * to_nat p.\nProof.\n exact (inj_mul 2 p).\nQed.\n\nLemma inj_xI p : to_nat (xI p) = S (2 * to_nat p).\nProof.\n now rewrite xI_succ_xO, inj_succ, inj_xO.\nQed.\n\n(** [Pos.to_nat] maps to the strictly positive subset of [nat] *)\n\nLemma is_succ : forall p, exists n, to_nat p = S n.\nProof.\n induction p using peano_ind.\n now exists 0.\n destruct IHp as (n,Hn). exists (S n). now rewrite inj_succ, Hn.\nQed.\n\n(** [Pos.to_nat] is strictly positive *)\n\nLemma is_pos p : 0 < to_nat p.\nProof.\n destruct (is_succ p) as (n,->). auto with arith.\nQed.\n\n(** [Pos.to_nat] is a bijection between [positive] and\n    non-zero [nat], with [Pos.of_nat] as reciprocal.\n    See [Nat2Pos.id] below for the dual equation. *)\n\nTheorem id p : of_nat (to_nat p) = p.\nProof.\n induction p using peano_ind. trivial.\n rewrite inj_succ. rewrite <- IHp at 2.\n now destruct (is_succ p) as (n,->).\nQed.\n\n(** [Pos.to_nat] is hence injective *)\n\nLemma inj p q : to_nat p = to_nat q -> p = q.\nProof.\n intros H. now rewrite <- (id p), <- (id q), H.\nQed.\n\nLemma inj_iff p q : to_nat p = to_nat q <-> p = q.\nProof.\n split. apply inj. intros; now subst.\nQed.\n\n(** [Pos.to_nat] is a morphism for comparison *)\n\nLemma inj_compare p q : (p ?= q)%positive = (to_nat p ?= to_nat q).\nProof.\n revert q. induction p as [ |p IH] using peano_ind; intros q.\n - destruct (succ_pred_or q) as [Hq|Hq]; [now subst|].\n   rewrite <- Hq, lt_1_succ, inj_succ, inj_1, Nat.compare_succ.\n   symmetry. apply Nat.compare_lt_iff, is_pos.\n - destruct (succ_pred_or q) as [Hq|Hq]; [subst|].\n   rewrite compare_antisym, lt_1_succ, inj_succ. simpl.\n   symmetry. apply Nat.compare_gt_iff, is_pos.\n   now rewrite <- Hq, 2 inj_succ, compare_succ_succ, IH.\nQed.\n\n(** [Pos.to_nat] is a morphism for [lt], [le], etc *)\n\nLemma inj_lt p q : (p < q)%positive <-> to_nat p < to_nat q.\nProof.\n unfold lt. now rewrite inj_compare, Nat.compare_lt_iff.\nQed.\n\nLemma inj_le p q : (p <= q)%positive <-> to_nat p <= to_nat q.\nProof.\n unfold le. now rewrite inj_compare, Nat.compare_le_iff.\nQed.\n\nLemma inj_gt p q : (p > q)%positive <-> to_nat p > to_nat q.\nProof.\n unfold gt. now rewrite inj_compare, Nat.compare_gt_iff.\nQed.\n\nLemma inj_ge p q : (p >= q)%positive <-> to_nat p >= to_nat q.\nProof.\n unfold ge. now rewrite inj_compare, Nat.compare_ge_iff.\nQed.\n\n(** [Pos.to_nat] is a morphism for subtraction *)\n\nTheorem inj_sub p q : (q < p)%positive ->\n to_nat (p - q) = to_nat p - to_nat q.\nProof.\n intro H. apply Nat.add_cancel_r with (to_nat q).\n rewrite Nat.sub_add.\n now rewrite <- inj_add, sub_add.\n now apply Nat.lt_le_incl, inj_lt.\nQed.\n\nTheorem inj_sub_max p q :\n to_nat (p - q) = Nat.max 1 (to_nat p - to_nat q).\nProof.\n destruct (ltb_spec q p).\n - (* q < p *)\n   rewrite <- inj_sub by trivial.\n   now destruct (is_succ (p - q)) as (m,->).\n - (* p <= q *)\n   rewrite sub_le by trivial.\n   apply inj_le, Nat.sub_0_le in H. now rewrite H.\nQed.\n\nTheorem inj_pred p : (1 < p)%positive ->\n to_nat (pred p) = Nat.pred (to_nat p).\nProof.\n intros. now rewrite <- Pos.sub_1_r, inj_sub, Nat.sub_1_r.\nQed.\n\nTheorem inj_pred_max p :\n to_nat (pred p) = Nat.max 1 (Peano.pred (to_nat p)).\nProof.\n rewrite <- Pos.sub_1_r, <- Nat.sub_1_r. apply inj_sub_max.\nQed.\n\n(** [Pos.to_nat] and other operations *)\n\nLemma inj_min p q :\n to_nat (min p q) = Nat.min (to_nat p) (to_nat q).\nProof.\n unfold min. rewrite inj_compare.\n case Nat.compare_spec; intros H; symmetry.\n - apply Nat.min_l. now rewrite H.\n - now apply Nat.min_l, Nat.lt_le_incl.\n - now apply Nat.min_r, Nat.lt_le_incl.\nQed.\n\nLemma inj_max p q :\n to_nat (max p q) = Nat.max (to_nat p) (to_nat q).\nProof.\n unfold max. rewrite inj_compare.\n case Nat.compare_spec; intros H; symmetry.\n - apply Nat.max_r. now rewrite H.\n - now apply Nat.max_r, Nat.lt_le_incl.\n - now apply Nat.max_l, Nat.lt_le_incl.\nQed.\n\nTheorem inj_iter :\n  forall p {A} (f:A->A) (x:A),\n    Pos.iter f x p = nat_rect _ x (fun _ => f) (to_nat p).\nProof.\n induction p using peano_ind.\n - trivial.\n - intros. rewrite inj_succ, iter_succ. \n  simpl. f_equal. apply IHp.\nQed.\n\nEnd Pos2Nat.\n\nModule Nat2Pos.\n\n(** [Pos.of_nat] is a bijection between non-zero [nat] and\n    [positive], with [Pos.to_nat] as reciprocal.\n    See [Pos2Nat.id] above for the dual equation. *)\n\nTheorem id (n:nat) : n<>0 -> Pos.to_nat (Pos.of_nat n) = n.\nProof.\n induction n as [|n H]; trivial. now destruct 1.\n intros _. simpl Pos.of_nat. destruct n. trivial.\n rewrite Pos2Nat.inj_succ. f_equal. now apply H.\nQed.\n\nTheorem id_max (n:nat) : Pos.to_nat (Pos.of_nat n) = max 1 n.\nProof.\n destruct n. trivial. now rewrite id.\nQed.\n\n(** [Pos.of_nat] is hence injective for non-zero numbers *)\n\nLemma inj (n m : nat) : n<>0 -> m<>0 -> Pos.of_nat n = Pos.of_nat m -> n = m.\nProof.\n intros Hn Hm H. now rewrite <- (id n), <- (id m), H.\nQed.\n\nLemma inj_iff (n m : nat) : n<>0 -> m<>0 ->\n (Pos.of_nat n = Pos.of_nat m <-> n = m).\nProof.\n split. now apply inj. intros; now subst.\nQed.\n\n(** Usual operations are morphisms with respect to [Pos.of_nat]\n    for non-zero numbers. *)\n\nLemma inj_succ (n:nat) : n<>0 -> Pos.of_nat (S n) = Pos.succ (Pos.of_nat n).\nProof.\nintro H. apply Pos2Nat.inj. now rewrite Pos2Nat.inj_succ, !id.\nQed.\n\nLemma inj_pred (n:nat) : Pos.of_nat (pred n) = Pos.pred (Pos.of_nat n).\nProof.\n destruct n as [|[|n]]; trivial. simpl. now rewrite Pos.pred_succ.\nQed.\n\nLemma inj_add (n m : nat) : n<>0 -> m<>0 ->\n Pos.of_nat (n+m) = (Pos.of_nat n + Pos.of_nat m)%positive.\nProof.\nintros Hn Hm. apply Pos2Nat.inj.\nrewrite Pos2Nat.inj_add, !id; trivial.\nintros H. destruct n. now destruct Hn. now simpl in H.\nQed.\n\nLemma inj_mul (n m : nat) : n<>0 -> m<>0 ->\n Pos.of_nat (n*m) = (Pos.of_nat n * Pos.of_nat m)%positive.\nProof.\nintros Hn Hm. apply Pos2Nat.inj.\nrewrite Pos2Nat.inj_mul, !id; trivial.\nintros H. apply Nat.mul_eq_0 in H. destruct H. now elim Hn. now elim Hm.\nQed.\n\nLemma inj_compare (n m : nat) : n<>0 -> m<>0 ->\n (n ?= m) = (Pos.of_nat n ?= Pos.of_nat m)%positive.\nProof.\nintros Hn Hm. rewrite Pos2Nat.inj_compare, !id; trivial.\nQed.\n\nLemma inj_sub (n m : nat) : m<>0 ->\n Pos.of_nat (n-m) = (Pos.of_nat n - Pos.of_nat m)%positive.\nProof.\n intros Hm.\n apply Pos2Nat.inj.\n rewrite Pos2Nat.inj_sub_max.\n rewrite (id m) by trivial. rewrite !id_max.\n destruct n, m; trivial.\nQed.\n\nLemma inj_min (n m : nat) :\n Pos.of_nat (min n m) = Pos.min (Pos.of_nat n) (Pos.of_nat m).\nProof.\n destruct n as [|n]. simpl. symmetry. apply Pos.min_l, Pos.le_1_l.\n destruct m as [|m]. simpl. symmetry. apply Pos.min_r, Pos.le_1_l.\n unfold Pos.min. rewrite <- inj_compare by easy.\n case Nat.compare_spec; intros H; f_equal;\n  apply Nat.min_l || apply Nat.min_r.\n rewrite H; auto. now apply Nat.lt_le_incl. now apply Nat.lt_le_incl.\nQed.\n\nLemma inj_max (n m : nat) :\n Pos.of_nat (max n m) = Pos.max (Pos.of_nat n) (Pos.of_nat m).\nProof.\n destruct n as [|n]. simpl. symmetry. apply Pos.max_r, Pos.le_1_l.\n destruct m as [|m]. simpl. symmetry. apply Pos.max_l, Pos.le_1_l.\n unfold Pos.max. rewrite <- inj_compare by easy.\n case Nat.compare_spec; intros H; f_equal;\n  apply Nat.max_l || apply Nat.max_r.\n rewrite H; auto. now apply Nat.lt_le_incl. now apply Nat.lt_le_incl.\nQed.\n\nEnd Nat2Pos.\n\n(**********************************************************************)\n(** Properties of the shifted injection from Peano natural numbers\n    to binary positive numbers *)\n\nModule Pos2SuccNat.\n\n(** Composition of [Pos.to_nat] and [Pos.of_succ_nat] is successor\n    on [positive] *)\n\nTheorem id_succ p : Pos.of_succ_nat (Pos.to_nat p) = Pos.succ p.\nProof.\nrewrite Pos.of_nat_succ, <- Pos2Nat.inj_succ. apply Pos2Nat.id.\nQed.\n\n(** Composition of [Pos.to_nat], [Pos.of_succ_nat] and [Pos.pred]\n    is identity on [positive] *)\n\nTheorem pred_id p : Pos.pred (Pos.of_succ_nat (Pos.to_nat p)) = p.\nProof.\nnow rewrite id_succ, Pos.pred_succ.\nQed.\n\nEnd Pos2SuccNat.\n\nModule SuccNat2Pos.\n\n(** Composition of [Pos.of_succ_nat] and [Pos.to_nat] is successor on [nat] *)\n\nTheorem id_succ (n:nat) : Pos.to_nat (Pos.of_succ_nat n) = S n.\nProof.\nrewrite Pos.of_nat_succ. now apply Nat2Pos.id.\nQed.\n\nTheorem pred_id (n:nat) : pred (Pos.to_nat (Pos.of_succ_nat n)) = n.\nProof.\nnow rewrite id_succ.\nQed.\n\n(** [Pos.of_succ_nat] is hence injective *)\n\nLemma inj (n m : nat) : Pos.of_succ_nat n = Pos.of_succ_nat m -> n = m.\nProof.\n intro H. apply (f_equal Pos.to_nat) in H. rewrite !id_succ in H.\n now injection H.\nQed.\n\nLemma inj_iff (n m : nat) : Pos.of_succ_nat n = Pos.of_succ_nat m <-> n = m.\nProof.\n split. apply inj. intros; now subst.\nQed.\n\n(** Another formulation *)\n\nTheorem inv n p : Pos.to_nat p = S n -> Pos.of_succ_nat n = p.\nProof.\n intros H. apply Pos2Nat.inj. now rewrite id_succ.\nQed.\n\n(** Successor and comparison are morphisms with respect to\n    [Pos.of_succ_nat] *)\n\nLemma inj_succ n : Pos.of_succ_nat (S n) = Pos.succ (Pos.of_succ_nat n).\nProof.\napply Pos2Nat.inj. now rewrite Pos2Nat.inj_succ, !id_succ.\nQed.\n\nLemma inj_compare n m :\n (n ?= m) = (Pos.of_succ_nat n ?= Pos.of_succ_nat m)%positive.\nProof.\nrewrite Pos2Nat.inj_compare, !id_succ; trivial.\nQed.\n\n(** Other operations, for instance [Pos.add] and [plus] aren't\n    directly related this way (we would need to compensate for\n    the successor hidden in [Pos.of_succ_nat] *)\n\nEnd SuccNat2Pos.\n\n(** For compatibility, old names and old-style lemmas *)\n\nNotation Psucc_S := Pos2Nat.inj_succ (only parsing).\nNotation Pplus_plus := Pos2Nat.inj_add (only parsing).\nNotation Pmult_mult := Pos2Nat.inj_mul (only parsing).\nNotation Pcompare_nat_compare := Pos2Nat.inj_compare (only parsing).\nNotation nat_of_P_xH := Pos2Nat.inj_1 (only parsing).\nNotation nat_of_P_xO := Pos2Nat.inj_xO (only parsing).\nNotation nat_of_P_xI := Pos2Nat.inj_xI (only parsing).\nNotation nat_of_P_is_S := Pos2Nat.is_succ (only parsing).\nNotation nat_of_P_pos := Pos2Nat.is_pos (only parsing).\nNotation nat_of_P_inj_iff := Pos2Nat.inj_iff (only parsing).\nNotation nat_of_P_inj := Pos2Nat.inj (only parsing).\nNotation Plt_lt := Pos2Nat.inj_lt (only parsing).\nNotation Pgt_gt := Pos2Nat.inj_gt (only parsing).\nNotation Ple_le := Pos2Nat.inj_le (only parsing).\nNotation Pge_ge := Pos2Nat.inj_ge (only parsing).\nNotation Pminus_minus := Pos2Nat.inj_sub (only parsing).\nNotation iter_nat_of_P := @Pos2Nat.inj_iter (only parsing).\n\nNotation nat_of_P_of_succ_nat := SuccNat2Pos.id_succ (only parsing).\nNotation P_of_succ_nat_of_P := Pos2SuccNat.id_succ (only parsing).\n\nNotation nat_of_P_succ_morphism := Pos2Nat.inj_succ (only parsing).\nNotation nat_of_P_plus_morphism := Pos2Nat.inj_add (only parsing).\nNotation nat_of_P_mult_morphism := Pos2Nat.inj_mul (only parsing).\nNotation nat_of_P_compare_morphism := Pos2Nat.inj_compare (only parsing).\nNotation lt_O_nat_of_P := Pos2Nat.is_pos (only parsing).\nNotation ZL4 := Pos2Nat.is_succ (only parsing).\nNotation nat_of_P_o_P_of_succ_nat_eq_succ := SuccNat2Pos.id_succ (only parsing).\nNotation P_of_succ_nat_o_nat_of_P_eq_succ := Pos2SuccNat.id_succ (only parsing).\nNotation pred_o_P_of_succ_nat_o_nat_of_P_eq_id := Pos2SuccNat.pred_id (only parsing).\n\nLemma nat_of_P_minus_morphism p q :\n Pos.compare_cont Eq p q = Gt ->\n  Pos.to_nat (p - q) = Pos.to_nat p - Pos.to_nat q.\nProof (fun H => Pos2Nat.inj_sub p q (Pos.gt_lt _ _ H)).\n\nLemma nat_of_P_lt_Lt_compare_morphism p q :\n Pos.compare_cont Eq p q = Lt -> Pos.to_nat p < Pos.to_nat q.\nProof (proj1 (Pos2Nat.inj_lt p q)).\n\nLemma nat_of_P_gt_Gt_compare_morphism p q :\n Pos.compare_cont Eq p q = Gt -> Pos.to_nat p > Pos.to_nat q.\nProof (proj1 (Pos2Nat.inj_gt p q)).\n\nLemma nat_of_P_lt_Lt_compare_complement_morphism p q :\n Pos.to_nat p < Pos.to_nat q -> Pos.compare_cont Eq p q = Lt.\nProof (proj2 (Pos2Nat.inj_lt p q)).\n\nDefinition nat_of_P_gt_Gt_compare_complement_morphism p q :\n Pos.to_nat p > Pos.to_nat q -> Pos.compare_cont Eq p q = Gt.\nProof (proj2 (Pos2Nat.inj_gt p q)).\n\n(** Old intermediate results about [Pmult_nat] *)\n\nSection ObsoletePmultNat.\n\nLemma Pmult_nat_mult : forall p n,\n Pmult_nat p n = Pos.to_nat p * n.\nProof.\n induction p; intros n; unfold Pos.to_nat; simpl.\n f_equal. rewrite 2 IHp. rewrite <- Nat.mul_assoc.\n  f_equal. simpl. now rewrite Nat.add_0_r.\n rewrite 2 IHp. rewrite <- Nat.mul_assoc.\n  f_equal. simpl. now rewrite Nat.add_0_r.\n simpl. now rewrite Nat.add_0_r.\nQed.\n\nLemma Pmult_nat_succ_morphism :\n forall p n, Pmult_nat (Pos.succ p) n = n + Pmult_nat p n.\nProof.\n intros. now rewrite !Pmult_nat_mult, Pos2Nat.inj_succ.\nQed.\n\nTheorem Pmult_nat_l_plus_morphism :\n forall p q n, Pmult_nat (p + q) n = Pmult_nat p n + Pmult_nat q n.\nProof.\n intros. rewrite !Pmult_nat_mult, Pos2Nat.inj_add. apply Nat.mul_add_distr_r.\nQed.\n\nTheorem Pmult_nat_plus_carry_morphism :\n forall p q n, Pmult_nat (Pos.add_carry p q) n = n + Pmult_nat (p + q) n.\nProof.\n intros. now rewrite Pos.add_carry_spec, Pmult_nat_succ_morphism.\nQed.\n\nLemma Pmult_nat_r_plus_morphism :\n forall p n, Pmult_nat p (n + n) = Pmult_nat p n + Pmult_nat p n.\nProof.\n intros. rewrite !Pmult_nat_mult. apply Nat.mul_add_distr_l.\nQed.\n\nLemma ZL6 : forall p, Pmult_nat p 2 = Pos.to_nat p + Pos.to_nat p.\nProof.\n intros. rewrite Pmult_nat_mult, Nat.mul_comm. simpl. now rewrite Nat.add_0_r.\nQed.\n\nLemma le_Pmult_nat : forall p n, n <= Pmult_nat p n.\nProof.\n intros. rewrite Pmult_nat_mult.\n apply Nat.le_trans with (1*n). now rewrite Nat.mul_1_l.\n apply Nat.mul_le_mono_r. apply Pos2Nat.is_pos.\nQed.\n\nEnd ObsoletePmultNat.\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/PArith/Pnat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.6997220528757881}}
{"text": "(** This module defines the full signature of language algebra we\nconsider here, and its finite complete axiomatization. We also define\nhere some normalisation functions, and list some of their properties. *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import tools language.\n  \nDelimit Scope lat_scope with lat.\nOpen Scope lat_scope.\n\n\nSection s.\n  (** * Main definitions *)\n  Variable X : Set.\n  Variable dec_X : decidable_set X.\n\n  (** [𝐄'' X] is the type of expressions with variables ranging over the\n  type [X]. They are built out of the constant [0], the\n  concatenation (also called sequential product) [⋅], the intersection\n  [∩], the union [+], and the non-zero iteration, denoted by [⁺]. *)\n  Inductive 𝐄'' : Set :=\n  | 𝐄''_zero : 𝐄''\n  | 𝐄''_var : X -> 𝐄''\n  | 𝐄''_seq : 𝐄'' -> 𝐄'' -> 𝐄''\n  | 𝐄''_inter : 𝐄'' -> 𝐄'' -> 𝐄''\n  | 𝐄''_plus : 𝐄'' -> 𝐄'' -> 𝐄''\n  | 𝐄''_iter : 𝐄'' -> 𝐄''.\n\n  Notation \"x ⋅ y\" := (𝐄''_seq x y) (at level 40) : lat_scope.\n  Notation \"x + y\" := (𝐄''_plus x y) (left associativity, at level 50) : lat_scope.\n  Notation \"x ∩ y\" := (𝐄''_inter x y) (at level 45) : lat_scope.\n  Notation \"x ⁺\" := (𝐄''_iter x) (at level 25) : lat_scope.\n  Notation \" 0 \" := 𝐄''_zero : lat_scope.\n\n  (** The size of an expression is the number of nodes in its syntax\n  tree. *)\n  Global Instance size_𝐄'' : Size 𝐄'' :=\n    fix 𝐄''_size (e: 𝐄'') : nat :=\n      match e with\n      | 0 | 𝐄''_var _ => 1%nat\n      | e + f | e ∩ f | e ⋅ f => S (𝐄''_size e + 𝐄''_size f)\n      | e ⁺ => S (𝐄''_size e)\n      end.\n  (* begin hide *)\n  Lemma 𝐄''_size_zero : |0| = 1%nat. trivial. Qed.\n  Lemma 𝐄''_size_var a : |𝐄''_var a| = 1%nat. trivial. Qed.\n  Lemma 𝐄''_size_seq e f : |e⋅f| = S(|e|+|f|). trivial. Qed.\n  Lemma 𝐄''_size_inter e f : |e∩f| = S(|e|+|f|). trivial. Qed.\n  Lemma 𝐄''_size_plus e f : |e+f| = S(|e|+|f|). trivial. Qed.\n  Lemma 𝐄''_size_iter e : |e⁺| = S(|e|). trivial. Qed.\n  Hint Rewrite 𝐄''_size_zero 𝐄''_size_var 𝐄''_size_seq\n       𝐄''_size_inter 𝐄''_size_plus 𝐄''_size_iter\n    : simpl_typeclasses.\n  Fixpoint eqb e f :=\n    match (e,f) with\n    | (0,0) => true\n    | (𝐄''_var a,𝐄''_var b) => eqX a b\n    | (e⁺,f⁺) => eqb e f\n    | (e1 + e2,f1 + f2)\n    | (e1 ⋅ e2,f1 ⋅ f2)\n    | (e1 ∩ e2,f1 ∩ f2) => eqb e1 f1 && eqb e2 f2\n    | _ => false\n    end.\n  Lemma eqb_reflect e f : reflect (e = f) (eqb e f).\n  Proof.\n    apply iff_reflect;symmetry;split;\n      [intro h;apply Is_true_eq_left in h;revert f h\n      |intros <-;apply Is_true_eq_true];induction e;\n        try destruct f;simpl;autorewrite with quotebool;firstorder.\n    - apply Is_true_eq_true,eqX_correct in h as ->;auto.\n    - erewrite IHe1;[|eauto]; erewrite IHe2;[|eauto];auto.\n    - erewrite IHe1;[|eauto]; erewrite IHe2;[|eauto];auto.\n    - erewrite IHe1;[|eauto]; erewrite IHe2;[|eauto];auto.\n    - erewrite IHe;[|eauto];auto.\n    - apply Is_true_eq_left,eqX_correct;auto.\n  Qed.\n  (* end hide *)\n\n  (** If the set of variables [X] is decidable, then so is the set of\n  expressions. _Note that we are here considering syntactic equality,\n  as no semantic or axiomatic equivalence relation has been defined\n  for expressions_. *)\n  Global Instance 𝐄''_decidable_set : decidable_set 𝐄''.\n  Proof. exact (Build_decidable_set eqb_reflect). Qed.\n\n  (** The following are the axioms of the algebra of languages over\n  this signature.*)\n  Inductive ax : 𝐄'' -> 𝐄'' -> Prop :=\n  (* first line *)\n  | ax_inter_assoc e f g : ax (e∩(f ∩ g)) ((e∩f)∩g)\n  | ax_inter_comm e f : ax (e∩f) (f∩e)\n  | ax_inter_idem e : ax (e ∩ e) e\n  (* second line *)\n  | ax_plus_inter e f g: ax (e ∩ (f + g)) ((e∩f) + (e∩g))\n  | ax_plus_inter_id e f : ax (e ∩ (e + f)) e\n  | ax_inter_plus_id e f : ax (e + (e ∩ f)) e\n  (* third line *)\n  | ax_plus_ass e f g : ax (e+(f+g)) ((e+f)+g)\n  | ax_plus_com e f : ax (e+f) (f+e)\n  | ax_plus_idem e : ax (e+e) e\n  (* fourth line *)                              \n  | ax_seq_assoc e f g : ax (e⋅(f ⋅ g)) ((e⋅f)⋅g)\n  | ax_seq_plus e f g: ax (e⋅(f + g)) (e⋅f + e⋅g)\n  | ax_plus_seq e f g: ax ((e + f)⋅g) (e⋅g + f⋅g)\n  | ax_plus_0 e : ax (e+0) e\n  | ax_seq_0 e : ax (e⋅0) 0\n  | ax_0_seq e : ax (0⋅e) 0\n  (* fifth line *)\n  | ax_iter_left e : ax (e⁺) (e + e⋅e⁺)\n  | ax_iter_right e : ax (e⁺) (e + e⁺ ⋅e).\n\n  Inductive ax_impl : 𝐄'' -> 𝐄'' -> 𝐄'' -> 𝐄'' -> Prop:=\n  | ax_right_ind e f : ax_impl (e⋅f + f) f (e⁺⋅f + f) f\n  | ax_left_ind e f : ax_impl (f ⋅ e + f) f (f ⋅e⁺ + f) f.\n\n  (** We use these axioms to generate an axiomatic equivalence\n  relation and an axiomatic order relations. *)\n  Inductive 𝐄''_eq : Equiv 𝐄'' :=\n  | eq_refl e : e ≡ e\n  | eq_trans f e g : e ≡ f -> f ≡ g -> e ≡ g\n  | eq_sym e f : e ≡ f -> f ≡ e\n  | eq_plus e f g h : e ≡ g -> f ≡ h -> (e + f) ≡ (g + h)\n  | eq_seq e f g h : e ≡ g -> f ≡ h -> (e ⋅ f) ≡ (g ⋅ h)\n  | eq_inter e f g h : e ≡ g -> f ≡ h -> (e ∩ f) ≡ (g ∩ h)\n  | eq_iter e f : e ≡ f -> (e⁺) ≡ (f⁺)\n  | eq_ax e f : ax e f -> e ≡ f\n  | eq_ax_impl e f g h : ax_impl e f g h -> e ≡ f -> g ≡ h.\n  Global Instance 𝐄''_Equiv : Equiv 𝐄'' := 𝐄''_eq.\n\n  Global Instance 𝐄''_Smaller : Smaller 𝐄'' := (fun e f => e + f ≡ f).\n\n  Hint Constructors 𝐄''_eq ax ax_impl.\n\n  Global Instance ax_equiv : subrelation ax equiv. \n  Proof. intros e f E;apply eq_ax,E. Qed.\n\nEnd s.\n\n(* begin hide *)\nArguments 𝐄''_zero {X}.\nArguments eqb {X} {dec_X} e%lat f%lat.\nHint Constructors 𝐄''_eq ax ax_impl.\nHint Rewrite @𝐄''_size_zero @𝐄''_size_var @𝐄''_size_seq\n     @𝐄''_size_inter @𝐄''_size_plus @𝐄''_size_iter\n  : simpl_typeclasses.\n(* end hide *)\n\nInfix \" ⋅ \" := 𝐄''_seq (at level 40) : lat_scope.\nInfix \" + \" := 𝐄''_plus (left associativity, at level 50) : lat_scope.\nInfix \" ∩ \" := 𝐄''_inter (at level 45) : lat_scope.\nNotation \"x ⁺\" := (𝐄''_iter x) (at level 25) : lat_scope.\nNotation \" 0 \" := 𝐄''_zero : lat_scope.\n\nSection language.\n  (** * Language interpretation *)\n  Context { X : Set }.\n\n  (** We interpret expressions as languages in the obvious way: *)\n  Global Instance to_lang_𝐄'' {Σ}: semantics 𝐄'' language X Σ :=\n    fix to_lang_𝐄'' σ e:=\n      match e with\n      | 0 => 0%lang\n      | 𝐄''_var a => (σ a)\n      | e + f => ((to_lang_𝐄'' σ e) + (to_lang_𝐄'' σ f))%lang\n      | e ⋅ f => ((to_lang_𝐄'' σ e) ⋅ (to_lang_𝐄'' σ f))%lang\n      | e ∩ f => ((to_lang_𝐄'' σ e) ∩ (to_lang_𝐄'' σ f))%lang\n      | e⁺ => (to_lang_𝐄'' σ e)⁺%lang\n      end.\n\n  (* begin hide *)\n  Global Instance semSmaller_𝐄'' : SemSmaller (𝐄'' X) :=\n    (@semantic_containment _ _ _ _ _).\n  Global Instance semEquiv_𝐄'' : SemEquiv (𝐄'' X) :=\n    (@semantic_equality _ _ _ _ _).\n  Hint Unfold semSmaller_𝐄'' semEquiv_𝐄'' : semantics.\n  \n  Section rsimpl.\n    Context { Σ : Set }{σ : 𝕬[X→Σ] }.\n    Lemma 𝐄''_union e f : (⟦ e+f ⟧σ) = ((⟦e⟧σ) + ⟦f⟧σ)%lang.\n    Proof. unfold interprete;simpl;auto. Qed.\n    Lemma 𝐄''_prod e f :  (⟦ e⋅f ⟧σ) = ((⟦e⟧σ) ⋅ ⟦f⟧σ)%lang.\n    Proof. unfold interprete;simpl;auto. Qed.\n    Lemma 𝐄''_intersection e f : (⟦ e∩f ⟧σ) = ((⟦e⟧σ) ∩ ⟦f⟧σ)%lang.\n    Proof. unfold interprete;simpl;auto. Qed.\n    Lemma 𝐄''_iter_l e :  (⟦ e⁺⟧σ) = (⟦e⟧σ)⁺%lang.\n    Proof. unfold interprete;simpl;auto. Qed.\n    Lemma 𝐄''_variable a : (⟦𝐄''_var a⟧ σ) = σ a.\n    Proof. unfold interprete;simpl;auto. Qed.\n    Lemma 𝐄''_empty : (⟦0⟧σ) = 0%lang.\n    Proof. unfold interprete;simpl;auto. Qed.\n  End rsimpl.\n  Hint Rewrite @𝐄''_empty @𝐄''_variable @𝐄''_intersection\n       @𝐄''_prod @𝐄''_union @𝐄''_iter_l\n    : simpl_typeclasses.\n  (* end hide *)\n  Theorem klm_completeness : forall e f : 𝐄'' X, e ≡ f <-> e ≃ f.\n  Admitted.\n\n  Corollary klm_completeness_inf : forall e f : 𝐄'' X, e ≤ f <-> e ≲ f.\n  Proof.\n    intros e f;unfold smaller,𝐄''_Smaller;rewrite klm_completeness.\n    split.\n    - intros E A ? u Ie;apply E;now left.\n    - intros E A ? u;split;rsimpl.\n      + intros [I|I];auto.\n        apply E,I.\n      + intros I;now right.\n  Qed.\nEnd language.\nHint Rewrite @𝐄''_empty @𝐄''_variable @𝐄''_intersection\n     @𝐄''_prod @𝐄''_union @𝐄''_iter_l\n  : simpl_typeclasses.\n\nClose Scope lat_scope.\n\n\n(*  LocalWords:  subunits\n *)\n\n\n\n\n\n\n", "meta": {"author": "monstrencage", "repo": "LangAlg", "sha": "a33b6e6457cec94eae57d0137b576c9547a4f63e", "save_path": "github-repos/coq/monstrencage-LangAlg", "path": "github-repos/coq/monstrencage-LangAlg/LangAlg-a33b6e6457cec94eae57d0137b576c9547a4f63e/klm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.699722052875788}}
{"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 Bool NZAxioms NZMulOrder.\n\n(** Parity functions *)\n\nModule Type NZParity (Import A : NZAxiomsSig').\n Parameter Inline even odd : t -> bool.\n Definition Even n := exists m, n == 2*m.\n Definition Odd n := exists m, n == 2*m+1.\n Axiom even_spec : forall n, even n = true <-> Even n.\n Axiom odd_spec : forall n, odd n = true <-> Odd n.\nEnd NZParity.\n\nModule Type NZParityProp\n (Import A : NZOrdAxiomsSig')\n (Import B : NZParity A)\n (Import C : NZMulOrderProp A).\n\n(** Morphisms *)\n\nInstance Even_wd : Proper (eq==>iff) Even.\nProof. unfold Even. solve_proper. Qed.\n\nInstance Odd_wd : Proper (eq==>iff) Odd.\nProof. unfold Odd. solve_proper. Qed.\n\nInstance even_wd : Proper (eq==>Logic.eq) even.\nProof.\n intros x x' EQ. rewrite eq_iff_eq_true, 2 even_spec. now f_equiv.\nQed.\n\nInstance odd_wd : Proper (eq==>Logic.eq) odd.\nProof.\n intros x x' EQ. rewrite eq_iff_eq_true, 2 odd_spec. now f_equiv.\nQed.\n\n(** Evenness and oddity are dual notions *)\n\nLemma Even_or_Odd : forall x, Even x \\/ Odd x.\nProof.\n nzinduct x.\n left. exists 0. now nzsimpl.\n intros x.\n split; intros [(y,H)|(y,H)].\n right. exists y. rewrite H. now nzsimpl.\n left. exists (S y). rewrite H. now nzsimpl'.\n right.\n assert (LT : exists z, z<y).\n  destruct (lt_ge_cases 0 y) as [LT|GT]; [now exists 0 | exists x].\n  rewrite <- le_succ_l, H. nzsimpl'.\n  rewrite <- (add_0_r y) at 3. now apply add_le_mono_l.\n destruct LT as (z,LT).\n destruct (lt_exists_pred z y LT) as (y' & Hy' & _).\n exists y'. rewrite <- succ_inj_wd, H, Hy'. now nzsimpl'.\n left. exists y. rewrite <- succ_inj_wd. rewrite H. now nzsimpl.\nQed.\n\nLemma double_below : forall n m, n<=m -> 2*n < 2*m+1.\nProof.\n intros. nzsimpl'. apply lt_succ_r. now apply add_le_mono.\nQed.\n\nLemma double_above : forall n m, n<m -> 2*n+1 < 2*m.\nProof.\n intros. nzsimpl'.\n rewrite <- le_succ_l, <- add_succ_l, <- add_succ_r.\n apply add_le_mono; now apply le_succ_l.\nQed.\n\nLemma Even_Odd_False : forall x, Even x -> Odd x -> False.\nProof.\nintros x (y,E) (z,O). rewrite O in E; clear O.\ndestruct (le_gt_cases y z) as [LE|GT].\ngeneralize (double_below _ _ LE); order.\ngeneralize (double_above _ _ GT); order.\nQed.\n\nLemma orb_even_odd : forall n, orb (even n) (odd n) = true.\nProof.\n intros.\n destruct (Even_or_Odd n) as [H|H].\n rewrite <- even_spec in H. now rewrite H.\n rewrite <- odd_spec in H. now rewrite H, orb_true_r.\nQed.\n\nLemma negb_odd : forall n, negb (odd n) = even n.\nProof.\n intros.\n generalize (Even_or_Odd n) (Even_Odd_False n).\n rewrite <- even_spec, <- odd_spec.\n destruct (odd n), (even n) ; simpl; intuition.\nQed.\n\nLemma negb_even : forall n, negb (even n) = odd n.\nProof.\n intros. rewrite <- negb_odd. apply negb_involutive.\nQed.\n\n(** Constants *)\n\nLemma even_0 : even 0 = true.\nProof.\n rewrite even_spec. exists 0. now nzsimpl.\nQed.\n\nLemma odd_0 : odd 0 = false.\nProof.\n now rewrite <- negb_even, even_0.\nQed.\n\nLemma odd_1 : odd 1 = true.\nProof.\n rewrite odd_spec. exists 0. now nzsimpl'.\nQed.\n\nLemma even_1 : even 1 = false.\nProof.\n now rewrite <- negb_odd, odd_1.\nQed.\n\nLemma even_2 : even 2 = true.\nProof.\n rewrite even_spec. exists 1. now nzsimpl'.\nQed.\n\nLemma odd_2 : odd 2 = false.\nProof.\n now rewrite <- negb_even, even_2.\nQed.\n\n(** Parity and successor *)\n\nLemma Odd_succ : forall n, Odd (S n) <-> Even n.\nProof.\n split; intros (m,H).\n exists m. apply succ_inj. now rewrite add_1_r in H.\n exists m. rewrite add_1_r. now f_equiv.\nQed.\n\nLemma odd_succ : forall n, odd (S n) = even n.\nProof.\n intros. apply eq_iff_eq_true. rewrite even_spec, odd_spec.\n apply Odd_succ.\nQed.\n\nLemma even_succ : forall n, even (S n) = odd n.\nProof.\n intros. now rewrite <- negb_odd, odd_succ, negb_even.\nQed.\n\nLemma Even_succ : forall n, Even (S n) <-> Odd n.\nProof.\n intros. now rewrite <- even_spec, even_succ, odd_spec.\nQed.\n\n(** Parity and successor of successor *)\n\nLemma Even_succ_succ : forall n, Even (S (S n)) <-> Even n.\nProof.\n intros. now rewrite Even_succ, Odd_succ.\nQed.\n\nLemma Odd_succ_succ : forall n, Odd (S (S n)) <-> Odd n.\nProof.\n intros. now rewrite Odd_succ, Even_succ.\nQed.\n\nLemma even_succ_succ : forall n, even (S (S n)) = even n.\nProof.\n intros. now rewrite even_succ, odd_succ.\nQed.\n\nLemma odd_succ_succ : forall n, odd (S (S n)) = odd n.\nProof.\n intros. now rewrite odd_succ, even_succ.\nQed.\n\n(** Parity and addition *)\n\nLemma even_add : forall n m, even (n+m) = Bool.eqb (even n) (even m).\nProof.\n intros.\n case_eq (even n); case_eq (even m);\n  rewrite <- ?negb_true_iff, ?negb_even, ?odd_spec, ?even_spec;\n  intros (m',Hm) (n',Hn).\n exists (n'+m'). now rewrite mul_add_distr_l, Hn, Hm.\n exists (n'+m'). now rewrite mul_add_distr_l, Hn, Hm, add_assoc.\n exists (n'+m'). now rewrite mul_add_distr_l, Hn, Hm, add_shuffle0.\n exists (n'+m'+1). rewrite Hm,Hn. nzsimpl'. now rewrite add_shuffle1.\nQed.\n\nLemma odd_add : forall n m, odd (n+m) = xorb (odd n) (odd m).\nProof.\n intros. rewrite <- !negb_even. rewrite even_add.\n now destruct (even n), (even m).\nQed.\n\n(** Parity and multiplication *)\n\nLemma even_mul : forall n m, even (mul n m) = even n || even m.\nProof.\n intros.\n case_eq (even n); simpl; rewrite ?even_spec.\n intros (n',Hn). exists (n'*m). now rewrite Hn, mul_assoc.\n case_eq (even m); simpl; rewrite ?even_spec.\n intros (m',Hm). exists (n*m'). now rewrite Hm, !mul_assoc, (mul_comm 2).\n (* odd / odd *)\n rewrite <- !negb_true_iff, !negb_even, !odd_spec.\n intros (m',Hm) (n',Hn). exists (n'*2*m' +n'+m').\n rewrite Hn,Hm, !mul_add_distr_l, !mul_add_distr_r, !mul_1_l, !mul_1_r.\n now rewrite add_shuffle1, add_assoc, !mul_assoc.\nQed.\n\nLemma odd_mul : forall n m, odd (mul n m) = odd n && odd m.\nProof.\n intros. rewrite <- !negb_even. rewrite even_mul.\n now destruct (even n), (even m).\nQed.\n\n(** A particular case : adding by an even number *)\n\nLemma even_add_even : forall n m, Even m -> even (n+m) = even n.\nProof.\n intros n m Hm. apply even_spec in Hm.\n rewrite even_add, Hm. now destruct (even n).\nQed.\n\nLemma odd_add_even : forall n m, Even m -> odd (n+m) = odd n.\nProof.\n intros n m Hm. apply even_spec in Hm.\n rewrite odd_add, <- (negb_even m), Hm. now destruct (odd n).\nQed.\n\nLemma even_add_mul_even : forall n m p, Even m -> even (n+m*p) = even n.\nProof.\n intros n m p Hm. apply even_spec in Hm.\n apply even_add_even. apply even_spec. now rewrite even_mul, Hm.\nQed.\n\nLemma odd_add_mul_even : forall n m p, Even m -> odd (n+m*p) = odd n.\nProof.\n intros n m p Hm. apply even_spec in Hm.\n apply odd_add_even. apply even_spec. now rewrite even_mul, Hm.\nQed.\n\nLemma even_add_mul_2 : forall n m, even (n+2*m) = even n.\nProof.\n intros. apply even_add_mul_even. apply even_spec, even_2.\nQed.\n\nLemma odd_add_mul_2 : forall n m, odd (n+2*m) = odd n.\nProof.\n intros. apply odd_add_mul_even. apply even_spec, even_2.\nQed.\n\nEnd NZParityProp.\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/NatInt/NZParity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.6997220501755008}}
{"text": "Require Import Wf_nat PeanoNat Psatz. (* lt_wf =? lia *)\n\nCheck lt_wf.\n\nDefinition dec : forall (b:bool), {b = true} + {b = false} :=\n    fun (b:bool) => \n        match b as b' return {b' = true} + {b' = false} with\n        | true  => left  (eq_refl true)\n        | false => right (eq_refl false)\n        end.\n\n\nDefinition fac : nat -> nat.\nProof.\nrefine (Fix lt_wf (fun _ => nat)\n    (fun (n:nat) =>\n        fun (fac : forall (y:nat), y < n -> nat) =>\n            if dec (n =? 0)\n                then 1\n                else n * (fac (n - 1) _)\n)).\nclear fac.\ndestruct n as [|n].\n    - inversion e.\n    - lia.\nDefined.\n\nCompute fac 8.\n\n(* works but no idea why                                                        *)\nLemma fac_S (n:nat) : fac (S n) = (S n) * fac n.\nProof.\n    unfold fac at 1; rewrite Fix_eq; fold fac.\n    now replace (S n - 1) with n by lia.\n    now intros x f g H; case dec; intros; rewrite ?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/WellFounded2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225518, "lm_q2_score": 0.7520125626441471, "lm_q1q2_score": 0.6997162985977406}}
{"text": "(*\ninversion について。\n*)\n\nRequire Export SfLib_J.\n\n(*\nLogic_J.vより。\n\nInversion 再び\n\nこれまでにも inversion が等値性にからむ仮定や帰納的に定義された命題に対して 使われるところを見てきま\nした。今度もやることは変わりませんが、もう少し近くまで 寄って inversion の振る舞いを観察してみましょ\nう。\n\n一般的に inversion タクティックは、\n- 帰納的に定義された型 P の命題 H をとる。 \n- その型 P の定義にある各コンストラクタ C が、 \n  - H が C から成っていると仮定するような新しいサブゴールを作る。 \n  - C の引数（前提）を、追加の仮定としてサブゴールのコンテキストに加える。 \n  - C の結論（戻り値の型）を現在のゴールとmatchして、 C を適用できるような一連の等式算出する。 \n  - そしてこれらの等式をサブゴールのコンテキストに加えてから、 \n  - もしこの等式が充足可能でない場合（S n = O というような式を含むなど）は、 即座にサブゴールを解決する。\n\n例 : or で構築された仮定を反転（ invert ）すると、or に二つのコンストラクタが あるため二つのサブゴー\nルが生成されます。コンストラクタ (P ∨ Q) の結果 （戻り値の型）は P や Q の形からくる制約を付けません。\nそのため追加の等式が サブゴールのコンテキストに加えられることはありません。\n\n例 : and で構築された仮定を反転（ invert ）すると、and にはコンストラクタが 一つしかないため、サブゴー\nルも一つしか生成されません。やはり、コンストラクタ (P ∧ Q) の結果（戻り値の型）は P や Q の形からく\nる制約を付けず、追加の等式が サブゴールのコンテキストに加えられることはありません。このコンストラクタ\nは引数を二つ とりますが、それらはサブゴールのコンテキストに現れます。\n\n例 : eq で構築された仮定を反転（ invert ）すると、これにもやはりコンストラクタが 一つしかないため、サ\nブゴールも一つしか生成されません。しかしこの場合 コンストラクタ refl_equal の形は我々にもう少し情報を\n与えてくれます。 それは、eq の二つの引数は同じでなければならないという点です。 inversion タクティック\nはこの事実をコンテキストに加えてくれます。\n\n*)\n\n(*\n証明事例集: 自前で inversion を行う より\nhttp://homepage2.nifty.com/magicant/programmingmemo/coq/maninv.html\n\nただし、ここでは同じ例題をinversionを使って証明する。\n*)\n\n(* 単純な例: even *)\n\nInductive even : nat -> Prop :=\n  | even_O : even O\n  | even_SS : forall n, even n -> even (S (S n)).\n\nGoal ~ even 1.\nProof.\n  intro H.\n  inversion H.\nQed.\n(*\neven 1 には even_O と even_SS のどちらも当てはまらないため、inversion を使うと直ちに証明が完了する。\n*)\n(*\nでは、組み込みの inversion タクティクを使わない場合はどうするか。以下のように単純に case H をしただけ\nでは、even の引数が 1 であることが場合分けの後に忘れられてしまうので、False を導くための条件が揃わな\nい。実際、case H した後の一つ目のサブゴールは case H をする前と全く変わっていない。（略）\n*)\n\n(* 追記： ~even 5のとき。*)\n\nGoal ~ even 7.\nProof.\n  intro H.\n  inversion H.\n  (* H1 : even 5 *)\n  inversion H1.\n  (* H3 : even 3 *)\n  inversion H3.\n  (* H5 : even 1 *)\n  inversion H5.\nQed.\n\n(* 途中で、いらない前提を消すと、見通しがよくなる。*)\nGoal ~ even 7.\nProof.\n  intro H.\n  inversion H. subst. clear H.\n  (* H1 : even 5 *)\n  inversion H1. subst. clear H1.\n  (* H0 : even 3 *)\n  inversion H0. subst. clear H0.\n  (* H1 : even 1 *)\n  inversion H1.\nQed.\n\n(* 次は証明できるに違いないが、前提のほうは even 0 から進まない。\nまた、前提Hを反転ることについては、GoalはTrueでもFalseでも関係ない、ことに注意するべきだ。\n *)\nGoal even 2 -> True.\nProof.\n  intro H.\n  inversion H. subst. clear H.\n  exact I.\nQed.\n\n(* その上、とどめのinversion H1さえ、GoalがTrueでもFalseでも有効である。 *)\nGoal even 3 -> True.\nProof.\n  intro H.\n  inversion H. subst. clear H.\n  inversion H1.                             (* exact Iでもよいが。 *)\nQed.\n\n(* さすがに、これは証明できない。*)\nGoal even 2 -> False.\nProof.\n  intro H.\n  inversion H. subst. clear H.\n  inversion H1.\nAdmitted.                                   (* OK *)\n\n\n(* 今度は、S (S n) が偶数ならば n も偶数であることを示そう。*)\nGoal forall n, even (S (S n)) -> even n.\nProof.\n  intros n H.\n  inversion H.\n  apply H1.\nQed.\n\n(* 複数の引数を取る述語: succ *)\n\n(*\n場合分けをする述語が複数の引数を取る場合は、それに合わせて複数の等式をゴールに追加する必要がある。こ\nこでは、二つの自然数の後者関係を表す述語 succ を定義し、任意の自然数は自分自身の後者ではないことを示\nそう。\n*)\n\nInductive succ : nat -> nat -> Prop :=\n  succ_intro : forall n, succ n (S n).\n(* succ は二つの引数を取るので、それらに対応する二つの等式をゴールに追加してから case する。 *)\n\nGoal forall n, ~ succ n n.\nProof.\n  intros n H.\n  induction n.\n  inversion H.\n  apply IHn.\n  inversion H.\n  apply H.\nQed.\n\n(* 固定パラメータのある述語: le *)\n\n(*\nInductive le (n : nat) : nat -> Prop :=\n  | le_n : n <= n\n  | le_S : forall m : nat, n <= m -> n <= S m\n\nle は二つの引数を受け取るように見えるが、実際には最初の引数は固定されたパラメータである。すなわち正確\nには、任意の自然数 n に対して le n が一つの引数を受け取ると考える必要がある。そのため、inversion では\n最初の引数 n に関する条件は得られず、最後の引数に関する条件だけが得られる。最後の引数に関する条件を場\n合分けの後まで覚えておくために、最後の引数に関する等式をゴールに追加してから場合分けを行う。\n\nなぜ最初の引数に関する等式を追加してはいけないのかというと、もしそうすると pattern 後の case で正しく\n値が置き換えられないからである。\n*)\n\n(* 以下の例は、n <= 0 から n = 0 を導く証明である。 *)\n\nGoal forall n, n <= 0 -> n = 0.\nProof.\n  intros n H.\n  induction n.\n  reflexivity.\n  inversion H.\nQed.\n\n(*\nタクティクリファレンス: 帰納法と場合分け より\nhttp://homepage2.nifty.com/magicant/programmingmemo/coq/t-induct.html\n*)\n\n(*\ninversion タクティク\n\ninversion タクティクは、case タクティクや destruct タクティクのように代数的データ型に対する場合分けを\n行うが、コンストラクタの引数に関する条件を保存する。\n\n特定の値に関する条件を表す述語が代数的データ型として定義してあり、そのような述語が実際に前提として得\nられている場合に、その述語から具体的な値に関する条件を取り出すのに使う。\n*)\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*)\n\nGoal forall n : nat, n <= 0 -> n = 0.\nProof.\n  intros n H.\n  inversion H as [ H' | ].\n  reflexivity.\nQed.\n(*\n上の例では、前提 H : n <= 0 から条件 n = 0 を取り出すために inversion を用いている。述語 le には二つ\nのコンストラクタがあるが、le_S から作ることのできる条件の型 n <= S m は前提 H の型 n <= 0 に適合しな\nいため、この場合は自動的に除外される。le_n の型 n <= n と H の型 n <= 0 とを照らし合わせた結果として\n条件 n = 0 が前提に追加され、この等式を利用して自動的にゴールの n が 0 に書き換えられる。\n*)\n\n(*\ninversion ident\n前提 ident に対して inversion を適用し、得られる条件を前提に追加する。指定した前提が存在しない場合は、\n先に intros until ident を試みる。\nas によって前提名を指定しないで inversion を使うと、処理系によって自動的に前提名が生成される。生成さ\nれる前提名は常に同じとは限らないので、前提名に依存した証明を書く場合は以下の as を用いる構文を使うこ\nと。\n\ninversion num\nintros until num を行い、最後に追加された前提に対して inversion を適用する。\n\ninversion … as intropattern\n追加される前提の名前を指定して inversion する。名前の指定のしかたは destruct … as … と似ているが、\ninversion が取り出した条件 (等式) の名前も追加で指定する必要がある。条件の名前の指定は injection …\nas … に準ずる。名前が足りない場合は処理系が自動的に名前を選ぶので注意。\n*)\n\nInductive list_in {A : Type} : A -> list A -> Prop :=\n| in_hd : forall a l, list_in a (a :: l)\n| in_tl : forall a b l, list_in a l -> list_in a (b :: l).\n\nGoal forall l, list_in 0 (1 :: l) -> list_in 0 l.\nProof.\n  inversion 1 as [ | a b l' H' H1 [H2 H3] ].\n  exact H'.\nQed.\n(*\n上の例では、述語 list_in の二つのコンストラクタのうち in_hd の場合については条件が合わずに自動的に除\n外されるので名前を指定していない。in_tl の場合の名前の指定は、まず a, b, l', H' の四つがそれぞれ\nin_tl の四つの引数に対応しており (ここまでは destruct と同じ)、その後の H1 と [H2 H3] はそれぞれ\nlist_in の二つの引数 (A 型と list A 型) に対応して得られる二つの条件 a = 0 と b :: l' = 1 :: l に対応\nしている。後者は自動的に適用される injection により b = 1 と l' = l とに分解されるため、それに合わせ\nて H2 と H3 の二つの名前を指定している。\n*)\n\n(*\ninversion … in ident1 … identn\nゴールだけでなく前提 ident1 … identn においても、得られた条件に基づいた書き換えを行う。\n\ninversion … as … in …\ninversion タクティクの最も一般的な形。\n\ninversion_clear ident\ninversion_clear ident as …\ninversion_clear ident in …\ninversion_clear ident as … in …\ninversion した後に、ident および不要な条件等を自動的に前提から消去する。\n\ninversion ident1 using ident2\ninversion ident1 using ident2 in …\nDerive Inversion コマンドで作成した補題 ident2 を使用して inversion ident1 を行う。\n*)\n\nDerive Inversion le_0_inv with (forall n, n <= 0) Sort Prop.\n\nCheck le_0_inv.\n(*\nle_0_inv\n     : forall (n : nat) (P : nat -> Prop),\n       (n <= 0 -> n = 0 -> P 0) -> n <= 0 -> P n\n*)\n\nGoal forall n, n <= 0 -> n = 0.\nProof.\n  intros n H.\n  inversion H using le_0_inv.\n  reflexivity.\nQed.\n(*\nこの例で inversion H using le_0_inv がしていることは、pattern n; apply le_0_inv, H に等しい。\n*)\n\n(*\nDerive Inversion コマンドの亜種として、Derive Inversion_clear, Derive Dependent Inversion, Derive\nDependent Inversion_clear コマンドがある。\n\ndependent inversion ident\ndependent inversion ident as …\ndependent inversion ident with …\ndependent inversion ident as … with …\ndependent inversion_clear ident\ndependent inversion_clear ident as …\ndependent inversion_clear ident with …\ndependent inversion_clear ident as … with …\nident 自体がゴールの型に含まれる場合に使う。通常の inversion/inversion_clear の処理をする他に、ゴール\nの型に含まれる ident を実際に場合分けされた値に置換する。\n\nsimple inversion ident\nsimple inversion num\nより単純な inversion を行う。すなわち、場合分けの際に条件が噛み合わない場合を除外したり、得られた条件\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/coq_inversion_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430520409023, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.6996775327955953}}
{"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.\n\n(* Why3 comment *)\n(* infix_ls is replaced with (x < x1)%Z by the coq driver *)\n\n(* Why3 goal *)\nLemma infix_lseq_def :\n  forall (x:Z) (y:Z), (x <= y)%Z <-> ((x < y)%Z \\/ (x = y)).\nexact Zle_lt_or_eq_iff.\nQed.\n\n(* Why3 comment *)\n(* infix_pl is replaced with (x + x1)%Z by the coq driver *)\n\n(* Why3 comment *)\n(* prefix_mn is replaced with (-x)%Z by the coq driver *)\n\n(* Why3 comment *)\n(* infix_as is replaced with (x * x1)%Z by the coq driver *)\n\n(* Why3 goal *)\nLemma Assoc :\nforall (x:Z) (y:Z) (z:Z), (((x + y)%Z + z)%Z = (x + (y + z)%Z)%Z).\nProof.\nintros x y z.\napply sym_eq.\napply Zplus_assoc.\nQed.\n\n(* Why3 goal *)\nLemma Unit_def_l :\nforall (x:Z), ((0%Z + x)%Z = x).\nProof.\nexact Zplus_0_l.\nQed.\n\n(* Why3 goal *)\nLemma Unit_def_r :\nforall (x:Z), ((x + 0%Z)%Z = x).\nProof.\nexact Zplus_0_r.\nQed.\n\n(* Why3 goal *)\nLemma Inv_def_l :\nforall (x:Z), (((-x)%Z + x)%Z = 0%Z).\nProof.\nexact Zplus_opp_l.\nQed.\n\n(* Why3 goal *)\nLemma Inv_def_r :\nforall (x:Z), ((x + (-x)%Z)%Z = 0%Z).\nProof.\nexact Zplus_opp_r.\nQed.\n\n(* Why3 goal *)\nLemma Comm :\nforall (x:Z) (y:Z), ((x + y)%Z = (y + x)%Z).\nProof.\nexact Zplus_comm.\nQed.\n\n(* Why3 goal *)\nLemma Assoc1 :\nforall (x:Z) (y:Z) (z:Z), (((x * y)%Z * z)%Z = (x * (y * z)%Z)%Z).\nProof.\nintros x y z.\napply sym_eq.\napply Zmult_assoc.\nQed.\n\n(* Why3 goal *)\nLemma Mul_distr_l :\nforall (x:Z) (y:Z) (z:Z), ((x * (y + z)%Z)%Z = ((x * y)%Z + (x * z)%Z)%Z).\nProof.\nintros x y z.\napply Zmult_plus_distr_r.\nQed.\n\n(* Why3 goal *)\nLemma Mul_distr_r :\nforall (x:Z) (y:Z) (z:Z), (((y + z)%Z * x)%Z = ((y * x)%Z + (z * x)%Z)%Z).\nProof.\nintros x y z.\napply Zmult_plus_distr_l.\nQed.\n\n(* Why3 goal *)\nLemma infix_mn_def : forall (x:Z) (y:Z), ((x - y)%Z = (x + (-y)%Z)%Z).\nreflexivity.\nQed.\n\n(* Why3 goal *)\nLemma Comm1 :\nforall (x:Z) (y:Z), ((x * y)%Z = (y * x)%Z).\nProof.\nexact Zmult_comm.\nQed.\n\n(* Why3 goal *)\nLemma Unitary :\nforall (x:Z), ((1%Z * x)%Z = x).\nProof.\nexact Zmult_1_l.\nQed.\n\n(* Why3 goal *)\nLemma NonTrivialRing :\n~ (0%Z = 1%Z).\nProof.\ndiscriminate.\nQed.\n\n(* Why3 goal *)\nLemma Refl :\nforall (x:Z), (x <= x)%Z.\nProof.\nintros x.\napply Zle_refl.\nQed.\n\n(* Why3 goal *)\nLemma Trans :\nforall (x:Z) (y:Z) (z:Z), (x <= y)%Z -> ((y <= z)%Z -> (x <= z)%Z).\nProof.\nexact Zle_trans.\nQed.\n\n(* Why3 goal *)\nLemma Antisymm :\nforall (x:Z) (y:Z), (x <= y)%Z -> ((y <= x)%Z -> (x = y)).\nProof.\nexact Zle_antisym.\nQed.\n\n(* Why3 goal *)\nLemma Total :\nforall (x:Z) (y:Z), (x <= y)%Z \\/ (y <= x)%Z.\nProof.\nintros x y.\ndestruct (Zle_or_lt x y) as [H|H].\nleft.\nassumption.\nright.\nnow apply Zlt_le_weak.\nQed.\n\n(* Why3 goal *)\nLemma ZeroLessOne :\n(0%Z <= 1%Z)%Z.\nProof.\napply Zle_lt_or_eq_iff.\nnow left.\nQed.\n\n(* Why3 goal *)\nLemma CompatOrderAdd :\nforall (x:Z) (y:Z) (z:Z), (x <= y)%Z -> ((x + z)%Z <= (y + z)%Z)%Z.\nProof.\nexact Zplus_le_compat_r.\nQed.\n\n(* Why3 goal *)\nLemma CompatOrderMult :\nforall (x:Z) (y:Z) (z:Z),\n (x <= y)%Z -> ((0%Z <= z)%Z -> ((x * z)%Z <= (y * z)%Z)%Z).\nProof.\nexact Zmult_le_compat_r.\nQed.\n\n", "meta": {"author": "florianschanda", "repo": "why3", "sha": "dc0d2720d58c6d130b9c3e1db820a07275a133eb", "save_path": "github-repos/coq/florianschanda-why3", "path": "github-repos/coq/florianschanda-why3/why3-dc0d2720d58c6d130b9c3e1db820a07275a133eb/lib/coq/int/Int.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.6995373935273288}}
{"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\nSet Implicit Arguments.\n\nSection sublist_defs.\n\n  Variable X : Type.\n\n  Reserved Notation \"x '<sl' y\" (at level 70).\n\n  Inductive sublist : list X -> list X -> Prop :=\n    | in_sl_0 : forall ll, nil <sl ll\n    | in_sl_1 : forall a ll mm, ll <sl mm -> a::ll <sl a::mm\n    | in_sl_2 : forall a ll mm, ll <sl mm -> ll <sl a::mm\n  where \"x <sl y\" := (sublist x y).\n  \n  Hint Constructors sublist.\n  \n  Fact sl_refl ll : ll <sl ll.              Proof. induction ll; auto. Qed.\n  \n  Hint Resolve sl_refl.\n\n  Fact sl_cons a ll : ll <sl a::ll.         Proof. auto. Qed.\n  Fact sl_app_left ll mm : mm <sl ll++mm.   Proof. induction ll; simpl; auto. Qed.\n  Fact sl_app_right ll mm : ll <sl ll++mm.  Proof. induction ll; simpl; auto. Qed.\n\n  Hint Resolve sl_cons sl_app_left sl_app_right.\n\n  Fact sl_nil_inv l : l <sl nil <-> l = nil.\n  Proof. \n    split.\n    + inversion 1; auto.\n    + intros; subst; auto.\n  Qed.\n  \n  Fact sl_cons_inv x y l m : x::l <sl y::m <-> (x = y /\\ l <sl m) \\/ x::l <sl m.\n  Proof.\n    split.\n    + inversion 1; subst; auto.\n    + intros [[]|]; subst; auto.\n  Qed.\n  \nEnd sublist_defs.\n\nInfix \"<sl\" := (@sublist _) (at level 70).\n\nHint Constructors sublist.\nHint Resolve sl_refl sl_cons sl_app_left sl_app_right.\n\nTactic Notation \"sl\" \"nil\" \"inv\" hyp(H) :=\n  repeat match type of H with\n    | _::_  <sl nil   => rewrite sl_nil_inv in H; discriminate\n    | _     <sl nil   => rewrite sl_nil_inv in H; subst\n  end; auto.\n  \nTactic Notation \"sl\" \"cons\" \"inv\" hyp(H) \"left\" :=\n  match type of H with\n    | ?a::_ <sl ?b::_ => rewrite sl_cons_inv in H; destruct H as [ (?&H) | H ]; [ subst a | ]\n  end; auto.\n  \nTactic Notation \"sl\" \"cons\" \"inv\" hyp(H) \"right\" :=\n  match type of H with\n    | ?a::_ <sl ?b::_ => rewrite sl_cons_inv in H; destruct H as [ (?&H) | H ]; [ subst b | ]\n  end; auto.\n\nTactic Notation \"sl\" \"inv\" hyp(H) :=\n  repeat match type of H with\n    | _ <sl nil       => sl nil inv H\n    | ?a::_ <sl ?b::_ => sl cons inv H left\n    | ?l    <sl _::_  => destruct l as [ | ? l ]; auto; sl cons inv H left\n    | ?a::_ <sl ?l    => destruct l as [ | ? l ]; auto; sl cons inv H right \n  end; auto.\n\nSection sublist_props.\n\n  Variable (X : Type).\n  \n  Implicit Type (l ll : list X).\n  \n  Fact sl_trans l1 l2 l3 : l1 <sl l2 -> l2 <sl l3 -> l1 <sl l3.\n  Proof.\n    intros H1 H2; revert H2 l1 H1.\n    induction 1; intros ? H1; auto; sl inv H1.\n  Qed.\n  \n  Fact sl_app l1 m1 l2 m2 : l1 <sl l2 -> m1 <sl m2 -> l1++m1 <sl l2++m2.\n  Proof.\n    intros H1 H2.\n    apply sl_trans with (l2 := l1++m2); auto.\n    + clear H1; induction l1; simpl; auto.\n    + clear H2; induction H1; simpl; auto.\n  Qed.\n\n  Fact sublist_nil_inv x l : x::l <sl nil <-> False.\n  Proof. split; inversion 1; auto. Qed.\n\n  Fact sublist_inv_cons l a : l <sl a::nil <-> l = nil \\/ l = a::nil.\n  Proof.\n    split.\n    + intros H; sl inv H.\n    + intros [|]; subst; auto.\n  Qed. \n  \n  Fact sublist_app_inv_lft l1 r1 mm : l1++r1 <sl mm -> exists l2 r2, mm = l2++r2 /\\ l1 <sl l2 /\\ r1 <sl r2.\n  Proof.\n    revert l1 r1; induction mm as [ | x mm IH ]; simpl; intros l1 r1 H.\n    + sl inv H; destruct l1; destruct r1; try discriminate; exists nil, nil; auto.\n    + destruct l1 as [ | y l1 ].\n      * exists nil, (x::mm); auto.\n      * simpl in H; sl inv H. \n        - destruct (IH _ _ H) as (l2 & r2 & H1 & H2 & H3).\n          exists (x::l2), r2; subst; auto.\n        - destruct (IH (_::_) _ H) as (l2 & r2 & H1 & H2 & H3).\n          exists (x::l2), r2; subst; auto.\n  Qed.\n\n  Fact sublist_app_inv_rt ll l2 r2 : ll <sl l2++r2 -> exists l1 r1, ll = l1++r1 /\\ l1 <sl l2 /\\ r1 <sl r2.\n  Proof.\n    revert ll; induction l2 as [ | x l2 IH ]; intros ll H.\n    + exists nil, ll; auto.\n    + destruct ll as [ | y ll ].\n      * exists nil, nil; auto.\n      * simpl in H; sl inv H; destruct (IH _ H) as (l1 & r1 & H1 & H2 & H3).\n        - exists (x::l1), r1; subst; auto.\n        - exists l1, r1; subst; auto.\n  Qed.\n\n  Fact sublist_cons_inv_rt ll x mm : ll <sl x::mm -> ll <sl mm \\/ exists l', ll = x::l' /\\ l' <sl mm.\n  Proof. destruct ll; auto; intros H; sl inv H; right; firstorder. Qed.\n  \n  Fact sl_length ll mm : ll <sl mm -> length ll <= length mm.\n  Proof. induction 1; simpl; auto; omega. Qed.\n\n  Fact sl_In ll mm x : ll <sl mm -> In x ll -> In x mm.\n  Proof. induction 1; simpl; tauto. Qed.\n\n  Fact In_sl x ll : In x ll <-> x::nil <sl ll.\n  Proof.\n    split.\n    + intros H; apply in_split in H.\n      destruct H as (? & ? & ?); subst.\n      apply sl_trans with (2 := sl_app_left _ _); auto.\n    + intros H; apply (sl_In _ H); left; auto.\n  Qed.\n  \n  Fact sl_erase l m r mm : l++m++r <sl mm -> l++r <sl mm.\n  Proof. intros H; apply sl_trans with (2 := H), sl_app; auto. Qed.\n\n  Fact sl_snoc l m x : l <sl m -> l <sl (m++x::nil).\n  Proof. intros H; apply sl_trans with (1 := H); auto. Qed.\n  \n  Hint Resolve sl_app sl_snoc.\n  \n  Fact sl_rev l m : l <sl m -> rev l <sl rev m.\n  Proof. induction 1; simpl; auto. Qed.\n\n  Fact sublist_cons_inv x ll mm : x::ll <sl mm <-> exists l r, mm = l++x::r /\\ ll <sl r.\n  Proof.\n    split.\n    * change (x::ll) with ((x::nil)++ll); intros H.\n      apply sublist_app_inv_lft in H.\n      destruct H as (pp & r & H1 & H2 & H3).\n      rewrite <- In_sl in H2.\n      apply in_split in H2.\n      destruct H2 as (l & m & H2); subst.\n      exists l, (m++r); rewrite app_ass; simpl; split; auto.\n      apply sl_trans with (1 := H3); auto.\n    * intros (? & ? & ? & ?); subst.\n      apply sl_trans with (2 := sl_app_left _ _); auto.\n  Qed.\n  \n  Fact sublist_snoc_inv ll mm x : ll <sl mm++x::nil -> ll <sl mm \\/ exists l', l' <sl mm /\\ ll = l'++x::nil.\n  Proof.\n    intros H.\n    apply sublist_app_inv_rt in H.\n    destruct H as ( l1 & r1 & H1 & H2 & H3 ).\n    inversion H3; subst.\n    left; rewrite <- app_nil_end; auto.\n    apply sublist_inv_cons in H3.\n    destruct H3 as [ H3 | H3 ]; try discriminate H3.\n    injection H3; clear H3; intros; subst.\n    right; exists l1; auto.\n    left; rewrite (app_nil_end mm); auto.\n  Qed.\n\n  Fact sl_cons_erase a l m : a::l <sl m -> l <sl m.\n  Proof. apply sl_erase with (l := nil) (m := a::nil). Qed.\n\n  Fact sublist_eq ll mm : ll <sl mm -> length mm <= length ll -> ll = mm.\n  Proof.\n    induction 1 as [ mm | a ll mm H IH | a ll mm H IH ].\n    destruct mm; simpl; try omega; auto.\n    simpl; intros H1; apply le_S_n in H1; f_equal; auto.\n    simpl; intros H1; apply sl_length in H; omega.\n  Qed.\n\nEnd sublist_props.\n\nHint Resolve sl_app sl_snoc.\n\nFact sublist_map X Y (f : X -> Y) l m : l <sl m -> map f l <sl map f m.\nProof. induction 1; simpl; auto. Qed.\n\n\n", "meta": {"author": "DmxLarchey", "repo": "Ramsey", "sha": "24510f63d4290149c4944fe68267d342345621ed", "save_path": "github-repos/coq/DmxLarchey-Ramsey", "path": "github-repos/coq/DmxLarchey-Ramsey/Ramsey-24510f63d4290149c4944fe68267d342345621ed/src/sublist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.6995373888015572}}
{"text": "Require Import Logic.Nat.Fresh.\nRequire Import Logic.Fol.Syntax.\n\nDefinition Formula : Type := P nat.\n\nDefinition Not (p:Formula)          :Formula := Imp p Bot.\nDefinition Or  (p q:Formula)        :Formula := Imp (Not p) q.\nDefinition And (p q:Formula)        :Formula := Not (Or (Not p) (Not q)).\nDefinition Exi  (n:nat) (p:Formula) :Formula := Not (All n (Not p)).\nDefinition Iff (p q:Formula)        :Formula := And (Imp p q) (Imp q p).\n\nDefinition Sub (n m:nat) : Formula := \n    let x := fresh n m in\n        All x (Imp (Elem x n) (Elem x m)).\n\nDefinition Equ (n m:nat) : Formula := \n    let x := fresh n m in And\n        (All x (Iff (Elem x n) (Elem x m)))\n        (All x (Iff (Elem n x) (Elem m x))).\n\nDefinition Empty (n:nat) : Formula := \n    let x := fresh n n in\n        All x (Not (Elem x n)).\n\n(* Predicate expressing the 'minimality' of a set n in a set m                  *)\nDefinition Min (n m:nat) : Formula :=\n    let x := fresh n m in And\n        (Elem n m)\n        (Not (Exi x (And (Elem x m) (Elem x 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/Lang1/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6995266916061029}}
{"text": "From Coq Require Import ArithRing.\nFrom Coq Require Import Compare_dec.\nFrom Coq Require Import Wf_nat.\nFrom Coq Require Import Arith.\nFrom Coq Require Import Lia.\n\nLemma add_zero_r : forall n, n + 0 = n.\nProof.\n  intros n.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite IHn.\n  reflexivity.\nQed.\n\nLemma x_times_2_is_even : forall x : nat,\n  Nat.even (2*x) = true.\nProof.\n  simpl.\n  induction x.\n  - simpl.\n    reflexivity.\n  - rewrite add_zero_r.\n    rewrite add_zero_r in IHx.\n    replace (S x + S x) with (S (S (x + x))).\n    + simpl.\n      apply IHx.\n    + simpl.\n      rewrite (Nat.add_comm x (S x)).\n      simpl.\n      reflexivity.\nQed.\n\nLemma even_exists : forall x : nat,\n  Nat.even x = true -> exists k, 2*k = x.\nProof.\n  intros.\n  apply Nat.even_spec in H.\n  unfold Nat.Even in H.\n  destruct H.\n  exists x0.\n  symmetry.\n  apply H.\nQed.\n\nLemma next_even_is_odd : forall x : nat,\n  Nat.even x = negb (Nat.even (S x)).\nProof.\n  intros.\n  induction x.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> IHx.\n    rewrite -> Bool.negb_involutive.\n    reflexivity.\nQed.\n\nLemma cancel_negb : forall a b: bool,\n  negb a = negb b -> a = b.\nProof.\n  intros.\n  destruct a.\n  - destruct b.\n    + reflexivity.\n    + simpl in H.\n      symmetry.\n      apply H.\n  - destruct b.\n    + simpl in H.\n      symmetry.\n      apply H.\n    + reflexivity.\nQed.\n\nLemma even_is_xor: forall x y : nat,\n  Nat.even (x+y) = negb (xorb (Nat.even x) (Nat.even y)).\nProof.\n  intros.\n  induction x.\n  - simpl.\n    case (Nat.even y); reflexivity.\n  - rewrite next_even_is_odd in IHx.\n    rewrite (next_even_is_odd x) in IHx.\n    apply cancel_negb in IHx.\n    rewrite Nat.add_succ_l.\n    rewrite -> IHx.\n    clear IHx.\n    rewrite Bool.negb_xorb_l.\n    reflexivity.\nQed.\n\nLemma square_even_is_even : forall x : nat,\n  Nat.even (x*x) = Nat.even x.\nProof.\n  intros.\n  induction x.\n  - simpl.\n    reflexivity.\n  - replace (S x * S x) with ((1 + x) * (1 + x)).\n    2: {\n      simpl.\n      reflexivity.\n    }\n    rewrite Nat.mul_add_distr_r.\n    rewrite Nat.mul_add_distr_l.\n    repeat rewrite Nat.mul_1_l.\n    rewrite Nat.mul_add_distr_l.\n    repeat rewrite Nat.mul_1_r.\n    rewrite Nat.add_assoc.\n    repeat rewrite <- Nat.add_assoc.\n    repeat rewrite even_is_xor.\n    repeat rewrite <- IHx.\n    replace (Nat.even 1) with false.\n    2 : { trivial. }\n    rewrite -> Bool.xorb_false_l.\n    rewrite -> Bool.xorb_nilpotent.\n    rewrite -> Bool.negb_involutive.\n    replace (negb false) with (true).\n    2 : { trivial. }\n    rewrite -> Bool.xorb_true_r.\n    rewrite -> IHx.\n    clear IHx.\n    induction x.\n    + simpl.\n      reflexivity.\n    + rewrite <- IHx.\n      rewrite -> Bool.negb_involutive.\n      simpl.\n      reflexivity.\nQed.\n\n\nLemma cancel_2: forall x y : nat,\n  2 * x = 2 * y -> x = y.\nProof.\n  intros.\n  lia.\nQed.\n\n\nTheorem sqrt2_infinite_descent: forall p q,\n  (q <> 0 /\\ p*p = 2*q*q) -> exists pp qq : nat,\n (qq <> 0 /\\ pp * pp = 2 * qq * qq) /\\ qq < q.\nProof.\n  intros p q [qnz eq].\n  assert (eq' := eq).\n\n  assert (Nat.even (p*p) = true).\n  {\n    rewrite -> eq.\n    rewrite <- Nat.mul_assoc.\n    apply x_times_2_is_even.\n  }\n\n  assert (Nat.even p = true).\n  {\n    rewrite square_even_is_even in H.\n    apply H.\n  }\n\n  apply even_exists in H0.\n  destruct H0 as [p' Hp'].\n  rewrite <- Hp' in eq.\n  repeat rewrite <- Nat.mul_assoc in eq.\n  apply cancel_2 in eq.\n  rewrite Nat.mul_comm in eq.\n  clear H.\n\n  assert (Nat.even (q*q) = true).\n  {\n    rewrite <- eq.\n    rewrite <- Nat.mul_assoc.\n    apply x_times_2_is_even.\n  }\n\n  assert (Nat.even q = true).\n  {\n    rewrite square_even_is_even in H.\n    apply H.\n  }\n\n  apply even_exists in H0.\n  destruct H0 as [q' Hq'].\n  rewrite <- Hq' in eq.\n  repeat rewrite <- Nat.mul_assoc in eq.\n  apply cancel_2 in eq.\n  symmetry in eq.\n  rewrite Nat.mul_comm in eq.\n  clear H.\n  symmetry in eq.\n\n  assert (q > q').\n  lia.\n\n  exists p'.\n  exists q'.\n  split.\n  split.\n  rewrite <- Hq' in qnz.\n  lia.\n  apply eq.\n  apply H.\nQed.\n\nDefinition lt_nat (p q : nat*nat) := snd p < snd q.\n\nTheorem lt_wf: well_founded lt_nat.\nProof.\n  apply (well_founded_lt_compat (nat*nat) snd).\n  intros.\n  unfold lt_nat in H.\n  apply H.\n\nQed.\n\nTheorem infinite_descent: forall f : nat -> nat -> Prop,\n  (forall p q : nat, ((f p q) -> exists p' q' : nat, (f p' q') /\\ q' < q)) ->\n  forall r s : nat, ~(f r s).\nProof.\n  intros f H.\n  intros r s.\n  pose (rs := (r,s)).\n  replace r with (fst rs); try reflexivity.\n  replace s with (snd rs); try reflexivity.\n  apply (well_founded_ind lt_wf (fun x => ~(f (fst x) (snd x)))).\n  intros.\n  specialize (H (fst x) (snd x)).\n  unfold not.\n  intros HA.\n  apply H in HA.\n  destruct HA as [A HA].\n  destruct HA as [B HA].\n  specialize (H0 (A,B)).\n  unfold lt_nat in H0.\n  destruct HA.\n  simpl in H0.\n  apply H0 in H2.\n  apply H2.\n  apply H1.\nQed.\n\nTheorem sqrt2_is_irrational: forall p q: nat,\n  q <> 0 -> p*p <> 2*q*q.\nProof.\n  intros p q qnz.\n  unfold not.\n  intros eq.\n  specialize (infinite_descent (fun (p q : nat) => q <> 0 /\\ p * p = 2 * q * q)).\n  intros id.\n  simpl in id.\n  generalize sqrt2_infinite_descent.\n  intros.\n  simpl in H.\n  assert (forall r s : nat, ~(s <> 0 /\\ r * r = (s + (s + 0)) * s)).\n  {\n    apply id.\n    apply H.\n  }\n\n  specialize (H0 p q).\n  unfold not in H0.\n  destruct H0.\n  split.\n  apply qnz.\n  apply eq.\n\nQed.\n\n\n  Set Printing All\n", "meta": {"author": "GwenTinho", "repo": "Examples-Coq-Prolog", "sha": "fb12d2ddc5dc76ffca5e66d9b6514eb71a3fd569", "save_path": "github-repos/coq/GwenTinho-Examples-Coq-Prolog", "path": "github-repos/coq/GwenTinho-Examples-Coq-Prolog/Examples-Coq-Prolog-fb12d2ddc5dc76ffca5e66d9b6514eb71a3fd569/coq/sqrt2Irrational.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6995266865803413}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) (lf1 : natural) : natural :=\n  mult (Succ Zero) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj43_coqofml_TfCzp5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6995266865444196}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq               *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later              *)\nFrom mathcomp Require Import all_ssreflect fingroup perm matrix.\nRequire Import Reals.\nFrom mathcomp Require Import Rstruct.\nRequire Import ssrR Reals_ext ssr_ext ssralg_ext Rbigop bigop_ext logb ln_facts.\nRequire Import fdist jfdist_cond proba binary_entropy_function divergence.\n\n(******************************************************************************)\n(*                Chapter 2 of Elements of Information Theory                 *)\n(*                                                                            *)\n(* Formalization of the chapter 2 of:                                         *)\n(* Thomas M. Cover, Joy A. Thomas, Elements of Information Theory, Wiley,     *)\n(* 2005                                                                       *)\n(* See also entropy_convex.v                                                  *)\n(*                                                                            *)\n(*                        `H P == the entropy of the (finite) probability     *)\n(*                                distribution P                              *)\n(*                 entropy_ge0 == the entropy is non-negative                 *)\n(*                 entropy_max == the entropy is bounded by log |A| where A   *)\n(*                                is the support of the distribution          *)\n(*                  entropy_Ex == the entropy is the expectation of the       *)\n(*                                negative logarithm                          *)\n(*                xlnx_entropy == the entropy is the natural entropy scaled   *)\n(*                                by ln(2)                                    *)\n(*             entropy_uniform == the entropy of a uniform distribution is    *)\n(*                                just log                                    *)\n(*                  entropy_H2 == the binary entropy H2 is the entropy over   *)\n(*                                {x, y}                                      *)\n(*               joint_entropy == entropy of a joint distribution             *)\n(*                cond_entropy == conditional entropy of a joint distribution *)\n(*                  chain_rule == (thm 2.1.1)                                 *)\n(*                 mutual_info == mutual information (`I(X ; Y))              *)\n(*               chain_rule_rV == chain rule for entropy (thm 2.5.1)          *)\n(*      chain_rule_information == chain rule for information (thm 2.5.2)      *)\n(* chain_rule_relative_entropy == chain rule for relative entropy (thm 2.5.3) *)\n(*  data_processing_inequality == (thm 2.8.1)                                 *)\n(*                         han == Han's inequality                            *)\n(*                                                                            *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nReserved Notation \"'`H'\" (at level 5).\nReserved Notation \"`H( X , Y )\" (at level 10, X, Y at next level,\n  format \"`H( X ,  Y )\").\nReserved Notation \"`H( Y | X )\" (at level 10, Y, X at next level).\nReserved Notation \"`I( X ; Y )\" (at level 50, format \"`I( X ;  Y )\").\n\nDeclare Scope entropy_scope.\nDeclare Scope chap2_scope.\nDelimit Scope chap2_scope with chap2.\n\nLocal Open Scope R_scope.\nLocal Open Scope fdist_scope.\nLocal Open Scope proba_scope.\nLocal Open Scope vec_ext_scope.\n\nSection entropy_definition.\nVariables (A : finType) (P : fdist A).\n\nDefinition entropy := - \\sum_(a in A) P a * log (P a).\nLocal Notation \"'`H'\" := (entropy).\n\nLemma entropy_ge0 : 0 <= `H.\nProof.\nrewrite /entropy big_morph_oppR; apply sumR_ge0 => i _.\nhave [->|Hi] := eqVneq (P i) 0; first by rewrite mul0R oppR0; exact/leRR.\n  (* NB: this step in a standard textbook would be handled as a consequence of lim x->0 x log x = 0 *)\nrewrite mulRC -mulNR; apply mulR_ge0 => //; apply: oppR_ge0.\nrewrite -log1; apply Log_increasing_le => //.\nby apply/ltRP; rewrite lt0R Hi; exact/leRP.\nQed.\n\nEnd entropy_definition.\n\nNotation \"'`H'\" := (entropy) : entropy_scope.\nLocal Open Scope entropy_scope.\n\nSection entropy_theory.\nLocal Open Scope fdist_scope.\nLocal Open Scope proba_scope.\nContext (A : finType).\n\nLemma entropy_Ex (P : fdist A) : `H P = `E (`-- (`log P)).\nProof.\nrewrite /entropy /log_RV /= big_morph_oppR.\nby apply eq_bigr => a _; rewrite mulRC -mulNR.\nQed.\n\nLemma xlnx_entropy (P : fdist A) : `H P = / ln 2 * - \\sum_(a : A) xlnx (P a).\nProof.\nrewrite /entropy mulRN; congr (- _); rewrite big_distrr/=.\napply: eq_bigr => a _; rewrite /log /Rdiv mulRA mulRC; congr (_ * _).\nrewrite /xlnx; case : ifP => // /ltRP Hcase.\nhave -> : P a = 0 by case (Rle_lt_or_eq_dec 0 (P a)).\nby rewrite mul0R.\nQed.\n\nLemma entropy_uniform n (An1 : #|A| = n.+1) :\n  `H (fdist_uniform An1) = log (INR #|A|).\nProof.\nrewrite /entropy.\nunder eq_bigr do rewrite fdist_uniformE.\nrewrite big_const iter_addR mulRA mulRV; last by rewrite INR_eq0' An1.\nby rewrite mul1R logV ?oppRK//; rewrite An1; apply/ltR0n.\nQed.\n\nLemma entropy_H2 (card_A : #|A| = 2%nat) (p : prob) :\n  H2 p = entropy (fdist_binary card_A p (Set2.a card_A)).\nProof.\nrewrite /H2 /entropy Set2sumE /= fdist_binaryxx !fdist_binaryE.\nby rewrite eq_sym (negbTE (Set2.a_neq_b _)) oppRD addRC.\nQed.\n\nLemma entropy_max (P : fdist A) : `H P <= log #|A|%:R.\nProof.\nhave [n An1] : exists n, #|A| = n.+1.\n  by exists #|A|.-1; rewrite prednK //; exact: (fdist_card_neq0 P).\nhave /div_ge0 H := dom_by_uniform P An1.\nrewrite -subR_ge0; apply/(leR_trans H)/Req_le.\ntransitivity (\\sum_(a|a \\in A) P a * log (P a) +\n              \\sum_(a|a \\in A) P a * - log (fdist_uniform An1 a)).\n  rewrite -big_split /=; apply eq_bigr => a _; rewrite -mulRDr.\n  case/boolP : (P a == 0) => [/eqP ->|H0]; first by rewrite !mul0R.\n  congr (_ * _); rewrite logDiv ?addR_opp //.\n    by rewrite -fdist_gt0.\n  by rewrite fdist_uniformE; apply/invR_gt0; rewrite An1; exact/ltR0n.\nunder [in X in _ + X]eq_bigr do rewrite fdist_uniformE.\nrewrite -[in X in _ + X = _]big_distrl /= FDist.f1 mul1R.\nby rewrite addRC /entropy /log LogV ?oppRK ?subR_opp // An1; exact/ltR0n.\nQed.\n\nLemma entropy_fdist_rV_of_prod n (P : {fdist A * 'rV[A]_n}) :\n  `H (fdist_rV_of_prod P) = `H P.\nProof.\nrewrite /entropy /=; congr (- _).\nrewrite -(big_rV_cons_behead _ xpredT xpredT) /= pair_bigA /=.\napply eq_bigr => -[a b] _ /=.\nby rewrite fdist_rV_of_prodE /= row_mx_row_ord0 rbehead_row_mx.\nQed.\n\nLemma entropy_fdist_prod_of_rV n (P : {fdist 'rV[A]_n.+1}) :\n  `H (fdist_prod_of_rV P) = `H P.\nProof.\nrewrite /entropy /=; congr (- _).\nrewrite -(big_rV_cons_behead _ xpredT xpredT) /= pair_bigA /=.\napply eq_bigr => -[a b] _ /=; by rewrite fdist_prod_of_rVE /=.\nQed.\n\nLemma entropy_fdist_perm n (P : {fdist 'rV[A]_n}) (s : 'S_n) :\n  `H (fdist_perm P s) = `H P.\nProof.\nrewrite /entropy; congr (- _) => /=; apply/esym.\nrewrite (@reindex_inj _ _ _ _ (@col_perm _ _ _ s) xpredT); last first.\n  exact: col_perm_inj.\nby apply eq_bigr => v _; rewrite fdist_permE.\nQed.\n\nEnd entropy_theory.\n\nSection joint_entropy.\nVariables (A B : finType) (P : {fdist A * B}).\n\n(* eqn 2.8 *)\nDefinition joint_entropy := `H P.\n\n(* eqn 2.9 *)\nLemma joint_entropyE : joint_entropy = `E (`-- (`log P)).\nProof. by rewrite /joint_entropy entropy_Ex. Qed.\n\nLemma joint_entropyC : joint_entropy = `H (fdistX P).\nProof.\ncongr (- _) => /=.\nrewrite (eq_bigr (fun a => P (a.1, a.2) * log (P (a.1, a.2)))); last by case.\nrewrite -(pair_bigA _ (fun a1 a2 => P (a1, a2) * log (P (a1, a2)))) /=.\nby rewrite exchange_big pair_big; apply eq_bigr => -[a b] _; rewrite fdistXE.\nQed.\n\nEnd joint_entropy.\n\nLemma entropy_rV (A : finType) n (P : {fdist 'rV[A]_n.+1}) :\n  `H P = joint_entropy (fdist_belast_last_of_rV P).\nProof.\nrewrite /joint_entropy /entropy; congr (- _) => /=.\nrewrite -(big_rV_belast_last _ xpredT xpredT) /=.\nrewrite pair_big /=; apply eq_bigr => -[a b] _ /=.\nby rewrite fdist_belast_last_of_rVE.\nQed.\n\nSection joint_entropy_RV_def.\nVariables (U A B : finType) (P : {fdist U}) (X : {RV P -> A}) (Y : {RV P -> B}).\nDefinition joint_entropy_RV := joint_entropy `p_[% X, Y].\nEnd joint_entropy_RV_def.\nNotation \"'`H(' X ',' Y ')'\" := (joint_entropy_RV X Y) : chap2_scope.\n\nLocal Open Scope chap2_scope.\n\nSection joint_entropy_RV_prop.\nVariables (U A B : finType) (P : {fdist U}) (X : {RV P -> A}) (Y : {RV P -> B}).\n\n(* 2.9 *)\nLemma eqn29 : `H(X, Y) = - `E (`log `p_[% X, Y]).\nProof. by rewrite /joint_entropy_RV joint_entropyE E_neg_RV. Qed.\n\nEnd joint_entropy_RV_prop.\n\nSection joint_entropy_prop.\nVariable (A : finType) (P : {fdist A}).\n\nLemma joint_entropy_self : joint_entropy (fdist_self P) = `H P.\nProof.\ncongr (- _).\nrewrite (eq_bigr (fun a => fdist_self P (a.1, a.2) *\n                           log (fdist_self P (a.1, a.2)))); last by case.\nrewrite -(pair_bigA _ (fun a1 a2 => fdist_self P (a1, a2) *\n                                    log (fdist_self P (a1, a2)))) /=.\napply/eq_bigr => a _.\nrewrite (bigD1 a) //= !fdist_selfE /= eqxx big1 ?addR0 //.\nby move=> a' /negbTE; rewrite fdist_selfE /= eq_sym => ->; rewrite mul0R.\nQed.\n\nEnd joint_entropy_prop.\n\nSection conditional_entropy.\nVariables (A B : finType) (QP : {fdist B * A}).\n\n(* H(Y|X = x), see eqn 2.10 *)\nDefinition cond_entropy1 a := - \\sum_(b in B)\n  \\Pr_QP [ [set b] | [set a] ] * log (\\Pr_QP [ [set b] | [set a] ]).\n\nLet P := QP`2.\n\n(*eqn 2.11 *)\nDefinition cond_entropy := \\sum_(a in A) P a * cond_entropy1 a.\n\nLet PQ := fdistX QP.\n\n(* cover&thomas 2.12 *)\nLemma cond_entropyE : cond_entropy = - \\sum_(a in A) \\sum_(b in B)\n  PQ (a, b) * log (\\Pr_QP [ [set b] | [set a]]).\nProof.\nrewrite /cond_entropy big_morph_oppR /=; apply eq_bigr => a _.\nrewrite /cond_entropy1 mulRN big_distrr /=; congr (- _); apply eq_bigr => b _.\nrewrite mulRA; congr (_ * _).\nby rewrite mulRC -(Pr_set1 P a) -jproduct_rule setX1 fdistXE Pr_set1.\nQed.\n\nLemma cond_entropy1_ge0 a : 0 <= cond_entropy1 a.\nProof.\nrewrite /cond_entropy1 big_morph_oppR; apply sumR_ge0 => b _; rewrite -mulRN.\nhave [->|H0] := eqVneq (\\Pr_QP[[set b]|[set a]]) 0.\n  by rewrite mul0R; exact/leRR.\napply mulR_ge0; [exact: jcPr_ge0|].\nrewrite -oppR0 -(Log_1 2) /log leR_oppr oppRK.\nby apply Log_increasing_le => //; [rewrite jcPr_gt0 | exact: jcPr_le1].\nQed.\n\nLemma cond_entropy_ge0 : 0 <= cond_entropy.\nProof.\nby apply sumR_ge0 => a _; apply mulR_ge0 => //; exact: cond_entropy1_ge0.\nQed.\n\nEnd conditional_entropy.\n\nSection cond_entropy1_RV_prop.\nVariables (U A B : finType) (P : {fdist U}) (X : {RV P -> A}) (Y : {RV P -> B}).\n\nDefinition cond_entropy1_RV a := `H (`p_[% X, Y] `(| a )).\n\nLemma cond_entropy1_RVE a : (`p_[% X, Y])`1 a != 0 ->\n  cond_entropy1_RV a = cond_entropy1 `p_[% Y, X] a.\nProof.\nmove=> a0.\nrewrite /cond_entropy1_RV /cond_entropy1 /entropy; congr (- _).\nby apply: eq_bigr => b _; rewrite jfdist_condE// fdistX_RV2.\nQed.\n\nEnd cond_entropy1_RV_prop.\nNotation \"'`H(' Y '|' X ')'\" := (cond_entropy `p_[% Y, X]) : chap2_scope.\n\nSection conditional_entropy_prop.\n\nVariables (A B C : finType) (PQR : {fdist A * B * C}).\n\nLemma cond_entropy1_fdistAC b c : cond_entropy1 (fdistA PQR) (b, c) =\n                                  cond_entropy1 (fdistA (fdistAC PQR)) (c, b).\nProof.\nrewrite /cond_entropy1; congr (- _).\nby apply eq_bigr => a _; rewrite -!setX1 jcPr_fdistA_AC.\nQed.\n\nLemma cond_entropy_fdistA : cond_entropy (fdistA PQR) = cond_entropy (fdistA (fdistAC PQR)).\nProof.\nrewrite /cond_entropy /=.\nrewrite (eq_bigr (fun a => (fdistA PQR)`2 (a.1, a.2) *\n                           cond_entropy1 (fdistA PQR) (a.1, a.2))); last by case.\nrewrite -(pair_bigA _ (fun a1 a2 => (fdistA PQR)`2 (a1, a2) *\n                                    cond_entropy1 (fdistA PQR) (a1, a2))) /=.\nrewrite exchange_big pair_big /=; apply eq_bigr => -[c b] _ /=; congr (_ * _).\n  by rewrite fdistA_AC_snd fdistXE.\nby rewrite cond_entropy1_fdistAC.\nQed.\n\nEnd conditional_entropy_prop.\n\nSection chain_rule.\nVariables (A B : finType) (PQ : {fdist A * B}).\nLet P := PQ`1.\nLet QP := fdistX PQ.\n\nLemma chain_rule : joint_entropy PQ = `H P + cond_entropy QP. (* 2.14 *)\nProof.\nrewrite /joint_entropy {1}/entropy.\ntransitivity (- (\\sum_(a in A) \\sum_(b in B)\n    PQ (a, b) * log (P a * \\Pr_QP [ [set b] | [set a] ]))). (* 2.16 *)\n  congr (- _); rewrite pair_big /=; apply eq_bigr => -[a b] _ /=.\n  congr (_ * log _); have [H0|H0] := eqVneq (P a) 0.\n  - by rewrite (dom_by_fdist_fst _ H0) H0 mul0R.\n  - rewrite -(Pr_set1 P a) /P -(fdistX2 PQ) mulRC -jproduct_rule setX1.\n    by rewrite Pr_set1 fdistXE.\ntransitivity (\n  - (\\sum_(a in A) \\sum_(b in B) PQ (a, b) * log (P a))\n  - (\\sum_(a in A) \\sum_(b in B) PQ (a, b) * log (\\Pr_QP [ [set b] | [set a] ]))). (* 2.17 *)\n  rewrite -oppRB; congr (- _); rewrite -addR_opp oppRK -big_split /=.\n  apply eq_bigr => a _; rewrite -big_split /=; apply eq_bigr => b _.\n  have [->|H0] := eqVneq (PQ (a, b)) 0; first by rewrite !mul0R addR0.\n  rewrite -mulRDr; congr (_ * _); rewrite mulRC logM //.\n    by rewrite -Pr_jcPr_gt0 setX1 Pr_set1 fdistXE -fdist_gt0.\n  by rewrite -fdist_gt0; exact: dom_by_fdist_fstN H0.\nrewrite [in X in _ + X = _]big_morph_oppR; congr (_ + _).\n- rewrite /entropy; congr (- _); apply eq_bigr => a _.\n  by rewrite -big_distrl /= -fdist_fstE.\n- rewrite cond_entropyE big_morph_oppR.\n  by apply eq_bigr => a _; congr (- _); apply eq_bigr => b _; rewrite !fdistXE.\nQed.\n\nEnd chain_rule.\n\nSection chain_rule_RV.\nLocal Open Scope chap2_scope.\nVariables (U A B : finType) (P : {fdist U}) (X : {RV P -> A}) (Y : {RV P -> B}).\n\nLemma chain_rule_RV : `H(X, Y) = `H `p_X + `H(Y | X).\nProof.\nrewrite /joint_entropy_RV.\nrewrite chain_rule fst_RV2.\ncongr (_ + _).\nby rewrite fdistX_RV2.\nQed.\n\nEnd chain_rule_RV.\n\nSection chain_rule_generalization.\n\nLocal Open Scope ring_scope.\n\n(* TODO: move *)\nDefinition put_front (n : nat) (i : 'I_n.+1) : 'I_n.+1 -> 'I_n.+1 := fun j =>\n  if j == i then ord0 else\n    if (j < i)%nat then inord (j.+1) else\n      j.\n\nDefinition put_back (n : nat) (i : 'I_n.+1) : 'I_n.+1 -> 'I_n.+1 := fun j =>\n  if j == ord0 then i else\n    if (j <= i)%nat then inord (j.-1) else\n      j.\n\nLemma put_backK n (i : 'I_n.+1) : cancel (put_front i) (put_back i).\nProof.\nmove=> j; rewrite /put_back /put_front; case: (ifPn (j == i)) => [ji|].\n  rewrite eqxx; exact/esym/eqP.\nrewrite neq_ltn => /orP[|] ji.\n  rewrite ji ifF; last first.\n    apply/negbTE/eqP => /(congr1 val) => /=.\n    by rewrite inordK // ltnS (leq_trans ji) // -ltnS.\n  rewrite inordK; last by rewrite ltnS (leq_trans ji) // -ltnS.\n  by rewrite ji /=; apply val_inj => /=; rewrite inordK.\nrewrite ltnNge (ltnW ji) /= ifF; last first.\n  by apply/negbTE; rewrite -lt0n (leq_trans _ ji).\nby rewrite leqNgt ji.\nQed.\n\nLemma put_front_inj (n : nat) (i : 'I_n.+1) : injective (put_front i).\nProof. exact: (can_inj (put_backK i)). Qed.\nArguments put_front_inj {n} _.\n\nDefinition put_front_perm (n : nat) i : 'S_n.+1 := perm (put_front_inj i).\n\n(* TODO: clean *)\nLemma fdist_col'_put_front n (A : finType) (P : {fdist 'rV[A]_n.+1}) (i : 'I_n.+1) :\n  i != ord0 ->\n  fdist_col' P i = (fdist_prod_of_rV (fdist_perm P (put_front_perm i)))`2.\nProof.\nmove=> i0; apply/fdist_ext => /= v; rewrite fdist_col'E fdist_sndE.\ndestruct n as [|n']; first by rewrite (ord1 i) eqxx in i0.\ntransitivity (\\sum_(x : A) P\n  (\\row_(k < n'.+2) (if k == i then x else v ``_ (inord (unbump i k)))))%R.\n  rewrite (reindex_onto (fun a => \\row_k (if k == i then a else v ``_ (inord (unbump i k))))\n    (fun w => w ``_ i)); last first.\n    move=> w wv.\n    apply/rowP => j.\n    rewrite !mxE; case: ifPn => [/eqP -> //|ji].\n    rewrite -(eqP wv) mxE; congr (w _ _).\n    move: ji; rewrite neq_ltn => /orP[|] ji.\n      apply val_inj => /=.\n      rewrite inordK; last first.\n        by rewrite /unbump (ltnNge i j) (ltnW ji) subn0 (leq_trans ji) // -ltnS.\n      by rewrite unbumpK //= inE ltn_eqF.\n    apply val_inj => /=.\n    rewrite inordK; last first.\n      by rewrite /unbump ji subn1 prednK //; [rewrite -ltnS | rewrite (leq_ltn_trans _ ji)].\n    by rewrite unbumpK //= inE gtn_eqF.\n  apply eq_bigl => a /=.\n  apply/andP; split.\n    apply/eqP/rowP => k.\n    rewrite !mxE eq_sym (negbTE (neq_lift _ _)).\n    congr (v _ _).\n    apply val_inj => /=.\n    by rewrite bumpK inordK.\n  by rewrite mxE eqxx.\nunder [RHS] eq_bigr do rewrite fdist_prod_of_rVE fdist_permE.\napply/eq_bigr => a _; congr (P _); apply/rowP => k /=.\nrewrite /col_perm /= 2!mxE /=.\nrewrite /put_front_perm /= permE /put_front.\ncase: ifPn => [ki|]; first by rewrite row_mx_row_ord0.\nrewrite neq_ltn => /orP[|] ki.\n  rewrite ki.\n  rewrite (_ : inord _ = rshift 1 (inord k)); last first.\n    apply/val_inj => /=.\n    rewrite add1n inordK /=.\n      by rewrite inordK // (leq_trans ki) // -ltnS.\n    by rewrite ltnS (leq_trans ki) // -ltnS.\n  rewrite (@row_mxEr _ _ 1); congr (v ``_ _).\n  apply val_inj => /=.\n  rewrite /unbump ltnNge (ltnW ki) subn0 inordK //.\n  by rewrite (leq_trans ki) // -ltnS.\nrewrite ltnNge (ltnW ki) /=; move: ki.\nhave [/eqP -> //|k0] := boolP (k == ord0).\nrewrite (_ : k = rshift 1 (inord k.-1)); last first.\n  by apply val_inj => /=; rewrite add1n inordK ?prednK // ?lt0n // -ltnS.\nrewrite (@row_mxEr _ 1 1) /=.\nrewrite inordK ?prednK ?lt0n // -1?ltnS // ltnS add1n prednK ?lt0n // => ik.\nby congr (v _ _); apply val_inj => /=; rewrite /unbump ik subn1.\nQed.\n\nLemma chain_rule_multivar (A : finType) (n : nat) (P : {fdist 'rV[A]_n.+1})\n  (i : 'I_n.+1) : i != ord0 ->\n  (`H P = `H (fdist_col' P i) +\n    cond_entropy (fdist_prod_of_rV (fdist_perm P (put_front_perm i))))%R.\nProof.\nmove=> i0; rewrite fdist_col'_put_front // -fdistX1.\nrewrite -{2}(fdistXI (fdist_prod_of_rV _)) -chain_rule joint_entropyC fdistXI.\nby rewrite entropy_fdist_prod_of_rV entropy_fdist_perm.\nQed.\n\nEnd chain_rule_generalization.\n\nSection entropy_chain_rule_corollary.\nVariables (A B C : finType) (PQR : {fdist A * B * C}).\nLet PR : {fdist A * C} := fdist_proj13 PQR.\nLet QPR : {fdist B * (A * C)} := fdistA (fdistC12 PQR).\n\n(* eqn 2.21, H(X,Y|Z) = H(X|Z) + H(Y|X,Z) *)\nLemma chain_rule_corollary :\n  cond_entropy PQR = cond_entropy PR + cond_entropy QPR.\nProof.\nrewrite !cond_entropyE -oppRD; congr (- _).\nrewrite [in X in _ = _ + X](eq_bigr (fun j => \\sum_(i in B) (fdistX QPR) ((j.1, j.2), i) *\n                                                            log \\Pr_QPR[[set i] | [set (j.1, j.2)]])); last by case.\nrewrite -[in RHS](pair_bigA _ (fun j1 j2 => \\sum_(i in B) (fdistX QPR ((j1, j2), i) *\n                                                          log \\Pr_QPR[[set i] | [set (j1, j2)]]))) /=.\nrewrite [in X in _ = _ + X]exchange_big /= -big_split; apply eq_bigr => c _ /=.\nrewrite [in LHS](eq_bigr (fun j => (fdistX PQR) (c, (j.1, j.2)) *\n                                   log \\Pr_PQR[[set (j.1, j.2)] | [set c]])); last by case.\nrewrite -[in LHS](pair_bigA _ (fun j1 j2 => (fdistX PQR) (c, (j1, j2)) *\n                                            log \\Pr_PQR[[set (j1, j2)] | [set c]])) /=.\nrewrite -big_split; apply eq_bigr => a _ /=.\nrewrite fdistXE fdist_proj13E big_distrl /= -big_split; apply eq_bigr => b _ /=.\nrewrite !(fdistXE,fdistAE,fdistC12E) /= -mulRDr.\nhave [->|H0] := eqVneq (PQR (a, b, c)) 0; first by rewrite !mul0R.\nrewrite -logM; last 2 first.\n  by rewrite -Pr_jcPr_gt0 Pr_gt0 setX1 Pr_set1; exact: fdist_proj13_dominN H0.\n  by rewrite -Pr_jcPr_gt0 Pr_gt0 setX1 Pr_set1 fdistAE /= fdistC12E.\ncongr (_ * log _).\nby rewrite -setX1 product_ruleC !setX1 mulRC.\nQed.\n\nEnd entropy_chain_rule_corollary.\n\nSection conditional_entropy_prop2. (* NB: here because use chain rule *)\n\nVariables (A B : finType) (PQ : {fdist A * B}).\nLet P := PQ`1.\nLet Q := PQ`2.\nLet QP := fdistX PQ.\n\nLemma entropyB : `H P - cond_entropy PQ = `H Q - cond_entropy QP.\nProof.\nrewrite subR_eq addRAC -subR_eq subR_opp -chain_rule joint_entropyC.\nby rewrite -/(joint_entropy (fdistX PQ)) chain_rule fdistX1 -/Q fdistXI.\nQed.\n\nEnd conditional_entropy_prop2.\n\nSection conditional_entropy_prop3. (* NB: here because use chain rule *)\n\nVariables (A : finType) (P : {fdist A}).\n\nLemma cond_entropy_self : cond_entropy (fdist_self P) = 0.\nProof.\nmove: (@chain_rule _ _ (fdist_self P)).\nrewrite !fdist_self1 fdistX_self addRC -subR_eq => <-.\nby rewrite joint_entropy_self subRR.\nQed.\n\nEnd conditional_entropy_prop3.\n\nSection mutual_information.\nLocal Open Scope divergence_scope.\nVariables (A B : finType) (PQ : {fdist A * B}).\nLet P := PQ`1.\nLet Q := PQ`2.\nLet QP := fdistX PQ.\n\nDefinition mutual_info := D(PQ || P `x Q).\n\nEnd mutual_information.\n\nSection mutual_information_prop.\nVariables (A B : finType) (PQ : {fdist A * B}).\nLet P := PQ`1.\nLet Q := PQ`2.\nLet QP := fdistX PQ.\n\n(* 2.28 *)\nLemma mutual_infoE0 : mutual_info PQ =\n  \\sum_(a in A) \\sum_(b in B) PQ (a, b) * log (PQ (a, b) / (P a * Q b)).\nProof.\nrewrite /mutual_info /div pair_big /=; apply eq_bigr; case => a b _ /=.\nhave [->|H0] := eqVneq (PQ (a, b)) 0; first by rewrite !mul0R.\nby rewrite fdist_prodE.\nQed.\n\n(* 2.39 *)\nLemma mutual_infoE : mutual_info PQ = `H P - cond_entropy PQ.\nProof.\nrewrite mutual_infoE0.\ntransitivity (\\sum_(a in A) \\sum_(b in B)\n    PQ (a, b) * log (\\Pr_PQ [ [set a] | [set b] ] / P a)).\n  apply eq_bigr => a _; apply eq_bigr => b _.\n  rewrite /jcPr setX1 2!Pr_set1 /= -/Q.\n  have [->|H0] := eqVneq (PQ (a, b)) 0; first by rewrite !mul0R.\n  by congr (_ * log _); rewrite divRM 1?mulRAC //; [\n    exact: dom_by_fdist_fstN H0 | exact: dom_by_fdist_sndN H0].\ntransitivity (- (\\sum_(a in A) \\sum_(b in B) PQ (a, b) * log (P a)) +\n  \\sum_(a in A) \\sum_(b in B) PQ (a, b) * log (\\Pr_PQ [ [set a] | [set b] ])). (* 2.37 *)\n  rewrite big_morph_oppR -big_split; apply/eq_bigr => a _ /=.\n  rewrite big_morph_oppR -big_split; apply/eq_bigr => b _ /=.\n  rewrite addRC -mulRN -mulRDr addR_opp.\n  have [->|H0] := eqVneq (PQ (a, b)) 0; first by rewrite !mul0R.\n  congr (_ * _); rewrite logDiv //.\n  - by rewrite -Pr_jcPr_gt0 Pr_gt0 setX1 Pr_set1.\n  - by rewrite -fdist_gt0; exact: dom_by_fdist_fstN H0.\nrewrite -subR_opp; congr (_ - _).\n- rewrite /entropy; congr (- _); apply/eq_bigr => a _.\n  by rewrite -big_distrl /= -fdist_fstE.\n- rewrite /cond_entropy exchange_big.\n  rewrite big_morph_oppR; apply eq_bigr=> b _ /=.\n  rewrite mulRN; congr (- _).\n  rewrite big_distrr /=; apply eq_bigr=> a _ /=.\n  rewrite mulRA; congr (_ * _); rewrite -/Q.\n  by rewrite -[in LHS]Pr_set1 -setX1 jproduct_rule Pr_set1 -/Q mulRC.\nQed.\n\nLemma mutual_infoE2 : mutual_info PQ = `H Q - cond_entropy QP. (* 2.40 *)\nProof. by rewrite mutual_infoE entropyB. Qed.\n\nLemma mutual_infoE3 : mutual_info PQ = `H P + `H Q - `H PQ. (* 2.41 *)\nProof.\nrewrite mutual_infoE; have := chain_rule QP.\nrewrite addRC -subR_eq -(fdistXI PQ) -/QP => <-.\nby rewrite -addR_opp oppRB fdistX1 -/Q addRA joint_entropyC.\nQed.\n\n(* nonnegativity of mutual information 2.90 *)\nLemma mutual_info_ge0 : 0 <= mutual_info PQ.\nProof. exact/div_ge0/Prod_dominates_Joint. Qed.\n\nLemma mutual_info0P : mutual_info PQ = 0 <-> PQ = P `x Q.\nProof.\nsplit; last by rewrite /mutual_info => <-; rewrite div0P //; exact: dominatesxx.\nby rewrite /mutual_info div0P //; exact: Prod_dominates_Joint.\nQed.\n\nEnd mutual_information_prop.\n\nSection mutualinfo_RV_def.\nVariables (U A B : finType) (P : {fdist U}) (X : {RV P -> A}) (Y : {RV P -> B}).\nDefinition mutual_info_RV := mutual_info `p_[% X, Y].\nEnd mutualinfo_RV_def.\nNotation \"'`I(' X ';' Y ')'\" := (mutual_info_RV X Y) : chap2_scope.\n\n(* TODO: example 2.3.1 *)\n\nSection mutualinfo_prop.\n\nLocal Open Scope divergence_scope.\n\n(* eqn 2.46 *)\nLemma mutual_info_sym (A B : finType) (PQ : {fdist A * B}) :\n  mutual_info PQ = mutual_info (fdistX PQ).\nProof. by rewrite !mutual_infoE entropyB fdistX1. Qed.\n\n(* eqn 2.47 *)\nLemma mutual_info_self (A : finType) (P : fdist A) :\n  mutual_info (fdist_self P) = `H P.\nProof. by rewrite mutual_infoE cond_entropy_self subR0 fdist_self1. Qed.\n\nEnd mutualinfo_prop.\n\nSection chain_rule_for_entropy.\nLocal Open Scope vec_ext_scope.\n\nLemma entropy_head_of1 (A : finType) (P : {fdist 'M[A]_1}) :\n  `H P = `H (head_of_fdist_rV P).\nProof.\nrewrite /entropy; congr (- _); apply: big_rV_1 => // a.\nrewrite /head_of_fdist_rV fdist_fstE /= big_rV0_row_of_tuple fdist_prod_of_rVE/=;\ncongr (P _ * log (P _)); apply/rowP => i.\n  by rewrite (ord1 i) !mxE; case: splitP => // i0; rewrite (ord1 i0) mxE.\nby rewrite (ord1 i) !mxE; case: splitP => // i0; rewrite (ord1 i0) mxE.\nQed.\n\nLemma chain_rule_rV (A : finType) (n : nat) (P : {fdist 'rV[A]_n.+1}) :\n  `H P = \\sum_(i < n.+1)\n          if i == O :> nat then\n            `H (head_of_fdist_rV P)\n          else\n            cond_entropy (fdistX (fdist_belast_last_of_rV (fdist_take P (lift ord0 i)))).\nProof.\nelim: n P => [P|n IH P].\n  by rewrite big_ord_recl /= big_ord0 addR0 -entropy_head_of1.\nrewrite entropy_rV chain_rule {}IH [in RHS]big_ord_recr /=.\nrewrite fdist_take_all; congr (_ + _); apply eq_bigr => i _.\ncase: ifP => i0; first by rewrite head_of_fdist_rV_belast_last.\ncongr (cond_entropy (fdistX (fdist_belast_last_of_rV _))).\nrewrite /fdist_take /fdist_fst /fdist_belast_last_of_rV !fdistmap_comp.\ncongr (fdistmap _ P); rewrite boolp.funeqE => /= v.\napply/rowP => j; rewrite !mxE !castmxE /= !mxE /= cast_ord_id; congr (v _ _).\nexact: val_inj.\nQed.\n\nEnd chain_rule_for_entropy.\n\nSection divergence_conditional_distributions.\nVariables (A B C : finType) (PQR : {fdist A * B * C}).\n\nDefinition cdiv1 z := \\sum_(x in {: A * B})\n  \\Pr_PQR[[set x] | [set z]] * log (\\Pr_PQR[[set x] | [set z]] /\n    (\\Pr_(fdist_proj13 PQR)[[set x.1] | [set z]] * \\Pr_(fdist_proj23 PQR)[[set x.2] | [set z]])).\n\nLocal Open Scope divergence_scope.\n\nLemma cdiv1_is_div (c : C) (Hc  : (fdistX PQR)`1 c != 0)\n                           (Hc1 : (fdistX (fdist_proj13 PQR))`1 c != 0)\n                           (Hc2 : (fdistX (fdist_proj23 PQR))`1 c != 0) :\n  cdiv1 c = D((fdistX PQR) `(| c ) ||\n    ((fdistX (fdist_proj13 PQR)) `(| c )) `x ((fdistX (fdist_proj23 PQR)) `(| c ))).\nProof.\nrewrite /cdiv1 /div; apply eq_bigr => -[a b] /= _; rewrite jfdist_condE //.\nrewrite fdistXI.\nhave [->|H0] := eqVneq (\\Pr_PQR[[set (a, b)]|[set c]]) 0; first by rewrite !mul0R.\nby rewrite fdist_prodE /= jfdist_condE // jfdist_condE // !fdistXI.\nQed.\n\nLemma cdiv1_ge0 z : 0 <= cdiv1 z.\nProof.\nhave [z0|z0] := eqVneq (PQR`2 z) 0.\n  apply sumR_ge0 => -[a b] _.\n  rewrite {1}/jcPr setX1 Pr_set1 (dom_by_fdist_snd _ z0) div0R mul0R.\n  exact: leRR.\nhave Hc : (fdistX PQR)`1 z != 0 by rewrite fdistX1.\nhave Hc1 : (fdistX (fdist_proj13 PQR))`1 z != 0.\n  by rewrite fdistX1 fdist_proj13_snd.\nhave Hc2 : (fdistX (fdist_proj23 PQR))`1 z != 0.\n  by rewrite fdistX1 fdist_proj23_snd.\nrewrite cdiv1_is_div //; apply div_ge0.\n(* TODO: lemma *)\napply/dominatesP => -[a b].\nrewrite fdist_prodE !jfdist_condE //= mulR_eq0 => -[|].\n- rewrite /jcPr !setX1 !Pr_set1 !mulR_eq0 => -[|].\n    rewrite !fdistXI.\n    by move/fdist_proj13_domin => ->; left.\n  rewrite !fdistXI.\n  by rewrite fdist_proj13_snd /Rdiv => ->; right.\n- rewrite /jcPr !setX1 !Pr_set1 !mulR_eq0 => -[|].\n    rewrite !fdistXI.\n    by move/fdist_proj23_domin => ->; left.\n  by rewrite !fdistXI fdist_proj23_snd => ->; right.\nQed.\n\nEnd divergence_conditional_distributions.\n\nSection conditional_mutual_information.\nSection def.\nVariables (A B C : finType) (PQR : {fdist A * B * C}).\n\n(* I(X;Y|Z) = H(X|Z) - H(X|Y,Z) 2.60 *)\nDefinition cond_mutual_info :=\n  cond_entropy (fdist_proj13 PQR) - cond_entropy (fdistA PQR).\nEnd def.\n\nSection prop.\nVariables (A B C : finType) (PQR : {fdist A * B * C}).\n\nLemma cond_mutual_infoE : cond_mutual_info PQR = \\sum_(x in {: A * B * C}) PQR x *\n  log (\\Pr_PQR[[set x.1] | [set x.2]] /\n       (\\Pr_(fdist_proj13 PQR)[[set x.1.1] | [set x.2]] *\n        \\Pr_(fdist_proj23 PQR)[[set x.1.2] | [set x.2]])).\nProof.\nrewrite /cond_mutual_info 2!cond_entropyE /= subR_opp big_morph_oppR.\nrewrite (eq_bigr (fun a => \\sum_(b in A) (fdistX (fdistA PQR)) (a.1, a.2, b) *\n                                          log \\Pr_(fdistA PQR)[[set b] | [set (a.1, a.2)]])); last by case.\nrewrite -(pair_bigA _ (fun a1 a2 => \\sum_(b in A) (fdistX (fdistA PQR)) ((a1, a2), b) *\n                                                   log \\Pr_(fdistA PQR)[[set b] | [set (a1, a2)]])).\nrewrite exchange_big -big_split /=.\nrewrite (eq_bigr (fun x => PQR (x.1, x.2) * log\n(\\Pr_PQR[[set x.1] | [set x.2]] /\n        (\\Pr_(fdist_proj13 PQR)[[set x.1.1] | [set x.2]] *\n         \\Pr_(fdist_proj23 PQR)[[set x.1.2] | [set x.2]])))); last by case.\nrewrite -(pair_bigA _ (fun x1 x2 => PQR (x1, x2) * log\n(\\Pr_PQR[[set x1] | [set x2]] /\n        (\\Pr_(fdist_proj13 PQR)[[set x1.1] | [set x2]] *\n         \\Pr_(fdist_proj23 PQR)[[set x1.2] | [set x2]])))).\nrewrite /= exchange_big; apply eq_bigr => c _.\nrewrite big_morph_oppR /= exchange_big -big_split /=.\nrewrite (eq_bigr (fun i => PQR ((i.1, i.2), c) * log\n       (\\Pr_PQR[[set (i.1, i.2)] | [set c]] /\n        (\\Pr_(fdist_proj13 PQR)[[set i.1] | [set c]] *\n         \\Pr_(fdist_proj23 PQR)[[set i.2] | [set c]])))); last by case.\nrewrite -(pair_bigA _ (fun i1 i2 => PQR (i1, i2, c) * log\n  (\\Pr_PQR[[set (i1, i2)] | [set c]] /\n  (\\Pr_(fdist_proj13 PQR)[[set i1] | [set c]] * \\Pr_(fdist_proj23 PQR)[[set i2] | [set c]])))).\napply eq_bigr => a _ /=.\nrewrite fdistXE fdist_proj13E big_distrl /= big_morph_oppR -big_split.\napply eq_bigr => b _ /=.\nrewrite fdistXE fdistAE /= -mulRN -mulRDr.\nhave [->|H0] := eqVneq (PQR (a, b, c)) 0; first by rewrite !mul0R.\ncongr (_ * _).\nrewrite addRC addR_opp -logDiv; last 2 first.\n  by rewrite -Pr_jcPr_gt0 Pr_gt0 setX1 Pr_set1; exact: fdistA_dominN H0.\n  by rewrite -Pr_jcPr_gt0 Pr_gt0 setX1 Pr_set1; exact: fdist_proj13_dominN H0.\ncongr (log _).\nrewrite divRM; last 2 first.\n  by rewrite -jcPr_gt0 -Pr_jcPr_gt0 Pr_gt0 setX1 Pr_set1; exact: fdist_proj13_dominN H0.\n  by rewrite -jcPr_gt0 -Pr_jcPr_gt0 Pr_gt0 setX1 Pr_set1; exact: fdist_proj23_dominN H0.\nrewrite {2}/Rdiv -mulRA mulRCA {1}/Rdiv [in LHS]mulRC; congr (_ * _).\nrewrite -[in X in _ = X * _]setX1 jproduct_rule_cond setX1 -mulRA mulRV ?mulR1 //.\nrewrite /jcPr divR_neq0' // ?setX1 !Pr_set1.\n  exact: fdist_proj23_dominN H0.\nby rewrite fdist_proj23_snd; exact: dom_by_fdist_sndN H0.\nQed.\n\nLet R := PQR`2.\n\nLemma cond_mutual_infoE2 : cond_mutual_info PQR = \\sum_(z in C) R z * cdiv1 PQR z.\nProof.\nrewrite cond_mutual_infoE.\nrewrite (eq_bigr (fun x => PQR (x.1, x.2) * log\n  (\\Pr_PQR[[set x.1] | [set x.2]] /\n    (\\Pr_(fdist_proj13 PQR)[[set x.1.1] | [set x.2]] *\n     \\Pr_(fdist_proj23 PQR)[[set x.1.2] | [set x.2]])))); last by case.\nrewrite -(pair_bigA _ (fun x1 x2 => PQR (x1, x2) * log\n  (\\Pr_PQR[[set x1] | [set x2]] /\n    (\\Pr_(fdist_proj13 PQR)[[set x1.1] | [set x2]] *\n     \\Pr_(fdist_proj23 PQR)[[set x1.2] | [set x2]])))).\nrewrite exchange_big; apply eq_bigr => c _ /=.\nrewrite big_distrr /=; apply eq_bigr => -[a b] _ /=; rewrite mulRA; congr (_ * _).\nrewrite mulRC.\nmove: (jproduct_rule PQR [set (a, b)] [set c]); rewrite -/R Pr_set1 => <-.\nby rewrite setX1 Pr_set1.\nQed.\n\n(* 2.92 *)\nLemma cond_mutual_info_ge0 : 0 <= cond_mutual_info PQR.\nProof.\nrewrite cond_mutual_infoE2; apply sumR_ge0 => c _; apply mulR_ge0 => //.\nexact: cdiv1_ge0.\nQed.\n\nLet P : fdist A := (fdistA PQR)`1.\nLet Q : fdist B := (PQR`1)`2.\n\nLemma chain_rule_mutual_info : mutual_info PQR = mutual_info (fdist_proj13 PQR) +\n                                                 cond_mutual_info (fdistX (fdistA PQR)).\nProof.\nrewrite mutual_infoE.\nhave := chain_rule (PQR`1); rewrite /joint_entropy => ->.\nrewrite (chain_rule_corollary PQR).\nrewrite -addR_opp oppRD addRCA 2!addRA -(addRA (- _ + _)) addR_opp; congr (_ + _).\n  rewrite mutual_infoE addRC; congr (_ - _).\n  by rewrite fdist_proj13_fst fdistA1.\nrewrite /cond_mutual_info; congr (cond_entropy _ - _).\n  by rewrite /fdist_proj13 -/(fdistC13 _) fdistA_C13_snd.\n(* TODO: lemma *)\nrewrite /cond_entropy.\nrewrite (eq_bigr (fun a => (fdistA (fdistC12 PQR))`2 (a.1, a.2) *\n                            cond_entropy1 (fdistA (fdistC12 PQR)) (a.1, a.2))); last by case.\nrewrite -(pair_bigA _ (fun a1 a2 => (fdistA (fdistC12 PQR))`2 (a1, a2) *\n                                     cond_entropy1 (fdistA (fdistC12 PQR)) (a1, a2))).\nrewrite exchange_big pair_big; apply eq_bigr => -[c a] _ /=; congr (_ * _).\n  rewrite !fdist_sndE; apply eq_bigr => b _.\n  by rewrite !(fdistXE,fdistAE,fdistC12E).\nrewrite /cond_entropy1; congr (- _).\nby under eq_bigr do rewrite -setX1 jcPr_fdistA_C12 setX1.\nQed.\nEnd prop.\n\nEnd conditional_mutual_information.\n\nSection conditional_relative_entropy.\nSection def.\nVariables (A B : finType) (P Q : (fdist A * (A -> fdist B))).\nLet Pj : {fdist B * A} := fdistX (P.1 `X P.2).\nLet Qj : {fdist B * A} := fdistX (Q.1 `X Q.2).\nLet P1 : {fdist A} := P.1.\n\n(* eqn 2.65 *)\nDefinition cond_relative_entropy := \\sum_(x in A) P1 x * \\sum_(y in B)\n  \\Pr_Pj[[set y]|[set x]] * log (\\Pr_Pj[[set y]|[set x]] / \\Pr_Qj[[set y]|[set x]]).\n\nEnd def.\n\nSection prop.\nLocal Open Scope divergence_scope.\nLocal Open Scope reals_ext_scope.\nVariables (A B : finType) (P Q : (fdist A * (A -> fdist B))).\nLet Pj : {fdist B * A} := fdistX (P.1 `X P.2).\nLet Qj : {fdist B * A} := fdistX (Q.1 `X Q.2).\nLet P1 : {fdist A} := P.1.\nLet Q1 : {fdist A} := Q.1.\n\nLemma chain_rule_relative_entropy :\n  Pj `<< Qj -> D(Pj || Qj) = D(P1 || Q1) + cond_relative_entropy P Q.\nProof.\nmove=> PQ.\nrewrite {2}/div /cond_relative_entropy -big_split /= {1}/div /=.\nrewrite (eq_bigr (fun a => Pj (a.1, a.2) * (log (Pj (a.1, a.2) / (Qj (a.1, a.2)))))); last by case.\nrewrite -(pair_bigA _ (fun a1 a2 => Pj (a1, a2) * (log (Pj (a1, a2) / (Qj (a1, a2)))))) /=.\nrewrite exchange_big; apply eq_bigr => a _ /=.\nrewrite [in X in _ = X * _ + _](_ : P1 a = Pj`2 a); last first.\n  by rewrite /P fdistX2 fdist_prod1.\nrewrite fdist_sndE big_distrl /= big_distrr /= -big_split /=; apply eq_bigr => b _.\nrewrite mulRA (_ : P1 a * _ = Pj (b, a)); last first.\n  rewrite /jcPr Pr_set1 -/P1 mulRCA setX1 Pr_set1 {1}/Pj fdistX2 fdist_prod1.\n  have [P2a0|P2a0] := eqVneq (P1 a) 0.\n    have Pba0 : Pj (b, a) = 0 by rewrite /P fdistXE fdist_prodE P2a0 mul0R.\n    by rewrite Pba0 mul0R.\n  by rewrite mulRV // ?mulR1.\nrewrite -mulRDr.\nhave [->|H0] := eqVneq (Pj (b, a)) 0; first by rewrite !mul0R.\ncongr (_ * _).\nhave P1a0 : P1 a != 0.\n  apply: contra H0 => /eqP.\n  by rewrite /P fdistXE fdist_prodE => ->; rewrite mul0R.\nhave Qba0 := dominatesEN PQ H0.\nhave Q2a0 : Q1 a != 0.\n  apply: contra Qba0; rewrite /Q fdistXE fdist_prodE => /eqP ->; by rewrite mul0R.\nrewrite -logM; last 2 first.\n  by apply/divR_gt0; rewrite -fdist_gt0.\n  apply/divR_gt0; by rewrite -Pr_jcPr_gt0 setX1 Pr_set1 -fdist_gt0.\ncongr (log _).\nrewrite /jcPr !setX1 !Pr_set1.\nrewrite !fdistXE !fdistX2 !fdist_prod1 !fdist_prodE /=.\nrewrite -/P1 -/Q1; field.\nsplit; first exact/eqP.\nsplit; first exact/eqP.\napply/eqP.\nby apply: contra Qba0; rewrite /Qj fdistXE fdist_prodE /= => /eqP ->; rewrite mulR0.\nQed.\n\nEnd prop.\n\nEnd conditional_relative_entropy.\n\nSection chain_rule_for_information.\nVariables (A : finType).\nLet B := A. (* need in the do-not-delete-me step *)\nVariables (n : nat) (PY : {fdist 'rV[A]_n.+1 * B}).\nLet P : {fdist 'rV[A]_n.+1} := PY`1.\nLet Y : {fdist B} := PY`2.\n\nLet f (i : 'I_n.+1) : {fdist A * 'rV[A]_i * B} := fdistC12 (fdist_prod_take PY i).\nLet fAC (i : 'I_n.+1) : {fdist A * B * 'rV[A]_i} := fdistAC (f i).\nLet fA (i : 'I_n.+1) : {fdist A * ('rV[A]_i * B)} := fdistA (f i).\n\nLocal Open Scope vec_ext_scope.\n\nLemma chain_rule_information :\n  (* 2.62 *) mutual_info PY = \\sum_(i < n.+1)\n    if i == O :> nat then\n      mutual_info (fdist_prod_nth PY ord0)\n    else\n      cond_mutual_info (fAC i).\nProof.\nrewrite mutual_infoE chain_rule_rV.\nhave -> : cond_entropy PY = \\sum_(j < n.+1)\n  if j == O :> nat then\n    cond_entropy (fdist_prod_nth PY ord0)\n  else\n    cond_entropy (fA j).\n  have := chain_rule (fdistX PY).\n  rewrite fdistXI addRC -subR_eq fdistX1 -/Y => <-.\n  rewrite /joint_entropy.\n  (* do-not-delete-me *)\n  set YP : {fdist 'rV[A]_n.+2} := fdist_rV_of_prod (fdistX PY).\n  transitivity (`H YP - `H Y); first by rewrite /YP entropy_fdist_rV_of_prod.\n  rewrite (chain_rule_rV YP).\n  rewrite [in LHS]big_ord_recl /=.\n  rewrite (_ : `H (head_of_fdist_rV YP) = `H Y); last first.\n    by rewrite /YP /head_of_fdist_rV (fdist_prod_of_rVK (fdistX PY)) fdistX1.\n  rewrite addRC addRK.\n  apply eq_bigr => j _.\n  case: ifPn => j0.\n  - have {}j0 : j = ord0 by move: j0 => /eqP j0; exact/val_inj.\n    subst j.\n    rewrite /cond_entropy /=.\n    apply big_rV_1 => // a1.\n    have H1 a : (fdistX (fdist_belast_last_of_rV (fdist_take YP (lift ord0 (lift ord0 ord0))))) (a, a1) =\n       (fdist_prod_nth PY ord0) (a, a1 ``_ ord0).\n      rewrite fdistXE fdist_belast_last_of_rVE.\n      rewrite (fdist_takeE _ (lift ord0 (lift ord0 ord0))) fdist_prod_nthE /=.\n      have H1 : (n.+2 - bump 0 (bump 0 0) = n)%nat.\n        by rewrite /bump !leq0n !add1n subn2.\n      rewrite (big_cast_rV H1).\n      rewrite (eq_bigr (fun x => PY (x.1, x.2))); last by case.\n      rewrite -(pair_big (fun i : 'rV_n.+1 => i ``_ ord0 == a) (fun i => i == a1 ``_ ord0) (fun i1 i2 => PY (i1, i2))) /=.\n      rewrite [in RHS](eq_bigl (fun i : 'rV_n.+1 => (xpred1 a (i ``_ ord0)) && (xpredT i))); last first.\n        move=> i; by rewrite andbT.\n      rewrite -(big_rV_cons_behead (fun i => \\sum_(j | j == a1 ``_ ord0) PY (i, j))\n                                   (fun i => i == a) xpredT).\n      rewrite exchange_big /=.\n      apply eq_bigr => v _.\n      rewrite big_pred1_eq.\n      rewrite big_pred1_eq.\n      rewrite /YP.\n      rewrite fdist_rV_of_prodE fdistXE /=; congr (PY (_, _)).\n        apply/rowP => i.\n        rewrite mxE castmxE /=.\n        move: (leq0n i); rewrite leq_eqVlt => /orP[/eqP|] i0.\n          move=> [:Hi1].\n          have @i1 : 'I_(bump 0 0).+1.\n            apply: (@Ordinal _ i.+1); abstract: Hi1.\n            by rewrite /bump leq0n add1n -i0.\n          rewrite (_ : cast_ord _ _ = lshift (n.+2 - bump 0 (bump 0 0)) i1); last exact/val_inj.\n          rewrite row_mxEl castmxE /= 2!cast_ord_id.\n          rewrite (_ : cast_ord _ _ = rshift 1 (Ordinal (ltn_ord ord0))); last first.\n            by apply val_inj => /=; rewrite add1n -i0.\n          rewrite row_mxEr mxE.\n          set i2 : 'I_1 := Ordinal (ltn_ord ord0).\n          rewrite (_ : i = lshift n i2); last exact/val_inj.\n          by rewrite (@row_mxEl _ _ 1) mxE.\n        move=> [:Hi1].\n        have @i1 : 'I_(n.+2 - bump 0 (bump 0 0)).\n          apply: (@Ordinal _ i.-1); abstract: Hi1.\n          by rewrite /bump !leq0n !add1n subn2 prednK //= -ltnS.\n        rewrite (_ : cast_ord _ _ = rshift (bump 0 0).+1 i1); last first.\n          by apply/val_inj => /=; rewrite /bump !leq0n !add1n add2n prednK.\n        rewrite row_mxEr castmxE /= !cast_ord_id.\n        have @i2 : 'I_n by apply: (@Ordinal _ i.-1); rewrite prednK // -ltnS.\n        rewrite (_ : i = rshift 1 i2); last first.\n          by apply/val_inj => /=; rewrite add1n prednK.\n        rewrite (@row_mxEr _ _ 1) //; congr (v _ _); exact/val_inj.\n      rewrite castmxE /=.\n      rewrite (_ : cast_ord _ _ = lshift (n.+2 - bump 0 (bump 0 0)) (Ordinal (ltn_ord ord0))); last exact/val_inj.\n      rewrite row_mxEl castmxE /= 2!cast_ord_id.\n      rewrite (_ : cast_ord _ _ = lshift 1 (Ordinal (ltn_ord ord0))); last exact/val_inj.\n      rewrite row_mxEl /=; congr (a1 ``_ _); exact/val_inj.\n    congr (_ * _).\n      rewrite 2!fdist_sndE; apply eq_bigr => a _; by rewrite H1.\n    rewrite /cond_entropy1; congr (- _).\n    apply eq_bigr => a _; congr (_ * log _).\n    + rewrite /jcPr /Pr !big_setX /= !big_set1.\n      rewrite H1; congr (_ / _).\n      rewrite !fdist_sndE; apply eq_bigr => a0 _.\n      by rewrite H1.\n    + rewrite /jcPr /Pr !big_setX /= !big_set1.\n      rewrite H1; congr (_ / _).\n      rewrite !fdist_sndE; apply eq_bigr => a0 _.\n      by rewrite H1.\n  - rewrite /fA /f.\n    rewrite /cond_entropy /=.\n    have H1 : bump 0 j = j.+1 by rewrite /bump leq0n.\n    rewrite (big_cast_rV H1) /=.\n    rewrite -(big_rV_cons_behead _ xpredT xpredT) /= exchange_big /= pair_bigA.\n    have H2 (v : 'rV_j) (b : B) (a : A) (H1' : (1 + j)%nat = lift ord0 j) :\n      (fdistX (fdist_belast_last_of_rV (fdist_take YP (lift ord0 (lift ord0 j)))))\n      (a, (castmx (erefl 1%nat, H1') (row_mx (\\row__ b) v))) =\n      (fdistA (fdistC12 (fdist_prod_take PY j))) (a, (v, b)).\n      rewrite /YP /fdistX /fdist_belast_last_of_rV /fdist_take /fdist_rV_of_prod.\n      rewrite /fdistA /fdistC12 /fdist_prod_take !fdistmap_comp !fdistmapE /=.\n      apply eq_bigl => -[w b0]; rewrite /= /swap /= !inE /=.\n      rewrite (_ : rlast _ = w ``_ j); last first.\n        rewrite /rlast !mxE !castmxE /= cast_ord_id.\n        rewrite (_ : cast_ord _ _ = rshift 1%nat j); last exact/val_inj.\n        by rewrite (@row_mxEr _ 1%nat 1%nat n.+1).\n      rewrite !xpair_eqE; congr (_ && _).\n      rewrite (_ : rbelast _ =\n        row_take (lift ord0 j) (rbelast (row_mx (\\row_(k<1) b0) w))); last first.\n        apply/rowP => i; rewrite !mxE !castmxE /= esymK !cast_ord_id.\n        by rewrite /rbelast mxE; congr (row_mx _ _ _ _); exact: val_inj.\n      rewrite (_ : rbelast _ = row_mx (\\row_(k<1) b0) (rbelast w)); last first.\n        apply/rowP => i; rewrite mxE /rbelast.\n        have [i0|i0] := eqVneq (i : nat) O.\n          rewrite (_ : widen_ord _ _ = ord0); last exact: val_inj.\n          rewrite (_ : i = ord0); last exact: val_inj.\n          by rewrite 2!row_mx_row_ord0.\n        have @k : 'I_n.+1.\n          apply: (@Ordinal _ i.-1).\n          by rewrite prednK // ?lt0n // -ltnS (leq_trans (ltn_ord i)).\n        rewrite (_ : widen_ord _ _ = rshift 1%nat k); last first.\n          by apply val_inj => /=; rewrite -subn1 subnKC // lt0n.\n        rewrite (@row_mxEr _ 1%nat 1%nat n.+1).\n        have @k' : 'I_n.\n          apply: (@Ordinal _ i.-1).\n          by rewrite prednK // ?lt0n // -ltnS (leq_trans (ltn_ord i)).\n        rewrite (_ : i = rshift 1%nat k'); last first.\n          by apply val_inj => /=; rewrite -subn1 subnKC // lt0n.\n        rewrite (@row_mxEr _ 1%nat 1%nat n) mxE; congr (w ord0 _); exact: val_inj.\n      apply/idP/idP; last first.\n        move/andP => /= [/eqP <- /eqP ->].\n        apply/eqP/rowP => k.\n        rewrite !mxE !castmxE /= esymK !cast_ord_id.\n        case/boolP : (k == O :> nat) => [/eqP | ] k0.\n          rewrite (_ : cast_ord _ _ = ord0); last exact: val_inj.\n          rewrite (_ : k = ord0); last exact: val_inj.\n          by rewrite 2!row_mx_row_ord0.\n        have @l : 'I_n.\n          apply: (@Ordinal _ k.-1).\n          by rewrite prednK // ?lt0n // -ltnS (leq_trans (ltn_ord k)).\n        rewrite (_ : cast_ord _ _ = rshift 1%nat l); last first.\n          by apply val_inj => /=; rewrite add1n prednK // lt0n.\n        rewrite (@row_mxEr _ 1%nat 1%nat n) //.\n        have @l0 : 'I_(widen_ord (leqnSn n.+1) j).\n          apply: (@Ordinal _ k.-1).\n          by rewrite prednK // ?lt0n // -ltnS (leq_trans (ltn_ord k)).\n        rewrite (_ : k = rshift 1%nat l0); last first.\n          by apply val_inj => /=; rewrite add1n prednK // lt0n.\n        rewrite (@row_mxEr _ 1%nat 1%nat) //.\n        rewrite !mxE !castmxE /= cast_ord_id; congr (w _ _).\n        exact: val_inj.\n      move/eqP/rowP => H.\n      move: (H ord0).\n      rewrite !mxE !castmxE /= 2!cast_ord_id esymK.\n      rewrite (_ : cast_ord _ _ = ord0); last exact: val_inj.\n      rewrite 2!row_mx_row_ord0 => ->; rewrite eqxx andbT.\n      apply/eqP/rowP => k.\n      have @k1 : 'I_(bump 0 j).\n        apply: (@Ordinal _ k.+1).\n        by rewrite /bump leq0n add1n ltnS.\n      move: (H k1).\n      rewrite !mxE !castmxE /= esymK !cast_ord_id.\n      have @k2 : 'I_n.\n        apply: (@Ordinal _ k).\n        by rewrite (leq_trans (ltn_ord k)) // -ltnS (leq_trans (ltn_ord j)).\n      rewrite (_ : cast_ord _ _ = rshift 1%nat k2); last first.\n        by apply val_inj => /=; rewrite add1n.\n      rewrite (@row_mxEr _ 1%nat 1%nat) mxE.\n      rewrite (_ : cast_ord _ _ = widen_ord (leqnSn n) k2); last exact: val_inj.\n      move=> ->.\n      rewrite (_ : k1 = rshift 1%nat k); last by apply val_inj => /=; rewrite add1n.\n      by rewrite row_mxEr.\n    apply eq_bigr => -[v b] _ /=.\n    rewrite 2!fdist_sndE; congr (_ * _).\n      apply eq_bigr => a _.\n      rewrite -H2.\n      congr (fdistX _ (a, castmx (_, _) _)).\n      exact: eq_irrelevance.\n    rewrite /cond_entropy1; congr (- _).\n    apply eq_bigr => a _.\n    rewrite /jcPr /Pr !big_setX /= !big_set1.\n    rewrite !H2 //=.\n    congr (_ / _ * log (_ / _)).\n    + rewrite 2!fdist_sndE; apply eq_bigr => a' _; by rewrite H2.\n    + rewrite 2!fdist_sndE; apply eq_bigr => a' _; by rewrite H2.\nrewrite -addR_opp big_morph_oppR -big_split /=; apply eq_bigr => j _ /=.\ncase: ifPn => j0.\n- rewrite mutual_infoE addR_opp; congr (`H _ - _).\n  rewrite /head_of_fdist_rV /fdist_fst /fdist_rV_of_prod.\n  by rewrite /fdist_prod_nth !fdistmap_comp.\n- rewrite /cond_mutual_info /fA -/P; congr (_ - _).\n  + congr cond_entropy.\n    by rewrite /fAC /f fdist_proj13_AC fdistC12_fst belast_last_take.\n  + rewrite /fAC /f /fdistAC fdistC12I /cond_entropy /=.\n    rewrite (eq_bigr (fun a => (fdistA (fdistC12 (fdist_prod_take PY j)))`2 (a.1, a.2) *\n       cond_entropy1 (fdistA (fdistC12 (fdist_prod_take PY j))) (a.1, a.2))); last by case.\n    rewrite -(pair_bigA _ (fun a1 a2 => (fdistA (fdistC12 (fdist_prod_take PY j)))`2 (a1, a2) *\n       cond_entropy1 (fdistA (fdistC12 (fdist_prod_take PY j))) (a1, a2))) /=.\n    rewrite exchange_big pair_bigA /=; apply eq_bigr => -[b v] _ /=.\n    congr (_ * _).\n    * rewrite !fdist_sndE; apply eq_bigr=> a _.\n      by rewrite !fdistAE /= fdistXE fdistC12E /= fdistAE.\n    * (* TODO: lemma? *)\n      rewrite /cond_entropy1; congr (- _); apply eq_bigr => a _.\n      by rewrite -!setX1 -jcPr_fdistA_AC /fdistAC fdistC12I.\nQed.\n\nEnd chain_rule_for_information.\n\nSection conditioning_reduces_entropy.\nSection prop.\nVariables (A B : finType) (PQ : {fdist A * B}).\nLet P := PQ`1.\nLet Q := PQ`2.\nLet QP := fdistX PQ.\n\n(* 2.95 *)\nLemma information_cant_hurt : cond_entropy PQ <= `H P.\nProof. by rewrite -subR_ge0 -mutual_infoE; exact: mutual_info_ge0. Qed.\n\nLemma condentropy_indep : PQ = P `x Q -> cond_entropy PQ = `H P.\nProof. by move/mutual_info0P; rewrite mutual_infoE subR_eq0 => <-. Qed.\nEnd prop.\n\nSection prop2.\nVariables (A B C : finType) (PQR : {fdist A * B * C}).\nLet P : fdist A := (fdistA PQR)`1.\nLet Q : fdist B := (PQR`1)`2.\nLet R := PQR`2.\nLemma mi_bound : PQR`1 = P `x Q (* P and Q independent *) ->\n  mutual_info (fdist_proj13 PQR) +\n  mutual_info (fdist_proj23 PQR) <= mutual_info PQR.\nProof.\nmove=> PQ; rewrite chain_rule_mutual_info leR_add2l /cond_mutual_info.\nrewrite [X in _ <= X - _](_ : _ = `H Q); last first.\n  rewrite condentropy_indep; last first.\n    rewrite fdist_proj13_fst fdistA1 fdistX1 fdistA21 -/Q.\n    rewrite fdist_proj13_snd fdistX2 -/P.\n    rewrite -[RHS]fdistXI fdistX_prod -PQ.\n    apply/fdist_ext => -[b a]. (* TODO: lemma? *)\n    rewrite fdist_proj13E fdistXE fdist_fstE; apply eq_bigr => c _.\n    by rewrite fdistXE fdistAE.\n  by rewrite /fdist_proj13 fdistA21 fdistC12_fst fdistX1 fdistX2 fdistA21 -/Q.\nrewrite mutual_infoE.\nrewrite fdist_proj23_fst -/Q.\nrewrite -oppRB leR_oppl oppRB -!addR_opp leR_add2r.\n(* conditioning cannot increase entropy *)\n(* Q|R,P <= Q|R, lemma *)\nrewrite -subR_ge0.\nmove: (cond_mutual_info_ge0 (fdistC12 PQR)); rewrite /cond_mutual_info.\nrewrite /fdist_proj13 fdistC12I -/(fdist_proj23 _).\nby rewrite cond_entropy_fdistA /fdistAC fdistC12I.\nQed.\nEnd prop2.\nEnd conditioning_reduces_entropy.\n\n(* TODO: example 2.6.1 *)\n\nSection independence_bound_on_entropy.\nVariables (A : finType) (n : nat) (P : {fdist 'rV[A]_n.+1}).\n\n(* thm 2.6.6 TODO: with equality in case of independence *)\nLemma independence_bound_on_entropy : `H P <= \\sum_(i < n.+1) `H (fdist_nth P i).\nProof.\nrewrite chain_rule_rV; apply leR_sumR => /= i _.\ncase: ifPn => [/eqP|] i0.\n  rewrite (_ : i = ord0); last exact/val_inj.\n  by rewrite head_of_fdist_rV_fdist_nth; exact/leRR.\napply: leR_trans; first exact: information_cant_hurt.\nby rewrite fdistX1 fdist_take_nth; exact/leRR.\nQed.\n\nEnd independence_bound_on_entropy.\n\nSection markov_chain.\n\nVariables (A B C : finType) (PQR : {fdist A * B * C}).\nLet P := PQR`1`1.\nLet Q := PQR`1`2.\nLet PQ := PQR`1.\nLet QP := fdistX PQ.\nLet RQ := fdistX ((fdistA PQR)`2).\n\n(* cond. distr. of Z depends only on Y and conditionally independent of X *)\nDefinition markov_chain := forall (x : A) (y : B) (z : C),\n  PQR (x, y, z) = P x * \\Pr_QP[ [set y] | [set x]] * \\Pr_RQ[ [set z] | [set y]].\n\nLet PRQ := fdistAC PQR.\n\n(* X and Z are conditionally independent given Y TODO: iff *)\nLemma markov_cond_mutual_info : markov_chain -> cond_mutual_info (PRQ : {fdist A * C * B}) = 0.\nProof.\nrewrite /markov_chain => mc.\nrewrite cond_mutual_infoE (eq_bigr (fun=> 0)) ?big_const ?iter_addR ?mulR0 //= => x _.\ncase/boolP : (PRQ x == 0) => [/eqP ->|H0]; first by rewrite mul0R.\nrewrite (_ : _ / _ = 1); first by rewrite /log Log_1 mulR0.\nrewrite eqR_divr_mulr ?mul1R; last first.\n  rewrite mulR_neq0'; apply/andP; split.\n    (* TODO: lemma? *)\n    rewrite /jcPr divR_neq0' //.\n      rewrite setX1 Pr_set1.\n      case: x => [[x11 x12] x2] in H0 *.\n      exact: fdist_proj13_dominN H0.\n    rewrite Pr_set1 fdist_proj13_snd.\n    case: x => [x1 x2] in H0 *.\n    exact: dom_by_fdist_sndN H0.\n  (* TODO: lemma? *)\n  rewrite /jcPr divR_neq0' //.\n    rewrite setX1 Pr_set1.\n    case: x => [[x11 x12] x2] in H0 *.\n    exact: fdist_proj23_dominN H0.\n  rewrite Pr_set1 fdist_proj23_snd.\n  case: x => [x1 x2] in H0 *.\n  exact: dom_by_fdist_sndN H0.\n(* TODO: lemma? *) (* 2.118 *)\ntransitivity (Pr PRQ [set x] / Pr Q [set x.2]).\n  rewrite /jcPr setX1 {2}/PRQ fdistAC2 -/Q; by case: x H0.\ntransitivity (Pr PQ [set (x.1.1,x.2)] * \\Pr_RQ[[set x.1.2]|[set x.2]] / Pr Q [set x.2]).\n  congr (_ / _).\n  case: x H0 => [[a c] b] H0 /=.\n  rewrite /PRQ Pr_set1 fdistACE /= mc; congr (_ * _).\n  rewrite /jcPr {2}/QP fdistX2 -/P Pr_set1 mulRCA mulRV ?mulR1; last first.\n    apply dom_by_fdist_fstN with b.\n    apply dom_by_fdist_fstN with c.\n    by rewrite fdistACE in H0.\n  by rewrite /QP Pr_fdistX setX1.\nrewrite {1}/Rdiv -mulRA mulRCA mulRC; congr (_ * _).\n  rewrite /jcPr fdist_proj13_snd -/Q {2}/PRQ fdistAC2 -/Q -/(Rdiv _ _); congr (_ / _).\n  by rewrite /PRQ /PQ setX1 fdist_proj13_AC.\nrewrite /jcPr fdist_proj23_snd; congr (_ / _).\n- by rewrite /RQ /PRQ /fdist_proj23 fdistA_AC_snd.\n- by rewrite /RQ fdistX2 fdistA21 /PRQ fdistAC2.\nQed.\n\nLet PR := fdist_proj13 PQR.\n\nLemma data_processing_inequality : markov_chain ->\n  mutual_info PR <= mutual_info PQ.\nProof.\nmove=> H.\nhave H1 : mutual_info (fdistA PQR) = mutual_info PR + cond_mutual_info PQR.\n  rewrite /cond_mutual_info !mutual_infoE addRA; congr (_ - _).\n  by rewrite -/PR subRK /PR fdist_proj13_fst.\nhave H2 : mutual_info (fdistA PQR) = mutual_info PQ + cond_mutual_info PRQ.\n  transitivity (mutual_info (fdistA PRQ)).\n    by rewrite !mutual_infoE fdistA_AC_fst cond_entropy_fdistA.\n  rewrite /cond_mutual_info !mutual_infoE addRA; congr (_ - _).\n  by rewrite fdistA1 {1}/PRQ fdist_proj13_AC -/PQ subRK /PQ fdistAC_fst_fst.\nhave H3 : cond_mutual_info PRQ = 0 by rewrite markov_cond_mutual_info.\nhave H4 : 0 <= cond_mutual_info PQR by exact: cond_mutual_info_ge0.\nmove: H2; rewrite {}H3 addR0 => <-.\nby rewrite {}H1 addRC -leR_subl_addr subRR.\nQed.\n\nEnd markov_chain.\n\nSection markov_chain_prop.\n\nVariables (A B C : finType) (PQR : {fdist A * B * C}).\n\nLemma markov_chain_order : markov_chain PQR -> markov_chain (fdistC13 PQR).\nProof.\nrewrite /markov_chain => H c b a.\nrewrite fdistC13E /=.\nrewrite {}H.\nrewrite fdistC13_fst_fst.\nrewrite (jBayes _ [set a] [set b]).\nrewrite fdistXI.\nrewrite fdistX1 fdistX2.\nrewrite (mulRC (_ a)) -mulRA.\nrewrite [in RHS]mulRCA -[in RHS]mulRA.\ncongr (_ * _).\n  by rewrite fdistA_C13_snd.\nrewrite (jBayes _ [set c] [set b]).\nrewrite fdistXI.\nrewrite [in LHS]mulRCA -[in LHS]mulRA.\nrewrite [in RHS](mulRC (_ c)) -[in RHS](mulRA _ (_ c)).\nrewrite [in RHS]mulRCA.\ncongr (_ * _).\n  congr (\\Pr_ _ [_ | _]).\n  by rewrite fdistC13_fst fdistXI.\nrewrite !Pr_set1.\nrewrite [in RHS]mulRCA.\ncongr (_ * _).\n  by rewrite fdistX1 fdistA22.\ncongr (_ * / _).\n  congr (_ a).\n  by rewrite fdistA22 fdistC13_snd.\nby rewrite fdistX2 fdistA21 fdistA_C13_snd fdistX1.\nQed.\n\nEnd markov_chain_prop.\n\nSection Han_inequality.\n\nLocal Open Scope ring_scope.\n\nLemma information_cant_hurt_cond (A : finType) (n' : nat) (n := n'.+1 : nat)\n  (P : {fdist 'rV[A]_n}) (i : 'I_n) (i0 : i != O :> nat) :\n  cond_entropy (fdist_prod_of_rV P) <=\n  cond_entropy (fdist_prod_of_rV (fdist_take P (lift ord0 i))).\nProof.\nrewrite -subR_ge0.\nset Q : {fdist A * 'rV[A]_i * 'rV[A]_(n' - i)} := fdist_take_drop P i.\nhave H1 : fdist_proj13 (fdistAC Q) = fdist_prod_of_rV (fdist_take P (lift ord0 i)).\n  rewrite /fdist_proj13 /fdistAC /fdist_prod_of_rV /fdist_take /fdist_snd /fdistA.\n  rewrite /fdistC12 /fdistX /fdist_take_drop !fdistmap_comp; congr (fdistmap _ P).\n  rewrite boolp.funeqE => /= v /=.\n  congr (_, _).\n  - rewrite mxE castmxE /= cast_ord_id; congr (v ord0 _); exact: val_inj.\n  - apply/rowP => j.\n    rewrite !mxE !castmxE /= !cast_ord_id !esymK mxE; congr (v ord0 _).\n    exact: val_inj.\nhave H2 : cond_entropy (fdistA (fdistAC Q)) = cond_entropy (fdist_prod_of_rV P).\n  rewrite -cond_entropy_fdistA /cond_entropy /=.\n  rewrite (partition_big (@row_take A _ i) xpredT) //=.\n  rewrite (eq_bigr (fun a => (fdistA Q)`2 (a.1, a.2) *\n           cond_entropy1 (fdistA Q) (a.1, a.2))%R); last by case.\n  rewrite -(pair_bigA _ (fun a1 a2 => (fdistA Q)`2 (a1, a2) *\n           cond_entropy1 (fdistA Q) (a1, a2))%R) /=.\n  apply eq_bigr => v _.\n(* TODO: lemma yyy *)\n  rewrite (@reindex_onto _ _ _ [finType of 'rV[A]_n'] [finType of 'rV[A]_(n' - i)]\n    (fun w => (castmx (erefl 1%nat, subnKC (ltnS' (ltn_ord i))) (row_mx v w)))\n    (@row_drop A _ i)) /=; last first.\n    move=> w wv; apply/rowP => j.\n    rewrite castmxE /= cast_ord_id /row_drop mxE; case: splitP => [j0 /= jj0|k /= jik].\n    - rewrite -(eqP wv) mxE castmxE /= cast_ord_id; congr (w _ _); exact: val_inj.\n    - rewrite mxE /= castmxE /= cast_ord_id; congr (w _ _); exact: val_inj.\n  apply eq_big => /= w.\n    apply/esym/andP; split; apply/eqP/rowP => j.\n    by rewrite !mxE !castmxE /= !cast_ord_id esymK cast_ordK row_mxEl.\n    by rewrite !mxE !castmxE /= cast_ord_id esymK cast_ordK cast_ord_id row_mxEr.\n  move=> _; congr (_ * _)%R.\n  - rewrite !fdist_sndE; apply eq_bigr => a _.\n    by rewrite fdistAE /= fdist_prod_of_rVE /= /Q fdist_take_dropE.\n  - rewrite /cond_entropy1; congr (- _)%R; apply eq_bigr => a _.\n    congr (_ * log _)%R.\n    + rewrite /jcPr !(Pr_set1,setX1) fdistAE /= /Q fdist_take_dropE /= fdist_prod_of_rVE /=.\n      congr (_ / _)%R.\n      rewrite !fdist_sndE; apply eq_bigr => a0 _.\n      by rewrite fdistAE fdist_take_dropE fdist_prod_of_rVE.\n    + rewrite /jcPr !(Pr_set1,setX1) fdistAE /= /Q fdist_take_dropE /= fdist_prod_of_rVE /=.\n      congr (_ / _)%R.\n      rewrite !fdist_sndE; apply eq_bigr => a0 _.\n      by rewrite fdistAE fdist_take_dropE fdist_prod_of_rVE.\nrewrite (_ : _ - _ = cond_mutual_info (fdistAC Q))%R; last by rewrite /cond_mutual_info H1 H2.\nexact/cond_mutual_info_ge0.\nQed.\n\nLemma han_helper (A : finType) (n' : nat) (n := n'.+1 : nat)\n  (P : {fdist 'rV[A]_n}) (i : 'I_n) (i0 : i != O :> nat) :\n  cond_entropy (fdist_prod_of_rV (fdist_perm P (put_front_perm i))) <=\n  cond_entropy (fdistX (fdist_belast_last_of_rV (fdist_take P (lift ord0 i)))).\nProof.\nrewrite (_ : fdistX _ = fdist_prod_of_rV (fdist_perm\n    (fdist_take P (lift ord0 i)) (put_front_perm (inord i)))); last first.\n  apply/fdist_ext => /= -[a v].\n  rewrite fdistXE fdist_belast_last_of_rVE fdist_prod_of_rVE /= fdist_permE.\n  rewrite !(fdist_takeE _ (lift ord0 i)); apply eq_bigr => /= w _; congr (P _); apply/rowP => k.\n  rewrite !castmxE /= cast_ord_id.\n  case/boolP : (k < i.+1)%nat => ki.\n    have @k1 : 'I_i.+1 := Ordinal ki.\n    rewrite (_ : cast_ord _ k = lshift (n - bump 0 i) k1); last exact/val_inj.\n    rewrite 2!row_mxEl castmxE /= cast_ord_id [in RHS]mxE.\n    case/boolP : (k < i)%nat => [ki'|].\n      rewrite (_ : cast_ord _ _ = lshift 1%nat (Ordinal ki')) /=; last exact/val_inj.\n      rewrite row_mxEl /put_front_perm permE /put_front ifF; last first.\n        apply/negbTE/eqP => /(congr1 val) /=.\n        by rewrite inordK // => /eqP; rewrite ltn_eqF.\n      rewrite inordK //= ki' (_ : inord k.+1 = rshift 1%nat (Ordinal ki')); last first.\n        by apply/val_inj => /=; rewrite inordK.\n      by rewrite (@row_mxEr _ 1%nat 1%nat).\n    rewrite permE /put_front.\n    rewrite -leqNgt leq_eqVlt => /orP[|] ik.\n      rewrite ifT; last first.\n        apply/eqP/val_inj => /=; rewrite inordK //; exact/esym/eqP.\n      rewrite row_mx_row_ord0 (_ : cast_ord _ _ = rshift i ord0); last first.\n        by apply val_inj => /=; rewrite addn0; apply/esym/eqP.\n      by rewrite row_mxEr mxE.\n    move: (leq_ltn_trans ik ki); by rewrite ltnn.\n  rewrite -ltnNge ltnS in ki.\n  move=> [:Hk1].\n  have @k1 : 'I_(n - bump 0 i).\n    apply: (@Ordinal _ (k - i.+1)).\n    abstract: Hk1.\n    by rewrite /bump leq0n add1n ltn_sub2r // (leq_ltn_trans _ (ltn_ord k)).\n  rewrite (_ : cast_ord _ _ = rshift i.+1 k1); last by apply val_inj => /=; rewrite subnKC.\n  by rewrite 2!row_mxEr.\nrewrite (_ : fdist_perm (fdist_take _ _) _ =\n  fdist_take (fdist_perm P (put_front_perm i)) (lift ord0 i)); last first.\n  apply/fdist_ext => /= w.\n  rewrite fdist_permE 2!(fdist_takeE _ (lift ord0 i)); apply eq_bigr => /= v _.\n  rewrite fdist_permE; congr (P _); apply/rowP => /= k.\n  rewrite /col_perm mxE !castmxE /= !cast_ord_id /=.\n  case/boolP : (k < bump 0 i)%nat => ki.\n    rewrite (_ : cast_ord _ _ = lshift (n - bump 0 i) (Ordinal ki)); last exact/val_inj.\n    rewrite row_mxEl mxE /put_front_perm !permE /= /put_front /=.\n    case/boolP : (k == i) => ik.\n      rewrite ifT; last first.\n        apply/eqP/val_inj => /=; rewrite inordK //; exact/eqP.\n      rewrite (_ : cast_ord _ _ = lshift (n - bump 0 i) ord0); last exact/val_inj.\n      by rewrite row_mxEl.\n    rewrite ifF; last first.\n      apply/negbTE/eqP => /(congr1 val) /=.\n      apply/eqP; by rewrite inordK.\n    case/boolP : (k < i)%nat => {}ik.\n      rewrite inordK // ik.\n      move=> [:Hk1].\n      have @k1 : 'I_(bump 0 i).\n        apply: (@Ordinal _ k.+1).\n        abstract: Hk1.\n        by rewrite /bump leq0n add1n.\n      rewrite (_ : cast_ord _ _ = lshift (n - bump 0 i) k1); last first.\n        apply/val_inj => /=; rewrite inordK // ltnS.\n        by rewrite (leq_trans ik) // -ltnS.\n      rewrite row_mxEl; congr (w _ _).\n      by apply val_inj => /=; rewrite inordK.\n    rewrite -ltnNge in ik.\n    rewrite ifF; last first.\n      apply/negbTE.\n      by rewrite -leqNgt -ltnS inordK.\n    rewrite (_ : cast_ord _ _ = lshift (n - bump 0 i) (Ordinal ki)); last exact/val_inj.\n    by rewrite row_mxEl.\n  rewrite -ltnNge /bump leq0n add1n ltnS in ki.\n  move=> [:Hk1].\n  have @k1 : 'I_(n - bump 0 i).\n    apply: (@Ordinal _ (k - i.+1)).\n    abstract: Hk1.\n    by rewrite /bump leq0n add1n ltn_sub2r // (leq_trans _ (ltn_ord k)).\n  rewrite (_ : cast_ord _ _ = rshift i.+1 k1); last by apply/val_inj => /=; rewrite subnKC.\n  rewrite row_mxEr permE /put_front /= ifF; last first.\n     by move: ki; rewrite ltnNge; apply: contraNF => /eqP ->.\n  rewrite ltnNge (ltnW ki) /=.\n  move=> [:Hk2].\n  have @k2 : 'I_(n - bump 0 i).\n    apply: (@Ordinal _ (k - i.+1)).\n    abstract: Hk2.\n    by rewrite /bump leq0n add1n ltn_sub2r // (leq_trans _ (ltn_ord k)).\n  rewrite (_ : cast_ord _ _ = rshift (bump 0 i) k2); last first.\n    by apply/val_inj => /=; rewrite /bump leq0n add1n subnKC.\n  rewrite row_mxEr; congr (v _ _); exact/val_inj.\nexact/information_cant_hurt_cond.\nQed.\n\nVariables (A : finType) (n' : nat).\nLet n := n'.+1.\nVariable P : {fdist 'rV[A]_n}.\n\nLemma han : n.-1%:R * `H P <= \\sum_(i < n) `H (fdist_col' P i).\nProof.\nrewrite -subn1 natRB // mulRBl mul1R leR_subl_addr {2}(chain_rule_rV P).\nrewrite -big_split /= -{1}(card_ord n) -sum1_card big_morph_natRD big_distrl /=.\napply leR_sumR => i _; rewrite mul1R.\ncase: ifPn => [/eqP|] i0.\n  rewrite (_ : i = ord0); last exact/val_inj.\n  rewrite -tail_of_fdist_rV_fdist_col' /tail_of_fdist_rV /head_of_fdist_rV.\n  rewrite -{1}(fdist_rV_of_prodK P) entropy_fdist_rV_of_prod.\n  move: (chain_rule (fdist_prod_of_rV P)); rewrite /joint_entropy => ->.\n  by rewrite [in X in _ <= X]addRC leR_add2l -fdistX1; exact: information_cant_hurt.\nby rewrite (chain_rule_multivar _ i0) leR_add2l; exact/han_helper.\nQed.\n\nEnd Han_inequality.\n", "meta": {"author": "affeldt-aist", "repo": "infotheo", "sha": "5f9efb859dbadcbcae2330e2e21e76f9b632d879", "save_path": "github-repos/coq/affeldt-aist-infotheo", "path": "github-repos/coq/affeldt-aist-infotheo/infotheo-5f9efb859dbadcbcae2330e2e21e76f9b632d879/information_theory/entropy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642526773001, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6995266832298335}}
{"text": "Require Import TLC.LibTactics.\n\nRequire Export ZArith.\nLocal Open Scope Z_scope.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nRequire Import Psatz. (* nia *)\nRequire Export Filter.\nRequire Import Dominated.\nRequire Import BigEnough.\n\nSection UltimatelyGe_k.\n\nVariable k : Z.\nHypothesis k_nonneg : 0 <= k.\n\nLemma ultimately_ge_cst :\n  forall c,\n  k <= c ->\n  ultimately Z_filterType (fun _ => k <= c).\nProof.\n  intros c Hc.\n  apply filter_universe_alt. intros _.\n  assumption.\nQed.\n\nLemma ultimately_ge_sum :\n  forall (A : filterType) f1 f2,\n  ultimately A (fun x => k <= f1 x) ->\n  ultimately A (fun x => k <= f2 x) ->\n  ultimately A (fun x => k <= f1 x + f2 x).\nProof.\n  introv. filter_closed_under_intersection.\n  intros. lia.\nQed.\n\nLemma ultimately_ge_max :\n  forall (A : filterType) f1 f2,\n  ultimately A (fun x => k <= f1 x) ->\n  ultimately A (fun x => k <= f2 x) ->\n  ultimately A (fun x => k <= Z.max (f1 x) (f2 x)).\nProof.\n  introv. filter_closed_under_intersection.\n  intros. lia.\nQed.\n\nLemma ultimately_ge_mul :\n  forall (A : filterType) f1 f2,\n  ultimately A (fun x => k <= f1 x) ->\n  ultimately A (fun x => k <= f2 x) ->\n  ultimately A (fun x => k <= f1 x * f2 x).\nProof.\n  introv. filter_closed_under_intersection.\n  intros. assert (k * k <= f1 a * f2 a) by nia.\n  nia.\nQed.\n\nLemma ultimately_ge_id :\n  ultimately Z_filterType (fun x => k <= x).\nProof.\n  exists k. auto.\nQed.\n\nLemma ultimately_ge_limit :\n  forall (A : filterType) f,\n  limit A Z_filterType f ->\n  ultimately A (fun x => k <= f x).\nProof.\n  introv L.\n  apply L. apply ultimately_ge_Z.\nQed.\n\nEnd UltimatelyGe_k.\n\nLemma ultimately_gt_ge :\n  forall (k: Z) (A : filterType) f,\n  ultimately A (fun x => k + 1 <= f x) ->\n  ultimately A (fun x => k < f x).\nProof.\n  introv. filter_closed_under_intersection.\n  intros. omega.\nQed.\n\nLemma ultimately_ge_cumul_Z :\n  forall (k : Z) (f : Z -> Z) (lo : Z),\n  ultimately Z_filterType (fun n => 0 < f n) ->\n  ultimately Z_filterType (fun n => k <= cumul lo n f).\nProof.\n  introv.\n  generalize (ultimately_ge_Z lo). filter_intersect.\n  introv U. rewrite ZP in U.\n  destruct U as (n0 & H).\n  exists_big n1 Z. intros n N.\n  assert (n1_ge_n0: n0 <= n1) by big.\n  rewrite (cumul_split n0); cycle 1.\n  { apply H. auto with zarith. }\n  { rewrite <-N. auto. }\n\n  assert (cumul_part_2: n - n0 <= cumul n0 n f).\n  { admit. (* cf dominated.v *) }\n\n  rewrite <-cumul_part_2.\n  cut (k + n0 - cumul lo n0 f <= n). omega.\n  rewrite <-N. big.\n  close.\nQed.\n\nLemma ultimately_ge_0_cumul_nonneg_Z :\n  forall (f : Z -> Z -> Z) (lo : Z),\n  (forall hi x, lo <= x < hi -> 0 <= f hi x) ->\n  ultimately Z_filterType (fun n => 0 <= cumul lo n (f n)).\nProof.\n  introv H.\n  apply filter_universe_alt. intros.\n  rewrite cumulP. apply big_nonneg_Z.\n  intros; auto with zarith.\nQed.\n\nLemma ultimately_lift1 (A B : filterType) P:\n  ultimately A (fun x => P x) ->\n  ultimately (product_filterType A B) (fun '(x, _) => P x).\nProof.\n  intros U.\n  rewrite productP. do 2 eexists. splits; try apply U. apply filter_universe.\n  tauto.\nQed.\n\nLemma ultimately_lift2 (A B : filterType) P:\n  ultimately B (fun y => P y) ->\n  ultimately (product_filterType A B) (fun '(_, y) => P y).\nProof.\n  intros U.\n  rewrite productP. do 2 eexists. splits; try apply U. apply filter_universe.\n  tauto.\nQed.\n\n(******************************************************************************)\n(* Put lemmas into a base of hints [ultimately_greater] *)\n\n(* For some lemmas, simply adding them as a [Hint Resolve] does not seem to\n   work. As a workaround we manually add them using [Hint Extern].\n*)\nHint Extern 0 (ultimately _ (fun _ => _ < _)) =>\n  apply ultimately_gt_ge : ultimately_greater.\nHint Resolve ultimately_ge_id : ultimately_greater.\nHint Resolve ultimately_ge_cst : ultimately_greater.\nHint Extern 3 (ultimately _ (fun _ => _ <= _ + _)) =>\n  simple apply ultimately_ge_sum : ultimately_greater.\nHint Extern 2 (ultimately _ (fun _ => _ <= Z.max _ _)) =>\n  simple apply ultimately_ge_max : ultimately_greater.\nHint Extern 3 (ultimately _ (fun _ => _ <= _ + _)) =>\n  simple apply ultimately_ge_mul : ultimately_greater.\nHint Extern 1 (ultimately Z_filterType (fun _ => 0 <= cumul _ _ _)) =>\n  simple apply ultimately_ge_0_cumul_nonneg_Z : ultimately_greater.\nHint Extern 2 (ultimately Z_filterType (fun _ => _ <= cumul _ _ _)) =>\n  simple apply ultimately_ge_cumul_Z.\nHint Resolve filter_universe_alt | 50 : ultimately_greater.\nHint Resolve ultimately_lift1 : ultimately_greater.\nHint Resolve ultimately_lift2 : ultimately_greater.\n\nHint Extern 100 => try (intros; omega) : ultimately_greater_sidegoals.\n\nHint Extern 999 (ultimately _ (fun _ => _ <= _)) => shelve : ultimately_greater_fallback.\n\n(******************************************************************************)\n\n(* The order of the hints bases given to auto seems to matter: things break if\n   [zarith] is put after [ultimately_greater]... *)\n\n(* Contrary to the standard behavior of [auto], this tactic tries to do some\n   progress by applying the lemmas, and returning the side-goals it could not\n   prove to the user. *)\nLtac ultimately_greater :=\n  unshelve (auto with zarith\n                      ultimately_greater\n                      ultimately_greater_sidegoals\n                      ultimately_greater_fallback).\n\n(* This variant follows [auto]'s standard behavior. It does not modifies the\n   goal if it could not prove it entirely. *)\nLtac ultimately_greater_trysolve :=\n  auto with zarith\n            ultimately_greater\n            ultimately_greater_sidegoals.\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/UltimatelyGreater.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6995002542714802}}
{"text": "\nDefinition compose {A:Type} (g f:A -> A) (x:A) := g (f x).\n\nDefinition thrice {A:Type} (f:A -> A) := compose  f (compose f f).\n\nDefinition iterate_27 {A:Type} := thrice (thrice (A:=A)) .\n\nDefinition plus_27 : nat -> nat := iterate_27 S.\n\nRequire Import ZArith.\n\nDefinition mult_27 (x:Z) := iterate_27 (Zplus x) 0%Z.\n\nDefinition exp_27 (x:Z) := iterate_27 (Zmult x) 1%Z.\n\n\n(** Tests :\n\nCompute plus_27 0.\n\nCompute mult_27 10. \n\nCompute exp_27 2.\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/ch4_dependent_product/SRC/thrice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6995002509731564}}
{"text": "Require Import prosa.classic.util.all.\nRequire Import prosa.classic.model.arrival.basic.job.\nRequire Import prosa.classic.model.schedule.uni.schedule.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.\n\nModule NonpreemptiveSchedule.\n\n  Export UniprocessorSchedule.\n\n  Section Definitions.\n    \n    Context {Job: eqType}.\n    Variable job_arrival: Job -> time.\n    Variable job_cost: Job -> time.\n    \n    (* Consider any uniprocessor schedule. *)\n    Variable sched: schedule Job.\n\n    (* For simplicity, let's define some local names. *)\n    Let job_completed_by := completed_by job_cost sched.\n    Let job_remaining_cost j t := remaining_cost job_cost sched j t.\n    \n    (* We define schedule to be nonpreemptive iff every job remains scheduled until completion. *)\n    Definition is_nonpreemptive_schedule := \n      forall j t t',\n        t <= t' -> \n        scheduled_at sched j t ->\n        ~~ job_completed_by j t' -> \n        scheduled_at sched j t'. \n\n    (* In this section, we prove some basic lemmas about nonpreemptive schedules. *)\n    Section Lemmas.\n\n      (* Assume that we have a nonpreemptive schedule. *)\n      Hypothesis H_nonpreemptive: is_nonpreemptive_schedule.\n\n      Section BasicLemmas.\n\n        (* Consider any job j. *)\n        Variable j: Job.\n        \n        (* Assume that completed jobs do not execute. *)\n        Hypothesis H_completed_jobs_dont_execute:\n          completed_jobs_dont_execute job_cost sched.\n        \n        (* First, we show that if j is scheduled at any two time instants, \n           then it is also scheduled at any time between them. *)\n        Lemma continuity_of_nonpreemptive_scheduling:\n          forall t t1 t2,\n            t1 <= t <= t2 ->\n            scheduled_at sched j t1 ->\n            scheduled_at sched j t2 ->\n            scheduled_at sched j t.\n        Proof.\n          move => t t1 t2 /andP [GT LE] SCHEDt1 SCHEDt2.          \n          unfold is_nonpreemptive_schedule, job_completed_by in *.\n          apply H_nonpreemptive with (t := t1); [by done| by done| ].\n          apply /negP; intros COMP.\n          apply (scheduled_implies_not_completed job_cost) in SCHEDt2; last by done.\n          apply completion_monotonic with (t' := t2) in COMP; last by done.\n            by move: SCHEDt2 => /negP SCHEDt2; apply: SCHEDt2.\n        Qed.\n\n        (* Next, we show that in any nonpreemptive schedule, once a job is scheduled, \n           it cannot be preempted until completion. *)\n        Lemma in_nonpreemption_schedule_preemption_implies_completeness:\n          forall t t' ,\n            t <= t' ->\n            scheduled_at sched j t ->\n            ~~ scheduled_at sched j t' ->\n            job_completed_by j t'.\n        Proof.\n          intros t t' LE SCHED; apply contraNT.\n            by apply H_nonpreemptive with (t := t). \n        Qed.\n         \n      End BasicLemmas.\n      \n      (* In this section, we prove properties related to job completion. *)\n      Section CompletionUnderNonpreemptive.\n        \n        (* Assume that completed jobs do not execute. *)\n        Hypothesis H_completed_jobs_dont_execute:\n          completed_jobs_dont_execute job_cost sched.\n\n        (* If job j is scheduled at time t, then it must complete by (t + remaining_cost j t). *)\n        Lemma job_completes_after_remaining_cost:\n          forall j t,\n            scheduled_at sched j t ->\n            job_completed_by j (t + job_remaining_cost j t).\n        Proof.\n          intros j t SCHED.\n          rewrite /job_completed_by /completed_by.\n          rewrite /service /service_during.\n          rewrite (@big_cat_nat _ _ _ t) //= ?leq_addr //.\n          apply leq_trans with (n := service sched j t + job_remaining_cost j t);\n            first by rewrite /remaining_cost subnKC //.\n          rewrite leq_add2l.\n          set t2 := t + _.\n          apply leq_trans with (n := \\sum_(t <= i < t2) 1);\n            first by simpl_sum_const; rewrite /t2 addKn.\n          apply leq_sum_nat. \n          move => i /andP [GE LT _].\n          rewrite lt0n eqb0 negbK.\n          apply (H_nonpreemptive j t i); try (by done).\n          unfold t2 in *; clear t2.\n          have NOTCOMP: ~~ job_completed_by j t.\n          {\n            apply contraT. rewrite negbK. intros COMP.\n            apply completed_implies_not_scheduled in COMP; last by done.\n              by rewrite SCHED in COMP.\n          }\n          apply job_doesnt_complete_before_remaining_cost in NOTCOMP; last by done.\n          apply contraT; rewrite negbK; intros COMP.\n          exfalso; move: NOTCOMP => /negP NOTCOMP; apply: NOTCOMP.\n          apply completion_monotonic with (t0 := i); try ( by done).\n            by apply subh3; first rewrite addn1.\n        Qed.\n        \n      End CompletionUnderNonpreemptive.\n\n      (* In this section, we determine bounds on the length of the execution interval. *)\n      Section ExecutionInterval.\n        \n        (* Assume that jobs do not execute after completion. *)\n        Hypothesis H_completed_jobs_dont_execute:\n          completed_jobs_dont_execute job_cost sched.\n\n        (* Let j be any job scheduled at time t. *)\n        Variable j: Job.\n        Variable t: time.\n        Hypothesis H_j_is_scheduled_at_t: scheduled_at sched j t.\n\n        (* Is this section we show that there is a bound for how early job j can start. *)\n        Section LeftBound.\n          \n          (* We prove that job j is scheduled at time (t - service sched j t)... *)\n          Lemma  j_is_scheduled_at_t_minus_service:\n            scheduled_at sched j (t - service sched j t).\n          Proof.\n            unfold is_nonpreemptive_schedule in *.\n            apply contraT; intros CONTRA; exfalso.\n            rename H_j_is_scheduled_at_t into SCHED.\n            have COSTPOS: job_cost j > 0.\n            { apply (scheduled_implies_not_completed job_cost) in SCHED; last by done.\n              unfold job_completed_by, completed_by in SCHED.\n              apply contraT; rewrite -eqn0Ngt.\n              move => /eqP EQ0.\n              rewrite EQ0 in SCHED.\n                by rewrite -ltnNge ltn0 in SCHED.\n            }\n\n            have H: service sched j (t + job_remaining_cost j t) == job_cost j.\n            { rewrite eqn_leq; apply/andP; split; eauto 2.\n                by apply job_completes_after_remaining_cost.\n            }              \n            unfold job_completed_by, completed_by in H.\n            move: H => /eqP H.\n            unfold service, service_during in H.\n            rewrite (@big_cat_nat _ _ _ (t - service sched j t)) //= in H;\n              last by rewrite leq_subLR addnC -addnA leq_addr.\n            have R: forall a b c, a + b = c -> b < c -> a > 0.\n            {  by intros a b c EQ LT; induction a;\n                first by rewrite add0n in EQ; subst b;\n                rewrite ltnn in LT.        \n            }\n            apply R in H; last first.\n            {\n              have CUMLED := cumulative_service_le_delta sched j 0 t.\n              have CUMLEJC := cumulative_service_le_job_cost _ _ j H_completed_jobs_dont_execute 0 t.\n              rewrite (@big_cat_nat _ _ _ ((t - service sched j t).+1)) //=.\n              {\n                rewrite big_nat_recl; last by done.\n                rewrite big_geq; last by done.\n                rewrite -eqb0 in CONTRA; move: CONTRA => /eqP CONTRA.\n                rewrite /service_at CONTRA add0n add0n.\n                apply leq_ltn_trans with\n                    (t + job_remaining_cost j t - ((t - service sched j t).+1)).\n                 set (t - service sched j t).+1 as T.\n                 apply leq_trans with (\\sum_(T <= i < t + job_remaining_cost j t) 1).\n                 rewrite leq_sum //; intros; by destruct (scheduled_at sched j i).\n                 simpl_sum_const. by done.\n                 unfold job_remaining_cost, remaining_cost.\n                 rewrite -addn1 -addn1  subh1; first by\n                     by rewrite leq_subLR addnBA;\n                 first by  rewrite -addnA [1+job_cost j]addnC addnA -subh1.\n                 { \n                  rewrite subh1; last by done.\n                  rewrite leq_subLR addnA.\n                  rewrite addnBA; last by done.\n                  rewrite [_+t]addnC [_+job_cost j]addnC addnA.\n                  rewrite -addnBA; last by done.\n                    by rewrite subnn addn0 addnC leq_add2r.\n                }\n              }\n              {\n                unfold remaining_cost.\n                rewrite addnBA; last by done.\n                rewrite -addn1 subh1; last by done.\n                rewrite leq_subLR -addnBA; last by done.\n                rewrite addnA [_+t]addnC -addnA leq_add2l addnBA; last by done.\n                  by rewrite addnC -addnBA; first by rewrite subnn addn0.\n              }\n            }\n            {\n              rewrite lt0n in H; move: H => /neqP H; apply: H.\n              rewrite big_nat_cond big1 //; move => i /andP [/andP [_ LT] _].\n              apply /eqP; rewrite eqb0; apply /negP; intros CONT.\n\n              have Y := continuity_of_nonpreemptive_scheduling j _ (t - service sched j t) i t.\n              feed_n 4 Y; try(done).\n                by apply/andP; split; [rewrite ltnW | rewrite leq_subr].\n                  by move: CONTRA => /negP CONTRA; apply CONTRA.\n            }\n          Qed. \n          \n          (* ... and it is not scheduled at time (t - service sched j t - 1). *)\n          Lemma j_is_not_scheduled_at_t_minus_service_minus_one:\n            t - service sched j t > 0 ->\n            ~~ scheduled_at sched j (t - service sched j t - 1).\n          Proof.\n            rename H_j_is_scheduled_at_t into SCHED.\n            intros GT; apply/negP; intros CONTRA.\n            have L1 := job_doesnt_complete_before_remaining_cost\n                         job_cost sched j H_completed_jobs_dont_execute t.\n            feed L1; first by rewrite scheduled_implies_not_completed.\n            have L2 := job_completes_after_remaining_cost\n                         H_completed_jobs_dont_execute\n                         j (t-service sched j t - 1).\n            feed L2; first by done. \n            have EQ:\n              t + job_remaining_cost j t - 1 =\n              t - service sched j t - 1 + job_remaining_cost j (t - service sched j t - 1).\n            {\n              have T1: service sched j (t - service sched j t - 1) = 0.\n              {\n\n                rewrite [service _ _ _]/service /service_during.\n                rewrite big_nat_cond big1 //; move => t' /andP [/andP [_ LT] _]. \n                apply /eqP; rewrite eqb0; apply /negP; intros CONTR.\n\n                have COMPL: completed_by job_cost sched j (t + job_remaining_cost j t - 1).\n                {\n                  apply completion_monotonic with (t0 := t' + job_remaining_cost j t');\n                  [| by apply job_completes_after_remaining_cost].\n                  unfold remaining_cost.\n                  have LLF: t' < t - service sched j t.\n                  {\n                      by apply ltn_trans with (t - service sched j t - 1);\n                    last by rewrite -addn1 subh1 // -addnBA // subnn addn0.\n                  } clear LT.\n                  rewrite !addnBA;\n                    try(rewrite H_completed_jobs_dont_execute //).\n                  rewrite [t' + _]addnC [t + _]addnC.\n                  rewrite -addnBA; last by rewrite cumulative_service_le_delta.\n                  rewrite -addnBA; last by rewrite cumulative_service_le_delta.\n                  rewrite -addnBA ?leq_add2l; last by done.\n                  by apply leq_trans with (t' + 1 - 1);\n                    rewrite addn1 subn1 -pred_Sn;\n                  [rewrite leq_subr | rewrite subh3 // addn1].\n                }\n                have L3 := job_doesnt_complete_before_remaining_cost job_cost sched\n                             j H_completed_jobs_dont_execute t;\n                    feed L3; first by rewrite scheduled_implies_not_completed.\n                unfold job_completed_by in *.\n                  by move: L3 => /negP L3; apply L3.\n              }\n              rewrite /job_remaining_cost /remaining_cost T1 subn0 addnBA; last by done.\n              rewrite -subh1.\n                by rewrite -[(t-service sched j t) + _ - _]subh1.\n                  by rewrite cumulative_service_le_delta.\n            }\n            move: L1 => /neqP L1; apply: L1.\n            rewrite -EQ in L2.\n              by unfold job_completed_by, completed_by in L2; move: L2 => /eqP L2.\n          Qed.\n\n          (* Using the previous lemma, we show that job j cannot be scheduled \n             before (t - service sched j t). *)\n          Lemma j_is_not_scheduled_earlier_t_minus_service:\n            forall t',\n              t' < t - service sched j t ->\n              ~~ scheduled_at sched j t'.\n          Proof.\n            intros t' GT.\n            have NOTSCHED := j_is_not_scheduled_at_t_minus_service_minus_one;\n                feed NOTSCHED; first by apply leq_ltn_trans with t'.\n            apply/negP;  intros CONTRA.\n            move: NOTSCHED => /negP NOTSCHED; apply: NOTSCHED.\n            apply continuity_of_nonpreemptive_scheduling with (t1 := t') (t2 := t);\n              [ by done | | by done | by done ].\n            apply/andP; split; last by apply leq_trans with (t - service sched j t); rewrite leq_subr.\n            rewrite [t']pred_Sn -subn1 leq_sub2r //.\n          Qed.\n          \n        End LeftBound.\n\n        (* Is this section we prove that job j cannot be scheduled after (t + remaining_cost j t - 1). *)\n        Section RightBound.\n\n          (* We show that if job j is scheduled at time t, \n             then it is also scheduled at time (t + remaining_cost j t - 1)... *)\n          Lemma j_is_scheduled_at_t_plus_remaining_cost_minus_one:\n            scheduled_at sched j (t + job_remaining_cost j t - 1).\n          Proof.\n            move: (H_j_is_scheduled_at_t) => COMP.\n            apply (scheduled_implies_not_completed job_cost) in COMP; last by done.\n            apply  job_doesnt_complete_before_remaining_cost in COMP; last by done.\n            move: COMP; apply contraR; intros CONTR.\n            apply in_nonpreemption_schedule_preemption_implies_completeness\n            with (t:=t); [|by done| by done].\n            rewrite subh3 // ?leq_add2l.\n              by rewrite scheduled_implies_positive_remaining_cost //.\n          Qed.\n\n          (* ... and it is not scheduled after (t + remaining cost j t - 1). *)       \n          Lemma j_is_not_scheduled_after_t_plus_remaining_cost_minus_one:\n            forall t',\n              t + job_remaining_cost j t <= t' ->\n              ~~ scheduled_at sched j t'.\n          Proof.\n            intros t' GE.\n            unfold job_completed_by in *.\n            rename H_j_is_scheduled_at_t into SCHED.\n            apply job_completes_after_remaining_cost in SCHED; last by done.\n            by apply (completion_monotonic job_cost) with (t' := t') in SCHED; first\n              by apply (completed_implies_not_scheduled job_cost).\n          Qed.\n          \n        End RightBound.\n        \n        (* To conclude, we identify the interval where job j is scheduled. *) \n        Lemma nonpreemptive_executing_interval:\n          forall t',\n            t - service sched j t <= t' < t + job_remaining_cost j t ->\n            scheduled_at sched j t'.\n        Proof.\n          move => t' /andP [GE LE].\n          move: (H_j_is_scheduled_at_t) => SCHED1; move: (H_j_is_scheduled_at_t) => SCHED2.\n          rewrite -addn1 in LE; apply subh3 with (m := t') (p := 1) in LE;\n            apply continuity_of_nonpreemptive_scheduling with\n                (t1 := t - service sched j t)\n                (t2 := t + job_remaining_cost j t - 1); first by done.\n          - by apply/andP;split.\n          - by apply j_is_scheduled_at_t_minus_service.\n          - by apply j_is_scheduled_at_t_plus_remaining_cost_minus_one.\n        Qed.\n        \n      End ExecutionInterval.\n      \n    End Lemmas.\n\n  End Definitions.\n\nEnd NonpreemptiveSchedule.", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/classic/model/schedule/uni/nonpreemptive/schedule.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.6995002496221551}}
{"text": "(*****************************************************************\n\n Initial objects in enriched categories\n\n We define the notion of initial objects in the context of\n enriched category theory. In ordinary category theory, an object\n is called initial if there is a unique morphism to every object\n in the category. To translate this concept to enriched category\n theory, we need to phrase this universal property in an arbitrary\n monoidal category instead of for sets.\n\n The idea is as follows. We want to say that an object `x` is\n initial. For every `y`, we have an object `C ⟦ x , y ⟧` in the\n monoidal category `V`. Then `x` is initial if this hom-object\n is a terminal object in `V`.\n\n Contents\n 1. Initial objects in an enriched category\n 2. Being initial is a proposition\n 3. Accessors for initial objects\n 4. Builders for initial objects\n 5. Being initial is closed under iso\n 6. Initial objects are isomorphic\n 7. Enriched categories with a terminal object\n\n *****************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.Univalence.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Monoidal.Categories.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Enrichment.\nRequire Import UniMath.CategoryTheory.limits.terminal.\nRequire Import UniMath.CategoryTheory.limits.initial.\n\nImport MonoidalNotations.\nLocal Open Scope cat.\nLocal Open Scope moncat.\n\nSection EnrichedInitial.\n  Context {V : monoidal_cat}\n          {C : category}\n          (E : enrichment C V).\n\n  (**\n   1. Initial objects in an enriched category\n   *)\n  Definition is_initial_enriched\n             (x : C)\n    : UU\n    := ∏ (y : C), isTerminal V (E ⦃ x , y ⦄).\n\n  Definition initial_enriched\n    : UU\n    := ∑ (x : C), is_initial_enriched x.\n\n  Coercion initial_enriched_to_ob\n           (x : initial_enriched)\n    : C\n    := pr1 x.\n\n  Coercion initial_enriched_to_is_initial\n           (x : initial_enriched)\n    : is_initial_enriched x\n    := pr2 x.\n\n  (**\n   2. Being initial is a proposition\n   *)\n  Proposition isaprop_is_initial_enriched\n              (x : C)\n    : isaprop (is_initial_enriched x).\n  Proof.\n    do 2 (use impred ; intro).\n    apply isapropiscontr.\n  Qed.\n\n  (**\n   3. Accessors for initial objects\n   *)\n  Section Accessors.\n    Context {x : C}\n            (Hx : is_initial_enriched x).\n\n    Definition is_initial_enriched_arrow\n               (y : C)\n      : I_{V} --> E ⦃ x , y ⦄\n      := TerminalArrow (_ ,, Hx y) I_{V}.\n\n    Definition is_initial_enriched_eq\n               {y : C}\n               (f g : I_{V} --> E ⦃ x , y ⦄)\n      : f = g.\n    Proof.\n      apply (@TerminalArrowEq _ (_ ,, Hx y) I_{V}).\n    Qed.\n\n    Definition initial_underlying\n      : Initial C.\n    Proof.\n      refine (x ,, _).\n      intros y.\n      use iscontraprop1.\n      - abstract\n          (use invproofirrelevance ;\n           intros f g ;\n           refine (!(enriched_to_from_arr E f) @ _ @ enriched_to_from_arr E g) ;\n           apply maponpaths ;\n           apply is_initial_enriched_eq).\n      - exact (enriched_to_arr E (is_initial_enriched_arrow y)).\n    Defined.\n  End Accessors.\n\n  (**\n   4. Builders for initial objects\n   *)\n  Definition make_is_initial_enriched\n             (x : C)\n             (f : ∏ (w : V) (y : C), w --> E ⦃ x , y ⦄)\n             (p : ∏ (w : V) (y : C) (f g : w --> E ⦃ x , y ⦄), f = g)\n    : is_initial_enriched x.\n  Proof.\n    intros y w.\n    use iscontraprop1.\n    - abstract\n        (use invproofirrelevance ;\n         intros φ₁ φ₂ ;\n         apply p).\n    - apply f.\n  Defined.\n\n  Definition make_is_initial_enriched_from_iso\n             (TV : Terminal V)\n             (x : C)\n             (Hx : ∏ (y : C),\n                   is_z_isomorphism (TerminalArrow TV (E ⦃ x , y ⦄)))\n    : is_initial_enriched x.\n  Proof.\n    intros y.\n    use (iso_to_Terminal TV).\n    exact (z_iso_inv (TerminalArrow TV (E ⦃ x , y ⦄) ,, Hx y)).\n  Defined.\n\n  Definition initial_enriched_from_underlying\n             (TC : Initial C)\n             (TV : Terminal V)\n             (HV : conservative_moncat V)\n    : is_initial_enriched TC.\n  Proof.\n    use (make_is_initial_enriched_from_iso TV).\n    intro y.\n    use HV.\n    use isweq_iso.\n    - intro f.\n      apply enriched_from_arr.\n      apply (InitialArrow TC).\n    - abstract\n        (intros f ; cbn ;\n         refine (_ @ enriched_from_to_arr E f) ;\n         apply maponpaths ;\n         apply InitialArrowEq).\n    - abstract\n        (intros f ; cbn ;\n         apply TerminalArrowEq).\n  Defined.\n\n  (**\n   5. Being initial is closed under iso\n   *)\n  Definition initial_enriched_from_iso\n             {x y : C}\n             (Hx : is_initial_enriched x)\n             (f : z_iso x y)\n    : is_initial_enriched y.\n  Proof.\n    intros w.\n    use (iso_to_Terminal (_ ,, Hx w)) ; cbn.\n    exact (precomp_arr_z_iso E w (z_iso_inv f)).\n  Defined.\n\n  (**\n   6. Initial objects are isomorphic\n   *)\n  Definition iso_between_initial_enriched\n             {x y : C}\n             (Hx : is_initial_enriched x)\n             (Hy : is_initial_enriched y)\n    : z_iso x y.\n  Proof.\n    use make_z_iso.\n    - exact (enriched_to_arr E (is_initial_enriched_arrow Hx y)).\n    - exact (enriched_to_arr E (is_initial_enriched_arrow Hy x)).\n    - split.\n      + abstract\n          (refine (enriched_to_arr_comp E _ _ @ _ @ enriched_to_arr_id E _) ;\n           apply maponpaths ;\n           apply (is_initial_enriched_eq Hx)).\n      + abstract\n          (refine (enriched_to_arr_comp E _ _ @ _ @ enriched_to_arr_id E _) ;\n           apply maponpaths ;\n           apply (is_initial_enriched_eq Hy)).\n  Defined.\n\n  Definition isaprop_initial_enriched\n             (HC : is_univalent C)\n    : isaprop initial_enriched.\n  Proof.\n    use invproofirrelevance.\n    intros φ₁ φ₂.\n    use subtypePath.\n    {\n      intro.\n      apply isaprop_is_initial_enriched.\n    }\n    use (isotoid _ HC).\n    use iso_between_initial_enriched.\n    - exact (pr2 φ₁).\n    - exact (pr2 φ₂).\n  Defined.\nEnd EnrichedInitial.\n\n(**\n 7. Enriched categories with a terminal object\n *)\nDefinition cat_with_enrichment_initial\n           (V : monoidal_cat)\n  : UU\n  := ∑ (C : cat_with_enrichment V), initial_enriched C.\n\nCoercion cat_with_enrichment_initial_to_cat_with_enrichment\n         {V : monoidal_cat}\n         (C : cat_with_enrichment_initial V)\n  : cat_with_enrichment V\n  := pr1 C.\n\nDefinition initial_of_cat_with_enrichment\n           {V : monoidal_cat}\n           (C : cat_with_enrichment_initial V)\n  : initial_enriched C\n  := pr2 C.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/CategoryTheory/EnrichedCats/Colimits/EnrichedInitial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.6995002478816887}}
{"text": "Require Import GeoCoq.Tarski_dev.Definitions.\n\nSection Euclid_def.\n\nContext `{Tn:Tarski_neutral_dimensionless}.\n\n(** First some statements needed for equivalence proofs\nbetween different versions of the parallel postulate. *)\n\nDefinition decidability_of_parallelism := forall A B C D,\n  Par A B C D \\/ ~ Par A B C D.\n\nDefinition decidability_of_not_intersection := forall A B C D,\n  ~ (exists I, Col I A B /\\ Col I C D) \\/\n  ~ ~ (exists I, Col I A B /\\ Col I C D).\n\nDefinition decidability_of_intersection := forall A B C D,\n  (exists I, Col I A B /\\ Col I C D) \\/\n  ~ (exists I, Col I A B /\\ Col I C D).\n\n(*\nDefinition decidability_of_intersection_in_a_plane :=\n  forall A B C D,\n  Coplanar A B C D ->\n  (exists I, Col I A B /\\ Col I C D) \\/\n  ~ (exists I, Col I A B /\\ Col I C D).\n*)\n\nDefinition tarski_s_parallel_postulate := forall A B C D T,\n  Bet A D T -> Bet B D C -> A <> D ->\n  exists X Y, Bet A B X /\\ Bet A C Y /\\ Bet X T Y.\n\n(** This is uniqueness of parallel postulate. *)\n\nDefinition playfair_s_postulate := forall A1 A2 B1 B2 C1 C2 P,\n  Par A1 A2 B1 B2 -> Col P B1 B2 ->\n  Par A1 A2 C1 C2 -> Col P C1 C2 ->\n  Col C1 B1 B2 /\\ Col C2 B1 B2.\n\n(** The sum of the angles of triangles is the flat angle.\n    Notice that we do not use pi here,\n    because defining angle measure requires some continuity axioms. *)\n\nDefinition triangle_postulate := forall A B C D E F,\n  TriSumA A B C D E F -> Bet D E F.\n\n(** A figure with three right angles is closed. *)\n\nDefinition bachmann_s_lotschnittaxiom := forall P Q R P1 R1,\n  P <> Q -> Q <> R -> Per P Q R -> Per Q P P1 -> Per Q R R1 ->\n  Coplanar P Q R P1 -> Coplanar P Q R R1 ->\n  exists S, Col P P1 S /\\ Col R R1 S.\n\n(** Transitivity of parallelism. *)\n\nDefinition postulate_of_transitivity_of_parallelism := forall A1 A2 B1 B2 C1 C2,\n  Par A1 A2 B1 B2 -> Par B1 B2 C1 C2 ->\n  Par A1 A2 C1 C2.\n\n(** This is the converse of triangle_mid_par. *)\n\nDefinition midpoint_converse_postulate := forall A B C P Q,\n  ~ Col A B C ->\n  Midpoint P B C -> Par A B Q P -> Col A C Q ->\n  Midpoint Q A C.\n\n(** This is the converse of l12_21_b.\n    The alternate interior angles between two parallel lines are congruent. *)\n\nDefinition alternate_interior_angles_postulate := forall A B C D,\n  TS A C B D -> Par A B C D ->\n  CongA B A C D C A.\n\n(** The consecutive interior angles between two parallel lines are supplementary. *)\n\nDefinition consecutive_interior_angles_postulate := forall A B C D,\n  OS B C A D -> Par A B C D -> SuppA A B C B C D.\n\n(** If two lines are parallel, every perpendicular to one of the lines is perpendicular to the other. *) \n\nDefinition perpendicular_transversal_postulate := forall A B C D P Q,\n  Par A B C D -> Perp A B P Q -> Coplanar C D P Q ->\n  Perp C D P Q.\n\n(** Two lines, each perpendicular to one of a pair of parallel lines, are parallel. *)\n\nDefinition postulate_of_parallelism_of_perpendicular_transversals :=\n  forall A1 A2 B1 B2 C1 C2 D1 D2,\n    Par A1 A2 B1 B2 -> Perp A1 A2 C1 C2 -> Perp B1 B2 D1 D2 ->\n    Coplanar A1 A2 C1 D1 -> Coplanar A1 A2 C1 D2 ->\n    Coplanar A1 A2 C2 D1 -> Coplanar A1 A2 C2 D2 ->\n    Par C1 C2 D1 D2.\n\n(** If two lines are parallel then they are everywhere equidistant. *)\n\nDefinition universal_posidonius_postulate := forall A1 A2 A3 A4 B1 B2 B3 B4,\n  Par A1 A2 B1 B2 ->\n  Col A1 A2 A3 -> Col B1 B2 B3 -> Perp A1 A2 A3 B3 ->\n  Col A1 A2 A4 -> Col B1 B2 B4 -> Perp A1 A2 A4 B4 ->\n  Cong A3 B3 A4 B4.\n\n(** A variant of Playfair's postulate useful in the proofs. *)\n\nDefinition alternative_playfair_s_postulate := forall A1 A2 B1 B2 C1 C2 P,\n  Perp2 A1 A2 B1 B2 P -> ~ Col A1 A2 P -> Col P B1 B2 -> Coplanar A1 A2 B1 B2 ->\n  Par A1 A2 C1 C2 -> Col P C1 C2 ->\n  Col C1 B1 B2 /\\ Col C2 B1 B2.\n\n(** According to wikipedia:\n\"Proclus (410-485) wrote a commentary on The Elements where he comments on attempted proofs to deduce\n the fifth postulate from the other four, in particular he notes that Ptolemy had produced a false 'proof'.\n Proclus then goes on to give a false proof of his own.\n However he did give a postulate which is equivalent to the fifth postulate.\" *)\n\nDefinition proclus_postulate := forall A B C D P Q,\n  Par A B C D -> Col A B P -> ~ Col A B Q -> Coplanar C D P Q ->\n  exists Y, Col P Q Y /\\ Col C D Y.\n\nDefinition alternative_proclus_postulate := forall A B C D P Q,\n  Perp2 A B C D P -> ~ Col C D P -> Coplanar A B C D ->\n  Col A B P -> ~ Col A B Q -> Coplanar C D P Q ->\n  exists Y, Col P Q Y /\\ Col C D Y.\n\n(** Non degenerated triangles can be circumscribed. *)\n\nDefinition triangle_circumscription_principle := forall A B C,\n  ~ Col A B C ->\n  exists CC, Cong A CC B CC /\\ Cong A CC C CC /\\ Coplanar A B C CC.\n\n(** For any given acute angle, any point together with\n    its orthogonal projection on one side of the angle\n    form a line which intersects the other side. *)\n\nDefinition inverse_projection_postulate := forall A B C P Q,\n  Acute A B C ->\n  Out B A P -> P <> Q -> Per B P Q -> Coplanar A B C Q ->\n  exists Y, Out B C Y /\\ Col P Q Y.\n\n(** Given a non-degenerated parallelogram PRQS and a point U strictly between Q and R,\n    the rays PU and SQ intersect beyond U and Q. *)\n\nDefinition euclid_5 := forall P Q R S T U,\n  BetS P T Q -> BetS R T S -> BetS Q U R -> ~ Col P Q S ->\n  Cong P T Q T -> Cong R T S T ->\n  exists I, BetS S Q I /\\ BetS P U I.\n\n(** Given a non-degenerated parallelogram PRQS and a point U not on line PR,\n    the lines PU and SQ intersect. *)\n\nDefinition strong_parallel_postulate :=  forall P Q R S T U,\n  BetS P T Q -> BetS R T S -> ~ Col P R U ->\n  Coplanar P Q R U ->\n  Cong P T Q T -> Cong R T S T ->\n  exists I, Col S Q I /\\ Col P U I.\n\n(** If a straight line falling on two straight lines make\n    the sum of the interior angles on the same side different from two right angles,\n    the two straight lines meet if produced indefinitely. *)\n\nDefinition alternative_strong_parallel_postulate := forall A B C D P Q R,\n  OS B C A D -> SumA A B C B C D P Q R -> ~ Bet P Q R ->\n  exists Y, Col B A Y /\\ Col C D Y.\n\n(** If a straight line falling on two straight lines\n    make the interior angles on the same side less than two right angles,\n    the two straight lines, if produced indefinitely,\n    meet on that side on which are the angles less than the two right angles. *)\n\nDefinition euclid_s_parallel_postulate := forall A B C D P Q R,\n  OS B C A D -> SAMS A B C B C D -> SumA A B C B C D P Q R -> ~ Bet P Q R ->\n  exists Y, Out B A Y /\\ Out C D Y.\n\n(** There exists a triangle whose sum of angles is equal to the flat angle. *)\n\nDefinition postulate_of_existence_of_a_triangle_whose_angles_sum_to_two_rights :=\n  exists A B C D E F, ~ Col A B C /\\ TriSumA A B C D E F /\\ Bet D E F.\n\n(** There exists two lines which are everywhere equidistant. *)\n\nDefinition posidonius_postulate :=\n  exists A1 A2 B1 B2,\n    ~ Col A1 A2 B1 /\\ B1 <> B2 /\\ Coplanar A1 A2 B1 B2 /\\\n    forall A3 A4 B3 B4,\n      Col A1 A2 A3 -> Col B1 B2 B3 -> Perp A1 A2 A3 B3 ->\n      Col A1 A2 A4 -> Col B1 B2 B4 -> Perp A1 A2 A4 B4 ->\n      Cong A3 B3 A4 B4.\n\n(** There exists two non congruent similar triangles. *)\n\nDefinition postulate_of_existence_of_similar_triangles :=\n  exists A B C D E F,\n    ~ Col A B C /\\ ~ Cong A B D E /\\\n    CongA A B C D E F /\\ CongA B C A E F D /\\ CongA C A B F D E.\n\n(** If A, B and C are points on a circle where the line AB is a diameter of the circle,\n    then the angle ACB is a right angle. *)\n\nDefinition thales_postulate := forall A B C M,\n  Midpoint M A B -> Cong M A M C -> Per A C B.\n\n(** The circumcenter of a right triangle is the midpoint of the hypotenuse. *)\n\nDefinition thales_converse_postulate := forall A B C M,\n  Midpoint M A B -> Per A C B -> Cong M A M C.\n\n(** There exists a right triangle whose circumcenter is the midpoint of the hypotenuse. *)\n\nDefinition existential_thales_postulate :=\n  exists A B C M, ~ Col A B C /\\ Midpoint M A B /\\ Cong M A M C /\\ Per A C B.\n\n(** The angles of a any Saccheri quadrilateral are right. *)\n\nDefinition postulate_of_right_saccheri_quadrilaterals := forall A B C D,\n  Saccheri A B C D -> Per A B C.\n\n(** There exists a Saccheri quadrilateral whose angles are right. *)\n\nDefinition postulate_of_existence_of_a_right_saccheri_quadrilateral :=\n  exists A B C D, Saccheri A B C D /\\ Per A B C.\n\n(** The angles of a any Lambert quadrilateral are right, i.e\n    if in a quadrilateral three angles are right, so is the fourth. *)\n\nDefinition postulate_of_right_lambert_quadrilaterals := forall A B C D,\n  Lambert A B C D -> Per B C D.\n\n(** There exists a Lambert quadrilateral whose angles are right. *)\n\nDefinition postulate_of_existence_of_a_right_lambert_quadrilateral :=\n  exists A B C D, Lambert A B C D /\\ Per B C D.\n\n(** For any angle, that, together with itself, make a right angle,\n    any point together with its orthogonal projection on one side of the angle\n    form a line which intersects the other side. *)\n\nDefinition weak_inverse_projection_postulate := forall A B C D E F P Q,\n  Acute A B C -> Per D E F -> SumA A B C A B C D E F ->\n  Out B A P -> P <> Q -> Per B P Q -> Coplanar A B C Q ->\n  exists Y, Out B C Y /\\ Col P Q Y.\n\nDefinition weak_tarski_s_parallel_postulate := forall A B C T,\n  Per A B C -> InAngle T A B C ->\n  exists X Y, Out B A X /\\ Out B C Y /\\ Bet X T Y.\n\n(** The perpendicular bisectors of the legs of a right triangle intersect *)\n\nDefinition weak_triangle_circumscription_principle := forall A B C A1 A2 B1 B2,\n  ~ Col A B C -> Per A C B ->\n  Perp_bisect A1 A2 B C -> Perp_bisect B1 B2 A C ->\n  Coplanar A B C A1 -> Coplanar A B C A2 ->\n  Coplanar A B C B1 -> Coplanar A B C B2 ->\n  exists I, Col A1 A2 I /\\ Col B1 B2 I.\n\nDefinition legendre_s_parallel_postulate :=\n  exists A B C,\n    ~ Col A B C /\\ Acute A B C /\\\n    forall T,\n      InAngle T A B C ->\n      exists X Y, Out B A X /\\ Out B C Y /\\ Bet X T Y.\n\n(** There exists a point and a line such that\n    there is only one parallel to this line going through this point. *)\n\nDefinition existential_playfair_s_postulate :=\n  exists A1 A2 P, ~ Col A1 A2 P /\\\n             (forall B1 B2 C1 C2,\n                Par A1 A2 B1 B2 -> Col P B1 B2 ->\n                Par A1 A2 C1 C2 -> Col P C1 C2 ->\n                Col C1 B1 B2 /\\ Col C2 B1 B2).\n\nEnd Euclid_def.\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Axioms/parallel_postulates.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.699500241285041}}
{"text": "\nRequire Export Iron.Language.Calc.Base.\n\n\n(* Type expressions *)\nInductive ty  : Type :=\n | TNat     : ty                        (* number   type constructor *)\n | TBool    : ty                        (* boolean  type constructor *)\n | TText    : ty                        (* test     type constructor *)\n | TFun     : ty  -> ty -> ty.          (* function type constructor *)\nHint Constructors ty : calc.\n\n\n(* Term expressions *)\nInductive va : Type :=\n | VNat     : nat    -> va              (* natural number value *)\n | VBool    : bool   -> va              (* boolean value *)\n | VText    : string -> va.             (* text value *)\nHint Constructors va : calc.\n\nInductive tm : Type :=\n | MVal     : va -> tm                  (* value *)\n | MAdd     : tm -> tm -> tm            (* addition       *)\n | MLess    : tm -> tm -> tm            (* less-than      *)\n | MAnd     : tm -> tm -> tm            (* boolean and    *)\n | MIf      : tm -> tm -> tm -> tm.     (* if-then-else   *)\nHint Constructors tm : calc.\n\nDefinition MNat  (n: nat)    := MVal (VNat  n).\nDefinition MBool (b: bool)   := MVal (VBool b).\nDefinition MText (t: string) := MVal (VText t).\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Language/Calc/Exp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6994738980865746}}
{"text": "(** This file contains some lemmas you will have to prove, i.e. replacing\n   the \"Admitted\" joker with a sequence of tactic calls, terminated with a \n   \"Qed\" command.\n\n   Each lemma 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\n*)\n\n\n\n\nSection Minimal_propositional_logic.\n Variables P Q R S : Prop.\n\n Lemma id_P : P -> P.\n Proof.\n Admitted. \n \n\n Lemma id_PP : (P -> P) -> P -> P.\n Proof.\n Admitted.\n\n\n Lemma imp_dist : (P -> Q -> R) -> (P -> Q) -> P -> R.\n Proof.\n Admitted.\n\n \n Lemma imp_trans : (P -> Q) -> (Q -> R) -> P -> R.\n Proof.\n Admitted.\n\n Lemma imp_perm : (P -> Q -> R) -> Q -> P -> R.\n Proof.\n Admitted.\n\n Lemma ignore_Q : (P -> R) -> P -> Q -> R.\n Proof.\n Admitted.\n\n Lemma delta_imp : (P -> P -> Q) -> P -> Q.\n Proof.\n Admitted.\n\n Lemma delta_impR : (P -> Q) -> P -> P -> Q.\n Proof.\n Admitted.\n\n Lemma diamond : (P -> Q) -> (P -> R) -> (Q -> R -> S) -> P -> S.\n Proof.\n Admitted.\n\n Lemma weak_peirce : ((((P -> Q) -> P) -> P) -> Q) -> Q.\n Proof.\n Admitted.\n\nEnd Minimal_propositional_logic.\n\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\n\nSection propositional_logic.\n\n Variables P Q R S T : Prop.\n\n Lemma and_assoc : P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\n Proof.\n Admitted.\n\n Lemma and_imp_dist : (P -> Q) /\\ (R -> S) -> P /\\ R -> Q /\\ S.\n Proof.\n Admitted.\n\n Lemma not_contrad :  ~(P /\\ ~P).\n Proof.\n Admitted.\n\n Lemma or_and_not : (P \\/ Q) /\\ ~P -> Q.\n Proof.\n Admitted.\n\n\n Lemma not_not_exm : ~ ~ (P \\/ ~ P).\n Proof.\n Admitted.\n\n Lemma de_morgan_1 : ~(P \\/ Q) -> ~P /\\ ~Q.\n Proof.\n Admitted.\n\n Lemma de_morgan_2 : ~P /\\ ~Q -> ~(P \\/ Q).\n Proof.\n Admitted.\n\n Lemma de_morgan_3 : ~P \\/ ~Q -> ~(P /\\ Q).\n Proof.\n Admitted.\n\n Lemma or_to_imp : P \\/ Q -> ~ P -> Q.\n Admitted.\n\n\n Lemma imp_to_not_not_or : (P -> Q) -> ~~(~P \\/ Q).\n Admitted.\n\n Lemma contraposition : (P -> Q) -> (~Q -> ~P).\n Admitted.\n\n Lemma contraposition' : (~P -> ~Q) <-> (~~Q -> ~~P).\n Admitted.\n\n Lemma contraposition'' : (~P -> ~Q) <-> ~~(Q -> P).\n Admitted.\n \n Section S0.\n  Hypothesis H0 : P -> R.\n  Hypothesis H1 : ~P -> R.\n\n  Lemma weak_exm : ~~R.\n  Admitted.\n\nEnd S0.\n\nCheck weak_exm.\n\n\n\n \n (* Now, you may invent and solve your own exercises ! \n    Note that you can trust the tactic tauto: if it fails, then your formula\n    is probably not (intuitionnistically) provable *)\n(*\nLemma contraposition''' : (~P -> ~Q) <-> (Q -> P).\nProof.\n tauto.\nToplevel input, characters 8-13:\nError: tauto failed.\n*)\nEnd propositional_logic.\n\n(* Now observe that the section mechanism discharges also the local\nvariables P, Q, R, etc. *)\n\nCheck and_imp_dist.\n\n\n\n\n\n\n\n\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Asian-Pacific Summer School/exercises/exercises/exercises3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.826711791935942, "lm_q1q2_score": 0.6993505978547089}}
{"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom Coq Require Import Strings.String.\nFrom PLF Require Import Maps.\nFrom Coq Require Import Bool.Bool.\nFrom Coq Require Import Arith.Arith.\nFrom Coq Require Import Arith.EqNat.\nFrom Coq Require Import Arith.PeanoNat. Import Nat.\nFrom Coq Require Import Lia.\nFrom PLF Require Export Imp.\nFrom PLF Require Import Hoare.\n\n\n(*    {{ True }}\n      if X ≤ Y then\n          {{ True /\\ X ≤ Y           }} ->>\n          {{ Y = X + Y - X           }}\n        Z := Y - X\n          {{ Y = X + Z               }}\n      else\n          {{ True /\\ ~(X ≤ Y)        }} ->>\n          {{ X + Z = X + Z           }}\n        Y := X + Z\n          {{ Y = X + Z               }}\n      end\n        {{ Y = X + Z }}\n*)\n\n\n\n(*\n        (1)      {{ True }}\n               while ~(X = 0) do\n        (2)        {{ True ∧ X ≠ 0 }} ->>\n        (3)        {{ True }}\n                 X := X - 1\n        (4)        {{ True }}\n               end\n        (5)      {{ True ∧ ~(X ≠ 0) }} ->>\n        (6)      {{ X = 0 }}\n*)\nDefinition reduce_to_zero' : com :=\n  <{ while ~(X = 0) do X := X - 1 end }>.\nTheorem reduce_to_zero_correct' :\n  {{True}} reduce_to_zero' {{X = 0}}.\nProof.\n  unfold reduce_to_zero'.\n  (* First we need to transform the postcondition so\n     that hoare_while will apply. *)\n  eapply hoare_consequence_post.\n  - apply hoare_while.\n    + (* Loop body preserves invariant *)\n      (* Need to massage precondition before hoare_asgn applies *)\n      eapply hoare_consequence_pre.\n      * apply hoare_asgn.\n      * (* Proving trivial implication (2) ->> (3) *)\n        unfold assn_sub, \"->>\". simpl. intros. exact I.\n  - (* Invariant and negated guard imply postcondition *)\n    intros st [Inv GuardFalse].\n    unfold bassn in GuardFalse. simpl in GuardFalse.\n    rewrite not_true_iff_false in GuardFalse.\n    rewrite negb_false_iff in GuardFalse.\n    apply eqb_eq in GuardFalse.\n    apply GuardFalse.\nQed.\n\n\nLtac verify_assn :=\n  repeat split;\n  simpl; unfold assert_implies;\n  unfold ap in *; unfold ap2 in *;\n  unfold bassn in *; unfold beval in *; unfold aeval in *;\n  unfold assn_sub; intros;\n  repeat (simpl in *;\n          rewrite t_update_eq ||\n          (try rewrite t_update_neq; [| (intro X; inversion X; fail)] ) );\n  simpl in *;\n  repeat match goal with [H : _ /\\ _ |- _] => destruct H end;\n  repeat rewrite not_true_iff_false in *;\n  repeat rewrite not_false_iff_true in *;\n  repeat rewrite negb_true_iff in *;\n  repeat rewrite negb_false_iff in *;\n  repeat rewrite eqb_eq in *;\n  repeat rewrite eqb_neq in *;\n  repeat rewrite leb_iff in *;\n  repeat rewrite leb_iff_conv in *;\n  try subst;\n  simpl in *;\n  repeat\n    match goal with\n      [st : state |- _] =>\n        match goal with\n        | [H : st _ = _ |- _] => rewrite -> H in *; clear H\n        | [H : _ = st _ |- _] => rewrite <- H in *; clear H\n        end\n    end;\n  try eauto; try lia.\n\nTheorem reduce_to_zero_correct''' :\n  {{True}} reduce_to_zero' {{X = 0}}.\nProof.\n  unfold reduce_to_zero'.\n  eapply hoare_consequence_post.\n  - apply hoare_while.\n    + eapply hoare_consequence_pre.\n      * apply hoare_asgn.\n      * verify_assn.\n  - verify_assn.\nQed.\n\n\n(*\n       X := m;\n       Y := 0;\n       while n ≤ X do\n         X := X - n;\n         Y := Y + 1\n       end;\n  \n    Y = m / n\n    X = m % n\n\n    n × Y + X = m ∧ X < n. \n\n      (1)    {{ True }} ->>\n      (2)    {{ n × 0 + m = m }}\n           X := m;\n      (3)    {{ n × 0 + X = m }}\n           Y := 0;\n      (4)    {{ n × Y + X = m }}\n           while n ≤ X do\n      (5)      {{ n × Y + X = m ∧ n ≤ X }} ->>\n      (6)      {{ n × (Y + 1) + (X - n) = m }}\n             X := X - n;\n      (7)      {{ n × (Y + 1) + X = m }}\n             Y := Y + 1\n      (8)      {{ n × Y + X = m }}\n           end\n      (9)    {{ n × Y + X = m ∧ ¬(n ≤ X) }} ->>\n     (10)    {{ n × Y + X = m ∧ X < n }}\n*)\n\n\n(*\n      {{ X = m }}\n      {{ X = m /\\ 0 = 0}}\n      Y := 0;\n      {{ X = m /\\ Y = 0}}\n      {{ X + Y = m /\\ ~(X = 0) }}\n      while ~(X = 0) do\n        {{ X - 1 + Y + 1 = m /\\ ~(X = 0) }}\n        X := X - 1;\n        {{ X + Y + 1 = m /\\ ~(X = 0) }}\n        Y := Y + 1\n        {{ X + Y = m /\\ ~(X = 0) }}\n      end\n      {{ X + Y = m /\\ X = 0 }}\n      {{ Y = m }}\n*)\nDefinition  slow_assignment_prog : com :=\n  <{ \n      Y := 0;\n      while ~(X = 0) do\n        X := X - 1;\n        Y := Y + 1\n      end\n  }>.\n\nDefinition body_slow_assignment_prog: com :=\n  <{\n    X := X - 1;\n    Y := Y + 1\n  }>.\nLemma tst: forall (m: nat), {{ X + Y = m /\\ ~(X = 0)}} body_slow_assignment_prog {{ X + Y = m }}.\nProof. intro m. unfold body_slow_assignment_prog.\n  eapply hoare_seq.\n  - (* Y *)\n    apply hoare_asgn.\n  - (* X *)\n    eapply hoare_consequence_pre.\n    + apply hoare_asgn.\n    + (* func *)\n      verify_assn.\nQed.\n\n\nFixpoint parity x :=\n  match x with\n  | 0 => 0\n  | 1 => 1\n  | S (S x') => parity x'\n  end.\n\nLemma parity_ge_2 : forall x, 2 <= x -> parity (x - 2) = parity x.\nProof.\n  induction x; intros; simpl.\n  - reflexivity.\n  - destruct x.\n    + lia.\n    + inversion H; subst; simpl.\n      * reflexivity.\n      * rewrite sub_0_r. reflexivity.\nQed.\n\nLemma parity_lt_2 : forall x, ~(2 <= x) -> parity x = x.\nProof.\n  induction x; intros; simpl.\n  - reflexivity.\n  - destruct x.\n    + reflexivity.\n    + lia.\nQed.\n\nTheorem parity_correct : forall (m:nat),\n  {{ X = m }}\n  while 2 <= X do\n    X := X - 2\n  end\n  {{ X = parity m }}.\nProof.\n  intro m.\n  apply hoare_consequence_pre with (P' := assert (ap parity X = parity m)).\n  --  eapply hoare_consequence_post.\n      - eapply hoare_while.\n        + (* While body *)\n          eapply hoare_consequence_pre.\n          * apply hoare_asgn.\n          * verify_assn.\n            rewrite <- H.\n            apply (parity_ge_2 (st X)).\n            destruct (st X). discriminate H0.\n            destruct n. discriminate H0.\n            lia.\n      - verify_assn.\n        rewrite <- H. symmetry.\n        apply parity_lt_2.\n        destruct (st X). lia.\n        destruct n. lia.\n        lia.\n  -- verify_assn.\nQed.\n\n\n\n(*\n    {{ X = m }} ->>\n    {{ X! * 1 = m!                                     }}\n      Y := 1;\n    {{ X! * Y = m!                                     }}\n      while ~(X = 0)\n      do   {{ X! * Y = m!  /\\  ~(X = 0)                }} ->>\n           {{ X! * Y = m!                              }}\n         Y := Y × X;\n           {{ X! * (Y * X) = m!                        }}\n         X := X - 1\n           {{ (X - 1)! * (Y * X) = m!                  }}\n      end\n    {{ X! * Y = m!  /\\  X = 0                          }} ->>\n    {{ Y = m! }}\n*)\n\n\n(*\n  {{ True }} ->>\n  {{ min a b  + 0 = min a b                      }}\n  X := a;\n  {{ min X b  + 0 = min a b                      }}\n  Y := b;\n  {{ min X Y  + 0 = min a b                      }}\n  Z := 0;\n  {{ min X Y  + Z = min a b                      }}\n  while ~(X = 0) && ~(Y = 0) do\n    {{ (min X Y  + Z = min a b) /\\ ~(X = 0) /\\ ~(Y = 0)    }} ->>\n    {{ (min (X - 1) (Y - 1)  + (Z + 1) = min a b)          }}\n    X := X - 1;\n    {{ (min X (Y - 1)  + (Z + 1) = min a b)                }}\n    Y := Y - 1;\n    {{ (min X Y  + (Z + 1) = min a b)                      }}\n    Z := Z + 1\n    {{ (min X Y  + Z = min a b)                        }}\n  end\n  {{ (min X Y  + Z = min a b) /\\ (X = 0) /\\ (Y = 0)    }} ->>\n  {{ Z = min a b }}\n*)\n\nDefinition is_wp P c Q :=\n  {{P}} c {{Q}} /\\ forall P', {{P'}} c {{Q}} -> (P' ->> P).\n\nTheorem is_wp_example :\n  is_wp (Y <= 4) <{X := Y + 1}> (X <= 5).\nProof.\n  split.\n  - eapply hoare_consequence_pre.\n    * apply hoare_asgn.\n    * verify_assn.\n  - intros P' H.\n    unfold hoare_triple in H.\n    unfold \"->>\".\n    intros st Hp'.\n    assert (G: (X !-> st Y + 1; st) X <= 5). {\n      simpl in H.\n      apply (H st (X !-> st Y + 1; st)).\n      + constructor. simpl. reflexivity.\n      + assumption.\n    }\n    unfold t_update in G. simpl in G.\n    Search (?c <-> S ?x <= S ?y).\n    Search (?x + ?y = ?y + ?x).\n    rewrite add_comm in G.\n    rewrite <- succ_le_mono in G.\n    simpl. \n    apply G.\nQed.\n\nTheorem hoare_asgn_weakest : forall Q X a,\n  is_wp (Q [X |-> a]) <{ X := a }> Q.\nProof.\n  split.\n  - apply hoare_asgn.\n  - intros P' Hc st Hpst.\n    unfold assn_sub.\n    apply (Hc st).\n    + constructor. reflexivity.\n    + assumption.\nQed.\n\n\nModule Himp2.\nImport Himp.\nLemma hoare_havoc_weakest : forall (P Q : Assertion) (X : string),\n  {{ P }} havoc X {{ Q }}  ->  P ->> havoc_pre X Q.\nProof.\n  intros P Q X H st Hpst n.\n  apply (H st).\n  - constructor.\n  - assumption.\nQed.\nEnd Himp2.\n\n\n\n\nInductive dcom : Type :=\n| DCSkip (Q : Assertion) (* skip {{ Q }} *)\n| DCSeq (d1 d2 : dcom)  (* d1 ; d2 *)\n| DCAsgn (X : string) (a : aexp) (Q : Assertion)  (* X := a {{ Q }} *)\n| DCIf (b : bexp) (P1 : Assertion) (d1 : dcom)\n       (P2 : Assertion) (d2 : dcom) (Q : Assertion)\n  (* if b then {{ P1 }} d1 else {{ P2 }} d2 end {{ Q }} *)\n| DCWhile (b : bexp) (P : Assertion) (d : dcom) (Q : Assertion)  (* while b do {{ P }} d end {{ Q }} *)\n| DCPre (P : Assertion) (d : dcom)  (* ->> {{ P }} d *)\n| DCPost (d : dcom) (Q : Assertion)  (* d ->> {{ Q }} *)\n.\n\nInductive decorated : Type :=\n  | Decorated : Assertion -> dcom -> decorated.\n\n\nDeclare Scope dcom_scope.\nNotation \"'skip' {{ P }}\" := (DCSkip P)\n      (in custom com at level 0, P constr) : dcom_scope.\nNotation \"l ':=' a {{ P }}\" := (DCAsgn l a P)\n      (in custom com at level 0, l constr at level 0, a custom com at level 85, P constr, no associativity) : dcom_scope.\nNotation \"'while' b 'do' {{ P }} d 'end' {{ Q }}\" := (DCWhile b P d Q)\n      (in custom com at level 89, b custom com at level 99, P constr, Q constr) : dcom_scope.\nNotation \"'if' b 'then' {{ P }} d 'else' {{ P' }} d' 'end' {{ Q }}\" := (DCIf b P d P' d' Q)\n      (in custom com at level 89, b custom com at level 99, P constr, P' constr, Q constr) : dcom_scope.\nNotation \"'->>' {{ P }} d\" := (DCPre P d)\n      (in custom com at level 12, right associativity, P constr) : dcom_scope.\nNotation \"d '->>' {{ P }}\" := (DCPost d P)\n      (in custom com at level 10, right associativity, P constr) : dcom_scope.\nNotation \" d ; d' \" := (DCSeq d d')\n      (in custom com at level 90, right associativity) : dcom_scope.\nNotation \"{{ P }} d\" := (Decorated P d)\n      (in custom com at level 91, P constr) : dcom_scope.\nOpen Scope dcom_scope.\n\nExample dec0 :=  <{ skip {{ True }} }>.\nExample dec1 :=  <{ while true do {{ True }} skip {{ True }} end  {{ True }} }>.\n\n\nExample dec_while : decorated :=\n  <{\n    {{ True }}\n    while ~(X = 0)\n    do\n      {{ True /\\ ~(X = 0) }}\n      X := X - 1\n      {{ True }}\n    end\n    {{ True /\\ X = 0}} ->>\n    {{ X = 0 }} \n  }>.\n\n\nFixpoint extract (d : dcom) : com :=\n  match d with\n  | DCSkip _            => CSkip\n  | DCSeq d1 d2         => CSeq (extract d1) (extract d2)\n  | DCAsgn X a _        => CAsgn X a\n  | DCIf b _ d1 _ d2 _  => CIf b (extract d1) (extract d2)\n  | DCWhile b _ d _     => CWhile b (extract d)\n  | DCPre _ d           => extract d\n  | DCPost d _          => extract d\n  end.\n\nDefinition extract_dec (dec : decorated) : com :=\n  match dec with\n  | Decorated P d => extract d\n  end.\n\nExample extract_while_ex :\n  extract_dec dec_while = <{while ~(X = 0) do X := X - 1 end}>.\nProof.\n  unfold dec_while.\n  reflexivity.\nQed.\n\n\nFixpoint post (d : dcom) : Assertion :=\n  match d with\n  | DCSkip P          => P\n  | DCSeq _ d2        => post d2\n  | DCAsgn _ _ Q      => Q\n  | DCIf _ _ _ _ _ Q  => Q\n  | DCWhile _ _ _ Q   => Q\n  | DCPre _ d         => post d\n  | DCPost _ Q        => Q\n  end.\n\nDefinition pre_dec (dec : decorated) : Assertion :=\n  match dec with\n  | Decorated P d => P\n  end.\n\nDefinition post_dec (dec : decorated) : Assertion :=\n  match dec with\n  | Decorated P d => post d\n  end.\n\n\nExample pre_dec_while : pre_dec dec_while = True.\nProof. reflexivity. Qed.\n\nExample post_dec_while : post_dec dec_while = (X = 0)%assertion.\nProof. reflexivity. Qed.\n\n\nDefinition dec_correct (dec : decorated) :=  {{pre_dec dec}} extract_dec dec {{post_dec dec}}.\n\nExample dec_while_triple_correct :\n  dec_correct dec_while\n = {{ True }}\n   while ~(X = 0) do X := X - 1 end\n   {{ X = 0 }}.\nProof. reflexivity. Qed.\n\nFixpoint verification_conditions (P : Assertion) (d : dcom) : Prop :=\n  match d with\n  | DCSkip Q    => (P ->> Q)\n  | DCSeq d1 d2 =>\n         verification_conditions P d1\n      /\\ verification_conditions (post d1) d2\n  | DCAsgn X a Q =>\n      (P ->> Q [X |-> a])\n  | DCIf b P1 d1 P2 d2 Q =>\n         ((P /\\  b) ->> P1)%assertion\n      /\\ ((P /\\ ~b) ->> P2)%assertion\n      /\\ (post d1 ->> Q) \n      /\\ (post d2 ->> Q)\n      /\\ verification_conditions P1 d1\n      /\\ verification_conditions P2 d2\n  | DCWhile b Pbody d Ppost =>\n      (* post d is the loop invariant and the initial precondition *)\n         (P ->> post d)\n      /\\ ((post d /\\  b) ->> Pbody)%assertion\n      /\\ ((post d /\\ ~b) ->> Ppost)%assertion\n      /\\ verification_conditions Pbody d\n  | DCPre P' d =>\n         (P ->> P') \n      /\\ verification_conditions P' d\n  | DCPost d Q =>\n         verification_conditions P d \n      /\\ (post d ->> Q)\n  end.\n\n\nTheorem verification_correct : forall d P,\n  verification_conditions P d -> {{P}} extract d {{post d}}.\nProof.\n  induction d; intros; simpl in *.\n  - (* Skip *)\n    eapply hoare_consequence_pre.\n      + apply hoare_skip.\n      + assumption.\n  - (* Seq *)\n    destruct H as [H1 H2].\n    eapply hoare_seq.\n      + apply IHd2. apply H2.\n      + apply IHd1. apply H1.\n  - (* Asgn *)\n    eapply hoare_consequence_pre.\n      + apply hoare_asgn.\n      + assumption.\n  - (* If *)\n    destruct H as [HPre1 [HPre2 [Hd1 [Hd2 [HThen HElse] ] ] ] ].\n    apply IHd1 in HThen. clear IHd1.\n    apply IHd2 in HElse. clear IHd2.\n    apply hoare_if.\n      + eapply hoare_consequence; eauto.\n      + eapply hoare_consequence; eauto.\n  - (* While *)\n    destruct H as [Hpre [Hbody1 [Hpost1 Hd] ] ].\n    eapply hoare_consequence; eauto.\n    apply hoare_while.\n    eapply hoare_consequence_pre; eauto.\n  - (* Pre *)\n    destruct H as [HP Hd].\n    eapply hoare_consequence_pre; eauto.\n  - (* Post *)\n    destruct H as [Hd HQ].\n    eapply hoare_consequence_post; eauto.\nQed.\n\nDefinition verification_conditions_dec (dec : decorated) : Prop :=\n  match dec with\n  | Decorated P d => verification_conditions P d\n  end.\n\nCorollary verification_correct_dec : forall dec,\n  verification_conditions_dec dec -> dec_correct dec.\nProof.\n  intros [P d]. apply verification_correct.\nQed.\n\nEval simpl in verification_conditions_dec dec_while.\n\nExample vc_dec_while : verification_conditions_dec dec_while.\nProof. verify_assn. Qed.\n\n\n\nLtac verify :=\n  intros;\n  apply verification_correct;\n  verify_assn.\n\nTheorem Dec_while_correct :  dec_correct dec_while.\nProof. verify. Qed.\n\n\nExample subtract_slowly_dec (m : nat) (p : nat) : decorated :=\n  <{\n      {{ X = m /\\ Z = p }} ->>\n      {{ Z - X = p - m }}\n    while ~(X = 0)\n    do {{ Z - X = p - m /\\ X <> 0 }} ->>\n         {{ (Z - 1) - (X - 1) = p - m }}\n       Z := Z - 1\n         {{ Z - (X - 1) = p - m }} ;\n       X := X - 1\n         {{ Z - X = p - m }}\n    end\n      {{ Z - X = p - m /\\ X = 0 }} ->>\n      {{ Z = p - m }} \n  }>.\nTheorem subtract_slowly_dec_correct : forall m p,\n  dec_correct (subtract_slowly_dec m p).\nProof. verify. (* this grinds for a bit! *) Qed.\n\n\n\n\n(* Definition swap : com := *)\n(*   <{ X := X + Y; *)\n(*      Y := X - Y; *)\n(*      X := X - Y }>. *)\nDefinition swap_dec (m n:nat) : decorated :=\n  <{\n       {{ X = m /\\ Y = n}} ->>\n       {{ (X + Y) - ((X + Y) - Y) = n /\\ (X + Y) - Y = m }}\n      X := X + Y\n       {{ X - (X - Y) = n /\\ X - Y = m }};\n      Y := X - Y\n       {{ X - Y = n /\\ Y = m }};\n      X := X - Y\n       {{ X = n /\\ Y = m}} \n  }>.\nTheorem swap_correct : forall m n,  dec_correct (swap_dec m n).\nProof. verify. Qed.\n\n\nDefinition div_mod_dec (a b : nat) : decorated :=\n  <{\n      {{ True }} ->>\n      {{ b * 0 + a = a }}\n      X := a\n      {{ b * 0 + X = a }};\n      Y := 0\n      {{ b * Y + X = a }};\n      while b <= X do\n        {{ b * Y + X = a /\\ b <= X }} ->>\n        {{ b * (Y + 1) + (X - b) = a }}\n        X := X - b\n        {{ b * (Y + 1) + X = a }};\n        Y := Y + 1\n        {{ b * Y + X = a }}\n      end\n      {{ b * Y + X = a /\\ ~(b <= X) }} ->>\n      {{ b * Y + X = a /\\ (X < b) }} \n  }>.\nTheorem div_mod_dec_correct : forall a b,  dec_correct (div_mod_dec a b).\nProof.\n  verify.\nQed.\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\nDefinition find_parity_dec' (m:nat) : decorated :=\n  <{\n        {{ X = m }} ->>\n        {{ ap ev X <-> ev m }}\n       while 2 <= X do\n          {{ (ap ev X <-> ev m) /\\ 2 <= X }} ->>\n          {{ ap ev (X - 2) <-> ev m }}\n          X := X - 2\n          {{ ap ev X <-> ev m }}\n       end\n       {{ (ap ev X <-> ev m) /\\ ~(2 <= X) }} ->>\n       {{ X=0 <-> ev m }} \n  }>.\n\nLemma l4 : forall m,\n  2 <= m -> (ev (m - 2) <-> ev m).\nProof.\n  induction m; intros. split; intro; constructor.\n  destruct m. inversion H. inversion H1. simpl in *.\n  rewrite <- minus_n_O in *. split; intro.\n    constructor. assumption.\n    inversion H0. assumption.\nQed.\n\nTheorem find_parity_correct' : forall m,  dec_correct (find_parity_dec' m).\nProof.\n  verify;\n    (* simplification too aggressive ... reverting a bit *)\n    fold (2 <=? (st X)) in *;\n    try rewrite leb_iff in *;\n    try rewrite leb_iff_conv in *; intuition; eauto; try lia.\n  - (* invariant preserved (part 1) *)\n    rewrite l4 in H0; eauto.\n  - (* invariant preserved (part 2) *)\n    rewrite l4; eauto.\n  - (* invariant strong enough to imply conclusion\n       (-> direction) *)\n    apply H0. constructor.\n  - (* invariant strong enough to imply conclusion\n       (<- direction) *)\n      destruct (st X) as [| [| n] ]. (* by H1 X can only be 0 or 1 *)\n      + (* st X = 0 *)\n        reflexivity.\n      + (* st X = 1 *)\n        inversion H.\n      + (* st X = 2 *)\n        lia.\nQed.\n\n\n\nExample slow_assignment_dec (m : nat) : decorated :=\n  <{  {{ X = m }} ->>\n      {{ X + 0 = m }}\n      Y := 0\n      {{ X + Y = m }};\n      while ~(X = 0) do\n        {{ X + Y = m /\\ ~(X = 0) }} ->>\n        {{ (X - 1) + (Y + 1) = m }}\n        X := X - 1\n        {{ X + (Y + 1) = m }};\n        Y := Y + 1\n        {{ X + Y = m }}\n      end\n      {{ X + Y = m /\\ (X = 0) }} ->>\n      {{ Y = m }}\n  }>.\n\nTheorem slow_assignment_dec_correct : forall m,  dec_correct (slow_assignment_dec m).\nProof. verify. Qed.\n\n\nDefinition foo1: nat -> nat -> nat := fun a b => a + b.\nDefinition foo2: nat -> nat -> Prop := fun a b => a = b.\n\nDefinition foo3: foo2 1 1. (* Theorem / Lemma is just functions *)\nProof. reflexivity. Qed.\n\n\n\nFixpoint fib n :=\n  match n with\n  | 0    => 1\n  | S n' => match n' with\n            | 0     => 1\n            | S n'' => fib n' + fib n''\n            end\n  end.\n\nLemma fib_eqn : forall n,\n  n > 0 -> fib n + fib (pred n) = fib (1 + n).\nProof.\n  intros n Hgt0.\n  destruct n as [| n'].\n  - inversion Hgt0.\n  - simpl. reflexivity.\nQed.\n\nDefinition T : string := \"T\".\n\nOpen Scope com_scope.\nDefinition fib_prog (n: nat) : com := \n  <{\n    X := 1;\n    Y := 1;\n    Z := 1;\n    while ~(X = 1 + n) do\n      T := Z;\n      Z := Z + Y;\n      Y := T;\n      X := 1 + X\n    end\n  }>.\n\n\nOpen Scope dcom_scope.\nDefinition dfib (n: nat) : decorated := \n  <{\n    {{ True }} ->>\n    {{ 1 = 1 /\\ 1 = 1 /\\ 1 = 1 }}\n    X := 1\n    {{ X = 1 /\\ 1 = 1 /\\ 1 = 1 }};\n    Y := 1\n    {{ X = 1 /\\ Y = 1 /\\ 1 = 1 }};\n    Z := 1\n    {{ X = 1 /\\ Y = 1 /\\ Z = 1 }} ->>\n    {{ X > 0 /\\ Y = (ap fib (X - 1)) /\\ Z = (ap fib X) }};\n    while ~(X = 1 + n) do\n      {{ X > 0 /\\ Y = (ap fib (X - 1)) /\\ Z = (ap fib X) /\\ ~(X = 1 + n) }}\n      T := Z\n      {{ X > 0 /\\ Y = (ap fib (X - 1)) /\\ Z = (ap fib X) /\\ T = (ap fib X) /\\ ~(X = 1 + n) }};\n      Z := Z + Y \n      {{ X > 0 /\\ Y = (ap fib (X - 1)) /\\ Z = (ap fib (1 + X)) /\\ T = (ap fib X) /\\ ~(X = 1 + n) }};\n      Y := T\n      {{ X > 0 /\\ Y = (ap fib X) /\\ Z = (ap fib (1 + X)) /\\ T = (ap fib X) /\\ ~(X = 1 + n)  }} ->>\n      {{ X > 0 /\\ Y = (ap fib ((X + 1) - 1)) /\\ Z = (ap fib (1 + X)) }};\n      X := 1 + X\n      {{ X > 0 /\\ Y = (ap fib (X - 1)) /\\ Z = (ap fib X) }}\n    end\n    {{ X > 0 /\\ Y = (ap fib (X - 1)) /\\ Z = (ap fib X) /\\ (X = 1 + n) }} ->>\n    {{ Y = fib n }}\n  }>.\n\nLemma sn_1: forall n, S n - 1 = n.\nProof. intros n. simpl. lia. Qed.\n\nLemma n_1_1: forall n, n + 1 - 1 = n.\nProof. intros n. lia. Qed.\n\nLemma n_0: forall n, n - 0 = n.\nProof. intros n. lia. Qed.\n\nTheorem dfib_correct : forall n,  dec_correct (dfib n).\nProof. verify.\n  - destruct (st X). inversion H.\n    rewrite -> sn_1. reflexivity.\n  - rewrite -> n_1_1. reflexivity.\n  - rewrite -> n_1_1.\n    rewrite -> n_0. reflexivity.\n  - rewrite -> sn_1. reflexivity.\nQed.\n\n(*\n  Exercise: 5 stars, advanced, optional (improve_dcom)\n  The formal decorated programs defined in this section are intended to \n  look as similar as possible to the informal ones defined earlier in the \n  chapter. If we drop this requirement, we can eliminate almost all annotations,\n   just requiring final postconditions and loop invariants to be provided explicitly. \n  Do this -- i.e., define a new version of dcom with as few annotations as possible \n  and adapt the rest of the formal development leading up to the verification_correct theorem. \n*)\n\nModule LastEx.\nEnd LastEx.\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/softwarefoundations/vol2_plf/Hoare2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.69935059725128}}
{"text": "\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** \n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Lesson 7: summary\n\n- generic notations and theories\n- interfaces\n- parametrizing theories\n- the BigOp library (the theories of fold)\n\nLet's start with a lie and then make it true:\n\n#<div style='color: red; font-size: 150%;'>#\nCoq is an object oriented\nprogramming language.\n#</div>#\n\n\n#</div>#\n\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Generic notations and theories\n\nPolymorphism != overloading.\n\nExample: the [==] computable equality\n\n#<div>#\n*)\n\n\n(**\n#</div>#\n\nPolymorphism \n\n#<div>#\n\n*)\n\nCheck (_ = _).\n\nCheck true = false.\n\nCheck (eq true false).\n\nCheck @eq.\n\nCheck (@eq _ true false).\n\nCheck (@eq bool true false).\n\n\n(**\n#</div>#\n\nOverloading : looking inside types \n\n#<div>#\n\n*)\n\nCheck (_ == _).\n\nCheck true == false.\n\nCheck (@eq_op _ true false).\n\nCheck (@eq_op bool_eqType true false).\n\nCheck 3 == 4.\n\nCheck [::] == [:: 2; 3; 4].\n\nSection T.\n\nVariable T : eqType.\nVariable x : T.\n\nEval lazy in x == x.\n\nEnd T.\n\n(**\n#</div>#\n\nObject oriented flavor\n\n#<div>#\n\n*)\n\nEval lazy in true == false.\n\nEval lazy in 3 == 4.\n\nEval lazy in [::] == [:: 2; 3; 4].\n\nCheck (3, true) == (4, false).\n\nEval lazy in (3, true) == (4, false).\n\n(**\n#</div>#\n\nOverloading may fail, polymorphism never\n\n#<div>#\n\n*)\n\nFail Check (fun x => x) == (fun y => y).\n\nCheck (fun x => x) = (fun y => y).\n\n(**\n#</div>#\n\nType inference\n\n#<div>#\n\n*)\n\nCheck [eqType of bool].\n\nFail Check [eqType of bool -> bool].\n\nCheck [eqType of {ffun bool -> bool}].\n\nCheck [eqType of nat].\n\nFail Check [eqType of nat -> nat].\n\nCheck [eqType of {ffun 'I_256 -> nat}].\n\nCheck [eqType of seq nat].\n\nFail Check [eqType of seq (nat -> nat)].\n\nCheck [eqType of seq {ffun 'I_256 -> nat}].\n\n(**\n#</div>#\n\nWe call [eqType] an interface. With some \"approximation\"\n[eqType] is defined as follows:\n\n<<\n\nModule Equality.\n\nStructure type : Type := Pack {\n  sort : Type;\n  op : sort -> sort -> bool;\n  axiom : ∀x y, reflect (x = y) (op x y)\n}.\n\n\nEnd Equality\n>>\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\nThis slide corresponds to\nsection 5.4 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n#<p><br/><p>#\n#</div>#\n\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Interfaces\n\nMathematical Components defines a hierarchy\nof interfaces. They group notations and\ntheorems.\n\n# <img style=\"width: 100%\" src=\"demo-support-master.png\"/>#\n\nLet's use the theory of [eqType]\n\n#<div>#\n*)\n\nAbout eqxx.\n\nAbout eq_refl.\n\nLemma test_eq (*(T : eqType) (x : T)*) :\n  (3 == 3) && (true == true) (*&& (x == x)*).\nProof.\nrewrite eqxx.\nrewrite eqxx.\n(* rewrite eqxx. *)\nby [].\nQed.\n\n(**\n#</div>#\n\nInterfaces do apply to registered, concrete examples\nsuch as [bool] or [nat]. They can also apply to variables,\nas long as their type is \"rich\" ([eqType] is richer than [Type]).\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\nThis slide corresponds to\nsection 5.5 and 7 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#<p><br/><p>#\n#</div>#\n\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Theories over an interface\n\nInterfaces can be used to parametrize an\nentire theory\n\n#<div>#\n*)\nModule Seq. Section Theory.\n\nVariable T : eqType.\n\nImplicit Type s : seq T.\n\nFixpoint mem_seq s x :=\n  if s is y :: s1\n  then (y == x) || mem_seq s1 x\n  else false.\n\n(* the infix \\in and \\notin are generic, not\n   just for sequences. *)\n\nFixpoint uniq s :=\n  if s is x :: s1\n  then (x \\notin s1) && uniq s1\n  else true.\n\nFixpoint undup s :=\n  if s is x :: s1 then\n    if x \\in s1 then undup s1 else x :: undup s1\n  else [::].\n\nEnd Theory. End Seq.\n\nAbout undup_uniq.\n\nEval lazy in (undup [::1;3;1;4]).\n\nLemma test : uniq (undup [::1;3;1;4]).\nProof.\nby rewrite undup_uniq.\nQed.\n\n(**\n#</div>#\n\nOthers interfaces\n\n**)\n\nSection Interfaces.\n\nVariable chT : choiceType.\n\nCheck (@sigW chT).\n\nCheck [eqType of chT].\n\nVariable coT : countType.\n\nCheck [countType of nat].\nCheck [choiceType of coT].\nCheck [choiceType of nat * nat].\nCheck [choiceType of seq coT].\n\nVariable fT : finType.\n\nCheck [finType of bool].\nCheck [finType of 'I_10].\nCheck [finType of {ffun 'I_10 -> fT}].\nCheck [finType of bool * bool].\n\nEnd Interfaces.\n\n\n(**\n#</div>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\nThis slide corresponds to\nsection 5.6 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#<p><br/><p>#\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Generic theories: the BigOp library\n\nThe BigOp library is the canonical example\nof a generic theory. It it about the\n[fold] iterator we studied in lesson 1,\nand the many uses it can have.\n\n#<div>#\n*)\n\nLemma sum_odd_3 :\n  \\sum_(0 <= i < 6 | odd i) i = 3^2.\nProof.\nrewrite unlock /=.\nby [].\nQed.\n\nAbout big_mkcond.\nAbout big_nat_recr.\n\nLemma sum_odd_3_bis :\n  \\sum_(0 <= i < 6 | odd i) i = 3^2.\nProof.\nrewrite big_mkcond big_nat_recr //= -big_mkcond /=.\nAbort.\n\nLemma prod_odd_3_bis : (* try [maxn/0] and also [maxn/1] *)\n  \\big[muln/1]_(0 <= i < 6 | odd i) i = 3^2.\nProof.\nrewrite big_mkcond big_nat_recr //= -big_mkcond /=.\nAbort.\n\n(**\n#</div>#\n\nMost of the lemmas require the operation to be a monoid,\nsome others to be a commutative monoid.\n\n#<div>#\n*)\n\nAbout bigD1.\n\n(**\n#</div>#\n\nSearching for bigop \n\n#<div>#\n*)\n\nLemma sum_odd_even_all n :\n  \\sum_(0 <= i < n) i = \n  \\sum_(0 <= i < n | odd i) i + \\sum_(0 <= i < n | ~~ odd i) i.\nProof.\nSearch _ (~~ _) in bigop.\nby rewrite (bigID odd).\nQed.\n\n(**\n#</div>#\n\nPrimer for bigop \n\n#<div>#\n*)\n\nSection Primer.\n\nVariable n: nat.\nVariable f : 'I_n -> nat.\nVariable g : nat -> nat.\n\nCheck \\big[addn/0]_(i <- [::1; 4; 5] | odd i) g i.\n\nCheck \\big[addn/0]_(i : 'I_n | odd i) f i.\n\nDefinition oddIn := [pred i | odd (i : 'I_n)].\n\nCheck \\big[addn/0]_(i in oddIn) f i.\n\nGoal \\sum_(i in oddIn) i = \\sum_(i < n | odd i) i.\nProof.\nby [].\nQed.\n\nCheck \\big[addn/0]_(0 <= i < n | odd i) g i.\n\nGoal \\sum_(0 <= i < n | odd i) g i = \\sum_(i < n | odd i) g i.\nProof.\nCheck big_mkord.\nrewrite big_mkord.\nby [].\nQed.\n\nGoal \\sum_(0 <= i < n |odd i) i.*2 = \\sum_(0 <= i < n|odd i) (i + i).\nProof.\nFail rewrite addnn.\nAbout eq_bigr.\napply: eq_bigr.\nmove=> i Hi.\nby rewrite addnn.\nQed.\n\nGoal \\sum_(0 <= i < n |odd i) i.*2 = \\sum_(0 <= i < n | odd i) (i + i).\nProof.\nAbout eq_bigr.\nrewrite (eq_bigr (fun i => i + i)) //.\nmove=> i Hi.\nby rewrite addnn.\nQed.\n\nGoal (\\sum_(i < n|odd i) i).*2 = \\sum_(i < n |odd i) i.*2.\nProof.\nAbout  big_morph.\nFail rewrite big_morph.\nrewrite (big_morph _ (_ : {morph double : x y / x + y}) (_ : 0.*2 = 0)).\n- by [].\n- move=> x y; exact: doubleD.\nby [].\nQed.\n\nEnd Primer.\n\n\n(**\n#</div>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\nThis slide corresponds to\nsection 5.7 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n\n#<p><br/><p>#\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Sum up\n\n- Coq is an object oriented language ;-)\n\n- in the Mathematical Components library [xxType] is an\n  interface (eg [eqType] for types with an equality test).\n  Notations and theorems are linked to interfaces.\n  Interfaces are organized in hierarchies (we just saw a picture,\n  how it works can be found in the book).\n\n#</div>#\n\n*)\n", "meta": {"author": "gares", "repo": "COQWS18", "sha": "2d438b94357d4be0baf47808db111214f08db467", "save_path": "github-repos/coq/gares-COQWS18", "path": "github-repos/coq/gares-COQWS18/COQWS18-2d438b94357d4be0baf47808db111214f08db467/lesson7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924674, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.6993505914328899}}
{"text": "(**************************************************************)\n(* Negation.v                                                 *)\n(*                                                            *)\n(* Author: Aaron Bohannon                                     *)\n(**************************************************************)\n\n(** This file provides some lemmas and tactics for manipulating\n    uses of [not] in propositions.  A few assorted items are\n    included that would make more sense in [Decidable.v] in the\n    standard library. *)\n\nRequire Export Decidable.\nRequire Import Setoid.\n\n(** * Some Lemmas and Tactics About Decidable Propositions *)\n\nLemma dec_iff : forall P Q : Prop,\n  decidable P ->\n  decidable Q ->\n  decidable (P <-> Q).\nProof.\n  unfold decidable in *. tauto.\nQed.\n\n(** With this hint database, we can leverage [auto] to check\n    decidability of propositions. *)\nHint Resolve\n  dec_True dec_False dec_or dec_and dec_imp dec_not dec_iff\n: decidable_prop.\n\n(** [solve_decidable using lib] will solve goals about the\n    decidability of a proposition, assisted by an auxiliary\n    database of lemmas.  The database is intended to contain\n    lemmas stating the decidability of additional propositions,\n    (e.g., the decidability of equality on a particular\n    inductive type). *)\nTactic Notation \"solve_decidable\" \"using\" ident(db) :=\n  match goal with\n  | |- decidable ?P =>\n    solve [ auto 100 with decidable_prop db ]\n  end.\n\nTactic Notation \"solve_decidable\" :=\n  solve_decidable using core.\n\n(** * Propositional Equivalences Involving Negation\n    These are all written with the unfolded form of negation,\n    since, in a situation (such as a tactic) where they will be\n    used repeatedly, we don't want to have to interleave their\n    uses with uses of [fold] or [unfold] to get their full\n    benefit.  (For a specific example, consider what would\n    happen if the first lemma [not_true_iff] were written as [~\n    True <-> False].  How would it be used to replace [True ->\n    (~ True)] with [False]?)\n*)\n\n(** ** Eliminating Negations\n    We begin with lemmas that, when read from left to right, can\n    be understood as ways to eliminate uses of [not]. *)\n\nLemma not_true_iff :\n  (True -> False) <-> False.\nProof.\n  tauto.\nQed.\n\nLemma not_false_iff :\n  (False -> False) <-> True.\nProof.\n  tauto.\nQed.\n\nLemma not_not_iff : forall P : Prop,\n  decidable P ->\n  (((P -> False) -> False) <-> P).\nProof.\n  unfold decidable in *. tauto.\nQed.\n\nLemma contrapositive : forall P Q : Prop,\n  decidable P ->\n  (((P -> False) -> (Q -> False)) <-> (Q -> P)).\nProof.\n  unfold decidable in *. tauto.\nQed.\n\nLemma and_not_l_iff_1 : forall P Q : Prop,\n  decidable P ->\n  ((P -> False) \\/ Q <-> (P -> Q)).\nProof.\n  unfold decidable in *. tauto.\nQed.\n\nLemma and_not_l_iff_2 : forall P Q : Prop,\n  decidable Q ->\n  ((P -> False) \\/ Q <-> (P -> Q)).\nProof.\n  unfold decidable in *. tauto.\nQed.\n\nLemma and_not_r_iff_1 : forall P Q : Prop,\n  decidable P ->\n  (P \\/ (Q -> False) <-> (Q -> P)).\nProof.\n  unfold decidable in *. tauto.\nQed.\n\nLemma and_not_r_iff_2 : forall P Q : Prop,\n  decidable Q ->\n  (P \\/ (Q -> False) <-> (Q -> P)).\nProof.\n  unfold decidable in *. tauto.\nQed.\n\nLemma imp_not_l : forall P Q : Prop,\n  decidable P ->\n  ((~ P -> Q) <-> (P \\/ Q)).\nProof.\n  unfold decidable in *. tauto.\nQed.\n\n(** ** Pushing Negations Around\n    We have four lemmas that, when read from left to right,\n    describe how to push negations toward the leaves of a\n    proposition and, when read from right to left, describe\n    how to pull negations toward the top of a propsition. *)\n\nLemma not_or_iff : forall P Q : Prop,\n  (P \\/ Q -> False) <-> (P -> False) /\\ (Q -> False).\nProof.\n  tauto.\nQed.\n\nLemma not_and_iff : forall P Q : Prop,\n  (P /\\ Q -> False) <-> (P -> Q -> False).\nProof.\n  tauto.\nQed.\n\nLemma not_imp_iff : forall P Q : Prop,\n  decidable P ->\n  (((P -> Q) -> False) <-> P /\\ (Q -> False)).\nProof.\n  unfold decidable in *. tauto.\nQed.\n\nLemma not_imp_rev_iff : forall P Q : Prop,\n  decidable P ->\n  (((P -> Q) -> False) <-> (Q -> False) /\\ P).\nProof.\n  unfold decidable in *. tauto.\nQed.\n\n(** * Tactics for Negations *)\n\n(** ** Folding Negations\n    This section provides tactics for folding uses of [not]\n    wherever possible.  Multiple versions are provided that\n    correspond to many of the forms used by the built-in\n    conversion tactics. *)\n\nTactic Notation \"fold\" \"any\" \"not\" :=\n  repeat (\n    match goal with\n    | |- context [?P -> False] =>\n      fold (~ P)\n    end).\n\nTactic Notation \"fold\" \"any\" \"not\" \"in\" ident(H) \"|-\" :=\n  repeat (\n    match goal with\n    | J: context [?P -> False] |- _ =>\n      fold (~ P) in H\n    end).\n\nTactic Notation \"fold\" \"any\" \"not\" \"in\" ident(H) :=\n  fold any not in H |-.\n\nTactic Notation \"fold\" \"any\" \"not\" \"in\" \"*\" \"|-\" :=\n  repeat (\n    match goal with\n    | H: context [?P -> False] |- _ =>\n      fold (~ P) in H\n    end).\n\nTactic Notation \"fold\" \"any\" \"not\" \"in\" \"*\" :=\n  fold any not in * |-; fold any not.\n\nTactic Notation \"fold\" \"any\" \"not\" \"in\" \"*\" \"|-\" \"*\" :=\n  fold any not in *.\n\n(** ** Folding [Iff]\n    This section provides tactics for folding uses of [iff]\n    wherever possible.  Multiple versions are provided that\n    correspond to many of the forms used by the built-in\n    conversion tactics.  These tactic may be better located\n    somewhere else in the standard library: although it is\n    used in this file, it has nothing to do with negation. *)\n\nTactic Notation \"fold\" \"any\" \"iff\" :=\n  repeat (\n    match goal with\n    | |- context [(?P -> ?Q) /\\ (?Q -> ?P)] =>\n      fold (P <-> Q)\n    end).\n\nTactic Notation \"fold\" \"any\" \"iff\" \"in\" ident(H) \"|-\" :=\n  repeat (\n    match goal with\n    | J: context [(?P -> ?Q) /\\ (?Q -> ?P)] |- _ =>\n      fold (P <-> Q) in H\n    end).\n\nTactic Notation \"fold\" \"any\" \"iff\" \"in\" ident(H) :=\n  fold any iff in H |-.\n\nTactic Notation \"fold\" \"any\" \"iff\" \"in\" \"*\" \"|-\" :=\n  repeat (\n    match goal with\n    | H: context [(?P -> ?Q) /\\ (?Q -> ?P)] |- _ =>\n      fold (P <-> Q) in H\n    end).\n\nTactic Notation \"fold\" \"any\" \"iff\" \"in\" \"*\" :=\n  fold any iff in * |-; fold any iff.\n\nTactic Notation \"fold\" \"any\" \"iff\" \"in\" \"*\" \"|-\" \"*\" :=\n  fold any iff in *.\n\n(** [push not using db] will push all negations to the leaves of\n    propositions in the goal, using the lemmas in [db] to assist\n    in checking the decidability of the propositions involved.\n    If [using db] is omitted, then [core] will be used.\n    Additional versions are provided to manipulate the\n    hypotheses, following the conventions used by the built-in\n    tactics.  (Is there a way to do this without using so much\n    cut-and-paste?) *)\n\nTactic Notation \"push\" \"not\" \"using\" ident(db) :=\n  unfold not, iff;\n  repeat (\n    match goal with\n    (** simplification by not_true_iff *)\n    | |- context [True -> False] =>\n      rewrite not_true_iff\n    (** simplification by not_false_iff *)\n    | |- context [False -> False] =>\n      rewrite not_false_iff\n    (** simplification by not_not_iff *)\n    | |- context [(?P -> False) -> False] =>\n      rewrite (not_not_iff P);\n        [ solve_decidable using db | ]\n    (** simplification by contrapositive *)\n    | |- context [(?P -> False) -> (?Q -> False)] =>\n      rewrite (contrapositive P Q);\n        [ solve_decidable using db | ]\n    (** simplification by and_not_l_iff_1/_2 *)\n    | |- context [(?P -> False) \\/ ?Q] =>\n      (rewrite (and_not_l_iff_1 P Q);\n        [ solve_decidable using db | ]) ||\n      (rewrite (and_not_l_iff_2 P Q);\n        [ solve_decidable using db | ])\n    (** simplification by and_not_r_iff_1/_2 *)\n    | |- context [?P \\/ (?Q -> False)] =>\n      (rewrite (and_not_r_iff_1 P Q);\n        [ solve_decidable using db | ]) ||\n      (rewrite (and_not_r_iff_2 P Q);\n        [ solve_decidable using db | ])\n    (** simplification by imp_not_l *)\n    | |- context [(?P -> False) -> ?Q] =>\n      rewrite (imp_not_l P Q);\n        [ solve_decidable using db | ]\n    (** rewriting by not_or_iff *)\n    | |- context [?P \\/ ?Q -> False] =>\n      rewrite (not_or_iff P Q)\n    (** rewriting by not_and_iff *)\n    | |- context [?P /\\ ?Q -> False] =>\n      rewrite (not_and_iff P Q)\n    (** rewriting by not_imp_iff *)\n    | |- context [(?P -> ?Q) -> False] =>\n      rewrite (not_imp_iff P Q);\n        [ solve_decidable using db | ]\n    end);\n  fold any not; fold any iff.\n\nTactic Notation \"push\" \"not\" :=\n  push not using core.\n\nTactic Notation \"push\" \"not\" \"in\" ident(H) \"|-\"\n  \"using\" ident(db) :=\n  unfold not, iff in * |-;\n  repeat (\n    match goal with\n    (** simplification by not_true_iff *)\n    | J: context [True -> False] |- _ =>\n      rewrite not_true_iff in H\n    (** simplification by not_false_iff *)\n    | J: context [False -> False] |- _ =>\n      rewrite not_false_iff in H\n    (** simplification by not_not_iff *)\n    | J: context [(?P -> False) -> False] |- _ =>\n      rewrite (not_not_iff P) in H;\n        [ | solve_decidable using db ]\n    (** simplification by contrapositive *)\n    | J: context [(?P -> False) -> (?Q -> False)] |- _ =>\n      rewrite (contrapositive P Q) in H;\n        [ | solve_decidable using db ]\n    (** simplification by and_not_l_iff_1/_2 *)\n    | J: context [(?P -> False) \\/ ?Q] |- _ =>\n      (rewrite (and_not_l_iff_1 P Q) in H;\n        [ | solve_decidable using db ]) ||\n      (rewrite (and_not_l_iff_2 P Q) in H;\n        [ | solve_decidable using db ])\n    (** simplification by and_not_r_iff_1/_2 *)\n    | J: context [?P \\/ (?Q -> False)] |- _ =>\n      (rewrite (and_not_r_iff_1 P Q) in H;\n        [ | solve_decidable using db ]) ||\n      (rewrite (and_not_r_iff_2 P Q) in H;\n        [ | solve_decidable using db ])\n    (** simplification by imp_not_l *)\n    | J: context [(?P -> False) -> ?Q] |- _ =>\n      rewrite (imp_not_l P Q) in H;\n        [ | solve_decidable using db ]\n    (** rewriting by not_or_iff *)\n    | J: context [?P \\/ ?Q -> False] |- _ =>\n      rewrite (not_or_iff P Q) in H\n    (** rewriting by not_and_iff *)\n    | J: context [?P /\\ ?Q -> False] |- _ =>\n      rewrite (not_and_iff P Q) in H\n    (** rewriting by not_imp_iff *)\n    | J: context [(?P -> ?Q) -> False] |- _ =>\n      rewrite (not_imp_iff P Q) in H;\n        [ | solve_decidable using db ]\n    end);\n  fold any not in * |-; fold any iff in * |-.\n\nTactic Notation \"push\" \"not\" \"in\" ident(H) \"|-\"  :=\n  push not in H |- using core.\n\nTactic Notation \"push\" \"not\" \"in\" ident(H) \"using\" ident(db) :=\n  push not in H |- using db.\nTactic Notation \"push\" \"not\" \"in\" ident(H) :=\n  push not in H |- using core.\n\nTactic Notation \"push\" \"not\" \"in\" \"*\" \"|-\" \"using\" ident(db) :=\n  unfold not, iff in * |-;\n  repeat (\n    match goal with\n    (** simplification by not_true_iff *)\n    | H: context [True -> False] |- _ =>\n      rewrite not_true_iff in H\n    (** simplification by not_false_iff *)\n    | H: context [False -> False] |- _ =>\n      rewrite not_false_iff in H\n    (** simplification by not_not_iff *)\n    | H: context [(?P -> False) -> False] |- _ =>\n      rewrite (not_not_iff P) in H;\n        [ | solve_decidable using db ]\n    (** simplification by contrapositive *)\n    | H: context [(?P -> False) -> (?Q -> False)] |- _ =>\n      rewrite (contrapositive P Q) in H;\n        [ | solve_decidable using db ]\n    (** simplification by and_not_l_iff_1/_2 *)\n    | H: context [(?P -> False) \\/ ?Q] |- _ =>\n      (rewrite (and_not_l_iff_1 P Q) in H;\n        [ | solve_decidable using db ]) ||\n      (rewrite (and_not_l_iff_2 P Q) in H;\n        [ | solve_decidable using db ])\n    (** simplification by and_not_r_iff_1/_2 *)\n    | H: context [?P \\/ (?Q -> False)] |- _ =>\n      (rewrite (and_not_r_iff_1 P Q) in H;\n        [ | solve_decidable using db ]) ||\n      (rewrite (and_not_r_iff_2 P Q) in H;\n        [ | solve_decidable using db ])\n    (** simplification by imp_not_l *)\n    | H: context [(?P -> False) -> ?Q] |- _ =>\n      rewrite (imp_not_l P Q) in H;\n        [ | solve_decidable using db ]\n    (** rewriting by not_or_iff *)\n    | H: context [?P \\/ ?Q -> False] |- _ =>\n      rewrite (not_or_iff P Q) in H\n    (** rewriting by not_and_iff *)\n    | H: context [?P /\\ ?Q -> False] |- _ =>\n      rewrite (not_and_iff P Q) in H\n    (** rewriting by not_imp_iff *)\n    | H: context [(?P -> ?Q) -> False] |- _ =>\n      rewrite (not_imp_iff P Q) in H;\n        [ | solve_decidable using db ]\n    end);\n  fold any not in * |-; fold any iff in * |-.\n\nTactic Notation \"push\" \"not\" \"in\" \"*\" \"|-\"  :=\n  push not in * |- using core.\n\nTactic Notation \"push\" \"not\" \"in\" \"*\" \"using\" ident(db) :=\n  push not using db; push not in * |- using db.\nTactic Notation \"push\" \"not\" \"in\" \"*\" :=\n  push not in * using core.\n\nTactic Notation \"push\" \"not\" \"in\" \"*\" \"|-\" \"*\"\n  \"using\" ident(db) :=\n  push not in * using db.\nTactic Notation \"push\" \"not\" \"in\" \"*\" \"|-\" \"*\" :=\n  push not in * using core.\n\nLemma test_push : forall P Q R : Prop,\n  decidable P ->\n  decidable Q ->\n  (~ True) ->\n  (~ False) ->\n  (~ ~ P) ->\n  (~ (P /\\ Q) -> ~ R) ->\n  ((P /\\ Q) \\/ ~ R) ->\n  (~ (P /\\ Q) \\/ R) ->\n  (R \\/ ~ (P /\\ Q)) ->\n  (~ R \\/ (P /\\ Q)) ->\n  (~ P -> R) ->\n  (~ ((R -> P) \\/ (R -> Q))) ->\n  (~ (P /\\ R)) ->\n  (~ (P -> R)) ->\n  True.\nProof.\n  intros. push not in *. tauto.\nQed.\n\n(** [pull not using db] will pull as many negations as possible\n    toward the top of the propositional formula in the goal,\n    using the lemmas in [db] to assist in checking the\n    decidability of the propositions involved.  If [using db] is\n    omitted, then [core] will be used.  Additional versions are\n    provided to manipulate the hypotheses, following the\n    conventions used by the built-in tactics.  (Is there a way\n    to do this without using so much cut-and-paste?) *)\n\nTactic Notation \"pull\" \"not\" \"using\" ident(db) :=\n  unfold not, iff;\n  repeat (\n    match goal with\n    (** simplification by not_true_iff *)\n    | |- context [True -> False] =>\n      rewrite not_true_iff\n    (** simplification by not_false_iff *)\n    | |- context [False -> False] =>\n      rewrite not_false_iff\n    (** simplification by not_not_iff *)\n    | |- context [(?P -> False) -> False] =>\n      rewrite (not_not_iff P);\n        [ solve_decidable using db | ]\n    (** simplification by contrapositive *)\n    | |- context [(?P -> False) -> (?Q -> False)] =>\n      rewrite (contrapositive P Q);\n        [ solve_decidable using db | ]\n    (** simplification by and_not_l_iff_1/_2 *)\n    | |- context [(?P -> False) \\/ ?Q] =>\n      (rewrite (and_not_l_iff_1 P Q);\n        [ solve_decidable using db | ]) ||\n      (rewrite (and_not_l_iff_2 P Q);\n        [ solve_decidable using db | ])\n    (** simplification by and_not_r_iff_1/_2 *)\n    | |- context [?P \\/ (?Q -> False)] =>\n      (rewrite (and_not_r_iff_1 P Q);\n        [ solve_decidable using db | ]) ||\n      (rewrite (and_not_r_iff_2 P Q);\n        [ solve_decidable using db | ])\n    (** simplification by imp_not_l *)\n    | |- context [(?P -> False) -> ?Q] =>\n      rewrite (imp_not_l P Q);\n        [ solve_decidable using db | ]\n    (** rewriting by not_or_iff *)\n    | |- context [(?P -> False) /\\ (?Q -> False)] =>\n      rewrite <- (not_or_iff P Q)\n    (** rewriting by not_and_iff *)\n    | |- context [?P -> ?Q -> False] =>\n      rewrite <- (not_and_iff P Q)\n    (** rewriting by not_imp_iff *)\n    | |- context [?P /\\ (?Q -> False)] =>\n      rewrite <- (not_imp_iff P Q);\n        [ solve_decidable using db | ]\n    (** rewriting by not_imp_rev_iff *)\n    | |- context [(?Q -> False) /\\ ?P] =>\n      rewrite <- (not_imp_rev_iff P Q);\n        [ solve_decidable using db | ]\n    end);\n  fold any not; fold any iff.\n\nTactic Notation \"pull\" \"not\" :=\n  pull not using core.\n\nTactic Notation \"pull\" \"not\" \"in\" ident(H) \"|-\"\n  \"using\" ident(db) :=\n  unfold not, iff in * |-;\n  repeat (\n    match goal with\n    (** simplification by not_true_iff *)\n    | J: context [True -> False] |- _ =>\n      rewrite not_true_iff in H\n    (** simplification by not_false_iff *)\n    | J: context [False -> False] |- _ =>\n      rewrite not_false_iff in H\n    (** simplification by not_not_iff *)\n    | J: context [(?P -> False) -> False] |- _ =>\n      rewrite (not_not_iff P) in H;\n        [ | solve_decidable using db ]\n    (** simplification by contrapositive *)\n    | J: context [(?P -> False) -> (?Q -> False)] |- _ =>\n      rewrite (contrapositive P Q) in H;\n        [ | solve_decidable using db ]\n    (** simplification by and_not_l_iff_1/_2 *)\n    | J: context [(?P -> False) \\/ ?Q] |- _ =>\n      (rewrite (and_not_l_iff_1 P Q) in H;\n        [ | solve_decidable using db ]) ||\n      (rewrite (and_not_l_iff_2 P Q) in H;\n        [ | solve_decidable using db ])\n    (** simplification by and_not_r_iff_1/_2 *)\n    | J: context [?P \\/ (?Q -> False)] |- _ =>\n      (rewrite (and_not_r_iff_1 P Q) in H;\n        [ | solve_decidable using db ]) ||\n      (rewrite (and_not_r_iff_2 P Q) in H;\n        [ | solve_decidable using db ])\n    (** simplification by imp_not_l *)\n    | J: context [(?P -> False) -> ?Q] |- _ =>\n      rewrite (imp_not_l P Q) in H;\n        [ | solve_decidable using db ]\n    (** rewriting by not_or_iff *)\n    | J: context [(?P -> False) /\\ (?Q -> False)] |- _ =>\n      rewrite <- (not_or_iff P Q) in H\n    (** rewriting by not_and_iff *)\n    | J: context [?P -> ?Q -> False] |- _ =>\n      rewrite <- (not_and_iff P Q) in H\n    (** rewriting by not_imp_iff *)\n    | J: context [?P /\\ (?Q -> False)] |- _ =>\n      rewrite <- (not_imp_iff P Q) in H;\n        [ | solve_decidable using db ]\n    (** rewriting by not_imp_rev_iff *)\n    | J: context [(?Q -> False) /\\ ?P] |- _ =>\n      rewrite <- (not_imp_rev_iff P Q) in H;\n        [ | solve_decidable using db ]\n    end);\n  fold any not in * |-; fold any iff in * |-.\n\nTactic Notation \"pull\" \"not\" \"in\" ident(H) \"|-\"  :=\n  pull not in H |- using core.\n\nTactic Notation \"pull\" \"not\" \"in\" ident(H) \"using\" ident(db) :=\n  pull not in H |- using db.\nTactic Notation \"pull\" \"not\" \"in\" ident(H) :=\n  pull not in H |- using core.\n\nTactic Notation \"pull\" \"not\" \"in\" \"*\" \"|-\" \"using\" ident(db) :=\n  unfold not, iff in * |-;\n  repeat (\n    match goal with\n    (** simplification by not_true_iff *)\n    | H: context [True -> False] |- _ =>\n      rewrite not_true_iff in H\n    (** simplification by not_false_iff *)\n    | H: context [False -> False] |- _ =>\n      rewrite not_false_iff in H\n    (** simplification by not_not_iff *)\n    | H: context [(?P -> False) -> False] |- _ =>\n      rewrite (not_not_iff P) in H;\n        [ | solve_decidable using db ]\n    (** simplification by contrapositive *)\n    | H: context [(?P -> False) -> (?Q -> False)] |- _ =>\n      rewrite (contrapositive P Q) in H;\n        [ | solve_decidable using db ]\n    (** simplification by and_not_l_iff_1/_2 *)\n    | H: context [(?P -> False) \\/ ?Q] |- _ =>\n      (rewrite (and_not_l_iff_1 P Q) in H;\n        [ | solve_decidable using db ]) ||\n      (rewrite (and_not_l_iff_2 P Q) in H;\n        [ | solve_decidable using db ])\n    (** simplification by and_not_r_iff_1/_2 *)\n    | H: context [?P \\/ (?Q -> False)] |- _ =>\n      (rewrite (and_not_r_iff_1 P Q) in H;\n        [ | solve_decidable using db ]) ||\n      (rewrite (and_not_r_iff_2 P Q) in H;\n        [ | solve_decidable using db ])\n    (** simplification by imp_not_l *)\n    | H: context [(?P -> False) -> ?Q] |- _ =>\n      rewrite (imp_not_l P Q) in H;\n        [ | solve_decidable using db ]\n    (** rewriting by not_or_iff *)\n    | H: context [(?P -> False) /\\ (?Q -> False)] |- _ =>\n      rewrite <- (not_or_iff P Q) in H\n    (** rewriting by not_and_iff *)\n    | H: context [?P -> ?Q -> False] |- _ =>\n      rewrite <- (not_and_iff P Q) in H\n    (** rewriting by not_imp_iff *)\n    | H: context [?P /\\ (?Q -> False)] |- _ =>\n      rewrite <- (not_imp_iff P Q) in H;\n        [ | solve_decidable using db ]\n    (** rewriting by not_imp_rev_iff *)\n    | H: context [(?Q -> False) /\\ ?P] |- _ =>\n      rewrite <- (not_imp_rev_iff P Q) in H;\n        [ | solve_decidable using db ]\n    end);\n  fold any not in * |-; fold any iff in * |-.\n\nTactic Notation \"pull\" \"not\" \"in\" \"*\" \"|-\"  :=\n  pull not in * |- using core.\n\nTactic Notation \"pull\" \"not\" \"in\" \"*\" \"using\" ident(db) :=\n  pull not using db; pull not in * |- using db.\nTactic Notation \"pull\" \"not\" \"in\" \"*\" :=\n  pull not in * using core.\n\nTactic Notation \"pull\" \"not\" \"in\" \"*\" \"|-\" \"*\"\n  \"using\" ident(db) :=\n  pull not in * using db.\nTactic Notation \"pull\" \"not\" \"in\" \"*\" \"|-\" \"*\" :=\n  pull not in * using core.\n\nLemma test_pull : forall P Q R : Prop,\n  decidable P ->\n  decidable Q ->\n  (~ True) ->\n  (~ False) ->\n  (~ ~ P) ->\n  (~ (P /\\ Q) -> ~ R) ->\n  ((P /\\ Q) \\/ ~ R) ->\n  (~ (P /\\ Q) \\/ R) ->\n  (R \\/ ~ (P /\\ Q)) ->\n  (~ R \\/ (P /\\ Q)) ->\n  (~ P -> R) ->\n  (~ (R -> P) /\\ ~ (R -> Q)) ->\n  (~ P \\/ ~ R) ->\n  (P /\\ ~ R) ->\n  (~ R /\\ P) ->\n  True.\nProof.\n  intros. pull not in *. tauto.\nQed.\n", "meta": {"author": "polyvios", "repo": "contextual-effects-coq", "sha": "d10f2a6ffb8544359f7996e07bfbd5dc1d403759", "save_path": "github-repos/coq/polyvios-contextual-effects-coq", "path": "github-repos/coq/polyvios-contextual-effects-coq/contextual-effects-coq-d10f2a6ffb8544359f7996e07bfbd5dc1d403759/Negation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.6993505900278402}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\nInductive natural : Type :=   Zero : natural | Succ : natural -> natural .\n\nInductive lst : Type :=  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 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.\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   - \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). \n      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   - \n     rewrite mult_zero. reflexivity.\n   - simpl. rewrite IHx. rewrite mult_succ. reflexivity.\nQed.\n\nLemma distrib : forall (x y z : natural), mult (plus x y) z = plus (mult x z) (mult y z).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. rewrite plus_assoc. rewrite (plus_commut (mult y z) z). \n     rewrite <- plus_assoc. reflexivity.\nQed.\n\nLemma mult_assoc : forall (x y z : natural), mult (mult x y) z = mult x (mult y z).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite distrib. rewrite IHx. reflexivity.\nQed.\n\nLemma qfac_mult : forall (x y : natural), qfac x y = mult (qfac x (Succ Zero)) y.\nProof.\n   intro.\n   induction x.\n   - reflexivity.\n   - intros. simpl. rewrite IHx. rewrite (IHx x). lfind. Admitted.\n", "meta": {"author": "ana-brendel", "repo": "coq-benchmarks", "sha": "78b9ca2993b0fb579d814ed17e63c6859e79681c", "save_path": "github-repos/coq/ana-brendel-coq-benchmarks", "path": "github-repos/coq/ana-brendel-coq-benchmarks/coq-benchmarks-78b9ca2993b0fb579d814ed17e63c6859e79681c/modifications/quickchick_fails/test96_goal33/lfind_goal33.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898229217591, "lm_q2_score": 0.7718435030872967, "lm_q1q2_score": 0.6992823586853701}}
{"text": "\nDefinition BoolE : forall (p:bool -> Prop), p true -> p false -> forall (x:bool), p x :=\n    fun (p:bool -> Prop) => \n        fun (tt:p true) =>\n            fun (ff: p false) =>\n                fun (x:bool) =>\n                    match x with\n                    | true  => tt\n                    | false => ff\n                    end.\n\nDefinition BoolC1 : bool := true.\nDefinition BoolC2 : bool := false.\n\nDefinition L1 : forall (x:bool), negb (negb x) = x.\nProof.\n    intros x.\n    apply (BoolE (fun z => negb (negb z) = z)).\n    - exact (eq_refl true).\n    - exact (eq_refl false).\nQed.\n\n\nDefinition L2 : forall (x:bool), negb (negb x) = x :=\n    fun (x:bool) => BoolE \n        (fun (z:bool) => negb (negb z) = z) \n        (eq_refl true) \n        (eq_refl false) \n        x.\n\n\nDefinition BoolRec : forall (p:bool -> Type), p true -> p false -> forall (x:bool), p x :=\n    fun (p:bool -> Type) => \n        fun (tt:p true) =>\n            fun (ff: p false) =>\n                fun (x:bool) =>\n                    match x with\n                    | true  => tt\n                    | false => ff\n                    end.\n\nDefinition not : bool -> bool := BoolRec (fun (x:bool) => bool) false true.\n\n\nDefinition L3 : not = fun(x:bool) => match x with true => false | false => true end :=\n    eq_refl not.\n\nDefinition BoolE' : forall (p:bool -> Prop), p true -> p false -> forall (x:bool), p x :=\n    fun (p:bool -> Prop) => BoolRec p.\n    \nVariable BoolE1 : forall (p:bool -> Prop), p true -> p false -> forall (x:bool), p x.\n\nDefinition L4 : forall (x:bool), x = true \\/ x = false :=\n    fun (x:bool) =>\n        match x with\n        | true  => or_introl (eq_refl true)\n        | false => or_intror (eq_refl false)\n        end.\n\nDefinition L5 : forall (x:bool), x = true \\/ x = false := BoolE1 \n    (fun (x:bool) => x = true \\/ x = false) \n    (or_introl (eq_refl true))\n    (or_intror (eq_refl false)).\n\nDefinition L6 : forall (p:bool -> Prop), (forall (x y:bool), y = x -> p x) -> forall (x:bool), p x :=\n    fun (p:bool -> Prop) => \n        fun (q:forall (x y:bool), y = x -> p x) =>\n            fun (x:bool) => q x x (eq_refl x).\n\n\nFail Definition L7 : forall (p:bool -> Prop) (x:bool), (x = true -> p true) -> (x = false -> p false) -> p x :=\n    fun (p:bool -> Prop) =>\n        fun (x:bool) =>\n            fun (tt:x = true -> p true) =>\n                fun (ff:x = false -> p false) =>\n                    match x with\n                    | true  => tt (eq_refl true)\n                    | false => ff (eq_refl false)\n                    end.\n\nDefinition bool_dec : forall (x:bool), x = true \\/ x = false :=\n    fun (x:bool) =>\n        match x with\n        | true  => or_introl (eq_refl true)\n        | false => or_intror (eq_refl false)\n        end.\n\nFail Definition L8 : forall (p:bool -> Prop) (x:bool), (x = true -> p true) -> (x = false -> p false) -> p x :=\n    fun (p:bool -> Prop) =>\n        fun (x:bool) =>\n            fun (tt:x = true -> p true) =>\n                fun (ff:x = false -> p false) =>\n                    match bool_dec x with\n                    | or_introl p  => tt p\n                    | or_intror p  => ff p\n                    end.\n\nDefinition bool_dec' : forall (x:bool), {x = true} + {x = false} :=\n    fun (x:bool) => \n        match x with\n        | true  => left  (eq_refl true)\n        | false => right (eq_refl false)\n        end. \n\n\nFail Definition L9 : forall (p:bool -> Prop) (x:bool), (x = true -> p true) -> (x = false -> p false) -> p x :=\n    fun (p:bool -> Prop) =>\n        fun (x:bool) =>\n            fun (tt:x = true -> p true) =>\n                fun (ff:x = false -> p false) =>\n                    match bool_dec' x with\n                    | left p   => tt p\n                    | right p  => ff p\n                    end.\n\n\nDefinition L10 : forall (p:bool -> Prop) (x:bool), (x = true -> p true) -> (x = false -> p false) -> p x.\nProof.\n    intros p x H1 H2. destruct x.\n    - apply H1. reflexivity.\n    - apply H2. reflexivity.\nQed.\n\n\nDefinition L11 : forall (p:bool -> Prop) (x:bool), (x = true -> p true) -> (x = false -> p false) -> p x :=\n    fun (p:bool -> Prop) (x:bool) (H1:x = true -> p true) (H2:x = false -> p false) =>\n        match x as b return x = b -> p b with\n        | true  => H1\n        | false => H2\n        end (eq_refl x).\n\n\nPrint L10.\n\nDefinition L12 : forall (p:bool -> Prop) (x:bool), (x = true -> p true) -> (x = false -> p false) -> p x :=\n    fun (p:bool -> Prop) (x:bool) (H1:x = true -> p true) (H2:x = false -> p false) =>\n        match x as b return  ((b = true -> p true) -> (b = false -> p false) -> p b) with\n        | true  => fun (H3:true  = true -> p true) (_ :true  = false -> p false) => H3 (eq_refl true)\n        | false => fun (_ :false = true -> p true) (H4:false = false -> p false) => H4 (eq_refl false) \n        end H1 H2.\n\n\nDefinition and1 : bool -> bool -> bool := BoolRec\n    (fun _ => bool -> bool)\n    (fun y => y)\n    (fun _ => false).\n\nDefinition and : bool -> bool -> bool :=\n    fun (x:bool) =>\n        fun(y:bool) => (BoolRec\n            (fun _ => bool)\n            y\n            false) x. \n\n(* and is computationally equal to ....                                        *)\nDefinition L13 : and = fun (x y:bool) => match x with true => y | false => false end.\nProof.\n    unfold and. unfold BoolRec. reflexivity.\nQed.\n\nDefinition or : bool -> bool -> bool :=\n    fun (x:bool) => \n        fun (y:bool) => (BoolRec\n            (fun _ => bool)\n            true\n            y) x.\n\n(* or is computationally equal to ....                                        *)\nDefinition L14 : or = fun (x y:bool) => match x with true => true | false => y end.\nProof.\n    unfold or. unfold BoolRec. reflexivity.\nQed.\n\n\nDefinition L15 : forall (x y:bool), and x y = true <-> x = true /\\ y = true.\nProof.\n    intros x y. split; intros H.\n    - unfold and in H. unfold BoolRec in H. destruct x.\n        + split. \n            { reflexivity. }\n            { assumption. }\n        + inversion H.\n    - destruct H as [H1 H2]. rewrite H1. rewrite H2. reflexivity.\nQed.\n\nPrint L15.\n\n\nDefinition subst2 (a:Type) (p:a -> Prop) (x y:a) (e:x = y) (px: p x) : p y.\nProof.\n   rewrite <- e. assumption. \nQed.\n\nDefinition subst1 (a:Type) (p:a -> Prop) (x y:a) (e:x = y) (px: p x) : p y.\nProof.\nrefine (\n    match e with\n    | eq_refl _ => px\n    end\n).\nDefined.\n\nDefinition subst : forall (a:Type) (p:a -> Prop) (x y:a), x = y -> p x -> p y :=\n    fun (a:Type) (p:a -> Prop) (x y:a) (e:x = y) (px:p x) =>\n        match e with\n        | eq_refl _ => px\n        end.\n\nDefinition boolFalse : false = true -> False :=\n    fun (e:false = true) => \n        subst bool (fun (b:bool) => if b then False else True) false true e I.\n\nDefinition contradiction : forall (p:Prop), False -> p :=\n    fun (p:Prop) (H:False) => match H with end.\n\n\nDefinition subst2d : forall (a:Type) (p:a -> a -> Prop) (x x' y y':a),\n    x = x' -> y = y' -> p x y -> p x' y' :=\n    fun (a:Type) (p:a -> a -> Prop) (x x' y y':a) =>\n        fun (ex:x = x') (ey:y = y') (pxy:p x y) =>\n            match ex with\n            | eq_refl _ =>\n                match ey with\n                | eq_refl _ => pxy\n                end\n            end.  \n\n\nDefinition L16 : forall (x y:bool), and x y = true <-> x = true /\\ y = true.\nProof.\n    refine (fun (x y:bool) => conj\n        (fun (H:and x y = true)       => \n            match x as b return (if b then y else false) = true -> b = true /\\ y = true with\n            | true  => fun (H1:y = true) => conj (eq_refl true) H1\n            | false => fun (H1:false = true) => conj H1 (contradiction _ (boolFalse H1))\n            end H)\n        (fun (H:x = true /\\ y = true) => \n            match H with \n            | conj H1 H2 => \n                subst2d bool (fun x y => and x y = true) \n                    true x true y (eq_sym H1) (eq_sym H2) (eq_refl true)\n            end)\n).\nQed.\n\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/cttwc/bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6992823452573095}}
{"text": "\n(**************************************************************************)\n(**  Mechanised Framework for Local Interactions & Distributed Algorithms   \n                                                                            \n     T. Balabonski, P. Courtieu, L. Rieg, X. Urbain                         \n                                                                            \n     PACTOLE project                                                        \n                                                                            \n     This file is distributed under the terms of the CeCILL-C licence     *)\n(**************************************************************************)\n\n\n(**************************************************************************)\n(* Author : Mathis Bouverot-Dupuis (June 2022).\n\n * This file implements an algorithm to ALIGN all robots on an arbitrary \n * axis, in the plane (R²). The algorithm assumes there are no byzantine robots,\n * and works in a FLEXIBLE and SEMI-SYNCHRONOUS setting. \n\n * The algorithm is as follows : all robots go towards the 'weber point' of \n * the configuration. The weber point, also called geometric median, is unique \n * if the robots are not aligned, and has the property that moving any robot\n * towards the weber point in a straight line doesn't change the weber point. \n * It thus remains at the same place throughout the whole execution.  *)\n(**************************************************************************)\n\n\nRequire Import Bool.\nRequire Import Arith.Div2.\nRequire Import Lia Field.\nRequire Import Rbase Rbasic_fun R_sqrt Rtrigo_def.\nRequire Import List.\nRequire Import SetoidList.\nRequire Import Relations.\nRequire Import RelationPairs.\nRequire Import Morphisms.\nRequire Import Psatz.\nRequire Import Inverse_Image.\nRequire Import FunInd.\nRequire Import FMapFacts.\n\n(* Helping typeclass resolution avoid infinite loops. *)\nTypeclasses eauto := (bfs).\n\n(* Pactole basic definitions *)\nRequire Export Pactole.Setting.\n(* Specific to R^2 topology *)\nRequire Import Pactole.Spaces.R2.\n(* Specific to gathering *)\nRequire Pactole.CaseStudies.Gathering.WithMultiplicity.\nRequire Import Pactole.CaseStudies.Gathering.Definitions.\n(* Specific to multiplicity *)\nRequire Import Pactole.Observations.MultisetObservation.\n(* Specific to flexibility *)\nRequire Import Pactole.Models.Flexible.\n(* Specific to settings with no Byzantine robots *)\nRequire Import Pactole.Models.NoByzantine.\n(* Utility lemmas. *)\nRequire Import Pactole.CaseStudies.Gathering.InR2.Weber.Utils.\n(* Specific to definition and properties of the weber point. *)\nRequire Import Pactole.CaseStudies.Gathering.InR2.Weber.Weber_point.\n\n(* User defined *)\nImport Permutation.\nImport Datatypes.\n\n\nSet Implicit Arguments.\nClose Scope R_scope.\nClose Scope VectorSpace_scope.\n\n\nSection Alignment.\nLocal Existing Instances dist_sum_compat.\n\n(* We assume the existence of a function that calculates a weber point of a collection\n * (even when the weber point is not unique).\n * This is a very strong assumption : such a function may not exist in closed form, \n * and the Weber point can only be approximated. *)\nAxiom weber_calc : list R2 -> R2.\nAxiom weber_calc_correct : forall ps, Weber ps (weber_calc ps).\n(* We also suppose this function doesn't depend on the order of the points. \n* This is probably not necessary (we can show that it holds when the points aren't colinear) \n* but simplifies the proof a bit. *)\nAxiom weber_calc_compat : Proper (PermutationA equiv ==> equiv) weber_calc.\nLocal Existing Instance weber_calc_compat.\n  \n(* The number of robots *)\nVariables n : nat.\nHypothesis lt_0n : 0 < n.\n\n(* There are no byzantine robots. *)\nLocal Instance N : Names := Robots n 0.\nLocal Instance NoByz : NoByzantine.\nProof using . now split. Qed.\n\nLemma list_in_length_n0 {A : Type} x (l : list A) : List.In x l -> length l <> 0.\nProof using . intros Hin. induction l as [|y l IH] ; cbn ; auto. Qed.\n\nLemma byz_impl_false : B -> False.\nProof using . \nintros b. assert (Hbyz := In_Bnames b). \napply list_in_length_n0 in Hbyz. \nrewrite Bnames_length in Hbyz.\ncbn in Hbyz. intuition.\nQed.\n\n(* Use this tactic to solve any goal\n * provided there is a byzantine robot as a hypothesis. *)\nLtac byz_exfalso :=\n  match goal with \n  | b : ?B |- _ => exfalso ; apply (byz_impl_false b)\n  end.\n\n(* Since all robots are good robots, we can define a function\n * from identifiers to good identifiers. *)\nDefinition unpack_good (id : ident) : G :=\n  match id with \n  | Good g => g \n  | Byz _ => ltac:(byz_exfalso)\n  end.\n\nLemma good_unpack_good id : Good (unpack_good id) == id.\nProof using . unfold unpack_good. destruct_match ; [auto | byz_exfalso]. Qed.\n\nLemma unpack_good_good g : unpack_good (Good g) = g.\nProof using . reflexivity. Qed.  \n\n(* The robots are in the plane (R^2). *)\nLocal Instance Loc : Location := make_Location R2.\nLocal Instance LocVS : RealVectorSpace location := R2_VS.\nLocal Instance LocES : EuclideanSpace location := R2_ES.\n\n(* Refolding typeclass instances *)\nLtac foldR2 :=\n  change R2 with location in *;\n  change R2_Setoid with location_Setoid in *;\n  change state_Setoid with location_Setoid in *;\n  change R2_EqDec with location_EqDec in *;\n  change state_EqDec with location_EqDec in *;\n  change R2_VS with LocVS in *;\n  change R2_ES with LocES in *.\n\n(* Robots don't have a state (and thus no memory) apart from their location. *)\nLocal Instance St : State location := OnlyLocation (fun f => True).\n(* Robots choose their destination and also the path they take to this destination. *)\nLocal Instance RobotC : robot_choice (path location) := {| robot_choice_Setoid := @path_Setoid _ location_Setoid |}.\n\n(* Robots view the other robots' positions up to a similarity. *)\nLocal Instance FrameC : frame_choice (similarity location) := FrameChoiceSimilarity.\nLocal Instance UpdateC : update_choice ratio := OnlyFlexible.\nLocal Instance InactiveC : inactive_choice unit := NoChoiceIna.\n\n(* In a flexible setting, the minimum distance that robots are allowed to move is delta. *)\nVariables delta : R.\nHypothesis delta_g0 : (0 < delta)%R.\n\n(* We are in a flexible and semi-synchronous setting (for now). *)\nLocal Instance UpdateF : update_function (path location) (similarity location) ratio := \n  FlexibleUpdate delta. \n(* We are in a semi-synchronous setting : inactive robots don't move. *)\nLocal Instance InactiveF : inactive_function _.\n  refine {| inactive := fun config id _ => config id |}.\nProof using . repeat intro. now subst. Defined.\n\n(* The support of a multiset, but elements are repeated \n * a number of times equal to their multiplicity. \n * This is needed to convert an observation from multiset to list format, \n * so that we can use functions [colinear_dec] and [weber_calc]. *)\nDefinition multi_support {A} `{EqDec A} (s : multiset A) :=\n  List.flat_map (fun '(x, mx) => alls x mx) (elements s).\n\nLocal Instance multi_support_compat {A} `{EqDec A} : Proper (equiv ==> PermutationA equiv) (@multi_support A _ _).\nProof using . \nintros s s' Hss'. unfold multi_support. f_equiv.\n+ intros [x mx] [y my] Hxy. inv Hxy. simpl in H0, H1. now rewrite H0, H1.\n+ now apply elements_compat.\nQed.\n\n\n(* The main algorithm : just move towards the weber point\n * (in a straight line) until all robots are aligned. *)\nDefinition gatherW_pgm obs : path location := \n  if aligned_dec (multi_support obs) \n  (* Don't move (the robot's local frame is always centered on itself, i.e. its position is at the origin). *)\n  then local_straight_path origin \n  (* Go towards the weber point. *)\n  else local_straight_path (weber_calc (multi_support obs)).\n\nLocal Instance gatherW_pgm_compat : Proper (equiv ==> equiv) gatherW_pgm.\nProof using .\nintros s1 s2 Hs. unfold gatherW_pgm.\nrepeat destruct_match.\n+ reflexivity.\n+ rewrite Hs in a. now intuition.\n+ rewrite Hs in n0. now intuition.\n+ f_equiv. apply weber_unique with (multi_support s1) ; auto.\n  - rewrite Hs. now apply weber_calc_correct.\n  - now apply weber_calc_correct.\nQed.\n\nDefinition gatherW : robogram := {| pgm := gatherW_pgm |}.\n\n\nLemma multi_support_add {A : Type} `{EqDec A} s x k : ~ In x s -> k > 0 ->\n  PermutationA equiv (multi_support (add x k s)) (alls x k ++ multi_support s).\nProof using . \nintros Hin Hk. unfold multi_support. \ntransitivity (flat_map (fun '(x0, mx) => alls x0 mx) ((x, k) :: elements s)).\n+ f_equiv.\n  - intros [a ka] [b kb] [H0 H1]. cbn in H0, H1. now rewrite H0, H1.\n  - apply elements_add_out ; auto.\n+ now cbn -[elements].\nQed.\n\nLemma multi_support_countA {A : Type} `{eq_dec : EqDec A} s x :\n  countA_occ equiv eq_dec x (multi_support s) == s[x]. \nProof using .\npattern s. apply MMultisetFacts.ind.\n+ intros m m' Hm. f_equiv. \n  - apply countA_occ_compat ; autoclass. now rewrite Hm.\n  - now rewrite Hm.\n+ intros m x' n' Hin Hn IH. rewrite add_spec, multi_support_add, countA_occ_app by auto.\n  destruct_match.\n  - now rewrite <-e, countA_occ_alls_in, Nat.add_comm, IH ; autoclass.\n  - now rewrite countA_occ_alls_out, IH, Nat.add_0_l ; auto.  \n+ now reflexivity.\nQed.\n\n(* This is the main result about multi_support. *)\nLemma multi_support_config config id : \n  PermutationA equiv \n    (multi_support (obs_from_config config (config id))) \n    (config_list config).\nProof using .\ncbv -[multi_support config_list equiv make_multiset List.map]. rewrite List.map_id.\napply PermutationA_countA_occ. intros x. rewrite multi_support_countA. now apply make_multiset_spec.\nQed. \n\nCorollary multi_support_map f config id : \n  Proper (equiv ==> equiv) (projT1 f) ->\n  PermutationA equiv \n    (multi_support (obs_from_config (map_config (lift f) config) (lift f (config id))))\n    (List.map (projT1 f) (config_list config)).\nProof using .  \nintros H. destruct f as [f Pf]. cbn -[equiv config_list multi_support]. \nchange (f (config id)) with (map_config f config id).\nnow rewrite multi_support_config, config_list_map.\nQed.\n\n\nLemma lift_update_swap da config1 config2 g target :\n  @equiv location _\n    (lift (existT precondition (frame_choice_bijection (change_frame da config1 g ⁻¹))\n                               (precondition_satisfied_inv da config1 g))\n          (update config2\n           g (change_frame da config1 g) target (choose_update da config2 g target)))\n    (update (map_config (lift (existT precondition (frame_choice_bijection (change_frame da config1 g ⁻¹))\n                                      (precondition_satisfied_inv da config1 g)))\n                        config2)\n            g Similarity.id\n            (lift_path (frame_choice_bijection (change_frame da config1 g ⁻¹)) target)\n            (choose_update da config2 g target)).\nProof using .\ncbn -[inverse dist equiv]. unfold id.\nrewrite Similarity.dist_prop, Rmult_1_l.\ndestruct_match_eq Hle; destruct_match_eq Hle' ; try reflexivity ; [|];\nrewrite Rle_bool_true_iff, Rle_bool_false_iff in *;\nexfalso; revert_one not; intro Hgoal; apply Hgoal.\n- assert (Hzoom := Similarity.zoom_pos (change_frame da config1 g)).\n  eapply Rmult_le_reg_l; eauto; []. simpl.\n  rewrite <- Rmult_assoc, Rinv_r, Rmult_1_l; trivial; [].\n  foldR2. lra.\n- assert (Hzoom := Similarity.zoom_pos (change_frame da config1 g ⁻¹)).\n  eapply Rmult_le_reg_l; eauto; []. simpl.\n  rewrite <- Rmult_assoc, Rinv_l, Rmult_1_l; trivial; [].\n  foldR2. generalize (Similarity.zoom_pos (change_frame da config1 g)). lra.\nQed.\n\n(* Simplify the [round] function and express it in the global frame of reference. *)\n(* All the proofs below use this simplified version. *)\nLemma round_simplify da config : similarity_da_prop da -> \n  exists r : G -> ratio,\n  round gatherW da config == \n  fun id => if activate da id then \n              if aligned_dec (config_list config) then config id \n              else \n                let trajectory := straight_path (config id) (weber_calc (config_list config)) in\n                update config (unpack_good id) Similarity.id trajectory (r (unpack_good id))\n            else config id.\nProof using . \nintros Hsim. eexists ?[r]. intros id. unfold round. \ndestruct_match ; [|reflexivity].\ndestruct_match ; [|byz_exfalso].\ncbn -[inverse equiv lift precondition frame_choice_bijection config_list origin update].\nrewrite (lift_update_swap da config _ g). \npose (f := existT precondition\n  (change_frame da config g)\n  (precondition_satisfied da config g)). \npose (f_inv := existT (fun _ : location -> location => True)\n  ((change_frame da config g) ⁻¹)\n  (precondition_satisfied_inv da config g)).\npose (obs := obs_from_config (map_config (lift f) config) (lift f (config (Good g)))).\nchange_LHS (update \n  (map_config (lift f_inv) (map_config (lift f) config)) g Similarity.id\n  (lift_path\n    (frame_choice_bijection (change_frame da config g ⁻¹))\n    (gatherW_pgm obs))\n  (choose_update da\n    (map_config (lift f) config) g (gatherW_pgm obs))).\nassert (Proper (equiv ==> equiv) (projT1 f)) as f_compat.\n{ unfold f ; cbn -[equiv]. intros x y Hxy ; now rewrite Hxy. }\nassert (Halign_loc_glob : aligned (config_list config) <-> aligned (multi_support obs)).\n{ unfold obs. rewrite multi_support_map by auto. unfold f. cbn -[config_list]. apply aligned_similarity. }\ndestruct_match.\n(* The robots are aligned. *)\n+ unfold gatherW_pgm. destruct_match ; [|intuition].\n  cbn -[equiv lift dist mul inverse]. unfold id.\n  repeat rewrite mul_origin. destruct_match ; apply Hsim.\n(* The robots aren't aligned. *)\n+ unfold gatherW_pgm. destruct_match ; [intuition|].\n  pose (sim := change_frame da config g). foldR2. fold sim.\n  assert (Hweb : weber_calc (multi_support obs) == sim (weber_calc (config_list config))).\n  {\n    unfold obs. rewrite multi_support_map by auto. unfold f. cbn -[equiv config_list].\n    foldR2. fold sim. \n    apply weber_unique with (List.map sim (config_list config)).\n    - now rewrite <-aligned_similarity.\n    - apply weber_similarity, weber_calc_correct.\n    - apply weber_calc_correct.\n  }\n  change location_Setoid with state_Setoid. apply update_compat ; auto.\n  - intros r. cbn -[equiv]. rewrite Bijection.retraction_section. reflexivity.\n  - intros r. rewrite Hweb. \n    pose (w := weber_calc (config_list config)). fold w. \n    pose (c := config (Good g)). fold c.\n    cbn -[equiv w c opp RealVectorSpace.add mul inverse].\n    rewrite sim_mul.  \n    assert (Hcenter : (sim ⁻¹) 0%VS == c).\n    { foldR2. change_LHS (center sim). apply Hsim. }\n    assert (Hsim_cancel : forall x, (inverse sim) (sim x) == x).\n    { cbn -[equiv]. now setoid_rewrite Bijection.retraction_section. }\n    rewrite Hcenter, Hsim_cancel. simplifyR2. \n    rewrite 2 RealVectorSpace.add_assoc. f_equiv. now rewrite RealVectorSpace.add_comm.\n  - rewrite Hweb. \n    instantiate (r := fun g => choose_update da (map_config ?[sim] config) g\n      (local_straight_path (?[sim'] (weber_calc (config_list config))))).\n    cbn -[equiv config_list]. reflexivity.\nQed.\n  \n(* This is the goal (for all demons and configs). *)\nDefinition eventually_aligned config (d : demon) (r : robogram) := \n  Stream.eventually \n    (Stream.forever (Stream.instant (fun c => aligned (config_list c)))) \n    (execute r d config).\n\n(* If the robots are aligned, they stay aligned. *)\nLemma round_preserves_aligned da config : similarity_da_prop da ->\n  aligned (config_list config) -> aligned (config_list (round gatherW da config)).\nProof using . \nintros Hsim Halign. assert (round gatherW da config == config) as H.\n{ intros id. destruct (round_simplify config Hsim) as [r Hround].\n  rewrite Hround. repeat destruct_match ; auto. }\nnow rewrite H.\nQed.\n\nLemma aligned_over config (d : demon) :\n  Stream.forever (Stream.instant similarity_da_prop) d ->\n  aligned (config_list config) -> \n  Stream.forever (Stream.instant (fun c => aligned (config_list c))) (execute gatherW d config).\nProof using .\nrevert config d. \ncofix Hind. intros config d Hsim Halign. constructor.\n+ cbn -[config_list]. apply Halign.\n+ cbn -[config_list]. simple apply Hind ; [apply Hsim |]. \n  apply round_preserves_aligned ; [apply Hsim | apply Halign].\nQed.\n\n\n(* This would have been much more pleasant to do with mathcomp's tuples. *)\nLemma config_list_In_combine x x' c c' : \n  List.In (x, x') (combine (config_list c) (config_list c')) <-> \n  exists id, x == c id /\\ x' == c' id.\nProof using lt_0n.\nassert (g0 : G).\n{ change G with (fin n). apply (exist _ 0). lia. }\nsplit.\n+ intros Hin. apply (@In_nth (location * location) _ _ (c (Good g0), c' (Good g0))) in Hin.\n  destruct Hin as [i [Hi Hi']]. \n  rewrite combine_nth in Hi' by now repeat rewrite config_list_length. inv Hi'.\n  assert (i < n) as Hin.\n  { \n    eapply Nat.lt_le_trans ; [exact Hi|]. rewrite combine_length.\n    repeat rewrite config_list_length. rewrite Nat.min_id. cbn. lia. \n  }\n  pose (g := exist (fun x => x < n) i Hin).\n  change (fin n) with G in *. exists (Good g) ;\n  split ; rewrite config_list_spec, map_nth ; f_equiv ; unfold names ;\n    rewrite app_nth1, map_nth by (now rewrite map_length, Gnames_length) ;\n    f_equiv ; cbn ; change G with (fin n) ; apply nth_enum.  \n+ intros [[g|b] [Hx Hx']]. \n  - assert ((x, x') = nth (proj1_sig g) (combine (config_list c) (config_list c')) (c (Good g0), c' (Good g0))) as H.\n    { \n      rewrite combine_nth by now repeat rewrite config_list_length.\n      destruct g as [g Hg].\n      repeat rewrite config_list_spec, map_nth. rewrite Hx, Hx'. unfold names.\n      repeat rewrite app_nth1, map_nth by now rewrite map_length, Gnames_length.\n      repeat f_equal ; cbn ; change G with (fin n) ; erewrite nth_enum ; reflexivity.   \n    }\n    rewrite H. apply nth_In. rewrite combine_length. repeat rewrite config_list_length.\n    rewrite Nat.min_id. cbn. destruct g. cbn. lia.\n  - exfalso. assert (Hbyz := In_Bnames b). apply list_in_length_n0 in Hbyz. rewrite Bnames_length in Hbyz. auto.\nQed.\n\n(* This measure counts how many robots aren't on the weber point. *)\nDefinition measure_count config : R := \n  let ps := config_list config in \n  (*INR (n - countA_occ equiv R2_EqDec (weber_calc ps) ps).*)\n  list_sum (List.map (fun x => if x =?= weber_calc ps then 0%R else 1%R) ps).\n\n(* This measure counts the total distance from the robots to the weber point. *)\nDefinition measure_dist config : R :=\n  let ps := config_list config in \n  dist_sum ps (weber_calc ps).\n\n(* This measure is positive, and decreases whenever a robot moves. *)\nDefinition measure config := (measure_count config + measure_dist config)%R.\n\nLocal Instance measure_compat : Proper (equiv ==> equiv) measure.\nProof using . \nintros c c' Hc. unfold measure, measure_count, measure_dist.\nassert (Rplus_compat : Proper (equiv ==> equiv ==> equiv) Rplus).\n{ intros x x' Hx y y' Hy. now rewrite Hx, Hy. } \napply Rplus_compat.\n+ apply list_sum_compat, eqlistA_PermutationA. f_equiv ; [| now rewrite Hc].\n  intros ? ? H. repeat destruct_match ; rewrite H, Hc in * ; intuition.\n+ now rewrite Hc.\nQed.\n\nLemma measure_nonneg config : (0 <= measure config)%R.\nProof using . \nunfold measure. apply Rplus_le_le_0_compat.\n+ unfold measure_count. apply list_sum_ge_0. rewrite Forall_map, Forall_forall.\n  intros x _. destruct_match ; lra.\n+ unfold measure_dist. apply list_sum_ge_0. rewrite Forall_map, Forall_forall.\n  intros x _. apply dist_nonneg.   \nQed.\n\n(* All the magic is here : when the robots move \n * they go towards the weber point so it is preserved. \n * This still holds in an asynchronous setting.\n * The point calculated by weber_calc thus stays the same during an execution,\n * until the robots are colinear. *)\nLemma round_preserves_weber config da w :\n  similarity_da_prop da -> Weber (config_list config) w -> \n    Weber (config_list (round gatherW da config)) w.\nProof using lt_0n. \nintros Hsim Hweb. apply weber_contract with (config_list config) ; auto.\nunfold contract. rewrite Forall2_Forall, Forall_forall by now repeat rewrite config_list_length.\nintros [x x']. rewrite config_list_In_combine.\nintros [id [Hx Hx']]. destruct (round_simplify config Hsim) as [r Hround].\nrevert Hx'. rewrite Hround. \nrepeat destruct_match ; intros Hx' ; rewrite Hx, Hx' ; try apply segment_end.\nassert (w == weber_calc (config_list config)) as Hw.\n{ apply weber_unique with (config_list config) ; auto. apply weber_calc_correct. }\ncbn zeta. rewrite <-Hw. cbn -[dist straight_path]. unfold Datatypes.id.\npose (c := config id). fold c.\ndestruct_match ; rewrite segment_sym ; apply segment_straight_path.\nQed.\n\n(* If the robots don't end up colinear, then the point calculated by weber_calc doesn't change. *)\nCorollary round_preserves_weber_calc config da :\n  similarity_da_prop da -> ~aligned (config_list (round gatherW da config)) -> \n  weber_calc (config_list (round gatherW da config)) == weber_calc (config_list config). \nProof using lt_0n. \nintros Hsim HNalign.\napply weber_unique with (config_list (round gatherW da config)) ; auto.\n+ apply round_preserves_weber ; [auto | apply weber_calc_correct].\n+ apply weber_calc_correct.\nQed.\n\nLemma Forall2_le_count_weber config da : \n  similarity_da_prop da -> ~aligned (config_list (round gatherW da config)) ->\n  Forall2 Rle\n    (List.map\n      (fun x : R2 => if x =?= weber_calc (config_list (round gatherW da config)) then 0%R else 1%R) \n      (config_list (round gatherW da config)))\n    (List.map\n      (fun x : R2 => if x =?= weber_calc (config_list config) then 0%R else 1%R)\n      (config_list config)).\nProof using lt_0n. \nintros Hsim RNcol.  \nassert (Hweb := round_preserves_weber_calc config Hsim RNcol).\nrewrite Forall2_Forall, combine_map, Forall_map, Forall_forall by now repeat rewrite map_length, config_list_length.\nintros [x' x] Hin. apply config_list_In_combine in Hin. destruct Hin as [id [Hx Hx']].\nrepeat destruct_match ; try lra. rewrite Hx, Hx', Hweb in *.\nassert (H : round gatherW da config id == weber_calc (config_list config)).\n{ \n  destruct (round_simplify config Hsim) as [r Hround].\n  rewrite Hround. repeat destruct_match ; auto.\n  cbn zeta. rewrite <-e. cbn -[equiv dist mul opp RealVectorSpace.add]. \n  simplifyR2. now destruct_match.\n}\nrewrite <-H in e. intuition.\nQed.\n\nLemma Forall2_le_dist_weber config da : \n  similarity_da_prop da -> ~aligned (config_list (round gatherW da config)) ->\n  Forall2 Rle\n    (List.map \n      (dist (weber_calc (config_list (round gatherW da config))))\n      (config_list (round gatherW da config)))\n    (List.map \n      (dist (weber_calc (config_list config))) \n      (config_list config)).\nProof using lt_0n. \nintros Hsim RNcol.\nassert (Hweb := round_preserves_weber_calc config Hsim RNcol).\nrewrite Forall2_Forall, combine_map, Forall_map, Forall_forall by now repeat rewrite map_length, config_list_length.\nintros [x' x] Hin. apply config_list_In_combine in Hin. destruct Hin as [id [Hx' Hx]].\nrewrite Hx, Hx', Hweb. destruct (round_simplify config Hsim) as [r Hround].\nrewrite Hround. repeat destruct_match ; try lra.\ncbn zeta. pose (w := weber_calc (config_list config)). fold w. rewrite <-Hx.\npose (ri := r (unpack_good id)). fold ri.\ncbn -[dist RealVectorSpace.add mul opp w ri]. destruct_match.\n+ repeat rewrite norm_dist. rewrite R2_opp_dist, RealVectorSpace.add_assoc.\n  rewrite <-(mul_1 (w - x)) at 1. rewrite <-minus_morph, add_morph, norm_mul.\n  rewrite <-Rmult_1_l. apply Rmult_le_compat_r ; try apply norm_nonneg.\n  unfold Rabs. destruct_match ; generalize (ratio_bounds ri) ; lra.\n+ rewrite mul_1, (RealVectorSpace.add_comm w), RealVectorSpace.add_assoc.\n  simplifyR2. rewrite dist_same. apply dist_nonneg.\nQed.\n\n(* If a robot moves, either the measure strictly decreases or the robots become colinear. *)\nLemma round_decreases_measure config da : \n  similarity_da_prop da ->\n  moving gatherW da config <> nil -> \n    aligned (config_list (round gatherW da config)) \\/ \n    (measure (round gatherW da config) <= measure config - Rmin delta 1)%R.\nProof using lt_0n. \nintros Hsim Hmove. \ndestruct (aligned_dec (config_list (round gatherW da config))) as [Rcol | RNcol] ; [now left|right].\nassert (Hweb := round_preserves_weber_calc config Hsim RNcol).\ndestruct (not_nil_In Hmove) as [i Hi]. apply moving_spec in Hi.\ndestruct (round gatherW da config i =?= weber_calc (config_list config)) as [Hreached | HNreached].\n(* The robot that moved reached its destination. *)\n+ transitivity (measure config - 1)%R ; [|generalize (Rmin_r delta 1%R) ; lra].\n  unfold measure, Rminus. rewrite Rplus_assoc, (Rplus_comm _ (-1)%R), <-Rplus_assoc.\n  apply Rplus_le_compat.\n  - unfold measure_count. apply list_sum_le_eps ; [now apply Forall2_le_count_weber|].\n    rewrite combine_map, Exists_map. apply Exists_exists. \n    exists (round gatherW da config i, config i).\n    split ; [apply config_list_In_combine ; exists i ; intuition |].\n    repeat destruct_match ; solve [lra | rewrite Hreached in * ; intuition]. \n  - unfold measure_dist. apply list_sum_le. now apply Forall2_le_dist_weber.\n(* The robots that moved didn't reach its destination. *)\n+ transitivity (measure config - delta)%R ; [|generalize (Rmin_l delta 1%R) ; lra].\n  unfold measure, Rminus. rewrite Rplus_assoc. \n  apply Rplus_le_compat.\n  - unfold measure_count. apply list_sum_le. now apply Forall2_le_count_weber.\n  - unfold measure_dist. apply list_sum_le_eps ; [now apply Forall2_le_dist_weber|].\n    rewrite combine_map, Exists_map. apply Exists_exists. \n    exists (round gatherW da config i, config i).\n    split ; [apply config_list_In_combine ; exists i ; intuition |].\n    rewrite Hweb. destruct (round_simplify config Hsim) as [r Hround].\n    rewrite Hround. destruct_match_eq Hact ; [destruct_match_eq Halign|].\n    * exfalso. now apply RNcol, round_preserves_aligned.\n    * cbn zeta. \n      pose (w := weber_calc (config_list config)). foldR2. fold w. \n      pose (x := config i). fold x.\n      pose (ri := r (unpack_good i)). fold ri.\n      cbn -[dist RealVectorSpace.add mul opp w ri]. rewrite Rmult_1_l, mul_1.\n      destruct_match_eq Hdelta ; unfold id in * ; rewrite good_unpack_good in * ; fold x in Hdelta.\n      --rewrite Rle_bool_true_iff in Hdelta. repeat rewrite norm_dist in *.\n        rewrite R2_opp_dist, RealVectorSpace.add_assoc in Hdelta |- *. \n        rewrite add_opp, add_origin_l, norm_opp, norm_mul, Rabs_pos_eq in Hdelta by (generalize (ratio_bounds ri) ; lra).\n        rewrite <-(mul_1 (w - x)) at 1. rewrite <-minus_morph, add_morph, norm_mul.\n        rewrite Rabs_pos_eq ; [|generalize (ratio_bounds ri) ; lra].\n        rewrite Rmult_plus_distr_r, Rmult_1_l.\n        simpl location in Hdelta |- *.\n        apply Rplus_le_compat ; try lra.\n        rewrite <-Ropp_mult_distr_l. now apply Ropp_le_contravar.\n      --exfalso. apply HNreached. rewrite Hround. destruct_match ; [|intuition].\n        cbn -[config_list dist mul opp RealVectorSpace.add].\n        rewrite Rmult_1_l, good_unpack_good ; unfold id ; fold x ; fold ri ; foldR2 ; fold w.\n        destruct_match ; intuition. \n        rewrite mul_1, (RealVectorSpace.add_comm w), RealVectorSpace.add_assoc. \n        now simplifyR2.\n    * exfalso. apply Hi. rewrite Hround. destruct_match ; intuition.\nQed.\n\nLemma gathered_aligned ps x : \n  (Forall (fun y => y == x) ps) -> aligned ps.\nProof using . \nrewrite Forall_forall. intros Hgathered.\nunfold aligned. rewrite ForallTriplets_forall.\nintros a b c Ha Hb Hc.\napply Hgathered in Ha, Hb, Hc. rewrite Ha, Hb, Hc, add_opp.\napply colinear_origin_r.\nQed.\n\n(* If the robots aren't aligned yet then there exists at least one robot which, \n * if activated, will move. \n * Any robot that isn't on the weber point will do the trick. *)\nLemma one_must_move config : ~aligned (config_list config) ->\n  exists i, forall da, similarity_da_prop da -> activate da i = true ->\n                       round gatherW da config i =/= config i.\nProof using delta_g0.\nintros Nalign.\npose (w := weber_calc (config_list config)).\ncut (exists i, config i =/= w). \n{\n  intros [i Hi]. exists i. intros da Hsim Hact. \n  destruct (round_simplify config Hsim) as [r Hround]. rewrite Hround.\n  repeat destruct_match ; try intuition. clear Hact.\n  cbn -[opp mul RealVectorSpace.add dist config_list equiv complement].\n  rewrite Rmult_1_l, mul_1, good_unpack_good ; unfold id ; fold w.\n  destruct_match_eq Hdelta.\n  + intros H. \n    rewrite <-(add_origin_r (config i)) in H at 3 ; apply add_reg_l in H.\n    rewrite mul_eq0_iff in H. destruct H as [H1|H2].\n    - rewrite H1, mul_0, add_origin_r, dist_same, Rle_bool_true_iff in Hdelta. lra.\n    - rewrite R2sub_origin in H2. intuition.\n  + rewrite (RealVectorSpace.add_comm w), RealVectorSpace.add_assoc.\n    simplifyR2. intuition.\n}\nassert (List.Exists (fun x => x =/= weber_calc (config_list config)) (config_list config)) as HE.\n{ \n  apply neg_Forall_Exists_neg ; [intros ; apply equiv_dec|].\n  revert Nalign. apply contra. apply gathered_aligned.\n}\nrewrite Exists_exists in HE. destruct HE as [x [Hin Hx]].\napply (@In_InA R2 equiv _) in Hin. \nfoldR2. change location_Setoid with state_Setoid in *. rewrite config_list_InA in Hin.\ndestruct Hin as [r Hr]. exists r. now rewrite <-Hr.\nQed.\n\n(* Fairness entails progress. *)\nLemma fair_first_move (d : demon) config : \n  Fair d -> Stream.forever (Stream.instant similarity_da_prop) d ->\n  ~(aligned (config_list config)) -> FirstMove gatherW d config.\nProof using delta_g0.\nintros Hfair Hsim Nalign.\ndestruct (one_must_move config Nalign) as [id Hmove].\ndestruct Hfair as [locallyfair Hfair].\nspecialize (locallyfair id).\nrevert config Nalign Hmove.\ninduction locallyfair as [d Hnow | d] ; intros config Nalign Hmove.\n* apply MoveNow. apply Hmove in Hnow.\n  + rewrite <-(moving_spec gatherW (Stream.hd d) config id) in Hnow.\n    intros Habs. now rewrite Habs in Hnow.   \n  + apply Hsim.\n* destruct (moving gatherW (Stream.hd d) config) as [| id' mov] eqn:Hmoving.\n  + apply MoveLater ; trivial.\n    apply IHlocallyfair.\n    - apply Hfair.\n    - apply Hsim.\n    - apply no_moving_same_config in Hmoving. now rewrite Hmoving.\n    - intros da Hda Hactive. apply no_moving_same_config in Hmoving.\n      rewrite (Hmoving id).\n      apply (round_compat (reflexivity gatherW) (reflexivity da)) in Hmoving. \n      rewrite (Hmoving id).\n      now apply Hmove.\n  + apply MoveNow. rewrite Hmoving. discriminate.\nQed.\n\n(* This is the well founded relation we will perform induction on. *)\nDefinition lt_config eps c c' := \n  (0 <= measure c <= measure c' - eps)%R. \n\nLocal Instance lt_config_compat : Proper (equiv ==> equiv ==> equiv ==> iff) lt_config.\nProof using . intros e e' He c1 c1' Hc1 c2 c2' Hc2. unfold lt_config. now rewrite He, Hc1, Hc2. Qed.\n\n(* We proove this using the well-foundedness of lt on nat. *)\nLemma lt_config_wf eps : (eps > 0)%R -> well_founded (lt_config eps).\nProof using . \nintros Heps. unfold well_founded. intros c.\npose (f := fun x : R => Z.to_nat (up (x / eps))).\nremember (f (measure c)) as k. generalize dependent c. \npattern k. apply (well_founded_ind lt_wf). clear k.\nintros k IH c Hk. apply Acc_intro. intros c' Hc'. apply IH with (f (measure c')) ; auto.\nrewrite Hk ; unfold f ; unfold lt_config in Hc'.\nrewrite <-Z2Nat.inj_lt.\n+ apply Zup_lt. unfold Rdiv. rewrite <-(Rinv_r eps) by lra. \n  rewrite <-Rmult_minus_distr_r. apply Rmult_le_compat_r ; intuition.\n+ apply up_le_0_compat, Rdiv_le_0_compat ; intuition. \n+ apply up_le_0_compat, Rdiv_le_0_compat ; intuition.\n  transitivity eps ; intuition. \n  apply (Rplus_le_reg_r (- eps)). rewrite Rplus_opp_r. etransitivity ; eauto.\nQed.\n\n(* The proof is essentially a well-founded induction on [measure config].\n * Fairness ensures that the measure must decrease at some point. *)\nTheorem weber_correct config : forall d,\n  Fair d -> \n  Stream.forever (Stream.instant similarity_da_prop) d ->\n  eventually_aligned config d gatherW.\nProof using delta_g0 lt_0n.\nassert (Hdelta1 : (Rmin delta 1 > 0)%R).\n{ unfold Rmin. destruct_match ; lra. }\ninduction config as [config IH] using (well_founded_ind (lt_config_wf Hdelta1)).\nintros d Hfair Hsim.\ndestruct (aligned_dec (config_list config)) as [align | Nalign] ;\n  [now apply Stream.Now, aligned_over|].\ninduction (fair_first_move config Hfair Hsim Nalign) as [d config Hmove | d config Hmove FM IH_FM] ;\n  destruct Hsim as [Hsim_hd Hsim_tl] ; cbn in Hsim_hd ; apply Stream.Later.\n+ destruct (round_decreases_measure config Hsim_hd Hmove) as [Ralign | Rmeasure].\n  - now apply Stream.Now, aligned_over.\n  - apply IH.\n    * unfold lt_config. split ; [apply measure_nonneg | apply Rmeasure].  \n    * apply Hfair. \n    * apply Hsim_tl. \n+ apply no_moving_same_config in Hmove. cbn -[config_list].\n  apply IH_FM.\n  - intros c' Hc' d' Hfair' Hsim'. rewrite Hmove in Hc'. apply IH ; auto.\n  - apply Hfair.\n  - apply Hsim_tl.\n  - now rewrite Hmove.\nQed.  \n\nEnd Alignment.\n", "meta": {"author": "MathisBD", "repo": "pactole_stage", "sha": "4b63da0898ae4f48956408dc31f7831d3ad8930f", "save_path": "github-repos/coq/MathisBD-pactole_stage", "path": "github-repos/coq/MathisBD-pactole_stage/pactole_stage-4b63da0898ae4f48956408dc31f7831d3ad8930f/CaseStudies/Gathering/InR2/Weber/Align_flex_ssync.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6992805683902935}}
{"text": "\n(***********************************************************************)\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\n(* Finite sets library.  \n * Authors: Pierre Letouzey and Jean-Christophe Filliâtre \n * Institution: LRI, CNRS UMR 8623 - Université Paris Sud\n *              91405 Orsay, France *)\n\n(* $Id$ *)\n\n(** This module implements sets using AVL trees.\n    It follows the implementation from Ocaml's standard library. *)\n\nRequire Import Coq.Program.Program.\nRequire Import FSetInterface.\nRequire Import FSetList0.\nRequire Import ZArith.\nRequire Import Int.\nRequire Import ROmega.\nRequire Import FunInd.\n\nSet Firstorder Depth 3.\n\nSet Firstorder Solver auto.\nLtac intuition ::= intuition auto.\n\nModule Raw (I:Int)(X:OrderedType).\nImport I.\nModule II:=MoreInt(I).\nImport II.\nOpen Scope Int_scope.\nLocal Notation int := I.t.\n\nLtac omega_max := i2z_refl; romega with Z.\n\nModule MX := OrderedTypeFacts X.\n\nDefinition elt := X.t.\n\n(** * Trees *)\n\nInductive tree :=\n  | Leaf : tree\n  | Node : tree -> X.t -> tree -> int -> tree.\n\nNotation t := tree.\n\n(** The fourth field of [Node] is the height of the tree *)\n\n(** A tactic to repeat [inversion_clear] on all hyps of the \n    form [(f (Node _ _ _ _))] *)\nLtac inv f :=\n  match goal with \n     | H:f Leaf |- _ => inversion_clear H; inv f\n     | H:f _ Leaf |- _ => inversion_clear H; inv f\n     | H:f (Node _ _ _ _) |- _ => inversion_clear H; inv f\n     | H:f _ (Node _ _ _ _) |- _ => inversion_clear H; inv f\n     | _ => idtac\n  end.\n\n(** Same, but with a backup of the original hypothesis. *)\n\nLtac safe_inv f := match goal with \n  | H:f (Node _ _ _ _) |- _ => \n        generalize H; inversion_clear H; safe_inv f\n  | _ => intros \n end.\n\n(** * Occurrence in a tree *)\n\nInductive In (x : elt) : tree -> Prop :=\n  | IsRoot :\n      forall (l r : tree) (h : int) (y : elt),\n      X.eq x y -> In x (Node l y r h)\n  | InLeft :\n      forall (l r : tree) (h : int) (y : elt),\n      In x l -> In x (Node l y r h)\n  | InRight :\n      forall (l r : tree) (h : int) (y : elt),\n      In x r -> In x (Node l y r h).\n\nHint Constructors In.\n\nLtac intuition_in := repeat progress (intuition; inv In).\n\n(** [In] is compatible with [X.eq] *)\n\nLemma In_1 :\n forall s x y, X.eq x y -> In x s -> In y s.\nProof.\n induction s; simpl; intuition_in; eauto.\nQed.\nHint Immediate In_1.\n\n(** * Binary search trees *)\n\n(** [lt_tree x s]: all elements in [s] are smaller than [x] \n   (resp. greater for [gt_tree]) *)\n\nDefinition lt_tree (x : elt) (s : tree) := \n forall y:elt, In y s -> X.lt y x.\nDefinition gt_tree (x : elt) (s : tree) := \n forall y:elt, In y s -> X.lt x y.\n\nHint Unfold lt_tree gt_tree.\n\nLtac order := match goal with \n | H: lt_tree ?x ?s, H1: In ?y ?s |- _ => generalize (H _ H1); clear H; order\n | H: gt_tree ?x ?s, H1: In ?y ?s |- _ => generalize (H _ H1); clear H; order\n | _ => MX.order\nend.\n\n(** Results about [lt_tree] and [gt_tree] *)\n\nLemma lt_leaf : forall x : elt, lt_tree x Leaf.\nProof.\n unfold lt_tree in |- *; intros; inversion H.\nQed.\n\nLemma gt_leaf : forall x : elt, gt_tree x Leaf.\nProof.\n  unfold gt_tree in |- *; intros; inversion H.\nQed.\n\nLemma lt_tree_node :\n forall (x y : elt) (l r : tree) (h : int),\n lt_tree x l -> lt_tree x r -> X.lt y x -> lt_tree x (Node l y r h).\nProof.\n unfold lt_tree in *; intuition_in; order.\nQed.\n\nLemma gt_tree_node :\n forall (x y : elt) (l r : tree) (h : int),\n gt_tree x l -> gt_tree x r -> X.lt x y -> gt_tree x (Node l y r h).\nProof.\n unfold gt_tree in *; intuition_in; order.\nQed.\n\nHint Resolve lt_leaf gt_leaf lt_tree_node gt_tree_node.\n\nLemma lt_tree_not_in :\n forall (x : elt) (t : tree), lt_tree x t -> ~ In x t.\nProof.\n intros; intro; order.\nQed.\n\nLemma lt_tree_trans :\n forall x y, X.lt x y -> forall t, lt_tree x t -> lt_tree y t.\nProof.\n firstorder eauto.\nQed.\n\nLemma gt_tree_not_in :\n forall (x : elt) (t : tree), gt_tree x t -> ~ In x t.\nProof.\n intros; intro; order.\nQed.\n\nLemma gt_tree_trans :\n forall x y, X.lt y x -> forall t, gt_tree x t -> gt_tree y t.\nProof.\n firstorder eauto.\nQed.\n\nHint Resolve lt_tree_not_in lt_tree_trans gt_tree_not_in gt_tree_trans.\n\n(** [bst t] : [t] is a binary search tree *)\n\nInductive bst : tree -> Prop :=\n  | BSLeaf : bst Leaf\n  | BSNode :\n      forall (x : elt) (l r : tree) (h : int),\n      bst l -> bst r -> lt_tree x l -> gt_tree x r -> bst (Node l x r h).\n\nHint Constructors bst.\n\n(** * AVL trees *)\n\n(** [avl s] : [s] is a properly balanced AVL tree,\n    i.e. for any node the heights of the two children\n    differ by at most 2 *)\n\nDefinition height (s : tree) : int :=\n  match s with\n  | Leaf => 0\n  | Node _ _ _ h => h\n  end.\n\nInductive avl : tree -> Prop :=\n  | RBLeaf : avl Leaf\n  | RBNode :\n      forall (x : elt) (l r : tree) (h : int),\n      avl l ->\n      avl r ->\n      -(2) <= height l - height r <= 2 ->\n      h = max (height l) (height r) + 1 -> \n      avl (Node l x r h).\n\nHint Constructors avl.\n\n(** Results about [avl] *)\n\nLemma avl_node :\n forall (x : elt) (l r : tree),\n avl l ->\n avl r ->\n -(2) <= height l - height r <= 2 ->\n avl (Node l x r (max (height l) (height r) + 1)).\nProof.\n  intros; auto.\nQed.\nHint Resolve avl_node.\n\n(** The tactics *)\n\nLemma height_non_negative : forall s : tree, avl s -> height s >= 0.\nProof.\n induction s; simpl; intros; auto with zarith.\n inv avl; intuition; omega_max.\nQed.\nImplicit Arguments height_non_negative. \n\n(** When [H:avl r], typing [avl_nn H] or [avl_nn r] adds [height r>=0] *)\n\nLtac avl_nn_hyp H := \n     let nz := fresh \"nz\" in assert (nz := height_non_negative H).\n\nLtac avl_nn h := \n  let t := type of h in \n  match type of t with \n   | Prop => avl_nn_hyp h\n   | _ => match goal with H : avl h |- _ => avl_nn_hyp H end\n  end.\n\n(* Repeat the previous tactic. \n   Drawback: need to clear the [avl _] hyps ... Thank you Ltac *)\n\nLtac avl_nns :=\n  match goal with \n     | H:avl _ |- _ => avl_nn_hyp H; clear H; avl_nns\n     | _ => idtac\n  end.\n\n(** * Some shortcuts. *)\n\nDefinition Equal s s' := forall a : elt, In a s <-> In a s'.\nDefinition Subset s s' := forall a : elt, In a s -> In a s'.\nDefinition Empty s := forall a : elt, ~ In a s.\nDefinition For_all (P : elt -> Prop) s := forall x, In x s -> P x.\nDefinition Exists (P : elt -> Prop) s := exists x, In x s /\\ P x.\n\n(** * Empty set *)\n\nDefinition empty := Leaf.\n\nLemma empty_bst : bst empty.\nProof.\n auto.\nQed.\n\nLemma empty_avl : avl empty.\nProof. \n auto.\nQed.\n\nLemma empty_1 : Empty empty.\nProof.\n intro; intro.\n inversion H.\nQed.\n\n(** * Emptyness test *)\n\nDefinition is_empty (s:t) := match s with Leaf => true | _ => false end.\n\nLemma is_empty_1 : forall s, Empty s -> is_empty s = true. \nProof.\n destruct s as [|r x l h]; simpl; auto.\n intro H; elim (H x); auto.\nQed.\n\nLemma is_empty_2 : forall s, is_empty s = true -> Empty s.\nProof. \n destruct s; simpl; intros; try discriminate; red; auto.\nQed.\n\n(** * Appartness *)\n\n(** The [mem] function is deciding appartness. It exploits the [bst] property\n    to achieve logarithmic complexity. *)\n\nFunction mem (x:elt)(s:t) { struct s } : bool := \n   match s with \n     |  Leaf => false \n     |  Node l y r _ => match X.compare x y with \n             | LT _ => mem x l \n             | EQ _ => true\n             | GT _ => mem x r\n         end\n   end.\n\nLemma mem_1 : forall s x, bst s -> In x s -> mem x s = true.\nProof. \n intros s x.\n functional induction (mem x s); inversion_clear 1; auto.\n inversion_clear 1.\n inversion_clear 1; auto; absurd (X.lt x y); eauto.\n inversion_clear 1; auto; absurd (X.lt y x); eauto.\nQed.\n\nLemma mem_2 : forall s x, mem x s = true -> In x s. \nProof. \n intros s x. \n functional induction (mem x s); auto; intros; try discriminate.\nQed.\n\n(** * Singleton set *)\n\nDefinition singleton (x : elt) := Node Leaf x Leaf 1.\n\nLemma singleton_bst : forall x : elt, bst (singleton x).\nProof.\n unfold singleton;  auto.\nQed.\n\nLemma singleton_avl : forall x : elt, avl (singleton x).\nProof.\n unfold singleton; intro.\n constructor; auto; try red; simpl; omega_max.\nQed.\n\nLemma singleton_1 : forall x y, In y (singleton x) -> X.eq x y. \nProof. \n unfold singleton; inversion_clear 1; auto; inversion_clear H0.\nQed.\n\nLemma singleton_2 : forall x y, X.eq x y -> In y (singleton x). \nProof. \n unfold singleton; auto.\nQed.\n\n(** * Helper functions *)\n\n(** [create l x r] creates a node, assuming [l] and [r]\n    to be balanced and [|height l - height r| <= 2]. *)\n\nDefinition create l x r := \n   Node l x r (max (height l) (height r) + 1).\n\nLemma create_bst : \n forall l x r, bst l -> bst r -> lt_tree x l -> gt_tree x r -> \n bst (create l x r).\nProof.\n unfold create; auto.\nQed.\nHint Resolve create_bst.\n\nLemma create_avl : \n forall l x r, avl l -> avl r ->  -(2) <= height l - height r <= 2 -> \n avl (create l x r).\nProof.\n unfold create; auto.\nQed.\n\nLemma create_height : \n forall l x r, avl l -> avl r ->  -(2) <= height l - height r <= 2 -> \n height (create l x r) = max (height l) (height r) + 1.\nProof.\n unfold create; intros; auto.\nQed.\n\nLemma create_in : \n forall l x r y,  In y (create l x r) <-> X.eq y x \\/ In y l \\/ In y r.\nProof.\n unfold create; split; [ inversion_clear 1 | ]; intuition.\nQed.\n\n(** trick for emulating [assert false] in Coq *)\n\nDefinition assert_false := Leaf.\n\n(** [bal l x r] acts as [create], but performs one step of\n    rebalancing if necessary, i.e. assumes [|height l - height r| <= 3]. *)\n\nDefinition bal l x r := \n  let hl := height l in \n  let hr := height r in\n  if gt_le_dec hl (hr+2) then \n    match l with \n     | Leaf => assert_false\n     | Node ll lx lr _ => \n       if ge_lt_dec (height ll) (height lr) then \n         create ll lx (create lr x r)\n       else \n         match lr with \n          | Leaf => assert_false \n          | Node lrl lrx lrr _ => \n              create (create ll lx lrl) lrx (create lrr x r)\n         end\n    end\n  else \n    if gt_le_dec hr (hl+2) then \n      match r with\n       | Leaf => assert_false\n       | Node rl rx rr _ =>\n         if ge_lt_dec (height rr) (height rl) then \n            create (create l x rl) rx rr\n         else \n           match rl with\n            | Leaf => assert_false\n            | Node rll rlx rlr _ => \n                create (create l x rll) rlx (create rlr rx rr) \n           end\n      end\n    else \n      create l x r. \n\nLtac bal_tac := \n intros l x r;\n unfold bal; \n destruct (gt_le_dec (height l) (height r + 2)); \n   [ destruct l as [ |ll lx lr lh]; \n     [ | destruct (ge_lt_dec (height ll) (height lr)); \n          [ | destruct lr ] ]\n   | destruct (gt_le_dec (height r) (height l + 2)); \n     [ destruct r as [ |rl rx rr rh];\n          [ | destruct (ge_lt_dec (height rr) (height rl)); \n               [ | destruct rl ] ]\n     | ] ]; intros.\n\nLemma bal_bst : forall l x r, bst l -> bst r -> \n lt_tree x l -> gt_tree x r -> bst (bal l x r).\nProof.\n (* intros l x r; functional induction bal l x r. MARCHE PAS !*) \n bal_tac; \n inv bst; repeat apply create_bst; auto; unfold create; \n apply lt_tree_node || apply gt_tree_node; auto; \n eapply lt_tree_trans || eapply gt_tree_trans || eauto; eauto.\nQed.\n\nLemma bal_avl : forall l x r, avl l -> avl r -> \n -(3) <= height l - height r <= 3 -> avl (bal l x r).\nProof.\n bal_tac; inv avl; repeat apply create_avl; simpl in *; auto; omega_max.\nQed.\n\nLemma bal_height_1 : forall l x r, avl l -> avl r -> \n -(3) <= height l - height r <= 3 ->\n 0 <= height (bal l x r) - max (height l) (height r) <= 1.\nProof.\n bal_tac; inv avl; avl_nns; simpl in *; omega_max.\nQed.\n\nLemma bal_height_2 : \n forall l x r, avl l -> avl r -> -(2) <= height l - height r <= 2 -> \n height (bal l x r) == max (height l) (height r) +1.\nProof.\n bal_tac; inv avl; simpl in *; omega_max.\nQed.\n\nLemma bal_in : forall l x r y, avl l -> avl r -> \n (In y (bal l x r) <-> X.eq y x \\/ In y l \\/ In y r).\nProof.\n bal_tac; \n solve [repeat rewrite create_in; intuition_in\n       |inv avl; avl_nns; simpl in *; omega_max ].\nQed.\n\nLtac omega_bal := match goal with \n  | H:avl ?l, H':avl ?r |- context [ bal ?l ?x ?r ] => \n     generalize (bal_height_1 l x r H H') (bal_height_2 l x r H H'); \n     omega_max\n  end. \n\n(** * Insertion *)\n\nFunction add (x:elt)(s:t) { struct s } : t := match s with \n   | Leaf => Node Leaf x Leaf 1\n   | Node l y r h => \n      match X.compare x y with\n         | LT _ => bal (add x l) y r\n         | EQ _ => Node l y r h\n         | GT _ => bal l y (add x r)\n      end\n  end.\n\nLemma add_avl_1 :  forall s x, avl s -> \n avl (add x s) /\\ 0 <= height (add x s) - height s <= 1.\nProof. \n intros s x; functional induction (add x s); subst;intros; inv avl; simpl in *.\n intuition; try constructor; simpl; auto; try omega_max.\n (* LT *)\n destruct IHt; auto.\n split.\n apply bal_avl; auto; omega_max.\n omega_bal.\n (* EQ *)\n intuition; omega_max.\n (* GT *)\n destruct IHt; auto.\n split.\n apply bal_avl; auto; omega_max.\n omega_bal.\nQed.\n\nLemma add_avl : forall s x, avl s -> avl (add x s).\nProof.\n intros; generalize (add_avl_1 s x H); intuition.\nQed.\nHint Resolve add_avl.\n\nLemma add_in : forall s x y, avl s -> \n (In y (add x s) <-> X.eq y x \\/ In y s).\nProof.\n intros s x; functional induction (add x s); auto; intros.\n intuition_in.\n (* LT *)\n inv avl.\n rewrite bal_in; auto.\n rewrite (IHt y0 H0); intuition_in.\n (* EQ *)  \n inv avl.\n intuition.\n eapply In_1; eauto.\n (* GT *)\n inv avl.\n rewrite bal_in; auto.\n rewrite (IHt y0 H1); intuition_in.\nQed.\n\nLemma add_bst : forall s x, bst s -> avl s -> bst (add x s).\nProof. \n intros s x; functional induction (add x s); auto; intros.\n inv bst; inv avl; apply bal_bst; auto.\n (* lt_tree -> lt_tree (add ...) *)\n red; red in H4.\n intros.\n rewrite (add_in l x y0 H) in H0.\n intuition.\n eauto.\n inv bst; inv avl; apply bal_bst; auto.\n (* gt_tree -> gt_tree (add ...) *)\n red; red in H4.\n intros.\n rewrite (add_in r x y0 H5) in H0.\n intuition.\n apply MX.lt_eq with x; auto.\nQed.\n\n(** * Join\n\n    Same as [bal] but does not assume anything regarding heights\n    of [l] and [r].\n*)\n\nFixpoint join (l:t) : elt -> t -> t :=\n  match l with\n    | Leaf => add\n    | Node ll lx lr lh => fun x => \n       fix join_aux (r:t) : t := match r with \n          | Leaf =>  add x l\n          | Node rl rx rr rh =>  \n               if gt_le_dec lh (rh+2) then bal ll lx (join lr x r)\n               else if gt_le_dec rh (lh+2) then bal (join_aux rl) rx rr \n               else create l x r\n          end\n  end.\n\nLtac join_tac := \n let l := fresh \"l\" in\n intro l; induction l as [| ll _ lx lr Hlr lh]; \n   [ | intros x r; induction r as [| rl Hrl rx rr _ rh]; unfold join;\n     [ | destruct (gt_le_dec lh (rh+2)); \n       [ match goal with |- context b [ bal ?a ?b ?c] => \n           replace (bal a b c) \n           with (bal ll lx (join lr x (Node rl rx rr rh))); [ | auto] \n         end \n       | destruct (gt_le_dec rh (lh+2)); \n         [ match goal with |- context b [ bal ?a ?b ?c] => \n             replace (bal a b c) \n             with (bal (join (Node ll lx lr lh) x rl) rx rr); [ | auto] \n           end\n         | ] ] ] ]; intros.\n\nLemma join_avl_1 : forall l x r, avl l -> avl r -> avl (join l x r) /\\\n 0<= height (join l x r) - max (height l) (height r) <= 1.\nProof. \n (* intros l x r; functional induction join l x r. AUTRE PROBLEME! *)\n join_tac.\n\n split; simpl; auto. \n destruct (add_avl_1 r x H0).\n avl_nns; omega_max.\n split; auto.\n set (l:=Node ll lx lr lh) in *.\n destruct (add_avl_1 l x H).\n simpl (height Leaf).\n avl_nns; omega_max.\n\n inversion_clear H.\n assert (height (Node rl rx rr rh) = rh); auto.\n set (r := Node rl rx rr rh) in *; clearbody r.\n destruct (Hlr x r H2 H0); clear Hrl Hlr.\n set (j := join lr x r) in *; clearbody j.\n simpl.\n assert (-(3) <= height ll - height j <= 3) by omega_max.\n split.\n apply bal_avl; auto.\n omega_bal.\n\n inversion_clear H0.\n assert (height (Node ll lx lr lh) = lh); auto.\n set (l' := Node ll lx lr lh) in *; clearbody l'.\n destruct (Hrl H H1); clear Hrl Hlr.\n set (j := join l' x rl) in *; clearbody j.\n simpl.\n assert (-(3) <= height j - height rr <= 3) by omega_max.\n split.\n apply bal_avl; auto.\n omega_bal.\n\n clear Hrl Hlr.\n assert (height (Node ll lx lr lh) = lh); auto.\n assert (height (Node rl rx rr rh) = rh); auto.\n set (l' := Node ll lx lr lh) in *; clearbody l'.\n set (r := Node rl rx rr rh) in *; clearbody r.\n assert (-(2) <= height l' - height r <= 2) by omega_max.\n split.\n apply create_avl; auto.\n rewrite create_height; auto; omega_max.\nQed.\n\nLemma join_avl : forall l x r, avl l -> avl r -> avl (join l x r).\nProof.\n intros; generalize (join_avl_1 l x r H H0); intuition.\nQed.\nHint Resolve join_avl.\n\nLemma join_in : forall l x r y, avl l -> avl r -> \n     (In y (join l x r) <-> X.eq y x \\/ In y l \\/ In y r).\nProof.\n join_tac.\n simpl.\n rewrite add_in; intuition_in.\n\n rewrite add_in; intuition_in.\n\n inv avl.\n rewrite bal_in; auto.\n rewrite Hlr; clear Hlr Hrl; intuition_in.\n\n inv avl.\n rewrite bal_in; auto.\n rewrite Hrl; clear Hlr Hrl; intuition_in.\n\n apply create_in.\nQed.\n\nLemma join_bst : forall l x r, bst l -> avl l -> bst r -> avl r -> \n lt_tree x l -> gt_tree x r -> bst (join l x r).\nProof.\n join_tac.\n apply add_bst; auto.\n apply add_bst; auto.\n\n inv bst; safe_inv avl.\n apply bal_bst; auto.\n clear Hrl Hlr H13 H14 H16 H17; intro; intros.\n set (r:=Node rl rx rr rh) in *; clearbody r.\n rewrite (join_in lr x r y) in H13; auto.\n intuition.\n apply MX.lt_eq with x; eauto.\n eauto.\n\n inv bst; safe_inv avl.\n apply bal_bst; auto.\n clear Hrl Hlr H13 H14 H16 H17; intro; intros.\n set (l':=Node ll lx lr lh) in *; clearbody l'.\n rewrite (join_in l' x rl y) in H13; auto.\n intuition.\n apply MX.eq_lt with x; eauto.\n eauto.\n\n apply create_bst; auto.\nQed.\n\n(** * Extraction of minimum element\n\n  morally, [remove_min] is to be applied to a non-empty tree \n  [t = Node l x r h]. Since we can't deal here with [assert false] \n  for [t=Leaf], we pre-unpack [t] (and forget about [h]). \n*)\n \nFunction remove_min (l:t)(x:elt)(r:t) { struct l } : t*elt := \n  match l with \n    | Leaf => (r,x)\n    | Node ll lx lr lh => let (l',m) := (remove_min ll lx lr : t*elt) in (bal l' x r, m)\n  end.\n\nLemma remove_min_avl_1 : forall l x r h, avl (Node l x r h) -> \n avl (fst (remove_min l x r)) /\\ \n 0 <= height (Node l x r h) - height (fst (remove_min l x r)) <= 1.\nProof.\n intros l x r; functional induction (remove_min l x r); subst;simpl in *; intros.\n inv avl; simpl in *; split; auto.\n avl_nns; omega_max.\n (* l = Node *)\n inversion_clear H.\n rewrite e0 in IHp;simpl in IHp;destruct (IHp lh); auto.\n split; simpl in *. \n apply bal_avl; auto; omega_max.\n omega_bal.\nQed.\n\nLemma remove_min_avl : forall l x r h, avl (Node l x r h) -> \n    avl (fst (remove_min l x r)). \nProof.\n intros; generalize (remove_min_avl_1 l x r h H); intuition.\nQed.\n\nLemma remove_min_in : forall l x r h y, avl (Node l x r h) -> \n (In y (Node l x r h) <-> \n  X.eq y (snd (remove_min l x r)) \\/ In y (fst (remove_min l x r))).\nProof.\n intros l x r; functional induction (remove_min l x r); simpl in *; intros.\n intuition_in.\n (* l = Node *)\n inversion_clear H.\n generalize (remove_min_avl ll lx lr lh H0).\n rewrite e0; simpl; intros.\n rewrite bal_in; auto.\n rewrite e0 in IHp;generalize (IHp lh y H0).\n intuition.\n inversion_clear H7; intuition.\nQed.\n\nLemma remove_min_bst : forall l x r h, \n bst (Node l x r h) -> avl (Node l x r h) -> bst (fst (remove_min l x r)).\nProof.\n intros l x r; functional induction (remove_min l x r); subst;simpl in *; intros.\n inv bst; auto.\n inversion_clear H; inversion_clear H0.\n rewrite_all e0;simpl in *.\n apply bal_bst; auto.\n firstorder.\n intro; intros.\n generalize (remove_min_in ll lx lr lh y H).\n rewrite e0; simpl.\n destruct 1.\n apply H3; intuition.\nQed.\n\nLemma remove_min_gt_tree : forall l x r h, \n bst (Node l x r h) -> avl (Node l x r h) -> \n gt_tree (snd (remove_min l x r)) (fst (remove_min l x r)).\nProof.\n intros l x r; functional induction (remove_min l x r); subst;simpl in *; intros.\n inv bst; auto.\n inversion_clear H; inversion_clear H0.\n intro; intro.\n generalize (IHp lh H1 H); clear H6 H7 IHp.\n generalize (remove_min_avl ll lx lr lh H).\n generalize (remove_min_in ll lx lr lh m H).\n rewrite e0; simpl; intros.\n rewrite (bal_in l' x r y H7 H5) in H0.\n destruct H6.\n firstorder.\n apply MX.lt_eq with x; auto.\n apply X.lt_trans with x; auto.\nQed.\n\n(** * Merging two trees\n\n  [merge t1 t2] builds the union of [t1] and [t2] assuming all elements\n  of [t1] to be smaller than all elements of [t2], and\n  [|height t1 - height t2| <= 2].\n*)\n\nFunction merge (s1 s2 :t) : t:=  match s1,s2 with \n  | Leaf, _ => s2 \n  | _, Leaf => s1\n  | _, Node l2 x2 r2 h2 => \n        let (s2',m) := remove_min l2 x2 r2 in bal s1 m s2'\nend.\n\nLemma merge_avl_1 : forall s1 s2, avl s1 -> avl s2 -> \n -(2) <= height s1 - height s2 <= 2 -> \n avl (merge s1 s2) /\\ \n 0<= height (merge s1 s2) - max (height s1) (height s2) <=1.\nProof.\n intros s1 s2; functional induction (merge s1 s2); subst;simpl in *; intros.\n split; auto; avl_nns; omega_max.\n split; auto; avl_nns; simpl in *; omega_max.\n destruct s1;try contradiction;clear y.\n generalize (remove_min_avl_1 l2 x2 r2 h2 H0).\n rewrite e1; simpl; destruct 1.\n split.\n apply bal_avl; auto.\n simpl; omega_max.\n omega_bal.\nQed.\n\nLemma merge_avl : forall s1 s2, avl s1 -> avl s2 -> \n  -(2) <= height s1 - height s2 <= 2 -> avl (merge s1 s2).\nProof. \n intros; generalize (merge_avl_1 s1 s2 H H0 H1); intuition.\nQed.\n\nLemma merge_in : forall s1 s2 y, bst s1 -> avl s1 -> bst s2 -> avl s2 -> \n (In y (merge s1 s2) <-> In y s1 \\/ In y s2).\nProof. \n intros s1 s2; functional induction (merge s1 s2); subst; simpl in *; intros.\n intuition_in.\n intuition_in.\n destruct s1;try contradiction;clear y.\n replace s2' with (fst (remove_min l2 x2 r2)); [|rewrite e1; auto].\n rewrite bal_in; auto.\n generalize (remove_min_in l2 x2 r2 h2 y0); rewrite e1; simpl; intro.\n rewrite H3 ; intuition.\n generalize (remove_min_avl l2 x2 r2 h2); rewrite e1; simpl; auto.\nQed.\n\nLemma merge_bst : forall s1 s2, bst s1 -> avl s1 -> bst s2 -> avl s2 -> \n (forall y1 y2 : elt, In y1 s1 -> In y2 s2 -> X.lt y1 y2) -> \n bst (merge s1 s2). \nProof.\n intros s1 s2; functional induction (merge s1 s2); subst;simpl in *; intros; auto.\n destruct s1;try contradiction;clear y.\n apply bal_bst; auto.\n generalize (remove_min_bst l2 x2 r2 h2); rewrite e1; simpl in *; auto.\n intro; intro.\n apply H3; auto.\n generalize (remove_min_in l2 x2 r2 h2 m); rewrite e1; simpl; intuition.\n generalize (remove_min_gt_tree l2 x2 r2 h2); rewrite e1; simpl; auto.\nQed. \n\n(** * Deletion *)\n\nFunction remove (x:elt)(s:tree) { struct s } : t := match s with \n  | Leaf => Leaf\n  | Node l y r h =>\n      match X.compare x y with\n         | LT _ => bal (remove x l) y r\n         | EQ _ => merge l r\n         | GT _ => bal l  y (remove x r)\n      end\n   end.\n\nLemma remove_avl_1 : forall s x, avl s -> \n avl (remove x s) /\\ 0 <= height s - height (remove x s) <= 1.\nProof.\n intros s x; functional induction (remove x s); subst;simpl; intros.\n intuition; omega_max.\n (* LT *)\n inv avl.\n destruct (IHt H0).\n split. \n apply bal_avl; auto.\n omega_max.\n omega_bal.\n (* EQ *)\n inv avl. \n generalize (merge_avl_1 l r H0 H1 H2).\n intuition omega_max.\n (* GT *)\n inv avl.\n destruct (IHt H1).\n split. \n apply bal_avl; auto.\n omega_max.\n omega_bal.\nQed.\n\nLemma remove_avl : forall s x, avl s -> avl (remove x s).\nProof. \n intros; generalize (remove_avl_1 s x H); intuition.\nQed.\nHint Resolve remove_avl.\n\nLemma remove_in : forall s x y, bst s -> avl s -> \n (In y (remove x s) <-> ~ X.eq y x /\\ In y s).\nProof.\n intros s x; functional induction (remove x s); subst;simpl; intros.\n intuition_in.\n (* LT *)\n inv avl; inv bst; clear e0.\n rewrite bal_in; auto.\n generalize (IHt y0 H0); intuition; [ order | order | intuition_in ].\n (* EQ *)\n inv avl; inv bst; clear e0.\n rewrite merge_in; intuition; [ order | order | intuition_in ].\n elim H9; eauto.\n (* GT *)\n inv avl; inv bst; clear e0.\n rewrite bal_in; auto.\n generalize (IHt y0 H5); intuition; [ order | order | intuition_in ].\nQed.\n\nLemma remove_bst : forall s x, bst s -> avl s -> bst (remove x s).\nProof. \n intros s x; functional induction (remove x s); simpl; intros.\n auto.\n (* LT *)\n inv avl; inv bst.\n apply bal_bst; auto.\n intro; intro.\n rewrite (remove_in l x y0) in H; auto.\n destruct H; eauto.\n (* EQ *)\n inv avl; inv bst.\n apply merge_bst; eauto.\n (* GT *) \n inv avl; inv bst.\n apply bal_bst; auto.\n intro; intro.\n rewrite (remove_in r x y0) in H; auto.\n destruct H; eauto.\nQed.\n\n (** * Minimum element *)\n\nFunction min_elt (s:t) : option elt := match s with \n   | Leaf => None\n   | Node Leaf y _  _ => Some y\n   | Node l _ _ _ => min_elt l\nend.\n\nLemma min_elt_1 : forall s x, min_elt s = Some x -> In x s. \nProof. \n intro s; functional induction (min_elt s); subst; simpl.\n inversion 1.\n inversion 1; auto.\n intros.\n destruct l; auto.\nQed.\n\nLemma min_elt_2 : forall s x y, bst s -> \n min_elt s = Some x -> In y s -> ~ X.lt y x. \nProof.\n intro s; functional induction (min_elt s); subst;simpl.\n inversion_clear 2.\n inversion_clear 1.\n inversion 1; subst.\n inversion_clear 1; auto.\n inversion_clear H5.\n destruct l;try contradiction.\n inversion_clear 1.\n simpl.\n destruct l1.\n inversion 1; subst.\n assert (X.lt x _x) by (apply H2; auto).\n inversion_clear 1; auto; order.\n assert (X.lt t _x) by auto.\n inversion_clear 2; auto; \n   (assert (~ X.lt t x) by auto); order.\nQed.\n\nLemma min_elt_3 : forall s, min_elt s = None -> Empty s.\nProof.\n intro s; functional induction (min_elt s); subst;simpl.\n red; auto.\n inversion 1.\n destruct l;try contradiction. \n clear y;intro H0.\n destruct (IHo H0 t);  auto.\nQed.\n\n(** * Maximum element *)\n\nFunction max_elt (s:t) : option elt := match s with \n   | Leaf => None\n   | Node _ y Leaf  _ => Some y\n   | Node _ _ r _ => max_elt r\nend.\n\nLemma max_elt_1 : forall s x, max_elt s = Some x -> In x s. \nProof. \n intro s; functional induction (max_elt s); subst;simpl.\n inversion 1.\n inversion 1; auto.\n destruct r;try contradiction; auto.\nQed.\n\nLemma max_elt_2 : forall s x y, bst s -> \n max_elt s = Some x -> In y s -> ~ X.lt x y. \nProof.\n intro s; functional induction (max_elt s); subst;simpl.\n inversion_clear 2.\n inversion_clear 1.\n inversion 1; subst.\n inversion_clear 1; auto.\n inversion_clear H5.\n destruct r;try contradiction.\n inversion_clear 1.\n(*  inversion 1; subst. *)\n(*  assert (X.lt y x) by (apply H4; auto). *)\n(*  inversion_clear 1; auto; order. *)\n assert (X.lt _x0 t) by auto.\n inversion_clear 2; auto; \n  (assert (~ X.lt x t) by auto); order.\nQed.\n\nLemma max_elt_3 : forall s, max_elt s = None -> Empty s.\nProof.\n intro s; functional induction (max_elt s); subst;simpl.\n red; auto.\n inversion 1.\n destruct r;try contradiction.\n intros H0; destruct (IHo H0 t); auto.\nQed.\n\n(** * Any element *)\n\nDefinition choose := min_elt.\n\nLemma choose_1 : forall s x, choose s = Some x -> In x s.\nProof. \n exact min_elt_1.\nQed.\n\nLemma choose_2 : forall s, choose s = None -> Empty s.\nProof. \n exact min_elt_3.\nQed.\n\nLemma choose_3 : forall s s', bst s -> avl s -> bst s' -> avl s' -> \n forall x x', choose s = Some x -> choose s' = Some x' -> \n  Equal s s' -> X.eq x x'.\nProof.\n unfold choose, Equal; intros s s' Hb Ha Hb' Ha' x x' Hx Hx' H.\n assert (~X.lt x x').\n  apply min_elt_2 with s'; auto.\n  rewrite <-H; auto using min_elt_1.\n assert (~X.lt x' x).\n  apply min_elt_2 with s; auto.\n  rewrite H; auto using min_elt_1.\n destruct (X.compare x x'); intuition.\nQed.\n\n(** * Concatenation\n\n    Same as [merge] but does not assume anything about heights.\n*)\n\nFunction concat (s1 s2 : t) : t  := \n   match s1, s2 with \n      | Leaf, _ => s2 \n      | _, Leaf => s1\n      | _, Node l2 x2 r2 h2 => \n            let (s2',m) := remove_min l2 x2 r2 in \n            join s1 m s2'\n   end.\n\nLemma concat_avl : forall s1 s2, avl s1 -> avl s2 -> avl (concat s1 s2).\nProof.\n intros s1 s2; functional induction (concat s1 s2); subst;auto.\n destruct s1;try contradiction;clear y.\n intros; apply join_avl; auto.\n generalize (remove_min_avl l2 x2 r2 h2 H0); rewrite e1; simpl; auto.\nQed.\n \nLemma concat_bst :   forall s1 s2, bst s1 -> avl s1 -> bst s2 -> avl s2 -> \n (forall y1 y2 : elt, In y1 s1 -> In y2 s2 -> X.lt y1 y2) -> \n bst (concat s1 s2).\nProof. \n intros s1 s2; functional induction (concat s1 s2); subst ;auto.\n destruct s1;try contradiction;clear y. \n intros;  apply join_bst; auto.\n generalize (remove_min_bst l2 x2 r2 h2 H1 H2); rewrite e1; simpl; auto.\n generalize (remove_min_avl l2 x2 r2 h2 H2); rewrite e1; simpl; auto.\n generalize (remove_min_in l2 x2 r2 h2 m H2); rewrite e1; simpl; auto.\n destruct 1; intuition.\n generalize (remove_min_gt_tree l2 x2 r2 h2 H1 H2); rewrite e1; simpl; auto.\nQed.\n\nLemma concat_in : forall s1 s2 y, bst s1 -> avl s1 -> bst s2 -> avl s2 -> \n (forall y1 y2 : elt, In y1 s1 -> In y2 s2 -> X.lt y1 y2) -> \n (In y (concat s1 s2) <-> In y s1 \\/ In y s2).\nProof.\n intros s1 s2; functional induction (concat s1 s2);subst;simpl.\n intuition.\n inversion_clear H5.\n destruct s1;try contradiction;clear y;intuition.\n inversion_clear H5.\n destruct s1;try contradiction;clear y; intros. \n rewrite (join_in _ m s2' y H0).\n generalize (remove_min_in l2 x2 r2 h2 y H2); rewrite e1; simpl.\n intro EQ; rewrite EQ; intuition.\n generalize (remove_min_avl l2 x2 r2 h2 H2); rewrite e1; simpl; auto.\nQed.\n\n(** * Splitting \n\n    [split x s] returns a triple [(l, present, r)] where\n    - [l] is the set of elements of [s] that are [< x]\n    - [r] is the set of elements of [s] that are [> x]\n    - [present] is [true] if and only if [s] contains  [x].\n*)\n\nFunction split (x:elt)(s:t) {struct s} : t * (bool * t) := match s with \n  | Leaf => (Leaf, (false, Leaf))\n  | Node l y r h => \n     match X.compare x y with \n      | LT _ => match split x l with \n                 | (ll,(pres,rl)) => (ll, (pres, join rl y r))\n                end\n      | EQ _ => (l, (true, r))\n      | GT _ => match split x r with \n                 | (rl,(pres,rr)) => (join l y rl, (pres, rr))\n                end\n     end\n end.\n\nLemma split_avl : forall s x, avl s -> \n  avl (fst (split x s)) /\\ avl (snd (snd (split x s))).\nProof. \n intros s x; functional induction (split x s);subst;simpl in *.\n auto.\n rewrite e1 in IHp;simpl in IHp;inversion_clear 1; intuition.\n simpl; inversion_clear 1; auto.\n rewrite e1 in IHp;simpl in IHp;inversion_clear 1; intuition.\nQed.\n\nLemma split_in_1 : forall s x y, bst s -> avl s -> \n (In y (fst (split x s)) <-> In y s /\\ X.lt y x).\nProof. \n intros s x; functional induction (split x s);subst;simpl in *.\n intuition; try inversion_clear H1.\n (* LT *)\n rewrite e1 in IHp;simpl in *; inversion_clear 1; inversion_clear 1; clear  H7 H6.\n rewrite (IHp y0 H0 H4); clear IHp e0.\n intuition.\n inversion_clear H6; auto; order.\n (* EQ *)\n simpl in *; inversion_clear 1; inversion_clear 1; clear H6 H5 e0.\n intuition.\n order.\n intuition_in; order.\n (* GT *)\n rewrite e1 in IHp;simpl in *; inversion_clear 1; inversion_clear 1; clear H7 H6.\n rewrite join_in; auto.\n rewrite (IHp y0 H1 H5); clear e1.\n intuition; [ eauto | eauto | intuition_in ].\n generalize (split_avl r x H5); rewrite e1; simpl; intuition.\nQed.\n\nLemma split_in_2 : forall s x y, bst s -> avl s -> \n (In y (snd (snd (split x s))) <-> In y s /\\ X.lt x y).\nProof. \n intros s x; functional induction (split x s);subst;simpl in *.\n intuition; try inversion_clear H1.\n (* LT *)\n rewrite e1 in IHp; simpl in *; inversion_clear 1; inversion_clear 1; clear H7 H6.\n rewrite join_in; auto.\n rewrite (IHp y0 H0 H4); clear IHp e0.\n intuition; [ order | order | intuition_in ].\n generalize (split_avl l x H4); rewrite e1; simpl; intuition.\n (* EQ *)\n simpl in *; inversion_clear 1; inversion_clear 1; clear H6 H5 e0.\n intuition; [ order | intuition_in; order ]. \n (* GT *)\n rewrite e1 in IHp; simpl in *; inversion_clear 1; inversion_clear 1; clear H7 H6.\n rewrite (IHp y0 H1 H5); clear IHp e0.\n intuition; intuition_in; order. \nQed.\n\nLemma split_in_3 : forall s x, bst s -> avl s -> \n (fst (snd (split x s)) = true <-> In x s).\nProof. \n intros s x; functional induction (split x s);subst;simpl in *.\n intuition; try inversion_clear H1.\n (* LT *)\n rewrite e1 in IHp; simpl in *; inversion_clear 1; inversion_clear 1; clear H7 H6.\n rewrite IHp; auto.\n intuition_in; absurd (X.lt x y); eauto.\n (* EQ *)\n simpl in *; inversion_clear 1; inversion_clear 1; intuition.\n (* GT *)\n rewrite e1 in IHp; simpl in *; inversion_clear 1; inversion_clear 1; clear H7 H6.\n rewrite IHp; auto.\n intuition_in; absurd (X.lt y x); eauto.\nQed.\n\nLemma split_bst : forall s x, bst s -> avl s -> \n bst (fst (split x s)) /\\ bst (snd (snd (split x s))).\nProof. \n intros s x; functional induction (split x s);subst;simpl in *.  \n intuition.\n (* LT *)\n rewrite e1 in IHp; simpl in *; inversion_clear 1; inversion_clear 1.\n intuition.\n apply join_bst; auto.\n generalize (split_avl l x H4); rewrite e1; simpl; intuition.\n intro; intro.\n generalize (split_in_2 l x y0 H0 H4); rewrite e1; simpl; intuition.\n (* EQ *)\n simpl in *; inversion_clear 1; inversion_clear 1; intuition.\n (* GT *)\n rewrite e1 in IHp; simpl in *; inversion_clear 1; inversion_clear 1.\n intuition.\n apply join_bst; auto.\n generalize (split_avl r x H5); rewrite e1; simpl; intuition.\n intro; intro.\n generalize (split_in_1 r x y0 H1 H5); rewrite e1; simpl; intuition.\nQed.\n\n(** * Intersection *)\n\nFixpoint inter (s1 s2 : t) {struct s1} : t := match s1, s2 with \n    | Leaf,_ => Leaf\n    | _,Leaf => Leaf\n    | Node l1 x1 r1 h1, _ => \n            match split x1 s2 with\n               | (l2',(true,r2')) => join (inter l1 l2') x1 (inter r1 r2')\n               | (l2',(false,r2')) => concat (inter l1 l2') (inter r1 r2')\n            end\n    end.\n\nLemma inter_avl : forall s1 s2, avl s1 -> avl s2 -> avl (inter s1 s2). \nProof. \n (* intros s1 s2; functional induction inter s1 s2; auto. BOF BOF *)\n induction s1 as [ | l1 Hl1 x1 r1 Hr1 h1]; simpl; auto.\n destruct s2 as [ | l2 x2 r2 h2]; intros; auto.\n generalize H0; inv avl.\n set (r:=Node l2 x2 r2 h2) in *; clearbody r; intros. \n destruct (split_avl r x1 H8).\n destruct (split x1 r) as [l2' (b,r2')]; simpl in *.\n destruct b; [ apply join_avl | apply concat_avl ]; auto.\nQed.\n\nLemma inter_bst_in : forall s1 s2, bst s1 -> avl s1 -> bst s2 -> avl s2 -> \n bst (inter s1 s2) /\\ (forall y, In y (inter s1 s2) <-> In y s1 /\\ In y s2).\nProof. \n induction s1 as [ | l1 Hl1 x1 r1 Hr1 h1]; simpl; auto.\n intuition; inversion_clear H3.\n destruct s2 as [ | l2 x2 r2 h2]; intros.\n simpl; intuition; inversion_clear H3.\n generalize H1 H2; inv avl; inv bst.\n set (r:=Node l2 x2 r2 h2) in *; clearbody r; intros.\n destruct (split_avl r x1 H17).\n destruct (split_bst r x1 H16 H17).\n split.\n (* bst *)\n destruct (split x1 r) as [l2' (b,r2')]; simpl in *.\n destruct (Hl1 l2'); auto.\n destruct (Hr1 r2'); auto.\n destruct b.\n (* bst join *)\n apply join_bst; try apply inter_avl; auto; \n  intro y; [rewrite (H22 y)|rewrite (H24 y)]; intuition.\n (* bst concat *)\n apply concat_bst; try apply inter_avl; auto.\n intros y1 y2; rewrite (H22 y1), (H24 y2); intuition eauto.\n (* in *)\n intros.\n destruct (split_in_1 r x1 y H16 H17). \n destruct (split_in_2 r x1 y H16 H17).\n destruct (split_in_3 r x1 H16 H17).\n destruct (split x1 r) as [l2' (b,r2')]; simpl in *.\n destruct (Hl1 l2'); auto.\n destruct (Hr1 r2'); auto.\n destruct b.\n (* in join *)\n rewrite join_in; try apply inter_avl; auto.\n rewrite H30, H28; intuition_in.\n apply In_1 with x1; auto.\n (* in concat *)\n rewrite concat_in; try apply inter_avl; auto.\n rewrite H30, H28; intuition_in.\n generalize (H26 (In_1 _ _ _ H22 H35)); intro; discriminate.\n intros y1 y2; rewrite (H28 y1), (H30 y2); intuition eauto.\nQed.\n\nLemma inter_bst : forall s1 s2, bst s1 -> avl s1 -> bst s2 -> avl s2 -> \n bst (inter s1 s2). \nProof. \n intros s1 s2 B1 A1 B2 A2; destruct (inter_bst_in s1 s2 B1 A1 B2 A2); auto.\nQed.\n\nLemma inter_in : forall s1 s2 y, bst s1 -> avl s1 -> bst s2 -> avl s2 -> \n (In y (inter s1 s2) <-> In y s1 /\\ In y s2).\nProof. \n intros s1 s2 y B1 A1 B2 A2; destruct (inter_bst_in s1 s2 B1 A1 B2 A2); auto.\nQed.\n\n(** * Difference *)\n\nFixpoint diff (s1 s2 : t) { struct s1 } : t := match s1, s2 with \n | Leaf, _ => Leaf\n | _, Leaf => s1\n | Node l1 x1 r1 h1, _ => \n    match split x1 s2 with \n      | (l2',(true,r2')) => concat (diff l1 l2') (diff r1 r2')\n      | (l2',(false,r2')) => join (diff l1 l2') x1 (diff r1 r2')\n    end\nend. \n\nLemma diff_avl : forall s1 s2, avl s1 -> avl s2 -> avl (diff s1 s2). \nProof. \n (* intros s1 s2; functional induction diff s1 s2; auto. BOF BOF *)\n induction s1 as [ | l1 Hl1 x1 r1 Hr1 h1]; simpl; auto.\n destruct s2 as [ | l2 x2 r2 h2]; intros; auto.\n generalize H0; inv avl.\n set (r:=Node l2 x2 r2 h2) in *; clearbody r; intros. \n destruct (split_avl r x1 H8).\n destruct (split x1 r) as [l2' (b,r2')]; simpl in *.\n destruct b; [ apply concat_avl | apply join_avl ]; auto.\nQed.\n\nLemma diff_bst_in : forall s1 s2, bst s1 -> avl s1 -> bst s2 -> avl s2 -> \n bst (diff s1 s2) /\\ (forall y, In y (diff s1 s2) <-> In y s1 /\\ ~In y s2).\nProof. \n induction s1 as [ | l1 Hl1 x1 r1 Hr1 h1]; simpl; auto.\n intuition; inversion_clear H3.\n destruct s2 as [ | l2 x2 r2 h2]; intros; auto.\n intuition; inversion_clear H4.\n generalize H1 H2; inv avl; inv bst.\n set (r:=Node l2 x2 r2 h2) in *; clearbody r; intros.\n destruct (split_avl r x1 H17).\n destruct (split_bst r x1 H16 H17).\n split.\n (* bst *)\n destruct (split x1 r) as [l2' (b,r2')]; simpl in *.\n destruct (Hl1 l2'); auto.\n destruct (Hr1 r2'); auto.\n destruct b.\n (* bst concat *)\n apply concat_bst; try apply diff_avl; auto.\n intros y1 y2; rewrite (H22 y1), (H24 y2); intuition eauto.\n (* bst join *)\n apply join_bst; try apply diff_avl; auto; \n  intro y; [rewrite (H22 y)|rewrite (H24 y)]; intuition.\n (* in *)\n intros.\n destruct (split_in_1 r x1 y H16 H17). \n destruct (split_in_2 r x1 y H16 H17).\n destruct (split_in_3 r x1 H16 H17).\n destruct (split x1 r) as [l2' (b,r2')]; simpl in *.\n destruct (Hl1 l2'); auto.\n destruct (Hr1 r2'); auto.\n destruct b.\n (* in concat *)\n rewrite concat_in; try apply diff_avl; auto.\n rewrite H30, H28; intuition_in.\n elim H35; apply In_1 with x1; auto.\n intros; generalize (H28 y1) (H30 y2); intuition eauto.\n (* in join *)\n rewrite join_in; try apply diff_avl; auto.\n rewrite H30, H28; intuition_in.\n generalize (H26 (In_1 _ _ _ H34 H24)); intro; discriminate.\nQed.\n\nLemma diff_bst : forall s1 s2, bst s1 -> avl s1 -> bst s2 -> avl s2 -> \n bst (diff s1 s2). \nProof. \n intros s1 s2 B1 A1 B2 A2; destruct (diff_bst_in s1 s2 B1 A1 B2 A2); auto.\nQed.\n\nLemma diff_in : forall s1 s2 y, bst s1 -> avl s1 -> bst s2 -> avl s2 -> \n (In y (diff s1 s2) <-> In y s1 /\\ ~In y s2).\nProof. \n intros s1 s2 y B1 A1 B2 A2; destruct (diff_bst_in s1 s2 B1 A1 B2 A2); auto.\nQed.\n\n(** * Elements *)\n\n(** [elements_tree_aux acc t] catenates the elements of [t] in infix\n    order to the list [acc] *)\n\nFixpoint elements_aux (acc : list X.t) (t : tree) {struct t} : list X.t :=\n  match t with\n   | Leaf => acc\n   | Node l x r _ => elements_aux (x :: elements_aux acc r) l\n  end.\n\n(** then [elements] is an instanciation with an empty [acc] *)\n\nDefinition elements := elements_aux nil.\n\nLemma elements_aux_in : forall s acc x, \n InA X.eq x (elements_aux acc s) <-> In x s \\/ InA X.eq x acc.\nProof.\n induction s as [ | l Hl x r Hr h ]; simpl; auto.\n intuition.\n inversion H0.\n intros.\n rewrite Hl.\n destruct (Hr acc x0); clear Hl Hr.\n intuition; inversion_clear H3; intuition.\nQed.\n\nLemma elements_in : forall s x, InA X.eq x (elements s) <-> In x s. \nProof. \n intros; generalize (elements_aux_in s nil x); intuition.\n inversion_clear H0.\nQed.\n\nLemma elements_aux_sort : forall s acc, bst s -> sort X.lt acc ->\n (forall x y : elt, InA X.eq x acc -> In y s -> X.lt y x) ->\n sort X.lt (elements_aux acc s).\nProof.\n induction s as [ | l Hl y r Hr h]; simpl; intuition.\n inv bst.\n apply Hl; auto.\n constructor. \n apply Hr; auto.\n apply MX.In_Inf; intros.\n destruct (elements_aux_in r acc y0); intuition.\n intros.\n inversion_clear H.\n order.\n destruct (elements_aux_in r acc x); intuition eauto.\nQed.\n\nLemma elements_sort : forall s : tree, bst s -> sort X.lt (elements s).\nProof.\n intros; unfold elements; apply elements_aux_sort; auto.\n intros; inversion H0.\nQed.\nHint Resolve elements_sort.\n\nLemma elements_nodup : forall s : tree, bst s -> NoDupA X.eq (elements s).\nProof.\n auto.\nQed.\n\n(** * Filter *)\n\nSection F.\nVariable f : elt -> bool.\n\nFixpoint filter_acc (acc:t)(s:t) { struct s } : t := match s with \n  | Leaf => acc\n  | Node l x r h => \n     filter_acc (filter_acc (if f x then add x acc else acc) l) r \n end.\n\nDefinition filter := filter_acc Leaf. \n\nLemma filter_acc_avl : forall s acc, avl s -> avl acc -> \n avl (filter_acc acc s).\nProof.\n induction s; simpl; auto.\n intros.\n inv avl.\n apply IHs2; auto.\n apply IHs1; auto.\n destruct (f t); auto.\nQed. \nHint Resolve filter_acc_avl.\n\nLemma filter_acc_bst : forall s acc, bst s -> avl s -> bst acc -> avl acc -> \n bst (filter_acc acc s).\nProof.\n induction s; simpl; auto.\n intros.\n inv avl; inv bst.\n destruct (f t); auto.\n apply IHs2; auto.\n apply IHs1; auto.\n apply add_bst; auto.\nQed. \n\nLemma filter_acc_in : forall s acc, avl s -> avl acc -> \n compat_bool X.eq f -> forall x : elt, \n In x (filter_acc acc s) <-> In x acc \\/ In x s /\\ f x = true.\nProof.  \n induction s; simpl; intros.\n intuition_in.\n inv bst; inv avl.\n rewrite IHs2 by (destruct (f t); auto).\n rewrite IHs1 by (destruct (f t); auto).\n case_eq (f t); intros.\n rewrite (add_in); auto.\n intuition_in.\n rewrite (H1 _ _ H8).\n intuition.\n intuition_in.\n rewrite (H1 _ _ H8) in H9.\n rewrite H in H9; discriminate.\nQed.\n\nLemma filter_avl : forall s, avl s -> avl (filter s). \nProof.\n unfold filter; intros; apply filter_acc_avl; auto.\nQed.\n\nLemma filter_bst : forall s, bst s -> avl s -> bst (filter s). \nProof.\n unfold filter; intros; apply filter_acc_bst; auto.\nQed.\n\nLemma filter_in : forall s, avl s -> \n compat_bool X.eq f -> forall x : elt, \n In x (filter s) <-> In x s /\\ f x = true.\nProof.\n unfold filter; intros; rewrite filter_acc_in; intuition_in.\nQed. \n\n(** * Partition *)\n\nFixpoint partition_acc (acc : t*t)(s : t) { struct s } : t*t := \n  match s with \n   | Leaf => acc\n   | Node l x r _ => \n      let (acct,accf) := acc in \n      partition_acc \n        (partition_acc \n           (if f x then (add x acct, accf) else (acct, add x accf)) l) r\n  end. \n\nDefinition partition := partition_acc (Leaf,Leaf).\n\nLemma partition_acc_avl_1 : forall s acc, avl s -> \n avl (fst acc) -> avl (fst (partition_acc acc s)).\nProof.\n induction s; simpl; auto.\n destruct acc as [acct accf]; simpl in *.\n intros.\n inv avl.\n apply IHs2; auto.\n apply IHs1; auto.\n destruct (f t); simpl; auto.\nQed. \n\nLemma partition_acc_avl_2 : forall s acc, avl s -> \n avl (snd acc) -> avl (snd (partition_acc acc s)).\nProof.\n induction s; simpl; auto.\n destruct acc as [acct accf]; simpl in *.\n intros.\n inv avl.\n apply IHs2; auto.\n apply IHs1; auto.\n destruct (f t); simpl; auto.\nQed. \nHint Resolve partition_acc_avl_1 partition_acc_avl_2.\n\nLemma partition_acc_bst_1 : forall s acc, bst s -> avl s -> \n bst (fst acc) -> avl (fst acc) -> \n bst (fst (partition_acc acc s)).\nProof.\n induction s; simpl; auto.\n destruct acc as [acct accf]; simpl in *.\n intros.\n inv avl; inv bst.\n destruct (f t); auto.\n apply IHs2; simpl; auto.\n apply IHs1; simpl; auto.\n apply add_bst; auto.\n apply partition_acc_avl_1; simpl; auto.\nQed. \n\nLemma partition_acc_bst_2 : forall s acc, bst s -> avl s -> \n bst (snd acc) -> avl (snd acc) -> \n bst (snd (partition_acc acc s)).\nProof.\n induction s; simpl; auto.\n destruct acc as [acct accf]; simpl in *.\n intros.\n inv avl; inv bst.\n destruct (f t); auto.\n apply IHs2; simpl; auto.\n apply IHs1; simpl; auto.\n apply add_bst; auto.\n apply partition_acc_avl_2; simpl; auto.\nQed. \n\nLemma partition_acc_in_1 : forall s acc, avl s -> avl (fst acc) -> \n compat_bool X.eq f -> forall x : elt, \n In x (fst (partition_acc acc s)) <-> \n In x (fst acc) \\/ In x s /\\ f x = true.\nProof.  \n induction s; simpl; intros.\n intuition_in.\n destruct acc as [acct accf]; simpl in *.\n inv bst; inv avl.\n rewrite IHs2 by (destruct (f t); auto; apply partition_acc_avl_1; simpl; auto).\n rewrite IHs1 by (destruct (f t); simpl; auto).\n case_eq (f t); simpl; intros.\n rewrite (add_in); auto.\n intuition_in.\n rewrite (H1 _ _ H8).\n intuition.\n intuition_in.\n rewrite (H1 _ _ H8) in H9.\n rewrite H in H9; discriminate.\nQed.\n\nLemma partition_acc_in_2 : forall s acc, avl s -> avl (snd acc) -> \n compat_bool X.eq f -> forall x : elt, \n In x (snd (partition_acc acc s)) <-> \n In x (snd acc) \\/ In x s /\\ f x = false.\nProof.  \n induction s; simpl; intros.\n intuition_in.\n destruct acc as [acct accf]; simpl in *.\n inv bst; inv avl.\n rewrite IHs2 by (destruct (f t); auto; apply partition_acc_avl_2; simpl; auto).\n rewrite IHs1 by (destruct (f t); simpl; auto).\n case_eq (f t); simpl; intros.\n intuition.\n intuition_in.\n rewrite (H1 _ _ H8) in H9.\n rewrite H in H9; discriminate.\n rewrite (add_in); auto.\n intuition_in.\n rewrite (H1 _ _ H8).\n intuition.\nQed. \n\nLemma partition_avl_1 : forall s, avl s -> avl (fst (partition s)). \nProof.\n unfold partition; intros; apply partition_acc_avl_1; auto.\nQed.\n\nLemma partition_avl_2 : forall s, avl s -> avl (snd (partition s)). \nProof.\n unfold partition; intros; apply partition_acc_avl_2; auto.\nQed.\n\nLemma partition_bst_1 : forall s, bst s -> avl s -> \n bst (fst (partition s)). \nProof.\n unfold partition; intros; apply partition_acc_bst_1; auto.\nQed.\n\nLemma partition_bst_2 : forall s, bst s -> avl s -> \n bst (snd (partition s)). \nProof.\n unfold partition; intros; apply partition_acc_bst_2; auto.\nQed.\n\nLemma partition_in_1 : forall s, avl s -> \n compat_bool X.eq f -> forall x : elt, \n In x (fst (partition s)) <-> In x s /\\ f x = true.\nProof.\n unfold partition; intros; rewrite partition_acc_in_1; \n simpl in *; intuition_in.\nQed. \n\nLemma partition_in_2 : forall s, avl s -> \n compat_bool X.eq f -> forall x : elt, \n In x (snd (partition s)) <-> In x s /\\ f x = false.\nProof.\n unfold partition; intros; rewrite partition_acc_in_2; \n simpl in *; intuition_in.\nQed. \n\n(** [for_all] and [exists] *)\n\nFixpoint for_all (s:t) : bool := match s with \n  | Leaf => true\n  | Node l x r _ => f x && for_all l && for_all r\nend.\n\nLemma for_all_1 : forall s, compat_bool X.eq f ->\n For_all (fun x => f x = true) s -> for_all s = true.\nProof.\n induction s; simpl; auto.\n intros.\n rewrite IHs1; try red; auto.\n rewrite IHs2; try red; auto.\n generalize (H0 t).\n destruct (f t); simpl; auto.\nQed.\n\nLemma for_all_2 : forall s, compat_bool X.eq f ->\n for_all s = true -> For_all (fun x => f x = true) s.\nProof.\n induction s; simpl; auto; intros; red; intros; inv In.\n destruct (andb_prop _ _ H0); auto.\n destruct (andb_prop _ _ H1); eauto.\n apply IHs1; auto.\n destruct (andb_prop _ _ H0); auto.\n destruct (andb_prop _ _ H1); auto.\n apply IHs2; auto.\n destruct (andb_prop _ _ H0); auto.\nQed.\n\nFixpoint exists_ (s:t) : bool := match s with \n  | Leaf => false\n  | Node l x r _ => f x || exists_ l || exists_ r\nend.  \n\nLemma exists_1 : forall s, compat_bool X.eq f ->\n Exists (fun x => f x = true) s -> exists_ s = true.\nProof.\n induction s; simpl; destruct 2 as (x,(U,V)); inv In.\n rewrite (H _ _ (X.eq_sym H0)); rewrite V; auto.\n apply orb_true_intro; left.\n apply orb_true_intro; right; apply IHs1; firstorder.\n apply orb_true_intro; right; apply IHs2; firstorder.\nQed.\n\nLemma exists_2 : forall s, compat_bool X.eq f ->\n exists_ s = true -> Exists (fun x => f x = true) s.\nProof. \n induction s; simpl; intros.\n discriminate.\n destruct (orb_true_elim _ _ H0) as [H1|H1]. \n destruct (orb_true_elim _ _ H1) as [H2|H2].\n exists t; auto.\n destruct (IHs1 H H2); firstorder.\n destruct (IHs2 H H1); firstorder.\nQed. \n\nEnd F.\n\n(** * Fold *)\n\nModule L := FSetList0.Raw X.\n\nFixpoint fold (A : Type) (f : elt -> A -> A)(s : tree) {struct s} : A -> A := \n fun a => match s with\n  | Leaf => a\n  | Node l x r _ => fold A f r (f x (fold A f l a))\n end.\nImplicit Arguments fold [A].\n\nDefinition fold' (A : Type) (f : elt -> A -> A)(s : tree) := \n  L.fold f (elements s).\nImplicit Arguments fold' [A].\n\nLemma fold_equiv_aux :\n forall (A : Type) (s : tree) (f : elt -> A -> A) (a : A) (acc : list elt),\n L.fold f (elements_aux acc s) a = L.fold f acc (fold f s a).\nProof.\n simple induction s.\n simpl in |- *; intuition.\n simpl in |- *; intros.\n rewrite H.\n simpl.\n apply H0.\nQed.\n\nLemma fold_equiv :\n forall (A : Type) (s : tree) (f : elt -> A -> A) (a : A),\n fold f s a = fold' f s a.\nProof.\n unfold fold', elements in |- *. \n simple induction s; simpl in |- *; auto; intros.\n rewrite fold_equiv_aux.\n rewrite H0.\n simpl in |- *; auto.\nQed.\n\nLemma fold_1 : \n forall (s:t)(Hs:bst s)(A : Type)(f : elt -> A -> A)(i : A),\n fold f s i = fold_left (fun a e => f e a) (elements s) i.\nProof.\n intros.\n rewrite fold_equiv.\n unfold fold'.\n rewrite L.fold_1.\n unfold L.elements; auto.\n apply elements_sort; auto.\nQed.\n\n(** * Cardinal *)\n\nFixpoint cardinal (s : tree) : nat :=\n  match s with\n   | Leaf => 0%nat\n   | Node l _ r _ => S (cardinal l + cardinal r)\n  end.\n\nLemma cardinal_elements_aux_1 :\n forall s acc, (length acc + cardinal s)%nat = length (elements_aux acc s).\nProof.\n simple induction s; simpl in |- *; intuition.\n rewrite <- H.\n simpl in |- *.\n rewrite <- H0; omega.\nQed.\n\nLemma cardinal_elements_1 : forall s : tree, cardinal s = length (elements s).\nProof.\n exact (fun s => cardinal_elements_aux_1 s nil).\nQed.\n\n(** Induction over cardinals *)\n\nLemma sorted_subset_cardinal : forall l' l : list X.t,\n sort X.lt l -> sort X.lt l' ->\n (forall x : elt, InA X.eq x l -> InA X.eq x l') -> (length l <= length l')%nat.\nProof.\n simple induction l'; simpl in |- *; intuition.\n destruct l; trivial; intros.\n absurd (InA X.eq t nil); intuition.\n inversion_clear H2.\n inversion_clear H1.\n destruct l0; simpl in |- *; intuition auto with arith.\n inversion_clear H0.\n apply le_n_S.\n case (X.compare t a); intro.\n absurd (InA X.eq t (a :: l)).\n intro.\n inversion_clear H0.\n order.\n assert (X.lt a t).\n apply MX.Sort_Inf_In with l; auto.\n order.\n firstorder.\n apply H; auto.\n intros.\n assert (InA X.eq x (a :: l)).\n apply H2; auto.\n inversion_clear H6; auto.\n assert (X.lt t x).\n apply MX.Sort_Inf_In with l0; auto.\n order.\n apply le_trans with (length (t :: l0)).\n simpl in |- *; omega.\n apply (H (t :: l0)); auto.\n intros.\n assert (InA X.eq x (a :: l)); firstorder.\n inversion_clear H6; auto.\n assert (X.lt a x).\n apply MX.Sort_Inf_In with (t :: l0); auto.\n elim (X.lt_not_eq (x:=a) (y:=x)); auto.\nQed.\n\nLemma cardinal_subset : forall a b : tree, bst a -> bst b ->\n (forall y : elt, In y a -> In y b) ->\n (cardinal a <= cardinal b)%nat.\nProof.\n intros.\n do 2 rewrite cardinal_elements_1.\n apply sorted_subset_cardinal; auto.\n intros.\n generalize (elements_in a x) (elements_in b x).\n intuition.\nQed.\n\nLemma height_0 : forall s, avl s -> height s = 0 -> s = Leaf.\nProof.\n destruct 1; intuition; simpl in *.\n avl_nns; simpl in *; elimtype False; omega_max.\nQed.\n\nNotation \"s #1\" := (fst s) (at level 9).\nNotation \"s #2\" := (snd s) (at level 9).\n\nDefinition cardinal2 (s:t*t) := \n (cardinal s#1 + cardinal s#2)%nat.\n\n(** * Union *)\n\nObligation Tactic := \n simpl ; intros ; destruct_exists ; simpl in * ; try subst; \n unfold cardinal2; simpl @fst in *; simpl @snd in *; \n try match goal with u:forall s:_,{x:_|_} |- _ => clear u end; \n try match goal with a: _ /\\ _ /\\ _ /\\ _ |- _ => \n   destruct a as (B1 & A1 & B2 & A2)\n end.\n\nProgram Fixpoint union\n (s : t * t | bst s#1 /\\ avl s#1 /\\ bst s#2 /\\ avl s#2) \n { measure (cardinal2 s) } : \n { s' : t | bst s' /\\ avl s' /\\ \n           forall x, In x s' <-> In x s#1 \\/ In x s#2 }\n :=\n match s with \n  | (Leaf, Leaf) => s#2\n  | (Leaf, Node _ _ _ _) => s#2\n  | (Node _ _ _ _, Leaf) => s#1\n  | (Node l1 x1 r1 h1, Node l2 x2 r2 h2) => \n        if ge_lt_dec h1 h2 then\n          if eq_dec h2 1 then add x2 s#1 else\n          let '(l2',(_,r2')) := split x1 s#2 in\n             join (union (l1,l2')) x1 (union (r1,r2'))\n        else\n          if eq_dec h1 1 then add x1 s#2 else\n          let '(l1',(_,r1')) := split x2 s#1 in \n             join (union (l1',l2)) x2 (union (r1',r2))\n end.\n\nNext Obligation. (* 1: postcondition about s2 *)\n intuition_in.\nQed.\n\nNext Obligation. (* 2: postcondition about s2 *)\n intuition_in.\nQed.\n\nNext Obligation. (* 3: postcondition about s1 *)\n intuition_in.\nQed.\n\nNext Obligation. (* 4: postcondition about (add x2 s1) *)\n  split.\n  apply add_bst; auto.\n  split; auto.\n  intros.\n  rewrite add_in; auto.\n  inv avl; inv bst.\n  avl_nn l2; avl_nn r2.\n  rewrite (height_0 _ H1); [ | omega_max].\n  rewrite (height_0 _ H2); [ | omega_max].\n  intuition_in.\nQed.\n\nNext Obligation. (* 5: precondition for (union (l1,l2')) *)\n  generalize (split_avl _ x1 A2).\n  generalize (split_bst _ x1 B2 A2).\n  rewrite <- Heq_anonymous; simpl.\n  inv avl; inv bst; intuition.\nQed.\n\nNext Obligation. (* 6: decreasing of (union (l1,l2')) *)\n  assert (l2' = (split x1 (Node l2 x2 r2 h2))#1).\n    rewrite <- Heq_anonymous; auto.\n  clear Heq_anonymous.\n  assert (cardinal l2' <= cardinal (Node l2 x2 r2 h2))%nat.\n    subst l2'.\n    apply cardinal_subset; auto.\n    destruct (split_bst _ x1 B2 A2); auto.\n    intros y; rewrite (split_in_1 _ x1 y B2 A2); tauto.\n  simpl (cardinal (Node l1 x1 r1 h1)).\n omega.\nQed.\n\nNext Obligation. (* 7: precondition for (union (r1,r2')) *)\n  generalize (split_avl _ x1 A2).\n  generalize (split_bst _ x1 B2 A2).\n  rewrite <- Heq_anonymous; simpl.\n  inv avl; inv bst; intuition.\nQed.\n\nNext Obligation. (* 8: decreasing of (union (r1,r2')) *)\n  assert (r2' = (split x1 (Node l2 x2 r2 h2))#2#2).\n    rewrite <- Heq_anonymous; auto.\n  clear Heq_anonymous.\n  assert (cardinal r2' <= cardinal (Node l2 x2 r2 h2))%nat.\n    subst r2'.\n    apply cardinal_subset; auto.\n      destruct (split_bst _ x1 B2 A2); auto.\n      intros y; rewrite (split_in_2 _ x1 y B2 A2); tauto.\n  simpl (cardinal (Node l1 x1 r1 h1)).\n  omega.\nQed.\n\nNext Obligation. (* 9: postcondition for (join (union (l1,l2')) x1 (union (r1,r2'))) *)\n  do 2 destruct_call union. simpl in a, a0 |- *.\n  decompose [and] a; clear a.\n  decompose [and] a0; clear a0.\n  clear union; simpl @snd in *; simpl @fst in *.\n  rename x into l; rename x2 into r.\n  assert (l2' = (split x1 (Node l2 r r2 h2))#1\n    /\\ r2' = (split x1 (Node l2 r r2 h2))#2#2).\n  rewrite <- Heq_anonymous; auto.\n  destruct H5; subst l2' r2'; clear Heq_anonymous.\n  split.\n  apply join_bst; auto. \n  red; intro.\n  rewrite H4; destruct 1.\n  inv bst; auto.\n  rewrite (split_in_1 _ x1 y B2 A2) in H5; tauto.\n  red; intro.\n  rewrite H7; destruct 1.\n  inv bst; auto.\n  rewrite (split_in_2 _ x1 y B2 A2) in H5; tauto.\n  split; auto.\n  intro y.\n  rewrite join_in; auto.\n  rewrite H4; rewrite H7; clear H4 H7.\n  rewrite (split_in_1 _ x1 y B2 A2); rewrite (split_in_2 _ x1 y B2 A2).\n  case (X.compare y x1); intuition_in.\nQed.\n\nNext Obligation. (* 10: postcondition about (add x1 s2) *)\n split.\n apply add_bst; auto.\n split; auto.\n intros.\n rewrite add_in; auto.\n inv avl; inv bst.\n avl_nn l1; avl_nn r1.\n rewrite (height_0 _ H5); [ | omega_max].\n rewrite (height_0 _ H6); [ | omega_max].\n intuition_in.\nQed.\n\nNext Obligation. (* 11: precondition for (union (l1',l2)) *)\n generalize (split_avl _ x2 A1).\n generalize (split_bst _ x2 B1 A1).\n rewrite <- Heq_anonymous; simpl.\n inv avl; inv bst; intuition.\nQed.\n\nNext Obligation. (* 12: decreasing of (union (l1',l2)) *)\n assert (l1' = (split x2 (Node l1 x1 r1 h1))#1).\n   rewrite <- Heq_anonymous; auto.\n clear Heq_anonymous.\n assert (cardinal l1' <= cardinal (Node l1 x1 r1 h1))%nat.\n  subst l1'.\n  apply cardinal_subset; auto.\n  destruct (split_bst _ x2 B1 A1); auto.\n  intros y; rewrite (split_in_1 _ x2 y B1 A1); tauto.\n simpl (cardinal (Node l2 x2 r2 h2)).\n omega.\nQed.\n\nNext Obligation. (* 13: precondition for (union (r1',r2)) *)\n generalize (split_avl _ x2 A1).\n generalize (split_bst _ x2 B1 A1).\n rewrite <- Heq_anonymous; simpl.\n inv avl; inv bst; intuition.\nQed.\n\nNext Obligation. (* 14: decreasing of (union (r1',r2)) *)\n assert (r1' = (split x2 (Node l1 x1 r1 h1))#2#2).\n   rewrite <- Heq_anonymous; auto.\n clear Heq_anonymous.\n assert (cardinal r1' <= cardinal (Node l1 x1 r1 h1))%nat.\n  subst r1'.\n  apply cardinal_subset; auto.\n  destruct (split_bst _ x2 B1 A1); auto.\n  intros y; rewrite (split_in_2 _ x2 y B1 A1); tauto.\n simpl (cardinal (Node l2 x2 r2 h2)).\n omega.\nQed.\n\nNext Obligation. (* 15: postcondition for (join (union (l1',l2)) x2 (union (snd pr1',r2))) *)\n do 2 destruct_call union; simpl in a, a0 |- *.\n decompose [and] a; clear a.\n decompose [and] a0; clear a0.\n simpl @snd in *; simpl @fst in *.\n clear union; rename x into l; rename x2 into r.\n assert (l1' = (split r (Node l1 x1 r1 h1))#1 \n      /\\ r1' = (split r (Node l1 x1 r1 h1))#2#2).\n   rewrite <- Heq_anonymous; auto.\n destruct H5; subst l1' r1'; clear Heq_anonymous.\n split.\n apply join_bst; auto. \n red; intro.\n rewrite H4; destruct 1.\n rewrite (split_in_1 _ r y B1 A1) in H5; tauto.\n inv bst; auto.\n red; intro.\n rewrite H7; destruct 1.\n rewrite (split_in_2 _ r y B1 A1) in H5; tauto.\n inv bst; auto.\n split; auto.\n intro y.\n rewrite join_in; auto.\n rewrite H4; rewrite H7; clear H4 H7.\n rewrite (split_in_1 _ r y B1 A1); rewrite (split_in_2 _ r y B1 A1).\n case (X.compare y r); intuition_in.\nQed.\n\nNext Obligation. (* Well_foundedness *)\nauto with arith.\nDefined.\n\n(** * Subset *)\n\nLocal Open Scope program_scope.\n\nNotation \"a && b\" := \n (if a then if b then in_left else in_right else in_right).\n\nObligation Tactic := \n simpl ; intros ; destruct_exists ; simpl in * ; try subst; \n unfold cardinal2;\n simpl @fst in *; simpl @snd in *; \n try match goal with u:forall s:_,{_}+{_} |- _ => clear u end;\n try match goal with a:_ /\\ _ |- _ => destruct a as (B1,B2) end.\n\nProgram Fixpoint subset (s:t*t|bst s#1 /\\ bst s#2) \n { measure (cardinal2 s) }\n : { Subset s#1 s#2 } + {~Subset s#1 s#2 } :=\n match s with \n  | (Leaf, Leaf) => in_left\n  | (Leaf, Node _ _ _ _) => in_left\n  | (Node _ _ _ _, Leaf) => in_right\n  | (Node l1 x1 r1 h1, Node l2 x2 r2 h2) => \n     match X.compare x1 x2 with \n      | EQ _ => subset (l1,l2) && subset (r1,r2)\n      | LT _ => subset (Node l1 x1 Leaf 0, l2) && subset (r1,s#2)\n      | GT _ => subset (Node Leaf x1 r1 0, r2) && subset (l1,s#2)\n     end\n end.\n\nNext Obligation. (* post Leaf,Leaf *)\n red; auto.\nQed.\n\nNext Obligation. (* post Leaf,Node *)\n red; intros; inv In.\nQed.\n\nNext Obligation. (* post Node,Leaf *)\n intro; assert (In wildcard'0 Leaf) by auto; inv In.\nQed.\n\nNext Obligation. (* pre subset (l1,l2) *)\n inv bst; auto.\nQed.\n\nNext Obligation. (* decr subset (l1,l2) *)\n simpl; omega.\nQed.\n\nNext Obligation. (* pre subset (r1,r2) *)\n inv bst; auto.\nQed.\n\nNext Obligation. (* decr subset (r1,r2) *)\n simpl; omega.\nQed.\n\nNext Obligation. (* post EQ + left + left *)\n clear Heq_anonymous. \n red; intros. \n intuition_in; constructor; order.\nQed.\n\nNext Obligation. (* post EQ + left + right *)\n clear Heq_anonymous.\n unfold Subset in *; contradict H0; intros.\n assert (In a (Node l2 x2 r2 h2)) by auto.\n inv bst; intuition_in; order.\nQed.\n\nNext Obligation. (* post EQ + right + _ *)\n clear Heq_anonymous.\n unfold Subset in *; contradict H; intros.\n assert (In a (Node l2 x2 r2 h2)) by auto.\n inv bst; intuition_in; order.\nQed.\n\nNext Obligation. (* pre subset (Node l1 x1 Leaf 0, l2) *)\n inv bst; auto.\nQed.\n\nNext Obligation. (* decr subset (Node l1 x1 Leaf 0, l2) *)\n simpl; omega.\nQed.\n\nNext Obligation. (* pre subset (r1,s2) *)\n split; auto; inv bst; auto.\nQed.\n\nNext Obligation. (* decr subset (r1,s2) *)\n simpl; omega.\nQed.\n\nNext Obligation. (* post LT + left + left *)\n clear Heq_anonymous.\n unfold Subset in *; intros.\n inv bst; intuition_in; order.\nQed.\n\nNext Obligation. (* post LT + left + right *)\n clear Heq_anonymous.\n unfold Subset in *; contradict H0; intros. \n inv bst; intuition_in; order.\nQed.\n\nNext Obligation. (* post LT + right + _ *)\n clear Heq_anonymous.\n unfold Subset in *; contradict H; intros. \n assert (In a (Node l2 x2 r2 h2)) by (inv In; auto).\n inv bst; intuition_in; order.\nQed.\n\nNext Obligation. (* pre subset (Node Leaf x1 r1 0, r2) *)\n split; auto; inv bst; auto.\nQed.\n\nNext Obligation. (* decr subset (Node Leaf x1 r1 0, r2) *)\n simpl; omega.\nQed.\n\nNext Obligation. (* pre subset (l1,s2) *)\n split; auto; inv bst; auto.\nQed.\n\nNext Obligation. (* decr subset (l1,s2) *)\n simpl; omega.\nQed.\n\nNext Obligation. (* post GT + left + left *)\n unfold Subset in *; intros.\n inv bst; intuition_in; order.\nQed.\n\nNext Obligation. (* post GT + left + right *)\n unfold Subset in *; contradict H0; intros.\n inv bst; intuition_in; order.\nQed.\n\nNext Obligation. (* post GT + right + _ *)\n clear Heq_anonymous.\n unfold Subset in *; contradict H; intros.\n assert (In a (Node l2 x2 r2 h2)) by (inv In; auto).\n inv bst; intuition_in; order.\nQed.\n\nNext Obligation. (* well-founded *)\n  auto with arith.\nDefined.\n\n\n(** * Comparison *)\n\n(** ** Relations [eq] and [lt] over trees *)\n\nDefinition eq : t -> t -> Prop := Equal.\n\nLemma eq_refl : forall s : t, eq s s. \nProof.\n unfold eq, Equal in |- *; intuition.\nQed.\n\nLemma eq_sym : forall s s' : t, eq s s' -> eq s' s.\nProof.\n unfold eq, Equal in |- *; firstorder.\nQed.\n\nLemma eq_trans : forall s s' s'' : t, eq s s' -> eq s' s'' -> eq s s''.\nProof.\n unfold eq, Equal in |- *; firstorder.\nQed.\n\nLemma eq_L_eq :\n forall s s' : t, eq s s' -> L.eq (elements s) (elements s').\nProof.\n unfold eq, Equal, L.eq, L.Equal in |- *; intros.\n generalize (elements_in s a) (elements_in s' a).\n firstorder.\nQed.\n\nLemma L_eq_eq :\n forall s s' : t, L.eq (elements s) (elements s') -> eq s s'.\nProof.\n unfold eq, Equal, L.eq, L.Equal in |- *; intros.\n generalize (elements_in s a) (elements_in s' a).\n firstorder.\nQed.\nHint Resolve eq_L_eq L_eq_eq.\n\nDefinition lt (s1 s2 : t) : Prop := L.lt (elements s1) (elements s2).\n\nDefinition lt_trans (s s' s'' : t) (h : lt s s') \n  (h' : lt s' s'') : lt s s'' := L.lt_trans h h'.\n\nLemma lt_not_eq : forall s s' : t, bst s -> bst s' -> lt s s' -> ~ eq s s'.\nProof.\n unfold lt in |- *; intros; intro.\n apply L.lt_not_eq with (s := elements s) (s' := elements s'); auto.\nQed.\n\n(** * A new comparison algorithm suggested by Xavier Leroy *)\n\n(** ** Enumeration of the elements of a tree *)\n\nInductive enumeration :=\n | End : enumeration\n | More : elt -> tree -> enumeration -> enumeration.\n\n(** [flatten_e e] returns the list of elements of [e] i.e. the list\n    of elements actually compared *)\n \nFixpoint flatten_e (e : enumeration) : list elt := match e with\n  | End => nil\n  | More x t r => x :: elements t ++ flatten_e r\n end.\n\n(** [sorted_e e] expresses that elements in the enumeration [e] are\n    sorted, and that all trees in [e] are binary search trees. *)\n\nInductive In_e (x:elt) : enumeration -> Prop :=\n  | InEHd1 :\n      forall (y : elt) (s : tree) (e : enumeration),\n      X.eq x y -> In_e x (More y s e)\n  | InEHd2 :\n      forall (y : elt) (s : tree) (e : enumeration),\n      In x s -> In_e x (More y s e)\n  | InETl :\n      forall (y : elt) (s : tree) (e : enumeration),\n      In_e x e -> In_e x (More y s e).\n\nInductive sorted_e : enumeration -> Prop :=\n  | SortedEEnd : sorted_e End\n  | SortedEMore :\n      forall (x : elt) (s : tree) (e : enumeration),\n      bst s ->\n      (gt_tree x s) ->\n      sorted_e e ->\n      (forall y : elt, In_e y e -> X.lt x y) ->\n      (forall y : elt,\n       In y s -> forall z : elt, In_e z e -> X.lt y z) ->\n      sorted_e (More x s e).\n\nHint Constructors In_e sorted_e.\n\nLemma elements_app :\n forall (s : tree) (acc : list elt), elements_aux acc s = elements s ++ acc.\nProof.\n simple induction s; simpl in |- *; intuition.\n rewrite H0.\n rewrite H.\n unfold elements; simpl.\n do 2 rewrite H.\n rewrite H0.\n repeat rewrite <- app_nil_end.\n repeat rewrite app_ass; auto.\nQed.\n\nLemma compare_flatten_1 :\n forall (t0 t2 : tree) (t1 : elt) (z : int) (l : list elt),\n elements t0 ++ t1 :: elements t2 ++ l =\n elements (Node t0 t1 t2 z) ++ l.\nProof.\n simpl in |- *; unfold elements in |- *; simpl in |- *; intuition.\n repeat rewrite elements_app.\n repeat rewrite <- app_nil_end.\n repeat rewrite app_ass; auto.\nQed.\n\n(** key lemma for correctness *)\n\nLemma flatten_e_elements :\n forall (x : elt) (l r : tree) (z : int) (e : enumeration),\n elements l ++ flatten_e (More x r e) = elements (Node l x r z) ++ flatten_e e.\nProof.\n intros; simpl.\n apply compare_flatten_1.\nQed.\n\n(** termination of [compare_aux] *)\n\nOpen Scope nat_scope.\n \nFixpoint measure_e_t (s : tree) : nat := match s with\n  | Leaf => 0\n  | Node l _ r _ => 1 + measure_e_t l + measure_e_t r\n end.\n\nFixpoint measure_e (e : enumeration) : nat := match e with\n  | End => 0\n  | More _ s r => 1 + measure_e_t s + measure_e r\n end.\n\n(** [cons t e] adds the elements of tree [t] on the head of \n    enumeration [e]. *)\n\nFixpoint cons s e {struct s} : enumeration := \n match s with \n  | Leaf => e\n  | Node l x r h => cons l (More x r e)\n end.\n\nLemma cons_1 : forall s e, \n  bst s -> sorted_e e ->\n  (forall (x y : elt), In x s -> In_e y e -> X.lt x y) ->\n  sorted_e (cons s e) /\\ \n  measure_e (cons s e) = measure_e_t s + measure_e e /\\\n  flatten_e (cons s e) = elements s ++ flatten_e e.\nProof.\n induction s; simpl; auto.\n clear IHs2; intros.\n inv bst.\n destruct (IHs1 (More t s2 e)); clear IHs1; intuition.\n inversion_clear H6; subst; auto; order.\n simpl in *; omega.\n rewrite H8.\n apply flatten_e_elements.\nQed.\n\nLemma l_eq_cons :\n forall (l1 l2 : list elt) (x y : elt),\n X.eq x y -> L.eq l1 l2 -> L.eq (x :: l1) (y :: l2).\nProof.\n unfold L.eq, L.Equal in |- *; intuition.\n inversion_clear H1; generalize (H0 a); clear H0; intuition.\n apply InA_eqA with x; eauto with *.\n inversion_clear H1; generalize (H0 a); clear H0; intuition.\n apply InA_eqA with y; eauto with *.\nQed.\n\nDefinition measure2 e := measure_e e#1 + measure_e e#2.\n\nObligation Tactic := \n simpl ; intros ; destruct_exists ;  \n unfold measure2; simpl in *; \n try match goal with c:forall e:_,Compare _ _ _ _ |- _ => clear c end;\n try match goal with a:_/\\_|-_=>destruct a as (S1,S2) end; \n try subst; simpl in *.\n\nProgram Fixpoint compare_aux \n (e:enumeration*enumeration|sorted_e e#1 /\\ sorted_e e#2)\n { measure (measure2 e) } : \n Compare L.lt L.eq (flatten_e e#1) (flatten_e e#2) \n :=\n match e with \n | (End,End) => EQ _\n | (End,More _ _ _) => LT _ \n | (More _ _ _, End) => GT _ \n | (More x1 r1 e1, More x2 r2 e2) => \n       match X.compare x1 x2 with \n        | EQ _ => match compare_aux (cons r1 e1, cons r2 e2) with \n             | EQ _ => EQ _\n             | LT _ => LT _\n             | GT _ => GT _\n             end\n        | LT _ => LT _ \n        | GT _ => GT _ \n       end\n end.\n\nNext Obligation. (* post End,End *)\n unfold L.eq, L.Equal; intuition.\nQed.\n\nNext Obligation. (* post End,More *)\n simpl; auto.\nQed.\n\nNext Obligation. (* post More,End *)\n simpl; auto.\nQed.\n\nNext Obligation. (* pre compare_aux (cons r1 e1, cons r2 e2) *)\n inversion S1; inversion S2; subst.\n  destruct (cons_1 r1 e1) as (H,_); auto.\n  destruct (cons_1 r2 e2) as (H',_); auto.\nQed.\n\nNext Obligation. (* decr compare_aux (cons r1 e1, cons r2 e2) *)\n inversion S1; inversion S2; subst.\n destruct (cons_1 r1 e1) as (_,(H,_)); auto.\n destruct (cons_1 r2 e2) as (_,(H0,_)); auto.\n rewrite H; rewrite H0; simpl; omega.\nQed.\n\nNext Obligation. (* post compare_aux (cons r1 e1, cons r2 e2) = EQ *)\n clear Heq_anonymous0 Heq_anonymous compare_aux.\n subst; simpl in *.\n inversion S1; inversion S2; subst.\n destruct (cons_1 r1 e1) as (_,(_,H)); auto.\n destruct (cons_1 r2 e2) as (_,(_,H0)); auto.\n rewrite <- H; rewrite <- H0; simpl.\n apply l_eq_cons; auto.\nQed.\n\nNext Obligation. (* post compare_aux (cons r1 e1, cons r2 e2) = LT *)\n clear Heq_anonymous0 Heq_anonymous compare_aux.\n subst; simpl in *.\n inversion S1; inversion S2; subst.\n destruct (cons_1 r1 e1) as (_,(_,H)); auto.\n destruct (cons_1 r2 e2) as (_,(_,H0)); auto.\n rewrite <- H; rewrite <- H0; simpl.\n apply L.lt_cons_eq; auto.\nQed.\n\nNext Obligation. (* post compare_aux (cons r1 e1, cons r2 e2) = GT *)\n clear Heq_anonymous0 Heq_anonymous compare_aux.\n subst; simpl in *.\n inversion S1; inversion S2; subst.\n destruct (cons_1 r1 e1) as (_,(_,H)); auto.\n destruct (cons_1 r2 e2) as (_,(_,H0)); auto.\n rewrite <- H; rewrite <- H0; simpl.\n apply L.lt_cons_eq; auto.\nQed.\n\nNext Obligation. (* post X.compare x1 x2 = LT *)\n simpl; auto.\nQed.\n\nNext Obligation. (* post X.compare x1 x2 = GT *)\n simpl; auto.\nQed.\n\nNext Obligation. (* well-founded *)\n  auto with arith.\nDefined.\n\nOpaque compare_aux.\n\nProgram Definition compare (s1:t|bst s1)(s2:t|bst s2) : \n Compare lt eq s1 s2 := \n match compare_aux (cons s1 End, cons s2 End) with \n  | EQ _ => EQ _ \n  | LT _ => LT _ \n  | GT _ => GT _ \n end.\n\nNext Obligation. (* pre compare_aux *)\n destruct (cons_1 s1 End); auto; try inversion 2.\n destruct (cons_1 s2 End); auto; try inversion 2.\nQed.\n\nNext Obligation. (* post EQ *)\n destruct (cons_1 s1 End) as (_,(_,H')); auto; try inversion 2.\n destruct (cons_1 s2 End) as (_,(_,H0')); auto; try inversion 2.\n simpl in *; rewrite <- app_nil_end in *.\n apply L_eq_eq; rewrite <- H0'; rewrite <- H'; auto.\nQed.\n\nNext Obligation. (* post LT *)\n destruct (cons_1 s1 End) as (_,(_,H')); auto; try inversion 2.\n destruct (cons_1 s2 End) as (_,(_,H0')); auto; try inversion 2.\n simpl in *; rewrite <- app_nil_end in *.\n red; intros; rewrite <- H0'; rewrite <- H'; auto.\nQed.\n\nNext Obligation. (* post GT *)\n destruct (cons_1 s1 End) as (_,(_,H')); auto; try inversion 2.\n destruct (cons_1 s2 End) as (_,(_,H0')); auto; try inversion 2.\n simpl in *; rewrite <- app_nil_end in *.\n red; intros; rewrite <- H0'; rewrite <- H'; auto.\nQed.\n\nTransparent compare_aux.\n\nClose Scope nat_scope.\n\n(** * Equality test *)\n\nOpaque compare.\n\nProgram Definition equal (s1:t|bst s1)(s2:t|bst s2) : bool := \n match compare s1 s2 with \n  | EQ _ => true\n  | LT _ => false \n  | GT _ => false \n end.\n\nTransparent compare.\n\nLemma equal_1 : forall s1 s2 (Hs1:bst s1)(Hs2:bst s2),  \n Equal s1 s2 -> equal (exist _ s1 Hs1) (exist _ s2 Hs2) = true.\nProof.\nunfold equal; intros.\ndestruct_call compare; simpl in *; auto.\ngeneralize (lt_not_eq _ _ Hs1 Hs2 l); auto.\nassert (eq s2 s1) by (apply eq_sym; auto).\ngeneralize (lt_not_eq _ _ Hs2 Hs1 l); auto.\nQed.\n\nLemma equal_2 : forall s1 s2 (Hs1:bst s1)(Hs2:bst s2),  \n equal (exist _ s1 Hs1) (exist _ s2 Hs2) = true -> Equal s1 s2.\nProof.\nunfold equal; intros.\ndestruct_call compare; simpl in *; auto; discriminate.\nQed.\n\nEnd Raw.\n\n(** * Encapsulation\n\n   Now, in order to really provide a functor implementing [S], we \n   need to encapsulate everything into a type of balanced binary search trees. *)\n\nModule IntMake (I:Int)(X: OrderedType) <: S with Module E := X.\n\n Module E := X.\n Module Raw := Raw I X. \n\n Record bbst := Bbst {this :> Raw.t; is_bst : Raw.bst this; is_avl: Raw.avl this}.\n Definition t := bbst. \n Definition elt := E.t.\n \n Definition In (x : elt) (s : t) : Prop := Raw.In x s.\n Definition Equal (s s':t) : Prop := forall a : elt, In a s <-> In a s'.\n Definition Subset (s s':t) : Prop := forall a : elt, In a s -> In a s'.\n Definition Empty (s:t) : Prop := forall a : elt, ~ In a s.\n Definition For_all (P : elt -> Prop) (s:t) : Prop := forall x, In x s -> P x.\n Definition Exists (P : elt -> Prop) (s:t) : Prop := exists x, In x s /\\ P x.\n  \n Lemma In_1 : forall (s:t)(x y:elt), E.eq x y -> In x s -> In y s. \n Proof. intro s; exact (Raw.In_1 s). Qed.\n \n Definition mem (x:elt)(s:t) : bool := Raw.mem x s.\n\n Definition empty : t := Bbst _ Raw.empty_bst Raw.empty_avl.\n Definition is_empty (s:t) : bool := Raw.is_empty s.\n Definition singleton (x:elt) : t := Bbst _ (Raw.singleton_bst x) (Raw.singleton_avl x).\n Definition add (x:elt)(s:t) : t := \n   Bbst _ (Raw.add_bst s x (is_bst s) (is_avl s)) \n          (Raw.add_avl s x (is_avl s)). \n Definition remove (x:elt)(s:t) : t := \n   Bbst _ (Raw.remove_bst s x (is_bst s) (is_avl s)) \n          (Raw.remove_avl s x (is_avl s)). \n Definition inter (s s':t) : t := \n   Bbst _ (Raw.inter_bst _ _ (is_bst s) (is_avl s) (is_bst s') (is_avl s'))  \n          (Raw.inter_avl _ _ (is_avl s) (is_avl s')).\n Definition diff (s s':t) : t := \n   Bbst _ (Raw.diff_bst _ _ (is_bst s) (is_avl s) (is_bst s') (is_avl s'))  \n          (Raw.diff_avl _ _ (is_avl s) (is_avl s')).\n Definition elements (s:t) : list elt := Raw.elements s.\n Definition min_elt (s:t) : option elt := Raw.min_elt s.\n Definition max_elt (s:t) : option elt := Raw.max_elt s.\n Definition choose (s:t) : option elt := Raw.choose s.\n Definition fold (B : Type) (f : elt -> B -> B) (s:t) : B -> B := Raw.fold f s. \n Definition cardinal (s:t) : nat := Raw.cardinal s.\n Definition filter (f : elt -> bool) (s:t) : t := \n   Bbst _ (Raw.filter_bst f _ (is_bst s) (is_avl s))\n          (Raw.filter_avl f _ (is_avl s)). \n Definition for_all (f : elt -> bool) (s:t) : bool := Raw.for_all f s.\n Definition exists_ (f : elt -> bool) (s:t) : bool := Raw.exists_ f s.\n Definition partition (f : elt -> bool) (s:t) : t * t :=\n   let p := Raw.partition f s in\n   (Bbst (fst p) (Raw.partition_bst_1 f _ (is_bst s) (is_avl s)) \n                 (Raw.partition_avl_1 f _ (is_avl s)),\n    Bbst (snd p) (Raw.partition_bst_2 f _ (is_bst s) (is_avl s)) \n                 (Raw.partition_avl_2 f _ (is_avl s))).\n\n Opaque Raw.union Raw.subset Raw.compare.\n\n Obligation Tactic := simpl ; intros ; destruct_exists ; simpl in * ; try subst.\n\n Program Definition union (s s':t) : t :=\n   Bbst (Raw.union (s.(this),s'.(this))) _ _.\n\n Next Obligation. destruct s; destruct s'; auto. Qed.\n Next Obligation. destruct_call Raw.union; simpl; tauto. Qed.\n Next Obligation. destruct_call Raw.union; simpl; tauto. Qed.\n\n Definition equal (s s':t) : bool := \n  Raw.equal (exist _ _ s.(is_bst)) (exist _ _ s'.(is_bst)).\n\n Program Definition subset (s s':t) : bool := \n  if Raw.subset (s.(this),s'.(this)) then true else false.\n\n Next Obligation. destruct s; destruct s'; auto. Qed.\n\n Definition eq (s s':t) : Prop := Raw.eq s s'.\n Definition lt (s s':t) : Prop := Raw.lt s s'.\n\n Program Definition compare (s s':t) : Compare lt eq s s' := \n  match Raw.compare (s:Raw.t) (s':Raw.t) with \n   | LT _ => LT _ \n   | EQ _ => EQ _ \n   | GT _ => GT _\n  end.\n\n Next Obligation. destruct s; auto. Qed. \n Next Obligation. destruct s'; auto. Qed.\n Next Obligation. auto. Qed.\n Next Obligation. auto. Qed.\n Next Obligation. auto. Qed. (* COUTEUX si compare_aux est transparent !! *)\n\n (* specs *)\n Section Specs. \n Variable s s' s'': t. \n Variable x y : elt.\n\n Hint Resolve is_bst is_avl.\n \n Lemma mem_1 : In x s -> mem x s = true. \n Proof. exact (Raw.mem_1 s x (is_bst s)). Qed.\n Lemma mem_2 : mem x s = true -> In x s.\n Proof. exact (Raw.mem_2 s x). Qed.\n\n Lemma equal_1 : Equal s s' -> equal s s' = true.\n Proof. exact (Raw.equal_1 s s' (is_bst s) (is_bst s')). Qed.\n Lemma equal_2 : equal s s' = true -> Equal s s'.\n Proof. exact (Raw.equal_2 s s' (is_bst s) (is_bst s')). Qed.\n\n Lemma subset_1 : Subset s s' -> subset s s' = true.\n Proof. \n unfold subset; destruct_call Raw.subset; simpl in *; intuition.\n Qed.\n\n Lemma subset_2 : subset s s' = true -> Subset s s'.\n Proof. \n unfold subset; destruct_call Raw.subset; simpl in *; intuition discriminate.\n Qed.\n\n Lemma empty_1 : Empty empty.\n Proof. exact Raw.empty_1. Qed.\n\n Lemma is_empty_1 : Empty s -> is_empty s = true.\n Proof. exact (Raw.is_empty_1 s). Qed.\n Lemma is_empty_2 : is_empty s = true -> Empty s. \n Proof. exact (Raw.is_empty_2 s). Qed.\n \n Lemma add_1 : E.eq x y -> In y (add x s).\n Proof. \n unfold add, In; simpl; rewrite Raw.add_in; auto.\n Qed.\n\n Lemma add_2 : In y s -> In y (add x s).\n Proof.\n unfold add, In; simpl; rewrite Raw.add_in; auto.\n Qed.\n\n Lemma add_3 : ~ E.eq x y -> In y (add x s) -> In y s. \n Proof. \n unfold add, In; simpl; rewrite Raw.add_in; intuition auto with exfalso sets.\n Qed.\n\n Lemma remove_1 : E.eq x y -> ~ In y (remove x s).\n Proof. \n unfold remove, In; simpl; rewrite Raw.remove_in; intuition.\n Qed.\n\n Lemma remove_2 : ~ E.eq x y -> In y s -> In y (remove x s).\n Proof. \n unfold remove, In; simpl; rewrite Raw.remove_in; intuition.\n Qed.\n\n Lemma remove_3 : In y (remove x s) -> In y s.\n Proof. \n unfold remove, In; simpl; rewrite Raw.remove_in; intuition.\n Qed.\n\n Lemma singleton_1 : In y (singleton x) -> E.eq x y. \n Proof. exact (Raw.singleton_1 x y). Qed.\n Lemma singleton_2 : E.eq x y -> In y (singleton x). \n Proof. exact (Raw.singleton_2 x y). Qed.\n\n Lemma union_1 : In x (union s s') -> In x s \\/ In x s'.\n Proof.\n unfold union, In; simpl.\n destruct_call Raw.union; simpl in *.\n decompose [and] a.\n destruct (H2 x); auto.\n Qed.\n\n Lemma union_2 : In x s -> In x (union s s'). \n Proof.\n unfold union, In; simpl.\n destruct_call Raw.union; simpl in *.\n decompose [and] a.\n destruct (H2 x); auto.\n Qed.\n\n Lemma union_3 : In x s' -> In x (union s s').\n Proof.\n unfold union, In; simpl.\n destruct_call Raw.union; simpl in *.\n decompose [and] a.\n destruct (H2 x); auto.\n Qed.\n\n Lemma inter_1 : In x (inter s s') -> In x s.\n Proof.\n unfold inter, In; simpl; rewrite Raw.inter_in; intuition.\n Qed.\n\n Lemma inter_2 : In x (inter s s') -> In x s'.\n Proof. \n unfold inter, In; simpl; rewrite Raw.inter_in; intuition.\n Qed.\n\n Lemma inter_3 : In x s -> In x s' -> In x (inter s s').\n Proof. \n unfold inter, In; simpl; rewrite Raw.inter_in; intuition.\n Qed.\n \n Lemma diff_1 : In x (diff s s') -> In x s. \n Proof. \n unfold diff, In; simpl; rewrite Raw.diff_in; intuition.\n Qed.\n\n Lemma diff_2 : In x (diff s s') -> ~ In x s'.\n Proof. \n unfold diff, In; simpl; rewrite Raw.diff_in; intuition.\n Qed.\n\n Lemma diff_3 : In x s -> ~ In x s' -> In x (diff s s').\n Proof. \n unfold diff, In; simpl; rewrite Raw.diff_in; intuition.\n Qed.\n \n Lemma fold_1 : forall (A : Type) (i : A) (f : elt -> A -> A),\n      fold A f s i = fold_left (fun a e => f e a) (elements s) i.\n Proof. \n unfold fold, elements; intros; apply Raw.fold_1; auto.\n Qed.\n\n Lemma cardinal_1 : cardinal s = length (elements s).\n Proof. \n unfold cardinal, elements; intros; apply Raw.cardinal_elements_1; auto.\n Qed.\n\n Section Filter.\n Variable f : elt -> bool.\n\n Lemma filter_1 : compat_bool E.eq f -> In x (filter f s) -> In x s. \n Proof. \n intro; unfold filter, In; simpl; rewrite Raw.filter_in; intuition.\n Qed.\n\n Lemma filter_2 : compat_bool E.eq f -> In x (filter f s) -> f x = true. \n Proof. \n intro; unfold filter, In; simpl; rewrite Raw.filter_in; intuition.\n Qed.\n\n Lemma filter_3 : compat_bool E.eq f -> In x s -> f x = true -> In x (filter f s).\n Proof. \n intro; unfold filter, In; simpl; rewrite Raw.filter_in; intuition.\n Qed.\n\n Lemma for_all_1 : compat_bool E.eq f -> For_all (fun x => f x = true) s -> for_all f s = true.\n Proof. exact (Raw.for_all_1 f s). Qed.\n Lemma for_all_2 : compat_bool E.eq f -> for_all f s = true -> For_all (fun x => f x = true) s.\n Proof. exact (Raw.for_all_2 f s). Qed.\n\n Lemma exists_1 : compat_bool E.eq f -> Exists (fun x => f x = true) s -> exists_ f s = true.\n Proof. exact (Raw.exists_1 f s). Qed.\n Lemma exists_2 : compat_bool E.eq f -> exists_ f s = true -> Exists (fun x => f x = true) s.\n Proof. exact (Raw.exists_2 f s). Qed.\n\n Lemma partition_1 : compat_bool E.eq f -> \n  Equal (fst (partition f s)) (filter f s).\n Proof.\n unfold partition, filter, Equal, In; simpl ;intros H a.\n rewrite Raw.partition_in_1; auto.\n rewrite Raw.filter_in; intuition.\n Qed.\n\n Lemma partition_2 : compat_bool E.eq f -> \n  Equal (snd (partition f s)) (filter (fun x => negb (f x)) s).\n Proof.\n unfold partition, filter, Equal, In; simpl ;intros H a.\n rewrite Raw.partition_in_2; auto.\n rewrite Raw.filter_in; intuition.\n rewrite H2; auto.\n destruct (f a); auto.\n repeat red; intros; f_equal.\n rewrite (H _ _ H0); auto.\n Qed.\n\n End Filter.\n\n Lemma elements_1 : In x s -> InA E.eq x (elements s).\n Proof. \n unfold elements, In; rewrite Raw.elements_in; auto.\n Qed.\n\n Lemma elements_2 : InA E.eq x (elements s) -> In x s.\n Proof. \n unfold elements, In; rewrite Raw.elements_in; auto.\n Qed.\n\n Lemma elements_3 : sort E.lt (elements s).\n Proof. exact (Raw.elements_sort _ (is_bst s)). Qed.\n\n Lemma elements_3w : NoDupA E.eq (elements s).\n Proof. exact (Raw.elements_nodup _ (is_bst s)). Qed.\n\n Lemma min_elt_1 : min_elt s = Some x -> In x s. \n Proof. exact (Raw.min_elt_1 s x). Qed.\n Lemma min_elt_2 : min_elt s = Some x -> In y s -> ~ E.lt y x.\n Proof. exact (Raw.min_elt_2 s x y (is_bst s)). Qed.\n Lemma min_elt_3 : min_elt s = None -> Empty s.\n Proof. exact (Raw.min_elt_3 s). Qed.\n\n Lemma max_elt_1 : max_elt s = Some x -> In x s. \n Proof. exact (Raw.max_elt_1 s x). Qed.\n Lemma max_elt_2 : max_elt s = Some x -> In y s -> ~ E.lt x y.\n Proof. exact (Raw.max_elt_2 s x y (is_bst s)). Qed.\n Lemma max_elt_3 : max_elt s = None -> Empty s.\n Proof. exact (Raw.max_elt_3 s). Qed.\n\n Lemma choose_1 : choose s = Some x -> In x s.\n Proof. exact (Raw.choose_1 s x). Qed.\n Lemma choose_2 : choose s = None -> Empty s.\n Proof. exact (Raw.choose_2 s). Qed.\n Lemma choose_3 : choose s = Some x -> choose s' = Some y ->\n  Equal s s' -> E.eq x y.\n Proof.\n  exact (@Raw.choose_3 _ _ (is_bst s) (is_avl s) (is_bst s') (is_avl s') x y).\n Qed.\n\n Lemma eq_refl : eq s s. \n Proof. exact (Raw.eq_refl s). Qed.\n Lemma eq_sym : eq s s' -> eq s' s.\n Proof. exact (Raw.eq_sym s s'). Qed.\n Lemma eq_trans : eq s s' -> eq s' s'' -> eq s s''.\n Proof. exact (Raw.eq_trans s s' s''). Qed.\n  \n Lemma lt_trans : lt s s' -> lt s' s'' -> lt s s''.\n Proof. exact (Raw.lt_trans s s' s''). Qed.\n Lemma lt_not_eq : lt s s' -> ~eq s s'.\n Proof. exact (Raw.lt_not_eq _ _ (is_bst s) (is_bst s')). Qed.\n\n Transparent Raw.union Raw.subset Raw.compare.\n\n End Specs.\n\n Definition eq_dec : forall s s' : t, {eq s s'} + {~ eq s s'}.\n Proof.\n   intros.\n   case_eq (equal s s'); intro H; [left|right].\n   apply equal_2; auto.\n   intro H'; rewrite equal_1 in H; auto; discriminate.\n Defined.\n\nEnd IntMake.\n\n(* For concrete use inside Coq, we propose an instantiation of [Int] by [Z]. *)\n\nModule Make (X: OrderedType) <: S with Module E := X\n :=IntMake(Z_as_Int)(X).\n\n\n", "meta": {"author": "coq-contribs", "repo": "fsets", "sha": "18b21173b85da4b89892d2a90fe213717aa0ee6c", "save_path": "github-repos/coq/coq-contribs-fsets", "path": "github-repos/coq/coq-contribs-fsets/fsets-18b21173b85da4b89892d2a90fe213717aa0ee6c/FSetAVL_prog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.6992804294431241}}
{"text": "Require Import Substitution Containers FiniteTypes Arith JMeq List.\nRequire Import MyTactics ZArith.\n\n Set Implicit Arguments.\n\n(** Containers for binary trees *)\n\n Section Preliminaries.\n  \n  \n   \n\n Inductive  Tree (A : Type) : Type :=\n  | Leaf : A -> Tree A\n  | Fork : Tree A -> Tree A -> Tree A.\n\n Definition tswap A (t : Tree A) : Tree A :=\n   match t with\n    | Leaf a =>  Leaf a\n    | Fork l r => Fork r l\n   end.\n\n Lemma swap_swap A (t : Tree A) : tswap (tswap t) = t.\n   destruct t; simpl; trivial.\n Qed.\n\n\n  Fixpoint  flatten A (t : Tree A) :  list A :=\n    match t with\n    | Leaf a =>  a::nil\n    | Fork l r => flatten l ++ flatten r\n   end.\n\n  Fixpoint rotRight A (t : Tree A) :=\n    match t with\n    | Fork (Fork a b) x => Fork (rotRight a) (Fork (rotRight b) (rotRight x))\n    | xs => xs\n    end.\n \n   Fixpoint rotLeft A (t : Tree A) :=\n    match t with\n    | Fork a (Fork b x) => Fork (Fork (rotLeft a) (rotLeft b)) (rotLeft x)\n    | xs => xs\n    end. (* *)\n\n   Fixpoint mirror A (t : Tree A) :=\n    match t with\n    | Fork a b => Fork (mirror a) (mirror  b) \n    | xs => xs\n    end.\n\n\n  (* map and fold *)\n   Fixpoint mapTree A B (f : A -> B) (t : Tree A) :=\n     match t with\n     | Leaf a => Leaf (f a)\n     | Fork l r => Fork (mapTree f l) (mapTree f r)\n     end.\n \n   Fixpoint foldTree A B (f : A  -> B) (g : B -> B -> B) (t : Tree A) : B :=\n     match t with\n     | Leaf a => f a\n     | Fork l r => g (foldTree f g l) (foldTree f g r)\n     end.\n\n End Preliminaries.\n\n Section Trees.\n\n (** binary trees *)\n  Inductive cTreeS : Set :=\n  | sleaf : cTreeS\n  | snode : cTreeS -> cTreeS -> cTreeS.\n\n  Inductive cTreeP : cTreeS -> Set :=\n  | phere  : cTreeP sleaf\n  | pleft  : forall (l r: cTreeS) ,  cTreeP l ->  cTreeP (snode l r)\n  | pright : forall (l r: cTreeS) (q : cTreeP r), cTreeP (snode l r). \n\n (* CTreeS hace decidable equality  *\n  Definition  cTreeS_dec : forall (x y : cTreeS), {x = y}+{x <> y}.\n   induction x; destruct y.\n   left; trivial.\n   right; discriminate.\n   right; discriminate.\n   destruct (IHx1 y1); subst.\n   destruct (IHx2 y2); subst.\n   left; trivial.\n   right; congruence.\n   right; congruence.\n  Defined. *)\n\n  Inductive SnodeS (x y : cTreeS) : cTreeP (snode x y) -> Set :=\n  | isl : forall z : cTreeP x, SnodeS (pleft y z)\n  | isr : forall z : cTreeP y, SnodeS (pright x z).\n\n  Inductive SnodeHere : cTreeP sleaf -> Set :=\n  | justHere : SnodeHere phere.\n\n  Definition snodeHere (i : cTreeP sleaf) : SnodeHere i :=\n   match i in cTreeP t return match t return cTreeP t -> Set with\n                              | sleaf => SnodeHere\n                              | _ => fun _ => unit\n                            end i with\n   | phere => justHere\n   | _ => tt\n   end.\n\n  Lemma onlyHere : forall x : cTreeP sleaf, x = phere.\n   intro x; destruct (snodeHere x); trivial.\n  Qed.\n \n  Definition snodeS (x y : cTreeS) (i : cTreeP (snode x y)) : SnodeS i :=\n   match i in cTreeP t return match t return cTreeP t -> Set with\n                              | sleaf => fun _ => unit\n                              | _ => @SnodeS _ _\n                            end i with\n   | pleft _ _ t => isl _ t\n   | pright _ _ t => isr _ t\n   | _ => tt\n   end. \n  \n  Definition ctree := ucont  cTreeP.\n\n Section leaf_and_fork.\n\n   Variable X : Type.\n \n   Definition noSleaf (x : X) :  cTreeP sleaf -> X :=\n     fun i => match snodeHere i with\n            | _ => x\n            end.\n \n   Definition cleaf x := uext ctree sleaf (noSleaf x).\n\n   Definition caseTreeP  (x y : cTreeS) (f : cTreeP x -> X) (g : cTreeP y -> X) : cTreeP (snode x y) -> X :=\n        fun i => match snodeS i with\n                   | isl  t => f t\n                   | isr t => g t\n                   end.\n \n   Definition cfork (x: X) (a b : Ext ctree X) : Ext ctree X :=\n      match a, b with\n     | uext x F,uext y G => \n         uext ctree (snode x y) (caseTreeP F G)\n     end.\n  \n End leaf_and_fork.\n \n \n  (** swapping the nodes in binary trees *) \n  Definition swapS (x : cTreeS ) :=\n  match x with\n  | sleaf => sleaf\n  | snode l r => snode r l\n  end.\n\n (** the shape map is involutinve *)\n  Lemma swap_inv : forall a, swapS (swapS a) = a.\n   induction a; simpl; auto.\n  Qed.\n\n (** position map for swap  *)\n  Definition Pmirr  (a :cTreeS) :  cTreeP a -> cTreeP (swapS a) :=\n   match a as c return (cTreeP c -> cTreeP (swapS c)) with\n   | sleaf => fun H : cTreeP sleaf => H\n   | snode a1 a2 =>\n      fun x : cTreeP (snode a1 a2) =>\n          match snodeS x with\n          | isl z => pright a2 z\n          | isr z => pleft a1 z\n          end\n   end. \n\n   Definition cmirP (a  : cTreeS) :  cTreeP (swapS a) ->  cTreeP a :=\n   match a as c return (cTreeP (swapS c) -> cTreeP c) with\n   | sleaf => fun _ : cTreeP (swapS sleaf) => phere\n   | snode a1 a2 => fun b0 : cTreeP (swapS (snode a1 a2)) => Pmirr b0\n   end.\n\n   (** the swap morphism *)\n   Definition cswap : cmr ctree ctree :=\n     uCmr  (ucont cTreeP) (ucont cTreeP) swapS cmirP.\n\n (* ====================================================================================*)\n   (**  Mirroring a binary tree  *)\n     Fixpoint mirrorS (x : cTreeS ) :=\n       match x with\n       | sleaf => sleaf\n       | snode l r => snode (mirrorS r) (mirrorS l)\n      end.\n\n    Lemma mirror1_inv : forall a, mirrorS (mirrorS a) = a.\n      induction a; simpl; auto. rewrite IHa1. rewrite IHa2; trivial.\n    Qed.\n\n\n  Fixpoint cmirrP a : cTreeP (mirrorS a) -> cTreeP  a := \n   match a as c return (cTreeP (mirrorS c) -> cTreeP c) with\n   | sleaf => fun H : cTreeP sleaf => H\n   | snode a1 a2 => fun x : cTreeP  (mirrorS (snode a1 a2)) =>\n                      match snodeS x with\n                      | isl z => pright a1 (cmirrP _ z)\n                      | isr z => pleft a2  (cmirrP _ z)\n                      end\n   end.\n  \n  (** The container morphism for mirror *)\n   Definition cmirror : cmr ctree ctree :=\n     uCmr  (ucont cTreeP) (ucont cTreeP) mirrorS cmirrP.\n \n  (* we can now prove that this is involutive*)\n  Lemma mirr_mir_ok a1 a2 (x : cTreeP (snode (mirrorS (mirrorS a1)) (mirrorS (mirrorS a2))))\n     (y : cTreeP (snode  a1 a2)) : JMeq x y ->  match (snodeS x) , (snodeS y) with\n                                  | isl p1 , isl q => JMeq p1 q\n                                  | isr p1 , isr q => JMeq p1 q\n                                  | _ , _  => False\n                                  end.\n      intros a1 a2. rewrite (mirror1_inv a1). rewrite (mirror1_inv a2).\n      intros. elim H.  destruct (snodeS x); auto.\n   Qed.\n\n   Lemma mirPos_ok :\n      forall (a : cTreeS) (p0 : cTreeP (comp mirrorS mirrorS a))\n        (p1 : cTreeP (id cTreeS a)),\n           JMeq p0 p1 -> comp (cmirrP a) (cmirrP (mirrorS a)) p0 = p1.\n   Proof.\n    intros. unfold comp. induction a; simpl in *. elim H. trivial.\n    generalize ( mirr_mir_ok H  ). \n    destruct ( snodeS p0 ); simpl.\n    destruct (snodeS p1); simpl in *.  \n    intro H0; rewrite (IHa1 z z0 H0); trivial.\n    intros H0; destruct H0. destruct (snodeS p1).\n    intros H0; destruct H0. intros. \n    rewrite (IHa2 z z0 H0); trivial.\n Qed.\n  \n  (* mirroring binary trees in involutive*)\n  Lemma cmir_inv :  Eqmor (m_comp cmirror cmirror) (idm ctree).\n  Proof.\n     contInitialize; \n      try (exact  mirror1_inv).  intros. \n      repeat ( match goal with\n      | [ H : JMeq ?p ?p1 |-  context[cmirrP ?a (cmirrP (mirrorS ?a) ?p)]]  => \n              let mrp := constr:(mirPos_ok H) in apply mrp\n       | |- context[comp] => unfold comp\n      end). \n  Qed.\n\n\n (* ============================================================================*)\n\n (* laborious container proof that  mirror involutive *) \n (* Lemma cmir_inv :  Eqmor (m_comp cmirror cmirror) (idm ctree).\n Proof.\n   unfold m_comp; unfold cmirror; unfold idm.\n   unfold comp; unfold id;\n   apply morq; simpl. \n   exact  mirr_inv . \n   intros. destruct a;  simpl in p0.\n   elim  H. simpl.\n   destruct (snodeHere p0); trivial.\n   simpl in p0.  elim H.  simpl.\n   destruct (snodeS p0); trivial.\n Qed. *)\n\n (** flattening a tree into a list  *)\n  Fixpoint Sum (s : cTreeS ) : nat :=\n   match s with\n   | sleaf => 1\n   | snode l r => Sum l + Sum r\n   end.\n\n  Fixpoint cflatten_p (s : cTreeS) :  Fin (Sum s) -> cTreeP s :=\n   match s as e return Fin (Sum e) -> cTreeP e with\n   | sleaf => fun _ => phere\n   | snode l r => fun i => match (finsplit  (Sum l) (Sum r)  i) with\n                           | is_inl i => pleft r (cflatten_p l i)\n                           | is_inr j => pright l (cflatten_p r j)\n                           end\n   end.         \n\n  (** the flatten morphism for data trees  *)         \n  Definition ctflat :=\n      uCmr (ucont cTreeP) (ucont Fin) Sum cflatten_p.\n\n Fixpoint cflatten_inv (s : cTreeS) :  cTreeP s ->  Fin (Sum s)  :=\n   match s as e return cTreeP e ->  Fin (Sum e) with\n   | sleaf => fun _ => (fz _)\n   | snode l r => fun i => match (snodeS (x := l) (y := r)   i) with\n                           | isl  i => fin_inl (Sum r) (cflatten_inv  i)\n                           | isr  j => fin_inr (Sum l) (cflatten_inv  j)\n                           end\n   end.  \n  \n (* cTreePs is isomorphic to Fin (Sum s) *)\nLemma cflattL  (s : cTreeS) (i : cTreeP s) : cflatten_p _ (cflatten_inv i) = i.    \n  Proof.\n    induction s; simpl.  intro snh; destruct (snodeHere snh); trivial.\n    intro slr.   destruct (snodeS slr); FSimpl. \n    rewrite (IHs1 z); trivial.\n    rewrite (IHs2 z); trivial.\n  Qed.\n\n Lemma cflattInvL  (s : cTreeS) (i : Fin (Sum s)) : cflatten_inv  (cflatten_p _ i) = i.    \n  Proof.\n    induction s as [ | bb IHbb cc IHcc ];  intros; simpl in *. FSimpl. \n    destruct (finsplit _ _ i); simpl.\n    rewrite (IHbb i); trivial.\n    rewrite (IHcc j); trivial.\n Qed.\n(*\n\n*) \n\n    \n\n\n  Section treeFold.\n  (* container fold for binary trees  *)\n\n     Section tfoldSmap.\n     (* The shape map for the folds *)\n     Variables (S' A : Type) (a0 : S' -> A) (f0 : S' * (A * A) -> A).\n\n     Fixpoint tld (n : cTreeS) (s  :S') {struct n} : A :=\n       match n with\n       | sleaf => a0 s\n       | snode l r => f0 (s , (tld l s, tld r s))\n       end.\n\n     End tfoldSmap.\n\n     Section cTreeFolds.\n\n     (* fold on contaienrs for trees  -- this is not correct! *)\n     Variables (S' A : Ucontainer)\n             (a : cmr S' A)\n             (F : cmr (cont_prod S' (cont_prod A A)) A).\n\n     Definition tGenfold : cmr (cont_prod S' (ucont cTreeP)) A.\n       refine (uCmr ( cont_prod S' (ucont cTreeP)) A \n                (fun sa =>  tld (v a) (v F) (snd sa) (fst sa ) ) _ ); simpl.\n       destruct a0; simpl.\n       induction c; simpl in *.\n       exact (fun i =>  inl (cTreeP sleaf) (g a s i)).\n       intro i; destruct (g F  (s, (tld (v a) (v F) c1 s, \n                         tld (v a) (v F) c2 s)) i);\n       simpl in *. exact (inl (cTreeP (snode c1 c2)) p).\n       destruct p as [p1 | p2].\n       destruct (IHc1 p1) as [l1 | l2].\n       exact (inl ( cTreeP (snode c1 c2)) l1).\n       exact (inr ( p S' s) (pleft _ l2)).\n       destruct (IHc2 p2) as [l1 | l2].\n       exact (inl (cTreeP (snode c1 c2)) l1).\n       exact (inr ( p S' s) (pright _ l2)).\n     Defined.\n\n    End  cTreeFolds. \n\n End treeFold.\n \n End Trees.\n\n \n (* Exporting Notation and tactics *)\n\n  Ltac treeDest_aux := \n     (* let treeDest_aux a :=\n           match goal with\n           | [ p0 : cTreeP (comp mirrorS mirrorS a) ,\n                p1 : cTreeP (id cTreeS a) |- _] =>\n             match goal with \n             | [ _ : JMeq p0 p1 |- _ ] => \n                  let mirpos := constr:(mirPos_ok _ p0 p1 _) in\n                    rewrite mirpos\n             end\n           end in *)\n    match goal with\n    | |- forall _, _ => intros\n    | |- context[comp] => unfold comp\n      (* this rewrite is for shapes *)\n    |  x : cTreeP (snode _ _  ) |- context [?i] => \n         match x with\n         | i =>  let H := constr:(snodeS x) in destruct H\n          end\n    |  x : cTreeP sleaf |- context [?i] => \n         match x with\n         | i =>   let H := constr:(snodeHere x) in destruct H\n         end\n    | |- context [swapS (swapS ?i)] =>\n           let Eq := constr:(swap_inv i) in\n             first [rewrite Eq in * ] (*| rewrite <- Eq in *] *)\n    | |- context [mirrorS (mirrorS ?i)] =>\n           let Eq := constr:(mirror1_inv i) in\n             first [rewrite Eq in *] (* | rewrite <- Eq in *] *)\n    | [ H : JMeq ?p ?p1 |-  context[cmirrP ?a (cmirrP (mirrorS ?a) ?x)]]  => \n              let mrp := constr:(mirPos_ok H) in apply mrp\n    end.\n\n  Ltac rewr_simpl :=\n      match goal with\n      | a : cTreeS |- _ =>\n          match goal with\n          | id : context [a] |- _ => destruct a; simpl in *\n          end\n      end.\n\n (* *)\n  Ltac JMeq_elim :=\n    match goal with\n    | x : ?A , y : ?A |- _ =>\n         match goal with\n         | H : JMeq x y |- _ => elim H; clear H\n         end \n    end.\n\n  Ltac treeDest :=\n     repeat ((JMeq_elim || treeDest_aux || rewr_simpl); auto).\n\n  Tactic Notation \"contInitialise\" :=  repeat (contInit cmirror).\n  Tactic Notation \"Tcontainer\" :=  contInitialise; treeDest. \n\n Lemma test2 :  Eqmor (m_comp cswap cswap) (idm ctree).\n      Tcontainer.\n Qed.\n\nLemma test1 :  Eqmor (m_comp cmirror cmirror) (idm ctree).\n   (*contInitialize.  treeDest. treeDest. *)\n     Tcontainer.\n Qed.\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/Trees.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.699280421589553}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice fintype tuple.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(** * Prop and Type *)\n\nLemma sig_exists A (P : A -> Prop) :\n  {x : A | P x} -> exists x : A, P x.\nProof.\ncase=> x px.\nby exists x.\nUndo.\nexists x.\nexact: px.\nQed.\n\nDefinition exists_sig A (P : A -> Prop) :\n  (exists x : A, P x) ->\n  {x : A | P x}.\nProof.\nFail case=> x px.\n(**\nError: ...\nCase analysis on sort [Type] is not allowed\nfor inductive definition [ex].\n*)\nAbort.\n(** Recall that [exists x : A, P x] is a notation\n    for [ex P] *)\nCheck ex :  forall A : Type, (A -> Prop) -> Prop.\nCheck sig : forall A : Type, (A -> Prop) -> Type.\n\n(** This happens because [ex] lives in [Prop] --\n    the universe of logical proposititons and\n    [sig] belongs to [Type] -- the universe of\n    computations.\n    If Coq wants to stay compatible with classical\n    logic it needs to prohibit information flow\n    from [Prop] to [Type].\n    In other words, one can _only_ use proofs to\n    build other proofs.\n*)\n\n(** ** But why exactly this restriction? *)\n\n(** First of all, we should mention that [Prop]\n    is _impredicative_, meaning the following\n    typechecks just fine:\n *)\nSection Impredicativity.\n\nCheck (forall P : Prop, P) : Prop.\n\n(**\nThis formula quantifies over all formulas,\nincluding itself:\n *)\n\nVariable p : (forall P : Prop, P).\nCheck p (forall P : Prop, P).\n\nEnd Impredicativity.\n\n\nSection TypeInType.\n(** But what about [Type]? Doesn't it have\n    the same property?  *)\n\nCheck (forall P : Type, P) : Type.\n\n(** Well, no. [Type] is not a primitive universe,\n    in fact, it's a family of indexed universes\n    but the indices are hidden by default.\n    We can recover those like so: *)\n\nSet Printing Universes.\nCheck (forall P : Type, P) : Type.\n(**\n(forall P : Type@{Top.246}, P) : Type@{Top.245}\n     : Type@{Top.245}\n(* {Top.246 Top.245} |= Top.246 < Top.245 *)\n*)\n\n(** To make this more readable we can declare\n    explicit universe levels: *)\nUniverse i j.\nCheck (forall P : Type@{i}, P) : ( Type@{j} ).\n(** Coq infers [i < j] in this case, so following\n    predictably fails: *)\nFail Check (forall P : Type@{i}, P) : ( Type@{i} ).\n(**\nuniverse inconsistency:\nCannot enforce i < i because i = i.\n*)\n\n(** This restriction prevents us from getting\n    the so-called \"type-in-type\" paradox --\n    had we not introduced this hierarchy of\n    universes we would get\n    [Type : Type] which leads to inconsistency\n    as famously shown by Girard.\n *)\n\nCheck Type@{i}.\n(** Type@{i} : Type@{i+1} *)\n\n(** Some more examples: *)\n\nCheck nat.\n(** nat : Set *)\n\nCheck Set.\n(** Set : Type@{Set+1} *)\n\nCheck Prop.\n(** Prop : Type@{Set+1} *)\n\nUnset Printing Universes.\nEnd TypeInType.\n\n\n\n(** * Large elimination *)\n\n(**\nNext, let's look at _large elimination\nLarge elimination is the ability to build values\nof type [Type] by eliminating an inductive value.\n\nWe used it to prove the disjointness of constructors\nin Lecture 03:\n*)\n\nDefinition false_implies_False_term :\n  false = true -> False\n:=\n  fun     eq :  false = true =>\n    match eq in (_    = b)\n             return (if b then False else True)\n                    (* ^^^^^^^^^^^^^^^^^^^^^^^ *)\n                    (* large elimination       *)\n    with\n    | erefl => I\n    end.\n\n\n(** Now, Coq is known to be consistent with the\n    Law of Excluded Middle, i.e. the following\n    axiom can be safely added\n *)\n\nAxiom LEM : forall P : Prop, P \\/ ~ P.\n\n(** But, as shown by Berardi in the 1990s,\n  impredicativity + excluded middle\n  => proof irrelevance\n\nSee the paper \"Proof-irrelevance out of\nExcluded-middle and Choice in the Calculus of\nConstructions\" - F. Barbanera, S. Berardi(1996)\n *)\n\n(** Had we not prohibited large elimination for\n    the impredicative universe [Prop],\n    we would get a means to proving disjointness\n    of constructors, i.e. that proofs can differ\n    from each other. *)\nInductive Bool : Prop := T : Bool | F : Bool.\n\nFail Definition prf_rel_Bool (Eq : T = F) : False :=\n  match Eq in (_ = y)\n        return (match y with\n                | T => True\n                | F => False\n                end)\n  with\n  | eq_refl => I\n  end.\n\n(** no large elimination for [Prop] *)\nFail Check match F with T => True | F => False end.\n\n(** no such restriction for [Type] *)\nCheck\n  match false with true => True | false => False end.\n\n(**\n  Upshot:\n  proof irrelevance + large elimination\n  => False\n\n  Hence\n  impredicative [Prop] + large elimination + excluded middle\n  => False\n\n  Overall, this lets [Prop] be impredicative\n  and Coq compatible with the law of excluded\n  middle, which is commonly used in mathematics.\n\n  See also https://github.com/FStarLang/FStar/issues/360\n\n*)\n\n\n(** It's now easy to see that some exceptions\n    that won't result in proof _relevance_\n    are fine:\n *)\nDefinition False_to_nat (prf : False) : nat :=\n  match prf with end.\n\nDefinition true_to_nat (prf : True) : nat :=\n  match prf with | I => 0 end.\n\n(** The above examples work because\n    the corresponding inductive types have only\n    zero or one constructors, i.e. not enough\n    to prove the disjointness *)\n\nFail Definition or_to_nat (prf : True \\/ True) : nat :=\n  match prf with\n  | or_introl _ => 0\n  | or_intror _ => 1\n  end.\n(**\nIncorrect elimination of \"prf\" in the inductive type \"or\":\nthe return type has sort \"Set\" while it should be \"Prop\".\nElimination of an inductive object of sort Prop\nis not allowed on a predicate in sort Set\nbecause proofs can be eliminated only to build proofs.\n*)\n\n\n\n(** * Totality and termination *)\n\n(** There is a plugin to control\n    - the guardedness check,\n    - strict positivity rule, and\n    - universe inconsistency check\n    It's not needed with the current development\n    version of Coq (8.11+alpha).\n    For Coq versions 8.7 - 8.9 it can be installed\n    with opam package manager:\n      opam install coq-typing-flags\n    or compiled manually using instructions from\n    the plugin's homepage:\n    https://github.com/SimonBoulier/TypingFlags\n    To start using the plugin in a Coq file:\n      From TypingFlags Require Import Loader.\n    This adds\n    Set Type In Type / Unset Type In Type\n    and\n    Set Guard Checking / Unset Guard Checking.\n    vernacular commands.\n *)\n\nFrom TypingFlags Require Import Loader.\n\n\n\n(** We already mentioned earlier that\n    Coq is a total language.\n    This ensures its consistency as a logic\n    because it rules out things like the following:\n *)\n\n(** Disable termination checker *)\nUnset Guard Checking.\n\nFixpoint proof_of_False (n : nat) : False :=\n  proof_of_False n.\n\nCheck proof_of_False 0 : False.\n\n(** The following vernacular reveals that\n    the proof of falsehood was obtained due to\n    bypassing of one of the checkers *)\nPrint Assumptions proof_of_False.\n(** Axioms:\n    proof_of_False is positive. *)\n\n\n(** Remark: Coq's implementation does not enforce\n    _strong_ normalization, only weak one *)\n\n(** Enable termination checker again *)\nSet Guard Checking.\n\nFixpoint weak_normalization (n : nat) : nat :=\n  let bar := weak_normalization n in\n  0.\n\nPrint Assumptions weak_normalization.\n(** [Closed under the global context]\n    This means neither axioms were used nor any checker was disabled *)\n\n\n\n(** * Intermezzo: [interleave] function *)\n\n(** ** Elegant, but non-structural recursive [interleave] function *)\n\nUnset Guard Checking.\nFixpoint interleave_ns {T} (xs ys : seq T)\n           {struct xs} : seq T :=\n  if xs is (x :: xs') then x :: interleave_ns ys xs'\n  else ys.\n\n(** A simple unit test. *)\nCheck erefl :\ninterleave_ns [:: 1; 3] [:: 2; 4] = [:: 1; 2; 3; 4].\n(** As you can see the evaluator does not care\n    if the function passes the guardedness check\n    or not *)\n\nPrint Assumptions interleave_ns.\n(**\n  Axioms:\n  interleave_ns is positive.\n*)\n\n\n(** Here is how [interleave] can be actually defined in Coq: *)\nSet Guard Checking.\nFixpoint interleave {T} (xs ys : seq T) : seq T :=\n  match xs, ys with\n  | (x :: xs'), (y :: ys') =>\n       x :: y :: interleave xs' ys'\n  | [::], _ => ys\n  | _, [::] => xs\n  end.\n\n(** We can even prove the two implementations\n    are \"the same\" *)\nLemma interleave_ns_eq_interleave {T} :\n  (@interleave_ns T) =2 (@interleave T).\nProof.\nby elim=> // x xs IHxs [|y ys] //=; rewrite IHxs.\nQed.\n\n\n(** Coq offers more ways of defining [interleave]\n    function *)\n\n(** ** 1. Using the builtin [Function] plugin *)\n\n(** To activate [Function] plugin,\n    this makes available a new piece of vernacular:\n    [Function] *)\nFrom Coq Require Import Recdef.\n\nDefinition sum_len {T} (xs_ys : seq T * seq T) : nat :=\n  length xs_ys.1 + length xs_ys.2.\n\nFunction interleave_f' {T} (xs_ys : (seq T * seq T))\n         {measure sum_len xs_ys} : seq T :=\n  if xs_ys is (x :: xs', ys) then\n    x :: interleave_f' (ys, xs')\n  else [::].\nProof.\nmove=> X xs_ys xs ys x xs' _ _.\nby rewrite /sum_len /= addnC.\nQed.\n(**\nNotice a bunch of autogenerated definitions:\n\ninterleave_f'_tcc is defined\ninterleave_f'_terminate is defined\ninterleave_f'_ind is defined\ninterleave_f'_rec is defined\ninterleave_f'_rect is defined\nR_interleave_f'_correct is defined\nR_interleave_f'_complete is defined\n *)\n\nFail Check erefl :\n  interleave_f' ([:: 1; 3], [:: 2; 4]) =\n  [:: 1; 2; 3; 4].\nEval hnf in interleave_f' ([:: 1; 3], [:: 2; 4]).\n(**\nThe above gets stuck on:\n  = let (v, _) :=\n      interleave_f'_terminate ([:: 1; 3], [:: 2; 4])\n    in v\n  : seq nat\n*)\nAbout interleave_f'_terminate.\n(**\n...\ninterleave_f'_terminate is opaque\n...\n *)\n\n(** First, we are going to fix evaluation\n    by making [interleave_f_terminate]\n    transparent: *)\nFunction interleave_f {T} (xs_ys : (seq T * seq T))\n         {measure sum_len xs_ys} : seq T :=\n  if xs_ys is (x :: xs', ys) then\n    x :: interleave_f (ys, xs')\n  else [::].\nProof.\nmove=> X xs_ys xs ys x xs' _ _.\nby rewrite /sum_len /= addnC.\n(** [Defined] makes [interleave_f_terminate]\n    transparent *)\nDefined.\n\n(** Now evaluation works: *)\nCheck erefl :\n  interleave_f ([:: 1; 3], [:: 2; 4]) =\n  [:: 1; 2; 3; 4].\nAbout interleave_f_terminate.\n(**\n...\ninterleave_f_terminate is transparent\n...\n*)\n\n\n(** Now let us see how [interleave_f] is built *)\nPrint interleave_f.\n(**\ninterleave_f =\nfun (x : Type) (x0 : seq x * seq x) =>\n  let (v, _) := interleave_f_terminate x0 in v\n     : forall x : Type, seq x * seq x -> seq x\n*)\nAbout interleave_f_terminate.\n(**\ninterleave_f_terminate :\nforall (T : Type) (xs_ys : seq T * seq T),\n{v : seq T |\nexists p : nat,\n  forall k : nat,\n  (p < k)%coq_nat ->\n  forall def : forall T0 : Type,\n                 seq T0 * seq T0 -> seq T0,\n  iter (forall T0 : Type, seq T0 * seq T0 -> seq T0)\n       k\n       interleave_f_F\n       def\n       T\n       xs_ys\n  = v}\n*)\n\n(** Under the hood [interleave_f_terminate]\n    is (of course) a structural recursive function.\n    To understand what type we do recursion over,\n    let's print the definition of the function and\n    search for [fix] *)\nPrint interleave_f_terminate.\n(**\n...\nfix hrec (T0 : Type) (xs_ys0 : seq T0 * seq T0)\n         (Acc_xs_ys0 : Acc (Wf_nat.ltof\n                              (seq T0 * seq T0)\n                              [eta sum_len])\n                           xs_ys0)\n         {struct Acc_xs_ys0} :\n...\n*)\n\n(** Here we meet the accessibility predicate [Acc]\n    which can be used to define well-founded\n    induction principles *)\nPrint Acc.\n(**\nInductive Acc (A : Type)\n              (R : A -> A -> Prop)\n              (x : A) : Prop :=\n  | Acc_intro :\n      (forall y : A, R y x -> Acc R y) -> Acc R x\n\n[Acc R x] can be read as \"x is accessible under\nrelation R if all elements staying in relation R\nwith it are also accessible\"\n*)\n\n(** Notice that Coq allows us do structural\n    recursion on a term of type [Acc]\n    which lives in [Prop] while building\n    a term of a type living in [Type].\n    (structural recursion involves pattern-matching).\n    But the accessibility predicate is defined\n    to be non-informative (one constructor!).\n *)\n\n\n\n(** ** More on choice operator *)\nSection Find.\n\n(** Getting a concrete value from\n    an abstract existence proof. *)\n\nVariable (P : pred nat).\n\n(** This construction lets us count up *)\nInductive acc_nat i : Prop :=\n| AccNat0 of P i\n| AccNatS of acc_nat i.+1.\n\nLemma find_ex :\n  (exists n, P n) -> {m | P m}.\nProof.\nmove=> exP.\n\nhave: acc_nat 0.\n  case exP => n; rewrite -(addn0 n); elim: n 0 => [|n IHn] j; first by left.\n  by rewrite addSnnS; right; apply: IHn.\n\nmove: 0.\nfix find_ex 2 => m IHm.\ncase Pm: (P m).\n- by exists m.\napply: find_ex m.+1 _.\ncase: IHm.\n- by rewrite Pm.\nby [].\nDefined.\n\nEnd Find.\n\n\n\n(** ** 2. Using the builtin [Program] mechanism *)\n\nFrom Coq Require Import Program.\n\nProgram Fixpoint interleave_p {A} (xs ys : seq A)\n  {measure (length xs + length ys)} : list A :=\n  if xs is (x :: xs') then\n    x :: interleave_p ys xs'\n  else ys.\nNext Obligation. by rewrite addnC. Qed.\n\nCheck erefl :\n  interleave_p [:: 1; 3] [:: 2; 4] =\n  [:: 1; 2; 3; 4].\n\n(** [Program] also relies on [Acc] predicate *)\n\nPrint Assumptions interleave_p.\n(** [Closed under the global context]\n\n    But sometimes [Program] relies on\n    [JMeq_eq] axiom to do dependent pattern\n    matching.\n *)\nCheck JMeq_eq.\n(**\nJMeq_eq : forall (A : Type) (x y : A),\n            x ~= y -> x = y\n*)\nPrint JMeq.\n(**\n\"JMeq\" means \"John Major equality\", a.k.a.\nheterogenous equality.\n\nInductive JMeq (A : Type) (x : A) :\n  forall B : Type, B -> Prop :=\n| JMeq_refl : x ~= x\n\n[~=] is a notation for [JMeq]\n*)\n\n\n(** ** 3. Using the [Equations] plugin *)\n\n(** The plugin can be installed via opam:\n      opam install coq-equations *)\n\nFrom Equations Require Import Equations.\n\nEquations interleave_e {T} (xs ys : seq T) : seq T\n  by wf (length xs + length ys) lt :=\ninterleave_e (x :: xs) ys :=\n  x :: (interleave_e ys xs);\ninterleave_e [::] ys :=\n  ys.\nNext Obligation. by rewrite addnC. Qed.\n\nCheck erefl :\n  interleave_e [:: 1; 3] [:: 2; 4] =\n  [:: 1; 2; 3; 4].\n\n\n(** One more trick to teach Coq termination:\n    nested [fix] *)\n\n(** Ackermann's function *)\n\nFixpoint ack (n m : nat) : nat :=\n  if n is n'.+1 then\n    let fix ackn (m : nat) :=\n        if m is m'.+1 then ack n' (ackn m')\n        else ack n' 1\n    in ackn m\n  else m.+1.\n\n\n\n\n(** * Strict positivity rule *)\n\nPrint Typing Flags.\n\nFail Inductive prop :=\n  RemoveNegation of (prop -> False).\n(**\nNon strictly positive occurrence of \"prop\" in\n\"(prop -> False) -> prop\".\n*)\n\nUnset Guard Checking.\nPrint Typing Flags.\n\nInductive prop :=\n  RemoveNegation of (prop -> False).\nPrint Assumptions prop.\n(**\nAxioms:\nprop is positive.\n*)\n\nDefinition not_prop (p : prop) : False :=\n  let '(RemoveNegation not_p) := p in not_p p.\nCheck not_prop : prop -> False.\n\nCheck RemoveNegation not_prop : prop.\n\nDefinition yet_another_proof_of_False : False :=\n  not_prop (RemoveNegation not_prop).\n\nPrint Assumptions yet_another_proof_of_False.\n(**\nAxioms:\nyet_another_proof_of_False is positive.\nnot_prop is positive.\nprop is positive.\n*)\nSet Guard Checking.\n\n(**\nRoughly, the positivity condition says that\nconstructors for an inductive data type can\nonly depend on maps to the data type but not on\nmaps from it.\n*)\n\n\n\n(** * Bonus: Universe polymorphism *)\n\nDefinition idf {A} : A -> A := fun x => x.\nFail Definition selfidfun := idf (@idf).\n(**\nThe term \"@idf\" has type \"forall A : Type, A -> A\"\nwhile it is expected to have type \"?A\"\n(unable to find a well-typed instantiation for \"?A\": cannot ensure that\n\"Type@{Top.1849+1}\" is a subtype of \"Type@{Top.1849}\").\n*)\n\nSet Universe Polymorphism.\n\nDefinition idf' {A} : A -> A := fun x => x.\nDefinition selfidfun' := idf' (@idf').\nPrint selfidfun'.\n\n(** See more examples in the Coq Reference Manual *)\n", "meta": {"author": "vyorkin", "repo": "coq-fv", "sha": "d65348888fc51722585d81f189fd1b71da7b8c3b", "save_path": "github-repos/coq/vyorkin-coq-fv", "path": "github-repos/coq/vyorkin-coq-fv/coq-fv-d65348888fc51722585d81f189fd1b71da7b8c3b/lectures/lecture09.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.6992804207031031}}
{"text": "Require Export RTopology.\nRequire Export ProductTopology.\n\nLocal Unset Standard Proposition Elimination Names.\n\nLemma Rplus_continuous: continuous_2arg Rplus (X:=RTop) (Y:=RTop) (Z:=RTop).\nProof.\napply pointwise_continuity_2arg.\nintros.\nred.\npose proof (RTop_metrization (x+y)).\napply continuous_at_neighborhood_basis with\n  (metric_topology_neighborhood_basis R_metric (x+y)).\napply open_neighborhood_basis_is_neighborhood_basis.\napply RTop_metrization.\n\nintros.\ndestruct H0.\nexists ([ p:point_set RTop * point_set RTop | let (x',y'):=p in\n  In (open_ball _ R_metric x (r/2)) x' /\\\n  In (open_ball _ R_metric y (r/2)) y' ]).\nrepeat split.\napply ProductTopology2_basis_is_basis.\nconstructor.\npose proof (RTop_metrization x).\ndestruct H1.\napply (open_neighborhood_basis_elements\n  (open_ball _ R_metric x (r/2))).\nconstructor.\nRequire Import Fourier.\nfourier.\ndestruct (RTop_metrization y).\napply (open_neighborhood_basis_elements\n  (open_ball _ R_metric y (r/2))).\nconstructor.\nfourier.\nrewrite metric_zero.\nfourier.\napply R_metric_is_metric.\nrewrite metric_zero.\nfourier.\napply R_metric_is_metric.\ndestruct x0 as [x' y'].\ndestruct H1 as [[[] []]].\nunfold R_metric.\nreplace (x'+y' - (x+y)) with ((x'-x) + (y'-y)) by ring.\napply Rle_lt_trans with (Rabs (x'-x) + Rabs(y'-y)).\napply Rabs_triang.\nreplace r with (r/2+r/2) by field; apply Rplus_lt_compat; trivial.\nQed.\n\nCorollary sum_continuous: forall (X:TopologicalSpace)\n  (f g:point_set X -> point_set RTop) (x:point_set X),\n  continuous_at f x -> continuous_at g x ->\n  continuous_at (fun x:point_set X => f x + g x) x (Y:=RTop).\nProof.\nintros.\napply continuous_composition_at_2arg; trivial.\napply continuous_func_continuous_everywhere.\napply Rplus_continuous.\nQed.\n\n(* Ropp_continuous was already proved in RTopology *)\n\nLemma Rminus_continuous: continuous_2arg Rminus\n  (X:=RTop) (Y:=RTop) (Z:=RTop).\nProof.\nunfold Rminus.\napply pointwise_continuity_2arg; intros.\nred.\npose proof (sum_continuous _\n  (fun p:point_set (ProductTopology2 RTop RTop) => fst p)\n  (fun p:point_set (ProductTopology2 RTop RTop) => -snd p) (x,y)).\nsimpl in H.\nmatch goal with |- continuous_at ?f ?q =>\n  replace f with (fun p:R*R => fst p + - snd p) end.\napply sum_continuous.\napply continuous_func_continuous_everywhere.\napply product2_fst_continuous.\napply (continuous_composition_at (Y:=RTop)).\napply continuous_func_continuous_everywhere.\napply Ropp_continuous.\napply continuous_func_continuous_everywhere.\napply product2_snd_continuous.\n\nRequire Import FunctionalExtensionality.\nextensionality p.\ndestruct p as [x' y'].\ntrivial.\nQed.\n\nCorollary diff_continuous: forall (X:TopologicalSpace)\n  (f g:point_set X -> point_set RTop) (x:point_set X),\n  continuous_at f x -> continuous_at g x ->\n  continuous_at (fun x:point_set X => f x - g x) x (Y:=RTop).\nProof.\nintros.\napply continuous_composition_at_2arg; trivial.\napply continuous_func_continuous_everywhere.\nexact Rminus_continuous.\nQed.\n\nLemma const_multiple_func_continuous: forall c:R,\n  continuous (fun x:R => c*x) (X:=RTop) (Y:=RTop).\nProof.\nintros.\napply pointwise_continuity; intros.\napply metric_space_fun_continuity with R_metric R_metric;\n  try apply RTop_metrization.\ndestruct (classic (c=0)).\nexists 1.\nsplit.\nred; auto with real.\nintros.\nrewrite H.\nunfold R_metric.\nreplace (0*x'-0*x) with 0 by ring.\nrewrite Rabs_R0.\ntrivial.\n\nintros.\nexists (eps / Rabs c).\nsplit.\napply Rmult_gt_0_compat; trivial.\napply Rinv_0_lt_compat.\napply Rabs_pos_lt; trivial.\nintros.\nunfold R_metric.\nreplace (c*x' - c*x) with (c*(x'-x)) by ring.\nrewrite Rabs_mult.\nreplace eps with (Rabs c * (eps / Rabs c)); try field.\napply Rmult_lt_compat_l.\napply Rabs_pos_lt; trivial.\ntrivial.\napply Rabs_no_R0; trivial.\nQed.\n\nCorollary const_multiple_continuous: forall (X:TopologicalSpace)\n  (f:point_set X -> point_set RTop) (c:R) (x:point_set X),\n  continuous_at f x -> continuous_at (fun x:point_set X => c * f x) x\n                       (Y:=RTop).\nProof.\nintros.\napply continuous_composition_at; trivial.\napply continuous_func_continuous_everywhere.\napply const_multiple_func_continuous with (c:=c).\nQed.\n\nLemma Rmult_continuous_at_origin: continuous_at_2arg Rmult 0 0\n                                  (X:=RTop) (Y:=RTop) (Z:=RTop).\nProof.\nred.\npose proof (RTop_metrization 0).\napply continuous_at_neighborhood_basis with\n  (metric_topology_neighborhood_basis R_metric 0).\napply open_neighborhood_basis_is_neighborhood_basis.\nreplace (0*0) with 0 by auto with real.\napply H.\n\nintros.\ndestruct H0.\nexists (characteristic_function_to_ensemble\n  (fun p:point_set RTop * point_set RTop => let (x',y'):=p in\n  In (open_ball _ R_metric 0 r) x' /\\\n  In (open_ball _ R_metric 0 1) y' )).\nrepeat split.\napply ProductTopology2_basis_is_basis.\nconstructor.\ndestruct H.\napply (open_neighborhood_basis_elements (open_ball _ R_metric 0 r)).\nconstructor; trivial.\ndestruct H.\napply (open_neighborhood_basis_elements (open_ball _ R_metric 0 1)).\nconstructor; red; auto with real.\nrewrite metric_zero; trivial.\napply R_metric_is_metric.\nrewrite metric_zero; auto with real.\napply R_metric_is_metric.\n\ndestruct H1.\ndestruct x as [x y].\ndestruct H1 as [[] []].\nunfold R_metric in H1, H2.\nunfold R_metric.\nreplace (x*y-0) with (x*y) by auto with real.\nreplace (x-0) with x in H1 by auto with real.\nreplace (y-0) with y in H2 by auto with real.\nrewrite Rabs_mult.\nreplace r with (r*1) by auto with real.\napply Rmult_le_0_lt_compat; trivial.\napply Rabs_pos.\napply Rabs_pos.\nQed.\n\nLemma Rmult_continuous: continuous_2arg Rmult (X:=RTop) (Y:=RTop) (Z:=RTop).\nProof.\napply pointwise_continuity_2arg.\nintros x0 y0.\nred.\nmatch goal with |- continuous_at ?f ?q => replace f with\n  (fun p:point_set RTop*point_set RTop =>\n   (fst p - x0) * (snd p - y0) + y0 * fst p + x0 * snd p - x0 * y0) end.\napply diff_continuous.\napply sum_continuous.\napply sum_continuous.\napply continuous_composition_at_2arg with RTop RTop.\nsimpl.\nreplace (x0-x0) with 0 by ring.\nreplace (y0-y0) with 0 by ring.\napply Rmult_continuous_at_origin.\napply diff_continuous.\napply continuous_func_continuous_everywhere; apply product2_fst_continuous.\napply continuous_func_continuous_everywhere; apply continuous_constant.\napply diff_continuous.\napply continuous_func_continuous_everywhere; apply product2_snd_continuous.\napply continuous_func_continuous_everywhere; apply continuous_constant.\napply const_multiple_continuous.\napply continuous_func_continuous_everywhere; apply product2_fst_continuous.\napply const_multiple_continuous.\napply continuous_func_continuous_everywhere; apply product2_snd_continuous.\napply continuous_func_continuous_everywhere; apply continuous_constant.\n\nextensionality p.\ndestruct p as [x y].\nsimpl.\nring.\nQed.\n\nCorollary product_continuous: forall (X:TopologicalSpace)\n  (f g:point_set X -> point_set RTop) (x:point_set X),\n  continuous_at f x -> continuous_at g x ->\n  continuous_at (fun x:point_set X => f x * g x) x (Y:=RTop).\nProof.\nintros.\napply continuous_composition_at_2arg; trivial.\napply continuous_func_continuous_everywhere.\nexact Rmult_continuous.\nQed.\n\nLemma Rinv_continuous_at_1: continuous_at Rinv 1 (X:=RTop) (Y:=RTop).\nProof.\napply metric_space_fun_continuity with R_metric R_metric;\n  try apply RTop_metrization.\nintros.\nexists (Rmin (1/2) (eps/2)).\nsplit; intros.\napply Rmin_Rgt_r; split; fourier.\nassert (x' > 1/2).\nassert (Rabs (x'-1) < 1/2).\napply Rlt_le_trans with (1 := H0).\napply Rmin_l.\ndestruct (Rabs_def2 _ _ H1).\nfourier.\nassert (/ x' < 2).\nrewrite <- Rinv_involutive.\napply Rinv_lt_contravar.\napply Rmult_lt_0_compat; fourier.\nunfold Rdiv in H1.\nreplace (1 * / 2) with (/ 2) in H1 by auto with real.\nexact H1.\nintro.\nfourier.\n\nunfold R_metric.\nreplace (/ x' - / 1) with ((1 - x') * / x'); try field.\nrewrite Rabs_mult.\nrewrite (Rabs_right (/ x')).\nrewrite Rabs_minus_sym.\nassert (Rabs (x' - 1) < eps/2).\napply Rlt_le_trans with (1:=H0).\napply Rmin_r.\nreplace eps with ((eps/2) * 2) by field.\napply Rmult_gt_0_lt_compat; trivial.\napply Rinv_0_lt_compat.\nfourier.\nfourier.\nleft.\napply Rinv_0_lt_compat.\nfourier.\nintro.\nfourier.\nQed.\n\n\nRequire Import Ensembles.\nRequire Import SeparatednessAxioms.\n\nLemma Rinv_continuous: forall x0:R, x0<>0 -> continuous_at Rinv x0 (X:=RTop) (Y:=RTop).\nProof.\n  intros.\n  apply continuous_at_is_local with\n    (f:=fun x:R => /x0 * Rinv (/x0 * x))\n    (N:=Complement (Singleton 0)).\n  apply open_neighborhood_is_neighborhood.\n  split.\n  apply Hausdorff_impl_T1_sep.\n  apply T3_sep_impl_Hausdorff.\n  apply normal_sep_impl_T3_sep.\n  apply metrizable_impl_normal_sep.\n  exists R_metric.\n  apply R_metric_is_metric.\n  apply RTop_metrization.\n  intro.\n  destruct H0.\n  contradiction H.\n  reflexivity.\n  intros.\n  assert (x<>0).\n  intro.\n  contradiction H0.\n  rewrite H1; constructor.\n  simpl.\n  field; split; trivial.\n\n  apply const_multiple_continuous.\n  apply (continuous_composition_at (Y:=RTop)).\n  replace (/x0 * x0) with 1.\n  apply Rinv_continuous_at_1.\n  field; trivial.\n  apply continuous_func_continuous_everywhere.\n  apply const_multiple_func_continuous with (c:=/ x0).\nQed.\n\nLemma Rdiv_continuous: forall x y:R, y <> 0 ->\n  continuous_at_2arg Rdiv x y (X:=RTop) (Y:=RTop) (Z:=RTop).\nProof.\nintros.\nred.\nmatch goal with |- continuous_at ?f ?q => replace f with\n  (fun p:point_set RTop * point_set RTop => fst p * / snd p) end.\napply product_continuous.\napply continuous_func_continuous_everywhere; apply product2_fst_continuous.\napply continuous_composition_at.\nsimpl.\napply Rinv_continuous; trivial.\napply continuous_func_continuous_everywhere; apply product2_snd_continuous.\n\nextensionality p.\ndestruct p as [x' y'].\ntrivial.\nQed.\n\nCorollary quotient_continuous: forall (X:TopologicalSpace)\n  (f g:point_set X -> point_set RTop) (x0:point_set X),\n  continuous_at f x0 -> continuous_at g x0 -> g x0 <> 0 ->\n  continuous_at (fun x:point_set X => f x / g x) x0 (Y:=RTop).\nProof.\nintros.\napply continuous_composition_at_2arg; trivial.\napply Rdiv_continuous; trivial.\nQed.\n\n\nLemma Rabs_continuous: continuous Rabs (X:=RTop) (Y:=RTop).\nProof.\napply pointwise_continuity; intros.\napply metric_space_fun_continuity with R_metric R_metric;\n  try apply RTop_metrization.\nintros.\nexists eps; split; trivial.\nintros.\napply Rle_lt_trans with (2 := H0).\napply Rabs_triang_inv2.\nQed.\n\n(* a miscellaneous example which is used in the proof of the\n   Tietze extension theorem *)\nRequire Import Homeomorphisms.\n\n\nLemma open_interval_homeomorphic_to_real_line:\n  let U:=characteristic_function_to_ensemble\n      (fun x:point_set RTop => -1 < x < 1) in\n  homeomorphic RTop (SubspaceTopology U).\nProof.\nintros.\nassert (forall x:R, -1 < x / (1 + Rabs x) < 1).\nintros.\nassert (0 < 1 + Rabs x).\napply Rlt_le_trans with 1; auto with real.\npattern 1 at 1; replace 1 with (1+0) by auto with real.\napply Rplus_le_compat_l.\napply Rabs_pos.\napply and_comm; apply Rabs_def2.\nunfold Rdiv; rewrite Rabs_mult.\nrewrite Rabs_Rinv.\nrewrite (Rabs_right (1 + Rabs x)); try (left; trivial).\npattern 1 at 2; replace 1 with ((1 + Rabs x) * / (1 + Rabs x)).\napply Rmult_lt_compat_r.\napply Rinv_0_lt_compat; trivial.\npattern (Rabs x) at 1; replace (Rabs x) with (0 + Rabs x); auto with real.\nfield.\napply Rgt_not_eq; trivial.\napply Rgt_not_eq; trivial.\n\nassert (forall x:point_set RTop, In U (x / (1 + Rabs x))).\nintros; constructor; apply H.\nRequire Import ContinuousFactorization.\nexists (continuous_factorization _ _ H0).\nexists (fun x:point_set (SubspaceTopology U) =>\n  (subspace_inc U x) / (1 - Rabs (subspace_inc U x))).\napply factorization_is_continuous.\napply pointwise_continuity; intros.\napply quotient_continuous.\napply continuous_func_continuous_everywhere; apply continuous_identity.\napply sum_continuous.\napply continuous_func_continuous_everywhere; apply continuous_constant.\napply continuous_func_continuous_everywhere; apply Rabs_continuous.\napply Rgt_not_eq.\napply Rlt_le_trans with 1; auto with real.\npattern 1 at 1; replace 1 with (1+0) by auto with real.\napply Rplus_le_compat_l.\napply Rabs_pos.\n\napply pointwise_continuity; intros.\napply quotient_continuous.\napply continuous_func_continuous_everywhere; apply subspace_inc_continuous.\napply diff_continuous.\napply continuous_func_continuous_everywhere; apply continuous_constant.\napply continuous_composition_at.\napply continuous_func_continuous_everywhere; apply Rabs_continuous.\napply continuous_func_continuous_everywhere; apply subspace_inc_continuous.\napply Rgt_not_eq.\napply Rgt_minus.\nred.\ndestruct x as [x [[]]]; simpl.\napply Rabs_def1; trivial.\n\nsimpl.\nintros.\nunfold Rabs at 1 3; destruct Rcase_abs.\nrewrite Rabs_left.\nfield.\nsplit; intro; fourier.\nassert (/ (1 + -x) > 0).\napply Rinv_0_lt_compat.\nfourier.\nreplace 0 with (x*0) by auto with real.\napply Rmult_lt_gt_compat_neg_l; trivial.\n\nrewrite Rabs_right.\nfield.\nsplit; intro; fourier.\nassert (/ (1+x) > 0).\napply Rinv_0_lt_compat.\nfourier.\napply Rle_ge.\napply Rge_le in r.\nred in H1.\nunfold Rdiv.\nreplace 0 with (0 * / (1+x)); auto with real.\n\nintros.\ndestruct y as [x].\nsimpl.\nRequire Import Proj1SigInjective.\napply subset_eq_compatT.\ndestruct i.\ndestruct H1.\nassert (Rabs x < 1).\napply Rabs_def1; trivial.\n\nunfold Rabs at 1 3; destruct Rcase_abs.\nrewrite Rabs_left.\nfield.\nsplit; intro; fourier.\nreplace (1 - -x) with (1+x) by ring.\nassert (/ (1+x) > 0).\napply Rinv_0_lt_compat.\nfourier.\nunfold Rdiv.\nreplace 0 with (x*0) by auto with real.\napply Rmult_lt_gt_compat_neg_l; trivial.\n\nrewrite Rabs_right.\nfield.\nsplit; intro; fourier.\nassert (/ (1-x) > 0).\napply Rinv_0_lt_compat.\napply Rgt_minus; trivial.\nunfold Rdiv.\nred in H4.\napply Rge_le in r.\napply Rle_ge.\nreplace 0 with (0 * / (1-x)); auto with real.\nQed.\n", "meta": {"author": "verimath", "repo": "topology", "sha": "9405aaf18d99c718769f1d2af8e030a902687837", "save_path": "github-repos/coq/verimath-topology", "path": "github-repos/coq/verimath-topology/topology-9405aaf18d99c718769f1d2af8e030a902687837/src/top/RFuncContinuity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.6992409220146082}}
{"text": "(* week-06_miscellany.v *)\n(* FPP 2020 - YSC3236 2020-2021, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 20 Sep 2020 *)\n(* was: *)\n(* Version of 19 Sep 2020 *)\n\n(* ********** *)\n\nRequire Import Arith Bool.\n\n(* ********** *)\n\nLemma about_decomposing_a_pair_using_the_injection_tactic :\n  forall i j : nat,\n    (i, j) = (0, 1) ->\n    i = 0 /\\ j = 1.\nProof.\n  intros i j H_ij.\n  injection H_ij.\n  \n  Restart.\n\n  intros i j H_ij.\n  injection H_ij as H_i H_j.\n  exact (conj H_i H_j).\nQed.\n\nLemma about_decomposing_a_pair_using_the_injection_tactic' :\n  forall i j : nat,\n    (i, 1) = (0, j) ->\n    i = 0 /\\ j = 1.\nProof.\n  intros i j H_ij.\n  injection H_ij as H_i H_j.\n  symmetry in H_j.\n  exact (conj H_i H_j).\nQed.\n\nLemma about_decomposing_a_pair_of_pairs_using_the_injection_tactic :\n  forall a b c d: nat,\n    ((a, 1), (2, d)) = ((0, b), (c, 3)) ->\n    a = 0 /\\ b = 1 /\\ c = 2 /\\ d = 3.\nProof.\n  intros a b c d H_abcd.\n  injection H_abcd as H_a H_b H_c H_d.\n  symmetry in H_b.\n  symmetry in H_c.\n  exact (conj H_a (conj H_b (conj H_c H_d))).\nQed.\n\n(* ********** *)\n\nLemma truism :\n  forall P : nat -> Prop,\n    (exists n : nat,\n        P n) ->\n    exists n : nat,\n      P n.\nProof.\n  intros P H_P.\n  exact H_P.\n\n  Restart.\n\n  intros P H_P.\n  destruct H_P as [n H_Pn].\n  exists n.\n  exact H_Pn.\n\n  Restart.\n\n  intros P [n H_Pn].\n  exists n.\n  exact H_Pn.\nQed.\n\n(* ***** *)\n\nLemma other_truism :\n  forall P Q : nat -> Prop,\n    (exists n : nat,\n        P n /\\ Q n) ->\n    exists m : nat,\n      P m \\/ Q m.\nProof.\n  intros P Q [n [H_Pn H_Qn]].\n  exists n.\n  left.\n  exact H_Pn.\n\n  Restart.\n\n  intros P Q [n [H_Pn H_Qn]].\n  exists n.\n  right.\n  exact H_Qn.\nQed.\n\n(* ********** *)\n\nLemma about_the_existential_quantifier_and_disjunction :\n  forall P Q : nat -> Prop,\n    (exists n : nat, P n \\/ Q n)\n    <->\n    ((exists n : nat, P n)\n     \\/\n     (exists n : nat, Q n)).\nProof.\n  intros P Q.\n  split.\n  - intros [n [H_P | H_Q]].\n    + left.\n      exists n.\n      exact H_P.\n    + right.\n      exists n.\n      exact H_Q.\n  - intros [[n H_P] | [n H_Q]].\n    + exists n.\n      left.\n      exact H_P.\n    + exists n.\n      right.\n      exact H_Q.\nQed.\n\n(* ********** *)\n\nLemma about_the_universal_quantifier_and_conjunction :\n  forall P Q : nat -> Prop,\n    (forall n : nat, P n /\\ Q n)\n    <->\n    ((forall n : nat, P n)\n     /\\\n     (forall n : nat, Q n)).\nProof.\n  intros P Q.\n  split.\n  - intro H_PQ.\n    split.\n    + intro n.\n      destruct (H_PQ n) as [H_Pn _].\n      exact H_Pn.\n    + intro n.\n      destruct (H_PQ n) as [_ H_Qn].\n      exact H_Qn.\n  - intros [H_P H_Q] n.\n    exact (conj (H_P n) (H_Q n)).\nQed.\n\n(* ********** *)\n\nDefinition specification_of_addition (add : nat -> nat -> nat) :=\n  (forall m : nat,\n      add O m = m)\n  /\\\n  (forall n' m : nat,\n      add (S n') m = S (add n' m)).\n\nDefinition specification_of_addition' (add : nat -> nat -> nat) :=\n  forall n' m : nat,\n    add O m = m\n    /\\\n    add (S n') m = S (add n' m).\n\nLemma about_two_universal_quantifiers_and_conjunction :\n  forall (P : nat -> Prop)\n         (Q : nat -> nat -> Prop),\n    ((forall j : nat, P j)\n     /\\\n     (forall i j : nat, Q i j))\n    <->\n    (forall i j : nat, P j /\\ Q i j).\nProof.\n  intros P Q.\n  split.\n  - intros [H_P H_Q] i j.\n    split.\n    + exact (H_P j).\n    + exact (H_Q i j).\n  - intro H_PQ.\n    split.\n    + intro j.\n      destruct (H_PQ 0 j) as [H_Pj _].\n      exact H_Pj.\n    + intros i j.\n      destruct (H_PQ i j) as [_ H_Qij].\n      exact H_Qij.\nQed.\n\nProposition the_two_specifications_of_addition_are_equivalent :\n  forall add : nat -> nat -> nat,\n    specification_of_addition add <-> specification_of_addition' add.\nProof.\n  intro add.\n  unfold specification_of_addition, specification_of_addition'.\n  Check (about_two_universal_quantifiers_and_conjunction\n           (fun m : nat => add 0 m = m)\n           (fun n' m : nat => add (S n') m = S (add n' m))).\n  exact (about_two_universal_quantifiers_and_conjunction\n           (fun m : nat => add 0 m = m)\n           (fun n' m : nat => add (S n') m = S (add n' m))).\nQed.\n\n(* ********** *)\n\nLemma even_or_odd_dropped :\n  forall n : nat,\n    (exists q : nat,\n        n = 2 * q)\n    \\/\n    (exists q : nat,\n        n = S (2 * q)).\nProof.\nAdmitted.\n\nLemma even_or_odd_lifted :\n  forall n : nat,\n  exists q : nat,\n    n = 2 * q\n    \\/\n    n = S (2 * q).\nProof.\nAdmitted.\n\nProposition the_two_specifications_of_even_or_odd_are_equivalent :\n  forall n : nat,\n    (exists q : nat,\n        n = 2 * q\n        \\/\n        n = S (2 * q))\n    <->\n    ((exists q : nat,\n         n = 2 * q)\n     \\/\n     (exists q : nat,\n         n = S (2 * q))).\nProof.\n  intro n.\n  Check (about_the_existential_quantifier_and_disjunction\n           (fun q : nat => n = 2 * q)\n           (fun q : nat => n = S (2 * q))).\n  exact (about_the_existential_quantifier_and_disjunction\n           (fun q : nat => n = 2 * q)\n           (fun q : nat => n = S (2 * q))).\nQed.\n\n(* ********** *)\n\nLemma O_or_S :\n  forall n : nat,\n    n = 0 \\/ (exists n' : nat, \n                 n = S n').\nProof.\n  intro n.\n  destruct n as [ | n'] eqn:H_n.\n\n  - left.\n    reflexivity.\n\n  - right.\n    exists n'.\n    reflexivity.\nQed.\n\n(* ********** *)\n\nProposition now_what :\n  (forall n : nat, n = S n) <-> 0 = 1.\nProof.\n  split.\n\n  - intro H_n_Sn.\n    Check (H_n_Sn 0).\n    exact (H_n_Sn 0).\n    \n  - intro H_absurd.\n    discriminate H_absurd.\n\n  Restart.\n\n  split.\n\n  - intro H_n_Sn.\n    Check (H_n_Sn 42).\n    discriminate (H_n_Sn 42).\n\n  - intro H_absurd.\n    discriminate H_absurd.\nQed.\n\nProposition what_now :\n  forall n : nat,\n    n = S n <-> 0 = 1.\nProof.\n  intro n.\n  split.\n\n  - intro H_n.\n    Search (_ <> S _).\n    Check (n_Sn n).\n    assert (H_tmp := n_Sn n).\n    unfold not in H_tmp.\n    Check (H_tmp H_n).\n    contradiction (H_tmp H_n).\n\n  - intro H_absurd.\n    discriminate H_absurd.\nQed.\n\n(* ********** *)\n\nProposition factoring_and_distributing_a_forall_in_a_conclusion :\n  forall (P : nat -> Prop)\n         (Q : Prop),\n    (Q -> forall n : nat, P n)\n    <->\n    (forall n : nat,\n        Q -> P n).\nProof.\n  intros P Q.\n  split.\n  - intros H_QP n H_Q.\n    exact (H_QP H_Q n).\n  - intros H_QP H_Q n.\n    exact (H_QP n H_Q).\nQed.\n\n(* ********** *)\n\nProposition interplay_between_quantifiers_and_implication :\n  forall (P : nat -> Prop)\n         (Q : Prop),\n    (exists n : nat, P n -> Q) ->\n    (forall n : nat, P n) -> Q.\nProof.\n  intros P Q [n H_PnQ] H_P.\n  Check (H_PnQ (H_P n)).\n  exact (H_PnQ (H_P n)).\nQed.    \n\n(* ********** *)\n\nProposition interplay_between_implication_and_quantifiers :\n  forall (P : nat -> Prop)\n         (Q : Prop),\n    ((exists n : nat, P n) -> Q) ->\n    forall n : nat, P n -> Q.\nProof.\n  intros P Q H_PQ n H_Pn.\n  apply H_PQ.\n  exists n.\n  exact H_Pn.\nQed.\n\n(* ********** *)\n\nProposition strengthening_X_in_the_conclusion :\n  forall A B C D X Y : Prop,\n    (A -> X) -> (B -> Y) -> (X -> C) -> (Y -> D) -> (X -> Y) -> A -> Y.\nProof.\n  intros A B C D X Y H_AX H_BY H_XC H_YD H_XY.\nAbort.\n\nProposition weakening_X_in_the_conclusion :\n  forall A B C D X Y : Prop,\n    (A -> X) -> (B -> Y) -> (X -> C) -> (Y -> D) -> (X -> Y) -> C -> Y.\nProof.\n  intros A B C D X Y H_AX H_BY H_XC H_YD H_XY.\nAbort.\n\nProposition strengthening_Y_in_the_conclusion :\n  forall A B C D X Y : Prop,\n    (A -> X) -> (B -> Y) -> (X -> C) -> (Y -> D) -> (X -> Y) -> X -> B.\nProof.\n  intros A B C D X Y H_AX H_BY H_XC H_YD H_XY.\nAbort.\n\nProposition weakening_Y_in_the_conclusion :\n  forall A B C D X Y : Prop,\n    (A -> X) -> (B -> Y) -> (X -> C) -> (Y -> D) -> (X -> Y) -> X -> D.\nProof.\n  intros A B C D X Y H_AX H_BY H_XC H_YD H_XY.\nAbort.\n\nProposition strengthening_X_in_a_premise :\n  forall A B C D X Y : Prop,\n    (A -> X) -> (B -> Y) -> (X -> C) -> (Y -> D) -> (A -> Y) -> X -> Y.\nProof.\n  intros A B C D X Y H_AX H_BY H_XC H_YD.\nAbort.\n\nProposition weakening_X_in_a_premise :\n  forall A B C D X Y : Prop,\n    (A -> X) -> (B -> Y) -> (X -> C) -> (Y -> D) -> (C -> Y) -> X -> Y.\nProof.\n  intros A B C D X Y H_AX H_BY H_XC H_YD.\nAbort.\n\nProposition strengthening_Y_in_a_premise :\n  forall A B C D X Y : Prop,\n    (A -> X) -> (B -> Y) -> (X -> C) -> (Y -> D) -> (X -> B) -> X -> Y.\nProof.\n  intros A B C D X Y H_AX H_BY H_XC H_YD.\nAbort.\n\nProposition weakening_Y_in_a_premise :\n  forall A B C D X Y : Prop,\n    (A -> X) -> (B -> Y) -> (X -> C) -> (Y -> D) -> (X -> D) -> X -> Y.\nProof.\n  intros A B C D X Y H_AX H_BY H_XC H_YD.\nAbort.\n\n(* ********** *)\n\n(* end of week-06_miscellany.v *)\n", "meta": {"author": "soedirgo", "repo": "fpp", "sha": "5a43df151c5c8bc3f49d449ffd6f3eac67a16eab", "save_path": "github-repos/coq/soedirgo-fpp", "path": "github-repos/coq/soedirgo-fpp/fpp-5a43df151c5c8bc3f49d449ffd6f3eac67a16eab/w06/week-06_miscellany.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738010682209, "lm_q2_score": 0.8705972600147106, "lm_q1q2_score": 0.6992409105255933}}
{"text": "Require Import Bool Psatz Arith.PeanoNat.\nRequire Import FunInd.\nRequire Import vsequent.\n\nFunction measure_p (p : prop) : nat :=\n  match p with\n  | p_sym _ => O\n  | p_neg p0 => S (measure_p p0)\n  | p_and p0 p1\n  | p_or p0 p1\n  | p_impl p0 p1 => S (measure_p p0 + measure_p p1)\n  end.\n\nFunction measure_l (s : seq_l) : nat :=\n  match s with\n  | seq_l_nil => O\n  | seq_l_cons p s0 => measure_p p + measure_l s0\n  end.\n\nFunction measure_r (s : seq_r) : nat :=\n  match s with\n  | seq_r_nil => O\n  | seq_r_cons p s0 => measure_p p + measure_r s0\n  end.\n\nFunction measure (s : seq_t) : nat :=\n  match s with\n  | seq l r => measure_l l + measure_r r\n  end.\n\nLemma measure_break : forall l r n,\n  measure (seq l r) = n -> exists n0 n1,\n  measure_l l = n0 /\\ measure_r r = n1 /\\ n = n0 + n1.\nProof.\n  intros l r n.\n  unfold measure. destruct (measure_l l); destruct (measure_r r).\n  - intros H. exists O. exists O. auto.\n  - intros H. exists O. exists (S n0). auto.\n  - intros H. exists (S n0). exists O. auto.\n  - intros H. exists (S n0). exists (S n1). auto.\nQed.\n\nLemma eval_unary_decreases : forall s0 s1 n0 n1,\n  eval_unary s0 s1 -> measure s0 = n0 ->\n  measure s1 = n1 -> n1 < n0.\nProof.\n  intros s0 s1 n0 n1 Heval. induction Heval.\n  - unfold measure. rewrite measure_l_equation.\n    rewrite (measure_r_equation (seq_r_cons p r)).\n    intros Heq0 Heq1. subst. simpl. lia.\n  - unfold measure. rewrite measure_r_equation.\n    rewrite (measure_l_equation (seq_l_cons p l)).\n    intros Heq0 Heq1. subst. simpl. lia.\n  - unfold measure. rewrite measure_r_equation.\n    rewrite (measure_r_equation (seq_r_cons p0 (seq_r_cons p1 r))).\n    rewrite (measure_r_equation (seq_r_cons p1 r)).\n    intros Heq0 Heq1. subst. simpl. lia.\n    - unfold measure. rewrite measure_r_equation.\n    rewrite (measure_l_equation (seq_l_cons p0 l)).\n    rewrite (measure_r_equation (seq_r_cons p1 r)).\n    intros Heq0 Heq1. subst. simpl. lia.\nQed.\n\nLemma eval_binary_decreases : forall s0 s1 s2 n0 n1 n2,\n  eval_binary s0 s1 s2 -> measure s0 = n0 ->\n  measure s1 = n1 -> measure s2 = n2 -> n1 < n0 /\\ n2 < n0.\nProof.\n  intros s0 s1 s2 n0 n1 n2 Heval. induction Heval.\n  - unfold measure. rewrite measure_l_equation.\n    rewrite (measure_l_equation (seq_l_cons p0 l)).\n    rewrite (measure_l_equation (seq_l_cons p1 l)).\n    intros Heq0 Heq1 Heq2. subst. simpl. lia.\nQed.\n\nDefinition normal_form_unary (s : seq_t) : Prop :=\n  ~ exists s', eval_unary s s'.\n\nDefinition normal_form_binary (s : seq_t) : Prop :=\n  ~ exists s' s'', eval_binary s s' s''.\n\nDefinition normal_form (s : seq_t) : Prop :=\n  normal_form_unary s /\\ normal_form_binary s.\n\nLemma prop_zero_measure : forall p,\n  measure_p p = O -> exists n, p = p_sym n.\nProof.\n  intros p Hm. rewrite measure_p_equation in Hm. induction p.\n  - exists n. reflexivity.\n  - discriminate.\n  - discriminate.\n  - discriminate.\n  - discriminate.\nQed.\n\nLemma seq_l_zero_measure : forall p l,\n  measure_l (seq_l_cons p l) = O -> exists n, p = p_sym n.\nProof.\n  intros p l. rewrite measure_l_equation. induction l.\n  - unfold measure_l. rewrite Plus.plus_0_r.\n    apply prop_zero_measure.\n  - rewrite measure_l_equation.\n    rewrite (Plus.plus_comm (measure_p p0) (measure_l l)).\n    rewrite (Plus.plus_assoc). intros Hm.\n    apply (Plus.plus_is_O (measure_p p + measure_l l) (measure_p p0)) in Hm as [ Hm Hp ].\n    apply IHl in Hm. assumption.\nQed.\n\nLemma seq_r_zero_measure : forall p r,\n  measure_r (seq_r_cons p r) = O -> exists n, p = p_sym n.\nProof.\n  intros p r. rewrite measure_r_equation. induction r.\n  - unfold measure_r. rewrite Plus.plus_0_r.\n    apply prop_zero_measure.\n  - rewrite measure_r_equation.\n    rewrite (Plus.plus_comm (measure_p p0) (measure_r r)).\n    rewrite (Plus.plus_assoc). intros Hm.\n    apply (Plus.plus_is_O (measure_p p + measure_r r) (measure_p p0)) in Hm as [ Hm Hp ].\n    apply IHr in Hm. assumption.\nQed.\n\nLemma plus_to_O : forall n0 n1,\n  n0 = O -> n1 = O -> n0 + n1 = O.\nProof.\n  lia.\nQed.\n\nLemma measure_zero_iff_normal_form : forall s,\n  measure s = O -> normal_form s.\nProof.\n  intros s.\n  unfold measure. destruct s as [ l r ]. induction l; induction r; intros Heq.\n  - split.\n    + unfold normal_form_unary, not. intros [ s Hex ]. inversion Hex.\n    + unfold normal_form_binary, not. intros [ s [ s' Hex ] ]. inversion Hex.\n  - split.\n    + unfold normal_form_unary, not. intros [s Hex].\n      apply Plus.plus_is_O in Heq as [ Hnil Hr ].\n      rewrite measure_r_equation in Hr.\n      apply Plus.plus_is_O in Hr as [ Hp Hr ].\n      apply (plus_to_O (measure_l seq_l_nil)) in Hr.\n      apply IHr in Hr.\n      clear IHr Hnil.\n      revert Hr.\n      intros [ H _ ]. unfold normal_form_unary, not in H. apply H. clear H.\n      apply prop_zero_measure in Hp as [ n Hp ]. subst. exists s.\n      \n      \n\n\n\n", "meta": {"author": "benmandrew", "repo": "vSequent", "sha": "5afa203dec826424fabca58f8084634582b0cce5", "save_path": "github-repos/coq/benmandrew-vSequent", "path": "github-repos/coq/benmandrew-vSequent/vSequent-5afa203dec826424fabca58f8084634582b0cce5/termination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.69919403071588}}
{"text": "Require Export XR_Rlt_trans.\nRequire Export XR_Rplus_lt_compat_r.\nRequire Export XR_Rplus_lt_compat_l.\n\nLocal Open Scope R_scope.\n\nLemma Rplus_lt_compat : forall r1 r2 r3 r4,\n  r1 < r2 ->\n  r3 < r4 ->\n  r1 + r3 < r2 + r4.\nProof.\n  intros u v w x.\n  intros huv hwx.\n  apply Rlt_trans with (u+x).\n  {\n    apply Rplus_lt_compat_l.\n    exact hwx.\n  }\n  {\n    apply Rplus_lt_compat_r.\n    exact huv.\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_Rplus_lt_compat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.699194030099222}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Lia Permutation Relations Bool Eqdep_dec.\n\nFrom Undecidability.Shared.Libs.DLW.Utils\n  Require Import utils_tac utils_nat.\n\nSet Implicit Arguments.\n\n(* Every class of X/~ is enumerated ie there is a surjective partial map\n    from nat to representatives of class *) \n\nDefinition nat_enum_cls X (R : X -> X -> Prop) := \n  { f : nat -> option X | forall x, exists y n, f n = Some y /\\ R y x }. \n\nNotation dec := ((fun X Y (R : X -> Y -> Prop) => forall x y, { R x y } + { R x y -> False }) _ _).\n\n(* A class function and its inverse, a function that computes representatives\n    with two equations characterizing the quotient *)\n\nDefinition quotient X (R : X -> X -> Prop) Y :=\n  { cls : X -> Y & \n  { rpr : Y -> X |\n         (forall y, cls (rpr y) = y)\n      /\\ (forall x1 x2, R x1 x2 <-> cls x1 = cls x2) } }.\n\nSection ep_quotient.\n\n  Variable (X : Type) (R : X -> X -> Prop) (f : nat -> option X) \n           (Hf : forall x, exists y n, f n = Some y /\\ R y x).\n \n  Hypothesis HR1 : equiv _ R.\n  Hypothesis HR2 : dec R.\n\n  Let T n m := \n    match f n, f m with\n      | Some x, Some y => R x y\n      | None  , None   => True\n      | _     , _      => False\n    end.\n\n  Let HT1 : equiv _ T.\n  Proof.\n    msplit 2.\n    + intros x; red; destruct (f x); auto; apply (proj1 HR1).\n    + intros x y z; unfold T.\n      destruct (f x); destruct (f y); destruct (f z); try tauto; apply HR1.\n    + intros x y; unfold T.\n      destruct (f x); destruct (f y); try tauto; apply HR1.\n  Qed.\n\n  Infix \"≈\" := T (at level 70, no associativity).\n\n  Let is_repr x n := \n    match f n with\n      | Some r => R r x\n      | None   => False\n    end.\n\n  Let is_repr_trans x1 x2 n : R x1 x2 -> is_repr x1 n -> is_repr x2 n.\n  Proof.\n    intros H1 H2; revert H2 H1.\n    unfold is_repr; destruct (f n); auto.\n    apply HR1.\n  Qed.\n\n  Let is_repr_dec : dec is_repr.\n  Proof. \n    intros x n.\n    unfold is_repr.\n    destruct (f n).\n    + apply HR2.\n    + tauto.\n  Qed.\n\n  Let is_repr_exists x : ex (is_repr x).\n  Proof.\n    destruct (Hf x) as (y & n & H1 & H2).\n    exists n; red; rewrite H1; auto.\n  Qed.\n\n  Let is_min_repr x n :=\n    is_repr x n /\\ forall m, is_repr x m -> n <= m.\n  \n  Let is_min_repr_inj x n1 n2 : is_min_repr x n1 -> is_min_repr x n2 -> n1 = n2.\n  Proof.\n    intros (H1 & H2) (H3 & H4).\n    apply Nat.le_antisymm; auto.\n  Qed.\n\n  Let is_min_repr_involutive x n : is_min_repr x n -> \n     match f n with \n       | Some y => is_min_repr y n\n       | None   => False\n     end.\n  Proof.\n    intros (H1 & H2); unfold is_min_repr, is_repr in *.\n    destruct (f n) as [ y | ]; try tauto. \n    split.\n    + apply (proj1 HR1).\n    + intros m; specialize (H2 m).\n      destruct (f m) as [ k | ]; try tauto.\n      intros H3; apply H2, (proj1 (proj2 HR1)) with (1 := H3); auto.\n  Qed.\n\n  Let find_min_repr x : sig (is_min_repr x).\n  Proof. \n    destruct min_dec with (P := is_repr x)\n      as (r & H1 & H2).\n    + intro; apply is_repr_dec.\n    + apply is_repr_exists.\n    + exists r; split; auto.\n  Qed.\n\n  Let is_min_repr_dec : dec is_min_repr.\n  Proof.\n    unfold is_min_repr, is_repr.\n    intros x n.\n    destruct (f n) as [ y | ].\n    2: right; tauto.\n    destruct (HR2 y x) as [ H1 | H1 ].\n    2: right; tauto.\n    destruct bounded_search with (m := n) (P := fun m => match f m with Some r => R r x | None => False end)\n      as [ (p & H2 & H3) | H ].\n    + intros m _; destruct (is_repr_dec x m); auto.\n    + case_eq (f p).\n      * intros r Hr.\n        right; intros (G1 & G2).\n        specialize (G2 p).\n        rewrite Hr in G2, H3.\n        specialize (G2 H3); lia.\n      * intros Hr; rewrite Hr in H3; tauto.\n    + left; split; auto.\n      intros m Hm.\n      destruct (le_lt_dec n m) as [ | C ]; auto.\n      exfalso; specialize (H _ C).\n      destruct (f m) as [ z | ]; tauto.\n  Qed.\n\n  Let P n := \n    match f n with\n      | Some x => if is_min_repr_dec x n then true else false\n      | None   => false\n    end.\n\n  Let P_spec n : P n = true <-> exists x, f n = Some x /\\ is_min_repr x n.\n  Proof.\n    unfold P.\n    destruct (f n) as [ x | ].\n    + destruct (is_min_repr_dec x n) as [ | C ]; split; try tauto.\n      * exists x; auto.\n      * discriminate.\n      * intros (y & Hy & ?).\n        destruct C; inversion Hy; auto.\n    + split; try discriminate.\n      intros (? & ? & _); discriminate.\n  Qed.\n\n  Let Y := sig (fun x => P x = true).\n\n  Let pi1_inj : forall x y : Y, proj1_sig x = proj1_sig y -> x = y.\n  Proof.\n    intros (x & H1) (y & H2); simpl; intros; subst; f_equal.\n    apply UIP_dec, bool_dec.\n  Qed.\n\n  Let Y_discrete : dec (@eq Y).\n  Proof.\n    intros (x & Hx) (y & Hy).\n    destruct (eq_nat_dec x y) as [ | H ].\n    + left; apply pi1_inj; simpl; auto.\n    + right; contradict H; inversion H; auto.\n  Qed.\n\n  Let is_min_repr_P n x : is_min_repr x n -> P n = true.\n  Proof.\n    intros H1.\n    apply P_spec; revert H1.\n    unfold is_min_repr, is_repr.\n    case_eq (f n).\n    + intros y Hy (H1 & H2).\n      exists y; msplit 2; auto.\n      * apply (proj1 HR1).\n      * intros m; specialize (H2 m).\n        destruct (f m) as [ z | ]; auto.\n        intros H; apply H2, (proj1 (proj2 HR1) _ y); auto.\n    + intros _ ([] & _).\n  Qed.\n\n  Let cls (x : X) : Y.\n  Proof.\n    destruct (find_min_repr x) as (n & Hn).\n    exists n; apply is_min_repr_P with x; auto.\n  Defined.\n\n  Let P_to_X n : P n = true -> { k | f n = Some k }.\n  Proof.\n    intros H; rewrite P_spec in H.\n    case_eq (f n).\n    + intros k _; exists k; auto.\n    + intros Hn; exfalso; revert Hn.\n      destruct H as (x & -> & _); discriminate.\n  Qed.\n\n  Let rpr (y : Y) := proj1_sig (P_to_X _ (proj2_sig y)).\n\n  Let Hrpr y : f (proj1_sig y) = Some (rpr y).\n  Proof. apply (proj2_sig (P_to_X _ (proj2_sig y))). Qed.\n\n  Let Hcr : forall y, cls (rpr y) = y.\n  Proof.\n    intros (n & Hn); simpl.\n    unfold rpr; simpl.\n    apply pi1_inj; simpl; unfold cls.\n    case (find_min_repr (proj1_sig (P_to_X n Hn))).\n    intros m Hm; simpl.\n    generalize Hn; rewrite P_spec; intros (y & G1 & G2).\n    destruct (P_to_X n Hn) as (z & Hz); simpl in Hm.\n    rewrite Hz in G1; inversion G1; subst z.\n    revert Hm G2; apply is_min_repr_inj.\n  Qed.\n\n  Let Hrc x1 x2 : R x1 x2 <-> cls x1 = cls x2.\n  Proof.\n    split.\n    + intros H; apply pi1_inj.\n      unfold cls.\n      case (find_min_repr x1); intros y1 (G1 & G2); simpl.\n      case (find_min_repr x2); intros y2 (G3 & G4); simpl.\n      apply Nat.le_antisymm.\n      * apply G2; revert G3.\n        apply is_repr_trans, (proj2 (proj2 HR1)); auto.\n      * apply G4; revert G1.\n        apply is_repr_trans; auto.\n    + unfold cls.\n      case (find_min_repr x1); intros y1 G1; simpl.\n      case (find_min_repr x2); intros y2 G2; simpl.\n      intros H; inversion H; subst y2; clear H.\n      apply proj1 in G1; apply proj1 in G2.\n      revert G1 G2; unfold is_repr.\n      destruct (f y1); try tauto; intros H.\n      apply HR1; revert H; apply HR1.\n  Qed.\n\n  Local Fact enum_quotient_rec : \n        { Y : Type & { _ : dec (@eq Y) & quotient R Y } }.\n  Proof using HR1 HR2 Hf.\n    exists Y, Y_discrete, cls, rpr; split; auto.\n  Qed.\n\nEnd ep_quotient.\n\n(* Given type X with a decidable equivalence ~ over X\n    such that the classes of X/~ can be enumerated then\n    one can build the quotient X/~ into a discrete type Y\n    and Y is necessarily enumerated, see below\n*) \n\nTheorem enum_quotient X R : \n          nat_enum_cls R \n       -> equiv X R\n       -> dec R\n       -> { Y : Type & { _ : dec (@eq Y) & quotient R Y } }.\nProof.\n  intros (f & Hf) H1 H2.\n  apply enum_quotient_rec with (1 := Hf) (R := R); auto.\nQed.\n\n(* A quotient of enumerated classes is automatically enumerated (for equality *)\n\nFact quotient_is_enum X R Y : nat_enum_cls R -> @quotient X R Y -> nat_enum_cls (@eq Y).\nProof.\n  intros (f & Hf) (c & r & H1 & H2).\n  exists (fun n => match f n with Some x => Some (c x) | None => None end).\n  intros y.\n  destruct (Hf (r y)) as (z & n & H3 & H4).\n  exists (c z), n; rewrite H3; split; auto.\n  rewrite <- (H1 y); apply H2; auto.\nQed.\n\n(*\nPrint nat_enum_cls.\nPrint quotient.\n\nCheck enum_quotient.\nCheck quotient_is_enum.\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/Shared/Libs/DLW/Utils/quotient.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6991940294952407}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (z : natural) : natural := plus lf3 z.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj146_coqofml_RdvLcC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735663, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6991597497683376}}
{"text": "(**\n総和（Σ）の補題 整数版\n\n2020_8_22 @suharahiromichi 自然数\n2022_6_12 @suharahiromichi 整数\n *)\nFrom mathcomp Require Import all_ssreflect.\nFrom mathcomp Require Import all_algebra.\nFrom common Require Import ssromega. (* ssromega *)\n\nImport GRing.Theory.         (* mulrA などを使えるようにする。 *)\nImport Num.Theory.           (* unitf_gt0 などを使えるようにする。 *)\nImport intZmod.              (* addz など *)\nImport intRing.              (* mulz など *)\nOpen Scope ring_scope.       (* 環の四則演算を使えるようにする。 *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Summation1.\n(**\n## 総和の結合と分配\n\n高校で習う、総和についての公式です。\n\n総和の範囲は、$m \\lt n$ としてmからnとします。\n$m \\ge n$ の場合は、Σの中身が単位元となり成立しません。\n\n```math\n\n\\sum_{i=m}^{n-1}a_i + \\sum_{i=m}^{n-1}b_i = \\sum_{i=m}^{n-1}(a_i + b_i) \\\\\n\n\\sum_{i=m}^{n-1}c a_i = c \\sum_{i=m}^{n-1}a_i \\\\\n\n\\sum_{i=m}^{n-1}(a_i c) = (\\sum_{i=m}^{n-1}a_i) c \\\\\n\n\\sum_{i=m}^{n-1} c = (n - m) c \\\\\n\n```\n*)\n  Lemma sum_split (m n : nat) (a b : nat -> int) :\n    (m < n)%N ->\n    \\sum_(m <= i < n)(a i) + \\sum_(m <= i < n)(b i) = \\sum_(m <= i < n)(a i + b i).\n  Proof. by rewrite big_split. Qed.\n  \n  Lemma sum_distrr (m n : nat) (c : int) (a : nat -> int) :\n    (m < n)%N ->\n    \\sum_(m <= i < n)(c * (a i)) = c * (\\sum_(m <= i < n)(a i)).\n  Proof. by rewrite big_distrr. Qed.\n  \n  Lemma sum_distrl (m n : nat) (a : nat -> int) (c : nat) :\n    (m < n)%N ->\n    \\sum_(m <= i < n)((a i) * c) = (\\sum_(m <= i < n)(a i)) * c.\n  Proof. by rewrite big_distrl. Qed.\n  \n  Lemma sum_nat_const_int (m n : nat) (c : int) :\n    (m < n)%N ->\n    \\sum_(m <= i < n) c = (n - m)%:Z * c.\n  Proof.\n    move=> H.\n    rewrite big_const_nat.\n    rewrite iter_addr_0.\n    rewrite mulrC.\n    rewrite -mulr_natr natz.\n    done.\n  Qed.\n  \n(**\n# Σの中身の書き換え\n\nΣの中の i は、ローカルに束縛されている（ラムダ変数である）ので、\n直接書き換えることはできません。一旦、取り出して書き換えることになります。\n *)\n  Lemma eq_sum (m n : nat) (a b : nat -> int) : a =1 b ->\n                         \\sum_(m <= i < n)(a i) = \\sum_(m <= j < n)(b j).\n  Proof.\n    move=> Hab.                             (* =1 は第1階の=です。 *)\n    apply: eq_big_nat => i Hmn.\n      by rewrite Hab.\n  Qed.\n  \n(**\n# 入れ子（ネスト）\n *)\n(**\n## ネストの入れ替え（総和どうしの場合）\n\n$$ \\sum_{i=0}^{m-1}(\\sum_{j=0}^{n-1)} a_{i j} =\n   \\sum_{j=0}^{n-1}(\\sum_{i=0}^{m-1)} a_{i j} $$\n*)\n  Lemma exchamge_sum (m n : nat) (a : nat -> nat -> int) :\n    \\sum_(0 <= i < m) (\\sum_(0 <= j < n) (a i j)) =\n    \\sum_(0 <= j < n) (\\sum_(0 <= i < m) (a i j)).\n  Proof. by rewrite exchange_big. Qed.\n  \n(**\n# Σを消す\n *)\n(**\n## 0を取り出す。\n\n$$ \\sum_{i \\in \\emptyset}a_i = 0 $$\n\n総和をとる範囲が無い場合（0以上0未満）は、単位元``0``になります。\n *)\n  Lemma sum_nil' (a : nat -> int) : \\sum_(0 <= i < 0)(a i) = 0.\n  Proof.\n    by rewrite big_nil.\n  Qed.\n  \n(**\n上記の補題は、1以上1未満などの場合にも適用できてしまいますが、任意のmとnで証明しておきます。\n*)\n  Lemma sum_nil (m n : nat) (a : nat -> int) :\n    (n <= m)%N -> \\sum_(m <= i < n)(a i) = 0.\n  Proof.\n    move=> Hmn.\n    have H : \\sum_(m <= i < n)(a i) = \\sum_(i <- [::])(a i).\n    - apply: congr_big => //=.\n      rewrite /index_iota.\n      have -> : (n - m = 0)%N by ssromega. (* apply/eqP; rewrite subn_eq0. *)\n      done.\n    - rewrite H.\n      by rewrite big_nil.\n  Qed.\n\n(**\n## ``a_n``項を取り出す。\n\n$$ \\sum_{i=n}^{n}a_i = a_n $$\n\n総和をとる範囲がひとつの項の場合（n以上n以下）は、``a n`` となります。\n *)\n  Lemma sum_nat1 (n : nat) (a : nat -> int) :\n    \\sum_(n <= i < n.+1)(a i) = a n.\n  Proof. by rewrite big_nat1. Qed.\n\n(**\n# インデックスを調整する補題\n*)\n(**\n## 総和の範囲を0起源に振りなおす。\n\n項のインデックスを調整して（ずらして）、mからn+mまでの総和の範囲を0からnまでにします。\n\n$$ \\sum_{i=m}^{n+m-1}a_i = \\sum_{i=0}^{n-1}a_{i+m} $$\n *)\n  Lemma sum_addn (m n : nat) (a : nat -> int) :\n    \\sum_(m <= i < n + m)(a i) = \\sum_(0 <= i < n)(a (i + m)%N).\n  Proof.\n    rewrite -{1}[m]add0n.\n    rewrite big_addn.\n    have -> : (n + m - m = n)%N by ssromega.\n    done.\n  Qed.\n\n(**\nこれは、任意のmで成り立ちますが、``Σ``の中の項のインデックスの``i.+1``を\n``i + 1`` に書き換えられないため、``i.+1`` と ``i.+2`` の場合については、\n個別に用意する必要があります。実際はこちらの方を使います。\n*)\n  Lemma sum_add1 (n : nat) (a : nat -> int) :\n    \\sum_(1 <= i < n.+1)(a i) = \\sum_(0 <= i < n)(a i.+1).\n  Proof. by rewrite big_add1 succnK. Qed.\n  \n  Lemma sum_add2 (n : nat) (a : nat -> int) :\n    \\sum_(2 <= i < n.+2)(a i) = \\sum_(0 <= i < n)(a i.+2).\n  Proof. by rewrite 2!big_add1 2!succnK. Qed.\n  \n(**\n# 最初の項、または、最後の項をΣの外に出す。\n *)\n(**\n## 最初の項をΣの外に出す。\n\n$$ \\sum_{i=m}^{n-1}a_i = a_m + \\sum_{i=m+1}^{n-1}a_i $$\n *)\n  Lemma sum_first (m n : nat) (a : nat -> int) :\n    (m < n)%N ->\n    \\sum_(m <= i < n)(a i) = a m + \\sum_(m.+1 <= i < n)(a i).\n  Proof.\n    move=> Hn.\n    by rewrite big_ltn.\n  Qed.\n\n(**\n総和の範囲の起点を変えずに、インデックスをずらす補題もあります。\n\n$$ \\sum_{i=m}^{n}a_i = a_m + \\sum_{i=m}^{n-1}a_{i + 1} $$\n*)\n  Lemma sum_first' (m n : nat) (a : nat -> int) :\n    (m <= n)%N ->\n    \\sum_(m <= i < n.+1)(a i) = a m + \\sum_(m <= i < n)(a i.+1).\n  Proof.\n    move=> Hn.\n    by rewrite big_nat_recl.\n  Qed.\n  \n(**\n## 最後の項をΣの外に出す。\n\nn(インデックスの上限)についての帰納法と組み合わせて使います。\n\n$$ \\sum_{i=m}^{n}a_i = \\sum_{i=m}^{n-1}a_i + a_n $$\n *)\n  Lemma sum_last (m n : nat) (a : nat -> int) :\n    (m <= n)%N ->\n    \\sum_(m <= i < n.+1)(a i) = \\sum_(m <= i < n)(a i) + a n.\n  Proof.\n    move=> Hmn.\n    by rewrite big_nat_recr.\n  Qed.\n\n(**\n## 数列の分割と結合\n\n$$ \\sum_{i=m}^{p}a_i = \\sum_{i=m}^{n}a_i + \\sum_{i=n}^{p}a_i $$\n *)\n  Lemma sum_cat' (m n1 n2 n : nat) (a : nat -> int) :\n    \\sum_(m <= i < m + n1 + n2) a i =\n    \\sum_(m <= i < m + n1) a i + \\sum_(m + n1 <= i < m + n1 + n2) a i.\n  Proof.\n    rewrite -big_cat.\n    f_equal.                       (* iインデックス部分を取り出す。 *)\n    rewrite /index_iota.\n    Check iota_add\n      : forall m n1 n2 : nat, iota m (n1 + n2) = iota m n1 ++ iota (m + n1) n2.\n    have -> : (m + n1 + n2 - m = n1 + n2)%N by ssromega.\n    have -> : (m + n1 - m = n1)%N by ssromega.\n    have -> : (m + n1 + n2 - (m + n1) = n2)%N by ssromega.\n    rewrite -iota_add.\n    done.\n  Qed.\n  \n  (* big_cat_nat を使えば、直接証明できる。 *)\n  Lemma sum_cat (m n p : nat) (a : nat -> int) :\n    (m <= n)%N -> (n <= p)%N ->\n    \\sum_(m <= i < p) a i = \\sum_(m <= i < n) a i + \\sum_(n <= i < p) a i.\n  Proof.\n    move=> Hmn Hnp.\n    by rewrite -big_cat_nat.\n      \n    Restart.\n    move=> Hmn Hnp.                         (* omega が使う。 *)\n    pose n1 := (n - m)%N.\n    pose n2 := (p - n)%N.\n    have -> : (p = m + n1 + n2)%N by rewrite /n1 /n2; ssromega.\n    have -> : (n = m + n1)%N by rewrite /n1; ssromega.\n    by apply: sum_cat'.\n  Qed.\n\nEnd Summation1.\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/common/ssrsumint.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6991597496859012}}
{"text": "Inductive Rotation : Type :=\n| R0 : Rotation\n| R120 : Rotation\n| R240 : Rotation.\n\nDefinition RaR (r2 r1 : Rotation) : Rotation:=\n  match r1 with\n  |R0 =>\n     (match r2 with\n     |R0 => R0\n     |R120 => R120\n     |R240 => R240\n      end)\n  |R120 =>\n     (match r2 with\n     |R0 => R120\n     |R120 => R240\n     |R240 => R0\n      end)\n  |R240 =>\n     (match r2 with\n     |R0 => R240\n     |R120 => R0\n     |R240 => R120 \n      end)\n  end.\n\nProposition R0_is_neutral_for_RaR_on_the_left:\n  forall (r : Rotation),\n    RaR R0 r = r.\nProof.\n  intro r.\n  induction r.\n  unfold RaR.\n  reflexivity.\n\n  unfold RaR.\n  reflexivity.\n  \n  unfold RaR.\n  reflexivity.\n\n  Restart.\n  intro r.\n  case r as [ | | ] eqn: H_r.\n\n  unfold RaR; reflexivity.\n\n  unfold RaR; reflexivity.\n\n  unfold RaR; reflexivity.\n\n  Restart.\n  intro r; case r as [ | | ] eqn: H_r; unfold RaR; reflexivity.\n\n  Restart.\n  intros [ | | ]; unfold RaR; reflexivity.\n\n  Restart.\n  intros [ | | ]; reflexivity.  \n  (* \nWe can unfold without writing unfold lemmas because RaR is not recursive.\n   *) \nQed.\n\n\nProposition R0_is_neutral_for_RaR_on_the_right:\n  forall (r : Rotation),\n    RaR R0 r = r.\nProof.\n  intros [ | | ]; reflexivity.\nQed.\n\nProposition RaR_is_commutative:\n  forall r1 r2: Rotation,\n    RaR r2 r1 = RaR r1 r2.\nProof.\n  intros r1 r2.\n  case r1 as [ | | ] eqn: H_r1.\n  case r2 as [ | | ] eqn: H_r2.\n  reflexivity.\n\n  unfold RaR.\n  reflexivity.\n\n  unfold RaR.\n  reflexivity.\n\n  unfold RaR.\n  reflexivity.\n\n  unfold RaR.\n  reflexivity.\n\n  Restart.\n  intros [ | | ] [ | | ]; reflexivity.\n\nQed.\n\n  \nProposition RaR_is_associative:\n  forall r1 r2 r3: Rotation,\n    RaR (RaR r3 r2) r1 = RaR r3 (RaR r2 r1).\nProof.\n  intros [ | | ] [ | | ] [ | | ]; reflexivity.\nQed.\n\nProposition RaR_is_nilpotent_with_order_3:\n  forall r : Rotation,\n    RaR (RaR r r) r = R0.\nProof.\n  intros [ | | ]; reflexivity.\nQed.\n\nInductive Reflection: Type :=\n| S_N : Reflection\n| S_SW : Reflection\n| S_SE : Reflection.\n\nDefinition SaS (s2 s1: Reflection) :=\n   match s1 with\n  |S_N =>\n     (match s2 with\n     |S_N => R0\n     |S_SW => R120\n     |S_SE => R240\n      end)\n  |S_SW =>\n     (match s2 with\n     |S_N => R240\n     |S_SW => R0\n     |S_SE => R120\n      end)\n  |S_SE =>\n     (match s2 with\n     |S_N => R120\n     |S_SW => R240\n     |S_SE => R0 \n      end)\n  end.\n\nProposition SaS_is_commutative:\n  forall s1 s2 : Reflection,\n  SaS s1 s2 = SaS s2 s1.\nProof.\n  (*\n  intros [ | | ] [ | | ]; reflexivity.\n   *)\n  intros s1 s2.\n  case s1 as [ | | ] eqn: H_s1.\n  case s2 as [ | | ] eqn: H_s2.\n\n  reflexivity.\n  unfold SaS.\nAbort.\n\nProposition SaS_is_not_commutative:\n  exists s1 s2 : Reflection,\n    (SaS s1 s2 <> SaS s2 s1).\nProof.\n  exists S_SW, S_SE.\n  unfold SaS.\n  intro H_absurd.\n  discriminate.\nQed.\n(*\nProposition SaS_is_associative:\n  forall s1 s2 : Reflection,\n  SaS (SaS s3 s2) s1 = SaS s3 (SaS s2 s1).\n  Proof.\nThis is type incorrect, as the codomain of SaS is a Rotation, and not a Reflection. \n *)\n\nProposition SaS_is_nilpotent_with_order_2:\n  forall s : Reflection,\n    SaS s s = R0.\nProof.\n  intros [ | | ]; reflexivity.\nQed.\n\nDefinition SaR (s : Reflection) (r : Rotation): Reflection :=\n   match r with\n  |R0 =>\n     (match s with\n     |S_N => S_N\n     |S_SW => S_SW\n     |S_SE => S_SE\n      end)\n  |R120 =>\n     (match s with\n     |S_N => S_SE \n     |S_SW => S_N\n     |S_SE => S_SW\n      end)\n  |R240 =>\n     (match s with\n     |S_N => S_SW\n     |S_SW => S_SE\n     |S_SE => S_N\n      end)\n  end.\n\n\nDefinition RaS (r : Rotation) (s : Reflection): Reflection :=\n   match s with\n  |S_N =>\n     (match r with\n     |R0 => S_N\n     |R120 => S_SE\n     |R240 => S_SW\n      end)\n  |S_SW =>\n     (match r with\n     |R0 => S_SW\n     |R120 => S_N\n     |R240 => S_SE\n      end)\n  |S_SE =>\n     (match r with\n     |R0 => S_SE\n     |R120 => S_SW\n     |R240 => S_N\n      end)\n  end.\n\nInductive Isomorphism : Type :=\n| IR : Rotation -> Isomorphism\n| IS : Reflection -> Isomorphism.\n\nDefinition Id : Isomorphism := IR R0.\n\nDefinition C (i2 i1 : Isomorphism) : Isomorphism :=\n  match i1 with\n  | IR r1 => match i2 with\n             | IR r2 => IR (RaR r2 r1)\n             | IS s2 => IS (SaR s2 r1)\n             end\n  | IS s1 => match i2 with\n             | IR r2 => IS (RaS r2 s1)\n             | IS s2 => IR (SaS s2 s1)\n             end\n  end.\n\nProposition Id_is_neutral_for_C_on_the_left :\n  forall i : Isomorphism,\n    C Id i = i.\nProof.\n  intros [ [ | | ] | [ | | ] ]. \n  unfold C.\n  unfold Id.\n  unfold RaR.\n  reflexivity.\n  Restart.\n\n  intro i.\n  unfold Id.\n  unfold C.\n  case i as [r| s] eqn: H_i.\n\n  case r as [ | | ] eqn: H_r.\n  unfold RaR.\n  reflexivity.\n  unfold RaR.\n  reflexivity.\n  unfold RaR.\n  reflexivity.\n  unfold RaR.\n  Restart.\n  \n  intros [ [ | | ] | [ | | ] ]; reflexivity.\nQed.\n\nProposition Id_is_neutral_for_C_on_the_right :\n  forall i : Isomorphism,\n    C i Id = i.\nProof.\n   intros [ [ | | ] | [ | | ] ]; reflexivity.\nQed.\n\n\nProposition C_is_associative:\n  forall i1 i2 i3 : Isomorphism,\n    C (C i3 i2) i1 = C i3 (C i2 i1).\nProof.\n  intros i1 i2 i3.\n  case i1 as [ [ | | ] | [ | | ] ] eqn:H_1.\n  case i2 as [ [ | | ] | [ | | ] ] eqn:H_2. \n  case i3 as [ [ | | ] | [ | | ] ] eqn:H_3.\n  \n  unfold C, SaS, SaR, RaS, RaR; reflexivity.\n  unfold C, SaS, SaR, RaS, RaR; reflexivity.\n  unfold C, SaS, SaR, RaS, RaR; reflexivity.\n  unfold C, SaS, SaR, RaS, RaR; reflexivity.\n\n  \nAbort.\n\n(* injective on the right, injective on the left *)\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-07_Rotations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.699159217123702}}
{"text": "Require Import Unicode.Utf8.\n\nInductive mynat : Set :=\n| zero : mynat\n| succ : mynat → mynat.\n\nDefinition one : mynat := succ zero.\nDefinition two : mynat := succ one.\n\nNotation \"0\" := zero.\nNotation \"1\" := one.\nNotation \"2\" := two.\n\nTheorem one_eq_succ_zero : 1 = succ 0.\nProof.\n  reflexivity.\nQed.\n\nTheorem two_eq_succ_one : 2 = succ 1.\nProof.\n  reflexivity.\nQed.\n\n(* `discriminate`: Prove structural inequality *)\n(* Goal of the form `C1 = C2` where C1 and C2 are different constructors of the same injective type *)\n\nLemma zero_ne_succ (a : mynat) : (0 : mynat) ≠ succ a.\nProof.\n  discriminate.\nQed.\n\n(* `injection`: Remove the same constructor from both sides of an equality *)\n(* Goal of the form `C a = C b` *)\n\nLemma succ_inj {a b : mynat} (h : succ a = succ b) : a = b.\nProof.\n  injection h.\n  intro f.\n  exact f.\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/Definition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240721511739, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.699159213080415}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom GraphTheory Require Import preliminaries bij digraph.\nFrom GraphTheory Require Import sgraph dom partition.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** * Clique Number, Stable Set Number and Chromatic Number *)\n\n(** In this file, we define the graph parameters α,ω, and χ. As much\nof the reasoning about these parameters is concerned with the values\nfor the parameters on induced subgraphs, we define the parameters as\nfunctions of type [mem_pred G \\to nat] and introduce a notation that\ninsertes the required [mem] cast. For [G : sgraph] and [A : {set G}],\nwe can therefore write both both χ(G) and χ(A). This (drastically)\nreduces the amount of (induced) subgraphs that need to be constructed,\nsignificantly simplifying the proofs. *)\n\n(** ** Clique number *)\n\nSection Cliques.\nVariables (G : sgraph).\nImplicit Types (H K : {set G}).\n\nDefinition cliques H := [set K : {set G} | (K \\subset H) && cliqueb K].\n\nLemma cliques_gt0 A : 0 < #|cliques A|. \nProof.\napply/card_gt0P; exists set0; rewrite inE sub0set; apply/cliqueP.\nby apply: small_clique; rewrite cards0.\nQed.\n\nLemma cliquesW (A B K : {set G}) : A \\subset B -> K \\in cliques A -> K \\in cliques B.\nProof. \nby move=> subAB; rewrite !inE => /andP[subKA ->]; rewrite (subset_trans subKA). \nQed.\n\nLemma cliques_subset (A K : {set G}) : K \\in cliques A -> K \\subset A.\nProof. by rewrite !inE => /andP[-> _]. Qed.\n\nLemma cliqueU1 x K : K \\subset N(x) -> clique K -> clique (x |: K).\nProof. \nmove => /subsetP subKNx clK u v /setU1P[-> {u}|uK] /setU1P[-> {v}|vK].\n- by rewrite eqxx.\n- by move/subKNx : vK; rewrite inE.\n- by move/subKNx : uK; rewrite inE sgP.\n- exact: clK.\nQed.\n\nLemma sub_clique K K' : K' \\subset K -> clique K -> clique K'.\nProof. by move=> /subsetP subK clK x y /subK xK /subK yK; exact: clK. Qed.\n\nLemma cliqueD K H : clique K -> clique (K :\\: H).\nProof. by move => clK x y /setDP[xK _] /setDP[yK _]; exact: clK. Qed.\n\nLemma cliquesD K H S : K \\in cliques (H :\\: S) -> K \\in cliques H.\nProof. by rewrite !inE subsetD -andbA => /and3P[-> _ ->]. Qed.\n\nDefinition omega_mem (A : mem_pred G) := \n  \\max_(B in cliques [set x in A]) #|B|.\n\nEnd Cliques.\n\nNotation \"ω( A )\" := (omega_mem (mem A)) (format \"ω( A )\").\n\nDefinition maxcliques (G : sgraph) (H : {set G}) := \n  [set K in cliques H | ω(H) <= #|K|].\n\nSection OmegaBasics.\nVariables (G : sgraph).\nImplicit Types (A B K H : {set G}).\n\nLemma maxclique_clique K H : K \\in maxcliques H -> clique K.\nProof. by rewrite !inE -andbA => /and3P[_ /cliqueP ? _]. Qed.\n\nLemma maxcliquesW S H : S \\in maxcliques H -> S \\in cliques H.\nProof. by rewrite !inE -andbA => /and3P[-> -> _]. Qed.\n\nVariant omega_spec A : nat -> Prop :=\n  OmegaSpec K of K \\in maxcliques A : omega_spec A #|K|.\n\nLemma omegaP A : omega_spec A ω(A).\nProof. \nrewrite /omega_mem setE. \nhave [/= K clK maxK] := eq_bigmax_cond (fun A => #|A|) (cliques_gt0 A).\nby rewrite maxK; apply: OmegaSpec; rewrite inE clK -maxK -{2}[A]setE leqnn.\nQed.\n\nLemma clique_bound K A : K \\in cliques A -> #|K| <= ω(A).\nProof. by move => clK; apply: bigmax_sup (leqnn _); rewrite setE. Qed.\n\nLemma card_maxclique K H : K \\in maxcliques H -> #|K| = ω(H).\nProof. \nrewrite inE => /andP[clK ltK]; apply/eqP; rewrite eqn_leq ltK andbT.\nexact: clique_bound.\nQed.\n\nLemma sub_omega A B : A \\subset B -> ω(A) <= ω(B).\nProof.\nmove=> subAB; have [K] := omegaP A; rewrite inE => /andP[clA _]. \nexact/clique_bound/(cliquesW subAB).\nQed.\n\nLemma maxclique_disjoint K H A : \n  K \\in maxcliques H -> [disjoint K & A] -> K \\in maxcliques (H :\\: A).\nProof.\nrewrite !inE -!andbA subsetD => /and3P[-> -> maxK] -> /=. \napply: leq_trans (sub_omega _) maxK. exact: subsetDl.\nQed.\n\nLemma maxclique_opn H K v : \n  v \\in H -> K \\in maxcliques H -> K \\subset N(v) -> v \\in K.\nProof.\nrewrite !inE -andbA => vH /and3P[subKH /cliqueP clK maxK] subNvK.\nhave/cliqueP clvK : clique (v |: K) by apply: cliqueU1.\napply: contraTT maxK => vNK ; rewrite -ltnNge.\nrewrite -add1n -[1 + _]/(true + #|K|) -vNK -cardsU1; apply: clique_bound.\nby rewrite !inE clvK subUset sub1set vH subKH.\nQed.\n\nLemma omega0 : ω(@set0 G) = 0.\nProof.  \nby case: omegaP => K; rewrite !inE subset0 -andbA => /andP[/eqP-> _]; rewrite cards0.\nQed.\n\nLemma omega_eq0 A : (ω(A) == 0) = (A == set0).\nProof.\napply/idP/idP => [|/eqP->]; last by rewrite omega0.\napply: contraTT => /set0Pn[x xH]; rewrite -lt0n -(cards1 x).\napply: clique_bound. rewrite inE sub1set xH. exact/cliqueP/clique1.\nQed.\n\n(** TODO: if [stable S], the difference is exactly 1 *)\nLemma omega_cut H S : \n  {in maxcliques H, forall K, S :&: K != set0} -> ω(H :\\: S) < ω(H).\nProof.\nmove/forall_inP; rewrite ltnNge; apply: contraTN; rewrite negb_forall_in.\nhave [/= K maxK geH] := omegaP (H :\\: S).\nmove: maxK; rewrite inE => /andP[clK cardK].\napply/exists_inP; exists K; first by rewrite inE geH (cliquesD clK).\nby move: clK; rewrite !inE subsetD negbK setI_eq0 disjoint_sym -andbA => /and3P[_ -> _].\nQed.\n\nEnd OmegaBasics.\n\n(** ** Stable Set Number *)\n\nSection StableSets.\nVariable (G : sgraph).\nImplicit Types (H A S : {set G}).\n\nDefinition stabsets H := [set S : {set G} | S \\subset H & stable S].\n\n(* mostly useful in the right to left region to reestablish [stabsets] *)\nLemma in_stabsets B H : B \\in stabsets H = (B \\subset H) && @stable G B.\nProof. by rewrite !inE. Qed.\n\nLemma stabsetsP H S : reflect (S \\subset H /\\ stable S) (S \\in stabsets H).\nProof. by rewrite in_stabsets; exact: andP. Qed.\n\nLemma stabsets_gt0 A : 0 < #|stabsets A|. \nProof.\napply/card_gt0P; exists set0; rewrite inE sub0set; apply/stableP.\nby move => u v; rewrite inE.\nQed.\n\nDefinition alpha_mem (A : mem_pred G) := \n  \\max_(S in stabsets [set x in A]) #|S|.\n\nLemma stable_compl A : stable (A : {set compl G}) = cliqueb A.\nProof. \napply/stableP/cliqueP => [stabA|clA] x y xA yA; first move=> xDy.\n  by move: (stabA _ _ xA yA); rewrite {1}/edge_rel/= xDy negbK.\nhave [<-|xDy] := eqVneq x y; by [rewrite sgP|rewrite /edge_rel/= xDy clA].\nQed.\n\n(** alternative proof, using duality, likely not worth it *)\nLemma clique_compl A : cliqueb (A : {set compl G}) = stable A.\nProof. \napply/cliqueP/stableP => [clA|stabA] x y xA yA; last move=> xDy.\n  have [<-|xDy] := eqVneq x y; first by rewrite sgP.\n  by move:(clA _ _ xA yA xDy); rewrite {1}/edge_rel/= xDy.\nby move: (stabA _ _ xA yA); rewrite {2}/edge_rel/= xDy.\nQed.\n\nEnd StableSets.\n\nNotation \"α( A )\" := (alpha_mem (mem A)) (format \"α( A )\").\n\nDefinition maxstabsets (G : sgraph) (H : {set G}) := \n  [set S in stabsets H | α(H) <= #|S|].\n\nSection AlphaBasics.\nVariables (G : sgraph).\nImplicit Types (A B K S H : {set G}).\n\nVariant alpha_spec A : nat -> Prop :=\n  AlphaSpec S of S \\in maxstabsets A : alpha_spec A #|S|.\n\nLemma maxstabset_stable S H : S \\in maxstabsets H -> stable S.\nProof. by rewrite !inE -andbA => /and3P[_ -> _]. Qed.\n\nLemma maxstabsetW S H : S \\in maxstabsets H -> S \\in stabsets H.\nProof. by rewrite !inE -andbA => /and3P[-> -> _]. Qed.\n\nLemma maxstabsetS S H : S \\in maxstabsets H -> S \\subset H.\nProof. by rewrite !inE -andbA => /and3P[-> _ _]. Qed.\n\nLemma alphaP A : alpha_spec A α(A).\nProof. \nrewrite /alpha_mem setE. \nhave [/= S stabS maxS] := eq_bigmax_cond (fun A => #|A|) (stabsets_gt0 A).\nby rewrite maxS; apply: AlphaSpec; rewrite inE stabS -maxS -{2}[A]setE leqnn.\nQed.\n\nLemma stabset_bound S A : S \\in stabsets A -> #|S| <= α(A).\nProof. by move => stabS; apply: bigmax_sup (leqnn _); rewrite setE. Qed.\n\nLemma card_maxstabset K H : K \\in maxstabsets H -> #|K| = α(H).\nProof. \nrewrite inE => /andP[stabS ltS]; apply/eqP; rewrite eqn_leq ltS andbT.\nexact: stabset_bound.\nQed.\n\nLemma alpha0 : α(set0 : {set G}) = 0.\nProof. \nby case: alphaP => S; rewrite !inE subset0 -!andbA => /and3P[/eqP ->]; rewrite cards0.\nQed.\n\nLemma alpha_eq0 H : (α(H) == 0) = (H == set0).\nProof.\napply/idP/idP => [|/eqP->]; last by rewrite alpha0.\napply: contraTT => /set0Pn[x xH]; rewrite -lt0n -(cards1 x).\nby apply: stabset_bound; rewrite !inE stable1 sub1set xH.\nQed.\n\nEnd AlphaBasics.\n\n(** ** chromatic number *)\n\nDefinition coloring (G : sgraph) (P : {set {set G}}) (D : {set G}) :=\n  partition P D && [forall S in P, stable S].\n\nDefinition trivial_coloring (G : sgraph) (A : {set G}) := \n  [set [set x] | x in A].\n\nLemma trivial_coloringP (G : sgraph) (A : {set G}) :\n  coloring (trivial_coloring A) A.\nProof.\napply/andP; split; last by apply/forall_inP=> ? /imsetP[x xA ->]; exact: stable1.\nsuff -> : trivial_coloring A = preim_partition id A by apply: preim_partitionP.\nhave E x : x \\in A -> [set x] = [set y in A | x == y].\n  by move=> xA; apply/setP => y; rewrite !inE eq_sym andb_idl // => /eqP<-.\nby apply/setP => P; apply/imsetP/imsetP => -[x xA ->]; exists x => //; rewrite E.\nQed.\nArguments trivial_coloringP {G A}.\n\nDefinition chi_mem (G : sgraph) (A : mem_pred G) := \n  #|[arg min_(P < trivial_coloring [set x in A] | coloring P [set x in A]) #|P|]|.\n\nNotation \"χ( A )\" := (chi_mem (mem A)) (format \"χ( A )\").\n\n\nSection Basics.\nVariable (G : sgraph).\nImplicit Types (P : {set {set G}}) (A B C D H : {set G}).\n\n(** the [sub_partition] is actually a sub_coloring *)\nLemma sub_coloring P D A :\n  coloring P D -> A \\subset D -> coloring (sub_partition P A) A.\nProof.\ncase/andP => partP /forall_inP/= stabP subAD; apply/andP;split.\n  exact: sub_partitionP.\nhave/subsetP sub := sub_partition_sub partP subAD.\napply/forall_inP => S {}/sub /imsetP [B BP ->]. \nby apply: sub_stable (stabP _ BP); apply: subsetIl.\nQed.\n\nLemma empty_coloring : coloring set0 (@set0 G).\nProof. \nby rewrite /coloring partition_set0 eqxx; apply/forall_inP => S; rewrite inE. \nQed.\n\nLemma coloringD1 P S H : coloring P H -> S \\in P -> coloring (P :\\ S) (H :\\: S).\nProof. \nmove=> /andP[partP stabP] SP; apply/andP; split; first exact: partitionD1.\nby apply/forall_inP => A /setD1P[_ /(forall_inP stabP)].\nQed.\n\nLemma coloringU1 P S H : \n  stable S -> S != set0 -> coloring P H -> [disjoint S & H] -> coloring (S |: P) (S :|: H).\nProof.\nmove=> stS SD0 /andP[partP stabP] disHS; apply/andP; split; first exact: partitionU1.\nby apply/forall_inP => A /setU1P[-> //|/(forall_inP stabP)].\nQed.\n\nVariant chi_spec A : nat -> Prop :=\n  ChiSpec P of coloring P A & (forall P', coloring P' A -> #|P| <= #|P'|) \n  : chi_spec A #|P|.\n\n(** We can always replace [χ(A)] with [#|P|] for some optimal coloring [P]. *)\nLemma chiP A : chi_spec A χ(A).\nProof.\nrewrite /chi_mem; case: arg_minnP; first exact: trivial_coloringP.\nby move=> P; rewrite setE => ? ?; apply: ChiSpec.\nQed.\n\nLemma color_bound P A : coloring P A -> χ(A) <= #|P|.\nProof. by move => col_P; case: chiP => P' _ /(_ _ col_P). Qed.\n\nLemma coloring_stabsetP P D : \n  reflect (partition P D /\\ {in P, forall B, B \\in stabsets D}) (coloring P D).\nProof.\napply: (iffP andP) => -[partP stabP]; split => //; [|apply/forall_inP] => B BP.\n  by rewrite inE (partitionS partP) ?(forall_inP stabP).\nby move/stabP : BP; rewrite !inE => /andP[_ ->].\nQed.\n\nLemma chi0 : χ(@set0 G) = 0.\nProof. \napply/eqP; rewrite -leqn0; apply: leq_trans (color_bound empty_coloring) _.\nby rewrite cards0.\nQed.\n\nLemma leq_chi A : χ(A) <= #|A|.\nProof. \ncase: chiP => C col_C /(_ _ (@trivial_coloringP _ A)).\nrewrite /trivial_coloring card_imset //. exact: set1_inj.\nQed.\n\nLemma sub_chi A B : A \\subset B -> χ(A) <= χ(B).\nProof.\nmove=> subAB; case: (chiP B) => P col_P opt_P.\nhave col_S := sub_coloring col_P subAB.\napply: leq_trans (color_bound col_S) (card_sub_partition _ subAB).\nby case/andP : col_P.\nQed.\n\nLemma cliqueIstable A C : clique C -> stable A -> #|C :&: A| <= 1.\nProof.\nmove => clique_C; apply: contraTT; rewrite -ltnNge.\ncase/card_gt1P => x [y] [/setIP[xA xC] /setIP[yA yC] xDy].\napply/stablePn; exists x, y; split => //. exact: clique_C.\nQed.\n\nLemma chi_clique C : clique C -> χ(C) = #|C|.\nProof.\nmove=> clique_C; apply/eqP; rewrite eqn_leq leq_chi /=.\nhave [P /andP[partP /forall_inP /= stabP] opt_P] := chiP.\nsuff S A : A \\in P -> #|A| = 1. \n{ rewrite (card_partition partP); under eq_bigr => A ? do rewrite S //.\n  by rewrite sum_nat_const muln1. }\nmove=> AP; apply/eqP; rewrite eqn_leq card_gt0 (partition_neq0 partP) //. \nrewrite andbT -(@setIidPl _ A C _) ?(partitionS partP) // setIC.\nexact : cliqueIstable (stabP _ _).\nQed.\n\nLemma omega_leq_chi A : ω(A) <= χ(A).\nProof.\ncase: omegaP => C; rewrite !inE -andbA => /and3P[subCA /cliqueP clique_C _].\nby apply: leq_trans (sub_chi subCA); rewrite chi_clique.\nQed.\n\nLemma chiD1 H S : stable S -> χ(H) <= χ(H :\\: S).+1.\nProof.\nmove=> stabS; wlog subSH : S stabS / S \\subset H.\n  move => /(_ (S :&: H)); rewrite setDIr setDv setU0 subsetIr; apply => //.\n  by apply: sub_stable stabS; rewrite subsetIl.\nhave [->|SD0] := eqVneq S set0; first by rewrite setD0.\ncase: (chiP (H :\\: S)) => P colP _; have := coloringU1 stabS SD0 colP. \nrewrite disjoint_sym disjoints_subset subsetDr [S :|: _]setUC setDK // => /(_ isT) => colP'.\nby apply: leq_trans (color_bound colP') _; rewrite cardsU1; case (_ \\in _).\nQed.\n\nLet setG : [set x in mem [set: G]] = [set x in mem G]. \nProof. by apply/setP => x; rewrite !inE. Qed.\n\nLemma alphaT : α([set: G]) = α(G). \nProof. by rewrite /alpha_mem setG. Qed.\n\nLemma omegaT : ω([set: G]) = ω(G). \nProof. by rewrite /omega_mem setG. Qed.\n\nLemma chiT : χ([set: G]) = χ(G).\nProof. by rewrite /chi_mem setG. Qed.\n\nEnd Basics.\n\n\nNotation sval := (@sval _ _).\n\nSection ISubgraph.\nVariables (F G : sgraph) (i : F ⇀ G).\nLet i_inj := isubgraph_inj i.\n\nLemma cliqueb_isubgraph (K : {set F}) : cliqueb K = cliqueb (i @: K).\nProof.\nrewrite /cliqueb (@forall2_imset _ _ i i).\napply: eq_forall_in => x xK; apply: eq_forall_in => y yK.\nby rewrite (inj_eq (isubgraph_inj i)) isubgraph_mono.\nQed.\n\nLemma stable_isubgraph (S  : {set F}) : stable S = stable (i @: S).\nProof.\nrewrite !stableEedge (@forall2_imset _ _ i i).\napply: eq_forall_in => x xS; apply: eq_forall_in => y yS.\nby rewrite isubgraph_mono.\nQed.\n\nLemma coloring_isubgraph (P : {set {set F}}) (D : {set F}) : \n  coloring P D = @coloring G [set i @: (S : {set F}) | S in P] (i @: D).\nProof.\nrewrite /coloring -imset_partition; last exact: isubgraph_inj.\nby rewrite forall_imset; under [in RHS]eq_forallb => S do rewrite -stable_isubgraph.\nQed.\n\nLemma preim_coloring (P : {set {set G}}) (D : {set F}) : \n  coloring P (i @: D) -> coloring [set i @^-1: (B : {set G}) | B in P] D.\nProof.\nmove => colP; rewrite coloring_isubgraph -imset_comp /comp /=.\nhave coB B : B \\in P -> B \\subset codom i. \n{ case/andP: colP => partP _; move/(partitionS partP) => sub.\n  apply: subset_trans sub _. exact: imset_codom. }\nunder [X in coloring X _]eq_in_imset => B BP. \n  rewrite (can_preimset i) ?coB //; over. \nby rewrite imset_id.\nQed.\n\nLemma chi_isubgraph (A : {set F}) : χ(A) = χ(i @: A).\nProof.\napply/eqP; rewrite eqn_leq; apply/andP; split.\n- case: (chiP (i @: A)) => P /preim_coloring colP minP.\n  exact: leq_trans (color_bound colP) (leq_imset_card _ _).\n- case: (chiP A) => P colP minP.\n  rewrite coloring_isubgraph in colP; apply: leq_trans (color_bound colP) _.\n  by rewrite card_imset //; apply/imset_inj/isubgraph_inj.\nQed.\n\nLemma isubgraph_cliques (B K : {set F}) : \n  (K \\in cliques B) = (i @: K \\in cliques (i @: B)).\nProof. by rewrite !inE inj_imsetS // -cliqueb_isubgraph. Qed.\n\nLemma clique_to_isubgraph (K A : {set G}) : \n  K \\in cliques A -> i @^-1: K \\in cliques (i @^-1: A).\nProof.\nrewrite !inE => /andP[subKA /cliqueP clK]. \nrewrite preimsetS //= cliqueb_isubgraph; apply/cliqueP.\nby apply: sub_clique clK; rewrite sub_imset_pre preimsetS.\nQed.\n\nLemma can_inj_imset (A : {set F}) : i @^-1: (i @: A) = A.\nProof. by apply/setP => x; rewrite !inE (mem_imset). Qed.\n\nLemma omega_isubgraph (B : {set F}) : ω(B) = ω(i @: B).\nProof.\napply/eqP; rewrite eqn_leq; apply/andP; split.\n- have [K] := omegaP B. \n  rewrite inE isubgraph_cliques => /andP[ckK _]; rewrite -(card_imset _ i_inj).\n  exact: clique_bound.\n- have [K] := omegaP; rewrite inE => /andP[clK].\n  move/clique_to_isubgraph : (clK). rewrite can_inj_imset => clK' _. \n  apply: leq_trans (clique_bound clK'). rewrite inj_card_preimset //.\n  exact: subset_trans (cliques_subset clK) (imset_codom _ _).\nQed.\n\nEnd ISubgraph.\n\n(** We have proper duality reasoning at this point *)\nLemma maxcliques_compl (G : sgraph) (H : {set G}) : \n  maxcliques (H : {set compl G}) = maxstabsets H.\nProof.\napply/setP => A. rewrite !inE clique_compl; apply: andb_id2l => /andP[subAH stabA].\nrewrite /omega_mem /alpha_mem setE /=.\nby under eq_bigl => B do rewrite inE clique_compl -(@in_stabsets G).\nQed.\n\nLemma omega_compl (G : sgraph) (A : {set G}) : ω(A : {set compl G}) = α(A).\nProof.\ncase: omegaP => K. rewrite maxcliques_compl. exact: (@card_maxstabset G). \nQed.\n\nLemma alpha_isubgraph (F G : sgraph) (i : F ⇀ G) (A : {set F}) : α(A) = α(i @: A).\nProof. \nby rewrite -omega_compl (omega_isubgraph (isubgraph_compl i)) omega_compl. \nQed.\n\nLemma maxstabsets_compl (G : sgraph) (H : {set G}) : \n  maxstabsets (H : {set compl G}) = maxcliques H.\nAbort. \n\nLemma alpha_compl (G : sgraph) (A : {set G}) : α(A : {set compl G}) = ω(A).\nAbort.\n\nSection Induced.\nVariables (G : sgraph) (H : {set G}).\nLet i := induced_isubgraph H.\n\nLemma alpha_induced : α(induced H) = α(H).\nProof. by rewrite -alphaT (alpha_isubgraph i) imset_valT setE. Qed.\n\nLemma omega_induced : ω(induced H) = ω(H).\nProof. by rewrite -omegaT (omega_isubgraph i) imset_valT setE. Qed.\n\nLemma chi_induced : χ(induced H) = χ(H).\nProof. by rewrite -chiT (chi_isubgraph i) imset_valT setE. Qed.\n\nLemma cliqueb_induced (K : {set induced H}) : cliqueb K = cliqueb (val @: K).\nProof. exact: (cliqueb_isubgraph i). Qed.\n\nLemma stable_induced (K : {set induced H}) : stable K = stable (val @: K).\nProof. exact: (stable_isubgraph i). Qed.\n\nEnd Induced.\n\nLemma maxstabset_to_induced (G : sgraph) (H : {set G}) (S : {set G}) : \n  S \\in maxstabsets H -> val @^-1: S \\in maxstabsets [set: induced H].\nProof.\npose i := induced_isubgraph H.\nrewrite !inE subsetT (stable_isubgraph i) -andbA /= => /and3P[S1 S2 S3].\nhave subSi : S \\subset codom i. \n{ apply: subset_trans S1 _; apply/subsetP => x xH. by apply/codomP; exists (Sub x xH). }\nrewrite (@can_preimset _ _ i) ?S2 //= (@inj_card_preimset _ _ i) //=.\nrewrite alphaT alpha_induced //. exact: val_inj.\nQed.\n\n(** A coloring consisting of maximal stable sets is optimal *)\nLemma maxstabset_coloring (G : sgraph) (P : {set {set G}}) (D : {set G}) :\n  partition P D -> {in P, forall S, S \\in maxstabsets D} -> χ(D) = #|P|.\nProof.\nmove=> partP maxP; have [D0|[x xD]] := set_0Vmem D. \n  by subst D; apply/esym/eqP; rewrite chi0 cards_eq0 -partition_set0.\nhave colP : coloring P D. \n  by apply/coloring_stabsetP; split => // B /maxP/maxstabsetW.\napply/eqP; rewrite eqn_leq (color_bound colP) /=.\nhave [P' /coloring_stabsetP[partP' stabP'] _] := chiP. \nhave [trivP trivP'] : trivIset P /\\ trivIset P'.\n  by case/and3P : partP; case/and3P : partP'.\napply: contraTT (leqnn #|D|); rewrite -!ltnNge => lt_P'_P.\nrewrite -{1}(cover_partition partP') -(cover_partition partP).\nrewrite -(eqP trivP) -(eqP trivP').\nunder [X in _ < X]eq_bigr => B BP do rewrite (card_maxstabset (maxP _ BP)).\napply: (@leq_ltn_trans (#|P'| * α(D))).\n  by rewrite -sum_nat_const; apply: leq_sum => B /stabP'; apply: stabset_bound.\nrewrite sum_nat_const ltn_mul2r lt0n alpha_eq0 lt_P'_P andbT.\nby apply/set0Pn; exists x.\nQed.\n\n\nSection Iso.\nVariables (F G : sgraph) (i : diso F G).\nImplicit Types (A : {set F}).\n\nLet i_mono : {mono i : x y / x -- y}.\nProof. by move => x y; rewrite edge_diso. Qed.\n\nLet i_inj : injective i.\nProof. by apply: (can_inj (g := i^-1)) => x; rewrite bijK. Qed.\n\nDefinition i' : F ⇀ G := ISubgraph i_inj i_mono.\n\n(* TODO *)\n\nLemma diso_stable A : stable A = stable (i @: A).\nAbort.\n\nLemma diso_clique A : cliqueb A = cliqueb (i @: A).\nAbort.\n\nLemma diso_omega A : ω(A) = ω(i @: A).\nAbort.\n\nLemma diso_chi A : χ(A) = χ(i @: A).\nAbort.\n\nEnd Iso.\n", "meta": {"author": "coq-community", "repo": "graph-theory", "sha": "18bdabc919f6b20946f40cd5d4fbb5143c46a2bf", "save_path": "github-repos/coq/coq-community-graph-theory", "path": "github-repos/coq/coq-community-graph-theory/graph-theory-18bdabc919f6b20946f40cd5d4fbb5143c46a2bf/theories/core/coloring.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6991556975743358}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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) : natural := plus y (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj238_coqofml_QqgxUM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6991556953868062}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf4 : natural) (lf1 : natural) : natural := plus lf4 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/goal33conj121_coqofml_l6Ujho.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.6990697192159189}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) : natural := mult y lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_90_mult_zero/goal33conj53_coqofml_SILhYF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6990697124708243}}
{"text": "Require Import Arith.\nLemma plus1: forall x:nat,x+2=x+1+1.\nProof.\n  intros.\n  SearchRewrite((_ + _)).\n  rewrite plus_assoc_reverse.\n  simpl.\n  reflexivity.\nQed.\n\nLemma ord: forall x:nat, x+1<x+1+1->x+1<x+2.\nProof.\n  intros.\n  SearchRewrite(_+_).\n  rewrite BinInt.ZL0.\n  rewrite Nat.add_assoc.\n  apply H.\nQed.\n\nTheorem plus2: (forall x:nat, x<x+1)->(forall x y z:nat, (x<y) -> (y<z)->x<z)->(forall x:nat, x<(x+1)+1).\nProof.\n  intros.\n  apply (H0 x (x+1) (x+1+1)).\n  apply (H x).\n  apply (H (x+1)).\nQed.\n\nTheorem ordlaw: forall x y z:nat, x<y->y<z->x<y<z.\nProof.\n  auto.\nQed.\n\nTheorem plus2': (forall x:nat, x<x+1)->(forall x y z:nat, x<y<z->x<z)->(forall x:nat, x<(x+1)+1).\nProof.\n  intros.\n  apply plus2.\n  apply H.\n  intros.\n  apply (H0 x0 y z).\n  apply (ordlaw x0 y z).\n  apply H1.\n  apply H2.\nQed.\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/testofmine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6990697122101953}}
{"text": "Require Import Coq.NArith.NArith\n  Znumtheory Lia\n  Zdiv Zpow_facts.\nFrom Coq Require Import Even.\n\nSection Fn.\n  \n\n  Fixpoint repeat_op_ntimes_rec (e : N) (n : positive) (w : N) : N :=\n    match n with\n    | xH => N.modulo e w\n    | xO p => let ret := repeat_op_ntimes_rec e p w in \n        N.modulo (ret * ret) w\n    | xI p => let ret := repeat_op_ntimes_rec e p w in \n        N.modulo (e * (ret * ret)) w \n    end.\n\n  Definition Npow_mod (e : N) (n w : N) :=\n    match n with\n    | N0 => Npos xH\n    | Npos p => repeat_op_ntimes_rec e p w \n    end.\n\n\n  (* Npow_mod is an efficient function *)\n\n  (* Inducive Type to capture the complexity of  \n    repeat_op_ntimes_rec. This is suffices for \n    our purpose because we will call this \n    function for exponentiation. In sigma protocol, \n    we need to demonstrate that it's efficient, i.e., \n    linear in number of bits (complexity bounded by \n    log). However, this won't scale for a bigger \n    project because we can't compose the \n    inductive datatype. Also see:\n    https://users.cs.northwestern.edu/~robby/publications/papers/flops2016-mfnff.pdf\n    https://dl.acm.org/doi/10.1145/3473585\n    https://dl.acm.org/doi/10.1145/3158124\n    https://www.cse.chalmers.se/~nad/publications/danielsson-popl2008.pdf \n    *)\n  Inductive complexity_repeat_op_ntimes_rec \n    (e t : N) : positive -> N -> N -> Prop :=\n  | xH_case : complexity_repeat_op_ntimes_rec e t xH \n      (N.modulo e t) N0\n  | xO_case p ret w : \n      complexity_repeat_op_ntimes_rec e t p ret w ->\n      complexity_repeat_op_ntimes_rec e t (xO p) \n      (N.modulo (ret * ret) t) (N.succ w)\n  | xI_case p ret w : \n      complexity_repeat_op_ntimes_rec e t p ret w ->\n      complexity_repeat_op_ntimes_rec e t (xI p) \n      (N.modulo (e * (ret * ret)) t) (N.succ w).\n\n\n\n  Lemma correct_complexity_repeat_op_ntimes_rec : \n    forall n e w, \n    complexity_repeat_op_ntimes_rec e w n \n      (repeat_op_ntimes_rec e n w)  (N.log2 (N.pos n)).\n  Proof.\n    induction n; \n    intros e w.\n    + specialize (IHn e w).\n      assert (Hwt : ((N.pos n~1) = (2 * (N.pos n) + 1))%N).\n      cbn; nia.\n      rewrite Hwt; clear Hwt.\n      rewrite N.log2_succ_double.\n      remember ((N.log2 (N.pos n))) as p. \n      cbn.\n      apply xI_case.\n      exact IHn.\n      nia. \n    + specialize (IHn e w).\n      assert (Hwt : ((N.pos n~0) = (2 * (N.pos n)))%N).\n      cbn; nia.\n      rewrite Hwt; clear Hwt.\n      rewrite N.log2_double.\n      remember ((N.log2 (N.pos n))) as p. \n      cbn.\n      apply xO_case.\n      exact IHn.\n      nia.\n    + cbn; apply xH_case.\n  Qed.\n  \n  (* end of the proof efficient funtion *)\n\n\n  (* slow function, will be used to prove that this slow function is \n    equivalent to Npow_mod, faster one. *)\n  Fixpoint Npow_mod_unary (e : N) (n : nat) (w : N) : N :=\n    match n with \n    | 0%nat => Npos xH\n    | S n' => N.modulo (e * Npow_mod_unary e n' w) w\n    end.\n\n\n  (* acc is accumulator, for efficient reduction of terms *)\n  Fixpoint repeat_op_ntimes_acc \n    (e : N) (n : positive) (w acc : N) : N :=\n    match n with\n    | xH => N.modulo (e * acc) w\n    | xO p => let ee := (N.modulo (e * e) w) in repeat_op_ntimes_acc ee p w acc \n    | xI p => let ee := (N.modulo (e * e) w) in \n              let ea := (N.modulo (e * acc) w) in \n              repeat_op_ntimes_acc ee p w ea  \n    end.\n\n  Lemma op_pushes_out : \n    forall n e w, prime (Z.of_N w) -> \n    repeat_op_ntimes_rec ((e * e) mod w) n w = \n    N.modulo (\n      (repeat_op_ntimes_rec e n w * repeat_op_ntimes_rec e n w)) w.\n  Proof.\n    induction n.\n    - simpl; intros ? ? Hw.\n      rewrite IHn.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      remember (repeat_op_ntimes_rec e n w * repeat_op_ntimes_rec e n w)%N as enw.\n      rewrite <- N.mul_mod_idemp_r.\n      repeat rewrite N.mul_mod_idemp_l.\n      repeat rewrite N.mul_mod_idemp_r.\n      assert (Ht : (e * enw * (e * enw) = \n        e * e * (enw * enw))%N). lia.\n      rewrite Ht; clear Ht.\n      repeat rewrite N.mul_assoc.\n      rewrite N.mul_mod_idemp_r.\n      reflexivity.\n      all:(try lia; try assumption).\n    - simpl; intros ? ? Hw.\n      rewrite IHn.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      reflexivity. exact Hw.\n    - simpl; intros ? ? Hw.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      rewrite N.mod_mod.\n      rewrite N.mul_mod_idemp_l.\n      rewrite N.mul_mod_idemp_r.\n      reflexivity.\n      all:lia.\n  Qed.\n\n\n  Lemma positive_mul_group_acc_rec_connection : \n    forall n e w acc, \n    prime (Z.of_N w) ->\n    repeat_op_ntimes_acc e n w acc = N.modulo (acc * repeat_op_ntimes_rec e n w) w.\n  Proof.\n    induction n.\n    - simpl; intros ? ? ? Hw.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      specialize (IHn (N.modulo (e * e) w) w (N.modulo (e * acc) w)).\n      rewrite IHn.\n      rewrite op_pushes_out.\n      remember (repeat_op_ntimes_rec e n w * repeat_op_ntimes_rec e n w)%N as enw.\n      rewrite N.mul_mod_idemp_l.\n      repeat rewrite N.mul_mod_idemp_r.\n      assert (Ht : ((acc * (e * enw) = e * acc * enw)%N)).\n      lia.\n      rewrite Ht; clear Ht.\n      reflexivity.\n      all:(try lia; try assumption).\n    - simpl; intros ? ? ? Hw.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      rewrite IHn. rewrite op_pushes_out.\n      reflexivity.\n      all:assumption.\n    - simpl; intros ? ? ? Hw.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      rewrite N.mul_mod_idemp_r.\n      assert (Ht : (acc * e = e * acc)%N). lia.\n      rewrite Ht; clear Ht.\n      reflexivity.\n      lia.\n  Qed.\n\n      \n  Definition Npow_mod_constant_space (e : N) (n w : N) :=\n    match n with\n    | N0 => Npos xH\n    | Npos p => repeat_op_ntimes_acc e p w 1 \n    end.\n\n  \n  Lemma npow_mod_npow_constant_eqv : \n    forall n e w, \n    prime (Z.of_N w) ->\n    Npow_mod e n w = Npow_mod_constant_space e n w.\n  Proof.\n    destruct n; simpl; intros ? ? Hw.\n    - reflexivity.\n    - pose proof positive_mul_group_acc_rec_connection p e w 1 Hw.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      rewrite H. rewrite N.mul_1_l.\n      destruct p.\n      all:simpl; rewrite N.mod_mod; lia.\n  Qed.\n\n\n  Lemma Npow_mod_unary_bound : \n    forall (n : nat) (e w : N), \n    prime (Z.of_N w) -> \n    (Npow_mod_unary e n w < w)%N.\n  Proof.\n    induction n.\n    - simpl; intros ? ? Hw.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      lia.\n    - simpl; intros ? ? Hw.\n      apply N.mod_lt.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      lia.\n  Qed.\n\n  Lemma binnat_zero : \n    forall (n : nat), 0%N = N.of_nat n -> n = 0%nat.\n  Proof.\n    induction n; try lia.\n  Qed.\n\n  Theorem Npow_mod_add_mul : \n    forall n m e w, \n    prime (Z.of_N w) ->\n    Npow_mod_unary e (n + m) w = N.modulo (Npow_mod_unary e n w * \n    Npow_mod_unary e m w) w.\n  Proof.\n    induction n.\n    - intros ? ? ? Hw.\n      rewrite Nat.add_0_l. \n      assert (Ht : Npow_mod_unary e 0 w = Npos xH).\n      simpl. reflexivity. \n      rewrite Ht.\n      rewrite N.mul_1_l.\n      induction m.\n      + simpl. rewrite N.mod_1_l.\n        reflexivity.\n        pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n        lia.\n      + simpl. rewrite N.mod_mod.\n        reflexivity. \n        pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n        lia.\n    - simpl; intros ? ? ? Hw.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      rewrite IHn. \n      rewrite N.mul_mod_idemp_r.\n      rewrite N.mul_mod_idemp_l.\n      rewrite N.mul_assoc. reflexivity.\n      lia. lia. assumption.\n  Qed.\n\n\n\n  Lemma binnat_odd : \n    forall (p : positive) (n : nat), \n    N.pos (xI p) = N.of_nat n -> \n    exists k,  n = (2 * k + 1)%nat /\\  (N.pos p) = (N.of_nat k).\n  Proof.\n    intros p n Hp.\n    destruct (Even.even_or_odd n) as [H | H].\n    apply Even.even_equiv in H. destruct H as [k Hk].\n    (* Even (impossible) Case *)\n    rewrite Hk in Hp; lia.\n    (* Odd (possible) case *)\n    apply Even.odd_equiv in H. destruct H as [k Hk].\n    rewrite Hk in Hp. exists k.\n    split. exact Hk. lia.\n  Qed.\n\n\n  Lemma binnat_even : forall (p : positive) (n : nat), \n    N.pos (xO p) = N.of_nat n :> N -> \n    exists k, n = (Nat.mul 2 k) /\\  (N.pos p) = (N.of_nat k).\n  Proof.\n    intros p n Hp.\n    destruct (Even.even_or_odd n) as [H | H].\n    apply Even.even_equiv in H. destruct H as [k Hk].\n    (* Even (possible) case*)\n    rewrite Hk in Hp. exists k.\n    split. exact Hk. lia.\n    (* Odd (impossible) case *)\n    apply Even.odd_equiv in H. \n    destruct H as [k Hk].\n    rewrite Hk in Hp. lia.\n  Qed.\n\n  (* slow is equivalent to fast *)\n  Lemma npow_mod_exp_unary_binary_eqv : \n    forall (n : N) e w, prime (Z.of_N w) ->\n    Npow_mod_unary e (N.to_nat n) w = Npow_mod e n w.\n  Proof.\n    destruct n.\n    - simpl; intros ? ? Hw.\n      reflexivity.\n    - simpl; revert p.\n      induction p.\n      + simpl; intros ? ? Hw.\n        pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n        rewrite <-IHp.\n        rewrite ZL6.\n        rewrite Npow_mod_add_mul.\n        rewrite N.mul_mod_idemp_r.\n        reflexivity.\n        lia. exact Hw.\n        exact Hw.\n      + simpl; intros ? ? Hw.\n        rewrite <-IHp.\n        rewrite Pos2Nat.inj_xO.\n        assert (Ht : (2 * Pos.to_nat p = \n          Pos.to_nat p + Pos.to_nat p)%nat).\n        lia. rewrite Ht.\n        rewrite Npow_mod_add_mul.\n        reflexivity.\n        exact Hw.\n        exact Hw.\n      + simpl; intros ? ? Hw.\n        rewrite N.mul_1_r.\n        reflexivity.\n  Qed.\n        \n     \n\n  \n  Lemma mod_reduce_pow : \n    forall n e w, prime (Z.of_N w) -> \n    repeat_op_ntimes_rec e n w = \n    repeat_op_ntimes_rec (N.modulo e w) n w.\n  Proof.\n    induction n.\n    - simpl; intros ? ? Hp.\n      rewrite IHn.\n      remember (repeat_op_ntimes_rec (e mod w) n w *\n      repeat_op_ntimes_rec (e mod w) n w)%N as t.\n      rewrite N.mul_mod_idemp_l.\n      reflexivity.\n      pose proof (prime_ge_2 (Z.of_N w) Hp) as Ht.\n      lia. exact Hp.\n    - simpl; intros ? ? Hp.\n      rewrite IHn.\n      reflexivity.\n      exact Hp.\n    - simpl; intros ? ? Hp.\n      rewrite N.mod_mod.\n      reflexivity.\n      pose proof (prime_ge_2 (Z.of_N w) Hp) as Ht.\n      lia.\n  Qed.\n\n\n  Lemma Nmod_reduce_pow : forall n e w, prime (Z.of_N w) -> \n    Npow_mod e n w = Npow_mod (N.modulo e w) n w.\n  Proof.\n    destruct n.\n    - simpl; intros ? ? Hp.\n      reflexivity.\n    - simpl; intros ? ? Hp.\n      apply mod_reduce_pow.\n      exact Hp.\n  Qed.\n\n  Lemma wp_mod_zero : \n    forall (w k p : N), \n    prime (Z.of_N p) -> \n    (2 <= k)%N -> (2 <= p)%N ->\n    (w mod p = 0)%N ->  (Npow_mod (w mod p) k p = 0)%N.\n  Proof.\n    intros ? ? ? Hp Hk Hpt Hwp.\n    rewrite Hwp.\n    unfold Npow_mod.\n    destruct k. lia.\n    clear Hk.\n    induction p0.\n    simpl. rewrite N.mod_0_l.\n    reflexivity. lia.\n    simpl. rewrite IHp0.\n    rewrite N.mod_0_l. \n    reflexivity. lia.\n    simpl. rewrite N.mod_0_l.\n    reflexivity. lia.\n  Qed.\n    \n  Lemma wp_mod_one : \n    forall (w k p : N), \n    prime (Z.of_N p) -> \n    (2 <= k)%N -> (2 <= p)%N ->\n    (w mod p = 1)%N ->  (Npow_mod (w mod p) k p = 1)%N.\n  Proof.\n    intros ? ? ? Hp Hk Hpt Hwp.\n    rewrite Hwp.\n    unfold Npow_mod.\n    destruct k. lia.\n    clear Hk.\n    induction p0.\n    simpl. rewrite IHp0.\n    simpl. rewrite N.mod_1_l.\n    reflexivity. lia.\n    simpl. rewrite IHp0.\n    rewrite N.mod_1_l. \n    reflexivity. lia.\n    simpl. rewrite N.mod_1_l.\n    reflexivity. lia.\n  Qed.\n\n  \n    \n  Lemma zmod_nmod : \n    forall (b a w : N), \n    prime (Z.of_N w) ->\n    Z.of_N (Npow_mod a b w) = \n    Zpow_mod (Z.of_N a) (Z.of_N b) (Z.of_N w).\n  Proof.\n    intros ? ? ? Hw.\n    rewrite Zpow_mod_correct.\n    destruct b; simpl.\n    - symmetry.\n      rewrite Z.mod_1_l.\n      reflexivity. \n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Ht.\n      lia.\n    - revert p.\n      induction p.\n      + simpl. \n        assert (Ht : (p~1 = p + p + 1)%positive).\n        lia. rewrite Ht.\n        rewrite Zpower_pos_is_exp.\n        rewrite Zpower_pos_is_exp.\n        rewrite Zpower_pos_1_r.\n        rewrite N2Z.inj_mod.\n        rewrite N2Z.inj_mul.\n        rewrite N2Z.inj_mul.\n        rewrite IHp.\n        remember (Z.pow_pos (Z.of_N a) p) as zps.\n        remember (Z.of_N a) as za.\n        remember (Z.of_N w) as zw. \n        assert (Hzp: zps * zps * za = za * (zps * zps)).\n        lia. rewrite Hzp; clear Hzp; clear Ht.\n        rewrite <-Zmult_mod_idemp_l.\n        assert (Ht : (za * (zps * zps)) mod zw = (za mod zw * (zps * zps)) mod zw).\n        rewrite <-Zmult_mod_idemp_l.\n        reflexivity. rewrite Ht; clear Ht.\n        assert (Ht : (za mod zw * (zps * zps)) mod zw = \n        (za mod zw * ((zps * zps) mod zw)) mod zw).\n        rewrite <-Zmult_mod_idemp_r. reflexivity.\n        rewrite Ht; clear Ht.\n        assert (Ht : (zps * zps) mod zw = \n          (zps mod zw * (zps mod zw)) mod zw).\n        rewrite <-Zmult_mod_idemp_l.\n        rewrite <-Zmult_mod_idemp_r.\n        reflexivity.\n        rewrite Ht.\n        rewrite Zmult_mod_idemp_r.\n        reflexivity.\n      + simpl.\n        assert (Ht : (p~0 = p + p)%positive).\n        lia. rewrite Ht.\n        rewrite Zpower_pos_is_exp.\n        rewrite N2Z.inj_mod.\n        rewrite N2Z.inj_mul.\n        rewrite IHp.\n        remember (Z.pow_pos (Z.of_N a) p) as zps.\n        remember (Z.of_N a) as za.\n        remember (Z.of_N w) as zw.\n        rewrite Zmult_mod_idemp_l.\n        rewrite Zmult_mod_idemp_r.\n        reflexivity.\n      + simpl. rewrite Zpower_pos_1_r.\n        rewrite N2Z.inj_mod.\n        reflexivity.\n    - pose proof (prime_ge_2 (Z.of_N w) Hw) as Ht.\n      lia.\n  Qed.\n\n  Lemma npow_mod_nat : forall (n a p : nat), \n    prime (Z.of_nat p) ->\n    Npow_mod_unary (N.of_nat a) n (N.of_nat p) =\n    N.of_nat (Nat.modulo (Nat.pow a n) p).\n  Proof.\n    induction n.\n    + intros * Hp.\n      pose proof prime_ge_2 (Z.of_nat p) Hp as Hf.\n      simpl. rewrite Nat.mod_1_l.\n      lia. lia.\n    + intros * Hp.\n      simpl.\n      pose proof (IHn a p Hp).\n      rewrite H.\n      rewrite <-Nat2N.inj_mul,\n      <-Nat2N.inj_mod.\n      f_equal.\n      rewrite Nat.mul_mod_idemp_r.\n      reflexivity.\n      pose proof prime_ge_2 (Z.of_nat p) Hp as Hf.\n      lia.\n  Qed. \n      \n  Lemma N_to_nat_exp : forall (n a p : N), \n    prime (Z.of_N p) ->\n    N.modulo (N.pow a n) p = \n    N.of_nat (Nat.modulo (Nat.pow (N.to_nat a) \n      (N.to_nat n)) (N.to_nat p)).\n  Proof.\n    intros * Hp.\n    rewrite <-N2Nat.inj_pow.\n    rewrite <-N2Nat.inj_mod.\n    lia.\n  Qed.\n\n\nEnd Fn.  \n", "meta": {"author": "mukeshtiwari", "repo": "Dlog-zkp", "sha": "c291925d28609f57eab069bd8479d868e7e7f66c", "save_path": "github-repos/coq/mukeshtiwari-Dlog-zkp", "path": "github-repos/coq/mukeshtiwari-Dlog-zkp/Dlog-zkp-c291925d28609f57eab069bd8479d868e7e7f66c/src/Functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6990696943970286}}
{"text": "From elpi Require Import elpi.\nFrom HB Require Import structures.\nFrom mathcomp Require Import all_ssreflect.\nFrom mathcomp Require Import all_algebra.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** *** Exercices on polynomials\n- Formalisation of the algebraic  part of  a                          \n simple proof that PI is irrational  described in:                   \n- http://projecteuclid.org/download/pdf_1/euclid.bams/1183510788    \n*)  \n\nSection Algebraic_part.\n\nOpen Scope ring_scope.\nImport GRing.Theory Num.Theory.\n\n(** *** Parameters definitions:\n- Let n na nb be  natural numbers\n- Suppose nb is a non zero nat: nb != 0\n- Define the corresponding rationals a , b \n- Define pi as a/b.\n*)\n(* to complete  for na nb*)\nVariable n : nat.\n(*D*)Variables na nb: nat.\nHypothesis nbne0: nb != 0%N.\n\nDefinition a:rat := (Posz na)%:~R.\nDefinition b:rat := \n(*D*)(Posz nb)%:~R.\n\nDefinition pi := \n(*D*)a / b.\n\n(** *** Definition of the polynomials:\n-  Look at the f definition: the factorial, the coercion nat :> R (as a Ring), etc...\n- Define F:{poly rat} using bigop.\n*)\nDefinition f :{poly rat} := \n  (n`!)%:R^-1 *: ('X^n * (a%:P -  b*:'X)^+n).\n\n(*D*)Definition F :{poly rat} := \\sum_(i < n.+1) (-1)^i *: f^`(2*i).\n\n\n(** *** Prove that:\n- b is non zero rational.\n*)\n(* Some intermediary simple theorems *)\nLemma bne0: b != 0.\n(*D*)Proof. by rewrite intr_eq0. Qed.\n(** *** Prove that:\n-  (a -  bX) has a size of 2\n*)\nLemma P1_size: size (a%:P -  b*:'X) = 2%N.\nProof.\n(*D*)have hs:  size (- (b *: 'X)) = 2%N.\n(*D*)  by rewrite size_opp size_scale ?bne0 // size_polyX.\n(*D*)by rewrite  addrC size_addl hs ?size_polyC //;  case:(a!= 0).\nQed.\n\n(** *** Prove that:\n-  the lead_coef of (a -  bX) is -b.\n*)\nLemma P1_lead_coef: lead_coef (a%:P -  b*:'X) = -b.\nProof.\n(*D*)rewrite addrC lead_coefDl.\n(*D*)  by rewrite lead_coefN lead_coefZ lead_coefX mulr1.\n(*D*)by rewrite size_opp size_scale ?bne0 // size_polyX size_polyC; case:(a!= 0).\nQed.\n\n(** *** Prove that:\n-  the size of (a-X)^n is n.+1\n*)\nLemma P_size : size ((a%:P -  b*:'X)^+n)  = n.+1.\n(*D*)elim:n=>[| n0 Hn0]; first by rewrite expr0 size_polyC.\n(*D*)rewrite exprS size_proper_mul.\n(*D*)  by rewrite P1_size /= Hn0.\n(*D*)by rewrite lead_coef_exp P1_lead_coef -exprS expf_neq0 // oppr_eq0 bne0.\nQed.\n\n(* 2 useful lemmas for the  Qint predicat. *)\nLemma int_Qint (z:int) : z%:~R \\is a Qint.\nProof. by apply/QintP; exists z. Qed.\n\nLemma nat_Qint (m:nat) : m%:R \\is a Qint.\nProof. by apply/QintP; exists m. Qed.\n\n(** *** Prove that:\n- Exponent and composition of polynomials combine:\n*)\nLemma comp_poly_exprn: \n   forall (p q:{poly rat}) i, p^+i \\Po q = (p \\Po q) ^+i.\n(*D*)move=> p q; elim=>[| i Hi].\n(*D*)  by rewrite !expr0 comp_polyC.\n(*D*)by rewrite !exprS comp_polyM Hi.\nQed.\n\n\n(** *** Prove that:\n- f's small coefficients are zero\n*)\n(* Let's begin the Niven proof *)\nLemma f_small_coef0 i: (i < n)%N -> f`_i = 0.\nProof.\n(*D*)move=> iltn;rewrite /f coefZ.\n(*D*)apply/eqP; rewrite mulf_eq0 invr_eq0 pnatr_eq0 eqn0Ngt (fact_gt0 n) /=.\n(*D*)by rewrite coefXnM iltn.\nQed.\n\n(** *** Prove that:\n- f/n! as integral coefficients \n*)\n\nLemma f_int i: (n`!)%:R * f`_i \\is a Qint.\nProof.\n(*D*)rewrite /f coefZ mulrA mulfV; last by rewrite pnatr_eq0 -lt0n (fact_gt0 n).\n(*D*)rewrite mul1r; apply/polyOverP.\n(*D*)rewrite rpredM ?rpredX ?polyOverX //.\n(*D*)by rewrite rpredB ?polyOverC ?polyOverZ ?polyOverX // int_Qint.\nQed.\n\n(** *** Prove that:\nthe f^`(i) (x) have integral values for x = 0\n*)\nLemma derive_f_0_int: forall i, f^`(i).[0] \\is a Qint.\nProof.\n(*D*)move=> i.\n(*D*)rewrite horner_coef0 coef_derivn addn0 binomial.ffactnn.\n(*D*)case:(boolP (i <n)%N).\n(*D*)  move/f_small_coef0 ->.\n(*D*)  by rewrite mul0rn // int_Qint.\n(*D*)rewrite -leqNgt.\n(*D*)move/binomial.bin_fact <-.\n(*D*)rewrite /f coefZ -mulrnAl -mulr_natr mulrC rpredM //; last first.\n(*D*)  rewrite mulnC !natrM !mulrA  mulVf ?mul1r ?rpredM ?nat_Qint //.\n(*D*)  by rewrite  pnatr_eq0 eqn0Ngt (fact_gt0 n).\n(*D*)apply/polyOverP;rewrite rpredM // ?rpredX ?polyOverX //.\n(*D*)by rewrite ?rpredB ?polyOverC ?polyOverZ ?polyOverX // int_Qint.\nQed.\n\n(** *** Deduce that:\nF (0) has an integral value\n*)\n\nLemma F0_int : F.[0] \\is a Qint.\nProof.\n(*D*)rewrite /F horner_sum rpred_sum // =>  i _ ; rewrite !hornerE rpredM //.\n(*D*)  by rewrite -exprnP rpredX.\n(*D*)by rewrite derive_f_0_int.\nQed.\n\n(** *** Then prove \n- the symmetry argument f(x) = f(pi -x).\n*)\nLemma pf_sym:  f \\Po (pi%:P -'X) = f.\nProof.\n(*D*)rewrite /f comp_polyZ;congr (_ *:_).\n(*D*)rewrite comp_polyM   !comp_poly_exprn.\n(*D*)rewrite comp_polyB comp_polyC !comp_polyZ !comp_polyX scalerBr /pi.\n(*D*)have h1:    b%:P * (a / b)%:P = a%:P.\n(*D*)  by rewrite polyCM mulrC -mulrA -polyCM mulVf ?bne0 // mulr1.\n(*D*)suff->: (a%:P - (b *: (a / b)%:P - b *: 'X)) = b%:P * 'X.\n(*D*)  rewrite exprMn mulrA - exprMn [X in _ = X]mulrC.\n(*D*)  congr (_ *_); congr (_^+_).\n(*D*)  rewrite mulrC mulrBr; congr (_ -_)=>//.\n(*D*)  by rewrite mul_polyC.\n(*D*)by rewrite -!mul_polyC h1 opprB addrA addrC addrA addNr add0r.\nQed.\n\n(** *** Prove \n- the symmetry for the derivative \n*)\n\nLemma  derivn_fpix i :\n      (f^`(i)\\Po(pi%:P -'X))= (-1)^+i *: f^`(i).\nProof.\n(*D*)elim:i ; first by rewrite /= expr0 scale1r pf_sym.\n(*D*)move => i Hi.\n(*D*)set fx := _ \\Po _.\n(*D*)rewrite derivnS exprS -scalerA -derivZ -Hi deriv_comp !derivE.\n(*D*)by rewrite mulrBr mulr0 add0r mulr1 -derivnS /fx scaleN1r opprK.\nQed.\n\n(** *** Deduce that\n- F(pi) is an integer \n*)\nLemma FPi_int : F.[pi] \\is a Qint.\nProof.\n(*D*)rewrite /F horner_sum rpred_sum //.\n(*D*)move=> i _ ; rewrite !hornerE rpredM //.\n(*D*)  by rewrite -exprnP rpredX.\n(*D*)move:(derivn_fpix (2*i)).\n(*D*)rewrite  mulnC exprM sqrr_sign scale1r => <-.\n(*D*)by rewrite horner_comp !hornerE subrr derive_f_0_int.\nQed.\n\n\n(** *** if you have time\n- you can prove the  equality  F^`(2) + F = f \n- that is  needed by the analytic part of the Niven proof\n*)\n\nLemma D2FDF : F^`(2) + F = f.\nProof.\n(*D*)rewrite /F linear_sum /=.\n(*D*)rewrite (eq_bigr (fun i:'I_n.+1 => (((-1)^i *: f^`(2 * i.+1)%N)))); last first.\n(*D*)  move=> i _ ;rewrite !derivZ; congr (_ *:_).\n(*D*)  rewrite -!derivnS;congr (_^`(_)).\n(*D*)  by rewrite mulnS addnC addn2.\n(*D*)rewrite [X in _ + X]big_ord_recl muln0 derivn0.\n(*D*)rewrite -exprnP expr0 scale1r (addrC f) addrA -[X in _ = X]add0r.\n(*D*)congr (_ + _).\n(*D*)rewrite big_ord_recr addrC addrA -big_split big1=>[| i _].\n(*D*)  rewrite add0r /=; apply/eqP; rewrite scaler_eq0 -derivnS derivn_poly0.\n(*D*)    by rewrite eqxx orbT.\n(*D*)  suff ->: (size f) = (n + n.+1)%N by rewrite -plus_n_O leqnSn.\n(*D*)  rewrite /f size_scale; last first.\n(*D*)    by rewrite invr_neq0 // pnatr_eq0 -lt0n (fact_gt0 n).\n(*D*)  rewrite size_monicM ?monicXn //; last by rewrite -size_poly_eq0 P_size.\n(*D*)  by rewrite  size_polyXn P_size.\n(*D*)rewrite /bump /= -scalerDl.\n(*D*)apply/eqP;rewrite scaler_eq0 /bump -exprnP add1n exprSr.\n(*D*)by rewrite mulrN1 addrC subr_eq0 eqxx orTb.\nQed.\n\nEnd Algebraic_part.\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/exercise6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.6990561898435037}}
{"text": "From mathcomp Require Import ssreflect.\n\nRequire Import zf.\n\nInductive SymDiffOfCollection {U:Type} (A B:Collection U): Collection U :=\n| intro_sym_diff_of_collection:\n    forall x:U, x ∈ (A \\ B) ∪ (B \\ A) -> x ∈ SymDiffOfCollection A B.\n\nNotation \"A △ B\" := (SymDiffOfCollection A B) (right associativity, at level 30).\n\nInductive DirectSumOfCollection {U:Type} (X':Collection (Collection U)): Collection U:=\n| definition_of_direct_sum_of_collection: forall x:U,\n    x ∈ (⋃ X')  /\\\n    (forall A B:Collection U, A ∈ X' /\\ B ∈ X' -> A ∩ B = `Ø`)\n    -> x ∈ DirectSumOfCollection X'.\n\nDefinition CoveringBySets {U:Type} (X:Collection U) (X':Collection (Collection U)) := X = (⋃ X').\n\nDefinition CollectionIsPartition {U:Type} (X:Collection U) (X':Collection (Collection U)) :=\n  X = (⋃ X') /\\\n  forall A B:Collection U, A ∈ X' /\\ B ∈ X' -> A ∩ B <> `Ø` -> A = B.\n\nSection CollectionOperator.\n  Variable U:Type.\n  Theorem AbsorptionEmpty:\n    forall A:Collection U, (A ∪ `Ø`) = A.\n  Proof.\n    move => A.\n    apply mutally_included_iff_eq.\n    split => x.\n    case. by [].\n    apply all_collection_included_empty.\n    move => H.\n    left. by [].\n  Qed.\n\n  Theorem AbsorptionFull:\n    forall A:Collection U, (A ∪ (FullCollection U)) = FullCollection U.\n  Proof.\n    move => A.\n    apply mutally_included_iff_eq.\n    split => x.\n    case. exact.\n    exact.\n    move => H.\n    right. by [].\n  Qed.\n\n  Theorem LawOfExcludedMiddleAtCollection:\n    forall A:Collection U, A ∪ (A ^c) = FullCollection U.\n  Proof.\n    move => A.\n    apply mutally_included_iff_eq.\n    split => x H.\n    exact.\n    apply: in_or_to_in_union.\n    apply LawOfExcludedMiddle.\n  Qed.\n\n  Theorem LawOfDistributiveByUnion:\n    forall A B C:Collection U, (A ∩ B) ∪ C = (A ∪ C) ∩ (B ∪ C).\n  Proof.\n    move => A B C.\n    apply mutally_included_iff_eq.\n    split => x H0.\n    apply in_intersection_iff_in_and.\n    suff: (x ∈ A \\/ x ∈ C) /\\ (x ∈ B \\/ x ∈ C).\n    case => HAC HBC.\n    split; apply in_or_to_in_union; by [].\n    have L1: (x ∈ A /\\ x ∈ B) \\/ x ∈ C.\n    case: H0 => x0 HAB; [left; apply in_intersection_iff_in_and | right]; by[].\n    apply LawOfDistributiveByOr. by[].\n    suff: (x ∈ A /\\ x ∈ B) \\/ x ∈ C.\n    case => H; [left; apply in_intersection_iff_in_and | right]; by[].\n    apply LawOfDistributiveByOr.\n    case H0 => x0 H1 H2.\n    split; apply in_union_iff_in_or; by [].\n  Qed.\n\n  Theorem LawOfDistributiveByIntersection:\n    forall A B C:Collection U, (A ∪ B) ∩ C = (A ∩ C) ∪ (B ∩ C).\n  Proof.\n    move => A B C.\n    apply mutally_included_iff_eq.\n    split => x H0.\n    apply in_union_iff_in_or.\n    suff: (x ∈ A /\\ x ∈ C) \\/ (x ∈ B /\\ x ∈ C).\n    case => H; [left|right]; apply in_intersection_iff_in_and; by [].\n    apply LawOfDistributiveByAnd.\n    case: H0 => x0 HAB HC.\n    split; [apply in_union_iff_in_or|]; by[].\n    suff: (x ∈ A \\/ x ∈ B) /\\ x ∈ C.\n    case => HAB HC.\n    apply in_and_to_in_intersection.\n    split; [apply in_union_iff_in_or|]; by[].\n    apply LawOfDistributiveByAnd.\n    case H0 => x0 H1; [left|right]; apply in_intersection_iff_in_and; by [].\n  Qed.\n\n  Theorem LawOfAbsorptionToUnion:\n    forall A B:Collection U, (A ∩ B) ∪ A = A.\n  Proof.\n    move => A B.\n    apply union_iff_subcollect.\n    move => x. case => x0 HA HB. by [].\n  Qed.\n\n  Theorem LawOfAbsorptionToIntersection:\n    forall A B:Collection U, (A ∪ B) ∩ A = A.\n  Proof.\n    move => A B.\n    rewrite LawOfCommutativeAtIntersection.\n    apply subcollect_to_intersection.\n    move => x. left. by [].\n  Qed.\n\n  Theorem DoMorgranLawAtUnion:\n    forall A B:Collection U, (A ∪ B)^c = A^c ∩ B^c.\n  Proof.\n    move => A B.\n    apply mutally_included_iff_eq.\n    split => x H.\n    apply in_and_to_in_intersection.\n    apply LawOfDeMorgan_NegtationOfDisjunction.\n    move => HAB.\n    apply H.\n    apply in_or_to_in_union. by [].\n    apply in_intersection_to_in_and in H.\n    apply LawOfDeMorgan_NegtationOfDisjunction in H.\n    move => HF.\n    apply H.\n    apply in_union_to_in_or. by [].\n  Qed.\n\n  Theorem DoMorgranLawAtIntersection:\n    forall A B:Collection U, (A ∩ B)^c = A^c ∪ B^c.\n  Proof.\n    move => A B.\n    apply mutally_included_iff_eq.\n    split => x H.\n    apply in_or_to_in_union.\n    apply LawOfDeMorgan_NegtationOfConjunction => HAB.\n    apply H.\n    apply in_and_to_in_intersection in HAB. by [].\n    apply in_union_to_in_or in H.\n    apply LawOfDeMorgan_NegtationOfConjunction in H.\n    move => HAB.\n    apply H.\n    apply in_intersection_to_in_and. by [].\n  Qed.\n\n  Goal forall (A B:Collection U), A △ B = A^c △ B^c.\n  Proof.\n    move => A B.\n    apply mutally_included_to_eq.\n    split => x H.\n    +inversion H as [x0 H0 Hx0].\n     split.\n     ++inversion H0 as [x1 H1|x1 H1];\n         [right|left];\n         inversion H1 as [x2 H3 H4 H5];\n         split.\n       apply notin_collect_iff_in_complement.\n       apply H4.\n       apply notin_collect_iff_in_complement.\n       rewrite -complement_of_complement_collect_is_self.\n       apply H3.\n       apply H4.\n       apply notin_collect_iff_in_complement.\n       rewrite -complement_of_complement_collect_is_self.\n       apply H3.\n    +inversion H.\n     inversion H0; split;\n       [right|left];\n       split; inversion H2.\n     apply DoubleNegativeElimination.\n     apply H5.\n     apply notin_collect_iff_in_complement.\n     apply H4.\n     apply DoubleNegativeElimination.\n     apply H5.\n     apply notin_collect_iff_in_complement.\n     apply H4.\n  Qed.\n\n  Goal\n    forall (X:Collection U) (X':Collection (Collection U)),\n      CollectionIsPartition X X' -> CoveringBySets X X'.\n  Proof.\n    move => X X' H.\n    inversion H.\n    trivial.\n  Qed.\n\nEnd CollectionOperator.\n\nRequire Export zf.\n", "meta": {"author": "seisyuu-hantatsushi", "repo": "implement_set_theory_in_coq", "sha": "49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c", "save_path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq", "path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq/implement_set_theory_in_coq-49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c/coq/collect_operator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6990561742391763}}
{"text": "Require Import Coq.Lists.List.\n\nImport ListNotations.\n\nTheorem Forall_app : forall (A : Type) (P : A -> Prop) (xs ys : list A),\n  Forall P xs ->\n  Forall P ys ->\n  Forall P (xs ++ ys).\nProof.\n  intros A P xs ys H1.\n  generalize dependent ys.\n  induction H1; intros ys H2.\n  - assumption.\n  - simpl.\n    auto using Forall_cons.\nQed.\n\nInductive Zip {A B : Type} : list A -> list B -> list (A * B) -> Prop :=\n| Zip_nil : Zip [] [] []\n| Zip_cons : forall x y xs ys zs,\n    Zip xs ys zs -> Zip (x :: xs) (y :: ys) ((x, y) :: zs).\n\nTheorem Zip_app : forall (A B : Type) (xs1 xs2 : list A) (ys1 ys2 : list B)\n  (zs1 zs2 : list (A * B)),\n  Zip xs1 ys1 zs1 ->\n  Zip xs2 ys2 zs2 ->\n  Zip (xs1 ++ xs2) (ys1 ++ ys2) (zs1 ++ zs2).\nProof.\n  intros A B xs1 xs2 ys1 ys2 zs1 zs2 HZip1.\n  generalize dependent zs2.\n  generalize dependent ys2.\n  generalize dependent xs2.\n  induction HZip1; intros xs2 ys2 zs2 HZip2; simpl; auto using Zip_cons.\nQed.", "meta": {"author": "mdesharnais", "repo": "coq-practical-ss17-amortised-ressource-bounds", "sha": "fe61cffbf28cfa2be45ae460b057fac2062e1044", "save_path": "github-repos/coq/mdesharnais-coq-practical-ss17-amortised-ressource-bounds", "path": "github-repos/coq/mdesharnais-coq-practical-ss17-amortised-ressource-bounds/coq-practical-ss17-amortised-ressource-bounds-fe61cffbf28cfa2be45ae460b057fac2062e1044/ListUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.699056167189408}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom fcsl Require Import axioms pred prelude domain.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLemma nat_leq_refl : forall x : nat, x <= x.\nProof.\nexact: leqnn.\nQed.\n\nLemma nat_leq_antisymmetric : forall x y, x <= y -> y <= x -> x = y.\nProof.\n  move => x' y'.  \n  rewrite leq_eqVlt.\n  move/orP.\n  case.\n  - by move/eqP.\n  - move => Hlt.\n    rewrite leq_eqVlt.\n    move/orP.\n    case.\n    * by move/eqP.\n    * move => Ht'.\n      rewrite ltnNge in Ht'.\n      rewrite ltnNge in Hlt.\n      have Ht := leq_total x' y'.\n      move/orP: Ht.\n      case.\n      + move => Hlt'.\n        by move/negP in Ht'.\n      + move => Hlt'.\n        by move/negP in Hlt.\nQed.\n\nLemma nat_leq_trans : forall x y z, x <= y -> y <= z -> x <= z.\nProof.\nmove => x y z.\napply: leq_trans.\nQed.\n\nDefinition nat_leq_PosetMixin := \n  PosetMixin nat_leq_refl nat_leq_antisymmetric nat_leq_trans.\nCanonical nat_leq_Poset := Eval hnf in Poset nat nat_leq_PosetMixin.\n\nInductive nat_top :=\n| nat_top_nat (n : nat)\n| nat_top_top.\n\nInductive nat_top_leq : nat_top -> nat_top -> Prop :=\n| nat_top_leq_nat_nat : forall m n, m <= n -> nat_top_leq (nat_top_nat m) (nat_top_nat n)\n| nat_top_leq_nat_top : forall n, nat_top_leq (nat_top_nat n) nat_top_top\n| nat_top_leq_top_top : nat_top_leq nat_top_top nat_top_top.\n\nNotation \"x <=T y\" := (nat_top_leq x y) (at level 40).\n\nLemma nat_top_leq_refl : forall x, x <=T x.\nProof.\ncase.\n- move => n.\n  apply nat_top_leq_nat_nat.\n  exact: leqnn.\n- apply nat_top_leq_top_top.\nQed.\n\nLemma nat_top_leq_antisymmetric : forall x y, x <=T y -> y <=T x -> x = y.\nProof.\ncase.\n- move => m.\n  case.\n  * move => n Hle Hle'.\n    inversion Hle; subst.\n    inversion Hle'; subst.\n    by rewrite (nat_leq_antisymmetric H1 H2).\n  * move => Hle Hle'.\n    by inversion Hle'.\n- case => //=.\n  move => n Hle.\n  by inversion Hle.\nQed.\n\nLemma nat_top_leq_trans : forall x y z, x <=T y -> y <=T z -> x <=T z.\nProof.\ncase.\n- move => x.\n  case.\n  * move => y.\n    case.\n    + move => z.\n      move => Hle Hle'.\n      inversion Hle; subst.\n      inversion Hle'; subst.\n      apply nat_top_leq_nat_nat.\n      by eapply nat_leq_trans; eauto.\n    + move => Hle Hle'.\n      exact: nat_top_leq_nat_top.\n  * case.\n    + move => n.\n      move => Hle Hle'.\n      by inversion Hle'.\n    + move => Hle Hle'.\n      exact: nat_top_leq_nat_top.\n- case.\n  * move => m.\n    case.\n    + move => n.\n      move => Hle Hle'.\n      by inversion Hle.\n    + move => Hle.\n      by inversion Hle.\n  * case.\n    + move => n Hle Hle'.\n      by inversion Hle'.\n    + move => Hle Hle'.\n      exact: nat_top_leq_top_top.\nQed.\n\nDefinition nat_top_leq_PosetMixin := \n  PosetMixin nat_top_leq_refl nat_top_leq_antisymmetric nat_top_leq_trans.\nCanonical nat_top_leq_Poset := Eval hnf in Poset nat_top nat_top_leq_PosetMixin.\n\nSection LatticeFacts.\n\nVariable L : lattice.\n\nVariable S T : Pred L.\n\nLocal Notation \"⋁ S\" := (sup S) (at level 40).\nLocal Notation \"⋀ S\" := (inf S) (at level 40).\nLocal Notation \"s ⋞ t\" := (Poset.leq s t) (at level 70).\nLocal Notation \"s ∈ S\" := (s \\In S) (at level 70).\n\n(* Mini-exercises from p. 44 in Ordered Sets and Complete Lattices *)\n(* http://profs.sci.univr.it/~giaco/paperi/lattices-for-CS.pdf *)\n\nLemma mini_i_1 : forall s, s ∈ S -> s ⋞ ⋁ S.\nProof.\nexact: supP.\nQed.\n\nLemma mini_i_2 : forall s, s ∈ S -> ⋀ S ⋞ s.\nProof.\nexact: infP.\nQed.\n\nLemma mini_iv_1 :\n  ⋁ S ⋞ ⋀ T ->\n  (forall s t, s ∈ S -> t ∈ T -> s ⋞ t).\nProof.\nmove => HST s t Hs Ht.\nhave HsupP := supP Hs.\nhave HinfP := infP Ht.\nhave Hle: s ⋞ inf T.\n  move: HsupP HST.\n  exact: poset_trans.\nmove: Hle HinfP.\nexact: poset_trans.\nQed.\n\nLemma mini_iv_2 :\n  (forall s t, s ∈ S -> t ∈ T -> s ⋞ t) ->\n  ⋁ S ⋞ ⋀ T.\nProof.\nmove => Hst.\nhave HsupM := @supM _ S (inf T).\napply HsupM.\nmove => y Hy.\nhave HinfM := @infM _ T y.\napply HinfM.\nmove => x Hx.\nexact: Hst.\nQed.\n\nHypothesis S_subset_T : forall s, s ∈ S -> s ∈ T.\n\nLemma mini_v_1 : ⋁ S ⋞ ⋁ T.\nProof.\napply supM.\nmove => y H.\napply supP.\nexact: S_subset_T.\nQed.\n\nLemma mini_v_2 : ⋀ T ⋞ ⋀ S.\nProof.\napply infM.\nmove => y H.\napply infP.\nexact: S_subset_T.\nQed.\n\nEnd LatticeFacts.\n", "meta": {"author": "palmskog", "repo": "lattices", "sha": "24fe873f0ffd9c4bdf9a17e67ae1636ba6f02755", "save_path": "github-repos/coq/palmskog-lattices", "path": "github-repos/coq/palmskog-lattices/lattices-24fe873f0ffd9c4bdf9a17e67ae1636ba6f02755/core/lattices.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.6990416062296134}}
{"text": "Require DTS_Def.\nModule DTS_Example <: DTS_Def.DTS_Par.\n\n(** Die Zustaende des Wechselschalters und die Instanziierung. *)\n\nInductive Q' := on : Q' | off : Q'.\nDefinition Q := Q'.\n\n(** Das Eingabealphabet des Wechselschalters und die Instanziierung. *)\n\nInductive Sigma' := press : Sigma'.\nDefinition Sigma := Sigma'.\n\n(** Definition, welche Uebergaenge moeglich sind. *)\n\nDefinition delta (p : Q) (a : Sigma) : Q :=\n  match p with\n    | on  => off\n    | off  => on\n  end.\n\n(** Startzustand: *)\n\nDefinition q0 := off.\n\n(** Akzeptierende Zustaende: *)\n\nDefinition is_accepting (q : Q) : Type :=\n  match q with\n    | on => True\n    | off => False\n  end.\n\nEnd DTS_Example.\n\nModule Ex_Prop := DTS_Def.DTS_Fun DTS_Example.\nRequire Import Words.\nImport DTS_Example.\nImport Ex_Prop.\n\n(** Durch die oben gegebenen Definitionen lassen sich zwei Sprachen definieren, die mit\n einer geraden Anzahl an Eingaben [even_press] und die mit einer ungeraden Anzahl\n an Eingaben [odd_press]. *)\n\nInductive even_press : @Word Sigma -> Type :=\n  | eps_even : even_press eps\n  | snoc_even {w : @Word Sigma} {a : Sigma} : odd_press w -> even_press (snoc w a)\nwith odd_press : @Word Sigma -> Type :=\n  | snoc_odd {w : @Word Sigma} {a : Sigma} : even_press w -> odd_press (snoc w a).\n\n(** Beweis, dass die Sprache des [DTS_Example] = [odd_press] ist, indem die folgenden\n Implikationen gezeigt werden.\n - forall w, Lang_delta w -> odd_press w\n - forall w, odd_press w -> Lang_delta w\n Dazu wird ein typwertiges Praedikat benoetigt, um zu wissen in welchem Zustand sich\n der Automat nach der Eingabe befindet. *)\n\nLemma finish_input : forall w,\n      ((even_press w * (delta_hat q0 w = off)) +\n      (odd_press w * (delta_hat q0 w = on)))%type.\nProof.\n  induction w.\n  - simpl.\n    left.\n    split.\n    + exact eps_even.\n    + reflexivity.\n  - simpl.\n    destruct IHw as [[peven x] | [podd y]].\n    + right.\n       split.\n       * exact (snoc_odd peven).\n       * rewrite x.\n         simpl.\n         reflexivity.\n    + left.\n       split.\n       * exact (snoc_even podd).\n       * rewrite y.\n         simpl.\n         reflexivity.\nDefined.\n\n(** Die Eingabe hat eine gerade oder ungerade Laenge. [even_press] und [odd_press]\n sind disjunkt. *)\n\nLemma even_odd_disjoint (w : @Word Sigma) :\n      even_press w -> odd_press w -> False.\nProof.\n  intros even odd.\n  induction w.\n  - inversion odd.\n  - inversion even.\n    inversion odd.\n    exact (IHw X0 X).\nDefined.\n\n(** Jetzt koennen beide Richtungen der Aequivalenz gezeigt werden.\n - forall w, Lang_delta w -> odd_press w\n - forall w, odd_press w -> Lang_delta w *)\n\nLemma Lang_odd : forall w, Lang_delta w -> odd_press w.\nProof.\n  unfold Lang_delta.\n  intros w w_in_L.\n  pose (finish_input w) as decide_L.\n  destruct decide_L as [[even off] |[odd on]].\n  - rewrite off in w_in_L.\n    simpl in w_in_L.\n    destruct w_in_L.\n  - exact odd.\nDefined.\n\nLemma odd_Lang : forall w, odd_press w -> Lang_delta w.\nProof.\n  unfold Lang_delta.\n  intros w odd.\n  pose (finish_input w) as decide_L.\n  destruct decide_L as [[even off] |[odd' on]].\n  - pose (even_odd_disjoint w even odd) as ff.\n    destruct ff.\n  - rewrite on.\n    simpl.\n    exact I.\nDefined.\n\n(** Aequivalenz zwischen odd_press und Lang_delta. Die Sprache die von dem\nToggle Automaten akzeptiert wird, besteht genau aus den Woertern deren Laenge\nungerade ist. *)\n\nRequire Import Equivalences.\nModule Lang_Toggle : Logical_EQ_type_valued_pred.\nDefinition  base := @Word Sigma.\nDefinition P := odd_press.\nDefinition Q := Lang_delta.\nDefinition pq := odd_Lang.\nDefinition qp := Lang_odd.\nEnd Lang_Toggle.\n\n(** Es muss noch gezeigt werden, dass das Eingabealphabet und die Zustandsmenge\n endlich sind. *)\n\nRequire Import FiniteClass.\nRequire Import Fin.\nRequire Import Program.\n\n(** Die Zustandsmenge ist endlich. *)\n\nInstance Q_Finite : Finite Q := {\n  card := 2;\n  to x := match x with\n    | off => F1\n    | on => FS (F1)\n  end;\n  from i := match i with\n    | F1             => off\n    | FS  (F1 )   => on\n    | FS  (FS _) => off\n  end\n}.\nProof.\n  - intro i.\n    repeat dependent destruction i; reflexivity.\n  - intro x.\n    destruct x;reflexivity.\nQed.\n\n(** Das Eingabealphabet ist endlich. *)\n\nInstance Sigma_Finite : Finite Sigma := {\n  card := 1;\n  to x := match x with\n    | press => F1\n  end;\n  from i := match i with\n    | F1             => press\n    | FS  (F1 )   => press\n    | FS  (FS _) => press\n  end\n}.\nProof.\n  - intro i.\n    repeat dependent destruction i; reflexivity.\n  - intro x.\n    destruct x;reflexivity.\nQed.\n", "meta": {"author": "margrit", "repo": "Code", "sha": "b3e89580b33732c23cdf4df8171d6c76ce9186e7", "save_path": "github-repos/coq/margrit-Code", "path": "github-repos/coq/margrit-Code/Code-b3e89580b33732c23cdf4df8171d6c76ce9186e7/Code/DTS_Toggle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.6990416025107692}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_congruenceflip.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_lessthancongruence.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_TGsymmetric : \n   forall A B C a b c, \n   TG A a B b C c ->\n   TG B b A a C c.\nProof.\nintros.\nrename_H H;\nlet Tf:=fresh in\nassert (Tf:exists H, (BetS A a H /\\ Cong a H B b /\\ Lt C c A H)) by (conclude_def TG );destruct Tf as [H];spliter.\nassert (neq a H) by (forward_using lemma_betweennotequal).\nassert (neq B b) by (conclude axiom_nocollapse).\nassert (neq A a) by (forward_using lemma_betweennotequal).\nlet Tf:=fresh in\nassert (Tf:exists F, (BetS B b F /\\ Cong b F A a)) by (conclude lemma_extension);destruct Tf as [F];spliter.\nassert (Cong a A F b) by (forward_using lemma_doublereverse).\nassert (Cong A a F b) by (forward_using lemma_congruenceflip).\nassert (Cong a H b B) by (forward_using lemma_congruenceflip).\nassert (BetS F b B) by (conclude axiom_betweennesssymmetry).\nassert (Cong A H F B) by (conclude cn_sumofparts).\nassert (Cong A H B F) by (forward_using lemma_congruenceflip).\nassert (Lt C c B F) by (conclude lemma_lessthancongruence).\nassert (TG B b A a C c) by (conclude_def TG ).\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_TGsymmetric.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.798186784940666, "lm_q1q2_score": 0.6990415979808574}}
{"text": "Require Import Bool Arith List Lib.CpdtTactics.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\n(* ---------- Source language of our compiler ------------- *)\n\nInductive type : Set := Nat | Bool.\n\n(* Map types of object language to Coq types. *)\nDefinition typeDenote (t : type) : Set :=\n  match t with\n  | Nat => nat\n  | Bool => bool\n  end.\n\n(* Syntax of the source language. *)\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 (* Polymorphism: allow equality of any two values of any type, as long as they have the same type. *)\n| TLt : tbinop Nat Nat Bool.\n\n(* Interpret with standard library. *)\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\n(* Our type of arithmetic 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\nFixpoint texpDenote t (e : texp t) : typeDenote t :=\n  match e with\n  | TNConst n => n\n  | TBConst b => b\n  | TBinop _ _ _ b e1 e2 => (tbinopDenote b) (texpDenote e1) (texpDenote e2)\n  end.\n\n(* Evaluate examples. *)\nEval simpl in texpDenote (TNConst 41).\nEval simpl in texpDenote (TBConst true).\nEval simpl in texpDenote (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).\nEval simpl in texpDenote (TBinop (TEq Nat) (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).\nEval simpl in texpDenote (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).\n\n(* ---------- Target language of our compiler ------------- *)\n\n(* Stack types classify sets of possible stacks. *)\nDefinition tstack := list type.\n\n(* Instructions in terms of stack types.\n   Every instruction's type tells what initial stack type it expects and\n   what final stack type it will produce. *)\nInductive tinstr : tstack -> tstack -> Set :=\n| TiNConst : forall s, nat -> tinstr s (Nat :: s)\n| TiBConst : forall s, bool -> tinstr s (Bool :: s)\n| TiBinop : forall arg1 arg2 res s,\n    tbinop arg1 arg2 res -> tinstr (arg1 :: arg2 :: s) (res :: s).\n\n(* Stack machine programs must guarantee that intermediate stack types\n   match within a program. *)\nInductive tprog : tstack -> tstack -> Set :=\n| TNil : forall s, tprog s s\n| TCons : forall s1 s2 s3,\n    tinstr s1 s2 -> tprog s2 s3 -> tprog s1 s3.\n\n(* Value stacks at runtime. *)\nFixpoint vstack (ts : tstack) : Set :=\n  match ts with\n  | nil => unit\n  | t :: ts' => typeDenote t * vstack ts'\n  end%type.\n\nDefinition tinstrDenote ts ts' (i : tinstr ts ts') : vstack ts -> vstack ts' :=\n  match i with\n  | TiNConst _ n => fun s => (n ,s)\n  | TiBConst _ b => fun s => (b, s)\n  | TiBinop _ _ _ _ b => fun s =>\n                           let '(arg1, (arg2, s')) := s in\n                           ((tbinopDenote b) arg1 arg2, s')\n  end.\n\nFixpoint tprogDenote ts ts' (p : tprog ts ts') : vstack ts -> vstack ts' :=\n  match p with\n  | TNil _ => fun s => s\n  | TCons _ _ _ i p' => fun s => tprogDenote p' (tinstrDenote i s)\n  end.\n\n(* ---------- Compiler definition ------------- *)\n\n(* Translation. *)\n\n(* Helper for concatenating two stack machine programs. *)\nFixpoint tconcat ts ts' ts'' (p : tprog ts ts') : tprog ts' ts'' -> tprog ts ts'' :=\n  match p with\n  | TNil _ => fun p' => p'\n  | TCons _ _ _ i p1 => fun p' => TCons i (tconcat p1 p')\n  end.\n\nFixpoint tcompile t (e : texp t) (ts : tstack) : tprog ts (t :: ts) :=\n  match e with\n  | TNConst n => TCons (TiNConst _ n) (TNil _)\n  | TBConst b => TCons (TiBConst _ b) (TNil _)\n  | TBinop _ _ _ b e1 e2 => tconcat (tcompile e2 _) (tconcat (tcompile e1 _) (TCons (TiBinop _ b) (TNil _)))\n  end.\n\n(* Run some compiled programs. *)\n\nEval simpl in tprogDenote (tcompile (TNConst 42) nil) tt.\nEval simpl in tprogDenote (tcompile (TBConst true) nil) tt.\nEval simpl in tprogDenote (tcompile (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)) nil) tt.\nEval simpl in tprogDenote (tcompile (TBinop (TEq Nat) (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)) nil) tt.\nEval simpl in tprogDenote (tcompile (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)) nil) tt.\n\n(* Show translation correctness. *)\n\n(* Strategy: In addition to the source expression and its type,\n   we quantify over an initial stack type and a stack compatible with it.\n   Running the compilation of the program starting from that stack,\n   we should arrive at a stack that differs only in having the program's\n   denotation pushed onto it. *)\nLemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),\n    tprogDenote (tcompile e ts) s = (texpDenote e, s).\nAbort.\n\n(* Analogue to the [app_assoc_reverse]. *)\nLemma tconcat_corret : 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\n(* Register lemma to be used by the brute-force script. *)\nHint Rewrite tconcat_corret.\n\nLemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),\n    tprogDenote (tcompile e ts) s = (texpDenote e, s).\nProof.\n  induction e; crush.\nQed.\n\nHint Rewrite tcompile_correct'.\n\nTheorem tcompile_correct : forall t (e : texp t),\n    tprogDenote (tcompile e nil) tt = (texpDenote e, tt).\nProof.\n  crush.\nQed.\n", "meta": {"author": "brunoflores", "repo": "cpdt", "sha": "81715180518e1063e9ab856e5a2e68a7c1378df0", "save_path": "github-repos/coq/brunoflores-cpdt", "path": "github-repos/coq/brunoflores-cpdt/cpdt-81715180518e1063e9ab856e5a2e68a7c1378df0/StackMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6990415926453634}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Word.Interface coqutil.Datatypes.HList coqutil.Datatypes.PrimitivePair.\nRequire Import coqutil.Word.Properties.\nRequire Import coqutil.Z.bitblast.\nRequire Import coqutil.Z.prove_Zeq_bitwise.\nRequire Import coqutil.Byte.\nLocal Set Universe Polymorphism.\n\nLocal Open Scope Z_scope.\n\nSection BigEndian. Local Set Default Proof Using \"All\".\n\n  Fixpoint combine (n : nat) : forall (bs : tuple byte n), Z :=\n    match n with\n    | O => fun _ => 0\n    | S m => fun bs => Z.lor (Z.shiftl (byte.unsigned (pair._1 bs)) (8 * Z.of_nat m))\n                             (combine m (pair._2 bs))\n    end.\n\n  Fixpoint split (n : nat) (w : Z) : tuple byte n :=\n    match n with\n    | O => tt\n    | S m => pair.mk (byte.of_Z (Z.shiftr w (8 * Z.of_nat m))) (split m w)\n    end.\n\n  Arguments Z.mul: simpl never.\n  Arguments Z.pow: simpl never.\n  Arguments Z.of_nat: simpl never.\n  Arguments Nat.mul: simpl never.\n\n  Lemma combine_bound: forall {n: nat} (t: HList.tuple byte n),\n      0 <= combine n t < 2 ^ (8 * Z.of_nat n).\n  Proof.\n    induction n; intros.\n    - destruct t. cbv. intuition discriminate.\n    - destruct t as [b t]. unfold combine. simpl.\n      specialize (IHn t).\n      match goal with\n      | |- context [?F n t] => change (F n t) with (combine n t)\n      end.\n      pose proof (byte.unsigned_range b).\n      replace (8 * Z.of_nat (S n)) with (8 * Z.of_nat n + 8) by blia.\n      rewrite Z.pow_add_r by blia.\n      rewrite Z.or_to_plus.\n      + rewrite (Z.shiftl_mul_pow2 (byte.unsigned b)) by blia. Lia.nia.\n      + prove_Zeq_bitwise.\n  Qed.\n\n  Lemma combine_split (n : nat) (z : Z) :\n    combine n (split n z) = z mod 2 ^ (Z.of_nat n * 8).\n  Proof.\n    revert z; induction n.\n    - cbn. intros. rewrite Z.mod_1_r. trivial.\n    - cbn [split combine PrimitivePair.pair._1 PrimitivePair.pair._2]; intros.\n      erewrite IHn; clear IHn.\n      rewrite byte.unsigned_of_Z, Nat2Z.inj_succ, Z.mul_succ_l by blia.\n      unfold byte.wrap.\n      rewrite <-! Z.land_ones by blia.\n      Z.bitblast.\n  Qed.\n\n  Lemma split_combine (n: nat) bs :\n    split n (combine n bs) = bs.\n  Proof.\n    revert bs; induction n.\n    - destruct bs. reflexivity.\n    - destruct bs; cbn [split combine PrimitivePair.pair._1 PrimitivePair.pair._2]; intros.\n      f_equal.\n      { eapply byte.unsigned_inj.\n        rewrite byte.unsigned_of_Z, <-byte.wrap_unsigned; cbv [byte.wrap].\n        pose proof combine_bound _2 as B.\n        Z.bitblast. cbn. subst.\n        rewrite (testbit_above B) by blia.\n        Z.bitblast_core. }\n      { etransitivity. 1: symmetry. 1: eapply IHn.\n        rewrite combine_split.\n        rewrite <-IHn.\n        f_equal.\n        pose proof combine_bound _2 as B.\n        rewrite <- (Z.mod_small _ _ B) at 2.\n        rewrite <-?Z.land_ones by blia.\n        Z.bitblast; subst; cbn.\n        rewrite (Z.testbit_neg_r _ (i - 8 * Z.of_nat n)) by blia.\n        reflexivity. }\n  Qed.\n\nEnd BigEndian.\n\nArguments combine: simpl never.\nArguments 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/BigEndian.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6988869352104142}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) : natural := mult lf2 lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_90_mult_zero/goal33conj32_coqofml_66b1Yq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6988869259334155}}
{"text": "(**\nフィボナッチ数の最大公約数 (GCD of Fibonacci Numbers)\n============================\n\n@suharahiromichi\n\n2022/01/21\n\n2022/01/29 GCDの帰納法について修正した。\n*)\n\n(**\nこのソースは、以下にあります。\n\nhttps://github.com/suharahiromichi/coq/blob/master/math/ssr_fib_3.v\n*)\n\n(**\n# はじめに\n\nm番めとn番めフィボナッチ数の最大公約数は、mとnの最大公約数番めのフィボナッチ数に等しい、\nという定理があります。\n\n```math\ngcd(F_m, F_n) = F_{gcd(m, n)}\n\n```\n\nこれは エドゥアール・リュカ (ルーカス）が最初に報告したのを\nクヌース先生が紹介して広まったのだそうです。\nTAOCP[2]に掲載されているようですが、私が読んだのは [1]と[1'] のほうで、\n証明は演習問題(6.27)になっています。\n\nそこで、早速答えをみると、\nフィボナッチ数の加法定理に相当する式から、「$ m > n $ \nならば、$ gcd(F_m, F_n) = gcd(F_{m - n}, F_n) $\nであることに注意して、帰納法使って証明せよ」、とだけ書いてあります。\n\n証明を集めたサイト[3]を見ても書いてあることは同じで、[4]\nはもう少し詳しいですが、帰納法のところは証明というより説明になっています。\n\nでは、この定理の証明をCoqでやってみましょう、とりあえず、以下の方針でおこないます。\n\n1. gcdに関する帰納法が肝なので、そこは Coq の Functional Induction [5] に任せる。\n\n2. 1.のためには、Function コマンドで自分でフィボナッチ数を定義する必要がある。\nそれも [5] を参考にした。\n\n3. MathComp の GCDに関する豊富な補題を使うために、2.の定義と\nMathCompのGCDの定義が同じであることを証明しておく。\n\n\n\nMathCompで証明をするならば、MathCompで定義されている\n自然数の最大公約数の関数 gcdn について、なんらかのかたちで帰納法の原理を用意するのが\n正しいアプローチですが、それは [7] を参照してください。\n\nまた、フィボナッチ数の加法定理については、[6] で証明しているため、証明は省略します。\n*)\n\nFrom mathcomp Require Import all_ssreflect.\nRequire Import FunInd.                      (* Functional Scheme *)\nRequire Import Recdef.                      (* Function *)\nRequire Import Wf_nat.                      (* wf *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n(* Set Print All. *)\n\nSection Fib3.\n\n(**  \n# フィボナッチ数の定義と定理\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(**\n1個分のフィボナッチ数の計算\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  Lemma fib_coprime (n : nat) : coprime (fib n) (fib n.+1).\n  Proof.\n    rewrite /coprime.\n    elim: n => [//= | n IHn].\n    rewrite fib_n.\n      by rewrite gcdnDr gcdnC.\n  Qed.\n  \n(**\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    (* see. ssr_fib_2.v *)\n  Admitted.                                 (* OK *)\n\n(**\n# GCDの定義と定理\n*)  \n(**\nFunction を使って定義します。\n*)\n  Function gcd (m n : nat) {wf lt m} : nat :=\n    match m with\n    | 0 => n\n    | _ => gcd (n %% m) m\n    end.\n  Proof.\n    - move=> m n m0 _.\n      apply/ltP.\n        by rewrite ltn_mod.\n    - by apply: lt_wf.\n  Qed.\n\n(**\nMathComp の gcdn を同じであることを証明する。\n*)  \n  Lemma gcdE m n : gcdn m n = gcd m n.\n  Proof.\n    functional induction (gcd m n).\n    - by rewrite gcd0n.\n    - rewrite -IHn0.\n        by rewrite gcdnC gcdn_modl.\n  Qed.\n  \n(**\nGCDの可換性\n*)\n  Check gcdnC : forall m n, gcdn m n = gcdn n m.\n  Lemma gcdC m n : gcd m n = gcd n m.\n  Proof.\n      by rewrite -2!gcdE gcdnC.\n  Qed.\n\n(**\nGCDの簡単な性質\n*)  \n  Lemma gcd0m m : gcd 0 m = m.\n  Proof.\n      by rewrite gcd_equation.            (* gcd の定義で展開する。 *)\n  Qed.\n  \n  Lemma gcdmm m : gcd m m = m.\n  Proof.\n    case: m => [| m].\n    - by rewrite gcd_equation.\n    - by rewrite gcd_equation modnn gcd0m.\n  Qed.\n  \n  Lemma gcdnn_gcd0n n : gcd n n = gcd 0 n.\n  Proof.\n      by rewrite gcdmm gcd0m.\n  Qed.\n  \n  Check gcdnMDl : forall k m n : nat, gcdn m (k * m + n) = gcdn m n.\n  Lemma gcdMDl (k m n : nat) : gcd m (k * m + n) = gcd m n.\n  Proof.\n      by rewrite -2!gcdE gcdnMDl.\n  Qed.\n  \n  Check Gauss_gcdl : forall p m n : nat, coprime p n -> gcdn p (m * n) = gcdn p m.\n  Lemma Gauss_gcdl' p m n : coprime p n -> gcd p (m * n) = gcd p m.\n  Proof.\n    rewrite -2!gcdE.\n      by apply: Gauss_gcdl.\n  Qed.\n  \n(**\n# フィボナッチ数のGCD\n*)\n\n(**\nGKPの解答にある、``m > n`` ならば ``gcd (fib m) (fib n) = gcd (fib (m - n)) (fib n)``\nと同じものを証明するが、そのために ``m`` を ``0`` と非0で振り分ける。\n *)\n  Lemma fib_lemma_gkp' m n :\n    1 <= m -> gcd (fib (n + m)) (fib n) = gcd (fib m) (fib n).\n  Proof.\n    move=> H.\n    rewrite fib_addition //.\n    rewrite gcdC addnC gcdMDl.\n    rewrite Gauss_gcdl'.\n    - by rewrite gcdC.\n    - by apply: fib_coprime.\n  Qed.\n  \n  Lemma fib_lemma_gkp m n :\n    gcd (fib (n + m)) (fib n) = gcd (fib m) (fib n).\n  Proof.\n    case: m => [| m].\n    - rewrite addn0 /=.\n        by apply: gcdnn_gcd0n.\n    - rewrite fib_lemma_gkp' //=.\n  Qed.\n  \n(**\ngcdnMDl のフィボナッチ数版\n*)\n  Check gcdnMDl : forall k m n : nat, gcdn m (k * m + n) = gcdn m n.\n  Lemma fib_gcdMDl n q r :\n    gcd (fib (q * n + r)) (fib n) = gcd (fib n) (fib r).\n  Proof.\n    elim: q => [| q IHq].\n    - rewrite mul0n add0n.\n      rewrite gcdC.\n      done.\n    - Search _ (_.+1 * _).\n      rewrite mulSn -addnA.\n      rewrite [LHS]fib_lemma_gkp.\n      done.\n  Qed.\n  \n(**\ngcdn_modr のフィボナッチ数版\n*)\n  Check gcdn_modr : forall m n : nat, gcdn m (n %% m) = gcdn m n.\n  Lemma fin_gcd_modr m n :\n    gcd (fib m) (fib n) = gcd (fib n) (fib (m %% n)).\n  Proof.\n    move: (fib_gcdMDl n (m %/ n) (m %% n)).\n    rewrite -divn_eq.\n    done.\n  Qed.\n\n(**\n# 証明したいもの\n\n$ F_0 = 0 $ や $ F_1 = 1 $ でも成り立つことを確認しておく。\n*)\n  Compute gcdn 0 0.                         (* 0 *)\n  Compute gcdn 1 0.                         (* 1 *)\n  Compute gcdn 0 1.                         (* 1 *)\n  Compute gcdn 1 1.                         (* 1 *)\n  \n  Goal gcd (fib 1) (fib 0) = fib (gcd 1 0).\n  Proof.\n    rewrite gcd_equation //=.\n      by rewrite gcd_equation.\n  Qed.\n  \n(**\nfunctional induction を使って証明します。\n*)\n  Theorem gcd_fib__fib_gcd (m n : nat) : gcd (fib m) (fib n) = fib (gcd m n).\n  Proof.\n    rewrite gcdC.\n    functional induction (gcd m n).\n    - rewrite gcdC.\n      rewrite gcd_equation.\n      done.\n    (* \n  IHn0 : gcd (fib m) (fib (n %% m)) = fib (gcd (n %% m) m)\n  ============================\n  gcd (fib n) (fib m) = fib (gcd (n %% m) m)\n     *)\n    - rewrite fin_gcd_modr.\n      done.\n  Qed.\n  \nEnd Fib3.\n\nSection Fib3_2.\n(**\n# おまけ\n\nCoq Tokyo 終了後に教えてもらった GCD の帰納法\n*)\n  Lemma my_gcdn_ind (P : nat -> nat -> nat -> Prop) :\n    (forall n, P 0 n n) ->\n    (forall m n, P (n %% m) m (gcdn (n %% m) m) -> P m n (gcdn m n)) ->\n    forall m n, P m n (gcdn m n).\n  Proof.\n    move => H0 Hmod.\n    elim/ltn_ind => [[| m ]] // H n.\n    - have -> : gcdn 0 n = n by elim: n.\n      done.\n    - apply : Hmod.\n      exact : H (ltn_mod _ _) _.\n  Qed.\n\n(**\nこれを使うと functional induction を使わずに証明できます。\n\n[7] を参照してください。\n*)  \nEnd Fib3_2.\n\n(**\n# 文献\n\n[1] Graham, Knuth, Patashnik \"Concrete Mathematics\", Second Edition\n\n\n[1'] 有澤、安村、萩野、石畑訳、「コンピュータの数学」共立出版\n\n\n[2] D.E.Knuth, \"The Art of Computer Programming: Vol.1: Fundamental Algorithms (3rd ed.) \"\n\n\n[3] \"GCD of Fibonacci Numbers\"、https://proofwiki.org/wiki/GCD_of_Fibonacci_Numbers\n\n\n[4] ぱるち、「フィボナッチ数列で互除法っぽいこと」、https://mathlog.info/articles/278\n\n\n[5] 名古屋大学 2021年度秋・数理解析・計算機数学 IV (同 概論IV) \"Mathcomp, 自己反映と数論の証明\"、\nhttps://www.math.nagoya-u.ac.jp/~garrigue/lecture/2021_AW/ssrcoq5.pdf\n\n\n[6] https://github.com/suharahiromichi/coq/blob/master/math/ssr_fib_2.v\n\n\n[7] https://github.com/suharahiromichi/coq/blob/master/math/ssr_fib_3_2.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/math/ssr_fib_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636752, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6988869175288327}}
{"text": "Require Import ZArith.\nRequire Import Zhints.\nRequire Import Zpow_facts.\nRequire Import BinInt. Import Z.\nRequire Import Znat.\nRequire Import Zeuclid. Import ZEuclid.\nRequire Import Znumtheory.\nRequire Import Reciprocity.Reciprocity.Finite. Import FiniteTypes.\nRequire Import Reciprocity.Reciprocity.Accumulation. Import Accum.\nRequire Import Classical.\nRequire Import Lia.\n\nLemma Zpos_induction (P : Z -> Prop) :\n  P 0 ->\n  (forall n : Z, 0 <= n -> P n -> P (succ n)) ->\n  (forall n : Z, 0 <= n -> P n).\nProof.\n  intros P0 Psucc.\n  assert (forall n : nat, P (Z.of_nat n)).\n  simple induction n. auto.\n  intro n0. rewrite Nat2Z.inj_succ. apply Psucc. apply Nat2Z.is_nonneg.\n  intros n Hpos. rewrite <- Z2Nat.id by auto. apply H.\nQed.\n\nLemma prime_divide_pow :\n  forall x p n : Z, 0 <= n -> prime p -> (p | x ^ n) -> (p | x).\nProof.\n  intros x p.\n  apply (Zpos_induction (fun n => prime p -> (p | x ^ n) -> (p | x))).\n  simpl. intros _ H. destruct H. exists (x * x0). rewrite <- Zmult_assoc.\n  rewrite <- H. apply Zred_factor0.\n  intros n Hpos Hrec Hprime Hdiv.\n  rewrite pow_succ_r in Hdiv by auto. apply prime_mult in Hdiv.\n  destruct Hdiv. auto. auto. auto.\nQed.\n\nLemma power_plus :\n  forall x m n, 0 <= n -> 0 <= m -> x ^ (n + m) = x ^ n * x ^ m.\nProof.\n  intros x m.\n  apply (Zpos_induction (fun n => 0 <= m -> x ^ (n + m) = x ^ n * x ^ m)).\n  intro H. rewrite pow_0_r. rewrite mul_1_l. auto.\n  intros n Hnpos Hrec Hmpos.\n  rewrite add_succ_l. rewrite pow_succ_r. rewrite pow_succ_r by auto.\n  rewrite <- Zmult_assoc. f_equal. auto. lia.\nQed.\n\nLemma one_pow :\n  forall n, 0 <= n -> 1 ^ n = 1.\nProof.\n  apply (Zpos_induction (fun n => 1 ^ n = 1)).\n  auto. intros n Hpos Hrec. rewrite pow_succ_r by auto. rewrite Hrec. lia.\nQed.\n\nLemma power_power :\n  forall x m n, 0 <= n -> 0 <= m -> (x ^ n) ^ m = x ^ (n * m).\nProof.\n  intros x m.\n  apply (Zpos_induction (fun n => 0 <= m -> (x ^ n) ^ m = x ^ (n * m))).\n  intro. simpl. apply one_pow. auto.\n  intros n Hnpos Hrec Hmpos. rewrite pow_succ_r by auto.\n  rewrite Zmult_power by auto. rewrite Zmult_succ_l.\n  rewrite power_plus. rewrite Zmult_comm. f_equal.\n  auto. rewrite <- mul_0_l with (n := m).\n  apply Zmult_le_compat_r. auto. auto. auto.\nQed.\n\nLemma minus_one_pow_even :\n  forall n : Z, 0 <= n -> Even n -> (-1) ^ n = 1.\nProof.\n  intros n Hpos Heven. destruct Heven.\n  rewrite H.\n  rewrite <- power_power by lia. apply one_pow. lia.\nQed.\n\nLemma minus_one_pow_odd :\n  forall n : Z, 0 <= n -> Odd n -> (-1) ^ n = -1.\nProof.\n  intros n Hpos Hodd. destruct Hodd.\n  rewrite H. rewrite power_plus by lia.\n  rewrite <- power_power by lia. rewrite one_pow. auto. lia.\nQed.\n\nLemma even_mod :\n  forall n : Z, Even n <-> n mod 2 = 0.\nProof.\n  intro n. split.\n  intro Heven. destruct Heven. rewrite H. rewrite Zmult_mod.\n  auto.\n  intro Hmod. exists (n / 2). apply Z_div_exact_2. lia. auto.\nQed.\n\nLemma odd_mod :\n  forall n : Z, Odd n <-> n mod 2 = 1.\nProof.\n  intro n. split.\n  intro Hodd. destruct Hodd. rewrite H. rewrite Zplus_comm.\n  rewrite Zmult_comm. rewrite Z_mod_plus_full. auto.\n  intro Hmod. exists (n / 2). rewrite <- Hmod. apply Z_div_mod_eq.\n  lia.\nQed.\n\nLemma even_or_odd n :\n  Even n \\/ Odd n.\nProof.\n  rewrite <- Zeven_equiv. rewrite <- Zodd_equiv.\n  destruct (Zeven_odd_dec n). auto. auto.\nQed.\n\nLemma minus_one_pow_mod_2 :\n  forall n m : Z, 0 <= n -> 0 <= m -> ((-1) ^ n = (-1) ^ m <-> n mod 2 = m mod 2).\nProof.\n  intros n m Hnpos Hmpos.\n  destruct (even_or_odd n). assert (n mod 2 = 0). apply even_mod. auto.\n  rewrite H0. rewrite minus_one_pow_even; [ | lia | auto].\n  destruct (even_or_odd m). assert (m mod 2 = 0). apply even_mod. auto.\n  rewrite H2. rewrite minus_one_pow_even; [ | lia | auto].\n  tauto.\n  assert (m mod 2 = 1). apply odd_mod. auto.\n  rewrite H2. rewrite minus_one_pow_odd; [ | lia | auto].\n  split. intro. discriminate. intro. discriminate.\n  assert (n mod 2 = 1). apply odd_mod. auto.\n  rewrite H0. rewrite minus_one_pow_odd; [ | lia | auto].\n  destruct (even_or_odd m). assert (m mod 2 = 0). apply even_mod. auto.\n  rewrite H2. rewrite minus_one_pow_even; [ | lia | auto].\n  split. intro. discriminate. intro. discriminate.\n  assert (m mod 2 = 1). apply odd_mod. auto.\n  rewrite H2. rewrite minus_one_pow_odd; [ | lia | auto].\n  tauto.\nQed.\n\nDefinition m1_pow (n : Z) := -2 * (n mod 2) + 1.\nLemma m1_pow_1_or_m1 :\n  forall n : Z, m1_pow n = 1 \\/ m1_pow n = -1.\nProof.\n  intro n.\n  destruct (even_or_odd n).\n  left. unfold m1_pow. assert (n mod 2 = 0). apply even_mod. auto. lia.\n  right. unfold m1_pow. assert (n mod 2 = 1). apply odd_mod. auto. lia.\nQed.\nLemma m1_pow_compatible :\n  forall n : Z, n >= 0 -> (-1) ^ n = m1_pow n.\nProof.\n  intros n H. destruct (even_or_odd n).\n  rewrite minus_one_pow_even by (lia || auto).\n  unfold m1_pow. assert (n mod 2 = 0). apply even_mod. auto. lia.\n  rewrite minus_one_pow_odd by (lia || auto).\n  unfold m1_pow. assert (n mod 2 = 1). apply odd_mod. auto. lia.\nQed.\nLemma m1_pow_morphism :\n  forall n m : Z, m1_pow (n + m) = m1_pow n * m1_pow m.\nProof.\n  intros n m. unfold m1_pow. rewrite Zplus_mod.\n  destruct (even_or_odd n). assert (n mod 2 = 0). apply even_mod. auto. repeat (rewrite H0).\n  destruct (even_or_odd m). assert (m mod 2 = 0). apply even_mod. auto. repeat (rewrite H2).\n  auto. assert (m mod 2 = 1). apply odd_mod. auto. repeat (rewrite H2). auto.\n  assert (n mod 2 = 1). apply odd_mod. auto. repeat (rewrite H0).\n  destruct (even_or_odd m). assert (m mod 2 = 0). apply even_mod. auto. repeat (rewrite H2).\n  auto. assert (m mod 2 = 1). apply odd_mod. auto. repeat (rewrite H2). auto.\nQed.\n\nLemma minus_mod :\n  forall n m, 0 < n < m -> (-n) mod m = m - n.\nProof.\n  intros n m H.\n  assert (0 < m). lia.\n  assert (0 <= m - n < m). split. lia. lia.\n  assert ((m - n) mod m = m - n).\n  apply Zmod_small. auto.\n  rewrite <- H2. rewrite <- Zminus_mod_idemp_l.\n  rewrite Z_mod_same. auto. lia.\nQed.\n\nLemma mod_eq_div :\n  forall a b n, n <> 0 -> (a mod n = b mod n <-> (n | a - b)).\nProof.\n  intros a b n Hnnz.\n  split.\n  intro H. apply Zmod_divide. auto. rewrite Zminus_mod.\n  rewrite H. rewrite Zminus_diag. auto.\n  intro H. destruct H.\n  assert (a = b + x * n). lia.\n  rewrite H0. apply Z_mod_plus_full.\nQed.\n\nLemma not_0_inversible_mod_p :\n  forall a p, prime p -> a mod p <> 0 -> exists b, (b * a) mod p = 1.\nProof.\n  intros a p Hprime Hanz.\n  assert (rel_prime p a).\n  apply prime_rel_prime. auto. intro H. apply Zdivide_mod in H. contradiction.\n  apply rel_prime_bezout in H. destruct H.\n  exists v. assert ((u * p + v * a) mod p = 1 mod p). f_equal. auto.\n  rewrite Zmod_1_l in H0 by (destruct Hprime; lia).\n  rewrite <- Zplus_mod_idemp_l in H0.\n  rewrite Zmult_mod in H0. rewrite Z_mod_same in H0 by (destruct Hprime; lia).\n  rewrite Zmult_0_r in H0. rewrite Zmod_0_l in H0. auto.\nQed.\n\nLemma simpl_mod_p :\n  forall a b c p, prime p -> a mod p <> 0 -> (a * b) mod p = (a * c) mod p -> b mod p = c mod p.\nProof.\n  intros a b c p Hprime Hanz Heq.\n  destruct (not_0_inversible_mod_p a p Hprime Hanz).\n  assert (((x * a) mod p * b) mod p = ((x * a) mod p * c) mod p).\n  repeat (rewrite Zmult_mod_idemp_l). repeat (rewrite <- Zmult_assoc).\n  rewrite <- Zmult_mod_idemp_r. rewrite Heq. rewrite Zmult_mod_idemp_r. auto.\n  repeat (rewrite H in H0). repeat (rewrite mul_1_l in H0). auto.\nQed.\n\nLemma over_2 :\n  forall a, a mod 2 = 1 -> (a - 1) / 2 = a / 2.\nProof.\n  intros a Hodd.\n  apply mul_reg_l with (p := 2). lia.\n  assert (2 * ((a - 1) / 2) = a - 1 - (a - 1) mod 2).\n  rewrite Zmod_eq_full. lia. lia.\n  assert (2 * (a / 2) = a - a mod 2).\n  rewrite Zmod_eq_full. lia. lia.\n  rewrite H. rewrite H0. rewrite Hodd. rewrite <- Zminus_mod_idemp_l.\n  rewrite Hodd. simpl. rewrite Zmod_0_l. lia.\nQed.\n\nSection Z_over_pZ.\nVariable p : Z.\nHypothesis p_prime : prime p.\nDefinition ZpZmult (x y : Z) := (x *  y) mod p.\nLemma ZpZmult_comm :\n  forall (x y : Z), ZpZmult x y = ZpZmult y x.\nProof.\n  intros. unfold ZpZmult. rewrite Zmult_comm. auto.\nQed.\nLemma ZpZmult_assoc :\n  forall (x y z : Z), ZpZmult x (ZpZmult y z) = ZpZmult (ZpZmult x y) z.\nProof.\n  intros. unfold ZpZmult.\n  rewrite Zmult_mod_idemp_l. rewrite Zmult_mod_idemp_r. rewrite Zmult_assoc.\n  auto.\nQed.\nLemma one_idemp :\n  ZpZmult 1 1 = 1.\nProof.\n  unfold ZpZmult. simpl. apply Zmod_1_l. destruct p_prime. lia.\nQed.\nLemma mod_1_mod :\n  forall x y : Z, ZpZmult x y = ZpZmult (ZpZmult x y) 1.\nProof.\n  intros x y. unfold ZpZmult.\n  rewrite Zmult_1_r. symmetry. apply Zmod_mod.\nQed.\nEnd Z_over_pZ.\n\nLemma card_interval_full :\n  forall a b : Z, a <= b + 1 ->\n    cardinality {u : Z | a <= u <= b} (Z.to_nat (b - a + 1)).\nProof.\n  intros a b Hsmall.\n  assert (forall u : {u : Z | a <= u <= b}, (Z.to_nat (`u - a) < Z.to_nat (b - a + 1))%nat).\n  intro u. destruct u as [u' Hu']. simpl.\n  apply Z2Nat.inj_lt. lia. lia. lia.\n  exists (fun u => exist _ (Z.to_nat (`u - a)) (H u)).\n  apply bijection_inversible.\n  assert (forall x : {x : nat | (x < Z.to_nat (b - a + 1)) % nat}, a <= a + Z.of_nat `x <= b).\n  intro x. destruct x as [x' Hx']. unfold proj1_sig.\n  assert (0 <= Z.of_nat x' < b - a + 1). split. apply Nat2Z.is_nonneg.\n  apply Nat2Z.inj_lt in Hx'. rewrite Z2Nat.id in Hx'. auto. lia.\n  lia.\n  exists (fun x => exist _ (a + Z.of_nat `x) (H0 x)).\n  split.\n  intro x. destruct x as [x' Hx']. apply proj1_inj. unfold proj1_sig.\n  rewrite Z2Nat.id. lia. lia.\n  intro y. destruct y as [y' Hy']. apply proj1_inj. unfold proj1_sig.\n  rewrite <- Nat2Z.id. f_equal. lia.\nQed.\n\nLemma card_interval :\n  forall a b : Z, a <= b ->\n    cardinality {u : Z | a <= u <= b} (Z.to_nat (b - a + 1)).\nProof.\n  intros a b H.\n  apply card_interval_full. lia.\nQed.\n\nSection FLT.\nVariable p : Z.\nHypothesis p_prime : prime p.\nVariable a : Z.\nHypothesis a_not_0 : a mod p <> 0.\n\nLet f (u : {u : Z | 1 <= u <= p - 1}) := (a * `u) mod p.\nLet f'_exists :\n  forall u, 1 <= f u <= p - 1.\nProof with ((destruct p_prime; lia) || auto).\n  intro u. destruct u as [u' Hu']. unfold f. simpl.\n  assert (0 <= (a * u' mod p) < p).\n  apply mod_pos_bound...\n  assert (a * u' mod p <> 0).\n  intro H1. apply Zmod_divide in H1... apply prime_mult in H1...\n  destruct H1. apply Zdivide_mod in H0. contradiction.\n  apply Zdivide_mod in H0. rewrite Zmod_small in H0...\n  lia.\nQed.\nLet f' u := exist (fun k => 1 <= k <= p - 1) (f u) (f'_exists u).\nLet f'_injective :\n  injection f'.\nProof.\n  intros u1 u2 H. destruct u1 as [u1' Hu1']. destruct u2 as [u2' Hu2'].\n  unfold f' in H. apply proj1_inj in H. simpl in H.\n  apply proj1_inj. simpl. unfold f in H. simpl in H.\n  apply simpl_mod_p in H. repeat (rewrite Zmod_small in H by lia). auto.\n  auto. auto.\nQed.\nLet f'_surjective :\n  surjection f'.\nProof with ((destruct p_prime; lia) || auto).\n  intro y. destruct y as [y' Hy'].\n  destruct (not_0_inversible_mod_p a p p_prime a_not_0) as [a' Ha'].\n  assert (1 <= (a' * y') mod p <= p - 1).\n  assert (0 <= (a' * y') mod p < p). apply mod_pos_bound...\n  assert ((a' * y') mod p <> 0). intro H1.\n  assert ((a * (a' * y')) mod p = 0). rewrite Zmult_mod. rewrite H1.\n  rewrite Zmult_0_r. rewrite Zmod_0_l. auto.\n  rewrite Zmult_assoc in H0. rewrite Zmult_comm with (m := a') in H0.\n  rewrite <- Zmult_mod_idemp_l in H0. rewrite Ha' in H0.\n  rewrite Zmult_1_l in H0. rewrite Zmod_small in H0. lia. lia.\n  lia.\n  exists (exist _ ((a' * y') mod p) H).\n  unfold f'. unfold f. simpl. apply proj1_inj. simpl.\n  rewrite Zmult_mod_idemp_r. rewrite Zmult_assoc. rewrite Zmult_comm with (m := a').\n  rewrite <- Zmult_mod_idemp_l. rewrite Ha'. rewrite Zmult_1_l.\n  apply Zmod_small. lia.\nQed.\nLet card_U :\n  cardinality {u : Z | 1 <= u <= p - 1} (Z.to_nat (p - 1)).\nProof.\n  assert (cardinality {u : Z | 1 <= u <= p - 1} (Z.to_nat (p - 1 - 1 + 1))).\n  apply card_interval. destruct p_prime; lia.\n  assert (p - 1 - 1 + 1 = p - 1). lia. rewrite H0 in H. auto.\nQed.\nLet U_finite :\n  finite {u : Z | 1 <= u <= p - 1}.\nProof.\n  exists (Z.to_nat (p - 1)). apply card_U.\nQed.\n\nLet P' := product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (fun x => `x).\nLet P'_not_0 :\n  P' mod p <> 0.\nProof.\n  unfold P'. apply product_property_conservation.\n  intros x y Hxnz Hynz. unfold ZpZmult. rewrite Zmod_mod.\n  intro H. apply Zmod_divide in H. apply prime_mult in H.\n  destruct H. apply Zdivide_mod in H. contradiction. apply Zdivide_mod in H. contradiction.\n  auto. destruct p_prime; lia. rewrite Zmod_1_l. lia. destruct p_prime; lia.\n  intro x. destruct x. simpl.  rewrite Zmod_small. lia. lia.\nQed.\nLet P'1 :\n  product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (compose (proj1_sig (P := fun k => 1 <= k <= p - 1)) f') =\n  (ZpZmult p) (product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (fun x => `x))\n              (product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (fun x => a)).\nProof.\n  unfold compose. unfold f'. simpl.\n  rewrite <- product_mul. apply product_ext.\n  intro i. unfold f. unfold ZpZmult. f_equal. apply Zmult_comm.\n  apply one_idemp. auto.\nQed.\nLet P'2 :\n  product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (compose (proj1_sig (P := fun k => 1 <= k <= p - 1)) f') = P'.\nProof.\n  unfold P'. rewrite <- product_bij with (b := f') (HI := U_finite). auto.\n  split. apply f'_injective. apply f'_surjective.\nQed.\nLet P'3 :\n  (product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (fun x => a)) mod p = (a ^ (p - 1)) mod p.\nProof.\n  assert (cardinality {u : Z | 1 <= u <= p - 1} (Z.to_nat (p - 1))).\n  apply card_U.\n  apply inv_bijection in H. destruct H as [b Hb].\n  rewrite (product_bij _ _ _ _ _ _ _ _ _ (Fints_finite (Z.to_nat (p - 1))) b Hb).\n  transitivity (a ^ (Z.of_nat (Z.to_nat (p - 1))) mod p).\n  unfold compose. remember (Z.to_nat (p - 1)) as n.\n  generalize n. simple induction n0.\n  rewrite empty_product. auto.\n  intros n1 H. rewrite product_n. rewrite Nat2Z.inj_succ.\n  unfold ZpZmult. rewrite Zmod_mod. rewrite Zmult_mod. unfold ZpZmult in H.\n  rewrite H. rewrite <- Zmult_mod. f_equal.\n  rewrite pow_succ_r. apply Zmult_comm. apply Nat2Z.is_nonneg.\n  rewrite Z2Nat.id. auto. destruct p_prime; lia.\nQed.\nTheorem FLT :\n  (a ^ (p - 1)) mod p = 1.\nProof.\n  assert (\n  (ZpZmult p) (product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (compose (proj1_sig (P := fun k => 1 <= k <= p - 1)) f')) 1 =\n  (ZpZmult p) P'\n              (product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (fun x => a))).\n  unfold P'. rewrite P'1. symmetry. apply mod_1_mod.\n  rewrite P'2 in H.\n  unfold ZpZmult in H.\n  apply simpl_mod_p in H.\n  fold (ZpZmult p) in H.\n  rewrite P'3 in H. rewrite Zmod_1_l in H. auto.\n  destruct p_prime; lia. auto. apply P'_not_0.\nQed.\nEnd FLT.\nDefinition inverse (p : Z) (a : Z) :=\n  (a ^ (p - 2)) mod p.\nLemma p_inverse :\n  forall p a : Z, prime p -> a mod p <> 0 -> (a * (inverse p a)) mod p = 1.\nProof.\n  intros p a Hprime Hanz.\n  unfold inverse. rewrite Zmult_mod_idemp_r.\n  rewrite <- pow_succ_r by (destruct Hprime; lia).\n  unfold succ. assert (p - 2 + 1 = p - 1). lia. rewrite H. apply FLT.\n  auto. auto.\nQed.\nLemma inv_not_0 :\n  forall p a : Z, prime p -> a mod p <> 0 -> (inverse p a) mod p <> 0.\nProof.\n  intros p a Hprime Hanz H. assert ((a * inverse p a) mod p = 1). apply p_inverse.\n  auto. auto. rewrite Zmult_mod in H0. rewrite H in H0. rewrite Zmult_0_r in H0.\n  rewrite Zmod_0_l in H0. discriminate.\nQed.\nLemma inv_inv :\n  forall p a : Z, prime p -> a mod p <> 0 -> (inverse p (inverse p a)) = a mod p.\nProof.\n  intros p a Hprime Hanz.\n  assert (inverse p (inverse p a) mod p = inverse p (inverse p a)).\n  unfold inverse. apply Zmod_mod. rewrite <- H.\n  assert (inverse p a mod p <> 0). apply inv_not_0. auto. auto.\n  apply simpl_mod_p with (a := (inverse p a)). auto. auto.\n  rewrite p_inverse by auto. rewrite Zmult_comm. rewrite p_inverse by auto. auto.\nQed.\nLemma inv_bounds :\n  forall p a : Z, prime p -> a mod p <> 0 -> 1 <= inverse p a <= p - 1.\nProof.\n  intros. assert (inverse p a <> 0). unfold inverse. rewrite <- Zmod_mod.\n  apply inv_not_0. auto. auto.\n  assert (0 <= inverse p a < p). apply Zmod_pos_bound. destruct H; lia. lia.\nQed.\nLemma inv_mod :\n  forall p a : Z, prime p -> inverse p a = inverse p (a mod p).\nProof.\n  intros. unfold inverse. apply Zpower_mod. destruct H; lia.\nQed.\nLemma inv_prod :\n  forall p a b : Z, prime p -> ((inverse p a) * (inverse p b)) mod p = inverse p (a * b).\nProof.\n  intros. unfold inverse. rewrite <- Zmult_mod.\n  rewrite Zmult_power. auto. destruct H; lia.\nQed.\n\nSection Wilson.\nVariable p : Z.\nHypothesis p_prime : prime p.\nHypothesis p_odd : p mod 2 = 1.\nLet p_not_2 :\n  p <> 2.\nProof.\n  intro. rewrite H in p_odd. rewrite Z_mod_same in p_odd. lia. lia.\nQed.\nLet U_finite :\n  finite {x : Z | 1 <= x <= p - 1}.\nProof.\n  exists (Z.to_nat (p - 1 - 1 + 1)). apply card_interval. destruct p_prime; lia.\nQed.\nTheorem Wilson :\n  product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _ U_finite (fun x => `x)\n    = -1 mod p.\nProof.\n  rewrite product_split with (P := fun x => `x = inverse p `x);\n  [ | (apply one_idemp; auto) | (intros; symmetry; rewrite ZpZmult_comm with (x := 1); apply mod_1_mod) ].\n  assert (1 <= 1 <= p - 1). destruct p_prime; lia.\n  assert (proj1_sig (exist (fun x => 1 <= x <= p - 1) 1 H) =\n      inverse p (proj1_sig (exist (fun x => 1 <= x <= p - 1) 1 H))).\n  simpl. unfold inverse. rewrite one_pow by (destruct p_prime; lia).\n  rewrite Zmod_1_l by (destruct p_prime; lia). auto.\n  assert (1 <= p - 1 <= p - 1). destruct p_prime; lia.\n   assert (proj1_sig (exist (fun x => 1 <= x <= p - 1) (p - 1) H1) =\n      inverse p (proj1_sig (exist (fun x => 1 <= x <= p - 1) (p - 1) H1))).\n  simpl. unfold inverse. transitivity ((-1) ^ (p - 2) mod p).\n  rewrite minus_one_pow_odd. rewrite <- minus_mod. f_equal. lia. lia.\n  apply odd_mod. rewrite Zminus_mod. rewrite Z_mod_same. rewrite p_odd. auto. lia.\n  rewrite Zpower_mod. f_equal. f_equal. rewrite <- minus_mod. f_equal. lia. lia.\n  assert ((0 < 2)%nat). lia. remember (exist (fun x => (x < 2)%nat) (0%nat) H3) as F2Zero.\n  assert ((1 < 2)%nat). lia. remember (exist (fun x => (x < 2)%nat) (1%nat) H4) as F2One.\n  remember (fun a : (Fints 2) =>\n    If a = F2Zero then exist (fun k => `k = inverse p `k) (exist (fun x => 1 <= x <= p - 1) 1 H) H0 else\n                       exist _ (exist (fun x => 1 <= x <= p - 1) (p - 1) H1) H2) as b.\n  assert (bijection b).\n  apply bijection_inversible.\n  exists (fun x => If ``x = 1 then F2Zero else F2One).\n  split. intro a. rewrite Heqb. ex_mid_destruct. ex_mid_destruct. auto.\n  simpl in e. exfalso. assert (p <> 2). apply p_not_2. lia.\n  ex_mid_destruct. simpl in n. lia. simpl in n. destruct a as [a' Ha'].\n  apply proj1_inj. rewrite HeqF2One. simpl. apply proj1_inj_neg in n0.\n  rewrite HeqF2Zero in n0. simpl in n0. lia.\n  intro x. rewrite Heqb. ex_mid_destruct. ex_mid_destruct.\n  apply proj1_inj. simpl. apply proj1_inj. simpl. auto.\n  rewrite HeqF2One in e. rewrite HeqF2Zero in e. discriminate.\n  ex_mid_destruct. contradict n. auto.\n  destruct x as [x' Hx']. destruct x' as [x'' Hx'']. apply proj1_inj. simpl.\n  apply proj1_inj. simpl in *.\n  assert (x'' mod p <> 0). rewrite Zmod_small. lia. lia.\n  assert ((x'' * (inverse p x'') - 1) mod p = 0).\n  rewrite Zminus_mod. rewrite p_inverse. rewrite Zminus_mod_idemp_r.\n  simpl. rewrite Zmod_0_l. auto. auto. auto.\n  rewrite <- Hx' in H6.\n  assert ((x'' - 1) * (x'' + 1) mod p = 0). rewrite <- H6.\n  f_equal. rewrite Zmult_minus_distr_r. repeat (rewrite Zmult_plus_distr_r).\n  lia. apply Zmod_divide in H7. apply prime_mult in H7.\n  destruct H7. apply Zdivide_mod in H7. rewrite Zmod_small in H7. lia.\n  lia. apply Zdivide_mod in H7. assert (((x'' + 1) - 1) mod p = p - 1).\n  rewrite Zminus_mod. rewrite H7. rewrite Zmod_1_l. apply minus_mod.\n  lia. lia. rewrite Zmod_small in H8. lia. lia. auto. lia.\n  rewrite product_bij with (b := b) (HJ := Fints_finite 2) by auto.\n  rewrite product_n. rewrite product_n. rewrite empty_product.\n  unfold compose. rewrite Heqb.\n  rewrite If_l by (unfold Fints_coerce; unfold Fints_last; rewrite HeqF2Zero; apply proj1_inj; auto).\n  rewrite If_r by (rewrite HeqF2Zero; unfold Fints_last; apply proj1_inj_neg; simpl; auto). simpl.\n  rewrite one_idemp by auto.\n  rewrite product_split with (P := fun x => ``x < inverse p ``x);\n  [ | (apply one_idemp; auto) | (intros; symmetry; rewrite ZpZmult_comm with (x := 1); apply mod_1_mod) ].\n  assert (c_ex1 : forall x : {x : Z | 1 <= x <= p - 1},\n    1 <= inverse p `x <= p - 1).\n  intro x. destruct x as [x' Hx'].\n  simpl in *. apply inv_bounds. auto. rewrite Zmod_small. lia. lia.\n  remember (fun x => exist (fun k => 1 <= k <= p - 1) (inverse p `x) (c_ex1 x)) as c1.\n  assert (c_ex2 : forall x : {x : {x : Z | 1 <= x <= p - 1} | `x <> inverse p `x},\n            proj1_sig (c1 `x) <>\n       inverse p (proj1_sig (c1 `x))).\n  rewrite Heqc1.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  simpl in *. rewrite inv_inv. rewrite Zmod_small. auto. lia. auto. rewrite Zmod_small. lia. lia.\n  remember (fun x => exist (fun k => `k <> inverse p `k) (c1 `x) (c_ex2 x)) as c2.\n  assert (c_ex3 : forall x : {x : {x : {x : Z | 1 <= x <= p - 1} | `x <> inverse p `x} |\n        ``x < inverse p ``x},\n    ~ (proj1_sig (proj1_sig (c2 `x)) < inverse p (proj1_sig (proj1_sig (c2 `x))))).\n  rewrite Heqc2. simpl. rewrite Heqc1. simpl.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. destruct x'' as [x''' Hx'''].\n  simpl in *. rewrite inv_inv. rewrite Zmod_small. lia. lia. auto. rewrite Zmod_small. lia. lia.\n  remember (fun x => exist (fun k => ~ ``k < inverse p ``k) (c2 `x) (c_ex3 x)) as c3.\n  assert (bijection c3).\n  apply bijection_inversible.\n  assert (c'_ex : forall x : {x : {x : {x : Z | 1 <= x <= p - 1} | `x <> inverse p `x} |\n     ~ ``x < inverse p ``x},\n    proj1_sig (proj1_sig (c2 `x)) < inverse p (proj1_sig (proj1_sig (c2 `x)))).\n  rewrite Heqc2. simpl. rewrite Heqc1. simpl.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. destruct x'' as [x''' Hx'''].\n  simpl in *. rewrite inv_inv. rewrite Zmod_small. lia. lia. auto. rewrite Zmod_small. lia. lia.\n  remember (fun x => exist (fun k => ``k < inverse p ``k) (c2 `x) (c'_ex x)) as c'.\n  assert (forall x, c2 (c2 x) = x). intro x.\n  destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  rewrite Heqc2. apply proj1_inj. simpl. rewrite Heqc1. apply proj1_inj. simpl.\n  rewrite inv_inv. apply Zmod_small. lia. auto. rewrite Zmod_small. lia. lia.\n  exists c'. split.\n  intro x. rewrite Heqc3. rewrite Heqc'. apply proj1_inj. simpl. auto.\n  intro y. rewrite Heqc3. rewrite Heqc'. apply proj1_inj. simpl. auto.\n  rewrite product_bij with (b := c3) (HJ :=\n    (subtype_finite\n           (subtype_finite U_finite\n              (fun x : {x : Z | 1 <= x <= p - 1} => `x <> inverse p `x))\n           (fun x : {x : {x : Z | 1 <= x <= p - 1} | `x <> inverse p `x} =>\n            ``x < inverse p ``x))) by auto.\n  rewrite <- product_mul by (apply one_idemp; auto).\n  rewrite product_ext with (g := fun x => 1).\n  unfold ZpZmult. rewrite Zmult_1_l. rewrite <- Zmult_1_r with (n := -1).\n  rewrite <- Zmult_mod_idemp_l with (a := -1). f_equal.\n  f_equal. rewrite Zmod_small by lia. rewrite <- minus_mod. auto. lia.\n  apply product_property_conservation. intros. rewrite H7. rewrite H8. apply one_idemp.\n  auto. auto. auto.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. destruct x'' as [x''' Hx'''].\n  simpl in *. unfold compose. rewrite Heqc3. simpl. rewrite Heqc2. simpl.\n  rewrite Heqc1. simpl. unfold ZpZmult. apply p_inverse. auto. rewrite Zmod_small. lia. lia.\nQed.\nEnd Wilson.\n\nDefinition legendre (p a : Z) :=\n  If a mod p = 0 then 0 else\n  If exists y, (y ^ 2) mod p = a mod p then 1 else -1.\n\nLemma pow_0_l :\n  forall n : Z, 0 < n -> 0 ^ n = 0.\nProof.\n  intros n H. rewrite (Zsucc_pred n). rewrite pow_succ_r. lia. lia.\nQed.\n\nSection Eulers_criterion.\nVariable p : Z.\nHypothesis p_prime : prime p.\nHypothesis p_odd : p mod 2 = 1.\nVariable a : Z.\nLet p_not_2 :\n  p <> 2.\nProof.\n  intro. rewrite H in p_odd. rewrite Z_mod_same in p_odd. lia. lia.\nQed.\nLet if_a_0 :\n  a mod p = 0 -> 0 mod p = (a ^ ((p - 1) / 2)) mod p.\nProof.\n  intro H.\n  rewrite Zpower_mod. rewrite H.\n  assert ((p - 1) / 2 >= 2 / 2). apply Z_div_ge. lia. destruct p_prime; lia.\n  rewrite Z_div_same in H0. assert (0 < (p - 1) / 2). lia. rewrite pow_0_l by auto.\n  auto. lia. destruct p_prime; lia.\nQed.\nLet if_a_square :\n  a mod p <> 0 -> (exists y, (y ^ 2) mod p = a mod p) ->\n    1 mod p = (a ^ ((p - 1) / 2)) mod p.\nProof.\n  intros H Hsq. destruct Hsq as [y Hsq].\n  assert (y mod p <> 0). intro Hc. rewrite Zpower_mod in Hsq by (destruct p_prime; lia).\n  rewrite Hc in Hsq. rewrite pow_0_l in Hsq. rewrite Zmod_0_l in Hsq. congruence.\n  lia.\n  rewrite Zpower_mod by (destruct p_prime; lia). rewrite <- Hsq.\n  rewrite <- Zpower_mod by (destruct p_prime; lia).\n  rewrite power_power.\n  symmetry. rewrite Zmod_1_l by (destruct p_prime; lia).\n  assert (2 * ((p - 1) / 2) = p - 1). symmetry. apply Z_div_exact_2. lia.\n  rewrite <- Zminus_mod_idemp_l. rewrite p_odd. auto.\n  rewrite H1. apply FLT. auto. auto. lia. apply Z_div_pos. lia. destruct p_prime; lia.\nQed.\nLet if_a_not_square :\n  a mod p <> 0 -> (forall y, (y * y) mod p <> a mod p) ->\n    -1 mod p = (a ^ ((p - 1) / 2)) mod p.\nProof.\n  intros Hanz Hnotsq.\n  remember (fun x : {x : Z | 1 <= x <= p - 1} => ((inverse p `x) * a) mod p) as f.\n  assert (forall x : {x : Z | 1 <= x <= p - 1}, 1 <= f x <= p - 1).\n  intro x. destruct x as [x' Hx']. rewrite Heqf. simpl.\n  assert (0 <= (inverse p x' * a) mod p < p). apply mod_pos_bound. destruct p_prime; lia.\n  assert ((inverse p x' * a) mod p <> 0). intro H1.\n  apply Zmod_divide in H1. apply prime_mult in H1. destruct H1.\n  apply Zdivide_mod in H0. assert (inverse p x' mod p <> 0).\n  apply inv_not_0. auto. rewrite Zmod_small. lia. lia. contradiction.\n  apply Zdivide_mod in H0. contradiction. auto. destruct p_prime; lia.\n  lia.\n  remember (fun x => exist (fun k => 1 <= k <= p - 1) (f x) (H x)) as f'.\n  assert (forall x, f' (f' x) = x). intro x. rewrite Heqf'. generalize H. rewrite Heqf.\n  intro. apply proj1_inj. simpl. destruct Heqf.\n  rewrite <- inv_mod. rewrite <- inv_prod. rewrite Zmult_mod_idemp_l.\n  rewrite <- Zmult_assoc. rewrite Zmult_mod. rewrite inv_inv. rewrite Zmult_comm with (m := a).\n  rewrite p_inverse. rewrite Zmult_1_r. repeat (rewrite Zmod_mod). destruct x. simpl. rewrite Zmod_small.\n  auto. lia. auto. auto. auto. destruct x. simpl. rewrite Zmod_small. lia. lia. auto. auto.\n  assert (forall x, proj1_sig (f' x) <> `x).\n  intro x. destruct x as [x' Hx']. rewrite Heqf'. simpl. rewrite Heqf. simpl. intro H1.\n  assert ((x' * ((inverse p x' * a) mod p)) mod p = a mod p).\n  rewrite Zmult_mod_idemp_r. rewrite Zmult_assoc. rewrite <- Zmult_mod_idemp_l.\n  rewrite p_inverse. f_equal. lia. auto. rewrite Zmod_small. lia. lia.\n  rewrite H1 in H2. apply (Hnotsq x'). auto.\n  assert (finite {x : Z | 1 <= x <= p - 1}).\n  exists (Z.to_nat (p - 1 - 1 + 1)). apply card_interval. destruct p_prime; lia.\n  assert (product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _ H2 (fun x => `x)\n    = -1 mod p). rewrite <- Wilson with (p_prime := p_prime) (p_odd := p_odd).\n  f_equal. apply proof_irrelevance. auto.\n  rewrite product_split with (P := fun x => proj1_sig (f' x) < `x) in H3;\n  [ | (apply one_idemp; auto) | (intros; symmetry; rewrite ZpZmult_comm with (x := 1); apply mod_1_mod) ].\n  assert (forall x : {x : {x : Z | 1 <= x <= p - 1} | proj1_sig (f' x) < `x},\n    ~ (proj1_sig (f' (f' `x)) < (proj1_sig (f' `x)))).\n  intro x. destruct x as [x' Hx']. rewrite H0. simpl. lia.\n  remember (fun x => exist (fun k => ~ (proj1_sig (f' k) < `k)) (f' `x) (H4 x)) as b.\n  assert (bijection b).\n  apply bijection_inversible.\n  assert (forall x : {x : {x : Z | 1 <= x <= p - 1} | ~ (proj1_sig (f' x) < `x)},\n    proj1_sig (f' (f' `x)) < proj1_sig (f' `x)).\n  intro x. destruct x as [x' Hx']. rewrite H0. simpl.\n  assert (proj1_sig (f' x') <> `x'). apply H1. lia.\n  exists (fun x => exist _ (f' `x) (H5 x)).\n  split. intro x. apply proj1_inj. simpl. rewrite Heqb. simpl. apply H0.\n  intro y. apply proj1_inj. simpl. rewrite Heqb. simpl. apply H0.\n  rewrite product_bij with (b := b) (HJ := (subtype_finite H2\n             (fun x : {x : Z | 1 <= x <= p - 1} => proj1_sig (f' x) < `x))) in H3.\n  rewrite <- product_mul in H3. unfold compose in H3.\n  rewrite Heqb in H3. simpl in H3.\n  rewrite product_ext with (g := fun x => a mod p) in H3.\n  destruct (subtype_finite H2\n          (fun x : {x : Z | 1 <= x <= p - 1} => proj1_sig (f' x) < `x)) as [n Hn].\n  assert (cardinality\n             {x : {x : Z | 1 <= x <= p - 1} | ~ proj1_sig (f' x) < `x} n).\n  apply card_bijection with (b := b). auto. auto.\n  assert (cardinality {x : Z | 1 <= x <= p - 1} (n + n)).\n  apply disjoint_union_cardinality with (P := fun x => proj1_sig (f' x) < `x).\n  auto. auto. assert ((n + n = Z.to_nat (p - 1))%nat).\n  apply cardinality_unique with (T := {x : Z | 1 <= x <= p - 1}).\n  auto. assert (Z.to_nat (p - 1) = Z.to_nat (p - 1 - 1 + 1)).\n  f_equal. lia. rewrite H8. apply card_interval. destruct p_prime; lia.\n  assert (n = Z.to_nat ((p - 1) / 2)).\n  assert (p - 1 = (p - 1) / 2 + (p - 1) / 2).\n  rewrite <- Zmult_1_r. rewrite Zmult_plus_distr_l. rewrite <- Zmult_plus_distr_r.\n  rewrite Zmult_comm. apply Z_div_exact_2. lia. rewrite <- Zminus_mod_idemp_l.\n  rewrite p_odd. rewrite Zmod_0_l. auto.\n  rewrite H9 in H8. rewrite Z2Nat.inj_add in H8. lia.\n  apply Z_div_pos. lia. destruct p_prime; lia. apply Z_div_pos. lia. destruct p_prime; lia.\n  assert (product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1\n       {x : {x : Z | 1 <= x <= p - 1} | proj1_sig (f' x) < `x}\n       (ex_intro\n          (fun n0 : nat =>\n           cardinality {x : {x : Z | 1 <= x <= p - 1} | proj1_sig (f' x) < `x} n0) n\n          Hn)\n       (fun _ : {x : {x : Z | 1 <= x <= p - 1} | proj1_sig (f' x) < `x} => a mod p) =\n    a ^ ((p - 1) / 2) mod p).\n  assert (Hc : cardinality {x : {x : Z | 1 <= x <= p - 1} | proj1_sig (f' x) < `x} n). auto.\n  apply inv_bijection in Hc. destruct Hc as [c Hc].\n  rewrite product_bij with (b := c) (HJ := Fints_finite n) by auto. unfold compose.\n  assert (Z.of_nat n = (p - 1) / 2). rewrite <- Z2Nat.id. f_equal. auto.\n  apply Z_div_pos. lia. destruct p_prime; lia.\n  rewrite <- H10.\n  generalize n. simple induction n0.\n  rewrite empty_product. rewrite Zmod_1_l. auto. destruct p_prime; lia.\n  intros n1 Hr. rewrite product_n. rewrite Hr. rewrite Nat2Z.inj_succ.\n  rewrite Zpower_succ_r. unfold ZpZmult. rewrite <- Zmult_mod. f_equal. apply Zmult_comm.\n  apply Nat2Z.is_nonneg.\n  rewrite <- H10. rewrite H3. f_equal.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  unfold ZpZmult. simpl. rewrite Heqf'. simpl. rewrite Heqf. simpl.\n  rewrite Zmult_mod_idemp_r. rewrite Zmult_assoc.\n  rewrite <- Zmult_mod_idemp_l. rewrite p_inverse. f_equal. lia. auto.\n  rewrite Zmod_small. lia. lia. apply one_idemp. auto. auto.\nQed.\nTheorem Eulers_criterion :\n  (legendre p a) mod p = a ^ ((p - 1) / 2) mod p.\nProof.\n\n  unfold legendre.\n  case_if. auto.\n  case_if. auto.\n  apply if_a_not_square. auto.\n  intro y. contradict n0. exists y.\n  assert (y ^ 2 = y * y).\n  simpl. unfold pow_pos. unfold Pos.iter. rewrite Zmult_assoc. rewrite Zmult_1_r. auto.\n  congruence.\nQed.\nEnd Eulers_criterion.\n\nSection Eisensteins_lemma.\nVariable p : Z.\nHypothesis p_prime : prime p.\nHypothesis p_odd : p mod 2 = 1.\n\nLet p_positive :\n  0 < p.\nProof.\n  destruct p_prime. lia.\nQed.\nLet p_positive_rev :\n  p > 0.\nProof.\n  destruct p_prime. lia.\nQed.\nLet p_not_0 :\n  p <> 0.\nProof.\n  assert (0 < p). apply p_positive. lia.\nQed.\nLet eq_mod_2 :\n  forall x y : Z, (x + y) mod 2 = 0 -> x mod 2 = y mod 2.\nProof.\n  intros x y H. rewrite Zplus_mod in H.\n  destruct (even_or_odd x). assert (x mod 2 = 0). apply even_mod. auto.\n  rewrite H1 in H. rewrite H1. simpl in H. rewrite Zmod_mod in H. auto.\n  assert (x mod 2 = 1). apply odd_mod. auto.\n  rewrite H1 in H. rewrite H1. rewrite Zplus_mod_idemp_r in H.\n  assert (y = 1 + y - 1). lia. rewrite H2. rewrite Zminus_mod.\n  rewrite H. auto.\nQed.\nLet div_mod_mod_2_even :\n  forall a : Z, a mod 2 = 0 -> (a / p) mod 2 = (a mod p) mod 2.\nProof.\n  intros a H.\n  rewrite <- Zmult_1_l with (n := (a / p)).\n  rewrite <- p_odd. rewrite Zmult_mod_idemp_l.\n  apply eq_mod_2. rewrite <- Z_div_mod_eq. auto. auto.\nQed.\nLet div_mod_mod_2_odd :\n  forall a : Z, a mod 2 = 1 -> (a / p) mod 2 = (a mod p + 1) mod 2.\nProof.\n  intros a H.\n  rewrite <- Zmult_1_l with (n := (a / p)).\n  rewrite <- p_odd. rewrite Zmult_mod_idemp_l.\n  apply eq_mod_2. rewrite Zplus_assoc. rewrite <- Z_div_mod_eq.\n  rewrite p_odd. rewrite <- Zplus_mod_idemp_l. rewrite H. auto. auto.\nQed.\n\nVariable q : Z.\nHypothesis q_not_0 : q mod p <> 0.\nHypothesis q_postive : q >= 0.\n\nLet r (u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0}) :=\n    (q * `u) mod p.\nLet r_positive :\n  forall (u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0}), 0 <= r u.\nProof.\n  intro u. assert (0 <= r u < p). unfold r.\n  apply mod_pos_bound with (b := p). apply p_positive. lia.\nQed.\nLet r' (u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0}) :=\n    ((Zpower (-1) (r u)) * (r u)) mod p.\nLet r''_ex (u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0}) :\n  1 <= (r' u) <= p - 1 /\\ (r' u) mod 2 = 0.\nProof with (exact p_not_0 || exact p_positive || auto).\n  split.\n  assert (0 <= r' u < p). unfold r'. apply mod_pos_bound...\n  destruct H.\n  split. assert (r' u <> 0).\n  intro H2. unfold r' in H2. apply Zmod_divide in H2...\n  apply prime_mult in H2... destruct H2.\n  apply prime_divide_pow in H1; [ | apply r_positive | auto].\n  apply Zdivide_opp_r_rev with (b := 1) in H1.\n  apply Zdivide_1 in H1. destruct p_prime. lia.\n  unfold r in H1. apply Zdivide_mod in H1.\n  rewrite <- Zmod_div_mod in H1... 2 : reflexivity.\n  apply Zmod_divide in H1... apply prime_mult in H1...\n  destruct H1. apply Zdivide_mod in H1...\n  assert (0 < `u). destruct u. simpl. lia.\n  assert (0 <> `u). lia.\n  apply Zdivide_bounds in H1... destruct u. simpl in *.\n  destruct p_prime. repeat (rewrite abs_eq in H1; [ | lia]).\n  lia. lia. lia.\n  unfold r'.\n  destruct (even_or_odd (r u)).\n  rewrite minus_one_pow_even; [ | apply r_positive | auto].\n  rewrite mul_1_l. unfold r. rewrite Zmod_mod.\n  apply even_mod. auto.\n  rewrite minus_one_pow_odd; [ | apply r_positive | auto].\n  assert (((p - r u) mod p) mod 2 = 0).\n  assert (0 <= p - r u < p).\n  assert (0 <= r u < p). unfold r. apply mod_pos_bound. apply p_positive.\n  assert (0 <> r u). intro H1. apply Zodd_equiv in H.\n  rewrite <- H1 in H. contradiction.\n  lia. rewrite Zmod_small with (n := p) by auto. apply odd_mod in H.\n  rewrite Zminus_mod. rewrite p_odd. rewrite H. auto.\n  rewrite <- H0. f_equal. rewrite Zminus_mod. f_equal.\n  unfold r. rewrite Zmod_mod. rewrite Z_mod_same; [ | apply p_positive_rev].\n  auto.\nQed.\nLet r'' (u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0}) :=\n   exist (fun k => 1 <= k <= p - 1 /\\ k mod 2 = 0) (r' u) (r''_ex u).\nLet r''_inj1 :\n  forall u1 u2, r' u1 = r' u2 -> Even (r u1) -> Odd (r u2) -> r u1 = r u2.\nProof.\n  intros u1 u2 Heq Hodd Heven.\n  exfalso.\n  unfold r' in Heq.\n  rewrite minus_one_pow_even in Heq; [ | apply r_positive | auto].\n  rewrite mul_1_l in Heq.\n  rewrite minus_one_pow_odd in Heq; [ | apply r_positive | auto].\n  unfold r in Heq.\n  rewrite Zmult_mod_idemp_r in Heq.\n  rewrite Zmult_comm with (n := -1) in Heq.\n  rewrite Zmod_mod in Heq.\n  rewrite <- Zmult_assoc in Heq. rewrite <- opp_eq_mul_m1 in Heq.\n  apply simpl_mod_p in Heq; [ | auto | auto].\n  destruct u1 as [u1' Hu1']. destruct u2 as [u2' Hu2'].\n  assert (u1' mod p = u1'). apply Zmod_small. lia.\n  assert (u2' mod p = u2'). apply Zmod_small. lia.\n  simpl in Heq.\n  rewrite Z_mod_nz_opp_full in Heq by lia.\n  rewrite H in Heq. rewrite H0 in Heq.\n  assert (u1' mod 2 = ((p mod 2) - (u2' mod 2)) mod 2).\n  rewrite <- Zminus_mod. f_equal. auto.\n  destruct Hu1' as [Hu1' Hu1'']. destruct Hu2' as [Hu2' Hu2''].\n  rewrite Hu1'' in H1. rewrite Hu2'' in H1. rewrite p_odd in H1.\n  discriminate.\nQed.\nLet r''_injective :\n  injection r''.\nProof.\n  intros u1 u2 H.\n  unfold r'' in H.\n  apply proj1_inj in H. simpl in H.\n  assert (H0: r' u1 = r' u2). auto.\n  unfold r' in H0.\n  assert (r u1 = r u2).\n  destruct (even_or_odd (r u1)).\n    rewrite minus_one_pow_even in H0; [ | apply r_positive | auto].\n    rewrite mul_1_l in H0.\n    destruct (even_or_odd (r u2)).\n      rewrite minus_one_pow_even in H0; [ | apply r_positive | auto].\n      rewrite mul_1_l in H0.\n      unfold r in H0.\n      repeat (rewrite Zmod_mod in H0). unfold r. auto.\n   (* Odd (r u2) *)\n     apply r''_inj1. auto. auto. auto.\n  (* Odd (r u1) *)\n    rewrite minus_one_pow_odd in H0; [ | apply r_positive | auto].\n    destruct (even_or_odd (r u2)).\n      symmetry. apply r''_inj1. auto. auto. auto.\n   (* Odd (r u1) *)\n      rewrite minus_one_pow_odd in H0; [ | apply r_positive | auto].\n      apply simpl_mod_p in H0; [ | auto | ].\n      unfold r in H0. repeat (rewrite Zmod_mod in H0). unfold r. auto.\n      intro H3. apply Zmod_divide in H3. apply Zdivide_opp_r in H3.\n      simpl in H3. apply Zdivide_mod in H3. rewrite Zmod_1_l in H3.\n      discriminate. destruct p_prime. auto. apply p_not_0.\n  unfold r in H1.\n  apply simpl_mod_p in H1; [ | auto | auto].\n  destruct u1 as [u1' Hu1']. destruct u2 as [u2' Hu2'].\n  assert (u1' mod p = u1'). apply Zmod_small. lia.\n  assert (u2' mod p = u2'). apply Zmod_small. lia.\n  apply proj1_inj. simpl in *. congruence.\nQed.\nLet r''_surjective :\n  surjection r''.\nProof with (exact p_not_0 || exact p_positive ||\n     exact p_positive_rev || auto).\n  intro y. destruct y as [y' Hy']. destruct Hy' as [Hy'1 Hy'2].\n  cut (exists x, r' x = y'). intro H. destruct H as [x Hx]. exists x.\n  unfold r''. apply proj1_inj. auto.\n  assert (exists a : Z, (q * a) mod p = y').\n  destruct (not_0_inversible_mod_p q p p_prime q_not_0) as [b Hb].\n  exists (y' * b). rewrite Zmult_comm. rewrite <- Zmult_assoc.\n  rewrite <- Zmult_mod_idemp_r. rewrite Hb. rewrite Zmult_1_r.\n  apply Zmod_small. lia.\n  destruct H as [a Ha].\n  destruct (even_or_odd (a mod p)).\n    assert (1 <= a mod p <= p - 1 /\\ (a mod p) mod 2 = 0).\n    split. assert (0 <= a mod p < p). apply mod_pos_bound...\n    assert (a mod p <> 0). intro H1. rewrite <- Zmult_mod_idemp_r in Ha.\n    rewrite H1 in Ha. rewrite mul_0_r in Ha. rewrite Zmod_0_l in Ha.\n    lia. lia. apply even_mod. auto.\n    exists (exist _ (a mod p) H0).\n    unfold r'. unfold r. simpl.\n    repeat (rewrite Zmult_mod_idemp_r). rewrite Ha.\n    rewrite minus_one_pow_even; [ | lia | auto]. rewrite mul_1_l.\n    rewrite Zmult_mod_idemp_r. auto. apply even_mod. auto.\n  (* Odd (a mod p) *)\n    assert (1 <= p - a mod p <= p - 1 /\\ (p - a mod p) mod 2 = 0).\n    split. assert (0 <= a mod p < p). apply mod_pos_bound...\n    assert (a mod p <> 0). intro H1. rewrite H1 in H. rewrite odd_mod in H.\n    discriminate. lia. rewrite odd_mod in H.\n    rewrite Zminus_mod. rewrite H. rewrite p_odd. auto.\n    exists (exist _ (p - a mod p) H0).\n    unfold r'. unfold r. simpl.\n    repeat (rewrite Zmult_mod_idemp_r).\n    repeat (rewrite Zmult_minus_distr_l with (p := q)).\n    assert (((q * p - q * (a mod p)) mod p) = p - y').\n    rewrite Zminus_mod. rewrite Zmult_mod. rewrite Z_mod_same...\n    rewrite mul_0_r. rewrite Zmod_0_l. rewrite Zmult_mod_idemp_r.\n    rewrite Ha. rewrite <- Z_mod_same with (a := p)... rewrite Zminus_mod_idemp_l.\n    apply Zmod_small. lia. rewrite <- Zmult_mod_idemp_r. repeat (rewrite H1).\n    assert (Odd (p - y')).\n    apply odd_mod. rewrite Zminus_mod. rewrite p_odd. rewrite Hy'2. auto.\n    rewrite minus_one_pow_odd. assert (-1 * (p - y') = y' + -1 * p). lia.\n    rewrite H3. rewrite Z_mod_plus_full. apply Zmod_small. lia. lia. auto.\nQed.\n\nLet card_R :\n  cardinality {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} (Z.to_nat ((p - 1) / 2)).\nProof.\n  assert (forall u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0}, (Z.to_nat ((`u - 1) / 2) < Z.to_nat ((p - 1) / 2))%nat).\n  intro u. destruct u as [u' Hu']. destruct Hu' as [Hu'1 Hu'2]. simpl.\n  apply Nat2Z.inj_lt.\n  repeat (rewrite Z2Nat.id by (apply Z_div_pos; destruct p_prime; lia)).\n  apply Zdiv_lt_upper_bound. lia. rewrite Zmult_comm.\n  rewrite <- Z_div_exact_full_2. lia. lia. rewrite Zminus_mod.\n  rewrite p_odd. auto.\n  exists (fun u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} =>\n      (exist _ (Z.to_nat ((`u - 1) / 2)) (H u))).\n  apply bijection_inversible.\n  assert (forall n : {k : nat | (k < Z.to_nat ((p - 1) / 2))%nat},\n    1 <= 2 + 2 * (Z.of_nat `n) <= p - 1 /\\ (2 + 2 * (Z.of_nat `n)) mod 2 = 0).\n  intro n. destruct n as [n' Hn']. unfold proj1_sig. split.\n  assert (0 <= Z.of_nat n'). apply Nat2Z.is_nonneg.\n  assert (Z.of_nat (S n') <= Z.of_nat (Z.to_nat ((p - 1) / 2))). apply Nat2Z.inj_le. auto.\n  rewrite Z2Nat.id in H1. apply Zmult_le_compat_l with (p := 2) in H1.\n  rewrite <- Z_div_exact_full_2 in H1. rewrite Nat2Z.inj_succ in H1.\n  lia. lia. rewrite Zminus_mod. rewrite p_odd. auto. lia.\n  apply Z_div_pos. lia. destruct p_prime; lia.\n  rewrite Zmult_comm. rewrite Z_mod_plus_full. auto.\n  exists (fun n : {k : nat | (k < Z.to_nat ((p - 1) / 2))%nat} =>\n           exist _ (2 + 2 * (Z.of_nat `n)) (H0 n)).\n  unfold proj1_sig. split.\n  intro u. destruct u as [u' Hu']. destruct Hu' as [Hu' Hu''].\n  apply proj1_inj. unfold proj1_sig.\n  rewrite Z2Nat.id. assert (u' - 1 = 2 * ((u' - 1) / 2) + ((u' - 1) mod 2)).\n  apply Z_div_mod_eq. lia. assert ((u' - 1) mod 2 = 1).\n  rewrite Zminus_mod. rewrite Hu''. auto. lia. apply Z_div_pos. lia.\n  lia.\n  intro y. destruct y as [y' Hy'].\n  apply proj1_inj. unfold proj1_sig.\n  assert (2 + 2 * Z.of_nat y' - 1 = 1 + of_nat y' * 2). lia.\n  rewrite H1. rewrite Z_div_plus_full. simpl. apply Nat2Z.id. lia.\nQed.\n\nLet R_finite :\n  finite {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0}.\nProof.\n  exists (Z.to_nat ((p - 1) / 2)). apply card_R.\nQed.\n\nLet mlt := ZpZmult p.\nLet mlt_comm := ZpZmult_comm p.\nLet mlt_assoc := ZpZmult_assoc p.\nLet one_id := one_idemp p p_prime.\n\nLet P := product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun x => `x).\nLet P_not_0 :\n  P mod p <> 0.\nProof.\n  unfold P. apply product_property_conservation.\n  intros x y Hxnz Hynz. unfold mlt. unfold ZpZmult. rewrite Zmod_mod.\n  intro H. apply Zmod_divide in H. apply prime_mult in H.\n  destruct H. apply Zdivide_mod in H. contradiction. apply Zdivide_mod in H. contradiction.\n  auto. apply p_not_0. rewrite Zmod_1_l. lia. destruct p_prime. lia.\n  intro x. destruct x. simpl.  rewrite Zmod_small. lia. lia.\nQed.\nLet P1 :\n  product Z mlt mlt_comm mlt_assoc 1 _ R_finite r =\n    mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun x => q)) P.\nProof.\n  unfold P.\n  rewrite <- product_mul. apply product_ext.\n  unfold mlt. unfold ZpZmult. unfold r. auto.\n  apply one_id.\nQed.\nLet P2 :\n  product Z mlt mlt_comm mlt_assoc 1 _ R_finite r' =\n    mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u)))\n        (product Z mlt mlt_comm mlt_assoc 1 _ R_finite r).\nProof.\n  rewrite <- product_mul. apply product_ext.\n  unfold mlt. unfold ZpZmult. unfold r'. auto.\n  apply one_id.\nQed.\nLet P3 :\n  product Z mlt mlt_comm mlt_assoc 1 _ R_finite r' = P.\nProof.\n  transitivity (product Z mlt mlt_comm mlt_assoc 1 _ R_finite\n    (compose (proj1_sig (P := (fun u => 1 <= u <= p - 1 /\\ u mod 2 = 0))) r'')).\n  apply product_ext. unfold compose. unfold r''. simpl. auto.\n  unfold P.\n  rewrite <- product_bij with (HI := R_finite).\n  apply product_ext. auto.\n  split. apply r''_injective. apply r''_surjective.\nQed.\nLet P4 :\n  mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u)))\n      (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u)))\n    = 1.\nProof.\n  rewrite <- product_mul. apply product_property_conservation.\n  intros. rewrite H. rewrite H0. apply one_id. auto.\n  unfold mlt. unfold ZpZmult. intro x. rewrite <- Zmult_power. simpl.\n  rewrite one_pow. rewrite Zmod_1_l. auto. destruct p_prime; lia.\n  apply r_positive. apply r_positive. apply one_id.\nQed.\nLet P5 :\n  mlt P ((product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u)))) =\n    mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite r) 1.\nProof.\n  assert (mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite r) 1 =\n          mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite r)\n                   (mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u)))\n                        (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u))))).\n  rewrite P4. auto.\n  rewrite H. rewrite <- P3. rewrite P2.\n  remember (product Z mlt mlt_comm mlt_assoc 1\n        {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} R_finite\n        (fun u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} => (-1) ^ r u)) as a.\n  remember (product Z mlt mlt_comm mlt_assoc 1\n     {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} R_finite r) as b.\n  rewrite mlt_comm. rewrite mlt_assoc. rewrite mlt_comm. auto.\nQed.\nLet P6 :\n  mlt P (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u))) =\n  mlt P (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => q)).\nProof.\n  assert (mlt P ((product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u)))) =\n    mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite r) 1).\n  apply P5.\n  rewrite P1 in H. rewrite <- (mod_1_mod p) in H. rewrite H. apply mlt_comm.\nQed.\nLet P7 :\n  (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u))) mod p =\n  (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => q)) mod p.\nProof.\n  apply simpl_mod_p with (a := P). auto. apply P_not_0.\n  apply P6.\nQed.\nLet P8 :\n  (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u))) =\n  (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ ((q * `u) / p))).\nProof.\n  apply product_ext. intro i. apply minus_one_pow_mod_2.\n  apply r_positive. apply Z_div_pos. apply p_positive_rev.\n  destruct i as [i' Hi']. simpl. rewrite <- Zmult_0_l with (n := i').\n  apply Zmult_le_compat_r. lia. lia.\n  unfold r.\n  destruct i as [i' Hi']. destruct Hi' as [Hi' Hi'']. simpl.\n  assert (q * i' = p * (q * i' / p) + (q * i') mod p).\n  apply Z_div_mod_eq. apply p_positive_rev.\n  assert ((q * i' + (q * i') mod p) mod 2 = (p * (q * i' / p) + 2 * ((q * i') mod p)) mod 2).\n  f_equal. lia.\n  rewrite Zplus_mod in H0. rewrite Zmult_mod in H0.\n  rewrite Hi'' in H0. rewrite Zmult_0_r in H0. rewrite Zmod_0_l in H0.\n  rewrite Zplus_0_l in H0. rewrite Zmod_mod in H0.\n  rewrite Zplus_mod in H0. rewrite Zmult_mod with (n := 2) in H0.\n  rewrite p_odd in H0. rewrite Zmult_1_l in H0. rewrite Zmod_mod in H0.\n  rewrite Zmult_mod with (n := 2) in H0. rewrite Z_mod_same in H0 by lia.\n  rewrite Zmult_0_l in H0. rewrite Zmod_0_l in H0. rewrite Zplus_0_r in H0.\n  rewrite Zmod_mod in H0. auto.\nQed.\nLet P9 :\n  (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ ((q * `u) / p))) mod p =\n  (m1_pow (product Z Zplus Zplus_comm Zplus_assoc 0 _ R_finite (fun u => (q * `u) / p))) mod p.\nProof.\n  transitivity ((product Z mlt mlt_comm mlt_assoc 1\n    {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} R_finite\n    (fun u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} => m1_pow (q * `u / p))) mod p).\n  f_equal.\n  apply product_ext. intro i. apply m1_pow_compatible.\n  apply Zge_iff_le. apply Z_div_pos. apply p_positive_rev.\n  destruct i as [i' Hi']. simpl. rewrite <- Zmult_0_l with (n := i').\n  apply Zmult_le_compat_r. lia. lia.\n  rewrite product_morph with (morph := fun x => (m1_pow x) mod p)\n                             (multS := mlt) (multS_com := mlt_comm)\n                             (multS_assoc := mlt_assoc) (eS := 1).\n  unfold compose.\n  apply product_morph with (morph := fun x => x mod p)\n                           (multS := mlt) (multS_com := mlt_comm)\n                           (multS_assoc := mlt_assoc) (eS := 1).\n  intros. unfold mlt. unfold ZpZmult. rewrite Zmod_mod. rewrite <- Zmult_mod. auto.\n  apply Zmod_1_l. destruct p_prime; lia.\n  intros. unfold mlt. unfold ZpZmult. rewrite <- Zmult_mod. f_equal. apply m1_pow_morphism.\n  unfold m1_pow. simpl. apply Zmod_1_l. destruct p_prime; lia.\nQed.\nLet P10 :\n  (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => q)) mod p =\n    (q ^ ((p - 1) / 2)) mod p.\nProof.\n  assert (cardinality {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} (Z.to_nat ((p - 1) / 2))).\n  apply card_R.\n  apply inv_bijection in H. destruct H as [b Hb].\n  rewrite (product_bij _ _ _ _ _ _ _ _ _ (Fints_finite (Z.to_nat ((p - 1) / 2))) b Hb).\n  unfold compose.\n  transitivity (q ^ (Z.of_nat (Z.to_nat ((p - 1) / 2))) mod p).\n  remember (to_nat ((p - 1) / 2)) as n.\n  generalize n. simple induction n0.\n  rewrite empty_product. simpl. auto.\n  intros n1 H. rewrite Nat2Z.inj_succ. rewrite product_n. unfold mlt. unfold ZpZmult.\n  rewrite Zmod_mod. fold (ZpZmult p). rewrite <- Zmult_mod_idemp_l. fold mlt. rewrite H.\n  rewrite Zmult_mod_idemp_l. f_equal. rewrite pow_succ_r. rewrite Zmult_comm.\n  auto. apply Nat2Z.is_nonneg.\n  rewrite Z2Nat.id. auto. apply Z_div_pos. lia. destruct p_prime; lia.\nQed.\nLet Eisensteins_lemma_mod_p :\n  (legendre p q) mod p = (m1_pow (product Z Zplus Zplus_comm Zplus_assoc 0 _ R_finite (fun u => (q * `u) / p))) mod p.\nProof.\n  rewrite Eulers_criterion by auto. rewrite <- P10. rewrite <- P7. rewrite P8. apply P9.\nQed.\nLet p_not_2 :\n  p <> 2.\nProof.\n intro H. rewrite H in p_odd. rewrite Z_mod_same in p_odd by lia. discriminate.\nQed.\nLemma Eisensteins_lemma1 :\n  legendre p q = m1_pow (product Z Zplus Zplus_comm Zplus_assoc 0 _ R_finite (fun u => (q * `u) / p)).\nProof.\n  assert ((legendre p q + 1) mod p = (m1_pow (product Z Zplus Zplus_comm Zplus_assoc 0 _ R_finite (fun u => (q * `u) / p)) + 1) mod p).\n  rewrite Zplus_mod. rewrite Eisensteins_lemma_mod_p. rewrite <- Zplus_mod. auto.\n  rewrite Zmod_small in H; [ | (destruct p_prime; unfold legendre; case_if; case_if; lia; lia)].\n  rewrite Zmod_small in H; [ | (destruct p_prime;\n    destruct (m1_pow_1_or_m1 (product Z add add_comm add_assoc 0\n     {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} R_finite\n     (fun u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} => q * `u / p))); lia; lia)].\n  lia.\nQed.\nLet U_finite :\n  finite {u : Z | 1 <= u <= (p - 1) / 2}.\nProof.\n  exists (Z.to_nat ((p - 1) / 2 - 1 + 1)). apply card_interval.\n  apply Zmult_le_reg_r with (p := 2). lia.\n  rewrite Zmult_comm with (n := (p - 1) / 2). rewrite <- Z_div_exact_full_2.\n  destruct p_prime; lia. lia. rewrite <- Zminus_mod_idemp_l. rewrite p_odd. auto.\nQed.\nHypothesis q_odd : q mod 2 = 1.\nHypothesis q_prime : prime q.\nLet E1 :\n  (product Z Zplus Zplus_comm Zplus_assoc 0 _ R_finite (fun u => (q * `u) / p)) mod 2 =\n  (product Z Zplus Zplus_comm Zplus_assoc 0 _ U_finite (fun u => (q * `u) / p)) mod 2.\nProof.\n  rewrite product_split with (P := fun u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} => `u <= (p - 1) / 2) by (intros; lia).\n  rewrite product_split with (P := fun u : {u : Z | 1 <= u <= (p - 1) / 2} => `u mod 2 = 0) by (intros; lia).\n  rewrite Zplus_mod.\n  rewrite Zplus_mod with (a := product _ _ _ _ _ {x : {u : Z | 1 <= u <= (p - 1) / 2} | `x mod 2 = 0} _ _).\n  f_equal. f_equal. f_equal.\n  assert (b_ex1 : forall x : {x : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} | `x <= (p - 1) / 2},\n    1 <= ``x <= (p - 1) / 2). intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  simpl in *. lia.\n  remember (fun x => exist (fun k => 1 <= k <= (p - 1) / 2) ``x (b_ex1 x)) as b1.\n  assert (b_ex2 : forall x, (proj1_sig (b1 x)) mod 2 = 0).\n  intro x. rewrite Heqb1. simpl. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. simpl in *. destruct Hx''. auto.\n  remember (fun x => exist (fun k => `k mod 2 = 0) (b1 x) (b_ex2 x)) as b2.\n  assert (Hb : bijection b2).\n  apply bijection_inversible.\n  assert (b'_ex1 : forall x : {x : {x : Z | 1 <= x <= (p - 1) / 2} | `x mod 2 = 0},\n    1 <= ``x <= p - 1 /\\ ``x mod 2 = 0). intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  simpl in *. split. assert ((p - 1) / 2 < p - 1). apply Z_div_lt. lia. destruct p_prime; lia.\n  lia. auto.\n  remember (fun x => exist (fun k => 1 <= k <= p - 1 /\\ k mod 2 = 0) ``x (b'_ex1 x)) as b'1.\n  assert (b'_ex2 : forall x, proj1_sig (b'1 x) <= (p - 1) / 2). intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  simpl in *. rewrite Heqb'1. simpl. lia.\n  remember (fun x => exist (fun k => `k <= (p - 1) / 2) (b'1 x) (b'_ex2 x)) as b'2.\n  exists b'2. split.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  rewrite Heqb2. rewrite Heqb'2. apply proj1_inj. simpl.\n  rewrite Heqb'1. apply proj1_inj. simpl. rewrite Heqb1. simpl. auto.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  rewrite Heqb2. rewrite Heqb'2. apply proj1_inj. simpl.\n  rewrite Heqb1. apply proj1_inj. simpl. rewrite Heqb'1. simpl. auto.\n  rewrite product_bij with (b := b2) (HJ := (subtype_finite R_finite\n     (fun u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} => `u <= (p - 1) / 2))).\n  unfold compose. rewrite Heqb2. simpl. rewrite Heqb1. simpl. auto. auto.\n  apply eq_mod_2.\n  assert (p - 1 = (p - 1) / 2 + (p - 1) / 2).\n  rewrite <- Zmult_1_r. rewrite Zmult_plus_distr_l. rewrite <- Zmult_plus_distr_r.\n  rewrite Zmult_comm. apply Z_div_exact_2. lia. rewrite <- Zminus_mod_idemp_l.\n  rewrite p_odd. rewrite Zmod_0_l. auto.\n  assert (c_ex1 : forall x : {x : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} | ~ `x <= (p - 1) / 2},\n    1 <= (p - ``x) <= (p - 1) / 2).\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  simpl in *. lia.\n  remember (fun x => exist (fun k => 1 <= k <= (p - 1) / 2) (p - ``x) (c_ex1 x)) as c1.\n  assert (c_ex2 : forall x, ~ (proj1_sig (c1 x) mod 2 = 0)).\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. simpl in *.\n  rewrite Heqc1. simpl. rewrite Zminus_mod. auto. rewrite p_odd.\n  destruct Hx'' as [Hx''1 Hx''2]. rewrite Hx''2. intro. discriminate.\n  remember (fun x => exist (fun k => ~ `k mod 2 = 0) (c1 x) (c_ex2 x)) as c2.\n  assert (Hc : bijection c2). apply bijection_inversible.\n  assert (c'_ex1 : forall x : {x : {x : Z | 1 <= x <= (p - 1) / 2} | `x mod 2 <> 0},\n    1 <= p - ``x <= p - 1 /\\ (p - ``x) mod 2 = 0).\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. simpl in *.\n  split. lia. rewrite Zminus_mod. rewrite p_odd.\n  assert (x'' mod 2 = 1). assert (0 <= x'' mod 2 < 2). apply mod_pos_bound. lia. lia.\n  rewrite H0. auto.\n  remember (fun x => exist (fun k => 1 <= k <= p - 1 /\\ k mod 2 = 0) (p - ``x) (c'_ex1 x)) as c'1.\n  assert (c'_ex2 : forall x, ~ proj1_sig (c'1 x) <= (p - 1) / 2).\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. simpl in *.\n  rewrite Heqc'1. simpl. lia.\n  remember (fun x => exist (fun k => ~ `k <= (p - 1) / 2) (c'1 x) (c'_ex2 x)) as c'2.\n  exists c'2. split.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  rewrite Heqc'2. apply proj1_inj. simpl. rewrite Heqc'1. apply proj1_inj. simpl.\n  rewrite Heqc2. simpl. rewrite Heqc1. simpl. lia.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  rewrite Heqc2. apply proj1_inj. simpl. rewrite Heqc1. apply proj1_inj. simpl.\n  rewrite Heqc'2. simpl. rewrite Heqc'1. simpl. lia.\n  rewrite product_bij with (b := c2) (HJ := (subtype_finite R_finite\n      (fun x : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} =>\n       ~ `x <= (p - 1) / 2))) by auto.\n  rewrite <- product_mul by auto. unfold compose.\n  rewrite Heqc2. simpl. rewrite Heqc1. simpl.\n  apply product_property_conservation.\n  intros x y H1 H2. rewrite Zplus_mod. rewrite H1. rewrite H2. auto. auto.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. simpl in *.\n  rewrite Zplus_mod.\n  rewrite div_mod_mod_2_even. rewrite div_mod_mod_2_odd.\n  rewrite <- Zplus_mod. rewrite Zmult_minus_distr_l.\n  rewrite Zminus_mod. rewrite Zmult_mod with (b := p).\n  rewrite Z_mod_same. rewrite Zmult_0_r. rewrite Zmod_0_l.\n  assert ((0 - (q * x'') mod p) = -((q * x'') mod p)). lia. rewrite H0.\n  rewrite minus_mod.\n  assert ((q * x'') mod p + (p - (q * x'') mod p + 1) = p + 1). lia. rewrite H1.\n  rewrite <- Zplus_mod_idemp_l. rewrite p_odd. auto.\n  assert (0 <= (q * x'') mod p < p). apply mod_pos_bound. auto.\n  assert ((q * x'') mod p <> 0). intro H2.\n  apply Zmod_divide in H2. apply prime_mult in H2. destruct H2.\n  apply Zdivide_mod in H2. contradiction.\n  apply Zdivide_mod in H2. rewrite Zmod_small in H2. lia. lia. auto. auto.\n  lia. auto. rewrite Zmult_mod.\n  rewrite q_odd. rewrite Zminus_mod. rewrite p_odd.\n  destruct Hx'' as [Hx''1 Hx''2]. rewrite Hx''2. auto.\n  rewrite Zmult_mod. destruct Hx'' as [Hx''1 Hx''2]. rewrite Hx''2. rewrite Zmult_0_r. auto.\nQed.\nDefinition EL := (product Z Zplus Zplus_comm Zplus_assoc 0 _ U_finite (fun u => (q * `u) / p)).\nLemma EL1 :\n  0 <= EL.\nProof.\n  unfold EL. apply product_property_conservation. intros. lia. lia.\n  intro x. destruct x as [x' Hx']. simpl.\n  apply Z_div_pos. lia. rewrite <- Zmult_0_l with (n := x').\n  apply Zmult_le_compat_r. lia. lia.\nQed.\nLemma EL2 :\n  legendre p q = m1_pow EL.\nProof.\n  rewrite Eisensteins_lemma1. unfold EL. unfold m1_pow.\n  rewrite E1. auto.\nQed.\nLemma EL3 :\n  cardinality {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2\n                                                     /\\ p * snd s <= q * fst s}\n   (Z.to_nat EL).\nProof.\n  unfold EL.\n  assert (Z.to_nat\n     (product Z Zplus Zplus_comm Zplus_assoc 0 {u : Z | 1 <= u <= (p - 1) / 2}\n        U_finite (fun u : {u : Z | 1 <= u <= (p - 1) / 2} => q * `u / p)) =\n      product nat plus plus_comm plus_assoc O {u : Z | 1 <= u <= (p - 1) / 2}\n        U_finite (fun u : {u : Z | 1 <= u <= (p - 1) / 2} => Z.to_nat (q * `u / p))).\n  rewrite <- Nat2Z.id. f_equal.\n  transitivity (product Z add add_comm add_assoc 0 {u : Z | 1 <= u <= (p - 1) / 2} U_finite\n    (fun u : {u : Z | 1 <= u <= (p - 1) / 2} => Z.of_nat (Z.to_nat (q * `u / p)))).\n  apply product_ext. intro i. rewrite Z2Nat.id. auto. destruct i as [i' Hi'].\n  simpl. apply Z_div_pos. lia. rewrite <- Zmult_0_r with (n := q).\n  apply Zmult_le_compat_l. lia. destruct q_prime; lia.\n  symmetry. apply product_morph. intros x y. apply Nat2Z.inj_add. auto.\n  rewrite H.\n  assert (f_ex : forall s : {s : Z * Z |\n    1 <= fst s <= (p - 1) / 2 /\\\n    1 <= snd s <= (q - 1) / 2 /\\ p * snd s <= q * fst s},\n   1 <= fst `s <= (p - 1) / 2).\n  intro s. destruct s as [s' Hs']. simpl. destruct Hs'. auto.\n  apply disjoint_union_cardinality_sum with\n   (f := fun s => exist (fun k => 1 <= k <= (p - 1) / 2) (fst `s) (f_ex s)).\n  intro k. destruct k as [k' Hk']. simpl.\n  assert (b_ex : forall s : {x : {s : Z * Z |\n      1 <= fst s <= (p - 1) / 2 /\\\n      1 <= snd s <= (q - 1) / 2 /\\ p * snd s <= q * fst s} |\n    exist (fun k : Z => 1 <= k <= (p - 1) / 2) (fst `x) (f_ex x) =\n    exist (fun k : Z => 1 <= k <= (p - 1) / 2) k' Hk'},\n      1 <= snd ``s <= (q * k') / p).\n  intro s. destruct s as [s' Hs']. destruct s' as [s'' Hs'']. simpl in *.\n  apply proj1_inj in Hs'. simpl in Hs'. rewrite Hs' in Hs''.\n  destruct Hs'' as [Hs''1 Hs''2]. destruct Hs''2 as [Hs''2 Hs''3].\n  split. lia. apply Zdiv_le_lower_bound. auto. rewrite Zmult_comm. auto.\n  remember (fun s => exist (fun k => 1 <= k <= (q * k' / p)) (snd ``s) (b_ex s)) as b.\n  assert (Hb : bijection b).\n  apply bijection_inversible.\n  assert (b'_ex1 : forall x : {k : Z | 1 <= k <= q * k' / p},\n    (1 <= fst (k', `x) <= (p - 1) / 2 /\\ (1 <= snd (k', `x) <= (q - 1) / 2\n                                      /\\ p * snd (k', `x) <= q * fst (k', `x)))).\n  intro x. simpl. destruct x as [x' Hx']. simpl.\n  split. lia. split. split. lia.\n  rewrite over_2 by auto. transitivity (q * k' / p). lia.\n  transitivity (q * ((p - 1) / 2) / p).\n  apply Z_div_le. auto. apply Zmult_le_compat_l. lia. lia.\n  rewrite over_2 by auto. apply Zdiv_le_lower_bound. lia.\n  transitivity ((q * (p / 2) * 2) / p).\n  rewrite Zmult_comm. rewrite Zmult_comm with (m := 2).\n  apply Zdiv_mult_le. rewrite <- Zmult_0_r with (n := q).\n  apply Zmult_le_compat_l. apply Z_div_pos. lia. lia. lia. lia. lia.\n  transitivity (q * p / p). apply Z_div_le. lia. rewrite <- Zmult_assoc.\n  apply Zmult_le_compat_l. rewrite Zmult_comm. apply Z_mult_div_ge. lia. lia.\n  rewrite Z_div_mult. lia. lia.\n  transitivity (p * ((q * k') / p)). apply Zmult_le_compat_l. lia. lia.\n  apply Z_mult_div_ge. lia.\n  remember (fun x => exist (fun s =>\n    1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2 /\\ p * snd s <= q * fst s\n  ) (k', `x) (b'_ex1 x)) as b'1.\n  assert (b'_ex2 : forall x,\n    exist (fun k : Z => 1 <= k <= (p - 1) / 2) (fst (proj1_sig (b'1 x))) (f_ex (b'1 x)) =\n    exist (fun k : Z => 1 <= k <= (p - 1) / 2) k' Hk').\n  intro x. apply proj1_inj. simpl. rewrite Heqb'1. simpl. auto.\n  exists (fun x => exist _ (b'1 x) (b'_ex2 x)).\n  split.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  apply proj1_inj. simpl. rewrite Heqb'1. apply proj1_inj. simpl in *.\n  rewrite Heqb. simpl. apply proj1_inj in Hx'. simpl in Hx'. rewrite <- Hx'.\n  symmetry. apply surjective_pairing.\n  intro y. destruct y as [y' Hy']. rewrite Heqb. apply proj1_inj. simpl.\n  rewrite Heqb'1. simpl. auto.\n  apply card_bijection with (b := b). auto.\n  assert (Z.to_nat (q * k' / p) = Z.to_nat (q * k' / p - 1 + 1)). f_equal. lia.\n  rewrite H0. apply card_interval_full.\n  assert (0 <= q * k' / p). apply Z_div_pos. lia.\n  rewrite <- Zmult_0_l with (n := k'). apply Zmult_le_compat_r.\n  lia. lia. lia.\nQed.\n\nEnd Eisensteins_lemma.\n\nSection Quadratic_reciprocity.\nVariable p : Z.\nVariable q : Z.\nHypothesis p_prime : prime p.\nHypothesis q_prime : prime q.\nHypothesis p_odd : p mod 2 = 1.\nHypothesis q_odd : q mod 2 = 1.\nHypothesis p_not_q : p <> q.\nLet p_ge_1 :\n  p > 1.\nProof.\n  destruct p_prime; lia.\nQed.\nLet q_ge_1 :\n  q > 1.\nProof.\n  destruct q_prime; lia.\nQed.\nLet p_not_2 :\n  p <> 2.\nProof.\n  intro H. rewrite H in p_odd. discriminate.\nQed.\nLet q_not_2 :\n  q <> 2.\nProof.\n  intro H. rewrite H in q_odd. discriminate.\nQed.\nLet p2_pos :\n  (p - 1) / 2 > 0.\nProof.\n  assert (1 <= (p - 1) / 2). apply Zdiv_le_lower_bound. lia. lia. lia.\nQed.\nLet q2_pos :\n  (q - 1) / 2 > 0.\nProof.\n  assert (1 <= (q - 1) / 2). apply Zdiv_le_lower_bound. lia. lia. lia.\nQed.\nLet p_mod_q_not_0 :\n  p mod q <> 0.\nProof.\n  intro H. apply Zmod_divide in H. contradict p_not_q. symmetry. apply prime_div_prime.\n  auto. auto. auto. lia.\nQed.\nLet q_mod_p_not_0 :\n  q mod p <> 0.\nProof.\n  intro H. apply Zmod_divide in H. contradict p_not_q. apply prime_div_prime.\n  auto. auto. auto. lia.\nQed.\nLet a := EL p p_prime p_odd q.\nLet b := EL q q_prime q_odd p.\nLet QR1 :\n  cardinality {s : {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2} |\n                                                     p * snd `s <= q * fst `s}\n   (Z.to_nat a).\nProof.\n  apply card_and with (Q := fun s => p * snd s <= q * fst s).\n  apply card_subtype with (Q := fun s =>\n    1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2 /\\ p * snd s <= q * fst s).\n  intro x. tauto.\n  unfold a.\n  apply EL3. lia. auto. auto.\nQed.\nLet QR2 :\n  cardinality {s : {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2} |\n                                                     ~ (p * snd `s <= q * fst `s)}\n   (Z.to_nat b).\nProof.\n  assert (forall s : {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2},\n    ~ p * snd `s <= q * fst `s <-> q * fst `s <= p * snd `s).\n  intro s. split.\n  intro H. lia.\n  intro H.\n  assert (q * fst `s <> p * snd `s). intro H0.\n  assert (p | q * fst `s). exists (snd `s). rewrite Zmult_comm with (m := p). auto.\n  apply prime_mult in H1. destruct H1. apply Zdivide_mod in H1.\n  apply q_mod_p_not_0 in H1. auto. apply Zdivide_mod in H1. rewrite Zmod_small in H1.\n  destruct s as [s' Hs']. simpl in H1.\n  lia. destruct s as [s' Hs']. simpl. destruct Hs' as [Hs'1 Hs'2].\n  assert ((p - 1) / 2 < p - 1). apply Z_div_lt. lia. lia. lia. auto. lia.\n  apply card_subtype with (Q := fun s => q * fst `s <= p * snd `s).\n  auto.\n  apply card_and with (Q := fun s => q * fst s <= p * snd s).\n  apply card_subtype with (Q := fun s =>\n    1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2 /\\ q * fst s <= p * snd s).\n  intro x. tauto.\n  assert (forall s : {x : Z * Z |\n    1 <= fst x <= (p - 1) / 2 /\\ 1 <= snd x <= (q - 1) / 2 /\\ q * fst x <= p * snd x},\n   1 <= fst (snd `s, fst `s) <= (q - 1) / 2 /\\ 1 <= snd (snd `s, fst `s) <= (p - 1) / 2 /\\\n   q * snd (snd `s, fst `s) <= p * fst (snd `s, fst `s)).\n  simpl. destruct s. simpl. tauto.\n  remember (fun s : {x : Z * Z |\n           1 <= fst x <= (p - 1) / 2 /\\\n           1 <= snd x <= (q - 1) / 2 /\\ q * fst x <= p * snd x} =>\n  exist (fun s =>\n    1 <= snd s <= (p - 1) / 2 /\\ 1 <= fst s <= (q - 1) / 2 /\\ q * snd s <= p * fst s\n  ) (snd `s, fst `s) (proj2_sig s)) as f.\n  apply card_bijection with (b := f).\n  rewrite Heqf.\n  apply sub_bijection with\n   (P := fun s => 1 <= snd s <= (p - 1) / 2 /\\ 1 <= fst s <= (q - 1) / 2 /\\ q * snd s <= p * fst s)\n   (b := fun s => (snd s, fst s)).\n  apply bijection_inversible. exists (fun s => (snd s, fst s)).\n  simpl. split. intro x. symmetry. apply surjective_pairing.\n  intro y. symmetry. apply surjective_pairing.\n  apply card_subtype with (Q := fun s =>\n    1 <= fst s <= (q - 1) / 2 /\\ 1 <= snd s <= (p - 1) / 2 /\\ q * snd s <= p * fst s).\n  tauto.\n  unfold b. apply EL3. lia. auto. auto.\nQed.\nLet QR3 :\n  cardinality {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2}\n  (Z.to_nat a + Z.to_nat b).\nProof.\n  apply disjoint_union_cardinality with (P := fun s => p * snd `s <= q * fst `s).\n  apply QR1. apply QR2.\nQed.\nLet QR4 :\n  cardinality {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2}\n  (Z.to_nat (((p - 1) / 2) * ((q - 1) / 2))).\nProof.\n  assert (forall s : {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2},\n    1 <= fst `s + ((p - 1) / 2) * (snd `s - 1) <= ((p - 1) / 2) * ((q - 1) / 2)).\n  intro s. destruct s as [s' Hs']. destruct Hs' as [Hs'1 Hs'2].\n  simpl. split.\n  transitivity (fst s' + ((p - 1) / 2) * (1 - 1)). lia.\n  apply Zplus_le_compat_l. apply Zmult_le_compat_l. lia.\n  apply Z_div_pos. lia. lia.\n  transitivity (fst s' + (p - 1) / 2 * ((q - 1) / 2 - 1)).\n  apply Zplus_le_compat_l. apply Zmult_le_compat_l. lia.\n  apply Z_div_pos. lia. lia.\n  transitivity ((p - 1) / 2 + (p - 1) / 2 * ((q - 1) / 2 - 1)).\n  lia. rewrite Zmult_minus_distr_l. lia.\n  apply card_bijection with (b := fun s =>\n    exist (fun x => 1 <= x <= ((p - 1) / 2) * ((q - 1) / 2))\n          (fst `s + ((p - 1) / 2) * (snd `s - 1)) (H s)).\n  apply bijection_inversible.\n\n  assert (forall x : {x : Z | 1 <= x <= ((p - 1) / 2) * ((q - 1) / 2)},\n    1 <= fst ((`x - 1) mod ((p - 1) / 2) + 1, (`x - 1) / ((p - 1) / 2) + 1) <= (p - 1) / 2 /\\\n    1 <= snd ((`x - 1) mod ((p - 1) / 2) + 1, (`x - 1) / ((p - 1) / 2) + 1) <= (q - 1) / 2).\n  intro x. destruct x as [x' Hx']. simpl.\n  split. assert (0 <= (x' - 1) mod ((p - 1) / 2) < (p - 1) / 2).\n  apply mod_pos_bound. lia. lia.\n  assert (0 <= (x' -1) / ((p - 1) / 2)). apply Z_div_pos. lia. lia.\n  assert ((x' - 1) / ((p - 1) / 2) < (q - 1) / 2). apply Zdiv_lt_upper_bound.\n  lia. rewrite Zmult_comm. lia. lia.\n  exists (fun x => exist _\n    ((`x - 1) mod ((p - 1) / 2) + 1, (`x - 1) / ((p - 1) / 2) + 1) (H0 x)).\n  simpl.\n  split.\n  intro s. destruct s as [s' Hs']. apply proj1_inj. simpl.\n  rewrite Zminus_mod. rewrite Zmult_comm. rewrite Z_mod_plus_full.\n  rewrite <- Zminus_mod. rewrite Zmod_small by lia.\n  assert (fst s' + (snd s' - 1) * ((p - 1) / 2) - 1 = fst s' - 1 + (snd s' - 1) * ((p - 1) / 2)).\n  lia. rewrite H1. rewrite Z_div_plus_full by lia. rewrite Zdiv_small by lia.\n  transitivity (fst s', snd s'). f_equal. lia. lia. symmetry. apply surjective_pairing.\n  intro x. destruct x as [x' Hx']. apply proj1_inj. simpl.\n  assert ((x' - 1) / ((p - 1) / 2) + 1 - 1 = (x' - 1) / ((p - 1) / 2)). lia.\n  rewrite H1.\n  assert ((x' - 1) mod ((p - 1) / 2) + 1 +\n    (p - 1) / 2 * ((x' - 1) / ((p - 1) / 2)) =\n          (p - 1) / 2 * ((x' - 1) / ((p - 1) / 2)) + (x' - 1) mod ((p - 1) / 2) + 1).\n  lia. rewrite H2.\n  rewrite <- Z_div_mod_eq. lia. lia.\n  assert (Z.to_nat ((p - 1) / 2 * ((q - 1) / 2)) = Z.to_nat ((p - 1) / 2 * ((q - 1) / 2) - 1 + 1)).\n  f_equal. lia. rewrite H0. apply card_interval_full.\n  assert (0 * ((q - 1) / 2) <= (p - 1) / 2 * ((q - 1) / 2)). apply Zmult_le_compat_r.\n  lia. lia. lia.\nQed.\nLet QR5 :\n  (Z.to_nat a + Z.to_nat b)%nat = (Z.to_nat (((p - 1) / 2) * ((q - 1) / 2))).\nProof.\n  apply cardinality_unique with\n   (T := {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2}).\n  auto. auto.\nQed.\nLet QR6 :\n  a + b = ((p - 1) / 2) * ((q - 1) / 2).\nProof.\n  assert (0 <= a). apply EL1. lia. assert (0 <= b). apply EL1. lia.\n  rewrite <- Z2Nat.id. rewrite <- Z2Nat.id with (n := a + b). f_equal.\n  rewrite Z2Nat.inj_add. apply QR5. auto. auto.\n  generalize H H0. generalize a b. intros. lia.\n  rewrite <- Zmult_0_r with (n := (p - 1) / 2).\n  apply Zmult_le_compat_l. lia. lia.\nQed.\nTheorem Quadratic_reciprocity :\n  (legendre p q) * (legendre q p) = (-1) ^ (((p - 1) / 2) * ((q - 1) / 2)).\nProof.\n  rewrite EL2 with (p_prime := p_prime) (p_odd := p_odd) by (lia || auto).\n  rewrite EL2 with (p_prime := q_prime) (p_odd := q_odd) by (lia || auto).\n  rewrite m1_pow_compatible. rewrite <- m1_pow_morphism.\n  f_equal. rewrite <- QR6. unfold a. unfold b. auto.\n  rewrite <- Zmult_0_r with (n := (p - 1) / 2).\n  apply Zmult_ge_compat_l. lia. lia.\nQed.\nEnd Quadratic_reciprocity.\n", "meta": {"author": "Ekdohibs", "repo": "coq-proofs", "sha": "4d5a1ca5927f8dc20017dd548e734ca384bca861", "save_path": "github-repos/coq/Ekdohibs-coq-proofs", "path": "github-repos/coq/Ekdohibs-coq-proofs/coq-proofs-4d5a1ca5927f8dc20017dd548e734ca384bca861/Reciprocity/Reciprocity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6988598572965822}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp\nRequire Import ssrfun ssrbool eqtype ssrnat seq choice fintype.\n\n(* finType *)\n\nCheck bool.\nFail Goal #| bool | == 2.\n\nCheck bool_finType.\nGoal #| bool_finType | == 2.\nrewrite cardT.\nrewrite enumT.\nrewrite unlock.\nsimpl Finite.mixin_enum.\nsimpl.\napply/eqP.\nreflexivity.\nQed.\n\nGoal [forall b : bool, (b == true) || (b == false)].\napply/forallP.\ncase.\nsimpl.\ndone.\nsimpl.\ndone.\nQed.\n\n(* finType registration *)\n\nInductive myunit : Set :=\n| mytt.\n\nFail Lemma myunit_enumP : Finite.axiom [:: mytt].\nSet Printing All.\nFail Lemma myunit_enumP : Finite.axiom [:: mytt].\nUnset Printing All.\n\nDefinition myunit_eq (a b : myunit) := true.\n\nLemma myunit_eqP : Equality.axiom myunit_eq.\nProof.\nunfold Equality.axiom.\ncase.\ncase.\napply: (iffP idP).\ndone.\ndone.\nQed.\n\nDefinition myunit_eqMixin := EqMixin myunit_eqP.\nCanonical myunit_eqType := EqType myunit myunit_eqMixin.\n\nCheck (mytt == mytt).\n\nLemma myunit_enumP : Finite.axiom [:: mytt].\nProof.\nunfold Finite.axiom.\ncase.\nsimpl.\nrewrite addn0.\nreflexivity.\nQed.\n\nFail Definition myunit_finMixin := FinMixin myunit_enumP.\nSet Printing All.\nFail Definition myunit_finMixin := FinMixin myunit_enumP.\nUnset Printing All.\n\nLemma bool_of_myunitK : cancel (fun _ : myunit => true) (fun _ : bool => mytt).\nProof.\nunfold cancel.\ncase.\nreflexivity.\nQed.\n\nDefinition myunit_choiceMixin := CanChoiceMixin bool_of_myunitK.\nCanonical myunit_choiceType := ChoiceType myunit myunit_choiceMixin.\n\nDefinition myunit_countMixin := CanCountMixin bool_of_myunitK.\nCanonical myunit_countType := CountType myunit myunit_countMixin.\n\nDefinition myunit_finMixin := FinMixin myunit_enumP.\nCanonical myunit_finType := FinType myunit myunit_finMixin.\n\nLemma card_myunit : #| myunit_finType | = 1.\nProof.\nrewrite cardT.\nrewrite enumT.\nrewrite unlock.\nsimpl.\nreflexivity.\nQed.\n\nCheck [forall x : myunit, x == x].\n", "meta": {"author": "affeldt", "repo": "ssrcoq-chiba2017", "sha": "0c5b1723367901b9bb3462de0de5769da527054c", "save_path": "github-repos/coq/affeldt-ssrcoq-chiba2017", "path": "github-repos/coq/affeldt-ssrcoq-chiba2017/ssrcoq-chiba2017-0c5b1723367901b9bb3462de0de5769da527054c/fintype_overview.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.6988598544137757}}
{"text": "\n(**** Sets with an equivalence relation. ****)\n\nDefinition binary_relation A := A -> A -> Prop.\n\nDefinition reflexive_relation A (R : binary_relation A) := forall x, R x x.\n\nDefinition symmetric_relation A (R : binary_relation A) := forall x y, R x y -> R y x.\n\nDefinition transitive_relation A (R : binary_relation A) :=\n  forall x y z, R x y -> R y z -> R x z.\n\nDefinition equivalence_relation A (R : binary_relation A) :=\n     reflexive_relation A R /\\\n     symmetric_relation A R /\\\n     transitive_relation A R.\n\nStructure higher_order_eqset (he_set : Type) :=\n  mk_higher_order_eqset {\n     he_eq : binary_relation he_set ;\n     he_equivalence : equivalence_relation he_set he_eq\n  }.\n\nStructure eqset := mk_eqset {\n     e_set : Type ;\n     e_hoeqset : higher_order_eqset e_set\n  }.\n\nDefinition mk_eqset_0 (e_set : Type)\n                      (e_eq : binary_relation e_set)\n                      (e_equivalence : equivalence_relation e_set e_eq)\n  := mk_eqset\n       e_set \n       (mk_higher_order_eqset\n          e_set\n          e_eq\n          e_equivalence).\n\nDefinition e_eq A : binary_relation (e_set A) :=\n  he_eq (e_set A) (e_hoeqset A).\n\nDefinition e_equivalence A : equivalence_relation (e_set A) (e_eq A) :=\n  he_equivalence (e_set A) (e_hoeqset A).\n\nNotation \"a == b\" := (e_eq _ a b) (at level 45).\n\nLemma e_reflexive : forall A (x : e_set A), x == x.\nProof.\n  intros A x.\n  assert (reflexive_relation (e_set A) (e_eq A)).\n  apply e_equivalence.\n  apply H.\nQed.\n\nLemma e_symmetric : forall A (x y : e_set A), x == y -> y == x.\nProof.\n  intros A x y x_eq_y.\n  assert (symmetric_relation (e_set A) (e_eq A)).\n  apply e_equivalence.\n  apply H.\n  assumption.\nQed.\n\nLemma e_transitive : forall A (x y z : e_set A), x == y -> y == z -> x == z.\nProof.\n  intros A x y z x_eq_y y_eq_z.\n  assert (transitive_relation (e_set A) (e_eq A)).\n  apply e_equivalence.\n  apply H with y.\n  assumption.\n  assumption.\nQed.\n\nDefinition e_function_set (A B : eqset) : Type := \n  { f : e_set A -> e_set B |\n      forall x y, x == y -> f x == f y }.\n\nDefinition e_function_eq A B (f g : e_function_set A B) : Prop :=\n  forall x, e_eq B (proj1_sig f x) (proj1_sig g x).\n\nLemma e_function_eq_equivalence A B :\n          equivalence_relation (e_function_set A B) (e_function_eq A B).\nProof.\n  assert (equivalence_relation (e_set B) (e_eq B)) as eqB_equivalence.\n    apply e_equivalence.\n  destruct eqB_equivalence as (refl, (sym, trans)).\n  unfold equivalence_relation.\n  split.\n    (* refl *)\n    unfold reflexive_relation.\n    unfold e_function_eq. \n    intros.\n    apply refl.\n  split.\n    (* sym *)\n    unfold symmetric_relation.\n    unfold e_function_eq.\n    intros f g H x.\n    apply sym.\n    specialize H with x.\n    assumption.\n    (* trans *)\n    unfold transitive_relation.\n    unfold e_function_eq.\n    intros f g h Hfg Hgh x.\n    apply trans with (proj1_sig g x).\n    specialize Hfg with x.\n    assumption.\n    specialize Hgh with x.\n    assumption.\nQed.\n\nDefinition e_function (A B : eqset) : eqset :=\n  mk_eqset_0 (e_function_set A B)\n             (e_function_eq A B)\n             (e_function_eq_equivalence A B).\n\nNotation \"A ==> B\" := (e_function A B) (at level 35, right associativity).\n\nDefinition e_apply A B (f : e_set (A ==> B)) (x : e_set A) :=\n  proj1_sig f x.\n\nNotation \"f $ x\" := (e_apply _ _ f x) (at level 35).\n\nLemma eq_equivalence : forall A, equivalence_relation A eq.\nProof.\n  intros.\n  unfold equivalence_relation.\n  split.\n    (* refl *)\n    unfold reflexive_relation.\n    intros.\n    apply eq_refl.\n  split.\n    (* sym *)\n    unfold symmetric_relation.\n    intros.\n    apply eq_sym.\n    assumption.\n    (* trans *)\n    intros x y z.\n    intros.\n    apply eq_trans with y.\n    assumption.\n    assumption.\nQed.\n\nDefinition e_lift (A : Type) : eqset := mk_eqset_0 A eq (eq_equivalence A).\n\nDefinition e_lift_function A B (f : A -> B) : e_set (e_lift A ==> e_lift B).\n  simpl.\n  unfold e_function_set.\n  exists f.\n  intros x y x_eq_y.\n  compute.\n  compute in x_eq_y.\n  apply f_equal.\n  assumption.\nDefined.\n\nLemma iff_equivalence : equivalence_relation Prop iff.\nProof.\n  unfold equivalence_relation. \n  split.\n  unfold reflexive_relation. apply iff_refl.\n  split.\n  unfold symmetric_relation. apply iff_sym.\n  unfold transitive_relation. apply iff_trans.\nQed.\n\nDefinition e_Prop := mk_eqset_0 Prop iff iff_equivalence.\n\nDefinition e_subset_set A (P : e_set (A ==> e_Prop)) := {x | (P $ x)}.\n\nDefinition e_subset_eq A P (x y : e_subset_set A P) : Prop :=\n  e_eq A (proj1_sig x) (proj1_sig y).\n\nLemma e_subset_eq_equivalence A P :\n  equivalence_relation (e_subset_set A P) (e_subset_eq A P).\nProof.\n  assert (equivalence_relation (e_set A) (e_eq A)) as eq_equivalence.\n    apply e_equivalence.\n  unfold equivalence_relation in eq_equivalence.\n  destruct eq_equivalence as (refl, (sym, trans)).\n  unfold equivalence_relation. \n  split.\n    (* refl *) \n    unfold reflexive_relation.\n    intros.\n    apply refl.\n  split.\n    (* sym *) \n    unfold symmetric_relation.\n    intros.\n    apply sym.\n    assumption.\n    (* trans *) \n    unfold transitive_relation.\n    intros x y z.\n    intros.\n    unfold e_subset_eq.\n    apply trans with (proj1_sig y).\n    assumption.\n    assumption.\nQed.\n\nDefinition e_mk_subset A (P : e_set (A ==> e_Prop)) : eqset :=\n  mk_eqset_0 (e_subset_set A P)\n             (e_subset_eq A P)\n             (e_subset_eq_equivalence A P).\n\nDefinition e_binary_relation A := A ==> A ==> e_Prop.\n\nDefinition e_apply_binary_relation A :\n             e_set (e_binary_relation A) -> binary_relation (e_set A) :=\n  fun R x y => R $ x $ y.\n\nDefinition e_equivalence_relation A (R : e_set (e_binary_relation A)) :=\n  equivalence_relation (e_set A) (e_apply_binary_relation A R).\n\nDefinition e_mk_quotient A Eq (Eq_equivalence : e_equivalence_relation A Eq) :=\n  mk_eqset_0 (e_set A) (e_apply_binary_relation A Eq) Eq_equivalence.\n\nDefinition removal_function A (x : e_set A) : e_set (A ==> e_Prop).\n  simpl.\n  unfold e_function_set.\n  exists (fun y => ~(x == y)).\n  intros x1 y x1_eq_y.\n  split.\n    (* -> *)\n    intros H1 H2.\n    assert (x == x1).\n    apply e_transitive with y. \n    assumption.\n    apply e_symmetric; assumption.\n    contradiction.\n    (* <- *)\n    intros H1 H2.\n    assert (x == y).\n    apply e_transitive with x1. \n    assumption.\n    assumption.\n    contradiction.\nDefined.\n\nDefinition eqset_remove A (x : e_set A) := e_mk_subset A (removal_function A x).", "meta": {"author": "foones", "repo": "dharma", "sha": "bea2a54256082c9349e267caae318d20e79cf8b6", "save_path": "github-repos/coq/foones-dharma", "path": "github-repos/coq/foones-dharma/dharma-bea2a54256082c9349e267caae318d20e79cf8b6/coq/math1/Eqset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.7905303087996142, "lm_q1q2_score": 0.6988598512200583}}
{"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.\nRequire Import Maps.\nRequire Import SfLib.\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  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  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\nPrint beq_nat.\nPrint eq_nat_dec.\n\nDefinition beq_nat_bydec (a b :nat) : bool :=\n  match (eq_nat_dec a b) with\n    | left _ => true\n    | right _ => false\n  end.\n\nPrint le_dec.\n\nDefinition leb_bydec (a b :nat) : bool :=\n  match le_dec a b with\n    | left _ => true\n    | right _ => false\n  end.\n\n  Fixpoint beval (b:bexp): bool :=\n    match b with\n      | BTrue => true\n      | BFalse => false\n      | BEq a1 a2 => beq_nat_bydec (aeval a1) (aeval a2)\n      | Ble a1 a2 => leb_bydec (aeval a1) (aeval a2)\n      | BNot b => negb (beval b)\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 => 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  Theorem optimize_0plus_sound:\n    forall a,\n      aeval a = aeval (optimize_0plus a).\n  Abort.\n\n  Module AEVALR_FIRST_TRY.\n\n    Reserved Notation \"e '\\\\' n\" (at level 50, left associativity).\n    Inductive aevalR : aexp -> nat -> Prop :=\n    | E_ANum :\n        forall n:nat, (ANum n) \\\\ n\n    | E_APlus : forall (e1 e2:aexp) (n1 n2:nat),\n                  (e1 \\\\ n1) -> (e2 \\\\ n2) -> (APlus e1 e2) \\\\ (n1 + n2)\n    | E_AMinus : forall (e1 e2:aexp) (n1 n2:nat),\n                   (e1 \\\\ n1) -> (e2 \\\\ n2) -> (AMinus e1 e2) \\\\ (n1 - n2)\n    | E_AMult : forall (e1 e2:aexp) (n1 n2:nat),\n                  (e1 \\\\ n1) -> (e2 \\\\ n2) -> (AMult e1 e2) \\\\ (n1 * n2)\n    where \"e '\\\\' n\" := (aevalR e n): type_scope.\n\n\n    Theorem aeval_iff_aevalR :\n      forall a n,\n        (a \\\\ n) <-> aeval a = n.\n      split. intros.\n      elim H; try auto; simpl;\n      repeat (intros; rewrite H1; rewrite H3; auto).\n      generalize n. clear n.\n      elim a; simpl; try auto.\n      intros. rewrite H; apply E_ANum.\n      intros. rewrite <- H1. apply E_APlus; auto.\n      intros. rewrite <- H1; apply E_AMinus; auto.\n      intros. rewrite <- H1; apply E_AMult; auto.\n    Qed.\n\n\n    End AEVALR_FIRST_TRY.\n\nEnd AExp.\n\nRequire Export Maps.\n\nDefinition state := total_map nat.\n\nDefinition empty_state : state :=\n  t_empty 0.\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\n\nDefinition X:id := Id 0.\nDefinition Y:id := Id 1.\nDefinition Z:id := Id 2.\n\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\n\nDefinition beq_nat_bydec (a b :nat) : bool :=\n  match (eq_nat_dec a b) with\n    | left _ => true\n    | right _ => false\n  end.\n\nPrint le_dec.\n\nDefinition leb_bydec (a b :nat) : bool :=\n  match le_dec a b with\n    | left _ => true\n    | right _ => false\n  end.\n\n\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\nFixpoint beval (st:state) (b:bexp) : bool :=\n  match b with\n    | BTrue => true\n    | BFalse => false\n    | BEq a1 a2 => beq_nat_bydec (aeval st a1) (aeval st a2)\n    | BLe a1 a2 => leb_bydec (aeval st a1) (aeval st a2)\n    | BNot b1 => negb (beval st b1)\n    | BAnd b1 b2 => andb (beval st b1) (beval st b2)\n  end.\n\nInductive com: Type :=\n| CSkip : com\n| CAss : id -> aexp -> com\n| CSeq : com -> com -> com\n| CIf : bexp -> com -> com -> com\n| CWhile : bexp -> com -> com.\n\nNotation \"'SKIP'\" := CSkip.\nNotation \"x '::=' c\" := (CAss x c) (at level 60).\nNotation \"c1 ;; c2\" := (CSeq c1 c2) (at level 80, right associativity).\nNotation \"'WHILE' b 'DO' c 'END'\" := (CWhile b c) (at level 80, right associativity).\nNotation \"'IFB' c1 'THEN' c2 'ELSE' c3 'FI'\" := (CIf c1 c2 c3)(at level 80, right associativity).\n\nFixpoint ceval_fun_no_while(st: state) (c:com) :state :=\n  match c with\n    | SKIP =>\n      st\n    | x ::= a1 =>\n      t_update 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\n  end.\n\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,\n             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 b c1 c2 st st',\n               (beval st b = true) ->\n               c1 / st \\\\ st' ->\n               (IFB b THEN c1 ELSE c2 FI) / st \\\\ st'\n| E_IfFalse :\n    forall b c1 c2 st st',\n      (beval st b = false) ->\n      c2 / st \\\\ st' ->\n      (IFB b THEN c1 ELSE c2 FI) / st \\\\ st'\n| E_WhileLoop :\n    forall b c st st' st'',\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| E_WhileEnd :\n    forall b c st,\n      (beval st b = false) ->\n      (WHILE b DO c END) / st \\\\ st\nwhere \"c1 '/' st '\\\\' st'\" := (ceval c1 st st').\n\nHint Resolve E_WhileLoop E_WhileEnd E_IfFalse E_IfTrue E_Seq E_Ass E_Skip : ceval_base.\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) / empty_state \\\\ (t_update (t_update empty_state X 2) Z 4).\nProof.\n  eapply E_Seq. eapply E_Ass. simpl; trivial.\n  simpl. eapply E_IfFalse; simpl. unfold t_update. rewrite eq_id_dec_id.\n  compute. trivial.\n  eapply E_Ass. simpl. trivial.\nQed.\n\nTheorem ceval_determinstic:\n  forall c st st1 st2,\n    c / st \\\\ st1 ->\n    c / st \\\\ st2 ->\n    st1 = st2.\n  intros. generalize st2 H0. clear H0 st2.\n  elim H;  try (eauto with ceval_base).\n  intros. inversion H0; trivial.\n  intros. inversion H1. rewrite H0 in H6. rewrite H6; trivial.\n  intros. inversion H4. pose(H1 st'0 H7). apply H3. rewrite e. auto.\n  intros. inversion H3.  exact(H2 st2 H10). rewrite H9 in H0. inversion H0.\n  intros. inversion H3.  rewrite H9 in H0. inversion H0.\n  apply H2. auto.\n  intros. inversion H5. pose (H2 _ H9). rewrite <- e in H12. apply H4. auto.\n  rewrite H9 in H0. rewrite H10 in H0. inversion H0.\n  intros. inversion H1. rewrite H4 in H0; inversion H0. trivial.\nQed.\n\n(*\nTheorem plus2_spec :\n  forall st n st',\n    st X = n ->\n    plus2 / st \\\\ st' ->\n    st' X = n + 2.*)\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\nTheorem plus2_spec :\n  forall st n st',\n    st X = n ->\n    plus2 / st \\\\ st' ->\n    st' X = n + 2.\n  intros. unfold plus2 in H0. inversion H0. rewrite <- H5.\n  simpl. rewrite H. unfold t_update. apply eq_id_dec_id.\nQed.\n\n\nTheorem XtimesYinZ_spec :\n  forall st n m st',\n    st X = n ->\n    st Y = m ->\n    XtimesYinZ / st \\\\ st' ->\n    st' Z = m * n.\n  unfold XtimesYinZ. intros.\n  inversion H1. rewrite <- H6 in H5. unfold t_update. rewrite eq_id_dec_id.\n  rewrite <- H6. simpl. rewrite H; rewrite H0. rewrite mult_comm. trivial.\nQed.\n\n\nTheorem loop_never_stops:\n  forall c st st',\n    c=loop -> ~(loop / st \\\\ st').\n  unfold loop. unfold not. intros.\n  generalize H. elim H0; rewrite H; intros; try discriminate.\n  auto. inversion H2. rewrite <- H4 in H1. simpl in H1; discriminate.\nQed.\n\n\nFixpoint no_whiles (c:com) : bool :=\n  match c with\n    | SKIP =>\n      true\n    | _ ::= _ =>\n      true\n    | c1 ;; c2 =>\n      andb (no_whiles c1) (no_whiles c2)\n    | IFB _ THEN c1 ELSE c2 FI =>\n      andb (no_whiles c1) (no_whiles c2)\n    | WHILE _ DO _ END  =>\n      false\n  end.\n\nInductive no_whilesR : com -> Prop :=\n| skip_nw : no_whilesR SKIP\n| ass_nw : forall a b, no_whilesR (a ::= b)\n| seq_nw : forall c1 c2, no_whilesR c1 -> no_whilesR c2 -> no_whilesR (c1 ;; c2)\n| if_nw : forall b c1 c2, no_whilesR c1 -> no_whilesR c2 -> no_whilesR (IFB b THEN c1 ELSE c2 FI).\n\nTheorem no_whiles_eqv :\n  forall c, no_whiles c = true <-> no_whilesR c.\n  split.\n  elim c; intros; try discriminate.\n  apply skip_nw. apply ass_nw. simpl in H1.\n  remember (no_whiles c0) as h1; remember (no_whiles c1) as h2.\n  generalize Heqh1 Heqh2; clear Heqh1 Heqh2.\n  case (no_whiles c0); case (no_whiles c1); intros hh hhh; try (rewrite hh in H1; rewrite hhh in H1; simpl in H1; inversion H1).\n  apply seq_nw; auto.\n  simpl in H1. remember (no_whiles c0) as h1; remember (no_whiles c1) as h2.\n  generalize Heqh1 Heqh2; clear Heqh1 Heqh2.\n  case (no_whiles c0); case (no_whiles c1); intros hh hhh; try (rewrite hh in H1; rewrite hhh in H1; simpl in H1; inversion H1).\n  apply if_nw; auto.\n  intros. elim H; intros; simpl; try auto.\n  rewrite H1; rewrite H3; try auto.\n  rewrite H1; rewrite H3; try auto.\nQed.\n\nPrint ex.\n\nTheorem no_whiles_terminating:\n  forall k, no_whilesR k -> forall st, exists st', k / st \\\\ st'.\n  intros k h.\n  elim h; intros.\n  exists st; apply E_Skip.\n  exists (t_update st a (aeval st b)). apply E_Ass. trivial.\n  pose (H0 st). inversion e. pose (H2 x). inversion e0.\n  exists x0. eapply E_Seq; eauto.\n  pose (H0 st). inversion e. pose (H2 st). inversion e0.\n  remember (beval st b) as c. generalize Heqc. clear Heqc.\n  case c; intros; [exists x; eapply E_IfTrue| exists x0; eapply E_IfFalse]; eauto.\nQed.\n\nInductive sinstr : Type :=\n| SPush : nat -> sinstr\n| SLoad : id -> sinstr\n| SPlus : sinstr\n| SMinus : sinstr\n| SMult : sinstr.\n\n\nFixpoint s_execute (st : state)\n         (stack : list nat)\n         (prog : list sinstr) {struct prog} : list nat :=\n  match prog with\n    | nil => stack\n    | SPush x :: fol => s_execute st (x :: stack) fol\n    | SLoad a :: fol => s_execute st ((st a) :: stack) fol\n    | SPlus :: fol =>\n      match stack with\n        | x1::x2::newstack => s_execute st ((x1 + x2)::newstack) fol\n        | _ => s_execute st stack fol\n      end\n    | SMinus :: fol =>\n      match stack with\n        | x1::x2::newstack => s_execute st ((x2-x1)::newstack) fol\n        | _ => s_execute st stack fol\n      end\n    | SMult :: fol =>\n      match stack with\n        | x1 :: x2 :: newstack => s_execute st ((x1*x2)::newstack) fol\n        | _ => s_execute st stack fol\n      end\n  end.\n\nExample s_execute1:\n  s_execute empty_state []\n            [SPush 5; SPush 3; SPush 1; SMinus]\n  = [2;5]. auto.\nQed.\n\n\nExample s_execute2:\n  s_execute (t_update empty_state X 3) [3;4]\n            [SPush 4; SLoad X; SMult; SPlus]\n  = [15;4].\nsimpl. unfold t_update. rewrite eq_id_dec_id. auto.\nQed.\n\n\n\nFixpoint s_compile (e:aexp) : list sinstr :=\n  match e with\n    | ANum x => SPush x :: nil\n    | AId i => SLoad i :: nil\n    | APlus a b => (s_compile a) ++ (s_compile b) ++  SPlus :: nil\n    | AMinus a b => (s_compile a) ++ (s_compile b) ++ SMinus :: nil\n    | AMult a b => (s_compile a) ++ (s_compile b) ++ SMult :: nil\n  end.\n\nLemma s_execute_append :\n  forall a b c st,\n    s_execute st (c) (a ++ b) = s_execute st (s_execute st (c) a) b. \n  intro. elim a; auto.\n  intros. elim a0; intros; auto. simpl. apply H.\n  simpl. apply H.\n  case c. simpl. apply H.\n  intros. case l0. simpl. apply H.\n  simpl. intros; apply H.\n  case c. simpl. apply H.\n  intros. case l0. simpl. apply H.\n  simpl. intros; apply H.\n  case c. simpl. apply H.\n  intros. case l0. simpl. apply H.\n  simpl.  intros; apply H.\nQed.\n\n  Theorem s_compile_correct :\n    forall st e c,\n      s_execute st c (s_compile e) =  [aeval st e] ++ c.\n    intros st e. elim e; intros; auto.\n    simpl. rewrite s_execute_append. rewrite H. rewrite s_execute_append. rewrite H0. simpl. rewrite plus_comm. trivial.\n    simpl. rewrite s_execute_append. rewrite H. rewrite s_execute_append. rewrite H0. simpl. trivial.\n    simpl. rewrite s_execute_append. rewrite H. rewrite s_execute_append. rewrite H0. simpl. rewrite mult_comm. trivial.\n  Qed.\n\n\n  Module 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    Notation \"'SKIP'\" :=\n      CSkip.\n\n    Notation \"'BREAK'\" :=\n      CBreak.\n\n    Notation \"x '::=' a\" :=\n      (CAss x a) (at level 60).\n\n    Notation \"c1 ;; c2\" :=\n      (CSeq c1 c2) (at level 80, right associativity).\n\n    Notation \"'WHILE' b 'DO' c 'END'\" :=\n      (CWhile b c) (at level 80, right associativity).\n\n    Notation \"'IFB' b 'THEN' c1 'ELSE' c2 'FI' \" :=\n      (CIf b c1 c2) (at level 80, right associativity).\n\n    Inductive status : Type :=\n    | SContinue : status\n    | SBreak : status.\n\n    Reserved Notation \"c1 '/' st '\\\\' s '/' st'\"\n             (at level 40, st, s at level 39).\n\n    Inductive ceval : com -> state -> status -> state -> Prop :=\n    | E_Skip : forall st,\n                 SKIP / st \\\\ SContinue / st\n    | E_Ass : forall st a b,\n                (a ::= b) / st \\\\ SContinue / (t_update st a (aeval st b))\n    | E_Break : forall st,\n                  BREAK / st \\\\ SBreak / st\n    | E_IfTrue : forall st st' c1 c2 signal,\n                   c1 / st \\\\ signal / st' ->\n                   (IFB BTrue THEN c1 ELSE c2 FI) / st \\\\ signal / st'\n    | E_IfFalse : forall st st' c1 c2 signal,\n                    c2 / st \\\\ signal / st' ->\n                    (IFB BFalse THEN c1 ELSE c2 FI) / st \\\\ signal / st'\n    | E_SeqBreak : forall st st' c1 c2,\n                     c1 / st \\\\ SBreak / st' ->\n                     (c1 ;; c2) / st \\\\ SBreak / st'\n    | E_SeqCont : forall st st' st'' c1 c2 signal,\n                    c1 / st \\\\ SContinue / st' ->\n                    c2 / st' \\\\ signal / st'' ->\n                    (c1 ;; c2) / st \\\\ signal / st''\n    | E_WhileFalse : forall st b c,\n                       beval st b = false ->\n                       WHILE b DO c END / st \\\\ SContinue / st\n    | E_WhileBreak : forall st st' b c,\n                       c / st \\\\ SBreak / st' ->\n                       beval st b = true ->\n                       (WHILE b DO c END) / st \\\\ SContinue / st'\n    | E_WhileTrue : forall st st' st'' b c,\n                      beval st b = true ->\n                      c / st \\\\ SContinue / st' ->\n                      (WHILE b DO c END) / st' \\\\ SContinue / st'' ->\n                      (WHILE b DO c END) / st \\\\ SContinue / st''\n    where \"c1 '/' st '\\\\' signal '/' st'\" := (ceval c1 st signal st').\n\n    Theorem break_ignore : forall c st st' s,\n                             (BREAK;;c) / st \\\\ s / st' ->\n                             st = st'.\n      intros. inversion H.  inversion H5. trivial. inversion H2.\n    Qed.\n\n    Theorem while_continue : forall b c st st' s,\n                               (WHILE b DO c END) / st \\\\ s / st' ->\n                               s = SContinue.\n      intros.\n      inversion H; auto.\n    Qed.\n\n    Theorem while_stops_on_break :\n      forall b c st st',\n        beval st b = true ->\n        c / st \\\\ SBreak / st' ->\n        (WHILE b DO c END) / st \\\\ SContinue / st'.\n\n      intros. apply E_WhileBreak; auto.\n    Qed.\n  End BREAKIMP.\n  \n\n  Theorem loop_never_stops__:\n    forall st st', ~(loop / st \\\\ st').\n    unfold loop. unfold not.\n    intros. remember (WHILE BTrue DO SKIP END) as c.\n    generalize Heqc. pattern c. elim H; try discriminate.\n    intros. inversion Heqc0. rewrite H6 in H4; rewrite H7 in H4; auto.\n    intros. inversion Heqc0. rewrite H2 in H0. simpl in H0. inversion H0.\n  Qed.\n", "meta": {"author": "DKXXXL", "repo": "SoftwareFoundations-AfterCh15", "sha": "f9fbacb555970fdf42dd834f29c4a6289d5acb59", "save_path": "github-repos/coq/DKXXXL-SoftwareFoundations-AfterCh15", "path": "github-repos/coq/DKXXXL-SoftwareFoundations-AfterCh15/SoftwareFoundations-AfterCh15-f9fbacb555970fdf42dd834f29c4a6289d5acb59/Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011833, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.6988598509862499}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.proposition_20.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_TGsymmetric.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_TGflip.\nRequire Export GeoCoq.Elements.OriginalProofs.proposition_22.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma proposition_23 : \n   forall A B C D E, \n   neq A B -> nCol D C E ->\n   exists X Y, Out A B Y /\\ CongA X A Y D C E.\nProof.\nintros.\nassert (~ Col E C D).\n {\n intro.\n assert (Col D C E) by (forward_using lemma_collinearorder).\n contradict.\n }\nassert (~ Col C E D).\n {\n intro.\n assert (Col D C E) by (forward_using lemma_collinearorder).\n contradict.\n }\nassert (Triangle D C E) by (conclude_def Triangle ).\nassert (Triangle C E D) by (conclude_def Triangle ).\nassert (Triangle E C D) by (conclude_def Triangle ).\nassert (TG C D D E C E) by (conclude proposition_20).\nassert (TG C E E D C D) by (conclude proposition_20).\nassert (TG E C C D E D) by (conclude proposition_20).\nassert (TG C D E C E D) by (conclude lemma_TGsymmetric).\nassert (TG C D D E E C) by (forward_using lemma_TGflip).\nassert (TG D E C D E C) by (conclude lemma_TGsymmetric).\nassert (TG E D C D E C) by (forward_using lemma_TGflip).\nassert (TG C D E D E C) by (conclude lemma_TGsymmetric).\nassert (TG E C E D C D) by (forward_using lemma_TGflip).\nlet Tf:=fresh in\nassert (Tf:exists G F, (Cong A G E C /\\ Cong A F C D /\\ Cong G F E D /\\ Out A B G /\\ Triangle A G F)) \n by (conclude proposition_22);destruct Tf as [G[F]];spliter.\nassert (Cong A G C E) by (forward_using lemma_congruenceflip).\nassert (Cong F G D E) by (forward_using lemma_congruenceflip).\nassert (eq E E) by (conclude cn_equalityreflexive).\nassert (eq D D) by (conclude cn_equalityreflexive).\nassert (eq F F) by (conclude cn_equalityreflexive).\nassert (eq G G) by (conclude cn_equalityreflexive).\nassert (~ eq C E).\n {\n intro.\n assert (Col D C E) by (conclude_def Col ).\n contradict.\n }\nassert (~ eq C D).\n {\n intro.\n assert (Col C D E) by (conclude_def Col ).\n assert (Col D C E) by (forward_using lemma_collinearorder).\n contradict.\n }\nassert (Out C E E) by (conclude lemma_ray4).\nassert (Out C D D) by (conclude lemma_ray4).\nassert (~ Col F A G).\n {\n intro.\n assert (Col A G F) by (forward_using lemma_collinearorder).\n assert (nCol A G F) by (conclude_def Triangle ).\n contradict.\n }\nassert (~ eq A F).\n {\n intro.\n assert (Col A F G) by (conclude_def Col ).\n assert (Col F A G) by (forward_using lemma_collinearorder).\n contradict.\n }\nassert (Out A F F) by (conclude lemma_ray4).\nassert (~ eq A G).\n {\n intro.\n assert (Col A G F) by (conclude_def Col ).\n assert (Col F A G) by (forward_using lemma_collinearorder).\n contradict.\n }\nassert (Out A G G) by (conclude lemma_ray4).\nassert (CongA F A G D C E) by (conclude_def CongA ).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/proposition_23.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.6988598505186329}}
{"text": "Require Import ZArith.\nRequire Import Zhints.\nRequire Import Zpow_facts.\nRequire Import BinInt. Import Z.\nRequire Import Znat.\nRequire Import Zeuclid. Import ZEuclid.\nRequire Import Znumtheory.\nRequire Import Reciprocity.Reciprocity.Finite. Import FiniteTypes.\nRequire Import Reciprocity.Reciprocity.Accumulation. Import Accum.\nRequire Import Classical.\n\nLemma Zpos_induction (P : Z -> Prop) :\n  P 0 ->\n  (forall n : Z, 0 <= n -> P n -> P (succ n)) ->\n  (forall n : Z, 0 <= n -> P n).\nProof.\n  intros P0 Psucc.\n  assert (forall n : nat, P (Z.of_nat n)).\n  simple induction n. auto.\n  intro n0. rewrite Nat2Z.inj_succ. apply Psucc. apply Nat2Z.is_nonneg.\n  intros n Hpos. rewrite <- Z2Nat.id by auto. apply H.\nQed.\n\nLemma prime_divide_pow :\n  forall x p n : Z, 0 <= n -> prime p -> (p | x ^ n) -> (p | x).\nProof.\n  intros x p.\n  apply (Zpos_induction (fun n => prime p -> (p | x ^ n) -> (p | x))).\n  simpl. intros _ H. destruct H. exists (x * x0). rewrite <- Zmult_assoc.\n  rewrite <- H. omega.\n  intros n Hpos Hrec Hprime Hdiv.\n  rewrite pow_succ_r in Hdiv by auto. apply prime_mult in Hdiv.\n  destruct Hdiv. auto. auto. auto.\nQed.\n\nLemma power_plus :\n  forall x m n, 0 <= n -> 0 <= m -> x ^ (n + m) = x ^ n * x ^ m.\nProof.\n  intros x m.\n  apply (Zpos_induction (fun n => 0 <= m -> x ^ (n + m) = x ^ n * x ^ m)).\n  intro H. rewrite pow_0_r. rewrite mul_1_l. auto.\n  intros n Hnpos Hrec Hmpos.\n  rewrite add_succ_l. rewrite pow_succ_r. rewrite pow_succ_r by auto.\n  rewrite <- Zmult_assoc. f_equal. auto. omega.\nQed.\n\nLemma one_pow :\n  forall n, 0 <= n -> 1 ^ n = 1.\nProof.\n  apply (Zpos_induction (fun n => 1 ^ n = 1)).\n  auto. intros n Hpos Hrec. rewrite pow_succ_r by auto. rewrite Hrec. omega.\nQed.\n\nLemma power_power :\n  forall x m n, 0 <= n -> 0 <= m -> (x ^ n) ^ m = x ^ (n * m).\nProof.\n  intros x m.\n  apply (Zpos_induction (fun n => 0 <= m -> (x ^ n) ^ m = x ^ (n * m))).\n  intro. simpl. apply one_pow. auto.\n  intros n Hnpos Hrec Hmpos. rewrite pow_succ_r by auto.\n  rewrite Zmult_power by auto. rewrite Zmult_succ_l.\n  rewrite power_plus. rewrite Zmult_comm. f_equal.\n  auto. rewrite <- mul_0_l with (n := m).\n  apply Zmult_le_compat_r. auto. auto. auto.\nQed.\n\nLemma minus_one_pow_even :\n  forall n : Z, 0 <= n -> Even n -> (-1) ^ n = 1.\nProof.\n  intros n Hpos Heven. destruct Heven.\n  rewrite H.\n  rewrite <- power_power by omega. apply one_pow. omega.\nQed.\n\nLemma minus_one_pow_odd :\n  forall n : Z, 0 <= n -> Odd n -> (-1) ^ n = -1.\nProof.\n  intros n Hpos Hodd. destruct Hodd.\n  rewrite H. rewrite power_plus by omega.\n  rewrite <- power_power by omega. rewrite one_pow. auto. omega.\nQed.\n\nLemma even_mod :\n  forall n : Z, Even n <-> n mod 2 = 0.\nProof.\n  intro n. split.\n  intro Heven. destruct Heven. rewrite H. rewrite Zmult_mod.\n  auto.\n  intro Hmod. exists (n / 2). apply Z_div_exact_2. omega. auto.\nQed.\n\nLemma odd_mod :\n  forall n : Z, Odd n <-> n mod 2 = 1.\nProof.\n  intro n. split.\n  intro Hodd. destruct Hodd. rewrite H. rewrite Zplus_comm.\n  rewrite Zmult_comm. rewrite Z_mod_plus_full. auto.\n  intro Hmod. exists (n / 2). rewrite <- Hmod. apply Z_div_mod_eq.\n  omega.\nQed.\n\nLemma even_or_odd n :\n  Even n \\/ Odd n.\nProof.\n  rewrite <- Zeven_equiv. rewrite <- Zodd_equiv.\n  destruct (Zeven_odd_dec n). auto. auto.\nQed.\n\nLemma minus_one_pow_mod_2 :\n  forall n m : Z, 0 <= n -> 0 <= m -> ((-1) ^ n = (-1) ^ m <-> n mod 2 = m mod 2).\nProof.\n  intros n m Hnpos Hmpos.\n  destruct (even_or_odd n). assert (n mod 2 = 0). apply even_mod. auto.\n  rewrite H0. rewrite minus_one_pow_even; [ | omega | auto].\n  destruct (even_or_odd m). assert (m mod 2 = 0). apply even_mod. auto.\n  rewrite H2. rewrite minus_one_pow_even; [ | omega | auto].\n  tauto.\n  assert (m mod 2 = 1). apply odd_mod. auto.\n  rewrite H2. rewrite minus_one_pow_odd; [ | omega | auto].\n  split. intro. discriminate. intro. discriminate.\n  assert (n mod 2 = 1). apply odd_mod. auto.\n  rewrite H0. rewrite minus_one_pow_odd; [ | omega | auto].\n  destruct (even_or_odd m). assert (m mod 2 = 0). apply even_mod. auto.\n  rewrite H2. rewrite minus_one_pow_even; [ | omega | auto].\n  split. intro. discriminate. intro. discriminate.\n  assert (m mod 2 = 1). apply odd_mod. auto.\n  rewrite H2. rewrite minus_one_pow_odd; [ | omega | auto].\n  tauto.\nQed.\n\nDefinition m1_pow (n : Z) := -2 * (n mod 2) + 1.\nLemma m1_pow_1_or_m1 :\n  forall n : Z, m1_pow n = 1 \\/ m1_pow n = -1.\nProof.\n  intro n.\n  destruct (even_or_odd n).\n  left. unfold m1_pow. assert (n mod 2 = 0). apply even_mod. auto. omega.\n  right. unfold m1_pow. assert (n mod 2 = 1). apply odd_mod. auto. omega.\nQed.\nLemma m1_pow_compatible :\n  forall n : Z, n >= 0 -> (-1) ^ n = m1_pow n.\nProof.\n  intros n H. destruct (even_or_odd n).\n  rewrite minus_one_pow_even by (omega || auto).\n  unfold m1_pow. assert (n mod 2 = 0). apply even_mod. auto. omega.\n  rewrite minus_one_pow_odd by (omega || auto).\n  unfold m1_pow. assert (n mod 2 = 1). apply odd_mod. auto. omega.\nQed.\nLemma m1_pow_morphism :\n  forall n m : Z, m1_pow (n + m) = m1_pow n * m1_pow m.\nProof.\n  intros n m. unfold m1_pow. rewrite Zplus_mod.\n  destruct (even_or_odd n). assert (n mod 2 = 0). apply even_mod. auto. repeat (rewrite H0).\n  destruct (even_or_odd m). assert (m mod 2 = 0). apply even_mod. auto. repeat (rewrite H2).\n  auto. assert (m mod 2 = 1). apply odd_mod. auto. repeat (rewrite H2). auto.\n  assert (n mod 2 = 1). apply odd_mod. auto. repeat (rewrite H0).\n  destruct (even_or_odd m). assert (m mod 2 = 0). apply even_mod. auto. repeat (rewrite H2).\n  auto. assert (m mod 2 = 1). apply odd_mod. auto. repeat (rewrite H2). auto.\nQed.\n\nLemma minus_mod :\n  forall n m, 0 < n < m -> (-n) mod m = m - n.\nProof.\n  intros n m H.\n  assert (0 < m). omega.\n  assert (0 <= m - n < m). split. omega. omega.\n  assert ((m - n) mod m = m - n).\n  apply Zmod_small. auto.\n  rewrite <- H2. rewrite <- Zminus_mod_idemp_l.\n  rewrite Z_mod_same. auto. omega.\nQed.\n\nLemma mod_eq_div :\n  forall a b n, n <> 0 -> (a mod n = b mod n <-> (n | a - b)).\nProof.\n  intros a b n Hnnz.\n  split.\n  intro H. apply Zmod_divide. auto. rewrite Zminus_mod.\n  rewrite H. rewrite Zminus_diag. auto.\n  intro H. destruct H.\n  assert (a = b + x * n). omega.\n  rewrite H0. apply Z_mod_plus_full.\nQed.\n\nLemma not_0_inversible_mod_p :\n  forall a p, prime p -> a mod p <> 0 -> exists b, (b * a) mod p = 1.\nProof.\n  intros a p Hprime Hanz.\n  assert (rel_prime p a).\n  apply prime_rel_prime. auto. intro H. apply Zdivide_mod in H. contradiction.\n  apply rel_prime_bezout in H. destruct H.\n  exists v. assert ((u * p + v * a) mod p = 1 mod p). f_equal. auto.\n  rewrite Zmod_1_l in H0 by (destruct Hprime; omega).\n  rewrite <- Zplus_mod_idemp_l in H0.\n  rewrite Zmult_mod in H0. rewrite Z_mod_same in H0 by (destruct Hprime; omega).\n  rewrite Zmult_0_r in H0. rewrite Zmod_0_l in H0. auto.\nQed.\n\nLemma simpl_mod_p :\n  forall a b c p, prime p -> a mod p <> 0 -> (a * b) mod p = (a * c) mod p -> b mod p = c mod p.\nProof.\n  intros a b c p Hprime Hanz Heq.\n  destruct (not_0_inversible_mod_p a p Hprime Hanz).\n  assert (((x * a) mod p * b) mod p = ((x * a) mod p * c) mod p).\n  repeat (rewrite Zmult_mod_idemp_l). repeat (rewrite <- Zmult_assoc).\n  rewrite <- Zmult_mod_idemp_r. rewrite Heq. rewrite Zmult_mod_idemp_r. auto.\n  repeat (rewrite H in H0). repeat (rewrite mul_1_l in H0). auto.\nQed.\n\nLemma over_2 :\n  forall a, a mod 2 = 1 -> (a - 1) / 2 = a / 2.\nProof.\n  intros a Hodd.\n  apply mul_reg_l with (p := 2). omega.\n  assert (2 * ((a - 1) / 2) = a - 1 - (a - 1) mod 2).\n  rewrite Zmod_eq_full. omega. omega.\n  assert (2 * (a / 2) = a - a mod 2).\n  rewrite Zmod_eq_full. omega. omega.\n  rewrite H. rewrite H0. rewrite Hodd. rewrite <- Zminus_mod_idemp_l.\n  rewrite Hodd. simpl. rewrite Zmod_0_l. omega.\nQed.\n\nSection Z_over_pZ.\nVariable p : Z.\nHypothesis p_prime : prime p.\nDefinition ZpZmult (x y : Z) := (x *  y) mod p.\nLemma ZpZmult_comm :\n  forall (x y : Z), ZpZmult x y = ZpZmult y x.\nProof.\n  intros. unfold ZpZmult. rewrite Zmult_comm. auto.\nQed.\nLemma ZpZmult_assoc :\n  forall (x y z : Z), ZpZmult x (ZpZmult y z) = ZpZmult (ZpZmult x y) z.\nProof.\n  intros. unfold ZpZmult.\n  rewrite Zmult_mod_idemp_l. rewrite Zmult_mod_idemp_r. rewrite Zmult_assoc.\n  auto.\nQed.\nLemma one_idemp :\n  ZpZmult 1 1 = 1.\nProof.\n  unfold ZpZmult. simpl. apply Zmod_1_l. destruct p_prime. omega.\nQed.\nLemma mod_1_mod :\n  forall x y : Z, ZpZmult x y = ZpZmult (ZpZmult x y) 1.\nProof.\n  intros x y. unfold ZpZmult.\n  rewrite Zmult_1_r. symmetry. apply Zmod_mod.\nQed.\nEnd Z_over_pZ.\n\nLemma card_interval_full :\n  forall a b : Z, a <= b + 1 ->\n    cardinality {u : Z | a <= u <= b} (Z.to_nat (b - a + 1)).\nProof.\n  intros a b Hsmall.\n  assert (forall u : {u : Z | a <= u <= b}, (Z.to_nat (`u - a) < Z.to_nat (b - a + 1))%nat).\n  intro u. destruct u as [u' Hu']. simpl.\n  apply Z2Nat.inj_lt. omega. omega. omega.\n  exists (fun u => exist _ (Z.to_nat (`u - a)) (H u)).\n  apply bijection_inversible.\n  assert (forall x : {x : nat | (x < Z.to_nat (b - a + 1)) % nat}, a <= a + Z.of_nat `x <= b).\n  intro x. destruct x as [x' Hx']. unfold proj1_sig.\n  assert (0 <= Z.of_nat x' < b - a + 1). split. apply Nat2Z.is_nonneg.\n  apply Nat2Z.inj_lt in Hx'. rewrite Z2Nat.id in Hx'. auto. omega.\n  omega.\n  exists (fun x => exist _ (a + Z.of_nat `x) (H0 x)).\n  split.\n  intro x. destruct x as [x' Hx']. apply proj1_inj. unfold proj1_sig.\n  rewrite Z2Nat.id. omega. omega.\n  intro y. destruct y as [y' Hy']. apply proj1_inj. unfold proj1_sig.\n  rewrite <- Nat2Z.id. f_equal. omega.\nQed.\n\nLemma card_interval :\n  forall a b : Z, a <= b ->\n    cardinality {u : Z | a <= u <= b} (Z.to_nat (b - a + 1)).\nProof.\n  intros a b H.\n  apply card_interval_full. omega.\nQed.\n\nSection FLT.\nVariable p : Z.\nHypothesis p_prime : prime p.\nVariable a : Z.\nHypothesis a_not_0 : a mod p <> 0.\n\nLet f (u : {u : Z | 1 <= u <= p - 1}) := (a * `u) mod p.\nLet f'_exists :\n  forall u, 1 <= f u <= p - 1.\nProof with ((destruct p_prime; omega) || auto).\n  intro u. destruct u as [u' Hu']. unfold f. simpl.\n  assert (0 <= (a * u' mod p) < p).\n  apply mod_pos_bound...\n  assert (a * u' mod p <> 0).\n  intro H1. apply Zmod_divide in H1... apply prime_mult in H1...\n  destruct H1. apply Zdivide_mod in H0. contradiction.\n  apply Zdivide_mod in H0. rewrite Zmod_small in H0...\n  omega.\nQed.\nLet f' u := exist (fun k => 1 <= k <= p - 1) (f u) (f'_exists u).\nLet f'_injective :\n  injection f'.\nProof.\n  intros u1 u2 H. destruct u1 as [u1' Hu1']. destruct u2 as [u2' Hu2'].\n  unfold f' in H. apply proj1_inj in H. simpl in H.\n  apply proj1_inj. simpl. unfold f in H. simpl in H.\n  apply simpl_mod_p in H. repeat (rewrite Zmod_small in H by omega). auto.\n  auto. auto.\nQed.\nLet f'_surjective :\n  surjection f'.\nProof with ((destruct p_prime; omega) || auto).\n  intro y. destruct y as [y' Hy'].\n  destruct (not_0_inversible_mod_p a p p_prime a_not_0) as [a' Ha'].\n  assert (1 <= (a' * y') mod p <= p - 1).\n  assert (0 <= (a' * y') mod p < p). apply mod_pos_bound...\n  assert ((a' * y') mod p <> 0). intro H1.\n  assert ((a * (a' * y')) mod p = 0). rewrite Zmult_mod. rewrite H1.\n  rewrite Zmult_0_r. rewrite Zmod_0_l. auto.\n  rewrite Zmult_assoc in H0. rewrite Zmult_comm with (m := a') in H0.\n  rewrite <- Zmult_mod_idemp_l in H0. rewrite Ha' in H0.\n  rewrite Zmult_1_l in H0. rewrite Zmod_small in H0. omega. omega.\n  omega.\n  exists (exist _ ((a' * y') mod p) H).\n  unfold f'. unfold f. simpl. apply proj1_inj. simpl.\n  rewrite Zmult_mod_idemp_r. rewrite Zmult_assoc. rewrite Zmult_comm with (m := a').\n  rewrite <- Zmult_mod_idemp_l. rewrite Ha'. rewrite Zmult_1_l.\n  apply Zmod_small. omega.\nQed.\nLet card_U :\n  cardinality {u : Z | 1 <= u <= p - 1} (Z.to_nat (p - 1)).\nProof.\n  assert (cardinality {u : Z | 1 <= u <= p - 1} (Z.to_nat (p - 1 - 1 + 1))).\n  apply card_interval. destruct p_prime; omega.\n  assert (p - 1 - 1 + 1 = p - 1). omega. rewrite H0 in H. auto.\nQed.\nLet U_finite :\n  finite {u : Z | 1 <= u <= p - 1}.\nProof.\n  exists (Z.to_nat (p - 1)). apply card_U.\nQed.\n\nLet P' := product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (fun x => `x).\nLet P'_not_0 :\n  P' mod p <> 0.\nProof.\n  unfold P'. apply product_property_conservation.\n  intros x y Hxnz Hynz. unfold ZpZmult. rewrite Zmod_mod.\n  intro H. apply Zmod_divide in H. apply prime_mult in H.\n  destruct H. apply Zdivide_mod in H. contradiction. apply Zdivide_mod in H. contradiction.\n  auto. destruct p_prime; omega. rewrite Zmod_1_l. omega. destruct p_prime; omega.\n  intro x. destruct x. simpl.  rewrite Zmod_small. omega. omega.\nQed.\nLet P'1 :\n  product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (compose (proj1_sig (P := fun k => 1 <= k <= p - 1)) f') =\n  (ZpZmult p) (product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (fun x => `x))\n              (product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (fun x => a)).\nProof.\n  unfold compose. unfold f'. simpl.\n  rewrite <- product_mul. apply product_ext.\n  intro i. unfold f. unfold ZpZmult. f_equal. apply Zmult_comm.\n  apply one_idemp. auto.\nQed.\nLet P'2 :\n  product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (compose (proj1_sig (P := fun k => 1 <= k <= p - 1)) f') = P'.\nProof.\n  unfold P'. rewrite <- product_bij with (b := f') (HI := U_finite). auto.\n  split. apply f'_injective. apply f'_surjective.\nQed.\nLet P'3 :\n  (product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (fun x => a)) mod p = (a ^ (p - 1)) mod p.\nProof.\n  assert (cardinality {u : Z | 1 <= u <= p - 1} (Z.to_nat (p - 1))).\n  apply card_U.\n  apply inv_bijection in H. destruct H as [b Hb].\n  rewrite (product_bij _ _ _ _ _ _ _ _ _ (Fints_finite (Z.to_nat (p - 1))) b Hb).\n  transitivity (a ^ (Z.of_nat (Z.to_nat (p - 1))) mod p).\n  unfold compose. remember (Z.to_nat (p - 1)) as n.\n  generalize n. simple induction n0.\n  rewrite empty_product. auto.\n  intros n1 H. rewrite product_n. rewrite Nat2Z.inj_succ.\n  unfold ZpZmult. rewrite Zmod_mod. rewrite Zmult_mod. unfold ZpZmult in H.\n  rewrite H. rewrite <- Zmult_mod. f_equal.\n  rewrite pow_succ_r. apply Zmult_comm. apply Nat2Z.is_nonneg.\n  rewrite Z2Nat.id. auto. destruct p_prime; omega.\nQed.\nTheorem FLT :\n  (a ^ (p - 1)) mod p = 1.\nProof.\n  assert (\n  (ZpZmult p) (product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (compose (proj1_sig (P := fun k => 1 <= k <= p - 1)) f')) 1 =\n  (ZpZmult p) P'\n              (product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _  U_finite (fun x => a))).\n  unfold P'. rewrite P'1. symmetry. apply mod_1_mod.\n  rewrite P'2 in H.\n  unfold ZpZmult in H.\n  apply simpl_mod_p in H.\n  fold (ZpZmult p) in H.\n  rewrite P'3 in H. rewrite Zmod_1_l in H. auto.\n  destruct p_prime; omega. auto. apply P'_not_0.\nQed.\nEnd FLT.\nDefinition inverse (p : Z) (a : Z) :=\n  (a ^ (p - 2)) mod p.\nLemma p_inverse :\n  forall p a : Z, prime p -> a mod p <> 0 -> (a * (inverse p a)) mod p = 1.\nProof.\n  intros p a Hprime Hanz.\n  unfold inverse. rewrite Zmult_mod_idemp_r.\n  rewrite <- pow_succ_r by (destruct Hprime; omega).\n  unfold succ. assert (p - 2 + 1 = p - 1). omega. rewrite H. apply FLT.\n  auto. auto.\nQed.\nLemma inv_not_0 :\n  forall p a : Z, prime p -> a mod p <> 0 -> (inverse p a) mod p <> 0.\nProof.\n  intros p a Hprime Hanz H. assert ((a * inverse p a) mod p = 1). apply p_inverse.\n  auto. auto. rewrite Zmult_mod in H0. rewrite H in H0. rewrite Zmult_0_r in H0.\n  rewrite Zmod_0_l in H0. discriminate.\nQed.\nLemma inv_inv :\n  forall p a : Z, prime p -> a mod p <> 0 -> (inverse p (inverse p a)) = a mod p.\nProof.\n  intros p a Hprime Hanz.\n  assert (inverse p (inverse p a) mod p = inverse p (inverse p a)).\n  unfold inverse. apply Zmod_mod. rewrite <- H.\n  assert (inverse p a mod p <> 0). apply inv_not_0. auto. auto.\n  apply simpl_mod_p with (a := (inverse p a)). auto. auto.\n  rewrite p_inverse by auto. rewrite Zmult_comm. rewrite p_inverse by auto. auto.\nQed.\nLemma inv_bounds :\n  forall p a : Z, prime p -> a mod p <> 0 -> 1 <= inverse p a <= p - 1.\nProof.\n  intros. assert (inverse p a <> 0). unfold inverse. rewrite <- Zmod_mod.\n  apply inv_not_0. auto. auto.\n  assert (0 <= inverse p a < p). apply Zmod_pos_bound. destruct H; omega. omega.\nQed.\nLemma inv_mod :\n  forall p a : Z, prime p -> inverse p a = inverse p (a mod p).\nProof.\n  intros. unfold inverse. apply Zpower_mod. destruct H; omega.\nQed.\nLemma inv_prod :\n  forall p a b : Z, prime p -> ((inverse p a) * (inverse p b)) mod p = inverse p (a * b).\nProof.\n  intros. unfold inverse. rewrite <- Zmult_mod.\n  rewrite Zmult_power. auto. destruct H; omega.\nQed.\n\nSection Wilson.\nVariable p : Z.\nHypothesis p_prime : prime p.\nHypothesis p_odd : p mod 2 = 1.\nLet p_not_2 :\n  p <> 2.\nProof.\n  intro. rewrite H in p_odd. rewrite Z_mod_same in p_odd. omega. omega.\nQed.\nLet U_finite :\n  finite {x : Z | 1 <= x <= p - 1}.\nProof.\n  exists (Z.to_nat (p - 1 - 1 + 1)). apply card_interval. destruct p_prime; omega.\nQed.\nTheorem Wilson :\n  product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _ U_finite (fun x => `x)\n    = -1 mod p.\nProof.\n  rewrite product_split with (P := fun x => `x = inverse p `x);\n  [ | (apply one_idemp; auto) | (intros; symmetry; rewrite ZpZmult_comm with (x := 1); apply mod_1_mod) ].\n  assert (1 <= 1 <= p - 1). destruct p_prime; omega.\n  assert (proj1_sig (exist (fun x => 1 <= x <= p - 1) 1 H) =\n      inverse p (proj1_sig (exist (fun x => 1 <= x <= p - 1) 1 H))).\n  simpl. unfold inverse. rewrite one_pow by (destruct p_prime; omega).\n  rewrite Zmod_1_l by (destruct p_prime; omega). auto.\n  assert (1 <= p - 1 <= p - 1). destruct p_prime; omega.\n   assert (proj1_sig (exist (fun x => 1 <= x <= p - 1) (p - 1) H1) =\n      inverse p (proj1_sig (exist (fun x => 1 <= x <= p - 1) (p - 1) H1))).\n  simpl. unfold inverse. transitivity ((-1) ^ (p - 2) mod p).\n  rewrite minus_one_pow_odd. rewrite <- minus_mod. f_equal. omega. omega.\n  apply odd_mod. rewrite Zminus_mod. rewrite Z_mod_same. rewrite p_odd. auto. omega.\n  rewrite Zpower_mod. f_equal. f_equal. rewrite <- minus_mod. f_equal. omega. omega.\n  assert ((0 < 2)%nat). omega. remember (exist (fun x => (x < 2)%nat) (0%nat) H3) as F2Zero.\n  assert ((1 < 2)%nat). omega. remember (exist (fun x => (x < 2)%nat) (1%nat) H4) as F2One.\n  remember (fun a : (Fints 2) =>\n    If a = F2Zero then exist (fun k => `k = inverse p `k) (exist (fun x => 1 <= x <= p - 1) 1 H) H0 else\n                       exist _ (exist (fun x => 1 <= x <= p - 1) (p - 1) H1) H2) as b.\n  assert (bijection b).\n  apply bijection_inversible.\n  exists (fun x => If ``x = 1 then F2Zero else F2One).\n  split. intro a. rewrite Heqb. ex_mid_destruct. ex_mid_destruct. auto.\n  simpl in e. exfalso. assert (p <> 2). apply p_not_2. omega.\n  ex_mid_destruct. simpl in n. omega. simpl in n. destruct a as [a' Ha'].\n  apply proj1_inj. rewrite HeqF2One. simpl. apply proj1_inj_neg in n0.\n  rewrite HeqF2Zero in n0. simpl in n0. omega.\n  intro x. rewrite Heqb. ex_mid_destruct. ex_mid_destruct.\n  apply proj1_inj. simpl. apply proj1_inj. simpl. auto.\n  rewrite HeqF2One in e. rewrite HeqF2Zero in e. discriminate.\n  ex_mid_destruct. contradict n. auto.\n  destruct x as [x' Hx']. destruct x' as [x'' Hx'']. apply proj1_inj. simpl.\n  apply proj1_inj. simpl in *.\n  assert (x'' mod p <> 0). rewrite Zmod_small. omega. omega.\n  assert ((x'' * (inverse p x'') - 1) mod p = 0).\n  rewrite Zminus_mod. rewrite p_inverse. rewrite Zminus_mod_idemp_r.\n  simpl. rewrite Zmod_0_l. auto. auto. auto.\n  rewrite <- Hx' in H6.\n  assert ((x'' - 1) * (x'' + 1) mod p = 0). rewrite <- H6.\n  f_equal. rewrite Zmult_minus_distr_r. repeat (rewrite Zmult_plus_distr_r).\n  omega. apply Zmod_divide in H7. apply prime_mult in H7.\n  destruct H7. apply Zdivide_mod in H7. rewrite Zmod_small in H7. omega.\n  omega. apply Zdivide_mod in H7. assert (((x'' + 1) - 1) mod p = p - 1).\n  rewrite Zminus_mod. rewrite H7. rewrite Zmod_1_l. apply minus_mod.\n  omega. omega. rewrite Zmod_small in H8. omega. omega. auto. omega.\n  rewrite product_bij with (b := b) (HJ := Fints_finite 2) by auto.\n  rewrite product_n. rewrite product_n. rewrite empty_product.\n  unfold compose. rewrite Heqb.\n  rewrite If_l by (unfold Fints_coerce; unfold Fints_last; rewrite HeqF2Zero; apply proj1_inj; auto).\n  rewrite If_r by (rewrite HeqF2Zero; unfold Fints_last; apply proj1_inj_neg; simpl; auto). simpl.\n  rewrite one_idemp by auto.\n  rewrite product_split with (P := fun x => ``x < inverse p ``x);\n  [ | (apply one_idemp; auto) | (intros; symmetry; rewrite ZpZmult_comm with (x := 1); apply mod_1_mod) ].\n  assert (c_ex1 : forall x : {x : Z | 1 <= x <= p - 1},\n    1 <= inverse p `x <= p - 1).\n  intro x. destruct x as [x' Hx'].\n  simpl in *. apply inv_bounds. auto. rewrite Zmod_small. omega. omega.\n  remember (fun x => exist (fun k => 1 <= k <= p - 1) (inverse p `x) (c_ex1 x)) as c1.\n  assert (c_ex2 : forall x : {x : {x : Z | 1 <= x <= p - 1} | `x <> inverse p `x},\n            proj1_sig (c1 `x) <>\n       inverse p (proj1_sig (c1 `x))).\n  rewrite Heqc1.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  simpl in *. rewrite inv_inv. rewrite Zmod_small. auto. omega. auto. rewrite Zmod_small. omega. omega.\n  remember (fun x => exist (fun k => `k <> inverse p `k) (c1 `x) (c_ex2 x)) as c2.\n  assert (c_ex3 : forall x : {x : {x : {x : Z | 1 <= x <= p - 1} | `x <> inverse p `x} |\n        ``x < inverse p ``x},\n    ~ (proj1_sig (proj1_sig (c2 `x)) < inverse p (proj1_sig (proj1_sig (c2 `x))))).\n  rewrite Heqc2. simpl. rewrite Heqc1. simpl.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. destruct x'' as [x''' Hx'''].\n  simpl in *. rewrite inv_inv. rewrite Zmod_small. omega. omega. auto. rewrite Zmod_small. omega. omega.\n  remember (fun x => exist (fun k => ~ ``k < inverse p ``k) (c2 `x) (c_ex3 x)) as c3.\n  assert (bijection c3).\n  apply bijection_inversible.\n  assert (c'_ex : forall x : {x : {x : {x : Z | 1 <= x <= p - 1} | `x <> inverse p `x} |\n     ~ ``x < inverse p ``x},\n    proj1_sig (proj1_sig (c2 `x)) < inverse p (proj1_sig (proj1_sig (c2 `x)))).\n  rewrite Heqc2. simpl. rewrite Heqc1. simpl.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. destruct x'' as [x''' Hx'''].\n  simpl in *. rewrite inv_inv. rewrite Zmod_small. omega. omega. auto. rewrite Zmod_small. omega. omega.\n  remember (fun x => exist (fun k => ``k < inverse p ``k) (c2 `x) (c'_ex x)) as c'.\n  assert (forall x, c2 (c2 x) = x). intro x.\n  destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  rewrite Heqc2. apply proj1_inj. simpl. rewrite Heqc1. apply proj1_inj. simpl.\n  rewrite inv_inv. apply Zmod_small. omega. auto. rewrite Zmod_small. omega. omega.\n  exists c'. split.\n  intro x. rewrite Heqc3. rewrite Heqc'. apply proj1_inj. simpl. auto.\n  intro y. rewrite Heqc3. rewrite Heqc'. apply proj1_inj. simpl. auto.\n  rewrite product_bij with (b := c3) (HJ :=\n    (subtype_finite\n           (subtype_finite U_finite\n              (fun x : {x : Z | 1 <= x <= p - 1} => `x <> inverse p `x))\n           (fun x : {x : {x : Z | 1 <= x <= p - 1} | `x <> inverse p `x} =>\n            ``x < inverse p ``x))) by auto.\n  rewrite <- product_mul by (apply one_idemp; auto).\n  rewrite product_ext with (g := fun x => 1).\n  unfold ZpZmult. rewrite Zmult_1_l. rewrite <- Zmult_1_r with (n := -1).\n  rewrite <- Zmult_mod_idemp_l with (a := -1). f_equal.\n  f_equal. rewrite Zmod_small by omega. rewrite <- minus_mod. auto. omega.\n  apply product_property_conservation. intros. rewrite H7. rewrite H8. apply one_idemp.\n  auto. auto. auto.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. destruct x'' as [x''' Hx'''].\n  simpl in *. unfold compose. rewrite Heqc3. simpl. rewrite Heqc2. simpl.\n  rewrite Heqc1. simpl. unfold ZpZmult. apply p_inverse. auto. rewrite Zmod_small. omega. omega.\nQed.\nEnd Wilson.\n\nDefinition legendre (p a : Z) :=\n  If a mod p = 0 then 0 else\n  If exists y, (y ^ 2) mod p = a mod p then 1 else -1.\n\nLemma pow_0_l :\n  forall n : Z, 0 < n -> 0 ^ n = 0.\nProof.\n  intros n H. rewrite (Zsucc_pred n). rewrite pow_succ_r. omega. omega.\nQed.\n\nSection Eulers_criterion.\nVariable p : Z.\nHypothesis p_prime : prime p.\nHypothesis p_odd : p mod 2 = 1.\nVariable a : Z.\nLet p_not_2 :\n  p <> 2.\nProof.\n  intro. rewrite H in p_odd. rewrite Z_mod_same in p_odd. omega. omega.\nQed.\nLet if_a_0 :\n  a mod p = 0 -> 0 mod p = (a ^ ((p - 1) / 2)) mod p.\nProof.\n  intro H.\n  rewrite Zpower_mod. rewrite H.\n  assert ((p - 1) / 2 >= 2 / 2). apply Z_div_ge. omega. destruct p_prime; omega.\n  rewrite Z_div_same in H0. assert (0 < (p - 1) / 2). omega. rewrite pow_0_l by auto.\n  auto. omega. destruct p_prime; omega.\nQed.\nLet if_a_square :\n  a mod p <> 0 -> (exists y, (y ^ 2) mod p = a mod p) ->\n    1 mod p = (a ^ ((p - 1) / 2)) mod p.\nProof.\n  intros H Hsq. destruct Hsq as [y Hsq].\n  assert (y mod p <> 0). intro Hc. rewrite Zpower_mod in Hsq by (destruct p_prime; omega).\n  rewrite Hc in Hsq. rewrite pow_0_l in Hsq. rewrite Zmod_0_l in Hsq. congruence.\n  omega.\n  rewrite Zpower_mod by (destruct p_prime; omega). rewrite <- Hsq.\n  rewrite <- Zpower_mod by (destruct p_prime; omega).\n  rewrite power_power.\n  symmetry. rewrite Zmod_1_l by (destruct p_prime; omega).\n  assert (2 * ((p - 1) / 2) = p - 1). symmetry. apply Z_div_exact_2. omega.\n  rewrite <- Zminus_mod_idemp_l. rewrite p_odd. auto.\n  rewrite H1. apply FLT. auto. auto. omega. apply Z_div_pos. omega. destruct p_prime; omega.\nQed.\nLet if_a_not_square :\n  a mod p <> 0 -> (forall y, (y * y) mod p <> a mod p) ->\n    -1 mod p = (a ^ ((p - 1) / 2)) mod p.\nProof.\n  intros Hanz Hnotsq.\n  remember (fun x : {x : Z | 1 <= x <= p - 1} => ((inverse p `x) * a) mod p) as f.\n  assert (forall x : {x : Z | 1 <= x <= p - 1}, 1 <= f x <= p - 1).\n  intro x. destruct x as [x' Hx']. rewrite Heqf. simpl.\n  assert (0 <= (inverse p x' * a) mod p < p). apply mod_pos_bound. destruct p_prime; omega.\n  assert ((inverse p x' * a) mod p <> 0). intro H1.\n  apply Zmod_divide in H1. apply prime_mult in H1. destruct H1.\n  apply Zdivide_mod in H0. assert (inverse p x' mod p <> 0).\n  apply inv_not_0. auto. rewrite Zmod_small. omega. omega. contradiction.\n  apply Zdivide_mod in H0. contradiction. auto. destruct p_prime; omega.\n  omega.\n  remember (fun x => exist (fun k => 1 <= k <= p - 1) (f x) (H x)) as f'.\n  assert (forall x, f' (f' x) = x). intro x. rewrite Heqf'. generalize H. rewrite Heqf.\n  intro. apply proj1_inj. simpl. destruct Heqf.\n  rewrite <- inv_mod. rewrite <- inv_prod. rewrite Zmult_mod_idemp_l.\n  rewrite <- Zmult_assoc. rewrite Zmult_mod. rewrite inv_inv. rewrite Zmult_comm with (m := a).\n  rewrite p_inverse. rewrite Zmult_1_r. repeat (rewrite Zmod_mod). destruct x. simpl. rewrite Zmod_small.\n  auto. omega. auto. auto. auto. destruct x. simpl. rewrite Zmod_small. omega. omega. auto. auto.\n  assert (forall x, proj1_sig (f' x) <> `x).\n  intro x. destruct x as [x' Hx']. rewrite Heqf'. simpl. rewrite Heqf. simpl. intro H1.\n  assert ((x' * ((inverse p x' * a) mod p)) mod p = a mod p).\n  rewrite Zmult_mod_idemp_r. rewrite Zmult_assoc. rewrite <- Zmult_mod_idemp_l.\n  rewrite p_inverse. f_equal. omega. auto. rewrite Zmod_small. omega. omega.\n  rewrite H1 in H2. apply (Hnotsq x'). auto.\n  assert (finite {x : Z | 1 <= x <= p - 1}).\n  exists (Z.to_nat (p - 1 - 1 + 1)). apply card_interval. destruct p_prime; omega.\n  assert (product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1 _ H2 (fun x => `x)\n    = -1 mod p). rewrite <- Wilson with (p_prime := p_prime).\n  f_equal. apply proof_irrelevance. auto.\n  rewrite product_split with (P := fun x => proj1_sig (f' x) < `x) in H3;\n  [ | (apply one_idemp; auto) | (intros; symmetry; rewrite ZpZmult_comm with (x := 1); apply mod_1_mod) ].\n  assert (forall x : {x : {x : Z | 1 <= x <= p - 1} | proj1_sig (f' x) < `x},\n    ~ (proj1_sig (f' (f' `x)) < (proj1_sig (f' `x)))).\n  intro x. destruct x as [x' Hx']. rewrite H0. simpl. omega.\n  remember (fun x => exist (fun k => ~ (proj1_sig (f' k) < `k)) (f' `x) (H4 x)) as b.\n  assert (bijection b).\n  apply bijection_inversible.\n  assert (forall x : {x : {x : Z | 1 <= x <= p - 1} | ~ (proj1_sig (f' x) < `x)},\n    proj1_sig (f' (f' `x)) < proj1_sig (f' `x)).\n  intro x. destruct x as [x' Hx']. rewrite H0. simpl.\n  assert (proj1_sig (f' x') <> `x'). apply H1. omega.\n  exists (fun x => exist _ (f' `x) (H5 x)).\n  split. intro x. apply proj1_inj. simpl. rewrite Heqb. simpl. apply H0.\n  intro y. apply proj1_inj. simpl. rewrite Heqb. simpl. apply H0.\n  rewrite product_bij with (b := b) (HJ := (subtype_finite H2\n             (fun x : {x : Z | 1 <= x <= p - 1} => proj1_sig (f' x) < `x))) in H3.\n  rewrite <- product_mul in H3. unfold compose in H3.\n  rewrite Heqb in H3. simpl in H3.\n  rewrite product_ext with (g := fun x => a mod p) in H3.\n  destruct (subtype_finite H2\n          (fun x : {x : Z | 1 <= x <= p - 1} => proj1_sig (f' x) < `x)) as [n Hn].\n  assert (cardinality\n             {x : {x : Z | 1 <= x <= p - 1} | ~ proj1_sig (f' x) < `x} n).\n  apply card_bijection with (b := b). auto. auto.\n  assert (cardinality {x : Z | 1 <= x <= p - 1} (n + n)).\n  apply disjoint_union_cardinality with (P := fun x => proj1_sig (f' x) < `x).\n  auto. auto. assert ((n + n = Z.to_nat (p - 1))%nat).\n  apply cardinality_unique with (T := {x : Z | 1 <= x <= p - 1}).\n  auto. assert (Z.to_nat (p - 1) = Z.to_nat (p - 1 - 1 + 1)).\n  f_equal. omega. rewrite H8. apply card_interval. destruct p_prime; omega.\n  assert (n = Z.to_nat ((p - 1) / 2)).\n  assert (p - 1 = (p - 1) / 2 + (p - 1) / 2).\n  rewrite <- Zmult_1_r. rewrite Zmult_plus_distr_l. rewrite <- Zmult_plus_distr_r.\n  rewrite Zmult_comm. apply Z_div_exact_2. omega. rewrite <- Zminus_mod_idemp_l.\n  rewrite p_odd. rewrite Zmod_0_l. auto.\n  rewrite H9 in H8. rewrite Z2Nat.inj_add in H8. omega.\n  apply Z_div_pos. omega. destruct p_prime; omega. apply Z_div_pos. omega. destruct p_prime; omega.\n  assert (product Z (ZpZmult p) (ZpZmult_comm p) (ZpZmult_assoc p) 1\n       {x : {x : Z | 1 <= x <= p - 1} | proj1_sig (f' x) < `x}\n       (ex_intro\n          (fun n0 : nat =>\n           cardinality {x : {x : Z | 1 <= x <= p - 1} | proj1_sig (f' x) < `x} n0) n\n          Hn)\n       (fun _ : {x : {x : Z | 1 <= x <= p - 1} | proj1_sig (f' x) < `x} => a mod p) =\n    a ^ ((p - 1) / 2) mod p).\n  assert (Hc : cardinality {x : {x : Z | 1 <= x <= p - 1} | proj1_sig (f' x) < `x} n). auto.\n  apply inv_bijection in Hc. destruct Hc as [c Hc].\n  rewrite product_bij with (b := c) (HJ := Fints_finite n) by auto. unfold compose.\n  assert (Z.of_nat n = (p - 1) / 2). rewrite <- Z2Nat.id. f_equal. auto.\n  apply Z_div_pos. omega. destruct p_prime; omega.\n  rewrite <- H10.\n  generalize n. simple induction n0.\n  rewrite empty_product. rewrite Zmod_1_l. auto. destruct p_prime; omega.\n  intros n1 Hr. rewrite product_n. rewrite Hr. rewrite Nat2Z.inj_succ.\n  rewrite Zpower_succ_r. unfold ZpZmult. rewrite <- Zmult_mod. f_equal. apply Zmult_comm.\n  apply Nat2Z.is_nonneg.\n  rewrite <- H10. rewrite H3. f_equal.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  unfold ZpZmult. simpl. rewrite Heqf'. simpl. rewrite Heqf. simpl.\n  rewrite Zmult_mod_idemp_r. rewrite Zmult_assoc.\n  rewrite <- Zmult_mod_idemp_l. rewrite p_inverse. f_equal. omega. auto.\n  rewrite Zmod_small. omega. omega. apply one_idemp. auto. auto.\nQed.\nTheorem Eulers_criterion :\n  (legendre p a) mod p = a ^ ((p - 1) / 2) mod p.\nProof.\n\n  unfold legendre.\n  case_if. auto.\n  case_if. auto.\n  apply if_a_not_square. auto.\n  intro y. contradict n0. exists y.\n  assert (y ^ 2 = y * y).\n  simpl. unfold pow_pos. unfold Pos.iter. rewrite Zmult_assoc. rewrite Zmult_1_r. auto.\n  congruence.\nQed.\nEnd Eulers_criterion.\n\nSection Eisensteins_lemma.\nVariable p : Z.\nHypothesis p_prime : prime p.\nHypothesis p_odd : p mod 2 = 1.\n\nLet p_positive :\n  0 < p.\nProof.\n  destruct p_prime. omega.\nQed.\nLet p_positive_rev :\n  p > 0.\nProof.\n  destruct p_prime. omega.\nQed.\nLet p_not_0 :\n  p <> 0.\nProof.\n  assert (0 < p). apply p_positive. omega.\nQed.\nLet eq_mod_2 :\n  forall x y : Z, (x + y) mod 2 = 0 -> x mod 2 = y mod 2.\nProof.\n  intros x y H. rewrite Zplus_mod in H.\n  destruct (even_or_odd x). assert (x mod 2 = 0). apply even_mod. auto.\n  rewrite H1 in H. rewrite H1. simpl in H. rewrite Zmod_mod in H. auto.\n  assert (x mod 2 = 1). apply odd_mod. auto.\n  rewrite H1 in H. rewrite H1. rewrite Zplus_mod_idemp_r in H.\n  assert (y = 1 + y - 1). omega. rewrite H2. rewrite Zminus_mod.\n  rewrite H. auto.\nQed.\nLet div_mod_mod_2_even :\n  forall a : Z, a mod 2 = 0 -> (a / p) mod 2 = (a mod p) mod 2.\nProof.\n  intros a H.\n  rewrite <- Zmult_1_l with (n := (a / p)).\n  rewrite <- p_odd. rewrite Zmult_mod_idemp_l.\n  apply eq_mod_2. rewrite <- Z_div_mod_eq. auto. auto.\nQed.\nLet div_mod_mod_2_odd :\n  forall a : Z, a mod 2 = 1 -> (a / p) mod 2 = (a mod p + 1) mod 2.\nProof.\n  intros a H.\n  rewrite <- Zmult_1_l with (n := (a / p)).\n  rewrite <- p_odd. rewrite Zmult_mod_idemp_l.\n  apply eq_mod_2. rewrite Zplus_assoc. rewrite <- Z_div_mod_eq.\n  rewrite p_odd. rewrite <- Zplus_mod_idemp_l. rewrite H. auto. auto.\nQed.\n\nVariable q : Z.\nHypothesis q_not_0 : q mod p <> 0.\nHypothesis q_postive : q >= 0.\n\nLet r (u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0}) :=\n    (q * `u) mod p.\nLet r_positive :\n  forall (u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0}), 0 <= r u.\nProof.\n  intro u. assert (0 <= r u < p). unfold r.\n  apply mod_pos_bound with (b := p). apply p_positive. omega.\nQed.\nLet r' (u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0}) :=\n    ((Zpower (-1) (r u)) * (r u)) mod p.\nLet r''_ex (u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0}) :\n  1 <= (r' u) <= p - 1 /\\ (r' u) mod 2 = 0.\nProof with (exact p_not_0 || exact p_positive || auto).\n  split.\n  assert (0 <= r' u < p). unfold r'. apply mod_pos_bound...\n  destruct H.\n  split. assert (r' u <> 0).\n  intro H2. unfold r' in H2. apply Zmod_divide in H2...\n  apply prime_mult in H2... destruct H2.\n  apply prime_divide_pow in H1; [ | apply r_positive | auto].\n  apply Zdivide_opp_r_rev with (b := 1) in H1.\n  apply Zdivide_1 in H1. destruct p_prime. omega.\n  unfold r in H1. apply Zdivide_mod in H1.\n  rewrite <- Zmod_div_mod in H1... 2 : reflexivity.\n  apply Zmod_divide in H1... apply prime_mult in H1...\n  destruct H1. apply Zdivide_mod in H1...\n  assert (0 < `u). destruct u. simpl. omega.\n  assert (0 <> `u). omega.\n  apply Zdivide_bounds in H1... destruct u. simpl in *.\n  destruct p_prime. repeat (rewrite abs_eq in H1; [ | omega]).\n  omega. omega. omega.\n  unfold r'.\n  destruct (even_or_odd (r u)).\n  rewrite minus_one_pow_even; [ | apply r_positive | auto].\n  rewrite mul_1_l. unfold r. rewrite Zmod_mod.\n  apply even_mod. auto.\n  rewrite minus_one_pow_odd; [ | apply r_positive | auto].\n  assert (((p - r u) mod p) mod 2 = 0).\n  assert (0 <= p - r u < p).\n  assert (0 <= r u < p). unfold r. apply mod_pos_bound. apply p_positive.\n  assert (0 <> r u). intro H1. apply Zodd_equiv in H.\n  rewrite <- H1 in H. contradiction.\n  omega. rewrite Zmod_small with (n := p) by auto. apply odd_mod in H.\n  rewrite Zminus_mod. rewrite p_odd. rewrite H. auto.\n  rewrite <- H0. f_equal. rewrite Zminus_mod. f_equal.\n  unfold r. rewrite Zmod_mod. rewrite Z_mod_same; [ | apply p_positive_rev].\n  auto.\nQed.\nLet r'' (u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0}) :=\n   exist (fun k => 1 <= k <= p - 1 /\\ k mod 2 = 0) (r' u) (r''_ex u).\nLet r''_inj1 :\n  forall u1 u2, r' u1 = r' u2 -> Even (r u1) -> Odd (r u2) -> r u1 = r u2.\nProof.\n  intros u1 u2 Heq Hodd Heven.\n  exfalso.\n  unfold r' in Heq.\n  rewrite minus_one_pow_even in Heq; [ | apply r_positive | auto].\n  rewrite mul_1_l in Heq.\n  rewrite minus_one_pow_odd in Heq; [ | apply r_positive | auto].\n  unfold r in Heq.\n  rewrite Zmult_mod_idemp_r in Heq.\n  rewrite Zmult_comm with (n := -1) in Heq.\n  rewrite Zmod_mod in Heq.\n  rewrite <- Zmult_assoc in Heq. rewrite <- opp_eq_mul_m1 in Heq.\n  apply simpl_mod_p in Heq; [ | auto | auto].\n  destruct u1 as [u1' Hu1']. destruct u2 as [u2' Hu2'].\n  assert (u1' mod p = u1'). apply Zmod_small. omega.\n  assert (u2' mod p = u2'). apply Zmod_small. omega.\n  simpl in Heq.\n  rewrite Z_mod_nz_opp_full in Heq by omega.\n  rewrite H in Heq. rewrite H0 in Heq.\n  assert (u1' mod 2 = ((p mod 2) - (u2' mod 2)) mod 2).\n  rewrite <- Zminus_mod. f_equal. auto.\n  destruct Hu1' as [Hu1' Hu1'']. destruct Hu2' as [Hu2' Hu2''].\n  rewrite Hu1'' in H1. rewrite Hu2'' in H1. rewrite p_odd in H1.\n  discriminate.\nQed.\nLet r''_injective :\n  injection r''.\nProof.\n  intros u1 u2 H.\n  unfold r'' in H.\n  apply proj1_inj in H. simpl in H.\n  assert (H0: r' u1 = r' u2). auto.\n  unfold r' in H0.\n  assert (r u1 = r u2).\n  destruct (even_or_odd (r u1)).\n    rewrite minus_one_pow_even in H0; [ | apply r_positive | auto].\n    rewrite mul_1_l in H0.\n    destruct (even_or_odd (r u2)).\n      rewrite minus_one_pow_even in H0; [ | apply r_positive | auto].\n      rewrite mul_1_l in H0.\n      unfold r in H0.\n      repeat (rewrite Zmod_mod in H0). unfold r. auto.\n   (* Odd (r u2) *)\n     apply r''_inj1. auto. auto. auto.\n  (* Odd (r u1) *)\n    rewrite minus_one_pow_odd in H0; [ | apply r_positive | auto].\n    destruct (even_or_odd (r u2)).\n      symmetry. apply r''_inj1. auto. auto. auto.\n   (* Odd (r u1) *)\n      rewrite minus_one_pow_odd in H0; [ | apply r_positive | auto].\n      apply simpl_mod_p in H0; [ | auto | ].\n      unfold r in H0. repeat (rewrite Zmod_mod in H0). unfold r. auto.\n      intro H3. apply Zmod_divide in H3. apply Zdivide_opp_r in H3.\n      simpl in H3. apply Zdivide_mod in H3. rewrite Zmod_1_l in H3.\n      discriminate. destruct p_prime. auto. apply p_not_0.\n  unfold r in H1.\n  apply simpl_mod_p in H1; [ | auto | auto].\n  destruct u1 as [u1' Hu1']. destruct u2 as [u2' Hu2'].\n  assert (u1' mod p = u1'). apply Zmod_small. omega.\n  assert (u2' mod p = u2'). apply Zmod_small. omega.\n  apply proj1_inj. simpl in *. congruence.\nQed.\nLet r''_surjective :\n  surjection r''.\nProof with (exact p_not_0 || exact p_positive ||\n     exact p_positive_rev || auto).\n  intro y. destruct y as [y' Hy']. destruct Hy' as [Hy'1 Hy'2].\n  cut (exists x, r' x = y'). intro H. destruct H as [x Hx]. exists x.\n  unfold r''. apply proj1_inj. auto.\n  assert (exists a : Z, (q * a) mod p = y').\n  destruct (not_0_inversible_mod_p q p p_prime q_not_0) as [b Hb].\n  exists (y' * b). rewrite Zmult_comm. rewrite <- Zmult_assoc.\n  rewrite <- Zmult_mod_idemp_r. rewrite Hb. rewrite Zmult_1_r.\n  apply Zmod_small. omega.\n  destruct H as [a Ha].\n  destruct (even_or_odd (a mod p)).\n    assert (1 <= a mod p <= p - 1 /\\ (a mod p) mod 2 = 0).\n    split. assert (0 <= a mod p < p). apply mod_pos_bound...\n    assert (a mod p <> 0). intro H1. rewrite <- Zmult_mod_idemp_r in Ha.\n    rewrite H1 in Ha. rewrite mul_0_r in Ha. rewrite Zmod_0_l in Ha.\n    omega. omega. apply even_mod. auto.\n    exists (exist _ (a mod p) H0).\n    unfold r'. unfold r. simpl.\n    repeat (rewrite Zmult_mod_idemp_r). rewrite Ha.\n    rewrite minus_one_pow_even; [ | omega | auto]. rewrite mul_1_l.\n    rewrite Zmult_mod_idemp_r. auto. apply even_mod. auto.\n  (* Odd (a mod p) *)\n    assert (1 <= p - a mod p <= p - 1 /\\ (p - a mod p) mod 2 = 0).\n    split. assert (0 <= a mod p < p). apply mod_pos_bound...\n    assert (a mod p <> 0). intro H1. rewrite H1 in H. rewrite odd_mod in H.\n    discriminate. omega. rewrite odd_mod in H.\n    rewrite Zminus_mod. rewrite H. rewrite p_odd. auto.\n    exists (exist _ (p - a mod p) H0).\n    unfold r'. unfold r. simpl.\n    repeat (rewrite Zmult_mod_idemp_r).\n    repeat (rewrite Zmult_minus_distr_l with (p := q)).\n    assert (((q * p - q * (a mod p)) mod p) = p - y').\n    rewrite Zminus_mod. rewrite Zmult_mod. rewrite Z_mod_same...\n    rewrite mul_0_r. rewrite Zmod_0_l. rewrite Zmult_mod_idemp_r.\n    rewrite Ha. rewrite <- Z_mod_same with (a := p)... rewrite Zminus_mod_idemp_l.\n    apply Zmod_small. omega. rewrite <- Zmult_mod_idemp_r. repeat (rewrite H1).\n    assert (Odd (p - y')).\n    apply odd_mod. rewrite Zminus_mod. rewrite p_odd. rewrite Hy'2. auto.\n    rewrite minus_one_pow_odd. assert (-1 * (p - y') = y' + -1 * p). omega.\n    rewrite H3. rewrite Z_mod_plus_full. apply Zmod_small. omega. omega. auto.\nQed.\n\nLet card_R :\n  cardinality {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} (Z.to_nat ((p - 1) / 2)).\nProof.\n  assert (forall u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0}, (Z.to_nat ((`u - 1) / 2) < Z.to_nat ((p - 1) / 2))%nat).\n  intro u. destruct u as [u' Hu']. destruct Hu' as [Hu'1 Hu'2]. simpl.\n  apply Nat2Z.inj_lt.\n  repeat (rewrite Z2Nat.id by (apply Z_div_pos; destruct p_prime; omega)).\n  apply Zdiv_lt_upper_bound. omega. rewrite Zmult_comm.\n  rewrite <- Z_div_exact_full_2. omega. omega. rewrite Zminus_mod.\n  rewrite p_odd. auto.\n  exists (fun u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} =>\n      (exist _ (Z.to_nat ((`u - 1) / 2)) (H u))).\n  apply bijection_inversible.\n  assert (forall n : {k : nat | (k < Z.to_nat ((p - 1) / 2))%nat},\n    1 <= 2 + 2 * (Z.of_nat `n) <= p - 1 /\\ (2 + 2 * (Z.of_nat `n)) mod 2 = 0).\n  intro n. destruct n as [n' Hn']. unfold proj1_sig. split.\n  assert (0 <= Z.of_nat n'). apply Nat2Z.is_nonneg.\n  assert (Z.of_nat (S n') <= Z.of_nat (Z.to_nat ((p - 1) / 2))). apply Nat2Z.inj_le. auto.\n  rewrite Z2Nat.id in H1. apply Zmult_le_compat_l with (p := 2) in H1.\n  rewrite <- Z_div_exact_full_2 in H1. rewrite Nat2Z.inj_succ in H1.\n  omega. omega. rewrite Zminus_mod. rewrite p_odd. auto. omega.\n  apply Z_div_pos. omega. destruct p_prime; omega.\n  rewrite Zmult_comm. rewrite Z_mod_plus_full. auto.\n  exists (fun n : {k : nat | (k < Z.to_nat ((p - 1) / 2))%nat} =>\n           exist _ (2 + 2 * (Z.of_nat `n)) (H0 n)).\n  unfold proj1_sig. split.\n  intro u. destruct u as [u' Hu']. destruct Hu' as [Hu' Hu''].\n  apply proj1_inj. unfold proj1_sig.\n  rewrite Z2Nat.id. assert (u' - 1 = 2 * ((u' - 1) / 2) + ((u' - 1) mod 2)).\n  apply Z_div_mod_eq. omega. assert ((u' - 1) mod 2 = 1).\n  rewrite Zminus_mod. rewrite Hu''. auto. omega. apply Z_div_pos. omega.\n  omega.\n  intro y. destruct y as [y' Hy'].\n  apply proj1_inj. unfold proj1_sig.\n  assert (2 + 2 * Z.of_nat y' - 1 = 1 + of_nat y' * 2). omega.\n  rewrite H1. rewrite Z_div_plus_full. simpl. apply Nat2Z.id. omega.\nQed.\n\nLet R_finite :\n  finite {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0}.\nProof.\n  exists (Z.to_nat ((p - 1) / 2)). apply card_R.\nQed.\n\nLet mlt := ZpZmult p.\nLet mlt_comm := ZpZmult_comm p.\nLet mlt_assoc := ZpZmult_assoc p.\nLet one_id := one_idemp p p_prime.\n\nLet P := product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun x => `x).\nLet P_not_0 :\n  P mod p <> 0.\nProof.\n  unfold P. apply product_property_conservation.\n  intros x y Hxnz Hynz. unfold mlt. unfold ZpZmult. rewrite Zmod_mod.\n  intro H. apply Zmod_divide in H. apply prime_mult in H.\n  destruct H. apply Zdivide_mod in H. contradiction. apply Zdivide_mod in H. contradiction.\n  auto. apply p_not_0. rewrite Zmod_1_l. omega. destruct p_prime. omega.\n  intro x. destruct x. simpl.  rewrite Zmod_small. omega. omega.\nQed.\nLet P1 :\n  product Z mlt mlt_comm mlt_assoc 1 _ R_finite r =\n    mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun x => q)) P.\nProof.\n  unfold P.\n  rewrite <- product_mul. apply product_ext.\n  unfold mlt. unfold ZpZmult. unfold r. auto.\n  apply one_id.\nQed.\nLet P2 :\n  product Z mlt mlt_comm mlt_assoc 1 _ R_finite r' =\n    mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u)))\n        (product Z mlt mlt_comm mlt_assoc 1 _ R_finite r).\nProof.\n  rewrite <- product_mul. apply product_ext.\n  unfold mlt. unfold ZpZmult. unfold r'. auto.\n  apply one_id.\nQed.\nLet P3 :\n  product Z mlt mlt_comm mlt_assoc 1 _ R_finite r' = P.\nProof.\n  transitivity (product Z mlt mlt_comm mlt_assoc 1 _ R_finite\n    (compose (proj1_sig (P := (fun u => 1 <= u <= p - 1 /\\ u mod 2 = 0))) r'')).\n  apply product_ext. unfold compose. unfold r''. simpl. auto.\n  unfold P.\n  rewrite <- product_bij with (HI := R_finite).\n  apply product_ext. auto.\n  split. apply r''_injective. apply r''_surjective.\nQed.\nLet P4 :\n  mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u)))\n      (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u)))\n    = 1.\nProof.\n  rewrite <- product_mul. apply product_property_conservation.\n  intros. rewrite H. rewrite H0. apply one_id. auto.\n  unfold mlt. unfold ZpZmult. intro x. rewrite <- Zmult_power. simpl.\n  rewrite one_pow. rewrite Zmod_1_l. auto. destruct p_prime; omega.\n  apply r_positive. apply r_positive. apply one_id.\nQed.\nLet P5 :\n  mlt P ((product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u)))) =\n    mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite r) 1.\nProof.\n  assert (mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite r) 1 =\n          mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite r)\n                   (mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u)))\n                        (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u))))).\n  rewrite P4. auto.\n  rewrite H. rewrite <- P3. rewrite P2.\n  remember (product Z mlt mlt_comm mlt_assoc 1\n        {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} R_finite\n        (fun u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} => (-1) ^ r u)) as a.\n  remember (product Z mlt mlt_comm mlt_assoc 1\n     {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} R_finite r) as b.\n  rewrite mlt_comm. rewrite mlt_assoc. rewrite mlt_comm. auto.\nQed.\nLet P6 :\n  mlt P (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u))) =\n  mlt P (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => q)).\nProof.\n  assert (mlt P ((product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u)))) =\n    mlt (product Z mlt mlt_comm mlt_assoc 1 _ R_finite r) 1).\n  apply P5.\n  rewrite P1 in H. rewrite <- (mod_1_mod p) in H. rewrite H. apply mlt_comm.\nQed.\nLet P7 :\n  (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u))) mod p =\n  (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => q)) mod p.\nProof.\n  apply simpl_mod_p with (a := P). auto. apply P_not_0.\n  apply P6.\nQed.\nLet P8 :\n  (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ (r u))) =\n  (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ ((q * `u) / p))).\nProof.\n  apply product_ext. intro i. apply minus_one_pow_mod_2.\n  apply r_positive. apply Z_div_pos. apply p_positive_rev.\n  destruct i as [i' Hi']. simpl. rewrite <- Zmult_0_l with (n := i').\n  apply Zmult_le_compat_r. omega. omega.\n  unfold r.\n  destruct i as [i' Hi']. destruct Hi' as [Hi' Hi'']. simpl.\n  assert (q * i' = p * (q * i' / p) + (q * i') mod p).\n  apply Z_div_mod_eq. apply p_positive_rev.\n  assert ((q * i' + (q * i') mod p) mod 2 = (p * (q * i' / p) + 2 * ((q * i') mod p)) mod 2).\n  f_equal. omega.\n  rewrite Zplus_mod in H0. rewrite Zmult_mod in H0.\n  rewrite Hi'' in H0. rewrite Zmult_0_r in H0. rewrite Zmod_0_l in H0.\n  rewrite Zplus_0_l in H0. rewrite Zmod_mod in H0.\n  rewrite Zplus_mod in H0. rewrite Zmult_mod with (n := 2) in H0.\n  rewrite p_odd in H0. rewrite Zmult_1_l in H0. rewrite Zmod_mod in H0.\n  rewrite Zmult_mod with (n := 2) in H0. rewrite Z_mod_same in H0 by omega.\n  rewrite Zmult_0_l in H0. rewrite Zmod_0_l in H0. rewrite Zplus_0_r in H0.\n  rewrite Zmod_mod in H0. auto.\nQed.\nLet P9 :\n  (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => (-1) ^ ((q * `u) / p))) mod p =\n  (m1_pow (product Z Zplus Zplus_comm Zplus_assoc 0 _ R_finite (fun u => (q * `u) / p))) mod p.\nProof.\n  transitivity ((product Z mlt mlt_comm mlt_assoc 1\n    {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} R_finite\n    (fun u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} => m1_pow (q * `u / p))) mod p).\n  f_equal.\n  apply product_ext. intro i. apply m1_pow_compatible.\n  apply Zge_iff_le. apply Z_div_pos. apply p_positive_rev.\n  destruct i as [i' Hi']. simpl. rewrite <- Zmult_0_l with (n := i').\n  apply Zmult_le_compat_r. omega. omega.\n  rewrite product_morph with (morph := fun x => (m1_pow x) mod p)\n                             (multS := mlt) (multS_com := mlt_comm)\n                             (multS_assoc := mlt_assoc) (eS := 1).\n  unfold compose.\n  apply product_morph with (morph := fun x => x mod p)\n                           (multS := mlt) (multS_com := mlt_comm)\n                           (multS_assoc := mlt_assoc) (eS := 1).\n  intros. unfold mlt. unfold ZpZmult. rewrite Zmod_mod. rewrite <- Zmult_mod. auto.\n  apply Zmod_1_l. destruct p_prime; omega.\n  intros. unfold mlt. unfold ZpZmult. rewrite <- Zmult_mod. f_equal. apply m1_pow_morphism.\n  unfold m1_pow. simpl. apply Zmod_1_l. destruct p_prime; omega.\nQed.\nLet P10 :\n  (product Z mlt mlt_comm mlt_assoc 1 _ R_finite (fun u => q)) mod p =\n    (q ^ ((p - 1) / 2)) mod p.\nProof.\n  assert (cardinality {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} (Z.to_nat ((p - 1) / 2))).\n  apply card_R.\n  apply inv_bijection in H. destruct H as [b Hb].\n  rewrite (product_bij _ _ _ _ _ _ _ _ _ (Fints_finite (Z.to_nat ((p - 1) / 2))) b Hb).\n  unfold compose.\n  transitivity (q ^ (Z.of_nat (Z.to_nat ((p - 1) / 2))) mod p).\n  remember (to_nat ((p - 1) / 2)) as n.\n  generalize n. simple induction n0.\n  rewrite empty_product. simpl. auto.\n  intros n1 H. rewrite Nat2Z.inj_succ. rewrite product_n. unfold mlt. unfold ZpZmult.\n  rewrite Zmod_mod. fold (ZpZmult p). rewrite <- Zmult_mod_idemp_l. fold mlt. rewrite H.\n  rewrite Zmult_mod_idemp_l. f_equal. rewrite pow_succ_r. rewrite Zmult_comm.\n  auto. apply Nat2Z.is_nonneg.\n  rewrite Z2Nat.id. auto. apply Z_div_pos. omega. destruct p_prime; omega.\nQed.\nLet Eisensteins_lemma_mod_p :\n  (legendre p q) mod p = (m1_pow (product Z Zplus Zplus_comm Zplus_assoc 0 _ R_finite (fun u => (q * `u) / p))) mod p.\nProof.\n  rewrite Eulers_criterion by auto. rewrite <- P10. rewrite <- P7. rewrite P8. apply P9.\nQed.\nLet p_not_2 :\n  p <> 2.\nProof.\n intro H. rewrite H in p_odd. rewrite Z_mod_same in p_odd by omega. discriminate.\nQed.\nLemma Eisensteins_lemma1 :\n  legendre p q = m1_pow (product Z Zplus Zplus_comm Zplus_assoc 0 _ R_finite (fun u => (q * `u) / p)).\nProof.\n  assert ((legendre p q + 1) mod p = (m1_pow (product Z Zplus Zplus_comm Zplus_assoc 0 _ R_finite (fun u => (q * `u) / p)) + 1) mod p).\n  rewrite Zplus_mod. rewrite Eisensteins_lemma_mod_p. rewrite <- Zplus_mod. auto.\n  rewrite Zmod_small in H; [ | (destruct p_prime; unfold legendre; case_if; case_if; omega; omega)].\n  rewrite Zmod_small in H; [ | (destruct p_prime;\n    destruct (m1_pow_1_or_m1 (product Z add add_comm add_assoc 0\n     {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} R_finite\n     (fun u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} => q * `u / p))); omega; omega)].\n  omega.\nQed.\nLet U_finite :\n  finite {u : Z | 1 <= u <= (p - 1) / 2}.\nProof.\n  exists (Z.to_nat ((p - 1) / 2 - 1 + 1)). apply card_interval.\n  apply Zmult_le_reg_r with (p := 2). omega.\n  rewrite Zmult_comm with (n := (p - 1) / 2). rewrite <- Z_div_exact_full_2.\n  destruct p_prime; omega. omega. rewrite <- Zminus_mod_idemp_l. rewrite p_odd. auto.\nQed.\nHypothesis q_odd : q mod 2 = 1.\nHypothesis q_prime : prime q.\nLet E1 :\n  (product Z Zplus Zplus_comm Zplus_assoc 0 _ R_finite (fun u => (q * `u) / p)) mod 2 =\n  (product Z Zplus Zplus_comm Zplus_assoc 0 _ U_finite (fun u => (q * `u) / p)) mod 2.\nProof.\n  rewrite product_split with (P := fun u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} => `u <= (p - 1) / 2) by (intros; omega).\n  rewrite product_split with (P := fun u : {u : Z | 1 <= u <= (p - 1) / 2} => `u mod 2 = 0) by (intros; omega).\n  rewrite Zplus_mod.\n  rewrite Zplus_mod with (a := product _ _ _ _ _ {x : {u : Z | 1 <= u <= (p - 1) / 2} | `x mod 2 = 0} _ _).\n  f_equal. f_equal. f_equal.\n  assert (b_ex1 : forall x : {x : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} | `x <= (p - 1) / 2},\n    1 <= ``x <= (p - 1) / 2). intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  simpl in *. omega.\n  remember (fun x => exist (fun k => 1 <= k <= (p - 1) / 2) ``x (b_ex1 x)) as b1.\n  assert (b_ex2 : forall x, (proj1_sig (b1 x)) mod 2 = 0).\n  intro x. rewrite Heqb1. simpl. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. simpl in *. destruct Hx''. auto.\n  remember (fun x => exist (fun k => `k mod 2 = 0) (b1 x) (b_ex2 x)) as b2.\n  assert (Hb : bijection b2).\n  apply bijection_inversible.\n  assert (b'_ex1 : forall x : {x : {x : Z | 1 <= x <= (p - 1) / 2} | `x mod 2 = 0},\n    1 <= ``x <= p - 1 /\\ ``x mod 2 = 0). intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  simpl in *. split. assert ((p - 1) / 2 < p - 1). apply Z_div_lt. omega. destruct p_prime; omega.\n  omega. auto.\n  remember (fun x => exist (fun k => 1 <= k <= p - 1 /\\ k mod 2 = 0) ``x (b'_ex1 x)) as b'1.\n  assert (b'_ex2 : forall x, proj1_sig (b'1 x) <= (p - 1) / 2). intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  simpl in *. rewrite Heqb'1. simpl. omega.\n  remember (fun x => exist (fun k => `k <= (p - 1) / 2) (b'1 x) (b'_ex2 x)) as b'2.\n  exists b'2. split.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  rewrite Heqb2. rewrite Heqb'2. apply proj1_inj. simpl.\n  rewrite Heqb'1. apply proj1_inj. simpl. rewrite Heqb1. simpl. auto.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  rewrite Heqb2. rewrite Heqb'2. apply proj1_inj. simpl.\n  rewrite Heqb1. apply proj1_inj. simpl. rewrite Heqb'1. simpl. auto.\n  rewrite product_bij with (b := b2) (HJ := (subtype_finite R_finite\n     (fun u : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} => `u <= (p - 1) / 2))).\n  unfold compose. rewrite Heqb2. simpl. rewrite Heqb1. simpl. auto. auto.\n  apply eq_mod_2.\n  assert (p - 1 = (p - 1) / 2 + (p - 1) / 2).\n  rewrite <- Zmult_1_r. rewrite Zmult_plus_distr_l. rewrite <- Zmult_plus_distr_r.\n  rewrite Zmult_comm. apply Z_div_exact_2. omega. rewrite <- Zminus_mod_idemp_l.\n  rewrite p_odd. rewrite Zmod_0_l. auto.\n  assert (c_ex1 : forall x : {x : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} | ~ `x <= (p - 1) / 2},\n    1 <= (p - ``x) <= (p - 1) / 2).\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  simpl in *. omega.\n  remember (fun x => exist (fun k => 1 <= k <= (p - 1) / 2) (p - ``x) (c_ex1 x)) as c1.\n  assert (c_ex2 : forall x, ~ (proj1_sig (c1 x) mod 2 = 0)).\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. simpl in *.\n  rewrite Heqc1. simpl. rewrite Zminus_mod. auto. rewrite p_odd.\n  destruct Hx'' as [Hx''1 Hx''2]. rewrite Hx''2. intro. discriminate.\n  remember (fun x => exist (fun k => ~ `k mod 2 = 0) (c1 x) (c_ex2 x)) as c2.\n  assert (Hc : bijection c2). apply bijection_inversible.\n  assert (c'_ex1 : forall x : {x : {x : Z | 1 <= x <= (p - 1) / 2} | `x mod 2 <> 0},\n    1 <= p - ``x <= p - 1 /\\ (p - ``x) mod 2 = 0).\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. simpl in *.\n  split. omega. rewrite Zminus_mod. rewrite p_odd.\n  assert (x'' mod 2 = 1). assert (0 <= x'' mod 2 < 2). apply mod_pos_bound. omega. omega.\n  rewrite H0. auto.\n  remember (fun x => exist (fun k => 1 <= k <= p - 1 /\\ k mod 2 = 0) (p - ``x) (c'_ex1 x)) as c'1.\n  assert (c'_ex2 : forall x, ~ proj1_sig (c'1 x) <= (p - 1) / 2).\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. simpl in *.\n  rewrite Heqc'1. simpl. omega.\n  remember (fun x => exist (fun k => ~ `k <= (p - 1) / 2) (c'1 x) (c'_ex2 x)) as c'2.\n  exists c'2. split.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  rewrite Heqc'2. apply proj1_inj. simpl. rewrite Heqc'1. apply proj1_inj. simpl.\n  rewrite Heqc2. simpl. rewrite Heqc1. simpl. omega.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  rewrite Heqc2. apply proj1_inj. simpl. rewrite Heqc1. apply proj1_inj. simpl.\n  rewrite Heqc'2. simpl. rewrite Heqc'1. simpl. omega.\n  rewrite product_bij with (b := c2) (HJ := (subtype_finite R_finite\n      (fun x : {u : Z | 1 <= u <= p - 1 /\\ u mod 2 = 0} =>\n       ~ `x <= (p - 1) / 2))) by auto.\n  rewrite <- product_mul by auto. unfold compose.\n  rewrite Heqc2. simpl. rewrite Heqc1. simpl.\n  apply product_property_conservation.\n  intros x y H1 H2. rewrite Zplus_mod. rewrite H1. rewrite H2. auto. auto.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx'']. simpl in *.\n  rewrite Zplus_mod.\n  rewrite div_mod_mod_2_even. rewrite div_mod_mod_2_odd.\n  rewrite <- Zplus_mod. rewrite Zmult_minus_distr_l.\n  rewrite Zminus_mod. rewrite Zmult_mod with (b := p).\n  rewrite Z_mod_same. rewrite Zmult_0_r. rewrite Zmod_0_l.\n  assert ((0 - (q * x'') mod p) = -((q * x'') mod p)). omega. rewrite H0.\n  rewrite minus_mod.\n  assert ((q * x'') mod p + (p - (q * x'') mod p + 1) = p + 1). omega. rewrite H1.\n  rewrite <- Zplus_mod_idemp_l. rewrite p_odd. auto.\n  assert (0 <= (q * x'') mod p < p). apply mod_pos_bound. auto.\n  assert ((q * x'') mod p <> 0). intro H2.\n  apply Zmod_divide in H2. apply prime_mult in H2. destruct H2.\n  apply Zdivide_mod in H2. contradiction.\n  apply Zdivide_mod in H2. rewrite Zmod_small in H2. omega. omega. auto. auto.\n  omega. auto. rewrite Zmult_mod.\n  rewrite q_odd. rewrite Zminus_mod. rewrite p_odd.\n  destruct Hx'' as [Hx''1 Hx''2]. rewrite Hx''2. auto.\n  rewrite Zmult_mod. destruct Hx'' as [Hx''1 Hx''2]. rewrite Hx''2. rewrite Zmult_0_r. auto.\nQed.\nDefinition EL := (product Z Zplus Zplus_comm Zplus_assoc 0 _ U_finite (fun u => (q * `u) / p)).\nLemma EL1 :\n  0 <= EL.\nProof.\n  unfold EL. apply product_property_conservation. intros. omega. omega.\n  intro x. destruct x as [x' Hx']. simpl.\n  apply Z_div_pos. omega. rewrite <- Zmult_0_l with (n := x').\n  apply Zmult_le_compat_r. omega. omega.\nQed.\nLemma EL2 :\n  legendre p q = m1_pow EL.\nProof.\n  rewrite Eisensteins_lemma1. unfold EL. unfold m1_pow.\n  rewrite E1. auto.\nQed.\nLemma EL3 :\n  cardinality {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2\n                                                     /\\ p * snd s <= q * fst s}\n   (Z.to_nat EL).\nProof.\n  unfold EL.\n  assert (Z.to_nat\n     (product Z Zplus Zplus_comm Zplus_assoc 0 {u : Z | 1 <= u <= (p - 1) / 2}\n        U_finite (fun u : {u : Z | 1 <= u <= (p - 1) / 2} => q * `u / p)) =\n      product nat plus plus_comm plus_assoc O {u : Z | 1 <= u <= (p - 1) / 2}\n        U_finite (fun u : {u : Z | 1 <= u <= (p - 1) / 2} => Z.to_nat (q * `u / p))).\n  rewrite <- Nat2Z.id. f_equal.\n  transitivity (product Z add add_comm add_assoc 0 {u : Z | 1 <= u <= (p - 1) / 2} U_finite\n    (fun u : {u : Z | 1 <= u <= (p - 1) / 2} => Z.of_nat (Z.to_nat (q * `u / p)))).\n  apply product_ext. intro i. rewrite Z2Nat.id. auto. destruct i as [i' Hi'].\n  simpl. apply Z_div_pos. omega. rewrite <- Zmult_0_r with (n := q).\n  apply Zmult_le_compat_l. omega. destruct q_prime; omega.\n  symmetry. apply product_morph. intros x y. apply Nat2Z.inj_add. auto.\n  rewrite H.\n  assert (f_ex : forall s : {s : Z * Z |\n    1 <= fst s <= (p - 1) / 2 /\\\n    1 <= snd s <= (q - 1) / 2 /\\ p * snd s <= q * fst s},\n   1 <= fst `s <= (p - 1) / 2).\n  intro s. destruct s as [s' Hs']. simpl. destruct Hs'. auto.\n  apply disjoint_union_cardinality_sum with\n   (f := fun s => exist (fun k => 1 <= k <= (p - 1) / 2) (fst `s) (f_ex s)).\n  intro k. destruct k as [k' Hk']. simpl.\n  assert (b_ex : forall s : {x : {s : Z * Z |\n      1 <= fst s <= (p - 1) / 2 /\\\n      1 <= snd s <= (q - 1) / 2 /\\ p * snd s <= q * fst s} |\n    exist (fun k : Z => 1 <= k <= (p - 1) / 2) (fst `x) (f_ex x) =\n    exist (fun k : Z => 1 <= k <= (p - 1) / 2) k' Hk'},\n      1 <= snd ``s <= (q * k') / p).\n  intro s. destruct s as [s' Hs']. destruct s' as [s'' Hs'']. simpl in *.\n  apply proj1_inj in Hs'. simpl in Hs'. rewrite Hs' in Hs''.\n  destruct Hs'' as [Hs''1 Hs''2]. destruct Hs''2 as [Hs''2 Hs''3].\n  split. omega. apply Zdiv_le_lower_bound. auto. rewrite Zmult_comm. auto.\n  remember (fun s => exist (fun k => 1 <= k <= (q * k' / p)) (snd ``s) (b_ex s)) as b.\n  assert (Hb : bijection b).\n  apply bijection_inversible.\n  assert (b'_ex1 : forall x : {k : Z | 1 <= k <= q * k' / p},\n    (1 <= fst (k', `x) <= (p - 1) / 2 /\\ (1 <= snd (k', `x) <= (q - 1) / 2\n                                      /\\ p * snd (k', `x) <= q * fst (k', `x)))).\n  intro x. simpl. destruct x as [x' Hx']. simpl.\n  split. omega. split. split. omega.\n  rewrite over_2 by auto. transitivity (q * k' / p). omega.\n  transitivity (q * ((p - 1) / 2) / p).\n  apply Z_div_le. auto. apply Zmult_le_compat_l. omega. omega.\n  rewrite over_2 by auto. apply Zdiv_le_lower_bound. omega.\n  transitivity ((q * (p / 2) * 2) / p).\n  rewrite Zmult_comm. rewrite Zmult_comm with (m := 2).\n  apply Zdiv_mult_le. rewrite <- Zmult_0_r with (n := q).\n  apply Zmult_le_compat_l. apply Z_div_pos. omega. omega. omega. omega. omega.\n  transitivity (q * p / p). apply Z_div_le. omega. rewrite <- Zmult_assoc.\n  apply Zmult_le_compat_l. rewrite Zmult_comm. apply Z_mult_div_ge. omega. omega.\n  rewrite Z_div_mult. omega. omega.\n  transitivity (p * ((q * k') / p)). apply Zmult_le_compat_l. omega. omega.\n  apply Z_mult_div_ge. omega.\n  remember (fun x => exist (fun s =>\n    1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2 /\\ p * snd s <= q * fst s\n  ) (k', `x) (b'_ex1 x)) as b'1.\n  assert (b'_ex2 : forall x,\n    exist (fun k : Z => 1 <= k <= (p - 1) / 2) (fst (proj1_sig (b'1 x))) (f_ex (b'1 x)) =\n    exist (fun k : Z => 1 <= k <= (p - 1) / 2) k' Hk').\n  intro x. apply proj1_inj. simpl. rewrite Heqb'1. simpl. auto.\n  exists (fun x => exist _ (b'1 x) (b'_ex2 x)).\n  split.\n  intro x. destruct x as [x' Hx']. destruct x' as [x'' Hx''].\n  apply proj1_inj. simpl. rewrite Heqb'1. apply proj1_inj. simpl in *.\n  rewrite Heqb. simpl. apply proj1_inj in Hx'. simpl in Hx'. rewrite <- Hx'.\n  symmetry. apply surjective_pairing.\n  intro y. destruct y as [y' Hy']. rewrite Heqb. apply proj1_inj. simpl.\n  rewrite Heqb'1. simpl. auto.\n  apply card_bijection with (b := b). auto.\n  assert (Z.to_nat (q * k' / p) = Z.to_nat (q * k' / p - 1 + 1)). f_equal. omega.\n  rewrite H0. apply card_interval_full.\n  assert (0 <= q * k' / p). apply Z_div_pos. omega.\n  rewrite <- Zmult_0_l with (n := k'). apply Zmult_le_compat_r.\n  omega. omega. omega.\nQed.\n\nEnd Eisensteins_lemma.\n\nSection Quadratic_reciprocity.\nVariable p : Z.\nVariable q : Z.\nHypothesis p_prime : prime p.\nHypothesis q_prime : prime q.\nHypothesis p_odd : p mod 2 = 1.\nHypothesis q_odd : q mod 2 = 1.\nHypothesis p_not_q : p <> q.\nLet p_ge_1 :\n  p > 1.\nProof.\n  destruct p_prime; omega.\nQed.\nLet q_ge_1 :\n  q > 1.\nProof.\n  destruct q_prime; omega.\nQed.\nLet p_not_2 :\n  p <> 2.\nProof.\n  intro H. rewrite H in p_odd. discriminate.\nQed.\nLet q_not_2 :\n  q <> 2.\nProof.\n  intro H. rewrite H in q_odd. discriminate.\nQed.\nLet p2_pos :\n  (p - 1) / 2 > 0.\nProof.\n  assert (1 <= (p - 1) / 2). apply Zdiv_le_lower_bound. omega. omega. omega.\nQed.\nLet q2_pos :\n  (q - 1) / 2 > 0.\nProof.\n  assert (1 <= (q - 1) / 2). apply Zdiv_le_lower_bound. omega. omega. omega.\nQed.\nLet p_mod_q_not_0 :\n  p mod q <> 0.\nProof.\n  intro H. apply Zmod_divide in H. contradict p_not_q. symmetry. apply prime_div_prime.\n  auto. auto. auto. omega.\nQed.\nLet q_mod_p_not_0 :\n  q mod p <> 0.\nProof.\n  intro H. apply Zmod_divide in H. contradict p_not_q. apply prime_div_prime.\n  auto. auto. auto. omega.\nQed.\nLet a := EL p p_prime p_odd q.\nLet b := EL q q_prime q_odd p.\nLet QR1 :\n  cardinality {s : {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2} |\n                                                     p * snd `s <= q * fst `s}\n   (Z.to_nat a).\nProof.\n  apply card_and with (Q := fun s => p * snd s <= q * fst s).\n  apply card_subtype with (Q := fun s =>\n    1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2 /\\ p * snd s <= q * fst s).\n  intro x. tauto.\n  unfold a.\n  apply EL3. omega. auto. auto.\nQed.\nLet QR2 :\n  cardinality {s : {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2} |\n                                                     ~ (p * snd `s <= q * fst `s)}\n   (Z.to_nat b).\nProof.\n  assert (forall s : {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2},\n    ~ p * snd `s <= q * fst `s <-> q * fst `s <= p * snd `s).\n  intro s. split.\n  intro H. omega.\n  intro H.\n  assert (q * fst `s <> p * snd `s). intro H0.\n  assert (p | q * fst `s). exists (snd `s). rewrite Zmult_comm with (m := p). auto.\n  apply prime_mult in H1. destruct H1. apply Zdivide_mod in H1.\n  apply q_mod_p_not_0 in H1. auto. apply Zdivide_mod in H1. rewrite Zmod_small in H1.\n  destruct s as [s' Hs']. simpl in H1.\n  omega. destruct s as [s' Hs']. simpl. destruct Hs' as [Hs'1 Hs'2].\n  assert ((p - 1) / 2 < p - 1). apply Z_div_lt. omega. omega. omega. auto. omega.\n  apply card_subtype with (Q := fun s => q * fst `s <= p * snd `s).\n  auto.\n  apply card_and with (Q := fun s => q * fst s <= p * snd s).\n  apply card_subtype with (Q := fun s =>\n    1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2 /\\ q * fst s <= p * snd s).\n  intro x. tauto.\n  assert (forall s : {x : Z * Z |\n    1 <= fst x <= (p - 1) / 2 /\\ 1 <= snd x <= (q - 1) / 2 /\\ q * fst x <= p * snd x},\n   1 <= fst (snd `s, fst `s) <= (q - 1) / 2 /\\ 1 <= snd (snd `s, fst `s) <= (p - 1) / 2 /\\\n   q * snd (snd `s, fst `s) <= p * fst (snd `s, fst `s)).\n  simpl. destruct s. simpl. tauto.\n  remember (fun s : {x : Z * Z |\n           1 <= fst x <= (p - 1) / 2 /\\\n           1 <= snd x <= (q - 1) / 2 /\\ q * fst x <= p * snd x} =>\n  exist (fun s =>\n    1 <= snd s <= (p - 1) / 2 /\\ 1 <= fst s <= (q - 1) / 2 /\\ q * snd s <= p * fst s\n  ) (snd `s, fst `s) (proj2_sig s)) as f.\n  apply card_bijection with (b := f).\n  rewrite Heqf.\n  apply sub_bijection with\n   (P := fun s => 1 <= snd s <= (p - 1) / 2 /\\ 1 <= fst s <= (q - 1) / 2 /\\ q * snd s <= p * fst s)\n   (b := fun s => (snd s, fst s)).\n  apply bijection_inversible. exists (fun s => (snd s, fst s)).\n  simpl. split. intro x. symmetry. apply surjective_pairing.\n  intro y. symmetry. apply surjective_pairing.\n  apply card_subtype with (Q := fun s =>\n    1 <= fst s <= (q - 1) / 2 /\\ 1 <= snd s <= (p - 1) / 2 /\\ q * snd s <= p * fst s).\n  tauto.\n  unfold b. apply EL3. omega. auto. auto.\nQed.\nLet QR3 :\n  cardinality {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2}\n  (Z.to_nat a + Z.to_nat b).\nProof.\n  apply disjoint_union_cardinality with (P := fun s => p * snd `s <= q * fst `s).\n  apply QR1. apply QR2.\nQed.\nLet QR4 :\n  cardinality {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2}\n  (Z.to_nat (((p - 1) / 2) * ((q - 1) / 2))).\nProof.\n  assert (forall s : {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2},\n    1 <= fst `s + ((p - 1) / 2) * (snd `s - 1) <= ((p - 1) / 2) * ((q - 1) / 2)).\n  intro s. destruct s as [s' Hs']. destruct Hs' as [Hs'1 Hs'2].\n  simpl. split.\n  transitivity (fst s' + ((p - 1) / 2) * (1 - 1)). omega.\n  apply Zplus_le_compat_l. apply Zmult_le_compat_l. omega.\n  apply Z_div_pos. omega. omega.\n  transitivity (fst s' + (p - 1) / 2 * ((q - 1) / 2 - 1)).\n  apply Zplus_le_compat_l. apply Zmult_le_compat_l. omega.\n  apply Z_div_pos. omega. omega.\n  transitivity ((p - 1) / 2 + (p - 1) / 2 * ((q - 1) / 2 - 1)).\n  omega. rewrite Zmult_minus_distr_l. omega.\n  apply card_bijection with (b := fun s =>\n    exist (fun x => 1 <= x <= ((p - 1) / 2) * ((q - 1) / 2))\n          (fst `s + ((p - 1) / 2) * (snd `s - 1)) (H s)).\n  apply bijection_inversible.\n\n  assert (forall x : {x : Z | 1 <= x <= ((p - 1) / 2) * ((q - 1) / 2)},\n    1 <= fst ((`x - 1) mod ((p - 1) / 2) + 1, (`x - 1) / ((p - 1) / 2) + 1) <= (p - 1) / 2 /\\\n    1 <= snd ((`x - 1) mod ((p - 1) / 2) + 1, (`x - 1) / ((p - 1) / 2) + 1) <= (q - 1) / 2).\n  intro x. destruct x as [x' Hx']. simpl.\n  split. assert (0 <= (x' - 1) mod ((p - 1) / 2) < (p - 1) / 2).\n  apply mod_pos_bound. omega. omega.\n  assert (0 <= (x' -1) / ((p - 1) / 2)). apply Z_div_pos. omega. omega.\n  assert ((x' - 1) / ((p - 1) / 2) < (q - 1) / 2). apply Zdiv_lt_upper_bound.\n  omega. rewrite Zmult_comm. omega. omega.\n  exists (fun x => exist _\n    ((`x - 1) mod ((p - 1) / 2) + 1, (`x - 1) / ((p - 1) / 2) + 1) (H0 x)).\n  simpl.\n  split.\n  intro s. destruct s as [s' Hs']. apply proj1_inj. simpl.\n  rewrite Zminus_mod. rewrite Zmult_comm. rewrite Z_mod_plus_full.\n  rewrite <- Zminus_mod. rewrite Zmod_small by omega.\n  assert (fst s' + (snd s' - 1) * ((p - 1) / 2) - 1 = fst s' - 1 + (snd s' - 1) * ((p - 1) / 2)).\n  omega. rewrite H1. rewrite Z_div_plus_full by omega. rewrite Zdiv_small by omega.\n  transitivity (fst s', snd s'). f_equal. omega. omega. symmetry. apply surjective_pairing.\n  intro x. destruct x as [x' Hx']. apply proj1_inj. simpl.\n  assert ((x' - 1) / ((p - 1) / 2) + 1 - 1 = (x' - 1) / ((p - 1) / 2)). omega.\n  rewrite H1.\n  assert ((x' - 1) mod ((p - 1) / 2) + 1 +\n    (p - 1) / 2 * ((x' - 1) / ((p - 1) / 2)) =\n          (p - 1) / 2 * ((x' - 1) / ((p - 1) / 2)) + (x' - 1) mod ((p - 1) / 2) + 1).\n  omega. rewrite H2.\n  rewrite <- Z_div_mod_eq. omega. omega.\n  assert (Z.to_nat ((p - 1) / 2 * ((q - 1) / 2)) = Z.to_nat ((p - 1) / 2 * ((q - 1) / 2) - 1 + 1)).\n  f_equal. omega. rewrite H0. apply card_interval_full.\n  assert (0 * ((q - 1) / 2) <= (p - 1) / 2 * ((q - 1) / 2)). apply Zmult_le_compat_r.\n  omega. omega. omega.\nQed.\nLet QR5 :\n  (Z.to_nat a + Z.to_nat b)%nat = (Z.to_nat (((p - 1) / 2) * ((q - 1) / 2))).\nProof.\n  apply cardinality_unique with\n   (T := {s : Z * Z | 1 <= fst s <= (p - 1) / 2 /\\ 1 <= snd s <= (q - 1) / 2}).\n  auto. auto.\nQed.\nLet QR6 :\n  a + b = ((p - 1) / 2) * ((q - 1) / 2).\nProof.\n  assert (0 <= a). apply EL1. omega. assert (0 <= b). apply EL1. omega.\n  rewrite <- Z2Nat.id. rewrite <- Z2Nat.id with (n := a + b). f_equal.\n  rewrite Z2Nat.inj_add. apply QR5. auto. auto.\n  generalize H H0. generalize a b. intros. omega.\n  rewrite <- Zmult_0_r with (n := (p - 1) / 2).\n  apply Zmult_le_compat_l. omega. omega.\nQed.\nTheorem Quadratic_reciprocity :\n  (legendre p q) * (legendre q p) = (-1) ^ (((p - 1) / 2) * ((q - 1) / 2)).\nProof.\n  rewrite EL2 with (p_prime := p_prime) (p_odd := p_odd) by (omega || auto).\n  rewrite EL2 with (p_prime := q_prime) (p_odd := q_odd) by (omega || auto).\n  rewrite m1_pow_compatible. rewrite <- m1_pow_morphism.\n  f_equal. rewrite <- QR6. unfold a. unfold b. auto.\n  rewrite <- Zmult_0_r with (n := (p - 1) / 2).\n  apply Zmult_ge_compat_l. omega. omega.\nQed.\nEnd Quadratic_reciprocity.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-reciprocity/coq-reciprocity.dev/Reciprocity/Reciprocity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7905303162021597, "lm_q1q2_score": 0.698859848103444}}
{"text": "Require Coq.Logic.Classical_Prop.\nRequire Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.lemma_congruenceflip.\nRequire Import ProofCheckingEuclid.lemma_congruencesymmetric.\nRequire Import ProofCheckingEuclid.lemma_lessthancongruence.\nRequire Import ProofCheckingEuclid.lemma_lessthantransitive.\nRequire Import ProofCheckingEuclid.lemma_partnotequalwhole.\nRequire Import ProofCheckingEuclid.lemma_s_lt.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_midpointunique :\n\tforall A B C D,\n\tMidpoint A B C ->\n\tMidpoint A D C ->\n\teq B D.\nProof.\n\tintros A B C D.\n\tintros Midpoint_A_B_C.\n\tintros Midpoint_A_D_C.\n\n\tdestruct Midpoint_A_B_C as (BetS_A_B_C & Cong_AB_BC).\n\tdestruct Midpoint_A_D_C as (BetS_A_D_C & Cong_AD_DC).\n\n\tpose proof (axiom_betweennesssymmetry _ _ _ BetS_A_B_C) as BetS_C_B_A.\n\tpose proof (axiom_betweennesssymmetry _ _ _ BetS_A_D_C) as BetS_C_D_A.\n\n\tpose proof (cn_congruencereflexive A B) as Cong_AB_AB.\n\tpose proof (cn_congruencereflexive A D) as Cong_AD_AD.\n\tpose proof (cn_congruencereflexive C B) as Cong_CB_CB.\n\tpose proof (cn_congruencereflexive C D) as Cong_CD_CD.\n\tpose proof (cn_congruencereverse C B) as Cong_CB_BC.\n\tpose proof (cn_congruencereverse C D) as Cong_CD_DC.\n\n\tpose proof (lemma_congruenceflip _ _ _ _ Cong_AB_BC) as (_ & _ & Cong_AB_CB).\n\tpose proof (lemma_congruenceflip _ _ _ _ Cong_AD_DC) as (_ & _ & Cong_AD_CD).\n\tpose proof (lemma_congruencesymmetric _ _ _ _ Cong_AB_BC) as Cong_BC_AB.\n\tpose proof (lemma_congruencesymmetric _ _ _ _ Cong_AD_DC) as Cong_DC_AD.\n\tpose proof (lemma_congruencesymmetric _ _ _ _ Cong_CD_DC) as Cong_DC_CD.\n\n\tpose proof (lemma_congruenceflip _ _ _ _ Cong_DC_AD) as (_ & Cong_CD_AD & _).\n\n\tassert (~ BetS C D B) as nBetS_C_D_B.\n\t{\n\t\tintros BetS_C_D_B.\n\n\t\tpose proof (axiom_betweennesssymmetry _ _ _ BetS_C_D_B) as BetS_B_D_C.\n\t\tpose proof (axiom_orderofpoints_ABD_BCD_ABC _ _ _ _ BetS_A_B_C BetS_B_D_C) as BetS_A_B_D.\n\t\tpose proof (lemma_s_lt _ _ _ _ _ BetS_A_B_D Cong_AB_AB) as Lt_AB_AD.\n\t\tpose proof (lemma_lessthancongruence _ _ _ _ _ _ Lt_AB_AD Cong_AD_CD) as Lt_AB_CD.\n\n\t\tpose proof (lemma_s_lt _ _ _ _ _ BetS_C_D_B Cong_CD_CD) as Lt_CD_CB.\n\t\tpose proof (lemma_lessthantransitive _ _ _ _ _ _ Lt_AB_CD Lt_CD_CB) as Lt_AB_CB.\n\t\tpose proof (lemma_lessthancongruence _ _ _ _ _ _ Lt_AB_CB Cong_CB_BC) as Lt_AB_BC.\n\t\tpose proof (lemma_lessthancongruence _ _ _ _ _ _ Lt_AB_BC Cong_BC_AB) as Lt_AB_AB.\n\n\t\tdestruct Lt_AB_AB as (E & BetS_A_E_B & Cong_AE_AB).\n\t\tpose proof (lemma_partnotequalwhole _ _ _ BetS_A_E_B) as nCong_AE_AB.\n\n\t\tcontradict Cong_AE_AB.\n\t\texact nCong_AE_AB.\n\t}\n\n\tassert (~ BetS C B D) as nBetS_C_B_D.\n\t{\n\t\tintros BetS_C_B_D.\n\n\t\tpose proof (axiom_betweennesssymmetry _ _ _ BetS_C_B_D) as BetS_D_B_C.\n\t\tpose proof (axiom_orderofpoints_ABD_BCD_ABC _ _ _ _ BetS_A_D_C BetS_D_B_C) as BetS_A_D_B.\n\t\tpose proof (lemma_s_lt _ _ _ _ _ BetS_A_D_B Cong_AD_AD) as Lt_AD_AB.\n\t\tpose proof (lemma_lessthancongruence _ _ _ _ _ _ Lt_AD_AB Cong_AB_CB) as Lt_AD_CB.\n\n\t\tpose proof (lemma_s_lt _ _ _ _ _ BetS_C_B_D Cong_CB_CB) as Lt_CB_CD.\n\t\tpose proof (lemma_lessthantransitive _ _ _ _ _ _ Lt_AD_CB Lt_CB_CD) as Lt_AD_CD.\n\t\tpose proof (lemma_lessthancongruence _ _ _ _ _ _ Lt_AD_CD Cong_CD_AD) as Lt_AD_AD.\n\n\t\tdestruct Lt_AD_AD as (F & BetS_A_F_D & Cong_AF_AD).\n\t\tpose proof (lemma_partnotequalwhole _ _ _ BetS_A_F_D) as nCong_AF_AD.\n\n\t\tcontradict Cong_AF_AD.\n\t\texact nCong_AF_AD.\n\t}\n\n\tpose proof (\n\t\taxiom_connectivity\n\t\t_ _ _ _\n\t\tBetS_C_B_A\n\t\tBetS_C_D_A\n\t\tnBetS_C_B_D\n\t\tnBetS_C_D_B\n\t) as eq_B_D.\n\n\texact eq_B_D.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_midpointunique.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.6988370718351733}}
{"text": "Load lab9strongInduction.\nRequire Import Coq.omega.Omega.\n\nFixpoint redeemBars (n : nat) : nat :=\n match n with\n | 0 => 0\n | 1 => 0\n | 2 => 0\n | 3 => 0\n | 4 => 0\n | 5 => 0\n | 6 => 0\n | 7 => 0\n | 8 => 0\n | 9 => 0\n | S(S(S(S(S(S(S(S(S(S n as n'))))))))) => 1 + redeemBars n'\n end.\n\nEval compute in (redeemBars 9).\nEval compute in (redeemBars 10).\nEval compute in (redeemBars 17).\nEval compute in (redeemBars 18).\nEval compute in (redeemBars 19).\nEval compute in (redeemBars 27).\nEval compute in (redeemBars 28).\n\nFixpoint div9 (n : nat) : nat :=\n match n with\n | 0 => 0\n | 1 => 0\n | 2 => 0\n | 3 => 0\n | 4 => 0\n | 5 => 0\n | 6 => 0\n | 7 => 0\n | 8 => 0\n | S(S(S(S(S(S(S(S(S n)))))))) => 1 + div9 n\n end.\n\nTheorem result: forall n : nat, redeemBars(S n) = div9 n.\nProof.\ninduction n using strong_induction.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\n(* TO BE COMPLETED *)\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/lab11/lab11task2.TEMPLATE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.6988370625770204}}
{"text": "(* Exercises on Category Theory in UniMath *)\n(* for lecture by Peter LeFanu Lumsdaine, Thu 2017-12-14 *)\n(* School and Workshop on Univalent Maths, Birmingham 2017 *)\n(* https://unimath.github.io/bham2017/ *)\n\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Prelude.\nRequire Import UniMath.CategoryTheory.Core.Setcategories.\nRequire Import UniMath.CategoryTheory.categories.HSET.Core.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Core.\nRequire Import UniMath.CategoryTheory.limits.graphs.colimits.\nRequire Import UniMath.CategoryTheory.limits.graphs.limits.\nRequire Import UniMath.CategoryTheory.limits.terminal.\nRequire Import UniMath.CategoryTheory.limits.initial.\nRequire Import UniMath.CategoryTheory.limits.FinOrdProducts.\nRequire Import UniMath.CategoryTheory.limits.equalizers.\nRequire Import UniMath.CategoryTheory.limits.pullbacks.\nRequire Import UniMath.CategoryTheory.Adjunctions.Core.\nRequire Import UniMath.CategoryTheory.Monads.Monads.\n\n\n(* NOTE: some of these exercises (or parts of them) are straightforward, while other parts are intended to be quite difficult.  So I don’t recomment aiming to complete them in order — if stuck on a difficult part, move on and come back for another attempt later!\n\nSkeleton solutions and hints are provided, to exhibit good tools and techniques for working with categories.  However, you may well want to add extra definitions/lemmas besides the ones suggested in the skeleton. *)\n\nSection Exercise_0.\n(** Univalent categories\n\n  Show that in any univalent category, the type of objects has h-level 3 *)\n\n  Proposition isofhlevel3_ob_of_univalent_cat (C : category) (H : is_univalent C)\n    : isofhlevel 3 (ob C).\n  Proof.\n  Admitted.\n\nEnd Exercise_0.\n\nSection Exercise_1.\n(** Non-univalent categories\n\n  Problem: Construct the category with objects the natural numbers, and with maps m->n all functions {1,…,m}->{1,…,n}.  Show that this is a set-category, and that it is NOT univalent.\n\n  Hint: for defining categories (and other large multi-component structures), it’s usually better to define them a few components at a time, following the structure of the definition, as the following skeleton suggests.\n\n  An alternative approach is to go directly for the total structure [Definition nat_category : category], then begin with [use makecategory.] and construct the whole thing in a single interactive proof.  This approach can be good for first finding a proof/construction; but it often causes speed issues down the line, because the resulting term is very large. *)\n\n  Definition nat_category_ob_mor : precategory_ob_mor.\n  Proof.\n  Admitted.\n\n  Definition nat_category_data : precategory_data.\n  Proof.\n  Admitted.\n\n  Definition nat_category_is_precategory : is_precategory nat_category_data.\n  Proof.\n  Admitted.\n\n  Definition nat_category : category.\n  Proof.\n  Admitted.\n\n  Definition nat_setcategory : setcategory.\n  Proof.\n  Admitted.\n\n  Proposition nat_category_not_univalent : ¬ (is_univalent nat_category).\n  Proof.\n  Admitted.\n\nEnd Exercise_1.\n\nSection Exercise_2.\n(** Displayed categories and displayed univalence.\n\nDefine the category of pointed sets, as the total category of a displayed category over sets.  Show it’s univalent as a displayed category, and conclude that it’s univalent as a category.  Alternatively, show directly that the total category is univalent.\n*)\n\n  Definition point_disp_cat : disp_cat hset_category.\n  Proof.\n    (* Hint: Remember, this is to be the displayed category whose *total* category is pointed sets. So the objects and morphisms of this are just the extra data needed to give a pointed set or map of pointed sets, compared to a set or map of sets.\n\n     As in Exercise 1, it may help to give the various components of this as separate lemmas. *)\n  Admitted.\n\n  Definition pointed_hset : category.\n  Proof.\n  Admitted.\n\n  Definition is_univalent_point_disp_cat : is_univalent_disp point_disp_cat.\n  Proof.\n    (* Hint: use [is_univalent_disp_from_fibers]. *)\n  Admitted.\n\n  Definition isunivalent_pointed_hset : is_univalent pointed_hset.\n  Proof.\n    (* Use [is_univalent_point_disp_cat] *)\n  Admitted.\n\n  Definition isunivalent_pointed_hset_proof_2 : is_univalent pointed_hset.\n  Proof.\n    (* Alternatively, prove this directly without using displayed univalence. *)\n  Admitted.\nEnd Exercise_2.\n\n\nSection Exercise_3.\n(** Limits and colimits.\n\n  1. Define the empty graph and empty diagram, and show that any limit of the empty diagram is a terminal object in the directly-defined sense.\n*)\n\n  Definition empty_graph : graph.\n  Proof.\n  Admitted.\n\n  Definition empty_diagram (C : category) : diagram empty_graph C.\n  Proof.\n  Admitted.\n\n  Definition isTerminal_limit_of_empty_diagram\n      {C} (L : LimCone (empty_diagram C))\n    : isTerminal _ (lim L).\n  Proof.\n  Admitted.\n\n  (* 2. Show that for a univalent category, “having an initial object” is a property. *)\n  Definition isaprop_initial_obs_of_univalent_category\n      {C : univalent_category}\n    : isaprop (Initial C).\n  Proof.\n  Admitted.\n\n  (* 3. Show that if a category has equalisers and finite products, then it has pullbacks *)\n  Definition pullbacks_from_equalizers_and_products {C : category}\n    : Equalizers C -> FinOrdProducts C -> Pullbacks C.\n  Proof.\n  Admitted.\n\nEnd Exercise_3.\n\nSection Exercise_4.\n(** Functors and natural transformations / monads and adjunctions\n\nProve that an adjunction induces a monad.  Construct the Kleisli category of a monad.  Show that the Kleisli construction does not preserve univalence: that is, give an example of a monad on a univalent category whose Kleisli category is not univalent. *)\n\n  (* Hint: as usual, it may be helpful to break out parts of these multi-component structures as separate definitions. *)\n\n  Definition monad_from_adjunction {C D : category}\n      (F : functor C D) (G : functor D C) (A : are_adjoints F G)\n    : Monad C.\n  Proof.\n  Admitted.\n\n  Definition kleisli_cat {C : category} (T : Monad C) : category.\n  Proof.\n    (* see <https://en.wikipedia.org/wiki/Kleisli_category> *)\n  Admitted.\n\n  Theorem kleisli_breaks_univalence\n    : ∑ (C : univalent_category) (T : Monad C), ¬ is_univalent (kleisli_cat T).\n  Proof.\n  Admitted.\n\nEnd Exercise_4.\n", "meta": {"author": "UniMath", "repo": "Schools", "sha": "ab62e1075171b5baf22da1bc1ec1dcb5d8f3ef2b", "save_path": "github-repos/coq/UniMath-Schools", "path": "github-repos/coq/UniMath-Schools/Schools-ab62e1075171b5baf22da1bc1ec1dcb5d8f3ef2b/2017-12-Birmingham/Part6_Category_Theory/category_theory_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.698800069585568}}
{"text": "Require Export TopologicalSpaces.\nRequire Export Nets.\nRequire Export FilterLimits.\nRequire Export Continuity.\n\nSet Asymmetric Patterns.\n\nDefinition compact (X:TopologicalSpace) :=\n  forall C:Family (point_set X),\n    (forall U:Ensemble (point_set X), In C U -> open U) ->\n    FamilyUnion C = Full_set ->\n    exists C':Family (point_set X),\n      Finite _ C' /\\ Included C' C /\\\n      FamilyUnion C' = Full_set.\n\nLemma compactness_on_indexed_covers:\n  forall (X:TopologicalSpace) (A:Type) (C:IndexedFamily A (point_set X)),\n    compact X ->\n    (forall a:A, open (C a)) -> IndexedUnion C = Full_set ->\n  exists A':Ensemble A, Finite _ A' /\\\n    IndexedUnion (fun a':{a':A | In A' a'} => C (proj1_sig a')) = Full_set.\nProof.\nintros.\npose (cover := ImageFamily C).\ndestruct (H cover) as [subcover].\nintros.\ndestruct H2.\nrewrite H3; apply H0.\nunfold cover; rewrite <- indexed_to_family_union; trivial.\ndestruct H2 as [? []].\ndestruct (finite_choice _ _\n  (fun (U:{U:Ensemble (point_set X) | In subcover U}) (a:A) =>\n      proj1_sig U = C a)) as [choice_fun].\napply Finite_ens_type; trivial.\ndestruct x as [U].\nsimpl.\napply H3 in i.\ndestruct i.\nexists x; trivial.\n\nexists (Im Full_set choice_fun).\nsplit.\napply FiniteT_img.\napply Finite_ens_type; trivial.\nintros; apply classic.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nrewrite <- H4 in H6.\ndestruct H6.\nassert (In (Im Full_set choice_fun) (choice_fun (exist _ S H6))).\nexists (exist _ S H6).\nconstructor.\ntrivial.\nexists (exist _ (choice_fun (exist _ S H6)) H8).\nsimpl.\nrewrite <- H5.\nsimpl.\ntrivial.\nQed.\n\nLemma compact_finite_nonempty_closed_intersection:\n  forall X:TopologicalSpace, compact X ->\n  forall F:Family (point_set X),\n    (forall G:Ensemble (point_set X), In F G -> closed G) ->\n    (forall F':Family (point_set X), Finite _ F' -> Included F' F ->\n     Inhabited (FamilyIntersection F')) ->\n    Inhabited (FamilyIntersection F).\nProof.\nintros.\napply NNPP; red; intro.\npose (C := [ U:Ensemble (point_set X) | In F (Complement U) ]).\nunshelve refine (let H3:=(H C _ _) in _).\nintros.\ndestruct H3.\napply H0 in H3.\napply closed_complement_open; trivial.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\napply NNPP; red; intro.\ncontradiction H2.\nexists x.\nconstructor.\nintros.\napply NNPP; red; intro.\ncontradiction H4.\nexists (Complement S).\nconstructor.\nrewrite Complement_Complement; trivial.\nexact H6.\n\ndestruct H3 as [C' [? [? ?]]].\npose (F' := [G : Ensemble (point_set X) | In C' (Complement G)]).\nunshelve refine (let H6 := (H1 F' _ _) in _).\nassert (F' = Im C' Complement).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H6.\nexists (Complement x); trivial.\nsymmetry; apply Complement_Complement.\ndestruct H6.\nconstructor.\nrewrite H7; rewrite Complement_Complement; trivial.\nrewrite H6; apply finite_image.\nassumption.\n\nred; intros.\ndestruct H6.\napply H4 in H6.\ndestruct H6.\nrewrite Complement_Complement in H6; trivial.\n\ndestruct H6 as [x0].\ndestruct H6.\nassert (In (FamilyUnion C') x).\nrewrite H5; constructor.\ndestruct H7.\nassert (In (Complement S) x).\napply H6.\nconstructor.\nrewrite Complement_Complement; trivial.\ncontradiction H9.\nQed.\n\nLemma finite_nonempty_closed_intersection_impl_compact:\n  forall X:TopologicalSpace,\n  (forall F:Family (point_set X),\n    (forall G:Ensemble (point_set X), In F G -> closed G) ->\n    (forall F':Family (point_set X), Finite _ F' -> Included F' F ->\n     Inhabited (FamilyIntersection F')) ->\n    Inhabited (FamilyIntersection F)) ->\n  compact X.\nProof.\nintros.\nred; intros.\napply NNPP; red; intro.\npose (F := [ G:Ensemble (point_set X) | In C (Complement G) ]).\nunshelve refine (let H3 := (H F _ _) in _).\nintros.\ndestruct H3.\napply H0; trivial.\nintros.\napply NNPP; red; intro.\ncontradiction H2.\nexists [ U:Ensemble (point_set X) | In F' (Complement U) ].\nrepeat split.\nassert ([U:Ensemble (point_set X) | In F' (Complement U)] =\n  Im F' Complement).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H6.\nexists (Complement x); trivial.\nsymmetry; apply Complement_Complement.\nconstructor.\ndestruct H6.\nrewrite H7; rewrite Complement_Complement; trivial.\nrewrite H6; apply finite_image; trivial.\n\nred; intros.\ndestruct H6.\napply H4 in H6.\ndestruct H6.\nrewrite Complement_Complement in H6; trivial.\n\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\napply NNPP; red; intro.\ncontradiction H5.\nexists x.\nconstructor.\nintros.\napply NNPP; red; intro.\ncontradiction H7.\nexists (Complement S).\nconstructor.\nrewrite Complement_Complement; trivial.\nexact H9.\n\ndestruct H3.\nassert (In (FamilyUnion C) x).\nrewrite H1; constructor.\ndestruct H4.\nassert (In (Complement S) x).\ndestruct H3.\napply H3.\nconstructor.\nrewrite Complement_Complement; trivial.\ncontradiction H6.\nQed.\n\nLemma compact_impl_filter_cluster_point:\n  forall X:TopologicalSpace, compact X ->\n    forall F:Filter (point_set X), exists x0:point_set X,\n    filter_cluster_point F x0.\nProof.\nintros.\npose proof (compact_finite_nonempty_closed_intersection\n  _ H [ G:Ensemble (point_set X) | In (filter_family F) G /\\\n                                   closed G ]) as [x0].\nintros.\ndestruct H0 as [[]]; trivial.\nintros.\nassert (closed (FamilyIntersection F')).\napply closed_family_intersection.\nintros.\napply H1 in H2.\ndestruct H2 as [[]]; trivial.\nassert (In (filter_family F) (FamilyIntersection F')).\nclear H2.\ninduction H0.\nrewrite empty_family_intersection.\napply filter_full.\nreplace (FamilyIntersection (Add A x)) with\n  (Intersection (FamilyIntersection A) x).\napply filter_intersection.\napply IHFinite.\nauto with sets.\nassert (In (Add A x) x) by (right; constructor).\napply H1 in H3.\ndestruct H3 as [[]]; trivial.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H3.\nconstructor.\nintros.\ndestruct H5.\ndestruct H3.\napply H3; trivial.\ndestruct H5; trivial.\ndestruct H3.\nconstructor.\nconstructor; intros.\napply H3.\nauto with sets.\napply H3.\nauto with sets.\napply NNPP; intro.\ncontradiction (filter_empty _ F).\nreplace (@Empty_set (point_set X)) with (FamilyIntersection F'); trivial.\napply Extensionality_Ensembles; split; red; intros.\ncontradiction H4.\nexists x; trivial.\ndestruct H5.\n\nexists x0.\nred; intros.\ndestruct H0.\napply H0.\nconstructor.\nsplit.\napply filter_upward_closed with S; trivial.\napply closure_inflationary.\napply closure_closed.\nQed.\n\nLemma filter_cluster_point_impl_compact:\n  forall X:TopologicalSpace,\n    (forall F:Filter (point_set X), exists x0:point_set X,\n      filter_cluster_point F x0) -> compact X.\nProof.\nintros.\napply finite_nonempty_closed_intersection_impl_compact.\nintros.\nunshelve refine (let H2:=_ in let filt := Build_Filter_from_subbasis F H2 in _).\nintros.\nrewrite indexed_to_family_intersection.\napply H1.\napply FiniteT_img; trivial.\nintros; apply classic.\nred; intros.\ndestruct H4.\nrewrite H5; apply H3.\nassert (filter_subbasis filt F) by apply filter_from_subbasis_subbasis.\ndestruct (H filt) as [x0].\nexists x0.\nconstructor; intros.\nassert (closed S) by (apply H0; trivial).\nassert (In (filter_family filt) S).\napply (filter_subbasis_elements _ _ H3); trivial.\npose proof (H4 _ H7).\nrewrite closure_fixes_closed in H8; trivial.\nQed.\n\nLemma ultrafilter_limit_impl_compact:\n  forall X:TopologicalSpace,\n    (forall U:Filter (point_set X), ultrafilter U ->\n      exists x0:point_set X, filter_limit U x0) -> compact X.\nProof.\nintros.\napply filter_cluster_point_impl_compact.\nintros.\ndestruct (ultrafilter_extension F) as [U].\ndestruct H0.\ndestruct (H _ H1) as [x0].\nexists x0.\nred; intros.\napply filter_limit_is_cluster_point in H2.\napply H0 in H3.\napply H2; trivial.\nQed.\n\nLemma compact_impl_net_cluster_point:\n  forall X:TopologicalSpace, compact X ->\n    forall (I:DirectedSet) (x:Net I X), inhabited (DS_set I) ->\n    exists x0:point_set X, net_cluster_point x x0.\nProof.\nRequire Import FiltersAndNets.\nintros.\ndestruct (compact_impl_filter_cluster_point\n  _ H (tail_filter x H0)) as [x0].\nexists x0.\napply tail_filter_cluster_point_impl_net_cluster_point with H0.\napply H1.\nQed.\n\nLemma net_cluster_point_impl_compact: forall X:TopologicalSpace,\n  (forall (I:DirectedSet) (x:Net I X), inhabited (DS_set I) ->\n    exists x0:point_set X, net_cluster_point x x0) ->\n  compact X.\nProof.\nintros.\napply filter_cluster_point_impl_compact.\nintros.\ndestruct (H _ (filter_to_net _ F)) as [x0].\ncut (inhabited (point_set X)).\nintro.\ndestruct H0 as [x].\nexists.\nsimpl.\napply Build_filter_to_net_DS_set with Full_set x.\napply filter_full.\nconstructor.\napply NNPP; intro.\ncontradiction (filter_empty _ F).\nreplace (@Empty_set (point_set X)) with (@Full_set (point_set X)).\napply filter_full.\napply Extensionality_Ensembles; split; red; intros.\ncontradiction H0.\nexists; exact x.\ndestruct H1.\n\nexists x0.\napply filter_to_net_cluster_point_impl_filter_cluster_point.\ntrivial.\nQed.\n\nRequire Export SeparatednessAxioms.\nRequire Export SubspaceTopology.\n\nLemma compact_closed: forall (X:TopologicalSpace)\n  (S:Ensemble (point_set X)), Hausdorff X ->\n  compact (SubspaceTopology S) -> closed S.\nProof.\nintros.\ndestruct (classic (Inhabited S)).\nassert (closure S = S).\napply Extensionality_Ensembles; split.\nred; intros.\ndestruct (net_limits_determine_topology _ _ H2) as [I0 [y []]].\npose (yS (i:DS_set I0) := exist (fun x:point_set X => In S x) (y i) (H3 i)).\nassert (inhabited (point_set (SubspaceTopology S))).\ndestruct H1.\nexists.\nexists x0; trivial.\nassert (inhabited (DS_set I0)) as HinhI0.\nred in H4.\ndestruct (H4 Full_set) as [i0]; auto with topology.\nconstructor.\npose proof (compact_impl_net_cluster_point\n  (SubspaceTopology S) H0 _ yS HinhI0).\ndestruct H6 as [[x0]].\napply net_cluster_point_impl_subnet_converges in H6.\ndestruct H6 as [J [y' []]].\ndestruct H6.\nassert (net_limit (fun j:DS_set J => y (h j)) x0).\napply continuous_func_preserves_net_limits with\n  (f:=subspace_inc S) (Y:=X) in H7.\nsimpl in H7.\nassumption.\napply continuous_func_continuous_everywhere.\napply subspace_inc_continuous.\nassert (net_limit (fun j:DS_set J => y (h j)) x).\napply subnet_limit with I0 y; trivial.\nconstructor; trivial.\nassert (x = x0).\nexact (Hausdorff_impl_net_limit_unique _ H _ _ H10 H9).\nrewrite H11; trivial.\ndestruct (H4 Full_set).\napply open_full.\nconstructor.\nexists; exact x1.\ndestruct H1.\n\napply closure_inflationary.\nrewrite <- H2; apply closure_closed.\n\nred.\nassert (Complement S = Full_set).\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nred; intro.\ncontradiction H1; exists x; trivial.\nrewrite H2; apply open_full.\nQed.\n\nLemma closed_compact: forall (X:TopologicalSpace) (S:Ensemble (point_set X)),\n  compact X -> closed S -> compact (SubspaceTopology S).\nProof.\nintros.\napply net_cluster_point_impl_compact.\nintros.\ndestruct (compact_impl_net_cluster_point _ H\n  _ (fun i:DS_set I => subspace_inc _ (x i))) as [x0].\ntrivial.\nassert (In S x0).\nrewrite <- (closure_fixes_closed S); trivial.\napply net_cluster_point_in_closure with\n  (2:=H2).\ndestruct H1 as [i0].\nexists i0.\nintros.\ndestruct (x j).\nsimpl.\ntrivial.\nexists (exist _ x0 H3).\nred; intros.\nred; intros.\ndestruct (subspace_topology_topology _ _ _ H4) as [V []].\nrewrite H7 in H5.\ndestruct H5.\nsimpl in H5.\ndestruct (H2 V H6 H5 i) as [j []]; trivial.\nexists j; split; trivial.\nrewrite H7.\nconstructor.\ntrivial.\nQed.\n\nLemma compact_image: forall {X Y:TopologicalSpace}\n  (f:point_set X->point_set Y),\n  compact X -> continuous f -> surjective f -> compact Y.\nProof.\nintros.\nred; intros.\npose (B := fun U:{U:Ensemble (point_set Y) | In C U} =>\n           inverse_image f (proj1_sig U)).\ndestruct (compactness_on_indexed_covers _ _ B H) as [subcover].\ndestruct a as [U].\nunfold B; simpl.\napply H0.\napply H2; trivial.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nassert (In (FamilyUnion C) (f x)).\nrewrite H3; constructor.\ninversion_clear H5 as [V].\nexists (exist _ V H6).\nunfold B; simpl.\nconstructor; trivial.\ndestruct H4.\n\nexists (Im subcover (@proj1_sig _ (fun U:Ensemble (point_set Y) => In C U))).\nrepeat split.\napply finite_image; trivial.\nred; intros V ?.\ndestruct H6 as [[U]].\nsimpl in H7.\ncongruence.\napply Extensionality_Ensembles; split; red; intros y ?.\nconstructor.\ndestruct (H1 y) as [x].\nassert (In (IndexedUnion\n  (fun a':{a' | In subcover a'} => B (proj1_sig a'))) x).\nrewrite H5; constructor.\ndestruct H8 as [[[U]]].\nexists U.\nsimpl in H8.\nexists (exist _ U i); trivial.\nunfold B in H8; simpl in H8.\ndestruct H8.\ncongruence.\nQed.\n\nLemma compact_Hausdorff_impl_normal_sep: forall X:TopologicalSpace,\n  compact X -> Hausdorff X -> normal_sep X.\nProof.\nintros.\nassert (T3_sep X).\nRequire Import ClassicalChoice.\ndestruct (choice (fun (xy:{xy:point_set X * point_set X |\n                  let (x,y):=xy in x <> y})\n  (UV:Ensemble (point_set X) * Ensemble (point_set X)) =>\n  match xy with | exist (x,y) i =>\n    let (U,V):=UV in\n  open U /\\ open V /\\ In U x /\\ In V y /\\ Intersection U V = Empty_set\n  end)) as\n[choice_fun].\ndestruct x as [[x y] i].\ndestruct (H0 _ _ i) as [U [V]].\nexists (U, V); trivial.\n\npose (choice_fun_U := fun (x y:point_set X)\n  (Hineq:x<>y) => fst (choice_fun (exist _ (x,y) Hineq))).\npose (choice_fun_V := fun (x y:point_set X)\n  (Hineq:x<>y) => snd (choice_fun (exist _ (x,y) Hineq))).\nassert (forall (x y:point_set X) (Hineq:x<>y),\n  open (choice_fun_U x y Hineq) /\\\n  open (choice_fun_V x y Hineq) /\\\n  In (choice_fun_U x y Hineq) x /\\\n  In (choice_fun_V x y Hineq) y /\\\n  Intersection (choice_fun_U x y Hineq) (choice_fun_V x y Hineq) = Empty_set).\nintros.\nunfold choice_fun_U; unfold choice_fun_V.\npose proof (H1 (exist _ (x,y) Hineq)).\ndestruct (choice_fun (exist _ (x,y) Hineq)).\nexact H2.\nclearbody choice_fun_U choice_fun_V; clear choice_fun H1.\n\nsplit.\napply Hausdorff_impl_T1_sep; trivial.\nintros.\npose proof (closed_compact _ _ H H1).\nassert (forall y:point_set X, In F y -> x <> y).\nintros.\ncongruence.\npose (cover := fun (y:point_set (SubspaceTopology F)) =>\n  let (y,i):=y in inverse_image (subspace_inc F)\n                     (choice_fun_V x y (H5 y i))).\ndestruct (compactness_on_indexed_covers _ _ cover H4) as [subcover].\ndestruct a as [y i].\napply subspace_inc_continuous.\napply H2.\napply Extensionality_Ensembles; split; red; intros y ?.\nconstructor.\nexists y.\ndestruct y as [y i].\nsimpl.\nconstructor.\nsimpl.\napply H2.\ndestruct H6.\n\nexists (IndexedIntersection\n  (fun y:{y:point_set (SubspaceTopology F) | In subcover y} =>\n    let (y,_):=y in let (y,i):=y in choice_fun_U x y (H5 y i))).\nexists (IndexedUnion\n  (fun y:{y:point_set (SubspaceTopology F) | In subcover y} =>\n    let (y,_):=y in let (y,i):=y in choice_fun_V x y (H5 y i))).\nrepeat split.\napply open_finite_indexed_intersection.\napply Finite_ens_type; trivial.\ndestruct a as [[y]].\napply H2.\napply open_indexed_union.\ndestruct a as [[y]].\napply H2.\ndestruct a as [[y]].\napply H2.\nred; intros y ?.\nassert (In (IndexedUnion\n  (fun y:{y:point_set (SubspaceTopology F) | In subcover y} =>\n    cover (proj1_sig y))) (exist _ y H8)).\nrewrite H7; constructor.\nremember (exist (In F) y H8) as ysig.\ndestruct H9 as [[y']].\nrewrite Heqysig in H9; clear x0 Heqysig.\nsimpl in H9.\ndestruct y' as [y'].\nsimpl in H9.\ndestruct H9.\nsimpl in H9.\nexists (exist _ (exist _ y' i0) i).\ntrivial.\n\napply Extensionality_Ensembles; split; auto with sets; red; intros y ?.\ndestruct H8.\ndestruct H8.\ndestruct H9.\npose proof (H8 a).\ndestruct a as [[y]].\nreplace (@Empty_set (point_set X)) with\n  (Intersection (choice_fun_U x y (H5 y i))\n                (choice_fun_V x y (H5 y i))).\nconstructor; trivial.\napply H2.\n\ndestruct (choice (fun (xF:{p:point_set X * Ensemble (point_set X) |\n                        let (x,F):=p in closed F /\\ ~ In F x})\n  (UV:Ensemble (point_set X) * Ensemble (point_set X)) =>\n  let (p,i):=xF in let (x,F):=p in\n  let (U,V):=UV in\n  open U /\\ open V /\\ In U x /\\ Included F V /\\\n  Intersection U V = Empty_set)) as [choice_fun].\ndestruct x as [[x F] []].\ndestruct H1.\ndestruct (H4 x F H2 H3) as [U [V]].\nexists (U,V); trivial.\n\npose (choice_fun_U := fun (x:point_set X) (F:Ensemble (point_set X))\n  (HC:closed F) (Hni:~ In F x) =>\n  fst (choice_fun (exist _ (x,F) (conj HC Hni)))).\npose (choice_fun_V := fun (x:point_set X) (F:Ensemble (point_set X))\n  (HC:closed F) (Hni:~ In F x) =>\n  snd (choice_fun (exist _ (x,F) (conj HC Hni)))).\nassert (forall (x:point_set X) (F:Ensemble (point_set X))\n  (HC:closed F) (Hni:~ In F x),\n  open (choice_fun_U x F HC Hni) /\\\n  open (choice_fun_V x F HC Hni) /\\\n  In (choice_fun_U x F HC Hni) x /\\\n  Included F (choice_fun_V x F HC Hni) /\\\n  Intersection (choice_fun_U x F HC Hni) (choice_fun_V x F HC Hni) =\n     Empty_set).\nintros.\npose proof (H2 (exist _ (x,F) (conj HC Hni))).\nunfold choice_fun_U; unfold choice_fun_V;\n  destruct (choice_fun (exist _ (x,F) (conj HC Hni))); trivial.\nclearbody choice_fun_U choice_fun_V; clear choice_fun H2.\nsplit.\napply H1.\nintros.\npose proof (closed_compact _ _ H H2).\nassert (forall x:point_set X, In F x -> ~ In G x).\nintros.\nintro.\nabsurd (In Empty_set x).\nred; destruct 1.\nrewrite <- H5; split; trivial.\n\npose (cover := fun x:point_set (SubspaceTopology F) =>\n  let (x,i):=x in inverse_image (subspace_inc F)\n                   (choice_fun_U x G H4 (H7 x i))).\ndestruct (compactness_on_indexed_covers _ _ cover H6) as [subcover].\ndestruct a as [x i].\napply subspace_inc_continuous.\napply H3.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nexists x.\ndestruct x.\nsimpl cover.\nconstructor.\nsimpl.\napply H3.\ndestruct H8.\n\nexists (IndexedUnion\n  (fun x:{x:point_set (SubspaceTopology F) | In subcover x} =>\n     let (x,i):=proj1_sig x in choice_fun_U x G H4 (H7 x i))).\nexists (IndexedIntersection\n  (fun x:{x:point_set (SubspaceTopology F) | In subcover x} =>\n     let (x,i):=proj1_sig x in choice_fun_V x G H4 (H7 x i))).\nrepeat split.\napply open_indexed_union.\ndestruct a as [[x]].\nsimpl.\napply H3.\napply open_finite_indexed_intersection.\napply Finite_ens_type; trivial.\ndestruct a as [[x]].\nsimpl.\napply H3.\nintros x ?.\nassert (In (@Full_set (point_set (SubspaceTopology F))) (exist _ x H10))\n  by constructor.\nrewrite <- H9 in H11.\nremember (exist _ x H10) as xsig.\ndestruct H11.\ndestruct a as [x'].\ndestruct x' as [x'].\nrewrite Heqxsig in H11; clear x0 Heqxsig.\nsimpl in H11.\ndestruct H11.\nsimpl in H11.\nexists (exist _ (exist _ x' i0) i).\nsimpl.\ntrivial.\ndestruct a as [x'].\nsimpl.\ndestruct x' as [x'].\nassert (Included G (choice_fun_V x' G H4 (H7 x' i0))) by apply H3.\nauto.\n\napply Extensionality_Ensembles; split; auto with sets; red; intros.\ndestruct H10.\ndestruct H10.\ndestruct H11.\npose proof (H11 a).\ndestruct a as [[x']].\nsimpl in H12.\nsimpl in H10.\nreplace (@Empty_set (point_set X)) with (Intersection\n  (choice_fun_U x' G H4 (H7 x' i))\n  (choice_fun_V x' G H4 (H7 x' i))).\nconstructor; trivial.\napply H3.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/topology/Compactness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6986271754167371}}
{"text": "Require Import Bool Arith List Cpdt.CpdtTactics.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nDefinition var := nat.\n\nInductive prop : Set :=\n| Var : var -> prop\n| Neg : prop -> prop\n| Conj : prop -> prop -> prop\n| Disj : prop -> prop -> prop.\n\nFixpoint propDenote (truth : var -> bool) (p : prop) : Prop :=\n  match p with\n  | Var v => if truth v then True else False\n  | Neg p' => ~ propDenote truth p'\n  | Conj p1 p2 => propDenote truth p1 /\\ propDenote truth p2\n  | Disj p1 p2 => propDenote truth p1 \\/ propDenote truth p2\n  end.\n\nNotation \"'Yes'\" := (left _ _).\nNotation \"'No'\" := (right _ _).\n\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). reflexivity. discriminate.\nDefined.\n\nDefinition decide : forall (truth : var -> bool) (p : prop),\n    {propDenote truth p} + {~ propDenote truth p}.\n  intros. induction p; crush. destruct (truth v); crush.\nDefined.\n\nNotation \"[ e ]\" := (exist _ e _).\nNotation \"x <- e1 ; e2\" :=\n  (match e1 with exist x _ => e2 end)\n  (right associativity, at level 60).\n\nDefinition negate : forall p : prop,\n    {p' : prop | forall truth, propDenote truth p <-> ~ propDenote truth p'}.\n  refine (fix F (p : prop) : {p' : prop | forall truth, propDenote truth p <-> ~ propDenote truth p'} :=\n            match p with\n            | Var v => [Neg (Var v)]\n            | Neg p => [p]\n            | Conj p1 p2 =>\n              p1' <- F p1;\n              p2' <- F p2;\n              [Disj p1' p2']\n            | Disj p1 p2 =>\n              p1' <- F p1;\n              p2' <- F p2;\n              [Conj p1' p2']\n            end); crush;\n    repeat (match goal with\n            | [i : forall truth : var -> bool, _ <-> _ |- _] =>\n              destruct (i truth); clear i\n            | [|- context[if ?E then _ else _]] =>\n              destruct E\n            end); crush.\n  destruct (decide truth p1'); crush.\nDefined.\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/0.4-2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6986127692654088}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) : natural := plus (Succ lf1) Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj81_coqofml_dHHhi0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6986127604880925}}
{"text": "\n(*partie 2.2*)\n(* ATTENTION !!!!!\nIl faut lancer coqide avec la cmd = coqide -impredicative-set*) \n(*L'identité polymorphe*)\n\n(*2.2.1*)\nDefinition tid : Set := forall T : Set, T -> T.\nDefinition id : tid := fun T:Set => fun x : T => x.\n\n(*TESTS OF IDENTITY*)\n(* 5 est nat? *)\nCompute id nat 5.\n(* true est boolean? *)\nCompute id bool true.\n(* BAD TEST | UNCOMMENT *)\n(*Compute id bool 0.*)\n\nDefinition nbtrue1 := \nfun b => match b with true => 1 | \nfalse => 0 end.\n\n(*Verif : la fonction rend bien un nat*)\nCompute id nat (nbtrue1 false).\nCompute id tid id.\n\n(*2.2.2*)\n(*booleans*)\nDefinition pbool : Set := forall T : Set, T -> T -> T.\n(*vrai*)\nDefinition ptr : pbool := fun T:Set => fun x:T => fun y:T => x .\n(*faux*)\nDefinition pfa : pbool := fun T:Set => fun (x:T) (y:T) => y.\nPrint ptr.\nPrint pfa.\n\n(*first negation*)\nDefinition cneg1 : pbool -> pbool := fun b => fun T:Set => fun x => fun y => b T y x.\n\nCompute cneg1 ptr.\nCompute cneg1 pfa.\n(*second negation*)\nDefinition cneg2 : pbool -> pbool:= fun b => b pbool pfa ptr.\n\nCompute cneg2 ptr.\nCompute cneg2 pfa.\n(*conj*)\nDefinition conjonc : pbool -> pbool -> pbool := fun a b => a pbool b a.\nCompute conjonc ptr pfa.\nCompute conjonc pfa ptr.\n\n(*disonj*)\nDefinition disjonc : pbool -> pbool -> pbool := fun a b => a pbool a b.\n\nCompute disjonc ptr pfa.\nCompute disjonc pfa ptr.\n\n\n(*3 si vrai. 5, sinon.*)\nDefinition foo35 : pbool -> nat := fun b => b nat 3 5.\nCompute foo35 ptr.\n\n(*BONUS : lui-meme*)\nDefinition bluimeme : pbool -> pbool := fun b => b pbool b b.\n\n(*2.2.3.1*)\n\n(*A -> B -> T) ->T*)\nDefinition pprod_nb : Set := forall T: Set, (nat -> bool -> T) -> T.\nDefinition pcpl_nb : nat -> bool -> pprod_nb := fun a b => fun T => fun k => k a b.\n\n(* (5,true) *)\nCompute pcpl_nb 5 true.\n(*2.2.3.2*)\nDefinition pprod_bn : Set := forall T: Set, (bool -> nat -> T) -> T.\nDefinition pcpl_bn : bool -> nat -> pprod_bn := fun a b => fun T => fun k => k a b.\n(* (true,5) *)\nCompute pcpl_bn true 5.\n\n(*2.2.3.3*)\nDefinition convertProd : pprod_nb -> pprod_bn := fun c => c pprod_bn (fun n b => pcpl_bn b n).\n(*TEST : (5,true) => (true, 5)*)\nDefinition c1 := pcpl_nb 5 true.\nDefinition res := convertProd c1.\nCompute c1.\nCompute res.\n(*produit universel*)\nDefinition pprod : Set -> Set -> Set := fun A B => forall T:Set, (A -> B -> T) -> T.\nDefinition pcpl : forall A B:Set, A -> B -> pprod A B := fun A B:Set => fun (a:A) (b:B) => fun T:Set => fun k:(A -> B -> T) => k a b.\n(* couple = (99,true) *)\nCompute pcpl nat bool 99 true.\n(* couple = (1,0) *)\nCompute pcpl nat nat 1 0.\n(* couple = (1,(3, si vrai, 5 sinon) *)\nCompute pcpl pbool nat ptr (foo35 ptr).\n\n\n(*Choix (Sommes de Types) *)\n(*On a juste implementé ça : A+B = ∀T, (A→T)→(B→T)→T.)*)\nDefinition psom (A B : Set) : Set := forall T:Set, (A -> T) -> (B -> T) -> T.\nDefinition inj1 (A B : Set) : A -> psom A B := fun a => fun T:Set => fun k1 : (A ->  T) => fun k2 : (B ->  T) => k1 a.\n(*Inspirée par inj1*)\nDefinition inj2 (A B : Set) : B -> psom A B := fun b => fun T:Set => fun k1 : (A ->  T) => fun k2 : (B ->  T) => k2 b.\n\n(*2.2.4  Entiers de Church avec typage polymorphe *)\n\n(*Base form*)\n(*On a re-utilisé les definitions de la partie1.v*)\nDefinition pnat := forall (T:Set), (T->T) -> (T->T).\nDefinition p0 : pnat := fun (T:Set) => fun (f:T->T) => fun (x:T) => x.\nDefinition pS : pnat -> pnat :=  fun (n: pnat) => fun (T : Set) f  x => f (n  T f x).\n(*Definition de 1 2 et 3 on utilisant pS*)\nDefinition p1 := pS p0.\nDefinition p2 := pS p1.\nDefinition p3 := pS p2.\n(*Definition cadd := \\n m·\\f x·n f(m f x).*)\nDefinition padd : pnat -> pnat -> pnat := fun n m => fun f x => n f (m f x ).\n(* 2 + 3 = 5 *)\nCompute padd p2 p3.\n(*Definition cmult := \\n m · \\f· n(m f).*)\nDefinition pmult : pnat -> pnat -> pnat := fun m n =>  fun T:Set => (fun f => n T (m T f)).\n(* 2 X 3 = 6 *)\nCompute pmult p2 p3.\n(*Definition ceq0 := \\n·\\x y· n(\\z·x) y.*)\nDefinition peq0 : pnat -> pbool := fun n => fun T:Set => fun (x:T) (y:T) => (n T (fun z => y) x).\n(* 3 X 0 == 0 ? *)\nCompute peq0 (pmult p3 p0).\n(* 3 == 0 ? *)\nCompute peq0  p3.\n\n(* special pplus *)\nDefinition pplus : pnat -> pnat -> pnat := fun n : pnat => fun m : pnat =>  n pnat pS m.\n(* Test : 1 + 3 *)\nCompute pplus p1 p3.\n\n(*prédécesseur : We did not implement it... No time :-( *)\n\n(* 2.2.5  Listes (bonus) *)\n(*On a fait que la premiere question.*)\n(*listen = ∀T, T→(pnat→T→T)→T.*)\nDefinition listen : Set := forall T: Set, T -> (pnat -> T -> T) -> T.\n(*liste A = ∀T, T→(A→T→T)→T.*)\n(*L'espace entre liste et A EST MANDATORY.*) \nDefinition liste A : Set := forall T: Set, T -> (A -> T -> T) -> T.\n(*pnil A :liste A = ΛT.λxTcA→T→T.x*)\nDefinition pnil A : liste A := fun T:Set => fun x : T => fun c : (A -> T -> T) =>x.\n(*pcons A :  A→ liste A →liste A = λaAq liste A.ΛT.λxTcA→T→T.c a(qTx c).*)\nDefinition pcons A : A -> liste A -> liste A :=  fun (a : A) (q : liste A) => fun T: Set => fun (x:T) (c : A -> T -> T)=> c a (q T x c).\n\n\n(*2.2.6  Super bonus : arbres binaires et tri par arbre binaire de recherche*)\n(*Reference*)\nDefinition arbin (A : Set) := forall T: Set, T -> (T -> A -> T -> T) -> T.\n(*arbre Vide.*)\nDefinition pV (A:Set) := fun T:Set=> fun x : T => fun c : T -> A -> T -> T=> x.\n(*le nœud comprenant un sous-arbre gauche, un habitant de A et un sous-arbre droit*)\nDefinition pN (A : Set):= fun (g : arbin A) (a : A) (d : arbin A) => fun T : Set  => fun(x : T) (c : T -> A -> T -> T) => c (g T x c) a (d T x c ). \n", "meta": {"author": "alaabenfatma", "repo": "LC_BinaryTree", "sha": "5a37ecf432c2f7475c62fba84fe6b898ec578220", "save_path": "github-repos/coq/alaabenfatma-LC_BinaryTree", "path": "github-repos/coq/alaabenfatma-LC_BinaryTree/LC_BinaryTree-5a37ecf432c2f7475c62fba84fe6b898ec578220/partie2.2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6986127604880925}}
{"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.\n\nSet Implicit Arguments.\n\nSection Tortoise_and_Hare.\n\n  Variables (X : Type) (eqdec : forall x y : X, { x = y } + { x <> y }).\n  \n  Infix \"=?\" := eqdec (at level 70).\n\n  Variable (f : X -> X) (x0 : X) \n           (Hx0 : exists τ, 0 < τ /\\ f↑τ x0 = f↑(2*τ) x0).\n  \n  (** The custom bar inductive predicate that serves as termination\n      criteria for tortoise_hare_rec *)\n  \n  Inductive bar_th x y : Prop :=\n    | in_bar_th_0 : x = y                  -> bar_th x y \n    | in_bar_th_1 : bar_th (f x) (f (f y)) -> bar_th x y.\n    \n  (** We give the explicit computational part using refine \n      and the proof of the logical part is delayed using _ \n  *)\n  \n  Fixpoint tort_hare_rec x y (H : bar_th x y) : { τ | f↑τ x = f↑(2*τ) y }.\n  Proof.\n    refine (match x =? y with\n             | left E  => exist _ 0 _\n             | right C => let (k,Hk) := tort_hare_rec (f x) (f (f y)) _ \n                          in  exist _ (S k) _\n           end).\n    * auto.\n    * inversion H; tauto.\n    * finish with Hk.\n  Defined.\n\n  (** Now we fix a starting point for which the iterations \n      of f ends into a non-empty loop, we use Hx0 *)\n  \n  Let bar_th_fx0_ffx0 : bar_th (f x0) (f (f x0)).\n  Proof.\n    destruct Hx0 as (k & H1 & H2).\n    apply in_bar_th_0 in H2.\n    revert k H1 H2; apply nat_rev_ind. \n    intros ? H; apply in_bar_th_1; finish with H.\n  Qed.\n  \n  Definition tortoise_hare : { τ | 0 < τ /\\ f↑τ x0 = f↑(2*τ) x0 }.\n  Proof.\n    refine (match tort_hare_rec bar_th_fx0_ffx0 with\n      | exist _ k Hk => exist _ (S k) _\n    end).\n    split; try omega; finish with Hk.\n  Defined.\n\n  Let tortoise_hare_tail_rec : \n    forall i x y, bar_th x y -> { k | i <= k /\\ f↑(k-i) x = f↑(2*(k-i)) y }.\n  Proof.\n    refine (fix loop i x y H { struct H } := \n           match x =? y with\n             | left E  => exist _ i _\n             | right C => match loop (S i) (f x) (f (f y)) _ with\n                            | exist _ k Hk => exist _ k _\n                          end\n           end).\n    * split; f_equal; auto; omega.\n    * inversion H; tauto.\n    * destruct Hk; split; try omega; finish with H1.\n  Qed.\n\n  Definition tortoise_hare_tail : { τ | 0 < τ /\\ f↑τ x0 = f↑(2*τ) x0 }.\n  Proof.\n    refine (let (k,Hk) := tortoise_hare_tail_rec 1 bar_th_fx0_ffx0 in exist _ k _).\n    destruct Hk as (? & Hk); split; try omega.\n    finish with Hk.\n  Defined.\n\nEnd Tortoise_and_Hare.\n\nCheck tortoise_hare.\nPrint Assumptions tortoise_hare.\nRecursive Extraction tortoise_hare.\n\nCheck tortoise_hare_tail.\nPrint Assumptions tortoise_hare_tail.\nExtraction tortoise_hare_tail.\n", "meta": {"author": "DmxLarchey", "repo": "The-Tortoise-and-the-Hare", "sha": "8aa3a897271cf8f61c9d9530bf9efd363eb2a574", "save_path": "github-repos/coq/DmxLarchey-The-Tortoise-and-the-Hare", "path": "github-repos/coq/DmxLarchey-The-Tortoise-and-the-Hare/The-Tortoise-and-the-Hare-8aa3a897271cf8f61c9d9530bf9efd363eb2a574/tortoise_hare.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6985654142565155}}
{"text": "Require Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Relations.Relation_Operators.\nRequire Import Coq.Relations.Operators_Properties.\nRequire Import Coq.Lists.List.\n\nRequire Import Setoid.\nRequire Import Lia.\nRequire Import Glib.Glib.\n\nRequire Export Coq.Relations.Relation_Definitions.\nRequire Export Coq.Relations.Relation_Operators.\n\n\n(* star - a reflexive transitive closure *)\nDefinition star {A} (R: relation A) : relation A := clos_refl_trans_n1 A R.\nNotation \"R ^*\" := (star R) (at level 5, format \"R ^*\").\n\nLtac star_notation := \n  repeat change (clos_refl_trans_n1 _ ?R) with (R^*) in *.\n\n\n(* seq - a transparent sequence of relation steps.\n   It is equivalent to the reflexive transitive closure, but is a `Type` rather than a `Prop`.\n *)\nReserved Notation \"R #*\" (at level 5, format \"R #*\").\nInductive seq {A} (R: relation A) : A -> A -> Type :=\n  | seq_refl : forall x,\n      R#* x x\n  | seq_step : forall x y z,\n      R y z ->\n      R#* x y ->\n      R#* x z\n  where \"R #*\" := (seq R).\n\n(* nseq - a length-indexed transition sequence *)\nReserved Notation \"R #\" (at level 5, format \"R #\").\nInductive nseq {A} (R: relation A) : nat -> A -> A -> Type :=\n  | nseq_refl : forall x,\n      R#0 x x\n  | nseq_step : forall n x y z,\n      R y z ->\n      R#n x y ->\n      R#(S n) x z\n  where \"R #\" := (nseq R).\nNotation \"R # n\" := (nseq R n) (at level 5, format \"R # n\").\n\n\n(* Length of a sequence in number of steps (not states) *)\nFixpoint seq_length {A} {R: relation A} {a a'} (seq: R#* a a') :=\n  match seq with \n  | seq_refl _ x => 0\n  | seq_step _ x y z r seq' => S (seq_length seq')\n  end.\n\nInductive in_seq {A} {R: relation A} {a}\n  : forall {a'}, A -> R#* a a' -> Prop :=\n  | in_seq_head : forall a' (seq: R#* a a'),\n      in_seq a' seq\n  | in_seq_tail : forall x x' y r seq,\n      in_seq y seq ->\n      in_seq y (seq_step R a x x' r seq).\n\nInductive in_seq_at {A} {R: relation A} {a}\n  : forall {a'}, A -> nat -> R#* a a' -> Prop :=\n  | in_seq_at_head : forall a' (seq: R#* a a'),\n      in_seq_at a' (seq_length seq) seq\n  | in_seq_at_tail : forall n x x' y r seq,\n      in_seq_at y n seq ->\n      in_seq_at y n (seq_step R a x x' r seq).\n\n\n(* This is an old, more complicated definition\n   TODO: rewrite in the style of in_seq\n *)\nInductive in_nseq {A} {R: relation A} {a}\n  : forall {n a'}, A -> R#n a a' -> Prop :=\n  | in_nseq_head_refl :\n      in_nseq a (nseq_refl R a)\n  | in_nseq_head_step : forall n x x' r p,\n      in_nseq x' (nseq_step R n a x x' r p)\n  | in_nseq_tail : forall n x x' y r p,\n      in_nseq y p ->\n      in_nseq y (nseq_step R n a x x' r p).\n\nInductive in_nseq_at {A} {R: relation A} {a}\n  : forall {n a'}, A -> nat -> R#n a a' -> Prop :=\n  | in_nseq_at_head_refl :\n      in_nseq_at a 0 (nseq_refl R a)\n  | in_nseq_at_head_step : forall n x x' r p,\n      in_nseq_at x' (S n) (nseq_step R n a x x' r p)\n  | in_nseq_at_tail : forall n m x x' y r p,\n      in_nseq_at y m p ->\n      in_nseq_at y m (nseq_step R n a x x' r p).\n\n\n(* Misc. definitions *)\n\nDefinition is_serial {A} (R: relation A) := forall a, exists b, R a b.\nDefinition serial A := {R: relation A | is_serial R}.\n\nDefinition serial_witness {A} (R: relation A) := forall a, {b | R a b}.\nDefinition serialT A := {R: relation A & serial_witness R}.\n\nDefinition rel_singleton {A} (x y : A): relation A :=\n  fun x' y' => x' = x /\\ y' = y -> True.\n\n\nSection BinaryRelationsProperties.\n\nContext {A: Type}.\nVariable R : relation A.\n\n(* star properties *)\n\nTheorem star_refl :\n  reflexive A R^*.\nProof using.\n  constructor.\nQed.\n\nTheorem star_trans : \n  transitive A R^*.\nProof using.\n  unfold transitive.\n  intros * Hxy Hyz.\n  induction Hyz.\n  - assumption.\n  - follows econstructor.\nQed.\n\nLemma star_lift : forall x y, \n  R x y ->\n  R^* x y.\nProof using.\n  intros * H.\n  econstructor.\n  - eassumption.\n  - constructor.\nQed.\n\nTheorem rt1n_star : forall x y,\n  clos_refl_trans_1n A R x y -> star R x y.\nProof.\n  intros * ?.\n  apply clos_rt_rtn1.\n  now apply clos_rt1n_rt.\nQed.\n\nTheorem star_rt1n : forall x y,\n  star R x y -> clos_refl_trans_1n A R x y.\nProof.\n  intros * ?.\n  apply clos_rt_rt1n.\n  now apply clos_rtn1_rt.\nQed.\n\nTheorem star_rt1n_trans : forall x y z,\n  R x y ->\n  R^* y z ->\n  R^* x z.\nProof using.\n  intros.\n  apply rt1n_star.\n  econstructor.\n  - eassumption.\n  - now apply star_rt1n.\nQed.\n\n\n(* seq properties *)\n\nTheorem seq__star : forall x y,\n  R#* x y ->\n  R^* x y.\nProof using.\n  intros * H.\n  induction H.\n  - constructor.\n  - follows econstructor.\nQed.\n\nTheorem star__seq : forall x y,\n  R^* x y ->\n  ‖R#* x y‖.\nProof using.\n  intros * H.\n  induction H.\n  - repeat constructor.\n  - find uninhabit.\n    constructor.\n    follows econstructor.\nQed.\n\nDefinition seq_singleton {x y} (r: R x y)\n  : R#* x y :=\n  seq_step R x x y r (seq_refl R x).\n\nDefinition seq_tail {x z} (r: R#* x z) (p: seq_length r > 0) : Σ y, R#* y z.\n  induction r.\n  - follows exfalso.\n  - destruct r0.\n    + exists x.\n      follows apply seq_singleton.\n    + forward IHr by (cbn; lia).\n      destruct exists IHr s.\n      follows exists s.\nDefined.\n\nDefinition seq_step_front x y z (step: R x y) (tail: R#* y z) : R#* x z.\n  induction tail.\n  - follows apply seq_singleton.\n  - eapply seq_step.\n    + exact r.\n    + tedious.\nDefined.\n\nTheorem destruct_seq_front : forall x z (s: R#* x z),\n  ⟨z, s⟩ = ⟨x, seq_refl R x⟩ \\/\n  exists y (r: R x y) (s': R#* y z), s = seq_step_front x y z r s'.\nProof using.\n  intros *.\n  induction s.\n  - follows left.\n  - right.\n    destruct or IHs.\n    + inject IHs.\n      follows exists z r (seq_refl R z).\n    + destruct IHs as (y' & r' & s' & ->).\n      follows exists y' r' (seq_step R y' y z r s').\nQed.\n\n(* Definition seq_rect_front : forall (P: forall x y, R#* x y -> Type),\n  (forall x, P x x (seq_refl R x)) ->\n  (forall x y z (r: R x y) (s: R#* y z), P y z s -> P x z (seq_step_front x y z r s)) ->\n  forall x y (s: R#* x y), P x y s.\nintros * H IH.\ninduction s.\n- assumption!.\n- todo.\nAdmitted. *)\n\nTheorem in_seq_first : forall x y (r: R#* x y),\n  in_seq x r.\nProof using.\n  intros *.\n  induction r.\n  - constructor.\n  - now constructor.\nQed.\n\nTheorem in_seq_at_0 : forall x y (r: R#* x y),\n  in_seq_at x 0 r.\nProof using.\n  intros *.\n  induction r.\n  - fold (seq_length (seq_refl R x)).\n    constructor.\n  - now constructor.\nQed.\n\nTheorem inv_in_seq_at_0 : forall x y (r: R#* x y) s,\n  in_seq_at s 0 r ->\n  s = x.\nProof using.\n  intros * H.\n  after induct! H as [z r|].\n  follows destruct r.\nQed.\n\nLemma in_seq_at_length {x z}: forall (r: R#* x z) y i,\n  in_seq_at y i r ->\n  i <= seq_length r.\nProof using.\n  tedious.\nQed.\n\nLemma inv_in_seq_at_length {x z}: forall (r: R#* x z) y,\n  in_seq_at y (seq_length r) r ->\n  y = z.\nProof using.\n  intros * Hin.\n  after invc! Hin.\n  simpl in *.\n  find (fun H => apply in_seq_at_length in H).\n  exfalso; lia.\nQed.\n\nTheorem in_seq_at_unique : forall x y (r: R#* x y) s s' i,\n  in_seq_at s i r ->\n  in_seq_at s' i r ->\n  s = s'.\nProof using.\n  intros * H H'.\n  max induction H.\n  - follows erewrite inv_in_seq_at_length.\n  - after invc! H'.\n    apply in_seq_at_length in H.\n    contradict H; simpl; lia.\nQed.\n\nLemma in_seq_at__in_seq {x y z}: forall (r: R#* x z) i,\n  in_seq_at y i r ->\n  in_seq y r.\nProof using.\n  tedious.\nQed.\n\nLemma in_seq__in_seq_at {x y z}: forall (r: R#* x z),\n  in_seq y r ->\n  exists i, in_seq_at y i r.\nProof using.\n  intros * H.\n  follows induction H.\nQed.\n\nLemma ex_in_seq_at_le_length {x z}: forall (r: R#* x z) i,\n  i <= seq_length r ->\n  exists y, in_seq_at y i r.\nProof using.\n  intros * ile.\n  induction r.\n  - follows inv ile.\n  - simpl! in ile.\n    after invc ile.\n    exists z.\n    change (S (seq_length r0)) with (seq_length (seq_step R x y z r r0)).\n    constructor.\nQed.\n\nLemma in_seq_at_succ_related {w z}: forall (r: R#* w z) x y i,\n  in_seq_at x i r ->\n  in_seq_at y (S i) r ->\n  R x y.\nProof using.\n  intros * Hin Hin'.\n  max induction Hin.\n  - apply in_seq_at_length in Hin'.\n    contradict Hin'; lia.\n  - after invc! Hin'.\n    simpl in H2.\n    inv H2.\n    apply inv_in_seq_at_length in Hin as <-.\n    assumption.\nQed.\n\nLemma ex_seq_prefix {x y z} : forall (r: R#* x z),\n  in_seq y r ->\n  exists prefix: R#* x y, \n    forall s i, in_seq_at s i prefix -> in_seq_at s i r.\nProof using.\n  tedious.\nQed.\n\nLemma ex_seq_at_prefix {x y z} : forall (r: R#* x z) n,\n  in_seq_at y n r ->\n  exists prefix: R#* x y, \n    seq_length prefix = n /\\\n    forall s i, in_seq_at s i prefix -> in_seq_at s i r.\nProof using.\n  intros * Hin.\n  induction Hin.\n  - follows define exists by assumption.\n  - follows destruct exists IHHin prefix.\nQed.\n\n(* Note equivalence to transitivity under Curry-Howard reflection to star *)\nDefinition seq_concat {x y z} (Rxy: R#* x y) (Ryz: R#* y z)\n  : R#* x z.\nProof using.\n  induction Ryz.\n  - assumption.\n  - econstructor.\n    + eassumption.\n    + find applyc.\n      assumption.\nDefined.\n\nTheorem seq_concat_refl : forall x y (r: R#* x y),\n  seq_concat (seq_refl R x) r = r.\nProof using.\n  intros *.\n  induction r.\n  - reflexivity.\n  - simpl.\n    now find rewrite.\nQed.  \n\nTheorem seq_concat_assoc : forall w x y z,\n  forall (a: R#* w x) (b: R#* x y) (c: R#* y z),\n    seq_concat (seq_concat a b) c =\n    seq_concat a (seq_concat b c).\nProof using.\n  intros *.\n  max induct c.\n  - reflexivity.\n  - simpl.\n    follows find rewrite.\nQed.\n\nTheorem in_seq__concat {x y z}: forall (a: R#* x y) (b: R#* y z) n,\n  in_seq n (seq_concat a b) <-> in_seq n a \\/ in_seq n b.\nProof using.\n  intros *.\n  split; intro H. \n  - induction b.\n    + simpl in H.\n      now left.\n    + simpl in *.\n      dependent invc H.\n      * right. constructor.\n      * specialize (IHb a H2); clear H2.\n        destruct IHb.\n       -- now left.\n       -- right. constructor. assumption.\n  - destruct H.\n    + induction b.\n      * assumption.\n      * simpl.\n        constructor.\n        now find apply.\n    + induction b.\n      * simpl.\n        inversion H; subst.\n        constructor.\n      * simpl.\n        dependent invc H.\n       -- constructor.\n       -- constructor.\n          now find apply.\nQed.\n\nTheorem in_seq_at__concat_l {x y z}: forall (a: R#* x y) (b: R#* y z) n i,\n  in_seq_at n i a -> in_seq_at n i (seq_concat a b).\nProof using.\n  intros * H.\n  induction b.\n  - assumption.\n  - simpl.\n    constructor.\n    now find applyc.\nQed.\n\nTheorem in_seq_at__concat_r {x y z}: forall (a: R#* x y) (b: R#* y z) n i,\n  in_seq_at n i b -> in_seq_at n (seq_length a + i) (seq_concat a b).\nProof using.\n  intros * H.\n  induction b.\n  - dependent invc H.\n    simpl.\n    rewrite PeanoNat.Nat.add_0_r.\n    constructor.\n  - simpl.\n    dependent invc H.\n    + clear IHb. \n      simpl.\n      match goal with \n      | |- in_seq_at _ ?i ?seq => \n          replace i with (seq_length seq)\n      end; [constructor|].\n      simpl.\n      rewrite PeanoNat.Nat.add_succ_r.\n      f_equal.\n      clear.\n      induction b; simpl; try find rewrite; lia.\n    + constructor.\n      now find apply.\nQed.\n\nLemma seq_length_concat {x y z}: forall (a: R#* x y) (b: R#* y z),\n  seq_length (seq_concat a b) = seq_length a + seq_length b.\nProof using.\n  intros *.\n  induction b; simpl; try find rewrite; lia.\nQed.\n\nDefinition seq_prepend (x y z: A):\n  R x y ->\n  R#* y z ->\n  R#* x z.\nProof using.\n  intros ? Ryz.\n  induction Ryz.\n  - now apply seq_singleton.\n  - econstructor.\n    + eassumption.\n    + now find apply.\nDefined.\n\n(* Isomorphic to seq. Sometimes, this reversed structure is more convenient\n   (Note the \"growth\" step prepends rather than appending to the end)\n*)\nInductive seq_rev : A -> A -> Type :=\n  | seq_rev_refl : forall x,\n      seq_rev x x\n  | seq_rev_step : forall x y z,\n      R x y ->\n      seq_rev y z ->\n      seq_rev x z.\n\nFixpoint seq_rev_length {a a'} (seqr: seq_rev a a') :=\n  match seqr with \n  | seq_rev_refl x => 0\n  | seq_rev_step x y z r seq' => S (seq_rev_length seq')\n  end.\n\nDefinition seq_rev_concat {x y z} (Rxy: seq_rev x y) (Ryz: seq_rev y z)\n  : seq_rev x z.\nProof using.\n  induction Rxy.\n  - assumption.\n  - econstructor.\n    + eassumption.\n    + find applyc.\n      assumption.\nDefined.\n\nDefinition seq__seq_rev {x y} (seq: R#* x y): seq_rev x y.\n  induction seq.\n  - constructor.\n  - eapply seq_rev_concat; [eassumption|].\n    econstructor.\n    + eassumption.\n    + constructor.\nDefined.\n\nDefinition seq_rev__seq {x y} (seqr: seq_rev x y): R#* x y.\n  induction seqr.\n  - constructor.\n  - eapply seq_concat; [|eassumption].\n    econstructor.\n    + eassumption.\n    + constructor.\nDefined.\n\nTheorem seq_rev_concat_refl : forall x y (r: seq_rev x y),\n  seq_rev_concat r (seq_rev_refl y) = r.\nProof using.\n  intros *.\n  induction r.\n  - reflexivity.\n  - simpl.\n    now find rewrite.\nQed.  \n\nTheorem seq_rev_concat_assoc : forall w x y z,\n  forall (a: seq_rev w x) (b: seq_rev x y) (c: seq_rev y z),\n    seq_rev_concat (seq_rev_concat a b) c =\n    seq_rev_concat a (seq_rev_concat b c).\nProof using.\n  intros *.\n  max induct a.\n  - reflexivity.\n  - simpl.\n    follows find rewrite.\nQed.\n  \nTheorem seq__seq_rev__concat {x y z}: forall (a: R#* x y) (b: R#* y z),\n  seq__seq_rev (seq_concat a b) = seq_rev_concat (seq__seq_rev a) (seq__seq_rev b).\nProof using.\n  intros *.\n  revert x a; induct b; intros.\n  - simpl.\n    now rewrite seq_rev_concat_refl.\n  - simpl seq_concat; simpl seq__seq_rev at 1.\n    find rewrite ->.\n    rewrite seq_rev_concat_assoc.\n    reflexivity.\nQed.\n\nTheorem seq_rev__seq__concat {x y z}: forall (a: seq_rev x y) (b: seq_rev y z),\n  seq_rev__seq (seq_rev_concat a b) = seq_concat (seq_rev__seq a) (seq_rev__seq b).\nProof using.\n  intros *.\n  revert z b; induct a; intros.\n  - simpl.\n    now rewrite seq_concat_refl.\n  - simpl seq_rev_concat; simpl seq_rev__seq at 1.\n    find rewrite ->.\n    rewrite <- seq_concat_assoc.\n    reflexivity.\nQed.\n\nDefinition ϕ_seq__seq_rev : forall x y,\n  R#* x y ≃> seq_rev x y.\nProof using.\n  intros *.\n  exists (@seq__seq_rev x y) (@seq_rev__seq x y).\n  split.\n  - intros *.\n    induct b.\n    + reflexivity.\n    + simpl.\n      rewrite seq__seq_rev__concat.\n      simpl.\n      now find rewrite.\n  - intros *.\n    induct a.\n    + reflexivity.\n    + simpl.\n      rewrite seq_rev__seq__concat.\n      simpl.\n      now find rewrite.\nDefined.\n\nTheorem isomorphic_seq__seq_rev : forall x y,\n  R#* x y ≃ seq_rev x y.\nProof using.\n  intros.\n  apply isomorphism__isomorphic.\n  apply ϕ_seq__seq_rev.\nQed.\n\n(* equivalent to in_seq under the obvious isomorphism *)\nInductive in_seq_rev {a} \n  : forall {a'}, A -> seq_rev a a' -> Prop :=\n  | in_seq_rev_head : forall a' (seqr: seq_rev a a'),\n      in_seq_rev a seqr\n  | in_seq_rev_tail : forall x x' y r seqr,\n      in_seq_rev y seqr ->\n      in_seq_rev y (seq_rev_step a x x' r seqr).\n\nInductive in_seq_rev_at {a} \n  : forall {a'}, A -> nat -> seq_rev a a' -> Prop :=\n  | in_seq_rev_at_head : forall a' (seqr: seq_rev a a'),\n      in_seq_rev_at a 0 seqr\n  | in_seq_rev_at_tail : forall n x x' y r seqr,\n      in_seq_rev_at y n seqr ->\n      in_seq_rev_at y (S n) (seq_rev_step a x x' r seqr).\n\n\nTheorem in_seq_rev_at__concat_l {x y z}: forall (a: seq_rev x y) (b: seq_rev y z) n i,\n  in_seq_rev_at n i a -> in_seq_rev_at n i (seq_rev_concat a b).\nProof using.\n  intros * H.\n  max induction a.\n  - follows inv H.\n  - simpl.\n    follows invc! H.\nQed.\n\nTheorem in_seq_rev_at__in_seq_at {x y z i} {seqr: seq_rev x z}:\n  in_seq_rev_at y i seqr ->\n  in_seq_at y i (seq_rev__seq seqr).\nProof using.\n  intros Hin.\n  max induction Hin.\n  - induction seqr.\n    + simpl.\n      apply in_seq_at_0.\n    + simpl.\n      apply in_seq_at__concat_l.\n      constructor.\n      apply in_seq_at_0.\n  - simpl.\n    change (S n) with (seq_length (seq_step R a a x r (seq_refl R a)) + n).\n    follows apply in_seq_at__concat_r.\nQed.\n\nTheorem in_seq_at__in_seq_rev_at__iso {x y z i} {seqr: seq_rev x z}:\n  in_seq_at y i ((ϕ_seq__seq_rev x z)⁻¹ seqr) ->\n  in_seq_rev_at y i seqr.\nProof using.\n  intros Hin.\n  max induct Hin.\n  - after induction seqr.\n    simpl.\n    follows rewrite seq_length_concat.\n  - change (seq_rev__seq ?x) with ((ϕ_seq__seq_rev _ _)⁻¹ x) in H0.\n    apply eq_cancel_right in H0.\n    especialize IHHin; forward IHHin by apply inv_cancel_iso.\n    simpl in H0;\n    change (seq__seq_rev ?x) with (ϕ_seq__seq_rev _ _ x) in H0.\n    subst.\n    follows apply in_seq_rev_at__concat_l.\nQed. \n\nTheorem in_seq_at__in_seq_rev_at {x y z i} {seqr: seq_rev x z}:\n  in_seq_at y i (seq_rev__seq seqr) ->\n  in_seq_rev_at y i seqr.\nProof using.\n  apply in_seq_at__in_seq_rev_at__iso.\nQed.\n\nTheorem in_seq_at__in_seq_rev_at__iso' {x y z i} {seq: R#* x z}:\n  in_seq_at y i seq ->\n  in_seq_rev_at y i (ϕ_seq__seq_rev x z seq).\nProof using.\n  iso ϕ_seq__seq_rev seq seqr.\n  rewrite iso_cancel_inv.\n  apply in_seq_at__in_seq_rev_at__iso.\nQed.\n\nTheorem in_seq_iso_in_seq_rev_flip : forall x y z,\n  forall b: seq_rev x y, in_seq_rev z b = in_seq z ((ϕ_seq__seq_rev x y)⁻¹ b).\nProof using.\n  intros *.\n  induct b; extensionality.\n  - simpl.\n    split; intro; find inversion; subst; constructor.\n  - split; intro H; simpl in *.\n    + apply in_seq__concat.\n      rewrite <- IHb.\n      dependent inv H.\n      * left.\n        repeat constructor.\n      * auto.\n    + apply in_seq__concat in H.\n      rewrite <- IHb in H.\n      destruct H.\n      * dependent inv H.\n       -- destruct b; repeat constructor.\n       -- inversion H3; subst.\n          repeat constructor.\n      * now constructor.\nQed.\n\nTheorem in_seq_iso_in_seq_rev : forall x y z,\n  iso_equiv (ϕ_seq__seq_rev x y) (@in_seq A R x y z) (@in_seq_rev x y z).\nProof using.\n  intros *.\n  rewrite iso_equiv_flip.\n  apply in_seq_iso_in_seq_rev_flip.\nQed.\n\nTheorem seq_length_iso_seq_rev_length : forall x y,\n  iso_equiv (ϕ_seq__seq_rev x y) seq_length seq_rev_length.\nProof using.\n  intros *.\n  rewrite iso_equiv_flip.\n  intros seqr.\n  after max induction seqr.\n  simpl.\n  rewrite seq_length_concat.\n  simpl.\n  follows f_equal.\nQed.\n\nLemma in_seq_rev_at_last : forall x y (seqr: seq_rev x y),\n  in_seq_rev_at y (seq_rev_length seqr) seqr.\nProof using.\n  tedious.\nQed.\n\n\n(* nseq properties *)\n\nDefinition nseq__seq {n} {x y}:\n  R#n x y ->\n  R#* x y.\nProof using.\n  intros * H.\n  induction H.\n  - constructor.\n  - econstructor; eassumption.\nDefined.\n\nDefinition seq__nseq {x y}:\n  R#* x y ->\n  {n & R#n x y}.\nProof using.\n  intros * H.\n  induction H.\n  - eexists. constructor.\n  - destruct exists IHseq n.\n    exists (S n).\n    econstructor; eassumption.\nDefined.\n\nTheorem in_nseq_at__in_nseq : forall x a b n m (r: R#n a b),\n  in_nseq_at x m r ->\n  in_nseq x r.\nProof using.\n  intros * H.\n  induction H; constructor.\n  assumption.\nQed.\n\nTheorem in_nseq__in_nseq_at : forall x a b n (r: R#n a b),\n  in_nseq x r ->\n  exists m, m <= n /\\ in_nseq_at x m r.\nProof using.\n  intros * H.\n  induction H.\n  - eexists.\n    split; [|constructor].\n    reflexivity.\n  - eexists.\n    split; [|constructor].\n    lia.\n  - destruct exists IHin_nseq m.\n    exists m.\n    destruct IHin_nseq.\n    split.\n    + lia.\n    + constructor.\n      assumption.\nQed. \n\nDefinition nseq_singleton {x y} (r: R x y) : R#1 x y.\n  tedious.\nDefined.\n\nDefinition nseq_prepend (x y z: A) n:\n  R x y ->\n  R#n y z ->\n  R#(S n) x z.\nProof using.\n  intros ? Ryz.\n  follows induction Ryz.\nDefined.\n\nEnd BinaryRelationsProperties.\n\n\n(* These must be declared outside the section to be visisble *)\n\nAdd Parametric Relation {A: Type} (R: relation A): A (star R)\n  reflexivity  proved by (star_refl R)\n  transitivity proved by (star_trans R)\n  as star_rel.\n\nArguments ϕ_seq__seq_rev {A R x y}.", "meta": {"author": "ku-sldg", "repo": "CTL", "sha": "75bb188ae2689baeb28d34a789fe839871c240fe", "save_path": "github-repos/coq/ku-sldg-CTL", "path": "github-repos/coq/ku-sldg-CTL/CTL-75bb188ae2689baeb28d34a789fe839871c240fe/Ctl/BinaryRelations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6985654074675448}}
{"text": "Require Import Ashley.Axioms.\nRequire Import Ashley.Category.\n\nClass Preorder (A:Type) :=\n{\n  within: A -> A -> Prop;\n  within_reflex: forall p, within p p;\n  within_trans: forall p q r, within q r -> within p q -> within p r\n}.\nNotation \"a >= b\" := (within b a).\nNotation \"a <= b\" := (within a b).\nNotation \"a > b\" := (~ within a b).\nNotation \"a < b\" := (~ within b a).\n\nInstance indexed_Preorder (I:Type) (A:Type) `{Preorder A} : Preorder (I -> A) :=\n{\n  within p q := forall i, within (p i) (q i)\n}.\nintros.\napply within_reflex.\nintros.\napply (within_trans (p i) (q i) (r i)).\napply H0.\napply H1.\nDefined.\n\nInstance within_Category (A:Type) `{Preorder A}: Category A :=\n{\n  hom := within;\n  id := within_reflex;\n  compose := within_trans\n}.\nintros.\napply proof_irrelevance.\nintros.\napply proof_irrelevance.\nintros.\napply proof_irrelevance.\nDefined.\n\nDefinition Preorder_Category {A} (po: Preorder A): Category A := @within_Category A po.\n\nClass PartialOrder (A:Type) `{Preorder A} :=\n{\n  within_antisym: forall p q, within p q -> within q p -> p = q\n}.\n\nInstance indexed_PartialOrder (I:Type) (A:Type) `{PartialOrder A} : PartialOrder (I -> A) :=\n{\n}.\nintros.\napply fun_ext.\nintros.\napply within_antisym.\napply H1.\napply H2.\nDefined.\n\nClass BoundedPartialOrder (A:Type) `{PartialOrder A} :=\n{\n  bottom: A;\n  bottom_within: forall (p:A), bottom <= p;\n  top: A;\n  top_without: forall (p:A), p <= top\n}.\n\nInstance indexed_BoundedPartialOrder (I:Type) (A:Type) `{BoundedPartialOrder A} : BoundedPartialOrder (I -> A) :=\n{\n  bottom i := bottom;\n  top i := top\n}.\nintros.\nunfold within.\nunfold indexed_Preorder.\nintros.\napply bottom_within.\nintros.\nunfold within.\nunfold indexed_Preorder.\nintros.\napply top_without.\nDefined.\n\n\nRequire Import Ashley.Proposition.\n\nInstance prop_Preorder: Preorder Prop :=\n{\n  within p q := p -> q\n}.\nintros.\nexact H.\nintros.\nfirstorder.\nDefined.\n\nInstance prop_PartialOrder: PartialOrder Prop :=\n{\n}.\nintros.\napply prop_ext.\nfirstorder.\nDefined.\n\nInstance prop_BoundedPartialOrder: BoundedPartialOrder Prop :=\n{\n  bottom := False;\n  top := True\n}.\nunfold within.\nunfold prop_PartialOrder.\nfirstorder.\nunfold within.\nunfold prop_PartialOrder.\nfirstorder.\nDefined.", "meta": {"author": "AshleyYakeley", "repo": "maths", "sha": "42d4de811802c553d8bf0dcd69902ea01dda9a3e", "save_path": "github-repos/coq/AshleyYakeley-maths", "path": "github-repos/coq/AshleyYakeley-maths/maths-42d4de811802c553d8bf0dcd69902ea01dda9a3e/coq/theory/PartialOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970685907242, "lm_q2_score": 0.793105941403651, "lm_q1q2_score": 0.6985653882702224}}
{"text": "Require Import Coq.Bool.Bool.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Lists.List.\nRequire Import language.\nRequire Import state.\nRequire Import util.\nImport ListNotations.\n\nFixpoint aeval (stoV: storeV) (stoF: storeF) (a:aexp) : nat :=\nmatch a with\n| ANum n => n\n| AId name => (stoV name)\n| APlus a1 a2 => (aeval stoV stoF a1) + (aeval stoV stoF a2)\n| AMult a1 a2 => (aeval stoV stoF a1) * (aeval stoV stoF a2)\n| AMinus a1 a2 => (aeval stoV stoF a1) - (aeval stoV stoF a2)\n| AFsize fname => length (stoF fname)\nend.\n\n\nFixpoint findbk (li:list nat) (loc:nat): option nat :=\nmatch li with\n| [] => None\n| x::xli => if (beq_nat loc 1) then Some x else (findbk xli (loc-1))\nend.\n\n\n\nFixpoint bkeval (stoV:storeV) (stoB:storeB) \n                (stoF:storeF) (bk:bkexp) : option nat :=\nmatch bk with\n| BKNum n => Some n\n| BKId name => Some (stoB name)\n| BKAddr fname a => findbk (stoF fname) (aeval stoV stoF a)\nend.\n\n\nFixpoint beval stoV stoB stoF (b:bexp) : option bool :=\nmatch b with\n| BTrue   => Some true\n| BFalse  => Some false\n| BEq a1 a2 => Some (beq_nat (aeval stoV stoF a1) (aeval stoV stoF a2))\n| BLe a1 a2 => Some (leb (aeval stoV stoF a1) (aeval stoV stoF a2))\n| BNot b1   =>(match (beval stoV stoB stoF b1) with\n               | None => None\n               | Some x => Some (negb x)\n               end)\n| BAnd b1 b2  =>(match (beval stoV stoB stoF b1), (beval stoV stoB stoF b2) with\n                 | None,_ => None\n                 | _,None => None\n                 | Some x1,Some x2 => Some (andb x1 x2)\n                 end)\n| BOr  b1 b2  =>(match (beval stoV stoB stoF b1), (beval stoV stoB stoF b2) with\n                 | None,_ => None\n                 | _,None => None\n                 | Some x1, Some x2 => Some (orb x1 x2)\n                 end)\n| BKeq bk1 bk2  =>(match (bkeval stoV stoB stoF bk1),\n                         (bkeval stoV stoB stoF bk2) \n                   with\n                   | None,_ => None\n                   | _,None => None\n                   | Some a1, Some a2 => (Some (beq_nat a1 a2))\n                   end)\n| BKle bk1 bk2  => (match (bkeval stoV stoB stoF bk1),\n                          (bkeval stoV stoB stoF bk2) \n                   with\n                   | None,_ => None\n                   | _,None => None\n                   | Some a1, Some a2 => (Some (leb a1 a2))\n                   end)\nend.\n\n\n(* auxiliary function *)\nDefinition beq_op_nat x y : bool :=\nmatch x,y with\n| None,None => true\n| Some n1,Some n2 => beq_nat n1 n2\n| _,_ => false\nend.\n\nFixpoint in_list (li:list (option nat)) (x:option nat) : bool :=\nmatch li with\n| [] => false\n| t::xli => if beq_op_nat t x then true else in_list xli x\nend.\n\nDefinition get_content (nli:list (option nat)) : list nat :=\nlet f := fun t => match t with\n                 | Some n => n\n                 | None => 0\n                 end\nin (map f nli).\n\nFixpoint all_none (opli:list (option nat)) : bool :=\nmatch opli with\n| [] => true\n| x::li => if beq_op_nat x None then all_none li\n           else false\nend.\n\nFixpoint h_unionB_many hB locli nli : heapB :=\nmatch locli,nli with\n| loc::locs,n::ns => h_unionB_many (h_updateB hB loc n) locs ns\n| [],[] => hB\n| _,_ => hB\nend.\n\n\n\n\n\n\n\n\n\n\n\nInductive big_step: command -> state -> ext_state -> Prop :=\n| E_Skip  : forall stat,\n              big_step CSkip stat (St stat)\n| E_Ass   : forall stoV stoB stoF hV hB x a n, (aeval stoV stoF a) = n ->\n              big_step (CAss x a) (stoV,stoB,stoF,hV,hB)\n                       (St ((st_updateV stoV x n),stoB,stoF,hV,hB))\n| E_Seq   : forall c1 c2 st0 st1 opst,\n              big_step c1 st0 (St st1) ->\n              big_step c2 st1 opst ->\n              big_step (CSeq c1 c2) st0 opst\n| E_Seq_Ab: forall c1 c2 st0,\n              big_step c1 st0 Abt ->\n              big_step (CSeq c1 c2) st0 Abt\n| E_IfTure: forall stoV stoB stoF hV hB opst b c1 c2,\n              beval stoV stoB stoF b = Some true ->\n              big_step c1 (stoV,stoB,stoF,hV,hB) opst ->\n              big_step (CIf b c1 c2) (stoV,stoB,stoF,hV,hB) opst\n| E_IfFalse: forall stoV stoB stoF hV hB opst b c1 c2,\n              beval stoV stoB stoF b = Some false ->\n              big_step c2 (stoV,stoB,stoF,hV,hB) opst ->\n              big_step (CIf b c1 c2) (stoV,stoB,stoF,hV,hB) opst\n| E_If_Ab : forall stoV stoB stoF hV hB b c1 c2,\n              beval stoV stoB stoF b = None ->\n              big_step (CIf b c1 c2) (stoV,stoB,stoF,hV,hB) Abt\n\n\n| E_WhileEnd : forall b stoV stoB stoF hV hB c,\n                 beval stoV stoB stoF b = Some false ->\n                 big_step (CWhile b c) (stoV,stoB,stoF,hV,hB) (St (stoV,stoB,stoF,hV,hB))\n\n| E_WhileLoop : forall stoV stoB stoF hV hB opst b c st,\n                  beval stoV stoB stoF b = Some true ->\n                  big_step c (stoV,stoB,stoF,hV,hB) (St st) ->\n                  big_step (CWhile b c) st opst ->\n                  big_step (CWhile b c) (stoV,stoB,stoF,hV,hB) opst\n| E_WhileLoop_Ab : forall stoV stoB stoF hV hB b c,\n                  beval stoV stoB stoF b = Some true ->\n                  big_step c (stoV,stoB,stoF,hV,hB) Abt ->\n                  big_step (CWhile b c) (stoV,stoB,stoF,hV,hB) Abt\n| E_While_Ab :  forall stoV stoB stoF hV hB b c,\n                  beval stoV stoB stoF b = None ->\n                  big_step (CWhile b c) (stoV,stoB,stoF,hV,hB) Abt\n\n| E_Cons : forall stoV stoB stoF hV hB a n x l,\n              aeval stoV stoF a = n ->\n              hV l = None ->\n              big_step (CCons x a) (stoV,stoB,stoF,hV,hB)\n                       (St ((st_updateV stoV x l),stoB,stoF,\n                            (h_updateV hV l n), hB))\n\n| E_Lookup : forall stoV stoB stoF hV hB x a1 l n,\n                aeval stoV stoF a1 = l ->\n                hV l = Some n ->\n                big_step (CLookup x a1) (stoV,stoB,stoF,hV,hB) \n                         (St ((st_updateV stoV x n),stoB,stoF,hV,hB))\n\n| E_Lookup_Ab : forall stoV stoB stoF hV hB x a1 l,\n                   aeval stoV stoF a1 = l ->\n                   hV l = None ->\n                   big_step (CLookup x a1) (stoV,stoB,stoF,hV,hB) Abt\n\n| E_Mutat : forall stoV stoB stoF hV hB a1 a2 n1 n2,\n                  aeval stoV stoF a1 = n1 ->\n                  aeval stoV stoF a2 = n2 ->\n                  in_domV n1 hV ->\n                  big_step (CMutat a1 a2) (stoV,stoB,stoF,hV,hB) \n                           (St (stoV,stoB,stoF,(h_updateV hV n1 n2),hB))\n\n| E_Mutat_Ab : forall stoV stoB stoF hV hB a1 a2 n1,\n                     aeval stoV stoF a1 = n1 ->\n                     hV n1 = None ->\n                     big_step (CMutat a1 a2) (stoV,stoB,stoF,hV,hB) Abt\n\n| E_Dispose : forall stoV stoB stoF hV hB a1 n1,\n                 aeval stoV stoF a1 = n1 ->\n                 in_domV n1 hV ->\n                 big_step\n                   (CDispose a1) (stoV,stoB,stoF,hV,hB)\n                   (St (stoV,stoB,stoF,(h_removeV hV n1),hB))\n\n| E_Dispose_Ab : forall stoV stoB stoF hV hB a1 n1,\n                    aeval stoV stoF a1 = n1 ->\n                    hV n1 = None ->\n                    big_step (CDispose a1) (stoV,stoB,stoF,hV,hB) Abt\n\n| E_Fcreate : forall stoV stoB stoF hV hB f bkli nli nlist locli xli,\n                 nli = map (bkeval stoV stoB stoF) bkli ->\n                 in_list nli None = false ->\n                 get_content nli = nlist ->\n                 length locli = length nli ->\n                 map hB locli = xli ->\n                 all_none xli = true ->\n                 big_step (CFcreate f bkli) (stoV,stoB,stoF,hV,hB)\n                          (St (stoV,stoB,(st_updateF stoF f locli),hV,\n                              (h_unionB_many hB locli nlist)))\n| E_Fcreate_Abt : forall stoV stoB stoF hV hB f bkli nli,\n                    nli = map (bkeval stoV stoB stoF) bkli ->\n                    in_list nli None = true ->\n                    big_step (CFcreate f bkli) (stoV,stoB,stoF,hV,hB) Abt\n\n| E_FcontentAppend : forall stoV stoB stoF hV hB f bkli nli nlist ff xli locli,\n                        nli = map (bkeval stoV stoB stoF) bkli ->\n                        in_list nli None = false ->\n                        get_content nli = nlist ->\n                        length locli = length nli ->\n                        map hB locli = xli ->\n                        all_none xli = true ->\n                        ff = stoF f ->\n                        big_step (CFcontentAppend f bkli) (stoV,stoB,stoF,hV,hB)\n                                 (St (stoV,stoB,\n                                     (st_updateF stoF f (ff ++ locli)),hV,\n                                     (h_unionB_many hB locli nlist)))\n\n| E_FcontentAppend_Abt : forall stoV stoB stoF hV hB f bkli nli,\n                          nli = map (bkeval stoV stoB stoF) bkli ->\n                          in_list nli None = true ->\n                          big_step (CFcontentAppend f bkli) \n                                   (stoV,stoB,stoF,hV,hB) Abt\n\n| E_FaddressAppend : forall stoV stoB stoF hV hB f1 f2 bkli nli nlist ff2,\n                        nli = map (bkeval stoV stoB stoF) bkli ->\n                        in_list nli None = false ->\n                        get_content nli = nlist ->\n                        ff2 = stoF f2 ->\n                        big_step (CFaddressAppend f1 f2 bkli) (stoV,stoB,stoF,hV,hB)\n                                 (St (stoV,stoB,\n                                     (st_updateF stoF f1 (ff2 ++ nlist)),hV,hB))\n\n| E_FaddressAppend_Abt : forall stoV stoB stoF hV hB f1 f2 bkli nli,\n                          nli = map (bkeval stoV stoB stoF) bkli ->\n                          in_list nli None = true ->\n                          big_step (CFaddressAppend f1 f2 bkli) \n                                   (stoV,stoB,stoF,hV,hB) Abt\n\n| E_Fdelete : forall stoV stoB stoF hV hB f,\n                big_step (CFdelete f) (stoV,stoB,stoF,hV,hB)\n                         (St (stoV,stoB,stoF,hV,hB))\n\n| E_Blookup : forall stoV stoB stoF hV hB b bk n v,\n                (bkeval stoV stoB stoF bk) = Some n->\n                hB n = Some v ->\n                big_step (CBlookup b bk) (stoV,stoB,stoF,hV,hB)\n                         (St (stoV,(st_updateB stoB b v),stoF,hV,hB))\n\n| E_Blookup_AbtBK : forall stoV stoB stoF hV hB b bk,\n                      (bkeval stoV stoB stoF bk) = None ->\n                      big_step (CBlookup b bk) (stoV,stoB,stoF,hV,hB) Abt\n\n| E_Blookup_AbtHp : forall stoV stoB stoF hV hB b bk n,\n                      (bkeval stoV stoB stoF bk) = Some n ->\n                      hB n = None ->\n                      big_step (CBlookup b bk) (stoV,stoB,stoF,hV,hB) Abt\n\n| E_Bass : forall stoV stoB stoF hV hB b bk n,\n              (bkeval stoV stoB stoF bk) = Some n ->\n              big_step (CBlookup b bk) (stoV,stoB,stoF,hV,hB)\n                       (St (stoV,(st_updateB stoB b n),stoF,hV,hB))\n\n| E_Bass_Abt : forall stoV stoB stoF hV hB b bk,\n                (bkeval stoV stoB stoF bk) = None ->\n                big_step (CBlookup b bk) (stoV,stoB,stoF,hV,hB) Abt\n\n| E_Bmutat : forall stoV stoB stoF hV hB bk1 bk2 n1 n2,\n                (bkeval stoV stoB stoF bk1) = Some n1 ->\n                (bkeval stoV stoB stoF bk2) = Some n2 ->\n                big_step (CBmutat bk1 bk2) (stoV,stoB,stoF,hV,hB)\n                         (St (stoV,stoB,stoF,hV,(h_updateB hB n1 n2)))\n\n| E_Bmutat_AbtBk1 : forall stoV stoB stoF hV hB bk1 bk2,\n                      (bkeval stoV stoB stoF bk1) = None ->\n                      big_step (CBmutat bk1 bk2) (stoV,stoB,stoF,hV,hB) Abt\n\n| E_Bmutat_AbtBk2 : forall stoV stoB stoF hV hB bk1 bk2 n1,\n                      (bkeval stoV stoB stoF bk1) = Some n1 ->\n                      (bkeval stoV stoB stoF bk2) = None ->\n                      big_step (CBmutat bk1 bk2) (stoV,stoB,stoF,hV,hB) Abt\n\n| E_Bdelete : forall stoV stoB stoF hV hB bk,\n                big_step (CBdelete bk) (stoV,stoB,stoF,hV,hB)\n                         (St (stoV,stoB,stoF,hV,hB)).\n\nNotation \"c1 '/' st '\\\\' opst\" := (big_step c1 st opst) \n                                  (at level 40, st at level 39).\n\n\n\n", "meta": {"author": "PKUTCS", "repo": "CSVerifi", "sha": "3def80d210c3dc5765c5527683b8f0284b52fed6", "save_path": "github-repos/coq/PKUTCS-CSVerifi", "path": "github-repos/coq/PKUTCS-CSVerifi/CSVerifi-3def80d210c3dc5765c5527683b8f0284b52fed6/semantic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6985120413308286}}
{"text": "Require Import Arith.\n\nDefinition Nat : Type :=\n  forall A : Type, (A -> A) -> (A -> A).\n\nDefinition NatPlus(n m : Nat) : Nat :=\n  fun A f x => n A f (m A f x).\n\nDefinition nat2Nat : nat -> Nat := nat_iter.\n\nDefinition Nat2nat(n : Nat) : nat := n _ S O.\n\nLemma NatPlus_plus :\n  forall n m, Nat2nat (NatPlus (nat2Nat n) (nat2Nat m)) = n + m.\nProof.\n  assert (forall n m : nat, nat_iter n S m = n + m).\n    intros.\n    induction n.\n    - reflexivity.\n    - simpl; apply eq_S; assumption.\n  - intros.\n  unfold nat2Nat; unfold Nat2nat; unfold NatPlus.\n  repeat rewrite H.\n  rewrite plus_0_r.\n  reflexivity.\nQed.\n", "meta": {"author": "spinylobster", "repo": "Coqex2014", "sha": "090f49c87abead6ea0b1c1a346817523efb777b0", "save_path": "github-repos/coq/spinylobster-Coqex2014", "path": "github-repos/coq/spinylobster-Coqex2014/Coqex2014-090f49c87abead6ea0b1c1a346817523efb777b0/第4回/18.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6985120257780197}}
{"text": "Require Import Bool ZArith micromega.Lia.\n\nFrom BY Require Import Matrix Divstep Zpower_nat Impl.\nFrom BY.Hierarchy Require Import Definitions BigOp.\n\nLocal Open Scope Z_scope.\nLocal Open Scope mat_scope.\nLocal Open Scope vec_scope.\n\nLocal Open Scope ring_scope.\nLocal Open Scope lmod_scope.\n\nImport Z.\n\n(* Notation big_mmult_rev := (fun n m f => @big_op_rev _ mmult I f n m). *)\n\nTheorem _9_1_1 d f g (n m : nat) : (m <= n)%nat -> Z.odd f = true ->\n    2 ^+ (n - m) ⋅ [ fn d f g n , gn d f g n ] ≡\n    big_mul_rev (fun i => Tn d f g i) m n ⋅ [ fn d f g m , gn d f g m ].\nProof.\n  revert m. induction n; intros.\n  - replace m with 0%nat by lia; auto_mat.\n  - destruct (Nat.eq_dec m (S n)).\n    + subst. rewrite big_op_rev_nil.\n\n      rewrite Nat.sub_diag.\n      auto_mat; lia. lia.\n    + rewrite <- minus_Sn_m. rewrite <- Zpower_nat_mul_r.\n      rewrite (left_act_assoc (⋅) Z.mul). rewrite Tn_transition.\n      rewrite scvec_vmult, scmat_vmult_swap.\n      rewrite IHn.\n      rewrite <- (left_act_assoc (⋅) [*]).\n      rewrite <- (big_op_rev_S_l [*] 1). reflexivity. all: try lia; assumption. Qed.\n\nTheorem _9_1_2 d f g (n m : nat) : (m <= n)%nat -> odd f = true ->\n    [ 1 , dn d f g n  ] ≡\n    big_mul_rev (fun i => Sn d f g i) m n ⋅ [ 1 , dn d f g m ].\nProof.\n  revert m. induction n; intros.\n  - replace m with 0%nat by lia. auto_mat.\n  - destruct (Nat.eq_dec m (S n)).\n    + subst. rewrite big_op_rev_nil. auto_mat. lia.\n    + rewrite Sn_transition. rewrite IHn with (m:=m).\n      rewrite <- (left_act_assoc (⋅) [*]). rewrite <- (big_op_rev_S_l [*] 1). reflexivity. all: try lia; assumption. 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/Section9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.698512020854395}}
{"text": "(* Alumno: Agustín Mista *)\n(* Fecha:        2/11/17 *)\n\n(* ------------------------------ *)\n(*          Ejercicio 1           *)\n(* ------------------------------ *)\nSection Ejercicio1.\n\n  Variable LEAL : Prop.        (* El general es leal *)\n  Variable OBEDECE : Prop.     (* El general obedece las órdenes *)\n  Variable INTELIGENTE : Prop. (* El general es inteligente *)\n  Variable COMPRENDE : Prop.   (* El general comprende las órdenes *)\n\n\n  (* Si el general era leal, habría obedecido las órdenes. *)\n  Hypothesis H1 : LEAL -> OBEDECE. \n\n  (* Si el general era inteligente, las habría comprendido (las órdenes). *)\n  Hypothesis H2 : INTELIGENTE -> COMPRENDE. \n\n  (* O el general desobedeció las órdenes o no las comprendió. *)\n  Hypothesis H3 : ~OBEDECE \\/ ~COMPRENDE.\n\n  (* Luego, el general era desleal o no era inteligente. *)\n  Lemma lemma1 : ~LEAL \\/ ~INTELIGENTE.\n  Proof.\n    unfold not in *.\n    elim H3; [left | right]; intros; apply H; [apply H1 | apply H2]; assumption.\n  Qed.\n  \nEnd Ejercicio1.\n\n(* ------------------------------ *)\n(*          Ejercicio 2           *)\n(* ------------------------------ *)\nSection Ejercicio2.\n\n  Require Import Classical.\n\n  Variable C : Set.\n  Variable P : C -> C -> Prop.\n\n  Lemma lemma2 : (exists x y : C, P x y) \\/ ~(exists x : C, P x x).\n  Proof.\n    unfold not in *.\n    elim classic with (P := exists x y : C, P x y).\n    - left. assumption.\n    - right. intros. elim H. elim H0. intros. exists x. exists x. assumption.\n  Qed.\n\nEnd Ejercicio2.\n\n(* ------------------------------ *)\n(*          Ejercicio 3           *)\n(* ------------------------------ *)\nSection Ejercicio3.\n\n  Variable U : Set.\n  Variable a : U.\n  Variables P Q R T : U -> Prop.\n\n  (* 3.1 *)\n  Lemma Ej3_1 : (forall x : U, P x -> Q x) -> P a -> Q a.\n  Proof.\n    intros. exact (H a H0).\n  Qed.\n\n  (* 3.2 *)\n  Lemma Ej3_2 : (forall x : U, P x -> Q x) -> (forall x : U, Q x -> R x)\n                -> (forall x : U, P x -> R x).\n  Proof.\n    intros. exact (H0 x (H x H1)).\n  Qed.\n\n  (* 3.3 *)\n  Lemma Ej3_3 : (forall x : U, Q x) \\/ (forall y : U, T y)\n                -> forall z : U, Q z \\/ T z.\n  Proof.\n    intros. elim H; intros; [left | right]; exact (H0 z).\n  Qed.\n \nEnd Ejercicio3.\n\n(* ------------------------------ *)\n(*          Ejercicio 4           *)\n(* ------------------------------ *)\nSection Ejercicio4.\n\n  Parameter ABnat : forall n : nat, Set.\n\n  (* 4.1 *)\n  Parameter null : ABnat O.\n\n  (* 4.2 *)\n  Parameter add : forall n m: nat, ABnat n -> nat -> ABnat m -> ABnat (n+m+1).\n\n  (* 4.3 *)\n  Definition leftTree : ABnat 1 := add 0 0 null 7 null.  \n  Definition rightTree : ABnat 1 := add 0 0 null 9 null.  \n  Definition myTree : ABnat 3 := add 1 1 leftTree 8 rightTree.  \n \nEnd Ejercicio4.", "meta": {"author": "agustinmista", "repo": "coq", "sha": "b88431c1bed91cf0d9a69f5a058504edd19482ce", "save_path": "github-repos/coq/agustinmista-coq", "path": "github-repos/coq/agustinmista-coq/coq-b88431c1bed91cf0d9a69f5a058504edd19482ce/parcial/parcial1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6985119206072512}}
{"text": "Require Export A003induction.\n\nInductive natprod : Type :=\n  pair : nat -> nat -> natprod.\n\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\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\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.\nQed.\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intro p.\n  destruct p.\n  reflexivity.\nQed.\n\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intro.\n  destruct p.\n  reflexivity.\nQed.\n\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  intro.\n  destruct p.\n  reflexivity.\nQed.\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\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)\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\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 oddmembers (l:natlist) : natlist :=\n  match l with\n    | nil => nil\n    | h :: t => match oddb h with\n                 | false => oddmembers t\n                 | true => h :: oddmembers t\n               end\n  end.\n\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\nDefinition countoddmembers (l:natlist) : nat :=\n  length (oddmembers l).\n\n\nExample test_countoddmembers1:\n  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    | h1 :: t1 => match l2 with\n                    | [] => l1\n                    | h2 :: t2 => h1 :: h2 :: alternate t1 t2\n                  end\n  end.\n\n\nExample test_alternate1:\n  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\nDefinition bag := natlist.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n    | [] => 0\n    | h :: t => match (beq_nat h v) with\n                  | true => S (count v t)\n                  | false => count v t\n                end\n  end.\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\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 bge_nat (n m:nat) : bool :=\n  negb (blt_nat n m).\n\nDefinition member (v:nat) (s:bag) : bool :=\n  (bge_nat (count v s) 1).\n\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\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n    | [] => []\n    | h :: t => match (beq_nat v h) with\n                  | true => t\n                  | false => h :: remove_one v t\n                end\n  end.\n\n\n\nExample test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one2: count 5 (remove_one 5 [2;1;4;1]) = 0.\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    | 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\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 (s__1:bag) (s__2:bag) : bool :=\n  match s__1 with\n    | [] => true\n    | h :: t => match count h s__2 with\n                 | 0 => false\n                 | _ => subset t (remove_one h s__2)\n               end\n  end.\n\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 bag_add_count: forall (b : bag) (i : nat),\n  count i (add i b) = S (count i b).\nProof.\n  intros.\n  destruct b.\n  Case \"b = []\".\n    replace (add i []) with [i].\n    replace (count i []) with 0.\n    simpl.\n    replace (beq_nat i i) with true.\n    reflexivity.\n    SCase \"beq_nat i i = true\".\n      rewrite <- beq_nat_refl.\n      reflexivity.\n    SCase \"0 = count i []\".\n      reflexivity.\n    SCase \"[i] = add i []\".\n      reflexivity.\n\n  Case \"b = add i b\".\n    replace (add i (n :: b)) with (i :: n :: b).\n    replace (count i (i :: n :: b)) with\n      (S (count i (n :: b))).\n    reflexivity.\n    SCase \"S (count i (n :: b)) = count i (i :: n :: b)\".\n      simpl.\n      rewrite <- beq_nat_refl.\n      reflexivity.\n    SCase \"i :: n :: b = add i (n :: b)\".\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  intro.\n  destruct l.\n  reflexivity.\n  simpl. 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'].\n  Case \"l1 = nil\".\n    reflexivity.\n  Case \"l1 = cons n l1'\".\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros l1 l2.\n  induction l1 as [| n l1'].\n  reflexivity.\n  simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nFixpoint snoc (l:natlist) (v:nat) : natlist :=\n  match l with\n    | [] => [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.\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    (* This is the tricky case.  Let's begin as usual\n       by simplifying. *)\n    simpl.\n    (* Now we seem to be stuck: the goal is an equality\n       involving snoc, but we don't have any equations\n       in either the immediate context or the global\n       environment that have anything to do with snoc!\n\n       We can make a little progress by using the IH to\n       rewrite the goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAbort.\n\n\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.\n  reflexivity.\n  simpl. rewrite <- IHl. reflexivity.\nQed.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intro l.\n  induction l.\n  reflexivity.\n  simpl. rewrite length_snoc. rewrite IHl. reflexivity.\nQed.\n\nTheorem app_nil_end : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intro l.\n  induction l.\n  reflexivity.\n  simpl. rewrite IHl. reflexivity.\nQed.\n\nLemma rev_snoc_rev : forall t : natlist, forall h : nat,\n                       rev (snoc (rev t) h) = h :: rev (rev t).\nProof.\n  intros.\n  induction t.\n  reflexivity.\n  simpl.\n\n  replace (rev (snoc (rev t) n)) with (n :: (rev (rev t))).\nAbort.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n  snoc l n = l ++ [n].\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  simpl. rewrite IHl. reflexivity.\nQed.\n\nLemma cons_rev : forall n : nat, forall l : natlist,\n                   n :: rev l = rev (l ++ [n]).\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  simpl.\n  rewrite <- IHl.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intro l.\n  induction l as [| h t].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = h :: t\".\n    simpl.\n    replace (rev (snoc (rev t) h)) with (h :: rev (rev t)).\n    rewrite IHt.\n    reflexivity.\n    SCase \"h :: rev (rev t) = rev (snoc (rev t) h)\".\n      rewrite IHt.\n      rewrite snoc_append.\n      rewrite <- cons_rev.\n      rewrite IHt.\n      reflexivity.\nQed.\n\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 app_nil_r : forall l : natlist,\n                    l ++ [] = l.\nProof.\n  induction l. reflexivity. 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 as [| h1 t1].\n  Case \"l1 = []\".\n    simpl.\n    rewrite app_nil_r.\n    reflexivity.\n  Case \"l1 = h1 :: t1\".\n    simpl.\n    rewrite snoc_append.\n    rewrite IHt1.\n    rewrite app_assoc.\n    rewrite snoc_append.\n    reflexivity.\nQed.\n\n\nLemma cons_app_assoc : forall h : nat, forall l1 l2 : natlist,\n                         (h :: l1) ++ l2 = h :: l1 ++ l2.\nProof. intros. reflexivity. Qed.\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 [| h1 t1].\n  Case \"l1 = []\".\n    reflexivity.\n  Case \"l1 = h1 :: t1\".\n    rewrite cons_app_assoc.\n    induction h1 as [| h1'].\n    SCase \"h1 = 0\".\n      simpl.\n      rewrite IHt1.\n      reflexivity.\n    SCase \"h1 = S h1'\".\n      simpl.\n      rewrite IHt1.\n      reflexivity.\nQed.\n\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n    | [], [] => true\n    | h1 :: t1, [] => false\n    | [], h2 :: t2 => false\n    | h1 :: t1, h2 :: t2 =>\n      (andb (beq_nat h1 h2) (beq_natlist t1 t2))\n  end.\n\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\nExample test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\nExample test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  intro.\n  induction l.\n  reflexivity.\n  simpl.\n  rewrite <- beq_nat_refl.\n  rewrite <- IHl.\n  reflexivity.\nQed.\n\n\nTheorem count_member_nonzero : forall (s : bag),\n  ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n  reflexivity.\nQed.  (* WHAT THE ****!! YOU'RE SO AMAZING COQ!! *)\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  intro.\n  induction s.\n  Case \"s = []\". reflexivity.\n  Case \"s = n :: s\".\n    induction n.\n    SCase \"n = 0\".\n      simpl.\n      rewrite ble_n_Sn.\n      reflexivity.\n    SCase \"n = S n\".\n      simpl.\n      rewrite IHs.\n      reflexivity.\nQed.\n\n\nTheorem bag_count_sum: forall s1 s2 : bag,\n  count 0 (sum s1 s2) = count 0 s1 + count 0 s2.\nProof.\n  intros.\n  induction s1, s2.\n  Case \"s1 = [], s2 = []\". reflexivity.\n  Case \"s1 = [], s2 = n :: s2\". reflexivity.\n  Case \"s1 = n :: s1, s2 = []\".\n    induction n.\n    SCase \"n = 0\".\n      rewrite plus_0_r.\n      rewrite app_nil_r.\n      reflexivity.\n    SCase \"n = S n\".\n      rewrite plus_0_r.\n      rewrite app_nil_r.\n      reflexivity.\n  Case \"s1 = n0 :: s1, s2 = n :: s2\".\n    induction n0, n; (simpl; rewrite IHs1; reflexivity).\n(*\n    induction n0, n.\n    SCase \"n0 = n = 0\".\n      simpl. rewrite IHs1.\n      reflexivity.\n    SCase \"n0 = 0, n = S n\".\n      simpl. rewrite IHs1.\n      reflexivity.\n    SCase \"n0 = S n0, n = 0\".\n      simpl. rewrite IHs1.\n      reflexivity.\n    SCase \"n0 = S n0, n = S n\".\n      simpl. rewrite IHs1.\n      reflexivity.\n*)\nQed.\n\n(* this question is a four-star exercise.\n\n  my idea is to apply induction on l1 and l2, then deny all false assumptions:\n   - l1 = [], l2 <> []\n   - l1 <> [], l1 = []\n  and prove the true assumptions:\n   - l1 = l2 = []\n   - l1 = l2 <> []\n\n  currently i have no idea about how to cope with such false hypotheses.\n *)\nTheorem rev_injective: forall (l1 l2 : natlist),\n                         rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros.\n  assert (rev (rev l1) = rev (rev l2)).\n  rewrite H. reflexivity.\n\n  rewrite rev_involutive in H0.\n  rewrite rev_involutive in H0.\n  assumption.\nQed.\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n 0 with\n               | true => Some a\n               | false => index (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\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 hd_opt (l : natlist) : natoption :=\n  match l with\n    | nil => None\n    | a :: _ => Some a\n  end.\n\n\nExample test_hd_opt1 : hd_opt [] = None.\nProof. reflexivity. Qed.\nExample test_hd_opt2 : hd_opt [1] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\nProof. reflexivity. Qed.\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_opt l).\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  reflexivity.\nQed.\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n  | empty : dictionary\n  | record : nat -> nat -> dictionary -> dictionary.\n\nDefinition insert (key value : nat) (d : dictionary) : 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\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n  (find k (insert k v d)) = Some v.\nProof.\n  intros.\n  induction d.\n  Case \"d = {}\".\n    simpl.\n    rewrite <- beq_nat_refl.\n    reflexivity.\n  Case \"d = (k:v)::d\".\n    simpl.\n    rewrite <- beq_nat_refl.\n    reflexivity.\nQed.\n\nTheorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),\n  beq_nat m n = false -> find m d = find m (insert n o d).\nProof.\n  intros.\n  simpl.\n  rewrite H.\n  reflexivity.\nQed.\n\nEnd Dictionary.\n", "meta": {"author": "shouya", "repo": "thinking-dumps", "sha": "bfe50272459ddfca95de74a1857e2e649218584e", "save_path": "github-repos/coq/shouya-thinking-dumps", "path": "github-repos/coq/shouya-thinking-dumps/thinking-dumps-bfe50272459ddfca95de74a1857e2e649218584e/software-foundations/A004list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321843145404, "lm_q2_score": 0.8670357598021707, "lm_q1q2_score": 0.69851191304824}}
{"text": "(*\n  10152160137 陈弈君 homeowork 9\n*)\n\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Export IndProp.\n\n(* 1 *)\nPrint le.\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  - Print le. apply le_S. apply IHle.\nQed.\n\n(* 2 *)\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. apply H1.\nQed.\n\n(* 3 *)\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros. induction a.\n  - simpl. apply O_le_n.\n  - simpl. apply n_le_m__Sn_le_Sm. apply IHa.\nQed.\n\n(* 4 *)\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n  unfold lt. intros. split.\n  - induction H. apply n_le_m__Sn_le_Sm. \n    + apply le_plus_l.\n    + apply le_S. apply IHle.\n  - induction H.\n    + apply n_le_m__Sn_le_Sm. rewrite -> plus_comm. apply le_plus_l.\n    + apply le_S. apply IHle.\nQed.\n\n(* 5 *)\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  unfold lt. intros. apply le_S. apply H.\nQed.", "meta": {"author": "yijunc", "repo": "FunctionalProgramming", "sha": "b3f585f6a39e114c8cd2fc5ae872f713777a9154", "save_path": "github-repos/coq/yijunc-FunctionalProgramming", "path": "github-repos/coq/yijunc-FunctionalProgramming/FunctionalProgramming-b3f585f6a39e114c8cd2fc5ae872f713777a9154/homework9_10152160137.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.6985119128367966}}
{"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.Rtrigo_def.\nRequire Reals.Rpower.\nRequire BuiltIn.\nRequire real.Real.\n\nImport Rtrigo_def.\nImport Rpower.\n\n(* Why3 comment *)\n(* exp is replaced with (Reals.Rtrigo_def.exp x) by the coq driver *)\n\n(* Why3 goal *)\nLemma Exp_zero : ((Reals.Rtrigo_def.exp 0%R) = 1%R).\nexact exp_0.\nQed.\n\nRequire Import Exp_prop.\n\n(* Why3 goal *)\nLemma Exp_sum : forall (x:R) (y:R),\n  ((Reals.Rtrigo_def.exp (x + y)%R) = ((Reals.Rtrigo_def.exp x) * (Reals.Rtrigo_def.exp y))%R).\nexact exp_plus.\nQed.\n\n(* Why3 comment *)\n(* log is replaced with (Reals.Rpower.ln x) by the coq driver *)\n\n(* Why3 goal *)\nLemma Log_one : ((Reals.Rpower.ln 1%R) = 0%R).\nexact ln_1.\nQed.\n\n(* Why3 goal *)\nLemma Log_mul : forall (x:R) (y:R), ((0%R < x)%R /\\ (0%R < y)%R) ->\n  ((Reals.Rpower.ln (x * y)%R) = ((Reals.Rpower.ln x) + (Reals.Rpower.ln y))%R).\nintros x y (Hx,Hy).\nnow apply ln_mult.\nQed.\n\n(* Why3 goal *)\nLemma Log_exp : forall (x:R),\n  ((Reals.Rpower.ln (Reals.Rtrigo_def.exp x)) = x).\nexact ln_exp.\nQed.\n\n(* Why3 goal *)\nLemma Exp_log : forall (x:R), (0%R < x)%R ->\n  ((Reals.Rtrigo_def.exp (Reals.Rpower.ln x)) = x).\nexact exp_ln.\nQed.\n\n(* Why3 assumption *)\nDefinition log2 (x:R): R := ((Reals.Rpower.ln x) / (Reals.Rpower.ln 2%R))%R.\n\n(* Why3 assumption *)\nDefinition log10 (x:R): R :=\n  ((Reals.Rpower.ln x) / (Reals.Rpower.ln 10%R))%R.\n\n", "meta": {"author": "ssaavedra", "repo": "why3", "sha": "e28f4cda05925849c1c203f56b9f9b49e4bfe5b4", "save_path": "github-repos/coq/ssaavedra-why3", "path": "github-repos/coq/ssaavedra-why3/why3-e28f4cda05925849c1c203f56b9f9b49e4bfe5b4/lib/coq/real/ExpLog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.6985119110251357}}
{"text": "From Coq Require Export NArith List.\nFrom Coq Require Import Arith Sorting Orders OrdersEx Lia.\nImport ListNotations.\n\nAdd Search Blacklist \"N_as\".\n\n#[global] Open Scope N_scope.\n\nNotation \"'input' x ',' .. ',' y\" := (cons x .. (cons y nil) ..)\n  (at level 200, x constr at level 0).\n\nDefinition example := input\n16,1,2,0,4,2,7,1,2,14\n.\n\nModule NTotalOrder := OTF_to_TTLB N_as_OT. \nModule SortN := Sort NTotalOrder.\n\nDefinition median (xs : list N) : N :=\n  match skipn (length xs / 2)%nat xs with\n  | [] => 0\n  | x :: _ => x\n  end.\n\nDefinition sum_N : list N -> N := fold_right N.add 0%N.\n\n(* |x-y| *)\nDefinition dist (x y : N) : N := if x <=? y then y - x else x - y.\n\nDefinition solve (xs : list N) : N :=\n  let xs := SortN.sort xs in\n  sum_N (map (dist (median xs)) xs).\n\n(* Compute solve example. *)\n\nDefinition dist2 (x y : N) : N :=\n  let d := dist x y in\n  d * (d + 1) / 2.\n\n(* Cost to move everyone starting at positions [xs] to the same position [y]. *)\nDefinition fuel2 (xs : list N) (y : N) : N :=\n  sum_N (map (dist2 y) xs).\n\nFixpoint searchMin (n : nat) (f : N -> N) (low width : N) : N * N :=\n  match n with O => (0, 0) | S n =>\n  let il := width / 2 in\n  let xl := low + il in\n  let xr := low + il + 1 in\n  let fl := f xl in\n  let fr := f xr in\n  match 1 <? width with\n  | true =>\n    if fl <=? fr then searchMin n f low il\n    else searchMin n f xr (width - il - 1)\n  | false =>\n    if (0 =? width)%N || (fl <=? fr)%N then (xl, fl) else (xr, fr)\n  end\n  end.\n\nFixpoint maximum (xs : list N) : N :=\n  match xs with\n  | [] => 0\n  | [x] => x\n  | x :: xs => N.max x (maximum xs)\n  end.\n\nDefinition solve2 (xs : list N) : N :=\n  let f n := fuel2 xs n in\n  let m := maximum xs in\n  snd (searchMin (S (N.to_nat m)) f 0 m).\n\n(* Compute solve2 example. *)\n\nDefinition solve12 (xs : list N) : N * N := (solve xs, solve2 xs).\n\nDefinition Convex (f : N -> N) : Prop :=\n  forall i j k, (j+k) * f (i+j) <= k * f i + j * f (i+j+k).\n\nDefinition LocallyConvex (f : N -> N) : Prop :=\n  forall i, 2 * f (i+1) <= f i + f (i+2).\n\nDefinition Predecreasing (f : N -> N) : Prop :=\n  forall i j, i < j -> f j <= f i -> forall k, k <= i -> f i <= f k.\n\nDefinition Postincreasing (f : N -> N) : Prop :=\n  forall i j, i < j -> f i <= f j -> forall k, j <= k -> f j <= f k.\n\nDefinition VShaped (f : N -> N) : Prop := Predecreasing f /\\ Postincreasing f.\n\nLemma cancel_add_sub : forall a b c, c <= b -> (a + c) + (b - c) = a + b.\nProof.\n  intros; rewrite N.add_sub_assoc; lia.\nQed.\n\nLtac forward H :=\n  match type of H with\n  | (?Y -> _) => let Z := fresh in assert (Z : Y); [ | specialize (H Z) ]\n  end.\n\nLemma searchMin_sound n f\n  : forall low width, width < N.of_nat n ->\n    let x := searchMin n f low width in\n    low <= fst x <= low + width\n      /\\ snd x = f (fst x).\nProof.\n  induction n; cbn [searchMin]; intros; [ lia | ].\n  rewrite Nat2N.inj_succ in H.\n  destruct (N.ltb_spec 1 width).\n  - assert (HH : width / 2 < width).\n    { apply N.div_lt_upper_bound; lia. }\n    destruct (_ <=? _).\n    { eapply Morphisms_Prop.and_impl_morphism; [ | exact (fun X => X) | apply IHn; lia ].\n      intros ?; lia. }\n    { eapply Morphisms_Prop.and_impl_morphism; [ | exact (fun X => X) | apply IHn ].\n      { eapply Morphisms_Prop.and_impl_morphism.\n        { red; apply N.le_trans. remember (width / 2). lia. }\n        { refine (fun X => N.le_trans _ _ _ X _). lia. } }\n      eapply N.le_lt_trans.\n      { apply N.sub_le_mono_r. apply N.le_sub_l. }\n      lia. }\n  - destruct (N.eqb_spec 0 width).\n    { subst width; cbn. rewrite N.add_0_r. split; [ split | ]; reflexivity. }\n    destruct (_ <=? _) eqn:E; cbn; split; try reflexivity.\n    all: apply N.le_1_r in H0; destruct H0 as [-> | ->]; cbn; lia.\nQed.\n\nLemma searchMin_correct n f (Hf : VShaped f)\n  : forall low width,\n    width < N.of_nat n ->\n    forall i, i <= width -> snd (searchMin n f low width) <= f (low+i).\nProof.\n  induction n; [ (* contradiction *) lia | ]. intros; cbn [searchMin].\n  rewrite Nat2N.inj_succ in H.\n  destruct (N.ltb_spec 1 width).\n  - assert (HH : width / 2 < width).\n    { apply N.div_lt_upper_bound; lia. }\n    assert (coIH : width / 2 < N.of_nat n) by lia.\n    destruct (N.leb_spec (f (low + width / 2)) (f (low + width / 2 + 1))).\n    + specialize (IHn low (width / 2) coIH).\n      destruct (N.leb_spec i (width / 2)).\n      { apply IHn; assumption. }\n      { etransitivity; [ apply IHn; reflexivity | ].\n        rewrite H2.\n        eapply (proj2 Hf); [ | apply H2 | ]; lia. }\n    + specialize (IHn (low + width / 2 + 1) (width - width / 2 - 1)).\n      forward IHn.\n      { eapply N.le_lt_trans.\n        { apply N.sub_le_mono_r. apply N.le_sub_l. }\n        lia. }\n      destruct (N.ltb_spec i (width / 2 + 1)).\n      { etransitivity; [ apply (IHn 0); lia | ].\n        rewrite N.add_0_r.\n        apply N.lt_le_incl in H2. rewrite H2.\n        eapply (proj1 Hf); [ | apply H2 | ]; lia. }\n      { replace i with (width / 2 + 1 + (i - (width / 2 + 1))) by lia.\n        rewrite 2 N.add_assoc. apply IHn. lia. }\n  - destruct (N.eqb_spec 0 width); cbn.\n    { subst width; cbn. apply N.le_0_r in H0. subst. reflexivity. }\n    destruct (N.leb_spec (f (low + width / 2)) (f (low + width / 2 + 1))) as [e | e]; cbn.\n    all: apply N.le_1_r in H1; destruct H1 as [-> | ->]; cbn; try contradiction.\n    all: apply N.le_1_r in H0; destruct H0 as [-> | ->]; cbn.\n    all: cbn in e; try rewrite N.add_0_r in *; try reflexivity; lia.\nQed.\n\nLemma Convex_additive f g : Convex f -> Convex g -> Convex (fun i => f i + g i).\nProof.\n  unfold Convex; intros Hf Hg i j k. specialize (Hf i j k). specialize (Hg i j k). lia.\nQed.\n\nLemma Convex_constant i : Convex (fun _ => i).\nProof.\n  unfold Convex; lia.\nQed.\n\nLemma Convex_summative {A} (f : A -> N -> N)\n  : (forall z, Convex (f z)) -> forall xs, Convex (fun i => sum_N (map (fun x => f x i) xs)).\nProof.\n  intros Hf; induction xs; cbn.\n  - apply Convex_constant.\n  - apply Convex_additive; auto.\nQed.\n\nLemma div_mul : forall n m, n mod m = 0 -> n / m * m = n.\nProof.\n  intros. rewrite (N.div_mod' n m) at 2. rewrite H, N.add_0_r. lia.\nQed.\n\nLemma conseq_even : forall n, (n * (n+1)) mod 2 = 0.\nProof.\n  intros n. assert (H := N.mod_bound_pos n 2). destruct H as [_ H]; [lia ..| ].\n  apply N.lt_le_pred in H.\n  apply N.le_1_r in H.\n  rewrite <- N.mul_mod_idemp_l by lia.\n  destruct H as [ H | H ]; rewrite H.\n  - reflexivity.\n  - rewrite N.mul_1_l. rewrite <- N.add_mod_idemp_l by lia. rewrite H. reflexivity.\nQed.\n\nLemma minus_minus m n p : n <= m -> p <= n -> m - n + p = m - (n - p).\nProof.\n  lia.\nQed.\n\nLemma LocallyConvex_dist2_2 : forall z, LocallyConvex (fun i => dist2 i z).\nProof.\n  unfold Convex, dist2, dist. intros z i.\n  repeat lazymatch goal with\n    | [ |- context [ ?x <=? ?y ] ] => destruct (N.leb_spec x y); cbn - [N.add N.sub N.mul]\n    end.\n  all: try lia.\n  all: apply (N.mul_le_mono_pos_r _ _ 2); [ lia | ].\n  all: rewrite (N.mul_add_distr_r _ _ 2).\n  all: rewrite <- !(N.mul_assoc _ _ 2).\n  all: rewrite !div_mul by apply conseq_even.\n  all: try lia.\n  - rewrite minus_minus, N.add_sub by lia.\n    replace (z - (i+1)) with ((z-i)-1) by lia.\n    replace (z - (i+2) + 1) with ((z-i)-1) by lia.\n    replace (z - (i+2)) with ((z-i)-2) by lia.\n    rewrite ?(N.mul_add_distr_l (z-i)), ?(N.mul_add_distr_r (z-i)), ?(N.mul_sub_distr_l (z-i)), ?(N.mul_sub_distr_r (z-i)).\n    remember ((z-i) * (z-i)) as ZZ.\n    lia.\n  - replace z with (i+1) by lia. lia.\n  - replace z with i by lia. lia.\nQed.\n\nInstance Proper_mul_le : Proper (N.le ==> N.le ==> N.le) N.mul.\nProof.\n  unfold Proper, respectful. auto using N.mul_le_mono.\nQed.\n\nInstance Proper_add_le : Proper (N.le ==> N.le ==> N.le) N.add.\nProof.\n  unfold Proper, respectful. auto using N.add_le_mono.\nQed.\n\nLemma add_twice n : n + n = 2 * n.\nProof.\n  lia.\nQed.\n\nLemma Convex_LocallyConvex f : LocallyConvex f -> Convex f.\nProof.\n  unfold LocallyConvex, Convex. intros Hf.\n  intros i j k; revert i j; induction k as [ | k IH ] using N.peano_ind; intros i j.\n  - rewrite N.mul_0_l, !N.add_0_r. lia.\n  - rewrite !N.add_succ_r, N.mul_succ_l.\n    etransitivity; [ rewrite <- N.add_le_mono_r; apply IH | ].\n    enough (j * f (i + j + k) + f (i + j) <= f i + j * f (N.succ (i + j + k))) by lia.\n    clear IH.\n    revert i j; induction k as [ | k IH ] using N.peano_ind; intros i j.\n    + rewrite N.add_0_r, <- N.mul_succ_l.\n      induction j as [ | j IH] using N.peano_ind.\n      * rewrite N.add_0_r, !N.mul_0_l. lia.\n      * rewrite (N.add_le_mono_r _ _ (N.succ j * f (i + N.succ j))).\n        rewrite N.mul_succ_l. rewrite N.add_shuffle0, add_twice, N.mul_shuffle3, N.add_succ_r, <- (N.add_1_r (i + j)).\n        rewrite (Hf (i+j)).\n        rewrite N.mul_add_distr_l, IH. rewrite <- N.add_1_r.\n        replace (N.succ (i + j + 1)) with (i + j + 2) by lia. lia.\n    + rewrite (N.add_le_mono_r _ _ (j * f (i + j + N.succ k))).\n      rewrite N.add_shuffle0, add_twice, N.mul_shuffle3.\n      replace (i + j + N.succ k) with (i + j + k + 1) by lia.\n      rewrite Hf.\n      replace (N.succ (i + j + k + 1)) with (i + j + k + 2) by lia.\n      rewrite !N.mul_add_distr_l.\n      rewrite N.add_shuffle0.\n      rewrite IH.\n      replace (N.succ (i + j + k)) with (i + j + k + 1) by lia.\n      lia.\nQed.\n\nLemma Postincreasing_Convex f : Convex f -> Postincreasing f.\nProof.\n  unfold Convex, Postincreasing; intros Hf i j Eij Fij k Ejk. revert Fij.\n  replace k with (j + (k - j)) in * by lia; generalize (k-j).\n  replace j with (i + (N.pred (j - i) + 1)) in * by lia; generalize (N.pred (j-i)).\n  clear j k Eij Ejk. intros j k. intros Fj.\n  specialize (Hf i (j + 1) k).\n  rewrite N.mul_add_distr_r in Hf.\n  rewrite Fj in Hf.\n  rewrite (N.add_comm (_ * _)) in Hf.\n  rewrite <- N.add_le_mono_l in Hf.\n  rewrite <- N.mul_le_mono_pos_l in Hf by lia.\n  lia.\nQed.\n\nLemma Predecreasing_Convex f : Convex f -> Predecreasing f.\nProof.\n  unfold Convex, Predecreasing; intros Hf i j Eij Fij k Ejk. revert Fij.\n  replace j with (i + (N.pred (j - i) + 1)) in * by lia; generalize (N.pred (j-i)).\n  replace i with (k + (i - k)) in * by lia; generalize (i-k).\n  clear i j Eij Ejk. intros i j. intros Fj.\n  specialize (Hf k i (j+1)).\n  rewrite N.mul_add_distr_r in Hf.\n  rewrite Fj in Hf.\n  rewrite (N.add_comm (_ * _)) in Hf.\n  rewrite <- N.add_le_mono_r in Hf.\n  rewrite <- N.mul_le_mono_pos_l in Hf by lia.\n  lia.\nQed.\n\nLemma VShaped_Convex f : Convex f -> VShaped f.\nProof.\n  constructor.\n  - apply Predecreasing_Convex; auto.\n  - apply Postincreasing_Convex; auto.\nQed.\n\nLemma Convex_fuel2 : forall z, Convex (fuel2 z).\nProof.\n  intros z; apply Convex_summative.\n  intros z'; apply Convex_LocallyConvex, LocallyConvex_dist2_2.\nQed.\n\nTheorem solve2_correct xs\n  : exists i, solve2 xs = fuel2 xs i /\\ forall j, j <= maximum xs -> fuel2 xs i <= fuel2 xs j.\nProof.\n  unfold solve2.\n  exists (fst (searchMin (S (N.to_nat (maximum xs))) (fuel2 xs) 0 (maximum xs))).\n  assert (Hmax : forall i, i < N.of_nat (S (N.to_nat i))) by lia.\n  refine ((fun I J => conj I (J I)) _ _).\n  - apply (searchMin_sound _ _ _ _ (Hmax _)).\n  - intros E j Hj. rewrite <- E. apply searchMin_correct with (low := 0).\n    + apply VShaped_Convex, Convex_fuel2.\n    + apply Hmax.\n    + apply Hj.\nQed.\n", "meta": {"author": "Lysxia", "repo": "advent-of-coq-2021", "sha": "1416cf87898d4991fa918e8d1142f45fbde269e9", "save_path": "github-repos/coq/Lysxia-advent-of-coq-2021", "path": "github-repos/coq/Lysxia-advent-of-coq-2021/advent-of-coq-2021-1416cf87898d4991fa918e8d1142f45fbde269e9/src/aoc07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.6985119047443794}}
{"text": "(** An Ssreflect Tutorial *)\n\n(** http://hal.archives-ouvertes.fr/docs/00/40/77/78/PDF/RT-367.pdf  *)\n\nRequire Import ssreflect ssrbool eqtype ssrnat ssrfun.\n\n(** 3 Arithmetic for Euclidean division *)\n(** ユーグリッド互除法 *)\n\n(* 3.2 Deﬁnitions *)\n\nFixpoint edivn_rec (d m q : nat) : nat*nat :=\n  if m - d is m'.+1 then edivn_rec d m' q.+1 else (q, m).\nEval compute in edivn_rec 3 7 1.            (* (2,3) *)\n\nDefinition edivn_rec'' d :=\n  fix loop (m q : nat) {struct m} :=\n  if m - d is m'.+1 then loop m' q.+1 else (q, m).\nEval compute in edivn_rec'' 3 7 1.            (* (2,3) *)\n\nDefinition edivn m d :=                     (* 商と余 *)\n  if d > 0 then edivn_rec d.-1 m 0 else (0, m).\nEval compute in edivn 7 3.\n\nDefinition edivn_rec2 d := fix loop (m q : nat) {struct m} := (* 不使用 *)\n  if m - (d - 1) is m'.+1 then loop m' q.+1 else (q, m).\nEval compute in edivn_rec2 4 7 1.            (* (2,3) *)\n\nDefinition edivn2 m d :=                    (* 不使用 *)\n  if d > 0 then edivn_rec2 d m 0 else (0, m).\n\nCoInductive edivn_spec (m d : nat) : nat * nat -> Type :=\n  EdivnSpec q r of (m = q * d + r) & ((d > 0) ==> (r < d)) :\n    edivn_spec m d (q, r).\nEval compute in (EdivnSpec 7 3 2 1).       (* 7 / 3 = 2 ... 1 *)\n(* :  7 = 2 * 3 + 1 -> (0 < 3) ==> (1 < 3) -> edivn_spec 7 3 (2, 1) *)\n\n(* 3.3 Results *)\n\nLemma edivnP : forall m d, edivn_spec m d (edivn m d).\nProof.\n  rewrite /edivn => m [|d] //=; rewrite -{1}[m]/(0 * d.+1 + m).\n  elim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //=; rewrite ltnS => le_mn.\n  rewrite subn_if_gt; case: ltnP => [// | le_dm].\n  rewrite -{1}(subnK le_dm) -addnS addnA.\n  rewrite addnAC -mulSnr.                   (* addnAC を追加した。  *)\n  apply (IHn (m - d) q.+1).                 (* apply: IHn でもよい。 *)\n  apply: leq_trans le_mn; exact: leq_subr.\nQed.\n\nLemma edivn_eq : forall d q r, r < d -> edivn (q * d + r) d = (q, r).\nProof.\n  move=> d q r lt_rd; have d_pos: 0 < d by exact: leq_trans lt_rd.\n  case: edivnP lt_rd => q' r'; rewrite d_pos /=.\n    wlog: q q' r r' / q <= q' by case (ltnP q q'); last symmetry; eauto.\n  rewrite leq_eqVlt; case: eqP => [-> _|_] /=; first by move/addnI->.\n    rewrite -(leq_pmul2r d_pos); move/leq_add=> Hqr Eqr _; move/Hqr {Hqr}.\n    by rewrite addnS ltnNge mulSn -addnA Eqr addnCA addnA leq_addr.\nQed.\nEval compute in edivn 7 3.                  (* (2,1) *)\nEval compute in edivn (2 * 3 + 1) 3.        (* (2,1) *)\n\n\n(* 3.4 Parametric type families and alternative speciﬁcations *)\n(* edivn_spec とだいたい同じ *)\nCoInductive edivn_spec_right : nat -> nat -> nat * nat -> Type :=\n  EdivnSpec_right m d q r of m = q * d + r & (d > 0) ==> (r < d) :\n    edivn_spec_right m d (q, r).\nEval compute in (EdivnSpec_right 7 3 2 1).  (* 7 / 3 = 2 ... 1 *)\n(* :  7 = 2 * 3 + 1 -> (0 < 3) ==> (1 < 3) -> edivn_right 7 3 (2, 1) *)\n\nCoInductive edivn_spec_left (m d : nat)(qr : nat * nat) : Type :=\n  EdivnSpec_left of m = qr.1 * d + qr.2 & (d > 0) ==> (snd qr < d) :\n    edivn_spec_left m d qr.\nEval compute in (EdivnSpec_left 7 3 (2,1)).  (* 7 / 3 = 2 ... 1 *)\n(* : 7 = (2, 1).1 * 3 + (2, 1).2 ->\n       (0 < 3) ==> ((2, 1).2 < 3) -> edivn_spec_left 7 3 (2, 1) *)\n\nLemma edivnP_right' : forall m d, edivn_spec_right m d (edivn m d).\nProof.\n  (* 証明は、edivnP と同じ。 *)\n  rewrite /edivn => m [|d] //=; rewrite -{1}[m]/(0 * d.+1 + m).\n  elim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //=; rewrite ltnS => le_mn.\n  rewrite subn_if_gt; case: ltnP => [// | le_dm].\n  rewrite -{1}(subnK le_dm) -addnS addnA.\n  rewrite addnAC -mulSnr.                   (* addnAC を追加した。  *)\n  apply (IHn (m - d) q.+1).                 (* apply: IHn でもよい。 *)\n  apply: leq_trans le_mn; exact: leq_subr.\nQed.\n\n(* ProofCafe yoshihiro503 による。 *)\nLemma edivnP_right : forall m d, edivn_spec_right m d (edivn m d).\nProof.\nCheck edivnP.\n move=> m d.\n case: (edivnP m d) => q r eq_m_dqr impl_0d_rd.\n by apply: EdivnSpec_right.\nQed.\n\nLemma edivnP_left' : forall m d, edivn_spec_left m d (edivn m d).\nProof.\n  (* 証明は、edivnP と同じ。 *)\n  rewrite /edivn => m [|d] //=; rewrite -{1}[m]/(0 * d.+1 + m).\n  elim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //=; rewrite ltnS => le_mn.\n  rewrite subn_if_gt; case: ltnP => [// | le_dm].\n  rewrite -{1}(subnK le_dm) -addnS addnA.\n  rewrite addnAC -mulSnr.                   (* addnAC を追加した。  *)\n  apply (IHn (m - d) q.+1).                 (* apply: IHn でもよい。 *)\n  apply: leq_trans le_mn; exact: leq_subr.\nQed.\n\n(* ProofCafe yoshihiro503 による。 *)\nLemma edivnP_left : forall m d, edivn_spec_left m d (edivn m d).\nProof.\n move=> m d.\n case: (edivnP m d) => q r eq impl.\n by apply EdivnSpec_left.\nQed.\n\nLemma edivn_eq_right : forall d q r, r < d -> edivn (q * d + r) d = (q, r).\nProof.\n  move=> d q r lt_rd; have d_pos: 0 < d by exact: leq_trans lt_rd.\n  set m := q * d + r; have: m = q * d + r by [].\n  set d' := d; have: d' = d by [].\n  case: (edivnP_right m d') => {m d'} m d' q' r' -> lt_r'd' d'd q'd'r'.\n  move: q'd'r' lt_r'd' lt_rd; rewrite d'd d_pos {d'd m} /=.\n    wlog: q q' r r' / q <= q' by case (ltnP q q'); last symmetry; eauto.\n  rewrite leq_eqVlt; case: eqP => [-> _|_] /=; first by move/addnI->.\n    rewrite -(leq_pmul2r d_pos); move/leq_add=> Hqr Eqr _; move/Hqr {Hqr}.\n  by rewrite addnS ltnNge mulSn -addnA -Eqr addnCA addnA leq_addr.\nQed.\n\nLemma edivn_eq_left : forall d q r, r < d -> edivn (q * d + r) d = (q, r).\nProof.\n  move=> d q r lt_rd; have d_pos: 0 < d by exact: leq_trans lt_rd.\n  case: (edivnP_left (q * d + r) d) lt_rd; rewrite d_pos /=.\n    set q' := (edivn (q * d + r) d).1; set r' := (edivn (q * d + r) d).2.\n  rewrite (surjective_pairing (edivn (q * d + r) d)) -/q' -/r'.\n    wlog: q r q' r' / q <= q' by case (ltnP q q'); last symmetry; eauto.\n  rewrite leq_eqVlt; case: eqP => [-> _|_] /=; first by move/addnI->.\n    rewrite -(leq_pmul2r d_pos); move/leq_add=> Hqr Eqr _; move/Hqr {Hqr}.\n  by rewrite addnS ltnNge mulSn -addnA Eqr addnCA addnA leq_addr.\nQed.\n(* .1と.2は直積のfstとsndである。これを使うには、ssrfunが必要である。 *)\n\n(* END *)\n\n\n(* 証明に直接使われていないもの。 *)\n\n(** 3.1 Basics *)\nVariable n : nat.\n\nLemma three : S (S (S O)) = 3 /\\ 2 = 0.+1.+1.\nProof. by [].\nQed.\n\nLemma concrete_plus : plus 16 64 = 80.\nProof.\n    by [].\nQed.\n\nLemma concrete_le : le 1 3.\nProof.\n    by apply: (Le.le_trans _ 2); apply: Le.le_n_Sn.\nQed.\n\nFixpoint subn_rec (m n : nat) {struct m} :=\n  match m, n with\n    | m'.+1, n'.+1 => (m' - n')\n    | _, _ => m\nend.\n\nLemma concrete_big_leq : 0 <= 51.\nProof.\n    by [].\nQed.\n\nLemma semi_concrete_leq : forall n m, n <= m -> 51 + n <= 51 + m.\nProof.\n    by [].\nQed.\n\nLemma concrete_arith : (50 < 100) && (3 + 4 < 3 * 4 <= 17 - 2).\nProof.\n    by [].\nQed.\n\nLemma plus_commute : forall n1 m1, n1 + m1 = m1 + n1.\nProof.\n    by elim=> [| n IHn m]; [elim | change (n.+1 + m) with ((n + m).+1); rewrite IHn; elim: m].\n(*  by elim=> [| n IHn m]; [elim | rewrite -[n.+1 + m]/(n + m).+1 IHn; elim: m]. *)\nQed.\n\n\nCoInductive ltn_xor_geq (m : nat) (n : nat) : bool -> bool -> Set := (* 不使用 *)\n| LtnNotGeq : m < n -> ltn_xor_geq m n false true\n| GeqNotLtn : n <= m -> ltn_xor_geq m n true false.\nCheck LtnNotGeq 1 2.                        (* : 1 < 2 -> ltn_xor_geq 1 2 false true *)\nCheck GeqNotLtn 1 1.                        (* : 0 < 1 -> ltn_xor_geq 1 1 true false *)\n\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/ssr/ssr_ast_3_euclid_divisin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.6985104385091928}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Graphs                                                                  *\n**************************************************************************)\n\n(* under construction *)\n\nSet Implicit Arguments.\nRequire Import LibCore LibArray LibSet.\n\n(*-----------------------------------------------------------*)\n\nDefinition value_nonneg A (f:A->int) (P:A->Prop) :=\n  forall x, P x -> f x >= 0.  \n\n(*-----------------------------------------------------------*)\n\nParameter graph : Type -> Type.\nParameter nodes : forall A, graph A -> set int.\nParameter edges : forall A, graph A -> set (int*int*A).\n  \nDefinition has_edge A (g:graph A) x y w :=\n  (x,y,w) \\in edges g.\n\nParameter has_edge_nodes : forall A (g : graph A) x y w,\n  has_edge g x y w -> x \\in nodes g /\\ y \\in nodes g.\n\nLemma has_edge_in_nodes_l : forall A (g : graph A) x y w,\n  has_edge g x y w -> x \\in nodes g.\nProof. intros. forwards*: has_edge_nodes. Qed.\n\nLemma has_edge_in_nodes_r : forall A (g : graph A) x y w,\n  has_edge g x y w -> y \\in nodes g.\nProof. intros. forwards*: has_edge_nodes. Qed.\n\nDefinition nonneg_edges (g:graph int) :=\n  forall x y w, has_edge g x y w -> w >= 0.\n  (* forall x y, value_nonneg id (has_edge g x y) *)\n\n(*-----------------------------------------------------------*)\n\nDefinition path A := list (int*int*A).\n\nInductive is_path A (g:graph A) : int -> int -> path A -> Prop :=\n  | is_path_nil : forall x, \n      x \\in nodes g ->\n      is_path g x x nil\n  | is_path_cons : forall x y z w p,\n      is_path g x y p ->\n      has_edge g y z w ->\n      is_path g x z ((y,z,w)::p).\n\nLemma is_path_in_nodes_l : forall A (g:graph A) x y p,\n  is_path g x y p -> x \\in nodes g.\nProof. introv H. induction~ H. Qed.\n\nLemma is_path_in_nodes_r : forall A (g:graph A) x y p,\n  is_path g x y p -> y \\in nodes g.\nProof. introv H. inverts~ H. apply* has_edge_in_nodes_r. Qed. \n\nLemma is_path_cons_has_edge : forall A (g:graph A) x y z w p,\n  is_path g x z ((y,z,w)::p) -> has_edge g y z w.\nProof. introv H. inverts~ H. Qed.\n\n(*-----------------------------------------------------------*)\n\nDefinition weight (p:path int) :=\n  nosimpl (fold_right (fun e acc => let '(_,_,w) := e in w+acc) 0 p).\n\nLemma weight_nil : \n  weight (nil : path int) = 0.\nProof. auto. Qed.\n\nLemma weight_cons : forall (p:path int) x y w, \n  weight ((x,y,w)::p) = w + weight p.\nProof. intros. unfold weight. rew_list~. Qed.\n\n(** A graph with nonnegative edges has only paths\n    of nonnegative weight *)\n\nLemma nonneg_edges_to_path : forall g, \n  nonneg_edges g -> forall x y,\n  value_nonneg weight (is_path g x y).\nProof.\n  introv NG H. induction H. \n  rewrite weight_nil. math. \n  rewrite weight_cons. forwards: NG H0. math.\nQed.\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/LibGraph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.6985104285960047}}
{"text": "(* Playing with (co-)fixpoints with local definitions *)\n\nInductive listn : nat -> Set :=\n  niln : listn 0\n| consn : forall n:nat, nat -> listn n -> listn (S n).\n\nFixpoint f (n:nat) (m:=pred n) (l:listn m) (p:=S n) {struct l} : nat :=\n   match n with O => p | _ =>\n     match l with niln => p | consn q _ l => f (S q) l end\n   end.\n\nEval compute in (f 2 (consn 0 0 niln)).\n\nCoInductive Stream : nat -> Set :=\n  Consn : forall n, nat -> Stream n -> Stream (S n).\n\nCoFixpoint g (n:nat) (m:=pred n) (l:Stream m) (p:=S n) : Stream p :=\n    match n return (let m:=pred n in forall l:Stream m, let p:=S n in Stream p)\n    with\n    | O => fun l:Stream 0 => Consn O 0 l\n    | S n' =>\n      fun l:Stream n' =>\n      let l' :=\n        match l in Stream q return Stream (pred q) with Consn _ _ l => l end\n      in\n      let a := match l with Consn _ a l => a end in\n      Consn (S n') (S a) (g n' l')\n   end l.\n\nEval compute in (fun l => match g 2 (Consn 0 6 l) with Consn _ a _ => a end).\n\n(* Check inference of simple types in presence of non ambiguous\n   dependencies (needs revision 10125) *)\n\nSection folding.\n\nInductive vector (A:Type) : nat -> Type :=\n  | Vnil : vector A 0\n  | Vcons : forall (a:A) (n:nat), vector A n -> vector A (S n).\n\nVariables (B C : Set) (g : B -> C -> C) (c : C).\n\nFixpoint foldrn n bs :=\n  match bs with\n  | Vnil _ => c\n  | Vcons _ b _ tl => g b (foldrn _ tl)\n  end.\n\nEnd folding.\n\n(* Check definition by tactics *)\n\nSet Automatic Introduction.\n\nInductive even : nat -> Type :=\n  | even_O : even 0\n  | even_S : forall n, odd n -> even (S n)\nwith odd : nat -> Type :=\n    odd_S : forall n, even n -> odd (S n).\n\nFixpoint even_div2 n (H:even n) : nat :=\n  match H with\n  | even_O => 0\n  | even_S n H => S (odd_div2 n H)\n  end\nwith odd_div2 n H : nat.\ndestruct H.\napply even_div2 with n.\nassumption.\nQed.\n\nFixpoint even_div2' n (H:even n) : nat with odd_div2' n (H:odd n) : nat.\ndestruct H.\nexact 0.\napply odd_div2' with n.\nassumption.\ndestruct H.\napply even_div2' with n.\nassumption.\nQed.\n\nCoInductive Stream1 (A B:Type) := Cons1 : A -> Stream2 A B -> Stream1 A B\nwith Stream2 (A B:Type) := Cons2 : B -> Stream1 A B -> Stream2 A B.\n\nCoFixpoint ex1 (n:nat) (b:bool) : Stream1 nat bool\nwith ex2 (n:nat) (b:bool) : Stream2 nat bool.\napply Cons1.\nexact n.\napply (ex2 n b).\napply Cons2.\nexact b.\napply (ex1 (S n) (negb b)).\nDefined.\n\nSection visibility.\n\n  Let Fixpoint imm (n:nat) : True := I.\n\n  Let Fixpoint by_proof (n:nat) : True.\n  Proof. exact I. Defined.\nEnd visibility.\n\nFail Check imm.\nFail Check by_proof.\n\nModule Import mod_local.\n  Fixpoint imm_importable (n:nat) : True := I.\n\n  Local Fixpoint imm_local (n:nat) : True := I.\n\n  Fixpoint by_proof_importable (n:nat) : True.\n  Proof. exact I. Defined.\n\n  Local Fixpoint by_proof_local (n:nat) : True.\n  Proof. exact I. Defined.\nEnd mod_local.\n\nCheck imm_importable.\nFail Check imm_local.\nCheck mod_local.imm_local.\nCheck by_proof_importable.\nFail Check by_proof_local.\nCheck mod_local.by_proof_local.\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/Fixpoint.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.6985104279286152}}
{"text": "(**\nHere we define the basic notions of setoids.\n *)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\n\n(**\nProjections and builder functions of equivalence relations.\n*)\nDefinition make_eq_rel\n           {X : hSet}\n           (rel : hrel X)\n           (isrefl_rel : isrefl rel)\n           (issymm_rel : issymm rel)\n           (istrans_rel : istrans rel)\n  : eqrel X\n  := rel ,, ((istrans_rel ,, isrefl_rel) ,, issymm_rel).\n\nNotation \"'id' g\" := (eqrelrefl _ g) (at level 30) : setoid_scope.\nNotation \"! p\" := (eqrelsymm _ _ _ p) : setoid_scope.\nNotation \"p @ q\" := (eqreltrans _ _ _ _ p q) : setoid_scope.\nDelimit Scope setoid_scope with setoid.\n\n(**\nA setoid is just a pair of a set and an equivalence relation.\n *)\nDefinition setoid :=\n  ∑ (X : hSet), eqrel X.\n\n(**\nProjections and builder functions of setoids.\n *)\nDefinition make_setoid\n           {X : hSet}\n           (R : eqrel X)\n  : setoid\n  := X ,, R.\n\nCoercion carrier (X : setoid) : hSet := pr1 X.\n\nDefinition carrier_eq\n           (X : setoid)\n  : eqrel X\n  := pr2 X.\n\nNotation \"x ≡ y\" := (carrier_eq _ x y) (at level 70).\n\nDefinition isaprop_setoid_eq\n           {X : setoid}\n           (x y : X)\n  : isaprop (x ≡ y).\nProof.\n  apply (pr1 (carrier_eq X)).\nDefined.\n\nDefinition setoid_path\n           {X : setoid}\n           {x y : X}\n           (p : x = y)\n  : x ≡ y.\nProof.\n  induction p.\n  apply (id _)%setoid.\nDefined.\n\n(**\nLastly, we define setoid morphisms.\n *)\nDefinition setoid_morphism (X₁ X₂ : setoid)\n  := ∑ (f : X₁ → X₂), ∏ (x y : X₁), x ≡ y → f x ≡ f y.\n\n(**\nProjections and builder functions for setoid morphisms.\n *)\nDefinition make_setoid_morphism\n           {X₁ X₂ : setoid}\n           (f : X₁ → X₂)\n           (Rf : ∏ (x y : X₁), x ≡ y → f x ≡ f y)\n  : setoid_morphism X₁ X₂\n  := f ,, Rf.\n\nDefinition map_carrier\n           {X₁ X₂ : setoid}\n           (f : setoid_morphism X₁ X₂)\n  : X₁ → X₂\n  := pr1 f.\n\nCoercion map_carrier : setoid_morphism >-> Funclass.\n\nDefinition map_eq\n           {X₁ X₂ : setoid}\n           (f : setoid_morphism X₁ X₂)\n           {x y : X₁}\n  : x ≡ y → f x ≡ f y\n  := pr2 f x y.\n\n(**\nEquality principle for setoid morphisms.\n *)\nDefinition setoid_morphism_eq\n           {X₁ X₂ : setoid}\n           (f g : setoid_morphism X₁ X₂)\n           (e : ∏ (x : X₁), f x = g x)\n  : f = g.\nProof.\n  use subtypePath.\n  - intro.    \n    do 3 (apply impred ; intro).\n    apply isaprop_setoid_eq.\n  - apply funextsec.\n    exact e.\nDefined.\n\nDefinition isaset_setoid_morphism (X₁ X₂ : setoid)\n  : isaset(setoid_morphism X₁ X₂).\nProof.\n  use isaset_total2.\n  - apply isaset_set_fun_space.\n  - intros f ; cbn.\n    apply isasetaprop.\n    repeat (apply impred ; intro).\n    apply isaprop_setoid_eq.\nDefined.\n", "meta": {"author": "nmvdw", "repo": "FinitaryFunctors", "sha": "7342b68819209fda64d2be8c8f0dbf5305e3608a", "save_path": "github-repos/coq/nmvdw-FinitaryFunctors", "path": "github-repos/coq/nmvdw-FinitaryFunctors/FinitaryFunctors-7342b68819209fda64d2be8c8f0dbf5305e3608a/new_code/setoids/base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.6985104223046316}}
{"text": "Require Import ZArith.\nRequire Import Ensembles.\n\nModule NaiveLang.\n  Definition expr := (nat -> Z) -> Prop.\n  Definition context := expr -> Prop.\n  Definition impp (e1 e2 : expr) : expr := fun st => e1 st -> e2 st.\n  Definition andp (e1 e2 : expr) : expr := fun st => e1 st /\\ e2 st.\n  Definition orp  (e1 e2 : expr) : expr := fun st => e1 st \\/ e2 st.\n  Definition falsep : expr := fun st => False.\n\n  Definition derivable (Phi: context) (e : expr) : Prop := forall st, (forall e0, Phi e0 -> e0 st) -> e st.\nEnd NaiveLang.\n\nRequire Import interface_3.\n\nModule NaiveRule.\n  Include DerivedNames (NaiveLang).\n  Axiom deduction_andp_intros : (forall (Phi : context) (x y : expr), derivable Phi x -> derivable Phi y -> derivable Phi (andp x y)) .\n  Axiom deduction_andp_elim1 : (forall (Phi : context) (x y : expr), derivable Phi (andp x y) -> derivable Phi x) .\n  Axiom deduction_andp_elim2 : (forall (Phi : context) (x y : expr), derivable Phi (andp x y) -> derivable Phi y) .\n  Axiom deduction_orp_intros1 : (forall (Phi : context) (x y : expr), derivable Phi x -> derivable Phi (orp x y)) .\n  Axiom deduction_orp_intros2 : (forall (Phi : context) (x y : expr), derivable Phi y -> derivable Phi (orp x y)) .\n  Axiom deduction_orp_elim : (forall (Phi : Ensemble expr) (x y z : expr), derivable (Union expr Phi (Singleton expr x)) z -> derivable (Union expr Phi (Singleton expr y)) z -> derivable (Union expr Phi (Singleton expr (orp x y))) z) .\n  Axiom deduction_falsep_elim : (forall (Phi : context) (x : expr), derivable Phi falsep -> derivable Phi x) .\n  Axiom deduction_modus_ponens : (forall (Phi : context) (x y : expr), derivable Phi x -> derivable Phi (impp x y) -> derivable Phi y) .\n  Axiom deduction_impp_intros : (forall (Phi : Ensemble expr) (x y : expr), derivable (Union expr Phi (Singleton expr x)) y -> derivable Phi (impp x y)) .\n  Axiom deduction_weaken : (forall (Phi Psi : Ensemble expr) (x : expr), Included expr Phi Psi -> derivable Phi x -> derivable Psi x) .\n  Axiom derivable_assum : (forall (Phi : Ensemble expr) (x : expr), In expr Phi x -> derivable Phi x) .\n  Axiom deduction_subst : (forall (Phi Psi : context) (y : expr), (forall x : expr, Psi x -> derivable Phi x) -> derivable (Union expr Phi Psi) y -> derivable Phi y) .\nEnd NaiveRule.\n\nModule T := LogicTheorem NaiveLang NaiveRule.\nModule Solver := IPSolver NaiveLang.\nImport T.\nImport Solver.\n\n\n", "meta": {"author": "QinxiangCao", "repo": "LOGIC", "sha": "d1476d57345c87447ea500b3d5ea99ee6d0f6863", "save_path": "github-repos/coq/QinxiangCao-LOGIC", "path": "github-repos/coq/QinxiangCao-LOGIC/LOGIC-d1476d57345c87447ea500b3d5ea99ee6d0f6863/LogicGenerator/demo/implementation_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6984699742238955}}
{"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   : Vector Theory based on Matrix of Function\n  author    : ZhengPu Shi\n  date      : 2021.12\n  \n  remark    :\n  1. This is version 2, fixed the shape problem\n*)\n\n\nRequire Export VectorThySig.\n\nRequire Import NatFun.MatrixThy.\n\nRequire Import ListListExt.\nRequire Import Lia.\n\nRequire Import Setoid.  (* => *)\n\n\n(* ######################################################################### *)\n(** * Vector theory *)\nModule VectorThy (F : FieldSig) <: VectorThySig F.\n  \n  (* ==================================== *)\n  (** ** Matrix theory *)\n  Module Export MatrixThy := MatrixThy F.\n  \n  \n  (* ==================================== *)\n  (** ** Vector type *)\n  \n  Declare Scope vec_scope.\n  Delimit Scope vec_scope with V.\n  Open Scope vec_scope.\n  \n  Definition vec X n := mat X n 1.\n  Notation V n := (vec X n).\n  \n  (** Get generate function of the vector *)\n  Definition vdata {n} (v : V n) : nat -> X :=\n    let g := mdata v in\n      fun i => g i O.\n  \n  \n  (* ==================================== *)\n  (** ** Vector equility *)\n(*   Definition veq {n} (v1 v2 : V n) := meq v1 v2.\n  Notation \"v1 == v2 \" := (@veq _ v1 v2) (at level 70).\n  \n  Lemma veq_refl : forall {n} (v : V n), v = v.\n  Proof. intros. apply meq_refl. Qed.\n   \n  Lemma veq_sym : forall {n} (v1 v2 : V n), v1 = v2 -> v2 = v1.\n  Proof. intros. apply meq_sym. easy. Qed.\n  \n  Lemma veq_trans : forall {n} (v1 v2 v3 : V n), \n    v1 = v2 -> v2 = v3 -> v1 = v3.\n  Proof. intros. apply meq_trans with (m2:=v2); auto. Qed. *)\n  \n  Lemma veq_dec : forall {n} (v1 v2 : V n), {v1 = v2} + {v1 <> v2}.\n  Proof. intros. apply meq_dec. Qed.\n  \n  \n  (* ==================================== *)\n  (** ** Convert between tuples and vector *)\n  Definition t2v_2 (t : @T2 X) : V 2 := \n    let '(a,b) := t in l2m [[a];[b]].\n    \n  Definition t2v_3 (t : @T3 X) : V 3 := \n    let '(a,b,c) := t in l2m [[a];[b];[c]].\n    \n  Definition t2v_4 (t : @T4 X) : V 4 := \n    let '(a,b,c,d) := t in l2m [[a];[b];[c];[d]].\n  \n  \n  Definition v2t_2 (v : V 2) : @T2 X :=\n    let g := vdata v in (g 0, g 1)%nat.\n\n  Definition v2t_3 (v : V 3) : @T3 X :=\n    let g := vdata v in (g 0, g 1, g 2)%nat.\n    \n  Definition v2t_4 (v : V 4) : @T4 X :=\n    let g := vdata v in (g 0, g 1, g 2, g 3)%nat.\n  \n  Lemma v2t_t2v_id_2 : forall (t : X * X), v2t_2 (t2v_2 t) = t.\n  Proof.\n    intros. destruct t. simpl. unfold v2t_2. simpl. f_equal.\n  Qed.\n  \n  Lemma t2v_v2t_id_2 : forall (v : V 2), t2v_2 (v2t_2 v) = v.\n  Proof.\n    intros. apply meq_iff; intros i j Hi Hj. simpl.\n    repeat (try destruct i; try destruct j; auto; try lia).\n  Qed.\n  \n  \n  (* ==================================== *)\n  (** ** Convert between list and vector *)\n  Definition v2l {n} (v : V n) : list X := MCol 0 v.\n  Definition l2v {n} (l : list X) : V n := l2m (cvt_row2col l).\n  \n  Lemma v2l_length : forall {n} (v : V n), length (v2l v) = n.\n  Admitted.\n  \n  Lemma v2l_l2v_id : forall {n} (l : list X),\n    length l = n -> @v2l n (@l2v n l) = l.\n  Admitted.\n\n  Lemma l2v_v2l_id : forall {n} (v : V n), \n    l2v (v2l v) = v.\n  Admitted.\n  \n  \n  (* ==================================== *)\n  (** ** Zero vector *)\n  Definition vec0 {n} : V n := mat0 n 1.\n\n  (** Assert that a vector is an zero vector. *)\n  Definition vzero {n} (v : V n) : Prop := v = vec0.\n\n  (** Assert that a vector is an non-zero vector. *)\n  Definition vnonzero {n} (v : V n) : Prop := ~(vzero v).\n  \n  (** vec0 is equal to mat0 with column 1 *)\n  Lemma vec0_eq_mat0 : forall n, vec0 = mat0 n 1.\n  Proof. intros. easy. Qed.\n\n  (** It is decidable that if a vector is zero vector. *)\n  Lemma vzero_dec : forall {n} (v : V n), {vzero v} + {vnonzero v}.\n  Proof. intros. apply meq_dec. Qed.\n  \n  \n  (* ==================================== *)\n  (** ** algebra operations *)\n  \n  (** 一个向量的映射 *)\n  Definition vmap {n} (v : V n) f : V n := mmap f v.\n  \n  (** 一个向量的fold操作 *)\n(*   Definition vfold : forall {B : Type} {n} (v : V n) (f : X -> B) (b : B), B. *)\n  \n  (** 两个向量的映射 *)\n  Definition vmap2 {n} (v1 v2 : V n) f : V n := mmap2 f v1 v2.\n  \n  (* 两个向量的点积。这里用矩阵乘法来定义点积，而我们之前是用点积来定义乘法 *)\n  Definition vdot {n : nat} (X : V n) (B : V n) :=\n    scalar_of_mat (@mmul 1 n 1 (mtrans X) B).\n\n  (** 向量加法 *)\n  Definition vadd {n} (v1 v2 : V n) : V n := madd v1 v2.\n  Infix \"+\" := vadd.\n\n  (** 向量加法交换律 *)\n  Lemma vadd_comm : forall {n} (v1 v2 : V n), v1 + v2 = v2 + v1.\n  Proof. intros. apply madd_comm. Qed.\n\n  (** 向量加法结合律 *)\n  Lemma vadd_assoc : forall {n} (v1 v2 v3 : V n), \n    (v1 + v2) + v3 = v1 + (v2 + v3).\n  Proof. intros. apply madd_assoc. Qed.\n\n  (** 向量左加0 *)\n  Lemma vadd_0_l : forall {n} (v : V n), vec0 + v = v.\n  Proof. intros. apply (@madd_0_l n 1). Qed.\n\n  (** 向量右加0 *)\n  Lemma vadd_0_r : forall {n} (v : V n), v + vec0 =  v.\n  Proof. intros. apply (@madd_0_r n 1). Qed.\n\n  (** 负向量 *)\n  Definition vopp {n} (v : V n) : V n := mopp v.\n  Notation \"- v\" := (vopp v).\n\n  (** 加上负向量等于0 *)\n  Lemma vadd_opp : forall {n} (v : V n), v + (- v) = vec0.\n  Proof. intros. apply madd_opp. Qed.\n\n  (** 向量减法 *)\n  Definition vsub {n} (v1 v2 : V n) : V n := v1 + (- v2).\n  Infix \"-\" := vsub.\n  \n  (** 取元素 *)\n  Definition vnth {n} (v : V n) i : X := @mnth n 1 v i 0.\n  \n(*   Notation \"v # i\" := (vnth v i) (at level 30). *)\n\n  (** 取出1x1矩阵的第 0,0 个元素 *)\n(*   Definition scalar_of_mat (m : mat 1 1) := mnth m 0 0. *)\n\n  (** 向量数乘 *)\n  Definition vcmul {n} a (v : V n) : V n := a c* v.\n  Definition vmulc {n} (v : V n) a : V n := v *c a.\n\n  (** 右数乘和左数乘等价 *)\n  Lemma vmulc_eq_vcmul : forall {n} a (v : V n), \n    v *c a = a c* v.\n  Proof. intros. apply mmulc_eq_mcmul. Qed.\n\n  (** 数乘结合律1 *)\n  Lemma vcmul_assoc : forall {n} a b (v : V n), \n    a c* (b c* v) = (a * b)%X c* v.\n  Proof. intros. apply mcmul_assoc. Qed.\n\n  (** 数乘结合律2 *)\n  Lemma vcmul_perm : forall {n} a b (v : V n), \n    a c* (b c* v) = b c* (a c* v).\n  Proof. intros. apply mcmul_perm. Qed.\n\n  (** 数乘左分配律 *)\n  Lemma vcmul_add_distr_l : forall {n} a b (v : V n), \n    (a + b)%X c* v = (a c* v) + (b c* v).\n  Proof. intros. apply mcmul_add_distr_r. Qed.\n\n  (** 数乘右分配律 *)\n  Lemma vcmul_add_distr_r : forall {n} a (v1 v2 : V n), \n    a c* (v1 + v2) = (a c* v1) + (a c* v2).\n  Proof. intros. unfold vadd. apply mcmul_add_distr_l. Qed.\n\n  (** 用1数乘 *)\n  Lemma vcmul_1_l : forall {n} (v : V n), X1 c* v = v.\n  Proof. intros. apply mcmul_1_l. Qed.\n\n  (** 用0数乘 *)\n  Lemma vcmul_0_l : forall {n} (v : V n), X0 c* v = vec0.\n  Proof. intros. apply mcmul_0_l. Qed.\n\n  (** 非零向量是k倍关系，则系数k不为0 *)\n  Lemma vec_eq_vcmul_imply_coef_neq0 : forall {n} (v1 v2 : V n) k,\n    vnonzero v1 -> vnonzero v2 -> v1 = k c* v2 -> k <> X0.\n  Proof.\n    intros. intro. subst. rewrite vcmul_0_l in H. destruct H. easy.\n  Qed.\n  \n  \n  (* ==================================== *)\n  (** ** 2-dim vector operations *)\n\n  (** 2维向量的“长度”，这里不是欧式距离，而是欧式距离的平方，为了方便计算 *)\n  Definition vlen2 (v : V 2) : X :=\n    let '(x,y) := v2t_2 v in\n      (x * x + y * y)%X.\n  \n  \n  (* ==================================== *)\n  (** ** 3-dim vector operations *)\n\n  (** 3维向量的“长度”，这里不是欧式距离，而是欧式距离的平方，为了方便计算 *)\n  Definition vlen3 (v : V 3) : X :=\n    let '(x,y,z) := v2t_3 v in\n      (x * x + y * y + z * z)%X.\n      \n  (** V3的点积 *)\n  Definition vdot3 (v0 v1 : V 3) : X :=\n    let '(a0,b0,c0) := v2t_3 v0 in\n    let '(a1,b1,c1) := v2t_3 v1 in\n      (a0 * a1 + b0 * b1 + c0 * c1)%X.\n  \nEnd VectorThy.\n\n\n(* ######################################################################### *)\n(** * Vector on R *)\nModule VectorR := VectorThy (FieldR.FieldDefR).\n\n\n(* ######################################################################### *)\n(** * Test of VectorR *)\nModule VectorR_test.\n  \n  Import FieldR.\n  Import VectorR.\n  Open Scope R.\n  Open Scope mat_scope.\n  \n  Definition v1 : V 3 := l2v [1;2;3].\n  Definition v2 : V 3 := l2v [4;5;6].\n  Example vdot_ex1 : vdot v1 v2 = (4+10+18)%R.\n  Proof. compute. ring. Qed.\n  \nEnd VectorR_test.\n\n\n(* ######################################################################### *)\n(** * Vector on Qc *)\nModule VectorQc := VectorThy (FieldQc.FieldDefQc).\n\n\n(* ######################################################################### *)\n(** * Test of VectorQc *)\nModule VectorQc_test.\n  \n  Import FieldQc.\n  Import VectorQc.\n  Open Scope Qc.\n  Open Scope mat_scope.\n  Definition v1 : V 3 := l2v [Q2Qc 1; Q2Qc 2; Q2Qc 3].\n  Definition v2 : V 3 := l2v [Q2Qc 4; Q2Qc 5; Q2Qc 6].\n  Example vdot_ex1 : vdot v1 v2 = Q2Qc (4+10+18).\n  Proof. compute. ring. Qed.\n  \n(*   Compute v2l v1. *)\n  \nEnd VectorQc_test.\n\n", "meta": {"author": "zhengpushi", "repo": "coq-matrix", "sha": "b0f5a3463d7f1973fd29be8b6b85e4a700297a34", "save_path": "github-repos/coq/zhengpushi-coq-matrix", "path": "github-repos/coq/zhengpushi-coq-matrix/coq-matrix-b0f5a3463d7f1973fd29be8b6b85e4a700297a34/MatrixComparison/src/Matrix/NatFun/VectorThy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.6982585486668604}}
{"text": "(*\n(C) Copyright 2010, COQTAIL team\n\nProject Info: http://sourceforge.net/projects/coqtail/\n\nThis library is free software; you can redistribute it and/or modify it\nunder the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation; either version 2.1 of the License, or\n(at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\nor FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\nLicense for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,\nUSA.\n*)\n\n(** Some usual integrals *)\n\n\nRequire Import Reals.\nRequire Import MyRfunctions.\nRequire Import Rintegral.\nRequire Import Lia.\n\nOpen Scope R_scope.\n\nLemma Rint_inv : forall a b, \n  0 < a <= b -> Rint (fun x => /x) a b (ln b - ln a).\nintros a b Hab.\napply Rint_derive.\n  intuition.\nintros x Hx.\n  apply derivable_pt_lim_ln.\n  apply Rlt_le_trans with a; intuition.\n  intros x Hx.\n  apply continuity_pt_inv.\n  apply derivable_continuous, derivable_id.\n  assert( 0 < x).\n  apply Rlt_le_trans with a; tauto.\n  auto with *.\nQed.\nHint Resolve Rint_inv : Rint.\n\nLemma Rint_exp : forall a b, Rint exp a b (exp b - exp a).\nProof.\nintros a b.\napply Rint_derive2.\nintros; apply derivable_pt_lim_exp.\nintros; apply derivable_continuous_pt, derivable_pt_exp.\nQed.\nHint Resolve Rint_exp : Rint.\n\nLemma Rint_pow_pos : forall n a b, \n  Rint (fun y : R => INR n * y ^ (pred n)) a b ((b ^ n - a ^ n)).\nProof.\nintros n a b.\ndestruct n.\n  replace (b ^ 0 - a ^ 0) with (0 * (b - a)) by ring.\n  apply Rint_eq_compat with (fct_cte 0).\n  unfold fct_cte; auto with *.\n  apply Rint_constant.\napply Rint_derive2 with (f := fun x => x ^ (S n)); intros.\napply derivable_pt_lim_pow_pos; lia.\napply continuity_pt_mult.\napply continuity_pt_const; intros u v ; reflexivity.\n\n  induction n.\n  apply continuity_pt_const; intros u v ; reflexivity.\n  simpl.\n  apply continuity_pt_mult.\n\nauto with Rcont.\nauto with Rcont.\nQed.\nHint Resolve Rint_pow_pos : Rint.\n\nLemma Rint_cos : forall a b, \n  Rint cos a b (sin b - sin a).\nProof.\nintros a b.\napply Rint_derive2.\nintros; apply derivable_pt_lim_sin.\nintros; apply continuity_cos.\nQed.\nHint Resolve Rint_cos : Rint.\n\nLemma Rint_sin : forall a b, \n  Rint sin a b (cos a - cos b).\nintros a b.\nreplace (cos a - cos b) with (- cos b - -cos a) by ring.\napply Rint_derive2 with (f := (-cos)%F).\nintros; replace (sin x) with (--sin x) by ring; \n  apply derivable_pt_lim_opp, derivable_pt_lim_cos.\nintros; apply continuity_sin.\nQed.\nHint Resolve Rint_sin : Rint.\n\nLemma Rint_sqrt_inv : forall a b, 0 < a -> 0 < b ->\n  Rint (fun x => /(sqrt x)) a b (2 *( sqrt b - sqrt a)).\nProof.\nintros a b Ha Hb.\nassert(Hneq : forall x, Rmin a b <= x <= Rmax a b -> 0 < sqrt x).\n  intros; \n    apply sqrt_lt_R0.\n    apply Rlt_le_trans with (Rmin a b).\n    apply Rmin_pos; assumption.\n    intuition.\napply Rint_eq_compat with (fun x => 2 * /(2 * sqrt x)).\n  intros; field.\n  auto with *.\napply Rint_scalar_mult_compat_l.\napply Rint_derive2.\nintros; apply derivable_pt_lim_sqrt.\n  apply Rlt_le_trans with (Rmin a b).\n  apply Rmin_pos; assumption.\n  intuition.\nintros.\napply continuity_pt_inv.\n  apply continuity_pt_mult.\n  apply continuity_pt_constant.\n  apply continuity_pt_sqrt.\n  apply Rle_trans with (Rmin a b).\n  apply Rmin_ge; intuition.\n  intuition.\nassert( 0 < 2 * sqrt x).\napply Rmult_lt_0_compat.\n  auto with *.\n  auto.\nauto with *.\nQed.\nHint Resolve Rint_sqrt_inv : Rint.\n\n(* cosh sinh  *)\n", "meta": {"author": "coq-community", "repo": "coqtail-math", "sha": "be26e1a6a52f2e13e0779c68aba685ddfb4f0535", "save_path": "github-repos/coq/coq-community-coqtail-math", "path": "github-repos/coq/coq-community-coqtail-math/coqtail-math-be26e1a6a52f2e13e0779c68aba685ddfb4f0535/Reals/Rintegral/Rintegral_usual.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.6982585419947454}}
{"text": "Require Export ZArith.\nRequire Export Znumtheory.\nRequire Export Zpow_facts.\n(*Require Export Binomial.\nRequire Export Rdefinitions.*)\n\nDefinition nCr n r : Z := Z.of_nat ((fact n) / (fact r * fact (n-r))).\n\n(*Search ((_:nat -> Z) (_:nat)).*)\n\nFixpoint sum_fZ (f:nat -> Z) (n:nat): Z :=\n  match n with\n  | O => f 0%nat\n  | S i => sum_fZ f i + f (S i)\n  end.\n\nLemma zbinomial : forall (x y n:Z),\n    (x + y) ^ n = sum_fZ (fun i:nat => nCr (Z.to_nat n) i * x ^ (Z.of_nat i) * y ^ (Z.of_nat ((Z.to_nat n)-i))) (Z.to_nat n).\nProof.\nAdmitted.\n\n(* Theorem 70 *)\n\nLemma freshmans_dream : forall p : Z, prime p -> forall x y : Z, (x + y)^p mod p = (x^p+y^p) mod p.\nProof.\nAdmitted.\n\nTheorem theorem_70 : forall p : Z, prime p -> forall a : Z, a>=0 -> a^p mod p = a mod p.\nProof.\n  intros.\n  pattern a.\n  apply natlike_ind.\n  rewrite Z.pow_0_l.\n  reflexivity.\n  apply prime_ge_2 in H.\n  omega.\n\n  intros.\n  replace (Z.succ x) with (x + 1); [|omega].\n  rewrite freshmans_dream.\n  replace (1^p) with 1.\n  rewrite <- Zplus_mod_idemp_l.\n  rewrite H2.\n  rewrite -> Zplus_mod_idemp_l.\n  reflexivity.\n\n  symmetry.\n  apply Z.pow_1_l.\n  apply prime_ge_2 in H.\n  omega.\n  assumption.\n  omega.\nQed.\n\nSearch (_ * _ = _ * _).\n\n(* Theorem 71 *)\nLemma mod_mul_cancel_l : forall p q r n : Z, prime n /\\ ~(n|r) -> (r * p) mod n = (r * q) mod n <-> p mod n = q mod n.\nProof.\n  intros.\n  split.\n  \n  intros eq.\n  (* hmm, is this actually true, or only if n is prime... *)\n  \n\n  admit.\n\n  intros eq.\n  rewrite <- Zmult_mod_idemp_r.\n  rewrite eq.\n  rewrite -> Zmult_mod_idemp_r.\n  reflexivity.\nAdmitted.                     \n\nTheorem fermats_theorem : forall a p : Z, a>=0 -> prime p /\\ ~(p|a) -> a^(p-1) mod p = 1.\nProof.\n  intros a p age0 [H H0].\n\n  (* so basically it comes down to the fact that a must have an inverse mod p *)\n\n  (*\n  replace (a ^ (p - 1) mod p = 1) with (p|(a ^ (p - 1) - 1)).\n  unfold Z.divide.\n\n  specialize (theorem_70 p).\n  intros eq.\n  apply eq with (a:=a) in H.\n  clear eq.\n\n  replace (a ^ p mod p = a mod p) with (p | (a ^ p - a)) in H.\n  destruct H.\n  exists x.\n  rewrite <- (Z.mul_cancel_l _ _ a).\n  *)\n\n  replace 1 with (1 mod p) at 2.\n  2 : {\n    apply Zmod_small.\n    apply prime_ge_2 in H.\n    omega.\n  }\n  \n  rewrite <- (mod_mul_cancel_l _ _ a).\n  rewrite <- Z.pow_succ_r.\n  replace (Z.succ (p - 1)) with p; [|omega].\n  rewrite Z.mul_1_r.\n  rewrite theorem_70.\n  reflexivity.\n  \n  - apply H.\n  - apply age0.\n  - apply prime_ge_2 in H.\n    omega.\n  - split.\n    + apply H.\n    + apply H0.\nQed.\n\n(* Theorem 72 : a^phi(m) mod m = 1 *)\n\n\n", "meta": {"author": "geohot", "repo": "coq-hardy", "sha": "14d57dccfc657aa42321cd4976909d152fd105e0", "save_path": "github-repos/coq/geohot-coq-hardy", "path": "github-repos/coq/geohot-coq-hardy/coq-hardy-14d57dccfc657aa42321cd4976909d152fd105e0/chapter_6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6982486408457076}}
{"text": "Require Import List.\n\nRequire Import Logic.Func.Composition.\n\nDefinition injective (v w:Type) (f:v -> w) : Prop :=\n    forall (x y:v), f x = f y -> x = y.\n\nArguments injective {v} {w} _.\n\n\nLemma injective_comp : forall (v w u:Type) (f:v -> w) (g:w -> u),\n    injective f -> injective g -> injective (g ; f).\nProof.\n    intros v w u f g If Ig x y H. apply If. apply Ig. 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/Func/Injective.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.7718435030872967, "lm_q1q2_score": 0.6982486301453958}}
{"text": "\nTheorem Ex029 (A B C : Prop): (A -> B) -> (C -> ~B) -> (A -> ~C).\nProof.\n  intros.\n  intro.\n  apply H0.\n  + exact H2.\n  + apply H.\n    exact H1.\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/Ex029.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6982416982221725}}
{"text": "(************************************************)\n(************************************************)\n(****                                        ****)\n(****   The category of sets and functions   ****)\n(****                                        ****)\n(************************************************)\n(************************************************)\n\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Main.CategoryTheory.Arrow.\nRequire Import Main.CategoryTheory.Category.\nRequire Import Main.CategoryTheory.Product.\nRequire Import Main.Tactics.\n\n#[local] Open Scope type. (* Parse `*` as `prod` rather than `mul`. *)\n\n(* Sets and functions form a category. *)\n\n#[local] Theorem setCAssoc w x y z (f : w -> x) (g : x -> y) (h : y -> z) :\n  (fun e : w => h (g (f e))) = (fun e : w => h (g (f e))).\nProof.\n  search.\nQed.\n\n#[local] Theorem setCIdent x y (f : x -> y) : (fun e : x => f e) = f.\nProof.\n  search.\nQed.\n\nDefinition setCategory : category := newCategory\n  Type\n  (fun x y => x -> y)\n  (fun _ _ _ f g e => f (g e))\n  (fun x e => e)\n  setCAssoc setCIdent setCIdent.\n\n(* Cartesian products are categorical products in this category. *)\n\nTheorem cartesianProduct x y :\n  @product setCategory x y (x * y) fst snd.\nProof.\n  unfold product.\n  clean.\n  unfold universal.\n  split.\n  - exists (fun w => (qx w, qy w)). search.\n  - unfold arrowUnique.\n    intros.\n    destruct H.\n    destruct H0.\n    apply functional_extensionality.\n    intros.\n    apply injective_projections.\n    + replace (fst (f x0)) with (qx x0); [idtac | search].\n      replace (fst (g x0)) with (qx x0); [search | rewrite H0; search].\n    + replace (snd (f x0)) with (qy x0); [idtac | search].\n      replace (snd (g x0)) with (qy x0); [search | rewrite H2; search].\nQed.\n", "meta": {"author": "stepchowfun", "repo": "proofs", "sha": "00da33f63a56080227d06d37fd0f28b560f24624", "save_path": "github-repos/coq/stepchowfun-proofs", "path": "github-repos/coq/stepchowfun-proofs/proofs-00da33f63a56080227d06d37fd0f28b560f24624/proofs/CategoryTheory/Examples/Set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6981715301524015}}
{"text": "(** * Tactics: More Basic Tactics *)\n\n(** This chapter introduces several additional proof strategies\n    and tactics that allow us to begin proving more interesting\n    properties of functional programs.  We will see:\n    - how to use auxiliary lemmas in both \"forward-style\" and\n      \"backward-style\" proofs;\n    - how to reason about data constructors (in particular, how to use\n      the fact that they are injective and disjoint);\n    - how to strengthen an induction hypothesis (and when such\n      strengthening is required); and\n    - more details on how to reason by case analysis. *)\n\nRequire Export poly.\n\n(* ################################################################# *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    _exactly_ the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n\n(** Here, we could finish with \"[rewrite -> eq2.  reflexivity.]\" as we\n    have done several times before.  We can achieve the same effect in\n    a single step by using the [apply] tactic instead: *)\n\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** You may find it instructive to experiment with this proof\n    and see if there is a way to complete it using just [rewrite]\n    instead of [apply]. *)\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] that binds some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex)  *)\n(** Complete the following proof without using [simpl]. *)\n\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 3 = true ->\n     oddb 4 = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal exactly -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  simpl.\n\n(** Here we cannot use [apply] directly, but we can use the [symmetry]\n    tactic, which switches the left and right sides of an equality in\n    the goal. *)\n\n  symmetry.\n  simpl. (* (This [simpl] is optional, since [apply] will perform\n            simplification first, if needed.) *)\n  apply H.  Qed.\n\n(** **** Exercise: 3 stars (apply_exercise1)  *)\n(** (_Hint_: You can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [Search] is\n    your friend.) *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optionalM (apply_rewrite)  *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  What are the situations where both can usefully be\n    applied?\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(* ################################################################# *)\n(** * The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might like to pull it out\n    as a lemma recording, once and for all, the fact that equality is\n    transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to prove the above\n    example.  However, to do this we need a slight refinement of the\n    [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n\n(** If we simply tell Coq [apply trans_eq] at this point, it can\n    tell (by matching the goal against the conclusion of the lemma)\n    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and\n    [o] with [[e,f]].  However, the matching process doesn't determine\n    an instantiation for [m]: we have to supply one explicitly by\n    adding [with (m:=[c,d])] to the invocation of [apply]. *)\n\n  apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2.   Qed.\n\n(** Actually, we usually don't have to include the name [m] in\n    the [with] clause; Coq is often smart enough to figure out which\n    instantiation we're giving. We could instead write: [apply\n    trans_eq with [c;d]]. *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * The [inversion] Tactic *)\n\n(** Recall the definition of natural numbers:\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n    It is obvious from this definition that every number has one of\n    two forms: either it is the constructor [O] or it is built by\n    applying the constructor [S] to another number.  But there is more\n    here than meets the eye: implicit in the definition (and in our\n    informal understanding of how datatype declarations work in other\n    programming languages) are two more facts:\n    - The constructor [S] is _injective_.  That is, if [S n = S m], it\n      must be the case that [n = m].\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n].\n    Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor\n    is injective and [nil] is different from every non-empty list.\n    For booleans, [true] and [false] are different.  (Since neither\n    [true] nor [false] take any arguments, their injectivity is not\n    interesting.)  And so on. *)\n\n(** Coq provides a tactic called [inversion] that allows us to\n    exploit these principles in proofs. To see how to use it, let's\n    show explicitly that the [S] constructor is injective: *)\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n\n(** By writing [inversion H] at this point, we are asking Coq to\n    generate all equations that it can infer from [H] as additional\n    hypotheses, replacing variables in the goal as it goes. In the\n    present example, this amounts to adding a new hypothesis [H1 : n =\n    m] and replacing [n] by [m] in the goal. *)\n\n  inversion H.\n  reflexivity.\nQed.\n\n(** Here's a more interesting example that shows how multiple\n    equations can be derived at once. *)\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity. Qed.\n\n(** We can name the equations that [inversion] generates with an\n    [as ...] clause: *)\n\nTheorem inversion_ex2 : forall (n m : nat),\n  [n] = [m] ->\n  n = m.\nProof.\n  intros n m H. inversion H as [Hnm]. reflexivity.  Qed.\n\n(** **** Exercise: 1 star (inversion_ex3)  *)\nExample inversion_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** When used on a hypothesis involving an equality between\n    _different_ constructors (e.g., [S n = O]), [inversion] solves the\n    goal immediately.  Consider the following proof: *)\n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  intros n.\n\n(** We can proceed by case analysis on [n]. The first case is\n    trivial. *)\n\n  destruct n as [| n'].\n  - (* n = 0 *)\n    intros H. reflexivity.\n\n(** However, the second one doesn't look so simple: assuming\n    [beq_nat 0 (S n') = true], we must show [S n' = 0], but the latter\n    clearly contradictory!  The way forward lies in the assumption.\n    After simplifying the goal state, we see that [beq_nat 0 (S n') =\n    true] has become [false = true]: *)\n\n  - (* n = S n' *)\n    simpl.\n\n(** If we use [inversion] on this hypothesis, Coq notices that\n    the subgoal we are working on is impossible, and therefore removes\n    it from further consideration. *)\n\n    intros H. inversion H. Qed.\n\n(** This is an instance of a logical principle known as the _principle\n    of explosion_, which asserts that a contradictory hypothesis\n    entails anything, even false things! *)\n\nTheorem inversion_ex4 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem inversion_ex5 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. inversion contra. Qed.\n\n(** If you find the principle of explosion confusing, remember\n    that these proofs are not actually showing that the conclusion of\n    the statement holds.  Rather, they are arguing that, if the\n    nonsensical situation described by the premise did somehow arise,\n    then the nonsensical conclusion would follow.  We'll explore the\n    principle of explosion of more detail in the next chapter. *)\n\n(** **** Exercise: 1 star (inversion_ex6)  *)\nExample inversion_ex6 : forall (X : Type)\n                          (x y z : X) (l j : list X),\n  x :: y :: l = [] ->\n  y :: l = z :: j ->\n  x = z.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** To summarize this discussion, suppose [H] is a hypothesis in the\n    context or a previously proven lemma of the form\n        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] has the following effect:\n    - If [c] and [d] are the same constructor, then, by the\n      injectivity of this constructor, we know that [a1 = b1], [a2 =\n      b2], etc.  The [inversion H] adds these facts to the context and\n      tries to use them to rewrite the goal.\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory, and the current goal doesn't have to be\n      considered at all.  In this case, [inversion H] marks the\n      current goal as completed and pops it off the goal stack. *)\n\n(** The injectivity of constructors allows us to reason that\n    [forall (n m : nat), S n = S m -> n = m].  The converse of this\n    implication is an instance of a more general fact about both\n    constructors and functions, which we will find useful in a few\n    places below: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n    For example, the tactic [simpl in H] performs simplification in\n    the hypothesis named [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     beq_nat (S n) (S m) = b  ->\n     beq_nat n m = b.\nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, [apply L in H] matches some conditional statement\n    [L] (of the form [L1 -> L2], say) against a hypothesis [H] in the\n    context.  However, unlike ordinary [apply] (which rewrites a goal\n    matching [L2] into a subgoal [L1]), [apply L in H] matches [H]\n    against [L1] and, if successful, replaces it with [L2].\n    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    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\nTheorem silly3' : forall (n : nat),\n  (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->\n  true = beq_nat n 5  ->\n  true = beq_nat (S (S n)) 7.\nProof.\n  intros n eq H.\n  symmetry in H. apply eq in H. symmetry in H.\n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, idiomatic use of Coq tends to favor backward reasoning,\n    but in some situations the forward style can be easier to think\n    about.  *)\n\n(** **** Exercise: 3 stars, recommended (plus_n_n_injective)  *)\n(** Practice using \"in\" variants in this exercise.  (Hint: use\n    [plus_n_Sm].) *)\n\nTheorem plus_n_n_injective : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Varying the Induction Hypothesis *)\n\n(** Sometimes it is important to control the exact form of the\n    induction hypothesis when carrying out inductive proofs in Coq.\n    In particular, we need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose\n    we want to show that the [double] function is injective -- i.e.,\n    that it maps different arguments to different results:\n    Theorem double_injective: forall n m,\n      double n = double m -> n = m.\n    The way we _start_ this proof is a bit delicate: if we begin with\n      intros n. induction n.\n    all is well.  But if we begin it with\n      intros n m. induction n.\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  - (* n = O *) simpl. intros eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n  - (* n = S n' *) intros eq. destruct m as [| m'].\n    + (* m = O *) inversion eq.\n    + (* m = S m' *) apply f_equal.\n\n(** At this point, the induction hypothesis, [IHn'], does _not_ give us\n    [n' = m'] -- there is an extra [S] in the way -- so the goal is\n    not provable. *)\n\n      Abort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context --\n    intuitively, we have told Coq, \"Let's consider some particular [n]\n    and [m]...\" and we now have to prove that, if [double n = double\n    m] for _these particular_ [n] and [m], then [n = m].\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove, for\n    _all_ [n], that the proposition\n      - [P n] = \"if [double n = double m], then [n = m]\"\n    holds, by showing\n      - [P O]\n         (i.e., \"if [double O = double m] then [O = m]\") and\n      - [P n -> P (S 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    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      - \"if [double n = double m] then [n = m]\"\n    then we can prove\n       - \"if [double (S n) = double m] then [S n = m]\".\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      - [Q] = \"if [double n = 10] then [n = 5]\"\n    then we can prove\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n    But knowing [Q] doesn't give us any help at all with proving\n    [R]!  (If we tried to prove [R] from [Q], we would start with\n    something like \"Suppose [double (S n) = 10]...\" but then we'd be\n    stuck: knowing that [double (S n)] is [10] tells us nothing about\n    whether [double n] is [10], so [Q] is useless.) *)\n\n(** Trying to carry out this proof by induction on [n] when [m] is\n    already in the context doesn't work because we are then trying to\n    prove a relation involving _every_ [n] but just a _single_ [m]. *)\n\n(** The successful proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  - (* n = O *) simpl. intros m eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n\n  - (* n = S n' *) simpl.\n\n(** Notice that both the goal and the induction hypothesis are\n    different this time: the goal asks us to prove something more\n    general (i.e., to prove the statement for _every_ [m]), but the IH\n    is correspondingly more flexible, allowing us to choose any [m] we\n    like when we apply the IH. *)\n\n    intros m eq.\n\n(** Now we've chosen a particular [m] and introduced the assumption\n    that [double n = double m].  Since we are doing a case analysis on\n    [n], we also need a case analysis on [m] to keep the two \"in sync.\" *)\n\n    destruct m as [| m'].\n    + (* m = O *) simpl.\n\n(** The 0 case is trivial: *)\n\n      inversion eq.\n\n    + (* m = S m' *)\n      apply f_equal.\n\n(** At this point, since we are in the second branch of the [destruct\n    m], the [m'] mentioned in the context is the predecessor of the\n    [m] we started out talking about.  Since we are also in the [S]\n    branch of the induction, this is perfect: if we instantiate the\n    generic [m] in the IH with the current [m'] (this instantiation is\n    performed automatically by the [apply] in the next step), then\n    [IHn'] gives us exactly what we need to finish the proof. *)\n\n      apply IHn'. inversion eq. reflexivity. Qed.\n\n(** What you should take away from all this is that we need to be\n    careful about using induction to try to prove something too\n    specific: To prove a property of [n] and [m] by induction on [n],\n    it is sometimes important to leave [m] generic. *)\n\n(** The following exercise requires the same pattern. *)\n\n(** **** Exercise: 2 stars (beq_nat_true)  *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nFixpoint ble_nat (n m : nat) : bool :=\nmatch n with\n| O => match m with\n  | O => false\n  | S _ => true\n  end\n| S n' => match m with \n  | O => true \n  | S m' => ble_nat n' m'\n  end\nend.\n\nTheorem ble_nat_true : forall n m,\n    ble_nat n m = true -> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** ... and try to prove a simple fact about [square]... *)\n\nDefinition square (n: nat) := n*n.\n\nLemma square_mult : forall n m, \nsquare (n * m) = square n * square m.\nProof.\nAdmitted.\n\n(** At this point, a deeper discussion of unfolding and simplification\n    is in order.\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    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    A more straightforward way to make progress is to explicitly tell\n    Coq to unfold [bar]. *)\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n\n(** Now it is apparent that we are stuck on the [match] expressions on\n    both sides of the [=], and we can use [destruct] to finish the\n    proof without thinking too hard. *)\n\n  destruct m.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where [destruct] is used to\n    perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (beq_nat n 3).\n    - (* beq_nat n 3 = true *) reflexivity.\n    - (* beq_nat n 3 = false *) destruct (beq_nat n 5).\n      + (* beq_nat n 5 = true *) reflexivity.\n      + (* beq_nat n 5 = false *) reflexivity.  Qed.\n\nFixpoint combine (X: Type)(l1 l2: list X): list X := \nmatch l1 with \n| [] => l2\n| h :: t => h :: (combine X t l2)\nend.\n(** **** Exercise: 3 stars, optional (combine_split)  *)\n\n\n(** However, [destruct]ing compound expressions requires a bit of\n    care, as such [destruct]s can sometimes erase information we need\n    to complete a proof. *)\n(** For example, suppose we define a function [sillyfun1] like\n    this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** Now suppose that we want to convince Coq of the (rather\n    obvious) fact that [sillyfun1 n] yields [true] only when [n] is\n    odd.  By analogy with the proofs we did with [sillyfun] above, it\n    is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAbort.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution performed by [destruct] is too brutal -- it threw\n    away every occurrence of [beq_nat n 3], but we need to keep some\n    memory of this expression and how it was destructed, because we\n    need to be able to reason that, since [beq_nat n 3 = true] in this\n    branch of the case analysis, it must be that [n = 3], from which\n    it follows that [n] is odd.\n    What we would really like is to substitute away all existing\n    occurences of [beq_nat n 3], but at the same time add an equation\n    to the context that records which case we are in.  The [eqn:]\n    qualifier allows us to introduce such an equation, giving it a\n    name that we choose. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got\n     stuck above, except that the context contains an extra\n     equality assumption, which is exactly what we need to\n     make progress. *)\n    - (* e3 = true *) apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    - (* e3 = false *)\n     (* When we come to the second equality test in the body\n        of the function we are reasoning about, we can use\n        [eqn:] again in the same way, allow us to finish the\n        proof. *)\n      destruct (beq_nat n 5) eqn:Heqe5.\n        + (* e5 = true *)\n          apply beq_nat_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + (* e5 = false *) inversion eq.  Qed.\n\n(** **** Exercise: 2 stars (destruct_eqn_practice)  *)\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Review *)\n\n(** We've now seen many of Coq's most fundamental tactics.  We'll\n    introduce a few more in the coming chapters, and later on we'll\n    see some more powerful _automation_ tactics that make Coq help us\n    with low-level details.  But basically we've got what we need to\n    get work done.\n    Here are the ones we've seen:\n      - [intros]: move hypotheses/variables from goal to context\n      - [reflexivity]: finish the proof (when the goal looks like [e =\n        e])\n      - [apply]: prove goal using a hypothesis, lemma, or constructor\n      - [apply... in H]: apply a hypothesis, lemma, or constructor to\n        a hypothesis in the context (forward reasoning)\n      - [apply... with...]: explicitly specify values for variables\n        that cannot be determined by pattern matching\n      - [simpl]: simplify computations in the goal\n      - [simpl in H]: ... or a hypothesis\n      - [rewrite]: use an equality hypothesis (or lemma) to rewrite\n        the goal\n      - [rewrite ... in H]: ... or a hypothesis\n      - [symmetry]: changes a goal of the form [t=u] into [u=t]\n      - [symmetry in H]: changes a hypothesis of the form [t=u] into\n        [u=t]\n      - [unfold]: replace a defined constant by its right-hand side in\n        the goal\n      - [unfold... in H]: ... or a hypothesis\n      - [destruct... as...]: case analysis on values of inductively\n        defined types\n      - [destruct... eqn:...]: specify the name of an equation to be\n        added to the context, recording the result of the case\n        analysis\n      - [induction... as...]: induction on values of inductively\n        defined types\n      - [inversion]: reason by injectivity and distinctness of\n        constructors\n      - [assert (H: e)] (or [assert (e) as H]): introduce a \"local\n        lemma\" [e] and call it [H]\n      - [generalize dependent x]: move the variable [x] (and anything\n        else that depends on it) from the context back to an explicit\n        hypothesis in the goal formula *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (beq_nat_sym)  *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advancedM? (beq_nat_sym_informal)  *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n   Proof:\n   (* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advancedM (split_combine)  *)\n(** We proved, in an exercise above, that for all lists of pairs,\n    [combine] is the inverse of [split].  How would you formalize the\n    statement that [split] is the inverse of [combine]?  When is this\n    property true?\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?) *)\n\nDefinition split_combine_statement : Prop\n  (* (\"[: Prop]\" means that we are giving a name to a\n     logical proposition here.) *)\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nTheorem split_combine : split_combine_statement.\nProof.\n(* FILL IN HERE *) Admitted.\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise)  *)\n(** This one is a bit challenging.  Pay attention to the form of your\n    induction hypothesis. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  (* FILL IN HERE *) Admitted.", "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/tactics - Copy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658104908603, "lm_q2_score": 0.8774767954920548, "lm_q1q2_score": 0.6981715242024822}}
{"text": "(** \nPerfect Crypto - Simple definitions for message encryption and signing using\nsymmetric and assymetric keys\n\nPerry Alexander\nThe University of Kansas\n\nProvides definitions for:\n\n- [keyType] - [symmetric], [public] and [private] key constructors.\n- [inverse] - defines the inverse of any key.\n- [is_inverse] - proof that [inverse] is decidable and provides a decision procesure for [inverse].\n- [is_not_decryptable] - predicate indicating that a message is or is not decryptable using a specified key.\n- [decrypt] - attempts to decrypt a message with a given key.  Returns the decrypted message if decryption occurs.  Returns a proof that the message cannot be decrypted with the key if decryption does not occur.\n- [is_signed] - proof that signature checking is decidable and provides a decision procedure for signature check.\n- [check] - checks a signature on a message with a given key.  Returns a proof that the check succeeds or does not succeed.\n- [check_dec] - proof that signature checking is decidable and provides a decision procedure for signature checking.  Alternative function for [check].\n*)\n\nRequire Import Omega.\n\n(** Key values will be [nat] *)\n\nDefinition key_val : Type := nat.\n\n(** Key types are [symmetric], [public] and [private]. *)\nInductive keyType: Type :=\n| symmetric : key_val -> keyType\n| private : key_val -> keyType\n| public : key_val -> keyType.\n\n(** A [symmetric] key is its own inverse.  A [public] key is the inverse of\n  the [private] key with the same [key_val].  A [private] key is the inverse of\n  the [public] key with the same [key_val]. *)\n\nFixpoint inverse(k:keyType):keyType :=\nmatch k with\n| symmetric k => symmetric k\n| public k => private k\n| private k => public k\nend.\n\n(** Proof that inverse is decidable for any two keys. The resulting proof\n gives us the function [is_inverse] that is a decision procedure for key \n inverse checking.  It will be used in [decrypt] and [check] later in the\n specification. *)\nTheorem is_inverse:forall k k', {k = (inverse k')}+{k <> (inverse k')}.\nProof.\n  intros.\n  destruct k; destruct k'.\n  destruct (eq_nat_dec k k0) as [Hinv | Hninv].\n    left. simpl. auto.\n    right. simpl. unfold not. intros. inversion H. contradiction.\n  right; simpl; unfold not; intros; inversion H.\n  right. simpl. unfold not. intros. inversion H.\n  right. simpl. unfold not. intros. inversion H.\n  right. simpl. unfold not. intros. inversion H.\n  destruct (eq_nat_dec k k0) as [Hinv | Hninv].\n    left. simpl. auto.\n    right. simpl. unfold not. intros. inversion H. contradiction.\n  right. simpl. unfold not. intros. inversion H.\n  destruct (eq_nat_dec k k0) as [Hinv | Hninv].\n    left. simpl. auto.\n    right. simpl. unfold not. intros. inversion H. contradiction.\n  right. simpl. unfold not. intros. inversion H.\nDefined.\n\nEval compute in (is_inverse (public 1) (private 1)).\n\nEval compute in (is_inverse (public 1) (private 2)).\n\nEval compute in (is_inverse (public 2) (private 1)).\n\nEval compute in (is_inverse (private 1) (public 1)).\n\nEval compute in (is_inverse (symmetric 1) (symmetric 1)).\n\nEval compute in (is_inverse (symmetric 1) (symmetric 2)).\n\n(** Various proofs for keys and properties of the inverse operation.  All keys\n  must have an inverse.  All keys have a unique inverse.  Equal inverses come\n  from equal keys *)\n\nTheorem inverse_injective : forall k1 k2, inverse k1 = inverse k2 -> k1 = k2.\nProof.\n  intros.\n  destruct k1; destruct k2; simpl in H; try (inversion H); try (reflexivity).\nQed.\n\nHint Resolve inverse_injective.\n\nTheorem inverse_inverse : forall k, inverse (inverse k) = k.\nProof.\n  intros. destruct k; try reflexivity.\nQed.\n\nHint Resolve inverse_inverse.\n\nTheorem inverse_surjective : forall k, exists k', (inverse k) = k'.\nProof.\n  intros. exists (inverse k). auto.\nQed.\n\nHint Resolve inverse_surjective.\n\nTheorem inverse_bijective : forall k k',\n    inverse k = inverse k' ->\n    k = k' /\\ forall k, exists k'', inverse k = k''.\nProof.\n  auto.\nQed.\n\n(** Basic messages held abstract.  Compound messages are keys, encrypted and\n  signed messages, hashes and pairs. *) \n\nInductive message(basicType:Type) : Type :=\n| basic : basicType -> message basicType\n| key : keyType -> message basicType\n| encrypt : message basicType -> keyType -> message basicType\n| sign : message basicType -> keyType -> message basicType\n| hash : message basicType -> message basicType\n| pair : message basicType -> message basicType -> message basicType.\n\n(** Predicate that determines if a message cannot be decrypted.  Could be\n  that it is not encrypted to begin with or the wrong key is used. *)\n\nDefinition is_not_decryptable{T:Type}(m:message T)(k:keyType):Prop :=\n  match m with\n  | basic _ => True\n  | key _ => True\n  | encrypt m' k' => k <> inverse k'\n  | sign _ _ => True\n  | hash _ => True\n  | pair _ _ => True\n  end.\n\n(** [decrypt] returns either a decrypted message or a proof of why the message\n  cannot be decrypted. *)\n\nFixpoint decrypt{T:Type}(m:message T)(k:keyType):(message T)+{(is_not_decryptable m k)}.\nrefine\n  match m with\n  | basic c => inright _ _\n  | key _ => inright _ _\n  | encrypt m' j => (if (is_inverse k j) then (inleft _ m') else (inright _ _ ))\n  | sign m' k => inright _ _\n  | hash _ => inright _ _\n  | pair _ _ => inright _ _\n  end.\nProof.\n  reflexivity.\n  reflexivity.\n  simpl. assumption.\n  reflexivity.\n  reflexivity.\n  reflexivity.\nDefined.\n  \nEval compute in decrypt(encrypt nat (basic nat 1) (symmetric 1)) (symmetric 1).\n\nEval compute in decrypt(encrypt nat (basic nat 1) (symmetric 1)) (symmetric 2).\n\n(** Predicate that determines if a message is properly signed. *)\n\nDefinition is_signed{T:Type}(m:message T)(k:keyType):Prop :=\n  match m with\n  | basic _ => False\n  | key _ => False\n  | encrypt _ _ => False\n  | sign m' k' => k = inverse k'\n  | hash _ => False\n  | pair _ _ => False\n  end.\n\n(** Signature check returns either a proof that the signature is correct\n  or a proof that the signature is not correct. *)\n\nFixpoint check{T:Type}(m:message T)(k:keyType):{(is_signed m k)}+{not (is_signed m k)}.\nrefine\n  match m with\n  | basic c => right _ _\n  | key _ => right _ _\n  | sign m' j => (if (is_inverse k j) then (left _ _) else (right _ _ ))\n  | encrypt m' k => right _ _\n  | hash _ => right _ _\n  | pair _ _ => right _ _\n  end.\nProof.\n  unfold not. intros. simpl in H. assumption.\n  unfold not. intros. simpl in H. assumption.\n  unfold not. intros. simpl in H. assumption.\n  destruct (is_inverse j k).\n  simpl. rewrite _H. reflexivity.\n  simpl. rewrite <- _H. reflexivity.\n  simpl. assumption.\n  unfold not. intros. simpl in H. assumption.\n  unfold not. intros. simpl in H. assumption.\nDefined.\n\nEval compute in check(sign nat (basic nat 1) (private 1)) (public 1).\n\nEval compute in check(sign nat (basic nat 1) (private 1)) (public 2).\n\nTheorem check_dec: forall T, forall m:(message T), forall k, {(is_signed m k)}+{not (is_signed m k)}.\nProof.\n  intros.\n  destruct m.\n  right. unfold is_signed. tauto.\n  right. unfold is_signed. tauto.\n  right. unfold is_signed. tauto.\n  destruct (is_inverse k0 k).\n  left. simpl. rewrite e. auto.\n  right. unfold not. simpl. unfold not in n. intros. subst. auto.\n  right. unfold is_signed. tauto.\n  right. unfold is_signed. tauto.\nDefined.\n\nEval compute in check_dec nat (sign nat (basic nat 1) (private 1)) (public 1).\n\nEval compute in check_dec nat (sign nat (basic nat 1) (private 1)) (public 2).\n\n\nRequire Import List.\nDefinition Name := nat.\n\nDefinition KeyServer  := list (Name * {k : keyType | exists x, k = public x}) % type.\n\n\nSearchAbout exist .\nLemma noteqpOne : forall x : nat, S x <> x.\nProof.  intros. induction x. congruence. unfold not.  intros. inversion H. contradiction.  Qed.\n\n\nFixpoint nameinServer (n : Name) (ks : KeyServer): bool :=\n  match ks with \n   | nil => false\n   | x :: xs => match x with \n                 (na,kk) => if beq_nat na n then true else nameinServer n xs\n                end\n  end. \nInductive keyServerError (ks : KeyServer): Prop :=\n | notAPublicKey : {k  | forall x, k <> public x} -> keyServerError ks\n | alreadyEntryForName : { n : Name | (nameinServer n ks) = true} -> keyServerError ks. \n\nSearchAbout In.\n    \nDefinition addKey (ks : KeyServer) (name : Name) (k : keyType) : KeyServer + {keyServerError ks}.\nProof. destruct k. case (symmetric k). intros. right. constructor. exists (symmetric k) . intros. unfold not. intros. inversion H.\nright. constructor. exists (private k). intros. unfold not. intros. inversion H.\nleft. assert ((public k) = (public k)). reflexivity.  refine ((name, _) ::ks).\neauto. Defined. \n\nDefinition ks0 : KeyServer := nil.\nEval compute in addKey ks0 1 (public 1).\nEval compute in addKey ks0 1 (private 1).\nEval compute in addKey ks0 1 (symmetric 1).\n\nFixpoint realRemove (ks : KeyServer) (name :Name) : KeyServer :=\n  match ks with \n    | nil => nil\n    | x :: xs => if beq_nat (fst x) name then realRemove xs name else x :: (realRemove xs name)\n  end.\n\nFixpoint  removeKey (ks : KeyServer) (name : Name) : KeyServer + {nameinServer name ks = false}.\n  case_eq (nameinServer name ks). intros. left. exact (realRemove ks name).\n  intros. right. reflexivity. Defined.\n\nDefinition PubProof :={k : keyType | exists x, k = public x}.\n\n\nDefinition pub2 : {k : keyType | exists x, k = public x}. exists (public 2). exists 2. reflexivity. Defined.   \nDefinition pub3 : PubProof. exists (public 3). exists 3. reflexivity. Defined.  \n\nDefinition ks3 := (2,pub2) :: ((3,pub3) :: ks0).\nEval compute in removeKey ks3 1.\nEval compute in removeKey ks3 2.\nEval compute in removeKey ks3 3.\nEval compute in removeKey ks3 4.\n\nDefinition publicServerKey := public 0.\nDefinition privateServerKey := private 0. \n\nInductive Maybe {T : Type} :=\n | Just : T -> Maybe\n | Nothing : Maybe.\n(*\nTheorem inImpliesIn : forall T : Type, \n                      forall t : T,\n                      forall t2 : T,\n                      forall ls : list T,\n                      In t ls \n*)\nSearchAbout In.\nFixpoint findOr (name : Name) (ks : KeyServer) : { x :PubProof | In (name,x) ks} + {forall kp : PubProof, ~In (name,kp) ks}. \nProof. induction ks. right.  intros.  simpl. unfold not.  intros.  apply H. \ndestruct a.  case_eq (beq_nat name n).  intros. left.  exists s.  SearchAbout beq_nat. symmetry in H. apply beq_nat_eq in H. rewrite H. SearchAbout In. apply in_eq.   \nintros. SearchAbout In. destruct IHks. left. destruct s0.  exists x. simpl. right. apply i. (* destruct s0. apply s0.  simpl.   exists s. exact p. right. *)\nintros. assert (forall pp, ~ (n,s) = (name, pp)). intros.  unfold not. intros. inversion H0. SearchAbout beq_nat. apply beq_nat_false in H.   symmetry in H2. contradiction.\nSearchAbout In. unfold not. right. intros. simpl in H1.  destruct H1.  apply H0 in H1.  apply H1. apply n0 in H1.  apply H1. Defined. \n\n\n(*\nFixpoint findMaybe (name : Name) (ks : KeyServer) : Maybe (T := PubProof).\nProof.  intros. remember k as p.   trivial. remember k. ( k : PubProof).\n\n\n\n :=\n  match ks with \n   | nil => Nothing\n   | x :: xs => if beq_nat (fst x) name then Just (snd x) else findMaybe name xs\n  end.\n\nTheorem findMaybeNotEmpty : forall name : Name, forall ks : KeyServer,\n forall s,  findMaybe name ks = Just s -> ks <> nil. \nProof. intros. induction ks. intros.  simpl in H. inversion H. unfold not. intros.  inversion H0. Qed.\nTheorem nameinServerNotEmpty : forall name : Name, forall ks : KeyServer,\n  nameinServer name ks = true -> ks <> nil. \nProof. intros. unfold not. intros. unfold nameinServer in H. rewrite H0 in H. inversion H. Defined.\n\nTheorem notInImpliesNothings : forall (name : Name), forall ks : KeyServer, forall kp, ~(In (name,kp) ks) -> findMaybe name ks = Nothing.\nProof. intros.  unfold not in H. simpl.  \n\nTheorem  findImpliesIn : forall (name : Name), forall (ks : KeyServer), forall (s : PubProof),\n(findMaybe name ks = Just s) ->   In (name, s) ks.\nProof.  intros. exists s.  case_eq (findMaybe name ks). intros.  induction findMaybe. \n*)\n\n\nFixpoint requestKey {T : Type} (name :Name) (ks : KeyServer) : { m : message T | \n                                                                 exists kp, m = sign T (key T (proj1_sig kp)) privateServerKey /\\\n                                                                 In (name,kp) ks } + {forall kp, ~ (In (name,kp) ks)}. \nProof. case_eq (findOr name ks). intros. destruct s.  left.  exists (sign T (key T (proj1_sig x)) privateServerKey). exists x. split. reflexivity. apply i. intros.    right. apply n. Defined.  \n\n\n\nFixpoint findMaybe (name : Name) (ks : KeyServer) : Maybe :=\n  match ks with \n   | nil => Nothing\n   | x :: xs => if beq_nat (fst x) name then Just (snd x) else findMaybe name xs\n  end.\n\nTheorem nameinServerNotEmpty : forall name : Name, forall ks : KeyServer,\n  nameinServer name ks = true -> ks <> nil. \nProof. intros. unfold not. intros. unfold nameinServer in H. rewrite H0 in H. inversion H. Defined.\n\n\n\nFixpoint requestKey2 (name :Name) (ks : KeyServer) : keyType + { findMaybe name ks = Nothing}. \nProof. case_eq (findMaybe name ks). intros. left.  exact (proj1_sig s). right. reflexivity. Defined.  \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(*\n\n name ks = false}.\nProof. case_eq (nameinServer name ks). intros.   induction (requestKey name ks).  (findMaybe name ks). intros. left.  exact (proj1_sig t). right. simpl.  \n\nFixpoint requestKey (name :Name) (ks : KeyServer) : Maybe := findMaybe name ks.  \n\n*)\n\nInductive RealMessage (T : Type) := \n  realmessage : Name -> Name -> message T -> RealMessage T.\n \nDefinition send {T : Type} (pk : keyType) (encryp : keyType) (m : message T) (fromGuy : Name) (toGuy : Name) : {mp : RealMessage T | mp = realmessage T fromGuy toGuy (sign T (encrypt T m encryp) pk)}.\nProof.  exists ( realmessage T fromGuy toGuy (sign T (encrypt T m encryp) pk)). reflexivity. Defined. \nDefinition getFrom {T : Type} (mp : RealMessage T): Name :=\n  match mp with\n   | realmessage f t m => f\n  end. \nDefinition getTo {T : Type} (mp : RealMessage T): Name :=\n  match mp with\n   | realmessage f t m => t\n  end.\n\nDefinition getMessage {T : Type} (mp : RealMessage T): message T :=\n  match mp with\n   | realmessage f t m => m\n  end. \nInductive MyError : Prop :=\n  myerror : MyError.\n(*\nDefinition checkServerMessage {T :Type} {ks : KeyServer} {name : Name} (mp : { m : message T |   exists kp, m = sign T (key T (proj1_sig kp)) privateServerKey /\\\n                                                   In (name,kp) ks }) : keyType. case_eq mp. intros.  destruct x. inversion e.    exists kp. e. destruct e. \nProof. intros. \nDefinition requestKey2{T : Type} (name: Name) (ks : KeyServer) : keyType  + {forall kp, ~ (In (name,kp) ks)}.\n\nProof. case_eq (requestKey ( T:=T) name ks ). intros. left.  destruct s. exact kp. elim e. destruct e. left.    simpl e. destruct e.  simpl in s.  remember (proj2_sig s).   left. destruct s. exact k.  case_eq s.  intros.  destruct s.   \n*)\nInductive badbadnotgood {T : Type} ( mp : RealMessage T) (ks : KeyServer) (key : keyType) : Prop :=\n  | notsignedman : (exists k, requestKey2 (getFrom mp) ks = inleft k /\\ ~ (is_signed (getMessage mp) (k))) -> badbadnotgood mp ks key\n  | cantdecryptman : { m : message T | exists innerM : message T, forall k, forall mm, innerM <> encrypt T mm k /\\ exists someK,                                  \n                       m = sign T innerM someK} -> badbadnotgood mp ks key\n  | myKeyFails : badbadnotgood mp ks key\n  | keyLookupFail : badbadnotgood mp ks key.\n\nTheorem inverses : forall k1 k2, inverse k1 = k2 -> inverse k2 = k1.\nProof. intros. destruct k1.  \n  simpl in H. rewrite <- H.  simpl. reflexivity. \n  simpl in H. rewrite <- H.  simpl. reflexivity.  \n  simpl in H.  rewrite <- H. simpl. reflexivity. Qed. \n\nDefinition receiveMessage {T : Type} (ks : KeyServer) (mp : RealMessage T) (mypriv : keyType) : \n   {res : message T |  exists kpub, (requestKey2 (getFrom mp) ks) = inleft kpub /\\  (exists k2, (getMessage mp) = sign T (encrypt T res k2) (inverse kpub) /\\\n                       decrypt (encrypt T res k2) mypriv= (inleft res) )\n                        }\n                  \n  + { badbadnotgood mp ks mypriv }.\nProof. case_eq (requestKey2 (getFrom mp) ks).  (*at this point, successful look up of pub key *)\n  intros.    \n    case_eq (getMessage mp).\n       intros. right.  constructor. exists k. split.  apply H.  rewrite H0. simpl. unfold not. intros.  apply H1. \n       intros. right. constructor. exists k. split. apply H.  rewrite H0. simpl. unfold not. intros. apply H1. \n       intros. right. constructor. exists k. split. apply H.  rewrite H0. simpl. unfold not. intros. apply H1.\n       intros. rename m into hopefullyEncrypted.\n       case_eq (is_inverse k0 k).\n        intros.  \n         (* this is the signed case *)\n         case_eq (hopefullyEncrypted). (* for all except encrypt form, return the error. *)\n           intros.  right.  apply cantdecryptman. exists  (getMessage mp). exists hopefullyEncrypted. intros. unfold not. rewrite H2. split.  intros.  inversion H3. exists k0. rewrite H0. rewrite H2. reflexivity. \n           intros.   right.  apply cantdecryptman. exists  (getMessage mp). exists hopefullyEncrypted. intros. unfold not. rewrite H2. split.  intros.  inversion H3. exists k0. rewrite H0. rewrite H2. reflexivity.\n           (*encrypt case *) intros. case_eq (decrypt hopefullyEncrypted mypriv). \n                                        intros.  left. exists m. exists k. split. reflexivity. exists k1. split.    rewrite e.  reflexivity.\n                                            assert (m0 = m).  rewrite H2 in H3.  simpl in H3. destruct (is_inverse mypriv k1).  inversion H3.  reflexivity.  inversion H3.  rewrite <- H2. rewrite H4 in H3. apply H3. \n                                                                      \n                                        intros. right. apply myKeyFails. (* this needs more descriptive args, but I'm really tired of this. *) \n           intros.    right.  apply cantdecryptman. exists  (getMessage mp). exists hopefullyEncrypted. intros. unfold not. rewrite H2. split.  intros.  inversion H3. exists k0. rewrite H0. rewrite H2. reflexivity. \n           intros.    right.  apply cantdecryptman. exists  (getMessage mp). exists hopefullyEncrypted. intros. unfold not. rewrite H2. split.  intros.  inversion H3. exists k0. rewrite H0. rewrite H2. reflexivity. \n           intros.    right.  apply cantdecryptman. exists  (getMessage mp). exists hopefullyEncrypted. intros. unfold not. rewrite H2. split.  intros.  inversion H3. exists k0. rewrite H0. rewrite H2. reflexivity. \n           intros. right. constructor. exists k. split. apply H.  rewrite H0. simpl. unfold not. intros. unfold not in n.  symmetry in H2. apply inverses in H2. symmetry in H2.   apply n in H2. apply H2.\nintros. right. constructor. exists k. split. apply H.  rewrite H0. simpl. unfold not. intros. apply H1.\nintros. right. constructor. exists k. split. apply H.  rewrite H0. simpl. unfold not. intros. apply H1.\n   intros. right.  apply keyLookupFail. (* needs more args again.*) Defined. \n\nDefinition engage {T: Type} (a : Name) (aPriv : keyType) (b: Name) ( bPriv : keyType) (ks : KeyServer) (m : message T) := \n   match requestKey2 b ks with \n     | inright _ => false\n     | inleft bPub => match receiveMessage ks (proj1_sig  (send bPriv aPriv m a b) ) bPriv with\n                          | inright _ => false\n                          | inleft _ => true\n                      end\n   end. \n\n(*\nTheorem Any message leaving a sending node is encrypted and signedsendTheorem     -- this is proven in the return type of send. \n)*)\n\n\n\n\n\n\n     ", "meta": {"author": "paul-kline", "repo": "coqFin", "sha": "465f23ccd7e42fc273c91e185bdee36ca31ea50e", "save_path": "github-repos/coq/paul-kline-coqFin", "path": "github-repos/coq/paul-kline-coqFin/coqFin-465f23ccd7e42fc273c91e185bdee36ca31ea50e/Crypto.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.698171523351276}}
{"text": "Parameter Atom : Type.\n\nInductive Proposition: Type := \n  | Atomic(P: Atom)\n  | Negation(P: Proposition)\n  | Conjunction(P Q: Proposition)\n  | Disjunction(P Q: Proposition)\n  | Implication(P Q: Proposition).\n\nNotation \"# P\" := (Atomic P) (at level 1).\nNotation \"¬ P\" := (Negation P) (at level 2).\nNotation \"P ∧ Q\" := (Conjunction P Q) (at level 3).\nNotation \"P ∨ Q\" := (Disjunction P Q) (at level 3).\nNotation \"P → Q\" := (Implication P Q) (at level 4).\n\nFixpoint valuation v P: bool :=\n  match P with\n  | # P' => v P'\n  | ¬ P' => negb (valuation v P')\n  | P' ∧ Q' => andb (valuation v P') (valuation v Q')\n  | P' ∨ Q' => orb (valuation v P') (valuation v Q')\n  | P' → Q' => orb (negb (valuation v P')) (valuation v Q')\n  end.\n\n(* TODO: Logical Equivalence and Substitution *)\n\n(* Satisfiability, Validity etc. *)\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\nDefinition satisfiable P: Prop := \n  exists v, valuation v P = true.\n\nDefinition valid P: Prop := \n  forall v, valuation v P = true.\n\nDefinition unsatisfiable P: Prop :=\n  forall v, valuation v P = false.\n\nDefinition falsifiable P: Prop :=\n  exists v, valuation v P = false.\n\nDefinition Satisfies v Γ: Prop :=\n  forall A, In A Γ -> valuation v A = true.\n\nFixpoint satisfies v Γ: bool :=\n  match Γ with\n  | nil => true\n  | (p' :: Γ')%list => andb (valuation v p') (satisfies v Γ')\n  end.\n\nTheorem Satisfies_to_split: forall v Γ a,\n  Satisfies v (a :: Γ)%list -> (valuation v a) = true /\\ Satisfies v Γ.\nProof.\n  unfold Satisfies.\n  intros.\n  split.\n  - apply H.\n    simpl.\n    left.\n    reflexivity.\n  - intros.\n    apply H.\n    simpl.\n    right.\n    apply H0.\nQed. \n\nTheorem split_to_Satisfies: forall v Γ a,\n  (valuation v a) = true /\\ Satisfies v Γ -> Satisfies v (a::Γ)%list.\nProof.\n  intros v Γ A [H1 H2].\n  unfold Satisfies.\n  intros.\n  simpl in H.\n  destruct H as [H | H].\n  - rewrite <- H. apply H1.\n  - unfold Satisfies in H2. apply H2.\n    apply H.\nQed.  \n\nTheorem satisfy_chain: forall v Γ A,\n  (valuation v A) = true -> Satisfies v Γ -> Satisfies v (A :: Γ)%list.\nProof.\n  intros.\n  apply split_to_Satisfies.\n  split.\n  apply H.\n  apply H0.\nQed.\n\nDefinition models Γ A: Prop :=\n  forall v, Satisfies v Γ -> valuation v A = true.\n\nNotation \"Γ |= A\" := (models Γ A) (at level 10).\n\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\n\nLemma and_both_true: forall p q,\n  (p && q)%bool = true -> p = true /\\ q = true.\nProof.\n  destruct p, q;\n  simpl;\n  intros.\n  - split; reflexivity.\n  - discriminate.\n  - discriminate.\n  - discriminate.\nQed.\n\nLemma or_either_true: forall p q,\n  (p || q)% bool = true -> p = true \\/ q = true.\nProof.\n  destruct p, q.\n  simpl;\n  intros.\n  - left. reflexivity.\n  - left. reflexivity.\n  - right. reflexivity.\n  - discriminate.\nQed.  \n\n\nTheorem Satisfies_iff_satisfies: forall Γ v,\n  Satisfies v Γ <-> satisfies v Γ = true.\nProof.\n  intros.\n  split.\n  - induction Γ.\n    + intros. simpl. reflexivity.\n    + intros.\n      simpl satisfies. \n      apply Satisfies_to_split in H.\n      destruct H as [H1 H2].\n      rewrite H1.\n      simpl.\n      apply IHΓ.\n      apply H2.\n  - induction Γ.\n    simpl.\n    + intros.\n      unfold Satisfies.\n      simpl.\n      intros.\n      inversion H0.\n    + intros. apply split_to_Satisfies.\n      split.\n      * simpl in H.\n        destruct (valuation v a).\n        --  reflexivity.\n        --  simpl in H.\n            discriminate H.\n      * apply IHΓ.\n        simpl in H.\n        apply and_both_true in H.\n        destruct H as [_ H].\n        apply H.\nQed.\n        \n\n\n\n", "meta": {"author": "wags-1314", "repo": "logic-in-Coq", "sha": "be5c9ab2fc951075142969d1fbbc33e962272959", "save_path": "github-repos/coq/wags-1314-logic-in-Coq", "path": "github-repos/coq/wags-1314-logic-in-Coq/logic-in-Coq-be5c9ab2fc951075142969d1fbbc33e962272959/PropLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.6981715144327889}}
{"text": "\nRequire Import Bool Arith List Cpdt.CpdtTactics.\nSet Implicit Arguments.\n\n(* Source Language *)\n\nInductive type : Set := Nat | Bool.\n\nInductive binop : type -> type -> type -> Set :=\n| Plus : binop Nat Nat Nat\n| Times : binop Nat Nat Nat\n| Eq : forall t , binop t t Bool\n| Lt : binop Nat Nat Bool\n.\n\nInductive exp : type -> Set :=\n| NConst : nat -> exp Nat\n| BConst : bool -> exp Bool\n| Binop : forall t1 t2 t , binop t1 t2 t -> exp t1 -> exp t2 -> exp t\n.\n\nDefinition typeDenote (t: type) : Set :=\n  match t with\n  | Nat => nat\n  | Bool => bool\n  end\n.\n\nDefinition binopDenote arg1 arg2 res (b: binop arg1 arg2 res)\n  : typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=\n  match b with\n  | Plus => plus\n  | Times => mult\n  | Eq Nat => beq_nat\n  | Eq Bool => eqb\n  | Lt => leb\n  end\n.\n\nFixpoint expDenote t (e : exp t) : typeDenote t :=\n  match e with\n  | NConst n => n\n  | BConst b => b\n  | Binop _ _ _ b e1 e2 => (binopDenote b) (expDenote e1) (expDenote e2)\n  end\n.\n\n(* Target langauge *)\n\nDefinition tstack := list type.\n\n(* Define an indexed type family, which captures the relation between well\n   defined stacks *)\nInductive instr : tstack -> tstack -> Set :=\n| INConst : forall s , nat -> instr s (Nat :: s)\n| IBConst : forall s , bool -> instr s (Bool :: s)\n| IBinop : forall arg1 arg2 res s ,\n    binop arg1 arg2 res -> instr (arg1 :: arg2 :: s) (res :: s)\n.\n\nInductive prog : tstack -> tstack -> Set :=\n| Nil : forall s , prog s s\n| Cons : forall s1 s2 s3 ,\n    instr s1 s2 -> prog s2 s3 -> prog s1 s3\n.\n\nFixpoint vstack (ts : tstack) : Set :=\n  match ts with\n  | nil => unit\n  | t :: ts' => typeDenote t * vstack ts'\n  end % type (* %type means parse as a type *)\n.\n\nDefinition instrDenote ts ts' (i : instr ts ts') : vstack ts -> vstack ts' :=\n  match i with\n  | INConst _ n => fun s => (n, s)\n  | IBConst _ b => fun s => (b, s)\n  | IBinop _ _ _ _ b => fun s =>\n                          let '(arg1, (arg2, s')) := s in\n                          ((binopDenote b) arg1 arg2, s')\n  end\n.\n\nFixpoint progDenote ts ts' (p : prog ts ts') : vstack ts -> vstack ts' :=\n  match p with\n  | Nil _ => fun s => s\n  | Cons _ _ _ i p' => fun s => progDenote p' (instrDenote i s)\n  end\n.\n\nFixpoint concat ts ts' ts'' (p : prog ts ts') : prog ts' ts'' -> prog ts ts'' :=\n  match p with\n  | Nil _ => fun p' => p'\n  | Cons _ _ _ i p1 => fun p' => Cons i (concat p1 p')\n  end\n.\n\nFixpoint compile t (e : exp t) (ts : tstack) : prog ts (t :: ts) :=\n  match e with\n  | NConst n => Cons (INConst _ n) (Nil _)\n  | BConst b => Cons (IBConst _ b) (Nil _)\n  | Binop _ _ _ b e1 e2 =>\n    concat (compile e2 _)\n           (concat (compile e1 _) (Cons (IBinop _ b) (Nil _)))\n  end\n.\n\nLemma compile_correct' : forall t (e : exp t) ts (s : vstack ts) ,\n    progDenote (compile e ts) s = (expDenote e, s)\n.\n\ninduction e; crush.\n\nAbort.\n\nLemma concat_correct : forall ts ts' ts'' (p : prog ts ts') (p' : prog ts' ts'') (s : vstack ts) ,\n    progDenote (concat p p') s = progDenote p' (progDenote p s)\n.\n    induction p; crush.\nQed.\n\nHint Rewrite concat_correct.\n\nLemma compile_correct' : forall t (e : exp t) ts (s : vstack ts),\n    progDenote (compile e ts) s = (expDenote e, s).\n    induction e; crush.\nQed.\n\nHint Rewrite compile_correct'.\n\nTheorem compile_correct : forall t (e : exp t),\n    progDenote (compile e nil) tt = (expDenote e, tt).\n    crush.\nQed.\n\nExtraction compile.\n\n", "meta": {"author": "andorp", "repo": "cpdt", "sha": "dd2099eeae2f12e1379a8706420f072aa174adc5", "save_path": "github-repos/coq/andorp-cpdt", "path": "github-repos/coq/andorp-cpdt/cpdt-dd2099eeae2f12e1379a8706420f072aa174adc5/StackMachine2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695836, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6981715016774822}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.lemma_extension.\nRequire Import ProofCheckingEuclid.lemma_inequalitysymmetric.\nRequire Import ProofCheckingEuclid.lemma_orderofpoints_ABC_BCD_ABD.\nRequire Import ProofCheckingEuclid.lemma_s_onray.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_onray_assert :\n\tforall A B E,\n\t(BetS A E B \\/ eq E B \\/ BetS A B E) -> neq A B ->\n\tOnRay A B E.\nProof.\n\tintros A B E.\n\tintros BetS_A_E_B_or_eq_E_B_or_BetS_A_B_E.\n\tintros neq_A_B.\n\n\tpose proof (lemma_inequalitysymmetric _ _ neq_A_B) as neq_B_A.\n\tpose proof (lemma_extension _ _ _ _ neq_B_A neq_A_B) as (J & BetS_B_A_J & Cong_AJ_AB).\n\tpose proof (axiom_betweennesssymmetry _ _ _ BetS_B_A_J) as BetS_J_A_B.\n\n\tdestruct BetS_A_E_B_or_eq_E_B_or_BetS_A_B_E as [BetS_A_E_B | [eq_E_B | BetS_A_B_E]].\n\t{\n\t\t(* case BetS_A_E_B *)\n\t\tpose proof (axiom_orderofpoints_ABD_BCD_ABC _ _ _ _ BetS_J_A_B BetS_A_E_B) as BetS_J_A_E.\n\t\tpose proof (lemma_s_onray _ _ _ _ BetS_J_A_B BetS_J_A_E) as OnRay_AB_E.\n\t\texact OnRay_AB_E.\n\t}\n\t{\n\t\t(* case eq_E_B *)\n\t\tassert (BetS J A E) as BetS_J_A_E by (rewrite eq_E_B; exact BetS_J_A_B).\n\t\tpose proof (lemma_s_onray _ _ _ _ BetS_J_A_B BetS_J_A_E) as OnRay_AB_E.\n\t\texact OnRay_AB_E.\n\t}\n\t{\n\t\t(* case BetS_A_B_E *)\n\t\tpose proof (lemma_orderofpoints_ABC_BCD_ABD _ _ _ _ BetS_J_A_B BetS_A_B_E) as BetS_J_A_E.\n\t\tpose proof (lemma_s_onray _ _ _ _ BetS_J_A_B BetS_J_A_E) as OnRay_AB_E.\n\t\texact OnRay_AB_E.\n\t}\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_onray_assert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.6981372713238952}}
{"text": "Set Implicit Arguments.\nUnset Standard Proposition Elimination Names.\n\nRequire Export List.\n\nRequire Import\n  Program Omega Factorial\n  Bool util Morphisms Relations RelationClasses Permutation.\n\nHint Resolve\n  in_map Permutation_refl.\n\nHint Constructors NoDup.\n\nHint Constructors\n  NoDup Permutation.\n\nArguments length {A}.\nArguments Permutation {A}.\nArguments map {A B}.\nArguments tail {A}.\n\nSection count.\n\n  Context {X: Type} (p: X -> bool).\n\n  Fixpoint count (l: list X): nat :=\n    match l with\n    | nil => 0\n    | h :: t => if p h then S (count t) else count t\n    end.\n\n  Lemma count_app l l': count (l ++ l') = count l + count l'.\n  Proof with auto.\n    induction l...\n    simpl.\n    destruct (p a)...\n    intros.\n    rewrite IHl...\n  Qed.\n\n  Lemma count_0 l: (forall x, In x l -> p x = false) -> count l = 0.\n  Proof with auto. induction l... simpl. intros. rewrite H... Qed.\n\n  Lemma count_le l: count l <= length l.\n  Proof with auto with arith.\n    induction l...\n    simpl.\n    destruct (p a)...\n  Qed.\n\n  Lemma count_filter_le (f: X -> bool) x: count (filter f x) <= count x.\n  Proof with auto with arith.\n    induction x...\n    simpl.\n    destruct (f a).\n      simpl.\n      destruct (p a)...\n    destruct (p a)...\n  Qed.\n\n  Hint Resolve count_le.\n\n  Lemma count_lt v l: In v l -> p v = false -> count l < length l.\n  Proof with auto with arith.\n    induction l; simpl; intros.\n      elimtype False...\n    inversion_clear H.\n      subst.\n      rewrite H0...\n    destruct (p a)...\n  Qed.\n\nEnd count.\n\nHint Resolve @count_le.\n\nLemma NoDup_map_inv' A B (f: A -> B) (l: list A): NoDup (map f l) -> NoDup l.\nProof with auto.\n  induction l...\n  simpl.\n  intros.\n  inversion_clear H.\n  apply NoDup_cons...\nQed.\n\nLemma length_filter X (p: X -> bool) (l: list X): length (filter p l) = count p l.\nProof with auto. intros. induction l... simpl. destruct (p a)... simpl... Qed.\n\nLemma length_filter_le T (p: T -> bool) (l: list T): length (filter p l) <= length l.\nProof. intros. rewrite length_filter. apply count_le. Qed.\n\nLemma filter_all X (p: X -> bool) (l: list X):\n  (forall x, In x l -> p x = true) -> filter p l = l.\nProof with auto.\n  induction l...\n  simpl.\n  intros.\n  rewrite H...\n  rewrite IHl...\nQed.\n\nLemma In_filter T (p: T -> bool) (t: T): p t = true -> forall l, In t l -> In t (filter p l).\nProof. intros. destruct (filter_In p t l). apply H2; auto. Qed.\n\nLemma incl_filter X (p: X -> bool) (l: list X): incl (filter p l) l.\nProof with auto.\n  unfold incl.\n  induction l; simpl...\n  intros.\n  destruct (p a); firstorder.\nQed.\n\nLemma incl_trans A (x y: list A): incl x y -> forall z, incl y z -> incl x z.\nProof. do 5 intro. apply H0. apply H. assumption. Qed.\n\nHint Resolve incl_filter.\n\nLemma filter_preserves_incl X (p: X -> bool) (a b: list X): incl a b -> incl (filter p a) (filter p b).\nProof with auto.\n  unfold incl.\n  intros.\n  destruct (filter_In p a0 a).\n  clear H2.\n  destruct (H1 H0).\n  clear H1.\n  apply In_filter...\nQed.\n\nHint Resolve filter_preserves_incl.\n\nLemma In_inv_perm X (x: X) (l: list X):\n  In x l -> exists l', Permutation (x :: l') l.\nProof with eauto.\n  induction l; intros; inversion_clear H. subst...\n  destruct IHl...\nQed.\n\nLemma In_map_inv T U (f: T -> U) (l: list T) (y: U): In y (map f l) -> exists x, f x = y /\\ In x l.\nProof. induction l; firstorder. Qed.\n\nArguments In_map_inv [T U f l y].\n\nInstance In_Permutation A (x: A): Proper (Permutation ==> iff) (In x).\nProof.\n  repeat intro.\n  pose proof (Permutation_in).\n  pose proof (Permutation_sym).\n  firstorder.\nQed.\n\nInstance Permutation_NoDup {X}: Proper (Permutation ==> iff) (@NoDup X).\nProof with firstorder auto.\n  pose proof NoDup_cons.\n  intros ? ? E.\n  induction E; [firstorder | | | firstorder].\n    split; intro A; inversion_clear A; apply NoDup_cons...\n      rewrite <- E...\n    rewrite E...\n  split; intro A; inversion_clear A; inversion_clear H1...\nQed.\n\nHint Resolve incl_tran.\n\nLemma Permutation_incl X (a b: list X): Permutation a b -> incl a b.\nProof. induction 1; firstorder. Qed.\n\nInstance count_perm A: Proper (pointwise_relation _ eq ==> Permutation ==> eq) (@count A).\nProof with auto.\n  intros p p' E.\n  assert (forall l, count p l = count p' l).\n    induction l...\n    simpl. rewrite E, IHl...\n  intros l l' P.\n  induction P; intros; simpl...\n      rewrite IHP.\n      rewrite E...\n    repeat rewrite E. (*rewrite E at 3.*)\n    destruct (p' y); destruct (p' x)...\n  rewrite IHP1.\n  rewrite <- H...\nQed.\n\nLemma pointwise_eq_refl A B (x: A -> B): pointwise_relation A eq x x.\nProof. reflexivity. Qed.\nHint Immediate pointwise_eq_refl.\n  (* this really should be redundant *)\n\nInstance count_perm_simple A (p: A -> bool): Proper (Permutation ==> eq) (count p).\nProof. intros. apply count_perm. auto. Qed.\n  (* just an instantiation of count_perm, but rewriting with the latter can produce nasty existentials *)\n\nInstance filter_eq_morphism T: Proper (pointwise_relation _ eq ==> eq ==> eq) (@filter T).\nProof with auto.\n  repeat intro.\n  subst.\n  induction y0...\n  simpl.\n  rewrite H.\n  rewrite IHy0...\nQed.\n\nInstance filter_perm X: Proper (pointwise_relation _ eq ==> Permutation ==> Permutation) (@filter X).\nProof with auto.\n  repeat intro.\n  induction H0; rewrite H in *; simpl...\n      destruct (y x0)...\n    destruct (y y0); destruct (y x0)...\n  eauto.\nQed.\n\nLemma complementary_filter_perm A (p: A -> bool) (l: list A):\n  Permutation l (filter p l ++ filter (negb ∘ p) l).\nProof with auto.\n  induction l...\n  simpl.\n  unfold compose.\n  destruct (p a); simpl...\n  apply Permutation_cons_app...\nQed.\n\nLemma filter_none X (p: X -> bool) (l: list X): (forall x, In x l -> p x = false) <-> filter p l = nil.\nProof with auto.\n  induction l.\n    split...\n    intros.\n    inversion H0.\n  destruct IHl.\n  split; simpl; intros.\n    rewrite H1...\n  destruct H2.\n    subst.\n    destruct (p x)...\n    discriminate.\n  apply H0...\n  destruct (p a)...\n  discriminate.\nQed.\n\nLemma incl_map X Y (f: X -> Y) (a b: list X): incl a b -> incl (map f a) (map f b).\nProof with auto.\n  do 3 intro.\n  destruct (In_map_inv H0).\n  destruct H1.\n  subst...\nQed.\n\nLemma incl_in T (a b: list T): incl a b -> forall x, In x a -> In x b.\nProof. auto. Qed.\n\nLemma incl_In X (x: X) (l: list X): In x l -> forall l', incl l l' -> In x l'.\nProof. intros. apply H0. assumption. Qed. (* todo: move *)\n\nLemma NoDup_filter T (p: T -> bool) (l: list T):\n  NoDup l -> NoDup (filter p l).\nProof with auto.\n  induction l...\n  simpl.\n  intros.\n  inversion_clear H.\n  destruct (p a)...\n  apply NoDup_cons...\n  intro.\n  apply H0...\n  apply (incl_filter p l)...\nQed.\n\nLemma length_excl_counts X (p: X -> bool) (l: list X):\n  length l = count p l + count (negb ∘ p) l.\nProof with auto.\n  unfold compose.\n  induction l...\n  intros.\n  simpl.\n  rewrite IHl.\n  destruct (p a); simpl...\nQed.\n\nLemma count_filtered X (p q: X -> bool):\n  (forall x, q x = true -> p x = false) ->\n  forall l, count p (filter q l) = 0.\nProof with auto.\n  induction l...\n  simpl.\n  cset (H a).\n  destruct (q a)...\n  simpl.\n  rewrite H0...\nQed.\n\nLemma app_nil_r T (l: list T): l ++ nil = l.\nProof with auto. induction l... simpl. rewrite IHl... Qed.\n\nHint Resolve Permutation_map.\n\nLemma map_cons T U (f: T -> U) (h: T) (l: list T): map f (h :: l) = f h :: map f l.\nProof. auto. Qed.\n\n(* concat *)\n\nDefinition concat {T}: list (list T) -> list T := fold_right (@app _) nil.\n\nLemma concat_app T (x y: list (list T)): concat (x ++ y) = concat x ++ concat y.\nProof with auto.\n  induction x...\n  simpl.\n  intros.\n  rewrite IHx.\n  rewrite app_ass...\nQed.\n\nLemma In_concat X (l: list (list X)) (s: list X) (x: X): In x s -> In s l -> In x (concat l).\nProof with auto.\n  induction l...\n  intros.\n  simpl.\n  apply in_or_app.\n  inversion_clear H0.\n    subst...\n  right...\nQed.\n\nLemma In_concat_inv X (x: X) (l: list (list X)):\n  In x (concat l) -> exists s, In x s /\\ In s l.\nProof with auto.\n  induction l.\n    intros.\n    elimtype False...\n  simpl.\n  intros.\n  destruct (in_app_or _ _ _ H).\n    exists a.\n    split...\n  destruct (IHl H0).\n  destruct H1.\n  exists x0...\nQed.\n\nDefinition eq_count X (d: forall (x y: X), { x = y } + { x <> y }) (x: X): list X -> nat :=\n count (fun y => unsum_bool (d x y)).\n\nLemma eq_count_0 X (d: forall (x y: X), { x = y } + { x <> y }) (x: X) l:\n  ~ In x l -> eq_count d x l = 0%nat.\nProof with auto.\n  induction l...\n  simpl.\n  intros.\n  destruct (d x a).\n    elimtype False.\n    apply H.\n    left...\n  simpl.\n  apply IHl.\n  intro.\n  apply H.\n  right...\nQed.\n\nLemma eq_count_NoDup X (d: forall (x y: X), { x = y } + { x <> y }) (x: X) l:\n  NoDup l -> eq_count d x l <= 1.\nProof with auto.\n  induction l...\n  simpl.\n  intros.\n  inversion_clear H...\n  destruct (d x a); simpl...\n  subst.\n  rewrite eq_count_0...\nQed.\n\nLemma NoDup_incl_Permutation A (a b: list A):\n  length a = length b -> NoDup a -> incl a b -> Permutation a b.\nProof with auto. (* todo: prove in terms of the vec equivalent *)\n  induction a in b |- *; intros.\n    destruct b.\n      apply perm_nil.\n    discriminate.\n  assert (In a b).\n    apply H1.\n    left...\n  destruct (In_inv_perm a b H2).\n  apply perm_trans with (a :: x)...\n  apply perm_skip.\n  apply IHa.\n      cset (Permutation_length H3).\n      rewrite <- H in H4.\n      inversion_clear H4...\n    inversion_clear H0...\n  cut (incl a0 (a :: x)).\n    intros.\n    intro.\n    intros.\n    cset (H4 a1 H5).\n    inversion_clear H6...\n    subst.\n    inversion_clear H0.\n    elimtype False...\n  apply incl_tran with b...\n    intro.\n    intros.\n    apply H1.\n    right...\n  apply Permutation_incl.\n  apply Permutation_sym...\nQed.\n\nLemma NoDup_map' A B (f: A -> B) (l: list A):\n  (forall x y: A, In x l -> In y l -> x <> y -> f x <> f y) ->\n  NoDup l -> NoDup (map f l).\nProof with auto.\n  induction l; simpl...\n  intros.\n  inversion_clear H0.\n  apply NoDup_cons...\n  intro.\n  destruct (In_map_inv H0).\n  destruct H3.\n  apply (H x a)...\n  intro.\n  subst...\nQed. (* todo: replace NoDup_map *)\n\nLemma NoDup_map A B (f: A -> B) l:\n  (forall x y, In x l -> In y l -> f x = f y -> x = y) -> NoDup l -> NoDup (map f l).\nProof with simpl; auto.\n  induction l...\n  intros.\n  simpl.\n  inversion_clear H0.\n  apply NoDup_cons...\n  intro.\n  apply H1.\n  destruct (In_map_inv H0).\n  destruct H3.\n  rewrite (H a x)...\nQed.\n\nInductive InP (X: Type) (P: X -> Prop): list X -> Prop :=\n  | InP_head x t: P x -> InP P (x :: t)\n  | InP_tail x t: InP P t -> InP P (x :: t).\n\nInductive NoDupL (A: Type): list (list A) -> Prop :=\n  | NoDupL_nil: NoDupL nil\n  | NoDupL_cons (l: list A) (ll: list (list A)): NoDup l ->\n      (forall x, In x l -> ~ InP (In x) ll) -> NoDupL ll -> NoDupL (l :: ll).\n\nHint Constructors NoDupL.\n\nLemma InP_In (X: Type) (l: list X) (ll: list (list X)): In l ll -> forall x, In x l -> InP (In x) ll.\nProof with auto.\n  induction ll.\n    intros.\n    inversion H.\n  intros.\n  inversion_clear H; [left | right]...\n  subst...\nQed.\n\nLemma InP_In_inv X (x: X) (ll: list (list X)):\n  InP (In x) ll -> exists l, In x l /\\ In l ll.\nProof with auto.\n  intros H.\n  induction H.\n    exists x0.\n    split...\n    left...\n  destruct IHInP.\n  destruct H0.\n  exists x1.\n  split...\n  right...\nQed.\n\nArguments InP_In_inv [X x ll].\n\nLemma NoDup_concat A (l: list (list A)): NoDupL l -> NoDup (concat l).\nProof with auto.\n  induction l; simpl; intros.\n    apply NoDup_nil.\n  inversion_clear H.\n  induction a...\n  inversion_clear H0.\n  simpl.\n  apply NoDup_cons...\n    intro.\n    destruct (in_app_or _ _ _ H0)...\n    apply (H1 a).\n      left...\n    destruct (In_concat_inv _ _ H4).\n    destruct H5.\n    apply InP_In with x...\n  apply IHa...\n  intros.\n  apply H1.\n  right...\nQed.\n\nLemma In_filter_inv A (f: A -> bool) (x: A) (l: list A): In x (filter f l) -> In x l /\\ f x = true.\nProof. intros. destruct (filter_In f x l). apply H0. assumption. Qed.\n\n(* Partitioning *)\n\nSection Partitioning.\n\n  Variable T: Set.\n\n  Definition Partitioning: Set := comparison -> list T.\n\n  Lemma partition_oblig c l h\n    (H: {p: Partitioning | Permutation (p Eq ++ p Lt ++ p Gt) l}):\n    Permutation\n      ((if cmp_cmp c Eq then h :: proj1_sig H Eq else proj1_sig H Eq) ++\n      (if cmp_cmp c Lt then h :: proj1_sig H Lt else proj1_sig H Lt) ++\n      (if cmp_cmp c Gt then h :: proj1_sig H Gt else proj1_sig H Gt))\n      (h :: l).\n  Proof with auto.\n    intros.\n    destruct H. simpl.\n    apply Permutation_sym.\n    cset (Permutation_sym p).\n    destruct c; simpl.\n        apply perm_skip...\n      apply Permutation_cons_app...\n    rewrite <- app_ass in *.\n    apply Permutation_cons_app...\n  Qed.\n\n  Definition addToPartitioning (c: comparison) (l: list T) (h: T) (H: {p: Partitioning | Permutation (p Eq ++ p Lt ++ p Gt) l}): {p: Partitioning | Permutation (p Eq ++ p Lt ++ p Gt) (h :: l)} :=\n    exist (fun p => Permutation (p Eq ++ p Lt ++ p Gt) (h :: l))\n      (fun c' => if cmp_cmp c c' then h :: proj1_sig H c' else proj1_sig H c')\n      (partition_oblig c h H).\n\n  Definition emp: {p: Partitioning | Permutation (p Eq ++ p Lt ++ p Gt) nil} :=\n    exist (fun p => Permutation (p Eq ++ p Lt ++ p Gt) nil) (fun _ => nil) (perm_nil T).\n\nEnd Partitioning.\n\nFixpoint repeat T (n: nat) (x: T): list T :=\n  match n with\n  | 0 => nil\n  | S n' => x :: repeat n' x\n  end.\n\nLemma map_concat T U (l: list (list T)) (f: T -> U): map f (concat l) = concat (map (map f) l).\nProof with auto.\n  induction l...\n  intros.\n  simpl.\n  rewrite map_app.\n  congruence.\nQed.\n\nLemma length_0_nil A (l: list A): length l = 0%nat <-> l = nil.\nProof with auto.\n  intuition.\n    destruct l...\n    discriminate.\n  subst...\nQed.\n\nLemma length_ne_0_ne_nil A (l: list A): length l <> 0%nat -> l <> nil.\nProof. destruct l. auto. intros. discriminate. Qed.\n\nInductive elemsR A B (R: A -> B -> Prop): list A -> list B -> Prop :=\n  | eR_nil: elemsR R nil nil\n  | eR_cons (a: A) (b: B): R a b -> forall l l', elemsR R l l' -> elemsR R (a :: l) (b :: l').\n\nHint Constructors elemsR.\n\nInstance elemsR_trans A `{R: relation A} {TR: Transitive R}: Transitive (elemsR R).\nProof with auto.\n  intro.\n  induction x.\n    intros.\n    destruct y...\n    inversion H.\n  intros.\n  destruct y.\n    inversion H.\n  destruct z.\n    inversion H0.\n  inversion_clear H.\n  inversion_clear H0.\n  apply eR_cons...\n    transitivity a0...\n  apply IHx with y...\nQed.\n\nLemma elemsR_le_S a b: elemsR le a b -> elemsR le (map S a) (map S b).\nProof. intros. induction H; simpl; auto with arith. Qed.\n\nLemma elemsR_map A (R: relation A) f l:\n  (forall x, In x l -> R (f x) x) -> elemsR R (map f l) l.\nProof. induction l; simpl; intuition. Qed.\n\nLemma elemsR_map_map (X Y: Type) (f g: Y -> X) (l: list Y) (R: relation X): (forall x, In x l -> R (f x) (g x)) -> elemsR R (map f l) (map g l).\nProof with auto.\n  induction l. simpl...\n  intros.\n  apply eR_cons; intuition.\nQed.\n\nLemma elemsR_impl A (R R' : relation A): (forall x y: A, R x y -> R' x y) -> forall l l', elemsR R l l' -> elemsR R' l l'.\nProof. induction l; intros; inversion_clear H0; auto. Qed.\n\nSection Permuted.\n\n  Context {A: Type} (R: relation A).\n\n  Inductive Permuted: relation (list A) :=\n    | permuted_nil : Permuted nil nil\n    | permuted_skip : forall (x x': A), R x x' -> forall (l l' : list A), Permuted l l' -> Permuted (x :: l) (x' :: l')\n    | permuted_swap : forall (x y: A) (l: list A), Permuted (y :: x :: l) (x :: y :: l)\n    | permuted_trans : forall l l' l'' : list A, Permuted l l' -> Permuted l' l'' -> Permuted l l''.\n\n  Hint Constructors Permuted.\n\n  Context {Rrefl: Reflexive R}.\n\n  Lemma permuted_refl l: Permuted l l.\n  Proof. induction l; auto. Qed.\n\n  Hint Immediate permuted_refl.\n\n  Lemma elemsR_permuted l l': elemsR R l l' -> Permuted l l'.\n  Proof. induction l in l' |- *; intros; inversion_clear H; auto. Qed.\n\n  (* the following looks like a more powerful type for the swap ctor, but it isn't, because we can implement it with the others: *)\n\n  Lemma alt_permuted_swap (x x' y y': A): R x x' -> R y y' ->\n    forall (l l': list A), elemsR R l l' -> Permuted (y :: x :: l) (x' :: y' :: l').\n  Proof with auto.\n    intros.\n    apply permuted_trans with (y' :: x' :: l)...\n    apply permuted_trans with (y' :: x' :: l')...\n    apply permuted_skip...\n    apply permuted_skip...\n    apply elemsR_permuted...\n  Qed.\n\nEnd Permuted.\n\nHint Constructors Permuted.\n\nLemma map_map_comp A B C (f: A -> B) (g: B -> C) (l: list A):\n  map g (map f l) = map (g ∘ f) l.\nProof.\n  intros.\n  rewrite map_map.\n  reflexivity.\nQed.\n\nLemma concat_map_singleton A (l: list A): concat (map (fun x => x :: nil) l) = l.\nProof.\n  induction l. intuition.\n  simpl. congruence.\nQed.\n\nLemma Permuted_sub A (R: relation A) x y: Permuted R x y -> forall (R': relation A), (forall x y, R x y -> R' x y) -> Permuted R' x y.\nProof with auto.\n  intros.\n  induction H...\n  apply permuted_trans with l'...\nQed.\n\n(*\nLemma Permuted_map_old (A B: Type) (R: relation B) (f: A -> B) x y:\n  Permuted (on f R) x y -> Permuted R (map f x) (map f y).\nProof with auto.\n  intros.\n  induction H.\n        simpl...\n      apply permuted_skip...\n    simpl.\n    apply permuted_swap...\n  apply permuted_trans with (map f l')...\nQed.\n*)\n\nLemma Permuted_map A B (R: relation B) (f: A -> B): Proper (Permuted (on f R) ==> Permuted R) (map f).\nProof. repeat intro. induction H; simpl; eauto. Qed.\n\nDefinition add := fold_right plus (0%nat).\n\nLemma add_same c l: (forall x, In x l -> x = c) -> add l = length l * c.\nProof with auto.\n  induction l...\n  intros.\n  simpl.\n  intuition.\nQed.\n\nLemma length_concat T (l: list (list T)):\n  length (concat l) = add (map (@length _) l).\nProof with auto.\n  induction l...\n  simpl.\n  rewrite app_length, IHl...\nQed.\n\nLemma concat_map_nil T U (l: list T): concat (map (fun _ => nil) l) = @nil U.\nProof. induction l; auto. Qed.\n\nDefinition product A B (aa: list A) (bb: list B): list (A * B) :=\n  concat (map (fun a => map (pair a) bb) aa).\n\nInstance Permutation_concat T: Proper (Permutation ==> Permutation) (@concat T).\nProof with auto.\n  repeat intro.\n  induction H...\n      simpl.\n      apply Permutation_app...\n    simpl.\n    repeat rewrite <- app_ass.\n    apply Permutation_app...\n    apply Permutation_app_swap.\n  eauto.\nQed.\n\nLemma concat_map_singleton_f T A (f: A -> T) l: concat (map (fun x : A => (f x)::nil) l) = map f l.\nProof with auto.\n  induction l...\n  simpl.\n  congruence.\nQed.\n\nLemma map_concat_map T U V (g: T -> list U) (f: U -> V) l:\n  map f (concat (map g l)) = concat (map (map f ∘ g) l).\nProof with auto.\n  unfold Basics.compose.\n  induction l...\n  simpl.\n  rewrite map_app.\n  congruence.\nQed.\n\nLemma concat_concat T (x: list (list (list T))):\n  concat (concat x) = concat (map concat x).\nProof with auto.\n  induction x...\n  simpl.\n  rewrite concat_app.\n  congruence.\nQed.\n\nSection two_lists_rect.\n\n  Variables (T: Type) (P: list T -> list T -> Type)\n    (Pnil_l: forall x, P nil x) (Pnil_r: forall x, P x nil)\n    (Pcons: forall x x' y y', P x' (y :: y') -> P (x :: x') y' -> P (x :: x') (y :: y')).\n\n  Let R: relation (list T * list T) := pair_rel (ltof (list T) (@length _)) (ltof (list T) (@length _)).\n\n  Let wf_R: well_founded R.\n  Proof. apply well_founded_pairs; apply well_founded_ltof. Qed.\n\n  Lemma two_lists_rect_pre (p: list T * list T): P (fst p) (snd p).\n  Proof with auto.\n    apply (well_founded_induction_type wf_R (fun p => P (fst p) (snd p))).\n    unfold R, ltof.\n    destruct x as [[|A] [|B]]...\n    intros.\n    simpl.\n    apply Pcons.\n      apply (X (l, B :: l0)).\n      apply pair_rel_l...\n    apply (X (A :: l, l0)).\n    apply pair_rel_r...\n  Defined.\n\n  Definition two_lists_rect x y: P x y := two_lists_rect_pre (x, y).\n\nEnd two_lists_rect.\n\nInstance Reflexive_Permutation T: Reflexive Permutation := @Permutation_refl T.\nInstance Reflexive_Symmetric T: Symmetric Permutation := @Permutation_sym T.\nInstance Reflexive_Transitive T: Transitive Permutation := @perm_trans T.\n\nInstance app_Permutation_mor T: Proper (Permutation ==> Permutation ==> Permutation) (@app T).\nProof. repeat intro. apply Permutation_app; assumption. Qed.\n\nInstance map_Permutation_mor T U (f: T -> U): Proper (Permutation ==> Permutation) (map f) :=\n  Permutation_map f.\n\n(*\nLemma concatMap_concatMap T U V (g: T -> list U) (f: U -> list V) l:\n  concat (map f (concat (map g l))) = concat (concat (map (map f ∘ g) l)).\nProof with auto.\n  intros.\n  rewrite map_concat_map...\n\n  intros.\n  rewrite <- map_map_comp.\n  rewrite <- map_concat...\nQed.\n*)\n\nLemma concatMap_concatMap' T U V (g: T -> list U) (f: U -> list V) l:\n  concat (map f (concat (map g l))) = concat (map (concat ∘ map f ∘ g) l).\nProof with auto.\n  induction l...\n  simpl.\n  rewrite <- IHl.\n  unfold Basics.compose.\n  rewrite map_app.\n  rewrite concat_app...\nQed.\n\nLemma Permutation_concatMap T U (f g: T -> list U) l:\n  (forall x, In x l -> Permutation (f x) (g x)) ->\n  Permutation (concat (map f l)) (concat (map g l)).\nProof with auto.\n  induction l...\n  simpl.\n  intros.\n  rewrite IHl...\n  rewrite H...\nQed.\n\nHint Resolve Permutation_concat.\n\nLemma Permutation_concat_map_app T A (f g: A -> list T) l:\n  Permutation (concat (map (fun x => f x ++ g x) l)) (concat (map f l ++ map g l)).\nProof with auto.\n  induction l...\n  simpl.\n  rewrite IHl.\n  repeat rewrite concat_app.\n  simpl.\n  rewrite app_ass.\n  apply Permutation_app...\n  rewrite Permutation_app_swap.\n  rewrite app_ass.\n  apply Permutation_app...\n  apply Permutation_app_swap.\nQed.\n\nLemma concat_product T U V (f: U -> T -> list V) l l':\n  Permutation\n    (concat (map (fun x => concat (map (fun y => f y x) l')) l))\n    (concat (map (fun x => concat (map (f x) l)) l')).\nProof with auto.\n  induction l...\n    intros.\n    simpl.\n    rewrite concat_map_nil...\n  intros.\n  simpl.\n  rewrite IHl.\n  apply Permutation_sym.\n  rewrite Permutation_concat_map_app.\n  rewrite concat_app...\nQed.\n\nInstance map_eq_morphism A B: Proper (pointwise_relation _ eq ==> eq ==> eq) (@map A B).\nProof with auto.\n  repeat intro.\n  subst.\n  induction y0...\n  simpl.\n  congruence.\nQed.\n\nSection splits_and_perms.\n\n  Context {T: Type}.\n\n  Fixpoint splits (l: list T): list (T * list T) :=\n    match l with\n    | nil => nil\n    | h :: t => (h, t) :: map (fun xy => (fst xy, h :: snd xy)) (splits t)\n    end.\n\n  Lemma length_splits l: length (splits l) = length l.\n  Proof with auto.\n    induction l...\n    simpl.\n    rewrite map_length.\n    intuition.\n  Qed.\n\n  Lemma splits_are_perms l p: In p (splits l) -> Permutation (fst p :: snd p) l.\n  Proof with auto.\n    induction l in p |- *...\n      simpl.\n      intuition.\n    simpl.\n    intros.\n    destruct H.\n      subst...\n    destruct (fst (conj_prod (in_map_iff _ _ _)) H).\n    destruct H0.\n    apply IHl in H1.\n    subst.\n    simpl...\n    apply perm_trans with (a :: fst x :: snd x).\n      apply perm_swap.\n    apply perm_skip...\n  Qed.\n\n  Lemma length_in_splits l p: In p (splits l) -> S (length (snd p)) = length l.\n  Proof.\n    intros.\n    apply splits_are_perms in H.\n    exact (Permutation_length H).\n  Qed.\n\n  Fixpoint insert_everywhere (x: T) (l: list T): list (list T) :=\n    match l with\n    | nil => (x :: nil) :: nil\n    | h :: t => (x :: h :: t) :: map (cons h) (insert_everywhere x t)\n    end.\n\n  Lemma insert_everywhere_are_perms x l:\n    forall y, In y (insert_everywhere x l) -> Permutation y (x :: l).\n  Proof with auto.\n    induction l...\n      intros.\n      simpl in H.\n      intuition.\n      subst...\n    intros.\n    simpl in H.\n    destruct H.\n      subst...\n    apply in_map_iff in H. destruct H as [x0 [A B]].\n    subst.\n    apply IHl in B.\n    eauto.\n  Qed.\n\n  Lemma length_insert_everywhere x l:\n    length (insert_everywhere x l) = S (length l).\n  Proof with auto.\n    induction l...\n    simpl.\n    rewrite map_length.\n    congruence.\n  Qed.\n\n  Definition perms: list T -> list (list T)\n    := fold_right (fun h => concat ∘ map (insert_everywhere h)) (nil :: nil).\n\n  Lemma perms_are_perms l a: In a (perms l) -> Permutation a l.\n  Proof with auto.\n    induction l in a |- *.\n      simpl.\n      intuition.\n      subst...\n    intros.\n    simpl in H.\n    unfold Basics.compose in H.\n    apply In_concat_inv in H. destruct H. destruct H.\n    apply in_map_iff in H0. destruct H0 as [x0 [A B]].\n    subst.\n    eauto using insert_everywhere_are_perms.\n  Qed.\n\n  Lemma length_perms l: length (perms l) = fact (length l).\n  Proof with auto.\n    induction l...\n    simpl.\n    unfold Basics.compose.\n    rewrite length_concat.\n    rewrite map_map.\n    rewrite (@add_same (S (length l)) (map (fun x => length (insert_everywhere a x)) (perms l))).\n      rewrite map_length.\n      rewrite IHl.\n      rewrite Mult.mult_comm...\n    intros.\n    destruct (in_map_iff (fun x => length (insert_everywhere a x)) (perms l) x).\n    clear H1.\n    apply H0 in H. clear H0.\n    destruct H. destruct H.\n    subst.\n    rewrite length_insert_everywhere.\n    f_equal.\n    apply Permutation_length.\n    apply perms_are_perms...\n  Qed.\n\n  Definition alt_perms l: list (list T) :=\n    match l with\n    | nil => nil :: nil\n    | _ => concat (map (fun p => (map (cons (fst p)) (perms (snd p)))) (splits l))\n    end.\n\n  Lemma splits_permuted (l l': list T): Permutation l l' ->\n    Permuted (fun x y => fst x = fst y /\\ Permutation (snd x) (snd y)) (splits l) (splits l').\n  Proof with auto.\n    intro.\n    set (fun x y: T * list T => fst x = fst y /\\ Permutation (snd x) (snd y)).\n    intros.\n    induction H.\n          simpl...\n        simpl.\n        apply permuted_skip...\n          split...\n        apply Permuted_map.\n        unfold on.\n        subst P.\n        simpl.\n        apply (Permuted_sub IHPermutation).\n        intuition.\n      simpl.\n      subst P.\n      apply alt_permuted_swap...\n      repeat rewrite map_map.\n      simpl.\n      apply elemsR_map_map.\n      simpl...\n    eauto.\n  Qed.\n\n  Inductive merges_spec: list T -> list T -> list (list T) -> Prop :=\n    | merges_left_nil x: merges_spec nil x (x :: nil)\n    | merges_right_nil x: merges_spec x nil (x :: nil)\n    | merges_cons x y h t r r':\n      merges_spec y (h :: t) r ->\n      merges_spec (x :: y) t r' ->\n      merges_spec (x :: y) (h :: t) (map (cons x) r ++ map (cons h) r').\n\n  Hint Constructors merges_spec.\n\n  Lemma merges_uniq a b r:\n    merges_spec a b r ->\n    forall r', merges_spec a b r' -> r = r'.\n  Proof with auto.\n    intros H.\n    induction H; intros.\n        inversion_clear H...\n      inversion_clear H...\n    inversion_clear H1.\n    apply IHmerges_spec1 in H2.\n    apply IHmerges_spec2 in H3.\n    congruence.\n  Qed.\n\n  Lemma length_merges (F: nat -> nat -> nat) a b r:\n    (forall n, F 0 n = 1) ->\n    (forall n, F n 0 = 1) ->\n    (forall n n', F n (S n') + F (S n) n' = F (S n) (S n')) ->\n    merges_spec a b r -> length r = F (length a) (length b).\n  Proof with auto.\n    intros.\n    induction H2.\n        simpl...\n      simpl...\n    rewrite app_length.\n    repeat rewrite map_length.\n    rewrite IHmerges_spec1. clear IHmerges_spec1.\n    rewrite IHmerges_spec2. clear IHmerges_spec2.\n    simpl @length...\n  Qed.\n\n  Definition me (ab: list T * list T): nat := length (fst ab) + length (snd ab).\n\n  Program Fixpoint merges_ex (ab: list T * list T) {measure (me ab)}: sig (merges_spec (fst ab) (snd ab)) :=\n    match ab with\n    | (nil, x) => x :: nil\n    | (x, nil) => x :: nil\n    | (x :: y, h :: t) => map (cons x) (merges_ex (y, h :: t)) ++ map (cons h) (merges_ex (x :: y, t))\n    end.\n\n  Next Obligation. unfold me. simpl. omega. Qed.\n  Next Obligation. repeat destruct_call merges_ex; auto. Qed.\n\n  Definition merges (a b: list T): list (list T) := proj1_sig (merges_ex (a, b)).\n\n  Lemma merges_real_eq a b: merges a b =\n    match a, b with\n    | nil, x => x :: nil\n    | x, nil => x :: nil\n    | x :: y, h :: t => map (cons x) (merges y (h :: t)) ++ map (cons h) (merges (x :: y) t)\n    end.\n  Proof with auto.\n    intros.\n    apply (@merges_uniq a b).\n      unfold merges. destruct_call merges_ex...\n    destruct a... destruct b...\n    unfold merges. repeat destruct_call merges_ex...\n  Qed.\n\n  Lemma merges_nil_r a: merges a [] = [a].\n  Proof with auto.\n    intros.\n    rewrite merges_real_eq.\n    destruct a...\n  Qed.\n\n  Hint Resolve Permutation_concat.\n\n  Lemma product_app: forall T (a b c: list T), product (a ++ b) c = product a c ++ product b c.\n  Proof with auto.\n    intros.\n    unfold product.\n    rewrite map_app.\n    rewrite concat_app...\n  Qed.\n\n  Lemma product_concat: forall T (a: list (list T)) (b: list T), product (concat a) b = concat (map (flip (@product _ _) b) a).\n  Proof with auto.\n    induction a...\n    simpl.\n    unfold flip at 1.\n    intros.\n    rewrite <- IHa.\n    apply product_app.\n  Qed. (* todo: this shouldn't need induction anymore *)\n\n  Lemma concatMap_insert_everywhere_comm x y l: Permutation\n    (concat (map (insert_everywhere x) (insert_everywhere y l)))\n    (concat (map (insert_everywhere y) (insert_everywhere x l))).\n  Proof with auto.\n    induction l...\n      simpl...\n    simpl.\n    rewrite perm_swap.\n    apply perm_skip.\n    apply perm_skip.\n    rewrite (map_map (cons a) (insert_everywhere x)).\n    rewrite (map_map (cons a) (insert_everywhere y)).\n    simpl.\n    rewrite (Permutation_concat_map_app (fun x0 => (x :: a :: x0) :: nil) (fun x0 => map (cons a) (insert_everywhere x x0)) (insert_everywhere y l)).\n    apply Permutation_sym.\n    rewrite (Permutation_concat_map_app (fun x0 => (y :: a :: x0) :: nil) (fun x => map (cons a) (insert_everywhere y x)) (insert_everywhere x l)).\n    repeat rewrite concat_app.\n    repeat rewrite concat_map_singleton_f.\n    rewrite <- (map_map (insert_everywhere x) (map (cons a))).\n    rewrite <- (map_map (insert_everywhere y) (map (cons a))).\n    repeat rewrite <- map_concat.\n    repeat rewrite map_map.\n    repeat rewrite <- app_ass.\n    symmetry in IHl...\n    apply Permutation_app...\n    apply Permutation_app_swap.\n  Qed.\n\n  Instance Permutation_perms: Proper (Permutation ==> Permutation) perms.\n  Proof with eauto 2.\n    intros l l' P.\n    induction P...\n      simpl.\n      apply Permutation_concat...\n    simpl.\n    unfold Basics.compose.\n    set (perms l). clearbody l0. clear l. rename l0 into l.\n    repeat rewrite concatMap_concatMap'.\n    apply Permutation_concatMap.\n    intros.\n    unfold Basics.compose.\n    apply concatMap_insert_everywhere_comm.\n  Qed.\n\n  Lemma merges_insert_everywhere a l: insert_everywhere a l = merges (a :: nil) l.\n  Proof with auto.\n    induction l...\n    simpl.\n    rewrite IHl.\n    rewrite (merges_real_eq [a] (a0::l)).\n    rewrite (merges_real_eq [] (a0::l)).\n    simpl...\n  Qed.\n\n  Lemma merges_insert_everywhere' a l: Permutation (insert_everywhere a l) (merges l (a :: nil)).\n  Proof with auto.\n    induction l...\n    simpl.\n    transitivity ((a :: a0 :: l) :: map (cons a0) (merges l [a]))...\n    rewrite (merges_real_eq (a0::l) [a]).\n    rewrite (merges_real_eq (a0::l) []).\n    simpl.\n    transitivity ([a :: a0 :: l] ++ map (cons a0) (merges l [a]))...\n    apply Permutation_app_swap.\n  Qed.\n\n  Lemma insert_everywhere_merges_commute a x y: Permutation\n    (concat (map (insert_everywhere a) (merges y x)))\n    (concat (map (merges y) (insert_everywhere a x))).\n      (* written with list monad notation, this would be:\n        Permutation\n          (insert_everywhere a >>= merges y x)\n          (merges y >>= insert_everywhere a x). *)\n  Proof with auto.\n    revert x y.\n    apply two_lists_rect; intros.\n        simpl.\n        rewrite merges_nil_r.\n        simpl.\n        repeat rewrite app_nil_r.\n        apply merges_insert_everywhere'.\n      simpl.\n      rewrite app_nil_r.\n      rewrite (map_ext (merges []) (fun x0 => [x0])).\n        rewrite concat_map_singleton...\n      intros.\n      apply merges_real_eq.\n    rewrite (merges_real_eq (y :: y') (x :: x')).\n    rewrite map_app.\n    rewrite concat_app.\n    repeat rewrite map_map.\n    simpl insert_everywhere.\n    rewrite (Permutation_concat_map_app (fun x0 => [a :: y :: x0]) (fun x0 => map (cons y) (insert_everywhere a x0))).\n    rewrite (Permutation_concat_map_app (fun x0 => [a :: x :: x0]) (fun x0 => map (cons x) (insert_everywhere a x0))).\n    repeat rewrite concat_app.\n    repeat rewrite concat_map_singleton_f.\n    rewrite app_ass.\n    rewrite <- (map_map (insert_everywhere a) (map (cons x))).\n    rewrite <- (map_map (insert_everywhere a) (map (cons y))).\n    rewrite <- map_concat.\n    rewrite <- map_concat.\n    rewrite H. rewrite H0.\n    clear H H0.\n    simpl @map at 7.\n    simpl @concat at 3.\n    rewrite map_map.\n    rewrite (merges_real_eq (y :: y') (a :: x :: x')).\n    rewrite (merges_real_eq (y :: y') (x :: x')).\n    rewrite map_app.\n    repeat rewrite map_map.\n    rewrite app_ass.\n    apply Permutation_sym.\n    rewrite (Permutation_app_swap (map (cons y) (merges y' (a :: x :: x')))).\n    repeat rewrite app_ass.\n    apply Permutation_app...\n    apply Permutation_sym.\n    rewrite (Permutation_app_swap (map (cons y) (concat (map (merges y') (insert_everywhere a (x :: x')))))).\n    repeat rewrite app_ass.\n    apply Permutation_app...\n    simpl.\n    rewrite map_map.\n    rewrite map_app.\n    rewrite (map_ext (fun x0 : list T => merges (y :: y') (x :: x0)) (fun x0 : list T => map (cons y) (merges y' (x :: x0)) ++ map (cons x) (merges (y :: y') x0))).\n      Focus 2.\n      intros.\n      rewrite merges_real_eq...\n    apply Permutation_sym.\n    rewrite Permutation_concat_map_app.\n    rewrite concat_app.\n    rewrite app_ass.\n    rewrite <- (map_map (fun x0 => merges y' (x :: x0)) (map (cons y))).\n    rewrite <- map_concat.\n    rewrite Permutation_app_swap.\n    rewrite <- app_ass.\n    apply Permutation_app...\n    rewrite <- (map_map (fun x0 => merges (y :: y') x0) (map (cons x))).\n    rewrite <- map_concat.\n    apply Permutation_app...\n  Qed. (* wow, can hardly believe it's true after this ordeal *)\n\n  Lemma merges_sym x y: Permutation (merges x y) (merges y x).\n  Proof with auto.\n    intros.\n    unfold merges at 1.\n    destruct_call merges_ex.\n    simpl in *.\n    induction m...\n      rewrite merges_nil_r...\n    rewrite IHm1.\n    rewrite IHm2.\n    rewrite (merges_real_eq (h :: t) (x :: y)).\n    apply Permutation_app_swap.\n  Qed.\n\n  Hint Immediate merges_sym.\n\n  Lemma perms_app (a b: list T): Permutation (perms (a ++ b)) (concat (map (uncurry merges) (product (perms a) (perms b)))).\n  Proof with auto.\n    unfold product.\n    intros.\n    rewrite map_concat.\n    rewrite map_map.\n    induction a.\n      simpl.\n      rewrite app_nil_r.\n      rewrite map_map.\n      unfold uncurry.\n      simpl.\n      rewrite (map_ext (fun x => merges [] x) (fun x => x :: nil))...\n      rewrite concat_map_singleton...\n    simpl.\n    unfold Basics.compose.\n    rewrite IHa. clear IHa.\n    rewrite (map_ext (fun x : list T => map (uncurry merges) (map (pair x) (perms b)))\n      (fun x : list T => map (merges x) (perms b))).\n      rewrite (map_ext (fun x : list T => map (uncurry merges) (map (pair x) (perms b)))\n        (fun x : list T => map (merges x) (perms b))).\n        rewrite concat_concat.\n        rewrite concat_concat.\n        rewrite map_map.\n        rewrite map_map.\n        rewrite map_concat_map.\n        rewrite concat_concat.\n        rewrite map_map.\n        rewrite map_concat_map.\n        rewrite concat_concat.\n        rewrite map_map.\n        apply Permutation_concatMap.\n        intros.\n        unfold Basics.compose.\n        rewrite map_concat_map.\n        rewrite concat_concat.\n        rewrite map_map.\n        rewrite (map_ext (fun x0 => concat ((map (insert_everywhere a) ∘ merges x) x0))\n          (concat ∘ (map (insert_everywhere a) ∘ merges x)))...\n        transitivity (concat (map (concat ∘ map (merges x) ∘ insert_everywhere a) (perms b))).\n          apply Permutation_concatMap.\n          intros.\n          unfold Basics.compose.\n          apply insert_everywhere_merges_commute.\n        apply Permutation_sym.\n        rewrite <- (concat_product merges (perms b) (insert_everywhere a x)).\n        apply Permutation_concatMap.\n        intros.\n        unfold Basics.compose.\n        apply Permutation_sym.\n        rewrite <- insert_everywhere_merges_commute.\n        transitivity (concat (map (merges x0) (insert_everywhere a x))).\n          apply Permutation_sym.\n          rewrite <- insert_everywhere_merges_commute...\n          rewrite merges_sym...\n        apply Permutation_concatMap.\n        intros...\n      intros.\n      rewrite map_map...\n    intros.\n    rewrite map_map...\n  Qed.\n\n  Lemma filter_merges p (x y: list T):\n     (forall z, In z x -> p z = true) ->\n     (forall z, In z y -> p z = false) ->\n     forall r, In r (map (filter p) (merges x y)) -> r = x.\n  Proof with auto.\n    pattern x, y.\n    apply two_lists_rect.\n        intros.\n        rewrite merges_real_eq in H1.\n        simpl in H1.\n        intuition.\n        subst.\n        apply (filter_none p x0)...\n      intros.\n      rewrite merges_nil_r in H1.\n      simpl in H1.\n      intuition.\n      subst.\n      apply filter_all...\n    intros.\n    rewrite merges_real_eq in H3.\n    rewrite map_app in H3.\n    repeat rewrite map_map in H3.\n    apply in_app_or in H3.\n    simpl in H3.\n    destruct H3.\n      rewrite H1 in H3.\n        Focus 2. left...\n      rewrite <- (map_map (filter p) (cons x0)) in H3.\n      apply in_map_iff in H3.\n      destruct H3.\n      destruct H3.\n      subst.\n      f_equal.\n      apply H...\n      intuition.\n    rewrite H2 in H3.\n      Focus 2. left...\n    apply H0...\n    intuition.\n  Qed.\n\n  (* While a closed formula for merges length is tricky, we can easily prove that the length depends only on the\n  length of the arguments. *)\n\n  Instance length_merges_mor: Proper (on length eq ==> on length eq ==> on length eq) merges.\n  Proof with auto.\n    unfold on.\n    do 4 intro.\n    generalize y H. clear y H.\n    unfold merges at 1.\n    destruct merges_ex.\n    simpl in *.\n    induction m; intros.\n        destruct y...\n        discriminate.\n      destruct y0.\n        rewrite merges_nil_r...\n      discriminate.\n    destruct y0. discriminate.\n    destruct y1. discriminate.\n    inversion H.\n    inversion H0.\n    rewrite merges_real_eq.\n    repeat rewrite app_length.\n    repeat rewrite map_length...\n  Qed.\n\n  Lemma merges_ne_nil x y: merges x y <> nil.\n  Proof with try discriminate; auto.\n    intros.\n    unfold merges.\n    destruct merges_ex.\n    simpl in *.\n    induction m...\n    destruct r...\n  Qed.\n\nEnd splits_and_perms.\n\nExisting Instance Permutation_perms.\n\nLemma map_repeat A B (f: A -> B) c (l: list A):\n  (forall x, In x l -> f x = c) -> map f l = repeat (length l) c.\nProof with auto.\n  induction l...\n  simpl.\n  intros.\n  rewrite IHl...\n  rewrite H...\nQed.\n\nLemma repeat_plus T (c: T) n m: repeat (n + m) c = repeat n c ++ repeat m c.\nProof. induction n. auto. simpl. congruence. Qed.\n\nLemma concat_repeat T n m (c: T): concat (repeat n (repeat m c)) = repeat (n * m) c.\nProof with auto.\n  induction n. auto.\n  simpl. intros. rewrite IHn, repeat_plus...\nQed.\n\nLemma filter_perms T p (l: list T):\n  Permutation\n    (map (filter p) (perms l))\n    (concat (map (repeat (fact (length (filter (negb ∘ p) l)) * length (merges (filter p l) (filter (negb ∘ p) l)))) (perms (filter p l)))).\n  (* this horrible first argument to repeat is inconsequential. what matters is that we express\n        perms (filter p l)\n    in terms of\n        map (filter p) (perms l)\n  *)\nProof with auto.\n  intros.\n  rewrite (complementary_filter_perm p l) at 1.\n  rewrite perms_app.\n  rewrite map_concat_map.\n  unfold product.\n  rewrite concatMap_concatMap'.\n  apply Permutation_concatMap.\n  intros.\n  unfold Basics.compose.\n  rewrite map_map.\n  unfold uncurry.\n  simpl.\n  set (t := repeat (length (merges x (filter (fun q => negb (p q)) l))) x).\n  rewrite (@map_repeat _ _ (fun x0 : list T => map (filter p) (merges x x0)) t (perms (filter (fun x0 : T => negb (p x0)) l))).\n    rewrite length_perms.\n    subst t.\n    rewrite concat_repeat.\n    pose proof (Permutation_length (perms_are_perms _ _ H)).\n    rewrite (length_merges_mor H0 refl_equal)...\n  intros.\n  rewrite (@map_repeat _ _ (filter p) x (merges x x0)).\n    subst t.\n    pose proof (Permutation_length (perms_are_perms _ _ H0)).\n    rewrite (length_merges_mor refl_equal H1)...\n  intros.\n  apply (filter_merges) with p x0...\n    intros.\n    apply (filter_In p z l)...\n    apply Permutation_in with x...\n    apply perms_are_perms...\n  intros.\n  pose proof (Permutation_in _ (perms_are_perms _ _ H0) H2).\n  cut (negb (p z) = true).\n    intros.\n    destruct (p z)...\n  apply (filter_In (fun q => negb (p q)) z l)...\nQed.\n\nInstance Permutation_length_morphism T: Proper (Permutation ==> eq) (@length T) :=\n  @Permutation_length T.\n\nLemma repeat_map_comm A B (f: A -> B) n: ext_eq (map f ∘ repeat n) (repeat n ∘ f).\nProof with auto.\n  unfold ext_eq.\n  unfold Basics.compose.\n  induction n...\n  simpl in *.\n  congruence.\nQed.\n\nLemma length_repeat T (c: T) n: length (repeat n c) = n.\nProof with auto.\n  induction n...\n  simpl.\n  congruence.\nQed.\n\nHint Immediate length_repeat.\n\nInstance map_ext_eq_mor A B: Proper (@ext_eq A B ==> ext_eq) map.\n  repeat intro.\n  apply map_ext.\n  assumption.\nQed.\n\nLemma concat_nil X (l: list (list X)): (forall x, In x l -> x = nil) -> concat l = nil.\nProof with intuition.\n  induction l...\n  simpl.\n  rewrite IHl...\n  rewrite (H a)...\nQed.\n\nLemma empty_nil X (x: list X): length x = 0%nat -> x = nil.\n  destruct x.\n    reflexivity.\n  intro.\n  discriminate.\nQed.\n\nLemma Permuted_Permutation_map T U (R: relation T) (f: T -> U):\n  (forall x y, R x y -> f x = f y) -> forall a b,\n  Permuted R a b ->\n  Permutation (map f a) (map f b).\nProof with auto.\n  intros.\n  induction H0...\n    simpl.\n    rewrite (H x x')...\n  eauto.\nQed.\n\nLemma elemsR_length A (R: A -> A -> Prop) a b (H: elemsR R a b):\n  length a = length b.\nProof with auto.\n  induction H...\n  simpl.\n  intuition.\nQed.\n\nLemma elemsRimpl A B (R: A -> B -> Prop) (l: list A): (forall x, In x l -> sig (R x)) -> sig (elemsR R l).\nProof with intuition; eauto.\n  induction l...\n  intros.\n  destruct IHl...\n  destruct (X a)...\nQed.\n\nLemma elemsRuniq A B (R: A -> B -> Prop) (l: list A):\n  (forall x, In x l -> forall y, R x y -> forall y', R x y' -> y = y') -> forall r, elemsR R l r -> forall r', elemsR R l r' -> r = r'.\nProof with intuition; auto.\n  induction l.\n    intros.\n    inversion_clear H0. inversion_clear H1...\n  intros.\n  inversion_clear H0.\n  inversion_clear H1.\n  rewrite (H a) with b b0...\n  rewrite IHl with l' l'0...\n  apply H with x...\nQed.\n\nDefinition triple0 A B C (t: A * B * C): A := fst (fst t).\nDefinition triple1 A B C (t: A * B * C): B := snd (fst t).\nDefinition triple2 A B C (t: A * B * C): C := snd t.\n\nFixpoint rsplits T (l: list T): list (list T * T * list T) :=\n  match l with\n  | nil => nil\n  | h :: t => (nil, h, t) :: map (fun p => (h :: triple0 p, triple1 p, triple2 p)) (rsplits t)\n  end.\n\nLemma splits_rsplits (T: Set) (l: list T): splits l = map (fun p => (triple1 p, triple0 p ++ triple2 p)) (rsplits l).\nProof with auto.\n  induction l...\n  simpl.\n  rewrite map_map.\n  simpl.\n  rewrite IHl. clear IHl.\n  unfold triple1.\n  simpl.\n  rewrite map_map.\n  simpl...\nQed.\n\nLemma insert_everywhere_rsplits (T: Set) (x: T) (l: list T):\n  insert_everywhere x l =\n   map (fun x0 => triple0 x0 ++ x :: triple1 x0 :: triple2 x0) (rsplits l) ++ [l ++ [x]].\nProof with auto.\n  induction l...\n  simpl.\n  rewrite IHl. clear IHl.\n  unfold triple0, triple1, triple2.\n  repeat rewrite map_map.\n  rewrite map_app.\n  rewrite map_map...\nQed.\n\nLemma elemsR_map':\n  forall (A B: Type) (Ra: relation A) (Rb: relation B) (f : A -> B)\n    (fR: forall x y, Ra x y -> Rb (f x) (f y)) (l l': list A),\n      elemsR Ra l l' -> elemsR Rb (map f l) (map f l').\nProof. intros. induction H; simpl; auto... Qed.\n\nInstance Permutation_cons_morphism A: Proper (eq ==> Permutation ==> Permutation) (@cons A).\nProof with auto.\n  repeat intro.\n  subst...\nQed.\n\nLemma concatMap_insert_everywhere T (x: T) (l: list (list T)):\n  Permutation\n    (concat (map (insert_everywhere x) l))\n    (map (cons x) l ++ concat (map (tail ∘ insert_everywhere x) l)).\nProof with auto.\n  induction l...\n  simpl @concat.\n  rewrite IHl.\n  apply Permutation_sym.\n  rewrite Permutation_app_swap.\n  unfold compose.\n  simpl.\n  rewrite app_ass.\n  generalize (concat (map (fun x0 : list T => tail (insert_everywhere x x0)) l)). intro.\n  rewrite (Permutation_app_swap l0).\n  rewrite <- app_ass.\n  rewrite <- app_ass.\n  apply Permutation_app...\n  destruct a...\n  simpl.\n  rewrite Permutation_app_swap.\n  simpl.\n  apply perm_skip.\n  apply Permutation_app_swap.\nQed.\n\nLemma map_length_filter_permuted_splits T (l l': list T): Permutation l l' ->\n  forall p,\n  Permutation\n    (map (fun x => length (filter (p (fst x)) (snd x))) (splits l))\n    (map (fun x => length (filter (p (fst x)) (snd x))) (splits l')).\nProof with auto.\n  intros.\n  apply (@Permuted_Permutation_map (T * list T) nat (fun x y => fst x = fst y /\\ Permutation (snd x) (snd y))  (fun x => length (filter (p (fst x)) (snd x)))).\n    intros.\n    destruct H0.\n    destruct x. destruct y.\n    simpl in H0. subst.\n    simpl.\n    simpl in H1.\n    rewrite H1...\n  apply splits_permuted...\nQed.\n\nLemma perms_alt_perms T (l: list T): Permutation (perms l) (alt_perms l).\nProof with auto.\n  unfold alt_perms.\n  induction l...\n  simpl.\n  unfold Basics.compose.\n  rewrite concatMap_insert_everywhere.\n  apply Permutation_app...\n  rewrite IHl. clear IHl.\n  destruct l...\n  rewrite map_concat.\n  rewrite map_map.\n  generalize (splits (t :: l)). intro.\n  setoid_rewrite map_map.\n  unfold compose.\n  rewrite concat_concat.\n  rewrite map_map.\n  simpl @fst. simpl @snd.\n  simpl.\n  unfold compose.\n  setoid_rewrite map_concat.\n  setoid_rewrite map_map...\nQed.\n\nLemma map_single A B (f: A -> B) x: map f [x] = [f x].\nProof. reflexivity. Qed.\n", "meta": {"author": "coq-contribs", "repo": "quicksort-complexity", "sha": "bf0205e5fcfec6d6c6017da071960594de79e0da", "save_path": "github-repos/coq/coq-contribs-quicksort-complexity", "path": "github-repos/coq/coq-contribs-quicksort-complexity/quicksort-complexity-bf0205e5fcfec6d6c6017da071960594de79e0da/list_utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.6980327407708697}}
{"text": "Require Import Options.\n\nRequire Import Coq.micromega.Lia.\n\n(*\n  This page contains some example proofs.\n  Replace it with your project's files.\n*)\n\nExample subtract_one : forall n,\n  n > 0 ->\n  n - 1 <> n.\nProof.\n\ninduction n; lia.\n\nQed.\n\nLemma even_plus_two : forall n,\n  Nat.even n = true ->\n  Nat.even (n + 2) = true.\nProof.\n\ninduction n; simpl; try reflexivity.\n\ndestruct n as [| n'].\n1: intros Hf; inversion Hf.\n\nintros.\nreplace (S n' + 2) with (S (S (S n'))) by lia.\n\nsimpl.\nassumption.\n\nQed.\n\nExample two_n_always_even : forall n,\n  Nat.even (2*n) = true.\nProof.\n\ninduction n; simpl; try reflexivity.\nreplace (n + S (n + 0)) with (S (2*n)) by lia.\nassumption.\n\nQed.\n\nExample even_plus_one_is_odd : forall n,\n  Nat.even n = true ->\n  Nat.odd (n + 1) = true.\nProof.\n\nintros.\n\nunfold Nat.odd.\napply Bool.negb_true_iff.\n\ndestruct (DecidableTypeEx.Nat_as_DT.eq_dec n 0); subst; try solve [simpl; auto].\ndestruct (DecidableTypeEx.Nat_as_DT.eq_dec n 1); subst; try solve [simpl; auto].\ndestruct (DecidableTypeEx.Nat_as_DT.eq_dec n 2); subst; try solve [simpl; auto].\n\nassert (Nat.even (n - 1) = false). {\n  assert (exists k, S k = n). { exists (n-1). lia. }\n  destruct H0 as [k Hk].\n  replace (n-1) with k by lia. subst n.\n\n  destruct (Sumbool.sumbool_of_bool (Nat.even k)); auto.\n  exfalso.\n\n  induction k.\n  1: { simpl in *; inversion H. }\n  destruct (DecidableTypeEx.Nat_as_DT.eq_dec k 1); subst; try solve [simpl; auto].\n  simpl in *. inversion H.\n}\n\nreplace (n + 1) with (S (S (n - 1))) by lia.\nsimpl.\nassumption.\n\nQed.\n\nLemma not_both_even_and_odd : forall n,\n  ~ (Nat.even n = true /\\ Nat.odd n = true).\nProof.\n\nintros. unfold not; intros Hf. destruct Hf.\nunfold Nat.odd in H0.\napply Bool.negb_true_iff in H0.\nrewrite H in H0.\ninversion H0.\n\nQed.", "meta": {"author": "edwardcwang", "repo": "coq-template", "sha": "380e9edf0742bfd33aef83f0bc0343b361bbc247", "save_path": "github-repos/coq/edwardcwang-coq-template", "path": "github-repos/coq/edwardcwang-coq-template/coq-template-380e9edf0742bfd33aef83f0bc0343b361bbc247/Hello.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.6980093186589241}}
{"text": "(* File: My_Arith.v  (last edited on 25/10/2000) (c) Klaus Weich  *)\n\nRequire Import Le.\nRequire Import Lt.\nRequire Import List.\nRequire Import Plus.\n\n(******* List stuff ***********************************************)\n\n\nLemma fold_right_perm :\n forall (A B : Set) (f : B -> A -> A) (o : A) (l0 l1 : list B) (x : B),\n (forall (a b : B) (c : A), f a (f b c) = f b (f a c)) ->\n fold_right f o (l0 ++ x :: l1) = fold_right f o (x :: l0 ++ l1).\nintros A B f o l0 l1 x f_perm.\nelim l0; clear l0.\ntrivial.\nintros a0 l0 ih.\nsimpl in |- *.\n rewrite ih. \nsimpl in |- *.\napply f_perm.\nQed.\n\n\n\n\n(********************************************************************)\n\n\nLemma plus_O : forall n : nat, n + 0 = n.\nintros n.\n rewrite (plus_comm n 0).\nsimpl in |- *.\ntrivial.\nQed.\n\n\nLemma n_Sn_false : forall n : nat, n = S n -> False.\nintros n; elim n; clear n.\nintro u0;  discriminate u0.\nintros n ih u0.\napply ih.\n injection u0; trivial.\nQed.\n\nLemma le_reg : forall m n : nat, n <= m -> S n <= S m.\nintros m; elim m; clear m.\nintros n; case n; clear n.\nintros.\napply le_n.\nintros.\ninversion_clear H.\nintros m ih n H.\ninversion_clear H.\napply le_n.\napply le_S.\napply ih; assumption.\nQed.\n\n\nLemma eq_lt_trans : forall n m p : nat, n = m -> m < p -> n < p.\nintros n m p eq lt.\n rewrite eq; assumption.\nQed.\n\n\nLemma S_reg : forall n m : nat, n = m -> S n = S m.\nintros.\n rewrite H.\ntrivial.\nQed.\n\n\n\nLemma plus_reg : forall l m n : nat, m = n -> l + m = l + n.\nintros.\nelim l; clear l; simpl in |- *.\nassumption.\nintros l' ih.\n rewrite ih.\ntrivial.\nQed.\n\n\nLemma lt_plus_assoc_l :\n forall n m k l : nat, n + m + k < l -> n + (m + k) < l.\nintros n m k l lt.\n rewrite (plus_assoc n m k); assumption.\nQed.\n\n\nLemma my_lt_weak : forall n m : nat, S n < m -> n < m.\nintros n m H.\napply lt_S_n.\napply lt_trans with m; try assumption.\napply lt_n_Sn.\nQed.\n\n\n\n\n\n\n(********************************************************************)\n(*      max                                                         *)\n\n\nFixpoint max (n m : nat) {struct n} : nat :=\n  match n with\n  | O => m\n  | S p => match m with\n           | O => S p\n           | S q => S (max p q)\n           end\n  end.\n\nLemma le_n_max1 : forall n m : nat, n <= max n m.\nintros n; elim n; clear n.\nsimpl in |- *.\nintros m.\napply le_O_n.\nintros n ih m.\ncase m; clear m.\nsimpl in |- *.\ntrivial.\nintros m0; simpl in |- *.\napply le_n_S.\napply ih.\nQed.\n\n\nLemma le_n_max2 : forall n m : nat, n <= max m n.\nintros n; elim n; clear n.\nintros m.\napply le_O_n.\nintros n ih m.\ncase m; clear m.\nsimpl in |- *.\ntrivial.\nintros m0; simpl in |- *.\napply le_n_S.\napply ih.\nQed.\n\n\nLemma max_n_n : forall n : nat, max n n = n.\nsimple induction n; clear n; simpl in |- *. \ntrivial.\nintros n ih.\n rewrite ih.\ntrivial.\nQed.\n\nLemma max_Sn_n : forall n : nat, max (S n) n = S n.\nsimple induction n; clear n; simpl in |- *. \ntrivial.\nintros n ih.\n rewrite ih.\ntrivial.\nQed.\n\nLemma max_n_Sn : forall n : nat, max n (S n) = S n.\nsimple induction n; clear n; simpl in |- *.\ntrivial.\nintros n ih.\n rewrite ih.\ntrivial.\nQed.\n\n\nLemma max_n_O : forall n : nat, max n 0 = n.\nintros n; elim n; clear n.\ntrivial.\nintros n ih.\ntrivial.\nQed.\n\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/ipc/My_Arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.6980092965240092}}
{"text": "Require Import ZArith Lia Syntax Semantics.\n\nInductive aexpr :=\n  | Cst : Z -> aexpr\n  | Add : aexpr -> aexpr -> aexpr\n  | Var : nat -> aexpr.\n\nInductive imp :=\n  | Imp_Seq   : imp -> imp -> imp\n  | Imp_Aff   : nat -> aexpr -> imp\n  | Imp_While : aexpr -> imp -> imp.\n\nFixpoint eval (a : aexpr) (s : store) : Z :=\n  match a with\n  | Cst v => v\n  | Add e1 e2 => eval e1 s + eval e2 s\n  | Var x => s x\n  end.\n\n\nInductive imp_exec : store -> imp -> store -> Prop :=\n  | iexec_seq  : forall s1 s2 s3 p1 p2,\n    imp_exec s1 p1 s2 ->\n    imp_exec s2 p2 s3 ->\n    imp_exec s1 (Imp_Seq p1 p2) s3\n  | iexec_loop : forall s1 s2 s3 c p,\n    eval c s1 <> 0%Z ->\n    imp_exec s1 p s2 ->\n    imp_exec s2 (Imp_While c p) s3 ->\n    imp_exec s1 (Imp_While c p) s3\n  | iexec_loop_done : forall s c p,\n    eval c s = 0%Z ->\n    imp_exec s (Imp_While c p) s.\n\nFixpoint compile_cst_pos (n : nat) : program :=\n  match n with\n  | O => Done\n  | S m =>\n    Seq Incr (compile_cst_pos m)\n  end.\n\nFixpoint compile_cst_neg (n : nat) : program :=\n  match n with\n  | O => Done\n  | S m =>\n    Seq Decr (compile_cst_neg m)\n  end.\n\nDefinition compile_cst (v : Z) : program :=\n  if (0 <=? v)%Z then compile_cst_pos (Z.abs_nat v) else compile_cst_neg (Z.abs_nat v).\n\nDefinition Zneg (n : nat) : Z := - Z.of_nat n.\n\nDefinition Zpos (n : nat) := Z.of_nat n.\n\nLemma Zpos_abs :\n  forall n, n = Z.abs_nat (Zpos n).\nProof.\n  induction n; intros.\n  + cbn; reflexivity.\n  + cbn; destruct n; lia.\nQed.\n\nLemma Zneg_abs :\n  forall n, n = Z.abs_nat (Zneg n).\nProof.\n  induction n; intros.\n  + cbn; reflexivity.\n  + cbn; destruct n; lia.\nQed.\n\nLemma Zpos_succ :\n  forall n, Zpos (S n) = (1 + Zpos n)%Z.\nProof.\n  induction n; auto.\n  rewrite IHn.\n  unfold Zpos.\n  repeat rewrite Nat2Z.inj_succ.\n  lia.\nQed.\n\nLemma Zneg_pred :\n  forall n, Zneg (S n) = (Zneg n - 1)%Z.\nProof.\n  induction n; auto.\n  rewrite IHn.\n  unfold Zneg.\n  repeat rewrite Nat2Z.inj_succ.\n  lia.\nQed.\n\nLemma eval_succ :\n  forall z s, (eval (Cst (1 + z)) s = 1 + eval (Cst z) s)%Z.\nProof.\n  reflexivity.\nQed.\n\nLemma eval_pred :\n  forall z s, (eval (Cst (z - 1)) s = eval (Cst z) s - 1)%Z.\nProof.\n  reflexivity.\nQed.\n\nLemma eval_cst :\n  forall v s s', eval (Cst v) s = eval (Cst v) s'.\nProof.\n  reflexivity.\nQed.\n\nLemma get_val_incr :\n  forall s, (1 + get_val s)%Z = get_val (incr s).\nProof.\n  intros [ ].\n  unfold incr.\n  unfold get_val, store_incr, store_update.\n  rewrite (Nat.eqb_refl).\n  lia.\nQed.\n\nLemma get_val_decr :\n  forall s, (get_val s - 1)%Z = get_val (decr s).\nProof.\n  intros [ ].\n  unfold decr, get_val, store_decr, store_update.\n  rewrite (Nat.eqb_refl).\n  lia.\nQed.\n\nLemma compile_cst_pos_correct :\n  forall n s s',\n  s -< compile_cst_pos n >-> s' ->\n  (get_val s + eval (Cst (Zpos n)) (get_store s))%Z = get_val s'.\nProof.\n  induction n; intros.\n  - inversion_clear H.\n    rewrite <- Z.add_comm.\n    reflexivity.\n  - cbn in H.\n    inversion_clear H.\n    inversion_clear H0.\n    subst.\n    pose proof (IHn _ _ H1).\n    rewrite Zpos_succ, eval_succ, <- H.\n    replace (get_val (incr s)) with (1 + get_val s)%Z by apply get_val_incr.\n    replace (eval (Cst (Zpos n)) (get_store (incr s))) with (eval (Cst (Zpos n)) (get_store s)) by reflexivity.\n    lia.\nQed.\n\nLemma compile_cst_neg_correct :\n  forall n s s',\n  s -< compile_cst_neg n >-> s' ->\n  (get_val s + eval (Cst (Zneg n)) (get_store s))%Z = get_val s'.\nProof.\n  induction n; intros.\n  - inversion_clear H.\n    subst.\n    rewrite <- Z.add_comm.\n    reflexivity.\n  - cbn in H.\n    inversion_clear H.\n    inversion_clear H0.\n    subst.\n    pose proof (IHn _ _ H1).\n    rewrite Zneg_pred, eval_pred, <- H.\n    replace (get_val (decr s)) with (get_val s - 1)%Z by apply get_val_decr.\n    replace (eval (Cst (Zneg n)) (get_store (decr s))) with (eval (Cst (Zneg n)) (get_store s)) by reflexivity.\n    lia.\nQed.\n\nLemma compile_cst_correct :\n  forall v s,\n  state0 -< compile_cst v >-> s ->\n  eval (Cst v) (get_store state0) = get_val s.\nProof.\n  intros.\n  destruct v.\n  + now inversion_clear H.\n  + cbn in H.\n    rewrite <- (compile_cst_pos_correct _ _ _ H).\n    simpl.\n    unfold Zpos.\n    now rewrite positive_nat_Z.\n  + cbn in H.\n    rewrite <- (compile_cst_neg_correct _ _ _ H).\n    simpl.\n    unfold Zneg.\n    now rewrite positive_nat_Z.\nQed.", "meta": {"author": "acorrenson", "repo": "BF", "sha": "dc42233fa2c81d7507bd95174138a79c4bb19db4", "save_path": "github-repos/coq/acorrenson-BF", "path": "github-repos/coq/acorrenson-BF/BF-dc42233fa2c81d7507bd95174138a79c4bb19db4/src/Completness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6979870481010365}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Arith.Bool_nat.\nRequire Import Init.Nat.\nImport ListNotations.\n\nDefinition vertex := nat.\nDefinition edge := prod vertex vertex.\nRecord graph := Graph\n{\n  v_list : list vertex;\n  e_list : list edge\n}. \n\nDefinition cover := list edge.\n\nDefinition size (c : cover) := length c.\n\nDefinition gt n m := negb (n <=? m).\n\nDefinition empty : graph := Graph [] [].\nDefinition empty_cover : cover := [].\n\nDefinition incident (v : vertex) (e : edge) := \nmatch e with \n| (x,y) => x = v \\/ y = v\nend.\n\nDefinition incident_b (v : vertex) (e : edge) := \nmatch e with \n| (x,y) => orb (x =? v) (y =? v)\nend.\n\nDefinition is_cover (es : cover) (g : graph) := \nincl es (e_list g) /\\\nforall v : vertex, In v (v_list g) -> \n  exists e, In e (e_list g) /\\ incident v e.\n\nFixpoint elem {X : Type} (f : X -> X -> bool) e l := \nmatch l with \n| [] => false\n| x::xs => if f e x then true else elem f e xs\nend.\n\nDefinition incl_b {X : Type} f (l m : list X) := forallb (fun x => elem f x m) l.\n\nDefinition is_cover_b (es : cover) (g : graph) := \nandb \n(incl_b (fun e1 e2 => match (e1,e2) with ((x1,y1),(x2,y2)) => andb (eqb x1 x2) (eqb y1 y2) end)\n es (e_list g))\n(forallb (fun v => existsb (incident_b v) es) (v_list g)).\n\nTheorem trivial_cover : forall c : cover,  is_cover c empty -> c = empty_cover.\nProof.\nintros c [H1 H2].\ncompute in H1.\ninduction c.\n- reflexivity.\n- pose (H1 a).\npose (f (or_introl eq_refl)).\ninversion f0.\nQed.\n\nFixpoint all_subset {X : Type} (l : list X) := \nmatch l with \n| [] => [[]]\n| x::xs => \n  let subsets := all_subset xs in \n  subsets ++ (map (fun e => x::e) subsets)\nend.\n\n\nDefinition min (l : list nat) d := fold_left (fun acc x => if x <? acc then x else acc) l d.\n\nFixpoint min_vc (g : graph) : nat := \nlet covers := filter (fun c => is_cover_b c g) (all_subset (e_list g)) in \nmin (map (fun c => length c) covers) 5000.\n\nCompute min_vc (Graph [1;2;3;4;5] [(1,2);(2,3);(4,3);(1,5)]). \n\nTheorem min_vc_correct : forall (k : nat) (g : graph), \nmin_vc g = k -> ~ exists c, is_cover c g /\\  size c <= k.\nProof.\nAdmitted.", "meta": {"author": "kaonn", "repo": "5", "sha": "a0bff50104ec09cea6e7cc8c93f021a2b83063e9", "save_path": "github-repos/coq/kaonn-5", "path": "github-repos/coq/kaonn-5/5-a0bff50104ec09cea6e7cc8c93f021a2b83063e9/vertex_cover.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6979870300570561}}
{"text": "Require Export List.\n \nInductive ltree (A : Type) : Type :=\n  lnode: A -> list (ltree A) ->  ltree A .\n \nSection correct_ltree_ind.\nVariables (A : Type) (P : ltree A ->  Prop) (Q : list (ltree A) ->  Prop).\nHypotheses\n   (H : forall (a : A) (l : list (ltree A)), Q l ->  P (lnode A a l))\n   (H0 : Q nil)\n   (H1 : forall (t : ltree A),\n         P t -> forall (l : list (ltree A)), Q l ->  Q (cons t l)).\n \nFixpoint ltree_ind2 (t : ltree A) : P t :=\n match t as x return P x with\n    lnode _ a l =>\n      H a l ((fix l_ind (l' : list (ltree A)) : Q l' :=\n                     match l' as x return Q x with\n                        nil => H0\n                       | cons t1 tl => H1 t1 (ltree_ind2 t1) tl (l_ind tl)\n                     end) l)\n end.\n \nEnd correct_ltree_ind.\n \nSection correct_list_ltree_ind.\nVariables (A : Type) (P : ltree A ->  Prop) (Q : list (ltree A) ->  Prop).\nHypotheses\n   (H : forall (a : A) (l : list (ltree A)), Q l ->  P (lnode A a l))\n   (H0 : Q nil)\n   (H1 : forall (t : ltree A),\n         P t -> forall (l : list (ltree A)), Q l ->  Q (cons t l)).\n \nFixpoint list_ltree_ind2 (l : list (ltree A)) : Q l :=\n match l as x return Q x with\n   | nil => H0\n   | t :: tl => H1 t (ltree_ind2 A P Q H H0 H1 t) tl (list_ltree_ind2 tl)\n end.\n \nEnd correct_list_ltree_ind.\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch14_fundations_of_inductive_types/SRC/list_ltree_ind2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6979499204282187}}
{"text": "Add LoadPath \".\" as OPAT.\nRequire Import OPAT.aula3 OPAT.aula8 OPAT.aula9 OPAT.aula10 OPAT.doit6.\n\n(** **** Exercise: 2 stars (filter_even_gt7)  *)\n(** Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\nFixpoint gt7b (n:nat) : bool :=\n  match n with\n  | 0 => false\n  | 8 => true\n  | S n' => gt7b n'\n  end.\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter evenb (filter gt7b l).\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity. Qed.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (partition)  *)\n(** Use [filter] to write a Coq function [partition]:\n\n      partition : forall X : Type,\n                  (X -> bool) -> list X -> list X * list X\n\n   Given a set [X], a test function of type [X -> bool] and a [list\n   X], [partition] should return a pair of lists.  The first member of\n   the pair is the sublist of the original list containing the\n   elements that satisfy the test, and the second is the sublist\n   containing those that fail the test.  The order of elements in the\n   two sublists should be the same as their order in the original\n   list. *)\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n  : list X * list X :=\n(filter test l, filter (fun x => negb (test x)) l). \n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (map_rev)  *)\n(** Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\nLemma distr_map : 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.\n  - reflexivity.\n  - simpl. rewrite IHl1. reflexivity.\nQed.\n  \nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros X Y f l. induction l as [ | n l' IHl'].\n  -reflexivity.\n  -simpl. rewrite distr_map. simpl. rewrite IHl'. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (flat_map)  *)\n(** The function [map] maps a [list X] to a [list Y] using a function\n    of type [X -> Y].  We can define a similar function, [flat_map],\n    which maps a [list X] to a [list Y] using a function [f] of type\n    [X -> list Y].  Your definition should work by 'flattening' the\n    results of [f], like so:\n\n        flat_map (fun n => [n;n+1;n+2]) [1;5;10]\n      = [1; 2; 3; 5; 6; 7; 10; 11; 12].\n*)\n\nFixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X)\n  : (list Y) :=\n  match l with\n  | [] => []\n  | x :: t => (f x) ++ (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(** **** Exercise: 2 stars (fold_length)  *)\n(** Many common functions on lists can be implemented in terms of\n   [fold].  For example, here is an alternative definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length]. *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros X l. induction l.\n  - reflexivity.\n  - simpl. rewrite <- IHl. unfold fold_length. simpl. 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\nExample test_fold_map : fold_map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.", "meta": {"author": "bugarela", "repo": "Coq", "sha": "9f4973fec5b34ed836aa2239a009385e0549c024", "save_path": "github-repos/coq/bugarela-Coq", "path": "github-repos/coq/bugarela-Coq/Coq-9f4973fec5b34ed836aa2239a009385e0549c024/OPAT exercises/doit8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.8887587920192298, "lm_q1q2_score": 0.6979499146435291}}
{"text": "From mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq path fintype bigop.\n\n(** * Rewriting *)\n(** In this file we prove a few lemmas \n   that simplify work with rewriting. *)\nSection RewriteFacilities.\n  \n  Lemma diseq:\n    forall {X : Type} (p : X -> Prop) (x y : X),\n      ~ p x -> p y -> x <> y.\n  Proof. intros ? ? ? ? NP P EQ; subst; auto. Qed.\n\n  \n  Lemma eqprop_to_eqbool {X : eqType} {a b : X}: a = b -> a == b.\n  Proof. by intros; apply/eqP. Qed.\n\n  Lemma eqbool_true {X : eqType} {a b : X}: a == b -> a == b = true.\n  Proof. by move =>/eqP EQ; subst b; rewrite eq_refl. Qed.\n\n  Lemma eqbool_false {X : eqType} {a b : X}: a != b -> a == b = false.\n  Proof. by apply negbTE. Qed.\n\n  \n  Lemma eqbool_to_eqprop {X : eqType} {a b : X}: a == b -> a = b.\n  Proof. by intros; apply/eqP. Qed.\n\n  Lemma neqprop_to_neqbool {X : eqType} {a b : X}: a <> b -> a != b.\n  Proof. by intros; apply/eqP. Qed.\n\n  Lemma neqbool_to_neqprop {X : eqType} {a b : X}: a != b -> a <> b.\n  Proof. by intros; apply/eqP. Qed.\n\n  Lemma neq_sym {X : eqType} {a b : X}:\n    a != b -> b != a.\n  Proof.\n    intros NEQ; apply/eqP; intros EQ;\n      subst b; move: NEQ => /eqP NEQ; auto. Qed.\n\n  Lemma neq_antirefl {X : eqType} {a : X}:\n    (a != a) = false.\n  Proof. by apply/eqP. Qed.\n  \n  \n  Lemma option_inj_eq {X : eqType} {a b : X}:\n    a == b -> Some a == Some b.\n  Proof. by move => /eqP EQ; apply/eqP; rewrite EQ. Qed.\n\n  Lemma option_inj_neq {X : eqType} {a b : X}:\n    a != b -> Some a != Some b.\n  Proof.\n    by move => /eqP NEQ;\n     apply/eqP; intros CONTR;\n       apply: NEQ; inversion_clear CONTR. Qed.\n\n  (** Example *)\n  (* As a motivation for this file, we consider the following example. *)\n  Section Example.\n\n    (* Let X  be an arbitrary type ... *)\n    Context {X : eqType}.\n\n    (* ... f be an arbitrary function [bool -> bool] ... *)\n    Variable f : bool -> bool.\n\n    (* ... p be an arbitrary predicate on X ... *)\n    Variable p : X -> Prop.\n\n    (* ... and let a and b be two elements of X such that ... *)\n    Variables a b : X.\n    \n    (* ... p holds for a and doesn't hold for b. *)\n    Hypothesis H_pa : p a.\n    Hypothesis H_npb : ~ p b.\n\n    (* The following examples are commented out\n       to expose the insides of the proofs. *)\n    \n    (*\n    (* Simplifying some relatively sophisticated \n       expressions can be quite tedious. *)\n    [Goal f ((a == b) && f false) = f false.]\n    [Proof.]\n      (* Things like [simpl/compute] make no sense here. *)\n      (* One can use [replace] to generate a new goal. *)\n      [replace (a == b) with false; last first.]\n      (* However, this leads to a \"loss of focus\". Moreover, \n         the resulting goal is not so trivial to prove. *)\n      [{ apply/eqP; rewrite eq_sym eqbF_neg.]\n      [    by apply/eqP; intros EQ; subst b; apply H_npb. }]\n      [  by rewrite Bool.andb_false_l.]\n    [Abort.]\n     *)\n    \n    (*\n    (* The second attempt. *)\n    [Goal f ((a == b) && f false) = f false.]\n      (* With the lemmas above one can compose multiple \n         transformations in a single rewrite. *)\n      [  by rewrite (eqbool_false (neq_sym (neqprop_to_neqbool (diseq _ _ _ H_npb H_pa))))]\n      [        Bool.andb_false_l.]\n    [Qed.]\n    *)\n    \n  End Example.\n  \nEnd RewriteFacilities.\n", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/util/rewrite_facilities.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.6979390563057803}}
{"text": "Require Import Recdef Lia.\n\nFrom Typonomikon Require Import BinaryPos.\n\nInductive Z : Type :=\n| Pos  : Pos -> Z\n| Zero : Z\n| Neg  : Pos -> Z.\n\nFunction inv (k : Z) : Z :=\nmatch k with\n| Pos p => Neg p\n| Zero   => Zero\n| Neg p => Pos p\nend.\n\nFunction succ (k : Z) : Z :=\nmatch k with\n| Pos p     => Pos (BinaryPos.succ p)\n| Zero      => Pos I'\n| Neg I'    => Zero\n| Neg p     => Neg (BinaryPos.pred p)\nend.\n\nFunction pred (k : Z) : Z :=\nmatch k with\n| Pos I'    => Zero\n| Pos p     => Pos (BinaryPos.pred p)\n| Zero      => Neg I'\n| Neg p     => Neg (BinaryPos.succ p)\nend.\n\n(* TODO\nFunction add (k1 k2 : Z) : Z :=\nmatch k1, k2 with\n| Zero   , _       => k2\n| _      , Zero    => k1\n| Pos k1', Pos k2' => Pos (BinaryPos.add k1' k2')\n| Pos k1', Neg k2' =>\n  match BinaryPos.compare k1' k2' with\n  | Lt => Neg (BinaryPos.sub k2' k1')\n  | Eq => Zero\n  | Gt => Pos (BinaryPos.sub k1' k2')\n  end\n| Neg k1', Pos k2' =>\n  match BinaryPos.compare k1' k2' with\n  | Lt => Pos (BinaryPos.sub k2' k1')\n  | Eq => Zero\n  | Gt => Neg (BinaryPos.sub k1' k2')\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.\n*)", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/code/Num/BinaryZ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6979294240176457}}
{"text": "Fixpoint fact n :=\n  match n with\n    | O    => 1\n    | S n' => n * fact n'\n  end.\n\nDefinition v := fact 5.\nEval compute in v.", "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.8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6978984950184756}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.Lists.SetoidList.\n\nDefinition equiv_2 A B p1 p2 := forall (a : A) (b : B), p1 a b <-> p2 a b.\n\nLemma equiv_2_trans : forall A B a b c, @equiv_2 A B a b -> equiv_2 b c -> equiv_2 a c.\n  unfold equiv_2; intros; split; intros.\n  eapply H0; eapply H; eauto.\n  eapply H; eapply H0; eauto.\nQed.\n\nLemma InA_eq_In_iff : forall elt (ls : list elt) (x : elt), InA eq x ls <-> List.In x ls.\n  induction ls; simpl; intros.\n  intuition.\n  eapply InA_nil in H; eauto.\n  split; intros.\n  inversion H; subst.\n  eauto.\n  right.\n  eapply IHls.\n  eauto.\n  destruct H.\n  subst.\n  econstructor 1.\n  eauto.\n  econstructor 2.\n  eapply IHls.\n  eauto.\nQed.\n\nLemma InA_weaken :\n  forall A (P : A -> A -> Prop) (x : A) (ls : list A),\n    InA P x ls ->\n    forall (P' : A -> A -> Prop) x',\n      (forall y, P x y -> P' x' y) ->\n      InA P' x' ls.\n  induction 1; simpl; intuition.\nQed.\n\nLemma equiv_InA : forall elt (eq1 eq2 : elt -> elt -> Prop), equiv_2 eq1 eq2 -> equiv_2 (InA eq1) (InA eq2).\n  unfold equiv_2; split; intros; eapply InA_weaken; eauto; intros; eapply H; eauto.\nQed.\n\nLemma In_InA : forall A (x : A) ls,\n  List.In x ls\n  -> InA eq x ls.\n  intros; eapply InA_eq_In_iff; eauto.\nQed.\n\nLemma InA_In : forall A (x : A) ls,\n  InA eq x ls ->\n  List.In x ls.\n  intros; eapply InA_eq_In_iff; eauto.\nQed.\n\nLocal Hint Constructors List.NoDup NoDupA.\n\nLemma NoDupA_NoDup : forall A ls,\n  @NoDupA A eq ls\n  -> List.NoDup ls.\n  induction 1; intuition auto using In_InA.\nQed.\n\nLemma NoDup_NoDupA : forall A ls,\n  List.NoDup ls ->\n  @NoDupA A eq ls.\n  induction 1; intuition auto using InA_In.\nQed.\n", "meta": {"author": "mit-plv", "repo": "bedrock", "sha": "e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd", "save_path": "github-repos/coq/mit-plv-bedrock", "path": "github-repos/coq/mit-plv-bedrock/bedrock-e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd/Bedrock/Platform/Cito/SetoidListFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.6978219607623992}}
{"text": "(*|\n################################################\nLocal ``Inductive`` definitions and ``Theorems``\n################################################\n\n:Link: https://stackoverflow.com/q/36235244\n|*)\n\n(*|\nQuestion\n********\n\nI'm using a couple of ``Inductive`` definitions as counter examples in\nsome proofs. I would however like to encapsulate these definitions by\nenclosing them in a ``Section``. Regular ``Definitions`` can be hidden\nusing ``Let``, but is this also possible for ``Inductive``\ndefinitions? And how about ``Theorem``\\ s?\n\nLet me give the actual thing I'm trying to achieve, as I may be going\nabout it totally the wrong way in the first place. I want to formalize\nall the proofs and exercises of the excellent book \"Logics of Time and\nComputation\" by Robert Goldblatt into Coq.\n\nFor starters we take classical logic as that is what the book does as\nwell.\n|*)\n\nRequire Import Classical_Prop.\nRequire Import Classical_Pred_Type.\n\n(*|\nNext we define identifiers the same way it is done in Software\nFoundations.\n|*)\n\nInductive id : Type := Id : nat -> id.\n\n(*| Definition of the syntax. |*)\n\nInductive modal : Type :=\n| Bottom : modal\n| V : id -> modal\n| Imp : modal -> modal -> modal\n| Box : modal -> modal.\n\nDefinition Not (f : modal) : modal := Imp f Bottom.\n\n(*| Definition of the semantics using Kripke frames. |*)\n\n(* Inspired by: www.cs.vu.nl/~tcs/mt/dewind.ps.gz *)\nRecord frame : Type :=\n  { Worlds : Type\n  ; WorldsExist : exists w : Worlds, True\n  ; Rel : Worlds -> Worlds -> Prop }.\n\nRecord kripke : Type :=\n  { Frame : frame\n  ; Label : (Worlds Frame) -> id -> Prop }.\n\nFixpoint satisfies (M : kripke) (x : Worlds (Frame M)) (f : modal) : Prop :=\n  match f with\n  | Bottom => False\n  | V v => Label M x v\n  | Imp f1 f2 => satisfies M x f1 -> satisfies M x f2\n  | Box f => forall y : Worlds (Frame M), Rel (Frame M) x y -> satisfies M y f\n  end.\n\n(*| The first lemma relates the modal ``Not`` to the one of Coq. |*)\n\nLemma satisfies_Not : forall M x f, satisfies M x (Not f) = ~ satisfies M x f.\nProof. auto. Qed.\n\n(*| Next we lift the semantics to complete models. |*)\n\nDefinition M_satisfies (M : kripke) (f : modal) : Prop :=\n  forall w : Worlds (Frame M), satisfies M w f.\n\n(*| And we show what it means for the ``Not`` connective. |*)\n\nLemma M_satisfies_Not : forall M f, M_satisfies M (Not f) -> ~ M_satisfies M f.\nProof.\n  unfold M_satisfies.\n  intros M f Hn Hcontra.\n  destruct (WorldsExist (Frame M)).\n  specialize (Hn x). clear H.\n  rewrite satisfies_Not in Hn.\n  specialize (Hcontra x). auto.\nQed.\n\n(*|\nHere comes the thing. The reverse of the above lemma does not hold and\nI want to show this by a counter example, exhibiting a model for which\nit doesn't hold.\n|*)\n\nInductive Wcounter : Set := x1 : Wcounter | x2 : Wcounter | x3 : Wcounter.\n\nLemma Wcounter_not_empty : exists w : Wcounter, True.\nProof. exists x1. constructor. Qed.\n\nInductive Rcounter (x : Wcounter) (y : Wcounter) : Prop :=\n| E1 : x = x1 -> y = x2 -> Rcounter x y\n| E2 : x = x2 -> y = x3 -> Rcounter x y.\n\nDefinition Lcounter : Wcounter -> id -> Prop :=\n  fun x i => match x with\n             | x1 => match i with | Id 0 => True | _ => False end\n             | x2 => match i with | Id 1 => True | _ => False end\n             | x3 => match i with | Id 0 => True | _ => False end\n             end.\n\nDefinition Fcounter : frame := Build_frame Wcounter Wcounter_not_empty Rcounter.\n\nDefinition Kcounter : kripke := Build_kripke Fcounter Lcounter.\n\n(*|\nNext an ``Ltac`` that relieves me from typing verbose ``assert``\\ s.\n|*)\n\nLtac counter_example H Hc :=\n  match type of H with\n  | ?P -> ~ ?Q => assert (Hc: Q)\n  | ?P -> (?Q -> False) => assert (Hc: Q)\n  | ?P -> ?Q => assert (Hc: ~Q)\n  end.\n\n(*|\nFinally I use this counter example to prove the following ``Lemma``.\n|*)\n\nLemma M_not_satisfies_Not :\n  ~ forall M f, ~ M_satisfies M f -> M_satisfies M (Not f).\nProof.\n  apply ex_not_not_all. exists Kcounter.\n  apply ex_not_not_all. exists (V (Id 0)).\n  unfold M_satisfies. simpl.\n  intro Hcontra. unfold not in Hcontra.\n  counter_example Hcontra Hn2.\n  - apply ex_not_not_all. exists x1. simpl. auto.\n  - apply Hn2. apply Hcontra. apply ex_not_not_all; exists x2. simpl. auto.\nQed.\n\n(*|\nPreferably I would have used the ``remember`` tactic to define the\ncounter example inside the proof, but I don't think it can be used for\nthe ``Inductive`` definitions. All the definitions relating to the\ncounter example are exported as part of my theory, which I prefer not\nto do. It is only used in the proof of ``M_not_satisfies_Not``.\nActually I would not even want to export this ``Lemma`` either as it\nis not very useful. I only put it there to argue that\n``M_satisfies_Not`` can not be an equivalence.\n|*)\n\n(*|\nAnswer\n******\n\n``Section`` doesn't hide definitions, use ``Module`` instead. For\nexample put the counter example in a module.\n\n.. code-block:: coq\n\n    Module CounterExample.\n      Import Definitions.\n      Inductive Wcounter : Set := x1 | x2 | x3.\n      ...\n      Lemma M_not_satisfies_Not : ...\n    End CounterExample.\n\nAt this stage, only ``CounterExample`` is defined at the top level.\n\nIf you don't want that either, then you could just put the definitions\nin one ``.v`` file and the counter example in another file that\nimports the definitions. Actually, the way it works is that ``.v``\nfiles are turned into individual modules.\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/local-inductive-definitions-and-theorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388040954683, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.6978219452896085}}
{"text": "(** Exercise 5.1 **)\n\nLemma id_P : forall P:Prop, P->P.\nProof.\n  intros P H; assumption.\nQed.\n\nLemma id_PP : forall P:Prop, (P->P)->(P->P).\nProof.\n  intros P H; assumption.\nQed.\n\nLemma imp_trans :\n  forall P Q R:Prop, (P->Q)->(Q->R)->P->R.\nProof.\n  intros P Q R PQH QRH PH.\n  apply QRH, PQH.\n  assumption.\nQed.\n\nLemma imp_perm :\n  forall P Q R:Prop, (P->Q->R)->(Q->P->R).\nProof.\n  intros P Q R PQRH QH PH.\n  apply PQRH; assumption.\nQed.\n\nLemma ignore_Q :\n  forall P Q R:Prop, (P->R)->P->Q->R.\nProof.\n  intros P Q R PRH PH QH.\n  apply PRH.\n  assumption.\nQed.\n\nLemma delta_imp :\n  forall P Q:Prop, (P->P->Q)->P->Q.\nProof.\n  intros P Q PPQH PH.\n  apply PPQH; assumption.\nQed.\n\nLemma delta_impR : \n  forall P Q:Prop, (P->Q)->(P->P->Q).\nProof.\n  intros P Q PQH PH PH2.\n  apply PQH.\n  assumption.\nQed.\n\nLemma diamond :\n  forall P Q R T:Prop,\n  (P->Q)->(P->R)->(Q->R->T)->P->T.\nProof.\n  intros P Q R T PQH PRH QRTH PH.\n  apply QRTH.\n  apply PQH.\n  assumption.\n  apply PRH.\n  assumption.\nQed.\n\nLemma weak_peirce :\nforall P Q:Prop, ((((P->Q)->P)->P)->Q)->Q.\nProof.\n  intros P Q H1.\n  apply H1.\n  intros H2.\n  apply H2.\n  intros PH.\n  apply H1.\n  intros H3.\n  assumption.\nQed.\n\n(** Exercise 5.2 **)\n\n(** ALREADY DONE THAT WAY... **)\n\n(** Exercise 5.3 **)\n\nLemma Ex_5_3_1: ~False.\nProof.\n  intro H.\n  exact H.\nQed.\n(* Essentially P->P *)\n\nLemma Ex_5_3_2: forall P:Prop, ~~~P->~P.\nProof.\n  unfold not.\n  intros P H1 p.\n  apply H1.\n  intro H2.\n  apply H2.\n  assumption.\nQed.\n(* Essentially (((P->Q)->Q)->Q)->P->Q *)\n\nLemma Ex_5_3_3:\n  forall P Q:Prop, ~~~P->P->Q.\nProof.\n  intros P Q H p.\n  assert (~P).\n  apply Ex_5_3_2; assumption.\n  elim H0; assumption.\nQed.\n\nLemma Ex_5_3_4:\n  forall P Q:Prop, (P->Q)->~Q->~P.\nProof.\n  unfold not.\n  intros p q H1 H2 H3.\n  apply H2, H1, H3.\nQed.\n(* Essentially (P->Q)->(Q->R)->P->R *)\n\nLemma Ex_5_3_5:\n  forall P Q R:Prop, (P->Q)->(P->~Q)->P->R.\nProof.\n  intros P Q R H1 H2 H3.\n  elim H2.\n  assumption.\n  apply H1; assumption.\nQed.\n\n(** Exercise 5.4 **)\n\nDefinition dyslexic_imp :=\n  forall P Q:Prop, (P->Q)->(Q->P).\n\nDefinition dyslexic_contrap :=\n  forall P Q:Prop, (P->Q)->(~P->~Q).\n\nTheorem dyslexic_imp_implies_false:\n  dyslexic_imp -> False.\nProof.\n  unfold dyslexic_imp.\n  intro H.\n  assert ((False->~False)->~False->False) as H1.\n  apply H.\n  apply H1.\n  intro H2.\n  elim H2.\n  intro H2.\n  assumption.\nQed.\n\nTheorem dyslexic_contrap_implies_flase:\n  dyslexic_contrap -> False.\nProof.\n  unfold dyslexic_contrap.\n  intro H.\n  assert\n    ((False->~False)->~False->~~False) as H1.\n  apply H.\n  apply H1.\n  intro H2; elim H2.\n  intro H2; assumption.\n  intro H2; assumption.\nQed.\n\n(** Exercise 5.5 **)\n\nTheorem Ex_5_5:\n  forall (A:Set)(a b c d:A),\n  a=c \\/ b=c \\/ c=c \\/ d=c.\nProof.\n  intros A a b c d.\n  right; right; left.\n  reflexivity.\nQed.\n\n(** Exercise 5.6 **)\n\nTheorem Ex_5_6_a:\n  forall A B C:Prop, A/\\(B/\\C)->(A/\\B)/\\C.\nProof.\n  intros A B C H.\n  repeat split; apply H.\nQed.\n\nTheorem Ex_5_6_b:\n  forall A B C D:Prop,\n  (A->B)/\\(C->D)/\\A/\\C -> B/\\D.\nProof.\n  intros A B C D H.\n  elim H.\n  split.\n  (* It's not very nice to use auto names *)\n  apply H0.\n  apply H.\n  repeat apply H1.\nQed.\n\nTheorem Ex_5_6_c: forall A:Prop, ~(A/\\~A).\nProof.\n  intros A H.\n  repeat apply H.\nQed.\n\nTheorem Ex_5_6_d: \n  forall A B C:Prop, A\\/(B\\/C)->(A\\/B)\\/C.\nProof.\n  intros A B C H.\n  elim H.\n  intro H1; repeat left; assumption.\n  intro H1; elim H1.\n  intro H2; left; right; assumption.\n  intro H2; repeat right; assumption.\nQed.\n\nTheorem Ex_5_6_e:\n  forall A:Prop, ~~(A\\/~A).\nProof.\n  unfold not.\n  intros A H.\n  elim H.\n  right.\n  intro H1.\n  apply H.\n  left.\n  assumption.\nQed.\n\nTheorem Ex_5_6_f:\n  forall A B:Prop, (A\\/B)/\\~A -> B.\nProof.\n  intros A B H.\n  elim H.\n  intros H1 H2.\n  elim H1.\n  intro H3.\n  contradiction.\n  intro H3.\n  assumption.\nQed.\n\n(** Exercise 5.7 **)\n\nDefinition peirce := \n  forall P Q:Prop, ((P->Q)->P)->P.\n\nDefinition classic :=\n  forall P:Prop, ~~P->P.\n\nDefinition excluded_middle :=\n  forall P:Prop, P\\/~P.\n\nDefinition de_morgan_not_and_not :=\n  forall P Q:Prop, ~(~P/\\~Q)->P\\/Q.\n\nDefinition implies_to_or :=\n  forall P Q:Prop, (P->Q)->(~P\\/Q).\n\nLemma peirce_implies_classic:\n  peirce -> classic.\nProof.\n  unfold peirce, classic.\n  intro H.\n  assert (forall P:Prop,\n          ((P->False)->P)->P) as H1.\n  intro P.\n  apply H.\n  intros P H2.\n  apply H1.\n  intro H3.\n  contradiction.\nQed.\n\nLemma nn_excluded_middle:\n  forall P:Prop, ~~(P\\/~P).\nProof.\n  intros P H.\n  assert (~P) as H1.\n  intro H2.\n  apply H.\n  left; assumption.\n  assert (~~P).\n  intro H2.\n  apply H.\n  right; assumption.\n  contradiction.\nQed.\n\nLemma classic_implies_excluded_middle:\n  classic -> excluded_middle.\nProof.\n  unfold classic, excluded_middle.\n  intros H P.\n  assert (~~(P\\/~P)) as H1.\n  apply nn_excluded_middle.\n  apply H; assumption.\nQed.\n\nLemma excluded_middle_implies_dmnan:\n  excluded_middle -> de_morgan_not_and_not.\nProof.\n  unfold excluded_middle, de_morgan_not_and_not.\n  intros H P Q.\n  assert (P\\/~P) as H1.\n  apply H.\n  assert (Q\\/~Q) as H2.\n  apply H.\n  elim H1.\n  elim H2.\n  intros; left; assumption.\n  intros; left; assumption.\n  elim H2.\n  intros; right; assumption.\n  intros H3 H4 H5.\n  assert (~P/\\~Q).\n  split; assumption.\n  contradiction.\nQed.\n\nLemma modus_tollens:\n  forall P Q:Prop, (P->Q)->(~Q->~P).\nProof.\n  intros P Q H1 H2 H3.\n  assert Q as H4.\n  apply H1, H3.\n  contradiction.\nQed.\n\nLemma dmnan_implies_implies_to_or:\n  de_morgan_not_and_not -> implies_to_or.\nProof.\n  unfold de_morgan_not_and_not, implies_to_or.\n  intros H P Q.\n  intro H1.\n  apply H.\n  intro H2.\n  assert (~Q->~P) as H3.\n  apply modus_tollens; assumption.\n  assert (~P); apply H3.\n  apply H2.\n  apply H2.\n  assert (~~P) as H4.\n  apply H2.\n  contradiction.\nQed.\n\nLemma implies_to_or_implies_peirce:\n  implies_to_or -> peirce.\nProof.\n  unfold implies_to_or, peirce.\n  intros H1 P Q.\n  assert (~P\\/P) as H2.\n  apply H1; intro H3; assumption.\n  elim H2.\n  intros H4 H5.\n  apply H5; intro H6; contradiction.\n  intros H7 H8; assumption.\nQed.\n\nLemma five_circ_impl_implies_equiv:\n  forall P Q R S T:Prop,\n  (P->Q)/\\(Q->R)/\\(R->S)/\\(S->T)/\\(T->P) ->\n  (P<->Q)/\\(Q<->R)/\\(R<->S)/\\(S<->T).\nProof.\n  intros P Q R S T H.\n  repeat split.\n  apply H. intro H'; do 4 apply H; assumption.\n  apply H. intro H'; do 4 apply H; assumption.\n  apply H. intro H'; do 4 apply H; assumption.\n  apply H. intro H'; do 4 apply H; assumption.\nQed.\n\nTheorem classical_axioms_equiv:\n  (peirce <-> classic) /\\\n  (classic <-> excluded_middle) /\\\n  (excluded_middle <-> de_morgan_not_and_not) /\\\n  (de_morgan_not_and_not <-> implies_to_or).\nProof.\n  apply five_circ_impl_implies_equiv.\n  repeat split.\n  apply peirce_implies_classic.\n  apply classic_implies_excluded_middle.\n  apply excluded_middle_implies_dmnan.\n  apply dmnan_implies_implies_to_or.\n  apply implies_to_or_implies_peirce.\nQed.\n\n(** Exercise 5.8 **)\n\n(* repeat idtac succeeds doing nothing and\n   repeat fail fails when first tried *)\n\n(** Exercise 5.9 **)\n\nSection ex_5_9.\n\n  Hypothesis A:Set.\n  Hypothesis P Q:A->Prop.\n\n  Lemma ex_5_9_a:\n    (exists x:A, P x \\/ Q x) ->\n    (ex P) \\/ (ex Q).\n  Proof.\n    intro H1.\n    elim H1.\n    intros H2 H3.\n    elim H3.\n    intro H4; left; exists H2; apply H4.\n    intro H5; right; exists H2; apply H5.\n  Qed.\n\n  Lemma ex_5_9_b:\n    (ex P)\\/(ex Q) -> exists x:A, P x \\/ Q x.\n  Proof.\n    intro H1.\n    elim H1.\n    intro H2; elim H2; intros H3 H4; exists H3.\n    left; assumption.\n    intro H2; elim H2; intros H3 H4; exists H3.\n    right; assumption.\n  Qed.\n\n  Lemma ex_5_9_c:\n    (exists  x:A, (forall R:A -> Prop, R x)) ->\n    2 = 3.\n  Proof.\n    intro H1.\n    elim H1.\n    intros H2 H3.\n    assert False as H4.\n    apply H3 with (R := fun (x:A) => False).\n    elim H4.\n  Qed.\n\n  Lemma ex_5_9_d:\n    (forall x:A, P x) -> ~(exists y:A, ~P y).\n  Proof.\n    intros H1 H2.\n    elim H2.\n    intros H3 H4.\n    apply H4, H1.\n  Qed.\n\nEnd ex_5_9.\n\n(** Exercise 5.10 **)\n\nRequire Import Arith.\n\nTheorem plus_permute2:\n  forall n m p:nat, n+m+p = n+p+m.\nProof.\n  intros.\n  assert (n+(m+p) = n+m+p) as H0.\n  apply plus_assoc.\n  assert (n+(p+m) = n+p+m) as H1.\n  apply plus_assoc.\n  rewrite <-H0, <-H1.\n  assert (m + p = p + m) as H2.\n  apply plus_comm.\n  rewrite H2.\n  reflexivity.\nQed.\n\n(** Exercise 5.11 **)\n\nTheorem eq_trans:\n  forall (A:Type)(x y z:A), \n  x = y -> y = z -> x = z.\nProof.\n  intros A x y z H0 H1.\n  Check eq_ind.\n  apply eq_ind with\n    (x := y)(y := x)(P := fun a:A => a = z).\n  assumption.\n  symmetry; assumption.\nQed.\n\nTheorem eq_trans_2:\n  forall (A:Type)(x y z:A), \n  x = y -> y = z -> x = z.\nProof.\n  intros A x y z H0 H1.\n  rewrite H0; assumption.\nQed.\n\n(** Exercise 5.12 **)\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.\n  assumption.\nQed.\n\nTheorem my_False_ind:\n  forall P:Prop, my_False -> P.\nProof.\n  intros P H.\n  apply H.\nQed.\n\nCheck (fun (P:Prop)(p:P) => p).\n\nCheck (fun (P:Prop)(mf:my_False) => mf P).\n\n(** Exercise 5.13 **)\n\nDefinition my_not (P:Prop) := P -> my_False.\n\nLemma Ex_5_13_1: my_not my_False.\nProof.\n  intro H.\n  exact H.\nQed.\n\nLemma Ex_5_13_2:\n  forall P:Prop, \n  my_not (my_not (my_not P)) -> my_not P.\nProof.\n  unfold my_not.\n  intros P H1 p.\n  apply H1.\n  intro H2.\n  apply H2.\n  assumption.\nQed.\n\nLemma Ex_5_13_3:\n  forall P Q:Prop,\n  my_not (my_not (my_not P)) -> P -> Q.\nProof.\n  intros P Q H p.\n  assert (my_not P).\n  apply Ex_5_13_2; assumption.\n  (* new ending *)\n  assert (my_False) as H1.\n  apply H0; assumption.\n  apply H1.\nQed.\n\nLemma Ex_5_13_4:\n  forall P Q:Prop,\n  (P->Q) -> (my_not Q) -> (my_not P).\nProof.\n  unfold my_not.\n  intros p q H1 H2 H3.\n  apply H2, H1, H3.\nQed.\n\nLemma Ex_5_13_5:\n  forall P Q R:Prop,\n  (P->Q)->(P->(my_not Q))->P->R.\nProof.\n  intros P Q R H1 H2 H3.\n  (* new ending *)\n  assert Q as H4.\n  apply H1; assumption.\n  assert (my_not Q) as H5.\n  apply H2; assumption.\n  assert (my_False) as H6.\n  apply H5, H4.\n  apply H6.\nQed.\n\n(** Exercise 5.14 **)\n\n(* Given *)\n\nSection leibniz.\n  Set Implicit Arguments.\n  Unset Strict Implicit.\n  Variable A : Set.\n\n  Definition leibniz (a b:A) : Prop :=\n    forall P:A -> Prop, P a -> P b.\n\n  Require Import Relations.\n\n  Theorem leibniz_sym: symmetric A leibniz.\n  Proof.\n    unfold symmetric, leibniz.\n    intros x y H Q.\n    apply H.\n    trivial.\n  Qed.\n\n  (* to prove *)\n\n  Theorem leibniz_refl: reflexive A leibniz.\n  Proof.\n    unfold reflexive, leibniz.\n    intros x P.\n    trivial.\n  Qed.\n\n  Theorem leibniz_trans: transitive A leibniz.\n  Proof.\n    unfold transitive, leibniz.\n    intros x y z H1 H2 P H3.\n    apply H2, H1; assumption.\n  Qed.\n\n  Theorem leibniz_equiv: equiv A leibniz.\n  Proof.\n    unfold equiv.\n    repeat split.\n    apply leibniz_refl.\n    apply leibniz_trans.\n    apply leibniz_sym.\n  Qed.\n\n  Theorem leibniz_least_reflexive:\n    forall R:relation A, \n    reflexive A R -> inclusion A leibniz R.\n  Proof.\n    unfold relation, reflexive, inclusion,\n           leibniz.\n    intros R H1 x y H2.\n    apply H2, H1.\n  Qed.\n\n  Theorem leibniz_eq: \n    forall a b:A, leibniz a b -> a = b.\n  Proof.\n    unfold leibniz.\n    intros a b H.\n    apply H; reflexivity.\n  Qed.\n\n  Theorem leibniz_ind:\n    forall (x:A)(P:A->Prop),\n    P x -> forall y:A, leibniz x y -> P y.\n  Proof.\n    unfold leibniz.\n    intros x P H1 y H2.\n    apply H2; assumption.\n  Qed.\n\n  Unset Implicit Arguments.\n\nEnd leibniz.\n\n(** Exercise 5.15 **)\n\n(* Definitions given *)\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:Set)(P:A->Prop) :=\n  forall R:Prop, (forall x:A, P x -> R)->R.\n\n(* To prove *)\n\nLemma ex_5_15_1:\n  forall P Q:Prop, my_and P Q -> P.\nProof.\n  unfold my_and.\n  intros P Q H.\n  apply H.\n  intros p q; assumption.\nQed.\n\nLemma ex_5_15_2:\n  forall P Q:Prop, my_and P Q -> Q.\nProof.\n  unfold my_and.\n  intros P Q H.\n  apply H.\n  intros p q; assumption.\nQed.\n\nLemma ex_5_15_3:\n  forall P Q R:Prop,\n  (P->Q->R) -> my_and P Q -> R.\nProof.\n  unfold my_and.\n  intros P Q R H1 H2.\n  apply H2; assumption.\nQed.\n\nLemma ex_5_15_4:\n  forall P Q:Prop, P -> my_or P Q.\nProof.\n  unfold my_or.\n  intros P Q p R.\n  intros H1 H2.\n  apply H1; assumption.\nQed.\n\nLemma ex_5_15_5:\n  forall P Q:Prop, Q -> my_or P Q.\nProof.\n  unfold my_or.\n  intros P Q q R.\n  intros H1 H2.\n  apply H2; assumption.\nQed.\n\nLemma ex_5_15_6:\n  forall P Q R:Prop,\n  (P->R) -> (Q->R) -> my_or P Q -> R.\nProof.\n  unfold my_or.\n  intros P Q R H1 H2 H3.\n  apply H3; assumption.\nQed.\n\nLemma ex_5_15_7:\n  forall P:Prop, my_or P my_False -> P.\nProof.\n  unfold my_or, my_False.\n  intros P H1.\n  apply H1; trivial.\n  intros H2.\n  apply H2.\nQed.\n\nLemma ex_5_15_8:\n  forall P Q:Prop, my_or P Q -> my_or Q P.\nProof.\n  unfold my_or.\n  intros P Q H1 R H2 H3.\n  apply H1; assumption.\nQed.\n\nLemma ex_5_15_9:\n  forall (A:Set)(P:A->Prop)(a:A),\n  P a -> my_ex A P.\nProof.\n  unfold my_ex.\n  intros A P a H1 R H2.\n  apply H2 with (x := a), H1.\nQed.\n\nLemma ex_5_15_10:\n  forall (A:Set)(P:A->Prop),\n  my_not (my_ex A P) ->\n  forall a:A, my_not (P a).\nProof.\n  unfold my_ex, my_not.\n  intros A P H1 a H2.\n  apply H1.\n  intros R H3.\n  apply H3 with (x := a).\n  assumption.\nQed.\n\n(** Exercise 5.16 **)\n\n(* Given *)\n\nDefinition my_le (n p:nat) :=\n  forall P:nat -> Prop,\n  P n -> (forall q:nat, P q -> P (S q)) -> P p.\n\n(* To prove *)\n\nLemma my_le_n:\n  forall n:nat, my_le n n.\nProof.\n  unfold my_le.\n  intros n P H1 _; assumption.\nQed.\n\nLemma my_le_S:\n  forall n p:nat, my_le n p -> my_le n (S p).\nProof.\n  unfold my_le.\n  intros n p H1 P H2 H3.\n  apply H3, H1.\n  assumption.\n  exact H3.\nQed.\n\nLemma my_le_le:\n  forall n p:nat, my_le n p -> n <= p.\nProof.\n  unfold my_le.\n  intros n p H1.\n  apply H1.\n  apply le_n.\n  apply le_S.\nQed.", "meta": {"author": "mchouza", "repo": "learning-coq", "sha": "b5a3409d34dcce571c002b6e6b8e80acce069e82", "save_path": "github-repos/coq/mchouza-learning-coq", "path": "github-repos/coq/mchouza-learning-coq/learning-coq-b5a3409d34dcce571c002b6e6b8e80acce069e82/coq-ch5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825635346563, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.6978219443148644}}
{"text": "(* begin hide *)\nRequire Import Unicode.Utf8.\nRequire Import CoqCats.Category.\nRequire Import CoqCats.PolyPrelude.\n\nSet Universe Polymorphism.\nSet Polymorphic Inductive Cumulativity.\n(* end hide *)\n\n(** * Categorical products.\n\n    I define products of an arbitrarily indexed set of objects. To\n    recover the familiar binary product, set idx to 2.\n *)\nRecord product {cat : category} {idx}\n       (object_product : cat) (components : idx → cat) :=\n  { (** The property we care about: An arrow to each component. *)\n    property o := ∀ i, o ⇝ (components i);\n    (** The projections from our object product. *)\n    π : property object_product;\n    (** Any object with our property has an arrow to our distingiushed\n        object prodcut. *)\n    morphism_product : ∀ {o}, property o → o ⇝ object_product;\n    (** We now have an indexed set of diagrams: Given an arbitrary\n        object satisfying our property, we have an arrow from it to\n        our object product and for each i, we have an arrow from\n        our object product to the relevant component and an arrow from\n        the arbitrary object to the relevant component. Abstracting\n        away the distingiushed morphism product and replacing it with\n        an arbitrary arrow f from the arbitrary object to our object\n        product, we say f commutes with this set of diagrams when each\n        diagram commutes in the obvious way.\n     *)\n    commutes o (γ : property o) f := ∀ i, π i ∘ f = γ i;\n    morphism_product_commutes : ∀ {o γ},\n        commutes o γ (morphism_product γ);\n    morphism_product_unique : ∀ {o γ f},\n        commutes o γ f → f = morphism_product γ;\n  }.\n\nArguments morphism_product [cat] [idx] [object_product] [components] _ [o].\nArguments π [cat] [idx] [object_product] [components].\nArguments commutes [cat] [idx] [object_product] [components].\nArguments morphism_product_commutes [cat] [idx] [object_product] [components] _ {o} {γ}.\nArguments morphism_product_unique [cat] [idx] [object_product] [components] _ [o] [γ] [f].\n\nSection product.\n  Variable cat : category.\n  Section identity.\n    Variable idx : Type.\n    Variable op : cat.\n    Variable comp : idx → cat.\n    Variable prod : product op comp.\n\n    (** In prose:\n        Lemma: The identity commutes\n        Proof: For each i, it's given by the fact that 1 is a right\n        identity of ∘.\n        Theorem: The identity is the morphism product from the object\n        product to itself.\n        Proof: The morphism product uniquely commutes, and the\n        identity commutes.\n\n        TODO Figure out how tactics work.\n     *)\n    Definition identity_morphism_product :\n      prod.(morphism_product) prod.(π) = 1 :=\n      let\n        id_commutes _ := cat.(right_identity)\n      in eq_sym (prod.(morphism_product_unique) id_commutes).\n  End identity.\n\n  Arguments identity_morphism_product [idx] [op] [comp].\n\n  Section product_unique.\n    Variable idx : Type.\n    Variable op op₂: cat.\n    Variable comp : idx → cat.\n    Variable prod : product op comp.\n    Variable prod₂ : product op₂ comp.\n    Definition product_unique_up_to_iso :\n      isomorphism (prod.(morphism_product) prod₂.(π)) :=\n      {| to := prod₂.(morphism_product) prod.(π);\n         comm_from :=\n           let\n             (** In prose:\n                 We want to prove that to ∘ from commutes with the\n                 relevant diagram, first we go from πᵢ₂ ∘ to ∘ from\n                 to πᵢ₁ ∘ from by the fact that the morphism product\n                 (in prod₂) commutes, then we go from πᵢ₁ ∘ from to\n                 πᵢ₂ by the fact that the morphism product (in prod₁)\n                 commutes\n              *)\n             loop_commutes i :=\n             eq_trans\n               (eq_sym cat.(compose_assoc))\n               (eq_trans\n                  (compose_transport_left\n                     (prod₂.(morphism_product_commutes) i))\n                  (prod.(morphism_product_commutes) i))\n           (** And now that we know the loop commutes, we know it\n               must be the identity by uniqueness of the morphism\n               product.\n            *)\n           in eq_trans\n                (prod₂.(morphism_product_unique) loop_commutes)\n                (prod₂.(identity_morphism_product));\n         (** This direction is just the other with indices flipped *)\n         comm_to :=\n           let\n             loop_commutes i :=\n             eq_trans\n               (eq_sym cat.(compose_assoc))\n               (eq_trans\n                  (compose_transport_left\n                     (prod.(morphism_product_commutes) i))\n                  (prod₂.(morphism_product_commutes) i))\n           in eq_trans\n                (prod.(morphism_product_unique) loop_commutes)\n                (prod.(identity_morphism_product));\n    |}.\n  End product_unique.\nEnd product.\n", "meta": {"author": "shlevy", "repo": "coq-cats", "sha": "c0283b39985753b0aa8df76365d881a7e4b607a2", "save_path": "github-repos/coq/shlevy-coq-cats", "path": "github-repos/coq/shlevy-coq-cats/coq-cats-c0283b39985753b0aa8df76365d881a7e4b607a2/src/Product.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.6978189043410711}}
{"text": "From Hammer Require Import Hammer.\n\n\n\nRequire Export Wf_nat.\nRequire Export ZArith.\nOpen Scope Z_scope.\n\nDefinition R_noet (x y : nat * nat) : Prop :=\n((fst x) + (snd x) < (fst y) + (snd y))%nat.\n\nDefinition f (x : nat * nat) := ((fst x) + (snd x))%nat.\n\nLemma R_noet_wf : well_founded R_noet.\nProof. hammer_hook \"Descent\" \"Descent.R_noet_wf\".\napply (well_founded_lt_compat _ f R_noet); auto.\nQed.\n\nLemma noetherian : forall P : nat * nat -> Prop,\n(forall z : nat * nat, (forall y : nat * nat,\n(fst(y) + snd(y) < fst(z) + snd(z))%nat -> P y) -> P z) ->\nforall x : nat * nat, P x.\nProof. hammer_hook \"Descent\" \"Descent.noetherian\".\nintros; generalize (well_founded_ind R_noet_wf P); auto.\nQed.\n\nLemma infinite_descent_nat : forall P : nat * nat -> Prop,\n(forall x : nat * nat, (P x -> exists y : nat * nat,\n(fst(y) + snd(y) < fst(x) + snd(x))%nat /\\ P y)) ->\nforall x : nat * nat, ~(P x).\nProof. hammer_hook \"Descent\" \"Descent.infinite_descent_nat\".\nintros; apply (noetherian (fun x => ~(P x))); red; intros; elim (H z H1);\nintros; apply (H0 x0); tauto.\nQed.\n\nLemma infinite_descent : forall P : Z -> Z -> Prop,\n(forall x1 x2 : Z, 0 <= x1 -> 0 <= x2 ->\n(P x1 x2 -> exists y1 : Z, exists y2 : Z, 0 <= y1 /\\ 0 <= y2 /\\\ny1 + y2 < x1 + x2 /\\ P y1 y2)) ->\nforall x y: Z, 0 <= x -> 0 <= y -> ~(P x y).\nProof. hammer_hook \"Descent\" \"Descent.infinite_descent\".\nintros; elim (Z_of_nat_complete _ H0); clear H0; intros;\nelim (Z_of_nat_complete _ H1); clear H1; intros; rewrite H0; rewrite H1;\nclear H0 H1;\ngeneralize (infinite_descent_nat\n(fun c => P (Z_of_nat (fst c)) (Z_of_nat (snd c)))); intro;\ncut (~( P (Z_of_nat (fst (x0, x1))) (Z_of_nat (snd (x0, x1))))); auto.\napply H0; clear H0; intros;\nelim (H (Z_of_nat (fst x2)) (Z_of_nat (snd x2)) (Zle_0_nat (fst x2))\n(Zle_0_nat (snd x2)) H0); clear H; intros; elim H; clear H; intros;\nintuition; elim (Z_of_nat_complete x3 H1); intros;\nelim (Z_of_nat_complete x4 H); intros; exists (x5, x6); simpl;\nrewrite H3 in H4; rewrite H5 in H4; intuition.\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/fermat4/Descent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6978189043383104}}
{"text": "(***************************************************************************\n* Safety for Simply Typed Lambda Calculus (CBV) - Definitions              *\n* Brian Aydemir & Arthur Charguéraud, July 2007                            *\n***************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibLN.\nImplicit Types x : var.\n\n(** Grammar of types. *)\n\nInductive typ : Set :=\n  | typ_var   : var -> typ\n  | typ_arrow : typ -> typ -> typ.\n\n(** Grammar of pre-terms. *)\n\nInductive trm : Set :=\n  | trm_bvar : nat -> trm\n  | trm_fvar : var -> trm\n  | trm_abs  : trm -> trm\n  | trm_app  : trm -> trm -> trm.\n\n(** Opening up abstractions *)\n\nFixpoint open_rec (k : nat) (u : trm) (t : trm) {struct t} : trm :=\n  match t with\n  | trm_bvar i    => If k = i then u else (trm_bvar i)\n  | trm_fvar x    => trm_fvar x\n  | trm_abs t1    => trm_abs (open_rec (S k) u t1)\n  | trm_app t1 t2 => trm_app (open_rec k u t1) (open_rec k u t2)\n  end.\n\nDefinition open t u := open_rec 0 u t.\n\nNotation \"{ k ~> u } t\" := (open_rec k u t) (at level 67).\nNotation \"t ^^ u\" := (open t u) (at level 67).\nNotation \"t ^ x\" := (open t (trm_fvar x)).\n\n(** Terms are locally-closed pre-terms *)\n\nInductive term : trm -> Prop :=\n  | term_var : forall x,\n      term (trm_fvar x)\n  | term_abs : forall L t1,\n      (forall x, x \\notin L -> term (t1 ^ x)) ->\n      term (trm_abs t1)\n  | term_app : forall t1 t2,\n      term t1 -> \n      term t2 -> \n      term (trm_app t1 t2).\n\n(** Environment is an associative list mapping variables to types. *)\n\nDefinition env := LibEnv.env typ.\n\n(** Typing relation *)\n\nReserved Notation \"E |= t ~: T\" (at level 69).\n\nInductive typing : env -> trm -> typ -> Prop :=\n  | typing_var : forall E x T,\n      ok E ->\n      binds x T E ->\n      E |= (trm_fvar x) ~: T\n  | typing_abs : forall L E U T t1,\n      (forall x, x \\notin L -> \n        (E & x ~ U) |= t1 ^ x ~: T) ->\n      E |= (trm_abs t1) ~: (typ_arrow U T)\n  | typing_app : forall S T E t1 t2,\n      E |= t1 ~: (typ_arrow S T) -> \n      E |= t2 ~: S ->\n      E |= (trm_app t1 t2) ~: T\n\nwhere \"E |= t ~: T\" := (typing E t T).\n\n(** Definition of values (only abstractions are values) *)\n\nInductive value : trm -> Prop :=\n  | value_abs : forall t1, \n      term (trm_abs t1) -> value (trm_abs t1).\n\n(** Reduction relation - one step in call-by-value *)\n\nInductive red : trm -> trm -> Prop :=\n  | red_beta : forall t1 t2,\n      term (trm_abs t1) ->\n      value t2 ->\n      red (trm_app (trm_abs t1) t2) (t1 ^^ t2)\n  | red_app_1 : forall t1 t1' t2,\n      term t2 ->\n      red t1 t1' ->\n      red (trm_app t1 t2) (trm_app t1' t2)\n  | red_app_2 : forall t1 t2 t2',\n      value t1 ->\n      red t2 t2' ->\n      red (trm_app t1 t2) (trm_app t1 t2').\n\nNotation \"t --> t'\" := (red t t') (at level 68).\n\n(** Goal is to prove preservation and progress *)\n\nDefinition preservation := forall E t t' T,\n  E |= t ~: T ->\n  t --> t' ->\n  E |= t' ~: T.\n\nDefinition progress := forall t T, \n  empty |= t ~: T ->\n     value t \n  \\/ exists t', t --> t'.\n\n", "meta": {"author": "samuelgruetter", "repo": "typesafety-proofs-spring14", "sha": "45189a3af1815788eed81a4f4ef60f7c4b8a2c98", "save_path": "github-repos/coq/samuelgruetter-typesafety-proofs-spring14", "path": "github-repos/coq/samuelgruetter-typesafety-proofs-spring14/typesafety-proofs-spring14-45189a3af1815788eed81a4f4ef60f7c4b8a2c98/DotTransitivity/ln/STLC_Core_Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.697818901613111}}
{"text": "From Coq Require Import NArith ZArith Lia.\n\nFrom EVM Require Import Logic2.\n\n(**************************************************************************)\n\nLemma N_ltb_lt_quad (a b c d: N):\n  ((a <? b)%N = (c <? d)%N) <-> ((a < b)%N <-> (c < d)%N).\nProof.\napply relation_quad; apply N.ltb_lt.\nQed.\n\nLemma Z_ltb_lt_quad (a b c d: Z):\n  ((a <? b)%Z = (c <? d)%Z) <-> ((a < b)%Z <-> (c < d)%Z).\nProof.\napply relation_quad; apply Z.ltb_lt.\nQed.\n\nLemma N_leb_le_quad (a b c d: N):\n  ((a <=? b)%N = (c <=? d)%N) <-> ((a <= b)%N <-> (c <= d)%N).\nProof.\napply relation_quad; apply N.leb_le.\nQed.\n\nLemma Z_leb_le_quad (a b c d: Z):\n  ((a <=? b)%Z = (c <=? d)%Z) <-> ((a <= b)%Z <-> (c <= d)%Z).\nProof.\napply relation_quad; apply Z.leb_le.\nQed.\n\nLemma N2Z_ltb (n m: N):\n  (n <? m)%N = (Z.of_N n <? Z.of_N m)%Z.\nProof.\napply (relation_quad N.ltb_lt Z.ltb_lt).\napply N2Z.inj_lt.\nQed.\n\nLemma N2Z_leb (n m: N):\n  (n <=? m)%N = (Z.of_N n <=? Z.of_N m)%Z.\nProof.\napply (relation_quad N.leb_le Z.leb_le).\napply N2Z.inj_le.\nQed.\n\n(**************************************************************************)\n\nLemma Z_shiftr_pow2 (n: Z) (B: (0 <= n)%Z):\n  Z.shiftr (2 ^ n) n = 1%Z.\nProof.\nrewrite (Z.shiftr_div_pow2 _ _ B).\napply Z.div_same.\nnow apply Z.pow_nonzero.\nQed.\n\nLemma Z_ltb_irrefl (n: Z):\n  (n <? n)%Z = false.\nProof.\nremember (n <? n)%Z as L.\ndestruct L; trivial.\nsymmetry in HeqL.\nrewrite Z.ltb_lt in HeqL.\napply Z.lt_irrefl in HeqL.\ncontradiction.\nQed.\n\nLemma N_ltb_irrefl (n: N):\n  (n <? n)%N = false.\nProof.\nremember (n <? n)%N as L.\ndestruct L; trivial.\nsymmetry in HeqL.\nrewrite N.ltb_lt in HeqL.\napply N.lt_irrefl in HeqL.\ncontradiction.\nQed.\n\n(**************************************************************************)\n\nLemma Z_land_pow2_shift (n m: Z) (BM: (0 <= m)%Z):\n  Z.land n (2 ^ m) = Z.shiftl (Z.land (Z.shiftr n m) 1) m.\nProof.\nrewrite<- (Z_shiftr_pow2 m BM).\nrewrite<- Z.shiftr_land.\nrewrite<- (Z.ldiff_ones_r _ _ BM).\nrewrite Z.ldiff_land.\nrewrite<- Z.land_assoc.\nf_equal.\napply Z.bits_inj'. intros k Bk.\nrewrite Z.land_spec.\nrewrite (Z.lnot_spec _ _ Bk).\nrewrite (Z.testbit_ones _ _ BM).\nrewrite (Z.pow2_bits_eqb _ _ BM).\nrewrite<- Z.leb_le in Bk.\nrewrite Bk.\nrewrite Bool.andb_true_l.\nremember (m =? k)%Z as MK. symmetry in HeqMK.\ndestruct MK. \n{\n  rewrite Z.eqb_eq in HeqMK. subst.\n  now rewrite Z_ltb_irrefl.\n}\ntrivial.\nQed.\n\nLemma Z_mul_pos_iff_l (n m: Z) (BM: (0 < m)%Z):\n  (0 < n)%Z <-> (0 < n * m)%Z.\nProof.\nsplit. { intro. apply Z.mul_pos_pos; assumption. }\napply (Z.mul_pos_cancel_r _ _ BM).\nQed.\n\nLemma Z_mul_pos_iff_r (n m: Z) (BN: (0 < n)%Z):\n  (0 < m)%Z <-> (0 < n * m)%Z.\nProof.\nsplit. { apply (Z.mul_pos_pos _ _ BN). }\napply (Z.mul_pos_cancel_l _ _ BN).\nQed.\n\nLemma Z_shiftl_pos_iff (n m: Z) (BM: (0 <= m)%Z):\n (0 < n)%Z <-> (0 < Z.shiftl n m)%Z.\nProof.\nrewrite (Z.shiftl_mul_pow2 _ _ BM).\napply Z_mul_pos_iff_l.\napply Z.pow_pos_nonneg.\n{ rewrite<- Z.ltb_lt. trivial. }\nassumption.\nQed.\n\nLemma Z_odd_land_1 (n: Z) (B: (0 <= n)%Z):\n  Z.odd n = (0 <? Z.land n 1)%Z.\nProof.\ndestruct n; now try destruct p.\nQed.\n\nLemma Z_testbit_alt (n m: Z) (BN: (0 <= n)%Z) (BM: (0 <= m)%Z):\n  Z.testbit n m = (0 <? Z.land n (2 ^ m))%Z.\nProof.\nrewrite (Z_land_pow2_shift _ _ BM).\nassert (Q: forall x, ((0 <? Z.shiftl x m) = (0 <? x))%Z).\n{\n  intro x.\n  rewrite Z_ltb_lt_quad.\n  symmetry.\n  apply Z_shiftl_pos_iff.\n  assumption.\n}\nrewrite Q. clear Q.\nrewrite Z.testbit_odd.\napply Z_odd_land_1.\napply Z.shiftr_nonneg.\nassumption.\nQed.\n\nLemma Z_testbit_high (a n: Z)\n                      (B: (0 <= n)%Z)\n                      (A: (0 <= a < 2 ^ n)%Z):\n  Z.testbit a n = false.\nProof.\nrewrite<- (Z.mod_small a (2 ^ n)%Z A).\napply Z.mod_pow2_bits_high.\nsplit. { assumption. }\napply Z.le_refl.\nQed.\n\n(**************************************************************************)\n\nLemma Z_to_N_land (x y: Z) (BX: (0 <= x)%Z) (BY: (0 <= y)%Z):\n  Z.to_N (Z.land x y) = N.land (Z.to_N x) (Z.to_N y).\nProof.\napply N.bits_inj. intro n.\nrewrite N.land_spec.\nremember (Z.of_N n) as m.\nassert (NM: n = Z.to_N m).\n{ subst m. symmetry. apply N2Z.id. }\nrepeat rewrite NM.\nassert (BM: (0 <= m)%Z).\n{ subst. apply N2Z.is_nonneg. }\nrepeat rewrite<- Z2N.inj_testbit; try assumption.\nrepeat rewrite Z2N.id; try assumption.\n{ apply Z.land_spec. }\nrewrite Z.land_nonneg. tauto.\nQed.\n\n\nLemma N_to_Z_land (x y: N):\n  Z.of_N (N.land x y) = Z.land (Z.of_N x) (Z.of_N y).\nProof.\nrewrite<- (Z2N.id (Z.land (Z.of_N x) (Z.of_N y))).\n{\n  f_equal.\n  rewrite Z_to_N_land; try apply N2Z.is_nonneg.\n  repeat rewrite N2Z.id.\n  trivial.\n}\napply Z.land_nonneg. left. apply N2Z.is_nonneg.\nQed.\n\nLemma Z_to_N_lor (x y: Z) (BX: (0 <= x)%Z) (BY: (0 <= y)%Z):\n  Z.to_N (Z.lor x y) = N.lor (Z.to_N x) (Z.to_N y).\nProof.\napply N.bits_inj. intro n.\nrewrite N.lor_spec.\nremember (Z.of_N n) as m.\nassert (NM: n = Z.to_N m).\n{ subst m. symmetry. apply N2Z.id. }\nrepeat rewrite NM.\nassert (BM: (0 <= m)%Z).\n{ subst. apply N2Z.is_nonneg. }\nrepeat rewrite<- Z2N.inj_testbit; try assumption.\nrepeat rewrite Z2N.id; try assumption.\n{ apply Z.lor_spec. }\nrewrite Z.lor_nonneg. tauto.\nQed.\n\nLemma N_to_Z_lor (x y: N):\n  Z.of_N (N.lor x y) = Z.lor (Z.of_N x) (Z.of_N y).\nProof.\nrewrite<- (Z2N.id (Z.lor (Z.of_N x) (Z.of_N y))).\n{\n  f_equal.\n  rewrite Z_to_N_lor; try apply N2Z.is_nonneg.\n  repeat rewrite N2Z.id.\n  trivial.\n}\napply Z.lor_nonneg. split; apply N2Z.is_nonneg.\nQed.\n\nLemma Z_to_N_lxor (x y: Z) (BX: (0 <= x)%Z) (BY: (0 <= y)%Z):\n  Z.to_N (Z.lxor x y) = N.lxor (Z.to_N x) (Z.to_N y).\nProof.\napply N.bits_inj. intro n.\nrewrite N.lxor_spec.\nremember (Z.of_N n) as m.\nassert (NM: n = Z.to_N m).\n{ subst m. symmetry. apply N2Z.id. }\nrepeat rewrite NM.\nassert (BM: (0 <= m)%Z).\n{ subst. apply N2Z.is_nonneg. }\nrepeat rewrite<- Z2N.inj_testbit; try assumption.\nrepeat rewrite Z2N.id; try assumption.\n{ apply Z.lxor_spec. }\nrewrite Z.lxor_nonneg. tauto.\nQed.\n\nLemma N_to_Z_lxor (x y: N):\n  Z.of_N (N.lxor x y) = Z.lxor (Z.of_N x) (Z.of_N y).\nProof.\nrewrite<- (Z2N.id (Z.lxor (Z.of_N x) (Z.of_N y))).\n{\n  f_equal.\n  rewrite Z_to_N_lxor; try apply N2Z.is_nonneg.\n  repeat rewrite N2Z.id.\n  trivial.\n}\napply Z.lxor_nonneg. split; intro; apply N2Z.is_nonneg.\nQed.\n\n(**************************************************************************)\n\nLemma N_testbit_alt (n m: N):\n  N.testbit n m = (0 <? N.land n (2 ^ m))%N.\nProof.\nrewrite<- Z.testbit_of_N.\nreplace (0 <? N.land n (2 ^ m))%N with (0 <? Z.land (Z.of_N n) (2 ^ (Z.of_N m)))%Z.\n2:{\n  rewrite N2Z_ltb.\n  rewrite N_to_Z_land.\n  cbn.\n  repeat f_equal.\n  rewrite N2Z.inj_pow.\n  trivial.\n}\napply Z_testbit_alt; apply N2Z.is_nonneg.\nQed.\n\n(**************************************************************************)\n\nDefinition N_0_lt_pow2 (n: N):\n  (0 < 2 ^ n)%N.\nProof.\ncase (N.eq_0_gt_0_cases (2 ^ n)); intro; try assumption.\napply N.pow_nonzero in H. { contradiction. }\ndiscriminate.\nQed.\n\nDefinition Z_0_lt_pow2 (n: Z) (B: (0 <= n)%Z):\n  (0 < 2 ^ n)%Z.\nProof.\nassert (A := N_0_lt_pow2 (Z.to_N n)).\napply N2Z.inj_lt in A.\nrewrite N2Z.inj_pow in A.\ncbn in A.\nnow rewrite Z2N.id in A.\nQed.\n\nLemma N_ne_0_gt_0 (n: N):\n  n <> 0%N <-> (0 < n)%N.\nProof.\nsplit; intro H.\n{ assert (CN := N.eq_0_gt_0_cases n). tauto. }\ndestruct n. { now apply N.lt_irrefl in H. }\ndiscriminate.\nQed.\n\nLemma N_div_0_r (n: N):\n  (n / 0 = 0)%N.\nProof.\nnow destruct n.\nQed.\n\nLemma Z_div_0_r (n: Z):\n  (n / 0 = 0)%Z.\nProof.\nnow destruct n.\nQed.\n\nLemma N_div_le (n: N) (d: N):\n  (n / d <= n)%N.\nProof.\nassert (CN := N.eq_0_gt_0_cases n).\nassert (CD := N.eq_0_gt_0_cases d).\ncase CN; intro. { subst. cbn. apply N.le_refl. }\ncase CD; intro. { subst. rewrite N_div_0_r. now apply N.lt_le_incl. }\nassert (D: N.succ (N.pred d) = d).\n{ apply N.succ_pred_pos. assumption. }\nremember (N.pred d) as k. clear Heqk. subst.\nassert (CK := N.eq_0_gt_0_cases k).\ncase CK; intro. { subst. cbn. now rewrite N.div_1_r. }\napply N.lt_le_incl.\napply N.div_lt. { assumption. }\nnow apply N.lt_pred_lt_succ.\nQed.\n\nLemma Z_div_nonneg (a b: Z)\n                    (A: (0 <= a)%Z)\n                    (B: (0 <= b)%Z):\n  (0 <= a / b)%Z.\nProof.\ndestruct b. { rewrite Zdiv_0_r. apply Z.le_refl. }\n{ apply Z.div_pos; easy. }\neasy.\nQed.\n\nLemma Z_abs_div_le (a b: Z):\n  (Z.abs a / Z.abs b <= Z.abs a)%Z.\nProof.\nassert(A := Z.abs_nonneg a).\nassert(B := Z.abs_nonneg b).\napply Z2N.inj_le. { now apply Z_div_nonneg. }\n{ assumption. }\nrewrite Z2N.inj_div; try assumption.\napply N_div_le.\nQed.\n\nLemma Z_abs_sgn (a b: Z):\n  Z.abs (Z.sgn a * b)%Z = match a with\n                          | 0%Z => 0%Z\n                          | _ => Z.abs b\n                          end.\nProof.\nnow destruct a, b.\nQed.\n\nLemma Z_sgn_abs (a: Z):\n  (Z.sgn a * Z.abs a)%Z = a.\nProof.\nnow destruct a.\nQed.\n\nLemma Z_add_nocarry_lor (a b: Z) (H: Z.land a b = 0%Z):\n  (a + b = Z.lor a b)%Z.\nProof.\nrewrite Z.add_nocarry_lxor by assumption.\napply Z.lxor_lor. assumption.\nQed.\n\nLemma Z_land_pow2_small (a b: Z) (A: (0 <= a < 2 ^ b)%Z) (B: (0 <= b)%Z):\n  Z.land a (2 ^ b) = 0%Z.\nProof.\nrewrite Arith2.Z_land_pow2_shift by tauto.\nreplace (Z.shiftr a b) with 0%Z. { cbn. apply Z.shiftl_0_l. }\nrewrite Z.shiftr_div_pow2 by tauto.\nsymmetry. apply Z.div_small. exact A.\nQed.\n\nLemma Z_testbit_flag_mul_pow2 (f: bool) (k: Z) (K: (0 <= k)%Z):\n  Z.testbit ((if f then 1 else 0) * 2 ^ k) k = f.\nProof.\ndestruct f.\n{ rewrite Z.mul_1_l. apply Z.pow2_bits_true. assumption. }\nrewrite Z.mul_0_l. apply Z.bits_0.\nQed.\n\n(* A version of Z.bits_above_log2 with a different bound. *)\nLemma Z_testbit_small (a n: Z) (A: (0 <= a)%Z)\n                               (B: (a < 2 ^ n)%Z):\n  Z.testbit a n = false.\nProof.\ndestruct a. { apply Z.testbit_0_l. }\n{ apply Z.bits_above_log2. trivial. now apply Z.log2_lt_pow2. }\nexfalso. rewrite<- Z.leb_le in A. cbn in A. discriminate.\nQed.\n\n(**************************************************************************)\n\nLemma Z_pos_ne_0 (a: positive):\n  Z.pos a <> 0%Z.\nProof.\ndiscriminate.\nQed.\n\nLemma Z_0_lt_pos (a: positive):\n  (0 < Z.pos a)%Z.\nProof.\nrewrite<- Z.ltb_lt.\ntrivial.\nQed.\n\nLemma Z_ceiling_via_floor (a b: Z) (B: (0 <= b)%Z):\n  (- ((- a) / b) = (a + b - 1) / b)%Z.\nProof.\ndestruct b as [|b|b]. { now repeat rewrite Z_div_0_r. }\n{\n  assert (D := Z.div_mod (-a) (Z.pos b) (Z_pos_ne_0 b)).\n  assert (E := Z.div_mod (a + Z.pos b - 1) (Z.pos b) (Z_pos_ne_0 b)).\n  assert (P := Z.mod_pos_bound (-a) (Z.pos b) (Z_0_lt_pos b)).\n  assert (Q := Z.mod_pos_bound (a + Z.pos b - 1) (Z.pos b) (Z_0_lt_pos b)).\n  nia.\n}\nrewrite<- Z.leb_le in B. discriminate.\nQed.\n\n(**************************************************************************)\n\nLemma Z_land_lxor_distr_l (a b c: Z):\n  Z.land (Z.lxor a b) c = Z.lxor (Z.land a c) (Z.land b c).\nProof.\napply Z.bits_inj. intro.\nrepeat (rewrite Z.land_spec || rewrite Z.lxor_spec).\ndestruct (Z.testbit a n); destruct (Z.testbit b n); destruct (Z.testbit c n); easy.\nQed.\n\nLemma Z_land_lxor_distr_r (a b c: Z):\n  Z.land a (Z.lxor b c) = Z.lxor (Z.land a b) (Z.land a c).\nProof.\napply Z.bits_inj. intro.\nrepeat (rewrite Z.land_spec || rewrite Z.lxor_spec).\ndestruct (Z.testbit a n); destruct (Z.testbit b n); destruct (Z.testbit c n); easy.\nQed.\n\n(**************************************************************************)\n\n(* This is a version of Z.log2_lt_pow2 but a can be 0 and b cannot. *)\nLemma Z_log2_lt_pow2 (a b: Z) (BA: (0 <= a)%Z) (BB: (0 < b)%Z):\n    (a < 2 ^ b <-> Z.log2 a < b)%Z.\nProof.\ndestruct a.\n{\n  cbn. assert (P: (0 < 2 ^ b)%Z). apply Z_0_lt_pow2. { apply Z.lt_le_incl. assumption. }\n  tauto.\n}\n{ apply Z.log2_lt_pow2. rewrite<- Z.ltb_lt. trivial. }\nrewrite<- Z.leb_le in BA. discriminate.\nQed.\n\n(**************************************************************************)\n\nLemma Z_mod_add_l (a b c m: Z)\n                  (H: (b mod m = c mod m)%Z):\n  ((a + b) mod m = (a + c) mod m)%Z.\nProof.\nrewrite<- (Zplus_mod_idemp_r b a).\nrewrite<- (Zplus_mod_idemp_r c a).\nrewrite H.\ntrivial.\nQed.\n\nLemma Z_mod_add_r (a b c m: Z)\n                  (H: (a mod m = b mod m)%Z):\n  ((a + c) mod m = (b + c) mod m)%Z.\nProof.\nrewrite<- (Zplus_mod_idemp_l a c).\nrewrite<- (Zplus_mod_idemp_l b c).\nrewrite H.\ntrivial.\nQed.\n\n(**************************************************************************)\n\nLemma Nat2N_inj_div (a b: nat):\n  N.of_nat (a / b) = (N.of_nat a / N.of_nat b)%N.\nProof.\ndestruct b. { cbn. now rewrite N_div_0_r. }\nassert (BNZ: S b <> 0) by discriminate.\nassert (D := Nat.div_mod a (S b) BNZ).\nremember (a / S b) as q.\nremember (a mod S b) as r.\napply N.div_unique with (r := N.of_nat r).\n{\n  unfold N.lt.\n  rewrite<- Nat2N.inj_compare.\n  apply Nat.compare_lt_iff.\n  subst. apply (Nat.mod_upper_bound _ _ BNZ).\n}\nrewrite<- Nat2N.inj_mul.\nrewrite<- Nat2N.inj_add.\nnow rewrite D.\nQed.\n\nLemma Nat2N_inj_mod (a b: nat) (ok: b <> 0):\n  N.of_nat (a mod b) = (N.of_nat a mod N.of_nat b)%N.\nProof.\ndestruct b. { contradiction. }\nrewrite Nat.mod_eq by discriminate.\nrewrite Nat2N.inj_sub.\nrewrite Nat2N.inj_mul.\nrewrite Nat2N_inj_div.\nsymmetry. apply N.mod_eq.\ndiscriminate.\nQed.\n\n(**************************************************************************)\n(** This is a strenghtening of Pos.size_nat_monotone from [p < q] to [p <= q]. *)\nLemma Pos_size_nat_monotone (p q: positive) (LE: (p <= q)%positive):\n  (Pos.size_nat p <= Pos.size_nat q)%nat.\nProof.\nremember (Pos.compare p q) as cmp. symmetry in Heqcmp. destruct cmp.\n{ apply Pos.compare_eq in Heqcmp. subst. apply Nat.le_refl. }\n{ apply Pos.size_nat_monotone. exact Heqcmp. }\ncontradiction.\nQed.", "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/Arith2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6978166799887304}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf1 : natural) : natural :=\n  plus lf1 x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj207_coqofml_wH2Jw1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.6978166706481655}}
{"text": "(* Library for Finite Sets *)\nRequire Import List Basics.\n\nDefinition set := list. \n\nFixpoint subset {A} (l : list A) (m: list A) : Prop := match l with\n  | nil => True\n  | cons x xs => In x m /\\ subset xs m\n  end.\n\nDefinition subset' {A} (l m : list A) : Prop := forall a, In a l -> In a m.\n\n\n", "meta": {"author": "stelleg", "repo": "cem_coq", "sha": "3487124d10e2bd4bb9328e4cb5e26d4e96f62387", "save_path": "github-repos/coq/stelleg-cem_coq", "path": "github-repos/coq/stelleg-cem_coq/cem_coq-3487124d10e2bd4bb9328e4cb5e26d4e96f62387/set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314738181874, "lm_q2_score": 0.7879312006227323, "lm_q1q2_score": 0.6978166704748443}}
{"text": "Require Import Coq.Setoids.Setoid.\nRequire Import New.Ring.\n\nLemma add_zero_left {A}\n  {srops : SemiRingOps A}\n  {sra : SemiRingNoAssoc A} :\n    forall a : A, 0 + a = a.\nProof.\n  intro.\n  rewrite add_comm.\n  apply add_zero_right.\nQed.\n\nLemma mul_zero_left {A}\n  {srops : SemiRingOps A}\n  {sra : SemiRingNoAssoc A} :\n    forall a : A, 0 * a = 0.\nProof.\n  intro.\n  rewrite mul_comm.\n  apply mul_zero_right.\nQed.\n\nLemma mul_one_left {A}\n  {srops : SemiRingOps A}\n  {sra : SemiRingNoAssoc A} :\n    forall a : A, 1 * a = a.\nProof.\n  intro.\n  rewrite mul_comm.\n  apply mul_one_right.\nQed.\n\nLemma neg_inv {A}\n  {rops : RingOps A}\n  {ra : Ring A} :\n    forall a : A, - -a = a.\nProof.\n  intro.\n  rewrite <- add_zero_right at 1.\n  rewrite <- (sub_zero a).\n  rewrite sub_def.\n  rewrite add_comm.\n  rewrite <- add_assoc.\n  rewrite <- sub_def.\n  rewrite sub_zero.\n  apply add_zero_right.\nQed.\n\nLemma zero_self_inv {A} {rops : RingOps A} {rna : RingNoAssoc A} : -0 = 0.\nProof.\n  rewrite <- add_zero_right at 1.\n  rewrite add_comm.\n  rewrite <- sub_def.\n  apply sub_zero.\nQed.\n\nLemma neg_sub {A} {rops : RingOps A} {rna : RingNoAssoc A} :\n  forall a b : A, -(a - b) = (-a) - (-b).\nProof.\n  intros.\n  rewrite 2 sub_def.\n  apply neg_add.\nQed.\n\nLemma sub_mul_dist {A} {rops : RingOps A} {rna : RingNoAssoc A} :\n  forall a b c : A, a * (b - c) = (a * b) - (a * c).\nProof.\n  intros.\n  rewrite 2! sub_def.\n  rewrite add_mul_dist.\n  rewrite neg_mul.\n  reflexivity.\nQed.\n\nLemma add_mul_dist_right {A} {srops : SemiRingOps A} {sra : SemiRingNoAssoc A} :\n  forall a b c : A, (b + c) * a = (b * a) + (c * a).\nProof.\n  intros.\n  rewrite mul_comm at 1.\n  rewrite add_mul_dist.\n  f_equal.\n  apply mul_comm.\n  apply mul_comm.\nQed.\n\nLemma sub_mul_dist_right {A} {srops : RingOps A} {sra : RingNoAssoc A} :\n  forall a b c : A, (b - c) * a = (b * a) - (c * a).\nProof.\n  intros.\n  rewrite mul_comm at 1.\n  rewrite sub_mul_dist.\n  f_equal.\n  apply mul_comm.\n  apply mul_comm.\nQed.\n\nLemma neg_mul_left {A} {srops : RingOps A} {sra : RingNoAssoc A} :\n  forall a b : A, -(a * b) = (-a) * b.\nProof.\n  intros.\n  rewrite mul_comm.\n  rewrite neg_mul.\n  apply mul_comm.\nQed.", "meta": {"author": "emc2", "repo": "state-space-model", "sha": "d4d34e8c5cb2e93bfe141313f1c7f8a94805dfb6", "save_path": "github-repos/coq/emc2-state-space-model", "path": "github-repos/coq/emc2-state-space-model/state-space-model-d4d34e8c5cb2e93bfe141313f1c7f8a94805dfb6/New/RingTheorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.6978166703015233}}
{"text": "(** * 超絶技巧演習問題 - Coq *)\n\nRequire Import Coq.Init.Prelude Coq.Init.Nat.\n\nOpen Scope nat_scope.\n\n(** フェルマーの最終定理 *)\n\nDefinition felmat\n  : forall n : nat, 2 < n -> ~ exists x y z, 0 < x /\\ 0 < y /\\ 0 < z /\\ x ^ n + y ^ n = z ^ n.\nProof.\n  (* [Admitted] を [Qed] に取り換えて、この空欄を埋めよ *)\nAdmitted.\n\n(** カタラン予想 *)\n\nDefinition catalanic a b x y := 1 < a /\\ 1 < b /\\ 1 < x /\\ 1 < y /\\ x ^ a = 1 + y ^ b.\n\nDefinition catalan\n  : forall a b x y, catalanic a b x y -> x = 3 /\\ a = 2 /\\ y = 2 /\\ b = 3.\nProof.\n  (* [Admitted] を [Qed] に取り換えて、この空欄を埋めよ *)\nAdmitted.\n\n(** バウデットの予想 *)\nDefinition baudetic (P : nat -> bool) a b c n := forall p, p < n -> P (a + b * p) = c.\n\nDefinition baudet\n  : forall P, exists c, forall n, exists a b, baudetic P a b c n.\nProof.\n  (* [Admitted] を [Qed] に取り換えて、この空欄を埋めよ *)\nAdmitted.\n\n(** コラッツの問題 *)\nDefinition collatzic n := if even n then div2 n else n * 3 + 1.\n\nDefinition collatz\n  : forall n, n <> 0 -> exists p, iter p collatzic n = 1.\nProof.\n  (* [Admitted] を [Qed] に取り換えて、この空欄を埋めよ *)\nAdmitted.\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/Transcendental.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.697795900228727}}
{"text": "(**\ncall/ccと古典論理\n======\n2015/08/22\n\n@suharahiromichi\n\n# はじめに\n\n継続は古典論理との意味をもって語られることが多いけれど、\n実は ``call/cc`` の型（p型を返すとする）、\n``((p→void)→p)→p`` が、Curry-Howard同型から、\n``forall P, ((P -> False) -> P) -> P)`` という論理式にみなせる、\nということだ（からだとおもう）。\n\nそれがどうして古典論理と関係するかというと、\nこの論理式と排中律や二重否定除去定理が同値だからである。\n\nここでは、実際にその証明をしてみたい。\n\n証明はSSReflectを使うが、あまり省略しないようにした。\n*)\n\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq.\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n(**\n``call/cc``と排中律が同値であるこを証明する。\n *)\nGoal (forall (P : Prop), ((P -> False) -> P) -> P) <->\n(forall (P : Prop), P \\/ ~P).\nProof.\n  split.\n  - move=> Callcc P.\n    apply: (Callcc (P \\/ ~P)).\n    move=> H.\n    right=> H1.\n    apply: H.\n    left.\n    by apply: H1.\n  - move=> Em P.\n    case: (Em P)=> HP H1.\n    + by apply: HP.\n    + apply: H1.\n      by apply: HP.\nQed.  \n\n(**\n``call/cc``と二重否定除去が同値であることを証明する。\n *)\nGoal (forall (P : Prop), ((P -> False) -> P) -> P) <->\n(forall (P : Prop), ~ ~ P -> P).\nProof.\n  split.\n  - move=> Callcc P.\n    apply: Callcc => H1 H2.\n    exfalso.\n    apply: H2 => HP.\n    apply: H1 => H3.\n    by apply: HP.\n  - move=> Dn P H1.\n    apply: (Dn P) => HnP.\n    apply HnP.\n    apply H1 => HP.\n    apply HnP.\n    by apply HP.\nQed.\n\n(**\n``call/cc``とパースの論理式が同値であるこを証明する。\n *)\nGoal (forall (P : Prop), ((P -> False) -> P) -> P) <->\n(forall (P Q : Prop), ((P -> Q) -> P) -> P).\nProof.\n  split.\n  - move=> Callcc P Q H1.\n    apply: Callcc => H2.\n    apply: H1 => HP.\n    exfalso.\n    apply: H2.\n    by apply: HP.\n  - move=> Pe P.\n    by apply (Pe P False).\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/ssr/ssr_callcc_classic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6977784216772763}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (x : natural) (y : natural) (lf2 : natural)\n  : natural := plus (Succ Zero) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_commut/goal33conj187_coqofml_x5Dhkv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.69776922673896}}
{"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\n(* No helper lemma required *)\nTheorem theorem0 : forall (x : Lst) (y : Lst), eq (len (append x y)) (plus (len x) (len y)).\nProof.\n  intros. induction x.\n  - simpl. rewrite IHx. reflexivity.\n  - reflexivity.\nQed.\n\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6977468498836095}}
{"text": "(** * ProofObjects (Объекты-Доказательства): Соответствие Curry-Howard *)\n\n(** \"_Алгоритмы это вычислитльное содержание доказательств_.\"  --Robert Harper *)\n\nRequire Export IndProp.\n\n(** Мы видели, Coq механизмы для _программировния_, используящие\n    индуктивные типы данных вроде [nat] или [list] и функций над этими\n    типами, а для _доказательства_ свойств этих программ, использования\n    индуктивных пропозиции (вроде [ev]), импликации, кванторов универсальности\n    , и другие. До сих пор, мы в основном использовали эти механизмы\n    так будто они довольно различны, и для многих целей это хороший\n    способ смотреть на вещи. Но мы также видели признаки того, что\n    программирование и доказательство в Coq тесно связаны.\n    Например, ключевое слово [Inductive] было использовано как для\n    декларирования типов, так и пропозиций. [->] используется как\n    для описания типа функций на данных, так и логическую импликацию.\n    Это не просто синтаксическое совпадение! На самом деле, программы\n    и доказательства в Coq практически одно и тоже. В этой главе\n    мы изучим как это работает.\n\n    Мы уже увидели фундаментальную идею: доказуемость в Coq \n    представляется через конкретное _свидетельство_.  Когда\n    мы строим доказательство базовой пропозиции, мы на самом деле\n    строим дерево свидетельства, которое может быть рассмотренно\n    как структура данных.\n\n    Если пропозиция есть импликация вроде [A -> B], тогда его доказательством\n    будет _трансформер_ свидетельств: рецепт для конвертации свидетельства\n    A в свидетельство для B. Таким образом, на фундаментальном уровне,\n    доказательства это просто программы для манипулирования свидетельствами. *)\n\n(** Вопрос: Если свидетельство есть данные, чем тогда являются сами пропозиции?\n\n    Ответы: Они являются типами!\n\n    Взгляните снова на формальное определение свойства [ev].  *)\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(** Предположим, что мы ввели альтернативное произношение для \"[:]\".\n    Вместо \"имеет тип\", мы говорим \"есть доказательство для\". Например,\n    вторая строчка в определении [ev] декларирует что [ev_0 : ev\n    0].  Вместо \"[ev_0] имеет тип [ev 0],\" мы можем сказать что \"[ev_0]\n    есть доказательство для [ev 0].\" *)\n\n(** Такое отношение между типами и пропозициями -- [:] как \"имеет тип\"\n    и [:] как \"доказательство для\" или \"свидетельство для\" -- называется\n    _соответствием Curry-Howard_. Оно предлагает глубокую связь\n    между миром логики и миром вычислений:\n\n                 пропозиции            ~  типы\n                 доказательства        ~  значения данных\n\n    Смотрите [Wadler 2015] для короткой истории и современной экспозиции.\n\n    Многие полезные идеи следуют из данной связи. Для начала, она\n    дает естественную интерпретацию типа для конструктора [ev_SS]: *)\n\nCheck ev_SS.\n(* ===> ev_SS : forall n,\n                  ev n ->\n                  ev (S (S n)) *)\n\n(** Оно может быть прочтено как \"[ev_SS] есть конструктор, который\n    берет два аргумента -- число [n] и свидетельство для пропозиции [ev\n    n] -- а затем производит свидетельство для пропозиции [ev (S (S n))].\" *)\n\n(** Теперь давайте снова взглянем на предыдущее доказательство использующее\n    [ev]. *)\n\nTheorem ev_4 : ev 4.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\n(** Как и в случае обычных значений данных и функций, мы можем использовать\n    команду [Print] для того чтобы увидеть _объект доказательство_ получаемый\n    из данного скрипта доказательства. *)\n\nPrint ev_4.\n(* ===> ev_4 = ev_SS 2 (ev_SS 0 ev_0)\n     : ev 4  *)\n\n(** Более того, мы также можем записать данный объект доказательства\n    _напрямую_, без необходимости для отдельного скрипта докозательства: *)\n\nCheck (ev_SS 2 (ev_SS 0 ev_0)).\n(* ===> ev 4 *)\n\n(** Выраэение [ev_SS 2 (ev_SS 0 ev_0)] может быть рассмотренно как\n    инстанциация параметризованного конструктора [ev_SS] со специфическими\n    аргументами [2] и [0] плюс соответствующими объектами доказательств\n    для предпосылок [ev 2] и [ev 0].  Альтернативно, мы можем думать\n    о [ev_SS] как о примитивном \"конструкторе свидетельств\", который\n    будучи применен к заданному числу, хочет в дальнейшем быть применен\n    к свидетельству того, что данное число четно; его тип,\n\n      forall n, ev n -> ev (S (S n)),\n\n    выражает эту функциональнсть, таким же способом полиморфный тип\n    [forall X, list X] выражает факт того, что конструктор\n    [nil] может быть задуман как функция из типов в пустые списки\n    с элементами этих типов. *)\n\n(** Вы можете вспомнить (как было показано в главе [Logic]) что можно\n    использовать синтаксис применения функции для инстанциации\n    переменных за кванторами всеобщности в леммах, а также предоставлять\n    свидетельство для тех предположений, что леммы требуют. Например: *)\n\nTheorem ev_4': ev 4.\nProof.\n  apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\n\n(** Мы теперь можем увидеть, что данное свойство есть тривиальное\n    следствия статуса который Coq предоставляют доказательствам и пропозициям:\n    Леммы и гипотезы могут быть объединены в выражениях (т.е.\n    объекты доказательств) следуя тем же основным правилам что\n    используются для программ. *)\n\n(* ################################################################# *)\n(** * Скрипты Доказательств *)\n\n(** _Объекты доказательств_ которые мы обсуждали лежат в основе\n    того как работает Coq. Когда Coq следует скрипту доказательства, \n    внутри него последовательно строится объект доказательства -- терм\n    чьим типом является доказуемая пропозиция. Тактики между\n    [Proof] и [Qed] указывают как построить терм требуемого типа. Чтобы \n    увидеть данный процесс в действии, используем команду\n    [Show Proof] для демонстрации текущего состояния дерева\n    доказательства в различных точках следующего доказательства\n    тактиками. *)\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(** В каждый заданный момент, Coq построил терм с некоторыми\n    \"пропусками\" (указанымми с помощью [?1], [?2], и так далее), и он знает\n    какой тип свидетельства требуется для каждого пропуска.  *)\n\n(** Каждый из пропусков соответствует подцели, и доказательство завершенно\n    когда больше нет подцелей. В этой точке, свидетельство, что мы\n    построили, хранится в глобальном контексте под именем заданным\n    командой [Theorem]. *)\n\n(** Доказательство тактиками полезно и удобно, но оно не обязательно:\n    в принципе, мы всегда можем построить требуемое свидетельство\n    руками, как показано сверху. Затем мы можем использовать [Definition]\n    (вместо [Theorem]) для задания глобального имени напрямую для\n    построенного свидетельства. *)\n\nDefinition ev_4''' : ev 4 :=\n  ev_SS 2 (ev_SS 0 ev_0).\n\n(** Все эти различные пути построения доказательств приводят точно к \n    тем же самым свидетельствам сохраненным в глобальном окружении. *)\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(** **** Упражнение: 1 звездочка (eight_is_even)  *)\n(** Задайте доказательство тактиками, а также объект доказательства того\n    что [ev 8]. *)\n\nTheorem ev_8 : ev 8.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nDefinition ev_8' : ev 8 \n  (* ЗАМЕНИТЕ ДАННУЮ СТРОКУ НА  := _ваше_определение_ . *) . Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Кванторы, Импликации, Функции *)\n\n(** В вычислительной вселенной Coq (где обитают структуры данных и программы\n    ), есть два вида значений со стрелками в своих типах: _конструкторы_ вводимые\n    типами определенными через [Inductive], и _функции_.\n\n    Аналогично, в логической вселенной Coq (в которой мы производим доказательства),\n    есть два способа предоставить свидетелюство для импликации:\n    конструкторы введеные [Inductive]-но определенными пропозициями,\n    и... функции!\n\n    Например, рассмотрим следующее утверждение: *)\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n H. simpl.\n  apply ev_SS.\n  apply ev_SS.\n  apply H.\nQed.\n\n(** Что является объектом доказательства соответствующим [ev_plus4]?\n\n    Мы ищем выражение чьим _типом_ было бы [forall n, ev n ->\n    ev (4 + n)] -- т.е., _функция_ которая берет два аргумента (одно\n    число и свидететельство) и возвращает также свидетельство!\n    Вот она: *)\n\nDefinition ev_plus4' : forall n, ev n -> ev (4 + n) :=\n  fun (n : nat) => fun (H : ev n) =>\n    ev_SS (S (S n)) (ev_SS n H).\n\nCheck ev_plus4'.\n(* ===> ev_plus4' : forall n : nat, ev n -> ev (4 + n) *)\n\n(** Вспомните что [fun n => blah] означает \"функция которая, имея [n],\n    производит [blah],\" и Coq рассматривает [4 + n] и [S (S (S (S n)))]\n    как синонимы. Другой эквивалентный способ записать данное определение: *)\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(** Когда мы рассматриваем пропозицию, доказуемою через [ev_plus4] кк\n    тип функции, один аспект может показаться необычным. Тип\n    второго аргумента, [ev n], упоминает _значение_ первого аргумента\n    [n]. Хотя такие _зависимые типы_ не встречаются в обычных языках\n    программирования, они также могут быть полезны в программировании,\n    как это показывает последнии достижения в сообществе\n    функционального программирования.\n\n    Заметьте, что как импликация ([->]) так и кванторы всеобщности ([forall])\n    соответствуют функциям на свидетельства. На самом деле, они представляют\n    из себя одно и тоже: [->] есть просто сокращение для вырожденного случая\n    применения [forall], когда зависимость отсутствует, т.е. нет необходимости\n    предоставлять имя типу в левой стороне стрелки. *)\n\n(** Например, рассмотрим следующую пропозицию: *)\n\nDefinition ev_plus2 : Prop :=\n  forall n, forall (E : ev n), ev (n + 2).\n\n(** Терм доказательства населяющий данную пропозицию будет функцией от\n    двух аргументов: числа [n] и некоторого свидетельства [E] того, что [n]\n    четно. Но имя [E] для этого свидетельства не использовано в дальнейшем\n    нигде в выражении [ev_plus2], таким образом немного глупо придумывать\n    ему имя. Мы могли бы вместо этого записать все следующим образом,\n    используя пропуск [_] вместо настощего имени: *)\n\nDefinition ev_plus2' : Prop :=\n  forall n, forall (_ : ev n), ev (n + 2).\n\n(** Или, эквивалентно, мы можем записать его в более знакомой нотации: *)\n\nDefinition ev_plus2'' : Prop :=\n  forall n, ev n -> ev (n + 2).\n\n(** В целом, \"[P -> Q]\" есть просто синтаксический сахар для\n    \"[forall (_:P), Q]\". *)\n\n(* ################################################################# *)\n(** * Связки как Индуктивные Типы *)\n\n(** Индуктивные определения достаточно мощны чтобы выразить большинство\n    связок и кванторов, что мы уже видели. Действительно, только\n    квантор всеобщности (и таким образом импликация) встроенны Coq;\n    все остальные определены индуктивно. Мы изучим эти определения\n    в данной секции. *)\n\nModule Props.\n\n(** ** Конъюкция\n\n    Чтобы доказать что [P /\\ Q] справедливо, мы должны предоставить\n    свидетельство как для [P], так и для [Q]. Таким образом, имеет\n    смысл определить объект доказательства для [P/\\ Q] как состоящего\n    из пары двух доказательств: одного для [P] и другого\n    для [Q]. Это приводит к следующему определению. *)\n\nModule And.\n\nInductive and (P Q : Prop) : Prop :=\n| conj : P -> Q -> and P Q.\n\nEnd And.\n\n(** Заметьте сходство с определением типа [prod], предоставленного\n    в главе [Poly]; единственная разница лишь в том, что [prod] принимает\n    [Type] аргументы, когда [and] принимает [Prop] аргументы. *)\n\nPrint prod.\n(* ===>\n   Inductive prod (X Y : Type) : Type :=\n   | pair : X -> Y -> X * Y. *)\n\n(** Это должно прояснить, почему мы паттерны [destruct] и [intros] могут\n    быть использованы на конъюктивных гипотезах.  Анализ случаев позволяет\n    нам рассмотреть все возможные пути, которыми можно доказать [P /\\ Q] -- \n    здесь всего лишь один (конструктор [conj]).  Аналогично, тактика [split]\n    на самом деле работает для любой индуктивно определенной пропозиции\n    с только одним конструктором. В частности, она работает для [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(** Это показывает почему индуктивное определение [and] может быть\n    манипулировано тактиками как мы и делали. Мы также можем использовать\n    его для построения доказательств напрямуп, используя паттерн матчинг.\n    Например: *)\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(** **** Упражнение: 2 звездочки, дополнительное (conj_fact)  *)\n(** Посторйте объект доказательства демонстрирующий следующую пропозицию. *)\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R \n  (* ЗАМЕНИТЕ ДАННУЮ СТРОКУ НА   := _ваше определение_ . *). Admitted.\n(** [] *)\n\n(** ** Дизъюнкция\n\n    Индуктивное определение дизъюнкции использует два конструктора, два для\n    каждой части: *)\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(** Данная декларация объясняет поведение тактики [destruct] на\n    дизъюнктивной гипотезе, так как сгенерированные подцели соответствуют\n    форме конструкторов [or_introl] и [or_intror].\n\n    Опять же, мы можем также напрямую записать объекты доказательств для\n    теорем включающих [or], без обращения к тактикам. *)\n\n(** **** Упражнение: 2 звездочки, дополнительное (or_commut'')  *)\n(** Попробуйте записать явный объект доказательства для [or_commut] (без применения\n   [Print] чтобы увидеть уже готовое!). *)\n\nDefinition or_comm : forall P Q, P \\/ Q -> Q \\/ P \n(* ЗАМЕНИТЕ ЭТУ СТРОКУ НА   := _ваше определение_ . *). Admitted.    \n(** [] *)\n\n(** ** Квантор Существования\n\n    Для предоставления доказательства в случае квантора существования, мы\n    упаковываем свидетельство [x] вместе с доказательством того что [x] удовлетворяет\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(** Это стоило бы немного разъяснить. Основа определения состоит в\n    формирующем тип [ex] которое может быть использовано для построения\n    пропозиций в форме [ex P], где [P] само по себе есть _функция_ из \n    значений свидетельства типа [A] в пропозиции. Конструктор [ex_intro]\n    таким образом предоставляет способ построения доказательства для [ex P],\n    имея свидетельство [x] и доказательство [P x].\n\n    Более знакомая форма [exists x, P x] есть синтаксический сахар для\n    выражения включающего [ex]: *)\n\nCheck ex (fun n => ev n).\n(* ===> exists n : nat, ev n\n        : Prop *)\n\n(** Вот пример того как определять явно объект доказательства включающий [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(** **** Упражнение: 2 звездочки, дополнительное (ex_ev_Sn)  *)\n(** Завершите определение следующего объекта доказательства: *)\n\nDefinition ex_ev_Sn : ex (fun n => ev (S n)) \n  (* ЗАМЕНИТЕ ДАННУЮ СТРОКУ НА   := _ваше определение_ . *). Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** [True] и [False] *)\n\n(** Индуктивное определение пропозиции [True] просто: *)\n\nInductive True : Prop :=\n  I : True.\n\n(** Оно имеет один конструктор (так что все доказательства [True] одинаковы, \n    так что иметь доказательство [True] не очень информативно.) *)\n\n(** [False] аналогично прост -- действительно, настолько просто, что может\n    показаться синктаксически неверным на первый взгляд! *)\n\nInductive False : Prop :=.\n\n(** И да, [False] является индуктивным типом _без_ конструкторов --\n    т.е., не существует способа построить его доказательства. *)\n\nEnd Props.\n\n(* ################################################################# *)\n(** * Программирование с Тактиками *)\n\n(** Если мы может строить доказательства преоставляя явные термы, вместо\n    запуска скриптов с тактиками, то можно спросить а можем ли\n    мы строить _программы_ используя _тактики_ вместо явных термов.\n    Естественно, ответ положителен! *)\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(** Заметьте, что мы завершили [Definition] используя [.] вместо\n    [:=] с последующим термом. Это говорит Coq зйати в режим _скрипта\n    доказательства_ для построения объекта типа [nat -> nat]. Также, мы\n    завершаем доказательство с [Defined] вместо [Qed]; это делает определение\n    _прозрачным_ так что оно может быть использовано в вычислениях как\n    и нормально определенная функция.  ([Qed]-определенные объекты не\n    прозрачны для вычислений.)\n\n    Данное свойство в основном полезно для написания функция с\n    зависимыми типами, которые мы не будем особенно затрагивать\n    в данной книге. Но оно иллюстрирует всеобщность и \n    ортогональность основных идей в Coq. *)\n\n(* ################################################################# *)\n(** * Равенство *)\n\n(** Даже отношение равенства не встроено в Coq.  Оно имеет следующее\n    индуктивное определение.  (На самом деле, определение в стандарной\n    библиотеке есть небольшая вариация его, котораое предоставляет\n    принцип индукции слегка более удобный для применения.) *)\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(** Способ которым нужно думать о данном определении следующий, имея множество\n    [X], оно определяет _семейство_ пропозиций \"[x] равно [y],\" индексированных\n    парами значений ([x] и [y]) из [X]. Существует лишь один способ\n    предоставления свидетельства для каждого члена этого семейства:\n    применяя конструктор [eq_refl] к типу [X] и значению [x :\n    X] что производит доказательство того, что [x] равно [x]. *)\n\n(** **** Упражнение: 2 звездочки (leibniz_equality)  *)\n(** Индуктивное определение равенства соответствует _равенству по\n    Лейбницу_: под \"[x] и [y] равны\" мы понимаем, что каждое свойство [P]\n    справедливое для [x] также справедливо для\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  (* ЗАПОЛНИТЕ ЗДЕСЬ *)\nAdmitted.\n(** [] *)\n\n(** Мы можем использовать [eq_refl] для построения доказательства что,\n    например, [2 = 2]. Можем ли мы также использовать его для построения\n    доказательства того что [1 + 1 = 2]? Да, мы можем. Действительно,\n    это тоже самое доказательство! Причина, по которой Coq принимает тоже\n    доказательство в том что он счичает \"одинаковыми\" любые два терма которые\n    _взаимно конвертируемы_ согласно простому набору вычислительных правил.\n    Эти правила, которые похожи на те что используются [Compute], включают\n    вычисления применения функции, раскрытие определений, и упрощение [match]ей.  *)\n\nLemma four: 2 + 2 = 1 + 3.\nProof.\n  apply eq_refl.\nQed.\n\n(** Тактика [reflexivity] которая была использована для доказательства\n    равенств до сих пор есть просто сокращение для [apply refl_equal].\n\n    В доказательствах равенств основанных на тактиках, правила конвертации\n    обычно скрыты в использованиях [simpl] (либо явно, либо неявно\n    в других тактиках как [reflexivity]). Но бы можете увидеть их\n    напрямую в работе в следующих явных объектах доказательств: *)\n\nDefinition four' : 2 + 2 = 1 + 3 :=\n  eq_refl 4.\n\nDefinition singleton : forall (X:Set) (x:X), []++[x] = x::[]  :=\n  fun (X:Set) (x:X) => eq_refl [x].\n\n\nEnd MyEquality.\n\nDefinition quiz6 : exists x,  x + 3 = 4\n  := ex_intro (fun z => (z + 3 = 4)) 1 (refl_equal 4).\n\n(* ================================================================= *)\n(** ** Инверсия, Снова *)\n\n(** Мы видели применение [inversion] как в случае равенства, так и в случае\n    индуктивно определенных пропозиций. Теперь, когда мы увидели, что это\n    теже самые вещи, мы можем более детально изучить как ведет себя [inversion].\n\n    В целом, тактика [inversion]...\n\n    - берет гипотезу [H] чей тип [P] индуктивно определен и\n\n    - для каждого конструктора [C] в определении [P],\n\n      - генерирует новую подцель, в которой предполагает что [H] было\n        посторено с [C],\n\n      - добавляет аргументы (предпосылки) для [C] в контекст подцели как\n        дополнительные гипотезы,\n\n      - сравнивает заключение (тип результата) [C] с текущей целью\n        и вычисляет множество равенств которые должны иметь место\n        для того чтобы [C] было применимо,\n\n      - добавляет данные равенства в контекст (и, для удобства\n        переписывает их в цели), и\n\n      - если равенства не могут быть удовлетворены (т.е., они включают\n        вещи вроде [S n = O]), сразу разрешает подцель. *)\n\n(** _Пример_: Если мы инвертируем гипотезу построенную с помощью [or],\n   то есть два конструктора, так что генерируются две подцели. Заключение\n   (окончательный тип) конструктора ([P \\/ Q]) не ставит никаких ограничений\n   на форму [P] или [Q], так что мы не получаем дополнительных равенств\n   в контексте подцелей.\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   _Пример_: Если мы инвертируем гипотезу постронную с [eq], то у нас\n   опять всего лишь один конструктор, так что генерируется лишь одна подцель.\n   Теперь, форма конструктора [refl_equal] предоставляет нам дополнительную\n   информацию: она говорит нам что два аргумента [eq] должны быть одним и\n   тем же!  Тактика [inversion] добавлает данный факт в контекст. *)\n\n(** $Date: 2016-07-14 17:02:35 -0400 (Thu, 14 Jul 2016) $ *)\n\n", "meta": {"author": "karsar", "repo": "SF_Russian", "sha": "653657985d4134973a512cc897bf1793c6ebd378", "save_path": "github-repos/coq/karsar-SF_Russian", "path": "github-repos/coq/karsar-SF_Russian/SF_Russian-653657985d4134973a512cc897bf1793c6ebd378/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.8558511543206819, "lm_q1q2_score": 0.6977176670516322}}
{"text": "(*|\n##############################\nInduction principle for ``le``\n##############################\n\n:Link: https://stackoverflow.com/q/55196816\n|*)\n\n(*|\nQuestion\n********\n\nFor the inductive type ``nat``, the generated induction principle uses\nthe constructors ``O`` and ``S`` in its statement:\n|*)\n\nPrint nat. (* .unfold .no-in *)\nCheck nat_ind. (* .unfold .no-in *)\n\n(*|\nBut for ``le``, the generated statement does not uses the constructors\n``le_n`` and ``le_S``:\n|*)\n\nPrint le. (* .unfold .no-in *)\nCheck le_ind. (* .unfold .no-in *)\n\n(*|\nHowever it is possible to state and prove an induction principle\nfollowing the same shape as the one for ``nat``:\n|*)\n\nLemma le_ind' : forall n (P : forall m, le n m -> Prop),\n    P n (le_n n) ->\n    (forall m (p : le n m), P m p -> P (S m) (le_S n m p)) ->\n    forall m (p : le n m), P m p.\nProof.\n  fix H 6. intros. destruct p.\n  - apply H0.\n  - apply H1, H. apply H0. apply H1.\nQed.\n\n(*|\nI guess the generated one is more convenient. But how does Coq chooses\nthe shape for its generated induction principle? If there is any rule,\nI cannot find them in the reference manual. What about other proof\nassistants such as Agda?\n|*)\n\n(*|\nAnswer\n******\n\nYou can manually generate an induction principle for an inductive type\nby using the command ``Scheme`` (see the `documentation\n<https://coq.inria.fr/distrib/current/refman/user-extensions/proof-schemes.html#generation-of-induction-principles-with-scheme>`__).\n\nThe command comes in two flavours:\n\n- ``Scheme scheme := Induction for Sort Prop`` generates the standard\n  induction scheme.\n- ``Scheme scheme := Minimality for Sort Prop`` generates a simplified\n  induction scheme more suited to inductive predicates.\n\nIf you define an inductive type in ``Type``, the generated induction\nprinciple is of the first kind. If you define an inductive type in\n``Prop`` (i.e. an inductive predicate), the generated induction\nprinciple is of the second kind.\n\nTo obtain the induction principle that you want in the case of ``le``,\nyou can define it in ``Type``:\n|*)\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).\n\nCheck le_ind. (* .unfold *)\n\n(*|\nor you can manually ask Coq to generate the expected induction principle:\n|*)\n\nReset le. (* .none *)\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_ind. (* .unfold *)\n\nScheme le_ind2 := Induction for le Sort Prop.\nCheck le_ind2. (* .unfold *)\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/induction-principle-for-le.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973932, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.6977176642860321}}
{"text": "Require Export ArithRing.\n\nRequire Import XRbase.\nRequire Export XRpow_def.\nRequire Export XR_Ifp.\nRequire Export XRbasic_fun.\nRequire Export XR_sqr.\nRequire Export XSplitAbsolu.\nRequire Export XSplitRmult.\nRequire Export XArithProp.\nRequire Import Omega.\nRequire Import Zpower.\nLocal Open Scope nat_scope.\nLocal Open Scope XR_scope.\n\nLemma INR_fact_neq_0 : forall n:nat, INR (fact n) <> R0.\nProof.\n  intros n.\n  (* forall n, n <> 0 -> INR n <> 0 *)\n  apply not_O_INR. \n  (* forall n : nat, fact n <> 0 *)\n  apply fact_neq_0. \nQed.\n\nLocal Open Scope nat_scope.\nLemma fact_simpl : forall n:nat, fact (S n) = (S n * fact n).\nProof.\n  intro n. simpl. reflexivity.\nQed.\nLocal Close Scope nat_scope.\n\nLemma simpl_fact :\n  forall n:nat, / INR (fact (S n)) * / / INR (fact n) = / INR (S n).\nProof.\n  intro n.\n  rewrite fact_simpl.\n  rewrite Rinv_involutive.\n  rewrite mult_INR.\n  rewrite Rinv_mult_distr.\n  rewrite Rmult_assoc.\n  rewrite Rinv_l.\n  rewrite Rmult_1_r.\n  reflexivity.\n  apply INR_fact_neq_0.\n  rewrite S_INR.\n  apply tech_Rplus.\n  apply pos_INR.\n  apply Rlt_0_1.\n  apply INR_fact_neq_0.\n  apply INR_fact_neq_0.\nQed.\n\nInfix \"^\" := pow : XR_scope.\n\nLemma pow_O : forall x:R, x ^ 0 = R1.\nProof.\n  intro x.\n  simpl.\n  reflexivity.\nQed.\n\nLemma pow_1 : forall x:R, x ^ 1 = x.\nProof.\n  intro x.\n  simpl.\n  rewrite Rmult_1_r.\n  reflexivity.\nQed.\n\nLemma pow_add : forall (x:R) (n m:nat), x ^ (n + m) = x ^ n * x ^ m.\nProof.\n  intros x n.\n  induction n as [ | n i ].\n  { intro m. simpl. rewrite Rmult_1_l. reflexivity. }\n  { intro m. simpl. rewrite i. rewrite Rmult_assoc.\n    reflexivity.\n  }\nQed.\n\nLemma Rpow_mult_distr : forall (x y:R) (n:nat), (x * y) ^ n = x^n * y^n.\nProof.\n  intros x y n.\n  induction n as [ | n i ].\n  { simpl. rewrite Rmult_1_l. reflexivity. }\n  { simpl. rewrite i.\n    repeat (rewrite Rmult_assoc).\n    rewrite (Rmult_comm y).\n    repeat (rewrite Rmult_assoc).\n    rewrite (Rmult_comm _ y).\n    reflexivity.\n  }\nQed.\n\nLemma pow_nonzero : forall (x:R) (n:nat), x <> R0 -> x ^ n <> R0.\nProof.\n  intro. simple induction n. simpl.\n  intro. red. intro. apply R1_neq_R0. assumption.\n  intros. red. intro. elim (Rmult_integral x (x ^ n0) H1).\n  intro. auto.\n  apply H. assumption.\nQed.\n\nHint Resolve pow_O pow_1 pow_add pow_nonzero: real.\n\nLemma pow_RN_plus :\n  forall (x:R) (n m:nat), x <> R0 -> x ^ n = x ^ (n + m) * / x ^ m.\nProof.\n  intros x n m h.\n  rewrite pow_add.\n  rewrite Rmult_assoc.\n  rewrite Rinv_r.\n  rewrite Rmult_1_r.\n  reflexivity.\n  apply pow_nonzero.\n  assumption.\nQed.\n\nLemma pow_lt : forall (x:R) (n:nat), R0 < x -> R0 < x ^ n.\nProof.\n  intros x n h.\n  induction n as [ | n i ].\n  simpl. apply Rlt_0_1.\n  simpl.\n  rewrite <- Rmult_0_r with R0.\n  apply Rmult_le_0_lt_compat.\n  right;reflexivity.\n  right;reflexivity.\n  assumption.\n  assumption.\nQed.\nHint Resolve pow_lt: real.\n\nLemma Rlt_pow_R1 : forall (x:R) (n:nat), R1 < x -> (0 < n)%nat -> R1 < x ^ n.\nProof.\n  intros x n.\n  induction n as [ | n i ].\n  {\n    intros hx hf.\n    inversion hf.\n  }\n  {\n    destruct n.\n    {\n      intros hx hu.\n      simpl.\n      rewrite Rmult_1_r.\n      exact hx.\n    }\n    {\n      intros hx hn.\n      rewrite <- Rmult_1_l with R1.\n      apply Rlt_trans with (x * R1).\n      { rewrite Rmult_1_r. rewrite Rmult_1_r. exact hx. }\n      {\n        simpl.\n        apply Rmult_lt_compat_l.\n        {\n          apply Rlt_trans with R1.\n          { apply Rlt_0_1. }\n          { exact hx. }\n        }\n        {\n          simpl in i.\n          apply i.\n          { exact hx. }\n          { unfold lt. apply le_n_S. apply le_0_n. }\n        }\n      }\n    }\n  }\nQed.\nHint Resolve Rlt_pow_R1: real.\n\nLemma Rlt_pow : forall (x:R) (n m:nat), R1 < x -> (n < m)%nat -> x ^ n < x ^ m.\nProof.\n  intros x n.\n  induction n as [ | n i ].\n  { simpl. intros m hx hm. apply Rlt_pow_R1. exact hx. exact hm. }\n  {\n    destruct m.\n    { simpl. intros hx hn. inversion hn. }\n    { intros hx hnm. unfold lt in hnm. apply le_S_n in hnm.\n      simpl. apply Rmult_lt_compat_l.\n      apply Rlt_trans with R1. apply Rlt_0_1. exact hx.\n      apply i. exact hx. unfold lt. exact hnm.\n    }\n  }\nQed.\nHint Resolve Rlt_pow: real.\n\nLemma tech_pow_Rmult : forall (x:R) (n:nat), x * x ^ n = x ^ S n.\nProof.\n  intros x n.\n  simpl.\n  reflexivity.\nQed.\n\nArguments INR _ : simpl nomatch.\n\nLemma tech_pow_Rplus :\n  forall (x:R) (a n:nat), x ^ a + INR n * x ^ a = INR (S n) * x ^ a.\nProof.\n  intros x a n.\n  induction n as [ | n i ].\n  { simpl. rewrite Rmult_0_l. rewrite Rmult_1_l. rewrite Rplus_0_r. reflexivity. }\n  {\n    simpl.\n    rewrite <- i.\n    rewrite S_INR.\n    rewrite Rmult_plus_distr_r.\n    rewrite Rmult_plus_distr_r.\n    rewrite Rmult_1_l.\n    rewrite Rplus_comm.\n    apply Rplus_eq_compat_r.\n    rewrite Rplus_comm.\n    reflexivity.\n  }\nQed.\n\nLemma poly : forall (n:nat) (x:R), R0 < x -> R1 + INR n * x <= (R1 + x) ^ n.\nProof.\n  intros n x hx.\n  induction n as [ | n i ].\n  { simpl. rewrite Rmult_0_l. rewrite Rplus_0_r. right. reflexivity. }\n  { destruct n.\n    { simpl. rewrite Rmult_1_l. rewrite Rmult_1_r. right. reflexivity. }\n    {\n      rewrite S_INR.\n      rewrite Rmult_plus_distr_r.\n      rewrite Rmult_1_l.\n      rewrite <- tech_pow_Rmult.\n      rewrite Rmult_plus_distr_r.\n      rewrite Rmult_1_l.\n      pose (l:= R1 + INR (S n) * x).\n      fold l in i.\n      rewrite <- Rplus_assoc.\n      fold l.\n      pose (r:= (R1+x)^(S n)).\n      fold r in i.\n      fold r.\n      apply Rplus_le_compat.\n      { exact i. }\n      {\n        pattern x at 1;rewrite <- Rmult_1_r.\n        apply Rmult_le_compat_l.\n        { left. exact hx. }\n        {\n          left.\n          unfold r.\n          apply Rlt_pow_R1.\n          {\n            pattern R1 at 1;rewrite <- Rplus_0_r.\n            apply Rplus_lt_compat_l.\n            exact hx.\n          }\n          {\n            unfold lt.\n            apply le_n_S.\n            apply le_0_n.\n          }\n        }\n      }\n    }\n  }\nQed.\n\nLemma Power_monotonic :\n  forall (x:R) (m n:nat),\n    R1 < Rabs x -> (m <= n)%nat -> Rabs (x ^ m) <= Rabs (x ^ n).\nProof.\n  intros x m n hx hmn.\n\n  unfold Rabs in hx. destruct (Rcase_abs x).\n  {\n    generalize dependent n.\n    induction m as [ | m mi ].\n    {\n      induction n as [ | n ni].\n      { simpl. intro u. right. reflexivity. }\n      {\n        simpl. intro u.\n        simpl in ni.\n        apply Rle_trans with (Rabs (x^n)).\n        apply ni. apply le_0_n.\n        rewrite Rabs_mult.\n        pattern (Rabs (x^n)) at 1;rewrite <- Rmult_1_l.\n        apply Rmult_le_compat_r.\n        apply Rabs_pos.\n        left.\n        unfold Rabs. destruct (Rcase_abs x).\n        exact hx.\n        destruct r0.\n        exfalso. apply Rlt_irrefl with R0. apply Rlt_trans with x;assumption.\n        subst x. apply Rlt_irrefl in r. contradiction.\n      }\n    }\n    {\n      intro n. destruct n.\n      { simpl. intro hm.\n        rewrite Rabs_mult.\n        specialize (mi 0%nat).\n        simpl in mi.\n        inversion hm.\n      }\n      {\n        intros hmn.\n        apply le_S_n in hmn.\n        simpl.\n        rewrite Rabs_mult.\n        rewrite Rabs_mult.\n        apply Rmult_le_compat_l.\n        apply Rabs_pos.\n        apply mi.\n        exact hmn.\n      }\n    }\n  }\n  {\n    destruct r.\n    {\n      generalize dependent n.\n      induction m as [ | m mi ].\n      {\n        induction n as [ | n ni].\n        { simpl. intro u. right. reflexivity. }\n        {\n          simpl. intro u.\n          simpl in ni.\n          apply Rle_trans with (Rabs (x^n)).\n          apply ni. apply le_0_n.\n          rewrite Rabs_mult.\n          pattern (Rabs (x^n)) at 1;rewrite <- Rmult_1_l.\n          apply Rmult_le_compat_r.\n          apply Rabs_pos.\n          left.\n          unfold Rabs. destruct (Rcase_abs x).\n          exfalso. apply Rlt_irrefl with R0. apply Rlt_trans with x;assumption.\n          exact hx.\n        }\n      }\n      {\n        intro n. destruct n.\n        { simpl. intro hm.\n          inversion hm.\n        }\n        {\n          intros hmn.\n          apply le_S_n in hmn.\n          simpl.\n          rewrite Rabs_mult.\n          rewrite Rabs_mult.\n          apply Rmult_le_compat_l.\n          apply Rabs_pos.\n          apply mi.\n          exact hmn.\n        }\n      }\n    }\n    {\n      subst x.\n      exfalso. apply Rlt_irrefl with R1. apply Rlt_trans with R0.\n      assumption. apply Rlt_0_1.\n    }\n  }\nQed.\n\nLemma RPow_abs : forall (x:R) (n:nat), Rabs x ^ n = Rabs (x ^ n).\nProof.\n  intros x n.\n  induction n as [ | n i ].\n  { simpl. rewrite Rabs_R1. reflexivity. }\n  { simpl. rewrite Rabs_mult. rewrite i. reflexivity. }\nQed.\n\nLemma XD_INR_Rge : forall r:R, exists n:nat, r <= INR n.\nProof.\n  intro r.\n  destruct (archimed r) as [ agt ale ].\n  exists (Z.abs_nat (up r)).\n  destruct (up r) eqn:upeq.\n  { (* up r = 0 *)\n    simpl.\n    left. exact agt.\n  }\n  { (* up r = Z.pos p *)\n    simpl.\n    destruct (Pos.to_nat p) eqn:poseq.\n    { (* Pos.to_nat p = 0 *)\n      simpl.\n      generalize (Pos2Nat.is_pos p);intro hpos.\n      rewrite poseq in hpos.\n      inversion hpos.\n    }\n    { (* Pos.to_nat p = S n *)\n      (* rewrite S_INR. *)\n      left.\n      rewrite INR_IZR_INZ.\n      rewrite <- poseq.\n      rewrite positive_nat_Z.\n      exact agt.\n    }\n  }\n  { (* up r = Z.neg p *)\n    simpl.\n    destruct (Pos.to_nat p) eqn:poseq.\n    { (* Pos.to_nat p = 0 *)\n      simpl.\n      generalize (Pos2Nat.is_pos p);intro hpos.\n      rewrite poseq in hpos.\n      inversion hpos.\n    }\n    { (* Pos.to_nat p = S n *)\n      left.\n      rewrite INR_IZR_INZ.\n      rewrite <- poseq.\n      rewrite positive_nat_Z.\n      apply Rlt_trans with (IZR (Z.neg p)).\n      { exact agt. }\n      {\n        apply IZR_lt.\n        apply Pos2Z.neg_lt_pos.\n      }\n    }\n  }\nQed.\n\n\nLemma Pow_x_infinity :\n  forall x:R,\n    R1 < Rabs x ->\n    forall b:R,\n      exists N : nat, (forall n:nat, (n >= N)%nat -> b <= Rabs (x ^ n) ).\nProof.\n  intros.\n  pose (exp := b * / (Rabs x - R1)).\n  destruct (archimed exp) as [H0 H1].\n  clear H1.\n  {\n    destruct (XD_INR_Rge exp) as [x0 H1].\n    exists x0.\n    intros n H2.\n    apply Rle_trans with (Rabs (x ^ x0)).\n    {\n      rewrite <- RPow_abs.\n      rewrite <- Rplus_0_l with (Rabs x).\n      rewrite <- Rplus_opp_r with R1.\n      rewrite Rplus_assoc.\n      rewrite (Rplus_comm _ (Rabs x)).\n      fold (Rabs x - R1).\n      apply Rle_trans with (R1 + INR x0 * (Rabs x - R1)).\n      {\n        apply Rle_trans with (INR x0 * (Rabs x - R1)).\n        {\n          rewrite <- Rmult_1_r with b.\n          pattern R1 at 1;rewrite <- Rinv_l with (Rabs x - R1).\n          rewrite <- Rmult_assoc.\n          fold (b / (Rabs x - R1)).\n          {\n            apply Rmult_le_compat_r.\n            {\n              apply Rplus_le_reg_r with R1.\n              unfold Rminus.\n              rewrite Rplus_0_l, Rplus_assoc, Rplus_opp_l, Rplus_0_r.\n              left.\n              exact H.\n            }\n            { \n              fold exp.\n              fold exp in H0, H1.\n              exact H1.\n            }\n          }\n          {\n            apply Rlt_dichotomy_converse.\n            right.\n            apply Rplus_lt_reg_r with R1.\n            unfold Rminus.\n            rewrite Rplus_0_l, Rplus_assoc, Rplus_opp_l, Rplus_0_r.\n            exact H.\n          }\n        }\n        {\n          left.\n          rewrite (Rplus_comm R1).\n          pattern (INR x0 * (Rabs x - R1)) at 1;rewrite <- Rplus_0_r.\n          apply Rplus_lt_compat_l.\n          apply Rlt_0_1.\n        }\n      }\n      {\n        apply poly.\n        apply Rplus_lt_reg_r with R1.\n        unfold Rminus.\n        rewrite Rplus_0_l, Rplus_assoc, Rplus_opp_l, Rplus_0_r.\n        exact H.\n      }\n    }\n    {\n      apply Power_monotonic.\n      { exact H. }\n      { unfold ge in H2. exact H2. }\n    }\n  }\nQed.\n\nLemma pow_ne_zero : forall n:nat, n <> 0%nat -> R0 ^ n = R0.\nProof.\n  intros n h.\n  destruct n.\n  { exfalso. apply h. reflexivity. }\n  { simpl. rewrite Rmult_0_l. reflexivity. }\nQed.\n\nLemma Rinv_pow : forall (x:R) (n:nat), x <> R0 -> / x ^ n = (/ x) ^ n.\nProof.\n  intros x n h.\n  induction n as [ | n i].\n  simpl. rewrite Rinv_1. reflexivity.\n  simpl. rewrite Rinv_mult_distr. rewrite i. reflexivity.\n  exact h.\n  apply pow_nonzero. exact h.\nQed.\n\n(* stopped here *)\n\nLemma Rlt_0_half : R0 < / (IZR 2). Admitted.\nLemma half_nz : / (IZR 2) <> R0. Admitted.\n\nLemma lala :\n    Rabs (/ (IZR 2)) < R1 ->\n    forall y:R,\n      R0 < y ->\n      exists N : nat, (/ (IZR 2)) ^ N < y.\nProof.\n  intros H y hy.\n  assert (hadx : R1 < Rabs (/ (/ (IZR 2))) ).\n  {\n    rewrite <- (Rinv_involutive R1).\n    { \n      rewrite Rabs_Rinv.\n      {\n        apply Rinv_lt_contravar.\n        {\n          apply Rmult_lt_0_compat.\n          {\n            apply Rabs_pos_lt.\n            exact half_nz.\n          }\n          {\n            rewrite Rinv_1.\n            apply Rlt_0_1.\n          }\n        }\n        {\n          rewrite Rinv_1.\n          exact H.\n        }\n      }\n      { exact half_nz. }\n    }\n    { \n      apply R1_neq_R0.\n    }\n  }\n  generalize Pow_x_infinity;intro hpow.\n  specialize (hpow (/ (/ (IZR 2)))).\n  specialize (hpow hadx).\n  specialize (hpow (/ y + R1)).\n  destruct hpow as [N hpow].\n  exists N.\n  specialize (hpow N).\n  assert (ob:(N >= N)%nat). constructor.\n  specialize (hpow ob).\n  rewrite <- (Rinv_involutive y).\n  {\n    {\n      {\n        {\n\nrewrite <- Rinv_pow.\napply Rinv_lt_contravar.\napply Rmult_lt_0_compat.\napply Rinv_0_lt_compat.\nexact hy.\napply pow_lt.\n\n(*\n      {\n        rewrite <- Rabs_Rinv.\n        {\n          rewrite Rinv_pow.\n          {\n            apply Rlt_le_trans with (/ y + 1).\n            {\n              pattern (/ y) at 1;rewrite <- Rplus_0_r.\n              apply Rplus_lt_compat_l.\n              apply Rlt_0_1.\n            }\n            {\n              apply Rge_le.\n              exact hpow.\n            }\n          }\n          { exact half_nz. }\n        }\n        {\n          apply pow_nonzero.\n          exact half_nz.\n        }\n      }\n    }\n    {\n      apply Rabs_no_R0.\n      apply pow_nonzero.\n      exact half_nz.\n    }\n  }\n  {\n    apply Rlt_dichotomy_converse.\n    right.\n    unfold Rgt.\n    exact hy.\n  }\n*)\nAdmitted.\n\n\nLemma pow_lt_1_zero :\n  forall x:R,\n    Rabs x < R1 ->\n    forall y:R,\n      R0 < y ->\n      exists N : nat, (forall n:nat, (n >= N)%nat -> Rabs (x ^ n) < y).\nProof.\n  intros x H y hy.\n  destruct (Req_dec x R0) as [hz | hnz]. (* x = 0 \\/ x <> 0 *)\n  { (* x = 0 *)\n    subst x.\n    exists 1%nat.\n    intros n hn.\n    rewrite pow_ne_zero. (* n <> 0 -> 0 ^ n = 0 *)\n    {\n      rewrite Rabs_R0. (* Rabs 0 = 0 *)\n      exact hy.\n    }\n    {\n      inversion hn as [ heq | m hmn ].\n      {\n        intro eq.\n        inversion eq.\n      }\n      {\n        subst n.\n        intro eq.\n        inversion eq.\n      }\n    }\n  }\n  { (* x <> 0 *)\n    assert (hadx : R1 < Rabs (/ x) ).\n    {\n      rewrite <- (Rinv_involutive R1).\n      { \n        rewrite Rabs_Rinv.\n        {\n          apply Rinv_lt_contravar.\n          {\n            apply Rmult_lt_0_compat.\n            {\n              apply Rabs_pos_lt.\n              exact hnz.\n            }\n            {\n              rewrite Rinv_1.\n              apply Rlt_0_1.\n            }\n          }\n          {\n            rewrite Rinv_1.\n            exact H.\n          }\n        }\n        { exact hnz. }\n      }\n      { \n        apply R1_neq_R0.\n      }\n    }\n    generalize Pow_x_infinity;intro hpow.\n    specialize (hpow (/ x)).\n    specialize (hpow hadx).\n    specialize (hpow (/ y + R1)).\n    destruct hpow as [N hpow].\n    exists N.\n    intros n hnN.\n    specialize (hpow n).\n    specialize (hpow hnN).\n    rewrite <- (Rinv_involutive y).\n    {\n      rewrite <- (Rinv_involutive (Rabs (x ^ n))).\n      {\n        apply Rinv_lt_contravar.\n        {\n          apply Rmult_lt_0_compat.\n          {\n            apply Rinv_0_lt_compat.\n            exact hy.\n          }\n          {\n            apply Rinv_0_lt_compat.\n            apply Rabs_pos_lt.\n            apply pow_nonzero.\n            exact hnz.\n          }\n        }\n        {\n          rewrite <- Rabs_Rinv.\n          {\n            rewrite Rinv_pow.\n            {\n              apply Rlt_le_trans with (/ y + R1).\n              {\n                pattern (/ y) at 1;rewrite <- Rplus_0_r.\n                apply Rplus_lt_compat_l.\n                apply Rlt_0_1.\n              }\n              {\n                exact hpow.\n              }\n            }\n            { exact hnz. }\n          }\n          {\n            apply pow_nonzero.\n            exact hnz.\n          }\n        }\n      }\n      {\n        apply Rabs_no_R0.\n        apply pow_nonzero.\n        exact hnz.\n      }\n    }\n    {\n      apply Rlt_dichotomy_converse.\n      right.\n      exact hy.\n    }\n  }\nQed.\n\nLemma XD_Rabs_lt_0_Sn: forall r n,\n  r<>R0 ->\n  R1 < Rabs r ->\n  Rabs r ^ 0 < Rabs r ^ S n.\nProof.\n  intros r n hrnz harlt.\n  simpl.\n  induction n as [ | n i ].\n  {\n    simpl.\n    rewrite Rmult_1_r.\n    exact harlt.\n  }\n  {\n    simpl.\n    apply Rlt_trans with (Rabs r).\n    {\n      exact harlt.\n    }\n    {\n      pattern (Rabs r) at 1;rewrite <- Rmult_1_r.\n      apply Rmult_lt_compat_l.\n      2:exact i.\n      {\n        apply Rabs_pos_lt.\n        exact hrnz.\n      }\n    }\n  }\nQed.\n\nLemma pow_R1 : forall (r:R) (n:nat), r ^ n = R1 -> Rabs r = R1 \\/ n = 0%nat.\nProof.\n  intros r n h.\n  destruct (Req_dec (Rabs r) R1) as [ hareq | harneq ].\n  { (* Rabs r = 1 *)\n    left. exact hareq.\n  }\n  { (* Rabs r <> 1 *)\n    right.\n    apply Rdichotomy in harneq.\n    destruct harneq as [ harlt | hargt ].\n    { (* Rabs r < 1 *)\n      {\n        destruct n as [ | n ].\n        { (* n = 0 *)\n          reflexivity.\n        }\n        { (* n <> 0 *)\n          {\n            (* h is absurd when r = 0 *)\n            assert (hrnz: r<>R0).\n            {\n              intro heq.\n              subst r.\n              simpl in h.\n              rewrite Rmult_0_l in h.\n              apply R1_neq_R0.\n              symmetry.\n              exact h.\n            }\n            (* from there, it's obvious that Rabs r <> 0 *)\n            assert (harnz : Rabs r <> R0).\n            { apply Rabs_no_R0. exact hrnz. }\n            (* We cannot show this goal, so there must be an inconsistency *)\n            exfalso.\n            (* We use XD_Rabs_lt_0_Sn to reveal the inconsistency *)\n            apply Rlt_irrefl with R1.\n            pattern R1 at 1;rewrite <- pow_O with (Rabs (/ r)).\n            rewrite <- Rabs_R1.\n            rewrite <- Rinv_1.\n            rewrite <- h.\n            rewrite Rinv_pow.\n            2:exact hrnz.\n            rewrite <- RPow_abs.\n            apply XD_Rabs_lt_0_Sn.\n            {\n              apply Rinv_neq_0_compat.\n              exact hrnz.\n            }\n            {\n              rewrite Rabs_Rinv.\n              2:exact hrnz.\n              pattern R1 at 1;rewrite <- Rinv_involutive.\n              2:exact R1_neq_R0.\n              apply Rinv_lt_contravar.\n              {\n                rewrite Rinv_1.\n                rewrite Rmult_1_r.\n                apply Rabs_pos_lt.\n                exact hrnz.\n              }\n              {\n                rewrite Rinv_1.\n                exact harlt.\n              }\n            }\n          }\n        }\n      }\n    }\n    {\n      destruct n as [ | n ].\n      { reflexivity. }\n      {\n        assert (hrnz:r<>R0).\n        {\n          intro hrz.\n          subst r.\n          simpl in h.\n          rewrite Rmult_0_l in h.\n          symmetry in h.\n          apply R1_neq_R0 in h.\n          contradiction.\n        }\n        assert (harnz:Rabs r <> R0).\n        {\n          apply Rabs_no_R0.\n          exact hrnz.\n        }\n        exfalso.\n        apply Rlt_irrefl with R1.\n        pattern R1 at 1;rewrite <- pow_O with (Rabs r).\n        rewrite <- Rabs_R1.\n        rewrite <- h.\n        rewrite <- RPow_abs.\n        apply XD_Rabs_lt_0_Sn.\n        exact hrnz.\n        exact hargt.\n      }\n    }\n  }\nQed.\n\nLemma pow_Rsqr : forall (x:R) (n:nat), x ^ (2 * n) = Rsqr x ^ n.\nProof.\n  intros x n.\n  induction n as [ | n i ].\n  { simpl. reflexivity. }\n  {\n    simpl.\n    rewrite plus_comm.\n    simpl.\n    rewrite (plus_comm n).\n    simpl.\n    simpl in i.\n    rewrite plus_comm in i.\n    rewrite <- plus_assoc in i.\n    simpl in i.\n    rewrite i.\n    unfold Rsqr.\n    repeat (rewrite Rmult_assoc).\n    reflexivity.\n  }\nQed.\n\nLemma pow_le : forall (a:R) (n:nat), R0 <= a -> R0 <= a ^ n.\nProof.\n  intros a n h.\n  induction n as [ | n i ].\n  { simpl. left. apply Rlt_0_1. }\n  { simpl. apply Rmult_le_pos. exact h. exact i. }\nQed.\n\nLemma pow_1_even : forall n:nat, (-R1) ^ (2 * n) = R1.\nProof.\n  intro n. induction n as [ | n i ].\n  { simpl. reflexivity. }\n  { rewrite pow_Rsqr. rewrite pow_Rsqr in i. simpl.\n    rewrite i. rewrite Rmult_1_r.\n    unfold Rsqr.\n    unfold IZR.\n    rewrite <- Ropp_mult_distr_l.\n    rewrite <- Ropp_mult_distr_r.\n    rewrite Ropp_involutive.\n    rewrite Rmult_1_r.\n    reflexivity.\n  }\nQed.\n\nLemma pow_1_odd : forall n:nat, (-R1) ^ S (2 * n) = -R1.\nProof.\n  intros n.\n  pose (twice:=(2*n)%nat).\n  fold twice.\n  simpl.\n  unfold twice.\n  rewrite pow_1_even.\n  rewrite Rmult_1_r.\n  reflexivity.\nQed.\n\nLemma XD_even_odd : forall n:nat, ((exists n', n=2 * n') \\/ (exists n', n = S(2 * n')))%nat.\nProof.\n  intro n.\n  induction n as [ | n i ].\n  {\n    simpl.\n    left. exists 0%nat. simpl. reflexivity.\n  }\n  {\n    destruct i as [ l | r ].\n    {\n      destruct l as [ n' h ].\n      subst n.\n      simpl.\n      right. exists n'. reflexivity.\n    }\n    {\n      destruct r as [ n' h ].\n      subst n.\n      simpl.\n      left.\n      exists (S n').\n      simpl.\n      rewrite (plus_comm n').\n      rewrite (plus_comm n').\n      simpl.\n      rewrite plus_n_Sm.\n      reflexivity.\n    }\n  }\nQed.\n\nLemma pow_1_abs : forall n:nat, Rabs ((-R1) ^ n) = R1.\nProof.\n  intros n.\n  destruct (XD_even_odd n) as [ heven | hodd ].\n  destruct heven as [n' eq].\n  subst n. rewrite pow_1_even. rewrite Rabs_R1. reflexivity.\n  destruct hodd as [n' eq].\n  subst n. rewrite pow_1_odd. unfold IZR. rewrite Rabs_Ropp.\n  fold (IZR 1). rewrite Rabs_R1. reflexivity.\nQed.\n\n(* stopped here *)\n\nLemma pow_mult : forall (x:R) (n1 n2:nat), x ^ (n1 * n2) = (x ^ n1) ^ n2.\nProof.\n  intros x n m.\n  induction n as [ | n i ].\n  { simpl.\n    induction m as [ | m i ].\n    { simpl. reflexivity. }\n    { simpl. rewrite <- i. rewrite Rmult_1_r. reflexivity. }\n  }\n  {\n    simpl.\n    rewrite pow_add.\n    rewrite i.\n    rewrite Rpow_mult_distr.\n    reflexivity.\n  }\nQed.\n\nLemma pow_incr : forall (x y:R) (n:nat), R0 <= x <= y -> x ^ n <= y ^ n.\nProof.\n  intros x y n h.\n  induction n as [ | n i ].\n  { simpl. right. reflexivity. }\n  {\n    simpl.\n    destruct h as [ l r ].\n    apply Rmult_le_compat.\n    { exact l. }\n    { apply pow_le. exact l. }\n    { exact r. }\n    { exact i. }\n  }\nQed.\n\nLemma pow_R1_Rle : forall (x:R) (k:nat), R1 <= x -> R1 <= x ^ k.\nProof.\n  intros x n h.\n  induction n as [ | n i ].\n  { simpl. right. reflexivity. }\n  {\n    simpl.\n    pattern R1 at 1;rewrite <- Rmult_1_l.\n    apply Rmult_le_compat.\n    left. exact Rlt_0_1.\n    left. exact Rlt_0_1.\n    exact h.\n    exact i.\n  }\nQed.\n\nLemma Rle_pow :\n  forall (x:R) (m n:nat), R1 <= x -> (m <= n)%nat -> x ^ m <= x ^ n.\nProof.\n  intros x m.\n  induction m as [ | m mi ].\n  {\n    intros n hx hn.\n    simpl.\n    apply pow_R1_Rle.\n    exact hx.\n  }\n  {\n    intros n hx hn.\n    destruct n.\n    { inversion hn. }\n    {\n      simpl.\n      apply Rmult_le_compat_l.\n      apply Rle_trans with R1.\n      left. exact Rlt_0_1.\n      exact hx.\n      apply mi.\n      exact hx.\n      apply le_S_n.\n      exact hn.\n    }\n  }\nQed.\n\nLemma pow1 : forall n:nat, R1 ^ n = R1.\nProof.\n  intro n.\n  induction n as [ | n i ].\n  simpl. reflexivity.\n  simpl. rewrite i. rewrite Rmult_1_l. reflexivity.\nQed.\n\nLemma pow_Rabs : forall (x:R) (n:nat), x ^ n <= Rabs x ^ n.\nProof.\n  intros x n.\n  destruct n.\n  { simpl. right. reflexivity. }\n  {\n    simpl.\n    unfold Rabs in *.\n    destruct (Rcase_abs x).\n    {\n      destruct (XD_even_odd n) as [ [ n' heven ] | [ n' hodd ]  ].\n      {\n        subst n. rename n' into n.\n        pattern (-x) at 2;rewrite <- Rmult_1_r.\n        rewrite <- (Ropp_mult_distr_l _ R1).\n        rewrite (Ropp_mult_distr_r _ R1).\n        rewrite Rpow_mult_distr.\n        rewrite pow_1_even.\n        rewrite Rmult_1_r.\n        apply Rmult_le_compat_r.\n        {\n          rewrite pow_Rsqr.\n          apply pow_le.\n          apply Rle_0_sqr.\n        }\n        {\n          left.\n          apply Rlt_trans with R0.\n          exact r.\n          rewrite <- Ropp_0.\n          apply Ropp_lt_contravar.\n          exact r.\n        }\n      }\n      {\n        subst n.\n        pattern (-x) at 2;rewrite <- Rmult_1_r.\n        rewrite <- (Ropp_mult_distr_l _ R1).\n        rewrite (Ropp_mult_distr_r _ R1).\n        rewrite Rpow_mult_distr.\n        rewrite pow_1_odd.\n        unfold IZR.\n        rewrite <- Ropp_mult_distr_r.\n        fold (IZR 1).\n        rewrite Rmult_1_r.\n        rewrite <- Ropp_mult_distr_r.\n        rewrite <- Ropp_mult_distr_l.\n        rewrite Ropp_involutive.\n        right.\n        reflexivity.\n      }\n    }\n    {\n      right.\n      reflexivity.\n    }\n  }\nQed.\n\nLemma pow_maj_Rabs : forall (x y:R) (n:nat), Rabs y <= x -> y ^ n <= x ^ n.\nProof.\n  intros x y n h.\n  assert (hx:R0 <= x).\n  {\n    apply Rle_trans with (Rabs y).\n    apply Rabs_pos.\n    exact h.\n  }\n  {\n    apply Rle_trans with (Rabs y ^ n).\n    { apply pow_Rabs. }\n    { induction  n as [ | n i ].\n      { right. simpl. reflexivity. }\n      {\n        simpl.\n        apply Rle_trans with (x * Rabs y ^ n).\n        {\n          apply Rmult_le_compat_r.\n          {\n            apply pow_le.\n            apply Rabs_pos.\n          }\n          { exact h. }\n        }\n        {\n          apply Rmult_le_compat_l.\n          { exact hx. }\n          { apply i. }\n        }\n      }\n    }\n  }\nQed.\n\nLemma Rsqr_pow2 : forall x, Rsqr x = x ^ 2.\nProof.\n  intro x.\n  unfold Rsqr.\n  simpl.\n  rewrite Rmult_1_r.\n  reflexivity.\nQed.\n\nSection PowerRZ.\n\nLocal Coercion Z_of_nat : nat >-> Z.\n\nSection Z_compl.\n\nLocal Open Scope Z_scope.\n\nInductive Z_spec (x : Z) : Z -> Type :=\n| ZintNull : x = 0 -> Z_spec x 0\n| ZintPos (n : nat) : x = n -> Z_spec x n\n| ZintNeg (n : nat) : x = - n -> Z_spec x (- n).\n\nLemma intP (x : Z) : Z_spec x x.\nProof.\n  induction x.\n  {\n    apply ZintNull. (* x = 0 -> Z_spec x 0 *)\n    reflexivity.\n  }\n  {\n    rewrite <- positive_nat_Z at 2. (* Pos.to_nat p = Z.pos p *)\n    apply ZintPos. (* x = n -> Z_spec x n *)\n    rewrite positive_nat_Z.\n    reflexivity.\n  }\n  {\n    rewrite  <- Pos2Z.opp_pos. (* - Z.pos p = Z.neg p *)\n    rewrite <- positive_nat_Z at 2.\n    apply ZintNeg.\n    rewrite positive_nat_Z.\n    reflexivity.\n  }\nQed.\n\nEnd Z_compl.\n\nDefinition powerRZ (x:R) (n:Z) :=\n  match n with\n    | Z0 => R1\n    | Zpos p => x ^ Pos.to_nat p\n    | Zneg p => / x ^ Pos.to_nat p\n  end.\n\nLocal Infix \"^Z\" := powerRZ (at level 30, right associativity) : XR_scope.\n\nLemma Zpower_NR0 :\n  forall (x:Z) (n:nat), (0 <= x)%Z -> (0 <= Zpower_nat x n)%Z.\nProof.\n  intros x n h.\n  induction n as [ | n i ].\n  {\n    simpl.\n    unfold Z.le.\n    simpl.\n    intro eq.\n    inversion eq.\n  }\n  {\n    simpl.\n    apply Z.mul_nonneg_nonneg.\n    exact h.\n    exact i.\n  }\nQed.\n\nLemma powerRZ_O : forall x:R, x ^Z 0 = R1.\nProof.\n  intro x.\n  simpl.\n  reflexivity.\nQed.\n\nLemma powerRZ_1 : forall x:R, x ^Z Z.succ 0 = x.\nProof.\n  intro x.\n  simpl.\n  rewrite Rmult_1_r.\n  reflexivity.\nQed.\n\nLemma powerRZ_NOR : forall (x:R) (z:Z), x <> R0 -> x ^Z z <> R0.\nProof.\n  intros x z neq eq.\n  destruct z;simpl in eq.\n  {\n    apply R1_neq_R0. exact eq.\n  }\n  {\n    apply (pow_nonzero _ (Pos.to_nat p)) in neq.\n    contradiction.\n  }\n  {\n    generalize neq;intro neqpow.\n    apply Rinv_neq_0_compat in neqpow.\n    apply (pow_nonzero _ (Pos.to_nat p)) in neqpow.\n    rewrite Rinv_pow in eq.\n    contradiction.\n    exact neq.\n  }\nQed.\n\n(* skipped *)\nLemma powerRZ_pos_sub (x:R) (n m:positive) : x <> R0 ->\n   x ^Z (Z.pos_sub n m) = x ^ Pos.to_nat n * / x ^ Pos.to_nat m.\nProof.\n intro Hx.\n rewrite Z.pos_sub_spec.\n case Pos.compare_spec; intro H; simpl.\n - subst; auto with real.\n - rewrite Pos2Nat.inj_sub by trivial.\n   rewrite Pos2Nat.inj_lt in H.\n   rewrite (pow_RN_plus x _ (Pos.to_nat n)) by auto with real.\n   rewrite plus_comm, le_plus_minus_r by auto with real.\n   rewrite Rinv_mult_distr, Rinv_involutive; auto with real.\n - rewrite Pos2Nat.inj_sub by trivial.\n   rewrite Pos2Nat.inj_lt in H.\n   rewrite (pow_RN_plus x _ (Pos.to_nat m)) by auto with real.\n   rewrite plus_comm, le_plus_minus_r by auto with real.\n   reflexivity.\nQed.\n\n(* skipped *)\nLemma powerRZ_add :\n  forall (x:R) (n m:Z), x <> R0 -> x ^Z (n + m) = x ^Z n * x ^Z m.\nProof.\n  intros x [|n|n] [|m|m]; simpl; intros; auto with real.\n  - (* + + *)\n    rewrite Pos2Nat.inj_add; auto with real.\n  - (* + - *)\n    now apply powerRZ_pos_sub.\n  - (* - + *)\n    rewrite Rmult_comm. now apply powerRZ_pos_sub.\n  - (* - - *)\n    rewrite Pos2Nat.inj_add; auto with real.\n    rewrite pow_add; auto with real.\n    apply Rinv_mult_distr; apply pow_nonzero; auto.\nQed.\nHint Resolve powerRZ_O powerRZ_1 powerRZ_NOR powerRZ_add: real.\n\n(* skipped *)\nLemma Zpower_nat_powerRZ :\n  forall n m:nat, IZR (Zpower_nat (Z.of_nat n) m) = INR n ^Z Z.of_nat m.\nProof.\n  intros n m; elim m; simpl; auto with real.\n  intros m1 H'; rewrite SuccNat2Pos.id_succ; simpl.\n  replace (Zpower_nat (Z.of_nat n) (S m1)) with\n  (Z.of_nat n * Zpower_nat (Z.of_nat n) m1)%Z.\n  rewrite mult_IZR; auto with real.\n  repeat rewrite <- INR_IZR_INZ; simpl.\n  rewrite H'; simpl.\n  case m1; simpl; auto with real.\n  intros m2; rewrite SuccNat2Pos.id_succ; auto.\n  unfold Zpower_nat; auto.\nQed.\n\n(* skipped *)\nLemma Zpower_pos_powerRZ :\n  forall n m, IZR (Z.pow_pos n m) = IZR n ^Z Zpos m.\nProof.\n  intros.\n  rewrite Zpower_pos_nat; simpl.\n  induction (Pos.to_nat m).\n  easy.\n  unfold Zpower_nat; simpl.\n  rewrite mult_IZR.\n  now rewrite <- IHn0.\nQed.\n\n(* skipped *)\nLemma powerRZ_lt : forall (x:R) (z:Z), R0 < x -> R0 < x ^Z z.\nProof.\n  intros x z; case z; simpl; auto with real.\nQed.\nHint Resolve powerRZ_lt: real.\n\n(* skipped *)\nLemma powerRZ_le : forall (x:R) (z:Z), R0 < x -> R0 <= x ^Z z.\nProof.\n  intros x z H'; apply Rlt_le; auto with real.\nQed.\nHint Resolve powerRZ_le: real.\n\n(* skipped *)\nLemma Zpower_nat_powerRZ_absolu :\n  forall n m:Z, (0 <= m)%Z -> IZR (Zpower_nat n (Z.abs_nat m)) = IZR n ^Z m.\nProof.\n  intros n m; case m; simpl; auto with zarith.\n  intros p H'; elim (Pos.to_nat p); simpl; auto with zarith.\n  intros n0 H'0; rewrite <- H'0; simpl; auto with zarith.\n  rewrite <- mult_IZR; auto.\n  intros p H'; absurd (0 <= Zneg p)%Z; auto with zarith.\nQed.\n\n(* skipped *)\nLemma powerRZ_R1 : forall n:Z, R1 ^Z n = R1.\nProof.\n  intros n; case n; simpl; auto.\n  intros p; elim (Pos.to_nat p); simpl; auto; intros n0 H'; rewrite H'.\n    rewrite Rmult_1_r.\nreflexivity.\n  intros p; elim (Pos.to_nat p); simpl.\n  exact Rinv_1.\n  intros n1 H'; rewrite Rinv_mult_distr; try rewrite Rinv_1; try rewrite H';\n    auto with real.\nQed.\n\nLocal Open Scope Z_scope.\n\n(* skipped *)\nLemma pow_powerRZ (r : R) (n : nat) :\n  (r ^ n)%R = powerRZ r (Z_of_nat n).\nProof.\n  induction n; [easy|simpl].\n  now rewrite SuccNat2Pos.id_succ.\nQed.\n\n(* skipped *)\nLemma powerRZ_ind (P : Z -> R -> R -> Prop) :\n  (forall x, P 0 x R1) ->\n  (forall x n, P (Z.of_nat n) x (x ^ n)%R) ->\n  (forall x n, P ((-(Z.of_nat n))%Z) x (Rinv (x ^ n))) ->\n  forall x (m : Z), P m x (powerRZ x m)%R.\nProof.\n  intros ? ? ? x m.\n  destruct (intP m) as [Hm|n Hm|n Hm].\n  - easy.\n  - now rewrite <- pow_powerRZ.\n  - unfold powerRZ.\n    destruct n as [|n]; [ easy |].\n    rewrite Nat2Z.inj_succ, <- Zpos_P_of_succ_nat, Pos2Z.opp_pos.\n    now rewrite <- Pos2Z.opp_pos, <- positive_nat_Z.\nQed.\n\n(* skipped *)\nLemma powerRZ_inv x alpha : (x <> R0)%R -> powerRZ (/ x) alpha = Rinv (powerRZ x alpha).\nProof.\n  intros; destruct (intP alpha).\n  - now simpl; rewrite Rinv_1.\n  - now rewrite <-!pow_powerRZ, ?Rinv_pow, ?pow_powerRZ.\n  - unfold powerRZ.\n    destruct (- n).\n    + now rewrite Rinv_1.\n    + now rewrite Rinv_pow.\n    + now rewrite <-Rinv_pow.\nQed.\n\n(* skipped *)\nLemma powerRZ_neg x : forall alpha, x <> R0 -> powerRZ x (- alpha) = powerRZ (/ x) alpha.\nProof.\n  intros [|n|n] H ; simpl.\n  - easy.\n  - now rewrite Rinv_pow.\n  - rewrite Rinv_pow by now apply Rinv_neq_0_compat.\n    now rewrite Rinv_involutive.\nQed.\n\n(* skipped *)\nLemma powerRZ_mult_distr :\n  forall m x y, ((Z.le Z0 m)%Z \\/\n\t\t(x * y <> R0)%R) ->\n           (powerRZ (x*y) m = powerRZ x m * powerRZ y m)%R.\nProof.\n  intros m x0 y0 Hmxy.\n  destruct (intP m) as [ | | n Hm ].\n  - now simpl; rewrite Rmult_1_l.\n  - now rewrite <- !pow_powerRZ, Rpow_mult_distr.\n  - destruct Hmxy as [H|H].\n    + assert(m = 0) as -> by now omega.\n      now rewrite <- Hm, Rmult_1_l.\n    + assert(x0 <> R0)%R by now intros ->; apply H; rewrite Rmult_0_l.\n      assert(y0 <> R0)%R by now intros ->; apply H; rewrite Rmult_0_r.\n      rewrite !powerRZ_neg by assumption.\n      rewrite Rinv_mult_distr by assumption.\n      now rewrite <- !pow_powerRZ, Rpow_mult_distr.\nQed.\n\nEnd PowerRZ.\n\nLocal Infix \"^Z\" := powerRZ (at level 30, right associativity) : XR_scope.\n\nDefinition decimal_exp (r:R) (z:Z) : R := (r * (IZR 10) ^Z z).\n\n\nFixpoint sum_nat_f_O (f:nat -> nat) (n:nat) : nat :=\n  match n with\n    | O => f 0%nat\n    | S n' => (sum_nat_f_O f n' + f (S n'))%nat\n  end.\n\nDefinition sum_nat_f (s n:nat) (f:nat -> nat) : nat :=\n  sum_nat_f_O (fun x:nat => f (x + s)%nat) (n - s).\n\nDefinition sum_nat_O (n:nat) : nat := sum_nat_f_O (fun x:nat => x) n.\n\nDefinition sum_nat (s n:nat) : nat := sum_nat_f s n (fun x:nat => x).\n\nFixpoint sum_f_R0 (f:nat -> R) (N:nat) : R :=\n  match N with\n    | O => f 0%nat\n    | S i => sum_f_R0 f i + f (S i)\n  end.\n\nDefinition sum_f (s n:nat) (f:nat -> R) : R :=\n  sum_f_R0 (fun x:nat => f (x + s)%nat) (n - s).\n\nDefinition fGP (x:R) (n : nat) := x ^n.\n\nLemma GP_finite :\n  forall (x:R) (n:nat),\n    sum_f_R0 (fGP x) n * (x - R1) = x ^ (n + 1) - R1.\nProof.\n  intros x n.\n  pose (f:=fun k => x^k).\n  fold f.\n  induction n as [ | n i].\n  { simpl. rewrite Rmult_1_l. rewrite Rmult_1_r. reflexivity. }\n  {\n    simpl.\n    unfold fGP at 2.\n    rewrite Rmult_plus_distr_r.\n    rewrite i.\n    unfold Rminus.\n    rewrite Rmult_plus_distr_l.\n    rewrite <- Ropp_mult_distr_r.\n    rewrite Rmult_1_r.\n    rewrite pow_add.\n    simpl.\n    rewrite Rmult_1_r.\n    repeat (rewrite Rplus_assoc).\n    rewrite Rplus_comm at 1.\n    repeat (rewrite Rplus_assoc).\n    rewrite (Rmult_comm x (x^n)).\n    rewrite Rplus_opp_l.\n    rewrite Rplus_0_r.\n    rewrite Rplus_comm.\n    apply Rplus_eq_compat_r.\n    rewrite Rmult_comm.\n    reflexivity.\n  }\nQed.\n\nDefinition fTR (f : nat -> R) (n:nat) := Rabs (f n).\n\nLemma sum_f_R0_triangle :\n  forall (f:nat -> R) (n:nat),\n    Rabs (sum_f_R0 f n) <= sum_f_R0 (fTR f) n.\nProof.\n  intros f n.\n  induction n as [ | n i ].\n  { simpl. unfold fTR. right. reflexivity. }\n  {\n    simpl.\n    pose (a:=sum_f_R0 f n).\n    fold a in i.\n    pose (b:=sum_f_R0 (fTR f) n).\n    fold b in i. fold b.\n    fold a.\n    pose (c:= f (S n)).\n    fold c.\n    apply Rle_trans with (Rabs a + Rabs c).\n    apply Rabs_triang.\n    apply Rplus_le_compat.\n    exact i.\n    unfold c. unfold fTR. right. reflexivity.\n  }\nQed.\n\nDefinition R_dist (x y:R) : R := Rabs (x - y).\n\nLemma R_dist_pos : forall x y:R, R0 <= R_dist x y .\nProof.\n  intros x y.\n  unfold R_dist.\n  apply Rabs_pos.\nQed.\n\nLemma R_dist_sym : forall x y:R, R_dist x y = R_dist y x.\nProof.\n  intros x y.\n  unfold R_dist.\n  rewrite Rabs_minus_sym.\n  reflexivity.\nQed.\n\nLemma R_dist_refl : forall x y:R, R_dist x y = R0 <-> x = y.\nProof.\n  intros x y.\n  split.\n  {\n    intro eq.\n    unfold R_dist in eq.\n    unfold Rabs in eq.\n    unfold Rminus in eq.\n    destruct (Rcase_abs (x + - y)).\n    {\n      apply Rplus_eq_reg_r with (-y).\n      rewrite Rplus_opp_r.\n      rewrite <- Ropp_0.\n      rewrite <- eq.\n      rewrite Ropp_involutive.\n      reflexivity.\n    }\n    {\n      apply Rplus_eq_reg_r with (-y).\n      rewrite Rplus_opp_r.\n      rewrite eq.\n      reflexivity.\n    }\n  }\n  { intro eq. subst y. unfold R_dist. unfold Rminus. rewrite Rplus_opp_r. rewrite Rabs_R0. reflexivity. }\nQed.\n\nLemma R_dist_eq : forall x:R, R_dist x x = R0.\nProof.\n  intros x.\n  unfold R_dist.\n  unfold Rminus.\n  rewrite Rplus_opp_r.\n  rewrite Rabs_R0.\n  reflexivity.\nQed.\n\nLemma R_dist_tri : forall x y z:R, R_dist x y <= R_dist x z + R_dist z y.\nProof.\n  intros x y z.\n  unfold R_dist.\n  unfold Rminus.\n  pattern x at 1;rewrite <- Rplus_0_r.\n  rewrite <- Rplus_opp_l with z.\n  rewrite Rplus_assoc.\n  rewrite Rplus_assoc.\n  rewrite <- (Rplus_assoc x).\n  apply Rle_trans with (Rabs (x+-z) + Rabs (z+-y)).\n  apply Rabs_triang.\n  right.\n  reflexivity.\nQed.\n\nLemma R_dist_plus :\n  forall a b c d:R, R_dist (a + c) (b + d) <= R_dist a b + R_dist c d.\nProof.\n  intros a b c d.\n  unfold R_dist.\n  unfold Rminus.\n  rewrite Ropp_plus_distr.\n  rewrite Rplus_assoc.\n  rewrite (Rplus_comm c).\n  rewrite Rplus_assoc.\n  rewrite (Rplus_comm _ c).\n  rewrite <- (Rplus_assoc a).\n  apply Rabs_triang.\nQed.\n\nLemma R_dist_mult_l : forall a b c,\n  R_dist (a * b) (a * c) = Rabs a * R_dist b c.\nProof.\n  intros a b c.\n  unfold R_dist at 1.\n  unfold Rminus.\n  rewrite Ropp_mult_distr_r.\n  rewrite <- Rmult_plus_distr_l.\n  fold (b-c).\n  rewrite Rabs_mult.\n  fold (R_dist b c).\n  reflexivity.\nQed.\n\n\n\n\nDefinition infinite_sum (s:nat -> R) (l:R) : Prop :=\n  forall eps:R,\n    R0 < eps ->\n    exists N : nat,\n      (forall n:nat, (n >= N)%nat -> R_dist (sum_f_R0 s n) l < eps).\n\nNotation infinit_sum := infinite_sum (only parsing).\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/Reals/XRfunctions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511359371249, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.6977176578277337}}
{"text": "Open Scope list_scope.\n\nInductive alpha : Set := M : alpha | I : alpha | U : alpha.\nDefinition word : Set := list alpha.\nCheck length.\n\nDefinition word_M : list alpha := M :: nil.\nDefinition word_MI := M::I::nil.\nDefinition word_MU := M::U::nil.\nDefinition word_I := I::nil.\nDefinition word_IU := I::U::nil.\nDefinition word_III := I::I::I::nil.\nDefinition word_U := U::nil.\nDefinition word_UU := U::U::nil.\n\n\nInductive lang : word -> Prop :=\n  | axiom :\n      lang word_MI\n  | rule1 : forall x,\n      lang (x ++ word_I) -> lang (x ++ word_IU)\n  | rule2 : forall x,\n      lang (word_M ++ x) -> lang (word_M ++ x ++ x)\n  | rule3 : forall x y,\n      lang (x ++ word_III ++ y) -> lang (x ++ word_U ++ y)\n  | rule4 : forall x y, \n      lang (x ++ word_UU ++ y) -> lang (x ++ y).\n\n  Definition hd_error (l:word) : option alpha :=\n    match l with\n      | nil => None\n      | x :: _ => Some x\n    end.\n\nLemma commence_par_M :\n  forall m : word, lang m -> hd_error m = Some M.\nProof.\nintros.\ninduction H.\n  - simpl. reflexivity.\n  - destruct x.\n    + simpl in *. \n    (* *)\n    discriminate. \n    (* on a faux dans l'hypothèse donc \n    chouet on peut tout prouver avec.\n    on peut aussi utiliser assumption. *)\n    + simpl in *. assumption.\n  - simpl. assumption.\n  - destruct x.\n    + simpl in *. discriminate.\n    + simpl in *. assumption.\n  - destruct x.\n    + simpl in *. discriminate.\n    + simpl in *. assumption.\nQed.\n\n\nInductive Z3 : Set := Z0 : Z3 | Z1 : Z3 | Z2 : Z3.\n\n", "meta": {"author": "arintaauza", "repo": "Coq", "sha": "1e69840d3ea96f54f516440f60aba759e8ac51ae", "save_path": "github-repos/coq/arintaauza-Coq", "path": "github-repos/coq/arintaauza-Coq/Coq-1e69840d3ea96f54f516440f60aba759e8ac51ae/tp9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.6976784544717224}}
{"text": "From Coq Require Import\n  List.\nFrom FunProofs.Lib Require Import\n  List.\n\nSection ZipMap.\n  Context {A B C : Type}.\n\n  Definition zipMap (f : A -> B -> C) xs ys : list C :=\n    map (fun xy => f (fst xy) (snd xy)) (combine xs ys).\n\n  Lemma zipMap_split {D E} (f : D -> A) (g : E -> B) (h : A -> B -> C) xs : forall ys,\n    map (fun xy => h (f (fst xy)) (g (snd xy))) (combine xs ys) =\n    zipMap h (map f xs) (map g ys).\n  Proof.\n    unfold zipMap; induction xs; cbn; intros; auto.\n    destruct ys; cbn; auto.\n    rewrite IHxs; auto.\n  Qed.\n\n  Lemma zipMap_repeat_r (f : A -> B -> C) y xs : forall n,\n    n = length xs -> zipMap f xs (repeat y n) = map (fun x => f x y) xs.\n  Proof.\n    unfold zipMap; induction xs; cbn; intros; subst; auto.\n    erewrite <- IHxs; eauto; auto.\n  Qed.\n\n  Lemma zipMap_app (f : A -> B -> C) xs xs' ys ys' :\n    length xs = length ys ->\n    length xs' = length ys' ->\n    zipMap f (xs ++ xs') (ys ++ ys') = zipMap f xs ys ++ zipMap f xs' ys'.\n  Proof. unfold zipMap; intros; rewrite combine_app, map_app; auto. Qed.\n\n  Lemma zipMap_rev (f : A -> B -> C) xs ys :\n    length xs = length ys -> rev (zipMap f xs ys) = zipMap f (rev xs) (rev ys).\n  Proof. unfold zipMap; intros; rewrite <- map_rev, combine_rev; auto. Qed.\nEnd ZipMap.\n", "meta": {"author": "whonore", "repo": "FunProofs", "sha": "f87c0d56670af0903f2a50a52c5f1056703f31cc", "save_path": "github-repos/coq/whonore-FunProofs", "path": "github-repos/coq/whonore-FunProofs/FunProofs-f87c0d56670af0903f2a50a52c5f1056703f31cc/Lib/ZipMap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.6976784507862543}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\nRequire Import Arith. \nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type :=   Nil : lst | Cons : natural -> lst -> lst .\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nFixpoint qreva (qreva_arg0 : lst) (qreva_arg1 : lst) : lst\n           := match qreva_arg0, qreva_arg1 with\n              | Nil, x => x\n              | Cons z x, y => qreva x (Cons z y)\n              end.\n\nLemma append_nil : forall (x : lst), append x Nil = x.\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma append_assoc : forall (x y z : lst), append (append x y) z = append x (append y z).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma rev_append : forall (x y : lst), rev (append x y) = append (rev y) (rev x).\nProof.\n   intros.\n   induction x.\n   - simpl. lfind.  reflexivity. \nAdmitted.\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. \n   rewrite (eq_refl : Cons n (rev y) = append (rev (Cons n Nil)) (rev y)). \n   rewrite <- rev_append. \n   rewrite IHx. \n   rewrite append_assoc. \n   simpl. reflexivity.\nQed.\n              \n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/clam_lf_goal82_rev_append_49_append_nil/goal82.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.6976784484855963}}
{"text": "Require Import Coq.Arith.PeanoNat.\nRequire Import List.\nImport ListNotations.\nRequire Import Lia.\n\nRequire Import CoqChess.Util.Rel.\nRequire Import CoqChess.Util.Dist.\nRequire Import CoqChess.Util.SBetween.\nRequire Import CoqChess.Util.Dec.\nRequire Import CoqChess.Util.UIP.\n\nDefinition Fin (n : nat) : Type :=\n  { x : nat & x < n }.\n\nDefinition val : forall {n}, Fin n -> nat :=\n  fun n => @projT1 nat (fun x => x < n).\n\nDefinition val_small : forall {n} (i : Fin n), val i < n :=\n  fun n => @projT2 nat (fun x => x < n).\n\nLemma val_inj : forall {n} (i j : Fin n),\n  val i = val j -> i = j.\nProof.\n  induction n; intros.\n  { destruct i; lia. }\n  { destruct i,j; simpl in *.\n    destruct H.\n    f_equal; apply UIP.\n  }\nQed.\n\nDefinition Fin_0 {n} : Fin (S n).\nProof.\n  exists 0.\n  lia.\nDefined.\n\nDefinition Fin_S {n} : Fin n -> Fin (S n).\nProof.\n  intros [i Hi].\n  exists (S i).\n  lia.\nDefined.\n\nDefinition Fin_case {n} : forall (i : Fin (S n)),\n  (i = Fin_0) + {j : Fin n & i = Fin_S j}.\nProof.\n  intro i.\n  destruct (val i) eqn:?.\n  - left.\n    apply val_inj; auto.\n  - right.\n    destruct i as [i Hi].\n    destruct i.\n    + discriminate.\n    + simpl in *.\n      assert (i < n) as pf by lia.\n      exists (existT _ i pf).\n      apply val_inj.\n      reflexivity.\nDefined.\n\nFixpoint all_fin n : list (Fin n) :=\n  match n with\n  | 0 => []\n  | S m => Fin_0 :: List.map Fin_S (all_fin m)\n  end.\n\nLemma all_fin_In (n : nat) : forall i : Fin n,\n  In i (all_fin n).\nProof.\n  induction n.\n  - intros [n Hn]; lia.\n  - intro i.\n    destruct (Fin_case i).\n    + left; congruence.\n    + right.\n      destruct s as [j Hj].\n      rewrite Hj.\n      apply in_map.\n      apply IHn.\nQed.\n\nDefinition fin_dist {n} : Fin n -> Fin n -> nat :=\n  fun i j => dist (val i) (val j).\n\nLemma fin_dist_sym {n} : forall i j : Fin n,\n  fin_dist i j = fin_dist j i.\nProof.\n  intros.\n  apply dist_sym.\nQed.\n\nDefinition fin_sbetween {n} : Rel 3 (Fin n) :=\n  fun i j k => sbetween (val i) (val j) (val k).\n\nLemma fin_sbetween_sym {n} : forall i j k : Fin n,\n  fin_sbetween i j k -> fin_sbetween k j i.\nProof.\n  intros i j k; unfold fin_sbetween; apply sbetween_sym.\nQed.\n\n#[export] Instance Fin_Discrete : forall {n},\n  Discrete (Fin n).\nProof.\n  intros.\n  constructor.\n  intros i j.\n  destruct (Nat.eq_dec (val i) (val j)).\n  - left; apply val_inj; auto.\n  - right; congruence.\nDefined.\n\n#[export] Instance Fin_Exhaustible : forall {n},\n  Exhaustible (Fin n).\nProof.\n  intro n.\n  constructor.\n  induction n.\n  - intros P _.\n    right; intros [[] _]; lia.\n  - intros P Pd.\n    destruct (Pd Fin_0).\n    + left; exists Fin_0; auto.\n    + destruct (IHn (fun j => P (Fin_S j))).\n      * intro; apply Pd.\n      * left; destruct e as [j Hj].\n        exists (Fin_S j); auto.\n      * right; intros [i Hi].\n        destruct (Fin_case i) as [|[j Hj]].\n        ** congruence.\n        ** apply n1.\n           exists j; congruence.\nDefined.\n\n\n", "meta": {"author": "emarzion", "repo": "coqchess", "sha": "c5f69e87e169709e7c7d2a7c53b6623774d99bc5", "save_path": "github-repos/coq/emarzion-coqchess", "path": "github-repos/coq/emarzion-coqchess/coqchess-c5f69e87e169709e7c7d2a7c53b6623774d99bc5/src/Util/Fin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.6976769012644531}}
{"text": "(** * Selection:  Selection Sort, With Specification and Proof of Correctness*)\n(**\n  This sorting algorithm works by choosing (and deleting) the smallest\n  element, then doing it again, and so on.  It takes O(N^2) time.\n\n  You should never* use a selection sort.  If you want a simple\n  quadratic-time sorting algorithm (for small input sizes) you should\n  use insertion sort.  Insertion sort is simpler to implement, runs\n  faster, and is simpler to prove correct.   We use selection sort here\n  only to illustrate the proof techniques.\n\n     *Well, hardly ever.  If the cost of \"moving\" an element is _much_\n  larger than the cost of comparing two keys, then selection sort is\n  better than insertion sort.  But this consideration does not apply in our\n  setting, where the elements are  represented as pointers into the\n  heap, and only the pointers need to be moved.\n\n  What you should really never use is bubble sort.  Bubble sort\n  would be the wrong way to go.  Everybody knows that!\n  https://www.youtube.com/watch?v=k4RRi_ntQc8\n*)\n\n(* ################################################################# *)\n(** * The Selection-Sort Program  *)\n\nRequire Export Coq.Lists.List.\nFrom VFA Require Import Perm.\nFrom VFA Require Import Multiset.\n\n(** Find (and delete) the smallest element in a list. *)\n\nFixpoint select (x: nat) (l: list nat) : nat * list nat :=\nmatch l with\n|  nil => (x, nil)\n|  h::t => if x <=? h\n               then let (j, l') := select x t in (j, h::l')\n               else let (j,l') := select h t in (j, x::l')\nend.\n\n(** Now, selection-sort works by repeatedly extracting the smallest element,\n   and making a list of the results. *)\n\n(* Uncomment this function, and try it.\nFixpoint selsort l :=\nmatch l with\n| i::r => let (j,r') := select i r\n               in j :: selsort r'\n| nil => nil\nend.\n*)\n\n(** _Error: Recursive call to selsort has principal argument equal\n  to [r'] instead of [r]_.  That is, the recursion is not _structural_, since\n  the list r' is not a structural sublist of (i::r).  One way to fix the\n  problem is to use Coq's [Function] feature, and prove that\n  [length(r')<length(i::r)].  Later in this chapter, we'll show that approach.\n\n  Instead, here we solve this problem is by providing \"fuel\", an additional\n  argument that has no use in the algorithm except to bound the\n  amount of recursion.  The [n] argument, below, is the fuel. *)\n\nFixpoint selsort l n {struct n} :=\nmatch l, n with\n| x::r, S n' => let (y,r') := select x r\n               in y :: selsort r' n'\n| nil, _ => nil\n| _::_, O => nil  (* Oops!  Ran out of fuel! *)\nend.\n\n(** What happens if we run out of fuel before we reach the end\n   of the list?  Then WE GET THE WRONG ANSWER. *)\n\nExample out_of_gas: selsort [3;1;4;1;5] 3 <> [1;1;3;4;5].\nProof.\nsimpl.\nintro. inversion H.\nQed.\n\n(** What happens if we have have too much fuel?  No problem. *)\n\nExample too_much_gas: selsort [3;1;4;1;5] 10 = [1;1;3;4;5].\nProof.\nsimpl.\nauto.\nQed.\n\n(** The selection_sort algorithm provides just enough fuel. *)\n\nDefinition selection_sort l := selsort l (length l).\n\nExample sort_pi: selection_sort [3;1;4;1;5;9;2;6;5;3;5] = [1;1;2;3;3;4;5;5;5;6;9].\nProof.\nunfold selection_sort.\nsimpl.\nreflexivity.\nQed.\n\n(** Specification of correctness of a sorting algorithm:\n   it rearranges the elements into a list that is totally ordered. *)\n\nInductive sorted: list nat -> Prop :=\n | sorted_nil: sorted nil\n | sorted_1: forall i, sorted (i::nil)\n | sorted_cons: forall i j l, i <= j -> sorted (j::l) -> sorted (i::j::l).\n\nDefinition is_a_sorting_algorithm (f: list nat -> list nat) :=\n  forall al, Permutation al (f al) /\\ sorted (f al).\n\n(* ################################################################# *)\n(** * Proof of Correctness of Selection sort *)\n\n(** Here's what we want to prove. *)\n\nDefinition selection_sort_correct : Prop :=\n    is_a_sorting_algorithm selection_sort.\n\n(** We'll start by working on part 1, permutations. *)\n\n(** **** Exercise: 3 stars (select_perm)  *)\nLemma select_perm: forall x l,\n  let (y,r) := select x l in\n   Permutation (x::l) (y::r).\nProof.\n\n(** NOTE: If you wish, you may [Require Import Multiset] and use the  multiset\n  method, along with the theorem [contents_perm].  If you do,\n  you'll still leave the statement of this theorem unchanged. *)\n\nintros x l; revert x.\ninduction l; intros; simpl in *.\nauto.\nbdestruct (x <=? a).\n- remember (select x l). destruct p.\n  apply perm_trans with (l' := ((a :: x :: l))).\n  -- econstructor.\n  -- apply perm_trans with (l' := ((a :: n :: l0))).\n     * econstructor. specialize (IHl x). \n       remember (select x l). destruct Heqp. auto.\n     * econstructor.\n- remember (select a l). destruct p.\n  apply perm_trans with (l' := ((x :: n :: l0))).\n  -- constructor. \n     specialize (IHl a).\n     remember (select a l). destruct p.\n     eapply perm_trans. apply IHl. inv Heqp. auto.\n  -- constructor.\nQed. \n(** [] *)\n\nLemma select_perm_alt: forall x l y r,\n   (y,r) = select x l ->\n   Permutation (x::l) (y::r).\nProof.\n  intros.\n  assert (let (y,r) := select x l in\n   Permutation (x::l) (y::r)).\n  -- apply select_perm.\n  -- destruct H. auto.\nQed. \n\nLemma select_preserves_len: \n   forall  y r x l, ((y,r) = select x l) -> (length r) = (length l).\nProof.\n  intros. generalize dependent r. generalize dependent x.\n   generalize dependent y. induction l.\n  - intros. simpl in H. inv H. auto.\n  - intros. simpl in H. destruct (x <=? a).\n    -- destruct (select x l) eqn : T. inv H. simpl. f_equal. eapply IHl. eauto.\n    --  destruct (select a l) eqn : T. inv H.  simpl. f_equal. eapply IHl. eauto.\nQed.\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(** NOTE: If you wish, you may [Require Import Multiset] and use the  multiset\n  method, along with the theorem [same_contents_iff_perm]. *)\nintros.\n(* apply same_contents_iff_perm. *)\ngeneralize dependent l.\ninduction n.\n- intros. destruct l. simpl. auto. inv H.\n- intros. destruct l.\n  -- inv H.\n  -- simpl. \n     remember (select n0 l). destruct p.\n     apply perm_trans with (l' := (n1 :: l0)).\n     * apply select_perm_alt. auto.\n     * econstructor. apply IHn. simpl in H. inv H.\n       eapply select_preserves_len. eauto.\nQed.\n\nTheorem selection_sort_perm:\n  forall l, Permutation l (selection_sort l).\nProof.\n  unfold selection_sort. intros.\n  apply selsort_perm. auto.\nQed.\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] *)\nintros.\nassert (Permutation (x :: al) (y :: bl)).\n- apply select_perm_alt.  auto.\n- assert (Forall (fun z : nat => y <= z) (y :: bl)).\n  * constructor. auto. auto.\n  * assert (Forall (fun z : nat => y <= z) (x :: al)).\n    -- eapply Forall_perm.\n       2 : apply H2. apply Permutation_sym. auto.\n    -- inv H3. auto.\nQed.\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- inv H. auto.  \n- bdestruct (x <=? a).\n  * destruct (select x al) eqn:?H.\n    inv H. constructor.\n    --  eapply le_trans.\n        2 : apply H0.\n        eapply select_smallest_aux. eapply IHal. apply H1. apply H1.\n    -- eapply IHal. eauto. \n  * destruct (select a al) eqn:?H.\n    inv H.\n    constructor. \n    -- apply le_trans with (m := a).\n       **  eapply select_smallest_aux. eapply IHal. eauto. eauto.\n       **  omega.\n    -- eauto.\nQed.\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 intros.\n assert (Forall (fun z : nat => y <= z) (selsort bl (length bl)) ).\n - eapply Forall_perm. eapply selsort_perm. auto. auto.\n - destruct (selsort bl (length bl)) eqn : S.\n  -- constructor.\n  -- econstructor.\n    * inv H1. auto.\n    * auto.\nQed. \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]. *)\nremember (length al). generalize dependent al.\ninduction n.\n- intros. destruct al. simpl. constructor. simpl in Heqn. discriminate.\n- intros. destruct al. simpl in Heqn. discriminate.\n  remember (select n0 al). destruct p.\n  assert (sorted (n1 :: (selsort l n))).\n  -- assert (length l = n).\n     * simpl in Heqn.\n       replace n with (length al). \n       --- eapply select_preserves_len. eauto.\n       ---  omega.\n     * rewrite <- H. apply selection_sort_sorted_aux.\n       ** rewrite -> H. apply IHn. auto.\n       ** eapply select_smallest. rewrite -> Heqp. auto.\n  -- unfold selsort. rewrite <- Heqp. apply H.\nQed.\n\n(** [] *)\n\n(** Now we wrap it all up.  *)\n\nTheorem selection_sort_is_correct: selection_sort_correct.\nProof.\nsplit. apply selection_sort_perm. apply selection_sort_sorted.\nQed.\n\n(* ################################################################# *)\n(** * Recursive Functions That are Not Structurally Recursive *)\n\n(** [Fixpoint] in Coq allows for recursive functions where some\n  parameter is structurally recursive: in every call, the argument\n  passed at that parameter position is an immediate substructure\n  of the corresponding formal parameter.  For recursive functions\n  where that is not the case -- but for which you can still prove\n  that they terminate -- you can use a more advanced feature of\n  Coq, called [Function]. *)\n\nRequire Import Recdef.  (* needed for [Function] feature *)\n\nFunction selsort' l {measure length l} :=\nmatch l with\n| x::r => let (y,r') := select x r\n               in y :: selsort' r'\n| nil => nil\nend.\n\n(** When you use [Function] with [measure], it's your\n  obligation to prove that the measure actually decreases,\n  before you can use the function. *)\n\nProof.\nintros.\npose proof (select_perm x r).\nrewrite teq0 in H.\napply Permutation_length in H.\nsimpl in *; omega.\nDefined.  (* Use [Defined] instead of [Qed], otherwise you\n  can't compute with the function in Coq. *)\n\n(** **** Exercise: 3 stars (selsort'_perm)  *)\nLemma selsort'_perm:\n  forall n,\n  forall l, length l = n -> Permutation l (selsort' l).\nProof.\n\n(** NOTE: If you wish, you may [Require Import Multiset]\n  and use the  multiset method, along with the\n  theorem [same_contents_iff_perm]. *)\n\n(** Important!  Don't unfold [selsort'], or in general, never\n  unfold anything defined with [Function]. Instead, use the\n  recursion equation [selsort'_equation] that is automatically\n  defined by the [Function] command. *)\n\n  intros. generalize dependent l.\n  induction n; intros.\n  - destruct l. auto. simpl in H. inv H.\n  - destruct l. simpl in H. inv H.\n    remember (select n0 l). destruct p.\n    rewrite -> selsort'_equation. rewrite <- Heqp.\n    apply perm_trans with (l' := (n1 :: l0)).\n    * apply select_perm_alt. auto.\n    * econstructor. apply IHn. simpl in H. replace n with (length l).\n      -- eapply select_preserves_len. eauto.\n      -- omega.\n(** [] *)\n\nEval compute in selsort' [3;1;4;1;5;9;2;6;5].\n\n(** $Date$ *)\n", "meta": {"author": "simpadjo", "repo": "coq-excercises", "sha": "7b9657412746b3d64798b840f040403e9c99e83c", "save_path": "github-repos/coq/simpadjo-coq-excercises", "path": "github-repos/coq/simpadjo-coq-excercises/coq-excercises-7b9657412746b3d64798b840f040403e9c99e83c/vfa/Selection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.8740772335247532, "lm_q1q2_score": 0.6976768989150441}}
{"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.\nRequire Import String.\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\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\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\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)\n  end.\n\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\n\n(* proved in Imp *)\nAxiom optimize_0plus_sound: forall a, aeval (optimize_0plus a) = aeval a.\n\n\n(** **** Exercise: 3 stars (optimize_0plus_b)  *)\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: forall b, beval (optimize_0plus_b b) = beval b.\nProof.\n  intros b.\n  induction b;\n    try (\n      reflexivity\n    );\n    try (\n      simpl;\n      repeat (rewrite optimize_0plus_sound);\n      reflexivity\n    ).\n  - simpl.\n    rewrite IHb.\n    reflexivity.\n  - simpl.\n    rewrite IHb1.\n    rewrite IHb2.\n    reflexivity.\nQed.\n\n\n(** **** Exercise: 4 stars, optional (optimizer)  *)\n(* not do it *)\n\n\nEnd AExp.\n\n\n\n\nInductive id: Type :=\n  | Id: string -> id.\n\nDefinition beq_id x y :=\n  match x, y with\n  | Id n1, Id n2 => if string_dec n1 n2 then true else false\n  end.\n\nDefinition total_map (A: Type) := id -> A.\n\nDefinition t_empty {A: Type}(v: A): total_map A := (fun _ => v).\n\nDefinition t_update {A:Type}(m: total_map A)(x: id)(v: A) :=\n  fun x' => if beq_id x x' then v else m x'.\n\n\nDefinition state := total_map nat.\n\nDefinition empty_state : state :=  t_empty 0.\n\n\nInductive aexp : Type :=\n  | ANum : nat -> aexp\n  | AId : id -> aexp                (* <----- NEW *)\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                                (* <----- NEW *)\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   => 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\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\n\nNotation \"'SKIP'\" := CSkip.\nNotation \"x '::=' a\" := (CAss x a) (at level 60).\nNotation \"c1 ;; c2\" := (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\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 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_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\n  where \"c1 '/' st '\\\\' st'\" := (ceval c1 st st').\n\n\n(** **** Exercise: 2 stars (ceval_example2)  *)\nExample ceval_example2:\n    (X ::= ANum 0;; Y ::= ANum 1;; Z ::= ANum 2) / empty_state \\\\\n    (t_update (t_update (t_update empty_state X 0) Y 1) Z 2).\nProof.\n  apply E_Seq with (t_update empty_state X 0).\n  - apply E_Ass.\n    reflexivity.\n  - apply E_Seq with (t_update (t_update empty_state X 0) Y 1).\n    + apply E_Ass.\n      reflexivity.\n    + apply E_Ass.\n      reflexivity.\nQed.\n\n\n\n(** **** Exercise: 3 stars, advanced (pup_to_n)  *)\n\nDefinition pup_to_n: com :=\n  Y ::= ANum 0;;\n  WHILE (BLe (AId X) (ANum 0)) DO\n    Y ::= APlus (AId X) (AId Y);;\n    X ::= AMinus (AId X) (ANum 1)\n  END.\n\n(*\nTheorem pup_to_2_ceval :\n  pup_to_n / (t_update empty_state X 2) \\\\\n    t_update (t_update (t_update (t_update (t_update (t_update empty_state\n      X 2) Y 0) Y 2) X 1) Y 3) X 0.\nProof.\n  unfold pup_to_n.\n  apply E_Seq with (t_update (t_update empty_state X 2) Y 0).\n  - apply E_Ass.\n    reflexivity.\nAbort.\n*)\n\n\n(** **** Exercise: 3 stars, recommendedM (XtimesYinZ_spec)  *)\nDefinition XtimesYinZ : com := Z ::= (AMult (AId X) (AId Y)).\n\n(* proved in Maps *)\nAxiom t_update_eq: forall A (m: total_map A) x v, (t_update m x v) x = v.\n\n\nTheorem xtimesyinz_spec: forall st n m st',\n  st X = n ->\n  st Y = m ->\n  XtimesYinZ / st \\\\ st' ->\n  st' Z = n * m.\nProof.\n  intros st n m st' H P Q.\n  inversion Q.\n  subst.\n  simpl.\n  apply t_update_eq.\nQed.\n\n\n(* More exercises *)\n\n\n\n\n\n\n\n\n\n\n\n\n\n(** **** Exercise: 3 stars (stack_compiler)  *)\n\nModule stack_compiler.\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\n\n\nInductive sinstr: Type :=\n  | SPush: nat -> sinstr\n  | SLoad: id -> sinstr\n  | SPlus: sinstr\n  | SMinus: sinstr\n  | SMult: sinstr\n  .\n\n\nFixpoint s_execute (st: state)(stack: list nat)(prog: list sinstr): list nat :=\n  match prog with\n  | nil => stack\n  | SPush n :: h  => s_execute st (n :: stack) h\n  | SLoad id :: h => s_execute st (st id :: stack) h\n  | SPlus :: h => \n    match stack with\n    | x :: y :: t => s_execute st ((y + x) :: t) h\n    | _ => stack \n    end\n  | SMinus :: h =>\n    match stack with\n    | x :: y :: t => s_execute st ((y - x) :: t) h\n    | _ => stack\n    end\n  | SMult :: h =>\n    match stack with\n    | x :: y :: t => s_execute st ((y * x) :: t) h\n    | _ => stack\n    end\n  end.\n\n\n\nExample s_execute1: s_execute empty_state [] [SPush 5; SPush 3; SPush 1; SMinus] = [2; 5].\nProof. reflexivity. Qed.\n\nDefinition X: id := Id \"X\".\nDefinition Y: id := Id \"Y\".\n\nExample s_execute2: s_execute (t_update empty_state X 3) [3;4][SPush 4; SLoad X; SMult; SPlus]\n   = [15; 4].\nProof. reflexivity. Qed.\n\n\nFixpoint s_compile (e: aexp): list sinstr :=\n  match e with\n  | ANum n =>     SPush n :: nil\n  | AId id =>     SLoad id :: nil\n  | APlus x y =>  s_compile x ++ s_compile y ++ [SPlus]\n  | AMinus x y => s_compile x ++ s_compile y ++ [SMinus] \n  | AMult x y =>  s_compile x ++ s_compile y ++ [SMult]\n  end.\n\n\nExample s_compile1: s_compile (AMinus (AId X) (AMult (ANum 2) (AId Y)))\n  = [SLoad X; SPush 2; SLoad Y; SMult; SMinus].\nProof. reflexivity. Qed.\n\nEnd stack_compiler.\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/Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.6976768912941497}}
{"text": "(* infotheo (c) AIST. R. Affeldt, M. Hagiwara, J. Senizergues. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq path div fintype.\nFrom mathcomp Require Import tuple finfun bigop.\nRequire Import Reals Fourier.\nRequire Import Reals_ext Rssr Rbigop log2 ln_facts proba divergence.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(** * Entropy of a distribution *)\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) (at level 5).\n\nLemma entropy_pos : 0 <= `H.\nProof.\nrewrite /entropy big_endo; last 2 first.\n  move=> *; by rewrite Ropp_plus_distr.\n  by rewrite Ropp_0.\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 Rle_big_0_P_g => i _.\ncase: (Req_EM_T (P i) 0).\n  (* NB: this step in a standard textbook would be handled as a\n     consequence of lim x->0 x log x = 0 *)\n  move=> ->.\n  rewrite Rmult_0_l.\n  fourier.\nmove=> Hi.\nrewrite Rmult_comm -Ropp_mult_distr_l_reverse.\napply Rmult_le_pos; last by apply Rle0f.\napply Ropp_0_ge_le_contravar, Rle_ge.\nrewrite -log_1.\napply log_increasing_le.\nmove: (Rle0f P i) => abs'.\napply Rnot_le_lt => abs.\nmove: (Rle_antisym _ _ abs' abs) => abs''; by rewrite abs'' in Hi.\nby apply dist_max.\nQed.\n\nHypothesis P_pos : forall b, 0 < P b.\n\nLemma entropy_pos_P_pos : 0 <= `H.\nProof.\nrewrite /entropy big_endo; last 2 first.\n  move=> *; by rewrite Ropp_plus_distr.\n  by rewrite Ropp_0.\nrewrite (_ : \\rsum_(_ in _) _ = \\rsum_(i in A | predT A) - (P i * log (P i))).\n  apply Rle_big_0_P_g => i _.\n  rewrite Rmult_comm -Ropp_mult_distr_l_reverse.\n  apply Rmult_le_pos; last by apply Rle0f.\n  apply Ropp_0_ge_le_contravar, Rle_ge.\n  rewrite -log_1.\n  apply log_increasing_le; by [apply P_pos | apply dist_max].\napply eq_bigl => i /=; by rewrite inE.\nQed.\n\nEnd entropy_definition.\n\nNotation \"'`H'\" := (entropy) (at level 5) : 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 /Ex_alt /= (big_morph _ morph_Ropp Ropp_0).\napply eq_bigr => a _; by rewrite mulRC -Ropp_mult_distr_l_reverse.\nQed.\n\nLemma xlnx_entropy {A} (P : dist A) :\n  `H P = / ln 2 * - \\rsum_(a : A) xlnx (P a).\nProof.\nrewrite /entropy; f_equal; rewrite Ropp_mult_distr_r_reverse; f_equal.\nrewrite (big_morph _ (morph_mulRDr _) (mulR0 _)).\napply eq_bigr => a _ ;rewrite /log /Rdiv mulRA mulRC; f_equal.\nrewrite /xlnx; case : ifP => // /RltP Hcase.\nhave : P a = 0; last by move=> ->; rewrite mul0R.\ncase (Rle_lt_or_eq_dec 0 (P a)) => //; by apply Rle0f.\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_Rplus /Rdiv mul1R mulRA Rinv_r; last first.\n  rewrite HA; by apply not_0_INR.\nrewrite mul1R log_Rinv; last by rewrite HA; apply lt_0_INR; apply/ltP.\nby rewrite Ropp_involutive.\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_support_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.\neapply Rle_trans; first by apply H.\napply 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 _.\n  by rewrite mulRDr.\nrewrite /= /Uniform.f /= /Rdiv mul1R.\nrewrite -[in X in _ + X = _]big_distrl /= pmf1 mul1R.\nrewrite /entropy Ropp_involutive.\nrewrite log_Rinv; last first.\n  rewrite HA.\n  apply lt_0_INR; by apply/ltP.\nby rewrite Ropp_involutive.\nQed.\n", "meta": {"author": "johnbender", "repo": "shannon", "sha": "552c66f7c76ad687430f4fb8122a2a2b94b741ee", "save_path": "github-repos/coq/johnbender-shannon", "path": "github-repos/coq/johnbender-shannon/shannon-552c66f7c76ad687430f4fb8122a2a2b94b741ee/entropy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846387, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.6976768892135675}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_oppositesidesymmetric.\nRequire Export GeoCoq.Elements.OriginalProofs.proposition_27.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma proposition_28A : \n   forall A B C D E G H, \n   BetS A G B -> BetS C H D -> BetS E G H -> CongA E G B G H D -> OS B D G H ->\n   Par A B C D.\nProof.\nintros.\nassert (OS D B G H) by (forward_using lemma_samesidesymmetric).\nassert (nCol E G B) by (conclude_def CongA ).\nassert (eq G G) by (conclude cn_equalityreflexive).\nassert (Col G H G) by (conclude_def Col ).\nassert (~ Col G H A).\n {\n intro.\n assert (Col H G A) by (forward_using lemma_collinearorder).\n assert (Col E G H) by (conclude_def Col ).\n assert (Col H G E) by (forward_using lemma_collinearorder).\n assert (neq G H) by (forward_using lemma_betweennotequal).\n assert (neq H G) by (conclude lemma_inequalitysymmetric).\n assert (Col G A E) by (conclude lemma_collinear4).\n assert (Col A G E) by (forward_using lemma_collinearorder).\n assert (Col A G B) by (conclude_def Col ).\n assert (neq A G) by (forward_using lemma_betweennotequal).\n assert (Col G E B) by (conclude lemma_collinear4).\n assert (Col E G B) by (forward_using lemma_collinearorder).\n contradict.\n }\nassert (TS A G H B) by (conclude_def TS ).\nassert (TS B G H A) by (conclude lemma_oppositesidesymmetric).\nassert (BetS B G A) by (conclude axiom_betweennesssymmetry).\nassert (CongA E G B A G H) by (conclude proposition_15a).\nassert (CongA A G H E G B) by (conclude lemma_equalanglessymmetric).\nassert (CongA A G H G H D) by (conclude lemma_equalanglestransitive).\nassert (TS D G H A) by (conclude lemma_planeseparation).\nassert (TS A G H D) by (conclude lemma_oppositesidesymmetric).\nassert (Par A B C D) by (conclude proposition_27).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/proposition_28A.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.6976768834394436}}
{"text": "Set Implicit Arguments.\n\nRequire Import\n        Discrete.DiscType\n        Discrete.DupFree\n        Discrete.In \n        Tactics.Tactics.\n\n(** function to count the number of an element in\n    a list *)\n\nFixpoint count {A : discType}(xs : list A)(x : A) : nat :=\n  match xs with\n  | nil => 0\n  | (cons y ys) => if decision (x = y) then 1 + (count ys x) else count ys x\n  end.\n\n(** some facts about count *)\n\nLemma count_not_in_iff {A : discType}\n  : forall (xs : list A)(x : A), ~ (x el xs) <-> count xs x = 0.\nProof.\n  induction xs as [ | x xs] ; crush.\n  +\n    destruct (decision (x0 = x)) ; crush.\n    apply IHxs ; auto.\n  +\n    destruct (decision (x = x)) ; crush.\n  +\n    destruct* (decision (x0 = x)) as [G | G]; crush.\n    specialize (IHxs x0).\n    destruct IHxs. specialize (H2 H) ; crush.\nQed.\n\nHint Resolve count_not_in_iff.\n\nLemma count_in_gt_zero {A : discType}\n  : forall (xs : list A)(x : A), x el xs <-> count xs x > 0.\nProof.\n  induction xs as [| x xs ] ; crush.\n  +\n    destruct* (decision (x = x)) ; crush.\n  +\n    destruct* (decision (x0 = x)) ; crush.\n    destruct* (IHxs x0) ; crush.\n  +\n    destruct (decision (x0 = x)) ; crush.\nQed.\n\nLemma count_in_dupfree {A : discType} (xs : list A) x\n  : dup_free xs -> x el xs -> count xs x = 1.\nProof.\n  intros H ; revert x ; induction H as [| x xs] ; intros y H1 ; simpl in *.\n  +\n    crush.\n  +\n    destruct H1 as [H1 | H1] ; substs.\n    *\n      decide (x = x) as [G | G].\n      - \n        specialize (count_not_in_iff xs x) ; intros H2.\n        destruct* H2.\n      -\n        crush.\n    *\n      specialize (IHdup_free y H1).\n      rewrite IHdup_free.\n      decide (y = x) as [G | G] ; substs* ; crush.\nQed.      \n\nLemma count_lt_dup_free {A : discType}(xs : list A)\n  : (forall x, count xs x <= 1) -> dup_free xs.\nProof.\n  induction xs as [| x xs] ; eauto.\n  -\n    intro H. constructor.\n    +\n      cbn in H.  specialize (H x). decide (x = x).\n      assert (Hz : count xs x = 0) by omega. apply count_not_in_iff in Hz ; eauto.\n      crush.\n    +\n      apply IHxs. intro y. specialize (H y). cbn in H. decide (y = x) ; omega.\nQed.\n\nLemma count_app {A : discType}(xs ys : list A) x\n  : count (xs ++ ys) x = count xs x + count ys x.\nProof.\n  induction xs ; crush.\n  +\n    decide (x = a) ; crush.\nQed.\n\n(** dealing with options *)\n\nDefinition to_option_list {A : Type} (xs : list A) :=\n    None :: map (@Some _) xs.\n\nLemma count_option_list (A : discType) (xs : list A) x\n  : count (to_option_list xs) (Some x) = count xs x .\nProof.\n  unfold to_option_list. simpl. dec ; try congruence.\n  induction xs ; crush.\n  +\n    dec ; congruence.\nQed.\n\n(** A list produced by toOptionList contains None exactly once *)\n\nLemma count_option_list_none (A : discType) (xs : list A)\n  : count (to_option_list xs) None = 1.\nProof.\n  unfold to_option_list. simpl. dec ; try congruence. f_equal.\n    induction xs as [| x xs] ; crush.\n  -\n    simpl; dec; congruence.\n Qed.\n\nLemma dup_free_count\n      (A : discType)\n      (x : A)\n      (xs : list A)\n  : dup_free xs -> x el xs -> count xs x = 1.\nProof.\n  intros D E. induction D.\n  -\n    contradiction E.\n  -\n    cbn.\n    dec.\n    +\n      f_equal.\n      subst x0.\n      apply count_not_in_iff. auto.\n    +\n      destruct E as [E | E] ; [> congruence | auto].\nQed.        \n\n", "meta": {"author": "rodrigogribeiro", "repo": "finite_types", "sha": "27582ce97686654d741bca49a0f091a68a3dc89d", "save_path": "github-repos/coq/rodrigogribeiro-finite_types", "path": "github-repos/coq/rodrigogribeiro-finite_types/finite_types-27582ce97686654d741bca49a0f091a68a3dc89d/Discrete/Count.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.6976580407317337}}
{"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\nTheorem S_inj : injective S.\nProof.\n  intros x y H. injection H as goal.\n  apply goal. Qed.\n\nCheck @eq : forall A : Type, A -> A -> Prop.\n\nExample and_example: 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  split.\n  - reflexivity.\n  - reflexivity. Qed.\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. Qed.\n\nExample and_example': 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro.\n  - reflexivity.\n  - reflexivity. Qed.\n\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'] eqn:En.\n  - destruct m as [| m'] eqn:Em.\n    + split.\n      * reflexivity.\n      * reflexivity.\n    + discriminate H.\n  - discriminate H. Qed.\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. Qed.\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  intros n m H. apply and_exercise in H.\n  destruct H as [Hn Hm]. rewrite Hn. rewrite Hm.\n  reflexivity. Qed.\n\nLemma proj1 : forall P Q : Prop,\n    P /\\ Q -> P.\nProof.\n  intros P Q H. destruct H as [HP _]. apply HP. Qed.\n\nLemma proj2 : forall P Q : Prop,\n    P /\\ Q -> Q.\nProof.\n  intros P Q H. destruct H as [_ HQ]. apply HQ. Qed.\n\nTheorem and_commut : forall P Q : Prop,\n    P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q H. destruct H as [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.\n  intros P Q R [HP [HQ HR]]. split.\n  - split.\n    + apply HP.\n    + apply HQ.\n  - apply HR. Qed.\n\nCheck and : Prop -> Prop -> Prop.\n\nSearch (_ * 0 = 0).\n\nLemma eq_mult_0 : 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. reflexivity. Qed.\n\nLemma or_intro_l : forall A B : Prop,\n    A -> A \\/ B.\nProof.\n  intros A B H. left. apply H. Qed.\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  intro n. destruct n as [| n'] eqn:E.\n  - left. reflexivity.\n  - right. reflexivity. Qed.\n\nModule MyNot.\n  Definition not (P : Prop) := P -> False.\n\n  Notation \"~ x\" := (not x) : type_scope.\n\n  Check not : Prop -> Prop.\nEnd MyNot.\n\nTheorem ex_falso_quodlibet : forall (P : Prop), False -> P.\nProof.\n  intros P contra. destruct contra. Qed.\n\nTheorem implies_false_implies_neg : forall (P : Prop),\n    (P -> False) -> ~ P.\nProof.\n  intros P H. unfold not. apply H. Qed.\n\nTheorem not_p_implies_q_implies_p_and_not_q :\n  forall (P Q : Prop), ~ (P -> Q) -> ~ P /\\ Q.\nProof.\n  intros P Q H. Abort.\n\nExample implication_test : forall (P Q : Prop),\n    ((P -> Q) -> False) -> P.\nProof.\n  intros P Q HnPQ. apply implies_false_implies_neg in HnPQ. Abort.\n  \nFact not_implies_our_not : forall (P : Prop),\n    ~ P -> (forall Q : Prop, P -> Q).\nProof.\n  intros P HnP Q HP. destruct HnP. apply HP. Qed.\n\nNotation \"x <> y\" := (~ (x = y)).\n\nTheorem zero_not_one : 0 <> 1.\nProof.\n  unfold not. intro H. discriminate H. Qed.\n\nTheorem not_false : ~ False.\nProof.\n  unfold not. intro H. destruct H. Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n    (P /\\ ~P) -> Q.\nProof.\n  intros P Q [HP HNA]. unfold not in HNA.\n  apply HNA in HP. destruct HP. Qed.\n\nTheorem double_neg : forall P : Prop,\n    P -> ~~P.\nProof.\n  intros P HP. unfold not. intros HNA.\n  apply HNA in HP. destruct HP. Qed.\n\nTheorem contrapositive : forall P Q : Prop,\n    (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q HPQ. unfold not. intro HNQ. intro HP.\n  apply HPQ in HP. apply HNQ in HP. destruct HP. Qed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n    ~ (P /\\ ~P).\nProof.\n  intro P. unfold not. intros [HP HNP].\n  apply HNP in HP. destruct HP. Qed.\n\nTheorem not_true_is_false : forall b : bool,\n    b <> true -> b = false.\nProof.\n  intros b H. unfold not in H.\n  destruct b.\n  - apply ex_falso_quodlibet. apply H. reflexivity.\n  - reflexivity. Qed.\n\nTheorem not_true_is_false' : forall b : bool,\n    b <> true -> b = false.\nProof.\n  intros b H. destruct b eqn:Eb.\n  - unfold not in H. exfalso.\n    apply H. reflexivity.\n  - reflexivity. Qed.\n\nCheck I : True.\n\nModule MyIff.\n  Definition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\n  Notation \"P <-> Q\" := (iff P Q)\n                          (at level 95, no associativity)\n                        : type_scope.\nEnd MyIff.\n\nTheorem iff_sym : forall (P Q : Prop),\n    (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q. unfold iff. intros [HPQ HQP]. split.\n  - apply HQP.\n  - apply HPQ. Qed.\n\nLemma not_true_iff_false : forall b : bool,\n    b <> true <-> b = false.\nProof.\n  unfold iff. split.\n  - apply not_true_is_false.\n  - intro H. rewrite H. intro H'. discriminate H'. 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. unfold iff. split.\n  - intros [HP | HQR].\n    + split.\n      * left. apply HP.\n      * left. apply HP.\n    + destruct HQR as [HQ HR]. split.\n      * right. apply HQ.\n      * right. apply HR.\n  - intros [HPoQ HPoR]. destruct HPoQ as [HP | HQ].\n    + destruct HPoR as [HP' | HR].\n      * left. apply HP.\n      * left. apply HP.\n    + destruct HPoR as [HP' | HR].\n      * left. apply HP'.\n      * right. split.\n        apply HQ. apply HR. Qed.\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - destruct n as [| n'].\n    + destruct m as [| m'].\n      * intro H. left. reflexivity.\n      * intro H. left. reflexivity.\n    + destruct m as [| m'].\n      * intro H. right. reflexivity.\n      * intro H. simpl in H. discriminate H.\n  - apply eq_mult_0.\nQed.\n\nTheorem or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R. split.\n  - intros [H | [H | H]].\n    + left. left. apply H.\n    + left. right. apply H.\n    + right. apply H.\n  - intros [[H | H] | H].\n    + left. apply H.\n    + right. left. apply H.\n    + right. right. apply H.\nQed.\n\nLemma mult_0_3 : forall n m p,\n    n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p. rewrite mult_0. rewrite mult_0.\n  rewrite or_assoc. reflexivity. Qed.\n\nDefinition Even x := exists n : nat, x = double n.\n\nTheorem four_is_even : Even 4.\nProof.\n  unfold even. exists 2. reflexivity. Qed.\n\nTheorem exists_example_2 : forall n,\n    (exists m, n = 4 + m) ->\n    (exists o, n = 2 + o).\nProof.\n  intro n. intros [m Hm]. exists (2 + m).\n  apply Hm. Qed.\n\nTheorem dist_not_exists {X : Type} (P : X -> Prop) :\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  intros HA [x HE]. unfold not in HE.\n  apply HE. apply HA. Qed.\n\nTheorem dist_exists_or {X : Type} (P Q : X -> Prop) :\n  (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n  unfold iff. split.\n  - intros H. destruct H as [x HE] eqn:E.\n    destruct HE as [HP | HQ].\n    + left. exists x. apply HP.\n    + right. exists x. apply HQ.\n  - intros HE. destruct HE as [HP | HQ].\n    + destruct HP as [x HE]. exists x. left. apply HE.\n    + destruct HQ as [x HE]. exists x. right. apply HE. Qed.\n\nFixpoint In {X : Type} (x : X) (l : list X) : Prop :=\n  match l with\n  | [] => False\n  | h :: t => h = x \\/ In x t\n  end.\n\nExample In_example_1 : In 4 [1; 2; 3; 4; 5].\nProof.\n  simpl. right. right. right. left. reflexivity. Qed.\n\nExample In_example_2 : forall n, In n [2; 4] -> exists n', n = 2 * n'.\nProof.\n  simpl. intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity. Qed.\n\nTheorem 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  induction l as [| h t IHt].\n  - intros x. simpl. intros [].\n  - simpl. intros x [Hhx | Hin].\n    + left. rewrite Hhx. reflexivity.\n    + right. apply IHt. apply Hin. Qed.\n\nTheorem In_map_iff : forall (A B : Type) (f : A -> B)\n                       (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 IHt].\n    + intros [].\n    + simpl. intros [Hfh | Hy].\n      * (* f h = y *) exists h. rewrite Hfh. split.\n        reflexivity. left. reflexivity.\n      * (* In y (map f t) *) apply IHt in Hy.\n        destruct Hy as [x [Hy Hin]]. exists x. split.\n        apply Hy. right. apply Hin.\n  - intros [x [Hy Hin]]. rewrite <- Hy. apply In_map.\n    apply Hin. Qed.\n\nTheorem In_app_iff : forall (A : Type) (l l' : list A) (a : A),\n    In a (l ++ l') <-> (In a l) \\/ (In a l').\nProof.\n  intros A l. split.\n  - induction l as [| h t IHt].\n    + (* In a l' *) simpl. intro H. right. apply H.\n    + (* In a h::t *) simpl. intros [Hha | Hin].\n      * left. left. apply Hha.\n      * apply or_assoc. right. apply IHt. apply Hin.\n  - induction l as [| h t IHt].\n    + (* In a l' *) simpl. intros [[] | H]. apply H.\n    + (* In a h::t *) simpl. rewrite <- or_assoc.\n      intros [Hha | Hin].\n      * left. apply Hha.\n      * right. apply IHt. apply Hin. Qed.\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\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. split.\n  - intro H. induction l as [| h t IHt].\n    + reflexivity.\n    + simpl. simpl in H. split.\n      * (* P h *) apply H. left. reflexivity.\n      * (* All P t *) apply IHt. intros x Hin.\n        apply H. right. apply Hin.\n  - intro H. induction l as [| h t IHt].\n    + intros x Hin. simpl in Hin. destruct Hin.\n    + simpl in H. destruct H as [HPh HPt].\n      simpl. intros x H. destruct H as [Hh | Ht].\n      * rewrite <- Hh. apply HPh.\n      * apply IHt. apply HPt. apply Ht. Qed.\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop\n  := fun n : nat =>\n       match (odd n) with\n       | true => Podd n\n       | false => Peven n\n       end.\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. destruct (odd n) eqn:E.\n  - intros Hodd Heven. unfold combine_odd_even.\n    rewrite E. apply Hodd. reflexivity.\n  - intros Hodd Heven. unfold combine_odd_even.\n    rewrite E. 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    odd n = true ->\n    Podd n.\nProof.\n  intros Podd Peven n H. unfold combine_odd_even in H.\n  intro Hodd. rewrite Hodd in H. apply H. Qed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    even n = true ->\n    Peven n.\nProof.\n  intros Podd Peven n H. unfold combine_odd_even in H.\n  intro Heven. unfold odd in H. rewrite Heven in H.\n  simpl in H. apply H. Qed.\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. assert (H2: disc_fn O).\n  { reflexivity. }\n  rewrite H1 in H2. simpl in H2. apply H2. Qed.\n\nCheck add_comm.\n\nTheorem in_not_nil : forall (X : Type) (x : X) (l : list X),\n    In x l -> l <> [].\nProof.\n  intros X x l H. unfold not. intro Hl.\n  rewrite Hl in H. simpl in H. apply H. Qed.\n\nTheorem in_not_nil_42 : forall (l : list nat),\n    In 42 l -> l <> [].\nProof.\n  intros l H. apply in_not_nil with (x:=42).\n  apply H. Qed.\n\nTheorem in_not_nil_42' : forall (l : list nat),\n    In 42 l -> l <> [].\nProof.\n  intros l H. apply in_not_nil in H.\n  apply H. Qed.\n\nTheorem in_not_nil_42'' : forall (l : list nat),\n    In 42 l -> l <> [].\nProof.\n  intros l H. Check (in_not_nil nat 42).\n  apply (in_not_nil nat 42). apply H. Qed.\n\nTheorem in_not_nil_42''' : forall (l : list nat),\n    In 42 l -> l <> [].\nProof.\n  intros l H. Check (in_not_nil _ _ _ H).\n  apply (in_not_nil _ _ _ H). Qed.\n\nModule MyPlayground.\n  Theorem matching_test : forall (x : nat) (P : nat -> Prop), P x -> P (S x).\n  Admitted.\n\n  Theorem matching_test' : forall (P : nat -> Prop),\n      P 12 -> P (S 12).\n  Proof.\n    intros P H. Check (matching_test _ _ H). Abort.\nEnd MyPlayground.\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. intro x.\n  apply add_comm. Qed.\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\nCompute rev_append [1;2;3] [7;8;9].\nCompute tr_rev [1;2;3].\nCompute rev [1;2;3].\n\nFixpoint app' (l1 l2 : list nat) : list nat :=\n  match l1 with\n  | [] => l2\n  | x :: l1' => x :: (app' l1' l2)\n  end.\n\nTheorem tr_rev_correct : forall X,  @tr_rev X = @rev X.\nProof.\n  intro X. apply functional_extensionality.\n  intro l. induction l as [| h t IHt].\n  - reflexivity.\n  - unfold tr_rev. simpl.\n    assert (H: forall l l1 l2 : list X, rev_append l (l1 ++ l2) = rev_append l l1 ++ l2).\n    { induction l as [| h' t' IHt'].\n      - reflexivity.\n      - intros l1 l2. simpl. rewrite <- IHt'. reflexivity. }\n    rewrite H with (l1:=[]) (l2:=[h]). f_equal. rewrite <- IHt.\n    reflexivity. Qed.\n\nLemma evenb_double : forall k,\n    even (double k) = true.\nProof.\n  intro k. induction k as [| k' IHk'].\n  - reflexivity.\n  - simpl. apply IHk'. Qed.\n\nLemma evenb_double_conv : forall n, exists k,\n      n = if even n then double k else S (double k).\nProof.\n  intro n. induction n as [| n' IHn'].\n  - exists 0. reflexivity.\n  - destruct IHn' as [k H]. destruct (even n') eqn:E.\n    + rewrite even_S. rewrite E. simpl. exists k.\n      rewrite H. reflexivity.\n    + rewrite even_S. rewrite E. simpl. exists (S k).\n      simpl. rewrite H. reflexivity. Qed.\n\nTheorem even_bool_prop : forall n : nat,\n    even n = true <-> Even n.\nProof.\n  split.\n  - intro H. destruct (evenb_double_conv n) as [k Hn].\n    rewrite H in Hn. exists k. apply Hn.\n  - intros [k Hn]. rewrite Hn. apply evenb_double. Qed.\n\nExample not_even_1001' : ~ (Even 1001).\nProof.\n  rewrite <- even_bool_prop.\n  unfold not.\n  simpl.\n  intro H.\n  discriminate H.\nQed.\n\nLemma eqb_eq : forall n m : nat, (n =? m) = true <-> n = m.\nProof.\n  split.\n  - generalize dependent m. induction n as [| n' IHn'].\n    + destruct m as [| m'] eqn:Em.\n      * reflexivity.\n      * discriminate.\n    + destruct m as [| m'] eqn:Em.\n      * discriminate.\n      * intro H. f_equal. apply IHn'.\n        simpl in H. apply H.\n  - intro H. rewrite H. apply eqb_refl. Qed.\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\nTheorem andb_true_iff : forall b1 b2 : bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros b1 b2. split.\n  - intro H. split.\n    + destruct b1. reflexivity. discriminate H.\n    + destruct b1.\n      * simpl in H. apply H.\n      * simpl in H. discriminate H.\n  - intros [H1 H2]. rewrite H1. rewrite H2. reflexivity. Qed.\n\nTheorem orb_true_iff : forall b1 b2 : bool,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros b1 b2. split.\n  - intro H. destruct b1.\n    + left. reflexivity.\n    + right. simpl in H. apply H.\n  - intros [H1 | H2].\n    + rewrite H1. reflexivity.\n    + rewrite H2. destruct b1.\n      * reflexivity.\n      * reflexivity. Qed.\n\nTheorem eqb_neq : forall n m : nat, (n =? m) = false <-> n <> m.\nProof.\n  intros n m. rewrite <- not_true_iff_false.\n  unfold not. rewrite eqb_eq. reflexivity. Qed.\n\nFixpoint eqb_list {A : Type}\n         (eqb : A -> A -> bool)\n         (l1 l2 : list A) : bool :=\n  match l1, l2 with\n  | [], [] => true\n  | [], _ | _, [] => false\n  | h1 :: t1, h2 :: t2 =>\n    (eqb h1 h2) && (eqb_list eqb t1 t2)\n  end.\n\nTheorem eqb_list_true_iff :\n  forall (A : Type) (eqb : A -> A -> bool),\n    (forall a1 a2 : A, eqb a1 a2 = true <-> a1 = a2) ->\n    forall l1 l2 : list A, eqb_list eqb l1 l2 = true <-> l1 = l2.\nProof.\n  intros A eqb H. split.\n  - generalize dependent l2. induction l1 as [| h1 t1 IHt1].\n    + destruct l2 as [| h2 t2] eqn:E.\n      * reflexivity.\n      * simpl. discriminate.\n    + destruct l2 as [| h2 t2] eqn:E.\n      * simpl. discriminate.\n      * simpl. intro Ht. rewrite andb_true_iff in Ht.\n        destruct Ht as [HEh HEt]. rewrite H in HEh.\n        f_equal. apply HEh. apply IHt1. apply HEt.\n  - generalize dependent l2. induction l1 as [| h1 t1 IHt1].\n    + destruct l2 as [| h2 t2] eqn:E.\n      * reflexivity.\n      * discriminate.\n    + destruct l2 as [| h2 t2] eqn:E.\n      * discriminate.\n      * simpl. intro HEht. injection HEht. intros HEt HEh.\n        rewrite andb_true_iff. split.\n        rewrite H. apply HEh.\n        apply IHt1. apply HEt. Qed.\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  split.\n  - induction l as [| h t IHt].\n    + reflexivity.\n    + simpl. intro HEht. rewrite andb_true_iff in HEht.\n      destruct HEht as [HEh HEt]. split.\n      * apply HEh.\n      * apply IHt. apply HEt.\n  - induction l as [| h t IHt].\n    + reflexivity.\n    + simpl. intros [HEh HEt].\n      rewrite andb_true_iff. split.\n      * apply HEh.\n      * apply IHt. apply HEt. Qed.\n\nDefinition excluded_middle := forall P : Prop,\n    P \\/ ~ P.\n\nTheorem restricted_excluded_middle : forall (P : Prop) (b : bool),\n    (P <-> b = true) -> P \\/ ~ P.\nProof.\n  intros P [] H.\n  - left. rewrite H. reflexivity.\n  - right. rewrite H. intros contra.\n    discriminate contra. Qed.\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) (eqb n m)).\n  symmetry. apply eqb_eq. Qed.\n\nTheorem excluded_middle_irrefutable : forall (P : Prop),\n    ~ ~ (P \\/ ~ P).\nProof.\n  unfold not. intros P H. Check double_neg.\n  assert (HP: ~ P -> ~ ~ ~ P).\n  { unfold not. intros H1 H2. apply H2. apply H1. }\n  unfold not in HP. apply HP.\n  - intro H1. apply H. left. apply H1.\n  - intro H1. apply H. right. apply H1. Qed.\n\nTheorem excluded_middle_irrefutable' : forall (P : Prop),\n    ~ ~ (P \\/ ~ P).\nProof.\n  unfold not.\n  intros P HPPFF.\n  apply HPPFF.\n  right. intros HP. apply HPPFF.\n  left. apply HP.\nQed.\n\nTheorem not_exists_dist :\n  excluded_middle ->\n  forall (X : Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n  intros EM X P. intro HNE. unfold not in HNE.\n  intro x. destruct (EM (P x)).\n  - (* P x *) apply H.\n  - (* ~ P x *) exfalso. apply HNE.\n    exists x. unfold not in H. apply H. Qed.\n\nDefinition peirce := forall P Q : Prop,\n    ((P -> Q) -> P) -> P.\n\nDefinition double_negation_elimination := forall P : Prop,\n    ~ ~ P -> P.\n\nDefinition de_morgan_not_and_not := forall P Q : Prop,\n    ~ (~ P /\\ ~ Q) -> P \\/ Q.\n\nDefinition implies_to_or := forall P Q : Prop,\n    (P -> Q) -> (~ P \\/ Q).\n\nTheorem excluded_middle__pierce :\n  excluded_middle -> peirce.\nProof.\n  intro EM. intros P Q HPQP.\nAbort.\n", "meta": {"author": "duinomaker", "repo": "LearningStuff", "sha": "73410047a0d9ee36e54580ee9d22460037b7459c", "save_path": "github-repos/coq/duinomaker-LearningStuff", "path": "github-repos/coq/duinomaker-LearningStuff/LearningStuff-73410047a0d9ee36e54580ee9d22460037b7459c/LogicalFoundations/ch6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.697658040374461}}
{"text": "(***\n * Oqarina\n * Copyright 2021 Carnegie Mellon University.\n *\n * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING\n * INSTITUTE MATERIAL IS FURNISHED ON AN \"AS-IS\" BASIS. CARNEGIE MELLON\n * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR\n * IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF\n * FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS\n * OBTAINED FROM USE OF THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT\n * MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT,\n * TRADEMARK, OR COPYRIGHT INFRINGEMENT.\n *\n * Released under a BSD (SEI)-style license, please see license.txt or\n * contact permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public\n * release and unlimited distribution.  Please see Copyright notice for\n * non-US Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party\n * Software subject to its own license:\n *\n * 1. Coq theorem prover (https://github.com/coq/coq/blob/master/LICENSE)\n * Copyright 2021 INRIA.\n *\n * 2. Coq JSON (https://github.com/liyishuai/coq-json/blob/comrade/LICENSE)\n * Copyright 2021 Yishuai Li.\n *\n * DM21-0762\n***)\n\n(*| .. coq:: none |*)\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Relations.Relation_Operators.\n(*| .. coq::  |*)\n\n(*|\n\n.. index:: transitive closue, CoqExt; clos_refl_trans_1n, CoqExt; rt1n_trans'\n\nRelations, transitive closures\n==============================\n\nFor a relation :coq:`R`, :coq:`clos_refl_trans_1n` defines the notion of direct reflexive-transitive closure on the left of this relation.\n\nWe extend Coq standard library :coq:`Coq.Relations.Relation_Operators` with additional results, as suggested in the course \"Mechanized semantics\" given by Xavier Leroy at Collège de France in 2019-2020. Although a Coq development serves as a companion for this class, we propose a different set of definitions that builds on top of the Coq standard library.\n\n|*)\n\n(*| .. coq:: none |*)\nSection Reflexive_Transitive_Closure_Ext.\n(*| .. coq:: |*)\n\nVariable A: Type.\nVariable R: relation A.\n\nLemma rt1n_trans': forall (a b: A) ,\n    clos_refl_trans_1n A R a b ->\n        forall c, clos_refl_trans_1n A R b c ->\n        clos_refl_trans_1n A R a c.\nProof.\n    intros.\n    induction H.\n    - apply H0.\n    - eapply rt1n_trans. apply H. auto.\nQed.\n\n(*| We define the transitive closure of a relation from :coq:`clos_refl_trans_1n`. This allows one to reason on zero, one, or many steps (:coq:`clos_refl_trans_1n_star`), or one or many (:coq:`clos_refl_trans_1n_plus`). This is important for definiing equivalences between relations. |*)\n\nInductive clos_refl_trans_1n_plus : A -> A -> Prop :=\n  | plus_trans: forall a b c,\n      R a b -> clos_refl_trans_1n A R b c -> clos_refl_trans_1n_plus a c.\n\nLemma clos_refl_trans_1n_plus_one:\n  forall a b, R a b -> clos_refl_trans_1n_plus a b.\nProof.\n    intros.\n    eapply plus_trans.\n    - apply H.\n    - apply rt1n_refl.\nQed.\n\nLemma clos_refl_trans_1n_plus_star: forall a b,\n    clos_refl_trans_1n_plus a b -> clos_refl_trans_1n A R a b.\nProof.\n    intros. inversion H.\n    eapply rt1n_trans.\n    - apply H0.\n    - apply H1.\nQed.\n\n(*| .. coq:: none |*)\nEnd Reflexive_Transitive_Closure_Ext.\n(*| .. coq:: |*)\n", "meta": {"author": "Oqarina", "repo": "oqarina", "sha": "5a5ea65688188e462b20d30ee4e5eba08285f629", "save_path": "github-repos/coq/Oqarina-oqarina", "path": "github-repos/coq/Oqarina-oqarina/oqarina-5a5ea65688188e462b20d30ee4e5eba08285f629/src/CoqExt/Reflexive_Transitive_Closure_Ext.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.6976580338830483}}
{"text": "Set Implicit Arguments.\n\n\n\nPrint bool. (* Inductive bool : Set :=  true : bool | false : bool *)\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\nInductive whatever : Set := | A | B | C | D. (* simpler syntax *)\n\nCheck month_ind.\n(*\nforall P : month -> Prop,\n       P January ->\n       P February ->\n       P March ->\n       P April ->\n       P May ->\n       P June ->\n       P July ->\n       P August ->\n       P September ->\n       P October -> P November -> P December -> forall m : month, P m\n*)\n\nCheck month_rec.\n(*\nforall P : month -> Set,\n       P January ->\n       P February ->\n       P March ->\n       P April ->\n       P May ->\n       P June ->\n       P July ->\n       P August ->\n       P September ->\n       P October -> P November -> P December -> forall m : month, P m\n*)\n\nInductive season : Set :=\n  | Spring : season\n  | Summer : season\n  | Autumn : season\n  | Winter : season.\n\nDefinition month_to_season : month -> season :=\n  month_rec (fun m => season)\n            Winter Winter Spring\n            Spring Spring Summer\n            Summer Summer Autumn\n            Autumn Autumn Winter.\n\nEval compute in month_to_season January.\nEval compute in month_to_season February.\nEval compute in month_to_season March.\nEval compute in month_to_season April.\nEval compute in month_to_season May.\nEval compute in month_to_season June.\nEval compute in month_to_season July.\nEval compute in month_to_season August.\nEval compute in month_to_season September.\nEval compute in month_to_season October.\nEval compute in month_to_season November.\nEval compute in month_to_season December.\n\nCheck bool_ind. (* forall P : bool -> Prop, P true -> P false -> forall b : bool, P b *)\nCheck bool_rec. (* forall P : bool -> Set, P true -> P false -> forall b : bool, P b  *)\nCheck bool_rect. (* forall P : bool -> Type, P true -> P false -> forall b : bool, P b *)\n\nTheorem month_equal : forall 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 \\/ m=December.\nProof.\n  induction m; auto 12.\nQed.\n\nReset month_equal.\n\nTheorem month_equal : forall 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 \\/ m=December.\nProof.\n  intro m. pattern m. apply month_ind; auto 12. (* 12 sub-goals *)\nQed.\n\n\nCheck or_introl. (* forall A B : Prop, A -> A \\/ B *)\nCheck or_intror. (* forall A B : Prop, B -> A \\/ B *)\nCheck refl_equal(A:=Type).  (* forall x : Type, x = x *)\nCheck eq_refl(A:=Type).     (* forall x : Type, x = x *)\nCheck bool_ind. (* forall P : bool -> Prop, P true -> P false -> forall b : bool, P b *)\n\nTheorem bool_equal: forall b:bool, b = true \\/ b = false.\nProof.\n  intro b. pattern b. apply bool_ind. apply or_introl. apply eq_refl.\n  apply or_intror. apply eq_refl.\nQed.\n\nPrint bool_equal.\n(*\nfun b : bool =>\n  bool_ind  (fun b0 : bool => b0 = true \\/ b0 = false) \n            (or_introl eq_refl) \n            (or_intror eq_refl) b\n\n  : forall b : bool, b = true \\/ b = false\n*)\n\nReset bool_equal.\n\nTheorem bool_equal: forall b:bool, b = true \\/ b = false.\nProof.\n  exact(fun b : bool => \n          bool_ind  (fun b0 : bool => b0 = true \\/ b0 = false) \n                    (or_introl (true = false) (eq_refl true)) \n                    (or_intror (false = true) (eq_refl false)) \n                    b).\nQed. \n\nCheck or_introl (true = false) (eq_refl true).  (*  true = true \\/ true = false *) \nCheck or_intror (false = true) (eq_refl false). (* false = true \\/ false = false *)\n\nReset bool_equal.\n\nTheorem bool_equal: forall b:bool, b = true \\/ b = false.\nProof.\n  intro b. pattern b. apply bool_ind. left. reflexivity. right. reflexivity.\nQed.\n\nCheck (fun b:bool => match b with true => 33 | false => 45 end). \n(*\nfun b : bool => if b then 33 else 45\n       : bool -> nat\n*)\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_length2 : bool->month->nat :=\n fun (leap:bool)(m:month) => match m with January => 31 end.\nError: Non exhaustive pattern-matching: no clause found for pattern February\n*)\n\nCheck month_rec.\n(*\nforall P : month -> Set,\n       P January ->\n       P February ->\n       P March ->\n       P April ->\n       P May ->\n       P June ->\n       P July ->\n       P August ->\n       P September ->\n       P October -> P November -> P December -> forall m : month, P m\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\nPrint month_length.\nPrint month_length'.\n\nDefinition month_length'' (leap:bool) (m:month) : nat :=\n  match m with\n  | February  => if leap then 29 else 28\n  | April => 30 | June  => 30 | September => 30 | November  => 30\n  | other  => 31 (* lower case indicates variable name *)\n  end.\n\nEval compute in (fun leap => month_length leap November).\n(* fun _ : bool => 30\n   : bool -> nat\n*)\n\nTheorem length_february : month_length false February = 28.\nProof.\n  simpl. (* triggers iota reduction *)\n  reflexivity.\nQed.\n\n\n\n\nDefinition month_even (leap:bool)(m:month) : bool :=\n  match (month_length leap m) with\n    | 28    => true \n    | 29    => false\n    | 30    => true\n    | 31    => false\n    | other => false \n  end.\n\nDefinition bool_xor (b1:bool)(b2:bool) : bool :=\n  match (b1,b2) with\n  | (true, true)    => false\n  | (true, false)   => true\n  | (false, true)   => true\n  | (false, false)  => false\n  end.\n\nDefinition bool_and (b1:bool)(b2:bool) : bool :=\n  match (b1,b2) with\n  | (true, true)    => true\n  | (true, false)   => false\n  | (false, true)   => false\n  | (false, false)  => false\n  end.\n\nDefinition bool_or (b1:bool)(b2:bool) : bool :=\n  match (b1,b2) with\n  | (true, true)    => true\n  | (true, false)   => true\n  | (false, true)   => true\n  | (false, false)  => false\n  end.\n\nDefinition bool_eq (b1:bool)(b2:bool) : bool :=\n  match (b1,b2) with\n  | (true, true)    => true\n  | (true, false)   => false\n  | (false, true)   => false\n  | (false, false)  => true\n  end.\n\nDefinition bool_not (b:bool): bool :=\n  match b with\n  | true  => false\n  | false => true\n  end.\n\nTheorem xor_not_eq : forall b1 b2:bool, bool_xor b1 b2 = bool_not (bool_eq b1 b2).\nProof.\n  intros x y. pattern x; apply bool_ind; pattern y; apply bool_ind; reflexivity.\nQed.\n\n\nTheorem not_and_or : forall x y: bool, \n  bool_not(bool_and x y) = bool_or (bool_not x)(bool_not y).\nProof.\n  intros x y. elim x; elim y; reflexivity.\nQed.\n\nTheorem not_not : forall b:bool, bool_not (bool_not b) = b.\nProof.\n  intro x. elim x; reflexivity. \nQed.\n\nTheorem bool_lem : forall b:bool, bool_or b (bool_not b) = true.\nProof.\n  intro x. elim x; reflexivity.\nQed.\n\nTheorem eq_eq : forall x y:bool, bool_eq x y = true -> x = y.\nProof.\n  intros x y. elim x; elim y; intro H; unfold bool_eq in H; auto.\nQed.\n\nTheorem eq_eq_rev : forall x y:bool, x = y -> bool_eq x y = true.\nProof.\n  intros x y H. rewrite H. elim y; reflexivity.\nQed.\n\nTheorem not_or_and_not : forall x y:bool,\n  bool_not (bool_or x y) = bool_and (bool_not x) (bool_not y).\nProof.\n  intros x y. elim x; elim y; reflexivity.\nQed.\n\nTheorem distr : forall x y z: bool,\n  bool_or (bool_and x z) (bool_and y z) = bool_and (bool_or x y) z.\nProof.\n  intros x y z. elim x; elim y; elim z; reflexivity.\nQed.\n\n\nTheorem at_least_28: forall (leap:bool)(m:month), 28 <= month_length leap m. \nProof.\n  intros leap m. case m; simpl; auto. case leap; auto.\nQed.\n\n\nPrint at_least_28.\n(*\nfun (leap : bool) (m : month) =>\nmatch m as m0 return (28 <= month_length leap m0) with\n| January => le_S 28 30 (le_S 28 29 (le_S 28 28 (le_n 28)))\n| February =>\n    if leap as b return (28 <= (if b then 29 else 28))\n      then le_S 28 28 (le_n 28)\n      else le_n 28\n| March => le_S 28 30 (le_S 28 29 (le_S 28 28 (le_n 28)))\n| April => le_S 28 29 (le_S 28 28 (le_n 28))\n| May => le_S 28 30 (le_S 28 29 (le_S 28 28 (le_n 28)))\n| June => le_S 28 29 (le_S 28 28 (le_n 28))\n| July => le_S 28 30 (le_S 28 29 (le_S 28 28 (le_n 28)))\n| August => le_S 28 30 (le_S 28 29 (le_S 28 28 (le_n 28)))\n| September => le_S 28 29 (le_S 28 28 (le_n 28))\n| October => le_S 28 30 (le_S 28 29 (le_S 28 28 (le_n 28)))\n| November => le_S 28 29 (le_S 28 28 (le_n 28))\n| December => le_S 28 30 (le_S 28 29 (le_S 28 28 (le_n 28)))\nend\n*)\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  | September => October \n  | October => November | November  => December   | December  => January\nend.\n\nTheorem next_august_then_july : forall m:month, \n  next_month m = August -> m = July.\nProof.\n  intro m. case m; simpl; intro Hnext_eq; discriminate Hnext_eq || reflexivity. \nQed.\n\nCheck I. (* I: True *)\n\nTheorem not_January_eq_February : January <> February.\nProof. \n  unfold not. intros H.\n  pose (g:=(fun (m:month) => match m with January => True | _ => False end)). (* can also define g from month_rec *)\n  change (g February). rewrite <- H. simpl. apply I.\nQed.\n\nTheorem not_true_eq_false : true <> false.\nProof. \n  unfold not. intro H. pose (g:= fun (b:bool) => match b with false => False | true => True end).\n  change (g false). rewrite <- H. simpl. apply I.\nQed.\n\nTheorem next_march_shorter : forall (leap:bool)(m1 m2:month), \n  next_month m1 = March -> month_length leap m1 <= month_length leap m2.  \nProof.\n  intros leap m1 m2 H.\n  case m1. (* we are stuck *)\n  Restart.\n  intros leap m1 m2.\n  case m1; simpl; (discriminate || (* cannot be handled by discriminate *)\n    simpl; case m2; simpl; case leap; auto).\n  Restart.\n  intros leap m1 m2 H. generalize H. (* then can proceed with 'case' *)\n  Restart.\n(* negative argument to specifiy which occurence of m1 should not be replaced in abstraction *) \n  intros leap m1 m2 H. generalize (eq_refl m1). pattern m1 at -1. \n  case m1; intro H0; rewrite H0 in H; simpl in H; (discriminate || (* case which cannot be handled with discriminate *) \n    simpl; case leap; case m2; simpl; auto).  \nQed.\n\n\nLtac caseEq f := (* our first tactic definition *)\n  generalize (eq_refl f); pattern f at -1; case f.\n\n\n\nTheorem next_march_shorter' : forall (leap:bool)(m1 m2:month), \n  next_month m1 = March -> month_length leap m1 <= month_length leap m2.  \nProof.\n  intros leap m1 m2 H.\n  caseEq m1; intro H'; rewrite H' in H; simpl in H; try (discriminate H).\n  case leap; simpl; case m2; simpl; auto.\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/inductive-data-type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.6976580320815589}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import NPeano.\nRequire Import List.\nImport ListNotations.\nRequire Import Sorting.Permutation.\nRequire Import VerdiTactics.\n\nSet Implicit Arguments.\n\nNotation member := (in_dec eq_nat_dec).\n\nLtac do_in_map :=\n  match goal with\n    | [ H : In _ (map _ _) |- _ ] => apply in_map_iff in H; break_exists; break_and\n  end.\n\nLtac do_in_app :=\n  match goal with\n    | [ H : In _ (_ ++ _) |- _ ] => apply in_app_iff in H\n  end.\n\nLemma filter_app : forall A (f : A -> bool) xs ys,\n    filter f (xs ++ ys) = filter f xs ++ filter f ys.\nProof.\n  induction xs; intros.\n  - auto.\n  - simpl. rewrite IHxs. break_if; auto.\nQed.\n\nSection dedup.\n  Variable A : Type.\n  Hypothesis A_eq_dec : forall x y : A, {x = y} + {x <> y}.\n\n  Fixpoint dedup (xs : list A) : list A :=\n    match xs with\n    | [] => []\n    | x :: xs => let tail := dedup xs in\n                 if in_dec A_eq_dec x xs then\n                   tail\n                 else\n                   x :: tail\n    end.\n\n  Lemma dedup_eliminates_duplicates : forall (a : A) b c,\n      (dedup (a :: b ++ a :: c) = dedup (b ++ a :: c)).\n  Proof.\n    intros. simpl in *.\n    break_match.\n    + auto.\n    + exfalso. intuition.\n  Qed.\n\n  Lemma dedup_In : forall (x : A) xs,\n      In x xs ->\n      In x (dedup xs).\n  Proof.\n    induction xs; intros.\n    - simpl in *. intuition.\n    - simpl in *. break_if; intuition.\n      + subst. auto.\n      + subst. simpl. auto.\n  Qed.\n\n  Lemma filter_dedup (pred : A -> bool) :\n    forall xs (p : A) ys,\n      pred p = false ->\n      filter pred (dedup (xs ++ ys)) = filter pred (dedup (xs ++ p :: ys)).\n  Proof.\n    intros. induction xs.\n    - simpl. repeat (break_match; simpl; auto; try discriminate).\n    - simpl. repeat (break_match; simpl; auto).\n      + exfalso. apply n. apply in_app_iff. apply in_app_or in i. intuition.\n      + exfalso. apply n. apply in_app_or in i. intuition.\n        * simpl in *. intuition. subst. rewrite Heqb in H. discriminate.\n      + rewrite IHxs. auto.\n      + discriminate.\n      + discriminate.\n  Qed.\n\n  Lemma dedup_app : forall (xs ys : list A),\n      (forall x y, In x xs -> In y ys -> x <> y) ->\n      dedup (xs ++ ys) = dedup xs ++ dedup ys.\n  Proof.\n    intros. induction xs; simpl; auto.\n    repeat break_match.\n    - apply IHxs.\n      intros. apply H; intuition.\n    - exfalso. specialize (H a a).\n      apply H; intuition.\n      do_in_app. intuition.\n    - exfalso. apply n. intuition.\n    - simpl. f_equal.\n      apply IHxs.\n      intros. apply H; intuition.\n  Qed.\n\n  Lemma in_dedup_was_in :\n    forall xs (x : A),\n      In x (dedup xs) ->\n      In x xs.\n  Proof.\n    induction xs; intros.\n    - simpl in *; intuition.\n    - simpl in *. break_if; simpl in *; intuition.\n  Qed.\n\n  Lemma NoDup_dedup :\n    forall (xs : list A),\n      NoDup (dedup xs).\n  Proof.\n    induction xs.\n    - simpl. constructor.\n    - simpl. break_if; auto.\n      constructor; auto.\n      intro.\n      apply n.\n      eapply in_dedup_was_in; eauto.\n  Qed.\n\n  Lemma remove_preserve :\n    forall (x y : A) xs,\n      x <> y ->\n      In y xs ->\n      In y (remove A_eq_dec x xs).\n  Proof.\n    induction xs; intros.\n    - intuition.\n    - simpl in *.\n      concludes.\n      intuition; break_if; subst; try congruence; intuition.\n  Qed.\n\n  Lemma in_remove :\n    forall (x y : A) xs,\n      In y (remove A_eq_dec x xs) ->\n      In y xs.\n  Proof.\n    induction xs; intros.\n    - auto.\n    - simpl in *. break_if; simpl in *; intuition.\n  Qed.\n\n  Lemma remove_dedup_comm : forall (x : A) xs,\n      remove A_eq_dec x (dedup xs) =\n      dedup (remove A_eq_dec x xs).\n  Proof.\n    induction xs; intros.\n    - auto.\n    - simpl. repeat (break_match; simpl); auto.\n      + exfalso. apply n0. apply remove_preserve; auto.\n      + exfalso. apply n. eapply in_remove; eauto.\n      + f_equal. auto.\n  Qed.\n\n  Lemma remove_partition :\n    forall xs (p : A) ys,\n      remove A_eq_dec p (xs ++ p :: ys) = remove A_eq_dec p (xs ++ ys).\n  Proof.\n    induction xs; intros.\n    - simpl. break_if; congruence.\n    - simpl. break_if.\n      + auto.\n      + f_equal. auto.\n  Qed.\n\n  Lemma remove_not_in : forall (x : A) xs,\n      ~ In x xs ->\n      remove A_eq_dec x xs = xs.\n  Proof.\n    intros. induction xs.\n    - intuition.\n    - simpl. break_match.\n      + exfalso. apply H.\n        subst. intuition.\n      + f_equal. apply IHxs.\n        intro Hin.\n        apply H. simpl. intuition.\n  Qed.\n\n  Lemma dedup_partition :\n    forall xs (p : A) ys xs' ys',\n      dedup (xs ++ p :: ys) = xs' ++ p :: ys' ->\n      remove A_eq_dec p (dedup (xs ++ ys)) = xs' ++ ys'.\n  Proof.\n    intros.\n    f_apply H (remove A_eq_dec p).\n    rewrite remove_dedup_comm in *.\n    rewrite remove_partition in *.\n    rewrite H0.\n    rewrite remove_partition.\n\n    apply remove_not_in.\n    apply NoDup_remove_2.\n    rewrite <- H.\n    apply NoDup_dedup.\n  Qed.\n\n  Lemma dedup_NoDup_id : forall (xs : list A),\n      NoDup xs -> dedup xs = xs.\n  Proof.\n    induction xs; intros.\n    - auto.\n    - simpl. invc H. concludes. rewrite IHxs.\n      break_if; congruence.\n  Qed.\n\n  Lemma dedup_not_in_cons :\n    forall x xs,\n      (~ In x xs) ->\n      x :: dedup xs = dedup (x :: xs).\n  Proof.\n    induction xs; intros.\n    - auto.\n    - simpl in *. intuition. repeat break_match; intuition.\n  Qed.\nEnd dedup.\n\nLemma filter_fun_ext_eq : forall A f g xs,\n                            (forall a : A, In a xs -> f a = g a) ->\n                            filter f xs = filter g xs.\nProof.\n  induction xs; intros.\n  - auto.\n  - simpl. rewrite H by intuition. rewrite IHxs by intuition. auto.\nQed.\n\n\n\nLemma NoDup_map_injective : forall A B (f : A -> B) xs,\n                              (forall x y, In x xs -> In y xs ->\n                                           f x = f y -> x = y) ->\n                              NoDup xs -> NoDup (map f xs).\nProof.\n  induction xs; intros.\n  - constructor.\n  - simpl. constructor.\n    + intro.\n      do_in_map.\n      specialize (H a x).\n      repeat conclude H intuition.\n      subst.\n      invc H0. auto.\n    + apply IHxs. intuition. inv H0. auto.\nQed.\n\nLemma NoDup_disjoint_append :\n  forall A (l : list A) l',\n    NoDup l ->\n    NoDup l' ->\n    (forall a, In a l -> ~ In a l') ->\n    NoDup (l ++ l').\nProof.\n  induction l; intros.\n  - auto.\n  - simpl. constructor.\n    + intro. do_in_app. intuition.\n      * invc H. auto.\n      * apply (H1 a); intuition.\n    + invc H. apply IHl; auto.\n      intros. apply H1. intuition.\nQed.\n\nLemma filter_NoDup :\n  forall A p (l : list A),\n    NoDup l ->\n    NoDup (filter p l).\nProof.\n  induction l; intros.\n  - auto.\n  - invc H. simpl. break_if.\n    + constructor; auto.\n      intro. apply filter_In in H. intuition.\n    + auto.\nQed.\n\n    \n\nLemma filter_true_id : forall A (f : A -> bool) xs,\n                         (forall x, In x xs -> f x = true) ->\n                         filter f xs = xs.\nProof.\n  induction xs; intros.\n  - auto.\n  - simpl. rewrite H by intuition. rewrite IHxs by intuition. auto.\nQed.\n\nLemma map_of_map : forall A B C (f : A -> B) (g : B -> C) xs,\n                     map g (map f xs) = map (fun x => g (f x)) xs.\nProof.\n  induction xs.\n  - auto.\n  - simpl. f_equal. auto.\nQed.\n\nLemma filter_except_one : forall A A_eq_dec (f g : A -> bool) x xs,\n                            (forall y, In y xs ->\n                                       x <> y ->\n                                       f y = g y) ->\n                            g x = false ->\n                            filter f (remove A_eq_dec x xs) = filter g xs.\nProof.\n  induction xs; intros.\n  - auto.\n  - simpl.\n    pose proof (A_eq_dec x a).\n    intuition; repeat (break_match; simpl); try congruence; subst; intuition; f_equal; intuition;\n    rewrite (H a) in * by intuition; congruence.\nQed.\n\nLemma flat_map_nil : forall A B (f : A -> list B) l,\n                       flat_map f l = [] ->\n                       l = [] \\/ (forall x, In x l -> f x = []).\nProof.\n  induction l; intros.\n  - intuition.\n  - right. simpl in *.\n    apply app_eq_nil in H.\n    intuition; subst; simpl in *; intuition.\nQed.\n\nFixpoint remove_first {A : Set} (A_eq_dec : forall x y : A, {x = y} + {x <> y}) (x : A) (l : list A) : list A :=\n  match l with\n    | [] => []\n    | y::tl => if (A_eq_dec x y) then tl else y::(remove_first A_eq_dec x tl)\n  end.\n\n\nFixpoint subseq {A} (xs ys : list A) : Prop :=\n  match xs, ys with\n    | [], _ => True\n    | x :: xs', y :: ys' => (x = y /\\ subseq xs' ys') \\/ subseq xs ys'\n    | _, _ => False\n  end.\n\nLemma subseq_refl : forall A (l : list A), subseq l l.\nProof.\n  induction l; simpl; tauto.\nQed.\n\nLemma subseq_trans :\n  forall A (zs xs ys : list A),\n    subseq xs ys ->\n    subseq ys zs ->\n    subseq xs zs.\nProof.\n  induction zs; intros; simpl in *;\n  repeat break_match; subst; simpl in *; intuition; subst; eauto;\n  right; (eapply IHzs; [|eauto]); simpl; eauto.\nQed.\nLemma subseq_In :\n  forall A (ys xs : list A) x,\n    subseq xs ys ->\n    In x xs ->\n    In x ys.\nProof.\n  induction ys; intros.\n  - destruct xs; simpl in *; intuition.\n  - simpl in *. break_match; simpl in *; intuition; subst; intuition eauto;\n                right; (eapply IHys; [eauto| intuition]).\nQed.\n\nTheorem subseq_NoDup :\n  forall A (ys xs : list A),\n    subseq xs ys ->\n    NoDup ys ->\n    NoDup xs.\nProof.\n  induction ys; intros.\n  - destruct xs; simpl in *; intuition.\n  - simpl in *. invc H0.\n    break_match.\n    + constructor.\n    + intuition.\n      subst. constructor.\n      * intro. apply H3.\n        eapply subseq_In; eauto.\n      * eauto.\nQed.\n\nTheorem NoDup_Permutation_NoDup :\n  forall A (l l' : list A),\n    NoDup l ->\n    Permutation l l' ->\n    NoDup l'.\nProof.\n  intros. induction H0.\n  - auto.\n  - invc H. constructor; auto.\n    intro. apply H3. apply Permutation_in with (l := l'); auto.\n    symmetry. auto.\n  - invc H. invc H3. constructor.\n    * simpl in *. intuition.\n    * constructor; simpl in *; intuition.\n  - auto.\nQed.\n\nTheorem NoDup_append :\n  forall A l (a : A),\n    NoDup (l ++ [a]) <-> NoDup (a :: l).\nProof.\n  intros.\n  split; intro.\n  - eapply NoDup_Permutation_NoDup; try eassumption.\n    symmetry.\n    apply Permutation_cons_append.\n  - eapply NoDup_Permutation_NoDup; try eassumption.\n    apply Permutation_cons_append.\nQed.\n\nLemma leb_false_lt : forall m n, leb m n = false -> n < m.\nProof.\n  induction m; intros.\n  - discriminate.\n  - simpl in *. break_match; subst; auto with arith.\nQed.\n\nLemma leb_true_le : forall m n, leb m n = true -> m <= n.\nProof.\n  induction m; intros.\n  - auto with arith.\n  - simpl in *. break_match; subst; auto with arith.\n    discriminate.\nQed.\n\nLemma ltb_false_le : forall m n, m <? n = false -> n <= m.\nProof.\n  induction m; intros; destruct n; try discriminate; auto with arith.\nQed.\n\nLemma ltb_true_lt : forall m n, m <? n = true -> m < n.\n  induction m; intros; destruct n; try discriminate; auto with arith.\nQed.\n\nLtac do_bool :=\n  repeat match goal with\n    | [ H : beq_nat _ _ = true |- _ ] => apply beq_nat_true in H\n    | [ H : beq_nat _ _ = false |- _ ] => apply beq_nat_false in H\n    | [ H : andb _ _ = true |- _ ] => apply Bool.andb_true_iff in H\n    | [ H : negb _ = true |- _ ] => apply Bool.negb_true_iff in H\n    | [ H : negb _ = false |- _ ] => apply Bool.negb_false_iff in H\n    | [ H : PeanoNat.Nat.ltb _ _ = true |- _ ] => apply ltb_true_lt in H\n    | [ H : PeanoNat.Nat.ltb _ _ = false |- _ ] => apply ltb_false_le in H\n    | [ H : leb _ _ = true |- _ ] => apply leb_true_le in H\n    | [ H : leb _ _ = false |- _ ] => apply leb_false_lt in H\n    | [ |- context [ andb _ _ ] ] => apply Bool.andb_true_iff\n    | [ |- context [ leb _ _ ] ] => apply leb_correct\n    | [ |- context [ _ <> false ] ] => apply Bool.not_false_iff_true\n    | [ |- beq_nat _ _ = false ] => apply beq_nat_false_iff\n    | [ |- beq_nat _ _ = true ] => apply beq_nat_true_iff\n  end.\n\n\nLemma NoDup_map_elim :\n  forall A B (f : A -> B) xs x y,\n    f x = f y ->\n    NoDup (map f xs) ->\n    In x xs ->\n    In y xs ->\n    x = y.\nProof.\n  induction xs; intros.\n  - simpl in *. intuition.\n  - simpl in *. invc H0. intuition; subst.\n    + auto.\n    + exfalso. repeat find_rewrite. apply H5. apply in_map. auto.\n    + exfalso. apply H5. rewrite <- H. apply in_map. auto.\nQed.\n\nLemma subseq_map :\n  forall A B (f : A -> B) ys xs,\n    subseq xs ys ->\n    subseq (map f xs) (map f ys).\nProof.\n  induction ys; intros.\n  - simpl in *. repeat break_match; try discriminate; auto.\n  - simpl in *. repeat break_match; try discriminate; auto.\n    simpl in *. find_inversion.\n    intuition.\n    + subst. auto.\n    + right. apply IHys in H0. auto.\nQed.\n\nLemma subseq_cons_drop :\n  forall A xs ys (a : A),\n    subseq (a :: xs) ys -> subseq xs ys.\nProof.\n  induction ys; intros; simpl in *; intuition; break_match; eauto.\nQed.\n\nLemma subseq_length :\n  forall A (ys xs : list A),\n    subseq xs ys ->\n    length xs <= length ys.\nProof.\n  induction ys; intros; simpl in *; break_match; intuition.\n  subst. simpl in *. specialize (IHys l). concludes. auto with *.\nQed.\n\nLemma subseq_subseq_eq :\n  forall A (xs ys : list A),\n    subseq xs ys ->\n    subseq ys xs ->\n    xs = ys.\nProof.\n  induction xs; intros.\n  - destruct ys; auto; simpl in *; intuition.\n  - destruct ys; simpl in *.\n    + intuition.\n    + intuition.\n      * f_equal; eauto.\n      * f_equal; eauto using subseq_cons_drop.\n      * f_equal; eauto using subseq_cons_drop.\n      * exfalso.\n        apply subseq_length in H1.\n        apply subseq_length in H.\n        simpl in *. omega.\nQed.\n\nLemma subseq_filter :\n  forall A (f : A -> bool) xs,\n    subseq (filter f xs) xs.\nProof.\n  induction xs; intros.\n  - simpl. auto.\n  - simpl. repeat break_match.\n    + discriminate.\n    + auto.\n    + find_inversion. auto.\n    + right. rewrite <- Heql. eauto.\nQed.\n\nFixpoint take A (n : nat) (xs : list A) : list A :=\n  match n with\n    | O => []\n    | S n' => match xs with\n               | [] => []\n               | x :: xs' => x :: take n' xs'\n             end\n  end.\n\nLemma remove_length_not_in : forall A A_eq_dec (x : A) xs,\n                               ~ In x xs ->\n                               length (remove A_eq_dec x xs) = length xs.\nProof.\n  induction xs; intros.\n  - auto.\n  - simpl in *. intuition.\n    break_if; subst; simpl; intuition.\nQed.\n\nLemma remove_length_in : forall A A_eq_dec (x : A) xs,\n                           In x xs ->\n                           NoDup xs ->\n                           S (length (remove A_eq_dec x xs)) = length xs.\nProof.\n  induction xs; intros.\n  - simpl in *. intuition.\n  - simpl in *. intuition.\n    + subst. break_if; try congruence.\n      inv H0.\n      rewrite remove_length_not_in; auto.\n    + invc H0.\n      break_if; subst; intuition.\nQed.\n\n\nLemma subset_size_eq :\n  forall A xs,\n    NoDup xs ->\n    forall ys,\n      NoDup ys ->\n      (forall x : A, In x xs -> In x ys) ->\n      length xs = length ys ->\n      (forall x, In x ys -> In x xs).\nProof.\n  induction xs; intros.\n  - destruct ys; try discriminate. auto.\n  - simpl in *. inv H. concludes.\n    pose proof H1 a (or_introl eq_refl).\n    apply in_split in H4. break_exists. subst.\n    specialize (IHxs (x0 ++ x1)).\n\n\n    forward IHxs.\n    eapply NoDup_remove_1; eauto.\n    concludes. clear H4.\n\n\n    forward IHxs.\n    intros. pose proof H1 x2 (or_intror H4).\n    pose proof NoDup_remove_2 x0 x1 a H0.\n    apply in_app_or in H5. simpl in *. intuition. subst. congruence.\n    concludes. clear H4.\n\n    forward IHxs. rewrite app_length in *. simpl in *. omega.\n    concludes.  clear H4.\n\n    apply in_app_or in H3. simpl in *. intuition.\nQed.\n\nLemma in_take : forall A n (x : A) xs,\n                  In x (take n xs) -> In x xs.\nProof.\n  induction n; intros.\n  - simpl in *. intuition.\n  - simpl in *. break_match.\n    + simpl in *. intuition.\n    + simpl in *. intuition.\nQed.\n\nLemma take_NoDup : forall A n (xs : list A),\n                     NoDup xs ->\n                     NoDup (take n xs).\nProof.\n  induction n; intros.\n  - destruct xs; simpl in *; intuition. constructor.\n  - simpl. destruct xs.\n    + auto.\n    + invc H. constructor; auto.\n      intro. apply in_take in H. auto.\nQed.\n\nLemma remove_NoDup :\n  forall A A_eq_dec (x : A) xs,\n    NoDup xs ->\n    NoDup (remove A_eq_dec x xs).\nProof.\n  induction xs; intros.\n  - auto.\n  - invc H. simpl. break_if.\n    + auto.\n    + constructor.\n      * intro. apply H2. eapply in_remove; eauto.\n      * auto.\nQed.\n\nLemma seq_range :\n  forall n a x,\n    In x (seq a n) ->\n    a <= x < a + n.\nProof.\n  induction n; intros.\n  - simpl in *. intuition.\n  - simpl in *. invc H. intuition.\n    apply IHn in H0. omega.\nQed.\n\n\nLemma take_length : forall A n (xs : list A),\n                      length xs >= n ->\n                      length (take n xs) = n.\nProof.\n  induction n; intros.\n  - auto.\n  - simpl. break_match.\n    + simpl in *. omega.\n    + simpl in *. rewrite IHn by omega. auto.\nQed.\n\n\nLemma seq_NoDup : forall n a ,\n                    NoDup (seq a n).\nProof.\n  induction n; intros; simpl in *.\n  - constructor.\n  - constructor.\n    intro. apply seq_range in H. omega.\n    auto.\nQed.\n\nLemma remove_length_ge : forall A A_eq_dec (x : A) xs,\n                           NoDup xs ->\n                           length (remove A_eq_dec x xs) >= length xs - 1.\nProof.\n  induction xs; intros.\n  - auto.\n  - inv H. simpl. break_if.\n    + rewrite <- minus_n_O.\n      subst.\n      rewrite remove_length_not_in; auto.\n    + simpl. concludes. omega.\nQed.\n\nLemma remove_length_le :\n  forall A (x : A) xs eq_dec,\n    length xs >= length (remove eq_dec x xs).\nProof.\n  induction xs; intros.\n  - auto.\n  - simpl in *.\n    specialize (IHxs eq_dec).\n    break_if; subst; simpl; omega.\nQed.\n\nLemma remove_length_lt :\n  forall A (x : A) xs eq_dec,\n    In x xs ->\n    length xs > length (remove eq_dec x xs).\nProof.\n  induction xs; intros.\n  - simpl in *. intuition.\n  - simpl in *.\n    intuition.\n    + subst.\n      break_if; try congruence.\n      pose proof remove_length_le x xs eq_dec.\n      omega.\n    + specialize (IHxs eq_dec H0).\n      break_if; subst; simpl; omega.\nQed.\n\nLemma subset_length :\n  forall A xs ys,\n    (forall a b : A, {a = b} + {a <> b}) ->\n    NoDup xs ->\n    (forall x : A, In x xs -> In x ys) ->\n    length ys >= length xs.\nProof.\n  induction xs; intros.\n  - simpl. omega.\n  - specialize (IHxs (remove X a ys) X).\n    invc H.\n    concludes.\n\n    forward IHxs.\n    intros.\n    apply remove_preserve.\n    intro. subst. congruence.\n\n    apply H0. intuition.\n    concludes.\n    pose proof remove_length_lt a ys X.\n    forwards.\n    apply H0. intuition. concludes.\n    simpl. omega.\nQed.\n\nLemma take_length_ge : forall A n m (xs : list A),\n                         length (take n xs) >= m ->\n                         length xs >= m.\nProof.\n  induction n; intros.\n  - simpl in *. omega.\n  - simpl in *. break_match.\n    + omega.\n    + simpl in *.\n      destruct m; try omega.\n      unfold ge in *.\n      apply le_S_n in H.\n      apply IHn in H. omega.\nQed.\n\nFixpoint fin (n : nat) : Type :=\n  match n with\n    | 0 => False\n    | S n' => option (fin n')\n  end.\n\nLemma fin_eq_dec : forall n (a b : fin n), {a = b} + {a <> b}.\nProof.\n  induction n.\n  - auto.\n  - intros. destruct a, b.\n    + specialize (IHn f f0). intuition.\n      * subst. auto.\n      * right. intros. inversion H. auto.\n    + right. discriminate.\n    + right. discriminate.\n    + auto.\nQed.\n\nFixpoint all_fin (n : nat) : list (fin n) :=\n  match n with\n    | 0 => []\n    | S n' => None :: map (fun x => Some x) (all_fin n')\n  end.\n\nLemma all_fin_all :\n  forall n (x : fin n),\n    In x (all_fin n).\nProof.\n  induction n; intros.\n  - solve_by_inversion.\n  - simpl in *. destruct x; auto using in_map.\nQed.\n\nLemma all_fin_NoDup :\n  forall n,\n    NoDup (all_fin n).\nProof.\n  induction n; intros; simpl; constructor.\n  - intro. apply in_map_iff in H. firstorder. discriminate.\n  - apply NoDup_map_injective; auto. congruence.\nQed.\n\nLemma or_false :\n  forall P : Prop, P -> (P \\/ False).\nProof.\n  firstorder.\nQed.\n\nLtac map_crush :=\n  repeat match goal with\n                   | [ H : context [ map _ (_ ++ _) ] |- _ ] => rewrite map_app in H\n                   | [ |- context [ map _ (_ ++ _) ] ] => rewrite map_app\n                   | [ H : context [ map _ (map _ _) ] |- _ ] => rewrite map_map in H\n                   | [ |- context [ map _ (map _ _) ] ] => rewrite map_map\n         end; simpl in *.\n\n\nLtac in_crush_finish :=\n  repeat match goal with\n    | [ |- _ \\/ _ ] => try first [solve [apply or_introl; in_crush_finish]|\n                                 solve [apply or_intror; in_crush_finish]]\n    | [ |- In _ (_ ++ _) ] => apply in_or_app; in_crush_finish\n    | [ |- In _ (map _ _) ] => apply in_map_iff; eexists; eauto\n  end.\nLtac in_crush_start :=\n  intuition; simpl in *;\n  repeat\n    (match goal with\n       | [ H : In _ (map _ _) |- _ ] => apply in_map_iff in H; break_exists; break_and\n       | [ H : In _ (_ ++ _) |- _ ] => apply in_app_iff in H\n     end; intuition; simpl in *); subst.\n\nLtac in_crush := repeat (in_crush_start; in_crush_finish).\n\nFixpoint Prefix {A} (l1 : list A) l2 : Prop :=\n  match l1, l2 with\n    | a :: l1', b :: l2' => a = b /\\ Prefix l1' l2'\n    | [], _ => True\n    | _, _ => False\n  end.\n\nLemma app_Prefix :\n  forall A (xs ys zs : list A),\n    xs ++ ys = zs ->\n    Prefix xs zs.\nProof.\n  induction xs; intros; simpl in *.\n  - auto.\n  - break_match.\n    + discriminate.\n    + subst. find_inversion. eauto.\nQed.\n\nFixpoint filterMap {A B} (f : A -> option B) (l : list A) : list B :=\n  match l with\n    | [] => []\n    | x :: xs => match f x with\n                   | None => filterMap f xs\n                   | Some y => y :: filterMap f xs\n                 end\n  end.\n\nLemma app_cons_singleton_inv :\n  forall A xs (y : A) zs w,\n    xs ++ y :: zs = [w] ->\n    xs = [] /\\ y = w /\\ zs = [].\nProof.\n  intros.\n  destruct xs.\n  - solve_by_inversion.\n  - destruct xs; solve_by_inversion.\nQed.\n\nDefinition null {A : Type} (xs : list A) : bool :=\n  match xs with\n    | [] => true\n    | _ => false\n  end.\n\nLemma null_sound :\n  forall A (l : list A),\n    null l = true -> l = [].\nProof.\n  destruct l; simpl in *; auto; discriminate.\nQed.\n\nLemma null_false_neq_nil :\n  forall A (l : list A),\n    null l = false -> l <> [].\nProof.\n  destruct l; simpl in *; auto; discriminate.\nQed.\n\nLemma map_of_filterMap :\n  forall A B C (f : A -> option B) (g : B -> C) l,\n    map g (filterMap f l) = filterMap (fun x => match f x with\n                                                  | Some y => Some (g y)\n                                                  | None => None\n                                                end) l.\nProof.\n  induction l; intros; simpl in *.\n  - auto.\n  - repeat break_match; simpl; auto using f_equal.\nQed.\n\nLemma filterMap_ext :\n  forall A B (f g : A -> option B) l,\n    (forall x, f x = g x) ->\n    filterMap f l = filterMap g l.\nProof.\n  induction l; intros; simpl in *.\n  - auto.\n  - repeat find_higher_order_rewrite; auto.\nQed.\n\nLemma filterMap_defn :\n  forall A B (f : A -> option B) x xs,\n    filterMap f (x :: xs) = match f x with\n                              | Some y => y :: filterMap f xs\n                              | None => filterMap f xs\n                            end.\nProof.\n  simpl. auto.\nQed.\n\nLemma app_cons_in :\n  forall A (l : list A) xs a ys,\n    l = xs ++ a :: ys ->\n    In a l.\nProof.\n  intros. subst. auto with *.\nQed.\nHint Resolve app_cons_in.\n\nLemma app_cons_in_rest:\n  forall A (l : list A) xs a b ys,\n    l = xs ++ a :: ys ->\n    In b (xs ++ ys) ->\n    In b l.\nProof.\n  intros. subst. in_crush.\nQed.\nHint Resolve app_cons_in_rest.\n\nLemma remove_filter_commute :\n  forall A  (l : list A) A_eq_dec f x,\n    remove A_eq_dec x (filter f l) = filter f (remove A_eq_dec x l).\nProof.\n  induction l; intros; simpl in *; auto.\n  repeat (break_if; subst; simpl in *; try congruence).\nQed.\n\nLemma filter_partition :\n  forall A (l1 : list A) f l2 x l1' l2',\n    NoDup (l1 ++ x :: l2) ->\n    filter f (l1 ++ x :: l2) = (l1' ++ x :: l2') ->\n    filter f l1 = l1' /\\ filter f l2 = l2'.\nProof.\n  induction l1; intros; simpl in *.\n  - break_if; simpl in *.\n    + invcs H.\n      destruct l1'; simpl in *; intuition.\n      * solve_by_inversion.\n      * find_inversion.\n        exfalso.\n        match goal with\n          | H : filter ?f ?l = _ ++ ?x :: _ |- _ =>\n            assert (In x (filter f l)) by (repeat find_rewrite; in_crush)\n        end.\n        find_apply_lem_hyp filter_In. intuition.\n      * find_inversion.\n        exfalso.\n        match goal with\n          | H : filter ?f ?l = _ ++ ?x :: _ |- _ =>\n            assert (In x (filter f l)) by (repeat find_rewrite; in_crush)\n        end.\n        find_apply_lem_hyp filter_In. intuition.\n    + exfalso.\n      match goal with\n        | H : filter ?f ?l = _ ++ ?x :: _ |- _ =>\n          assert (In x (filter f l)) by (repeat find_rewrite; in_crush)\n      end.\n      find_apply_lem_hyp filter_In. intuition. congruence.\n  - break_if.\n    + invcs H.\n      destruct l1'; simpl in *; intuition;\n      try solve [\n            find_inversion; exfalso;\n            match goal with\n              | _ : In ?x ?l -> False |- _ =>\n                assert (In x l) by in_crush; intuition\n            end|\n            find_inversion; f_equal;\n            find_apply_hyp_hyp; intuition].\n    + invcs H. eauto.\nQed.\n\nLemma map_inverses :\n  forall A B (la : list A) (lb : list B)  (f : A -> B) g,\n    (forall a, g (f a) = a) ->\n    (forall b, f (g b) = b) ->\n    lb = map f la ->\n    la = map g lb.\nProof.\n  destruct la; intros; simpl in *.\n  - subst. reflexivity.\n  - destruct lb; try congruence.\n    simpl in *. find_inversion.\n    find_higher_order_rewrite.\n    f_equal.\n    rewrite map_map.\n    erewrite map_ext; [symmetry; apply map_id|].\n    simpl in *. auto.\nQed.\n\nLemma if_sum_bool_fun_comm :\n  forall A B C D (b : {A}+{B}) (c1 c2 : C) (f : C -> D),\n    f (if b then c1 else c2) = if b then f c1 else f c2.\nProof.\n  intros. break_if; auto.\nQed.\n\nSection assoc.\n  Variable K V : Type.\n  Variable K_eq_dec : forall k k' : K, {k = k'} + {k <> k'}.\n\n  Fixpoint assoc (l : list (K * V)) (k : K) : option V :=\n    match l with\n      | [] => None\n      | (k', v) :: l' =>\n        if K_eq_dec k k' then\n          Some v\n        else\n          assoc l' k\n    end.\n\n  Definition assoc_default (l : list (K * V)) (k : K) (default : V) : V :=\n    match (assoc l k) with\n      | Some x => x\n      | None => default\n    end.\n\n  Fixpoint assoc_set (l : list (K * V)) (k : K) (v : V) : list (K * V) :=\n    match l with\n      | [] => [(k, v)]\n      | (k', v') :: l' =>\n        if K_eq_dec k k' then\n          (k, v) :: l'\n        else\n          (k', v') :: (assoc_set l' k v)\n    end.\n\n  Fixpoint assoc_del (l : list (K * V)) (k : K) : list (K * V) :=\n    match l with\n      | [] => []\n      | (k', v') :: l' =>\n        if K_eq_dec k k' then\n          l'\n        else\n          (k', v') :: (assoc_del l' k)\n    end.\n\n  Lemma get_set_same :\n    forall k v l,\n      assoc (assoc_set l k v) k = Some v.\n  Proof.\n    induction l; intros; simpl; repeat (break_match; simpl); subst; congruence.\n  Qed.\n\n  Lemma get_set_diff :\n    forall k k' v l,\n      k <> k' ->\n      assoc (assoc_set l k v) k' = assoc l k'.\n  Proof.\n    induction l; intros; simpl; repeat (break_match; simpl); subst; try congruence; auto.\n  Qed.\n\n  Lemma not_in_assoc :\n    forall k l,\n      ~ In k (map (@fst _ _) l) ->\n      assoc l k = None.\n  Proof.\n    intros.\n    induction l.\n    - auto.\n    - simpl in *. repeat break_match; intuition.\n      subst. simpl in *. congruence.\n  Qed.\n\n  Lemma get_del_same :\n    forall k l,\n      NoDup (map (@fst _ _) l) ->\n      assoc (assoc_del l k) k = None.\n  Proof.\n    induction l; intros; simpl in *.\n    - auto.\n    - invc H.\n      repeat break_match; subst.\n      + simpl in *. apply not_in_assoc. auto.\n      + simpl in *. break_if; try congruence.\n        auto.\n  Qed.\n\n  Lemma get_del_diff :\n    forall k k' l,\n      k <> k' ->\n      assoc (assoc_del l k') k = assoc l k.\n  Proof.\n    induction l; intros; simpl in *.\n    - auto.\n    - repeat (break_match; simpl); subst; try congruence.\n      auto.\n  Qed.\nEnd assoc.\n\n", "meta": {"author": "andres-erbsen", "repo": "notary", "sha": "a2bd24db19a19642480fe17d3ee83e75ae8df61f", "save_path": "github-repos/coq/andres-erbsen-notary", "path": "github-repos/coq/andres-erbsen-notary/notary-a2bd24db19a19642480fe17d3ee83e75ae8df61f/Util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.6976580237886566}}
{"text": "Require Import CoqRefinements.Types.\nRequire Import ProofIrrelevance.\nRequire Import ZArith.\nRequire Import Lia.\nRequire Import CoqRefinements.Common.\nRequire Import CoqRefinements.Tactics.\nRequire Import PLF.LibTactics.\nRequire Import Program.Utils. (* for 'dec' *)\n\nOpen Scope Z_scope.\nSection nat_lt_ind_principle.\nVariable P : Nat -> Prop.\n\n\nHypothesis ind_n : forall n:Nat, (forall k:{v:Z | v >= 0 /\\ v < `n}, P ltac:(upcast k)) -> P n.\n\nTheorem nat_lt_ind (n: Nat) : P n.\n\n  (* enough (H0: forall p, p <= n -> P p).\n  - apply H0, le_n. *)\n  case n; intros n_val n_ref. generalize n_ref. pattern n_val. apply Z_lt_induction.\n  + intros; apply ind_n; intros; destruct k.   apply H. simpl in *.  lia.\n  + lia.\nQed.\nEnd nat_lt_ind_principle.\n\n\nSection natZ_lex_ind_principle.\nVariable P : Nat -> Nat -> Prop.\n\nHypothesis true_for_lzero : forall m n:Nat, `m = 0 -> P m n.\nHypothesis ind_m : forall m n,  `m > 0  -> (forall p q, lex_lt p q m n -> P p q) -> P m n.\n\nTheorem nat_lex_ind (m n: Nat) :  P m n.\nProof.\n  (* destruct (splitZ_zero_pos m) as [ m_zero | m_pos]. *)\n  revert n; induction m as [m IHm] using nat_lt_ind.\n\n  destruct (dec (`m =? 0)).\n  + intro; apply true_for_lzero; lia.\n  +  induction n as [n IHn] using nat_lt_ind. apply ind_m.\n    * destruct m; simpl in *; try lia.\n    * intros p q [ lt_p_m | [eq_p_m lt_q_n] ].\n      ++  applys_eq (IHm ltac:(infer p) q); reft_eq.\n      ++  enough (p = m) as -> by (applys_eq (IHn ltac:(infer q)); reft_eq); reft_eq.\nQed.\nEnd natZ_lex_ind_principle.\n\n", "meta": {"author": "lykmast", "repo": "coq-refinements", "sha": "0ec3cbfdcf9d26c14b2781d632d33d256938c765", "save_path": "github-repos/coq/lykmast-coq-refinements", "path": "github-repos/coq/lykmast-coq-refinements/coq-refinements-0ec3cbfdcf9d26c14b2781d632d33d256938c765/theories/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.6975859960694609}}
{"text": "Require Import Classical.\n\nTheorem drinker: forall A: Type, forall P: A -> Prop,\n  forall a: A,\n  exists x: A, (P x -> forall y: A, P y).\nProof.\n  intros A P a.\n  apply NNPP.\n  intro H1.\n  apply H1.\n  exists a.\n  intros Pa y.\n  apply NNPP.\n  intro H2.\n  apply H1.\n  exists y.\n  intro Py.\n  contradiction.\nQed.\n\nLemma prenex: forall A: Type, forall P: A -> Prop,\n  (forall x: A, exists y: A, P x /\\ ~ P y)\n  <-> ~ (exists x: A, P x -> forall y: A, P y).\nProof.\n  intros A P.\n  split.\n    intro H1.\n    apply all_not_not_ex.\n    intro a.\n    elim (H1 a).\n    intros b H2.\n    elim H2.\n    intros Pa nPb H3.\n    apply nPb.\n    apply H3.\n    exact Pa.\n    \n    intros H1 a.\n    apply not_all_not_ex.\n    intro H2.\n    apply (H2 a).\n    split.\n      apply NNPP.\n      intro H3.\n      apply H1.\n      exists a.\n      intro H4.\n      contradiction.\n      \n      intro H3.\n      apply H1.\n      exists a.\n      intros _ y.\n      assert (H4 := not_and_or (P a) (~ P y) (H2 y)).\n      elim H4.\n        intro nPa.\n        contradiction.\n        \n        intro nnPy.\n        apply NNPP.\n        exact nnPy.\nQed.\n\nTheorem drinker_with_prenex: forall A: Type, forall P: A -> Prop,\n  forall a: A,\n  exists x: A, (P x -> forall y: A, P y).\nProof.\n  intros A P a.\n  apply NNPP.\n  intro H1.\n  apply H1.\n  exists a.\n  intros Pa y.\n  assert (H2 := proj2 (prenex A P) H1).\n  assert (H3 := H2 y).\n  elim H3.\n  intros x H4.\n  exact (proj1 H4).\nQed.\n\n(*\nLemma all_conj: forall A: Type, forall P Q: A -> Prop,\n  (forall x: A, P x) /\\ (forall x: A, Q x)\n  <-> (forall x: A, P x /\\ Q x).\nProof.\nintros A P Q.\nsplit.\n  intros H1 x.\n  elim H1.\n  intros H2 H3.\n  split.\n    exact (H2 x).\n    \n    exact (H3 x).\n  \n  intro H1.\n  split.\n    intro x.\n    exact (proj1 (H1 x)).\n    \n    intro x.\n    exact (proj2 (H1 x)).\nQed.\n*)\n\n(*\nLemma drinker1: forall A: Type, forall P: A -> Prop,\n  (forall x : A, exists y : A, P x /\\ ~ P y)\n  -> (forall x : A, exists y : A, ~ P x \\/ P y).\nProof.\nintros A P H1 x.\nexists x.\nassert (H2 := classic (P x)).\nelim H2.\n  intro Px.\n  right.\n  exact Px.\n  \n  intro nPx.\n  left.\n  exact nPx.\nQed.\n*)\n\n", "meta": {"author": "rf0444", "repo": "coq", "sha": "ea26e698cd68ccc051a309b856c7724181be6aae", "save_path": "github-repos/coq/rf0444-coq", "path": "github-repos/coq/rf0444-coq/coq-ea26e698cd68ccc051a309b856c7724181be6aae/drinker.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.6975859938920569}}
{"text": "Inductive or (A B:Prop) : Prop :=\n  | or_introl : A -> A \\/ B\n  | or_intror : B -> A \\/ B\nwhere \"A \\/ B\" := (or A B) : type_scope.\n\n\nGoal forall P Q, P \\/ Q -> Q \\/ P.\nProof.\n  intros.\n  elim H.\n  - intros.\n    apply or_intror.\n    trivial.\n  - intros.\n    apply or_introl.\n    trivial.\nQed.\n\n(* Lemma myor_ind is automatically defined. *)\n(* \"elim\" uses it. *)", "meta": {"author": "utatatata", "repo": "coq-sandbox", "sha": "146bb7ee52d57494f57ac52daf76dd5983e9b93a", "save_path": "github-repos/coq/utatatata-coq-sandbox", "path": "github-repos/coq/utatatata-coq-sandbox/coq-sandbox-146bb7ee52d57494f57ac52daf76dd5983e9b93a/myor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.6975859851824404}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.lemma_betweennotequal.\nRequire Import ProofCheckingEuclid.lemma_extensionunique.\nRequire Import ProofCheckingEuclid.lemma_inequalitysymmetric.\nRequire Import ProofCheckingEuclid.lemma_orderofpoints_ABC_BCD_ABD.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_partnotequalwhole :\n\tforall A B C,\n\tBetS A B C ->\n\t~ Cong A B A C.\nProof.\n\tintros A B C.\n\tintros BetS_A_B_C.\n\n\tpose proof (lemma_betweennotequal _ _ _ BetS_A_B_C) as (neq_B_C & neq_A_B & _).\n\tapply lemma_inequalitysymmetric in neq_A_B as neq_B_A.\n\tpose proof (postulate_Euclid2 B A neq_B_A) as (D & BetS_B_A_D).\n\tapply axiom_betweennesssymmetry in BetS_B_A_D as BetS_D_A_B.\n\tpose proof (lemma_orderofpoints_ABC_BCD_ABD _ _ _ _ BetS_D_A_B BetS_A_B_C) as BetS_D_A_C.\n\tassert (~ Cong A B A C) as nCong_AB_AC.\n\t{\n\t\tintro Cong_AB_AC.\n\n\t\tpose proof (lemma_extensionunique _ _ _ _ BetS_D_A_B BetS_D_A_C Cong_AB_AC) as eq_B_C.\n\n\t\tcontradict eq_B_C.\n\t\texact neq_B_C.\n\t}\n\texact nCong_AB_AC.\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_partnotequalwhole.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.6975859713173664}}
{"text": "Require Import LC.Util.Fin.\nRequire Import LC.Util.Vec.\nRequire Import LC.Util.Star.\nRequire Import LC.LC.\n\nFixpoint cnum_aux {n} (x : nat) : Term (S (S n)) :=\n  match x with\n  | 0 => Var (inl tt : Fin (S (S n)))\n  | S y => App (Var (inr (inl tt) : Fin (S (S n))))\n            (cnum_aux y)\n  end.\n\nDefinition cnum (i : nat) {n} : Term n :=\n  Lam (Lam (cnum_aux i)).\n\nLemma cnum_aux_normal {n} (x : nat) :\n  normal (@cnum_aux n x).\nProof.\n  induction x; simpl; tauto.\nQed.\n\n#[export]\nInstance cnum_Const {x} : Const (@cnum x).\nProof.\n  constructor.\n  unfold cnum.\n  simpl.\n  intros n i.\n  do 2 f_equal.\n  induction x.\n  { reflexivity. }\n  { simpl.\n    now rewrite IHx.\n  }\nQed.\n\nFixpoint iter_app {n} (M : Term n) (i : nat) (N : Term n) : Term n :=\n  match i with\n  | 0 => N\n  | S j => M # (iter_app M j N)\n  end.\n\nLemma cnum_reds {n} (M N : Term n) : forall i,\n  reds (cnum i # M # N) (iter_app M i N).\nProof.\n  unfold cnum; intro i.\n  normal_order.\n  induction i; simpl.\n  { normal_order. }\n  { normal_order.\n    rewrite subst_weaken.\n    apply app_reds_r.\n    apply IHi.\n  }\nQed.\n\n", "meta": {"author": "emarzion", "repo": "lc-self-interpreter", "sha": "d3ec0e13c4e725f886d81d7d9e17dc06e4584e0f", "save_path": "github-repos/coq/emarzion-lc-self-interpreter", "path": "github-repos/coq/emarzion-lc-self-interpreter/lc-self-interpreter-d3ec0e13c4e725f886d81d7d9e17dc06e4584e0f/src/CNum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625321, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.6975859713173663}}
{"text": "Require Import Coq.Init.Prelude Coq.ZArith.ZArith. Local Open Scope Z_scope.\n\nDefinition step (n : Z) :=\n  if Z.eqb n 1 then None else\n  if Z.even n\n  then Some (Z.div2 n)\n  else Some (3*n + 1).\n\nLtac collatz :=\n  intros;\n  subst;\n  repeat\n  lazymatch goal with\n  | H: _ = ?RHS |- _ =>\n    lazymatch RHS with\n    | Some ?n =>\n    first\n      [\n        let n' := open_constr:(_) in\n        eassert (step n = Some n') by (cbv; refine eq_refl)\n      | exists n; refine eq_refl ]\n    end\n  end.\n\n(* 350 steps *)\nGoal forall n, n = 77031 -> Some n = Some n -> exists n, step n = None.\nTime collatz. Time Qed.\n(*\nFinished transaction in 1.148 secs (1.143u,0.s) (successful)\nFinished transaction in 0.077 secs (0.077u,0.s) (successful)\n*)\n\n(* 685 steps *)\nGoal forall n, n = 8400511 -> Some n = Some n -> exists n, step n = None.\nTime collatz. Time Qed.\n(*\nFinished transaction in 4.967 secs (4.877u,0.062s) (successful)\nFinished transaction in 0.208 secs (0.207u,0.s) (successful)\n*)", "meta": {"author": "andres-erbsen", "repo": "coq-experiments", "sha": "2018edd397a23c0429d316c96e86f9be7a9678f1", "save_path": "github-repos/coq/andres-erbsen-coq-experiments", "path": "github-repos/coq/andres-erbsen-coq-experiments/coq-experiments-2018edd397a23c0429d316c96e86f9be7a9678f1/experiments/bench/collatz_literal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6975771992733814}}
{"text": "(* http://d.hatena.ne.jp/hzkr/20100919 *)\n\nRequire Import Omega.\n\n\nGoal forall n: nat, exists m: nat, n = 2 * m \\/ n = 2 * m + 1.\nProof.\n  induction n.\n  - exists 0.\n    left.\n    reflexivity.\n  - destruct IHn; destruct H.\n    + exists x.\n      right.\n      omega.\n    + exists (x + 1).\n      left.\n      omega.\nQed.", "meta": {"author": "ahuglajbclajep", "repo": "coq-sandbox", "sha": "ec4eda49412481ccaeab83581859f7b1965537c6", "save_path": "github-repos/coq/ahuglajbclajep-coq-sandbox", "path": "github-repos/coq/ahuglajbclajep-coq-sandbox/coq-sandbox-ec4eda49412481ccaeab83581859f7b1965537c6/hatena-hzkr/EvenOrOdd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6975354145089034}}
{"text": "Set Implicit Arguments.\nRequire Import List.\nImport ListNotations.\n\nRequire Import Omega.  (* also makes firstorder more powerful! *)\n\n\n\n  Definition state : Set := nat * list nat.\n\n  Inductive step : state -> state -> Prop :=\n    step1_hi : forall n x xs, n > 100 -> step (1, n :: x :: xs) (x, (n - 10) :: xs)\n  | step1_lo : forall n xs, n <= 100 -> step (1, n :: xs) (1, (n + 11) :: 4 :: xs)\n  | step4 : forall n xs, step (4, n :: xs) (1, n :: 5 :: xs)\n  | step5 : forall n x xs, step (5, n :: x :: xs) (x, n :: xs)\n  .\n\n  Definition inv1 s :=\n    match s with\n      (i, n :: xs) => i = 1 \\/ i = 4 \\/ In 4 xs \\/ n >= 91\n    | _ => False\n    end.\n\n  Lemma inv1_inv s1 s2 : inv1 s1 -> step s1 s2 -> inv1 s2.\n  Proof.\n    induction 2; firstorder.\n  Qed.\n\n  Definition inv2 (s : state) :=\n    match s with\n      (i, n :: xs) => forall a, In a xs -> In a [0; 4; 5]\n    | _ => False\n    end.\n\n  Lemma inv2_inv s1 s2 : inv2 s1 -> step s1 s2 -> inv2 s2.\n  Proof.\n    induction 2; firstorder.\n  Qed.\n      \n  Fixpoint cnt4 l :=\n    match l with\n      [] => 0\n    | 4 :: xs => 1 + cnt4 xs\n    | _ :: xs => cnt4 xs\n    end.\n\n  (* Definition cnt4 l := count_occ Nat.eq_dec l 4. *)\n  \n  Definition inv3 (s : state) :=\n    match s with\n      (i, n :: xs) => (i = 1 \\/ i = 4) /\\ n <= (cnt4 xs) * 10 + 101 \\/\n                     (i = 0 \\/ i = 5) /\\ n <= (cnt4 xs) * 10 + 91\n    | _ => False\n    end.\n\n  Lemma inv3_inv s1 s2 : inv2 s1 -> inv3 s1 -> step s1 s2 -> inv3 s2.\n  Proof.\n    induction 3.\n    (* intros Inv2 Inv3 Step. *)\n    (* induction Step. *)\n    - destruct H with (a:=x).\n      + firstorder.\n      + subst. right. simpl in H0. omega.\n      + destruct H2.\n        * subst. left.\n          { destruct H0.\n            - simpl in H0. omega.\n            - simpl in H0. omega.\n          }\n        * destruct H2; try contradiction.\n          subst. right. simpl in H0. omega.\n    - left. simpl. omega.\n    - left. simpl in H0. simpl. omega.\n    - destruct H with (a:=x).\n      + firstorder.\n      + subst. right. simpl in H0. omega.\n      + destruct H1.\n        * subst.  left. simpl in H0. omega.\n        * destruct H1; try contradiction.\n          subst. right. simpl in H0. omega.\n  Qed.\n\n\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  Lemma inv123_tc s1 s2 : inv1 s1 -> inv2 s1 -> inv3 s1 -> tc step s1 s2 ->\n                          inv1 s2 /\\ inv2 s2 /\\ inv3 s2.\n  Proof.\n    induction 4.\n    - firstorder.\n    - apply IHtc; firstorder using inv1_inv, inv2_inv, inv3_inv.\n  Qed.\n\n  Theorem mccarthy91 n n' : n <= 101 -> tc step (1, [n; 0]) (0, [n']) -> n' = 91.\n  Proof.\n    intros.\n    assert (inv1 (0, [n']) /\\ inv2 (0, [n']) /\\ inv3 (0, [n'])).\n    - apply inv123_tc with (s1:=(1, [n; 0])).\n      + firstorder.\n      + firstorder.\n      + firstorder.\n      + assumption.\n    - firstorder.\n  Qed.\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/mccarthy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6975354107899243}}
{"text": "(*****************************************************************\n\n Enrichment over structured sets\n\n In this file, we look at categories enriched over a notion of\n structured sets. The notion of structured sets in consideration\n here is designed so that structures are preserved under product\n and the unit set has a structure. As such, we have a cartesian\n monoidal category of structured sets (`StructuresMonoidal.v`).\n\n We first show that this monoidal category is faithful. From this,\n it follows that all natural transformations are enriched, so\n afterwards we don't consider enriched transformations.\n\n Afterwards, we give an elementary definition of enrichment over\n structures. This elementary notion says that for every homset,\n we have a structure and that composition preserves the structure.\n This notion of enrichment is equivalent to the usual one.\n\n Lastly, we do the same for enriched functors, and for those,\n enrichment is the same as the action on morphisms being a\n structure-preserving map. Again this is equivalent to the\n general definition of enrichment.\n\n We can apply the content of this file to various notions of\n structured sets, such as posets and domains. However, note that\n not for every notion of structured set this gives the 'right'\n notion of enriched category. For example, for abelian groups\n (or modules), the corresponding notion of enriched category\n should be over a different monoidal category than the one\n induced by the cartesian structure of these categories. For these\n notions of structure, one should construct the tensor product\n instead and show that this gives rise to a monoidal category.\n\n Contents\n 1. The monoidal category is faithful\n 2. Elementary definition of enrichment over structures\n 3. Equivalence of enrichments with the elementary definition\n 4. Elementary definition of functor enrichments over structures\n 5. Equivalence of functor enrichments with elementary definition\n\n *****************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.CategoryTheory.Core.Univalence.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Examples.StructureWithProd.\nRequire Import UniMath.CategoryTheory.Monoidal.WhiskeredBifunctors.\nRequire Import UniMath.CategoryTheory.Monoidal.Categories.\nRequire Import UniMath.CategoryTheory.Monoidal.Structure.Cartesian.\nRequire Import UniMath.CategoryTheory.Monoidal.Examples.StructuresMonoidal.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Enrichment.\nRequire Import UniMath.CategoryTheory.EnrichedCats.EnrichmentFunctor.\n\nLocal Open Scope cat.\n\nSection FixAStructure.\n  Context (P : hset_struct).\n\n  (**\n   1. The monoidal category is faithful\n   *)\n  Definition category_of_hset_struct_faithful_moncat\n    : faithful_moncat (monoidal_cat_of_hset_struct P).\n  Proof.\n    intros R₁ R₂ f g p.\n    use subtypePath.\n    {\n      intro ; cbn -[isaprop].\n      apply isaprop_hset_struct_on_mor.\n    }\n    use funextsec ; intro x.\n    assert (mor_hset_struct P (hset_struct_unit P) (pr2 R₁) (λ _, x)) as H.\n    {\n      apply hset_struct_const.\n    }\n    exact (eqtohomot (maponpaths pr1 (p ((λ _, x) ,, H))) tt).\n  Qed.\n\n  (**\n   2. Elementary definition of enrichment over structures\n   *)\n  Definition struct_enrichment_data\n             (C : category)\n    : UU\n    := ∏ (x y : C), P (homset x y).\n\n  Definition struct_enrichment_laws\n             {C : category}\n             (SC : struct_enrichment_data C)\n    : UU\n    := ∏ (x y z : C),\n       mor_hset_struct\n         P\n         (hset_struct_prod P (SC y z) (SC x y))\n         (SC x z)\n         (λ (fg : C ⟦ y, z ⟧ × C ⟦ x, y ⟧), pr2 fg · pr1 fg).\n\n  Proposition isaprop_struct_enrichment_laws\n              {C : category}\n              (SC : struct_enrichment_data C)\n    : isaprop (struct_enrichment_laws SC).\n  Proof.\n    repeat (use impred ; intro).\n    apply isaprop_hset_struct_on_mor.\n  Qed.\n\n  Definition struct_enrichment\n             (C : category)\n    : UU\n    := ∑ (SC : struct_enrichment_data C),\n       struct_enrichment_laws SC.\n\n  Definition struct_enrichment_to_data\n             {C : category}\n             (SC : struct_enrichment C)\n             (x y : C)\n    : P (homset x y)\n    := pr1 SC x y.\n\n  Coercion struct_enrichment_to_data : struct_enrichment >-> Funclass.\n\n  Proposition struct_enrichment_comp\n              {C : category}\n              (SC : struct_enrichment C)\n              (x y z : C)\n    : mor_hset_struct\n        P\n        (hset_struct_prod P (SC y z) (SC x y))\n        (SC x z)\n        (λ (fg : C ⟦ y, z ⟧ × C ⟦ x, y ⟧), pr2 fg · pr1 fg).\n  Proof.\n    exact (pr2 SC x y z).\n  Qed.\n\n  (**\n   3. Equivalence of enrichments with the elementary definition\n   *)\n  Section MakeStructEnrichment.\n    Context (C : category)\n            (SC : struct_enrichment C).\n\n    Definition make_enrichment_over_struct_data\n      : enrichment_data C (monoidal_cat_of_hset_struct P).\n    Proof.\n      simple refine (_ ,, _ ,, _ ,, _ ,, _).\n      - exact (λ x y, _ ,, SC x y).\n      - refine (λ x, (λ _, identity _) ,, _).\n        abstract\n          (cbn ;\n           apply hset_struct_const).\n      - simple refine (λ x y z, _ ,, _) ; cbn in *.\n        + exact (λ fg, pr2 fg · pr1 fg).\n        + apply struct_enrichment_comp.\n      - refine (λ x y f, (λ _, f) ,, _).\n        apply hset_struct_const.\n      - exact (λ x y f, pr1 f tt).\n    Defined.\n\n    Proposition make_enrichment_over_struct_laws\n      : enrichment_laws make_enrichment_over_struct_data.\n    Proof.\n      repeat split.\n      - intros x y.\n        use eq_mor_hset_struct.\n        intro a ; cbn.\n        rewrite id_right.\n        apply idpath.\n      - intros x y.\n        use eq_mor_hset_struct.\n        intro a ; cbn.\n        rewrite id_left.\n        apply idpath.\n      - intros w x y z.\n        use eq_mor_hset_struct.\n        intro a ; cbn.\n        rewrite assoc.\n        apply idpath.\n      - intros x y f.\n        use eq_mor_hset_struct.\n        intro a ; cbn in *.\n        apply maponpaths.\n        apply isapropunit.\n    Qed.\n\n    Definition make_enrichment_over_struct\n      : enrichment C (monoidal_cat_of_hset_struct P)\n      := make_enrichment_over_struct_data ,, make_enrichment_over_struct_laws.\n  End MakeStructEnrichment.\n\n  Section FromStructEnrichment.\n    Context (C : category)\n            (E : enrichment C (monoidal_cat_of_hset_struct P)).\n\n    Definition mor_to_enriched_hom\n               {x y : C}\n               (f : x --> y)\n      : pr11 (E ⦃ x , y ⦄)\n      := pr1 (enriched_from_arr E f) tt.\n\n    Definition enriched_hom_to_mor\n               {x y : C}\n               (f : pr11 (E ⦃ x , y ⦄))\n      : x --> y.\n    Proof.\n      assert (mor_hset_struct P (hset_struct_unit P) (pr2 (E ⦃ x, y ⦄)) (λ _, f)) as H.\n      {\n        apply hset_struct_const.\n      }\n      exact (enriched_to_arr E (_ ,, H)).\n    Defined.\n\n    Definition mor_weq_enriched_hom\n               (x y : C)\n      : pr11 (E ⦃ x , y ⦄) ≃ (x --> y).\n    Proof.\n      use weq_iso.\n      - exact enriched_hom_to_mor.\n      - exact mor_to_enriched_hom.\n      - abstract\n          (intro f ;\n           unfold mor_to_enriched_hom, enriched_hom_to_mor ;\n           rewrite enriched_from_to_arr ;\n           apply idpath).\n      - abstract\n          (intro f ;\n           unfold mor_to_enriched_hom, enriched_hom_to_mor ;\n           refine (_ @ enriched_to_from_arr E f) ;\n           apply maponpaths ;\n           use eq_mor_hset_struct ;\n           intro t ; cbn ;\n           apply maponpaths ;\n           apply isapropunit).\n    Defined.\n\n    Definition make_struct_enrichment_data\n      : struct_enrichment_data C.\n    Proof.\n      intros x y.\n      refine (transportf_struct_weq P _ (pr2 (E ⦃ x , y ⦄))).\n      exact (mor_weq_enriched_hom x y).\n    Defined.\n\n    Proposition make_struct_enrichment_laws\n      : struct_enrichment_laws make_struct_enrichment_data.\n    Proof.\n      intros x y z.\n      use (transportf_struct_mor_prod_via_eq P).\n      - exact (pr1 (enriched_comp E x y z)).\n      - exact (pr2 (enriched_comp E x y z)).\n      - intros fg ; cbn.\n        unfold enriched_hom_to_mor.\n        rewrite (enriched_to_arr_comp E).\n        apply maponpaths.\n        use eq_mor_hset_struct.\n        intro t ; induction t.\n        apply idpath.\n    Qed.\n\n    Definition make_struct_enrichment\n      : struct_enrichment C.\n    Proof.\n      simple refine (_ ,, _).\n      - exact make_struct_enrichment_data.\n      - exact make_struct_enrichment_laws.\n    Defined.\n  End FromStructEnrichment.\n\n  Section EnrichmentEquiv.\n    Context {C : category}\n            (E : enrichment C (monoidal_cat_of_hset_struct P)).\n\n    Definition enrichment_over_struct_weq_struct_enrichment_iso\n               (x y : C)\n      : @z_iso\n          (category_of_hset_struct P)\n          (homset x y ,, make_struct_enrichment_data C E x y)\n          (E ⦃ x , y ⦄).\n    Proof.\n      use make_z_iso.\n      - simple refine (_ ,, _).\n        + exact (λ f, pr1 (enriched_from_arr E f) tt).\n        + cbn.\n          apply transportf_struct_weq_on_invweq.\n      - simple refine (_ ,, _).\n        + refine (λ f, enriched_to_arr E ((λ _, f) ,, _)).\n          apply hset_struct_const.\n        + cbn.\n          apply transportf_struct_weq_on_weq.\n      - split.\n        + use eq_mor_hset_struct.\n          intro w ; cbn.\n          refine (_ @ enriched_to_from_arr E _).\n          apply maponpaths.\n          use eq_mor_hset_struct.\n          intro t.\n          cbn.\n          apply maponpaths.\n          apply isapropunit.\n        + use eq_mor_hset_struct.\n          intro f.\n          cbn.\n          rewrite enriched_from_to_arr.\n          apply idpath.\n    Defined.\n\n    Definition enrichment_over_struct_weq_struct_enrichment_inv_1\n      : make_enrichment_over_struct C (make_struct_enrichment C E) = E.\n    Proof.\n      use subtypePath.\n      {\n        intro.\n        apply isaprop_enrichment_laws.\n      }\n      use (invweq (total2_paths_equiv _ _ _)).\n      use (invmap (enrichment_data_hom_path _ _ _)).\n      {\n        exact (is_univalent_category_of_hset_struct P).\n      }\n      simple refine (_ ,, _ ,, _ ,, _ ,, _).\n      - exact enrichment_over_struct_weq_struct_enrichment_iso.\n      - intro x.\n        use eq_mor_hset_struct.\n        intro t ; cbn.\n        rewrite enriched_from_arr_id.\n        apply maponpaths.\n        apply isapropunit.\n      - intros x y z.\n        use eq_mor_hset_struct.\n        intro t ; cbn.\n        rewrite enriched_from_arr_comp ; cbn.\n        apply idpath.\n      - intros x y f.\n        use eq_mor_hset_struct.\n        intro t.\n        cbn.\n        apply maponpaths.\n        apply isapropunit.\n      - intros x y f.\n        cbn.\n        assert (mor_hset_struct\n                  P\n                  (hset_struct_unit P)\n                  (make_struct_enrichment_data C E x y)\n                  (λ _, pr1 f tt))\n          as H.\n        {\n          apply hset_struct_const.\n        }\n        refine (!(enriched_to_from_arr E (pr1 f tt)) @ _).\n        apply maponpaths.\n        use eq_mor_hset_struct.\n        intro t ; induction t.\n        cbn.\n        apply idpath.\n    Defined.\n  End EnrichmentEquiv.\n\n  Proposition enrichment_over_struct_weq_struct_enrichment_inv_2\n              {C : category}\n              (E : struct_enrichment C)\n    : make_struct_enrichment C (make_enrichment_over_struct C E) = E.\n  Proof.\n    use subtypePath.\n    {\n      intro.\n      apply isaprop_struct_enrichment_laws.\n    }\n    use funextsec ; intro x.\n    use funextsec ; intro y.\n    simpl.\n    unfold make_struct_enrichment_data.\n    unfold make_enrichment_over_struct.\n    simpl.\n    unfold transportf_struct_weq.\n    refine (_ @ idpath_transportf _ _).\n    apply maponpaths_2.\n    refine (_ @ univalence_hSet_idweq _).\n    apply maponpaths.\n    use subtypePath.\n    {\n      intro ; apply isapropisweq.\n    }\n    apply idpath.\n  Qed.\n\n  Definition enrichment_over_struct_weq_struct_enrichment\n             (C : category)\n    : enrichment C (monoidal_cat_of_hset_struct P) ≃ struct_enrichment C.\n  Proof.\n    use weq_iso.\n    - exact (make_struct_enrichment C).\n    - exact (make_enrichment_over_struct C).\n    - apply enrichment_over_struct_weq_struct_enrichment_inv_1.\n    - apply enrichment_over_struct_weq_struct_enrichment_inv_2.\n  Defined.\n\n  (**\n   4. Elementary definition of functor enrichments over structures\n   *)\n  Definition functor_struct_enrichment\n             {C₁ C₂ : category}\n             (P₁ : struct_enrichment C₁)\n             (P₂ : struct_enrichment C₂)\n             (F : C₁ ⟶ C₂)\n    : UU\n    := ∏ (x y : C₁), mor_hset_struct P (P₁ x y) (P₂ (F x) (F y)) (λ f, #F f).\n\n  (**\n   5. Equivalence of functor enrichments with elementary definition\n   *)\n  Definition make_functor_struct_enrichment\n             {C₁ C₂ : category}\n             (P₁ : struct_enrichment C₁)\n             (P₂ : struct_enrichment C₂)\n             (F : C₁ ⟶ C₂)\n             (HF : functor_enrichment\n                     F\n                     (make_enrichment_over_struct C₁ P₁)\n                     (make_enrichment_over_struct C₂ P₂))\n    : functor_struct_enrichment P₁ P₂ F.\n  Proof.\n    intros x y.\n    refine (transportf\n              _\n              _\n              (pr2 (HF x y))).\n    use funextsec.\n    intro f.\n    pose (eqtohomot\n            (maponpaths\n               pr1\n               (functor_enrichment_from_arr HF f))\n            tt)\n      as p.\n    cbn in p.\n    exact (!p).\n  Qed.\n\n  Definition make_functor_enrichment_over_struct\n             {C₁ C₂ : category}\n             (P₁ : struct_enrichment C₁)\n             (P₂ : struct_enrichment C₂)\n             (F : C₁ ⟶ C₂)\n             (HF : functor_struct_enrichment P₁ P₂ F)\n    : functor_enrichment\n        F\n        (make_enrichment_over_struct C₁ P₁)\n        (make_enrichment_over_struct C₂ P₂).\n  Proof.\n    simple refine (_ ,, _).\n    - exact (λ x y, (λ f, #F f) ,, HF x y).\n    - repeat split.\n      + abstract\n          (intros x ;\n           use eq_mor_hset_struct ;\n           intro f ; cbn ;\n           apply functor_id).\n      + abstract\n          (intros x y z ;\n           use eq_mor_hset_struct ;\n           intro f ; cbn ;\n           apply functor_comp).\n      + abstract\n          (intros x y f ;\n           use eq_mor_hset_struct ;\n           intro w ; cbn ;\n           apply idpath).\n  Defined.\n\n  Definition functor_enrichment_over_struct_weq_struct_enrichment\n             {C₁ C₂ : category}\n             (P₁ : struct_enrichment C₁)\n             (P₂ : struct_enrichment C₂)\n             (F : C₁ ⟶ C₂)\n    : functor_enrichment\n        F\n        (make_enrichment_over_struct C₁ P₁)\n        (make_enrichment_over_struct C₂ P₂)\n      ≃\n      functor_struct_enrichment P₁ P₂ F.\n  Proof.\n    use weq_iso.\n    - exact (make_functor_struct_enrichment P₁ P₂ F).\n    - exact (make_functor_enrichment_over_struct P₁ P₂ F).\n    - abstract\n        (intro EF ;\n         use subtypePath ; [ intro ; apply isaprop_is_functor_enrichment | ] ;\n         use funextsec ; intro x ;\n         use funextsec ; intro y ;\n         use eq_mor_hset_struct ;\n         intro f ;\n         cbn ;\n         exact (eqtohomot (maponpaths pr1 (functor_enrichment_from_arr EF f)) tt)).\n    - abstract\n        (intros EF ;\n         use funextsec ; intro x ;\n         use funextsec ; intro y ;\n         cbn ;\n         apply isaprop_hset_struct_on_mor).\n  Defined.\nEnd FixAStructure.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/CategoryTheory/EnrichedCats/Examples/StructureEnriched.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6975354061039241}}
{"text": "\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Arith.Wf_nat.\nRequire Import Recdef.\n\nOpen Scope nat_scope.\n\nImport ListNotations.\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 : nat (* height of the tree it represents *)\n            -> tree\n    | Bin : nat -> (* height *)\n            tree -> (* left child *)\n            tree ->  (* right child *)\n            tree.\n\n(* functions on trees *)\n\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\nInductive s_inc : (list tree) -> Prop :=\n  | s_inc_nil  : s_inc nil\n  | s_inc_sin  : forall (x : tree), s_inc (x :: nil)\n  | s_inc_two  : forall (x y : tree), ht x < ht y -> s_inc (x :: y :: nil)\n  | s_inc_cons : forall (x y : tree) (ys : list tree), ht x < ht y /\\ s_inc (y :: ys) -> s_inc (x :: y :: ys).\n(*\nExample first : s_inc ((Bin 1)::(Bin 2)::nil).\nProof.\n  apply s_inc_two with (x := Bin 1) (y := Bin 2). intuition.\nQed.\n\nExample sec : s_inc ((Bin 1)::(Bin 2)::(Bin 3)::(Bin 4)::nil).\nProof.\n  apply s_inc_cons. simpl. split; [|apply s_inc_cons; simpl; intuition; apply s_inc_two]; intuition.\nQed.\n*)\nInductive lmp : tree -> tree -> list tree -> Set :=\n  | lmp_pair : forall (a b : tree), lmp a b (a :: b :: nil)\n  | lmp_threel : forall (a b x : tree), \n                   (ht a < ht b /\\ ht x >= ht b) \\/ ht b <= ht a \n                   -> lmp a b (x :: a :: b :: nil)\n  | lmp_threer : 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  | lmp_left : 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  | lmp_right : 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(*\nExample lmp_first : lmp (Bin 2) (Bin 3) (Bin 4 :: Bin 2 :: Bin 3 :: Bin 5 :: nil).\nProof.\n  apply lmp_right with (x := Bin 4) (y := Bin 5) (l1 := nil) (l2 := nil).\n    reflexivity. \n    intuition.\n    intuition.\n    intuition.\nQed.\n*)\nTheorem s_inc_two_lmp : forall (a b : tree) (l1 l2 : list tree), \n  l1 = (a :: b :: l2) -> s_inc l1 -> lmp a b l1.\nProof.\n  intros a b l1 l2 Cons Inc. rewrite Cons. \n  destruct l2 as [|y]. apply lmp_pair. \n    (* step *) apply lmp_threer. left. \n    (* using the fact that the list is strictly increasing on both cases *)\n      split; rewrite Cons in Inc; inversion Inc; inversion H0.\n        assumption.\n        inversion H4. assumption. inversion H6. assumption.\nQed.\n\nDefinition minimum (l : list tree) (t : tree) : Prop :=\n  forall (t' : tree), flatten t' = l -> ht t <= ht t'.\n\n(* Implementation of the algorithm itself *)\n(*\nInductive Step_acc : list tree -> Set :=\n  | step_nil  : Step_acc nil\n  | step_sin  : forall (u : tree),  Step_acc (u :: nil)\n  | step_mul  : forall (u v : tree) (ts : list tree) (pts : Step_acc ts),\n                       Step_acc (v :: ts) ->\n                       Step_acc (step pts (join u v) ts) ->\n                       Step_acc (u :: v :: ts).\n*)\n\nDefinition admit {T: Type} : T. Admitted.\n\nFixpoint step (t : tree) (xs : list tree) (n : nat) {struct n} : list tree :=\n    match xs,n with\n    | nil,_       => [t]\n    | _, 0        => [t]\n    | u :: nil, _ =>\n        match nat_compare (ht t) (ht u) with\n        | Lt => t :: u :: nil\n        | _  => (join t u) :: nil\n        end\n    | u :: v :: ts, S n2 =>\n        match nat_compare (ht t) (ht u) with\n        | Lt => t :: u :: v :: ts\n        | _  =>\n            match nat_compare (ht t) (ht v) with\n            | Lt => step (join t u) (v :: ts) (n2)\n            | _  => step t (step (join u v) ts n2) (n2)\n            end\n        end\n(*    | u :: v :: ts, _ => t :: nil *)\n    end.\n\n\n(*  match acc, xs with\nFixpoint step (t : tree) (xs : list tree) : list tree := \n  admit.\n  | step_nil, nil      => t :: nil\n  | step_sin, u :: nil => \n     match nat_compare (ht t) (ht u) with\n     | Lt => t :: u :: nil\n     | _  => (join t u) :: nil\n     end\n  | (step_mul pts pvts pstep), u :: v :: ts => \n        match nat_compare (ht t) (ht u) with\n        | Lt => t :: u :: v :: ts\n        | _  =>\n            match nat_compare (ht t) (ht v) with\n            | Lt => step pvts (join t u) (v :: ts)\n            | _  => step pstep t (step pts (join u v) ts)\n            end\n        end\n    end.*)\n\nTheorem step_inc : forall (l : list tree) (t : tree),\n  s_inc l -> s_inc (step t l (length l)).\nProof.\n  induction l. simpl. intros t Sinc. apply s_inc_sin.\n  (* step *) induction l. simpl. intros t sIncA. remember (nat_compare (ht t) (ht a)) as H. destruct H; [apply s_inc_sin | apply s_inc_two; apply nat_compare_lt; symmetry; assumption | apply s_inc_sin].\n    (* step *) intros t sInc. unfold step. \nAdmitted.\n\nTheorem fold_right_step : forall (l : list tree),\n  s_inc (fold_right (fun (a : tree) (xs : list tree) => step a xs (length xs)) nil l).\nProof.\n  induction l as [|l']. simpl. apply s_inc_nil. simpl. apply step_inc. assumption.\nQed.\n\nTheorem step_not_nil : forall (l : list tree) (t : tree),\n  step t l (length l) <> [].\nProof.\n  induction l. simpl. intros t contra. inversion contra. \n (* step *) induction l. simpl. intros t. case (nat_compare (ht t) (ht a)). intros contra. inversion contra. intros contra. inversion contra. intros contra. inversion contra. \n   (* step *) intros t. unfold step. case (nat_compare (ht t) (ht a)).\n   (* 1/3 : induction h, 2/3 trivial, 3/3 : induction h *)\nAdmitted.\n\nTheorem fold_right_not_nil : forall (l : list tree),\n  l <> [] -> fold_right (fun (a : tree) (xs : list tree) => step a xs (length xs)) [] l <> [].\nProof.\n  induction l. intros LNNil. simpl. assumption.\n  (* step *) intros alNNil. simpl. apply step_not_nil.\nQed.\n\nTheorem fold_step_not_nil : forall (l : list tree),\n  l <> nil -> (fold_right (fun (a : tree) (xs : list tree) => step a xs (length xs)) nil l) <> nil.\nProof.\n  intros l NNil. apply fold_right_not_nil. assumption.\nQed.\n\nDefinition foldl1 (f : tree -> tree -> tree) (l : list tree) (P : l <> nil) : tree. \n  case l as [| x xs].\n  contradiction P. reflexivity.\n  apply fold_left with (B := tree). \n  exact f. exact xs. exact x.\nDefined.\n(*\nTheorem foldl1test : [Tip 2; Tip 3] <> [].\nProof.\n  intuition. inversion H.\nQed.\n\n\nEval program in (foldl1 join [Tip 2;Tip 3] (foldl1test)).\n*)\n\nTheorem foldl1_fold_left : forall (t : tree) (l1 : list tree) (P : l1 <> []),\n  foldl1 join l1 P = fold_left join l1 t.\nProof.\n  intros t l1 NNil. \nAdmitted.\n\nTheorem join_preserves : forall (t1 t2 t3 : tree) (l s: list tree) (sub : l = [t1;t2] ++ s),\n  lmp t1 t2 l -> minimum l t3 -> minimum (join t1 t2 :: s) t3.\nProof.\nAdmitted.\n\nTheorem Lemma1 : forall (l s : list tree) (a b : tree) (sub : l = [a;b] ++ s),\n  lmp a b l -> exists (t : tree), siblings t a b -> minimum l t.\nProof.\nAdmitted.\n\nTheorem foldl1_join : forall (t1 t2 : tree) (l1 l2 : list tree) (P: l1 <> []) (sub : l1 = [t1;t2] ++ l2),\n  siblings t1 t2 (foldl1 join l1 P).\nProof.\nAdmitted.\n\nTheorem join_pairs : forall (t1 t2 : tree) (l1 l2 : list tree) (P : l1 <> []) (sub : l1 = [t1;t2] ++ l2), \n  lmp t1 t2 l1 -> minimum l1 (foldl1 join l1 P).\nProof.\n  intros t1 t2 l1 l2 P sub lmp.\nAdmitted.\n\nTheorem flatten_pres_ht : forall (t hd : tree),\n  flatten t = hd :: nil -> ht hd <= ht t.\nProof.\n  intros t hd flthd. induction t. simpl in *. \n    (* trivial *)\n    (* trivial from contradiction, flatten Bin cannot lead to a list of size 1 *)\nAdmitted.\n\nTheorem foldl1_is_min : forall (l1 : list tree) (P : l1 <> []),\n  s_inc l1 -> minimum l1 (foldl1 join l1 P).\nProof.\n  intros l1 NNil Sinc. destruct l1. contradiction NNil. reflexivity.\n  (* <> nil *) destruct l1. simpl. unfold minimum. intros t' flt'. apply flatten_pres_ht. assumption. \n    (* <> nil *) apply join_pairs with (t1 := t) (t2 := t0) (l2 := l1). reflexivity. apply s_inc_two_lmp with (l2 := l1). reflexivity. assumption.\nQed.\n\nDefinition build (xs : list tree) (P : xs <> []) : tree := \n  foldl1 join (fold_right (fun (a : tree) (xs : list tree) => step a xs (length xs)) nil xs) (fold_step_not_nil xs P).\n\nTheorem build_is_min : forall (l : list tree) (t : tree) (P : l <> nil), \n  t = build l P -> minimum l t.\nProof.\n  intros l t NNil BRes. unfold build in BRes. rewrite BRes. apply foldl1_is_min. \n    reflexivity.\n    apply fold_right_step.\nQed.\n", "meta": {"author": "ltbinsbe", "repo": "INFODTP", "sha": "2995a6503d4b8028f83a0907e83bcd85dd417d48", "save_path": "github-repos/coq/ltbinsbe-INFODTP", "path": "github-repos/coq/ltbinsbe-INFODTP/INFODTP-2995a6503d4b8028f83a0907e83bcd85dd417d48/coq/abandonware/BoveCapretta.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6975354025187077}}
{"text": "Require Import Coq.ZArith.ZArith Coq.Classes.RelationClasses.\n\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma ge_refl x : x >= x.\n  Proof. rewrite !Z.ge_le_iff; reflexivity. Qed.\n  Lemma ge_trans n m p : n >= m -> m >= p -> n >= p.\n  Proof. rewrite !Z.ge_le_iff; eauto using Z.le_trans. Qed.\n\n  Global Instance ge_preorder : PreOrder Z.ge.\n  Proof. constructor; hnf; [ apply ge_refl | apply ge_trans ]. Defined.\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/Ge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6975354010012947}}
{"text": "(** * MoreCoq: Mas Sobre Coq *)\n\nRequire Export Poly.\n\n(** Este capitulo introduce varias tacticas que, en conjunto, nos\n    ayudan a demostrar muchos teoremas sobre los programas funcionales\n    que estuvimos escribiendo.  *)\n\n(* ###################################################### *)\n(** * La Tactica [apply] *)\n\n(** Usualmente nos encontramos en situaciones en que el objetivo a ser\n    demostrado es exactamente lo mismo que alguna hipotesis en el\n    contexto o un lema previo. *)\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  (* En este punto, podemos concluir con\n     \"[rewrite -> eq2. reflexivity.]\" como hemos hecho varias veces\n     anteriormente.  Pero podemos lograr lo mismo en un solo paso\n     usando la tactica [apply]: *)\n  apply eq2.  Qed.\n\n(** La tactica [apply] tambien funciona con hipotesis _condicionales_\n    y lemas: si el lema siendo aplicado es una implicacion, entonces\n    las premisas de esta implicacion van a ser agregadas a nuestra\n    lista de sub-objetivos a demostrar. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2. \n  apply eq2. apply eq1.  Qed.\n\n(** Puede encontrar instructivo experimentar con esta prueba y ver si\n    existe forma de utilizar [rewrite] para resolverla, en vez de\n    [apply]. *)\n\n(** Tipicamente, cuando usamos [apply H], el lema (o hipotesis) [H] va\n    a comenzar con un ligador [forall] ligando _variables\n    universales_.  Cuando Coq \"matchea\" (unifica) el objetivo actual\n    contra la conclusion de [H], va a intentar encontrar valores\n    apropiados para estas variables.  Por ejemplo, cuando hacemos\n    [apply eq2] en la siguente prueba, la variable universal [q] en\n    [eq2] es instanciada con [n] y [r] es instanciada con [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(** **** Ejercicio: 2 stars, opcional (silly_ex) *)\n(** Complete la siguiente prueba sin utilizar [simpl]. *)\n\nTheorem silly_ex : \n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 3 = true ->\n     oddb 4 = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Para usar la tactica [apply], la (conclusion del) lema siendo\n    aplicado tiene que matchear el objetivo _exactamente_ -- por\n    ejemplo, [apply] no va a funcionar si el lado izquierdo y el lado\n    derecho de la igualdad estan intercambiados. *)\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  (* Aqui no podemos utilizar la tactica [apply] directamente *)\nAbort.\n\n(** En este caso podemos utilizar la tactica [symmetry], que\n    intercambia los lados izquierdo y derecho de una igualdad en el\n    objetivo.  *)\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. (* De hecho, este [simpl] no es necesario, puesto \n            que [apply] hace un paso de [simpl] primero. *)  \n  apply H.  Qed.         \n\n(** **** Ejercicio: 3 stars (apply_exercise1) *)\n(** Ayuda: usted puede usar [apply] con lemas definidos previamente,\n    no solo hipotesis en el contexto.  Recuerde que [SearchAbout] es\n    su amigo! *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 1 star, optional (apply_rewrite) *)\n(** Explique brevemente la diferencia entre las tacticas [apply] y\n    [rewrite].  Hay situaciones en las que ambas puedan ser\n    exitosamente aplicadas?\n  (* FILL IN HERE *)\n*)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * La Tactica [apply ... with ...] *)\n\n(** El siguiente ejemplo tonto utiliza dos rewrites seguidos para ir\n    de [[a,b]] a [[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(** Como es comun tener este tipo de situaciones, podemos abstraer en\n    un lema el hecho de que la igualdad es transitiva.  *)\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(** Ahora, deberiamos poder utilizar [trans_eq] para provar el ejemplo\n    de mas arriba.  Sin embargo, para hacer esto necesitamos una\n    pequenia variacion de la tactica [apply].  *)\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  (* Si le decimos a Coq simplemente [apply trans_eq] en este punto,\n     puede deducir (mediante el matcheo del objetivo con la conclusion\n     del lema) que debe instanciar [X] con [[nat]], [n] con [[a,b]], y\n     [o] con [[e,f]].  Sin embargo, el proceso de matcheo no determina\n     una instanciacion para [m]: tenemos que suplir uno explicitamnete\n     agregando [with (m:=[c,d])] a la invocacion de [apply]. *)\n     apply trans_eq with (m:=[c;d]). apply eq1. apply eq2.  Qed.\n\n(** De hecho, usualmente no tenemos que incluir el nombre [m] en la\n    clausula [with]; Coq es muchas veces inteligente y puede darse\n    cuenta de que instanciacion estamos proveyendo.  Podemos escribir\n    entonces: [apply trans_eq with [c,d]]. *)\n\n(** **** Ejercicio: 3 stars, opcional (apply_with_exercise) *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o). \nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * La Tactica [inversion] *)\n\n(** Recuerde la definicion de numeros naturales:\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n\n    Es claro de esta definicion que cada numero tiene una de dos\n    formas: o es el constructor [O] o esta construido a partir de\n    aplicar el constructor [S] a otro numero.  Pero hay mas aqui que\n    lo que el ojo puede ver: implicito en esta definicion (y en\n    nuestra forma de entender informalmente como las declaraciones de\n    tipo funcionan en otros lenguajes de programacion) tambien hay\n    otros dos hechos:\n\n    - El constructor [S] es _inyectivo_.  Es decir, la unica forma de\n      tener [S n = S m] es si [n = m].\n\n    - Los constructores [O] y [S] son _disjuntos_.  Es decir, [O] no\n      es igual a [S n] para ningun [n]. *)\n\n(** Principios similares se aplican a todos los tipos definidos\n    inductivamente: todos los constructores son inyectivos, y los\n    valores construidos con distintos constructores son diferentes.\n    Para listas, el constructor [cons] es inyectivo y [nil] es\n    diferente de cualquier lista no vacia.  Para booleanos, [true] and\n    [false] son diferentes.  (Como [true] y [false] no toman ningun\n    argumento, su inyectividad es irrelevante). *)\n\n(** Coq provee una tactica llamada [inversion] que nos permite\n    explotar estos principios en una prueba.\n \n    La tactica [inversion] es usada de la siguiente forma.  Suponga\n    que [H] es una hipotesis en el context (o un lema ya establecido)\n    de la forma\n      c a1 a2 ... an = d b1 b2 ... bm\n    para dos constructores [c] y [d] y argumentos [a1 ... an] y [b1\n    ... bm].  Entonces [inversion H] instruye a Coq a \"invertir\" esta\n    igualdad para extraer la informacion que contiene acerca de estos\n    terminos:\n\n    - Si [c] y [d] son el mismo constructor, entonces sabemos, por el\n      principio de inyectividad de este constructor, que [a1 = b1],\n      [a2 = b2], etc.; [inversion H] agrega estos conocimientos al\n      contexto, e intenta utilizarlos para reescribir el objetivo.\n\n    - Si [c] y [d] son constructores diferentes, entonces la hipotesis\n      [H] es contradictoria.  Es decir, una premisa falsa ha aparecido\n      en nuestro contexto, y esto significa que cualquier objetivo es\n      demostrable!  En este caso, [inversion H] marca el objetivo\n      actual como completo y lo saca del stack de objetivos por\n      resolver. *)\n\n(** Posiblemente la tactica [inversion] sea mas facil de entender\n    viendola en accion que en descripciones generales como la de\n    arriba.  Abajo va a encontrar ejemplos de teoremas que muestran el\n    uso de [inversion] y ejercicios para probar su entendimiento.  *)\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(** Como conveniencia, la tactica [inversion] tambien puede destruir\n    igualdades entre valores complejos, ligando multiples variables a\n    la vez. *)\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(** **** Ejercicio: 1 star (sillyex1) *) \nExample sillyex1 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = z :: j ->\n     y :: l = x :: j ->\n     x = y.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nTheorem silly6 : forall (n : nat),\n     S n = O ->\n     2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem silly7 : forall (n m : nat),\n     false = true ->\n     [n] = [m].\nProof.\n  intros n m contra. inversion contra.  Qed.\n\n(** **** Ejercicio: 1 star (sillyex2) *)\nExample sillyex2 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = [] ->\n     y :: l = z :: j ->\n     x = z.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Mientras que la inyectividad de los constructores nos permite\n    razonar acerca de [forall (n m : nat), S n = S m -> n = m], la\n    direccion inversa de la implicacion es una instancia de un caso\n    mas general acerca de constructores y funciones, que vamos a\n    encontrar util: *)\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(** Aqui hay otro ejemplo de [inversion].  Este ejemplo es una\n    modificacion de lo que probamos arriba.  Las igualdades extras nos\n    forzan a hacer un poco de razonamiento ecuacional y ejercitar las\n    tacticas que vimos recientemente. *)\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(** **** Ejercicio: 2 stars, opcional (practice) *)\n(** Un par de ejemplos no triviales pero tampoco tan complicados para\n    ejercitar estos conceptos.  Pueden requerir lemas ya provados\n    anteriormente.  *)\n \n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem beq_nat_0_r : forall n,\n   beq_nat n 0 = true -> n = 0.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Usando Tacticas en las Hipotesis *)\n\n(** Por defecto, la mayoria de las tacticas funcionan en el objetivo y\n    dejan el contexto sin cambiar.  Sin embargo, la mayoria de las\n    tacticas tambien tienen una variante que realiza una operacion\n    similar en una premisa del contexto. \n\n    Por ejemplo, la tactica [simpl in H] realiza una simplificaion en\n    la hipotesis llamada [H] en el contexto. *)\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(** De forma similar, la tactica [apply L in H] matchea algun lema o\n    hipotesis condicional [L] (de la forma [L1 -> L2], digamos) contra\n    una hipotesis [H] en el contexto.  Sin embargo, a diferencia del\n    [apply] ordinario (que reescribe el objetivo matcheando [L2] en el\n    sub-objetivo [L1]), [apply L in H] matchea [H] contra [L1] y, si\n    es exitoso, lo reemplaza con [L2].\n \n    En otras palabras, [apply L in H] nos da una forma de\n    \"razonamiento hacia adelante\" -- de [L1 -> L2] y una hipotesis\n    matcheando [L1], nos da una hipotesis matcheando [L2].  En\n    contraste, [apply L] es \"razonamiento hacia atras\" -- dice que si\n    sabemos [L1->L2] y queremos probar [L2], es suficiente con probar\n    [L1].\n\n    Aqui hay una variante de una prueba de arriba, usando razonamiento\n    hacia adelante en toda la prueba, en vez de hacia atras. *)\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(** El razonamiento hacia adelante empieza desde lo que esta _dado_\n    (las premisas, teoremas provados anteriormente), e iterativamente\n    obtiene conclusiones desde ellos hasta que el objetivo es\n    encontrado.  El razonamiento hacia atras empieza desde el\n    _objetivo_, e iterativamente razona acerca que puede implicar el\n    objetivo, hasta llegar a las premisas o teoremas existentes.  Si\n    usted ha visto pruebas informales antes (por ejemplo, en\n    matematica o en una clase de ciencias de la computacion),\n    probablemente hayan utilizado razonamiento hacia adelante.  En\n    general, Coq tiende a favorecer razonamiento hacia atras, pero en\n    algunas situaciones el estilo de razonamiento hacia adelante puede\n    ser mas facil de usar o de pensar.  *)\n\n(** **** Ejercicio: 3 stars (plus_n_n_injective) *)\n(** Practique utilizando variantes de \"in\" en este ejercicio. *)\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    (* Ayuda: utilice el lema plus_n_Sm *)\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Variando la Hipotesis Inductiva *)\n\n(** A veces es importante controlar la forma exacta de la hipotesis\n    inductiva.  En particular, necesitamos ser cuidadosos acerca de\n    que premisas movemos del objetivo al contexto (usando [intros])\n    antes de invocar la tactica [induction]. Por ejemplo, suponga que\n    queremos mostrar que la funcion [double] es inyectiva -- es decir,\n    que siempre mapea diferentes argumentos a diferentes resultados:\n\n    Theorem double_injective: forall n m, double n = double m -> n = m.\n\n    La forma que _empezamos_ esta demostracion es un poco delicada: si\n    comenzamos con [intros n. induction n.] todo va bien.  Pero si\n    comenzamos con [intros n m. induction n.] nos quedamos estancados\n    en el medio del caso inductivo...  *)\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      (* Aqui estamos estancados.  La hipotesis inductiva, [IHn'], nos\n         da [n' = m'] -- hay un extra [S] en el camino -- asi que este\n         objetivo no es demostrable. *) \nAbort.\n\n(** Que salio mal? *)\n\n(** El problema es que, en el punto en que invocamos la hipotesis\n    inductiva, ya hemos introducido [m] en el contexto --\n    intuitivamente le dijimos a Coq \"Consideremos unos [n] y [m]\n    particulares...\" y ahora vamos a demostrar que, si [double n =\n    double m] para _este [n] y [m] en particular_, entonces [n = m].\n\n    La siguiente tactica, [induction n], le dice a Coq: Ahora vamos a\n    mostrar el objetivo por induccion en [n].  Es decir, vamos a\n    provar que la proposicion\n\n      - [P n]  =  \"si [double n = double m], entonces [n = m]\"\n\n    vale para todo [n] mostrando\n\n      - [P O]              \n\n         (es decir, \"si [double O = double m] entonces [O = m]\")\n\n      - [P n -> P (S n)]  \n\n        (es decir, \"si [double n = double m] entonces [n = m]\" implica \"si\n        [double (S n) = double m] entonces [S n = m]\").\n\n    Si miramos en detalle al segundo objetivo, esta diciendo algo un\n    poco extranio: dice que, para un [m] _en particular_, si sabemos\n\n      - \"si [double n = double m] entonces [n = m]\"\n\n    podemos probar\n\n       - \"si [double (S n) = double m] entonces [S n = m]\".\n\n    Para ver porque esto es extranio, pensemos en un [m] particular --\n    digamos, [5].  Este objetivo dice que, si sabemos\n\n      - [Q] = \"si [double n = 10] entonces [n = 5]\"\n\n    entonces podemos probar\n\n      - [R] = \"si [double (S n) = 10] entonces [S n = 5]\".\n\n    Pero sabiendo [Q] no nos ayuda a probar [R]!  (Si intentaramos\n    probar [R] a partir de [Q], deberiamos decir algo como \"Suponga\n    [double (S n) = 10]...\" pero entonces nos quedamos estancados:\n    sabiendo que [double (S n)] is [10] no nos dice nada acerca de que\n    [double n] es [10], asi que [Q] es inutil.) *)\n\n(** Para sumarizar: Intentar hacer esta prueba por induccion en [n]\n    cuando [m] esta en el contexto no funciona porque estamos tratando\n    de probar una relacion involucrando _todo_ [n] pero solo un\n    _unico_ [m].  *)\n\n(** La prueba adecuada de [double_injective] deja [m] en el objetivo\n    antes de invocar [induction] en [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    (* Note que ahora el objetivo y la hipotesis inductiva cambiaron:\n       el objetivo pide demostrar algo mas general (es decir, probar\n       la propiedad para _todo_ [m]), pero la hipotesis inductiva es\n       correspondientemente mas flexible, permitiendonos elegir\n       cualquier [m] que queramos cuando la apliquemos.   *)\n    intros m eq.\n    (* Ahora elegimos al [m] en particular e introducimos la premisa\n       que [double n = double m].  Como estamos haciendo analisis por\n       caso en [n], tenemos que hacer analisis por caso en [m] para\n       mantener las dos \"sincronizadas\". *)\n\n    destruct m as [| m'].\n    SCase \"m = O\". \n      (* El caso 0 es trivial *)\n      inversion eq.  \n    SCase \"m = S m'\".  \n      apply f_equal. \n      (* En este punto, como estamos en la segunda rama de [destruct\n         m], la variable [m'] mencionada en el contexto en este punto\n         es de hecho el predecesor de la que veniamos hablando.  Y\n         como ademas estamos la rama [S] de la induccion, esto es\n         perfecto: si instanciamos la [m] generica de la hipotesis\n         inductiva con el [m'] que estamos mencionando ahora\n         (instanciacion hecha automaticamente por [apply]), entonces\n         [IHn'] nos da exactamente lo que necesitamos para terminar la\n         prueba.  *)\n      apply IHn'. inversion eq. reflexivity. Qed.\n\n(** Lo que esto nos ensenia es que tenemos que ser cuidadosos cuando\n    usamos induccion para evitar caer en un caso muy especifico: Si\n    estamos provando una propiedad en [n] y [m] por induccion en [n],\n    tal vez sea una buena idea idea dejar [m] generica.  *)\n\n(** La demostracion de este teorema tiene que ser tratada similarmente: *)\n\n(** **** Ejercicio: 2 stars (beq_nat_true) *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 2 stars, avanzado (beq_nat_true_informal) *)\n(** De una prueba informal de [beq_nat_true], siendo tan explicita\n    como se pueda acerca de los cuantificadores. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** La estrategia de hacer menos [intros] antes de una [induction] no\n    funciona siempre; a veces se necesita hacer un pequenia\n    _reorganizacion_ de las variabes cuantificadas.  Suponga, por\n    ejemplo, que quisieramos demostrar [double_injective] por\n    induccion en [m] en vez de [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        (* Estancados aca de nuevo, igual que antes. *)\nAbort.\n\n(** El problema es que, para acer induccion en [m], queremos pimero\n    introducir [n].  (Si simplemente decimos [induction m] sin\n    introducir nada antes, Coq va a introducir automaticamente [n] por\n    nosotros!)  *)\n\n(** Que podemos hacer con esto?  Una posibilidad es reescribir el lema\n    de forma que [m] sea cuantificada antes que [n].  Esto funciona,\n    pero no es elegante: No queremos adaptar los lemas para satisfacer\n    las necesidades de la estrategia de la prueba -- queremos\n    especificarlo en la forma mas natural y comprensible. *)\n\n(** Lo que podemos hacer, en vez, es introducir todas las variables\n    cuantificadas y luego _re-generalizar_ ona o mas variables,\n    tomandolas del contexto y poniendolas de vuelta en el objetivo.\n    La tactica [generalize dependent] hace esto. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. \n  (* [n] y [m] estan las dos en el contexto *)\n  generalize dependent n.\n  (* Ahora [n] esta devuelta en el objetivo, y ahora podemos hacer\n     induccion en [m] y obtener una HI suficientemente general. *)\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(** Miremos a una prueba informal de este teorema.  Note que la\n    proposicion que provamos por induccion deja [n] cuantificado,\n    correspondiendo al uso de [generalize dependent] en la prueba\n    formal.\n\n_Teorema_: Para todos naturales [n] y [m], si [double n = double m],\n  entonces [n = m].\n\n_Demostracion_: Sea [m] un [nat]. Provamos por induccion en [m] que,\n  para cualquier [n], si [double n = double m] entonces [n = m].\n\n  - Primero suponga [m = 0], y suponga que [n] es un numero\n    tal que [double n = double m].  Debemos mostrar que [n = 0].\n\n    Como [m = 0], por definicion de [double] tenemos [double n = 0].\n    Tenemos que considerar dos casos para [n].  Si [n = 0] entonces ya\n    esta, puesto que esto es lo que queriamos probar.  En otro caso,\n    si [n = S n'] para algun [n'], derivamos una contradiccion: por la\n    definicion de [double] obtenemos que [double n = S (S (double\n    n'))], pero esto contradice la premisa de que [double n = 0].\n\n  - En otro caso, suponga [m = S m'] y que [n] es, de vuelta, un\n    number tal que [double n = double m].  Debemos mostrar que [n = S\n    m'], con la hipotesis inductiva que para cualquier numero [s], si\n    [double s = double m'] entonces [s = m'].\n \n    Dado que [m = S m'] y la definicion de [double], tenemos que\n    [double n = S (S (double m'))].  Hay dos casos que considerar para\n    [n].\n\n    Si [n = 0], entonces por definicion [double n = 0], una\n    contradiccion.  Entonces, tenemos que asumir que [n = S n'] para\n    algun [n'], y de vuelta por definicion de [double] tenemos [S (S\n    (double n')) = S (S (double m'))], que por inversion implica\n    [double n' = double m'].\n\n    Instanciando la hipotesis inductiva con [n'] entonces nos permite\n    concluir que [n' = m'], y en consecuencia, [S n' = S m'].  Como [S\n    n' = n] y [S m' = m], esto es justo lo que queriamos probar. [] *)\n\n(** **** Ejercicio: 3 stars (gen_dep_practice) *)\n\n(** Demuestre por induccion en [l]. *)\n\nTheorem index_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     index n l = None.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 3 stars, avanzado, opcional (index_after_last_informal) *)\n(** Escriba una prueba informal correspondiendo a su prueba de Coq de\n    [index_after_last]:\n \n     _Teorema_: Para todo conjunto [X], listas [l : list X], y numero\n      [n], si [length l = n] entonces [index n l = None].\n \n     _Demostracion_:\n     (* FILL IN HERE *)\n[]\n*)\n\n(** **** Ejercicio: 3 stars, opcional (gen_dep_practice_more) *)\n(** Demuestre lo siguiente por induccion en [l]. *)\n\nTheorem length_snoc''' : forall (n : nat) (X : Type) \n                              (v : X) (l : list X),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 3 stars, opcional (app_length_cons) *)\n(** Demuestre esto por induccion en [l1], sin utilizar [app_length]. *)\n\nTheorem app_length_cons : forall (X : Type) (l1 l2 : list X) \n                                  (x : X) (n : nat),\n     length (l1 ++ (x :: l2)) = n ->\n     S (length (l1 ++ l2)) = n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 4 stars, opcional (app_length_twice) *)\n(** Demuestre esto por induccion en [l], sin utilizar [app_length]. *)\n\nTheorem app_length_twice : forall (X:Type) (n:nat) (l:list X),\n     length l = n ->\n     length (l ++ l) = n + n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Usando [destruct] en Expresiones Compuestas *)\n\n(** Vimos muchos ejemplos donde la tactica [destruct] es utilizada\n    para realizar analisis por caso en el valor de una variable.  Pero\n    a veces necesitamos razonar por casos en el resultado de alguna\n    _expresion_.  Tambien podemos hacer esto con [destruct].\n\n    Aqui hay unos ejemplos: *)\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(** Luego de expandir (unfold) [sillyfun] en la definicion de arriba,\n    nos encontramos con que estamos varados en [if (beq_nat n 3) then\n    ... else ...].  Bueno, o [n] es igual a [3] o no lo es, asi que\n    [destruct (beq_nat n 3)] nos permite razonar acerca de los dos\n    casos.\n\n    En general, la tactica [destruct] puede ser utilizada para\n    realizar analisis por caso en los resultados de computaciones\n    arbitrarias.  Si [e] es una expresion cuyo tipo es algun tipo\n    definido inductivamente [T], entonces, para cada constructor [c]\n    de [T], [destruct e] genera un sub-objetivo en el cual todas las\n    ocurrencias de [e] (en el objetivo y en el contexto) son\n    reemplazadas por [c].\n\n*)\n\n(** **** Ejercicio: 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(** **** Ejercicio: 3 stars, opcional (combine_split) *)\n(** Complete la demostracion de abajo *)\n\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** A veces, haciendo un [destruct] en una expresion compuesta (una\n    no-variable) puede borrar informacion que necesitamos para\n    concluir la prueba. *)\n(** Por ejemplo, suponga que definimos la funcion [sillyfun1] de la\n    siguiente forma: *)\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(** Y suponga que queremos convencer a Coq de la observacion bastante\n     obvia que [sillyfun1 n] retorna [true] solo cuando [n] es impar.\n     En analogia con las demostraciones que hicimos con [sillyfun] de\n     arriba, es natural pensar la prueba de la siguiente manera: *)\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(** Nos quedamos estancados en este punto porque el contexto no\n    contiene suficiente informacion para probar el objetivo!  El\n    problema es que la sustitucion realizada por [destruct] es\n    demasiado brutal -- tira todas las ocurrencias de [beq_nat n 3],\n    pero a veces es necesario quedarnos con algun recuerdo de esta\n    expresion y como ha sido destruida, porque debemos ser capaces de\n    razonar que, en esta rama del analisis por caso, [beq_nat n 3 =\n    true], y ergo debe ser que [n = 3], de lo cual concluimos que [n]\n    es impar.\n\n    Lo que realmente quisieramos es sustituir todas las ocurrencias de\n    [beq_nat n 3], pero a la vez quedarnos con una ecuacion en el\n    contexto que indique en que caso estamos.  el modificador [_eqn:]\n    (o simplemente [eqn:] en Coq 8.4) nos permite obtener esta\n    ecuacion (con el nombre que querramos ponerle). *)\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) as [] _eqn:Heqe3.\n  (* Ahora estamos en el mismo punto en el que estabamos cuando nos\n    quedamos estancados arriba, excepto que ahora tenemos lo que\n    necesitamos para poder progresar en la demostracion.  *)\n    Case \"e3 = true\". apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    Case \"e3 = false\".\n     (* Cuando llegamos al segundo test de igualdad, podemos utilizar\n       [_eqn:] de vuelta para poder concluir la prueba. *)\n      destruct (beq_nat n 5) as [] _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(** **** Ejercicio: 2 stars (destruct_eqn_practice) *)\nTheorem bool_fn_applied_thrice : \n  forall (f : bool -> bool) (b : bool), \n  f (f (f b)) = f b.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 2 stars (override_same) *)\nTheorem override_same : forall (X:Type) x1 k1 k2 (f : nat->X),\n  f k1 = x1 -> \n  (override f k1 x1) k2 = f k2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################## *)\n(** * Resumen *)\n\n(** Ahora hemos visto una serie de tacticas fundamentales en Coq.\n    Vamos a introducir algunas mas a medida que avanzemos en los\n    capitulos, y mas adelante veremos algunas tacticas poderosas para\n    _automatizar_ mucho del trabajo.  Pero basicamente tenemos todo lo\n    necesario para poder trabajar.\n\n    Aqui estan las que hemos vistos:\n\n      - [intros]: \n        mueve las hipotesis/variables desde el objetivo al contexto. \n\n      - [reflexivity]:\n        concluye la demostracion cuando el objetivo es de la forma [e = e].\n\n      - [apply]:\n        demuestra el objetivo utilizando una hipotesis, lema, o constructor.\n\n      - [apply... in H]: \n        aplica una hipotesis, lema, o constructor a otra hipotesis en el\n        contexto (razonamiento hacia adelante).\n\n      - [apply... with...]:\n        explicita los valores especificos para las variables que no pueden\n        ser determinadas por simple matcheo.\n\n      - [simpl]:\n        simplifica (reduce cuidadosamente) las computaciones en el objetivo...\n\n      - [simpl in H]:\n        ... on en una hipotesis.\n\n      - [rewrite]:\n        utiliza una premisa (o lema) de igualdad para reescribir el objetivo...\n\n      - [rewrite ... in H]:\n        ... o una hipotesis.\n\n      - [symmetry]:\n        cambia un objetivo de la forma [t=u] en [u=t].\n\n      - [symmetry in H]:\n        cambia una hipotesis de la forma [t=u] en [u=t]\n\n      - [unfold]:\n        reemplaza la definicion de una constante en el objetivo...\n\n      - [unfold... in H]:\n        ... o en una hipotesis  \n\n      - [destruct... as...]:\n        analiza por casos los valores de tipos definidos inductivamente.\n\n      - [destruct... _eqn:...]:\n        especifica el nombre de la ecuacion a ser agregada en el contexto,\n        guardando el resultado del analisis por caso.\n\n      - [induction... as...]:\n        induccion en variables de un tipo inductivo. \n\n      - [inversion]:\n        razonamiento por inyectividad y distincion de constructores.\n\n      - [assert (e) as H]:\n        introduce un \"lema local\" [e] y lo llama [H].\n\n      - [generalize dependent x]:\n        mueve la variable [x] (y todo lo que dependa de ella)\n        desde el contexto hacia el objetivo.\n*)\n\n(* ###################################################### *)\n(** * Ejercicios Adicionales *)\n\n(** **** Ejercicio: 3 stars (beq_nat_sym) *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 3 stars, avanzado, opcional (beq_nat_sym_informal) *)\n(** De una prueba informal a este lema que corresponda con la\n    demostracion formal suya de arriba:\n\n   Teorema: Para todos [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Demostracion:\n   (* FILL IN HERE *)\n[]\n *)\n\n(** **** Ejercicio: 3 stars, opcional (beq_nat_trans) *)\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 3 stars, avanzado (split_combine) *)\n(** Hemos demostrado que para todas las listas de pares, [combine] es\n    el inverso de [split].  Como formalizaria el hecho de que\n    [split] es el inverso de [combine]?\n\n    Complete la definicion de [split_combine_statement] de abajo con\n     una propiedad que estalece que [split] es el inverso de\n     [combine]. Luego, pruebe que esta propiedad vale.  (Asegurese de\n     dejar su hipotesis inductiva general evitando introducir mas\n     cosas que las necesarias.  Ayuda: que propiedad necesita de\n     [l1] y [l2] para [split] que haga cierto [combine l1 l2 = (l1,l2)]?)\n     *)\n\nDefinition split_combine_statement : Prop :=\n(* FILL IN HERE *) admit.\n\nTheorem split_combine : split_combine_statement.\nProof.\n(* FILL IN HERE *) Admitted.\n\n\n(** [] *)\n\n(** **** Ejercicio: 3 stars (override_permute) *)\nTheorem override_permute : forall (X:Type) x1 x2 k1 k2 k3 (f : nat->X),\n  beq_nat k2 k1 = false ->\n  (override (override f k2 x2) k1 x1) k3 = (override (override f k1 x1) k2 x2) k3.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 3 stars, avanzado (filter_exercise) *)\n(** Este es un poco dificil.  Preste atencion a la forma de su HI. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 4 stars, avanzado (forall_exists_challenge) *)\n(** Defina dos [Fixpoints], [forallb] y [existsb].  El primero\n    verifica que todo elemento de una lista dada satisfaga una\n    predicado dado:\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n  \n      forallb evenb [0;2;4;5] = false\n  \n      forallb (beq_nat 5) [] = true\n\n    El segundo verifica que existe al menos un elmento de la lista que\n    satisfaga el predicado dado:\n\n      existsb (beq_nat 5) [0;2;3;6] = false\n \n      existsb (andb true) [true;true;false] = true\n \n      existsb oddb [1;0;0;0;0;3] = true\n \n      existsb evenb [] = false\n\n    A continuacion, defina una version _no recursiva_ de [existsb] --\n    llamela [existsb'] -- usando [forallb] y [negb].\n \n    Demuestre que [existsb'] y [existsb] tienen el mismo\n    comportamiento.  *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n\n\n\n", "meta": {"author": "gciruelos", "repo": "ECI2014T2", "sha": "3d38f7bf1e87732523095ae80ee92556dde99a91", "save_path": "github-repos/coq/gciruelos-ECI2014T2", "path": "github-repos/coq/gciruelos-ECI2014T2/ECI2014T2-3d38f7bf1e87732523095ae80ee92556dde99a91/sp/MoreCoq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577159, "lm_q2_score": 0.9005297867852853, "lm_q1q2_score": 0.6975354004174629}}
{"text": "(** * Tactics: More Basic Tactics *)\n\n(** This chapter introduces several additional proof strategies\n    and tactics that allow us to begin proving more interesting\n    properties of functional programs.\n\n    We will see:\n    - how to use auxiliary lemmas in both \"forward-\" and\n      \"backward-style\" proofs;\n    - how to reason about data constructors -- in particular, how to use\n      the fact that they are injective and disjoint;\n    - how to strengthen an induction hypothesis, and when such\n      strengthening is required; and\n    - more details on how to reason by case analysis. *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Poly.\n\n(* ################################################################# *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    _exactly_ the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n\n(** Here, we could finish with \"[rewrite -> eq2.  reflexivity.]\" as we\n    have done several times before.  We can finish this proof in\n    a single step by using the [apply] tactic instead: *)\n\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n    n = m ->\n    (n = m -> [n;o] = [m;p]) ->\n    [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] that introduces some _universally quantified\n    variables_.  When Coq matches the current goal against the\n    conclusion of [H], it will try to find appropriate values for\n    these variables.  For example, when we do [apply eq2] in the\n    following proof, the universal variable [q] in [eq2] gets\n    instantiated with [n], and [r] gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, standard, optional (silly_ex) \n\n    Complete the following proof using only [intros] and [apply]. *)\n\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 2 = true ->\n     oddb 3 = true.\nProof.\n  (* SOLUTION: *)\n  intros eq1 eq2. apply eq2. Qed.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal exactly -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = (n =? 5)  ->\n     (S (S n)) =? 7 = true.\nProof.\n  intros n H.\n\n(** Here we cannot use [apply] directly, but we can use the [symmetry]\n    tactic, which switches the left and right sides of an equality in\n    the goal. *)\n\n  symmetry.\n  simpl. (** (This [simpl] is optional, since [apply] will perform\n             simplification first, if needed.) *)\n  apply H.  Qed.\n\n(** **** Exercise: 3 stars, standard (apply_exercise1) \n\n    (_Hint_: You can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [Search] is\n    your friend.) *)\n\n(** For the slick solution to this exercise, we can use the fact that\n    [rev] is involutive. *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  (* SOLUTION: *)\n  intros l l' eq. rewrite -> eq.\n  symmetry.\n  apply rev_involutive.   Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (apply_rewrite) \n\n    Briefly explain the difference between the tactics [apply] and\n    [rewrite].  What are the situations where both can usefully be\n    applied? *)\n\n(* SOLUTION:\n\n    The [rewrite] tactic is used to apply a known equality (a\n    hypothesis from the context or a previously proved lemma) to\n    modify the goal, replacing all occurrences of one side by the\n    other.  The [apply] tactic uses a known implication (a hypothesis\n    from the context, a previously proved lemma, or a constructor) to\n    replace a goal that matches the conclusion of the implication with\n    subgoals, one for each premise of the implication.  If the known\n    fact is itself an equality (with no premises), then either tactic\n    can be used.  (We will see below that each tactic can also be used\n    to modify a hypothesis rather than the goal.)\n\n    [] *)\n\n(* ################################################################# *)\n(** * The [apply with] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a;b]] to [[e;f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might like to pull it out as a\n    lemma that records, once and for all, the fact that equality is\n    transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to prove the above\n    example.  However, to do this we need a slight refinement of the\n    [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n\n(** If we simply tell Coq [apply trans_eq] at this point, it can\n    tell (by matching the goal against the conclusion of the lemma)\n    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and\n    [o] with [[e,f]].  However, the matching process doesn't determine\n    an instantiation for [m]: we have to supply one explicitly by\n    adding \"[with (m:=[c,d])]\" to the invocation of [apply]. *)\n\n  apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2.   Qed.\n\n(** (Actually, we usually don't have to include the name [m] in\n    the [with] clause; Coq is often smart enough to figure out which\n    variable we are instantiating. We could instead write [apply\n    trans_eq with [c;d]].) *)\n\n(** Coq also has a tactic [transitivity] that accomplishes the\n    same purpose as applying [trans_eq]. The tactic requires us to\n    state the instantiation we want, just like [apply with] does. *)\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  transitivity [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  (* SOLUTION: *)\n  intros n m o p eq1 eq2.\n  apply trans_eq with m. apply eq2. apply eq1.   Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * The [injection] and [discriminate] Tactics *)\n\n(** Recall the definition of natural numbers:\n\n     Inductive nat : Type :=\n       | O\n       | S (n : nat).\n\n    It is obvious from this definition that every number has one of\n    two forms: either it is the constructor [O] or it is built by\n    applying the constructor [S] to another number.  But there is more\n    here than meets the eye: implicit in the definition are two more\n    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  assert (H2: n = pred (S n)). { reflexivity. }\n  rewrite H2. rewrite H1. reflexivity.\nQed.\n\n(** This technique can be generalized to any constructor by\n    writing the equivalent of [pred] -- 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\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\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  intros n m o H.\n  injection H.\n  (* WORKED IN CLASS *)\n  intros H1 H2. rewrite H1. rewrite H2. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, standard (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  (* SOLUTION: *)\n  intros X x y z l j eq1 eq2.\n  injection eq1 as Hxz Hyl_j.\n  assert (Hyl_zl : y :: l = z :: l).\n  { apply trans_eq with j.\n    - apply Hyl_j.\n    - apply eq2. }\n  injection Hyl_zl as Hyz.\n  rewrite -> Hxz. rewrite -> Hyz. 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   0 =? n = true -> n = 0.\nProof.\n  intros n.\n\n(** We can proceed by case analysis on [n]. The first case is\n    trivial. *)\n\n  destruct n as [| n'] eqn:E.\n  - (* n = 0 *)\n    intros H. reflexivity.\n\n(** However, the second one doesn't look so simple: assuming [0\n    =? (S n') = true], we must show [S n' = 0]!  The way forward is to\n    observe that the assumption itself is nonsensical: *)\n\n  - (* n = S n' *)\n    simpl.\n\n(** If we use [discriminate] on this hypothesis, Coq confirms\n    that the subgoal we are working on is impossible and removes it\n    from further consideration. *)\n\n    intros H. discriminate H.\nQed.\n\n(** This is an instance of a logical principle known as the _principle\n    of explosion_, which asserts that a contradictory hypothesis\n    entails anything (even false things!). *)\n\nTheorem discriminate_ex1 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. discriminate contra. Qed.\n\nTheorem discriminate_ex2 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. discriminate contra. Qed.\n\n(** If you find the principle of explosion confusing, remember\n    that these proofs are _not_ showing that the conclusion of the\n    statement holds.  Rather, they are showing that, _if_ the\n    nonsensical situation described by the premise did somehow arise,\n    _then_ the nonsensical conclusion would 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. *)\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  (* SOLUTION: *)\n  intros X x y z l j eq1. discriminate eq1. Qed.\n(** [] *)\n\n\n\n(** The injectivity of constructors allows us to reason that\n    [forall (n m : nat), S n = S m -> n = m].  The converse of this\n    implication is an instance of a more general fact about both\n    constructors and functions, which we will find convenient in a few\n    places below: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.\n\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(** There is also a tactic named `f_equal` that can prove such\n    theorems.  Given a goal of the form [f a1 ... an = g b1 ... bn],\n    the tactic [f_equal] will produce subgoals of the form [f = g],\n    [a1 = b1], ..., [an = bn]. At the same time, any of these subgoals\n    that are simple enough (e.g., immediately provable by\n    [reflexivity]) will be automatically discharged by [f_equal]. *)\n\nTheorem eq_implies_succ_equal' : forall (n m : nat),\n    n = m -> S n = S m.\nProof. intros n m H. f_equal. apply H. Qed.\n\n(* ################################################################# *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic \"[simpl in H]\" performs simplification on\n    the hypothesis [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     (S n) =? (S m) = b  ->\n     n =? m = b.\nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, [apply L in H] matches some conditional statement\n    [L] (of the form [X -> Y], say) against a hypothesis [H] in the\n    context.  However, unlike ordinary [apply] (which rewrites a goal\n    matching [Y] into a subgoal [X]), [apply L in H] matches [H]\n    against [X] and, if successful, replaces it with [Y].\n\n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\": from [X -> Y] and a hypothesis matching [X], it\n    produces a hypothesis matching [X].  By contrast, [apply L] is\n    \"backward reasoning\": it says that if we know [X -> Y] and we\n    are trying to prove [Y], it suffices to prove [X].\n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\nTheorem silly3' : forall (n : nat),\n  (n =? 5 = true -> (S (S n)) =? 7 = true) ->\n  true = (n =? 5)  ->\n  true = ((S (S n)) =? 7).\nProof.\n  intros n eq H.\n  symmetry in H. apply eq in H. symmetry in H.\n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_ and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n\n    The informal proofs that you've seen in math or computer science\n    classes probably tended to use forward reasoning.  In general,\n    idiomatic use of Coq favors backward reasoning, but in some\n    situations the forward style can be easier to think about. *)\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 sometimes need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose\n    we want to show that [double] is injective -- i.e., that it maps\n    different arguments to different results:\n\n       Theorem double_injective: forall n m,\n         double n = double m -> n = m.\n\n    The way we start this proof is a bit delicate: if we begin it with\n\n       intros n. induction n.\n\n    all is well.  But if we begin it with\n\n       intros n m. induction n.\n\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n' 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.\n\n(** At this point, the induction hypothesis ([IHn']) does _not_ give us\n    [n' = m'] -- there is an extra [S] in the way -- so the goal is\n    not provable. *)\n\nAbort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context --\n    intuitively, we have told Coq, \"Let's consider some particular [n]\n    and [m]...\" and we now have to prove that, if [double n = double\n    m] for _those particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove, for\n    _all_ [n], that the proposition\n\n      - [P n] = \"if [double n = double m], then [n = m]\"\n\n    holds, by showing\n\n      - [P O]\n\n         (i.e., \"if [double O = double m] then [O = m]\") and\n\n      - [P n -> P (S n)]\n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: 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 (arbitrary,\n    but fixed) [m] -- say, [5].  The statement is then saying that,\n    if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help at all with proving\n    [R]!  If we tried to prove [R] from [Q], we would start with\n    something like \"Suppose [double (S n) = 10]...\" but then we'd be\n    stuck: knowing that [double (S n)] is [10] tells us nothing\n    helpful about whether [double n] is [10] (indeed, it strongly\n    suggests that [double n] is _not_ [10]!!), so [Q] is useless. *)\n\n(** Trying to carry out this proof by induction on [n] when [m] is\n    already in the context doesn't work because we are then trying to\n    prove a statement involving _every_ [n] but just a _single_ [m]. *)\n\n(** A successful proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = O *) simpl. intros m eq. destruct m as [| m'] eqn:E.\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) simpl in eq. discriminate eq.\n\n  - (* n = S n' *)\n\n(** Notice that both the goal and the induction hypothesis are\n    different this time: the goal asks us to prove something more\n    general (i.e., to prove the statement for _every_ [m]), but the IH\n    is correspondingly more flexible, allowing us to choose whichever\n    [m] we like when we apply the IH. *)\n\n    intros m eq.\n\n(** Now we've chosen a particular [m] and introduced the assumption\n    that [double n = double m].  Since we are doing a case analysis on\n    [n], we also need a case analysis on [m] to keep the two \"in sync.\" *)\n\n    destruct m as [| m'] eqn:E.\n    + (* m = O *)\n\n(** The 0 case is trivial: *)\n\n      simpl in eq. discriminate eq.\n\n    + (* m = S m' *)\n      apply f_equal.\n\n(** At this point, since we are in the second branch of the [destruct\n    m], the [m'] mentioned in the context is the predecessor of the\n    [m] we started out talking about.  Since we are also in the [S]\n    branch of the induction, this is perfect: if we instantiate the\n    generic [m] in the IH with the current [m'] (this instantiation is\n    performed automatically by the [apply] in the next step), then\n    [IHn'] gives us exactly what we need to finish the proof. *)\n\n      apply IHn'. simpl in eq. injection eq as goal. apply goal. Qed.\n\n(** What you should take away from all this is that we need to be\n    careful, when using induction, that we are not trying to prove\n    something too specific: When proving a property involving two\n    variables [n] and [m] by induction on [n], it is sometimes\n    crucial to leave [m] generic. *)\n\n(** The following exercise follows the same pattern. *)\n\n(** **** Exercise: 2 stars, standard (eqb_true)  *)\nTheorem eqb_true : forall n m,\n    n =? m = true -> n = m.\nProof.\n  (* SOLUTION: *)\n      intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    intros m. destruct m as [| m'] eqn:E.\n    + (* m = 0 *) reflexivity.\n    + (* m = S m' *) simpl. intros contra. discriminate contra.\n  - (* n = S n' *)\n    intros m. destruct m as [| m'] eqn:E.\n    + (* m = 0 *) simpl. intros contra. discriminate contra.\n    + (* m = S m' *) simpl. intros H.\n      apply f_equal. apply IHn'. apply H. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (eqb_true_informal) \n\n    Give a careful informal proof of [eqb_true], being as explicit\n    as possible about quantifiers. *)\n\n(* SOLUTION:\n\n    _Theorem_: For all natural numbers [n] and [m], if [n =? m =\n      true], then [n = m].\n\n    _Proof_ (more pedantic, arguably less clear): We argue by\n    induction on [n].\n\n      - Base case: [n = 0].  We must show, for all natural numbers\n        [m], that [0 =? m = true] implies [0 = m].  We proceed by\n        cases on [m].\n\n          - If [m = 0], we must show that [0 =? 0 = true] implies [0 =\n            0], which holds by reflexivity.\n\n          - If [m = S m'] for some [m'], we must show that [0 =? S m'\n            = true] implies [0 = S m'].  But [0 =? S m'] evaluates to\n            [false], so the antecedent of this implication is [false =\n            true], which is absurd, and hence the whole implication is\n            true.\n\n      - Inductive case: [n = S n']. We must show that for all natural\n        numbers [m], [S n' =? m = true] implies [S n' = m].\n\n        We may assume the induction hypothesis: for all natural\n        numbers [m], [n' =? m = true], implies [n' = m].\n\n        We again proceed by cases on [m].\n\n          - If [m = 0], we must show that [S n' =? 0 = true] implies\n            [S n' = m]. But [S n' =? 0] evaluates to [false], so the\n            antecedent of this implies is again absurd, and hence the\n            whole implication is true.\n\n          - If [m = S m'] for some [m'], we must show that [S n' =? S\n            m' = true] implies [S n' = S m'].  So let us assume the [S\n            n' =? S m' = true].  This simplifes to [n' =? m' =\n            true]. Hence we can apply the induction hypothesis (with\n            [m] instantiated to [m']) to obtain [n' = m'].  Hence, to\n            show [S n' = S m'] it suffices to show [S n' = S n'],\n            which is true by reflexivity. []\n\n    _Proof_ (somewhat more natural style): By induction on [n].\n\n      - Suppose [n = 0].  We must show that if [0 =? m = true] then [0\n        = m]. Now if [m] were of the form [S m'] for some [m'], then\n        we would have [0 =? S m' = true], which is absurd. So [m] must\n        indeed be 0.\n\n      - Otherwise, we have [n = S n']. The induction hypothesis states\n        that for all m, if [n' =? m = true], then [n' = m]; and on the\n        assumption [S n' =? m = true], we must show that [S n' = m].\n        In this case [m] must have the form [S m'] for some [m'], for\n        if [m] were 0, our assumption would be [S n' =? 0 = true],\n        which is absurd.  So our assumption has the form [S n' =? S m'\n        = true], which simplifies to [n' =? m' = true]. Applying the\n        induction hypothesis to the assumption (with [m] instantiated\n        to [m']) gives us that [n' = m'], which directly implies our\n        goal [S n' = S m']. [] *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_proof : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, recommended (plus_n_n_injective) \n\n    In addition to being careful about how you use [intros], practice\n    using \"in\" variants 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  (* SOLUTION: *)\n      intros n. induction n as [| n'].\n  - (* n = 0 *) intros m. simpl. intros eq. destruct m as [| m'] eqn:E.\n      + (* m = 0 *) reflexivity.\n      + (* m = S m' *) discriminate eq.\n    - (* n = S n' *) intros m eq. destruct m as [| m'] eqn:E.\n      + (* m = 0 *) discriminate eq.\n      + (* m = S m' *)\n        apply f_equal. apply IHn'.\n        (* just [simpl in eq] doesn't work here! *)\n        rewrite <- plus_n_Sm in eq. rewrite <- plus_n_Sm in eq.\n        injection eq as goal. apply goal. Qed.\n(** [] *)\n\n(** The strategy of doing fewer [intros] before an [induction] to\n    obtain a more general IH doesn't always work by itself; sometimes\n    some _rearrangement_ of quantified variables is needed.  Suppose,\n    for example, that we wanted to prove [double_injective] by\n    induction on [m] instead of [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m' IHm'].\n  - (* m = O *) simpl. intros eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) discriminate eq.\n  - (* m = S m' *) intros eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) discriminate eq.\n    + (* n = S n' *) apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (And if we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce [n]\n    for us!)  *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    works, but it's not nice: We don't want to have to twist the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them!  Rather we want to state them in the clearest and\n    most natural way. *)\n\n(** What we can do instead is to first introduce all the quantified\n    variables and then _re-generalize_ one or more of them,\n    selectively taking variables out of the context and putting them\n    back at the beginning of the goal.  The [generalize dependent]\n    tactic does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m.\n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m' IHm'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) discriminate eq.\n  - (* m = S m' *) intros n eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) discriminate eq.\n    + (* n = S n' *) apply f_equal.\n      apply IHm'. injection eq as goal. apply goal. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n    _Theorem_: For any nats [n] and [m], if [double n = double m], then\n      [n = m].\n\n    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n      any [n], if [double n = double m] then [n = m].\n\n      - First, suppose [m = 0], and suppose [n] is a number such\n        that [double n = double m].  We must show that [n = 0].\n\n        Since [m = 0], by the definition of [double] we have [double n =\n        0].  There are two cases to consider for [n].  If [n = 0] we are\n        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']\n        for some [n'], we derive a contradiction: by the definition of\n        [double], we can calculate [double n = S (S (double n'))], but\n        this contradicts the assumption that [double n = 0].\n\n      - Second, suppose [m = S m'] and that [n] is again a number such\n        that [double n = double m].  We must show that [n = S m'], with\n        the induction hypothesis that for every number [s], if [double s =\n        double m'] then [s = m'].\n\n        By the fact that [m = S m'] and the definition of [double], we\n        have [double n = S (S (double m'))].  There are two cases to\n        consider for [n].\n\n        If [n = 0], then by definition [double n = 0], a contradiction.\n\n        Thus, we may assume that [n = S n'] for some [n'], and again by\n        the definition of [double] we have [S (S (double n')) =\n        S (S (double m'))], which implies by injectivity that [double n' =\n        double m'].  Instantiating the induction hypothesis with [n'] thus\n        allows us to conclude that [n' = m'], and it follows immediately\n        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just\n        what we wanted to show. [] *)\n\n(** **** 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  (* SOLUTION: *)\n  intros n X l. generalize dependent n. induction l as [| x l' IHl'].\n  - (* l = nil *) reflexivity.\n  - (* l = x :: l' *) intros n eq. simpl. simpl in eq.\n    rewrite <- eq.  apply IHl'.  reflexivity.  Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Unfolding Definitions *)\n\n(** It sometimes happens that we need to manually unfold a name that\n    has been introduced by a [Definition] so that we can manipulate\n    the expression it denotes.  For example, if we define... *)\n\nDefinition square n := n * n.\n\n(** ... and try to prove a simple fact about [square]... *)\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\n  simpl.\n\n(** ... we appear to be stuck: [simpl] doesn't simplify anything, and\n    since we haven't proved any other facts about [square], there is\n    nothing we can [apply] or [rewrite] with.\n\n    To make progress, we can manually [unfold] the definition of\n    [square]: *)\n\n  unfold square.\n\n(** Now we have plenty to work with: both sides of the equality are\n    expressions involving multiplication, and we have lots of facts\n    about multiplication at our disposal.  In particular, we know that\n    it is commutative and associative, and from these it is not hard\n    to finish the proof. *)\n\n  rewrite mult_assoc.\n  assert (H : n * m * n = n * n * m).\n    { rewrite mult_comm. apply mult_assoc. }\n  rewrite H. rewrite mult_assoc. reflexivity.\nQed.\n\n(** At this point, some discussion of unfolding and simplification is\n    in order.\n\n    We already have observed that tactics like [simpl], [reflexivity],\n    and [apply] will often unfold the definitions of functions\n    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\n    [reflexivity], if we omit the [simpl]) will unfold [foo m] to\n    [(fun x => 5) m] and then further simplify this expression to just\n    [5]. *)\n\nFact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.\nProof.\n  intros m.\n  simpl.\n  reflexivity.\nQed.\n\n(** However, this automatic unfolding is somewhat conservative.  For\n    example, if we define a slightly more complicated function\n    involving a pattern match... *)\n\nDefinition bar x :=\n  match x with\n  | O => 5\n  | S _ => 5\n  end.\n\n(** ...then the analogous proof will get stuck: *)\n\nFact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  simpl. (* Does nothing! *)\nAbort.\n\n(** The reason that [simpl] doesn't make progress here is that it\n    notices that, after tentatively unfolding [bar m], it is left with\n    a match whose scrutinee, [m], is a variable, so the [match] cannot\n    be simplified further.  It is not smart enough to notice that the\n    two branches of the [match] are identical, so it gives up on\n    unfolding [bar m] and leaves it alone.  Similarly, tentatively\n    unfolding [bar (m+1)] leaves a [match] whose scrutinee is a\n    function application (that cannot itself be simplified, even\n    after unfolding the definition of [+]), so [simpl] leaves it\n    alone. *)\n\n(** At this point, there are two ways to make progress.  One is to use\n    [destruct m] to break the proof into two cases, each focusing on a\n    more concrete choice of [m] ([O] vs [S _]).  In each case, the\n    [match] inside of [bar] can now make progress, and the proof is\n    easy to complete. *)\n\nFact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  destruct m eqn:E.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(** This approach works, but it depends on our recognizing that the\n    [match] hidden inside [bar] is what was preventing us from making\n    progress. *)\n\n(** A more straightforward way forward is to explicitly tell Coq to\n    unfold [bar]. *)\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n\n(** Now it is apparent that we are stuck on the [match] expressions on\n    both sides of the [=], and we can use [destruct] to finish the\n    proof without thinking too hard. *)\n\n  destruct m eqn:E.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where [destruct] is used to\n    perform case analysis of the value of some variable.  Sometimes we\n    need to reason by cases on the result of some _expression_.  We\n    can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if n =? 3 then false\n  else if n =? 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (n =? 3) eqn:E1.\n    - (* n =? 3 = true *) reflexivity.\n    - (* n =? 3 = false *) destruct (n =? 5) eqn:E2.\n      + (* n =? 5 = true *) reflexivity.\n      + (* n =? 5 = false *) reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (n =? 3) then ... else ...].  But either\n    [n] is equal to [3] or it isn't, so we can use [destruct (eqb\n    n 3)] to let us reason about the two cases.\n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c]. *)\n\n(** **** Exercise: 3 stars, standard (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  (* SOLUTION: *)\n  intros X Y l. induction l as [| [x y] l' IHl'].\n  - (* l = [] *)\n    intros l1 l2 H.\n    injection H as l2mt l1mt.\n    rewrite <- l2mt.\n    rewrite <- l1mt.\n    reflexivity.\n  - (* l = (x, y) :: l' *)\n    intros l1 l2 H.\n    simpl in H.\n    destruct (split l') as [lx ly] eqn:E.\n    injection H as l2in l1in.\n    rewrite <- l2in.\n    rewrite <- l1in.\n    simpl.\n    rewrite -> IHl'.\n      reflexivity.\n      reflexivity.  Qed.\n(** [] *)\n\n(** The [eqn:] part of the [destruct] tactic is optional: So far,\n    we've chosen to include it most of the time, just for the sake of\n    documentation.\n\n    However, when [destruct]ing compound expressions, the information\n    recorded by the [eqn:] can actually be critical: if we leave it\n    out, then [destruct] can erase information we need to complete a\n    proof.\n\n    For example, suppose we define a function [sillyfun1] like\n    this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if n =? 3 then true\n  else if n =? 5 then true\n  else false.\n\n(** Now suppose that we want to convince Coq that [sillyfun1 n]\n    yields [true] only when [n] is odd.  If we start the proof like\n    this (with no [eqn:] on the [destruct])... *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3).\n  (* stuck... *)\nAbort.\n\n(** ... then we are stuck at this point because the context does\n    not contain enough information to prove the goal!  The problem is\n    that the substitution performed by [destruct] is quite brutal --\n    in this case, it thows away every occurrence of [n =? 3], but we\n    need to keep some memory of this expression and how it was\n    destructed, because we need to be able to reason that, since [n =?\n    3 = true] in this branch of the case analysis, it must be that [n\n    = 3], from which it follows that [n] is odd.\n\n    What we want here is to substitute away all existing occurences of\n    [n =? 3], but at the same time add an equation to the context that\n    records which case we are in.  This is precisely what the [eqn:]\n    qualifier does. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got\n     stuck above, except that the context contains an extra\n     equality assumption, which is exactly what we need to\n     make progress. *)\n    - (* e3 = true *) apply eqb_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    - (* e3 = false *)\n     (* When we come to the second equality test in the body\n        of the function we are reasoning about, we can use\n        [eqn:] again in the same way, allowing us to finish the\n        proof. *)\n      destruct (n =? 5) eqn:Heqe5.\n        + (* e5 = true *)\n          apply eqb_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + (* e5 = false *) discriminate eq.  Qed.\n\n(** **** Exercise: 2 stars, standard (destruct_eqn_practice)  *)\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  (* SOLUTION: *)\n  intros f b.\n  destruct b.\n  - (* b = true *)\n    destruct (f true) eqn:Heqftrue.\n    + (* f true = true *)\n      rewrite Heqftrue.\n      apply Heqftrue.\n    + (* f true = false *)\n      destruct (f false) eqn:Heqffalse.\n      * (* f false = true *)\n        apply Heqftrue.\n      * (* f false = false *)\n        apply Heqffalse.\n  - (* b = false *)\n    destruct (f false) eqn:Heqffalse.\n    + (* f false = true *)\n      destruct (f true) eqn: Heqftrue.\n      * (* f true = true *)\n        apply Heqftrue.\n      * (* f true = false *)\n        apply Heqffalse.\n    + (* f false = false *)\n      rewrite Heqffalse.\n      apply Heqffalse.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Review *)\n\n(** We've now seen many of Coq's most fundamental tactics.  We'll\n    introduce a few more in the coming chapters, and later on we'll\n    see some more powerful _automation_ tactics that make Coq help us\n    with low-level details.  But basically we've got what we need to\n    get work done.\n\n    Here are the ones we've seen:\n\n      - [intros]: move hypotheses/variables from goal to context\n\n      - [reflexivity]: finish the proof (when the goal looks like [e =\n        e])\n\n      - [apply]: prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: apply a hypothesis, lemma, or constructor to\n        a hypothesis in the context (forward reasoning)\n\n      - [apply... with...]: explicitly specify values for variables\n        that cannot be determined by pattern matching\n\n      - [simpl]: simplify computations in the goal\n\n      - [simpl in H]: ... or a hypothesis\n\n      - [rewrite]: use an equality hypothesis (or lemma) to rewrite\n        the goal\n\n      - [rewrite ... in H]: ... or a hypothesis\n\n      - [symmetry]: changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]: changes a hypothesis of the form [t=u] into\n        [u=t]\n\n      - [transitivity y]: prove a goal [x=z] by proving two new subgoals,\n        [x=y] and [y=z]\n\n      - [unfold]: replace a defined constant by its right-hand side in\n        the goal\n\n      - [unfold... in H]: ... or a hypothesis\n\n      - [destruct... as...]: case analysis on values of inductively\n        defined types\n\n      - [destruct... eqn:...]: specify the name of an equation to be\n        added to the context, recording the result of the case\n        analysis\n\n      - [induction... as...]: induction on values of inductively\n        defined types\n\n      - [injection]: reason by injectivity on equalities\n        between values of inductively defined types\n\n      - [discriminate]: reason by disjointness of constructors on\n        equalities between values of inductively defined types\n\n      - [assert (H: e)] (or [assert (e) as H]): introduce a \"local\n        lemma\" [e] and call it [H]\n\n      - [generalize dependent x]: move the variable [x] (and anything\n        else that depends on it) from the context back to an explicit\n        hypothesis in the goal formula\n\n      - [f_equal]: change a goal of the form [f x = f y] into [x = y] *)\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  (* SOLUTION: *)\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    intros m. destruct m as [| m'].\n    + (* m = 0 *) reflexivity.\n    + (* m = S m' *) reflexivity.\n  - (* n = S n' *)\n    intros m. destruct m as [| m'].\n    + (* m = 0 *) reflexivity.\n    + (* m = S m' *) apply IHn'.  Qed.\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   (* SOLUTION:\n   Let an arbitrary nat [n] be given.  We go by induction\n   on [n].\n\n   - For the base case, we have [n = 0].  Let [m] be given.\n     We must show that\n\n       0 =? m = m =? 0\n\n     Either [m = 0] or not.\n\n     - If [m = 0], we must show [0 =? 0 = 0 =? 0]\n       which is true by reflexivity.\n\n     - Otherwise, [m = S m'] for some [m'], and we must show\n       [0 =? (S m') = (S m') =? 0]. By the definition\n       of [eqb], both sides are [false].\n\n   - In the inductive case, we have [n = S n'] for some\n     [n'] such that, for any [m],\n\n       n' =? m = m =? n'\n\n     Let [m] be given.  Again, [m] is either zero or nonzero.\n\n     - Suppose first [m = 0].  It's\n       enough to show [(S n') =? 0 = 0 =? (S n')].\n       By the definition of [eqb], both sides are [false].\n\n     - Otherwise, [m = S m'] for some [m'].  By the\n       assumption, it's enough to show:\n\n         (S n') =? (S m') = (S m') =? (S n')\n\n       And, by the definition of [eqb], this reduces to\n       showing:\n\n         m' =? n' = n' =? m'.\n\n       which is exactly the induction hypothesis.  *)\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  (* SOLUTION: *)\n  intros n m p. intros Hnm Hmp.\n  apply eqb_true in Hnm.\n  rewrite -> Hnm.\n  rewrite -> Hmp.\n  reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine) \n\n    We proved, in an exercise above, that for all lists of pairs,\n    [combine] is the inverse of [split].  How would you formalize the\n    statement that [split] is the inverse of [combine]?  When is this\n    property true?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split (combine l1 l2) = (l1,l2)] to be true?) *)\n\nDefinition split_combine_statement : Prop\n  (* (\"[: Prop]\" means that we are giving a name to a\n     logical proposition here.) *)\n  (* SOLUTION: *) :=\n  forall (X Y:Type) (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(* SOLUTION: *)\n  intros X Y. induction l1 as [| x l1' IHl1'].\n  - (* l1 = [] *)\n    intros l2 Heq. destruct l2 as [|y l2'].\n    + (* l2 = [] *) reflexivity.\n    + (* l2 = y :: l2' *) discriminate Heq.\n  - (* l1 = x :: l1' *)\n    intros l2 Heq. destruct l2 as [|y l2'].\n    + (* l2 = [] *) discriminate Heq.\n    + (* l2 = y :: l2' *)\n      simpl. rewrite IHl1'. reflexivity.\n      injection Heq as goal. apply goal. Qed.\n\n(** Here are more approaches *)\n\nTheorem split_combine' : forall (X Y:Type) l (l1 : list X) (l2 : list Y),\n  (l1, l2) = split l -> split (combine l1 l2) = (l1, l2).\nProof.\n  induction l as [| [x y] l' IHl'].\n  - (* l = [] *) intros l1 l2 Heq.\n    simpl in Heq. injection Heq as l2mt l1mt.\n    rewrite l2mt. rewrite l1mt. reflexivity.\n  - (* l = (x,y) :: l' *) intros l1 l2 Heq.\n    simpl in Heq. destruct (split l') as [l1' l2'].\n    injection Heq as l2in l1in.\n    rewrite l2in. rewrite l1in. simpl. rewrite IHl'.\n    reflexivity. reflexivity.  Qed.\n\nTheorem split_combine''_equiv :\n  forall (X Y:Type) l (l1 : list X) (l2 : list Y),\n    (split l = (l1, l2) -> split (combine l1 l2) = (l1, l2))\n    <-> (split l = (l1, l2) -> combine l1 l2 = l).\nProof.\n  intros X Y.\n  induction l; intros; split; intros;\n    try solve [inversion H0; auto].\n  - inversion H0. destruct x.\n    destruct (split l). inversion H2; subst. simpl.\n    apply f_equal. apply IHl; auto. apply H in H0.\n    inversion H0. destruct (split (combine x0 y0)).\n    inversion H3; subst; auto.\n  - pose proof H0. apply H in H0. rewrite H0; auto.\nQed.\n\nTheorem split_combine'' : forall X Y (l : list (X * Y)) l1 l2,\n    split l = (l1, l2) -> combine l1 l2 = l.\nProof.\n  induction l as [| [x y] l' IHl'].\n  - (* l = [] *) intros l1 l2 Heq.\n    simpl in Heq. injection Heq as l2mt l1mt.\n    rewrite <- l2mt. rewrite <- l1mt. reflexivity.\n  - (* l = (x,y) :: l' *) intros l1 l2 Heq.\n    simpl in Heq. destruct (split l') as [l1' l2'].\n    injection Heq as l2in l1in.\n    rewrite <- l2in. rewrite <- l1in. simpl. rewrite IHl'.\n    reflexivity. reflexivity.  Qed.\n(* Do not modify the following line: *)\nDefinition manual_grade_for_split_combine : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise) \n\n    This one is a bit challenging.  Pay attention to the form of your\n    induction hypothesis. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  (* SOLUTION: *)\n  intros X test x l. induction l as [| v' l' IHl'].\n    - (* l = [] *) intros lf eq. discriminate eq.\n    - (* l = v' :: l' *) intros lf eq.\n      simpl in eq.\n      destruct (test v') eqn: Heq.\n        + (* test v' = true *)\n          injection eq as eqhead eqtail. rewrite <- eqhead.\n          apply Heq.\n        + (* test v' = false *)\n          apply IHl' with lf. apply eq.  Qed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge) \n\n    Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n\n      forallb evenb [0;2;4;5] = false\n\n      forallb (eqb 5) [] = true\n\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n\n      existsb (eqb 5) [0;2;3;6] = false\n\n      existsb (andb true) [true;true;false] = true\n\n      existsb oddb [1;0;0;0;0;3] = true\n\n      existsb evenb [] = false\n\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n\n    Finally, prove a theorem [existsb_existsb'] stating that\n    [existsb'] and [existsb] have the same behavior.\n*)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool\n  (* SOLUTION: *) :=\n  match l with\n    | [] => true\n    | x :: l' => andb (test x) (forallb test l')\n  end.\n\nExample test_forallb_1 : forallb oddb [1;3;5;7;9] = true.\nProof. (* SOLUTION: *) reflexivity.  Qed. \nExample test_forallb_2 : forallb negb [false;false] = true.\nProof. (* SOLUTION: *) reflexivity.  Qed. \nExample test_forallb_3 : forallb evenb [0;2;4;5] = false.\nProof. (* SOLUTION: *) reflexivity.  Qed. \nExample test_forallb_4 : forallb (eqb 5) [] = true.\nProof. (* SOLUTION: *) reflexivity.  Qed. \nFixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool\n  (* SOLUTION: *) :=\n  match l with\n    | [] => false\n    | x :: l' => orb (test x) (existsb test l')\n  end.\n\nExample test_existsb_1 : existsb (eqb 5) [0;2;3;6] = false.\nProof. (* SOLUTION: *) reflexivity.  Qed. \nExample test_existsb_2 : existsb (andb true) [true;true;false] = true.\nProof. (* SOLUTION: *) reflexivity.  Qed. \nExample test_existsb_3 : existsb oddb [1;0;0;0;0;3] = true.\nProof. (* SOLUTION: *) reflexivity.  Qed. \nExample test_existsb_4 : existsb evenb [] = false.\nProof. (* SOLUTION: *) reflexivity.  Qed. \nDefinition existsb' {X : Type} (test : X -> bool) (l : list X) : bool\n  (* SOLUTION: *) :=\n  negb (forallb (fun x => negb (test x)) l).\n\nTheorem existsb_existsb' : forall (X : Type) (test : X -> bool) (l : list X),\n  existsb test l = existsb' test l.\nProof. (* SOLUTION: *)\n  intros. unfold existsb'. induction l as [| x l' IHl'].\n  - (* l = [] *)\n    reflexivity.\n  - (* l = x :: l' *)\n    simpl.\n    destruct (test x).\n    + (* test x = true *)\n      reflexivity.\n    + (* test x = false *)\n      simpl.\n      rewrite -> IHl'.\n      reflexivity.  Qed.\n\n(** [] *)\n\n\n\n(* 04 Mar 2020 *)\n", "meta": {"author": "maspin22", "repo": "CoqFormalVerification", "sha": "9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d", "save_path": "github-repos/coq/maspin22-CoqFormalVerification", "path": "github-repos/coq/maspin22-CoqFormalVerification/CoqFormalVerification-9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d/coq_4160/a6src/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.9005297854505006, "lm_q1q2_score": 0.6975353993835607}}
{"text": "Require Export Basics.\n\nTheorem plus_n_O : forall n :nat, n = plus n O.\ninduction n as [|m h].\nShow Proof.\nreflexivity.\nShow Proof.\nsimpl. rewrite <- h. reflexivity.\nShow Proof.\nQed.\n\nDefinition plus_n_O' : forall n : nat, n = plus n O :=\n(fun n : nat => nat_ind\n  (fun n0 : nat => n0 = plus n0 O)\n  eq_refl\n  (fun (m : nat) (h : m = plus m O) => eq_ind m\n    (fun n0 : nat => S m = S n0)\n    eq_refl\n    (plus m O)\n    h\n  )\n  n\n)\n.\n\nTheorem minus_diag : forall n:nat, minus n n = O.\ninduction n as [|m h].\nShow Proof.\nreflexivity.\nShow Proof.\nsimpl. assumption.\nShow Proof.\nQed.\n\nDefinition minus_diag' : forall n:nat, minus n n = O :=\n(fun n : nat =>\n nat_ind (fun n0 : nat => minus n0 n0 = O) eq_refl\n   (fun (m : nat) (h : minus m m = O) => h) n).\n\nTheorem plus_commute : forall n m : nat, (plus n m) = (plus m n).\ninduction n.\ninduction m.\nreflexivity.\nsimpl. rewrite <- IHm. simpl. reflexivity.\ninduction m. simpl. rewrite IHn. simpl. reflexivity.\nsimpl. simpl in IHm. rewrite IHn. simpl.  rewrite <- IHm. rewrite <- IHn. reflexivity.\nShow Proof.\nQed.\n\n\nTheorem plus_rearrange : forall n m p q : nat, (plus (plus n m) (plus p q)) = (plus (plus m n) (plus p q)).\nintros n m p q.\nrewrite (plus_commute n m).\nreflexivity.\nShow Proof.\nQed.\n\nTheorem plus_assoc : forall n m p : nat, (plus n (plus m p)) = (plus (plus n m) p).\ninduction n.\nreflexivity.\nintros m p.\nsimpl.\nrewrite <- IHn.\nreflexivity.\nShow Proof.\nQed.\n\nTheorem thm : forall n m : nat, n = plus n m -> m = O.\ninduction n.\nintro m. intro h. simpl in h. symmetry. assumption.\nintro m.\nintro h.\napply IHn.\ninversion h.\nrewrite <- H0.\nrewrite <- H0.\nreflexivity.\nShow Proof.\nQed.\n\nTheorem thm' : forall a : bool, negb a = false -> a = true.\nintros a h.\ndestruct a.\nreflexivity.\nsimpl in h.\ninversion h.\nShow Proof.\nQed.\n\nTheorem thma : forall n:nat, n=n.\nreflexivity.\nShow Proof.\nQed.\n\nTheorem thmb : forall n m:nat, n=m -> (plus O n)=(plus O m).\nintros n m heq.\nrewrite heq.\nreflexivity.\nShow Proof.\n(*\n(fun (n m : nat) (heq : n = m) => eq_ind_r\n  (fun n0 : nat => plus O n0 = plus O m)\n  eq_refl\n  heq\n)\n*)\nQed.\n\n\nTheorem thmc : forall n m:nat, n=m -> (plus O n)=(plus O m).\nintros n m heq.\napply heq.\nShow Proof.\nQed.\n\nTheorem thmd : forall n m:nat, n=m -> (plus O n)=(plus O m).\nintros n m heq.\nrewrite <- heq.\nreflexivity.\nShow Proof.\n(*\n(fun (n m : nat) (heq : n = m) => eq_ind\n  n\n  (fun m0 : nat => plus O n = plus O m0)\n  eq_refl\n  m\n  heq)\n*)\nQed.\n\nTheorem thme : forall (n m: nat) (f:nat->nat), n=m -> f n = f m.\nintros n m f heq.\nrewrite heq.\nreflexivity.\nShow Proof.\n(*\n(fun (n m : nat) (f : nat -> nat) (heq : n = m) =>\n eq_ind_r (fun x : nat => f x = f m) eq_refl heq)\n*)\nQed.\n\nPrint eq_ind_r.\n(*\neq_ind_r = fun (A : Type) (x : A) (P : A -> Prop) (H : P x) (y : A) (H0 : y = x) =>\neq_ind x (fun y0 : A => P y0) H y (eq_sym H0) :\nforall (A : Type) (x : A) (P : A -> Prop), P x -> forall y : A, y = x -> P y\n*)\n\nPrint eq_ind.\n(*\neq_ind = fun (A : Type) (x : A) (P : A -> Prop) => eq_rect x P :\nforall (A : Type) (x : A) (P : A -> Prop), P x -> forall y : A, x = y -> P y\n*)\n\nPrint eq_rect.\n(*\neq_rect = fun (A : Type) (x : A) (P : A -> Type) (f : P x) (y : A) (e : x = y) =>\nmatch e in (_ = y0) return (P y0) with\n| eq_refl => f\nend :\nforall (A : Type) (x : A) (P : A -> Type),P x -> forall y : A, x = y -> P y\n*)\n\nPrint eq_refl.\n\nTheorem thmf :\nforall (f : nat -> nat) (x:nat) (P:nat->Prop) (H:P x) (m:nat) (H0:m=x) (toto:P m),\nP = (fun x : nat => f x = f m) ->\n@eq_ind_r nat x P H m H0 = toto.\nintros f x P H y H0 toto Ph.\nunfold eq_ind_r.\nunfold eq_ind.\nunfold eq_rect.\nsubst P.\nAdmitted.\n\n\n", "meta": {"author": "xavierdpt", "repo": "adventures", "sha": "038a17cf71d8f9690ad168b2592b12e61d2e6c32", "save_path": "github-repos/coq/xavierdpt-adventures", "path": "github-repos/coq/xavierdpt-adventures/adventures-038a17cf71d8f9690ad168b2592b12e61d2e6c32/trove/SF/V1/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245618, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.6974473337378811}}
{"text": "Welcome to Coq 8.4pl4 (November 2015)\n\nCoq < Definition doit3times {X:Type} (f:X -> X) (n:X) : X := f (f (f n)).\ndoit3times is defined\n\nCoq < Check @doit3times.\ndoit3times\n     : forall X : Type, (X -> X) -> X -> X\n\nCoq < Definition minustwo (n : nat) : nat := match n with | O => O | S O => O | S (S n') => n' end.\nminustwo is defined\n\nCoq < Example test_doit3times: doit3times minustwo 9 = 3.\n1 subgoal\n  \n  ============================\n   doit3times minustwo 9 = 3\n\ntest_doit3times < reflexivity.\nNo more subgoals.\n\ntest_doit3times < Qed.\nreflexivity.\n\ntest_doit3times is defined\n\nCoq < Definition negb (b:bool) : bool := match b with | true => false | false => true end.\nnegb is defined\n\nCoq < Notation \"x :: l\" := (cons x l) (at level 60, right associativity).\n\nCoq < Notation \"[ ]\" := nil.\nSetting notation at level 0.\n\nCoq < Notation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\nSetting notation at level 0.\n\nCoq < Fixpoint filter {X:Type} (test: X -> bool) (l:list X) : (list X) := match l with | [] => [] | h :: t => if test h then h :: (filter test t) else filter test t end.\nfilter is recursively defined (decreasing on 3rd argument)\n\nCoq < Fixpoint evenb (n:nat) : bool := match n with | O => true | S O => false | S (S n') => evenb n' end.\nevenb is recursively defined (decreasing on 1st argument)\n\nCoq < Example test_filter1: filter evenb [1;2;3;4] = [2;4].\n1 subgoal\n  \n  ============================\n   filter evenb [1; 2; 3; 4] = [2; 4]\n\ntest_filter1 < Proof.\n1 subgoal\n  \n  ============================\n   filter evenb [1; 2; 3; 4] = [2; 4]\n\ntest_filter1 < reflexivity.\nNo more subgoals.\n\ntest_filter1 < Qed.\nreflexivity.\n\ntest_filter1 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/poly/poly005.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619134371953, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.6974473173189314}}
{"text": "From Coq Require Import\n     List\n     Logic.Decidable\n     Relations.\n\nLtac symm_not :=\n  let H := fresh\n  in unfold not;\n     intros H;\n     symmetry in H;\n     generalize dependent H.\n\nOpen Scope list_scope.\n\nSection forall_dec.\n  Context {A} (P : A -> Prop).\n\n  Definition Forall_dec l :\n    (forall a, decidable (P a)) ->\n    decidable (Forall P l).\n  Proof.\n    intros Hdec.\n    induction l.\n    { left. constructor. }\n    { destruct IHl as [Hl|Hl].\n      - destruct (Hdec a).\n        + left. constructor; auto.\n        + right. intros H'.\n          inversion H'. auto.\n      - right. intros H.\n        inversion H. auto.\n    }\n  Defined.\nEnd forall_dec.\n", "meta": {"author": "Zabrane", "repo": "libtx", "sha": "0e3f24ef165a240ee6af59a4956995c2205fe9aa", "save_path": "github-repos/coq/Zabrane-libtx", "path": "github-repos/coq/Zabrane-libtx/libtx-0e3f24ef165a240ee6af59a4956995c2205fe9aa/theories/Misc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.697256543321337}}
{"text": "Require Import XR_Rsqr.\nRequire Import XR_Ropp_mult_distr_l.\nRequire Import XR_Ropp_mult_distr_r.\nRequire Import XR_Ropp_involutive.\n\nLocal Open Scope R_scope.\n\nLemma Rsqr_neg : forall x:R, Rsqr x = Rsqr (- x).\nProof.\n  intro x.\n  unfold Rsqr.\n  rewrite <- Ropp_mult_distr_l.\n  rewrite <- Ropp_mult_distr_r.\n  rewrite Ropp_involutive.\n  reflexivity.\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rsqr_neg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6972565289768523}}
{"text": "Require Import ZArith.\nRequire Import Nat_utils.\n\nLemma add_simpl (m n p : Z) :\n  Z.add m p = Z.add n p -> m = n.\nProof.\n  intro.\n  rewrite <- Z.add_0_r with (n := m).\n  rewrite <- Z.add_0_r with (n := n).\n  rewrite <- Z.add_opp_diag_r with (n := p).\n  rewrite Z.add_assoc with (n := m) (m := p) (p := Z.opp p).\n  rewrite Z.add_assoc with (n := n) (m := p) (p := Z.opp p).\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma excluded_middle_pos (p q : positive) :\n  p = q \\/ p <> q.\nProof.\n  revert q.\n  induction p.\n  induction q.\n  destruct IHp with (q := q).\n  left.\n  apply f_equal with (f := xI).\n  assumption.\n  right.\n  injection.\n  assumption.\n  right.\n  discriminate.\n  right.\n  discriminate.\n  induction q.\n  right.\n  discriminate.\n  destruct IHp with (q := q).\n  left.\n  apply f_equal with (f := xO).\n  assumption.\n  right.\n  injection.\n  assumption.\n  right.\n  discriminate.\n  induction q.\n  right.\n  discriminate.\n  right.\n  discriminate.\n  left.\n  reflexivity.\nQed.\n\n\nLemma excluded_middle_z (z1 z2 : Z) :\n  z1 = z2 \\/ z1 <> z2.\nProof.\n  revert z2.\n  induction z1.\n  induction z2.\n  left.\n  reflexivity.\n  right.\n  discriminate.\n  right.\n  discriminate.\n  induction z2.\n  right.\n  discriminate.\n  destruct excluded_middle_pos with (p := p) (q := p0).\n  left.\n  apply f_equal with (f := Z.pos).\n  assumption.\n  right.\n  injection.\n  assumption.\n  right.\n  discriminate.\n  induction z2.\n  right.\n  discriminate.\n  right.\n  discriminate.\n  destruct excluded_middle_pos with (p := p) (q := p0).\n  left.\n  apply f_equal with (f := Z.neg).\n  assumption.\n  right.\n  injection.\n  assumption.\nQed.\n\nLemma affine_not_constant (a b c : Z) :\n  a <> Z.zero -> exists (x : Z), x <> Z.zero /\\ (b + a * x)%Z <> c.\nProof.\n  intro.\n  destruct excluded_middle_z with (z1 := (b + a)%Z) (z2 := c).\n  exists (2)%Z.\n  split.\n  discriminate.\n  rewrite Z.two_succ.\n  rewrite Z.mul_succ_r.\n  rewrite Z.mul_1_r.\n  rewrite Z.add_assoc.\n  rewrite H0.\n  intro.\n  apply f_equal with (f := fun z => Z.sub z c) in H1.\n  revert H1.\n  rewrite Z.add_simpl_l.\n  rewrite Z.sub_diag.\n  assumption.\n  exists Z.one.\n  split.\n  discriminate.\n  rewrite Z.mul_1_r.\n  assumption.\nQed.\n\nImport Z.\n\nLemma z_lt_irrefl (z1 z2 : Z) :\n  (z1 < z2)%Z -> z1 <> z2.\nProof.\n  intro.\n  intro.\n  revert H.\n  rewrite H0.\n  apply Z.lt_irrefl.\nQed.\n\nLemma z_add_pos (z1 z2 : Z) :\n  (0 < z1)%Z -> (0 < z2)%Z -> (0 < z1 + z2)%Z.\nProof.\n  induction z1.\n  intro.\n  apply Z.lt_irrefl in H.\n  contradiction.\n  intro.\n  induction z2.\n  intro.\n  apply Z.lt_irrefl in H0.\n  contradiction.\n  intro.\n  apply Pos2Z.is_pos.\n  intro.\n  apply Z.lt_asymm in H0.\n  exfalso.\n  apply H0.\n  apply Pos2Z.neg_is_neg.\n  induction z2.\n  intros.\n  apply Z.lt_irrefl in H0.\n  contradiction.\n  intros.\n  apply Z.lt_asymm in H.\n  exfalso.\n  apply H.\n  apply Pos2Z.neg_is_neg.\n  intro.\n  apply Z.lt_asymm in H.\n  exfalso.\n  apply H.\n  apply Pos2Z.neg_is_neg.\nQed.\n\nLemma z_mul_pos (z1 z2 : Z) :\n  (0 < z1)%Z -> (0 < z2)%Z -> (0 < z1 * z2)%Z.\nProof.\n  induction z1.\n  intro.\n  apply Z.lt_irrefl in H.\n  contradiction.\n  intro.\n  induction z2.\n  intro.\n  apply Z.lt_irrefl in H0.\n  contradiction.\n  intro.\n  apply Pos2Z.is_pos.\n  intro.\n  apply Z.lt_asymm in H0.\n  exfalso.\n  apply H0.\n  apply Pos2Z.neg_is_neg.\n  induction z2.\n  intros.\n  apply Z.lt_irrefl in H0.\n  contradiction.\n  intros.\n  apply Z.lt_asymm in H.\n  exfalso.\n  apply H.\n  apply Pos2Z.neg_is_neg.\n  intros.\n  apply Pos2Z.is_pos.\nQed.\n\nLemma z_mul_le_0 (z1 z2 : Z) :\n  (0 <= z1)%Z -> (0 <= z2)%Z -> (0 <= z1 * z2)%Z.\nProof.\n  induction z1.\n  intros.\n  rewrite Z.mul_0_l.\n  apply Z.le_refl.\n  intro.\n  induction z2.\n  intro.\n  rewrite Z.mul_0_r.\n  apply Z.le_refl.\n  intro.\n  apply Z.lt_le_incl.\n  apply Pos2Z.is_pos.\n  intro.\n  apply Zle_not_lt in H0.\n  exfalso.\n  apply H0.\n  apply Pos2Z.neg_is_neg.\n  induction z2.\n  intros.\n  rewrite Z.mul_0_r.\n  apply Z.le_refl.\n  intros.\n  apply Zle_not_lt in H.\n  exfalso.\n  apply H.\n  apply Pos2Z.neg_is_neg.\n  intros.\n  apply Pos2Z.is_nonneg.\nQed.\n\nLemma z_pos_ge_1 (z : Z) :\n  (0 < z)%Z -> (1 <= z)%Z.\nProof.\n  elim z.\n  intro.\n  exfalso.\n  apply Z.lt_irrefl with (x := 0%Z).\n  assumption.\n  intros.\n  apply Pos.le_1_l.\n  intros.\n  apply Z.lt_asymm in H.\n  exfalso.\n  apply H.\n  apply Pos2Z.neg_is_neg.\nQed.\n\nLemma z_pos_pos_mul (z1 z2 : Z) :\n  (0 < z1)%Z -> (0 < z2)%Z -> (z1 <= z1 * z2)%Z.\nProof.\n  intros.\n  rewrite <- Z.add_simpl_r with (n := (z1 * z2)%Z) (m := z1).\n  rewrite <- Z.add_opp_r.\n  rewrite <- Z.add_assoc.\n  rewrite <- Z.add_comm with (m := z1) (n := (-z1)%Z).\n  rewrite Z.add_assoc.\n  rewrite <- Z.mul_1_r with (n := (-z1)%Z).\n  rewrite <- Zopp_mult_distr_l with (n := z1) (m := 1%Z).\n  rewrite Zopp_mult_distr_r with (n := z1) (m := 1%Z).\n  rewrite <- Z.mul_add_distr_l.\n  rewrite Z.add_opp_r.\n  apply Zplus_le_reg_r with (p := (-z1)%Z).\n  rewrite <- Z.add_assoc.\n  rewrite Z.add_opp_diag_r with (n := z1).\n  rewrite Z.add_0_r.\n  apply z_mul_le_0.\n  apply Z.lt_le_incl.\n  assumption.\n  apply Zplus_le_reg_r with (p := 1%Z).\n  rewrite Z.add_0_l.\n  rewrite <- Z.add_opp_r.\n  rewrite <- Z.add_assoc.\n  rewrite Z.add_opp_diag_l.\n  rewrite Z.add_0_r.\n  apply z_pos_ge_1.\n  assumption.\nQed.\n\nLemma pos_plus_neg (z : Z) (p : positive) :\n  (z * pos p + z * neg p)%Z = 0%Z.\nProof.\n  rewrite <- Z.mul_add_distr_l.\n  simpl.\n  rewrite pos_sub_diag.\n  apply Z.mul_0_r.\nQed.\n\nLemma z_abs_lt (z1 z2 z3 : Z) :\n  (Z.abs z1 < z2)%Z -> z3 <> 0%Z -> (z1 + z2 * z3)%Z <> 0%Z.\nProof.\n  elim z1.\n  intros.\n  intro.\n  apply z_integrity in H1.\n  destruct H1.\n  rewrite H1 in H.\n  apply Z.lt_irrefl with (x := 0%Z).\n  assumption.\n  apply H0.\n  assumption.\n\n  elim z3.\n  intros.\n  exfalso.\n  apply H0.\n  reflexivity.\n\n  intros.\n  intro.\n  symmetry in H1.\n  revert H1.\n  apply z_lt_irrefl with (z1 := 0%Z) (z2 := (pos p0 + z2 * pos p)%Z).\n  apply z_add_pos.\n  apply Pos2Z.is_pos.\n  apply z_mul_pos.\n  apply Z.lt_trans with (m := Z.pos p0).\n  apply Pos2Z.is_pos.\n  assumption.\n  apply Pos2Z.is_pos.\n\n  intros.\n  apply z_lt_irrefl with (z2 := 0%Z) (z1 := (pos p0 + z2 * neg p)%Z).\n  rewrite <- pos_plus_neg with (z := z2) (p := p).\n  apply Zplus_lt_compat_r with (n := Z.pos p0) (m := (z2 * pos p)%Z) (p := (z2 * neg p)%Z).\n  apply Z.lt_le_trans with (m := z2).\n  assumption.\n  apply z_pos_pos_mul.\n  apply Z.lt_trans with (m := Z.pos p0).\n  apply Pos2Z.is_pos.\n  assumption.\n  apply Pos2Z.is_pos.\n\n  elim z3.\n  intros.\n  exfalso.\n  apply H0.\n  reflexivity.\n\n  intros.\n  intro.\n  symmetry in H1.\n  revert H1.\n  apply z_lt_irrefl with (z1 := 0%Z) (z2 := (neg p0 + z2 * pos p)%Z).\n  rewrite <- pos_plus_neg with (z := z2) (p := p).\n  rewrite add_comm.\n  apply Zplus_lt_compat_r with (m := Z.neg p0) (n := (z2 * neg p)%Z) (p := (z2 * pos p)%Z).\n  rewrite <- Pos2Z.opp_pos.\n  rewrite <- Pos2Z.opp_pos.\n  rewrite <- Zopp_mult_distr_r with (n := z2) (m := Z.pos p).\n  apply Z.opp_lt_mono with (m := (z2 * pos p)%Z) (n := Z.pos p0).\n  apply Z.lt_le_trans with (m := z2).\n  assumption.\n  apply z_pos_pos_mul.\n  apply Z.lt_trans with (m := Z.pos p0).\n  apply Pos2Z.is_pos.\n  assumption.\n  apply Pos2Z.is_pos.\n\n  intros.\n  apply z_lt_irrefl with (z1 := (neg p0 + z2 * neg p)%Z) (z2 := 0%Z).\n  rewrite <- Pos2Z.opp_pos.\n  rewrite <- Pos2Z.opp_pos.\n  rewrite <- Zopp_mult_distr_r with (n := z2) (m := Z.pos p).\n  rewrite <- Z.opp_add_distr.\n  apply Z.opp_lt_mono with (m := (pos p0 + z2 * pos p)%Z) (n := 0%Z).\n  apply z_add_pos.\n  apply Pos2Z.is_pos.\n  apply z_mul_pos.\n  apply Z.lt_trans with (m := Z.pos p0).\n  apply Pos2Z.is_pos.\n  assumption.\n  apply Pos2Z.is_pos.\nQed.\n", "meta": {"author": "TabetSalwa", "repo": "2.7.2-polynomials", "sha": "78bcea3ccdf0b614223266cf867b6954dc704dbf", "save_path": "github-repos/coq/TabetSalwa-2.7.2-polynomials", "path": "github-repos/coq/TabetSalwa-2.7.2-polynomials/2.7.2-polynomials-78bcea3ccdf0b614223266cf867b6954dc704dbf/Z_utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.697256528253455}}
{"text": "(** * Tactics: More Basic Tactics *)\n\n(* Suppress some annoying warnings from Coq: *)\nSet Warnings \"-notation-overridden,-parsing\".\nFrom COC Require Export Poly.\n\n(* ################################################################# *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    _exactly_ the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n\n(** Here, we could finish with \"[rewrite -> eq2.  reflexivity.]\" as we\n    have done several times before.  We can finish this proof in\n    a single step by using the [apply] tactic instead: *)\n\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n    n = m ->\n    (n = m -> [n;o] = [m;p]) ->\n    [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] that introduces some _universally quantified\n    variables_.  When Coq matches the current goal against the\n    conclusion of [H], it will try to find appropriate values for\n    these variables.  For example, when we do [apply eq2] in the\n    following proof, the universal variable [q] in [eq2] gets\n    instantiated with [n], and [r] 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.\nQed.\n\n(** **** Exercise: 2 stars, standard, optional (silly_ex) \n\n    Complete the following proof using only [intros] and [apply]. *)\n\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 2 = true ->\n     oddb 3 = true.\nProof.\n  intros n eq1.\n  apply eq1.\nQed.\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), true = (n =? 5)  ->\n     (S (S n)) =? 7 = true.\nProof.\n  intros n H.\n\n(** Here we cannot use [apply] directly, but we can use the [symmetry]\n    tactic, which switches the left and right sides of an equality in\n    the goal. *)\n\n  symmetry.\n  simpl. (** (This [simpl] is optional, since [apply] will perform\n             simplification first, if needed.) *)\n  apply H.\nQed.\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.  You may find earlier lemmas like\n    [app_nil_r], [app_assoc], [rev_app_distr], [rev_involutive],\n    etc. helpful.  Also, remember that [Search] is your friend\n    (though it may not find earlier lemmas if they were posed as\n    optional problems and you chose not to finish the proofs). *)\n\nTheorem rev_exercise1 : forall (l l' : list nat), l = rev l' ->\n     l' = rev l.\nProof.\n  intros l l' H.\n  rewrite -> H.\n  symmetry.\n  apply rev_involutive.\nQed.\n\n(** **** Exercise: 1 star, optional (apply_rewrite)  *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  What are the situations where both can usefully be\n    applied? *)\n\n(* When we need to use global variables, \"apply\" is better than \"rewrite\". *)\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.\nQed.\n\n(** Since this is a common pattern, we might like to pull it out as a\n    lemma that records, once and for all, the fact that equality is\n    transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. \n  rewrite -> eq1. rewrite -> eq2.\n  reflexivity.\nQed.\n\n(** Now, we should be able to use [trans_eq] to prove the above\n    example.  However, to do this we need a slight refinement of the\n    [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n\n(** If we simply tell Coq [apply trans_eq] at this point, it can\n    tell (by matching the goal against the conclusion of the lemma)\n    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and\n    [o] with [[e,f]].  However, the matching process doesn't determine\n    an instantiation for [m]: we have to supply one explicitly by\n    adding \"[with (m:=[c,d])]\" to the invocation of [apply]. *)\n  apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2.\nQed.\n\n(** (Actually, we usually don't have to include the name [m] in\n    the [with] clause; Coq is often smart enough to figure out which\n    variable we are instantiating. We could instead write [apply\n    trans_eq with [c;d]].) *)\n\n(** Coq also has a tactic [transitivity] that accomplishes the\n    same purpose as applying [trans_eq]. The tactic requires us to\n    state the instantiation we want, just like [apply with] does. *)\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  transitivity [c;d].\n  apply eq1. apply eq2.\nQed.\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.\n  apply H2.\n  apply H1.\nQed.\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    It is obvious from this definition that every number has one of\n    two forms: either it is the constructor [O] or it is built by\n    applying the constructor [S] to another number.  But there is more\n    here than meets the eye: implicit in the definition are two more\n    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  (* insert new hypothesis H2 *)\n  assert (H2: n = pred (S n)). { reflexivity. }\n  (* prove H1 *)\n  rewrite H2. \n  rewrite H1. \n  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\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\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  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  intros n m o H.\n  injection H.\n  intros H1 H2. rewrite H1. rewrite H2. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, standard (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 H1 H2.\n  injection H1. rewrite -> H2.\n  (* insert new hypothesis H3 *)\nAdmitted.\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  0 =? n = true -> n = 0.\nProof.\n  intros n.\n\n(** We can proceed by case analysis on [n]. The first case is\n    trivial. *)\n\n  destruct n as [| n'] eqn:E.\n  - (* n = 0 *)\n    intros H. reflexivity.\n\n(** However, the second one doesn't look so simple: assuming [0\n    =? (S n') = true], we must show [S n' = 0]!  The way forward is to\n    observe that the assumption itself is nonsensical: *)\n\n  - (* n = S n' *)\n    simpl.\n\n(** If we use [discriminate] on this hypothesis, Coq confirms\n    that the subgoal we are working on is impossible and removes it\n    from further consideration. *)\n\n    intros H. discriminate H.\nQed.\n\n(** This is an instance of a logical principle known as the _principle\n    of explosion_, which asserts that a contradictory hypothesis\n    entails anything (even false things!). *)\n\nTheorem discriminate_ex1 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. discriminate contra. Qed.\n\nTheorem discriminate_ex2 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. discriminate contra. Qed.\n\n(** If you find the principle of explosion confusing, remember\n    that these proofs are _not_ showing that the conclusion of the\n    statement holds.  Rather, they are showing that, _if_ the\n    nonsensical situation described by the premise did somehow arise,\n    _then_ the nonsensical conclusion would 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. *)\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 contra.\n  discriminate contra.\nQed.\n\n\n\n(** To summarize this discussion, suppose [H] is a hypothesis in the\n    context or a previously proven lemma of the form\n      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] has the following effect:\n    - If [c] and [d] are the same constructor, then, by the\n      injectivity of this constructor, we know that [a1 = b1], [a2 =\n      b2], etc.; [inversion H] adds these facts to the context, and\n      tries to use them to rewrite the goal.\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory, and the current goal doesn't have to be\n      considered. In this case, [inversion H] marks the current goal\n      as completed and pops it off the goal stack. *)\n\n\n\n(** The injectivity of constructors allows us to reason that\n    [forall (n m : nat), S n = S m -> n = m].  The converse of this\n    implication is an instance of a more general fact about both\n    constructors and functions, which we will find convenient in a few\n    places below: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. \n  intros A B f x y H. \n  rewrite H.\n  reflexivity.\nQed.\n\nTheorem eq_implies_succ_equal : forall (n m : nat),\n    n = m -> S n = S m.\nProof. intros n m H. apply f_equal. apply H. Qed.\n\n(** There is also a tactic named `f_equal` that can prove such\n    theorems.  Given a goal of the form [f a1 ... an = g b1 ... bn],\n    the tactic [f_equal] will produce subgoals of the form [f = g],\n    [a1 = b1], ..., [an = bn]. At the same time, any of these subgoals\n    that are simple enough (e.g., immediately provable by\n    [reflexivity]) will be automatically discharged by [f_equal]. *)\n\nTheorem eq_implies_succ_equal' : forall (n m : nat),\n    n = m -> S n = S m.\nProof. intros n m H. f_equal. apply H. Qed.\n\n(* ################################################################# *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic \"[simpl in H]\" performs simplification on\n    the hypothesis [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     (S n) =? (S m) = b  ->\n     n =? m = b.\nProof.\n  intros n m b H. simpl in H. apply H.\nQed.\n\n\n(** Similarly, [apply L in H] matches some conditional statement\n    [L] (of the form [X -> Y], say) against a hypothesis [H] in the\n    context.  However, unlike ordinary [apply] (which rewrites a goal\n    matching [Y] into a subgoal [X]), [apply L in H] matches [H]\n    against [X] and, if successful, replaces it with [Y].\n\n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\": from [X -> Y] and a hypothesis matching [X], it\n    produces a hypothesis matching [Y].  By contrast, [apply L] is\n    \"backward reasoning\": it says that if we know [X -> Y] and we\n    are trying to prove [Y], it suffices to prove [X].\n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\nTheorem silly3' : forall (n : nat),\n  (n =? 5 = true -> (S (S n)) =? 7 = true) ->\n  true = (n =? 5)  ->\n  true = ((S (S n)) =? 7).\nProof.\n  intros n eq H.\n  symmetry in H. apply eq in H. symmetry in H. apply H.\nQed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_ and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n\n    The informal proofs that you've seen in math or computer science\n    classes probably tended to use forward reasoning.  In general,\n    idiomatic use of Coq favors backward reasoning, but in some\n    situations the forward style can be easier to think about. *)\n\n(* ################################################################# *)\n(** * Varying the Induction Hypothesis *)\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 sometimes need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose\n    we want to show that [double] is injective -- i.e., that it maps\n    different arguments to different results:\n\n       Theorem double_injective: forall n m,\n         double n = double m -> n = m.\n\n    The way we start this proof is a bit delicate: if we begin it with\n\n       intros n. induction n.\n\n    all is well.  But if we begin it with\n\n       intros n m. induction n.\n\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n' IHn'].\n  - (* n = O *) \n  simpl. intros eq. destruct m as [| m'] eqn:E.\n    + (* m = O *) \n    reflexivity.\n    + (* m = S m' *)\n    discriminate eq.\n  - (* n = S n' *) \n  intros eq. destruct m as [| m'] eqn:E.\n    + (* m = O *)\n    discriminate eq.\n    + (* m = S m' *)\n    apply f_equal.\n\n(** At this point, the induction hypothesis ([IHn']) does _not_ give us\n    [n' = m'] -- there is an extra [S] in the way -- so the goal is\n    not provable. *)\n\nAbort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context --\n    intuitively, we have told Coq, \"Let's consider some particular [n]\n    and [m]...\" and we now have to prove that, if [double n = double\n    m] for _those particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove, for\n    _all_ [n], that the proposition\n\n      - [P n] = \"if [double n = double m], then [n = m]\"\n\n    holds, by showing\n\n      - [P O]\n\n         (i.e., \"if [double O = double m] then [O = m]\") and\n\n      - [P n -> P (S n)]\n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: 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 (arbitrary,\n    but fixed) [m] -- say, [5].  The statement is then saying that,\n    if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help at all with proving\n    [R]!  If we tried to prove [R] from [Q], we would start with\n    something like \"Suppose [double (S n) = 10]...\" but then we'd be\n    stuck: knowing that [double (S n)] is [10] tells us nothing\n    helpful about whether [double n] is [10] (indeed, it strongly\n    suggests that [double n] is _not_ [10]!!), so [Q] is useless. *)\n\n(** Trying to carry out this proof by induction on [n] when [m] is\n    already in the context doesn't work because we are then trying to\n    prove a statement involving _every_ [n] but just a _single_ [m]. *)\n\n(** A successful proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = O *) simpl. intros m eq. destruct m as [| m'] eqn:E.\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) discriminate eq.\n\n  - (* n = S n' *) simpl.\n\n(** Notice that both the goal and the induction hypothesis are\n    different this time: the goal asks us to prove something more\n    general (i.e., to prove the statement for _every_ [m]), but the IH\n    is correspondingly more flexible, allowing us to choose whichever\n    [m] we like when we apply the IH. *)\n\n    intros m eq.\n\n(** Now we've chosen a particular [m] and introduced the assumption\n    that [double n = double m].  Since we are doing a case analysis on\n    [n], we also need a case analysis on [m] to keep the two \"in sync.\" *)\n\n    destruct m as [| m'] eqn:E.\n    + (* m = O *)\n\n(** The 0 case is trivial: *)\n\n    discriminate eq.\n    + (* m = S m' *)\n      apply f_equal.\n\n(** At this point, since we are in the second branch of the [destruct\n    m], the [m'] mentioned in the context is the predecessor of the\n    [m] we started out talking about.  Since we are also in the [S]\n    branch of the induction, this is perfect: if we instantiate the\n    generic [m] in the IH with the current [m'] (this instantiation is\n    performed automatically by the [apply] in the next step), then\n    [IHn'] gives us exactly what we need to finish the proof. *)\n\n      apply IHn'. simpl in eq. injection eq as goal. apply goal. Qed.\n\n(** What you should take away from all this is that we need to be\n    careful, when using induction, that we are not trying to prove\n    something too specific: When proving a property involving two\n    variables [n] and [m] by induction on [n], it is sometimes\n    crucial to leave [m] generic. *)\n\n(** The following exercise follows the same pattern. *)\n\n(** **** Exercise: 2 stars, standard (eqb_true)  *)\nTheorem eqb_true : forall n m,\n    n =? m = true -> n = m.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = O *)\n    intros m eq. destruct m as [| m'] eqn:E.\n    + (* m = O *) simpl. reflexivity.\n    + (* m = S m' *) discriminate eq.\n  - (* n = S n' *)\n     intros m eq.  destruct m as [| m'] eqn:E.\n    + (* m = O *)  discriminate eq.\n    + (* m = S m' *) apply f_equal. apply IHn'.\n    simpl in eq. apply eq.\nQed.\n\n(** The strategy of doing fewer [intros] before an [induction] to\n    obtain a more general IH doesn't always work by itself; sometimes\n    some _rearrangement_ of quantified variables is needed.  Suppose,\n    for example, that we wanted to prove [double_injective] by\n    induction on [m] instead of [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m' IHm'].\n  - (* m = O *) simpl. intros eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) discriminate eq.\n  - (* m = S m' *) intros eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) discriminate eq.\n    + (* n = S n' *) apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (And if we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce [n]\n    for us!)  *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    works, but it's not nice: We don't want to have to twist the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them!  Rather we want to state them in the clearest and\n    most natural way. *)\n\n(** What we can do instead is to first introduce all the quantified\n    variables and then _re-generalize_ one or more of them,\n    selectively taking variables out of the context and putting them\n    back at the beginning of the goal.  The [generalize dependent]\n    tactic does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m.\n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m' IHm'].\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(* ################################################################# *)\n(** * Unfolding Definitions *)\n\n(** It sometimes happens that we need to manually unfold a name that\n    has been introduced by a [Definition] so that we can manipulate\n    the expression it denotes.  For example, if we define... *)\n\nDefinition square n := n * n.\n\n(** ... and try to prove a simple fact about [square]... *)\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\n  simpl.\n\n(** ... we appear to be stuck: [simpl] doesn't simplify anything, and\n    since we haven't proved any other facts about [square], there is\n    nothing we can [apply] or [rewrite] with. *)\n\n(**  To make progress, we can manually [unfold] the definition of\n    [square]: *)\n\n  unfold square.\n\n(** Now we have plenty to work with: both sides of the equality are\n    expressions involving multiplication, and we have lots of facts\n    about multiplication at our disposal.  In particular, we know that\n    it is commutative and associative, and from these it is not hard\n    to finish the proof. *)\n\n  rewrite mult_assoc.\n  assert (H : n * m * n = n * n * m).\n    { rewrite mult_comm. apply mult_assoc. }\n  rewrite -> H. rewrite -> mult_assoc. reflexivity.\nQed.\n\n(** At this point, some discussion of unfolding and simplification is\n    in order.\n\n    We already have observed that tactics like [simpl], [reflexivity],\n    and [apply] will often unfold the definitions of functions\n    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\n    [reflexivity], if we omit the [simpl]) will unfold [foo m] to\n    [(fun x => 5) m] and then further simplify this expression to just\n    [5]. *)\n\nFact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.\nProof.\n  intros m.\n  simpl.\n  reflexivity.\nQed.\n\n(** However, this automatic unfolding is somewhat conservative.  For\n    example, if we define a slightly more complicated function\n    involving a pattern match... *)\n\nDefinition bar x :=\n  match x with\n  | O => 5\n  | S _ => 5\n  end.\n\n(** ...then the analogous proof will get stuck: *)\n\nFact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  simpl. (* Does nothing! *)\nAbort.\n\n(** The reason that [simpl] doesn't make progress here is that it\n    notices that, after tentatively unfolding [bar m], it is left with\n    a match whose scrutinee, [m], is a variable, so the [match] cannot\n    be simplified further.  It is not smart enough to notice that the\n    two branches of the [match] are identical, so it gives up on\n    unfolding [bar m] and leaves it alone.  Similarly, tentatively\n    unfolding [bar (m+1)] leaves a [match] whose scrutinee is a\n    function application (that cannot itself be simplified, even\n    after unfolding the definition of [+]), so [simpl] leaves it\n    alone. *)\n\n(** At this point, there are two ways to make progress.  One is to use\n    [destruct m] to break the proof into two cases, each focusing on a\n    more concrete choice of [m] ([O] vs [S _]).  In each case, the\n    [match] inside of [bar] can now make progress, and the proof is\n    easy to complete. *)\n\nFact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  destruct m eqn:E.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(** This approach works, but it depends on our recognizing that the\n    [match] hidden inside [bar] is what was preventing us from making\n    progress. *)\n\n(** A more straightforward way forward is to explicitly tell Coq to\n    unfold [bar]. *)\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n\n(** Now it is apparent that we are stuck on the [match] expressions on\n    both sides of the [=], and we can use [destruct] to finish the\n    proof without thinking too hard. *)\n\n  destruct m eqn:E.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where [destruct] is used to\n    perform case analysis of the value of some variable.  Sometimes we\n    need to reason by cases on the result of some _expression_.  We\n    can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if n =? 3 then false\n  else if n =? 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (n =? 3) eqn:E1.\n    - (* n =? 3 = true *) reflexivity.\n    - (* n =? 3 = false *) destruct (n =? 5) eqn:E2.\n      + (* n =? 5 = true *) reflexivity.\n      + (* n =? 5 = false *) reflexivity.\nQed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (n =? 3) then ... else ...].  But either\n    [n] is equal to [3] or it isn't, so we can use [destruct (eqb\n    n 3)] to let us reason about the two cases.\n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c]. *)\n\n(** **** Exercise: 3 stars, optional (combine_split)  *)\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. generalize dependent l. generalize l1.\n  induction l2 as [| h2 l2'].\n  - intros l0 l. generalize dependent l0. induction l as [|h l'].\n    + intros l0 H. assert (l0 = []). { inversion H. reflexivity. } rewrite H0. reflexivity.\n    + intros l0 H. inversion H. unfold app_list_pair in H1. Abort.\n\n(** The [eqn:] part of the [destruct] tactic is optional: So far,\n    we've chosen to include it most of the time, just for the sake of\n    documentation.\n\n    However, when [destruct]ing compound expressions, the information\n    recorded by the [eqn:] can actually be critical: if we leave it\n    out, then [destruct] can erase information we need to complete a\n    proof.\n\n    For example, suppose we define a function [sillyfun1] like\n    this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if n =? 3 then true\n  else if n =? 5 then true\n  else false.\n\n(** Now suppose that we want to convince Coq that [sillyfun1 n]\n    yields [true] only when [n] is odd.  If we start the proof like\n    this (with no [eqn:] on the [destruct])... *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3).\n  (* stuck... *)\nAbort.\n\n(** ... then we are stuck at this point because the context does\n    not contain enough information to prove the goal!  The problem is\n    that the substitution performed by [destruct] is quite brutal --\n    in this case, it throws away every occurrence of [n =? 3], but we\n    need to keep some memory of this expression and how it was\n    destructed, because we need to be able to reason that, since [n =?\n    3 = true] in this branch of the case analysis, it must be that [n\n    = 3], from which it follows that [n] is odd.\n\n    What we want here is to substitute away all existing occurences of\n    [n =? 3], but at the same time add an equation to the context that\n    records which case we are in.  This is precisely what the [eqn:]\n    qualifier does. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got\n     stuck above, except that the context contains an extra\n     equality assumption, which is exactly what we need to\n     make progress. *)\n    - (* e3 = true *) apply eqb_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    - (* e3 = false *)\n     (* When we come to the second equality test in the body\n        of the function we are reasoning about, we can use\n        [eqn:] again in the same way, allowing us to finish the\n        proof. *)\n      destruct (n =? 5) eqn:Heqe5.\n        + (* e5 = true *)\n          apply eqb_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + (* e5 = false *) discriminate eq.\nQed.\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/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059462938815, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.6972565226985679}}
{"text": "Require Import ZArith.\n\nOpen Scope Z_scope.\n\nRecord Hurwitz : Set := mkHurwitz { h : Z ; i : Z ; j : Z ; k : Z }.\n\n(** Internal operations *)\n\nDefinition hopp (h1 : Hurwitz) : Hurwitz :=\n  let (h1, i1, j1, k1) := h1 in\n  mkHurwitz (- h1) (- i1) (- j1) (- k1).\n\nDefinition hadd (h1 h2 : Hurwitz) : Hurwitz :=\n  let (h1, i1, j1, k1) := h1 in\n  let (h2, i2, j2, k2) := h2 in\n  mkHurwitz (h1 + h2) (i1 + i2) (j1 + j2) (k1 + k2).\n\nDefinition hminus (h1 h2 : Hurwitz) : Hurwitz := hadd h1 (hopp h2).\n\nDefinition hmul (h1 h2 : Hurwitz) : Hurwitz :=\n  let (h1, i1, j1, k1) := h1 in\n  let (h2, i2, j2, k2) := h2 in\n  let hh := h1 * h2 in\n  let hi := h1 * i2 in\n  let hj := h1 * j2 in\n  let hk := h1 * k2 in\n  let ih := i1 * h2 in\n  let ii := i1 * i2 in\n  let ij := i1 * j2 in\n  let ik := i1 * k2 in\n  let jh := j1 * h2 in\n  let ji := j1 * i2 in\n  let jj := j1 * j2 in\n  let jk := j1 * k2 in\n  let kh := k1 * h2 in\n  let ki := k1 * i2 in\n  let kj := k1 * j2 in\n  let kk := k1 * k2 in\n    mkHurwitz\n      (- hh - hi - hj - hk - ih - 2 * ii - jh - 2 * jj - kh - 2 * kk)\n      (hh + hi + hk + ih + ii + jh + jj + jk - kj + kk)\n      (hh + hi + hj + ii - ik + jh + jj + kh + ki + kk)\n      (hh + hj + hk + ih + ii + ij - ji + jj + kh + kk).\n\n(* awesome bash:\n for x in h i j k; do for y in h i j k; do\n echo \"let $x$y := ${x}1 * ${y}2 in\"; done; done *)\n\n\n(** Notations *)\n\nNotation \"h-\" := hopp.\nInfix \" h+ \" := hadd (at level 50).\nInfix \" h- \" := hminus (at level 10).\nInfix \" h* \" := hmul (at level 60).\n\n(** External operations *)\n\nDefinition IZH (n : Z) : Hurwitz := mkHurwitz (2 * n) (- n) (- n) (- n).\n\nDefinition hsmul (k : Z) (h1 : Hurwitz) : Hurwitz :=\n  let (h1, i1, j1, k1) := h1 in\n  mkHurwitz (k * h1) (k * i1) (k * j1) (k * k1).\n\n(** Conjugate, norm *)\n\nDefinition hconj (h : Hurwitz) :=\n  let (a, b, c, d) := h in\n  mkHurwitz a (- a - b) (- a - c) (- a - d).\n\nDefinition hnorm2 (h1 : Hurwitz) := (- i (hmul h1 (hconj h1)))%Z.\n\nDefinition is_real (x : Hurwitz) : Prop :=\n  h x + 2 * i x = 0 /\\ i x = j x /\\ i x = k x.\n\n\n(** Divisibility, units *)\n\nDefinition h1 := mkHurwitz 2 (- 1) (- 1) (- 1).\nDefinition hh := mkHurwitz 1 0 0 0.\nDefinition hi := mkHurwitz 0 1 0 0.\nDefinition hj := mkHurwitz 0 0 1 0.\nDefinition hk := mkHurwitz 0 0 0 1. \n\nDefinition divide (x y : Hurwitz) := { d | hmul x d = y }.\n\nDefinition is_H_unit (x : Hurwitz) := { y | hmul x y = IZH 1 }.\n\nInductive Z_unit := Z_one | Z_mone.\n\nDefinition halfsub (u v : Z_unit) : Z :=\n  match u, v with\n  | Z_one, Z_one => 0\n  | Z_one, Z_mone => 1\n  | Z_mone, Z_one => -1\n  | Z_mone, Z_mone => 0\n  end.\n\nDefinition Z_of_Z_unit (u : Z_unit) :=\n  match u with\n  | Z_one => 1\n  | Z_mone => -1\n  end.\n\nInductive H_unit : Hurwitz -> Type :=\n  | H_unit_1 : forall u, let n := Z_of_Z_unit u in H_unit (mkHurwitz (2 * n) (- n) (- n) (- n))\n  | H_unit_i : forall u, H_unit (mkHurwitz 0 (Z_of_Z_unit u) 0 0)\n  | H_unit_j : forall u, H_unit (mkHurwitz 0 0 (Z_of_Z_unit u) 0)\n  | H_unit_k : forall u, H_unit (mkHurwitz 0 0 0 (Z_of_Z_unit u))\n  | H_unit_h : forall u v w z, H_unit (mkHurwitz\n      (Z_of_Z_unit u)\n      (halfsub v u)\n      (halfsub w u)\n      (halfsub z u)).\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/Hurwitz_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.69725596236698}}
{"text": "From Hammer Require Import Hammer.\n\nFrom Topology Require Export TopologicalSpaces.\nFrom Topology Require Export DirectedSets.\nFrom Topology Require Export InteriorsClosures.\nFrom Topology Require 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 :=\nforall U:Ensemble (point_set X), open U -> In U x0 ->\nfor large i:DS_set I, In U (x i).\n\nDefinition net_cluster_point (x:Net) (x0:point_set X) : Prop :=\nforall U:Ensemble (point_set X), open U -> In U x0 ->\nexists arbitrarily large i:DS_set I, In U (x i).\n\nLemma net_limit_is_cluster_point: forall (x:Net) (x0:point_set X),\nnet_limit x x0 -> net_cluster_point x x0.\nProof. hammer_hook \"Nets\" \"Nets.net_limit_is_cluster_point\".\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)) ->\nnet_limit x x0 -> In (closure S) x0.\nProof. hammer_hook \"Nets\" \"Nets.net_limit_in_closure\".\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)) ->\nnet_cluster_point x x0 -> In (closure S) x0.\nProof. hammer_hook \"Nets\" \"Nets.net_cluster_point_in_closure\".\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 :\nforall (U:Ensemble (point_set X)) (y:point_set X),\nopen 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 :=\nmatch Uy, Vz with\n| intro_neighborhood_net_DS U _ _ _ _,\nintro_neighborhood_net_DS V _ _ _ _ =>\nIncluded V U\nend.\n\nDefinition neighborhood_net_DS : DirectedSet.\nrefine (Build_DirectedSet neighborhood_net_DS_set\nneighborhood_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\nH H0 H0).\nsimpl; auto with sets.\nDefined.\n\nDefinition neighborhood_net : Net neighborhood_net_DS X :=\nfun (x:neighborhood_net_DS_set) => match x with\n| intro_neighborhood_net_DS _ y _ _ _ => y\nend.\n\nLemma neighborhood_net_limit: net_limit neighborhood_net x.\nProof. hammer_hook \"Nets\" \"Nets.neighborhood_net_limit\".\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:\nforall {X:TopologicalSpace} (S:Ensemble (point_set X))\n(x0:point_set X), In (closure S) x0 ->\nexists I:DirectedSet, exists x:Net I X,\n(forall i:DS_set I, In S (x i)) /\\ net_limit x x0.\nProof. hammer_hook \"Nets\" \"Nets.net_limits_determine_topology\".\nintros.\nassert (forall U:Ensemble (point_set X), open U -> In U x0 ->\nInhabited (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 =>\nmatch n with\n| intro_neighborhood_net_DS V y _ _ _ => (In S y)\nend).\npose (our_DS_set := {n:neighborhood_net_DS_set X x0 | Ssel n}).\npose (our_DS_ord := fun (n1 n2:our_DS_set) =>\nneighborhood_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,\nour_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\nU 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:\nforall {I:DirectedSet} (x:Net I X) (x0:point_set X),\nnet_limit x x0 -> continuous_at f x0 ->\nnet_limit (fun i:DS_set I => f (x i)) (f x0).\nProof. hammer_hook \"Nets\" \"Nets.continuous_func_preserves_net_limits\".\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));\ntrivial.\nintros.\nassert (In (inverse_image f V) (x i)); auto with sets.\ndestruct H9; trivial.\nQed.\n\nLemma func_preserving_net_limits_is_continuous:\nforall x0:point_set X,\n(forall (I:DirectedSet) (x:Net I X),\nnet_limit x x0 -> net_limit (fun i:DS_set I => f (x i)) (f x0))\n-> continuous_at f x0.\nProof. hammer_hook \"Nets\" \"Nets.func_preserving_net_limits_is_continuous\".\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 ->\nDS_ord (h j1) (h j2)) ->\n(exists arbitrarily large i:DS_set I,\nexists j:DS_set J, h j = i) ->\nSubnet (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 ->\nnet_limit y x0.\nProof. hammer_hook \"Nets\" \"Nets.subnet_limit\".\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 ->\nSubnet y -> net_cluster_point x x0.\nProof. hammer_hook \"Nets\" \"Nets.subnet_cluster_point\".\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 := {\ncps_i:DS_set I;\ncps_U:Ensemble (point_set X);\ncps_U_open_neigh: open_neighborhood cps_U x0;\ncps_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 :=\nDS_ord (cps_i iU1) (cps_i iU2) /\\\nIncluded (cps_U iU2) (cps_U iU1).\n\nDefinition cluster_point_subnet_DS : DirectedSet.\nrefine (Build_DirectedSet\ncluster_point_subnet_DS_set\ncluster_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 =>\nassert C end.\napply H1.\napply open_intersection2;\n(apply cps_U_open_neigh0 ||\napply cps_U_open_neigh1).\nconstructor;\n(apply cps_U_open_neigh0 ||\napply 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 ||\napply cps_U_open_neigh1).\nassert (In kU (x ki)).\nexact H4.\n\nexists (Build_cluster_point_subnet_DS_set\nki 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\ncluster_point_subnet_DS X :=\nfun (iU:DS_set cluster_point_subnet_DS) =>\nx (cps_i iU).\n\nLemma cluster_point_subnet_is_subnet:\nSubnet cluster_point_subnet.\nProof. hammer_hook \"Nets\" \"Nets.cluster_point_subnet_is_subnet\".\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\ni Full_set H H0).\ntrivial.\nQed.\n\nLemma cluster_point_subnet_converges:\nnet_limit cluster_point_subnet x0.\nProof. hammer_hook \"Nets\" \"Nets.cluster_point_subnet_converges\".\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\nx1 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:\nexists J:DirectedSet, exists y:Net J X,\nSubnet y /\\ net_limit y x0.\nProof. hammer_hook \"Nets\" \"Nets.net_cluster_point_impl_subnet_converges\".\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": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/topology/Nets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6972559552863076}}
{"text": "Require Export \"ProofObjects\".\n\nCheck ev_SS.\nCheck nat_ind ev ev_O.\n(*\nev_SS\n     : forall n : nat, ev n -> ev (S (S n))\n *)\n\nCheck nat_ind.\n\n(*\nnat_ind\n     : forall P : nat -> Prop,\n       P 0 -> (forall n : nat, P n -> P (S n)) -> forall n : nat, P n\n *)\n\nTheorem mult_0_r' : forall n:nat,\n                      n * 0 = 0.\nProof.\n  apply nat_ind. Show Proof.\n  Case \"O\". SearchAbout ( _ * O = O ). apply mult_O_r.\n  Show Proof.\n  Case \"n = S\".\n  simpl. intros n H. assumption.\nQed.\n\nTheorem plus_one_r' : forall n:nat,\n  n + 1 = S n.\nProof.\n  apply nat_ind. Show Proof.\n  Case \"O\". reflexivity. Show Proof.\n  Case \"S\".\n  intros n IHn'. simpl. apply f_equal. assumption. Show Proof.\nQed.\n\nInductive yesno : Type :=\n  | yes : yesno\n  | no : yesno.\n\nCheck yesno_ind.\n\nInductive rgb : Type :=\n  | red : rgb\n  | green : rgb\n  | blue : rgb.\nCheck rgb_ind.\n\nInductive natlist : Type :=\n  | nnil : natlist\n  | ncons : nat -> natlist -> natlist.\n\nCheck natlist_ind.\n\nInductive natlist1 : Type :=\n  | nnil1 : natlist1\n  | nsnoc1 : natlist1 -> nat -> natlist1.\nCheck natlist1_ind.\n\nInductive byntree : Type :=\n | bempty : byntree\n | bleaf : yesno -> byntree\n | nbranch : yesno -> byntree -> byntree -> byntree.\nPrint byntree_ind.\n\n(*\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 :=\n| con1 : bool -> ExSet\n| con2 : nat -> ExSet -> ExSet.\nPrint ExSet_ind.\n\nInductive list (X:Type) : Type :=\n        | nil : list X\n        | cons : X -> list X -> list X.\nPrint list_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(*\n\nmytype_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 *)\nInductive mytype ( X : Type ) : Type :=\n| constr1 : X -> mytype X\n| constr2 : nat -> mytype X\n| constr3 : mytype X -> nat -> mytype X.\nPrint mytype_ind.\n\n(*\nmytype_ind = \nfun (X : Type) (P : mytype X -> Prop) => mytype_rect X P\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 -> forall n : nat, P (constr3 X m n)) ->\n       forall m : mytype X, P m\n *)\n\n(*\n\n foo_ind :\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   *)\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. \nPrint foo_ind.\n\n(*\nfoo_ind = \nfun (X Y : Type) (P : foo X Y -> Prop) => foo_rect X Y P\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 (quxx X Y f1)) ->\n       forall f2 : foo X Y, P f2\n\nArgument scopes are [type_scope type_scope _ _ _ _ _]\n\n *)\n\nInductive foo' (X:Type) : Type :=\n  | C1 : list X -> foo' X -> foo' X\n  | C2 : foo' X.\n\nPrint foo'_ind.\n\nLemma pred_of_positive : forall n, 1 <= n -> exists p : nat , n = S p.\nProof.\n  intros n H. induction n. inversion H.\n  exists n. reflexivity.\nQed.\n\nDefinition pred_spec (n:nat) :=\n  { m : nat | n = 0 /\\ m = 0 \\/ n = S m }.\n\nDefinition predecessor : forall n : nat , pred_spec n.\n  intros n. induction n.\n  unfold pred_spec. exists 0. left. split. reflexivity. reflexivity.\n  unfold pred_spec. exists n. right. reflexivity.\nDefined.\n\nCheck { m : nat | 2 = S 1 }.\n\nExtraction pred_spec.\nExtraction predecessor.\n\nInductive prop : Prop :=\n  prop_intro : Prop -> prop.\nCheck ( prop_intro prop ).\n\nTheorem le_reverse_rules :\n  forall n m : nat, n <= m -> n = m \\/ exists p, n <= p /\\ m = S p.\nProof.\n  intros n m H. inversion H. left. reflexivity.\n  right. exists m0. split. assumption. reflexivity.\nQed.\n", "meta": {"author": "tabtab777", "repo": "Coq", "sha": "4ffc37f0c970349ef1942a1519b729c6e5cba581", "save_path": "github-repos/coq/tabtab777-Coq", "path": "github-repos/coq/tabtab777-Coq/Coq-4ffc37f0c970349ef1942a1519b729c6e5cba581/MoreInd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.8577681086260461, "lm_q1q2_score": 0.6972516578968979}}
{"text": "Require Export P09.\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_end. reflexivity.\n  - simpl. rewrite -> snoc_append. rewrite -> snoc_append. rewrite -> IHl1. rewrite <- app_assoc. reflexivity.\nQed.\n\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/02/P10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.6972516549413591}}
{"text": "Welcome to Coq 8.4pl4 (November 2015)\n\nCoq < Definition doit3times {X:Type} (f:X -> X) (n:X) : X := f (f (f n)).\ndoit3times is defined\n\nCoq < Check @doit3times.\ndoit3times\n     : forall X : Type, (X -> X) -> X -> X\n\nCoq < Definition minustwo (n : nat) : nat := match n with | O => O | S O => O | S (S n') => n' end.\nminustwo is defined\n\nCoq < Example test_doit3times: doit3times minustwo 9 = 3.\n1 subgoal\n  \n  ============================\n   doit3times minustwo 9 = 3\n\ntest_doit3times < reflexivity.\nNo more subgoals.\n\ntest_doit3times < Qed.\nreflexivity.\n\ntest_doit3times is defined\n\nCoq < Example test_doit3times'': doit3times minustwo 9 = 3.\n1 subgoal\n  \n  ============================\n   doit3times minustwo 9 = 3\n\ntest_doit3times'' < info_auto.\n(* info auto : *)\n apply @eq_refl.\nNo more subgoals.\n\ntest_doit3times'' < Qed.\ninfo_auto.\n\ntest_doit3times'' is defined\n\nCoq < Definition negb (b:bool) : bool := match b with | true => false | false => true end.\nnegb is defined\n\nCoq < Example test_doit3times': doit3times negb true = false.\n1 subgoal\n  \n  ============================\n   doit3times negb true = false\n\ntest_doit3times' < Proof.\n1 subgoal\n  \n  ============================\n   doit3times negb true = false\n\ntest_doit3times' < reflexivity.\nNo more subgoals.\n\ntest_doit3times' < Qed.\nreflexivity.\n\ntest_doit3times' is defined\n\nCoq < Notation \"x :: l\" := (cons l) (at level 60, right associativity).\nError: x is unbound in the right-hand side.\n\nCoq < Notation \"x :: l\" := (cons x l) (at level 60, right associativity).\n\nCoq < Notation \"[ ]\" := nil.\nSetting notation at level 0.\n\nCoq < Notation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\nSetting notation at level 0.\n\nCoq < Fixpoint filter {X:Type} (test: X -> bool) (l:list X) : (list X) := match l with | [] => [] | h :: t => if test h then h :: (filter test t) else filter test t end.\nfilter is recursively defined (decreasing on 3rd argument)\n\nCoq < Fixpoint evenb (n:nat) : bool := match n with | O => true | S O => false | S (S n') => evenb n' end.\nevenb is recursively defined (decreasing on 1st argument)\n\nCoq < Example test_filter1: filter evenb [1;2;3;4] = [2;4].\n1 subgoal\n  \n  ============================\n   filter evenb [1; 2; 3; 4] = [2; 4]\n\ntest_filter1 < Proof.\n1 subgoal\n  \n  ============================\n   filter evenb [1; 2; 3; 4] = [2; 4]\n\ntest_filter1 < reflexivity.\nNo more subgoals.\n\ntest_filter1 < Qed.\nreflexivity.\n\ntest_filter1 is defined\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 recursively defined (decreasing on 1st argument)\n\nCoq < Definition length_is_1 {X : Type} (l : list X) : bool := beq_nat (length l) 1.\nlength_is_1 is defined\n\nCoq < Example test_filter2: filter length_is_1 [ [1;2]; [3]; [4]; [5;6;7]; []; [8] ] = [ [3]; [4]; [8] ].\n1 subgoal\n  \n  ============================\n   filter length_is_1 [[1; 2]; [3]; [4]; [5; 6; 7]; []; [8]] =\n   [[3]; [4]; [8]]\n\ntest_filter2 < Proof.\n1 subgoal\n  \n  ============================\n   filter length_is_1 [[1; 2]; [3]; [4]; [5; 6; 7]; []; [8]] =\n   [[3]; [4]; [8]]\n\ntest_filter2 < reflexivity.\nNo more subgoals.\n\ntest_filter2 < Qed.\nreflexivity.\n\ntest_filter2 is defined\n\nCoq < Definition oddb (n:nat) : bool := negb (evenb n).\noddb is defined\n\nCoq < Definition countoddmembers' (l:list nat) : nat := length (filter oddb l).\ncountoddmembers' is defined\n\nCoq < Example test_countoddmembers'1: countoddmembers' [1;0;3;1;4;5] = 4.\n1 subgoal\n  \n  ============================\n   countoddmembers' [1; 0; 3; 1; 4; 5] = 4\n\ntest_countoddmembers'1 < Proof.\n1 subgoal\n  \n  ============================\n   countoddmembers' [1; 0; 3; 1; 4; 5] = 4\n\ntest_countoddmembers'1 < reflexivity.\nNo more subgoals.\n\ntest_countoddmembers'1 < Qed.\nreflexivity.\n\ntest_countoddmembers'1 is defined\n\nCoq < Example test_countoddmembers'2: countoddmembers' [0;2;4] = 0.\n1 subgoal\n  \n  ============================\n   countoddmembers' [0; 2; 4] = 0\n\ntest_countoddmembers'2 < Proof.\n1 subgoal\n  \n  ============================\n   countoddmembers' [0; 2; 4] = 0\n\ntest_countoddmembers'2 < reflexivity.\nNo more subgoals.\n\ntest_countoddmembers'2 < Qed.\nreflexivity.\n\ntest_countoddmembers'2 is defined\n\nCoq < Example test_countoddmembers'3: countoddmembers' nil = 0.\n1 subgoal\n  \n  ============================\n   countoddmembers' [] = 0\n\ntest_countoddmembers'3 < Proof.\n1 subgoal\n  \n  ============================\n   countoddmembers' [] = 0\n\ntest_countoddmembers'3 < reflexivity.\nNo more subgoals.\n\ntest_countoddmembers'3 < Qed.\nreflexivity.\n\ntest_countoddmembers'3 is defined\n\nCoq < Example test_anon_fun': doit3times (fun n => n * n) 2 = 256.\n1 subgoal\n  \n  ============================\n   doit3times (fun n : nat => n * n) 2 = 256\n\ntest_anon_fun' < Proof.\n1 subgoal\n  \n  ============================\n   doit3times (fun n : nat => n * n) 2 = 256\n\ntest_anon_fun' < reflexivity.\nNo more subgoals.\n\ntest_anon_fun' < Qed.\nreflexivity.\n\ntest_anon_fun' is defined\n\nCoq < Example test_filter2': filter (fun l => beq_nat (length l) 1) [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ] = [ [3]; [4]; [8] ].\n1 subgoal\n  \n  ============================\n   filter (fun l : list nat => beq_nat (length l) 1)\n     [[1; 2]; [3]; [4]; [5; 6; 7]; []; [8]] = [[3]; [4]; [8]]\n\ntest_filter2' < Proof.\n1 subgoal\n  \n  ============================\n   filter (fun l : list nat => beq_nat (length l) 1)\n     [[1; 2]; [3]; [4]; [5; 6; 7]; []; [8]] = [[3]; [4]; [8]]\n\ntest_filter2' < reflexivity.\nNo more subgoals.\n\ntest_filter2' < Qed.\nreflexivity.\n\ntest_filter2' 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/poly/poly008.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541611, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.697251650041538}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. You may distribute   *)\n(* under the terms of either the CeCILL-B License or the CeCILL        *)\n(* version 2 License, as specified in the README file.                 *)\nRequire Import ssreflect.\nRequire Import ssrfun.\nRequire Export Bool.\n\n(*****************************************************************************)\n(* A theory of boolean predicates and operators. A large part of this file   *)\n(* is concerned with boolean reflection. Definitions and notations:          *)\n(*                                                                           *)\n(* a && b                  == boolean conjection                             *)\n(* a || b                  == boolean disjunction                            *)\n(* a ==> b                 == boolean implication                            *)\n(* ~~ a                    == boolean negation                               *)\n(* a (+) b                 == boolean xor                                    *)\n(* is_true                 == coercion bool >-> Prop                         *)\n(* reflect                 == the reflection inductive predicate             *)\n(* iffP,...                == user-oriented reflection lemmas                *)\n(* elimT                   == coercion reflect >-> Funclass, to apply        *)\n(*                            reflection lemmas to boolean assertions        *)\n(* [ /\\ P1 , P2 & P3 ]     == iterated logical conjonction, up to 5          *)\n(* [ \\/ P1 , P2 & P3 ]     == iterated logical disjonction, up to 4          *)\n(* [&& a, b, c & d]        == iterated, right associated boolean conjunction *)\n(*                            with arbitrary arity                           *)\n(* [|| a, b, c | d]        == iterated, right associated boolean disjunction *)\n(*                            with arbitrary arity                           *)\n(* [==> a, b, c => d]      == iterated, right associated boolean             *)\n(*                            implication with arbitrary arity               *)\n(* and3P,...               == specific reflection lemmas for iterated        *)\n(*                            connectives                                    *)\n(* andTb, orbAC,...        == systematic names for boolean connective        *)\n(*                            properties                                     *)\n(* prop_congr              == a tactic to move a boolean equality from       *)\n(*                            its coerced form in Prop to the equality       *)\n(*                            in bool                                        *)\n(* bool_congr              == resolution tactic for blindly weeding out      *)\n(*                            like terms from boolean equalities (can fail)  *)\n(*                                                                           *)\n(* This file provides a theory of boolean predicates and relations :         *)\n(*   pred T                == T -> bool                                      *)\n(*   simpl_pred T          == type of simplifying (see ssrfun) predicates    *)\n(*   rel T                 == T -> pred T == T -> T -> bool                  *)\n(*   simpl_rel T           == type of simplifying relations                  *)\n(*   predType              == generic predicate interface,                   *)\n(*                             implemented for lists, sets                   *)\n(* If P is a predicate the proposition \"x satisfies P\" can be written        *)\n(* applicatively as (P x), or using an explicit connective as (x \\in P); in  *)\n(* the latter case we say that P is a \"collective\" predicate. We use A, B    *)\n(* rather than P, Q for collective predicates:                               *)\n(*   x \\in A               == x satisfies the (collective) predicate A       *)\n(*   x \\notin A            == x doesn't satisfy the (collective) predicate A *)\n(* The pred T type can be used as a generic predicate type for either kind,  *)\n(* but the two kinds of predicates should not be mixed. Explicit values of   *)\n(* pred T (i.e., lamdba terms) should always be used applicatively, while    *)\n(* values of collection types implementing the predType interface, such as   *)\n(* lists or sets should always be used as collective predicates; simpl_pred  *)\n(* predicates are the only type that can be used either way (however, the    *)\n(* x \\in A notation will not simplify). We provide the following conversions *)\n(*   SimplPred P           == a (simplifying) applicative equivalent of P    *)\n(*   mem A                 == an applicative equivalent of A:                *)\n(*                            mem A x simplifies to x \\in A                  *)\n(* Alternatively one can use the syntax for explicit simplifying predicates  *)\n(* and relations:                                                            *)\n(*                                                                           *)\n(* [pred x | E]            == simplifying (see ssrfun) predicate x => E      *)\n(* [pred x : T| E]         == predicate x => T, with a cast on the argument  *)\n(* [pred : T | E]          == constant predicate E on type T                 *)\n(* [pred x \\in A]          == [pred x | x \\in A]                             *)\n(* [pred x \\in A | E]      == [pred x | (x \\in A) && E]                      *)\n(*                                                                           *)\n(* [predU A & B]           == union of two collective predicates             *)\n(* [predI A & B]           == intersection of collective predicates          *)\n(* [predD A & B]           == difference of collective predicates            *)\n(* [predC A]               == complement of a collective predicate           *)\n(* [preim f of A]          == preimage by f of the collective predicate A    *)\n(* predU P Q, ...          == union, etc of applicative predicates           *)\n(* pred0                   == the empty predicate                            *)\n(* predT                   == the total (always true) predicate              *)\n(*                            if T : predArgType, then T coerces to predT    *)\n(* {:T}                    == T cast to predArgType (e.g., {:bool * nat})    *)\n(*                                                                           *)\n(* [rel x y | E]           == simplifying relation                           *)\n(* [rel x y : T | E]       == relation, with a cast on the arguments         *)\n(* [rel x y \\in A & B | E] == [rel x y | [&& x \\in A, y \\in B & E]]          *)\n(* [rel x y \\in A & B]     == [rel x y | (x \\in A) && (y \\in B)]             *)\n(* [rel x y \\in A | E]     == [rel x y \\in A & A | E]                        *)\n(* [rel x y \\in A]         == [rel x y \\in A & A]                            *)\n(* relU R S                == union of relations R and S                     *)\n(*                                                                           *)\n(* Some properties of predicates and relations:                              *)\n(* A =i B                  == A and B are extensionally equivalent           *)\n(* {subset A <= B}         == A is a (collective) subpredicate of B          *)\n(* subpred P Q             == P is an (applicative) subpredicate or Q        *)\n(* subrel R S              == R is a subrelation of S                        *)\n(*                                                                           *)\n(* reflexive R             == R (in rel T) is reflexive                      *)\n(* irreflexive R           == R (in rel T) is irreflexive                    *)\n(* symmetric R             == R (in rel T) is symmetric (equational)         *)\n(* pre_symmetric R         == R (in rel T) is symmetric (implication)        *)\n(* antisymmetric R         == R (in rel T) is antisymmetric                  *)\n(* total R                 == R (in rel T) is total                          *)\n(* transitive R            == R (in rel T) is transitive                     *)\n(* left_transitive R       == R is a congruence on the left hand side of R   *)\n(* right_transitive R      == R is a congruence on the right hand side of R  *)\n(*                                                                           *)\n(* Localization of (Prop) predicates; if P1 is convertible to forall x, Qx,  *)\n(* P2 to forall x y, Qxy and P3 to forall x y z, Qxyz :                      *)\n(*                                                                           *)\n(* {in d , P1}            == forall x, x \\in d -> Qx                         *)\n(* {in d1 & d2 , P2}      == forall x y, x \\in d1 -> y \\in d2 -> Qxy         *)\n(* {in d & , P2}          == forall x y, x \\in d -> y \\in d -> Qxy           *)\n(* {in d1 & d2 &, Q3}     == forall x y z,                                   *)\n(*                            x \\in d1 -> y \\in d2 -> z \\in d2 -> Qxyz       *)\n(*                            + Variants                                     *)\n(* {in d, bijective f}    == f has a right inverse in d                      *)\n(* {on cd, P1}            == forall x, (f x) \\in cd -> Qx                    *)\n(*                            when P1 is also convertible to Pf f            *)\n(* {on cd &, P2}          == forall x y, f x \\in cd -> f y \\in cd -> Qxy     *)\n(*                            when P2 is also convertible to Pf f            *)\n(* {on cd, P1' & g}       == forall x, (f x) \\in cd -> Qx                    *)\n(*                            when P1' is convertible to Pf f and P1' g is   *)\n(*                            convertible to forall x, Qx                    *)\n(* {on cd, bijective f}    == f has a right inverse on cd                    *)\n(*                                                                           *)\n(* This file introduces the following suffix policy for lemma names:         *)\n(* A : associativity                                                         *)\n(* C : commutativity or set complement                                       *)\n(* D : set difference                                                        *)\n(* E : elimination                                                           *)\n(* F : boolean false                                                         *)\n(* I : set intersection                                                      *)\n(* K : cancellation                                                          *)\n(* N : boolean negation                                                      *)\n(* T : boolean truth                                                         *)\n(* U : set union                                                             *)\n(* W : weakening                                                             *)\n(*****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nReserved Notation \"~~ b\" (at level 35, right associativity).\nReserved Notation \"b ==> c\" (at level 55, right associativity).\nReserved Notation \"b1  (+)  b2\" (at level 50, left associativity).\nReserved Notation \"x \\in A\" (at level 70, no associativity).\nReserved Notation \"x \\notin A\" (at level 70, no associativity).\nReserved Notation \"p1 =i p2\" (at level 70, no associativity).\n\n(* We introduce a number of n-ary \"list-style\" notations, which share a *)\n(* common format, namely                                                *)\n(*    [op arg1, arg2, ... last_separator last_arg]                      *)\n(* This usually denotes a right-associative applications of op, e.g.,   *)\n(*  [&& a, b, c & d] denotes a && (b && (c && d))                       *)\n(* The last_separator must be a non-operator token; here we use &, | or *)\n(* => (our default is &, but we try to match the intended meaning of    *)\n(* op). The separator is a workaround for limitations of the parsing    *)\n(* engine; for similar reasons the separator cannot be omitted even     *)\n(* when last_arg can. The Notation declarations are complicated by the  *)\n(* separate treatments for fixed arities (binary for bool operators,    *)\n(* and all arities for Prop operators).                                 *)\n(*   We also use the square brackets in comprehension-style notations   *)\n(* of the form                                                          *)\n(*    [type var separator expr]                                         *)\n(* where \"type\" is the type of the comprehension (e.g., pred) and       *)\n(* separator is | or => . It is important that in other notations a      *)\n(* leading square bracket [ is always by an operator symbol or at least *)\n(* a fixed identifier.                                                  *)\n\nReserved Notation \"[ /\\ P1 & P2 ]\" (at level 0, only parsing).\nReserved Notation \"[ /\\ P1 , P2 & P3 ]\" (at level 0, format\n  \"'[hv' [ /\\ '['  P1 , '/'  P2 ']' '/ '  &  P3 ] ']'\").\nReserved Notation \"[ /\\ P1 , P2 , P3 & P4 ]\" (at level 0, format\n  \"'[hv' [ /\\ '['  P1 , '/'  P2 , '/'  P3 ']' '/ '  &  P4 ] ']'\").\nReserved Notation \"[ /\\ P1 , P2 , P3 , P4 & P5 ]\" (at level 0, format\n  \"'[hv' [ /\\ '['  P1 , '/'  P2 , '/'  P3 , '/'  P4 ']' '/ '  &  P5 ] ']'\").\n\nReserved Notation \"[ \\/ P1 | P2 ]\" (at level 0, only parsing).\nReserved Notation \"[ \\/ P1 , P2 | P3 ]\" (at level 0, format\n  \"'[hv' [ \\/ '['  P1 , '/'  P2 ']' '/ '  |  P3 ] ']'\").\nReserved Notation \"[ \\/ P1 , P2 , P3 | P4 ]\" (at level 0, format\n  \"'[hv' [ \\/ '['  P1 , '/'  P2 , '/'  P3 ']' '/ '  |  P4 ] ']'\").\n\nReserved Notation \"[ && b1 & c ]\" (at level 0, only parsing).\nReserved Notation \"[ && b1 , b2 , .. , bn & c ]\" (at level 0, format\n  \"'[hv' [ && '['  b1 , '/'  b2 , '/'  .. , '/'  bn ']' '/ '  &  c ] ']'\").\n\nReserved Notation \"[ || b1 | c ]\" (at level 0, only parsing).\nReserved Notation \"[ || b1 , b2 , .. , bn | c ]\" (at level 0, format\n  \"'[hv' [ || '['  b1 , '/'  b2 , '/'  .. , '/'  bn ']' '/ '  |  c ] ']'\").\n\nReserved Notation \"[ ==> b1 => c ]\" (at level 0, only parsing).\nReserved Notation \"[ ==> b1 , b2 , .. , bn => c ]\" (at level 0, format\n  \"'[hv' [ ==> '['  b1 , '/'  b2 , '/'  .. , '/'  bn ']' '/'  =>  c ] ']'\").\n\nReserved Notation \"[ 'pred' : T => E ]\" (at level 0, format\n\n  \"'[hv' [ 'pred' :  T  => '/ '  E ] ']'\").\nReserved Notation \"[ 'pred' x => E ]\" (at level 0, x at level 8, format\n  \"'[hv' [ 'pred'  x  => '/ '  E ] ']'\").\nReserved Notation \"[ 'pred' x : T => E ]\" (at level 0, x at level 8, format\n  \"'[hv' [ 'pred'  x  :  T  => '/ '  E ] ']'\").\n\nReserved Notation \"[ 'rel' x y => E ]\" (at level 0, x, y at level 8, format\n  \"'[hv' [ 'rel'  x   y  => '/ '  E ] ']'\").\nReserved Notation \"[ 'rel' x y : T => E ]\" (at level 0, x, y at level 8, format\n  \"'[hv' [ 'rel'  x  y :  T  => '/ '  E ] ']'\").\n\n(* Shorter delimiter *)\n\nDelimit Scope bool_scope with B.\n\n(* The Coq library forgets to set argument scopes on bool ops. *)\n\nArguments Scope negb [bool_scope].\nArguments Scope orb [bool_scope bool_scope].\nArguments Scope xorb [bool_scope bool_scope].\nArguments Scope andb [bool_scope bool_scope].\nArguments Scope implb [bool_scope bool_scope].\nArguments Scope eqb [bool_scope bool_scope].\nArguments Scope leb [bool_scope bool_scope].\nArguments Scope ifb [bool_scope bool_scope bool_scope].\n\n(* An alternative to xorb that behaves somewhat better wrt simplification. *)\n\nDefinition addb b := if b then negb else fun b' => b'.\n\n(* Bool operator notation; we need to redeclare && and || so they get the *)\n(* correct argument scopes.                                               *)\n\nNotation \"~~ b\" := (negb b) : bool_scope.\n(* Redundant for now; may be added if dependency on Bool is removed\nNotation \"b1 && b2\" := (andb b1 b2) : bool_scope.\nNotation \"b1 || b2\" := (orb b1 b2) : bool_scope.\n*)\nNotation \"b ==> c\" := (implb b c) : bool_scope.\nNotation \"b1 (+) b2\" := (addb b1 b2) : bool_scope.\n\n(* Coercion bool >-> Prop.                    *)\n\nCoercion is_true b := b = true.\n\n(*\nLtac fold_prop := match goal with |- (?b = true) => change (is_true b) end.\n*)\nLemma prop_congr : forall b b' : bool, b = b' -> b = b' :> Prop.\nProof. by move=> b b' ->. Qed.\n\nLtac prop_congr := apply: prop_congr.\n\n(* Lemmas for auto. *)\nLemma is_true_true : true.               Proof. by []. Qed.\nLemma not_false_is_true : ~ false.       Proof. by []. Qed.\nLemma is_true_locked_true : locked true. Proof. by unlock. Qed.\nHint Resolve is_true_true not_false_is_true is_true_locked_true.\n\n(* Negation lemmas. *)\n\n(* Note: in the general we take NEGATION as the standard form of a *)\n(* false condition : hypotheses should be of the form ~~ b rather  *)\n(* than b = false or ~ b, as much as possible.                     *)\n\nLemma negbT : forall b, b = false -> ~~ b.        Proof. by case. Qed.\nLemma negbTE : forall b, ~~ b -> b = false.       Proof. by case. Qed.\nLemma negbF : forall b : bool, b -> ~~ b = false. Proof. by case. Qed.\nLemma negbFE : forall b, ~~ b = false -> b.       Proof. by case. Qed.\nLemma negbK : involutive negb.                    Proof. by case. Qed.\nLemma negbNE : forall b, ~~ ~~ b -> b.            Proof. by case. Qed.\n\nLemma negb_inj : injective negb. Proof. exact: can_inj negbK. Qed.\n\nLemma negbLR : forall b c, b = ~~ c -> ~~ b = c.\nProof. by move=> ? [] ->. Qed.\n\nLemma negbRL : forall b c, ~~ b = c -> b = ~~ c.\nProof. by move=> [] ? <-. Qed.\n\nLemma contra : forall c b : bool, (c -> b) -> ~~ b -> ~~ c.\nProof. by case=> // ? ->. Qed.\n\n(* Coercion of sum-style datatypes into bool, which makes it possible *)\n(* to use ssr's boolean if rather than Coq's \"generic\" if.            *)\n\nCoercion isSome T (u : option T) := if u is Some _ then true else false.\n\nCoercion is_inl A B (u : A + B) := if u is inl _ then true else false.\n\nCoercion is_left A B (u : {A} + {B}) := if u is left _ then true else false.\n\nCoercion is_inleft A B (u : A + {B}) := if u is inleft _ then true else false.\n\nPrenex Implicits  isSome is_inl is_left is_inleft.\n\n(* Lemmas for ifs with large conditions, which allow reasoning about the  *)\n(* condition without repeating it inside the proof (the latter IS         *)\n(* preferable when the condition is short).                               *)\n(* Usage :                                                                *)\n(*   if the goal contains (if cond then ...) = ...                        *)\n(*     case: ifP => Hcond.                                                *)\n(*   generates two subgoal, with the assumption Hcond : cond = true/false *)\n(*     Rewrite if_same  eliminates redundant ifs                          *)\n(*     Rewrite (fun_if f) moves a function f inside an if                 *)\n(*     Rewrite if_arg moves an argument inside a function-valued if       *)\n\nSection BoolIf.\n\nVariables (A B : Type) (x : A) (f : A -> B) (b : bool) (vT vF : A).\n\nCoInductive if_spec : A -> bool -> Set :=\n  | IfSpecTrue  of b         : if_spec vT true\n  | IfSpecFalse of b = false : if_spec vF false.\n\nLemma ifP : if_spec (if b then vT else vF) b.\nProof. by case Db: b; constructor. 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 : forall 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\n(* Patch for a bug in ssreflect 8.1 that corrupts patterns where a *)\n(* wildcard appears under a match. Usage:                          *)\n(*   rewrite -ifE; set x := if_expr _ _ _.                         *)\n\nDefinition if_expr := if b then vT else vF.\nLemma ifE : (if b then vT else vF) = if_expr. Proof. by []. Qed.\n\nEnd BoolIf.\n\n(* The reflection predicate.                                          *)\n\nInductive reflect (P : Prop) : bool -> Set :=\n  | ReflectT  of   P : reflect P true\n  | ReflectF of ~ P : reflect P false.\n\n(* Core (internal) reflection lemmas, used for the three kinds of views. *)\n\nSection ReflectCore.\n\nVariables (P Q : Prop) (b c : bool).\n\nHypothesis Hb : reflect P b.\n\nLemma introNTF : (if c then ~ P else P) -> ~~ b = c.\nProof. by case c; case Hb. Qed.\n\nLemma introTF : (if c then P else ~ P) -> b = c.\nProof. by case c; case Hb. Qed.\n\nLemma elimNTF : ~~ b = c -> if c then ~ P else P.\nProof. by move <-; case Hb. Qed.\n\nLemma elimTF : b = c -> if c then P else ~ P.\nProof. by move <-; case Hb. Qed.\n\nLemma equivPif : (Q -> P) -> (P -> Q) -> if b then Q else ~ Q.\nProof. by case Hb; auto. Qed.\n\nLemma xorPif : Q \\/ P -> ~ (Q /\\ P) -> if b then ~ Q else Q.\nProof. by case Hb => [? _ H ? | ? H _]; case: H. Qed.\n\nEnd ReflectCore.\n\n(* Internal negated reflection lemmas *)\nSection ReflectNegCore.\n\nVariables (P Q : Prop) (b c : bool).\nHypothesis Hb : reflect P (~~ b).\n\nLemma introTFn : (if c then ~ P else P) -> b = c.\nProof. by move/(introNTF Hb) <-; case b. Qed.\n\nLemma elimTFn : b = c -> if c then ~ P else P.\nProof. by move <-; apply: (elimNTF Hb); case b. Qed.\n\nLemma equivPifn : (Q -> P) -> (P -> Q) -> if b then ~ Q else Q.\nProof. rewrite -if_neg; exact: equivPif. Qed.\n\nLemma xorPifn : Q \\/ P -> ~ (Q /\\ P) -> if b then Q else ~ Q.\nProof. rewrite -if_neg; exact: xorPif. Qed.\n\nEnd ReflectNegCore.\n\n(* User-oriented reflection lemmas *)\nSection Reflect.\n\nVariables (P Q : Prop) (b b' c : bool).\nHypotheses (Pb : reflect P b) (Pb' : reflect P (~~ b')).\n\nLemma introT  : P -> b.            Proof. exact: introTF true _. Qed.\nLemma introF  : ~ P -> b = false.  Proof. exact: introTF false _. Qed.\nLemma introN  : ~ P -> ~~ b.       Proof. exact: introNTF true _. Qed.\nLemma introNf : P -> ~~ b = false. Proof. exact: introNTF false _. Qed.\nLemma introTn : ~ P -> b'.         Proof. exact: introTFn true _. Qed.\nLemma introFn : P -> b' = false.   Proof. exact: introTFn false _. Qed.\n\nLemma elimT  : b -> P.             Proof. exact: elimTF true _. Qed.\nLemma elimF  : b = false -> ~ P.   Proof. exact: elimTF false _. Qed.\nLemma elimN  : ~~ b -> ~P.         Proof. exact: elimNTF true _. Qed.\nLemma elimNf : ~~ b = false -> P.  Proof. exact: elimNTF false _. Qed.\nLemma elimTn : b' -> ~ P.          Proof. exact: elimTFn true _. Qed.\nLemma elimFn : b' = false -> P.    Proof. exact: elimTFn false _. Qed.\n\nLemma introP : (b -> Q) -> (~~ b -> ~ Q) -> reflect Q b.\nProof. by case b; constructor; auto. Qed.\n\nLemma iffP : (P -> Q) -> (Q -> P) -> reflect Q b.\nProof. by case: Pb; constructor; auto. Qed.\n\nLemma appP : reflect Q b -> P -> Q.\nProof. by move=> Qb; move/introT; case: Qb. Qed.\n\nLemma sameP : reflect P c -> b = c.\nProof. case; [exact: introT | exact: introF]. Qed.\n\nLemma decPcases : if b then P else ~ P. Proof. by case Pb. Qed.\n\nDefinition decP : {P} + {~ P}. by case: b decPcases; [left | right]. Defined.\n\nEnd Reflect.\n\nHint View for move/ elimTF|3 elimNTF|3 elimTFn|3 introT|2 introTn|2 introN|2.\n\nHint View for apply/ introTF|3 introNTF|3 introTFn|3 elimT|2 elimTn|2 elimN|2.\n\nHint View for apply// equivPif|3 xorPif|3 equivPifn|3 xorPifn|3.\n\n(* Allow the direct application of a reflection lemma to a boolean assertion.  *)\nCoercion elimT : reflect >-> Funclass.\n\n(* List notations for wider connectives; the Prop connectives have a fixed  *)\n(* width so as to avoid iterated destruction (we go up to width 5 for /\\,   *)\n(* and width 4 for or. The bool connectives have arbitrary widths, but      *)\n(* denote expressions that associate to the RIGHT. This is consistent with  *)\n(* the right associativity of list expressions, and thus more convenient in *)\n(* many proofs.                                                             *)\n\nInductive and3 (P1 P2 P3 : Prop) : Prop := And3 of P1 & P2 & P3.\n\nInductive and4 (P1 P2 P3 P4 : Prop) : Prop := And4 of P1 & P2 & P3 & P4.\n\nInductive and5 (P1 P2 P3 P4 P5 : Prop) : Prop :=\n  And5 of P1 & P2 & P3 & P4 & P5.\n\nInductive or3 (P1 P2 P3 : Prop) : Prop := Or31 of P1 | Or32 of P2 | Or33 of P3.\n\nInductive or4 (P1 P2 P3 P4 : Prop) : Prop :=\n  Or41 of P1 | Or42 of P2 | Or43 of P3 | Or44 of P4.\n\nNotation \"[ /\\ P1 & P2 ]\" := (and P1 P2) (only parsing) : type_scope.\nNotation \"[ /\\ P1 , P2 & P3 ]\" := (and3 P1 P2 P3) : type_scope.\nNotation \"[ /\\ P1 , P2 , P3 & P4 ]\" := (and4 P1 P2 P3 P4) : type_scope.\nNotation \"[ /\\ P1 , P2 , P3 , P4 & P5 ]\" := (and5 P1 P2 P3 P4 P5) : type_scope.\n\nNotation \"[ \\/ P1 | P2 ]\" := (or P1 P2) (only parsing) : type_scope.\nNotation \"[ \\/ P1 , P2 | P3 ]\" := (or3 P1 P2 P3) : type_scope.\nNotation \"[ \\/ P1 , P2 , P3 | P4 ]\" := (or4 P1 P2 P3 P4) : type_scope.\n\nNotation \"[ && b1 & c ]\" := (b1 && c) (only parsing) : bool_scope.\nNotation \"[ && b1 , b2 , .. , bn & c ]\" := (b1 && (b2 && .. (bn && c) .. ))\n  : bool_scope.\n\nNotation \"[ || b1 | c ]\" := (b1 || c) (only parsing) : bool_scope.\nNotation \"[ || b1 , b2 , .. , bn | c ]\" := (b1 || (b2 || .. (bn || c) .. ))\n  : bool_scope.\n\nNotation \"[ ==> b1 , b2 , .. , bn => c ]\" :=\n   (b1 ==> (b2 ==> .. (bn ==> c) .. )) : bool_scope.\nNotation \"[ ==> b1 => c ]\" := (b1 ==> c) (only parsing) : bool_scope.\n\nSection ReflectConnectives.\n\nVariable b1 b2 b3 b4 b5 : bool.\n\nLemma idP : reflect b1 b1.\nProof. by case b1; constructor. Qed.\n\nLemma idPn : reflect (~~ b1) (~~ b1).\nProof. by case b1; constructor. Qed.\n\nLemma negP : reflect (~ b1) (~~ b1).\nProof. by case b1; constructor; auto. Qed.\n\nLemma negPn : reflect b1 (~~ ~~ b1).\nProof. by case b1; constructor. Qed.\n\nLemma negPf : reflect (b1 = false) (~~ b1).\nProof. by case b1; constructor. Qed.\n\nLemma andP : reflect (b1 /\\ b2) (b1 && b2).\nProof. by case b1; case b2; constructor=> //; case. Qed.\n\nLemma and3P : reflect [/\\ b1, b2 & b3] [&& b1, b2 & b3].\nProof. by case b1; case b2; case b3; constructor; try by case. Qed.\n\nLemma and4P : reflect [/\\ b1, b2, b3 & b4] [&& b1, b2, b3 & b4].\nProof.\nby case b1; case b2; case b3; case b4; constructor; try by case. Qed.\n\nLemma and5P : reflect [/\\ b1, b2, b3, b4 & b5] [&& b1, b2, b3, b4 & b5].\nProof.\nby case b1; case b2; case b3; case b4; case b5; constructor; try by case.\nQed.\n\nLemma orP : reflect (b1 \\/ b2) (b1 || b2).\nProof. by case b1; case b2; constructor; auto; case. Qed.\n\nLemma or3P : reflect [\\/ b1, b2 | b3] [|| b1, b2 | b3].\nProof.\ncase b1; first by constructor; constructor 1.\ncase b2; first by constructor; constructor 2.\ncase b3; first by constructor; constructor 3.\nby constructor; case.\nQed.\n\nLemma or4P : reflect [\\/ b1, b2, b3 | b4] [|| b1, b2, b3 | b4].\nProof.\ncase b1; first by constructor; constructor 1.\ncase b2; first by constructor; constructor 2.\ncase b3; first by constructor; constructor 3.\ncase b4; first by constructor; constructor 4.\nby constructor; case.\nQed.\n\nLemma nandP : reflect (~~ b1 \\/ ~~ b2) (~~ (b1 && b2)).\nProof. by case b1; case b2; constructor; auto; case; auto. Qed.\n\nLemma norP : reflect (~~ b1 /\\ ~~ b2) (~~ (b1 || b2)).\nProof. by case b1; case b2; constructor; auto; case; auto. Qed.\n\nLemma implyP: reflect (b1 -> b2) (b1 ==> b2).\nProof. by case b1; case b2; constructor; auto. Qed.\n\nEnd ReflectConnectives.\n\nImplicit Arguments idP [b1].\nImplicit Arguments idPn [b1].\nImplicit Arguments negP [b1].\nImplicit Arguments negPn [b1].\nImplicit Arguments negPf [b1].\nImplicit Arguments andP [b1 b2].\nImplicit Arguments and3P [b1 b2 b3].\nImplicit Arguments and4P [b1 b2 b3 b4].\nImplicit Arguments and5P [b1 b2 b3 b4 b5].\nImplicit Arguments orP [b1 b2].\nImplicit Arguments or3P [b1 b2 b3].\nImplicit Arguments or4P [b1 b2 b3 b4].\nImplicit Arguments nandP [b1 b2].\nImplicit Arguments norP [b1 b2].\nImplicit Arguments implyP [b1 b2].\nPrenex Implicits idP idPn negP negPn negPf.\nPrenex Implicits andP and3P and4P and5P orP or3P or4P nandP norP implyP.\n\n(* Shorter, more systematic names for the boolean connectives laws.       *)\n\nLemma andTb : left_id true andb.     Proof. by []. Qed.\nLemma andFb : left_zero false andb.    Proof. by []. Qed.\nLemma andbT : right_id true andb.    Proof. by case. Qed.\nLemma andbF : right_zero false andb.   Proof. by case. Qed.\nLemma andbb : idempotent andb.         Proof. by case. Qed.\nLemma andbC : commutative andb.        Proof. by do 2!case. Qed.\nLemma andbA : associative andb.        Proof. by do 3!case. Qed.\nLemma andbCA : left_commutative andb.  Proof. by do 3!case. Qed.\nLemma andbAC : right_commutative andb. Proof. by do 3!case. Qed.\n\nLemma orTb : forall b, true || b.      Proof. by []. Qed.\nLemma orFb : left_id false orb.      Proof. by []. Qed.\nLemma orbT : forall b, b || true.      Proof. by case. Qed.\nLemma orbF : right_id false orb.     Proof. by case. Qed.\nLemma orbb : idempotent orb.           Proof. by case. Qed.\nLemma orbC : commutative orb.          Proof. by do 2!case. Qed.\nLemma orbA : associative orb.          Proof. by do 3!case. Qed.\nLemma orbCA : left_commutative orb.    Proof. by do 3!case. Qed.\nLemma orbAC : right_commutative orb.   Proof. by do 3!case. Qed.\n\nLemma andbN : forall b, b && ~~ b = false. Proof. by case. Qed.\nLemma andNb : forall b, ~~ b && b = false. Proof. by case. Qed.\nLemma orbN : forall b, b || ~~ b = true.   Proof. by case. Qed.\nLemma orNb : forall b, ~~ b || b = true.   Proof. by case. Qed.\n\nLemma andb_orl : left_distributive andb orb.  Proof. by do 3!case. Qed.\nLemma andb_orr : right_distributive andb orb. Proof. by do 3!case. Qed.\nLemma orb_andl : left_distributive orb andb.  Proof. by do 3!case. Qed.\nLemma orb_andr : right_distributive orb andb. Proof. by do 3!case. Qed.\n\nLemma negb_and : forall b1 b2, ~~ (b1 && b2) = ~~ b1 || ~~ b2.\nProof. by do 2!case. Qed.\n\nLemma negb_or : forall b1 b2, ~~ (b1 || b2) = ~~ b1 && ~~ b2.\nProof. by do 2!case. Qed.\n\n(* Pseudo-cancellation -- i.e, absorbtion *)\n\nLemma andbK : forall b1 b2, b1 && b2 || b1 = b1.  Proof. by do 2!case. Qed.\nLemma andKb : forall b1 b2, b1 || b2 && b1 = b1.  Proof. by do 2!case. Qed.\nLemma orbK : forall b1 b2, (b1 || b2) && b1 = b1. Proof. by do 2!case. Qed.\nLemma orKb : forall b1 b2, b1 && (b2 || b1) = b1. Proof. by do 2!case. Qed.\n\n(* Imply *)\n\nLemma implybT : forall b, b ==> true.           Proof. by case. Qed.\nLemma implybF : forall b, (b ==> false) = ~~ b. Proof. by case. Qed.\nLemma implyFb : forall b, false ==> b.          Proof. by []. Qed.\nLemma implyTb : forall b, (true ==> b) = b.     Proof. by []. Qed.\n\nLemma negb_imply : forall b1 b2, ~~ (b1 ==> b2) = b1 && ~~ b2.\nProof. by do 2!case. Qed.\n\nLemma implybE : forall b1 b2, (b1 ==> b2) = ~~ b1 || b2.\nProof. by do 2!case. Qed.\n\nLemma implybN : forall b1 b2, (~~ b1 ==> ~~ b2) = b2 ==> b1.\nProof. by do 2!case. Qed.\n\n(* addition (xor) *)\n\nLemma addFb : left_id false addb.             Proof. by []. Qed.\nLemma addbF : right_id false addb.            Proof. by case. Qed.\nLemma addbb : self_inverse false addb.          Proof. by case. Qed.\nLemma addbC : commutative addb.                 Proof. by do 2!case. Qed.\nLemma addbA : associative addb.                 Proof. by do 3!case. Qed.\nLemma addbCA : left_commutative addb.           Proof. by do 3!case. Qed.\nLemma addbAC : right_commutative addb.          Proof. by do 3!case. Qed.\nLemma andb_addl : left_distributive andb addb.  Proof. by do 3!case. Qed.\nLemma andb_addr : right_distributive andb addb. Proof. by do 3!case. Qed.\nLemma addKb : forall b, involutive (addb b).    Proof. by do 2!case. Qed.\nLemma addbK : forall b, involutive (addb^~ b).  Proof. by do 2!case. Qed.\n\n\nLemma addTb : forall b, true (+) b = ~~ b. Proof. by []. Qed.\nLemma addbT : forall b, b (+) true = ~~ b. Proof. by case. Qed.\n\nLemma addbN : forall b1 b2, b1 (+) ~~ b2 = ~~ (b1 (+) b2).\nProof. by do 2!case. Qed.\nLemma addNb : forall b1 b2, ~~ b1 (+) b2 = ~~ (b1 (+) b2).\nProof. by do 2!case. Qed.\n\nLemma addbP : forall b1 b2, b1 (+) b2 -> ~~ b1 = b2.\nProof. by do 2!case. Qed.\n\n(* Resolution tactic for blindly weeding out common terms from boolean       *)\n(* equalities. When faced with a goal of the form (andb/orb/addb b1 b2) = b3 *)\n(* they will try to locate b1 in b3 and remove it. This can fail!            *)\n\nLtac bool_congr :=\n  match goal with\n  | |- (?X1 && ?X2 = ?X3) => first\n  [ symmetry; rewrite -1?(andbC X1) -?(andbCA X1); congr 1 (andb X1); symmetry\n  | case X1; [ rewrite ?andTb ?andbT | by rewrite /= ?andbF ] ]\n  | |- (?X1 || ?X2 = ?X3) => first\n  [ symmetry; rewrite -1?(orbC X1) -?(orbCA X1); congr 1 (orb X1); symmetry\n  | case X1; [ by rewrite /= ?orbT | rewrite ?orFb ?orbF ] ]\n  | |- (?X1 (+) ?X2 = ?X3) =>\n    symmetry; rewrite -1?(addbC X1) -?(addbCA X1); congr 1 (addb X1); symmetry\n  | |- (~~ ?X1 = ?X2) => congr 1 negb\n  end.\n\n(* Predicates, i.e., packaged functions to bool.                  *)\n(*   Indeed, pred T, the basic type for predicates over a type T, *)\n(* is simply an alias for T -> bool.                              *)\n(*   We actually distinguish two kinds of predicates, which we    *)\n(* applicative and collective, based on the syntax used to        *)\n(* specialize them to some value x in T:                          *)\n(*  - For an applicative predicate P, one uses prefix syntax:     *)\n(*        P x                                                     *)\n(*    Also, most operations on applicative predicates us prefix   *)\n(*    syntax as well (e.g., predI P Q).                           *)\n(*  - For a collective predicate A, one uses infix syntax:        *)\n(*        x \\in A                                                 *)\n(*    and all operations on collective predicates use infix       *)\n(*    syntax as well (e.g., [predI A & B]).                       *)\n(* There are only two kinds of applicative predicates:            *)\n(*  - pred T, the alias for T -> bool mentioned above             *)\n(*  - simpl_pred T, an alias for simpl_fun T bool with a coercion *)\n(*    to pred T that auto-simplifies on application (see ssrfun). *)\n(* On the other hand, the set of collective predicate types is    *)\n(* open-ended, via                                                *)\n(*  - predType T, a Structure that can be used to put Canonical   *)\n(*    collective predicate interpretation on other types, such    *)\n(*    as lists, tuples, finite sets, etc.                         *)\n(* Indeed, we define such interpretations for both applicative    *)\n(* predicate types, which can therefore also be used with the     *)\n(* infix syntax, e.g. x \\in predI P Q. Moreover these infix forms *)\n(* are convertible to their prefix counterpart (e.g., predI P Q x *)\n(* which in turn simplifies to P x && Q x).                       *)\n(*   The converse is not true, however; collective predicate      *)\n(* types cannot, in general, be used applicatively, because of    *)\n(* the \"uniform inheritance\" restriction on implicit coercion.    *)\n(*   However, we do define an explicit generic coercion           *)\n(*  - mem : forall (pT : predType), pT -> mem_pred T              *)\n(*    where mem_pred T is a variant of simpl_pred T that          *)\n(*    preserves the infix syntax, i.e.,                           *)\n(*       mem A x auto-simplifies to x \\in A                       *)\n(* Indeed, the infix \"collective\" operators are notation for a    *)\n(* prefix operator with arguments of type mem_pred T or pred T,   *)\n(* applied to coerced collective predicates, e.g.,                *)\n(*      Notation \"x \\in A\" := (in_mem x (mem A)).                 *)\n(* This prevents the variability in the predicate type from       *)\n(* interfering with the application of generic lemmas. Moreover   *)\n(* this also makes it much easier to define generic lemmas,       *)\n(* because the simplest type -- pred T -- can be used as the type *)\n(* of generic collective predicates, provided one takes care not  *)\n(* to use it applicatively; this avoids the burden of having to   *)\n(* declare a different predicate type for each predicate          *)\n(* parameter of each section or lemma.                            *)\n(*   This trick is made possible by the fact that the constructor *)\n(* of the mem_pred T type aligns the unification process, forcing *)\n(* a generic \"collective\" predicate A : pred T to unify with the  *)\n(* actual collective B, which mem has coerced to pred T via an    *)\n(* internal, hidden implicit coercion, supplied by the predType   *)\n(* structure for B. Users should take care not to inadvertently   *)\n(* \"strip\" (mem B) down to the coerced B, since this will expose  *)\n(* the internal coercion: Coq will display a term B x that can't  *)\n(* be typed as such. The topredE lemma can be used to restore the *)\n(* x \\in B syntax in this case. While -topredE can conversely be  *)\n(* used to change x \\in P into P x, it is safer to use the inE    *)\n(* and memE lemmas instead, as they do not run the risk of        *)\n(* exposing internal coercions. As a consequence, it is better to *)\n(* explicitly cast a generic applicative pred T to simpl_pred,    *)\n(* using the SimplPred constructor, when it is used as a          *)\n(* collective predicate (see, e.g., Lemma eq_big in bigops.v).    *)\n(*   We also sometimes \"instantiate\" the predType structure by    *)\n(* defining a coercion to the sort of the predPredType structure. *)\n(* This works better for types such as set T that have subtypes   *)\n(* that coerce to them, since the same coercion will be inserted  *)\n(* by the application of mem. It also allows us to turn some      *)\n(* specific Types (namely, any aT : predArgType) into predicates, *)\n(* specifically, the total predicate over that type, i.e.,        *)\n(* fun _ : aT => true. This allows us to write, e.g.,  #|'I_n|    *)\n(* for the cardinal of the (finite) type of integers less than n. *)\n(*   Collective predicates have a specific extensional equality,  *)\n(*     - A =i B,                                                  *)\n(* while applicative predicates just use the extensional equality *)\n(* of functions,                                                  *)\n(*     - P =1 Q                                                   *)\n(* The two forms are convertible, however.                        *)\n(*   We lift boolean operations to predicates, defining:          *)\n(*  - predU (union), predI (intersection), predC (complement),    *)\n(*    predD (difference), and preim (preimage, i.e., composition) *)\n(* For each operation we define three forms, typically:           *)\n(*   - predU : pred T -> pred T -> simpl_pred T                   *)\n(*   - [predU A & B], a Notation for predU (mem A) (mem B)        *)\n(*   - xpredU, a Notation for the lambda-expression inside predU, *)\n(*     which is mostly useful as an argument of =1, since it      *)\n(*     exposes the head constant of the expression to the         *)\n(*     ssreflect matching algorithm.                              *)\n(* The syntax for the preimage of a collective predicate A is     *)\n(*   - [preim f of A]                                             *)\n(* Finally, the generic syntax for defining a simpl_pred T is     *)\n(*   - [pred x : T | P(x)], [pred x | P(x)], [pred x \\in A | P(x) *)\n(* We also support boolean relations, but only the applicative    *)\n(* form, with types                                               *)\n(*   - rel T, an alias for T -> pred T                            *)\n(*   - simpl_rel T, an auto-simplifying version, and syntax       *)\n(*     [rel x y | P(x,y)], [rel x y \\in A & B | P(x,y)], etc.     *)\n(* The notation [rel of fA] can be used to coerce a function      *)\n(* returning a collective predicate to one returning pred T.      *)\n\nDefinition pred T := T -> bool.\n\nIdentity Coercion fun_of_pred : pred >-> Funclass.\n\nDefinition rel T := T -> pred T.\n\nIdentity Coercion fun_of_rel : rel >-> Funclass.\n\nNotation xpred0 := (fun _ => false).\nNotation xpredT := (fun _ => true).\nNotation xpredI := (fun (p1 p2 : pred _) x => p1 x && p2 x).\nNotation xpredU := (fun (p1 p2 : pred _) x => p1 x || p2 x).\nNotation xpredC := (fun (p : pred _) x => ~~ p x).\nNotation xpredD := (fun (p1 p2 : pred _) x => ~~ p2 x && p1 x).\nNotation xpreim := (fun f (p : pred _) x => p (f x)).\nNotation xrelU := (fun (r1 r2 : rel _) x y => r1 x y || r2 x y).\n\nSection Predicates.\n\nVariables T : Type.\n\nDefinition subpred (p1 p2 : pred T) := forall x, p1 x -> p2 x.\n\nDefinition subrel (r1 r2 : rel T) := forall x y, r1 x y -> r2 x y.\n\nDefinition simpl_pred := simpl_fun T bool.\n\nDefinition SimplPred (p : pred T) : simpl_pred := SimplFun p.\n\nCoercion pred_of_simpl (p : simpl_pred) : pred T := p : T -> bool.\n\nDefinition pred0 := SimplPred xpred0.\nDefinition predT := SimplPred xpredT.\nDefinition predI p1 p2 := SimplPred (xpredI p1 p2).\nDefinition predU p1 p2 := SimplPred (xpredU p1 p2).\nDefinition predC p := SimplPred (xpredC p).\nDefinition predD p1 p2 := SimplPred (xpredD p1 p2).\nDefinition preim rT f (d : pred rT) := SimplPred (xpreim f d).\n\nDefinition simpl_rel := simpl_fun T (pred T).\n\nDefinition SimplRel (r : rel T) : simpl_rel := [fun x => r x].\n\nCoercion rel_of_simpl_rel (r : simpl_rel) : rel T := fun x y => r x y.\n\nDefinition relU r1 r2 := SimplRel (xrelU r1 r2).\n\nLemma subrelUl : forall r1 r2, subrel r1 (relU r1 r2).\nProof. by move=> * ? *; apply/orP; left. Qed.\n\nLemma subrelUr : forall r1 r2, subrel r2 (relU r1 r2).\nProof. by move=> * ? *; apply/orP; right. Qed.\n\nCoInductive mem_pred : Type := Mem of pred T.\n\nDefinition isMem pT topred mem := mem = (fun p : pT => Mem [eta topred p]).\n\nStructure predType : Type := PredType {\n  pred_sort :> Type;\n  topred : pred_sort -> pred T;\n  _ : {mem | isMem topred mem}\n}.\n\nDefinition mkPredType pT toP := PredType (exist (@isMem pT toP) _ (erefl _)).\n\nCanonical Structure predPredType := Eval hnf in @mkPredType (pred T) id.\nCanonical Structure simplPredType := Eval hnf in mkPredType pred_of_simpl.\n\nCoercion pred_of_mem mp : pred_sort predPredType :=\n  let: Mem p := mp in [eta p].\n\nCanonical Structure memPredType := Eval hnf in mkPredType pred_of_mem.\n\nEnd Predicates.\n\nImplicit Arguments pred0 [T].\nImplicit Arguments predT [T].\nPrenex Implicits pred0 predT predI predU predC predD preim relU.\n\nNotation \"[ 'pred' : T | E ]\" := (SimplPred (fun _ : T => E))\n  (at level 0, format \"[ 'pred' :  T  |  E ]\") : fun_scope.\nNotation \"[ 'pred' x | E ]\" := (SimplPred (fun x => E))\n  (at level 0, x ident, format \"[ 'pred'  x  |  E ]\") : fun_scope.\nNotation \"[ 'pred' x : T | E ]\" := (SimplPred (fun x : T => E))\n  (at level 0, x ident, only parsing) : fun_scope.\nNotation \"[ 'rel' x y | E ]\" := (SimplRel (fun x y => E))\n  (at level 0, x ident, y ident, format \"[ 'rel'  x  y  |  E ]\") : fun_scope.\nNotation \"[ 'rel' x y : T | E ]\" := (SimplRel (fun x y : T => E))\n  (at level 0, x ident, y ident, only parsing) : fun_scope.\n\nDefinition repack_pred T pT :=\n  let: PredType _ a mP := pT return {type of @PredType T for pT} -> _ in\n   fun k => k a mP.\n\nNotation \"[ 'predType' 'of' T ]\" := (repack_pred (fun a => @PredType _ T a))\n  (at level 0, format \"[ 'predType'  'of'  T ]\") : form_scope.\n\n(* This redundant coercion lets us \"inherit\" the simpl_predType canonical *)\n(* structure by declaring a coercion to simpl_pred. This hack is the only *)\n(* way to put a predType structure on a predArgType. We use simpl_pred    *)\n(* rather than pred to ensure that /= removes the identity coercion. Note *)\n(* that the coercion will never be used directly for simpl_pred, since    *)\n(* the canonical structure should always resolve.                         *)\n\nNotation pred_class := (pred_sort (predPredType _)).\nCoercion sort_of_simpl_pred T (p : simpl_pred T) : pred_class := p : pred T.\n\n(* This lets us use some types as a synonym for their universal predicate. *)\n(* Unfortunately, this won't work for existing types like bool, unless     *)\n(* we redefine bool, true, false and all bool ops.                         *)\n(*   We don't define a coercion to Sortclass because then any coercion to  *)\n(* predArgType would always be in a conflict with a preexisting coercion   *)\n(* to Sortclass.                                                           *)\nDefinition predArgType := Type.\nCoercion pred_of_argType (T : predArgType) : simpl_pred T := predT.\n\nNotation \"{ : T }\" := (T%type : predArgType)\n  (at level 0, format \"{ :  T }\") : type_scope.\n\n(* These must be defined outside a Section because \"cooking\" kills the *)\n(* nosimpl tag.                                                        *)\n\nDefinition mem T (pT : predType T) : pT -> mem_pred T :=\n  nosimpl (let: PredType _ _ (exist mem _) := pT return pT -> _ in mem).\nDefinition in_mem T x mp := nosimpl pred_of_mem T mp x.\n\nPrenex Implicits mem.\n\nCoercion pred_of_mem_pred T mp := [pred x : T | in_mem x mp].\n\nDefinition eq_mem T p1 p2 := forall x : T, in_mem x p1 = in_mem x p2.\nDefinition sub_mem T p1 p2 := forall x : T, in_mem x p1 -> in_mem x p2.\n\nNotation \"x \\in A\" := (in_mem x (mem A)) : bool_scope.\nNotation \"x \\in A\" := (in_mem x (mem A)) : bool_scope.\nNotation \"x \\notin A\" := (~~ (x \\in A)) : bool_scope.\nNotation \"A =i B\" := (eq_mem (mem A) (mem B)) : type_scope.\nNotation \"{ 'subset' A <= B }\" := (sub_mem (mem A) (mem B))\n  (at level 0, A, B at level 69,\n   format \"{ '[hv' 'subset'  A '/   '  <=  B ']' }\") : type_scope.\nNotation \"[ 'mem' A ]\" := (pred_of_simpl (pred_of_mem_pred (mem A)))\n  (at level 0, only parsing) : fun_scope.\nNotation \"[ 'rel' 'of' fA ]\" := (fun x => [mem (fA x)])\n  (at level 0, format \"[ 'rel'  'of'  fA ]\") : fun_scope.\nNotation \"[ 'predI' A & B ]\" := (predI [mem A] [mem B])\n  (at level 0, format \"[ 'predI'  A  &  B ]\") : fun_scope.\nNotation \"[ 'predU' A & B ]\" := (predU [mem A] [mem B])\n  (at level 0, format \"[ 'predU'  A  &  B ]\") : fun_scope.\nNotation \"[ 'predD' A & B ]\" := (predD [mem A] [mem B])\n  (at level 0, format \"[ 'predD'  A  &  B ]\") : fun_scope.\nNotation \"[ 'predC' A ]\" := (predC [mem A])\n  (at level 0, format \"[ 'predC'  A ]\") : fun_scope.\nNotation \"[ 'preim' f 'of' A ]\" := (preim f [mem A])\n  (at level 0, format \"[ 'preim'  f  'of'  A ]\") : fun_scope.\n\nNotation \"[ 'pred' x \\in A ]\" := [pred x | x \\in A]\n  (at level 0, x ident, format \"[ 'pred'  x  \\in  A ]\") : fun_scope.\nNotation \"[ 'pred' x \\in A | E ]\" := [pred x | (x \\in A) && E]\n  (at level 0, x ident, format \"[ 'pred'  x  \\in  A  |  E ]\") : fun_scope.\nNotation \"[ 'rel' x y \\in A & B | E ]\" :=\n  [rel x y | (x \\in A) && (y \\in B) && E]\n  (at level 0, x ident, y ident,\n   format \"[ 'rel'  x  y  \\in  A  &  B  |  E ]\") : fun_scope.\nNotation \"[ 'rel' x y \\in A & B ]\" := [rel x y | (x \\in A) && (y \\in B)]\n  (at level 0, x ident, y ident,\n   format \"[ 'rel'  x  y  \\in  A  &  B ]\") : fun_scope.\nNotation \"[ 'rel' x y \\in A | E ]\" := [rel x y \\in A & A | E]\n  (at level 0, x ident, y ident,\n   format \"[ 'rel'  x  y  \\in  A  |  E ]\") : fun_scope.\nNotation \"[ 'rel' x y \\in A ]\" := [rel x y \\in A & A]\n  (at level 0, x ident, y ident,\n   format \"[ 'rel'  x  y  \\in  A ]\") : fun_scope.\n\nSection simpl_mem.\n\nVariables (T : Type) (pT : predType T).\n\nLemma mem_topred : forall (p : pT), mem (topred p) = mem p.\nProof. by rewrite /mem; case: pT => T1 app1 [mem1  /= ->]. Qed.\n\nLemma topredE : forall x (p : pT), topred p x = (x \\in p).\nProof. by move=> *; rewrite -mem_topred. Qed.\n\nLemma in_simpl : forall x (p : simpl_pred T), (x \\in p) = p x.\nProof. by []. Qed.\n\nLemma simpl_predE : forall (p : pred T), [pred x | p x] =1 p.\nProof. by []. Qed.\n\nDefinition inE := (in_simpl, simpl_predE). (* to be extended *)\n\nLemma mem_simpl : forall (p : simpl_pred T), mem p = p :> pred T.\nProof. by []. Qed.\n\nDefinition memE := mem_simpl. (* could be extended *)\n\nLemma mem_mem : forall p : pT, (mem (mem p) = mem p) * (mem [mem p] = mem p).\nProof. by move=> p; rewrite -mem_topred. Qed.\n\nEnd simpl_mem.\n\nSection RelationProperties.\n\n(* Caveat: reflexive should not be used to state lemmas, since auto *)\n(* and trivial will not expand the constant.                        *)\n\nVariable T : Type.\n\nVariable R : rel T.\n\nDefinition total := forall x y, R x y || R y x.\nDefinition transitive := forall y x z, R x y -> R y z -> R x z.\n\nDefinition symmetric := forall x y, R x y = R y x.\nDefinition antisymmetric := forall x y, R x y && R y x -> x = y.\nDefinition pre_symmetric := forall x y, R x y -> R y x.\n\nLemma symmetric_from_pre : pre_symmetric -> symmetric.\nProof. move=> symR x y; apply/idP/idP; exact: symR. Qed.\n\nDefinition reflexive := forall x, R x x.\nDefinition irreflexive := forall x, R x x = false.\n\nDefinition left_transitive := forall x y, R x y -> R x =1 R y.\nDefinition right_transitive := forall x y, R x y -> R^~ x =1 R^~ y.\n\nEnd RelationProperties.\n\n(* Property localization *)\n\nNotation Local \"{ 'all1' P }\" := (forall x, P x : Prop) (at level 0).\nNotation Local \"{ 'all2' P }\" := (forall x y, P x y : Prop) (at level 0).\nNotation Local \"{ 'all3' P }\" := (forall x y z, P x y z: Prop) (at level 0).\nNotation Local ph := (phantom _).\n\nSection LocalProperties.\n\nVariables T1 T2 T3 : Type.\n\nVariables (d1 : mem_pred T1) (d2 : mem_pred T2) (d3 : mem_pred T3).\nNotation Local ph := (phantom Prop).\n\nDefinition prop_in1 P & ph {all1 P} :=\n  forall x, in_mem x d1 -> P x.\n\nDefinition prop_in11 P & ph {all2 P} :=\n  forall x y, in_mem x d1 -> in_mem y d2 -> P x y.\n\nDefinition prop_in2 P & ph {all2 P} :=\n  forall x y, in_mem x d1 -> in_mem y d1 -> P x y.\n\nDefinition prop_in111 P & ph {all3 P} :=\n  forall x y z, in_mem x d1 -> in_mem y d2 -> in_mem z d3 -> P x y z.\n\nDefinition prop_in12 P & ph {all3 P} :=\n  forall x y z, in_mem x d1 -> in_mem y d2 -> in_mem z d2 -> P x y z.\n\nDefinition prop_in21 P & ph {all3 P} :=\n  forall x y z, in_mem x d1 -> in_mem y d1 -> in_mem z d2 -> P x y z.\n\nDefinition prop_in3 P & ph {all3 P} :=\n  forall x y z, in_mem x d1 -> in_mem y d1 -> in_mem z d1 -> P x y z.\n\nVariable f : T1 -> T2.\n\nDefinition prop_on1 Pf P & phantom T3 (Pf f) & ph {all1 P} :=\n  forall x, in_mem (f x) d2 -> P x.\n\nDefinition prop_on2 Pf P & phantom T3 (Pf f) & ph {all2 P} :=\n  forall x y, in_mem (f x) d2 -> in_mem (f y) d2 -> P x y.\n\nEnd LocalProperties.\n\nDefinition inPhantom (P : Prop) := Phantom P.\nDefinition onPhantom T (P : T -> Prop) x := Phantom (P x).\n\nDefinition bijective_in aT rT (d : mem_pred aT) (f : aT -> rT) :=\n  exists2 g, prop_in1 d (inPhantom (cancel f g))\n           & prop_on1 d (Phantom (cancel g)) (onPhantom (cancel g) f).\n\nDefinition bijective_on aT rT (cd : mem_pred rT) (f : aT -> rT) :=\n  exists2 g, prop_on1 cd (Phantom (cancel f)) (onPhantom (cancel f) g)\n           & prop_in1 cd (inPhantom (cancel g f)).\n\nNotation \"{ 'in' d , P }\" :=\n  (prop_in1 (mem d) (inPhantom P))\n  (at level 0, format \"{ 'in'  d ,  P }\") : type_scope.\n\nNotation \"{ 'in' d1 & d2 , P }\" :=\n  (prop_in11 (mem d1) (mem d2) (inPhantom P))\n  (at level 0, format \"{ 'in'  d1  &  d2 ,  P }\") : type_scope.\n\nNotation \"{ 'in' d & , P }\" :=\n  (prop_in2 (mem d) (inPhantom P))\n  (at level 0, format \"{ 'in'  d  & ,  P }\") : type_scope.\n\nNotation \"{ 'in' d1 & d2 & d3 , P }\" :=\n  (prop_in111 (mem d1) (mem d2) (mem d3) (inPhantom P))\n  (at level 0, format \"{ 'in'  d1  &  d2  &  d3 ,  P }\") : type_scope.\n\nNotation \"{ 'in' d1 & & d3 , P }\" :=\n  (prop_in21 (mem d1) (mem d3) (inPhantom P))\n  (at level 0, format \"{ 'in'  d1  &  &  d3 ,  P }\") : type_scope.\n\nNotation \"{ 'in' d1 & d2 & , P }\" :=\n  (prop_in12 (mem d1) (mem d2) (inPhantom P))\n  (at level 0, format \"{ 'in'  d1  &  d2  & ,  P }\") : type_scope.\n\nNotation \"{ 'in' d & & , P }\" :=\n  (prop_in3 (mem d) (inPhantom P))\n  (at level 0, format \"{ 'in'  d  &  & ,  P }\") : type_scope.\n\nNotation \"{ 'on' cd , P }\" :=\n  (prop_on1 (mem cd) (inPhantom P) (inPhantom P))\n  (at level 0, format \"{ 'on'  cd ,  P }\") : type_scope.\n\nNotation \"{ 'on' cd & , P }\" :=\n  (prop_on2 (mem cd) (inPhantom P) (inPhantom P))\n  (at level 0, format \"{ 'on'  cd  & ,  P }\") : type_scope.\n\nNotation \"{ 'on' cd , P & g }\" :=\n  (prop_on1 (mem cd) (Phantom P) (onPhantom P g))\n  (at level 0, format \"{ 'on'  cd ,  P  &  g }\") : type_scope.\n\nNotation \"{ 'in' d , 'bijective' f }\" := (bijective_in (mem d) f)\n  (at level 0, f at level 8,\n   format \"{ 'in'  d ,  'bijective'  f }\") : type_scope.\n\nNotation \"{ 'on' cd , 'bijective' f }\" := (bijective_on (mem cd) f)\n  (at level 0, f at level 8,\n   format \"{ 'on'  cd ,  'bijective'  f }\") : type_scope.\n\n(* Weakening and monotonicity lemmas for localized predicates. *)\n(* Note that using these lemmas in backward reasoning will     *)\n(* cause the expansion of the predicate definition, as Coq     *)\n(* needs to expose the quantifier to apply these lemmas. We    *)\n(* define some specialized variants to avoid this for some of  *)\n(* the ssrfun definitions.                                     *)\n\nSection LocalGlobal.\n\nVariables T1 T2 T3 : predArgType.\nVariables (D1 : pred T1) (D2 : pred T2) (D3 : pred T3).\nVariables (d1 d1' : mem_pred T1) (d2 d2' : mem_pred T2) (d3 d3' : mem_pred T3).\nVariables (f f' : T1 -> T2) (g : T2 -> T1) (h : T3).\nVariables (P1 : T1 -> Prop) (P2 : T1 -> T2 -> Prop).\nVariable P3 : T1 -> T2 -> T3 -> Prop.\nVariable Q1 : (T1 -> T2) -> T1 -> Prop.\nVariable Q1l : (T1 -> T2) -> T3 -> T1 -> Prop.\nVariable Q2 : (T1 -> T2) -> T1 -> T1 -> Prop.\n\nHypothesis sub1 : sub_mem d1 d1'.\nHypothesis sub2 : sub_mem d2 d2'.\nHypothesis sub3 : sub_mem d3 d3'.\n\nLemma in1W : {all1 P1} -> {in D1, {all1 P1}}.\nProof. by move=> ? ?. Qed.\nLemma in2W : {all2 P2} -> {in D1 & D2, {all2 P2}}.\nProof. by move=> ? ?. Qed.\nLemma in3W : {all3 P3} -> {in D1 & D2 & D3, {all3 P3}}.\nProof. by move=> ? ?. Qed.\n\nLemma in1A : {in T1, {all1 P1}} -> {all1 P1}.\nProof. by move=> ? ?; auto. Qed.\nLemma in2A : {in T1 & T2, {all2 P2}} -> {all2 P2}.\nProof. by move=> ? ?; auto. Qed.\nLemma in3A : {in T1 & T2 & T3, {all3 P3}} -> {all3 P3}.\nProof. by move=> ? ?; auto. Qed.\n\nLemma sub_in1 : forall Ph : ph {all1 P1},\n  prop_in1 d1' Ph -> prop_in1 d1 Ph.\nProof. move=> ? allP x; move/sub1; exact: allP. Qed.\n\nLemma sub_in11 : forall Ph : ph {all2 P2},\n  prop_in11 d1' d2' Ph -> prop_in11 d1 d2 Ph.\nProof. move=> ? allP x1 x2; move/sub1=> d1x1; move/sub2; exact: allP. Qed.\n\nLemma sub_in111 :  forall Ph : ph {all3 P3},\n  prop_in111 d1' d2' d3' Ph -> prop_in111 d1 d2 d3 Ph.\nProof.\nmove=> ? allP x1 x2 x3.\nmove/sub1=> d1x1; move/sub2=> d2x2; move/sub3; exact: allP.\nQed.\n\nLet allQ1 f'' := {all1 Q1 f''}.\nLet allQ1l f'' h' := {all1 Q1l f'' h'}.\nLet allQ2 f'' := {all2 Q2 f''}.\n\nLemma on1W : allQ1 f -> {on D2, allQ1 f}. Proof. by move=> ? ?. Qed.\n\nLemma on1lW : allQ1l f h -> {on D2, allQ1l f & h}. Proof. by move=> ? ?. Qed.\n\nLemma on2W : allQ2 f -> {on D2 &, allQ2 f}. Proof. by move=> ? ?. Qed.\n\nLemma on1A : {on T2, allQ1 f} -> allQ1 f. Proof. by move=> ? ?; auto. Qed.\n\nLemma on1lA : {on T2, allQ1l f & h} -> allQ1l f h.\nProof. by move=> ? ?; auto. Qed.\n\nLemma on2A : {on T2 &, allQ2 f} -> allQ2 f.\nProof. by move=> ? ?; auto. Qed.\n\nLemma subon1 : forall (Phf : ph (allQ1 f)) (Ph : ph (allQ1 f)),\n  prop_on1 d2' Phf Ph -> prop_on1 d2 Phf Ph.\nProof. move=> ? ? allQ x; move/sub2; exact: allQ. Qed.\n\nLemma subon1l : forall (Phf : ph (allQ1l f)) (Ph : ph (allQ1l f h)),\n  prop_on1 d2' Phf Ph -> prop_on1 d2 Phf Ph.\nProof. move=> ? ? allQ x; move/sub2; exact: allQ. Qed.\n\nLemma subon2 : forall (Phf : ph (allQ2 f)) (Ph : ph (allQ2 f)),\n  prop_on2 d2' Phf Ph -> prop_on2 d2 Phf Ph.\nProof. move=> ? ? allQ x y; move/sub2=> d2fx; move/sub2; exact: allQ. Qed.\n\nLemma can_in_inj : {in D1, cancel f g} -> {in D1 &, injective f}.\nProof.\nby move=> fK x y; do 2![move/fK=> def; rewrite -{2}def {def}] => ->.\nQed.\n\nLemma on_can_inj : {on D2, cancel f & g} -> {on D2 &, injective f}.\nProof.\nby move=> fK x y; do 2![move/fK=> def; rewrite -{2}def {def}] => ->.\nQed.\n\nLemma inW_bij : bijective f -> {in D1, bijective f}.\nProof. by case=> g' fK g'K; exists g' => * ? *; auto. Qed.\n\nLemma onW_bij : bijective f -> {on D2, bijective f}.\nProof. by case=> g' fK g'K; exists g' => * ? *; auto. Qed.\n\nLemma inA_bij : {in T1, bijective f} -> bijective f.\nProof. by case=> g' fK g'K; exists g' => * ? *; auto. Qed.\n\nLemma onA_bij : {on T2, bijective f} -> bijective f.\nProof. by case=> g' fK g'K; exists g' => * ? *; auto. Qed.\n\nLemma sub_in_bij : forall D1' : pred T1,\n  {subset D1 <= D1'} -> {in D1', bijective f} -> {in D1, bijective f}.\nProof.\nmove=> D1' subD [g' fK g'K].\nexists g' => x; move/subD; [exact: fK | exact: g'K].\nQed.\n\nLemma subon_bij :  forall D2' : pred T2,\n {subset D2 <= D2'} -> {on D2', bijective f} -> {on D2, bijective f}.\nProof.\nmove=> D2' subD [g' fK g'K].\nexists g' => x; move/subD; [exact: fK | exact: g'K].\nQed.\n\nEnd LocalGlobal.\n\nLemma sub_in2 : forall T d d' (P : T -> T -> Prop),\n  sub_mem d d' -> forall Ph : ph {all2 P}, prop_in2 d' Ph -> prop_in2 d Ph.\nProof. by move=> T d d' P /= sub; exact: sub_in11. Qed.\n\nLemma sub_in3 : forall T d d' (P : T -> T -> T -> Prop),\n  sub_mem d d' -> forall Ph : ph {all3 P}, prop_in3 d' Ph -> prop_in3 d Ph.\nProof. by move=> T d d' P /= sub; exact: sub_in111. Qed.\n\nLemma sub_in12 : forall T1 T d1 d1' d d' (P : T1 -> T -> T -> Prop),\n  sub_mem d1 d1' -> sub_mem d d' ->\n  forall Ph : ph {all3 P}, prop_in12 d1' d' Ph -> prop_in12 d1 d Ph.\nProof. by move=> T1 T d1 d1' d d' P /= sub1 sub; exact: sub_in111. Qed.\n\nLemma sub_in21 : forall T T3 d d' d3 d3' (P : T -> T -> T3 -> Prop),\n  sub_mem d d' -> sub_mem d3 d3' ->\n  forall Ph : ph {all3 P}, prop_in21 d' d3' Ph -> prop_in21 d d3 Ph.\nProof. by move=> T T3 d d' d3 d3' P /= sub sub3; exact: sub_in111. Qed.\n", "meta": {"author": "Wassasin", "repo": "ssreflect", "sha": "45cf056aa48bec1e7e2bbb77cb4458d4bddf43e4", "save_path": "github-repos/coq/Wassasin-ssreflect", "path": "github-repos/coq/Wassasin-ssreflect/ssreflect-45cf056aa48bec1e7e2bbb77cb4458d4bddf43e4/theories/ssrbool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.6971898782014692}}
{"text": "(* A collection of auxiliary results about reals. *)\nRequire Import base.\nRequire Import Reals.\nRequire Import micromega.Lra.\n\nOpen Scope R_scope.\n\nLemma neq_2_0 : 2 <> 0. Proof. lra. Qed.\nLemma le_1_2 : 1 <= 2. Proof. lra. Qed.\nLemma le_0_2 : 0 <= 2. Proof. lra. Qed.\nLemma le_0_4 : 0 <= 4. Proof. lra. Qed.\nLemma lt_0_2 : 0 < 2. Proof. lra. Qed.\nLemma eq_2_2_4 : 2 * 2 = 4. Proof. lra. Qed.\nLemma lt_0_4 : 0 < 4. Proof. lra. Qed.\nLemma div_eq_4_2 : 4 / 2 = 2. Proof. lra. Qed.\nLemma div_eq_8_2 : 8 / 2 = 4. Proof. lra. Qed.\nLemma eq_3_1_4 : 3 + 1 = 4. Proof. lra. Qed.\nLemma Rmult_4_2 : 4 * 2 = 8. Proof. lra. Qed.\n\nLemma Rminus_2_1 : 2 + - (1) = 1. Proof. lra. Qed.\n\nLemma Rdiv_4_2 : forall n : nat, 4/2^n = 4 * /2^n.\nProof.\n  intro n.\n  unfold Rdiv.\n  reflexivity.\nQed.\n\nLemma Rdiv_expand : forall n : nat, 1/2^n = 1 * /2^n.\nProof.\n  intro n.\n  unfold Rdiv.\n  reflexivity.\nQed.\n\nLemma neq_inv_2_0 : 0 <= /2.\nProof.\n  apply (Rlt_le 0 (/2)).\n  exact (pos_half_prf).\nQed.\n\nLemma le_eq : forall x y z : R, 0 <= x -> x + y = z -> y <= z.\nProof.\n  intros x y z Hx H.\n  rewrite <- H.\n  rewrite <- (Rplus_0_l y) at 1.\n  apply (Rplus_le_compat_r y 0 x Hx).\nQed.\n\nLemma le_eq_comm : forall x y z : R, 0 <= y -> x + y = z -> x <= z.\nProof.\n  intros x y z Hy H.\n  rewrite (Rplus_comm x y) in H.\n  exact (le_eq y x z Hy H).\nQed.\n\nLemma Rle_minus_0 : forall x : R, 0 <= x -> - x <= 0.\nProof.\n  intros x H.\n  apply (le_eq x (- x) 0 H (Rplus_opp_r x)).\nQed.\n\nLemma Rle_inv_2n : forall n : nat, 0 <= /2^n.\nProof.\n  intro n.\n  rewrite <- (Rmult_1_l (/2^n)).\n  exact (Rle_mult_inv_pos 1 (2^n) Rle_0_1 (pow_lt 2 n Rlt_0_2)).\nQed.\n\nLemma Rlt_inv_2n : forall n : nat, 0 < /2^n.\nProof.\n  intro n.\n  rewrite <- (Rmult_1_l (/2^n)).\n  exact (Rlt_mult_inv_pos 1 (2^n) Rlt_0_1 (pow_lt 2 n Rlt_0_2)).\nQed.\n\nLemma pow2 : forall n : R, n^2 = n * n.\nProof.\n  intro n.\n  simpl.\n  rewrite (Rmult_1_r n).\n  reflexivity.\nQed.\n\nLemma sqr_expand : forall a b : R, (a + b)^2 = a^2 + b * (2 * a + b).\nProof.\n  exact\n    (fun a b =>\n      eq_refl ((a + b)^2)\n      || _ = (a + b) * X @X by <- Rmult_1_r (a + b)\n      || _ = X @X by <- Rmult_plus_distr_r a b (a + b)\n      || _ = X + _ @X by <- Rmult_plus_distr_l a a b\n      || _ = X + _ + _ @X by pow2 a\n      || _ = _ + _ + X @X by <- Rmult_plus_distr_l b a b\n      || _ = X @X by <- Rplus_assoc (a^2) (a * b) (b * a + b * b)\n      || _ = _ + X @X by Rplus_assoc (a * b) (b * a) (b * b)\n      || _ = _ + (_ + X + _) @X by Rmult_comm a b\n      || _ = _ + (X + _) @X by double (a * b)\n      || _ = _ + (X + _) @X by Rmult_assoc 2 a b\n      || _ = _ + X @X by Rmult_plus_distr_r (2 * a) b b\n      || _ = _ + X @X by <- Rmult_comm (2 * a + b) b).\nQed.\n\nLemma eq_2_2n\n  : forall n : nat, 2/2^(S n) = 1/2^n.\nProof.\n  intro n.\n  unfold Rdiv.\n  unfold pow.\n  fold pow.\n  rewrite (Rinv_mult_distr 2 (2^n) neq_2_0 (pow_nonzero 2 n neq_2_0)).\n  rewrite <- (Rmult_assoc 2 (/2) (/2^n)).\n  rewrite (Rinv_r 2 neq_2_0).\n  reflexivity.\nQed.\n\nLemma eq_1_2n\n  : forall n : nat, 1/2^n + 1/2^n = 2/2^n.\nProof.\n  intro n.\n  unfold Rdiv.\n  lra.\nQed.\n\nLemma le_0_1_2n : forall n : nat, 0 <= 1/2^n.\nProof.\n  intro n.\n  unfold Rdiv.\n  exact (Rle_mult_inv_pos 1 (2^n) ltac:(lra) (pow_lt 2 n Rlt_0_2)).\nQed.\n\nLemma lt_0_1_2n : forall n : nat, 0 < 1/2^n.\nProof.\n  intro n.\n  unfold Rdiv.\n  exact (Rlt_mult_inv_pos 1 (2^n) ltac:(lra) (pow_lt 2 n Rlt_0_2)).\nQed.\n\nClose Scope R_scope.\n", "meta": {"author": "llee454", "repo": "FPU-Verification", "sha": "c8bbb7b9dd08b6f0a054463f7737aac77c4e144c", "save_path": "github-repos/coq/llee454-FPU-Verification", "path": "github-repos/coq/llee454-FPU-Verification/FPU-Verification-c8bbb7b9dd08b6f0a054463f7737aac77c4e144c/verification/aux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.6971898723918583}}
{"text": "Require Import Arith_base.\nRequire Vectors.Fin.\nImport EqNotations.\nLocal Open Scope nat_scope.\n\nInductive sortedlist : nat -> Type :=\n  | nil : sortedlist 0\n  | cons : forall (m n : nat), sortedlist m -> m <= n -> sortedlist n.\n\nTheorem zero_leq_all : forall (m : nat), 0 <= m.\n  intros.\n  induction m.\n    apply le_n.\n    apply le_S.\n    apply IHm.\nQed.\n\nTheorem zero_leq_1 : 0 <= 1. apply zero_leq_all. Qed.\n\nDefinition sortedlist_01 : sortedlist 1 := cons 0 1 nil zero_leq_1.\n\n", "meta": {"author": "Riib11", "repo": "Coq-Work", "sha": "e163edd331fd15549910f0fe0a361bc93ca951d7", "save_path": "github-repos/coq/Riib11-Coq-Work", "path": "github-repos/coq/Riib11-Coq-Work/Coq-Work-e163edd331fd15549910f0fe0a361bc93ca951d7/Math/old/Sorted.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678382, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.697188667034222}}
{"text": "Require Import Omega.\nGoal (221 * 293 * 389 * 397 + 17 = 14 * 119 * 127 * 151 * 313)%nat.\nProof.\n  omega.\nQed.\n", "meta": {"author": "kitayuta", "repo": "CoqEx2014", "sha": "ed9e347270aaed9872b4ebc50ab44a7c1e7ea24c", "save_path": "github-repos/coq/kitayuta-CoqEx2014", "path": "github-repos/coq/kitayuta-CoqEx2014/CoqEx2014-ed9e347270aaed9872b4ebc50ab44a7c1e7ea24c/Ex6/26.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6971886563070304}}
{"text": "(* Bibliotecas importadas *)\n\nRequire Import Arith.\n\n\n(* Definição indutiva dos termos de L0 *)\n\nInductive term :=\n | zero   : term\n | succ   : term -> term\n | true   : term\n | false  : term\n | iszero : term -> term\n | pred   : term -> term\n | ifte   : term -> term -> term -> term \n.\n\n(* Definição indutiva da propriedade de ser um número *)\n\nInductive nv : term -> Prop :=\n | zeroNum : nv zero\n | succNum : forall n, (nv n) -> (nv (succ n))\n.\n\n(* Definição indutiva de valor : números OU booleanos *)\n\nInductive value : term -> Prop :=\n | trueVal  : value true\n | falseVal : value false\n | numVal   : forall n, (nv n) -> (value n)\n.\n\n(* Testando termos *)\nCheck ifte false zero (succ zero).\n\n(* Testando valores do tipo termo *)\nCheck value (iszero true).\n\n(* Provando uma propriedade *)\nTheorem teste1 : value (succ zero).\nProof.\nconstructor 3.\nconstructor 2.\nconstructor 1.\nQed.\n\n(* Provando uma propriedade 2 *)\nTheorem teste2 : value (succ zero).\nProof.\napply numVal.\napply succNum.\napply zeroNum.\nQed.\n\n\n(* Provando uma propriedade negada *)\nLemma teste : ~ value (iszero true).\nProof.\nunfold not.\nintro H.\ninversion H.\nsubst.\ninversion H0.\nQed.\n\n\n\n\n\n\n\n(*****************************************************************)\n\n\n\n\n\n\n(* Definição da semântica operacional *)\nInductive step : term -> term -> Prop :=\n | e_iftrue     : forall t2 t3,        step (ifte true  t2 t3) t2\n | e_iffalse    : forall t2 t3,        step (ifte false t2 t3) t3\n | e_if         : forall t1 t2 t3 t1', (step t1 t1') -> step (ifte t1 t2 t3) (ifte t1' t2 t3)\n | e_succ       : forall t t',         step t t' -> step (succ t) (succ t')\n | e_predzero   :                      step (pred zero) zero\n | e_predsucc   : forall t,  (nv t) -> step (pred (succ t)) t\n | e_pred       : forall t t',         step t t' -> step (pred t) (pred t')\n | e_iszerozero :                      step (iszero zero) true\n | e_iszerosucc : forall t,  (nv t) -> step (iszero (succ t)) false\n | e_iszero     : forall t t',         step t t' -> step (iszero t) (iszero t')\n.\n \n\n(* Definição de forma normal *)\n\nDefinition NF (t:term) : Prop := forall t', not (step t t').\n\n\n\n\n\n(*****************************************************************)\n\n\n\n(* Exercício : TODO NV É FORMA NORMAL *)\nTheorem nvNF : forall (t:term), nv t -> NF t.\nProof.\ninduction t.\nintro. unfold NF. intro. unfold not. intro. inversion H0. (* zero *)  \nintro. inversion H. subst. apply IHt in H1. unfold NF in H1.  intro. unfold not. intro. inversion H0. subst. unfold not in H1. apply (H1 t'0) in H3. assumption. (* succ *) \nintro. unfold NF. intro. intro. inversion H0. (* true *) \nintro. unfold NF. intro. intro. inversion H0. (* false *)\nintro. inversion H. (* iszero *)\nintro. inversion H. (* pred *)\nintro. inversion H. (* ifte *)\nQed.\n\n\n\n(* Exercício : TODO VALOR É FORMA NORMAL *)\n\nTheorem valueNF : forall (t:term), value t -> NF t.\nProof.\nintro. \nintro. \ninduction H.\n  (* H=true *)\n  unfold NF.\n  intro.\n  unfold not.\n  intro.\n  inversion H.\n  (* H=false *)\n  unfold NF.\n  intro.\n  unfold not.\n  intro.\n  inversion H.\n  (* H=nv *)\n  apply nvNF.\n  assumption.\nQed.\n\n\n\n(* DETERMINISMO *)\n\nTheorem determinismo : forall t t' t'', (step t t') -> (step t t'') -> (t' = t'').\nProof.\ninduction t.\n(* zero *)\nintros. inversion H.\n(* succ *) \nintros.  inversion H. inversion H0. subst. assert (t'0 = t'1). apply (IHt t'0 t'1 H2 H5). apply f_equal. assumption.\n(* true *)\nintros. inversion H.\n(* false *)\nintros. inversion H.\n(* iszero *)\n\nintros. inversion H. subst. inversion H0. reflexivity. inversion H2. \ninversion H0.  subst. discriminate H5. reflexivity. subst. \napply succNum in H2. apply nvNF in H2. unfold NF in H2. unfold not in H2. apply H2 in H5. exfalso. assumption.\ninversion H0.  subst.  inversion H2. subst. apply succNum in H5. apply nvNF in H5. unfold NF in H5. unfold not in H5. exfalso. apply (H5 t'0 H2). subst. apply f_equal. apply (IHt t'0 t'1 H2 H5).\n\n\nintros. inversion H. subst. inversion H0. reflexivity. inversion H2. \ninversion H0.  subst. discriminate H5. subst. injection H4. intro. symmetry.  assumption.  \nsubst. \napply succNum in H2. apply nvNF in H2. unfold NF in H2. unfold not in H2. apply H2 in H5. exfalso. assumption.\ninversion H0.  subst.  inversion H2. subst. apply succNum in H5. apply nvNF in H5. unfold NF in H5. unfold not in H5. exfalso. apply (H5 t'0 H2). subst. apply f_equal. apply (IHt t'0 t'1 H2 H5).\n\n\nintros. \ninversion H. subst. inversion H0. subst. reflexivity. inversion H5.\n\ninversion H0. subst. discriminate. subst. assumption. subst. inversion H9. subst. inversion H0. subst. inversion H5. subst. inversion H5. subst. assert (t1'=t1'0). apply IHt1. assumption. assumption. rewrite H1. reflexivity.\n\nQed.\n\nInductive type :=\n  | tNat : type\n  | tBool : type.\n\nInductive hasType : term -> type -> Prop :=\n  | tTrue : hasType true tBool\n  | tFalse : hasType false tBool\n  | tZero : hasType zero tNat\n  | tSucc : forall t1, hasType t1 tNat -> hasType (succ t1) tNat\n  | tPred : forall t1, hasType t1 tNat -> hasType (pred t1) tNat\n  | tIsZero: forall t1, hasType t1 tNat -> hasType (iszero t1) tBool\n  | tIf: forall t1 t2 t3 T, hasType t1 tBool -> hasType t2 T -> hasType t3 T -> hasType (ifte t1 t2 t3) T.\n\nTheorem two_a : hasType (ifte ((iszero (succ (succ zero)))) (succ zero) zero) tNat.\nProof.\napply tIf.\napply tIsZero.\napply tSucc. apply tSucc. apply tZero. \napply tSucc. apply tZero.\napply tZero.\nQed.\n\nTheorem two_b: step (ifte (iszero (succ (succ zero))) (succ zero) zero) (ifte false (succ zero) zero).\nProof.\napply e_if.\napply e_iszerosucc. apply succNum. apply zeroNum.\nQed.\n\nTheorem two_c: ~ step (ifte (iszero (succ (succ zero))) (succ zero) zero) zero.\nProof.\nunfold not.\nintros.\ninversion H.\nQed.\n\nTheorem two_d:  ~ forall (t : term) , value t.\nProof.\nunfold not.\nintro.\nassert (value (iszero zero)).\napply (H (iszero zero)).\ninversion H0.\ninversion H1.\nQed.\n\nTheorem two_e:  forall (t : term), (value t \\/ ~value t).\nProof.\ninduction t.\n  left. apply numVal. apply zeroNum.\n  induction IHt.\n    induction H.\n      right. unfold not. intros. inversion H. subst. inversion H0. subst. inversion H2.\n      right. unfold not. intros. inversion H. subst. inversion H0. subst. inversion H2.\n      left. apply numVal. apply succNum. assumption.\n      right. intro. apply H. apply numVal. inversion H0. inversion H1. subst. assumption.\n  left. apply trueVal.\n  left. apply falseVal.\n  right. unfold not. intros. inversion H. subst. inversion H0.\n  right. unfold not. intros. inversion H. subst. inversion H0.\n  right. unfold not. intros. inversion H. subst. inversion H0. \n(* martelado *)\nQed.\n\nTheorem unicidade: forall (t : term) (T : type) , (hasType t T) -> forall T', (hasType t T') -> T=T'.\nProof.\ninduction t.\n  intros. inversion H. subst. inversion H0. reflexivity.\n  intros. inversion H. subst. inversion H0. reflexivity.\n  intros. inversion H. subst. inversion H0. reflexivity.\n  intros. inversion H. subst. inversion H0. reflexivity.\n  intros. inversion H. subst. inversion H0. reflexivity.\n  intros. inversion H. subst. inversion H0. reflexivity.\n  intros. inversion H. subst. apply IHt2. assumption.\n    inversion H0. subst. assumption.\nQed.\n\nTheorem preservacao:  forall t t', step t t' -> forall T, hasType t T -> hasType t' T.\nProof.\ninduction t.\n  intros. inversion H0. subst. inversion H.\n  intros. inversion H0. subst. apply e_succ in H.\n(* proof by cansaço *)\nAdmitted.", "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/paulo_linguagem-de-termos.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.6970802760719786}}
{"text": "Require Import Arith.\nRequire Import ZArith.\nRequire Import Bool.\nRequire Import List.\nOpen Scope Z_scope.\n\nInductive sorted : list Z -> Prop :=\n | sortedzer : sorted nil\n | sortedone : forall x : Z, sorted ( x :: nil )\n | sortedres : forall ( x y : Z ) ( l : list Z ) ,\n                  x <= y -> sorted ( y :: l ) -> sorted ( x :: y :: l ).\n\nTheorem sorted_inv : forall ( z : Z ) ( l : list Z ),\n                       sorted ( z :: l ) -> sorted l.\nProof.\n  intros z l H. inversion H. apply sortedzer. auto.\nQed.\n\nPrint  Z_le_gt_dec.\nFixpoint aux ( n : Z ) ( l : list Z ) : list Z :=\n  match l with\n    | nil => n :: nil\n    | ( p :: l' ) => if Z_le_gt_dec n p then p :: ( aux n l' )\n                     else n :: p :: l'\n  end.\n\nTheorem aux_equiv :\n  forall ( x : Z ) ( l : list Z ), aux x l = x :: l.\nProof.\n  intros x l. unfold aux. Admitted.\n\nTheorem imp_trans :\n  forall ( P Q R : Prop ), ( P -> Q ) -> ( Q -> R ) -> P -> R.\nProof.\n  intros P Q R H1 H2 p. apply H2. apply H1. apply p.\nQed.\n\nLemma weak_peirce :\n  forall ( P Q : Prop ), (((( P -> Q ) -> P ) -> P ) -> Q ) -> Q.\nProof.                      \n  intros P Q H. apply H. intros H1. apply H1. intros H2.\n  apply H. intros H3. apply H2.\nQed.\n\nCheck le 3 4.\nCheck and.\nCheck fst.\nCheck ( forall ( P : Prop ), P -> P ).\nCheck ( true = false ).\nCheck list Prop.\nOpen Scope nat_scope.\nDefinition lt ( n p : nat ) : Prop := S n <= p.\n\nTheorem conv_example :\n  forall n : nat , 7 * 5 < n -> 6 * 6 <= n.\nProof.\n  intros n H. assumption.\nQed.\n\nPrint conv_example.\nCheck ( imp_trans _ _ _ ( le_S 0 1 ) ( le_S 0 2 ) ).\n\nDefinition neutral_left ( A : Set ) ( op : A -> A -> A ) ( e : A ) : Prop :=\n  forall x : A, op e x = x.\n\nTheorem one_neutral_left : neutral_left Z Zmult 1%Z.\nProof.\n  unfold neutral_left. intros x. omega.\nQed.\n\nTheorem all_imp_dist :\n  forall ( A : Type ) ( P Q : A -> Type ),\n    (forall x : A, P x -> Q x ) -> ( forall y : A , P y ) -> forall z : A , Q z.\nProof.\n  intros A P Q H1 H2 z.\n  apply H1. apply H2.\nQed.\n\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 le_trans with ( m := c * b ).\n  Search ( _ <= _ -> _ * _ <= _ * _ ).\n  apply mult_le_compat_r. assumption.\n  apply mult_le_compat_l. assumption.\nQed.\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  eapply mult_le_compat_l. eexact H2.\n  apply mult_le_compat_r. assumption.\nQed.\n\nTheorem lt_S :\n  forall n p : nat, n < p -> n < S p.\nProof.\n  intros n p H. apply le_S. trivial.\nQed.\n\nDefinition opaque_f : nat -> nat -> nat.\n  intros. assumption.\nQed.\n\nPrint opaque_f.\nOpen Scope Z_scope.\n\nDefinition Zsquare_diff ( x y : Z ) : Z := (x * x - y * y).\nTheorem unfold_example:\n  forall x y : Z, x * x = y * y  ->\n                  ( Zsquare_diff x y )%Z * Zsquare_diff ( x + y ) ( x + y ) = 0.\nProof.\n  intros x y H. unfold Zsquare_diff at 1. rewrite -> H.\n  SearchAbout ( _ * _ - _ * _ ).\nAdmitted.\n\n\nSection ex_falso_quodlibet.\n  Hypothesis ff : False.\n  Lemma ex1 : 220 = 284.\n  Proof.\n    apply False_ind. exact ff.\n  Qed.\n  Lemma ex2 : 220 = 284.\n  Proof.\n    elim ff.\n  Qed.\nEnd ex_falso_quodlibet.\n\nPrint ex2.\nTheorem absurd : forall P Q : Prop, P -> ~P -> Q.\nProof.\n  intros P Q p H. elim H. assumption.\nQed.\n\nTheorem double_neg_i :\n  forall P : Prop, P -> ~~P.\nProof.\n  intros P p H. elim H. assumption.\nQed.\n\nTheorem modus_ponens :\n  forall P Q : Prop, P -> ( P -> Q ) -> Q.\nProof.\n  intros P Q p H. apply H. assumption.\nQed.\n\nTheorem double_neg_i' :\n  forall P : Prop, P -> ~~P.\nProof.\n  intros P. Proof ( modus_ponens P False ).\n\nTheorem contrap :\n     forall A B : Prop, ( A -> B ) -> ( ~B -> ~A ).\nProof.\n  intros A B. unfold not.\n  intros H1 H2 a. apply H2. apply H1. assumption.\nQed.\n\nTheorem not_false : ~False.\nProof.\n  unfold not. intros H. assumption.\nQed.\n\nTheorem not_not_not_p :\n  forall P Q : Prop, ~~~P -> P -> Q.\nProof.\n  intros P Q. unfold not. intros H p. elim H.\n  intros H1. apply H1. assumption.\nQed.\n\nTheorem ex_imp_ex :\n  forall ( A : Type ) ( P Q : A -> Prop ),\n    ( ex P ) -> ( forall x : A, P x -> Q x ) -> ex Q.\nProof.\n  intros A P Q H1 H2.\n  inversion H1. exists x.\n  apply H2. assumption.\nQed.\n\nTheorem ex_PQ :\n  forall ( A : Set ) ( P Q : A -> Prop ),\n    ( exists  x : A, ( P x \\/ Q x )) ->  ( ex P ) \\/ ( ex Q ).\nProof.\n  intros A P Q H.\n  inversion H. inversion H0 as [ HP | HQ ].\n  left. exists x. assumption.\n  right. exists x. assumption.\nQed.\n\nTheorem diff_square :\n  forall a b : Z,\n    ( a + b ) * ( a - b ) = a * a - b * b .\nProof.\n  intros a b.\n  Require Import ZArithRing.\n  ring.\nQed.\n\n(*\nDefinition my_true : Prop :=\n  forall P : Prop, P -> P.\nDefinition my_false : Prop :=\n  forall P : Prop, P.\nTheorem my_I : my_true.\nproof.\n  unfold my_true. intros P p. assumption.\n*)\n  \nSection inject_example.\n  Variables A B : Set.\n  Inductive T : Set :=\n  | cone : A -> T\n  | ctwo : B -> T.\n  Theorem inject_ctwo :\n    forall x y : B, ctwo x = ctwo y -> x = y.\n  Proof.\n    intros x y H.\n    change ( let phi :=  fun ( v : T ) =>\n      match v with\n       | cone _ => x\n       | ctwo v' => v'\n      end in phi ( ctwo x ) = phi ( ctwo y )).\n    rewrite H. reflexivity.   \n  Qed.\nEnd inject_example.\n\nPrint nat_ind.\n\nVariable div_pair :\n  forall a b : Z, 0 < b ->\n                  { p : Z * Z | a = ( fst p ) * b + snd p /\\ 0 <= snd p < b}.\n\nEval compute in div_pair 4 5.\n\nDefinition pred' :\n  forall n : nat, { p : nat | n = S p }+{ n = O }.\n  intros n. case n.\n  right. apply refl_equal.\n  intros p.left. exists p. reflexivity.\nDefined.\n\n", "meta": {"author": "tabtab777", "repo": "Coq", "sha": "4ffc37f0c970349ef1942a1519b729c6e5cba581", "save_path": "github-repos/coq/tabtab777-Coq", "path": "github-repos/coq/tabtab777-Coq/Coq-4ffc37f0c970349ef1942a1519b729c6e5cba581/CoqArtChapterOne.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.6970802719314325}}
{"text": "Require Import Coq.Lists.List Setoid Coq.Lists.SetoidList Omega.\nRequire Export Coq.Classes.EquivDec FinTypes.\n\nSet Implicit Arguments.\n\nFixpoint take n X (L:list X) :=\n  match n, L with\n    | S n, x::L => x::take n L\n    | _, _ => nil\n  end.\n\nLemma take_nil (X:Type) n\n  : @take n X nil = nil.\nProof.\n  destruct n; eauto.\nQed.\n\nLemma take_length_le X (L:list X) n\n  : n <= length L -> length (take n L) = n.\nProof.\n  intros. revert dependent n;induction L;intros; destruct n; simpl in *; try omega; eauto.\n  rewrite IHL; eauto; omega.\nQed.\n\n\nLemma take_length_ge X (L:list X) n\n  : n >= length L -> length (take n L) = length L.\nProof.\n  intros. revert dependent n; induction L;intros; destruct n; simpl in *; try omega; eauto.\n  rewrite IHL; eauto; omega.\nQed.\n\nLemma take_length X (L:list X) n\n  : length (take n L) = min (length L) n.\nProof.\n  decide (n < length L). \n  - rewrite take_length_le; try omega.\n    rewrite min_r; omega.\n  - eapply not_lt in n0.\n    rewrite min_l; try omega.\n    eapply take_length_ge; eauto.\nQed.\n\n Lemma map_take X Y (f:X -> Y) (L:list X) n\n  : map f (take n L) = take n (map f L).\nProof.\n  revert dependent L; induction n;intros; simpl; eauto.\n  destruct L; simpl ; eauto.\n  f_equal; eauto.\nQed.\n\nLemma take_app_le n X (L L':list X)\n  : n <= length L\n    -> take n (L ++ L') = take n L.\nProof.\n  intros. revert dependent L; induction n; intros ; simpl; eauto.\n  destruct L; [cbn in H; omega| ] ; simpl.\n  rewrite IHn; eauto. simpl in *; omega.\nQed.\n\nLemma take_app_ge n X (L L':list X)\n  : n >= length L\n    -> take n (L ++ L') = L ++ take (n - length L) L'.\nProof.\n  intros. revert dependent L; induction n;intros; simpl; eauto.\n  - destruct L; simpl in *; eauto. exfalso; omega.\n  - destruct L; simpl in *; eauto.\n    rewrite IHn; eauto. omega.\nQed.\n\nLemma take_eq_ge n X (L:list X)\n  : n >= |L| -> take n L = L.\nProof.\n  intros. revert dependent L; induction n;intros; destruct L; simpl in *; eauto.\n  - exfalso; omega.\n  - rewrite IHn; eauto. omega.\nQed.\n\n\nLemma take_app_eq n X (L L':list X)\n  : n = length L\n    -> take n (L ++ L') = L.\nProof.\n  intros. subst. revert dependent L'; induction L;intros; simpl; eauto.\n  f_equal; eauto.\nQed.\n\nLemma take_take_lt X (L:list X) n m\n  : n < m\n    -> take n L = take n (take m L).\nProof.\n  intros. revert dependent L; revert dependent m;  induction n;intros; destruct L, m; simpl; eauto.\n  - omega.\n  - erewrite IHn; eauto. omega.\nQed.\n\nLemma take_one X (L:list X) x k\n  : k > 0\n    -> take k (x::L) = x :: take (k - 1) L.\nProof.\n  intros; destruct k; simpl.\n  - omega.\n  - f_equal. f_equal. omega.\nQed.\n", "meta": {"author": "cdl-saarland", "repo": "uniana", "sha": "abef56560e9b1b2e8653f732b4c14a823125f212", "save_path": "github-repos/coq/cdl-saarland-uniana", "path": "github-repos/coq/cdl-saarland-uniana/uniana-abef56560e9b1b2e8653f732b4c14a823125f212/uniana/external/lvc/Take.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.6970802710971961}}
{"text": "(** * Maps: Total and Partial Maps *)\n\n(** This file is almost identical to the [Maps] chapter of Software\n    Foundations volume 1 (Logical Foundations), except that it implements\n    functions from [nat] to [A] rather than functions from [id] to [A].\n\n    Maps (or dictionaries) are ubiquitous data structures, both in\n    software construction generally and in the theory of programming\n    languages in particular; we're going to need them in many places\n    in the coming chapters.  They also make a nice case study using\n    ideas we've seen in previous chapters, including building data\n    structures out of higher-order functions (from [Basics] and\n    [Poly]) and the use of reflection to streamline proofs (from\n    [IndProp]).\n\n    We'll define two flavors of maps: _total_ maps, which include a\n    \"default\" element to be returned when a key being looked up\n    doesn't exist, and _partial_ maps, which return an [option] to\n    indicate success or failure.  The latter is defined in terms of\n    the former, using [None] as the default element. *)\n\n(* ################################################################# *)\n(** * The Coq Standard Library *)\n\n(** One small digression before we start.\n\n    Unlike the chapters we have seen so far, this one does not\n    [Require Import] the chapter before it (and, transitively, all the\n    earlier chapters).  Instead, in this chapter and from now, on\n    we're going to import the definitions and theorems we need\n    directly from Coq's standard library stuff.  You should not notice\n    much difference, though, because we've been careful to name our\n    own definitions and theorems the same as their counterparts in the\n    standard library, wherever they overlap. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(** Documentation for the standard library can be found at\n    http://coq.inria.fr/library/.  \n\n    The [Search] command is a good way to look for theorems \n    involving objects of specific types. *)\n\n\n(* ################################################################# *)\n(** * Total Maps *)\n\n(** Our main job in this chapter will be to build a definition of\n    partial maps that is similar in behavior to the one we saw in the\n    [Lists] chapter, plus accompanying lemmas about their behavior.\n\n    This time around, though, we're going to use _functions_, rather\n    than lists of key-value pairs, to build maps.  The advantage of\n    this representation is that it offers a more _extensional_ view of\n    maps, where two maps that respond to queries in the same way will\n    be represented as literally the same thing (the same function),\n    rather than just \"equivalent\" data structures.  This, in turn,\n    simplifies proofs that use maps.\n\n    We build partial maps in two steps.  First, we define a type of\n    _total maps_ that return a default value when we look up a key\n    that is not present in the map. *)\n\nDefinition total_map (A:Type) := nat -> A.\n\n(** Intuitively, a total map over an element type [A] _is_ just a\n    function that can be used to look up [id]s, yielding [A]s.\n\n    The function [t_empty] yields an empty total map, given a default\n    element; this map always returns the default element when applied\n    to any id. *)\n\nDefinition t_empty {A:Type} (v : A) : total_map A :=\n  (fun _ => v).\n\n(** More interesting is the [update] function, which (as before) takes\n    a map [m], a key [x], and a value [v] and returns a new map that\n    takes [x] to [v] and takes every other key to whatever [m] does. *)\n\nDefinition t_update {A:Type} (m : total_map A)\n                    (x : nat) (v : A) :=\n  fun x' => if beq_nat x x' then v else m x'.\n\n(** This definition is a nice example of higher-order programming.\n    The [t_update] function takes a _function_ [m] and yields a new\n    function [fun x' => ...] that behaves like the desired map.\n\n    For example, we can build a map taking [id]s to [bool]s, where [Id\n    3] is mapped to [true] and every other key is mapped to [false],\n    like this: *)\n\nDefinition examplemap :=\n  t_update (t_update (t_empty false) 1 false) 3 true.\n\n(** This completes the definition of total maps.  Note that we don't\n    need to define a [find] operation because it is just function\n    application! *)\n\nExample update_example1 : examplemap 0 = false.\nProof. reflexivity. Qed.\n\nExample update_example2 : examplemap 1 = false.\nProof. reflexivity. Qed.\n\nExample update_example3 : examplemap 2 = false.\nProof. reflexivity. Qed.\n\nExample update_example4 : examplemap 3 = true.\nProof. reflexivity. Qed.\n\n(** To use maps in later chapters, we'll need several fundamental\n    facts about how they behave.  Even if you don't work the following\n    exercises, make sure you thoroughly understand the statements of\n    the lemmas!  (Some of the proofs require the functional\n    extensionality axiom, which is discussed in the [Logic]\n    chapter and included in the Coq standard library.) *)\n\n(** **** Exercise: 1 star, optional (t_apply_empty)  *)\n(** First, the empty map returns its default element for all keys: *)\nLemma t_apply_empty:  forall A x v, @t_empty A v x = v.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_eq)  *)\n(** Next, if we update a map [m] at a key [x] with a new value [v]\n    and then look up [x] in the map resulting from the [update], we\n    get back [v]: *)\n\nLemma t_update_eq : forall A (m: total_map A) x v,\n  (t_update m x v) x = v.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_neq)  *)\n(** On the other hand, if we update a map [m] at a key [x1] and then\n    look up a _different_ key [x2] in the resulting map, we get the\n    same result that [m] would have given: *)\n\nTheorem t_update_neq : forall (X:Type) v x1 x2\n                         (m : total_map X),\n  x1 <> x2 ->\n  (t_update m x1 v) x2 = m x2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_shadow)  *)\n(** If we update a map [m] at a key [x] with a value [v1] and then\n    update again with the same key [x] and another value [v2], the\n    resulting map behaves the same (gives the same result when applied\n    to any key) as the simpler map obtained by performing just\n    the second [update] on [m]: *)\n\nLemma t_update_shadow : forall A (m: total_map A) v1 v2 x,\n    t_update (t_update m x v1) x v2\n  = t_update m x v2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** For the final two lemmas about total maps, it's convenient to use\n    the reflection idioms introduced in chapter [IndProp].  We begin\n    by proving a fundamental _reflection lemma_ relating the equality\n    proposition on [id]s with the boolean function [beq_id]. *)\n\n(** **** Exercise: 2 stars (beq_idP)  *)\n(** Use the proof of [beq_natP] in chapter [IndProp] as a template to\n    prove the following: *)\n\nLemma beq_idP : forall x y, reflect (x = y) (beq_nat x y).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Now, given [id]s [x1] and [x2], we can use the [destruct (beq_idP\n    x1 x2)] to simultaneously perform case analysis on the result of\n    [beq_id x1 x2] and generate hypotheses about the equality (in the\n    sense of [=]) of [x1] and [x2]. *)\n\n(** **** Exercise: 2 stars (t_update_same)  *)\n(** Using the example in chapter [IndProp] as a template, use\n    [beq_idP] to prove the following theorem, which states that if we\n    update a map to assign key [x] the same value as it already has in\n    [m], then the result is equal to [m]: *)\n\nTheorem t_update_same : forall X x (m : total_map X),\n  t_update m x (m x) = m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (t_update_permute)  *)\n(** Use [beq_idP] to prove one final property of the [update]\n    function: If we update a map [m] at two distinct keys, it doesn't\n    matter in which order we do the updates. *)\n\nTheorem t_update_permute : forall (X:Type) v1 v2 x1 x2\n                             (m : total_map X),\n  x2 <> x1 ->\n    (t_update (t_update m x2 v2) x1 v1)\n  = (t_update (t_update m x1 v1) x2 v2).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Partial maps *)\n\n(** Finally, we define _partial maps_ on top of total maps.  A partial\n    map with elements of type [A] is simply a total map with elements\n    of type [option A] and default element [None]. *)\n\nDefinition partial_map (A:Type) := total_map (option A).\n\nDefinition empty {A:Type} : partial_map A :=\n  t_empty None.\n\nDefinition update {A:Type} (m : partial_map A)\n                  (x : nat) (v : A) :=\n  t_update m x (Some v).\n\n(** We can now lift all of the basic lemmas about total maps to\n    partial maps.  *)\n\nLemma apply_empty : forall A x, @empty A x = None.\nProof.\n  intros. unfold empty. rewrite t_apply_empty.\n  reflexivity.\nQed.\n\nLemma update_eq : forall A (m: partial_map A) x v,\n  (update m x v) x = Some v.\nProof.\n  intros. unfold update. rewrite t_update_eq.\n  reflexivity.\nQed.\n\nTheorem update_neq : forall (X:Type) v x1 x2\n                       (m : partial_map X),\n  x2 <> x1 ->\n  (update m x2 v) x1 = m x1.\nProof.\n  intros X v x1 x2 m H.\n  unfold update. rewrite t_update_neq. reflexivity.\n  apply H. Qed.\n\nLemma update_shadow : forall A (m: partial_map A) v1 v2 x,\n  update (update m x v1) x v2 = update m x v2.\nProof.\n  intros A m v1 v2 x1. unfold update. rewrite t_update_shadow.\n  reflexivity.\nQed.\n\nTheorem update_same : forall X v x (m : partial_map X),\n  m x = Some v ->\n  update m x v = m.\nProof.\n  intros X v x m H. unfold update. rewrite <- H.\n  apply t_update_same.\nQed.\n\nTheorem update_permute : forall (X:Type) v1 v2 x1 x2\n                                (m : partial_map X),\n  x2 <> x1 ->\n    (update (update m x2 v2) x1 v1)\n  = (update (update m x1 v1) x2 v2).\nProof.\n  intros X v1 v2 x1 x2 m. unfold update.\n  apply t_update_permute.\nQed.\n\n(** $Date: 2017-08-22 17:13:32 -0400 (Tue, 22 Aug 2017) $ *)\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/wand_demo/vfa/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.8705972684083608, "lm_q1q2_score": 0.6970802698611593}}
{"text": "From Coq Require Import NArith ZArith Lia.\n\nFrom Vyper Require Import Logic2.\n\n(**************************************************************************)\n\nLemma N_ltb_lt_quad (a b c d: N):\n  ((a <? b)%N = (c <? d)%N) <-> ((a < b)%N <-> (c < d)%N).\nProof.\napply relation_quad; apply N.ltb_lt.\nQed.\n\nLemma Z_ltb_lt_quad (a b c d: Z):\n  ((a <? b)%Z = (c <? d)%Z) <-> ((a < b)%Z <-> (c < d)%Z).\nProof.\napply relation_quad; apply Z.ltb_lt.\nQed.\n\nLemma N_leb_le_quad (a b c d: N):\n  ((a <=? b)%N = (c <=? d)%N) <-> ((a <= b)%N <-> (c <= d)%N).\nProof.\napply relation_quad; apply N.leb_le.\nQed.\n\nLemma Z_leb_le_quad (a b c d: Z):\n  ((a <=? b)%Z = (c <=? d)%Z) <-> ((a <= b)%Z <-> (c <= d)%Z).\nProof.\napply relation_quad; apply Z.leb_le.\nQed.\n\nLemma N2Z_ltb (n m: N):\n  (n <? m)%N = (Z.of_N n <? Z.of_N m)%Z.\nProof.\napply (relation_quad N.ltb_lt Z.ltb_lt).\napply N2Z.inj_lt.\nQed.\n\nLemma N2Z_leb (n m: N):\n  (n <=? m)%N = (Z.of_N n <=? Z.of_N m)%Z.\nProof.\napply (relation_quad N.leb_le Z.leb_le).\napply N2Z.inj_le.\nQed.\n\n(**************************************************************************)\n\nLemma Z_shiftr_pow2 (n: Z) (B: (0 <= n)%Z):\n  Z.shiftr (2 ^ n) n = 1%Z.\nProof.\nrewrite (Z.shiftr_div_pow2 _ _ B).\napply Z.div_same.\nnow apply Z.pow_nonzero.\nQed.\n\nLemma Z_ltb_irrefl (n: Z):\n  (n <? n)%Z = false.\nProof.\nremember (n <? n)%Z as L.\ndestruct L; trivial.\nsymmetry in HeqL.\nrewrite Z.ltb_lt in HeqL.\napply Z.lt_irrefl in HeqL.\ncontradiction.\nQed.\n\nLemma N_ltb_irrefl (n: N):\n  (n <? n)%N = false.\nProof.\nremember (n <? n)%N as L.\ndestruct L; trivial.\nsymmetry in HeqL.\nrewrite N.ltb_lt in HeqL.\napply N.lt_irrefl in HeqL.\ncontradiction.\nQed.\n\n(**************************************************************************)\n\nLemma Z_land_pow2_shift (n m: Z) (BM: (0 <= m)%Z):\n  Z.land n (2 ^ m) = Z.shiftl (Z.land (Z.shiftr n m) 1) m.\nProof.\nrewrite<- (Z_shiftr_pow2 m BM).\nrewrite<- Z.shiftr_land.\nrewrite<- (Z.ldiff_ones_r _ _ BM).\nrewrite Z.ldiff_land.\nrewrite<- Z.land_assoc.\nf_equal.\napply Z.bits_inj'. intros k Bk.\nrewrite Z.land_spec.\nrewrite (Z.lnot_spec _ _ Bk).\nrewrite (Z.testbit_ones _ _ BM).\nrewrite (Z.pow2_bits_eqb _ _ BM).\nrewrite<- Z.leb_le in Bk.\nrewrite Bk.\nrewrite Bool.andb_true_l.\nremember (m =? k)%Z as MK. symmetry in HeqMK.\ndestruct MK. \n{\n  rewrite Z.eqb_eq in HeqMK. subst.\n  now rewrite Z_ltb_irrefl.\n}\ntrivial.\nQed.\n\nLemma Z_mul_pos_iff_l (n m: Z) (BM: (0 < m)%Z):\n  (0 < n)%Z <-> (0 < n * m)%Z.\nProof.\nsplit. { intro. apply Z.mul_pos_pos; assumption. }\napply (Z.mul_pos_cancel_r _ _ BM).\nQed.\n\nLemma Z_mul_pos_iff_r (n m: Z) (BN: (0 < n)%Z):\n  (0 < m)%Z <-> (0 < n * m)%Z.\nProof.\nsplit. { apply (Z.mul_pos_pos _ _ BN). }\napply (Z.mul_pos_cancel_l _ _ BN).\nQed.\n\nLemma Z_shiftl_pos_iff (n m: Z) (BM: (0 <= m)%Z):\n (0 < n)%Z <-> (0 < Z.shiftl n m)%Z.\nProof.\nrewrite (Z.shiftl_mul_pow2 _ _ BM).\napply Z_mul_pos_iff_l.\napply Z.pow_pos_nonneg.\n{ rewrite<- Z.ltb_lt. trivial. }\nassumption.\nQed.\n\nLemma Z_odd_land_1 (n: Z) (B: (0 <= n)%Z):\n  Z.odd n = (0 <? Z.land n 1)%Z.\nProof.\ndestruct n; now try destruct p.\nQed.\n\nLemma Z_testbit_alt (n m: Z) (BN: (0 <= n)%Z) (BM: (0 <= m)%Z):\n  Z.testbit n m = (0 <? Z.land n (2 ^ m))%Z.\nProof.\nrewrite (Z_land_pow2_shift _ _ BM).\nassert (Q: forall x, ((0 <? Z.shiftl x m) = (0 <? x))%Z).\n{\n  intro x.\n  rewrite Z_ltb_lt_quad.\n  symmetry.\n  apply Z_shiftl_pos_iff.\n  assumption.\n}\nrewrite Q. clear Q.\nrewrite Z.testbit_odd.\napply Z_odd_land_1.\napply Z.shiftr_nonneg.\nassumption.\nQed.\n\nLemma Z_testbit_high (a n: Z)\n                      (B: (0 <= n)%Z)\n                      (A: (0 <= a < 2 ^ n)%Z):\n  Z.testbit a n = false.\nProof.\nrewrite<- (Z.mod_small a (2 ^ n)%Z A).\napply Z.mod_pow2_bits_high.\nsplit. { assumption. }\napply Z.le_refl.\nQed.\n\n(**************************************************************************)\n\nLemma Z_to_N_land (x y: Z) (BX: (0 <= x)%Z) (BY: (0 <= y)%Z):\n  Z.to_N (Z.land x y) = N.land (Z.to_N x) (Z.to_N y).\nProof.\napply N.bits_inj. intro n.\nrewrite N.land_spec.\nremember (Z.of_N n) as m.\nassert (NM: n = Z.to_N m).\n{ subst m. symmetry. apply N2Z.id. }\nrepeat rewrite NM.\nassert (BM: (0 <= m)%Z).\n{ subst. apply N2Z.is_nonneg. }\nrepeat rewrite<- Z2N.inj_testbit; try assumption.\nrepeat rewrite Z2N.id; try assumption.\n{ apply Z.land_spec. }\nrewrite Z.land_nonneg. tauto.\nQed.\n\n\nLemma N_to_Z_land (x y: N):\n  Z.of_N (N.land x y) = Z.land (Z.of_N x) (Z.of_N y).\nProof.\nrewrite<- (Z2N.id (Z.land (Z.of_N x) (Z.of_N y))).\n{\n  f_equal.\n  rewrite Z_to_N_land; try apply N2Z.is_nonneg.\n  repeat rewrite N2Z.id.\n  trivial.\n}\napply Z.land_nonneg. left. apply N2Z.is_nonneg.\nQed.\n\nLemma Z_to_N_lor (x y: Z) (BX: (0 <= x)%Z) (BY: (0 <= y)%Z):\n  Z.to_N (Z.lor x y) = N.lor (Z.to_N x) (Z.to_N y).\nProof.\napply N.bits_inj. intro n.\nrewrite N.lor_spec.\nremember (Z.of_N n) as m.\nassert (NM: n = Z.to_N m).\n{ subst m. symmetry. apply N2Z.id. }\nrepeat rewrite NM.\nassert (BM: (0 <= m)%Z).\n{ subst. apply N2Z.is_nonneg. }\nrepeat rewrite<- Z2N.inj_testbit; try assumption.\nrepeat rewrite Z2N.id; try assumption.\n{ apply Z.lor_spec. }\nrewrite Z.lor_nonneg. tauto.\nQed.\n\nLemma N_to_Z_lor (x y: N):\n  Z.of_N (N.lor x y) = Z.lor (Z.of_N x) (Z.of_N y).\nProof.\nrewrite<- (Z2N.id (Z.lor (Z.of_N x) (Z.of_N y))).\n{\n  f_equal.\n  rewrite Z_to_N_lor; try apply N2Z.is_nonneg.\n  repeat rewrite N2Z.id.\n  trivial.\n}\napply Z.lor_nonneg. split; apply N2Z.is_nonneg.\nQed.\n\nLemma Z_to_N_lxor (x y: Z) (BX: (0 <= x)%Z) (BY: (0 <= y)%Z):\n  Z.to_N (Z.lxor x y) = N.lxor (Z.to_N x) (Z.to_N y).\nProof.\napply N.bits_inj. intro n.\nrewrite N.lxor_spec.\nremember (Z.of_N n) as m.\nassert (NM: n = Z.to_N m).\n{ subst m. symmetry. apply N2Z.id. }\nrepeat rewrite NM.\nassert (BM: (0 <= m)%Z).\n{ subst. apply N2Z.is_nonneg. }\nrepeat rewrite<- Z2N.inj_testbit; try assumption.\nrepeat rewrite Z2N.id; try assumption.\n{ apply Z.lxor_spec. }\nrewrite Z.lxor_nonneg. tauto.\nQed.\n\nLemma N_to_Z_lxor (x y: N):\n  Z.of_N (N.lxor x y) = Z.lxor (Z.of_N x) (Z.of_N y).\nProof.\nrewrite<- (Z2N.id (Z.lxor (Z.of_N x) (Z.of_N y))).\n{\n  f_equal.\n  rewrite Z_to_N_lxor; try apply N2Z.is_nonneg.\n  repeat rewrite N2Z.id.\n  trivial.\n}\napply Z.lxor_nonneg. split; intro; apply N2Z.is_nonneg.\nQed.\n\n(**************************************************************************)\n\nLemma N_testbit_alt (n m: N):\n  N.testbit n m = (0 <? N.land n (2 ^ m))%N.\nProof.\nrewrite<- Z.testbit_of_N.\nreplace (0 <? N.land n (2 ^ m))%N with (0 <? Z.land (Z.of_N n) (2 ^ (Z.of_N m)))%Z.\n2:{\n  rewrite N2Z_ltb.\n  rewrite N_to_Z_land.\n  cbn.\n  repeat f_equal.\n  rewrite N2Z.inj_pow.\n  trivial.\n}\napply Z_testbit_alt; apply N2Z.is_nonneg.\nQed.\n\n(**************************************************************************)\n\nDefinition N_0_lt_pow2 (n: N):\n  (0 < 2 ^ n)%N.\nProof.\ncase (N.eq_0_gt_0_cases (2 ^ n)); intro; try assumption.\napply N.pow_nonzero in H. { contradiction. }\ndiscriminate.\nQed.\n\nDefinition Z_0_lt_pow2 (n: Z) (B: (0 <= n)%Z):\n  (0 < 2 ^ n)%Z.\nProof.\nassert (A := N_0_lt_pow2 (Z.to_N n)).\napply N2Z.inj_lt in A.\nrewrite N2Z.inj_pow in A.\ncbn in A.\nnow rewrite Z2N.id in A.\nQed.\n\nLemma N_ne_0_gt_0 (n: N):\n  n <> 0%N <-> (0 < n)%N.\nProof.\nsplit; intro H.\n{ assert (CN := N.eq_0_gt_0_cases n). tauto. }\ndestruct n. { now apply N.lt_irrefl in H. }\ndiscriminate.\nQed.\n\nLemma N_div_0_r (n: N):\n  (n / 0 = 0)%N.\nProof.\nnow destruct n.\nQed.\n\nLemma Z_div_0_r (n: Z):\n  (n / 0 = 0)%Z.\nProof.\nnow destruct n.\nQed.\n\nLemma N_div_le (n: N) (d: N):\n  (n / d <= n)%N.\nProof.\nassert (CN := N.eq_0_gt_0_cases n).\nassert (CD := N.eq_0_gt_0_cases d).\ncase CN; intro. { subst. cbn. apply N.le_refl. }\ncase CD; intro. { subst. rewrite N_div_0_r. now apply N.lt_le_incl. }\nassert (D: N.succ (N.pred d) = d).\n{ apply N.succ_pred_pos. assumption. }\nremember (N.pred d) as k. clear Heqk. subst.\nassert (CK := N.eq_0_gt_0_cases k).\ncase CK; intro. { subst. cbn. now rewrite N.div_1_r. }\napply N.lt_le_incl.\napply N.div_lt. { assumption. }\nnow apply N.lt_pred_lt_succ.\nQed.\n\nLemma Z_div_nonneg (a b: Z)\n                    (A: (0 <= a)%Z)\n                    (B: (0 <= b)%Z):\n  (0 <= a / b)%Z.\nProof.\ndestruct b. { rewrite Zdiv_0_r. apply Z.le_refl. }\n{ apply Z.div_pos; easy. }\neasy.\nQed.\n\nLemma Z_abs_div_le (a b: Z):\n  (Z.abs a / Z.abs b <= Z.abs a)%Z.\nProof.\nassert(A := Z.abs_nonneg a).\nassert(B := Z.abs_nonneg b).\napply Z2N.inj_le. { now apply Z_div_nonneg. }\n{ assumption. }\nrewrite Z2N.inj_div; try assumption.\napply N_div_le.\nQed.\n\nLemma Z_abs_sgn (a b: Z):\n  Z.abs (Z.sgn a * b)%Z = match a with\n                          | 0%Z => 0%Z\n                          | _ => Z.abs b\n                          end.\nProof.\nnow destruct a, b.\nQed.\n\nLemma Z_sgn_abs (a: Z):\n  (Z.sgn a * Z.abs a)%Z = a.\nProof.\nnow destruct a.\nQed.\n\nLemma Z_add_nocarry_lor (a b: Z) (H: Z.land a b = 0%Z):\n  (a + b = Z.lor a b)%Z.\nProof.\nrewrite Z.add_nocarry_lxor by assumption.\napply Z.lxor_lor. assumption.\nQed.\n\nLemma Z_land_pow2_small (a b: Z) (A: (0 <= a < 2 ^ b)%Z) (B: (0 <= b)%Z):\n  Z.land a (2 ^ b) = 0%Z.\nProof.\nrewrite Arith2.Z_land_pow2_shift by tauto.\nreplace (Z.shiftr a b) with 0%Z. { cbn. apply Z.shiftl_0_l. }\nrewrite Z.shiftr_div_pow2 by tauto.\nsymmetry. apply Z.div_small. exact A.\nQed.\n\nLemma Z_testbit_flag_mul_pow2 (f: bool) (k: Z) (K: (0 <= k)%Z):\n  Z.testbit ((if f then 1 else 0) * 2 ^ k) k = f.\nProof.\ndestruct f.\n{ rewrite Z.mul_1_l. apply Z.pow2_bits_true. assumption. }\nrewrite Z.mul_0_l. apply Z.bits_0.\nQed.\n\n(* A version of Z.bits_above_log2 with a different bound. *)\nLemma Z_testbit_small (a n: Z) (A: (0 <= a)%Z)\n                               (B: (a < 2 ^ n)%Z):\n  Z.testbit a n = false.\nProof.\ndestruct a. { apply Z.testbit_0_l. }\n{ apply Z.bits_above_log2. trivial. now apply Z.log2_lt_pow2. }\nexfalso. rewrite<- Z.leb_le in A. cbn in A. discriminate.\nQed.\n\n(**************************************************************************)\n\nLemma Z_pos_ne_0 (a: positive):\n  Z.pos a <> 0%Z.\nProof.\ndiscriminate.\nQed.\n\nLemma Z_0_lt_pos (a: positive):\n  (0 < Z.pos a)%Z.\nProof.\nrewrite<- Z.ltb_lt.\ntrivial.\nQed.\n\nLemma Z_ceiling_via_floor (a b: Z) (B: (0 <= b)%Z):\n  (- ((- a) / b) = (a + b - 1) / b)%Z.\nProof.\ndestruct b as [|b|b]. { now repeat rewrite Z_div_0_r. }\n{\n  assert (D := Z.div_mod (-a) (Z.pos b) (Z_pos_ne_0 b)).\n  assert (E := Z.div_mod (a + Z.pos b - 1) (Z.pos b) (Z_pos_ne_0 b)).\n  assert (P := Z.mod_pos_bound (-a) (Z.pos b) (Z_0_lt_pos b)).\n  assert (Q := Z.mod_pos_bound (a + Z.pos b - 1) (Z.pos b) (Z_0_lt_pos b)).\n  nia.\n}\nrewrite<- Z.leb_le in B. discriminate.\nQed.\n\n(**************************************************************************)\n\nLemma Z_land_lxor_distr_l (a b c: Z):\n  Z.land (Z.lxor a b) c = Z.lxor (Z.land a c) (Z.land b c).\nProof.\napply Z.bits_inj. intro.\nrepeat (rewrite Z.land_spec || rewrite Z.lxor_spec).\ndestruct (Z.testbit a n); destruct (Z.testbit b n); destruct (Z.testbit c n); easy.\nQed.\n\nLemma Z_land_lxor_distr_r (a b c: Z):\n  Z.land a (Z.lxor b c) = Z.lxor (Z.land a b) (Z.land a c).\nProof.\napply Z.bits_inj. intro.\nrepeat (rewrite Z.land_spec || rewrite Z.lxor_spec).\ndestruct (Z.testbit a n); destruct (Z.testbit b n); destruct (Z.testbit c n); easy.\nQed.\n\n(**************************************************************************)\n\n(* This is a version of Z.log2_lt_pow2 but a can be 0 and b cannot. *)\nLemma Z_log2_lt_pow2 (a b: Z) (BA: (0 <= a)%Z) (BB: (0 < b)%Z):\n    (a < 2 ^ b <-> Z.log2 a < b)%Z.\nProof.\ndestruct a.\n{\n  cbn. assert (P: (0 < 2 ^ b)%Z). apply Z_0_lt_pow2. { apply Z.lt_le_incl. assumption. }\n  tauto.\n}\n{ apply Z.log2_lt_pow2. rewrite<- Z.ltb_lt. trivial. }\nrewrite<- Z.leb_le in BA. discriminate.\nQed.\n\n(**************************************************************************)\n\nLemma Z_mod_add_l (a b c m: Z)\n                  (H: (b mod m = c mod m)%Z):\n  ((a + b) mod m = (a + c) mod m)%Z.\nProof.\nrewrite<- (Zplus_mod_idemp_r b a).\nrewrite<- (Zplus_mod_idemp_r c a).\nrewrite H.\ntrivial.\nQed.\n\nLemma Z_mod_add_r (a b c m: Z)\n                  (H: (a mod m = b mod m)%Z):\n  ((a + c) mod m = (b + c) mod m)%Z.\nProof.\nrewrite<- (Zplus_mod_idemp_l a c).\nrewrite<- (Zplus_mod_idemp_l b c).\nrewrite H.\ntrivial.\nQed.\n\n(**************************************************************************)\n\nLemma Nat2N_inj_div (a b: nat):\n  N.of_nat (a / b) = (N.of_nat a / N.of_nat b)%N.\nProof.\ndestruct b. { cbn. now rewrite N_div_0_r. }\nassert (BNZ: S b <> 0) by discriminate.\nassert (D := Nat.div_mod a (S b) BNZ).\nremember (a / S b) as q.\nremember (a mod S b) as r.\napply N.div_unique with (r := N.of_nat r).\n{\n  unfold N.lt.\n  rewrite<- Nat2N.inj_compare.\n  apply Nat.compare_lt_iff.\n  subst. apply (Nat.mod_upper_bound _ _ BNZ).\n}\nrewrite<- Nat2N.inj_mul.\nrewrite<- Nat2N.inj_add.\nnow rewrite D.\nQed.\n\nLemma Nat2N_inj_mod (a b: nat) (ok: b <> 0):\n  N.of_nat (a mod b) = (N.of_nat a mod N.of_nat b)%N.\nProof.\ndestruct b. { contradiction. }\nrewrite Nat.mod_eq by discriminate.\nrewrite Nat2N.inj_sub.\nrewrite Nat2N.inj_mul.\nrewrite Nat2N_inj_div.\nsymmetry. apply N.mod_eq.\ndiscriminate.\nQed.\n\n(**************************************************************************)\n(** This is a strenghtening of Pos.size_nat_monotone from [p < q] to [p <= q]. *)\nLemma Pos_size_nat_monotone (p q: positive) (LE: (p <= q)%positive):\n  (Pos.size_nat p <= Pos.size_nat q)%nat.\nProof.\nremember (Pos.compare p q) as cmp. symmetry in Heqcmp. destruct cmp.\n{ apply Pos.compare_eq in Heqcmp. subst. apply Nat.le_refl. }\n{ apply Pos.size_nat_monotone. exact Heqcmp. }\ncontradiction.\nQed.\n", "meta": {"author": "formalize", "repo": "coq-vyper", "sha": "8996c1534b9d56696f92b60031ff1523b3593690", "save_path": "github-repos/coq/formalize-coq-vyper", "path": "github-repos/coq/formalize-coq-vyper/coq-vyper-8996c1534b9d56696f92b60031ff1523b3593690/Lib2/Arith2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.697080259726012}}
{"text": "\n\nRequire Import NaturalNumbers.\nRequire Export ssreflect.\n\n\n\nTheorem Plus_unit_l :\n    forall n, Plus Z n n.\nProof. autoP. Qed.\n\n\n    Theorem Plus_unit_r n : Plus n Z n.\nProof.\n    elim n => [|m IHm]; autoP.\nQed.\n\nTheorem Plus_uniq :\n    forall x y z1 z2, Plus x y z1 -> Plus x y z2 -> z1 = z2.\nProof.\n    elim => [y z1 z2 H1 H2|x0 IH y z1 z2 H1 H2].\n    + (* x == Z *)\n      inversion H1.\n      inversion H2.\n      subst n n0 y => //.\n    + (* x ==  (S x0)*)\n      inversion H1.\n      inversion H2.\n      specialize (IH y l l0 H0 H6).\n      rewrite IH => //.\nQed.\n\n\nTheorem Plus_close :\n    forall x y, exists z, Plus x y z.\nProof.\n    move => x y.\n    elim x => [|x0 IHx].\n\n    + (* x == Z *)\n      exists y; apply Plus_unit_l.\n\n    + (* x == (S x0) *)\n      induction IHx as [z H].\n      exists (S z).\n      apply P_Succ => //.\nQed.\n\nTheorem P_Succ_r :\n    forall x y z, Plus x y z -> Plus x (S y) (S z).\nProof.\n    elim.\n    \n    + (* x == Z *)\n      move => y z H.\n      inversion H.\n      apply Plus_unit_l.\n\n    + (* x == (S x0) *)\n      move => x0 IH y z H.\n      inversion H.\n      apply P_Succ.\n      apply (IH y l) =>//.\nQed.\n\n\nTheorem Plus_comm :\n    forall x y z, Plus x y z -> Plus y x z.\nProof.\n    elim => [|n IHn].            \n\n    + (* x == Z *)\n      move => y z H.\n      inversion H.\n      apply Plus_unit_r.\n    \n    + (* x == (S n) *)\n      move => y z H.\n      inversion H.\n      apply P_Succ_r.\n      apply IHn => //.\nQed.\n\n\nTheorem Plus_assoc :\n    forall x y z xy xyz,\n    Plus x y xy -> Plus xy z xyz ->\n    exists yz, Plus y z yz /\\ Plus x yz xyz.\nProof.    \n    elim => [| x0 IHx].\n\n    + (* x == Z *)\n      move => y z xy xyz Hl Hr.\n      inversion Hl.\n      inversion Hr.\n\n      - subst n n0 xy.\n        exists xyz.\n        split; apply Plus_unit_l.\n\n      - subst n xy.\n        exists (S l).\n        split.\n        apply P_Succ=> //.\n        apply Plus_unit_l.\n   \n    + (* x == (S x0)*)\n      move => y z xy xyz Hl Hr.\n      inversion Hl; move => {Hl}.\n      subst n m xy.\n      inversion Hr => {Hr}.\n      subst n m xyz.\n      specialize (IHx y z l l0 H0 H1).\n      inversion IHx as [yz [Hl Hr]].\n      exists yz; split => //.\n      apply P_Succ => //.\nQed.\n\n\nTheorem Times_uniq :\n    forall x y z z', Times x y z -> Times x y z' -> z = z'.\nProof.\n    elim => [|x0 IHx].\n    + move => y z z' H1 H2.\n      inversion H1; inversion H2  => //.\n    + move => y z z' H1 H2.\n      inversion H1; inversion H2 => {H1 H2}.\n      subst n m o n0 m0 o0.\n      suff ll : l = l0.\n      - subst l0.\n        apply (Plus_uniq y l) => //.\n      - apply (IHx y l l0) => //.\nQed.          \n\n\nTheorem Times_close :\n    forall x y, exists z, Times x y z.\nProof.\n    move => x y.\n    elim  x=> [|x0 IHx].\n    + exists Z; apply T_Zero.\n    + inversion IHx as [z H]; move => {IHx}.\n      induction (Plus_close y z) as [yz Hyz].\n      exists yz.\n      apply T_Succ with (l := z) => //.\nQed.\n\nTheorem Times_zero_l :\n    forall n, Times Z n Z.\nProof. autoP. Qed.\n    \n\nTheorem Times_zero_r :\n    forall n, Times n Z Z.\nProof.\n    elim => [|n0 IHn].\n    + autoP.\n    + apply T_Succ with (l := Z); autoP.\nQed.\n\n\n\nLemma T_Succ_r :\n    forall n m l o,\n    Times n m l -> Plus n l o -> Times n (S m) o.\nProof.\n    move => n m.\n    induction n,  m; move => l o H1 H2; inversion H1 => {H1}; inversion H2 => {H2}.\n    + subst n l n0 o.\n      apply T_Zero.\n    + subst n l n0 o.\n      apply T_Zero.\n    + subst n0 m o0 n1 m0 o.\n      apply T_Succ with (l := n).\n      - apply IHn with (l := Z).\n        apply Times_zero_r.\n        apply Plus_unit_r.\n      - apply P_Succ.\n        inversion H3 => {H3}; subst n0 l0.\n        suff nl : l1 = n.\n        * subst l1.\n          apply P_Zero.\n        * suff lz : l = Z.\n          subst l.\n          apply (Plus_uniq n Z) => //.\n          apply Plus_unit_r.\n          apply (Times_uniq n Z) => //.\n          apply Times_zero_r.\n    + subst n0 m0 o0 n1 m1 o.\n      inversion H3 => {H3}; subst n0 m0 l.\n      specialize (Plus_close n l0); move => [z Hz].\n      apply T_Succ with (l := z).\n      - apply IHn with (l := l0) => //.\n      - apply P_Succ.\n        apply (Plus_comm n (S l2) l1) in H6.\n        inversion H6 => {H6}; subst n0 m0 l1.\n        specialize (Plus_assoc m l0 n l2 l H1 H2).\n        move => [z_ [H3 H4]].\n        apply P_Succ.\n        suff zz : z = z_.\n        * subst z_ => //.\n        * apply (Plus_uniq n l0) => //.\n          apply Plus_comm => //.\nQed.\n\n\n\n\n\n\nTheorem Times_comm :\n    forall x y z, Times x y z -> Times y x z.\nProof.\n    elim => [| x0 IHx].\n    + move => y z H; inversion H; subst n z.\n      apply Times_zero_r.\n    + move => y z H; inversion H; subst n m o.\n      apply T_Succ_r with (l := l) => //.\n      apply IHx => //.\nQed. \n\nTheorem Times_eq_Z :\n    forall x y, Times x y Z -> x = Z \\/ y = Z.\nProof.\n    move => x y.\n    induction x, y => H.\n    + left => //.\n    + left => //.\n    + right => //.\n    + inversion H; subst n m o.\n      inversion H2.\nQed.   \n\nLemma dist_l :\n    forall x y z yz xyxz , Times x yz xyxz -> Plus y z yz ->\n    exists xy xz, Times x y xy /\\ Times x z xz /\\ Plus xy xz xyxz.\nProof.    \n    elim => [|x_ IHx] => y z yz xyxz HT HP.\n    + inversion HT; subst n xyxz.\n      exists Z, Z; autoP.\n    + inversion HT; subst n m o.\n      move : (IHx y z yz l H0 HP) => [xy_ [xz_ [Hxy_ [Hxz_ Hl]]]].\n      move : (Plus_close y xy_) => [xy Hxy].\n      move : (Plus_close z xz_) => [xz Hxz].\n      exists xy, xz; split; [|split].\n      - apply T_Succ with (l := xy_) => //.\n      - apply T_Succ with (l := xz_) => //.\n      - move : (Plus_assoc y z l yz xyxz HP H1) => [zl [Hzl Hyzl]].\n        apply Plus_comm in Hzl.\n        move  : (Plus_assoc xy_ xz_ z l zl Hl Hzl) => [xz' [Hxz' Hzl']].\n        apply Plus_comm in Hxz; apply Plus_comm in Hxy.\n        move : (Plus_uniq xz_ z xz xz' Hxz Hxz') => xzxz; subst xz'.\n        apply Plus_comm in Hzl'.\n        apply Plus_comm in Hyzl.\n        move : (Plus_assoc xz xy_ y zl xyxz Hzl' Hyzl) => [xy' [Hxy' Hyz']].\n        move : (Plus_uniq xy_ y xy xy' Hxy Hxy') => xyxy; subst xy'.\n        apply Plus_comm => //.\nQed.        \n\nLemma dist_r :\n    forall x y z xy xzyz, Times xy z xzyz -> Plus x y xy ->\n    exists xz yz, Times x z xz /\\ Times y z yz /\\ Plus xz yz xzyz.\nProof.\n    move => x y z xy xzyz HT HP.\n    apply Times_comm in HT.\n    move : (dist_l z x y xy xzyz HT HP) => [xz [yz [Hxz [Hyz H]]]].\n    exists xz, yz; split; [|split] => //; apply Times_comm => //.\nQed.\n\n\n\n    \n           \n\nTheorem Times_assoc :\n    forall x y z xy xyz,\n    Times x y xy -> Times xy z xyz  ->\n    exists yz, Times y z yz /\\ Times x yz xyz.\nProof.\n    move => x y; move : x.\n    induction y => x z xy xyz H1 H2.\n    + apply Times_comm in H1.\n      inversion H1; subst n xy.\n      inversion H2; subst n xyz.\n      exists Z; split => //.\n      apply Times_zero_r.\n    + apply Times_comm in H1.\n      inversion H1; subst n m o.\n      move : (Times_close y z) => [yz_ Hyz_].\n      move : (Plus_close z yz_) => [yz Hyz].\n      exists yz; split.\n      - apply T_Succ with (l := yz_) => //.\n      - move : (dist_r x l z xy xyz H2 H3) => [xz [lz [Hzx [Hlz Hxyz]]]]. \n        move : (Times_close x yz) => [xyz' H].\n        move :  (dist_l x z yz_ _ _ H Hyz) => [xz' [yz' [Hxz [Hxyz_ Hxyz']]]].\n        move : (Times_uniq x z _ _ Hzx Hxz) => xzxz; subst xz'.\n        apply Times_comm in H0.\n        move : (IHy x z l lz H0 Hlz) => [yz'' [Hyz'' Hlz']].\n        move : (Times_uniq y z _ _ Hyz_ Hyz'') => yzyz; subst yz''.\n        suff : xyz = xyz'.\n          move => -> //.\n        apply (Plus_uniq xz lz) => //.\n        suff  : lz = yz'.\n          move => -> //.\n        apply (Times_uniq x yz_) => //.\nQed.\n\n\n\n(* Theorem 2.11 (CompareNat1) *)\nTheorem LessThan1_Z_Sn :\n    forall n : peano, LessThan1 Z (S n).\nProof.\n    induction n as [| n' H'].\n    \n        (* Case : n = Z *)\n        apply L1_Succ.\n    \n        (* Case : n = S n' *)\n        apply (L1_Trans _ (S n') _ H').\n        apply L1_Succ.\nQed.\n\n(* Theorem 2.11 (CompareNat2) *)\nTheorem LessThan2_Z_Sn :\n    forall n : peano, LessThan2 Z (S n).\nProof.\n    apply L2_Zero.\nQed.\n\n(* Theorem 2.11 (CompareNat3) *)\nTheorem LessThan3_Z_Sn :\n    forall n : peano, LessThan3 Z (S n).\nProof.\n    induction n as [| n' H].\n    \n        (* Case : n = Z *)\n        apply L3_Succ.\n    \n        (* Case : n = S n' *)\n        apply (L3_SuccR _ _ H).\nQed.\n\n(* Theorem 2.12 (CompareNat1) *)\nTheorem LessThan1_prev :\n    forall n1 n2 : peano, LessThan1 (S n1) (S n2) -> LessThan1 n1 n2.\nProof.\nAdmitted.\n\n(* Theorem 2.12 (CompareNat2) *)\nTheorem LessThan2_prev :\n    forall n1 n2 : peano, LessThan2 (S n1) (S n2) -> LessThan2 n1 n2.\nProof.\nAdmitted.\n\n(* Theorem 2.12 (CompareNat3) *)\nTheorem LessThan3_prev :\n    forall n1 n2 : peano, LessThan3 (S n1) (S n2) -> LessThan3 n1 n2.\nProof.\nAdmitted.\n\n(* Theorem 2.13 (CompareNat1) *)\nTheorem LessThan1_trans :\n    forall n1 n2 n3 : peano,\n    LessThan1 n1 n2 -> LessThan1 n2 n3 -> LessThan1 n1 n3.\nProof.\n    apply L1_Trans.\nQed.\n\n(* Theorem 2.13 (CompareNat2) *)\nTheorem LessThan2_trans :\n    forall n1 n2 n3 : peano,\n    LessThan2 n1 n2 -> LessThan2 n2 n3 -> LessThan2 n1 n3.\nProof.\nAdmitted.\n\n(* Theorem 2.13 (CompareNat3) *)\nTheorem LessThan3_trans :\n    forall n1 n2 n3 : peano,\n    LessThan3 n1 n2 -> LessThan3 n2 n3 -> LessThan3 n1 n3.\nProof.\nAdmitted.\n\n(* Theorem 2.14 (1) (2) *)\nTheorem LessThan_equiv_1_2 :\n    forall n1 n2 : peano, LessThan1 n1 n2 <-> LessThan2 n1 n2.\nProof.\nAdmitted.\n\n(* Theorem 2.14 (2) (3) *)\nTheorem LessThan_equiv_2_3 :\n    forall n1 n2 : peano, LessThan2 n1 n2 <-> LessThan3 n1 n2.\nProof.\nAdmitted.\n\n(* Theorem 2.14 (1) (3) *)\nTheorem LessThan_equiv_1_3 :\n    forall n1 n2 : peano, LessThan1 n1 n2 <-> LessThan3 n1 n2.\nProof.\nAdmitted.\n\nTheorem EvalTo_total :\n    forall e, exists n, EvalTo e n.\nProof.\n    move => e.\n    (* inversion e as [n| x y | x y]. *)\n    induction e as [n | x [x_ Hx] y [y_ Hy]| x [x_ Hx] y [y_ Hy]].\n    +   exists n.\n        apply E_Const.\n    +   move : (Plus_close x_ y_) => [xy Hxy].\n        exists xy.\n        apply (E_Plus x y x_ y_ xy) => //.\n    +   move : (Times_close x_ y_) => [xy Hxy].\n        exists xy.\n        apply (E_Times x y x_ y_ xy) => //.\nQed.  \n\nTheorem EvalTo_uniq :\n    forall e x y, EvalTo e x -> EvalTo e y -> x = y.\nProof.\n    elim => [|e_ He_|e_ He_].\n    +   move => p x y H1 H2.\n        inversion H1; inversion H2.\n        subst n n0 p => //.\n    +   move => e He x y H1 H2.\n        inversion H1; inversion H2.\n        subst e1 e2 n e0 e3 n4.\n        suff H : n1 = n0 /\\ n2 = n3.\n        -   inversion H.\n            subst n0 n3.\n            apply (Plus_uniq n1 n2) => //.\n        -   split.\n            *   apply He_ => //.\n            *   apply He => //.\n    +   move => e He x y H1 H2.\n        inversion H1; inversion H2.\n        subst e1 e2 n e0 e3 n4.\n        suff H : n1 = n0 /\\ n2 = n3.\n        -   inversion H.\n            subst n0 n3.\n            apply (Times_uniq n1 n2) => //.\n        -   split.\n            *   apply He_ => //.\n            *   apply He => //.\nQed.      \n\nTheorem EPlus_comm : \n    forall X Y xy, EvalTo (EPlus X Y) xy -> EvalTo (EPlus Y X) xy.\nProof.\n    move => X Y xy H.\n    inversion H.\n    apply (E_Plus Y X n2 n1) => //.\n    apply Plus_comm => //.\nQed.\n\nTheorem EPlus_assoc :\n    forall X Y Z xyz,\n    EvalTo (EPlus (EPlus X Y) Z) xyz -> EvalTo (EPlus X (EPlus Y Z)) xyz.\nProof.\n    move => X Y Z xyz H.\n    inversion H.\n    inversion H2.\n    subst e1 e2 n e0 e3 n4.\n    move : (Plus_close n3 n2) => [yz Hyz].\n    apply (E_Plus _ _ n0 yz) => //.\n    +   apply (E_Plus Y Z n3 n2) => //.\n    +   move :  (Plus_assoc n0 n3 n2 n1 xyz H11 H5) => [yz_ [Hyz_ Hxyz]].\n        suff : yz = yz_.\n        -   move => -> //.\n        -   apply (Plus_uniq n3 n2) => //.\nQed.\n\nTheorem ETimes_comm :\n    forall X Y n, EvalTo (ETimes X Y) n -> EvalTo (ETimes Y X) n.\nProof.\n    move => X Y n H.\n    inversion H.\n    apply (E_Times Y X n2 n1) => //.\n    apply Times_comm => //. \nQed.\n\n\nTheorem ETimes_assoc :\n    forall X Y Z xyz,\n    EvalTo (ETimes (ETimes X Y) Z) xyz -> EvalTo (ETimes X (ETimes Y Z)) xyz.\nProof.\n    move => X Y Z xyz H.\n    inversion H.\n    inversion H2.\n    subst e1 e2 n e0 e3 n4.\n    move : (Times_close n3 n2) => [yz Hyz].\n    apply (E_Times _ _ n0 yz) => //.\n    +   apply (E_Times Y Z n3 n2) => //.\n    +   move :  (Times_assoc n0 n3 n2 n1 xyz H11 H5) => [yz_ [Hyz_ Hxyz]].\n        suff : yz = yz_.\n        -   move => -> //.\n        -   apply (Times_uniq n3 n2) => //.\nQed.\n\nTheorem ReduceTo_progress :\n    forall e, (exists n, e = ENum n) \\/ (exists e', ReduceTo e e').\nProof.\n    move => e.\n    induction e.\n    +   left; exists p => //.\n    +   move : IHe1 => [[x Hx]|[X HX]]; move : IHe2 => [[y Hy] | [Y HY]].\n        -   subst e1 e2.\n            move : (Plus_close x y) => [xy Hxy].\n            right; exists (ENum xy).\n            apply (R_Plus x y xy) => //.\n        -   subst e1.\n            right.\n            exists (EPlus (ENum x) Y).\n            apply R_PlusR => //.\n        -   subst e2; right.\n            exists (EPlus X (ENum y)).\n            apply R_PlusL => //.\n        -   right.\n            exists (EPlus e1 Y).\n            apply R_PlusR => //.\n    +   move : IHe1 => [[x Hx]|[X HX]]; move : IHe2 => [[y Hy] | [Y HY]].\n        -   subst e1 e2.\n            move : (Times_close x y) => [xy Hxy].\n            right; exists (ENum xy).\n            apply (R_Times x y xy) => //.\n        -   subst e1.\n            right.\n            exists (ETimes (ENum x) Y).\n            apply R_TimesR => //.\n        -   subst e2; right.\n            exists (ETimes X (ENum y)).\n            apply R_TimesL => //.\n        -   right.\n            exists (ETimes e1 Y).\n            apply R_TimesR => //.\nQed.\n\n\n\n\n\n\n\nTheorem DetReduceTo_uniq :\n    forall X Y1 Y2, DetReduceTo X Y1 -> DetReduceTo X Y2 -> Y1 = Y2.\nProof.\n    move => X; induction X => Y1 Y2 H1 H2.        \n    +   inversion H1.\n    +   inversion H1; subst X1 X2 Y1; inversion H2.\n        *   subst n0 m0 Y2.\n            move : (Plus_uniq n m l l0 H4 H5) -> => //.\n        *   subst e1 e2 Y2.\n            inversion H5.\n        *   subst n1 e2 Y2.\n            inversion H5.\n        *   subst e1 e2 Y2.\n            inversion H4.\n        *   subst e0 e3 Y2.\n            suff : e1' = e1'0.\n            -   move => -> //.\n            -   apply IHX1 => //.\n        *   subst e1 e2 Y2.\n            inversion H4.\n        *   subst n1 e2 Y2.\n            inversion H4.\n        *   subst e1 e0 Y2.\n            inversion H5.\n        *   subst n0 e0 Y2.\n            move : (IHX2 e2' e2'0 H4 H5) -> => //.\n    +   inversion H1; subst X1 X2 Y1; inversion H2.\n        *   subst n0 m0 Y2.\n            move : (Times_uniq n m l l0 H4 H5) -> => //.\n        *   subst e1 e2 Y2.\n            inversion H5.\n        *   subst n1 e2 Y2.\n            inversion H5.\n        *   subst e1 e2 Y2.\n            inversion H4.\n        *   subst e0 e3 Y2.\n            suff : e1' = e1'0.\n            -   move => -> //.\n            -   apply IHX1 => //.\n        *   subst e1 e2 Y2.\n            inversion H4.\n        *   subst n1 e2 Y2.\n            inversion H4.\n        *   subst e1 e0 Y2.\n            inversion H5.\n        *   subst n0 e0 Y2.\n            move : (IHX2 e2' e2'0 H4 H5) -> => //.\nQed.   \n\n\n    \nTheorem DetReduceTo_ReduceTo :\n    forall X Y, DetReduceTo X Y -> ReduceTo X Y.\nProof.\n    elim.\n    +   move => x Y H.\n        inversion H.\n    +   move => a IHa b IHb Y H.\n        inversion H.\n        *   subst a b Y.\n            apply R_Plus => //.\n        *   subst e1 e2 Y.\n            apply R_PlusL.\n            apply IHa => //.\n        *   subst a b Y.\n            apply R_PlusR.\n            apply IHb => //.\n    +   move => a IHa b IHb Y H.\n        inversion H.\n        *   subst a b Y.\n            apply R_Times => //.\n        *   subst e1 e2 Y.\n            apply R_TimesL.\n            apply IHa => //.\n        *   subst a b Y.\n            apply R_TimesR.\n            apply IHb => //.\nQed.  \n\nLemma MR_PlusR :\n    forall X Y Y', MultiReduceTo Y Y' -> \n    MultiReduceTo (EPlus X Y) (EPlus X Y').\nProof.\n    move => X Y Y' H.\n    elim H.\n    +   move => e.\n        apply MR_Zero.\n    +   move => e e' He.\n        apply MR_One.\n        apply R_PlusR => //.\n    +   move => x y z Hxy IHxy Hyz IHyz.\n        apply (MR_Multi _ _ _ IHxy IHyz).\nQed.  \n\nLemma MR_PlusL :\n    forall X X' Y, MultiReduceTo X X' ->\n    MultiReduceTo (EPlus X Y) (EPlus X' Y).\nProof.\n    move => X Y Y' H.\n    elim H.\n    +   move => e.\n        apply MR_Zero.\n    +   move => e e' He.\n        apply MR_One.\n        apply R_PlusL => //.\n    +   move => x y z Hxy IHxy Hyz IHyz.\n        apply (MR_Multi _ _ _ IHxy IHyz).\nQed.  \n\nLemma MR_TimesR :\n    forall X Y Y', MultiReduceTo Y Y' -> \n    MultiReduceTo (ETimes X Y) (ETimes X Y').\nProof.\n    move => X Y Y' H.\n    elim H.\n    +   move => e.\n        apply MR_Zero.\n    +   move => e e' He.\n        apply MR_One.\n        apply R_TimesR => //.\n    +   move => x y z Hxy IHxy Hyz IHyz.\n        apply (MR_Multi _ _ _ IHxy IHyz).\nQed.  \n\nLemma MR_TimesL :\n    forall X X' Y, MultiReduceTo X X' ->\n    MultiReduceTo (ETimes X Y) (ETimes X' Y).\nProof.\n    move => X Y Y' H.\n    elim H.\n    +   move => e.\n        apply MR_Zero.\n    +   move => e e' He.\n        apply MR_One.\n        apply R_TimesL => //.\n    +   move => x y z Hxy IHxy Hyz IHyz.\n        apply (MR_Multi _ _ _ IHxy IHyz).\nQed.  \n\n\n\nTheorem ReduceTo_weak_normal :\n    forall e, exists n, MultiReduceTo e (ENum n).\nProof.\n    elim.\n    +   move => x; exists x.\n        apply MR_Zero.\n    +   move => X [x Hx] Y [y Hy].\n        move : (Plus_close x y) => [xy Hxy].        \n        exists xy.\n        refine (MR_Multi _ (EPlus X (ENum y)) _ _ _).\n        -   apply MR_PlusR => //.\n        -   refine (MR_Multi _ (EPlus (ENum x) (ENum y)) _ _ _ ).\n            *   apply MR_PlusL => //.\n            *   apply MR_One.\n                apply R_Plus => //.\n    +   move => X [x Hx] Y [y Hy].\n        move : (Times_close x y) => [xy Hxy].        \n        exists xy.\n        refine (MR_Multi _ (ETimes X (ENum y)) _ _ _).\n        -   apply MR_TimesR => //.\n        -   refine (MR_Multi _ (ETimes (ENum x) (ENum y)) _ _ _ ).\n            *   apply MR_TimesL => //.\n            *   apply MR_One.\n                apply R_Times => //.\nQed.  \n\nTheorem ReduceTo_confl :\n   forall X Y1 Y2, ReduceTo X Y1 -> ReduceTo X Y2 ->\n    exists Z, MultiReduceTo Y1 Z /\\ MultiReduceTo Y2 Z.\nProof.\n    elim.\n    +   move => x Y1 Y2 H1.\n        inversion H1.\n    +   move => A HA B HB Y1 Y2 H1 H2.\n        inversion H1; inversion H2.\n        -   subst A B Y1 Y2.\n            inversion H5; inversion H7.\n            subst n0 m0.\n            move : (Plus_uniq n m l l0 H4 H8) ->.\n            exists (ENum l0); split; apply MR_Zero.\n        -   subst A B Y1 Y2 e1 e2.\n            inversion H8.\n        -   subst A B e1 e2 Y1 Y2.\n            inversion H8.\n        -   subst A B e1 e2 Y1 Y2.\n            inversion H4.\n        -   subst A B e0 e3 Y1 Y2.\n            move : (HA e1' e1'0 H4 H8) => [Z [HZ1 HZ2]].\n            exists (EPlus Z e2); split; apply MR_PlusL => //.\n        -   subst A B e0 e3 Y1 Y2.\n            exists (EPlus e1' e2'); split.\n            *   apply MR_PlusR; apply MR_One => //.\n            *   apply MR_PlusL; apply MR_One => //.\n        -   subst A B e1 e2 Y1 Y2.\n            inversion H4.\n        -   subst A B e0 e3 Y1 Y2. \n            exists (EPlus e1' e2'); split.\n            *   apply MR_PlusL; apply MR_One => //.\n            *   apply MR_PlusR; apply MR_One => //.\n        -   subst A B e0 e3 Y1 Y2.\n            move : (HB e2' e2'0 H4 H8) => [z [Hz1 Hz2]].\n            exists (EPlus e1 z); split; apply MR_PlusR => //.\n    +   move => A HA B HB Y1 Y2 H1 H2.\n        inversion H1; inversion H2.\n        -   subst A B Y1 Y2.\n            inversion H5; inversion H7.\n            subst n0 m0.\n            move : (Times_uniq n m l l0 H4 H8) ->.\n            exists (ENum l0); split; apply MR_Zero.\n        -   subst A B Y1 Y2 e1 e2.\n            inversion H8.\n        -   subst A B e1 e2 Y1 Y2.\n            inversion H8.\n        -   subst A B e1 e2 Y1 Y2.\n            inversion H4.\n        -   subst A B e0 e3 Y1 Y2.\n            move : (HA e1' e1'0 H4 H8) => [Z [HZ1 HZ2]].\n            exists (ETimes Z e2); split; apply MR_TimesL => //.\n        -   subst A B e0 e3 Y1 Y2.\n            exists (ETimes e1' e2'); split.\n            *   apply MR_TimesR; apply MR_One => //.\n            *   apply MR_TimesL; apply MR_One => //.\n        -   subst A B e1 e2 Y1 Y2.\n            inversion H4.\n        -   subst A B e0 e3 Y1 Y2. \n            exists (ETimes e1' e2'); split.\n            *   apply MR_TimesL; apply MR_One => //.\n            *   apply MR_TimesR; apply MR_One => //.\n        -   subst A B e0 e3 Y1 Y2.\n            move : (HB e2' e2'0 H4 H8) => [z [Hz1 Hz2]].\n            exists (ETimes e1 z); split; apply MR_TimesR => //.\nQed.            \n                    \n\n\n\nTheorem EvalTo_MultiReduceTo :\n    forall e n, EvalTo e n -> MultiReduceTo e (ENum n).\nProof.\n    elim.\n    +   move => m n H.\n        inversion H.\n        subst n0 m.\n        apply MR_Zero.        \n    +   move => x Hx y Hy n H.\n        inversion H.\n        subst e1 e2 n0.\n        move : (Hx n1 H2) => H1 {H2 Hx}.\n        move : (Hy n2 H3) => H2 {H3 Hy}.\n        refine (MR_Multi _ (EPlus x (ENum n2))_ _ _).\n        *   apply MR_PlusR => //.\n        *   refine (MR_Multi _ (EPlus (ENum n1) (ENum n2))_ _ _).\n            -   apply MR_PlusL => //.\n            -   apply MR_One.\n                apply R_Plus => //.\n    +   move => x Hx y Hy n H.\n        inversion H.\n        subst e1 e2 n0.\n        move : (Hx n1 H2) => H1 {H2 Hx}.\n        move : (Hy n2 H3) => H2 {H3 Hy}.\n        refine (MR_Multi _ (ETimes x (ENum n2))_ _ _).\n        *   apply MR_TimesR => //.\n        *   refine (MR_Multi _ (ETimes (ENum n1) (ENum n2))_ _ _).\n            -   apply MR_TimesL => //.\n            -   apply MR_One.\n                apply R_Times => //.\nQed.\n\n\n\n\nLemma MR_eq :\n    forall x y, MultiReduceTo (ENum x) (ENum y) -> x = y.\nProof.\n    move => x y H.\n    inversion H => //.\n    +   inversion H0.\n    +   subst e e''.\n        (* move : (ReduceTo_weak_normal e') => [z Hz]. *)\n        inversion H0; inversion H1.\n        -   subst e e' e0.\n            inversion H5 => //.\n        -   subst e e' e0 e'0.\n            inversion H4.\n        -   subst e e' e0 e''.\nAdmitted.            \n\n\n\n\n\nTheorem MultiReduceTo_EvalTo :\n    forall e n, MultiReduceTo e (ENum n) -> EvalTo e n.\nProof.\nAdmitted.\n\n\n\n    \n\n\n\n\n\n\n\n\n\n    \n    \n\n\n\n\n\n    \n\n\n\n      \n    \n\n    \n\n\n\n           \n\n        \n       \n          \n\n    \n        \n\n       \n         \n\n\n\n", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "CoPL", "sha": "fdf26a94dc8dae7b53c6a12679e3ebb417113f31", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-CoPL", "path": "github-repos/coq/gaxiiiiiiiiiiii-CoPL/CoPL-fdf26a94dc8dae7b53c6a12679e3ebb417113f31/MetaTheorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.6970802582737573}}
{"text": "Welcome to Coq ciosx:/builds/workspace/coq-8.5pl3-macos,(detached from 2290dbb) (2290dbb9c95b63e693ced647731623e64297f5c8)\n\nCoq < Theorem plus_1_1 : forall n : nat, 1 + n = S n.\n1 subgoal\n  \n  ============================\n  forall n : nat, 1 + n = S n\n\nplus_1_1 < Proof.\n1 subgoal\n  \n  ============================\n  forall n : nat, 1 + n = S n\n\nplus_1_1 < intros n.\n1 subgoal\n  \n  n : nat\n  ============================\n  1 + n = S n\n\nplus_1_1 < reflexivity.\nNo more subgoals.\n\nplus_1_1 < Qed.\nProof.\nintros n.\nreflexivity.\n\nQed.\nplus_1_1 is defined\n\nCoq < Theorem mult_0_1 : forall n : nat , 0 * n = 0.\n1 subgoal\n  \n  ============================\n  forall n : nat, 0 * n = 0\n\nmult_0_1 < Proof.\n1 subgoal\n  \n  ============================\n  forall n : nat, 0 * n = 0\n\nmult_0_1 < intros n.\n1 subgoal\n  \n  n : nat\n  ============================\n  0 * n = 0\n\nmult_0_1 < reflexivity.\nNo more subgoals.\n\nmult_0_1 < Qed.\nProof.\nintros n.\nreflexivity.\n\nQed.\nmult_0_1 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/basics011.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782012, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.6970523828050621}}
{"text": "Inductive AList (A : Type) : Type :=\n| Single : A -> AList A\n| Append : AList A -> AList A -> AList A.\n\nArguments Single {A} _.\nArguments Append {A} _ _.\n\nInductive CList (A : Type) : Type :=\n| Nil    : CList A\n| NotNil : AList A -> CList A.\n\nArguments Nil    {A}.\nArguments NotNil {A} _.\n\nDefinition append {A : Type} (l1 l2 : CList A) : CList A :=\nmatch l1, l2 with\n| Nil       , _          => l2\n| _         , Nil        => l1\n| NotNil l1', NotNil l2' => NotNil (Append l1' l2')\nend.\n\nFixpoint hd {A : Type} (l : AList A) : A :=\nmatch l with\n| Single h    => h\n| Append l' _ => hd l'\nend.\n\nFixpoint last {A : Type} (l : AList A) : A :=\nmatch l with\n| Single x    => x\n| Append _ l' => last l'\nend.\n\nRequire Import List.\nImport ListNotations.\n\nFixpoint toListA {A : Type} (l : AList A) : list A :=\nmatch l with\n| Single x     => [x]\n| Append l1 l2 => toListA l1 ++ toListA l2\nend.\n\nDefinition toListC {A : Type} (l : CList A) : list A :=\nmatch l with\n| Nil       => []\n| NotNil l' => toListA l'\nend.\n\nLemma append_spec :\n  forall {A : Type} (l1 l2 : CList A),\n    toListC (append l1 l2) = toListC l1 ++ toListC l2.\nProof.\n  destruct l1 as [| [|]], l2 as []; cbn; try reflexivity.\n  symmetry. apply app_nil_r.\nQed.", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/code/IndRec/Mutual/MutualAppendList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6970523695869647}}
{"text": "Require Export hott_lemmas.\n\nOpen Scope type.\n\nSection MonoidalGroupoids.\n\nSection MonoidalStructure.\n\nContext {X : Type} (e : X) (m : X -> X -> X).\n\nDefinition IsAssociative : Type\n  := forall a b c : X, m (m a b) c = m a (m b c).\n\nDefinition IsLeftUnital : Type\n  := forall b : X, m e b = b.\n\nDefinition IsRightUnital : Type\n  := forall a : X, m a e = a.\n\nDefinition IsPentagonCoherent (alpha : IsAssociative) : Type\n  := forall a b c d : X,\n      alpha (m a b) c d @ alpha a b (m c d)\n      = ap011 m (alpha a b c) (idpath d) @ alpha a (m b c) d @ ap011 m (idpath a) (alpha b c d).\n\nDefinition IsTriangleCoherent (alpha : IsAssociative) (lambda : IsLeftUnital) (rho : IsRightUnital) : Type\n  := forall a b : X,\n      alpha a e b @ ap011 m (idpath a) (lambda b)\n      = ap011 m (rho a) (idpath b).\n\nEnd MonoidalStructure.\n\nClass MonoidalGroupoid := {\n  mgcarrier : Type;\n  mgtrunc : IsTrunc 1 mgcarrier;\n  mg_e : mgcarrier;\n  mg_m : mgcarrier -> mgcarrier -> mgcarrier;\n  mg_alpha : IsAssociative mg_m;\n  mg_lambda : IsLeftUnital mg_e mg_m;\n  mg_rho : IsRightUnital mg_e mg_m;\n  mg_pentagon : IsPentagonCoherent mg_m mg_alpha;\n  mg_triangle : IsTriangleCoherent mg_e mg_m mg_alpha mg_lambda mg_rho\n  }.\nCoercion mgcarrier : MonoidalGroupoid >-> Sortclass.\n\nDefinition mg_mm {M : MonoidalGroupoid} {a b a' b'} (pa : a = a') (pb : b = b')\n  : mg_m a b = mg_m a' b'\n  := ap011 mg_m pa pb.\n\nDefinition mg_mmm {M : MonoidalGroupoid} {a b a' b'} {pa pa' : a = a'} {pb pb' : b = b'}\n  (fa : pa = pa') (fb : pb = pb')\n  : mg_mm pa pb = mg_mm pa' pb'\n  := ap011 mg_mm fa fb.\n\nSection Naturality.\n\nContext {M : MonoidalGroupoid}.\n\nDefinition alpha_natural {a b c a' b' c'} (pa : a = a') (pb : b = b') (pc : c = c')\n  : mg_alpha a b c @ mg_mm pa (mg_mm pb pc) = mg_mm (mg_mm pa pb) pc @ mg_alpha a' b' c'.\nProof.\n  induction pa, pb, pc.\n  exact (concat_p1 _ @ (concat_1p _)^).\nDefined.\n\nDefinition lambda_natural {b b'} (pb : b = b')\n  : mg_lambda b @ pb = mg_mm (idpath mg_e) pb @ mg_lambda b'.\nProof.\n  induction pb;\n  exact (concat_p1 _ @ (concat_1p _)^).\nDefined.\n\nDefinition rho_natural {a a'} (pa : a = a')\n  : mg_rho a @ pa = mg_mm pa (idpath mg_e) @ mg_rho a'.\nProof.\n  induction pa;\n  exact (concat_p1 _ @ (concat_1p _)^).\nDefined.\n\nEnd Naturality.\n\nSection DerivedCoherence.\n\nContext {M : MonoidalGroupoid}.\n\nDefinition rho_a_e (a : M)\n  : mg_rho (mg_m a mg_e) = mg_mm (mg_rho a) (idpath mg_e).\nProof.\n  apply (cancelR _ _ (mg_rho a)).\n  exact (rho_natural (mg_rho a)).\nDefined.\n\nDefinition lambda_e_b (b : M)\n  : mg_lambda (mg_m mg_e b) = mg_mm (idpath mg_e) (mg_lambda b).\nProof.\n  apply (cancelR _ _ (mg_lambda b)).\n  exact (lambda_natural (mg_lambda b)).\nDefined.\n\nDefinition alpha_lambda (a b : M)\n  : mg_alpha mg_e a b @ mg_lambda (mg_m a b) = mg_mm (mg_lambda a) (idpath b).\nProof.\n  apply (cancelL (mg_lambda _) _ _); refine (concat_p_pp _ _ _ @ _);\n    refine (whiskerR (lambda_natural (mg_alpha mg_e a b)) _ @ concat_pp_p _ _ _ @ _).\n  refine (whiskerL _ (lambda_natural (mg_lambda (mg_m a b))) @ concat_p_pp _ _ _ @ _).\n  refine (_ @ (lambda_natural (mg_mm (mg_lambda a) (idpath b)))^); apply whiskerR.\n  apply (cancelL (mg_alpha _ _ _) _ _); refine (concat_p_pp _ _ _ @ _);\n    refine (_ @ (alpha_natural (idpath mg_e) (mg_lambda a) (idpath b))^);\n    refine (concat_pp_p _ _ _ @ _).\n  apply (cancelL (mg_mm (mg_alpha _ _ _) idpath) _ _);\n    refine (concat_p_pp _ _ _ @ concat_p_pp _ _ _ @ _ @ concat_pp_p _ _ _);\n    refine (whiskerR (mg_pentagon mg_e mg_e a b)^ _ @ concat_pp_p _ _ _ @ _).\n  refine (whiskerL _ (mg_triangle mg_e (mg_m a b)) @ _).\n  refine (alpha_natural (mg_rho mg_e) idpath idpath @ _); apply whiskerR.\n  refine (_ @ (ap011_pqpq mg_m (mg_alpha mg_e mg_e a) (mg_mm idpath (mg_lambda a)) idpath idpath)^);\n    exact (mg_mmm (mg_triangle _ _)^ idpath).\nDefined.\n\nDefinition alpha_rho (a b : M)\n  : mg_alpha a b mg_e @ mg_mm (idpath a) (mg_rho b) = mg_rho (mg_m a b).\nProof.\n  apply (cancelL (mg_rho _) _ _); refine (concat_p_pp _ _ _ @ _).\n  refine (whiskerR (rho_natural (mg_alpha a b mg_e)) _ @ concat_pp_p _ _ _ @ _).\n  refine (whiskerL _ (rho_natural (mg_mm (idpath a) (mg_rho b))) @ concat_p_pp _ _ _ @ _).\n  refine (_ @ (rho_natural (mg_rho (mg_m a b)))^); apply whiskerR.\n  refine (_ @ mg_triangle (mg_m a b) mg_e).\n  apply (cancelR _ _ (mg_alpha _ _ _)); refine (concat_pp_p _ _ _ @ _ @ concat_p_pp _ _ _).\n  refine (whiskerL _ (alpha_natural idpath (mg_rho _) idpath)^ @ concat_p_pp _ _ _ @ _).\n  refine (_ @ concat_pp_p _ _ _ @ whiskerL _ (alpha_natural idpath idpath (mg_lambda _))).\n  refine (_ @ concat_p_pp _ _ _ @ whiskerR (mg_pentagon _ _ _ _)^ _); apply whiskerL.\n  refine (_ @ (ap011_pqpq mg_m idpath idpath (mg_alpha b mg_e mg_e) (mg_mm idpath (mg_lambda mg_e)))^);\n    exact (mg_mmm idpath (mg_triangle _ _)^).\nDefined.\n\nDefinition lambda_rho_e\n  : mg_lambda mg_e = mg_rho mg_e.\nProof.\n  apply (cancelL (mg_rho (mg_m mg_e mg_e)) _ _).\n  refine (rho_natural (mg_lambda mg_e) @ _).\n  refine (_ @ (rho_natural (mg_rho mg_e))^); apply whiskerR.\n  refine ((alpha_lambda mg_e mg_e)^ @ _).\n  apply (cancelR _ _ (mg_lambda mg_e)); refine (concat_pp_p _ _ _ @ _).\n  refine (whiskerL _ (lambda_natural (mg_lambda mg_e)) @ concat_p_pp _ _ _ @ _); apply whiskerR.\n  apply mg_triangle.\nDefined.\n\nEnd DerivedCoherence.\n\n\nClass MonoidalFunctor (A B : MonoidalGroupoid) := {\n  mg_f : A -> B;\n  mg_f0 : mg_e = mg_f mg_e;\n  mg_f2 : forall a b : A, mg_m (mg_f a) (mg_f b) = mg_f (mg_m a b);\n  mg_dalpha : forall a b c : A,\n    mg_alpha (mg_f a) (mg_f b) (mg_f c) @ (mg_mm idpath (mg_f2 b c) @ mg_f2 a (mg_m b c))\n    = (mg_mm (mg_f2 a b) idpath @ mg_f2 (mg_m a b) c) @ ap mg_f (mg_alpha a b c);\n  mg_dlambda : forall b : A,\n    mg_lambda (mg_f b) = mg_mm mg_f0 idpath @ mg_f2 mg_e b @ ap mg_f (mg_lambda b);\n  mg_drho : forall a : A,\n    mg_rho (mg_f a) = mg_mm idpath mg_f0 @ mg_f2 a mg_e @ ap mg_f (mg_rho a)\n  }.\nCoercion mg_f : MonoidalFunctor >-> Funclass.\n\nDefinition mg_f2_natural {A B : MonoidalGroupoid} (F : MonoidalFunctor A B)\n  {a b a' b' : A} (pa : a = a') (pb : b = b')\n  : mg_f2 a b @ ap mg_f (mg_mm pa pb)\n    = mg_mm (ap mg_f pa) (ap mg_f pb) @ mg_f2 a' b'.\nProof.\n  induction pa, pb; exact (concat_p1 _ @ (concat_1p _)^).\nDefined.\n\nDefinition MonoidalFunctor_id (A : MonoidalGroupoid)\n  : MonoidalFunctor A A.\nProof.\n  srapply @Build_MonoidalFunctor.\n  + exact idmap.\n  + constructor.\n  + constructor.\n  + intros. simpl. refine (concat_p1 _ @ (ap_idmap _)^ @ (concat_1p _)^).\n  + intros. simpl. refine ((ap_idmap _)^ @ (concat_1p _)^).\n  + intros. simpl. refine ((ap_idmap _)^ @ (concat_1p _)^).\nDefined.\n\n\nDefinition MonoidalFunctor_comp {A B C : MonoidalGroupoid}\n  (G : MonoidalFunctor B C) (F : MonoidalFunctor A B)\n  : MonoidalFunctor A C.\nProof.\n  srapply @Build_MonoidalFunctor.\n  + exact (fun x => G (F x)).\n  + simpl. exact (@mg_f0 B C G @ ap G (@mg_f0 A B F)).\n  + intros; simpl.\n    exact (@mg_f2 B C G (F a) (F b) @ ap G (@mg_f2 A B F a b)).\n  + intros; simpl.\n    refine (whiskerL _ (whiskerR (ap011_pqpq mg_m idpath idpath (mg_f2 (F b) (F c)) (ap G (mg_f2 b c)))^ _) @ _ @ whiskerR (whiskerR (ap011_pqpq mg_m (mg_f2 (F a) (F b)) (ap G (mg_f2 a b)) idpath idpath) _) _).\n    refine (whiskerL _ (concat_p_pp _ _ _ @ whiskerR (concat_pp_p _ _ _) _) @ _);\n      refine (whiskerL _ (whiskerR (whiskerL _ (mg_f2_natural G (idpath (F a)) (mg_f2 b c))^ @ concat_p_pp _ _ _) _ @ concat_pp_p _ _ _) @ _).\n    refine (concat_p_pp _ _ _ @ whiskerR (mg_dalpha _ _ _ @ concat_pp_p _ _ _) _ @ concat_pp_p _ _ _ @ _);\n      refine (_ @ concat_p_pp _ _ _ @ concat_p_pp _ _ _); apply whiskerL.\n    refine (whiskerL _ (ap_pp _ _ _)^ @ concat_pp_p _ _ _ @ whiskerL _ ((ap_pp _ _ _)^ @ ap (ap G) (mg_dalpha a b c) @ ap_pp _ _ _ @ whiskerR (ap_pp _ _ _) _ @ concat_pp_p _ _ _) @ concat_p_pp _ _ _ @ _).\n    refine (whiskerR (mg_f2_natural G (mg_f2 a b) (idpath (F c))) _ @ concat_pp_p _ _ _ @ _); apply whiskerL;\n      refine (concat_p_pp _ _ _ @ _); apply whiskerL.\n    exact (ap_compose F G _)^.\n  + intros; simpl.\n    refine (_ @ concat_p_pp _ _ _ @ concat_p_pp _ _ _ @ whiskerR (whiskerR (ap011_pqpq mg_m mg_f0 (ap G mg_f0) idpath idpath) _) _).\n    refine (mg_dlambda (F b) @ concat_pp_p _ _ _ @ _); apply whiskerL.\n    refine (_ @ concat_pp_p _ _ _ @ whiskerL _ (concat_p_pp _ _ _));\n      refine (_ @ concat_p_pp _ _ _ @ whiskerR (mg_f2_natural G mg_f0 idpath) _); apply whiskerL.\n    refine (_ @ whiskerL _ (whiskerL _ (ap_compose F G (mg_lambda b))^)).\n    refine (_ @ ap_pp G _ _ @ whiskerR (ap_pp G _ _) _ @ concat_pp_p _ _ _);\n      apply ap; exact (mg_dlambda b).\n  + intros; simpl.\n    refine (_ @ concat_p_pp _ _ _ @ concat_p_pp _ _ _ @ whiskerR (whiskerR (ap011_pqpq mg_m idpath idpath mg_f0 (ap G mg_f0)) _) _).\n    refine (mg_drho (F a) @ concat_pp_p _ _ _ @ _); apply whiskerL.\n    refine (_ @ concat_pp_p _ _ _ @ whiskerL _ (concat_p_pp _ _ _));\n      refine (_ @ concat_p_pp _ _ _ @ whiskerR (mg_f2_natural G idpath mg_f0) _); apply whiskerL.\n    refine (_ @ whiskerL _ (whiskerL _ (ap_compose F G (mg_rho a))^)).\n    refine (_ @ ap_pp G _ _ @ whiskerR (ap_pp G _ _) _ @ concat_pp_p _ _ _);\n      apply ap; exact (mg_drho a).\nDefined.\n\nClass MonoidalNatIso {A B} (F G : MonoidalFunctor A B) := {\n  mg_nt : F == G;\n  mg_nt0 : @mg_f0 _ _ F @ mg_nt mg_e = @mg_f0 _ _ G;\n  mg_nt2 : forall a b : A,\n    @mg_f2 _ _ F a b @ mg_nt (mg_m a b)\n    = ap011 mg_m (mg_nt a) (mg_nt b) @ @mg_f2 _ _ G a b\n  }.\n\nLemma MonoidalNatIso_V {A B : MonoidalGroupoid} (F G : MonoidalFunctor A B)\n  : MonoidalNatIso F G -> MonoidalNatIso G F.\nProof.\n  intro eta.\n  srapply @Build_MonoidalNatIso.\n  + intro x. exact (mg_nt x)^.\n  + simpl. refine (whiskerR (@mg_nt0 _ _ _ _ eta)^ _ @ _).\n    exact (concat_pp_p _ _ _ @ whiskerL _ (concat_pV _) @ concat_p1 _).\n  + simpl. intros.\n    refine (_ @ whiskerR (ap011_VV _ _ _)^ _).\n    apply moveL_Vp; refine (concat_p_pp _ _ _ @ _); apply moveR_pV.\n    exact (mg_nt2 a b)^.\nDefined.\n\nLemma MonoidalFunctor_comp_associative {A B C D : MonoidalGroupoid}\n  (H : MonoidalFunctor C D) (G : MonoidalFunctor B C) (F : MonoidalFunctor A B)\n  : MonoidalNatIso\n      (MonoidalFunctor_comp (MonoidalFunctor_comp H G) F)\n      (MonoidalFunctor_comp H (MonoidalFunctor_comp G F)).\nProof.\n  srapply @Build_MonoidalNatIso.\n  + simpl; constructor.\n  + simpl. refine (concat_p1 _ @ concat_pp_p _ _ _ @ _).\n    apply whiskerL.\n    refine (_ @ (ap_pp H _ _)^).\n    apply whiskerL.\n    apply ap_compose.\n  + intros; simpl. refine (concat_p1 _ @ concat_pp_p _ _ _ @ _ @ (concat_1p _)^).\n    apply whiskerL.\n    refine (_ @ (ap_pp H _ _)^).\n    apply whiskerL.\n    apply ap_compose.\nDefined.\n\nLemma MonoidalFunctor_comp_left_unital {A B : MonoidalGroupoid}\n  (F : MonoidalFunctor A B)\n  : MonoidalNatIso (MonoidalFunctor_comp F (MonoidalFunctor_id A)) F.\nProof.\n  srapply @Build_MonoidalNatIso; simpl.\n  + constructor.\n  + simpl. exact (concat_p1 _ @ concat_p1 _).\n  + intros; simpl. exact (concat_p1 _ @ concat_p1 _ @ (concat_1p _)^).\nDefined.\n\nLemma MonoidalFunctor_comp_right_unital {A B : MonoidalGroupoid}\n  (F : MonoidalFunctor A B)\n  : MonoidalNatIso (MonoidalFunctor_comp (MonoidalFunctor_id B) F) F.\nProof.\n  srapply @Build_MonoidalNatIso; simpl.\n  + constructor.\n  + simpl. exact (concat_p1 _ @ concat_1p _ @ ap_idmap _).\n  + intros; simpl. exact (concat_p1 _ @ concat_1p _ @ ap_idmap _ @ (concat_1p _)^).\nDefined.\n\nLemma MonoidalNatIso_vcomp {A B : MonoidalGroupoid} {F G H : MonoidalFunctor A B}\n  (theta : MonoidalNatIso F G) (eta : MonoidalNatIso G H)\n  : MonoidalNatIso F H.\nProof.\n  srapply @Build_MonoidalNatIso.\n  + intro x. exact (mg_nt x @ mg_nt x).\n  + simpl. refine (concat_p_pp _ _ _ @ _).\n    exact (whiskerR mg_nt0 _ @ mg_nt0).\n  + intros; simpl.\n    refine (_ @ whiskerR (ap011_pqpq mg_m (mg_nt a) (mg_nt a) (mg_nt b) (mg_nt b)) _).\n    refine (concat_p_pp _ _ _ @ _ @ concat_p_pp _ _ _).\n    refine (whiskerR (mg_nt2 a b) _ @ concat_pp_p _ _ _ @ _); apply whiskerL.\n    exact (mg_nt2 a b).\nDefined.\n\nLemma MonoidalNatIso_hcomp {A B C : MonoidalGroupoid}\n  {G1 G2 : MonoidalFunctor B C} {F1 F2 : MonoidalFunctor A B}\n  (eta : MonoidalNatIso G1 G2) (theta : MonoidalNatIso F1 F2)\n  : MonoidalNatIso (MonoidalFunctor_comp G1 F1) (MonoidalFunctor_comp G2 F2).\nProof.\n  srapply @Build_MonoidalNatIso; simpl.\n  + intro x. exact (mg_nt (F1 x) @ ap G2 (mg_nt x)).\n  + simpl.\n    refine (concat_pp_p _ _ _ @ _ @ concat_p_pp _ _ _ @ whiskerR mg_nt0 _); apply whiskerL.\n    refine (concat_p_pp _ _ _ @ _ @ concat_pp_p _ _ _ @ whiskerL _ ((ap_pp _ _ _)^ @ ap (ap G2) mg_nt0));\n    apply whiskerR.\n    exact (homotopy_square mg_nt mg_f0)^.\n  + intros; simpl.\n    refine (_ @ whiskerR (ap011_pqpq mg_m _ _ _ _) _).\n    refine (concat_pp_p _ _ _ @ whiskerL _ (concat_p_pp _ _ _ @ whiskerR (homotopy_square mg_nt (@mg_f2 _ _ F1 a b))^ _ @ concat_pp_p _ _ _) @ concat_p_pp _ _ _ @ _).\n    refine (whiskerL _ ((ap_pp _ _ _)^ @ ap (ap G2) (mg_nt2 a b) @ ap_pp _ _ _) @ _);\n    refine (concat_p_pp _ _ _ @ _ @ concat_pp_p _ _ _); apply whiskerR.\n    refine (whiskerR (mg_nt2 (F1 a) (F1 b)) _ @ concat_pp_p _ _ _ @ _ @ concat_p_pp _ _ _); apply whiskerL.\n    (* this would need a lemma ... *)\n    generalize (mg_nt a) as p; induction p; generalize (mg_nt b) as q; induction q.\n    exact (concat_p1 _ @ (concat_1p _)^).\nDefined.\n\nDefinition MonoidalEquivalence (M N : MonoidalGroupoid) : Type\n  := {F : MonoidalFunctor M N & {G : MonoidalFunctor N M & (MonoidalNatIso (MonoidalFunctor_comp G F) (MonoidalFunctor_id M)) * (MonoidalNatIso (MonoidalFunctor_comp F G) (MonoidalFunctor_id N))}}.\n\nSection UniversalProperty.\n\nClass IsFunctor (F : forall X : Type, IsHSet X -> MonoidalGroupoid) := {\n  F_arr : forall (X Y : Type) (T_X : IsHSet X) (T_Y : IsHSet Y) (f : X -> Y),\n          MonoidalFunctor (F X T_X) (F Y T_Y);\n  F_id : forall (X : Type) (T_X : IsHSet X),\n          MonoidalNatIso (F_arr X X T_X T_X (fun x => x)) (MonoidalFunctor_id (F X T_X));\n  F_comp : forall (X Y Z : Type) (T_X : IsHSet X) (T_Y : IsHSet Y) (T_Z : IsHSet Z)\n            (g : Y -> Z) (f : X -> Y),\n            MonoidalNatIso (MonoidalFunctor_comp (F_arr Y Z T_Y T_Z g) (F_arr X Y T_X T_Y f)) (F_arr X Z T_X T_Z (g o f))\n  }.\n\nClass IsFreeFunctor (F : forall X : Type, IsHSet X -> MonoidalGroupoid) := {\n  free_functor : IsFunctor F;\n  Phi : forall (X : Type) (T_X : IsHSet X)\n        (M : MonoidalGroupoid) (G : MonoidalFunctor (F X T_X) M),\n        X -> @mgcarrier M;\n  Phi_nat_M : forall (X : Type) (T_X : IsHSet X)\n              (M : MonoidalGroupoid) (G : MonoidalFunctor (F X T_X) M)\n              (N : MonoidalGroupoid) (H : MonoidalFunctor M N),\n              H o Phi X T_X M G == Phi X T_X N (MonoidalFunctor_comp H G);\n  Psi : forall (X : Type) (T_X : IsHSet X)\n        (M : MonoidalGroupoid) (g : X -> @mgcarrier M),\n        MonoidalFunctor (F X T_X) M;\n  Psi_nat_X : forall (X : Type) (T_X : IsHSet X)\n              (M : MonoidalGroupoid) (g : X -> @mgcarrier M)\n              (Y : Type) (T_Y : IsHSet Y) (h : Y -> X),\n              MonoidalNatIso\n                (MonoidalFunctor_comp (Psi X T_X M g) (@F_arr F free_functor Y X T_Y T_X h))\n                (Psi Y T_Y M (g o h));\n  Theta : forall (X : Type) (T_X : IsHSet X) (M : MonoidalGroupoid),\n          Phi X T_X M o Psi X T_X M == idmap;\n  Chi : forall (X : Type) (T_X : IsHSet X)\n          (M : MonoidalGroupoid) (G : MonoidalFunctor (F X T_X) M),\n          MonoidalNatIso (Psi X T_X M (Phi X T_X M G)) G\n  }.\n\nEnd UniversalProperty.\n\n(** If a monoidal functor determines an equivalence, then it determines a monoidal equivalence **)\nSection Inverse.\n\nContext (M N : MonoidalGroupoid) (F : MonoidalFunctor M N) (equiv: IsEquiv F).\nLet G := F^-1.\nLet h := eissect F : Sect F G.\nLet k := eisretr F : Sect G F.\nLet d := eisadj F : forall m : M, k (F m) = ap F (h m).\nLet d' := eisadj F^-1 : forall n : N, h (G n) = ap G (k n).\n\n  Lemma MonoidalFunctor_equiv_inverse_G0\n    : mg_e = G mg_e.\n  Proof.\n    exact ((h mg_e)^ @ ap G mg_f0^).\n  Defined.\n  Let G0 := MonoidalFunctor_equiv_inverse_G0.\n\n  Lemma MonoidalFunctor_equiv_inverse_G2\n    : forall a b : N, mg_m (G a) (G b) = G (mg_m a b).\n  Proof.\n    intros. exact ((h _)^ @ ap G (mg_f2 _ _)^ @ ap G (mg_mm (k _) (k _))).\n  Defined.\n  Let G2 := MonoidalFunctor_equiv_inverse_G2.\n\n  Lemma MonoidalFunctor_equiv_inverse_Galpha\n    : forall a b c : N, mg_alpha (G a) (G b) (G c) @ (mg_mm 1 (G2 b c) @ G2 a (mg_m b c)) = (mg_mm (G2 a b) 1 @ G2 (mg_m a b) c) @ ap G (mg_alpha a b c).\n  Proof.\n    intros.\n    refine (whiskerR ((ap_idmap _)^ @ moveL_Vp _ _ _ (homotopy_square h (mg_alpha _ _ _))) _ @ concat_pp_p _ _ _ @ _); (* 10 *)\n    apply moveR_Vp.\n    refine (_ @ concat_p_pp _ _ _ @ whiskerR (moveR_Vp _ _ _ (homotopy_square h (mg_mm (h (mg_m (G a) (G b))) (h (G c))))) _); (* 5 *)\n    apply moveL_Vp;\n    repeat rewrite ap_idmap; repeat rewrite (ap_compose F G).\n    repeat rewrite concat_pp_p. refine (whiskerR (ap (ap G) (moveL_Vp _ _ _ (homotopy_square_2 F mg_m mg_m mg_f2 (h (mg_m (G a) (G b))) (h (G c))))) _ @ _); (* 9 *)\n    repeat rewrite <- d; repeat rewrite ap_pp; repeat rewrite concat_pp_p.\n    apply moveL_Mp.\n    refine (concat_p_pp _ _ _ @ concat_p_pp _ _ _ @ _).\n    change (G2 (F (mg_m (G a) (G b))) (F (G c)) @ (ap G (mg_f2 (mg_m (G a) (G b)) (G c)) @ (ap G (ap F (mg_alpha (G a) (G b) (G c))) @ (h (mg_m (G a) (mg_m (G b) (G c))) @ (mg_mm 1 (G2 b c) @ G2 a (mg_m b c))))) = mg_mm (h (mg_m (G a) (G b))) (h (G c)) @ (mg_mm (G2 a b) 1 @ ((h (mg_m (G (mg_m a b)) (G c)))^ @ (ap G (mg_f2 (G (mg_m a b)) (G c))^ @ (ap G (mg_mm (k (mg_m a b)) (k c)) @ ap G (mg_alpha a b c)))))). (* 6 *)\n    refine (whiskerR (moveR_Vp _ _ _ (homotopy_square_2 G mg_m mg_m G2 (mg_f2 (G a) (G b)) (idpath (F (G c)))))^ _ @ concat_pp_p _ _ _ @ _); (* 8 *)\n    apply moveR_Vp; refine (concat_pp_p _ _ _ @ _).\n    refine (_ @ concat_p_pp _ _ _ @ concat_p_pp _ _ _ @ whiskerR (moveL_pV _ _ _ (ap011_p11q mg_m (ap G (mg_f2 (G a) (G b))) (h (G c)) @ (ap011_1qp1 mg_m (ap G (mg_f2 (G a) (G b))) (h (G c)))^))^ _). (* 3 *)\n    refine (_ @ whiskerL _ (whiskerL _ (whiskerR (moveL_Vp _ _ _ (ap011_1qp1 mg_m (h (mg_m (G a) (G b))) (h (G c)))) _ @ concat_pp_p _ _ _))). (* 2 *)\n    refine (_ @ concat_p_pp _ _ _ @ whiskerR (moveL_pV _ _ _ (ap011_1qp1 mg_m (ap G (mg_mm (k a) (k b))) (h (G c))))^ _). (* 4 *)\n    refine (_ @ whiskerL _ (whiskerR ((ap011_VV mg_m (G2 a b) idpath)^ @ ap (fun z => ap011 mg_m z idpath) (ap inverse (whiskerR (whiskerL _ (ap_V G _)) _ @ concat_pp_p _ _ _ @ whiskerL _ (whiskerL _ (inv_V _)^ @ (inv_pp _ _)^)) @ inv_VV _ _) @ ap011_pp1 mg_m _ (h (mg_m (G a) (G b))) @ whiskerR (ap011_pp1 mg_m (ap G (mg_mm (k a) (k b)))^ (ap G (mg_f2 (G a) (G b))) @ whiskerR (ap011_VV mg_m (ap G (mg_mm (k a) (k b))) idpath) _) _) _ @ concat_pp_p _ _ _ @ concat_pp_p _ _ _)); (* 1 *)\n    refine (_ @ whiskerL _ ((concat_1p _)^ @ whiskerR (concat_Vp _)^ _ @ concat_pp_p _ _ _)).\n    refine (_ @ whiskerL _ (concat_pp_p _ _ _ @ concat_pp_p _ _ _));\n    refine (_ @ concat_pp_p _ _ _ @ whiskerR (ap (ap011 mg_m _) (d' _)^) _);\n    refine (_ @ concat_p_pp _ _ _ @ whiskerR (homotopy_square_2 G mg_m mg_m G2 (mg_mm (k a) (k b)) (k c)) _); (* 7 *)\n    apply whiskerL.\n    refine (_ @ (ap_pp G _ _)^ @ ap (ap G) (alpha_natural (k a) (k b) (k c)) @ ap_pp G _ _). (* 12 *)\n    refine (concat_p_pp _ _ _ @ whiskerR (ap_pp G _ _)^ _ @ concat_p_pp _ _ _ @ whiskerR ((ap_pp G _ _)^ @ ap (ap G) (mg_dalpha (G a) (G b) (G c))^ @ ap_pp G _ _ @ whiskerL _ (ap_pp G _ _)) _ @ concat_pp_p _ _ _ @ whiskerL _ (concat_pp_p _ _ _) @ _); (* 11 *)\n    apply whiskerL.\n    srapply (cancelL (G2 _ _) _ _);\n    refine (whiskerL _ (whiskerL _ (whiskerL _ (concat_p_pp _ _ _) @ concat_p_pp _ _ _) @ concat_p_pp _ _ _) @ concat_p_pp _ _ _ @ _ @ (homotopy_square_2 G mg_m mg_m G2 (k a) (mg_mm (k b) (k c)))^); (* 7' *)\n    apply whiskerR.\n    refine (concat_p_pp _ _ _ @ whiskerR (homotopy_square_2 G mg_m mg_m G2 (idpath (F (G a))) (mg_f2 (G b) (G c))) _ @ concat_pp_p _ _ _ @ _). (* 8' *)\n    refine (whiskerR (moveL_pV _ _ _ (ap011_1qp1 mg_m (h _) (ap G (mg_f2 (G b) (G c))) @ (ap011_p11q mg_m (h _) (ap G (mg_f2 (G b) (G c))))^)) _ @ concat_pp_p _ _ _ @ concat_pp_p _ _ _ @ _). (* 3' *)\n    refine (_ @ ap011_p11q mg_m (h (G a)) (ap G (mg_mm (k b) (k c))) @ ap (fun z => ap011 mg_m z _) (d' a)); (* 4' *)\n    apply whiskerL.\n    refine (whiskerL _ (whiskerR (moveR_pV _ _ _ (moveL_Vp _ _ _ (ap011_p11q mg_m (h _) (h _))))^ _ @ concat_pp_p _ _ _) @ _). (* 2' *)\n    apply moveR_Mp;\n    refine (_ @ ap011_1pp mg_m _ _ @ whiskerR (ap (ap011 mg_m idpath) (ap_V G _) @ ap011_VV mg_m idpath _) _);\n    apply moveR_Mp;\n    refine (_ @ ap (ap011 mg_m idpath) (concat_pp_p _ _ _) @ ap011_1pp mg_m _ _ @ whiskerR (ap011_VV mg_m idpath _) _); (* 1' *)\n    refine (whiskerL _ (whiskerL _ (concat_p_pp _ _ _) @ concat_p_pp _ _ _) @ concat_p_pp _ _ _ @ _ @ concat_1p _);\n    apply whiskerR;\n    apply moveR_Vp; refine (_ @ (concat_p1 _)^).\n    refine (_ @ ((ap_idmap _)^ @ moveL_Vp _ _ _ (homotopy_square h (mg_mm (h _) (h _))))^); (* 5' *)\n    apply moveL_Vp;\n    refine (concat_p_pp _ _ _ @ concat_p_pp _ _ _ @ _);\n    apply whiskerR.\n    unfold G2, MonoidalFunctor_equiv_inverse_G2;\n    refine (whiskerR (concat_p_pp _ _ _ @ whiskerR (concat_p_pp _ _ _ @ whiskerR (concat_pV _) _ @ concat_1p _) _) _ @ concat_pp_p _ _ _ @ whiskerR (ap_V G _) _ @ _); (* 6' *)\n    apply moveR_Vp.\n    rewrite (ap_compose F G); repeat rewrite <- ap_pp; apply ap.\n    refine (_ @ (homotopy_square_2 F mg_m mg_m mg_f2 (h _) (h _))^); apply whiskerR; repeat rewrite d; constructor.\n  Qed.\n\n  Lemma MonoidalFunctor_equiv_inverse_Glambda\n    : forall b : N, mg_lambda (G b) = (mg_mm G0 1 @ G2 mg_e b) @ ap G (mg_lambda b).\n  Proof.\n    intros.\n    refine ((ap_idmap _)^ @ moveL_Vp _ _ _ (homotopy_square h (mg_lambda (G b))) @ _); (* 1 *)\n    apply moveR_Vp; apply moveR_pM.\n    refine (ap_compose F G _ @ ap (ap G) ((moveR_Vp _ _ _ (mg_dlambda (G b)))^ @ whiskerR (inv_pp _ _) _) @ ap_pp G _ _ @ whiskerR (ap_pp G _ _) _ @ concat_pp_p _ _ _ @ _);  (* 9 *)\n    repeat rewrite ap_V;\n    apply moveR_Vp; apply moveR_Vp.\n    refine (_ @ concat_pp_p _ _ _ @ concat_pp_p _ _ _); apply moveL_pV;\n    refine (whiskerL _ (d' _) @ (ap_pp G _ _)^ @ ap (ap G) (lambda_natural (k b)) @ ap_pp G _ _ @ _ @ concat_pp_p _ _ _ @ concat_pp_p _ _ _); (* 10 *)\n    apply whiskerR.\n    refine (moveL_Vp _ _ _ (homotopy_square_2 G mg_m mg_m G2 idpath (k b)) @ _); (* 11 *)\n    apply moveR_Vp;\n    refine (_ @ concat_pp_p _ _ _ @ concat_pp_p _ _ _);\n    apply whiskerR;\n    refine (ap (mg_mm idpath) (d' b)^ @ _).\n    srapply (cancelL (mg_mm G0 idpath) _ _ _);\n    srefine (_ @ concat_pp_p _ _ _);\n    refine (ap011_p11q mg_m G0 (h (G b)) @ (ap011_1qp1 mg_m G0 (h (G b)))^ @ _); (* 6 *)\n    apply whiskerR.\n    unfold G0, MonoidalFunctor_equiv_inverse_G0;\n    refine (_ @ concat_p_pp _ _ _ @ whiskerR (concat2 (ap011_VV mg_m (h mg_e) idpath)^ ((ap011_VV mg_m (ap G mg_f0) idpath)^ @ ap (fun z => ap011 mg_m z idpath) (ap_V G _)^) @ (ap011_pp1 _ _ _)^) _); (* 7 *)\n    apply moveL_Vp; apply moveL_Vp.\n    refine (whiskerR (moveR_pV _ _ _ (homotopy_square_2 G mg_m mg_m G2 mg_f0 idpath))^ _ @ concat_pp_p _ _ _ @ concat_pp_p _ _ _ @ _); (* 8 *)\n    apply whiskerL; refine (_ @ concat_p_pp _ _ _); apply whiskerL;\n    apply moveR_Vp.\n    refine (ap011_p11q mg_m (h mg_e) (h (G b)) @ _). (* 2 *)\n    unfold G2, MonoidalFunctor_equiv_inverse_G2;\n    refine (_ @ concat_p_pp _ _ _ @ concat_p_pp _ _ _);\n    apply moveL_Vp;\n    refine (_ @ whiskerR (ap_V G _)^ _);\n    apply moveL_Vp. (* 4 *)\n    refine (_ @ concat_p_pp _ _ _ @ whiskerR ((ap_pp G _ _)^ @ ap (ap G) (homotopy_square_2 F mg_m mg_m mg_f2 (h mg_e) (h (G b)) @ whiskerR (ap011 (ap011 mg_m) (d _)^ (d _)^) _) @ ap_pp G _ _) _ @ concat_pp_p _ _ _); (* 5 *)\n    apply whiskerL.\n    refine (whiskerL _ (ap_idmap _)^ @ homotopy_square h (ap011 mg_m (h mg_e) (h (G b))) @ _); (* 3 *)\n    apply whiskerR; apply ap_compose.\n  Qed.\n\n  Lemma MonoidalFunctor_equiv_inverse_Grho\n    : forall a : N, mg_rho (G a) = (mg_mm 1 G0 @ G2 a mg_e) @ ap G (mg_rho a).\n  Proof.\n    intros.\n    refine ((ap_idmap _)^ @ moveL_Vp _ _ _ (homotopy_square h (mg_rho (G a))) @ _); (* 1 *)\n    apply moveR_Vp; apply moveR_pM.\n    refine (ap_compose F G _ @ ap (ap G) ((moveR_Vp _ _ _ (mg_drho (G a)))^ @ whiskerR (inv_pp _ _) _) @ ap_pp G _ _ @ whiskerR (ap_pp G _ _) _ @ concat_pp_p _ _ _ @ _);  (* 9 *)\n    repeat rewrite ap_V;\n    apply moveR_Vp; apply moveR_Vp.\n    refine (_ @ concat_pp_p _ _ _ @ concat_pp_p _ _ _); apply moveL_pV;\n    refine (whiskerL _ (d' _) @ (ap_pp G _ _)^ @ ap (ap G) (rho_natural (k a)) @ ap_pp G _ _ @ _ @ concat_pp_p _ _ _ @ concat_pp_p _ _ _); (* 10 *)\n    apply whiskerR.\n    refine (moveL_Vp _ _ _ (homotopy_square_2 G mg_m mg_m G2 (k a) idpath) @ _); (* 11 *)\n    apply moveR_Vp;\n    refine (_ @ concat_pp_p _ _ _ @ concat_pp_p _ _ _);\n    apply whiskerR;\n    refine (ap (fun z => mg_mm z idpath) (d' a)^ @ _).\n    srapply (cancelL (mg_mm idpath G0) _ _ _);\n    srefine (_ @ concat_pp_p _ _ _);\n    refine (ap011_1qp1 mg_m (h (G a)) G0 @ (ap011_p11q mg_m (h (G a)) G0)^ @ _); (* 6 *)\n    apply whiskerR.\n    unfold G0, MonoidalFunctor_equiv_inverse_G0;\n    refine (_ @ concat_p_pp _ _ _ @ whiskerR (concat2 (ap011_VV mg_m idpath (h mg_e))^ ((ap011_VV mg_m idpath (ap G mg_f0))^ @ ap (ap011 mg_m idpath) (ap_V G _)^) @ (ap011_1pp _ _ _)^) _); (* 7 *)\n    apply moveL_Vp; apply moveL_Vp.\n    refine (whiskerR (moveR_pV _ _ _ (homotopy_square_2 G mg_m mg_m G2 idpath mg_f0))^ _ @ concat_pp_p _ _ _ @ concat_pp_p _ _ _ @ _); (* 8 *)\n    apply whiskerL; refine (_ @ concat_p_pp _ _ _); apply whiskerL;\n    apply moveR_Vp.\n    refine (ap011_1qp1 mg_m (h (G a)) (h mg_e) @ _). (* 2 *)\n    unfold G2, MonoidalFunctor_equiv_inverse_G2;\n    refine (_ @ concat_p_pp _ _ _ @ concat_p_pp _ _ _);\n    apply moveL_Vp;\n    refine (_ @ whiskerR (ap_V G _)^ _);\n    apply moveL_Vp. (* 4 *)\n    refine (_ @ concat_p_pp _ _ _ @ whiskerR ((ap_pp G _ _)^ @ ap (ap G) (homotopy_square_2 F mg_m mg_m mg_f2 (h (G a)) (h mg_e) @ whiskerR (ap011 (ap011 mg_m) (d _)^ (d _)^) _) @ ap_pp G _ _) _ @ concat_pp_p _ _ _); (* 5 *)\n    apply whiskerL.\n    refine (whiskerL _ (ap_idmap _)^ @ homotopy_square h (ap011 mg_m (h (G a)) (h mg_e)) @ _); (* 3 *)\n    apply whiskerR; apply ap_compose.\n  Qed.\n\nLemma MonoidalFunctor_equiv_inverse\n  : MonoidalFunctor N M.\nProof.\n  srapply @Build_MonoidalFunctor.\n  + exact G.\n  + exact G0.\n  + exact G2.\n  + exact MonoidalFunctor_equiv_inverse_Galpha.\n  + exact MonoidalFunctor_equiv_inverse_Glambda.\n  + exact MonoidalFunctor_equiv_inverse_Grho.\nDefined.\n\nLemma MonoidalFunctor_equiv_inverse_Sect\n  : MonoidalNatIso (MonoidalFunctor_comp MonoidalFunctor_equiv_inverse F) (MonoidalFunctor_id M).\nProof.\n  srapply @Build_MonoidalNatIso; simpl.\n  + exact h.\n  + unfold G0, MonoidalFunctor_equiv_inverse_G0.\n    refine (concat_pp_p _ _ _ @ concat_pp_p _ _ _ @ _); apply moveR_Vp.\n    refine (whiskerR (ap_V G _) _ @ _ @ (concat_p1 _)^); apply moveR_Vp; constructor.\n  + intros; unfold G2, MonoidalFunctor_equiv_inverse_G2.\n    refine (concat_pp_p _ _ _ @ concat_pp_p _ _ _ @ concat_pp_p _ _ _ @ _ @ (concat_p1 _)^);\n    apply moveR_Vp.\n    refine (whiskerR (ap_V G _) _ @ _);\n    apply moveR_Vp.\n    refine (concat_p_pp _ _ _ @ whiskerR ((ap_pp G _ _)^ @ ap (ap G) (whiskerR (ap011 mg_mm (d _) (d _)) _ @ (homotopy_square_2 F mg_m mg_m mg_f2 (h a) (h b))^) @ ap_pp G _ _) _ @ concat_pp_p _ _ _ @ _);\n    apply whiskerL.\n    refine (whiskerR (ap_compose _ _ _)^ _ @ _).\n    refine ((homotopy_square h (ap011 mg_m (h a) (h b)))^ @ _);\n    apply whiskerL; apply ap_idmap.\nDefined.\n\nLemma MonoidalFunctor_equiv_inverse_Retr\n  : MonoidalNatIso (MonoidalFunctor_comp F MonoidalFunctor_equiv_inverse) (MonoidalFunctor_id N).\nProof.\n  srapply @Build_MonoidalNatIso; simpl.\n  + exact k.\n  + unfold G0, MonoidalFunctor_equiv_inverse_G0.\n    refine (whiskerR (whiskerL _ (ap_pp F _ _ @ whiskerL _ (ap_compose _ _ _)^) @ concat_p_pp _ _ _) _ @ concat_pp_p _ _ _ @ _).\n    refine (whiskerL _ ((homotopy_square k mg_f0^)^ @ whiskerL _ (ap_idmap _)) @ concat_p_pp _ _ _ @ _); apply moveR_pV.\n    refine (concat_pp_p _ _ _ @ _ @ concat_p1 _ @ (concat_1p _)^); apply whiskerL.\n    refine (whiskerR (ap_V F _) _ @ _); apply moveR_Vp; refine (_ @ (concat_p1 _)^).\n    apply d.\n  + intros; unfold G2, MonoidalFunctor_equiv_inverse_G2.\n    repeat rewrite (ap_pp F _ _).\n    refine (whiskerR (concat_p_pp _ _ _) _ @ concat_pp_p _ _ _ @ whiskerL _ (whiskerR (ap_compose _ _ _)^ _) @ _ @ (concat_p1 _)^).\n    refine (whiskerL _ ((homotopy_square k (mg_mm (k a) (k b)))^ @ whiskerL _ (ap_idmap _)) @ concat_p_pp _ _ _ @ _ @ (concat_1p _)); apply whiskerR.\n    repeat rewrite ap_V.\n    repeat rewrite <- d.\n    refine (concat_pp_p _ _ _ @ _); apply moveR_Mp.\n    refine (concat_pp_p _ _ _ @ _ @ (concat_p1 _)^); apply moveR_Vp.\n    repeat rewrite <- ap_V.\n    repeat rewrite <- ap_compose.\n    refine ((homotopy_square k (mg_f2 (G a) (G b))^)^ @ _); apply whiskerL; apply ap_idmap.\nQed.\n\nLemma MonoidalEquivalence_from_equivalence\n  : MonoidalEquivalence M N.\nProof.\n  exists F.\n  exists MonoidalFunctor_equiv_inverse.\n  exact (MonoidalFunctor_equiv_inverse_Sect, MonoidalFunctor_equiv_inverse_Retr).\nDefined.\n\nEnd Inverse.\n\nEnd MonoidalGroupoids.\n ", "meta": {"author": "spiceghello", "repo": "FSMG", "sha": "796391b5da61564a984d405747b79166b3e698a5", "save_path": "github-repos/coq/spiceghello-FSMG", "path": "github-repos/coq/spiceghello-FSMG/FSMG-796391b5da61564a984d405747b79166b3e698a5/monoidalgroupoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240721511739, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.6970523551309177}}
{"text": "(* Exercise 21 *) \n\nRequire Import BenB.\n\nDefinition D:=R.\n\nVariables P Q S T : D -> Prop.\n\nTheorem exercise_021 : ~((forall x : D, P (x+2)) /\\ (exists x : D, ~ P (x-3))).\nProof.\nneg_i (forall x:D, P (x - 3)) a1.\nexi_e (exists x:D, ~P (x - 3)) a a2.\ncon_e2 (forall x:D, P (x+2)).\nhyp a1.\nneg_i (P (a-3)) a3.\nhyp a2.\nall_e (forall x:D, P (x - 3)) a.\nhyp a3.\nall_i a.\nneg_e' (forall x:D, P (x-3)) a2.\nneg_i (P (a-3)) a3.\nhyp a2.\nall_e (forall x:D, P (x-3)) a.\nhyp a3.\nall_i b.\nreplace (b - 3) with (b - 5 + 2).\nall_e (forall x:D, P (x + 2)) (b - 5).\ncon_e1 (exists x:D, ~P (x - 3)).\nhyp a1.\nlin_solve.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_real021.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6969882684478427}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) (lf2 : natural)\n  : natural := plus (Succ y) Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj187_coqofml_RMB633.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6968999504479992}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf2 : natural) (y : natural) (x : natural)\n  : natural := plus (Succ Zero) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj237_coqofml_1eUbGQ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6968999336877582}}
{"text": "Require Import  prosa.classic.util.all.\nRequire Import  prosa.classic.model.time\n                prosa.classic.model.arrival.basic.task \n                prosa.classic.model.arrival.basic.job.\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq fintype bigop div.\n\nModule PolicyTDMA.\n\n  Import Time.\n\n  (** In this section, we define the TDMA policy.*)\n  Section TDMA.\n    (* The TDMA policy is based on two properties.\n      (1) Each task has a fixed, reserved time slot for execution;\n      (2) These time slots are ordered in sequence to form a TDMA cycle, which repeats along the timeline.\n      An example of TDMA schedule is illustrated in the following.\n      ______________________________\n      | s1 |  s2  |s3| s1 |  s2  |s3|...\n      --------------------------------------------->\n      0                                            t\n    *)\n    Variable Task: eqType.\n    (* With each task, we associate the duration of the corresponding TDMA slot. *)\n    Definition TDMA_slot:= Task -> duration.\n    (* Moreover, within each TDMA cycle, task slots are ordered according to some relation. *)\n    Definition TDMA_slot_order:= rel Task.\n\n  End TDMA.\n\n  (** In this section, we define the properties of TDMA and prove some basic lemmas. *)\n  Section PropertiesTDMA.\n\n    Context {Task:eqType}.\n\n    (* Consider any task set ts... *)\n    Variable ts: {set Task}.\n\n    (* ...and any slot order (i.e, slot_order slot1 slot2 means that slot1 comes before slot2 in a TDMA cycle). *)\n    Variable slot_order: TDMA_slot_order Task.\n\n    (* First, we define the properties of a valid time slot order. *)\n    Section Relation.\n      (* Time slot order must transitive... *)\n      Definition slot_order_is_transitive:= transitive slot_order.\n\n      (* ..., totally ordered over the task set... *)\n      Definition slot_order_is_total_over_task_set :=\n        total_over_list slot_order ts.\n\n      (* ... and antisymmetric over task set. *)\n      Definition slot_order_is_antisymmetric_over_task_set :=\n        antisymmetric_over_list slot_order ts. \n\n    End Relation.\n\n    (* Next, we define some properties of task time slots *)\n    Section TimeSlot.\n\n      (* Consider any task in task set ts*)\n      Variable task: Task.\n      Hypothesis H_task_in_ts: task \\in ts. \n\n      (* Consider any TDMA slot assignment for these tasks *)\n      Variable task_time_slot: TDMA_slot Task.\n\n      (* A valid time slot must be positive *)\n      Definition is_valid_time_slot:=\n        task_time_slot task > 0.\n\n      (* We define the TDMA cycle as the sum of all the tasks' time slots *)\n      Definition TDMA_cycle:= \n        \\sum_(tsk <- ts) task_time_slot tsk.\n\n       (* We define the function returning the slot offset for each task: \n         i.e., the distance between the start of the TDMA cycle and \n         the start of the task time slot *)\n      Definition Task_slot_offset:= \n        \\sum_(prev_task <- ts | slot_order prev_task task && (prev_task != task)) task_time_slot prev_task.\n\n      (* The following function tests whether a task is in its time slot at instant t *)\n      Definition Task_in_time_slot (t:time):=\n       ((t + TDMA_cycle - (Task_slot_offset)%% TDMA_cycle) %% TDMA_cycle) \n        < (task_time_slot task).\n\n      Section BasicLemmas.\n\n        (* Assume task_time_slot is valid time slot*)\n        Hypothesis time_slot_positive:\n          is_valid_time_slot.\n\n        (* Obviously, the TDMA cycle is greater or equal than any task time slot which is \n          in TDMA cycle *)\n        Lemma TDMA_cycle_ge_each_time_slot:\n          TDMA_cycle >= task_time_slot task.\n        Proof. \n        rewrite /TDMA_cycle (big_rem task) //.\n        apply:leq_trans; last by exact: leq_addr.\n        by apply leqnn.\n        Qed.\n\n        (* Thus, a TDMA cycle is always positive *)\n        Lemma TDMA_cycle_positive:\n          TDMA_cycle > 0.\n        Proof.\n        move:time_slot_positive. move/leq_trans;apply;apply TDMA_cycle_ge_each_time_slot.\n        Qed.\n\n        (* Slot offset is less then cycle *)\n        Lemma Offset_lt_cycle:\n          Task_slot_offset < TDMA_cycle.\n        Proof.\n        rewrite /Task_slot_offset /TDMA_cycle big_mkcond.\n        apply leq_ltn_trans with (n:=\\sum_(prev_task <- ts )if prev_task!=task then task_time_slot prev_task else 0).\n        - apply leq_sum. intros* T. case (slot_order i task);auto.\n        - rewrite -big_mkcond. rewrite-> bigD1_seq with (j:=task);auto.\n          rewrite -subn_gt0 -addnBA. rewrite subnn addn0 //.\n          trivial. apply (set_uniq ts).\n        Qed.\n\n        (* For a task, the sum of its slot offset and its time slot is \n          less then or equal to cycle. *)\n        Lemma Offset_add_slot_leq_cycle:\n          Task_slot_offset + task_time_slot task <= TDMA_cycle.\n        Proof.\n        rewrite /Task_slot_offset /TDMA_cycle.\n        rewrite addnC (bigD1_seq task) //=. rewrite leq_add2l.\n        rewrite big_mkcond.\n        replace (\\sum_(i <- ts | i != task) task_time_slot i)\n        with (\\sum_(i <- ts ) if i != task then task_time_slot i else 0).\n        apply leq_sum. intros*T. case (slot_order i task);auto.\n        by rewrite -big_mkcond. apply (set_uniq ts).\n        Qed.\n\n      End BasicLemmas.\n\n    End TimeSlot.\n\n    (* In this section, we prove that no two tasks share the same time slot at any time. *)\n    Section InTimeSlotUniq.\n\n      (* Consider any TDMA slot assignment for these tasks *)\n      Variable task_time_slot: TDMA_slot Task.\n\n      (* Assume that slot order is total... *)\n      Hypothesis slot_order_total:\n        slot_order_is_total_over_task_set.\n\n      (*..., antisymmetric... *)\n      Hypothesis slot_order_antisymmetric:\n        slot_order_is_antisymmetric_over_task_set.\n\n      (*... and transitive. *)\n      Hypothesis slot_order_transitive:\n        slot_order_is_transitive.\n\n      (* Then, we can prove that the difference value between two offsets is\n        at least a slot *)\n      Lemma relation_offset:\n        forall tsk1 tsk2, tsk1 \\in ts -> tsk2 \\in ts ->\n        slot_order tsk1 tsk2 -> tsk1 != tsk2 ->\n        Task_slot_offset tsk2 task_time_slot >= Task_slot_offset tsk1 task_time_slot + task_time_slot tsk1 .\n      Proof.\n      intros* IN1 IN2 ORDER NEQ.\n      rewrite /Task_slot_offset big_mkcond addnC.\n      replace (\\sum_(tsk <- ts | slot_order tsk tsk2 && (tsk != tsk2)) task_time_slot tsk)\n        with (task_time_slot tsk1 + \\sum_(tsk <- ts )if slot_order tsk tsk2 && (tsk != tsk1) && (tsk!=tsk2) then task_time_slot tsk else O).\n      rewrite leq_add2l. apply leq_sum_seq. intros* IN T.\n      case (slot_order i tsk1)eqn:SI2;auto. case (i==tsk1)eqn:IT2;auto;simpl.\n      case (i==tsk2)eqn:IT1;simpl;auto.\n      - by move/eqP in IT1;rewrite IT1 in SI2;apply slot_order_antisymmetric in ORDER;auto;apply ORDER in SI2;move/eqP in NEQ.\n      - by rewrite (slot_order_transitive _ _ _ SI2 ORDER).\n      - symmetry. rewrite big_mkcond /=. rewrite->bigD1_seq with (j:=tsk1);auto;last by apply (set_uniq ts).\n        move/eqP /eqP in ORDER. move/eqP in NEQ. rewrite ORDER //=. apply /eqP.\n        have TS2: (tsk1 != tsk2) = true . apply /eqP;auto. rewrite TS2.\n        rewrite eqn_add2l. rewrite big_mkcond. apply/eqP. apply eq_bigr;auto.\n        intros* T. case(i!=tsk1);case (slot_order i tsk2);case (i!=tsk2) ;auto.\n      Qed.\n\n      (* Then, we proved that no two tasks share the same time slot at any time. *)\n      Lemma task_in_time_slot_uniq:\n        forall tsk1 tsk2 t, tsk1 \\in ts -> task_time_slot tsk1 > 0 ->\n        tsk2 \\in ts -> task_time_slot tsk2 > 0 ->\n        Task_in_time_slot tsk1 task_time_slot t ->\n        Task_in_time_slot tsk2 task_time_slot t ->\n        tsk1 = tsk2.\n      Proof.\n      intros* IN1 SLOT1 IN2 SLOT2.\n      rewrite /Task_in_time_slot.\n      set cycle:=TDMA_cycle task_time_slot.\n      set O1:= Task_slot_offset tsk1 task_time_slot.\n      set O2:= Task_slot_offset tsk2 task_time_slot.\n      have CO1: O1 < cycle by apply Offset_lt_cycle.\n      have CO2: O2 < cycle by apply Offset_lt_cycle.\n      have C: cycle > 0 by apply (TDMA_cycle_positive tsk1).\n      have GO1:O1 %% cycle = O1 by apply modn_small,Offset_lt_cycle. rewrite GO1.\n      have GO2:O2 %% cycle = O2 by apply modn_small,Offset_lt_cycle. rewrite GO2.\n      have SO1:O1 + task_time_slot tsk1 <= cycle by apply (Offset_add_slot_leq_cycle tsk1).\n      have SO2:O2 + task_time_slot tsk2 <= cycle by apply (Offset_add_slot_leq_cycle tsk2).\n      repeat rewrite mod_elim;auto.\n      case (O1 <= t%%cycle)eqn:O1T;case (O2 <= t %%cycle)eqn:O2T;intros G1 G2;try ssromega.\n      apply util.nat.ltn_subLR in G1;apply util.nat.ltn_subLR in G2. case (tsk1==tsk2) eqn:NEQ;move/eqP in NEQ;auto.\n      destruct (slot_order_total tsk1 tsk2) as [order |order];auto;apply relation_offset in order;\n      fold O1 O2 in order;try ssromega;auto. by move/eqP in NEQ. apply /eqP;auto.\n      Qed.\n\n    End InTimeSlotUniq.\n\n  End PropertiesTDMA.\n\nEnd PolicyTDMA.\n\n\n\n", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/classic/model/policy_tdma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6968999236739787}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL B FREE SOFTWARE LICENSE AGREEMENT           *)\n(**************************************************************)\n\nFrom Coq\n  Require Import Arith List.\n\nFrom KruskalTrees\n  Require Import notations.\n\nImport ListNotations.\n\nSet Implicit Arguments.\n\nSection list_sum.\n\n  Variables (X : Type) (f : X -> nat).\n\n  Fixpoint list_sum l :=\n    match l with\n      | []   => 0\n      | x::l => f x + list_sum l\n    end.\n\n  Fact list_sum_app l m : list_sum (l++m) = list_sum l + list_sum m.\n  Proof.\n    induction l as [ | x l IHl ]; simpl; auto.\n    now rewrite IHl, plus_assoc.\n  Qed.\n\n  Hint Resolve le_trans le_plus_l le_plus_r : core.\n\n  Fact list_sum_in x l : x ∈ l -> f x <= list_sum l.\n  Proof.\n    induction l as [ | y l IHl ].\n    + intros [].\n    + intros [ <- | Hl%IHl ]; simpl; eauto.\n  Qed.\n\nEnd list_sum.\n", "meta": {"author": "DmxLarchey", "repo": "Kruskal-Trees", "sha": "3118293d44b79655eea068a77ea5ea010211f8b4", "save_path": "github-repos/coq/DmxLarchey-Kruskal-Trees", "path": "github-repos/coq/DmxLarchey-Kruskal-Trees/Kruskal-Trees-3118293d44b79655eea068a77ea5ea010211f8b4/theories/list/list_sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.6968857151039208}}
{"text": "Require Import ZArith ROmega.\nOpen Scope Z_scope.\n\n(* Pierre L: examples gathered while debugging romega. *)\n\nLemma test_romega_0 :\n forall m m',\n  0<= m <= 1 -> 0<= m' <= 1 -> (0 < m <-> 0 < m') -> m = m'.\nProof.\nintros.\nromega.\nQed.\n\nLemma test_romega_0b :\n forall m m',\n  0<= m <= 1 -> 0<= m' <= 1 -> (0 < m <-> 0 < m') -> m = m'.\nProof.\nintros m m'.\nromega.\nQed.\n\nLemma test_romega_1 :\n forall (z z1 z2 : Z),\n    z2 <= z1 ->\n    z1 <= z2 ->\n    z1 >= 0 ->\n    z2 >= 0 ->\n    z1 >= z2 /\\ z = z1 \\/ z1 <= z2 /\\ z = z2 ->\n    z >= 0.\nProof.\nintros.\nromega.\nQed.\n\nLemma test_romega_1b :\n forall (z z1 z2 : Z),\n    z2 <= z1 ->\n    z1 <= z2 ->\n    z1 >= 0 ->\n    z2 >= 0 ->\n    z1 >= z2 /\\ z = z1 \\/ z1 <= z2 /\\ z = z2 ->\n    z >= 0.\nProof.\nintros z z1 z2.\nromega.\nQed.\n\nLemma test_romega_2 : forall a b c:Z,\n 0<=a-b<=1 -> b-c<=2 -> a-c<=3.\nProof.\nintros.\nromega.\nQed.\n\nLemma test_romega_2b : forall a b c:Z,\n 0<=a-b<=1 -> b-c<=2 -> a-c<=3.\nProof.\nintros a b c.\nromega.\nQed.\n\nLemma test_romega_3 : forall a b h hl hr ha hb,\n 0 <= ha - hl <= 1 ->\n -2 <= hl - hr <= 2 ->\n h =b+1 ->\n (ha >= hr /\\ a = ha \\/ ha <= hr /\\ a = hr) ->\n (hl >= hr /\\ b = hl \\/ hl <= hr /\\ b = hr) ->\n (-3 <= ha -hr <=3 -> 0 <= hb - a <= 1) ->\n (-2 <= ha-hr <=2 -> hb = a  + 1) ->\n 0 <= hb - h <= 1.\nProof.\nintros.\nromega.\nQed.\n\nLemma test_romega_3b : forall a b h hl hr ha hb,\n 0 <= ha - hl <= 1 ->\n -2 <= hl - hr <= 2 ->\n h =b+1 ->\n (ha >= hr /\\ a = ha \\/ ha <= hr /\\ a = hr) ->\n (hl >= hr /\\ b = hl \\/ hl <= hr /\\ b = hr) ->\n (-3 <= ha -hr <=3 -> 0 <= hb - a <= 1) ->\n (-2 <= ha-hr <=2 -> hb = a  + 1) ->\n 0 <= hb - h <= 1.\nProof.\nintros a b h hl hr ha hb.\nromega.\nQed.\n\n\nLemma test_romega_4 : forall hr ha,\n ha = 0 ->\n (ha = 0 -> hr =0) ->\n hr = 0.\nProof.\nintros hr ha.\nromega.\nQed.\n\nLemma test_romega_5 : forall hr ha,\n ha = 0 ->\n (~ha = 0 \\/ hr =0) ->\n hr = 0.\nProof.\nintros hr ha.\nromega.\nQed.\n\nLemma test_romega_6 : forall z, z>=0 -> 0>z+2 -> False.\nProof.\nintros.\nromega.\nQed.\n\nLemma test_romega_6b : forall z, z>=0 -> 0>z+2 -> False.\nProof.\nintros z.\nromega.\nQed.\n\nLemma test_romega_7 : forall z,\n  0>=0 /\\ z=0 \\/ 0<=0 /\\ z =0 -> 1 = z+1.\nProof.\nintros.\nromega.\nQed.\n\nLemma test_romega_7b : forall z,\n  0>=0 /\\ z=0 \\/ 0<=0 /\\ z =0 -> 1 = z+1.\nProof.\nintros.\nromega.\nQed.\n\n(* Magaud #240 *)\n\nLemma test_romega_8 : forall x y:Z, x*x<y*y-> ~ y*y <= x*x.\nintros.\nromega.\nQed.\n\nLemma test_romega_8b : forall x y:Z, x*x<y*y-> ~ y*y <= x*x.\nintros x y.\nromega.\nQed.\n\n(* Besson #1298 *)\n\nLemma test_romega9 : forall z z':Z, z<>z' -> z'=z -> False.\nintros.\nromega.\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/ROmega0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563823, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.6968856989033795}}
{"text": "(** * Poly: Polymorphism and Higher-Order Functions *)\n\n(* Final reminder: Please do not put solutions to the exercises in\n   publicly accessible places.  Thank you!! *)\n\n(* Suppress some annoying warnings from Coq: *)\nSet Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export Lists.\n\n(* ################################################################# *)\n(** * Polymorphism *)\n\n(** In this chapter we continue our development of basic\n    concepts of functional programming.  The critical new ideas are\n    _polymorphism_ (abstracting functions over the types of the data\n    they manipulate) and _higher-order functions_ (treating functions\n    as data).  We begin with polymorphism. *)\n\n(* ================================================================= *)\n(** ** Polymorphic Lists *)\n\n(** For the last chapter, we've been working with lists\n    containing just numbers.  Obviously, interesting programs also\n    need to be able to manipulate lists with elements from other\n    types -- lists of booleans, lists of lists, etc.  We _could_ just\n    define a new inductive datatype for each of these, for\n    example... *)\n\nInductive boollist : Type :=\n  | bool_nil\n  | bool_cons (b : bool) (l : boollist).\n\n(** ... but this would quickly become tedious, partly because we\n    have to make up different constructor names for each datatype, but\n    mostly because we would also need to define new versions of all\n    our list manipulating functions ([length], [rev], etc.) and all\n    their properties ([rev_length], [app_assoc], etc.) for each\n    new datatype definition. *)\n\n(** To avoid all this repetition, Coq supports _polymorphic_\n    inductive type definitions.  For example, here is a _polymorphic\n    list_ datatype. *)\n\nInductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\n(** This is exactly like the definition of [natlist] from the\n    previous chapter, except that the [nat] argument to the [cons]\n    constructor has been replaced by an arbitrary type [X], a binding\n    for [X] has been added to the function header on the first line,\n    and the occurrences of [natlist] in the types of the constructors\n    have been replaced by [list X].\n\n    What sort of thing is [list] itself?  A good way to think about it\n    is that the definition of [list] is a _function_ from [Type]s to\n    [Inductive] definitions; or, to put it more concisely, [list] is a\n    function from [Type]s to [Type]s.  For any particular type [X],\n    the type [list X] is the [Inductive]ly defined set of lists whose\n    elements are of type [X]. *)\n\nCheck list : Type -> Type.\n\n(** The [X] in the definition of [list] automatically becomes a\n    parameter to the constructors [nil] and [cons] -- that is, [nil]\n    and [cons] are now polymorphic constructors; when we use them, we\n    must now provide a first argument that is the type of the list\n    they are building. For example, [nil nat] constructs the empty\n    list of type [nat]. *)\n\nCheck (nil nat) : list nat.\n\n(** Similarly, [cons nat] adds an element of type [nat] to a list of\n    type [list nat]. Here is an example of forming a list containing\n    just the natural number 3. *)\n\nCheck (cons nat 3 (nil nat)) : list nat.\n\n(** What might the type of [nil] be? We can read off the type\n    [list X] from the definition, but this omits the binding for [X]\n    which is the parameter to [list]. [Type -> list X] does not\n    explain the meaning of [X]. [(X : Type) -> list X] comes\n    closer. Coq's notation for this situation is [forall X : Type,\n    list X]. *)\n\nCheck nil : forall X : Type, list X.\n\n(** Similarly, the type of [cons] from the definition looks like\n    [X -> list X -> list X], but using this convention to explain the\n    meaning of [X] results in the type [forall X, X -> list X -> list\n    X]. *)\n\nCheck cons : forall X : Type, X -> list X -> list X.\n\n(** (A side note on notations: In .v files, the \"forall\"\n    quantifier is spelled out in letters.  In the corresponding HTML\n    files (and in the way some IDEs show .v files, depending on the\n    settings of their display controls), [forall] is usually typeset\n    as the standard mathematical \"upside down A,\" though you'll still\n    see the spelled-out \"forall\" in a few places.  This is just a\n    quirk of typesetting -- there is no difference in meaning.) *)\n\n(** Having to supply a type argument for every single use of a\n    list constructor would be rather burdensome; we will soon see ways\n    of reducing this annotation burden. *)\n\nCheck (cons nat 2 (cons nat 1 (nil nat)))\n      : list nat.\n\n(** We can now go back and make polymorphic versions of all the\n    list-processing functions that we wrote before.  Here is [repeat],\n    for example: *)\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\n(** As with [nil] and [cons], we can use [repeat] by applying it\n    first to a type and then to an element of this type (and a number): *)\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity. Qed.\n\n(** To use [repeat] to build other kinds of lists, we simply\n    instantiate it with an appropriate type parameter: *)\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, standard, optional (mumble_grumble)\n\n    Consider the following two inductively defined types. *)\n\nModule MumbleGrumble.\n\nInductive mumble : Type :=\n  | a\n  | b (x : mumble) (y : nat)\n  | c.\n\nInductive grumble (X:Type) : Type :=\n  | d (m : mumble)\n  | e (x : X).\n\n(** Which of the following are well-typed elements of [grumble X] for\n    some type [X]?  (Add YES or NO to each line.)\n      - [d (b a 5)]\n      - [d mumble (b a 5)]\n      - [d bool (b a 5)]\n      - [e bool true]\n      - [e mumble (b c 0)]\n      - [e bool (b c 0)]\n      - [c]  *)\nEval compute in d mumble (b a 5).\nEval compute in d bool (b a 5).\nEval compute in e bool true.\nEval compute in e mumble (b c 0).\nEnd MumbleGrumble.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Annotation Inference *)\n\n(** Let's write the definition of [repeat] again, but this time we\n    won't specify the types of any of the arguments.  Will Coq still\n    accept it? *)\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0        => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\n(** Indeed it will.  Let's see what type Coq has assigned to [repeat']... *)\n\nCheck repeat'\n  : forall X : Type, X -> nat -> list X.\nCheck repeat\n  : forall X : Type, X -> nat -> list X.\n\n(** It has exactly the same type as [repeat].  Coq was able to\n    use _type inference_ to deduce what the types of [X], [x], and\n    [count] must be, based on how they are used.  For example, since\n    [X] is used as an argument to [cons], it must be a [Type], since\n    [cons] expects a [Type] as its first argument; matching [count]\n    with [0] and [S] means it must be a [nat]; and so on.\n\n    This powerful facility means we don't always have to write\n    explicit type annotations everywhere, although explicit type\n    annotations can still be quite useful as documentation and sanity\n    checks, so we will continue to use them much of the time. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Argument Synthesis *)\n\n(** To use a polymorphic function, we need to pass it one or\n    more types in addition to its other arguments.  For example, the\n    recursive call in the body of the [repeat] function above must\n    pass along the type [X].  But since the second argument to\n    [repeat] is an element of [X], it seems entirely obvious that the\n    first argument can only be [X] -- why should we have to write it\n    explicitly?\n\n    Fortunately, Coq permits us to avoid this kind of redundancy.  In\n    place of any type argument we can write a \"hole\" [_], which can be\n    read as \"Please try to figure out for yourself what belongs here.\"\n    More precisely, when Coq encounters a [_], it will attempt to\n    _unify_ all locally available information -- the type of the\n    function being applied, the types of the other arguments, and the\n    type expected by the context in which the application appears --\n    to determine what concrete type should replace the [_].\n\n    This may sound similar to type annotation inference -- and, indeed,\n    the two procedures rely on the same underlying mechanisms.  Instead\n    of simply omitting the types of some arguments to a function, like\n\n      repeat' X x count : list X :=\n\n    we can also replace the types with holes\n\n      repeat' (X : _) (x : _) (count : _) : list X :=\n\n    to tell Coq to attempt to infer the missing information.\n\n    Using holes, the [repeat] function can be written like this: *)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n(** In this instance, we don't save much by writing [_] instead of\n    [X].  But in many cases the difference in both keystrokes and\n    readability is nontrivial.  For example, suppose we want to write\n    down a list containing the numbers [1], [2], and [3].  Instead of\n    this... *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...we can use holes to write this: *)\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ----------------------------------------------------------------- *)\n(** *** Implicit Arguments *)\n\n(** In fact, we can go further and even avoid writing [_]'s in most\n    cases by telling Coq _always_ to infer the type argument(s) of a\n    given function.\n\n    The [Arguments] directive specifies the name of the function (or\n    constructor) and then lists the (leading) argument names to be\n    treated as implicit, each surrounded by curly braces. *)\n\nArguments nil {X}.\nArguments cons {X}.\nArguments repeat {X}.\n\n(** Now we don't have to supply any type arguments at all in the example: *)\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\n(** Alternatively, we can declare an argument to be implicit\n    when defining the function itself, by surrounding it in curly\n    braces instead of parens.  For example: *)\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0        => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n(** (Note that we didn't even have to provide a type argument to the\n    recursive call to [repeat'''].  Indeed, it would be invalid to\n    provide one, because Coq is not expecting it.)\n\n    We will use the latter style whenever possible, but we will\n    continue to use explicit [Argument] declarations for [Inductive]\n    constructors.  The reason for this is that marking the parameter\n    of an inductive type as implicit causes it to become implicit for\n    the type itself, not just for its constructors.  For instance,\n    consider the following alternative definition of the [list]\n    type: *)\n\nInductive list' {X:Type} : Type :=\n  | nil'\n  | cons' (x : X) (l : list').\n\n(** Because [X] is declared as implicit for the _entire_ inductive\n    definition including [list'] itself, we now have to write just\n    [list'] whether we are talking about lists of numbers or booleans\n    or anything else, rather than [list' nat] or [list' bool] or\n    whatever; this is a step too far. *)\n\n(** Let's finish by re-implementing a few other standard list\n    functions on our new polymorphic lists... *)\n\nFixpoint app {X : Type} (l1 l2 : list X) : list X :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity. Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Supplying Type Arguments Explicitly *)\n\n(** One small problem with declaring arguments to be implicit is\n    that, once in a while, Coq does not have enough local information\n    to determine a type argument; in such cases, we need to tell Coq\n    that we want to give the argument explicitly just this time.  For\n    example, suppose we write this: *)\n\nFail Definition mynil := nil.\n\n(** (The [Fail] qualifier that appears before [Definition] can be\n    used with _any_ command, and is used to ensure that that command\n    indeed fails when executed. If the command does fail, Coq prints\n    the corresponding error message, but continues processing the rest\n    of the file.)\n\n    Here, Coq gives us an error because it doesn't know what type\n    argument to supply to [nil].  We can help it by providing an\n    explicit type declaration (so that Coq has more information\n    available when it gets to the \"application\" of [nil]): *)\n\nDefinition mynil : list nat := nil.\n\n(** Alternatively, we can force the implicit arguments to be explicit by\n    prefixing the function name with [@]. *)\n\nCheck @nil : forall X : Type, list X.\n\nDefinition mynil' := @nil nat.\n\n(** Using argument synthesis and implicit arguments, we can\n    define convenient notation for lists, as before.  Since we have\n    made the constructor type arguments implicit, Coq will know to\n    automatically infer these when we use the notations. *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** Now lists can be written just the way we'd hope: *)\n\nDefinition list123''' := [1; 2; 3].\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, standard (poly_exercises)\n\n    Here are a few simple exercises, just like ones in the [Lists]\n    chapter, for practice with polymorphism.  Complete the proofs\n    below. *)\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros X.\n  induction l as [| n l'].\n  - reflexivity.\n  - simpl. rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros X l1 l2 l3.\n  induction l1 as [| n 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 X l1 l2.\n  induction l1 as [| n l1' IHl1'].\n  - reflexivity.\n  - simpl. rewrite -> IHl1'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (more_poly_exercises)\n\n    Here are some slightly more interesting ones... *)\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros X l1 l2.\n  induction l1.\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IHl1. rewrite -> app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros X l.\n  induction l.\n  - reflexivity.\n  - simpl.\n    rewrite -> rev_app_distr. rewrite -> IHl. reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Pairs *)\n\n(** Following the same pattern, the definition for pairs of\n    numbers that we gave in the last chapter can be generalized to\n    _polymorphic pairs_, often called _products_: *)\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\n\nArguments pair {X} {Y}.\n\n(** As with lists, we make the type arguments implicit and define the\n    familiar concrete notation. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** We can also use the [Notation] mechanism to define the standard\n    notation for _product types_ (i.e., the types of pairs): *)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** (The annotation [: type_scope] tells Coq that this abbreviation\n    should only be used when parsing types, not when parsing\n    expressions.  This avoids a clash with the multiplication\n    symbol.) *)\n\n(** It is easy at first to get [(x,y)] and [X*Y] confused.\n    Remember that [(x,y)] is a _value_ built from two other values,\n    while [X*Y] is a _type_ built from two other types.  If [x] has\n    type [X] and [y] has type [Y], then [(x,y)] has type [X*Y]. *)\n\n(** The first and second projection functions now look pretty\n    much as they would in any functional programming language. *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\n(** The following function takes two lists and combines them\n    into a list of pairs.  In other functional languages, it is often\n    called [zip]; we call it [combine] for consistency with Coq's\n    standard library. *)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\n(** **** Exercise: 1 star, standard, optional (combine_checks)\n\n    Try answering the following questions on paper and\n    checking your answers in Coq:\n    - What is the type of [combine] (i.e., what does [Check\n      @combine] print?)\n    - What does\n\n        Compute (combine [1;2] [false;false;true;true]).\n\n      print?\n\n    [] *)\n\n(** **** Exercise: 2 stars, standard, especially useful (split)\n\n    The function [split] is the right inverse of [combine]: it takes a\n    list of pairs and returns a pair of lists.  In many functional\n    languages, it is called [unzip].\n\n    Fill in the definition of [split] below.  Make sure it passes the\n    given unit test. *)\n\nFixpoint split {X Y : Type} (l : list (X*Y)) : (list X) * (list Y)\n  := match l with\n     | (m, n) :: l' => (m :: fst (split l'), n :: snd (split l'))\n     | nil          => ([], [])\n     end.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof.\n  reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Options *)\n\n(** Our last polymorphic type for now is _polymorphic options_,\n    which generalize [natoption] from the previous chapter.  (We put\n    the definition inside a module because the standard library\n    already defines [option] and it's this one that we want to use\n    below.) *)\n\nModule OptionPlayground.\n\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\n\nArguments Some {X}.\nArguments None {X}.\n\nEnd OptionPlayground.\n\n(** We can now rewrite the [nth_error] function so that it works\n    with any type of lists. *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | nil => None\n  | a :: l' => match n with\n               | O => Some a\n               | S n' => nth_error l' n'\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, standard, optional (hd_error_poly)\n\n    Complete the definition of a polymorphic version of the\n    [hd_error] function from the last chapter. Be sure that it\n    passes the unit tests below. *)\n\nDefinition hd_error {X : Type} (l : list X) : option X\n  := match l with\n     | nil    => None\n     | h :: _ => Some h\n     end.\n\n(** Once again, to force the implicit arguments to be explicit,\n    we can use [@] before the name of the function. *)\n\nCheck @hd_error : forall X : Type, list X -> option X.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Functions as Data *)\n\n(** Like most modern programming languages -- especially other\n    \"functional\" languages, including OCaml, Haskell, Racket, Scala,\n    Clojure, etc. -- Coq treats functions as first-class citizens,\n    allowing them to be passed as arguments to other functions,\n    returned as results, stored in data structures, etc. *)\n\n(* ================================================================= *)\n(** ** Higher-Order Functions *)\n\n(** Functions that manipulate other functions are often called\n    _higher-order_ functions.  Here's a simple one: *)\n\nDefinition doit3times {X : Type} (f : X->X) (n : X) : X :=\n  f (f (f n)).\n\n(** The argument [f] here is itself a function (from [X] to\n    [X]); the body of [doit3times] applies [f] three times to some\n    value [n]. *)\n\nCheck @doit3times : forall X : Type, (X -> X) -> X -> X.\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity. Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\n\n(* ================================================================= *)\n(** ** Filter *)\n\n(** Here is a more useful higher-order function, taking a list\n    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])\n    and \"filtering\" the list, returning a new list containing just\n    those elements for which the predicate returns [true]. *)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X) : 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\n(** For example, if we apply [filter] to the predicate [even]\n    and a list of numbers [l], it returns a list containing just the\n    even members of [l]. *)\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  (length l) =? 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\n(** We can use [filter] to give a concise version of the\n    [countoddmembers] function from the [Lists] chapter. *)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter odd l).\n\nExample test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity. Qed.\n\n(* ================================================================= *)\n(** ** Anonymous Functions *)\n\n(** It is arguably a little sad, in the example just above, to\n    be forced to define the function [length_is_1] and give it a name\n    just to be able to pass it as an argument to [filter], since we\n    will probably never use it again.  Moreover, this is not an\n    isolated example: when using higher-order functions, we often want\n    to pass as arguments \"one-off\" functions that we will never use\n    again; having to give each of these functions a name would be\n    tedious.\n\n    Fortunately, there is a better way.  We can construct a function\n    \"on the fly\" without declaring it at the top level or giving it a\n    name. *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity. Qed.\n\n(** The expression [(fun n => n * n)] can be read as \"the function\n    that, given a number [n], yields [n * n].\" *)\n\n(** Here is the [filter] example, rewritten to use an anonymous\n    function. *)\n\nExample test_filter2':\n    filter (fun l => (length l) =? 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, standard (filter_even_gt7)\n\n    Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat\n  := filter (fun n => (even n) && (leb 7 n)) l.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity.  Qed.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (partition)\n\n    Use [filter] to write a Coq function [partition]:\n\n      partition : forall X : Type,\n                  (X -> bool) -> list X -> list X * list X\n\n   Given a set [X], a predicate of type [X -> bool] and a [list X],\n   [partition] should return a pair of lists.  The first member of the\n   pair is the sublist of the original list containing the elements\n   that satisfy the test, and the second is the sublist containing\n   those that fail the test.  The order of elements in the two\n   sublists should be the same as their order in the original list. *)\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X\n  := (filter test l, filter (fun n => negb (test n)) l).\n\nExample test_partition1: partition odd [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Map *)\n\n(** Another handy higher-order function is called [map]. *)\n\nFixpoint map {X Y : Type} (f : X->Y) (l : list X) : list Y :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]\n    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has\n    been applied to each element of [l] in turn.  For example: *)\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\n(** The element types of the input and output lists need not be\n    the same, since [map] takes _two_ type arguments, [X] and [Y]; it\n    can thus be applied to a list of numbers and a function from\n    numbers to booleans to yield a list of booleans: *)\n\nExample test_map2:\n  map odd [2;1;2;5] = [false;true;false;true].\nProof. reflexivity. Qed.\n\n(** It can even be applied to a list of numbers and\n    a function from numbers to _lists_ of booleans to\n    yield a _list of lists_ of booleans: *)\n\nExample test_map3:\n    map (fun n => [even n;odd n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 3 stars, standard (map_rev)\n\n    Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\nLemma app_map : forall (X Y : Type) (f : X -> Y) (l : list X) (x : X),\n  app (map f l) [f x] = map f (app l [x]).\nProof.\n  intros X Y f l x.\n  induction l.\n  reflexivity.\n  simpl. rewrite -> IHl. reflexivity.\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros X Y f l.\n  induction l as [|x l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = n :: l' *)\n    simpl. rewrite <- IHl'. simpl.\n    rewrite -> app_map. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, especially useful (flat_map)\n\n    The function [map] maps a [list X] to a [list Y] using a function\n    of type [X -> Y].  We can define a similar function, [flat_map],\n    which maps a [list X] to a [list Y] using a function [f] of type\n    [X -> list Y].  Your definition should work by 'flattening' the\n    results of [f], like so:\n\n        flat_map (fun n => [n;n+1;n+2]) [1;5;10]\n      = [1; 2; 3; 5; 6; 7; 10; 11; 12].\n*)\n\nFixpoint flat_map {X Y: Type} (f: X -> list Y) (l: list X)\n                   : list Y\n  := match l with\n     | nil     => nil\n     | x :: l' => (f x) ++ flat_map f l'\n     end.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\nProof. reflexivity. Qed.\n(** [] *)\n\n(** Lists are not the only inductive type for which [map] makes sense.\n    Here is a [map] for the [option] type: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n  | None => None\n  | Some x => Some (f x)\n  end.\n\n(** **** Exercise: 2 stars, standard, optional (implicit_args)\n\n    The definitions and uses of [filter] and [map] use implicit\n    arguments in many places.  Replace the curly braces around the\n    implicit arguments with parentheses, and then fill in explicit\n    type parameters where necessary and use Coq to check that you've\n    done so correctly.  (This exercise is not to be turned in; it is\n    probably easiest to do it on a _copy_ of this file that you can\n    throw away afterwards.)\n*)\n(** [] *)\n\n(* ================================================================= *)\n(** ** Fold *)\n\n(** An even more powerful higher-order function is called\n    [fold].  This function is the inspiration for the \"[reduce]\"\n    operation that lies at the heart of Google's map/reduce\n    distributed programming framework. *)\n\nFixpoint fold {X Y: Type} (f : X->Y->Y) (l : list X) (b : Y)\n                         : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(** Intuitively, the behavior of the [fold] operation is to\n    insert a given binary operator [f] between every pair of elements\n    in a given list.  For example, [ fold plus [1;2;3;4] ] intuitively\n    means [1+2+3+4].  To make this precise, we also need a \"starting\n    element\" that serves as the initial second input to [f].  So, for\n    example,\n\n       fold plus [1;2;3;4] 0\n\n    yields\n\n       1 + (2 + (3 + (4 + 0))).\n\n    Some more examples: *)\n\nCheck (fold andb) : list bool -> bool -> bool.\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, standard, optional (fold_types_different)\n\n    Observe that the type of [fold] is parameterized by _two_ type\n    variables, [X] and [Y], and the parameter [f] is a binary operator\n    that takes an [X] and a [Y] and returns a [Y].  Can you think of a\n    situation where it would be useful for [X] and [Y] to be\n    different? *)\n\nDefinition flat_map' {X : Type} (l : list (list X)) : list X\n  := fold app l [].\n\n(* ================================================================= *)\n(** ** Functions That Construct Functions *)\n\n(** Most of the higher-order functions we have talked about so\n    far take functions as arguments.  Let's look at some examples that\n    involve _returning_ functions as the results of other functions.\n    To begin, here is a function that takes a value [x] (drawn from\n    some type [X]) and returns a function from [nat] to [X] that\n    yields [x] whenever it is called, ignoring its [nat] argument. *)\n\nDefinition constfun {X: Type} (x: X) : nat -> X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** In fact, the multiple-argument functions we have already\n    seen are also examples of passing functions as data.  To see why,\n    recall the type of [plus]. *)\n\nCheck plus : nat -> nat -> nat.\n\n(** Each [->] in this expression is actually a _binary_ operator\n    on types.  This operator is _right-associative_, so the type of\n    [plus] is really a shorthand for [nat -> (nat -> nat)] -- i.e., it\n    can be read as saying that \"[plus] is a one-argument function that\n    takes a [nat] and returns a one-argument function that takes\n    another [nat] and returns a [nat].\"  In the examples above, we\n    have always applied [plus] to both of its arguments at once, but\n    if we like we can supply just the first.  This is called _partial\n    application_. *)\n\nDefinition plus3 := plus 3.\nCheck plus3 : nat -> nat.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity. Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity. Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity. Qed.\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\nModule Exercises.\n\n(** **** Exercise: 2 stars, standard (fold_length)\n\n    Many common functions on lists can be implemented in terms of\n    [fold].  For example, here is an alternative definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length].  (Hint: It may help to\n    know that [reflexivity] simplifies expressions a bit more\n    aggressively than [simpl] does -- i.e., you may find yourself in a\n    situation where [simpl] does nothing but [reflexivity] solves the\n    goal.) *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros X l.\n  induction l as [| x l' IHl'].\n  reflexivity. simpl. rewrite <- IHl'.\n  simpl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (fold_map)\n\n    We can also define [map] in terms of [fold].  Finish [fold_map]\n    below. *)\n\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y\n  := fold (fun x l => cons (f x) l) l [].\n\n(** Write down a theorem [fold_map_correct] in Coq stating that\n    [fold_map] is correct, and prove it.  (Hint: again, remember that\n    [reflexivity] simplifies expressions a bit more aggressively than\n    [simpl].) *)\n\nTheorem fold_map_correct : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f l = fold_map f l.\nProof.\n  intros X Y f l.\n  induction l as [|x l'].\n  reflexivity.\n  simpl. rewrite -> IHl'.\n  simpl. reflexivity.\nQed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_map : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (currying)\n\n    The type [X -> Y -> Z] can be read as describing functions that\n    take two arguments, one of type [X] and another of type [Y], and\n    return an output of type [Z]. Strictly speaking, this type is\n    written [X -> (Y -> Z)] when fully parenthesized.  That is, if we\n    have [f : X -> Y -> Z], and we give [f] an input of type [X], it\n    will give us as output a function of type [Y -> Z].  If we then\n    give that function an input of type [Y], it will return an output\n    of type [Z]. That is, every function in Coq takes only one input,\n    but some functions return a function as output. This is precisely\n    what enables partial application, as we saw above with [plus3].\n\n    By contrast, functions of type [X * Y -> Z] -- which when fully\n    parenthesized is written [(X * Y) -> Z] -- require their single\n    input to be a pair.  Both arguments must be given at once; there\n    is no possibility of partial application.\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\n    _currying_, in honor of the logician Haskell Curry.  Converting\n    from [X -> Y -> Z] to [X * Y -> Z] is called _uncurrying_.  *)\n\n(** We can define currying as follows: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** As an exercise, define its inverse, [prod_uncurry].  Then prove\n    the theorems below to show that the two are inverses. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z\n  := f (fst p) (snd p).\n\n(** As a (trivial) example of the usefulness of currying, we can use it\n    to shorten one of the examples that we saw above: *)\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\n(** Thought exercise: before running the following commands, can you\n    calculate the types of [prod_curry] and [prod_uncurry]? *)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  reflexivity. Qed.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  destruct p. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (nth_error_informal)\n\n    Recall the definition of the [nth_error] function:\n\n   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n     match l with\n     | [] => None\n     | a :: l' => if n =? O then Some a else nth_error l' (pred n)\n     end.\n\n   Write a careful informal proof of the following theorem:\n\n   forall X l n, length l = n -> @nth_error X l n = None\n\n   Make sure to state the induction hypothesis _explicitly_.\n*)\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_proof : option (nat*string) := None.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Church Numerals (Advanced) *)\n\n(** The following exercises explore an alternative way of defining\n    natural numbers using the _Church numerals_, which are named after\n    their inventor, the mathematician Alonzo Church.  We can represent\n    a natural number [n] as a function that takes a function [f] as a\n    parameter and returns [f] iterated [n] times. *)\n\nModule Church.\nDefinition cnat := forall X : Type, (X -> X) -> X -> X.\n\n(** Let's see how to write some numbers with this notation. Iterating\n    a function once should be the same as just applying it.  Thus: *)\n\nDefinition one : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** Similarly, [two] should apply [f] twice to its argument: *)\n\nDefinition two : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** Defining [zero] is somewhat trickier: how can we \"apply a function\n    zero times\"?  The answer is actually simple: just return the\n    argument untouched. *)\n\nDefinition zero : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(** More generally, a number [n] can be written as [fun X f x => f (f\n    ... (f x) ...)], with [n] occurrences of [f].  Let's informally\n    notate that as [fun X f x => f^n x], with the convention that [f^0 x]\n    is just [x]. Note how the [doit3times] function we've defined\n    previously is actually just the Church representation of [3]. *)\n\nDefinition three : cnat := @doit3times.\n\n(** So [n X f x] represents \"do it [n] times\", where [n] is a Church\n    numerals and \"it\" means applying [f] starting with [x].\n\n    Another way to think about the Church representation is that\n    function [f] represents the successor operation on [X], and value\n    [x] represents the zero element of [X].  We could even rewrite\n    with those names to make it clearer: *)\n\nDefinition zero' : cnat :=\n  fun (X : Type) (succ : X -> X) (zero : X) => zero.\nDefinition one' : cnat :=\n  fun (X : Type) (succ : X -> X) (zero : X) => succ zero.\nDefinition two' : cnat :=\n  fun (X : Type) (succ : X -> X) (zero : X) => succ (succ zero).\n\n(** If we passed in [S] as [succ] and [O] as [zero], we'd even get the Peano\n    naturals as a result: *)\n\nExample zero_church_peano : zero nat S O = 0.\nProof. reflexivity. Qed.\n\nExample one_church_peano : one nat S O = 1.\nProof. reflexivity. Qed.\n\nExample two_church_peano : two nat S O = 2.\nProof. reflexivity. Qed.\n\n(** But the intellectually exciting implication of the Church numerals\n    is that we don't strictly need the natural numbers to be built-in\n    to a functional programming language, or even to be definable with\n    an inductive data type. It's possible to represent them purely (if\n    not efficiently) with functions.\n\n    Of course, it's not enough to represent numerals; we need to be\n    able to do arithmetic with them. Show that we can by completing\n    the definitions of the following functions. Make sure that the\n    corresponding unit tests pass by proving them with\n    [reflexivity]. *)\n\n(** **** Exercise: 2 stars, advanced (church_scc) *)\n\n(** Define a function that computes the successor of a Church numeral.\n    Given a Church numeral [n], its successor [scc n] should iterate\n    its function argument once more than [n]. That is, given [fun X f x\n    => f^n x] as input, [scc] should produce [fun X f x => f^(n+1) x] as\n    output. In other words, do it [n] times, then do it once more. *)\n\nDefinition scc (n : cnat) : cnat\n  := fun (X : Type) (f : X -> X) (x : X) => n X f (f x).\n\nExample scc_1 : scc zero = one.\nProof. reflexivity. Qed.\n\nExample scc_2 : scc one = two.\nProof. reflexivity. Qed.\n\nExample scc_3 : scc two = three.\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (church_plus) *)\n\n(** Define a function that computes the addition of two Church\n    numerals.  Given [fun X f x => f^n x] and [fun X f x => f^m x] as\n    input, [plus] should produce [fun X f x => f^(n + m) x] as output.\n    In other words, do it [n] times, then do it [m] more times.\n\n    Hint: the \"zero\" argument to a Church numeral need not be just\n    [x]. *)\n\nDefinition plus (n m : cnat) : cnat\n  := fun (X : Type) (f : X -> X) (x : X) => n X f (m X f x).\n\nExample plus_1 : plus zero one = one.\nProof. reflexivity. Qed.\n\nExample plus_2 : plus two three = plus three two.\nProof. reflexivity. Qed.\n\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (church_mult) *)\n\n(** Define a function that computes the multiplication of two Church\n    numerals.\n\n    Hint: the \"successor\" argument to a Church numeral need not be\n    just [f].\n\n    Warning: Coq will not let you pass [cnat] itself as the type [X]\n    argument to a Church numeral; you will get a \"Universe\n    inconsistency\" error. That is Coq's way of preventing a paradox in\n    which a type contains itself. So leave the type argument\n    unchanged. *)\n\nDefinition mult (n m : cnat) : cnat\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(** [] *)\n\n(** **** Exercise: 3 stars, advanced (church_exp) *)\n\n(** Exponentiation: *)\n\n(** Define a function that computes the exponentiation of two Church\n    numerals.\n\n    Hint: the type argument to a Church numeral need not just be [X].\n    But again, you cannot pass [cnat] itself as the type argument.\n    Finding the right type can be tricky. *)\n\nDefinition exp (n m : cnat) : cnat\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 zero = one.\nProof. reflexivity. Qed.\n\nExample exp_3 : exp three two = plus (mult two (mult two two)) one.\nProof. reflexivity. Qed.\n\n(** [] *)\n\nEnd Church.\nEnd Exercises.\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/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126791, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.6968856957837171}}
{"text": "Require Import Program.Basics.\n\nOpen Scope program_scope.\n\n(* typeclass and laws *)\n\nClass Profunctor (p : Type -> Type -> Type) :=\n{ dimap {A A' B B'} (f : A' -> A) (g : B -> B') : p A B -> p A' B' \n; lmap {A A' B} (f : A' -> A) : p A B -> p A' B := dimap f id\n; rmap {A B B'} (f : B -> B') : p A B -> p A B' := dimap id f\n}.\n\nClass ProfunctorDec p `{Profunctor p} :=\n{ profunctor_id : forall A B (pab : p A B), dimap id id pab = pab\n; profunctor_comp : forall A A' A'' B B' B'' (pab : p A B)\n                          (f : A'' -> A') (f' : A' -> A) \n                          (g' : B -> B') (g : B' -> B''),\n    dimap (f' ∘ f) (g ∘ g') pab = (dimap f g ∘ dimap f' g') pab\n}.\n\n(* cartesian profunctor *)\n\nClass Cartesian p `{ProfunctorDec p} :=\n{ first  {A B C} (pab : p A B) : p (prod A C) (prod B C)\n; second {A B C} (pab : p A B) : p (prod C A) (prod C B)\n}.\n\n(* auxiliar defs to define cartesian laws *)\n\nDefinition r1  {A} (a1 : prod A unit) : A := fst a1.\nDefinition r1' {A} (a: A) : prod A unit := (a, tt).\n\nDefinition assoc {A B C} (a_bc : prod A (prod B C)) : prod (prod A B) C :=\n  match a_bc with | pair a (pair b c) => pair (pair a b) c end.\nDefinition assoc' {A B C} (ab_c : prod (prod A B) C) : prod A (prod B C) :=\n  match ab_c with | pair (pair a b) c => pair a (pair b c) end.\n\nClass CartesianDec p `{Cartesian p} :=\n{ cartesian_unit : forall A B (h : p A B), dimap r1 r1' h = first h\n; cartesian_assoc : forall A B C (h : p A A), \n                           dimap assoc assoc' (first (first h)) = @first p _ _ _ A A (prod B C) h\n}.\n", "meta": {"author": "hablapps", "repo": "koky", "sha": "7dc9141fafabeb0b381cfbda0cd6e856394cc9d4", "save_path": "github-repos/coq/hablapps-koky", "path": "github-repos/coq/hablapps-koky/koky-7dc9141fafabeb0b381cfbda0cd6e856394cc9d4/Core/Profunctor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6968393807272942}}
{"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 drop (drop_arg0 : natural) (drop_arg1 : lst) : lst\n           := match drop_arg0, drop_arg1 with\n              | x, Nil => Nil\n              | Zero, x => x\n              | Succ x, Cons y z => drop x z\n              end.\n\nLemma lem: forall n1 n2 l, drop (Succ n1) (drop n2 l) = drop n1 (drop (Succ n2) l).\nProof.\nintros. generalize dependent n1. generalize dependent n2. induction l.\n- intros. assert (forall n x l, drop (Succ n) (Cons x l) = drop n l). \n   + intros. reflexivity.\n   + destruct n2.\n   * rewrite H. rewrite H. rewrite <- IHl. reflexivity.\n   * simpl. destruct l. reflexivity. reflexivity.\n- intros. assert (forall n, drop n Nil = Nil).\n   + intros. destruct n. reflexivity. reflexivity.\n   + rewrite H. rewrite H. rewrite H. reflexivity.\nQed.\n\n\nTheorem theorem0 : forall (v : natural) (w : natural) (x : natural) (y : natural) (z : lst), eq (drop (Succ v) (drop w (drop x (Cons y z)))) (drop v (drop w (drop x z))).\nProof.\nintros. \nrewrite lem. \nrewrite lem. 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/goal56.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6968270077600537}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type :=  Nil : lst | Cons : natural -> lst -> lst .\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint 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. lfind.  reflexivity. \nAdmitted.\n              \n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/clam_lf_goal80_theorem0_58_append_nil/goal80.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.6968270048897194}}
{"text": "Inductive truth : Set := Yes | No | Maybe.\n\nDefinition not (t : truth): truth :=\n  match t with\n  | Yes => No\n  | No => Yes\n  | Maybe => Maybe\n  end.\n\nDefinition and (t1 : truth) (t2 : truth) : truth :=\n  match t1 with\n  | Yes => t2\n  | No => No\n  | Maybe =>\n    match t2 with\n    | Yes => Maybe\n    | No => No\n    | Maybe => Maybe\n    end\n  end.\n\nDefinition or (t1 : truth) (t2 : truth) : truth :=\n  match t1 with\n  | Yes => Yes\n  | No => t2\n  | Maybe =>\n    match t2 with\n    | Yes => Yes\n    | No => Maybe\n    | Maybe => Maybe\n    end\n  end.\n\nTheorem and_commutative : forall t1 t2 : truth, and t1 t2 = and t2 t1.\n  destruct t1; destruct t2; reflexivity.\nQed.\n\nTheorem and_distributes_over_or : forall t1 t2 t3 : truth,\n    and t1 (or t2 t3) = or (and t1 t2) (and t1 t3).\n  destruct t1; destruct t2; destruct t3; reflexivity.\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/0.1-1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.7690802264851918, "lm_q1q2_score": 0.6967788640624861}}
{"text": "Require Import QArith.\nRequire Import Setoid.\n\nRequire Import basics.\nRequire Import preord.\nRequire Import categories.\nRequire Import sets.\nRequire Import finsets.\nRequire Import esets.\nRequire Import effective.\nRequire Import directed.\nRequire Import plotkin.\nRequire Import joinable.\nRequire Import approx_rels.\nRequire Import profinite.\nRequire Import cusl.\n\nRequire Import rational_intervals.\nRequire Import realdom.\n\nRequire Import Qabs.\nRequire Import Qminmax.\n\n\n\nSection cuts.\n  Record cut  := Cut\n    { cut_upper : eset Qpreord\n    ; cut_lower : eset Qpreord\n    ; cut_proper : forall u l, u ∈ cut_upper -> l ∈ cut_lower -> l <= u\n    ; cut_is_lower : forall (q1 q2:Qpreord), q1 <= q2 -> q2 ∈ cut_lower -> q1 ∈ cut_lower\n    ; cut_is_upper : forall (q1 q2:Qpreord), q1 <= q2 -> q1 ∈ cut_upper -> q2 ∈ cut_upper\n     (** probably should reformulate the prereals as directed sets of\n         intervals where the endpoints may be -∞ or ∞.\n       *)\n    ; cut_nonextended : (exists x, x ∈ cut_upper) <-> (exists x, x ∈ cut_lower)\n    }.\n\n  Definition cut_ord (x y:cut) :=\n    cut_upper x ⊆ cut_upper y /\\\n    cut_lower x ⊆ cut_lower y.\n\n  Program Definition cut_ord_mixin : Preord.mixin_of cut :=\n    Preord.Mixin cut cut_ord _ _ .\n  Next Obligation.\n    intros. red; split; red; auto.\n  Qed.\n  Next Obligation.\n    unfold cut_ord. intuition; repeat intro; eauto.\n  Qed.\n\n  Definition cut_preord := Preord.Pack cut cut_ord_mixin.\n\n  Program Definition rints_to_cut\n          (X:eset PreRealDom)\n          (Hdir:directed true X)\n          (Hdown:forall (r r':PreRealDom), r ≤ r' -> r' ∈ X -> r ∈ X )\n          : cut :=\n    Cut (eimage' _ _ rint_end   X)\n        (eimage' _ _ rint_start X)\n        _ _ _ _.\n  Next Obligation.\n    unfold eimage'.\n    intros.\n    destruct H as [n1 ?].\n    destruct H0 as [n2 ?].\n    revert H. case_eq (X n1); intros.\n    revert H0. case_eq (X n2); intros.\n    destruct H1 as [? _]. destruct H2 as [? _].\n    red in H1. simpl in H1.\n    red in H2. simpl in H2.\n    rewrite H2. rewrite H1.\n    destruct (Hdir (c::c0::nil)%list).\n    exists c. apply cons_elem; auto.\n    red; simpl; intros.\n    apply cons_elem in H3. destruct H3. rewrite H3.\n    exists n1. rewrite H. auto.\n    apply cons_elem in H3. destruct H3. rewrite H3.\n    exists n2. rewrite H0. auto.\n    apply nil_elem in H3. elim H3.\n    destruct H3.\n    assert (c ≤ x).\n    apply H3. apply cons_elem; auto.\n    assert (c0 ≤ x).\n    apply H3. apply cons_elem; right. apply cons_elem; auto.\n    apply Qle_trans with (rint_start x).\n    apply rint_ord_test in H6. intuition.\n    apply Qle_trans with (rint_end x).\n    apply rint_proper.\n    apply rint_ord_test in H5. intuition.\n    elim H2.\n    elim H1.\n  Qed.\n  Next Obligation.\n    repeat intro.\n    unfold eimage' in H0.\n    destruct H0 as [n ?].\n    revert H0. case_eq (X n); intros.\n    destruct H1 as [? _]. red in H1. simpl in H1.\n    assert (q1 <= rint_end c).\n    apply Qle_trans with q2; auto.\n    rewrite H1. apply rint_proper.\n    set (r := RatInt q1 (rint_end c) H2).\n    assert (r ∈ X).\n    apply Hdown with c.\n    apply rint_ord_test.\n    split; simpl; auto.\n    apply Qle_trans with q2; auto.\n    rewrite H1; auto.\n    apply Qle_refl.\n    apply Qle_refl.\n    exists n. rewrite H0. auto.\n    destruct H3 as [n' ?].\n    exists n'.\n    unfold eimage'.\n    destruct (X n').\n    assert (q1 == rint_start c0).\n    destruct H3.\n    assert (rint_start r == rint_start c0).\n    apply rint_ord_test in H3.\n    apply rint_ord_test in H4.\n    apply Qle_antisym; intuition.\n    simpl in H5. auto.\n    split; red; simpl; auto.\n    symmetry; auto.\n    auto.\n    elim H1.\n  Qed.\n  Next Obligation.\n    repeat intro.\n    unfold eimage' in H0.\n    destruct H0 as [n ?].\n    revert H0. case_eq (X n); intros.\n    destruct H1 as [? _]. red in H1. simpl in H1.\n    assert (rint_start c <= q2).\n    apply Qle_trans with q1; auto.\n    rewrite H1. apply rint_proper.\n    set (r := RatInt (rint_start c) q2 H2).\n    assert (r ∈ X).\n    apply Hdown with c.\n    apply rint_ord_test.\n    split; simpl; auto.\n    apply Qle_refl.\n    apply Qle_trans with q1; auto.\n    rewrite H1; auto.\n    apply Qle_refl.\n    exists n. rewrite H0. auto.\n    destruct H3 as [n' ?].\n    exists n'.\n    unfold eimage'.\n    destruct (X n').\n    assert (q2 == rint_end c0).\n    destruct H3.\n    assert (rint_end r == rint_end c0).\n    apply rint_ord_test in H3.\n    apply rint_ord_test in H4.\n    apply Qle_antisym; intuition.\n    simpl in H5. auto.\n    split; red; simpl; auto.\n    symmetry; auto.\n    auto.\n    elim H1.\n  Qed.\n  Next Obligation.\n    intros.\n    unfold eimage'.\n    split; intros [x ?].\n    destruct H as [n ?].\n    revert H. case_eq (X n); intros.\n    exists (rint_start c).\n    exists n. rewrite H. auto.\n    elim H0.\n    destruct H as [n ?].\n    revert H. case_eq (X n); intros.\n    exists (rint_end c).\n    exists n. rewrite H. auto.\n    elim H0.\n  Qed.\n\n  Lemma rints_to_cut_upper q X Hdir Hdown :\n    q ∈ cut_upper (rints_to_cut X Hdir Hdown) <->\n    exists r, r ∈ X /\\ q == rint_end r.\n  Proof.\n    simpl; intros. unfold eimage'.\n    split; intros.\n    destruct H as [n ?].\n    revert H. case_eq (X n); intros.\n    exists c. split.\n    exists n. rewrite H; auto.\n    destruct H0; auto.\n    elim H0.\n    destruct H as [r [??]].\n    destruct H as [n ?]. exists n.\n    destruct (X n); auto.\n    assert (rint_end r == rint_end c).\n    destruct H.\n    apply rint_ord_test in H.\n    apply rint_ord_test in H1.\n    apply Qle_antisym; intuition.\n    rewrite H1 in H0.\n    split; red; simpl; auto.\n    symmetry; auto.\n  Qed.\n\n  Lemma rints_to_cut_lower q X Hdir Hdown :\n    q ∈ cut_lower (rints_to_cut X Hdir Hdown) <->\n    exists r, r ∈ X /\\ q == rint_start r.\n  Proof.\n    simpl; intros. unfold eimage'.\n    split; intros.\n    destruct H as [n ?].\n    revert H. case_eq (X n); intros.\n    exists c. split.\n    exists n. rewrite H; auto.\n    destruct H0; auto.\n    elim H0.\n    destruct H as [r [??]].\n    destruct H as [n ?]. exists n.\n    destruct (X n); auto.\n    assert (rint_start r == rint_start c).\n    destruct H.\n    apply rint_ord_test in H.\n    apply rint_ord_test in H1.\n    apply Qle_antisym; intuition.\n    rewrite H1 in H0.\n    split; red; simpl; auto.\n    symmetry; auto.\n  Qed.\n\n  Opaque rints_to_cut.\n\n\n  Parameter A:∂PLT.\n\n  Program Definition hom_to_cut (f:A → PreRealDom) : PLT.ord A → cut_preord :=\n    Preord.Hom (PLT.ord A) cut_preord \n               (fun a => rints_to_cut (erel_image _ _ (PLT.dec A) (PLT.hom_rel f) a) \n                                    (PLT.hom_directed _ _ _ f a)\n                                     _)\n               _.\n  Next Obligation.\n    intros.\n    apply erel_image_elem in H0.\n    apply erel_image_elem.\n    revert H0. apply PLT.hom_order; auto.\n  Qed.\n  Next Obligation.\n    simpl; intros.\n    assert (erel_image _ _ (PLT.dec A) (PLT.hom_rel f) a ⊆\n            erel_image _ _ (PLT.dec A) (PLT.hom_rel f) b).\n    red; simpl; intros.\n    apply erel_image_elem in H0.\n    apply erel_image_elem.\n    revert H0.\n    apply PLT.hom_order; auto.\n\n    split; red; intros.\n    apply rints_to_cut_upper in H1.\n    apply rints_to_cut_upper.\n    destruct H1 as [r [??]]. exists r; split; auto.\n    apply rints_to_cut_lower in H1.\n    apply rints_to_cut_lower.\n    destruct H1 as [r [??]]. exists r; split; auto.\n  Qed.\n\n  Program Definition cut_to_hom_rel (f:PLT.ord A → cut_preord) : erel A PreRealDom :=\n    @esubset (prod_preord A PreRealDom)\n            (fun ar => rint_end (snd ar) ∈ cut_upper (f (fst ar)) /\\\n                       rint_start (snd ar) ∈ cut_lower (f (fst ar)))\n            _\n            (eff_enum _ (effective_prod (PLT.effective A) (PLT.effective PreRealDom))).\n  Next Obligation.\n    intros.\n    apply semidec_conj.\n    apply semidec_in.\n    constructor. apply Qeq_dec.\n    apply semidec_in.\n    constructor. apply Qeq_dec.\n  Qed.\n\n  Lemma cut_to_hom_rel_elem (f:PLT.ord A → cut_preord) a r :\n    (a,r) ∈ cut_to_hom_rel f <-> \n       (rint_end r ∈ cut_upper (f a) /\\ rint_start r ∈ cut_lower (f a)).\n  Proof.\n    unfold cut_to_hom_rel.\n    rewrite esubset_elem. intuition.\n    apply eprod_elem; split; apply eff_complete.\n    simpl; intros.\n    destruct H as [[??][??]].\n    intuition.\n    cut (rint_end (snd b) ∈ cut_upper (f (fst a0))).\n    destruct (Preord.axiom _ _ f (fst a0) (fst b)); auto.\n    revert H4. apply cut_is_upper.\n    apply rint_ord_test in H3. intuition.\n    cut (rint_start (snd b) ∈ cut_lower (f (fst a0))).\n    destruct (Preord.axiom _ _ f (fst a0) (fst b)); auto.\n    revert H5. apply cut_is_lower.\n    apply rint_ord_test in H3. intuition.\n  Qed.\n\n  Program Definition cut_to_hom (f:PLT.ord A → cut_preord) : A → PreRealDom :=\n    PLT.Hom true A PreRealDom (cut_to_hom_rel f) _ _. \n  Next Obligation.\n    simpl; intros.\n    apply cut_to_hom_rel_elem in H1.\n    apply cut_to_hom_rel_elem.\n    apply rint_ord_test in H0.\n    intuition.\n    cut (rint_end y' ∈ cut_upper (f x)).\n    destruct (Preord.axiom _ _ f x x'); auto.\n    revert H0.\n    apply cut_is_upper; auto.\n    cut (rint_start y' ∈ cut_lower(f x)).\n    destruct (Preord.axiom _ _ f x x'); auto.\n    revert H4.\n    apply cut_is_lower; auto.\n  Qed.\n  Next Obligation.\n    intros f a. apply prove_directed; auto.\n    intros.\n    apply erel_image_elem in H.\n    apply erel_image_elem in H0.\n    apply cut_to_hom_rel_elem in H.\n    apply cut_to_hom_rel_elem in H0.\n    destruct H. destruct H0.\n    assert (Qmax (rint_start x) (rint_start y) <= Qmin (rint_end x) (rint_end y)).\n    apply Q.max_case.\n    intros. rewrite <- H3; auto.\n    apply Q.min_case.\n    intros. rewrite <- H3; auto.\n    eapply cut_proper; eauto.\n    eapply cut_proper; eauto.\n    apply Q.min_case.\n    intros. rewrite <- H3; auto.\n    eapply cut_proper; eauto.\n    eapply cut_proper; eauto.\n    exists (RatInt _ _ H3).\n    split.\n    apply rint_ord_test. simpl.\n    split. apply Q.le_max_l. apply Q.le_min_l.\n    split.\n    apply rint_ord_test. simpl.\n    split. apply Q.le_max_r. apply Q.le_min_r.\n    apply erel_image_elem.\n    apply cut_to_hom_rel_elem.\n    simpl. split.\n    apply Q.min_case; simpl; auto.\n    intros p q ?. apply member_eq.\n    split; red; simpl; auto. symmetry; auto.\n    apply Q.max_case; simpl; auto.\n    intros p q ?. apply member_eq.\n    split; red; simpl; auto. symmetry; auto.\n  Qed.\n\n\n  Lemma cut_roundtrip1 f :\n    cut_to_hom (hom_to_cut f) ≈ f.\n  Proof.\n    split; hnf; simpl; intros [a r] H.\n    apply cut_to_hom_rel_elem in H. destruct H.\n    simpl in *.\n    rewrite rints_to_cut_upper in H.\n    rewrite rints_to_cut_lower in H0.\n    destruct H as [r1 [??]].\n    destruct H0 as [r2 [??]].\n    apply erel_image_elem in H.\n    apply erel_image_elem in H0.\n    destruct (plt_hom_directed2 _ _ _ f a r1 r2) as [r' [?[??]]]; auto.\n    apply PLT.hom_order with a r'; auto.\n    apply rint_ord_test.\n    apply rint_ord_test in H4.\n    apply rint_ord_test in H5.\n    split.\n    rewrite H2; intuition.\n    rewrite H1; intuition.\n\n    apply cut_to_hom_rel_elem.\n    split; simpl.\n    rewrite rints_to_cut_upper.\n    exists r. split; auto.\n    apply erel_image_elem. auto. reflexivity.\n    rewrite rints_to_cut_lower.\n    exists r. split; auto.\n    apply erel_image_elem. auto. reflexivity.\n  Qed.\n\n  Lemma cut_roundtrip2 f :\n    hom_to_cut (cut_to_hom f) ≈ f.\n  Proof.\n    intro a. split; split; simpl; hnf; intros.\n    apply rints_to_cut_upper in H.\n    destruct H as [r [??]].\n    apply erel_image_elem in H. \n    apply cut_to_hom_rel_elem in H. destruct H.\n    revert H. apply member_eq.\n    split; red; simpl; auto. symmetry; auto.\n    apply rints_to_cut_lower in H.\n    destruct H as [r [??]].\n    apply erel_image_elem in H. \n    apply cut_to_hom_rel_elem in H. destruct H.\n    revert H1. apply member_eq.\n    split; red; simpl; auto. symmetry; auto.\n    \n    apply rints_to_cut_upper.\n    destruct (cut_nonextended (f a)) as [? _].\n    destruct H0 as [z ?]; eauto.\n    assert (z <= a0).\n    eapply cut_proper; eauto.\n    exists (RatInt z a0 H1).\n    split; simpl; auto.\n    apply erel_image_elem.\n    apply cut_to_hom_rel_elem.\n    simpl. split; auto. reflexivity.\n    \n    apply rints_to_cut_lower.\n    destruct (cut_nonextended (f a)) as [_ ?].\n    destruct H0 as [z ?]; eauto.\n    assert (a0 <= z).\n    eapply cut_proper; eauto.\n    exists (RatInt a0 z H1).\n    split; simpl; auto.\n    apply erel_image_elem.\n    apply cut_to_hom_rel_elem.\n    simpl. split; auto. reflexivity.\n  Qed.\n\n  Definition cut_canonical (x:cut) :=\n    (forall u, u ∈ cut_upper x -> exists u', u' ∈ cut_upper x /\\ u' < u) /\\ \n    (forall l, l ∈ cut_lower x -> exists l', l' ∈ cut_lower x /\\ l < l').\n\n  Definition located (x:cut) :=\n    forall (ε:Q), ε > 0 ->\n      exists u l,\n        u ∈ cut_upper x /\\\n        l ∈ cut_lower x /\\\n        u - l <= ε.\n\n  Lemma canonical_to_hom (f:PLT.ord A → cut_preord) :\n    (forall a, cut_canonical (f a)) ->\n    canonical A (cut_to_hom f).\n  Proof.\n    repeat intro.\n    destruct (H a).\n    simpl in H0.\n    apply cut_to_hom_rel_elem in H0. destruct H0.\n    destruct (H1 (rint_end x)) as [u' [??]]; auto.\n    destruct (H2 (rint_start x)) as [l' [??]]; auto.\n    assert (l' <= u').\n    apply cut_proper with (f a); auto.\n    exists (RatInt l' u' H8).\n    split; simpl.\n    apply cut_to_hom_rel_elem; split; simpl; auto.\n    red; split; simpl; auto.\n  Qed.\n\n  Lemma canonical_to_cut (f:A → PreRealDom) :\n    canonical A f ->\n    forall a, cut_canonical (hom_to_cut f a).\n  Proof.\n    repeat intro.\n    split; simpl; intros.\n    apply rints_to_cut_upper in H0.\n    destruct H0 as [r [??]].\n    apply erel_image_elem in H0.\n    destruct (H a r) as [r' [??]]; auto.\n    exists (rint_end r').\n    split.\n    apply rints_to_cut_upper.\n    exists r'. split.\n    apply erel_image_elem. auto.\n    reflexivity.\n    rewrite H1.\n    destruct H3; auto.\n    apply rints_to_cut_lower in H0.\n    destruct H0 as [r [??]].\n    apply erel_image_elem in H0.\n    destruct (H a r) as [r' [??]]; auto.\n    exists (rint_start r').\n    split.\n    apply rints_to_cut_lower.\n    exists r'. split.\n    apply erel_image_elem. auto.\n    reflexivity.\n    rewrite H1.\n    destruct H3; auto.\n  Qed.\n\n  Lemma located_converges (f:PLT.ord A → cut_preord) :\n    (forall a, located (f a)) ->\n   realdom_converges A (cut_to_hom f).\n  Proof.\n    repeat intro.\n    destruct (H a ε) as [u [l [?[??]]]]; auto.\n    assert (l <= u).\n    apply cut_proper with (f a); auto.\n    exists (RatInt l u H4). split; simpl; auto.\n    apply cut_to_hom_rel_elem. split; simpl; auto.\n  Qed.\n\n  Lemma converges_located (f:A → PreRealDom) :\n    realdom_converges A f ->\n    forall a, located (hom_to_cut f a).\n  Proof.\n    repeat intro.\n    destruct (H a ε) as [r [??]]; auto.\n    exists (rint_end r), (rint_start r); split; simpl; auto.\n    apply rints_to_cut_upper.\n    exists r; split; auto.\n    apply erel_image_elem. auto. reflexivity.\n    split.\n    apply rints_to_cut_lower.\n    exists r; split; auto.\n    apply erel_image_elem. auto. reflexivity.\n    auto.\n  Qed.\n\n  Lemma hom_to_cut_mono (f g:A → PreRealDom) :\n    f ≤ g -> hom_to_cut f ≤ hom_to_cut g.\n  Proof.\n    repeat intro.\n    split; red; simpl; intros.\n    apply rints_to_cut_upper in H0.\n    apply rints_to_cut_upper.\n    destruct H0 as [r [??]].\n    exists r. split; auto.\n    apply erel_image_elem in H0.\n    apply erel_image_elem.\n    apply H; auto.\n    apply rints_to_cut_lower in H0.\n    apply rints_to_cut_lower.\n    destruct H0 as [r [??]].\n    exists r. split; auto.\n    apply erel_image_elem in H0.\n    apply erel_image_elem.\n    apply H; auto.\n  Qed.\n\n  Lemma cut_to_hom_mono (f g:PLT.ord A → cut_preord) :\n    f ≤ g -> cut_to_hom f ≤ cut_to_hom g.\n  Proof.\n    repeat intro; simpl in *.\n    destruct a as [a r].\n    apply cut_to_hom_rel_elem in H0.\n    apply cut_to_hom_rel_elem.\n    destruct H0. split.\n    apply (H a); auto.\n    apply (H a); auto.\n  Qed.\n\nEnd cuts.\n\nCanonical Structure cut_preord.\n\nDefinition cut_lt (x y:cut) :=\n  exists u l,\n    u ∈ cut_upper x /\\\n    l ∈ cut_lower y /\\\n    u < l.\n\nModule interval_limit_cuts.\n\nSection limit.\n  Variable seq_upper : N -> cut.\n  Variable seq_lower : N -> cut.\n\n  Hypothesis seq_proper : forall n, cut_lt (seq_lower n) (seq_upper n).\n  Hypothesis seq_upper_inside : forall n m, (n < m)%N -> cut_lt (seq_upper m) (seq_upper n).\n  Hypothesis seq_lower_inside : forall n m, (n < m)%N -> cut_lt (seq_lower n) (seq_lower m).\n\n  Definition limit_upper : eset Qpreord :=\n    union ( (fun n => Some (cut_upper (seq_upper n))) : eset (eset Qpreord)).\n\n  Definition limit_lower : eset Qpreord :=\n    union ( (fun n => Some (cut_lower (seq_lower n)))  : eset (eset Qpreord)).\n\n  Program Definition interval_limit : cut :=\n    Cut limit_upper limit_lower _ _ _ _.\n  Next Obligation.\n    unfold limit_upper, limit_lower. intros. \n    apply union_axiom in H.\n    apply union_axiom in H0.\n    destruct H as [XU [??]].\n    destruct H0 as [XL [??]].\n    destruct H as [n1 ?].\n    destruct H0 as [n2 ?].\n    set (o := (1 + N.max n1 n2)%N).\n    destruct (seq_lower_inside n2 (1 + N.max n1 n2)) as [a [b [?[??]]]].\n    zify. omega.\n    apply Qle_trans with a.\n    apply cut_proper with (seq_lower n2); auto.\n    rewrite <- H0; auto.\n    apply Qle_trans with b.\n    intuition.\n    destruct (seq_proper (1 + N.max n1 n2)) as [c [d [?[??]]]].\n    apply Qle_trans with c.\n    apply cut_proper with (seq_lower (1 + N.max n1 n2)); auto.\n    apply Qle_trans with d.\n    intuition.\n    destruct (seq_upper_inside n1 (1 + N.max n1 n2)) as [e [f [?[??]]]].\n    zify. omega.\n    apply Qle_trans with e.\n    apply cut_proper with (seq_upper (1 + N.max n1 n2)); auto.\n    apply Qle_trans with f.\n    intuition.\n    apply cut_proper with (seq_upper n1); auto.\n    rewrite <- H. auto.\n  Qed.\n  Next Obligation.\n    unfold limit_lower; intros.\n    apply union_axiom in H0.\n    destruct H0 as [X [??]].\n    destruct H0 as [n ?].\n    apply union_axiom.\n    exists X. split; auto.\n    exists n. auto.\n    rewrite H0. rewrite H0 in H1.\n    revert H1. apply cut_is_lower. auto.\n  Qed.\n  Next Obligation.\n    unfold limit_upper; intros.\n    apply union_axiom in H0.\n    destruct H0 as [X [??]].\n    destruct H0 as [n ?].\n    apply union_axiom.\n    exists X. split; auto.\n    exists n. auto.\n    rewrite H0. rewrite H0 in H1.\n    revert H1. apply cut_is_upper. auto.\n  Qed.\n  Next Obligation.\n    unfold limit_upper, limit_lower.\n    destruct (seq_proper 0) as [u [l [?[??]]]].\n    split; intros.\n    destruct (cut_nonextended (seq_lower 0)).\n    destruct H3 as [l' ?].\n    exists u. auto.\n    exists l'.\n    apply union_axiom.\n    exists (cut_lower (seq_lower 0)).\n    split; auto.\n    exists 0%N. auto.\n    \n    destruct (cut_nonextended (seq_upper 0)).\n    destruct H4 as [u' ?].\n    exists l. auto.\n    exists u'.\n    apply union_axiom.\n    exists (cut_upper (seq_upper 0)).\n    split; auto.\n    exists 0%N. auto.\n  Qed.\n\n  Lemma interval_limit_inside_upper : forall n,\n    cut_lt interval_limit (seq_upper n).                                  \n  Proof.\n    repeat intro. hnf.\n    destruct (seq_upper_inside n (n+1)) as [u' [l' [?[??]]]].\n    zify. omega.\n    exists u'. exists l'. intuition.\n    unfold interval_limit. simpl.\n    unfold limit_upper.\n    apply union_axiom.\n    exists (cut_upper (seq_upper (n+1))).\n    split. exists (n+1)%N. auto.\n    auto.\n  Qed.\n\n  Lemma interval_limit_inside_lower : forall n,\n    cut_lt (seq_lower n) interval_limit.\n  Proof.\n    repeat intro. hnf.\n    destruct (seq_lower_inside n (n+1)) as [u' [l' [?[??]]]].\n    zify. omega.\n    exists u'. exists l'. intuition.\n    unfold interval_limit. simpl.\n    unfold limit_upper.\n    apply union_axiom.\n    exists (cut_lower (seq_lower (n+1))).\n    split. exists (n+1)%N. auto.\n    auto.\n  Qed.\n\n  Lemma interval_limit_least_defined lim :\n    (forall n, cut_lt lim (seq_upper n)) ->\n    (forall n, cut_lt (seq_lower n) lim) ->\n    interval_limit ≤ lim.\n  Proof.\n    repeat intro. split; hnf; simpl; intros.\n\n    unfold limit_upper in H1.\n    apply union_axiom in H1.\n    destruct H1 as [X [??]].\n    destruct H1 as [n ?].\n    destruct (H n) as [u [l [?[??]]]].\n    rewrite H1 in H2.\n    apply cut_is_upper with u; auto.\n    apply Qle_trans with l; intuition.\n    apply cut_proper with (seq_upper n); auto.\n    \n    unfold limit_lower in H1.\n    apply union_axiom in H1.\n    destruct H1 as [X [??]].\n    destruct H1 as [n ?].\n    destruct (H0 n) as [u [l [?[??]]]].\n    rewrite H1 in H2.\n    apply cut_is_lower with l; auto.\n    apply Qle_trans with u; intuition.\n    apply cut_proper with (seq_lower n); auto.\n  Qed.\n\n  Hypothesis seq_converges : forall ε, 0 < ε ->\n     exists n a b,\n       a ∈ cut_upper (seq_upper n) /\\\n       b ∈ cut_lower (seq_lower n) /\\\n       a - b <= ε.\n       \n  Lemma interval_limit_located : located interval_limit.\n  Proof.\n    red; intros.\n    destruct (seq_converges ε H) as [n [a [b [?[??]]]]].\n    exists a. exists b. intuition.\n    simpl. unfold limit_upper.\n    apply union_axiom. exists (cut_upper (seq_upper n)).\n    split; auto. exists n. auto.\n    apply union_axiom. exists (cut_lower (seq_lower n)).\n    split; auto. exists n. auto.\n  Qed.\nEnd limit.\nEnd interval_limit_cuts.\n\n\n\nDefinition pow2 (n:N) : positive :=\n match n with\n | N0     => 1%positive\n | Npos p => shift_pos p 1\n end.\n\nLemma pow2_commute n1 n2 :\n  (pow2 n1 * pow2 n2 = pow2 (n1+n2))%positive.\nProof.\n  unfold pow2.\n  destruct n1; simpl; auto.\n  destruct n2; simpl; auto.\n  apply Pos.mul_1_r.\n  unfold shift_pos.\n  rewrite Pos.iter_add.\n  induction p using Pos.peano_ind; simpl; auto.\n  rewrite Pos.iter_succ. simpl.\n  rewrite IHp.\n  rewrite Pos.iter_succ. auto.\nQed.\n\nLemma pow2_div_eq (a b:N) :\n  (a <= b)%N -> (pow2 (b - a) * pow2 a = pow2 b)%positive.\nProof.\n  intros.\n  rewrite pow2_commute.\n  replace (b - a + a)%N with b; auto.\n  assert (0 <= a)%N.\n  hnf. simpl. destruct a; discriminate.\n  symmetry. apply N.sub_add; auto.\nQed. \n\nDefinition oneOver2n (n:N) : Q := (1 # pow2 n)%Q.\n\nLemma oneOver2n_pos n : 0 < oneOver2n n.\nProof.\n  unfold oneOver2n. intuition.\nQed.\n\nLemma oneOver2n_commute n1 n2 :\n  (oneOver2n n1 * oneOver2n n2 == oneOver2n (n1+n2))%Q.\nProof.\n  unfold oneOver2n.\n  red. simpl. symmetry.\n  f_equal. apply pow2_commute.\nQed.\n\nLemma oneOver2n_div_eq a b  :\n  (a <= b)%N -> (oneOver2n (b - a) * oneOver2n a == oneOver2n b)%Q.\nProof.\n  intro.\n  unfold oneOver2n.\n  red. simpl. symmetry.\n  f_equal. apply pow2_div_eq. auto.\nQed.\n\nLemma pow2_ge1 (a:N) :\n  (1 <= pow2 a)%positive.\nProof.\n  induction a using N.peano_ind.\n  simpl. reflexivity.\n  replace (N.succ a) with (1+a)%N.\n  2: zify; omega.\n  rewrite <- pow2_commute.\n  simpl pow2 at 1. unfold shift_pos. simpl Pos.iter.\n  zify. omega.\nQed.\n\nLemma pow2_mono (a b:N) :\n  (a <= b)%N -> (pow2 a <= pow2 b)%positive.\nProof.\n  revert b. induction a using N.peano_ind.\n  simpl; intros.\n  apply pow2_ge1.\n  intro b. induction b using N.peano_ind.\n  intros.\n  elimtype False. zify. omega.\n  intros.\n  replace (N.succ a) with (1+a)%N.\n  replace (N.succ b) with (1+b)%N.\n  2: zify; omega.\n  2: zify; omega.\n  rewrite <- pow2_commute.\n  rewrite <- pow2_commute.\n  cut (pow2 a <= pow2 b)%positive.\n  simpl. zify. omega.\n  apply IHa. zify. omega.\nQed.\n\nLemma oneOver2n_subsumes (a b c:N) :\n    (a < b)%N -> (a < c)%N -> \n       oneOver2n b + oneOver2n c <= oneOver2n a.\nProof.\n  intros. unfold oneOver2n.\n  red. simpl.\n  cut ((pow2 c + pow2 b) * pow2 a <= (pow2 b * pow2 c))%positive. auto.\n  rewrite pow2_commute.\n  rewrite Pos.mul_add_distr_r.\n  rewrite pow2_commute.\n  rewrite pow2_commute.\n  replace (b + c)%N with (1 + (b+c-1))%N by (zify; omega).\n  rewrite <- (pow2_commute 1).\n  simpl pow2 at 3. unfold shift_pos. simpl Pos.iter.\n  replace 2%positive with (1 + 1)%positive.\n  rewrite Pos.mul_add_distr_r.\n  simpl.\n  apply Pos.add_le_mono.\n  apply pow2_mono.\n  zify. omega.\n  apply pow2_mono.\n  zify. omega.\n  zify. omega.\nQed.  \n\nFixpoint pos_log2 (p:positive) : N :=\n  match p with\n    | xH => 1%N\n    | xO p' => N.succ (pos_log2 p')\n    | xI p' => N.succ (pos_log2 p')\n  end.\n\nLemma pow2_succ (n:N) : (pow2 (N.succ n) = (pow2 n)~0)%positive.\nProof.\n  destruct n.\n  compute. auto.\n  simpl.\n  unfold shift_pos. simpl.\n  rewrite Pos.iter_succ.\n  auto.\nQed.    \n\nLemma pow2_pos_log2 (p:positive) : (p < pow2 (pos_log2 p))%positive.\nProof.\n  red. unfold Pos.compare.\n  generalize Eq.\n  induction p.\n  simpl; intros.\n  rewrite pow2_succ.\n  simpl. apply IHp.\n  simpl; intros.\n  rewrite pow2_succ.\n  simpl. apply IHp.\n  simpl. auto.\nQed.    \n\nLemma oneOver2n_small : forall ε:Q, 0 < ε -> exists n, oneOver2n n <= ε.\nProof.\n  intros.\n  exists (pos_log2 (Qden ε)).\n  destruct ε.\n  red in H. simpl in H.\n  ring_simplify in H.\n  simpl.\n  red; simpl.\n  apply Z.le_trans with (1 * 'Qden)%Z.\n  simpl. reflexivity.\n  apply Zmult_le_compat.\n  omega.\n  cut ( Qden <  pow2 (pos_log2 Qden))%positive.\n  zify. omega.\n  apply pow2_pos_log2.\n  omega.\n  compute. discriminate.\nQed.\n\n\nModule cauchy_limit_cuts.\n\nProgram Definition widen_cut (n:N) (x:cut) : cut :=\n  Cut (image (Preord.Hom _ _ (Qplus (oneOver2n n)) _) (cut_upper x))\n      (image (Preord.Hom _ _ (Qplus (- oneOver2n n)) _) (cut_lower x))\n      _ _ _ _.\nNext Obligation.\n  intros. red in H. simpl in H.\n  red. simpl. rewrite H. reflexivity.\nQed.\nNext Obligation.\n  intros. red in H. simpl in H.\n  red. simpl. rewrite H. reflexivity.\nQed.\nNext Obligation.\n  simpl; intros.\n  apply image_axiom2 in H.\n  apply image_axiom2 in H0.\n  destruct H as [q1 [??]].\n  destruct H0 as [q2 [??]].\n  simpl in *.\n  destruct H1. red in H1. simpl in H1.\n  destruct H2. red in H2. simpl in H2.\n  rewrite H2. rewrite H1.\n  apply Qle_trans with (0 + q2)%Q.\n  apply Qplus_le_compat.\n  rewrite <- (Qplus_le_l _ _ (oneOver2n n)).\n  ring_simplify.\n  apply Qlt_le_weak.\n  apply oneOver2n_pos.\n  apply Qle_refl.\n  apply Qle_trans with (0 + q1)%Q.\n  apply Qplus_le_compat; auto.\n  apply Qle_refl.\n  apply cut_proper with x; auto.\n  apply Qplus_le_compat.\n  apply Qlt_le_weak.\n  apply oneOver2n_pos.\n  apply Qle_refl.\nQed.\nNext Obligation.\n  intros.\n  apply image_axiom2 in H0.\n  destruct H0 as [y [??]]. simpl in *.\n  apply image_axiom1'.\n  exists (q1 + oneOver2n n)%Q.\n  split. simpl.\n  split; red; simpl; ring.\n  eapply cut_is_lower; eauto.\n  destruct H1. red in H1. simpl in H1.\n  rewrite <- (Qplus_le_l _ _ (-oneOver2n n)).\n  ring_simplify.\n  apply Qle_trans with q2; auto.\n  rewrite H1.\n  ring_simplify. apply Qle_refl.\nQed.\nNext Obligation.\n  intros.\n  apply image_axiom2 in H0.\n  destruct H0 as [y [??]]. simpl in *.\n  apply image_axiom1'.\n  exists (q2 - oneOver2n n)%Q.\n  split. simpl.\n  split; red; simpl; ring.\n  eapply cut_is_upper; eauto.\n  destruct H1. red in H1. simpl in H1.\n  rewrite <- (Qplus_le_l _ _ (oneOver2n n)).\n  ring_simplify.\n  apply Qle_trans with q1; auto.\n  rewrite H1.\n  ring_simplify. apply Qle_refl.\nQed.\nNext Obligation.\n  intros. split; intros [q ?].\n  apply image_axiom2 in H.\n  destruct H as [y [??]]; simpl in *.\n  destruct (cut_nonextended x).\n  destruct H1 as [z ?]; eauto.\n  exists (- oneOver2n n + z)%Q.\n  apply image_axiom1'. exists z. split; auto.\n  apply image_axiom2 in H.\n  destruct H as [y [??]]; simpl in *.\n  destruct (cut_nonextended x).\n  destruct H2 as [z ?]; eauto.\n  exists (oneOver2n n + z)%Q.\n  apply image_axiom1'. exists z. split; auto.\nQed.\n\nDefinition near ε (x y:cut) :=\n  (exists u l, u ∈ cut_upper x /\\ l ∈ cut_lower y /\\ u - l <= ε) /\\\n  (exists u l, u ∈ cut_upper y /\\ l ∈ cut_lower x /\\ u - l <= ε).\n\nDefinition is_limit (seq:N -> cut) (c:cut) :=\n  forall ε:Q, ε > 0 ->\n    exists m:N, forall (n:N), (m <= n)%N -> near ε (seq n) c.\n\nLemma is_limit_located seq lim : is_limit seq lim -> located lim.\nProof.\n  red; intros.\n  destruct (H (ε/(2#1))); auto.\n  apply Qlt_shift_div_l.\n  compute. auto.\n  ring_simplify. auto.\n  destruct (H1 x). reflexivity.\n  destruct H2 as [u1 [l1 [?[??]]]].\n  destruct H3 as [u2 [l2 [?[??]]]].\n  exists u2. exists l1.\n  split; auto. split; auto.\n  rewrite <- (Qplus_le_l _ _ l1).\n  rewrite <- (Qplus_le_l _ _ (-l2)).\n  ring_simplify.\n  apply Qle_trans with (ε/(2#1)).\n  ring_simplify in H7; auto.\n  rewrite <- (Qplus_le_l _ _ u1).\n  rewrite <- (Qplus_le_l _ _ (-l1)).\n  ring_simplify.\n  apply Qle_trans with (ε/(2#1) + ε/(2#1) )%Q.\n  rewrite <- Qplus_assoc.\n  apply Qplus_le_compat. apply Qle_refl.\n  ring_simplify in H5. auto.\n  rewrite <- (Qplus_le_l _ _ l2).\n  ring_simplify.\n  field_simplify.\n  cut (ε + l2 <= ε + u1).\n  intros. field_simplify in H8. auto.\n  apply Qplus_le_compat.\n  apply Qle_refl.\n  eapply cut_proper; eauto.\nQed.\n\nDefinition cauchy_sequence (seq:N -> cut) :=\n  forall n m o,\n     (o <= m)%N -> (o <= n)%N ->\n        exists u, u ∈ cut_upper (seq m) /\\\n        exists l, l ∈ cut_lower (seq n) /\\\n        u - l < oneOver2n o.\n\nSection cut_cauchy_limit.\n  Variable seq : N -> cut.\n  Hypothesis seq_cauchy : cauchy_sequence seq.\n\n  Program Definition limit_uppers (n:N) : eset Qpreord :=\n    image (Preord.Hom _ _ (Qplus (oneOver2n n)) _) (cut_upper (seq n)).\n  Next Obligation.\n    intros. red; simpl.\n    red in H. simpl in H. rewrite H. reflexivity.\n  Qed.\n\n  Program Definition limit_lowers (n:N) : eset Qpreord :=\n    image (Preord.Hom _ _ (Qplus (-oneOver2n n)) _) (cut_lower (seq n)).\n  Next Obligation.\n    intros. red; simpl.\n    red in H. simpl in H. rewrite H. reflexivity.\n  Qed.\n \n  Definition limit_upper : eset Qpreord :=\n    union ( (fun n => Some (limit_uppers n)) : eset (eset Qpreord)).\n\n  Definition limit_lower : eset Qpreord :=\n    union ( (fun n => Some (limit_lowers n)) : eset (eset Qpreord)).\n\n  Program Definition limit : cut :=\n    Cut limit_upper limit_lower _ _ _ _.\n  Next Obligation.\n    simpl; intros.\n    apply union_axiom in H.\n    apply union_axiom in H0.\n    destruct H as [R [??]].\n    destruct H0 as [S [??]].\n    destruct H as [n ?].\n    destruct H0 as [m ?].\n    rewrite H in H1.\n    rewrite H0 in H2. clear H H0.\n    unfold limit_uppers in H1.\n    apply image_axiom2 in H1.\n    destruct H1 as [y [??]].\n    simpl in *.\n    destruct H0 as [? _]. red in H0; simpl in H0.\n    rewrite H0.\n    unfold limit_lowers in H2.\n    apply image_axiom2 in H2.\n    destruct H2 as [y' [??]].\n    simpl in *.\n    destruct H2 as [? _]. red in H2. simpl in H2. rewrite H2.\n    destruct (seq_cauchy n m (N.min n m)) as [u' [? [l' [??]]]].\n    apply N.le_min_r.\n    apply N.le_min_l.\n    assert (y' <= u'). eapply cut_proper; eauto.\n    assert (l' <= y). eapply cut_proper; eauto.\n    rewrite <- (Qplus_le_l _ _ (oneOver2n m)).\n    ring_simplify. \n    apply Qle_trans with u'; auto.\n    rewrite <- (Qplus_le_l _ _ (-l')).\n    apply Qle_trans with (oneOver2n (N.min n m)).\n    ring_simplify in H5. ring_simplify. intuition.\n    rewrite <- (Qplus_le_l _ _ (l')). ring_simplify.\n    apply Qplus_le_compat; auto.\n    apply N.min_case.\n    rewrite <- (Qplus_le_l _ _ (-oneOver2n n)). ring_simplify.\n    apply Qlt_le_weak. apply oneOver2n_pos.\n    rewrite <- (Qplus_le_l _ _ (-oneOver2n m)). ring_simplify.\n    apply Qlt_le_weak. apply oneOver2n_pos.\n  Qed.    \n  Next Obligation.\n    unfold limit_lower.\n    simpl; intros.\n    apply union_axiom in H0.\n    apply union_axiom.\n    destruct H0 as [X [??]].\n    exists X. split; auto.\n    destruct H0 as [n ?].\n    rewrite H0. rewrite H0 in H1.\n    unfold limit_lowers in H1.\n    unfold limit_lowers.\n    apply image_axiom2 in H1.\n    destruct H1 as [q [??]]. simpl in *.\n    apply image_axiom1'. simpl.\n    exists (q1 + oneOver2n n)%Q.\n    split.\n    split; red; simpl; ring.\n    apply cut_is_lower with q; auto.\n    apply Qle_trans with (q2 + oneOver2n n)%Q.\n    apply Qplus_le_compat; auto. apply Qle_refl.\n    destruct H2. red in H2; simpl in H2. rewrite H2.\n    ring_simplify. apply Qle_refl.\n  Qed.\n  Next Obligation.\n    unfold limit_upper.\n    simpl; intros.\n    apply union_axiom in H0.\n    apply union_axiom.\n    destruct H0 as [X [??]].\n    exists X. split; auto.\n    destruct H0 as [n ?].\n    rewrite H0. rewrite H0 in H1.\n    unfold limit_uppers in H1.\n    unfold limit_uppers.\n    apply image_axiom2 in H1.\n    destruct H1 as [q [??]]. simpl in *.\n    apply image_axiom1'. simpl.\n    exists (q2 - oneOver2n n)%Q.\n    split.\n    split; red; simpl; ring.\n    apply cut_is_upper with q; auto.\n    apply Qle_trans with (q1 - oneOver2n n)%Q.\n    destruct H2. red in H2; simpl in H2. rewrite H2.\n    ring_simplify. apply Qle_refl.\n    apply Qplus_le_compat; auto. apply Qle_refl.\n  Qed.\n  Next Obligation.\n    unfold limit_upper, limit_lower.\n    destruct (seq_cauchy 0 0 0)%N as [u [? [l [??]]]]. \n    reflexivity.\n    reflexivity.\n    split; intros.\n    exists (-oneOver2n 0 + l)%Q.\n    apply union_axiom.\n    exists (limit_lowers 0).\n    split. exists 0%N. auto.\n    unfold limit_lowers.\n    apply image_axiom1'.\n    simpl.\n    exists l. split; auto.\n    exists (oneOver2n 0 + u)%Q.\n    apply union_axiom.\n    exists (limit_uppers 0).\n    split. exists 0%N. auto.\n    unfold limit_lowers.\n    apply image_axiom1'.\n    simpl.\n    exists u. split; auto.\n  Qed.    \n\n  Lemma limit_correct : is_limit seq limit.\n  Proof.\n    red; intros.\n    destruct (oneOver2n_small ε) as [m ?]; auto.\n    exists (m+1)%N. intros.\n    split.\n    destruct (seq_cauchy (m+1) n (m+1))%N as [u [? [l [??]]]]; auto.\n    reflexivity.\n    exists u. exists (-oneOver2n (m+1) + l)%Q. split; auto. split.\n    simpl.\n    unfold limit_lower.\n    apply union_axiom.\n    exists (limit_lowers (m+1)).\n    split. exists (m+1)%N. auto.\n    unfold limit_lowers.\n    apply image_axiom1'; simpl.\n    exists l. split; auto.\n    rewrite <- (Qplus_le_l _ _ (-oneOver2n (m+1))).\n    ring_simplify.\n    apply Qle_trans with (oneOver2n (m+1)).\n    ring_simplify in H4. intuition.\n    rewrite <- (Qplus_le_l _ _ (oneOver2n (m+1))).\n    ring_simplify.\n    rewrite <- oneOver2n_commute.\n    unfold oneOver2n at 2. simpl.\n    unfold shift_pos. simpl.\n    field_simplify.\n    field_simplify in H0. auto.\n            \n    destruct (seq_cauchy n (m+1) (m+1))%N as [u [? [l [??]]]]; auto.\n    reflexivity.\n    exists (oneOver2n (m+1) + u)%Q. exists l. split; auto. \n    simpl.\n    unfold limit_upper.\n    apply union_axiom.\n    exists (limit_uppers (m+1)).\n    split. exists (m+1)%N. auto.\n    unfold limit_uppers.\n    apply image_axiom1'; simpl.\n    exists u. split; auto.\n    split; auto.\n    rewrite <- (Qplus_le_l _ _ (-oneOver2n (m+1))).\n    ring_simplify.\n    apply Qle_trans with (oneOver2n (m+1)).\n    ring_simplify in H4. intuition.\n    rewrite <- (Qplus_le_l _ _ (oneOver2n (m+1))).\n    ring_simplify.\n    rewrite <- oneOver2n_commute.\n    unfold oneOver2n at 2. simpl.\n    unfold shift_pos. simpl.\n    field_simplify.\n    field_simplify in H0. auto.\n  Qed.\n\n  Lemma located_limit : located limit.\n  Proof.\n    eapply is_limit_located. apply limit_correct.\n  Qed.\nEnd cut_cauchy_limit.\n\nEnd cauchy_limit_cuts.\n\n\n\nProgram Definition shift_cut (q:Q) (c:cut) :=\n  Cut (image (Preord.Hom _ _ (Qplus q) _) (cut_upper c))\n      (image (Preord.Hom _ _ (Qplus q) _) (cut_lower c))\n      _ _ _ _.\nNext Obligation.\n  red; intros.\n  simpl. red in H. simpl in H. rewrite H. reflexivity.\nQed.\nNext Obligation.\n  red; intros.\n  simpl. red in H. simpl in H. rewrite H. reflexivity.\nQed.\nNext Obligation.\n  simpl; intros.\n  apply image_axiom2 in H.\n  destruct H as [u' [??]].\n  apply image_axiom2 in H0.\n  destruct H0 as [l' [??]].\n  simpl in *.\n  destruct H1. destruct H2.\n  red in H1. simpl in H1.\n  red in H2. simpl in H2.\n  rewrite H2. rewrite H1.\n  apply Qplus_le_compat.\n  apply Qle_refl.\n  eapply cut_proper; eauto.\nQed.\nNext Obligation.\n  intros.\n  apply image_axiom2 in H0.\n  destruct H0 as [y [??]]. simpl in *.\n  apply image_axiom1'. simpl.\n  exists (q1 - q)%Q.\n  split.\n  split; red; simpl; ring.\n  apply cut_is_lower with y; auto.\n  rewrite <- (Qplus_le_l _ _ q).\n  ring_simplify.\n  apply Qle_trans with q2; auto.\n  destruct H1. red in H1. simpl in H1.\n  rewrite H1.\n  ring_simplify. apply Qle_refl.\nQed.\nNext Obligation.\n  intros.\n  apply image_axiom2 in H0.\n  destruct H0 as [y [??]]. simpl in *.\n  apply image_axiom1'. simpl.\n  exists (q2 - q)%Q.\n  split.\n  split; red; simpl; ring.\n  apply cut_is_upper with y; auto.\n  rewrite <- (Qplus_le_l _ _ (q)).\n  ring_simplify.\n  apply Qle_trans with q1; auto.\n  destruct H1. red in H1. simpl in H1.\n  rewrite H1.\n  ring_simplify. apply Qle_refl.\nQed.\nNext Obligation.\n  intros.\n  split; intros.\n  destruct H as [x ?].\n  apply image_axiom2 in H.\n  destruct H as [y [??]]. simpl in*.\n  destruct (cut_nonextended c).\n  destruct H1 as [l ?]; eauto.\n  exists (l + q)%Q.\n  apply image_axiom1'. simpl.\n  exists l. split.\n  split; red; simpl; ring.\n  auto.\n  destruct H as [x ?].\n  apply image_axiom2 in H.\n  destruct H as [y [??]]. simpl in*.\n  destruct (cut_nonextended c).\n  destruct H2 as [u ?]; eauto.\n  exists (u + q)%Q.\n  apply image_axiom1'. simpl.\n  exists u. split.\n  split; red; simpl; ring.\n  auto.\nQed.\n\n\nRecord cut_telescope := CutTelescope\n  { seq_upper : N -> cut\n  ; seq_lower : N -> cut\n  ; seq_proper : forall n, cut_lt (seq_lower n) (seq_upper n)\n  ; seq_upper_inside : forall n m, (n < m)%N -> cut_lt (seq_upper m) (seq_upper n)\n  ; seq_lower_inside : forall n m, (n < m)%N -> cut_lt (seq_lower n) (seq_lower m)\n  ; seq_converges : forall ε, 0 < ε ->\n     exists n a b,\n       a ∈ cut_upper (seq_upper n) /\\\n       b ∈ cut_lower (seq_lower n) /\\\n       a - b <= ε\n  }.\n\nSection cauchy_to_telescope.\n  Variable seq : N -> cut.\n  Hypothesis Hcauchy : cauchy_limit_cuts.cauchy_sequence seq.\n\n  Program Definition cauchy_telescope :=\n    CutTelescope\n      (fun n => shift_cut (oneOver2n n) (seq (n+1)))\n      (fun n => shift_cut (-oneOver2n n) (seq (n+1)))\n      _ _ _ _.\n  Next Obligation.\n    repeat intro.\n    red. simpl.\n    destruct (Hcauchy (n+1) (n+1) n)%N as [u [? [l [??]]]]; auto.\n    zify; omega.\n    zify; omega.\n\n    exists (u - oneOver2n n)%Q.\n    exists (l + oneOver2n n)%Q.\n    split.\n    apply image_axiom1'. simpl.\n    exists u. split.\n    split; red; simpl; ring. auto.\n    split.\n    apply image_axiom1'. simpl.\n    exists l. split.\n    split; red; simpl; ring. auto.\n    rewrite <- (Qplus_lt_l _ _ (oneOver2n n)).\n    ring_simplify.\n    rewrite <- (Qplus_lt_l _ _ (-l)). ring_simplify.\n    apply Qle_lt_trans with (u-l).\n    ring_simplify. apply Qle_refl.\n    eapply Qlt_le_trans. apply H1.\n    rewrite <- (Qplus_le_l _ _ (-oneOver2n n)).\n    ring_simplify.\n    apply Qlt_le_weak.\n    apply oneOver2n_pos.\n  Qed.    \n  Next Obligation.\n    repeat intro. red.\n    destruct (Hcauchy (n+1) (m+1) (n+1))%N as [u [? [l [??]]]]; intuition.\n    zify. omega.\n\n    exists (u + oneOver2n m)%Q.\n    exists (l + oneOver2n n)%Q.\n    split.\n    simpl.\n    apply image_axiom1'.\n    simpl. exists u. split.\n    split; red; simpl; ring.\n    auto.\n    split.\n    apply image_axiom1'.\n    simpl. exists l. split.\n    split; red; simpl; ring.\n    auto.\n    rewrite <- (Qplus_lt_l _ _ (-oneOver2n m)).\n    ring_simplify.\n    rewrite <- (Qplus_lt_l _ _ (-l)).\n    apply Qle_lt_trans with (u-l); auto.\n    ring_simplify. apply Qle_refl.\n    eapply Qlt_le_trans. apply H2.\n    ring_simplify.\n    rewrite <- (Qplus_le_l _ _ (oneOver2n m)).\n    ring_simplify.\n    apply oneOver2n_subsumes; auto.\n    zify. omega.\n  Qed.\n  Next Obligation.\n    repeat intro. red.\n    destruct (Hcauchy (m+1) (n+1) (n+1))%N as [u [? [l [??]]]]; intuition.\n    zify. omega.\n\n    exists (u - oneOver2n n)%Q.\n    exists (l - oneOver2n m)%Q.\n    split.\n    simpl.\n    apply image_axiom1'.\n    simpl. exists u. split.\n    split; red; simpl; ring.\n    auto.\n    split.\n    apply image_axiom1'.\n    simpl. exists l. split.\n    split; red; simpl; ring.\n    auto.\n    rewrite <- (Qplus_lt_l _ _ (oneOver2n n)).\n    ring_simplify.\n    rewrite <- (Qplus_lt_l _ _ (-l)).\n    ring_simplify.\n    apply Qle_lt_trans with (u-l); auto.\n    ring_simplify. apply Qle_refl.\n    eapply Qlt_le_trans. apply H2.\n    rewrite <- (Qplus_le_l _ _ (oneOver2n m)).\n    ring_simplify.\n    apply oneOver2n_subsumes; auto.\n    zify. omega.\n  Qed.\n  Next Obligation.\n    intros.\n    destruct (oneOver2n_small (ε/(3#1))).\n    apply Qlt_shift_div_l. compute. auto.\n    ring_simplify. auto.\n\n    exists x.\n    destruct (Hcauchy (x+1) (x+1) (x+1))%N as [u [? [l [??]]]]; intuition.\n    exists (u + oneOver2n x)%Q.\n    exists (l - oneOver2n x)%Q.\n    split.\n    simpl.\n    apply image_axiom1'.\n    simpl.\n    exists u. split; auto.\n    split; red; simpl; ring.\n    split.\n    simpl.\n    apply image_axiom1'.\n    simpl.\n    exists l. split; auto.\n    split; red; simpl; ring.\n    ring_simplify.\n    rewrite <- (Qplus_le_l _ _ (-(2#1) * oneOver2n x)).\n    ring_simplify.\n    apply Qlt_le_weak.\n    eapply Qlt_le_trans. apply H3.\n    rewrite <- (Qplus_le_l _ _ ((2#1) * oneOver2n x)).\n    ring_simplify.\n    rewrite <- oneOver2n_commute.\n    unfold oneOver2n at 2. simpl.\n    unfold shift_pos. simpl.\n    ring_simplify.\n    apply Qle_trans with ((5#2)*(ε/(3#1))).\n    apply Qmult_le_compat; intuition.\n    unfold Qdiv. unfold Qinv. simpl.\n    ring_simplify.\n    apply Qle_trans with (1*ε).\n    apply Qmult_le_compat; intuition.\n    ring_simplify. apply Qle_refl.\n  Qed.\n\n  Let interval_limit (t:cut_telescope) : cut :=\n    interval_limit_cuts.interval_limit \n      (seq_upper t) (seq_lower t)\n      (seq_proper t) (seq_upper_inside t) (seq_lower_inside t).\n\n  Lemma telescope_limit_is_limit :\n    cauchy_limit_cuts.is_limit seq (interval_limit cauchy_telescope).\n  Proof.\n    red. intros.\n    destruct (oneOver2n_small (ε/(2#1))).\n    apply Qlt_shift_div_l. compute. auto.\n    ring_simplify. auto.\n    exists x. intros. split.\n    destruct (Hcauchy (x+1) n x)%N as [u [? [l [??]]]]; auto.\n    zify; omega. \n    exists u. exists (l - oneOver2n x). split; auto.\n    split; simpl.\n    unfold interval_limit_cuts.limit_lower.\n    apply union_axiom.\n    exists (cut_lower (shift_cut (- oneOver2n x) (seq (x+1)))).\n    split. exists x. auto.\n    simpl. apply image_axiom1'.\n    simpl. exists l. split; auto.\n    split; red; simpl; ring.\n    ring_simplify.\n    rewrite <- (Qplus_le_l _ _ (- oneOver2n x)).\n    ring_simplify.\n    apply Qlt_le_weak. eapply Qlt_le_trans. apply H4.\n    rewrite <- (Qplus_le_l _ _ (oneOver2n x)).\n    ring_simplify.\n    apply Qle_trans with ((2#1) * (ε / (2#1))).\n    apply Qmult_le_compat; intuition.\n    field_simplify.\n    field_simplify.\n    intuition.\n        \n    destruct (Hcauchy n (x+1) x)%N as [u [? [l [??]]]]; auto.\n    zify; omega. \n    exists (u + oneOver2n x)%Q. exists l. \n    split.\n    simpl.\n    unfold interval_limit_cuts.limit_upper.\n    apply union_axiom.\n    exists (cut_upper (shift_cut (oneOver2n x) (seq (x+1)))).\n    split. exists x. auto.\n    simpl. apply image_axiom1'.\n    simpl. exists u. split; auto.\n    split; red; simpl; ring.\n    split; auto.\n    rewrite <- (Qplus_le_l _ _ (- oneOver2n x)).\n    ring_simplify.\n    apply Qlt_le_weak. eapply Qlt_le_trans. apply H4.\n    rewrite <- (Qplus_le_l _ _ (oneOver2n x)).\n    ring_simplify.\n    apply Qle_trans with ((2#1) * (ε / (2#1))).\n    apply Qmult_le_compat; intuition.\n    field_simplify.\n    field_simplify.\n    intuition.\n  Qed.\n\nEnd cauchy_to_telescope.\n", "meta": {"author": "robdockins", "repo": "domains", "sha": "6feea4ed576f8aa849af9fa102633d5df1191360", "save_path": "github-repos/coq/robdockins-domains", "path": "github-repos/coq/robdockins-domains/domains-6feea4ed576f8aa849af9fa102633d5df1191360/realcuts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6967788638919725}}
{"text": "Require Export XR_S_INR.\nRequire Export XR_Rplus_le_compat.\nRequire Export XR_Rlt_0_1.\n\nLocal Open Scope R_scope.\n\nLemma pos_INR : forall n:nat, R0 <= INR n.\nProof.\n  induction n as [ | n hn ].\n  {\n    simpl.\n    unfold \"<=\".\n    right.\n    reflexivity.\n  }\n  {\n    rewrite S_INR.\n    rewrite <- Rplus_0_r with R0.\n    apply Rplus_le_compat.\n    { exact hn. }\n    {\n      unfold \"<=\".\n      left.\n      exact Rlt_0_1.\n    }\n  }\nQed.", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_pos_INR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.69677500566762}}
{"text": "Require Export Arith.\nRequire Export ArithRing.\nRequire Export Omega.\nRequire Export Wf_nat.\n \nFixpoint div2 (n : nat) : nat :=\n match n with S (S p) => S (div2 p) | _ => 0 end.\n \nTheorem div2_ind:\n forall (P : nat ->  Prop),\n P 0 -> P 1 -> (forall n, P n ->  P (S (S n))) -> forall n,  P n.\nProof.\nintros P H0 H1 Hstep n.\nassert (H : P n /\\ P (S n)) by (elim n; intuition).\n now destruct H.\nQed.\n \nTheorem div2_lt: forall n,  (div2 (S n) < S n).\nProof.\nintros; elim n  using div2_ind; simpl; intros; omega.\nQed.\n \nDefinition log2_it_F (log2 : nat ->  nat) (n : nat) : nat :=\n   match n with\n     0 => 0\n    | 1 => 0\n    | S (S p) => S (log2 (div2 (S (S p))))\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 log2_terminates:\n forall (n : nat),\n  ({v : nat | exists p : nat , forall k g, p < k ->  iter log2_it_F k g n = v }).\nProof. \n intros n; elim n  using (well_founded_induction lt_wf); clear n.\n intros n; case n.\n - intros; exists 0, 0;  intros k; case k.\n   + intros; omega.\n   + intros k' g _; simpl; auto.\n - intros n'; case n'.\n   + intros; exists 0; exists 0; intros k; case k.\n     * intros; omega.\n     * intros k' g_; simpl; auto.\n   + intros p f; assert (Hlt: div2 (S (S p)) < S (S p))\n                 by apply div2_lt.\n     destruct (f (div2 (S (S p))) Hlt) as [v Hex];exists (S v).\n     destruct Hex as [p' Heq];exists (S p').\n     intros k g; case k.\n     * intros; omega.\n     * intros k' Hltk;rewrite <- (Heq k' g); auto.\n       omega.\nQed.\n \nDefinition log2 (n : nat) : nat :=\n   match log2_terminates n with exist _ v _ => v end.\n \nTheorem log2_fix_eqn:\n forall n,  log2 n = match n with\n                       0 => 0\n                      | 1 => 0\n                      | S (S p) => S (log2 (div2 (S (S p))))\n                     end.\nProof. \n intros n; unfold log2; case (log2_terminates n); case n.\n - intros v [p Heq]; rewrite <- (Heq (S p) log2); auto.\n - intros n'; case n'.\n   + intros v [p Heq];rewrite <- (Heq (S p) log2); auto.\n   + intros n'' v [p Heq];case (log2_terminates (div2 (S (S n'')))).\n     intros v' [p' Heq'];\n     rewrite <- (Heq (S (S (p + p'))) log2),\n             <- (Heq' (S (p + p')) log2); auto.\n     omega.\n     omega.\nQed.\n \nTheorem div2_eq: forall n,  2 * div2 n = n \\/ 2 * div2 n + 1 = n.\nProof.\nintros n; elim n  using div2_ind; simpl; (try omega).\nintros n' [Heq|Heq]; omega.\nQed.\n \nFixpoint exp2 (n : nat) : nat :=\n match n with 0 => 1 | S p => 2 * exp2 p end.\n \nTheorem log2_power:\n forall n, 0 < n ->  ( exp2 (log2 n) <= n < 2 * exp2 (log2 n) ).\nProof. \nintros n; elim n  using (well_founded_ind lt_wf).\nintros x; case x.\n- simpl; intros; omega.\n- intros x'; case x'.\n  + rewrite (log2_fix_eqn 1); simpl; auto with arith.\n  + intros p Hrec; elim (Hrec (div2 (S (S p)))).\n    * intros Hle Hlt _; rewrite (log2_fix_eqn (S (S p))).\n      cbv zeta iota beta delta [exp2]; fold exp2.\n      split.\n      apply le_trans with (2 * div2 (S (S p))).\n      auto with arith.\n      elim (div2_eq (S (S p))).\n      omega.\n      omega.\n      apply le_lt_trans with (2 * div2 (S (S p)) + 1).\n      elim (div2_eq (S (S p))).\n      omega.\n      omega.\n      omega.\n    * apply div2_lt; simpl; auto with arith.\n    *  simpl; auto with arith.\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/ch15_general_recursion/SRC/log2_it.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6967749878061501}}
{"text": "(*\nJust some extra (optional) thms/stuff, feel free to add more.\n*)\n\n(* Thm references etc. are to \"Introduction to Bisimulation and Coinduction\". *)\nSection LTS.\n\nRequire Import Coq.Lists.List.\nImport ListNotations. (* defines notation [[]] for [nil] *)\n\n(* Stolen from coq-contribs/ccs on Github *)\n\nVariable process action : Set.\nVariable transition : process -> action -> process -> Prop.\n\n(*\nThis is bisimilarity characterized as the largest bisimilation. I.e. thm 1.4.15,\nbut taken as a definition.\n\nThis definition (and its name) is from the above repo.\n*)\nCoInductive strong_eq : process -> process -> Prop :=\n  str_eq : forall p q : process,\n    (forall (a : action) (p' : process),\n        transition p a p' ->\n        exists q' : process, transition q a q' /\\ strong_eq p' q') ->\n    (forall (a : action) (q' : process),\n        transition q a q' ->\n        exists p' : process, transition p a p' /\\ strong_eq p' q') ->\n    strong_eq p q.\n\n(*\nNow we want a co-induction principle for this thing! This does not correspond directly to the definition in the book, because we do not want the /\\ inside the forall ...\n(This is not from the above repo.)\n*)\nTheorem strong_eq_coind : forall (R : process -> process -> Prop),\n    (forall (p q : process),\n    (forall (a : action) (p' : process),\n        R p q -> transition p a p' ->\n        exists q' : process, transition q a q' /\\ R p' q')) ->\n    (forall (p q : process),\n    (forall (a : action) (q' : process),\n        R p q -> transition q a q' ->\n        exists p' : process, transition p a p' /\\ R p' q')) ->\n    forall (p q : process), R p q -> strong_eq p q.\nAdmitted.\n\nRequire Import Coq.Relations.Relation_Definitions.\n\n(*\nPeople asked about this during the \"lecture\", so why not prove it formally?\n(Why isn't the first argument implicit for equiv? Strange design!)\nAlso, warning: The transitivity proof seemed long in the original file (but not necessarily complicated or unreasonably long).\n\nThis is thm 1.4.14 in the book.\n*)\nTheorem strong_eq_equiv' : equiv _ strong_eq.\nAdmitted.\n\n(* Almost exercise 1.4.16, but alternative definition of bisimilar instead of bisimulation *)\nInductive ttransition : process -> list action -> process -> Prop :=\n| ttransition_base : forall (p : process),\n    ttransition p [] p\n| ttransition_step : forall (p1 p2 p3 : process) (act : action) (acts : list action),\n    transition p1 act p2 -> ttransition p2 acts p3 -> ttransition p1 (act::acts) p3.\n\nCoInductive tstrong_eq : process -> process -> Prop :=\n  tstr_eq : forall p q : process,\n    (forall (acts : list action) (p' : process),\n        ttransition p acts p' ->\n        exists q' : process, ttransition q acts q' /\\ tstrong_eq p' q') ->\n    (forall (acts : list action) (q' : process),\n        ttransition q acts q' ->\n        exists p' : process, ttransition p acts p' /\\ tstrong_eq p' q') ->\n    tstrong_eq p q.\n\nTheorem strong_eq_eq_tstrong_eq : forall (p q : process), strong_eq p q <-> tstrong_eq p q.\nAdmitted.\n\n(* 2.1.1 Finite traces and ω-traces on processes *)\n\n(* Finite traces *)\nInductive ft : process -> Prop :=\n| ft_stopped p : (forall (a : action), ~(exists (p' : process), transition p a p')) -> ft p\n| ft_step p : forall (a : action) (p' : process), transition p a p' -> ft p' -> ft p.\n\nTheorem strong_eq_ft : forall (p q : process),\n    ft p -> strong_eq p q -> ft q.\nAdmitted.\n\n(* ω-traces *)\nCoInductive wt (a : action) : process -> Prop :=\n| wt_step p : forall (p' : process), transition p a p' -> wt a p' -> wt a p.\n\n(* Co-induction principle for ω-traces *)\nTheorem wt_coind : forall (a : action) (R : process -> Prop),\n    (forall (p : process), R p -> exists (p' : process), R p' /\\ transition p a p') ->\n    (forall (p : process), R p -> wt a p).\nAdmitted.\n\nTheorem strong_eq_wt : forall (a : action) (p q : process),\n    wt a p -> strong_eq p q -> wt a q.\nAdmitted.\n\nEnd LTS.\n\n(* Shows that P1 and Q1 from fig. 1.2 (in the book), i.e. one of the examples from the \"lecture\", are bisimilar *)\nInductive ex1_processes :=\n  P1 | P2 | Q1 | Q2 | Q3.\n\nInductive ex1_actions :=\n  a | b.\n\nInductive ex1_trans : ex1_processes -> ex1_actions -> ex1_processes -> Prop :=\n(* Left system *)\n| P1P2 : ex1_trans P1 a P2\n| P2P1 : ex1_trans P2 b P1\n(* Right system *)\n| Q1Q2 : ex1_trans Q1 a Q2\n| Q2Q3 : ex1_trans Q2 b Q3\n| Q3Q2 : ex1_trans Q3 a Q2.\n\nInductive ex1_R : ex1_processes -> ex1_processes -> Prop :=\n| P1Q1_R : ex1_R P1 Q1\n| P1Q3_R : ex1_R P1 Q3\n| P2Q2_R : ex1_R P2 Q2.\n\nTheorem P1_Q1_bisim : strong_eq _ _ ex1_trans P1 Q1.\nProof.\n  apply (strong_eq_coind _ _ _ ex1_R); intros.\n  * destruct p; inversion H; inversion H0; subst.\n   + (* R (P1, Q1) *) exists Q2. split; constructor.\n   + (* R (P1, Q3) *) exists Q2. split; constructor.\n   + (* R (P2, Q2) *) exists Q3. split; constructor.\n  * destruct q; inversion H; inversion H0; subst.\n   + (* R (P1, Q1) *) exists P2. split; constructor.\n   + (* R (P2, Q2) *) exists P1. split; constructor.\n   + (* R (P1, Q3) *) exists P2. split; constructor.\n  * constructor. Qed.\n", "meta": {"author": "vlopezj", "repo": "coq-course", "sha": "b7f3c44d73859ddad49a6edbfd3430283bcc251f", "save_path": "github-repos/coq/vlopezj-coq-course", "path": "github-repos/coq/vlopezj-coq-course/coq-course-b7f3c44d73859ddad49a6edbfd3430283bcc251f/exercises/4/extra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6967393490463795}}
{"text": "Inductive even : nat -> Prop :=\n  | Even0 : even 0\n  | EvenS : forall n:nat, even n -> even (S (S n)).\n\nLemma not_1_even: ~ even 1.\nProof.\n  unfold not. cut (forall n:nat, n = 1 -> even n -> False). eauto.\n  intros n H He. generalize H. clear H. generalize He. elim He.\n  intros. discriminate. clear He n. intros. discriminate.\nQed.\n\n\nLemma not_1_even': ~ even 1.\nProof.\n  unfold not. intros H. inversion H.\nQed.\n\nLemma plus_2_even_inv: forall n:nat, even (S (S n)) -> even n.\nProof.\n  intros n H. inversion H. exact H1.\nQed.\n\n\nLemma not_1_even'': ~ even 1.\nProof.\n  intro H. generalize (refl_equal 1).\n  pattern 1 at -2. elim H; intros; discriminate.\nQed.\n\n\nLemma plus_2_even_inv': forall n:nat, even (S (S n)) -> even n.\nProof.\n  intro n. cut(forall m:nat, m = S (S n) -> even m -> even n).\n  eauto. intros m H He. generalize He H. clear H. generalize n.\n  clear n. elim He. intros. discriminate. clear m He.\n  intros. injection H1. intros. rewrite <- H2. exact H.\nQed.\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915616, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.6967393480250829}}
{"text": "Require Export GeoCoq.Tarski_dev.Annexes.circles.\nRequire Export GeoCoq.Tarski_dev.Annexes.half_angles.\nRequire Export GeoCoq.Tarski_dev.Ch12_parallel_inter_dec.\n\nSection Inscribed_angle.\n\nContext `{TE:Tarski_euclidean}.\n\n(** The sum of the angles of a triangle is the flat angle. *)\n\nLemma trisuma__bet : forall A B C D E F, TriSumA A B C D E F -> Bet D E F.\nProof.\n  apply alternate_interior__triangle.\n  unfold alternate_interior_angles_postulate.\n  apply l12_21_a.\nQed.\n\nLemma bet__trisuma : forall A B C D E F, Bet D E F -> A <> B -> B <> C -> A <> C -> D <> E -> E <> F ->\n  TriSumA A B C D E F.\nProof.\n  intros A B C D E F HBet; intros.\n  destruct (ex_trisuma A B C) as [P [Q [R HTri]]]; auto.\n  apply conga_trisuma__trisuma with P Q R; trivial.\n  assert (Hd := HTri).\n  apply trisuma_distincts in Hd; spliter.\n  apply conga_line; auto.\n  apply (trisuma__bet A B C); trivial.\nQed.\n\nLemma right_saccheris : forall A B C D, Saccheri A B C D -> Per A B C.\nProof.\n  apply postulates_in_euclidean_context; simpl; repeat (try (left; reflexivity); right).\nQed.\n\nLemma not_obtuse_saccheris : ~ hypothesis_of_obtuse_saccheri_quadrilaterals.\nProof.\n  apply not_oah; right.\n  unfold hypothesis_of_right_saccheri_quadrilaterals; apply right_saccheris.\nQed.\n\nLemma suma123231__sams : forall A B C D E F, SumA A B C B C A D E F -> SAMS D E F C A B.\nProof. exact (t22_20 not_obtuse_saccheris). Qed.\n\nLemma bet_suma__suma : forall A B C D E F G H I, G <> H -> H <> I ->\n  Bet G H I -> SumA A B C B C A D E F -> SumA D E F C A B G H I.\nProof.\n  intros A B C D E F G H I HGH HHI HBet HSuma.\n  suma.assert_diffs.\n  destruct (bet__trisuma A B C G H I) as [D' [E' [F' []]]]; auto.\n  apply (conga3_suma__suma D' E' F' C A B G H I); try apply conga_refl; auto.\n  apply (suma2__conga A B C B C A); assumption.\nQed.\n\nLemma high_school_exterior_angle_theorem : forall A B C B', A <> B -> B <> C -> A <> C -> A <> B' ->\n  Bet B A B' -> SumA A B C B C A C A B'.\nProof.\n  intros A B C B'; intros.\n  assert (SumA C A B' C A B B A B').\n    apply suma_sym, suma_left_comm, bet__suma; auto.\n  destruct (ex_suma A B C B C A) as [D [E [F]]]; auto.\n  apply (conga3_suma__suma A B C B C A D E F); try apply conga_refl; auto.\n  apply sams2_suma2__conga123 with C A B B A B'.\n    apply suma123231__sams; assumption.\n    apply bet_suma__sams with B A B'; assumption.\n    apply bet_suma__suma; auto.\n    assumption.\nQed.\n\n(** If A, B and C are points on a circle where the line AB is a diameter of the circle,\n    then the angle ACB is a right angle. *)\n\nLemma thales_theorem : forall A B C M, ~ Col A B C ->\n  Midpoint M A B -> Cong M A M C -> Per A C B.\nProof.\n  apply rah__thales_postulate.\n  unfold postulate_of_right_saccheri_quadrilaterals; apply right_saccheris.\nQed.\n\n(** In a right triangle, the midpoint of the hypotenuse is the circumcenter. *)\n\nLemma thales_converse_theorem : forall A B C M, A <> C -> B <> C ->\n  Midpoint M A B -> Per A C B -> Cong M A M C.\nProof.\n  intros A B C M HAC HBC HM HPer.\n  apply thales_postulate__thales_converse_postulate with B; [| |assumption..].\n    unfold thales_postulate; apply thales_theorem.\n  apply not_col_permutation_5, per_not_col; auto.\nQed.\n\nLemma bet_cong__ghalfa : forall A B C B', A <> B -> B <> C -> A <> B' ->\n  Bet B A B' -> Cong A B A C -> gHalfA A B C C A B'.\nProof.\n  intros A B C B' HAB HBC HAB' HBet HCong.\n  apply ghalfa_chara; split.\n    apply cong__acute; auto.\n  assert_diffs.\n  apply (conga3_suma__suma A B C B C A C A B'); try apply conga_refl; auto.\n    apply high_school_exterior_angle_theorem; auto.\n  apply conga_left_comm, l11_44_1_a; Cong.\nQed.\n\n(** If the angle ACB is inscribed in a circle of center O and\n    C, O lie on the same side of AB, then this angle is acute. *)\n\nLemma onc3_os__acute : forall O P A B C,\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> OS A B O C ->\n  Acute A C B.\nProof.\n  intros O P A B C HA HB HC HOS.\n  destruct (midpoint_existence A B) as [M HM].\n  assert (HNCol : ~ Col A B C) by (eapply one_side_not_col124, HOS).\n  assert (HLt : Lt M A M C).\n  { assert (HNCol1 : ~ Col A B O) by (eapply one_side_not_col123, HOS).\n    assert (M <> O) by (intro; treat_equalities; apply HNCol1; Col).\n    assert (O <> C) by (intro; treat_equalities; auto).\n    assert_diffs.\n    assert (Cong O A O C) by (apply (onc2__cong O P); assumption).\n    destruct (angle_partition M O C); auto.\n    - assert (HMO := H).\n      clear H.\n      destruct (l8_18_existence M O C) as [H []].\n      { intro.\n        destruct (acute_col__out M O C) as [_ [_ [HBet|HBet]]]; auto.\n        - apply l9_9_bis in HOS.\n          apply HOS.\n          repeat split; Col.\n          exists M; split; Col.\n        - apply (le__nlt O C O M); Le.\n          apply (cong2_lt__lt O M O P); Cong.\n          apply bet_inc2__incs with A B; Circle; Between.\n      }\n      assert (Perp O M A B) by (apply mid_onc2__perp with P; auto).\n      assert (HOS1 : OS A B C H).\n      { apply l12_6, par_not_col_strict with C; Col.\n        apply l12_9 with O M; Perp; [|Cop| |Cop].\n          apply coplanar_perm_5, col_cop__cop with B; Col; Cop.\n          apply coplanar_perm_5, col_cop__cop with A; Col; Cop.\n      }\n      assert (M <> H) by (intro; subst; apply one_side_not_col124 in HOS1; apply HOS1; Col).\n      assert (Per M H C) by (apply perp_per_1, perp_left_comm, perp_col with O; Col).\n      apply lt_transitivity with H C; [|assert_diffs; apply l11_46; auto].\n      apply cong_lt_per2__lt_1 with O O; Cong.\n        apply l8_2, per_col with M; Col; Perp.\n        apply perp_per_1, perp_left_comm, perp_col1 with B; Col.\n      apply bet__lt1213; auto; apply out2__bet.\n        apply (acute_col_perp__out C); [apply acute_sym|..]; Col; Perp.\n        apply (l9_19 A B); Col; apply one_side_transitivity with C; assumption.\n    - apply lt_transitivity with O C; [|apply l11_46; auto].\n      apply (cong2_lt__lt M A O A); Cong.\n      apply l11_46; auto.\n      left.\n      apply mid_onc2__per with P B; auto.\n  }\n  destruct HLt as [[C' [HBet HCong]] HNCong].\n  exists A, C', B; split.\n    apply thales_theorem with M; trivial; intro; apply HNCol; ColR.\n  assert_diffs.\n  assert (C <> C') by (intro; subst; apply HNCong, HCong).\n  apply os3__lta.\n  - apply one_side_transitivity with M.\n      apply invert_one_side, out_one_side; [Col|apply l6_6, bet_out; Between].\n      apply out_one_side; [left; intro; apply HNCol; ColR|apply l6_6, bet_out; Between].\n  - apply out_one_side_1 with M; Col; apply l6_6, bet_out; auto.\n  - apply one_side_transitivity with M.\n      apply invert_one_side, out_one_side; [Col|apply l6_6, bet_out; Between].\n      apply out_one_side; [left; intro; apply HNCol; ColR|apply l6_6, bet_out; Between].\nQed.\n\nLemma inscribed_angle_aux : forall O P A B C,\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P ->\n  OS A B O C -> TS O C A B ->\n  gHalfA A C B A O B.\nProof.\n  intros O P A B C HA HB HC HOS HTS.\n  destruct (segment_construction C O O P) as [C' []].\n  assert_diffs.\n  assert (O <> C') by (intro; treat_equalities; auto).\n  assert (HCong := (onc2__cong O P)).\n  apply suma_preserves_ghalfa with A C C' C' C B A O C' C' O B.\n    apply (onc3_os__acute O P); assumption.\n    apply ts__suma, invert_two_sides, col_two_sides with O; Side; Col.\n    apply ts__suma, invert_two_sides, col_two_sides with C; Col.\n    apply ghalfa_out4__ghalfa with A O A C'; try apply out_trivial; auto;\n      [apply l6_6, bet_out|apply ghalfa_left_comm, bet_cong__ghalfa]; auto.\n    apply ghalfa_out4__ghalfa with O B C' B; try apply out_trivial; auto;\n      [apply l6_6, bet_out|apply ghalfa_right_comm, bet_cong__ghalfa]; auto.\nQed.\n\nLemma inscribed_angle_aux1 : forall O P A B C,\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P ->\n  OS A B O C -> OS O C A B ->\n  gHalfA A C B A O B.\nProof.\n  assert (Haux : forall O P A B C, OnCircle A O P -> OnCircle B O P -> OnCircle C O P ->\n  OS A B O C -> OS O C A B -> OS O B A C -> gHalfA A C B A O B).\n  { intros O P A B C HA HB HC HOS1 HOS2 HOS3.\n    destruct (chord_completion O P C O) as [C' [HC' HBet ]]; Circle.\n    assert_diffs.\n    assert (C' <> O) by (intro; treat_equalities; auto).\n    assert (TS O B A C').\n    { apply l9_8_2 with C; [|Side].\n      apply one_side_not_col124 in HOS3.\n      repeat split.\n        Col.\n        intro; apply HOS3; ColR.\n      exists O; split; Col.\n    }\n    assert (HCong := (onc2__cong O P)).\n    apply acute_ghalfa2_sams_suma2__ghalfa123 with B C O A C O B O C' A O C'.\n    - repeat split; auto.\n        right; intro; assert_cols; assert_ncols; Col.\n      exists C'.\n      split; CongA.\n      repeat split; [Side| |Cop].\n      apply l9_9_bis, invert_one_side, one_side_symmetry, os_ts1324__os; [|Side].\n      apply col_one_side with C; Col; Side.\n    - apply (onc3_os__acute O P); assumption.\n    - exists O.\n      repeat (split; CongA); [|Cop].\n      apply l9_9, invert_two_sides, l9_31; Side.\n    - exists C'.\n      repeat (split; CongA); [Side|Cop].\n    - apply ghalfa_left_comm, bet_cong__ghalfa; auto.\n    - apply ghalfa_left_comm, bet_cong__ghalfa; auto.\n  }\n  intros O P A B C HA HB HC HOS1 HOS2.\n  assert_ncols.\n  destruct (cop__one_or_two_sides O B A C) as [HTS|]; Col; Cop.\n    apply ghalfa_comm, Haux with P; auto; [..|apply one_side_symmetry, os_ts1324__os]; Side.\n    apply Haux with P; assumption.\nQed.\n\n(** Euclid Book III Prop 20:\n    In a circle the angle at the centre is double of the angle at the circumference,\n    when the angles have the same circumference as base. *)\n\nLemma inscribed_angle : forall O P A B C,\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> OS A B O C ->\n  gHalfA A C B A O B.\nProof.\n  intros O P A B C HA HB HC HOS.\n  assert (HCong := (onc2__cong O P)).\n  destruct (col_dec A O C).\n  { assert_diffs.\n    assert (Bet C O A) by (apply col_inc_onc2__bet with O P; Col; Circle).\n    assert (O <> C) by (intro; treat_equalities; auto).\n    apply ghalfa_right_comm, ghalfa_out4__ghalfa with O B B A; try apply out_trivial; auto.\n      apply l6_6, bet_out; auto.\n    apply bet_cong__ghalfa; auto.\n  }\n  destruct (col_dec B O C).\n  { assert_diffs.\n    assert (Bet C O B) by (apply col_inc_onc2__bet with O P; Col; Circle).\n    assert (O <> C) by (intro; treat_equalities; auto).\n    apply ghalfa_left_comm, ghalfa_out4__ghalfa with O A A B; try apply out_trivial; auto.\n      apply l6_6, bet_out; auto.\n    apply bet_cong__ghalfa; auto.\n  }\n  destruct (cop__one_or_two_sides O C A B); Cop.\n    apply inscribed_angle_aux with P; assumption.\n    apply inscribed_angle_aux1 with P; assumption.\nQed.\n\nLemma diam_onc2_ts__suppa : forall O P A B C C',\n  OnCircle A O P -> OnCircle B O P -> Diam C C' O P -> TS A B C C' ->\n  SuppA A C B A C' B.\nProof.\n  intros O P A B C C' HA HB [HBet [HC HC']] HTS.\n  assert_diffs.\n  assert (HCong := onc2__cong O P).\n  assert (HMid : Midpoint O C C') by (split; Cong).\n  assert (C <> C') by (intro; treat_equalities; auto).\n  assert (HNColA : ~ Col C C' A) by (apply (onc3__ncol O P); auto).\n  assert (HNColB : ~ Col C C' B) by (apply (onc3__ncol O P); auto).\n  assert (HSumaA : SumA A C C' C C' A C A C') by (apply cong_mid__suma with O; auto).\n  assert (HSumaB : SumA B C C' C C' B C B C') by (apply cong_mid__suma with O; auto).\n  assert (Per C A C') by (apply thales_theorem with O; auto).\n  assert (Per C B C') by (apply thales_theorem with O; auto).\n  assert (HSuma : SumA C A C' C B C' C O C') by (assert_diffs; apply bet_per2__suma; auto).\n  apply bet_suma__suppa with C O C'; trivial.\n  destruct (ex_suma C A C' C' C B) as [D [E [F HSuma1]]]; auto.\n  assert (HTS2 : TS C C' A B) by (apply (chord_intersection O P); assumption).\n  assert (HTS3 : TS C' C A B) by (apply invert_two_sides, HTS2).\n  assert (Acute C' C A).\n  { assert_diffs; apply acute_out2__acute with O A.\n      apply l6_6, bet_out; auto.\n      apply out_trivial; auto.\n      apply cong__acute; auto.\n  }\n  assert (Acute C' C B).\n  { assert_diffs; apply acute_out2__acute with O B.\n      apply l6_6, bet_out; auto.\n      apply out_trivial; auto.\n      apply cong__acute; auto.\n  }\n  assert (Acute C C' A).\n  { assert_diffs; apply acute_out2__acute with O A.\n      apply l6_6, bet_out; Between.\n      apply out_trivial; auto.\n      apply cong__acute; auto.\n  }\n  assert (Acute C C' B).\n  { assert_diffs; apply acute_out2__acute with O B.\n      apply l6_6, bet_out; Between.\n      apply out_trivial; auto.\n      apply cong__acute; auto.\n  }\n  assert (HSuma2 : SumA A C B A C' C D E F).\n    apply suma_sym, suma_assoc_1 with A C C' C' C B C A C'; SumA.\n  assert (HSAMS : SAMS A C B A C' C).\n    apply sams_sym, sams_assoc_1 with A C C' C' C B C A C'; SumA.\n  apply suma_assoc_1 with A C' C C C' B D E F; [SumA..|].\n  apply suma_assoc_2 with C A C' B C C' C B C'; SumA.\nQed.\n\n(** In a circle the angle at the centre is double of the angle at the circumference. *)\n\nLemma inscribed_angle_1 : forall O P A B C, A <> B -> B <> C -> A <> C ->\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> Coplanar A B C O ->\n  SumA A C B A C B A O B.\nProof.\n  intros O P A B C HAB HBC HAC HA HB HC HCop.\n  assert (~ Col A B C) by (apply (onc3__ncol O P); auto).\n  destruct (col_dec A B O).\n  { assert (Midpoint O A B) by (apply col_onc2__mid with P; auto).\n    assert (Per A C B) by (apply thales_theorem with O; auto; apply cong_transitivity with O P; Cong).\n    assert_diffs; apply bet_per2__suma; Between.\n  }\n  destruct (cop__one_or_two_sides A B O C); Col; Cop.\n  - destruct (chord_completion O P C O) as [C' []]; Circle.\n    assert (TS A B C' C) by (apply l9_2, bet_ts__ts with O; Side).\n    assert (SuppA A C' B A C B).\n      apply (diam_onc2_ts__suppa O P); [..|repeat split|]; Between.\n    apply (suma_suppa2__suma A C' B A C' B); trivial.\n    apply ghalfa__suma, inscribed_angle with P; trivial.\n    exists C; split; trivial.\n  - apply ghalfa__suma, inscribed_angle with P; trivial.\nQed.\n\n(** If two angles ACB and ADB are inscribed in the same circle,\n    then they are either congruent or supplementary. *)\n\nLemma cop2_onc4__or_conga_suppa : forall O P A B C C',\n  A <> B -> B <> C -> A <> C -> B <> C' -> A <> C' ->\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> OnCircle C' O P ->\n  Coplanar A B C O -> Coplanar A B C' O ->\n  CongA A C B A C' B \\/ SuppA A C B A C' B.\nProof.\n  intros O P A B C C'; intros.\n  apply suma2__or_conga_suppa with A O B; trivial; apply inscribed_angle_1 with P; assumption.\nQed.\n\n(** If the angle ACB is inscribed in a circle of center O and\n    C, O lie on opposite sides of AB, then this angle is obtuse. *)\n\nLemma onc3_ts__obtuse : forall O P A B C,\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> TS A B O C ->\n  Obtuse A C B.\nProof.\n  intros O P A B C HA HB HC HTS.\n  destruct (chord_completion O P C O) as [C' []]; Circle.\n  assert (TS A B C C') by (apply bet_ts__ts with O; Side).\n  apply (acute_suppa__obtuse A C' B).\n    apply (onc3_os__acute O P); trivial; exists C; split; Side.\n  apply (diam_onc2_ts__suppa O P); Side.\n  repeat split; Between.\nQed.\n\n(** Euclid Book III Prop 21:\n    In a circle the angles in the same segment are equal to one another. *)\n\nLemma cop_onc4_os__conga : forall O P A B C C',\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> OnCircle C' O P ->\n  OS A B C C' -> Coplanar A B C O ->\n  CongA A C B A C' B.\nProof.\n  intros O P A B C C' HA HB HC HC' HOS HCop.\n  assert_ncols.\n  destruct (col_dec A B O).\n  { assert_diffs.\n    assert (Midpoint O A B) by (apply col_onc2__mid with P; auto).\n    apply l11_16; auto; apply thales_theorem with O; Col; apply cong_transitivity with O P; Cong.\n  }\n  destruct (cop__one_or_two_sides A B O C); Col; Cop.\n  - assert_diffs; destruct (cop2_onc4__or_conga_suppa O P A B C C') as [|Habs]; auto.\n      apply coplanar_trans_1 with C; Col; Cop.\n    exfalso.\n    apply (nlta A C' B), acute_obtuse__lta.\n      apply (obtuse_suppa__acute A C B); [apply (onc3_ts__obtuse O P)|]; trivial.\n      apply (onc3_ts__obtuse O P); trivial; apply l9_2, l9_8_2 with C; Side.\n  - apply ghalfa2__conga_2 with A O B; apply inscribed_angle with P; trivial.\n    apply one_side_transitivity with C; Side.\nQed.\n\n(** Euclid Book III Prop 22:\n    The opposite angles of quadrilaterals in circles are equal to two right angles. *)\n\nLemma cop_onc4_ts__suppa : forall O P A B C C',\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> OnCircle C' O P ->\n  TS A B C C' -> Coplanar A B C O ->\n  SuppA A C B A C' B.\nProof.\n  intros O P A B C C' HA HB.\n  revert C C'.\n  assert (Haux : forall C C', OnCircle C O P -> OnCircle C' O P -> TS A B C C' -> OS A B O C ->\n    SuppA A C B A C' B).\n  { intros C C' HC HC' HTS HOS.\n    assert_diffs.\n    assert (~ Col C A B) by (destruct HTS; assumption).\n    assert (Coplanar A B C' O) by (apply coplanar_trans_1 with C; Cop).\n    destruct (cop2_onc4__or_conga_suppa O P A B C C') as [Habs|]; Cop.\n    exfalso.\n    assert (HLta : LtA A C B A C' B); [|destruct HLta as [_ HN]; apply HN, Habs].\n    apply acute_obtuse__lta.\n      apply (onc3_os__acute O P); assumption.\n    apply (onc3_ts__obtuse O P); trivial.\n    apply l9_8_2 with C; Side.\n  }\n  intros C C' HC HC' HTS HCop.\n  assert (~ Col C A B) by (destruct HTS; assumption).\n  destruct (col_dec A B O).\n  { assert_diffs.\n    assert (Midpoint O A B) by (apply col_onc2__mid with P; auto).\n    destruct HTS as [_ []].\n    apply per2__suppa; auto; apply thales_theorem with O; Col; apply cong_transitivity with O P; Cong.\n  }\n  destruct (cop__one_or_two_sides A B O C); Col; Cop.\n  apply suppa_sym, Haux; [..|exists C; split]; Side.\nQed.\n\n(** If the angle ACB is acute and inscribed in a circle of center O,\n    then C and O lie on the same side of AB. *)\n\nLemma acute_cop_onc3__os : forall O P A B C, A <> B ->\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> Coplanar A B C O -> Acute A C B ->\n  OS A B O C.\nProof.\n  intros O P A B C HAB HA HB HC HCop HAcute.\n  assert_diffs.\n  assert (~ Col A B C) by (apply (onc3__ncol O P); auto).\n  apply coplanar_perm_1 in HCop.\n  apply cop__not_two_sides_one_side; Col; intro Habs; apply (nlta A C B).\n  - apply acute_per__lta; auto.\n    apply thales_theorem with O; trivial.\n      apply col_onc2__mid with P; Col.\n      apply (onc2__cong O P); assumption.\n  - apply acute_obtuse__lta; trivial.\n    apply (onc3_ts__obtuse O P); assumption.\nQed.\n\n(** If the angle ACB is obtuse and inscribed in a circle of center O,\n    then C and O lie on opposite sides of AB. *)\n\nLemma cop_obtuse_onc3__ts : forall O P A B C,\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> Coplanar A B C O -> Obtuse A C B ->\n  TS A B O C.\nProof.\n  intros O P A B C HA HB HC HCop HObtuse.\n  assert_diffs.\n  assert (~ Col A B C) by (apply (onc3__ncol O P); auto).\n  apply coplanar_perm_1 in HCop.\n  apply cop__not_one_side_two_sides; Col; intro Habs; apply (nlta A C B).\n  - apply obtuse_per__lta; auto.\n    apply thales_theorem with O; trivial.\n      apply col_onc2__mid with P; Col.\n      apply (onc2__cong O P); assumption.\n  - apply acute_obtuse__lta; trivial.\n    apply (onc3_os__acute O P); assumption.\nQed.\n\n(** If the angles ACB and ADB are congruent and inscribed in the same circle,\n    then C and D lie on the same side of AB. *)\n\nLemma conga_cop2_onc4__os : forall O P A B C D, ~ Col A B O ->\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> OnCircle D O P ->\n  Coplanar A B O C -> Coplanar A B O D -> CongA A C B A D B ->\n  OS A B C D.\nProof.\n  intros O P A B C D HNCol HA HB HC HD HCopC HCopD HConga.\n  assert_diffs.\n  destruct (angle_partition A C B) as [HAcute|[HPer|HObtuse]]; auto.\n  - apply one_side_transitivity with O; [apply one_side_symmetry|];\n      apply acute_cop_onc3__os with P; Cop.\n    apply (acute_conga__acute A C B); assumption.\n  - exfalso.\n    apply HNCol, col_permutation_1, midpoint_col.\n    destruct (midpoint_existence A B) as [M HM].\n    assert (M = O); [|subst; apply HM].\n    assert (HCong := onc2__cong O P).\n    apply (cong4_cop2__eq A C B); Cong; [..|Cop|Cop].\n      apply per_not_col; auto.\n      apply cong_commutativity, thales_converse_theorem with B; auto.\n  - exists O; split; apply l9_2; apply cop_obtuse_onc3__ts with P; Cop.\n    apply (conga_obtuse__obtuse A C B); assumption.\nQed.\n\n(** If the angles ACB and ADB are supplementary and inscribed in the same circle,\n    then C and D lie on opposite sides of AB. *)\n\nLemma cop2_onc4_suppa__ts : forall O P A B C D, ~ Col A B O ->\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> OnCircle D O P ->\n  Coplanar A B O C -> Coplanar A B O D -> SuppA A C B A D B ->\n  TS A B C D.\nProof.\n  intros O P A B C D HNCol HA HB HC HD HCopC HCopD HSuppa.\n  assert_diffs.\n  destruct (angle_partition A C B) as [HAcute|[HPer|HObtuse]]; auto.\n  - apply l9_8_2 with O.\n      apply cop_obtuse_onc3__ts with P; Cop; apply (acute_suppa__obtuse A C B); assumption.\n      apply acute_cop_onc3__os with P; Cop.\n  - exfalso.\n    apply HNCol, col_permutation_1, midpoint_col.\n    destruct (midpoint_existence A B) as [M HM].\n    assert (M = O); [|subst; apply HM].\n    assert (HCong := onc2__cong O P).\n    apply (cong4_cop2__eq A C B); Cong; [..|Cop|Cop].\n      apply per_not_col; auto.\n      apply cong_commutativity, thales_converse_theorem with B; auto.\n  - apply l9_2, l9_8_2 with O.\n      apply cop_obtuse_onc3__ts with P; Cop.\n    apply acute_cop_onc3__os with P; Cop; apply (obtuse_suppa__acute A C B); assumption.\nQed.\n\n(** Non degenerated triangles can be circumscribed. *)\n\nLemma triangle_circumscription : forall A B C, ~ Col A B C ->\n  exists CC : Tpoint, Cong A CC B CC /\\ Cong A CC C CC /\\ Coplanar A B C CC.\nProof.\n  apply postulates_in_euclidean_context; simpl; repeat (try (left; reflexivity); right).\nQed.\n\n(** Euclid Book III Prop 23:\n    On the same straight line there cannot be constructed\n    two similar and unequal segments of circles on the same side. *)\n\nLemma conga_cop_onc6_os__eq : forall A B C D O P O' P',\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> Coplanar A B C O ->\n  OnCircle A O' P' -> OnCircle B O' P' -> OnCircle D O' P' -> Coplanar A B D O' ->\n  OS A B C D -> CongA A C B A D B ->\n  (O = O' /\\ Cong O P O' P').\nProof.\n  intros A B C D O P O' P' HA HB HC HCop HA' HB' HD' HCop' HOS HConga.\n  assert (O = O'); [|split; trivial; subst O'; apply cong_transitivity with O A; Cong].\n  assert (HNCol : ~ Col A B C) by (apply one_side_not_col123 with D, HOS).\n  assert (HCong := onc2__cong O P).\n  destruct (col_dec A B O) as [|HNCol1].\n  { assert_diffs.\n    apply cong2_cop2_onc3__eq with P' A B D; auto; [|apply coplanar_trans_1 with C; Col; Cop].\n    assert (Midpoint O A B) by (apply col_onc2__mid with P; assumption).\n    apply thales_converse_theorem with B; auto.\n    apply (l11_17 A C B); trivial.\n    apply thales_theorem with O; Cong.\n  }\n  assert (HNCol' : ~ Col A B D) by (apply one_side_not_col124 with C, HOS).\n  assert (HCong' := onc2__cong O' P').\n  destruct (midpoint_existence A B) as [M HM].\n  assert (HOS1 : OS A B O O').\n  { assert_diffs; destruct (angle_partition A C B) as [HAcute|[HPer|HObtuse]]; auto.\n    - apply one_side_transitivity with C;\n        [|apply one_side_transitivity with D; trivial; apply one_side_symmetry].\n        apply acute_cop_onc3__os with P; auto.\n      apply acute_cop_onc3__os with P'; auto.\n      apply (acute_conga__acute A C B); assumption.\n    - exfalso.\n      apply HNCol1.\n      assert (O = M); [|subst; Col].\n      apply (cong4_cop2__eq A B C); Cong; [|Cop].\n      apply cong_commutativity, thales_converse_theorem with B; auto.\n    - exists C; split; [|apply l9_2, l9_8_2 with D; [apply l9_2|Side]].\n        apply cop_obtuse_onc3__ts with P; auto.\n      apply cop_obtuse_onc3__ts with P'; auto.\n      apply (conga_obtuse__obtuse A C B); assumption.\n  }\n  assert (HNCol1' : ~ Col A B O') by (apply one_side_not_col124 with O, HOS1).\n  destruct (bet_cop_onc2__ex_onc_os_out O P A B C M) as [C1]; Between; Col; [assert_diffs; auto..|].\n  destruct (bet_cop_onc2__ex_onc_os_out O' P' A B D M) as [D1]; Between; Col; [assert_diffs; auto..|].\n  spliter.\n  assert (HNCol2 : ~ Col A B C1) by (apply one_side_not_col124 with C; assumption).\n  assert (HOut : Out M C1 D1).\n  { apply (l9_19 A B); [Col| |\n      apply one_side_transitivity with C; [|apply one_side_transitivity with D]; Side].\n    assert (O <> M) by (intro; subst; apply HNCol1; Col).\n    assert (O' <> M) by (intro; subst; apply HNCol1'; Col).\n    assert (Col O O' M); [|ColR].\n    assert_diffs; apply (cop_per2__col A); auto;\n      [|apply mid_onc2__per with P B; auto|apply mid_onc2__per with P' B; auto].\n    apply coplanar_trans_1 with B; Col; [|Cop].\n    apply coplanar_trans_1 with C; Col; [Cop|].\n    apply coplanar_perm_12, coplanar_trans_1 with D; Col; Cop.\n  }\n  destruct (eq_dec_points C1 D1).\n  { subst D1.\n    apply (cong4_cop2__eq A B C1); Cong; exists M; left; split; Col.\n  }\n  assert (HNCol2' : ~ Col A B D1) by (apply one_side_not_col124 with D; assumption).\n  assert (CongA A C1 B A C B) by (apply (cop_onc4_os__conga O P); Side; exists M; left; split; Col).\n  assert (CongA A D1 B A D B) by (apply (cop_onc4_os__conga O' P'); Side; exists M; left; split; Col).\n  assert (Out A B M) by (assert_diffs; apply l6_6, bet_out; Between).\n  assert (Out B A M) by (assert_diffs; apply l6_6, bet_out; Between).\n  assert (HH := HOut).\n  destruct HH as [HMC1 [HMD1 [HBet|HBet]]]; exfalso.\n  - apply (lta_not_conga A D B A C B); CongA.\n    apply (conga_preserves_lta A D1 B A C1 B); trivial.\n    assert (Out D1 M C1) by (apply l6_6, bet_out; Between).\n    apply os3__lta; [|apply one_side_symmetry, l9_19 with M; Col|];\n      apply one_side_transitivity with M.\n      apply invert_one_side, out_one_side; Col.\n      apply out_one_side; trivial; left; intro; apply HNCol2'; ColR.\n      apply invert_one_side, out_one_side; Col.\n      apply out_one_side; trivial; left; intro; apply HNCol2'; ColR.\n  - apply (lta_not_conga A C B A D B); trivial.\n    apply (conga_preserves_lta A C1 B A D1 B); trivial.\n    assert (Out C1 M D1) by (apply l6_6, bet_out; Between).\n    apply os3__lta; [|apply l9_19 with M; Col|];\n      apply one_side_transitivity with M.\n      apply invert_one_side, out_one_side; Col.\n      apply out_one_side; trivial; left; intro; apply HNCol2; ColR.\n      apply invert_one_side, out_one_side; Col.\n      apply out_one_side; trivial; left; intro; apply HNCol2; ColR.\nQed.\n\nLemma conga_cop_onc3_os__onc : forall A B C D O P,\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P ->\n  Coplanar A B C O -> OS A B C D -> CongA A C B A D B ->\n  OnCircle D O P.\nProof.\n  intros A B C D O P HA HB HC HCop HOS HConga.\n  destruct (triangle_circumscription A B D) as [O'].\n    apply one_side_not_col124 in HOS; Col.\n  spliter.\n  assert (OnCircle A O' A /\\ OnCircle B O' A /\\ OnCircle D O' A).\n    unfold OnCircle; repeat split; Cong.\n  spliter.\n  destruct (conga_cop_onc6_os__eq A B C D O P O' A); trivial.\n  subst O'; apply cong_transitivity with O A; Cong.\nQed.\n\n(** If the angles ACB and ADB are congruent and C, D lie on the same side of AB,\n    then A, B, C and D are concyclic. *)\n\nLemma conga_os__ex_circle : forall A B C D,\n  OS A B C D -> CongA A C B A D B -> exists O P,\n  OnCircle A O P /\\ OnCircle B O P /\\ OnCircle C O P /\\ OnCircle D O P /\\ Coplanar A B C O.\nProof.\n  intros A B C D HOS HConga.\n  destruct (triangle_circumscription A B C) as [O]; spliter.\n    apply one_side_not_col123 with D, HOS.\n  assert (OnCircle A O A /\\ OnCircle B O A /\\ OnCircle C O A).\n    unfold OnCircle; repeat split; Cong.\n  spliter.\n  exists O, A; repeat split; trivial.\n  apply (conga_cop_onc3_os__onc A B C); assumption.\nQed.\n\n(** If the angles ACB and ADB are supplementary and C, D lie on opposite sides of AB,\n    then A, B, C and D are concyclic. *)\n\nLemma suppa_ts__ex_circle : forall A B C D,\n  TS A B C D -> SuppA A C B A D B -> exists O P,\n  OnCircle A O P /\\ OnCircle B O P /\\ OnCircle C O P /\\ OnCircle D O P /\\ Coplanar A B C O.\nProof.\n  intros A B.\n  assert (Haux : forall C D, TS A B C D -> Obtuse A C B -> SuppA A C B A D B -> exists O P,\n    OnCircle A O P /\\ OnCircle B O P /\\ OnCircle C O P /\\ OnCircle D O P /\\ Coplanar A B C O).\n  { intros C D HTS HObtuse HSuppa.\n    assert (HNCol : ~ Col A B C) by (destruct HTS; Col).\n    destruct (triangle_circumscription A B C HNCol) as [O]; spliter.\n    assert (OnCircle A O A /\\ OnCircle B O A /\\ OnCircle C O A).\n      unfold OnCircle; repeat split; Cong.\n    spliter.\n    exists O, A; repeat split; trivial.\n    destruct (chord_completion O A C O) as [C'[HC' HBet]]; Circle.\n    assert (TS A B C C').\n      apply bet_ts__ts with O; [apply l9_2, cop_obtuse_onc3__ts with A|]; assumption.\n    apply (conga_cop_onc3_os__onc A B C'); trivial.\n      apply coplanar_trans_1 with C; Col; Cop.\n      exists C; split; Side.\n      apply (suppa2__conga456 A C B); [apply (cop_onc4_ts__suppa O A)|]; assumption.\n  }\n  intros C D HTS HSuppa.\n  assert_diffs; destruct (angle_partition A C B) as [|[|]]; auto.\n  { destruct (Haux D C) as [O [P]].\n      Side.\n      apply (acute_suppa__obtuse A C B); trivial.\n      apply suppa_sym, HSuppa.\n    exists O, P.\n    spliter; repeat split; trivial.\n    apply coplanar_trans_1 with D; [destruct HTS as [_ []]; Col|Cop..].\n  }\n  destruct (midpoint_existence A B) as [M].\n  exists M, A.\n  destruct HTS as [HNCol1 [HNCol2 _]].\n  unfold OnCircle; repeat split; [Cong..| | |Cop];\n    apply cong_symmetry, thales_converse_theorem with B; auto.\n  apply (per_suppa__per A C B); assumption.\nQed.\n\n(** In a convex quadrilateral, if two opposite angles are supplementary\n    then the two other angles are also supplementary. *)\n\nLemma suppa_ts2__suppa : forall A B C D,\n  TS A C B D -> TS B D A C -> SuppA A B C A D C -> SuppA B A D B C D.\nProof.\n  intros A B C D HTS1 HTS2 HSuppa.\n  destruct (suppa_ts__ex_circle A C B D) as [O [P]]; trivial.\n  spliter.\n  apply (cop_onc4_ts__suppa O P); trivial.\n  apply coplanar_perm_2, coplanar_trans_1 with C; [destruct HTS1; Col|Cop..].\nQed.\n\nEnd Inscribed_angle.\n\nSection Inscribed_angle_2.\n\nContext `{T2D:Tarski_2D}.\nContext `{TE:@Tarski_euclidean Tn TnEQD}.\n\nLemma chord_par_diam : forall O P A B C C' A' U,\n O <> P -> ~Col A B C' -> Diam C C' O P -> Midpoint A' A C' -> OnCircle A O P -> OnCircle B O P ->\n Col A B U -> Perp O U A B -> Par A C' O U -> B = C.\nProof.\nintros.\nassert_diffs.\nassert(Midpoint U A B).\n{\n  apply(col_onc2_perp__mid O P A B U); Col.\n}\nassert(O <> A').\nintro.\ntreat_equalities.\ninduction H7.\napply H7.\nexists O.\nsplit; Col.\nspliter.\nassert(Perp A U  O U).\n{\n  apply perp_sym in H6.\n  apply (perp_col A B O U U); Col.\n  intro.\n  treat_equalities.\n  apply perp_distinct in H6.\n  tauto.\n}\napply perp_left_comm in H18.\napply perp_not_col in H18.\napply H18; Col.\nunfold Diam in H1.\nspliter.\nassert(HH:=mid_onc2__perp O P A C' A' H15 H13 H3 H17 H2).\nassert(Perp O U O A').\n{\n  apply(par_perp__perp A C' O U O A' H7); Perp.\n}\n\nassert(Par O A' A B).\n{\n  apply (l12_9_2D _ _ _ _ O U); Perp.\n}\nassert(HM:=midpoint_existence B C').\nex_and HM O'.\nassert(HP:= triangle_mid_par A B C' O' A' H0 H20 H2).\napply par_strict_par in HP.\nassert(Par O A' A' O').\n{\n  apply (par_trans _ _ A B); Par.\n}\nassert(Col O O' A').\n{\n  induction H21.\n  apply False_ind.\n  apply H21.\n  exists A'.\n  split; Col.\n  spliter.\n  Col.\n}\n\ninduction(eq_dec_points O O').\ntreat_equalities.\neapply(symmetric_point_uniqueness C' O); Midpoint.\nsplit; eCong.\nBetween.\n\nassert(HQ:= mid_onc2__perp O P B C' O' H23  H10 H4 H17 H20).\napply(perp_col O A' A C' O') in HH; Col.\nassert(Par A C' B C').\n{\n  apply(l12_9_2D A C' B C' O O'); Perp.\n}\napply False_ind.\ninduction H24.\napply H24.\nexists C'.\nsplit;Col.\nspliter.\napply H0.\nCol.\nQed.\n\nEnd Inscribed_angle_2.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/GeoCoq/Tarski_dev/Annexes/inscribed_angle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.696739336879711}}
{"text": "(* -*- coding: utf-8 -*- *)\n(*************************************************************************\n\n   PROJET RNRT Calife - 2001\n   Author: Pierre Crégut - France Télécom R&D\n   Licence du projet : LGPL version 2.1\n\n *************************************************************************)\n\nRequire Import List Bool Sumbool EqNat Setoid Ring_theory Decidable ZArith_base.\nDelimit Scope Int_scope with I.\n\n(** * Abstract Integers. *)\n\nModule Type Int.\n\n  Parameter t : Set.\n\n  Bind Scope Int_scope with t.\n\n  Parameter Inline zero : t.\n  Parameter Inline one : t.\n  Parameter Inline plus : t -> t -> t.\n  Parameter Inline opp : t -> t.\n  Parameter Inline minus : t -> t -> t.\n  Parameter Inline mult : t -> t -> t.\n\n  Notation \"0\" := zero : Int_scope.\n  Notation \"1\" := one : Int_scope.\n  Infix \"+\" := plus : Int_scope.\n  Infix \"-\" := minus : Int_scope.\n  Infix \"*\" := mult : Int_scope.\n  Notation \"- x\" := (opp x) : Int_scope.\n\n  Open Scope Int_scope.\n\n  (** First, Int is a ring: *)\n  Axiom ring : @ring_theory t 0 1 plus mult minus opp (@eq t).\n\n  (** Int should also be ordered: *)\n\n  Parameter Inline le : t -> t -> Prop.\n  Parameter Inline lt : t -> t -> Prop.\n  Parameter Inline ge : t -> t -> Prop.\n  Parameter Inline gt : t -> t -> Prop.\n  Notation \"x <= y\" := (le x y): Int_scope.\n  Notation \"x < y\" := (lt x y) : Int_scope.\n  Notation \"x >= y\" := (ge x y) : Int_scope.\n  Notation \"x > y\" := (gt x y): Int_scope.\n  Axiom le_lt_iff : forall i j, (i<=j) <-> ~(j<i).\n  Axiom ge_le_iff : forall i j, (i>=j) <-> (j<=i).\n  Axiom gt_lt_iff : forall i j, (i>j) <-> (j<i).\n\n  (** Basic properties of this order *)\n  Axiom lt_trans : forall i j k, i<j -> j<k -> i<k.\n  Axiom lt_not_eq : forall i j, i<j -> i<>j.\n\n  (** Compatibilities *)\n  Axiom lt_0_1 : 0<1.\n  Axiom plus_le_compat : forall i j k l, i<=j -> k<=l -> i+k<=j+l.\n  Axiom opp_le_compat : forall i j, i<=j -> (-j)<=(-i).\n  Axiom mult_lt_compat_l :\n   forall i j k, 0 < k -> i < j -> k*i<k*j.\n\n  (** We should have a way to decide the equality and the order*)\n  Parameter compare : t -> t -> comparison.\n  Infix \"?=\" := compare (at level 70, no associativity) : Int_scope.\n  Axiom compare_Eq : forall i j, compare i j = Eq <-> i=j.\n  Axiom compare_Lt : forall i j, compare i j = Lt <-> i<j.\n  Axiom compare_Gt : forall i j, compare i j = Gt <-> i>j.\n\n  (** Up to here, these requirements could be fulfilled\n     by any totally ordered ring. Let's now be int-specific: *)\n  Axiom le_lt_int : forall x y, x<y <-> x<=y+-(1).\n\n  (** Btw, lt_0_1 could be deduced from this last axiom *)\n\n  (** Now we also require a division function.\n      It is deliberately underspecified, since that's enough\n      for the proofs below. But the most appropriate variant\n      (and the one needed to stay in sync with the omega engine)\n      is \"Floor\" (the historical version of Coq's [Z.div]). *)\n\n  Parameter diveucl : t -> t -> t * t.\n  Notation \"i / j\" := (fst (diveucl i j)).\n  Notation \"i 'mod' j\" := (snd (diveucl i j)).\n  Axiom diveucl_spec :\n    forall i j, j<>0 -> i = j * (i/j) + (i mod j).\n\nEnd Int.\n\n\n\n(** Of course, Z is a model for our abstract int *)\n\nModule Z_as_Int <: Int.\n\n  Open Scope Z_scope.\n\n  Definition t := Z.\n  Definition zero := 0.\n  Definition one := 1.\n  Definition plus := Z.add.\n  Definition opp := Z.opp.\n  Definition minus := Z.sub.\n  Definition mult := Z.mul.\n\n  Lemma ring : @ring_theory t zero one plus mult minus opp (@eq t).\n  Proof.\n  constructor.\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_comm.\n  exact Z.mul_assoc.\n  exact Z.mul_add_distr_r.\n  unfold minus, Z.sub; auto.\n  exact Z.add_opp_diag_r.\n  Qed.\n\n  Definition le := Z.le.\n  Definition lt := Z.lt.\n  Definition ge := Z.ge.\n  Definition gt := Z.gt.\n  Definition le_lt_iff := Z.le_ngt.\n  Definition ge_le_iff := Z.ge_le_iff.\n  Definition gt_lt_iff := Z.gt_lt_iff.\n\n  Definition lt_trans := Z.lt_trans.\n  Definition lt_not_eq := Z.lt_neq.\n\n  Definition lt_0_1 := Z.lt_0_1.\n  Definition plus_le_compat := Z.add_le_mono.\n  Definition mult_lt_compat_l := Zmult_lt_compat_l.\n  Lemma opp_le_compat i j : i<=j -> (-j)<=(-i).\n  Proof. apply -> Z.opp_le_mono. Qed.\n\n  Definition compare := Z.compare.\n  Definition compare_Eq := Z.compare_eq_iff.\n  Lemma compare_Lt i j : compare i j = Lt <-> i<j.\n  Proof. reflexivity. Qed.\n  Lemma compare_Gt i j : compare i j = Gt <-> i>j.\n  Proof. reflexivity. Qed.\n\n  Definition le_lt_int := Z.lt_le_pred.\n\n  Definition diveucl := Z.div_eucl.\n  Definition diveucl_spec := Z.div_mod.\n\nEnd Z_as_Int.\n\n\n(** * Properties of abstract integers *)\n\nModule IntProperties (I:Int).\n Import I.\n Local Notation int := I.t.\n\n (** Primo, some consequences of being a ring theory... *)\n\n Definition two := 1+1.\n Notation \"2\" := two : Int_scope.\n\n (** Aliases for properties packed in the ring record. *)\n\n Definition plus_assoc := ring.(Radd_assoc).\n Definition plus_comm := ring.(Radd_comm).\n Definition plus_0_l := ring.(Radd_0_l).\n Definition mult_assoc := ring.(Rmul_assoc).\n Definition mult_comm := ring.(Rmul_comm).\n Definition mult_1_l := ring.(Rmul_1_l).\n Definition mult_plus_distr_r := ring.(Rdistr_l).\n Definition opp_def := ring.(Ropp_def).\n Definition minus_def := ring.(Rsub_def).\n\n Opaque plus_assoc plus_comm plus_0_l mult_assoc mult_comm mult_1_l\n  mult_plus_distr_r opp_def minus_def.\n\n (** More facts about [plus] *)\n\n Lemma plus_0_r : forall x, x+0 = x.\n Proof. intros; rewrite plus_comm; apply plus_0_l. Qed.\n\n Lemma plus_permute : forall x y z, x+(y+z) = y+(x+z).\n Proof. intros; do 2 rewrite plus_assoc; f_equal; apply plus_comm. Qed.\n\n Lemma plus_reg_l : forall x y z, x+y = x+z -> y = z.\n Proof.\n  intros.\n  rewrite <- (plus_0_r y), <- (plus_0_r z), <-(opp_def x).\n  now rewrite plus_permute, plus_assoc, H, <- plus_assoc, plus_permute.\n Qed.\n\n (** More facts about [mult] *)\n\n Lemma mult_plus_distr_l : forall x y z, x*(y+z)=x*y+x*z.\n Proof.\n  intros.\n  rewrite (mult_comm x (y+z)), (mult_comm x y), (mult_comm x z).\n  apply mult_plus_distr_r.\n Qed.\n\n Lemma mult_0_l x : 0*x = 0.\n Proof.\n  assert (H := mult_plus_distr_r 0 1 x).\n  rewrite plus_0_l, mult_1_l, plus_comm in H.\n  apply plus_reg_l with x.\n  now rewrite <- H, plus_0_r.\n Qed.\n\n Lemma mult_0_r x : x*0 = 0.\n Proof.\n   rewrite mult_comm. apply mult_0_l.\n Qed.\n\n Lemma mult_1_r x : x*1 = x.\n Proof.\n   rewrite mult_comm. apply mult_1_l.\n Qed.\n\n (** More facts about [opp] *)\n\n Definition plus_opp_r := opp_def.\n\n Lemma plus_opp_l : forall x, -x + x = 0.\n Proof. intros; now rewrite plus_comm, opp_def. Qed.\n\n Lemma mult_opp_comm : forall x y, - x * y = x * - y.\n Proof.\n  intros.\n  apply plus_reg_l with (x*y).\n  rewrite <- mult_plus_distr_l, <- mult_plus_distr_r.\n  now rewrite opp_def, opp_def, mult_0_l, mult_comm, mult_0_l.\n Qed.\n\n Lemma opp_eq_mult_neg_1 : forall x, -x = x * -(1).\n Proof.\n  intros; now rewrite mult_comm, mult_opp_comm, mult_1_l.\n Qed.\n\n Lemma opp_involutive : forall x, -(-x) = x.\n Proof.\n  intros.\n  apply plus_reg_l with (-x).\n  now rewrite opp_def, plus_comm, opp_def.\n Qed.\n\n Lemma opp_plus_distr : forall x y, -(x+y) = -x + -y.\n Proof.\n  intros.\n  apply plus_reg_l with (x+y).\n  rewrite opp_def.\n  rewrite plus_permute.\n  do 2 rewrite plus_assoc.\n  now rewrite (plus_comm (-x)), opp_def, plus_0_l, opp_def.\n Qed.\n\n Lemma opp_mult_distr_r : forall x y, -(x*y) = x * -y.\n Proof.\n  intros.\n  rewrite <- mult_opp_comm.\n  apply plus_reg_l with (x*y).\n  now rewrite opp_def, <-mult_plus_distr_r, opp_def, mult_0_l.\n Qed.\n\n Lemma egal_left n m : 0 = n+-m <-> n = m.\n Proof.\n  split; intros.\n  - apply plus_reg_l with (-m).\n    rewrite plus_comm, <- H. symmetry. apply plus_opp_l.\n  - symmetry. subst; apply opp_def.\n Qed.\n\n (** Specialized distributivities *)\n\n Hint Rewrite mult_plus_distr_l mult_plus_distr_r mult_assoc : int.\n Hint Rewrite <- plus_assoc : int.\n\n Hint Rewrite plus_0_l plus_0_r mult_0_l mult_0_r mult_1_l mult_1_r : int.\n\n Lemma OMEGA10 v c1 c2 l1 l2 k1 k2 :\n  v * (c1 * k1 + c2 * k2) + (l1 * k1 + l2 * k2) =\n  (v * c1 + l1) * k1 + (v * c2 + l2) * k2.\n Proof.\n  autorewrite with int; f_equal; now rewrite plus_permute.\n Qed.\n\n Lemma OMEGA11 v1 c1 l1 l2 k1 :\n  v1 * (c1 * k1) + (l1 * k1 + l2) = (v1 * c1 + l1) * k1 + l2.\n Proof.\n  now autorewrite with int.\n Qed.\n\n Lemma OMEGA12 v2 c2 l1 l2 k2 :\n   v2 * (c2 * k2) + (l1 + l2 * k2) = l1 + (v2 * c2 + l2) * k2.\n Proof.\n  autorewrite with int; now rewrite plus_permute.\n Qed.\n\n Lemma sum1 a b c d : 0 = a -> 0 = b -> 0 = a * c + b * d.\n Proof.\n intros; subst. now autorewrite with int.\n Qed.\n\n\n (** Secondo, some results about order (and equality) *)\n\n Lemma lt_irrefl : forall n, ~ n<n.\n Proof.\n intros n H.\n elim (lt_not_eq _ _ H); auto.\n Qed.\n\n Lemma lt_antisym : forall n m, n<m -> m<n -> False.\n Proof.\n intros; elim (lt_irrefl _ (lt_trans _ _ _ H H0)); auto.\n Qed.\n\n Lemma lt_le_weak : forall n m, n<m -> n<=m.\n Proof.\n  intros; rewrite le_lt_iff; intro H'; eapply lt_antisym; eauto.\n Qed.\n\n Lemma le_refl : forall n, n<=n.\n Proof.\n intros; rewrite le_lt_iff; apply lt_irrefl; auto.\n Qed.\n\n Lemma le_antisym : forall n m, n<=m -> m<=n -> n=m.\n Proof.\n intros n m; do 2 rewrite le_lt_iff; intros.\n rewrite <- compare_Lt in H0.\n rewrite <- gt_lt_iff, <- compare_Gt in H.\n rewrite <- compare_Eq.\n destruct compare; intuition.\n Qed.\n\n Lemma lt_eq_lt_dec : forall n m, { n<m }+{ n=m }+{ m<n }.\n Proof.\n  intros.\n  generalize (compare_Lt n m)(compare_Eq n m)(compare_Gt n m).\n  destruct compare; [ left; right | left; left | right ]; intuition.\n  rewrite gt_lt_iff in H1; intuition.\n Qed.\n\n Lemma lt_dec : forall n m: int, { n<m } + { ~n<m }.\n Proof.\n  intros.\n  generalize (compare_Lt n m)(compare_Eq n m)(compare_Gt n m).\n  destruct compare; [ right | left | right ]; intuition discriminate.\n Qed.\n\n Lemma lt_le_iff : forall n m, (n<m) <-> ~(m<=n).\n Proof.\n  intros.\n  rewrite le_lt_iff.\n  destruct (lt_dec n m); intuition.\n Qed.\n\n Lemma le_dec : forall n m: int, { n<=m } + { ~n<=m }.\n Proof.\n  intros; destruct (lt_dec m n); [right|left]; rewrite le_lt_iff; intuition.\n Qed.\n\n Lemma le_lt_dec : forall n m, { n<=m } + { m<n }.\n Proof.\n  intros; destruct (le_dec n m); [left|right]; auto; now rewrite lt_le_iff.\n Qed.\n\n\n Definition beq i j := match compare i j with Eq => true | _ => false end.\n\n Infix \"=?\" := beq : Int_scope.\n\n Lemma beq_iff i j : (i =? j) = true <-> i=j.\n Proof.\n unfold beq. rewrite <- (compare_Eq i j). now destruct compare.\n Qed.\n\n Lemma beq_reflect i j : reflect (i=j) (i =? j).\n Proof.\n apply iff_reflect. symmetry. apply beq_iff.\n Qed.\n\n Lemma eq_dec : forall n m:int, { n=m } + { n<>m }.\n Proof.\n  intros n m; generalize (beq_iff n m); destruct beq; [left|right]; intuition.\n Qed.\n\n Definition blt i j := match compare i j with Lt => true | _ => false end.\n\n Infix \"<?\" := blt : Int_scope.\n\n Lemma blt_iff i j : (i <? j) = true <-> i<j.\n Proof.\n unfold blt. rewrite <- (compare_Lt i j). now destruct compare.\n Qed.\n\n Lemma blt_reflect i j : reflect (i<j) (i <? j).\n Proof.\n apply iff_reflect. symmetry. apply blt_iff.\n Qed.\n\n Lemma le_is_lt_or_eq : forall n m, n<=m -> { n<m } + { n=m }.\n Proof.\n  intros n m Hnm.\n  destruct (eq_dec n m) as [H'|H'].\n  - right; intuition.\n  - left; rewrite lt_le_iff.\n    contradict H'.\n    now apply le_antisym.\n Qed.\n\n Lemma le_neq_lt : forall n m, n<=m -> n<>m -> n<m.\n Proof.\n  intros n m H. now destruct (le_is_lt_or_eq _ _ H).\n Qed.\n\n Lemma le_trans : forall n m p, n<=m -> m<=p -> n<=p.\n Proof.\n  intros n m p; rewrite 3 le_lt_iff; intros A B C.\n  destruct (lt_eq_lt_dec p m) as [[H|H]|H]; subst; auto.\n  generalize (lt_trans _ _ _ H C); intuition.\n Qed.\n\n Lemma not_eq (a b:int) : ~ a <> b <-> a = b.\n Proof.\n  destruct (eq_dec a b); intuition.\n Qed.\n\n (** Order and operations *)\n\n Lemma le_0_neg n : n <= 0 <-> 0 <= -n.\n Proof.\n rewrite <- (mult_0_l (-(1))) at 2.\n rewrite <- opp_eq_mult_neg_1.\n split; intros.\n - now apply opp_le_compat.\n - rewrite <-(opp_involutive 0), <-(opp_involutive n).\n   now apply opp_le_compat.\n Qed.\n\n Lemma plus_le_reg_r : forall n m p, n + p <= m + p -> n <= m.\n Proof.\n intros.\n replace n with ((n+p)+-p).\n replace m with ((m+p)+-p).\n apply plus_le_compat; auto.\n apply le_refl.\n now rewrite <- plus_assoc, opp_def, plus_0_r.\n now rewrite <- plus_assoc, opp_def, plus_0_r.\n Qed.\n\n Lemma plus_le_lt_compat : forall n m p q, n<=m -> p<q -> n+p<m+q.\n Proof.\n intros.\n apply le_neq_lt.\n apply plus_le_compat; auto.\n apply lt_le_weak; auto.\n rewrite lt_le_iff in H0.\n contradict H0.\n apply plus_le_reg_r with m.\n rewrite (plus_comm q m), <-H0, (plus_comm p m).\n apply plus_le_compat; auto.\n apply le_refl; auto.\n Qed.\n\n Lemma plus_lt_compat : forall n m p q, n<m -> p<q -> n+p<m+q.\n Proof.\n intros.\n apply plus_le_lt_compat; auto.\n apply lt_le_weak; auto.\n Qed.\n\n Lemma opp_lt_compat : forall n m, n<m -> -m < -n.\n Proof.\n intros n m; do 2 rewrite lt_le_iff; intros H; contradict H.\n rewrite <-(opp_involutive m), <-(opp_involutive n).\n apply opp_le_compat; auto.\n Qed.\n\n Lemma lt_0_neg n : n < 0 <-> 0 < -n.\n Proof.\n rewrite <- (mult_0_l (-(1))) at 2.\n rewrite <- opp_eq_mult_neg_1.\n split; intros.\n - now apply opp_lt_compat.\n - rewrite <-(opp_involutive 0), <-(opp_involutive n).\n   now apply opp_lt_compat.\n Qed.\n\n Lemma mult_lt_0_compat : forall n m, 0 < n -> 0 < m -> 0 < n*m.\n Proof.\n intros.\n rewrite <- (mult_0_l n), mult_comm.\n apply mult_lt_compat_l; auto.\n Qed.\n\n Lemma mult_integral_r n m : 0 < n -> n * m = 0 -> m = 0.\n Proof.\n intros Hn H.\n destruct (lt_eq_lt_dec 0 m) as [[Hm| <- ]|Hm]; auto; exfalso.\n - generalize (mult_lt_0_compat _ _ Hn Hm).\n   rewrite H.\n   exact (lt_irrefl 0).\n - rewrite lt_0_neg in Hm.\n   generalize (mult_lt_0_compat _ _ Hn Hm).\n   rewrite <- opp_mult_distr_r, opp_eq_mult_neg_1, H, mult_0_l.\n   exact (lt_irrefl 0).\n Qed.\n\n Lemma mult_integral n m : n * m = 0 -> n = 0 \\/ m = 0.\n Proof.\n intros H.\n destruct (lt_eq_lt_dec 0 n) as [[Hn|Hn]|Hn].\n - right; apply (mult_integral_r n m); trivial.\n - now left.\n - right; apply (mult_integral_r (-n) m).\n   + now apply lt_0_neg.\n   + rewrite mult_comm, <- opp_mult_distr_r, mult_comm, H.\n     now rewrite opp_eq_mult_neg_1, mult_0_l.\n Qed.\n\n Lemma mult_le_compat_l i j k :\n   0<=k -> i<=j -> k*i <= k*j.\n Proof.\n intros Hk Hij.\n apply le_is_lt_or_eq in Hk. apply le_is_lt_or_eq in Hij.\n destruct Hk as [Hk | <-], Hij as [Hij | <-];\n  rewrite ? mult_0_l; try apply le_refl.\n now apply lt_le_weak, mult_lt_compat_l.\n Qed.\n\n Lemma mult_le_compat i j k l :\n   i<=j -> k<=l -> 0<=i -> 0<=k -> i*k<=j*l.\n Proof.\n intros Hij Hkl Hi Hk.\n apply le_trans with (i*l).\n - now apply mult_le_compat_l.\n - rewrite (mult_comm i), (mult_comm j).\n   apply mult_le_compat_l; trivial.\n   now apply le_trans with k.\n Qed.\n\n Lemma sum5 a b c d : 0 <> c -> 0 <> a -> 0 = b -> 0 <> a * c + b * d.\n Proof.\n intros Hc Ha <-. autorewrite with int. contradict Hc.\n symmetry in Hc. destruct (mult_integral _ _ Hc); congruence.\n Qed.\n\n Lemma le_left n m : n <= m <-> 0 <= m + - n.\n Proof.\n  split; intros.\n  - rewrite <- (opp_def m).\n    apply plus_le_compat.\n    apply le_refl.\n    apply opp_le_compat; auto.\n  - apply plus_le_reg_r with (-n).\n    now rewrite plus_opp_r.\n Qed.\n\n Lemma OMEGA8 x y : 0 <= x -> 0 <= y -> x = - y -> x = 0.\n Proof.\n intros.\n assert (y=-x).\n  subst x; symmetry; apply opp_involutive.\n clear H1; subst y.\n destruct (eq_dec 0 x) as [H'|H']; auto.\n assert (H'':=le_neq_lt _ _ H H').\n generalize (plus_le_lt_compat _ _ _ _ H0 H'').\n rewrite plus_opp_l, plus_0_l.\n intros.\n elim (lt_not_eq _ _ H1); auto.\n Qed.\n\n Lemma sum2 a b c d :\n   0 <= d -> 0 = a -> 0 <= b -> 0 <= a * c + b * d.\n Proof.\n intros Hd <- Hb. autorewrite with int.\n rewrite <- (mult_0_l 0).\n apply mult_le_compat; auto; apply le_refl.\n Qed.\n\n Lemma sum3 a b c d :\n  0 <= c -> 0 <= d -> 0 <= a -> 0 <= b -> 0 <= a * c + b * d.\n Proof.\n intros.\n rewrite <- (plus_0_l 0).\n apply plus_le_compat; auto.\n rewrite <- (mult_0_l 0).\n apply mult_le_compat; auto; apply le_refl.\n rewrite <- (mult_0_l 0).\n apply mult_le_compat; auto; apply le_refl.\n Qed.\n\n (** Lemmas specific to integers (they use [le_lt_int]) *)\n\n Lemma lt_left n m : n < m <-> 0 <= m + -n + -(1).\n Proof.\n rewrite <- plus_assoc, (plus_comm (-n)), plus_assoc.\n rewrite <- le_left.\n apply le_lt_int.\n Qed.\n\n Lemma OMEGA4 x y z : 0 < x -> x < y -> z * y + x <> 0.\n Proof.\n intros H H0 H'.\n assert (0 < y) by now apply lt_trans with x.\n destruct (lt_eq_lt_dec z 0) as [[G|G]|G].\n\n - generalize (plus_le_lt_compat _ _ _ _ (le_refl (z*y)) H0).\n   rewrite H'.\n   rewrite <-(mult_1_l y) at 2. rewrite <-mult_plus_distr_r.\n   apply le_lt_iff.\n   rewrite mult_comm. rewrite <- (mult_0_r y).\n   apply mult_le_compat_l; auto using lt_le_weak.\n   apply le_0_neg. rewrite opp_plus_distr.\n   apply le_lt_int. now apply lt_0_neg.\n\n - apply (lt_not_eq 0 (z*y+x)); auto.\n   subst. now autorewrite with int.\n\n - apply (lt_not_eq 0 (z*y+x)); auto.\n   rewrite <- (plus_0_l 0).\n   auto using plus_lt_compat, mult_lt_0_compat.\n Qed.\n\n Lemma OMEGA19 x : x<>0 -> 0 <= x + -(1) \\/ 0 <= x * -(1) + -(1).\n Proof.\n intros.\n do 2 rewrite <- le_lt_int.\n rewrite <- opp_eq_mult_neg_1.\n destruct (lt_eq_lt_dec 0 x) as [[H'|H']|H'].\n auto.\n congruence.\n right.\n rewrite <-(mult_0_l (-(1))), <-(opp_eq_mult_neg_1 0).\n apply opp_lt_compat; auto.\n Qed.\n\n Lemma mult_le_approx n m p :\n  0 < n -> p < n -> 0 <= m * n + p -> 0 <= m.\n Proof.\n do 2 rewrite le_lt_iff; intros Hn Hpn H Hm. destruct H.\n apply lt_0_neg, le_lt_int, le_left in Hm.\n rewrite lt_0_neg.\n rewrite opp_plus_distr, mult_comm, opp_mult_distr_r.\n rewrite le_lt_int. apply lt_left.\n rewrite le_lt_int.\n apply le_trans with (n+-(1)); [ now apply le_lt_int | ].\n apply plus_le_compat; [ | apply le_refl ].\n rewrite <- (mult_1_r n) at 1.\n apply mult_le_compat_l; auto using lt_le_weak.\n Qed.\n\n (** Some decidabilities *)\n\n Lemma dec_eq : forall i j:int, decidable (i=j).\n Proof.\n  red; intros; destruct (eq_dec i j); auto.\n Qed.\n\n Lemma dec_ne : forall i j:int, decidable (i<>j).\n Proof.\n  red; intros; destruct (eq_dec i j); auto.\n Qed.\n\n Lemma dec_le : forall i j:int, decidable (i<=j).\n Proof.\n  red; intros; destruct (le_dec i j); auto.\n Qed.\n\n Lemma dec_lt : forall i j:int, decidable (i<j).\n Proof.\n  red; intros; destruct (lt_dec i j); auto.\n Qed.\n\n Lemma dec_ge : forall i j:int, decidable (i>=j).\n Proof.\n  red; intros; rewrite ge_le_iff; destruct (le_dec j i); auto.\n Qed.\n\n Lemma dec_gt : forall i j:int, decidable (i>j).\n Proof.\n  red; intros; rewrite gt_lt_iff; destruct (lt_dec j i); auto.\n Qed.\n\nEnd IntProperties.\n\n\n(** * The Coq side of the romega tactic *)\n\nModule IntOmega (I:Int).\nImport I.\nModule IP:=IntProperties(I).\nImport IP.\nLocal Notation int := I.t.\n\n(* ** Definition of reified integer expressions\n\n   Terms are either:\n   - integers [Tint]\n   - variables [Tvar]\n   - operation over integers (addition, product, opposite, subtraction)\n\n   Opposite and subtraction are translated in additions and products.\n   Note that we'll only deal with products for which at least one side\n   is [Tint]. *)\n\nInductive term : Set :=\n  | Tint : int -> term\n  | Tplus : term -> term -> term\n  | Tmult : term -> term -> term\n  | Tminus : term -> term -> term\n  | Topp : term -> term\n  | Tvar : N -> term.\n\nBind Scope romega_scope with term.\nDelimit Scope romega_scope with term.\nArguments Tint _%I.\nArguments Tplus (_ _)%term.\nArguments Tmult (_ _)%term.\nArguments Tminus (_ _)%term.\nArguments Topp _%term.\n\nInfix \"+\" := Tplus : romega_scope.\nInfix \"*\" := Tmult : romega_scope.\nInfix \"-\" := Tminus : romega_scope.\nNotation \"- x\" := (Topp x) : romega_scope.\nNotation \"[ x ]\" := (Tvar x) (at level 0) : romega_scope.\n\n(* ** Definition of reified goals\n\n   Very restricted definition of handled predicates that should be extended\n   to cover a wider set of operations.\n   Taking care of negations and disequations require solving more than a\n   goal in parallel. This is a major improvement over previous versions. *)\n\nInductive proposition : Set :=\n  (** First, basic equations, disequations, inequations *)\n  | EqTerm : term -> term -> proposition\n  | NeqTerm : term -> term -> proposition\n  | LeqTerm : term -> term -> proposition\n  | GeqTerm : term -> term -> proposition\n  | GtTerm : term -> term -> proposition\n  | LtTerm : term -> term -> proposition\n  (** Then, the supported logical connectors *)\n  | TrueTerm : proposition\n  | FalseTerm : proposition\n  | Tnot : proposition -> proposition\n  | Tor : proposition -> proposition -> proposition\n  | Tand : proposition -> proposition -> proposition\n  | Timp : proposition -> proposition -> proposition\n  (** Everything else is left as a propositional atom (and ignored). *)\n  | Tprop : nat -> proposition.\n\n(** Definition of goals as a list of hypothesis *)\nNotation hyps := (list proposition).\n\n(** Definition of lists of subgoals (set of open goals) *)\nNotation lhyps := (list hyps).\n\n(** A single goal packed in a subgoal list *)\nNotation singleton := (fun a : hyps => a :: nil).\n\n(** An absurd goal *)\nDefinition absurd := FalseTerm :: nil.\n\n(** ** Decidable equality on terms *)\n\nFixpoint eq_term (t1 t2 : term) {struct t2} : bool :=\n  match t1, t2 with\n  | Tint i1, Tint i2 => i1 =? i2\n  | (t11 + t12), (t21 + t22) => eq_term t11 t21 && eq_term t12 t22\n  | (t11 * t12), (t21 * t22) => eq_term t11 t21 && eq_term t12 t22\n  | (t11 - t12), (t21 - t22) => eq_term t11 t21 && eq_term t12 t22\n  | (- t1), (- t2) => eq_term t1 t2\n  | [v1], [v2] => N.eqb v1 v2\n  | _, _ => false\n  end%term.\n\nInfix \"=?\" := eq_term : romega_scope.\n\nTheorem eq_term_iff (t t' : term) :\n (t =? t')%term = true <-> t = t'.\nProof.\n revert t'. induction t; destruct t'; simpl in *;\n rewrite ?andb_true_iff, ?beq_iff, ?N.eqb_eq, ?IHt, ?IHt1, ?IHt2;\n  intuition congruence.\nQed.\n\nTheorem eq_term_reflect (t t' : term) : reflect (t=t') (t =? t')%term.\nProof.\n apply iff_reflect. symmetry. apply eq_term_iff.\nQed.\n\n(** ** Interpretations of terms (as integers). *)\n\nFixpoint Nnth {A} (n:N)(l:list A)(default:A) :=\n match n, l with\n   | _, nil => default\n   | 0%N, x::_ => x\n   | _, _::l => Nnth (N.pred n) l default\n end.\n\nFixpoint interp_term (env : list int) (t : term) : int :=\n  match t with\n  | Tint x => x\n  | (t1 + t2)%term => interp_term env t1 + interp_term env t2\n  | (t1 * t2)%term => interp_term env t1 * interp_term env t2\n  | (t1 - t2)%term => interp_term env t1 - interp_term env t2\n  | (- t)%term => - interp_term env t\n  | [n]%term => Nnth n env 0\n  end.\n\n(** ** Interpretation of predicats (as Coq propositions) *)\n\nFixpoint interp_prop (envp : list Prop) (env : list int)\n (p : proposition) : Prop :=\n  match p with\n  | EqTerm t1 t2 => interp_term env t1 = interp_term env t2\n  | NeqTerm t1 t2 => (interp_term env t1) <> (interp_term env t2)\n  | LeqTerm t1 t2 => interp_term env t1 <= interp_term env t2\n  | GeqTerm t1 t2 => interp_term env t1 >= interp_term env t2\n  | GtTerm t1 t2 => interp_term env t1 > interp_term env t2\n  | LtTerm t1 t2 => interp_term env t1 < interp_term env t2\n  | TrueTerm => True\n  | FalseTerm => False\n  | Tnot p' => ~ interp_prop envp env p'\n  | Tor p1 p2 => interp_prop envp env p1 \\/ interp_prop envp env p2\n  | Tand p1 p2 => interp_prop envp env p1 /\\ interp_prop envp env p2\n  | Timp p1 p2 => interp_prop envp env p1 -> interp_prop envp env p2\n  | Tprop n => nth n envp True\n  end.\n\n(** ** Intepretation of hypothesis lists (as Coq conjunctions) *)\n\nFixpoint interp_hyps (envp : list Prop) (env : list int) (l : hyps)\n  : Prop :=\n  match l with\n  | nil => True\n  | p' :: l' => interp_prop envp env p' /\\ interp_hyps envp env l'\n  end.\n\n(** ** Interpretation of conclusion + hypotheses\n\n   Here we use Coq implications : it's less easy to manipulate,\n   but handy to relate to the Coq original goal (cf. the use of\n   [generalize], and lighter (no repetition of types in intermediate\n   conjunctions). *)\n\nFixpoint interp_goal_concl (c : proposition) (envp : list Prop)\n (env : list int) (l : hyps) : Prop :=\n  match l with\n  | nil => interp_prop envp env c\n  | p' :: l' =>\n      interp_prop envp env p' -> interp_goal_concl c envp env l'\n  end.\n\nNotation interp_goal := (interp_goal_concl FalseTerm).\n\n(** Equivalence between these two interpretations. *)\n\nTheorem goal_to_hyps :\n forall (envp : list Prop) (env : list int) (l : hyps),\n (interp_hyps envp env l -> False) -> interp_goal envp env l.\nProof.\n induction l; simpl; auto.\nQed.\n\nTheorem hyps_to_goal :\n forall (envp : list Prop) (env : list int) (l : hyps),\n interp_goal envp env l -> interp_hyps envp env l -> False.\nProof.\n induction l; simpl; auto.\n intros H (H1,H2). auto.\nQed.\n\n(** ** Interpretations of list of goals\n\n    Here again, two flavours... *)\n\nFixpoint interp_list_hyps (envp : list Prop) (env : list int)\n (l : lhyps) : Prop :=\n  match l with\n  | nil => False\n  | h :: l' => interp_hyps envp env h \\/ interp_list_hyps envp env l'\n  end.\n\nFixpoint interp_list_goal (envp : list Prop) (env : list int)\n (l : lhyps) : Prop :=\n  match l with\n  | nil => True\n  | h :: l' => interp_goal envp env h /\\ interp_list_goal envp env l'\n  end.\n\n(** Equivalence between the two flavours. *)\n\nTheorem list_goal_to_hyps :\n forall (envp : list Prop) (env : list int) (l : lhyps),\n (interp_list_hyps envp env l -> False) -> interp_list_goal envp env l.\nProof.\n induction l; simpl; intuition. now apply goal_to_hyps.\nQed.\n\nTheorem list_hyps_to_goal :\n forall (envp : list Prop) (env : list int) (l : lhyps),\n interp_list_goal envp env l -> interp_list_hyps envp env l -> False.\nProof.\n induction l; simpl; intuition. eapply hyps_to_goal; eauto.\nQed.\n\n(** ** Stabiliy and validity of operations *)\n\n(** An operation on terms is stable if the interpretation is unchanged. *)\n\nDefinition term_stable (f : term -> term) :=\n  forall (e : list int) (t : term), interp_term e t = interp_term e (f t).\n\n(** An operation on one hypothesis is valid if this hypothesis implies\n    the result of this operation. *)\n\nDefinition valid1 (f : proposition -> proposition) :=\n  forall (ep : list Prop) (e : list int) (p1 : proposition),\n  interp_prop ep e p1 -> interp_prop ep e (f p1).\n\nDefinition valid2 (f : proposition -> proposition -> proposition) :=\n  forall (ep : list Prop) (e : list int) (p1 p2 : proposition),\n  interp_prop ep e p1 ->\n  interp_prop ep e p2 -> interp_prop ep e (f p1 p2).\n\n(** Same for lists of hypotheses, and for list of goals *)\n\nDefinition valid_hyps (f : hyps -> hyps) :=\n  forall (ep : list Prop) (e : list int) (lp : hyps),\n  interp_hyps ep e lp -> interp_hyps ep e (f lp).\n\nDefinition valid_list_hyps (f : hyps -> lhyps) :=\n  forall (ep : list Prop) (e : list int) (lp : hyps),\n  interp_hyps ep e lp -> interp_list_hyps ep e (f lp).\n\nDefinition valid_list_goal (f : hyps -> lhyps) :=\n  forall (ep : list Prop) (e : list int) (lp : hyps),\n  interp_list_goal ep e (f lp) -> interp_goal ep e lp.\n\n(** Some results about these validities. *)\n\nTheorem valid_goal :\n  forall (ep : list Prop) (env : list int) (l : hyps) (a : hyps -> hyps),\n  valid_hyps a -> interp_goal ep env (a l) -> interp_goal ep env l.\nProof.\n intros; simpl; apply goal_to_hyps; intro H1;\n apply (hyps_to_goal ep env (a l) H0); apply H; assumption.\nQed.\n\nTheorem goal_valid :\n forall f : hyps -> lhyps, valid_list_hyps f -> valid_list_goal f.\nProof.\n unfold valid_list_goal; intros f H ep e lp H1; apply goal_to_hyps;\n intro H2; apply list_hyps_to_goal with (1 := H1);\n apply (H ep e lp); assumption.\nQed.\n\nTheorem append_valid :\n forall (ep : list Prop) (e : list int) (l1 l2 : lhyps),\n interp_list_hyps ep e l1 \\/ interp_list_hyps ep e l2 ->\n interp_list_hyps ep e (l1 ++ l2).\nProof.\n induction l1; simpl in *.\n - now intros l2 [H| H].\n - intros l2 [[H| H]| H].\n   + auto.\n   + right; apply IHl1; now left.\n   + right; apply IHl1; now right.\nQed.\n\n(** ** Valid operations on hypotheses *)\n\n(** Extract an hypothesis from the list *)\n\nDefinition nth_hyps (n : nat) (l : hyps) := nth n l TrueTerm.\n\nTheorem nth_valid :\n forall (ep : list Prop) (e : list int) (i : nat) (l : hyps),\n interp_hyps ep e l -> interp_prop ep e (nth_hyps i l).\nProof.\n unfold nth_hyps. induction i; destruct l; simpl in *; try easy.\n intros (H1,H2). now apply IHi.\nQed.\n\n(** Apply a valid operation on two hypotheses from the list, and\n    store the result in the list. *)\n\nDefinition apply_oper_2 (i j : nat)\n  (f : proposition -> proposition -> proposition) (l : hyps) :=\n  f (nth_hyps i l) (nth_hyps j l) :: l.\n\nTheorem apply_oper_2_valid :\n forall (i j : nat) (f : proposition -> proposition -> proposition),\n valid2 f -> valid_hyps (apply_oper_2 i j f).\nProof.\n intros i j f Hf; unfold apply_oper_2, valid_hyps; simpl;\n intros lp Hlp; split.\n - apply Hf; apply nth_valid; assumption.\n - assumption.\nQed.\n\n(** In-place modification of an hypothesis by application of\n    a valid operation. *)\n\nFixpoint apply_oper_1 (i : nat) (f : proposition -> proposition)\n (l : hyps) {struct i} : hyps :=\n  match l with\n  | nil => nil\n  | p :: l' =>\n      match i with\n      | O => f p :: l'\n      | S j => p :: apply_oper_1 j f l'\n      end\n  end.\n\nTheorem apply_oper_1_valid :\n forall (i : nat) (f : proposition -> proposition),\n valid1 f -> valid_hyps (apply_oper_1 i f).\nProof.\n unfold valid_hyps.\n induction i; intros f Hf ep e [ | p lp]; simpl; intuition.\nQed.\n\n(** ** A tactic for proving stability *)\n\nLtac loop t :=\n  match t with\n  (* Global *)\n  | (?X1 = ?X2) => loop X1 || loop X2\n  | (_ -> ?X1) => loop X1\n  (* Interpretations *)\n  | (interp_hyps _ _ ?X1) => loop X1\n  | (interp_list_hyps _ _ ?X1) => loop X1\n  | (interp_prop _ _ ?X1) => loop X1\n  | (interp_term _ ?X1) => loop X1\n  (* Propositions *)\n  | (EqTerm ?X1 ?X2) => loop X1 || loop X2\n  | (LeqTerm ?X1 ?X2) => loop X1 || loop X2\n  (* Terms *)\n  | (?X1 + ?X2)%term => loop X1 || loop X2\n  | (?X1 - ?X2)%term => loop X1 || loop X2\n  | (?X1 * ?X2)%term => loop X1 || loop X2\n  | (- ?X1)%term => loop X1\n  | (Tint ?X1) => loop X1\n  (* Eliminations *)\n  | (if ?X1 =? ?X2 then _ else _) =>\n      let H := fresh \"H\" in\n      case (beq_reflect X1 X2); intro H;\n      try (rewrite H in *; clear H); simpl; auto; Simplify\n  | (if ?X1 <? ?X2 then _ else _) =>\n      case (blt_reflect X1 X2); intro; simpl; auto; Simplify\n  | (if (?X1 =? ?X2)%term then _ else _) =>\n      let H := fresh \"H\" in\n      case (eq_term_reflect X1 X2); intro H;\n      try (rewrite H in *; clear H); simpl; auto; Simplify\n  | (if _ && _ then _ else _) => rewrite andb_if; Simplify\n  | (if negb _ then _ else _) => rewrite negb_if; Simplify\n  | match N.compare ?X1 ?X2 with _ => _ end =>\n    destruct (N.compare_spec X1 X2); Simplify\n  | match ?X1 with _ => _ end => destruct X1; auto; Simplify\n  | _ => fail\n  end\n\nwith Simplify := match goal with\n  |  |- ?X1 => try loop X1\n  | _ => idtac\n  end.\n\n(** ** Operations on equation bodies *)\n\n(** The operations below handle in priority _normalized_ terms, i.e.\n    terms of the form:\n      [([v1]*Tint k1 + ([v2]*Tint k2 + (... + Tint cst)))]\n    with [v1>v2>...] and all [ki<>0].\n    See [normalize] below for a way to put terms in this form.\n\n    These operations also produce a correct (but suboptimal)\n    result in case of non-normalized input terms, but this situation\n    should normally not happen when running [romega].\n\n     /!\\ Do not modify this section (especially [fusion] and [normalize])\n    without tweaking the corresponding functions in [refl_omega.ml].\n*)\n\n(** Multiplication and sum by two constants. Invariant: [k1<>0]. *)\n\nFixpoint scalar_mult_add (t : term) (k1 k2 : int) : term :=\n  match t with\n  | v1 * Tint x1 + l1 =>\n    v1 * Tint (x1 * k1) + scalar_mult_add l1 k1 k2\n  | Tint x => Tint (k1 * x + k2)\n  | _ => t * Tint k1 + Tint k2 (* shouldn't happen *)\n  end%term.\n\nTheorem scalar_mult_add_stable e t k1 k2 :\n interp_term e (scalar_mult_add t k1 k2) =\n interp_term e (t * Tint k1 + Tint k2).\nProof.\n induction t; simpl; Simplify; simpl; auto. f_equal. apply mult_comm.\n rewrite IHt2. simpl. apply OMEGA11.\nQed.\n\n(** Multiplication by a (non-nul) constant. *)\n\nDefinition scalar_mult (t : term) (k : int) := scalar_mult_add t k 0.\n\nTheorem scalar_mult_stable e t k :\n interp_term e (scalar_mult t k) =\n interp_term e (t * Tint k).\nProof.\n unfold scalar_mult. rewrite scalar_mult_add_stable. simpl.\n apply plus_0_r.\nQed.\n\n(** Adding a constant\n\n    Instead of using [scalar_norm_add t 1 k], the following\n    definition spares some computations.\n *)\n\nFixpoint scalar_add (t : term) (k : int) : term :=\n  match t with\n  | m + l => m + scalar_add l k\n  | Tint x => Tint (x + k)\n  | _ => t + Tint k\n  end%term.\n\nTheorem scalar_add_stable e t k :\n interp_term e (scalar_add t k) = interp_term e (t + Tint k).\nProof.\n induction t; simpl; Simplify; simpl; auto.\n rewrite IHt2. simpl. apply plus_assoc.\nQed.\n\n(** Division by a constant\n\n    All the non-constant coefficients should be exactly dividable *)\n\nFixpoint scalar_div (t : term) (k : int) : option (term * int) :=\n  match t with\n  | v * Tint x + l =>\n    let (q,r) := diveucl x k in\n    if (r =? 0)%I then\n      match scalar_div l k with\n      | None => None\n      | Some (u,c) => Some (v * Tint q + u, c)\n      end\n    else None\n  | Tint x =>\n    let (q,r) := diveucl x k in\n    Some (Tint q, r)\n  | _ => None\n  end%term.\n\nLemma scalar_div_stable e t k u c : k<>0 ->\n  scalar_div t k = Some (u,c) ->\n  interp_term e (u * Tint k + Tint c) = interp_term e t.\nProof.\n revert u c.\n induction t; simpl; Simplify; try easy.\n - intros u c Hk. assert (H := diveucl_spec t0 k Hk).\n   simpl in H.\n   destruct diveucl as (q,r). simpl in H. rewrite H.\n   injection 1 as <- <-. simpl. f_equal. apply mult_comm.\n - intros u c Hk.\n   destruct t1; simpl; Simplify; try easy.\n   destruct t1_2; simpl; Simplify; try easy.\n   assert (H := diveucl_spec t0 k Hk).\n   simpl in H.\n   destruct diveucl as (q,r). simpl in H. rewrite H.\n   case beq_reflect; [intros -> | easy].\n   destruct (scalar_div t2 k) as [(u',c')|] eqn:E; [|easy].\n   injection 1 as <- ->. simpl.\n   rewrite <- (IHt2 u' c Hk); simpl; auto.\n   rewrite plus_0_r , (mult_comm k q). symmetry. apply OMEGA11.\nQed.\n\n\n(** Fusion of two equations.\n\n    From two normalized equations, this fusion will produce\n    a normalized output corresponding to the coefficiented sum.\n    Invariant: [k1<>0] and [k2<>0].\n*)\n\nFixpoint fusion (t1 t2 : term) (k1 k2 : int) : term :=\n  match t1 with\n  | [v1] * Tint x1 + l1 =>\n    (fix fusion_t1 t2 : term :=\n       match t2 with\n         | [v2] * Tint x2 + l2 =>\n           match N.compare v1 v2 with\n             | Eq =>\n               let k := (k1 * x1 + k2 * x2)%I in\n               if (k =? 0)%I then fusion l1 l2 k1 k2\n               else [v1] * Tint k + fusion l1 l2 k1 k2\n             | Lt => [v2] * Tint (k2 * x2) + fusion_t1 l2\n             | Gt => [v1] * Tint (k1 * x1) + fusion l1 t2 k1 k2\n           end\n         | Tint x2 => [v1] * Tint (k1 * x1) + fusion l1 t2 k1 k2\n         | _ => t1 * Tint k1 + t2 * Tint k2 (* shouldn't happen *)\n       end) t2\n  | Tint x1 => scalar_mult_add t2 k2 (k1 * x1)\n  | _ => t1 * Tint k1 + t2 * Tint k2 (* shouldn't happen *)\n  end%term.\n\nTheorem fusion_stable e t1 t2 k1 k2 :\n interp_term e (fusion t1 t2 k1 k2) =\n interp_term e (t1 * Tint k1 + t2 * Tint k2).\nProof.\n revert t2; induction t1; simpl; Simplify; simpl; auto.\n - intros; rewrite scalar_mult_add_stable. simpl.\n   rewrite plus_comm. f_equal. apply mult_comm.\n - intros. Simplify. induction t2; simpl; Simplify; simpl; auto.\n   + rewrite IHt1_2. simpl. rewrite (mult_comm k1); apply OMEGA11.\n   + rewrite IHt1_2. simpl. subst n0.\n     rewrite (mult_comm k1), (mult_comm k2) in H0.\n     rewrite <- OMEGA10, H0. now autorewrite with int.\n   + rewrite IHt1_2. simpl. subst n0.\n     rewrite (mult_comm k1), (mult_comm k2); apply OMEGA10.\n   + rewrite IHt2_2. simpl. rewrite (mult_comm k2); apply OMEGA12.\n   + rewrite IHt1_2. simpl. rewrite (mult_comm k1); apply OMEGA11.\nQed.\n\n(** Term normalization.\n\n   Precondition: all [Tmult] should be on at least one [Tint].\n   Postcondition: a normalized equivalent term (see below).\n*)\n\nFixpoint normalize t :=\n  match t with\n  | Tint n => Tint n\n  | [n]%term => ([n] * Tint 1 + Tint 0)%term\n  | (t + t')%term => fusion (normalize t) (normalize t') 1 1\n  | (- t)%term => scalar_mult (normalize t) (-(1))\n  | (t - t')%term => fusion (normalize t) (normalize t') 1 (-(1))\n  | (Tint k * t)%term | (t * Tint k)%term =>\n    if k =? 0 then Tint 0 else scalar_mult (normalize t) k\n  | (t1 * t2)%term => (t1 * t2)%term (* shouldn't happen *)\n  end.\n\nTheorem normalize_stable : term_stable normalize.\nProof.\n intros e t.\n induction t; simpl; Simplify; simpl;\n rewrite ?scalar_mult_stable; simpl in *; rewrite <- ?IHt1;\n rewrite ?fusion_stable; simpl; autorewrite with int; auto.\n - now f_equal.\n - rewrite mult_comm. now f_equal.\n - rewrite <- opp_eq_mult_neg_1, <-minus_def. now f_equal.\n - rewrite <- opp_eq_mult_neg_1. now f_equal.\nQed.\n\n(** ** Normalization of a proposition.\n\n    The only basic facts left after normalization are\n    [0 = ...] or [0 <> ...] or [0 <= ...].\n    When a fact is in negative position, we factorize a [Tnot]\n    out of it, and normalize the reversed fact inside.\n\n    /!\\ Here again, do not change this code without corresponding\n    modifications in [refl_omega.ml].\n*)\n\nFixpoint normalize_prop (negated:bool)(p:proposition) :=\n  match p with\n  | EqTerm t1 t2 =>\n    if negated then Tnot (NeqTerm (Tint 0) (normalize (t1-t2)))\n    else EqTerm (Tint 0) (normalize (t1-t2))\n  | NeqTerm t1 t2 =>\n    if negated then Tnot (EqTerm (Tint 0) (normalize (t1-t2)))\n    else NeqTerm (Tint 0) (normalize (t1-t2))\n  | LeqTerm t1 t2 =>\n    if negated then Tnot (LeqTerm (Tint 0) (normalize (t1-t2+Tint (-(1)))))\n    else LeqTerm (Tint 0) (normalize (t2-t1))\n  | GeqTerm t1 t2 =>\n    if negated then Tnot (LeqTerm (Tint 0) (normalize (t2-t1+Tint (-(1)))))\n    else LeqTerm (Tint 0) (normalize (t1-t2))\n  | LtTerm t1 t2 =>\n    if negated then Tnot (LeqTerm (Tint 0) (normalize (t1-t2)))\n    else LeqTerm (Tint 0) (normalize (t2-t1+Tint (-(1))))\n  | GtTerm t1 t2 =>\n    if negated then Tnot (LeqTerm (Tint 0) (normalize (t2-t1)))\n    else LeqTerm (Tint 0) (normalize (t1-t2+Tint (-(1))))\n  | Tnot p => Tnot (normalize_prop (negb negated) p)\n  | Tor p p' => Tor (normalize_prop negated p) (normalize_prop negated p')\n  | Tand p p' => Tand (normalize_prop negated p) (normalize_prop negated p')\n  | Timp p p' => Timp (normalize_prop (negb negated) p)\n                      (normalize_prop negated p')\n  | Tprop _ | TrueTerm | FalseTerm => p\n  end.\n\nDefinition normalize_hyps := List.map (normalize_prop false).\n\nLocal Ltac simp := cbn -[normalize].\n\nTheorem normalize_prop_valid b e ep p :\n  interp_prop e ep (normalize_prop b p) <-> interp_prop e ep p.\nProof.\n revert b.\n induction p; intros; simp; try tauto.\n - destruct b; simp;\n   rewrite <- ?normalize_stable; simpl; rewrite ?minus_def.\n   + rewrite not_eq. apply egal_left.\n   + apply egal_left.\n - destruct b; simp;\n   rewrite <- ?normalize_stable; simpl; rewrite ?minus_def;\n   apply not_iff_compat, egal_left.\n - destruct b; simp;\n   rewrite <- ? normalize_stable; simpl; rewrite ?minus_def.\n   + symmetry. rewrite le_lt_iff. apply not_iff_compat, lt_left.\n   + now rewrite <- le_left.\n - destruct b; simp;\n   rewrite <- ? normalize_stable; simpl; rewrite ?minus_def.\n   + symmetry. rewrite ge_le_iff, le_lt_iff.\n     apply not_iff_compat, lt_left.\n   + rewrite ge_le_iff. now rewrite <- le_left.\n - destruct b; simp;\n   rewrite <- ? normalize_stable; simpl; rewrite ?minus_def.\n   + rewrite gt_lt_iff, lt_le_iff. apply not_iff_compat.\n     now rewrite <- le_left.\n   + symmetry. rewrite gt_lt_iff. apply lt_left.\n - destruct b; simp;\n   rewrite <- ? normalize_stable; simpl; rewrite ?minus_def.\n   + rewrite lt_le_iff. apply not_iff_compat.\n     now rewrite <- le_left.\n   + symmetry. apply lt_left.\n - now rewrite IHp.\n - now rewrite IHp1, IHp2.\n - now rewrite IHp1, IHp2.\n - now rewrite IHp1, IHp2.\nQed.\n\nTheorem normalize_hyps_valid : valid_hyps normalize_hyps.\nProof.\n intros e ep l. induction l; simpl; intuition.\n now rewrite normalize_prop_valid.\nQed.\n\nTheorem normalize_hyps_goal (ep : list Prop) (env : list int) (l : hyps) :\n interp_goal ep env (normalize_hyps l) -> interp_goal ep env l.\nProof.\n intros; apply valid_goal with (2 := H); apply normalize_hyps_valid.\nQed.\n\n(** ** A simple decidability checker\n\n   For us, everything is considered decidable except\n   propositional atoms [Tprop _]. *)\n\nFixpoint decidability (p : proposition) : bool :=\n  match p with\n  | Tnot t => decidability t\n  | Tand t1 t2 => decidability t1 && decidability t2\n  | Timp t1 t2 => decidability t1 && decidability t2\n  | Tor t1 t2 => decidability t1 && decidability t2\n  | Tprop _ => false\n  | _ => true\n  end.\n\nTheorem decidable_correct :\n forall (ep : list Prop) (e : list int) (p : proposition),\n decidability p = true -> decidable (interp_prop ep e p).\nProof.\n induction p; simpl; intros Hp; try destruct (andb_prop _ _ Hp).\n - apply dec_eq.\n - apply dec_ne.\n - apply dec_le.\n - apply dec_ge.\n - apply dec_gt.\n - apply dec_lt.\n - left; auto.\n - right; unfold not; auto.\n - apply dec_not; auto.\n - apply dec_or; auto.\n - apply dec_and; auto.\n - apply dec_imp; auto.\n - discriminate.\nQed.\n\n(** ** Omega steps\n\n   The following inductive type describes steps as they can be\n   found in the trace coming from the decision procedure Omega.\n   We consider here only normalized equations [0=...], disequations\n   [0<>...] or inequations [0<=...].\n\n   First, the final steps leading to a contradiction:\n   - [O_BAD_CONSTANT i] : hypothesis i has a constant body\n     and this constant is not compatible with the kind of i.\n   - [O_NOT_EXACT_DIVIDE i k] :\n     equation i can be factorized as some [k*t+c] with [0<c<k].\n\n   Now, the intermediate steps leading to a new hypothesis:\n   - [O_DIVIDE i k cont] :\n     the body of hypothesis i could be factorized as [k*t+c]\n     with either [k<>0] and [c=0] for a (dis)equation, or\n     [0<k] and [c<k] for an inequation. We change in-place the\n     body of i for [t].\n   - [O_SUM k1 i1 k2 i2 cont] : creates a new hypothesis whose\n     kind depends on the kind of hypotheses [i1] and [i2], and\n     whose body is [k1*body(i1) + k2*body(i2)]. Depending of the\n     situation, [k1] or [k2] might have to be positive or non-nul.\n   - [O_MERGE_EQ i j cont] :\n     inequations i and j have opposite bodies, we add an equation\n     with one these bodies.\n   - [O_SPLIT_INEQ i cont1 cont2] :\n     disequation i is split into a disjonction of inequations.\n*)\n\nDefinition idx := nat. (** Index of an hypothesis in the list *)\n\nInductive t_omega : Set :=\n  | O_BAD_CONSTANT : idx -> t_omega\n  | O_NOT_EXACT_DIVIDE : idx -> int -> t_omega\n\n  | O_DIVIDE : idx -> int -> t_omega -> t_omega\n  | O_SUM : int -> idx -> int -> idx -> t_omega -> t_omega\n  | O_MERGE_EQ : idx -> idx -> t_omega -> t_omega\n  | O_SPLIT_INEQ : idx -> t_omega -> t_omega -> t_omega.\n\n(** ** Actual resolution steps of an omega normalized goal *)\n\n(** First, the final steps, leading to a contradiction *)\n\n(** [O_BAD_CONSTANT] *)\n\nDefinition bad_constant (i : nat) (h : hyps) :=\n  match nth_hyps i h with\n  | EqTerm (Tint Nul) (Tint n) => if n =? Nul then h else absurd\n  | NeqTerm (Tint Nul) (Tint n) => if n =? Nul then absurd else h\n  | LeqTerm (Tint Nul) (Tint n) => if n <? Nul then absurd else h\n  | _ => h\n  end.\n\nTheorem bad_constant_valid i : valid_hyps (bad_constant i).\nProof.\n unfold valid_hyps, bad_constant; intros ep e lp H.\n generalize (nth_valid ep e i lp H); Simplify.\n rewrite le_lt_iff. intuition.\nQed.\n\n(** [O_NOT_EXACT_DIVIDE] *)\n\nDefinition not_exact_divide (i : nat) (k : int) (l : hyps) :=\n  match nth_hyps i l with\n  | EqTerm (Tint Nul) b =>\n    match scalar_div b k with\n    | Some (body,c) =>\n      if (Nul =? 0) && (0 <? c) && (c <? k) then absurd\n      else l\n    | None => l\n    end\n  | _ => l\n  end.\n\nTheorem not_exact_divide_valid i k :\n valid_hyps (not_exact_divide i k).\nProof.\n unfold valid_hyps, not_exact_divide; intros.\n generalize (nth_valid ep e i lp).\n destruct (nth_hyps i lp); simpl; auto.\n destruct t0; auto.\n destruct (scalar_div t1 k) as [(body,c)|] eqn:E; auto.\n Simplify.\n assert (k <> 0).\n { intro. apply (lt_not_eq 0 k); eauto using lt_trans. }\n apply (scalar_div_stable e) in E; auto. simpl in E.\n intros H'; rewrite <- H' in E; auto.\n exfalso. revert E. now apply OMEGA4.\nQed.\n\n(** Now, the steps generating a new equation. *)\n\n(** [O_DIVIDE] *)\n\nDefinition divide (k : int) (prop : proposition) :=\n  match prop with\n  | EqTerm (Tint o) b =>\n    match scalar_div b k with\n    | Some (body,c) =>\n      if (o =? 0) && (c =? 0) && negb (k =? 0)\n      then EqTerm (Tint 0) body\n      else TrueTerm\n    | None => TrueTerm\n    end\n  | NeqTerm (Tint o) b =>\n    match scalar_div b k with\n    | Some (body,c) =>\n      if (o =? 0) && (c =? 0) && negb (k =? 0)\n      then NeqTerm (Tint 0) body\n      else TrueTerm\n    | None => TrueTerm\n    end\n  | LeqTerm (Tint o) b =>\n    match scalar_div b k with\n    | Some (body,c) =>\n      if (o =? 0) && (0 <? k) && (c <? k)\n      then LeqTerm (Tint 0) body\n      else prop\n    | None => prop\n    end\n  | _ => TrueTerm\n  end.\n\nTheorem divide_valid k : valid1 (divide k).\nProof.\n unfold valid1, divide; intros ep e p;\n destruct p; simpl; auto;\n destruct t0; simpl; auto;\n destruct scalar_div as [(body,c)|] eqn:E; simpl; Simplify; auto.\n - apply (scalar_div_stable e) in E; auto. simpl in E.\n   intros H'; rewrite <- H' in E. rewrite plus_0_r in E.\n   apply mult_integral in E. intuition.\n - apply (scalar_div_stable e) in E; auto. simpl in E.\n   intros H' H''. now rewrite <- H'', mult_0_l, plus_0_l in E.\n - assert (k <> 0).\n   { intro. apply (lt_not_eq 0 k); eauto using lt_trans. }\n   apply (scalar_div_stable e) in E; auto. simpl in E. rewrite <- E.\n   intro H'. now apply mult_le_approx with (3 := H').\nQed.\n\n(** [O_SUM]. Invariant: [k1] and [k2] non-nul. *)\n\nDefinition sum (k1 k2 : int) (prop1 prop2 : proposition) :=\n  match prop1 with\n  | EqTerm (Tint o) b1 =>\n      match prop2 with\n      | EqTerm (Tint o') b2 =>\n          if (o =? 0) && (o' =? 0)\n          then EqTerm (Tint 0) (fusion b1 b2 k1 k2)\n          else TrueTerm\n      | LeqTerm (Tint o') b2 =>\n          if (o =? 0) && (o' =? 0) && (0 <? k2)\n          then LeqTerm (Tint 0) (fusion b1 b2 k1 k2)\n          else TrueTerm\n      | NeqTerm (Tint o') b2 =>\n          if (o =? 0) && (o' =? 0) && negb (k2 =? 0)\n          then NeqTerm (Tint 0) (fusion b1 b2 k1 k2)\n          else TrueTerm\n      | _ => TrueTerm\n      end\n  | LeqTerm (Tint o) b1 =>\n      if (o =? 0) && (0 <? k1)\n      then match prop2 with\n          | EqTerm (Tint o') b2 =>\n              if o' =? 0 then\n              LeqTerm (Tint 0) (fusion b1 b2 k1 k2)\n              else TrueTerm\n          | LeqTerm (Tint o') b2 =>\n              if (o' =? 0) && (0 <? k2)\n              then LeqTerm (Tint 0) (fusion b1 b2 k1 k2)\n              else TrueTerm\n          | _ => TrueTerm\n          end\n      else TrueTerm\n  | NeqTerm (Tint o) b1 =>\n      match prop2 with\n      | EqTerm (Tint o') b2 =>\n          if (o =? 0) && (o' =? 0) && negb (k1 =? 0)\n          then NeqTerm (Tint 0) (fusion b1 b2 k1 k2)\n          else TrueTerm\n      | _ => TrueTerm\n      end\n  | _ => TrueTerm\n  end.\n\nTheorem sum_valid :\n forall (k1 k2 : int), valid2 (sum k1 k2).\nProof.\n unfold valid2; intros k1 k2 t ep e p1 p2; unfold sum;\n Simplify; simpl; rewrite ?fusion_stable;\n simpl; intros; auto.\n - apply sum1; auto.\n - rewrite plus_comm. apply sum5; auto.\n - apply sum2; auto using lt_le_weak.\n - apply sum5; auto.\n - rewrite plus_comm. apply sum2; auto using lt_le_weak.\n - apply sum3; auto using lt_le_weak.\nQed.\n\n(** [MERGE_EQ] *)\n\nDefinition merge_eq (prop1 prop2 : proposition) :=\n  match prop1 with\n  | LeqTerm (Tint o) b1 =>\n      match prop2 with\n      | LeqTerm (Tint o') b2 =>\n          if (o =? 0) && (o' =? 0) &&\n             (b1 =? scalar_mult b2 (-(1)))%term\n          then EqTerm (Tint 0) b1\n          else TrueTerm\n      | _ => TrueTerm\n      end\n  | _ => TrueTerm\n  end.\n\nTheorem merge_eq_valid : valid2 merge_eq.\nProof.\n unfold valid2, merge_eq; intros ep e p1 p2; Simplify; simpl; auto.\n rewrite scalar_mult_stable. simpl.\n intros; symmetry ; apply OMEGA8 with (2 := H0).\n - assumption.\n - elim opp_eq_mult_neg_1; trivial.\nQed.\n\n(** [O_SPLIT_INEQ] (only step to produce two subgoals). *)\n\nDefinition split_ineq (i : nat) (f1 f2 : hyps -> lhyps) (l : hyps) :=\n  match nth_hyps i l with\n  | NeqTerm (Tint o) b1 =>\n      if o =? 0 then\n       f1 (LeqTerm (Tint 0) (scalar_add b1 (-(1))) :: l) ++\n       f2 (LeqTerm (Tint 0) (scalar_mult_add b1 (-(1)) (-(1))) :: l)\n      else l :: nil\n  | _ => l :: nil\n  end.\n\nTheorem split_ineq_valid :\n forall (i : nat) (f1 f2 : hyps -> lhyps),\n valid_list_hyps f1 ->\n valid_list_hyps f2 -> valid_list_hyps (split_ineq i f1 f2).\nProof.\n unfold valid_list_hyps, split_ineq; intros i f1 f2 H1 H2 ep e lp H;\n generalize (nth_valid _ _ i _ H); case (nth_hyps i lp);\n simpl; auto; intros t1 t2; case t1; simpl;\n auto; intros z; simpl; auto; intro H3.\n Simplify.\n apply append_valid; elim (OMEGA19 (interp_term e t2)).\n - intro H4; left; apply H1; simpl; rewrite scalar_add_stable;\n    simpl; auto.\n - intro H4; right; apply H2; simpl; rewrite scalar_mult_add_stable;\n    simpl; auto.\n - generalize H3; unfold not; intros E1 E2; apply E1;\n    symmetry ; trivial.\nQed.\n\n(** ** Replaying the resolution trace *)\n\nFixpoint execute_omega (t : t_omega) (l : hyps) : lhyps :=\n  match t with\n  | O_BAD_CONSTANT i => singleton (bad_constant i l)\n  | O_NOT_EXACT_DIVIDE i k => singleton (not_exact_divide i k l)\n  | O_DIVIDE i k cont =>\n      execute_omega cont (apply_oper_1 i (divide k) l)\n  | O_SUM k1 i1 k2 i2 cont =>\n      execute_omega cont (apply_oper_2 i1 i2 (sum k1 k2) l)\n  | O_MERGE_EQ i1 i2 cont =>\n      execute_omega cont (apply_oper_2 i1 i2 merge_eq l)\n  | O_SPLIT_INEQ i cont1 cont2 =>\n      split_ineq i (execute_omega cont1) (execute_omega cont2) l\n  end.\n\nTheorem omega_valid : forall tr : t_omega, valid_list_hyps (execute_omega tr).\nProof.\n simple induction tr; unfold valid_list_hyps, valid_hyps; simpl.\n - intros; left; now apply bad_constant_valid.\n - intros; left; now apply not_exact_divide_valid.\n - intros m k t' Ht' ep e lp H; apply Ht';\n    apply\n     (apply_oper_1_valid m (divide k)\n        (divide_valid k) ep e lp H).\n - intros k1 i1 k2 i2 t' Ht' ep e lp H; apply Ht';\n    apply\n     (apply_oper_2_valid i1 i2 (sum k1 k2) (sum_valid k1 k2) ep e\n        lp H).\n - intros i1 i2 t' Ht' ep e lp H; apply Ht';\n    apply\n     (apply_oper_2_valid i1 i2 merge_eq merge_eq_valid ep e\n        lp H).\n - intros i k1 H1 k2 H2 ep e lp H;\n    apply\n     (split_ineq_valid i (execute_omega k1) (execute_omega k2) H1 H2 ep e\n        lp H).\nQed.\n\n\n(** ** Rules for decomposing the hypothesis\n\n   This type allows navigation in the logical constructors that\n   form the predicats of the hypothesis in order to decompose them.\n   This allows in particular to extract one hypothesis from a conjunction.\n   NB: negations are now silently traversed. *)\n\nInductive direction : Set :=\n  | D_left : direction\n  | D_right : direction.\n\n(** This type allows extracting useful components from hypothesis, either\n   hypothesis generated by splitting a disjonction, or equations.\n   The last constructor indicates how to solve the obtained system\n   via the use of the trace type of Omega [t_omega] *)\n\nInductive e_step : Set :=\n  | E_SPLIT : nat -> list direction -> e_step -> e_step -> e_step\n  | E_EXTRACT : nat -> list direction -> e_step -> e_step\n  | E_SOLVE : t_omega -> e_step.\n\n(** Selection of a basic fact inside an hypothesis. *)\n\nFixpoint extract_hyp_pos (s : list direction) (p : proposition) :\n proposition :=\n  match p, s with\n  | Tand x y, D_left :: l => extract_hyp_pos l x\n  | Tand x y, D_right :: l => extract_hyp_pos l y\n  | Tnot x, _ => extract_hyp_neg s x\n  | _, _ => p\n  end\n\n with extract_hyp_neg (s : list direction) (p : proposition) :\n proposition :=\n  match p, s with\n  | Tor x y, D_left :: l => extract_hyp_neg l x\n  | Tor x y, D_right :: l => extract_hyp_neg l y\n  | Timp x y, D_left :: l =>\n    if decidability x then extract_hyp_pos l x else Tnot p\n  | Timp x y, D_right :: l => extract_hyp_neg l y\n  | Tnot x, _ => if decidability x then extract_hyp_pos s x else Tnot p\n  | _, _ => Tnot p\n  end.\n\nTheorem extract_valid :\n forall s : list direction, valid1 (extract_hyp_pos s).\nProof.\n assert (forall p s ep e,\n         (interp_prop ep e p ->\n          interp_prop ep e (extract_hyp_pos s p)) /\\\n         (interp_prop ep e (Tnot p) ->\n          interp_prop ep e (extract_hyp_neg s p))).\n { induction p; destruct s; simpl; auto; split; try destruct d; try easy;\n   intros; (apply IHp || apply IHp1 || apply IHp2 || idtac); simpl; try tauto;\n   destruct decidability eqn:D; auto;\n   apply (decidable_correct ep e) in D; unfold decidable in D;\n   (apply IHp || apply IHp1); tauto. }\n red. intros. now apply H.\nQed.\n\n(** Attempt to shorten error messages if romega goes rogue...\n    NB: [interp_list_goal _ _ BUG = False /\\ True]. *)\nDefinition BUG : lhyps := nil :: nil.\n\n(** Split and extract in hypotheses *)\n\nFixpoint decompose_solve (s : e_step) (h : hyps) : lhyps :=\n  match s with\n  | E_SPLIT i dl s1 s2 =>\n      match extract_hyp_pos dl (nth_hyps i h) with\n      | Tor x y => decompose_solve s1 (x :: h) ++ decompose_solve s2 (y :: h)\n      | Tnot (Tand x y) =>\n          if decidability x\n          then\n           decompose_solve s1 (Tnot x :: h) ++\n           decompose_solve s2 (Tnot y :: h)\n          else BUG\n      | Timp x y =>\n          if decidability x then\n            decompose_solve s1 (Tnot x :: h) ++ decompose_solve s2 (y :: h)\n          else BUG\n      | _ => BUG\n      end\n  | E_EXTRACT i dl s1 =>\n      decompose_solve s1 (extract_hyp_pos dl (nth_hyps i h) :: h)\n  | E_SOLVE t => execute_omega t h\n  end.\n\nTheorem decompose_solve_valid (s : e_step) :\n valid_list_goal (decompose_solve s).\nProof.\n apply goal_valid. red. induction s; simpl; intros ep e lp H.\n - assert (H' : interp_prop ep e (extract_hyp_pos l (nth_hyps n lp))).\n   { now apply extract_valid, nth_valid. }\n   destruct extract_hyp_pos; simpl in *; auto.\n   + destruct p; simpl; auto.\n     destruct decidability eqn:D; [ | simpl; auto].\n     apply (decidable_correct ep e) in D.\n     apply append_valid. simpl in *. destruct D.\n     * right. apply IHs2. simpl; auto.\n     * left. apply IHs1. simpl; auto.\n   + apply append_valid. destruct H'.\n     * left. apply IHs1. simpl; auto.\n     * right. apply IHs2. simpl; auto.\n   + destruct decidability eqn:D; [ | simpl; auto].\n     apply (decidable_correct ep e) in D.\n     apply append_valid. destruct D.\n     * right. apply IHs2. simpl; auto.\n     * left. apply IHs1. simpl; auto.\n - apply IHs; simpl; split; auto.\n   now apply extract_valid, nth_valid.\n - now apply omega_valid.\nQed.\n\n(** Reduction of subgoal list by discarding the contradictory subgoals. *)\n\nDefinition valid_lhyps (f : lhyps -> lhyps) :=\n  forall (ep : list Prop) (e : list int) (lp : lhyps),\n  interp_list_hyps ep e lp -> interp_list_hyps ep e (f lp).\n\nFixpoint reduce_lhyps (lp : lhyps) : lhyps :=\n  match lp with\n  | nil => nil\n  | (FalseTerm :: nil) :: lp' => reduce_lhyps lp'\n  | x :: lp' => BUG\n  end.\n\nTheorem reduce_lhyps_valid : valid_lhyps reduce_lhyps.\nProof.\n unfold valid_lhyps; intros ep e lp; elim lp.\n - simpl; auto.\n - intros a l HR; elim a.\n    + simpl; tauto.\n    + intros a1 l1; case l1; case a1; simpl; tauto.\nQed.\n\nTheorem do_reduce_lhyps :\n forall (envp : list Prop) (env : list int) (l : lhyps),\n interp_list_goal envp env (reduce_lhyps l) -> interp_list_goal envp env l.\nProof.\n intros envp env l H; apply list_goal_to_hyps; intro H1;\n apply list_hyps_to_goal with (1 := H); apply reduce_lhyps_valid;\n assumption.\nQed.\n\n(** Pushing the conclusion into the hypotheses. *)\n\nDefinition concl_to_hyp (p : proposition) :=\n  if decidability p then Tnot p else TrueTerm.\n\nDefinition do_concl_to_hyp :\n  forall (envp : list Prop) (env : list int) (c : proposition) (l : hyps),\n  interp_goal envp env (concl_to_hyp c :: l) ->\n  interp_goal_concl c envp env l.\nProof.\n induction l; simpl.\n - unfold concl_to_hyp; simpl.\n   destruct decidability eqn:D; [ | simpl; tauto ].\n   apply (decidable_correct envp env) in D. unfold decidable in D.\n   simpl. tauto.\n - simpl in *; tauto.\nQed.\n\n(** The omega tactic : all steps together *)\n\nDefinition omega_tactic (t1 : e_step) (c : proposition) (l : hyps) :=\n  reduce_lhyps (decompose_solve t1 (normalize_hyps (concl_to_hyp c :: l))).\n\nTheorem do_omega :\n forall (t : e_step) (envp : list Prop)\n   (env : list int) (c : proposition) (l : hyps),\n interp_list_goal envp env (omega_tactic t c l) ->\n interp_goal_concl c envp env l.\nProof.\n unfold omega_tactic; intros t ep e c l H.\n apply do_concl_to_hyp.\n apply normalize_hyps_goal.\n apply (decompose_solve_valid t).\n now apply do_reduce_lhyps.\nQed.\n\nEnd IntOmega.\n\n(** For now, the above modular construction is instanciated on Z,\n    in order to retrieve the initial ROmega. *)\n\nModule ZOmega := IntOmega(Z_as_Int).\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/plugins/romega/ReflOmegaCore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.6967393344014123}}
{"text": "Inductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\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\nArguments nil {X}.\nArguments cons {X}.\nArguments repeat {X}.\n\nFixpoint app {X : Type} (l1 l2 : list X) : list X :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons h (app t l2)\n  end.\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\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_app_iff: forall A l l' (a: A),\n  In a (l ++ l') <-> In a l \\/ In a l'.\nProof.\n  intros A.\n  induction l as [| a t IH].\n  - intros l' a. split.\n    + intros H. right. apply H.\n    + intros [H1 | H2].\n      * destruct H1.\n      * apply H2.\n  - intros l' x. split.\n    + intros [H1 | H2]. \n      * left. left. apply H1.\n      * apply IH in H2.\n        destruct H2 as [H3 | H4].\n        -- left. right. apply H3.\n        -- right. apply H4.\n    + intros [[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  | a :: t => P a /\\ 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  intros T.\n  induction l as [| a t IH].\n  - split.\n    + intros H. apply I.\n    + intros H0 x H.\n      destruct H.\n  - split.\n    + intros H. split.\n      * apply H. left. reflexivity.\n      * apply IH. intros x H2.\n        apply H. right. apply H2.\n    + intros [H1 H2] x H3.\n      destruct H3 as [H4 | H5].\n      * rewrite <- H4. apply H1.\n      * apply IH. apply H2. apply H5.\nQed.", "meta": {"author": "pikapikapikaori", "repo": "Coq", "sha": "d2af0d21f12b45ee70c3298882b219a133ba9425", "save_path": "github-repos/coq/pikapikapikaori-Coq", "path": "github-repos/coq/pikapikapikaori-Coq/Coq-d2af0d21f12b45ee70c3298882b219a133ba9425/Homework/week10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.696739333965706}}
{"text": "(* Set Implicit Arguments. *)\n\nInductive term : Set :=\n  | tm_true : term\n  | tm_false : term\n  | tm_if : term -> term -> term -> term.\n\nReserved Notation \"t --> t'\" (at level 50).\n\nInductive s_step : term -> term -> Prop :=\n  | E_IfTrue : forall t2 t3, tm_if tm_true t2 t3 --> t2\n  | E_IfFalse : forall t2 t3, tm_if tm_false t2 t3 --> t3\n  | E_If : forall t1 t1' t2 t3, t1 --> t1' -> tm_if t1 t2 t3 --> tm_if t1' t2 t3\n  where \"t --> t'\" := (s_step t t').\n\nDefinition s : term := tm_if tm_true tm_false tm_false.\nDefinition t : term := tm_if s tm_true tm_true.\nDefinition u : term := tm_if tm_false tm_true tm_true.\n\nExample p36_ex_step :\n  tm_if t tm_false tm_false --> tm_if u tm_false tm_false.\nProof.\n  apply E_If. \n  apply E_If.\n  apply E_IfTrue.\nQed.\n\nTheorem theo3_5_4 :\n  forall t t' t'' : term, t --> t' /\\ t --> t'' -> t' = t''.\nProof.\n  intros t t' t'' H1.\n  destruct H1 as [e1 e2].\n\n  generalize dependent t''.\n  induction e1.\n\n  (* E_IfTrue *)\n  intros. inversion e2. reflexivity. inversion H3.\n  (* E_IfFalse *)\n  intros. inversion e2. reflexivity. inversion H3.\n  (* E_If *)\n  intros. inversion e2.\n    rewrite <- H0 in e1. inversion e1.\n    rewrite <- H0 in e1. inversion e1.\n    rewrite (IHe1 t1'0 H3). reflexivity.\nQed.\n", "meta": {"author": "i321takeji", "repo": "tapl-coq", "sha": "26436b303f82b2c02e714b4f895ffa4561be20c0", "save_path": "github-repos/coq/i321takeji-tapl-coq", "path": "github-repos/coq/i321takeji-tapl-coq/tapl-coq-26436b303f82b2c02e714b4f895ffa4561be20c0/ch03/bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6967293987332565}}
{"text": "Require Import lam_cl_es_no\n               abstract_machine_facts.\n\n\n\n\nModule Sim := DetAbstractMachine_Sim Lam_ClES_NO_EAM_minus.\n\nImport Lam_ClES_NO_EAM_minus.\nImport Lam_ClES_NO_RefLang Lam_ClES_NO_Cal.RedLang.\n\n\n\nExample t1 := Lam0 (App0 (Lam0 (Lam0 (Var0 1))) (Var0 0)).\n\n\nEval compute in \n    Sim.n_steps \n    ( c_init t1 )\n    14.\n\n\nEval compute in \n    Sim.n_steps \n    ( c_init (Lam0 (App0  t1  (Var0 0) )) )\n    20.\n\n\n\nFixpoint nat_term0 n :=\n    match n with\n    | 0   => Lam0 (Lam0 (Var0 0))\n    | S n => Lam0 (Lam0 (App0 (Var0 1) (App0 (App0 (nat_term0 n) (Var0 1)) (Var0 0))))\n    end.\n\n\nDefinition add_term0 := \n    Lam0 (Lam0 (Lam0 (Lam0 \n        (App0 (App0 (Var0 3) \n            (Var0 1)) \n            (App0 (App0 (Var0 2) (Var0 1)) (Var0 0)))))).\n\nDefinition mul_term0 := \n    Lam0 (Lam0 (Lam0 (Lam0\n        (App0 (App0\n\n        (App0 (App0 (Var0 2) \n            (Lam0 (App0 (App0 add_term0 (Var0 4)) (Var0 0)) ))\n            (nat_term0 0))\n\n        (Var0 1)) (Var0 0))))).\n\n\nEval compute in\n    Sim.n_steps \n    ( c_init (App0 (App0 mul_term0 (nat_term0 3)) (nat_term0 4)) ) \n    672.\n\n", "meta": {"author": "klara-zielinska", "repo": "refocusing2", "sha": "f741a1bdb746b53d34435c61298261b846e6be38", "save_path": "github-repos/coq/klara-zielinska-refocusing2", "path": "github-repos/coq/klara-zielinska-refocusing2/refocusing2-f741a1bdb746b53d34435c61298261b846e6be38/refocusing_examples/lam_cl_es_no_tests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6967293870227509}}
{"text": "(* Copyright 2012-2015 by Adam Petcher.\t\t\t\t*\n * Use of this source code is governed by the license described\t*\n * in the LICENSE file at the root of the source tree.\t\t*)\n\n(* A theory of limits of a sequence *)\n\nSet Implicit Arguments.\n\nRequire Import Arith.\nRequire Import FCF.Fold.\nRequire Import List.\n\nRequire Import FCF.StdNat.\nRequire Import FCF.Rat.\n\nSection Limit.\n\n  Variable A : Set.\n  Variable eq : A -> A -> Prop.\n  Hypothesis eq_dec : forall (a1 a2 : A), \n    {eq a1 a2} + {~eq a1 a2}.\n  Hypothesis eq_refl : forall (a : A),\n    eq a a.\n  Hypothesis eq_symm : forall a1 a2,\n    eq a1 a2 ->\n    eq a2 a1.\n\n  Variable distance : A -> A -> A.\n  Hypothesis distance_comm : forall a1 a2,\n    eq (distance a1 a2) (distance a2 a1).\n  Variable half : A -> A.\n  Variable zero : A.\n  Hypothesis half_nz : forall (a : A),\n    ~eq a zero ->\n    ~eq (half a) zero.\n\n  Hypothesis distance_eq_zero : forall (a1 a2 : A),\n    eq a1 a2 <->\n    eq (distance a1 a2) zero.\n  Hypothesis distance_eq_compat : forall a1 a2 a3 a4,\n    eq a1 a3 ->\n    eq a2 a4 ->\n    eq (distance a1 a2) (distance a3 a4).\n \n\n  Variable le : A -> A -> Prop.\n  Hypothesis le_eq : forall (a1 a2 : A),\n    eq a1 a2 ->\n    le a1 a2.\n  Hypothesis le_trans : forall (a1 a2 a3 : A),\n    le a1 a2 ->\n    le a2 a3 ->\n    le a1 a3.\n  \n  (* all numbers positive *)\n  Hypothesis all_pos : forall (a : A),\n    le zero a.\n  Hypothesis le_impl_eq : forall (a1 a2 : A),\n    le a1 a2 ->\n    le a2 a1 ->\n    eq a1 a2.\n\n  Variable plus : A -> A -> A.\n  Variable plus_0_eq : forall (a1 a2 : A),\n    eq a2 zero ->\n    eq a1 (plus a1 a2).\n  Variable plus_le_compat : forall a1 a2 a3 a4,\n    le a1 a2 ->\n    le a3 a4 ->\n    le (plus a1 a3) (plus a2 a4).\n\n  Hypothesis triangle_inequality : forall (a1 a2 a3 : A),\n    le (distance a1 a2) (plus (distance a1 a3) (distance a3 a2)).\n  Hypothesis half_plus : forall (a : A),\n    eq (plus (half a) (half a)) a.\n  Hypothesis le_half : forall (a : A),\n    le a (half a) ->\n    eq a zero.\n\n  Theorem le_epsilon_zero : forall (a : A),\n    (forall (epsilon : A), ~eq epsilon zero -> le a epsilon) ->\n    eq a zero.\n    \n    intuition.\n    \n    destruct (eq_dec a zero).\n    trivial.\n    \n    exfalso.\n    specialize (H (half a)).\n    apply f.\n    eapply le_half.\n    apply H.\n    eapply half_nz.\n    trivial.\n  Qed.\n\n\n  Definition left_total(r : nat -> A -> Prop) :=\n    forall n, exists a, r n a.\n\n  Definition functional(r : nat -> A -> Prop) :=\n    forall n a1 a2,\n      r n a1 ->\n      r n a2 ->\n      eq a1 a2.\n    \n\n  Definition inf_limit(f : nat -> A -> Prop)(a : A) :=\n    forall (epsilon : A),\n      ~eq epsilon zero -> \n      exists n : nat,\n        forall (n' : nat),\n          n' >= n ->\n          forall a',\n            f n' a' ->\n            le (distance a' a) epsilon.\n\n    (* Note: if the codomain of the relation is empty (after any point), then we can assign any limit to it. *)\n\n  (* We could define inf_limit in terms of inf_limit_2, but inf_limit_2 only shows up in proofs, while inf_limit shows up in top-level definitions. *)\n  Definition inf_limit_2(f f' : nat -> A -> Prop) :=\n    forall (epsilon : A),\n      ~eq epsilon zero -> \n      exists n : nat,\n        forall (n' : nat),\n          n' >= n ->\n          forall a a',\n            f n' a ->\n            f' n' a' ->\n            le (distance a a') epsilon.\n  \n  Theorem inf_limit_2_const : forall (f : nat -> A -> Prop)(a : A),\n    inf_limit_2 f (fun x => eq a) <->\n    inf_limit f a.\n\n    intuition.\n  Abort.\n\n\n(*  limits are unique for left-total relations *)\n  Theorem limit_eq_h : forall f epsilon a1 a2,\n    left_total f ->\n    ~eq epsilon zero ->\n    inf_limit f a1 ->\n    inf_limit f a2 ->\n    le (distance a1 a2) epsilon.\n    \n   (*  remember half as h. *)\n\n    intuition.\n    unfold inf_limit in *.\n    intuition.\n    specialize (H1 (half epsilon)).\n    specialize (H2 (half epsilon)).\n\n    destruct H1.\n    intuition.\n    eapply half_nz; eauto.\n\n    destruct H2.\n    intuition.\n    eapply half_nz; eauto.\n\n    destruct (H (max x x0)).\n    specialize (H1 (max x x0)).\n    specialize (H2 (max x x0)).\n\n    eapply le_trans.\n    eapply (triangle_inequality _ _ x1).\n    eapply le_trans.\n    eapply plus_le_compat.\n    eapply le_trans.\n    eapply le_eq.\n    eapply distance_comm.\n    eapply H1.\n    eapply Max.max_lub_l; eauto.\n    trivial.\n    eapply H2.\n    eapply Max.max_lub_r; eauto.\n    trivial.\n    eapply le_eq.\n    eapply half_plus.\n  Qed.    \n\n  Theorem limits_eq : forall f a1 a2,\n    left_total f ->\n    inf_limit f a1 ->\n    inf_limit f a2 ->\n    eq a1 a2.\n\n    intuition.\n    eapply distance_eq_zero.\n\n    eapply le_epsilon_zero.\n    intuition.\n \n    eapply limit_eq_h; eauto.\n  Qed.\n\n  Theorem limit_f_eq : forall f1 f2 a,\n    inf_limit f1 a ->\n    (forall n a', (f1 n a' <-> f2 n a')) ->\n    inf_limit f2 a.\n\n    unfold inf_limit; intuition.\n\n    destruct (H epsilon).\n    trivial.\n    exists x.\n    intuition.\n    eapply H2.\n    eapply H3.\n    eapply H0.\n    trivial.\n  Qed.\n\nEnd Limit.\n\n\n(* limits for Rat *)\nLocal Open Scope rat_scope.\n\nDefinition rat_inf_limit(f : nat -> Rat -> Prop)(r : Rat) :=\n  inf_limit eqRat ratDistance rat0 leRat f r.\n\nDefinition rat_inf_limit_2(f1 f2 : nat -> Rat -> Prop) :=\n  inf_limit_2 eqRat ratDistance rat0 leRat f1 f2.\n\nDefinition rat_limits_eq :=\n  limits_eq eq_Rat_dec ratDistance_comm ratHalf ratHalf_ne_0 ratIdentityIndiscernables eqRat_impl_leRat leRat_trans ratAdd ratAdd_leRat_compat ratTriangleInequality ratHalf_add le_ratHalf_0.\n\nRequire Import Arith.\n\nTheorem rat_inf_limit_2_trans : forall f1 f2 f3,\n  rat_inf_limit_2 f1 f2 ->\n  rat_inf_limit_2 f2 f3 ->\n  left_total f2 ->\n  rat_inf_limit_2 f1 f3.\n  \n  unfold rat_inf_limit_2, inf_limit_2; intuition.\n  edestruct (H (ratHalf epsilon)).\n  eapply ratHalf_ne_0; intuition.\n  edestruct (H0 (ratHalf epsilon)); eauto.\n  eapply ratHalf_ne_0.\n  intuition.\n  exists (max x x0).\n  intuition.\n  destruct (H1 n').\n  eapply leRat_trans.\n  eapply ratDistance_le_trans.\n  eapply H3.\n  eapply Max.max_lub_l.\n  eapply H5.\n  trivial.\n  eapply H8.\n  eapply H4.\n  eapply Max.max_lub_r.\n  eapply H5.\n  eauto.\n  trivial.\n  eapply eqRat_impl_leRat.\n  eapply ratHalf_add.\nQed.\n\n\n\nLemma rat_inf_limit_squeeze : forall (f1 f2 f: nat -> Rat -> Prop) c (v : Rat),\n  rat_inf_limit f1 v ->\n  rat_inf_limit f2 v ->\n  (forall n a a1, n >= c -> f n a -> f1 n a1 -> a1 <= a) ->\n  (forall n a a2, n >= c -> f n a -> f2 n a2 -> a <= a2) ->\n  left_total f1 ->\n  left_total f2 ->\n  rat_inf_limit f v.\n\n  unfold rat_inf_limit, inf_limit in *.\n  intuition.\n  destruct (H epsilon); intuition.\n  destruct (H0 epsilon); intuition.\n  exists (max c (max x x0)).\n  intuition.\n\n  destruct (H3 n').\n  destruct (H4 n').\n  eapply leRat_trans.\n  eapply ratDistance_le_max.\n  eapply H1.\n  eapply Max.max_lub_l.\n  eauto.\n  eapply H9.\n  eapply H10.\n\n  eapply H2.\n  eapply Max.max_lub_l.\n  eauto.\n  eapply H9.\n  eapply H11.\n\n  eapply maxRat_leRat_same; eauto using Max.max_lub_l, Max.max_lub_r.\n\nQed.\n\nLemma rat_inf_limit_div_2 : forall (f : nat -> Rat -> Prop)(v : Rat),\n  rat_inf_limit f v ->\n  rat_inf_limit (fun n => (f (div2 n))) v.\n\n  unfold rat_inf_limit, inf_limit.\n  intuition.\n  destruct (H epsilon); intuition.\n  \n  econstructor.\n  intuition.\n  specialize (H1 (div2 n')).\n  eapply H1.\n\n  eapply div2_ge; eauto.\n  eauto.\nQed.\n\nLemma rat_inf_limit_sum : forall (f1 f2 : nat -> Rat -> Prop) v1 v2,\n  left_total f1 ->\n  left_total f2 ->\n  rat_inf_limit f1 v1 ->\n  rat_inf_limit f2 v2 ->\n  rat_inf_limit (fun n => (ratAdd_rel (f1 n) (f2 n))) (v1 + v2).\n\n  unfold rat_inf_limit, inf_limit in *.\n  intuition.\n  edestruct (H1 (ratHalf epsilon)).\n  eapply ratHalf_ne_0.\n  intuition.\n  edestruct (H2 (ratHalf epsilon)).\n  eapply ratHalf_ne_0.\n  intuition.\n  exists (Max.max x x0).\n  intuition.\n  unfold ratAdd_rel in *.\n  destruct (H n').\n  destruct (H0 n').\n  rewrite H7; eauto.\n  eapply leRat_trans.\n  eapply rat_distance_of_sum.\n  rewrite H4.\n  rewrite H5.\n  rewrite ratHalf_add.\n  intuition.\n  eapply Max.max_lub_r.\n  eauto.\n  trivial.\n  eapply Max.max_lub_l.\n  eauto.\n  trivial.\nQed.\n\n\n\nLemma rat_inf_limit_difference : forall (f1 f2 : nat -> Rat -> Prop) c1 c2,\n  left_total f1 ->\n  left_total f2 ->\n  rat_inf_limit f1 c1 ->\n  rat_inf_limit f2 c2 -> \n  rat_inf_limit (fun n => (ratSubtract_rel (f1 n) (f2 n))) (ratSubtract c1 c2).\n\n  unfold rat_inf_limit, inf_limit in *.\n  intuition.\n\n  destruct (le_Rat_dec c1 c2).\n\n  edestruct (H1 (ratHalf epsilon)).\n  eapply ratHalf_ne_0.\n  intuition.  \n  edestruct (H2 (ratHalf epsilon)).\n  eapply ratHalf_ne_0.\n  intuition. \n  exists (Max.max x x0).\n  intuition.\n  unfold ratSubtract_rel in *.\n  destruct (H n').\n  destruct (H0 n').\n  rewrite H7; eauto.\n  rewrite (ratSubtract_0 l).\n  eapply ratDistance_0_r_le.\n  \n  eapply leRat_trans.\n  eapply ratSubtract_partition_leRat.\n  \n  eapply ratSubtract_ratDistance_le.\n  2:{\n    rewrite H4.\n    rewrite ratHalf_add.\n    intuition.\n    eapply Max.max_lub_l.\n    eauto.\n    trivial.\n  }\n  eapply leRat_trans.\n  eapply ratSubtract_partition_leRat.\n  rewrite ratSubtract_0.\n  eapply leRat_refl.\n  eapply l.\n  eapply ratSubtract_ratDistance_le.\n  rewrite ratDistance_comm.\n  rewrite H5.\n  rewrite <- ratAdd_0_l.\n  intuition.\n  eapply Max.max_lub_r.\n  eauto.\n  trivial.\n\n  edestruct (H1 (minRat (ratHalf epsilon) (ratHalf (ratSubtract c1 c2)))).\n  intuition.\n  unfold minRat in *.\n  destruct (bleRat (ratHalf epsilon) (ratHalf (ratSubtract c1 c2))).\n  eapply ratHalf_ne_0 in H4;\n  intuition.\n  eapply ratHalf_ne_0 in H4;\n  intuition.\n  eapply n.\n  eapply ratSubtract_0_inv.\n  trivial.\n\n  edestruct (H2 (minRat (ratHalf epsilon) (ratHalf (ratSubtract c1 c2)))).\n  intuition.\n  unfold minRat in *.\n  destruct (bleRat (ratHalf epsilon) (ratHalf (ratSubtract c1 c2))).\n  eapply ratHalf_ne_0 in H5;\n  intuition.\n  eapply ratHalf_ne_0 in H5;\n  intuition.\n  eapply n.\n  eapply ratSubtract_0_inv.\n  trivial.\n\n  exists (Max.max x x0).\n  intuition.\n  destruct (H n').\n  destruct (H0 n').\n  unfold ratSubtract_rel in *.\n  rewrite H7; eauto.\n  assert (x2 <= x1).\n  eapply leRat_trans.\n  eapply ratDistance_le_sum.\n  eapply H5.\n  eapply Max.max_lub_r.\n  eauto.\n  trivial.\n  eapply leRat_trans.\n  eapply ratAdd_leRat_compat.\n  eapply leRat_refl.\n\n  eapply minRat_le_r.\n  eapply (leRat_ratAdd_same_r (ratHalf (ratSubtract c1 c2))).\n  rewrite ratAdd_assoc.\n  rewrite ratHalf_add.\n  rewrite ratSubtract_ratAdd_inverse_2.\n  eapply ratDistance_le_sum.\n  eapply leRat_trans.\n  rewrite ratDistance_comm.\n  eapply H4.\n  eapply Max.max_lub_l.\n  eauto.\n  trivial.\n  eapply minRat_le_r.\n  case_eq (bleRat c1 c2); intuition.\n  eapply bleRat_total.\n  trivial.\n\n  eapply leRat_trans.\n  eapply rat_distance_of_difference.\n  trivial.\n  case_eq (bleRat c1 c2); intuition.\n  eapply bleRat_total.\n  trivial.\n\n  eapply H4.\n  eapply Max.max_lub_l.\n  eauto.\n  trivial.\n\n  eapply H5.\n  eapply Max.max_lub_r.\n  eauto.\n  trivial.\n\n  rewrite minRat_le_l.\n  rewrite ratHalf_add.\n  intuition.\nQed.\n\nLemma rat_inf_limit_product : forall (f1 f2 : nat -> Rat -> Prop) c1 c2,\n  left_total f1 ->\n  left_total f2 ->\n  rat_inf_limit f1 c1 ->\n  rat_inf_limit f2 c2 -> \n  rat_inf_limit (fun n => (ratMult_rel (f1 n) (f2 n))) (c1 * c2).\n\n  (* This is the proof found at http://planetmath.org/ProofOfLimitRuleOfProduct.html *)\n\n  unfold rat_inf_limit, inf_limit in *.\n  intuition.\n\n  edestruct (H1 ((ratInverse (1 + c2)) * epsilon * (1/ 2))).\n  intuition.\n  apply ratMult_0 in H4.\n  intuition.\n  apply ratMult_0 in H5.\n  intuition.\n  eapply ratInverse_nz.\n  eauto.\n\n  edestruct (H2 ((ratInverse (1 + c1)) * epsilon * (1 / 2))).\n  intuition.\n  apply ratMult_0 in H5.\n  intuition.\n  apply ratMult_0 in H6.\n  intuition.\n  eapply ratInverse_nz.\n  eauto.\n\n  edestruct (H2 1).\n  intuition.\n\n  exists (maxList (x :: x0 :: x1 :: nil)).\n  intuition.\n  unfold ratMult_rel in *.\n  edestruct H.\n  edestruct H0.\n  rewrite H8; eauto.\n  eapply leRat_trans.\n  eapply (ratTriangleInequality _ _ (c1 * x3)).\n\n  rewrite ratMult_ratDistance_factor_r.\n  rewrite ratMult_ratDistance_factor_l.\n  rewrite ratMult_comm.\n  eapply leRat_trans.\n  eapply ratAdd_leRat_compat.\n  eapply ratMult_leRat_compat.\n  eapply ratDistance_le_sum.\n  eapply H6; [idtac | eapply H10].\n  eapply le_trans.\n  eapply (maxList_correct (x :: x0 :: x1 :: nil)).\n  simpl.\n  intuition.\n  trivial.\n  eapply H4; [idtac | eapply H9].\n  eapply le_trans.\n  eapply (maxList_correct (x :: x0 :: x1 :: nil)).\n  simpl.\n  intuition.\n  trivial.\n  eapply ratMult_leRat_compat.\n  eapply (ratAdd_any_leRat_l 1).\n  eapply leRat_refl.\n  eapply H5; [idtac | eapply H10].\n  eapply le_trans.\n  eapply (maxList_correct (x :: x0 :: x1 :: nil)).\n  simpl.\n  intuition.\n  trivial.\n  eapply eqRat_impl_leRat.\n  repeat rewrite <- ratMult_assoc.\n  rewrite (ratAdd_comm c2).\n  rewrite (ratAdd_comm c1).\n  rewrite (ratMult_assoc ((1 + c2) * (ratInverse (1 + c2)))).\n  rewrite (ratMult_assoc ((1 + c1) * (ratInverse (1 + c1)))).\n  rewrite <- ratMult_distrib_r.\n  rewrite (ratMult_comm (1 + c2)).\n  rewrite (ratMult_comm (1 + c1)).\n  repeat rewrite ratInverse_prod_1.\n  rewrite ratMult_2.\n  rewrite ratMult_1_l.\n  rewrite ratMult_comm.\n  rewrite ratMult_assoc.\n\n  rewrite ratMult_eq_rat1.\n  eapply ratMult_1_r.\n\n  intuition.\n  assert (1 <= 0).\n  eapply leRat_trans.\n  eapply (ratAdd_any_leRat_r c1).\n  eapply leRat_refl.\n  eapply eqRat_impl_leRat.\n  rewrite ratAdd_comm.\n  trivial.\n  intuition.\n\n  intuition.\n  assert (1 <= 0).\n  eapply leRat_trans.\n  eapply (ratAdd_any_leRat_r c2).\n  eapply leRat_refl.\n  eapply eqRat_impl_leRat.\n  rewrite ratAdd_comm.\n  trivial.\n  intuition.\n\nQed.\n\nDefinition rat_limit(f : Rat -> Rat -> Prop)(p L : Rat) :=\n  forall epsilon, \n    ~ (epsilon == 0) ->\n    exists delta, (~delta == 0) /\\\n      forall x v,\n        f x v ->\n        (ratDistance x p) <= delta ->\n        (ratDistance v L) <= epsilon.\n\nDefinition continuous_at(f : Rat -> Rat -> Prop)(c : Rat) :=\n  forall v, f c v ->\n    rat_limit f c v.\n\nLemma rat_inf_limit_comp : forall (f : nat -> Rat -> Prop)(g : Rat -> Rat -> Prop) a v,\n  rat_inf_limit f a ->\n  g a v ->\n  continuous_at g a ->\n  left_total f ->\n  rat_inf_limit (fun n r => forall v', (f n v' -> g v' r)) v.\n\n  unfold continuous_at, rat_limit, rat_inf_limit, inf_limit in *.\n  intuition.\n  edestruct H1; eauto.\n  intuition.\n  destruct (H x).\n  trivial.\n  exists x0.\n  intuition.\n  destruct (H2 n').\n  eapply H6.\n  eauto.\n  eapply H4.\n  eapply H7.\n  trivial.\nQed.\n\nLemma rat_inf_limit_trans : forall (f1 f2 : nat -> Rat -> Prop) a,\n  rat_inf_limit_2 f1 f2 ->\n  rat_inf_limit f2 a ->\n  left_total f2 ->\n  rat_inf_limit f1 a.\n\n  intuition.\n  unfold rat_inf_limit_2, inf_limit_2, rat_inf_limit, inf_limit in *.\n  intuition.\n  edestruct (H (ratHalf epsilon)).\n  eapply ratHalf_ne_0.\n  intuition.  \n  edestruct (H0 (ratHalf epsilon)).\n  eapply ratHalf_ne_0.\n  intuition.  \n  exists (Max.max x x0).\n  intuition.\n  destruct (H1 n').\n  eapply leRat_trans.\n  eapply ratTriangleInequality.\n  rewrite H3.\n  rewrite H4.\n  rewrite ratHalf_add.\n  intuition.\n  eapply Max.max_lub_r.\n  eauto.\n  eauto.\n  eapply Max.max_lub_l.\n  eauto.\n  trivial.\n  trivial.\nQed.\n\nLemma rat_inf_limit_eq : forall f a1 a2,\n  rat_inf_limit f a1 ->\n  a1 == a2 ->\n  rat_inf_limit f a2.\n\n  unfold rat_inf_limit, inf_limit in *.\n  intuition.\n  edestruct H; eauto.\n  exists x.\n  intuition.\n  rewrite <- H0.\n  eapply H2.\n  eapply H3.\n  trivial.\nQed.\n\nLemma rat_inf_limit_const : forall (f : Rat -> Prop) a,\n  f a ->\n  (forall a1 a2, f a1 -> f a2 -> a1 == a2) ->\n  rat_inf_limit (fun _ => f) a.\n\n  unfold rat_inf_limit, inf_limit in *.\n  intuition.\n  exists O.\n  intuition.\n  eapply leRat_trans.\n  eapply eqRat_impl_leRat.\n  rewrite <- ratIdentityIndiscernables.\n  eauto.\n  eapply rat0_le_all.\n\nQed.\n\n\nLemma rat_inf_limit_summation : forall (A : Set)(f1 : A -> nat -> Rat -> Prop)(f2 : A -> Rat)(ls : list A),\n  (forall a, rat_inf_limit (f1 a) (f2 a)) ->\n  (forall a, left_total (f1 a)) ->\n  (forall a n r1 r2, f1 a n r1 -> f1 a n r2 -> r1 == r2) ->\n  rat_inf_limit\n  (fun n : nat => sumList_rel (fun a0 : A => f1 a0 n) ls)\n  (sumList ls f2).\n\n  induction ls; intuition.\n  unfold rat_inf_limit, inf_limit.\n  intuition.\n  exists O.\n  intuition.\n  inversion H4; clear H4; subst.\n  unfold sumList.\n  simpl.\n  rewrite H5.\n  eapply leRat_trans.\n  eapply eqRat_impl_leRat.\n  rewrite <- ratIdentityIndiscernables.\n  intuition.\n  eapply rat0_le_all.\n\n  eapply (@rat_inf_limit_trans _ (fun n : nat => ratAdd_rel (f1 a n) (sumList_rel (fun a0 : A => f1 a0 n) ls))).\n  unfold rat_inf_limit_2, inf_limit_2.\n  intuition.\n  exists O.\n  intuition.\n  inversion H5; clear H5; subst.\n  unfold ratAdd_rel in *.\n  rewrite H6.\n  rewrite H12.\n  eapply leRat_trans.\n  eapply eqRat_impl_leRat.\n  rewrite <- ratIdentityIndiscernables.\n  eapply eqRat_refl.\n  eapply rat0_le_all.\n  trivial.\n  trivial.\n  eapply rat_inf_limit_eq.\n  eapply rat_inf_limit_sum.\n  eauto.\n  unfold left_total; intuition.\n  eapply sumList_rel_left_total.\n  intuition.\n  eapply H0.\n  eapply H.\n  eauto.\n  unfold sumList.\n  simpl.\n  symmetry.\n  rewrite fold_add_body_eq; [idtac | eapply ratAdd_comm | idtac].\n  rewrite fold_add_init.\n  eapply eqRat_refl.\n  intuition.\n\n  unfold left_total; intuition.\n  eapply ratAdd_rel_left_total.\n  eapply H0.\n  eapply sumList_rel_left_total.\n  intuition.\n  eapply H0.\n  eauto.\n  intuition.\n  eapply sumList_rel_func; eauto.\n  intuition.\n  eauto.\nQed.\n  \nLemma ratInverse_continuous : forall c,\n  ~ c == 0 ->\n  continuous_at (fun v' r : Rat => r == ratInverse v') c.\n  \n  unfold continuous_at, rat_limit in *.\n  intuition.\n\n  exists (minRat (c * (1 / 2)) (c * (1/2) * c * epsilon)).\n  intuition.\n  unfold minRat in *.\n  destruct (bleRat (c * (1 / 2)) (c * (1 / 2) * c * epsilon)).\n  apply ratMult_0 in H2; intuition.\n  apply ratMult_0 in H2; intuition.\n  apply ratMult_0 in H3; intuition.\n  apply ratMult_0 in H2; intuition.\n\n  rewrite H2.\n  rewrite H0.\n  \n  assert (ratDistance x c <= c * (1/2)).\n  eapply leRat_trans.\n  eapply H3.\n  eapply minRat_le_l.\n\n  assert (ratSubtract c (c * (1/2)) <= x).\n  eapply ratDistance_ge_difference.\n  rewrite ratDistance_comm.\n  trivial.\n  assert (x <= c + (c * (1/2))).\n  eapply ratDistance_le_sum.\n  trivial.\n  assert (c * (1/2) <= x).\n\n  rewrite <- (ratSubtract_half).\n  trivial.\n\n  clear H5.\n  assert (x <= c * (3/2)).\n\n  rewrite ratMult_ratAdd_cd in H6.\n  simpl in *.\n  trivial.\n\n  clear H6.\n  assert (ratInverse x <= ratInverse (c * (1 / 2))).\n  apply ratInverse_leRat.\n  intuition.\n  apply ratMult_0 in H6; intuition.\n  trivial.\n\n  rewrite ratDistance_ratInverse.\n  rewrite H3.\n  rewrite minRat_le_r.\n\n  rewrite ratInverse_ratMult; intuition.\n  rewrite H6.\n  rewrite ratInverse_ratMult; intuition.\n  rewrite ratMult_comm.\n  repeat rewrite <- ratMult_assoc.\n  rewrite (ratMult_assoc ((ratInverse c) * (ratInverse (1/2)))).\n  rewrite ratInverse_prod_1; intuition.\n  rewrite ratMult_1_r.\n  rewrite (ratMult_assoc (ratInverse c)).\n  rewrite ratInverse_prod_1; intuition.\n  rewrite ratMult_1_r.\n  rewrite ratInverse_prod_1; intuition.\n  rewrite ratMult_1_l.\n  intuition.\n  rewrite H8 in H7.\n  assert (c * (1 / 2) == 0).\n  eapply leRat_impl_eqRat.\n  trivial.\n  eapply rat0_le_all.\n  apply ratMult_0 in H9; intuition.\n  intuition.\n  rewrite H8 in H7.\n  assert (c * (1 / 2) == 0).\n  eapply leRat_impl_eqRat.\n  trivial.\n  eapply rat0_le_all.\n  apply ratMult_0 in H9; intuition.\n  intuition.\nQed.\n\nLemma rat_inf_limit_ratInverse : forall (f : nat -> Rat -> Prop) a v,\n  rat_inf_limit f a ->\n  ~ a == 0 ->\n  ratInverse a == v ->\n  left_total f ->\n  rat_inf_limit (fun n => ratInverse_rel (f n)) v.\n  \n  intuition.\n  eapply rat_inf_limit_comp.\n  eauto.\n  symmetry.\n  trivial.\n  eapply ratInverse_continuous.\n  trivial.\n  trivial.\n  \nQed.\n\nLemma rat_inf_limit_exp_0 : forall (f : nat -> Rat -> Prop) a,\n  rat_inf_limit f a ->\n  ~ 1 <= a ->\n  (forall n, exists r, f n r) ->\n  rat_inf_limit (fun n => (expRat_rel (f n) n)) 0.\n\n  intuition.\n  unfold rat_inf_limit, inf_limit in *.\n  intuition.\n  edestruct (H (1 / 2 * (ratSubtract 1 a))); eauto.\n  intuition.\n  apply ratMult_0 in H3.\n  intuition.\n  eapply H0.  \n  eapply ratSubtract_0_inv.\n  trivial.\n\n  edestruct (@expRat_le_exp_exists (a + (1 / 2) * (ratSubtract 1 a)) epsilon).\n  eapply half_distance_1_le; trivial.\n  trivial.\n\n  exists (Max.max x x0).\n  intuition.\n  unfold expRat_rel in *.\n  destruct (H1 n').\n  rewrite H6; eauto.\n\n  apply ratDistance_0_r_le.\n  eapply leRat_trans.\n  eapply expRat_leRat_compat.\n  eapply ratDistance_le_sum.\n  eapply H3.\n  eapply Max.max_lub_l.\n  eauto.\n  trivial.\n  \n  eapply expRat_le'.\n  eauto.\n  eapply half_distance_1_le; trivial.\n  eapply Max.max_lub_r.\n  eauto.\n \nQed.\n\nLemma power_series_limit_2 : forall (f : nat -> Rat -> Prop) a,\n  rat_inf_limit f a ->\n  (forall n v, f n v -> ~ 1 <= v) ->\n  ~ 1 <= a ->\n  (forall n, exists v, f n v) ->\n  (forall n v1 v2, f n v1 -> f n v2 -> v1 == v2) ->\n  rat_inf_limit \n  (fun n => sumList_rel \n    (fun i => expRat_rel (f n) i)\n    (getNats O n))\n  (ratInverse (ratSubtract 1 a)).\n\n  intuition.\n  \n  eapply (@rat_inf_limit_trans _ (fun n => (ratMult_rel (ratSubtract_rel (eqRat 1) (expRat_rel (f n) n)) (ratInverse_rel (ratSubtract_rel (eqRat 1) (f n)))))).\n  unfold rat_inf_limit_2, inf_limit_2.\n  intuition.\n  exists (S O).\n  intuition.\n  destruct (H2 n'). \n  eapply leRat_trans.\n  eapply eqRat_impl_leRat.\n  rewrite <- ratIdentityIndiscernables.\n  eapply sum_power_series.\n  assert (n' > O).\n  lia.\n  eapply H9.\n  econstructor.\n  eapply H8.\n  eapply H3.\n  intuition.\n  eapply H0.\n  eapply H9.\n  trivial.\n  trivial.\n  trivial.\n  eapply rat0_le_all.\n\n  eapply rat_inf_limit_eq.\n  eapply rat_inf_limit_product.\n    \n  unfold left_total, ratSubtract_rel, expRat_rel. intuition.\n  destruct (H2 n).\n  exists (ratSubtract 1 (expRat x n)).\n  intuition.\n  eapply ratSubtract_eqRat_compat; eauto.\n  symmetry.\n  eapply H6.\n  trivial.\n\n  unfold left_total, ratInverse_rel, ratSubtract_rel. intuition.\n  destruct (H2 n).\n  exists (ratInverse (ratSubtract 1 x)).\n  intuition.\n  eapply ratInverse_eqRat_compat.\n  intuition.\n  eapply H0.\n  eauto.\n  eapply ratSubtract_0_inv.\n  trivial.\n\n  symmetry.\n  eapply H5; intuition.\n  \n  eapply rat_inf_limit_difference.\n\n  unfold left_total; intuition.\n  exists 1; intuition.\n  \n  unfold left_total, expRat_rel; intuition.\n  destruct (H2 n).\n  exists (expRat x n).\n  intuition.\n\n  eapply expRat_eqRat_compat; eauto.\n\n  eapply rat_inf_limit_const.\n  eapply eqRat_refl.\n  intuition.\n  rewrite <- H4.\n  rewrite H5.\n  intuition.\n\n  eapply rat_inf_limit_exp_0.\n  eauto.\n  trivial.\n  trivial.\n\n  eapply rat_inf_limit_ratInverse.\n  eapply rat_inf_limit_difference.\n  unfold left_total; intuition.\n  econstructor.\n  eapply eqRat_refl.\n  unfold left_total; intuition.\n  \n  eapply rat_inf_limit_const.\n  eapply eqRat_refl.\n  intuition.\n  rewrite <- H4.\n  rewrite H5.\n  intuition.\n  eauto.\n  intuition.\n  eapply H1.\n  eapply ratSubtract_0_inv.\n  trivial.\n  \n  eapply eqRat_refl.\n  unfold left_total; intuition.\n  destruct (H2 n).\n  exists (ratSubtract 1 x).\n  unfold ratSubtract_rel; intuition.\n  eapply ratSubtract_eqRat_compat; eauto.\n  rewrite ratSubtract_0_r.\n  rewrite ratMult_1_l.\n  intuition.\n\n  unfold left_total, ratMult_rel, ratSubtract_rel, expRat_rel, ratInverse_rel.\n  intuition.\n  destruct (H2 n).\n  exists ((ratSubtract 1 (expRat x n)) * (ratInverse (ratSubtract 1 x))).\n  intuition.\n  eapply ratMult_eqRat_compat.\n  symmetry.\n  eapply H5;\n  intuition.\n  eapply expRat_eqRat_compat.\n  eauto.\n  symmetry.\n  eapply H6.\n  intuition.\n  eapply ratSubtract_eqRat_compat; intuition.\n  eauto.\nQed.\n\nLemma rat_inf_limit_mono  : forall (f : nat -> Rat -> Prop) (g : nat -> nat)(v : Rat),\n    rat_inf_limit f v -> \n    (forall n1 n2, n1 <= n2 -> g n1 <= g n2)%nat ->\n    (forall y, exists x, g x = y) ->\n    rat_inf_limit (fun n => f (g n)) v.\n\n  unfold rat_inf_limit, inf_limit.\n  intuition.\n  destruct (H epsilon); intuition.\n  destruct (H1 x).\n  econstructor.\n  intuition.\n  eapply (H3 (g n')).\n  eapply le_trans.\n  2:{\n    eapply H0.\n    eapply H5.\n  }\n  rewrite <- H4.\n  eapply le_refl.\n  trivial.\nQed.\n\n\nLemma rat_inf_limit_sqrt:\n  forall (f : nat -> Rat -> Prop) (v : Rat),\n    rat_inf_limit f v -> \n    rat_inf_limit (fun n => f (Nat.sqrt n)) v.\n\n  intuition.\n  eapply rat_inf_limit_mono.\n  trivial.\n  intuition.\n  eapply Nat.sqrt_le_mono.\n  trivial.\n  intuition.\n  econstructor.\n  eapply Nat.sqrt_square.\nQed.\n", "meta": {"author": "adampetcher", "repo": "fcf", "sha": "10a39a091eb695daba8175cb59bf481dd85d8ce2", "save_path": "github-repos/coq/adampetcher-fcf", "path": "github-repos/coq/adampetcher-fcf/fcf-10a39a091eb695daba8175cb59bf481dd85d8ce2/src/FCF/Limit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6967293851332832}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\nRequire Import List Arith Max Lia Wellfounded Bool.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import list_focus utils_tac utils_list utils_nat.\n\nSet Implicit Arguments.\n\n(* We show that unbounded decidable predicates are exactly\n    the direct images of strictly increasing sequences nat -> nat \n\n    Hence, this gives an easy construction of the sequence\n    of all primes ...\n\n*)\n\nSection list_choose_d.\n\n  Variable (X : Type) (P Q : X -> Prop).\n\n  Theorem list_choose_d l : (forall x, In x l -> P x \\/ Q x)\n                           -> (exists x, In x l /\\ P x)\n                           \\/ forall x, In x l -> Q x.\n  Proof.\n    induction l as [ | x l IHl ]; intros Hl.\n    + right; intros _ [].\n    + destruct (Hl x) as [ H1 | H1 ].\n      * left; auto.\n      * left; exists x; simpl; auto.\n      * destruct IHl as [ (y & H2 & H3) | H2 ].\n        - intros; apply Hl; right; auto.\n        - left; exists y; simpl; auto.\n        - right; intros ? [ <- | ]; auto.\n  Qed.\n\nEnd list_choose_d.\n\nSection bounded_choose_d.\n\n  Variable (P Q : nat -> Prop).\n\n  Theorem bounded_choose_d n : (forall x, x < n -> P x \\/ Q x)\n                           -> (exists x, x < n /\\ P x)\n                           \\/ forall x, x < n -> Q x.\n  Proof.\n    intros H.\n    destruct list_choose_d with (P := P) (Q := Q) (l := list_an 0 n)\n      as [ (x & H1 & H2) | H1 ].\n    + intro; rewrite list_an_spec; intro; apply H; lia.\n    + left; exists x; split; auto.\n      apply list_an_spec in H1; lia.\n    + right; intros x Hx; apply H1, list_an_spec; lia.\n  Qed. \n\nEnd bounded_choose_d.\n\nSection bounded_min.\n\n  Variable (P Q : nat -> Prop).\n\n  Theorem bounded_min_d n :   (forall x, x < n -> P x \\/ Q x)\n                           -> (exists x, x < n /\\ P x /\\ forall y, y < x -> Q y)\n                           \\/ forall x, x < n -> Q x.\n  Proof.\n    induction n as [ | n IHn ]; intros Hn.\n    + right; intros; lia.\n    + destruct IHn as [ (x & H1 & H2 & H3) | H1 ].\n      * intros; apply Hn; lia.\n      * left; exists x; msplit 2; auto; lia.\n      * destruct (Hn n); auto.\n        - left; exists n; msplit 2; auto.\n        - right; intros x Hx.\n          destruct (eq_nat_dec x n); subst; auto.\n          apply H1; lia.\n  Qed.\n\nEnd bounded_min.\n\nSection list_choose_dep.\n\n  Variable (X : Type) (P Q : X -> Prop).\n\n  Theorem list_choose_dep l : (forall x, In x l -> { P x } + { Q x })\n                           -> { x | In x l /\\ P x }\n                            + { forall x, In x l -> Q x }.\n  Proof.\n    induction l as [ | x l IHl ]; intros Hl.\n    + right; intros _ [].\n    + destruct (Hl x) as [ H1 | H1 ].\n      * left; auto.\n      * left; exists x; simpl; auto.\n      * destruct IHl as [ (y & H2 & H3) | H2 ].\n        - intros; apply Hl; right; auto.\n        - left; exists y; simpl; auto.\n        - right; intros ? [ <- | ]; auto.\n  Qed.\n\nEnd list_choose_dep.\n\n\nSection sinc_decidable.\n\n  Variable (P : nat -> Prop)\n           (f : nat -> nat) \n           (Hf : forall n, f n < f (S n))\n           (HP : forall n, P n <-> exists k, n = f k).\n\n  Let f_mono x y : x <= y -> f x <= f y.\n  Proof.\n    induction 1 as [ | y H IH ]; auto.\n    apply le_trans with (1 := IH), lt_le_weak, Hf.\n  Qed.\n\n  Let f_smono x y : x < y -> f x < f y.\n  Proof.\n    intros H; apply f_mono in H.\n    apply lt_le_trans with (2 := H), Hf.\n  Qed.\n\n  Let f_ge_n n : n <= f n.\n  Proof.\n    induction n as [ | n IHn ]; try lia.\n    apply le_trans with (2 := Hf _); lia.\n  Qed.\n\n  Let unbounded n : exists k, n <= k /\\ P k.\n  Proof. exists (f n); split; auto; rewrite HP; exists n; auto. Qed.\n\n  Let decidable n : { P n } + { ~ P n }.\n  Proof.\n    destruct (@bounded_search (S n) (fun i => f i = n))\n      as [ (i & H1 & H2) | H1 ].\n    + intros i _; destruct (eq_nat_dec (f i) n); tauto.\n    + left; rewrite HP; eauto.\n    + right; rewrite HP; intros (k & Hk).\n      symmetry in Hk; generalize Hk; apply H1.\n      rewrite <- Hk; apply le_n_S; auto.\n  Qed.\n\n  Theorem sinc_decidable : (forall n, exists k, n <= k /\\ P k)\n                         * (forall n, { P n } + { ~ P n }).\n  Proof. split; auto. Qed.\n\nEnd sinc_decidable.\n\nSection decidable_sinc.\n\n  Variable (P    : nat -> Prop)\n           (Punb : forall n, exists k, n <= k /\\ P k)\n           (Pdec : forall n, { P n } + { ~ P n }).\n\n  Let next n : { k | P k /\\ n <= k /\\ forall x, P x -> x < n \\/ k <= x }.\n  Proof.\n    destruct min_dec with (P := fun k => P k /\\ n <= k)\n      as (k & (H1 & H2) & H3).\n    + intros i; destruct (Pdec i); destruct (le_lt_dec n i); try tauto; right; intro; lia.\n    + destruct (Punb (S n)) as (k & H1 & H2).\n      exists k; split; auto; lia.\n    + exists k; repeat (split; auto).\n      intros x Hx.\n      destruct (le_lt_dec n x); try lia.\n      right; apply H3; auto.\n  Qed.\n\n  Let f := fix f n := match n with \n    | 0   => proj1_sig (next 0)\n    | S n => proj1_sig (next (S (f n)))\n  end.\n\n  Let f_sinc n : f n < f (S n).\n  Proof.\n    simpl.\n    destruct (next (S (f n))) as (?&?&?&?); auto.\n  Qed.\n\n  Let f_select x : { n | f n <= x < f (S n) } + { x < f 0 }.\n  Proof.\n    induction x as [ | x IHx ].\n    + destruct (eq_nat_dec 0 (f 0)) as [ H | H ].\n      * left; exists 0; rewrite H at 2 3; split; auto.\n      * right; lia.\n    + destruct IHx as [ (n & Hn) | Hx ].\n      * destruct (eq_nat_dec (S x) (f (S n))) as [ H | H ].\n        - left; exists (S n); rewrite H; split; auto.\n        - left; exists n; lia.\n      * destruct (eq_nat_dec (S x) (f 0)) as [ H | H ].\n        - left; exists 0; rewrite H; split; auto.\n        - right; lia.\n  Qed.\n \n  Let f_P n : P n <-> exists k, n = f k.\n  Proof.\n    split.\n    + intros Hn.\n      destruct (f_select n) as [ (k & Hk) | C ].\n      * simpl in Hk.\n        destruct (next (S (f k))) as (m & H1 & H2 & H3); simpl in Hk.\n        apply H3 in Hn.\n        destruct Hn as [ Hn | Hn ]; try lia.\n        exists k; lia.\n      * simpl in C.\n        destruct (next 0) as (m & H1 & H2 & H3); simpl in C.\n        apply H3 in Hn; lia.\n    + intros (k & Hk); subst.\n      induction k as [ | k IHk ]; simpl.\n      * destruct (next 0) as (m & H1 & H2 & H3); simpl; auto.\n      * destruct (next (S (f k))) as (m & H1 & H2 & H3); simpl; auto.\n  Qed.\n\n  Theorem decidable_sinc : { f | (forall n, f n < f (S n))\n                              /\\ (forall n, P n <-> exists k, n = f k) }.\n  Proof. exists f; auto. Qed.\n\nEnd decidable_sinc.\n\n(*\nCheck sinc_decidable.\nCheck decidable_sinc.\n*)\n\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/Shared/Libs/DLW/Utils/utils_decidable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6967293851332832}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_sameside2.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_10_12.\nRequire Export GeoCoq.Elements.OriginalProofs.proposition_07.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_erectedperpendicularunique : \n   forall A B C E, \n   Per A B C -> Per A B E -> OS C E A B ->\n   Out B C E.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists D, (BetS A B D /\\ Cong A B D B /\\ Cong A C D C /\\ neq B C)) by (conclude_def Per );destruct Tf as [D];spliter.\nassert (neq B E) by (conclude_def Per ).\nrename_H H;let Tf:=fresh in\nassert (Tf:exists H, (Out B E H /\\ Cong B H B C)) by (conclude lemma_layoff);destruct Tf as [H];spliter.\nassert (eq B B) by (conclude cn_equalityreflexive).\nassert (Col A B B) by (conclude_def Col ).\nassert (OS C H A B) by (conclude lemma_sameside2).\nassert (Per A B H) by (conclude lemma_8_3).\nassert (Cong B C B H) by (conclude lemma_congruencesymmetric).\nassert (Cong A C A H) by (conclude lemma_10_12).\nassert (Cong C A H A) by (forward_using lemma_congruenceflip).\nassert (Cong C B H B) by (forward_using lemma_congruenceflip).\nassert (~ eq A B).\n {\n intro.\n assert (Col A B C) by (conclude_def Col ).\n assert (nCol A B C) by (conclude lemma_rightangleNC).\n contradict.\n }\nassert (eq C H) by (conclude proposition_07).\nassert (Out B E C) by (conclude cn_equalitysub).\nassert (Out B C E) by (conclude lemma_ray5).\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_erectedperpendicularunique.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6967293755385615}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(**********************************************************************\n    Proth.v                        \n                                                                     \n    Proth's Test \n                                                                 \n    Definition: ProthTest              \n **********************************************************************)\nRequire Import ZArith.\nRequire Import ZCAux.\nRequire Import Pocklington.\n\nOpen Scope Z_scope.\n\nTheorem ProthTest: forall h k a, let n := h * 2 ^ k + 1 in 1 < a -> 0 < h < 2 ^k -> (a ^ ((n - 1) / 2) + 1) mod n = 0 -> prime n.\nintros h k a n; unfold n; intros H H1 H2.\nassert (Hu: 0 < h * 2 ^ k).\napply Zmult_lt_O_compat; auto with zarith.\nassert (Hu1: 0 < k).\ncase (Zle_or_lt k 0); intros Hv; auto.\ngeneralize H1 Hv; case k; simpl.\nintros (Hv1, Hv2); contradict Hv2; auto with zarith.\nintros p1 _ Hv1; contradict Hv1; auto with zarith.\nintros   p (Hv1, Hv2); contradict Hv2; auto with zarith.\napply PocklingtonCorollary1 with (F1 := 2 ^ k) (R1 := h); auto with zarith.\nring.\napply Zlt_le_trans with ((h + 1) * 2 ^ k); auto with zarith.\nrewrite Zmult_plus_distr_l; apply Zplus_lt_compat_l.\nrewrite Zmult_1_l; apply Zlt_le_trans with 2; auto with zarith.\nintros p H3 H4.\ngeneralize H2; replace (h * 2 ^ k + 1 - 1) with (h * 2 ^k); auto with zarith; clear H2; intros H2.\nexists a; split; auto; split.\npattern (h * 2 ^k) at 1; rewrite (Zdivide_Zdiv_eq  2 (h * 2 ^ k)); auto with zarith.\nrewrite (Zmult_comm 2); rewrite Zpower_mult; auto with zarith.\nrewrite Zpower_mod; auto with zarith.\nassert (tmp: forall p, p = (p + 1) -1); auto with zarith; rewrite (fun x => (tmp (a ^ x))).\nrewrite Zminus_mod; auto with zarith.\nrewrite H2.\nrewrite (Zmod_small 1); auto with zarith.\nrewrite <- Zpower_mod; auto with zarith.\nrewrite Zmod_small; auto with zarith.\nsimpl; unfold Zpower_pos; simpl; auto with zarith.\napply Z_div_pos; auto with zarith.\napply Zdivide_trans with (2 ^ k).\napply Zpower_divide; auto with zarith.\napply Zdivide_factor_l; auto with zarith.\napply Zis_gcd_gcd; auto with zarith.\napply Zis_gcd_intro; auto with zarith.\nintros x HD1 HD2.\nassert (Hd1: p = 2).\napply prime_div_Zpower_prime with (4 := H4); auto with zarith.\napply prime_2.\nassert (Hd2: (x | 2)).\nreplace 2 with ((a ^ (h * 2 ^ k / 2) + 1) - (a ^ (h * 2 ^ k/ 2) - 1)); auto with zarith.\napply Zdivide_minus_l; auto.\napply Zdivide_trans with (1 := HD2).\napply Zmod_divide; auto with zarith.\npattern 2 at 2; rewrite <- Hd1; auto.\nreplace 1 with ((h * 2 ^k + 1) - (h * 2 ^ k)); auto with zarith.\napply Zdivide_minus_l; auto.\napply Zdivide_trans with (1 := Hd2); auto.\napply Zdivide_trans with (2 ^ k).\napply Zpower_divide; auto with zarith.\napply Zdivide_factor_l; auto with zarith.\nQed.\n\n\nDefinition proth_test h k a :=\n  let n := h * 2 ^ k + 1 in \n   if (Z_lt_dec 1  a) then \n      if (Z_lt_dec 0 h) then\n        if (Z_lt_dec h (2 ^k)) then\n            if Z_eq_dec (Zpow_mod a  ((n - 1) / 2) n) (n - 1) then true\n            else false else false else false else false. \n\n \nTheorem ProthTestOp: forall h k a, proth_test h k a = true -> prime (h * 2 ^ k + 1).\nintros h k a; unfold proth_test.\nrepeat match goal with |- context[if ?X then _ else _] => case X end; try (intros; discriminate).\nintros H1 H2 H3 H4 _.\nassert (Hu: 0 < h * 2 ^ k).\napply Zmult_lt_O_compat; auto with zarith.\napply ProthTest with (a := a); auto.\nrewrite Zplus_mod; auto with zarith.\nrewrite <- Zpow_mod_Zpower_correct; auto with zarith.\nrewrite H1.\nrewrite (Zmod_small 1); auto with zarith.\nreplace (h * 2 ^ k + 1 - 1 + 1) with (h * 2 ^ k + 1); auto with zarith.\napply Zdivide_mod; auto with zarith.\napply Z_div_pos; auto with zarith.\nQed.\n\nTheorem prime5: prime 5.\nexact (ProthTestOp 1 2 2 (refl_equal _)).\nQed.\n\nTheorem prime17: prime 17.\nexact (ProthTestOp 1 4 3 (refl_equal _)).\nQed.\n\nTheorem prime257:  prime 257.\nexact (ProthTestOp 1 8 3 (refl_equal _)).\nQed.\n\nTheorem prime65537:  prime 65537.\nexact (ProthTestOp 1 16 3 (refl_equal _)).\nQed.\n\n(* Too tough !! \nTheorem prime4294967297:  prime 4294967297.\nexact (ProthTestOp 1 32 3 (refl_equal _)).\nQed.\n*)\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/coqprime/src/Coqprime/PrimalityTest/Proth.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6966560793158015}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) (lf1 : natural) : natural :=\n  plus Zero lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj33_coqofml_sO1wSG.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.696656076530492}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (lf1 : natural) (lf2 : natural)\n  : natural := plus Zero (plus z lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj125_coqofml_TiMhqd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6966302072605443}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus (Succ y) Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj287_coqofml_ppm5AS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.696630193260533}}
{"text": "Require Import Reals Gappa_tactic.\nOpen Scope R_scope.\n\nGoal -10 <= 12 * powerRZ 2 (-3) <= 10.\nProof. gappa. Qed.\n\nGoal -10 <= 150 * powerRZ 10 (-2) <= 10.\nProof. gappa. Qed.\n\nGoal -10 <= 24 * powerRZ 2 (-3) <= 10.\nProof. gappa. Qed.\n\nGoal -10 <= 0 * powerRZ 10 (-3) <= 10.\nProof. gappa. Qed.\n\nGoal -10 <= -300 * powerRZ 10 (-2) <= 10.\nProof. gappa. Qed.\n\nGoal -10 <= -12 * powerRZ 2 (-3) <= 10.\nProof. gappa. Qed.\n\nGoal -10 <= -150 * powerRZ 10 (-2) <= 10.\nProof. gappa. Qed.\n", "meta": {"author": "ejgallego", "repo": "gappa-coq", "sha": "3798341fa22a0f1e399ab06ff5a5da5509a9d275", "save_path": "github-repos/coq/ejgallego-gappa-coq", "path": "github-repos/coq/ejgallego-gappa-coq/gappa-coq-3798341fa22a0f1e399ab06ff5a5da5509a9d275/testsuite/bug-20200404.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172572644805, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6966186824505138}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import all_ssreflect.\nFrom mathcomp Require Import all_algebra.\n\nImport GRing.Theory Num.Def Num.Theory.\n\nLocal Open Scope ring_scope.\n\n(** This file defines generic notions of extrema. *)\n\nSection Extrema.\n(** The primary parameters are:\n      - [rty : realFieldType]    A real field\n      - [I : finType]            A finite type\n      - [P : pred I]             A subset of [I] \n      - [F : I -> rty]           A \"valuation\" function over [I] \n    The module implements the following functions: \n      - [arg_min]                An [i : I \\in P] that minimizes [F]\n      - [arg_max]                An [i : I \\in P] that maximizes [F]\n      - [min]                    := [F arg_min]\n      - [max]                    := [F arg_max]\n*)\n  Variable rty : realFieldType.\n  Variables (I : finType) (P : pred I) (F : I -> rty).\n\n  Section getOrd.\n    Variable ord : rel rty.\n    Hypothesis ord_refl : reflexive ord.\n    Hypothesis ord_trans : transitive ord.\n    Hypothesis ord_total : total ord.\n\n    Fixpoint getOrd (i0 : I) (l : list I) : I :=\n      if l is (i :: l') then\n        if ord (F i0) (F i) then getOrd i0 l' else getOrd i l'\n      else i0.\n\n    Lemma getOrd_mono i1 i2 l :\n      ord (F i1) (F i2) ->\n      ord (F (getOrd i1 l)) (F (getOrd i2 l)).\n    Proof.\n      move: i1 i2; elim: l=> // a l IH i1 i2 H /=.\n      case H2: (ord (F i1) (F a)). \n      { by case H3: (ord (F i2) (F a)); apply: IH.\n      }\n      case H3: (ord (F i2) _)=> //.\n      apply: IH.\n      have H4: ord (F i1) (F a).\n      { by apply: ord_trans; first by apply: H.\n      }\n      by rewrite H4 in H2.\n    Qed.    \n\n    Lemma getOrd_minimalIn i0 l :\n      [&& ord (F (getOrd i0 l)) (F i0)\n        & [forall (t | t \\in l), ord (F (getOrd i0 l)) (F t)]].\n    Proof.\n      move: i0; elim: l.\n      { move=> i0; apply/andP; split=> //.\n        by apply/forallP.\n      }\n      move=> a l IH i0.\n      apply/andP; split.\n      { simpl; case H2: (ord (F i0) _)=> //.\n        by case: (andP (IH i0)).                                        \n        apply: ord_trans.        \n        case: (andP (IH a))=> H3 _; apply: H3.\n        by case: (orP (ord_total (F i0) (F a))); first by rewrite H2.\n      }\n      apply/forallP=> x; apply/implyP.\n      move: (in_cons a l x)=> ->; case/orP.\n      { move/eqP=> ?; subst x=> /=.\n        case H4: (ord (F i0) _).\n        case: (andP (IH i0))=> H2 _.\n        by apply: ord_trans; first by apply: H2.\n        by case: (andP (IH a)).\n      }\n      move=> H /=.\n      case H2: (ord (F i0) _).\n      { case: (andP (IH i0))=> H0; move/forallP; move/(_ x).\n        by move/implyP; move/(_ H)=> H3.\n      }\n      case: (andP (IH a))=> H3; move/forallP; move/(_ x).\n      by move/implyP; move/(_ H)=> H4.\n    Qed.\n\n    Definition getOrd_tot i0 := getOrd i0 (enum I).\n    \n    Lemma getOrd_totP i0 : [forall i, ord (F (getOrd_tot i0)) (F i)].\n    Proof.\n      case: (andP (getOrd_minimalIn i0 (enum I)))=> H H2.\n      apply/forallP=> x; apply/implyP=> H3.\n      suff H4: false by [].\n      apply: H3; move: (forallP H2 x); move/implyP; apply.\n      by rewrite mem_enum.\n    Qed.\n\n    Definition getOrd_sub i0 := getOrd i0 (filter P (enum I)).\n\n    Lemma getOrd_sub_hasP i0 (Hi0 : P i0) : P (getOrd_sub i0).\n    Proof.\n      rewrite /getOrd_sub; move: (enum I)=> l.\n      elim: l=> // a l /=.\n      case H: (P a)=> //=.                   \n      case: (ord _ _)=> //.                      \n      elim: l a H i0 Hi0 => //= a0 l IH a H i0 Hi0.\n      case H2: (P a0)=> //=.\n      case: (ord _ _).\n      case: (ord _ _)=> //.\n      by apply: IH.\n      by apply: IH.\n      case: (ord _ _)=> //.\n      by apply: IH.\n      by apply: IH.\n    Qed.        \n      \n    Lemma getOrd_subP i0 (Hi0 : P i0) :\n      [&& P (getOrd_sub i0)\n        & [forall (i | P i), ord (F (getOrd_sub i0)) (F i)]].\n    Proof.\n      case: (andP (getOrd_minimalIn i0 (filter P (enum I))))=> H H2.\n      apply/andP; split; first by apply: getOrd_sub_hasP.\n      apply/forallP=> x; apply/implyP=> H3.\n      move: (forallP H2 x); move/implyP; apply.\n      by rewrite mem_filter; apply/andP; split=> //; rewrite mem_enum.\n    Qed.\n  End getOrd.\n\n  Section default.\n    Variable i0 : I.\n    Hypothesis H : P i0.\n  \n    Definition arg_max := getOrd_sub ger i0.\n  \n    Lemma arg_maxP : [&& P arg_max & [forall (i | P i), F arg_max >= F i]].\n    Proof.\n      apply: getOrd_subP=> //; rewrite /ger.\n      by apply: lerr.\n      by move=> x y z /= H2 H3; apply: (ler_trans H3 H2).\n      by move=> x y /=; move: (ler_total x y); rewrite orbC.\n    Qed.\n\n    Definition max := F arg_max.\n\n    Lemma maxP : [forall (i | P i), max >= F i].\n    Proof.\n      rewrite /max.\n      by case: (andP arg_maxP).\n    Qed.      \n    \n    Definition arg_min := getOrd_sub ler i0.\n\n    Lemma arg_minP : [&& P arg_min & [forall (i | P i), F arg_min <= F i]].\n    Proof.\n      apply: getOrd_subP=> //.\n      by apply: ler_trans.                           \n      by apply: ler_total.\n    Qed.\n\n    Definition min := F arg_min.\n\n    Lemma minP : [forall (i | P i), min <= F i].\n    Proof.\n      rewrite /min.\n      by case: (andP arg_minP).\n    Qed.      \n  \n    Lemma min_le_max : min <= max.\n    Proof.\n      rewrite /min /max.\n      case: (andP arg_minP)=> H2; move/forallP=> H3.\n      case: (andP arg_maxP)=> H4; move/forallP=> H5.\n      move: (implyP (H3 i0)); move/(_ H)=> Hx.\n      move: (implyP (H5 i0)); move/(_ H)=> Hy.\n      apply: ler_trans.\n      apply: Hx.\n      apply: Hy.\n    Qed.\n  End default.\nEnd Extrema.\n\nArguments arg_min [rty I] P F i0.\nArguments arg_max [rty I] P F i0.\n\nArguments arg_minP [rty I P] F [i0] _.\nArguments arg_maxP [rty I P] F [i0] _.\n\nArguments min [rty I] P F i0.\nArguments max [rty I] P F i0.\n\nArguments minP [rty I P] F [i0] _.\nArguments maxP [rty I P] F [i0] _.\n\nArguments min_le_max [rty I P] F [i0] _.\n\nLemma max_ge (rty : realFieldType) (I : finType) (f : I -> rty) (def i : I) :\n  f i <= max xpredT f def.\nProof.\n  have H: xpredT i by [].\n  move: (forallP (@maxP rty I xpredT f def H)); move/(_ i).\n  by move/implyP; apply.\nQed.\n\nLemma min_le (rty : realFieldType) (I : finType) (f : I -> rty) (def i : I) :\n  min xpredT f def <= f i.\nProof.\n  have H: xpredT i by [].\n  move: (forallP (@minP rty I xpredT f def H)); move/(_ i).\n  by move/implyP; apply.\nQed.\n", "meta": {"author": "gstew5", "repo": "games", "sha": "8791c776f95c6b8ea5b08e71c75da1617fca37a0", "save_path": "github-repos/coq/gstew5-games", "path": "github-repos/coq/gstew5-games/games-8791c776f95c6b8ea5b08e71c75da1617fca37a0/extrema.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.6965621400916162}}
{"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 Helpers.\nRequire Import Recdef.\nRequire Import Tree.\n\nOpen Scope nat_scope.\n\nImport ListNotations.\n\n\nInductive s_inc : (list tree) -> Prop :=\n    | s_inc_nil  : s_inc nil\n    | s_inc_sin  : forall (x : tree), s_inc (x :: nil)\n    | s_inc_two  : forall (x y : tree), ht x < ht y -> s_inc (x :: y :: nil)\n    | s_inc_cons : forall (x y : tree) (ys : list tree),\n                          ht x < ht y /\\ s_inc (y :: ys) -> s_inc (x :: y :: ys).\n\nFixpoint join_until_smaller (t : tree) (ts : list tree) :=\n    match ts with\n    | nil     => [t]\n    | x :: xs =>\n        match nat_compare (ht t) (ht x) with\n        | Eq => join_until_smaller (join t x) xs\n        | Lt => t :: x :: xs\n        | Gt => join_until_smaller (join t x) xs\n        end\n    end.\n\nTheorem join_until_smaller_produces: forall (ts : list tree) (t : tree),\n    join_until_smaller t ts <> [].\nProof.\n    induction ts. simpl. intros t contra. inversion contra.\n    intros t. remember (nat_compare (ht t) (ht a)) as R. destruct R.\n        simpl. rewrite <- HeqR. apply IHts.\n        simpl. rewrite <- HeqR. intros contra. inversion contra. \n        simpl. rewrite <- HeqR. apply IHts.\nQed.\n\nTheorem join_until_smaller_inc: forall (ts : list tree) (t : tree),\n    s_inc ts -> s_inc (join_until_smaller t ts).\nProof.\n    induction ts.\n        intros t s_inc_nil.\n        simpl. apply s_inc_sin.\n        intros t s_inc_ats.\n        remember (nat_compare (ht t) (ht a)) as R.\n        destruct R.\n            simpl. rewrite <- HeqR. apply IHts. inversion s_inc_ats.\n            apply s_inc_nil. apply s_inc_sin. destruct H0. assumption.\n\n            simpl. rewrite <- HeqR. apply s_inc_cons. split.\n            apply nat_compare_lt. symmetry. assumption. assumption.\n\n            simpl. rewrite <- HeqR. apply IHts. inversion s_inc_ats.\n            apply s_inc_nil. apply s_inc_sin. destruct H0. assumption.\nQed.\n\n\nFixpoint step (t : tree) (xs : list tree) : list tree :=\n    match xs with\n    | nil  => [t]\n    | u :: vs =>\n        match vs with \n            | nil => \n                match nat_compare (ht t) (ht u) with\n                | Lt => t :: u :: nil\n                | _  => (join t u) :: nil\n                end\n            | v :: ts =>\n                match nat_compare (ht t) (ht u) with\n                | Lt => t :: u :: v :: ts\n                | _  =>\n                    match nat_compare (ht t) (ht v) with\n                    | Lt => step (join t u) vs\n                    | _  => join_until_smaller t (join_until_smaller (join u v) ts)\n                    end\n                end\n        end\n    end.\n\n\nTheorem step_not_nil : forall (xs : list tree) (t : tree),\n  step t xs <> [].\nProof. \n    (* match xs with*) induction xs as [|u].\n    (* | nil  => [t]*) simpl. intuition. inversion H.\n    (* | u :: vs =>*)\n      (* match vs with *) remember xs as vs. induction vs as [|v]; intros t. \n        (* | nil => *)\n          (* match nat_compare (ht t) (ht u) with*) remember (nat_compare (ht t) (ht u)) as R1. destruct R1.\n          (* | Eq => (join t u) :: nil*) simpl. rewrite <- HeqR1. intros contra. inversion contra.\n          (* | Lt => t :: u :: nil*) simpl. rewrite <- HeqR1. intros contra. inversion contra.\n          (* | Gt => (join t u) :: nil*) simpl. rewrite <- HeqR1. intros contra. inversion contra.\n          (* end*)\n        (* | v :: ts =>*)\n         (* match nat_compare (ht t) (ht u) with *) remember (nat_compare (ht t) (ht u)) as R1. destruct R1.\n         (* | Eq => *) \n              (* match nat_compare (ht t) (ht v) with *) remember (nat_compare (ht t) (ht v)) as R2. destruct R2.\n              (* | Eq =>  join_until_smaller t (join u v :: ts) *) unfold step. rewrite <- HeqR1. rewrite <- HeqR2. apply join_until_smaller_produces.\n              (* | Lt => step (join t u) vs *) rewrite Heqvs. simpl. rewrite <- Heqvs. rewrite <- HeqR1. rewrite <- HeqR2. apply IHxs.\n              (* | Gt =>  join_until_smaller t (join u v :: ts) *) unfold step. rewrite <- HeqR1. rewrite <- HeqR2. apply join_until_smaller_produces.\n              (* end *)\n         (* | Lt => t :: u :: v :: ts *) simpl.  rewrite <- HeqR1. intros contra. inversion contra.\n         (* | Gt => *) \n              (* match nat_compare (ht t) (ht v) with *) remember (nat_compare (ht t) (ht v)) as R2. destruct R2.\n              (* | Eq =>  join_until_smaller t (join u v :: ts) *) unfold step. rewrite <- HeqR1. rewrite <- HeqR2. apply join_until_smaller_produces.\n              (* | Lt => step (join t u) vs *)  rewrite Heqvs. simpl. rewrite <- Heqvs. rewrite <- HeqR1. rewrite <- HeqR2. apply IHxs.\n              (* | Gt =>  join_until_smaller t (join u v :: ts) *) unfold step. rewrite <- HeqR1. rewrite <- HeqR2. apply join_until_smaller_produces.\n              (* end *)\n      (* end*)\n    (* end.*)\nQed.\n\nTheorem step_inc : forall (xs : list tree) (t : tree),\n  s_inc xs -> s_inc (step t xs).\nProof. \n    (* match xs with*) induction xs as [|u].\n    (* | nil  => [t]*) simpl. intuition. apply s_inc_sin.\n    (* | u :: vs =>*)\n      (* match vs with *) remember xs as vs. induction vs as [|v]; intros t H. \n        (* | nil => *)\n          (* match nat_compare (ht t) (ht u) with*) remember (nat_compare (ht t) (ht u)) as R1. destruct R1.\n          (* | Eq => (join t u) :: nil*) simpl. rewrite <- HeqR1. apply s_inc_sin.\n          (* | Lt => t :: u :: nil*) simpl. rewrite <- HeqR1. apply s_inc_two. apply nat_compare_lt. symmetry. assumption.\n          (* | Gt => (join t u) :: nil*) simpl. rewrite <- HeqR1. apply s_inc_sin.\n          (* end*)\n        (* | v :: ts =>*)\n         (* match nat_compare (ht t) (ht u) with *) remember (nat_compare (ht t) (ht u)) as R1. destruct R1.\n         (* | Eq => *) \n              (* match nat_compare (ht t) (ht v) with *) remember (nat_compare (ht t) (ht v)) as R2. destruct R2.\n              (* | Eq =>  join_until_smaller t (join u v :: ts) *) inversion H. contradict H1. apply not_eq_r. apply eq_ge. apply eq_nmo_mo with (n := ht t); assumption. \n                                                                   inversion H1. contradict H4. apply not_eq_r. apply eq_ge. apply eq_nmo_mo with (n := ht t); assumption.\n              (* | Lt => step (join t u) vs *) rewrite Heqvs. simpl. rewrite <- Heqvs. rewrite <- HeqR1. rewrite <- HeqR2. apply IHxs. inversion H. apply s_inc_sin. inversion H1. assumption.\n              (* | Gt =>  join_until_smaller t (join u v :: ts) *) inversion H. contradict H1. apply not_eq_r. apply gt_ge. apply gt_nmo_mo with (n := ht t); assumption. \n                                                                   inversion H1. contradict H4. apply not_eq_r. apply gt_ge. apply gt_nmo_mo with (n := ht t); assumption. \n              (* end *)\n         (* | Lt => t :: u :: v :: ts *) simpl.  rewrite <- HeqR1. apply s_inc_cons. split. apply nat_compare_lt. symmetry. assumption. assumption.\n         (* | Gt => *) \n              (* match nat_compare (ht t) (ht v) with *) remember (nat_compare (ht t) (ht v)) as R2. destruct R2.\n              (* | Eq =>  join_until_smaller t (join u v :: ts) *) simpl. rewrite <- HeqR1. rewrite <- HeqR2. remember (nat_compare (ht t) (max (ht u) (ht v) + 1)) as R3. destruct R3.\n                                                                     apply join_until_smaller_inc. apply join_until_smaller_inc. inversion H. apply s_inc_nil. inversion H1. inversion H5. apply s_inc_nil. apply s_inc_sin. inversion H7. assumption.\n                                                                     apply join_until_smaller_inc. apply join_until_smaller_inc. inversion H. apply s_inc_nil. inversion H1. inversion H5. apply s_inc_nil. apply s_inc_sin. inversion H7. assumption.\n                                                                     apply join_until_smaller_inc. apply join_until_smaller_inc. inversion H. apply s_inc_nil. inversion H1. inversion H5. apply s_inc_nil. apply s_inc_sin. inversion H7. assumption.\n              (* | Lt => step (join t u) vs *)  rewrite Heqvs. simpl. rewrite <- Heqvs. rewrite <- HeqR1. rewrite <- HeqR2. apply IHxs. inversion H. apply s_inc_sin. inversion H1. assumption. \n              (* | Gt =>  join_until_smaller t (join u v :: ts) *)  simpl. rewrite <- HeqR1. rewrite <- HeqR2. remember (nat_compare (ht t) (max (ht u) (ht v) + 1)) as R3. destruct R3.\n                                                                     apply join_until_smaller_inc. apply join_until_smaller_inc. inversion H. apply s_inc_nil. inversion H1. inversion H5. apply s_inc_nil. apply s_inc_sin. inversion H7. assumption.\n                                                                     apply join_until_smaller_inc. apply join_until_smaller_inc. inversion H. apply s_inc_nil. inversion H1. inversion H5. apply s_inc_nil. apply s_inc_sin. inversion H7. assumption.\n                                                                     apply join_until_smaller_inc. apply join_until_smaller_inc. inversion H. apply s_inc_nil. inversion H1. inversion H5. apply s_inc_nil. apply s_inc_sin. inversion H7. assumption.\n              (* end *)\n      (* end*)\n    (* end.*)\nQed.\n\nTheorem fold_right_not_nil : forall (l : list tree),\n  l <> [] -> fold_right (fun (a : tree) (xs : list tree) => step a xs) [] l <> [].\nProof.\n  induction l. intros LNNil. simpl. assumption.\n  (* step *) intros alNNil. simpl. apply step_not_nil.\nQed.\n\nTheorem fold_step_not_nil : forall (l : list tree),\n  l <> nil -> (fold_right (fun (a : tree) (xs : list tree) => step a xs) nil l) <> nil.\nProof.\n  intros l NNil. apply fold_right_not_nil. assumption.\nQed.\n\nTheorem fold_step_inc : forall (l : list tree),\n  s_inc (fold_right (fun (a : tree) (xs : list tree) => step a xs) nil l).\nProof.\n  induction l as [|l']. simpl. apply s_inc_nil. simpl. apply step_inc. assumption.\nQed.\n  \n", "meta": {"author": "ltbinsbe", "repo": "INFODTP", "sha": "2995a6503d4b8028f83a0907e83bcd85dd417d48", "save_path": "github-repos/coq/ltbinsbe-INFODTP", "path": "github-repos/coq/ltbinsbe-INFODTP/INFODTP-2995a6503d4b8028f83a0907e83bcd85dd417d48/coq/SInc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.6965621282614378}}
{"text": "(** Formal Reasoning About Programs <http://adam.chlipala.net/frap/>\n  * Chapter 4: Transition Systems\n  * Author: Adam Chlipala\n  * License: https://creativecommons.org/licenses/by-nc-nd/4.0/ *)\n\nRequire Import Frap.\n\nSet Implicit Arguments.\n(* This command will treat type arguments to functions as implicit, like in\n * Haskell or ML. *)\n\n\n(* Here's a classic recursive, functional program for factorial. *)\nFixpoint fact (n : nat) : nat :=\n  match n with\n  | O => 1\n  | S n' => fact n' * S n'\n  end.\n\n(* But let's reformulate factorial relationally, as an example to explore\n * treatment of inductive relations in Coq.  First, these are the states of our\n * state machine. *)\nInductive fact_state :=\n| AnswerIs (answer : nat)\n| WithAccumulator (input accumulator : nat).\n\n(* *Initial* states *)\nInductive fact_init (original_input : nat) : fact_state -> Prop :=\n| FactInit : fact_init original_input (WithAccumulator original_input 1).\n\n(** *Final* states *)\nInductive fact_final : fact_state -> Prop :=\n| FactFinal : forall ans, fact_final (AnswerIs ans).\n\n(** The most important part: the relation to step between states *)\nInductive fact_step : fact_state -> fact_state -> Prop :=\n| FactDone : forall acc,\n  fact_step (WithAccumulator O acc) (AnswerIs acc)\n| FactStep : forall n acc,\n  fact_step (WithAccumulator (S n) acc) (WithAccumulator n (acc * S n)).\n\n(* We care about more than just single steps.  We want to run factorial to\n * completion, for which it is handy to define a general relation of\n * *transitive-reflexive closure*, like so. *)\nInductive trc {A} (R : A -> A -> Prop) : A -> A -> Prop :=\n| TrcRefl : forall x, trc R x x\n| TrcFront : forall x y z,\n  R x y\n  -> trc R y z\n  -> trc R x z.\n\n(* Transitive-reflexive closure is so common that it deserves a shorthand notation! *)\nNotation \"R ^*\" := (trc R) (at level 0).\n\n(* Now let's use it to execute the factorial program. *)\nExample factorial_3 : fact_step^* (WithAccumulator 3 1) (AnswerIs 6).\nProof.\nAdmitted.\n\n(* It will be useful to give state machines more first-class status, as\n * *transition systems*, formalized by this record type.  It has one type\n * parameter, [state], which records the type of states. *)\nRecord trsys state := {\n  Initial : state -> Prop;\n  Step : state -> state -> Prop\n}.\n\n(* The example of our factorial program: *)\nDefinition factorial_sys (original_input : nat) : trsys fact_state := {|\n  Initial := fact_init original_input;\n  Step := fact_step\n|}.\n\n(* A useful general notion for transition systems: reachable states *)\nInductive reachable {state} (sys : trsys state) (st : state) : Prop :=\n| Reachable : forall st0,\n  sys.(Initial) st0\n  -> sys.(Step)^* st0 st\n  -> reachable sys st.\n\n(* To prove that our state machine is correct, we rely on the crucial technique\n * of *invariants*.  What is an invariant?  Here's a general definition, in\n * terms of an arbitrary transition system. *)\nDefinition invariantFor {state} (sys : trsys state) (invariant : state -> Prop) :=\n  forall s, sys.(Initial) s\n            -> forall s', sys.(Step)^* s s'\n                          -> invariant s'.\n(* That is, when we begin in an initial state and take any number of steps, the\n * place we wind up always satisfies the invariant. *)\n\n(* Here's a simple lemma to help us apply an invariant usefully,\n * really just restating the definition. *)\nLemma use_invariant' : forall {state} (sys : trsys state)\n  (invariant : state -> Prop) s s',\n  invariantFor sys invariant\n  -> sys.(Initial) s\n  -> sys.(Step)^* s s'\n  -> invariant s'.\nProof.\n  unfold invariantFor.\n  simplify.\n  eapply H.\n  eassumption.\n  assumption.\nQed.\n\nTheorem use_invariant : forall {state} (sys : trsys state)\n  (invariant : state -> Prop) s,\n  invariantFor sys invariant\n  -> reachable sys s\n  -> invariant s.\nProof.\n  simplify.\n  invert H0.\n  eapply use_invariant'.\n  eassumption.\n  eassumption.\n  assumption.\nQed.\n\n(* What's the most fundamental way to establish an invariant?  Induction! *)\nLemma invariant_induction' : forall {state} (sys : trsys state)\n  (invariant : state -> Prop),\n  (forall s, invariant s -> forall s', sys.(Step) s s' -> invariant s')\n  -> forall s s', sys.(Step)^* s s'\n     -> invariant s\n     -> invariant s'.\nProof.\n  induct 2; propositional.\n  (* [propositional]: simplify the goal according to the rules of propositional\n   *   logic. *)\n\n  apply IHtrc.\n  eapply H.\n  eassumption.\n  assumption.\nQed.\n\nTheorem invariant_induction : forall {state} (sys : trsys state)\n  (invariant : state -> Prop),\n  (forall s, sys.(Initial) s -> invariant s)\n  -> (forall s, invariant s -> forall s', sys.(Step) s s' -> invariant s')\n  -> invariantFor sys invariant.\nProof.\n  unfold invariantFor; intros.\n  eapply invariant_induction'.\n  eassumption.\n  eassumption.\n  apply H.\n  assumption.\nQed.\n\nDefinition fact_invariant (original_input : nat) (st : fact_state) : Prop :=\n  True.\n(* We must fill in a better invariant. *)\n\nTheorem fact_invariant_ok : forall original_input,\n  invariantFor (factorial_sys original_input) (fact_invariant original_input).\nProof.\nAdmitted.\n\n(* Therefore, every reachable state satisfies this invariant. *)\nTheorem fact_invariant_always : forall original_input s,\n  reachable (factorial_sys original_input) s\n  -> fact_invariant original_input s.\nProof.\n  simplify.\n  eapply use_invariant.\n  apply fact_invariant_ok.\n  assumption.\nQed.\n\n(* Therefore, any final state has the right answer! *)\nLemma fact_ok' : forall original_input s,\n  fact_final s\n  -> fact_invariant original_input s\n  -> s = AnswerIs (fact original_input).\nAdmitted.\n\nTheorem fact_ok : forall original_input s,\n  reachable (factorial_sys original_input) s\n  -> fact_final s\n  -> s = AnswerIs (fact original_input).\nProof.\n  simplify.\n  apply fact_ok'.\n  assumption.\n  apply fact_invariant_always.\n  assumption.\nQed.\n\n\n(** * A simple example of another program as a state transition system *)\n\n(* We'll formalize this pseudocode for one thread of a concurrent, shared-memory program.\n  lock();\n  local = global;\n  global = local + 1;\n  unlock();\n*)\n\n(* This inductive state effectively encodes all possible combinations of two\n * kinds of *local*state* in a thread:\n * - program counter\n * - values of local variables that may be read eventually *)\nInductive increment_program :=\n| Lock\n| Read\n| Write (local : nat)\n| Unlock\n| Done.\n\n(* Next, a type for state shared between threads. *)\nRecord inc_state := {\n  Locked : bool; (* Does a thread hold the lock? *)\n  Global : nat   (* A shared counter *)\n}.\n\n(* The combined state, from one thread's perspective, using a general\n * definition. *)\nRecord threaded_state shared private := {\n  Shared : shared;\n  Private : private\n}.\n\nDefinition increment_state := threaded_state inc_state increment_program.\n\n(* Now a routine definition of the three key relations of a transition system.\n * The most interesting logic surrounds saving the counter value in the local\n * state after reading. *)\n\nInductive increment_init : increment_state -> Prop :=\n| IncInit :\n  increment_init {| Shared := {| Locked := false; Global := O |};\n                    Private := Lock |}.\n\nInductive increment_step : increment_state -> increment_state -> Prop :=\n| IncLock : forall g,\n  increment_step {| Shared := {| Locked := false; Global := g |};\n                    Private := Lock |}\n                 {| Shared := {| Locked := true; Global := g |};\n                    Private := Read |}\n| IncRead : forall l g,\n  increment_step {| Shared := {| Locked := l; Global := g |};\n                    Private := Read |}\n                 {| Shared := {| Locked := l; Global := g |};\n                    Private := Write g |}\n| IncWrite : forall l g v,\n  increment_step {| Shared := {| Locked := l; Global := g |};\n                    Private := Write v |}\n                 {| Shared := {| Locked := l; Global := S v |};\n                    Private := Unlock |}\n| IncUnlock : forall l g,\n  increment_step {| Shared := {| Locked := l; Global := g |};\n                    Private := Unlock |}\n                 {| Shared := {| Locked := false; Global := g |};\n                    Private := Done |}.\n\nDefinition increment_sys := {|\n  Initial := increment_init;\n  Step := increment_step\n|}.\n\n\n(** * Running transition systems in parallel *)\n\n(* That last example system is a cop-out: it only runs a single thread.  We want\n * to run several threads in parallel, sharing the global state.  Here's how we\n * can do it for just two threads.  The key idea is that, while in the new\n * system the type of shared state remains the same, we take the Cartesian\n * product of the sets of private state. *)\n\nInductive parallel1 shared private1 private2\n  (init1 : threaded_state shared private1 -> Prop)\n  (init2 : threaded_state shared private2 -> Prop)\n  : threaded_state shared (private1 * private2) -> Prop :=\n| Pinit : forall sh pr1 pr2,\n  init1 {| Shared := sh; Private := pr1 |}\n  -> init2 {| Shared := sh; Private := pr2 |}\n  -> parallel1 init1 init2 {| Shared := sh; Private := (pr1, pr2) |}.\n\nInductive parallel2 shared private1 private2\n          (step1 : threaded_state shared private1 -> threaded_state shared private1 -> Prop)\n          (step2 : threaded_state shared private2 -> threaded_state shared private2 -> Prop)\n          : threaded_state shared (private1 * private2)\n            -> threaded_state shared (private1 * private2) -> Prop :=\n| Pstep1 : forall sh pr1 pr2 sh' pr1',\n  (* First thread gets to run. *)\n  step1 {| Shared := sh; Private := pr1 |} {| Shared := sh'; Private := pr1' |}\n  -> parallel2 step1 step2 {| Shared := sh; Private := (pr1, pr2) |}\n               {| Shared := sh'; Private := (pr1', pr2) |}\n| Pstep2 : forall sh pr1 pr2 sh' pr2',\n  (* Second thread gets to run. *)\n  step2 {| Shared := sh; Private := pr2 |} {| Shared := sh'; Private := pr2' |}\n  -> parallel2 step1 step2 {| Shared := sh; Private := (pr1, pr2) |}\n               {| Shared := sh'; Private := (pr1, pr2') |}.\n\nDefinition parallel shared private1 private2\n           (sys1 : trsys (threaded_state shared private1))\n           (sys2 : trsys (threaded_state shared private2)) := {|\n  Initial := parallel1 sys1.(Initial) sys2.(Initial);\n  Step := parallel2 sys1.(Step) sys2.(Step)\n|}.\n\n(* Example: composing two threads of the kind we formalized earlier *)\nDefinition increment2_sys := parallel increment_sys increment_sys.\n\n(* Let's prove that the counter is always 2 when the composed program terminates. *)\n\n(** We must write an invariant. *)\nInductive increment2_invariant :\n  threaded_state inc_state (increment_program * increment_program) -> Prop :=\n| Inc2Inv : forall sh pr1 pr2,\n  increment2_invariant {| Shared := sh; Private := (pr1, pr2) |}.\n(* This isn't it yet! *)\n\n(* Now, to show it really is an invariant. *)\nTheorem increment2_invariant_ok : invariantFor increment2_sys increment2_invariant.\nProof.\nAdmitted.\n\n(* Now, to prove our final result about the two incrementing threads, let's use\n * a more general fact, about when one invariant implies another. *)\nTheorem invariant_weaken : forall {state} (sys : trsys state)\n  (invariant1 invariant2 : state -> Prop),\n  invariantFor sys invariant1\n  -> (forall s, invariant1 s -> invariant2 s)\n  -> invariantFor sys invariant2.\nProof.\n  unfold invariantFor; simplify.\n  apply H0.\n  eapply H.\n  eassumption.\n  assumption.\nQed.\n\n(* Here's another, much weaker invariant, corresponding exactly to the overall\n * correctness property we want to establish for this system. *)\nDefinition increment2_right_answer\n  (s : threaded_state inc_state (increment_program * increment_program)) :=\n  s.(Private) = (Done, Done)\n  -> s.(Shared).(Global) = 2.\n\n(** Now we can prove that the system only runs to happy states. *)\nTheorem increment2_sys_correct : forall s,\n  reachable increment2_sys s\n  -> increment2_right_answer s.\nProof.\nAdmitted.\n(*simplify.\n  eapply use_invariant.\n  apply invariant_weaken with (invariant1 := increment2_invariant).\n  (* Note the use of a [with] clause to specify a quantified variable's\n   * value. *)\n\n  apply increment2_invariant_ok.\n\n  simplify.\n  invert H0.\n  unfold increment2_right_answer; simplify.\n  invert H0.\n  (* Here we use inversion on an equality, to derive more primitive\n   * equalities. *)\n  simplify.\n  equality.\n\n  assumption.\nQed.*)\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/TransitionSystems_template.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6965621254420652}}
{"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    In this chapter we take a deeper look at the way propositions are\n    expressed in Coq and at the structure of the logical evidence that\n    we construct when we carry out proofs.  \n\n    Some of the concepts in this chapter may seem a bit abstract on a\n    first encounter.  We've included a _lot_ of exercises, most of\n    which should be quite approachable even if you're still working on\n    understanding the details of the text.  Try to work as many of\n    them as you can, especially the one-starred exercises. \n\n*)\n(* ##################################################### *)\n(** * Inductively Defined Propositions *)\n\n(** This chapter will take us on a first tour of the\n    propositional (logical) side of Coq.  As a running example, let's\n    define a simple property of natural numbers -- we'll call it\n    \"[beautiful].\" *)\n\n(** Informally, a number is [beautiful] if it is [0], [3], [5], or the\n    sum of two [beautiful] numbers.  \n\n    More pedantically, we can define [beautiful] numbers by giving four\n    rules:\n\n       - Rule [b_0]: The number [0] is [beautiful].\n       - Rule [b_3]: The number [3] is [beautiful]. \n       - Rule [b_5]: The number [5] is [beautiful]. \n       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is\n         their sum. *)\n\n(** We will see many definitions like this one during the rest\n    of the course, and for purposes of informal discussions, it is\n    helpful to have a lightweight notation that makes them easy to\n    read and write.  _Inference rules_ are one such notation: *)\n(**\n                              -----------                               (b_0)\n                              beautiful 0\n                              \n                              ------------                              (b_3)\n                              beautiful 3\n\n                              ------------                              (b_5)\n                              beautiful 5    \n\n                       beautiful n     beautiful m\n                       ---------------------------                      (b_sum)\n                              beautiful (n+m)   \n*)\n\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  The rules with no premises above the line are\n    called _axioms_.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8   \n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty) *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n(** The first line declares that [beautiful] is a proposition -- or,\n    more formally, a family of propositions \"indexed by\" natural\n    numbers.  (That is, for each number [n], the claim that \"[n] is\n    [beautiful]\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.  Each of the remaining lines\n    embodies one of the rules for [beautiful] numbers.\n\n    We can use Coq's tactic scripting facility to assemble proofs that\n    particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the axiom [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have axioms for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(* ##################################################### *)\n(** * Proof Objects *)\n\n(** Look again at the formal definition of the [beautiful]\n    property.  The opening keyword, [Inductive], has been used up to\n    this point to declare new types of _data_, such as numbers and\n    lists.  Does this interpretation also make sense for the Inductive\n    definition of [beautiful]?  That is, can we view evidence of\n    beauty as some kind of data structure? Yes, we can!\n\n    The trick is to introduce an alternative pronunciation of \"[:]\".\n    Instead of \"has type,\" we can also say \"is a proof of.\"  For\n    example, the second line in the definition of [beautiful] declares\n    that [b_0 : beautiful 0].  Instead of \"[b_0] has type \n    [beautiful 0],\" we can say that \"[b_0] is a proof of [beautiful 0].\"\n    Similarly for [b_3] and [b_5]. *)\n\n(** This pun between types and propositions (between [:] as \"has type\"\n    and [:] as \"is a proof of\" or \"is evidence for\") is called the\n    _Curry-Howard correspondence_.  It proposes a deep connection\n    between the world of logic and the world of computation.\n<<\n                 propositions  ~  types\n                 proofs        ~  data values\n>>\n    Many useful insights follow from this connection.  To begin with, it\n    gives us a natural interpretation of the type of [b_sum] constructor: *)\n\nCheck b_sum.\n(* ===> b_sum : forall n m, \n                  beautiful n -> \n                  beautiful m -> \n                  beautiful (n+m) *)\n\n(** This can be read \"[b_sum] is a constructor that takes four\n    arguments -- two numbers, [n] and [m], and two values, of types\n    [beautiful n] and [beautiful m] -- and yields evidence for the\n    proposition [beautiful (n+m)].\" *)\n\n(** In view of this, we might wonder whether we can write an\n    expression of type [beautiful 8] by applying [b_sum] to\n    appropriate arguments.  Indeed, we can: *)\n\nCheck (b_sum 3 5 b_3 b_5).  \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(** ** 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.  In the [Show Proof]\n    output, lines of the form [?1 -> beautiful n] record these\n    requirements.  (The [->] here has nothing to do with either\n    implication or function types -- it is just an unfortunate choice\n    of concrete syntax for the output!)  \n\n    Each of the holes corresponds to a subgoal, and the proof is\n    finished when there are no more subgoals.  At this point, the\n    [Theorem] command gives a name to the evidence we've built and\n    stores it in the global context. *)\n\n(** Tactic proofs are useful and convenient, but they are not\n    essential: in principle, we can always construct the required\n    evidence by hand.  Indeed, we don't even need the [Theorem]\n    command: we can instead use [Definition] to directly give a global\n    name to a piece of evidence. *)\n\nDefinition eight_is_beautiful''' : beautiful 8 :=\n  b_sum 3 5 b_3 b_5.\n\n(** All these different ways of building the proof lead to exactly the\n    same evidence being saved in the global environment. *)\n\nPrint eight_is_beautiful.\n(* ===> eight_is_beautiful    = b_sum 3 5 b_3 b_5 : beautiful 8 *)\nPrint eight_is_beautiful'.\n(* ===> eight_is_beautiful'   = b_sum 3 5 b_3 b_5 : beautiful 8 *)\nPrint eight_is_beautiful''.\n(* ===> eight_is_beautiful''  = b_sum 3 5 b_3 b_5 : beautiful 8 *)\nPrint eight_is_beautiful'''.\n(* ===> eight_is_beautiful''' = b_sum 3 5 b_3 b_5 : beautiful 8 *)\n\n(** **** Exercise: 1 star (six_is_beautiful) *)\n(** Give a tactic proof and a proof object showing that [6] is [beautiful]. *)\n\nTheorem six_is_beautiful :\n  beautiful 6.\nProof.\n  (* 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(** ** 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 => fun H : beautiful n =>\n    b_sum 3 n b_3 H.\n\nCheck b_plus3'.\n(* ===> b_plus3' : forall n, beautiful n -> beautiful (3+n) *)\n\n(** Recall that [fun n => blah] means \"the function that, given [n],\n    yields [blah].\"  Another equivalent way to write this definition is: *)\n\nDefinition b_plus3'' (n : nat) (H : beautiful n) : beautiful (3+n) := \n  b_sum 3 n b_3 H.\n\nCheck b_plus3''.\n(* ===> b_plus3'' : forall n, beautiful n -> beautiful (3+n) *)\n\n(** **** Exercise: 2 stars (b_times2) *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (b_times2') *)\n(** Write a proof object corresponding to [b_times2] above *)\n\nDefinition b_times2': forall n, beautiful n -> beautiful (2*n) :=\n  (* FILL IN HERE *) admit.\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(** ** Induction Over Proof Objects *)\n\n(** Since we use the keyword [Induction] to define primitive\n    propositions together with their evidence, we might wonder whether\n    there are some sort of induction principles associated with these\n    definitions.  Indeed there are, and in this section we'll take a\n    look at how they can be used.  *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells us not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    two constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]), \n      - [E] is [b_5] (and [n] is [5]), or \n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n    \n(** This gives rise to an _induction principle_ for proofs -- i.e., we\n    can use the [induction] tactic that we have already seen for\n    reasoning about inductively defined _data_ to reason about\n    inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree) *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n \n(* FILL IN HERE *)\n[]\n*)\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! *)\nAdmitted.\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(** **** 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(** **** Exercise: 2 stars, optional (gorgeous_plus13_po):\nGive the proof object for theorem [gorgeous_plus13] above. *)\n\nDefinition gorgeous_plus13_po: forall n, gorgeous n -> gorgeous (13+n):=\n   (* FILL IN HERE *) admit.\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 (b_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(** 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(** Construct a tactic proof of the following proposition. *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (double_even_pfobj) *)\n(** Try to predict what proof object is constructed by the above\n    tactic proof.  (Before checking your answer, you'll want to\n    strip out any uses of [Case], as these will make the proof\n    object look a bit cluttered.) *)\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(** ** [Inversion] on Evidence *)\n\n(** Besides [induction], we can use the other tactics in our toolkit\n    to reason about evidence.  For example, this proof uses [destruct]\n    on 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'].\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 [destruct] on [n] instead of [E]? *)\n\n(* FILL IN HERE *)\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   Briefly explain why.\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(** Another situation where we want to analyze evidence for evenness\n    is when proving that, if [n+2] is even, then [n] is. *)\n\n(** Our first idea might be to use [destruct] for this kind of case\n    analysis: *)\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  (* Stuck: [destruct] gives us an unprovable subgoal here! *)\nAdmitted.\n\n(** In the first sub-goal, we've lost the information that [n] is [0].\n    We could have used [remember], but then we still need [inversion]\n    on both cases. *)\n\nTheorem SSev_ev_secondtry : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. remember (S (S n)) as n2.\n  destruct E as [| n' E'].\n  Case \"n = 0\". inversion Heqn2.\n  Case \"n = S n'\". inversion Heqn2. rewrite <- H0. apply E'.\nQed.\n\n(** There is a much simpler way to do this. We can use\n    [inversion] directly on the inductively defined proposition\n    [ev (S (S n))]. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. inversion E as [| n' E']. apply E'. Qed.\n\n(** This use 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    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(** **** 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(** We can generally use [inversion] on inductive propositions.\n    This illustrates that in general, we get one case for each\n    possible constructor.  Again, we also get some auxiliary\n    equalities that are rewritten in the goal but not in the other\n    hypotheses. *)\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\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.  You'll want the [replace] tactic used for [plus_swap']\n    in Basics.v *)\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(** ** Building Proof Objects Incrementally (Optional) *)\n\n(** As you probably noticed while solving the exercises earlier in the\n    chapter, constructing proof objects is more involved than\n    constructing the corresponding tactic proofs. Fortunately, there\n    is a bit of syntactic sugar that we've already introduced to help\n    in the construction: the [admit] term, which we've sometimes used\n    to force Coq into accepting incomplete exercies. As an example,\n    let's walk through the process of constructing a proof object\n    demonstrating the beauty of [16]. *)\n\nDefinition b_16_atmpt_1 : beautiful 16 := admit.\n\n(** Maybe we can use [b_sum] to construct a term of type [beautiful 16]?\n    Recall that [b_sum] is of type\n\n    forall n m : nat, beautiful n -> beautiful m -> beautiful (n + m)\n\n    If we can demonstrate the beauty of [5] and [11], we should\n    be done. *)\n\nDefinition b_16_atmpt_2 : beautiful 16 := b_sum 5 11 admit admit.\n\n(** In the attempt above, we've omitted the proofs of the propositions\n    that [5] and [11] are beautiful. But the first of these is already\n    axiomatized in [b_5]: *)\n\nDefinition b_16_atmpt_3 : beautiful 16 := b_sum 5 11 b_5 admit.\n\n(** What remains is to show that [11] is beautiful. We repeat the\n    procedure: *)\n\nDefinition b_16_atmpt_4 : beautiful 16 :=\n  b_sum 5 11 b_5 (b_sum 5 6 admit admit).\n\nDefinition b_16_atmpt_5 : beautiful 16 :=\n  b_sum 5 11 b_5 (b_sum 5 6 b_5 admit).\n\nDefinition b_16_atmpt_6 : beautiful 16 :=\n  b_sum 5 11 b_5 (b_sum 5 6 b_5 (b_sum 3 3 admit admit)).\n\n(** And finally, we can complete the proof object: *)\n\nDefinition b_16 : beautiful 16 :=\n  b_sum 5 11 b_5 (b_sum 5 6 b_5 (b_sum 3 3 b_3 b_3)).\n\n(** To recap, we've been guided by an informal proof that we have in\n    our minds, and we check the high level details before completing\n    the intricacies of the proof. The [admit] term allows us to do\n    this. *)\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(* 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(* ##################################################### *)\n(* ##################################################### *)\n(* ##################################################### *)\n(* ##################################################### *)\n\n(* $Date: 2013-01-30 19:12:43 -0500 (Wed, 30 Jan 2013) $ *)\n\n\n\n", "meta": {"author": "steven7woo", "repo": "Coq-CIS500", "sha": "405653248c19d78ec35f4b7bc2b2144c4aa92738", "save_path": "github-repos/coq/steven7woo-Coq-CIS500", "path": "github-repos/coq/steven7woo-Coq-CIS500/Coq-CIS500-405653248c19d78ec35f4b7bc2b2144c4aa92738/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.8840392817460333, "lm_q1q2_score": 0.6965621194566933}}
{"text": "(**\nObjectif de ce suppport de TD :\nfamiliarisation avec les AST winstr pour le langage WHILE.\n*)\n\n(* ------------------------------------------------------------ *)\n(** * Familiarisation avec les AST winstr pour le langage WHILE *)\n\n(** ** Syntaxe abstraite *)\nInductive aexp :=\n| Aco : nat -> aexp (* constantes *)\n| Ava : nat -> aexp (* variables *)\n| Apl : aexp -> aexp -> aexp\n| Amu : aexp -> aexp -> aexp\n| Amo : aexp -> aexp -> aexp\n.\n\nInductive bexp :=\n| Btrue : bexp\n| Bfalse : bexp\n| Bnot : bexp -> bexp\n| Band : bexp -> bexp -> bexp\n| Bor : bexp -> bexp -> bexp\n| Beq : bexp -> bexp -> bexp (* test égalité de bexp *)\n| Beqnat : aexp -> aexp -> bexp (* test égalité d'aexp *)\n.\n\nInductive winstr :=\n| Skip   : winstr\n| Assign : nat -> aexp -> winstr\n| Seq    : winstr -> winstr -> winstr\n| If     : bexp -> winstr -> winstr -> winstr\n| While  : bexp -> winstr -> winstr\n.\n\n(** Le langage IMP : comme WHILE mais sans While *)\nInductive instr :=\n| ISkip   : instr\n| IAssign : nat -> aexp -> instr\n| ISeq    : instr -> instr -> instr\n| IIf     : bexp -> instr -> instr -> instr\n.\n\n(** Définir les AST des programmes suivants *)\n(** x3 := 5 * x2 *)\nDefinition P1 : instr := IAssign 3 (Amu (Aco 5) (Ava 2)).\n(** x2 := x2 + 1 *)\nDefinition P2 : instr := IAssign 2 (Apl (Ava 2) (Aco 1)).\n(** if x1 = x3 then (x2 := x2 + 1; x2 := x2 + 1) else x3 := 5 * x2 *)\nDefinition P3 : instr := IIf\n  (Beqnat (Ava 1) (Ava 3))\n  (ISeq\n    (IAssign 2 (Apl (Ava 2) (Aco 1)))\n    (IAssign 2 (Apl (Ava 2) (Aco 1)))\n  )\n  (IAssign 3 (Amu (Aco 5) (Ava 2))).\n\n(** ** Sémantique fonctionnelle *)\n\nInductive state :=\n  | Nil : state\n  | Cons : nat -> state -> state\n.\n\n(** On se donne des notations préalables pour faciliter la présentation *)\nNotation \"[]\" := Nil.\nNotation \"x :: y\" := (Cons x y).\n\n(** L'appel [get i s] rend la valeur associée à xi dans l'état s *)\nFixpoint get (i: nat) (s: state) : nat :=\n  match s with\n  | []     => 0\n  | v :: s' =>\n    match i with\n    | O => v\n    | S i' => get i' s'\n    end\n  end.\n\n(** *** Sémantique fonctionnelle de aexp*)\nFixpoint evalA (a: aexp) (s: state) : nat :=\n  match a with\n  | Aco n => n\n  | Ava x => get x s\n  | Apl a1 a2 =>  evalA a1 s + evalA a2 s\n  | Amu a1 a2 =>  evalA a1 s * evalA a2 s\n  | Amo a1 a2 =>  evalA a1 s - evalA a2 s\n  end.\n\n\n(** *** Sémantique fonctionnelle de bexp*)\nDefinition eqboolb b1 b2 : bool :=\n  match b1, b2  with\n  | true, true   => true\n  | false, false => true\n  | _ , _        => false\n  end.\n\nFixpoint eqnatb n1 n2 : bool :=\n   match n1, n2 with\n  | O, O         => true\n  | S n1', S n2' => eqnatb n1' n2'\n  | _, _         => false\n  end.\n\n Fixpoint evalB (b : bexp) (s : state) : bool :=\n  match b with\n  | Btrue => true\n  | Bfalse => false\n  | Bnot b => negb (evalB b s)\n  | Band e1 e2 => (evalB e1 s) && (evalB e2 s)\n  | Bor e1 e2 => (evalB e1 s) || (evalB e2 s)\n  | Beq e1 e2 => eqboolb (evalB e1 s) (evalB e2 s)\n  | Beqnat n1 n2 => eqnatb (evalA n1 s) (evalA n2 s)\n  end.\n\n\n(** *** Sémantique fonctionnelle de IMP *)\n\n(** La mise à jour d'une variable [v] par un nouvel entier [n]\n    dans un état [s] s'écrit [update s v n'].\n    Cette fonction n'échoue jamais et écrit la valeur à sa place même\n    si elle n'est pas encore définie dans l'état [s]. *)\n\n(** À définir en TD *)\n(** [update i v s] rend l'état dans lequel xi vaut [v],\n    les valeurs des autres variables étant celles de [s].\n    Attention à bien traiter tous les cas, notament ceux\n    où l'état est représenté par une liste vide : tout se passe\n    comme si, à la place, on avait une liste comprenant\n    suffisamment de 0 (valeur par défaut).\n *)\nFixpoint update (i:nat) (v:nat) (s:state) : state := match i with\n| 0 => match s with\n  | [] => v :: []\n  | _ :: xs => v :: xs\n  end\n| S n => match s with\n  | [] => 0 :: update n v s\n  | x :: xs => x :: update n v xs\n  end\nend.\n\n(** Quelques états pour faire des tests *)\n(** S1 est un état dans lequel la variable \"x0\" vaut 1 et la variable \"x1\"\n    vaut 2 et toutes les autres valent 0 (valeur par défaut) *)\n\nDefinition S1 := 1 :: 2 :: Nil.\nDefinition S2 := 0 :: 3 :: Nil.\nDefinition S3 := 0 :: 7 :: 5 :: 41 :: Nil.\n\n\nDefinition S4 :=\n  let s1 := update 4 1 S1 in\n  let s2 := update 3 2 s1 in\n  let s3 := update 2 3 s2 in\n  let s4 := update 2 3 s3 in\n  update 0 5 s4.\nExample test_S4 : S4 = 5 :: 2 :: 3 :: 2 :: 1 :: [].\nProof. reflexivity. Qed.\n\n(** Peut s'écrire dans une premier temps avec update laissé \"Admitted\". *)\nFixpoint evalI (i : instr) (s : state) : state :=\n  match i with\n  | ISkip       => s\n  | IAssign v exp => update v (evalA exp s) s\n  | ISeq instr1 instr2 => evalI instr2 (evalI instr1 s)\n  | IIf cond i e => if evalB cond s then evalI i s else evalI e s\n  end.\n\n(** La pré-commande \"Fail\" indique que l'on s'attend à un échec *)\n(** La présence de [{struct i}] indique que l'argument devant\n    décroître structurellement est [i] ;\n    Pour [evalI] on aurait pu le préciser aussi mais Coq a su\n    reconstruire cette information à partir du corps de la fonction.\n*)\nFail Fixpoint evalW (i : winstr) (s : state) {struct i} : state :=\n  (** à compléter, en expliquant le diagnostic rendu par Coq *)\n  match i with\n  | Skip       => s\n  | Assign v exp => update v (evalA exp s) s\n  | Seq instr1 instr2 => evalW instr2 (evalW instr1 s)\n  | If cond i e => if evalB cond s then evalW i s else evalW e s\n  | While cond instr => if evalB cond s then evalW (While cond instr) s else s\n  end.\n  (* Coq n'accepte pas cette définition car il n'arrive pas\n     à démontrer qu'elle ne sera pas infiniement récursive.\n     En effet, dans le cas du While, l'évalution peut être infinie.\n  *)\n\n(** ** Tests *)\n\nCompute P1.\nCompute S1.\nCompute evalI P1 S1.\nExample test1 : evalI P1 S1 = 1 :: 2 :: 0 :: 0 :: [].\nProof. reflexivity. Qed.\n\nExample test2 : evalI P1 S4 = 5 :: 2 :: 3 :: 15 :: 1 :: [].\nProof. reflexivity. Qed.\n\nExample test3 : evalI P3 S1 = 1 :: 2 :: 0 :: 0 :: [].\nProof. reflexivity. Qed.\n\nExample test4 : evalI P3 S4 = 5 :: 2 :: 5 :: 2 :: 1 :: [].\nProof. reflexivity. Qed.\n\n\n", "meta": {"author": "elegaanz", "repo": "info4-ltpf", "sha": "1c2802dc05157ac781e07147763d35491f7995a6", "save_path": "github-repos/coq/elegaanz-info4-ltpf", "path": "github-repos/coq/elegaanz-info4-ltpf/info4-ltpf-1c2802dc05157ac781e07147763d35491f7995a6/TD05_winstr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040853, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.6965348781038142}}
{"text": "Require Coq.Lists.List.\nRequire Import Coq.Program.Basics.\nRequire Export Fiat.Common.Coq__8_4__8_5__Compat.\n\nSection LogicFacts.\n  Lemma or_false :\n    forall (P: Prop), P \\/ False <-> P.\n  Proof.\n    tauto.\n  Qed.\n\n  Lemma false_or :\n    forall (P Q: Prop),\n      (False <-> P \\/ Q) <-> (False <-> P) /\\ (False <-> Q).\n  Proof.\n    tauto.\n  Qed.\n\n  Lemma false_or' :\n    forall (P Q: Prop),\n      (P \\/ Q <-> False) <-> (False <-> P) /\\ (False <-> Q).\n  Proof.\n    tauto.\n  Qed.\n\n  Lemma equiv_false :\n    forall P,\n      (False <-> P) <-> (~ P).\n  Proof.\n    tauto.\n  Qed.\n\n  Lemma equiv_false' :\n    forall P,\n      (P <-> False) <-> (~ P).\n  Proof.\n    tauto.\n  Qed.\n\n  Lemma and_True :\n    forall P,\n      (P /\\ True) <-> P.\n  Proof.\n    tauto.\n  Qed.\n\n  Lemma not_exists_forall :\n    forall {A} (P: A -> Prop),\n      (~ (exists a, P a)) <-> (forall a, ~ P a).\n  Proof.\n    firstorder.\n  Qed.\n\n  Lemma not_and_implication :\n    forall (P Q: Prop),\n      ( ~ (P /\\ Q) ) <-> (P -> ~ Q).\n  Proof.\n    firstorder.\n  Qed.\n\n  Lemma eq_sym_iff :\n    forall {A} x y, @eq A x y <-> @eq A y x.\n  Proof.\n    split; intros; symmetry; assumption.\n  Qed.\n\n  Lemma fold_right_and_True {ls : list Prop}\n  : List.fold_right and True ls <-> (forall P, List.In P ls -> P).\n  Proof.\n    split; induction ls; simpl in *; repeat (subst || intros [] || intro);\n    repeat split; try assumption;\n    try apply IHls; intros; eauto;\n    match goal with\n      | [ H : _ |- _ ]\n        => apply H; solve [ left; reflexivity | right; assumption ]\n    end.\n  Qed.\n\n  Lemma fold_right_and_True_map {A} {P : A -> Prop} {ls : list A}\n  : List.fold_right and True (List.map P ls) <-> (forall x, List.In x ls -> P x).\n  Proof.\n    rewrite fold_right_and_True; split; intros H x Hx.\n    { apply H, List.in_map, Hx. }\n    { apply List.in_map_iff in Hx.\n      destruct Hx as [? [? ?]]; subst; eauto. }\n  Qed.\n\n  Lemma forall_iff {A B C}\n  : (forall x : A, (B x <-> C x)) -> ((forall x, B x) <-> (forall x, C x)).\n  Proof.\n    intro H; split; intros H' x; apply H, H'.\n  Qed.\n\n  Lemma forall_impl {A B C}\n  : (forall x : A, (impl (B x) (C x))) -> (impl (forall x, B x) (forall x, C x)).\n  Proof.\n    intro H; intros H' x; apply H, H'.\n  Qed.\n\n  Lemma and_distr_or_r A B C\n  : (A /\\ (B \\/ C)) <-> ((A /\\ B) \\/ (A /\\ C)).\n  Proof. tauto. Qed.\n  Lemma and_distr_or_l A B C\n  : ((B \\/ C) /\\ A) <-> ((B /\\ A) \\/ (C /\\ A)).\n  Proof. tauto. Qed.\n  Lemma ex_distr_or A B C\n  : (exists x : A, B x \\/ C x) <-> ((exists x : A, B x) \\/ (exists x : A, C x)).\n  Proof.\n    repeat ((intros [H0 H1]; revert H0 H1)\n            || (intros [H|H]; revert H)\n            || split\n            || intro);\n    first [ do 2 first [ left | esplit ]; eassumption\n          | do 2 first [ right | esplit ]; eassumption ].\n  Defined.\n\n  Lemma and_TrueP_L {P Q : Prop} (H : P) : P /\\ Q <-> Q.\n  Proof. tauto. Qed.\n  Lemma and_TrueP_R {P Q : Prop} (H : Q) : P /\\ Q <-> P.\n  Proof. tauto. Qed.\n  Lemma impl_distr_or {A B C : Prop}\n    : (A \\/ B -> C) <-> ((A -> C) /\\ (B -> C)).\n  Proof. tauto. Qed.\n  Lemma forall_distr_and {A B C}\n    : (forall x : A, B x /\\ C x) <-> ((forall x, B x) /\\ (forall x, C x)).\n  Proof.\n    split; intro H; split; intros; apply H.\n  Qed.\n  Lemma ex_eq_and {A P} y\n    : (exists x : A, y = x /\\ P x) <-> P y.\n  Proof.\n    split; [ intros [? ?] | intro; eexists ];\n      intuition try (tauto || congruence).\n  Qed.\n  Lemma ex_eq'_and {A P} y\n    : (exists x : A, x = y /\\ P x) <-> P y.\n  Proof.\n    split; [ intros [? ?] | intro; eexists ];\n      intuition try (tauto || congruence).\n  Qed.\n  Lemma ex_eq_snd_and {A B C} x\n    : (exists y : A * B, snd y = x /\\ C y) <-> (exists y : A, C (y, x)).\n  Proof.\n    split; intros [y H]; try destruct y; eexists; repeat intuition (subst; eauto; simpl).\n  Qed.\n  Lemma ex_eq'_snd_and {A B C} x\n    : (exists y : A * B, x = snd y /\\ C y) <-> (exists y : A, C (y, x)).\n  Proof.\n    split; intros [y H]; try destruct y; eexists; repeat intuition (subst; eauto; simpl).\n  Qed.\n  Lemma ex_eq_fst_and {A B C} x\n    : (exists y : A * B, fst y = x /\\ C y) <-> (exists y : B, C (x, y)).\n  Proof.\n    split; intros [y H]; try destruct y; eexists; repeat intuition (subst; eauto; simpl).\n  Qed.\n  Lemma ex_eq'_fst_and {A B C} x\n    : (exists y : A * B, x = fst y /\\ C y) <-> (exists y : B, C (x, y)).\n  Proof.\n    split; intros [y H]; try destruct y; eexists; repeat intuition (subst; eauto; simpl).\n  Qed.\n  Lemma forall_eq_and {A C} {D : _ -> Prop} x\n    : (forall y : A, y = x /\\ C y -> D y) <-> (C x -> D x).\n  Proof. repeat firstorder subst. Qed.\n  Lemma forall_eq'_and {A C} {D : _ -> Prop} x\n    : (forall y : A, x = y /\\ C y -> D y) <-> (C x -> D x).\n  Proof. repeat firstorder subst. Qed.\n  Lemma forall_eq_snd_and {A B C} {D : _ -> Prop} x\n    : (forall y : A * B, snd y = x /\\ C y -> D y) <-> (forall y : A, C (y, x) -> D (y, x)).\n  Proof. split; intros H y; try destruct y; repeat firstorder subst. Qed.\n  Lemma forall_eq'_snd_and {A B C} {D : _ -> Prop} x\n    : (forall y : A * B, x = snd y /\\ C y -> D y) <-> (forall y : A, C (y, x) -> D (y, x)).\n  Proof. split; intros H y; try destruct y; repeat firstorder subst. Qed.\n  Lemma forall_eq_fst_and {A B C} {D : _ -> Prop} x\n    : (forall y : A * B, fst y = x /\\ C y -> D y) <-> (forall y : B, C (x, y) -> D (x, y)).\n  Proof. split; intros H y; try destruct y; repeat firstorder subst. Qed.\n  Lemma forall_eq'_fst_and {A B C} {D : _ -> Prop} x\n    : (forall y : A * B, x = fst y /\\ C y -> D y) <-> (forall y : B, C (x, y) -> D (x, y)).\n  Proof. split; intros H y; try destruct y; repeat firstorder subst. Qed.\n  Lemma True_iff {P : Prop}\n    : P -> (P <-> True).\n  Proof. firstorder. Qed.\n  Lemma False_iff {P : Prop}\n    : ~P -> (P <-> False).\n  Proof. firstorder. Qed.\n  Lemma nnTrue : ~~True.\n  Proof. tauto. Qed.\n  Lemma and_False_r {P} : (P /\\ False) <-> False.\n  Proof. tauto. Qed.\n  Lemma and_False_l {P} : (False /\\ P) <-> False.\n  Proof. tauto. Qed.\n  Lemma and_True_r {P} : (P /\\ True) <-> P.\n  Proof. tauto. Qed.\n  Lemma and_True_l {P} : (True /\\ P) <-> P.\n  Proof. tauto. Qed.\n  Lemma or_False_r {P} : (P \\/ False) <-> P.\n  Proof. tauto. Qed.\n  Lemma or_False_l {P} : (False \\/ P) <-> P.\n  Proof. tauto. Qed.\n  Lemma or_True_r {P} : (P \\/ True) <-> True.\n  Proof. tauto. Qed.\n  Lemma or_True_l {P} : (True \\/ P) <-> True.\n  Proof. tauto. Qed.\n  Lemma ex_False {T} : (exists x : T, False) <-> False.\n  Proof. firstorder. Qed.\n  Lemma forall_True {T} : (forall x : T, True) <-> True.\n  Proof. firstorder. Qed.\n  Lemma forall_iff_nondep {A B} {C : Prop} (H : exists x : A, B x)\n    : (forall x : A, B x -> C) <-> C.\n  Proof. firstorder. Qed.\n  Lemma False_impl_iff_True {P : Prop}\n    : (False -> P) <-> True.\n  Proof. firstorder. Qed.\n  Lemma ex_True {T} : (exists x : T, True) <-> inhabited T.\n  Proof. firstorder. Qed.\n\n  Lemma ex_ind_iff {T P} {Q : _ -> Prop}\n    : (forall pf : @ex T P, Q pf) <-> forall (x : T) (y : P x), Q (ex_intro P x y).\n  Proof.\n    intuition; destruct_all (ex P); auto.\n  Qed.\n\n  Lemma pull_forall_iff {A} (P Q : A -> Prop)\n    : (forall x : A, (P x <-> Q x))\n      -> ((forall x : A, P x) <-> (forall x : A, Q x)).\n  Proof. firstorder eauto. Qed.\nEnd LogicFacts.\n\nCreate HintDb logic discriminated.\n#[global]\nHint Rewrite and_distr_or_l and_distr_or_r @ex_distr_or @impl_distr_or @forall_distr_and @ex_eq'_and @ex_eq_and @ex_eq'_fst_and @ex_eq'_snd_and @ex_eq_fst_and @ex_eq_snd_and @forall_eq'_fst_and @forall_eq'_snd_and @forall_eq_fst_and @forall_eq_snd_and and_assoc (True_iff (eq_refl true)) (False_iff nnTrue) @and_False_r @and_False_l @ex_False @and_True_l @and_True_r @or_False_l @or_False_r @or_True_l @or_True_r @forall_True (True_iff Bool.diff_false_true) (False_iff Bool.diff_false_true) @False_impl_iff_True @ex_True : logic.\nLtac setoid_rewrite_logic_step :=\n  first [ rewrite_strat repeat topdown hints logic\n        | setoid_rewrite ex_distr_or\n        | setoid_rewrite forall_distr_and\n        | setoid_rewrite ex_eq'_and\n        | setoid_rewrite ex_eq'_fst_and\n        | setoid_rewrite ex_eq'_snd_and\n        | setoid_rewrite ex_eq_and\n        | setoid_rewrite ex_eq_fst_and\n        | setoid_rewrite ex_eq_snd_and\n        | setoid_rewrite forall_eq'_and\n        | setoid_rewrite forall_eq'_fst_and\n        | setoid_rewrite forall_eq'_snd_and\n        | setoid_rewrite forall_eq_and\n        | setoid_rewrite forall_eq_fst_and\n        | setoid_rewrite forall_eq_snd_and\n        | setoid_rewrite False_impl_iff_True ].\nLtac setoid_rewrite_logic := repeat setoid_rewrite_logic_step.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Common/LogicFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.8519528057272544, "lm_q1q2_score": 0.6965348688841652}}
{"text": "(**\nMUパズル (MU Puzzle) の証明\n======\n\n2022_05_14 @suharahiromichi\n\n*)\n\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(**\n# MUパズルの証明\n*)\nSection MU_Puzzle.\n\n(**\nMUパズルで使用する文字を定義する。\n*)\n  Inductive MIU :=\n  | M\n  | I\n  | U.\n\n(**\nMUパズルの規則による文字列の生成規則を定義する。\n*)\n  Inductive MU : seq MIU -> Prop :=\n  | S_MU  : MU [:: M; I]\n  | S_xIU : forall x, MU (x ++ [:: I]) -> MU (x ++ [:: I; U])\n  | S_Mxx : forall x, MU ([:: M] ++ x) -> MU ([:: M] ++ x ++ x)\n  | S_xUy : forall x y, MU (x ++ [:: I; I; I] ++ y) -> MU (x ++ [:: U] ++ y)\n  | S_xy  : forall x y, MU (x ++ [:: U; U] ++ y) -> MU (x ++ y)\n  .\n\n(**\n文字列の I の数を算える関数 ci を定義する。\n*)\n  Fixpoint ci (s : seq MIU) : nat :=\n    match s with\n    | [::] => 0\n    | I :: s => (ci s).+1\n    | _ :: s => (ci s)\n    end.\n  \n(**\nci が、文字列の連結(cat)について分配則を満たすことを証明する。\n*)\n  Lemma ci_cat (x y : seq MIU) : ci (x ++ y) = ci x + ci y.\n  Proof.\n    elim: x => //.                        (* x = a :: x の場合 *)\n    case=> x IHx //=.                     (* a による場合分けする。 *)\n    rewrite addSn.\n    by rewrite IHx.\n  Qed.\n  \n(**\n補題の証明で使用するモジュラスについての補題を証明しておく。\nこれは一般に成立するわけではなく、\n``3 %| 2 * n`` の2と3が互いに素だからである。\n*)\n  Lemma l_mod_2n_eq (n : nat) : (3 %| n + n) = (3 %| n).\n  Proof.\n    rewrite addnn -mul2n.\n    by apply: Gauss_dvdr.\n  Qed.\n  \n(**\n補題を証明する。\n\n``MU s`` に対する帰納法を適用する。\n解りやすさのために、一律に対偶を適用する。\n*)\n  Lemma miu_inv (s : seq MIU) : MU s -> ~~ (3 %| ci s).\n  Proof.\n    elim=> //= [x | x | x y | x y] _;\n           apply: contraTT; rewrite 2!negbK.\n    \n    (* 3 %| ci (x ++ [:: I; U]) -> 3 %| ci (x ++ [:: I]) *)\n    - have -> : x ++ [:: I; U] = (x ++ [:: I]) ++ [:: U]\n        by rewrite -catA cat1s.\n      by rewrite ci_cat //= addn0.\n      \n    (* 3 %| ci (x ++ x) -> 3 %| ci x *)\n    - by rewrite ci_cat l_mod_2n_eq.\n\n    (* 3 %| ci (x ++ U :: y) -> 3 %| ci (x ++ [:: I, I, I & y]) *)\n    - have -> : x ++ (U :: y) = x ++ [:: U] ++ y by done.\n      rewrite 2!ci_cat /= add0n.\n      have -> : x ++ (I :: I :: I :: y) = x ++ [:: I; I; I] ++ y by done.\n      rewrite 2!ci_cat /=.\n      have -> : ci x + (3 + ci y) = ci x + ci y + 3\n        by rewrite -addnACl [ci y + ci x]addnC.\n      by move=> H; rewrite dvdn_addl.\n      \n    (* 3 %| ci (x ++ y) -> 3 %| ci (x ++ [:: U, U & y]) *)\n    - have -> : x ++ (U :: U :: y) = x ++ [:: U; U] ++ y by done.\n      by rewrite 3!ci_cat /= add0n.\n  Qed.\n  \n(**\n補題を適用して背理法を適用すると、\n\n``3 %| ci [:: M; U]``\n\nを証明すればよい。これは計算すれば、\n\n``3 %| 0``\n\nであり、成立することは自明である。\n*)\n  Theorem mu : ~ MU [:: M; U].\n  Proof.\n    move/miu_inv/negP.\n    by apply.\n  Qed.\n  \nEnd MU_Puzzle.\n\n(**\n\n# 参考\n\n[1] MUパズル https://www.principia-m.com/doc/0/\n\n[1] MUパズル https://zenn.dev/hatsugai/articles/dacd6c19bbd210\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/ssr/ssr_mu_puzzle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6965050894627659}}
{"text": "Require Import Reals Interval.Tactic.\n\nOpen Scope R_scope.\n\nNotation pow2 := (Raux.bpow Zaux.radix2).\n\n(*\nExample taken from:\nWilliam J. Cody Jr. and William Waite\nSoftware Manual for the Elementary Functions\n*)\n\nGoal forall x : R, Rabs x <= 35/100 ->\n  let p := fun t => 1 * pow2 (-2) + t * (1116769 * pow2 (-28)) in\n  let q := fun t => 1 * pow2 (-1) + t * (13418331 * pow2 (-28)) in\n  let r := 2 * (x * p (x^2) / (q (x^2) - x * p (x^2)) + 1 * pow2 (-1)) in\n  Rabs ((r - exp x) / exp x) <= 17 * pow2 (-34).\nProof.\nintros x Hx p q r.\nunfold r, p, q.\ninterval with (i_prec 40, i_bisect x, i_taylor x, i_degree 3).\nQed.\n", "meta": {"author": "validsdp", "repo": "coq-interval", "sha": "4035680e718ae256601e00454279f1770e5c15e8", "save_path": "github-repos/coq/validsdp-coq-interval", "path": "github-repos/coq/validsdp-coq-interval/coq-interval-4035680e718ae256601e00454279f1770e5c15e8/testsuite/example-20150105.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6965050721658747}}
{"text": "From Cyclic_PA.Maths Require Import naturals.\nFrom Cyclic_PA.Maths Require Import lists.\nFrom Cyclic_PA.Logic Require Import definitions.\n\nRequire Import Lia.\nRequire Import Nat.\nRequire Import List.\nRequire Import Coq.Arith.Wf_nat.\n\nOpen Scope bool_scope.\nOpen Scope list_scope.\n\nImport ListNotations.\n\n(*Language*)\nInductive term : Type :=\n| zero : term\n| succ : term -> term\n| plus : term -> term -> term\n| times : term -> term -> term\n| var : nat -> term.\n\nInductive atomic_formula : Type :=\n| equ : term -> term -> atomic_formula.\n\nInductive formula : Type :=\n| atom : atomic_formula -> formula\n| neg : formula -> formula\n| lor : formula -> formula -> formula\n| univ : nat -> formula -> formula.\n\n(*Logical Connectives*)\nFixpoint num_conn (a : formula) : nat :=\nmatch a with\n| atom a' => 0\n| neg a' => S (num_conn a')\n| lor a1 a2 => S ((num_conn a1) + (num_conn a2))\n| univ n a' => S (num_conn a')\nend.\n\n(*Boolean Equality*)\nFixpoint term_eqb (s t : term) : bool :=\nmatch s, t with\n| zero, zero => true\n| succ s', succ t' => term_eqb s' t'\n| plus s1 s2, plus t1 t2 => term_eqb s1 t1 && term_eqb s2 t2\n| times s1 s2, times t1 t2 => term_eqb s1 t1 && term_eqb s2 t2\n| var m, var n => nat_eqb m n\n| _, _ => false\nend.\n\nDefinition atom_eqb (a b : atomic_formula) : bool :=\nmatch a, b with\n| equ s1 s2, equ t1 t2 => term_eqb s1 t1 && term_eqb s2 t2\nend.\n\nFixpoint form_eqb (a b : formula) : bool :=\nmatch a, b with\n| atom a', atom b' => atom_eqb a' b'\n| neg a', neg b' => form_eqb a' b'\n| lor a1 a2, lor b1 b2 => form_eqb a1 b1 && form_eqb a2 b2\n| univ m a', univ n b' => nat_eqb m n && form_eqb a' b'\n| _, _ => false\nend.\n\n(*Given some term t, returns t+1 if the formula is closed, 0 otherwise*)\nFixpoint eval (t : term) : nat :=\nmatch t with\n| zero => 1\n| succ t1 =>\n    (match eval t1 with\n    | 0 => 0\n    | S n => S (S n)\n    end)\n| plus t1 t2 =>\n    (match eval t1, eval t2 with\n    | S n, S m => S (n + m)\n    | _, _ => 0\n    end)\n| times t1 t2 =>\n    (match eval t1, eval t2 with\n    | S n, S m => S (n * m)\n    | _, _ => 0\n    end)\n| var n => 0\nend.\n\n(*Natural Numbers as terms*)\nFixpoint represent (n : nat) : term :=\nmatch n with\n| O => zero\n| S n' => succ (represent n')\nend.\n\n(*Decidability Prediate*)\nInductive ternary : Type :=\n| correct : ternary\n| incorrect : ternary\n| undefined : ternary.\n\nDefinition correctness (a : atomic_formula) : ternary :=\nmatch a with\n| equ t1 t2 =>\n    (match eval t1, eval t2 with\n    | S n, S m =>\n        (match nat_eqb (eval t1) (eval t2) with\n        | true => correct\n        | false => incorrect\n        end)\n    | _, _ => undefined\n    end)\nend.\n\nDefinition correct_a (a : atomic_formula) : bool :=\nmatch correctness a with\n| correct => true\n| _ => false\nend.\n\nDefinition incorrect_a (a : atomic_formula) : bool :=\nmatch correctness a with\n| incorrect => true\n| _ => false\nend.\n\nFixpoint free_list_t (t : term) : list nat :=\nmatch t with\n| zero => nil\n| succ t1 => free_list_t t1\n| plus t1 t2 => nodup nat_eq_dec ((free_list_t t1) ++ (free_list_t t2))\n| times t1 t2 => nodup nat_eq_dec ((free_list_t t1) ++ (free_list_t t2))\n| var n => [n]\nend.\n\nDefinition free_list_a (a : atomic_formula) : list nat :=\nmatch a with\n| equ t1 t2 => nodup nat_eq_dec ((free_list_t t1) ++ (free_list_t t2))\nend.\n\nFixpoint free_list (A : formula) : list nat :=\nmatch A with\n| atom a => free_list_a a\n| neg B => free_list B\n| lor B D => nodup nat_eq_dec ((free_list B) ++ (free_list D))\n| univ n B => remove nat_eq_dec n (free_list B)\nend.\n\n(*Closedness*)\nFixpoint closed_t (t : term) : bool :=\nmatch t with\n| zero => true\n| succ t1 => closed_t t1\n| plus t1 t2 => closed_t t1 && closed_t t2\n| times t1 t2 => closed_t t1 && closed_t t2\n| var n => false\nend.\n\nDefinition closed_a (a : atomic_formula) : bool :=\n  match a with\n  | equ t1 t2 => closed_t t1 && closed_t t2\n  end.\n\nFixpoint closed (A : formula) : bool :=\nmatch A with\n| atom a => closed_a a\n| neg B => closed B\n| lor B D => closed B && closed D\n| univ n B =>\n  (match closed B with\n   | true => true\n   | false =>\n    (match free_list B with\n    | [] => false\n    | m :: l => nat_eqb m n && list_eqb l []\n    end)\n  end)\nend.\n\n(*Closed Terms*)\nDefinition c_term : Type := {t : term & closed_t t = true}.\n\nDefinition closing (t : term) (Ht : closed_t t = true) : c_term. exists t. exact Ht. Defined.\n\nDefinition value (c : c_term) : nat := eval (projT1 c) - 1.\n\n(*Substitution of free occurrences of x_n with t in a formula f*)\nFixpoint substitution_t (T : term) (n : nat) (t : term) : term :=\nmatch T with\n| zero => T\n| succ T1 => succ (substitution_t T1 n t)\n| plus T1 T2 => plus (substitution_t T1 n t) (substitution_t T2 n t)\n| times T1 T2 => times (substitution_t T1 n t) (substitution_t T2 n t)\n| var m =>\n    (match nat_eqb m n with\n    | true => t\n    | false => T\n    end)\nend.\n\nDefinition substitution_a (a : atomic_formula) (n : nat) (t : term)\n  : atomic_formula :=\nmatch a with\n  equ t1 t2 => equ (substitution_t t1 n t) (substitution_t t2 n t)\nend.\n\nFixpoint substitution (A : formula) (n : nat) (t : term) : formula :=\nmatch A with\n| atom a => atom (substitution_a a n t)\n| neg B => neg (substitution B n t)\n| lor B D => lor (substitution B n t) (substitution D n t)\n| univ m B => \n    (match nat_eqb m n with\n    | true => A\n    | false => univ m (substitution B n t)\n    end)\nend.\n\nFixpoint closure_type_t (t : term) (c : c_term) (L : list nat) : term :=\nmatch L with\n| [] => t\n| x :: L' => closure_type_t (substitution_t t x (projT1 c)) c L'\nend.\n\nDefinition closure_t (t : term) (c : c_term) := closure_type_t t c (free_list_t t).\n\nFixpoint closure_type (A : formula) (c : c_term) (L : list nat) : formula :=\nmatch L with\n| [] => A\n| x :: L' => closure_type (substitution A x (projT1 c)) c L'\nend.\n\nDefinition closure (A : formula) (c : c_term) := closure_type A c (free_list A).\n\n(*Equality Lemmas*)\nLemma term_eqb_refl :\n    forall (t : term),\n        term_eqb t t = true.\nProof.\ninduction t;\nunfold term_eqb; fold term_eqb;\ntry rewrite IHt;\ntry rewrite IHt1,IHt2;\ntry reflexivity.\napply nat_eqb_refl.\nQed.\n\nLemma atom_eqb_refl :\n    forall (a : atomic_formula),\n        atom_eqb a a = true.\nProof.\ndestruct a as [t1 t2].\nunfold atom_eqb.\nrewrite term_eqb_refl.\napply term_eqb_refl.\nQed.\n\nLemma form_eqb_refl :\n    forall (f : formula),\n        form_eqb f f = true.\nProof.\ninduction f as [a | f IH | f1 IH1 f2 IH2 | n f IH].\n- apply atom_eqb_refl.\n- apply IH.\n- unfold form_eqb; fold form_eqb.\n  rewrite IH1.\n  apply IH2.\n- unfold form_eqb; fold form_eqb.\n  rewrite nat_eqb_refl.\n  apply IH.\nQed.\n\nLemma term_beq_eq :\n    forall (s t : term),\n        term_eqb s t = true ->\n            s = t.\nProof.\ninduction s;\nintros t EQ;\ndestruct t;\ninversion EQ as [EQ'];\ntry destruct (and_bool_prop _ _ EQ') as [EQ1 EQ2];\ntry rewrite (IHs _ EQ');\ntry rewrite (IHs1 _ EQ1),(IHs2 _ EQ2);\ntry rewrite (nat_eqb_eq _ _ EQ');\nreflexivity.\nQed.\n\nLemma atom_beq_eq :\n    forall (a b : atomic_formula),\n        atom_eqb a b = true ->\n            a = b.\nProof.\nintros a b EQ.\ndestruct a as [al ar],b as [bl br].\ndestruct (and_bool_prop _ _ EQ) as [EQ1 EQ2].\nrewrite (term_beq_eq _ _ EQ1),(term_beq_eq _ _ EQ2).\nreflexivity.\nQed.\n\nLemma form_eqb_eq :\n    forall (A B : formula),\n        form_eqb A B = true ->\n            A = B.\nProof.\ninduction A;\nintros B EQ;\ndestruct B;\ninversion EQ as [EQ'];\ntry destruct (and_bool_prop _ _ EQ') as [EQ1 EQ2].\n- rewrite (atom_beq_eq _ _ EQ').\n  reflexivity.\n- rewrite (IHA _ EQ').\n  reflexivity.\n- rewrite (IHA1 _ EQ1),(IHA2 _ EQ2).\n  reflexivity.\n- rewrite (nat_eqb_eq _ _ EQ1),(IHA _ EQ2).\n  reflexivity.\nQed.\n\nDefinition form_eq_dec : forall (a b : formula), {a = b} + {a <> b}.\nintros a b.\ncase (form_eqb a b) eqn:EQ.\n- left. apply form_eqb_eq, EQ.\n- right. intros FAL.\n  destruct FAL.\n  rewrite form_eqb_refl in EQ.\n  inversion EQ.\nQed.\n\n(*Properties of the evaluation function*)\nLemma eval_succ_lemma :\n    forall (t : term),\n        eval (succ t) > 0 ->\n            eval t > 0.\nProof.\nintros t Et.\nunfold eval in Et;\nfold eval in Et.\ndestruct (eval t).\n- inversion Et.\n- lia.\nQed.\n\nLemma eval_plus_lemma :\n    forall (t1 t2 : term),\n        eval (plus t1 t2) > 0 ->\n            eval t1 > 0 /\\ eval t2 > 0.\nProof.\nintros t1 t2 Et.\nunfold eval in Et;\nfold eval in Et.\ndestruct (eval t1);\ndestruct (eval t2);\ninversion Et as [];\nsplit;\nlia.\nQed.\n\nLemma eval_times_lemma :\n    forall (t1 t2 : term),\n        eval (times t1 t2) > 0 ->\n            eval t1 > 0 /\\ eval t2 > 0.\nProof.\nintros t1 t2 Et.\nunfold eval in Et;\nfold eval in Et.\ndestruct (eval t1);\ndestruct (eval t2);\ninversion Et as [];\nsplit;\nlia.\nQed.\n\nLemma eval_closed :\n    forall (t : term),\n        eval t > 0 ->\n            closed_t t = true.\nProof.\nintros t Et.\ninduction t.\n- reflexivity.\n- apply IHt.\n  apply eval_succ_lemma.\n  apply Et.\n- destruct (eval_plus_lemma _ _ Et) as [Et1 Et2].\n  unfold closed_t;\n  fold closed_t.\n  rewrite (IHt1 Et1).\n  rewrite (IHt2 Et2).\n  reflexivity.\n- destruct (eval_times_lemma _ _ Et) as [Et1 Et2].\n  unfold closed_t;\n  fold closed_t.\n  rewrite (IHt1 Et1).\n  rewrite (IHt2 Et2).\n  reflexivity.\n- inversion Et.\nQed.\n\nLemma closed_eval :\n    forall (t : term),\n        closed_t t = true ->\n            eval t > 0.\nProof.\nintros t Ct.\ninduction t.\n- unfold eval, gt, lt.\n  reflexivity.\n- apply IHt in Ct.\n  unfold eval; fold eval.\n  destruct (eval t).\n  + inversion Ct.\n  + lia.\n- apply and_bool_prop in Ct.\n  destruct Ct as [Ct1 Ct2].\n  apply IHt1 in Ct1.\n  apply IHt2 in Ct2.\n  unfold eval; fold eval.\n  destruct (eval t1);\n  destruct (eval t2).\n  + inversion Ct1.\n  + inversion Ct1.\n  + inversion Ct2.\n  + lia.\n- apply and_bool_prop in Ct.\n  destruct Ct as [Ct1 Ct2].\n  apply IHt1 in Ct1.\n  apply IHt2 in Ct2.\n  unfold eval; fold eval.\n  destruct (eval t1);\n  destruct (eval t2).\n  + inversion Ct1.\n  + inversion Ct1.\n  + inversion Ct2.\n  + lia.\n- inversion Ct.\nQed.\n\nLemma eval_eq_eval_subst_eq :\n  forall (T s t : term) (n : nat),\n      eval s = eval t ->\n          eval (substitution_t T n s) = eval (substitution_t T n t).\nProof.\nintros T s t n EQ.\ninduction T;\nunfold substitution_t; fold substitution_t;\nunfold eval; fold eval.\n- reflexivity.\n- rewrite IHT.\n  reflexivity. \n- rewrite IHT1,IHT2.\n  reflexivity.\n- rewrite IHT1,IHT2.\n  reflexivity.\n- case (nat_eqb n0 n).\n  + apply EQ.\n  + reflexivity.\nQed.\n\nLemma eval_eq_subst_cor_eq :\n  forall (a : atomic_formula) (s t : term) (n : nat),\n      eval s = eval t ->\n          correctness (substitution_a a n s) = correct ->\n              correctness (substitution_a a n t) = correct.\nProof.\nintros [t1 t2] s t n EQ COR.\nunfold substitution_a, correctness in *.\ndestruct (eval_eq_eval_subst_eq t1 s t n EQ).\ndestruct (eval_eq_eval_subst_eq t2 s t n EQ).\napply COR.\nQed.\n\nLemma equ_cor_eval_eq :\n  forall (s t : term),\n      correct_a (equ s t) = true ->\n          eval s = eval t.\nProof.\nintros s t COR.\nunfold correct_a, correctness in *.\ndestruct (eval s);\ndestruct (eval t);\ninversion COR.\ncase (nat_eqb (S n) (S n0)) eqn:EQ.\n- apply (nat_eqb_eq _ _ EQ).\n- inversion COR.\nQed.\n\n(*Lemmas about representing natural numbers*)\nLemma succ_represent_comm :\n    forall (n : nat),\n        succ (represent n) = represent (S n).\nProof.\nintros n.\nunfold represent.\nreflexivity.\nQed.\n\nLemma eval_represent_non_zero :\n    forall (n : nat),\n        eval (represent n) > 0.\nProof.\ninduction n.\n- unfold represent,eval,gt,lt.\n  reflexivity.\n- unfold represent,eval,gt,lt.\n  fold eval represent.\n  destruct (eval (represent n)).\n  + inversion IHn.\n  + lia.\nQed.\n\nLemma eval_represent_is_succ :\n    forall (n : nat),\n        eval (represent n) = (S n).\nProof.\ninduction n.\n- reflexivity.\n- unfold eval, represent.\n  fold eval represent.\n  destruct (eval (represent n)).\n  + inversion IHn.\n  + rewrite IHn.\n    reflexivity.\nQed.\n\nLemma represent_closed :\n    forall (n : nat),\n        closed_t (represent n) = true.\nProof.\nintros n.\napply eval_closed, eval_represent_non_zero.\nQed.\n\nLemma represent_eval :\n    forall (t : term),\n        closed_t t = true ->\n            eval (represent ((eval t) - 1)) = (eval t).\nProof.\nintros t Ct.\ndestruct t;\nunfold eval, represent;\nfold eval represent;\nunfold closed_t in Ct;\nfold closed_t in Ct;\ntry destruct (and_bool_prop _ _ Ct) as [Ct1 Ct2].\n- reflexivity.\n- pose proof (closed_eval _ Ct) as Et.\n  destruct (eval t).\n  + inversion Et.\n  + apply eval_represent_is_succ.\n- pose proof (closed_eval _ Ct1) as Et1.\n  pose proof (closed_eval _ Ct2) as Et2.\n  destruct (eval t1).\n  + inversion Et1.\n  + destruct (eval t2).\n    * inversion Et2.\n    * unfold sub; fold sub.\n      rewrite minus_n_0.\n      apply eval_represent_is_succ.\n- pose proof (closed_eval _ Ct1) as Et1.\n  pose proof (closed_eval _ Ct2) as Et2.\n  destruct (eval t1).\n  + inversion Et1.\n  + destruct (eval t2).\n    * inversion Et2.\n    * unfold sub; fold sub.\n      rewrite minus_n_0.\n      apply eval_represent_is_succ.\n- inversion Ct. \nQed.\n\n(*Results about lists of free variables*)\nLemma free_list_remove_dups_idem_t :\n    forall (t : term),\n        free_list_t t = nodup nat_eq_dec (free_list_t t).\nProof.\ninduction t;\nunfold free_list_t;\nfold free_list_t;\ntry rewrite remove_dups_twice;\ntry reflexivity.\napply IHt.\nQed.\n\nLemma free_list_remove_dups_idem_a :\n    forall (a : atomic_formula),\n        free_list_a a = nodup nat_eq_dec (free_list_a a).\nProof.\nintros [t1 t2].\nunfold free_list_a.\nrewrite remove_dups_twice.\nreflexivity.\nQed.\n\nLemma free_list_remove_dups_idem :\n    forall (A : formula),\n        free_list A = nodup nat_eq_dec (free_list A).\nProof.\ninduction A.\n- apply free_list_remove_dups_idem_a.\n- apply IHA.\n- unfold free_list; fold free_list.\n  rewrite remove_dups_twice.\n  reflexivity.\n- unfold free_list; fold free_list.\n  rewrite IHA at 1.\n  apply remove_dups_order.\nQed.\n\nLemma free_list_univ_empty_cases :\n    forall (A : formula) (n : nat),\n        free_list (univ n A) = [] ->\n            free_list A = [n] \\/ free_list A = [].\nProof.\nintros A n FREE.\ninduction A;\nunfold free_list in *; fold free_list in *.\n- rewrite free_list_remove_dups_idem_a in FREE.\n  rewrite free_list_remove_dups_idem_a.\n  apply remove_n_dups_empty.\n  apply FREE.\n- apply IHA.\n  apply FREE.\n- apply remove_n_dups_empty.\n  apply FREE.\n- rewrite free_list_remove_dups_idem.\n  rewrite remove_dups_order.\n  apply remove_n_dups_empty.\n  rewrite <- remove_dups_order.\n  rewrite <- free_list_remove_dups_idem.\n  apply FREE.\nQed.\n\n(*Closed and Free List interrelations*)\nLemma free_list_closed_t :\n    forall (t : term),\n        free_list_t t = [] ->\n            closed_t t = true.\nProof.\nintros t FREE.\ninduction t;\nunfold closed_t; fold closed_t;\nunfold free_list_t in FREE; fold free_list_t in FREE.\n- reflexivity.\n- apply IHt.\n  apply FREE.\n- apply remove_dups_empty in FREE.\n  destruct (app_eq_nil _ _ FREE) as [L1 L2].\n  rewrite (IHt1 L1).\n  apply (IHt2 L2).\n- apply remove_dups_empty in FREE.\n  destruct (app_eq_nil _ _ FREE) as [L1 L2].\n  rewrite (IHt1 L1).\n  apply (IHt2 L2).\n- inversion FREE.\nQed.\n\nLemma free_list_closed_a :\n    forall (a : atomic_formula),\n        free_list_a a = [] ->\n            closed_a a = true.\nProof.\nintros [t1 t2] FREE.\nunfold closed_a.\napply remove_dups_empty in FREE.\ndestruct (app_eq_nil _ _ FREE) as [L1 L2].\nrewrite (free_list_closed_t _ L1).\napply (free_list_closed_t _ L2).\nQed.\n\nLemma free_list_closed :\n    forall (A : formula),\n        free_list A = [] ->\n            closed A = true.\nProof.\nintros A FREE.\ninduction A;\nunfold closed; fold closed;\nunfold free_list in FREE; fold free_list in FREE.\n- apply free_list_closed_a, FREE.\n- apply IHA, FREE.\n- destruct (app_eq_nil _ _ (remove_dups_empty _ FREE)) as [L1 L2].\n  rewrite (IHA1 L1).\n  apply (IHA2 L2).\n- rewrite free_list_remove_dups_idem in FREE.\n  destruct (remove_n_dups_empty _ _ FREE) as [Ln | LE].\n  + rewrite <- free_list_remove_dups_idem in Ln.\n    destruct (closed A) eqn:CA.\n    * reflexivity.\n    * rewrite Ln.\n      rewrite nat_eqb_refl.\n      apply list_eqb_refl.\n  + rewrite IHA.\n    * reflexivity.\n    * rewrite free_list_remove_dups_idem.\n      apply LE.\nQed.\n\nLemma closed_free_list_t :\n    forall (t : term),\n        closed_t t = true ->\n            free_list_t t = [].\nProof.\nintros t Ct.\ninduction t;\nunfold closed_t in Ct; fold closed_t in Ct;\nunfold free_list_t; fold free_list_t;\ntry destruct (and_bool_prop _ _ Ct) as [Ct1 Ct2].\n- reflexivity.\n- apply (IHt Ct).\n- rewrite (IHt1 Ct1).\n  rewrite (IHt2 Ct2).\n  reflexivity.\n- rewrite (IHt1 Ct1).\n  rewrite (IHt2 Ct2).\n  reflexivity.\n- inversion Ct.\nQed.\n\nLemma closed_free_list_a :\n    forall (a : atomic_formula),\n        closed_a a = true ->\n            free_list_a a = [].\nProof.\nintros [t1 t2] Ca.\nunfold free_list_a.\ndestruct (and_bool_prop _ _ Ca) as [Ct1 Ct2].\nrewrite (closed_free_list_t _ Ct1), (closed_free_list_t _ Ct2).\nreflexivity.\nQed.\n\nLemma closed_free_list :\n    forall (A : formula),\n        closed A = true ->\n            free_list A = [].\nProof.\nintros A CA.\ninduction A;\nunfold closed in CA; fold closed in CA;\nunfold free_list; fold free_list.\n- apply closed_free_list_a, CA.\n- apply IHA, CA.\n- destruct (and_bool_prop _ _ CA) as [CA1 CA2].\n  rewrite (IHA1 CA1), (IHA2 CA2).\n  reflexivity.\n- destruct (closed A).\n  + rewrite (IHA CA).\n    reflexivity.\n  + destruct (free_list A).\n    * inversion CA.\n    * apply and_bool_prop in CA as [EQ1 EQ2].\n      apply list_eqb_eq in EQ2.\n      rewrite EQ2.\n      unfold remove.\n      apply nat_eqb_eq in EQ1.\n      destruct EQ1.\n      case (nat_eq_dec n0 n0) as [_ | FAL].\n      --  reflexivity.\n      --  contradict FAL.\n          reflexivity.\nQed.\n\nLemma closed_univ :\n    forall (A : formula) (n : nat),\n        closed (univ n A) = true ->\n            closed A = true \\/ free_list A = [n].\nProof.\nintros A n CuA.\ndestruct (free_list_univ_empty_cases _ _ (closed_free_list _ CuA)) as [Ln | LE].\n- right.\n  apply Ln.\n- left.\n  apply free_list_closed, LE.\nQed.\n\n(*Correctness Lemmas*)\nLemma correctness_decid :\n    forall (a : atomic_formula),\n        closed_a a = true ->\n            sum (correct_a a = true) (incorrect_a a = true).\nProof.\nintros [t1 t2] Ca.\ndestruct (and_bool_prop _ _ Ca) as [Ct1 Ct2].\napply closed_eval in Ct1.\napply closed_eval in Ct2.\nunfold correct_a.\nunfold incorrect_a.\nunfold correctness.\ndestruct (eval t1).\n- exfalso.\n  inversion Ct1.\n- destruct (eval t2).\n  + exfalso.\n    inversion Ct2. \n  + destruct (nat_eqb (S n) (S n0)).\n    * left.\n      reflexivity.\n    * right.\n      reflexivity.\nQed.\n\nLemma correct_atom_symm :\n    forall (s t : term),\n        correct_a (equ s t) = true ->\n            correct_a (equ t s) = true.\nProof.\nintros s t COR.\nunfold correct_a in *.\nunfold correctness in *.\ndestruct (eval s);\ndestruct (eval t);\ninversion COR as [COR1].\nrewrite nat_eqb_symm.\nunfold nat_eqb. fold nat_eqb.\nrepeat rewrite COR1.\nreflexivity.\nQed.\n\n(*Substitution Lemmas*)\nLemma subst_remove_t : forall (T t : term) (n : nat),\n  closed_t t = true ->\n  free_list_t (substitution_t T n t) = remove nat_eq_dec n (free_list_t T).\nProof.\nintros. induction T; auto.\n- simpl. rewrite IHT1, IHT2.\n  rewrite remove_dups_order. rewrite remove_app. auto.\n- simpl. rewrite IHT1, IHT2.\n  rewrite remove_dups_order. rewrite remove_app. auto.\n- simpl. case_eq (nat_eqb n0 n); intros; auto.\n  + apply nat_eqb_eq in H0.\n    destruct H0.\n    case (nat_eq_dec n0 n0) as [_ | FAL].\n    * apply closed_free_list_t, H.\n    * contradict FAL.\n      reflexivity.\n  + case (nat_eq_dec n n0) as [FAL | _].\n    * destruct FAL.\n      rewrite nat_eqb_refl in H0.\n      inversion H0.\n    * reflexivity.\nQed.\n\nLemma subst_remove_a : forall (a : atomic_formula) (n : nat) (t : term),\n  closed_t t = true ->\n  free_list_a (substitution_a a n t) = remove nat_eq_dec n (free_list_a a).\nProof.\nintros. destruct a as [t1 t2]. simpl.\nrewrite (subst_remove_t t1 _ _ H). rewrite (subst_remove_t t2 _ _ H).\nrewrite remove_dups_order. rewrite remove_app. auto.\nQed.\n\nLemma subst_remove : forall (A : formula) (n : nat) (t : term),\n  closed_t t = true ->\n  free_list (substitution A n t) = remove nat_eq_dec n (free_list A).\nProof.\nintros. induction A; auto; simpl.\n- rewrite (subst_remove_a _ _ _ H). auto.\n- rewrite IHA1, IHA2.\n  rewrite remove_dups_order. rewrite remove_app. auto.\n- destruct (nat_eqb n0 n) eqn:Hn.\n  + rewrite (nat_eqb_eq _ _ Hn). rewrite remove_remove_eq. auto.\n  + simpl. rewrite IHA. apply remove_remove_comm.\nQed.\n\nLemma one_var_free_lemma_a : forall (a : atomic_formula) (n : nat) (t : term),\n  closed_t t = true ->\n  free_list_a a = [n] ->\n  closed_a (substitution_a a n t) = true.\nProof.\nintros.\napply free_list_closed_a. \nrewrite (subst_remove_a _ _ _ H).\nrewrite H0. simpl. case (nat_eq_dec n n) as [_ | FAL]. auto.\ncontradict FAL.\nreflexivity.\nQed.\n\nLemma one_var_free_lemma : forall (A : formula) (n : nat) (t : term),\n  closed_t t = true ->\n  free_list A = [n] ->\n  closed (substitution A n t) = true.\nProof.\nintros.\napply free_list_closed.\nrewrite (subst_remove _ _ _ H).\nrewrite H0. simpl. case (nat_eq_dec n n) as [_ | FAL]. auto.\ncontradict FAL.\nreflexivity.\nQed.\n\nLemma subst_one_var_free : forall (A : formula) (n : nat) (t : term),\n  closed_t t = true ->\n  closed (substitution A n t) = true ->\n  free_list A = [n] \\/ free_list A = [].\nProof.\nintros.\npose proof (subst_remove A n t H).\napply closed_free_list in H0. rewrite H0 in H1. symmetry in H1.\nrewrite free_list_remove_dups_idem in H1. apply remove_n_dups_empty in H1.\ndestruct H1.\n- left. rewrite free_list_remove_dups_idem. apply H1.\n- right. rewrite free_list_remove_dups_idem. apply H1.\nQed.\n\nLemma closed_lor : forall (B D : formula),\n  closed (lor B D) = true -> closed B = true /\\ closed D = true.\nProof.\nintros. simpl in H. split.\n- case_eq (closed B); case_eq (closed D); intros; auto;\n  rewrite H0 in H; rewrite H1 in H; inversion H.\n- case_eq (closed B); case_eq (closed D); intros; auto;\n  rewrite H0 in H; rewrite H1 in H; inversion H.\nQed.\n\nLemma closed_subst_eq_aux_t : forall (T : term) (n : nat) (t : term),\n  member n (free_list_t T) = false -> substitution_t T n t = T.\nProof.\nintros.\ninduction T; auto.\n- apply IHT in H. simpl. rewrite H. auto.\n- simpl. simpl in H. destruct (member_remove_dups_concat _ _ _ H).\n  rewrite IHT1, IHT2.\n  + auto.\n  + apply H1.\n  + apply H0.\n- simpl. simpl in H. destruct (member_remove_dups_concat _ _ _ H).\n  rewrite IHT1, IHT2.\n  + auto.\n  + apply H1.\n  + apply H0.\n- simpl in H. simpl. case_eq (nat_eqb n0 n); intros.\n  + rewrite H0 in H. inversion H.\n  + auto.\nQed.\n\nLemma closed_subst_eq_aux_a : forall (a : atomic_formula) (n : nat) (t : term),\n  member n (free_list_a a) = false -> substitution_a a n t = a.\nProof.\nintros. destruct a as [t1 t2]. simpl. simpl in H.\ndestruct (member_remove_dups_concat _ _ _ H).\nrewrite (closed_subst_eq_aux_t t1 n t), (closed_subst_eq_aux_t t2 n t).\n- auto.\n- apply H1.\n- apply H0.\nQed.\n\nLemma closed_subst_eq_aux : forall (A : formula) (n : nat) (t : term),\n  member n (free_list A) = false -> substitution A n t = A.\nProof.\nintros.\ninduction A.\n- simpl. rewrite closed_subst_eq_aux_a; auto.\n- simpl in H. simpl. rewrite (IHA H). auto.\n- simpl. simpl in H. destruct (member_remove_dups_concat _ _ _ H).\n  rewrite IHA1, IHA2.\n  + auto.\n  + apply H1.\n  + apply H0.\n- simpl. case_eq (nat_eqb n0 n); intros; auto.\n  simpl in H. rewrite IHA. \n  + auto.\n  + apply (member_remove _ _ _ H0 H).\nQed.\n\nLemma closed_subst_eq_t : forall (n : nat) (T t : term),\n  closed_t T = true -> substitution_t T n t = T.\nProof.\nintros.\napply closed_subst_eq_aux_t.\napply closed_free_list_t in H.\nrewrite H. auto.\nQed.\n\nLemma closed_subst_eq_a : forall (a : atomic_formula) (n : nat) (t : term),\n  closed_a a = true -> substitution_a a n t = a.\nProof.\nintros.\napply closed_subst_eq_aux_a.\napply closed_free_list_a in H.\nrewrite H. auto.\nQed.\n\nLemma closed_subst_eq : forall (A : formula) (n : nat) (t : term),\n  closed A = true -> substitution A n t = A.\nProof.\nintros.\napply closed_subst_eq_aux.\napply closed_free_list in H.\nrewrite H. auto.\nQed.\n\nLemma closed_subst_closed_t : forall (s t : term) (n : nat), closed_t s = true -> closed_t (substitution_t s n t) = true.\nProof.\nintros s t n CS.\ninduction s;\nunfold substitution_t; fold substitution_t.\n3, 4: unfold closed_t in *; fold closed_t in *;\n      destruct (and_bool_prop _ _ CS) as [CS1 CS2];\n      rewrite (IHs1 CS1);\n      rewrite (IHs2 CS2);\n      unfold \"&&\";\n      reflexivity.\n- apply CS.\n- unfold closed_t in *; fold closed_t in *.\n  apply (IHs CS).\n- unfold closed_t in CS; fold closed_t in CS.\n  inversion CS.\nQed.\n\nLemma closed_subst_closed_a : forall (a : atomic_formula) (n : nat) (t : term), closed_a a = true -> closed_a (substitution_a a n t) = true.\nProof.\nintros a n t CA.\ndestruct a.\nunfold closed_a in *.\nunfold substitution_a.\ndestruct (and_bool_prop _ _ CA) as [CA1 CA2].\nrewrite (closed_subst_closed_t _ _ _ CA1).\nrewrite (closed_subst_closed_t _ _ _ CA2).\nunfold \"&&\".\nreflexivity.\nQed.\n\nLemma closed_subst_closed : forall (A : formula) (n : nat) (t : term), closed A = true -> closed (substitution A n t) = true.\nProof.\nintros A n t CA.\nrewrite (closed_subst_eq _ _ _ CA).\napply CA.\nQed.\n\nLemma closed_univ_sub : forall (B : formula) (n : nat),\n  closed (univ n B) = true ->\n  (forall (t : term), closed_t t = true -> closed (substitution B n t) = true).\nProof.\nintros.\ndestruct (closed_univ B n H).\n- rewrite (closed_subst_eq _ _ _ H1). apply H1.\n- apply free_list_closed. rewrite (subst_remove B n t H0).\n  rewrite H1. simpl. case (nat_eq_dec n n) as [_ | FAL]. auto.\n  contradict FAL.\n  reflexivity.\nQed.\n\nLemma closed_sub_univ : forall (B : formula) (n : nat) (t : term),\n    closed_t t = true ->\n        closed (substitution B n t) = true ->\n            closed (univ n B) = true.\nProof.\nintros A n t Ct CS.\ncase (closed A) eqn:CA.\n- unfold closed.\n  fold closed.\n  rewrite CA.\n  reflexivity.\n- apply closed_free_list in CS.\n  apply free_list_closed.\n  rewrite (subst_remove _ _ _ Ct) in CS.\n  apply CS.\nQed.\n\nLemma closed_univ_sub_repr : forall (B : formula) (n : nat),\n  closed (univ n B) = true ->\n  (forall (m : nat), closed (substitution B n (represent m)) = true).\nProof.\nintros.\napply closed_univ_sub.\n- apply H.\n- apply eval_closed, eval_represent_non_zero.\nQed.\n\nLemma free_list_lor : forall (B C : formula) (n : nat),\n  free_list (lor B C) = [n] ->\n    ((free_list B = [n]) + (closed B = true)) *\n    ((free_list C = [n]) + (closed C = true)).\nProof.\nintros. simpl in H.\napply remove_dups_repeated_element' in H.\ndestruct (repeated_element_n_concat _ _ _ H) as [HB HC]. split.\n- destruct (remove_dups_repeated_element _ _ HB) as [HB' | HB'].\n  + left. rewrite free_list_remove_dups_idem. apply HB'.\n  + right. apply free_list_closed, HB'.\n- destruct (remove_dups_repeated_element _ _ HC) as [HC' | HC'].\n  + left. rewrite free_list_remove_dups_idem. apply HC'.\n  + right. apply free_list_closed, HC'.\nQed.\n\nLemma substitution_order_t : forall (T : term) (m n : nat) (s t : term),\n  closed_t s = true ->\n  closed_t t = true ->\n  nat_eqb m n = false ->\n  substitution_t (substitution_t T n s) m t =\n  substitution_t (substitution_t T m t) n s.\nProof.\nintros T m n s t Hs Ht Hmn. induction T; auto; simpl.\n- rewrite IHT. auto.\n- rewrite IHT1, IHT2. auto.\n- rewrite IHT1, IHT2. auto.\n- destruct (nat_eqb n0 n) eqn:Hn.\n  + rewrite <- (nat_eqb_eq _ _ Hn) in Hmn. rewrite nat_eqb_symm.\n    rewrite Hmn.\n    simpl. rewrite Hn. apply closed_subst_eq_t, Hs.\n  + destruct (nat_eqb n0 m) eqn:Hm; simpl; rewrite Hm.\n    * symmetry. apply closed_subst_eq_t, Ht.\n    * rewrite Hn. auto.\nQed.\n\nLemma substitution_order_a :\n  forall (a : atomic_formula) (m n : nat) (s t : term),\n  closed_t s = true ->\n  closed_t t = true ->\n  nat_eqb m n = false ->\n  substitution_a (substitution_a a n s) m t =\n  substitution_a (substitution_a a m t) n s.\nProof.\nintros a m n s t Hs Ht Hmn. destruct a as [t1 t2]. simpl.\nrewrite (substitution_order_t _ _ _ _ _ Hs Ht Hmn).\nrewrite (substitution_order_t _ _ _ _ _ Hs Ht Hmn). auto.\nQed.\n\nLemma substitution_order : forall (B : formula) (m n : nat) (s t : term),\n  closed_t s = true ->\n  closed_t t = true ->\n  nat_eqb m n = false ->\n  substitution (substitution B n s) m t =\n  substitution (substitution B m t) n s.\nProof.\nintros B m n s t Hs Ht Hmn. induction B; simpl.\n- rewrite (substitution_order_a _ _ _ _ _ Hs Ht Hmn). auto.\n- rewrite IHB. auto.\n- rewrite IHB1, IHB2. auto.\n- destruct (nat_eqb n0 n) eqn:Hn.\n  + apply nat_eqb_eq in Hn. rewrite Hn.\n    rewrite nat_eqb_symm. rewrite Hmn. simpl.\n    rewrite nat_eqb_symm. rewrite Hmn. rewrite nat_eqb_refl. auto.\n  + destruct (nat_eqb n0 m) eqn:Hm; simpl; rewrite Hm, Hn; auto.\n    rewrite IHB. auto.\nQed.\n\nLemma univ_free_var : forall (B : formula) (m n : nat),\n  free_list (univ m B) = [n] -> nat_eqb m n = false.\nProof.\nintros. simpl in H.\ndestruct (nat_eqb m n) eqn:Hm; auto.\napply nat_eqb_eq in Hm. rewrite Hm in H.\npose proof (remove_remove_eq nat_eq_dec (free_list B) n).\nrewrite H in H0. simpl in H0. case (nat_eq_dec n n) as [_ | FAL]. inversion H0.\ncontradict FAL.\nreflexivity.\nQed.\n\nLemma free_list_univ_sub :\n  forall (B : formula) (m : nat) (t : term) (l : list nat),\n  closed_t t = true ->\n  free_list (univ m B) = l ->\n  free_list (substitution B m t) = l.\nProof. intros. rewrite (subst_remove _ _ _ H). apply H0. Qed.\n\nLemma num_conn_sub : forall (B : formula) (m : nat) (t : term),\n  num_conn (substitution B m t) = num_conn B.\nProof.\nintros.\ninduction B; auto; simpl.\n- rewrite IHB. auto.\n- rewrite IHB1, IHB2. auto.\n- destruct (nat_eqb n m).\n  + auto.\n  + simpl. rewrite IHB. auto.\nQed.\n\nLemma num_conn_lor : forall (B C : formula) (n : nat),\n  num_conn (lor B C) = S n -> num_conn B <= n /\\ num_conn C <= n.\nProof. intros. simpl in H. lia. Qed.\n\nLemma free_list_sub_sef_t_eq : forall (n : nat) (t : term), free_list_t t = [n] -> free_list_t (substitution_t t n (succ (var n))) = [n].\nProof.\nintros n t. induction t; intros.\n- inversion H.\n- simpl in *. apply IHt. auto.\n- simpl in *. case (free_list_t t1) eqn:X.\n  + rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ X)). rewrite X. simpl. case (free_list_t t2) eqn:X1. inversion H. rewrite app_nil_l in H. destruct X1. rewrite <- free_list_remove_dups_idem_t in H. rewrite <- free_list_remove_dups_idem_t. rewrite IHt2; auto.\n  + case (free_list_t t2) eqn:X1.\n    * rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ X1)). rewrite X1. destruct X. rewrite app_nil_r in *. rewrite <- free_list_remove_dups_idem_t in H. rewrite <- free_list_remove_dups_idem_t. rewrite IHt1; auto.\n    * destruct X,X1. destruct (remove_dup_single_left _ _ _ H); destruct (remove_dup_single_right _ _ _ H). \n      --  rewrite <- free_list_remove_dups_idem_t in H0,H1. rewrite IHt1,IHt2; auto. simpl. case (nat_eq_dec n n) as [_ | FAL]. auto.\n          contradict FAL.\n          reflexivity.\n      --  rewrite <- free_list_remove_dups_idem_t in H0,H1. rewrite IHt1; auto. rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ H1)). rewrite H1. auto.\n      --  rewrite <- free_list_remove_dups_idem_t in H0,H1. rewrite IHt2; auto. rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ H0)). rewrite H0. auto.\n      --  rewrite <- free_list_remove_dups_idem_t in H0,H1. rewrite H0,H1 in H. inversion H.\n- simpl in *. case (free_list_t t1) eqn:X.\n  + rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ X)). rewrite X. simpl. case (free_list_t t2) eqn:X1. inversion H. rewrite app_nil_l in H. destruct X1. rewrite <- free_list_remove_dups_idem_t in H. rewrite <- free_list_remove_dups_idem_t. rewrite IHt2; auto.\n  + case (free_list_t t2) eqn:X1.\n    * rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ X1)). rewrite X1. destruct X. rewrite app_nil_r in *. rewrite <- free_list_remove_dups_idem_t in H. rewrite <- free_list_remove_dups_idem_t. rewrite IHt1; auto.\n    * destruct X,X1. destruct (remove_dup_single_left _ _ _ H); destruct (remove_dup_single_right _ _ _ H). \n      --  rewrite <- free_list_remove_dups_idem_t in H0,H1. rewrite IHt1,IHt2; auto. simpl. case (nat_eq_dec n n) as [_ | FAL]. auto.\n          contradict FAL.\n          reflexivity.\n      --  rewrite <- free_list_remove_dups_idem_t in H0,H1. rewrite IHt1; auto. rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ H1)). rewrite H1. auto.\n      --  rewrite <- free_list_remove_dups_idem_t in H0,H1. rewrite IHt2; auto. rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ H0)). rewrite H0. auto.\n      --  rewrite <- free_list_remove_dups_idem_t in H0,H1. rewrite H0,H1 in H. inversion H.\n- simpl in *. inversion H. destruct H1. rewrite nat_eqb_refl. auto.\nQed.\n\nLemma free_list_sub_sef_t : forall (n : nat) (t : term), member n (free_list_t t) = true -> free_list_t (substitution_t t n (succ (var n))) = free_list_t t.\nProof.\nintros n t. induction t; intros.\n- inversion H.\n- simpl in *. apply IHt. auto.\n- simpl in *. case (free_list_t t1) eqn:X.\n  + rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ X)). rewrite X. simpl. case (free_list_t t2) eqn:X1. inversion H. rewrite app_nil_l in H. destruct X1. rewrite <- free_list_remove_dups_idem_t in H. rewrite <- free_list_remove_dups_idem_t. rewrite IHt2; auto. rewrite <- free_list_remove_dups_idem_t. auto.\n  + case (free_list_t t2) eqn:X1.\n    * rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ X1)). rewrite X1. destruct X. rewrite app_nil_r in *. rewrite <- free_list_remove_dups_idem_t in H. rewrite <- free_list_remove_dups_idem_t. rewrite IHt1; auto. rewrite app_nil_r. rewrite <- free_list_remove_dups_idem_t. auto.\n    * destruct X,X1. case (member n (free_list_t t1)) eqn:X; destruct (member n (free_list_t t2)) eqn:X1. \n      --  rewrite IHt1,IHt2; auto.\n      --  rewrite IHt1; auto. rewrite closed_subst_eq_aux_t; auto.\n      --  rewrite IHt2; auto. rewrite closed_subst_eq_aux_t; auto.\n      --  apply member_remove_dups_true in H. destruct (member_concat' _ _ _ H). rewrite H0 in X. inversion X. rewrite H0 in X1. inversion X1.\n- simpl in *. case (free_list_t t1) eqn:X.\n  + rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ X)). rewrite X. simpl. case (free_list_t t2) eqn:X1. inversion H. rewrite app_nil_l in H. destruct X1. rewrite <- free_list_remove_dups_idem_t in H. rewrite <- free_list_remove_dups_idem_t. rewrite IHt2; auto. rewrite <- free_list_remove_dups_idem_t. auto.\n  + case (free_list_t t2) eqn:X1.\n    * rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ X1)). rewrite X1. destruct X. rewrite app_nil_r in *. rewrite <- free_list_remove_dups_idem_t in H. rewrite <- free_list_remove_dups_idem_t. rewrite IHt1; auto. rewrite app_nil_r. rewrite <- free_list_remove_dups_idem_t. auto.\n    * destruct X,X1. case (member n (free_list_t t1)) eqn:X; destruct (member n (free_list_t t2)) eqn:X1. \n      --  rewrite IHt1,IHt2; auto.\n      --  rewrite IHt1; auto. rewrite closed_subst_eq_aux_t; auto.\n      --  rewrite IHt2; auto. rewrite closed_subst_eq_aux_t; auto.\n      --  apply member_remove_dups_true in H. destruct (member_concat' _ _ _ H). rewrite H0 in X. inversion X. rewrite H0 in X1. inversion X1.\n- simpl in *. case (nat_eqb n0 n) eqn:X. apply nat_eqb_eq in X. destruct X. auto. inversion H.\nQed.\n\nLemma free_list_sub_self : forall (A : formula) (n : nat) (t : term), member n (free_list A) = true -> free_list (substitution A n (succ (var n))) = free_list A.\nProof.\nintros. induction A.\n- destruct a. simpl in *. case (free_list_t t0) eqn:X.\n  + rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ X)). rewrite X. case (free_list_t t1) eqn:X1. inversion H. rewrite app_nil_l in H. destruct X1. rewrite <- free_list_remove_dups_idem_t in H. simpl. repeat rewrite <- free_list_remove_dups_idem_t. apply free_list_sub_sef_t. auto.\n  + case (free_list_t t1) eqn:X1.\n    * rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ X1)). rewrite X1. destruct X. rewrite app_nil_r in *. rewrite <- free_list_remove_dups_idem_t in H. rewrite app_nil_r. repeat rewrite <- free_list_remove_dups_idem_t. apply free_list_sub_sef_t. auto.\n    * destruct X,X1. case (member n (free_list_t t0)) eqn:X; destruct (member n (free_list_t t1)) eqn:X1. \n      --  rewrite free_list_sub_sef_t,free_list_sub_sef_t; auto.\n      --  rewrite free_list_sub_sef_t; auto. rewrite closed_subst_eq_aux_t; auto.\n      --  rewrite (free_list_sub_sef_t _ _ X1); auto. rewrite closed_subst_eq_aux_t; auto.\n      --  apply member_remove_dups_true in H. destruct (member_concat' _ _ _ H). rewrite H0 in X. inversion X. rewrite H0 in X1. inversion X1.\n- simpl. apply IHA. auto.\n- simpl in *. case (free_list A1) eqn:X.\n+ rewrite (closed_subst_eq _ _ _ (free_list_closed _ X)). rewrite X. case (free_list A2) eqn:X1. inversion H. rewrite app_nil_l in H. destruct X1. rewrite <- free_list_remove_dups_idem in H. simpl. repeat rewrite <- free_list_remove_dups_idem. apply IHA2. auto.\n+ case (free_list A2) eqn:X1.\n  * rewrite (closed_subst_eq _ _ _ (free_list_closed _ X1)). rewrite X1. destruct X. rewrite app_nil_r in *. rewrite <- free_list_remove_dups_idem in H. rewrite app_nil_r. repeat rewrite <- free_list_remove_dups_idem. apply IHA1. auto.\n  * destruct X,X1. case (member n (free_list A1)) eqn:X; destruct (member n (free_list A2)) eqn:X1. \n      --  rewrite IHA1,IHA2; auto.\n      --  rewrite IHA1; auto. rewrite closed_subst_eq_aux; auto.\n      --  rewrite IHA2; auto. rewrite closed_subst_eq_aux; auto.\n      --  apply member_remove_dups_true in H. destruct (member_concat' _ _ _ H). rewrite H0 in X. inversion X. rewrite H0 in X1. inversion X1.\n- simpl in *. case (nat_eqb n0 n) eqn:X. apply nat_eqb_eq in X. destruct X. rewrite remove_not_member in H. inversion H. simpl. rewrite (IHA (member_remove_true _ _ _ H)). auto.\nQed.\n\nLemma free_list_sub_self_eq : forall (A : formula) (n : nat) (t : term), free_list A = [n] -> free_list (substitution A n (succ (var n))) = [n].\nProof.\nintros. induction A.\n- destruct a. simpl in *. case (free_list_t t0) eqn:X.\n  + rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ X)). rewrite X. case (free_list_t t1) eqn:X1. inversion H. rewrite app_nil_l in H. destruct X1. rewrite <- free_list_remove_dups_idem_t in H. simpl. rewrite <- free_list_remove_dups_idem_t. apply free_list_sub_sef_t_eq. auto.\n  + case (free_list_t t1) eqn:X1.\n    * rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ X1)). rewrite X1. destruct X. rewrite app_nil_r in *. rewrite <- free_list_remove_dups_idem_t in H. rewrite <- free_list_remove_dups_idem_t. apply free_list_sub_sef_t_eq. auto.\n    * destruct X,X1. destruct (remove_dup_single_left _ _ _ H); destruct (remove_dup_single_right _ _ _ H). \n      --  rewrite <- free_list_remove_dups_idem_t in H0,H1. repeat rewrite free_list_sub_sef_t_eq; auto. simpl. case (nat_eq_dec n n) as [_ | FAL]. auto.\n          contradict FAL.\n          reflexivity.\n      --  rewrite <- free_list_remove_dups_idem_t in H0,H1. rewrite free_list_sub_sef_t_eq; auto. rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ H1)). rewrite H1. auto.\n      --  rewrite <- free_list_remove_dups_idem_t in H0,H1. rewrite (free_list_sub_sef_t_eq _ t1); auto. rewrite (closed_subst_eq_t _ _ _ (free_list_closed_t _ H0)). rewrite H0. auto.\n      --  rewrite <- free_list_remove_dups_idem_t in H0,H1. rewrite H0,H1 in H. inversion H.\n- simpl. apply IHA. auto.\n- simpl in *. case (free_list A1) eqn:X.\n+ rewrite (closed_subst_eq _ _ _ (free_list_closed _ X)). rewrite X. case (free_list A2) eqn:X1. inversion H. rewrite app_nil_l in H. destruct X1. rewrite <- free_list_remove_dups_idem in H. simpl. rewrite <- free_list_remove_dups_idem. apply IHA2. auto.\n+ case (free_list A2) eqn:X1.\n  * rewrite (closed_subst_eq _ _ _ (free_list_closed _ X1)). rewrite X1. destruct X. rewrite app_nil_r in *. rewrite <- free_list_remove_dups_idem in H. rewrite <- free_list_remove_dups_idem. apply IHA1. auto.\n  * destruct X,X1. destruct (remove_dup_single_left _ _ _ H); destruct (remove_dup_single_right _ _ _ H). \n    --  rewrite <- free_list_remove_dups_idem in H0,H1. rewrite IHA1,IHA2; auto. simpl. case (nat_eq_dec n n) as [_ | FAL]. auto.\n        contradict FAL.\n        reflexivity.\n    --  rewrite <- free_list_remove_dups_idem in H0,H1. rewrite IHA1; auto. rewrite (closed_subst_eq _ _ _ (free_list_closed _ H1)). rewrite H1. auto.\n    --  rewrite <- free_list_remove_dups_idem in H0,H1. rewrite IHA2; auto. rewrite (closed_subst_eq _ _ _ (free_list_closed _ H0)). rewrite H0. auto.\n    --  rewrite <- free_list_remove_dups_idem in H0,H1. rewrite H0,H1 in H. inversion H.\n- simpl in *. pose proof (univ_free_var _ _ _ H). rewrite H0. simpl. rewrite free_list_sub_self; auto. apply (member_remove_true _ _ n0). rewrite H. simpl. rewrite nat_eqb_refl. auto.\nQed.\n\nLemma sub_succ_self_t : forall (t s : term) (n : nat), substitution_t (substitution_t t n (succ (var n))) n s = substitution_t t n (succ s).\nProof.\nintros t. induction t; intros.\n- auto.\n- simpl. rewrite IHt. auto.\n- simpl. rewrite IHt1. rewrite IHt2. auto.\n- simpl. rewrite IHt1. rewrite IHt2. auto.\n- simpl. case (nat_eqb n n0) eqn:X. apply nat_eqb_eq in X. destruct X. simpl. rewrite nat_eqb_refl. auto. simpl. rewrite X. auto.\nQed.\n\nLemma sub_succ_self : forall (A : formula) (n : nat) (t : term), substitution (substitution A n (succ (var n))) n t = substitution A n (succ t).\nProof.\nintros A. induction A; intros.\n- destruct a. simpl. rewrite sub_succ_self_t. rewrite sub_succ_self_t. auto.\n- simpl. rewrite IHA. auto.\n- simpl. rewrite IHA1. rewrite IHA2. auto.\n- simpl. case (nat_eqb n n0) eqn:X. apply nat_eqb_eq in X. destruct X. simpl. rewrite nat_eqb_refl. auto. simpl. rewrite X. rewrite IHA. auto.\nQed.\n\n\n\nLemma closure_closed' : forall (L : list nat) (A : formula) (c : c_term), free_list A = L -> closed (closure_type A c L) = true.\nProof.\nintros L. induction L; intros A [c Hc] FREE.\n- simpl. apply free_list_closed. auto.\n- simpl. rewrite IHL; auto. rewrite subst_remove; auto. rewrite FREE. apply remove_dups_idem_remove_triv. destruct FREE. symmetry. apply free_list_remove_dups_idem.\nQed.\n\nLemma closure_closed : forall (A : formula) (c : c_term), closed (closure A c) = true.\nProof.\nintros. apply closure_closed'; auto.\nQed.\n\nLemma closure_type_lor : forall (L : list nat) (A B : formula) (c : c_term), closure_type (lor A B) c L = lor (closure_type A c L) (closure_type B c L).\nProof.\ninduction L; intros; simpl; auto.\nQed.\n\nLemma closure_closed_id : forall (A : formula) (c : c_term), closed A = true -> closure A c = A.\nintros. unfold closure. rewrite closed_free_list; auto.\nQed.\n\nLemma closure_closed_list_id : forall (L : list nat) (A : formula) (c : c_term), closed A = true -> closure_type A c L = A.\nintros L. induction L; auto. intros. simpl. rewrite closed_subst_eq; auto. \nQed.\n\nLemma closure_type_symm : forall (A : formula) (c : c_term) (n m : nat) (L : list nat), closure_type A c (n :: m :: L) = closure_type A c (m :: n :: L).\nProof.\nintros A [c Hc] n m L. case (nat_eqb m n) eqn:X.\n- apply nat_eqb_eq in X. destruct X. auto.\n- simpl. rewrite substitution_order; auto.\nQed.\n\nLemma closure_type_concat_symm : forall (L1 L2 : list nat) (A : formula) (c : c_term), closure_type A c (L1 ++ L2) = closure_type A c (L2 ++ L1).\nProof.\ninduction L1.\n- intros. simpl. rewrite app_nil_r. auto.\n- intros L2. simpl. induction L2; intros A [c Hc].\n  + simpl. rewrite app_nil_r. auto.\n  + rewrite IHL1; auto. simpl. rewrite <- IHL2; auto. rewrite IHL1; auto. simpl.\n    case (nat_eqb a0 a) eqn:X.\n   * apply nat_eqb_eq in X. destruct X. auto.\n   * rewrite substitution_order; auto.\nQed.\n\nLemma closure_type_concat : forall (L1 L2 : list nat) (A : formula) (c : c_term), closure_type A c (L1 ++ L2) = closure_type (closure_type A c L1) c L2.\nProof.\nintros L1. induction L1. auto. intros. simpl. rewrite IHL1; auto.\nQed.\n\n\nLemma closure_type_not_used : forall (L : list nat) (A : formula) (c : c_term) (n : nat), member n (free_list A) = false -> closure_type A c (n :: L) = closure_type A c L.\nProof.\nintros L. induction L.\n- intros. simpl. apply closed_subst_eq_aux. auto.\n- intros A [ Hc] n LIST. simpl. case (nat_eqb a n) eqn:X.\n  + apply nat_eqb_eq in X. destruct X. repeat rewrite (closed_subst_eq_aux _ _ _ LIST). auto.\n  + rewrite substitution_order; auto. rewrite closed_subst_eq_aux. auto. rewrite subst_remove; auto. apply remove_member_false. auto.\nQed.\n\nLemma closure_type_not_used_any : forall (L1 L2 : list nat) (A : formula) (c : c_term) (n : nat), member n (free_list A) = false -> closure_type A c (L1 ++ (n :: L2)) = closure_type A c (L1 ++ L2).\nProof.\nintros. rewrite (closure_type_concat_symm _ L2); auto. rewrite closure_type_concat_symm; auto. apply closure_type_not_used; auto.\nQed.\n\nLemma closure_type_not_used_remove : forall (L : list nat) (A : formula) (c : c_term) (n : nat), member n (free_list A) = false -> closure_type A c (remove nat_eq_dec n L) = closure_type A c L.\nProof.\nintros L. induction L. auto. intros A [c Hc] n LIST. simpl. case (nat_eq_dec n a) as [EQ | NE].\n- destruct EQ. rewrite IHL; auto. rewrite closed_subst_eq_aux; auto.\n- simpl. rewrite IHL; auto. rewrite subst_remove; auto. apply remove_member_false. auto.\nQed.\n\n\nLemma closure_type_sets : forall (L1 L2 : list nat) (A : formula) (c : c_term), (forall (m : nat), In m L1 <-> In m L2) -> closure_type A c L1 = closure_type A c L2.\nProof.\ninduction L1 as [L1 IND] using (induction_ltof1 _ (@length _)); unfold ltof in IND.\nintros L2 A c SETEQ.\ndestruct L1.\n- destruct L2.\n  + reflexivity.\n  + destruct (proj2 (SETEQ n)).\n    left.\n    reflexivity.\n- pose proof (in_split _ _ ((proj1 (SETEQ _)) (or_introl (eq_refl _)))) as [L1' [L2' EQ]].\n  rewrite EQ.\n  rewrite closure_type_concat_symm.\n  rewrite <- app_comm_cons.\n  unfold closure_type; fold closure_type.\n  rewrite <- (closure_type_not_used_remove _ _ _ n).\n  rewrite <- (closure_type_not_used_remove (L2' ++ L1') _ _ n).\n  apply IND.\n  + pose proof (remove_length_le nat_eq_dec L1 n) as IE.\n    unfold length; fold (@length nat).\n    lia.\n  + intros m.\n    split;\n    intros IN;\n    apply in_remove in IN as [IN NE];\n    apply (in_in_remove _ _ NE).\n    * pose proof (proj1 (SETEQ m) (or_intror IN)) as IN'.\n      rewrite EQ, in_app_iff, or_comm, <- in_app_iff, <- app_comm_cons in IN'.\n      destruct IN' as [EQ' | IN'].\n      --  destruct EQ'.\n          contradict NE.\n          reflexivity.\n      --  apply IN'.          \n    * pose proof (in_cons n _ _ IN) as IN'.\n      rewrite app_comm_cons, in_app_iff, or_comm, <- in_app_iff, <- EQ in IN'.\n      destruct (proj2 (SETEQ m) IN') as [EQ' | IN''].\n      --  destruct EQ'.\n          contradict NE.\n          reflexivity.\n      --  apply IN''.\n  + destruct c as [c Hc].\n    rewrite subst_remove; auto.\n    apply remove_not_member.\n  + destruct c as [c Hc].\n    rewrite subst_remove; auto.\n    apply remove_not_member.\nQed.\n\nLemma closure_type_dupes : forall (L : list nat) (A : formula) (c : c_term), closure_type A c L = closure_type A c (nodup nat_eq_dec L).\nProof.\nintros.\nsymmetry.\napply closure_type_sets, nodup_In.\nQed.\n\nLemma closure_lor : forall A B c, closure (lor A B) c = lor (closure A c) (closure B c).\nProof.\nintros A. unfold closure. simpl. induction (free_list A) eqn:X.\n- intros. simpl. rewrite <- free_list_remove_dups_idem. rewrite closure_type_lor; auto. rewrite closure_closed_list_id; auto. apply free_list_closed. auto.\n- intros. rewrite <- closure_type_dupes; auto. rewrite closure_type_lor; auto. rewrite closure_type_concat; auto. rewrite closure_type_concat_symm; auto. rewrite closure_type_concat; auto.\n  destruct X. rewrite closure_closed_list_id. rewrite (closure_closed_list_id (free_list A) (closure_type B c (free_list B))). auto. apply closure_closed; auto. apply closure_closed; auto.\nQed.\n\nLemma closure_neg_list : forall L A c, closure_type (neg A) c L = neg (closure_type A c L).\nProof.\nintros L. induction L. auto. intros. simpl. rewrite IHL; auto.\nQed.\n\nLemma closure_univ_list : forall L A c n, closure_type (univ n A) c L = univ n (closure_type A c (remove nat_eq_dec n L)).\nProof.\nintros L. induction L. auto. intros. simpl. case (nat_eqb n a) eqn:X.\n- case nat_eq_dec as [EQ | NE].\n  + auto.\n  + apply nat_eqb_eq in X.\n    destruct X.\n    contradict NE.\n    reflexivity.\n- case nat_eq_dec as [EQ | NE].\n  + destruct EQ.\n    rewrite nat_eqb_refl in X.\n    inversion X.\n  + rewrite IHL; auto.\nQed.\n\nLemma closure_neg : forall A c, closure (neg A) c = neg (closure A c).\nProof.\nintros. apply closure_neg_list.\nQed.\n\nLemma closure_univ : forall A c n, closure (univ n A) c = univ n (closure_type A c (free_list (univ n A))).\nProof.\nintros. unfold closure. simpl. rewrite <- remove_remove_eq at 2. apply closure_univ_list.\nQed.\n\nLemma num_conn_closure_eq_list : forall (L : list nat) (A : formula) (c : c_term), num_conn A = num_conn (closure_type A c L).\nProof.\nintros L. induction L. auto. intros. simpl. rewrite <- IHL. rewrite num_conn_sub. auto.\nQed.\n\nLemma num_conn_closure_eq : forall (A : formula) (c : c_term), num_conn A = num_conn (closure A c).\nProof.\nintros. apply num_conn_closure_eq_list.\nQed.\n\nLemma closure_subst_list :  forall (L : list nat) (A : formula) (c1 c2 : c_term) (n : nat), (substitution (closure_type A c1 (remove nat_eq_dec n L)) n (projT1 c2)) = (closure_type (substitution A n (projT1 c2)) c1 L).\nProof.\nintros L. induction L. auto. intros A c1 c2 n. simpl. case (nat_eq_dec n a) as [EQ | NE].\n- destruct EQ. rewrite IHL; auto. rewrite (closed_subst_eq_aux (substitution A n (projT1 c2))). auto. rewrite subst_remove; auto. apply remove_not_member. destruct c2 as [c2 Hc2]. auto.\n- simpl. rewrite IHL; auto. rewrite substitution_order; destruct c1 as [c1 Hc1]; destruct c2 as [c2 Hc2]; auto.\n  case (nat_eqb n a) eqn:EQ.\n  + apply nat_eqb_eq in EQ.\n    destruct EQ.\n    contradict NE.\n    reflexivity.\n  + reflexivity.\nQed.\n\nLemma closure_subst :  forall (A : formula) (c1 c2 : c_term) (n : nat), (substitution (closure_type A c1 (free_list (univ n A))) n (projT1 c2)) = (closure (substitution A n (projT1 c2)) c1).\nProof.\nintros. unfold closure. rewrite <- closure_subst_list; auto. rewrite remove_not_mem_idem. rewrite (free_list_univ_sub _ _ _ (free_list (univ n A))); auto. destruct c2 as [c2 Hc2]. auto. rewrite subst_remove; auto. apply remove_not_member. destruct c2 as [c2 Hc2]. auto.\nQed.\n\n\n\nLemma closure_closed_t' : forall (L : list nat) (t : term) (c : c_term), free_list_t t = L -> closed_t (closure_type_t t c L) = true.\nProof.\nintros L. induction L; intros t [c Hc] LIST.\n- simpl. apply free_list_closed_t. auto.\n- simpl. rewrite IHL; auto. rewrite subst_remove_t; auto. rewrite LIST. rewrite remove_dups_idem_remove_triv. auto. destruct LIST. rewrite <- free_list_remove_dups_idem_t. auto.\nQed.\n\nLemma closure_closed_t : forall (t : term) (c : c_term), closed_t (closure_t t c) = true.\nProof.\nintros. unfold closure_t. rewrite closure_closed_t'; auto.\nQed.\n\nLemma closure_type_equiv_list : forall L t1 t2 s, closure_type (atom (equ t1 t2)) s L = atom (equ (closure_type_t t1 s L) (closure_type_t t2 s L)).\nProof.\nintros L. induction L; simpl; auto.\nQed.\n\nLemma closure_type_concat_t : forall (L1 L2 : list nat) (t : term) (c : c_term), closure_type_t t c (L1 ++ L2) = closure_type_t (closure_type_t t c L1) c L2.\nProof.\nintros L1. induction L1. auto. intros. simpl. rewrite IHL1; auto.\nQed.\n\nLemma closure_type_concat_symm_t : forall (L1 L2 : list nat) (t : term) (c : c_term), closure_type_t t c (L1 ++ L2) = closure_type_t t c (L2 ++ L1).\nProof.\nintros L1. induction L1.\n- intros. simpl. rewrite app_nil_r. auto.\n- intros L2. simpl. induction L2; intros.\n  + simpl. rewrite app_nil_r. auto.\n  + rewrite IHL1; auto. simpl. rewrite <- IHL2; auto. rewrite IHL1; auto. case (nat_eqb a0 a) eqn:X.\n   * apply nat_eqb_eq in X. destruct X. auto.\n   * rewrite substitution_order_t; destruct c; auto.\nQed.\n\nLemma closure_closed_id_t : forall (t : term) (c : c_term), closed_t t = true -> closure_t t c = t.\nintros. unfold closure_t. rewrite closed_free_list_t; auto.\nQed.\n\nLemma closure_closed_list_id_t : forall (L : list nat) (t : term) (c : c_term), closed_t t = true -> closure_type_t t c L = t.\nintros L. induction L; auto. intros. simpl. rewrite closed_subst_eq_t; auto. \nQed.\n\nLemma closure_type_not_used_remove_t : forall (L : list nat) (t : term) (c : c_term) (n : nat), member n (free_list_t t) = false -> closure_type_t t c (remove nat_eq_dec n L) = closure_type_t t c L.\nProof.\nintros L. induction L. auto. intros. simpl. case (nat_eq_dec n a) as [EQ | NE].\n- destruct EQ. rewrite IHL; auto. rewrite closed_subst_eq_aux_t; auto.\n- simpl. rewrite IHL; auto. rewrite subst_remove_t; auto. apply remove_member_false. auto. destruct c; auto.\nQed.\n\nLemma closure_type_sets_t : forall (L1 L2 : list nat) (t : term) (c : c_term), (forall (m : nat), In m L1 <-> In m L2) -> closure_type_t t c L1 = closure_type_t t c L2.\nProof.\ninduction L1 as [L1 IND] using (induction_ltof1 _ (@length _)); unfold ltof in IND.\nintros L2 t c SETEQ.\ndestruct L1.\n- destruct L2.\n  + reflexivity.\n  + destruct (proj2 (SETEQ n)).\n    left.\n    reflexivity.\n- pose proof (in_split _ _ ((proj1 (SETEQ _)) (or_introl (eq_refl _)))) as [L1' [L2' EQ]].\n  rewrite EQ.\n  rewrite closure_type_concat_symm_t.\n  rewrite <- app_comm_cons.\n  unfold closure_type_t; fold closure_type_t.\n  rewrite <- (closure_type_not_used_remove_t _ _ _ n).\n  rewrite <- (closure_type_not_used_remove_t (L2' ++ L1') _ _ n).\n  apply IND.\n  + pose proof (remove_length_le nat_eq_dec L1 n) as IE.\n    unfold length; fold (@length nat).\n    lia.\n  + intros m.\n    split;\n    intros IN;\n    apply in_remove in IN as [IN NE];\n    apply (in_in_remove _ _ NE).\n    * pose proof (proj1 (SETEQ m) (or_intror IN)) as IN'.\n      rewrite EQ, in_app_iff, or_comm, <- in_app_iff, <- app_comm_cons in IN'.\n      destruct IN' as [EQ' | IN'].\n      --  destruct EQ'.\n          contradict NE.\n          reflexivity.\n      --  apply IN'.          \n    * pose proof (in_cons n _ _ IN) as IN'.\n      rewrite app_comm_cons, in_app_iff, or_comm, <- in_app_iff, <- EQ in IN'.\n      destruct (proj2 (SETEQ m) IN') as [EQ' | IN''].\n      --  destruct EQ'.\n          contradict NE.\n          reflexivity.\n      --  apply IN''.\n  + destruct c as [c Hc].\n    rewrite subst_remove_t; auto.\n    apply remove_not_member.\n  + destruct c as [c Hc].\n    rewrite subst_remove_t; auto.\n    apply remove_not_member.\nQed.\n\nLemma closure_type_dupes_t : forall (L : list nat) (t : term) (c : c_term), closure_type_t t c L = closure_type_t t c (nodup nat_eq_dec L).\nProof.\nintros.\nsymmetry.\napply closure_type_sets_t, nodup_In.\nQed.\n\nLemma closure_type_equiv : forall t1 t2 c, closure (atom (equ t1 t2)) c = atom (equ (closure_t t1 c) (closure_t t2 c)).\nProof.\nintros. unfold closure. rewrite closure_type_equiv_list. simpl. rewrite <- closure_type_dupes_t; auto. rewrite <- closure_type_dupes_t; auto.\nrewrite closure_type_concat_t; auto. rewrite closure_type_concat_symm_t; auto. rewrite closure_type_concat_t; auto.\nrewrite (closure_closed_list_id_t (free_list_t t2)). rewrite (closure_closed_list_id_t (free_list_t t1) (closure_type_t t2 c _)); auto. apply closure_closed_t; auto. apply closure_closed_t; auto.\nQed.\n\nLemma closure_t_succ_list : forall L t s, closure_type_t (succ t) s L = succ (closure_type_t t s L).\nProof.\nintros L. induction L. auto. intros. simpl. rewrite IHL. auto.\nQed.\n\nLemma closure_t_succ : forall t s, closure_t (succ t) s = succ (closure_t t s).\nProof.\nintros. apply closure_t_succ_list.\nQed.\n\nLemma closure_t_plus_list : forall L t1 t2 s, closure_type_t (plus t1 t2) s L = plus (closure_type_t t1 s L) (closure_type_t t2 s L).\nProof.\nintros L. induction L. auto. intros. simpl. rewrite IHL. auto.\nQed.\n\nLemma closure_t_plus : forall t1 t2 c, closure_t (plus t1 t2) c = plus (closure_t t1 c) (closure_t t2 c).\nProof.\nintros. unfold closure_t. rewrite closure_t_plus_list. simpl. rewrite <- closure_type_dupes_t; auto. rewrite <- closure_type_dupes_t; auto.\nrewrite closure_type_concat_t; auto. rewrite closure_type_concat_symm_t; auto. rewrite closure_type_concat_t; auto.\nrewrite (closure_closed_list_id_t (free_list_t t2)). rewrite (closure_closed_list_id_t (free_list_t t1) (closure_type_t t2 c _)); auto. apply closure_closed_t; auto. apply closure_closed_t; auto.\nQed.\n\nLemma closure_t_times_list : forall L t1 t2 s, closure_type_t (times t1 t2) s L = times (closure_type_t t1 s L) (closure_type_t t2 s L).\nProof.\nintros L. induction L. auto. intros. simpl. rewrite IHL. auto.\nQed.\n\nLemma closure_t_times : forall t1 t2 s, closure_t (times t1 t2) s = times (closure_t t1 s) (closure_t t2 s).\nProof.\nintros. unfold closure_t. rewrite closure_t_times_list. simpl. rewrite <- closure_type_dupes_t; auto. rewrite <- closure_type_dupes_t; auto.\nrewrite closure_type_concat_t; auto. rewrite closure_type_concat_symm_t; auto. rewrite closure_type_concat_t; auto.\nrewrite (closure_closed_list_id_t (free_list_t t2)). rewrite (closure_closed_list_id_t (free_list_t t1) (closure_type_t t2 s _)); auto. apply closure_closed_t; auto. apply closure_closed_t; auto.\nQed.\n\nLemma weak_substitution_order_t : forall (T : term) (m n : nat) (s t : term),\n  member m (free_list_t s) = false ->\n  member n (free_list_t t) = false ->\n  nat_eqb m n = false ->\n  substitution_t (substitution_t T n s) m t =\n  substitution_t (substitution_t T m t) n s.\nProof.\nintros T m n s t Hs Ht Hmn. induction T; auto; simpl.\n- rewrite IHT. auto.\n- rewrite IHT1, IHT2. auto.\n- rewrite IHT1, IHT2. auto.\n- destruct (nat_eqb n0 n) eqn:Hn.\n  + rewrite <- (nat_eqb_eq _ _ Hn) in Hmn. rewrite nat_eqb_symm. rewrite Hmn.\n    simpl. rewrite Hn. rewrite closed_subst_eq_aux_t; auto.\n  + destruct (nat_eqb n0 m) eqn:Hm; simpl; rewrite Hm.\n    * rewrite closed_subst_eq_aux_t; auto.\n    * rewrite Hn. auto.\nQed.\n\nLemma weak_substitution_order_a :\n  forall (a : atomic_formula) (m n : nat) (s t : term),\n  member m (free_list_t s) = false ->\n  member n (free_list_t t) = false ->\n  nat_eqb m n = false ->\n  substitution_a (substitution_a a n s) m t =\n  substitution_a (substitution_a a m t) n s.\nProof.\nintros a m n s t Hs Ht Hmn. destruct a as [t1 t2]. simpl.\nrewrite (weak_substitution_order_t _ _ _ _ _ Hs Ht Hmn).\nrewrite (weak_substitution_order_t _ _ _ _ _ Hs Ht Hmn). auto.\nQed.\n\nLemma weak_substitution_order : forall (B : formula) (m n : nat) (s t : term),\n  member m (free_list_t s) = false ->\n  member n (free_list_t t) = false ->\n  nat_eqb m n = false ->\n  substitution (substitution B n s) m t =\n  substitution (substitution B m t) n s.\nProof.\nintros B m n s t Hs Ht Hmn. induction B; simpl.\n- rewrite (weak_substitution_order_a _ _ _ _ _ Hs Ht Hmn). auto.\n- rewrite IHB. auto.\n- rewrite IHB1, IHB2. auto.\n- destruct (nat_eqb n0 n) eqn:Hn.\n  + apply nat_eqb_eq in Hn. rewrite Hn.\n    rewrite nat_eqb_symm. rewrite Hmn. simpl.\n    rewrite nat_eqb_symm. rewrite Hmn. rewrite nat_eqb_refl. auto.\n  + destruct (nat_eqb n0 m) eqn:Hm; simpl; rewrite Hm, Hn; auto.\n    rewrite IHB. auto.\nQed.\n\nLemma closure_type_sub_remove_list : forall (L : list nat) (A : formula) (c : c_term) (n : nat), (closure_type (substitution A n (succ (var n))) c (remove nat_eq_dec n L)) = substitution (closure_type A c (remove nat_eq_dec n L)) n (succ (var n)).\nProof.\nintros L. induction L. auto. intros. simpl. case (nat_eq_dec n a) as [EQ | NE].\n- destruct EQ. rewrite IHL; auto.\n- simpl. rewrite <- IHL; auto. rewrite weak_substitution_order; simpl; auto.\n  + case (nat_eqb n a) eqn:EQ.\n    * apply nat_eqb_eq in EQ.\n      destruct EQ.\n      contradict NE.\n      reflexivity.\n    * reflexivity.\n  + rewrite closed_free_list_t; auto. destruct c. auto.\n  + case (nat_eqb a n) eqn:EQ.\n    * apply nat_eqb_eq in EQ.\n      destruct EQ.\n      contradict NE.\n      reflexivity.\n    * reflexivity.\nQed.\n\nLemma closure_type_sub_remove : forall (A : formula) (c : c_term) (n : nat), (closure_type (substitution A n (succ (var n))) c (free_list (univ n (lor (neg A) (substitution A n (succ (var n))))))) = substitution (closure_type A c (free_list (univ n A))) n (succ (var n)).\nProof.\nintros A [c Hc] n. case (member n (free_list A)) eqn:X.\n- simpl. rewrite free_list_sub_self; auto. rewrite remove_dups_concat_self. rewrite <- free_list_remove_dups_idem. rewrite closure_type_sub_remove_list; auto.\n- simpl. rewrite closed_subst_eq_aux; auto. rewrite remove_dups_concat_self. rewrite <- free_list_remove_dups_idem. rewrite <- closure_type_sub_remove_list; auto. rewrite closed_subst_eq_aux; auto.\nQed.\n\nLemma closure_type_list_remove : forall (L : list nat) (A : formula) (c : c_term) (n : nat), L = free_list A -> free_list (closure_type A c (remove nat_eq_dec n L)) = [n] \\/ free_list (closure_type A c (remove nat_eq_dec n L)) = [].\nProof.\nintros L. induction L. auto. intros. simpl. assert (L = free_list (substitution A a (projT1 c))) as Y. rewrite subst_remove; auto. rewrite <- H. rewrite remove_dups_idem_remove_triv; auto. rewrite H. rewrite <- free_list_remove_dups_idem. auto. destruct c. auto. case (nat_eq_dec n a) as [EQ | NE]. \n- destruct EQ. destruct (IHL (substitution A n (projT1 c)) c n Y).\n  + rewrite closure_type_not_used_remove in H0; auto.\n    * rewrite <- closure_subst_list in H0; auto. rewrite subst_remove in H0; auto. pose proof (remove_not_member (free_list (closure_type A c (remove nat_eq_dec n L))) n). rewrite H0 in H1. simpl in H1. rewrite nat_eqb_refl in H1. inversion H1. destruct c. auto.\n    * rewrite subst_remove; auto. apply remove_not_member. destruct c. auto.\n  + rewrite <- closure_subst_list in H0; auto. rewrite subst_remove in H0; auto. rewrite remove_remove_eq in H0. rewrite free_list_remove_dups_idem in H0. rewrite free_list_remove_dups_idem. destruct (remove_n_dups_empty _ _ H0); auto. destruct c; auto.\n- simpl. apply IHL; auto. \nQed.\n\nLemma free_list_univ_closure : forall (A : formula) (c : c_term) (n : nat), free_list (closure_type A c (free_list (univ n A))) = [n] \\/ free_list (closure_type A c (free_list (univ n A))) = [].\nProof.\nintros. simpl. apply closure_type_list_remove; auto.\nQed.\n\nLemma correct_correctness : forall (a : atomic_formula),\n  correct_a a = true -> correctness a = correct.\nProof.\nintros. unfold correct_a in H.\ncase_eq (correctness a); auto; intros; rewrite H0 in H; inversion H.\nQed.\n\nLemma incorrect_correctness : forall (a : atomic_formula),\n  incorrect_a a = true -> correctness a = incorrect.\nProof.\nintros. unfold incorrect_a in H.\ncase_eq (correctness a); auto; intros; rewrite H0 in H; inversion H.\nQed.\n\nLemma correct_eval : forall (s t : term),\n  correct_a (equ s t) = true -> eval s > 0 /\\ eval t > 0.\nProof.\nintros.\nassert (correctness (equ s t) = correct).\n{ apply correct_correctness. apply H. }\nunfold correct_a in H.\nrewrite H0 in H.\nunfold correctness in H0.\ncase_eq (eval s); case_eq (eval t); intros;\nrewrite H1 in H0; rewrite H2 in H0; inversion H0;\nsplit; lia.\nQed.\n\nLemma incorrect_eval : forall (s t : term),\n  incorrect_a (equ s t) = true -> eval s > 0 /\\ eval t > 0.\nProof.\nintros.\nassert (correctness (equ s t) = incorrect).\n{ apply incorrect_correctness. apply H. }\nunfold incorrect_a in H.\nrewrite H0 in H.\nunfold correctness in H0.\ncase_eq (eval s); case_eq (eval t); intros;\nrewrite H1 in H0; rewrite H2 in H0; inversion H0;\nsplit; lia.\nQed.\n\nLemma correct_closed : forall (a : atomic_formula),\n  correct_a a = true -> closed_a a = true.\nProof.\nintros. case_eq a. intros t1 t2 Ha. rewrite Ha in H. clear Ha. simpl.\ndestruct (correct_eval _ _ H).\napply eval_closed in H0. rewrite H0.\napply eval_closed in H1. rewrite H1. auto.\nQed.\n\nLemma incorrect_closed : forall (a : atomic_formula),\n  incorrect_a a = true -> closed_a a = true.\nProof.\nintros. case_eq a. intros t1 t2 Ha. rewrite Ha in H. clear Ha. simpl.\ndestruct (incorrect_eval _ _ H).\napply eval_closed in H0. rewrite H0.\napply eval_closed in H1. rewrite H1. auto.\nQed.\n\nLemma subst_closed_t : forall (n : nat) (T s t : term),\n  closed_t t = true ->\n  closed_t (substitution_t T n s) = true ->\n  closed_t (substitution_t T n t) = true.\nProof.\nintros. induction T; auto.\n- simpl. simpl in H0.\n  case_eq (closed_t (substitution_t T1 n s)); intros HT1;\n  case_eq (closed_t (substitution_t T2 n s)); intros HT2.\n  + rewrite (IHT1 HT1). rewrite (IHT2 HT2). auto.\n  + rewrite HT1 in H0. rewrite HT2 in H0. inversion H0.\n  + rewrite HT1 in H0. rewrite HT2 in H0. inversion H0.\n  + rewrite HT1 in H0. rewrite HT2 in H0. inversion H0.\n- simpl. simpl in H0.\n  case_eq (closed_t (substitution_t T1 n s)); intros HT1;\n  case_eq (closed_t (substitution_t T2 n s)); intros HT2.\n  + rewrite (IHT1 HT1). rewrite (IHT2 HT2). auto.\n  + rewrite HT1 in H0. rewrite HT2 in H0. inversion H0.\n  + rewrite HT1 in H0. rewrite HT2 in H0. inversion H0.\n  + rewrite HT1 in H0. rewrite HT2 in H0. inversion H0.\n- case_eq (nat_eqb n0 n); intros; simpl; rewrite H1.\n  + apply H.\n  + simpl in H0. rewrite H1 in H0. inversion H0.\nQed.\n\nLemma incorrect_subst_closed :\n  forall (a : atomic_formula) (n : nat) (s t : term),\n  closed_t t = true ->\n  incorrect_a (substitution_a a n s) = true ->\n  closed_a (substitution_a a n t) = true.\nProof.\nintros.\ncase_eq a. intros t1 t2 Ha. rewrite Ha in H0. clear Ha. simpl.\napply incorrect_closed in H0. simpl in H0.\ncase_eq (closed_t (substitution_t t1 n s)); intros Ht1;\ncase_eq (closed_t (substitution_t t2 n s)); intros Ht2; auto.\n- rewrite (subst_closed_t n t1 s t H Ht1).\n  rewrite (subst_closed_t n t2 s t H Ht2). auto.\n- rewrite Ht1 in H0. rewrite Ht2 in H0. inversion H0.\n- rewrite Ht1 in H0. rewrite Ht2 in H0. inversion H0.\n- rewrite Ht1 in H0. rewrite Ht2 in H0. inversion H0.\nQed.\n\n\nLemma correct_closed_t : forall (s t : term),\n  correct_a (equ s t) = true -> closed_t s = true /\\ closed_t t = true.\nProof.\nintros.\ndestruct (correct_eval _ _ H). split; apply eval_closed.\napply H0. apply H1.\nQed.\n\nDefinition czero := (closing zero (represent_closed 0)).\n\nDefinition cterm_equiv_correct : forall c : c_term, correct_a (equ (represent (value c)) (projT1 c)) = true.\nProof.\nintros. unfold correct_a. unfold correctness. pose proof eval_represent_non_zero (value c). case (eval (represent (value c))) eqn:X. inversion H.\npose proof (closed_eval (projT1 c) (projT2 c)). case (eval (projT1 c)) eqn:X1. inversion H0. unfold value in X. rewrite represent_eval in X.\ndestruct X. destruct X1. rewrite nat_eqb_refl. auto. destruct c. auto.\nQed.", "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/Logic/fol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308054739519, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6964691159909774}}
{"text": "Require Import definition basic.\n\nAxiom ax_power_set : forall x , exists y , forall z , z ⊆ x -> z ∈ y.\n\nDefinition power_set ( x : Zset ) := \n  { k ∈ proj1_exists (ax_power_set x) | k ⊆ x }.\n\nLemma power_set_def : forall x y , x ∈ power_set y <-> x ⊆ y.\nProof.\n  intros.\n  constructor; unfold power_set.\n  intros.\n  apply set_builder_property in H.\n  auto.\n  intros.\n  apply set_builder_def.\n  pose (a:= proj2_exists (ax_power_set y)).\n  auto.\n  auto.\nQed.\n\nLtac set_solver_power :=\n  repeat match goal with\n  | [ H : _ ∈ power_set _ |- _ ] => apply power_set_def in H\n  | [ |- _ ∈ power_set _ ] => apply power_set_def\n  | _ => set_solver\n  end.\n\nLemma power_set_empty : power_set Ø = { Ø }.\nProof.\n  set_solver_power.\nQed.\n\nLemma power_set_one : forall a, power_set { a } = { Ø , { a } }.\nProof.\n  set_solver_power.\n  pose (H z0 H2).\n  set_solver.\n  elim H0; intros.\n  destruct H3.\n  destruct (Classical_Prop.classic (x ∈ z)).\n  pose (H x H5).\n  pose (H3 H5).\n  contradiction.\n  destruct (Classical_Prop.classic (x ∉ {z0})).\n  pose (H4 H6).\n  contradiction.\n  apply Classical_Prop.NNPP in H6.\n  set_solver.\nQed.\n", "meta": {"author": "HKalbasi", "repo": "ZFC-coq", "sha": "1f9f634a533062b83547e4b992cf8bc6cff3847d", "save_path": "github-repos/coq/HKalbasi-ZFC-coq", "path": "github-repos/coq/HKalbasi-ZFC-coq/ZFC-coq-1f9f634a533062b83547e4b992cf8bc6cff3847d/power_set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6964444927257274}}
{"text": "Require Export models.\n\n(* When we give a mathematical definition of a concept sometimes we\n   parametrize this definition by a mathematical object. So for\n   instance, when we give the definition of what a formula is in a\n   dynamic logic we parametrize this definition by a set of dynamic\n   operators. Then, when we talk of a particular set of dynamic\n   formulas we specify the set of operators we are using and by doing\n   this we define a concrete set of formulas.\n\n   Certainly it would be highly inconvenient if a proof assistant\n   didn't have this particular form of abstraction. Imagine having to\n   repeat all the definitions that make a dynamic logic (e.g., the set\n   of formulas, the semantics, the notion of equivalent models, etc.)\n   separately for each concrete dynamic logic. This would be\n   innaceptable.\n\n   One elegant solution of this problem in Coq is to use modules,\n   module types and parameterized modules (aka functors).\n\n   Modules will allows us to wrap our mathematical definitions,\n   theorems and proofs and anything else that we could do in the\n   toplevel. Module types specify the general shape and type\n   properties of modules. A parameterized module is a module that\n   depends on a parameter. This parameter must also be module.\n\n   We now define the module type (or signature) DYN as consisting of:\n\n   - A dynamic set of operators Dyn with type Set and\n\n   - A function F with type (Dyn -> muf) that maps each dynamic\n   operator to its corresponding model update function.\n\n   By using this module type we can pack together these two concepts.\n\n   A module D of module type DYN would consist of:\n\n   - A concrete set of dynamic operators D.Dyn and\n\n   - A concrete mapping D.F between these dynamic operators and their\n   corresponding muf.\n\n   Notice how we used the dot operator to access the components of the\n   module D.\n\n   The reader can find examples of modules of type DYN in the file\n   examples.v.\n\n*)\n\nModule Type DYN.\nContext (Dyn : Set).\nContext (F : Dyn -> muf).\nEnd DYN.\n\n(* Here we define a parameterized module DynLogic that expects as a\n   parameter a module D of module type DYN. This means that inside\n   this module we can assume the existence of:\n\n   - A set of dynamic operators D.Dyn and\n\n   - A mapping D.F between these dynamic operators and their\n   corresponding muf.\n\n   This parameterization allows us to give all of the definitions that\n   depend on D.Dyn and on D.F without assuming a particular set of\n   dynamic operators. Moreover, we can later take this functor and\n   apply it to a module D of type DYN to obtain a module with all the\n   definitions of the concrete dynamic logic with the dynamic\n   operators defined in the parameter D.\n\n   The reader can find examples of modules that are the result of\n   applications of this functor (i.e., concrete dynamic logics) in\n   the file examples.v.\n\n*)\n\nModule DynLogic (D: DYN).\n\n(* Syntax *)\n\nInductive form : Set :=\n  | Atom    : prop -> form\n  | Bottom  : form\n  | Impl    : form -> form -> form\n  | DynDiam : D.Dyn -> form -> form.\n\nCoercion Atom : prop >-> form.\n\n(* Basic notation *)\nNotation \"⊥'\" := Bottom.\n\nNotation \"p ->' q\" := (Impl p q)\n                     (at level 90, right associativity).\n\nNotation \"⃟ f φ\" := (DynDiam f φ)\n                     (at level 65, f at level 9, right associativity).\n\n(* Syntactic sugar *)\nDefinition Not (φ : form) : form := φ ->' ⊥'.\n\nNotation \"~' p\" := (Not p)\n                   (at level 70, right associativity).\n\nDefinition Top : form := ~'⊥'.\n\nNotation \"⊤'\" := Top.\n\nDefinition And (φ ψ : form) : form := ~' (φ ->' ~'ψ).\n\nNotation \"p /\\' q\" := (And p q)\n                     (at level 80, right associativity).\n\nDefinition Or (φ ψ : form) : form := ~'φ ->' ψ.\n\nNotation \"p \\/' q\" := (Or p q)\n                     (at level 85, right associativity).\n\nDefinition Iif (φ ψ : form) : form := (φ ->' ψ) /\\' (ψ ->' φ).\n\nNotation \"p <->' q\" := (Iif p q)\n                     (at level 95, right associativity).\n\nDefinition DynBox (d : D.Dyn) (φ : form) : form := ~'⃟ d ~'φ.\n\nNotation \"⃞ d φ\" := (DynBox d φ)\n                     (at level 65, d at level 9, right associativity).\n\n\n(* Semantics *)\n\nReserved Notation \"p |= φ\" (at level 30).\n\nFixpoint satisfies (𝔐: pointed_model) (φ : form) : Prop :=\n  match φ with\n  | Atom a => (a, 𝔐.(pm_point)) ∈ 𝔐.(m_val)\n  | Bottom => False\n  | φ1 ->' φ2 => (𝔐 |= φ1) -> (𝔐 |= φ2)\n  | ⃟f φ =>\n    let fw := D.F f 𝔐.(m_states) in\n    exists p', p' ∈ fw 𝔐  /\\  p' |= φ\n  end\nwhere \"𝔐 |= φ\" := (satisfies 𝔐 φ).\n\nDefinition big_and Δ := fold_right And Top Δ.\n\nNotation \"'⋀' Δ\" := (big_and Δ) (at level 0).\n\nLemma sat_fold_forall m Δ:\n  Forall (fun φ : form => m |= φ) Δ <-> m |= ⋀Δ.\nProof.\n  elim: Δ; first by simpl; tauto.\n  move=>φ Δ /= ->.\n  tauto.\nQed.\n\nTheorem sat_classic : forall st φ, st |= φ \\/ st |= ~' φ.\nProof. by move=>*; apply: classic. Qed.\n\nDefinition equivalent (𝔐 𝔐': pointed_model) :=\n  forall (φ: form), (𝔐 |= φ) <-> (𝔐' |= φ).\n\nNotation \"m ≡ m'\" := (equivalent m m') (at level 0).\n\n(* Semantic Definitions *)\n\nSection Bisimulation.\n\nContext {W W' : Set}.\n\nDefinition state_model_relation : Type :=\n  state_model W -> state_model W' -> Prop.\n\nContext (Z : state_model_relation).\n\nDefinition atomic_harmony : Prop :=\n  forall p p', Z p p' -> forall pr: prop,\n      (pr, p.(st_point)) ∈ p.(st_val) <-> (pr, p'.(st_point)) ∈ p'.(st_val).\n\n\nDefinition f_zig (f : muf) : Prop :=\n  forall p q p', Z p p' ->\n    q ∈ f W p ->\n    (exists q', q' ∈ f W' p' /\\ Z q q').\n\nDefinition f_zag (f : muf) : Prop :=\n  forall p q' p', Z p p' ->\n    q' ∈ f W' p' ->\n    (exists q, q ∈ f W p /\\ Z q q').\n\nDefinition bisimulation : Prop :=\n  atomic_harmony /\\\n  (forall d, f_zig (D.F d)) /\\\n  (forall d, f_zag (D.F d)).\n\nEnd Bisimulation.\n\nDefinition bisimilar (𝔐 𝔐': pointed_model) : Prop :=\n  exists Z, bisimulation Z /\\ Z 𝔐 𝔐'.\n\nNotation \"𝔐 ⇆ 𝔐'\" := (bisimilar 𝔐 𝔐') (at level 30).\n\nArguments state_model_relation : clear implicits.\n\nSection Getters.\n\nContext {W W' : Set}.\nContext {Z: state_model_relation W W'}.\nContext (bis: bisimulation Z).\n\nDefinition get_AH : atomic_harmony Z.\n  move: bis =>[HA _].\n  exact: HA.\nDefined.\n\nDefinition get_Zig d : f_zig Z (D.F d).\n  move: bis =>[_ [H _]].\n  exact: H.\nDefined.\n\nDefinition get_Zag d : f_zag Z (D.F d).\n  move: bis =>[_ [_ H]].\n  exact: H.\nDefined.\n\nEnd Getters.\n\nEnd DynLogic.\n\n(* Local Variables: *)\n(* company-coq-local-symbols: ( ) *)\n(* End: *)\n", "meta": {"author": "liis-modal-logics", "repo": "RelationChangingLogicsInCoq", "sha": "f320f9b0804d9bddff5640493c876e6db6252f70", "save_path": "github-repos/coq/liis-modal-logics-RelationChangingLogicsInCoq", "path": "github-repos/coq/liis-modal-logics-RelationChangingLogicsInCoq/RelationChangingLogicsInCoq-f320f9b0804d9bddff5640493c876e6db6252f70/theories/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6964444822567136}}
{"text": "From DEZ.Has Require Export\n  FieldOperations FieldIdentities FieldInverses.\nFrom DEZ.ShouldHave Require Export\n  FieldNotations.\n\n(** Semirings only come with zero and one out of the box,\n    so we have to construct all the other natural numbers\n    from repeated additions and multiplications.\n    The optimal way to do this is quite complicated,\n    as demonstrated in OEIS sequence A005245,\n    but we can make the job more manageable\n    by limiting ourselves to just addition. *)\n\n(** The following definitions produce\n    the natural numbers using the simplest suboptimal reduction tree. *)\n\nSection Context.\n\nContext {A : Type} {has_add : HasAdd A} {has_zero : HasZero A}\n  {has_one : HasOne A}.\n\nFixpoint of_nat (n : nat) : A :=\n  match n with\n  | O => 0\n  | S p => 1 + of_nat p\n  end.\n\nEnd Context.\n\n(** The following definitions produce\n    the natural numbers using one of the optimal reduction trees. *)\n\n(** TODO Clean up the termination proof. *)\n\nRequire Import List Program Recdef Omega PeanoNat.\n\nSection Context.\n\nImport ListNotations Nat.\n\nContext {A : Type} {has_add : HasAdd A} {has_zero : HasZero A}\n  {has_one : HasOne A}.\n\nFunction of_nat' (n : nat) {measure id n} : A :=\n  if n =? 0 then 0 else\n  if n =? 1 then 1 else\n  let p : nat := log2 n in\n  if n =? 2 ^ p then of_nat' (n / 2) + of_nat' (n / 2) else\n  of_nat' (n - 2 ^ p) + of_nat' (2 ^ p).\nProof.\n  { intros n H0 H1 H2.\n    apply eqb_neq in H0. apply eqb_neq in H1. apply eqb_eq in H2. cbv [id].\n    rewrite H2.\n    pose proof (neq_succ_0 1) as H.\n    epose proof log2_spec n _ as H'. rewrite pow_succ_r' in H'.\n    eapply le_lt_trans.\n      apply div_le_mono. apply H. apply (proj1 H').\n      apply (div_lt_upper_bound _ _ _ H). apply H'. }\n  { intros n H0 H1 H2.\n    apply eqb_neq in H0. apply eqb_neq in H1. apply eqb_neq in H2. cbv [id].\n    pose proof (neq_succ_0 1) as H.\n    epose proof log2_spec n _ as H'. rewrite pow_succ_r' in H'.\n    rewrite le_neq. split.\n      apply H'.\n      apply neq_sym. apply H2. }\n  { intros n H0 H1 H2.\n    apply eqb_neq in H0. apply eqb_neq in H1. apply eqb_neq in H2. cbv [id].\n    pose proof (neq_succ_0 1) as H.\n    epose proof log2_spec n _ as H'. rewrite pow_succ_r' in H'.\n    apply sub_lt.\n      apply H'. epose proof mul_lt_mono_pos_l 2 0 (2 ^ log2 n) _.\n      apply H3. eapply lt_trans.\n      apply neq_0_lt. apply neq_sym. apply H0.\n      apply H'. }\nUnshelve. all: omega. Defined.\n\nEnd Context.\n\n(** The following definitions produce\n    the first few natural numbers as special cases. *)\n\nSection Context.\n\nContext {A : Type} {has_add : HasAdd A} {has_one : HasOne A}.\n\nDefinition two : A := one + one.\nDefinition three : A := two + one.\nDefinition four : A := two + two.\nDefinition five : A := four + one.\nDefinition six : A := four + two.\nDefinition seven : A := four + three.\nDefinition eight : A := four + four.\nDefinition nine : A := eight + one.\n\nEnd Context.\n", "meta": {"author": "Tuplanolla", "repo": "dez", "sha": "c2eadc2e032094c3504ec3803c000dba4feb547e", "save_path": "github-repos/coq/Tuplanolla-dez", "path": "github-repos/coq/Tuplanolla-dez/dez-c2eadc2e032094c3504ec3803c000dba4feb547e/garbage/prototype/Offers/FieldConstants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6964444791807796}}
{"text": "(** Abstract Reduction Systems, from Semantics Lecture at Programming Systems Lab, https://www.ps.uni-saarland.de/courses/sem-ws13/ *)\n\nRequire Export Base.\n\nNotation \"p '<=1' q\" := (forall x, p x -> q x) (at level 70).\nNotation \"p '=1' q\" := (p <=1 q /\\ q <=1 p) (at level 70).\nNotation \"R '<=2' S\" := (forall x y, R x y -> S x y) (at level 70).\nNotation \"R '=2' S\"  := (R <=2 S /\\ S <=2 R) (at level 70).\n\n(** Relational composition *)\n\nDefinition rcomp X Y Z (R : X -> Y -> Prop) (S : Y -> Z -> Prop) \n: X -> Z -> Prop :=\n  fun x z => exists y, R x y /\\ S y z.\n\n(** Power predicates *)\n\nRequire Import Arith.\nDefinition pow X R n : X -> X -> Prop := it (rcomp R) n eq.\n\nSection FixX.\n  Variable X : Type.\n  Implicit Types R S : X -> X -> Prop.\n  Implicit Types x y z : X.\n\n  Definition reflexive R := forall x, R x x.\n  Definition symmetric R := forall x y, R x y -> R y x.\n  Definition transitive R := forall x y z, R x y -> R y z -> R x z.\n  Definition functional R := forall x y z, R x y -> R x z -> y = z.\n\n\n  (** Reflexive transitive closure *)\n\n  Inductive star R : X -> X -> Prop :=\n  | starR x : star R x x\n  | starC x y z : R x y -> star R y z -> star R x z.\n\n  Lemma star_trans R:\n    transitive (star R).\n  Proof.\n    induction 1; eauto using star.\n  Qed.\n\n  Lemma R_star R: R <=2 star R.\n  Proof.\n    eauto using star.\n  Qed.\n\n  Instance star_PO R: PreOrder (star R).\n  Proof.\n    constructor;repeat intro;try eapply star_trans;  now eauto using star.\n  Qed.\n  \n  (** Power characterization *)\n\n  Lemma star_pow R x y :\n    star R x y <-> exists n, pow R n x y.\n  Proof.\n    split; intros A.\n    - induction A as [|x x' y B _ [n IH]].\n      + exists 0. reflexivity.\n               + exists (S n), x'. auto.\n               - destruct A as [n A].\n                 revert x A. induction n; intros x A.\n                 + destruct A. constructor.\n                 + destruct A as [x' [A B]]. econstructor; eauto.\n  Qed.\n\n  Lemma pow_star R x y n:\n    pow R n x y -> star R x y.\n  Proof.\n    intros A. erewrite star_pow. eauto.\n  Qed.\n\n  Lemma pow_add R n m (s t : X) : pow R (n + m) s t <-> rcomp (pow R n) (pow R m) s t.\n  Proof.\n    revert m s t; induction n; intros m s t.\n    - simpl. split; intros. econstructor. split. unfold pow. simpl. reflexivity. eassumption.\n      destruct H as [u [H1 H2]]. unfold pow in H1. simpl in *. subst s. eassumption.\n    - simpl in *; split; intros.\n      + destruct H as [u [H1 H2]].\n        change (it (rcomp R) (n + m) eq) with (pow R (n+m)) in H2.\n        rewrite IHn in H2.\n        destruct H2 as [u' [A B]]. unfold pow in A.\n        econstructor. \n        split. econstructor. repeat split; repeat eassumption. eassumption.\n      + destruct H as [u [H1 H2]].\n        destruct H1 as [u' [A B]].\n        econstructor.  split. eassumption. change (it (rcomp R) (n + m) eq) with (pow R (n + m)).\n        rewrite IHn. econstructor. split; eassumption.\n  Qed.\n  \n  Lemma rcomp_1 (R : X -> X -> Prop): R =2 pow R 1.  Proof.\n    split; intros s t; unfold pow in *; simpl in *; intros H.\n    - econstructor. split; eauto.\n    - destruct H as [u [H1 H2]]; subst u; eassumption.\n  Qed.\n\n  \nEnd FixX.\n\nExisting Instance star_PO.\n\n(** A notion of a reduction sequence which keeps track of the largest occuring state *)\n\nInductive redWithMaxSize {X} (size:X -> nat) (step : X -> X -> Prop): nat -> X -> X -> Prop:=\n  redWithMaxSizeR m s: m = size s -> redWithMaxSize size step m s s \n| redWithMaxSizeC s s' t m m': step s s' -> redWithMaxSize size step m' s' t -> m = max (size s) m' -> redWithMaxSize size step m s t.\n\nLemma redWithMaxSize_ge X size step (s t:X) m:\n  redWithMaxSize size step m s t -> size s<= m /\\ size t <= m.\nProof.\n  induction 1;subst;firstorder (repeat eapply Nat.max_case_strong; try omega).\nQed.\n\nLemma redWithMaxSize_trans X size step (s t u:X) m1 m2 m3:\n redWithMaxSize size step m1 s t -> redWithMaxSize size step m2 t u -> max m1 m2 = m3 -> redWithMaxSize size step m3 s u.\nProof.\n  induction 1 in m2,u,m3|-*;intros.\n  -specialize (redWithMaxSize_ge H0) as [].\n   revert H1;\n     repeat eapply Nat.max_case_strong; subst m;intros. all:replace m3 with m2 by omega. all:eauto.\n  - specialize (redWithMaxSize_ge H0) as [].\n    specialize (redWithMaxSize_ge H2) as [].\n    eassert (H1':=Max.le_max_l _ _);rewrite H3 in H1'.\n    eassert (H2':=Max.le_max_r _ _);rewrite H3 in H2'.\n    econstructor. eassumption.\n     \n    eapply IHredWithMaxSize. eassumption. reflexivity.\n    subst m;revert H3;repeat eapply Nat.max_case_strong;intros;try omega. \nQed.\n\n", "meta": {"author": "uds-psl", "repo": "cbv-lambda-calculus-reasonable", "sha": "4f12b7c8ce2816cdd771d22d04943e0fa81c63fd", "save_path": "github-repos/coq/uds-psl-cbv-lambda-calculus-reasonable", "path": "github-repos/coq/uds-psl-cbv-lambda-calculus-reasonable/cbv-lambda-calculus-reasonable-4f12b7c8ce2816cdd771d22d04943e0fa81c63fd/ARS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.6963804109472649}}
{"text": "(** * Stlc: The Simply Typed Lambda-Calculus *)\n\nAdd LoadPath \"~/src/stlc_coq/\".\nRequire Export SfLib.\n\nModule STLC.\n\n(* Types *)\nInductive ty : Type := \n  | TBool  : ty\n  | TNat   : ty\n  | TArrow : ty -> ty -> ty.\n\n\n(* Terms *)\nInductive tm : Type :=\n  | tvar : id -> tm\n  | tapp : tm -> tm -> tm\n  | tabs : id -> ty -> tm -> tm\n  | ttrue : tm\n  | tfalse : tm\n  | tif : tm -> tm -> tm -> tm\n  | tzero : tm\n  | tsucc : tm -> tm\n  | tiszero : tm -> tm.\n\nTactic Notation \"t_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"tvar\" | Case_aux c \"tapp\" \n  | Case_aux c \"tabs\" | Case_aux c \"ttrue\" \n  | Case_aux c \"tfalse\" | Case_aux c \"tif\" ].\n\n\n(* Values *)\nInductive avalue : tm -> Prop := \n  | av_abs : forall x T t, avalue (tabs x T t).\n\nInductive bvalue : tm -> Prop :=\n  | bv_true : bvalue ttrue\n  | bv_false : bvalue tfalse.\n\nInductive nvalue : tm -> Prop :=\n  | nv_zero : nvalue tzero\n  | nv_succ : forall t, nvalue t -> nvalue (tsucc t).\n\nDefinition value (t:tm) := avalue t \\/ bvalue t \\/ nvalue t.\n\nHint Constructors avalue bvalue nvalue.\nHint Unfold value.  \nHint Unfold extend.\n\n\n(* Substitution *)\nReserved Notation \"'[' x ':=' s ']' t\" (at level 20).\n\nFixpoint subst (x:id) (s:tm) (t:tm) : tm :=\n  match t with\n  | tvar x' => \n      if eq_id_dec x x' then s else t\n  | tabs x' T t1 => \n      tabs x' T (if eq_id_dec x x' then t1 else ([x:=s] t1)) \n  | tapp t1 t2 => \n      tapp ([x:=s] t1) ([x:=s] t2)\n  | ttrue => \n      ttrue\n  | tfalse => \n      tfalse\n  | tif t1 t2 t3 => \n      tif ([x:=s] t1) ([x:=s] t2) ([x:=s] t3)\n  | tzero =>\n      tzero\n  | tsucc n =>\n     tsucc ([x:=s] n)\n  | tiszero n =>\n      tiszero ([x:=s] n)\n  end\n\nwhere \"'[' x ':=' s ']' t\" := (subst x s t).\n\n\n(* Small-Step Semantics *)\nReserved Notation \"t1 '==>' t2\" (at level 40).\n\nInductive step : tm -> tm -> Prop :=\n  (* final substitution *)\n  | ST_AppAbs : forall x T t12 v2,\n         value v2 ->\n         (tapp (tabs x T t12) v2) ==> [x:=v2]t12\n  (* reduce the left side *)\n  | ST_App1 : forall t1 t1' t2,\n         t1 ==> t1' ->\n         tapp t1 t2 ==> tapp t1' t2\n  (* reduce the right side *)\n  | ST_App2 : forall v1 t2 t2',\n         value v1 ->\n         t2 ==> t2' -> \n         tapp v1 t2 ==> tapp v1  t2'\n  (* return first clause if true *)\n  | ST_IfTrue : forall t1 t2,\n      (tif ttrue t1 t2) ==> t1\n  (* return second clause if false *)\n  | ST_IfFalse : forall t1 t2,\n      (tif tfalse t1 t2) ==> t2\n  (* reduce test to a ttrue or tfalse *)\n  | ST_If : forall t1 t1' t2 t3,\n      t1 ==> t1' ->\n      (tif t1 t2 t3) ==> (tif t1' t2 t3)\n  (* step body of Succ *)\n  | ST_Succ : forall t1 t1',\n      t1 ==> t1' ->\n      (tsucc t1) ==> (tsucc t1')\n  (* iszero(O) is true *)\n  | ST_IszeroZero :\n      (tiszero tzero) ==> ttrue\n  (* iszero(S(n)) is false *)\n  | ST_IszeroSucc : forall t1,\n       nvalue t1 ->\n      (tiszero (tsucc t1)) ==> tfalse\n  (* step body of iszero *)\n  | ST_Iszero : forall t1 t1',\n      t1 ==> t1' ->\n      (tiszero t1) ==> (tiszero t1')\n\nwhere \"t1 '==>' t2\" := (step t1 t2).\n\nNotation multistep := (multi step).\nNotation \"t1 '==>*' t2\" := (multistep t1 t2) (at level 40).\n\nTactic Notation \"step_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"ST_AppAbs\" | Case_aux c \"ST_App1\" \n  | Case_aux c \"ST_App2\" | Case_aux c \"ST_IfTrue\" \n  | Case_aux c \"ST_IfFalse\" | Case_aux c \"ST_If\" ].\n\nHint Constructors step.\n\n\n(* Typing, Contexts *)\nModule PartialMap.\n\nDefinition partial_map (A:Type) := id -> option A.\n\nDefinition empty {A:Type} : partial_map A := (fun _ => None). \n\nDefinition extend {A:Type} (Gamma : partial_map A) (x:id) (T : A) :=\n  fun x' => if eq_id_dec x x' then Some T else Gamma x'.\n\nLemma extend_eq : forall A (ctxt: partial_map A) x T,\n  (extend ctxt x T) x = Some T.\nProof.\n  intros. unfold extend. rewrite eq_id. auto.\nQed.\n\nLemma extend_neq : forall A (ctxt: partial_map A) x1 T x2,\n  x2 <> x1 ->                       \n  (extend ctxt x2 T) x1 = ctxt x1.\nProof.\n  intros. unfold extend. rewrite neq_id; auto.\nQed.\n\nEnd PartialMap.\n\nDefinition context := partial_map ty.\n\n\n(* Typing Relation *)\nReserved Notation \"Gamma '|-' t '\\in' T\" (at level 40).\n    \nInductive has_type : context -> tm -> ty -> Prop :=\n  | T_Var : forall Gamma x T,\n      Gamma x = Some T ->\n      Gamma |- tvar x \\in T\n  | T_Abs : forall Gamma x T11 T12 t12,\n      extend Gamma x T11 |- t12 \\in T12 -> \n      Gamma |- tabs x T11 t12 \\in TArrow T11 T12\n  | T_App : forall T11 T12 Gamma t1 t2,\n      Gamma |- t1 \\in TArrow T11 T12 -> \n      Gamma |- t2 \\in T11 -> \n      Gamma |- tapp t1 t2 \\in T12\n  | T_True : forall Gamma,\n      Gamma |- ttrue \\in TBool\n  | T_False : forall Gamma,\n      Gamma |- tfalse \\in TBool\n  | T_If : forall t1 t2 t3 T Gamma,\n      Gamma |- t1 \\in TBool ->\n      Gamma |- t2 \\in T ->\n      Gamma |- t3 \\in T ->\n      Gamma |- tif t1 t2 t3 \\in T\n  | T_Zero : forall Gamma,\n      Gamma |- tzero \\in TNat \n  | T_Succ : forall t1 Gamma,\n      Gamma |- t1 \\in TNat ->\n      Gamma |- tsucc t1 \\in TNat\n  | T_Iszero : forall t1 Gamma,\n      Gamma |- t1 \\in TNat ->\n      Gamma |- tiszero t1 \\in TBool\n\nwhere \"Gamma '|-' t '\\in' T\" := (has_type Gamma t T).\n\nTactic Notation \"has_type_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"T_Var\" | Case_aux c \"T_Abs\" \n  | Case_aux c \"T_App\" | Case_aux c \"T_True\" \n  | Case_aux c \"T_False\" | Case_aux c \"T_If\"\n  | Case_aux c \"T_Zero\"  | Case_aux c \"T_Succ\" \n  | Case_aux c \"T_Iszero\" ].\n\nHint Constructors has_type.\n\n\n(* Generation Relation *)\nReserved Notation \"Gamma '|-' T '~>' t\" (at level 40).\n    \nInductive gens_term : context -> ty -> tm -> Prop :=\n  | G_Var : forall Gamma x T,\n      Gamma x = Some T ->\n      Gamma |- T ~> tvar x\n  | G_Abs : forall Gamma x T11 T12 t12,\n      extend Gamma x T11 |- T12 ~> t12 -> \n      Gamma |- TArrow T11 T12 ~> tabs x T11 t12\n  | G_App : forall T11 T12 Gamma t1 t2,\n      Gamma |- TArrow T11 T12 ~> t1 ->\n      Gamma |- T11 ~> t2 ->\n      Gamma |- T12 ~> tapp t1 t2\n  | G_True : forall Gamma,\n      Gamma |- TBool ~> ttrue\n  | G_False : forall Gamma,\n      Gamma |- TBool ~> tfalse\n  | G_If : forall t1 t2 t3 T Gamma,\n      Gamma |- TBool ~> t1 ->\n      Gamma |- T ~> t2 ->\n      Gamma |- T ~> t3 ->\n      Gamma |- T ~> tif t1 t2 t3\n  | G_Zero : forall Gamma,\n      Gamma |- TNat ~> tzero\n  | G_Succ : forall t1 Gamma,\n      Gamma |- TNat ~> t1 ->\n      Gamma |- TNat ~> tsucc t1\n  | G_Iszero : forall t1 Gamma,\n      Gamma |- TNat ~> t1 ->\n      Gamma |- TBool ~> tiszero t1\n\nwhere \"Gamma '|-' T '~>' t\" := (gens_term Gamma T t).\n\nTactic Notation \"gens_term_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"G_Var\"   | Case_aux c \"G_Abs\" \n  | Case_aux c \"G_App\"   | Case_aux c \"G_True\" \n  | Case_aux c \"G_False\" | Case_aux c \"G_If\" \n  | Case_aux c \"G_Zero\"  | Case_aux c \"G_Succ\" \n  | Case_aux c \"G_Iszero\" ].\n\nHint Constructors gens_term.\n\n\n(* Typing and Generation tests *)\nDefinition x := (Id 0).\nDefinition y := (Id 1).\nDefinition z := (Id 2).\nHint Unfold x.\nHint Unfold y.\nHint Unfold z.\n\nExample typing_example_1 :\n  empty |- tabs x TBool (tvar x) \\in TArrow TBool TBool.\nProof. auto.  Qed.\n\nExample typing_example_2 :\n  empty |-\n    (tabs x TBool\n       (tabs y (TArrow TBool TBool)\n          (tapp (tvar y) (tapp (tvar y) (tvar x))))) \\in\n    (TArrow TBool (TArrow (TArrow TBool TBool) TBool)).\nProof with auto using extend_eq.\n  apply T_Abs.\n  apply T_Abs.\n  eapply T_App. apply T_Var...\n  eapply T_App. apply T_Var...\n  apply T_Var...\nQed.\n\n(* Nat ~> S(S(S(O))) *)\nExample typing_example_3 :\n  empty |-\n    tsucc (tsucc (tsucc tzero))\n    \\in TNat.\nProof with auto using extend_eq.\n  auto.\nQed.\n\n(* Nat ~> (\\x:nat.S(x)) O *)\nExample typing_example_4 :\n  empty |-\n    tapp (tabs x TNat (tsucc (tvar x))) (tsucc tzero)\n    \\in TNat.\nProof with auto using extend_eq.\n  eapply T_App. apply T_Abs. apply T_Succ. apply T_Var...\n  apply T_Succ. apply T_Zero.\nQed.\n\n\nExample gen_example_1 :\n  empty |- TArrow TBool TBool ~> tabs x TBool (tvar x).\nProof.\n  apply G_Abs. apply G_Var. reflexivity.  Qed.\n\n(* (bool->((bool->bool)->bool)) ~> (\\x:bool.(\\y:bool->bool.(y(y x)))) *)\nExample gen_example_2 :\n  empty |-\n    (TArrow TBool (TArrow (TArrow TBool TBool) TBool)) ~>\n    (tabs x TBool\n       (tabs y (TArrow TBool TBool)\n          (tapp (tvar y) (tapp (tvar y) (tvar x))))).\nProof with auto using extend_eq.\n  apply G_Abs. apply G_Abs. eapply G_App. apply G_Var...\n  eapply G_App. apply G_Var...\n  apply G_Var...\nQed.\n\n(* thesis page 14 example *)\nExample gen_example_3 :\n  empty |-\n    (TArrow TBool TBool) ~>\n    (tapp (tabs x (TArrow TBool TBool) (tvar x)) (tabs y TBool ttrue)).\nProof with auto using extend_eq.\n  eapply G_App. apply G_Abs. apply G_Var...\n  apply G_Abs. apply G_True.\nQed.\n\n(* Nat ~> S(S(S(O))) *)\nExample gen_example_4 :\n  empty |-\n    TNat ~>\n    tsucc (tsucc (tsucc tzero)).\nProof with auto using extend_eq.\n  auto.\nQed.\n\n(* Nat ~> (\\x:nat.S(x)) O *)\nExample gen_example_5 :\n  empty |-\n    TNat ~>\n    tapp (tabs x TNat (tsucc (tvar x))) (tsucc tzero).\nProof with auto using extend_eq.\n  eapply G_App. apply G_Abs. apply G_Succ. apply G_Var...\n  apply G_Succ. apply G_Zero.\nQed.\n\n\n(* Soundness *)\nTheorem soundness : forall Gamma t T,\n  Gamma |- T ~> t -> \n  Gamma |- t \\in T. \nProof.\n  intros G t T H. induction H.\n  Case \"Gamma |- T ~> tvar\".\n    apply T_Var. rewrite H. reflexivity.\n  Case \"Gamma |- T ~> tabs\".\n    apply T_Abs. apply IHgens_term.\n  Case \"Gamma |- T ~> tapp\".\n    apply (T_App T11). \n    apply IHgens_term1. apply IHgens_term2.\n  Case \"Gamma |- T ~> ttrue\".\n    apply T_True.\n  Case \"Gamma |- T ~> tfalse\".\n    apply T_False.\n  Case \"Gamma |- T ~> tif\".\n    apply T_If. apply IHgens_term1. \n    apply IHgens_term2. apply IHgens_term3.\n  Case \"Gamma |- T ~> tzero\".\n    apply T_Zero.\n  Case \"Gamma |- T ~> tsucc\".\n    apply T_Succ. apply IHgens_term.\n  Case \"Gamma |- T ~> tiszero\".\n    apply T_Iszero. apply IHgens_term.\nQed.\n\n\n(* Completeness *)\nTheorem completeness : forall Gamma t T,\n  Gamma |- t \\in T ->\n  Gamma |- T ~> t.\nProof.\n  intros G t T H. induction H.\n  Case \"Gamma |- tvar \\in T\".\n    apply G_Var. rewrite H. reflexivity.\n  Case \"Gamma |- tabs \\in T\".\n    apply G_Abs. apply IHhas_type.\n  Case \"Gamma |- tapp \\in T\".\n    apply (G_App T11). \n    apply IHhas_type1. apply IHhas_type2.\n  Case \"Gamma |- ttrue \\in T\".\n    apply G_True.\n  Case \"Gamma |- tfalse \\in T\".\n    apply G_False.\n  Case \"Gamma |- tif \\in T\".\n    apply G_If. apply IHhas_type1. \n    apply IHhas_type2. apply IHhas_type3.\n  Case \"Gamma |- tzero \\in T\".\n    apply G_Zero.\n  Case \"Gamma |- tsucc \\in T\".\n    apply G_Succ. apply IHhas_type.\n  Case \"Gamma |- tiszero \\in T\".\n    apply G_Iszero. apply IHhas_type.\nQed.\n\n\nEnd STLC.\n\n", "meta": {"author": "mulias", "repo": "type_directed_synthesis", "sha": "5403d4be43a9c79ba60c1c75aba9ec11dfd30ec4", "save_path": "github-repos/coq/mulias-type_directed_synthesis", "path": "github-repos/coq/mulias-type_directed_synthesis/type_directed_synthesis-5403d4be43a9c79ba60c1c75aba9ec11dfd30ec4/Stlc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.696380405537007}}
{"text": "(* week-02_proving-logical-properties.v *)\n(* FPP 2020 - YSC3236 2020-2021, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 23 Aug 2020 *)\n\n(* ********** *)\n\nLemma identity :\n  forall A : Prop,\n    A -> A.\nProof.\n  intro A.\n  intro H_A.\n  exact H_A.\nQed.\n\n(* ********** *)\n\nLemma proving_a_conjunction :\n  forall A B : Prop,\n    A -> B -> A /\\ B.\nProof.\n  intros A B H_A H_B.\n  split.\n\n  exact H_A.\n\n  exact H_B.\n\n  Restart.\n\n  intros A B H_A H_B.\n  split.\n  { exact H_A. }\n  { exact H_B. }\n\n  Restart.\n\n  intros A B H_A H_B.\n  split.\n  - exact H_A.\n\n  - exact H_B.\n\n  Restart.\n\n  intros A B H_A H_B.\n  Check (conj H_A H_B).\n  exact (conj H_A H_B).\nQed.\n\n(* ********** *)\n\nLemma proving_a_ternary_conjunction :\n  forall A B C : Prop,\n    A -> B -> C -> A /\\ B /\\ C.\nProof.\n  intros A B C.\n  intros H_A H_B H_C.\n  split.\n  - exact H_A.\n  - split.\n    + exact H_B.\n    + exact H_C.\n\n  Restart.\n\n  intros A B C.\n  intros H_A H_B H_C.\n  exact (conj H_A (conj H_B H_C)).\nQed.\n\n(* ********** *)\n\nLemma proving_a_disjunction :\n  forall A B : Prop,\n    A -> B -> A \\/ B.\nProof.\n  intros A B H_A H_B.\n  left.\n  exact H_A.\n\n  Restart.\n\n  intros A B H_A H_B.\n  right.\n  exact H_B.\nQed.\n\n(* ********** *)\n\nLemma conjunction_is_commutative :\n  forall A B : Prop,\n    A /\\ B <-> B /\\ A.\nProof.\n  intros A B.\n  split.\n\n  - intros [H_A H_B].\n    exact (conj H_B H_A).\n\n  - intros [H_B H_A].\n    exact (conj H_A H_B).\nQed.\n\nLemma conjunction_is_commutative_aux :\n  forall A B : Prop,\n    A /\\ B -> B /\\ A.\nProof.\n  intros A B [H_A H_B].\n  exact (conj H_B H_A).\nQed.\n\nLemma conjunction_is_commutative_revisited :\n  forall A B : Prop,\n    A /\\ B <-> B /\\ A.\nProof.\n  intros A B.\n  split.\n\n  - exact (conjunction_is_commutative_aux A B).\n\n  - exact (conjunction_is_commutative_aux B A).\nQed.\n\n(* ********** *)\n\n(** * Exercise 9-13 *)\n\nLemma conjunction_is_associative :\n  forall A B C : Prop,\n    (A /\\ B) /\\ C <-> A /\\ B /\\ C.\nProof.\n  intros A B C.\n  split.\n\n  - intros [[H_A H_B] H_C].\n    exact (conj H_A (conj H_B H_C)).\n\n  - intros [H_A [H_B H_C]].\n    exact (conj (conj H_A H_B) H_C).\nQed.\n\nLemma disjunction_is_commutative :\n  forall A B : Prop,\n    A \\/ B <-> B \\/ A.\nProof.\n  intros A B.\n  split.\n\n  - intros [H_A | H_B].\n    right. exact H_A.\n    left. exact H_B.\n\n  - intros [H_B | H_A].\n    right. exact H_B.\n    left. exact H_A.\nQed.\n\nLemma disjunction_is_associative :\n  forall A B C : Prop,\n    (A \\/ B) \\/ C <-> A \\/ B \\/ C.\nProof.\n  intros A B C.\n  split.\n\n  - intros [[H_A | H_B] | H_C].\n    left. exact H_A.\n    right. left. exact H_B.\n    right. right. exact H_C.\n\n  - intros [H_A | [H_B | H_C]].\n    left. left. exact H_A.\n    left. right. exact H_B.\n    right. exact H_C.\nQed.\n\n(* ********** *)\n\nProposition disjunction_distributes_over_conjunction_on_the_left :\n  forall A B C : Prop,\n    A \\/ (B /\\ C) <-> (A \\/ B) /\\ (A \\/ C).\nProof.\n  intros A B C.\n  split.\n\n  - intros [H_A | [H_B H_C]].\n\n    + split.\n\n      * left.\n        exact H_A.\n\n      * left.\n        exact H_A.\n\n    + split.\n\n      * right.\n        exact H_B.\n\n      * right.\n        exact H_C.\n\n  - intros [[H_A | H_B] [H_A' | H_C]].\n\n    + left. exact H_A.\n\n    + left. exact H_A.\n\n    + left. exact H_A'.\n\n    + right. exact (conj H_B H_C).\n\nQed.\n\nProposition disjunction_distributes_over_conjunction_on_the_right :\n  forall A B C : Prop,\n    (A /\\ B) \\/ C <-> (A \\/ C) /\\ (B \\/ C).\nProof.\n  intros A B C.\n  split.\n\n  - intros [[H_A H_B] | H_C].\n\n    + split.\n\n      * left.\n        exact H_A.\n\n      * left.\n        exact H_B.\n\n    + split.\n\n      * right.\n        exact H_C.\n\n      * right.\n        exact H_C.\n\n  - intros [[H_A | H_C] [H_B | H_C']].\n\n    + left. exact (conj H_A H_B).\n\n    + right. exact H_C'.\n\n    + right. exact H_C.\n\n    + right. exact H_C.\n\nQed.\n\nProposition conjunction_distributes_over_disjunction_on_the_left :\n  forall A B C : Prop,\n    A /\\ (B \\/ C) <-> (A /\\ B) \\/ (A /\\ C).\nProof.\n  intros A B C.\n  split.\n\n  - intros [H_A [H_B | H_C]].\n\n    + left. exact (conj H_A H_B).\n\n    + right. exact (conj H_A H_C).\n\n  - intros [[H_A H_B] | [H_A' H_C]].\n\n    + split.\n\n      * exact H_A.\n\n      * left. exact H_B.\n\n    + split.\n\n      * exact H_A'.\n\n      * right. exact H_C.\n\nQed.\n\nProposition conjunction_distributes_over_disjunction_on_the_right :\n  forall A B C : Prop,\n    (A \\/ B) /\\ C <-> (A /\\ C) \\/ (B /\\ C).\nProof.\n  intros A B C.\n  split.\n\n  - intros [[H_A | H_B] H_C].\n\n    + left. exact (conj H_A H_C).\n\n    + right. exact (conj H_B H_C).\n\n  - intros [[H_A H_C] | [H_B H_C']].\n\n    + split.\n\n      * left. exact H_A.\n\n      * exact H_C.\n\n    + split.\n\n      * right. exact H_B.\n\n      * exact H_C'.\n\nQed.\n\n(* ********** *)\n\nProposition modus_ponens :\n  forall A B : Prop,\n    A -> (A -> B) -> B.\nProof.\n  intros A B.\n  intros H_A H_A_implies_B.\n  Check (H_A_implies_B H_A).\n  exact (H_A_implies_B H_A).\n\n  Restart.\n    \n  intros A B.\n  intros H_A H_A_implies_B.\n  apply H_A_implies_B.\n  exact H_A.\nQed.\n\n(* ********** *)\n\nProposition modus_tollens :\n  forall A B : Prop,\n    ~B -> (A -> B) -> ~A.\nProof.\n  intros A B.\n  unfold not.\n  intros H_B_implies_False H_A_implies_B H_A.\n  apply H_B_implies_False.\n  apply H_A_implies_B.\n  exact H_A.\n \n  Restart.\n\n  intros A B.\n  unfold not.\n  intros H_B_implies_False H_A_implies_B H_A.\n  Check (H_A_implies_B H_A).\n  Check (H_B_implies_False (H_A_implies_B H_A)).\n  exact (H_B_implies_False (H_A_implies_B H_A)).\n\n  Restart.\n\n  intros A B.\n  unfold not.\n  intros H_B_implies_False H_A_implies_B H_A.\n  Check (modus_ponens A B).\n  Check (modus_ponens A B H_A).\n  Check (modus_ponens A B H_A H_A_implies_B).\n  Check (H_B_implies_False (modus_ponens A B H_A H_A_implies_B)).\n  exact (H_B_implies_False (modus_ponens A B H_A H_A_implies_B)).\nQed.\n\n(* ********** *)\n\nProposition conjunction_distributes_over_implication :\n  forall A B C : Prop,\n    (A -> B /\\ C) <-> ((A -> B) /\\ (A -> C)).\nProof.\n  intros A B C.\n  split.\n\n  - intros H_A_implies_B_and_C.\n    split.\n\n    * intro H_A.\n      Check (H_A_implies_B_and_C H_A).\n      destruct (H_A_implies_B_and_C H_A) as [H_B _].\n      exact H_B.\n\n    * intro H_A.\n      destruct (H_A_implies_B_and_C H_A) as [_ H_C].\n      exact H_C.\n\n  - intros [H_A_implies_B H_A_implies_C] H_A.\n    Check (H_A_implies_B H_A).\n    Check (H_A_implies_C H_A).\n    Check (conj (H_A_implies_B H_A) (H_A_implies_C H_A)).\n    exact (conj (H_A_implies_B H_A) (H_A_implies_C H_A)).\nQed.\n\n(* ********** *)\n\nProposition disjunction_distributes_over_implication :\n  forall A B C : Prop,\n    ((A \\/ B) -> C) <-> ((A -> C) /\\ (B -> C)).\nProof.\n  intros A B C.\n  split.\n\n  - intros H_A_or_B_implies_C.\n    split.\n\n    + intro H_A.\n      apply H_A_or_B_implies_C.\n      left.\n      exact H_A.\n\n    + intro H_B.\n      apply H_A_or_B_implies_C.\n      right.\n      exact H_B.\n\n  - intros [H_A_implies_C H_B_implies_C] [H_A | H_B].\n\n    + Check (H_A_implies_C H_A).\n      exact (H_A_implies_C H_A).\n\n    + exact (H_B_implies_C H_B).\nQed.\n\n(* ********** *)\n\nProposition contrapositive_of_implication :\n  forall A B : Prop,\n    (A -> B) -> ~B -> ~A.\nProof.\n  intros A B.\n  intros H_A_implies_B H_not_B.\n  Check (modus_tollens A B H_not_B H_A_implies_B).\n  exact (modus_tollens A B H_not_B H_A_implies_B).\nQed.\n\n(* ********** *)\n\nProposition contrapositive_of_contrapositive_of_implication :\n  forall A B : Prop,\n    (~B -> ~A) -> ~~A -> ~~B.\nProof.\n  intros A B.\n  unfold not.\n  intros H_not_B_implies_not_A H_A H_not_B.\n  apply H_A.\n  apply H_not_B_implies_not_A.\n  exact H_not_B.\nQed.\n\n(* ********** *)\n\nProposition double_negation :\n  forall A : Prop,\n    A -> ~~A.\nProof.\n  intros A H_A.\n  unfold not.\n  intros H_A_implies_False.\n  exact (H_A_implies_False H_A).\nQed.\n\n(* ********** *)\n\n(* end of week-02_proving-logical-properties.v *)\n", "meta": {"author": "soedirgo", "repo": "fpp", "sha": "5a43df151c5c8bc3f49d449ffd6f3eac67a16eab", "save_path": "github-repos/coq/soedirgo-fpp", "path": "github-repos/coq/soedirgo-fpp/fpp-5a43df151c5c8bc3f49d449ffd6f3eac67a16eab/w02/week-02_proving-logical-properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173791645582, "lm_q2_score": 0.8670357649558007, "lm_q1q2_score": 0.6963804028318781}}
{"text": "(*|\n#####################################################\nHow to replace a term with some property of the term?\n#####################################################\n\n:Link: https://stackoverflow.com/q/69949496\n|*)\n\n(*|\nQuestion\n********\n\nI apologize if this example is contrived, I am attempting to prove a\nsimilar Lemma with a more complex function than ``list_even``. I wish\nto prove some property about a translation of a list.\n|*)\n\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nDefinition list_even (c : list nat) := map Nat.even c.\n\nLemma list_even_split : forall (c : list nat),\n    c = nil \\/\n      exists c1 c2 b,\n        c = c1 ++ c2\n        /\\ list_even c1 = b :: nil\n        /\\ list_even c = b :: list_even c2.\n\n(*| The proof I came up with is as follows. |*)\n\nProof.\n  induction c.\n  - left. reflexivity.\n  - right. exists [a], c.\n    (* I am stuck here. *)\n    assert (e := Nat.even a).\n\n(*|\nIf I were to prove this by hand, my argument goes as follows.\n\nLet ``c = [a] :: c2``, so ``c1 = [a]``. By ``Nat.Even_or_Odd``, ``a``\nis even or it is odd. If ``a`` is even, then ``b = true`` and so\n\n.. code-block:: coq\n\n    c = [a] ++ c2 /\\\n        list_even [a] = [true] /\\\n        list_even c = true :: list_even c2\n\nIf ``a`` is odd, then ``b = false`` and so\n\n.. code-block:: coq\n\n    c = [a] ++ c2 /\\\n        list_even [a] = [false] /\\\n        list_even c = false :: list_even c2\n\nwhich hold by simplification and reflexivity.\n\nHowever, I do not know how to translate the proof state of\n|*)\n\n    Show. (* .unfold .messages *)\nAbort. (* .none *)\n\n(*|\ninto one which proceeds with the evenness of ``a``.\n\nI also do not believe I need induction for this.\n|*)\n\n(*|\nAnswer\n******\n\nEven-ness isn't actually important to this goal, as it is just a fact\nabout mapping. Either ``c`` is the empty list, or ``c`` is of the form\n``c = x :: xs = [x] ++ xs`` so ``map Nat.even c = Nat.even x ++ map\nNat.even xs``. As such, you could have a proof like\n|*)\n\nLemma list_even_split : forall (c : list nat),\n    c = nil \\/\n      exists c1 c2 b,\n        c = c1 ++ c2\n        /\\ list_even c1 = b :: nil\n        /\\ list_even c = b :: list_even c2.\nProof.\n  intros c.\n  destruct c as [|x xs];\n    [ left; auto\n    | right; exists (x :: nil); do 2 eexists; repeat split; eauto ].\nQed.\n\n(*|\nHowever, in other cases where one needs evenness of a variable you can\nrecord it via\n\n.. code-block:: coq\n\n    destruct (Nat.even x) eqn : NAT_IS_EVEN\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/how-to-replace-a-term-with-some-property-of-the-term.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.8807970889295664, "lm_q1q2_score": 0.6962968120883323}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_lessthancongruence.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_3_6b.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_partnotequalwhole.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_trichotomy2 : \n   forall A B C D, \n   Lt A B C D ->\n   ~ Lt C D A B.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists E, (BetS C E D /\\ Cong C E A B)) by (conclude_def Lt );destruct Tf as [E];spliter.\nassert (Cong A B C E) by (conclude lemma_congruencesymmetric).\nassert (~ Lt C D A B).\n {\n intro.\n assert (Lt C D C E) by (conclude lemma_lessthancongruence).\n let Tf:=fresh in\n assert (Tf:exists F, (BetS C F E /\\ Cong C F C D)) by (conclude_def Lt );destruct Tf as [F];spliter.\n assert (BetS C F D) by (conclude lemma_3_6b).\n assert (~ Cong C F C D) by (conclude lemma_partnotequalwhole).\n contradict.\n }\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_trichotomy2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6962968040311558}}
{"text": "Require Import Bool.\n\nTheorem orb_is_or : (forall a b, Is_true (orb a b) <-> Is_true a \\/ Is_true b).\nProof.\n  intros a b.\n  unfold iff.\n  refine (conj _ _).\n    intros H.\n    case a, b.\n      (* suppose a=true, b=true *)\n      exact (or_introl I).\n      (* suppose a=true, b=false *)\n      exact (or_introl I).\n      (* suppose a=false, b=true *)\n      exact (or_intror I).\n      (* suppose a=false, b=false *)\n      case H.\n  intros H.\n  case a, b.\n    (* suppose a=true, b=true *)\n    exact I.\n    (* suppose a=true, b=true *)\n    exact I.\n    (* suppose a=true, b=true *)\n    exact I.\n    case H.\n      (* false -> false \\/ false *)\n      intros A.\n      case A.\n      (* false -> false \\/ false *)\n      intros B.\n      case B.\nQed.\n\nTheorem andb_is_and : (forall a b, Is_true (andb a b) <-> Is_true a /\\ Is_true b).\nProof.\n  intros a b.\n  unfold iff.\n  refine (conj _ _).\n    intros H.\n    case a, b.\n      (* a=true, b=true *)\n      exact (conj I I).\n      (* a=true, b=false *)\n      case H.\n      (* a=false, b=true *)\n      case H.\n      (* a=false, b=false *)\n      case H.\n    intros H.\n    case a, b.\n      (* a=true, b=true *)\n      exact I.\n      (* a=true, b=false *)\n      destruct H as [ A B ].\n      case B.\n      (* a=false, b=true *)\n      destruct H as [ A B ].\n      case A.\n      (* a=false, b=false *)\n      destruct H as [ A B ].\n      case A.\nQed.\n\nTheorem negb_is_not : (forall a, Is_true (negb a) <-> (~(Is_true a)) ).\nProof.\n  intros a.\n  unfold iff.\n  refine (conj _ _).\n    case a.\n      (* a=true *)\n      simpl.\n      intros H.\n      case H.\n      (* a=false *)\n      simpl.\n      intros H.\n      intros A.\n      case A.\n    case a.\n      (* a=true *)\n      simpl.\n      intros H.\n      case H.\n      exact I.\n      (* a=false *)\n      simpl.\n      intros H.\n      exact I.\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/bools2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6962967903904137}}
{"text": "Require Export FiniteTypes Relation_Definitions ZArith QArith IndexedFamilies.\nRequire Import InfiniteTypes CSB DecidableDec\n               FunctionalExtensionality ProofIrrelevance\n               DependentTypeChoice ClassicalChoice\n               Arith ArithRing.\n\nLocal Close Scope Q_scope.\n\nSet Asymmetric Patterns.\n\nInductive CountableT (X : Type) : Prop :=\n  | intro_nat_injection (f : X -> nat) : injective f -> CountableT X.\n\nLemma CountableT_is_FiniteT_or_countably_infinite (X : Type) :\n  CountableT X -> {FiniteT X} + {exists f : X -> nat, bijective f}.\nProof.\nintros.\napply exclusive_dec.\n- intro.\n  destruct H0 as [? [f ?]].\n  contradiction nat_infinite.\n  apply bij_finite with _ f; trivial.\n  apply bijective_impl_invertible; trivial.\n- destruct (classic (FiniteT X)).\n  + left; trivial.\n  + right.\n    apply infinite_nat_inj in H0.\n    destruct H, H0 as [g].\n    now apply CSB with f g.\nQed.\n\nLemma nat_countable : CountableT nat.\nProof.\napply intro_nat_injection with (fun n => n).\nnow intros [|m] [|n].\nQed.\n\nLemma countable_nat_product: CountableT (nat * nat).\nProof.\npose (sum_1_to_n := fix sum_1_to_n n:nat := match n with\n  | O => O\n  | S m => (sum_1_to_n m) + n\nend).\nexists (fun p:nat*nat => let (m,n):=p in\n  (sum_1_to_n (m+n)) + n).\nassert (forall m n:nat, m<n ->\n  sum_1_to_n m + m < sum_1_to_n n).\n- intros.\n  induction H.\n  + simpl.\n    auto with arith.\n  + apply lt_trans with (sum_1_to_n m0); trivial.\n    assert (sum_1_to_n m0 + 0 < sum_1_to_n m0 + S m0) by auto with arith.\n    assert (sum_1_to_n m0 + 0 = sum_1_to_n m0) by auto with arith.\n    now rewrite H1 in H0.\n- intros [x1 y1] [x2 y2] H0.\n  case (lt_eq_lt_dec (x1+y1) (x2+y2)); intro.\n  + case s; intro.\n    * assert (sum_1_to_n (x1+y1) + y1 < sum_1_to_n (x2+y2) + y2).\n      ** apply le_lt_trans with (sum_1_to_n (x1+y1) + (x1+y1)).\n         *** assert (sum_1_to_n (x1+y1) + (x1+y1) =\n               (sum_1_to_n (x1+y1) + y1) + x1);\n             [ ring | auto with arith ].\n         *** apply lt_le_trans with (sum_1_to_n (x2+y2));\n             [ apply H |];\n             auto with arith.\n      ** rewrite H0 in H1.\n         contradict H1.\n         auto with arith.\n    * assert (y1=y2).\n      ** rewrite e in H0.\n         now apply plus_reg_l in H0.\n      ** f_equal; trivial.\n         rewrite H1, plus_comm, (plus_comm x2 y2) in e.\n         now apply plus_reg_l in e.\n  + assert (sum_1_to_n (x2+y2) + y2 < sum_1_to_n (x1+y1) + y1).\n    * apply le_lt_trans with (sum_1_to_n (x2+y2) + (x2+y2)),\n            lt_le_trans with (sum_1_to_n (x1+y1));\n        auto with arith.\n    * rewrite H0 in H1.\n      contradict H1.\n      auto with arith.\nQed.\n\nLemma countable_sum (X Y : Type) :\n  CountableT X -> CountableT Y -> CountableT (X + Y).\nProof.\nintros [f] [g].\ndestruct countable_nat_product as [h].\nexists (fun s:X+Y => match s with\n  | inl x => h (0, f x)\n  | inr y => h (1, g y)\nend).\nintros [x1|y1] [x2|y2] ?;\n  apply H1 in H2; try discriminate H2;\n  intros; f_equal;\n  apply H + apply H0;\n  now injection H2.\nQed.\n\nLemma countable_product (X Y:Type) :\n  CountableT X -> CountableT Y -> CountableT (X * Y).\nProof.\nintros [f] [g].\npose (fg := fun (p:X*Y) => let (x,y):=p in (f x, g y)).\ndestruct countable_nat_product as [h].\nexists (fun p:X*Y => h (fg p)).\nintros [x1 y1] [x2 y2] H2.\napply H1 in H2.\ninjection H2 as H3 H4.\napply H in H3.\napply H0 in H4.\nnow subst.\nQed.\n\nLemma countable_exp (X Y : Type) :\n  FiniteT X -> CountableT Y -> CountableT (X -> Y).\nProof.\nintros.\ninduction H.\n- exists (fun _ => 0).\n  red; intros.\n  extensionality f.\n  destruct f.\n- destruct (countable_product (T -> Y) Y); trivial.\n  exists (fun g =>\n    f (fun x => g (Some x), g None)).\n  intros g1 g2 ?.\n  apply H1 in H2.\n  extensionality o.\n  destruct o;\n    injection H2;\n    trivial.\n  intros.\n  pose proof (equal_f H4).\n  apply H5.\n- destruct H1, IHFiniteT.\n  exists (fun h => f0 (fun x => h (f x))).\n  intros h1 h2 ?.\n  apply H3 in H4.\n  pose proof (equal_f H4).\n  simpl in H5.\n  extensionality y.\n  rewrite <- (H2 y).\n  apply H5.\nQed.\n\nDefinition Countable {X : Type} (S : Ensemble X) : Prop :=\n  CountableT {x:X | In S x}.\n\nLemma inj_countable {X Y : Type} (f : X -> Y) :\n  CountableT Y -> injective f -> CountableT X.\nProof.\nintros [g] ?.\nexists (fun x:X => g (f x)).\nintros x1 x2 ?.\nauto.\nQed.\n\nLemma surj_countable {X Y : Type} (f : X -> Y) :\n  CountableT X -> surjective f -> CountableT Y.\nProof.\nintros.\ndestruct (choice (fun (y:Y) (x:X) => f x = y)) as [finv]; trivial.\napply inj_countable with finv; trivial.\nintros x1 x2 ?.\ncongruence.\nQed.\n\nLemma countable_downward_closed {X : Type} (S T : Ensemble X) :\n  Countable T -> Included S T -> Countable S.\nProof.\nintros [f H] H0.\nexists (fun x => match x with\n  | exist x0 i => f (exist _ x0 (H0 _ i))\n  end).\nintros [x1] [x2] H1.\napply H in H1.\ninjection H1 as H1.\nnow destruct H1, (proof_irrelevance _ i i0).\nQed.\n\nLemma countable_img {X Y : Type} (f : X -> Y) (S : Ensemble X) :\n  Countable S -> Countable (Im S f).\nProof.\nintros.\nassert (forall x, In S x -> In (Im S f) (f x)) by auto with sets.\npose (fS := fun x =>\n  match x with\n  | exist x0 i => exist _ (f x0) (H0 x0 i)\n  end).\napply surj_countable with fS; trivial.\nintros [? [x i y e]].\nexists (exist _ x i).\nsimpl.\ngeneralize (H0 x i); intro.\ngeneralize (Im_intro X Y S f x i y e); intro.\nnow destruct e, (proof_irrelevance _ i0 i1).\nQed.\n\nLemma countable_type_ensemble  {X : Type} (S : Ensemble X) :\n  CountableT X -> Countable S.\nProof.\nintros.\napply (inj_countable (@proj1_sig _ (In S)) H).\nintros [? ?] [? ?].\nnow apply subset_eq_compat.\nQed.\n\nLemma FiniteT_impl_CountableT (X : Type) :\n  FiniteT X -> CountableT X.\nProof.\nintros.\ninduction H.\n- exists (False_rect nat).\n  now intro.\n- destruct IHFiniteT.\n  exists (fun x => match x with\n    | Some x0 => S (f x0)\n    | None => 0\n  end).\n  intros [x1|] [x2|] H1;\n    injection H1 as H1 + discriminate H1 + trivial.\n  now destruct (H0 _ _ H1).\n- destruct IHFiniteT as [g],\n           H0 as [finv].\n  exists (fun y:Y => g (finv y)).\n  intros y1 y2 ?.\n  apply H1 in H3.\n  congruence.\nQed.\n\nLemma Finite_impl_Countable: forall {X : Type} (S : Ensemble X),\n  Finite _ S -> Countable S.\nProof.\nintros.\nnow apply FiniteT_impl_CountableT, Finite_ens_type.\nQed.\n\nLemma positive_countable: CountableT positive.\nProof.\nexists nat_of_P.\nintros n1 n2 ?.\nnow apply nat_of_P_inj.\nQed.\n\nLemma Z_countable: CountableT Z.\nProof.\ndestruct countable_nat_product as [f],\n         positive_countable as [g].\nexists (fun n:Z => match n with\n  | Z0 => f (0, 0)\n  | Zpos p => f (1, g p)\n  | Zneg p => f (2, g p)\nend).\nintros [|p1|p1] [|p2|p2] H1;\n  apply H in H1;\n  discriminate H1 + trivial;\n  injection H1 as H1; f_equal; auto.\nQed.\n\nLemma Q_countable: CountableT Q.\nProof.\ndestruct countable_nat_product as [f],\n         positive_countable as [g],\n         Z_countable as [h].\nexists (fun q:Q => match q with\n  n # d => f (h n, g d)\nend)%Q.\nintros [n1 d1] [n2 d2] ?.\napply H in H2.\ninjection H2 as H2.\nf_equal; auto.\nQed.\n\nLemma countable_union: forall {X A:Type}\n  (F:IndexedFamily A X), CountableT A ->\n    (forall a:A, Countable (F a)) ->\n    Countable (IndexedUnion F).\nProof.\nintros.\ndestruct (choice_on_dependent_type (fun (a:A)\n                               (f:{x:X | In (F a) x} -> nat) =>\n  injective f)) as [choice_fun_inj].\n- intro.\n  destruct (H0 a).\n  now exists f.\n- destruct (choice (fun (x:{x:X | In (IndexedUnion F) x}) (a:A) =>\n    In (F a) (proj1_sig x))) as [choice_fun_a].\n  + destruct x as [x [a]].\n    now exists a.\n  + destruct countable_nat_product as [g],\n             H as [h].\n    exists (fun x:{x:X | In (IndexedUnion F) x} =>\n      g (h (choice_fun_a x), choice_fun_inj _ (exist _ _ (H2 x)))).\n    intros x1 x2 H4.\n    apply H3 in H4.\n    injection H4 as H5 H6.\n    apply H in H5.\n    revert H6.\n    generalize (H2 x1), (H2 x2).\n    rewrite H5.\n    intros.\n    apply H1 in H6.\n    injection H6.\n    destruct x1, x2.\n    apply subset_eq_compat.\nQed.\n", "meta": {"author": "coq-community", "repo": "zorns-lemma", "sha": "aaf46b0c5f7857ce9211cbaaf36f184ca810e0e8", "save_path": "github-repos/coq/coq-community-zorns-lemma", "path": "github-repos/coq/coq-community-zorns-lemma/zorns-lemma-aaf46b0c5f7857ce9211cbaaf36f184ca810e0e8/CountableTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.6962961542926818}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type :=   Nil : lst | Cons : natural -> lst -> lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint len (len_arg0 : lst) : natural\n           := match len_arg0 with\n              | Nil => Zero\n              | Cons x y => Succ (len y)\n              end.\n\nFixpoint rotate (rotate_arg0 : natural) (rotate_arg1 : lst) : lst\n           := match rotate_arg0, rotate_arg1 with\n              | Zero, x => x\n              | Succ n, Nil => Nil\n              | Succ n, Cons y x => rotate n (append x (Cons y Nil))\n              end.\n\nLemma append_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 rotate_len_append : forall (x y : lst), rotate (len x) (append x y) = append y x.\nProof.\n   intro.\n   induction x.\n   - intros.  simpl. lfind.  reflexivity. \nAdmitted.\n\nTheorem rotate_len : forall (x : lst), eq (rotate (len x) x) x.\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite rotate_len_append. 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_goal32_rotate_len_append_50_append_nil/goal32.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6962961305782418}}
{"text": "(*Autor: David Felipe Hernandez Chiapa\nProyecto Final de Semantica y Verificacion\n*)\n\nRequire Import Nat.\n\nRequire Import List.\nRequire Import Utf8.\n\nExport ListNotations.\n\nDefinition key := nat.\n\nInductive color := Red | Black.\n\nSection RBTree.\nVariable V : Type.\nVariable default: V.\n\n Inductive Tree : Type :=\n | E : Tree \n | T: color → Tree → key → V → Tree → Tree.\n\n\n\n\nFixpoint lookup (x: key) (t : Tree) : V :=\n  match t with\n  | E => default\n  | T _ tl k v tr => if x <? k then lookup x tl \n                         else if k <? x then lookup x tr\n                         else v\n  end.\n\nDefinition balance rb t1 k vk t2 :=\n match rb with \n | Black => match t1 with \n        | T Red (T Red a x vx b) y vy c => T Red (T Black a x vx b) y vy (T Black c k vk t2)\n        | T Red a x vx (T Red b y vy c) => T Red (T Black a x vx b) y vy (T Black c k vk t2)\n        | _ => match t2 with \n            | T Red (T Red b y vy c) z vz d => T Red (T Black t1 k vk b) y vy (T Black c z vz d)\n            | T Red b y vy (T Red c z vz d) => T Red (T Black t1 k vk b) y vy (T Black c z vz d)\n            | _ => T Black t1 k vk t2\n            end\n        end\n | Red => T Red t1 k vk t2\n end.\n\nDefinition makeBlack t := \n  match t with \n  | E => E\n  | T _ a x vx b => T Black a x vx b\n  end.\n\nFixpoint ins x vx t :=\n match t with \n | E => T Red E x vx E\n | T c a y vy b => if ltb x y then balance c (ins x vx a) y vy b\n                        else if ltb y x then balance c a y vy (ins x vx b)\n                        else T c a x vx b\n end.\n\nDefinition insert x vx t := makeBlack (ins x vx t).\n\n\n\nInductive SearchTreeAux : nat → Tree → nat → Prop :=\n| ST_E : ∀ min max, min ≤ max → SearchTreeAux min E max\n| ST_T: ∀ min c l k v r max,\n    SearchTreeAux min l k →\n    SearchTreeAux (S k)  r max →\n    SearchTreeAux min (T c l k v r) max.\n\nInductive isSearchTree: Tree → Prop :=\n| ST_intro: ∀ t min max, SearchTreeAux min t max → isSearchTree t.\n\nTheorem SearchTreeCorrectness: ∀ col lt rt k v min max, \n                                SearchTreeAux min lt k ->\n                                SearchTreeAux (S k) rt max ->\n                                SearchTreeAux min (balance col lt k v rt) max.\nProof.\nintros.\nunfold balance.\ndestruct col.\n*\nconstructor;trivial.\n*\ndestruct lt;destruct rt.\nconstructor;trivial.\ndestruct c.\ndestruct rt1;destruct rt2.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H0;inversion H8;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H0;inversion H8;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c.\ndestruct lt1;destruct lt2.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\ndestruct c0.\nconstructor;constructor;inversion H;inversion H9;trivial.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c;destruct lt1;destruct lt2;destruct c0;destruct rt1;destruct rt2.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H0;inversion H8;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H0;inversion H8;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H9;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H9;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H8;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H9;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H8;trivial.\ndestruct c1.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H8;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H8;trivial.\ndestruct c1.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\ndestruct c1.\nconstructor;constructor;inversion H;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\ndestruct c1.\nconstructor;constructor;inversion H;inversion H9;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\ndestruct c1.\nconstructor;constructor;inversion H;inversion H9;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H8;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\ndestruct c1.\nconstructor;constructor;inversion H;inversion H9;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H8;trivial.\ndestruct c2.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\ndestruct c1.\nconstructor;constructor;inversion H;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\ndestruct c1.\nconstructor;constructor;inversion H;inversion H9;trivial.\ndestruct c0.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\ndestruct c1.\nconstructor;constructor;inversion H;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H;inversion H8;trivial.\ndestruct c1.\nconstructor;constructor;inversion H;inversion H9;trivial.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H0;inversion H8;trivial.\nconstructor;trivial.\ndestruct c.\nconstructor;constructor;inversion H0;inversion H8;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H8;trivial.\nconstructor;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H8;trivial.\ndestruct c1.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H8;trivial.\nconstructor;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H8;trivial.\ndestruct c1.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H8;trivial.\nconstructor;trivial.\ndestruct c0.\nconstructor;constructor;inversion H0;inversion H8;trivial.\ndestruct c2.\nconstructor;constructor;inversion H0;inversion H9;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\nQed.\n\nInductive isRB : Tree → color → nat → Prop :=\n | IsRB_leaf: ∀ c, isRB E c 0\n | IsRB_r: ∀ tl k kv tr n,\n          isRB tl Red n →\n          isRB tr Red n →\n          isRB (T Red tl k kv tr) Black n\n | IsRB_b: ∀ c tl k kv tr n,\n          isRB tl Black n →\n          isRB tr Black n →\n          isRB (T Black tl k kv tr) c (S n).\n\n\nLemma red_to_black : ∀ t n, isRB t Red n -> isRB t Black n.\nProof.\nintros.\ndestruct H;constructor;trivial.\nQed.\nHint Resolve red_to_black.\n\n\n\nInductive nearRB : Tree → nat → Prop :=\n| nrRB_r: ∀ tl k kv tr n,\n         isRB tl Black n →\n         isRB tr Black n →\n         nearRB (T Red tl k kv tr) n\n| nrRB_b: ∀ tl k kv tr n,\n         isRB tl Black n →\n         isRB tr Black n →\n         nearRB (T Black tl k kv tr) (S n).\n\nLemma insAux : ∀ k x t1 n,isRB (ins k x t1) Black n -> isRB (ins k x t1) Red n.\nAdmitted.\n\nTheorem ins_isRB:\n  ∀ k x t n, \n    (isRB t Red n → nearRB (ins k x t) n) ∧\n    (isRB t Black n → isRB (ins k x t) Black n).\nProof.\ninduction t; intro n; simpl; split; intros; inversion H; repeat constructor; auto.\n*\ndestruct (IHt1 n0); clear IHt1.\ndestruct (IHt2 n0); clear IHt2.\nspecialize (H10 H7).\nspecialize (H12 H8).\nunfold balance.\ndestruct (k <? k0).\ndestruct (ins k x t1).\ndestruct t2.\nconstructor;trivial.\ndestruct c1.\ndestruct t2_1.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19;auto.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H18;auto.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19;auto.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\ndestruct t3.\ndestruct t4.\ndestruct t2.\nconstructor;trivial.\ndestruct c1.\ndestruct t2_1.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19;auto.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H18;auto.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19;auto.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H10;inversion H19;auto.\ndestruct t2.\nconstructor;trivial.\ndestruct c1.\ndestruct t2_1.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19;auto.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H18;auto.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19;auto.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H10;inversion H18;auto.\ndestruct t4.\ndestruct t2.\nconstructor;trivial.\ndestruct c1.\ndestruct t2_1.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19;auto.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H18;auto.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19;auto.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H10;inversion H19;auto.\ndestruct t2.\nconstructor;trivial.\ndestruct c1.\ndestruct t2_1.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19;auto.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H18;auto.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19;auto.\nconstructor;trivial.\nconstructor;trivial.\ndestruct t2.\nconstructor;trivial.\ndestruct c1.\ndestruct t2_1.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19;auto.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H18;auto.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19;auto.\nconstructor;trivial.\nconstructor;trivial.\ndestruct (k0 <? k).\ndestruct t1.\ndestruct (ins k x t2).\nconstructor;trivial.\ndestruct c1.\ndestruct t1.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H18.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\ndestruct t1_1.\ndestruct t1_2.\ndestruct (ins k x t2).\nconstructor;trivial.\ndestruct c1.\ndestruct t1.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H18.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H7;inversion H19;trivial.\ndestruct (ins k x t2).\nconstructor;trivial.\ndestruct c1.\ndestruct t1.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H18.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H7;inversion H18;trivial.\ndestruct t1_2. \ndestruct (ins k x t2).\nconstructor;trivial.\ndestruct c1.\ndestruct t1.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H18.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H7;inversion H19;trivial.\ndestruct (ins k x t2).\nconstructor;trivial.\ndestruct c1.\ndestruct t1.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H18.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct (ins k x t2).\nconstructor;trivial.\ndestruct c1.\ndestruct t1.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H18.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\n*\ndestruct (IHt1 n); clear IHt1.\ndestruct (IHt2 n); clear IHt2.\nassert (A := H6).\nassert (B := H7).\napply red_to_black in H6.\napply red_to_black in H7.\nspecialize (H11 H7).\nspecialize (H9 H6).\nunfold balance.\ndestruct (k0 <? k);destruct (k <? k0);constructor;trivial.\napply insAux;trivial.\napply insAux;trivial.\napply insAux;trivial.\n*\ndestruct (IHt1 n0); clear IHt1.\ndestruct (IHt2 n0); clear IHt2.\nspecialize (H10 H7).\nspecialize (H12 H8).\nunfold balance.\ndestruct (k <? k0).\ndestruct (ins k x t1).\ndestruct t2.\nconstructor;trivial.\ndestruct c1.\ndestruct t2_1.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H18.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\ndestruct t3.\ndestruct t4.\ndestruct t2.\nconstructor;trivial.\ndestruct c1.\ndestruct t2_1.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H18.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H10;inversion H19.\ndestruct t2.\nconstructor;trivial.\ndestruct c1.\ndestruct t2_1.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H18.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H10;inversion H18.\ndestruct t4.\ndestruct t2.\nconstructor;trivial.\ndestruct c1.\ndestruct t2_1.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H18.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H10;inversion H19.\ndestruct t2.\nconstructor;trivial.\ndestruct c1.\ndestruct t2_1.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H18.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct t2.\nconstructor;trivial.\ndestruct c1.\ndestruct t2_1.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H18.\ndestruct t2_2.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H8;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct (k0 <? k).\ndestruct t1.\ndestruct (ins k x t2).\nconstructor;trivial.\ndestruct c1.\ndestruct t1.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H18.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\ndestruct t1_1.\ndestruct t1_2.\ndestruct (ins k x t2).\nconstructor;trivial.\ndestruct c1.\ndestruct t1.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H18.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H7;inversion H19.\ndestruct (ins k x t2).\nconstructor;trivial.\ndestruct c1.\ndestruct t1.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H18.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H7;inversion H18.\ndestruct t1_2.\ndestruct (ins k x t2).\nconstructor;trivial.\ndestruct c1.\ndestruct t1.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H18.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H7;inversion H19.\ndestruct (ins k x t2).\nconstructor;trivial.\ndestruct c1.\ndestruct t1.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H18.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\ndestruct (ins k x t2).\nconstructor;trivial.\ndestruct c1.\ndestruct t1.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H18.\ndestruct t3.\nconstructor;trivial.\ndestruct c1.\nconstructor;constructor;inversion H12;inversion H19.\nconstructor;trivial.\nconstructor;trivial.\nconstructor;trivial.\nQed.\n\n\nEnd RBTree.\n\n\n\n\n\n\n\n\n\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": "DavidFHCh", "repo": "Tesis-FTW", "sha": "f84ab8eb92f3984e973ce6a441262d9a8a62e9b0", "save_path": "github-repos/coq/DavidFHCh-Tesis-FTW", "path": "github-repos/coq/DavidFHCh-Tesis-FTW/Tesis-FTW-f84ab8eb92f3984e973ce6a441262d9a8a62e9b0/tesis/ProyectoSemantica.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6962319366530236}}
{"text": "Require Import Arith Euclid Omega.\n\nDefinition is_mod (a b r : nat) :=\n  exists q, r < b /\\ q * b + r = a.\n\nTheorem a2mod3_cases : forall a, is_mod (a*a) 3 0 \\/ is_mod (a*a) 3 1.\nProof.\n  intros.\n  assert (3 > 0) by auto with arith.\n  destruct (modulo _ H a) as [r [q [Hq Hr]]].\n  destruct r.\n    left.\n    exists (q * 3 * q).\n    rewrite Hq.\n    repeat rewrite <- plus_n_O.\n    rewrite mult_assoc.\n    now auto.\n  destruct r.\n    right.\n    rewrite Hq.\n    exists (2 * q + 3 * q * q).\n    repeat rewrite <- (mult_comm 3).\n    simpl.\n    repeat rewrite <- plus_n_O.\n    repeat rewrite mult_plus_distr_l.\n    repeat rewrite mult_plus_distr_r.\n    omega.\n  destruct r.\n    right.\n    exists (1 + 4 * q + 3 * q * q).\n    rewrite Hq.\n    repeat rewrite <- (mult_comm 3).\n    simpl.\n    repeat rewrite <- plus_n_O.\n    repeat rewrite mult_plus_distr_l.\n    repeat rewrite mult_plus_distr_r.\n    omega.\n  repeat apply lt_S_n in Hr.\n  elim (lt_n_O _ Hr).\nQed.\n\nDefinition div3 n := exists q, 3 * q = n.\n\nLemma div3_square : forall a, div3 (a * a) -> div3 a.\nProof.\n  intros.\n  assert (3 > 0) by auto with arith.\n  destruct (modulo _ H0 a) as [r [q [Hq Hr]]].\n  destruct r.\n    exists q.\n    omega.\n  destruct r.\n    destruct H as [q' Hq'].\n    rewrite Hq in Hq'.\n    repeat rewrite mult_plus_distr_l in *.\n    repeat rewrite mult_plus_distr_r in *.\n    rewrite <- (mult_comm 1) in Hq'.\n    rewrite (mult_comm 3) in Hq'.\n    simpl in Hq'.\n    repeat rewrite <- plus_n_O in Hq'.\n    rewrite plus_assoc in Hq'.\n    repeat rewrite mult_assoc in Hq'.\n    repeat rewrite <- mult_plus_distr_r in Hq'.\n    apply plus_minus in Hq'.\n    rewrite <- mult_minus_distr_r in Hq'.\n    destruct (q' - (q * 3 * q + q + q)).\n      discriminate.\n    simpl in Hq'.\n    inversion Hq'.\n  destruct r.\n    destruct H as [q' Hq'].\n    rewrite Hq in Hq'.\n    repeat rewrite mult_plus_distr_l in *.\n    repeat rewrite mult_plus_distr_r in *.\n    rewrite (mult_assoc 2), (mult_comm 2) in Hq'.\n    rewrite <- (mult_assoc q 3 2) in Hq'.\n    repeat rewrite (mult_comm 3) in Hq'.\n    repeat rewrite mult_assoc in Hq'.\n    simpl in Hq'.\n    change 4 with (1*3 + 1) in Hq'.\n    repeat rewrite plus_assoc in Hq'.\n    repeat rewrite <- mult_plus_distr_r in Hq'.\n    apply plus_minus in Hq'.\n    rewrite <- mult_minus_distr_r in Hq'.\n    destruct (q' - (q * 3 * q + q * 2 + q * 2 + 1)).\n      discriminate.\n    simpl in Hq'.\n    inversion Hq'.\n  repeat apply lt_S_n in Hr.\n  elim (lt_n_O _ Hr).\nQed.\n    \nTheorem a_b_c_div3 : forall a b c,\n  a * a + b * b = 3 * c * c -> div3 a /\\ div3 b /\\ div3 c.\nProof.\n  intros.\n  destruct (a2mod3_cases a), (a2mod3_cases b).\n  + assert (div3 a).\n      destruct H0 as [q [Hr Hq]].\n      rewrite <- plus_n_O in Hq.\n      apply div3_square.\n      exists q.\n      now rewrite mult_comm.\n    assert (div3 b).\n      destruct H1 as [q [Hr Hq]].\n      rewrite <- plus_n_O in Hq.\n      apply div3_square.\n      exists q.\n      now rewrite mult_comm.\n    assert (div3 c).\n      apply div3_square.\n      destruct H2 as [qa Ha].\n      destruct H3 as [qb Hb].\n      rewrite <-Ha, <-Hb in H.\n      repeat rewrite mult_assoc in H.\n      repeat rewrite <- (mult_comm 3) in H.\n      repeat rewrite <- mult_assoc in H.\n      rewrite <- mult_plus_distr_l in H.\n      assert (3 * (qa * qa) + 3 * (qb * qb) = c * c) by omega.\n      rewrite <- mult_plus_distr_l in H2.\n      esplit; eauto.\n    now auto.\n  + destruct H0 as [qa [Hra Hqa]].\n    destruct H1 as [qb [Hrb Hqb]].\n    rewrite <- Hqa, <- Hqb in H.\n    rewrite <- mult_assoc, (mult_comm 3) in H.\n    rewrite <- (plus_comm 0) in H.\n    simpl in H.\n    rewrite plus_assoc in H.\n    apply eq_sym in H.\n    apply plus_minus in H.\n    rewrite <- mult_plus_distr_r, <- mult_minus_distr_r in H.\n    destruct (c * c - (qa + qb)).\n      discriminate.\n    simpl in H.\n    inversion H.\n  + destruct H0 as [qa [Hra Hqa]].\n    destruct H1 as [qb [Hrb Hqb]].\n    rewrite <- Hqa, <- Hqb in H.\n    rewrite <- mult_assoc, (mult_comm 3) in H.\n    rewrite <- (plus_comm 0) in H.\n    simpl in H.\n    rewrite <- plus_assoc, (plus_comm 1 (qb * 3)), plus_assoc in H.\n    apply eq_sym, plus_minus in H.\n    rewrite <- mult_plus_distr_r, <- mult_minus_distr_r in H.\n    destruct (c * c - (qa + qb)).\n      discriminate.\n    simpl in H.\n    inversion H.\n  + destruct H0 as [qa [Hra Hqa]].\n    destruct H1 as [qb [Hrb Hqb]].\n    rewrite <- Hqa, <- Hqb in H.\n    rewrite <- mult_assoc, (mult_comm 3) in H.\n    rewrite <- plus_assoc, (plus_comm 1 (qb * 3 + 1)) in H.\n    repeat rewrite plus_assoc in H.\n    rewrite <- plus_assoc in H.\n    apply eq_sym, plus_minus in H.\n    rewrite <- mult_plus_distr_r, <- mult_minus_distr_r in H.\n    destruct (c * c - (qa + qb)).\n      discriminate.\n    simpl in H.\n    inversion H.\nQed.\n\nRequire Import Wf_nat.\n\nTheorem a_b_c_0 : forall a b c,\n  a * a + b * b = 3 * c * c -> a = 0 /\\ b = 0 /\\ c = 0.\nProof.\n  intros a b c; revert a b.\n  induction c using lt_wf_ind.\n  intros a b Habc.\n  destruct c.\n    destruct a; try discriminate.\n    destruct b; try discriminate.\n    now auto.\n  destruct (a_b_c_div3 _ _ _ Habc) as [[qa Ha] [[qb Hb] [qc Hc]]].\n  rewrite <- Ha, <- Hb, <- Hc in Habc |- *.\n  assert (qc < S c) by omega.\n  destruct (H qc H0 qa qb) as [Hqa [Hqb Hqc]].\n    repeat rewrite <- mult_assoc in Habc.\n    rewrite (mult_comm qa), (mult_comm qb), (mult_comm qc) in Habc.\n    repeat rewrite mult_assoc in Habc.\n    simpl (3*3) in Habc.\n    repeat rewrite <- mult_assoc in Habc.\n    rewrite (mult_assoc 3 qc qc) in Habc.\n    omega.\n  subst.\n  now auto.\nQed.\n", "meta": {"author": "KyushuUniversityMathematics", "repo": "TPP2014", "sha": "8439769862a9619cdb4e0af1597d447c7cca2325", "save_path": "github-repos/coq/KyushuUniversityMathematics-TPP2014", "path": "github-repos/coq/KyushuUniversityMathematics-TPP2014/TPP2014-8439769862a9619cdb4e0af1597d447c7cca2325/JacquesGarrigue/tpp2014.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6962319181060802}}
{"text": "Require Import List Min Arith Div2.\n\nNotation \"n .+1\" := (S n)(at level 2, left associativity, format \"n .+1\"): nat_scope.\n\n(* Minus *)\n\nLemma minus_match k1 k2: match k2 - k1 with O => k2 <= k1 | S _ => k1 < k2 end.\nProof.\ngeneralize k2; clear k2.\ninduction k1 as [| k1 IH]; intros [| k2]; simpl; auto with arith.\ngeneralize (IH k2); case minus; auto with arith.\nQed.\n\n\n(* The exponential function *)\n\nSection Exp.\n\nFixpoint exp (n m: nat) {struct m} : nat := \n  match m with O => 1 | 1 => n | (S m1) => n * exp n m1 end.\n\nLemma exp0 n: exp n 0 = 1.\nProof. auto. Qed.\n\nLemma expS n m: exp n (S m) = n * exp n m.\nProof. \ndestruct m; simpl; auto; rewrite <- mult_n_Sm; rewrite <- mult_n_O; auto.\nQed.\n\nEnd Exp.\n\n(* Some iterators on list *)\n\nSection Fold2.\n\nVariable A B C: Type.\nVariable f: A -> B -> C -> C.\n\nDefinition dhead a (l : list A) :=\n  match l with nil => a | b :: _ => b end.\n\nFixpoint fold2 (l1: list A) (l2: list B) (c: C) {struct l1}: C :=\n  match l1, l2 with\n    a::l3, b::l4 => fold2 l3 l4 (f a b c)\n  | _, _ => c\n  end.\n\nVariable g: A -> B -> C.\n\nFixpoint map2 (l1: list A) (l2: list B) {struct l1}: list C :=\n  match l1, l2 with\n    a::l3, b::l4 => (g a b)::map2 l3 l4\n  | _, _ => nil\n  end.\n\nLemma map2_length l1 l2:\n  length (map2 l1 l2) = min (length l1) (length l2).\nProof.\ngeneralize l2; clear l2.\ninduction l1 as [| a1 l1 IH]; intros [| a2 l2]; simpl; auto.\nQed.\n\n\nFixpoint dmap2 (a : A) (l1: list A) (l2: list B) {struct l2}: list C :=\n  match l1, l2 with\n    a1::l3, b1 :: l4 => g a1 b1 :: dmap2 a l3 l4\n  |    nil, b1 :: l4 =>  g a b1 :: dmap2 a nil l4\n  | _, _ => nil\n  end.\n\nEnd Fold2.\nArguments dhead[A].\nArguments fold2[A B C].\nArguments map2[A B C].\nArguments dmap2[A B C].\n\nSection Perm.\n\nVariable A: Type.\n\nInductive perm: list A -> list A -> Prop :=\n  perm_id: forall l, perm l l\n| perm_swap: forall a b l,  perm (a::b::l) (b::a::l)\n| perm_skip: forall a l1 l2,  perm l1 l2 -> perm (a::l1) (a::l2)\n| perm_trans: forall l1 l2 l3, perm l1 l2 -> perm l2 l3 -> perm l1 l3.\n\nLemma perm_sym l1 l2: perm l1 l2 -> perm l2 l1.\nProof.\nintros HH; elim HH; simpl; auto.\nintros; apply perm_id; auto.\nintros; apply perm_swap.\nintros; apply perm_skip; auto.\nintros l3 l4 l5 H1 H2 H3 H4; \n  apply perm_trans with (1 := H4); auto.\nQed.\n\n\nLemma perm_cons_app a l1 l2: perm ((a:: l1) ++ l2) (l1 ++ (a:: l2)).\nProof.\ngeneralize l2; clear l2; induction l1 as [| b l1 IH]; auto.\nintros l2; apply perm_id.\nintros l2; apply perm_trans with (1 := perm_swap a b (l1 ++ l2)).\nsimpl; apply perm_skip; auto.\napply (IH l2).\nQed.\n\nLemma perm_length l1 l2: perm l1 l2 -> length l1 = length l2.\nProof.\nintros HH; elim HH; simpl; auto.\nintros l3 l4 l5 H1 H2 H3 H4; rewrite H2; auto.\nQed.\n\nLemma perm_in a l1 l2: perm l1 l2 -> In a l1 -> In a l2.\nProof.\nintros H; generalize a; elim H; clear a l1 l2 H; auto with datatypes.\nsimpl; intros a b l c [H1 | [H1 | H1]]; subst; auto.\nsimpl; intros a l1 l2 H IH c [H1 | H1]; subst; auto.\nQed.\n\nLemma perm_in_inv a l1: In a l1 -> exists l2, perm l1 (a:: l2).\nProof.\ninduction l1 as [| b l1 IH]; simpl; intros HH; case HH; auto.\nintros HH1; subst; exists l1; apply perm_id.\nintros HH1; case IH; auto.\nintros l2 Hl2; exists (b::l2).\napply perm_trans with (b::a::l2).\napply perm_skip; auto.\napply perm_swap; auto.\nQed.\n\nLemma perm_incl_r l1 l2 l3: perm l1 l2 -> incl l1 l3 -> incl l2 l3.\nProof.\nintros H; generalize l3; elim H; clear l3 l1 l2 H; auto with datatypes.\nintros a b l1 l2 H x; simpl; intros [H1 | [H1 | H1]]; subst; apply H;\n   auto with datatypes.\nintros a l1 l2 Hp IH l3 Hi x; simpl; intros [H1 | H1]; subst.\napply Hi; auto with datatypes.\napply IH; auto with datatypes.\nintros y Hy; apply Hi; auto with datatypes.\nQed.\n\nLemma perm_incl_l l1 l2 l3: perm l1 l2 -> incl l3 l1 -> incl l3 l2.\nProof.\nintros H; generalize l3; elim H; clear l3 l1 l2 H; auto with datatypes.\nintros a b l1 l2 H x Hx.\ngeneralize (H _ Hx); simpl; intros [H1 | [H1 | H1]]; subst; auto.\nintros a l1 l2 Hp IH l3 Hi x Hx.\ngeneralize (Hi _ Hx); simpl; intros [H1 | H1]; subst; auto.\nright; apply perm_in with (1 := Hp); auto.\nQed.\n\nEnd Perm.\n\nArguments perm[A].\n\nSection Uniq.\n\nVariable A: Type.\n\nInductive uniq: list A -> Prop :=\n  uniq_nil: uniq nil\n| uniq_cons: forall a l, ~ In a l -> uniq l -> uniq (a::l).\n\nLemma uniq_perm l1 l2: perm l1 l2 -> uniq l1 -> uniq l2.\nProof.\nintros H; elim H; auto.\nintros a b l HH; inversion_clear HH as [| aa bb Hi HH1].\ninversion_clear HH1 as [| aa bb Hi1 HH2].\nrepeat apply uniq_cons; auto with datatypes.\nsimpl; intros [H1 | H1]; subst; auto.\ncase Hi; auto with datatypes.\nintros a l3 l4 H1 IH HH.\ninversion_clear HH as [| aa bb Hi HH1].\napply uniq_cons; auto.\nintros HH2; case Hi; apply perm_in with (1 := perm_sym _ _ _ H1); auto.\nQed.\n\nLemma uniq_cons_inv a l: uniq (a::l) -> uniq l.\nProof.\nintros HH; inversion HH; auto.\nQed.\n\nLemma uniq_app_inv_l l1 l2: uniq (l1 ++ l2) -> uniq l1.\nProof.\ngeneralize l1; induction l2 as [| a l2 IH]; clear l1; intros l1.\nrewrite <-app_nil_end; auto.\nintros HH; apply uniq_cons_inv with a.\napply IH.\napply uniq_perm with (2 := HH).\napply perm_sym; apply perm_cons_app.\nQed.\n\nLemma uniq_app_inv_r l1 l2: uniq (l1 ++ l2) -> uniq l2.\nProof.\ngeneralize l2; clear l2; induction l1 as [| a l1 IH]; auto.\nintros l2 Hl2. \napply uniq_cons_inv with a.\napply IH.\napply uniq_perm with (2 := Hl2).\napply perm_cons_app.\nQed.\n\nLemma perm_incl_inv l1 l2: \n  uniq l1 -> uniq l2 -> incl l1 l2 -> exists l3, perm l2 (l1 ++ l3).\nProof.\ngeneralize l2; clear l2; induction l1 as [| a l1 IH]; intros l2.\nintros; exists l2; apply perm_id.\nintros Hu1 Hu2 Hi.\nassert (H1: In a l2).\napply Hi; auto with datatypes.\ncase perm_in_inv with (1 := H1).\nintros l3 Hl3.\ncase (IH l3); auto.\napply uniq_cons_inv with a; auto.\napply uniq_cons_inv with a; auto.\napply uniq_perm with (1 := Hl3); auto.\nintros x Hx.\nassert (H2: In x (a::l3)).\napply perm_in with (1 := Hl3).\napply Hi; auto with datatypes.\nsimpl in H2; case H2; intros HH; subst; auto.\ninversion_clear Hu1 as [| aa bb HH1 HH2].\ncase HH1; auto.\nintros l4 Hl4.\nexists l4.\napply perm_trans with (1 := Hl3).\nsimpl; apply perm_skip; auto.\nQed.\n\nEnd Uniq.\n\nLemma list_split (A: Type) n1 n2 (l: list A):\n length l = n1 + n2 ->\n   exists l1, exists l2, l = l1 ++ l2 /\\ length l1 = n1 /\\ length l2 = n2.\nProof.\ngeneralize n2 l; clear n2 l; induction n1 as [| n1 IH].\nintros n2 l Hl; exists nil; exists l; auto.\nintros n2 [| a l] H; try discriminate.\ncase (IH n2 l); auto.\nintros l1 (l2, (H1, (H2, H3))).\nexists (a::l1); exists l2; repeat split; subst; simpl; auto.\nQed.\n\nLemma length_split (A B: Type) (a b: A) (lk: list B) l1 l2:\n length lk = length ((a:: l1) ++ b :: l2)%list ->\n exists k1, exists k2, exists lk1, exists lk2,\n lk = ((k1::lk1) ++ k2::lk2)%list /\\ length lk1 = length l1 /\\ length lk2 = length l2.\nProof.\ndestruct lk as [| a1 lk].\nintros; discriminate.\nsimpl; intros HH; injection HH; clear HH; intros HH.\nassert (H1:  exists k2, exists lk1, exists lk2,\n lk = (lk1 ++ k2::lk2)%list /\\ length lk1 = length l1 /\\ length lk2 = length l2).\ngeneralize l1 HH; clear HH; induction lk as [| a2 lk IH]; clear l1;\n  intros [| b1 l1]; try (intros; discriminate).\nsimpl; intros HH; injection HH; clear HH; intros HH.\nexists a2; exists (@nil _); exists lk; repeat split; auto.\nsimpl; intros HH; injection HH; clear HH; intros HH.\ncase (IH _ HH); auto.\nintros k1 (lk1, (lk2, (H1lk1, (H2lk1, H3lk1)))).\nexists k1; exists (a2::lk1); exists lk2; simpl; repeat split; auto.\nrewrite H1lk1; auto.\ncase H1; intros k2 (lk1, (lk2, (H1lk, (H2lk, H3lk)))).\nexists a1; exists k2; exists lk1; exists lk2; repeat split; auto.\nrewrite H1lk; auto.\nQed.\n\nLemma list_app_inj (A: Type) (l1 l2 l3 l4: list A):\n length l1 = length l3 -> l1 ++ l2 = l3 ++ l4 -> l1 = l3 /\\ l2 = l4.\nProof.\ngeneralize l2 l3 l4; clear l2 l3 l4; induction l1 as [| x1 l1 IH].\nintros  l2 [| x3 l3] l4 H1 H2; try discriminate; auto.\nintros l2 [| x3 l3] l4 H1 H2; try discriminate.\ninjection H2; intros; subst; auto.\ncase (IH l2 l3 l4); auto; intros; subst; auto.\nQed.\n\nLemma list_case (A:Type) (l: list A): l = nil \\/ l <> nil.\ndestruct l as [|a l]; simpl; auto.\nright; intros HH; discriminate.\nQed.\n\nLemma list_dec (A: Type) (P: A -> Prop) l:\n (forall x, P x \\/ ~ P x) -> (forall x, In x l -> P x) \\/ (exists x, In x l /\\ ~ P x).\nProof.\nintros Pdec.\ninduction l as [| a l IH].\nleft; intros x [].\ncase (Pdec a); intros H.\n2: right; exists a; auto with datatypes.\ncase IH.\nsimpl; intros H1; left; intros x [Hx|Hx]; subst; auto.\nintros (x,(H1x,H2x)); right; exists x; auto with datatypes.\nQed.\n\n\nArguments uniq[A].\n\n(* Georges' trick for easy case analysis *)\n\nInductive eq_Spec (A: Type) (x y: A): bool -> Prop :=\n |eq_Spect:  x = y -> eq_Spec A x y true\n |eq_Specf: x <> y -> eq_Spec A x y false.\n\nArguments eq_Spec[A].\n\n(** Binomial Coefficient defined using Pascal's triangle *)\nFixpoint bin (a b : nat) {struct a} : nat :=\n match a, b with\n   _, O => 1\n  | O, S b' => 0\n  | S a', S b' => bin a' (S b') + bin a' b'\n end.\n\n(** Basic properties of binomial coefficients *) \nLemma bin_0: forall (n : nat),  bin n 0 = 1.\nintros n; induction n; auto.\nQed.\n\nLemma bin_1: forall (n : nat),  bin n 1 = n.\nintros; induction n as [|n IH]; simpl; auto.\nrewrite bin_0, IH, Plus.plus_comm; auto.\nQed.\n\nLemma bin_more: forall (n m : nat), n < m ->  bin n m = 0.\nintros n; induction n as [| n IH]; simpl; auto.\nintros m; case m; simpl; auto.\nintros H'; inversion H'; auto.\nintros m; case m; simpl; auto.\nintros H'0; contradict H'0; auto with arith.\nintros n1 H'0; rewrite !IH; auto with arith.\nQed.\n \nLemma bin_nn: forall (n : nat),  bin n n = 1.\nintros n; induction n as [| n IH]; intros; simpl; auto.\nrewrite (bin_more n (S n)); auto.\nQed.\n \nLemma bin_def:\n forall (n k : nat),  bin (S n) (S k) = bin n (S k) + bin n k.\nsimpl; auto.\nQed.\n \nFixpoint iter {A: Type} (f: A -> A) (n: nat) (x: A) :=\n  match n with \n  | O => x\n  | S n1 => f (iter f n1 x)\n  end.\n\n(* A bit of ssreflect *)\n\nCoercion b2Prop (x : bool) := x = true.\n\nLemma b2PropT: b2Prop true.\nProof. exact (refl_equal true). Qed.\n\nGlobal Hint Resolve b2PropT : core.\n\nRequire Import Bool.\n\nLemma andbP b1 b2: b1 && b2 <-> b1 /\\ b2.\nProof.\ncase b1; case b2; intuition.\nQed.\n\n(* Some facts about div2 *)\n\nLemma div2_double_p n m : div2 (2 * n + m) = n + div2 m.\nProof.\ninduction n as [| n IH]; simpl; auto.\nrewrite <-plus_n_Sm; simpl in IH |- *.\nrewrite IH; auto.\nQed.\n\nLemma div2_prop n: n + div2 (n * (n - 1)) = div2 (n.+1 * n).\nProof.\nassert (F1: forall n, (n + n * n = 2 * n + n * (n - 1))%nat).\nintros [|n1]; simpl; auto.\nrewrite <-!Minus.minus_n_O; ring.\ninduction n; simpl; auto.\nrewrite <-plus_n_Sm.\nrewrite <-Minus.minus_n_O.\nrewrite F1, div2_double_p.\nrewrite !Plus.plus_assoc; replace (n + n) with (2 * n); try ring.\nrewrite div2_double_p, <-(Mult.mult_comm (n.+1)), <-IHn.\nring.\nQed.\n\nLemma minus_minus_le m n: n <= m -> m - (m - n) = n.\nProof.\nassert (F1: (forall n m, n <= m -> exists k, m = k + n)%nat).\nintros n1 m1 H; elim H; auto.\nexists 0%nat; auto.\nintros m2 _ (k, Hk); rewrite Hk; exists k.+1; auto.\nintros H; case (F1 _ _ H).\nintros k Hk; subst.\nrewrite (Plus.plus_comm k), Minus.minus_plus.\nrewrite (Plus.plus_comm n), Minus.minus_plus; auto.\nQed.\n\nLemma minus0_le m n: m <= n -> m - n = 0.\nProof.\ngeneralize n; clear n; induction m as [| m IH]; auto.\nintros [|n]; simpl; auto with arith.\nQed.\n\nFixpoint eq_nat (m n: nat) :=\n  match m, n with (S m), (S n) => eq_nat m n | 0, 0 => true | _, _ => false end.\n\nNotation \"m ?= n\" := (eq_nat m n) (at level 70): nat_scope.\n\nInductive eq_nat_spec: nat -> nat -> bool -> Type := \n  eq_nat_spect: forall m, eq_nat_spec m m true\n| eq_nat_specb: forall m n, m <> n -> eq_nat_spec m n false.\n\nLemma eq_natP m n: eq_nat_spec m n (m ?= n).\nProof.\ngeneralize n; clear n; induction m as [| m IH]; intros [| n]; simpl;\n  try constructor; try (intros; discriminate).\n(case (IH n); clear m n IH); [intros m | intros m n H];\n  constructor; intros H1; case H; injection H1; auto.\nQed.\n\nNotation \"x .+2\" := (S (S x))  (at level 9): nat_scope.", "meta": {"author": "olivierverdier", "repo": "GeometricAlgebra", "sha": "86105900b5c3e58e7b117f714037b173a9cdcc75", "save_path": "github-repos/coq/olivierverdier-GeometricAlgebra", "path": "github-repos/coq/olivierverdier-GeometricAlgebra/GeometricAlgebra-86105900b5c3e58e7b117f714037b173a9cdcc75/Aux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245828938678, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.6962289666578232}}
{"text": "(* Coq演習 ex1 *)\nTheorem Modus_ponens : forall P Q : Prop, P -> (P -> Q) -> Q.\nProof.\n  intros.\n  apply H0.\n  exact H.\nQed.\n\nTheorem Modus_tollens : forall P Q : Prop, ~Q /\\ (P -> Q) -> ~P.\nProof.\n  unfold not.\n  intros.\n  inversion H.\n  apply H1.\n  apply H2.\n  exact H0.\nQed.\n\nTheorem Disjunctive_syllogism : forall P Q : Prop, (P \\/ Q) -> ~P -> Q.\nProof.\n  unfold not.\n  intros.\n  inversion H.\n  contradiction.\n\n  exact H1.\nQed.\n\n\nTheorem DeMorgan1 : forall P Q : Prop, ~P \\/ ~Q -> ~(P /\\ Q).\nProof.\n  unfold not.\n  intros.\n  inversion H0.\n  inversion H.\n  apply H3.\n  exact H1.\n\n  apply H3.\n  apply H2.\nQed.\n\nTheorem DeMorgan2 : forall P Q : Prop, ~P /\\ ~Q -> ~(P \\/ Q).\nProof.\n  unfold not.\n  intros.\n  inversion H.\n  inversion H0.\n  apply H1.\n  apply H3.\n\n  apply H2.\n  apply H3.\nQed.\n\nTheorem DeMorgan3 : forall P Q : Prop, ~(P \\/ Q) -> ~P /\\ ~Q.\nProof.\n  unfold not.\n  intros.\n  split.\n  intros.\n  apply H.\n  left.\n  exact H0.\n\n  intros.\n  apply H.\n  right.\n  exact H0.\nQed.\n\nTheorem NotNot_LEM : forall P : Prop, ~ ~(P \\/ ~P).\nProof.\n  unfold not.\n  intros.\n  apply H.\n  right.\n  intros.\n  apply H.\n  left.\n  exact H0.\nQed.\n", "meta": {"author": "sakabar", "repo": "CoqExercise", "sha": "f1138c25b4bc2b27edb9827b1712150ae3995b30", "save_path": "github-repos/coq/sakabar-CoqExercise", "path": "github-repos/coq/sakabar-CoqExercise/CoqExercise-f1138c25b4bc2b27edb9827b1712150ae3995b30/ex1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.6961820192445244}}
{"text": "(** Semántica y Verificación\n    Ejemplo 5\n    Manuel Soto Romero\n    Luis F. Benítez Lluis \n    \n    Contenido:\n    1 Definiciones de listas polimórficas\n    2 Pares Polimórficos\n      2.1 La función split\n    3 Opcioes polimórficos\n      3.1 Función head para listas polimóficas\n    4 La táctica discriminate\n    5 Manejo de la hipótesis inductiva \n    6 Desdoblando definiciones \n    7 Resumen de téctias (extracto citado del libro) \n    \n\n    Para acceder rápidamente a la sección deseada\n    buscar la cadena \">n\" donde \"n\" es el número de\n    sección. \n    \n    Material basado en los scripts \n    correspondientes al libro Logical Foundations en\n    Software Foundations- Benjamin C. Pierce, et al. \n    *)\n\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Bool.Bool.\n\n(** >1 Definiciones de listas polimórficas*)\n\nInductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\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 rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\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(** >2 Pares Polimórficos *)\n\n(* Generalizemos la noción de par *)\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\n\n(* Definimos lor argumentos implicitos *)\nArguments pair {X} {Y} _ _.\n\n\n(* Definomos la notación usual de par *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(* Podemos usar también notación para el producto de tipos*)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(* La anotación [: type_scope] le dice a Coq que la anotación de \n    tipos sólo aplica en el parsing de tipos, más no para expresiones. \n    Gracias a esta restricción evitamos conflicto con la notación\n    de multiplicación. *)\n\n\n(* Es importante hacer hincapié en que (x,y) representa la notación \n  de expresiones que representan parejas ordenadas y que \n  X*Y representan el producto de tipos. Si x:X y y:Y entonces\n  (x,y):X*Y*)\n\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\n(*Función que combina dos listas en parejas de entradas \n  de cada lista respectivamente *)\n(* [1,2,3], [4,5,6]=> [(1,4),(2,5),(3,6)]*)\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          \nExample test_combine: combine [1;2;3] [4;5;6]=[(1,4);(2,5);(3,6)].\nProof.\nsimpl.\nreflexivity.\nQed.\n\n\n\n(** >2.1 La función split*) \n(*  La función [split] es la inversa derecha de [combine], desdoblando\n    listas de parejas en una pareja de listas con los elementos\n    respectivos.*)\n(*    [(1,4);(2,5);(3,6)]\n   \n   (1,4)\n   ([2;3],[5;6]) *)\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y):=\nmatch l with\n  | [] => ([],[])\n  | h::t => ((fst h)::fst (split t), (snd h)::snd(split t))\nend.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof.\nreflexivity.\nQed.\n\n\n\n\n\n(** >3 Opcioes polimórficos *)\n\n(* Hagamos la definición en un módulo pues coq ya posee \n    el tipo opción que buscamos*)\nModule OptionPlayground.\n\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\n\nArguments Some {X} _.\nArguments None {X}.\n\nEnd OptionPlayground.\n\n(* Recordemos que nth-error es una función que devuelve el \n    n-ésimo elemento de una lista. Dado que se puede elegir \n    n ue supere la longitud de la lista, es conveniente que \n    devolvamos un tipo opción para ajustar para este error.  *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | nil => None\n  | a :: l' => match n with\n               | O => Some a\n               | S n' => nth_error l' n'\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\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\n\n(** >3.1 Función head para listas polimóficas *)\n\nDefinition hd_error {X : Type} (l : list X) : option X:=\n  match l with \n    | [] => None\n    | h::t=> Some h\n  end. \n\n\nCheck @hd_error : forall X : Type, list X -> option X.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\nProof.\nreflexivity.\nQed.\n\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\nProof.\nreflexivity.\nQed.\n \n \n \n \n(** >4 La táctica discriminate*)\n\n(*  La táctica [discriminate] sirve para detectar hipótesis inválidas\n    sobre igualdadades. Para que la táctica funcione, es inminente\n    que los términos sean sintácticamente distintos. Por ejemplo\n    cuando se tiene iguadad entre un sucesor y cero [S n = O]. *)\n\nTheorem eqb_0_l : forall n,\n   0 =? n = true -> n = 0.\nProof.\n  intros.\n  destruct n.\n  -  simpl in H. reflexivity.\n  - simpl in H.\n    discriminate H.\nQed.\n\n\n\n(*  El razonamiento lógico a esta solución sigue el principio de\n    explosión que afirma que de cosas falsas se sigue \n    lo que sea. En este caso la falsedad se encarna como \n    igualdades insatisfacibles. *)\n\nTheorem discriminate_ex1 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros.\n  discriminate H.\nQed.\n\n\nTheorem discriminate_ex2 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\nintros.\ndiscriminate H.\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.\n  intros.\n  discriminate H.\nQed.\n\n\nExample inversion_ex :\n  forall (n:nat), S n <=0-> 2+2=5.\nProof.\n  intros.\n  inversion H.  \nQed.\n\n\n(** >5 Manejo de la hipótesis inductiva *)\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\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' 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.\n\nAbort.\n\n\nTheorem double_injective : forall  n m,\n     double n = double m ->\n     n = m.\nProof.\nintro.\n\ninduction n.\n- intros. destruct m.\n  -- reflexivity.\n  -- discriminate H.\n- intros. destruct m.\n  -- discriminate H.\n  -- apply f_equal.\n      apply IHn.\n      inversion H.\n      reflexivity.\nQed.\n\n\n(* intros  n. induction n as [| n' IHn'].\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 = S n' *) simpl.\n    intros m eq.\n    destruct m as [| m'] eqn:E.\n    + (* m = O *)\n    discriminate eq.\n    + (* m = S m' *)\n      apply f_equal.\n      apply IHn'. simpl in eq. injection eq as goal. apply goal. \nQed. \n *)\n\n\n(* intro.\ninduction n.\n- intros. destruct m.\n-- reflexivity.\n-- simpl in H. discriminate H.\n- intros. simpl in H.\ndestruct m.\n-- simpl in H. discriminate H.\n-- simpl in H. apply f_equal. \n  apply IHn. \n  injection H.\n  intro.\n  assumption.\n  \n  (*  inversion H.\n   reflexivity. *)\nQed. *)\n  \n\n\n\n\n\n\n\nTheorem eqb_true : forall n m,\n    n =? m = true -> n = m.\nProof.\nintro.\ninduction n.\n- destruct m.\n-- intros. reflexivity.\n--  intros. discriminate H.\n- destruct m.\n-- intros. discriminate H.\n-- intros. apply f_equal.\n  apply IHn.\n  simpl in H.\n  assumption.\n  Qed.\n\n\n\n(* Hint: usar [plus_n_Sm] *)\nCheck plus_n_Sm.\nTheorem plus_n_n_injective : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\nintro.\ninduction n.\n- intros. simpl in H. destruct m.\n-- reflexivity.\n-- simpl in H.\ndiscriminate H.\n- intros.\ndestruct m. \n-- discriminate H.\n-- apply f_equal.\n   apply IHn.\n   simpl in H.\n   inversion H.\n   rewrite <-plus_n_Sm in H1.\n   rewrite <-plus_n_Sm in H1.\n   inversion H1.\n   reflexivity.\nQed.\n\n\n(* A veces hay que reorganizar las variables para que al generalizar\nlas pruebas salgas adecuadamente*)\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    + (* n = O *) reflexivity.\n    + (* n = S n' *) discriminate eq.\n  - (* m = S m' *) intros eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) discriminate eq.\n    + (* n = S n' *) apply f_equal.\n\nAbort.\n\n\nTheorem double_injective_take2 : forall m n,\n     double n = double m ->\n     n = m.\nProof.\nintros.\ngeneralize dependent m.\ninduction n.\n- intros. destruct m.\n  -- reflexivity.\n  -- discriminate H.\n- intros. destruct m.\n  -- discriminate H.\n  -- apply f_equal.\n      apply IHn.\n      inversion H.\n      reflexivity.\nQed.\n\n\n\n\n\n\n(*   intros n m.\n  generalize dependent n.\n  induction m as [| m' IHm'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) discriminate eq.\n  - (* m = S m' *) intros n eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) discriminate eq.\n    + (* n = S n' *) apply f_equal.\n      apply IHm'. injection eq as goal. apply goal. Qed. *)\n\n\n\n(* Probemos por inducción sobre 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.\nAdmitted.\n\n\n\n\n(** >6 Desdoblando definiciones *)\nRequire Import Coq.Arith.PeanoNat.\n\nDefinition square n := n * n.\n\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\nintros.\nunfold square.\nrewrite Nat.mul_assoc.\nassert (H : n * m * n = n * n * m).\n    { rewrite Nat.mul_comm. apply Nat.mul_assoc. }\n  rewrite H. rewrite Nat.mul_assoc. reflexivity.\nQed.\n\n\n\n\n\n\n\n\n(*  Algunas tácticas como [apply][simpl] y [reflexivity]\n    simplifican términos cuando se usan, y particularmente \n    desdoblan definiciones de algunas funciones.\n    Por lo que en algunos casos no hace falta desdoblar\n    las deficniciones pues se hace automáticamente *)\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\n(*  No obstante, este desdoblamiento no siempre se ejecuta\n    sobretodo si la expresión es algo compleja. *)\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. \nAbort.\n(* [simpl] no siempre logra progreso pues la cláusula match \n   impide que se simplifique a su última expresión, ya que\n   la entrada no se puede catalogar en la búsqueda de patrones.\n   Es hasta que se desestructura la entrad que se puede resolver\n   el match y simplificar la expresión*)\n\nFact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  destruct m eqn:E.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(* Esto funciona pero si alguna parte de la expresión no se puede\n  detectar para caza de patrones puede que requiramos más \n  desestructuración. Otra forma es literalmente desdoblando la \n  definición.*)\n\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\nAdmitted.\n\n\n\n(*   intros m.\n  unfold bar.\n  destruct m eqn:E.\n  - reflexivity.\n  - reflexivity.\nQed. *)\n\n\n\n\n\n(** >7 Resumen de téctias (extracto citado del libro) *)\n(* \n\n      - [intros]: move hypotheses/variables from goal to context\n\n      - [reflexivity]: finish the proof (when the goal looks like [e =\n        e])\n\n      - [apply]: prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: apply a hypothesis, lemma, or constructor to\n        a hypothesis in the context (forward reasoning)\n\n      - [apply... with...]: explicitly specify values for variables\n        that cannot be determined by pattern matching\n\n      - [simpl]: simplify computations in the goal\n\n      - [simpl in H]: ... or a hypothesis\n\n      - [rewrite]: use an equality hypothesis (or lemma) to rewrite\n        the goal\n\n      - [rewrite ... in H]: ... or a hypothesis\n\n      - [symmetry]: changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]: changes a hypothesis of the form [t=u] into\n        [u=t]\n\n      - [transitivity y]: prove a goal [x=z] by proving two new subgoals,\n        [x=y] and [y=z]\n\n      - [unfold]: replace a defined constant by its right-hand side in\n        the goal\n\n      - [unfold... in H]: ... or a hypothesis\n\n      - [destruct... as...]: case analysis on values of inductively\n        defined types\n\n      - [destruct... eqn:...]: specify the name of an equation to be\n        added to the context, recording the result of the case\n        analysis\n\n      - [induction... as...]: induction on values of inductively\n        defined types\n\n      - [injection]: reason by injectivity on equalities\n        between values of inductively defined types\n\n      - [discriminate]: reason by disjointness of constructors on\n        equalities between values of inductively defined types\n\n      - [assert (H: e)] (or [assert (e) as H]): introduce a \"local\n        lemma\" [e] and call it [H]\n\n      - [generalize dependent x]: move the variable [x] (and anything\n        else that depends on it) from the context back to an explicit\n        hypothesis in the goal formula\n\n      - [f_equal]: change a goal of the form [f x = f y] into [x = y] *)\n\n\n", "meta": {"author": "manu-msr", "repo": "coq", "sha": "69b461db086cac993f5877d24129a1cec7b95322", "save_path": "github-repos/coq/manu-msr-coq", "path": "github-repos/coq/manu-msr-coq/coq-69b461db086cac993f5877d24129a1cec7b95322/scripts_coq/SVcoq_ejemplo5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.6961820127752186}}
{"text": "(* ListCalculus.v *)\n(* author: Peter Urbak *)\n(* version: 2014-06-02 *)\n\n(** * List calculus\n\n  This module defines a small calculus over the [list nat] type with the\n  following selectors:\n\n  - [hd]\n  - [tl]\n  - [nth]\n  - [last]\n  - [removelast]\n  - [app]\n  - [length]\n  - [rev]\n\n  constructors:\n\n  - [make_list]\n  - [list_constant]\n  - [list_successor]\n\n  and operators:\n\n  - [list_map]\n  - [list_scalar_mult]\n  - [list_exponentiation]\n  - [list_zip]\n  - [list_sum]\n  - [list_product]\n  - [list_partial_sums_acc]\n  - [list_partial_sums]\n*)\n\n(** * Preliminaries *)\n\n(** ** Requirements *)\n\n(* Standard library *)\nRequire Import Arith.\nRequire Export List.\nExport ListNotations. (* enable [ ] and [ a ; b ; c] notation *)\n\n(* Own modules *)\nRequire Import Cases.\nRequire Export Power.\n\n(** * List basics *)\n\n(** ** List type *)\n\n(** ** List\n\n  *** Definition *)\n\n(*\n(* {LIST} *)\nInductive list (A : Type) : Type :=\n | nil : list A\n | cons : A -> list A -> list A.\n(* {END} *)\n\n(* {NOTATION} *)\nNotation \" [ ] \" := nil : list_scope.\nNotation \" [ x ] \" := (cons x nil) : list_scope.\nNotation \" [ x ; .. ; y ] \" := (cons x .. (cons y nil) ..) : list_scope.\nInfix \"::\" := cons (at level 60, right associativity) : list_scope.\n(* {END} *)\n*)\n\n(** ** List selectors *)\n\n(** ** Hd\n\n  *** Definition *)\n\n(*\n(* {HD} *)\nDefinition hd {A : Type} (d : A) (xs : list A) :=\n  match xs with\n    | [] => d\n    | x :: _ => x\n  end.\n(* {END} *)\n*)\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_list_head :\n  forall (d : nat) (xs : list nat),\n    hd d xs = match xs with\n               | [] => d\n               | x :: _ => x\n              end.\nProof.\n  intros d xs.\n  unfold hd.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_head : listcalc.\n\n(** ** Tl\n\n  *** Definition *)\n\n(*\n(* {TL} *)\nDefinition tl {A : Type} (xs : list A) :=\n  match xs with\n    | [] => []\n    | _ :: xs' => xs'\n  end.\n(* {END} *)\n*)\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_list_tail :\n  forall (xs : list nat),\n    tl xs = match xs with\n              | [] => []\n              | _ :: xs' => xs'\n            end.\nProof.\n  intro xs.\n  unfold tl.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_tail : listcalc.\n\n(** ** Nth\n\n *** Definition *)\n\n(*\n(* {NTH} *)\nFixpoint nth {A : Type} (n : nat) (xs: list A) (d : A) : A :=\n  match n, xs with\n    | O, x :: xs' => x\n    | O, [] => d\n    | S n', [] => d\n    | S n', x :: xs => nth n' xs' d\n  end.\n(* {END} *)\n*)\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_nth_base_case_nil :\n  forall (A : Type) (d : A),\n    nth 0 [] d = d.\nProof.\n  intros A d.\n  unfold nth.\n  reflexivity.\nQed.\nHint Rewrite unfold_nth_base_case_nil : listcalc.\n\nLemma unfold_nth_base_case_cons :\n  forall (A : Type) (d x : A) (xs' : list A),\n    nth 0 (x :: xs') d = x.\nProof.\n  intros A d x xs'.\n  unfold nth.\n  reflexivity.\nQed.\nHint Rewrite unfold_nth_base_case_cons : listcalc.\n\nLemma unfold_nth_induction_case_nil :\n  forall (A : Type) (n' : nat) (d : A),\n    nth (S n') [] d = d.\nProof.\n  intros A n' d.\n  unfold nth.\n  reflexivity.\nQed.\nHint Rewrite unfold_nth_induction_case_nil : listcalc.\n\nLemma unfold_nth_induction_case_cons :\n  forall (A : Type) (n' : nat) (d x : A) (xs' : list A),\n    nth (S n') (x :: xs') d = nth n' xs' d.\nProof.\n  intros A n' d x xs'.\n  unfold nth.\n  reflexivity.\nQed.\nHint Rewrite unfold_nth_induction_case_cons : listcalc.\n\n(** *** Properties *)\n\nLemma nth_n_nil :\n  forall (A : Type) (n : nat) (d : A),\n    nth n [] d = d.\nProof.\n  intros A n d.\n  case n as [ | n' ].\n\n  Case \"n = 0\".\n  rewrite -> unfold_nth_base_case_nil.\n  reflexivity.\n\n  Case \"n = S n'\".\n  rewrite -> unfold_nth_induction_case_nil.\n  reflexivity.\nQed.\nHint Rewrite nth_n_nil : listcalc.\n\n(** ** Last\n\n  *** Definition *)\n\n(*\n(* {LAST} *)\nFixpoint last {A : Type} (xs: list A) (d : A) : A :=\n  match xs with\n    | [] => d\n    | [x] => x\n    | x :: xs => last xs d\n  end.\n(* {END} *)\n*)\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_last_base_case_nil :\n  forall (A : Type) (d : A),\n    last [] d = d.\nProof.\n  intros A d.\n  unfold last.\n  reflexivity.\nQed.\nHint Rewrite unfold_last_base_case_nil : listcalc.\n\nLemma unfold_last_base_case_cons :\n  forall (A : Type) (x d : A),\n    last [x] d = x.\nProof.\n  intros A x d.\n  unfold last.\n  reflexivity.\nQed.\nHint Rewrite unfold_last_base_case_cons : listcalc.\n\nLemma unfold_last_induction_case :\n  forall (A : Type) (x x' d : A) (xs'' : list A),\n    last (x :: x' :: xs'') d = last (x' :: xs'') d.\nProof.\n  intros A x x' d xs''.\n  unfold last; fold last.\n  reflexivity.\nQed.\nHint Rewrite unfold_last_induction_case : listcalc.\n\n(** *** Properties *)\n\nLemma last_cons :\n  forall (x d : nat) (xs' : list nat),\n    length xs' > 0 ->\n    last (x :: xs') d = last xs' d.\nProof.\n  intros x d.\n  case xs' as [ | x' xs'' ].\n\n  Case \"xs' = []\".\n  intro H_absurd; inversion H_absurd.\n\n  Case \"xs' = x' :: xs''\".\n  intros _.\n  rewrite -> unfold_last_induction_case.\n  reflexivity.\nQed.\nHint Resolve last_cons : listcalc.\n\n(** ** Remove last\n\n  *** Definition *)\n\n(*\n(* {REMOVELAST} *)\nFixpoint removelast {A : Type} (xs : list A) : list A :=\n  match xs with\n    | [] => []\n    | [x] => []\n    | x :: xs => x :: removelast xs\n  end.\n(* {END} *)\n*)\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_removelast_base_case_nil :\n  forall (A : Type),\n    removelast ([] : list A) = ([] : list A).\nProof.\n  intro A.\n  unfold removelast.\n  reflexivity.\nQed.\nHint Rewrite unfold_removelast_base_case_nil : listcalc.\n\nLemma unfold_removelast_base_case_cons :\n  forall (A : Type) (x : A),\n    removelast [x] = [].\nProof.\n  intros A x.\n  unfold removelast.\n  reflexivity.\nQed.\nHint Rewrite unfold_removelast_base_case_cons : listcalc.\n\nLemma unfold_removelast_induction_case :\n  forall (A : Type) (x x' : A) (xs'' : list A),\n    removelast (x :: x' :: xs'') = x :: removelast (x' :: xs'').\nProof.\n  intros A x x' xs''.\n  unfold removelast.\n  reflexivity.\nQed.\nHint Rewrite unfold_removelast_induction_case : listcalc.\n\n(** ** App\n\n  *** Definition *)\n\n(*\n(* {APP} *)\nFixpoint app {A : Type} (xs ys : list A) : list A :=\n  match xs with\n    | [] => ys\n    | x :: xs' => x :: app xs' ys\n  end.\nInfix \"++\" := app (right associativity, at level 60) : list_scope.\n(* {END} *)\n*)\n\n(** ** Length\n\n  *** Definition *)\n\n(*\n(* {LENGTH} *)\nFixpoint length {A : Type} (xs : list A) : nat :=\n  match xs with\n   | [] => O\n   | _ :: xs' => S (length xs')\n  end.\n(* {END} *)\n*)\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_length_base_case :\n  length ([] : list nat) = 0.\nProof.\n  unfold length.\n  reflexivity.\nQed.\nHint Rewrite unfold_length_base_case : listcalc.\n\nLemma unfold_length_induction_case :\n  forall (x : nat) (xs' : list nat),\n    length (x :: xs') = S (length xs').\nProof.\n  intros x xs'.\n  unfold length.\n  reflexivity.\nQed.\nHint Rewrite unfold_length_induction_case : listcalc.\n\n(** *** Properties *)\n\nLemma length_nil_0 :\n  forall (xs : list nat),\n    length xs = 0 ->\n    xs = [].\nProof.\n  case xs as [ | x xs' ].\n\n  Case \"xs = []\".\n  intro H_length_nil_eq_0.\n  reflexivity.\n\n  Case \"xs = x :: xs'\".\n  intro H_absurd; inversion H_absurd.\nQed.\nHint Rewrite length_nil_0 : listcalc.\n\nLemma length_implies_last_index :\n  forall (n d : nat) (xs : list nat),\n    length xs = (S n) ->\n    last xs d = nth n xs d.\nProof.\n  induction n as [ | n' IH_n' ].\n\n  Case \"n = 0\".\n  intro d.\n  case xs as [ | x xs' ].\n\n  SCase \"xs = []\".\n  intro H_absurd; inversion H_absurd.\n\n  SCase \"xs = x :: xs'\".\n  intro H_length_x_xs'_eq_1.\n  rewrite -> unfold_nth_base_case_cons.\n  inversion H_length_x_xs'_eq_1;\n    rename H0 into H_length_xs'_eq_0.\n  rewrite -> (length_nil_0 xs' H_length_xs'_eq_0).\n  rewrite -> unfold_last_base_case_cons.\n  reflexivity.\n\n  Case \"n = S n'\".\n  intro d.\n  case xs as [ | x xs' ].\n\n  SCase \"xs = []\".\n  intro H_absurd; inversion H_absurd.\n\n  SCase \"xs = x :: xs'\".\n  intro H_length_x_xs'_eq_S_S_n'.\n  rewrite -> unfold_nth_induction_case_cons.\n  inversion H_length_x_xs'_eq_S_S_n';\n   rename H0 into H_length_xs'_eq_S_n'.\n  rewrite <- (IH_n' d xs' H_length_xs'_eq_S_n').\n  rewrite -> last_cons;\n    [ reflexivity | rewrite -> H_length_xs'_eq_S_n'; apply gt_Sn_O ].\nQed.\nHint Resolve length_implies_last_index : listcalc.\n\n(** ** Rev\n\n  ** Definition *)\n\n(*\n(* {REV} *)\nFixpoint rev {A : Type} (xs : list A) : list A :=\n  match xs with\n    | [] => []\n    | x :: xs' => rev xs' ++ [x]\n  end.\n(* {END} *)\n*)\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_rev_base_case :\n  forall (A : Type),\n    rev ([] : list A) = [].\nProof.\n  intro A.\n  unfold rev.\n  reflexivity.\nQed.\nHint Rewrite unfold_rev_base_case : listcalc.\n\nLemma unfold_rev_induction_case :\n  forall (A : Type) (x : A) (xs' : list A),\n    rev (x :: xs') = rev xs' ++ [x].\nProof.\n  intros A x xs'.\n  unfold rev; fold rev.\n  reflexivity.\nQed.\nHint Rewrite unfold_rev_induction_case : listcalc.\n\n(** *** Properties *)\n\n(* {NTH_REV_EQ_LAST} *)\nLemma nth_rev_eq_last :\n  forall (xs : list nat) (d : nat),\n    nth 0 (rev xs) d =\n    last xs d.\n(* {END} *)\nProof.\n  induction xs as [ | x xs' IH_xs' ].\n\n  Case \"xs = []\".\n  intro d.\n  rewrite -> unfold_last_base_case_nil.\n  rewrite -> unfold_rev_base_case.\n  rewrite -> unfold_nth_base_case_nil.\n  reflexivity.\n\n  Case \"xs = x :: xs'\".\n  intro d.\n  case xs' as [ | x' xs'' ].\n\n  SCase \"xs' = []\".\n  rewrite -> unfold_last_base_case_cons.\n  rewrite -> unfold_rev_induction_case.\n  rewrite -> unfold_rev_base_case.\n  rewrite -> app_nil_l.\n  rewrite -> unfold_nth_base_case_cons.\n  reflexivity.\n\n  SCase \"xs' = x' :: xs''\".\n  rewrite -> unfold_rev_induction_case.\n  rewrite -> unfold_last_induction_case.\n  rewrite <- (IH_xs' d).\n  rewrite -> unfold_rev_induction_case.\n  rewrite -> app_nth1;\n    [ idtac |\n      rewrite -> app_length;\n        rewrite -> unfold_length_induction_case;\n        rewrite -> unfold_length_base_case;\n        rewrite -> plus_comm;\n        apply lt_0_Sn ].\n  reflexivity.\nQed.\nHint Rewrite nth_rev_eq_last : listcalc.\n\n(** ** List constructors *)\n\n(** ** Make list\n\n  *** Definition *)\n\n(* {MAKE_LIST} *)\nFixpoint make_list (n i : nat) (f : nat -> nat) : list nat :=\n  match n with\n    | 0 => []\n    | S n' => i :: (make_list n' (f i) f)\n  end.\n(* {END} *)\nHint Unfold make_list : listcalc.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_make_list_base_case :\n  forall (i : nat) (f : nat -> nat),\n    make_list 0 i f = [].\nProof.\n  intros i f.\n  unfold make_list.\n  reflexivity.\nQed.\nHint Rewrite unfold_make_list_base_case : listcalc.\n\nLemma unfold_make_list_induction_case :\n  forall (n' i : nat) (f : nat -> nat),\n    make_list (S n') i f = i :: (make_list n' (f i) f).\nProof.\n  intros n' i f.\n  unfold make_list; fold make_list.\n  reflexivity.\nQed.\nHint Rewrite unfold_make_list_induction_case : listcalc.\n\n(** *** List constant\n\n  *** Definition *)\n\n(* {LIST_CONSTANT} *)\nDefinition list_constant (n c : nat) : list nat :=\n  make_list n c (fun x : nat => x).\n(* {END} *)\nHint Unfold list_constant : listcalc.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_list_constant_base_case :\n  forall (c : nat),\n    list_constant 0 c = [].\nProof.\n  intro c.\n  unfold list_constant.\n  rewrite -> unfold_make_list_base_case.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_constant_base_case : listcalc.\n\nLemma unfold_list_constant_induction_case :\n  forall (c n' : nat),\n    list_constant (S n') c = c :: (list_constant n' c).\nProof.\n  intros c n'.\n  unfold list_constant.\n  rewrite -> unfold_make_list_induction_case.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_constant_induction_case : listcalc.\n\n(** List successor *)\n\n(* {LIST_SUCCESSOR} *)\nDefinition list_successor (n i : nat) : list nat :=\n  make_list n i S.\n(* {END} *)\nHint Unfold list_successor : listcalc.\n\nLemma unfold_list_successor_base_case :\n  forall (i : nat),\n    list_successor 0 i = [].\nProof.\n  intro i.\n  unfold list_successor.\n  rewrite -> unfold_make_list_base_case.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_successor_base_case : listcalc.\n\nLemma unfold_list_successor_induction_case :\n  forall (n' i : nat),\n    list_successor (S n') i = i :: (list_successor n' (S i)).\nProof.\n  intros n' i.\n  unfold list_successor.\n  rewrite -> unfold_make_list_induction_case.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_successor_induction_case : listcalc.\n\n(** * List operators *)\n\n(** ** List map\n\n  *** Definition *)\n\n(* {LIST_MAP} *)\nFixpoint list_map (f : nat -> nat) (xs : list nat) : list nat :=\n  match xs with\n    | [] => xs\n    | x :: xs' => (f x) :: (list_map f xs')\n  end.\n(* {END} *)\nHint Unfold list_map : listcalc.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_list_map_base_case :\n  forall (f : nat -> nat),\n    list_map f [] = [].\nProof.\n  intro f.\n  unfold list_map.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_map_base_case : listcalc.\n\nLemma unfold_list_map_induction_case :\n  forall (x : nat) (xs' : list nat) (f : nat -> nat),\n    list_map f (x :: xs') = (f x) :: (list_map f xs').\nProof.\n  intros x xs' f.\n  unfold list_map; fold list_map.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_map_induction_case : listcalc.\n\n(** ** List scalar multiplication\n\n  *** Definition *)\n\n(* {LIST_SCALAR_MULTIPLICATION} *)\nDefinition list_scalar_multiplication (k : nat)\n           (xs : list nat) : list nat :=\n  list_map (mult k) xs.\nNotation \"k ls* xs\" := (list_scalar_multiplication k xs)\n                         (at level 40, left associativity).\n(* {END} *)\nHint Unfold list_scalar_multiplication : listcalc.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_list_scalar_multiplication :\n  forall (k : nat) (xs : list nat),\n    list_scalar_multiplication k xs = list_map (mult k) xs.\nProof.\n  intros k xs.\n  unfold list_scalar_multiplication.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_scalar_multiplication : listcalc.\n\nLemma unfold_list_scalar_multiplication_base_case :\n  forall (k : nat),\n    k ls* [] = [].\nProof.\n  intro k.\n  unfold list_scalar_multiplication.\n  exact (unfold_list_map_base_case (mult k)).\nQed.\nHint Rewrite unfold_list_scalar_multiplication_base_case : listcalc.\n\nLemma unfold_list_scalar_multiplication_induction_case :\n  forall (k x : nat) (xs' : list nat),\n    k ls* (x :: xs') = (k * x) :: (k ls* xs').\nProof.\n  intros k x xs'.\n  unfold list_scalar_multiplication.\n  exact (unfold_list_map_induction_case x xs' (mult k)).\nQed.\nHint Rewrite unfold_list_scalar_multiplication_induction_case : listcalc.\n\n(** ** List exponentiation\n\n  *** Definition *)\n\n(* {LIST_EXPONENTIATION} *)\nDefinition list_exponentiation (n : nat) (xs : list nat) : list nat :=\n  list_map (power n) xs.\nNotation \"xs l^ n\" := (list_exponentiation n xs)\n                        (at level 31, left associativity).\n(* {END} *)\nHint Unfold list_exponentiation : listcalc.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_list_exponentiation :\n  forall (n : nat) (xs : list nat),\n    list_exponentiation n xs = list_map (power n) xs.\nProof.\n  intros n xs.\n  unfold list_exponentiation.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_exponentiation : listcalc.\n\nLemma unfold_list_exponentiation_base_case :\n  forall (n : nat),\n    [] l^ n = [].\nProof.\n  intro n.\n  unfold list_exponentiation.\n  rewrite -> unfold_list_map_base_case.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_exponentiation_base_case : listcalc.\n\nLemma unfold_list_exponentiation_induction_case :\n  forall (n x : nat) (xs' : list nat),\n    (x :: xs') l^ n = (x ^ n) :: (xs' l^ n).\nProof.\n  intros n x xs'.\n  unfold list_exponentiation.\n  rewrite -> unfold_list_map_induction_case.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_exponentiation_induction_case : listcalc.\n\n(** ** List zip\n\n  *** Definition *)\n\n(* {LIST_ZIP} *)\nFixpoint list_zip (f : nat -> nat -> nat)\n         (xs ys : list nat) : list nat :=\n  match xs, ys with\n    | xs, [] => xs\n    | [], ys => ys\n    | x :: xs', y :: ys' => (f x y) :: (list_zip f xs' ys')\n  end.\n(* {END} *)\nHint Unfold list_zip : listcalc.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_list_zip_base_case_nil :\n  forall (f : nat -> nat -> nat),\n    list_zip f [] [] = [].\nProof.\n  intro f.\n  unfold list_zip.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_zip_base_case_nil : listcalc.\n\nLemma unfold_list_zip_base_case_cons :\n  forall (y : nat) (ys' : list nat) (f : nat -> nat -> nat),\n    list_zip f [] (y :: ys') = (y :: ys').\nProof.\n  intros y ys' f.\n  unfold list_zip.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_zip_base_case_cons : listcalc.\n\nLemma unfold_list_zip_induction_case_nil :\n  forall (x : nat) (xs' : list nat) (f : nat -> nat -> nat),\n    list_zip f (x :: xs') [] = (x :: xs').\nProof.\n  intros x xs' f.\n  unfold list_zip.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_zip_induction_case_nil : listcalc.\n\nLemma unfold_list_zip_induction_case_cons :\n  forall (x y : nat) (xs' ys' : list nat) (f : nat -> nat -> nat),\n    list_zip f (x :: xs') (y :: ys') = (f x y) :: (list_zip f xs' ys').\nProof.\n  intros x y xs' ys' f.\n  unfold list_zip; fold list_zip.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_zip_induction_case_cons : listcalc.\n\n(** ** List sum\n\n  *** Definition *)\n\n(* {LIST_SUM} *)\nDefinition list_sum (xs ys : list nat) : list nat :=\n  list_zip plus xs ys.\nInfix \"l+\" := list_sum (at level 50, left associativity).\n(* {END} *)\nHint Unfold list_sum : listcalc.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_list_sum :\n  forall (xs ys : list nat),\n    xs l+ ys = list_zip plus xs ys.\nProof.\n  intros xs ys.\n  unfold list_sum.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_sum : listcalc.\n\nLemma unfold_list_sum_base_case_nil :\n  [] l+ [] = [].\nProof.\n  unfold list_sum.\n  exact (unfold_list_zip_base_case_nil plus).\nQed.\nHint Rewrite unfold_list_sum_base_case_nil : listcalc.\n\nLemma unfold_list_sum_base_case_cons :\n  forall (y : nat) (ys' : list nat),\n    [] l+ (y :: ys') = (y :: ys').\nProof.\n  intros y ys'.\n  unfold list_sum.\n  exact (unfold_list_zip_base_case_cons y ys' plus).\nQed.\nHint Rewrite unfold_list_sum_base_case_cons : listcalc.\n\nLemma unfold_list_sum_induction_case_nil :\n  forall (x : nat) (xs' : list nat),\n    (x :: xs') l+ [] = (x :: xs').\nProof.\n  intros x xs'.\n  unfold list_sum.\n  exact (unfold_list_zip_induction_case_nil x xs' plus).\nQed.\nHint Rewrite unfold_list_sum_induction_case_nil : listcalc.\n\nLemma unfold_list_sum_induction_case_cons :\n  forall (x y : nat) (xs' ys' : list nat),\n    (x :: xs') l+ (y :: ys') = (x + y) :: (xs' l+ ys').\nProof.\n  intros x y xs' ys'.\n  unfold list_sum.\n  exact (unfold_list_zip_induction_case_cons x y xs' ys' plus).\nQed.\nHint Rewrite unfold_list_sum_induction_case_cons : listcalc.\n\n(** ** List product\n\n  *** Definition *)\n\n(* {LIST_PRODUCT} *)\nDefinition list_product (xs ys : list nat) : list nat :=\n  list_zip mult xs ys.\nInfix \"l*\" := list_product (at level 40, left associativity).\n(* {END} *)\nHint Unfold list_product : listcalc.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_list_product :\n  forall (xs ys : list nat),\n    xs l* ys = list_zip mult xs ys.\nProof.\n  intros xs ys.\n  unfold list_product.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_product : listcalc.\n\nLemma unfold_list_product_base_case_nil :\n  [] l* [] = [].\nProof.\n  unfold list_product.\n  exact (unfold_list_zip_base_case_nil mult).\nQed.\nHint Rewrite unfold_list_product_base_case_nil : listcalc.\n\nLemma unfold_list_product_base_case_cons :\n  forall (y : nat) (ys' : list nat),\n    [] l* (y :: ys') = (y :: ys').\nProof.\n  intros y ys'.\n  unfold list_product.\n  exact (unfold_list_zip_base_case_cons y ys' mult).\nQed.\nHint Rewrite unfold_list_product_base_case_cons : listcalc.\n\nLemma unfold_list_product_induction_case_nil :\n  forall (x : nat) (xs' : list nat),\n    (x :: xs') l* [] = (x :: xs').\nProof.\n  intros x xs'.\n  unfold list_product.\n  exact (unfold_list_zip_induction_case_nil x xs' mult).\nQed.\nHint Rewrite unfold_list_product_induction_case_nil : listcalc.\n\nLemma unfold_list_product_induction_case_cons :\n  forall (x y : nat) (xs' ys' : list nat),\n    (x :: xs') l* (y :: ys') = (x * y) :: (xs' l* ys').\nProof.\n  intros x y xs' ys'.\n  unfold list_product.\n  exact (unfold_list_zip_induction_case_cons x y xs' ys' mult).\nQed.\nHint Rewrite unfold_list_product_induction_case_cons : listcalc.\n\n(** ** List partial sums acc\n\n  *** Definition *)\n\n(* {LIST_PARTIAL_SUMS_ACC} *)\nFixpoint list_partial_sums_acc (a : nat) (xs : list nat) : list nat :=\n  match xs with\n    | [] => []\n    | x :: xs' => (x + a) :: (list_partial_sums_acc (x + a) xs')\n  end.\n(* {END} *)\nHint Unfold list_partial_sums_acc : listcalc.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_list_partial_sums_acc_base_case :\n  forall (a : nat),\n    list_partial_sums_acc a [] = [].\nProof.\n  intro a.\n  unfold list_partial_sums_acc.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_partial_sums_acc_base_case : listcalc.\n\nLemma unfold_list_partial_sums_acc_induction_case :\n  forall (a x : nat) (xs' : list nat),\n    list_partial_sums_acc a (x :: xs') =\n    (x + a) :: (list_partial_sums_acc (x + a) xs').\nProof.\n  intros a x xs'.\n  unfold list_partial_sums_acc; fold list_partial_sums_acc.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_partial_sums_acc_induction_case : listcalc.\n\n(** *** Properties *)\n\nLemma nth_list_partial_sums_acc :\n  forall (xs : list nat) (a d : nat),\n    length xs > 0 ->\n    nth 0 (list_partial_sums_acc a xs) d =\n    (nth 0 xs d) + a.\nProof.\n  induction xs as [ | x xs' IH_xs' ].\n\n  Case \"xs = []\".\n  intros a d H_absurd.\n  inversion H_absurd.\n\n  Case \"xs = x :: xs'\".\n  intros a d H_length_x_xs'_gt_0.\n  rewrite -> unfold_list_partial_sums_acc_induction_case.\n  rewrite -> unfold_nth_base_case_cons.\n  rewrite -> unfold_nth_base_case_cons.\n  reflexivity.\nQed.\nHint Rewrite nth_list_partial_sums_acc : listcalc.\n\n(** *** List partial sums\n\n  *** Definition *)\n\n(* {LIST_PARTIAL_SUMS} *)\nDefinition list_partial_sums (xs : list nat) : list nat :=\n  list_partial_sums_acc 0 xs.\n(* {END} *)\nHint Unfold list_partial_sums : listcalc.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_list_partial_sums :\n  forall (xs : list nat),\n    list_partial_sums xs = list_partial_sums_acc 0 xs.\nProof.\n  intro xs.\n  unfold list_partial_sums.\n  reflexivity.\nQed.\nHint Rewrite unfold_list_partial_sums : listcalc.\n\n(** *** Properties *)\n\nLemma nth_list_partial_sums :\n  forall (xs : list nat) (d : nat),\n    length xs > 0 ->\n    nth 0 (list_partial_sums xs) d =\n    (nth 0 xs d).\nProof.\n  intros xs d H_length_xs_gt_0.\n  rewrite -> unfold_list_partial_sums.\n  rewrite <- plus_0_r.\n  exact (nth_list_partial_sums_acc xs 0 d H_length_xs_gt_0).\nQed.\nHint Rewrite nth_list_partial_sums : listcalc.", "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/ListCalculus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.6961819918890974}}
{"text": "(** * Step 1 and 2. Defining syntax and isomorphism *)\n\n(** Grammar of pseudo-type  \n\n   Add this annotation to guide the isomorphism generation tool \n   to produce the isomorphism modules for type automatically\n<<\n(*@Iso Iso_typ*)\n>> *)\n\n(*@Iso Iso_typ*)\nInductive typ :=\n| typ_var : nat -> typ\n| typ_arrow  : typ -> typ -> typ.\n\n(** Grammar of pseudo-term \n\nAdd this annotation to guide the isomorphism generation tool to produce the isomorphism modules for term automatically\n<<\n(*@Iso Iso_trm {\n  Parameter trm_fvar,\n  Variable  trm_bvar,\n  Binder trm_abs\n}*)\n>> *)\n\n(*@Iso Iso_trm {\n  Parameter trm_fvar,\n  Variable  trm_bvar,\n  Binder trm_abs\n}*)\nInductive trm :=\n| trm_fvar : nat -> trm\n| trm_bvar : nat -> trm\n| trm_abs  : trm -> trm\n| trm_app  : trm -> trm -> trm. \n\n\n(***********************************************************)\n(** ** Isomorphism modules for type and term *)\n(***********************************************************)\n(** Isomorphism generation tool will produce isomorphism modules for type and term automatically. \n\n> genIsos Tutorial_STLC_Syntax.v\n\nThis command will generate [Iso_typ.v] and [Iso_trm.v] \nwhich contain isomorphism for type and isomorphism for term respectively.\n\n<<\nModule Iso_typ <: Iso_partial.\n  ...\nEnd Iso_typ\n\n\nModule Iso_trm <: Iso_full.\n  ...\nEnd Iso_trm\n>> *)\n", "meta": {"author": "Blaisorblade", "repo": "knot-esop-2017-case-study", "sha": "cf541cb38a483a514474f4c948bf005bc49b1e6f", "save_path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study", "path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study/knot-esop-2017-case-study-cf541cb38a483a514474f4c948bf005bc49b1e6f/poplmark_comparison/gmeta/Tutorial_STLC_Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.696180784018638}}
{"text": "Require Import LC.Util.Fin.\n\nFixpoint Vec X n : Type :=\n  match n with\n  | 0 => unit\n  | S m => X * Vec X m\n  end.\n\nFixpoint vmap {X Y} {n} (f : X -> Y) : Vec X n -> Vec Y n :=\n  match n with\n  | 0 => fun _ => tt\n  | S m => fun '(x, xs) => (f x, vmap f xs)\n  end.\n\nFixpoint vlookup {X} {n} : Fin n -> Vec X n -> X :=\n  match n with\n  | 0 => fun e =>\n    match e with\n    end\n  | S m => fun i v =>\n    match i with\n    | inl _ => fst v\n    | inr j => vlookup j (snd v)\n    end\n  end.\n\nLemma vlookup_vmap {X Y} {n} (f : X -> Y) (v : Vec X n) (i : Fin n) :\n  vlookup i (vmap f v) = f (vlookup i v).\nProof.\n  induction n.\n  - destruct i.\n  - destruct i; destruct v; simpl.\n    + reflexivity.\n    + now rewrite IHn.\nQed.\n\nFixpoint Fins n : Vec (Fin n) n :=\n  match n with\n  | 0 => tt\n  | S m => (inl tt, vmap inr (Fins m))\n  end.\n\nLemma vlookup_Fins {n} : forall i : Fin n,\n  vlookup i (Fins n) = i.\nProof.\n  induction n; intro i.\n  - destruct i.\n  - destruct i as [[]|j].\n    + reflexivity.\n    + simpl.\n      rewrite vlookup_vmap.\n      now rewrite IHn.\nQed.\n", "meta": {"author": "emarzion", "repo": "lc-self-interpreter", "sha": "d3ec0e13c4e725f886d81d7d9e17dc06e4584e0f", "save_path": "github-repos/coq/emarzion-lc-self-interpreter", "path": "github-repos/coq/emarzion-lc-self-interpreter/lc-self-interpreter-d3ec0e13c4e725f886d81d7d9e17dc06e4584e0f/src/Util/Vec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.696180778273082}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Omega.\n\nSet Implicit Arguments.\n\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. 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.\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      omega.\n      revert H4; apply HP, H3.\n    apply (H x y).\n    omega.\n    split; auto; omega.\n  Qed.\n\nEnd nat_rev_ind'.\n\nSection minimizer_bool.\n\n  Variable (T F : nat -> Prop)\n           (HFun  : forall n, T n -> F n -> False)\n           (HComp : forall n, T n \\/ F n -> { T n } + { F n }).\n\n  Definition minimizer n := T n /\\ forall i, i < n -> F i.\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; destruct (@HFun n); auto.\n    * apply H2 in H; destruct (@HFun m); auto.\n  Qed. \n\n  Inductive bar n : Prop :=\n    | in_bar_0 : T n -> bar n\n    | in_bar_1 : F n -> bar (S n) -> bar n.\n\n  Let bar_ex n : bar n -> T n \\/ F n.\n  Proof. induction 1; auto. Qed.\n\n  Let loop : forall n, bar n -> { k | T k /\\ forall i, n <= i < k -> F i }.\n  Proof.\n    refine (fix loop n Hn { struct Hn } := match HComp (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; trivial. \n      intros; omega.\n    * destruct Hn; trivial. \n      destruct (@HFun n); trivial.\n    * destruct Hk as (H1 & H2); split; trivial.\n      intros i Hi; destruct (eq_nat_dec i n).\n      - subst; trivial.\n      - apply H2; omega.\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    revert H1.\n    apply nat_rev_ind' with (k := k).\n    intros i H3.\n    apply in_bar_1, H2; trivial.\n    omega.\n  Qed.\n\n  Definition minimizer_bool_coq : sig minimizer.\n  Proof.\n    destruct (loop bar_0) as (k & H1 & H2).\n    exists k; split; auto.\n    intros; apply H2; omega.\n  Defined.\n\nEnd minimizer_bool.\n\nSection 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  Let T n := R n 0.\n  Let F n := exists u, R n (S u).\n \n  Definition minimizer_coq : ex (@minimizer T F) -> sig (@minimizer T F).\n  Proof.\n    apply minimizer_bool_coq.\n    intros n H1 (u & H2).\n    generalize (Rfun H1 H2); discriminate.\n    intros n Hn.\n    refine (match @HR n _ with\n      | exist _ u Hu => match u as m return R _ m -> _ with\n        | 0   => fun H => left H\n        | S v => fun H => right (ex_intro _ v H)\n        end Hu\n      end).\n    destruct Hn as [ Hn | (u & Hu) ].\n    - exists 0; auto.\n    - exists (S u); auto.\n  Defined.\n\nEnd minimizer.\n\nCheck minimizer_coq.\nPrint Assumptions minimizer_coq.\n\nExtraction \"minimizer.ml\" minimizer_bool_coq minimizer_coq.\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/minimizer_bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6961416029776486}}
{"text": "Require Import Arith.\nRequire Import List.\nImport ListNotations.\n\n(** On définit ici des fonctions d'indexage et d'insertion dans la mémoire\nqui tiennent compte de sa taille.\nAinsi, on empêche les accès en dehors du domaine autorisé. *)\n\nLemma zltz: 0 < 0 -> False.\nProof.\n  intros. contradict H. apply Lt.lt_irrefl.\nQed.\n\nLemma nltz: forall n: nat, n < 0 -> False.\nProof.\n  intros. contradict H. apply Lt.lt_n_0.\nQed.\n\nLemma predecessor_proof: forall {X: Type} (n: nat) (x: X) (xs: list X),\n  S n < length (x::xs) -> n < length xs.\nProof.\n  intros. simpl in H. apply Lt.lt_S_n. assumption.\nQed.\n\nFixpoint safe_nth {X: Type} (xs: list X) (n: nat): n < length xs -> X :=\n  match xs, n with\n  | [], _ => fun pf => match nltz n pf with end\n  | x::_, 0 => fun _ => x\n  | x::xs', S n' => fun pf => safe_nth xs' n' (predecessor_proof n' x xs' pf)\n  end.\n\nFixpoint safe_insert {X: Type} (xs: list X) (n: nat) (elt: X): n < length xs -> list X :=\n  match xs, n with\n    | nil, _ => fun pf => elt::nil\n    | h::t, 0 => fun _ => elt::t\n    | h :: t, S n' => fun pf => h :: safe_insert t n' elt (predecessor_proof n' h t pf)\n    end.\n\nDefinition insert' {A:Type} (l: list A) (n : nat) (elt : A)  :=\nmatch lt_dec n (length l) with\n  | left pf => Some (safe_insert l n elt pf)\n  | right _ => None\n  end.\n\nDefinition nth' {A:Type} (l: list A) (n : nat) :=\nmatch lt_dec n (length l) with\n  | left pf => Some (safe_nth l n pf)\n  | right _ => None\n  end.\n\nEval compute in insert' [1;2;3] 2 4.\nEval compute in nth' [1;2;3] 0.\n", "meta": {"author": "ebtaleb", "repo": "6502Coq", "sha": "e0dfca46375e411ccd0bfc53ab93b08480847694", "save_path": "github-repos/coq/ebtaleb-6502Coq", "path": "github-repos/coq/ebtaleb-6502Coq/6502Coq-e0dfca46375e411ccd0bfc53ab93b08480847694/Insert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.6961374242256788}}
{"text": "Set Implicit Arguments.\n\nHint Extern 1 (_ = _) => congruence.\n\n(* syntax *)\n\nInductive exp : Set :=\n| Zero   : exp\n| Succ   : exp -> exp\n| T      : exp\n| F      : exp\n| Pred   : exp -> exp             \n| If     : exp -> exp -> exp -> exp\n| IsZero : exp -> exp.\n\n\n(* values *)\n\nInductive bvalue : exp -> Prop :=\n| btrue  : bvalue T\n| bfalse : bvalue F.\n\nInductive nvalue : exp -> Prop :=\n| nzero  : nvalue Zero\n| nsucc  : forall n, nvalue n -> nvalue (Succ n).\n\nInductive value : exp -> Prop :=\n| Bvalue : forall e, bvalue e -> value e\n| Nvalue : forall e, nvalue e -> value e.\n\nHint Constructors bvalue nvalue value.\n\nReserved Notation \"e '==>' e1\" (at level 40).\n\nInductive step : exp -> exp -> Prop :=\n| ST_If_T\n  : forall e e', (If T e e') ==> e\n| ST_If_F\n  : forall e e', If F e e' ==> e'\n| ST_If\n  : forall e e' e1 e2,\n    e ==> e'                ->\n    If e e1 e2 ==> If e' e1 e2\n| ST_Succ\n  : forall e e',\n    e ==> e'                ->\n    (Succ e) ==> (Succ e')\n| ST_Pred_Zero\n  : Pred Zero ==> Zero\n| ST_Pred_Succ\n  : forall e,\n    nvalue e         ->\n    Pred (Succ e) ==> e\n| ST_Pred\n  : forall e e',\n    e ==> e'           ->\n    (Pred e) ==> (Pred e')\n| ST_IsZeroZero\n  : IsZero Zero ==> T\n| ST_IsZeroSucc\n  : forall e,\n    nvalue e           ->\n    IsZero (Succ e) ==> F\n| ST_IsZero\n  : forall e e',\n    e ==> e'               -> \n    (IsZero e) ==> (IsZero e')\nwhere \"e '==>' e1\" := (step e e1).\n\nHint Constructors step.\n\nDefinition normal_form e :=\n  ~ exists e', step e e'.\n\nDefinition stuck e :=\n  normal_form e /\\ ~ value e.\n\nHint Unfold normal_form stuck.\n\n(* first lemma *)\n\nLtac inverts H := inversion H ; clear H ; subst.\n\nLemma value_is_nf' : forall e, value e -> normal_form e.\nProof.\n  intros e Hv.\n  unfold normal_form.\n  intro contra.\n  induction e.\n  +\n    inverts contra.\n    inverts H.\n  +\n    inverts contra.\n    inverts Hv.\n    inverts H0.\n    inverts H0.\n    apply IHe.\n    auto.\n    inverts H.\n    exists e'.\n    auto.\n  +\n    inverts contra.\n    inverts H.\n  +\n    inverts contra.\n    inverts H.\n  +\n    inverts Hv.\n    inverts H.\n    inverts H.\n  +\n    inverts Hv.\n    inverts H.\n    inverts H.\n  +\n    inverts Hv.\n    inverts H.\n    inverts H.\nQed.\n\nLtac s :=\n      match goal with\n      | [ H : ex _ |- _ ] => destruct H\n      | [ H : Zero ==> _ |- _] => inverts H\n      | [ H : T ==> _ |- _] => inverts H\n      | [ H : F ==> _ |- _] => inverts H\n      | [ H : value (Pred _) |- _] => inverts H\n      | [ H : bvalue (Pred _) |- _] => inverts H\n      | [ H : nvalue (Pred _) |- _] => inverts H\n      | [ H : value (If _ _ _) |- _] => inverts H\n      | [ H : bvalue (If _ _ _) |- _] => inverts H\n      | [ H : nvalue (If _ _ _) |- _] => inverts H\n      | [ H : value (IsZero _) |- _] => inverts H\n      | [ H : bvalue (IsZero _) |- _] => inverts H\n      | [ H : nvalue (IsZero _) |- _] => inverts H\n      | [ H : value (Succ _) |- _] => inverts H\n      | [ H : bvalue (Succ _) |- _] => inverts H\n      | [ H : nvalue (Succ _) |- _] => inverts H\n      | [ H : (Succ _) ==> _ |- _ ] => inverts H\n      end.\n\nLemma value_is_nf : forall e, value e -> normal_form e.\nProof.\n  unfold normal_form ; intros e H contra ; induction e ;\n    try (repeat s) ; eauto.\nQed.\n\nHint Resolve value_is_nf.\n\nLtac s1 :=\n  match goal with\n  | [ H : (nvalue ?e) , H1 : ?e ==> _ |- _] =>\n    apply Nvalue in H ; apply value_is_nf in H ;\n    unfold normal_form in H ; apply ex_intro in H1 ; contradiction\n  end.  \n\nLemma step_deterministic\n  : forall e e', e ==> e' -> forall e'', e ==> e'' -> e' = e''.\nProof.\n  intros e e' H ; induction H ; intros e'' H' ;\n    inverts H' ; f_equal ; try repeat s ; auto ; try repeat s1.\nQed.\n\nReserved Notation \"e '==>*' e1\" (at level 40).\n\nInductive multi_step : exp -> exp -> Prop :=\n| mstep_refl\n  : forall e, e ==>* e\n| mstep_step\n  : forall e e1 e',\n    e ==> e1   ->\n    e1 ==>* e' ->\n    e ==>* e'\nwhere \"e '==>*' e1\" := (multi_step e e1).\n\nHint Constructors multi_step.\n\nLemma succ_multi_step : forall e e', e ==>* e' -> Succ e ==>* Succ e'.\nProof.\n  induction 1 ;\n     try match goal with\n         | [H : ?e ==> ?e1, IH : Succ ?e1 ==>* Succ ?e' |- _] =>\n           apply ST_Succ in H ; eapply mstep_step with (e1 := Succ e1) \n         end ; auto.\nQed.\n  \nHint Resolve succ_multi_step.\n\nReserved Notation \"e '==>>' e1\" (at level 40).\n\nInductive big_step : exp -> exp -> Prop :=\n| B_Value\n  : forall v, value v -> v ==>> v\n| B_If_True\n  : forall e e1 e11 e2,\n    e ==>> T ->\n    e1 ==>> e11 ->\n    (If e e1 e2) ==>> e11\n| B_If_False\n  : forall e e1 e2 e22,\n    e ==>> F ->\n    e2 ==>> e22 ->\n    (If e e1 e2) ==>> e22\n| B_Succ\n  : forall e nv,\n    nvalue nv ->\n    e ==>> nv ->\n    (Succ e) ==>> (Succ nv)\n| B_PredZero\n  : forall e,\n    e ==>> Zero ->\n    (Pred e) ==>> Zero\n| B_PredSucc\n  : forall e nv,\n    nvalue nv ->\n    e ==>> (Succ nv) ->\n    Pred e ==>> nv\n| B_IsZeroZero\n  : forall e,\n    e ==>> Zero ->\n    (IsZero e) ==>> T\n| B_IsZeroSucc\n  : forall e nv,\n    nvalue nv ->\n    e ==>> (Succ nv) ->\n    (IsZero e) ==>> F\nwhere \"e '==>>' e1\" := (big_step e e1).\n\nHint Constructors big_step.\n\nLtac bs := match goal with\n            | [H : T ==>> _ |- _] => inverts H\n            | [H : F ==>> _ |- _] => inverts H \n            | [H : Zero ==>> _ |- _] => inverts H\n            | [H : (Succ _) ==>> _ |- _] => inverts H\n            | [H : value _ |- _] => inverts H\n            | [H : bvalue (Succ _) |- _] => inverts H\n            | [H : nvalue (Succ _) |- _] => inverts H\n            | [H : (Pred _) ==>> _ |- _] => inverts H     \n            | [H : bvalue (Pred _) |- _] => inverts H\n            | [H : nvalue (Pred _) |- _] => inverts H\n            | [H : (If _ _ _) ==>> _ |- _] => inverts H     \n            | [H : bvalue (If _ _ _) |- _] => inverts H\n            | [H : nvalue (If _ _ _) |- _] => inverts H\n            | [H : (IsZero _) ==>> _ |- _] => inverts H     \n            | [H : bvalue (IsZero _) |- _] => inverts H\n            | [H : nvalue (IsZero _) |- _] => inverts H\n            | [ IH : forall v, ?e ==>> v -> forall v', ?e ==>> v' -> _\n                , H : ?e ==>> _, H1 : ?e ==>> _ |- _] =>\n              apply (IH _ H) in H1\n            end ; subst ; try f_equal ; auto.\n  \n\nLemma big_step_deterministic : forall e v, e ==>> v -> forall v', e ==>> v' -> v = v'.\nProof.\n  induction e ; intros ; repeat bs.\nQed.\n\n(* typing *)\n\nInductive type : Set :=\n| TBool : type\n| TNat  : type.\n\nReserved Notation \"e '<<-' t\" (at level 40).\n\nInductive has_type : exp -> type -> Prop :=\n| T_True\n  : T <<- TBool\n| T_False\n  : F <<- TBool\n| T_Zero\n  : Zero <<- TNat\n| T_Succ\n  : forall e,\n    e <<- TNat ->\n    (Succ e) <<- TNat\n| T_Pred\n  : forall e,\n    e <<- TNat  ->\n    (Pred e) <<- TNat\n| T_If\n  : forall e e' e'' t,\n    e <<- TBool ->\n    e' <<- t    ->\n    e'' <<- t   ->\n    (If e e' e'') <<- t\n| T_IsZero\n  : forall e,\n    e <<- TNat ->\n    (IsZero e) <<- TBool\nwhere \"e '<<-' t\" := (has_type e t).               \n\nHint Constructors has_type.\n\nLemma bool_canonical : forall e, e <<- TBool -> value e -> bvalue e.\nProof.\n  intros e H Hv ; inverts Hv ; inverts H ; repeat s ; auto.\nQed.\n\nLemma nat_canonical : forall e, e <<- TNat -> value e -> nvalue e. \nProof.\n  intros e H Hv ; inverts H ; inverts Hv ; repeat s ; auto.\nQed.\n\nHint Resolve bool_canonical nat_canonical.\n\nTheorem progress : forall e t, e <<- t -> value e \\/ exists e', e ==> e'.\nProof.\n  induction 1 ; try solve [left ; auto] ;                                    \n    try repeat (match goal with\n                | [H : _ \\/ _ |- _] => destruct H\n                | [H : ex _ |- _] => destruct H\n                | [H : value _ |- _] => inverts H\n                | [H : bvalue _ |- _] => inverts H\n                | [H : T <<- _ |- _] => inverts H\n                | [H : F <<- _ |- _] => inverts H\n                | [H : nvalue _ |- context[(Pred _)]] => inverts H\n                | [H : nvalue _ |- context[(IsZero _)]] => inverts H                   \n                | [H : ?e <<- TBool , H1 : nvalue ?e |- _] =>\n                  inverts H1 ; inverts H\n                end ; try solve [ right ; eexists ; eauto ] ; auto).\nQed.\n\nTheorem preservation : forall e t, e <<- t -> forall e', e ==> e' -> e' <<- t.\nProof.\n  induction 1 ; intros ; repeat (s ; eauto) ;\n    try repeat (match goal with\n                | [H : _ ==> _ |- _] => inverts H ; eauto\n                | [H : (Succ _) <<- _ |- _] => inverts H ; eauto  \n                end).\nQed.\n\n\n\n(* notations for subset types -- sig types *)\n\nNotation \"!\" := (False_rec _ _).\nNotation \"[ e ]\" := (exist _ e _).\n\n(* notations for sumbool types *)\n\nNotation \"'Yes'\" := (left _ _).\nNotation \"'No'\" := (right _ _).\nNotation \"'Reduce' x\" := (if x then Yes else No) (at level 50).\nNotation \"x || y\" := (if x then Yes else Reduce y).\n\n(* notations for sumor *)\n\nNotation \"!!\" := (inright _ _).\nNotation \"[|| x ||]\" := (inleft _ [x]).\n\nNotation \"x <-- e1 ; e2\" := (match e1 with\n                               | inright _ => !!\n                               | inleft (exist _ x _) => e2\n                             end)\n                              (right associativity, at level 60).\n\nNotation \"e1 ;;; e2\" := (if e1 then e2 else !!)\n                          (right associativity, at level 60).\n\nDefinition eq_ty_dec : forall (t t' : type), {t = t'} + {t <> t'}.\n  decide equality.\nDefined.\n\nTheorem has_type_det : forall e t, e <<- t -> forall t', e <<- t' -> t = t'.\nProof.\n  induction 1 ; intros t' Hc ; inverts Hc ; eauto.\nQed.\n\nHint Resolve has_type_det.\n\nDefinition typecheck : forall e, {t | e <<- t} + {forall t, ~ (e <<- t)}.\n  refine (fix tc (e : exp) : {t | e <<- t} + {forall t, ~ (e <<- t)} :=\n            match e as e' return e = e' -> {t | e' <<- t} + {forall t, ~ (e' <<- t)} with\n            | T  => fun _ => [|| TBool ||]\n            | F  => fun _ => [|| TBool ||]\n            | Zero  => fun _ => [|| TNat ||]\n            | Succ e => fun _ =>\n                          ty <-- tc e ;\n                          eq_ty_dec ty TNat ;;;\n                          [|| TNat ||]          \n            | Pred e => fun _ => \n                          ty <-- tc e ;\n                          eq_ty_dec ty TNat ;;;\n                          [|| TNat ||]          \n            | IsZero e => fun _ => \n                          ty <-- tc e ;\n                          eq_ty_dec ty TNat ;;;\n                          [|| TBool ||]          \n            | If e e1 e2 => fun _ =>\n                          ty <-- tc e ;\n                          ty1 <-- tc e1 ;\n                          ty2 <-- tc e2 ;\n                          eq_ty_dec ty TBool ;;;\n                          eq_ty_dec ty1 ty2  ;;;          \n                          [|| ty1 ||]\n            end eq_refl) ; clear tc ;\n           simpl in * ; subst ;\n             try (intro ; intro) ;\n             try (match goal with\n                  | [ H : _ <<- _ |- _] => inverts H\n                  end) ;\n                 try (match goal with\n                      | [ H : forall x, ~ (_ <<- _) |- False ] => eapply H ; eauto\n                    | [H : ?e <<- ?t , H1 : ?e <<- ?t' |- _] =>\n                      eapply (has_type_det H) in H1 ; subst\n                      end) ; eauto.\nDefined.  ", "meta": {"author": "rodrigogribeiro", "repo": "coqcourse", "sha": "1e39614285522cba5045b0a190e3bd19c560a2f7", "save_path": "github-repos/coq/rodrigogribeiro-coqcourse", "path": "github-repos/coq/rodrigogribeiro-coqcourse/coqcourse-1e39614285522cba5045b0a190e3bd19c560a2f7/code/semantics_sol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.6961374181640771}}
{"text": "(***************************************************************)\n(* Coq code for OCAP                                           *)\n(*                                                             *)\n(* Utilities for manipulating natural numbers                  *)\n(*                                                             *)\n(*                                                             *)\n(***************************************************************)\n\n(* $Id: IntBool.v 21 2012-08-16 14:14:35Z guoyu $ *)\n\nRequire Import ZArith.\nRequire Export Bool.\n\n(* *********************************************************** *)\n\nDefinition int := Z.\n\nOpen Scope Z_scope.\n\nTheorem int_eq_dec : forall a b : int, {a = b} + {a <> b}.\nProof.\n  apply Z_eq_dec.\nQed.\n\n(* *********************************************************** *)\n\nFixpoint blt_pos (p q : positive) {struct p} : bool :=\n  match (Pcompare p q Eq) with\n    | Lt => true \n    | _  => false\n  end.\n\nFixpoint blt_int (n m : int) {struct n} : bool :=\n  match n, m with\n    | Z0, Zpos p => true\n    | Zneg p, Z0 => true\n    | Zneg p, Zpos q => true\n    | Zneg p, Zneg q => blt_pos q p\n    | Zpos p, Zpos q => blt_pos p q\n    | _, _ => false\n  end.\n\nLemma blt_pos_irrefl : \n  forall p : positive, blt_pos p p = false.\nProof.\n  induction p; simpl; auto with arith.\n  rewrite Pcompare_refl; trivial.\n  rewrite Pcompare_refl; trivial.\nQed.\n\nLemma blt_irrefl :\n  forall a : int, blt_int a a = false.\nProof.\n  destruct a; simpl; auto with arith.\n  apply blt_pos_irrefl; trivial.\n  apply blt_pos_irrefl; trivial.\nQed.\n\nLemma blt_irrefl_Prop :\n  forall a : int, ~ (blt_int a a = true).\nProof.\n  induction a; simpl; auto with arith.\n  intro H. rewrite blt_pos_irrefl in H.\n  discriminate.\n  intro H; rewrite blt_pos_irrefl in H; discriminate.\nQed.\n\n(* *********************************************************** *)\n\nFixpoint beq_pos (p p' : positive) {struct p} : bool :=\n  match p, p' with\n    | x~0, x'~0 => andb true (beq_pos x x')\n    | p~1, p'~1 => andb true (beq_pos p p')\n    | 1, 1 => true \n    | _, _ => false\n  end %positive.\n\nFixpoint beq_int (z z' : int) {struct z} : bool :=\n  match z, z' with\n    | Z0, Z0 => true\n    | Zpos p, Zpos p' => beq_pos p p'\n    | Zneg p, Zneg p' => beq_pos p p'\n    | _, _ => false\n  end.\n\nLemma beq_int_true_eq : forall z z' : int, \n  beq_int z z' = true -> z = z'.\nProof.\n  intros.\n  induction z;destruct z';try inversion H;trivial.\n  clear -H1.\n  generalize dependent p0.\n  induction p.\n  intros.\n  destruct p0.\n  simpl in H1.\n  apply IHp in H1.\n  rewrite Zpos_xI.\n  rewrite Zpos_xI.\n  rewrite H1.\n  trivial.\n  inversion H1.\n  inversion H1.\n  intros.\n  destruct p0.\n  inversion H1.\n  simpl in H1.\n  apply IHp in H1.\n  rewrite Zpos_xO.\n  symmetry.\n  rewrite Zpos_xO.\n  rewrite H1.\n  trivial.\n  inversion H1.\n  intros.\n  destruct p0;try inversion H1;trivial.\n  generalize dependent p0.\n  induction p.\n  intros.\n  destruct p0.\n  simpl in H1.\n  apply IHp in H1.\n  rewrite Zneg_xI.\n  rewrite Zneg_xI.\n  rewrite H1;trivial.\n  simpl in H.\n  simpl.\n  assumption.\n  inversion H1.\n  inversion H1.\n  intros.\n  destruct p0.\n  inversion H1.\n  simpl in H1.\n  apply IHp in H1.\n  rewrite Zneg_xO.\n  rewrite Zneg_xO.\n  rewrite H1.\n  trivial.\n  simpl in H.\n  simpl.\n  assumption.\n  inversion H1.\n  intros.\n  destruct p0;inversion H1;trivial.\nQed.\n\nLemma beq_int_false_neq : forall z z' : int,\n  beq_int z z' = false -> z <> z'.\nProof.\n  intros z z' Hbeq Hz.\n  subst z'.\n  induction z;try inversion Hbeq;induction p;try apply IHp;try assumption;try inversion Hbeq.\nQed.\n\nLemma eq_beq_int_true : forall z z' : int, \n  z = z' -> beq_int z z' = true.\nProof.\n  intros.\n  subst z'.\n  induction z;trivial;induction p;try assumption;trivial.\nQed.\n\nLemma neq_beq_int_false : forall z z' : int, \n  z <> z' -> beq_int z z' = false.\nProof.\n  intros.\n  induction z.\n  destruct z'.\n  case H.\n  trivial.\n  trivial.\n  trivial.\n  destruct z'.\n  trivial.\n  simpl.\n  generalize dependent p0.\n  induction p.\n  intros.\n  destruct p0.\n  simpl.\n  apply IHp.\n  rewrite Zpos_xI in H.\n  rewrite Zpos_xI in H.\n  intro.\n  rewrite H0 in H.\n  case H;trivial.\n  trivial.\n  trivial.\n  intros.\n  destruct p0.\n  trivial.\n  trivial.\n  apply IHp.\n  intro.\n  apply H.\n  rewrite Zpos_xO.\n  symmetry.\n  rewrite Zpos_xO.\n  rewrite H0.\n  trivial.\n  trivial.\n  intros.\n  destruct p0;trivial;try case H;trivial.\n  trivial.\n  destruct z'.\n  trivial.\n  trivial.\n  simpl.\n  generalize dependent p0.\n  induction p.\n  intros.\n  destruct p0.\n  simpl.\n  apply IHp.\n  intro.\n  rewrite Zneg_xI in H.\n  rewrite Zneg_xI in H.\n  rewrite H0 in H.\n  case H;trivial.\n  trivial.\n  trivial.\n  intros.\n  destruct p0.\n  trivial.\n  simpl.\n  apply IHp.\n  intro.\n  rewrite Zneg_xO in H.\n  rewrite Zneg_xO in H.\n  rewrite H0 in H.\n  case H;trivial.\n  trivial.\n  intros.\n  destruct p0;trivial;try case H;trivial.\nQed.\n\nLemma beq_int_dec : forall a b,\n  {beq_int a b = true} + {beq_int a b = false}.\nProof.\n  intros; destruct (beq_int a b); [left |  right];  trivial.\nQed.\n\n(* *********************************************************** *)\n\n(* *********************************************************** *)\n\n(* *********************************************************** *)\n\n(* for beq int *)\n\nLtac beq_case_tac x y :=\n  let Hb := fresh \"Hb\" in\n    (destruct (beq_int_dec x y) as [Hb | Hb]; trivial).\n\nTactic Notation \"bint\" \"case\" constr(i) constr (i') := beq_case_tac i i'.\n(*\nLtac simpl_int_tac := \n  match goal with\n\n    (* beq rewrite directly *)\n    | [H : beq_int ?x ?y = ?f \n      |- context [(beq_int ?x ?y)]] =>\n       rewrite H; simpl_int_tac\n    | [H : beq_int ?x ?y = ?f,\n       H0 : context [(beq_int ?x ?y)] |- _ ] =>\n       rewrite H in H0; simpl_int_tac\n\n    (* beq_refl *)\n    | [ |- context [(beq_int ?x ?x)] ] =>\n      rewrite (beq_int_refl x); simpl_int_tac\n    | [H : context [(beq_int ?x ?x)] |- _ ] => \n      rewrite (beq_int_refl x) in H; simpl_int_tac\n\n    (* beq_sym *)\n    | [ H : beq_int ?x ?y = ?b \n        |- context [(beq_int ?y ?x)] ] =>\n      rewrite (beq_int_sym x y b H); simpl_int_tac\n    | [H : beq_int ?x ?y = ?b,\n       H0 : context [(beq_int ?y ?x)] |- _ ] => \n      rewrite (beq_int_sym x y b H) in H0; simpl_int_tac\n\n    (* (* neq -> beq *) *)\n    (* | [ H : ?x <> ?y |- context [(beq_int ?x ?y)] ] =>  *)\n    (*   rewrite (neq_beq_int_false x y H); simpl_int_tac *)\n    (* | [ H : ?x <> ?y,  *)\n    (*     H0 : context [(beq_int ?x ?y)] |- _ ] =>  *)\n    (*   rewrite (neq_beq_false x y H) in H0; simplbnat *)\n\n    (* | [ H : ?y <> ?x |- context [(beq_int ?x ?y)] ] =>  *)\n    (*   rewrite (neq_beq_false x y (sym_not_eq H)); simplbnat *)\n    (* | [ H : ?y <> ?x,  *)\n    (*     H0 : context [(beq_int ?x ?y)] |- _ ] =>  *)\n    (*   rewrite (neq_beq_false x y (sym_not_eq H)) in H0; simplbnat *)\n        \n    | [H : ?x = ?x |- _ ] => clear H; simpl_int_tac\n    | [H : true = false |- _ ] => discriminate H\n    | [H : false = true |- _ ] => discriminate H\n    | _ => idtac\n  end.\n\nTactic Notation \"bint\" \"simpl\" := simpl_int_tac.\n\nLtac rew_beq_tac H :=\n  match type of H with\n    | beq_int ?a ?b = true => \n      match goal with \n        | [ |- context [(?a)]] => \n          rewrite (beq_int_true_eq a b H)\n        | [ |- context [(?b)]] => \n          rewrite <- (beq_int_true_eq a b H)\n      end\n    | _ => fail\n  end.\n\nTactic Notation \"bint\" \"rewrite\" constr(t) := rew_beq_tac t.\n\nLtac rewH_beq_tac H H' :=\n  match type of H with\n    | beq_int ?a ?b = true => \n      match goal with \n        | [ H' : context [(?a)] |- _ ] => \n          rewrite (beq_int_true_eq a b H) in H'\n        | [ H' : context [(?b)] |- _ ] => \n          rewrite <- (beq_int_true_eq a b H) in H'\n      end\n    | _ => fail\n  end.\n\nTactic Notation \"bint\" \"rewrite\" constr(t) \"in\" hyp(H) := rewH_beq_tac t H.\n\n*)\n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/framework/auxlibs/IntBool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.6961374109883148}}
{"text": "Require Export List. Export ListNotations.\nRequire Import ZArith Lia.\nLocal Open Scope Z_scope.\nRequire Import VST.zlist.sublist.\n\nFixpoint repeat_op_nat{T: Type}(n: nat)(start: T)(op: T -> T): T := match n with\n| O => start\n| S m => op (repeat_op_nat m start op)\nend.\n\nDefinition repeat_op{T: Type}(n: Z)(start: T)(op: T -> T): T := repeat_op_nat (Z.to_nat n) start op.\n\nLemma repeat_op_step: forall {T: Type} (i: Z) (start: T) (op: T -> T),\n  0 <= i ->\n  repeat_op (i + 1) start op = op (repeat_op i start op).\nProof.\n  intros. unfold repeat_op. rewrite Z2Nat.inj_add by lia.\n  rewrite Nat.add_1_r. simpl. reflexivity.\nQed.\n\nFixpoint repeat_op_table_nat{T: Type}(n: nat)(start: T)(op: T -> T): list T := match n with\n| O => []\n| S m => (repeat_op_table_nat m start op) ++ [repeat_op_nat m start op]\nend.\n\nDefinition repeat_op_table{T: Type}(n: Z)(start: T)(op: T -> T): list T :=\n  repeat_op_table_nat (Z.to_nat n) start op.\n\nLemma repeat_op_table_step: forall {T: Type} (i: Z) (start: T) (op: T -> T),\n  0 <= i ->\n  repeat_op_table (i + 1) start op = (repeat_op_table i start op) ++ [repeat_op i start op].\nProof.\n  intros. unfold repeat_op_table. rewrite Z2Nat.inj_add by lia.\n  rewrite Nat.add_1_r. simpl. reflexivity.\nQed.\n\nLemma repeat_op_table_nat_length: forall {T: Type} (i: nat) (x: T) (f: T -> T),\n  length (repeat_op_table_nat i x f) = i.\nProof.\n  intros. induction i. reflexivity. simpl. rewrite app_length. simpl.\n  rewrite IHi. lia.\nQed.\n\nLemma repeat_op_table_length: forall {T: Type} (i: Z) (x: T) (f: T -> T),\n  0 <= i ->\n  Zlength (repeat_op_table i x f) = i.\nProof.\n  intros. unfold repeat_op_table.\n  rewrite Zlength_correct. rewrite repeat_op_table_nat_length.\n  apply Z2Nat.id. assumption.\nQed.\n\nLemma repeat_op_nat_id: forall {T: Type} (n: nat) (v: T),\n  repeat_op_nat n v id = v.\nProof.\n  intros. induction n.\n  - reflexivity.\n  - simpl. apply IHn.\nQed.\n\nLemma repeat_op_table_nat_id_app: forall {T: Type} (len1 len2: nat) (v: T),\n  repeat_op_table_nat (len1 + len2) v id \n  = repeat_op_table_nat len1 v id ++ repeat_op_table_nat len2 v id.\nProof.\n  intros. induction len2.\n  - simpl. replace (len1 + 0)%nat with len1 by lia. rewrite app_nil_r. reflexivity.\n  - replace (len1 + S len2)%nat with (S (len1 + len2)) by lia. simpl.\n    rewrite IHlen2. rewrite <- app_assoc. f_equal. f_equal. do 2 rewrite repeat_op_nat_id.\n    reflexivity.\nQed.\n\nLemma sublist_repeat_op_table_id: forall {T: Type} (lo n: Z) (v: T),\n  0 <= lo ->\n  0 <= n ->\n  sublist lo (lo + n) (repeat_op_table (lo + n) v id) = repeat_op_table n v id.\nProof.\n  intros.\n  replace (lo + n) with (Zlength (repeat_op_table (lo + n) v id)) at 1\n    by (apply repeat_op_table_length; lia).\n  rewrite sublist_skip by lia.\n  unfold repeat_op_table at 1. rewrite Z2Nat.inj_add by lia.\n  rewrite repeat_op_table_nat_id_app.\n  rewrite Zskipn_app1 by (\n    rewrite Zlength_correct;\n    rewrite repeat_op_table_nat_length;\n    rewrite Z2Nat.id; lia\n  ).\n  rewrite skipn_short; [ reflexivity | ].\n  rewrite repeat_op_table_nat_length. lia.\nQed.\n\nFixpoint fill_list_nat{T: Type}(n: nat)(f: nat -> T): list T := match n with\n| O => []\n| S m => (fill_list_nat m f) ++ [f m]\nend.\n\nDefinition fill_list{T: Type}(n: Z)(f: Z -> T): list T :=\n  fill_list_nat (Z.to_nat n) (fun i => f (Z.of_nat i)).\n\nLemma fill_list_step: forall {T: Type} (n: Z) (f: Z -> T),\n  0 <= n ->\n  fill_list (n + 1) f = fill_list n f ++ [f n].\nProof.\n  intros. unfold fill_list. rewrite Z2Nat.inj_add by lia.\n  rewrite Nat.add_1_r. simpl. rewrite Z2Nat.id by lia. reflexivity.\nQed.\n\nLtac eval_list l :=\n  let l' := eval hnf in l in lazymatch l' with\n  | ?h :: ?tl => let tl' := eval_list tl in constr:(h :: tl')\n  | (@nil ?T) => constr:(@nil T)\n  end.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/aes/list_utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.6960880678197892}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (lf2 : natural) (y : natural) (lf1 : natural)\n  : natural := plus (Succ Zero) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj206_coqofml_TtEQ0R.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6960191691462743}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) (y : natural) (lf1 : natural)\n  : natural := plus (Succ Zero) x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj245_coqofml_NJHl14.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802529509909, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6960191607891006}}
{"text": "Require Import List PeanoNat.\nImport ListNotations.\n\nFixpoint list_in (l: list nat) (n: nat) :=\n  match l with\n  | [] => false\n  | h :: t =>\n    match Nat.eqb n h with\n    | true => true\n    | false => list_in t n\n    end\n  end.\n\nFixpoint unique (l: list nat) :=\n  match l with\n  | [] => []\n  | h :: t =>\n    match list_in t h with\n    | true => unique t\n    | false => h :: unique t\n    end\n  end.\n\nDefinition task := forall l n, list_in l n = true -> count_occ Nat.eq_dec (unique l) n = 1.\n", "meta": {"author": "tzik", "repo": "top-prover", "sha": "3f92af1e76e437bee6b49152f11a6dfb3b730a61", "save_path": "github-repos/coq/tzik-top-prover", "path": "github-repos/coq/tzik-top-prover/top-prover-3f92af1e76e437bee6b49152f11a6dfb3b730a61/tasks/019/Problem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802350995703, "lm_q2_score": 0.7577943603346811, "lm_q1q2_score": 0.6960191422373264}}
{"text": "From LF Require Export Poly.\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\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 1*)\n(** Complete the following proof without using [simpl]. *)\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 3 = true ->\n     oddb 4 = true.\nProof.\n  intros. apply H. apply H0. Qed.\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = eqb n 5  ->\n     eqb (S (S n)) 7 = true.\nProof.\n  intros n H.\n  symmetry.\n  simpl.\n  apply H.  Qed.\n\n(*Exercise 2*)\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  intros. rewrite H. symmetry. apply rev_involutive. 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  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*)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o).\nProof.\n  intros. rewrite <- H. apply H0. Qed.\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n  inversion H.\n  reflexivity.\nQed.\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity. Qed.\n\nTheorem inversion_ex2 : forall (n m : nat),\n  [n] = [m] ->\n  n = m.\nProof.\n  intros n m H. inversion H as [Hnm]. reflexivity.  Qed.\n\n(*Exercise 4*)\nExample inversion_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  intros. inversion H0. reflexivity. Qed.\n\nTheorem beq_nat_0_l : forall n,\n   eqb 0 n = true -> n = 0.\nProof.\n  intros n.\n  destruct n as [| n'].\n  - (* n = 0 *)\n    intros H. reflexivity.\n  - (* n = S n' *)\n    simpl.\n    intros H. inversion H. Qed.\n\nTheorem inversion_ex4 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem inversion_ex5 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. inversion contra. Qed.\n\n(*Exercise 5*)\nExample inversion_ex6 : forall (X : Type)\n                          (x y z : X) (l j : list X),\n  x :: y :: l = [] ->\n  y :: l = z :: j ->\n  x = z.\nProof.\n  intros. 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),\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\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(*Exercise 6*)\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 as [| m'].\n    + reflexivity.\n    +  inversion eq.\n  - simpl. intros m eq.\n    destruct m as [| m'].\n    + simpl. inversion eq.\n    + apply f_equal.\n      apply IHn'. inversion eq. rewrite plus_comm in H0. symmetry in H0.\n    rewrite plus_comm in H0. simpl in H0. \n    inversion H0. reflexivity. Qed.\n\n\n(*Exercise 7: Use backward reasoning*)\nTheorem example1:\n  forall p q r,\n  (p -> q -> r) -> p -> q -> r.\n\nProof.\n  intros p q r H. apply H. Qed.\n  \n\n(*Exercise 8: Use forward reasoning*)\nTheorem example2:\n  forall p q r,\n  (p -> q -> r) -> p -> q -> r.\n\nProof.\n  intros. apply X in X0. apply X0. apply X1. Qed.\n\n(*Exercise 9: Don't use rewrite!*)\nTheorem length_nil:\n  forall (X: Type) (l: list X),\n  l = [] -> length l = 0.\n\nProof.\n  intros. inversion H. simpl. reflexivity. Qed.\n\n(*Exercise 10: *)\nTheorem xxx :\n  forall (X: Type) (l t: list X) (h: X),\n  l = h :: t -> leb 1 (length l) = true.\n\nProof.\n  intros. inversion H. simpl. reflexivity. Qed.\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/CA09.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.6959472016030058}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Omega Permutation.\n\nSet Implicit Arguments.\n\nInfix \"~p\" := (@Permutation _) (at level 80, no associativity).\n\nSection map.\n\n  Variables (X Y : Type) (f g : X -> Y).\n\n  Fact map_ext_dep l : (forall x, In x l -> f x = g x) -> map f l = map g l.\n  Proof. rewrite <- Forall_forall; induction 1; simpl; f_equal; auto. Qed.\n\n  Fact map_ext : (forall x, f x = g x) -> (forall l, map f l = map g l).\n  Proof. intros; apply map_ext_dep; auto. Qed.\n\nEnd map.\n\nDefinition list_length_split X n (ll : list X) : \n    { l : _ & { r | ll = l++r /\\ length l = n } } + { length ll < n }.\nProof.\n  revert ll; induction n as [ | n IHn ].\n  + left; exists nil, ll; auto.\n  + intros [ | x ll ].\n    * right; simpl; omega.\n    * destruct (IHn ll) as [ (l & r & H1 & H2) | H1 ].\n      - left; exists (x::l), r; split; subst; auto.\n      - right; simpl; omega.\nQed.\n\nDefinition list_length_prefix X n (ll : list X) : \n    n <= length ll -> { l : _ & { r | ll = l++r /\\ length l = n } }.\nProof. intro; destruct (list_length_split n ll); trivial; omega. Qed.\n\nSection list_length_eq_ind.\n\n  Variable (X : Type) (P : list X -> list X -> Prop)\n           (HP0 : P nil nil)\n           (HP1 : forall x y l m, length l = length m -> P l m -> P (x::l) (y::m)).\n\n  Theorem list_length_eq_ind l m : length l = length m -> P l m.\n  Proof.\n    intros H; cut (Forall2 (fun _ _ => True) l m).\n    + induction 1; auto.\n    + revert m H; induction l; intros [|]; auto; discriminate.\n  Qed.\n\nEnd list_length_eq_ind.\n\nSection app.\n\n  Variable X : Type.\n\n  Fact split_In ll l (x : X) r : ll = l++x::r -> In x ll.\n  Proof. intros; subst; apply in_or_app; simpl; auto. Qed.\n\n  Fact in_concat_iff ll (x : X) : In x (concat ll) <-> exists l, In x l /\\ In l ll.\n  Proof.\n    split.\n    * induction ll as [ | l ll IH ]; simpl.\n      - intros [].\n      - intros H; apply in_app_or in H.\n        destruct H as [ H | H ].\n        + exists l; split; auto.\n        + destruct IH as (l1 & ? & ?); auto; exists l1; auto.\n   * intros (l & H1 & H2).\n     apply in_split in H2.\n     destruct H2 as (ll1 & ll2 & ?); subst.\n     rewrite concat_app; apply in_or_app; simpl; right.\n     apply in_or_app; simpl; auto.\n  Qed.\n\nEnd app.\n\nSection incl.\n\n  Variable X : Type.\n  \n  Implicit Type l : list X.\n  \n  Fact incl_cons_linv l m x : incl (x::m) l -> In x l /\\ incl m l.\n  Proof.\n    intros H; split.\n    + apply H; left; auto.\n    + intros ? ?; apply H; right; auto.\n  Qed.\n\n  Fact incl_app_rinv l m p : incl m (l++p) -> exists m1 m2, m ~p m1++m2 /\\ incl m1 l /\\ incl m2 p.\n  Proof.\n    induction m as [ | x m IHm ].\n    + exists nil, nil; simpl; repeat split; auto; intros ? [].\n    + intros H.\n      apply incl_cons_linv in H.\n      destruct H as (H1 & H2).\n      destruct (IHm H2) as (m1 & m2 & H3 & H4 & H5).\n      apply in_app_or in H1; destruct H1.\n      * exists (x::m1), m2; repeat split; auto.\n        - constructor 2; auto.\n        - intros ? [|]; subst; auto.\n      * exists m1, (x::m2); repeat split; auto.\n        - apply Permutation_cons_app; auto.\n        - intros ? [|]; subst; auto.\n  Qed.\n  \n  Fact incl_cons_rinv x l m : incl m (x::l) -> exists m1 m2, m ~p m1 ++ m2 /\\ Forall (eq x) m1 /\\ incl m2 l.\n  Proof.\n    intros H.\n    apply (@incl_app_rinv (x::nil) _ l) in H.\n    destruct H as (m1 & m2 & H1 & H2 & H3).\n    exists m1, m2; repeat split; auto.\n    rewrite Forall_forall.\n    intros a Ha; apply H2 in Ha; destruct Ha as [ | [] ]; auto.\n  Qed.\n\n  Fact incl_right_cons_choose x l m : incl m (x::l) -> In x m \\/ incl m l.\n  Proof.\n    intros H.\n    apply incl_cons_rinv in H.\n    destruct H as ( m1 & m2 & H1 & H2 & H3 ); simpl in H1.\n    destruct m1 as [ | y m1 ].\n    + right.\n      intros u H; apply H3; revert H.\n      apply Permutation_in; auto.\n    + left.\n      apply Permutation_in with (1 := Permutation_sym H1).\n      rewrite Forall_forall in H2.\n      rewrite (H2 y); left; auto.\n  Qed.\n\n  Fact incl_left_right_cons x l y m : incl (x::l) (y::m) -> y = x  /\\ In y l \n                                                         \\/ y = x  /\\ incl l m\n                                                         \\/ In x m /\\ incl l (y::m).\n  Proof.\n    intros H; apply incl_cons_linv in H.\n    destruct H as [ [|] H2 ]; auto.\n    apply incl_right_cons_choose in H2; tauto.\n  Qed.\n\n  Fact perm_incl_left m1 m2 l: m1 ~p m2 -> incl m2 l -> incl m1 l.\n  Proof. intros H1 H2 ? H. apply H2; revert H; apply Permutation_in; auto. Qed.\n\n  Fact perm_incl_right m l1 l2: l1 ~p l2 -> incl m l1 -> incl m l2.\n  Proof.\n    intros H1 H2 ? ?; apply Permutation_in with (1 := H1), H2; auto.\n  Qed.\n  \nEnd incl.\n\nSection Permutation_tools.\n\n  Variable X : Type.\n  \n  Implicit Types (l : list X).\n  \n  Theorem Permutation_In_inv l1 l2: l1 ~p l2 -> forall x, In x l1 -> exists l, exists r, l2 = l++x::r.\n  Proof. intros H ? ?; apply in_split, Permutation_in with (1 := H); auto. Qed.\n  \n  Fact perm_in_head x l : In x l -> exists m, l ~p x::m.\n  Proof.\n    induction l as [ | y l IHl ].\n    + destruct 1.\n    + intros [ ? | H ]; subst.\n      * exists l; apply Permutation_refl.\n      * destruct (IHl H) as (m & Hm).\n        exists (y::m).\n        apply Permutation_trans with (2 := perm_swap _ _ _).\n        constructor 2; auto.\n  Qed.\n\nEnd Permutation_tools.\n\nSection Forall.\n\n  Variable (X : Type) (R : X -> Prop).\n\n  Fact Forall_app l m : Forall R l -> Forall R m -> Forall R (l++m).\n  Proof. induction 1; simpl; auto. Qed.\n\n  Fact Forall_map Y f l : Forall (fun y : Y => R (f y)) l -> Forall R (map f l).\n  Proof. induction 1; constructor; auto. Qed.\n\nEnd Forall.\n\nSection Forall2.\n\n  Variables (X Y : Type) (R : X -> Y -> Prop).\n\n  Fact Forall2_length l m : Forall2 R l m -> length l = length m.\n  Proof. induction 1; simpl; f_equal; auto. Qed.\n\n  Fact Forall2_nil_inv_right l : Forall2 R nil l -> l = nil.\n  Proof. inversion 1; auto. Qed.\n\n  Fact Forall2_cons_inv x l y m : Forall2 R (x::l) (y::m) -> R x y /\\ Forall2 R l m.\n  Proof. inversion 1; auto. Qed.\n\n  Fact Forall2_rev l m : Forall2 R l m -> Forall2 R (rev l) (rev m).\n  Proof. induction 1; simpl; auto; apply Forall2_app; simpl; auto. Qed.\n \n  Fact Forall2_app_inv l1 l2 m1 m2 : length l1 = length m1\n                                  -> Forall2 R (l1++l2) (m1++m2)\n                                  -> Forall2 R l1 m1 /\\ Forall2 R l2 m2.\n  Proof.\n    revert m1; induction l1 as [ | x l1 IH ]; intros [ | y m1 ]; \n      try discriminate; simpl; intros H1 H2; auto.\n    apply Forall2_cons_inv in H2.\n    destruct H2; destruct (IH m1); auto.\n  Qed.\n\n  Fact Forall2_snoc_inv l x m y : Forall2 R (l++x::nil) (m++y::nil) -> R x y /\\ Forall2 R l m.\n  Proof.\n    intros H.\n    apply Forall2_rev in H.\n    rewrite rev_app_distr, rev_app_distr in H; simpl in H.\n    apply Forall2_cons_inv in H; destruct H as [ H1 H ]; split; auto.\n    rewrite <- (rev_involutive l), <- (rev_involutive m); apply Forall2_rev; auto.\n  Qed.\n\n  Fact Forall2_2snoc_inv l a b m u v : Forall2 R (l++a::b::nil) (m++u::v::nil) \n                                    -> R a u /\\ R b v /\\ Forall2 R l m.\n  Proof.\n    replace (l++a::b::nil) with ((l++a::nil)++b::nil) by (rewrite app_ass; auto).\n    replace (m++u::v::nil) with ((m++u::nil)++v::nil) by (rewrite app_ass; auto).\n    intros H.\n    apply Forall2_snoc_inv in H; destruct H as (H1 & H).\n    apply Forall2_snoc_inv in H; tauto.\n  Qed.\n\n  Hint Resolve Forall2_app.\n\n  Fact Forall2_concat l m : Forall2 (Forall2 R) l m -> Forall2 R (concat l) (concat m).\n  Proof. induction 1; simpl; auto. Qed.\n\n  Fact Forall2_sym l m : Forall2 R l m -> Forall2 (fun y x => R x y) m l.\n  Proof. induction 1; constructor; auto. Qed.\n  \n  Fact Forall2_In_inv_left l m x : Forall2 R l m -> In x l -> exists y, In y m /\\ R x y.\n  Proof. induction 1; intros []; subst; firstorder. Qed.    \n\nEnd Forall2.\n\nHint Resolve Forall2_app.\n\nTactic Notation \"Forall2\" \"inv\" hyp(H) \"as\" ident(E) :=\n  match type of H with\n    | Forall2 _ nil _ => apply Forall2_nil_inv_right in H; rename H into E\n    | Forall2 _ (_::_) (_::_) => apply Forall2_cons_inv in H; destruct H as [ E H ]\n    | Forall2 _ (_++_::nil) (_++_::nil) => apply Forall2_snoc_inv in H; destruct H as [ E H ]\n    | Forall2 _ (_++_) (_++_) => apply Forall2_app_inv in H; [ destruct H as [ E H ] | ]\n  end.\n\nFact Forall2_map_left X Y Z (f : X -> Y) (R : Y -> Z -> Prop) l m : \n     Forall2 (fun x z => R (f x) z) l m -> Forall2 R (map f l) m.\nProof. induction 1; simpl; auto. Qed.\n\nFact Forall2_mono X Y (R S : X -> Y -> Prop) l m : \n        (forall x y, R x y -> S x y)\n     -> Forall2 R l m -> Forall2 S l m.\nProof. induction 2; auto. Qed.\n\nSection seq_an.\n\n  (* seq_an a n = [a;a+1;...;a+(n-1)] *)\n\n  Fixpoint seq_an a n: list nat :=\n    match n with\n      | 0    => nil\n      | S n  => a::seq_an (S a) n\n    end.\n\n  Fact seq_an_length a n : length (seq_an a n) = n.\n  Proof. revert a; induction n; simpl; intros; f_equal; auto. Qed.\n\n  Fact seq_an_spec a n x : In x (seq_an a n) <-> a <= x < a+n.\n  Proof. \n    revert x a; induction n as [ | n IHn ]; intros x a; simpl;\n      [ | rewrite IHn ]; omega.\n  Qed.\n\n  Fixpoint is_seq_from n (l : list nat) { struct l }: Prop :=\n    match l with  \n      | nil  => True\n      | x::l => n=x /\\ is_seq_from (S n) l\n    end.\n\n  Theorem is_seq_from_spec a l : is_seq_from a l <-> exists n, l = seq_an a n.\n  Proof.\n    revert a; induction l as [ | x l IH ]; intros a; simpl.\n    + split; auto; exists 0; auto.\n    + rewrite IH; split.\n      * intros (? & n & Hn); subst x; exists (S n); subst; auto.\n      * intros ([ | n ] & ?); subst; try discriminate.\n        simpl in H; inversion H; subst; split; auto.\n        exists n; auto.\n  Qed.\n\nEnd seq_an.\n\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/list_utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.6959471911340499}}
{"text": "Require Export FunctionProperties.\nRequire Export Ensembles.\nRequire Import EnsemblesImplicit.\nRequire Export EnsemblesSpec.\n\nDefinition inverse_image {X Y:Type} (f:X->Y) (T:Ensemble Y) : Ensemble X :=\n  [ x:X | In T (f x) ].\nHint Unfold inverse_image : sets.\n\nLemma inverse_image_increasing: forall {X Y:Type} (f:X->Y)\n  (T1 T2:Ensemble Y), Included T1 T2 ->\n  Included (inverse_image f T1) (inverse_image f T2).\nProof.\nintros.\nred; intros.\ndestruct H0.\nconstructor.\nauto.\nQed.\n\nLemma inverse_image_empty: forall {X Y:Type} (f:X->Y),\n  inverse_image f Empty_set = Empty_set.\nProof.\nintros.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H as [[]].\ndestruct H.\nQed.\n\nLemma inverse_image_full: forall {X Y:Type} (f:X->Y),\n  inverse_image f Full_set = Full_set.\nProof.\nintros.\napply Extensionality_Ensembles; split; red; intros;\n  constructor; constructor.\nQed.\n\nLemma inverse_image_intersection: forall {X Y:Type} (f:X->Y)\n  (T1 T2:Ensemble Y), inverse_image f (Intersection T1 T2) =\n  Intersection (inverse_image f T1) (inverse_image f T2).\nProof.\nintros.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H.\ninversion H.\nconstructor; constructor; trivial.\n\ndestruct H as [? [] []].\nconstructor; constructor; trivial.\nQed.\n\nLemma inverse_image_union: forall {X Y:Type} (f:X->Y)\n  (T1 T2:Ensemble Y), inverse_image f (Union T1 T2) =\n  Union (inverse_image f T1) (inverse_image f T2).\nProof.\nintros.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H.\ninversion H.\nleft; constructor; trivial.\nright; constructor; trivial.\n\nconstructor.\ndestruct H as [? []|? []].\nleft; trivial.\nright; trivial.\nQed.\n\nLemma inverse_image_complement: forall {X Y:Type} (f:X->Y)\n  (T:Ensemble Y), inverse_image f (Complement T) =\n  Complement (inverse_image f T).\nProof.\nintros.\napply Extensionality_Ensembles; split; red; intros.\nred; intro.\ndestruct H.\ndestruct H0.\ncontradiction H.\n\nconstructor.\nintro.\ncontradiction H.\nconstructor; trivial.\nQed.\n\nLemma inverse_image_composition: forall {X Y Z:Type} (f:Y->Z) (g:X->Y)\n  (U:Ensemble Z), inverse_image (fun x:X => f (g x)) U =\n  inverse_image g (inverse_image f U).\nProof.\nintros.\napply Extensionality_Ensembles; split; red; intros.\nconstructor; constructor.\ndestruct H.\nassumption.\n\ndestruct H; inversion H.\nconstructor; trivial.\nQed.\n\nHint Resolve @inverse_image_increasing : sets.\nHint Rewrite @inverse_image_empty @inverse_image_full\n  @inverse_image_intersection @inverse_image_union\n  @inverse_image_complement @inverse_image_composition : sets.\n\nRequire Import IndexedFamilies.\n\nLemma inverse_image_indexed_intersection :\n  forall {A X Y:Type} (f:X->Y) (F:IndexedFamily A Y),\n    inverse_image f (IndexedIntersection F) =\n    IndexedIntersection (fun a:A => inverse_image f (F a)).\nProof.\nintros.\napply Extensionality_Ensembles; split; red; intros.\n- destruct H.\n  inversion_clear H.\n  constructor. intros.\n  constructor.\n  apply H0.\n- destruct H.\n  constructor.\n  constructor. intros.\n  destruct (H a).\n  exact H0.\nQed.\n\nLemma inverse_image_indexed_union :\n  forall {A X Y:Type} (f:X->Y) (F:IndexedFamily A Y),\n    inverse_image f (IndexedUnion F) =\n    IndexedUnion (fun a:A => inverse_image f (F a)).\nProof.\nintros.\napply Extensionality_Ensembles; split; red; intros.\n- destruct H.\n  inversion_clear H.\n  exists a.\n  constructor.\n  exact H0.\n- destruct H.\n  inversion_clear H.\n  constructor.\n  exists a.\n  exact H0.\nQed.\n\nLemma inverse_image_fun\n  {X Y : Type}\n  (f : X -> Y)\n  (T : Ensemble Y) :\n  inverse_image f T = fun x => T (f x).\nProof.\n  apply Extensionality_Ensembles.\n  split;\n    red;\n    intros;\n    constructor + destruct H;\n    assumption.\nQed.\n\nLemma in_inverse_image\n  {X Y : Type}\n  (f : X -> Y)\n  (T : Ensemble Y)\n  (x : X) :\n  In T (f x) <-> In (inverse_image f T) x.\nProof.\n  rewrite inverse_image_fun.\n  split; auto.\nQed.\n\nLemma inverse_image_id\n  {X Y : Type}\n  {f : X -> Y}\n  {g : Y -> X} :\n  (forall y, f (g y) = y) ->\n  forall S,\n    inverse_image g (inverse_image f S) = S.\nProof.\n  intros Hfg S.\n  rewrite <- inverse_image_composition.\n  apply Extensionality_Ensembles.\n  split; red; intros.\n  - destruct H.\n    rewrite <- Hfg.\n    assumption.\n  - constructor.\n    rewrite Hfg.\n    assumption.\nQed.\n\nLemma inverse_image_empty_set {X Y : Type} (f : X -> Y) :\n  inverse_image f Empty_set = Empty_set.\nProof.\napply Extensionality_Ensembles.\nsplit; red; intros;\n  repeat destruct H.\nQed.\n\nLemma inverse_image_full_set {X Y : Type} (f : X -> Y) :\n  inverse_image f Full_set = Full_set.\nProof.\napply Extensionality_Ensembles.\nsplit; red; intros;\n  repeat constructor.\nQed.\n\nLemma inverse_image_union2 {X Y : Type} (f : X -> Y) (U V : Ensemble Y) :\n  inverse_image f (Union U V) = Union (inverse_image f U) (inverse_image f V).\nProof.\napply Extensionality_Ensembles.\nsplit; red; intros.\n- destruct H.\n  inversion H;\n    subst;\n  [ left | right ];\n    now constructor.\n- now inversion H;\n    destruct H0;\n    subst;\n    constructor;\n  [ left | right ].\nQed.\n\nLemma inverse_image_family_union\n  {X Y : Type}\n  {f : X -> Y}\n  {g : Y -> X}\n  (F : Family Y) :\n  (forall x, g (f x) = x) ->\n  (forall y, f (g y) = y) ->\n  inverse_image f (FamilyUnion F) = FamilyUnion (inverse_image (inverse_image g) F).\nProof.\n  intros Hgf Hfg.\n  apply Extensionality_Ensembles.\n  split; red; intros.\n  - apply in_inverse_image in H.\n    inversion H.\n    subst.\n    rewrite <- Hgf.\n    econstructor.\n    + constructor.\n      erewrite inverse_image_id.\n      * exact H0.\n      * exact Hfg.\n    + rewrite Hgf.\n      constructor.\n      assumption.\n  - destruct H.\n    apply in_inverse_image in H.\n    constructor.\n    econstructor.\n    + exact H.\n    + constructor.\n      rewrite Hgf.\n      assumption.\nQed.\n\nLemma inverse_image_family_union_image\n  {X Y : Type}\n  (f : X -> Y)\n  (F : Family Y) :\n  inverse_image f (FamilyUnion F) = FamilyUnion (Im F (inverse_image f)).\nProof.\napply Extensionality_Ensembles.\nsplit; red; intros;\n  inversion H;\n  inversion H0;\n  subst;\n  repeat econstructor;\n  eassumption + now destruct H1.\nQed.\n\nLemma inverse_image_singleton\n  {X Y : Type}\n  (f : X -> Y)\n  (g : Y -> X)\n  (T : Ensemble Y) :\n  (forall x, g (f x) = x) ->\n  (forall y, f (g y) = y) ->\n  inverse_image (inverse_image g) (Singleton T) = Singleton (inverse_image f T).\nProof.\n  intros Hgf Hfg.\n  rewrite inverse_image_fun.\n  apply Extensionality_Ensembles.\n  split;\n    red;\n    intros;\n    inversion H;\n    subst;\n    red;\n    rewrite inverse_image_id;\n    constructor + assumption.\nQed.\n\nLemma inverse_image_add\n  {X Y : Type}\n  (f : X -> Y)\n  (g : Y -> X)\n  (F : Family Y)\n  (T : Ensemble Y) :\n  (forall x, g (f x) = x) ->\n  (forall y, f (g y) = y) ->\n  inverse_image (inverse_image g) (Add F T) = Add (inverse_image (inverse_image g) F) (inverse_image f T).\nProof.\n  intros Hgf Hfg.\n  apply Extensionality_Ensembles.\n  rewrite inverse_image_fun, inverse_image_fun.\n  split;\n    red;\n    intros;\n    inversion H;\n    subst;\n    (left;\n     assumption) +\n    (right;\n     inversion H0;\n     rewrite inverse_image_id;\n     constructor + assumption).\nQed.\n\nLemma inverse_image_image_surjective\n  {X Y : Type}\n  (f : X -> Y)\n  (T : Ensemble Y) :\n  surjective f ->\n  Im (inverse_image f T) f = T.\nProof.\nintro.\napply Extensionality_Ensembles.\nsplit;\n  red;\n  intros.\n- inversion H0.\n  subst.\n  now destruct H1.\n- destruct (H x).\n  subst.\n  now repeat econstructor.\nQed.\n\nLemma inverse_image_surjective_singleton\n  {X Y : Type}\n  (f : X -> Y)\n  (T : Ensemble X) :\n  surjective f ->\n  Included (inverse_image (inverse_image f) (Singleton T)) (Singleton (Im T f)).\nProof.\nintros H U HU.\ndestruct HU.\ninversion H0.\nsubst.\nnow rewrite inverse_image_image_surjective.\nQed.\n\nLemma inverse_image_finite {X Y : Type} (f : X -> Y) (F : Family X) :\n  surjective f ->\n  Finite _ F ->\n  Finite _ (inverse_image (inverse_image f) F).\nProof.\nintros Hf H.\ninduction H.\n- rewrite inverse_image_empty_set.\n  constructor.\n- unfold Add.\n  rewrite inverse_image_union2.\n  pose proof (Singleton_is_finite _ (Im x f)).\n  now eapply Union_preserves_Finite,\n             Finite_downward_closed,\n             inverse_image_surjective_singleton.\nQed.\n\nLemma inverse_image_surjective_injective\n  {X Y : Type}\n  (f : X -> Y) :\n  surjective f ->\n  injective (inverse_image f).\nProof.\nintros H U V eq.\napply Extensionality_Ensembles.\nsplit; red; intros;\n  destruct (H x);\n  subst;\n  apply (in_inverse_image f);\n[ rewrite <- eq | rewrite eq ];\n  now constructor.\nQed.\n", "meta": {"author": "coq-community", "repo": "zorns-lemma", "sha": "aaf46b0c5f7857ce9211cbaaf36f184ca810e0e8", "save_path": "github-repos/coq/coq-community-zorns-lemma", "path": "github-repos/coq/coq-community-zorns-lemma/zorns-lemma-aaf46b0c5f7857ce9211cbaaf36f184ca810e0e8/InverseImage.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6959320787790767}}
{"text": "From Ssreflect Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice fintype.\nFrom MathComp Require Import div bigop ssralg finset fingroup zmodp poly ssrnum.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope ring_scope.\nImport GRing.Theory.\n\nImport Num.Theory.\n\nVariable R : realFieldType.\n\nRecord dist (A : finType) := mkDist {\n  pmf :> A -> R ;\n  pmf0 : forall a, 0 <= pmf a ;\n  pmf1 : \\sum_(a in A) pmf a = 1 }.\n\nDefinition dist_of {A : finType} := fun phT : phant (Finite.sort A) => dist A.\n\nNotation \"{ 'dist' T }\" := (dist_of (Phant T))\n  (at level 0, format \"{ 'dist'  T }\") : proba_scope.\n\nLocal Open Scope proba_scope.\n\nSection probability.\n\nVariable A : finType.\nVariable P : dist A.\n\nDefinition Pr (E : {set A}) := \\sum_(a in E) P a.\n\nEnd probability.\n\nModule ProdDist.\n\nSection local.\n\nVariables A B : finType.\nVariable P1 : dist A.\nVariable P2 : dist B.\n\nDefinition f := fun ab => P1 ab.1 * P2 ab.2.\n\nLemma f0 a : 0 <= f a.\nProof.\nrewrite /f.\napply mulr_ge0.\napply pmf0.\napply pmf0.\nQed.\n\nLemma f1 : \\sum_ab f ab = 1.\nProof.\nrewrite /f.\nrewrite -(pair_big xpredT xpredT (fun a b => P1 a * P2 b)) /=.\nrewrite -(pmf1 P1).\napply eq_bigr => a _.\nrewrite -big_distrr /=.\nrewrite pmf1.\nrewrite mulr1.\ndone.\nQed.\n\nDefinition d : {dist A * B} := mkDist f0 f1.\n\nEnd local.\n\nEnd ProdDist.\n\nLocal Notation \"P1 `x P2\" := (ProdDist.d P1 P2) (at level 9).\n\nFrom MathComp Require Import tuple finfun.\n\nLocal Notation \"t \\_ i\" := (tnth t i) (at level 9).\n\nModule TupleDist.\n\nSection local.\n\nVariable A : finType.\nVariable P : dist A.\nVariable n : nat.\n\nDefinition f (t : n.-tuple A) := \\prod_(i < n) P t \\_ i.\n\nLemma f0 t : 0 <= f t.\nProof.\nrewrite /f.\napply prodr_ge0.\nmove=> i _.\napply pmf0.\nQed.\n\nLemma f1 : \\sum_t f t = 1.\nProof.\nrewrite /f.\ntransitivity (\\sum_(f : {ffun 'I_n -> A}) \\prod_(i < n) P (f i)).\n  rewrite (reindex_onto (fun f : {ffun 'I_n -> A} => [tuple f i | i < n])\n                        (fun t => [ffun i : 'I_n => t \\_ i])) /=; last first.\n    move=> t _.\n    apply eq_from_tnth => i.\n    rewrite tnth_mktuple.\n    rewrite ffunE.\n    done.\n   apply eq_big.\n     move=> f.\n     apply/eqP/ffunP => /= i.\n     rewrite ffunE.\n     by rewrite tnth_mktuple.\n   move=> f /eqP Hf.\n   apply eq_bigr => i _.\n   by rewrite tnth_mktuple.\nrewrite -(@bigA_distr_bigA _ _ _ _ _ _ _ (fun (i : 'I_n) (a : A) => P a)) /=.\nrewrite big_const_ord.\nrewrite pmf1.\nelim: n => // m.\nby rewrite iterSr mulr1.\nQed.\n\nDefinition d : {dist n.-tuple A} := mkDist f0 f1.\n\nEnd local.\n\nEnd TupleDist.\n\nNotation \"P `^ n\" := (TupleDist.d P n) (at level 9).\n", "meta": {"author": "affeldt", "repo": "ssrcoq-kyoto2015", "sha": "e7dbd84e60fd2c24e8b025d60ca663f091800907", "save_path": "github-repos/coq/affeldt-ssrcoq-kyoto2015", "path": "github-repos/coq/affeldt-ssrcoq-kyoto2015/ssrcoq-kyoto2015-e7dbd84e60fd2c24e8b025d60ca663f091800907/bigop2_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6959320672601228}}
{"text": "Coq < Section Disjunction.\n\nCoq < Variables A B : Prop.\nA is assumed\nB is assumed\n\nCoq < Goal A \\/ B -> B \\/ A.\n1 subgoal\n  \n  A : Prop\n  B : Prop\n  ============================\n   A \\/ B -> B \\/ A\n\nUnnamed_thm < intro.\n1 subgoal\n  \n  A : Prop\n  B : Prop\n  H : A \\/ B\n  ============================\n   B \\/ A\n\nUnnamed_thm < elim H.\n2 subgoals\n  \n  A : Prop\n  B : Prop\n  H : A \\/ B\n  ============================\n   A -> B \\/ A\n\nsubgoal 2 is:\n B -> B \\/ A\n\nUnnamed_thm < intro H1.\n2 subgoals\n  \n  A : Prop\n  B : Prop\n  H : A \\/ B\n  H1 : A\n  ============================\n   B \\/ A\n\nsubgoal 2 is:\n B -> B \\/ A\n\nUnnamed_thm < right.\n2 subgoals\n  \n  A : Prop\n  B : Prop\n  H : A \\/ B\n  H1 : A\n  ============================\n   A\n\nsubgoal 2 is:\n B -> B \\/ A\n\nUnnamed_thm < exact H1.\n1 subgoal\n  \n  A : Prop\n  B : Prop\n  H : A \\/ B\n  ============================\n   B -> B \\/ A\n\nUnnamed_thm < auto.\nProof completed.\n\nUnnamed_thm < Qed.\nintro.\nelim H.\n intro H1.\n right.\n exact H1.\n \n auto.\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/practice03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.6959320574910529}}
{"text": "From Coq Require Import Reals ssreflect.\nRequire Import Coq.micromega.Lia.\n\nLemma ineq2: forall(k0 M: nat),\nk0 <= 2 ^ M - 1 -> k0 < 2^M.\nProof.\n  intros.\n  assert (2 ^ M - 1 < 2 ^ M).\n  2: {\n  pose proof Nat.le_lt_trans _ _ _ H H0.\n  exact H1.\n  }\n  eapply Nat.sub_lt.\n  {\n  pose proof Nat.eq_0_gt_0_cases M.\n  apply Nat.lt_eq_cases.\n  destruct H0.\n  {\n  right.\n  rewrite H0.\n  simpl.\n  reflexivity.\n  }\n  pose proof Nat.pow_gt_1 2 M.\n  left.\n  apply H1.\n  auto.\n  apply Nat.neq_0_lt_0.\n  exact H0.\n  }\n  auto.\nQed.\n\nLemma ineq3: forall(k0 M: nat),\n 2 ^ M - 1 < k0 ->  2^M <= k0.\nProof.\n  intros.\n  lia.\nQed.\n\nLemma ineq4:  forall(k M: nat),\n k <= 2 ^ S M - 1 -> k - 2 ^ M <= 2 ^ M - 1.\nProof.\n  intros.\n  assert (2 ^ S M - 1 - 2 ^ M = 2 ^ M - 1)%nat.\n  {\n  simpl.\n  lia.\n  }\n  rewrite <- H0.\n  lia.\nQed.\n\nLemma ineq5: forall (k : nat),\n  2 ^ k <> 0.\nProof.\n  intros.\n  apply Nat.pow_nonzero.\n  congruence.\nQed.\n\nLemma ineq6: forall (k0 M : nat),\n  2 ^ M <= 2 ^ M + k0.\nProof.\n  intros.\n  lia.\nQed.\n\n\nLemma ineq: forall(k0: nat) (M: nat),\n2^(S M - 1) - 1 < (k0 + 2 ^ (S M - 1)).\nProof.\n  intros.\n  eapply Nat.lt_le_trans.\n  {\n  eapply Nat.sub_lt.\n  {\n  pose proof Nat.eq_0_gt_0_cases M.\n  apply Nat.lt_eq_cases.\n  destruct H.\n  {\n  right.\n  rewrite H.\n  simpl.\n  reflexivity.\n  }\n  pose proof Nat.pow_gt_1 2 (S M - 1).\n  left.\n  apply H0.\n  auto.\n  apply Nat.neq_0_lt_0.\n  simpl.\n  lia.\n  }\n  auto.\n  }\n  apply le_plus_r.\nQed.\n\nLemma eq0: forall M,\n(2 * INR (2 ^ M))%R = (INR (2 * 2 ^ M)).\nProof.\n  intros.\n  pose proof mult_INR 2 (2 ^ M).\n  assert (INR 2 = 2)%R.\n  constructor.\n  rewrite H0 in H.\n  rewrite H.\n  reflexivity.\nQed.\n", "meta": {"author": "RealHMLi", "repo": "PLProject", "sha": "0d179313914074b9b4317d1234070d32c5386717", "save_path": "github-repos/coq/RealHMLi-PLProject", "path": "github-repos/coq/RealHMLi-PLProject/PLProject-0d179313914074b9b4317d1234070d32c5386717/Inequalities.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6959320506588098}}
{"text": "(* infotheo (c) AIST. R. Affeldt, M. Hagiwara, J. Senizergues. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq div fintype tuple.\nFrom mathcomp Require Import finfun bigop fingroup perm ssralg zmodp matrix mxalgebra.\nFrom mathcomp Require Import poly mxpoly.\nRequire Import num_occ.\n\nImport GRing.Theory.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nSection AboutF2.\n\n(** * Finite Field with Two Elements\n\n   Prime finite fields are directly available in SSReflect.\n\n*)\n\nLocal Open Scope ring_scope.\n\nCoercion F2_of_bool (b : bool) : 'F_2 := if b then 1 else 0.\n\nDefinition bool_of_F2 (x : 'F_2) : bool := x != 0.\n\nDefinition negF2 (x : 'F_2) : 'F_2 := (*F2_of_bool*) (x == 0%R).\n\nLemma F2_0_1 : forall x : 'F_2, x = (x != 0).\nProof. move=> x; rewrite -{1}[x]natr_Zp; case: x; case=> //; by case. Qed.\n\nLemma F2_0_1' : forall x : 'F_2, ((x == 1)%R = (x != 0)%R).\nProof. move=> x; rewrite -{1}[x]natr_Zp; case: x; case=> //; by case. Qed.\n\nLemma F2_0_1'' : forall x : 'F_2, ((x == 0)%R = (x != 1)%R).\nProof. move=> x; rewrite -{1}[x]natr_Zp; case: x; case=> //; by case. Qed.\n\n(* TODO: rename *)\nLemma F2_0_1''' : forall x : 'F_2, (bool_of_F2 x) = (x != 0)%R.\nProof. move=> x; rewrite -{1}[x]natr_Zp; case: x; case=> //; by case. Qed.\nLemma F2_0_1'''' : forall x : 'F_2, ~~ (bool_of_F2 x) = (x == 0)%R.\nProof. move=> x; rewrite -{1}[x]natr_Zp; case: x; case=> //; by case. Qed.\n\nCoInductive F2_spec : 'F_2 -> bool -> bool -> Prop :=\n| F2_0 : F2_spec 0 true false\n| F2_1 : F2_spec 1 false true.\n\nLemma F2P a : F2_spec a (a == 0) (a == 1).\nProof.\ncase/boolP : (a == 0).\n  move/eqP => ?; subst a.\n  rewrite (_ : 0 == 1 = false) //; by constructor.\nrewrite F2_0_1'' negbK => /eqP ?; subst a.\nrewrite eqxx; by constructor.\nQed.\n\nLemma F2_opp (x : 'F_2) : - x = x.\nProof.\nrewrite (F2_0_1 x) -[x]natr_Zp; case: x.\ncase; first by rewrite /= oppr0.\nby case.\nQed.\n\nLemma F2_add (x : 'F_2) : x + x = 0.\nProof. by rewrite -{2}(F2_opp x) addrN. Qed.\n\nLemma F2_of_bool_addr (x  y : 'F_2) :\n  (x + F2_of_bool (y == 0) = F2_of_bool ((x + y) == 0))%R.\nProof.\n  destruct (F2P x), (F2P y); simpl; try done.\n    by rewrite GRing.add0r.\n  by rewrite F2_add.\nQed.\n\nLemma F2_of_bool_0_inv : forall x, F2_of_bool x = 0 -> x = false.\nProof. by case. Qed.\n\nLemma F2_of_boolK : forall x, bool_of_F2 (F2_of_bool x) = x.\nProof. by case. Qed.\n\nLemma bool_of_F2K x : F2_of_bool (bool_of_F2 x) = x.\nProof. rewrite (F2_0_1 x); by case Heq : ( _ == _ ). Qed.\n\nLemma bool_of_F2_add_xor a b :\n  bool_of_F2 (a + b) = bool_of_F2 a (+) bool_of_F2 b.\nProof.\nrewrite (F2_0_1 a) (F2_0_1 b).\nby case Ha : ( a == _ ); case Hb : ( b == _ ).\nQed.\n\nLemma morph_F2_of_bool : {morph F2_of_bool : x y / x (+) y >-> (x + y) : 'F_2}.\nProof.\nmove=> x y /=.\nrewrite /F2_of_bool.\nmove: x y; case; case => //=; by rewrite F2_add.\nQed.\n\nLemma morph_bool_of_F2 : {morph bool_of_F2 : x y / (x + y) : 'F_2 >-> x (+) y}.\nProof. move=> x y /=; by rewrite bool_of_F2_add_xor. Qed.\n\nLocal Open Scope nat_scope.\n\nLemma num_occ_sum : forall (t : seq 'F_2),\n  num_occ 1%R t = \\sum_(i <- t) i.\nProof.\nelim => [ /= | /= h t ->].\n  by rewrite big_nil.\nrewrite big_cons.\nby case/F2P: h.\nQed.\n\nLocal Close Scope nat_scope.\n\n(** Properties of %$\\mathbb{F}_2$%#F_2# generalize to matrices over\n   %$\\mathbb{F}_2$%#F_2#: *)\n\nLemma F2_addmx m n (v : 'M['F_2]_(m, n)) : v + v = 0.\nProof. apply/matrixP => i j; by rewrite !mxE F2_add. Qed.\n\nLemma F2_mx_opp m n (v : 'M['F_2]_(m, n)) : - v = v.\nProof. apply/matrixP => i j; by rewrite mxE F2_opp. Qed.\n\nLemma F2_addmx0 m n (a b : 'M['F_2]_(m, n)) : a + b = 0 -> a = b.\nProof.\nmove/eqP.\nrewrite addr_eq0 F2_mx_opp.\nby move/eqP.\nQed.\n\n(** Properties of %$\\mathbb{F}_2$%#F_2# generalize to polynomials over\n   %$\\mathbb{F}_2$%#F_2#: *)\n\nLemma F2_poly_add (p : {poly 'F_2}) : p + p = 0.\nProof.\napply/polyP => i.\nby rewrite coef0 coef_add_poly F2_add.\nQed.\n\n(*Lemma poly_rV_scale n (a : 'F_2) (p : { poly 'F_2 }) :\n poly_rV (a%:P * p) = a%:M *m (@poly_rV _ n p).\nProof. by rewrite mul_polyC linearZ /= mul_scalar_mx. Qed.*)\n\n(* TODO: move *)\nFrom mathcomp Require Import polydiv.\n\n(*Lemma scale_modp (p d : {poly 'F_2}) (c : 'F_2) :\n  (c%:P * p) %% d = c%:P * (p %% d).\nProof.\nrewrite (F2_0_1 c); case: (_ =P _) => /= _.\n- by rewrite polyC0 2!mul0r mod0p.\n- by rewrite polyC1 2!mul1r.\nQed.*)\n\n(** Furthermore, polynomials over %$\\mathbb{F}_2$%#F_2# enjoy special properties\n    w.r.t. their coefficients, e.g.: *)\n\nLemma size_lead_coef_F2 (p : {poly 'F_2}) : size p <> O -> lead_coef p = 1.\nProof.\nmove=> sz_p.\nsuff goal : lead_coef p <> 0.\n  apply/eqP; rewrite F2_0_1'; by apply/eqP.\nrewrite lead_coefE.\ncontradict sz_p.\ncase: p sz_p => p /= last_p sz_p.\nrewrite (nth_last 0 p) in sz_p.\ncase: p last_p sz_p => //= last_p sz_p.\nby move/negbTE; move/eqP.\nQed.\n\nLemma size1_polyC_F2 (p : {poly 'F_2}) : size p = 1%nat -> p = 1%:P.\nProof.\nmove=> sz_1.\nhave sz_1' : (size p <= 1)%nat by rewrite sz_1.\nrewrite (size1_polyC sz_1').\ntransitivity (lead_coef p)%:P.\nby rewrite /lead_coef sz_1.\nby rewrite size_lead_coef_F2 // sz_1.\nQed.\n\nLemma lead_coef_F2 (p q : {poly 'F_2}) : size p = size q -> lead_coef p = lead_coef q.\nProof.\nmove=> X.\ncase/orP : (orbN (size p == O)) => [ | Y].\n- move/eqP => Y; rewrite Y in X.\n  symmetry in X; move/eqP: X; rewrite size_poly_eq0; move/eqP => ->.\n  by move/eqP: Y; rewrite size_poly_eq0; move/eqP => ->.\n- rewrite size_lead_coef_F2; last by apply/eqP.\n  rewrite size_lead_coef_F2 //; by rewrite -X; apply/eqP.\nQed.\n\nLemma monic_F_2 (p : { poly 'F_2 }) : p != 0 -> p \\is monic.\nProof.\nmove=> Hp; apply negbNE; apply/negP => H.\nhave {H} : lead_coef p == 0.\n  move/monicP/eqP : H; by rewrite F2_0_1' negbK.\nrewrite lead_coef_eq0.\nby apply/negP.\nQed.\n\nLemma row_nth n (i j : bitseq) : (size i <= n)%nat -> size j = size i ->\n  \\row_(i0 < n) F2_of_bool (nth false i i0) =\n  \\row_(i0 < n) F2_of_bool (nth false j i0) -> i = j.\nProof.\nmove=> Hi Hj /matrixP Heq.\napply/esym.\napply (@eq_from_nth _ false _ _ Hj) => i0 Hi0.\nrewrite Hj in Hi0.\nhave {Hi0}Hi0 : (i0 < n)%nat.\n  apply leq_ltn_trans with ((size i).-1)%nat;\n    rewrite -ltnS prednK //; by apply leq_ltn_trans with i0.\nmove: (Heq 0 (Ordinal Hi0)).\nrewrite !mxE /=; by do 2 case: nth.\nQed.\n\n(*Lemma col_nth n (i j : bitseq) : (size i <= n)%nat -> size j = size i ->\n  \\col_(i0 < n) F2_of_bool (nth false i i0) =\n  \\col_(i0 < n) F2_of_bool (nth false j i0) -> i = j.\nProof.\nmove=> Hi Hj /matrixP Heq.\napply/esym.\napply (@eq_from_nth _ false _ _ Hj) => i0 Hi0.\nrewrite Hj in Hi0.\nhave {Hi0}Hi0 : (i0 < n)%nat.\n  apply leq_ltn_trans with ((size i).-1)%nat;\n    rewrite -ltnS prednK //; by apply leq_ltn_trans with i0.\nmove: (Heq (Ordinal Hi0) 0).\nrewrite !mxE /=; by do 2 case: nth.\nQed.*)\n\nEnd AboutF2.\n", "meta": {"author": "johnbender", "repo": "shannon", "sha": "552c66f7c76ad687430f4fb8122a2a2b94b741ee", "save_path": "github-repos/coq/johnbender-shannon", "path": "github-repos/coq/johnbender-shannon/shannon-552c66f7c76ad687430f4fb8122a2a2b94b741ee/f2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.6957593841347359}}
{"text": "(** Supplement to Coq's axiomatized Reals *)\n  \nRequire Export Reals.\nRequire Import Psatz.\nRequire Export Program.\nRequire Export Summation.\n \n(** * Basic lemmas *)\n\n(** Relevant lemmas from Coquelicot's Rcomplements.v **)\n\nOpen Scope R_scope.\nLocal Coercion INR : nat >-> R.\n\nLemma Rle_minus_l : forall a b c,(a - c <= b <-> a <= b + c). Proof. intros. lra. Qed.\nLemma Rlt_minus_r : forall a b c,(a < b - c <-> a + c < b). Proof. intros. lra. Qed.\nLemma Rlt_minus_l : forall a b c,(a - c < b <-> a < b + c). Proof. intros. lra. Qed.\nLemma Rle_minus_r : forall a b c,(a <= b - c <-> a + c <= b). Proof. intros. lra. Qed.\nLemma Rminus_le_0 : forall a b, a <= b <-> 0 <= b - a. Proof. intros. lra. Qed.\nLemma Rminus_lt_0 : forall a b, a < b <-> 0 < b - a. Proof. intros. lra. Qed.\n\n(* Automation *)\n\nLemma Rminus_unfold : forall r1 r2, (r1 - r2 = r1 + -r2). Proof. reflexivity. Qed.\nLemma Rdiv_unfold : forall r1 r2, (r1 / r2 = r1 */ r2). Proof. reflexivity. Qed.\n\nHint Rewrite Rminus_unfold Rdiv_unfold Ropp_0 Ropp_involutive Rplus_0_l \n             Rplus_0_r Rmult_0_l Rmult_0_r Rmult_1_l Rmult_1_r : R_db.\nHint Rewrite <- Ropp_mult_distr_l Ropp_mult_distr_r : R_db.\nHint Rewrite Rinv_l Rinv_r sqrt_sqrt using lra : R_db.\n\nNotation \"√ n\" := (sqrt n) (at level 20) : R_scope.\n\n(** Other useful facts *)\n\nLemma Rmult_div_assoc : forall (x y z : R), x * (y / z) = x * y / z.\nProof. intros. unfold Rdiv. rewrite Rmult_assoc. reflexivity. Qed.\n\nLemma Rmult_div : forall r1 r2 r3 r4 : R, r2 <> 0 -> r4 <> 0 -> \n  r1 / r2 * (r3 / r4) = r1 * r3 / (r2 * r4). \nProof. intros. unfold Rdiv. rewrite Rinv_mult_distr; trivial. lra. Qed.\n\nLemma Rdiv_cancel :  forall r r1 r2 : R, r1 = r2 -> r / r1 = r / r2.\nProof. intros. rewrite H. reflexivity. Qed.\n\nLemma Rsum_nonzero : forall r1 r2 : R, r1 <> 0 \\/ r2 <> 0 -> r1 * r1 + r2 * r2 <> 0. \nProof.\n  intros.\n  replace (r1 * r1)%R with (r1 ^ 2)%R by lra.\n  replace (r2 * r2)%R with (r2 ^ 2)%R by lra.\n  specialize (pow2_ge_0 (r1)). intros GZ1.\n  specialize (pow2_ge_0 (r2)). intros GZ2.\n  destruct H.\n  - specialize (pow_nonzero r1 2 H). intros NZ. lra.\n  - specialize (pow_nonzero r2 2 H). intros NZ. lra.\nQed.\n\nLemma Rpow_le1: forall (x : R) (n : nat), 0 <= x <= 1 -> x ^ n <= 1.\nProof.\n  intros; induction n.\n  - simpl; lra.\n  - simpl.\n    rewrite <- Rmult_1_r.\n    apply Rmult_le_compat; try lra.\n    apply pow_le; lra.\nQed.\n    \n(* The other side of Rle_pow, needed below *)\nLemma Rle_pow_le1: forall (x : R) (m n : nat), \n  0 <= x <= 1 -> (m <= n)%nat -> x ^ n <= x ^ m.\nProof.\n  intros x m n [G0 L1] L.\n  remember (n - m)%nat as p.\n  replace n with (m+p)%nat in * by lia.\n  clear -G0 L1.\n  rewrite pow_add.\n  rewrite <- Rmult_1_r.\n  apply Rmult_le_compat; try lra.\n  apply pow_le; trivial.\n  apply pow_le; trivial.\n  apply Rpow_le1; lra.\nQed.\n\n\n(** * Square roots *)\n\nLemma pow2_sqrt : forall x:R, 0 <= x -> (√ x) ^ 2 = x.\nProof. intros; simpl; rewrite Rmult_1_r, sqrt_def; auto. Qed.\n\nLemma sqrt_pow : forall (r : R) (n : nat), (0 <= r)%R -> (√ (r ^ n) = √ r ^ n)%R.\nProof.\n  intros r n Hr.\n  induction n.\n  simpl. apply sqrt_1.\n  rewrite <- 2 tech_pow_Rmult.\n  rewrite sqrt_mult_alt by assumption.\n  rewrite IHn. reflexivity.\nQed.\n\nLemma pow2_sqrt2 : (√ 2) ^ 2 = 2.\nProof. apply pow2_sqrt; lra. Qed.\n\nLemma pown_sqrt : forall (x : R) (n : nat), \n  0 <= x -> √ x ^ (S (S n)) = x * √ x ^ n.\nProof.\n  intros. simpl. rewrite <- Rmult_assoc. rewrite sqrt_sqrt; auto.\nQed.  \n\nLemma sqrt_neq_0_compat : forall r : R, 0 < r -> √ r <> 0.\nProof. intros. specialize (sqrt_lt_R0 r). lra. Qed.\n\nLemma sqrt_inv : forall (r : R), 0 < r -> √ (/ r) = (/ √ r)%R.\nProof.\n  intros.\n  replace (/r)%R with (1/r)%R by lra.\n  rewrite sqrt_div_alt, sqrt_1 by lra.\n  lra.\nQed.  \n\nLemma sqrt2_div2 : (√ 2 / 2)%R = (1 / √ 2)%R.\nProof.\n   field_simplify_eq; try (apply sqrt_neq_0_compat; lra).\n   rewrite pow2_sqrt2; easy.\nQed.\n\nLemma sqrt2_inv : √ (/ 2) = (/ √ 2)%R.\nProof. apply sqrt_inv; lra. Qed.  \n\nLemma sqrt_sqrt_inv : forall (r : R), 0 < r -> (√ r * √ / r)%R = 1.\nProof. \n  intros. \n  rewrite sqrt_inv; trivial. \n  rewrite Rinv_r; trivial. \n  apply sqrt_neq_0_compat; easy.\nQed.\n\nLemma sqrt2_sqrt2_inv : (√ 2 * √ / 2)%R = 1.\nProof. apply sqrt_sqrt_inv. lra. Qed.\n\nLemma sqrt2_inv_sqrt2 : ((√ / 2) * √ 2)%R = 1.\nProof. rewrite Rmult_comm. apply sqrt2_sqrt2_inv. Qed.\n\nLemma sqrt2_inv_sqrt2_inv : ((√ / 2) * (√ / 2) = /2)%R.\nProof. \n  rewrite sqrt2_inv. field_simplify. \n  rewrite pow2_sqrt2. easy. \n  apply sqrt_neq_0_compat; lra. \nQed.\n\nLemma sqrt_1_unique : forall x, 1 = √ x -> x = 1.\nProof. intros. assert (H' := H). unfold sqrt in H. destruct (Rcase_abs x).\n       - apply R1_neq_R0 in H; easy. \n       - rewrite <- (sqrt_def x); try rewrite <- H'; lra.\nQed.\n\nLemma lt_ep_helper : forall (ϵ : R),\n  ϵ > 0 <-> ϵ / √ 2 > 0.\nProof. intros; split; intros. \n       - unfold Rdiv. \n         apply Rmult_gt_0_compat; auto; \n           apply Rinv_0_lt_compat; apply Rlt_sqrt2_0.\n       - rewrite <- (Rmult_1_r ϵ).\n         rewrite <- (Rinv_l (√ 2)), <- Rmult_assoc.\n         apply Rmult_gt_0_compat; auto. \n         apply Rlt_sqrt2_0.\n         apply sqrt2_neq_0.\nQed.\n\n\n\n\n(** Defining 2-adic valuation of an integer and properties *)\n\nOpen Scope Z_scope.\n\n(* could return nat, but int seem better *)\nFixpoint two_val_pos (p : positive) : Z :=\n  match p with \n  | xO p' => 1 + (two_val_pos p')\n  | _ => 0\n  end.\n\nFixpoint odd_part_pos (p : positive) : positive :=\n  match p with \n  | xO p' => odd_part_pos p'\n  | _ => p\n  end.\n\n\nLemma two_val_pos_mult : forall (p1 p2 : positive),\n  two_val_pos (p1 * p2) = two_val_pos p1 + two_val_pos p2.\nProof. induction p1; try easy; intros. \n       - replace (two_val_pos p1~1) with 0 by easy.\n         induction p2; try easy.\n         replace ((xI p1) * (xO p2))%positive with (xO ((xI p1) * p2))%positive by lia.\n         replace (two_val_pos (xO ((xI p1) * p2))%positive) with \n           (1 + (two_val_pos ((xI p1) * p2)%positive)) by easy.\n         rewrite IHp2; easy.\n       - replace (two_val_pos (xO p1)) with (1 + two_val_pos p1) by easy.\n         rewrite <- Z.add_assoc, <- IHp1.\n         replace ((xO p1) * p2)%positive with (xO (p1 * p2))%positive by lia.\n         easy.\nQed.\n\n(* TODO: prove at some point, don't actually need this now though. *)\n(*\nLemma two_val_pos_plus : forall (p1 p2 : positive),\n  two_val_pos (p1 + p2) >= Z.min (two_val_pos p1) (two_val_pos p2).\nProof. induction p1; try easy; intros.\n       - replace (two_val_pos p1~1) with 0 by easy.\n         induction p2; try easy.\n         replace ((xI p1) * (xO p2))%positive with (xO ((xI p1) * p2))%positive by lia.\n         replace (two_val_pos (xO ((xI p1) * p2))%positive) with \n           (1 + (two_val_pos ((xI p1) * p2)%positive)) by easy.\n         rewrite IHp2; easy.\n       - replace (two_val_pos (xO p1)) with (1 + two_val_pos p1) by easy.\n         rewrite <- Z.add_assoc, <- IHp1.\n         replace ((xO p1) * p2)%positive with (xO (p1 * p2))%positive by lia.\n         easy.\nQed. *)\n\n\n\n\n(* CHECK: maybe only need these for positives since we split on 0, pos, neg, anyways *)\n\nDefinition two_val (z : Z) : Z :=\n  match z with \n  | Z0 => 0 (* poorly defined on 0 *)\n  | Zpos p => two_val_pos p\n  | Zneg p => two_val_pos p\n  end.\n\n\nDefinition odd_part (z : Z) : Z :=\n  match z with \n  | Z0 => 0  (* poorly defined on 0 *)\n  | Zpos p => Zpos (odd_part_pos p)\n  | Zneg p => Zneg (odd_part_pos p)\n  end.\n\n\n(* useful for below since its easier to induct on nats rather than ints *)\nCoercion Z.of_nat : nat >-> Z.\n\n(* helper for the next section to go from nats to ints *)\nLemma Z_plusminus_nat : forall z : Z, \n  (exists n : nat, z = n \\/ z = - n)%Z.\nProof. intros. \n       destruct z.\n       - exists O; left; easy.\n       - exists (Pos.to_nat p); left; lia.\n       - exists (Pos.to_nat p); right; lia.\nQed.\n\nLemma two_val_mult : forall (z1 z2 : Z),\n  z1 <> 0 -> z2 <> 0 ->\n  two_val (z1 * z2) = two_val z1 + two_val z2.\nProof. intros.\n       destruct z1; destruct z2; simpl; try easy.\n       all : rewrite two_val_pos_mult; easy.\nQed.\n         \n(* TODO: should prove this, but don't actually need it. \nLemma two_val_plus : forall (z1 z2 : Z),\n  z1 <> 0 -> z2 <> 0 -> \n  z1 + z2 <> 0 ->\n  two_val (z1 + z2) >= Z.min (two_val z1) (two_val z2).\nProof. intros.\n       destruct z1; destruct z2; try easy.\n*)\n       \n\n\nLemma two_val_odd_part : forall (z : Z),\n  two_val (2 * z + 1) = 0.\nProof. intros. \n       destruct z; auto.\n       destruct p; auto.\nQed.\n\nLemma two_val_even_part : forall (a : Z),\n  a >= 0 -> two_val (2 ^ a) = a.\nProof. intros.\n       destruct (Z_plusminus_nat a) as [x [H0 | H0]]; subst.\n       induction x; auto.\n       replace (S x) with (1 + x)%nat by lia.\n       rewrite Nat2Z.inj_add, Z.pow_add_r, two_val_mult; try lia.\n       rewrite IHx; auto; try lia.\n       try (apply (Z.pow_nonzero 2 x); lia).\n       induction x; auto.\n       replace (S x) with (1 + x)%nat by lia.\n       rewrite Nat2Z.inj_add, Z.opp_add_distr, Z.pow_add_r, two_val_mult; try lia.\nQed.\n\nLemma twoadic_nonzero : forall (a b : Z),\n  a >= 0 -> 2^a * (2 * b + 1) <> 0.\nProof. intros. \n       apply Z.neq_mul_0; split; try lia;\n       try (apply Z.pow_nonzero; lia).\nQed.\n\nLemma get_two_val : forall (a b : Z),\n  a >= 0 -> \n  two_val (2^a * (2 * b + 1)) = a.\nProof. intros. \n       rewrite two_val_mult; auto.\n       rewrite two_val_odd_part, two_val_even_part; try lia.\n       apply Z.pow_nonzero; try lia.\n       lia.\nQed.       \n\nLemma odd_part_reduce : forall (a : Z),\n  odd_part (2 * a) = odd_part a.\nProof. intros.\n       induction a; try easy.\nQed.\n\nLemma get_odd_part : forall (a b : Z),\n  a >= 0 -> \n  odd_part (2^a * (2 * b + 1)) = 2 * b + 1.\nProof. intros. \n       destruct (Z_plusminus_nat a) as [x [H0 | H0]]; subst.\n       induction x; try easy.\n       - replace (2 ^ 0%nat * (2 * b + 1)) with (2 * b + 1) by lia.\n         destruct b; simpl; auto.\n         induction p; simpl; easy.\n       - replace (2 ^ S x * (2 * b + 1)) with (2 * (2 ^ x * (2 * b + 1))).\n         rewrite odd_part_reduce, IHx; try lia.\n         replace (S x) with (1 + x)%nat by lia.\n         rewrite Nat2Z.inj_add, Z.pow_add_r; try lia.\n       - destruct x; try easy.\n         replace (2 ^ (- 0%nat) * (2 * b + 1)) with (2 * b + 1) by lia.\n         destruct b; simpl; auto.\n         induction p; simpl; easy.\nQed.       \n\nLemma break_into_parts : forall (z : Z),\n  z <> 0 -> exists a b, a >= 0 /\\ z = (2^a * (2 * b + 1)).\nProof. intros. \n       destruct z; try easy.\n       - induction p.\n         + exists 0, (Z.pos p); try easy.\n         + destruct IHp as [a [b [H0 H1]]]; try easy.\n           exists (1 + a), b.\n           replace (Z.pos (xO p)) with (2 * Z.pos p) by easy.\n           split; try lia.\n           rewrite H1, Z.pow_add_r; try lia.\n         + exists 0, 0; split; try lia.\n       - induction p.\n         + exists 0, (Z.neg p - 1); try easy; try lia.\n         + destruct IHp as [a [b [H0 H1]]]; try easy.\n           exists (1 + a), b.\n           replace (Z.neg (xO p)) with (2 * Z.neg p) by easy.\n           split; try lia.\n           rewrite H1, Z.pow_add_r; try lia.\n         + exists 0, (-1); split; try lia.\nQed.\n\nLemma twoadic_breakdown : forall (z : Z),\n  z <> 0 -> z = (2^(two_val z)) * (odd_part z).\nProof. intros. \n       destruct (break_into_parts z) as [a [b [H0 H1]]]; auto.\n       rewrite H1, get_two_val, get_odd_part; easy.\nQed.\n\nLemma odd_part_pos_odd : forall (p : positive),\n  (exists p', odd_part_pos p = xI p') \\/ (odd_part_pos p = xH).\nProof. intros.\n       induction p.\n       - left; exists p; easy. \n       - destruct IHp.\n         + left. \n           destruct H.\n           exists x; simpl; easy.\n         + right; simpl; easy.\n       - right; easy.\nQed.\n\nLemma odd_part_0 : forall (z : Z),\n  odd_part z = 0 -> z = 0.\nProof. intros.\n       destruct z; simpl in *; easy.\nQed.\n\nLemma odd_part_odd : forall (z : Z),\n  z <> 0 -> \n  2 * ((odd_part z - 1) / 2) + 1 = odd_part z.\nProof. intros. \n       rewrite <- (Zdiv.Z_div_exact_full_2 _ 2); try lia.\n       destruct z; try easy; simpl;\n         destruct (odd_part_pos_odd p).\n       - destruct H0; rewrite H0; simpl.\n         rewrite Pos2Z.pos_xO, Zmult_comm, Zdiv.Z_mod_mult.\n         easy.\n       - rewrite H0; easy.\n       - destruct H0; rewrite H0; simpl.\n         rewrite (Pos2Z.neg_xO (Pos.succ x)), Zmult_comm, Zdiv.Z_mod_mult. \n         easy.\n       - rewrite H0; easy. \nQed.\n\nLemma two_val_ge_0 : forall (z : Z),\n  two_val z >= 0.\nProof. intros. \n       destruct z; simpl; try lia.\n       - induction p; try (simpl; lia). \n         replace (two_val_pos p~0) with (1 + two_val_pos p) by easy.\n         lia. \n       - induction p; try (simpl; lia). \n         replace (two_val_pos p~0) with (1 + two_val_pos p) by easy.\n         lia. \nQed.\n     \n\n\n\n(*\n *\n *\n *)\n\n\nClose Scope Z_scope.\n\n\n(** proving that sqrt2 is irrational! *)\n\n\n(* note that the machinery developed in the previous section makes this super easy, \n   although does not generalize for other primes *)\nLemma two_not_square : forall (a b : Z),\n  (b <> 0)%Z -> \n  ~ (a*a = b*b*2)%Z.\nProof. intros.  \n       unfold not; intros. \n       destruct (Z.eq_dec a 0); try lia. \n       apply (f_equal_gen two_val two_val) in H0; auto.\n       do 3 (rewrite two_val_mult in H0; auto); try lia.\n       replace (two_val 2) with 1%Z in H0 by easy.\n       lia. \nQed.\n\n\nTheorem sqrt2_irrational : forall (a b : Z),\n  (b <> 0)%Z -> ~ (IZR a = (IZR b) * √ 2).\nProof. intros. \n       apply (two_not_square a b) in H.\n       unfold not; intros; apply H.\n       apply (f_equal_gen (fun x => x * x) (fun x => x * x)) in H0; auto.\n       rewrite Rmult_assoc, (Rmult_comm (√ 2)), Rmult_assoc, \n         sqrt_def, <- Rmult_assoc in H0; try lra.\n       repeat rewrite <- mult_IZR in H0.\n       apply eq_IZR in H0.\n       easy.\nQed.\n\n\nCorollary one_sqrt2_Rbasis : forall (a b : Z),\n  (IZR a) + (IZR b) * √2 = 0 -> \n  (a = 0 /\\ b = 0)%Z.\nProof. intros. \n       destruct (Req_dec (IZR b) 0); subst.\n       split.\n       rewrite H0, Rmult_0_l, Rplus_0_r in H.\n       all : try apply eq_IZR; auto.\n       apply Rplus_opp_r_uniq in H; symmetry in H.\n       assert (H' : b <> 0%Z).\n       unfold not; intros; apply H0.\n       rewrite H1; auto.\n       apply (sqrt2_irrational (-a) b) in H'.\n       rewrite Ropp_Ropp_IZR in H'.\n       easy.\nQed.\n\n\n\n(* Automation *)\nLtac R_field_simplify := repeat field_simplify_eq [pow2_sqrt2 sqrt2_inv].\nLtac R_field := R_field_simplify; easy.\n\n(** * Trigonometry *)\n\nLemma sin_upper_bound_aux : forall x : R, 0 < x < 1 -> sin x <= x.\nProof.\n  intros x H.\n  specialize (SIN_bound x) as B.\n    destruct (SIN x) as [_ B2]; try lra.\n    specialize PI2_1 as PI1. lra.\n    unfold sin_ub, sin_approx in *.\n    simpl in B2.\n    unfold sin_term at 1 in B2.\n    simpl in B2.\n    unfold Rdiv in B2.\n    rewrite Rinv_1, Rmult_1_l, !Rmult_1_r in B2.\n    (* Now just need to show that the other terms are negative... *)\n    assert (sin_term x 1 + sin_term x 2 + sin_term x 3 + sin_term x 4 <= 0); try lra.\n    unfold sin_term.\n    remember (INR (fact (2 * 1 + 1))) as d1.\n    remember (INR (fact (2 * 2 + 1))) as d2.\n    remember (INR (fact (2 * 3 + 1))) as d3.\n    remember (INR (fact (2 * 4 + 1))) as d4.\n    assert (0 < d1) as L0.\n    { subst. apply lt_0_INR. apply lt_O_fact. }\n    assert (d1 <= d2) as L1.\n    { subst. apply le_INR. apply fact_le. simpl; lia. }\n    assert (d2 <= d3) as L2.\n    { subst. apply le_INR. apply fact_le. simpl; lia. }\n    assert (d3 <= d4) as L3.\n    { subst. apply le_INR. apply fact_le. simpl; lia. }\n    simpl.    \n    ring_simplify.\n    assert ( - (x * (x * (x * 1)) / d1) + x * (x * (x * (x * (x * 1)))) / d2 <= 0).\n    rewrite Rplus_comm.\n    apply Rle_minus.\n    field_simplify; try lra.\n    assert (x ^ 5 <= x ^ 3).\n    { apply Rle_pow_le1; try lra; try lia. }\n    apply Rmult_le_compat; try lra.\n    apply pow_le; lra.\n    left. apply Rinv_0_lt_compat. lra.\n    apply Rinv_le_contravar; lra.\n    unfold Rminus.\n    assert (- (x * (x * (x * (x * (x * (x * (x * 1)))))) / d3) +\n            x * (x * (x * (x * (x * (x * (x * (x * (x * 1)))))))) / d4 <= 0).\n    rewrite Rplus_comm.\n    apply Rle_minus.\n    field_simplify; try lra.\n    assert (x ^ 9 <= x ^ 7).\n    { apply Rle_pow_le1; try lra; try lia. }\n    apply Rmult_le_compat; try lra.\n    apply pow_le; lra.\n    left. apply Rinv_0_lt_compat. lra.\n    apply Rinv_le_contravar; lra.\n    lra.\nQed.\n\nLemma sin_upper_bound : forall x : R, Rabs (sin x) <= Rabs x.\nProof.\n  intros x.  \n  specialize (SIN_bound x) as B.\n  destruct (Rlt_or_le (Rabs x) 1).\n  (* abs(x) > 1 *)\n  2:{ apply Rabs_le in B. lra. }\n  destruct (Rtotal_order x 0) as [G | [E| L]].\n  - (* x < 0 *)\n    rewrite (Rabs_left x) in * by lra.\n    rewrite (Rabs_left (sin x)).\n    2:{ apply sin_lt_0_var; try lra.\n        specialize PI2_1 as PI1.\n        lra. }\n    rewrite <- sin_neg.\n    apply sin_upper_bound_aux.\n    lra.\n  - (* x = 0 *)\n    subst. rewrite sin_0. lra.\n  - rewrite (Rabs_right x) in * by lra.\n    rewrite (Rabs_right (sin x)).\n    2:{ apply Rle_ge.\n        apply sin_ge_0; try lra.\n        specialize PI2_1 as PI1. lra. }\n    apply sin_upper_bound_aux; lra.\nQed.    \n\nHint Rewrite sin_0 sin_PI4 sin_PI2 sin_PI cos_0 cos_PI4 cos_PI2 \n             cos_PI sin_neg cos_neg : trig_db.\n\n(** * glb support *) \n\nDefinition is_lower_bound (E:R -> Prop) (m:R) := forall x:R, E x -> m <= x.\n\nDefinition bounded_below (E:R -> Prop) := exists m : R, is_lower_bound E m.\n\nDefinition is_glb (E:R -> Prop) (m:R) :=\n  is_lower_bound E m /\\ (forall b:R, is_lower_bound E b -> b <= m).\n\nDefinition neg_Rset (E : R -> Prop) :=\n  fun r => E (-r).\n\nLemma lb_negset_ub : forall (E : R -> Prop) (b : R),\n  is_lower_bound E b <-> is_upper_bound (neg_Rset E) (-b).\nProof. unfold is_lower_bound, is_upper_bound, neg_Rset; split; intros.\n       - apply H in H0; lra. \n       - rewrite <- Ropp_involutive in H0. \n         apply H in H0; lra.\nQed.\n\nLemma ub_negset_lb : forall (E : R -> Prop) (b : R),\n  is_upper_bound E b <-> is_lower_bound (neg_Rset E) (-b).\nProof. unfold is_lower_bound, is_upper_bound, neg_Rset; split; intros.\n       - apply H in H0; lra. \n       - rewrite <- Ropp_involutive in H0. \n         apply H in H0; lra.\nQed.\n\nLemma negset_bounded_above : forall (E : R -> Prop),\n  bounded_below E -> (bound (neg_Rset E)).\nProof. intros. \n       destruct H.\n       exists (-x).\n       apply lb_negset_ub; easy.\nQed.\n\nLemma negset_glb : forall (E : R -> Prop) (m : R),\n  is_lub (neg_Rset E) m -> is_glb E (-m).\nProof. intros.  \n       destruct H; split. \n       - apply lb_negset_ub.\n         rewrite Ropp_involutive; easy. \n       - intros. \n         apply lb_negset_ub in H1.\n           apply H0 in H1; lra.\nQed.\n\nLemma glb_completeness :\n  forall E:R -> Prop,\n    bounded_below E -> (exists x : R, E x) -> { m:R | is_glb E m }.\nProof. intros.  \n       apply negset_bounded_above in H.\n       assert (H' : exists x : R, (neg_Rset E) x).\n       { destruct H0; exists (-x).\n         unfold neg_Rset; rewrite Ropp_involutive; easy. }\n       apply completeness in H'; auto.\n       destruct H' as [m [H1 H2] ].\n       exists (-m).\n       apply negset_glb; easy.\nQed.\n\n\n\n(** * Showing that R is a field, and a vector space over itself *)\n\nGlobal Program Instance R_is_monoid : Monoid R := \n  { Gzero := 0\n  ; Gplus := Rplus\n  }.\nSolve All Obligations with program_simpl; try lra.\n\nGlobal Program Instance R_is_group : Group R :=\n  { Gopp := Ropp }.\nSolve All Obligations with program_simpl; try lra.\n\nGlobal Program Instance R_is_comm_group : Comm_Group R.\nSolve All Obligations with program_simpl; lra. \n\nGlobal Program Instance R_is_ring : Ring R :=\n  { Gone := 1\n  ; Gmult := Rmult\n  }.\nSolve All Obligations with program_simpl; try lra. \nNext Obligation. try apply Req_EM_T. Qed.\n\n\nGlobal Program Instance R_is_comm_ring : Comm_Ring R.\nSolve All Obligations with program_simpl; lra. \n                                                     \nGlobal Program Instance R_is_field : Field R :=\n  { Ginv := Rinv }.\nNext Obligation. \n  rewrite Rinv_r; easy.\nQed.\n\nGlobal Program Instance R_is_module_space : Module_Space R R :=\n  { Vscale := Rmult }.\nSolve All Obligations with program_simpl; lra. \n\n\nGlobal Program Instance R_is_vector_space : Vector_Space R R.  \n\n\n\n(** * some big_sum lemmas specific to R *)\n\nLemma Rsum_le : forall (f g : nat -> R) (n : nat),\n  (forall i, (i < n)%nat -> f i <= g i) ->\n  (big_sum f n) <= (big_sum g n).\nProof. induction n as [| n']; simpl; try lra.  \n       intros.\n       apply Rplus_le_compat.\n       apply IHn'; intros. \n       all : apply H; try lia. \nQed.\n\nLemma Rsum_ge_0 : forall (f : nat -> R) (n : nat),\n  (forall i, (i < n)%nat -> 0 <= f i) ->\n  0 <= big_sum f n.\nProof. induction n as [| n'].\n       - intros; simpl; lra. \n       - intros. simpl; apply Rplus_le_le_0_compat.\n         apply IHn'; intros; apply H; lia. \n         apply H; lia. \nQed.\n", "meta": {"author": "inQWIRE", "repo": "QuantumLib", "sha": "d97ea40581961d7b53291a4a3dc7885fe7428060", "save_path": "github-repos/coq/inQWIRE-QuantumLib", "path": "github-repos/coq/inQWIRE-QuantumLib/QuantumLib-d97ea40581961d7b53291a4a3dc7885fe7428060/RealAux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.6957593841347359}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Basic_Cons.Product.\nRequire Import Coq_Cats.Type_Cat.Type_Cat.\n\nLocal Notation \"A + B\" := (@Sum Type_Cat A B) : object_scope.\n\n(** The sum of types in coq is the categorical notion of sum in category of\n    types. *)\nProgram Definition sum_Sum (A B : Type) : (A + B)%object :=\n{|\n  product := (A + B)%type;\n  Prod_morph_ex :=\n    fun (p' : Type)\n        (r1 : A → p')\n        (r2 : B → p')\n        (X : A + B) =>\n      match X return p' with\n      | inl a => r1 a\n      | inr b => r2 b\n      end\n|}.\n\nLocal Obligation Tactic := idtac.\n\nNext Obligation. (* Sum_morph_unique *)\nProof.\n  intros A B p' r1 r2 f g H1 H2 H3 H4.\n  rewrite <- H3 in H1.\n  rewrite <- H4 in H2.\n  clear H3 H4.\n  extensionality x.\n  destruct x;\n    match goal with\n        [|- f (?m ?y) = g (?m ?y)] =>\n        apply (@equal_f _ _ (fun x => f (m x)) (fun x => g (m x)))\n    end; auto.\nQed.\n\n(* sum_Sum defined *)\n\nProgram Instance Type_Cat_Has_Sums : Has_Sums Type_Cat := sum_Sum.\n\n", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/Categories/Coq_Cats/Type_Cat/Sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.7690802264851918, "lm_q1q2_score": 0.6957488364482782}}
{"text": "Require Export Polynomial.\nRequire Import Setoid.\n\n(************************************)\n(* First, we define a topology on C *)\n(************************************)\n\nDeclare Scope topology_scope.\nDelimit Scope topology_scope with T.\nOpen Scope topology_scope.\n\n \n\n(* we define a subset of C as a function from C to {True, False} *)  \n(* so c is in A if A(c) = True *)\nDefinition Cset := C -> Prop.\n\nDefinition union (A B : Cset) : Cset :=\n  fun c => A c \\/ B c.\n\nDefinition intersection (A B : Cset) : Cset :=\n  fun c => A c /\\ B c.\n\nDefinition complement (A : Cset) : Cset :=\n  fun c => not (A c).\n\nDefinition setminus (A B : Cset) : Cset :=\n  intersection A (complement B).\n\nDefinition is_in (a : C) (A : Cset) : Prop := A a.\n\nDefinition subset (A B : Cset) : Prop :=\n  forall c, A c -> B c.\n\nDefinition eq_set (A B : Cset) : Prop :=\n  forall c, A c <-> B c.\n\nDefinition ϵ_disk (a : C) (ϵ : R) : Cset :=\n  fun c => Cmod (c - a) < ϵ.\n\nDefinition open_square (cen : C) (s : R) : Cset :=\n  fun c => Rabs (fst c - fst cen) < s /\\ Rabs (snd c - snd cen) < s. \n\nDefinition open_rect (cen : C) (s1 s2 : R) : Cset := \n  fun c => Rabs (fst c - fst cen) < s1 /\\ Rabs (snd c - snd cen) < s2. \n\nDefinition bounded (A : Cset) : Prop :=\n  exists ϵ, subset A (ϵ_disk C0 ϵ). \n\nDefinition image (f : C -> C) (A : Cset) : Cset := \n  fun c => (exists c', A c' /\\ f c' = c).\n\nDefinition preimage (f : C -> C) (B : Cset) : Cset :=\n  fun c => B (f c).\n\nDefinition continuous_on (f : C -> C) (A : Cset) : Prop :=\n  forall c, A c -> continuous_at f c.\n\nInfix \"∪\" := union (at level 50, left associativity) : topology_scope.\nInfix \"∩\" := intersection (at level 40, left associativity) : topology_scope.\nInfix \"⊂\" := subset (at level 0) : topology_scope.\nInfix \"⩦\" := eq_set (at level 0) : topology_scope.\nInfix \"\\\" := setminus (at level 0) : topology_scope.\nInfix \"@\" := image (at level 0) : topology_scope.\nNotation \"f *{ A }\" := (preimage f A) (at level 0) : topology_scope.\nNotation \"A `\" := (complement A) (at level 0) : topology_scope.\nInfix \"∈\" := is_in (at level 0) : topology_scope.\nNotation \"B( a , ϵ )\" := (ϵ_disk a ϵ) (at level 30, no associativity) : topology_scope.\n\n\nDefinition open (A : Cset) : Prop :=\n  forall c, A c -> exists ϵ, ϵ > 0 /\\ B(c,ϵ) ⊂ A.\n\nDefinition closed (A : Cset) : Prop :=\n  open (A`).\n\nDefinition empty_set : Cset :=\n  fun _ => False. \n\nDefinition C_ : Cset :=\n  fun _ => True. \n\n\n(** showing that all the above def's are preserved by eq_set *)\n\nLemma eq_set_refl : forall (A : Cset), A ⩦ A.\nProof. easy. Qed.\n\nLemma eq_set_symm : forall (A B : Cset), A ⩦ B -> B ⩦ A. \nProof. easy. Qed. \n\nLemma eq_set_trans : forall (A B C : Cset), \n  A ⩦ B -> B ⩦ C -> A ⩦ C.\nProof. intros. \n       unfold eq_set in *; intros. \n       split; intros. \n       apply H0; apply H; easy.\n       apply H; apply H0; easy.\nQed.\n\nAdd Parametric Relation : Cset eq_set\n  reflexivity proved by eq_set_refl\n  symmetry proved by eq_set_symm\n  transitivity proved by eq_set_trans\n  as eq_set_equiv_rel.\n\n\nAdd Parametric Morphism : subset\n  with signature eq_set ==> eq_set ==> iff as subset_mor.\nProof. unfold subset, eq_set; split; intros;\n       apply H0; apply H1; apply H; easy. \nQed.\n\nAdd Parametric Morphism : union\n  with signature eq_set ==> eq_set ==> eq_set as union_mor.\nProof. unfold union, eq_set; split; intros; destruct H1; \n         try (left; apply H; easy); right; apply H0; easy.\nQed.\n\nAdd Parametric Morphism : intersection\n  with signature eq_set ==> eq_set ==> eq_set as intersection_mor.\nProof. unfold intersection, eq_set; split; intros; split; \n       try (apply H; apply H1); apply H0; apply H1.\nQed.\n\nAdd Parametric Morphism : bounded\n  with signature eq_set ==> iff as bounded_mor.\nProof. unfold bounded; split; intros;\n         destruct H0; exists x0. \n       rewrite <- H; easy. \n       rewrite H; easy. \nQed.\n\nAdd Parametric Morphism : open\n  with signature eq_set ==> iff as open_mor.\nProof. unfold open; split; intros;\n       apply H in H1; apply H0 in H1; destruct H1 as [e [H2 H3] ];\n       exists e; split; auto.\n       rewrite <- H; easy. \n       rewrite H; easy. \nQed.\n\n(* one quick helper *)\nLemma Cmod_lt_helper : forall (c : C) (ϵ : R),\n  Cmod c < ϵ -> Rabs (fst c) < ϵ /\\ Rabs (snd c) < ϵ.\nProof. intros. \n       assert (H' := Rmax_Cmod c).\n       split. \n       - eapply Rle_lt_trans. \n         eapply Rle_trans.\n         apply Rmax_l.\n         apply H'. \n         easy. \n       - eapply Rle_lt_trans. \n         eapply Rle_trans.\n         apply Rmax_r.\n         apply H'. \n         easy. \nQed.\n\n(** Subset lemmas *)\n\nLemma subset_cup_l : forall (A B : Cset),\n  A ⊂ (A ∪ B).\nProof. unfold subset, union; left; easy. Qed.\n\nLemma subset_cup_r : forall (A B : Cset),\n  B ⊂ (A ∪ B).\nProof. unfold subset, union; right; easy. Qed.\n\nLemma subset_cap_l : forall (A B : Cset),\n  (A ∩ B) ⊂ A.\nProof. unfold subset, intersection; easy. Qed.\n\nLemma subset_cap_r : forall (A B : Cset),\n  (A ∩ B) ⊂ B.\nProof. unfold subset, intersection; easy. Qed.\n\nLemma subset_self : forall (A : Cset),\n  A ⊂ A.\nProof. easy. Qed. \n\nLemma subset_transitive : forall (A B C : Cset),\n  A ⊂ B -> B ⊂ C -> A ⊂ C.\nProof. unfold subset; intros. \n       apply H0; apply H; easy. \nQed.\n\n#[global] Hint Resolve subset_cup_l subset_cup_r subset_cap_l subset_cap_r subset_self subset_transitive : Csub_db.\n\nLemma subset_cup_reduce : forall (A B C : Cset),\n  A ⊂ B \\/ A ⊂ C -> A ⊂ (B ∪ C). \nProof. unfold subset, union; intros. \n       destruct H.\n       - left; apply H; easy. \n       - right; apply H; easy. \nQed.\n\nLemma subset_cap_reduce : forall (A B C : Cset),\n  A ⊂ B /\\ A ⊂ C -> A ⊂ (B ∩ C). \nProof. unfold subset, intersection; intros. \n       destruct H; split.\n       apply H; easy.\n       apply H1; easy.\nQed.\n\nLemma subset_ball_l : forall (a : C) (ϵ1 ϵ2 : R),\n  B(a, Rmin ϵ1 ϵ2) ⊂ B(a, ϵ1).\nProof. unfold subset, ϵ_disk; intros. \n       eapply Rlt_le_trans; eauto.\n       apply Rmin_l.\nQed.\n\nLemma subset_ball_r : forall (a : C) (ϵ1 ϵ2 : R),\n  B(a, Rmin ϵ1 ϵ2) ⊂ B(a, ϵ2).\nProof. unfold subset, ϵ_disk; intros. \n       eapply Rlt_le_trans; eauto.\n       apply Rmin_r.\nQed.\n\nLemma subset_C_ : forall (A : Cset),\n  A ⊂ C_.\nProof. unfold subset; easy. Qed.\n\n#[global] Hint Resolve subset_cup_reduce subset_cap_reduce subset_ball_l subset_ball_r subset_C_ : Csub_db.\n\nLemma subset_equal : forall (A B : Cset),\n  A ⊂ B -> B ⊂ A -> A ⩦ B.\nProof. unfold subset, eq_set; intros. \n       split; try apply H; apply H0. \nQed.\n\nLemma subset_not : forall (A B : Cset), \n  ~ (A ⊂ B) -> (exists a, A a /\\ B` a).\nProof. intros. \n       destruct (Classical_Prop.classic (exists a : C, A a /\\ (B) ` a)); auto. \n       assert (H1 : forall a, ~ (A a /\\ (B) ` a)).\n       { unfold not; intros. \n         apply H0; exists a; easy. }\n       assert (H2 : A ⊂ B).\n       { unfold subset; intros. \n         assert (H' := H1 c). \n         apply Classical_Prop.not_and_or in H'.\n         destruct H'; try easy.\n         unfold not, complement in H3.\n         apply Decidable.dec_not_not; auto. \n         unfold Decidable.decidable.\n         apply Classical_Prop.classic. }\n       easy.\nQed.\n\n\n(* some image and preimage relationships with subsets *)\n\nLemma subset_image : forall (A B : Cset) (f : C -> C),\n  A ⊂ B -> (f @ A) ⊂ (f @ B).\nProof. unfold subset; intros. \n       destruct H0 as [x [H0 H1] ].\n       apply H in H0.\n       exists x; easy. \nQed.\n\n(* showing subset relationships between squares, circles, and rectangles *) \nLemma circle_in_square : forall (cen : C) (s : R),\n  (ϵ_disk cen s) ⊂ (open_square cen s).\nProof. unfold subset, ϵ_disk, open_square; intros. \n       apply Cmod_lt_helper in H.\n       easy. \nQed.\n\nLemma square_in_circle : forall (cen : C) (ϵ : R),\n  (open_square cen (ϵ / √ 2)) ⊂ (ϵ_disk cen ϵ).\nProof. unfold subset, ϵ_disk, open_square; intros. \n       destruct H.\n       destruct (Rle_lt_dec ϵ 0).\n       - assert (H' : ϵ / √ 2 <= 0). \n         { unfold Rdiv.\n           rewrite <- (Rmult_0_r ϵ).\n           apply Rmult_le_compat_neg_l; auto; left. \n           apply Rinv_0_lt_compat; apply Rlt_sqrt2_0. }\n         assert (H1 := Rabs_pos ((fst c - fst cen))).\n         lra.\n       - assert (H' : 0 < ϵ / √ 2).\n         unfold Rdiv; apply Rmult_lt_0_compat; auto.\n         apply Rinv_0_lt_compat; apply Rlt_sqrt2_0.\n         assert (H1 : (ϵ / √ 2 = Rabs (ϵ / √ 2))%R).\n         { unfold Rabs.\n           destruct (Rcase_abs (ϵ / √ 2)); lra. }\n         rewrite H1 in *.\n         apply Rsqr_lt_abs_1 in H; apply Rsqr_lt_abs_1 in H0.\n         assert (H2 : ((ϵ / √ 2)² = ϵ² / 2)%R).\n         { unfold Rsqr, Rdiv. \n           R_field_simplify; try easy.\n           apply sqrt2_neq_0. }\n         rewrite H2 in *.\n         unfold Cmod.\n         rewrite <- sqrt_Rsqr; try lra. \n         apply sqrt_lt_1_alt. split. \n         apply Rplus_le_le_0_compat; apply pow2_ge_0.\n         rewrite double_var.\n         apply Rplus_lt_compat;\n         unfold Rsqr in *; simpl; lra. \nQed.\n\nLemma square_is_rectangle : forall (cen : C) (s : R),\n  (open_square cen s) ⩦ (open_rect cen s s).\nProof. intros; easy. Qed.\n\nLemma square_in_rect_at_point : forall (cen c : C) (s1 s2 : R),\n  s1 > 0 -> s2 > 0 ->\n  (open_rect cen s1 s2) c ->\n  exists s, s > 0 /\\ (open_square c s) ⊂ (open_rect cen s1 s2).\nProof. intros. \n       exists (Rmin (s1 - (Rabs (fst c - fst cen))) (s2 - (Rabs (snd c - snd cen)))).\n       destruct H1 as [H1 H2].\n       repeat split.\n       apply Rmin_pos; try lra. \n       all : destruct H3.\n       - eapply Rlt_le_trans in H3; try apply Rmin_l.\n         replace (fst c0 - fst cen)%R with ((fst c0 - fst c) + (fst c - fst cen))%R by lra.\n         eapply Rle_lt_trans; try apply Rabs_triang; lra.\n       - eapply Rlt_le_trans in H4; try apply Rmin_r.\n         replace (snd c0 - snd cen)%R with ((snd c0 - snd c) + (snd c - snd cen))%R by lra.\n         eapply Rle_lt_trans; try apply Rabs_triang; lra.\nQed.\n\nLemma square_contains_center : forall (cen : C) (s : R),\n  s > 0 -> open_square cen s cen.\nProof. intros. \n       unfold open_square.\n       do 2 rewrite Rminus_eq_0, Rabs_R0; easy.\nQed.\n\n(** some lemmas about open/closed sets *)\n\nLemma emptyset_open : open empty_set.\nProof. easy. Qed.\n\nLemma C_open : open C_.\nProof. unfold open, C_, is_in; intros. \n       exists 1; split; try lra. \n       easy. \nQed.\n\nLemma ball_open : forall (a : C) (ϵ : R),\n  ϵ > 0 -> open (B(a,ϵ)).\nProof. unfold open; intros.\n       unfold ϵ_disk in H0.\n       exists (ϵ - Cmod (c - a))%R.\n       split; try lra.\n       unfold subset; intros.\n       unfold ϵ_disk in *.\n       assert (H2 : Cmod (c0 - c) + Cmod (c - a) < ϵ). { lra. }\n       apply Cmod_triangle_diff in H2.\n       easy. \nQed.\n\nLemma closed_ball_complement_open : forall (c : C) (r : R),\n  open (fun c' => Cmod (c' - c) > r).\nProof. unfold open; intros.\n       exists (Cmod (c0 - c) - r)%R.\n       split; try lra. \n       unfold subset, ϵ_disk; intros. \n       assert (H' := Cmod_triangle (c1 - c) (c0 - c1)).\n       replace (c1 - c + (c0 - c1)) with (c0 - c) in H' by lca. \n       rewrite Cmod_switch in H0; lra. \nQed.\n\nLemma closed_ball_closed : forall (a : C) (ϵ : R),\n  closed (fun c' => Cmod (c' - a) <= ϵ).\nProof. intros; unfold closed. \n       assert (H' : (fun c' : C => Cmod (c' - a) <= ϵ) ` ⩦ (fun c' : C => Cmod (c' - a) > ϵ)).\n       { apply subset_equal; unfold subset, complement; intros; lra. } \n       rewrite H'.\n       apply closed_ball_complement_open.\nQed.\n\nLemma rect_open : forall (cen : C) (s1 s2 : R),\n  s1 > 0 -> s2 > 0 -> open (open_rect cen s1 s2).\nProof. unfold open; intros. \n       apply square_in_rect_at_point in H1; auto.\n       destruct H1 as [s [H1 H2] ].\n       exists s; split; auto.\n       eapply subset_transitive; try apply H2.\n       apply circle_in_square.\nQed.\n\nLemma cup_open : forall (A B : Cset),\n  open A -> open B -> open (A ∪ B).\nProof. unfold open; intros.  \n       unfold union in H1.\n       destruct H1.\n       - destruct ((H c) H1) as [ϵ [H2 H3] ].\n         exists ϵ.\n         split; eauto with Csub_db. \n       - destruct ((H0 c) H1) as [ϵ [H2 H3] ].\n         exists ϵ.\n         split; eauto with Csub_db. \nQed.\n\nLemma cap_open : forall (A B : Cset),\n  open A -> open B -> open (A ∩ B).\nProof. unfold open; intros.  \n       unfold intersection in H1.\n       destruct H1.\n       destruct ((H c) H1) as [ϵ1 [H3 H4] ].\n       destruct ((H0 c) H2) as [ϵ2 [H5 H6] ].\n       exists (Rmin ϵ1 ϵ2).\n       split. \n       apply Rmin_Rgt_r; easy.       \n       eauto with Csub_db.\nQed.\n\n\n\n\n(** lemmas about preimage *)\n\n(** some lemmas showing basic properties *)\n\nLemma complement_involutive : forall (A : Cset),\n  (A`)` ⩦ A.\nProof. unfold complement; intros. \n       apply subset_equal.\n       - unfold subset; intros. \n         apply Classical_Prop.NNPP; easy. \n       - unfold subset; intros. \n         unfold not. intros.\n         easy. \nQed.\n\nLemma bounded_cup : forall (A B : Cset),\n  bounded A -> bounded B -> bounded (A ∪ B).\nProof. intros. \n       destruct H as [ϵ1 H].\n       destruct H0 as [ϵ2 H0].\n       exists (Rmax ϵ1 ϵ2).\n       unfold subset, ϵ_disk in *; intros. \n       destruct H1. \n       - apply H in H1.\n         eapply Rlt_le_trans; eauto. \n         apply Rmax_l.\n       - apply H0 in H1.\n         eapply Rlt_le_trans; eauto. \n         apply Rmax_r.\nQed.       \n\n\n(************************)\n(* Defining compactness *)\n(************************)\n\nDefinition Ccover := Cset -> Prop.\n\nDefinition WF_cover (G : Ccover) : Prop :=\n  forall A A', (A ⩦ A' /\\ G A) -> G A'.\n\nDefinition WFify_cover (G : Ccover) : Ccover :=\n  fun A => exists A', A ⩦ A' /\\ G A'.\n\nDefinition open_cover (G : Ccover) : Prop :=\n  forall A, G A -> open A.\n\nDefinition subcover (G1 G2 : Ccover) : Prop :=\n  forall A, G1 A -> G2 A.\n\nDefinition eq_cover (G1 G2 : Ccover) : Prop :=\n  forall A, G1 A <-> G2 A.\n\n(* used in list_to_cover *)\nFixpoint In' (A : Cset) (l : list Cset) : Prop :=\n  match l with\n  | [] => False\n  | (A' :: l) => A ⩦ A' \\/ In' A l\n  end.\n\nDefinition list_to_cover (l : list Cset) : Ccover :=\n  fun A => In' A l.\n\nDefinition finite_cover (G : Ccover) : Prop :=\n  exists l, eq_cover G (list_to_cover l).\n\nDefinition big_cup (G : Ccover) : Cset :=\n  fun c => (exists A, G A /\\ A c).\n\nDefinition big_cap (G : Ccover) : Cset :=\n  fun c => (forall A, G A -> A c).\n\n(* the star of the show! *)\nDefinition compact (A : Cset) : Prop :=\n  forall G, open_cover G -> WF_cover G -> A ⊂ (big_cup G) -> \n       (exists G', finite_cover G' /\\ subcover G' G /\\ A ⊂ (big_cup G')).\n\n(* showing some basic wf lemmas *)\n\nLemma WF_WFify : forall (G : Ccover),\n  WF_cover (WFify_cover G).\nProof. intros. unfold WF_cover, WFify_cover. intros. \n       destruct H as [H [A0 [H0 H1 ] ] ].\n       exists A0; split; try easy. \n       symmetry in H.\n       eapply eq_set_trans;\n       try apply H; easy.\nQed.\n\nLemma WF_finitecover : forall (l : list Cset),\n  WF_cover (list_to_cover l).\nProof. induction l as [| A]. \n       - unfold WF_cover, list_to_cover; intros. \n         destruct H.\n         easy. \n       - unfold WF_cover, list_to_cover in *; intros. \n         destruct H; destruct H0.\n         left; rewrite <- H, <- H0; easy. \n         right; apply (IHl A0); easy. \nQed.\n\nLemma WFify_is_projection : forall (G : Ccover),\n  WF_cover G -> \n  eq_cover G (WFify_cover G).\nProof. unfold eq_cover; intros; split; intros.  \n       exists A; easy. \n       destruct H0 as [A0 [H0 H1] ].\n       apply (H A0 A); easy. \nQed.\n\n\n(* showing that all the def's are preserved by eq_cover *)\n\nLemma eq_cover_refl : forall (G : Ccover), eq_cover G G.\nProof. easy. Qed.\n\nLemma eq_cover_symm : forall (G1 G2 : Ccover), eq_cover G1 G2 -> eq_cover G2 G1.  \nProof. easy. Qed. \n\nLemma eq_cover_trans : forall (G1 G2 G3 : Ccover), \n  eq_cover G1 G2 -> eq_cover G2 G3 -> eq_cover G1 G3.\nProof. intros. \n       unfold eq_cover in *; intros. \n       split; intros. \n       apply H0; apply H; easy.\n       apply H; apply H0; easy.\nQed.\n\nAdd Parametric Relation : Ccover eq_cover\n  reflexivity proved by eq_cover_refl\n  symmetry proved by eq_cover_symm\n  transitivity proved by eq_cover_trans\n  as eq_cover_equiv_rel.\n\nAdd Parametric Morphism : subcover\n  with signature eq_cover ==> eq_cover ==> iff as subcover_mor.\nProof. intros. unfold subcover, eq_cover; split; intros;\n       apply H0; apply H1; apply H; easy. \nQed.\n\nAdd Parametric Morphism : open_cover\n  with signature eq_cover ==> iff as opencover_mor.\nProof. unfold eq_cover, open_cover; split; intros;\n         apply H0; apply H; easy. \nQed.\n\nAdd Parametric Morphism : big_cup\n  with signature eq_cover ==> eq_set as bigcup_mor.\nProof. unfold eq_cover, big_cup; split; intros; \n         destruct H0 as [A [H0 H1] ]; exists A; split; auto; apply H; auto. \nQed.\n\nAdd Parametric Morphism : big_cap\n  with signature eq_cover ==> eq_set as bigcap_mor.\nProof. unfold eq_cover, big_cap; split; intros;\n         apply H0; apply H; apply H1.\nQed.\n\n(* must also show that compactness is preserved by eq_set *)\n\nAdd Parametric Morphism : compact\n  with signature eq_set ==> iff as compact_mor.\nProof. intros. unfold compact; split; intros. \n       - rewrite <- H in *.\n         apply H0 in H3; try easy. \n         destruct H3 as [G' [H3 [H4 H5] ] ].\n         rewrite H in H5.\n         exists G'; easy. \n       - rewrite H in *.\n         apply H0 in H3; try easy. \n         destruct H3 as [G' [H3 [H4 H5] ] ].\n         rewrite <- H in H5.\n         exists G'; easy. \nQed.\n\n(** now some lemmas *)\n\nLemma list_to_cover_reduce : forall (A A0 : Cset) (l : list Cset),\n  list_to_cover (A :: l) A0 <->\n  A ⩦ A0 \\/ list_to_cover l A0.\nProof. intros; split; intros; \n         destruct H; try (left; easy); right; easy. \nQed.\n\nLemma open_cover_reduce : forall (l : list Cset) (A : Cset),\n  open_cover (list_to_cover (A :: l)) ->\n  open A /\\ open_cover (list_to_cover l).\nProof.  intros; split; unfold open_cover in H.\n        apply H. \n        apply list_to_cover_reduce; left; easy. \n        unfold open_cover; intros. \n        apply H. \n        apply list_to_cover_reduce; right; easy. \nQed.\n\nLemma subcover_reduce : forall (l : list Cset) (A : Cset) (G : Ccover),\n  subcover (list_to_cover (A :: l)) G ->\n  G A /\\ subcover (list_to_cover l) G.\nProof. intros; split.       \n       apply H. \n       apply list_to_cover_reduce; left; easy. \n       unfold subcover; intros. \n       apply H. \n       apply list_to_cover_reduce; right; easy. \nQed.\n\nLemma finite_cover_subset : forall (l : list Cset) (G : Ccover),\n  WF_cover G -> subcover G (list_to_cover l) ->\n  finite_cover G.\nProof. induction l as [| A].\n       - intros.  \n         exists []; split; intros; auto; easy. \n       - intros. \n         destruct (IHl (fun A' => G A' /\\ ~ (eq_set A' A))).\n         + unfold WF_cover in *; intros; split; \n           destruct H1 as [H1 [H2 H3] ].\n           apply (H A0 A'); easy. \n           unfold not; intros; apply H3.\n           rewrite H1; easy. \n         + unfold subcover in *; intros. \n           destruct H1.\n           apply H0 in H1.\n           apply list_to_cover_reduce in H1.\n           destruct H1; try easy. \n           unfold not in H2.\n           symmetry in H1.\n           apply H2 in H1; easy.\n         + destruct (Classical_Prop.classic (G A)).\n           * exists (A :: x).\n             unfold eq_cover; split; intros; simpl. \n             destruct (Classical_Prop.classic (A ⩦ A0)); try (left; easy). \n             right; apply H1; split; auto.\n             unfold not; intros; apply H4; easy. \n             apply list_to_cover_reduce in H3.\n             destruct H3.\n             apply (H A A0); easy.\n             apply H1 in H3; easy. \n           * exists x. \n             unfold eq_cover; intros; split; intros. \n             apply H1; split; auto.\n             unfold not; intros; apply H2.\n             apply (H A0 A); easy. \n             apply H1 in H3; easy. \nQed.\n         \nLemma big_cup_extend_l : forall (l : list Cset) (A : Cset),\n  (A ∪ (big_cup (list_to_cover l))) ⩦ (big_cup (list_to_cover (A :: l))).\nProof. intros.\n       unfold union, big_cup, list_to_cover; intros.        \n       apply subset_equal.\n       - unfold subset; intros. \n         destruct H.\n         + exists A; split; try left; easy. \n         + destruct H as [A0 [H H0] ]. \n           exists A0. split; try right; easy. \n       - unfold subset; intros. \n         destruct H as [A0 [ [H | H] H0] ]; subst.\n         left; apply H; easy. \n         right; exists A0; split; easy. \nQed.\n\nLemma big_cap_extend_l : forall (l : list Cset) (A : Cset),\n  (A ∩ (big_cap (list_to_cover l))) ⩦ (big_cap (list_to_cover (A :: l))).\nProof. intros.\n       unfold intersection, big_cap, list_to_cover; intros.        \n       apply subset_equal.\n       - unfold subset; intros. \n         destruct H; destruct H0; subst; try easy.\n         apply H0; easy.  \n         apply H1; apply H0.\n       - unfold subset; intros. \n         split.\n         apply H; left; easy. \n         intros; apply H; right; apply H0.\nQed.\n\nLemma app_union : forall (l1 l2 : list Cset),\n  (big_cup (list_to_cover (l1 ++ l2))) ⩦ \n  ((big_cup (list_to_cover l1)) ∪ (big_cup (list_to_cover l2))).\nProof. induction l1 as [| A].\n       - intros; simpl. \n         apply subset_equal; auto with Csub_db.\n         unfold subset; intros. \n         destruct H; try easy. \n         destruct H; easy. \n       - intros. \n         rewrite <- app_comm_cons.\n         rewrite <- big_cup_extend_l.\n         rewrite IHl1.\n         rewrite <- big_cup_extend_l.\n         split; intros. \n         + destruct H. \n           left; left; easy.\n           destruct H. left; right; easy.\n           right; easy. \n         + destruct H. destruct H. \n           left; easy. \n           right; left; easy. \n           right; right; easy. \nQed.\n\nLemma In'_app_or : forall (l1 l2 : list Cset) (A : Cset),\n  In' A (l1 ++ l2) -> In' A l1 \\/ In' A l2.\nProof. induction l1 as [| A0].\n       - intros; right; easy.\n       - intros. \n         rewrite <- app_comm_cons in H.\n         destruct H.\n         left; left; easy.\n         apply IHl1 in H.\n         destruct H.\n         left; right; easy. \n         right; easy.\nQed.\n\nLemma In'_map : forall {X} (l : list X) (f : X -> Cset) (A : Cset),  \n  In' A (map f l) -> exists (x : X), (f x) ⩦ A /\\ In x l.\nProof. induction l; firstorder (subst; auto).\nQed.\n\nLemma arb_cup_open : forall (G : Ccover),\n  open_cover G -> open (big_cup G).\nProof. unfold open_cover, open, big_cup in *; intros. \n       destruct H0 as [A [H0 H1] ].\n       destruct (H A H0 c) as [ϵ [H2 H3] ]; auto.\n       exists ϵ.\n       split; auto. \n       eapply subset_transitive; eauto. \n       unfold subset; intros. \n       exists A; split; easy. \nQed.\n\nLemma ltc_open : forall (l : list Cset),\n  open_cover (list_to_cover l) -> open (big_cap (list_to_cover l)).\nProof. induction l as [| h].\n       - intros. \n         unfold list_to_cover, big_cap, open; intros. \n         exists 1; split; try easy; lra. \n       - intros. \n         apply open_cover_reduce in H.\n         rewrite <- big_cap_extend_l.\n         apply cap_open; try easy. \n         apply IHl; easy. \nQed.\n\nLemma fin_cap_open : forall (G : Ccover),\n  open_cover G -> finite_cover G -> open (big_cap G).\nProof. intros. \n       unfold finite_cover in H0.\n       destruct H0 as [l H0].\n       rewrite H0.\n       apply ltc_open.\n       rewrite <- H0; easy. \nQed.\n\n(* we have not yet defined enough setup to define preimage for functions whose domains differ\n   from C_. This is fine when proving FTA, since polynomials are continuous everywhere.\n   Could be expanded if we want to make a general topology library *)\nLemma continuous_preimage_open : forall (f : C -> C),\n  continuous_on f C_ -> (forall A, open A -> open f*{A}).\nProof. intros. \n       unfold open in *; intros. \n       unfold preimage in H1. \n       destruct (H0 (f c) H1) as [ϵ [H2 H3] ]. \n       assert (H' : C_ c). easy. \n       destruct (H c H' ϵ) as [δ [H4 H5] ]; auto.  \n       exists δ; split; auto.\n       unfold subset, preimage, ϵ_disk in *; intros.  \n       destruct (Ceq_dec c0 c); subst; try easy. \n       apply H3; apply H5; try easy.  \nQed.\n\nLemma preimage_open_continuous : forall (f : C -> C),\n  (forall A, open A -> open f*{A}) -> continuous_on f C_.\nProof. unfold continuous_on; intros. \n       unfold continuous_at, limit_at_point; intros. \n       assert (H2 := (H ( B(f c,ϵ) ) (ball_open (f c) ϵ H1))).\n       unfold open in H2. \n       destruct (H2 c) as [δ [H3 H4] ].\n       unfold preimage, ϵ_disk. \n       replace (f c - f c)%C with C0 by lca. \n       rewrite Cmod_0; lra. \n       exists δ; split; auto; intros. \n       unfold preimage, subset, ϵ_disk in H4.\n       apply H4; easy.  \nQed.\n\n(* we define the preimage of a cover *)\nDefinition preimage_cover (f : C -> C) (G : Ccover) : Ccover :=\n  fun A => (exists A', G A' /\\ A ⩦ (f*{A'})).\n\nLemma open_cover_preimage_open : forall (f : C -> C) (G : Ccover),\n  open_cover G -> continuous_on f C_ ->\n  open_cover (preimage_cover f G).\nProof. intros. \n       unfold open_cover, preimage_cover; intros. \n       destruct H1 as [A' [H1 H2] ]; subst.\n       apply H in H1.\n       rewrite H2.\n       apply (continuous_preimage_open _ H0); easy.\nQed.\n\nLemma WF_preimage_cover : forall (f : C -> C) (G : Ccover),\n  WF_cover (preimage_cover f G).\nProof. unfold WF_cover, preimage_cover; intros. \n       destruct H as [H [A0 [H0 H1] ] ].\n       exists A0; split; auto. \n       rewrite <- H; easy. \nQed.\n\nLemma subset_preimage_pres : forall (f : C -> C) (A : Cset) (G : Ccover),\n  ((f) @ (A)) ⊂ (big_cup G) ->\n  A ⊂ (big_cup (preimage_cover f G)).\nProof. unfold subset; intros. \n       unfold big_cup, preimage_cover.\n       assert (H' : big_cup G (f c)).\n       { apply H.\n         exists c; split; easy. }\n       unfold big_cup in H'.\n       destruct H' as [A0 [H1 H2] ].\n       exists (f*{A0}); split; try easy. \n       exists A0; split; easy.\nQed.       \n\nLemma extract_finite_image : forall (f : C -> C) (l : list Cset) (A : Cset) (G : Ccover),\n  WF_cover G -> \n  subcover (list_to_cover l) (preimage_cover f G) -> \n  A ⊂ (big_cup (list_to_cover l)) ->\n  exists l', subcover (list_to_cover l') G /\\ (f @ A) ⊂ (big_cup (list_to_cover l')).\nProof. induction l as [| A0].\n       - intros.\n         exists []; split; auto.  \n         unfold subcover; easy. \n         unfold subset in *; intros. \n         destruct H2 as [c0 [H2 H3] ].\n         apply H1 in H2.\n         unfold list_to_cover, big_cup in H2.\n         destruct H2; easy. \n       - intros.\n         apply subcover_reduce in H0.\n         destruct H0. \n         apply (IHl (A \\ A0)) in H2; auto.\n         destruct H0 as [A'0 [H0 H3] ].\n         destruct H2 as [l' [H2 H4] ].\n         exists (A'0 :: l'); split. \n         unfold subcover, list_to_cover; intros. \n         destruct H5; try (apply (H A'0 A1); easy).         \n         apply H2; easy.  \n         unfold subset in *; intros. \n         apply big_cup_extend_l.\n         destruct (Classical_Prop.classic (A'0 c)).\n         left; easy. \n         right; apply H4.\n         destruct H5 as [c' [H5 H7] ]. \n         exists c'; repeat split; auto. \n         unfold complement, not; intros. \n         apply H6; apply H3 in H8.\n         unfold preimage in H8; subst; easy. \n         unfold subset in *; intros. \n         destruct H3; apply H1 in H3.\n         apply big_cup_extend_l in H3.\n         destruct H3; easy.\nQed. \n\nLemma continuous_image_compact : forall (f : C -> C) (A : Cset),\n  continuous_on f C_ -> compact A ->\n  compact (f @ A).\nProof. intros. \n       unfold compact; intros. \n       assert (H4 := (subset_preimage_pres _ _ _ H3)). \n       apply H0 in H4.\n       destruct H4 as [G' [H4 [H5 H6] ] ].\n       destruct H4 as [l H4]; subst.\n       destruct (extract_finite_image f l A G) as [l' [H7 H8] ]; auto.\n       all : try (rewrite <- H4; easy).\n       exists (list_to_cover l'); repeat split; try easy.\n       exists l'; easy. \n       apply open_cover_preimage_open; easy. \n       apply WF_preimage_cover.\nQed.\n\n\n(*************************************************************************)\n(* We now introduce cube_compact and show that is is the same as compact *)\n(*************************************************************************)\n\nDefinition cube_cover (G : Ccover) : Prop := \n  forall A, G A -> exists s cen, s > 0 /\\ A ⩦ (open_square cen s). \n\nDefinition cube_compact (A : Cset) : Prop :=\n  forall G, cube_cover G -> WF_cover G -> A ⊂ (big_cup G) -> \n       (exists G', finite_cover G' /\\ subcover G' G /\\ A ⊂ (big_cup G')).\n\n(* we use this to turn covers to cube_covers *)\nDefinition cover_to_cube_cover (G : Ccover) : Ccover :=\n  fun A => (exists s cen A', s > 0 /\\ (A ⩦ (open_square cen s)) /\\ G A' /\\ (open_square cen s) ⊂ A').\n\nLemma cube_cover_open_cover : forall (G : Ccover),\n  cube_cover G -> open_cover G.\nProof. unfold open_cover, cube_cover; intros.\n       apply H in H0.\n       destruct H0 as [s [cen [H0 H1] ] ].\n       rewrite H1, square_is_rectangle.\n       apply rect_open; easy.\nQed.\n\nLemma WF_ctcc : forall (G : Ccover),\n  WF_cover (cover_to_cube_cover G).\nProof. unfold WF_cover; intros. \n       destruct H.\n       destruct H0 as [s [cen [A0 [H0 [H1 [H2 H3] ] ] ] ] ].\n       exists s, cen, A0; split; auto.\n       split; try easy.\n       rewrite <- H1; easy.\nQed.\n\nLemma cube_cover_ctcc : forall (G : Ccover),\n  cube_cover (cover_to_cube_cover G).\nProof. unfold cube_cover; intros. \n       destruct H as [s [cen [A0 [H0 [H1 [H2 H3] ] ] ] ] ].\n       exists s, cen.\n       split; easy.\nQed.\n\nLemma ctcc_in_cover : forall (G : Ccover),\n  open_cover G -> (big_cup G) ⩦ (big_cup (cover_to_cube_cover G)).\nProof. intros; split; intros. \n       - destruct H0 as [A [H0 H1] ].\n         assert (H0' := H0).\n         apply H in H0.\n         assert (H2 := H1); apply H0 in H1.\n         destruct H1 as [ϵ [H1 H3] ].\n         exists (open_square c (ϵ / √ 2)). \n         split. \n         unfold cover_to_cube_cover.\n         exists (ϵ / √ 2)%R, c, A; split.\n         apply lt_ep_helper in H1; easy. \n         split; try easy.\n         split; try easy.\n         eapply subset_transitive; try apply H3.\n         apply square_in_circle.\n         apply square_contains_center.\n         apply (lt_ep_helper ϵ); easy.\n       - destruct H0 as [A [H0 H1] ].\n         destruct H0 as [s [cen [A0 [H0 [H2 [H3 H4] ] ] ] ] ].\n         exists A0; split; auto.\n         apply H4; apply H2; easy.\nQed.\n\nLemma fin_cubecover_gives_fin_cover : forall (l : list Cset) (G : Ccover),\n  WF_cover G ->\n  subcover (list_to_cover l) (cover_to_cube_cover G) -> \n  exists l', subcover (list_to_cover l') G /\\ \n          (big_cup (list_to_cover l)) ⊂ (big_cup (list_to_cover l')).\nProof. induction l as [| A].\n       - intros. exists []; split; try easy.\n       - intros.\n         apply subcover_reduce in H0; destruct H0.\n         apply IHl in H1; auto.\n         destruct H1 as [l' [H1 H2] ].\n         destruct H0 as [s [cen [A0 [H0 [H3 [H4 H5] ] ] ] ] ].\n         exists (A0 :: l').\n         split. \n         unfold subcover, list_to_cover; intros. \n         destruct H6.\n         apply (H A0 A1); easy.\n         apply H1; easy.\n         do 2 rewrite <- big_cup_extend_l.\n         unfold subset; intros. \n         destruct H6. \n         left; apply H5; apply H3; easy.\n         right; apply H2; easy.\nQed.\n\nLemma compact_is_cube_compact : forall (A : Cset),\n  compact A <-> cube_compact A.\nProof. split; intros. \n       - unfold cube_compact; intros. \n         apply cube_cover_open_cover in H0.\n         apply H in H2; easy.\n       - unfold compact, cube_compact in *; intros. \n         destruct (H (cover_to_cube_cover G)) as [G' [H3 [H4 H5] ] ].\n         apply cube_cover_ctcc.\n         apply WF_ctcc.\n         rewrite <- ctcc_in_cover; easy.\n         destruct H3 as [l H3].\n         destruct (fin_cubecover_gives_fin_cover l G) as [l' [H6 H7] ]; auto.\n         rewrite <- H3; easy.\n         exists (list_to_cover l'); repeat split; try easy.\n         exists l'; easy.\n         eapply subset_transitive; try apply H7.\n         rewrite <- H3; easy.\nQed.\n\n(*******************************************)\n(* Showing that the closed ball is compact *)\n(*******************************************)\n\n(* we first consider the line [0,1] ∈ C *)\nDefinition unit_line : Cset :=\n  fun c => 0 <= fst c <= 1 /\\ snd c = 0.\n\nDefinition partial_line (x : R) : Cset :=\n  fun c => 0 <= fst c <= x /\\ snd c = 0.\n\nDefinition partial_line_covered (G : Ccover) (x : R) : Prop :=\n  exists G', finite_cover G' /\\ subcover G' G /\\ (partial_line x) ⊂ (big_cup G').\n\nLemma zero_always_covered : forall (G : Ccover),\n  WF_cover G -> unit_line ⊂ (big_cup G) -> \n  partial_line_covered G 0.\nProof. intros. \n       assert (H' : (big_cup G) C0).\n       { apply H0. \n         repeat split; simpl; lra. } \n       destruct H'.\n       exists (list_to_cover [x]). \n       repeat split. \n       exists [x]; easy. \n       unfold subcover, list_to_cover; intros. \n       destruct H1; destruct H2; try easy. \n       apply (H x A); easy.\n       unfold subset, partial_line; intros. \n       destruct H2 as [ [H2 H3] H4].\n       apply Rle_antisym in H2; auto. \n       replace 0 with (fst C0) in H2 by easy. \n       apply c_proj_eq in H2; try easy; subst.  \n       exists x; split; try easy. \n       left; easy. \nQed.\n\nLemma plc_le_subset : forall (x x' : R),\n  x' <= x -> \n  (partial_line x') ⊂ (partial_line x).\nProof. unfold partial_line, subset; intros. \n       repeat split; try easy. \n       destruct H0 as [ [H0 H1] H2].\n       lra. \nQed.       \n\n(* showing that if x is covered than so are all points less than x *)\nLemma plc_less : forall (x x' : R) (G : Ccover),\n  x' <= x ->\n  partial_line_covered G x ->\n  partial_line_covered G x'.\nProof. intros. \n       unfold partial_line_covered in *.\n       destruct H0 as [G' [H0 [H1 H2] ] ].\n       exists G'; repeat split; auto. \n       eapply subset_transitive.\n       apply plc_le_subset; eauto.\n       easy. \nQed.\n\nLemma not_ub_implies_larger_elem : forall (E : R -> Prop) (a b : R),\n  E a -> ~ (is_upper_bound E b) ->\n  exists a', E a' /\\ b < a'.\nProof. intros. \n       destruct (Classical_Prop.classic (exists a' : R, E a' /\\ b < a')); auto. \n       assert (H' : is_upper_bound E b). \n       { unfold is_upper_bound; intros. \n         destruct (Classical_Prop.classic (x <= b)); auto. \n         apply Rnot_le_lt in H3.\n         assert (H'' : False).\n         apply H1. \n         exists x; easy. \n         easy. }\n       easy. \nQed.\n\nLemma extract_elem_lt_lub : forall (E : R -> Prop) (a lub ϵ : R),\n  E a -> ϵ > 0 -> is_lub E lub ->\n  exists x, (E x /\\ lub - ϵ < x). \nProof. intros. \n       apply (not_ub_implies_larger_elem _ a); auto. \n       unfold not; intros. \n       destruct H1.\n       apply H3 in H2.\n       lra. \nQed.\n\n\nTheorem unit_line_compact : compact unit_line. \nProof. unfold compact, unit_line; intros. \n       destruct (Classical_Prop.classic (partial_line_covered G 1)).\n       - destruct H2 as [G' [H2 [H3 H4] ] ].\n         exists G'; repeat split; easy. \n       - destruct (Classical_Prop.classic (is_upper_bound (partial_line_covered G) 1)).\n         + destruct (completeness (partial_line_covered G)).\n           exists 1; easy. \n           exists 0. \n           apply zero_always_covered; easy. \n           destruct i.\n           assert (H6 : x <= 1). \n           { apply H5; easy. }\n           assert (H7 : 0 <= x). \n           { apply H4; apply zero_always_covered; easy. } \n           assert (H' : big_cup G (x, 0)).\n           apply H1; repeat split; easy. \n           destruct H' as [A [H8 H9] ].  \n           assert (H8' := H8).\n           apply H in H8; apply H8 in H9.\n           destruct H9 as [ϵ [H9 H10] ].\n           assert (H11 : ϵ / 2 > 0).\n           { unfold Rdiv. apply Rmult_gt_0_compat; lra. } \n           assert (H12 : partial_line_covered G (x - ϵ / 2)). \n           { apply (extract_elem_lt_lub (partial_line_covered G) 0 x (ϵ / 2)) in H11; try easy.\n             destruct H11 as [x0 [H11 H12] ].\n             apply (plc_less x0); auto; lra.  \n             apply zero_always_covered; easy. }\n           assert (H13 : partial_line_covered G (x + ϵ / 2)).\n           { destruct H12 as [G' [H13 [H14 H15] ] ].\n             destruct H13 as [l H13].\n             exists (list_to_cover (A :: l)); repeat split. \n             exists (A :: l); easy.  \n             unfold subcover, list_to_cover; intros. \n             destruct H12.\n             apply (H0 A A0); easy.\n             apply H14; apply H13; easy. \n             unfold subset, partial_line; intros. \n             destruct H12 as [ [H12 H16] H17 ].\n             destruct (Rle_dec (fst c) (x - ϵ / 2)).\n             apply big_cup_extend_l. right. \n             rewrite H13 in H15.\n             apply H15; repeat split; auto. \n             apply Rnot_le_gt in n.\n             exists A; split. \n             left; easy. \n             apply H10.\n             unfold ϵ_disk. \n             apply (Rplus_le_compat_r (-x)) in H16.\n             apply (Rplus_lt_compat_r (-x)) in n.\n             replace (x + ϵ / 2 + - x)%R with (ϵ / 2)%R in H16 by lra. \n             replace (x - ϵ / 2 + - x)%R with (- ϵ / 2)%R in n by lra. \n             unfold Cmod; simpl; rewrite H17. \n             rewrite Rmult_1_r, Ropp_0, Rplus_0_r, Rmult_0_l, Rplus_0_r. \n             replace (Rmult (fst c + - x) (fst c + - x))%R with ((fst c + - x)²)%R by easy. \n             rewrite sqrt_Rsqr_abs; apply Rabs_def1; lra. }\n           apply H4 in H13. lra. \n         + apply (not_ub_implies_larger_elem _ 0) in H3.\n           destruct H3 as [a' [H3 H4] ].\n           apply (plc_less a' 1 G) in H3; try lra; easy. \n           apply zero_always_covered; easy. \nQed.\n\nDefinition horiz_Cline (a b h : R) : Cset :=\n   fun c => a <= fst c <= b /\\ snd c = h.\n       \nDefinition horiz_from_01_poly (a b h : R) : Polynomial := [(a, h) ; ((b - a)%R, 0)].\n\nLemma horiz_Cline_image : forall (a b h : R), \n  a <= b -> ((Peval (horiz_from_01_poly a b h)) @ unit_line) ⩦ (horiz_Cline a b h).\nProof. intros; split; intros. \n       - destruct H0 as [c0 [H0 H1] ]. \n         unfold Peval, horiz_Cline, horiz_from_01_poly in *; simpl in *.\n         destruct H0 as [ [H0 H2] H3].\n         unfold Cmult in H1; rewrite H3 in H1; simpl in H1.\n         assert (H1' := H1).\n         apply (f_equal fst) in H1; simpl in H1.\n         apply (f_equal snd) in H1'; simpl in H1'.\n         rewrite <- H1, <- H1'; simpl.\n         split; try lra. \n         unfold Rminus.\n         rewrite Rmult_0_r, Rmult_0_l, Ropp_0, Rplus_0_r, Rplus_0_l.\n         rewrite Rmult_0_r, Rmult_0_l, Ropp_0, Rplus_0_r.\n         do 2 rewrite Rmult_1_r; rewrite Rplus_0_r.\n         split. \n         assert (H' : forall a b : R, 0 <= b -> a <= a + b). intros. lra. \n         apply H'; apply Rmult_le_pos; lra. \n         assert (H' : 0 <= (b + - a)). lra.\n         apply (Rmult_le_compat_l _ (fst c0) 1) in H'; auto; lra. \n       - unfold horiz_Cline in H0. \n         destruct (Req_dec a b); subst.\n         + assert (H' : fst c = b). lra. \n           exists C0; split. \n           unfold unit_line; simpl; lra. \n           unfold horiz_from_01_poly, Peval; simpl. \n           apply c_proj_eq. simpl. \n           rewrite H'. lra. \n           destruct H0; rewrite H1; simpl; lra.\n         + assert (H' : b - a > 0). lra. apply Rinv_0_lt_compat in H'.\n           exists (((fst c) - a) / (b - a), 0)%R; split.\n           split; auto; simpl. \n           destruct H0 as [ [H0 H2] H3].\n           split. unfold Rdiv. apply Rmult_le_pos; lra. \n           apply (Rmult_le_reg_r (b - a)); try lra. \n           unfold Rdiv. rewrite Rmult_assoc, Rinv_l; lra. \n           unfold horiz_from_01_poly, Peval; simpl.\n           C_field_simplify. unfold Cmult; simpl.\n           do 2 rewrite Rmult_0_r; rewrite Rmult_0_l.\n           apply c_proj_eq; simpl; try lra. \n           unfold Rminus, Rdiv; rewrite Ropp_0, Rplus_0_r, Rmult_comm, Rmult_assoc, Rinv_l; lra.\nQed.\n\nLemma horiz_Cline_compact : forall (a b h : R), \n  compact (horiz_Cline a b h). \nProof. intros. \n       destruct (Rle_lt_dec a b).\n       - rewrite <- horiz_Cline_image; auto.\n         apply continuous_image_compact.\n         unfold continuous_on; intros. \n         apply polynomial_continuous.\n         apply unit_line_compact.\n       - exists (list_to_cover []).\n         repeat split.\n         exists []; easy. \n         unfold subcover; intros; easy. \n         unfold subset; intros. \n         unfold horiz_Cline in H2.\n         lra. \nQed.\n\n(* we now do it again for a vertical line *)\nDefinition verti_Cline (a b h : R) : Cset :=\n   fun c => a <= snd c <= b /\\ fst c = h.\n\nDefinition switch_pair (c : C) : C := (snd c, fst c).\n\nLemma switch_pair_Cmod : forall c, Cmod c = Cmod (switch_pair c).\nProof. intros. \n       unfold Cmod, switch_pair; simpl. \n       rewrite Rplus_comm; easy. \nQed.\n\nLemma switch_pair_minus : forall c c0, switch_pair (c - c0) = switch_pair c - switch_pair c0.\nProof. intros.\n       unfold switch_pair; easy.\nQed.\n\nLemma switch_pair_continuous_on_C : continuous_on switch_pair C_.\nProof. unfold continuous_on, continuous_at, limit_at_point; intros. \n       exists ϵ; split; auto; intros. \n       rewrite <- switch_pair_minus, <- switch_pair_Cmod; easy. \nQed.\n\nLemma verti_Cline_image : forall (a b h : R),\n  switch_pair @ (horiz_Cline a b h) ⩦ (verti_Cline a b h).\nProof. intros; split; intros.  \n       - destruct H as [c0 [H H0] ].\n         unfold horiz_Cline, verti_Cline, switch_pair in *.\n         destruct c; destruct c0; simpl in *.\n         assert (H1 := H0).\n         apply (f_equal fst) in H0; apply (f_equal snd) in H1; simpl in *; subst; easy. \n       - exists (snd c, fst c).\n         split. \n         unfold horiz_Cline, verti_Cline in *; simpl; easy. \n         unfold switch_pair; destruct c; simpl; easy. \nQed.\n\nLemma verti_Cline_compact : forall (a b h : R), \n  compact (verti_Cline a b h). \nProof. intros. \n       rewrite <- verti_Cline_image.\n       apply continuous_image_compact.\n       apply switch_pair_continuous_on_C.\n       apply horiz_Cline_compact.\nQed.\n\n(* now the main event, showing a cube is compact *)\n(* we use the same lub approach as before, but need some more lemmas *)\n\nDefinition center_square (s : R) : Cset :=\n  fun c => -s <= fst c <= s /\\ -s <= snd c <= s.\n\nDefinition partial_center_square (s x : R) : Cset :=\n  fun c => -s <= fst c <= x /\\ -s <= snd c <= s.\n\nDefinition partial_center_square_covered (G : Ccover) (s x : R) : Prop :=\n  exists G', finite_cover G' /\\ subcover G' G /\\ (partial_center_square s x) ⊂ (big_cup G').\n\nLemma line_in_square : forall (s h : R), \n  -s <= h <= s -> \n  ((verti_Cline (-s) s h) ⊂ (center_square s)).\nProof. unfold subset; intros. \n       unfold verti_Cline, center_square in *.\n       destruct H0; subst. easy. \nQed.      \n\nLemma zero_width_square : forall (s : R),\n  (partial_center_square s (-s)) ⩦ (verti_Cline (-s) s (-s)).\nProof. split; intros. \n       - unfold verti_Cline, partial_center_square in *.\n         split; try easy.\n         symmetry; apply Rle_le_eq; easy. \n       - unfold verti_Cline, partial_center_square in *.\n         split; try easy.\n         destruct H; rewrite H0; lra.\nQed.\n\nLemma negc_always_covered : forall (G : Ccover) (s : R),\n  s > 0 ->\n  WF_cover G -> open_cover G ->\n  (center_square s) ⊂ (big_cup G) -> \n  partial_center_square_covered G s (-s).\nProof. intros. \n       assert (H3 : (partial_center_square s (-s)) ⊂ (big_cup G)).\n       eapply subset_transitive; try apply H3.\n       rewrite zero_width_square.\n       apply line_in_square; try lra.\n       easy. \n       rewrite zero_width_square in H3.\n       apply verti_Cline_compact in H3; auto.\n       destruct H3 as [G' H3]. \n       exists G'; repeat split; try easy.\n       rewrite zero_width_square; easy.\nQed. \n\nLemma pcs_le_subset : forall (s x x' : R),\n  x' <= x -> \n  (partial_center_square s x') ⊂ (partial_center_square s x).\nProof. unfold partial_center_square, subset; intros. \n       repeat split; try easy. \n       destruct H0 as [ [H0 H1] H2].\n       lra. \nQed.       \n\n(* same analogue as plc_less *)\nLemma pcs_less : forall (s x x' : R) (G : Ccover),\n  x' <= x ->\n  partial_center_square_covered G s x ->\n  partial_center_square_covered G s x'.\nProof. intros. \n       unfold partial_center_square_covered in *.\n       destruct H0 as [G' [H0 [H1 H2] ] ].\n       exists G'; repeat split; auto. \n       eapply subset_transitive.\n       apply pcs_le_subset; eauto.\n       easy. \nQed.\n\nDefinition cover_to_centered_cube_cover (G : Ccover) (a b h : R) : Ccover :=\n  fun A => (exists s y A', s > 0 /\\ A ⩦ (open_square (h, y) s) /\\ G A' /\\ (open_square (h, y) s) ⊂ A').\n\nLemma WF_ctccc : forall (G : Ccover) (a b h : R),\n  WF_cover (cover_to_centered_cube_cover G a b h).\nProof. unfold WF_cover; intros. \n       destruct H.\n       destruct H0 as [s [y [A0 [H0 [H1 [H2 H3] ] ] ] ] ].\n       exists s, y, A0. \n       split; auto.\n       split; auto.\n       rewrite <- H; easy. \nQed.\n\nLemma cube_cover_ctccc : forall (G : Ccover) (a b h : R),\n  cube_cover (cover_to_centered_cube_cover G a b h).\nProof. unfold cube_cover; intros.\n       destruct H as [s [y [A' [H [H1 [H2 H3] ] ] ] ] ].\n       exists s, (h, y); split; auto.\nQed.\n\nLemma ctccc_smaller : forall (G : Ccover) (a b h : R),\n  (big_cup (cover_to_centered_cube_cover G a b h)) ⊂ (big_cup G).\nProof. unfold subset, big_cup; intros. \n       destruct H as [A [H H0] ].\n       destruct H as [s [y [A' H] ] ].\n       exists A'; split; try easy. \n       do 2 apply H; easy.\nQed.\n\nLemma ctccc_big_enough : forall (G : Ccover) (a b h : R),\n  open_cover G -> (verti_Cline a b h) ⊂ (big_cup G) ->\n  (verti_Cline a b h) ⊂ (big_cup (cover_to_centered_cube_cover G a b h)).\nProof. intros. \n       unfold subset; intros.  \n       assert (H' : fst c = h). apply H1.\n       apply H0 in H1.\n       destruct H1 as [A [H1 H2] ].\n       assert (H3 := H1); apply H in H3.\n       destruct (H3 c) as [ϵ [H4 H5] ]; auto.\n       assert (H6 := square_in_circle c ϵ).\n       exists (open_square c (ϵ / √ 2)); split.\n       exists (ϵ / √ 2)%R, (snd c), A.\n       split. \n       apply (lt_ep_helper ϵ); easy.\n       split. \n       destruct c; simpl in *; subst; easy.  \n       split; try easy.\n       eapply subset_transitive; try apply H5.\n       destruct c; simpl in *; subst; easy.  \n       apply square_contains_center.\n       apply (lt_ep_helper ϵ); easy.\nQed.\n\n(* maps a pair to a square whose center is (w, fst p) with side lenght snd p *)\nDefinition pair_to_sqaures (w : R) (p : R * R) : Cset := open_square (w, (fst p)) (snd p).\n\nLemma pts_gives_cube_cover : forall (h : R) (l : list (R * R)),\n  (forall p, In p l -> snd p > 0) -> \n  cube_cover (list_to_cover (map (pair_to_sqaures h) l)).\nProof. induction l as [| p].\n       - unfold cube_cover; intros; easy.\n       - unfold cube_cover; intros. \n         destruct H0.\n         exists (snd p), (h, fst p); split. \n         apply (H p); left; easy.\n         rewrite H0; easy.\n         apply IHl in H0; try easy.\n         intros.\n         apply (H p0); right; easy. \nQed.         \n\nLemma gen_ccc_list : forall (G : Ccover) (a b h : R) (l : list Cset),\n  subcover (list_to_cover l) (cover_to_centered_cube_cover G a b h) -> \n  exists l', (forall p, In p l' -> snd p > 0) /\\ \n          eq_cover (list_to_cover (map (pair_to_sqaures h) l')) (list_to_cover l).\nProof. induction l as [| A].\n       - intros; exists []; easy.  \n       - intros.\n         assert (H0 : subcover (list_to_cover l) (cover_to_centered_cube_cover G a b h)).\n         { unfold subcover; intros. \n           apply H; right; easy. }\n         apply IHl in H0.\n         assert (H1 : (cover_to_centered_cube_cover G a b h) A).\n         { apply H; left; easy. }\n         assert (H2 : exists (s y : R), s > 0 /\\ (A) ⩦ (open_square (h, y) s)).\n         { destruct H1 as [s [y [A0 [H1 H2] ] ] ].\n           exists s, y; easy. } \n         destruct H2 as [s [y [H2 H3] ] ].\n         destruct H0 as [l' H0].\n         exists ((y, s) :: l').\n         split; intros. \n         destruct H4; subst; simpl; auto.\n         apply H0; easy.\n         split; intros. \n         + destruct H4.\n           left; rewrite H3, H4; easy.\n           right; apply H0 in H4; easy.\n         + destruct H4.\n           left; rewrite H4, H3; easy.\n           right; apply H0; easy.\nQed.\n\nLemma min_side_length : forall (p0 : R * R) (l : list (R * R)),\n  (forall p, In p (p0 :: l) -> snd p > 0) -> \n  (exists min, 0 < min /\\ (forall p, In p (p0 :: l) -> min < snd p)).\nProof. induction l as [| p1].\n       - intros.  \n         exists ((snd p0) * /2)%R.\n         split. \n         apply Rmult_lt_0_compat; try lra. \n         apply (H p0); left; easy.\n         intros. \n         destruct H0; try easy; subst.\n         rewrite <- Rmult_1_r.\n         apply Rmult_lt_compat_l; try lra. \n         apply (H p); left; easy. \n       - intros. \n         assert (H' : (forall p : R * R, In p (p0 :: l) -> snd p > 0)).\n         { intros; apply (H p); destruct H0; try (left; easy); do 2 right; auto. }\n         apply IHl in H'.\n         destruct H' as [min [H0 H1] ]. \n         exists (Rmin min ((snd p1) * /2))%R.\n         split. apply Rmin_glb_lt; auto.\n         apply Rmult_lt_0_compat; try lra. \n         apply (H p1).\n         right; left; easy.  \n         intros.  \n         destruct H2. \n         + eapply Rle_lt_trans; try apply Rmin_l.\n           apply H1; left; easy. \n         + destruct H2; subst. \n           eapply Rle_lt_trans; try apply Rmin_r.\n           assert (H' : snd p > 0). apply H; right; left; easy.\n           lra. \n           eapply Rle_lt_trans; try apply Rmin_l.\n           apply H1; right; easy. \nQed.\n\nLemma boost_line : forall (a b h : R) (O : Cset),\n  a < b ->\n  open O -> (verti_Cline a b h) ⊂ O ->\n  exists ϵ, ϵ > 0 /\\ (verti_Cline (a - ϵ) (b + ϵ) h) ⊂ O.\nProof. intros.\n       assert (H2 : (verti_Cline a b h) (h, a)).\n       { unfold verti_Cline; split; simpl; lra. }\n       assert (H3 : (verti_Cline a b h) (h, b)).\n       { unfold verti_Cline; split; simpl; lra. }\n       apply H1 in H2; apply H1 in H3.\n       apply H0 in H2; apply H0 in H3.\n       destruct H2 as [ϵ1 [H2 H4] ].\n       destruct H3 as [ϵ2 [H3 H5] ].\n       exists (Rmin (ϵ1 * /2) (ϵ2 * /2)) .\n       split; try (apply Rmin_Rgt_r; lra). \n       unfold subset; intros. \n       destruct H6 as [H6 H7].\n       destruct (Rlt_le_dec b (snd c)).\n       - apply H5.\n         unfold ϵ_disk; destruct c; simpl in *; subst.\n         destruct H6; unfold Cminus, Cmod; simpl. \n         replace (h + - h)%R with 0 by lra. \n         rewrite Rmult_0_l, Rplus_0_l, Rmult_1_r, sqrt_square; try lra.\n         assert (H' := (Rmin_r (ϵ1 * /2) (ϵ2 * /2))); lra. \n       - destruct (Rlt_le_dec (snd c) a).\n         + apply H4.\n           unfold ϵ_disk; destruct c; simpl in *; subst.\n           destruct H6; unfold Cminus, Cmod; simpl. \n           replace (h + - h)%R with 0 by lra.\n           rewrite Rmult_0_l, Rplus_0_l, Rmult_1_r.  \n           replace ((r2 + - a) * (r2 + - a))%R with (r2 + - a)² by easy.\n           rewrite sqrt_Rsqr_abs, Rabs_left1; try lra.\n           replace (- (r2 + - a))%R with (a - r2)%R by lra. \n           assert (H' := (Rmin_l (ϵ1 * /2) (ϵ2 * /2))); lra. \n         + apply H1.\n           unfold verti_Cline; easy.\nQed.\n\n(* or is THIS the crucial lemma? *)\nLemma rect_within_centered_sqaures : forall (a b h : R) (l : list (R * R)),\n  a < b -> (forall p, In p l -> snd p > 0) ->\n  (verti_Cline a b h) ⊂ (big_cup (list_to_cover (map (pair_to_sqaures h) l))) ->\n  exists h' s1 s2, s1 > 0 /\\ s2 > 0 /\\ (verti_Cline a b h) ⊂ (open_rect (h, h') s1 s2) /\\\n             (open_rect (h, h') s1 s2) ⊂ (big_cup (list_to_cover (map (pair_to_sqaures h) l))).\nProof. intros. \n       destruct l as [| p].\n       - simpl in H1.\n         assert (H' : (verti_Cline a b h) (h, a)).\n         { unfold verti_Cline; split; simpl; try lra. }\n         apply H1 in H'.\n         destruct H'; try easy.\n       - exists ((b + a) * /2)%R.\n         apply boost_line in H1; auto.\n         destruct H1 as [ϵ [H1 H2] ].\n         apply min_side_length in H0.\n         destruct H0 as [min [H0 H3] ].\n         exists min, ((b - a) * /2 + ϵ)%R.\n         split; auto. split.\n         apply Rplus_lt_0_compat; auto.\n         apply Rmult_lt_0_compat; try lra.\n         split.\n         unfold subset, open_rect; intros. \n         destruct H4; destruct c; subst; simpl in *. \n         split.\n         rewrite Rminus_eq_0, Rabs_R0; auto.  \n         apply Rabs_def1; lra.\n         unfold subset; intros. \n         destruct H4; simpl.\n         assert (H' : (verti_Cline (a - ϵ) (b + ϵ) h) (h, snd c)).\n         { split; simpl in *; try easy.\n           apply Rabs_def2 in H5; lra. } \n         apply H2 in H'.\n         destruct H' as [A [H6 H7] ].\n         exists A; split; simpl; try easy. \n         unfold list_to_cover in H6.\n         apply In'_map in H6.\n         destruct H6 as [p0 [H6 H8] ].\n         apply H3 in H8.\n         apply H6; apply H6 in H7.\n         destruct c; split; simpl in *; try lra.\n         destruct H7; simpl in *; easy.\n         apply arb_cup_open.\n         apply cube_cover_open_cover.\n         apply pts_gives_cube_cover; easy. \nQed.\n\n(* the crucial lemma *)\nLemma rect_within_fin_cubecover : forall (a b h : R) (l : list Cset),\n  a < b ->\n  cube_cover (list_to_cover l) -> \n  (verti_Cline a b h) ⊂ (big_cup (list_to_cover l)) -> \n  exists h' s1 s2, s1 > 0 /\\ s2 > 0 /\\ (verti_Cline a b h) ⊂ (open_rect (h, h') s1 s2) /\\\n                 (open_rect (h, h') s1 s2) ⊂ (big_cup (list_to_cover l)).\nProof. intros. \n       apply cube_cover_open_cover in H0. \n       apply ctccc_big_enough in H1; try easy.\n       apply verti_Cline_compact in H1. \n       destruct H1 as [G' [H1 [H2 H3] ] ].\n       destruct H1 as [l' H1]. \n       assert (H2' := H2).\n       rewrite H1 in H2.\n       apply gen_ccc_list in H2.\n       destruct H2 as [l0 [H_ H2] ].       \n       rewrite H1, <- H2 in H3. \n       apply rect_within_centered_sqaures in H3; auto.\n       destruct H3 as [h' [s1 [s2 [H3 [H4 [H5 H6] ] ] ] ] ].\n       exists h', s1, s2. \n       split; auto. split; auto. split; auto.\n       eapply subset_transitive; try apply H6.\n       rewrite H2.\n       assert (H' := (ctccc_smaller (list_to_cover l) a b h)).\n       unfold subset; intros; apply H'.\n       assert (H8 : (big_cup G') ⩦ (big_cup ((list_to_cover l')))). rewrite H1; easy.\n       apply H8 in H7.\n       destruct H7 as [A [H7 H9] ].\n       exists A; split; auto.\n       apply cube_cover_open_cover.\n       apply cube_cover_ctccc.\n       apply WF_ctccc.\nQed.       \n\n\n(** TODO: write a program that reads this proof and makes a more efficient FTA proof. \n    There must be a better way than this... *)\nTheorem center_square_compact : forall (s : R),  \n  s > 0 -> compact (center_square s).\nProof. intros. \n       apply compact_is_cube_compact.\n       unfold cube_compact, center_square; intros. \n       destruct (Classical_Prop.classic (partial_center_square_covered G s s)).\n       - destruct H3 as [G' H3].\n         exists G'; easy.\n       - destruct (Classical_Prop.classic \n                     (is_upper_bound (partial_center_square_covered G s) s)).\n         + destruct (completeness (partial_center_square_covered G s)).\n           exists s; easy. \n           exists (-s)%R. \n           apply negc_always_covered; try easy. \n           apply cube_cover_open_cover; easy. \n           destruct i.\n           assert (H7 : x <= s). \n           { apply H6; easy. }\n           assert (H8 : (-s) <= x). \n           { apply H5; apply negc_always_covered; try easy. \n             apply cube_cover_open_cover; easy. } \n           assert (H9 :  (verti_Cline (-s) s x) ⊂ (big_cup G)).\n           { eapply subset_transitive; try apply H2.\n             apply line_in_square; easy. }\n           assert (H10 := verti_Cline_compact (-s) s x).\n           apply compact_is_cube_compact in H10.\n           apply H10 in H9; try easy.\n           destruct H9 as [G' [H9 [H11 H12] ] ].\n           destruct H9 as [l H9].\n           assert (H13 : cube_cover (list_to_cover l)).\n           { unfold cube_cover; intros. \n             rewrite H9 in H11.\n             apply H11 in H13.\n             apply H0 in H13; easy. }\n           rewrite H9 in H12.\n           apply rect_within_fin_cubecover in H12; auto.\n           destruct H12 as [h' [s1 [s2 [H12 [H14 [H15 H16] ] ] ] ] ].\n           assert (H17 : s1 / 2 > 0).\n           { unfold Rdiv; apply Rmult_gt_0_compat; lra. } \n           assert (H18 : partial_center_square_covered G s (x - s1 / 2)).\n           { apply (extract_elem_lt_lub \n                      (partial_center_square_covered G s) (-s) x (s1 / 2)) in H17; try easy.\n             destruct H17 as [x0 [H17 H18] ].\n             apply (pcs_less _ x0); auto; lra.  \n             apply negc_always_covered; try easy. \n             apply cube_cover_open_cover; easy. }\n           assert (H19 : partial_center_square_covered G s (x + s1 / 2)).\n           { destruct H18 as [G'' [H18 [H19 H20] ] ].\n             destruct H18 as [l' H18].\n             exists (list_to_cover (l ++ l')).\n             split. exists (l ++ l'); easy. \n             split. \n             unfold subcover; intros. \n             apply In'_app_or in H21.\n             destruct H21.\n             rewrite H9 in H11; apply H11; easy.\n             rewrite H18 in H19; apply H19; easy.\n             unfold subset; intros. \n             apply app_union.\n             destruct (Rle_dec (fst c) (x - s1 / 2)).\n             + right.\n               rewrite H18 in H20.\n               apply H20.\n               destruct H21.\n               split; try easy.\n             + left. \n               apply Rnot_le_gt in n.\n               apply H16.\n               split; simpl. \n               destruct H21. \n               assert (H' : s1 / 2 < s1).\n               unfold Rdiv. rewrite <- Rmult_1_r. \n               apply Rmult_lt_compat_l; lra.\n               destruct H21.  \n               apply Rabs_def1; lra.\n               assert (H22 :  (verti_Cline (- s) s x) (x, snd c)).\n               { destruct H21; split; try easy. }\n               apply H15 in H22.\n               destruct H22; easy. }\n           apply H5 in H19; lra.\n           lra.\n         + apply (not_ub_implies_larger_elem _ (-s)) in H4.\n           destruct H4 as [a' [H4 H5] ].\n           apply (pcs_less s a' s G) in H4; try lra; easy. \n           apply negc_always_covered; try easy.\n           apply cube_cover_open_cover; easy. \nQed.\n\n\n(**********************************************)\n(* Showing that compact is closed and bounded *)\n(**********************************************)\n\n(* first, we show compact -> bounded *)\nDefinition ball_cover : Ccover :=\n  fun G => open G /\\ exists r, r > 0 /\\ G ⊂ B(0,r).\n\nLemma open_cover_ball_cover : open_cover ball_cover.\nProof. unfold ball_cover; easy. Qed.\n      \nLemma WF_ball_cover : WF_cover ball_cover.\nProof. unfold ball_cover, WF_cover; intros.  \n       destruct H as [H [H0 [r [H1 H2] ] ] ].\n       split; try (rewrite <- H; easy). \n       exists r; split; auto. \n       rewrite <- H; easy. \nQed.\n\nLemma ball_cover_elems_bounded : forall (A : Cset),\n  ball_cover A -> bounded A.\nProof. intros. \n       unfold ball_cover, bounded in *.\n       destruct H.\n       destruct H0 as [r [H0 H1] ].\n       exists r; easy.\nQed.\n\nLemma C_subset_ball_cover : \n  C_ ⊂ (big_cup ball_cover).\nProof. unfold subset, big_cup, ball_cover; intros. \n       exists (B(0, Cmod c + 1)).\n       repeat split. \n       apply ball_open; apply Rle_lt_0_plus_1; apply Cmod_ge_0.\n       exists ((Cmod c) + 1)%R. \n       split; auto with Csub_db.\n       apply Rle_lt_0_plus_1; apply Cmod_ge_0.\n       unfold ϵ_disk. \n       replace (c - 0) with c by lca. \n       lra. \nQed.\n\nLemma list_cover_ball_cover_bounded : forall (l : list Cset),\n  subcover (list_to_cover l) ball_cover ->\n  bounded (big_cup (list_to_cover l)).\nProof. induction l as [| A].\n       - intros. \n         exists 1. \n         unfold subset; intros. \n         unfold big_cup, list_to_cover in H0.\n         destruct H0; easy.\n       - intros. \n         rewrite <- big_cup_extend_l.\n         unfold subcover in H.\n         apply bounded_cup.\n         apply ball_cover_elems_bounded; apply H.\n         left; easy. \n         apply IHl. \n         unfold subcover; intros. \n         apply H; right; easy. \nQed.\n\nLemma fin_subcover_ball_cover_bounded : forall (G : Ccover),\n  finite_cover G -> subcover G ball_cover -> \n  bounded (big_cup G).\nProof. intros. \n       destruct H as [l H]; subst.\n       rewrite H in *.\n       apply list_cover_ball_cover_bounded; easy. \nQed.\n\nLemma compact_implies_bounded : forall (A : Cset),\n  compact A -> bounded A. \nProof. intros. \n       unfold compact in H.\n       destruct (H ball_cover).\n       apply open_cover_ball_cover.\n       apply WF_ball_cover.\n       eapply subset_transitive.\n       eapply subset_C_.\n       apply C_subset_ball_cover.\n       destruct H0 as [H0 [H1 H2] ].\n       apply fin_subcover_ball_cover_bounded in H0; auto.\n       unfold bounded in *.\n       destruct H0 as [ϵ H0].\n       exists ϵ; eauto with Csub_db.\nQed.\n\n\n(* now, we show compact -> closed *)\nDefinition bad_point_cover (c : C) : Ccover :=\n  fun G => open G /\\ exists r, r > 0 /\\ G ⊂ (fun c' => Cmod (c' - c) > r).\n\nLemma open_cover_bpc : forall c, open_cover (bad_point_cover c).\nProof. unfold bad_point_cover; easy. Qed.\n\nLemma WF_bpc : forall c, WF_cover (bad_point_cover c).\nProof. unfold WF_cover, bad_point_cover; intros. \n       destruct H as [H [H1 [r [H2 H3] ] ] ].\n       split; try (rewrite <- H; easy).\n       exists r; split; auto; rewrite <- H; easy. \nQed.\n\nLemma bpc_covers_almost_all : forall (c : C) (A : Cset),\n  A` c -> A ⊂ (big_cup (bad_point_cover c)).\nProof. unfold subset; intros. \n       unfold bad_point_cover, big_cup.\n       exists (fun c' => Cmod (c' - c) > Cmod (c0 - c) / 2).\n       assert (H' :  Cmod (c0 - c) > 0).\n       { apply Cmod_gt_0.\n         apply Cminus_eq_contra.\n         destruct (Ceq_dec c0 c); subst; easy. }\n       repeat split; try lra.\n       apply closed_ball_complement_open.\n       exists ((Cmod (c0 - c)) / 2)%R.\n       split; auto with Csub_db.\n       apply Rdiv_lt_0_compat; try lra. \nQed.\n\nLemma bpc_separates_from_c : forall (c : C) (l : list Cset),\n  subcover (list_to_cover l) (bad_point_cover c) ->\n  exists r, r > 0 /\\ (big_cup (list_to_cover l)) ⊂ (fun c' => Cmod (c' - c) > r).\nProof. induction l as [| A].\n       - intros; exists 1; split; try lra. \n         unfold subset; intros. \n         unfold list_to_cover, big_cup in H0. \n         destruct H0; easy. \n       - intros. \n         apply subcover_reduce in H; repeat destruct H.\n         destruct H1 as [r1 [H1 H2] ].\n         apply IHl in H0.\n         destruct H0 as [r2 [H0 H3] ].\n         exists (Rmin r1 r2); split. \n         apply Rmin_glb_lt; auto. \n         unfold list_to_cover, big_cup, subset; intros. \n         destruct H4 as [A0 [ [H4 | H4] H5] ]; subst. \n         + apply H4 in H5.\n           apply H2 in H5.\n           eapply Rgt_ge_trans; eauto.\n           assert (H' := Rmin_l r1 r2). lra. \n         + assert (H' : (big_cup (list_to_cover l)) c0).\n           { exists A0; split; easy. }\n           apply H3 in H'.\n           eapply Rgt_ge_trans; eauto.\n           assert (H'' := Rmin_r r1 r2). lra. \nQed.\n\nLemma compact_implies_closed : forall (A : Cset),\n  compact A -> closed A. \nProof. unfold compact, closed, open; intros. \n       destruct (H (bad_point_cover c)) as [G' [H1 [H2 H3] ] ].\n       apply open_cover_bpc.\n       apply WF_bpc.\n       apply bpc_covers_almost_all; easy. \n       destruct H1 as [l H1]; subst.\n       rewrite H1 in *.\n       apply bpc_separates_from_c in H2.\n       destruct H2 as [r [H2 H4] ].\n       exists r; split; auto.\n       unfold complement, ϵ_disk, subset, not; intros. \n       apply H3 in H6; apply H4 in H6; lra. \nQed.\n\nLemma add_comp_covers_all : forall (A : Cset) (G : Ccover),\n  WF_cover G -> A ⊂ (big_cup G) ->\n  C_ ⊂ (big_cup (fun A' : Cset => G A' \\/ (A') ⩦ ((A) `) )).\nProof. intros.\n       unfold subset, C_, big_cup; intros. \n       destruct (Classical_Prop.classic (A c)).\n       - apply H0 in H2.\n         destruct H2 as [A' [H2 H3] ].\n         exists A'; split; auto. \n       - exists A`; split; auto. \n         right; easy. \nQed.\n\nLemma closed_subset_compact : forall (A B : Cset),\n  A ⊂ B -> compact B -> closed A -> \n  compact A.\nProof. unfold compact; intros. \n       destruct (H0 (fun A' => G A' \\/ A' ⩦ ((A) `) )).\n       unfold open_cover; intros. \n       destruct H5; try (rewrite H5; easy). \n       apply H2 in H5; easy.\n       unfold WF_cover; intros.\n       destruct H5; destruct H6. \n       left; apply (H3 A0 A'); easy. \n       right; rewrite <- H5; easy. \n       eapply subset_transitive.\n       eapply subset_C_.\n       apply add_comp_covers_all; easy. \n       destruct H5. destruct H5 as [l H5].\n       exists (fun A' => x A' /\\ ~ (A' ⩦ (A`))).\n       split; try split. \n       - apply (finite_cover_subset l).\n         unfold WF_cover; intros. \n         destruct H7 as [H7 [H8 H9] ].\n         split. \n         apply H5 in H8; apply H5.\n         apply ((WF_finitecover l) A0 A'); easy. \n         unfold not; intros; apply H9. \n         rewrite H7; easy. \n         rewrite <- H5. \n         unfold subcover; intros; easy. \n       - destruct H6.  \n         unfold subcover; intros. \n         destruct H8. \n         apply H6 in H8.\n         destruct H8; easy. \n       - unfold subset, big_cup; intros. \n         destruct H6. \n         apply (subset_transitive A B) in H8; auto. \n         destruct (H8 c); auto. \n         exists x0; split; try easy. \n         split; try easy. \n         unfold not; intros. \n         destruct H9; apply H10 in H11.\n         apply H11; easy. \nQed.\n\nLemma closed_bounded_implies_compact : forall (A : Cset),\n  closed A -> bounded A ->\n  compact A.\nProof. intros. \n       destruct H0 as [ϵ H0].\n       assert (H1 : A ⊂ (center_square ϵ)).\n       { unfold subset; intros. \n         apply H0 in H1.\n         unfold ϵ_disk in H1.\n         replace (c - 0)%C with c in H1 by lca. \n         assert (H' := (Rmax_Cmod c)).\n         apply (Rle_lt_trans _ _ ϵ) in H'; auto.\n         split. \n         + apply (Rle_lt_trans (Rabs (fst c)) _ ϵ) in H'; try apply Rmax_l.\n           apply Rabs_def2 in H'; lra.\n         + apply (Rle_lt_trans (Rabs (snd c)) _ ϵ) in H'; try apply Rmax_r.\n           apply Rabs_def2 in H'; lra. }\n       apply closed_subset_compact in H1; auto.\n       destruct (Rlt_le_dec 0 ϵ).\n       apply center_square_compact; easy.\n       unfold compact; intros. \n       destruct (Rlt_le_dec ϵ 0).\n       exists (list_to_cover []); split. \n       exists []; easy. split.\n       unfold subcover; intros; easy. \n       unfold subset; intros. \n       unfold center_square in H5; lra. \n       apply Rle_antisym in r; auto; subst.\n       assert (H' : (big_cup G) 0).\n       apply H4. \n       unfold center_square; simpl; lra.\n       destruct H' as [A' [H5 H6] ].\n       exists (list_to_cover [A']).\n       repeat split. \n       exists [A']; easy.\n       unfold subcover; intros. \n       destruct H7; try easy.\n       apply (H3 A' A0); easy. \n       unfold subset; intros. \n       destruct H7 as [ [H7 H8] [H9 H10] ]. \n       replace (-0)%R with 0 in * by lra.\n       apply Rle_antisym in H7; auto.\n       apply Rle_antisym in H9; auto.\n       destruct c; simpl in *; subst. \n       exists A'. split; auto.\n       left; easy.\nQed.\n\nTheorem Heine_Borel : forall (A : Cset),\n  compact A <-> closed A /\\ bounded A.\nProof. split; intros. \n       split. \n       apply compact_implies_closed; easy.\n       apply compact_implies_bounded; easy.\n       apply closed_bounded_implies_compact; easy.\nQed.\n\n(** showing that closed sets have a minimum norm element *)\n\n\nDefinition nonneg_real_line : Cset := \n  fun c => fst c >= 0 /\\ snd c = 0.\n\nLemma continuous_Cmod : continuous_on Cmod C_.\nProof. unfold continuous_on, C_, continuous_at, limit_at_point; intros. \n       exists ϵ.\n       split; auto; intros. \n       assert (H3 := Cmod_triangle (x - c) c).\n       assert (H4 := Cmod_triangle (c - x) x).\n       replace (Cminus (RtoC (Cmod x)) (RtoC (Cmod c))) with\n               (RtoC (Rminus (Cmod x) (Cmod c))) by lca.\n       rewrite Cmod_R.\n       apply Rabs_def1.\n       replace (x - c + c) with x in H3 by lca; lra. \n       replace (c - x + x) with c in H4 by lca.\n       rewrite <- Ropp_minus_distr.\n       apply Ropp_lt_contravar.\n       rewrite Cmod_switch in H2; lra. \nQed.\n\nLemma image_nnp : Cmod @ C_ ⩦ nonneg_real_line.\nProof. unfold nonneg_real_line.\n       split; intros. \n       destruct H as [c0 [_ H] ]; subst; simpl.  \n       split; try easy.\n       assert (H' := Cmod_ge_0 c0); lra. \n       exists (fst c)%R.\n       split; try easy.\n       destruct H; destruct c; simpl in *; subst.\n       apply injective_projections; simpl; try easy.\n       rewrite Cmod_R, Rabs_right; lra.\nQed.\n\nLemma not_lb_implies_smaller_elem : forall (E : R -> Prop) (a b : R),\n  E a -> ~ (is_lower_bound E b) ->\n  exists a', E a' /\\ a' < b.\nProof. intros. \n       destruct (Classical_Prop.classic (exists a' : R, E a' /\\ a' < b)); auto. \n       assert (H' : is_lower_bound E b). \n       { unfold is_lower_bound; intros. \n         destruct (Classical_Prop.classic (b <= x)); auto. \n         apply Rnot_le_lt in H3.\n         assert (H'' : False).\n         apply H1. \n         exists x; easy. \n         easy. }\n       easy. \nQed.\n\nLemma extract_elem_gt_glb : forall (E : R -> Prop) (a glb ϵ : R),\n  E a -> ϵ > 0 -> is_glb E glb ->\n  exists x, (E x /\\ x < glb + ϵ). \nProof. intros. \n       apply (not_lb_implies_smaller_elem _ a); auto. \n       unfold not; intros. \n       destruct H1.\n       apply H3 in H2.\n       lra. \nQed.\n\nLemma closed_line_has_min : forall (A : Cset),\n  closed A -> A ⊂ nonneg_real_line -> \n  (exists c, A c) ->\n  exists min, A (min, 0) /\\ (forall p, A p -> min <= fst p).\nProof. intros. \n       assert (H2 : bounded_below (fun x => A (x, 0))).\n       { exists 0; unfold is_lower_bound; intros.\n         apply H0 in H2.\n         destruct H2; simpl in *; lra. }\n       destruct (glb_completeness (fun x : R => A (x, 0))) as [glb [H3 H4] ]; auto.\n       destruct H1; exists (fst x); destruct x; simpl in *.\n       destruct (H0 _ H1); simpl in *; subst; easy.\n       exists glb; split. \n       destruct (Classical_Prop.classic (A (glb, 0))); auto.\n       unfold closed in H.\n       assert (H' : (A`) (glb, 0)). easy. \n       apply H in H'.\n       destruct H' as [ϵ [H6 H7] ].\n       destruct H1 as [c0 H1].\n       destruct (extract_elem_gt_glb (fun x : R => A (x, 0)) (fst c0) glb ϵ) as [x [H8 H9] ]; auto.\n       destruct (H0 _ H1); destruct c0; simpl in *; subst; easy. \n       split; auto. \n       assert (H' : glb <= x).\n       { apply H3; easy. }\n       assert (H10 : A` (x, 0)).\n       { apply H7.\n         unfold ϵ_disk, Cmod; simpl. \n         rewrite Ropp_0, Rplus_0_l, Rmult_0_l, Rplus_0_r, Rmult_1_r.\n         replace ((x + - glb) * (x + - glb))%R with ((x + - glb)²) by easy.\n         rewrite sqrt_Rsqr_abs.\n         apply Rabs_def1; try lra. } \n       easy.\n       intros. \n       apply H3.\n       destruct p; destruct (H0 _ H5); simpl in *; subst; easy. \nQed.\n\nLemma compact_contains_min_norn_elem : forall (A : Cset),\n  (exists c, A c) -> compact A -> \n  (exists mne, A mne /\\ (forall c, A c -> Cmod mne <= Cmod c)).\nProof. intros. \n       apply (continuous_image_compact Cmod) in H0; try apply continuous_Cmod.\n       apply Heine_Borel in H0; destruct H0.\n       apply closed_line_has_min in H0.\n       destruct H0 as [min [H0 H2] ].\n       destruct H0 as [mne [H0 H3] ].\n       exists mne; split; auto.\n       intros. \n       apply (f_equal fst) in H3; simpl in H3.\n       rewrite H3.\n       assert (H' : (fun x : C => Cmod x) @ (A) (Cmod c)).\n       { exists c; easy. }\n       apply H2 in H'; easy.  \n       rewrite <- image_nnp.\n       apply subset_image; easy. \n       destruct H.\n       exists (Cmod x).\n       exists x; easy. \nQed.\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/Ctopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.6956934361607181}}
{"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(** Sets as characteristic functions *)\n\n(* G. Huet 1-9-95 *)\n(* Updated Papageno 12/98 *)\n\nRequire Import Bool.\n\nSet Implicit Arguments.\n\nSection defs.\n\nVariable A : Set.\nVariable eqA : A -> A -> Prop.\nHypothesis eqA_dec : forall x y:A, {eqA x y} + {~ eqA x y}.\n\nInductive uniset : Set :=\n    Charac : (A -> bool) -> uniset.\n\nDefinition charac (s:uniset) (a:A) : bool := let (f) := s in f a.\n\nDefinition Emptyset := Charac (fun a:A => false).\n\nDefinition Fullset := Charac (fun a:A => true).\n\nDefinition Singleton (a:A) :=\n  Charac\n    (fun a':A =>\n       match eqA_dec a a' with\n       | left h => true\n       | right h => false\n       end).\n\nDefinition In (s:uniset) (a:A) : Prop := charac s a = true.\nHint Unfold In.\n\n(** uniset inclusion *)\nDefinition incl (s1 s2:uniset) := forall a:A, leb (charac s1 a) (charac s2 a).\nHint Unfold incl.\n\n(** uniset equality *)\nDefinition seq (s1 s2:uniset) := forall a:A, charac s1 a = charac s2 a.\nHint Unfold seq.\n\nLemma leb_refl : forall b:bool, leb b b.\nProof.\ndestruct b; simpl in |- *; auto.\nQed.\nHint Resolve leb_refl.\n\nLemma incl_left : forall s1 s2:uniset, seq s1 s2 -> incl s1 s2.\nProof.\nunfold incl in |- *; intros s1 s2 E a; elim (E a); auto.\nQed.\n\nLemma incl_right : forall s1 s2:uniset, seq s1 s2 -> incl s2 s1.\nProof.\nunfold incl in |- *; intros s1 s2 E a; elim (E a); auto.\nQed.\n\nLemma seq_refl : forall x:uniset, seq x x.\nProof.\ndestruct x; unfold seq in |- *; auto.\nQed.\nHint Resolve seq_refl.\n\nLemma seq_trans : forall x y z:uniset, seq x y -> seq y z -> seq x z.\nProof.\nunfold seq in |- *.\ndestruct x; destruct y; destruct z; simpl in |- *; intros.\nrewrite H; auto.\nQed.\n\nLemma seq_sym : forall x y:uniset, seq x y -> seq y x.\nProof.\nunfold seq in |- *.\ndestruct x; destruct y; simpl in |- *; auto.\nQed.\n\n(** uniset union *)\nDefinition union (m1 m2:uniset) :=\n  Charac (fun a:A => orb (charac m1 a) (charac m2 a)).\n\nLemma union_empty_left : forall x:uniset, seq x (union Emptyset x).\nProof.\nunfold seq in |- *; unfold union in |- *; simpl in |- *; auto.\nQed.\nHint Resolve union_empty_left.\n\nLemma union_empty_right : forall x:uniset, seq x (union x Emptyset).\nProof.\nunfold seq in |- *; unfold union in |- *; simpl in |- *.\nintros x a; rewrite (orb_b_false (charac x a)); auto.\nQed.\nHint Resolve union_empty_right.\n\nLemma union_comm : forall x y:uniset, seq (union x y) (union y x).\nProof.\nunfold seq in |- *; unfold charac in |- *; unfold union in |- *.\ndestruct x; destruct y; auto with bool.\nQed.\nHint Resolve union_comm.\n\nLemma union_ass :\n forall x y z:uniset, seq (union (union x y) z) (union x (union y z)).\nProof.\nunfold seq in |- *; unfold union in |- *; unfold charac in |- *.\ndestruct x; destruct y; destruct z; auto with bool.\nQed.\nHint Resolve union_ass.\n\nLemma seq_left : forall x y z:uniset, seq x y -> seq (union x z) (union y z).\nProof.\nunfold seq in |- *; unfold union in |- *; unfold charac in |- *.\ndestruct x; destruct y; destruct z.\nintros; elim H; auto.\nQed.\nHint Resolve seq_left.\n\nLemma seq_right : forall x y z:uniset, seq x y -> seq (union z x) (union z y).\nProof.\nunfold seq in |- *; unfold union in |- *; unfold charac in |- *.\ndestruct x; destruct y; destruct z.\nintros; elim H; auto.\nQed.\nHint Resolve seq_right.\n\n\n(** All the proofs that follow duplicate [Multiset_of_A] *)\n\n(** Here we should make uniset an abstract datatype, by hiding [Charac],\n    [union], [charac]; all further properties are proved abstractly *)\n\nRequire Import Permut.\n\nLemma union_rotate :\n forall x y z:uniset, seq (union x (union y z)) (union z (union x y)).\nProof.\nintros; apply (op_rotate uniset union seq); auto.\nexact seq_trans.\nQed.\n\nLemma seq_congr :\n forall x y z t:uniset, seq x y -> seq z t -> seq (union x z) (union y t).\nProof.\nintros; apply (cong_congr uniset union seq); auto.\nexact seq_trans.\nQed.\n\nLemma union_perm_left :\n forall x y z:uniset, seq (union x (union y z)) (union y (union x z)).\nProof.\nintros; apply (perm_left uniset union seq); auto.\nexact seq_trans.\nQed.\n\nLemma uniset_twist1 :\n forall x y z t:uniset,\n   seq (union x (union (union y z) t)) (union (union y (union x t)) z).\nProof.\nintros; apply (twist uniset union seq); auto.\nexact seq_trans.\nQed.\n\nLemma uniset_twist2 :\n forall x y z t:uniset,\n   seq (union x (union (union y z) t)) (union (union y (union x z)) t).\nProof.\nintros; apply seq_trans with (union (union x (union y z)) t).\napply seq_sym; apply union_ass.\napply seq_left; apply union_perm_left.\nQed.\n\n(** specific for treesort *)\n\nLemma treesort_twist1 :\n forall x y z t u:uniset,\n   seq u (union y z) ->\n   seq (union x (union u t)) (union (union y (union x t)) z).\nProof.\nintros; apply seq_trans with (union x (union (union y z) t)).\napply seq_right; apply seq_left; trivial.\napply uniset_twist1.\nQed.\n\nLemma treesort_twist2 :\n forall x y z t u:uniset,\n   seq u (union y z) ->\n   seq (union x (union u t)) (union (union y (union x z)) t).\nProof.\nintros; apply seq_trans with (union x (union (union y z) t)).\napply seq_right; apply seq_left; trivial.\napply uniset_twist2.\nQed.\n\n\n(*i theory of minter to do similarly\nRequire Min.\n(* uniset intersection *)\nDefinition minter := [m1,m2:uniset]\n    (Charac [a:A](andb (charac m1 a)(charac m2 a))).\ni*)\n\nEnd defs.\n\nUnset Implicit Arguments.\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/Sets/Uniset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.6956934233148084}}
{"text": "(* mathcomp analysis (c) 2017 Inria and AIST. License: CeCILL-C.              *)\nFrom mathcomp Require Import all_ssreflect ssralg ssrint ssrnum finmap matrix.\nFrom mathcomp Require Import rat interval zmodp vector fieldext falgebra.\nFrom mathcomp.classical Require Import boolp classical_sets functions.\nFrom mathcomp.classical Require Import cardinality set_interval mathcomp_extra.\nRequire Import ereal reals signed topology prodnormedzmodule.\n\n(******************************************************************************)\n(* This file extends the topological hierarchy with norm-related notions.     *)\n(*                                                                            *)\n(* Note that balls in topology.v are not necessarily open, here they are.     *)\n(*                                                                            *)\n(* * Normed Topological Abelian groups:                                       *)\n(*  pseudoMetricNormedZmodType R  == interface type for a normed topological  *)\n(*                                   Abelian group equipped with a norm       *)\n(*  PseudoMetricNormedZmodule.Mixin nb == builds the mixin for a normed       *)\n(*                                   topological Abelian group from the       *)\n(*                                   compatibility between the norm and       *)\n(*                                   balls; the carrier type must have a      *)\n(*                                   normed Zmodule over a numDomainType.     *)\n(*                                                                            *)\n(* * Normed modules :                                                         *)\n(*                normedModType K == interface type for a normed module       *)\n(*                                   structure over the numDomainType K.      *)\n(*           NormedModMixin normZ == builds the mixin for a normed module     *)\n(*                                   from the property of the linearity of    *)\n(*                                   the norm; the carrier type must have a   *)\n(*                                   pseudoMetricNormedZmodType structure     *)\n(*            NormedModType K T m == packs the mixin m to build a             *)\n(*                                   normedModType K; T must have canonical   *)\n(*                                   pseudoMetricNormedZmodType K and         *)\n(*                                   pseudoMetricType structures.             *)\n(*  [normedModType K of T for cT] == T-clone of the normedModType K structure *)\n(*                                   cT.                                      *)\n(*         [normedModType K of T] == clone of a canonical normedModType K     *)\n(*                                   structure on T.                          *)\n(*                           `|x| == the norm of x (notation from ssrnum).    *)\n(*                      ball_norm == balls defined by the norm.               *)\n(*                      nbhs_norm == neighborhoods defined by the norm.       *)\n(*                    closed_ball == closure of a ball.                       *)\n(*   f @`[ a , b ], f @`] a , b [ == notations for images of intervals,       *)\n(*                                   intended for continuous, monotonous      *)\n(*                                   functions, defined in ring_scope and     *)\n(*                                   classical_set_scope respectively as:     *)\n(*                  f @`[ a , b ] := `[minr (f a) (f b), maxr (f a) (f b)]%O  *)\n(*                  f @`] a , b [ := `]minr (f a) (f b), maxr (f a) (f b)[%O  *)\n(*                  f @`[ a , b ] := `[minr (f a) (f b),                      *)\n(*                                     maxr (f a) (f b)]%classic              *)\n(*                  f @`] a , b [ := `]minr (f a) (f b),                      *)\n(*                                     maxr (f a) (f b)[%classic              *)\n(*                                                                            *)\n(* * Domination notations:                                                    *)\n(*              dominated_by h k f F == `|f| <= k * `|h|, near F              *)\n(*                  bounded_near f F == f is bounded near F                   *)\n(*            [bounded f x | x in A] == f is bounded on A, ie F := globally A *)\n(*   [locally [bounded f x | x in A] == f is locally bounded on A             *)\n(*                       bounded_set == set of bounded sets.                  *)\n(*                                   := [set A | [bounded x | x in A]]        *)\n(*                       bounded_fun == set of functions bounded on their     *)\n(*                                      whole domain.                         *)\n(*                                   := [set f | [bounded f x | x in setT]]   *)\n(*                  lipschitz_on f F == f is lipschitz near F                 *)\n(*          [lipschitz f x | x in A] == f is lipschitz on A                   *)\n(* [locally [lipschitz f x | x in A] == f is locally lipschitz on A           *)\n(*               k.-lipschitz_on f F == f is k.-lipschitz near F              *)\n(*                  k.-lipschitz_A f == f is k.-lipschitz on A                *)\n(*        [locally k.-lipschitz_A f] == f is locally k.-lipschitz on A        *)\n(*                   contraction q f == f is q.-lipschitz and q < 1           *)\n(*                  is_contraction f == exists q, f is q.-lipschitz and q < 1 *)\n(*                                                                            *)\n(*                     is_interval E == the set E is an interval              *)\n(*                bigcup_ointsub U q == union of open real interval included  *)\n(*                                      in U and that contain the rational    *)\n(*                                      number q                              *)\n(*                           Rhull A == the real interval hull of a set A     *)\n(*                         shift x y == y + x                                 *)\n(*                          center c := shift (- c)                           *)\n(*                                                                            *)\n(* * Complete normed modules :                                                *)\n(*        completeNormedModType K == interface type for a complete normed     *)\n(*                                   module structure over a realFieldType    *)\n(*                                   K.                                       *)\n(* [completeNormedModType K of T] == clone of a canonical complete normed     *)\n(*                                   module structure over K on T.            *)\n(*                                                                            *)\n(* * Filters :                                                                *)\n(*          at_left x, at_right x == filters on real numbers for predicates   *)\n(*                                   s.t. nbhs holds on the left/right of x   *)\n(*                                                                            *)\n(* --> We used these definitions to prove the intermediate value theorem and  *)\n(*     the Heine-Borel theorem, which states that the compact sets of R^n are *)\n(*     the closed and bounded sets.                                           *)\n(*                                                                            *)\n(******************************************************************************)\n\nReserved Notation \"f @`[ a , b ]\" (at level 20, b at level 9,\n  format \"f  @`[ a ,  b ]\").\nReserved Notation \"f @`] a , b [\" (at level 20, b at level 9,\n  format \"f  @`] a ,  b [\").\nReserved Notation \"x ^'+\" (at level 3, format \"x ^'+\").\nReserved Notation \"x ^'-\" (at level 3, format \"x ^'-\").\nReserved Notation \"+oo_ R\" (at level 3, format \"+oo_ R\").\nReserved Notation \"-oo_ R\" (at level 3, format \"-oo_ R\").\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport Order.TTheory GRing.Theory Num.Def Num.Theory.\nImport numFieldTopology.Exports.\n\nLocal Open Scope classical_set_scope.\nLocal Open Scope ring_scope.\n\nDefinition pointed_of_zmodule (R : zmodType) : pointedType := PointedType R 0.\n\nDefinition filtered_of_normedZmod (K : numDomainType) (R : normedZmodType K)\n  : filteredType R := Filtered.Pack (Filtered.Class\n    (@Pointed.class (pointed_of_zmodule R))\n    (nbhs_ball_ (ball_ (fun x => `|x|)))).\n\nSection pseudoMetric_of_normedDomain.\nVariables (K : numDomainType) (R : normedZmodType K).\nLemma ball_norm_center (x : R) (e : K) : 0 < e -> ball_ normr x e x.\nProof. by move=> ? /=; rewrite subrr normr0. Qed.\nLemma ball_norm_symmetric (x y : R) (e : K) :\n  ball_ normr x e y -> ball_ normr y e x.\nProof. by rewrite /= distrC. Qed.\nLemma ball_norm_triangle (x y z : R) (e1 e2 : K) :\n  ball_ normr x e1 y -> ball_ normr y e2 z -> ball_ normr x (e1 + e2) z.\nProof.\nmove=> /= ? ?; rewrite -(subr0 x) -(subrr y) opprD opprK (addrA x _ y) -addrA.\nby rewrite (le_lt_trans (ler_norm_add _ _)) // ltr_add.\nQed.\nDefinition pseudoMetric_of_normedDomain\n  : PseudoMetric.mixin_of K (@entourage_ K R R (ball_ (fun x => `|x|)))\n  := PseudoMetricMixin ball_norm_center ball_norm_symmetric ball_norm_triangle erefl.\n\nLemma nbhs_ball_normE :\n  @nbhs_ball_ K R R (ball_ normr) = nbhs_ (entourage_ (ball_ normr)).\nProof.\nrewrite /nbhs_ entourage_E predeq2E => x A; split.\n  move=> [e egt0 sbeA].\n  by exists [set xy | ball_ normr xy.1 e xy.2] => //; exists e.\nby move=> [E [e egt0 sbeE] sEA]; exists e => // ??; apply/sEA/sbeE.\nQed.\nEnd pseudoMetric_of_normedDomain.\n\nLemma nbhsN (R : numFieldType) (x : R) : nbhs (- x) = -%R @ x.\nProof.\nrewrite predeqE => A; split=> //= -[] e e_gt0 xeA; exists e => //= y /=.\n  by move=> ?; apply: xeA => //=; rewrite -opprD normrN.\nby rewrite -opprD normrN => ?; rewrite -[y]opprK; apply: xeA; rewrite /= opprK.\nQed.\n\nLemma nbhsNimage (R : numFieldType) (x : R) :\n  nbhs (- x) = [set -%R @` A | A in nbhs x].\nProof.\nrewrite nbhsN /fmap/=; under eq_set => A do rewrite preimageEinv//= inv_oppr.\nby rewrite (eq_imageK opprK opprK).\nQed.\n\nLemma nearN (R : numFieldType) (x : R) (P : R -> Prop) :\n  (\\forall y \\near - x, P y) <-> \\near x, P (- x).\nProof. by rewrite -near_simpl nbhsN. Qed.\n\nLemma openN (R : numFieldType) (A : set R) :\n  open A -> open [set - x | x in A].\nProof.\nmove=> Aop; rewrite openE => _ [x /Aop x_A <-].\nby rewrite /interior nbhsNimage; exists A.\nQed.\n\nLemma closedN (R : numFieldType) (A : set R) :\n  closed A -> closed [set - x | x in A].\nProof.\nmove=> Acl x clNAx.\nsuff /Acl : closure A (- x) by exists (- x)=> //; rewrite opprK.\nmove=> B oppx_B; have : [set - x | x in A] `&` [set - x | x in B] !=set0.\n  by apply: clNAx; rewrite -[x]opprK nbhsNimage; exists B.\nmove=> [y [[z Az oppzey] [t Bt opptey]]]; exists (- y).\nby split; [rewrite -oppzey opprK|rewrite -opptey opprK].\nQed.\n\nModule PseudoMetricNormedZmodule.\nSection ClassDef.\nVariable R : numDomainType.\nRecord mixin_of (T : normedZmodType R) (ent : set (set (T * T)))\n    (m : PseudoMetric.mixin_of R ent) := Mixin {\n  _ : PseudoMetric.ball m = ball_ (fun x => `| x |) }.\n\nRecord class_of (T : Type) := Class {\n  base : Num.NormedZmodule.class_of R T;\n  pointed_mixin : Pointed.point_of T ;\n  nbhs_mixin : Filtered.nbhs_of T T ;\n  topological_mixin : @Topological.mixin_of T nbhs_mixin ;\n  uniform_mixin : @Uniform.mixin_of T nbhs_mixin ;\n  pseudoMetric_mixin :\n    @PseudoMetric.mixin_of R T (Uniform.entourage uniform_mixin) ;\n  mixin : @mixin_of (Num.NormedZmodule.Pack _ base) _ pseudoMetric_mixin\n}.\nLocal Coercion base : class_of >-> Num.NormedZmodule.class_of.\nDefinition base2 T c := @PseudoMetric.Class _ _\n    (@Uniform.Class _\n      (@Topological.Class _\n        (Filtered.Class\n         (Pointed.Class (@base T c) (pointed_mixin c))\n         (nbhs_mixin c))\n        (topological_mixin c))\n      (uniform_mixin c))\n    (pseudoMetric_mixin c).\nLocal Coercion base2 : class_of >-> PseudoMetric.class_of.\n(* TODO: base3? *)\n\nStructure type (phR : phant R) :=\n  Pack { sort; _ : class_of sort }.\nLocal Coercion sort : type >-> Sortclass.\n\nVariables (phR : phant R) (T : Type) (cT : type phR).\n\nDefinition class := let: Pack _ c := cT return class_of cT in c.\nDefinition clone c of phant_id class c := @Pack phR T c.\nLet xT := let: Pack T _ := cT in T.\nNotation xclass := (class : class_of xT).\nDefinition pack (b0 : Num.NormedZmodule.class_of R T) lm0 um0\n  (m0 : @mixin_of (@Num.NormedZmodule.Pack R (Phant R) T b0) lm0 um0) :=\n  fun bT (b : Num.NormedZmodule.class_of R T)\n      & phant_id (@Num.NormedZmodule.class R (Phant R) bT) b =>\n  fun uT (u : PseudoMetric.class_of R T) & phant_id (@PseudoMetric.class R uT) u =>\n  fun (m : @mixin_of (Num.NormedZmodule.Pack _ b) _ u) & phant_id m m0 =>\n  @Pack phR T (@Class T b u u u u u m).\n\nDefinition eqType := @Equality.Pack cT xclass.\nDefinition choiceType := @Choice.Pack cT xclass.\nDefinition zmodType := @GRing.Zmodule.Pack cT xclass.\nDefinition normedZmodType := @Num.NormedZmodule.Pack R phR cT xclass.\nDefinition pointedType := @Pointed.Pack cT xclass.\nDefinition filteredType := @Filtered.Pack cT cT xclass.\nDefinition topologicalType := @Topological.Pack cT xclass.\nDefinition uniformType := @Uniform.Pack cT xclass.\nDefinition pseudoMetricType := @PseudoMetric.Pack R cT xclass.\nDefinition pointed_zmodType := @GRing.Zmodule.Pack pointedType xclass.\nDefinition filtered_zmodType := @GRing.Zmodule.Pack filteredType xclass.\nDefinition topological_zmodType := @GRing.Zmodule.Pack topologicalType xclass.\nDefinition uniform_zmodType := @GRing.Zmodule.Pack uniformType xclass.\nDefinition pseudoMetric_zmodType := @GRing.Zmodule.Pack pseudoMetricType xclass.\nDefinition pointed_normedZmodType := @Num.NormedZmodule.Pack R phR pointedType xclass.\nDefinition filtered_normedZmodType := @Num.NormedZmodule.Pack R phR filteredType xclass.\nDefinition topological_normedZmodType := @Num.NormedZmodule.Pack R phR topologicalType xclass.\nDefinition uniform_normedZmodType := @Num.NormedZmodule.Pack R phR uniformType xclass.\nDefinition pseudoMetric_normedZmodType := @Num.NormedZmodule.Pack R phR pseudoMetricType xclass.\n\nEnd ClassDef.\n\n(*Definition numDomain_normedDomainType (R : numDomainType) : type (Phant R) :=\n  Pack (Phant R) (@Class R _ _ (NumDomain.normed_mixin (NumDomain.class R))).*)\n\nModule Exports.\nCoercion base : class_of >-> Num.NormedZmodule.class_of.\nCoercion base2 : class_of >-> PseudoMetric.class_of.\nCoercion sort : type >-> Sortclass.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> GRing.Zmodule.type.\nCanonical zmodType.\nCoercion normedZmodType : type >-> Num.NormedZmodule.type.\nCanonical normedZmodType.\nCoercion pointedType : type >-> Pointed.type.\nCanonical pointedType.\nCoercion filteredType : type >-> Filtered.type.\nCanonical filteredType.\nCoercion topologicalType : type >-> Topological.type.\nCanonical topologicalType.\nCoercion uniformType : type >-> Uniform.type.\nCanonical uniformType.\nCoercion pseudoMetricType : type >-> PseudoMetric.type.\nCanonical pseudoMetricType.\nCanonical pointed_zmodType.\nCanonical filtered_zmodType.\nCanonical topological_zmodType.\nCanonical uniform_zmodType.\nCanonical pseudoMetric_zmodType.\nCanonical pointed_normedZmodType.\nCanonical filtered_normedZmodType.\nCanonical topological_normedZmodType.\nCanonical uniform_normedZmodType.\nCanonical pseudoMetric_normedZmodType.\nNotation pseudoMetricNormedZmodType R := (type (Phant R)).\nNotation PseudoMetricNormedZmodType R T m :=\n  (@pack _ (Phant R) T _ _ _ m _ _ idfun _ _ idfun _ idfun).\nNotation \"[ 'pseudoMetricNormedZmodType' R 'of' T 'for' cT ]\" :=\n  (@clone _ (Phant R) T cT _ idfun)\n  (at level 0, format \"[ 'pseudoMetricNormedZmodType'  R  'of'  T  'for'  cT ]\") :\n  form_scope.\nNotation \"[ 'pseudoMetricNormedZmodType' R 'of' T ]\" :=\n  (@clone _ (Phant R) T _ _ idfun)\n  (at level 0, format \"[ 'pseudoMetricNormedZmodType'  R  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd PseudoMetricNormedZmodule.\nExport PseudoMetricNormedZmodule.Exports.\n\nSection pseudoMetricnormedzmodule_lemmas.\nContext {K : numDomainType} {V : pseudoMetricNormedZmodType K}.\n\nLocal Notation ball_norm := (ball_ (@normr K V)).\n\nLemma ball_normE : ball_norm = ball.\nProof. by case: V => ? [? ? ? ? ? ? []]. Qed.\n\nEnd pseudoMetricnormedzmodule_lemmas.\n\n(** neighborhoods *)\n\nSection Nbhs'.\nContext {R : numDomainType} {T : pseudoMetricType R}.\n\nLemma ex_ball_sig (x : T) (P : set T) :\n  ~ (forall eps : {posnum R}, ~ (ball x eps%:num `<=` ~` P)) ->\n    {d : {posnum R} | ball x d%:num `<=` ~` P}.\nProof.\nrewrite forallNE notK => exNP.\npose D := [set d : R^o | d > 0 /\\ ball x d `<=` ~` P].\nhave [|d_gt0] := @getPex _ D; last by exists (PosNum d_gt0).\nby move: exNP => [e eP]; exists e%:num.\nQed.\n\nLemma nbhsC (x : T) (P : set T) :\n  ~ (forall eps : {posnum R}, ~ (ball x eps%:num `<=` ~` P)) ->\n  nbhs x (~` P).\nProof. by move=> /ex_ball_sig [e] ?; apply/nbhs_ballP; exists e%:num => /=. Qed.\n\nLemma nbhsC_ball (x : T) (P : set T) :\n  nbhs x (~` P) -> {d : {posnum R} | ball x d%:num `<=` ~` P}.\nProof.\nmove=> /nbhs_ballP xNP; apply: ex_ball_sig.\nby have [_ /posnumP[e] eP /(_ _ eP)] := xNP.\nQed.\n\nLemma nbhs_ex (x : T) (P : T -> Prop) : nbhs x P ->\n  {d : {posnum R} | forall y, ball x d%:num y -> P y}.\nProof.\nmove=> /nbhs_ballP xP.\npose D := [set d : R^o | d > 0 /\\ forall y, ball x d y -> P y].\nhave [|d_gt0 dP] := @getPex _ D; last by exists (PosNum d_gt0).\nby move: xP => [e bP]; exists (e : R).\nQed.\n\nEnd Nbhs'.\n\nLemma coord_continuous {K : numFieldType} m n i j :\n  continuous (fun M : 'M[K]_(m, n) => M i j).\nProof.\nmove=> /= M s /= /(nbhs_ballP (M i j)) [e e0 es].\napply/nbhs_ballP; exists e => //= N MN; exact/es/MN.\nQed.\n\nGlobal Instance Proper_dnbhs_numFieldType (R : numFieldType) (x : R) :\n  ProperFilter x^'.\nProof.\napply: Build_ProperFilter => A /nbhs_ballP[_/posnumP[e] Ae].\nexists (x + e%:num / 2); apply: Ae; last first.\n  by rewrite eq_sym addrC -subr_eq subrr eq_sym.\nrewrite /ball /= opprD addrA subrr distrC subr0 ger0_norm //.\nby rewrite {2}(splitr e%:num) ltr_spaddl.\nQed.\n\nGlobal Instance Proper_dnbhs_realType (R : realType) (x : R) :\n  ProperFilter x^'.\nProof. exact: Proper_dnbhs_numFieldType. Qed.\n\n(** * Some Topology on extended real numbers *)\n\nDefinition pinfty_nbhs (R : numFieldType) : set (set R) :=\n  fun P => exists M, M \\is Num.real /\\ forall x, M < x -> P x.\nArguments pinfty_nbhs R : clear implicits.\nDefinition ninfty_nbhs (R : numFieldType) : set (set R) :=\n  fun P => exists M, M \\is Num.real /\\ forall x, x < M -> P x.\nArguments ninfty_nbhs R : clear implicits.\n\nNotation \"+oo_ R\" := (pinfty_nbhs [numFieldType of R])\n  (only parsing) : ring_scope.\nNotation \"-oo_ R\" := (ninfty_nbhs [numFieldType of R])\n  (only parsing) : ring_scope.\n\nNotation \"+oo\" := (pinfty_nbhs _) : ring_scope.\nNotation \"-oo\" := (ninfty_nbhs _) : ring_scope.\n\nSection infty_nbhs_instances.\nContext {R : numFieldType}.\nLet R_topologicalType := [topologicalType of R].\nImplicit Types r : R.\n\nGlobal Instance proper_pinfty_nbhs : ProperFilter (pinfty_nbhs R).\nProof.\napply Build_ProperFilter.\n  by move=> P [M [Mreal MP]]; exists (M + 1); apply MP; rewrite ltr_addl.\nsplit=> /= [|P Q [MP [MPr gtMP]] [MQ [MQr gtMQ]] |P Q sPQ [M [Mr gtM]]].\n- by exists 0.\n- exists (maxr MP MQ); split=> [|x]; first exact: max_real.\n  by rewrite comparable_lt_maxl ?real_comparable // => /andP[/gtMP ? /gtMQ].\n- by exists M; split => // ? /gtM /sPQ.\nQed.\n\nGlobal Instance proper_ninfty_nbhs : ProperFilter (ninfty_nbhs R).\nProof.\napply Build_ProperFilter.\n  move=> P [M [Mr ltMP]]; exists (M - 1).\n  by apply: ltMP; rewrite gtr_addl oppr_lt0.\nsplit=> /= [|P Q [MP [MPr ltMP]] [MQ [MQr ltMQ]] |P Q sPQ [M [Mr ltM]]].\n- by exists 0.\n- exists (Num.min MP MQ); split=> [|x]; first exact: min_real.\n  by rewrite comparable_lt_minr ?real_comparable // => /andP[/ltMP ? /ltMQ].\n- by exists M; split => // x /ltM /sPQ.\nQed.\n\nLemma nbhs_pinfty_gt r : r \\is Num.real -> \\forall x \\near +oo, r < x.\nProof. by exists r. Qed.\n\nLemma nbhs_pinfty_ge r : r \\is Num.real -> \\forall x \\near +oo, r <= x.\nProof. by exists r; split => //; apply: ltW. Qed.\n\nLemma nbhs_ninfty_lt r : r \\is Num.real -> \\forall x \\near -oo, r > x.\nProof. by exists r. Qed.\n\nLemma nbhs_ninfty_le r : r \\is Num.real -> \\forall x \\near -oo, r >= x.\nProof. by exists r; split => // ?; apply: ltW. Qed.\n\nLemma nbhs_pinfty_real : \\forall x \\near +oo, x \\is @Num.real R.\nProof. by apply: filterS (nbhs_pinfty_gt (@real0 _)); apply: gtr0_real. Qed.\n\nLemma nbhs_ninfty_real : \\forall x \\near -oo, x \\is @Num.real R.\nProof. by apply: filterS (nbhs_ninfty_lt (@real0 _)); apply: ltr0_real. Qed.\n\nLemma pinfty_ex_gt (m : R) (A : set R) : m \\is Num.real ->\n  (\\forall k \\near +oo, A k) -> exists2 M, m < M & A M.\nProof.\nmove=> m_real Agt; near (pinfty_nbhs R) => M.\nby exists M; near: M => //; apply: nbhs_pinfty_gt.\nUnshelve. all: by end_near. Qed.\n\nLemma pinfty_ex_ge (m : R) (A : set R) : m \\is Num.real ->\n  (\\forall k \\near +oo, A k) -> exists2 M, m <= M & A M.\nProof.\nmove=> m_real Agt; near (pinfty_nbhs R) => M.\nby exists M; near: M => //; apply: nbhs_pinfty_ge.\nUnshelve. all: by end_near. Qed.\n\nLemma pinfty_ex_gt0 (A : set R) :\n  (\\forall k \\near +oo, A k) -> exists2 M, M > 0 & A M.\nProof. exact: pinfty_ex_gt. Qed.\n\nLemma near_pinfty_div2 (A : set R) :\n  (\\forall k \\near +oo, A k) -> (\\forall k \\near +oo, A (k / 2)).\nProof.\nmove=> [M [Mreal AM]]; exists (M * 2); split; first by rewrite realM.\nby move=> x; rewrite -ltr_pdivl_mulr //; exact: AM.\nQed.\n\nEnd infty_nbhs_instances.\n\n#[global] Hint Extern 0 (is_true (_ < ?x)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_pinfty_gt end : core.\n#[global] Hint Extern 0 (is_true (_ <= ?x)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_pinfty_ge end : core.\n#[global] Hint Extern 0 (is_true (_ > ?x)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_ninfty_lt end : core.\n#[global] Hint Extern 0 (is_true (_ >= ?x)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_ninfty_le end : core.\n#[global] Hint Extern 0 (is_true (?x \\is Num.real)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_pinfty_real end : core.\n#[global] Hint Extern 0 (is_true (?x \\is Num.real)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_ninfty_real end : core.\n\n#[global] Hint Extern 0 (is_true (_ < ?x)%E) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: ereal_nbhs_pinfty_gt end : core.\n#[global] Hint Extern 0 (is_true (_ <= ?x)%E) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: ereal_nbhs_pinfty_ge end : core.\n#[global] Hint Extern 0 (is_true (_ > ?x)%E) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: ereal_nbhs_ninfty_lt end : core.\n#[global] Hint Extern 0 (is_true (_ >= ?x)%E) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: ereal_nbhs_ninfty_le end : core.\n#[global] Hint Extern 0 (is_true (fine ?x \\is Num.real)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: ereal_nbhs_pinfty_real end : core.\n#[global] Hint Extern 0 (is_true (fine ?x \\is Num.real)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: ereal_nbhs_ninfty_real end : core.\n\nSection cvg_infty_numField.\nContext {R : numFieldType}.\n\nLet cvgryPnum {F : set (set R)} {FF : Filter F} : [<->\n(* 0 *) F --> +oo;\n(* 1 *) forall A, A \\is Num.real -> \\forall x \\near F, A <= x;\n(* 2 *) forall A, A \\is Num.real -> \\forall x \\near F, A < x;\n(* 3 *) \\forall A \\near +oo, \\forall x \\near F, A < x;\n(* 4 *) \\forall A \\near +oo, \\forall x \\near F, A <= x ].\nProof.\ntfae; first by move=> Foo A Areal; apply: Foo; apply: nbhs_pinfty_ge.\n- move=> AF A Areal; near +oo_R => B.\n  by near do apply: (@lt_le_trans _ _ B) => //=; apply: AF.\n- by move=> Foo; near do apply: Foo => //.\n- by apply: filterS => ?; apply: filterS => ?; apply: ltW.\ncase=> [A [AR AF]] P [x [xR Px]]; near +oo_R => B.\nby near do [apply: Px; apply: (@lt_le_trans _ _ B) => //]; apply: AF.\nUnshelve. all: by end_near. Qed.\n\nLet cvgrNyPnum {F : set (set R)} {FF : Filter F} : [<->\n(* 0 *) F --> -oo;\n(* 1 *) forall A, A \\is Num.real -> \\forall x \\near F, A >= x;\n(* 2 *) forall A, A \\is Num.real -> \\forall x \\near F, A > x;\n(* 3 *) \\forall A \\near -oo, \\forall x \\near F, A > x;\n(* 4 *) \\forall A \\near -oo, \\forall x \\near F, A >= x ].\nProof.\ntfae; first by move=> Foo A Areal; apply: Foo; apply: nbhs_ninfty_le.\n- move=> AF A Areal; near -oo_R => B.\n  by near do apply: (@le_lt_trans _ _ B) => //; apply: AF.\n- by move=> Foo; near do apply: Foo => //.\n- by apply: filterS => ?; apply: filterS => ?; apply: ltW.\ncase=> [A [AR AF]] P [x [xR Px]]; near -oo_R => B.\nby near do [apply: Px; apply: (@le_lt_trans _ _ B) => //]; apply: AF.\nUnshelve. all: end_near. Qed.\n\nContext {T} {F : set (set T)} {FF : Filter F}.\nImplicit Types f : T -> R.\n\nLemma cvgryPger f :\n  f @ F --> +oo <-> forall A, A \\is Num.real -> \\forall x \\near F, A <= f x.\nProof. exact: (cvgryPnum 0%N 1%N). Qed.\n\nLemma cvgryPgtr f :\n  f @ F --> +oo <-> forall A, A \\is Num.real -> \\forall x \\near F, A < f x.\nProof. exact: (cvgryPnum 0%N 2%N). Qed.\n\nLemma cvgryPgty f :\n  f @ F --> +oo <-> \\forall A \\near +oo, \\forall x \\near F, A < f x.\nProof. exact: (cvgryPnum 0%N 3%N). Qed.\n\nLemma cvgryPgey f :\n  f @ F --> +oo <-> \\forall A \\near +oo, \\forall x \\near F, A <= f x.\nProof. exact: (cvgryPnum 0%N 4%N). Qed.\n\nLemma cvgrNyPler f :\n  f @ F --> -oo <-> forall A, A \\is Num.real -> \\forall x \\near F, A >= f x.\nProof. exact: (cvgrNyPnum 0%N 1%N). Qed.\n\nLemma cvgrNyPltr f :\n  f @ F --> -oo <-> forall A, A \\is Num.real -> \\forall x \\near F, A > f x.\nProof. exact: (cvgrNyPnum 0%N 2%N). Qed.\n\nLemma cvgrNyPltNy f :\n  f @ F --> -oo <-> \\forall A \\near -oo, \\forall x \\near F, A > f x.\nProof. exact: (cvgrNyPnum 0%N 3%N). Qed.\n\nLemma cvgrNyPleNy f :\n  f @ F --> -oo <-> \\forall A \\near -oo, \\forall x \\near F, A >= f x.\nProof. exact: (cvgrNyPnum 0%N 4%N). Qed.\n\nLemma cvgry_ger f :\n  f @ F --> +oo -> forall A, A \\is Num.real -> \\forall x \\near F, A <= f x.\nProof. by rewrite cvgryPger. Qed.\n\nLemma cvgry_gtr f :\n  f @ F --> +oo -> forall A, A \\is Num.real -> \\forall x \\near F, A < f x.\nProof. by rewrite cvgryPgtr. Qed.\n\nLemma cvgrNy_ler f :\n  f @ F --> -oo -> forall A, A \\is Num.real -> \\forall x \\near F, A >= f x.\nProof. by rewrite cvgrNyPler. Qed.\n\nLemma cvgrNy_ltr f :\n  f @ F --> -oo -> forall A, A \\is Num.real -> \\forall x \\near F, A > f x.\nProof. by rewrite cvgrNyPltr. Qed.\n\nLemma cvgNry f : (- f @ F --> +oo) <-> (f @ F --> -oo).\nProof.\nrewrite cvgrNyPler cvgryPger; split=> Foo A Areal;\nby near do rewrite -ler_opp2 ?opprK; apply: Foo; rewrite rpredN.\nUnshelve. all: end_near. Qed.\n\nLemma cvgNrNy f : (- f @ F --> -oo) <-> (f @ F --> +oo).\nProof. by rewrite -cvgNry opprK. Qed.\n\nEnd cvg_infty_numField.\n\nSection cvg_infty_realField.\nContext {R : realFieldType}.\nContext {T} {F : set (set T)} {FF : Filter F} (f : T -> R).\n\nLemma cvgryPge : f @ F --> +oo <-> forall A, \\forall x \\near F, A <= f x.\nProof.\nby rewrite cvgryPger; under eq_forall do rewrite num_real; split=> + *; apply.\nQed.\n\nLemma cvgryPgt : f @ F --> +oo <-> forall A, \\forall x \\near F, A < f x.\nProof.\nby rewrite cvgryPgtr; under eq_forall do rewrite num_real; split=> + *; apply.\nQed.\n\nLemma cvgrNyPle : f @ F --> -oo <-> forall A, \\forall x \\near F, A >= f x.\nProof.\nby rewrite cvgrNyPler; under eq_forall do rewrite num_real; split=> + *; apply.\nQed.\n\nLemma cvgrNyPlt : f @ F --> -oo <-> forall A, \\forall x \\near F, A > f x.\nProof.\nby rewrite cvgrNyPltr; under eq_forall do rewrite num_real; split=> + *; apply.\nQed.\n\nLemma cvgry_ge : f @ F --> +oo -> forall A, \\forall x \\near F, A <= f x.\nProof. by rewrite cvgryPge. Qed.\n\nLemma cvgry_gt : f @ F --> +oo -> forall A, \\forall x \\near F, A < f x.\nProof. by rewrite cvgryPgt. Qed.\n\nLemma cvgrNy_le : f @ F --> -oo -> forall A, \\forall x \\near F, A >= f x.\nProof. by rewrite cvgrNyPle. Qed.\n\nLemma cvgrNy_lt : f @ F --> -oo -> forall A, \\forall x \\near F, A > f x.\nProof. by rewrite cvgrNyPlt. Qed.\n\nEnd cvg_infty_realField.\n\nLemma cvgrnyP {R : realType} {T} {F : set (set T)} {FF : Filter F} (f : T -> nat) :\n   (((f n)%:R : R) @[n --> F] --> +oo) <-> (f @ F --> \\oo).\nProof.\nsplit=> [/cvgryPge|/cvgnyPge] Foo.\n  by apply/cvgnyPge => A; near do rewrite -(@ler_nat R); apply: Foo.\napply/cvgryPgey; near=> A; near=> n.\nrewrite (le_trans (@ceil_ge R A))// (ler_int _ _ (f n)) [ceil _]intEsign.\nby rewrite le_gtF ?expr0 ?mul1r ?lez_nat ?ceil_ge0//; near: n; apply: Foo.\nUnshelve. all: by end_near. Qed.\n\nSection ecvg_infty_numField.\nLocal Open Scope ereal_scope.\n\nContext {R : numFieldType}.\n\nLet cvgeyPnum {F : set (set \\bar R)} {FF : Filter F} : [<->\n(* 0 *) F --> +oo;\n(* 1 *) forall A, A \\is Num.real -> \\forall x \\near F, A%:E <= x;\n(* 2 *) forall A, A \\is Num.real -> \\forall x \\near F, A%:E < x;\n(* 3 *) \\forall A \\near +oo%R, \\forall x \\near F, A%:E < x;\n(* 4 *) \\forall A \\near +oo%R, \\forall x \\near F, A%:E <= x ].\nProof.\ntfae; first by move=> Foo A Areal; apply: Foo; apply: ereal_nbhs_pinfty_ge.\n- move=> AF A Areal; near +oo_R => B.\n  by near do rewrite (@lt_le_trans _ _ B%:E) ?lte_fin//; apply: AF.\n- by move=> Foo; near do apply: Foo => //.\n- by apply: filterS => ?; apply: filterS => ?; apply: ltW.\ncase=> [A [AR AF]] P [x [xR Px]]; near +oo_R => B.\nby near do [apply: Px; rewrite (@lt_le_trans _ _ B%:E) ?lte_fin//]; apply: AF.\nUnshelve. all: end_near. Qed.\n\nLet cvgeNyPnum {F : set (set \\bar R)} {FF : Filter F} : [<->\n(* 0 *) F --> -oo;\n(* 1 *) forall A, A \\is Num.real -> \\forall x \\near F, A%:E >= x;\n(* 2 *) forall A, A \\is Num.real -> \\forall x \\near F, A%:E > x;\n(* 3 *) \\forall A \\near -oo%R, \\forall x \\near F, A%:E > x;\n(* 4 *) \\forall A \\near -oo%R, \\forall x \\near F, A%:E >= x ].\nProof.\ntfae; first by move=> Foo A Areal; apply: Foo; apply: ereal_nbhs_ninfty_le.\n- move=> AF A Areal; near -oo_R => B.\n  by near do rewrite (@le_lt_trans _ _ B%:E) ?lte_fin//; apply: AF.\n- by move=> Foo; near do apply: Foo => //.\n- by apply: filterS => ?; apply: filterS => ?; apply: ltW.\ncase=> [A [AR AF]] P [x [xR Px]]; near -oo_R => B.\nby near do [apply: Px; rewrite (@le_lt_trans _ _ B%:E) ?lte_fin//]; apply: AF.\nUnshelve. all: end_near. Qed.\n\nContext {T} {F : set (set T)} {FF : Filter F}.\nImplicit Types (f : T -> \\bar R) (u : T -> R).\n\nLemma cvgeyPger f :\n  f @ F --> +oo <-> forall A, A \\is Num.real -> \\forall x \\near F, A%:E <= f x.\nProof. exact: (cvgeyPnum 0%N 1%N). Qed.\n\nLemma cvgeyPgtr f :\n  f @ F --> +oo <-> forall A, A \\is Num.real -> \\forall x \\near F, A%:E < f x.\nProof. exact: (cvgeyPnum 0%N 2%N). Qed.\n\nLemma cvgeyPgty f :\n  f @ F --> +oo <-> \\forall A \\near +oo%R, \\forall x \\near F, A%:E < f x.\nProof. exact: (cvgeyPnum 0%N 3%N). Qed.\n\nLemma cvgeyPgey f :\n  f @ F --> +oo <-> \\forall A \\near +oo%R, \\forall x \\near F, A%:E <= f x.\nProof. exact: (cvgeyPnum 0%N 4%N). Qed.\n\nLemma cvgeNyPler f :\n  f @ F --> -oo <-> forall A, A \\is Num.real -> \\forall x \\near F, A%:E >= f x.\nProof. exact: (cvgeNyPnum 0%N 1%N). Qed.\n\nLemma cvgeNyPltr f :\n  f @ F --> -oo <-> forall A, A \\is Num.real -> \\forall x \\near F, A%:E > f x.\nProof. exact: (cvgeNyPnum 0%N 2%N). Qed.\n\nLemma cvgeNyPltNy f :\n  f @ F --> -oo <-> \\forall A \\near -oo%R, \\forall x \\near F, A%:E > f x.\nProof. exact: (cvgeNyPnum 0%N 3%N). Qed.\n\nLemma cvgeNyPleNy f :\n  f @ F --> -oo <-> \\forall A \\near -oo%R, \\forall x \\near F, A%:E >= f x.\nProof. exact: (cvgeNyPnum 0%N 4%N). Qed.\n\nLemma cvgey_ger f :\n  f @ F --> +oo -> forall A, A \\is Num.real -> \\forall x \\near F, A%:E <= f x.\nProof. by rewrite cvgeyPger. Qed.\n\nLemma cvgey_gtr f :\n  f @ F --> +oo -> forall A, A \\is Num.real -> \\forall x \\near F, A%:E < f x.\nProof. by rewrite cvgeyPgtr. Qed.\n\nLemma cvgeNy_ler f :\n  f @ F --> -oo -> forall A, A \\is Num.real -> \\forall x \\near F, A%:E >= f x.\nProof. by rewrite cvgeNyPler. Qed.\n\nLemma cvgeNy_ltr f :\n  f @ F --> -oo -> forall A, A \\is Num.real -> \\forall x \\near F, A%:E > f x.\nProof. by rewrite cvgeNyPltr. Qed.\n\nLemma cvgNey f : (\\- f @ F --> +oo) <-> (f @ F --> -oo).\nProof.\nrewrite cvgeNyPler cvgeyPger; split=> Foo A Areal;\nby near do rewrite -lee_opp2 ?oppeK; apply: Foo; rewrite rpredN.\nUnshelve. all: end_near. Qed.\n\nLemma cvgNeNy f : (\\- f @ F --> -oo) <-> (f @ F --> +oo).\nProof.\nby rewrite -cvgNey (_ : \\- \\- f = f)//; apply/funeqP => x /=; rewrite oppeK.\nQed.\n\nLemma cvgeryP u : ((u x)%:E @[x --> F] --> +oo) <-> (u @ F --> +oo%R).\nProof.\nsplit=> [/cvgeyPger|/cvgryPger] Foo.\n  by apply/cvgryPger => A Ar; near do rewrite -lee_fin; apply: Foo.\nby apply/cvgeyPger => A Ar; near do rewrite lee_fin; apply: Foo.\nUnshelve. all: end_near. Qed.\n\nLemma cvgerNyP u : ((u x)%:E @[x --> F] --> -oo) <-> (u @ F --> -oo%R).\nProof.\nsplit=> [/cvgeNyPler|/cvgrNyPler] Foo.\n  by apply/cvgrNyPler => A Ar; near do rewrite -lee_fin; apply: Foo.\nby apply/cvgeNyPler => A Ar; near do rewrite lee_fin; apply: Foo.\nUnshelve. all: end_near. Qed.\n\nEnd ecvg_infty_numField.\n\nSection ecvg_infty_realField.\nLocal Open Scope ereal_scope.\nContext {R : realFieldType}.\nContext {T} {F : set (set T)} {FF : Filter F} (f : T -> \\bar R).\n\nLemma cvgeyPge : f @ F --> +oo <-> forall A, \\forall x \\near F, A%:E <= f x.\nProof.\nby rewrite cvgeyPger; under eq_forall do rewrite num_real; split=> + *; apply.\nQed.\n\nLemma cvgeyPgt : f @ F --> +oo <-> forall A, \\forall x \\near F, A%:E < f x.\nProof.\nby rewrite cvgeyPgtr; under eq_forall do rewrite num_real; split=> + *; apply.\nQed.\n\nLemma cvgeNyPle : f @ F --> -oo <-> forall A, \\forall x \\near F, A%:E >= f x.\nProof.\nby rewrite cvgeNyPler; under eq_forall do rewrite num_real; split=> + *; apply.\nQed.\n\nLemma cvgeNyPlt : f @ F --> -oo <-> forall A, \\forall x \\near F, A%:E > f x.\nProof.\nby rewrite cvgeNyPltr; under eq_forall do rewrite num_real; split=> + *; apply.\nQed.\n\nLemma cvgey_ge : f @ F --> +oo -> forall A, \\forall x \\near F, A%:E <= f x.\nProof. by rewrite cvgeyPge. Qed.\n\nLemma cvgey_gt : f @ F --> +oo -> forall A, \\forall x \\near F, A%:E < f x.\nProof. by rewrite cvgeyPgt. Qed.\n\nLemma cvgeNy_le : f @ F --> -oo -> forall A, \\forall x \\near F, A%:E >= f x.\nProof. by rewrite cvgeNyPle. Qed.\n\nLemma cvgeNy_lt : f @ F --> -oo -> forall A, \\forall x \\near F, A%:E > f x.\nProof. by rewrite cvgeNyPlt. Qed.\n\nEnd ecvg_infty_realField.\n\nLemma cvgenyP {R : realType} {T} {F : set (set T)} {FF : Filter F} (f : T -> nat) :\n   (((f n)%:R : R)%:E @[n --> F] --> +oo%E) <-> (f @ F --> \\oo).\nProof. by rewrite cvgeryP cvgrnyP. Qed.\n\n(** ** Modules with a norm *)\n\nModule NormedModule.\n\nRecord mixin_of (K : numDomainType)\n  (V : pseudoMetricNormedZmodType K) (scale : K -> V -> V) := Mixin {\n  _ : forall (l : K) (x : V), `| scale l x | = `| l | * `| x |;\n}.\n\nSection ClassDef.\n\nVariable K : numDomainType.\n\nRecord class_of (T : Type) := Class {\n  base : PseudoMetricNormedZmodule.class_of K T ;\n  lmodmixin : GRing.Lmodule.mixin_of K (GRing.Zmodule.Pack base) ;\n  mixin : @mixin_of K (PseudoMetricNormedZmodule.Pack (Phant K) base)\n                      (GRing.Lmodule.scale lmodmixin)\n}.\nLocal Coercion base : class_of >-> PseudoMetricNormedZmodule.class_of.\nLocal Coercion base2 T (c : class_of T) : GRing.Lmodule.class_of K T :=\n  @GRing.Lmodule.Class K T (base c) (lmodmixin c).\nLocal Coercion mixin : class_of >-> mixin_of.\n\nStructure type (phK : phant K) :=\n  Pack { sort; _ : class_of sort }.\nLocal Coercion sort : type >-> Sortclass.\n\nVariables (phK : phant K) (T : Type) (cT : type phK).\n\nDefinition class := let: Pack _ c := cT return class_of cT in c.\nDefinition clone c of phant_id class c := @Pack phK T c.\nLet xT := let: Pack T _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack b0 l0\n                (m0 : @mixin_of K (@PseudoMetricNormedZmodule.Pack K (Phant K) T b0)\n                                (GRing.Lmodule.scale l0)) :=\n  fun bT b & phant_id (@PseudoMetricNormedZmodule.class K (Phant K) bT) b =>\n  fun l & phant_id l0 l =>\n  fun m & phant_id m0 m => Pack phK (@Class T b l m).\n\nDefinition eqType := @Equality.Pack cT xclass.\nDefinition choiceType := @Choice.Pack cT xclass.\nDefinition zmodType := @GRing.Zmodule.Pack cT xclass.\nDefinition normedZmodType := @Num.NormedZmodule.Pack K phK cT xclass.\nDefinition lmodType := @GRing.Lmodule.Pack K phK cT xclass.\nDefinition pointedType := @Pointed.Pack cT xclass.\nDefinition filteredType := @Filtered.Pack cT cT xclass.\nDefinition topologicalType := @Topological.Pack cT xclass.\nDefinition uniformType := @Uniform.Pack cT xclass.\nDefinition pseudoMetricType := @PseudoMetric.Pack K cT xclass.\nDefinition pseudoMetricNormedZmodType := @PseudoMetricNormedZmodule.Pack K phK cT xclass.\nDefinition pointed_lmodType := @GRing.Lmodule.Pack K phK pointedType xclass.\nDefinition filtered_lmodType := @GRing.Lmodule.Pack K phK filteredType xclass.\nDefinition topological_lmodType := @GRing.Lmodule.Pack K phK topologicalType xclass.\nDefinition uniform_lmodType := @GRing.Lmodule.Pack K phK uniformType xclass.\nDefinition pseudoMetric_lmodType := @GRing.Lmodule.Pack K phK pseudoMetricType xclass.\nDefinition normedZmod_lmodType := @GRing.Lmodule.Pack K phK normedZmodType xclass.\nDefinition pseudoMetricNormedZmod_lmodType := @GRing.Lmodule.Pack K phK pseudoMetricNormedZmodType xclass.\nEnd ClassDef.\n\nModule Exports.\n\nCoercion base : class_of >-> PseudoMetricNormedZmodule.class_of.\nCoercion base2 : class_of >-> GRing.Lmodule.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> GRing.Zmodule.type.\nCanonical zmodType.\nCoercion normedZmodType : type >-> Num.NormedZmodule.type.\nCanonical normedZmodType.\nCoercion lmodType : type >-> GRing.Lmodule.type.\nCanonical lmodType.\nCoercion pointedType : type >-> Pointed.type.\nCanonical pointedType.\nCoercion filteredType : type >-> Filtered.type.\nCanonical filteredType.\nCoercion topologicalType : type >-> Topological.type.\nCanonical topologicalType.\nCoercion uniformType : type >-> Uniform.type.\nCanonical uniformType.\nCoercion pseudoMetricType : type >-> PseudoMetric.type.\nCanonical pseudoMetricType.\nCoercion pseudoMetricNormedZmodType : type >-> PseudoMetricNormedZmodule.type.\nCanonical pseudoMetricNormedZmodType.\nCanonical pointed_lmodType.\nCanonical filtered_lmodType.\nCanonical topological_lmodType.\nCanonical uniform_lmodType.\nCanonical pseudoMetric_lmodType.\nCanonical normedZmod_lmodType.\nCanonical pseudoMetricNormedZmod_lmodType.\nNotation normedModType K := (type (Phant K)).\nNotation NormedModType K T m := (@pack _ (Phant K) T _ _ m _ _ idfun _ idfun _ idfun).\nNotation NormedModMixin := Mixin.\nNotation \"[ 'normedModType' K 'of' T 'for' cT ]\" := (@clone _ (Phant K) T cT _ idfun)\n  (at level 0, format \"[ 'normedModType'  K  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'normedModType' K 'of' T ]\" := (@clone _ (Phant K) T _ _ id)\n  (at level 0, format \"[ 'normedModType'  K  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd NormedModule.\n\nExport NormedModule.Exports.\n\nModule regular_topology.\n\nSection regular_topology.\nLocal Canonical pseudoMetricNormedZmodType (R : numFieldType) :=\n  @PseudoMetricNormedZmodType\n    R R^o\n    (PseudoMetricNormedZmodule.Mixin (erefl : @ball _ R = ball_ Num.norm)).\nLocal Canonical normedModType (R : numFieldType) :=\n  NormedModType R R^o (@NormedModMixin _ _ ( *:%R : R -> R^o -> _) (@normrM _)).\nEnd regular_topology.\n\nModule Exports.\nCanonical pseudoMetricNormedZmodType.\nCanonical normedModType.\nEnd Exports.\n\nEnd regular_topology.\nExport regular_topology.Exports.\n\nModule numFieldNormedType.\n\nSection realType.\nVariable (R : realType).\nLocal Canonical real_lmodType := [lmodType R of R for [lmodType R of R^o]].\nLocal Canonical real_lalgType := [lalgType R of R for [lalgType R of R^o]].\nLocal Canonical real_algType := [algType R of R for [algType R of R^o]].\nLocal Canonical real_comAlgType := [comAlgType R of R].\nLocal Canonical real_unitAlgType := [unitAlgType R of R].\nLocal Canonical real_comUnitAlgType := [comUnitAlgType R of R].\nLocal Canonical real_vectType := [vectType R of R for [vectType R of R^o]].\nLocal Canonical real_FalgType := [FalgType R of R].\nLocal Canonical real_fieldExtType :=\n  [fieldExtType R of R for [fieldExtType R of R^o]].\nLocal Canonical real_pseudoMetricNormedZmodType :=\n  [pseudoMetricNormedZmodType R of R for [pseudoMetricNormedZmodType R of R^o]].\nLocal Canonical real_normedModType :=\n  [normedModType R of R for [normedModType R of R^o]].\nEnd realType.\n\nSection rcfType.\nVariable (R : rcfType).\nLocal Canonical rcf_lmodType := [lmodType R of R for [lmodType R of R^o]].\nLocal Canonical rcf_lalgType := [lalgType R of R for [lalgType R of R^o]].\nLocal Canonical rcf_algType := [algType R of R for [algType R of R^o]].\nLocal Canonical rcf_comAlgType := [comAlgType R of R].\nLocal Canonical rcf_unitAlgType := [unitAlgType R of R].\nLocal Canonical rcf_comUnitAlgType := [comUnitAlgType R of R].\nLocal Canonical rcf_vectType := [vectType R of R for [vectType R of R^o]].\nLocal Canonical rcf_FalgType := [FalgType R of R].\nLocal Canonical rcf_fieldExtType :=\n  [fieldExtType R of R for [fieldExtType R of R^o]].\nLocal Canonical rcf_pseudoMetricNormedZmodType :=\n  [pseudoMetricNormedZmodType R of R for [pseudoMetricNormedZmodType R of R^o]].\nLocal Canonical rcf_normedModType :=\n  [normedModType R of R for [normedModType R of R^o]].\nEnd rcfType.\n\nSection archiFieldType.\nVariable (R : archiFieldType).\nLocal Canonical archiField_lmodType :=\n  [lmodType R of R for [lmodType R of R^o]].\nLocal Canonical archiField_lalgType :=\n  [lalgType R of R for [lalgType R of R^o]].\nLocal Canonical archiField_algType := [algType R of R for [algType R of R^o]].\nLocal Canonical archiField_comAlgType := [comAlgType R of R].\nLocal Canonical archiField_unitAlgType := [unitAlgType R of R].\nLocal Canonical archiField_comUnitAlgType := [comUnitAlgType R of R].\nLocal Canonical archiField_vectType :=\n  [vectType R of R for [vectType R of R^o]].\nLocal Canonical archiField_FalgType := [FalgType R of R].\nLocal Canonical archiField_fieldExtType :=\n  [fieldExtType R of R for [fieldExtType R of R^o]].\nLocal Canonical archiField_pseudoMetricNormedZmodType :=\n  [pseudoMetricNormedZmodType R of R for [pseudoMetricNormedZmodType R of R^o]].\nLocal Canonical archiField_normedModType :=\n  [normedModType R of R for [normedModType R of R^o]].\nEnd archiFieldType.\n\nSection realFieldType.\nVariable (R : realFieldType).\nLocal Canonical realField_lmodType := [lmodType R of R for [lmodType R of R^o]].\nLocal Canonical realField_lalgType := [lalgType R of R for [lalgType R of R^o]].\nLocal Canonical realField_algType := [algType R of R for [algType R of R^o]].\nLocal Canonical realField_comAlgType := [comAlgType R of R].\nLocal Canonical realField_unitAlgType := [unitAlgType R of R].\nLocal Canonical realField_comUnitAlgType := [comUnitAlgType R of R].\nLocal Canonical realField_vectType := [vectType R of R for [vectType R of R^o]].\nLocal Canonical realField_FalgType := [FalgType R of R].\nLocal Canonical realField_fieldExtType :=\n  [fieldExtType R of R for [fieldExtType R of R^o]].\nLocal Canonical realField_pseudoMetricNormedZmodType :=\n  [pseudoMetricNormedZmodType R of R for [pseudoMetricNormedZmodType R of R^o]].\nLocal Canonical realField_normedModType :=\n  [normedModType R of R for [normedModType R of R^o]].\nDefinition lmod_latticeType := [latticeType of realField_lmodType].\nDefinition lmod_distrLatticeType := [distrLatticeType of realField_lmodType].\nDefinition lmod_orderType := [orderType of realField_lmodType].\nDefinition lmod_realDomainType := [realDomainType of realField_lmodType].\nDefinition lalg_latticeType := [latticeType of realField_lalgType].\nDefinition lalg_distrLatticeType := [distrLatticeType of realField_lalgType].\nDefinition lalg_orderType := [orderType of realField_lalgType].\nDefinition lalg_realDomainType := [realDomainType of realField_lalgType].\nDefinition alg_latticeType := [latticeType of realField_algType].\nDefinition alg_distrLatticeType := [distrLatticeType of realField_algType].\nDefinition alg_orderType := [orderType of realField_algType].\nDefinition alg_realDomainType := [realDomainType of realField_algType].\nDefinition comAlg_latticeType := [latticeType of realField_comAlgType].\nDefinition comAlg_distrLatticeType :=\n  [distrLatticeType of realField_comAlgType].\nDefinition comAlg_orderType := [orderType of realField_comAlgType].\nDefinition comAlg_realDomainType := [realDomainType of realField_comAlgType].\nDefinition unitAlg_latticeType := [latticeType of realField_unitAlgType].\nDefinition unitAlg_distrLatticeType :=\n  [distrLatticeType of realField_unitAlgType].\nDefinition unitAlg_orderType := [orderType of realField_unitAlgType].\nDefinition unitAlg_realDomainType := [realDomainType of realField_unitAlgType].\nDefinition comUnitAlg_latticeType := [latticeType of realField_comUnitAlgType].\nDefinition comUnitAlg_distrLatticeType :=\n  [distrLatticeType of realField_comUnitAlgType].\nDefinition comUnitAlg_orderType := [orderType of realField_comUnitAlgType].\nDefinition comUnitAlg_realDomainType :=\n  [realDomainType of realField_comUnitAlgType].\nDefinition vect_latticeType := [latticeType of realField_vectType].\nDefinition vect_distrLatticeType := [distrLatticeType of realField_vectType].\nDefinition vect_orderType := [orderType of realField_vectType].\nDefinition vect_realDomainType := [realDomainType of realField_vectType].\nDefinition Falg_latticeType := [latticeType of realField_FalgType].\nDefinition Falg_distrLatticeType := [distrLatticeType of realField_FalgType].\nDefinition Falg_orderType := [orderType of realField_FalgType].\nDefinition Falg_realDomainType := [realDomainType of realField_FalgType].\nDefinition fieldExt_latticeType := [latticeType of realField_fieldExtType].\nDefinition fieldExt_distrLatticeType :=\n  [distrLatticeType of realField_fieldExtType].\nDefinition fieldExt_orderType := [orderType of realField_fieldExtType].\nDefinition fieldExt_realDomainType :=\n  [realDomainType of realField_fieldExtType].\nDefinition pseudoMetricNormedZmod_latticeType :=\n  [latticeType of realField_pseudoMetricNormedZmodType].\nDefinition pseudoMetricNormedZmod_distrLatticeType :=\n  [distrLatticeType of realField_pseudoMetricNormedZmodType].\nDefinition pseudoMetricNormedZmod_orderType :=\n  [orderType of realField_pseudoMetricNormedZmodType].\nDefinition pseudoMetricNormedZmod_realDomainType :=\n  [realDomainType of realField_pseudoMetricNormedZmodType].\nDefinition normedMod_latticeType := [latticeType of realField_normedModType].\nDefinition normedMod_distrLatticeType :=\n  [distrLatticeType of realField_normedModType].\nDefinition normedMod_orderType := [orderType of realField_normedModType].\nDefinition normedMod_realDomainType :=\n  [realDomainType of realField_normedModType].\nEnd realFieldType.\n\nSection numClosedFieldType.\nVariable (R : numClosedFieldType).\nLocal Canonical numClosedField_lmodType :=\n  [lmodType R of R for [lmodType R of R^o]].\nLocal Canonical numClosedField_lalgType :=\n  [lalgType R of R for [lalgType R of R^o]].\nLocal Canonical numClosedField_algType :=\n  [algType R of R for [algType R of R^o]].\nLocal Canonical numClosedField_comAlgType := [comAlgType R of R].\nLocal Canonical numClosedField_unitAlgType := [unitAlgType R of R].\nLocal Canonical numClosedField_comUnitAlgType := [comUnitAlgType R of R].\nLocal Canonical numClosedField_vectType :=\n  [vectType R of R for [vectType R of R^o]].\nLocal Canonical numClosedField_FalgType := [FalgType R of R].\nLocal Canonical numClosedField_fieldExtType :=\n  [fieldExtType R of R for [fieldExtType R of R^o]].\nLocal Canonical numClosedField_pseudoMetricNormedZmodType :=\n  [pseudoMetricNormedZmodType R of R for [pseudoMetricNormedZmodType R of R^o]].\nLocal Canonical numClosedField_normedModType :=\n  [normedModType R of R for [normedModType R of R^o]].\nDefinition lmod_decFieldType := [decFieldType of numClosedField_lmodType].\nDefinition lmod_closedFieldType := [closedFieldType of numClosedField_lmodType].\nDefinition lalg_decFieldType := [decFieldType of numClosedField_lalgType].\nDefinition lalg_closedFieldType := [closedFieldType of numClosedField_lalgType].\nDefinition alg_decFieldType := [decFieldType of numClosedField_algType].\nDefinition alg_closedFieldType := [closedFieldType of numClosedField_algType].\nDefinition comAlg_decFieldType := [decFieldType of numClosedField_comAlgType].\nDefinition comAlg_closedFieldType :=\n  [closedFieldType of numClosedField_comAlgType].\nDefinition unitAlg_decFieldType := [decFieldType of numClosedField_unitAlgType].\nDefinition unitAlg_closedFieldType :=\n  [closedFieldType of numClosedField_unitAlgType].\nDefinition comUnitAlg_decFieldType :=\n  [decFieldType of numClosedField_comUnitAlgType].\nDefinition comUnitAlg_closedFieldType :=\n  [closedFieldType of numClosedField_comUnitAlgType].\nDefinition vect_decFieldType := [decFieldType of numClosedField_vectType].\nDefinition vect_closedFieldType := [closedFieldType of numClosedField_vectType].\nDefinition Falg_decFieldType := [decFieldType of numClosedField_FalgType].\nDefinition Falg_closedFieldType := [closedFieldType of numClosedField_FalgType].\nDefinition fieldExt_decFieldType :=\n  [decFieldType of numClosedField_fieldExtType].\nDefinition fieldExt_closedFieldType :=\n  [closedFieldType of numClosedField_fieldExtType].\nDefinition pseudoMetricNormedZmod_decFieldType :=\n  [decFieldType of numClosedField_pseudoMetricNormedZmodType].\nDefinition pseudoMetricNormedZmod_closedFieldType :=\n  [closedFieldType of numClosedField_pseudoMetricNormedZmodType].\nDefinition normedMod_decFieldType :=\n  [decFieldType of numClosedField_normedModType].\nDefinition normedMod_closedFieldType :=\n  [closedFieldType of numClosedField_normedModType].\nEnd numClosedFieldType.\n\nSection numFieldType.\nVariable (R : numFieldType).\nLocal Canonical numField_lmodType := [lmodType R of R for [lmodType R of R^o]].\nLocal Canonical numField_lalgType := [lalgType R of R for [lalgType R of R^o]].\nLocal Canonical numField_algType := [algType R of R for [algType R of R^o]].\nLocal Canonical numField_comAlgType := [comAlgType R of R].\nLocal Canonical numField_unitAlgType := [unitAlgType R of R].\nLocal Canonical numField_comUnitAlgType := [comUnitAlgType R of R].\nLocal Canonical numField_vectType := [vectType R of R for [vectType R of R^o]].\nLocal Canonical numField_FalgType := [FalgType R of R].\nLocal Canonical numField_fieldExtType :=\n  [fieldExtType R of R for [fieldExtType R of R^o]].\nLocal Canonical numField_pseudoMetricNormedZmodType :=\n  [pseudoMetricNormedZmodType R of R for [pseudoMetricNormedZmodType R of R^o]].\nLocal Canonical numField_normedModType :=\n  [normedModType R of R for [normedModType R of R^o]].\nDefinition lmod_porderType := [porderType of numField_lmodType].\nDefinition lmod_numDomainType := [numDomainType of numField_lmodType].\nDefinition lalg_pointedType := [pointedType of numField_lalgType].\nDefinition lalg_filteredType := [filteredType R of numField_lalgType].\nDefinition lalg_topologicalType := [topologicalType of numField_lalgType].\nDefinition lalg_uniformType := [uniformType of numField_lalgType].\nDefinition lalg_pseudoMetricType := [pseudoMetricType R of numField_lalgType].\nDefinition lalg_normedZmodType := [normedZmodType R of numField_lalgType].\nDefinition lalg_pseudoMetricNormedZmodType :=\n  [pseudoMetricNormedZmodType R of numField_lalgType].\nDefinition lalg_normedModType := [normedModType R of numField_lalgType].\nDefinition lalg_porderType := [porderType of numField_lalgType].\nDefinition lalg_numDomainType := [numDomainType of numField_lalgType].\nDefinition alg_pointedType := [pointedType of numField_algType].\nDefinition alg_filteredType := [filteredType R of numField_algType].\nDefinition alg_topologicalType := [topologicalType of numField_algType].\nDefinition alg_uniformType := [uniformType of numField_algType].\nDefinition alg_pseudoMetricType := [pseudoMetricType R of numField_algType].\nDefinition alg_normedZmodType := [normedZmodType R of numField_algType].\nDefinition alg_pseudoMetricNormedZmodType :=\n  [pseudoMetricNormedZmodType R of numField_algType].\nDefinition alg_normedModType := [normedModType R of numField_algType].\nDefinition alg_porderType := [porderType of numField_algType].\nDefinition alg_numDomainType := [numDomainType of numField_algType].\nDefinition comAlg_pointedType := [pointedType of numField_comAlgType].\nDefinition comAlg_filteredType := [filteredType R of numField_comAlgType].\nDefinition comAlg_topologicalType := [topologicalType of numField_comAlgType].\nDefinition comAlg_uniformType := [uniformType of numField_comAlgType].\nDefinition comAlg_pseudoMetricType :=\n  [pseudoMetricType R of numField_comAlgType].\nDefinition comAlg_normedZmodType := [normedZmodType R of numField_comAlgType].\nDefinition comAlg_pseudoMetricNormedZmodType :=\n  [pseudoMetricNormedZmodType R of numField_comAlgType].\nDefinition comAlg_normedModType := [normedModType R of numField_comAlgType].\nDefinition comAlg_porderType := [porderType of numField_comAlgType].\nDefinition comAlg_numDomainType := [numDomainType of numField_comAlgType].\nDefinition unitAlg_pointedType := [pointedType of numField_unitAlgType].\nDefinition unitAlg_filteredType := [filteredType R of numField_unitAlgType].\nDefinition unitAlg_topologicalType := [topologicalType of numField_unitAlgType].\nDefinition unitAlg_uniformType := [uniformType of numField_unitAlgType].\nDefinition unitAlg_pseudoMetricType :=\n  [pseudoMetricType R of numField_unitAlgType].\nDefinition unitAlg_normedZmodType := [normedZmodType R of numField_unitAlgType].\nDefinition unitAlg_pseudoMetricNormedZmodType :=\n  [pseudoMetricNormedZmodType R of numField_unitAlgType].\nDefinition unitAlg_normedModType := [normedModType R of numField_unitAlgType].\nDefinition unitAlg_porderType := [porderType of numField_unitAlgType].\nDefinition unitAlg_numDomainType := [numDomainType of numField_unitAlgType].\nDefinition comUnitAlg_pointedType := [pointedType of numField_comUnitAlgType].\nDefinition comUnitAlg_filteredType :=\n  [filteredType R of numField_comUnitAlgType].\nDefinition comUnitAlg_topologicalType :=\n  [topologicalType of numField_comUnitAlgType].\nDefinition comUnitAlg_uniformType := [uniformType of numField_comUnitAlgType].\nDefinition comUnitAlg_pseudoMetricType :=\n  [pseudoMetricType R of numField_comUnitAlgType].\nDefinition comUnitAlg_normedZmodType :=\n  [normedZmodType R of numField_comUnitAlgType].\nDefinition comUnitAlg_pseudoMetricNormedZmodType :=\n  [pseudoMetricNormedZmodType R of numField_comUnitAlgType].\nDefinition comUnitAlg_normedModType :=\n  [normedModType R of numField_comUnitAlgType].\nDefinition comUnitAlg_porderType := [porderType of numField_comUnitAlgType].\nDefinition comUnitAlg_numDomainType :=\n  [numDomainType of numField_comUnitAlgType].\nDefinition vect_pointedType := [pointedType of numField_vectType].\nDefinition vect_filteredType := [filteredType R of numField_vectType].\nDefinition vect_topologicalType := [topologicalType of numField_vectType].\nDefinition vect_uniformType := [uniformType of numField_vectType].\nDefinition vect_pseudoMetricType := [pseudoMetricType R of numField_vectType].\nDefinition vect_normedZmodType := [normedZmodType R of numField_vectType].\nDefinition vect_pseudoMetricNormedZmodType :=\n  [pseudoMetricNormedZmodType R of numField_vectType].\nDefinition vect_normedModType := [normedModType R of numField_vectType].\nDefinition vect_porderType := [porderType of numField_vectType].\nDefinition vect_numDomainType := [numDomainType of numField_vectType].\nDefinition Falg_pointedType := [pointedType of numField_FalgType].\nDefinition Falg_filteredType := [filteredType R of numField_FalgType].\nDefinition Falg_topologicalType := [topologicalType of numField_FalgType].\nDefinition Falg_uniformType := [uniformType of numField_FalgType].\nDefinition Falg_pseudoMetricType := [pseudoMetricType R of numField_FalgType].\nDefinition Falg_normedZmodType := [normedZmodType R of numField_FalgType].\nDefinition Falg_pseudoMetricNormedZmodType :=\n  [pseudoMetricNormedZmodType R of numField_FalgType].\nDefinition Falg_normedModType := [normedModType R of numField_FalgType].\nDefinition Falg_porderType := [porderType of numField_FalgType].\nDefinition Falg_numDomainType := [numDomainType of numField_FalgType].\nDefinition fieldExt_pointedType := [pointedType of numField_fieldExtType].\nDefinition fieldExt_filteredType := [filteredType R of numField_fieldExtType].\nDefinition fieldExt_topologicalType :=\n  [topologicalType of numField_fieldExtType].\nDefinition fieldExt_uniformType := [uniformType of numField_fieldExtType].\nDefinition fieldExt_pseudoMetricType :=\n  [pseudoMetricType R of numField_fieldExtType].\nDefinition fieldExt_normedZmodType :=\n  [normedZmodType R of numField_fieldExtType].\nDefinition fieldExt_pseudoMetricNormedZmodType :=\n  [pseudoMetricNormedZmodType R of numField_fieldExtType].\nDefinition fieldExt_normedModType := [normedModType R of numField_fieldExtType].\nDefinition fieldExt_porderType := [porderType of numField_fieldExtType].\nDefinition fieldExt_numDomainType := [numDomainType of numField_fieldExtType].\nDefinition pseudoMetricNormedZmod_ringType :=\n  [ringType of numField_pseudoMetricNormedZmodType].\nDefinition pseudoMetricNormedZmod_comRingType :=\n  [comRingType of numField_pseudoMetricNormedZmodType].\nDefinition pseudoMetricNormedZmod_unitRingType :=\n  [unitRingType of numField_pseudoMetricNormedZmodType].\nDefinition pseudoMetricNormedZmod_comUnitRingType :=\n  [comUnitRingType of numField_pseudoMetricNormedZmodType].\nDefinition pseudoMetricNormedZmod_idomainType :=\n  [idomainType of numField_pseudoMetricNormedZmodType].\nDefinition pseudoMetricNormedZmod_fieldType :=\n  [fieldType of numField_pseudoMetricNormedZmodType].\nDefinition pseudoMetricNormedZmod_porderType :=\n  [porderType of numField_pseudoMetricNormedZmodType].\nDefinition pseudoMetricNormedZmod_numDomainType :=\n  [numDomainType of numField_pseudoMetricNormedZmodType].\nDefinition normedMod_ringType := [ringType of numField_normedModType].\nDefinition normedMod_comRingType := [comRingType of numField_normedModType].\nDefinition normedMod_unitRingType := [unitRingType of numField_normedModType].\nDefinition normedMod_comUnitRingType :=\n  [comUnitRingType of numField_normedModType].\nDefinition normedMod_idomainType := [idomainType of numField_normedModType].\nDefinition normedMod_fieldType := [fieldType of numField_normedModType].\nDefinition normedMod_porderType := [porderType of numField_normedModType].\nDefinition normedMod_numDomainType := [numDomainType of numField_normedModType].\nEnd numFieldType.\n\nModule Exports.\nExport topology.numFieldTopology.Exports.\n(* realType *)\nCanonical real_lmodType.\nCanonical real_lalgType.\nCanonical real_algType.\nCanonical real_comAlgType.\nCanonical real_unitAlgType.\nCanonical real_comUnitAlgType.\nCanonical real_vectType.\nCanonical real_FalgType.\nCanonical real_fieldExtType.\nCanonical real_pseudoMetricNormedZmodType.\nCanonical real_normedModType.\nCoercion real_lmodType : realType >-> lmodType.\nCoercion real_lalgType : realType >-> lalgType.\nCoercion real_algType : realType >-> algType.\nCoercion real_comAlgType : realType >-> comAlgType.\nCoercion real_unitAlgType : realType >-> unitAlgType.\nCoercion real_comUnitAlgType : realType >-> comUnitAlgType.\nCoercion real_vectType : realType >-> vectType.\nCoercion real_FalgType : realType >-> FalgType.\nCoercion real_fieldExtType : realType >-> fieldExtType.\nCoercion real_pseudoMetricNormedZmodType :\n  realType >-> pseudoMetricNormedZmodType.\nCoercion real_normedModType : realType >-> normedModType.\n(* rcfType *)\nCanonical rcf_lmodType.\nCanonical rcf_lalgType.\nCanonical rcf_algType.\nCanonical rcf_comAlgType.\nCanonical rcf_unitAlgType.\nCanonical rcf_comUnitAlgType.\nCanonical rcf_vectType.\nCanonical rcf_FalgType.\nCanonical rcf_fieldExtType.\nCanonical rcf_pseudoMetricNormedZmodType.\nCanonical rcf_normedModType.\nCoercion rcf_lmodType : rcfType >-> lmodType.\nCoercion rcf_lalgType : rcfType >-> lalgType.\nCoercion rcf_algType : rcfType >-> algType.\nCoercion rcf_comAlgType : rcfType >-> comAlgType.\nCoercion rcf_unitAlgType : rcfType >-> unitAlgType.\nCoercion rcf_comUnitAlgType : rcfType >-> comUnitAlgType.\nCoercion rcf_vectType : rcfType >-> vectType.\nCoercion rcf_FalgType : rcfType >-> FalgType.\nCoercion rcf_fieldExtType : rcfType >-> fieldExtType.\nCoercion rcf_pseudoMetricNormedZmodType :\n  rcfType >-> pseudoMetricNormedZmodType.\nCoercion rcf_normedModType : rcfType >-> normedModType.\n(* archiFieldType *)\nCanonical archiField_lmodType.\nCanonical archiField_lalgType.\nCanonical archiField_algType.\nCanonical archiField_comAlgType.\nCanonical archiField_unitAlgType.\nCanonical archiField_comUnitAlgType.\nCanonical archiField_vectType.\nCanonical archiField_FalgType.\nCanonical archiField_fieldExtType.\nCanonical archiField_pseudoMetricNormedZmodType.\nCanonical archiField_normedModType.\nCoercion archiField_lmodType : archiFieldType >-> lmodType.\nCoercion archiField_lalgType : archiFieldType >-> lalgType.\nCoercion archiField_algType : archiFieldType >-> algType.\nCoercion archiField_comAlgType : archiFieldType >-> comAlgType.\nCoercion archiField_unitAlgType : archiFieldType >-> unitAlgType.\nCoercion archiField_comUnitAlgType : archiFieldType >-> comUnitAlgType.\nCoercion archiField_vectType : archiFieldType >-> vectType.\nCoercion archiField_FalgType : archiFieldType >-> FalgType.\nCoercion archiField_fieldExtType : archiFieldType >-> fieldExtType.\nCoercion archiField_pseudoMetricNormedZmodType :\n  archiFieldType >-> pseudoMetricNormedZmodType.\nCoercion archiField_normedModType : archiFieldType >-> normedModType.\n(* realFieldType *)\nCanonical realField_lmodType.\nCanonical realField_lalgType.\nCanonical realField_algType.\nCanonical realField_comAlgType.\nCanonical realField_unitAlgType.\nCanonical realField_comUnitAlgType.\nCanonical realField_vectType.\nCanonical realField_FalgType.\nCanonical realField_fieldExtType.\nCanonical realField_pseudoMetricNormedZmodType.\nCanonical realField_normedModType.\nCanonical lmod_latticeType.\nCanonical lmod_distrLatticeType.\nCanonical lmod_orderType.\nCanonical lmod_realDomainType.\nCanonical lalg_latticeType.\nCanonical lalg_distrLatticeType.\nCanonical lalg_orderType.\nCanonical lalg_realDomainType.\nCanonical alg_latticeType.\nCanonical alg_distrLatticeType.\nCanonical alg_orderType.\nCanonical alg_realDomainType.\nCanonical comAlg_latticeType.\nCanonical comAlg_distrLatticeType.\nCanonical comAlg_orderType.\nCanonical comAlg_realDomainType.\nCanonical unitAlg_latticeType.\nCanonical unitAlg_distrLatticeType.\nCanonical unitAlg_orderType.\nCanonical unitAlg_realDomainType.\nCanonical comUnitAlg_latticeType.\nCanonical comUnitAlg_distrLatticeType.\nCanonical comUnitAlg_orderType.\nCanonical comUnitAlg_realDomainType.\nCanonical vect_latticeType.\nCanonical vect_distrLatticeType.\nCanonical vect_orderType.\nCanonical vect_realDomainType.\nCanonical Falg_latticeType.\nCanonical Falg_distrLatticeType.\nCanonical Falg_orderType.\nCanonical Falg_realDomainType.\nCanonical fieldExt_latticeType.\nCanonical fieldExt_distrLatticeType.\nCanonical fieldExt_orderType.\nCanonical fieldExt_realDomainType.\nCanonical pseudoMetricNormedZmod_latticeType.\nCanonical pseudoMetricNormedZmod_distrLatticeType.\nCanonical pseudoMetricNormedZmod_orderType.\nCanonical pseudoMetricNormedZmod_realDomainType.\nCanonical normedMod_latticeType.\nCanonical normedMod_distrLatticeType.\nCanonical normedMod_orderType.\nCanonical normedMod_realDomainType.\nCoercion realField_lmodType : realFieldType >-> lmodType.\nCoercion realField_lalgType : realFieldType >-> lalgType.\nCoercion realField_algType : realFieldType >-> algType.\nCoercion realField_comAlgType : realFieldType >-> comAlgType.\nCoercion realField_unitAlgType : realFieldType >-> unitAlgType.\nCoercion realField_comUnitAlgType : realFieldType >-> comUnitAlgType.\nCoercion realField_vectType : realFieldType >-> vectType.\nCoercion realField_FalgType : realFieldType >-> FalgType.\nCoercion realField_fieldExtType : realFieldType >-> fieldExtType.\nCoercion realField_pseudoMetricNormedZmodType :\n  Num.RealField.type >-> PseudoMetricNormedZmodule.type.\nCoercion realField_normedModType : Num.RealField.type >-> NormedModule.type.\n(* numClosedFieldType *)\nCanonical numClosedField_lmodType.\nCanonical numClosedField_lalgType.\nCanonical numClosedField_algType.\nCanonical numClosedField_comAlgType.\nCanonical numClosedField_unitAlgType.\nCanonical numClosedField_comUnitAlgType.\nCanonical numClosedField_vectType.\nCanonical numClosedField_FalgType.\nCanonical numClosedField_fieldExtType.\nCanonical numClosedField_pseudoMetricNormedZmodType.\nCanonical numClosedField_normedModType.\nCanonical lmod_decFieldType.\nCanonical lmod_closedFieldType.\nCanonical lalg_decFieldType.\nCanonical lalg_closedFieldType.\nCanonical alg_decFieldType.\nCanonical alg_closedFieldType.\nCanonical comAlg_decFieldType.\nCanonical comAlg_closedFieldType.\nCanonical unitAlg_decFieldType.\nCanonical unitAlg_closedFieldType.\nCanonical comUnitAlg_decFieldType.\nCanonical comUnitAlg_closedFieldType.\nCanonical vect_decFieldType.\nCanonical vect_closedFieldType.\nCanonical Falg_decFieldType.\nCanonical Falg_closedFieldType.\nCanonical fieldExt_decFieldType.\nCanonical fieldExt_closedFieldType.\nCanonical pseudoMetricNormedZmod_decFieldType.\nCanonical pseudoMetricNormedZmod_closedFieldType.\nCanonical normedMod_decFieldType.\nCanonical normedMod_closedFieldType.\nCoercion numClosedField_lmodType : numClosedFieldType >-> lmodType.\nCoercion numClosedField_lalgType : numClosedFieldType >-> lalgType.\nCoercion numClosedField_algType : numClosedFieldType >-> algType.\nCoercion numClosedField_comAlgType : numClosedFieldType >-> comAlgType.\nCoercion numClosedField_unitAlgType : numClosedFieldType >-> unitAlgType.\nCoercion numClosedField_comUnitAlgType : numClosedFieldType >-> comUnitAlgType.\nCoercion numClosedField_vectType : numClosedFieldType >-> vectType.\nCoercion numClosedField_FalgType : numClosedFieldType >-> FalgType.\nCoercion numClosedField_fieldExtType : numClosedFieldType >-> fieldExtType.\nCoercion numClosedField_pseudoMetricNormedZmodType :\n  numClosedFieldType >-> pseudoMetricNormedZmodType.\nCoercion numClosedField_normedModType : numClosedFieldType >-> normedModType.\n(* numFieldType *)\nCanonical numField_lmodType.\nCanonical numField_lalgType.\nCanonical numField_algType.\nCanonical numField_comAlgType.\nCanonical numField_unitAlgType.\nCanonical numField_comUnitAlgType.\nCanonical numField_vectType.\nCanonical numField_FalgType.\nCanonical numField_fieldExtType.\nCanonical numField_pseudoMetricNormedZmodType.\nCanonical numField_normedModType.\nCanonical lmod_porderType.\nCanonical lmod_numDomainType.\nCanonical lalg_pointedType.\nCanonical lalg_filteredType.\nCanonical lalg_topologicalType.\nCanonical lalg_uniformType.\nCanonical lalg_pseudoMetricType.\nCanonical lalg_normedZmodType.\nCanonical lalg_pseudoMetricNormedZmodType.\nCanonical lalg_normedModType.\nCanonical lalg_porderType.\nCanonical lalg_numDomainType.\nCanonical alg_pointedType.\nCanonical alg_filteredType.\nCanonical alg_topologicalType.\nCanonical alg_uniformType.\nCanonical alg_pseudoMetricType.\nCanonical alg_normedZmodType.\nCanonical alg_pseudoMetricNormedZmodType.\nCanonical alg_normedModType.\nCanonical alg_porderType.\nCanonical alg_numDomainType.\nCanonical comAlg_pointedType.\nCanonical comAlg_filteredType.\nCanonical comAlg_topologicalType.\nCanonical comAlg_uniformType.\nCanonical comAlg_pseudoMetricType.\nCanonical comAlg_normedZmodType.\nCanonical comAlg_pseudoMetricNormedZmodType.\nCanonical comAlg_normedModType.\nCanonical comAlg_porderType.\nCanonical comAlg_numDomainType.\nCanonical unitAlg_pointedType.\nCanonical unitAlg_filteredType.\nCanonical unitAlg_topologicalType.\nCanonical unitAlg_uniformType.\nCanonical unitAlg_pseudoMetricType.\nCanonical unitAlg_normedZmodType.\nCanonical unitAlg_pseudoMetricNormedZmodType.\nCanonical unitAlg_normedModType.\nCanonical unitAlg_porderType.\nCanonical unitAlg_numDomainType.\nCanonical comUnitAlg_pointedType.\nCanonical comUnitAlg_filteredType.\nCanonical comUnitAlg_topologicalType.\nCanonical comUnitAlg_uniformType.\nCanonical comUnitAlg_pseudoMetricType.\nCanonical comUnitAlg_normedZmodType.\nCanonical comUnitAlg_pseudoMetricNormedZmodType.\nCanonical comUnitAlg_normedModType.\nCanonical comUnitAlg_porderType.\nCanonical comUnitAlg_numDomainType.\nCanonical vect_pointedType.\nCanonical vect_filteredType.\nCanonical vect_topologicalType.\nCanonical vect_uniformType.\nCanonical vect_pseudoMetricType.\nCanonical vect_normedZmodType.\nCanonical vect_pseudoMetricNormedZmodType.\nCanonical vect_normedModType.\nCanonical vect_porderType.\nCanonical vect_numDomainType.\nCanonical Falg_pointedType.\nCanonical Falg_filteredType.\nCanonical Falg_topologicalType.\nCanonical Falg_uniformType.\nCanonical Falg_pseudoMetricType.\nCanonical Falg_normedZmodType.\nCanonical Falg_pseudoMetricNormedZmodType.\nCanonical Falg_normedModType.\nCanonical Falg_porderType.\nCanonical Falg_numDomainType.\nCanonical fieldExt_pointedType.\nCanonical fieldExt_filteredType.\nCanonical fieldExt_topologicalType.\nCanonical fieldExt_uniformType.\nCanonical fieldExt_pseudoMetricType.\nCanonical fieldExt_normedZmodType.\nCanonical fieldExt_pseudoMetricNormedZmodType.\nCanonical fieldExt_normedModType.\nCanonical fieldExt_porderType.\nCanonical fieldExt_numDomainType.\nCanonical pseudoMetricNormedZmod_ringType.\nCanonical pseudoMetricNormedZmod_comRingType.\nCanonical pseudoMetricNormedZmod_unitRingType.\nCanonical pseudoMetricNormedZmod_comUnitRingType.\nCanonical pseudoMetricNormedZmod_idomainType.\nCanonical pseudoMetricNormedZmod_fieldType.\nCanonical pseudoMetricNormedZmod_porderType.\nCanonical pseudoMetricNormedZmod_numDomainType.\nCanonical normedMod_ringType.\nCanonical normedMod_comRingType.\nCanonical normedMod_unitRingType.\nCanonical normedMod_comUnitRingType.\nCanonical normedMod_idomainType.\nCanonical normedMod_fieldType.\nCanonical normedMod_porderType.\nCanonical normedMod_numDomainType.\nCoercion numField_lmodType : numFieldType >-> lmodType.\nCoercion numField_lalgType : numFieldType >-> lalgType.\nCoercion numField_algType : numFieldType >-> algType.\nCoercion numField_comAlgType : numFieldType >-> comAlgType.\nCoercion numField_unitAlgType : numFieldType >-> unitAlgType.\nCoercion numField_comUnitAlgType : numFieldType >-> comUnitAlgType.\nCoercion numField_vectType : numFieldType >-> vectType.\nCoercion numField_FalgType : numFieldType >-> FalgType.\nCoercion numField_fieldExtType : numFieldType >-> fieldExtType.\nCoercion numField_pseudoMetricNormedZmodType :\n  numFieldType >-> pseudoMetricNormedZmodType.\nCoercion numField_normedModType : numFieldType >-> normedModType.\nEnd Exports.\n\nEnd numFieldNormedType.\nImport numFieldNormedType.Exports.\n\nSection NormedModule_numDomainType.\nVariables (R : numDomainType) (V : normedModType R).\n\nLemma normrZ l (x : V) : `| l *: x | = `| l | * `| x |.\nProof. by case: V x => V0 [a b [c]] //= v; rewrite c. Qed.\n\nLemma normrZV (x : V) : `|x| \\in GRing.unit -> `| `| x |^-1 *: x | = 1.\nProof. by move=> nxu; rewrite normrZ normrV// normr_id mulVr. Qed.\n\nEnd NormedModule_numDomainType.\n\n#[deprecated(since=\"mathcomp-analysis 0.6.0\", note=\"renamed `normrZ`\")]\nNotation normmZ := normrZ.\n\nSection NormedModule_numFieldType.\nVariables (R : numFieldType) (V : normedModType R).\n\nLemma normfZV (x : V) : x != 0 -> `| `|x|^-1 *: x | = 1.\nProof. by rewrite -normr_eq0 -unitfE => /normrZV->. Qed.\n\nEnd NormedModule_numFieldType.\n\nSection PseudoNormedZmod_numDomainType.\nVariables (R : numDomainType) (V : pseudoMetricNormedZmodType R).\n\nLocal Notation ball_norm := (ball_ (@normr R V)).\n\nLocal Notation nbhs_ball := (@nbhs_ball _ V).\n\nLocal Notation nbhs_norm := (nbhs_ball_ ball_norm).\n\n(* if we do not give the V argument to nbhs, the universally quantified set that\nappears inside the notation for cvg_to has type\nset (let '{| PseudoMetricNormedZmodule.sort := T |} := V in T) instead of set V,\nwhich causes an inference problem in derive.v *)\nLemma nbhs_nbhs_norm : nbhs_norm = nbhs.\nProof. by rewrite ball_normE funeqE => x; rewrite -filter_from_ballE. Qed.\n\nLemma nbhs_normP x (P : V -> Prop) : (\\near x, P x) <-> nbhs_norm x P.\nProof. by rewrite nbhs_nbhs_norm. Qed.\n\nLemma nbhs_le_nbhs_norm (x : V) : @nbhs V _ x `=>` nbhs_norm x.\nProof. by move=> P [e e0 subP]; apply/nbhs_normP; exists e. Qed.\n\nLemma nbhs_norm_le_nbhs x : nbhs_norm x `=>` nbhs x.\nProof. by move=> P /nbhs_normP [e e0 Pxe]; exists e. Qed.\n\nLemma filter_from_norm_nbhs x :\n  @filter_from R _ [set x : R | 0 < x] (ball_norm x) = nbhs x.\nProof. by rewrite -nbhs_nbhs_norm ball_normE. Qed.\n\nLemma nbhs_normE (x : V) (P : V -> Prop) :\n  nbhs_norm x P = \\near x, P x.\nProof. by rewrite nbhs_nbhs_norm near_simpl. Qed.\n\nLemma filter_from_normE (x : V) (P : V -> Prop) :\n  @filter_from R _ [set x : R | 0 < x] (ball_norm x) P = \\near x, P x.\nProof. by rewrite filter_from_norm_nbhs. Qed.\n\nLemma near_nbhs_norm (x : V) (P : V -> Prop) :\n  (\\forall x \\near nbhs_norm x, P x) = \\near x, P x.\nProof. exact: nbhs_normE. Qed.\n\nLemma nbhs_norm_ball_norm x (e : {posnum R}) :\n  nbhs_norm x (ball_norm x e%:num).\nProof. by rewrite ball_normE; exists e%:num => /=. Qed.\n\nLemma nbhs_ball_norm (x : V) (eps : {posnum R}) : nbhs x (ball_norm x eps%:num).\nProof. rewrite -nbhs_nbhs_norm; apply: nbhs_norm_ball_norm. Qed.\n\nLemma ball_norm_dec x y (e : R) : {ball_norm x e y} + {~ ball_norm x e y}.\nProof. exact: pselect. Qed.\n\nLemma ball_norm_sym x y (e : R) : ball_norm x e y -> ball_norm y e x.\nProof. by rewrite /ball_norm/= -opprB normrN. Qed.\n\nLemma ball_norm_le x (e1 e2 : R) :\n  e1 <= e2 -> ball_norm x e1 `<=` ball_norm x e2.\nProof. by move=> e1e2 y /lt_le_trans; apply. Qed.\n\nLet nbhs_simpl := (nbhs_simpl,@nbhs_nbhs_norm,@filter_from_norm_nbhs).\n\nLemma fcvgrPdist_lt {F : set (set V)} {FF : Filter F} (y : V) :\n  F --> y <-> forall eps, 0 < eps -> \\forall y' \\near F, `|y - y'| < eps.\nProof. by rewrite -filter_fromP /= !nbhs_simpl. Qed.\n\nLemma cvgrPdist_lt {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y <-> forall eps, 0 < eps -> \\forall t \\near F, `|y - f t| < eps.\nProof. exact: fcvgrPdist_lt. Qed.\n\nLemma cvgrPdistC_lt {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y <-> forall eps, 0 < eps -> \\forall t \\near F, `|f t - y| < eps.\nProof.\nby rewrite cvgrPdist_lt; under eq_forall do under eq_near do rewrite distrC.\nQed.\n\nLemma cvgr_dist_lt {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y -> forall eps, eps > 0 -> \\forall t \\near F, `|y - f t| < eps.\nProof. by move=> /cvgrPdist_lt. Qed.\n\nLemma __deprecated__cvg_dist {F : set (set V)} {FF : Filter F} (y : V) :\n  F --> y -> forall eps, eps > 0 -> \\forall y' \\near F, `|y - y'| < eps.\nProof. exact: cvgr_dist_lt. Qed.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"use `cvgr_dist_lt` or a variation instead\")]\nNotation cvg_dist := __deprecated__cvg_dist.\n\nLemma cvgr_distC_lt {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y -> forall eps, eps > 0 -> \\forall t \\near F, `|f t - y| < eps.\nProof. by move=> /cvgrPdistC_lt. Qed.\n\nLemma cvgr_dist_le {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y -> forall eps, eps > 0 -> \\forall t \\near F, `|y - f t| <= eps.\nProof.\nby move=> ? ? ?; near do rewrite ltW//; apply: cvgr_dist_lt.\nUnshelve. all: by end_near. Qed.\n\nLemma cvgr_distC_le {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y -> forall eps, eps > 0 -> \\forall t \\near F, `|f t - y| <= eps.\nProof.\nby move=> ? ? ?; near do rewrite ltW//; apply: cvgr_distC_lt.\nUnshelve. all: by end_near. Qed.\n\nLemma nbhs_norm0P {P : V -> Prop} :\n  (\\forall x \\near 0, P x) <->\n  filter_from [set e | 0 < e] (fun e => [set y | `|y| < e]) P.\nProof.\nrewrite nbhs_normP; split=> -[/= e e0 Pe];\nby exists e => // y /=; have /= := Pe y; rewrite distrC subr0.\nQed.\n\nLemma cvgr0Pnorm_lt {T} {F : set (set T)} {FF : Filter F} (f : T -> V) :\n  f @ F --> 0 <-> forall eps, 0 < eps -> \\forall t \\near F, `|f t| < eps.\nProof.\nby rewrite cvgrPdistC_lt; under eq_forall do under eq_near do rewrite subr0.\nQed.\n\nLemma cvgr0_norm_lt {T} {F : set (set T)} {FF : Filter F} (f : T -> V) :\n  f @ F --> 0 -> forall eps, eps > 0 -> \\forall t \\near F, `|f t| < eps.\nProof. by move=> /cvgr0Pnorm_lt. Qed.\n\nLemma cvgr0_norm_le {T} {F : set (set T)} {FF : Filter F} (f : T -> V) :\n  f @ F --> 0 -> forall eps, eps > 0 -> \\forall t \\near F, `|f t| <= eps.\nProof.\nby move=> ? ? ?; near do rewrite ltW//; apply: cvgr0_norm_lt.\nUnshelve. all: by end_near. Qed.\n\nLemma nbhs0_lt e : 0 < e -> \\forall x \\near (0 : V), `|x| < e.\nProof. exact: cvgr0_norm_lt. Qed.\n\nLemma dnbhs0_lt e : 0 < e -> \\forall x \\near (0 : V)^', `|x| < e.\nProof. by move=> e_gt0; apply: cvg_within; apply: nbhs0_lt. Qed.\n\nLemma nbhs0_le e : 0 < e -> \\forall x \\near (0 : V), `|x| <= e.\nProof. exact: cvgr0_norm_le. Qed.\n\nLemma dnbhs0_le e : 0 < e -> \\forall x \\near (0 : V)^', `|x| <= e.\nProof. by move=> e_gt0; apply: cvg_within; apply: nbhs0_le. Qed.\n\nLemma nbhs_norm_ball x (eps : {posnum R}) : nbhs_norm x (ball x eps%:num).\nProof. rewrite nbhs_nbhs_norm; by apply: nbhsx_ballx. Qed.\n\nLemma nbhsDl (P : set V) (x y : V) :\n  (\\forall z \\near (x + y), P z) <-> (\\near x, P (x + y)).\nProof.\nsplit=> /nbhs_normP[_/posnumP[e]/= Px]; apply/nbhs_normP; exists e%:num => //=.\n  by move=> z /= xze; apply: Px; rewrite /= opprD addrACA subrr addr0.\nby move=> z /= xyz; rewrite -[z](addrNK y); apply: Px; rewrite /= opprB addrA.\nQed.\n\nLemma nbhsDr (P : set V) x y :\n  (\\forall z \\near (x + y), P z) <-> (\\near y, P (x + y)).\nProof. by rewrite addrC nbhsDl -propeqE; apply: eq_near => ?; rewrite addrC. Qed.\n\nLemma nbhs0P (P : set V) x : (\\near x, P x) <-> (\\forall e \\near 0, P (x + e)).\nProof. by rewrite -nbhsDr addr0. Qed.\n\nEnd PseudoNormedZmod_numDomainType.\n#[global] Hint Resolve normr_ge0 : core.\nArguments cvgr_dist_lt {_ _ _ F FF}.\nArguments cvgr_distC_lt {_ _ _ F FF}.\nArguments cvgr_dist_le {_ _ _ F FF}.\nArguments cvgr_distC_le {_ _ _ F FF}.\nArguments cvgr0_norm_lt {_ _ _ F FF}.\nArguments cvgr0_norm_le {_ _ _ F FF}.\n\n#[global] Hint Extern 0 (is_true (`|_ - ?x| < _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: cvgr_dist_lt end : core.\n#[global] Hint Extern 0 (is_true (`|?x - _| < _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: cvgr_distC_lt end : core.\n#[global] Hint Extern 0 (is_true (`|?x| < _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: cvgr0_norm_lt end : core.\n#[global] Hint Extern 0 (is_true (`|_ - ?x| <= _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: cvgr_dist_le end : core.\n#[global] Hint Extern 0 (is_true (`|?x - _| <= _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: cvgr_distC_le end : core.\n#[global] Hint Extern 0 (is_true (`|?x| <= _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: cvgr0_norm_le end : core.\n\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"use `cvgrPdist_lt` or a variation instead\")]\nNotation cvg_distP := fcvgrPdist_lt.\n\nSection open_closed_sets.\n(* TODO: duplicate theory within the subspace topology of Num.real\n         in a numDomainType *)\nVariable R : realFieldType.\n\n(** Some open sets of [R] *)\nLemma open_lt (y : R) : open [set x : R| x < y].\nProof.\nmove=> x /=; rewrite -subr_gt0 => yDx_gt0. exists (y - x) => // z.\nby rewrite /= ltr_distlC addrCA subrr addr0 => /andP[].\nQed.\nHint Resolve open_lt : core.\n\nLemma open_gt (y : R) : open [set x : R | x > y].\nProof.\nmove=> x /=; rewrite -subr_gt0 => xDy_gt0; exists (x - y) => // z.\nby rewrite /= ltr_distlC opprB addrCA subrr addr0 => /andP[].\nQed.\nHint Resolve open_gt : core.\n\nLemma open_neq (y : R) : open [set x : R | x != y].\nProof.\nrewrite (_ : mkset _ = [set x | x < y] `|` [set x | x > y]); first exact: openU.\nrewrite predeqE => x /=; rewrite eq_le !leNgt negb_and !negbK orbC.\nby symmetry; apply (rwP orP).\nQed.\n\nLemma interval_open a b : ~~ bound_side true a -> ~~ bound_side false b ->\n  open [set x : R^o | x \\in Interval a b].\nProof.\nmove: a b => [[]a|[]] [[]b|[]]// _ _.\n- have -> : [set x | a < x < b] = [set x | a < x] `&` [set x | x < b].\n    by rewrite predeqE => r; rewrite /mkset; split => [/andP[? ?] //|[-> ->]].\n  by apply openI; [exact: open_gt | exact: open_lt].\n- by under eq_set do rewrite itv_ge// inE.\n- by under eq_set do rewrite in_itv andbT/=; exact: open_gt.\n- exact: open_lt.\n- by rewrite (_ : mkset _ = setT); [exact: openT | rewrite predeqE].\nQed.\n\n(** Some closed sets of [R] *)\n(* TODO: we can probably extend these results to numFieldType\n   by adding a precondition that y \\is Num.real *)\n\nLemma closed_le (y : R) : closed [set x : R | x <= y].\nProof.\nrewrite (_ : mkset _ = ~` [set x | x > y]); first exact: open_closedC.\nby rewrite predeqE => x /=; rewrite leNgt; split => /negP.\nQed.\n\nLemma closed_ge (y : R) : closed [set x : R | y <= x].\nProof.\nrewrite (_ : mkset _ = ~` [set x | x < y]); first exact: open_closedC.\nby rewrite predeqE => x /=; rewrite leNgt; split => /negP.\nQed.\n\nLemma closed_eq (y : R) : closed [set x : R | x = y].\nProof.\nrewrite [X in closed X](_ : (eq^~ _) = ~` (xpredC (eq_op^~ y))).\n  by apply: open_closedC; exact: open_neq.\nby rewrite predeqE /setC => x /=; rewrite (rwP eqP); case: eqP; split.\nQed.\n\nLemma interval_closed a b : ~~ bound_side false a -> ~~ bound_side true b ->\n  closed [set x : R^o | x \\in Interval a b].\nProof.\nmove: a b => [[]a|[]] [[]b|[]]// _ _;\n  do ?by under eq_set do rewrite itv_ge// inE falseE; apply: closed0.\n- have -> : `[a, b]%classic = [set x | x >= a] `&` [set x | x <= b].\n    by rewrite predeqE => ?; rewrite /= in_itv/=; split=> [/andP[]|[->]].\n  by apply closedI; [exact: closed_ge | exact: closed_le].\n- by under eq_set do rewrite in_itv andbT/=; exact: closed_ge.\n- exact: closed_le.\nQed.\n\nEnd open_closed_sets.\n\n#[global] Hint Extern 0 (open _) => now apply: open_gt : core.\n#[global] Hint Extern 0 (open _) => now apply: open_lt : core.\n#[global] Hint Extern 0 (open _) => now apply: open_neq : core.\n#[global] Hint Extern 0 (closed _) => now apply: closed_ge : core.\n#[global] Hint Extern 0 (closed _) => now apply: closed_le : core.\n#[global] Hint Extern 0 (closed _) => now apply: closed_eq : core.\n\nSection at_left_right_pmNormedZmod.\nVariable (R : numFieldType) (V : pseudoMetricNormedZmodType R).\n\nDefinition at_left (x : R) := within (fun u => u < x) (nbhs x).\nDefinition at_right (x : R) := within (fun u => x < u) (nbhs x).\nLocal Notation \"x ^'-\" := (at_left x) : classical_set_scope.\nLocal Notation \"x ^'+\" := (at_right x) : classical_set_scope.\n\nGlobal Instance at_right_proper_filter (x : R) : ProperFilter x^'+.\nProof.\napply: Build_ProperFilter' => -[_/posnumP[d] /(_ (x + d%:num / 2))].\napply; last (by rewrite ltr_addl); rewrite /=.\nrewrite opprD !addrA subrr add0r normrN normf_div !ger0_norm //.\nby rewrite ltr_pdivr_mulr // ltr_pmulr // (_ : 1 = 1%:R) // ltr_nat.\nQed.\n\nGlobal Instance at_left_proper_filter (x : R) : ProperFilter x^'-.\nProof.\napply: Build_ProperFilter' => -[_ /posnumP[d] /(_ (x - d%:num / 2))].\napply; last (by rewrite ltr_subl_addl ltr_addr); rewrite /=.\nrewrite opprD !addrA subrr add0r opprK normf_div !ger0_norm //.\nby rewrite ltr_pdivr_mulr // ltr_pmulr // (_ : 1 = 1%:R) // ltr_nat.\nQed.\n\nLemma nbhs_right0P x (P : set R) :\n  (\\forall y \\near x^'+, P y) <-> \\forall e \\near 0^'+, P (x + e).\nProof.\nrewrite !near_withinE !near_simpl nbhs0P -propeqE.\nby apply: (@eq_near _ (nbhs (0 : R))) => y; rewrite ltr_addl.\nQed.\n\nLemma nbhs_left0P x (P : set R) :\n  (\\forall y \\near x^'-, P y) <-> \\forall e \\near 0^'+, P (x - e).\nProof.\nrewrite !near_withinE !near_simpl nbhs0P; split=> Px.\n  rewrite -oppr0 nearN; near=> e; rewrite ltr_opp2 opprK => e_lt0.\n  by apply: (near Px) => //; rewrite gtr_addl.\nby rewrite -oppr0 nearN; near=> e; rewrite gtr_addl oppr_lt0; apply: (near Px).\nUnshelve. all: by end_near. Qed.\n\nLemma nbhs_right_gt x : \\forall y \\near x^'+, x < y.\nProof. by rewrite near_withinE; apply: nearW. Qed.\n\nLemma nbhs_left_lt x : \\forall y \\near x^'-, y < x.\nProof. by rewrite near_withinE; apply: nearW. Qed.\n\nLemma nbhs_right_neq x : \\forall y \\near x^'+, y != x.\nProof. by rewrite near_withinE; apply: nearW => ? /gt_eqF->. Qed.\n\nLemma nbhs_left_neq x : \\forall y \\near x^'-, y != x.\nProof. by rewrite near_withinE; apply: nearW => ? /lt_eqF->. Qed.\n\nLemma nbhs_right_ge x : \\forall y \\near x^'+, x <= y.\nProof. by rewrite near_withinE; apply: nearW; apply/ltW. Qed.\n\nLemma nbhs_left_le x : \\forall y \\near x^'-, y <= x.\nProof. by rewrite near_withinE; apply: nearW => ?; apply/ltW. Qed.\n\nLemma nbhs_right_lt x z : x < z -> \\forall y \\near x^'+, y < z.\nProof.\nmove=> xz; exists (z - x) => //=; first by rewrite subr_gt0.\nby move=> y /= + xy; rewrite distrC ?ger0_norm ?subr_ge0 1?ltW// ltr_add2r.\nQed.\n\nLemma nbhs_right_le x z : x < z -> \\forall y \\near x^'+, y <= z.\nProof. by move=> xz; near do apply/ltW; apply: nbhs_right_lt.\nUnshelve. all: by end_near. Qed.\n\nLemma nbhs_left_gt x z : z < x -> \\forall y \\near x^'-, z < y.\nProof.\nmove=> xz; rewrite nbhs_left0P; near do rewrite -ltr_opp2 opprB ltr_subl_addl.\nby apply: nbhs_right_lt; rewrite subr_gt0.\nUnshelve. all: by end_near. Qed.\n\nLemma nbhs_left_ge x z : z < x -> \\forall y \\near x^'-, z <= y.\nProof. by move=> xz; near do apply/ltW; apply: nbhs_left_gt.\nUnshelve. all: by end_near. Qed.\n\nLemma nbhsr0P (P : set V) x :\n  (\\forall y \\near x, P y) <-> (\\forall e \\near 0^'+, forall y, `|x - y| <= e -> P y).\nProof.\nrewrite nbhs0P/= near_withinE/= !near_simpl.\nsplit=> /nbhs_norm0P[/= _/posnumP[e] /(_ _) Px]; apply/nbhs_norm0P.\n  exists e%:num => //= r /= re yr y xyr; rewrite -[y](addrNK x) addrC.\n  by apply: Px; rewrite /= distrC (le_lt_trans _ re)// gtr0_norm.\nexists (e%:num / 2) => //= r /= re; apply: (Px (e%:num / 2)) => //=.\n   by rewrite gtr0_norm// ltr_pdivr_mulr// ltr_pmulr// ?(ltr_nat _ 1 2).\nby rewrite opprD addNKr normrN ltW.\nQed.\n\nLet cvgrP {F : set (set V)} {FF : Filter F} (y : V) : [<->\n  F --> y;\n  forall eps, 0 < eps -> \\forall t \\near F, `|y - t| <= eps;\n  \\forall eps \\near 0^'+, \\forall t \\near F, `|y - t| <= eps;\n  \\forall eps \\near 0^'+, \\forall t \\near F, `|y - t| < eps].\nProof.\ntfae; first by move=> *; apply: cvgr_dist_le.\n- by move=> Fy; near do apply: Fy; apply: nbhs_right_gt.\n- move=> Fy; near=> e; near 0^'+ => d; near=> x.\n  rewrite (@le_lt_trans _ _ d)//; first by near: x; near: d.\n  by near: d; apply: nbhs_right_lt; near: e; apply: nbhs_right_gt.\n- move=> Fy; apply/cvgrPdist_lt => e e_gt0; near 0^'+ => d.\n  near=> x; rewrite (@lt_le_trans _ _ d)//; first by near: x; near: d.\n  by near: d; apply: nbhs_right_le.\nUnshelve. all: by end_near. Qed.\n\nLemma cvgrPdist_le {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y <-> forall eps, 0 < eps -> \\forall t \\near F, `|y - f t| <= eps.\nProof. exact: (cvgrP _ 0 1)%N. Qed.\n\nLemma cvgrPdist_ltp {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y <-> \\forall eps \\near 0^'+, \\forall t \\near F, `|y - f t| < eps.\nProof. exact: (cvgrP _ 0 3)%N. Qed.\n\nLemma cvgrPdist_lep {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y <-> \\forall eps \\near 0^'+, \\forall t \\near F, `|y - f t| <= eps.\nProof. exact: (cvgrP _ 0 2)%N. Qed.\n\nLemma cvgrPdistC_le {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y <-> forall eps, 0 < eps -> \\forall t \\near F, `|f t - y| <= eps.\nProof.\nrewrite cvgrPdist_le.\nby under [X in X <-> _]eq_forall do under eq_near do rewrite distrC.\nQed.\n\nLemma cvgrPdistC_ltp {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y <-> \\forall eps \\near 0^'+, \\forall t \\near F, `|f t - y| < eps.\nProof.\nby rewrite cvgrPdist_ltp; under eq_near do under eq_near do rewrite distrC.\nQed.\n\nLemma cvgrPdistC_lep {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y <-> \\forall eps \\near 0^'+, \\forall t \\near F, `|f t - y| <= eps.\nProof.\nby rewrite cvgrPdist_lep; under eq_near do under eq_near do rewrite distrC.\nQed.\n\nLemma cvgr0Pnorm_le {T} {F : set (set T)} {FF : Filter F} (f : T -> V) :\n  f @ F --> 0 <-> forall eps, 0 < eps -> \\forall t \\near F, `|f t| <= eps.\nProof.\nrewrite cvgrPdistC_le.\nby under [X in X <-> _]eq_forall do under eq_near do rewrite subr0.\nQed.\n\nLemma cvgr0Pnorm_ltp {T} {F : set (set T)} {FF : Filter F} (f : T -> V) :\n  f @ F --> 0 <-> \\forall eps \\near 0^'+, \\forall t \\near F, `|f t| < eps.\nProof.\nby rewrite cvgrPdistC_ltp; under eq_near do under eq_near do rewrite subr0.\nQed.\n\nLemma cvgr0Pnorm_lep {T} {F : set (set T)} {FF : Filter F} (f : T -> V) :\n  f @ F --> 0 <-> \\forall eps \\near 0^'+, \\forall t \\near F, `|f t| <= eps.\nProof.\nby rewrite cvgrPdistC_lep; under eq_near do under eq_near do rewrite subr0.\nQed.\n\nLemma cvgr_norm_lt {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y -> forall u, `|y| < u -> \\forall t \\near F, `|f t| < u.\nProof.\nmove=> Fy z zy; near 0^'+ => k; near=> x; have : `|f x - y| < k.\n  by near: x; apply: cvgr_distC_lt => //; near: k; apply: nbhs_right_gt.\nmove=> /(le_lt_trans (ler_dist_dist _ _)) /real_ltr_normlW.\nrewrite realB// ltr_subl_addl => /(_ _)/lt_le_trans; apply => //.\nby rewrite -ler_subr_addl; near: k; apply: nbhs_right_le; rewrite subr_gt0.\nUnshelve. all: by end_near. Qed.\n\nLemma cvgr_norm_le {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y -> forall u, `|y| < u -> \\forall t \\near F, `|f t| <= u.\nProof.\nby move=> fy u yu; near do apply/ltW; apply: cvgr_norm_lt yu.\nUnshelve. all: by end_near. Qed.\n\nLemma cvgr_norm_gt {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y -> forall u, `|y| > u -> \\forall t \\near F, `|f t| > u.\nProof.\nmove=> Fy z zy; near 0^'+ => k; near=> x; have: `|f x - y| < k.\n  by near: x; apply: cvgr_distC_lt => //; near: k; apply: nbhs_right_gt.\nmove=> /(le_lt_trans (ler_dist_dist _ _)); rewrite distrC => /real_ltr_normlW.\nrewrite realB// ltr_subl_addl  -ltr_subl_addr => /(_ isT); apply: le_lt_trans.\nrewrite ler_subr_addl -ler_subr_addr; near: k; apply: nbhs_right_le.\nby rewrite subr_gt0.\nUnshelve. all: by end_near. Qed.\n\nLemma cvgr_norm_ge {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y -> forall u, `|y| > u -> \\forall t \\near F, `|f t| >= u.\nProof.\nby move=> fy u yu; near do apply/ltW; apply: cvgr_norm_gt yu.\nUnshelve. all: by end_near. Qed.\n\nLemma cvgr_neq0 {T} {F : set (set T)} {FF : Filter F} (f : T -> V) (y : V) :\n  f @ F --> y -> y != 0 -> \\forall t \\near F, f t != 0.\nProof.\nmove=> Fy z; near do rewrite -normr_gt0.\nby apply: (@cvgr_norm_gt _ _ _ _ y); rewrite // normr_gt0.\nUnshelve. all: by end_near. Qed.\n\nEnd at_left_right_pmNormedZmod.\nArguments cvgr_norm_lt {R V T F FF f}.\nArguments cvgr_norm_le {R V T F FF f}.\nArguments cvgr_norm_gt {R V T F FF f}.\nArguments cvgr_norm_ge {R V T F FF f}.\nArguments cvgr_neq0 {R V T F FF f}.\n\n#[global] Hint Extern 0 (is_true (`|_ - ?x| < _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: cvgr_dist_lt end : core.\n#[global] Hint Extern 0 (is_true (`|?x - _| < _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: cvgr_distC_lt end : core.\n#[global] Hint Extern 0 (is_true (`|?x| < _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: cvgr0_norm_lt end : core.\n#[global] Hint Extern 0 (is_true (`|_ - ?x| <= _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: cvgr_dist_le end : core.\n#[global] Hint Extern 0 (is_true (`|?x - _| <= _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: cvgr_distC_le end : core.\n#[global] Hint Extern 0 (is_true (`|?x| <= _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: cvgr0_norm_le end : core.\n\n#[global] Hint Extern 0 (is_true (_ < ?x)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_right_gt end : core.\n#[global] Hint Extern 0 (is_true (?x < _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_left_lt end : core.\n#[global] Hint Extern 0 (is_true (?x != _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_right_neq end : core.\n#[global] Hint Extern 0 (is_true (?x != _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_left_neq end : core.\n#[global] Hint Extern 0 (is_true (_ < ?x)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_left_gt end : core.\n#[global] Hint Extern 0 (is_true (?x < _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_right_lt end : core.\n#[global] Hint Extern 0 (is_true (_ <= ?x)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_right_ge end : core.\n#[global] Hint Extern 0 (is_true (?x <= _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_left_le end : core.\n#[global] Hint Extern 0 (is_true (_ <= ?x)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_right_ge end : core.\n#[global] Hint Extern 0 (is_true (?x <= _)) => match goal with\n  H : x \\is_near _ |- _ => near: x; exact: nbhs_left_le end : core.\n\n#[global] Typeclasses Opaque at_left at_right.\nNotation \"x ^'-\" := (at_left x) : classical_set_scope.\nNotation \"x ^'+\" := (at_right x) : classical_set_scope.\n\nSection at_left_rightR.\nVariable (R : numFieldType).\n\nLemma real_cvgr_lt {T} {F : set (set T)} {FF : Filter F} (f : T -> R) (y : R) :\n    y \\is Num.real -> f @ F --> y ->\n  forall z, z > y -> \\forall t \\near F, f t \\is Num.real -> f t < z.\nProof.\nmove=> yr Fy z zy; near=> x => fxr.\nrewrite -(ltr_add2r (- y)) real_ltr_normlW// ?rpredB//.\nby near: x; apply: cvgr_distC_lt => //; rewrite subr_gt0.\nUnshelve. all: by end_near. Qed.\n\nLemma real_cvgr_le {T} {F : set (set T)} {FF : Filter F} (f : T -> R) (y : R) :\n    y \\is Num.real ->  f @ F --> y ->\n  forall z, z > y -> \\forall t \\near F, f t \\is Num.real -> f t <= z.\nProof.\nmove=> /real_cvgr_lt/[apply] + ? z0 => /(_ _ z0).\nby apply: filterS => ? /[apply]/ltW.\nQed.\n\nLemma real_cvgr_gt {T} {F : set (set T)} {FF : Filter F} (f : T -> R) (y : R) :\n    y \\is Num.real -> f @ F --> y ->\n  forall z, y > z -> \\forall t \\near F, f t \\is Num.real -> f t > z.\nProof.\nmove=> yr Fy z zy; near=> x => fxr.\nrewrite -ltr_opp2 -(ltr_add2l y) real_ltr_normlW// ?rpredB//.\nby near: x; apply: cvgr_dist_lt => //; rewrite subr_gt0.\nUnshelve. all: by end_near. Qed.\n\nLemma real_cvgr_ge {T} {F : set (set T)} {FF : Filter F} (f : T -> R) (y : R) :\n    y \\is Num.real -> f @ F --> y ->\n  forall z, z < y -> \\forall t \\near F, f t \\is Num.real -> f t >= z.\nProof.\nmove=> /real_cvgr_gt/[apply] + ? z0 => /(_ _ z0).\nby apply: filterS => ? /[apply]/ltW.\nQed.\n\nEnd at_left_rightR.\nArguments real_cvgr_le {R T F FF f}.\nArguments real_cvgr_lt {R T F FF f}.\nArguments real_cvgr_ge {R T F FF f}.\nArguments real_cvgr_gt {R T F FF f}.\n\nSection realFieldType.\nContext (R : realFieldType).\n\nLemma at_right_in_segment (x : R) (P : set R) :\n  (\\forall e \\near 0^'+, {in `[x - e, x + e], forall x, P x}) <-> (\\near x, P x).\nProof.\nrewrite nbhsr0P -propeqE; apply: eq_near => y /=.\nby rewrite -propeqE; apply: eq_forall => z; rewrite ler_distlC.\nQed.\n\nLemma cvgr_lt {T} {F : set (set T)} {FF : Filter F} (f : T -> R) (y : R) :\n  f @ F --> y -> forall z, z > y -> \\forall t \\near F, f t < z.\nProof.\nmove=> Fy z zy; near=> x; rewrite -(ltr_add2r (- y)) ltr_normlW//.\nby near: x; apply: cvgr_distC_lt => //; rewrite subr_gt0.\nUnshelve. all: by end_near. Qed.\n\nLemma cvgr_le {T} {F : set (set T)} {FF : Filter F} (f : T -> R) (y : R) :\n  f @ F --> y -> forall z, z > y -> \\forall t \\near F, f t <= z.\nProof.\nby move=> /cvgr_lt + ? z0 => /(_ _ z0); apply: filterS => ?; apply/ltW.\nQed.\n\nLemma cvgr_gt {T} {F : set (set T)} {FF : Filter F} (f : T -> R) (y : R) :\n  f @ F --> y -> forall z, y > z -> \\forall t \\near F, f t > z.\nProof.\nmove=> Fy z zy; near=> x; rewrite -ltr_opp2 -(ltr_add2l y) ltr_normlW//.\nby near: x; apply: cvgr_dist_lt => //; rewrite subr_gt0.\nUnshelve. all: by end_near. Qed.\n\nLemma cvgr_ge {T} {F : set (set T)} {FF : Filter F} (f : T -> R) (y : R) :\n  f @ F --> y -> forall z, z < y -> \\forall t \\near F, f t >= z.\nProof.\nby move=> /cvgr_gt + ? z0 => /(_ _ z0); apply: filterS => ?; apply/ltW.\nQed.\n\nEnd realFieldType.\nArguments cvgr_le {R T F FF f}.\nArguments cvgr_lt {R T F FF f}.\nArguments cvgr_ge {R T F FF f}.\nArguments cvgr_gt {R T F FF f}.\n\nDefinition self_sub (K : numDomainType) (V W : normedModType K)\n  (f : V -> W) (x : V * V) : W := f x.1 - f x.2.\nArguments self_sub {K V W} f x /.\n\nDefinition fun1 {T : Type} {K : numFieldType} : T -> K := fun=> 1.\nArguments fun1 {T K} x /.\n\nDefinition dominated_by {T : Type} {K : numDomainType} {V W : pseudoMetricNormedZmodType K}\n  (h : T -> V) (k : K) (f : T -> W) (F : set (set T)) :=\n  F [set x | `|f x| <= k * `|h x|].\n\nDefinition strictly_dominated_by {T : Type} {K : numDomainType} {V W : pseudoMetricNormedZmodType K}\n  (h : T -> V) (k : K) (f : T -> W) (F : set (set T)) :=\n  F [set x | `|f x| < k * `|h x|].\n\nLemma sub_dominatedl (T : Type) (K : numDomainType) (V W : pseudoMetricNormedZmodType K)\n   (h : T -> V) (k : K) (F G : set (set T)) : F `=>` G ->\n  (@dominated_by T K V W h k)^~ G `<=` (dominated_by h k)^~ F.\nProof. by move=> FG f; exact: FG. Qed.\n\nLemma sub_dominatedr (T : Type) (K : numDomainType) (V : pseudoMetricNormedZmodType K)\n    (h : T -> V) (k : K) (f g : T -> V) (F : set (set T)) (FF : Filter F) :\n   (\\forall x \\near F, `|f x| <= `|g x|) ->\n   dominated_by h k g F -> dominated_by h k f F.\nProof. by move=> le_fg; apply: filterS2 le_fg => x; apply: le_trans. Qed.\n\nLemma dominated_by1 {T : Type} {K : numFieldType} {V : pseudoMetricNormedZmodType K} :\n  @dominated_by T K _ V fun1 = fun k f F => F [set x | `|f x| <= k].\nProof.\nrewrite funeq3E => k f F.\nby congr F; rewrite funeqE => x/=; rewrite normr1 mulr1.\nQed.\n\nLemma strictly_dominated_by1 {T : Type} {K : numFieldType}\n    {V : pseudoMetricNormedZmodType K} :\n  @strictly_dominated_by T K _ V fun1 = fun k f F => F [set x | `|f x| < k].\nProof.\nrewrite funeq3E => k f F.\nby congr F; rewrite funeqE => x/=; rewrite normr1 mulr1.\nQed.\n\nLemma ex_dom_bound {T : Type} {K : numFieldType} {V W : pseudoMetricNormedZmodType K}\n    (h : T -> V) (f : T -> W) (F : set (set T)) {PF : ProperFilter F}:\n  (\\forall M \\near +oo, dominated_by h M f F) <->\n  exists M, dominated_by h M f F.\nProof.\nrewrite /dominated_by; split => [/pinfty_ex_gt0[M M_gt0]|[M]] FM.\n  by exists M.\nhave [] := pselect (exists x, (h x != 0) && (`|f x| <= M * `|h x|)); last first.\n  rewrite -forallNE => Nex; exists 0; split => //.\n  move=> k k_gt0; apply: filterS FM => x /= f_le_Mh.\n  have /negP := Nex x; rewrite negb_and negbK f_le_Mh orbF => /eqP h_eq0.\n  by rewrite h_eq0 normr0 !mulr0 in f_le_Mh *.\ncase => x0 /andP[hx0_neq0] /(le_trans (normr_ge0 _)) /ger0_real.\nrewrite realrM // ?normr_eq0// => M_real.\nexists M; split => // k Mk; apply: filterS FM => x /le_trans/= ->//.\nby rewrite ler_wpmul2r// ltW.\nQed.\n\nLemma ex_strict_dom_bound {T : Type} {K : numFieldType}\n    {V W : pseudoMetricNormedZmodType K}\n    (h : T -> V) (f : T -> W) (F : set (set T)) {PF : ProperFilter F} :\n  (\\forall x \\near F, h x != 0) ->\n  (\\forall M \\near +oo, dominated_by h M f F) <->\n   exists M, strictly_dominated_by h M f F.\nProof.\nmove=> hN0; rewrite ex_dom_bound /dominated_by /strictly_dominated_by.\nsplit => -[] M FM; last by exists M; apply: filterS FM => x /ltW.\nexists (M + 1); apply: filterS2 hN0 FM => x hN0 /le_lt_trans/= ->//.\nby rewrite ltr_pmul2r ?normr_gt0// ltr_addl.\nQed.\n\nDefinition bounded_near {T : Type} {K : numFieldType}\n    {V : pseudoMetricNormedZmodType K}\n  (f : T -> V) (F : set (set T)) :=\n  \\forall M \\near +oo, F [set x | `|f x| <= M].\n\nLemma boundedE {T : Type} {K : numFieldType} {V : pseudoMetricNormedZmodType K} :\n  @bounded_near T K V = fun f F => \\forall M \\near +oo, dominated_by fun1 M f F.\nProof. by rewrite dominated_by1. Qed.\n\nLemma sub_boundedr (T : Type) (K : numFieldType) (V : pseudoMetricNormedZmodType K)\n     (F G : set (set T)) : F `=>` G ->\n  (@bounded_near T K V)^~ G `<=` bounded_near^~ F.\nProof. by move=> FG f; rewrite /bounded_near; apply: filterS=> M; apply: FG. Qed.\n\nLemma sub_boundedl (T : Type) (K : numFieldType) (V : pseudoMetricNormedZmodType K)\n     (f g : T -> V) (F : set (set T)) (FF : Filter F) :\n (\\forall x \\near F, `|f x| <= `|g x|) ->  bounded_near g F -> bounded_near f F.\nProof.\nmove=> le_fg; rewrite /bounded_near; apply: filterS => M.\nby apply: filterS2 le_fg => x; apply: le_trans.\nQed.\n\nLemma ex_bound {T : Type} {K : numFieldType} {V : pseudoMetricNormedZmodType K}\n  (f : T -> V) (F : set (set T)) {PF : ProperFilter F}:\n  bounded_near f F <-> exists M, F [set x | `|f x| <= M].\nProof. by rewrite boundedE ex_dom_bound dominated_by1. Qed.\n\nLemma ex_strict_bound {T : Type} {K : numFieldType} {V : pseudoMetricNormedZmodType K}\n  (f : T -> V) (F : set (set T)) {PF : ProperFilter F}:\n  bounded_near f F <-> exists M, F [set x | `|f x| < M].\nProof.\nrewrite boundedE ex_strict_dom_bound ?strictly_dominated_by1//.\nby near=> x; rewrite oner_eq0.\nUnshelve. all: by end_near. Qed.\n\nLemma ex_strict_bound_gt0 {T : Type} {K : numFieldType} {V : pseudoMetricNormedZmodType K}\n  (f : T -> V) (F : set (set T)) {PF : Filter F}:\n  bounded_near f F -> exists2 M, M > 0 & F [set x | `|f x| < M].\nProof.\nmove=> /pinfty_ex_gt0[M M_gt0 FM]; exists (M + 1); rewrite ?addr_gt0//.\nby apply: filterS FM => x /le_lt_trans/= ->//; rewrite ltr_addl.\nQed.\n\nNotation \"[ 'bounded' E | x 'in' A ]\" := (bounded_near (fun x => E) (globally A))\n  (at level 0, x name, format \"[ 'bounded'  E  |  x  'in'  A ]\").\nNotation bounded_set := [set A | [bounded x | x in A]].\nNotation bounded_fun := [set f | [bounded f x | x in setT]].\n\nLemma bounded_fun_has_ubound (T : Type) (R : realFieldType) (a : T -> R) :\n  bounded_fun a -> has_ubound (range a).\nProof.\nmove=> [M [Mreal]]/(_ (`|M| + 1)).\nrewrite (le_lt_trans (ler_norm _)) ?ltr_addl// => /(_ erefl) aM.\nby exists (`|M| + 1) => _ [n _ <-]; rewrite (le_trans (ler_norm _))// aM.\nQed.\n\nLemma bounded_funN (T : Type) (R : realFieldType) (a : T -> R) :\n  bounded_fun a -> bounded_fun (- a).\nProof.\nmove=> [M [Mreal aM]]; rewrite /bounded_fun /bounded_near; near=> x => y /= _.\nby rewrite normrN; apply: aM.\nUnshelve. all: by end_near. Qed.\n\nLemma bounded_fun_has_lbound (T : Type) (R : realFieldType) (a : T -> R) :\n  bounded_fun a -> has_lbound (range a).\nProof.\nmove=> /bounded_funN/bounded_fun_has_ubound ba; apply/has_lb_ubN.\nby apply: subset_has_ubound ba => _ [_ [n _] <- <-]; exists n.\nQed.\n\nLemma bounded_funD (T : Type) (R : realFieldType) (a b : T -> R) :\n  bounded_fun a -> bounded_fun b -> bounded_fun (a \\+ b).\nProof.\nmove=> [M [Mreal Ma]] [N [Nreal Nb]].\nrewrite /bounded_fun/bounded_near; near=> x => y /= _.\nrewrite (le_trans (ler_norm_add _ _))// [x]splitr.\nby rewrite ler_add// (Ma, Nb)// ltr_pdivl_mulr//;\n   near: x; apply: nbhs_pinfty_gt; rewrite ?rpredM ?rpred_nat.\nUnshelve. all: by end_near. Qed.\n\nLemma bounded_locally (T : topologicalType)\n    (R : numFieldType) (V : normedModType R) (A : set T) (f : T -> V) :\n  [bounded f x | x in A] -> [locally [bounded f x | x in A]].\nProof. by move=> /sub_boundedr AB x Ax; apply: AB; apply: within_nbhsW. Qed.\n\nNotation \"k .-lipschitz_on f\" := (dominated_by (self_sub id) k (self_sub f))\n  (at level 2, format \"k .-lipschitz_on  f\") : type_scope.\n\nDefinition sub_klipschitz (K : numFieldType) (V W : normedModType K) (k : K)\n           (f : V -> W) (F G : set (set (V * V))) :\n  F `=>` G -> k.-lipschitz_on f G -> k.-lipschitz_on f F.\nProof. exact. Qed.\n\nDefinition lipschitz_on (K : numFieldType) (V W : normedModType K)\n           (f : V -> W) (F : set (set (V * V))) :=\n  \\forall M \\near +oo, M.-lipschitz_on f F.\n\nDefinition sub_lipschitz (K : numFieldType) (V W : normedModType K)\n           (f : V -> W) (F G : set (set (V * V))) :\n  F `=>` G -> lipschitz_on f G -> lipschitz_on f F.\nProof. by move=> FG; rewrite /lipschitz_on; apply: filterS => M; apply: FG. Qed.\n\nLemma klipschitzW (K : numFieldType) (V W : normedModType K) (k : K)\n      (f : V -> W) (F : set (set (V * V))) {PF : ProperFilter F} :\n  k.-lipschitz_on f F -> lipschitz_on f F.\nProof. by move=> f_lip; apply/ex_dom_bound; exists k. Qed.\n\nNotation \"k .-lipschitz_ A f\" :=\n  (k.-lipschitz_on f (globally (A `*` A)))\n  (at level 2, A at level 0, format \"k .-lipschitz_ A  f\").\nNotation \"k .-lipschitz f\" := (k.-lipschitz_setT f)\n  (at level 2, format \"k .-lipschitz  f\") : type_scope.\nNotation \"[ 'lipschitz' E | x 'in' A ]\" :=\n  (lipschitz_on (fun x => E) (globally (A `*` A)))\n  (at level 0, x name, format \"[ 'lipschitz'  E  |  x  'in'  A ]\").\nNotation lipschitz f := [lipschitz f x | x in setT].\n\nLemma klipschitz_locally (R : numFieldType) (V W : normedModType R)\n   (k : R) (f : V -> W) (A : set V) :\n  k.-lipschitz_A f -> [locally k.-lipschitz_A f].\nProof.\nby move=> bndf x Ax; apply: sub_klipschitz bndf; apply: within_nbhsW.\nQed.\n\nLemma lipschitz_locally (R : numFieldType) (V W : normedModType R)\n    (A : set V) (f : V -> W) :\n  [lipschitz f x | x in A] -> [locally [lipschitz f x | x in A]].\nProof.\nby move=> bndf x Ax; apply: sub_lipschitz bndf; apply: within_nbhsW.\nQed.\n\nLemma lipschitz_id (R : numFieldType) (V : normedModType R) : 1.-lipschitz (@id V).\nProof. by move=> [/= x y] _; rewrite mul1r. Qed.\nArguments lipschitz_id {R V}.\n\nSection contractions.\nContext {R : numDomainType} {X Y : normedModType R} {U : set X} {V : set Y}.\n\nDefinition contraction (q : {nonneg R}) (f : {fun U >-> V}) :=\n  q%:num < 1 /\\ q%:num.-lipschitz_U f.\n\nDefinition is_contraction (f : {fun U >-> V}) := exists q, contraction q f.\n\nEnd contractions.\n\nLemma contraction_fixpoint_unique {R : realDomainType}\n    {X : normedModType R} (U : set X) (f : {fun U >-> U}) (x y : X) :\n  is_contraction f -> U x -> U y -> x = f x -> y = f y -> x = y.\nProof.\ncase => q [q1 ctrfq] Ux Uy fixx fixy; apply/subr0_eq/normr0_eq0/eqP.\nhave [->|xyneq] := eqVneq x y; first by rewrite subrr normr0.\nhave xypos : 0 < `|x - y| by rewrite normr_gt0 subr_eq0.\nsuff : `|x - y| <= q%:num * `|x - y| by rewrite ler_pmull // leNgt q1.\nby rewrite [in leLHS]fixx [in leLHS]fixy; exact: (ctrfq (_, _)).\nQed.\n\nSection PseudoNormedZMod_numFieldType.\nVariables (R : numFieldType) (V : pseudoMetricNormedZmodType R).\n\nLocal Notation ball_norm := (ball_ (@normr R V)).\n\nLocal Notation nbhs_norm := (@nbhs_ball _ V).\n\nLemma norm_hausdorff : hausdorff_space V.\nProof.\nrewrite ball_hausdorff => a b ab.\nhave ab2 : 0 < `|a - b| / 2 by apply divr_gt0 => //; rewrite normr_gt0 subr_eq0.\nset r := PosNum ab2; exists (r, r) => /=.\napply/negPn/negP => /set0P[c] []; rewrite -ball_normE /ball_ => acr bcr.\nhave r22 : r%:num * 2 = r%:num + r%:num.\n  by rewrite (_ : 2 = 1 + 1) // mulrDr mulr1.\nmove: (ltr_add acr bcr); rewrite -r22 (distrC b c).\nmove/(le_lt_trans (ler_dist_add c a b)).\nby rewrite -mulrA mulVr ?mulr1 ?ltxx // unitfE.\nQed.\nHint Extern 0 (hausdorff_space _) => solve[apply: norm_hausdorff] : core.\n\n(* TODO: check if the following lemma are indeed useless *)\n(*       i.e. where the generic lemma is applied, *)\n(*            check that norm_hausdorff is not used in a hard way *)\n\nLemma norm_closeE (x y : V): close x y = (x = y). Proof. exact: closeE. Qed.\nLemma norm_close_eq (x y : V) : close x y -> x = y. Proof. exact: close_eq. Qed.\n\nLemma norm_cvg_unique {F} {FF : ProperFilter F} : is_subset1 [set x : V | F --> x].\nProof. exact: cvg_unique. Qed.\n\nLemma norm_cvg_eq (x y : V) : x --> y -> x = y. Proof. exact: (@cvg_eq V). Qed.\nLemma norm_lim_id (x : V) : lim x = x. Proof. exact: lim_id. Qed.\n\nLemma norm_cvg_lim {F} {FF : ProperFilter F} (l : V) : F --> l -> lim F = l.\nProof. exact: (@cvg_lim V). Qed.\n\nLemma norm_lim_near_cst U {F} {FF : ProperFilter F} (l : V) (f : U -> V) :\n   (\\forall x \\near F, f x = l) -> lim (f @ F) = l.\nProof. exact: lim_near_cst. Qed.\n\nLemma norm_lim_cst U {F} {FF : ProperFilter F} (k : V) :\n   lim ((fun _ : U => k) @ F) = k.\nProof. exact: lim_cst. Qed.\n\nLemma norm_cvgi_unique {U : Type} {F} {FF : ProperFilter F} (f : U -> set V) :\n  {near F, is_fun f} -> is_subset1 [set x : V | f `@ F --> x].\nProof. exact: cvgi_unique. Qed.\n\nLemma norm_cvgi_lim {U} {F} {FF : ProperFilter F} (f : U -> V -> Prop) (l : V) :\n  F (fun x : U => is_subset1 (f x)) ->\n  f `@ F --> l -> lim (f `@ F) = l.\nProof. exact: cvgi_lim. Qed.\n\nLemma distm_lt_split (z x y : V) (e : R) :\n  `|x - z| < e / 2 -> `|z - y| < e / 2 -> `|x - y| < e.\nProof. by have := @ball_split _ _ z x y e; rewrite -ball_normE. Qed.\n\nLemma distm_lt_splitr (z x y : V) (e : R) :\n  `|z - x| < e / 2 -> `|z - y| < e / 2 -> `|x - y| < e.\nProof. by have := @ball_splitr _ _ z x y e; rewrite -ball_normE. Qed.\n\nLemma distm_lt_splitl (z x y : V) (e : R) :\n  `|x - z| < e / 2 -> `|y - z| < e / 2 -> `|x - y| < e.\nProof. by have := @ball_splitl _ _ z x y e; rewrite -ball_normE. Qed.\n\nLemma normm_leW (x : V) (e : R) : e > 0 -> `|x| <= e / 2 -> `|x| < e.\nProof.\nby move=> /posnumP[{}e] /le_lt_trans ->//; rewrite [ltRHS]splitr ltr_spaddl.\nQed.\n\nLemma normm_lt_split (x y : V) (e : R) :\n  `|x| < e / 2 -> `|y| < e / 2 -> `|x + y| < e.\nProof.\nby move=> xlt ylt; rewrite -[y]opprK (@distm_lt_split 0) ?subr0 ?opprK ?add0r.\nQed.\n\nLemma __deprecated__cvg_distW {F : set (set V)} {FF : Filter F} (y : V) :\n  (forall eps, 0 < eps -> \\forall y' \\near F, `|y - y'| <= eps) ->\n  F --> y.\nProof. by move=> /cvgrPdist_le. Qed.\n\nEnd PseudoNormedZMod_numFieldType.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"use `cvgrPdist_le` or a variation instead\")]\nNotation cvg_distW := __deprecated__cvg_distW.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"renamed to `norm_cvgi_lim`\")]\nNotation norm_cvgi_map_lim := norm_cvgi_lim.\n\nSection NormedModule_numFieldType.\nVariables (R : numFieldType) (V : normedModType R).\n\nSection cvgr_norm_infty.\nVariables (I : Type) (F : set (set I)) (FF : Filter F) (f : I -> V) (y : V).\n\nLemma cvgr_norm_lty :\n  f @ F --> y -> \\forall M \\near +oo, \\forall y' \\near F, `|f y'| < M.\nProof. by move=> Fy; near do exact: (cvgr_norm_lt y).\nUnshelve. all: by end_near. Qed.\n\nLemma cvgr_norm_ley :\n  f @ F --> y -> \\forall M \\near +oo, \\forall y' \\near F, `|f y'| <= M.\nProof.\nby move=> Fy; near do exact: (cvgr_norm_le y).\nUnshelve. all: by end_near. Qed.\n\nLemma cvgr_norm_gtNy :\n  f @ F --> y -> \\forall M \\near -oo, \\forall y' \\near F, `|f y'| > M.\nProof.\nby move=> Fy; near do exact: (cvgr_norm_gt y).\nUnshelve. all: by end_near. Qed.\n\nLemma cvgr_norm_geNy :\n  f @ F --> y -> \\forall M \\near -oo, \\forall y' \\near F, `|f y'| >= M.\nProof.\nby move=> Fy; near do exact: (cvgr_norm_ge y).\nUnshelve. all: by end_near. Qed.\n\nEnd cvgr_norm_infty.\n\nLemma __deprecated__cvg_bounded_real {F : set (set V)} {FF : Filter F} (y : V) :\n  F --> y -> \\forall M \\near +oo, \\forall y' \\near F, `|y'| < M.\nProof. exact: cvgr_norm_lty. Qed.\n\nLemma cvg_bounded {I} {F : set (set I)} {FF : Filter F} (f : I -> V) (y : V) :\n  f @ F --> y -> bounded_near f F.\nProof. exact: cvgr_norm_ley. Qed.\n\nEnd NormedModule_numFieldType.\nArguments cvgr_norm_lty {R V I F FF}.\nArguments cvgr_norm_ley {R V I F FF}.\nArguments cvgr_norm_gtNy {R V I F FF}.\nArguments cvgr_norm_geNy {R V I F FF}.\nArguments cvg_bounded {R V I F FF}.\n#[global]\nHint Extern 0 (hausdorff_space _) => solve[apply: norm_hausdorff] : core.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"use `cvgr_norm_lty` or a variation instead\")]\nNotation cvg_bounded_real := __deprecated__cvg_bounded_real.\n\nModule Export NbhsNorm.\nDefinition nbhs_simpl := (nbhs_simpl,@nbhs_nbhs_norm,@filter_from_norm_nbhs).\nEnd NbhsNorm.\n\n(* TODO: generalize to R : numFieldType *)\nSection hausdorff.\n\nLemma Rhausdorff (R : realFieldType) : hausdorff_space R.\nProof.\nmove=> x y clxy; apply/eqP; rewrite eq_le.\napply/in_segment_addgt0Pr => _ /posnumP[e].\nrewrite in_itv /= -ler_distl; set he := (e%:num / 2)%:pos.\nhave [z [zx_he yz_he]] := clxy _ _ (nbhsx_ballx x he) (nbhsx_ballx y he).\nhave := ball_triangle yz_he (ball_sym zx_he).\nby rewrite -mulr2n -mulr_natr divfK // => /ltW.\nQed.\n\nLemma pseudoMetricNormedZModType_hausdorff (R : realFieldType)\n    (V : pseudoMetricNormedZmodType R) :\n  hausdorff_space V.\nProof.\nmove=> p q clp_q; apply/subr0_eq/normr0_eq0/Rhausdorff => A B pq_A.\nrewrite -(@normr0 _ V) -(subrr p) => pp_B.\nsuff loc_preim r C : nbhs`|p - r| C ->\n    nbhs r ((fun r => `|p - r|) @^-1` C).\n  have [r []] := clp_q _ _ (loc_preim _ _ pp_B) (loc_preim _ _ pq_A).\n  by exists `|p - r|.\nmove=> [e egt0 pre_C]; apply: nbhs_le_nbhs_norm; exists e => //= s /= rse.\napply: pre_C; apply: le_lt_trans (ler_dist_dist _ _) _.\nby rewrite opprB addrC subrKA distrC.\nQed.\n\nEnd hausdorff.\n\nModule Export NearNorm.\nDefinition near_simpl := (@near_simpl, @nbhs_normE, @filter_from_normE,\n  @near_nbhs_norm).\nLtac near_simpl := rewrite ?near_simpl.\nEnd NearNorm.\n\nLemma __deprecated__continuous_cvg_dist {R : numFieldType}\n  (V W : pseudoMetricNormedZmodType R) (f : V -> W) x l :\n  continuous f -> x --> l -> forall e : {posnum R}, `|f l - f x| < e%:num.\nProof. by move=> cf /cvg_eq->// e; rewrite subrr normr0. Qed.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"simply use the fact that `(x --> l) -> (x = l)`\")]\nNotation continuous_cvg_dist := __deprecated__continuous_cvg_dist.\n\n(** ** Matrices *)\n\nSection mx_norm.\nVariables (K : numDomainType) (m n : nat).\nImplicit Types x y : 'M[K]_(m, n).\n\nDefinition mx_norm x : K := (\\big[maxr/0%:nng]_i `|x i.1 i.2|%:nng)%:num.\n\nLemma mx_normE x : mx_norm x = (\\big[maxr/0%:nng]_i `|x i.1 i.2|%:nng)%:num.\nProof. by []. Qed.\n\nLemma ler_mx_norm_add x y : mx_norm (x + y) <= mx_norm x + mx_norm y.\nProof.\nrewrite !mx_normE [_ <= _%:num]num_le; apply/bigmax_leP.\nsplit=> [|ij _]; first exact: addr_ge0.\nrewrite mxE; apply: le_trans (ler_norm_add _ _) _.\nby rewrite ler_add// -[leLHS]nngE num_le; exact: le_bigmax.\nQed.\n\nLemma mx_norm_eq0 x : mx_norm x = 0 -> x = 0.\nProof.\nmove/eqP; rewrite eq_le -[0]nngE mx_normE num_le => /andP[/bigmax_leP[_ x0] _].\napply/matrixP => i j; rewrite mxE; apply/eqP.\nby rewrite -num_abs_eq0 eq_le (x0 (i, j))//= -num_le/=.\nQed.\n\nLemma mx_norm0 : mx_norm 0 = 0.\nProof.\nrewrite /mx_norm (eq_bigr (fun=> 0%R%:nng)) /=.\n  by elim/big_ind : _ => // a b; rewrite num_max => -> ->; rewrite maxxx.\nby move=> i _; apply val_inj => /=; rewrite mxE normr0.\nQed.\n\nLemma mx_norm_neq0 x : mx_norm x != 0 -> exists i, mx_norm x = `|x i.1 i.2|.\nProof.\nrewrite /mx_norm.\nelim/big_ind : _ => [|a b Ha Hb H|/= i _ _]; [by rewrite eqxx| |by exists i].\ncase: (leP a b) => ab.\n+ suff /Hb[i xi] : b%:num != 0 by exists i.\n  by apply: contra H => b0; rewrite max_r.\n+ suff /Ha[i xi] : a%:num != 0 by exists i.\n  by apply: contra H => a0; rewrite max_l // ltW.\nQed.\n\nLemma mx_norm_natmul x k : mx_norm (x *+ k) = (mx_norm x) *+ k.\nProof.\nrewrite [in RHS]/mx_norm; elim: k => [|k ih]; first by rewrite !mulr0n mx_norm0.\nrewrite !mulrS; apply/eqP; rewrite eq_le; apply/andP; split.\n  by rewrite -ih; exact/ler_mx_norm_add.\nhave [/mx_norm_eq0->|x0] := eqVneq (mx_norm x) 0.\n  by rewrite -/(mx_norm 0) -/(mx_norm 0) !(mul0rn,addr0,mx_norm0).\nrewrite -/(mx_norm x) -num_abs_le; last by rewrite mx_normE.\napply/bigmax_geP; right => /=.\nhave [i Hi] := mx_norm_neq0 x0.\nexists i => //; rewrite Hi -!mulrS -normrMn mulmxnE.\nby rewrite le_eqVlt; apply/orP; left; apply/eqP/val_inj => /=; rewrite normr_id.\nQed.\n\nLemma mx_normN x : mx_norm (- x) = mx_norm x.\nProof.\ncongr (_%:nngnum).\nby apply eq_bigr => /= ? _; apply/eqP; rewrite mxE -num_eq //= normrN.\nQed.\n\nEnd mx_norm.\n\nLemma mx_normrE (K : realDomainType) (m n : nat) (x : 'M[K]_(m, n)) :\n  mx_norm x = \\big[maxr/0]_ij `|x ij.1 ij.2|.\nProof.\nrewrite /mx_norm; apply/esym.\nelim/big_ind2 : _ => //= a a' b b' ->{a'} ->{b'}.\nby have [ab|ab] := leP a b; [rewrite max_r | rewrite max_l // ltW].\nQed.\n\nDefinition matrix_normedZmodMixin (K : numDomainType) (m n : nat) :=\n  @Num.NormedMixin _ _ _ (@mx_norm K m.+1 n.+1) (@ler_mx_norm_add _ _ _)\n    (@mx_norm_eq0 _ _ _) (@mx_norm_natmul _ _ _) (@mx_normN _ _ _).\n\nCanonical matrix_normedZmodType (K : numDomainType) (m n : nat) :=\n  NormedZmodType K 'M[K]_(m.+1, n.+1) (matrix_normedZmodMixin K m n).\n\nSection matrix_NormedModule.\nVariables (K : numFieldType) (m n : nat).\n\nLocal Lemma ball_gt0 (x y : 'M[K]_(m.+1, n.+1)) e : ball x e y -> 0 < e.\nProof. by move/(_ ord0 ord0); apply: le_lt_trans. Qed.\n\nLemma mx_norm_ball :\n  @ball _ [pseudoMetricType K of 'M[K]_(m.+1, n.+1)] = ball_ (fun x => `| x |).\nProof.\nrewrite /normr /ball_ predeq3E => x e y /=; rewrite mx_normE; split => xey.\n- have e_gt0 : 0 < e := ball_gt0 xey.\n  move: e_gt0 (e_gt0) xey => /ltW/nonnegP[{}e] e_gt0 xey.\n  rewrite num_lt; apply/bigmax_ltP => /=.\n  by rewrite -num_lt /=; split => // -[? ?] _; rewrite !mxE; exact: xey.\n- have e_gt0 : 0 < e by rewrite (le_lt_trans _ xey).\n  move: e_gt0 (e_gt0) xey => /ltW/nonnegP[{}e] e_gt0.\n  move=> /(bigmax_ltP _ _ _ (fun _ => _%:sgn)) /= [e0 xey] i j.\n  by move: (xey (i, j)); rewrite !mxE; exact.\nQed.\n\nDefinition matrix_PseudoMetricNormedZmodMixin :=\n  PseudoMetricNormedZmodule.Mixin mx_norm_ball.\nCanonical matrix_pseudoMetricNormedZmodType :=\n  PseudoMetricNormedZmodType K 'M[K]_(m.+1, n.+1) matrix_PseudoMetricNormedZmodMixin.\n\nLemma mx_normZ (l : K) (x : 'M[K]_(m.+1, n.+1)) : `| l *: x | = `| l | * `| x |.\nProof.\nrewrite {1 3}/normr /= !mx_normE\n (eq_bigr (fun i => (`|l| * `|x i.1 i.2|)%:nng)); last first.\n  by move=> i _; rewrite mxE //=; apply/eqP; rewrite -num_eq /= normrM.\nelim/big_ind2 : _ => // [|a b c d bE dE]; first by rewrite mulr0.\nby rewrite !num_max bE dE maxr_pmulr.\nQed.\n\nDefinition matrix_NormedModMixin := NormedModMixin mx_normZ.\nCanonical matrix_normedModType :=\n  NormedModType K 'M[K]_(m.+1, n.+1) matrix_NormedModMixin.\n\nEnd matrix_NormedModule.\n\n(** ** Pairs *)\n\nSection prod_PseudoMetricNormedZmodule.\nContext {K : numDomainType} {U V : pseudoMetricNormedZmodType K}.\n\nLemma ball_prod_normE : ball = ball_ (fun x => `| x : U * V |).\nProof.\nrewrite funeq2E => - [xu xv] e; rewrite predeqE => - [yu yv].\nrewrite /ball /= /prod_ball -!ball_normE /ball_ /=.\nby rewrite comparable_lt_maxl// ?real_comparable//; split=> /andP.\nQed.\n\nLemma prod_norm_ball : @ball _ [pseudoMetricType K of U * V] = ball_ (fun x => `|x|).\nProof. by rewrite /= - ball_prod_normE. Qed.\n\nDefinition prod_pseudoMetricNormedZmodMixin :=\n  PseudoMetricNormedZmodule.Mixin prod_norm_ball.\nCanonical prod_pseudoMetricNormedZmodType :=\n  PseudoMetricNormedZmodType K (U * V) prod_pseudoMetricNormedZmodMixin.\n\nEnd prod_PseudoMetricNormedZmodule.\n\nSection prod_NormedModule.\nContext {K : numDomainType} {U V : normedModType K}.\n\nLemma prod_norm_scale (l : K) (x : U * V) : `| l *: x | = `|l| * `| x |.\nProof. by rewrite prod_normE /= !normrZ maxr_pmulr. Qed.\n\nDefinition prod_NormedModMixin := NormedModMixin prod_norm_scale.\nCanonical prod_normedModType :=\n  NormedModType K (U * V) prod_NormedModMixin.\n\nEnd prod_NormedModule.\n\nSection example_of_sharing.\nVariables (K : numDomainType).\n\nExample matrix_triangke m n (M N : 'M[K]_(m.+1, n.+1)) :\n  `|M + N| <= `|M| + `|N|.\nProof. apply ler_norm_add. Qed.\n\nExample pair_triangle (x y : K * K) : `|x + y| <= `|x| + `|y|.\nProof. apply ler_norm_add. Qed.\n\nEnd example_of_sharing.\n\nSection prod_NormedModule_lemmas.\n\nContext {T : Type} {K : numDomainType} {U V : normedModType K}.\n\nLemma fcvgr2dist_ltP {F : set (set U)} {G : set (set V)}\n  {FF : Filter F} {FG : Filter G} (y : U) (z : V) :\n  (F, G) --> (y, z) <->\n  forall eps, 0 < eps ->\n   \\forall y' \\near F & z' \\near G, `| (y, z) - (y', z') | < eps.\nProof. exact: fcvgrPdist_lt. Qed.\n\nLemma cvgr2dist_ltP {I J} {F : set (set I)} {G : set (set J)}\n  {FF : Filter F} {FG : Filter G} (f : I -> U) (g : J -> V) (y : U) (z : V) :\n  (f @ F, g @ G) --> (y, z) <->\n  forall eps, 0 < eps ->\n   \\forall i \\near F & j \\near G, `| (y, z) - (f i, g j) | < eps.\nProof.\nrewrite fcvgr2dist_ltP; split=> + e e0 => /(_ e e0);\n  by rewrite !near_simpl// => ?; rewrite !near_simpl.\nQed.\n\nLemma cvgr2dist_lt {I J} {F : set (set I)} {G : set (set J)}\n  {FF : Filter F} {FG : Filter G} (f : I -> U) (g : J -> V) (y : U) (z : V) :\n  (f @ F, g @ G) --> (y, z) ->\n  forall eps, 0 < eps ->\n   \\forall i \\near F & j \\near G, `| (y, z) - (f i, g j) | < eps.\nProof. by rewrite cvgr2dist_ltP. Qed.\n\nLemma __deprecated__cvg_dist2 {F : set (set U)} {G : set (set V)}\n  {FF : Filter F} {FG : Filter G} (y : U) (z : V):\n  (F, G) --> (y, z) ->\n  forall eps, 0 < eps ->\n   \\forall y' \\near F & z' \\near G, `|(y, z) - (y', z')| < eps.\nProof. exact: cvgr2dist_lt. Qed.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\nnote=\"use `cvgr2dist_lt` or a variant instead\")]\nNotation cvg_dist2 := __deprecated__cvg_dist2.\n\nEnd prod_NormedModule_lemmas.\nArguments cvgr2dist_ltP {_ _ _ _ _ F G FF FG}.\nArguments cvgr2dist_lt {_ _ _ _ _ F G FF FG}.\n\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\nnote=\"use `fcvgr2dist_ltP` or a variant instead\")]\nNotation cvg_dist2P := fcvgr2dist_ltP.\n\n(** Normed vector spaces have some continuous functions *)\n(** that are in fact continuous on pseudoMetricNormedZmodType *)\nSection NVS_continuity_pseudoMetricNormedZmodType.\nContext {K : numFieldType} {V : pseudoMetricNormedZmodType K}.\n\nLemma opp_continuous : continuous (@GRing.opp V).\nProof.\nmove=> x; apply/cvgrPdist_lt=> e e0; near do rewrite -opprD normrN.\nexact: cvgr_dist_lt.\nUnshelve. all: by end_near. Qed.\n\nLemma add_continuous : continuous (fun z : V * V => z.1 + z.2).\nProof.\nmove=> [/= x y]; apply/cvgrPdist_lt=> _/posnumP[e]; near=> a b => /=.\nby rewrite opprD addrACA normm_lt_split.\nUnshelve. all: by end_near. Qed.\n\nLemma natmul_continuous n : continuous (fun x : V => x *+ n).\nProof.\ncase: n => [|n] x; first exact: cvg_cst.\napply/cvgrPdist_lt=> _/posnumP[e]; near=> a.\nby rewrite -mulrnBl normrMn -mulr_natr -ltr_pdivl_mulr.\nUnshelve. all: by end_near. Qed.\n\nLemma norm_continuous : continuous (normr : V -> K).\nProof.\nmove=> x; apply/cvgrPdist_lt => e e0; apply/nbhs_normP; exists e => //= y.\nexact/le_lt_trans/ler_dist_dist.\nQed.\n\nEnd NVS_continuity_pseudoMetricNormedZmodType.\n\nSection NVS_continuity_normedModType.\nContext {K : numFieldType} {V : normedModType K}.\n\nLemma scale_continuous : continuous (fun z : K * V => z.1 *: z.2).\nProof.\nmove=> [/= k x]; apply/cvgrPdist_lt => _/posnumP[e]; near +oo_K => M.\nnear=> l z => /=; have M0 : 0 < M by [].\nrewrite (@distm_lt_split _ _ (k *: z)) // -?(scalerBr, scalerBl) normrZ.\n  rewrite (@le_lt_trans _ _ (M * `|x - z|)) ?ler_wpmul2r -?ltr_pdivl_mull//.\n  by near: z; apply: cvgr_dist_lt; rewrite // mulr_gt0 ?invr_gt0.\nrewrite (@le_lt_trans _ _ (`|k - l| * M)) ?ler_wpmul2l -?ltr_pdivl_mulr//.\n  by near: z; near: M; apply: cvg_bounded (@cvg_refl _ _).\nby near: l; apply: cvgr_dist_lt; rewrite // divr_gt0.\nUnshelve. all: by end_near. Qed.\n\nArguments scale_continuous _ _ : clear implicits.\n\nLemma scaler_continuous k : continuous (fun x : V => k *: x).\nProof.\nby move=> x; apply: (cvg_comp2 (cvg_cst _) cvg_id (scale_continuous (_, _))).\nQed.\n\nLemma scalel_continuous (x : V) : continuous (fun k : K => k *: x).\nProof.\nby move=> k; apply: (cvg_comp2 cvg_id (cvg_cst _) (scale_continuous (_, _))).\nQed.\n\n(** Continuity of norm *)\nEnd NVS_continuity_normedModType.\n\nSection NVS_continuity_mul.\n\nContext {K : numFieldType}.\n\nLemma mul_continuous : continuous (fun z : K * K => z.1 * z.2).\nProof. exact: scale_continuous. Qed.\n\nLemma mulrl_continuous (x : K) : continuous ( *%R x).\nProof. exact: scaler_continuous. Qed.\n\nLemma mulrr_continuous (y : K) : continuous ( *%R^~ y).\nProof. exact: scalel_continuous. Qed.\n\nLemma inv_continuous (x : K) : x != 0 -> {for x, continuous GRing.inv}.\nProof.\nmove=> x_neq0; have nx_gt0 : `|x| > 0 by rewrite normr_gt0.\napply/(@cvgrPdist_ltp _ _ _ (nbhs x)); near (0 : K)^'+ => d. near=> e.\nnear=> y; have y_neq0 : y != 0 by near: y; apply: (cvgr_neq0 x).\nrewrite /= -div1r -[y^-1]div1r -mulNr addf_div// mul1r mulN1r normrM normfV.\nrewrite ltr_pdivr_mulr ?normr_gt0 ?mulf_neq0// (@lt_le_trans _ _ (e * d))//.\n  by near: y;  apply: cvgr_distC_lt => //; rewrite mulr_gt0.\nrewrite ler_pmul2l => //=; rewrite normrM -ler_pdivr_mull//.\nnear: y; apply: (cvgr_norm_ge x) => //; rewrite ltr_pdivr_mull//.\nby near: d; apply: nbhs_right_lt; rewrite mulr_gt0.\nUnshelve. all: by end_near. Qed.\n\nEnd NVS_continuity_mul.\n\nSection cvg_composition_pseudometric.\n\nContext {K : numFieldType} {V : pseudoMetricNormedZmodType K} {T : Type}.\nContext (F : set (set T)) {FF : Filter F}.\nImplicit Types (f g : T -> V) (s : T -> K) (k : K) (x : T) (a b : V).\n\nLemma cvgN f a : f @ F --> a -> - f @ F --> - a.\nProof. by move=> ?; apply: continuous_cvg => //; exact: opp_continuous. Qed.\n\nLemma cvgNP f a : - f @ F --> - a <-> f @ F --> a.\nProof. by split=> /cvgN//; rewrite !opprK. Qed.\n\nLemma is_cvgN f : cvg (f @ F) -> cvg (- f @ F).\nProof. by move=> /cvgN /cvgP. Qed.\n\nLemma is_cvgNE f : cvg ((- f) @ F) = cvg (f @ F).\nProof. by rewrite propeqE; split=> /cvgN; rewrite ?opprK => /cvgP. Qed.\n\nLemma cvgMn f n a : f @ F --> a -> ((@GRing.natmul _)^~n \\o f) @ F --> a *+ n.\nProof. by move=> ?;  apply: continuous_cvg => //; exact: natmul_continuous. Qed.\n\nLemma is_cvgMn f n : cvg (f @ F) -> cvg (((@GRing.natmul _)^~n \\o f) @ F).\nProof. by move=> /cvgMn /cvgP. Qed.\n\nLemma cvgD f g a b : f @ F --> a -> g @ F --> b -> (f + g) @ F --> a + b.\nProof. by move=> ? ?; apply: continuous2_cvg => //; exact: add_continuous. Qed.\n\nLemma is_cvgD f g : cvg (f @ F) -> cvg (g @ F) -> cvg (f + g @ F).\nProof. by have := cvgP _ (cvgD _ _); apply. Qed.\n\nLemma cvgB f g a b : f @ F --> a -> g @ F --> b -> (f - g) @ F --> a - b.\nProof. by move=> ? ?; apply: cvgD => //; apply: cvgN. Qed.\n\nLemma is_cvgB f g : cvg (f @ F) -> cvg (g @ F) -> cvg (f - g @ F).\nProof. by have := cvgP _ (cvgB _ _); apply. Qed.\n\nLemma is_cvgDlE f g : cvg (g @ F) -> cvg ((f + g) @ F) = cvg (f @ F).\nProof.\nmove=> g_cvg; rewrite propeqE; split; last by move=> /is_cvgD; apply.\nby move=> /is_cvgB /(_ g_cvg); rewrite addrK.\nQed.\n\nLemma is_cvgDrE f g : cvg (f @ F) -> cvg ((f + g) @ F) = cvg (g @ F).\nProof. by rewrite addrC; apply: is_cvgDlE. Qed.\n\nLemma cvg_sub0 f g a : (f - g) @ F --> (0 : V) -> g @ F --> a -> f @ F --> a.\nProof.\nby move=> Cfg Cg; have := cvgD Cfg Cg; rewrite subrK add0r; apply.\nQed.\n\nLemma cvg_zero f a : (f - cst a) @ F --> (0 : V) -> f @ F --> a.\nProof. by move=> Cfa; apply: cvg_sub0 Cfa (cvg_cst _). Qed.\n\nLemma cvg_norm f a : f @ F --> a -> `|f x| @[x --> F] --> (`|a| : K).\nProof. by apply: continuous_cvg; apply: norm_continuous. Qed.\n\nLemma is_cvg_norm f : cvg (f @ F) -> cvg ((Num.norm \\o f : T -> K) @ F).\nProof. by have := cvgP _ (cvg_norm _); apply. Qed.\n\nLemma norm_cvg0P f : `|f x| @[x --> F] --> 0 <-> f @ F --> 0.\nProof.\nsplit; last by move=> /cvg_norm; rewrite normr0.\nmove=> f0; apply/cvgr0Pnorm_lt => e e_gt0.\nby near do rewrite -normr_id; apply: cvgr0_norm_lt.\nUnshelve. all: by end_near. Qed.\n\nLemma norm_cvg0 f : `|f x| @[x --> F] --> 0 -> f @ F --> 0.\nProof. by rewrite norm_cvg0P. Qed.\n\nEnd cvg_composition_pseudometric.\n\nLemma __deprecated__cvg_dist0 {U} {K : numFieldType} {V : normedModType K}\n  {F : set (set U)} {FF : Filter F} (f : U -> V) :\n  (fun x => `|f x|) @ F --> (0 : K)\n  -> f @ F --> (0 : V).\nProof. exact: norm_cvg0. Qed.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n note=\"renamed to `norm_cvg0` and generalized to `pseudoMetricNormedZmodType`\")]\nNotation cvg_dist0 := __deprecated__cvg_dist0.\n\nSection cvg_composition_normed.\nContext {K : numFieldType} {V : normedModType K} {T : Type}.\nContext (F : set (set T)) {FF : Filter F}.\nImplicit Types (f g : T -> V) (s : T -> K) (k : K) (x : T) (a b : V).\n\nLemma cvgZ s f k a : s @ F --> k -> f @ F --> a ->\n                     s x *: f x @[x --> F] --> k *: a.\nProof. move=> ? ?; apply: continuous2_cvg => //; exact: scale_continuous. Qed.\n\nLemma is_cvgZ s f : cvg (s @ F) ->\n  cvg (f @ F) -> cvg ((fun x => s x *: f x) @ F).\nProof. by have := cvgP _ (cvgZ _ _); apply. Qed.\n\nLemma cvgZl s k a : s @ F --> k -> s x *: a @[x --> F] --> k *: a.\nProof. by move=> ?; apply: cvgZ => //; exact: cvg_cst. Qed.\n\nLemma is_cvgZl s a : cvg (s @ F) -> cvg ((fun x => s x *: a) @ F).\nProof. by have := cvgP _ (cvgZl  _); apply. Qed.\n\nLemma cvgZr k f a : f @ F --> a -> k \\*: f @ F --> k *: a.\nProof. apply: cvgZ => //; exact: cvg_cst. Qed.\n\nLemma is_cvgZr k f : cvg (f @ F) -> cvg (k *: f  @ F).\nProof. by have := cvgP _ (cvgZr  _); apply. Qed.\n\nLemma is_cvgZrE k f : k != 0 -> cvg (k *: f @ F) = cvg (f @ F).\nProof.\nmove=> k_neq0; rewrite propeqE; split => [/(@cvgZr k^-1)|/(@cvgZr k)/cvgP//].\nby under [_ \\*: _]funext => x /= do rewrite scalerK//; apply: cvgP.\nQed.\n\nEnd cvg_composition_normed.\n\nSection cvg_composition_field.\nContext {K : numFieldType}  {T : Type}.\nContext (F : set (set T)) {FF : Filter F}.\nImplicit Types (f g : T -> K) (a b : K).\n\nLemma cvgV f a : a != 0 -> f @ F --> a -> f\\^-1 @ F --> a^-1.\nProof.\nby move=> k_neq0 f_cvg; apply: continuous_cvg => //; apply: inv_continuous.\nQed.\n\nLemma cvgVP f a : a != 0 -> f\\^-1 @ F --> a^-1 <-> f @ F --> a.\nProof.\nmove=> aN0; split=> /(cvgV _); last exact.\nby rewrite invrK invr_eq0 inv_funK; apply.\nQed.\n\nLemma is_cvgV f : lim (f @ F) != 0 -> cvg (f @ F) -> cvg (f\\^-1 @ F).\nProof. by move=> /cvgV cvf /cvf /cvgP. Qed.\n\nLemma cvgM f g a b : f @ F --> a -> g @ F --> b -> (f \\* g) @ F --> a * b.\nProof. exact: cvgZ. Qed.\n\nLemma cvgMl f a b : f @ F --> a -> (f x * b) @[x --> F] --> a * b.\nProof. exact: cvgZl. Qed.\n\nLemma cvgMr g a b : g @ F --> b -> (a * g x) @[x --> F] --> a * b.\nProof. exact: cvgZr. Qed.\n\nLemma is_cvgM f g : cvg (f @ F) -> cvg (g @ F) -> cvg (f \\* g @ F).\nProof. exact: is_cvgZ. Qed.\n\nLemma is_cvgMr g a (f := fun=> a) : cvg (g @ F) -> cvg (f \\* g @ F).\nProof. exact: is_cvgZr. Qed.\n\nLemma is_cvgMrE g a (f := fun=> a) : a != 0 -> cvg (f \\* g @ F) = cvg (g @ F).\nProof. exact: is_cvgZrE. Qed.\n\nLemma is_cvgMl f a (g := fun=> a) : cvg (f @ F) -> cvg (f \\* g @ F).\nProof.\nmove=> f_cvg; have -> : f \\* g = g \\* f by apply/funeqP=> x; rewrite /= mulrC.\nexact: is_cvgMr.\nQed.\n\nLemma is_cvgMlE f a (g := fun=> a) : a != 0 -> cvg (f \\* g @ F) = cvg (f @ F).\nProof.\nmove=> a_neq0; have -> : f \\* g = g \\* f by apply/funeqP=> x; rewrite /= mulrC.\nexact: is_cvgMrE.\nQed.\n\nEnd cvg_composition_field.\n\nSection limit_composition_pseudometric.\n\nContext {K : numFieldType} {V : pseudoMetricNormedZmodType K} {T : Type}.\nContext (F : set (set T)) {FF : ProperFilter F}.\nImplicit Types (f g : T -> V) (s : T -> K) (k : K) (x : T) (a : V).\n\nLemma limN f : cvg (f @ F) -> lim (- f @ F) = - lim (f @ F).\nProof. by move=> ?; apply: cvg_lim => //; apply: cvgN. Qed.\n\nLemma limD f g : cvg (f @ F) -> cvg (g @ F) ->\n   lim (f + g @ F) = lim (f @ F) + lim (g @ F).\nProof. by move=> ? ?; apply: cvg_lim => //; apply: cvgD. Qed.\n\nLemma limB f g : cvg (f @ F) -> cvg (g @ F) ->\n   lim (f - g @ F) = lim (f @ F) - lim (g @ F).\nProof. by move=> ? ?; apply: cvg_lim => //; apply: cvgB. Qed.\n\nLemma lim_norm f : cvg (f @ F) -> lim ((fun x => `|f x| : K) @ F) = `|lim (f @ F)|.\nProof. by move=> ?; apply: cvg_lim => //; apply: cvg_norm. Qed.\n\nEnd limit_composition_pseudometric.\n\nSection limit_composition_normed.\n\nContext {K : numFieldType} {V : normedModType K} {T : Type}.\nContext (F : set (set T)) {FF : ProperFilter F}.\nImplicit Types (f g : T -> V) (s : T -> K) (k : K) (x : T) (a : V).\n\nLemma limZ s f : cvg (s @ F) -> cvg (f @ F) ->\n   lim ((fun x => s x *: f x) @ F) = lim (s @ F) *: lim (f @ F).\nProof. by move=> ? ?; apply: cvg_lim => //; apply: cvgZ. Qed.\n\nLemma limZl s a : cvg (s @ F) ->\n   lim ((fun x => s x *: a) @ F) = lim (s @ F) *: a.\nProof. by move=> ?; apply: cvg_lim => //; apply: cvgZl. Qed.\n\nLemma limZr k f : cvg (f @ F) -> lim (k *: f @ F) = k *: lim (f @ F).\nProof. by move=> ?; apply: cvg_lim => //; apply: cvgZr. Qed.\n\nEnd limit_composition_normed.\n\nSection limit_composition_field.\n\nContext {K : numFieldType} {T : Type}.\nContext (F : set (set T)) {FF : ProperFilter F}.\nImplicit Types (f g : T -> K).\n\nLemma limM f g : cvg (f @ F) -> cvg (g @ F) ->\n   lim (f \\* g @ F) = lim (f @ F) * lim (g @ F).\nProof. by move=> ? ?; apply: cvg_lim => //; apply: cvgM. Qed.\n\nEnd limit_composition_field.\n\nSection cvg_composition_field_proper.\n\nContext {K : numFieldType}  {T : Type}.\nContext (F : set (set T)) {FF : ProperFilter F}.\nImplicit Types (f g : T -> K) (a b : K).\n\nLemma limV f : lim (f @ F) != 0 -> lim (f\\^-1 @ F) = (lim (f @ F))^-1.\nProof.\nby move=> ?; apply: cvg_lim => //; apply: cvgV => //; apply: cvgNpoint.\nQed.\n\nLemma is_cvgVE f : lim (f @ F) != 0 -> cvg (f\\^-1 @ F) = cvg (f @ F).\nProof.\nmove=> ?; apply/propeqP; split=> /is_cvgV; last exact.\nby rewrite inv_funK; apply; rewrite limV ?invr_eq0//.\nQed.\n\nEnd cvg_composition_field_proper.\n\nSection ProperFilterRealType.\nContext {T : Type} {F : set (set T)} {FF : ProperFilter F} {R : realFieldType}.\nImplicit Types (f g h : T -> R) (a b : R).\n\nLemma cvgr_to_ge f a b : f @ F --> a -> (\\near F, b <= f F) -> b <= a.\nProof. by move=> /[swap]/(closed_cvg _ (@closed_ge _ b))/[apply]. Qed.\n\nLemma cvgr_to_le f a b : f @ F --> a -> (\\near F, f F <= b) -> a <= b.\nProof. by move=> /[swap]/(closed_cvg _ (@closed_le _ b))/[apply]. Qed.\n\nLemma limr_ge x f : cvg (f @ F) -> (\\near F, x <= f F) -> x <= lim (f @ F).\nProof. exact: cvgr_to_ge. Qed.\n\nLemma limr_le x f : cvg (f @ F) -> (\\near F, x >= f F) -> x >= lim (f @ F).\nProof. exact: cvgr_to_le. Qed.\n\nLemma __deprecated__cvg_gt_ge (u : T -> R) a b :\n  u @ F --> b -> a < b -> \\forall n \\near F, a <= u n.\nProof. by move=> ?; apply: cvgr_ge. Qed.\n\nLemma __deprecated__cvg_lt_le (u : T -> R) c b :\n  u @ F --> b -> b < c -> \\forall n \\near F, u n <= c.\nProof. by move=> ?; apply: cvgr_le. Qed.\n\nEnd ProperFilterRealType.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"renamed to `cvgr_ge` and generalized to a `Filter`\")]\nNotation cvg_gt_ge := __deprecated__cvg_gt_ge.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"renamed to `cvgr_le` and generalized to a `Filter`\")]\nNotation cvg_lt_le_:= __deprecated__cvg_lt_le.\n\nSection local_continuity.\n\nContext {K : numFieldType} {V : normedModType K} {T : topologicalType}.\nImplicit Types (f g : T -> V) (s t : T -> K) (x : T) (k : K) (a : V).\n\nLemma continuousN (f : T -> V) x :\n  {for x, continuous f} -> {for x, continuous (fun x => - f x)}.\nProof. by move=> ?; apply: cvgN. Qed.\n\nLemma continuousD f g x :\n  {for x, continuous f} -> {for x, continuous g} ->\n  {for x, continuous (f + g)}.\nProof. by move=> f_cont g_cont; apply: cvgD. Qed.\n\nLemma continuousB f g x :\n  {for x, continuous f} -> {for x, continuous g} ->\n  {for x, continuous (f - g)}.\nProof. by move=> f_cont g_cont; apply: cvgB. Qed.\n\nLemma continuousZ s f x :\n  {for x, continuous s} -> {for x, continuous f} ->\n  {for x, continuous (fun x => s x *: f x)}.\nProof. by move=> ? ?; apply: cvgZ. Qed.\n\nLemma continuousZr f k x :\n  {for x, continuous f} -> {for x, continuous (k \\*: f)}.\nProof. by move=> ?; apply: cvgZr. Qed.\n\nLemma continuousZl s a x :\n  {for x, continuous s} -> {for x, continuous (fun z => s z *: a)}.\nProof. by move=> ?; apply: cvgZl. Qed.\n\nLemma continuousM s t x :\n  {for x, continuous s} -> {for x, continuous t} ->\n  {for x, continuous (s * t)}.\nProof. by move=> f_cont g_cont; apply: cvgM. Qed.\n\nLemma continuousV s x : s x != 0 ->\n  {for x, continuous s} -> {for x, continuous (fun x => (s x)^-1%R)}.\nProof. by move=> ?; apply: cvgV. Qed.\n\nEnd local_continuity.\n\nSection nbhs_ereal.\nContext {R : numFieldType} (P : \\bar R -> Prop).\n\nLemma nbhs_EFin (x : R) : (\\forall y \\near x%:E, P y) <-> \\near x, P x%:E.\nProof. done. Qed.\n\nLemma nbhs_ereal_pinfty :\n  (\\forall x \\near +oo%E, P x) <-> [/\\ P +oo%E & \\forall x \\near +oo, P x%:E].\nProof.\nsplit=> [|[Py]] [x [xr Px]]; last by exists x; split=> // -[y||]//; apply: Px.\nby split; [|exists x; split=> // y xy]; apply: Px.\nQed.\n\nLemma nbhs_ereal_ninfty :\n  (\\forall x \\near -oo%E, P x) <-> [/\\ P -oo%E & \\forall x \\near -oo, P x%:E].\nProof.\nsplit=> [|[Py]] [x [xr Px]]; last by exists x; split=> // -[y||]//; apply: Px.\nby split; [|exists x; split=> // y xy]; apply: Px.\nQed.\nEnd nbhs_ereal.\n\nSection cvg_fin.\nContext {R : numFieldType}.\n\nSection filter.\nContext {F : set (set \\bar R)} {FF : Filter F}.\n\nLemma fine_fcvg a : F --> a%:E -> fine @ F --> a.\nProof.\nmove=> /(_ _)/= Fa; apply/cvgrPdist_lt=> // _/posnumP[e]; rewrite near_simpl.\nby apply: Fa; apply/nbhs_EFin => /=; apply: (@cvgr_dist_lt _ _ _ (nbhs a)).\n(* BUG: using cvgr_dist_lt without (nbhs _) expands the definition of nbhs, *)\n(*    so that it is not recognized as a filter anymore *)\nQed.\n\nLemma fcvg_is_fine a : F --> a%:E -> \\near F, F \\is a fin_num.\nProof. by apply; apply/nbhs_EFin; near=> x. Unshelve. all: by end_near. Qed.\n\nEnd filter.\n\nSection limit.\nContext {I : Type} {F : set (set I)} {FF : Filter F} (f : I -> \\bar R).\n\nLemma fine_cvg a : f @ F --> a%:E -> fine \\o f @ F --> a.\nProof. exact: fine_fcvg. Qed.\n\nLemma cvg_is_fine a : f @ F --> a%:E -> \\near F, f F \\is a fin_num.\nProof. exact: fcvg_is_fine. Qed.\n\nLemma cvg_EFin a : (\\near F, f F \\is a fin_num) -> fine \\o f @ F --> a ->\n  f @ F --> a%:E.\nProof.\nmove=> Ffin Fa P/= /nbhs_EFin /Fa; rewrite !near_simpl.\nby apply: filterS2 Ffin => x /fineK->.\nQed.\n\nLemma fine_cvgP a :\n   f @ F --> a%:E <-> (\\near F, f F \\is a fin_num) /\\ fine \\o f @ F --> a.\nProof.\nby split;[split;[exact: (@cvg_is_fine a)|exact: fine_cvg]|case; apply: cvg_EFin].\nQed.\n\nLemma neq0_fine_cvgP a : a != 0 -> f @ F --> a%:E <-> fine \\o f @ F --> a.\nProof.\nmove=> a_neq0; split=> [|Fa]; first exact: fine_cvg.\napply: cvg_EFin=> //; near (0 : R)^'+ => e.\nhave lea : e <= `|a| by near: e; apply: nbhs_right_le; rewrite normr_gt0.\nnear=> x; have : `|a - fine (f x)| < e by near: x; apply: cvgr_dist_lt.\nby case: f=> //=; rewrite subr0; apply: contra_ltT.\nUnshelve. all: by end_near. Qed.\n\nEnd limit.\n\nEnd cvg_fin.\n\nLemma eq_cvg (T T' : Type) (F : set (set T)) (f g : T -> T') (x : set (set T')) :\n  f =1 g -> (f @ F --> x) = (g @ F --> x).\nProof. by move=> /funext->. Qed.\n\nLemma eq_is_cvg (T T' : Type) (fT : filteredType T') (F : set (set T)) (f g : T -> T') :\n  f =1 g -> [cvg (f @ F) in fT] = [cvg (g @ F) in fT].\nProof. by move=> /funext->. Qed.\n\nSection ecvg_realFieldType.\nContext {I} {F : set (set I)} {FF : Filter F} {R : realFieldType}.\nImplicit Types f g u v : I -> \\bar R.\nLocal Open Scope ereal_scope.\n\nLemma cvgeD f g a b :\n  a +? b -> f @ F --> a -> g @ F --> b -> f \\+ g @ F --> a + b.\nProof.\nhave yE u v x : u @ F --> +oo -> v @ F --> x%:E -> u \\+ v @ F --> +oo.\n  move=> /cvgeyPge/= foo /fine_cvgP[Fg gb]; apply/cvgeyPgey.\n  near=> A; near=> n; have /(_ _)/wrap[//|Fgn] := near Fg n.\n  rewrite -lee_subl_addr// (@le_trans _ _ (A - (x - 1))%:E)//; last by near: n.\n  rewrite ?EFinB lee_sub// lee_subl_addr// -[v n]fineK// -EFinD lee_fin.\n  by rewrite ler_distl_addr// ltW//; near: n; apply: cvgr_dist_lt.\nhave NyE u v x : u @ F --> -oo -> v @ F --> x%:E -> u \\+ v @ F --> -oo.\n  move=> /cvgeNyPle/= foo /fine_cvgP -[Fg gb]; apply/cvgeNyPleNy.\n  near=> A; near=> n; have /(_ _)/wrap[//|Fgn] := near Fg n.\n  rewrite -lee_subr_addr// (@le_trans _ _ (A - (x + 1))%:E)//; first by near: n.\n  rewrite ?EFinB ?EFinD lee_sub// -[v n]fineK// -EFinD lee_fin.\n  by rewrite ler_distlC_addr// ltW//; near: n; apply: cvgr_dist_lt.\nhave yyE u v : u @ F --> +oo -> v @ F --> +oo -> u \\+ v @ F --> +oo.\n  move=> /cvgeyPge foo /cvgeyPge goo; apply/cvgeyPge => A; near=> y.\n  by rewrite -[leLHS]adde0 lee_add//; near: y; [apply: foo|apply: goo].\nhave NyNyE u v : u @ F --> -oo -> v @ F --> -oo -> u \\+ v @ F --> -oo.\n  move=> /cvgeNyPle foo /cvgeNyPle goo; apply/cvgeNyPle => A; near=> y.\n  by rewrite -[leRHS]adde0 lee_add//; near: y; [apply: foo|apply: goo].\nhave addfC u v : u \\+ v = v \\+ u.\n  by apply/funeqP => x; rewrite /= addeC.\nmove: a b => [a| |] [b| |] //= _; rewrite ?(addey, addye, addeNy, addNye)//=;\n  do ?by [apply: yE|apply: NyE|apply: yyE|apply: NyNyE].\n- move=> /fine_cvgP[Ff fa] /fine_cvgP[Fg ga]; rewrite -EFinD.\n  apply/fine_cvgP; split.\n    by near do [rewrite fin_numD; apply/andP; split].\n  apply: (@cvg_trans _ ((fine \\o f) \\+ (fine \\o g) @ F))%R; last exact: cvgD.\n  by apply: near_eq_cvg; near do rewrite /= fineD//.\n- by move=> /[swap]; rewrite addfC; apply: yE.\n- by move=> /[swap]; rewrite addfC; apply: NyE.\nUnshelve. all: by end_near. Qed.\n\nLemma cvgeN f x : f @ F --> x -> - f x @[x --> F] --> - x.\nProof. by move=> ?; apply: continuous_cvg => //; exact: oppe_continuous. Qed.\n\nLemma cvgeNP f a : - f x @[x --> F] --> - a <-> f @ F --> a.\nProof.\nby split=> /cvgeN//; rewrite oppeK//; under eq_cvg do rewrite /= oppeK.\nQed.\n\nLemma cvgeB f g a b :\n  a +? - b -> f @ F --> a -> g @ F --> b -> f \\- g @ F --> a - b.\nProof. by move=> ab fa gb; apply: cvgeD => //; exact: cvgeN. Qed.\n\nLemma cvge_sub0 f (k : \\bar R) :\n  k \\is a fin_num -> (fun x => f x - k) @ F --> 0 <-> f @ F --> k.\nProof.\nmove=> kfin; split.\n  move=> /cvgeD-/(_ (cst k) _ isT (cvg_cst _)).\n  by rewrite add0e; under eq_fun => x do rewrite subeK//.\nmove: k kfin => [k _ fk| |]//; rewrite -(@subee _ k%:E)//.\nby apply: cvgeB => //; exact: cvg_cst.\nQed.\n\nLemma abse_continuous : continuous (@abse R).\nProof.\ncase=> [r|A /= [r [rreal rA]]|A /= [r [rreal rA]]]/=.\n- exact/(cvg_comp (@norm_continuous _ [normedModType R of R^o] r)).\n- by exists r; split => // y ry; apply: rA; rewrite (lt_le_trans ry)// lee_abs.\n- exists (- r)%R; rewrite realN; split => // y; rewrite EFinN -lte_oppr => yr.\n  by apply: rA; rewrite (lt_le_trans yr)// -abseN lee_abs.\nQed.\n\nLemma cvg_abse f (a : \\bar R) : f @ F --> a -> `|f x|%E @[x --> F] --> `|a|%E.\nProof. by apply: continuous_cvg => //; apply: abse_continuous. Qed.\n\nLemma is_cvg_abse (f : I -> \\bar R) : cvg (f @ F) -> cvg (`|f x|%E @[x --> F]).\nProof. by move/cvg_abse/cvgP. Qed.\n\nLemma is_cvgeN f : cvg (f @ F) -> cvg (\\- f @ F).\nProof. by move=> /cvg_ex[l fl]; apply: (cvgP (- l)); exact: cvgeN. Qed.\n\nLemma is_cvgeNE f : cvg (\\- f @ F) = cvg (f @ F).\nProof.\nrewrite propeqE; split=> /cvgeNP/cvgP//.\nby under eq_is_cvg do rewrite oppeK.\nQed.\n\nLemma mule_continuous (r : R) : continuous (mule r%:E).\nProof.\nwlog r0 : r / (r > 0)%R => [hwlog|].\n  have [r0|r0|->] := ltrgtP r 0; do ?exact: hwlog; last first.\n    by move=> x; rewrite mul0e; apply: cvg_near_cst; near=> y; rewrite mul0e.\n  have -> : *%E r%:E = \\- ( *%E (- r)%:E ).\n    by apply/funeqP=> x /=; rewrite EFinN mulNe oppeK.\n  move=> x; apply: (continuous_comp (hwlog (- r)%R _ _)); rewrite ?oppr_gt0//.\n  exact: oppe_continuous.\nmove=> [s||]/=.\n- rewrite -EFinM; apply: cvg_EFin => /=.\n    by apply/nbhs_EFin; near do rewrite fin_numM//.\n  move=> P /= Prs; apply/nbhs_EFin=> //=.\n  by apply: near_fun => //=; apply: continuousM => //=; apply: cvg_cst.\n- rewrite muleC /mule/= eqe gt_eqF// lte_fin r0 => A [u [realu uA]].\n  exists (r^-1 * u)%R; split; first by rewrite realM// realV realE ltW.\n  by move=> x rux; apply: uA; move: rux; rewrite EFinM lte_pdivr_mull.\n- rewrite muleC /mule/= eqe gt_eqF// lte_fin r0 => A [u [realu uA]].\n  exists (r^-1 * u)%R; split; first by rewrite realM// realV realE ltW.\n  by move=> x xru; apply: uA; move: xru; rewrite EFinM lte_pdivl_mull.\nUnshelve. all: by end_near. Qed.\n\nLemma cvgeMl f x y : y \\is a fin_num ->\n  f @ F --> x -> (fun n => y * f n) @ F --> y * x.\nProof. by move: y => [r| |]// _ /cvg_comp; apply; exact: mule_continuous. Qed.\n\nLemma is_cvgeMl f y : y \\is a fin_num ->\n  cvg (f @ F) -> cvg ((fun n => y * f n) @ F).\nProof. by move=> fy /(cvgeMl fy)/cvgP. Qed.\n\nLemma cvgeMr f x y : y \\is a fin_num ->\n  f @ F --> x -> (fun n => f n * y) @ F --> x * y.\nProof.\nby move=> ? ?; rewrite muleC; under eq_fun do rewrite muleC; exact: cvgeMl.\nQed.\n\nLemma is_cvgeMr f y : y \\is a fin_num ->\n  cvg (f @ F) -> cvg ((fun n => f n * y) @ F).\nProof. by move=> fy /(cvgeMr fy)/cvgP. Qed.\n\nLemma cvg_abse0P f : abse \\o f @ F --> 0 <-> f @ F --> 0.\nProof.\nsplit; last by move=> /cvg_abse; rewrite abse0.\nmove=> /cvg_ballP f0; apply/cvg_ballP => _/posnumP[e].\nhave := !! f0 _ (gt0 e); rewrite !near_simpl => absf0; rewrite near_simpl.\napply: filterS absf0 => x /=; rewrite /ball/= /ereal_ball !contract0 !sub0r !normrN.\nhave [fx0|fx0] := leP 0 (f x); first by rewrite gee0_abs.\nby rewrite (lte0_abs fx0) contractN normrN.\nQed.\n\nLet cvgeM_gt0_pinfty f g b :\n  (0 < b)%R -> f @ F --> +oo -> g @ F --> b%:E -> f \\* g @ F --> +oo.\nProof.\nmove=> b_gt0 /cvgeyPge foo /fine_cvgP[gfin gb]; apply/cvgeyPgey.\nnear (0%R : R)^'+ => e; near=> A; near=> n.\nrewrite (@le_trans _ _ (f n * e%:E))// ?lee_pmul// ?lee_fin//.\n- by rewrite -lee_pdivr_mulr ?divr_gt0//; near: n; apply: foo.\n- by rewrite (@le_trans _ _ 1) ?lee_fin//; near: n; apply: foo.\nrewrite -(@fineK _ (g n)) ?lee_fin; last by near: n; exact: gfin.\nby near: n; apply: (cvgr_ge b).\nUnshelve. all: end_near. Qed.\n\nLet cvgeM_lt0_pinfty  f g b :\n  (b < 0)%R -> f @ F --> +oo -> g @ F --> b%:E -> f \\* g @ F --> -oo.\nProof.\nmove=> b0 /cvgeyPge foo /fine_cvgP -[gfin gb]; apply/cvgeNyPleNy.\nnear (0%R : R)^'+ => e; near=> A; near=> n.\nrewrite -lee_opp -muleN (@le_trans _ _ (f n * e%:E))//.\n  by rewrite -lee_pdivr_mulr ?mulr_gt0 ?oppr_gt0//; near: n; apply: foo.\nrewrite lee_pmul ?lee_fin//.\n  by rewrite (@le_trans _ _ 1) ?lee_fin//; near: n; apply: foo.\nrewrite -(@fineK _ (g n)) ?lee_fin; last by near: n; exact: gfin.\nnear: n; apply: (cvgr_ge (- b)); rewrite 1?cvgNP//.\nby near: e; apply: nbhs_right_lt; rewrite oppr_gt0.\nUnshelve. all: end_near. Qed.\n\nLet cvgeM_gt0_ninfty f g b :\n  (0 < b)%R -> f @ F --> -oo -> g @ F --> b%:E -> f \\* g @ F --> -oo.\nProof.\nmove=> b0 foo gb; under eq_fun do rewrite -muleNN.\napply: (@cvgeM_lt0_pinfty _ _ (- b)%R); first by rewrite oppr_lt0.\n- by rewrite -(oppeK +oo); apply: cvgeN.\n- by rewrite EFinN; apply: cvgeN.\nQed.\n\nLet cvgeM_lt0_ninfty f g b :\n  (b < 0)%R -> f @ F --> -oo -> g @ F --> b%:E -> f \\* g @ F --> +oo.\nProof.\nmove=> b0 foo gb; under eq_fun do rewrite -muleNN.\napply: (@cvgeM_gt0_pinfty _ _ (- b)%R); first by rewrite oppr_gt0.\n- by rewrite -(oppeK +oo); apply: cvgeN.\n- by rewrite EFinN; apply: cvgeN.\nQed.\n\nLemma cvgeM f g (a b : \\bar R) :\n a *? b -> f @ F --> a -> g @ F --> b -> f \\* g @ F --> a * b.\nProof.\nmove=> [:apoo] [:bnoo] [:poopoo] [:poonoo]; move: a b => [a| |] [b| |] //.\n- move=> _ /fine_cvgP[finf fa] /fine_cvgP[fing gb].\n  apply/fine_cvgP; split.\n    by near do apply: fin_numM; [apply: finf | apply: fing].\n  apply: (@cvg_trans _ (((fine \\o f) \\* (fine \\o g)) @ F)%R).\n    apply: near_eq_cvg; near=> n => //=.\n    rewrite -[in RHS](@fineK _ (f n)); last by near: n; exact: finf.\n    by rewrite -[in RHS](@fineK _ (g n)) //; near: n; exact: fing.\n  exact: cvgM.\n- move: f g a; abstract: apoo.\n  move=> {}f {}g {}a + fa goo; have [a0 _|a0 _|->] := ltgtP a 0%R.\n  + rewrite mulry ltr0_sg// ?mulN1e.\n    by under eq_fun do rewrite muleC; exact: (cvgeM_lt0_pinfty a0).\n  + rewrite mulry gtr0_sg// ?mul1e.\n    by under eq_fun do rewrite muleC; exact: (cvgeM_gt0_pinfty a0).\n  + by rewrite /mule_def eqxx.\n- move: f g a; abstract: bnoo.\n  move=> {}f {}g {}a + fa goo; have [a0 _|a0 _|->] := ltgtP a 0%R.\n  + rewrite mulrNy ltr0_sg// ?mulN1e.\n    by under eq_fun do rewrite muleC; exact: (cvgeM_lt0_ninfty a0).\n  + rewrite mulrNy gtr0_sg// ?mul1e.\n    by under eq_fun do rewrite muleC; exact: (cvgeM_gt0_ninfty a0).\n  + by rewrite /mule_def eqxx.\n- rewrite mule_defC => ? foo gb; rewrite muleC.\n  by under eq_fun do rewrite muleC; exact: apoo.\n- move=> _; move: f g; abstract: poopoo.\n  move=> {}f {}g /cvgeyPge foo /cvgeyPge goo.\n  rewrite mulyy; apply/cvgeyPgey; near=> A; near=> n.\n  have A_gt0 : (0 <= A)%R by [].\n  by rewrite -[leLHS]mule1 lee_pmul//=; near: n; [apply: foo|apply: goo].\n- move=> _; move: f g; abstract: poonoo.\n  move=> {}f {}g /cvgeyPge foo /cvgeNyPle goo.\n  rewrite mulyNy; apply/cvgeNyPle => A; near=> n.\n  rewrite (@le_trans _ _ (g n))//; last by near: n; exact: goo.\n  apply: lee_nemull; last by near: n; apply: foo.\n  by rewrite (@le_trans _ _ (- 1)%:E)//; near: n; apply: goo; rewrite ltrN10.\n- rewrite mule_defC => ? foo gb; rewrite muleC.\n  by under eq_fun do rewrite muleC; exact: bnoo.\n- move=> _ foo goo.\n  by under eq_fun do rewrite muleC; exact: poonoo.\n- move=> _ foo goo; rewrite mulNyNy -mulyy.\n  by under eq_fun do rewrite -muleNN; apply: poopoo;\n    rewrite -/(- -oo); apply: cvgeN.\nUnshelve. all: end_near. Qed.\n\nEnd ecvg_realFieldType.\n\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"renamed to cvgeN, and generalized to filter in Type\")]\nNotation ereal_cvgN := cvgeN.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"renamed to is_cvgeN, and generalized to filter in Type\")]\nNotation ereal_is_cvgN := is_cvgeN.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"renamed to cvgeMl, and generalized to filter in Type\")]\nNotation ereal_cvgrM := cvgeMl.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"renamed to is_cvgeMl, and generalized to filter in Type\")]\nNotation ereal_is_cvgrM := is_cvgeMl.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"renamed to cvgeMr, and generalized to filter in Type\")]\nNotation ereal_cvgMr := cvgeMr.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"renamed to is_cvgeMr, and generalized to filter in Type\")]\nNotation ereal_is_cvgMr := is_cvgeMr.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"renamed to cvgeM, and generalized to a realFieldType\")]\nNotation ereal_cvgM := cvgeM.\n\nSection open_closed_sets_ereal.\nVariable R : realFieldType (* TODO: generalize to numFieldType? *).\nLocal Open Scope ereal_scope.\nImplicit Types x y : \\bar R.\nImplicit Types r : R.\n\nLemma open_ereal_lt y : open [set r : R | r%:E < y].\nProof.\ncase: y => [y||] /=; first exact: open_lt.\n- rewrite (_ : [set _ | _] = setT); first exact: openT.\n  by rewrite funeqE => ? /=; rewrite ltry trueE.\n- rewrite (_ : [set _ | _] = set0); first exact: open0.\n  by rewrite funeqE => ? /=; rewrite falseE.\nQed.\n\nLemma open_ereal_gt y : open [set r : R | y < r%:E].\nProof.\ncase: y => [y||] /=; first exact: open_gt.\n- rewrite (_ : [set _ | _] = set0); first exact: open0.\n  by rewrite funeqE => ? /=; rewrite falseE.\n- rewrite (_ : [set _ | _] = setT); first exact: openT.\n  by rewrite funeqE => ? /=; rewrite ltNyr trueE.\nQed.\n\nLemma open_ereal_lt' x y : x < y -> ereal_nbhs x (fun u => u < y).\nProof.\ncase: x => [x|//|] xy; first exact: open_ereal_lt.\n- case: y => [y||//] /= in xy *; last by exists 0%R.\n  by exists y; rewrite num_real; split => //= x ?.\n- case: y => [y||//] /= in xy *.\n  + by exists y; rewrite num_real; split => //= x ?.\n  + by exists 0%R; split => // x /lt_le_trans; apply; rewrite leey.\nQed.\n\nLemma open_ereal_gt' x y : y < x -> ereal_nbhs x (fun u => y < u).\nProof.\ncase: x => [x||] //=; do ?[exact: open_ereal_gt];\n  case: y => [y||] //=; do ?by exists 0.\n- by exists y; rewrite num_real.\n- by move=> _; exists 0%R; split => // x; apply/le_lt_trans; rewrite leNye.\nQed.\n\nLemma open_ereal_lt_ereal x : open [set y | y < x].\nProof.\nhave openr r : open [set x | x < r%:E].\n  case => [? | // | ?]; [rewrite /= lte_fin => xy | by exists r].\n  by move: (@open_ereal_lt r%:E); rewrite openE; apply; rewrite /= lte_fin.\ncase: x => [ // | | [] // ].\nsuff -> : [set y | y < +oo] = \\bigcup_r [set y : \\bar R | y < r%:E].\n  exact: bigcup_open.\nrewrite predeqE => -[r | | ]/=.\n- rewrite ltry; split => // _.\n  by exists (r + 1)%R => //=; rewrite lte_fin ltr_addl.\n- by rewrite ltxx; split => // -[] x /=; rewrite ltNge leey.\n- by split => // _; exists 0%R => //=.\nQed.\n\nLemma open_ereal_gt_ereal x : open [set y | x < y].\nProof.\nhave openr r : open [set x | r%:E < x].\n  case => [? | ? | //]; [rewrite /= lte_fin => xy | by exists r].\n  by move: (@open_ereal_gt r%:E); rewrite openE; apply; rewrite /= lte_fin.\ncase: x => [ // | [] // | ].\nsuff -> : [set y | -oo < y] = \\bigcup_r [set y : \\bar R | r%:E < y].\n  exact: bigcup_open.\nrewrite predeqE => -[r | | ]/=.\n- rewrite ltNyr; split => // _.\n  by exists (r - 1)%R => //=; rewrite lte_fin ltr_subl_addr ltr_addl.\n- by split => // _; exists 0%R => //=.\n- by rewrite ltxx; split => // -[] x _ /=; rewrite ltNge leNye.\nQed.\n\nLemma closed_ereal_le_ereal y : closed [set x | y <= x].\nProof.\nrewrite (_ : [set x | y <= x] = ~` [set x | y > x]); last first.\n  by rewrite predeqE=> x; split=> [rx|/negP]; [apply/negP|]; rewrite -leNgt.\nexact/open_closedC/open_ereal_lt_ereal.\nQed.\n\nLemma closed_ereal_ge_ereal y : closed [set x | y >= x].\nProof.\nrewrite (_ : [set x | y >= x] = ~` [set x | y < x]); last first.\n  by rewrite predeqE=> x; split=> [rx|/negP]; [apply/negP|]; rewrite -leNgt.\nexact/open_closedC/open_ereal_gt_ereal.\nQed.\n\nEnd open_closed_sets_ereal.\n\nSection closure_left_right_open.\nVariable R : realFieldType.\nImplicit Types z : R.\n\nLemma closure_gt z : closure ([set x | z < x] : set R) = [set x | z <= x].\nProof.\nrewrite eqEsubset; split.\n  by rewrite closureE; apply: smallest_sub => // ? /ltW.\nmove=> v; rewrite /mkset le_eqVlt => /predU1P[<-{v}|]; last first.\n  by move=> ?; exact: subset_closure.\nmove=> B [e /= e0 zB]; near (0 : R)^'+ => d.\nexists (z + d); split; rewrite /= ?ltr_addl//; apply: zB => /=.\nby rewrite opprD addNKr normrN gtr0_norm//.\nUnshelve. all: by end_near. Qed.\n\nLemma closure_lt z : closure ([set x : R | x < z]) = [set x | x <= z].\nProof.\nrewrite eqEsubset; split.\n  by rewrite closureE; apply: smallest_sub => // ? /ltW.\nmove=> v; rewrite /mkset le_eqVlt => /predU1P[<-{z}|]; last first.\n  by move=> ?; exact: subset_closure.\nmove=> B [e /= e0 vB]; near (0 : R)^'+ => d.\nexists (v - d); split; rewrite /= ?gtr_addl ?oppr_lt0//; apply: vB => /=.\nby rewrite opprB addrC addrNK gtr0_norm//; near: d.\nUnshelve. all: by end_near. Qed.\n\nEnd closure_left_right_open.\n\n(** ** Complete Normed Modules *)\n\nModule CompleteNormedModule.\n\nSection ClassDef.\n\nVariable K : numFieldType.\n\nRecord class_of (T : Type) := Class {\n  base : NormedModule.class_of K T ;\n  mixin : Complete.axiom (PseudoMetric.Pack base)\n}.\nLocal Coercion base : class_of >-> NormedModule.class_of.\nDefinition base2 T (cT : class_of T) : CompletePseudoMetric.class_of K T :=\n  @CompletePseudoMetric.Class _ _ (@base T cT) (@mixin T cT).\nLocal Coercion base2 : class_of >-> CompletePseudoMetric.class_of.\n\nStructure type (phK : phant K) := Pack { sort; _ : class_of sort }.\nLocal Coercion sort : type >-> Sortclass.\n\nVariables (phK : phant K) (cT : type phK) (T : Type).\n\nDefinition class := let: Pack _ c := cT return class_of cT in c.\n\nDefinition pack :=\n  fun bT (b : NormedModule.class_of K T) & phant_id (@NormedModule.class K phK bT) b =>\n  fun mT m & phant_id (@Complete.class mT) (@Complete.Class T b m) =>\n    Pack phK (@Class T b m).\nLet xT := let: Pack T _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition eqType := @Equality.Pack cT xclass.\nDefinition choiceType := @Choice.Pack cT xclass.\nDefinition zmodType := @GRing.Zmodule.Pack cT xclass.\nDefinition normedZmodType := @Num.NormedZmodule.Pack K phK cT xclass.\nDefinition lmodType := @GRing.Lmodule.Pack K phK cT xclass.\nDefinition pointedType := @Pointed.Pack cT xclass.\nDefinition filteredType := @Filtered.Pack cT cT xclass.\nDefinition topologicalType := @Topological.Pack cT xclass.\nDefinition uniformType := @Uniform.Pack cT xclass.\nDefinition pseudoMetricType := @PseudoMetric.Pack K cT xclass.\nDefinition pseudoMetricNormedZmodType :=\n  @PseudoMetricNormedZmodule.Pack K phK cT xclass.\nDefinition normedModType := @NormedModule.Pack K phK cT xclass.\nDefinition completeType := @Complete.Pack cT xclass.\nDefinition completePseudoMetricType := @CompletePseudoMetric.Pack K cT xclass.\nDefinition complete_zmodType := @GRing.Zmodule.Pack completeType xclass.\nDefinition complete_lmodType := @GRing.Lmodule.Pack K phK completeType xclass.\nDefinition complete_normedZmodType := @Num.NormedZmodule.Pack K phK completeType xclass.\nDefinition complete_pseudoMetricNormedZmodType :=\n  @PseudoMetricNormedZmodule.Pack K phK completeType xclass.\nDefinition complete_normedModType := @NormedModule.Pack K phK completeType xclass.\nDefinition completePseudoMetric_lmodType : GRing.Lmodule.type phK :=\n  @GRing.Lmodule.Pack K phK (CompletePseudoMetric.sort completePseudoMetricType)\n  xclass.\nDefinition completePseudoMetric_zmodType : GRing.Zmodule.type :=\n  @GRing.Zmodule.Pack (CompletePseudoMetric.sort completePseudoMetricType)\n  xclass.\nDefinition completePseudoMetric_normedModType : NormedModule.type phK :=\n  @NormedModule.Pack K phK (CompletePseudoMetric.sort completePseudoMetricType)\n  xclass.\nDefinition completePseudoMetric_normedZmodType : Num.NormedZmodule.type phK :=\n  @Num.NormedZmodule.Pack K phK\n  (CompletePseudoMetric.sort completePseudoMetricType) xclass.\nDefinition completePseudoMetric_pseudoMetricNormedZmodType :\n  PseudoMetricNormedZmodule.type phK :=\n  @PseudoMetricNormedZmodule.Pack K phK\n  (CompletePseudoMetric.sort completePseudoMetricType) xclass.\nEnd ClassDef.\n\nModule Exports.\n\nCoercion base : class_of >-> NormedModule.class_of.\nCoercion base2 : class_of >-> CompletePseudoMetric.class_of.\nCoercion sort : type >-> Sortclass.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> GRing.Zmodule.type.\nCanonical zmodType.\nCoercion pseudoMetricNormedZmodType : type >-> PseudoMetricNormedZmodule.type.\nCanonical pseudoMetricNormedZmodType.\nCoercion normedZmodType : type >-> Num.NormedZmodule.type.\nCanonical normedZmodType.\nCoercion lmodType : type >-> GRing.Lmodule.type.\nCanonical lmodType.\nCoercion pointedType : type >-> Pointed.type.\nCanonical pointedType.\nCoercion filteredType : type >-> Filtered.type.\nCanonical filteredType.\nCoercion topologicalType : type >-> Topological.type.\nCanonical topologicalType.\nCoercion uniformType : type >-> Uniform.type.\nCanonical uniformType.\nCoercion pseudoMetricType : type >-> PseudoMetric.type.\nCanonical pseudoMetricType.\nCoercion normedModType : type >-> NormedModule.type.\nCanonical normedModType.\nCoercion completeType : type >-> Complete.type.\nCanonical completeType.\nCoercion completePseudoMetricType : type >-> CompletePseudoMetric.type.\nCanonical completePseudoMetricType.\nCanonical complete_zmodType.\nCanonical complete_lmodType.\nCanonical complete_normedZmodType.\nCanonical complete_pseudoMetricNormedZmodType.\nCanonical complete_normedModType.\nCanonical completePseudoMetric_lmodType.\nCanonical completePseudoMetric_zmodType.\nCanonical completePseudoMetric_normedModType.\nCanonical completePseudoMetric_normedZmodType.\nCanonical completePseudoMetric_pseudoMetricNormedZmodType.\nNotation completeNormedModType K := (type (Phant K)).\nNotation \"[ 'completeNormedModType' K 'of' T ]\" := (@pack _ (Phant K) T _ _ idfun _ _ idfun)\n  (at level 0, format \"[ 'completeNormedModType'  K  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd CompleteNormedModule.\n\nExport CompleteNormedModule.Exports.\n\n(** * Extended Types *)\n\n(** * The topology on real numbers *)\n\nLemma R_complete (R : realType) (F : set (set R)) : ProperFilter F -> cauchy F -> cvg F.\nProof.\nmove=> FF /cauchy_ballP F_cauchy; apply/cvg_ex.\npose D := \\bigcap_(A in F) (down A).\nhave /cauchy_ballP /cauchyP /(_ 1) [//|x0 x01] := F_cauchy.\nhave D_has_sup : has_sup D; first split.\n- exists (x0 - 1) => A FA.\n  near F => x.\n  apply/downP; exists x; first by near: x.\n  by rewrite ler_distl_subl // ltW //; near: x.\n- exists (x0 + 1); apply/ubP => x /(_ _ x01) /downP [y].\n  rewrite -[ball _ _ _]/(_ (_ < _)) ltr_distl ltr_subl_addr => /andP[/ltW].\n  by move=> /(le_trans _) yx01 _ /yx01.\nexists (sup D).\napply/cvgrPdist_le => /= _ /posnumP[eps]; near=> x.\nrewrite ler_distl; move/ubP: (sup_upper_bound D_has_sup) => -> //=.\n  apply: sup_le_ub => //; first by case: D_has_sup.\n  have Fxeps : F (ball_ [eta normr] x eps%:num).\n    by near: x; apply: nearP_dep; apply: F_cauchy.\n  apply/ubP => y /(_ _ Fxeps) /downP[z].\n  rewrite /ball_/= ltr_distl ltr_subl_addr.\n  by move=> /andP [/ltW /(le_trans _) le_xeps _ /le_xeps].\nrewrite /D /= => A FA; near F => y.\napply/downP; exists y.\nby near: y.\nrewrite ler_subl_addl -ler_subl_addr ltW //.\nsuff: `|x - y| < eps%:num by rewrite ltr_norml => /andP[_].\nby near: y; near: x; apply: nearP_dep; apply: F_cauchy.\nUnshelve. all: by end_near. Qed.\n\nCanonical R_regular_completeType (R : realType) :=\n  CompleteType R^o (@R_complete R). (*todo : delete*)\nCanonical R_regular_CompleteNormedModule (R : realType) :=\n  [completeNormedModType R of R^o]. (*todo : delete*)\n\nCanonical R_completeType (R : realType) :=\n  [completeType of R for [completeType of R^o]].\nCanonical R_CompleteNormedModule (R : realType) :=\n  [completeNormedModType R of R].\n(* new *)\n\nSection cvg_seq_bounded.\nContext {K : numFieldType}.\nLocal Notation \"'+oo'\" := (@pinfty_nbhs K).\n\nLemma cvg_seq_bounded {V : normedModType K} (a : nat -> V) :\n  cvg a -> bounded_fun a.\nProof.\nmove=> /cvg_bounded/ex_bound => -[/= Moo] => -[N _ /(_ _) aM].\nhave Moo_real : Moo \\is Num.real by rewrite ger0_real ?(le_trans _ (aM N _))/=.\nrewrite /bounded_near /=; near=> M => n _.\nhave [nN|nN]/= := leqP N n; first by apply: (le_trans (aM _ _)).\nmove: n nN; suff /(_ (Ordinal _)) : forall n : 'I_N, `|a n| <= M by [].\nby near: M; apply: filter_forall => i; apply: nbhs_pinfty_ge.\nUnshelve. all: by end_near. Qed.\n\nEnd cvg_seq_bounded.\n\nLemma closure_sup (R : realType) (A : set R) :\n  A !=set0 -> has_ubound A -> closure A (sup A).\nProof.\nmove=> A0 ?; have [|AsupA] := pselect (A (sup A)); first exact: subset_closure.\nrewrite closure_limit_point; right => U /nbhs_ballP[_ /posnumP[e]] supAeU.\nsuff [x [Ax /andP[sAex xsA]]] : exists x, A x /\\ sup A - e%:num < x < sup A.\n  exists x; split => //; first by rewrite lt_eqF.\n  apply supAeU; rewrite /ball /= ltr_distl (addrC x e%:num) -ltr_subl_addl sAex.\n  by rewrite andbT (le_lt_trans _ xsA) // ler_subl_addl ler_addr.\napply: contrapT => /forallNP Ax.\nsuff /(sup_le_ub A0) : ubound A (sup A - e%:num).\n  by rewrite leNgt => /negP; apply; rewrite ltr_subl_addl ltr_addr.\nmove=> y Ay; have /not_andP[//|/negP] := Ax y.\nrewrite negb_and leNgt => /orP[//|]; apply: contra => sAey.\nrewrite lt_neqAle sup_upper_bound // andbT.\nby apply: contra_not_neq AsupA => <-.\nQed.\n\nLemma near_infty_natSinv_lt (R : archiFieldType) (e : {posnum R}) :\n  \\forall n \\near \\oo, n.+1%:R^-1 < e%:num.\nProof.\nnear=> n; rewrite -(@ltr_pmul2r _ n.+1%:R) // mulVr ?unitfE //.\nrewrite -(@ltr_pmul2l _ e%:num^-1) // mulr1 mulrA mulVr ?unitfE // mul1r.\nrewrite (lt_trans (archi_boundP _)) // ltr_nat.\nby near: n; exists (Num.bound e%:num^-1).\nUnshelve. all: by end_near. Qed.\n\nLemma near_infty_natSinv_expn_lt (R : archiFieldType) (e : {posnum R}) :\n  \\forall n \\near \\oo, 1 / 2 ^+ n < e%:num.\nProof.\nnear=> n.\nrewrite -(@ltr_pmul2r _ (2 ^+ n)) // -?natrX ?ltr0n ?expn_gt0//.\nrewrite mul1r mulVr ?unitfE ?gt_eqF// ?ltr0n ?expn_gt0//.\nrewrite -(@ltr_pmul2l _ e%:num^-1) // mulr1 mulrA mulVr ?unitfE // mul1r.\nrewrite (lt_trans (archi_boundP _)) // natrX upper_nthrootP //.\nnear: n; eexists; last by move=> m; exact.\nby [].\nUnshelve. all: by end_near. Qed.\n\nLemma limit_pointP (T : archiFieldType) (A : set T) (x : T) :\n  limit_point A x <-> exists a_ : nat -> T,\n    [/\\ a_ @` setT `<=` A, forall n, a_ n != x & a_ --> x].\nProof.\nsplit=> [Ax|[a_ [aTA a_x] ax]]; last first.\n  move=> U /ax[m _ a_U]; near \\oo => n; exists (a_ n); split => //.\n  by apply aTA; exists n.\n  by apply a_U; near: n; exists m.\npose U := fun n : nat => [set z : T | `|x - z| < n.+1%:R^-1].\nsuff /(_ _)/cid-/all_sig[a_ anx] : forall n, exists a, a != x /\\ (U n `&` A) a.\n  exists a_; split.\n  - by move=> a [n _ <-]; have [? []] := anx n.\n  - by move=> n; have [] := anx n.\n  - apply/cvgrPdist_lt => _/posnumP[e]; near=> n;  have [? [] Uan Aan] := anx n.\n    by rewrite (lt_le_trans Uan)// ltW//; near: n; exact: near_infty_natSinv_lt.\nmove=> n; have : nbhs (x : T) (U n).\n  by apply/(nbhs_ballP (x:T) (U n)); rewrite nbhs_ballE; exists n.+1%:R^-1 => //=.\nby move/Ax/cid => [/= an [anx Aan Uan]]; exists an.\nUnshelve. all: by end_near. Qed.\n\nSection interval.\nVariable R : numDomainType.\n\nDefinition is_interval (E : set R) :=\n  forall x y, E x -> E y -> forall z, x <= z <= y -> E z.\n\nLemma is_intervalPlt (E : set R) :\n  is_interval E <-> forall x y, E x -> E y -> forall z, x < z < y -> E z.\nProof.\nsplit=> iE x y Ex Ey z /andP[].\n  by move=> xz zy; apply: (iE x y); rewrite ?ltW.\nrewrite !le_eqVlt => /predU1P[<-//|xz] /predU1P[->//|zy].\nby apply: (iE x y); rewrite ?xz.\nQed.\n\nLemma interval_is_interval (i : interval R) : is_interval [set` i].\nProof.\nby case: i => -[[]a|[]] [[]b|[]] // x y /=; do ?[by rewrite ?itv_ge//];\n  move=> xi yi z; rewrite -[x <= z <= y]/(z \\in `[x, y]); apply/subitvP;\n  rewrite subitvE /Order.le/= ?(itvP xi, itvP yi).\nQed.\n\nEnd interval.\n\nSection ereal_is_hausdorff.\nVariable R : realFieldType.\nImplicit Types r : R.\n\nLemma nbhs_image_EFin (x : R) (X : set R) :\n  nbhs x X -> nbhs x%:E ((fun r => r%:E) @` X).\nProof.\ncase => _/posnumP[e] xeX; exists e%:num => //= r xer.\nby exists r => //; apply xeX.\nQed.\n\nLemma nbhs_open_ereal_lt r (f : R -> R) : r < f r ->\n  nbhs r%:E [set y | y < (f r)%:E]%E.\nProof.\nmove=> xfx; rewrite nbhsE /=; eexists; last by move=> y; exact.\nby split; [apply open_ereal_lt_ereal | rewrite /= lte_fin].\nQed.\n\nLemma nbhs_open_ereal_gt r (f : R -> R) : f r < r ->\n  nbhs r%:E [set y | (f r)%:E < y]%E.\nProof.\nmove=> xfx; rewrite nbhsE /=; eexists; last by move=> y; exact.\nby split; [apply open_ereal_gt_ereal | rewrite /= lte_fin].\nQed.\n\nLemma nbhs_open_ereal_pinfty r : (nbhs +oo [set y | r%:E < y])%E.\nProof.\nrewrite nbhsE /=; eexists; last by move=> y; exact.\nby split; [apply open_ereal_gt_ereal | rewrite /= ltry].\nQed.\n\nLemma nbhs_open_ereal_ninfty r : (nbhs -oo [set y | y < r%:E])%E.\nProof.\nrewrite nbhsE /=; eexists; last by move=> y; exact.\nby split; [apply open_ereal_lt_ereal | rewrite /= ltNyr].\nQed.\n\nLemma ereal_hausdorff : hausdorff_space (ereal_topologicalType R).\nProof.\nmove=> -[r| |] // [r' | |] //=.\n- move=> rr'; congr (_%:E); apply Rhausdorff => /= A B rA r'B.\n  have [/= z [[r0 ? r0z] [r1 ?]]] :=\n    rr' _ _ (nbhs_image_EFin rA) (nbhs_image_EFin r'B).\n  by rewrite -r0z => -[r1r0]; exists r0; split => //; rewrite -r1r0.\n- have /(@nbhs_open_ereal_lt _ (fun x => x + 1)) loc_r : r < r + 1.\n    by rewrite ltr_addl.\n  move/(_ _ _ loc_r (nbhs_open_ereal_pinfty (r + 1))) => -[z [zr rz]].\n  by move: (lt_trans rz zr); rewrite lte_fin ltxx.\n- have /(@nbhs_open_ereal_gt _ (fun x => x - 1)) loc_r : r - 1 < r.\n    by rewrite ltr_subl_addr ltr_addl.\n  move/(_ _ _ loc_r (nbhs_open_ereal_ninfty (r - 1))) => -[z [rz zr]].\n  by move: (lt_trans zr rz); rewrite ltxx.\n- have /(@nbhs_open_ereal_lt _ (fun x => x + 1)) loc_r' : r' < r' + 1.\n    by rewrite ltr_addl.\n  move/(_ _ _ (nbhs_open_ereal_pinfty (r' + 1)) loc_r') => -[z [r'z zr']].\n  by move: (lt_trans zr' r'z); rewrite ltxx.\n- move/(_ _ _ (nbhs_open_ereal_pinfty 0) (nbhs_open_ereal_ninfty 0)).\n  by move=> -[z [zx xz]]; move: (lt_trans xz zx); rewrite ltxx.\n- have /(@nbhs_open_ereal_gt _ (fun x => x - 1)) yB : r' - 1 < r'.\n    by rewrite ltr_subl_addr ltr_addl.\n  move/(_ _ _ (nbhs_open_ereal_ninfty (r' - 1)) yB) => -[z [zr' r'z]].\n  by move: (lt_trans r'z zr'); rewrite ltxx.\n- move/(_ _ _ (nbhs_open_ereal_ninfty 0) (nbhs_open_ereal_pinfty 0)).\n  by move=> -[z [zO Oz]]; move: (lt_trans Oz zO); rewrite ltxx.\nQed.\n\nEnd ereal_is_hausdorff.\n\n#[global]\nHint Extern 0 (hausdorff_space _) => solve[apply: ereal_hausdorff] : core.\n\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"renamed to `nbhs_image_EFin`\")]\nNotation nbhs_image_ERFin := nbhs_image_EFin.\n\nLemma EFin_lim (R : realFieldType) (f : nat -> R) : cvg f ->\n  lim (EFin \\o f) = (lim f)%:E.\nProof.\nmove=> cf; apply: cvg_lim => //; move/cvg_ex : cf => [l fl].\nby apply: (cvg_comp fl); rewrite (cvg_lim _ fl).\nQed.\n\nSection ProperFilterERealType.\nContext {T : Type} {a : set (set T)} {Fa : ProperFilter a} {R : realFieldType}.\nLocal Open Scope ereal_scope.\nImplicit Types f g h : T -> \\bar R.\n\nLemma cvge_to_ge f b c : f @ a --> c -> (\\near a, b <= f a) -> b <= c.\nProof.\nby move=> /[swap]/(closed_cvg _ (@closed_ereal_le_ereal _ b)) /[apply].\nQed.\n\nLemma cvge_to_le f b c : f @ a --> c -> (\\near a, f a <= b) -> c <= b.\nProof.\nby move=> /[swap]/(closed_cvg _ (@closed_ereal_ge_ereal _ b))/[apply].\nQed.\n\nLemma lime_ge x f : cvg (f @ a) -> (\\near a, x <= f a) -> x <= lim (f @ a).\nProof. exact: cvge_to_ge. Qed.\n\nLemma lime_le x f : cvg (f @ a) -> (\\near a, x >= f a) -> x >= lim (f @ a).\nProof. exact: cvge_to_le. Qed.\n\nEnd ProperFilterERealType.\n\nSection ecvg_realFieldType_proper.\nContext {I} {F : set (set I)} {FF : ProperFilter F} {R : realFieldType}.\nImplicit Types (f g : I -> \\bar R) (u v : I -> R) (x : \\bar R) (r : R).\nLocal Open Scope ereal_scope.\n\nLemma is_cvgeD f g :\n  lim (f @ F) +? lim (g @ F) -> cvg (f @ F) -> cvg (g @ F) -> cvg (f \\+ g @ F).\nProof. by move=> fg fc gc; have /(_ _)/cvgP := cvgeD fg fc gc. Qed.\n\nLemma limeD f g :\n  cvg (f @ F) -> cvg (g @ F) -> lim (f @ F) +? lim (g @ F) ->\n  lim (f \\+ g @ F) = lim (f @ F) + lim (g @ F).\nProof. by move=> cf cg fg; apply/cvg_lim => //; exact: cvgeD. Qed.\n\nLemma limeMl f y : y \\is a fin_num -> cvg (f @ F) ->\n  lim ((fun n => y * f n) @ F) = y * lim (f @ F).\nProof. by move=> yfn cf; apply/cvg_lim => //; exact: cvgeMl. Qed.\n\nLemma limeMr f y : y \\is a fin_num -> cvg (f @ F) ->\n  lim ((fun n => f n * y) @ F) = lim (f @ F) * y.\nProof. by move=> yfn cf; apply/cvg_lim => //; apply: cvgeMr. Qed.\n\nLemma is_cvgeM f g :\n  lim (f @ F) *? lim (g @ F) -> cvg (f @ F) -> cvg (g @ F) -> cvg (f \\* g @ F).\nProof. by move=> fg fc gc; have /(_ _)/cvgP := cvgeM fg fc gc. Qed.\n\nLemma limeM f g :\n  cvg (f @ F) -> cvg (g @ F) -> lim (f @ F) *? lim (g @ F) ->\n  lim (f \\* g @ F) = lim (f @ F) * lim (g @ F).\nProof. by move=> cf cg fg; apply/cvg_lim => //; exact: cvgeM. Qed.\n\nLemma limeN f : cvg (f @ F) -> lim (\\- f @ F) = - lim (f @ F).\nProof. by move=> cf; apply/cvg_lim => //; apply: cvgeN. Qed.\n\nLemma cvge_ge f a b : (\\forall x \\near F, b <= f x) -> f @ F --> a -> b <= a.\nProof. by move=> ? fa; rewrite -(cvg_lim _ fa) ?lime_ge//=; apply: cvgP fa. Qed.\n\nLemma cvge_le f a b : (\\forall x \\near F, b >= f x) -> f @ F --> a -> b >= a.\nProof. by move=> ? fa; rewrite -(cvg_lim _ fa) ?lime_le//=; apply: cvgP fa. Qed.\n\nLemma cvg_nnesum (J : Type) (r : seq J) (f : J -> I -> \\bar R)\n   (l : J -> \\bar R) (P : pred J) :\n  (forall j, P j -> \\near F, 0 <= f j F) ->\n  (forall j, P j -> f j @ F --> l j) ->\n  \\sum_(j <- r | P j) f j i @[i --> F] --> \\sum_(j <- r | P j) l j.\nProof.\npose bigsimp := (big_nil, big_cons);\nelim: r => [|x r IHr]/= f0 fl; rewrite bigsimp; under eq_fun do rewrite bigsimp.\n  exact: cvg_cst.\ncase: ifPn => [Px|Pnx]; last exact: IHr.\napply: cvgeD; [|exact: fl|exact: IHr].\nby rewrite ge0_adde_def ?inE// ?sume_ge0// => [|j Pj];\n   rewrite (cvge_ge _ (fl _ _))//; apply: f0.\nQed.\n\nLemma lim_nnesum (J : Type) (r : seq J) (f : J -> I -> \\bar R)\n   (l : J -> \\bar R) (P : pred J) :\n  (forall j, P j -> \\near F, 0 <= f j F) ->\n  (forall j, P j -> cvg (f j @ F)) ->\n  lim (\\sum_(j <- r | P j) f j i @[i --> F]) = \\sum_(j <- r | P j) (lim (f j @ F)).\nProof. by move=> ? ?; apply/cvg_lim => //; apply: cvg_nnesum. Qed.\n\nEnd ecvg_realFieldType_proper.\n\n#[deprecated(since=\"mathcomp-analysis 0.6.0\", note=\"generalized to `limeMl`\")]\nNotation ereal_limrM := limeMl.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\", note=\"generalized to `limeMr`\")]\nNotation ereal_limMr := limeMr.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\", note=\"generalized to `limeN`\")]\nNotation ereal_limN := limeN.\n\nSection cvg_0_pinfty.\nContext {R : realFieldType} {I : Type} {a : set (set I)} {FF : Filter a}.\nImplicit Types f : I -> R.\n\nLemma gtr0_cvgV0 f : (\\near a, 0 < f a) -> f\\^-1 @ a --> 0 <-> f @ a --> +oo.\nProof.\nmove=> f_gt0; split; last first.\n  move=> /cvgryPgt cvg_f_oo; apply/cvgr0Pnorm_lt => _/posnumP[e].\n  near=> i; rewrite gtr0_norm ?invr_gt0//; last by near: i.\n  by rewrite -ltf_pinv ?qualifE ?invr_gt0 ?invrK//=; near: i.\nmove=> /cvgr0Pnorm_lt uB; apply/cvgryPgty.\nnear=> M; near=> i; suff: `|(f i)^-1| < M^-1.\n  by rewrite gtr0_norm ?ltf_pinv ?qualifE ?invr_gt0//; near: i.\nby near: i; apply: uB; rewrite ?invr_gt0.\nUnshelve. all: by end_near. Qed.\n\nLemma cvgrVy f : (\\near a, 0 < f a) -> f\\^-1 @ a --> +oo <-> f @ a --> 0.\nProof.\nby move=> f_gt0; rewrite -gtr0_cvgV0 ?inv_funK//; near do rewrite invr_gt0.\nUnshelve. all: by end_near. Qed.\n\nLemma ltr0_cvgV0 f : (\\near a, 0 > f a) -> f\\^-1 @ a --> 0 <-> f @ a --> -oo.\nProof.\nmove=> fL0; rewrite -cvgNP oppr0 (_ : - f\\^-1 =  (- f)\\^-1); last first.\n   by apply/funeqP => i; rewrite opprfctE/= invrN.\nby rewrite gtr0_cvgV0 ?cvgNry//; near do rewrite oppr_gt0.\nUnshelve. all: by end_near. Qed.\n\nLemma cvgrVNy f : (\\near a, 0 > f a) -> f\\^-1 @ a --> -oo <-> f @ a --> 0.\nProof.\nby move=> f_lt0; rewrite -ltr0_cvgV0 ?inv_funK//; near do rewrite invr_lt0.\nUnshelve. all: by end_near. Qed.\n\nEnd cvg_0_pinfty.\n\nSection FilterRealType.\nContext {T : Type} {a : set (set T)} {Fa : Filter a} {R : realFieldType}.\nImplicit Types f g h : T -> R.\n\nLemma squeeze_cvgr f g h : (\\near a, f a <= g a <= h a) ->\n  forall (l : R), f @ a --> l -> h @ a --> l -> g @ a --> l.\nProof.\nmove=> fgh l lfa lga; apply/cvgrPdist_lt => e e_gt0.\nnear=> x; have /(_ _)/andP[//|fg gh] := near fgh x.\nrewrite distrC ltr_distl (lt_le_trans _ fg) ?(le_lt_trans gh)//=.\n  by near: x; apply: (cvgr_lt l); rewrite // ltr_addl.\nby near: x; apply: (cvgr_gt l); rewrite // gtr_addl oppr_lt0.\nUnshelve. all: end_near. Qed.\n\nLemma ger_cvgy f g : (\\near a, f a <= g a) ->\n  f @ a --> +oo -> g @ a --> +oo.\nProof.\nmove=> uv /cvgryPge ucvg; apply/cvgryPge => A.\nby near=> x do rewrite (le_trans _ (near uv x _))//.\nUnshelve. all: end_near. Qed.\n\nLemma ler_cvgNy f g : (\\near a, f a >= g a) ->\n  f @ a --> -oo -> g @ a --> -oo.\nProof.\nmove=> uv /cvgrNyPle ucvg; apply/cvgrNyPle => A.\nby near=> x do rewrite (le_trans (near uv x _))//.\nUnshelve. all: end_near. Qed.\n\nEnd FilterRealType.\n\nSection TopoProperFilterRealType.\nContext {T : topologicalType} {a : set (set T)} {Fa : ProperFilter a}.\nContext {R : realFieldType}.\nImplicit Types f g h : T -> R.\n\nLemma ler_cvg_to f g l l' : f @ a --> l -> g @ a --> l' ->\n  (\\near a, f a <= g a) -> l <= l'.\nProof.\nmove=> fl gl; under eq_near do rewrite -subr_ge0; rewrite -subr_ge0.\nby apply: cvgr_to_ge; apply: cvgB.\nQed.\n\nLemma ler_lim f g : cvg (f @ a) -> cvg (g @ a) ->\n  (\\near a, f a <= g a) -> lim (f @ a) <= lim (g @ a).\nProof. exact: ler_cvg_to. Qed.\n\nEnd TopoProperFilterRealType.\n\nSection FilterERealType.\nContext {T : Type} {a : set (set T)} {Fa : Filter a} {R : realFieldType}.\nLocal Open Scope ereal_scope.\nImplicit Types f g h : T -> \\bar R.\n\nLemma gee_cvgy f g : (\\near a, f a <= g a) ->\n  f @ a --> +oo -> g @ a --> +oo.\nProof.\nmove=> uv /cvgeyPge uecvg; apply/cvgeyPge => A.\nby near=> x do rewrite (le_trans _ (near uv x _))//.\nUnshelve. all: end_near. Qed.\n\nLemma lee_cvgNy f g : (\\near a, f a >= g a) ->\n  f @ a --> -oo -> g @ a --> -oo.\nProof.\nmove=> uv /cvgeNyPle uecvg; apply/cvgeNyPle => A.\nby near=> x do rewrite (le_trans (near uv x _))//.\nUnshelve. all: end_near. Qed.\n\nLemma squeeze_fin f g h : (\\near a, f a <= g a <= h a) ->\n    (\\near a, f a \\is a fin_num) -> (\\near a, h a \\is a fin_num) ->\n  (\\near a, g a \\is a fin_num).\nProof.\napply: filterS3 => x /andP[fg gh].\nrewrite !fin_numElt => /andP[oof _] /andP[_ hoo].\nby rewrite (lt_le_trans oof) ?(le_lt_trans gh).\nQed.\n\nLemma squeeze_cvge f g h : (\\near a, f a <= g a <= h a) ->\n  forall (l : \\bar R), f @ a --> l -> h @ a --> l -> g @ a --> l.\nProof.\nmove=> fgh [l||]; last 2 first.\n- by move=> + _; apply: gee_cvgy; apply: filterS fgh => ? /andP[].\n- by move=> _; apply: lee_cvgNy; apply: filterS fgh => ? /andP[].\nmove=> /fine_cvgP[Ff fl] /fine_cvgP[Fh hl]; apply/fine_cvgP.\nhave Fg := squeeze_fin fgh Ff Fh; split=> //.\napply: squeeze_cvgr fl hl; near=> x => /=.\nby have /(_ _)/andP[//|fg gh] := near fgh x; rewrite !fine_le//=; near: x.\nUnshelve. all: end_near. Qed.\n\nEnd FilterERealType.\n\nSection TopoProperFilterERealType.\nContext {T : topologicalType} {a : set (set T)} {Fa : ProperFilter a}.\nContext {R : realFieldType}.\nLocal Open Scope ereal_scope.\nImplicit Types f g h : T -> \\bar R.\n\nLemma lee_cvg_to f g l l' : f @ a --> l -> g @ a --> l' ->\n  (\\near a, f a <= g a) -> l <= l'.\nProof.\nmove=> + + fg; move: l' l.\nmove=> /= [l'||] [l||]//=; rewrite ?leNye ?leey//=; first 1 last.\n- by move=> /(gee_cvgy fg) /cvg_lim<-// /cvg_lim<-.\n- by move=> /cvg_lim <-// /(lee_cvgNy fg) /cvg_lim<-.\n- by move=> /(gee_cvgy fg) /cvg_lim<-// /cvg_lim<-.\nmove=> /fine_cvgP[Ff fl] /fine_cvgP[Fg gl].\nrewrite lee_fin -(cvg_lim _ fl)// -(cvg_lim _ gl)//.\nby apply: ler_lim; [apply: cvgP fl|apply: cvgP gl|near do apply: fine_le].\nUnshelve. all: end_near. Qed.\n\nLemma lee_lim f g : cvg (f @ a) -> cvg (g @ a) ->\n  (\\near a, f a <= g a) -> lim (f @ a) <= lim (g @ a).\nProof. exact: lee_cvg_to. Qed.\n\nEnd TopoProperFilterERealType.\n\nSection open_union_rat.\nVariable R : realType.\nImplicit Types A U : set R.\n\nLet ointsub A U := [/\\ open A, is_interval A & A `<=` U].\n\nLet ointsub_rat U q := [set A | ointsub A U /\\ A (ratr q)].\n\nLet ointsub_rat0 q : ointsub_rat set0 q = set0.\nProof. by apply/seteqP; split => // A [[_ _]]; rewrite subset0 => ->. Qed.\n\nDefinition bigcup_ointsub U q := \\bigcup_(A in ointsub_rat U q) A.\n\nLemma bigcup_ointsub0 q : bigcup_ointsub set0 q = set0.\nProof. by rewrite /bigcup_ointsub ointsub_rat0 bigcup_set0. Qed.\n\nLemma open_bigcup_ointsub U q : open (bigcup_ointsub U q).\nProof. by apply: bigcup_open => i [[]]. Qed.\n\nLemma is_interval_bigcup_ointsub U q : is_interval (bigcup_ointsub U q).\nProof.\nmove=> /= a b [A [[oA iA AU] Aq] Aa] [B [[oB iB BU] Bq] Bb] c /andP[ac cb].\nhave [cq|cq|->] := ltgtP c (ratr q); last by exists A.\n- by exists A => //; apply: (iA a (ratr q)) => //; rewrite ac (ltW cq).\n- by exists B => //; apply: (iB (ratr q) b) => //; rewrite cb (ltW cq).\nQed.\n\nLemma bigcup_ointsub_sub U q : bigcup_ointsub U q `<=` U.\nProof. by move=> y [A [[oA _ +] _ Ay]]; exact. Qed.\n\nLemma open_bigcup_rat U : open U ->\n  U = \\bigcup_(q in [set q | ratr q \\in U]) bigcup_ointsub U q.\nProof.\nmove=> oU; have [->|U0] := eqVneq U set0.\n  by rewrite bigcup0// => q _; rewrite bigcup_ointsub0.\napply/seteqP; split=> [x Ux|x [p _ Ipx]]; last exact: bigcup_ointsub_sub Ipx.\nsuff [q Iqx] : exists q, bigcup_ointsub U q x.\n  by exists q => //=; rewrite in_setE; case: Iqx => A [[_ _ +] ? _]; exact.\nhave : nbhs x U by rewrite nbhsE /=; exists U.\nrewrite -nbhs_ballE /nbhs_ball /nbhs_ball_ => -[_/posnumP[r] xrU].\nhave /rat_in_itvoo[q qxxr] : (x - r%:num < x + r%:num)%R.\n  by rewrite ltr_subl_addr -addrA ltr_addl.\nexists q, `](x - r%:num)%R, (x + r%:num)%R[%classic; last first.\n  by rewrite /= in_itv/= ltr_subl_addl ltr_addr// ltr_addl//; apply/andP.\nsplit=> //; split; [exact: interval_open|exact: interval_is_interval|].\nmove=> y /=; rewrite in_itv/= => /andP[xy yxr]; apply xrU => /=.\nrewrite /ball /= /ball_ /= in xrU *; have [yx|yx] := leP x y.\n  by rewrite ler0_norm ?subr_le0// opprB ltr_subl_addl.\nby rewrite gtr0_norm ?subr_gt0// ltr_subl_addr -ltr_subl_addl.\nQed.\n\nEnd open_union_rat.\n\nLemma right_bounded_interior (R : realType) (X : set R) :\n  has_ubound X -> X^° `<=` [set r | r < sup X].\nProof.\nmove=> uX r Xr; rewrite /mkset ltNge; apply/negP.\nrewrite le_eqVlt => /orP[/eqP supXr|]; last first.\n  by apply/negP; rewrite -leNgt sup_ub //; exact: interior_subset.\nsuff : ~ X^° (sup X) by rewrite supXr.\ncase/nbhs_ballP => _/posnumP[e] supXeX.\nhave [f XsupXf] : exists f : {posnum R}, X (sup X + f%:num).\n  exists (e%:num / 2)%:pos; apply supXeX; rewrite /ball /= opprD addrA subrr.\n  by rewrite sub0r normrN gtr0_norm // ltr_pdivr_mulr // ltr_pmulr // ltr1n.\nhave : sup X + f%:num <= sup X by apply sup_ub.\nby apply/negP; rewrite -ltNge; rewrite ltr_addl.\nQed.\n\nLemma left_bounded_interior (R : realType) (X : set R) :\n  has_lbound X -> X^° `<=` [set r | inf X < r].\nProof.\nmove=> lX r Xr; rewrite /mkset ltNge; apply/negP.\nrewrite le_eqVlt => /orP[/eqP rinfX|]; last first.\n  by apply/negP; rewrite -leNgt inf_lb //; exact: interior_subset.\nsuff : ~ X^° (inf X) by rewrite -rinfX.\ncase/nbhs_ballP => _/posnumP[e] supXeX.\nhave [f XsupXf] : exists f : {posnum R}, X (inf X - f%:num).\n  exists (e%:num / 2)%:pos; apply supXeX; rewrite /ball /= opprB addrCA subrr.\n  by rewrite addr0 gtr0_norm // ltr_pdivr_mulr // ltr_pmulr // ltr1n.\nhave : inf X <= inf X - f%:num by apply inf_lb.\nby apply/negP; rewrite -ltNge; rewrite ltr_subl_addr ltr_addl.\nQed.\n\nSection interval_realType.\nVariable R : realType.\n\nLemma interval_unbounded_setT (X : set R) : is_interval X ->\n  ~ has_lbound X -> ~ has_ubound X -> X = setT.\nProof.\nmove=> iX lX uX; rewrite predeqE => x; split => // _.\nmove/has_lbPn : lX => /(_ x) [y Xy xy].\nmove/has_ubPn : uX => /(_ x) [z Xz xz].\nby apply: (iX y z); rewrite ?ltW.\nQed.\n\nLemma interval_left_unbounded_interior (X : set R) : is_interval X ->\n  ~ has_lbound X -> has_ubound X -> X^° = [set r | r < sup X].\nProof.\nmove=> iX lX uX; rewrite eqEsubset; split; first exact: right_bounded_interior.\nrewrite -(open_subsetE _ (@open_lt _ _)) => r rsupX.\nmove/has_lbPn : lX => /(_ r)[y Xy yr].\nhave hsX : has_sup X by split => //; exists y.\nhave /sup_adherent/(_ hsX)[e Xe] : 0 < sup X - r by rewrite subr_gt0.\nby rewrite opprB addrCA subrr addr0 => re; apply: (iX y e); rewrite ?ltW.\nQed.\n\nLemma interval_right_unbounded_interior (X : set R) : is_interval X ->\n  has_lbound X -> ~ has_ubound X -> X^° = [set r | inf X < r].\nProof.\nmove=> iX lX uX; rewrite eqEsubset; split; first exact: left_bounded_interior.\nrewrite -(open_subsetE _ (@open_gt _ _)) => r infXr.\nmove/has_ubPn : uX => /(_ r)[y Xy yr].\nhave hiX : has_inf X by split => //; exists y.\nhave /inf_adherent/(_ hiX)[e Xe] : 0 < r - inf X by rewrite subr_gt0.\nby rewrite addrCA subrr addr0 => er; apply: (iX e y); rewrite ?ltW.\nQed.\n\nLemma interval_bounded_interior (X : set R) : is_interval X ->\n  has_lbound X -> has_ubound X -> X^° = [set r | inf X < r < sup X].\nProof.\nmove=> iX bX aX; rewrite eqEsubset; split=> [r Xr|].\n  apply/andP; split;\n    [exact: left_bounded_interior|exact: right_bounded_interior].\nrewrite -open_subsetE; last exact: (@interval_open _ (BRight _) (BLeft _)).\nmove=> r /andP[iXr rsX].\nhave [X0|/set0P X0] := eqVneq X set0.\n  by move: (lt_trans iXr rsX); rewrite X0 inf_out ?sup_out ?ltxx // => - [[]].\nhave hiX : has_inf X by split.\nhave /inf_adherent/(_ hiX)[e Xe] : 0 < r - inf X by rewrite subr_gt0.\nrewrite addrCA subrr addr0 => er.\nhave hsX : has_sup X by split.\nhave /sup_adherent/(_ hsX)[f Xf] : 0 < sup X - r by rewrite subr_gt0.\nby rewrite opprB addrCA subrr addr0 => rf; apply: (iX e f); rewrite ?ltW.\nQed.\n\nDefinition Rhull (X : set R) : interval R := Interval\n  (if `[< has_lbound X >] then BSide `[< X (inf X) >] (inf X)\n                          else BInfty _ true)\n  (if `[< has_ubound X >] then BSide (~~ `[< X (sup X) >]) (sup X)\n                          else BInfty _ false).\n\nLemma Rhull0 : Rhull set0 = `]0, 0[ :> interval R.\nProof.\nrewrite /Rhull  (asboolT (has_lbound0 R)) (asboolT (has_ubound0 R)) asboolF //.\nby rewrite sup0 inf0.\nQed.\n\nLemma sub_Rhull (X : set R) : X `<=` [set x | x \\in Rhull X].\nProof.\nmove=> x Xx/=; rewrite in_itv/=.\ncase: (asboolP (has_lbound _)) => ?; case: (asboolP (has_ubound _)) => ? //=.\n+ by case: asboolP => ?; case: asboolP => ? //=;\n     rewrite !(lteifF, lteifT, sup_ub, inf_lb, sup_ub_strict, inf_lb_strict).\n+ by case: asboolP => XinfX; rewrite !(lteifF, lteifT);\n     [rewrite inf_lb | rewrite inf_lb_strict].\n+ by case: asboolP => XsupX; rewrite !(lteifF, lteifT);\n     [rewrite sup_ub | rewrite sup_ub_strict].\nQed.\n\nLemma is_intervalP (X : set R) : is_interval X <-> X = [set x | x \\in Rhull X].\nProof.\nsplit=> [iX|->]; last exact: interval_is_interval.\nrewrite predeqE => x /=; split; [exact: sub_Rhull | rewrite in_itv/=].\ncase: (asboolP (has_lbound _)) => ?; case: (asboolP (has_ubound _)) => ? //=.\n- case: asboolP => XinfX; case: asboolP => XsupX;\n    rewrite !(lteifF, lteifT).\n  + move=> /andP[]; rewrite le_eqVlt => /orP[/eqP <- //|infXx].\n    rewrite le_eqVlt => /orP[/eqP -> //|xsupX].\n    apply: (@interior_subset R).\n    by rewrite interval_bounded_interior // /mkset infXx.\n  + move=> /andP[]; rewrite le_eqVlt => /orP[/eqP <- //|infXx supXx].\n    apply: (@interior_subset R).\n    by rewrite interval_bounded_interior // /mkset infXx.\n  + move=> /andP[infXx]; rewrite le_eqVlt => /orP[/eqP -> //|xsupX].\n    apply: (@interior_subset R).\n    by rewrite interval_bounded_interior // /mkset infXx.\n  + move=> ?; apply: (@interior_subset R).\n    by rewrite interval_bounded_interior // /mkset infXx.\n- case: asboolP => XinfX; rewrite !(lteifF, lteifT, andbT).\n  + rewrite le_eqVlt => /orP[/eqP<-//|infXx].\n    apply: (@interior_subset R).\n    by rewrite interval_right_unbounded_interior.\n  + move=> infXx; apply: (@interior_subset R).\n    by rewrite interval_right_unbounded_interior.\n- case: asboolP => XsupX /=.\n  + rewrite le_eqVlt => /orP[/eqP->//|xsupX].\n    apply: (@interior_subset R).\n    by rewrite interval_left_unbounded_interior.\n  + move=> xsupX; apply: (@interior_subset R).\n    by rewrite interval_left_unbounded_interior.\n- by move=> _; rewrite (interval_unbounded_setT iX).\nQed.\n\nLemma connected_intervalP (E : set R) : connected E <-> is_interval E.\nProof.\nsplit => [cE x y Ex Ey z /andP[xz zy]|].\n- apply: contrapT => Ez.\n  pose Az := E `&` [set x | x < z]; pose Bz := E `&` [set x | z < x].\n  apply/connectedPn : cE; exists (fun b => if b then Az else Bz); split.\n  + move: xz zy Ez.\n    rewrite !le_eqVlt => /predU1P[<-//|xz] /predU1P[->//|zy] Ez.\n    by case; [exists x | exists y].\n  + rewrite /Az /Bz -setIUr; apply/esym/setIidPl => u Eu.\n    by apply/orP; rewrite -neq_lt; apply/negP; apply: contraPnot Eu => /eqP <-.\n  + split; [|rewrite setIC].\n    + apply/disjoints_subset => /= u /closureI[_]; rewrite closure_gt => zu.\n      by rewrite /Az setCI; right; apply/negP; rewrite -leNgt.\n    + apply/disjoints_subset => /= u /closureI[_]; rewrite closure_lt => zu.\n      by rewrite /Bz setCI; right; apply/negP; rewrite -leNgt.\n- apply: contraPP => /connectedPn[A [A0 EU sepA]] intE.\n  have [/= x A0x] := A0 false; have [/= y A1y] := A0 true.\n  wlog xy : A A0 EU sepA x A0x y A1y / x < y.\n    move=> /= wlog_hypo; have [xy|yx|{wlog_hypo}yx] := ltgtP x y.\n    + exact: (wlog_hypo _ _ _ _ _ A0x _ A1y).\n    + apply: (wlog_hypo (A \\o negb) _ _ _ y _ x) => //=;\n      by [rewrite setUC | rewrite separatedC].\n    + move/separated_disjoint : sepA; rewrite predeqE => /(_ x)[] + _; apply.\n      by split => //; rewrite yx.\n  pose z := sup (A false `&` [set z | x <= z <= y]).\n  have A1z : ~ (A true) z.\n    have cA0z : closure (A false) z.\n      suff : closure (A false `&` [set z | x <= z <= y]) z by case/closureI.\n      apply: closure_sup; last by exists y => u [_] /andP[].\n      by exists x; split => //; rewrite /mkset lexx /= (ltW xy).\n    by move: sepA; rewrite /separated => -[] /disjoints_subset + _; apply.\n  have /andP[xz zy] : x <= z < y.\n    rewrite sup_ub //=; [|by exists y => u [_] /andP[]|].\n    + rewrite lt_neqAle sup_le_ub ?andbT; last by move=> u [_] /andP[].\n      * by apply/negP; apply: contraPnot A1y => /eqP <-.\n      * by exists x; split => //; rewrite /mkset /= lexx /= (ltW xy).\n    + by split=> //; rewrite /mkset lexx (ltW xy).\n  have [A0z|A0z] := pselect ((A false) z); last first.\n  have {}xzy : x <= z <= y by rewrite xz ltW.\n    have : ~ E z by rewrite EU => -[].\n    by apply; apply (intE x y) => //; rewrite EU; [left|right].\n  suff [z1 [/andP[zz1 z1y] Ez1]] : exists z1 : R, z <= z1 <= y /\\ ~ E z1.\n    apply Ez1; apply (intE x y) => //; rewrite ?EU; [by left|by right|].\n    by rewrite z1y (le_trans _ zz1).\n  have [r zcA1] : {r:{posnum R}| ball z r%:num `<=` ~` closure (A true)}.\n    have ? : ~ closure (A true) z.\n      by move: sepA; rewrite /separated => -[] _ /disjoints_subset; apply.\n    have ? : open (~` closure (A true)) by exact/closed_openC/closed_closure.\n    exact/nbhsC_ball/open_nbhs_nbhs.\n  pose z1 : R := z + r%:num / 2; exists z1.\n  have z1y : z1 <= y.\n    rewrite leNgt; apply/negP => yz1.\n    suff : (~` closure (A true)) y by apply; exact: subset_closure.\n    apply zcA1; rewrite /ball /= ltr_distl (lt_le_trans zy) // ?ler_addl //.\n    rewrite andbT ltr_subl_addl addrC (lt_trans yz1) // ltr_add2l.\n    by rewrite ltr_pdivr_mulr // ltr_pmulr // ltr1n.\n  rewrite z1y andbT ler_addl; split => //.\n  have ncA1z1 : (~` closure (A true)) z1.\n    apply zcA1; rewrite /ball /= /z1 opprD addrA subrr add0r normrN.\n    by rewrite ger0_norm // ltr_pdivr_mulr // ltr_pmulr // ltr1n.\n  have nA0z1 : ~ (A false) z1.\n    move=> A0z1; have : z < z1 by rewrite /z1 ltr_addl.\n    apply/negP; rewrite -leNgt.\n     apply: sup_ub; first by exists y => u [_] /andP[].\n    by split => //; rewrite /mkset /z1 (le_trans xz) /= ?ler_addl // (ltW z1y).\n  by rewrite EU => -[//|]; apply: contra_not ncA1z1; exact: subset_closure.\nQed.\nEnd interval_realType.\n\nSection segment.\nVariable R : realType.\n\n(** properties of segments in [R] *)\n\nLemma segment_connected (a b : R) : connected `[a, b].\nProof. exact/connected_intervalP/interval_is_interval. Qed.\n\nLemma segment_compact (a b : R) : compact `[a, b].\nProof.\nhave [leab|ltba] := lerP a b; last first.\n  by move=> F FF /filter_ex [x abx]; move: ltba; rewrite (itvP abx).\nrewrite compact_cover => I D f fop sabUf.\nset B := [set x | exists2 E : {fset I}, {subset E <= D} &\n  `[a, x] `<=` \\bigcup_(i in [set` E]) f i /\\ (\\bigcup_(i in [set` E]) f i) x].\nset A := `[a, b] `&` B.\nsuff Aeab : A = `[a, b]%classic.\n  suff [_ [E ? []]] : A b by exists E.\n  by rewrite Aeab/= inE/=; apply/andP.\napply: segment_connected.\n- have aba : a \\in `[a, b] by rewrite in_itv /= lexx.\n  exists a; split=> //; have /sabUf [i /= Di fia] := aba.\n  exists [fset i]%fset; first by move=> ?; rewrite inE inE => /eqP->.\n  split; last by exists i => //=; rewrite inE.\n  move=> x /= aex; exists i; [by rewrite /= inE|suff /eqP-> : x == a by []].\n  by rewrite eq_le !(itvP aex).\n- exists B => //; rewrite openE => x [E sD [saxUf [i Di fx]]].\n  have : open (f i) by have /sD := Di; rewrite inE => /fop.\n  rewrite openE => /(_ _ fx) [e egt0 xe_fi]; exists e => // y xe_y.\n  exists E => //; split; last by exists i => //; apply/xe_fi.\n  move=> z /= ayz; have [lezx|ltxz] := lerP z x.\n    by apply/saxUf; rewrite /= in_itv/= (itvP ayz) lezx.\n  exists i => //; apply/xe_fi; rewrite /ball_/= distrC ger0_norm.\n    have lezy : z <= y by rewrite (itvP ayz).\n    rewrite ltr_subl_addl; apply: le_lt_trans lezy _; rewrite -ltr_subl_addr.\n    by have := xe_y; rewrite /ball_ => /ltr_distlC_subl.\n  by rewrite subr_ge0; apply/ltW.\nexists A; last by rewrite predeqE => x; split=> [[] | []].\nmove=> x clAx; have abx : x \\in `[a, b].\n  by apply: interval_closed; have /closureI [] := clAx.\nsplit=> //; have /sabUf [i Di fx] := abx.\nhave /fop := Di; rewrite openE => /(_ _ fx) [_ /posnumP[e] xe_fi].\nhave /clAx [y [[aby [E sD [sayUf _]]] xe_y]] := nbhsx_ballx x e.\nexists (i |` E)%fset; first by move=> j /fset1UP[->|/sD] //; rewrite inE.\nsplit=> [z axz|]; last first.\n  exists i; first by rewrite /= !inE eq_refl.\n  by apply/xe_fi; rewrite /ball_/= subrr normr0.\nhave [lezy|ltyz] := lerP z y.\n  have /sayUf [j Dj fjz] : z \\in `[a, y] by rewrite in_itv /= (itvP axz) lezy.\n  by exists j => //=; rewrite inE orbC Dj.\nexists i; first by rewrite /= !inE eq_refl.\napply/xe_fi; rewrite /ball_/= ger0_norm; last by rewrite subr_ge0 (itvP axz).\nrewrite ltr_subl_addl -ltr_subl_addr; apply: lt_trans ltyz.\nby apply: ltr_distlC_subl; rewrite distrC.\nQed.\n\nEnd segment.\n\nLemma __deprecated__ler0_addgt0P (R : numFieldType) (x : R) :\n  reflect (forall e, e > 0 -> x <= e) (x <= 0).\nProof. exact: ler_gtP. Qed.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"use `ler_gtP` instead which generalizes it to any upper bound.\")]\nNotation ler0_addgt0P := __deprecated__ler0_addgt0P.\n\nLemma IVT (R : realType) (f : R -> R) (a b v : R) :\n  a <= b -> {within `[a, b], continuous f} ->\n  minr (f a) (f b) <= v <= maxr (f a) (f b) ->\n  exists2 c, c \\in `[a, b] & f c = v.\nProof.\nmove=> leab fcont; gen have ivt : f v fcont / f a <= v <= f b ->\n    exists2 c, c \\in `[a, b] & f c = v; last first.\n  case: (leP (f a) (f b)) => [] _ fabv; first exact: ivt.\n  have [| |c cab /oppr_inj] := ivt (- f) (- v); last by exists c.\n  - by move=> x; apply: continuousN; apply: fcont.\n  - by rewrite ler_oppr opprK ler_oppr opprK andbC.\nmove=> favfb; suff: is_interval (f @` `[a,b]).\n  apply; last exact: favfb.\n  - by exists a => //=; rewrite in_itv/= lexx.\n  - by exists b => //=; rewrite in_itv/= leab lexx.\napply/connected_intervalP/connected_continuous_connected => //.\nexact: segment_connected.\nQed.\n\n(** Local properties in [R] *)\n\n(* Topology on [R]² *)\n\n(* Lemma locally_2d_align : *)\n(*   forall (P Q : R -> R -> Prop) x y, *)\n(*   ( forall eps : {posnum R}, (forall uv, ball (x, y) eps uv -> P uv.1 uv.2) -> *)\n(*     forall uv, ball (x, y) eps uv -> Q uv.1 uv.2 ) -> *)\n(*   {near x & y, forall x y, P x y} ->  *)\n(*   {near x & y, forall x y, Q x y}. *)\n(* Proof. *)\n(* move=> P Q x y /= K => /locallyP [d _ H]. *)\n(* apply/locallyP; exists d => // uv Huv. *)\n(* by apply (K d) => //. *)\n(* Qed. *)\n\n(* Lemma locally_2d_1d_const_x : *)\n(*   forall (P : R -> R -> Prop) x y, *)\n(*   locally_2d x y P -> *)\n(*   locally y (fun t => P x t). *)\n(* Proof. *)\n(* move=> P x y /locallyP [d _ Hd]. *)\n(* exists d => // z Hz. *)\n(* by apply (Hd (x, z)). *)\n(* Qed. *)\n\n(* Lemma locally_2d_1d_const_y : *)\n(*   forall (P : R -> R -> Prop) x y, *)\n(*   locally_2d x y P -> *)\n(*   locally x (fun t => P t y). *)\n(* Proof. *)\n(* move=> P x y /locallyP [d _ Hd]. *)\n(* apply/locallyP; exists d => // z Hz. *)\n(* by apply (Hd (z, y)). *)\n(* Qed. *)\n\n(* Lemma locally_2d_1d_strong (P : R -> R -> Prop) (x y : R): *)\n(*   (\\near x & y, P x y) -> *)\n(*   \\forall u \\near x & v \\near y, *)\n(*       forall (t : R), 0 <= t <= 1 -> *)\n(*       \\forall z \\near t, \\forall a \\near (x + z * (u - x)) *)\n(*                                & b \\near (y + z * (v - y)), P a b. *)\n(* Proof. *)\n(* move=> P x y. *)\n(* apply locally_2d_align => eps HP uv Huv t Ht. *)\n(* set u := uv.1. set v := uv.2. *)\n(* have Zm : 0 <= Num.max `|u - x| `|v - y| by rewrite ler_maxr 2!normr_ge0. *)\n(* rewrite ler_eqVlt in Zm. *)\n(* case/orP : Zm => Zm. *)\n(* - apply filterE => z. *)\n(*   apply/locallyP. *)\n(*   exists eps => // pq. *)\n(*   rewrite !(RminusE,RmultE,RplusE). *)\n(*   move: (Zm). *)\n(*   have : Num.max `|u - x| `|v - y| <= 0 by rewrite -(eqP Zm). *)\n(*   rewrite ler_maxl => /andP[H1 H2] _. *)\n(*   rewrite (_ : u - x = 0); last by apply/eqP; rewrite -normr_le0. *)\n(*   rewrite (_ : v - y = 0); last by apply/eqP; rewrite -normr_le0. *)\n(*   rewrite !(mulr0,addr0); by apply HP. *)\n(* - have : Num.max (`|u - x|) (`|v - y|) < eps. *)\n(*     rewrite ltr_maxl; apply/andP; split. *)\n(*     - case: Huv => /sub_ball_abs /=; by rewrite mul1r absrB. *)\n(*     - case: Huv => _ /sub_ball_abs /=; by rewrite mul1r absrB. *)\n(*   rewrite -subr_gt0 => /RltP H1. *)\n(*   set d1 := mk{posnum R} _ H1. *)\n(*   have /RltP H2 : 0 < pos d1 / 2 / Num.max `|u - x| `|v - y| *)\n(*     by rewrite mulr_gt0 // invr_gt0. *)\n(*   set d2 := mk{posnum R} _ H2. *)\n(*   exists d2 => // z Hz. *)\n(*   apply/locallyP. *)\n(*   exists [{posnum R} of d1 / 2] => //= pq Hpq. *)\n(*   set p := pq.1. set q := pq.2. *)\n(*   apply HP; split. *)\n(*   + apply/sub_abs_ball => /=. *)\n(*     rewrite absrB. *)\n(*     rewrite (_ : p - x = p - (x + z * (u - x)) + (z - t + t) * (u - x)); last first. *)\n(*       by rewrite subrK opprD addrA subrK. *)\n(*     apply: (ler_lt_trans (ler_abs_add _ _)). *)\n(*     rewrite (_ : pos eps = pos d1 / 2 + (pos eps - pos d1 / 2)); last first. *)\n(*       by rewrite addrCA subrr addr0. *)\n(*     rewrite (_ : pos eps - _ = d1) // in Hpq. *)\n(*     case: Hpq => /sub_ball_abs Hp /sub_ball_abs Hq. *)\n(*     rewrite mul1r /= (_ : pos eps - _ = d1) // !(RminusE,RplusE,RmultE,RdivE) // in Hp, Hq. *)\n(*     rewrite absrB in Hp. rewrite absrB in Hq. *)\n(*     rewrite (ltr_le_add Hp) // (ler_trans (absrM _ _)) //. *)\n(*     apply (@ler_trans _ ((pos d2 + 1) * Num.max `|u - x| `|v - y|)). *)\n(*     apply ler_pmul; [by rewrite normr_ge0 | by rewrite normr_ge0 | | ]. *)\n(*     rewrite (ler_trans (ler_abs_add _ _)) // ler_add //. *)\n(*     move/sub_ball_abs : Hz; rewrite mul1r => tzd2; by rewrite absrB ltrW. *)\n(*     rewrite absRE ger0_norm //; by case/andP: Ht. *)\n(*     by rewrite ler_maxr lerr. *)\n(*     rewrite /d2 /d1 /=. *)\n(*     set n := Num.max _ _. *)\n(*     rewrite mulrDl mul1r -mulrA mulVr ?unitfE ?lt0r_neq0 // mulr1. *)\n(*     rewrite ler_sub_addr addrAC -mulrDl -mulr2n -mulr_natr. *)\n(*     by rewrite -mulrA mulrV ?mulr1 ?unitfE // subrK. *)\n(*   + apply/sub_abs_ball => /=. *)\n(*     rewrite absrB. *)\n(*     rewrite (_ : (q - y) = (q - (y + z * (v - y)) + (z - t + t) * (v - y))); last first. *)\n(*       by rewrite subrK opprD addrA subrK. *)\n(*     apply: (ler_lt_trans (ler_abs_add _ _)). *)\n(*     rewrite (_ : pos eps = pos d1 / 2 + (pos eps - pos d1 / 2)); last first. *)\n(*       by rewrite addrCA subrr addr0. *)\n(*     rewrite (_ : pos eps - _ = d1) // in Hpq. *)\n(*     case: Hpq => /sub_ball_abs Hp /sub_ball_abs Hq. *)\n(*     rewrite mul1r /= (_ : pos eps - _ = d1) // !(RminusE,RplusE,RmultE,RdivE) // in Hp, Hq. *)\n(*     rewrite absrB in Hp. rewrite absrB in Hq. *)\n(*     rewrite (ltr_le_add Hq) // (ler_trans (absrM _ _)) //. *)\n(*     rewrite (@ler_trans _ ((pos d2 + 1) * Num.max `|u - x| `|v - y|)) //. *)\n(*     apply ler_pmul; [by rewrite normr_ge0 | by rewrite normr_ge0 | | ]. *)\n(*     rewrite (ler_trans (ler_abs_add _ _)) // ler_add //. *)\n(*     move/sub_ball_abs : Hz; rewrite mul1r => tzd2; by rewrite absrB ltrW. *)\n(*     rewrite absRE ger0_norm //; by case/andP: Ht. *)\n(*     by rewrite ler_maxr lerr orbT. *)\n(*     rewrite /d2 /d1 /=. *)\n(*     set n := Num.max _ _. *)\n(*     rewrite mulrDl mul1r -mulrA mulVr ?unitfE ?lt0r_neq0 // mulr1. *)\n(*     rewrite ler_sub_addr addrAC -mulrDl -mulr2n -mulr_natr. *)\n(*     by rewrite -mulrA mulrV ?mulr1 ?unitfE // subrK. *)\n(* Qed. *)\n(* Admitted. *)\n\n(* TODO redo *)\n(* Lemma locally_2d_1d (P : R -> R -> Prop) x y : *)\n(*   locally_2d x y P -> *)\n(*   locally_2d x y (fun u v => forall t, 0 <= t <= 1 -> locally_2d (x + t * (u - x)) (y + t * (v - y)) P). *)\n(* Proof. *)\n(* move/locally_2d_1d_strong. *)\n(* apply: locally_2d_impl. *)\n(* apply locally_2d_forall => u v H t Ht. *)\n(* specialize (H t Ht). *)\n(* have : locally t (fun z => locally_2d (x + z * (u - x)) (y + z * (v - y)) P) by []. *)\n(* by apply: locally_singleton. *)\n(* Qed. *)\n\n(* TODO redo *)\n(* Lemma locally_2d_ex_dec : *)\n(*   forall P x y, *)\n(*   (forall x y, P x y \\/ ~P x y) -> *)\n(*   locally_2d x y P -> *)\n(*   {d : {posnum R} | forall u v, `|u - x| < d -> `|v - y| < d -> P u v}. *)\n(* Proof. *)\n(* move=> P x y P_dec H. *)\n(* destruct (@locally_ex _ (x, y) (fun z => P (fst z) (snd z))) as [d Hd]. *)\n(* - move: H => /locallyP [e _ H]. *)\n(*   by apply/locallyP; exists e. *)\n(* exists d=>  u v Hu Hv. *)\n(* by apply (Hd (u, v)) => /=; split; apply sub_abs_ball; rewrite absrB. *)\n(* Qed. *)\n\nLemma compact_bounded (K : realType) (V : normedModType K) (A : set V) :\n  compact A -> bounded_set A.\nProof.\nrewrite compact_cover => Aco.\nhave covA : A `<=` \\bigcup_(n : int) [set p | `|p| < n%:~R].\n  by move=> p _; exists (floor `|p| + 1) => //; rewrite rmorphD/= lt_succ_floor.\nhave /Aco [] := covA.\n  move=> n _; rewrite openE => p; rewrite /= -subr_gt0 => ltpn.\n  apply/nbhs_ballP; exists (n%:~R - `|p|) => // q.\n  rewrite -ball_normE /= ltr_subr_addr distrC; apply: le_lt_trans.\n  by rewrite -{1}(subrK p q) ler_norm_add.\nmove=> D _ DcovA.\nexists (\\big[maxr/0]_(i : D) (fsval i)%:~R).\nrewrite bigmax_real//; last by move=> ? _; rewrite realz.\nsplit => // x ltmaxx p /DcovA [n Dn /lt_trans /(_ _)/ltW].\napply; apply: le_lt_trans ltmaxx.\nhave : n \\in enum_fset D by [].\nby rewrite enum_fsetE => /mapP[/= i iD ->]; exact/le_bigmax.\nQed.\n\nLemma rV_compact (T : topologicalType) n (A : 'I_n.+1 -> set T) :\n  (forall i, compact (A i)) ->\n  compact [ set v : 'rV[T]_n.+1 | forall i, A i (v ord0 i)].\nProof.\nmove=> Aico.\nhave : @compact (product_topologicalType _) [set f | forall i, A i (f i)].\n  by apply: tychonoff.\nmove=> Aco F FF FA.\nset G := [set [set f : 'I_n.+1 -> T | B (\\row_j f j)] | B in F].\nhave row_simpl (v : 'rV[T]_n.+1) : \\row_j (v ord0 j) = v.\n  by apply/rowP => ?; rewrite mxE.\nhave row_simpl' (f : 'I_n.+1 -> T) : (\\row_j f j) ord0 = f.\n  by rewrite funeqE=> ?; rewrite mxE.\nhave [f [Af clGf]] : [set f | forall i, A i (f i)] `&`\n  @cluster (product_topologicalType _) G !=set0.\n  suff GF : ProperFilter G.\n    apply: Aco; exists [set v : 'rV[T]_n.+1 | forall i, A i (v ord0 i)] => //.\n    by rewrite predeqE => f; split => Af i; [have := Af i|]; rewrite row_simpl'.\n  apply Build_ProperFilter.\n    move=> _ [C FC <-]; have /filter_ex [v Cv] := FC.\n    by exists (v ord0); rewrite /= row_simpl.\n  split.\n  - by exists setT => //; apply: filterT.\n  - by move=> _ _ [C FC <-] [D FD <-]; exists (C `&` D) => //; apply: filterI.\n  move=> C D sCD [E FE EeqC]; exists [set v : 'rV[T]_n.+1 | D (v ord0)].\n    by apply: filterS FE => v Ev; apply/sCD; rewrite -EeqC/= row_simpl.\n  by rewrite predeqE => ? /=; rewrite row_simpl'.\nexists (\\row_j f j); split; first by move=> i; rewrite mxE; apply: Af.\nmove=> C D FC f_D; have {}f_D :\n  nbhs (f : product_topologicalType _) [set g | D (\\row_j g j)].\n  have [E f_E sED] := f_D; rewrite nbhsE.\n  set Pj := fun j Bj => open_nbhs (f j) Bj /\\ Bj `<=` E ord0 j.\n  have exPj : forall j, exists Bj, open_nbhs (f j) Bj /\\ Bj `<=` E ord0 j.\n    move=> j; have := f_E ord0 j; rewrite nbhsE => - [Bj].\n    by rewrite row_simpl'; exists Bj.\n  exists [set g | forall j, (get (Pj j)) (g j)]; last first.\n    move=> g Pg; apply: sED => i j; rewrite ord1 row_simpl'.\n    by have /getPex [_ /(_ _ (Pg j))] := exPj j.\n  split; last by move=> j; have /getPex [[]] := exPj j.\n  exists [set [set g | forall j, get (Pj j) (g j)] | k in [set x | 'I_n.+1 x]];\n    last first.\n    rewrite predeqE => g; split; first by move=> [_ [_ _ <-]].\n    move=> Pg; exists [set g | forall j, get (Pj j) (g j)] => //.\n    by exists ord0.\n  move=> _ [_ _ <-]; set s := [seq (@^~ j) @^-1` (get (Pj j)) | j : 'I_n.+1].\n  exists [fset x in s]%fset.\n    move=> B'; rewrite in_fset => /mapP [j _ ->]; rewrite inE.\n    exists j => //; exists (get (Pj j)) => //.\n    by have /getPex [[]] := exPj j.\n  rewrite predeqE => g; split=> [Ig j|Ig B'].\n    apply: (Ig ((@^~ j) @^-1` (get (Pj j)))).\n    by rewrite /= in_fset; apply/mapP; exists j => //; rewrite mem_enum.\n  by rewrite /= in_fset => /mapP [j _ ->]; apply: Ig.\nhave GC : G [set g | C (\\row_j g j)] by exists C.\nby have [g []] := clGf _ _ GC f_D; exists (\\row_j (g j : T)).\nQed.\n\nLemma bounded_closed_compact (R : realType) n (A : set 'rV[R]_n.+1) :\n  bounded_set A -> closed A -> compact A.\nProof.\nmove=> [M [Mreal normAltM]] Acl.\nhave Mnco : compact\n  [set v : 'rV[R]_n.+1 | forall i, v ord0 i \\in `[(- (M + 1)), (M + 1)]].\n  apply: (@rV_compact _  _ (fun _ => `[(- (M + 1)), (M + 1)]%classic)).\n  by move=> _; apply: segment_compact.\napply: subclosed_compact Acl Mnco _ => v /normAltM normvleM i.\nsuff : `|v ord0 i : R| <= M + 1 by rewrite ler_norml.\napply: le_trans (normvleM _ _); last by rewrite ltr_addl.\nhave /mapP[j Hj ->] : `|v ord0 i| \\in [seq `|v x.1 x.2| | x : 'I_1 * 'I_n.+1].\n  by apply/mapP; exists (ord0, i) => //=; rewrite mem_enum.\nby rewrite [leRHS]/normr /= mx_normrE; apply/bigmax_geP; right => /=; exists j.\nQed.\n\n\n(** * Some limits on real functions *)\n\nSection Shift.\n\nContext {R : zmodType} {T : Type}.\n\nDefinition shift (x y : R) := y + x.\nNotation center c := (shift (- c)).\nArguments shift x / y.\n\nLemma comp_shiftK (x : R) (f : R -> T) : (f \\o shift x) \\o center x = f.\nProof. by rewrite funeqE => y /=; rewrite addrNK. Qed.\n\nLemma comp_centerK (x : R) (f : R -> T) : (f \\o center x) \\o shift x = f.\nProof. by rewrite funeqE => y /=; rewrite addrK. Qed.\n\nLemma shift0 : shift 0 = id.\nProof. by rewrite funeqE => x /=; rewrite addr0. Qed.\n\nLemma center0 : center 0 = id.\nProof. by rewrite oppr0 shift0. Qed.\n\nEnd Shift.\nArguments shift {R} x / y.\nNotation center c := (shift (- c)).\n\nLemma near_shift {K : numDomainType} {R : normedModType K}\n   (y x : R) (P : set R) :\n   (\\near x, P x) = (\\forall z \\near y, (P \\o shift (x - y)) z).\nProof.\nrewrite propeqE nbhs0P [X in _ <-> X]nbhs0P/= -propeqE.\nby apply: eq_near => e; rewrite ![_ + e]addrC addrACA subrr addr0.\nQed.\n\nLemma cvg_comp_shift {T : Type} {K : numDomainType} {R : normedModType K}\n  (x y : R) (f : R -> T) :\n  (f \\o shift x) @ y = f @ (y + x).\nProof.\nrewrite funeqE => A; rewrite /= !near_simpl (near_shift (y + x)).\nby rewrite (_ : _ \\o _ = A \\o f) // funeqE=> z; rewrite /= opprD addNKr addrNK.\nQed.\n\nSection continuous.\nVariables (K : numFieldType) (U V : normedModType K).\n\nLemma continuous_shift (f : U -> V) u :\n  {for u, continuous f} = {for 0, continuous (f \\o shift u)}.\nProof. by rewrite [in RHS]forE /= add0r cvg_comp_shift add0r. Qed.\n\nLemma continuous_withinNshiftx (f : U -> V) u :\n  f \\o shift u @ 0^' --> f u <-> {for u, continuous f}.\nProof.\nrewrite continuous_shift; split=> [cfu|].\n  by apply/(continuous_withinNx _ _).2/(cvg_trans cfu); rewrite /= add0r.\nby move/(continuous_withinNx _ _).1/cvg_trans; apply; rewrite /= add0r.\nQed.\n\nEnd continuous.\n\nSection Closed_Ball.\n\nLemma ball_open (R : numDomainType) (V : normedModType R) (x : V) (r : R) :\n  0 < r -> open (ball x r).\nProof.\nrewrite openE -ball_normE /interior => r0 y /= Bxy; near=> z.\nrewrite /= (le_lt_trans (ler_dist_add y _ _)) // addrC -ltr_subr_addr.\nby near: z; apply: cvgr_dist_lt; rewrite // subr_gt0.\nUnshelve. all: by end_near. Qed.\n\nDefinition closed_ball_ (R : numDomainType) (V : zmodType) (norm : V -> R)\n  (x : V) (e : R) := [set y | norm (x - y) <= e].\n\nLemma closed_closed_ball_ (R : realFieldType) (V : normedModType R)\n  (x : V) (e : R) : closed (closed_ball_ normr x e).\nProof.\nrewrite /closed_ball_ -/((normr \\o (fun y => x - y)) @^-1` [set x | x <= e]).\napply: (closed_comp _ (@closed_le _ _)) => y _.\napply: (continuous_comp _ (@norm_continuous _ _ _)).\nexact: (continuousB (@cst_continuous _ _ _ _)).\nQed.\n\nDefinition closed_ball (R : numDomainType) (V : pseudoMetricType R)\n  (x : V) (e : R) := closure (ball x e).\n\nLemma closed_ballxx (R: numDomainType) (V : pseudoMetricType R) (x : V)\n  (e : R) : 0 < e -> closed_ball x e x.\nProof. by move=> ?; exact/subset_closure/ballxx. Qed.\n\nLemma closed_ballE (R : realFieldType) (V : normedModType R) (x : V)\n  (r : R) : 0 < r -> closed_ball x r = closed_ball_ normr x r.\nProof.\nmove=> /posnumP[e]; rewrite eqEsubset; split => y.\n  rewrite /closed_ball closureE; apply; split; first exact: closed_closed_ball_.\n  by move=> z; rewrite -ball_normE; exact: ltW.\nhave [-> _|xy] := eqVneq x y; first exact: closed_ballxx.\nrewrite /closed_ball closureE -ball_normE.\nrewrite /closed_ball_ /= le_eqVlt.\nmove => /orP[/eqP xye B [Bc Be]|xye _ [_ /(_ _ xye)]//].\napply: Bc => B0 /nbhs_ballP[s s0] B0y.\nhave [es|se] := leP s e%:num; last first.\n  exists x; split; first by apply: Be; rewrite ball_normE; apply: ballxx.\n  by apply: B0y; rewrite -ball_normE /ball_ /= distrC xye.\nexists (y + (s / 2) *: (`|x - y|^-1 *: (x - y))); split; [apply: Be|apply: B0y].\n  rewrite /= opprD addrA -[X in `|X - _|](scale1r (x - y)) scalerA -scalerBl.\n  rewrite -[X in X - _](@divrr _ `|x - y|) ?unitfE ?normr_eq0 ?subr_eq0//.\n  rewrite -mulrBl -scalerA normrZ normfZV ?subr_eq0// mulr1.\n  rewrite gtr0_norm; first by rewrite ltr_subl_addl xye ltr_addr mulr_gt0.\n  by rewrite subr_gt0 xye ltr_pdivr_mulr // mulr_natr mulr2n ltr_spaddl.\nrewrite -ball_normE /ball_ /= opprD addrA addrN add0r normrN normrZ.\nrewrite normfZV ?subr_eq0// mulr1 normrM (gtr0_norm s0) gtr0_norm //.\nby rewrite ltr_pdivr_mulr // ltr_pmulr // ltr1n.\nQed.\n\nLemma closed_ball_closed (R : realFieldType) (V : normedModType R) (x : V)\n  (r : R) : 0 < r -> closed (closed_ball x r).\nProof. by move => r0; rewrite closed_ballE //; exact: closed_closed_ball_. Qed.\n\nLemma closed_ballR_compact (R : realType) (x e : R) : 0 < e ->\n  compact (closed_ball x e).\nProof.\nmove=> e_gt0; have : compact `[x - e, x + e] by apply: segment_compact.\nby rewrite closed_ballE//; under eq_set do rewrite in_itv -ler_distlC.\nQed.\n\nLemma closed_ball_subset (R : realFieldType) (M : normedModType R) (x : M)\n  (r0 r1 : R) : 0 < r0 -> r0 < r1 -> closed_ball x r0 `<=` ball x r1.\nProof.\nmove=> r00 r01; rewrite (_ : r0 = (PosNum r00)%:num) // closed_ballE //.\nby move=> m xm; rewrite -ball_normE /ball_ /= (le_lt_trans _ r01).\nQed.\n\nLemma nbhs_closedballP (R : realFieldType) (M : normedModType R) (B : set M)\n  (x : M) : nbhs x B <-> exists (r : {posnum R}), closed_ball x r%:num `<=` B.\nProof.\nsplit=> [/nbhs_ballP[_/posnumP[r] xrB]|[e xeB]]; last first.\n  apply/nbhs_ballP; exists e%:num => //=.\n  exact: (subset_trans (@subset_closure _ _) xeB).\nexists (r%:num / 2)%:sgn.\napply: (subset_trans (closed_ball_subset _ _) xrB) => //=.\nby rewrite lter_pdivr_mulr // ltr_pmulr // ltr1n.\nQed.\n\nLemma subset_closed_ball (R : realFieldType) (V : normedModType R) (x : V)\n  (r : R) : 0 < r -> ball x r `<=` closed_ball x r.\nProof. move=> r0; rewrite /closed_ball; apply: subset_closure. Qed.\n\nLemma locally_compactR (R : realType) : locally_compact [set: R].\nProof.\nmove=> x _; rewrite withinET; exists (closed_ball x 1).\n  by apply/nbhs_closedballP; exists 1%:pos.\nby split; [apply: closed_ballR_compact | apply: closed_ball_closed].\nQed.\n\n(*TBA topology.v once ball_normE is there*)\n\nLemma interior_closed_ballE (R : realType) (V : normedModType R) (x : V)\n  (r : R) : 0 < r -> (closed_ball x r)^° = ball x r.\nProof.\nmove=> r0; rewrite eqEsubset; split; last first.\n  by rewrite -open_subsetE; [exact: subset_closure | exact: ball_open].\nmove=> /= t; rewrite closed_ballE // /interior /= -nbhs_ballE => [[]] s s0.\nhave [-> _|nxt] := eqVneq t x; first exact: ballxx.\nnear ((0 : R^o)^') => e; rewrite -ball_normE /closed_ball_ => tsxr.\npose z := t + `|e| *: (t - x); have /tsxr /= : `|t - z| < s.\n  rewrite distrC addrAC subrr add0r normrZ normr_id.\n  rewrite -ltr_pdivl_mulr ?(normr_gt0,subr_eq0) //.\n  by near: e; apply/dnbhs0_lt; rewrite divr_gt0 // normr_gt0 subr_eq0.\nrewrite /z opprD addrA -scalerN -{1}(scale1r (x - t)) opprB -scalerDl normrZ.\napply lt_le_trans; rewrite ltr_pmull; last by rewrite normr_gt0 subr_eq0 eq_sym.\nby rewrite ger0_norm // ltr_addl normr_gt0; near: e; exists 1 => /=.\nUnshelve. all: by end_near. Qed.\n\nLemma open_nbhs_closed_ball (R : realType) (V : normedModType R) (x : V)\n  (r : R) : 0 < r -> open_nbhs x (closed_ball x r)^°.\nProof.\nmove=> r0; split; first exact: open_interior.\nby rewrite interior_closed_ballE //; exact: ballxx.\nQed.\n\nEnd Closed_Ball.\n\n(* multi-rule bound_in_itv already exists in interval.v, but we\n  advocate that it should actually have the following statement.\n  This does not expose the order between interval bounds. *)\nLemma bound_itvE (R : numDomainType) (a b : R) :\n  ((a \\in `[a, b]) = (a <= b)) *\n  ((b \\in `[a, b]) = (a <= b)) *\n  ((a \\in `[a, b[) = (a < b)) *\n  ((b \\in `]a, b]) = (a < b)) *\n  (a \\in `[a, +oo[) *\n  (a \\in `]-oo, a]).\nProof. by rewrite !(boundr_in_itv, boundl_in_itv). Qed.\n\nLemma near_in_itv {R : realFieldType} (a b : R) :\n  {in `]a, b[, forall y, \\forall z \\near y, z \\in `]a, b[}.\nProof. exact: interval_open. Qed.\n\nNotation \"f @`[ a , b ]\" :=\n  (`[minr (f a) (f b), maxr (f a) (f b)]) : ring_scope.\nNotation \"f @`[ a , b ]\" :=\n  (`[minr (f a) (f b), maxr (f a) (f b)]%classic) : classical_set_scope.\nNotation \"f @`] a , b [\" :=\n  (`](minr (f a) (f b)), (maxr (f a) (f b))[) : ring_scope.\nNotation \"f @`] a , b [\" :=\n  (`](minr (f a) (f b)), (maxr (f a) (f b))[%classic) : classical_set_scope.\n\nSection image_interval.\nVariable R : realDomainType.\nImplicit Types (a b : R) (f : R -> R).\n\nLemma mono_mem_image_segment a b f : monotonous `[a, b] f ->\n  {homo f : x / x \\in `[a, b] >-> x \\in f @`[a, b]}.\nProof.\nmove=> [fle|fge] x xab; have leab : a <= b by rewrite (itvP xab).\n  have: f a <= f b by rewrite fle ?bound_itvE.\n  by case: leP => // fafb _; rewrite in_itv/= !fle ?(itvP xab).\nhave: f a >= f b by rewrite fge ?bound_itvE.\nby case: leP => // fafb _; rewrite in_itv/= !fge ?(itvP xab).\nQed.\n\nLemma mono_mem_image_itvoo a b f : monotonous `[a, b] f ->\n  {homo f : x / x \\in `]a, b[ >-> x \\in f @`]a, b[}.\nProof.\nmove=> []/[dup] => [/leW_mono_in|/leW_nmono_in] flt fle x xab;\n    have ltab : a < b by rewrite (itvP xab).\n  have: f a <= f b by rewrite ?fle ?bound_itvE ?ltW.\n  by case: leP => // fafb _; rewrite in_itv/= ?flt ?in_itv/= ?(itvP xab, lexx).\nhave: f a >= f b by rewrite fle ?bound_itvE ?ltW.\nby case: leP => // fafb _; rewrite in_itv/= ?flt ?in_itv/= ?(itvP xab, lexx).\nQed.\n\nLemma mono_surj_image_segment a b f : a <= b ->\n    monotonous `[a, b] f -> set_surj `[a, b] (f @`[a, b]) f ->\n  f @` `[a, b] = f @`[a, b]%classic.\nProof.\nmove=> leab fmono; apply: surj_image_eq => _ /= [x xab <-];\nexact: mono_mem_image_segment.\nQed.\n\nLemma inc_segment_image a b f : f a <= f b -> f @`[a, b] = `[f a, f b].\nProof. by case: ltrP. Qed.\n\nLemma dec_segment_image a b f : f b <= f a -> f @`[a, b] = `[f b, f a].\nProof. by case: ltrP. Qed.\n\nLemma inc_surj_image_segment a b f : a <= b ->\n    {in `[a, b] &, {mono f : x y / x <= y}} ->\n    set_surj `[a, b] `[f a, f b] f ->\n  f @` `[a, b] = `[f a, f b]%classic.\nProof.\nmove=> leab fle f_surj; have fafb : f a <= f b by rewrite fle ?bound_itvE.\nby rewrite mono_surj_image_segment ?inc_segment_image//; left.\nQed.\n\nLemma dec_surj_image_segment a b f : a <= b ->\n    {in `[a, b] &, {mono f : x y /~ x <= y}} ->\n    set_surj `[a, b] `[f b, f a] f ->\n  f @` `[a, b] = `[f b, f a]%classic.\nProof.\nmove=> leab fge f_surj; have fafb : f b <= f a by rewrite fge ?bound_itvE.\nby rewrite mono_surj_image_segment ?dec_segment_image//; right.\nQed.\n\nLemma inc_surj_image_segmentP a b f : a <= b ->\n    {in `[a, b] &, {mono f : x y / x <= y}} ->\n    set_surj `[a, b] `[f a, f b] f ->\n  forall y, reflect (exists2 x, x \\in `[a, b] & f x = y) (y \\in `[f a, f b]).\nProof.\nmove=> /inc_surj_image_segment/[apply]/[apply]/predeqP + y => /(_ y) fab.\nby apply/(equivP idP); symmetry.\nQed.\n\nLemma dec_surj_image_segmentP a b f : a <= b ->\n    {in `[a, b] &, {mono f : x y /~ x <= y}} ->\n    set_surj `[a, b] `[f b, f a] f ->\n  forall y, reflect (exists2 x, x \\in `[a, b] & f x = y) (y \\in `[f b, f a]).\nProof.\nmove=> /dec_surj_image_segment/[apply]/[apply]/predeqP + y => /(_ y) fab.\nby apply/(equivP idP); symmetry.\nQed.\n\nLemma mono_surj_image_segmentP a b f : a <= b ->\n    monotonous `[a, b] f -> set_surj `[a, b] (f @`[a, b]) f ->\n  forall y, reflect (exists2 x, x \\in `[a, b] & f x = y) (y \\in f @`[a, b]).\nProof.\nmove=> /mono_surj_image_segment/[apply]/[apply]/predeqP + y => /(_ y) fab.\nby apply/(equivP idP); symmetry.\nQed.\n\nEnd image_interval.\n\nSection LinearContinuousBounded.\n\nVariables (R : numFieldType) (V W : normedModType R).\n\nLemma linear_boundedP (f : {linear V -> W}) : bounded_near f (nbhs 0) <->\n  \\forall r \\near +oo, forall x, `|f x| <= r * `|x|.\nProof.\nsplit=> [|/pinfty_ex_gt0 [r r0 Bf]]; last first.\n  apply/ex_bound; exists r; apply/nbhs_norm0P; exists 1 => //= x /=.\n  by rewrite -(gtr_pmulr _ r0) => /ltW; exact/le_trans/Bf.\nrewrite /bounded_near => /pinfty_ex_gt0 [M M0 /nbhs_norm0P [_/posnumP[e] efM]].\nnear (0 : R)^'+ => d; near=> r => x.\nhave[->|x0] := eqVneq x 0; first by rewrite raddf0 !normr0 mulr0.\nhave nd0 : d / `|x| > 0 by rewrite divr_gt0 ?normr_gt0.\nhave: `|f (d / `|x| *: x)| <= M.\n  by apply: efM => /=; rewrite normrZ gtr0_norm// divfK ?normr_eq0//.\nrewrite linearZ/= normrZ gtr0_norm// -ler_pdivl_mull//; move/le_trans; apply.\nrewrite invfM invrK mulrAC ler_wpmul2r//; near: r; apply: nbhs_pinfty_ge.\nby rewrite rpredM// ?rpredV ?gtr0_real.\nUnshelve. all: by end_near. Qed.\n\nLemma continuous_linear_bounded (x : V) (f : {linear V -> W}) :\n  {for 0, continuous f} -> bounded_near f (nbhs x).\nProof.\nrewrite /prop_for linear0 /bounded_near => f0; near=> M; apply/nbhs0P.\nnear do rewrite /= linearD (le_trans (ler_norm_add _ _))// -ler_subr_addl.\nby apply: cvgr0_norm_le; rewrite // subr_gt0.\nUnshelve. all: by end_near. Qed.\n\nLemma __deprecated__linear_continuous0 (f : {linear V -> W}) :\n  {for 0, continuous f} -> bounded_near f (nbhs (0 : V)).\nProof. exact: continuous_linear_bounded. Qed.\n\nLemma bounded_linear_continuous (f : {linear V -> W}) :\n  bounded_near f (nbhs (0 : V)) -> continuous f.\nProof.\nmove=> /linear_boundedP [y [yreal fr]] x; near +oo_R => r.\napply/(@cvgrPdist_lt _ _ _ (nbhs x)) => e e_gt0; near=> z; rewrite -linearB.\nrewrite (le_lt_trans (fr r _ _))// -?ltr_pdivl_mull//.\nby near: z; apply: cvgr_dist_lt => //; rewrite mulrC divr_gt0.\nUnshelve. all: by end_near. Qed.\n\nLemma __deprecated__linear_bounded0 (f : {linear V -> W}) :\n  bounded_near f (nbhs (0 : V)) -> {for 0, continuous f}.\nProof. by move=> ? ?; exact: bounded_linear_continuous. Qed.\n\nLemma continuousfor0_continuous (f : {linear V -> W}) :\n  {for 0, continuous f} -> continuous f.\nProof. by move=> /continuous_linear_bounded/bounded_linear_continuous. Qed.\n\nLemma linear_bounded_continuous (f : {linear V -> W}) :\n  bounded_near f (nbhs 0) <-> continuous f.\nProof.\nsplit; first exact: bounded_linear_continuous.\nby move=> /(_ 0); apply: continuous_linear_bounded.\nQed.\n\nLemma bounded_funP (f : {linear V -> W}) :\n  (forall r, exists M, forall x, `|x| <= r -> `|f x| <= M) <->\n  bounded_near f (nbhs (0 : V)).\nProof.\nsplit => [/(_ 1) [M Bf]|/linear_boundedP fr y].\n  apply/ex_bound; exists M; apply/nbhs_normP => /=; exists 1 => //= x /=.\n  by rewrite sub0r normrN => x1; exact/Bf/ltW.\nnear +oo_R => r; exists (r * y) => x xe.\nrewrite (@le_trans _ _ (r * `|x|)) //; first by move: {xe} x; near: r.\nby rewrite ler_pmul //.\nUnshelve. all: by end_near. Qed.\n\nEnd LinearContinuousBounded.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"generalized to `continuous_linear_bounded`\")]\nNotation linear_continuous0 := __deprecated__linear_continuous0.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"generalized to `bounded_linear_continuous`\")]\nNotation linear_bounded0 := __deprecated__linear_bounded0.\n", "meta": {"author": "math-comp", "repo": "analysis", "sha": "ee12aba894e8949a32daa9d2ee72b3a440c0609f", "save_path": "github-repos/coq/math-comp-analysis", "path": "github-repos/coq/math-comp-analysis/analysis-ee12aba894e8949a32daa9d2ee72b3a440c0609f/theories/normedtype.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.69567091549478}}
{"text": "Definition id {A : Type} (a : A) : A := a.\n\nDefinition compose {A B C : Type} (g : B -> C) (f : A -> B): A -> C :=\n    fun (a : A) => g (f a).\n\nAxiom extensional_equality : forall (A B : Type)\n (f : A -> B)\n (f': A -> B),\n (forall x, f x = f' x) ->\n  f = f'.\n\nTheorem compose_left_identity\n    : forall (A B : Type) (f : A -> B)\n    , compose id f = f.\nProof.\n    intros.\n    apply extensional_equality.\n    intros.\n    unfold compose.\n    unfold id.\n    reflexivity.\nQed.\n\nTheorem compose_right_identity\n    : forall (A B : Type) (f : A -> B)\n    , compose f id = f.\nProof.\n    intros.\n    apply extensional_equality.\n    intros.\n    unfold compose.\n    unfold id.\n    reflexivity.\nQed.\n", "meta": {"author": "domdere", "repo": "haskell-coq", "sha": "83c7ffec0fb78a246d350621ff5c76577916d417", "save_path": "github-repos/coq/domdere-haskell-coq", "path": "github-repos/coq/domdere-haskell-coq/haskell-coq-83c7ffec0fb78a246d350621ff5c76577916d417/src/classes/Function.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.6956626530067884}}
{"text": "(** * StlcProp: Properties of STLC *)\n\nRequire Import SF.SfLib.\nRequire Import SF.Maps.\nRequire Import SF.Types.\nRequire Import SF.Stlc.\nRequire Import SF.Smallstep.\nModule STLCProp.\nImport STLC.\n\n(** In this chapter, we develop the fundamental theory of the Simply\n    Typed Lambda Calculus -- in particular, the type safety\n    theorem. *)\n\n(* ###################################################################### *)\n(** * Canonical Forms *)\n\n(** As we saw for the simple calculus in the [Types] chapter, the\n    first step in establishing basic properties of reduction and types\n    is to identify the possible _canonical forms_ (i.e., well-typed\n    closed values) belonging to each type.  For [Bool], these are the boolean\n    values [ttrue] and [tfalse].  For arrow types, the canonical forms\n    are lambda-abstractions.  *)\n\nLemma canonical_forms_bool : forall t,\n  empty |- t \\in TBool ->\n  value t ->\n  (t = ttrue) \\/ (t = tfalse).\nProof.\n  intros t HT HVal.\n  inversion HVal; intros; subst; try inversion HT; auto.\nQed.\n\nLemma canonical_forms_fun : forall t T1 T2,\n  empty |- t \\in (TArrow T1 T2) ->\n  value t ->\n  exists x u, t = tabs x T1 u.\nProof.\n  intros t T1 T2 HT HVal.\n  inversion HVal; intros; subst; try inversion HT; subst; auto.\n  exists x0. exists t0.  auto.\nQed.\n\n(* ###################################################################### *)\n(** * Progress *)\n\n(** As before, the _progress_ theorem tells us that closed, well-typed\n    terms are not stuck: either a well-typed term is a value, or it\n    can take a reduction step.  The proof is a relatively\n    straightforward extension of the progress proof we saw in the\n    [Types] chapter.  We'll give the proof in English first, then the\n    formal version. *)\n\nTheorem progress : forall t T,\n     empty |- t \\in T ->\n     value t \\/ exists t', t ==> t'.\n\n(** _Proof_: By induction on the derivation of [|- t \\in T].\n\n    - The last rule of the derivation cannot be [T_Var], since a\n      variable is never well typed in an empty context.\n\n    - The [T_True], [T_False], and [T_Abs] cases are trivial, since in\n      each of these cases we can see by inspecting the rule that [t]\n      is a value.\n\n    - If the last rule of the derivation is [T_App], then [t] has the\n      form [t1 t2] for som e[t1] and [t2], where we know that [t1] and\n      [t2] are also well typed in the empty context; in particular,\n      there exists a type [T2] such that [|- t1 \\in T2 -> T] and [|-\n      t2 \\in T2].  By the induction hypothesis, either [t1] is a value\n      or it can take a reduction step.\n\n        - If [t1] is a value, then consider [t2], which by the other\n          induction hypothesis must also either be a value or take a step.\n\n            - Suppose [t2] is a value.  Since [t1] is a value with an\n              arrow type, it must be a lambda abstraction; hence [t1\n              t2] can take a step by [ST_AppAbs].\n\n            - Otherwise, [t2] can take a step, and hence so can [t1\n              t2] by [ST_App2].\n\n        - If [t1] can take a step, then so can [t1 t2] by [ST_App1].\n\n    - If the last rule of the derivation is [T_If], then [t = if t1\n      then t2 else t3], where [t1] has type [Bool].  By the IH, [t1]\n      either is a value or takes a step.\n\n        - If [t1] is a value, then since it has type [Bool] it must be\n          either [true] or [false].  If it is [true], then [t] steps\n          to [t2]; otherwise it steps to [t3].\n\n        - Otherwise, [t1] takes a step, and therefore so does [t] (by\n          [ST_If]). *)\n\nProof with eauto.\n  intros t T Ht.\n  remember (@empty ty) as Gamma.\n  induction Ht; subst Gamma...\n  - (* T_Var *)\n    (* contradictory: variables cannot be typed in an\n       empty context *)\n    inversion H.\n\n  - (* T_App *)\n    (* [t] = [t1 t2].  Proceed by cases on whether [t1] is a\n       value or steps... *)\n    right. destruct IHHt1...\n    + (* t1 is a value *)\n      destruct IHHt2...\n      * (* t2 is also a value *)\n        assert (exists x0 t0, t1 = tabs x0 T11 t0).\n        eapply canonical_forms_fun; eauto.\n        destruct H1 as [x0 [t0 Heq]]. subst.\n        exists ([x0:=t2]t0)...\n\n      * (* t2 steps *)\n        inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...\n\n    + (* t1 steps *)\n      inversion H as [t1' Hstp]. exists (tapp t1' t2)...\n\n  - (* T_If *)\n    right. destruct IHHt1...\n\n    + (* t1 is a value *)\n      destruct (canonical_forms_bool t1); subst; eauto.\n\n    + (* t1 also steps *)\n      inversion H as [t1' Hstp]. exists (tif t1' t2 t3)...\nQed.\n\n(** **** Exercise: 3 stars, optional (progress_from_term_ind)  *)\n(** Show that progress can also be proved by induction on terms\n    instead of induction on typing derivations. *)\n\nTheorem progress' : forall t T,\n     empty |- t \\in T ->\n     value t \\/ exists t', t ==> t'.\nProof.\n  intros t.\n  induction t; intros T Ht; auto.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################################### *)\n(** * Preservation *)\n\n(** The other half of the type soundness property is the preservation\n    of types during reduction.  For this, we need to develop some\n    technical machinery for reasoning about variables and\n    substitution.  Working from top to bottom (from the high-level\n    property we are actually interested in to the lowest-level\n    technical lemmas that are needed by various cases of the more\n    interesting proofs), the story goes like this:\n\n      - The _preservation theorem_ is proved by induction on a typing\n        derivation, pretty much as we did in the [Types] chapter.  The\n        one case that is significantly different is the one for the\n        [ST_AppAbs] rule, whose definition uses the substitution\n        operation.  To see that this step preserves typing, we need to\n        know that the substitution itself does.  So we prove a...\n\n      - _substitution lemma_, stating that substituting a (closed)\n        term [s] for a variable [x] in a term [t] preserves the type\n        of [t].  The proof goes by induction on the form of [t] and\n        requires looking at all the different cases in the definition\n        of substitition.  This time, the tricky cases are the ones for\n        variables and for function abstractions.  In both cases, we\n        discover that we need to take a term [s] that has been shown\n        to be well-typed in some context [Gamma] and consider the same\n        term [s] in a slightly different context [Gamma'].  For this\n        we prove a...\n\n      - _context invariance_ lemma, showing that typing is preserved\n        under \"inessential changes\" to the context [Gamma] -- in\n        particular, changes that do not affect any of the free\n        variables of the term.  And finally, for this, we need a\n        careful definition of...\n\n      - the _free variables_ of a term -- i.e., those variables\n        mentioned in a term and not in the scope of an enclosing\n        function abstraction binding a variable of the same name.\n\n   To make Coq happy, we need to formalize the story in the opposite\n   order... *)\n\n(* ###################################################################### *)\n(** ** Free Occurrences *)\n\n(** A variable [x] _appears free in_ a term _t_ if [t] contains some\n    occurrence of [x] that is not under an abstraction labeled [x].\n    For example:\n      - [y] appears free, but [x] does not, in [\\x:T->U. x y]\n      - both [x] and [y] appear free in [(\\x:T->U. x y) x]\n      - no variables appear free in [\\x:T->U. \\y:T. x y]\n\n    Formally: *)\n\nInductive appears_free_in : id -> tm -> Prop :=\n  | afi_var : forall x,\n      appears_free_in x (tvar x)\n  | afi_app1 : forall x t1 t2,\n      appears_free_in x t1 -> appears_free_in x (tapp t1 t2)\n  | afi_app2 : forall x t1 t2,\n      appears_free_in x t2 -> appears_free_in x (tapp t1 t2)\n  | afi_abs : forall x y T11 t12,\n      y <> x  ->\n      appears_free_in x t12 ->\n      appears_free_in x (tabs y T11 t12)\n  | afi_if1 : forall x t1 t2 t3,\n      appears_free_in x t1 ->\n      appears_free_in x (tif t1 t2 t3)\n  | afi_if2 : forall x t1 t2 t3,\n      appears_free_in x t2 ->\n      appears_free_in x (tif t1 t2 t3)\n  | afi_if3 : forall x t1 t2 t3,\n      appears_free_in x t3 ->\n      appears_free_in x (tif t1 t2 t3).\n\nHint Constructors appears_free_in.\n\n(** A term in which no variables appear free is said to be _closed_. *)\n\nDefinition closed (t:tm) :=\n  forall x, ~ appears_free_in x t.\n\n(** **** Exercise: 1 star (afi)  *)\n(** If the definition of [appears_free_in] is not crystal clear to\n    you, it is a good idea to take a piece of paper and write out the\n    rules in informal inference-rule notation.  (Although it is a\n    rather low-level, technical definition, understanding it is\n    crucial to understanding substitution and its properties, which\n    are really the crux of the lambda-calculus.) *)\n(** [] *)\n\n(* ###################################################################### *)\n(** ** Substitution *)\n\n(** To prove that substitution preserves typing, we first need a\n    technical lemma connecting free variables and typing contexts: If\n    a variable [x] appears free in a term [t], and if we know [t] is\n    well typed in context [Gamma], then it must be the case that\n    [Gamma] assigns a type to [x]. *)\n\nLemma free_in_context : forall x t T Gamma,\n   appears_free_in x t ->\n   Gamma |- t \\in T ->\n   exists T', Gamma x = Some T'.\n\n(** _Proof_: We show, by induction on the proof that [x] appears\n      free in [t], that, for all contexts [Gamma], if [t] is well\n      typed under [Gamma], then [Gamma] assigns some type to [x].\n\n      - If the last rule used was [afi_var], then [t = x], and from\n        the assumption that [t] is well typed under [Gamma] we have\n        immediately that [Gamma] assigns a type to [x].\n\n      - If the last rule used was [afi_app1], then [t = t1 t2] and [x]\n        appears free in [t1].  Since [t] is well typed under [Gamma],\n        we can see from the typing rules that [t1] must also be, and\n        the IH then tells us that [Gamma] assigns [x] a type.\n\n      - Almost all the other cases are similar: [x] appears free in a\n        subterm of [t], and since [t] is well typed under [Gamma], we\n        know the subterm of [t] in which [x] appears is well typed\n        under [Gamma] as well, and the IH gives us exactly the\n        conclusion we want.\n\n      - The only remaining case is [afi_abs].  In this case [t =\n        \\y:T11.t12], and [x] appears free in [t12]; we also know that\n        [x] is different from [y].  The difference from the previous\n        cases is that whereas [t] is well typed under [Gamma], its\n        body [t12] is well typed under [(Gamma, y:T11)], so the IH\n        allows us to conclude that [x] is assigned some type by the\n        extended context [(Gamma, y:T11)].  To conclude that [Gamma]\n        assigns a type to [x], we appeal to lemma [update_neq], noting\n        that [x] and [y] are different variables. *)\n\nProof.\n  intros x t T Gamma H H0. generalize dependent Gamma.\n  generalize dependent T.\n  induction H;\n         intros; try solve [inversion H0; eauto].\n  - (* afi_abs *)\n    inversion H1; subst.\n    apply IHappears_free_in in H7.\n    rewrite update_neq in H7; assumption.\nQed.\n\n(** Next, we'll need the fact that any term [t] which is well typed in\n    the empty context is closed (it has no free variables). *)\n\n(** **** Exercise: 2 stars, optional (typable_empty__closed)  *)\nCorollary typable_empty__closed : forall t T,\n    empty |- t \\in T  ->\n    closed t.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Sometimes, when we have a proof [Gamma |- t : T], we will need to\n    replace [Gamma] by a different context [Gamma'].  When is it safe\n    to do this?  Intuitively, it must at least be the case that\n    [Gamma'] assigns the same types as [Gamma] to all the variables\n    that appear free in [t]. In fact, this is the only condition that\n    is needed. *)\n\nLemma context_invariance : forall Gamma Gamma' t T,\n     Gamma |- t \\in T  ->\n     (forall x, appears_free_in x t -> Gamma x = Gamma' x) ->\n     Gamma' |- t \\in T.\n\n(** _Proof_: By induction on the derivation of \n    [Gamma |- t \\in T].\n\n      - If the last rule in the derivation was [T_Var], then [t = x]\n        and [Gamma x = T].  By assumption, [Gamma' x = T] as well, and\n        hence [Gamma' |- t \\in T] by [T_Var].\n\n      - If the last rule was [T_Abs], then [t = \\y:T11. t12], with [T\n        = T11 -> T12] and [Gamma, y:T11 |- t12 \\in T12].  The\n        induction hypothesis is that, for any context [Gamma''], if\n        [Gamma, y:T11] and [Gamma''] assign the same types to all the\n        free variables in [t12], then [t12] has type [T12] under\n        [Gamma''].  Let [Gamma'] be a context which agrees with\n        [Gamma] on the free variables in [t]; we must show [Gamma' |-\n        \\y:T11. t12 \\in T11 -> T12].\n\n        By [T_Abs], it suffices to show that [Gamma', y:T11 |- t12 \\in\n        T12].  By the IH (setting [Gamma'' = Gamma', y:T11]), it\n        suffices to show that [Gamma, y:T11] and [Gamma', y:T11] agree\n        on all the variables that appear free in [t12].\n\n        Any variable occurring free in [t12] must be either [y] or\n        some other variable.  [Gamma, y:T11] and [Gamma', y:T11]\n        clearly agree on [y].  Otherwise, note that any variable other\n        than [y] that occurs free in [t12] also occurs free in [t =\n        \\y:T11. t12], and by assumption [Gamma] and [Gamma'] agree on\n        all such variables; hence so do [Gamma, y:T11] and [Gamma',\n        y:T11].\n\n      - If the last rule was [T_App], then [t = t1 t2], with [Gamma |-\n        t1 \\in T2 -> T] and [Gamma |- t2 \\in T2].  One induction\n        hypothesis states that for all contexts [Gamma'], if [Gamma']\n        agrees with [Gamma] on the free variables in [t1], then [t1]\n        has type [T2 -> T] under [Gamma']; there is a similar IH for\n        [t2].  We must show that [t1 t2] also has type [T] under\n        [Gamma'], given the assumption that [Gamma'] agrees with\n        [Gamma] on all the free variables in [t1 t2].  By [T_App], it\n        suffices to show that [t1] and [t2] each have the same type\n        under [Gamma'] as under [Gamma].  But all free variables in\n        [t1] are also free in [t1 t2], and similarly for [t2]; hence\n        the desired result follows from the induction hypotheses. *)\n\nProof with eauto.\n  intros.\n  generalize dependent Gamma'.\n  induction H; intros; auto.\n  - (* T_Var *)\n    apply T_Var. rewrite <- H0...\n  - (* T_Abs *)\n    apply T_Abs.\n    apply IHhas_type. intros x1 Hafi.\n    (* the only tricky step... the [Gamma'] we use to\n       instantiate is [update Gamma x T11] *)\n    unfold update. unfold t_update. destruct (beq_id x0 x1) eqn: Hx0x1...\n    rewrite beq_id_false_iff in Hx0x1. auto.\n  - (* T_App *)\n    apply T_App with T11...\nQed.\n\n(** Now we come to the conceptual heart of the proof that reduction\n    preserves types -- namely, the observation that _substitution_\n    preserves types.\n\n    Formally, the so-called _Substitution Lemma_ says this: Suppose we\n    have a term [t] with a free variable [x], and suppose we've been\n    able to assign a type [T] to [t] under the assumption that [x] has\n    some type [U].  Also, suppose that we have some other term [v] and\n    that we've shown that [v] has type [U].  Then, since [v] satisfies\n    the assumption we made about [x] when typing [t], we should be\n    able to substitute [v] for each of the occurrences of [x] in [t]\n    and obtain a new term that still has type [T]. *)\n\n(** _Lemma_: If [Gamma,x:U |- t \\in T] and [|- v \\in U], then [Gamma |-\n    [x:=v]t \\in T]. *)\n\nLemma substitution_preserves_typing : forall Gamma x U t v T,\n     update Gamma x U |- t \\in T ->\n     empty |- v \\in U   ->\n     Gamma |- [x:=v]t \\in T.\n\n(** One technical subtlety in the statement of the lemma is that\n    we assign [v] the type [U] in the _empty_ context -- in other\n    words, we assume [v] is closed.  This assumption considerably\n    simplifies the [T_Abs] case of the proof (compared to assuming\n    [Gamma |- v \\in U], which would be the other reasonable assumption\n    at this point) because the context invariance lemma then tells us\n    that [v] has type [U] in any context at all -- we don't have to\n    worry about free variables in [v] clashing with the variable being\n    introduced into the context by [T_Abs].\n\n    The substitution lemma can be viewed as a kind of \"commutation\"\n    property.  Intuitively, it says that substitution and typing can\n    be done in either order: we can either assign types to the terms\n    [t] and [v] separately (under suitable contexts) and then combine\n    them using substitution, or we can substitute first and then\n    assign a type to [ [x:=v] t ] -- the result is the same either\n    way.\n\n    _Proof_: We show, by induction on [t], that for all [T] and\n    [Gamma], if [Gamma,x:U |- t \\in T] and [|- v \\in U], then [Gamma\n    |- [x:=v]t \\in T].\n\n      - If [t] is a variable there are two cases to consider,\n        depending on whether [t] is [x] or some other variable.\n\n          - If [t = x], then from the fact that [Gamma, x:U |- x \\in\n            T] we conclude that [U = T].  We must show that [[x:=v]x =\n            v] has type [T] under [Gamma], given the assumption that\n            [v] has type [U = T] under the empty context.  This\n            follows from context invariance: if a closed term has type\n            [T] in the empty context, it has that type in any context.\n\n          - If [t] is some variable [y] that is not equal to [x], then\n            we need only note that [y] has the same type under [Gamma,\n            x:U] as under [Gamma].\n\n      - If [t] is an abstraction [\\y:T11. t12], then the IH tells us,\n        for all [Gamma'] and [T'], that if [Gamma',x:U |- t12 \\in T']\n        and [|- v \\in U], then [Gamma' |- [x:=v]t12 \\in T'].\n\n        The substitution in the conclusion behaves differently\n        depending on whether [x] and [y] are the same variable.\n\n        First, suppose [x = y].  Then, by the definition of\n        substitution, [[x:=v]t = t], so we just need to show [Gamma |-\n        t \\in T].  But we know [Gamma,x:U |- t : T], and, since [y]\n        does not appear free in [\\y:T11. t12], the context invariance\n        lemma yields [Gamma |- t \\in T].\n\n        Second, suppose [x <> y].  We know [Gamma,x:U,y:T11 |- t12 \\in\n        T12] by inversion of the typing relation, from which\n        [Gamma,y:T11,x:U |- t12 \\in T12] follows by the context\n        invariance lemma, so the IH applies, giving us [Gamma,y:T11 |-\n        [x:=v]t12 \\in T12].  By [T_Abs], [Gamma |- \\y:T11. [x:=v]t12\n        \\in T11->T12], and by the definition of substitution (noting\n        that [x <> y]), [Gamma |- \\y:T11. [x:=v]t12 \\in T11->T12] as\n        required.\n\n      - If [t] is an application [t1 t2], the result follows\n        straightforwardly from the definition of substitution and the\n        induction hypotheses.\n\n      - The remaining cases are similar to the application case.\n\n    One more technical note: This proof is a rare case where an\n    induction on terms, rather than typing derivations, yields a\n    simpler argument.  The reason for this is that the assumption\n    [update Gamma x U |- t \\in T] is not completely generic, in the\n    sense that one of the \"slots\" in the typing relation -- namely the\n    context -- is not just a variable, and this means that Coq's\n    native induction tactic does not give us the induction hypothesis\n    that we want.  It is possible to work around this, but the needed\n    generalization is a little tricky.  The term [t], on the other\n    hand, _is_ completely generic. *)\n\nProof with eauto.\n  intros Gamma x U t v T Ht Ht'.\n  generalize dependent Gamma. generalize dependent T.\n  induction t; intros T Gamma H;\n    (* in each case, we'll want to get at the derivation of H *)\n    inversion H; subst; simpl...\n  - (* tvar *)\n    rename i into y. destruct (beq_idP x y) as [Hxy|Hxy].\n    + (* x=y *)\n      subst.\n      rewrite update_eq in H2.\n      inversion H2; subst. clear H2.\n                  eapply context_invariance... intros x Hcontra.\n      destruct (free_in_context _ _ T empty Hcontra) as [T' HT']...\n      inversion HT'.\n    + (* x<>y *)\n      apply T_Var. rewrite update_neq in H2...\n  - (* tabs *)\n    rename i into y. apply T_Abs.\n    destruct (beq_idP x y) as [Hxy | Hxy].\n    + (* x=y *)\n      subst.\n      eapply context_invariance...\n      intros x Hafi. unfold update, t_update.\n      destruct (beq_id y x) eqn: Hyx...\n    + (* x<>y *)\n      apply IHt. eapply context_invariance...\n      intros z Hafi. unfold update, t_update.\n      destruct (beq_idP y z) as [Hyz | Hyz]; subst; trivial.\n      rewrite <- beq_id_false_iff in Hxy.\n      rewrite Hxy...\nQed.\n\n(* ###################################################################### *)\n(** ** Main Theorem *)\n\n(** We now have the tools we need to prove preservation: if a closed\n    term [t] has type [T] and takes a step to [t'], then [t']\n    is also a closed term with type [T].  In other words, the small-step\n    reduction relation preserves types. *)\n\nTheorem preservation : forall t t' T,\n     empty |- t \\in T  ->\n     t ==> t'  ->\n     empty |- t' \\in T.\n\n(** _Proof_: By induction on the derivation of [|- t \\in T].\n\n    - We can immediately rule out [T_Var], [T_Abs], [T_True], and\n      [T_False] as the final rules in the derivation, since in each of\n      these cases [t] cannot take a step.\n\n    - If the last rule in the derivation was [T_App], then [t = t1\n      t2].  There are three cases to consider, one for each rule that\n      could have been used to show that [t1 t2] takes a step to [t'].\n\n        - If [t1 t2] takes a step by [ST_App1], with [t1] stepping to\n          [t1'], then by the IH [t1'] has the same type as [t1], and\n          hence [t1' t2] has the same type as [t1 t2].\n\n        - The [ST_App2] case is similar.\n\n        - If [t1 t2] takes a step by [ST_AppAbs], then [t1 =\n          \\x:T11.t12] and [t1 t2] steps to [[x:=t2]t12]; the\n          desired result now follows from the fact that substitution\n          preserves types.\n\n    - If the last rule in the derivation was [T_If], then [t = if t1\n      then t2 else t3], and there are again three cases depending on\n      how [t] steps.\n\n        - If [t] steps to [t2] or [t3], the result is immediate, since\n          [t2] and [t3] have the same type as [t].\n\n        - Otherwise, [t] steps by [ST_If], and the desired conclusion\n          follows directly from the induction hypothesis. *)\n\nProof with eauto.\n  remember (@empty ty) as Gamma.\n  intros t t' T HT. generalize dependent t'.\n  induction HT;\n       intros t' HE; subst Gamma; subst;\n       try solve [inversion HE; subst; auto].\n  - (* T_App *)\n    inversion HE; subst...\n    (* Most of the cases are immediate by induction,\n       and [eauto] takes care of them *)\n    + (* ST_AppAbs *)\n      apply substitution_preserves_typing with T11...\n      inversion HT1...\nQed.\n\n(** **** Exercise: 2 stars, recommended (subject_expansion_stlc)  *)\n(** An exercise in the [Types] chapter asked about the subject\n    expansion property for the simple language of arithmetic and\n    boolean expressions.  Does this property hold for STLC?  That is,\n    is it always the case that, if [t ==> t'] and [has_type t' T],\n    then [empty |- t \\in T]?  If so, prove it.  If not, give a\n    counter-example not involving conditionals.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(* ###################################################################### *)\n(** * Type Soundness *)\n\n(** **** Exercise: 2 stars, optional (type_soundness)  *)\n(** Put progress and preservation together and show that a well-typed\n    term can _never_ reach a stuck state.  *)\n\nDefinition stuck (t:tm) : Prop :=\n  (normal_form step) t /\\ ~ value t.\n\nCorollary soundness : forall t t' T,\n  empty |- t \\in T ->\n  t ==>* t' ->\n  ~(stuck t').\nProof.\n  intros t t' T Hhas_type Hmulti. unfold stuck.\n  intros [Hnf Hnot_val]. unfold normal_form in Hnf.\n  induction Hmulti.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################################### *)\n(** * Uniqueness of Types *)\n\n(** **** Exercise: 3 stars (types_unique)  *)\n(** Another nice property of the STLC is that types are unique: a\n    given term (in a given context) has at most one type. *)\n(** Formalize this statement and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ###################################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 1 star (progress_preservation_statement)  *)\n(** Without peeking at their statements above, write down the progress\n    and preservation theorems for the simply typed lambda-calculus. *)\n(** [] *)\n\n(** **** Exercise: 2 stars (stlc_variation1)  *)\n(** Suppose we add a new term [zap] with the following reduction rule\n\n                         ---------                  (ST_Zap)\n                         t ==> zap\n\nand the following typing rule:\n\n                      ----------------               (T_Zap)\n                      Gamma |- zap : T\n\n    Which of the following properties of the STLC remain true in\n    the presence of these rules?  For each property, write either\n    \"remains true\" or \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n[]\n*)\n\n(** **** Exercise: 2 stars (stlc_variation2)  *)\n(** Suppose instead that we add a new term [foo] with the following \n    reduction rules:\n\n                       -----------------                (ST_Foo1)\n                       (\\x:A. x) ==> foo\n\n                         ------------                   (ST_Foo2)\n                         foo ==> true\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n[]\n*)\n\n(** **** Exercise: 2 stars (stlc_variation3)  *)\n(** Suppose instead that we remove the rule [ST_App1] from the [step]\n    relation. Which of the following properties of the STLC remain\n    true in the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation4)  *)\n(** Suppose instead that we add the following new rule to the \n    reduction relation:\n\n            ----------------------------------        (ST_FunnyIfTrue)\n            (if true then t1 else t2) ==> true\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation5)  *)\n(** Suppose instead that we add the following new rule to the typing \n    relation:\n\n                 Gamma |- t1 \\in Bool->Bool->Bool\n                     Gamma |- t2 \\in Bool\n                 ------------------------------          (T_FunnyApp)\n                    Gamma |- t1 t2 \\in Bool\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation6)  *)\n(** Suppose instead that we add the following new rule to the typing \n    relation:\n\n                     Gamma |- t1 \\in Bool\n                     Gamma |- t2 \\in Bool\n                    ---------------------               (T_FunnyApp')\n                    Gamma |- t1 t2 \\in Bool\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation7)  *)\n(** Suppose we add the following new rule to the typing relation \n    of the STLC:\n\n                         ------------------- (T_FunnyAbs)\n                         |- \\x:Bool.t \\in Bool\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n[]\n*)\n\nEnd STLCProp.\n\n(* ###################################################################### *)\n(* ###################################################################### *)\n(** ** Exercise: STLC with Arithmetic *)\n\n(** To see how the STLC might function as the core of a real\n    programming language, let's extend it with a concrete base\n    type of numbers and some constants and primitive\n    operators. *)\n\nModule STLCArith.\n\n(** To types, we add a base type of natural numbers (and remove\n    booleans, for brevity). *)\n\nInductive ty : Type :=\n  | TArrow : ty -> ty -> ty\n  | TNat   : ty.\n\n(** To terms, we add natural number constants, along with\n    successor, predecessor, multiplication, and zero-testing. *)\n\nInductive tm : Type :=\n  | tvar : id -> tm\n  | tapp : tm -> tm -> tm\n  | tabs : id -> ty -> tm -> tm\n  | tnat  : nat -> tm\n  | tsucc : tm -> tm\n  | tpred : tm -> tm\n  | tmult : tm -> tm -> tm\n  | tif0  : tm -> tm -> tm -> tm.\n\n(** **** Exercise: 4 stars (stlc_arith)  *)\n(** Finish formalizing the definition and properties of the STLC extended\n    with arithmetic.  Specifically:\n\n    - Copy the whole development of STLC that we went through above (from\n      the definition of values through the Type Soundness theorem), and\n      paste it into the file at this point.\n\n    - Extend the definitions of the [subst] operation and the [step]\n      relation to include appropriate clauses for the arithmetic operators.\n\n    - Extend the proofs of all the properties (up to [soundness]) of\n      the original STLC to deal with the new syntactic forms.  Make\n      sure Coq accepts the whole file. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd STLCArith.\n\n(** $Date: 2016-05-26 16:17:19 -0400 (Thu, 26 May 2016) $ *)\n\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/StlcProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6956626488746628}}
{"text": "Require Import init.\n\nRequire Import set.\n\n(* begin show *)\nSet Universe Polymorphism.\n(* end show *)\n\n(** Note: I am learning category theory while writing this.  Apologies if\nanything here is incorrect/not specified in the best way.\n*)\n\n(* begin show *)\nClass Category := {\n    cat_U : Type;\n    cat_morphism : cat_U → cat_U → Type;\n    cat_compose : ∀ {A B C},\n        cat_morphism B C → cat_morphism A B → cat_morphism A C;\n    cat_id : ∀ A, cat_morphism A A;\n    cat_assoc : ∀ {A B C D}\n        (h : cat_morphism C D) (g : cat_morphism B C) (f : cat_morphism A B),\n        cat_compose h (cat_compose g f) = cat_compose (cat_compose h g) f;\n    cat_lid : ∀ {A B} (f : cat_morphism A B), cat_compose (cat_id B) f = f;\n    cat_rid : ∀ {A B} (f : cat_morphism A B), cat_compose f (cat_id A) = f;\n}.\n(* end show *)\n\nArguments cat_U : clear implicits.\nArguments cat_morphism : clear implicits.\nArguments cat_compose Category {A B C} f g.\nArguments cat_id : clear implicits.\n\nInfix \"∘\" := (cat_compose _).\nNotation \"𝟙\" := (cat_id _ _).\n\nDefinition cat_domain `{C0 : Category} {A B} (f : cat_morphism C0 A B) := A.\nDefinition cat_codomain `{C0 : Category} {A B} (f : cat_morphism C0 A B) := B.\n\nDefinition isomorphism `{C0 : Category} {A B} (f : cat_morphism C0 A B)\n    := ∃ g, f ∘ g = 𝟙 ∧ g ∘ f = 𝟙.\n\nDefinition cat_inverse `{C0 : Category} {A B}\n    (f : cat_morphism C0 A B) (H : isomorphism f) := ex_val H.\n\nDefinition isomorphic `{C0 : Category} A B\n    := ∃ f : cat_morphism C0 A B, isomorphism f.\n\nNotation \"A ≅ B\" := (isomorphic A B) (at level 70, no associativity).\n\n(* begin show *)\nLocal Program Instance dual_category `(C0 : Category) : Category := {\n    cat_U := cat_U C0;\n    cat_morphism A B := cat_morphism C0 B A;\n    cat_compose {A B C} f g := cat_compose C0 g f;\n    cat_id A := cat_id C0 A;\n}.\n(* end show *)\nNext Obligation.\n    symmetry.\n    apply cat_assoc.\nQed.\nNext Obligation.\n    apply cat_rid.\nQed.\nNext Obligation.\n    apply cat_lid.\nQed.\n\n(* begin show *)\nLocal Program Instance product_category `(C1 : Category) `(C2 : Category) : Category\n:= {\n    cat_U := prod_type (cat_U C1) (cat_U C2);\n    cat_morphism A B\n        := prod_type (cat_morphism C1 (fst A) (fst B)) (cat_morphism C2 (snd A) (snd B));\n    cat_compose {A B C} f g := (fst f ∘ fst g, snd f ∘ snd g);\n    cat_id A := (𝟙, 𝟙);\n}.\n(* end show *)\nNext Obligation.\n    do 2 rewrite cat_assoc.\n    reflexivity.\nQed.\nNext Obligation.\n    do 2 rewrite cat_lid.\n    destruct f; reflexivity.\nQed.\nNext Obligation.\n    do 2 rewrite cat_rid.\n    destruct f; reflexivity.\nQed.\n\nClass SubCategory `(C0 : Category) := {\n    subcat_S : cat_U C0 → Prop;\n    subcat_morphism : ∀ {A B}, cat_morphism C0 A B → Prop;\n    subcat_compose : ∀ {A B C} (f : cat_morphism C0 B C) (g : cat_morphism C0 A B),\n        subcat_morphism f → subcat_morphism g → subcat_morphism (f ∘ g);\n    subcat_id : ∀ A, subcat_morphism (cat_id C0 A);\n}.\n\n(* begin show *)\nLocal Program Instance subcategory `(SubCategory) : Category := {\n    cat_U := set_type subcat_S;\n    cat_morphism A B := set_type (subcat_morphism (A:=[A|]) (B:=[B|]));\n    cat_compose {A B C} f g := [_|subcat_compose [f|] [g|] [|f] [|g]];\n    cat_id A := [_|subcat_id [A|]];\n}.\n(* end show *)\nNext Obligation.\n    apply set_type_eq; cbn.\n    apply cat_assoc.\nQed.\nNext Obligation.\n    apply set_type_eq; cbn.\n    apply cat_lid.\nQed.\nNext Obligation.\n    apply set_type_eq; cbn.\n    apply cat_rid.\nQed.\nGlobal Remove Hints dual_category product_category subcategory : typeclass_instances.\n\nDefinition full_subcategory `(SubCategory) := ∀ A B,\n    subcat_morphism (A:=A) (B:=B) = all.\n\n(* begin hide *)\nSection Category.\n\nContext `{C0 : Category}.\n\nLocal Arguments cat_morphism {Category}.\n\n(* end hide *)\nTheorem lcompose : ∀ {A B C} {f g : cat_morphism A B} (h : cat_morphism B C),\n    f = g → h ∘ f = h ∘ g.\nProof.\n    intros A B C f g h eq.\n    rewrite eq.\n    reflexivity.\nQed.\nTheorem rcompose : ∀ {A B C} {f g : cat_morphism B C} (h : cat_morphism A B),\n    f = g → f ∘ h = g ∘ h.\nProof.\n    intros A B C f g h eq.\n    rewrite eq.\n    reflexivity.\nQed.\nTheorem lrcompose : ∀ {A B C} {f g : cat_morphism B C} {h i : cat_morphism A B},\n    f = g → h = i → f ∘ h = g ∘ i.\nProof.\n    intros A B C f g h i eq1 eq2.\n    rewrite eq1, eq2.\n    reflexivity.\nQed.\n\nTheorem id_isomorphism : ∀ A, isomorphism (cat_id _ A).\nProof.\n    intros A.\n    exists 𝟙.\n    split; apply cat_lid.\nQed.\n\nTheorem compose_isomorphism : ∀ {A B C}\n    (f : cat_morphism B C) (g : cat_morphism A B),\n    isomorphism f → isomorphism g → isomorphism (f ∘ g).\nProof.\n    intros A B C f g [f' [f1 f2]] [g' [g1 g2]].\n    exists (g' ∘ f').\n    split.\n    -   rewrite <- cat_assoc.\n        rewrite (cat_assoc g).\n        rewrite g1.\n        rewrite cat_lid.\n        exact f1.\n    -   rewrite <- cat_assoc.\n        rewrite (cat_assoc f').\n        rewrite f2.\n        rewrite cat_lid.\n        exact g2.\nQed.\n\nTheorem cat_inverse_unique : ∀ {A B} (f : cat_morphism A B) g1 g2,\n    f ∘ g1 = 𝟙 → g1 ∘ f = 𝟙 → f ∘ g2 = 𝟙 → g2 ∘ f = 𝟙 → g1 = g2.\nProof.\n    intros A B f g1 g2 fg1 g1f fg2 g2f.\n    apply lcompose with g2 in fg1.\n    rewrite cat_assoc in fg1.\n    rewrite g2f in fg1.\n    rewrite cat_lid, cat_rid in fg1.\n    exact fg1.\nQed.\n\nTheorem isomorphic_refl : ∀ A, A ≅ A.\nProof.\n    intros A.\n    exists 𝟙, 𝟙.\n    rewrite cat_lid.\n    split; reflexivity.\nQed.\nTheorem isomorphic_sym : ∀ A B, A ≅ B → B ≅ A.\nProof.\n    intros A B [f [g [eq1 eq2]]].\n    exists g, f.\n    split; assumption.\nQed.\nTheorem isomorphic_trans : ∀ {A B C}, A ≅ B → B ≅ C → A ≅ C.\nProof.\n    intros A B C [f1 [g1 [eq11 eq12]]] [f2 [g2 [eq21 eq22]]].\n    exists (f2 ∘ f1).\n    exists (g1 ∘ g2).\n    split.\n    -   rewrite <- cat_assoc.\n        rewrite (cat_assoc f1).\n        rewrite eq11.\n        rewrite cat_lid.\n        exact eq21.\n    -   rewrite <- cat_assoc.\n        rewrite (cat_assoc g2).\n        rewrite eq22.\n        rewrite cat_lid.\n        exact eq12.\nQed.\nTheorem isomorphic_trans2 : ∀ {A B C}, B ≅ C → A ≅ B → A ≅ C.\nProof.\n    intros A B C eq1 eq2.\n    exact (isomorphic_trans eq2 eq1).\nQed.\n\nTheorem dual_isomorphism : ∀ {A B} (f : cat_morphism A B),\n    isomorphism (C0 := C0) f ↔ isomorphism (C0:=dual_category C0) f.\nProof.\n    intros A B f.\n    split.\n    -   intros [g [g_eq1 g_eq2]].\n        exists g.\n        cbn in *.\n        split; assumption.\n    -   intros [g [g_eq1 g_eq2]].\n        exists g.\n        cbn in *.\n        split; assumption.\nQed.\n\n(* begin hide *)\nEnd Category.\n\n(* end hide *)\nDefinition convert_type {A B : Type} (H : A = B) (x : A) : B.\n    rewrite H in x.\n    exact x.\nDefined.\n\nTheorem cat_eq : ∀ C1 C2,\n    ∀ H : @cat_U C1 = @cat_U C2,\n    ∀ H' : (∀ A B, cat_morphism C1 A B =\n                   cat_morphism C2 (convert_type H A) (convert_type H B)),\n    (∀ A B C (f : cat_morphism C1 B C) (g : cat_morphism C1 A B),\n        convert_type (H' _ _) (f ∘ g) =\n        (convert_type (H' _ _) f) ∘ (convert_type (H' _ _) g)) →\n    (∀ A, convert_type (H' A A) (cat_id C1 A) = cat_id C2 (convert_type H A)) →\n    C1 = C2.\nProof.\n    intros [U1 morphism1 compose1 id1 assoc1 lid1 rid1]\n           [U2 morphism2 compose2 id2 assoc2 lid2 rid2] H H' eq1 eq2.\n    cbn in *.\n    destruct H.\n    assert (morphism1 = morphism2) as eq.\n    {\n        apply functional_ext.\n        intros A.\n        apply functional_ext.\n        apply H'.\n    }\n    subst morphism2; cbn in *.\n    pose (H'2 A B := Logic.eq_refl (morphism1 A B)).\n    rewrite (proof_irrelevance H' H'2) in eq1, eq2.\n    clear H'.\n    cbn in *.\n    assert (compose1 = compose2) as eq.\n    {\n        apply functional_ext; intros A.\n        apply functional_ext; intros B.\n        apply functional_ext; intros C.\n        apply functional_ext; intros f.\n        apply functional_ext; intros g.\n        apply eq1.\n    }\n    subst compose2; clear eq1.\n    assert (id1 = id2) as eq.\n    {\n        apply functional_ext; intros A.\n        apply eq2.\n    }\n    subst id2; clear eq2.\n    rewrite (proof_irrelevance assoc2 assoc1).\n    rewrite (proof_irrelevance lid2 lid1).\n    rewrite (proof_irrelevance rid2 rid1).\n    reflexivity.\nQed.\n\nTheorem cat_dual_dual : ∀ C, C = dual_category (dual_category C).\nProof.\n    intros C.\n    assert (@cat_U C = @cat_U (dual_category (dual_category C))) as H\n        by reflexivity.\n    pose (H2 := Logic.eq_refl (cat_U C)).\n    assert (∀ A B, cat_morphism _ A B =\n                   cat_morphism _ (convert_type H A) (convert_type H B)) as H'.\n    {\n        intros A B.\n        rewrite (proof_irrelevance H H2).\n        cbn.\n        reflexivity.\n    }\n    apply (cat_eq _ _ H H').\n    all: pose proof (proof_irrelevance H H2) as H_eq.\n    all: subst H.\n    all: unfold H2 in *; cbn in *.\n    all: clear H2.\n    all: pose (H'2 A B := Logic.eq_refl (cat_morphism C A B)).\n    all: rewrite (proof_irrelevance H' H'2).\n    all: cbn.\n    all: reflexivity.\nQed.\n\nUnset Universe Polymorphism.\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/Category/category_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6956626441947273}}
{"text": "Require Import ZArith Arith Bool Omega.\n\nOpen Scope Z_scope.\n\n(* The key to this corollary is that if s=Zsqrt_plain x, then\n  s*s < (s+1) * (s+1), as stated by the companion theorem\n  Zsqrt_interval, and the squaring operation is monotonic only\n  for positive values. *)\n\nTheorem div_Zsqrt :\n forall m n p:Z, 0 < m < n ->\n  n=m*p-> 0 < m <= Z.sqrt n \\/ 0 < p <= Z.sqrt n.\nProof.\n intros m n p Hint Heq.\n elim (Z_lt_le_dec (Z.sqrt n) m); \n elim (Z_lt_le_dec (Z.sqrt n) p).\n -  intros Hltm Hltp.\n    assert (Hlem : (Z.sqrt n)+1 <= m) by  omega.\n    assert (Hlep : (Z.sqrt n)+1 <= p) by  omega.\n    elim (Zlt_irrefl n).\n    apply Zlt_le_trans with (((Z.sqrt n)+1)*((Z.sqrt n)+1)).\n    assert (Hposn : 0 <= n) by  omega.\n    generalize (Z.sqrt_spec n Hposn);cbv zeta;intro H23.\n    intuition. \n    pattern n at 3; rewrite Heq.\n    apply Zmult_le_compat; try omega.\n    generalize (Z.sqrt_nonneg n).\n    omega.\n    generalize (Z.sqrt_nonneg n).\n    omega.\n - intros Hple _; right; split; auto.\n   apply Zmult_lt_0_reg_r with m; try tauto.\n   rewrite Zmult_comm; omega.\n -  intros _ Hmle; left; split; tauto.\n -  intros _ Hmle; left; split; tauto.\nQed.\n\n\nDefinition divides_bool (p t:Z) : bool :=\n match t mod p with\n   0 => true\n | _ => false\n end.\n\nFixpoint test_odds (n:nat) (p t:Z) {struct n} : bool :=\n match n with\n | 0%nat => negb (divides_bool 2 t)\n | S n' =>\n   if test_odds n' (p - 2) t then negb (divides_bool p t) else false\n end.\n\n\nDefinition prime_test (n:nat) : bool :=\n match n with\n | 0%nat => false\n | 1%nat => false\n | S (S n) => \n  let x := (Z_of_nat (S (S n))) in\n  let s := (Z.sqrt x) in\n  let (half_s, even_bit) :=\n    match s with\n    | Zpos(xI h) => (Zpos h, 0)\n    | Zpos(xO h) => (Zpos h, 1)\n    | Zpos xH => (0, 0)\n    | _ => (0, 1)  \n    end  in\n  test_odds (Zabs_nat half_s) (s + even_bit) x\n end.\n\nTime Eval lazy beta iota delta zeta in (prime_test 2333).\n\n(* Time Eval compute in (prime_test 2333). \n \n  This command takes a much longer time.  The reason is that Z.sqrt_plain\n  calls a strongly specified function, which builds a proof term that is\n  large, but is discarded later.  Lazy computation avoid the useless \n  work. *)\n\n(* we use the same axiom as in the book, it is corrected in another exercise.\n *)\n\nAxiom verif_divide :\n  (forall m p:nat, 0 < m -> 0 < p ->\n   (exists q:nat, m = q*p) ->(Z_of_nat m mod Z_of_nat p = 0)%Z )%nat.\n\n(* This axiom is actually a lemma used in the same other exercise. *)\n\nAxiom Z_to_nat_and_back :\n forall x:Z, (0 <= x)%Z -> (Z_of_nat (Zabs_nat x))=x.\n\nTheorem test_odds_correct2 :\n  forall n x:nat,\n    (1 < x)%nat ->\n  forall p:Z,\n    test_odds n p (Z_of_nat x) = true ->\n    ~(exists y:nat, x = y*2)%nat.\nProof.\n intros n; elim n.\n - unfold test_odds, divides_bool; intros x H1ltx _ Heq Hex.\n   assert (Heq' : Z_of_nat x mod Z_of_nat 2 = 0).\n  +  apply verif_divide; auto with zarith.\n  +  simpl (Z_of_nat 2) in Heq'; rewrite Heq' in Heq; simpl in Heq; discriminate.\n\n - clear n; intros n IHn x H1ltx p; simpl.\n   case_eq (test_odds n (p - 2) (Z_of_nat x)).\n   +  intros Htest' _ ; apply (IHn x H1ltx (p -2)); auto.\n   +  intros; discriminate.\nQed.\n\nTheorem Z_of_nat_le :\n  forall x y, Z_of_nat x <= Z_of_nat y -> (x <= y)%nat.\nProof.\n intros; omega.\nQed.\n\n\nTheorem test_odds_correct :\n  forall (n x:nat)(p:Z),\n   p = 2*(Z_of_nat n)+1 ->\n   (1 < x)%nat -> test_odds n p (Z_of_nat x) = true -> \n   forall q:nat, (1 < q <= 2*n+1)%nat -> ~(exists y:nat, x = q*y)%nat.\nProof.\n induction n.\n -  intros x p Hp1 H1ltx Hn q Hint.\n    elimtype False;  omega.\n  - intros x p Hp H1ltx; simpl (test_odds (S n) p (Z_of_nat x));\n    intros Htest q (H1ltq, Hqle).\n    case_eq (test_odds n (p -2) (Z_of_nat x)).\n    + intros Htest'true.\n      rewrite Htest'true in Htest.\n      unfold divides_bool in Htest.\n      elim (le_lt_or_eq q (2*S n + 1)%nat Hqle).\n      *  intros Hqlt.\n         assert (Hqle': (q <= (2* S n))%nat) by  omega.\n         elim (le_lt_or_eq q (2 * S n)%nat Hqle').\n         replace (2*S n)%nat with (2*n +2)%nat.\n         intros Hqlt'.\n         assert (Hqle'' : (q <= 2*n +1)%nat) by omega.\n         apply (IHn x (p - 2)); auto with zarith arith.\n         rewrite Hp; rewrite inj_S; unfold Zsucc; ring.\n         ring.\n         intros Hq (y, Hdiv); elim (test_odds_correct2 n x H1ltx (p - 2)); auto.\n         exists (S n * y)%nat; rewrite Hdiv; rewrite Hq; ring.\n  \n      * intros Hq Hex; assert (Hp' : p = Z_of_nat q).\n        rewrite Hp; rewrite Hq; rewrite inj_plus; rewrite inj_mult; auto.\n        rewrite Hp' in Htest; rewrite (verif_divide x q) in Htest.\n        simpl in Htest; discriminate.\n        omega.\n        omega.\n        elim Hex; intros y Hdiv; exists y; rewrite Hdiv; ring.\n    + intros Htest'; rewrite Htest' in Htest; simpl in Htest; discriminate.\nQed.\n\nAxiom divisor_smaller :\n  (forall m p:nat, 0 < m -> forall q:nat, m = q*p -> q <= m)%nat.\n\n\nTheorem lt_Zpos : forall p:positive, 0 < Zpos p.\nProof.\n intros p; elim p.\n -  intros; rewrite Zpos_xI; omega.\n -  intros; rewrite Zpos_xO; omega.\n -  auto with zarith.\nQed.\n\nTheorem Zneg_lt : forall p:positive, Zneg p < 0.\nProof.\n intros p; elim p.\n -  intros; rewrite Zneg_xI; omega.\n -  intros; rewrite Zneg_xO; omega.\n -  auto with zarith.\nQed.\n\n\nTheorem prime_test_correct :\n forall n:nat, prime_test n = true ->\n ~(exists k:nat, k <> 1 /\\ k <> n /\\ (exists q:nat, n = q*k))%nat.\nProof.\n intros n; case_eq n.\n -  simpl;  intros Heq Hd; discriminate.\n -  intros n0; case_eq n0.\n   +  simpl; intros Heq1 Heq2 Hd; discriminate.\n   + unfold prime_test; intros n1 Heqn0 Heqn.\n     assert (H1ltn : (1 < n)%nat).\n     *  rewrite Heqn; auto with arith.\n     * rewrite <- Heqn.\n       lazy beta zeta delta [prime_test].\n       case_eq (Z.sqrt (Z_of_nat n)).\n       intros Hsqrt_eq.\n       elim (Zlt_asym 1 (Z_of_nat n)).\n       omega.\n       lapply (Z.sqrt_spec (Z_of_nat n)).\n       rewrite Hsqrt_eq; simpl.\n       omega.\n       omega.\n       intros p Hsqrt_eq Htest_eq (k, (Hn1, (Hnn, (q,Heq)))).\n       assert (H0ltn:(0 < n)%nat) by  omega.\n       assert (Hkltn:(k < n)%nat).\n       assert (Heq' : n=(k*q)%nat).\n       rewrite Heq; ring.\n       generalize (divisor_smaller n q H0ltn k Heq'). \n       omega.\n       assert (Hex: exists k':nat, (1 < (Z_of_nat k') <= (Z.sqrt (Z_of_nat n))) /\\\n               (exists q':nat, n=(k'*q')%nat)).\n       elim (div_Zsqrt (Z_of_nat k) (Z_of_nat n) (Z_of_nat q)).\n       intros Hint1; exists k;split.\n       omega.\n       exists q; rewrite Heq; ring.\n       intros Hint2; exists q; split.\n       split.\n       elim (Zle_or_lt (Z_of_nat q) 1); auto.\n       intros hqle1;  assert (Hq1: q = 1%nat).\n       omega.\n       rewrite Hq1 in Heq; simpl in Heq; elim Hnn; rewrite Heq; ring.\n       tauto.\n       exists k; auto.\n       split.\n       case_eq k.\n       intros Hk0; rewrite Hk0 in Heq; rewrite Heq in H1ltn;\n       rewrite mult_0_r in H1ltn; omega.\n       intros; unfold Zlt; simpl; auto.\n       omega.\n       rewrite Zmult_comm; rewrite <- inj_mult; rewrite Heq;auto.\n       elim Hex; intros k' ((H1ltk', Hk'ltsqrt), Hex'); clear Hex.\n       case_eq p.\n       intros p' Hp; rewrite Hp in Htest_eq.\n       elim (test_odds_correct (Zabs_nat (Zpos p'))\n           n (Zpos p)) with k'.\n       rewrite Z_to_nat_and_back.\n       rewrite Hp.\n       auto with zarith.\n       auto with zarith.\n       auto.\n       repeat rewrite Zminus_0_r in Htest_eq.\n       rewrite Hp; auto.\n       split.\n       omega.\n       apply Z_of_nat_le.\n       rewrite inj_plus.\n       rewrite inj_mult.\n       rewrite Z_to_nat_and_back.\n       simpl (Z_of_nat 2).\n       simpl (Z_of_nat 1).\n       rewrite <- Zpos_xI.\n       rewrite <- Hp.\n       rewrite <- Hsqrt_eq; auto.\n       auto with zarith.\n       auto.\n       intros p' Hp; rewrite Hp in Htest_eq.\n       elim (test_odds_correct (Zabs_nat (Zpos p')) n (Zpos p + 1))\n       with k'.\n       rewrite Z_to_nat_and_back.\n       rewrite Hp; rewrite Zpos_xO; ring.\n       generalize (lt_Zpos p'); intros; omega.\n       auto.\n       rewrite <- Hp in Htest_eq; auto.\n       split; try omega.\n       apply Z_of_nat_le.\n       rewrite inj_plus.\n       rewrite inj_mult.\n       rewrite Z_to_nat_and_back.\n       simpl (Z_of_nat 2); simpl (Z_of_nat 1).\n       rewrite <- Zpos_xO.\n       rewrite <- Hp; omega.\n       auto with zarith.\n       auto.\n       intros Hp; rewrite Hp in Hsqrt_eq.\n       rewrite Hsqrt_eq in Hk'ltsqrt.\n       omega.\n       intros p Hsqrt_eq.\n       elim (Zle_not_lt 0 (Z.sqrt (Z_of_nat n))).\n       apply Z.sqrt_nonneg.\n       rewrite Hsqrt_eq.\n       apply Zneg_lt.\nQed.\n\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch16_proof_by_reflection/SRC/prime_sqrt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6956062747632185}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_NCdistinct.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_NChelper.\n\nSection Euclid.\n\nContext `{Ax1:euclidean_neutral_ruler_compass}.\n\nLemma lemma_samesidecollinear : \n   forall A B C P Q, \n   OS P Q A B -> Col A B C -> neq A C ->\n   OS P Q A C.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists p q r, (Col A B p /\\ Col A B q /\\ BetS P p r /\\ BetS Q q r /\\ nCol A B P /\\ nCol A B Q)) by (conclude_def OS );destruct Tf as [p[q[r]]];spliter.\nassert (neq A B) by (forward_using lemma_NCdistinct).\nassert (eq A A) by (conclude cn_equalityreflexive).\nassert (Col A B A) by (conclude_def Col ).\nassert (nCol A C P) by (conclude lemma_NChelper).\nassert (nCol A C Q) by (conclude lemma_NChelper).\nassert (Col B A p) by (forward_using lemma_collinearorder).\nassert (Col B A C) by (forward_using lemma_collinearorder).\nassert (neq B A) by (conclude lemma_inequalitysymmetric).\nassert (Col A C p) by (conclude lemma_collinear4).\nassert (Col B A q) by (forward_using lemma_collinearorder).\nassert (Col A C q) by (conclude lemma_collinear4).\nassert (OS P Q A C) by (conclude_def OS ).\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_samesidecollinear.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6955981695170331}}
{"text": "Require Import Coq.Arith.EqNat.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.micromega.Psatz.\n\nImport ListNotations.\n\nDefinition tree_id := (nat * list nat) % type.\n\nNotation root := (0, []).\n\nModule TreeId.\n  Definition tick (p:tree_id) :=\n  let (n, l) := p in (S n, l).\n\n  Definition child (p:tree_id) : tree_id :=\n  let (n, l) := p in (0, n :: l).\n\n  Definition add (p:tree_id) m :=\n  let (n, l) := p in (n + m, l).\nEnd TreeId.\n\nModule Interval.\n  Section Spec.\n  \n  Import TreeId.\n\n  Require Import Coq.QArith.QArith.\n\n  Definition interval := (Q * Q) % type.\n\n  Definition max (x y:Q) :=\n  if Qlt_le_dec x y then y else x.\n\n  Definition min (x y:Q) :=\n  if Qlt_le_dec x y then x else y.\n\n  Definition merge (i j:interval) : interval :=\n  let (l1, h1) := i in\n  let (l2, h2) := j in\n  (min l1 l2, max h1 h2).\n\n  Open Scope Q_scope.\n\n  Definition iroot : interval := (0, 1).\n\n  Definition halve (i:interval) := \n  let (l, h) := i in\n  (h - l) * (1# 2).\n\n  Definition itick (i:interval) :=\n  let (l, h) := i in\n  (l, h - halve i).\n\n  Definition ichild (i:interval) :=\n  let (l, h) := i in\n  (h - halve i, h).\n\n  Fixpoint iadd (i:interval) (n:nat) :=\n  match n with\n  | 0 % nat => i\n  | S n => iadd (itick i) n\n  end.\n\n  Fixpoint itree (l:list nat) :=\n  match l with\n  | nil => iroot\n  | n :: l => iadd (ichild (itree l)) n\n  end.\n\n  Definition from_tree (t:tree_id) :=\n  let (n, l) := t in itree (n:: l).\n\n  Lemma tick_add_0:\n    forall i,\n    itick i = iadd i 1.\n  Proof.\n    intros.\n    auto.\n  Qed.\n\n  Lemma itick_iadd:\n    forall n i,\n    iadd (itick i) n = itick (iadd i n).\n  Proof.\n    induction n; intros. {\n      simpl; auto.\n    }\n    simpl.\n    rewrite IHn.\n    auto.\n  Qed.\n\n  Lemma itick_iadd_1:\n    forall n i,\n    itick (iadd i n) = iadd i (S n).\n  Proof.\n    intros.\n    simpl.\n    rewrite itick_iadd.\n    auto.\n  Qed.\n\n  Lemma tick_1:\n    forall (t:tree_id),\n    itick (from_tree t) = from_tree (tick t).\n  Proof.\n    intros.\n    destruct t.\n    simpl.\n    rewrite itick_iadd.\n    auto.\n  Qed.\n\n  Lemma iadd_iadd:\n    forall n (i:interval) m,\n    iadd (iadd i n) m = iadd i (n + m).\n  Proof.\n    induction n; intros. {\n      simpl; auto.\n    }\n    simpl.\n    rewrite IHn.\n    auto.\n  Qed.\n\n  Lemma add_1:\n    forall (t:tree_id) n,\n    iadd (from_tree t) n = from_tree (add t n).\n  Proof.\n    intros.\n    destruct t.\n    simpl.\n    rewrite iadd_iadd.\n    auto.\n  Qed.\n\n  Lemma ichild_child:\n    forall t,\n    from_tree (child t) = ichild (from_tree t).\n  Proof.\n    intros.\n    destruct t.\n    simpl.\n    auto.\n  Qed.\n\n  Goal iroot = (0, 1).\n    auto.\n  Qed.\n\n  Goal itick iroot = (0, 1 # 2).\n    simpl.\n    compute.\n    auto.\n  Qed.\n\n  Goal ichild iroot = (1 # 2, 1).\n    auto.\n  Qed.\n\n  Goal itick (ichild iroot) = (1#2, 3#4).\n    simpl.\n    compute.\n    auto.\n  Qed.\n\n  Goal ichild (ichild iroot) = (3#4, 1).\n    compute.\n    auto.\n  Qed.\n\n  Goal itree [2%nat] = itick (itick (ichild iroot)).\n    compute.\n    auto.\n  Qed.\n\n  Inductive Overlap: interval -> interval -> Prop :=\n  | overlap_def:\n    forall l1 h1 l2 h2,\n    l1 <= h2 ->\n    l2 < h1 ->\n    Overlap (l1, h1) (l2, h2).\n\n  Lemma overlap_dec i1 i2 :\n    { Overlap i1 i2 } + { ~ Overlap i1 i2 }.\n  Proof.\n    destruct i1 as (l1,h1), i2 as (l2,h2).\n    destruct (Qlt_le_dec h2 l1). {\n      right.\n      unfold not; intros.\n      inversion H.\n      lra.\n    }\n    destruct (Qlt_le_dec l2 h1). {\n      auto using overlap_def.\n    }\n    right.\n    unfold not; intros N.\n    inversion N.\n    lra.\n  Defined.\n\n  Inductive Follows: interval -> interval -> Prop :=\n  | follows_def:\n    forall l1 h1 l2 h2,\n    h1 == l2 ->\n    Follows (l1, h1) (l2, h2).\n\n  Inductive Contiguous i1 i2 : Prop :=\n  | contiguous_l:\n    Follows i1 i2 ->\n    Contiguous i1 i2\n  | contiguous_2:\n    Follows i2 i1 ->\n    Contiguous i1 i2.\n\n  Inductive Prec : interval -> interval -> Prop :=\n  | prec_def:\n    forall l1 h1 l2 h2,\n    h1 < l2 ->\n    Prec (l1, h1) (l2, h2).\n\n  Inductive CanMerge i1 i2 : Prop :=\n  | can_merge_overlap:\n    Overlap i1 i2 ->\n    CanMerge i1 i2\n  | can_merge_contiguous:\n    Contiguous i1 i2 ->\n    CanMerge i1 i2.\n\nEnd Spec.\nEnd Interval.\n\nModule Event.\n  Import Interval.\n  Definition event := (interval * nat) % type.\n\n  Definition union (e1 e2:event) :=\n  let (i1, n1) := e1 in\n  let (i2, n2) := e2 in\n  (merge i1 i2, Nat.max n1 n2).\n\n  Inductive Lt : event -> event -> Prop :=\n  | lt_def:\n    forall i1 i2 n1 n2,\n    Overlap i1 i2 ->\n    n1 < n2->\n    Lt (i1, n1) (i2, n2).\n\n  Lemma lt_trans:\n    forall e1 e2 e3,\n    Overlap (fst e1) (fst e3) ->\n    Lt e1 e2 ->\n    Lt e2 e3 ->\n    Lt e1 e3.\n  Proof.\n    intros (i1, n1) (i2, n2) (i3, n3); intros.\n    inversion H0; inversion H1; subst; clear H0 H1; simpl in *; subst.\n    auto using lt_def with *.\n  Qed.\n\n  Inductive CanUnion: event -> event -> Prop :=\n  | can_union_def:\n    forall i1 i2 n1 n2,\n    CanMerge i1 i2 ->\n    CanUnion (i1,n1) (i2,n2).\n\nEnd Event.\n\nModule Stamp.\n  Import Event.\n  Definition stamp := (event * list event) % type.\n\n  Definition Le l1 l2 :=\n    forall x y,\n    List.In x l1 ->\n    List.In y l2 ->\n    Event.Le x y.\n\nEnd Stamp.\n\nModule Others.\n\n  Inductive Observes : list nat -> list nat -> Prop :=\n  | observes_def:\n    forall x y l,\n    x > y ->\n    Observes (x::l) (y::l).\n\n  Inductive Spawn: tree_id -> tree_id -> Prop :=\n  | spawn_def:\n    forall n l,\n    Spawn (S n, l) (0, n::l).\n\n  Inductive ParentOf : tree_id -> tree_id -> Prop :=\n  | parent_of_def:\n    forall a b c l,\n    a > c ->\n    ParentOf (a, l) (b, c :: l).\n\n  Lemma spawn_to_parent_of:\n    forall x y,\n    Spawn x y ->\n    ParentOf x y.\n  Proof.\n    intros.\n    inversion H; subst; clear H.\n    apply parent_of_def.\n    auto.\n  Qed.\n\nDefinition parent_of (l:list nat) (r:list nat) :=\nmatch r with\n| _ :: r => if (list_eq_dec PeanoNat.Nat.eq_dec l r) then true else false\n| _ => false\nend.\n\n(*\nGoal parent_of [0;0] [1;0;0]  = true.\n  compute.\n  trivial.\nQed.\n*)\nDefinition lt_sibling (l r:list nat) :=\nmatch l, r with\n| x :: l, y :: r =>\n  if (lt_dec x y) then\n    if (list_eq_dec PeanoNat.Nat.eq_dec l r) then true else false\n  else false\n| _,_ => false\nend.\n\nDefinition gt_sibling (l r:list nat) := lt_sibling r l.\n\nDefinition contains (i j:list nat) :=\nlet fix ancestor_gt_sibling i j :=\n  match i with\n  | _ :: i => gt_sibling i j || ancestor_gt_sibling i j\n  | _ => false\n  end\nin\nif parent_of i j then true else ancestor_gt_sibling i j.\n(*\nGoal contains [3;1;0] [0;0]  = true.\n  compute; auto.\nQed.\n\nGoal contains [3;1;0] [2;0]  = false.\n  compute;auto.\nQed.\n\nGoal contains [3;3;0] [2;0]  = true.\n  compute;auto.\nQed.\n*)\nSection AsCG.\n  Require Import SafeJoins.\n  Import SJ_Notations.\n  Require Import Tid.\n\n  Inductive MapsTo : tree_id -> tid -> list op -> Prop :=\n  | maps_to_tick_root:\n    forall x y,\n    MapsTo (tick root) x [F x y]\n  | maps_to_child_root:\n    forall x y,\n    MapsTo (child root) y [F x y]\n  | maps_to_fork_parent:\n    forall x y t k,\n    MapsTo t x k ->\n    MapsTo (tick t) x (F x y::k)\n  | maps_to_fork_child:\n    forall x y t k,\n    MapsTo t x k ->\n    MapsTo (child t) y (F x y::k)\n  | maps_to_fork_neq:\n    forall x y z k t,\n    z <> x ->\n    MapsTo t z k ->\n    MapsTo t z (F x y::k)\n  | maps_to_join:\n    forall x y z t k,\n    MapsTo t z k ->\n    MapsTo t z (J x y::k).\n\n  Lemma maps_to_inv_0:\n    forall t x y,\n    x <> y ->\n    MapsTo t x [F x y] ->\n    t = tick root.\n  Proof.\n    intros.\n    inversion H0; subst; clear H0; auto; intuition.\n    inversion H4.\n  Qed.\n\n  Lemma maps_to_inv_1:\n    forall t x y,\n    x <> y ->\n    MapsTo t y [F x y] ->\n    t = child root.\n  Proof.\n    intros.\n    inversion H0; subst; clear H0; subst; simpl; intuition.\n    + inversion H4.\n    + inversion H7.\n  Qed.\n\n  Lemma maps_to_inv_2:\n    forall t x o,\n    MapsTo t x [o] ->\n    exists y,\n    (o = F x y /\\ t = tick root)\n    \\/\n    (o = F y x /\\ t = child root).\n  Proof.\n    intros.\n    inversion H; subst; clear H; eauto; try inversion H3.\n    inversion H5.\n  Qed.\n\n  Lemma trace_inv_0:\n    forall o,\n    Trace [o] ->\n    exists x y, F x y = o.\n  Proof.\n    intros.\n    inversion H; subst. {\n      eauto.\n    }\n    inversion H; subst.\n    inversion H3.\n  Qed.\n\n  Lemma maps_to_inv_3:\n    forall k t x y,\n    x <> y ->\n    k <> nil ->\n    Trace (F x y :: k) ->\n    MapsTo t x (F x y :: k) ->\n    exists s, t = tick s /\\ MapsTo s x k.\n  Proof.\n    induction k; intros; auto. {\n      intuition.\n    }\n    destruct k. {\n      inversion H1; subst; clear H1.\n      inversion H2; subst; clear H2; intuition.\n      apply maps_to_inv_2 in H5.\n      destruct H5 as (z, [(?,He)|(?,He)]); inversion He; subst. {\n        eauto using maps_to_tick_root.\n      }\n      eauto using maps_to_child_root.\n    }\n    inversion H1; subst; clear H1.\n    inversion H2; subst; clear H2; eauto; intuition.\n  Qed.\n\n  Lemma maps_to_to_in:\n    forall t x k,\n    MapsTo t x k ->\n    Graph.In (Edge k) x.\n  Proof.\n    intros.\n    induction H;\n    eauto using\n    Graph.in_left, Graph.in_right,\n    edge_fork_eq, Graph.in_impl, edge_cons.\n  Qed.\n\n  Lemma maps_to_fun:\n    forall k t s x,\n    Trace k ->\n    MapsTo t x k ->\n    MapsTo s x k ->\n    t = s.\n  Proof.\n    induction k; intros. {\n      inversion H0.\n    }\n    destruct a as ([], a, b). {\n      inversion H; subst.\n      inversion H0; subst; clear H0.\n      + apply maps_to_inv_0 in H1; auto.\n      + apply maps_to_inv_1 in H1; auto.\n      + destruct k. {\n          inversion H8.\n        }\n        apply maps_to_inv_3 in H1; auto with *.\n        destruct H1 as (s', (?, Hm)).\n        subst.\n        apply IHk with (t:=t0) in Hm; subst; auto.\n      + inversion H1; subst; clear H1; intuition.\n        * inversion H8.\n        * assert (t0 = t) by eauto; subst; auto.\n        * contradiction H6.\n          eauto using maps_to_to_in.\n      + inversion H1; subst; clear H1; intuition.\n        * inversion H11.\n        * contradiction H6.\n          eauto using maps_to_to_in.\n        * eauto.\n    }\n    inversion H0; subst; clear H0.\n    inversion H1; subst; clear H1.\n    inversion H; subst; eauto.\n  Qed.\n\n  Lemma maps_to_inv_4:\n    forall x y s t k,\n    Trace (F x y :: k) ->\n    MapsTo s x (F x y :: k) ->\n    MapsTo t x k ->\n    s = tick t.\n  Proof.\n    intros.\n    destruct k. {\n      inversion H1.\n    }\n    inversion H; subst.\n    apply maps_to_inv_3 in H0; auto with *.\n    destruct H0 as (t', (He, Hm)); subst.\n    assert (He: t = t') by eauto using maps_to_fun.\n    subst; auto.\n  Qed.\n\n  Lemma maps_to_inv_5:\n    forall x y z t,\n    x <> y ->\n    MapsTo t z [F x y] ->\n    (t = tick root /\\ z = x) \\/\n    (t = child root /\\ z = y).\n  Proof.\n    intros.\n    inversion H0; subst; auto; try inversion H4.\n    inversion H7.\n  Qed.\n\n  Lemma maps_to_inv_6:\n    forall x y z,\n    MapsTo (tick root) x [F y z] ->\n    y = x.\n  Proof.\n    intros.\n    inversion H; subst; clear H; auto. {\n      inversion H3.\n    }\n    inversion H6.\n  Qed.\n\n  Lemma maps_to_inv_7:\n    forall x y z,\n     MapsTo (child root) x [F y z] ->\n     x = z.\n   Proof.\n    intros.\n    inversion H; subst; clear H; auto. {\n      inversion H3.\n    }\n    inversion H6.\n   Qed.\n\n  Lemma child_neq_tick:\n    forall x y,\n    child x <> tick y.\n  Proof.\n    intros.\n    unfold not; intros.\n    destruct x, y.\n    simpl in *.\n    inversion H.\n  Qed.\n\n  Lemma maps_to_absurd_0:\n    forall k n m l x y,\n    n <> m ->\n    MapsTo (n, l) x k ->\n    ~ MapsTo (m, l) y k.\n  Proof.\n    induction k; intros. {\n      inversion H0.\n    }\n    unfold not; intros.\n    inversion H0; subst; clear H0.\n    - inversion H1; subst; clear H1.\n      + contradiction H; auto.\n      + inversion H4.\n      + inversion H4.\n      + inversion H7.\n    - inversion H1; subst; clear H1.\n      + contradiction H; auto.\n      + inversion H4.\n      + inversion H4.\n      + inversion H7.\n    - destruct t; subst.\n      inversion H2; subst; clear H2.\n      inversion H1; subst; clear H1.\n      + inversion H5.\n      + inversion H5.\n      + destruct t.\n        simpl in *.\n        destruct m. {\n          inversion H0.\n        }\n        inversion H0; subst; clear H0.\n        assert (n0 <> m). {\n          unfold not; intros; subst.\n          contradiction H; auto.\n        }\n        eapply IHk in H4; eauto.\n      + destruct t.\n        simpl in *.\n        destruct m. {\n          inversion H0; subst; clear H0.\n        }\n        apply child_neq_tick in H; contradiction.\n      + destruct t0.\n        simpl in *.\n        destruct n. {\n          \n        }\n  Qed.\n\n  Lemma maps_to_fun_2:\n    forall k t x y,\n    Trace k ->\n    MapsTo t x k ->\n    MapsTo t y k ->\n    x = y.\n  Proof.\n    induction k; intros. {\n      inversion H0.\n    }\n    inversion H; subst. {\n      inversion H0; subst; clear H0.\n      - apply maps_to_inv_6 in H1; subst; auto.\n      - apply maps_to_inv_7 in H1; subst; auto.\n      - inversion H1; subst; clear H1.\n        + inversion H8.\n        + inversion H8.\n        + auto.\n        + apply child_neq_tick in H0; contradiction.\n        + apply IHk with (x:=x0) (y:=y) in H6.\n    }\n  Qed.\n\n\n  Inductive In t k : Prop :=\n  | in_def:\n    forall x,\n    MapsTo t x k ->\n    In t k.\n\n  Inductive TreeId t x : list op -> Prop :=\n  | tree_id_eq:\n    forall k,\n    MapsTo t x k ->\n    TreeId t x k\n  | tree_id_cons:\n    forall k e,\n    TreeId t x k ->\n    TreeId t x (e::k).\n\n  Inductive ForkTree : tid * tid -> tree_id * tree_id -> list op -> Prop :=\n  | fork_tree_eq:\n    forall x y t1 t2 k,\n    MapsTo t1 x (F x y::k) ->\n    MapsTo t2 y (F x y::k) ->\n    ForkTree (x,y) (t1, t2) (F x y::k)\n  | fork_tree_cons:\n    forall e1 e2 e3 k,\n    ForkTree e1 e2 k ->\n    ForkTree e1 e2 (e3::k).\n\n  Lemma parent_of_child:\n    forall t,\n    ParentOf (tick t) (child t).\n  Proof.\n    intros (n, l).\n    unfold tick, child; simpl.\n    auto using parent_of_def, observes_def with *.\n  Qed.\n\n  Lemma fork_tree_to_parent_of:\n    forall k x y s t,\n    Trace k ->\n    ForkTree (x, y) (s, t) k ->\n    ParentOf s t.\n  Proof.\n    induction k; intros. {\n      inversion H0.\n    }\n    inversion H0; subst; clear H0. {\n      inversion H; subst.\n      inversion H8; subst; clear H8; intuition.\n      + apply maps_to_inv_0 in H4; auto; subst.\n        auto using parent_of_child.\n      + eapply maps_to_inv_4 in H7; eauto; subst.\n        auto using parent_of_child.\n      + contradiction H5.\n        eauto using maps_to_to_in.\n    }\n    inversion H; subst; clear H; eauto.\n  Qed.\n\n  Let absurd_cons:\n    forall {A} l (x:A), x :: l <> l.\n  Proof.\n    induction l; intros. {\n      auto with *.\n    }\n    unfold not; intros N.\n    inversion N.\n    apply IHl in H1.\n    contradiction.\n  Qed.\n\n  Let absurd_cons_cons:\n    forall {A} l (x y:A), y :: x :: l <> l.\n  Proof.\n    induction l; intros. {\n      auto with *.\n    }\n    unfold not; intros N.\n    inversion N.\n    apply IHl in H1.\n    contradiction.\n  Qed.\n\n  Lemma observes_length:\n    forall x y,\n    Observes x y ->\n    length x = length y.\n  Proof.\n    induction x; intros. {\n      inversion H.\n    }\n    inversion H; subst.\n    simpl; auto.\n  Qed.\n\n  Lemma observes_irrefl:\n    forall x,\n    ~ Observes x x.\n  Proof.\n    intros.\n    unfold not; intros.\n    inversion H; subst; clear H.\n    intuition.\n  Qed.\n\n  Lemma observes_asymm:\n    forall x y,\n    Observes x y ->\n    ~ Observes y x.\n  Proof.\n    intros.\n    unfold not; intros.\n    inversion H; subst; clear H.\n    inversion H0; subst; clear H0.\n    intuition.\n  Qed.\n\n  Lemma parent_of_asymm:\n    forall x y,\n    ParentOf x y ->\n    ~ ParentOf y x.\n  Proof.\n    intros.\n    unfold not; intros.\n    inversion H; subst; clear H.\n    inversion H0; clear H0.\n    rewrite <- H3 in *.\n    rewrite H3 in *.\n    apply absurd_cons_cons in H5.\n    contradiction.\n  Qed.\n\n  Lemma parent_of_irrefl:\n    forall x,\n    ~ ParentOf x x.\n  Proof.\n    intros.\n    unfold not; intros.\n    inversion H.\n    apply absurd_cons in H3.\n    contradiction.\n  Qed.\n\n  Lemma parent_of_tick_snd:\n    forall x y,\n    ParentOf x y ->\n    ParentOf x (tick y).\n  Proof.\n    intros.\n    inversion H; subst; clear H; simpl.\n    apply parent_of_def; simpl; auto.\n  Qed.\n\n  Lemma parent_of_absurd_root:\n    forall x,\n    ~ ParentOf x root.\n  Proof.\n    intros.\n    unfold not; intros.\n    inversion H; subst.\n  Qed.\n\n  Lemma parent_of_absurd_tick_root:\n    forall x,\n    ~ ParentOf x (tick root).\n  Proof.\n    intros.\n    unfold not; intros.\n    inversion H; subst.\n  Qed.\n\n  Lemma spawn_absurd_tick_root:\n    forall x,\n    ~ Spawn x (tick root).\n  Proof.\n    unfold tick, not; intros.\n    inversion H.\n  Qed.\n\n  Require Import Omega.\n\n  Lemma parent_of_child_root:\n    forall x,\n    ParentOf x (child root) ->\n    exists n, x = tick (n, []).\n  Proof.\n    intros.\n    unfold tick.\n    simpl.\n    inversion H; subst; clear H.\n    destruct a. {\n      omega.\n    }\n    eauto.\n  Qed.\n\n  Let fork_tree_eq_0:\n    forall x y,\n    ForkTree (x, y) (tick root, child root) [F x y].\n  Proof.\n    intros.\n    auto using fork_tree_eq, maps_to_tick_root, maps_to_child_root.\n  Qed.\n\n  Lemma parent_of_simpl_left:\n    forall x y,\n    ParentOf x (tick y) ->\n    ParentOf x y.\n  Proof.\n    intros.\n    destruct y as (n, l); simpl in *.\n    inversion H; subst; clear H.\n    auto using parent_of_def.\n  Qed.\n\n  Lemma fork_tree_eq_fork:\n    forall x y k t,\n    x <> y ->\n    ~ Graph.In (Edge k) y ->\n    MapsTo t x k ->\n    ForkTree (x, y) (tick t, child t) (F x y :: k).\n  Proof.\n    intros.\n    auto using fork_tree_eq, maps_to_fork_parent, maps_to_fork_child.\n  Qed.\n\n  Lemma spawn_irrefl:\n    forall x,\n    ~ Spawn x x.\n  Proof.\n    unfold not; intros.\n    destruct x.\n    inversion H.\n  Qed.\n\n  Lemma spawn_inv_tick_child:\n    forall x y,\n    Spawn (tick x) (child y) ->\n    x = y.\n  Proof.\n    intros.\n    destruct x, y.\n    unfold child, tick in *.\n    inversion H; subst.\n    auto.\n  Qed.\n\n  Lemma spawn_absurd_tick_tick:\n    forall x y,\n    ~ Spawn (tick x) (tick y).\n  Proof.\n    intros; destruct x, y.\n    simpl.\n    unfold not; intros.\n    inversion H.\n  Qed.\n\n  Lemma maps_to_inv_root:\n    forall k x,\n    ~ MapsTo root x k.\n  Proof.\n    induction k; unfold not; intros. {\n      inversion H.\n    }\n    inversion H; subst; clear H.\n    - destruct t.\n      simpl in *.\n      inversion H0.\n    - destruct t.\n      simpl in *.\n      inversion H0.\n    - apply IHk in H5.\n      contradiction.\n    - apply IHk in H3; contradiction.\n  Qed.\n\n  Lemma tick_absurd_0:\n    forall x,\n    tick x <> x.\n  Proof.\n    intros.\n    destruct x.\n    unfold not; intros.\n    simpl in *.\n    inversion H.\n    omega.\n  Qed.\n\n  Ltac simpl_tree :=\n  repeat match goal with\n  | [ H : ParentOf ?x ?x |- _ ] =>\n    apply parent_of_irrefl in H; contradiction\n  | [ H : Spawn ?x ?x |- _ ] =>\n    apply spawn_irrefl in H; contradiction\n  | [ H: Spawn (child ?x) (tick ?x) |- _ ] =>\n    inversion H\n  | [ H: Spawn (tick ?x) (child ?x) |- _ ] =>\n    clear H\n  | [ H: ParentOf _ (tick root) |- _ ] =>\n    apply parent_of_absurd_tick_root in H; contradiction\n  | [ H: Spawn (tick _) (tick _) |- _ ] =>\n    apply spawn_absurd_tick_tick in H; contradiction\n  | [ H: Spawn (tick ?x) (child ?y) |- _ ] =>\n    apply spawn_inv_tick_child in H; rewrite H in *; clear H\n  | [ H: Spawn _ (tick root) |- _ ] =>\n    apply spawn_absurd_tick_root in H; contradiction\n  | [ H: MapsTo root _ _ |- _ ] =>\n    apply maps_to_inv_root in H; contradiction\n  | [ H: MapsTo _ _ nil |- _ ] =>\n    inversion H\n  | [ H: MapsTo ?t ?x ?k, H2: MapsTo ?s ?x ?k |- _ ] =>\n    assert (t = s) by eauto using maps_to_fun; subst; clear H2\n  end.\n\n  Lemma parent_of_to_fork_tree:\n    forall k x y s t,\n    Trace k ->\n    MapsTo t x k ->\n    MapsTo s y k ->\n    Spawn t s ->\n    ForkTree (x, y) (t, s) k.\n  Proof.\n    induction k; intros; simpl_tree.\n    inversion H; subst; clear H. {\n      inversion H0; subst; clear H0.\n      + apply maps_to_inv_5 in H1; auto.\n        destruct H1 as [(?,?)|(?,?)]; subst; simpl_tree.\n        auto using fork_tree_eq_fork.\n      + apply maps_to_inv_5 in H1; auto.\n        destruct H1 as [(?,?)|(?,?)]; subst; simpl_tree.\n      + inversion H1; subst; clear H1; simpl_tree. {\n          auto using fork_tree_eq_fork.\n        }\n        apply fork_tree_cons.\n        inversion H11; subst; clear H11; simpl_tree.\n        - inversion H8; subst; clear H8; simpl_tree. {\n            \n          }\n        - destruct t0; simpl in *.\n          unfold root, child in *.\n          simpl in *.\n          inversion H2; subst.\n        inversion H2; subst; clear H2.\n        destruct t0; simpl in *.\n        inversion H0; subst; clear H0.\n        inversion H11; subst; clear H11.\n        - destruct t.\n          simpl in *.\n          inversion H; subst; clear H.\n        - destruct t.\n          simpl in *.\n          subst.\n          apply \n        destruct x, t0; simpl in *; subst; simpl in *; simpl_tree.\n        apply fork_tree_cons.\n        apply IHk; auto using spawn_def.\n        unfold tick.\n        simpl.\n    }\n    inversion H0; subst.\n    - inversion H0.\n    - inversion H0; subst; clear H0.\n      + apply maps_to_inv_5 in H1; auto.\n        destruct H1 as [(?,?)|(?,?)]; subst; simpl_tree; auto.\n      + apply maps_to_inv_5 in H1; auto.\n        destruct H1 as [(?,?)|(?,?)]; subst; simpl_tree.\n      + inversion H1; subst; clear H1; simpl_tree.\n        * auto using fork_tree_eq_fork.\n        * apply fork_tree_cons.\n  Qed.\n\n  Inductive JoinTree : tree_id -> tree_id -> list op -> Prop :=\n  | join_tree_eq:\n    forall x y t1 t2 k,\n    MapsTo t1 x k ->\n    MapsTo t2 y k ->\n    JoinTree t1 t2 (J x y::k)\n  | join_tree_cons:\n    forall t1 t2 k e,\n    JoinTree t1 t2 k ->\n    JoinTree t1 t2 (e :: k).\n\n  Lemma fork_spec_1 k es (Hs: Safe k es):\n    forall x y t s,\n    MapsTo t x k ->\n    MapsTo s y k ->\n    ForkTree t s k ->\n    List.In (F x y) k.\n  Proof.\n    induction k; intros. {\n      inversion H; subst; clear H.\n    }\n    destruct a as ([], a,b). {\n      destruct (tid_eq_dec x a). {\n        subst.\n        destruct (tid_eq_dec y b). {\n          subst.\n          auto using in_eq.\n        }\n        inversion Hs; subst; clear Hs.\n        inversion H4; subst; clear H4.\n      }\n    }\n  Qed.\n\n  Inductive ForkEdge x y k : Prop :=\n  | fork_edge_def:\n    forall t s,\n    ForkTree t s k ->\n    TreeId t x k ->\n    TreeId s y k ->\n    ForkEdge x y k.\n\n  Lemma fork_spec_1:\n    forall k x y,\n    ForkEdge x y k ->\n    List.In (F x y) k.\n  Proof.\n    induction k; intros. {\n      inversion H; subst; clear H.\n      inversion H1; inversion H.\n    }\n    inversion H; subst; clear H. {\n      inversion H0; subst; clear H0. {\n        \n      }\n    }\n  Qed.\n\nEnd AsCG.\n", "meta": {"author": "cogumbreiro", "repo": "gorn-coq", "sha": "ee4384d7ae8513c314ffb25027c4249903c6275b", "save_path": "github-repos/coq/cogumbreiro-gorn-coq", "path": "github-repos/coq/cogumbreiro-gorn-coq/gorn-coq-ee4384d7ae8513c314ffb25027c4249903c6275b/src/TreeId.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6955981561071812}}
{"text": "(* File: Lists.v *)\n(* Title: Lists - Data Structures in Coq *)\n(* Author: Peter Urbak <peteru@dragonwasrobot.com> *)\n(* Version: 2012-09-24 *)\n\nRequire Export \"Basics\".\n\nModule NatList.\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.\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  intros n m.\n  unfold fst.\n  unfold snd.\n  reflexivity.\nQed.\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.\n  destruct p as (n, m).\n  unfold fst.\n  unfold snd.\n  reflexivity.\nQed.\n\n(* Exercise: 1 star (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.\n  destruct p as (n, m).\n  unfold swap_pair.\n  unfold snd.\n  unfold fst.\n  reflexivity.\nQed.\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.\n  destruct p as (n, m).\n  unfold swap_pair.\n  unfold fst.\n  unfold snd.\n  reflexivity.\nQed.\n\n(* Lists of Numbers *)\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\n(* Added the ' on repeat to avoid wrong syntax highlighting in emacs. *)\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) (at level 60, right associativity).\n\nExample test_app1 : [1,2,3] ++ [4,5] = [1,2,3,4,5].\nProof. unfold app. reflexivity. Qed.\n\nExample test_app2 : nil ++ [4,5] = [4,5].\nProof. unfold app. reflexivity. Qed.\n\nExample test_app3 : [1,2,3] ++ nil = [1,2,3].\nProof. unfold app. 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. unfold hd. reflexivity. Qed.\n\nExample test_hd2 : hd 0 [] = 0.\nProof. unfold hd. reflexivity. Qed.\n\nExample test_tail : tail [1,2,3] = [2,3].\nProof. unfold tail. reflexivity. Qed.\n\n(* Exercise: 2 stars, recommended (list_funs) *)\n\nFixpoint nonzeros (l : natlist) : natlist :=\n  match l with\n    | nil => nil\n    | O :: t => (nonzeros t)\n    | h :: t => h :: (nonzeros t)\n  end.\n\nExample test_nonzeros : nonzeros [0,1,0,2,3,0,0] = [1,2,3].\nProof. unfold nonzeros. reflexivity. Qed.\n\nFixpoint oddmembers (l : natlist) : natlist :=\n  match l with\n    | nil => nil\n    | h :: t => match (evenb h) with\n                  | true => (oddmembers t)\n                  | false => h :: (oddmembers t)\n                end\n  end.\n\nExample test_oddmembers : oddmembers [0,1,0,2,3,0,0] = [1,3].\nProof. unfold oddmembers. unfold evenb. reflexivity. Qed.\n\nFixpoint countoddmembers (l : natlist) : nat :=\n  match l with\n    | nil => O\n    | h :: t => match (evenb h) with\n                  | true => (countoddmembers t)\n                  | false => S (countoddmembers t)\n                end\n  end.\n\nExample test_countoddmembers1: countoddmembers [1,0,3,1,4,5] = 4.\nProof. unfold countoddmembers. unfold evenb. reflexivity. Qed.\n\nExample test_countoddmembers2: countoddmembers [0,2,4] = 0.\nProof. unfold countoddmembers. unfold evenb. reflexivity. Qed.\n\nExample test_countoddmembers3: countoddmembers nil = 0.\nProof. unfold countoddmembers. unfold evenb. reflexivity. Qed.\n\n(* Exercise: 3 stars (alternate) *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n    | nil, l2 => l2\n    | l1, nil => l1\n    | h1 :: t1, h2 :: t2 => h1 :: h2 :: (alternate t1 t2)\n  end.\n\nLemma unfold_alternate_inductive_case : forall (h1 h2 : nat) (t1 t2 : natlist),\n  alternate (h1 :: t1) (h2 :: t2) = h1 :: h2 :: (alternate t1 t2).\nProof.\n  intros h1 h2 t1 t2.\n  unfold alternate.\n  fold alternate.\n  reflexivity.\nQed.\n\nLemma alternate_nil_l_case : forall (h1 : nat) (t1 : natlist),\n  alternate [] (h1 :: t1) = (h1 :: t1).\nProof.\n  intros h1 t1.\n  unfold alternate.\n  reflexivity.\nQed.\n\nLemma alternate_nil_r_case : forall (h1 : nat) (t1 : natlist),\n  alternate (h1 :: t1) [] = (h1 :: t1).\nProof.\n  intros h1 t1.\n  unfold alternate.\n  reflexivity.\nQed.\n\nExample test_alternate1 : alternate [1,2,3] [4,5,6] = [1,4,2,5,3,6].\nProof. unfold alternate. reflexivity. Qed.\nExample test_alternate2: alternate [1] [4,5,6] = [1,4,5,6].\nProof. unfold alternate. reflexivity. Qed.\nExample test_alternate3: alternate [1,2,3] [4] = [1,4,2,3].\nProof. unfold alternate. reflexivity. Qed.\nExample test_alternate4: alternate [] [20,30] = [20,30].\nProof. unfold alternate. reflexivity. Qed.\n\n(* Bags via Lists *)\n\nDefinition bag := natlist.\n\n(* Exercise: 3 stars (bag_functions) *)\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\nLemma unfold_count_inductive_case : forall (v h : nat) (t : bag),\n  count v (h :: t) = match (beq_nat h v) with\n                       | true => S (count v t)\n                       | false => (count v t)\n                     end.\nProof.\n  intros v h t.\n  unfold count.\n  fold count.\n  reflexivity.\nQed.\n\nExample test_count1: count 1 [1,2,3,1,4,1] = 3.\nProof. unfold count. unfold beq_nat. reflexivity. Qed.\nExample test_count2: count 6 [1,2,3,1,4,1] = 0.\nProof. unfold count. unfold beq_nat. reflexivity. Qed.\n\nDefinition sum : bag -> bag -> bag :=\n  alternate.\n\nLemma sum_eq_alternate : sum = alternate.\nProof. unfold sum. reflexivity. Qed.\n\nExample test_sum1: count 1 (sum [1,2,3] [1,4,1]) = 3.\nProof. unfold sum. unfold alternate. unfold count.\nunfold beq_nat. reflexivity. Qed.\n\nDefinition add (v : nat) (s : bag) : bag :=\n  app [v] s.\n\nExample test_add1 : count 1 (add 1 [1,4,1]) = 3.\nProof. unfold add. unfold app. unfold count.\nunfold beq_nat. reflexivity. Qed.\nExample test_add2 : count 5 (add 1 [1,4,1]) = 0.\nProof. unfold add. unfold app. unfold count.\nunfold beq_nat. reflexivity. Qed.\n\nDefinition member (v : nat) (s : bag) : bool :=\n  blt_nat O (count v s).\n\nExample test_member1 : member 1 [1,4,1] = true.\nProof. unfold member. unfold count. unfold beq_nat.\nunfold blt_nat. unfold ble_nat. unfold beq_nat.\nunfold negb. unfold andb. reflexivity. Qed.\n\nExample test_member1' : member 1 [1,4,1] = true.\nProof. reflexivity. Qed.\n\nExample test_member2 : member 2 [1,4,1] = false.\nProof. unfold member. unfold count. unfold beq_nat.\nunfold blt_nat. unfold ble_nat. unfold beq_nat.\nunfold negb. unfold andb. reflexivity. Qed.\n\nExample test_member2' : member 2 [1,4,1] = false.\nProof. reflexivity. Qed.\n\n(* Exercise: 3 stars, optional (bag_more_functions) *)\n\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. unfold remove_one. unfold beq_nat. unfold count. unfold beq_nat.\nreflexivity. Qed.\n\nExample test_remove_one2: count 5 (remove_one 5 [2,1,4,1]) = 0.\nProof. unfold remove_one. unfold beq_nat. unfold count. unfold beq_nat.\nreflexivity. Qed.\n\nExample test_remove_one3: count 4 (remove_one 5 [2,1,4,5,1,4]) = 2.\nProof. unfold remove_one. unfold beq_nat. unfold count. unfold beq_nat.\nreflexivity. Qed.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2,1,5,4,5,1,4]) = 1.\nProof. unfold remove_one. unfold beq_nat. unfold count. unfold beq_nat.\nreflexivity. 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. unfold remove_all. unfold beq_nat. unfold count. unfold beq_nat.\nreflexivity. Qed.\n\nExample test_remove_all2: count 5 (remove_all 5 [2,1,4,1]) = 0.\nProof. unfold remove_all. unfold beq_nat. unfold count. unfold beq_nat.\nreflexivity. Qed.\n\nExample test_remove_all3: count 4 (remove_all 5 [2,1,4,5,1,4]) = 2.\nProof. unfold remove_all. unfold beq_nat. unfold count. unfold beq_nat.\nreflexivity. 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(* From now on I won't do all the unfolding for Examples unless I feel it is\n   important for the particular example. *)\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n    | nil => true\n    | h :: t => match member h s2 with\n                  | true => (subset t (remove_one h s2))\n                  | false => false\n                end\n    end.\n\nExample test_subset1: subset [1,2] [2,1,4,1] = true.\nProof. reflexivity. Qed.\n\nExample test_subset2: subset [1,2,2] [2,1,4,1] = false.\nProof.  reflexivity. Qed.\n\n(* Exercise: 3 stars, recommended (bag_theorem) *)\n\n(* Hmm, will simply show that count increment when another of the element type\n   being looked for is added to the list. *)\n\nTheorem bag_theorem : forall (v : nat) (s : bag),\n  count v (add v s) = S (count v s).\nProof.\n  intros v s.\n  unfold add.\n  unfold app.\n  unfold count.\n  fold count.\n  rewrite <- beq_nat_refl.\n  reflexivity.\nQed.\n\n(* Reasoning about Lists *)\n\nTheorem nil_app : forall (l : natlist),\n  [] ++ l = l.\nProof.\n  intro l.\n  unfold app.\n  reflexivity.\nQed.\n\nTheorem tl_length_pred : forall (l : natlist),\n  pred (length l) = length (tail l).\nProof.\n  intro l.\n  destruct l as [ | l' ].\n\n  Case \"l = nil\".\n  unfold tail.\n  unfold length.\n  unfold pred.\n  reflexivity.\n\n  Case \"l = cons n l'\".\n  unfold tail.\n  unfold pred.\n  unfold length.\n  reflexivity.\nQed.\n\n(* Induction on Lists *)\n\nTheorem app_ass : forall (l1 l2 l3 : natlist),\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3.\n  induction l1 as [ | n l1' ].\n\n  Case \"l1 = nil\".\n  unfold app.\n  fold app.\n  reflexivity.\n\n  Case \"l1 = cons n l1'\".\n  unfold app.\n  fold app.\n  rewrite -> IHl1'.\n  reflexivity.\nQed.\n\nTheorem app_length : forall (l1 l2 : natlist),\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros l1 l2.\n  induction l1 as [ | n l1' ].\n\n  Case \"l1 = nil\".\n  unfold app.\n  unfold length.\n  fold length.\n  unfold plus.\n  reflexivity.\n\n  Case \"l1 = cons n l1'\".\n  unfold app.\n  fold app.\n  unfold length.\n  fold length.\n  rewrite -> IHl1'.\n  rewrite -> plus_Sn_m.\n  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.\n\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\n  Case \"l = nil\".\n  unfold snoc.\n  unfold length.\n  reflexivity.\n\n  Case \"l = cons n' l'\".\n  unfold snoc.\n  fold snoc.\n  unfold length.\n  fold length.\n  rewrite -> IHl'.\n  reflexivity.\nQed.\n\nTheorem rev_length : forall (l : natlist),\n  length (rev l) = length l.\nProof.\n  intro l.\n  induction l as [ | n l' ].\n\n  Case \"l = nil\".\n  unfold rev.\n  unfold length.\n  reflexivity.\n\n  Case \"l = cons n l'\".\n  unfold rev.\n  fold rev.\n  unfold length.\n  fold length.\n  rewrite -> length_snoc.\n  rewrite -> IHl'.\n  reflexivity.\nQed.\n\n(* List Exercises, Part 1 *)\n\n(* Exercise: 3 stars, recommended (list_exercises) *)\n\nTheorem app_nil_end : forall (l : natlist),\n  l ++ [] = l.\nProof.\n  intro l.\n  induction l as [ | n l' ].\n\n  Case \"l = nil\".\n  unfold app.\n  reflexivity.\n\n  Case \"l = cons n l'\".\n  unfold app.\n  fold app.\n  rewrite -> IHl'.\n  reflexivity.\nQed.\n\nLemma unfold_app_inductive_case : forall (h : nat) (t l : natlist),\n  app (h :: t) l = h :: (app t l).\nProof.\n  intros h t l.\n  unfold app.\n  fold app.\n  reflexivity.\nQed.\n\nLemma unfold_snoc_inductive_case : forall (h n : nat) (t : natlist),\n  snoc (h :: t) n = h :: (snoc t n).\nProof.\n  intros h n l.\n  unfold snoc.\n  fold snoc.\n  reflexivity.\nQed.\n\nLemma unfold_rev_inductive_case : forall (h : nat) (t : natlist),\n  rev (h :: t) = snoc (rev t) h.\nProof.\n  intros h t.\n  unfold rev.\n  fold rev.\n  reflexivity.\nQed.\n\nLemma rev_snoc : forall (n : nat) (l : natlist),\n  rev (snoc l n) = n :: (rev l).\nProof.\n  intros n l.\n  induction l as [ | n' l' ].\n  unfold rev.\n  unfold snoc.\n  reflexivity.\n\n  unfold snoc.\n  fold snoc.\n  unfold rev.\n  fold rev.\n  rewrite -> IHl'.\n  unfold snoc.\n  fold snoc.\n  reflexivity.\nQed.\n\nTheorem rev_involutive : forall (l : natlist),\n  rev (rev l) = l.\nProof.\n  intro l.\n  induction l as [ | n l' ].\n\n  Case \"l = nil\".\n  unfold rev.\n  reflexivity.\n\n  Case \"l = cons n l'\".\n  rewrite -> unfold_rev_inductive_case.\n  rewrite -> rev_snoc.\n  rewrite -> IHl'.\n  reflexivity.\nQed.\n\nTheorem snoc_append : forall (n : nat) (l : natlist),\n  snoc l n = l ++ [n].\nProof.\n  intros n l.\n  induction l as [ | n' l' ].\n\n  Case \"l = nil\".\n  unfold app.\n  unfold snoc.\n  reflexivity.\n\n  Case \"l = cons n' l'\".\n  rewrite -> unfold_snoc_inductive_case.\n  rewrite -> unfold_app_inductive_case.\n  rewrite -> IHl'.\n  reflexivity.\nQed.\n\nTheorem distr_rev : forall (l1 l2 : natlist),\n  rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n  intros l1 l2.\n  induction l1 as [ | n l' ].\n\n  Case \"l1 = nil\".\n  unfold rev.\n  fold rev.\n  rewrite -> app_nil_end.\n  unfold app.\n  reflexivity.\n\n  Case \"l2 = cons n l'\".\n  rewrite -> unfold_app_inductive_case.\n  rewrite -> unfold_rev_inductive_case.\n  rewrite -> snoc_append.\n  rewrite -> IHl'.\n  rewrite -> unfold_rev_inductive_case.\n  rewrite -> snoc_append.\n  rewrite -> app_ass.\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 l1 l2 l3 l4.\n  rewrite -> app_ass.\n  rewrite -> app_ass.\n  reflexivity.\nQed.\n\nLemma nonzeros_length : forall (l1 l2 : natlist),\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2.\n  induction l1 as [ | n l1'].\n\n  Case \"l1 = nil\".\n  unfold app at 1.\n  unfold nonzeros at 2.\n  unfold app at 1.\n  reflexivity.\n\n  Case \"l1 = cons n l1'\".\n  rewrite -> unfold_app_inductive_case.\n  unfold nonzeros.\n  fold nonzeros.\n  rewrite -> IHl1'.\n  case n.\n\n  SCase \"n = O\".\n  reflexivity.\n\n  SCase \"n = S n'\".\n  intros n'.\n  reflexivity.\nQed.\n\n(* List Exercises, Part 2 *)\n\n(* Exercise: 2 stars, recommended (list_design) *)\n\nTheorem cons_snoc : forall (h n : nat) (t : natlist),\n  (cons h t) ++ [n] = [h] ++ (snoc t n).\nProof.\n  intros h n t.\n  rewrite -> unfold_app_inductive_case.\n  rewrite -> unfold_app_inductive_case.\n  rewrite -> snoc_append.\n  unfold app at 2.\n  reflexivity.\nQed.\n\n(* Exercise: 2 stars, optional (bag_proofs) *)\n\nTheorem count_member_nonzero : forall (s : bag),\n  ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n  intro s.\n  induction s as [ | n s' ].\n\n  Case \"s = nil\".\n  unfold count.\n  unfold beq_nat.\n  unfold ble_nat.\n  reflexivity.\n\n  Case \"s = cons n s'\".\n  unfold count.\n  fold count.\n  unfold beq_nat.\n  fold beq_nat.\n  case (beq_nat n 1).\n\n  SCase \"(beq_nat n 1) = true\".\n  unfold ble_nat.\n  reflexivity.\n\n  SCase \"(beq_nat n 1) = false\".\n  unfold ble_nat.\n  reflexivity.\nQed.\n\nTheorem ble_nat_refl : forall n,\n  ble_nat n n = true.\nProof.\n  intro n.\n  induction n as [ | n' ].\n\n  Case \"n = O\".\n  unfold ble_nat.\n  reflexivity.\n\n  Case \"n = S n'\".\n  unfold ble_nat.\n  fold ble_nat.\n  rewrite -> IHn'.\n  reflexivity.\nQed.\n\nTheorem ble_n_Sn : forall n,\n  ble_nat n (S n) = true.\nProof.\n  intros n.\n  induction n as [ | n' ].\n\n  Case \"n = O\".\n  unfold ble_nat.\n  reflexivity.\n\n  Case \"n = S n'\".\n  unfold ble_nat.\n  fold ble_nat.\n  rewrite -> IHn'.\n  reflexivity.\nQed.\n\nTheorem remove_decreases_count : forall (s : bag),\n  ble_nat (count O (remove_one O s)) (count O s) = true.\nProof.\n  intro s.\n  induction s as [ | n s' ].\n\n  Case \"s = nil\".\n  unfold remove_one.\n  unfold count.\n  unfold ble_nat.\n  reflexivity.\n\n  Case \"s = cons n s'\".\n  unfold remove_one.\n  fold remove_one.\n  case (beq_nat 0 n).\n\n  SCase \"(beq_nat 0 n) = true\".\n  unfold count.\n  fold count.\n  case (beq_nat n 0).\n\n  SSCase \"(beq_nat n 0) = true\".\n  rewrite -> ble_n_Sn.\n  reflexivity.\n\n  SSCase \"(beq_nat n 0) = false\".\n  rewrite -> ble_nat_refl.\n  reflexivity.\n\n  SCase \"(beq_nat 0 n) = false\".\n  unfold count.\n  fold count.\n  case (beq_nat n 0).\n\n  SSCase \"(beq_nat n 0) = true\".\n  unfold count.\n  fold count.\n  unfold ble_nat.\n  fold ble_nat.\n  rewrite -> IHs'.\n  reflexivity.\n\n  SSCase \"(beq_nat n 0) = false\".\n  rewrite -> IHs'.\n  reflexivity.\nQed.\n(* Hmm, a bit long, maybe it can be done simpler without all the subcases. *)\n\n(* Exercise: 3 stars, optional (bag_count_sum) *)\n\nTheorem bag_count_sum : forall (n : nat) (s1 s2 : bag),\n  (count n s1) + (count n s2) = count n (alternate s1 s2).\nProof.\n  intros n s1 s2.\n  induction s1 as [ | n1' s1' ].\n\n  Case \"s1 = []\".\n  induction s2 as [ | n2' s2' ].\n\n  SCase \"s2 = []\".\n  simpl.\n  reflexivity.\n\n  SCase \"s2 = n2' :: s2'\".\n  simpl.\n  reflexivity.\n\n  Case \"s1 = n1' :: s1'\".\n  induction s2 as [ | n2' s2' ].\n\n  SCase \"s2 = []\".\n  simpl.\n  rewrite -> plus_O_r.\n  reflexivity.\n\n  SCase \"s2 = n2' :: s2'\".\n  Admitted. (* to be continued *)\n\n(* Exercise: 4 stars, optional (rev_injective) *)\n\nTheorem rev_injective : forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2.\n  intro 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\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 (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\nDefinition hd_opt (l : natlist) : natoption :=\n  match l with\n    | nil => None\n    | h :: t => Some h\n  end.\n\nExample test_hd_opt1 : hd_opt [] = None.\nProof. reflexivity. Qed.\nExample test_hd_opt2 : hd_opt [1] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_opt3 : hd_opt [5,6] = Some 5.\nProof. reflexivity. Qed.\n\n(* Exercise: 2 stars, optional (option_elim_hd) *)\n\nTheorem option_elim_hd : forall (l : natlist) (default : nat),\n  hd default l = option_elim default (hd_opt l).\nProof.\n  intros l default.\n  induction l as [ | n l' ].\n\n  Case \"l = nil\".\n  unfold hd_opt.\n  unfold option_elim.\n  unfold hd.\n  reflexivity.\n\n  Case \"l = cons n l'\".\n  unfold hd_opt.\n  unfold option_elim.\n  unfold hd.\n  reflexivity.\nQed.\n\n(* Exercise: 2 stars, recommended (beq_natlist) *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n    | nil, nil => true\n    | (h1 :: t1), (h2 :: t2) => if beq_nat h1 h2 then (beq_natlist t1 t2) else false\n    | _, _ => false\n    end.\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\nExample test_beq_natlist2 : beq_natlist [1,2,3] [1,2,3] = true.\nProof. reflexivity. Qed.\nExample test_beq_natlist3 : beq_natlist [1,2,3] [1,2,4] = false.\nProof. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall (l : natlist),\n  true = beq_natlist l l.\nProof.\n  intro l.\n  induction l as [ | n l' ].\n\n  Case \"l = nil\".\n  unfold beq_natlist.\n  reflexivity.\n\n  Case \"l = cons n l'\".\n  unfold beq_natlist.\n  fold beq_natlist.\n  rewrite <- beq_nat_refl.\n  rewrite <- IHl'.\n  reflexivity.\nQed.\n\n(* Extended Exercise: 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 k key) then (Some v) else (find key d')\n  end.\n\n(* Exercise: 1 star (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.\n  induction d as [ | k' v' d' ].\n\n  Case \"d = empty\".\n  unfold insert.\n  unfold find.\n  rewrite <- beq_nat_refl.\n  reflexivity.\n\n  Case \"d = (record k' v' d')\".\n  unfold insert.\n  unfold find.\n  fold find.\n  rewrite <- beq_nat_refl.\n  reflexivity.\nQed.\n\n(* Exercise: 1 star (dictionary_invariant2) *)\n\n(* took the liberity of writing 'beq_nat n m' instead of 'beq_nat m n' so I\n   didn't have to prove beq_nat n m = beq_nat m n. *)\nTheorem dictionary_invariant2 : forall (d : dictionary) (m n o : nat),\n  (beq_nat n m) = false -> (find m d) = (find m (insert n o d)).\nProof.\n  intros d m n o.\n  intro H.\n  induction d as [ | n' o' d' ].\n\n  Case \"d = empty\".\n  unfold insert.\n  unfold find.\n  rewrite -> H.\n  reflexivity.\n\n  Case \"d = (record n' o' d')\".\n  unfold insert.\n  unfold find.\n  fold find.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nEnd Dictionary.\n\nEnd NatList.\n\n(* end-of-Lists.v *)\n", "meta": {"author": "sunshuai0719", "repo": "software-foundations-exercises", "sha": "7bca1be885da90f1ca85f3753f5ed72aa9c2f168", "save_path": "github-repos/coq/sunshuai0719-software-foundations-exercises", "path": "github-repos/coq/sunshuai0719-software-foundations-exercises/software-foundations-exercises-7bca1be885da90f1ca85f3753f5ed72aa9c2f168/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321936479701, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.6955760767204295}}
{"text": "Require Import rt.util.all.\nRequire Import rt.model.arrival.basic.task rt.model.arrival.basic.job rt.model.arrival.basic.task_arrival.\nRequire Import rt.model.schedule.uni.schedule.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.\n\nModule ResponseTime.\n\n  Import UniprocessorSchedule SporadicTaskset TaskArrival.\n\n  (* In this section, we define the notion of a response-time bound. *)\n  Section ResponseTimeBound.\n\n    Context {sporadic_task: eqType}.\n    Context {Job: eqType}.\n    Variable job_arrival: Job -> time.\n    Variable job_cost: Job -> time.\n    Variable job_task: Job -> sporadic_task.\n\n    (* Consider any job arrival sequence... *)\n    Variable arr_seq: arrival_sequence Job.\n\n    (* ...and any uniprocessor schedule of these jobs. *)\n    Variable sched: schedule Job.\n\n    (* Let tsk be any task that is to be analyzed. *)\n    Variable tsk: sporadic_task.\n\n    (* For simplicity, let's define some local names. *)\n    Let job_has_completed_by := completed_by job_cost sched.\n\n    (* Then, we say that R is a response-time bound of tsk in this schedule ... *)\n    Variable R: time.\n\n    (* ... iff any job j of tsk in this arrival sequence has\n       completed by (job_arrival j + R). *)\n    Definition is_response_time_bound_of_task :=\n      forall j,\n        arrives_in arr_seq j ->\n        job_task j = tsk ->\n        job_has_completed_by j (job_arrival j + R).\n        \n  End ResponseTimeBound.\n\n  (* In this section, we prove some basic lemmas about response-time bounds. *)\n  Section BasicLemmas.\n\n    Context {sporadic_task: eqType}.\n    Context {Job: eqType}.\n    Variable job_arrival: Job -> time.\n    Variable job_cost: Job -> time.\n    Variable job_task: Job -> sporadic_task.\n    \n    (* Consider any job arrival sequence... *)\n    Variable arr_seq: arrival_sequence Job.\n\n    (* ...and any uniprocessor schedule of these jobs. *)\n    Variable sched: schedule Job.\n\n    (* Assume that jobs don't execute after completion. *)\n    Hypothesis H_completed_jobs_dont_execute:\n      completed_jobs_dont_execute job_cost sched.\n\n    (* For simplicity, let's define some local names. *)\n    Let job_has_completed_by := completed_by job_cost sched.\n\n    (* We begin by proving lemmas about job response-time bounds. *)\n    Section SpecificJob.\n\n      (* Let j be any job... *)\n      Variable j: Job.\n      \n      (* ...with response-time bound R. *)\n      Variable R: time.\n      Hypothesis response_time_bound:\n        job_has_completed_by j (job_arrival j + R). \n\n      (* Then, the service received by j at any time t' after its response time is 0. *)\n      Lemma service_after_job_rt_zero :\n        forall t',\n          t' >= job_arrival j + R ->\n          service_at sched j t' = 0.\n      Proof.\n        rename response_time_bound into RT,\n               H_completed_jobs_dont_execute into EXEC; ins.\n        unfold is_response_time_bound_of_task, completed_by,\n               completed_jobs_dont_execute in *.\n        apply/eqP; rewrite -leqn0.\n        rewrite <- leq_add2l with (p := job_cost j).\n        move: RT => /eqP RT; rewrite -{1}RT addn0.\n        apply leq_trans with (n := service sched j t'.+1);\n          last by apply EXEC.\n        unfold service, service_during.\n        rewrite -> big_cat_nat with (p := t'.+1) (n := job_arrival j + R);\n          [rewrite leq_add2l /= | by ins | by apply ltnW].\n        by rewrite big_nat_recr // /=; apply leq_addl.\n      Qed.\n\n      (* The same applies for the cumulative service of job j. *)\n      Lemma cumulative_service_after_job_rt_zero :\n        forall t' t'',\n          t' >= job_arrival j + R ->\n          \\sum_(t' <= t < t'') service_at sched j t = 0.\n      Proof.\n        ins; apply/eqP; rewrite -leqn0.\n        rewrite big_nat_cond; rewrite -> eq_bigr with (F2 := fun i => 0);\n          first by rewrite big_const_seq iter_addn mul0n addn0 leqnn.\n        intro i; rewrite andbT; move => /andP [LE _].\n        by rewrite service_after_job_rt_zero;\n          [by ins | by apply leq_trans with (n := t')].\n      Qed.\n      \n    End SpecificJob.\n\n    (* Next, we prove properties about task response-time bounds. *)\n    Section AllJobs.\n\n      (* Consider any task tsk ...*)\n      Variable tsk: sporadic_task.\n\n      (* ... for which a response-time bound R is known. *)\n      Variable R: time.\n      Hypothesis response_time_bound:\n        is_response_time_bound_of_task job_arrival job_cost job_task arr_seq sched tsk R.\n\n      (* Then, for any job j of this task, ...*)\n      Variable j: Job.\n      Hypothesis H_from_arrival_sequence: arrives_in arr_seq j.\n      Hypothesis H_job_of_task: job_task j = tsk.\n\n      (* ...the service received by job j at any time t' after the response time is 0. *)\n      Lemma service_after_task_rt_zero :\n        forall t',\n          t' >= job_arrival j + R ->\n          service_at sched j t' = 0.\n      Proof.\n        intros t' LE.\n        apply service_after_job_rt_zero with (R := R); last by done.\n        by apply response_time_bound.\n      Qed.\n\n      (* The same applies for the cumulative service of job j. *)\n      Lemma cumulative_service_after_task_rt_zero :\n        forall t' t'',\n          t' >= job_arrival j + R ->\n          \\sum_(t' <= t < t'') service_at sched j t = 0.\n      Proof.\n        by ins; apply cumulative_service_after_job_rt_zero with (R := R);\n          first by apply response_time_bound. \n      Qed.\n      \n    End AllJobs.\n\n  End BasicLemmas.\n    \nEnd ResponseTime.", "meta": {"author": "cd-public", "repo": "rt-proofs", "sha": "ebef0b65460fe009c51f638fe2b459f16a6d1dd5", "save_path": "github-repos/coq/cd-public-rt-proofs", "path": "github-repos/coq/cd-public-rt-proofs/rt-proofs-ebef0b65460fe009c51f638fe2b459f16a6d1dd5/model/schedule/uni/response_time.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.6955760714938868}}
{"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.\nRequire Import List.\n\nRequire Import list_utils.\nRequire Import finite.\n\nSet Implicit Arguments.\n\nSection minimizer.\n\n  Variable (X : Type) (f : X -> nat).\n  \n  Let minimizer_rec n ll : 1 <= length ll < n -> { a | In a ll /\\ forall b, In b ll -> f a <= f b }.\n  Proof.\n    revert ll.\n    induction n as [ | n IHn ]; intros ll (H1 & H2).\n    omega.\n    destruct ll as [ | a ll ].\n    contradict H1; simpl; omega.\n    destruct (list_dec_rec (fun b => f b < f a) ll) as [ (a' & Ha1 & Ha2) | Ha ].\n    intros; apply lt_dec.\n    \n    destruct (IHn ll) as (m & H3 & H4).\n    split.\n    destruct ll; simpl in H2 |- *; try omega.\n    destruct Ha1.\n    simpl in H2; omega.\n    exists m; split.\n    right; auto.\n    intros b [ Hb | Hb ]; auto.\n    subst b; apply le_trans with (1 := H4 _ Ha1); auto; omega.\n    \n    exists a; split.\n    left; auto.\n    intros b [ Hb | Hb ]; auto.\n    subst; auto.\n    specialize (Ha _ Hb); omega.\n  Qed.\n  \n  Let minimizer_list ll : ll <> nil -> { a | In a ll /\\ forall b, In b ll -> f a <= f b }.\n  Proof.\n    intros Hll.\n    apply minimizer_rec with (n := S (length ll)).\n    destruct ll.\n    contradict Hll; auto.\n    simpl; omega.\n  Qed.\n  \n  Fact minimizer_finite (P : X -> Prop) : finite P\n                                       -> (exists a, P a)\n                                       -> exists a, P a /\\ forall b, P b -> f a <= f b.\n  Proof.\n    intros (ll & Hll) (a & Ha).\n    destruct (@minimizer_list ll) as (m & H1 & H2).\n    apply Hll in Ha.\n    destruct ll.\n    destruct Ha.\n    discriminate.\n    exists m; split.\n    apply Hll; auto.\n    intros b Hb; apply H2, Hll; auto.\n  Qed.\n  \n  Fact minimizer_finite_t (P : X -> Prop) : finite_t P\n                                         -> (exists a, P a) \n                                         -> { a | P a /\\ forall b, P b -> f a <= f b }.\n  Proof.\n    intros (ll & Hll) Ha.\n    destruct (@minimizer_list ll) as (m & H1 & H2).\n    destruct Ha as (a & Ha).\n    apply Hll in Ha.\n    destruct ll.\n    destruct Ha.\n    discriminate.\n    exists m; split.\n    apply Hll; auto.\n    intros b Hb; apply H2, Hll; auto.\n  Qed.\n\nEnd minimizer.\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/minimizer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.6955760674075814}}
{"text": "Require Import init.\n\nRequire Import set_base.\n\nDefinition image {U V} (f : U → V) := λ y, ∃ x, y = f x.\nDefinition image_under {U V} (f : U → V) (S : U → Prop)\n    := λ y, ∃ x, S x ∧ y = f x.\nDefinition inverse_image {U V} (f : U → V) (T : V → Prop)\n    := λ x, T (f x).\n\nTheorem image_under_in {U V} : ∀ {f : U → V} {S : U → Prop} {x},\n    S x → image_under f S (f x).\nProof.\n    intros f S x Sx.\n    exists x.\n    split.\n    -   exact Sx.\n    -   reflexivity.\nQed.\n\nTheorem image_inverse_sub {U V} : ∀ (f : U → V) (S : V → Prop),\n    image_under f (inverse_image f S) ⊆ S.\nProof.\n    intros f S y [x [x_in eq]].\n    subst y.\n    exact x_in.\nQed.\n\nTheorem image_sub {U V} :\n    ∀ (f : U → V) S T, S ⊆ T → image_under f S ⊆ image_under f T.\nProof.\n    intros f S T sub y [x [Sx y_eq]].\n    subst y.\n    apply sub in Sx.\n    apply image_under_in.\n    exact Sx.\nQed.\n\nTheorem inverse_complement {U V} : ∀ (f : U → V) S,\n    inverse_image f (𝐂 S) = 𝐂 (inverse_image f S).\nProof.\n    intros f S.\n    reflexivity.\nQed.\n\nTheorem inverse_image_bij_inv {U V} : ∀ S (f : U → V) `{@Bijective U V f},\n    (inverse_image (bij_inv f) S) = image_under f S.\nProof.\n    intros S f f_bij.\n    apply antisym.\n    -   intros y y_in.\n        unfold inverse_image in y_in.\n        exists (bij_inv f y).\n        split; [>exact y_in|].\n        symmetry; apply inverse_eq2.\n        apply bij_inv_inv.\n    -   intros y [x [Sx y_eq]]; subst y.\n        unfold inverse_image.\n        rewrite inverse_eq1 by apply bij_inv_inv.\n        exact Sx.\nQed.\n\nTheorem bij_inverse_image {U V} : ∀ S (f : U → V),\n    Bijective f → image_under f (inverse_image f S) = S.\nProof.\n    intros S f f_bij.\n    apply antisym; [>apply image_inverse_sub|].\n    intros y Sy.\n    exists (bij_inv f y).\n    unfold inverse_image.\n    rewrite inverse_eq2 by apply bij_inv_inv.\n    split.\n    -   exact Sy.\n    -   reflexivity.\nQed.\n\nTheorem inj_inverse_image {U V} : ∀ S (f : U → V),\n    Injective f → inverse_image f (image_under f S) = S.\nProof.\n    intros S f f_inj.\n    apply antisym.\n    -   intros x [y [Sy eq]].\n        apply inj in eq.\n        subst.\n        exact Sy.\n    -   intros x Sx.\n        apply image_under_in.\n        exact Sx.\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/Set/set_function.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633915959134572, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.6955760573345755}}
{"text": "From LF Require Export Lists.\n(* \npolymorphism (abstracting functions over the types of the data they manipulate) \nhigher-order functions (treating functions as data).  \n*)\nDefinition odd (n:nat) :=\n  (negb (even n)).\n(* Coq supports polymorphic inductive types *)\nInductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\n(* list is a function from Types to Inductive definitions; \nor, to put it more concisely, list is a function from Types to Types. \nFor any particular type X, the type list X is the Inductively defined \nset of lists whose elements are of type X. *)\n\nCheck list : Type -> Type. \nCheck (nil nat) : list nat.\nCheck (cons nat 3 (nil nat)) : list nat.\n\n(* What is nil's type? \nIntuitively, it is (X : Type) → list X. \nBut Coq notation is represents it as follows. *)\nCheck nil : forall X : Type, list X.\n\nCheck cons : forall X : Type, X -> list X -> list X.\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.\nExample test_repeat1 : repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)). Proof. reflexivity. Qed.\nExample test_repeat2 : repeat bool false 1 = cons bool false (nil bool). Proof. reflexivity. Qed.\n\nModule MumbleGrumble.\nInductive mumble : Type :=\n  | a\n  | b (x : mumble) (y : nat)\n  | c.\nInductive grumble (X:Type) : Type :=\n  | d (m : mumble)\n  | e (x : X).\n\n(* \nTODO: \nWhich of the following are well-typed elements of grumble X for some type X? (Add YES or NO to each line.)\nd (b a 5)           NO since it has to use the mumble constructor \nd mumble (b a 5)    YES. type grumble mumble. Uses mumble constructor, where (b a 5) is type mumble because (1 2 3) in the mumble constructor, b=1 matches, a=2 matches since a is a mumble type, and 5=3 matches since 5 is nat\nd bool (b a 5)      NO, because (b a 5) expects to be a bool\ne bool true         YES, type grumble bool\ne mumble (b c 0)    YES, type grumble mumble\ne bool (b c 0)      NO because it expocts (b c 0) to be bool\nc                   YES, type mumble\n\n*)\nCheck (grumble nat ).\nCheck (d nat).\nCheck (e nat).\n\nCheck (d mumble (b a 5)).\nCheck (e bool true).\nCheck (e mumble (b c 0)).\nCheck d mumble (b a 5). \n\nCheck list nat. \nEnd MumbleGrumble.\n\n(* 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(* when Coq encounters a \"hole\" represented by underscore character _, \nit will attempt to unify all locally available information\n -- the type of the function being applied, the types of the other arguments, \nand the type expected by the context in which the application appears -- to determine \n    what concrete type should replace the _.\n     *)\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* Implicit Arguments *)\n\n(* The Arguments directive specifies the name of the function (or constructor) \nand then lists the (leading) argument names to be treated as implicit, each surrounded by curly braces. *)\nArguments nil {X}.\nArguments cons {X}.\nArguments repeat {X}.\n\n(* No need to supply type arg since it's explicitly told to be treated implict with Arguments declaration *)\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\n(* But don't make everything implicit. Consider the following list'  *)\nInductive list' {X:Type} : Type :=\n  | nil'\n  | cons' (x : X) (l : list').\n(* Because X is declared as implicit for the entire \ninductive definition including list' itself, we now \nhave to write just list' whether we are talking about \nlists of numbers or booleans or anything else, rather than \nlist' nat or list' bool or whatever; this is a step too far. *)\n\n(* So let's stick with our original implementation of list but with \nthe Arguments for nil, cons defined to treat their leading terms as implicit *)\n\n(* So we explicitly supply the generic type arg X for the list constructor, but not for the function type arg *)\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 _ t => 1 + length t \n    end. \n\nExample test_rev1 : rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)). Proof. reflexivity. Qed.\nExample test_rev2: rev (cons true nil) = cons true nil. Proof. reflexivity. Qed.\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3. Proof. reflexivity. Qed.\n\n    (* Supplying Type Arguments Explicitly *)\nDefinition mynil : list nat := nil.\n\n(* Alternatively, we can force the implicit arguments to\n be explicit by prefixing the function name with @. *)\nCheck 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\nDefinition list123''' := [1; 2; 3].\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n intros X l.\n induction l as [| n l' IHl']. \n - (* l = [] *)\n    reflexivity.\n - (* l = n :: l' *)\n    simpl. rewrite IHl'. reflexivity.\nQed.  \n\nTheorem app_assoc : forall (X: Type), forall (l m n: list X),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n    intros X l m n. \n    induction l as [| x l' IHl'].\n    - (* l = [] *)\n        simpl. reflexivity.\n    - (* l = n :: l'*)\n        simpl. rewrite <- IHl'. reflexivity.\nQed. \n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n    intros X l1 l2.\n    induction l1 as [| n l1' IHl1'].\n    - (* l1 = [] *)\n        reflexivity.\n    - (* l1 = n :: l1' *)\n        simpl. rewrite IHl1'. reflexivity. \nQed. \n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n    intros X l1 l2. \n    induction l1 as [| n l1' IHl1' ].\n    - (* l1 = [] *)\n        simpl. rewrite app_nil_r. reflexivity.\n    - (* l1 = n :: l1' *)\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 X l. \n    induction l as [| n l' IHl'].\n    - (* l = [] *)\n        reflexivity.\n    - (* l = n :: l' *)\n        simpl. rewrite rev_app_distr. rewrite IHl'. simpl. reflexivity.\nQed. \n\n(*  Polymorphic Pairs  *)\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\nArguments pair {X} {Y}.\nNotation \"( x , y )\" := (pair x y).\nNotation \"X * Y\" := (prod X Y) : type_scope.\n(* type_scope tells Coq that this abbreviation should only be used when parsing types, not when parsing expressions.  *)\n\n(* \nIt is easy at first to get (x,y) and X * Y confused. Remember that (x,y) is a value built from two other values, while X * Y is a type built from two other types. If x has type X and y has type Y, then (x,y) has type X * Y. \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\n(* often called zip, but calling it combine to be consistent with coq's stdlib  *)\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n        : list (X*Y) :=\nmatch lx, ly with\n    | [], _ => []\n    | _, [] => []\n    | x :: tx, y :: ty => (x, y) :: (combine tx ty)\nend.\nCompute (combine [1;2] [false;false;true;true]).\n(* [(1, false);(2, false)] *)\n\n\n(* USEFUL *)\n(* also known as unzip  *)\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 in (x::(fst t'), (y::(snd t')))\n    end. \n\nExample test_split0: split [(1,false);(2,false)] = ([1;2],[false;false]). Proof. reflexivity. Qed.\nExample test_split2: let t' := split [(1,false);(2,false)] in combine (fst t') (snd t') = [(1,false);(2,false)]. Proof. reflexivity. Qed.\n\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. Proof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2]. Proof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None. Proof. reflexivity. Qed.\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n    match l with \n        | [] => None \n        | h::t => Some h \n    end. \n\n    (* Force implicit arguments to be explicit *)\nCheck @hd_error : forall X : Type, list X -> option X.\nExample test_hd_error1 : hd_error [1;2] = Some 1. Proof. reflexivity. Qed.\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1]. Proof. reflexivity. Qed.\n\n\n    (* Higher Order Functions *)\n\nDefinition doit3times {X : Type} (f : X->X) (n : X) : X :=\n  f (f (f n)).\nCheck @doit3times : forall X : Type, (X -> X) -> X -> X.\n\nDefinition minustwo (n : nat) : nat :=\n    (minus n 2).\n\nExample test_doit3times: doit3times  minustwo 9 = 3. Proof. reflexivity. Qed.\nExample test_doit3times': doit3times negb true = false. Proof. reflexivity. Qed.\n\nFixpoint filter {X : Type} (pred : X -> bool) (l : list X) : list X :=\n    match l with \n        | [] => []\n        | h :: t => match (pred h) with\n                        | true => h :: (filter pred t) \n                        | false =>  (filter pred t)\n                    end \n    end. \nExample test_filter1: filter even [1;2;3;4] = [2;4]. Proof. reflexivity. Qed.\nExample test_filter2: filter negb [true;false;true] = [false]. Proof. reflexivity. Qed.\nExample test_filter3: filter even [2;4;6] = [2;4;6]. Proof. reflexivity. Qed.\nExample test_filter4: filter even [1;3;5] = []. Proof. reflexivity. Qed.\nExample test_filter5: filter even [] = []. Proof. reflexivity. Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  (length l) =? 1.\nExample test_filter6:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ]. Proof. reflexivity. Qed.\n\n    (* use lambda *)\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter (fun n => negb (even n)) l).\nExample test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4. Proof. reflexivity. Qed.\nExample test_countoddmembers'2:   countoddmembers' [0;2;4] = 0. Proof. reflexivity. Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0. Proof. reflexivity. Qed.\nExample test_anon_fun': doit3times (fun n => n * n) 2 = 256. Proof. reflexivity. Qed.\n\nExample test_filter6':\n    filter (fun l => (length l) =? 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\n    Definition filter_even_gt7 (l : list nat) : list nat:=\n        filter (fun n => (andb (even n) (geb n 7))) l.\nExample test_filter_even_gt7_1 : filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8]. Proof. reflexivity. Qed.\nExample test_filter_even_gt7_2 : filter_even_gt7 [5;2;6;19;129] = []. Proof. reflexivity. Qed.\n\n\nFixpoint partition' {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X :=\n    match l with \n      | [] => ([], [])\n      | h::t => let t' := (partition' test t) in match (test h) with \n                                | true => (h::(fst t'), (snd t'))\n                                | false => ((fst t'), h::(snd t'))\n                                end\n    end. \nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X := ((filter test l),(filter (fun n => (negb (test n))) l)).\n\nExample test_partition1: partition even [1;2;3;4;5] = ([2;4], [1;3;5] ).  Proof. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).  Proof. 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. \nDefinition mapf := fun n => (geb n 2). \nExample test_map0: (map mapf [1;2;3]) = [false;true;true].  Proof. reflexivity. Qed.\nExample test_map3:\n    map (fun n => [even n; (negb (even n))]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]]. Proof. reflexivity. Qed.\n\n\nLemma map_assoc : forall (X Y : Type) (f : X -> Y) (l1 l2 : list X) ,\n    (map f (l1 ++ l2)) = (map f l1) ++ (map f l2).\nProof. \n    intros X Y f l1 l2.\n    induction l1 as [| n l1' IHl1'].\n    - (* l1 = [] *)\n        reflexivity.\n    - (* l1 = n :: l1' *)\n        simpl. rewrite IHl1'. reflexivity.\nQed. \n\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros X Y f l. \n  induction l as [| n l' IHl'].\n  - (* l = [] *)\n    reflexivity.\n  - (* l = n :: l' *)\n    simpl. rewrite <- IHl'.  rewrite map_assoc. simpl. reflexivity.\nQed. \n\nFixpoint flat_map {X Y: Type} (f: X -> list Y) (l: list X)\n                   : list Y := \nmatch 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]. Proof. 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  (* \n  Intuitively, the behavior of the fold operation is to insert a given binary operator f between every pair of elements in a given list. For example, fold plus [1;2;3;4] intuitively means 1+2+3+4. To make this precise, we also need a \"starting element\" that serves as the initial second input to f. So, for example,\n       fold plus [1;2;3;4] 0\nyields\n       1 + (2 + (3 + (4 + 0))).\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\nExample fold_example1 : fold mult [1;2;3;4] 1 = 24. Proof. reflexivity. Qed. \n    (* FOLD LEFT\n    1 * (2 * (3 * (4 * 1)))\n    *)\nExample fold_example2 :fold andb [true;true;false;true] true = false. Proof. reflexivity. Qed.\nExample fold_example3 :fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4]. Proof. 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. Proof. reflexivity. Qed.\nExample constfun_example2 : (constfun 5) 99 = 5. Proof. reflexivity. Qed.\n(* \"plus is a one-argument function that takes a nat and returns a one-argument function that takes another nat and returns a nat.\"\n  RIGHT ASSOCIATIVE / PARTIAL APPLICATION *)\n\nDefinition plus3 := plus 3.\nCheck plus3 : nat -> nat.\nExample test_plus3 :    plus3 4 = 7. Proof. reflexivity. Qed.\nExample test_plus3' :   doit3times plus3 0 = 9. Proof. reflexivity. Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9. Proof. reflexivity. Qed.\n\nModule Exercises.\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. Proof. reflexivity. Qed.\n\nLemma fold_length_Sn : forall X (l : list X) (n : X),\n  fold_length (n :: l) = S (fold_length l).\nProof. \n  (* intros X l n. *)\n  reflexivity.\n  (* induction l as [| n' l' IHl'].\n  - (* l = [] *)\n    reflexivity.\n  - (* l = n' :: l' *)\n    simpl. reflexivity. *)\nQed. \nLemma fold_length_assoc : forall X (l1 l2 : list X),\n  fold_length (l1 ++ l2) = fold_length l1 + fold_length l2.\nProof. \n  intros X l1 l2. \n  induction l1 as [| n l1' IHl1'].\n  - (* l1 = [] *)\n    reflexivity.\n  - (* l1 = n :: l1' *)\n    assert (H: (n :: l1') ++ l2 = n :: (l1' ++ l2)). \n      { reflexivity.  }\n    rewrite H. \n    rewrite fold_length_Sn. \n    rewrite fold_length_Sn. \n    rewrite IHl1'. \n    reflexivity.\nQed. \n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros X l. \n  induction l as [| n l' IHl'].\n  - (* l = [] *)\n    reflexivity.\n  - (* l = n :: l' *)\n    simpl. rewrite <- IHl'. \n    rewrite fold_length_Sn. reflexivity.\nQed. \nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y :=\n  fold (fun a b => f a :: b) l []. \n\nExample test_map0: map mapf [1;2;3] = fold_map mapf [1;2;3].  Proof. reflexivity. Qed.\n  (* [false;true;true] *)\nExample test_map3:\n    map (fun n => [even n; (negb (even n))]) [2;1;2;5]\n  = fold_map (fun n => [even n; (negb (even n))]) [2;1;2;5]. Proof. reflexivity. Qed.\n(*   [[true;false];[false;true];[true;false];[false;true]] *)\n\nTheorem fold_map_correct: forall X Y (f : X -> Y) (l : list X), \n  fold_map f l = map f l. \nProof. \n  intros X Y f l. \n  induction l as [| n l' IHl'].\n  - (* l = [] *)\n    reflexivity.\n  - (* l = n :: l' *)\n    simpl. \n    assert (H : fold_map f (n :: l') = f n :: fold_map f l' ).\n    { reflexivity. } \n    rewrite H. \n    rewrite IHl'. \n    reflexivity.\nQed. \n(* f h (fold f t b) *)\n\n(* In Coq, a function f : A → B → C really has the \ntype A → (B → C). That is, if you give f a value of type A,\n it will give you function f' : B → C. If you then give \n f' a value of type B, it will return a value of type C. \n This allows for partial application, as in plus3. \n Processing a list of arguments with functions that \n return functions is called currying, in honor of the \n logician Haskell Curry.\nConversely, we can reinterpret the type A → B → C as \n(A * B) → C. This is called uncurrying. With an uncurried \nbinary function, both arguments must be given at once as \na pair; there is no partial application.\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 := f (fst p) (snd p).\n\n(* Example test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5]. Proof. reflexivity. Qed. *)\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5]. Proof. reflexivity. Qed.\nExample test_curry_inverse :  prod_curry (prod_uncurry plus) 1 2 = plus 1 2. Proof. reflexivity. Qed.\nCheck @prod_curry.\n(* forall X Y Z : Type, (X * Y -> Z) -> X -> Y -> Z *)\nCheck @prod_uncurry.\n(* forall X Y Z : Type, (X -> Y -> Z) -> X * Y -> Z  *)\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  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 as [x y].\n  reflexivity. \nQed. \n\nModule Church.\n(* \nChurch numerals, named after mathematician Alonzo Church, are \nan alternate way of defining natural number n as a function \nthat takes a function f as a parameter and returns f iterated n times.\n*)\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 three : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f (f x)).\n(*\nDefining zero is somewhat trickier: \nhow can we \"apply a function zero times\"? \nThe answer is actually simple: just return the argument untouched.\n*)\nDefinition zero : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\nDefinition succ (n : cnat) : cnat :=\n    fun (X : Type) (f : X -> X) (x : X) => f (n _ f x).\n\nExample succ_1 : succ zero = one. Proof. reflexivity. Qed.\nExample succ_2 : succ one = two. Proof. reflexivity. Qed.\nExample succ_3 : succ two = three. Proof. reflexivity. Qed.\n\n(* \nTODO\nDefinition pred (n : cnat) : cnat :=\n    match n with \n      | zero => zero \n      | one => one\n    end. \n    \n    fun X f x => f (n _ f x).\n\nExample pred_1 : pred zero = zero. Proof. reflexivity. Qed.\nExample pred_2 : pred one = zero. Proof. reflexivity. Qed.\nExample pred_3 : pred two = one. Proof. reflexivity. Qed.       *)\n  \nDefinition plus (n m : cnat) : cnat :=\n  fun X f x => n _ f (m _ f x).\n\nExample plus_1 : plus zero one = one. Proof. reflexivity. Qed. \nExample plus_2 : plus two three = plus three two. Proof. reflexivity. Qed.\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three). Proof. reflexivity. Qed.\n\nCheck plus one. \nCheck succ. \nCheck cnat.\n\nDefinition mult (n m : cnat) : cnat :=\n    fun _ f x => n _ (m _ f) x.\n\nExample mult_1 : mult one one = one. Proof. reflexivity. Qed.\nExample mult_2 : mult zero (plus three three) = zero. Proof. reflexivity. Qed.\nExample mult_3 : mult two three = plus three three. Proof. reflexivity. Qed.\n\nDefinition exp (n m : cnat) : cnat :=\n  (* fun _ f => m _ ((n _ f)) .  *)\n  fun X => m (X -> X) (n X).\n \n\n\nExample exp_1 : exp two two = plus two two. Proof. reflexivity. Qed.\nExample exp_2 : exp three zero = one. Proof. reflexivity. Qed.\nExample exp_3 : exp three two = plus (mult two (mult two two)) one. Proof. reflexivity. Qed.\nEnd Church. \nEnd Exercises. \n\n\nModule Entries.\n\nInductive id : Type :=\n  | Id (id : nat)\n  | None. \nInductive eid : Type :=\n  | Eid (eid : nat). (* external id *)\n\nInductive entry_op : Type := \n  | Create \n  | Update \n  | Delete \n  | Exist. \n\nInductive entry : Type :=\n  | Asset (id : id) (eid : eid) (op : entry_op) (amt : nat).\n  (* | Liability (id : id) (op : entry_op) (amt : nat)\n  | IncExp (id : id) (op : entry_op) (amt : nat). *)\n\nDefinition eqb_eid (x1 x2 : eid) :=\n  match x1, x2 with\n  | Eid n1, Eid n2 => n1 =? n2\n  end.\n\n\n  (* if exist, remove one. if does not exist, do nothing. *)\nFixpoint remove_one (l : list entry) (n : eid) : (list entry) := \n  match l with \n    | [] => []\n    | Asset id (Eid eid) op amt :: t => if (eqb_eid (Eid eid) n) then t else (Asset id (Eid eid) op amt) :: remove_one t n\n  end. \n(* Reducer *)\nFixpoint parse (l : list entry) (acc : list entry) : (list entry) :=\n  match l with \n    | [] => acc\n    | Asset id (Eid eid) op amt :: t => match id, op with \n                  | None, Create => parse t (acc ++ [(Asset None (Eid eid ) Create amt)])\n                  \n                    (* replace the create with update for eid *)\n                  | None,  Update => let acc' := remove_one acc (Eid eid) in parse t (acc' ++ [(Asset None (Eid eid) Create amt)]) \n\n                    (* remove the create for eid *)\n                  | None,  Delete => let acc' := remove_one acc (Eid eid) in parse t acc' \n\n\n                  | (Id id),  Update => let acc' := remove_one acc (Eid eid) in parse t (acc' ++ [(Asset (Id id) (Eid eid) Update amt)]) \n                  | (Id id),  Delete => let acc' := remove_one acc (Eid eid) in parse t (acc' ++ [(Asset (Id id) (Eid eid) Delete amt)]) \n                  \n                    (* Do nothing *)\n                  | (Id id),  Exist => parse t acc \n\n                  (* Do nothing since these two case does not exist  *)\n                  | None,  Exist => parse t acc  \n                  | (Id id), Create => parse t acc \n                  end \n  end. \n  (* Add will work regardless, unless you delete? *)\n  (*  Delete only if it contains ID *)\n\n(* Add *)\nExample parse_0 : parse [(Asset None (Eid 0) Create 0)] [] = [(Asset None (Eid 0) Create 0)].  Proof. reflexivity. Qed.\nExample parse_1 : parse [(Asset None (Eid 0) Create 0);(Asset None (Eid 0) Delete 0)] [] = [].  Proof. reflexivity. Qed.\nExample parse_2 : parse [(Asset None (Eid 0) Create 0);(Asset None (Eid 0) Update 1)] [] = [(Asset None (Eid 0) Create 1)].  Proof. reflexivity. Qed.\nExample parse_2' : parse [(Asset None (Eid 0) Create 0);(Asset None (Eid 0) Update 1);(Asset None (Eid 0) Update 2)] [] = [(Asset None (Eid 0) Create 2)].  Proof. reflexivity. Qed.\n\n  Example parse_3 : parse [(Asset None (Eid 0) Create 0);(Asset None (Eid 0) Update 1);(Asset None (Eid 0) Delete 1)] [] = [].  Proof. reflexivity. Qed.\n\n(* Delete *)\nExample parse_4 : parse [(Asset (Id 0) (Eid 0) Exist 0); (Asset (Id 0) (Eid 0) Delete 0)] [] = [(Asset (Id 0) (Eid 0) Delete 0)].  Proof. reflexivity. Qed.\nExample parse_5 : parse [(Asset (Id 0) (Eid 0) Exist 0); (Asset (Id 0) (Eid 0) Update 1); (Asset (Id 0) (Eid 0) Delete 1)] [] = [(Asset (Id 0) (Eid 0) Delete 1)].  Proof. reflexivity. Qed.\n\n(* Update *)\nExample parse_6 : parse [(Asset (Id 0) (Eid 0) Exist 0); (Asset (Id 0) (Eid 0) Update 1); (Asset (Id 0) (Eid 0) Update 2)] [] = [(Asset (Id 0) (Eid 0) Update 2)].  Proof. reflexivity. Qed.\n\n(* Combine *)\nExample parse_7 : \n  parse \n  [\n  (Asset (Id 0) (Eid 0) Exist 0); \n  (Asset (Id 1) (Eid 1) Exist 0); \n  (Asset None (Eid 2) Create 0); \n  (Asset None (Eid 3) Create 0);  \n\n  (Asset (Id 0) (Eid 0) Update 1); \n  (Asset (Id 0) (Eid 1) Update 1);\n  (Asset None (Eid 2) Update 1);  \n  (Asset None (Eid 3) Update 1);  \n\n  (Asset (Id 0) (Eid 0) Update 2); \n  (Asset (Id 0) (Eid 1) Update 2);\n  (Asset None (Eid 2) Update 2);  \n  (Asset None (Eid 3) Update 2); \n\n  (Asset (Id 0) (Eid 0) Delete 2); \n  (Asset None (Eid 2) Delete 2)\n  ] [] \n  =\n [Asset (Id 0) (Eid 1) Update 2; Asset None (Eid 3) Create 2;\nAsset (Id 0) (Eid 0) Delete 2].\n  Proof. simpl. reflexivity. Qed.\n\nEnd Entries.\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/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924673, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.6955246783527966}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Import PeanoNat Lt Le.\n\nLocal Open Scope nat_scope.\n\n\n\nLemma minus_n_O n : n = n - 0.\nProof. hammer_hook \"Minus\" \"Minus.minus_n_O\".  \nsymmetry. apply Nat.sub_0_r.\nQed.\n\n\n\nLemma minus_Sn_m n m : m <= n -> S (n - m) = S n - m.\nProof. hammer_hook \"Minus\" \"Minus.minus_Sn_m\".  \nintros. symmetry. now apply Nat.sub_succ_l.\nQed.\n\nTheorem pred_of_minus n : pred n = n - 1.\nProof. hammer_hook \"Minus\" \"Minus.pred_of_minus\".  \nsymmetry. apply Nat.sub_1_r.\nQed.\n\n\n\nNotation minus_diag := Nat.sub_diag (compat \"8.4\").\n\nLemma minus_diag_reverse n : 0 = n - n.\nProof. hammer_hook \"Minus\" \"Minus.minus_diag_reverse\".  \nsymmetry. apply Nat.sub_diag.\nQed.\n\nNotation minus_n_n := minus_diag_reverse.\n\n\n\nLemma minus_plus_simpl_l_reverse n m p : n - m = p + n - (p + m).\nProof. hammer_hook \"Minus\" \"Minus.minus_plus_simpl_l_reverse\".  \nnow rewrite Nat.sub_add_distr, Nat.add_comm, Nat.add_sub.\nQed.\n\n\n\nLemma plus_minus n m p : n = m + p -> p = n - m.\nProof. hammer_hook \"Minus\" \"Minus.plus_minus\".  \nsymmetry. now apply Nat.add_sub_eq_l.\nQed.\n\nLemma minus_plus n m : n + m - n = m.\nProof. hammer_hook \"Minus\" \"Minus.minus_plus\".  \nrewrite Nat.add_comm. apply Nat.add_sub.\nQed.\n\nLemma le_plus_minus_r n m : n <= m -> n + (m - n) = m.\nProof. hammer_hook \"Minus\" \"Minus.le_plus_minus_r\".  \nrewrite Nat.add_comm. apply Nat.sub_add.\nQed.\n\nLemma le_plus_minus n m : n <= m -> m = n + (m - n).\nProof. hammer_hook \"Minus\" \"Minus.le_plus_minus\".  \nintros. symmetry. rewrite Nat.add_comm. now apply Nat.sub_add.\nQed.\n\n\n\nNotation minus_le_compat_r :=\nNat.sub_le_mono_r (compat \"8.4\").\n\nNotation minus_le_compat_l :=\nNat.sub_le_mono_l (compat \"8.4\").\n\nNotation le_minus := Nat.le_sub_l (compat \"8.4\").\nNotation lt_minus := Nat.sub_lt (compat \"8.4\").\n\nLemma lt_O_minus_lt n m : 0 < n - m -> m < n.\nProof. hammer_hook \"Minus\" \"Minus.lt_O_minus_lt\".  \napply Nat.lt_add_lt_sub_r.\nQed.\n\nTheorem not_le_minus_0 n m : ~ m <= n -> n - m = 0.\nProof. hammer_hook \"Minus\" \"Minus.not_le_minus_0\".  \nintros. now apply Nat.sub_0_le, Nat.lt_le_incl, Nat.lt_nge.\nQed.\n\n\n\nHint Resolve minus_n_O: arith.\nHint Resolve minus_Sn_m: arith.\nHint Resolve minus_diag_reverse: arith.\nHint Resolve minus_plus_simpl_l_reverse: arith.\nHint Immediate plus_minus: arith.\nHint Resolve minus_plus: arith.\nHint Resolve le_plus_minus: arith.\nHint Resolve le_plus_minus_r: arith.\nHint Resolve lt_minus: arith.\nHint Immediate lt_O_minus_lt: arith.\n", "meta": {"author": "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/Minus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891261650247, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.6955246781066143}}
{"text": "Require Import Unicode.Utf8.\nRequire Import Game.World.Addition.\n\n(* Level 1 *)\n\nLemma example_1_prop (P Q : Prop) (p : P) (h : P → Q) : Q.\nProof.\n  apply h.\n  exact p.\nQed.\n\n(* Level 2 *)\n\nLemma imp_self (P : Prop) : P → P.\nProof.\n  intro p.\n  exact p.\nQed.\n\n(* Level 3 *)\n\nLemma maze1 (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  pose (q := h(p)).\n  pose (t := j(q)).\n  pose (u := l(t)).\n  exact u.\nQed.\n\n(* Level 4 *)\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.\n  apply h.\n  exact p.\nQed.\n\n(* Level 5 *)\n\nLemma example_5_prop (P Q : Prop) : P → (Q → P).\nProof.\n  intro p.\n  intro q.\n  exact p.\nQed.\n\n(* Level 6 *)\n\nLemma example_6_prop (P Q R : Prop) : (P → (Q → R)) → ((P → Q) → (P → R)).\nProof.\n  intro f.\n  intro g.\n  intro p.\n  apply f.\n  exact p.\n  apply g.\n  exact p.\nQed.\n\n(* Level 7 *)\n\nLemma imp_trans (P Q R : Prop) : (P → Q) → ((Q → R) → (P → R)).\nProof.\n  intro f.\n  intro g.\n  intro p.\n  apply g.\n  apply f.\n  exact p.\nQed.\n\n(* Level 8 *)\n\nLemma contrapositive (P Q : Prop) : (P → Q) → (¬ Q → ¬ P).\nProof.\n  (* ¬Q ↔ P → false *)\n  unfold not.\n  intro f.\n  intro g.\n  intro p.\n  apply g.\n  apply f.\n  exact p.\nQed.\n\n(* Level 9 *)\n(* `tauto`: Automatically solve easy goals *)\n\nLemma example_9_prop (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  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/Proposition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.6955246642289316}}
{"text": "Require Import Arith_base.\nRequire Vectors.Fin.\nImport EqNotations.\nLocal Open Scope nat_scope.\n\nInductive vector A : nat -> Type :=\n  | nil : vector A 0\n  | cons : forall (h:A) (n:nat), vector A n -> vector A (S n).\n\n\n\n", "meta": {"author": "Riib11", "repo": "Coq-Work", "sha": "e163edd331fd15549910f0fe0a361bc93ca951d7", "save_path": "github-repos/coq/Riib11-Coq-Work", "path": "github-repos/coq/Riib11-Coq-Work/Coq-Work-e163edd331fd15549910f0fe0a361bc93ca951d7/Math/old/Vector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6955197345790484}}
{"text": "Require Omega.   \nRequire Export Bool List.\nExport ListNotations.\nRequire Export Arith Arith.EqNat.\nRequire Export Smallest.\n\nInductive is_sorted : list nat -> Prop :=\n  sorted_nil  : is_sorted []\n| sorted_one  : forall n, is_sorted [n]\n| sorted_cons : forall n tl, \n    is_sorted tl -> is_smallest n (n::tl) -> is_sorted (n::tl).\n\nHint Constructors is_sorted.\n\nLemma head_is_smallest : forall (a : nat) (l : list nat),\n  is_sorted (a::l) -> is_smallest a (a::l).\nProof. intros. inversion H; auto. Defined.\n\nLemma tail_is_sorted : forall (a : nat) (l : list nat),\n  is_sorted (a::l) -> is_sorted l.\nProof. intros. inversion H; auto. Defined.\n\nInductive is_inserted : nat -> list nat -> list nat -> Prop :=\n  ins_head : forall n tl, is_inserted n tl (n::tl)\n| ins_tail : forall n m tl tl', is_inserted n tl tl' -> is_inserted n (m::tl) (m::tl').\n\nHint Constructors is_inserted.\n\nLemma smallest_head_perm a n tl : is_smallest a (n :: a :: tl) -> is_smallest a (a :: n :: tl).\nProof.\nintros H; inversion H.\n  rewrite H0 in H. assumption.\n  inversion H4.\n    apply (smallest_head a n [n] (lt_le_weak _ _ H3)). constructor.\n    set (le_lt_dec n m0) as S.\n      inversion S.\n        apply (smallest_head a n (n :: tl) (lt_le_weak _ _ H3)).                \n          apply (smallest_head n m0 tl H9 H8).\n        apply (smallest_head a m0 (n :: tl) H6).\n          apply (smallest_tail n m0 tl H9 H8).\n    omega.\nQed.\n\nLemma smallest_with_n a n tl : is_smallest a (a :: tl) -> a <= n -> is_smallest a (a :: n :: tl).\nProof.\nintros H; inversion H; intros Hle.\n  apply (smallest_head a n [n] Hle). constructor.\n  apply (smallest_head_perm).\n    set (le_lt_eq_dec a n Hle) as S.\n      inversion S.\n        apply (smallest_tail _ _ _ H4 H).\n        rewrite<-H4.\n          apply (smallest_head a a (a :: tl) (le_refl a) H). \n  omega.\nQed.\n\nLemma smallest_without_n a n tl : is_smallest a (a :: n :: tl) -> is_smallest a (a :: tl).\nProof.\nintros H; inversion H.\n  inversion H3. \n    apply smallest_unit. \n    apply (smallest_head a m0 tl).\n      rewrite H4 in H3, H1.\n        apply (le_trans a n m0 H1 H7). assumption.\n    apply (smallest_head a m tl H1). assumption.\n  omega.\nQed.\n\nLemma smallest_than_snd a n tl : is_smallest a (a :: n :: tl) -> a <= n.\nProof.\nintros H; inversion H.\n  inversion H3.\n    rewrite<-H6; assumption.\n    rewrite<-H4; assumption.\n    apply lt_le_weak.\n      apply (le_lt_trans a m n H1 H7).\n  omega.\nQed.  \n\nLemma insert_bigger : forall (a b : nat) (l l' : list nat),\n  is_smallest a (a::l) -> b > a -> is_inserted b l l' -> is_smallest a (a::l').\nProof.\nintros a b l l' H1 H2 H3.\n  induction H3.\n    apply (smallest_with_n a n tl H1); omega.\n    apply (smallest_with_n a m tl').\n      apply IHis_inserted; try assumption.\n        apply (smallest_without_n a m tl H1).       \n      apply (smallest_than_snd a m tl H1).\nQed.\n\nLemma insert_sorted : forall (a : nat) (l : list nat),\n  is_sorted l -> {l' | is_inserted a l l' & is_sorted l'}.\nProof.\n  intros. induction l. exists [a]; auto.\n    assert (A: is_sorted l). apply (tail_is_sorted a0 l). assumption.\n      apply IHl in A. inversion A. \n      destruct (le_gt_dec a a0).\n        exists (a::a0::l); auto. apply (sorted_cons a (a0::l)). \n          auto. apply (smallest_head a a0 (a0::l)). auto. \n          apply head_is_smallest. assumption.\n        exists (a0::x). auto. apply sorted_cons. auto.\n          apply (insert_bigger a0 a l x);\n            try apply (head_is_smallest a0 l); assumption.\nDefined.\n\nInductive is_permutation : list nat -> list nat -> Prop :=\n  perm_nil  : is_permutation [] []\n| perm_cons : forall n l l' m, \n   is_permutation l l' -> is_inserted n l' m -> is_permutation (n::l) m.\n\nHint Constructors is_permutation.\n\nTheorem sort : forall (l : list nat), {l' | is_permutation l l' & is_sorted l'}.\nProof.\n  intros. induction l. exists []; auto.\n    inversion IHl. apply (insert_sorted a x) in H0. inversion H0. \n      exists x0. eauto. assumption.\nDefined.\n\nPrint sort.\n\nExtraction Language Ocaml.\nExtraction \"insort.ml\" sort.\n\nProgram Fixpoint insert_sorted_fix (a : nat) (l : list nat) :\n    is_sorted l -> {l' | is_inserted a l l' /\\ is_sorted l'} := fun H =>\n  match l with\n  | nil     => [a]\n  | x :: xs => if le_gt_dec a x\n               then a :: l\n               else x :: (insert_sorted_fix a xs _)\n  end.\nNext Obligation.\nsplit; auto.\n  apply sorted_cons. assumption.\n    apply (smallest_head a x). assumption.\n      inversion H; auto.\nQed.\nNext Obligation.\ninversion H; auto.\nQed.\nNext Obligation.\nsplit.\n  apply ins_tail; auto.\n    apply sorted_cons; auto.\n      apply (insert_bigger x a xs x0); auto.\n        inversion H; auto.\nDefined.            \n\nRequire Import Permutation.\n\nLemma insert_sorted_fix_perm (a : nat) (l : list nat) (H : is_sorted l) :\n    Permutation (a :: l) (proj1_sig (insert_sorted_fix a l H)).\nProof.\n  generalize dependent H.\n    generalize dependent a.\n      induction l.\n        intros a H. unfold insert_sorted_fix; simpl; auto.\n        intros b H; simpl.\n          destruct (le_gt_dec b a) eqn: Hab; simpl.\n            apply Permutation_refl.\n            apply (@perm_trans _ (b :: a :: l) (a :: b :: l)); auto.\n              apply perm_swap.\nQed.            \n   \n(* \nProgram Fixpoint sort_prog (l : list nat) :\n    {l' | Permutation l l' /\\ is_sorted l'} :=\n  match l with\n  | nil     => nil\n  | x :: xs => insert_sorted_fix x (sort_prog xs) _\n  end.\nNext Obligation.\n  Admitted.\n  split.\n  admit.\nDefined.\n*)\n\n(* Realization w/o dependent types *)\n\nFixpoint insert_fun a l :=\n  match l with\n  | nil     => [a]\n  | x :: xs => if le_gt_dec a x\n               then a :: l\n               else x :: (insert_fun a xs)\n  end.\n\nFixpoint insert_sort l :=\n  match l with\n  | nil     => nil\n  | x :: xs => insert_fun x (insert_sort xs)\n  end.\n\nLemma smallest_in : forall l a, is_smallest a l -> (forall x, In x l -> a <= x).\nProof.\ninduction l.\n  intros a  H1 x H2. inversion H2.\n  intros a0 H1 x H2. destruct H2.\n    rewrite H in H1. clear a H.\n      inversion H1; auto. apply lt_le_weak; auto.\n    inversion H1.\n      rewrite <- H4 in H; inversion H.\n      apply (le_trans a m x H4). \n        apply (IHl _ H5 _ H).\n      apply IHl; auto.        \nQed.\n\nLemma smallest_in_perm : forall a l l',\n  is_smallest a l -> Permutation l l' -> (forall x, In x l' -> a <= x).\nProof.\nintros a l l' H1 H2 x H3.\n  apply (smallest_in l a H1).\n    apply (Permutation_in x (Permutation_sym H2) H3).\nQed.\n\nLemma smallest_dec : forall l, l <> [] -> {x | is_smallest x l}.\nProof.\ninduction l. intros H; exfalso; auto. \n  intros _.\n    destruct l. exists a; auto.\n      assert (n :: l <> []) as H. intros H. inversion H.\n      apply IHl in H; destruct H. \n        destruct (le_lt_dec a x).\n          exists a. apply (smallest_head a x); auto.\n          exists x. apply smallest_tail; auto.\nQed.\n\nLemma smallest_in_list : forall a l, is_smallest a l -> In a l.\nProof.\ninduction l; intros H; inversion H.\n  constructor; auto.\n  constructor; auto.\n  right. apply (IHl H4).\nQed.\n\nLemma in_list_smallest : forall l a,\n  In a l -> (forall x, In x l -> a <= x) -> is_smallest a l.\nProof.\ninduction l.\n  intros a H; inversion H.\n  intros b H1 H2.\n    destruct H1.\n      rewrite <- H in H2. rewrite <- H. clear b H.\n        destruct l; auto.\n        pose (smallest_dec (n::l)) as H3.\n          assert (n::l <> []) as H4. intros H0. inversion H0.\n          apply H3 in H4. destruct H4.\n            assert (a <= x) as H5. apply H2. right.\n              apply (smallest_in_list _ _ i).\n            apply (smallest_head _ x); auto.\n      assert (b <= a) as H1. apply H2. left; auto.\n      destruct (le_lt_eq_dec _ _ H1).\n        apply smallest_tail; auto. \n          apply IHl; auto.\n            intros x H3. apply H2; right; auto.\n        rewrite e. rewrite e in H2, H. clear b H1 e.\n          apply (smallest_head _ a). apply le_refl.\n            apply IHl; auto. intros x H3. apply H2.\n              right; auto.\nQed.\n\nLemma smallest_perm : forall a l l', is_smallest a l -> Permutation l l' -> is_smallest a l'.\nProof.\nintros a l l' H1 H2. \n  apply in_list_smallest.\n    apply (Permutation_in _ H2). apply (smallest_in_list _ _ H1).\n    apply (smallest_in_perm _ _ _ H1 H2).\nQed.\n\nLemma insert_fun_to_sort : forall a l, is_sorted l ->\n  Permutation (insert_fun a l) (a :: l) /\\ is_sorted (insert_fun a l).\nProof.\nintros a l. induction l; intros H.\n  split; auto. unfold insert_fun; auto.\n  assert (is_sorted l) as H1. inversion H; auto.\n    unfold insert_fun.\n      destruct (le_gt_dec a a0) eqn: H2; fold insert_fun.\n        split; auto; constructor; auto.\n          apply (smallest_head _ a0); auto.\n            apply head_is_smallest; auto.\n        split.\n          eapply (@perm_trans _ _ (a0 :: a :: l)); constructor.\n            apply (IHl H1).\n          destruct (IHl H1). constructor; auto.\n            apply (smallest_perm a0 (a0 :: a :: l)).\n              apply smallest_head_perm.\n                apply smallest_tail; auto.\n                  apply head_is_smallest; auto.\n              constructor. apply Permutation_sym. auto.\nQed.\n\nTheorem insert_sort_is_sort :\n  forall l, Permutation (insert_sort l) l /\\  is_sorted (insert_sort l).\nProof.\nintros l; induction l; simpl; auto.\n  destruct IHl as [H1 H2].\n    pose (H := insert_fun_to_sort a (insert_sort l)).\n      destruct H as [H3 H4]; auto.\n       split; auto. eapply (@perm_trans _ _ (a :: insert_sort l)); auto.\nQed.", "meta": {"author": "dboulytchev", "repo": "direct-curry-howard", "sha": "3e73befad8ccd701eabe3469468b4857f4ea6890", "save_path": "github-repos/coq/dboulytchev-direct-curry-howard", "path": "github-repos/coq/dboulytchev-direct-curry-howard/direct-curry-howard-3e73befad8ccd701eabe3469468b4857f4ea6890/Insort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6955197277820823}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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 := plus lf1 lf3.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj111_coqofml_6lRTyp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6955197250922232}}
{"text": "(*\nTheorem plus_0_r_firsttry : forall n:nat,\n  n + 0 = n.\nProof.\nintros.\ninduction n.\nsimpl. reflexivity.\nsimpl. rewrite IHn.\nsimpl. reflexivity.\nQed.\n*)\n\nFixpoint minus (m n : nat) :=\nmatch m, n with\n  | O   , _    => O\n  | S _ , O    => n\n  | S m', S n' => minus m' n'\n  end.\n \nTheorem minus_diag : forall n,\n  minus n n = 0. \nProof.\ninduction n.\nsimpl. reflexivity.\nsimpl. rewrite IHn.\nsimpl. reflexivity.\nQed.\n\nTheorem mult_0_plus' : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\nintros.\ninduction m.\nsimpl. reflexivity.\nsimpl. reflexivity.\nQed.\n\nTheorem mult_0_plus'_1 : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\nintros n m.\nsimpl. reflexivity.\nQed.\n\nTheorem mult_0_plus'_2 : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\nintros.\nassert (H: 0+n=n).\nsimpl. reflexivity.\nrewrite H.\nsimpl. reflexivity.\nQed.\n\n\n\n(*\n\nTheorem plus_swap : forall n m p : nat, \n  n + (m + p) = m + (n + p).\nProof.\nintros.\nassert (H : n+m = m+n).\nsimpl. \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/Test_EATON_Pierce/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6954940027142307}}
{"text": "Global Set Automatic Coercions Import.\nSet Implicit Arguments.\n\nRequire Import Arith.\nRequire Compare_dec.\nRequire EqNat.\nRequire Import Omega.\n\nFixpoint cond_eq (T: nat -> Set) n m {struct n}: forall c, T (c + n) -> T (c + m) -> Prop :=\n  match n, m return forall c, T (c + n) -> T (c + m) -> Prop with\n  | 0, 0 => fun c x y => x = y\n  | S n', S m' => fun c x y => cond_eq T n' m' (S c)\n      (eq_rec_r T x (plus_n_Sm c n'))\n      (eq_rec_r T y (plus_n_Sm c m'))\n  | _, _ => fun _ _ _ => True\n  end.\n\nLemma cond_eq_eq (T: nat -> Set) n c (x y: T (c + n)): cond_eq T n n c x y = (x = y).\nProof with auto.\n  induction n in c, x, y |- *...\n  simpl.\n  intros.\n  rewrite IHn.\n  unfold eq_rec_r.\n  unfold eq_rec.\n  unfold eq_rect.\n  simpl plus.\n  case (sym_eq (plus_n_Sm c n))...\nQed.\n\nLemma cond_eq_neq (T: nat -> Set) n m c (x: T (c + n)) (y: T (c + m)): n <> m -> cond_eq T n m c x y = True.\nProof with auto.\n  induction n in m, c, x, y |- *...\n    destruct m...\n    intros.\n    elimtype False...\n  destruct m...\n  intros.\n  simpl.\n  apply IHn.\n  intro.\n  apply H.\n  subst...\nQed.\n\nInductive natBelow: nat -> Set := mkNatBelow (v p: nat): natBelow (S (v + p)).\n\nDefinition nb_val {n: nat} (nb: natBelow n): nat := match nb with mkNatBelow m _ => m end.\n\nCoercion nb_val: natBelow >-> nat.\n\nLemma natBelow_unique n (x y: natBelow n): nb_val x = nb_val y -> x = y.\nProof with auto.\n  cut (forall n (x: natBelow n) m (y: natBelow m), nb_val x = nb_val y -> cond_eq natBelow n m 0 x y); [|clear x y]; intros.\n    set (H n x n y H0).\n    rewrite cond_eq_eq in c...\n  destruct x.\n  destruct y.\n  simpl in H.\n  subst.\n  destruct (eq_nat_dec p p0).\n    subst.\n    rewrite cond_eq_eq...\n  rewrite cond_eq_neq...\n  intro.\n  omega.\nQed.\n\nLemma natBelow_uneq n (x y: natBelow n): nb_val x <> nb_val y -> x <> y.\nProof. intros. intro. subst. auto. Qed.\n\nLemma natBelow_eq_dec n (x y: natBelow n): { x = y } + { x <> y }.\nProof with auto.\n  intros. destruct (eq_nat_dec x y); [left | right].\n    apply natBelow_unique...\n  apply natBelow_uneq...\nQed.\n\nDefinition nb0 n: natBelow (S n) := mkNatBelow 0 n.\n\nDefinition Snb n (nb: natBelow n): natBelow (S n) :=\n  match nb in (natBelow n0) return (natBelow (S n0)) with\n  | mkNatBelow v p => mkNatBelow (S v) p\n  end.\n", "meta": {"author": "coq-contribs", "repo": "quicksort-complexity", "sha": "bf0205e5fcfec6d6c6017da071960594de79e0da", "save_path": "github-repos/coq/coq-contribs-quicksort-complexity", "path": "github-repos/coq/coq-contribs-quicksort-complexity/quicksort-complexity-bf0205e5fcfec6d6c6017da071960594de79e0da/nat_below.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6954666385926782}}
{"text": "\nRequire Import Coq.Relations.Relations.\n\nRequire Export Misc.\nRequire Export CatSem.CAT.category.\nRequire Import CatSem.CAT.product.\nRequire Import CatSem.CAT.initial_terminal.\nRequire Import CatSem.CAT.coproduct.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Transparent Obligations.\nUnset Automatic Introduction.\n\n\nSection SET.\n\nSection SET_data.\n\nVariable A B:Set.\n\nDefinition SET_hom_equiv:\n   relation (A -> B) := fun f g => forall x, f x = g x.\n\nLemma SET_hom_oid_prf: @Equivalence (A -> B) \n                       (fun f g => forall x, f x = g x).\nProof.\n  constructor;\n  unfold Reflexive; \n  unfold Symmetric; \n  unfold Transitive;\n  intros;\n  etransitivity;\n  eauto.\nQed.\n\nDefinition SET_hom_oid := Build_Setoid SET_hom_oid_prf.\n\nEnd SET_data.\n\nObligation Tactic := cat; try unf_Proper;\n  intros; repeat rew_hyp; auto.\n\nProgram Instance SET_catstruct : Cat_struct (fun a b : Set => a -> b) := {\n   mor_oid a b := SET_hom_oid a b;\n   id a := fun x: a => x;\n   comp a b c f g := fun x => g (f x)\n}.\n\nDefinition SET := Build_Cat SET_catstruct.\n\nEnd SET.\n\nSection SET_INIT_TERM.\n\nInductive Empty : Set := .\n\nObligation Tactic := simpl; intros;\n  repeat match goal with [H:Empty |- _ ] => elim H end; \n      cat.\n\nProgram Instance SET_INIT : Initial SET := {\n   Init := Empty }.\n\nHint Extern 3 (?a = ?b) => elim a.\n\nProgram Instance SET_TERM : Terminal SET := {\n    Term := unit;\n    TermMor A := fun x => tt\n}.\n\nEnd SET_INIT_TERM.\n\nSection SET_COPROD.\n\nInductive SET_COPROD_ob (A B: Set): Set := \n  | INL : A -> SET_COPROD_ob A B\n  | INR : B -> SET_COPROD_ob A B.\n\nObligation Tactic := simpl; intros;\n  repeat unf_Proper;\n  intros;\n  repeat match goal with \n      [x : SET_COPROD_ob _ _ |- _ ] => destruct x end;\n  elim_conjs;\n  auto.\n\nProgram Instance SET_COPROD : Cat_Coprod SET := {\n  coprod a b := SET_COPROD_ob a b;\n  inl a b x := INL (A:=a) b x;\n  inr a b x := INR a x;\n  coprod_mor a b d f g := \n         fun x => match x with INL a => f a | \n                               INR b => g b end\n}.\n\nEnd SET_COPROD.\n\nSection SET_PROD.\n\nObligation Tactic := simpl; intros;\n   try unf_Proper;\n   intros; elim_conjs;   \n   repeat rew_hyp;\n   cat.\n\nHint Extern 1 (_ = _ ) => apply injective_projections; simpl.\n\nProgram Instance SET_PRODUCT: Cat_Prod (SET) := {\n  product a b := prod a b;\n  prl a b x := fst x;\n  prr a b x := snd x;\n  prod_mor a c d f g := fun x => (f x, g x)\n}.\n\nEnd SET_PROD.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "JasonGross", "repo": "benediktahrens-coq-fossil", "sha": "834bc904a07549ac3f659e68d94a3f1c73c5b72a", "save_path": "github-repos/coq/JasonGross-benediktahrens-coq-fossil", "path": "github-repos/coq/JasonGross-benediktahrens-coq-fossil/benediktahrens-coq-fossil-834bc904a07549ac3f659e68d94a3f1c73c5b72a/CAT/cat_SET.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6954666307628554}}
{"text": "(**\nThe Little Prover の memb?/remb をCoqで解いてみる\n *)\n\nRequire Import Bool.\nRequire Import List.\nRequire Import Program.\nSet Implicit Arguments.\n\n(** * はじめに *)\n\n(**\nThe Little Prover (TLP) の第6章では、memb?/remb という定理が扱われています。\nこれは、リニアなリストの要素から、文字 '?' を削除する関数 remb と、\nこれは、リニアなリストの要素に、文字 '?' が含まれるかを判定する関数 memb? が\n定義されているとき、\n任意のリスト xs に対して、(memb? (remb xs)) が必ず False になるというものです。\n\nオリジナルはLisp系の言語なので、リストの要素は任意のデータでよいのですが、\nCoqの場合は、false と true からなる bool型のリストとし、もじ '?' の代わりに true とします。\n  *)\n\n(**\nソースコードは、\n#<a href=\"https://github.com/suharahiromichi/coq/blob/master/prog/coq_membp_remb_2.v\">\nここ\n</a>\nにあります。\n *)\n\n(**\nまず、membp (memb? に対応する) の自然数のリストに 0 が含まれていることを判定する関数を定義ましす。\nリストの先頭から見ていき 0 が含まれていたらそこで True を返します。\n*)\n\nFixpoint membp (xs : list nat) : Prop :=\n  match xs with\n  | nil => False\n  | 0 :: xs' => True\n  | _ :: xs' => membp xs'\n  end.\n\nCompute membp (1 :: 0 :: 2 :: nil).         (** ==> [True] *)\n\nCompute membp (1 :: 2 :: 3 :: nil).         (** ==> [False] *)\n\nCompute membp nil.                          (** ==> [False] *)\n\n(**\nついで、remb のリストから 0 を削除する関数を定義します。\nリストの先頭から見ていき 0 なら、それを含まない結果を返し\nfalse なら、それを含む結果を返します。\n*)\n\nFixpoint remb (xs : list nat) : list nat :=\n  match xs with\n  | nil => nil\n  | 0 :: xs' => remb xs'\n  | x :: xs' => x :: remb xs'\n  end.\n\nCompute remb (0 :: 1 :: 0 :: nil).         (** ==> [[1]] *)\n\n(** * memb?/remb の証明 *)\n\n(**\nmemb?/remb に対応する membp_remb は、文字通りの定義です。\n結果は偽であるため、「~」がついています。\n *)\n\nDefinition membp_remb (xs : list nat) := ~ membp (remb xs).\n\n(** 以下に、membp_remb を証明します。線形リスト xs に対する帰納法と、\n要素 x に対する場合分けだけで証明されています。\nなお、帰納法の仮定IHxsは、ふたつめとみっつめのnowでトリビアルに使われます。\n *)\n  \nLemma le_membp_remb : forall (xs : list nat), membp_remb xs.\nProof.\n  unfold membp_remb.\n  induction xs as [|x xs IHxs].\n  - now simpl.\n  (** x が 0 か 0 でないかで場合分けする。 *)\n  - case x as [| x']; simpl.\n    (** ここで帰納法の仮定を使う。 *)\n    + now trivial.\n    + now trivial.\n\n  Restart.\n  unfold membp_remb.\n  intros xs.\n  induction xs as [|x xs IHxs]; try auto.\n  now case x.\nQed.\n\n(**\nmemb?/remb は定理としては自明ですが、 0 が含まれないことをチェックする関数membpによって、\n 0 を削除する関数rembが正しく動作していることを証明する、と考えることができます。\n\nこれは、関数の定義とその証明を同時におこなう証明駆動開発の一例となります。\nCoqにはそれをサポートする「Program」コマンドがあります。\nこれを使って remb を再定義してみましょう。\n\nremb' の値は、単なる list nat ではなく、\n[{ys : list nat | ~ membp ys}]\nすなわち、\n[~ membp ys] を満たす [ys] の集合の要素、\nとなります。\n\nこれだと、最初に想定した型と違うので困ると思うかもしれませんが、\n「Program」コマンドの中では、そのサブタイプ・コアーションの機能によって、\nlist boot 型と同一視されます。\n\nremb' の結果が普通にconsされていることに気づいてください。\n\n「Program」コマンドの中では、そのサブタイプ・コアーションは、\n再帰呼び出しのみならず、他の（定義済みの）任意な関数に適用されます。\n *)\n\nProgram Fixpoint remb' (xs : list nat) : {ys : list nat | ~ membp ys} :=\n  match xs with\n  | nil => nil\n  | 0 :: xs' => remb' xs'\n  | x :: xs' => x :: remb' xs'\n  end.\nObligation 2.\nProof.\n  case x as [| x']; simpl.\n  - generalize (H xs'); intro H'.\n    exfalso.\n    now apply H'.\n  - now trivial.\nDefined.\n\nCompute ` (remb' (0 :: 1 :: 0 :: nil)).     (** ==> [[1]] *)\n\nExtraction remb'.\n(**\n生成されたコードには、rembp は含まれていない。\n\n[[\nval remb' : nat list -> nat list,\n\nlet rec remb' = function\n| Nil -> Nil\n| Cons (x, xs') ->\n  (match x with\n   | O -> remb' xs'\n   | S n -> let x0 = S n in Cons (x0, (remb' xs')))\n]]\n*)\n\n(** * 証明駆動開発 *)\n\n(**\nこれからは、TLP の範囲を越える事項ですが、\nremb' の定義を「リストから 0 を除去する関数」の証明付き定義と考えると問題があります。\n\nmembp は 0 の有無しかチェックしていませんから、\nremb の本体が「つねにnil」を返すような定義であっても問題なくパスします。これではだめです。\n\nremb の厳密な定義は、(1)に加えて(2)も満たさないといけません。\n\n(1) 結果のリストに 0 が含まれないこと。\n\n(2) 結果のリストがもとのリストのサブリストであること。\n *)\n\n(** サブリストを定義します。  *)\n\nSection Sublist.\n  Variable A : Type.\n  Variable f : A -> bool.\n\n  (** Sublist l' l <==> l' ⊆ l *)\n  \n  Inductive Sublist : list A -> list A -> Prop :=\n  | SL_nil l : Sublist nil l\n  | SL_skip x l' l : Sublist l' l -> Sublist l' (x :: l)\n  | SL_cons x l' l : Sublist l' l -> Sublist (x :: l') (x :: l).\n  \nEnd Sublist.\n\nHint Constructors Sublist.\n\n(**\n定理を直接証明します。\n(1) と (2) を連言(/\\)でつなぎます。\nまた let ... in は普通の意味で、ys は構文的な意味しかもちません。\n*)\n\nGoal forall (xs : list nat),\n    let ys := remb xs in\n    ~ membp (remb xs) /\\ Sublist ys xs.\nProof.\n  intros xs.\n  split.\n  - apply le_membp_remb.\n  - induction xs as [| x' xs' IHxs]; simpl.\n    + now auto.                             (** SL_nil を使う。 *)\n    + case x' as [|x''].\n      * now auto.                           (** SL_Skip を使う。 *)\n      * now auto.                           (** SL_cons を使う。 *)\nQed.\n\n(**\n「Program」コマンドでの定義に条件を追加します。\n*)\n\nProgram Fixpoint remb'' (xs : list nat) :\n  {ys : list nat | ~ membp (remb xs) /\\ Sublist ys xs} :=\n  match xs with\n  | nil => nil\n  | 0 :: xs' => remb'' xs'\n  | x :: xs' => x :: remb'' xs'\n  end.\nObligation 3.\nProof.\n  split.\n  - case x as [| x']; simpl.\n    + generalize (H xs'); intro H'.\n      exfalso.\n      now apply H'.\n    + now trivial.\n  - now auto.                               (** SL_cons を使う。 *)\nDefined.\n\nCompute ` (remb'' (0 :: 1 :: 0 :: nil)).    (** ==> [[1]] *)\n\nExtraction remb''.\n\n(**\n生成されたコードには、Sublist は含まれていません。\n\n[[\nval remb'' : nat list -> nat list\n\nlet rec remb'' = function\n| Nil -> Nil\n| Cons (b, xs') ->\n  (match b with\n   |  0  -> remb'' xs'\n   | False -> Cons (False, (remb'' xs')))\n]]\n *)\n\n(** * 帰納法の公理 *)\n\n(**\nTLPにもどって、帰納法による証明について考えてみましょう。\nTLPでは、（例によって、天から降ってきた）「inductive claim」を証明しています。\nこれの導きかたは第6章の最後に記載されていますが、Coqの場合は、\nリストの型定義にもとづく「公理」を使います。\n *)\n\nCheck list_ind : forall (A : Type) (P : list A -> Prop),\n    P [] ->\n    (forall (a : A) (l : list A), P l -> P (a :: l)) ->\n    forall l : list A, P l.\n\n(**\nこれを membp_remb に適用すると次を得ます。\n繰り返しますが、これは証明するべきものではなく、「公理」です。\n *)\n\nCheck list_ind membp_remb :\n  membp_remb [] ->\n  (forall (a : nat) (l : list nat), membp_remb l -> membp_remb (a :: l)) ->\n  forall l : list nat, membp_remb l.\n\n(**\nこの公理を使うなら、\n\n[forall l : list nat, membp_remb l]\n\nを証明するには、\n\n[membp_remb []]\n\nと\n\n[forall (a : nat) (l : list nat), membp_remb l -> membp_remb (a :: l)]\n\nとを証明すればよいことになります。後者は、TLPでは、l は nil でないことを条件に、\n[(cdr l)] をとっていて、つまり、\n\n[forall (l : list nat  ), membp_remb (tl l) -> membp_remb l]\n\nとなっています。おなじですね。\n *)\n\n(**\n実際の証明は、以下の通りです。\n *)\n\nGoal forall xs, membp_remb xs.\nProof.\n  intros xs.\n  apply (list_ind membp_remb).\n  - now simpl.\n  - intros x' xs' IHxs.\n    case x'; simpl.\n    + now trivial.\n    + now trivial.\nQed.\n\n(**\n最初の証明では、\n\n[induction xs] というタクティクを使いましたが、\n\nこの公理を\n\n[apply (list_ind membp_remb)]\n\nとして、適用することと同じです。\n *)\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/prog/coq_membp_remb_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6954666253944959}}
{"text": "Require Import PeanoNat.\nLocal Open Scope nat_scope.\n\nRequire Import List.\nImport ListNotations.\n\nInductive btree : Type :=\n  | empty : btree \n  | node : btree->nat->btree->btree.\n\nDefinition tree :=node (node empty 7 (node empty 2 empty)) 1 (node(node empty 10 empty)8 (node empty 3 empty)).\n\nPrint List.\n(*[] == nli*)\nCheck [].\n(*cons pentru a adauga in lista*)\nCheck (cons 4 []).\nCheck (cons 5 nil).\nCheck [4;5].\n\nDefinition myList := [4;5].\n\nCompute 6 :: myList.\n (*Concatenarea a doua liste*)\nCompute myList++myList.\n\nFixpoint returnNodeValue(t :btree):nat :=\n  match t with\n  |empty=>0\n  |node l v r =>v  \nend.\n\nFixpoint preorderCrossing(b:btree):list nat :=\n  match b with\n  | empty => []\n  | node l n r => \n    n :: (preorderCrossing l) ++ (preorderCrossing r)\nend.\n\nCompute (preorderCrossing tree).\n(*Parcurgerea inordine*)\n\n(*Exercitiu 1*)\nFixpoint inorderCrossing(t:btree):list nat :=\n  match t with\n  |empty => []\n  | node l n r => \n    (inorderCrossing l)++[n]++(inorderCrossing r)\nend.\n\nCompute (inorderCrossing tree).\n\n(*Exercitiul 2*)\nFixpoint sibling (t:btree) (a:nat):list nat :=\n  match t with \n  | node l v r => if (returnNodeValue l) =? a\n                  then [(returnNodeValue r)]\n                  else if (returnNodeValue r)=? a\n                        then [(returnNodeValue l)]\n                          else (sibling l a)++(sibling r a)\n  | empty => []\n  \nend.\n\n\nCompute (sibling tree 8).\nFixpoint parent (t:btree) (a:nat) : list nat :=\n  match t with\n  | empty => []\n  | node l v r => if orb ((returnNodeValue l) =? a) ((returnNodeValue r)=?a)\n                    then [v]\n                     else (parent l a)++(parent r a)\nend.\n\nFixpoint returnListValue (l:list nat) : nat :=\n  match l with\n  | [] => 0\n  | cons v list => v\nend.\n\nFixpoint isRoot(t:btree):bool :=\n match t with\n  | empty => false\n  | node l v r => true\nend.\n\nCompute parent tree 7.\nCompute returnListValue myList.\n\nFixpoint degree (t original:btree) (a:nat) : list nat :=\n  match t with\n  | empty => []\n  | node empty v empty => if negb( a =? v)\n                          then []\n                          else if length(parent original v)=? 0\n                                then [0]\n                                else [1]\n  | node l v empty => if negb (a =? v)\n                      then []++(degree l original a)\n                      else if length(parent original v)=? 0\n                            then [1]\n                            else [2]\n\n  | node empty v r => if negb ( a=? v)\n                      then []++(degree r original a)\n                      else if length(parent original v)=? 0\n                            then [1]\n                            else [2]\n  \n  | node l v r => if negb ( a =? v)\n                    then (degree l original a)++(degree r original a)\n                    else if length(parent original v) =? 0\n                          then [2]\n                          else [3]\nend.\nCompute length [2].\nCompute degree tree tree 7.\n\nFixpoint findTheRighestNode (t:btree) : nat :=\n  match t with\n  | empty => 0\n  | node l v empty => v\n  | node l v r => findTheRighestNode r\nend.\n\nFixpoint deleteTheRighestNode (t original:btree):btree :=\n  match t with\n  | empty => empty\n  | node empty v empty => empty\n  | node l v r => deleteTheRighestNode r original\n  \nend.\n\nCompute deleteTheRighestNode tree tree.\nPrint tree.\n", "meta": {"author": "IonitaCatalin", "repo": "programming-language-principle", "sha": "e6a5b4f5284f28127707dc1b8838bad29f215c69", "save_path": "github-repos/coq/IonitaCatalin-programming-language-principle", "path": "github-repos/coq/IonitaCatalin-programming-language-principle/programming-language-principle-e6a5b4f5284f28127707dc1b8838bad29f215c69/Lab3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6953398624118606}}
{"text": "Require\n  MathClasses.implementations.stdlib_binary_integers MathClasses.theory.integers MathClasses.orders.semirings.\nRequire Import\n  Coq.Setoids.Setoid Bignums.SpecViaZ.NSig Bignums.SpecViaZ.NSigNAxioms Coq.NArith.NArith Coq.ZArith.ZArith Coq.Program.Program Coq.Classes.Morphisms\n  MathClasses.interfaces.abstract_algebra MathClasses.interfaces.naturals MathClasses.interfaces.integers\n  MathClasses.interfaces.orders MathClasses.interfaces.additional_operations.\n\nModule NType_Integers (Import anyN: NType).\n\nModule axioms := NTypeIsNAxioms anyN.\n\n#[global]\nInstance NType_equiv : Equiv t := eq.\n#[global]\nInstance NType_plus : Plus t := add.\n#[global]\nInstance NType_0 : Zero t := zero.\n#[global]\nInstance NType_1 : One t := one.\n#[global]\nInstance NType_mult : Mult t := mul.\n\n#[global]\nInstance: Setoid t | 10 := {}.\n\n#[global]\nProgram Instance: ∀ x y: t, Decision (x = y) := λ x y, match compare x y with\n  | Eq => left _\n  | _ => right _\n  end.\nNext Obligation.\n  apply Zcompare_Eq_eq. now rewrite <-spec_compare.\nQed.\nNext Obligation.\n  rewrite spec_compare in *. intros E.\n  apply Zcompare_Eq_iff_eq in E. auto.\nQed.\n\nLtac unfold_equiv := unfold equiv, NType_equiv, eq in *.\n\nLemma  NType_semiring_theory: semi_ring_theory zero one add mul eq.\nProof. repeat split; repeat intro; axioms.zify; auto with zarith. Qed.\n\n#[global]\nInstance: SemiRing t | 10 := rings.from_stdlib_semiring_theory NType_semiring_theory.\n\n#[global]\nInstance inject_NType_N: Cast t N := to_N.\n\n#[global]\nInstance: Proper ((=) ==> (=)) to_N.\nProof. intros x y E. unfold equiv, NType_equiv, eq in E. unfold to_N. now rewrite E. Qed.\n\n#[global]\nInstance: SemiRing_Morphism to_N.\nProof.\n  repeat (split; try apply _); unfold to_N; intros.\n     now rewrite spec_add, Z2N.inj_add by apply spec_pos.\n    unfold mon_unit, zero_is_mon_unit, NType_0. now rewrite spec_0.\n   now rewrite spec_mul, Z2N.inj_mul by apply spec_pos.\n  unfold mon_unit, one_is_mon_unit, NType_1. now rewrite spec_1.\nQed.\n\n#[global]\nInstance inject_N_NType: Cast N t := of_N.\n#[global]\nInstance: Inverse to_N := of_N.\n\n#[global]\nInstance: Surjective to_N.\nProof.\n  split; try apply _. intros x y E.\n  rewrite <-E. unfold to_N, inverse, compose. rewrite spec_of_N.\n  apply N2Z.id.\nQed.\n\n#[global]\nInstance: Injective to_N.\nProof.\n  split; try apply _. intros x y E.\n  unfold equiv, NType_equiv, eq. unfold to_N in E.\n  rewrite <-(Z2N.id (to_Z x)), <-(Z2N.id (to_Z y)) by now apply spec_pos.\n  now rewrite E.\nQed.\n\n#[global]\nInstance: Bijective to_N := {}.\n\n#[global]\nInstance: Inverse of_N := to_N.\n\n#[global]\nInstance: Bijective of_N.\nProof. apply jections.flip_bijection. Qed.\n\n#[global]\nInstance: SemiRing_Morphism of_N.\nProof. change (SemiRing_Morphism (to_N⁻¹)). split; apply _. Qed.\n\n#[global]\nInstance: NaturalsToSemiRing t := naturals.retract_is_nat_to_sr of_N.\n#[global]\nInstance: Naturals t := naturals.retract_is_nat of_N.\n\n#[global]\nInstance inject_NType_Z: Cast t Z := to_Z.\n\n#[global]\nInstance: Proper ((=) ==> (=)) to_Z.\nProof. now intros x y E. Qed.\n\n#[global]\nInstance: SemiRing_Morphism to_Z.\nProof.\n  repeat (split; try apply _).\n     exact spec_add.\n    exact spec_0.\n   exact spec_mul.\n  exact spec_1.\nQed.\n\n(* Order *)\n#[global]\nInstance  NType_le: Le t := le.\n#[global]\nInstance  NType_lt: Lt t := lt.\n\n#[global]\nInstance: Proper ((=) ==> (=) ==> iff) NType_le.\nProof.\n  intros ? ? E1 ? ? E2. unfold NType_le, le. unfold equiv, NType_equiv, eq in *.\n  now rewrite E1, E2.\nQed.\n\n#[global]\nInstance: SemiRingOrder NType_le.\nProof.\n  apply (semirings.projected_srorder to_Z).\n   reflexivity.\n  intros x y E. exists (sub y x).\n  unfold_equiv. rewrite spec_add, spec_sub.\n  rewrite Z.max_r by now apply Z.le_0_sub.\n  ring.\nQed.\n\n#[global]\nInstance: OrderEmbedding to_Z.\nProof. now repeat (split; try apply _). Qed.\n\n#[global]\nInstance: TotalRelation NType_le.\nProof. now apply (maps.projected_total_order to_Z). Qed.\n\n#[global]\nInstance: FullPseudoSemiRingOrder NType_le NType_lt.\nProof.\n  rapply semirings.dec_full_pseudo_srorder.\n  intros x y. split.\n   intro. split.\n    apply axioms.lt_eq_cases. now left.\n   intros E. destruct (irreflexivity (<) (to_Z x)). now rewrite E at 2.\n  intros [E1 E2].\n  now destruct (proj1 (axioms.lt_eq_cases _ _) E1).\nQed.\n\n(* Efficient comparison *)\n#[global]\nProgram Instance: ∀ x y: t, Decision (x ≤ y) := λ x y, match (compare x y) with\n  | Gt => right _\n  | _ => left _\n  end.\nNext Obligation.\n  rewrite spec_compare in *.\n  destruct (Z.compare_spec (to_Z x) (to_Z y)); try discriminate.\n  now apply orders.lt_not_le_flip.\nQed.\nNext Obligation.\n  rewrite spec_compare in *.\n  destruct (Z.compare_spec (to_Z x) (to_Z y)); try discriminate; try intuition.\n   now apply Zeq_le.\n  now apply orders.lt_le.\nQed.\n\nLemma NType_succ_1_plus x : succ x = 1 + x.\nProof.\n  unfold_equiv. rewrite spec_succ, rings.preserves_plus, rings.preserves_1.\n  now rewrite commutativity.\nQed.\n\nLemma NType_two_2 : two = 2.\nProof.\n  unfold_equiv. rewrite spec_2.\n  now rewrite rings.preserves_plus, rings.preserves_1.\nQed.\n\n(* Efficient [nat_pow] *)\n#[global]\nProgram Instance NType_pow: Pow t t := pow.\n\n#[global]\nInstance: NatPowSpec t t NType_pow.\nProof.\n  split.\n    intros x1 y1 E1 x2 y2 E2.\n    now apply axioms.pow_wd.\n   intros x1. apply axioms.pow_0_r.\n  intros x n.\n  unfold_equiv. unfold \"^\", NType_pow.\n  rewrite <-axioms.pow_succ_r by (red; rewrite spec_0; apply spec_pos).\n  now rewrite NType_succ_1_plus.\nQed.\n\n(* Efficient [shiftl] *)\n#[global]\nProgram Instance NType_shiftl: ShiftL t t := shiftl.\n\n#[global]\nInstance: ShiftLSpec t t NType_shiftl.\nProof.\n  apply shiftl_spec_from_nat_pow.\n  intros x y.\n  unfold additional_operations.pow, NType_pow, additional_operations.shiftl, NType_shiftl.\n  unfold_equiv. simpl.\n  rewrite rings.preserves_mult, spec_pow.\n  rewrite spec_shiftl, Z.shiftl_mul_pow2 by apply spec_pos.\n  now rewrite <-NType_two_2, spec_2.\nQed.\n\n(* Efficient [shiftr] *)\n#[global]\nProgram Instance: ShiftR t t := shiftr.\n\nEnd NType_Integers.\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/NType_naturals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593496, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6953398394867902}}
{"text": "Require Export TopologicalSpaces.\nRequire Export InverseImage.\nRequire Export Continuity.\n\nSection StrongTopology.\n\nVariable A:Type.\nVariable X:forall a:A, TopologicalSpace.\nVariable Y:Type.\nVariable f:forall a:A, point_set (X a) -> Y.\n\nDefinition strong_open (S:Ensemble Y) : Prop :=\n  forall a:A, open (inverse_image (f a) S).\n\nDefinition StrongTopology : TopologicalSpace.\nrefine (Build_TopologicalSpace Y strong_open _ _ _).\nintros.\nred; intro.\nassert (inverse_image (f a) (FamilyUnion F) =\n  IndexedUnion (fun U:{ U:Ensemble Y | In F U } =>\n                 inverse_image (f a) (proj1_sig U))).\napply Extensionality_Ensembles; red; split; red; intros.\ndestruct H0.\ninversion H0.\nexists (exist _ S H1).\nconstructor.\nexact H2.\n\ndestruct H0.\ndestruct H0.\ndestruct a0 as [U].\nconstructor.\nexists U; trivial.\n\nrewrite H0.\napply open_indexed_union.\nintros.\ndestruct a0 as [U].\nsimpl.\napply H; trivial.\n\nintros.\nred; intro.\nrewrite inverse_image_intersection.\napply open_intersection2; (apply H || apply H0).\n\nred; intro.\nrewrite inverse_image_full.\napply open_full.\nDefined.\n\nLemma strong_topology_makes_continuous_funcs:\n  forall a:A, continuous (f a) (Y:=StrongTopology).\nProof.\nintros.\nred.\nintros.\nauto.\nQed.\n\nLemma strong_topology_strongest: forall (T':Ensemble Y->Prop)\n  (H1:_) (H2:_) (H3:_),\n  (forall a:A, continuous (f a)\n          (Y:=Build_TopologicalSpace Y T' H1 H2 H3)) ->\n  forall V:Ensemble Y, T' V -> strong_open V.\nProof.\nintros.\nunfold continuous in H.\nsimpl in H.\nred; intros; apply H; trivial.\nQed.\n\nEnd StrongTopology.\n\nArguments StrongTopology [A] [X] [Y].\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/StrongTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.78793120560257, "lm_q1q2_score": 0.6952924575452927}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq path.\nFrom mathcomp Require Import div choice fintype tuple finfun bigop prime order.\nFrom mathcomp Require Import ssralg poly ssrnum ssrint rat matrix.\nFrom mathcomp Require Import polydiv perm zmodp mxalgebra vector.\n\n(******************************************************************************)\n(* This file provides various results on divisibility of integers.            *)\n(* It defines, for m, n, d : int,                                             *)\n(*   (m %% d)%Z == the remainder of the Euclidean division of m by d; this is *)\n(*                 the least non-negative element of the coset m + dZ when    *)\n(*                 d != 0, and m if d = 0.                                    *)\n(*   (m %/ d)%Z == the quotient of the Euclidean division of m by d, such     *)\n(*                 that m = (m %/ d)%Z * d + (m %% d)%Z. Since for d != 0 the *)\n(*                 remainder is non-negative, (m %/ d)%Z is non-zero for      *)\n(*                 negative m.                                                *)\n(*   (d %| m)%Z <=> m is divisible by d; dvdz d is the (collective) predicate *)\n(*                 for integers divisible by d, and (d %| m)%Z is actually    *)\n(*                 (transposing) notation for m \\in dvdz d.                   *)\n(* (m = n %[mod d])%Z, (m == n %[mod d])%Z, (m != n %[mod d])%Z               *)\n(*                 m and n are (resp. compare, don't compare) equal mod d.    *)\n(*     gcdz m n == the (non-negative) greatest common divisor of m and n,     *)\n(*                 with gcdz 0 0 = 0.                                         *)\n(*     lcmz m n == the (non-negative) least common multiple of m and n.       *)\n(* coprimez m n <=> m and n are coprime.                                      *)\n(*    egcdz m n == the Bezout coefficients of the gcd of m and n: a pair      *)\n(*                 (u, v) of coprime integers such that u*m + v*n = gcdz m n. *)\n(*                 Alternatively, a Bezoutz lemma states such u and v exist.  *)\n(* zchinese m1 m2 n1 n2 == for coprime m1 and m2, a solution to the Chinese   *)\n(*                 remainder problem for n1 and n2, i.e., and integer n such  *)\n(*                 that n = n1 %[mod m1] and n = n2 %[mod m2].                *)\n(*  zcontents p == the contents of p : {poly int}, that is, the gcd of the    *)\n(*                 coefficients of p, with the same sign as the lead          *)\n(*                 coefficient of p.                                          *)\n(* zprimitive p == the primitive part of p : {poly int}, i.e., p divided by   *)\n(*                 its contents.                                              *)\n(* inIntSpan X v <-> v is an integral linear combination of elements of       *)\n(*                 X : seq V, where V is a zmodType. We prove that this is a  *)\n(*                 decidable property for Q-vector spaces.                    *)\n(* int_Smith_normal_form :: a theorem asserting the existence of the Smith    *)\n(*                 normal form for integer matrices.                          *)\n(* Note that many of the concepts and results in this file could and perhaps  *)\n(* should be generalized to the more general setting of integral, unique      *)\n(* factorization, principal ideal, or Euclidean domains.                      *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport Order.TTheory GRing.Theory Num.Theory.\nLocal Open Scope ring_scope.\n\nDefinition divz (m d : int) : int :=\n  let: (K, n) := match m with Posz n => (Posz, n) | Negz n => (Negz, n) end in\n  sgz d * K (n %/ `|d|)%N.\n\nDefinition modz (m d : int) : int := m - divz m d * d.\n\nDefinition dvdz d m := (`|d| %| `|m|)%N.\n\nDefinition gcdz m n := (gcdn `|m| `|n|)%:Z.\n\nDefinition lcmz m n := (lcmn `|m| `|n|)%:Z.\n\nDefinition egcdz m n : int * int :=\n  if m == 0 then (0, (-1) ^+ (n < 0)%R) else\n  let: (u, v) := egcdn `|m| `|n| in (sgz m * u, - (-1) ^+ (n < 0)%R * v%:Z).\n\nDefinition coprimez m n := (gcdz m n == 1).\n\nInfix \"%/\" := divz : int_scope.\nInfix \"%%\" := modz : int_scope.\nNotation \"d %| m\" := (m \\in dvdz d) : int_scope.\nNotation \"m = n %[mod d ]\" := (modz m d = modz n d) : int_scope.\nNotation \"m == n %[mod d ]\" := (modz m d == modz n d) : int_scope.\nNotation \"m <> n %[mod d ]\" := (modz m d <> modz n d) : int_scope.\nNotation \"m != n %[mod d ]\" := (modz m d != modz n d) : int_scope.\n\nLemma divz_nat (n d : nat) : (n %/ d)%Z = (n %/ d)%N.\nProof. by case: d => // d; rewrite /divz /= mul1r. Qed.\n\nLemma divzN m d : (m %/ - d)%Z = - (m %/ d)%Z.\nProof. by case: m => n; rewrite /divz /= sgzN abszN mulNr. Qed.\n\nLemma divz_abs (m d : int) : (m %/ `|d|)%Z = (-1) ^+ (d < 0)%R * (m %/ d)%Z.\nProof.\nby rewrite {3}[d]intEsign !mulr_sign; case: ifP => -> //; rewrite divzN opprK.\nQed.\n\nLemma div0z d : (0 %/ d)%Z = 0.\nProof.\nby rewrite -(canLR (signrMK _) (divz_abs _ _)) (divz_nat 0) div0n mulr0.\nQed.\n\nLemma divNz_nat m d : (d > 0)%N -> (Negz m %/ d)%Z = - (m %/ d).+1%:Z.\nProof. by case: d => // d _; apply: mul1r. Qed.\n\nLemma divz_eq m d : m = (m %/ d)%Z * d + (m %% d)%Z.\nProof. by rewrite addrC subrK. Qed.\n\nLemma modzN m d : (m %% - d)%Z = (m %% d)%Z.\nProof. by rewrite /modz divzN mulrNN. Qed.\n\nLemma modz_abs m d : (m %% `|d|%N)%Z = (m %% d)%Z.\nProof. by rewrite {2}[d]intEsign mulr_sign; case: ifP; rewrite ?modzN. Qed.\n\nLemma modz_nat (m d : nat) : (m %% d)%Z = (m %% d)%N.\nProof.\nby apply: (canLR (addrK _)); rewrite addrC divz_nat {1}(divn_eq m d).\nQed.\n\nLemma modNz_nat m d : (d > 0)%N -> (Negz m %% d)%Z = d%:Z - 1 - (m %% d)%:Z.\nProof.\nrewrite /modz => /divNz_nat->; apply: (canLR (addrK _)).\nrewrite -!addrA -!opprD -!PoszD -opprB mulnSr !addnA PoszD addrK.\nby rewrite addnAC -addnA mulnC -divn_eq.\nQed.\n\nLemma modz_ge0 m d : d != 0 -> 0 <= (m %% d)%Z.\nProof.\nrewrite -absz_gt0 -modz_abs => d_gt0.\ncase: m => n; rewrite ?modNz_nat ?modz_nat // -addrA -opprD subr_ge0.\nby rewrite lez_nat ltn_mod.\nQed.\n\nLemma divz0 m : (m %/ 0)%Z = 0. Proof. by case: m. Qed.\nLemma mod0z d : (0 %% d)%Z = 0. Proof. by rewrite /modz div0z mul0r subrr. Qed.\nLemma modz0 m : (m %% 0)%Z = m. Proof. by rewrite /modz mulr0 subr0. Qed.\n\nLemma divz_small m d : 0 <= m < `|d|%:Z -> (m %/ d)%Z = 0.\nProof.\nrewrite -(canLR (signrMK _) (divz_abs _ _)); case: m => // n /divn_small.\nby rewrite divz_nat => ->; rewrite mulr0.\nQed.\n\nLemma divzMDl q m d : d != 0 -> ((q * d + m) %/ d)%Z = q + (m %/ d)%Z.\nProof.\nrewrite neq_lt -oppr_gt0 => nz_d.\nwlog{nz_d} d_gt0: q d / d > 0; last case: d => // d in d_gt0 *.\n  move=> IH; case/orP: nz_d => /IH// /(_  (- q)).\n  by rewrite mulrNN !divzN -opprD => /oppr_inj.\nwlog q_gt0: q m / q >= 0; last case: q q_gt0 => // q _.\n  move=> IH; case: q => n; first exact: IH; rewrite NegzE mulNr.\n  by apply: canRL (addKr _) _; rewrite -IH ?addNKr.\ncase: m => n; first by rewrite !divz_nat divnMDl.\nhave [le_qd_n | lt_qd_n] := leqP (q * d) n.\n  rewrite divNz_nat // NegzE -(subnKC le_qd_n) divnMDl //.\n  by rewrite -!addnS !PoszD !opprD !addNKr divNz_nat.\nrewrite divNz_nat // NegzE -PoszM subzn // divz_nat.\napply: canRL (addrK _) _; congr _%:Z; rewrite addnC -divnMDl // mulSnr.\nrewrite -{3}(subnKC (ltn_pmod n d_gt0)) addnA addnS -divn_eq addnAC.\nby rewrite subnKC // divnMDl // divn_small ?addn0 // subnSK ?ltn_mod ?leq_subr.\nQed.\n\nLemma mulzK m d : d != 0 -> (m * d %/ d)%Z = m.\nProof. by move=> d_nz; rewrite -[m * d]addr0 divzMDl // div0z addr0. Qed.\n\nLemma mulKz m d : d != 0 -> (d * m %/ d)%Z = m.\nProof. by move=> d_nz; rewrite mulrC mulzK. Qed.\n\nLemma expzB p m n : p != 0 -> (m >= n)%N -> p ^+ (m - n) = (p ^+ m %/ p ^+ n)%Z.\nProof. by move=> p_nz /subnK{2}<-; rewrite exprD mulzK // expf_neq0. Qed.\n\nLemma modz1 m : (m %% 1)%Z = 0.\nProof. by case: m => n; rewrite (modNz_nat, modz_nat) ?modn1. Qed.\n\nLemma divz1 m : (m %/ 1)%Z = m. Proof. by rewrite -{1}[m]mulr1 mulzK. Qed.\n\nLemma divzz d : (d %/ d)%Z = (d != 0).\nProof. by have [-> // | d_nz] := eqVneq; rewrite -{1}[d]mul1r mulzK. Qed.\n\nLemma ltz_pmod m d : d > 0 -> (m %% d)%Z < d.\nProof.\ncase: m d => n [] // d d_gt0; first by rewrite modz_nat ltz_nat ltn_pmod.\nby rewrite modNz_nat // -lez_addr1 addrAC subrK ger_addl oppr_le0.\nQed.\n\nLemma ltz_mod m d : d != 0 -> (m %% d)%Z < `|d|.\nProof. by rewrite -absz_gt0 -modz_abs => d_gt0; apply: ltz_pmod. Qed.\n\nLemma divzMpl p m d : p > 0 -> (p * m %/ (p * d) = m %/ d)%Z.\nProof.\ncase: p => // p p_gt0; wlog d_gt0: d / d > 0; last case: d => // d in d_gt0 *.\n  by move=> IH; case/intP: d => [|d|d]; rewrite ?mulr0 ?divz0 ?mulrN ?divzN ?IH.\nrewrite {1}(divz_eq m d) mulrDr mulrCA divzMDl ?mulf_neq0 ?gt_eqF // addrC.\nrewrite divz_small ?add0r // PoszM pmulr_rge0 ?modz_ge0 ?gt_eqF //=.\nby rewrite ltr_pmul2l ?ltz_pmod.\nQed.\nArguments divzMpl [p m d].\n\nLemma divzMpr p m d : p > 0 -> (m * p %/ (d * p) = m %/ d)%Z.\nProof. by move=> p_gt0; rewrite -!(mulrC p) divzMpl. Qed.\nArguments divzMpr [p m d].\n\nLemma lez_floor m d : d != 0 -> (m %/ d)%Z * d <= m.\nProof. by rewrite -subr_ge0; apply: modz_ge0. Qed.\n\n(* leq_mod does not extend to negative m. *)\nLemma lez_div m d : (`|(m %/ d)%Z| <= `|m|)%N.\nProof.\nwlog d_gt0: d / d > 0; last case: d d_gt0 => // d d_gt0.\n  by move=> IH; case/intP: d => [|n|n]; rewrite ?divz0 ?divzN ?abszN // IH.\ncase: m => n; first by rewrite divz_nat leq_div.\nby rewrite divNz_nat // NegzE !abszN ltnS leq_div.\nQed.\n \nLemma ltz_ceil m d : d > 0 -> m < ((m %/ d)%Z + 1) * d.\nProof.\nby case: d => // d d_gt0; rewrite mulrDl mul1r -ltr_subl_addl ltz_mod ?gt_eqF.\nQed.\n\nLemma ltz_divLR m n d : d > 0 -> ((m %/ d)%Z < n) = (m < n * d).\nProof.\nmove=> d_gt0; apply/idP/idP.\n  by rewrite -[_ < n]lez_addr1 -(ler_pmul2r d_gt0);\n     apply: lt_le_trans (ltz_ceil _ _).\nrewrite -(ltr_pmul2r d_gt0 _ n) //; apply: le_lt_trans (lez_floor _ _).\nby rewrite gt_eqF.\nQed.\n\nLemma lez_divRL m n d : d > 0 -> (m <= (n %/ d)%Z) = (m * d <= n).\nProof. by move=> d_gt0; rewrite !leNgt ltz_divLR. Qed.\n\nLemma lez_pdiv2r d : 0 <= d -> {homo divz^~ d : m n / m <= n}.\nProof.\nby case: d => [[|d]|]// _ [] m [] n //; rewrite /divz !mul1r; apply: leq_div2r.\nQed.\n\nLemma divz_ge0 m d : d > 0 -> ((m %/ d)%Z >= 0) = (m >= 0).\nProof. by case: d m => // d [] n d_gt0; rewrite (divz_nat, divNz_nat). Qed.\n\nLemma divzMA_ge0 m n p : n >= 0 -> (m %/ (n * p) = (m %/ n)%Z %/ p)%Z.\nProof.\ncase: n => // [[|n]] _; first by rewrite mul0r !divz0 div0z.\nwlog p_gt0: p / p > 0; last case: p => // p in p_gt0 *.\n  by case/intP: p => [|p|p] IH; rewrite ?mulr0 ?divz0 ?mulrN ?divzN // IH.\nrewrite {2}(divz_eq m (n.+1%:Z * p)) mulrA mulrAC !divzMDl // ?gt_eqF //.\nrewrite [rhs in _ + rhs]divz_small ?addr0 // ltz_divLR // divz_ge0 //.\nby rewrite mulrC ltz_pmod ?modz_ge0 ?gt_eqF ?pmulr_lgt0.\nQed.\n\nLemma modz_small m d : 0 <= m < d -> (m %% d)%Z = m.\nProof. by case: m d => //= m [] // d; rewrite modz_nat => /modn_small->. Qed.\n\nLemma modz_mod m d : ((m %% d)%Z = m %[mod d])%Z.\nProof.\nrewrite -!(modz_abs _ d); case: {d}`|d|%N => [|d]; first by rewrite !modz0.\nby rewrite modz_small ?modz_ge0 ?ltz_mod.\nQed.\n\nLemma modzMDl p m d : (p * d + m = m %[mod d])%Z.\nProof.\nhave [-> | d_nz] := eqVneq d 0; first by rewrite mulr0 add0r.\nby rewrite /modz divzMDl // mulrDl opprD addrACA subrr add0r.\nQed.\n\nLemma mulz_modr {p m d} : 0 < p -> p * (m %% d)%Z = ((p * m) %% (p * d))%Z.\nProof.\ncase: p => // p p_gt0; rewrite mulrBr; apply: canLR (addrK _) _.\nby rewrite mulrCA -(divzMpl p_gt0) subrK.\nQed.\n\nLemma mulz_modl {p m d} : 0 < p -> (m %% d)%Z * p = ((m * p) %% (d * p))%Z.\nProof. by rewrite -!(mulrC p); apply: mulz_modr. Qed.\n\nLemma modzDl m d : (d + m = m %[mod d])%Z.\nProof. by rewrite -{1}[d]mul1r modzMDl. Qed.\n\nLemma modzDr m d : (m + d = m %[mod d])%Z.\nProof. by rewrite addrC modzDl. Qed.\n\nLemma modzz d : (d %% d)%Z = 0.\nProof. by rewrite -{1}[d]addr0 modzDl mod0z. Qed.\n\nLemma modzMl p d : (p * d %% d)%Z = 0.\nProof. by rewrite -[p * d]addr0 modzMDl mod0z. Qed.\n\nLemma modzMr p d : (d * p %% d)%Z = 0.\nProof. by rewrite mulrC modzMl. Qed.\n\nLemma modzDml m n d : ((m %% d)%Z + n = m + n %[mod d])%Z.\nProof. by rewrite {2}(divz_eq m d) -[_ * d + _ + n]addrA modzMDl. Qed.\n\nLemma modzDmr m n d : (m + (n %% d)%Z = m + n %[mod d])%Z.\nProof. by rewrite !(addrC m) modzDml. Qed.\n\nLemma modzDm m n d : ((m %% d)%Z + (n %% d)%Z = m + n %[mod d])%Z.\nProof. by rewrite modzDml modzDmr. Qed.\n\nLemma eqz_modDl p m n d : (p + m == p + n %[mod d])%Z = (m == n %[mod d])%Z.\nProof.\nhave [-> | d_nz] := eqVneq d 0; first by rewrite !modz0 (inj_eq (addrI p)).\napply/eqP/eqP=> eq_mn; last by rewrite -modzDmr eq_mn modzDmr.\nby rewrite -(addKr p m) -modzDmr eq_mn modzDmr addKr.\nQed.\n\nLemma eqz_modDr p m n d : (m + p == n + p %[mod d])%Z = (m == n %[mod d])%Z.\nProof. by rewrite -!(addrC p) eqz_modDl. Qed.\n\nLemma modzMml m n d : ((m %% d)%Z * n = m * n %[mod d])%Z.\nProof. by rewrite {2}(divz_eq m d) mulrDl mulrAC modzMDl. Qed.\n\nLemma modzMmr m n d : (m * (n %% d)%Z = m * n %[mod d])%Z.\nProof. by rewrite !(mulrC m) modzMml. Qed.\n\nLemma modzMm m n d : ((m %% d)%Z * (n %% d)%Z = m * n %[mod d])%Z.\nProof. by rewrite modzMml modzMmr. Qed.\n\nLemma modzXm k m d : ((m %% d)%Z ^+ k = m ^+ k %[mod d])%Z.\nProof. by elim: k => // k IHk; rewrite !exprS -modzMmr IHk modzMm. Qed.\n\nLemma modzNm m d : (- (m %% d)%Z = - m %[mod d])%Z.\nProof. by rewrite -mulN1r modzMmr mulN1r. Qed.\n\nLemma modz_absm m d : ((-1) ^+ (m < 0)%R * (m %% d)%Z = `|m|%:Z %[mod d])%Z.\nProof. by rewrite modzMmr -abszEsign. Qed.\n\n(** Divisibility **)\n\nFact dvdz_key d : pred_key (dvdz d). Proof. by []. Qed.\nCanonical dvdz_keyed d := KeyedPred (dvdz_key d).\n\nLemma dvdzE d m : (d %| m)%Z = (`|d| %| `|m|)%N. Proof. by []. Qed.\nLemma dvdz0 d : (d %| 0)%Z. Proof. exact: dvdn0. Qed.\nLemma dvd0z n : (0 %| n)%Z = (n == 0). Proof. by rewrite -absz_eq0 -dvd0n. Qed.\nLemma dvdz1 d : (d %| 1)%Z = (`|d|%N == 1%N). Proof. exact: dvdn1. Qed.\nLemma dvd1z m : (1 %| m)%Z. Proof. exact: dvd1n. Qed.\nLemma dvdzz m : (m %| m)%Z. Proof. exact: dvdnn. Qed.\n\nLemma dvdz_mull d m n : (d %| n)%Z -> (d %| m * n)%Z.\nProof. by rewrite !dvdzE abszM; apply: dvdn_mull. Qed.\n\nLemma dvdz_mulr d m n : (d %| m)%Z -> (d %| m * n)%Z.\nProof. by move=> d_m; rewrite mulrC dvdz_mull. Qed.\n#[global] Hint Resolve dvdz0 dvd1z dvdzz dvdz_mull dvdz_mulr : core.\n\nLemma dvdz_mul d1 d2 m1 m2 : (d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2)%Z.\nProof. by rewrite !dvdzE !abszM; apply: dvdn_mul. Qed.\n\nLemma dvdz_trans n d m : (d %| n -> n %| m -> d %| m)%Z.\nProof. by rewrite !dvdzE; apply: dvdn_trans. Qed.\n\nLemma dvdzP d m : reflect (exists q, m = q * d) (d %| m)%Z.\nProof.\napply: (iffP dvdnP) => [] [q Dm]; last by exists `|q|%N; rewrite Dm abszM.\nexists ((-1) ^+ (m < 0)%R * q%:Z * (-1) ^+ (d < 0)%R).\nby rewrite -!mulrA -abszEsign -PoszM -Dm -intEsign.\nQed.\nArguments dvdzP {d m}.\n\nLemma dvdz_mod0P d m : reflect (m %% d = 0)%Z (d %| m)%Z.\nProof.\napply: (iffP dvdzP) => [[q ->] | md0]; first by rewrite modzMl.\nby rewrite (divz_eq m d) md0 addr0; exists (m %/ d)%Z.\nQed.\nArguments dvdz_mod0P {d m}.\n\nLemma dvdz_eq d m : (d %| m)%Z = ((m %/ d)%Z * d == m).\nProof. by rewrite (sameP dvdz_mod0P eqP) subr_eq0 eq_sym. Qed.\n\nLemma divzK d m : (d %| m)%Z -> (m %/ d)%Z * d = m.\nProof. by rewrite dvdz_eq => /eqP. Qed.\n\nLemma lez_divLR d m n : 0 < d -> (d %| m)%Z -> ((m %/ d)%Z <= n) = (m <= n * d).\nProof. by move=> /ler_pmul2r <- /divzK->. Qed.\n\nLemma ltz_divRL d m n : 0 < d -> (d %| m)%Z -> (n < m %/ d)%Z = (n * d < m).\nProof. by move=> /ltr_pmul2r/(_ n)<- /divzK->. Qed.\n\nLemma eqz_div d m n : d != 0 -> (d %| m)%Z -> (n == m %/ d)%Z = (n * d == m).\nProof. by move=> /mulIf/inj_eq <- /divzK->. Qed.\n\nLemma eqz_mul d m n : d != 0 -> (d %| m)%Z -> (m == n * d) = (m %/ d == n)%Z.\nProof. by move=> d_gt0 dv_d_m; rewrite eq_sym -eqz_div // eq_sym. Qed.\n\nLemma divz_mulAC d m n : (d %| m)%Z -> (m %/ d)%Z * n = (m * n %/ d)%Z.\nProof.\nhave [-> | d_nz] := eqVneq d 0; first by rewrite !divz0 mul0r.\nby move/divzK=> {2} <-; rewrite mulrAC mulzK.\nQed.\n\nLemma mulz_divA d m n : (d %| n)%Z -> m * (n %/ d)%Z = (m * n %/ d)%Z.\nProof. by move=> dv_d_m; rewrite !(mulrC m) divz_mulAC. Qed.\n\nLemma mulz_divCA d m n :\n  (d %| m)%Z -> (d %| n)%Z -> m * (n %/ d)%Z = n * (m %/ d)%Z.\nProof. by move=> dv_d_m dv_d_n; rewrite mulrC divz_mulAC ?mulz_divA. Qed.\n\nLemma divzA m n p : (p %| n -> n %| m * p -> m %/ (n %/ p)%Z = m * p %/ n)%Z.\nProof.\nmove/divzK=> p_dv_n; have [->|] := eqVneq n 0; first by rewrite div0z !divz0.\nrewrite -{1 2}p_dv_n mulf_eq0 => /norP[pn_nz p_nz] /divzK; rewrite mulrA p_dv_n.\nby move/mulIf=> {1} <- //; rewrite mulzK.\nQed.\n\nLemma divzMA m n p : (n * p %| m -> m %/ (n * p) = (m %/ n)%Z %/ p)%Z.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 !divz0.\nhave [-> | nz_n] := eqVneq n 0; first by rewrite mul0r !divz0 div0z.\nby move/divzK=> {2} <-; rewrite mulrA mulrAC !mulzK.\nQed.\n\nLemma divzAC m n p : (n * p %| m -> (m %/ n)%Z %/ p =  (m %/ p)%Z %/ n)%Z.\nProof. by move=> np_dv_mn; rewrite -!divzMA // mulrC. Qed.\n\nLemma divzMl p m d : p != 0 -> (d %| m -> p * m %/ (p * d) = m %/ d)%Z.\nProof.\nhave [-> | nz_d nz_p] := eqVneq d 0; first by rewrite mulr0 !divz0.\nby move/divzK=> {1}<-; rewrite mulrCA mulzK ?mulf_neq0.\nQed.\n\nLemma divzMr p m d : p != 0 -> (d %| m -> m * p %/ (d * p) = m %/ d)%Z.\nProof. by rewrite -!(mulrC p); apply: divzMl. Qed.\n\nLemma dvdz_mul2l p d m : p != 0 -> (p * d %| p * m)%Z = (d %| m)%Z.\nProof. by rewrite !dvdzE -absz_gt0 !abszM; apply: dvdn_pmul2l. Qed.\nArguments dvdz_mul2l [p d m].\n\nLemma dvdz_mul2r p d m : p != 0 -> (d * p %| m * p)%Z = (d %| m)%Z.\nProof. by rewrite !dvdzE -absz_gt0 !abszM; apply: dvdn_pmul2r. Qed.\nArguments dvdz_mul2r [p d m].\n\nLemma dvdz_exp2l p m n : (m <= n)%N -> (p ^+ m %| p ^+ n)%Z.\nProof. by rewrite dvdzE !abszX; apply: dvdn_exp2l. Qed.\n\nLemma dvdz_Pexp2l p m n : `|p| > 1 -> (p ^+ m %| p ^+ n)%Z = (m <= n)%N.\nProof. by rewrite dvdzE !abszX ltz_nat; apply: dvdn_Pexp2l. Qed.\n\nLemma dvdz_exp2r m n k : (m %| n -> m ^+ k %| n ^+ k)%Z.\nProof. by rewrite !dvdzE !abszX; apply: dvdn_exp2r. Qed.\n\nFact dvdz_zmod_closed d : zmod_closed (dvdz d).\nProof.\nsplit=> [|_ _ /dvdzP[p ->] /dvdzP[q ->]]; first exact: dvdz0.\nby rewrite -mulrBl dvdz_mull.\nQed.\nCanonical dvdz_addPred d := AddrPred (dvdz_zmod_closed d).\nCanonical dvdz_oppPred d := OpprPred (dvdz_zmod_closed d).\nCanonical dvdz_zmodPred d := ZmodPred (dvdz_zmod_closed d).\n  \nLemma dvdz_exp k d m : (0 < k)%N -> (d %| m -> d %| m ^+ k)%Z.\nProof. by case: k => // k _ d_dv_m; rewrite exprS dvdz_mulr. Qed.\n\nLemma eqz_mod_dvd d m n : (m == n %[mod d])%Z = (d %| m - n)%Z.\nProof.\napply/eqP/dvdz_mod0P=> eq_mn.\n  by rewrite -modzDml eq_mn modzDml subrr mod0z.\nby rewrite -(subrK n m) -modzDml eq_mn add0r.\nQed.\n\nLemma divzDl m n d :\n  (d %| m)%Z -> ((m + n) %/ d)%Z = (m %/ d)%Z + (n %/ d)%Z.\nProof.\nhave [-> | d_nz] := eqVneq d 0; first by rewrite !divz0.\nby move/divzK=> {1}<-; rewrite divzMDl.\nQed.\n\nLemma divzDr m n d :\n  (d %| n)%Z -> ((m + n) %/ d)%Z = (m %/ d)%Z + (n %/ d)%Z.\nProof. by move=> dv_n; rewrite addrC divzDl // addrC. Qed.\n\nLemma Qint_dvdz (m d : int) : (d %| m)%Z -> ((m%:~R / d%:~R : rat) \\is a Qint).\nProof.\ncase/dvdzP=> z ->; rewrite rmorphM /=; have [->|dn0] := eqVneq d 0.\n  by rewrite mulr0 mul0r.\nby rewrite mulfK ?intr_eq0 // rpred_int.\nQed.\n\nLemma Qnat_dvd (m d : nat) : (d %| m)%N -> ((m%:R / d%:R : rat) \\is a Qnat).\nProof.\nmove=> h; rewrite Qnat_def divr_ge0 ?ler0n // -[m%:R]/(m%:~R) -[d%:R]/(d%:~R).\nby rewrite Qint_dvdz.\nQed.\n\n(* Greatest common divisor *)\n\nLemma gcdzz m : gcdz m m = `|m|%:Z. Proof. by rewrite /gcdz gcdnn. Qed.\nLemma gcdzC : commutative gcdz. Proof. by move=> m n; rewrite /gcdz gcdnC. Qed.\nLemma gcd0z m : gcdz 0 m = `|m|%:Z. Proof. by rewrite /gcdz gcd0n. Qed.\nLemma gcdz0 m : gcdz m 0 = `|m|%:Z. Proof. by rewrite /gcdz gcdn0. Qed.\nLemma gcd1z : left_zero 1 gcdz. Proof. by move=> m; rewrite /gcdz gcd1n. Qed.\nLemma gcdz1 : right_zero 1 gcdz. Proof. by move=> m; rewrite /gcdz gcdn1. Qed.\nLemma dvdz_gcdr m n : (gcdz m n %| n)%Z. Proof. exact: dvdn_gcdr. Qed.\nLemma dvdz_gcdl m n : (gcdz m n %| m)%Z. Proof. exact: dvdn_gcdl. Qed.\nLemma gcdz_eq0 m n : (gcdz m n == 0) = (m == 0) && (n == 0).\nProof. by rewrite -absz_eq0 eqn0Ngt gcdn_gt0 !negb_or -!eqn0Ngt !absz_eq0. Qed.\nLemma gcdNz m n : gcdz (- m) n = gcdz m n. Proof. by rewrite /gcdz abszN. Qed.\nLemma gcdzN m n : gcdz m (- n) = gcdz m n. Proof. by rewrite /gcdz abszN. Qed.\n\nLemma gcdz_modr m n : gcdz m (n %% m)%Z = gcdz m n.\nProof.\nrewrite -modz_abs /gcdz; move/absz: m => m.\nhave [-> | m_gt0] := posnP m; first by rewrite modz0.\ncase: n => n; first by rewrite modz_nat gcdn_modr.\nrewrite modNz_nat // NegzE abszN {2}(divn_eq n m) -addnS gcdnMDl.\nrewrite -addrA -opprD -intS /=; set m1 := _.+1.\nhave le_m1m: (m1 <= m)%N by apply: ltn_pmod.\nby rewrite subzn // !(gcdnC m) -{2 3}(subnK le_m1m) gcdnDl gcdnDr gcdnC.\nQed.\n\nLemma gcdz_modl m n : gcdz (m %% n)%Z n = gcdz m n.\nProof. by rewrite -!(gcdzC n) gcdz_modr. Qed.\n\nLemma gcdzMDl q m n : gcdz m (q * m + n) = gcdz m n.\nProof. by rewrite -gcdz_modr modzMDl gcdz_modr. Qed.\n \nLemma gcdzDl m n : gcdz m (m + n) = gcdz m n.\nProof. by rewrite -{2}(mul1r m) gcdzMDl. Qed.\n\nLemma gcdzDr m n : gcdz m (n + m) = gcdz m n.\nProof. by rewrite addrC gcdzDl. Qed.\n\nLemma gcdzMl n m : gcdz n (m * n) = `|n|%:Z.\nProof. by rewrite -[m * n]addr0 gcdzMDl gcdz0. Qed.\n\nLemma gcdzMr n m : gcdz n (n * m) = `|n|%:Z.\nProof. by rewrite mulrC gcdzMl. Qed.\n\nLemma gcdz_idPl {m n} : reflect (gcdz m n = `|m|%:Z) (m %| n)%Z.\nProof. by apply: (iffP gcdn_idPl) => [<- | []]. Qed.\n\nLemma gcdz_idPr {m n} : reflect (gcdz m n = `|n|%:Z) (n %| m)%Z.\nProof. by rewrite gcdzC; apply: gcdz_idPl. Qed.\n\nLemma expz_min e m n : e >= 0 -> e ^+ minn m n = gcdz (e ^+ m) (e ^+ n).\nProof.\nby case: e => // e _; rewrite /gcdz !abszX -expn_min -natz -natrX !natz.\nQed.\n\nLemma dvdz_gcd p m n : (p %| gcdz m n)%Z = (p %| m)%Z && (p %| n)%Z.\nProof. exact: dvdn_gcd. Qed.\n\nLemma gcdzAC : right_commutative gcdz.\nProof. by move=> m n p; rewrite /gcdz gcdnAC. Qed.\n\nLemma gcdzA : associative gcdz.\nProof. by move=> m n p; rewrite /gcdz gcdnA. Qed.\n\nLemma gcdzCA : left_commutative gcdz.\nProof. by move=> m n p; rewrite /gcdz gcdnCA. Qed.\n\nLemma gcdzACA : interchange gcdz gcdz.\nProof. by move=> m n p q; rewrite /gcdz gcdnACA. Qed.\n\nLemma mulz_gcdr m n p : `|m|%:Z * gcdz n p = gcdz (m * n) (m * p).\nProof. by rewrite -PoszM muln_gcdr -!abszM. Qed.\n\nLemma mulz_gcdl m n p : gcdz m n * `|p|%:Z = gcdz (m * p) (n * p).\nProof. by rewrite -PoszM muln_gcdl -!abszM. Qed.\n\nLemma mulz_divCA_gcd n m : n * (m %/ gcdz n m)%Z  = m * (n %/ gcdz n m)%Z.\nProof. by rewrite mulz_divCA ?dvdz_gcdl ?dvdz_gcdr. Qed.\n\n(* Least common multiple *)\n\nLemma dvdz_lcmr m n : (n %| lcmz m n)%Z.\nProof. exact: dvdn_lcmr. Qed.\n\nLemma dvdz_lcml m n : (m %| lcmz m n)%Z.\nProof. exact: dvdn_lcml. Qed.\n\nLemma dvdz_lcm d1 d2 m : ((lcmn d1 d2 %| m) = (d1 %| m) && (d2 %| m))%Z.\nProof. exact: dvdn_lcm. Qed.\n\nLemma lcmzC : commutative lcmz.\nProof. by move=> m n; rewrite /lcmz lcmnC. Qed.\n\nLemma lcm0z : left_zero 0 lcmz.\nProof. by move=> x; rewrite /lcmz absz0 lcm0n. Qed.\n\nLemma lcmz0 : right_zero 0 lcmz.\nProof. by move=> x; rewrite /lcmz absz0 lcmn0. Qed.\n\nLemma lcmz_ge0 m n : 0 <= lcmz m n.\nProof. by []. Qed.\n\nLemma lcmz_neq0 m n : (lcmz m n != 0) = (m != 0) && (n != 0).\nProof.\nhave [->|m_neq0] := eqVneq m 0; first by rewrite lcm0z.\nhave [->|n_neq0] := eqVneq n 0; first by rewrite lcmz0.\nby rewrite gt_eqF// [0 < _]lcmn_gt0 !absz_gt0 m_neq0 n_neq0.\nQed.\n\n(* Coprime factors *)\n\nLemma coprimezE m n : coprimez m n = coprime `|m| `|n|. Proof. by []. Qed.\n\nLemma coprimez_sym : symmetric coprimez.\nProof. by move=> m n; apply: coprime_sym. Qed.\n\nLemma coprimeNz m n : coprimez (- m) n = coprimez m n.\nProof. by rewrite coprimezE abszN. Qed.\n\nLemma coprimezN m n : coprimez m (- n) = coprimez m n.\nProof. by rewrite coprimezE abszN. Qed.\n\nVariant egcdz_spec m n : int * int -> Type :=\n  EgcdzSpec u v of u * m + v * n = gcdz m n & coprimez u v\n     : egcdz_spec m n (u, v).\n\nLemma egcdzP m n : egcdz_spec m n (egcdz m n).\nProof.\nrewrite /egcdz; have [-> | m_nz] := eqVneq.\n  by split; [rewrite -abszEsign gcd0z | rewrite coprimezE absz_sign].\nhave m_gt0 : (`|m| > 0)%N by rewrite absz_gt0.\ncase: egcdnP (coprime_egcdn `|n| m_gt0) => //= u v Duv _ co_uv; split.\n  rewrite !mulNr -!mulrA mulrCA -abszEsg mulrCA -abszEsign.\n  by rewrite -!PoszM Duv addnC PoszD addrK.\nby rewrite coprimezE abszM absz_sg m_nz mul1n mulNr abszN abszMsign.\nQed.\n\nLemma Bezoutz m n : {u : int & {v : int | u * m + v * n = gcdz m n}}.\nProof. by exists (egcdz m n).1, (egcdz m n).2; case: egcdzP. Qed.\n\nLemma coprimezP m n :\n  reflect (exists uv, uv.1 * m + uv.2 * n = 1) (coprimez m n).\nProof.\napply: (iffP eqP) => [<-| [[u v] /= Duv]].\n  by exists (egcdz m n); case: egcdzP.\ncongr _%:Z; apply: gcdn_def; rewrite ?dvd1n // => d dv_d_n dv_d_m.\nby rewrite -(dvdzE d 1) -Duv [m]intEsg [n]intEsg rpredD ?dvdz_mull.\nQed.\n\nLemma Gauss_dvdz m n p :\n  coprimez m n -> (m * n %| p)%Z = (m %| p)%Z && (n %| p)%Z.\nProof. by move/Gauss_dvd <-; rewrite -abszM. Qed.\n\nLemma Gauss_dvdzr m n p : coprimez m n -> (m %| n * p)%Z = (m %| p)%Z.\nProof. by rewrite dvdzE abszM => /Gauss_dvdr->. Qed.\n\nLemma Gauss_dvdzl m n p : coprimez m p -> (m %| n * p)%Z = (m %| n)%Z.\nProof. by rewrite mulrC; apply: Gauss_dvdzr. Qed.\n\nLemma Gauss_gcdzr p m n : coprimez p m -> gcdz p (m * n) = gcdz p n.\nProof. by rewrite /gcdz abszM => /Gauss_gcdr->. Qed.\n\nLemma Gauss_gcdzl p m n : coprimez p n -> gcdz p (m * n) = gcdz p m.\nProof. by move=> co_pn; rewrite mulrC Gauss_gcdzr. Qed.\n\nLemma coprimezMr p m n : coprimez p (m * n) = coprimez p m && coprimez p n.\nProof. by rewrite -coprimeMr -abszM. Qed.\n\nLemma coprimezMl p m n : coprimez (m * n) p = coprimez m p && coprimez n p.\nProof. by rewrite -coprimeMl -abszM. Qed.\n\nLemma coprimez_pexpl k m n : (0 < k)%N -> coprimez (m ^+ k) n = coprimez m n.\nProof. by rewrite /coprimez /gcdz abszX; apply: coprime_pexpl. Qed.\n\nLemma coprimez_pexpr k m n : (0 < k)%N -> coprimez m (n ^+ k) = coprimez m n.\nProof. by move=> k_gt0; rewrite !(coprimez_sym m) coprimez_pexpl. Qed.\n\nLemma coprimezXl k m n : coprimez m n -> coprimez (m ^+ k) n.\nProof. by rewrite /coprimez /gcdz abszX; apply: coprimeXl. Qed.\n\nLemma coprimezXr k m n : coprimez m n -> coprimez m (n ^+ k).\nProof. by rewrite !(coprimez_sym m); apply: coprimezXl. Qed.\n\nLemma coprimez_dvdl m n p : (m %| n)%N -> coprimez n p -> coprimez m p.\nProof. exact: coprime_dvdl. Qed.\n\nLemma coprimez_dvdr m n p : (m %| n)%N -> coprimez p n -> coprimez p m.\nProof. exact: coprime_dvdr. Qed.\n\nLemma dvdz_pexp2r m n k : (k > 0)%N -> (m ^+ k %| n ^+ k)%Z = (m %| n)%Z.\nProof. by rewrite dvdzE !abszX; apply: dvdn_pexp2r. Qed.\n\nSection Chinese.\n\n(***********************************************************************)\n(*   The chinese remainder theorem                                     *)\n(***********************************************************************)\n\nVariables m1 m2 : int.\nHypothesis co_m12 : coprimez m1 m2.\n\nLemma zchinese_remainder x y :\n  (x == y %[mod m1 * m2])%Z = (x == y %[mod m1])%Z && (x == y %[mod m2])%Z.\nProof. by rewrite !eqz_mod_dvd Gauss_dvdz. Qed.\n\n(***********************************************************************)\n(*   A function that solves the chinese remainder problem              *)\n(***********************************************************************)\n\nDefinition zchinese r1 r2 :=\n  r1 * m2 * (egcdz m1 m2).2 + r2 * m1 * (egcdz m1 m2).1.\n\nLemma zchinese_modl r1 r2 : (zchinese r1 r2 = r1 %[mod m1])%Z.\nProof.\nrewrite /zchinese; have [u v /= Duv _] := egcdzP m1 m2.\nrewrite -{2}[r1]mulr1 -((gcdz _ _ =P 1) co_m12) -Duv.\nby rewrite mulrDr mulrAC addrC (mulrAC r2) !mulrA !modzMDl.\nQed.\n\nLemma zchinese_modr r1 r2 : (zchinese r1 r2 = r2 %[mod m2])%Z.\nProof.\nrewrite /zchinese; have [u v /= Duv _] := egcdzP m1 m2.\nrewrite -{2}[r2]mulr1 -((gcdz _ _ =P 1) co_m12) -Duv.\nby rewrite mulrAC modzMDl mulrAC addrC mulrDr !mulrA modzMDl.\nQed.\n\nLemma zchinese_mod x : (x = zchinese (x %% m1)%Z (x %% m2)%Z %[mod m1 * m2])%Z.\nProof.\napply/eqP; rewrite zchinese_remainder //.\nby rewrite zchinese_modl zchinese_modr !modz_mod !eqxx.\nQed.\n\nEnd Chinese.\n\nSection ZpolyScale.\n\nDefinition zcontents (p : {poly int}) : int :=\n  sgz (lead_coef p) * \\big[gcdn/0%N]_(i < size p) `|(p`_i)%R|%N.\n\nLemma sgz_contents p : sgz (zcontents p) = sgz (lead_coef p).\nProof.\nrewrite /zcontents mulrC sgzM sgz_id; set d := _%:Z.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite lead_coef0 mulr0.\nrewrite gtr0_sgz ?mul1r // ltz_nat polySpred ?big_ord_recr //= -lead_coefE.\nby rewrite gcdn_gt0 orbC absz_gt0 lead_coef_eq0 nz_p.\nQed.\n\nLemma zcontents_eq0 p : (zcontents p == 0) = (p == 0).\nProof. by rewrite -sgz_eq0 sgz_contents sgz_eq0 lead_coef_eq0. Qed.\n\nLemma zcontents0 : zcontents 0 = 0.\nProof. by apply/eqP; rewrite zcontents_eq0. Qed.\n\nLemma zcontentsZ a p : zcontents (a *: p) = a * zcontents p.\nProof.\nhave [-> | nz_a] := eqVneq a 0; first by rewrite scale0r mul0r zcontents0.\nrewrite {2}[a]intEsg mulrCA -mulrA -PoszM big_distrr /= mulrCA mulrA -sgzM.\nrewrite -lead_coefZ; congr (_ * _%:Z); rewrite size_scale //.\nby apply: eq_bigr => i _; rewrite coefZ abszM.\nQed.\n\nLemma zcontents_monic p : p \\is monic -> zcontents p = 1.\nProof.\nmove=> mon_p; rewrite /zcontents polySpred ?monic_neq0 //.\nby rewrite big_ord_recr /= -lead_coefE (monicP mon_p) gcdn1.\nQed.\n\nLemma dvdz_contents a p : (a %| zcontents p)%Z = (p \\is a polyOver (dvdz a)).\nProof.\nrewrite dvdzE abszM absz_sg lead_coef_eq0.\nhave [-> | nz_p] := eqVneq; first by rewrite mul0n dvdn0 rpred0.\nrewrite mul1n; apply/dvdn_biggcdP/(all_nthP 0)=> a_dv_p i ltip /=.\n  exact: (a_dv_p (Ordinal ltip)).\nexact: a_dv_p.\nQed.\n\nLemma map_poly_divzK {a} p :\n  p \\is a polyOver (dvdz a) -> a *: map_poly (divz^~ a) p = p.\nProof.\nmove/polyOverP=> a_dv_p; apply/polyP=> i.\nby rewrite coefZ coef_map_id0 ?div0z // mulrC divzK.\nQed.\n\nLemma polyOver_dvdzP a p :\n  reflect (exists q, p = a *: q) (p \\is a polyOver (dvdz a)).\nProof.\napply: (iffP idP) => [/map_poly_divzK | [q ->]].\n  by exists (map_poly (divz^~ a) p).\nby apply/polyOverP=> i; rewrite coefZ dvdz_mulr.\nQed.\n\nDefinition zprimitive p := map_poly (divz^~ (zcontents p)) p.\n\nLemma zpolyEprim p : p = zcontents p *: zprimitive p.\nProof. by rewrite map_poly_divzK // -dvdz_contents. Qed.\n\nLemma zprimitive0 : zprimitive 0 = 0.\nProof.\nby apply/polyP=> i; rewrite coef0 coef_map_id0 ?div0z // zcontents0 divz0.\nQed.\n\nLemma zprimitive_eq0 p : (zprimitive p == 0) = (p == 0).\nProof.\napply/idP/idP=> /eqP p0; first by rewrite [p]zpolyEprim p0 scaler0.\nby rewrite p0 zprimitive0.\nQed.\n\nLemma size_zprimitive p : size (zprimitive p) = size p.\nProof.\nhave [-> | ] := eqVneq p 0; first by rewrite zprimitive0.\nby rewrite {1 3}[p]zpolyEprim scale_poly_eq0 => /norP[/size_scale-> _].\nQed.\n\nLemma sgz_lead_primitive p : sgz (lead_coef (zprimitive p)) = (p != 0).\nProof.\nhave [-> | nz_p] := eqVneq; first by rewrite zprimitive0 lead_coef0.\napply: (@mulfI _ (sgz (zcontents p))); first by rewrite sgz_eq0 zcontents_eq0.\nby rewrite -sgzM mulr1 -lead_coefZ -zpolyEprim sgz_contents.\nQed.\n\nLemma zcontents_primitive p : zcontents (zprimitive p) = (p != 0).\nProof.\nhave [-> | nz_p] := eqVneq; first by rewrite zprimitive0 zcontents0.\napply: (@mulfI _ (zcontents p)); first by rewrite zcontents_eq0.\nby rewrite mulr1 -zcontentsZ -zpolyEprim.\nQed.\n\nLemma zprimitive_id p : zprimitive (zprimitive p) = zprimitive p.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite !zprimitive0.\nby rewrite {2}[zprimitive p]zpolyEprim zcontents_primitive nz_p scale1r.\nQed.\n\nLemma zprimitive_monic p : p \\in monic -> zprimitive p = p.\nProof. by move=> mon_p; rewrite {2}[p]zpolyEprim zcontents_monic ?scale1r. Qed.\n\nLemma zprimitiveZ a p : a != 0 -> zprimitive (a *: p) = zprimitive p.\nProof.\nhave [-> | nz_p nz_a] := eqVneq p 0; first by rewrite scaler0.\napply: (@mulfI _ (a * zcontents p)%:P).\n  by rewrite polyC_eq0 mulf_neq0 ?zcontents_eq0.\nby rewrite -{1}zcontentsZ !mul_polyC -zpolyEprim -scalerA -zpolyEprim.\nQed.\n\nLemma zprimitive_min p a q :\n    p != 0 -> p = a *: q ->\n  {b | sgz b = sgz (lead_coef q) & q = b *: zprimitive p}.\nProof.\nmove=> nz_p Dp; have /dvdzP/sig_eqW[b Db]: (a %| zcontents p)%Z.\n  by rewrite dvdz_contents; apply/polyOver_dvdzP; exists q.\nsuffices ->: q = b *: zprimitive p.\n  by rewrite lead_coefZ sgzM sgz_lead_primitive nz_p mulr1; exists b.\napply: (@mulfI _ a%:P).\n  by apply: contraNneq nz_p; rewrite Dp -mul_polyC => ->; rewrite mul0r.\nby rewrite !mul_polyC -Dp scalerA mulrC -Db -zpolyEprim.\nQed.\n\nLemma zprimitive_irr p a q :\n  p != 0 -> zprimitive p = a *: q -> a = sgz (lead_coef q).\nProof.\nmove=> nz_p Dp; have: p = (a * zcontents p) *: q.\n  by rewrite mulrC -scalerA -Dp -zpolyEprim.\ncase/zprimitive_min=> // b <- /eqP.\nrewrite Dp -{1}[q]scale1r scalerA -subr_eq0 -scalerBl scale_poly_eq0 subr_eq0.\nhave{Dp} /negPf->: q != 0.\n  by apply: contraNneq nz_p; rewrite -zprimitive_eq0 Dp => ->; rewrite scaler0.\nby case: b a => [[|[|b]] | [|b]] [[|[|a]] | [|a]] //; rewrite mulr0.\nQed.\n\nLemma zcontentsM p q : zcontents (p * q) = zcontents p * zcontents q.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite !(mul0r, zcontents0).\nhave [-> | nz_q] := eqVneq q 0; first by rewrite !(mulr0, zcontents0).\nrewrite -[zcontents q]mulr1 {1}[p]zpolyEprim {1}[q]zpolyEprim.\nrewrite -scalerAl -scalerAr !zcontentsZ; congr (_ * (_ * _)).\nrewrite [zcontents _]intEsg sgz_contents lead_coefM sgzM !sgz_lead_primitive.\napply/eqP; rewrite nz_p nz_q !mul1r [_ == _]eqn_leq absz_gt0 zcontents_eq0.\nrewrite mulf_neq0 ?zprimitive_eq0 // andbT leqNgt.\napply/negP=> /pdivP[r r_pr r_dv_d]; pose to_r : int -> 'F_r := intr.\nhave nz_prim_r q1: q1 != 0 -> map_poly to_r (zprimitive q1) != 0.\n  move=> nz_q1; apply: contraTneq (prime_gt1 r_pr) => r_dv_q1.\n  rewrite -leqNgt dvdn_leq // -(dvdzE r true) -nz_q1 -zcontents_primitive.\n  rewrite dvdz_contents; apply/polyOverP=> i /=; rewrite dvdzE /=.\n  have /polyP/(_ i)/eqP := r_dv_q1; rewrite coef_map coef0 /=.\n  rewrite {1}[_`_i]intEsign rmorphM rmorph_sign /= mulf_eq0 signr_eq0 /=.\n  by rewrite -val_eqE /= val_Fp_nat.\nsuffices{nz_prim_r} /idPn[]: map_poly to_r (zprimitive p * zprimitive q) == 0.\n  by rewrite rmorphM mulf_neq0 ?nz_prim_r.\nrewrite [_ * _]zpolyEprim [zcontents _]intEsign mulrC -scalerA map_polyZ /=.\nby rewrite scale_poly_eq0 -val_eqE /= val_Fp_nat ?(eqnP r_dv_d).\nQed.\n\n\nLemma zprimitiveM p q : zprimitive (p * q) = zprimitive p * zprimitive q.\nProof.\nhave [pq_0|] := eqVneq (p * q) 0.\n  rewrite pq_0; move/eqP: pq_0; rewrite mulf_eq0.\n  by case/pred2P=> ->; rewrite !zprimitive0 (mul0r, mulr0).\nrewrite -zcontents_eq0 -polyC_eq0 => /mulfI; apply; rewrite !mul_polyC.\nby rewrite -zpolyEprim zcontentsM -scalerA scalerAr scalerAl -!zpolyEprim.\nQed.\n\nLemma dvdpP_int p q : p %| q -> {r | q = zprimitive p * r}.\nProof.\ncase/Pdiv.Idomain.dvdpP/sig2_eqW=> [[c r] /= nz_c Dpr].\nexists (zcontents q *: zprimitive r); rewrite -scalerAr.\nby rewrite -zprimitiveM mulrC -Dpr zprimitiveZ // -zpolyEprim.\nQed.\n\nLocal Notation pZtoQ := (map_poly (intr : int -> rat)).\n\nLemma size_rat_int_poly p : size (pZtoQ p) = size p.\nProof. by apply: size_map_inj_poly; first apply: intr_inj. Qed.\n\nLemma rat_poly_scale (p : {poly rat}) :\n  {q : {poly int} & {a | a != 0 & p = a%:~R^-1 *: pZtoQ q}}.\nProof.\npose a := \\prod_(i < size p) denq p`_i.\nhave nz_a: a != 0 by apply/prodf_neq0=> i _; apply: denq_neq0.\nexists (map_poly numq (a%:~R *: p)), a => //.\napply: canRL (scalerK _) _; rewrite ?intr_eq0 //.\napply/polyP=> i; rewrite !(coefZ, coef_map_id0) // numqK // Qint_def mulrC.\nhave [ltip | /(nth_default 0)->] := ltnP i (size p); last by rewrite mul0r.\nby rewrite [a](bigD1 (Ordinal ltip)) // rmorphM mulrA -numqE -rmorphM denq_int.\nQed.\n\nLemma dvdp_rat_int p q : (pZtoQ p %| pZtoQ q) = (p %| q).\nProof.\napply/dvdpP/Pdiv.Idomain.dvdpP=> [[/= r1 Dq] | [[/= a r] nz_a Dq]]; last first.\n  exists (a%:~R^-1 *: pZtoQ r); rewrite -scalerAl -rmorphM -Dq.\n  by rewrite -{2}[a]intz scaler_int rmorphMz -scaler_int scalerK ?intr_eq0.\nhave [r [a nz_a Dr1]] := rat_poly_scale r1; exists (a, r) => //=.\napply: (map_inj_poly _ _ : injective pZtoQ) => //; first exact: intr_inj.\nrewrite -[a]intz scaler_int rmorphMz -scaler_int /= Dq Dr1.\nby rewrite -scalerAl -rmorphM scalerKV ?intr_eq0.\nQed.\n\nLemma dvdpP_rat_int p q :\n    p %| pZtoQ q ->\n  {p1 : {poly int} & {a | a != 0 & p = a *: pZtoQ p1} & {r | q = p1 * r}}.\nProof.\nhave{p} [p [a nz_a ->]] := rat_poly_scale p.\nrewrite dvdpZl ?invr_eq0 ?intr_eq0 // dvdp_rat_int => dv_p_q.\nexists (zprimitive p); last exact: dvdpP_int.\nhave [-> | nz_p] := eqVneq p 0.\n  by exists 1; rewrite ?oner_eq0 // zprimitive0 map_poly0 !scaler0.\nexists ((zcontents p)%:~R / a%:~R).\n  by rewrite mulf_neq0 ?invr_eq0 ?intr_eq0 ?zcontents_eq0.\nby rewrite mulrC -scalerA -map_polyZ -zpolyEprim.\nQed.\n\nEnd ZpolyScale.\n\n(* Integral spans. *)\n\nLemma int_Smith_normal_form m n (M : 'M[int]_(m, n)) :\n  {L : 'M[int]_m & L \\in unitmx &\n  {R : 'M[int]_n & R \\in unitmx &\n  {d : seq int | sorted dvdz d &\n   M = L *m (\\matrix_(i, j) (d`_i *+ (i == j :> nat))) *m R}}}.\nProof.\nmove: {2}_.+1 (ltnSn (m + n)) => mn.\nelim: mn => // mn IHmn in m n M *; rewrite ltnS => le_mn.\nhave [[i j] nzMij | no_ij] := pickP (fun k => M k.1 k.2 != 0%N); last first.\n  do 2![exists 1%:M; first exact: unitmx1]; exists nil => //=.\n  apply/matrixP=> i j; apply/eqP; rewrite mulmx1 mul1mx mxE nth_nil mul0rn.\n  exact: negbFE (no_ij (i, j)).\ndo [case: m i => [[]//|m] i; case: n j => [[]//|n] j /=] in M nzMij le_mn *.\nwlog Dj: j M nzMij / j = 0; last rewrite {j}Dj in nzMij.\n  case/(_ 0 (xcol j 0 M)); rewrite ?mxE ?tpermR // => L uL [R uR [d dvD dM]].\n  exists L => //; exists (xcol j 0 R); last exists d => //=.\n     by rewrite xcolE unitmx_mul uR unitmx_perm.\n  by rewrite xcolE !mulmxA -dM xcolE -mulmxA -perm_mxM tperm2 perm_mx1 mulmx1.\nmove Da: (M i 0) nzMij => a nz_a.\nhave [A leA] := ubnP `|a|; elim: A => // A IHa in a leA m n M i Da nz_a le_mn *.\nwlog [j a'Mij]: m n M i Da le_mn / {j | ~~ (a %| M i j)%Z}; last first.\n  have nz_j: j != 0 by apply: contraNneq a'Mij => ->; rewrite Da.\n  case: n => [[[]//]|n] in j le_mn nz_j M a'Mij Da *.\n  wlog{nz_j} Dj: j M a'Mij Da / j = 1; last rewrite {j}Dj in a'Mij.\n    case/(_ 1 (xcol j 1 M)); rewrite ?mxE ?tpermR ?tpermD //.\n    move=> L uL [R uR [d dvD dM]]; exists L => //.\n    exists (xcol j 1 R); first by rewrite xcolE unitmx_mul uR unitmx_perm.\n    exists d; rewrite //= xcolE !mulmxA -dM xcolE -mulmxA -perm_mxM tperm2.\n    by rewrite perm_mx1 mulmx1.\n  have [u [v]] := Bezoutz a (M i 1); set b := gcdz _ _ => Db.\n  have{leA} ltA: (`|b| < A)%N.\n    rewrite -ltnS (leq_trans _ leA) // ltnS ltn_neqAle andbC.\n    rewrite dvdn_leq ?absz_gt0 ? dvdn_gcdl //=.\n    by rewrite (contraNneq _ a'Mij) ?dvdzE // => <-; apply: dvdn_gcdr.\n  pose t2 := [fun j : 'I_2 => [tuple _; _]`_j : int]; pose a1 := M i 1.\n  pose Uul := \\matrix_(k, j) t2 (t2 u (- (a1 %/ b)%Z) j) (t2 v (a %/ b)%Z j) k.\n  pose U : 'M_(2 + n) := block_mx Uul 0 0 1%:M; pose M1 := M *m U.\n  have{nz_a} nz_b: b != 0 by rewrite gcdz_eq0 (negPf nz_a).\n  have uU: U \\in unitmx.\n    rewrite unitmxE det_ublock det1 (expand_det_col _ 0) big_ord_recl big_ord1.\n    do 2!rewrite /cofactor [row' _ _]mx11_scalar !mxE det_scalar1 /=.\n    rewrite mulr1 mul1r mulN1r opprK -[_ + _](mulzK _ nz_b) mulrDl.\n    by rewrite -!mulrA !divzK ?dvdz_gcdl ?dvdz_gcdr // Db divzz nz_b unitr1.\n  have{} Db: M1 i 0 = b.\n    rewrite /M1 -(lshift0 n 1) [U]block_mxEh mul_mx_row row_mxEl.\n    rewrite -[M](@hsubmxK _ _ 2) (@mul_row_col _ _ 2) mulmx0 addr0 !mxE /=.\n    rewrite big_ord_recl big_ord1 !mxE /= [lshift _ _]((_ =P 0) _) // Da.\n    by rewrite [lshift _ _]((_ =P 1) _) // mulrC -(mulrC v).\n  have [L uL [R uR [d dvD dM1]]] := IHa b ltA _ _ M1 i Db nz_b le_mn.\n  exists L => //; exists (R *m invmx U); last exists d => //.\n    by rewrite unitmx_mul uR unitmx_inv.\n  by rewrite mulmxA -dM1 mulmxK.\nmove=> {A leA}IHa; wlog Di: i M Da / i = 0; last rewrite {i}Di in Da.\n  case/(_ 0 (xrow i 0 M)); rewrite ?mxE ?tpermR // => L uL [R uR [d dvD dM]].\n  exists (xrow i 0 L); first by rewrite xrowE unitmx_mul unitmx_perm.\n  exists R => //; exists d; rewrite //= xrowE -!mulmxA (mulmxA L) -dM xrowE.\n  by rewrite mulmxA -perm_mxM tperm2 perm_mx1 mul1mx.\nwithout loss /forallP a_dvM0: / [forall j, a %| M 0%R j]%Z.\n  case: (altP forallP) => [_ IH|/forallPn/sigW/IHa IH _]; exact: IH.\nwithout loss{Da a_dvM0} Da: M / forall j, M 0 j = a.\n  pose Uur := col' 0 (\\row_j (1 - (M 0%R j %/ a)%Z)).\n  pose U : 'M_(1 + n) := block_mx 1 Uur 0 1%:M; pose M1 := M *m U.\n  have uU: U \\in unitmx by rewrite unitmxE det_ublock !det1 mulr1.\n  case/(_ (M *m U)) => [j | L uL [R uR [d dvD dM]]].\n    rewrite -(lshift0 m 0) -[M](@submxK _ 1 _ 1) (@mulmx_block _ 1 m 1).\n    rewrite (@col_mxEu _ 1) !mulmx1 mulmx0 addr0 [ulsubmx _]mx11_scalar.\n    rewrite mul_scalar_mx !mxE !lshift0 Da.\n    case: splitP => [j0 _ | j1 Dj]; rewrite ?ord1 !mxE // lshift0 rshift1.\n    by rewrite mulrBr mulr1 mulrC divzK ?subrK.\n  exists L => //; exists (R * U^-1); first by rewrite unitmx_mul uR unitmx_inv.\n  by exists d; rewrite //= mulmxA -dM mulmxK.\nwithout loss{IHa} /forallP/(_ (_, _))/= a_dvM: / [forall k, a %| M k.1 k.2]%Z.\n  case: (altP forallP) => [_|/forallPn/sigW [[i j] /= a'Mij] _]; first exact.\n  have [|||L uL [R uR [d dvD dM]]] := IHa _ _ M^T j; rewrite ?mxE 1?addnC //.\n    by exists i; rewrite mxE.\n  exists R^T; last exists L^T; rewrite ?unitmx_tr //; exists d => //.\n  rewrite -[M]trmxK dM !trmx_mul mulmxA; congr (_ *m _ *m _).\n  by apply/matrixP=> i1 j1 /[!mxE]; case: eqVneq => // ->.\nwithout loss{nz_a a_dvM} a1: M a Da / a = 1.\n  pose M1 := map_mx (divz^~ a) M; case/(_ M1 1)=> // [k|L uL [R uR [d dvD dM]]].\n    by rewrite !mxE Da divzz nz_a.\n  exists L => //; exists R => //; exists [seq a * x | x <- d].\n    case: d dvD {dM} => //= x d; elim: d x => //= y d IHd x /andP[dv_xy /IHd].\n    by rewrite [dvdz _ _]dvdz_mul2l ?[_ \\in _]dv_xy.\n  have ->: M = a *: M1 by apply/matrixP=> i j; rewrite !mxE mulrC divzK ?a_dvM.\n  rewrite dM scalemxAl scalemxAr; congr (_ *m _ *m _).\n  apply/matrixP=> i j; rewrite !mxE mulrnAr; congr (_ *+ _).\n  have [lt_i_d | le_d_i] := ltnP i (size d); first by rewrite (nth_map 0).\n  by rewrite !nth_default ?size_map ?mulr0.\nrewrite {a}a1 -[m.+1]/(1 + m)%N -[n.+1]/(1 + n)%N in M Da *.\npose Mu := ursubmx M; pose Ml := dlsubmx M.\nhave{} Da: ulsubmx M = 1 by rewrite [_ M]mx11_scalar !mxE !lshift0 Da.\npose M1 := - (Ml *m Mu) + drsubmx M.\nhave [|L uL [R uR [d dvD dM1]]] := IHmn m n M1; first by rewrite -addnS ltnW.\nexists (block_mx 1 0 Ml L).\n  by rewrite unitmxE det_lblock det_scalar1 mul1r.\nexists (block_mx 1 Mu 0 R).\n  by rewrite unitmxE det_ublock det_scalar1 mul1r.\nexists (1 :: d); set D1 := \\matrix_(i, j) _ in dM1.\n  by rewrite /= path_min_sorted //; apply/allP => g _; apply: dvd1n.\nrewrite [D in _ *m D *m _](_ : _ = block_mx 1 0 0 D1); last first.\n  by apply/matrixP=> i j; do 3?[rewrite ?mxE ?ord1 //=; case: splitP => ? ->].\nrewrite !mulmx_block !(mul0mx, mulmx0, addr0) !mulmx1 add0r mul1mx -Da -dM1.\nby rewrite addNKr submxK.\nQed.\n\nDefinition inIntSpan (V : zmodType) m (s : m.-tuple V) v :=\n  exists a : int ^ m, v = \\sum_(i < m) s`_i *~ a i.\n\nLemma dec_Qint_span (vT : vectType rat) m (s : m.-tuple vT) v :\n  decidable (inIntSpan s v).\nProof.\nhave s_s (i : 'I_m): s`_i \\in <<s>>%VS by rewrite memv_span ?memt_nth.\nhave s_Zs a: \\sum_(i < m) s`_i *~ a i \\in <<s>>%VS.\n  by rewrite memv_suml // => i _; rewrite -scaler_int memvZ.\ncase s_v: (v \\in <<s>>%VS); last by right=> [[a Dv]]; rewrite Dv s_Zs in s_v.\npose S := \\matrix_(i < m, j < _) coord (vbasis <<s>>) j s`_i.\npose r := \\rank S; pose k := (m - r)%N; pose Em := erefl m; pose Ek := erefl k.\nhave Dm: (m = k + r)%N by rewrite subnK ?rank_leq_row.\nhave [K kerK]: {K : 'M_(k, m) | map_mx intr K == kermx S}%MS.\n  pose B := row_base (kermx S); pose d := \\prod_ij denq (B ij.1 ij.2).\n  exists (castmx (mxrank_ker S, Em) (map_mx numq (intr d *: B))).\n  rewrite /k; case: _ / (mxrank_ker S); set B1 := map_mx _ _.\n  have ->: B1 = (intr d *: B).\n    apply/matrixP=> i j; rewrite 3!mxE mulrC [d](bigD1 (i, j)) // rmorphM mulrA.\n    by rewrite -numqE -rmorphM numq_int.\n  suffices nz_d: d%:Q != 0 by rewrite !eqmx_scale // !eq_row_base andbb.\n  by rewrite intr_eq0; apply/prodf_neq0 => i _; apply: denq_neq0.\nhave [L _ [G uG [D _ defK]]] := int_Smith_normal_form K.\npose Gud := castmx (Dm, Em) G; pose G'lr := castmx (Em, Dm) (invmx G).\nhave{K L D defK kerK} kerGu: map_mx intr (usubmx Gud) *m S = 0.\n  pose Kl : 'M[rat]_k:= map_mx intr (lsubmx (castmx (Ek, Dm) (K *m invmx G))).\n  have{} defK: map_mx intr K = row_mx Kl 0 *m map_mx intr Gud.\n    rewrite -[K](mulmxKV uG) -{2}[G](castmxK Dm Em) -/Gud.\n    rewrite -[K *m _](castmxK Ek Dm) map_mxM map_castmx.\n    rewrite -(hsubmxK (castmx _ _)) map_row_mx -/Kl map_castmx /Em.\n    set Kr := map_mx _ _; case: _ / (esym Dm) (map_mx _ _) => /= GudQ.\n    congr (row_mx _ _ *m _); apply/matrixP=> i j; rewrite !mxE defK mulmxK //=.\n    rewrite castmxE mxE big1 //= => j1 _; rewrite mxE /= eqn_leq andbC.\n    by rewrite leqNgt (leq_trans (valP j1)) ?mulr0 ?leq_addr.\n  have /row_full_inj: row_full Kl; last apply.\n    rewrite /row_full eqn_leq rank_leq_row /= -{1}[k](mxrank_ker S).\n    rewrite -(eqmxP kerK) defK map_castmx mxrankMfree; last first.\n      case: _ / (Dm); apply/row_freeP; exists (map_mx intr (invmx G)).\n      by rewrite -map_mxM mulmxV ?map_mx1.\n    by rewrite -mxrank_tr tr_row_mx trmx0 -addsmxE addsmx0 mxrank_tr.\n  rewrite mulmx0 mulmxA (sub_kermxP _) // -(eqmxP kerK) defK.\n  by rewrite -{2}[Gud]vsubmxK map_col_mx mul_row_col mul0mx addr0.\npose T := map_mx intr (dsubmx Gud) *m S.\nhave{kerGu} defS: map_mx intr (rsubmx G'lr) *m T = S.\n  have: G'lr *m Gud = 1%:M by rewrite /G'lr /Gud; case: _ / (Dm); apply: mulVmx.\n  rewrite -{1}[G'lr]hsubmxK -[Gud]vsubmxK mulmxA mul_row_col -map_mxM.\n  move/(canRL (addKr _))->; rewrite -mulNmx raddfD /= map_mx1 map_mxM /=.\n  by rewrite mulmxDl -mulmxA kerGu mulmx0 add0r mul1mx.\npose vv := \\row_j coord (vbasis <<s>>) j v.\nhave uS: row_full S.\n  apply/row_fullP; exists (\\matrix_(i, j) coord s j (vbasis <<s>>)`_i).\n  apply/matrixP=> j1 j2; rewrite !mxE.\n  rewrite -(coord_free _ _ (basis_free (vbasisP _))).\n  rewrite -!tnth_nth (coord_span (vbasis_mem (mem_tnth j1 _))) linear_sum.\n  by apply: eq_bigr => i _; rewrite !mxE (tnth_nth 0) !linearZ.\nhave eqST: (S :=: T)%MS by apply/eqmxP; rewrite -{1}defS !submxMl.\ncase Zv: (map_mx denq (vv *m pinvmx T) == const_mx 1).\n  pose a := map_mx numq (vv *m pinvmx T) *m dsubmx Gud.\n  left; exists [ffun j => a 0 j].\n  transitivity (\\sum_j (map_mx intr a *m S) 0 j *: (vbasis <<s>>)`_j).\n    rewrite {1}(coord_vbasis s_v); apply: eq_bigr => j _; congr (_ *: _).\n    have ->: map_mx intr a = vv *m pinvmx T *m map_mx intr (dsubmx Gud).\n      rewrite map_mxM /=; congr (_ *m _); apply/rowP=> i; rewrite 2!mxE numqE.\n      by have /eqP/rowP/(_ i)/[!mxE]-> := Zv; rewrite mulr1.\n    by rewrite -(mulmxA _ _ S) mulmxKpV ?mxE // -eqST submx_full.\n  rewrite (coord_vbasis (s_Zs _)); apply: eq_bigr => j _; congr (_ *: _).\n  rewrite linear_sum mxE; apply: eq_bigr => i _.\n  by rewrite -scaler_int linearZ [a]lock !mxE ffunE.\nright=> [[a Dv]]; case/eqP: Zv; apply/rowP.\nhave ->: vv = map_mx intr (\\row_i a i) *m S.\n  apply/rowP=> j; rewrite !mxE Dv linear_sum.\n  by apply: eq_bigr => i _; rewrite -scaler_int linearZ !mxE.\nrewrite -defS -2!mulmxA; have ->: T *m pinvmx T = 1%:M.\n  have uT: row_free T by rewrite /row_free -eqST.\n  by apply: (row_free_inj uT); rewrite mul1mx mulmxKpV.\nby move=> i; rewrite mulmx1 -map_mxM 2!mxE denq_int mxE.\nQed.\n", "meta": {"author": "math-comp", "repo": "math-comp", "sha": "e39f9173b484f2e8e7f69f746a619dcc8f3abc1b", "save_path": "github-repos/coq/math-comp-math-comp", "path": "github-repos/coq/math-comp-math-comp/math-comp-e39f9173b484f2e8e7f69f746a619dcc8f3abc1b/mathcomp/algebra/intdiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.7879312006227323, "lm_q1q2_score": 0.6952924482784433}}
{"text": "Require Export XR_R.\nRequire Export XR_Rlt.\nRequire Export XR_Rlt_irrefl.\nRequire Export XR_total_order_T.\n\nImplicit Type r : R.\nLocal Open Scope R_scope.\n\nLemma Req_dec : forall r1 r2, r1 = r2 \\/ r1 <> r2.\nProof.\n  intros x y.\n  destruct (total_order_T x y) as [ [ hxy | heq ] | hyx ].\n  {\n    right.\n    unfold not.\n    intro heq.\n    subst y.\n    generalize dependent hxy.\n    apply Rlt_irrefl.\n  }\n  {\n    left.\n    exact heq.\n  }\n  {\n    right.\n    unfold not.\n    intro heq.\n    subst y.\n    generalize dependent hyx.\n    apply Rlt_irrefl.\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_Req_dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6952924385334391}}
{"text": "Require Import Notations.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.Le.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.omega.Omega.\nRequire Import Bool.Sumbool.\nRequire Import Bool.Bool.\nRequire Import Coq.Logic.ConstructiveEpsilon.\nRequire Import Coq.ZArith.ZArith.\nRequire Import ListLemma.\nImport ListNotations.\nOpen Scope Z.\n\nSection Schulze.\n\n  (* candidates are a finite type with decidable equality *)\n  Variable cand : Type.\n  Variable cand_all : list cand.\n  Hypothesis cand_fin : forall c: cand, In c cand_all.\n  Hypothesis dec_cand : forall n m : cand, {n = m} + {n <> m}.\n  Hypothesis cand_not_nil : cand_all <> nil.\n\n  Section Evote.\n    (** Section 2: Specification of Schulze Vote Counting **)\n\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\n        (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 : forall c d, marg c d >= k -> PathT k c d\n    | consT : forall 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) *\n       (existsT (f : (cand * cand) -> bool), 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),\n      ((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      intros c d k H.\n      induction H; [constructor 1 | constructor 2 with d]; auto.\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      (* 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;  omega.\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 | omega].\n    Qed.\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    Fixpoint M (n : nat) (c d : cand) : Z :=\n      match n with\n      | 0%nat => marg c d\n      | S n' =>\n        Z.max (M n' c d) (maxlist (map (fun x : cand => Z.min (marg c x) (M n' x d)) cand_all))\n      end.\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    Definition iterated_marg_patht : forall n s c d, M n c d >= s -> PathT s c d :=\n      fix F n s c d :=\n        match n as m return (M m c d >= s -> PathT s c d) with\n        | O =>\n          fun Hm : M 0 c d >= s => unitT s c d Hm\n        | S n' =>\n          fun Hm : M (S n') c d >= s =>\n            let t1 := M n' c d in\n            let t2 := maxlist (map (fun x : cand => Z.min (marg c x) (M n' x d)) cand_all) in\n            let cm := t1 ?= t2  in\n            match\n              cm as cv\n              return\n              (match cv with\n               | Eq => t1\n               | Lt => t2\n               | Gt => t1\n               end >= s -> PathT s c d)\n            with\n            | Eq => fun Heq : M n' c d >= s => F n' s c d Heq\n            | Lt =>\n              fun Hlt : maxlist (map (fun x : cand => Z.min (marg c x) (M n' x d)) cand_all) >= s =>\n                match max_of_nonempty_list_type cand cand_all cand_not_nil dec_cand s _ Hlt with\n                | existT _ x (conj H1 H2) =>\n                  match proj1 (z_min_lb _ _ _) H2 with\n                  | conj H3 H4 => (consT s c x d H3  (F n' s x d H4))\n                  end\n                end\n            | Gt => fun Hgt : M n' c d >= s =>  F n' s c d Hgt\n            end Hm\n        end.\n            \n   \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. 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. auto. destruct IHPath.\n      exists (S x). simpl. 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 omega.\n      apply Z.ge_le. apply z_max_lb with (m := M m c d).\n      left. omega.\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 *. auto.\n      intros. simpl in *. destruct l. simpl in *. apply z_max_lb.\n      left. apply IHk with []. simpl. omega. simpl. auto.\n      simpl in *. apply z_min_lb in H0. destruct H0.\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      omega. apply IHk with l. omega. omega.\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      simpl. intros. pose proof (proj1 (z_max_lb (M k c d) _ s) H). destruct H0.\n      specialize (IHk c d s H0). destruct IHk as [l [H1 H2]]. exists l. omega. 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. omega.\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). omega.\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 omega.\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))). omega.\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 omega.\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).  omega.\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        omega. }\n      rewrite H9 in H10. rewrite H8 in H10.\n      assert (((k' + n) < (p + n))%nat -> (k' < p)%nat) by omega.\n      specialize (H11 H10). assert (k' < k)%nat by omega.\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. omega. }\n      specialize (H14 H15). clear H13. rewrite <- H9 in H. omega.\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 omega.\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. omega.\n        assert ((v <= m)%nat -> (m >= v)%nat) by omega.\n        specialize (H1 H). specialize (IHle H1). destruct IHle as [p H2].\n        exists (S p). omega. }\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    (* 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    (* 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. omega.\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. omega.\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). omega.\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.\n            intuition.\n            apply IHn. 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 omega.\n            destruct A as [A1 | A2].\n            left. apply Z.ltb_lt. simpl. omega.\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 omega.\n            destruct B as [B1 | B2].\n            intuition.\n            apply iterated_marg_path in B2.\n            assert (A3 : marg x y >= r + 1) by omega.\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). omega.\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). omega.\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). omega.\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 omega.\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. omega.\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). simpl in *. omega.\n      simpl in H0. apply Z.max_lub_lt_iff in H0. destruct H0. apply IHn. auto.\n      simpl 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 omega.\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 omega.\n      destruct H2. auto.\n      apply iterated_marg_path in H2.  pose proof (Evote.cons _ _ _ _ H1 H2).\n      apply  path_iterated_marg in H3. destruct H3 as [n H3].\n      pose proof (iterated_marg_fp x z n). omega.\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). omega.\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). omega.\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. pose proof (proj1 (c_wins_true c) H). destruct H0. specialize (H1 x). omega.\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). omega.\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\n  \n    \n  End Evote.\n  \n  \n  Section Count.\n\n    (* votes put numbers next to candidates when filling in a ballot. We understand\n       zero next to a candidates name as a preference that hasn't been filled in *)\n    Definition ballot := cand -> nat.\n\n    (* a State is an intermediate state of contstructing the margin function, given\n       by a list of uncounted, and a list of invalid ballots, or a final state, given by\n       a boolean function that determines the election winners *)\n    Inductive State: Type :=\n    | partial: (list ballot * list ballot)  -> (cand -> cand -> Z) -> State\n    | winners: (cand -> bool) ->  State.\n\n    (* The inductive type that represents vote counting according to the Schulze method.\n       Constructors:\n       - ax initiates the count: all ballots are uncounted, no ballots are invalid,\n         and the initial margin between candidates is zero.\n       - cvalid counts a valid ballot, i.e. all entries in the ballot are > 0.\n         Here u is the ballot being counted, us are the remaining uncounted ballots, inbs are\n         invalid ballots, m is the margin function, and nm the new margin function obtained after\n         updating m according to the preferences recorded in the ballot u.\n       - cinvalid counts an invalid ballot, i.e. a ballot with a zero entry. Again, u\n         is the ballot being processed, inbs are the invalid ballots and m is the margin\n         function. Here, m does not change, but u is added to the invalid ballots.\n       - fin concludes the count by determining the winners and losers of a Schulze\n         count according to the fully constructed margin function m. Here w is a boolean function\n         that determines which candidates are winners, and d gives type level evidence of this. *)\n    Inductive Count (bs : list ballot) : State -> Type :=\n    | ax us m : us = bs -> (forall c d, m c d = 0) ->\n                Count bs (partial (us, []) m)             (* zero margin      *)\n    | cvalid u us m nm inbs : Count bs (partial (u :: us, inbs) m) ->\n                              (forall c, (u c > 0)%nat) ->              (* u is valid       *)\n                              (forall c d : cand,\n                                  ((u c < u d)%nat -> nm c d = m c d + 1) (* c preferred to d *) /\\\n                                  ((u c = u d)%nat -> nm c d = m c d)     (* c, d rank equal  *) /\\\n                                  ((u c > u d)%nat -> nm c d = m c d - 1))(* d preferred to c *) ->\n                              Count bs (partial (us, inbs) nm)\n    | cinvalid u us m inbs : Count bs (partial (u :: us, inbs) m) ->\n                             (exists c, (u c = 0)%nat)                 (* u is invalid     *) ->\n                             Count bs (partial (us, u :: inbs) m)\n    | fin m inbs w (d : (forall c, (wins_type m c) + (loses_type m\n                                                            c))):\n        Count bs (partial ([], inbs) m)           (* no ballots left  *) ->\n        (forall c, w c = true <-> (exists x, d c = inl x)) ->\n        (forall c, w c = false <-> (exists x, d c = inr x)) ->\n        Count bs (winners w).\n\n    Open Scope nat_scope.\n\n    (* for finite lists and decidable predicates, existential quantifiers are equivalent\n      to negated universal quantifiers. This holds more generally, but the formulation\n      below suffices for our purposes. *)\n    Definition forall_exists_fin_dec : forall (A : Type) (l : list A) (f : A -> nat),\n        {forall x, In x l -> f x > 0} + {exists x, In x l /\\ f x = 0} := \n      fun (A : Type) =>\n        fix F l f {struct l} :=\n        match l with\n        | [] => left (fun (x : A) (H : In x []) => match H with end)\n        | h :: t =>\n          match Nat.eq_dec (f h) 0 with\n          | left e =>\n            right (ex_intro _  h (conj (in_eq h t) e))\n          | right n =>\n            match F t f with\n            | left Fl =>\n              left (fun x H =>\n                      match H with\n                      | or_introl H1 =>\n                        match zerop (f x) with\n                        | left e =>\n                          False_ind (f x > 0) ((eq_ind h (fun v : A => f v <> 0) n x H1) e)\n                        | right r => r\n                        end\n                      | or_intror H2 => Fl x H2\n                      end)\n            | right Fr =>\n              right\n                match Fr with\n                | ex_intro _ x (conj Frl Frr) =>\n                  ex_intro _ x (conj (in_cons h x t Frl) Frr)\n                end\n            end\n          end\n        end.\n            \n    (* we can decide whether a given ballot is valid, i.e. has only non-zero entries, or\n     is invalid, i.e. contains at least one zero entry *)\n    Definition ballot_valid_dec : forall b : ballot, {forall c, b c > 0} + {exists c, b c = 0} :=\n      fun b => let H := forall_exists_fin_dec cand cand_all in\n            match H b with\n            | left Lforall => left\n                               (fun c : cand => Lforall c (cand_fin c))\n            | right Lexists => right\n                                match Lexists with\n                                | ex_intro _ x (conj _ L) =>\n                                  ex_intro (fun c : cand => b c = 0) x L\n                                end\n            end.\n    \n    Open Scope Z_scope.\n\n    (* update margin function to account for preferences recorded in a single ballot *)\n    Definition update_marg (p : ballot) (m : cand -> cand -> Z) : cand -> cand -> Z :=\n      fun c d =>  if (Nat.ltb (p c) (p d))%nat\n               then (m c d + 1)%Z\n               else (if (Nat.ltb (p d) (p c))%nat\n                     then (m c d -1)%Z\n                     else m c d).\n\n\n    \n    Definition listify_v (m : cand -> cand -> Z) :=\n      map (fun s => (fst s, snd s, m (fst s) (snd s))) (all_pairs cand_all). \n\n\n    Fixpoint linear_search_v (c d : cand) (m : cand -> cand -> Z) l :=\n      match l with\n      | [] => m 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_v c d m t\n        end\n      end.\n    \n   \n\n    \n\n    Definition update_marg_listify (p : ballot) (m : cand -> cand -> Z) : cand -> cand -> Z :=\n      let t := update_marg p m in\n      let l := listify_v t in\n      fun c d => linear_search_v c d t l.\n    \n    \n    \n\n\n    Theorem equivalent_m_w_v : forall c d m, linear_search_v c d m (listify_v m) = m c d.\n    Proof.\n      unfold  listify_v.\n      intros. induction (all_pairs cand_all); simpl; auto.\n      destruct a as (a1, a2). simpl in *.\n      destruct (dec_cand c a1).\n      destruct (dec_cand d a2). subst. auto.\n      auto. auto.\n    Qed.\n\n    Corollary equiv_cor : forall p m c d, update_marg p m c d = update_marg_listify p m c d.\n    Proof.\n      intros p m c d.  unfold update_marg_listify.\n      rewrite <- equivalent_m_w_v. \n      auto.      \n    Qed.\n      \n    (* correctness of update_marg above *)\n    Lemma update_marg_corr: forall m (p : ballot) (c d : cand),\n        ((p c < p d)%nat -> update_marg p m c d = m c d + 1) /\\\n        ((p c = p d)%nat -> update_marg p m c d = m c d) /\\\n        ((p c > p d)%nat -> update_marg p m c d = m c d - 1).\n    Proof.\n      intros m p c d.\n      split; intros; unfold update_marg.\n      destruct (p c <? p d)%nat eqn: H1. omega.\n      destruct (p d <? p c)%nat eqn: H2. apply Nat.ltb_lt in H2.\n      apply Nat.ltb_ge in H1. omega.\n      apply Nat.ltb_ge in H2. apply Nat.ltb_ge in H1. omega.\n      split; intros.\n      destruct (p c <? p d)%nat eqn: H1.\n      apply Nat.ltb_lt in H1. omega.\n      apply Nat.ltb_ge in H1. destruct (p d <? p c)%nat eqn: H2. apply Nat.ltb_lt in H2.\n      apply Nat.ltb_ge in H1. omega. apply Nat.ltb_ge in H2. omega.\n      unfold update_marg.\n      destruct (p c <? p d)%nat eqn:H1. apply Nat.ltb_lt in H1. omega.\n      apply Nat.ltb_ge in H1. destruct (p d <? p c)%nat eqn: H2.\n      apply Nat.ltb_lt in H2. omega. apply Nat.ltb_ge in H2. omega.\n    Qed.\n\n    \n     Lemma update_marg_corr_listify: forall m (p : ballot) (c d : cand),\n        ((p c < p d)%nat -> update_marg_listify p m c d = m c d + 1) /\\\n        ((p c = p d)%nat -> update_marg_listify p m c d = m c d) /\\\n        ((p c > p d)%nat -> update_marg_listify p m c d = m c d - 1).\n     Proof.\n       intros m p c d. rewrite <- equiv_cor. apply update_marg_corr.\n     Qed. \n\n    \n    (* every partial state of vote tallying can be progressed to a state where\n       the margin function is fully constructed, i.e. all ballots are counted *)\n\n    Definition partial_count_all_counted bs : forall u inbs m,\n        Count bs (partial (u, inbs) m) ->  existsT i m, (Count bs (partial ([], i) m)) :=\n      fix F u {struct u} :=\n        match u with\n        | [] =>\n          fun inbs m Hc =>\n            existT _ inbs (existT _ m Hc)\n        | h :: t =>\n          fun inbs m Hc =>\n            match ballot_valid_dec h with\n            | left Hv =>\n              let w := update_marg_listify h m in \n              F t inbs w (cvalid bs h t m w inbs Hc Hv (update_marg_corr_listify m h))\n            | right Hi =>  F t (h :: inbs) m (cinvalid bs h t m inbs Hc Hi)\n            end\n        end.\n  \n      \n     \n   \n    \n    (* for every list of incoming ballots, we can progress the count to a state where all\n     ballots are processed *)\n\n    Definition all_ballots_counted (bs : list ballot) :\n      existsT i m, Count bs (partial ([], i) m) :=\n      partial_count_all_counted bs bs [] (fun _ _ : cand => 0)\n                                (ax bs bs (fun _ _ : cand => 0) eq_refl\n                                    (fun _ _ : cand => eq_refl)).\n\n\n    (* memoization part to run it faster *)\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    Fixpoint linear_search (c d : cand) (m : cand -> cand -> Z) l :=\n      match l with\n      | [] => m 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 m t\n        end\n      end.\n    \n    Definition w m (c d : cand) :=\n      let l := listify m in\n      linear_search c d m l.\n    \n    \n    Theorem equivalent_m_w : forall m c d, w m c d = m c d.\n    Proof.\n      unfold w. unfold listify.\n      intros. induction (all_pairs cand_all); simpl; auto.\n      destruct a as (a1, a2). simpl in *.\n      destruct (dec_cand c a1).\n      destruct (dec_cand d a2). subst. auto.\n      auto. auto.\n    Qed.\n    \n    Require Import Coq.Logic.FunctionalExtensionality.\n    Theorem ext : forall m,  (forall c d, w m c d = m c d) -> w m = m.\n    Proof.\n      intros. extensionality a. extensionality b. auto.     \n    Qed.\n    \n    \n    Definition schulze_winners (bs : list ballot) :\n      existsT (f : cand -> bool) (p : Count bs (winners f)), True.\n      refine (let (i, t) := all_ballots_counted bs in\n              let (m, p) := t in\n              let l := listify m in\n              let g := fun c d => linear_search c d m l in _).\n      pose proof (ext m (equivalent_m_w m)) as H.\n      rewrite <- H in p. \n      refine (existT _ (c_wins g) (existT _ (fin _ _ _ _ (wins_loses_type_dec g) p\n                                                 (c_wins_true_type g) (c_wins_false_type g)) I)).\n    Defined. *)\n    \n    \n    \n  \n    (* The main theorem: for every list of ballots, we can find a boolean function that decides\n     winners, together with evidences of the correctness of this determination *)\n    Definition schulze_winners (bs : list ballot) :\n      existsT (f : cand -> bool) (p : Count bs (winners f)), True :=\n      let (i, t) := all_ballots_counted bs in\n      let (m, p) := t in\n      existT _ (c_wins m) (existT _ (fin _ _ _ _ (wins_loses_type_dec m) p\n                                         (c_wins_true_type m) (c_wins_false_type m)) I).\n   \n    \n    \n  End Count.\n  \nEnd Schulze.\n\n\n\nSection Candidate.\n  \n  Inductive cand := A | B | C | D.\n  Definition cand_all := [A; B; C; D].\n\n  Lemma cand_finite : forall c, In c cand_all.\n  Proof.\n    unfold cand_all; intro a; repeat induction a || (unfold In; tauto).\n  Qed.\n\n  Lemma  cand_eq_dec : forall c d : cand, {c = d} + {c <> d}.\n  Proof.\n    intros a b;\n      repeat induction a; \n      repeat (induction b) || (right; discriminate) ||(left; trivial).\n  Defined.\n\n  Lemma cand_not_empty : cand_all <> nil.\n  Proof. unfold cand_all. intuition. inversion H.\n  Qed.\n\nEnd Candidate.\n\n\nDefinition schulze_winners_pf :=\n  schulze_winners cand cand_all cand_finite cand_eq_dec cand_not_empty.\n\n", "meta": {"author": "mukeshtiwari", "repo": "formalized-voting", "sha": "44c001288087c96c0fe8569dcc6c9704e68fb9aa", "save_path": "github-repos/coq/mukeshtiwari-formalized-voting", "path": "github-repos/coq/mukeshtiwari-formalized-voting/formalized-voting-44c001288087c96c0fe8569dcc6c9704e68fb9aa/SchulzeCounting/SchulzeSynthesis.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6952675952873684}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma mul_split_at_bitwidth_mod bw x y : fst (Z.mul_split_at_bitwidth bw x y)  = (x * y) mod 2^bw.\n  Proof.\n    unfold Z.mul_split_at_bitwidth, LetIn.Let_In; break_innermost_match; Z.ltb_to_lt; try reflexivity;\n      apply Z.land_ones; lia.\n  Qed.\n  Lemma mul_split_at_bitwidth_div bw x y : snd (Z.mul_split_at_bitwidth bw x y)  = (x * y) / 2^bw.\n  Proof.\n    unfold Z.mul_split_at_bitwidth, LetIn.Let_In; break_innermost_match; Z.ltb_to_lt; try reflexivity;\n      apply Z.shiftr_div_pow2; lia.\n  Qed.\n  Lemma mul_split_mod s x y : fst (Z.mul_split s x y)  = (x * y) mod s.\n  Proof.\n    unfold Z.mul_split; break_match; Z.ltb_to_lt;\n      [ rewrite mul_split_at_bitwidth_mod; congruence | reflexivity ].\n  Qed.\n  Hint Rewrite mul_split_mod : to_div_mod.\n  Lemma mul_split_div s x y : snd (Z.mul_split s x y)  = (x * y) / s.\n  Proof.\n    unfold Z.mul_split; break_match; Z.ltb_to_lt;\n      [ rewrite mul_split_at_bitwidth_div; congruence | reflexivity ].\n  Qed.\n  Hint Rewrite mul_split_div : to_div_mod.\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/MulSplit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6952675817612111}}
{"text": "(*\n    Proof of Correctness of Insertion Sort from scratch\n    Only assumptions include existence of a type with\n    a decidable ordering that is transitive and antisymmetric.\n    \n    Last updated 28th December 2021\n*)\n\nSection Sorting.\n  Inductive list {T : Type} : Type :=\n  | nil_list : list\n  | cons_list : T -> list -> list.\n  \n  Inductive Bool : Set :=\n  | false : Bool\n  | true : Bool.\n  \n  Inductive True : Prop :=\n  | yes : True.\n  \n  Register True as core.True.type.\n  \n  Inductive False : Prop :=.\n  \n  Register False as core.False.type.\n  \n  Definition is_true (b : Bool) :=\n  match b with\n  | true => True\n  | false => False\n  end.\n  \n  Inductive inhabited (T : Type) : Prop := inhabits : T -> inhabited T. \n  \n  Lemma prop_eq_iff : forall (P Q : Prop), P = Q -> (P <-> Q).\n  Proof.\n    split. all: intro. \n    rewrite H in H0. trivial. \n    rewrite <- H in H0. trivial.\n  Qed.\n  \n  Lemma forall_and : forall {T : Type}(P Q : T -> Prop),\n    (forall t : T, P t /\\ Q t) <-> \n    (forall t : T, P t) /\\ (forall t : T, Q t).\n  Proof.\n    split. intro. split. apply H. apply H.\n    intros. destruct H as [H G]. split. apply (H t). apply (G t).\n  Qed.\n  \n  Lemma diff_true_false : true <> false.\n  Proof. \n    intro. apply f_equal with (f := fun t => is_true t) in H.\n    simpl in H. apply prop_eq_iff in H. destruct H. contradiction.\n  Qed.\n  \n  Lemma diff_false_true : false <> true.\n  Proof.\n    intro. symmetry in H. apply diff_true_false in H. contradiction.\n  Qed.\n  \n  Definition diff_bool : true <> false /\\ false <> true.\n  Proof.\n    split. apply diff_true_false. apply diff_false_true.\n  Qed.\n  \n  Inductive Nat : Set :=\n  | zero : Nat\n  | succ : Nat -> Nat.\n  \n  Theorem zero_not_succ : forall (n : Nat), succ n <> zero.\n  Proof.\n    set (N2B (n : Nat) := match n with | succ n' => true | zero => false end).\n    intro. induction n. \n    all: intro; apply f_equal with (f := fun t => N2B t) in H;\n    simpl in H; apply diff_bool in H; contradiction.\n  Qed.\n  \n  Theorem nat_not_succ : forall (n : Nat), succ n <> n.\n  Proof.\n    intro. induction n. apply zero_not_succ.\n    intro. inversion H. contradiction.\n  Qed.\n  \n  Fixpoint add (n m : Nat) :=\n  match n with\n  | zero => m\n  | succ n' => succ (add n' m)\n  end.\n  \n  Lemma add_id_r : forall n, add n zero = n.\n  Proof.\n    intro. induction n. trivial.\n    simpl. rewrite IHn. reflexivity.\n  Qed.\n  \n  Lemma add_succ_r : forall n m, add n (succ m) = succ (add n m).\n  Proof.\n    intros. induction n. trivial.\n    simpl. rewrite IHn. reflexivity.\n  Qed.\n  \n  Lemma add_comm : forall n m, add n m = add m n.\n  Proof.\n    intros. induction m. rewrite add_id_r. trivial.\n    simpl. rewrite add_succ_r, IHm. reflexivity.\n  Qed.\n  \n  Fixpoint sum_over_list {T : Type} (f : T -> Nat) (l : list) :=\n  match l with\n  | nil_list => zero\n  | cons_list a w => add (f a) (sum_over_list f w)\n  end.\n  \n  Lemma nil_list_unique : forall {T : Type} (l : @list T) t, \n    (cons_list t l) <> nil_list.\n  Proof.\n    intros T l t H.\n    apply f_equal with \n      (f := fun k => match k with | nil_list => true | _ => false end)\n    in H.\n    apply diff_bool, H.\n  Qed. \n  \n  Ltac destruct_bool := intros; destruct_all Bool; simpl in *; trivial; try discriminate.\n  \n  Lemma bool_decidability : forall (a b : Bool), {a = b} + {a <> b}.\n  Proof.\n    intros. destruct_bool.\n    left. reflexivity. right. apply diff_bool.\n    right. apply diff_bool. left. reflexivity.\n  Qed.\n  \n  Lemma true_proof (P : Prop) : (True -> P) -> P.\n  Proof.\n    intro. exact (H yes).\n  Qed.\n  \n  Definition band (a b : Bool) : Bool :=\n  match a, b with\n  | true, true => true\n  | _, _ => false\n  end.\n  Infix \"&&\" := band (at level 40, left associativity).\n  \n  Definition bor (a b : Bool) : Bool :=\n  match a, b with\n  | true, _ => true\n  | _, true => true\n  | _, _ => false\n  end.\n  Infix \"||\" := bor (at level 50, left associativity).\n\n  Inductive Permutation {T : Type} : @list T -> list -> Prop :=\n  | perm_nil : Permutation nil_list nil_list\n  | perm_skip : forall a x y, Permutation x y -> Permutation (cons_list a x) (cons_list a y)\n  | perm_swap : forall a b x, Permutation (cons_list a (cons_list b x)) (cons_list b (cons_list a x))\n  | perm_trans : forall x y z, Permutation x y -> Permutation y z -> Permutation x z.\n  \n  Definition perm_id : forall {T : Type} (l : @list T), Permutation l l.\n  Proof.\n    intro. induction l. exact perm_nil. exact (perm_skip t l l IHl).\n  Qed.\n  \n  Definition perm_refl : \n    forall {T : Type} (x y : @list T), Permutation x y -> Permutation y x.\n  Proof.\n    intros. induction H. \n    exact perm_nil.\n    apply (perm_skip a y x). assumption.\n    apply (perm_swap b a x).\n    apply (perm_trans z y x IHPermutation2 IHPermutation1).\n  Qed.\n  \n  Fixpoint length {T : Type} (l : @list T) : Nat :=\n  match l with\n  | cons_list a w => succ (length w)\n  | nil_list  => zero\n  end.\n  \n  Lemma list_length_zero : forall {T : Type} (l : @list T), \n    length l = zero -> l = nil_list.\n  Proof.\n    intros. induction l. \n    reflexivity. simpl in H.\n    apply zero_not_succ in H. contradiction.\n  Qed.\n  \n  Theorem length_invar_perm : forall {T : Type} (x y : @list T), \n    Permutation x y -> (length x) = (length y).\n  Proof.\n    intros. induction H. reflexivity.\n    simpl. rewrite IHPermutation. reflexivity.\n    simpl. reflexivity.\n    rewrite IHPermutation2 in IHPermutation1. assumption.\n  Qed.\n  \n  Lemma perm_of_nil : \n    forall {T : Type} (l : @list T), Permutation l nil_list -> l = nil_list.\n  Proof.\n    intros. apply length_invar_perm in H. simpl in H.\n    apply list_length_zero in H. assumption.\n  Qed.\n  \n  Fixpoint All {T : Type} (P : T -> Prop) (l : list) : Prop :=\n  match l with\n  | nil_list => True\n  | cons_list x w => (P x) /\\ (All P w)\n  end.\n  \n  Inductive Every {T : Type} (P : T -> Prop) : list -> Prop :=\n  | every_nil : Every P nil_list\n  | every_cons t l : Every P l -> P t -> Every P (cons_list t l).\n  \n  Theorem all_every_equiv : forall {T : Type} (P : T -> Prop) l,\n    All P l -> Every P l.\n  Proof.\n    intros. induction l. exact (every_nil P).\n    simpl in H. destruct H. apply IHl in H0.\n    exact (every_cons P t l H0 H).\n  Qed.\n  \n  Theorem every_all_equiv : forall {T : Type} (P : T -> Prop) l,\n    Every P l -> All P l.\n  Proof.\n    intros. induction H. simpl. apply yes.\n    simpl. split. apply H0. apply IHEvery.\n  Qed.\n  \n  Lemma every_rem : forall {T : Type} (P : T -> Prop) t l,\n  Every P (cons_list t l) -> Every P l.\n  Proof.\n    intros. apply every_all_equiv in H. simpl in H. destruct H.\n    apply all_every_equiv in H0. apply H0.\n  Qed.\n  \n  Lemma every_check : forall {T : Type} (P : T -> Prop) t l,\n  Every P (cons_list t l) -> P t.\n  Proof.\n    intros. apply every_all_equiv in H. simpl in H.\n    destruct H. apply H.\n  Qed.\n  \n  Lemma every_expand : forall {T : Type} (P : T -> Prop) t l,\n  Every P (cons_list t l) <-> (P t) /\\ (Every P l).\n  Proof.\n    split. intro. split. apply every_all_equiv in H. simpl in H. destruct H.\n    apply H. apply every_rem in H. apply H.\n    intro. destruct H. apply (every_cons P t l).\n    apply H0. apply H.\n  Qed.\n  \n  Lemma all_in_perms : forall {T : Type} (P : T -> Prop) (x y : list),\n    Permutation x y -> All P x -> All P y.\n  Proof.\n    intros.\n    \n    induction H. apply H0.\n    simpl in H0. destruct H0. simpl. split.\n    apply H0. apply (IHPermutation H1).\n    \n    simpl. repeat split. \n    all: simpl in H0; repeat destruct H0; trivial.\n    \n    apply (IHPermutation2 (IHPermutation1 H0)).\n  Qed.\n  \n  (*Lemma perm_f_indpndnt : forall {T : Type} (f : @list T -> list) t l,\n    Permutation l (f l) -> Permutation (cons_list t (f l)) (f (cons_list t l)).\n  Proof.\n    intros.\n    induction l.\n  Qed.*)\n  \n  Variable A : Type.\n  Variable blt : A -> A -> Bool.\n  Variable blt_antisym : forall (a b : A), blt a b = true <-> blt b a = false.\n  Variable blt_trans : forall (a b c : A), ((blt a b) && (blt b c)) = (blt a c).\n  \n  (*Variable lt : A -> A -> Prop.\n  Variable lt_antisym : forall (a b : A), lt a b <-> (lt b a -> False).\n  Variable lt_blt_equiv : forall (a b : A), blt a b = true <-> lt a b.\n  Variable lt_blt_antiequiv : forall (a b : A), blt a b = false <-> lt b a.\n  Variable lt_decidability : forall (a b : A), \n    (lt a b /\\ not (lt b a)) \\/ (lt b a /\\ not (lt a b)).*)\n  \n  Variable beq : A -> A -> Bool.\n  Infix \"==\" := beq (at level 50, left associativity).\n  \n  Variable beq_refl : forall (a : A), a == a = true.\n  \n  (*Variable beq_symmetry : forall (a b : A), (a == b) = (b == a).\n\n  Variable beq_transitivity : forall (a b c : A), \n    ((a == b) && (b == c)) = (a == c).*)\n  \n  Variable beq_eq : forall (a b : A), a == b = true -> a = b.\n  \n  Lemma blt_antirefl : forall (a : A), blt a a = false.\n  Proof.\n    intro. destruct (blt a a) eqn:H.\n    reflexivity. apply blt_antisym in H as G.\n    rewrite H in G. assumption.\n  Qed.\n  \n  Lemma blt_decidability : forall (a b : A), {blt a b = true} + {blt a b = false}.\n  Proof.\n    intros. destruct (blt a b) eqn:H.\n    right. reflexivity.\n    left. reflexivity.\n  Qed.\n  \n  Definition lt (a b : A) := blt a b = true.\n\n  Lemma lt_antisym : forall (a b : A), lt a b <-> (lt b a -> False).\n  Proof.\n    split. unfold lt. intros. apply blt_antisym in H.\n    rewrite H0 in H. apply diff_bool in H. contradiction.\n    unfold lt. intros. apply blt_antisym.\n    destruct (blt b a) eqn:G. reflexivity. contradiction.\n  Qed.\n  \n  Lemma lt_decidability : forall (a b : A), \n    (lt a b /\\ not (lt b a)) \\/ (lt b a /\\ not (lt a b)).\n  Proof.\n    intros. unfold lt. destruct (blt a b) eqn:H.\n    right. split. apply blt_antisym in H. \n    apply H. apply diff_bool.\n    left. split. \n    reflexivity. apply blt_antisym in H. rewrite H. apply diff_bool.\n  Qed.\n  \n  Lemma lt_blt_equiv : forall (a b : A), blt a b = true <-> lt a b.\n  Proof.\n    split. intro. unfold lt. assumption. \n    intro. unfold lt in H. assumption.\n  Qed.\n  \n  Lemma lt_blt_antiequiv : forall (a b : A), blt a b = false <-> lt b a.\n  Proof.\n    split. intro. unfold lt. apply blt_antisym. assumption.\n    intro. unfold lt in H. apply blt_antisym. assumption.\n  Qed.\n\n  \n  Lemma blt_inv (a b : A) : blt a b = true <-> blt b a = false.\n  Proof.\n    split. intro. apply lt_blt_equiv, lt_blt_antiequiv in H. apply H.\n    intro. apply lt_blt_antiequiv, lt_blt_equiv in H. apply H.\n  Qed.\n  \n  Fixpoint frequency (l : @list A) (t : A) :=\n  match l with\n  | nil_list => zero\n  | cons_list r w => match t == r with\n                     | true => succ (frequency w t)\n                     | false => frequency w t\n                     end\n  end.\n  \n  Lemma frequency_cons : forall l t,\n    frequency (cons_list t l) t = succ (frequency l t).\n  Proof.\n    intros. induction l. simpl. rewrite beq_refl. reflexivity.\n    destruct (t == t0) eqn:Ht;\n    simpl; rewrite Ht; rewrite beq_refl; reflexivity.\n  Qed.\n  \n  Lemma frequency_succ : forall l t a,\n    frequency (cons_list t l) a = succ (frequency l a) -> a == t = true.\n  Proof.\n    intros. destruct (a == t) eqn:G.\n    unfold frequency in H. rewrite G in H. fold frequency in H.\n    symmetry in H. apply nat_not_succ in H. contradiction.\n    reflexivity.\n  Qed.\n  \n  Lemma frequency_nil : forall l, (forall t, frequency l t = zero) <->\n    l = nil_list.\n  Proof.\n    split. intros. induction l. reflexivity.\n    \n    exfalso. set (G := frequency (cons_list t l) t).\n    assert (exists m, G = succ m).\n    unfold G, frequency. rewrite beq_refl.\n    fold frequency. exists (frequency l t). reflexivity.\n    unfold G in H0. rewrite H in H0. destruct H0. symmetry in H0.\n    apply (zero_not_succ x H0).\n    \n    intros.\n    rewrite H. simpl. reflexivity.\n  Qed.\n  \n  Definition Permutation' (x y : list):= forall (a : A),\n    frequency x a = frequency y a.\n  \n  Lemma perm'_nil : Permutation' nil_list nil_list.\n  Proof.\n    unfold Permutation'. trivial.\n  Qed.\n  \n  Lemma perm'_skip : forall (x y : list) (t : A),\n    Permutation' x y -> Permutation' (cons_list t x) (cons_list t y).\n  Proof.\n    unfold Permutation'. intros.\n    destruct (a == t) eqn:Ht;\n    simpl; rewrite Ht; rewrite H; reflexivity.\n  Qed.\n  \n  Lemma perm'_swap : forall (l : list) (a b : A),\n    Permutation' (cons_list a (cons_list b l))\n                 (cons_list b (cons_list a l)).\n  Proof.\n    unfold Permutation'. intros.\n    destruct (a0 == a) eqn:Ha; destruct (a0 == b) eqn:Hb; simpl;\n    rewrite Ha, Hb; reflexivity.\n  Qed.\n  \n  Lemma perm'_trans : forall (x y z : list),\n    Permutation' x y -> Permutation' y z -> Permutation' x z.\n  Proof.\n    unfold Permutation'. intros x y z Hxy Hyz a.\n    rewrite Hxy, Hyz. reflexivity.\n  Qed.\n  \n  Lemma perm'_of_nil : \n    forall (l : list), Permutation' l nil_list -> l = nil_list.\n  Proof.\n    intros. unfold Permutation' in H. simpl in H.\n    apply frequency_nil in H. assumption.\n  Qed.\n  \n  Theorem Permutation_Permutation'_coincide_r : forall x y,\n    Permutation x y -> Permutation' x y.\n  Proof.\n    intros. induction H.\n    \n    apply perm'_nil.\n    apply perm'_skip. assumption.\n    apply perm'_swap.\n    apply (perm'_trans x y z); assumption.\n  Qed. (*I haven't been able to prove that the reverse isn't possible*)\n  \n  Fixpoint contains {T : Type} (x : list) (t : T) : Prop :=\n  match x with\n  | nil_list => False\n  | cons_list a y => t = a \\/ contains y t\n  end.\n  \n  Inductive contains' {T : Type} : list -> T -> Prop :=\n  | contains_cons : forall (x : list) (t : T),\n      contains' (cons_list t x) t\n  | contains_cont : forall (x : list) (t a : T),\n      contains' x t -> contains' (cons_list a x) t.\n  \n  Lemma contains_nil : forall {T : Type} (a : T),\n    contains nil_list a -> False.\n  Proof.\n    intros. simpl in H. apply H.\n  Qed.\n  \n  Lemma contains_singleton : forall {T : Type} (a t : T),\n    contains (cons_list a nil_list) t -> t = a.\n  Proof.\n    intros. simpl in H. destruct H. apply H. contradiction.\n  Qed.\n  \n  Lemma contains'_nil : forall {T : Type} (a : T),\n    contains' nil_list a -> False.\n  Proof.\n    intros. inversion H as [x b Hl Ha | x b c Ha Hl Ht];\n    apply f_equal with (f := fun t => length t) in Hl;\n    simpl in Hl; apply zero_not_succ in Hl; contradiction.\n  Qed.\n  \n  Lemma contains'_cons : forall {T : Type} (x : list) (a t : T),\n    contains' (cons_list a x) t -> t = a \\/ contains' x t.\n  Proof.\n    intros. inversion H as [l b Hx Heq | l b c Hcon Hx Heq].\n    left; reflexivity. right; apply Hcon.\n  Qed.\n  \n  Lemma contains'_cons_nil : forall {T : Type} (x : list) (a t : T),\n    (contains' (cons_list a x) t -> False) -> (contains' x t -> False).\n  Proof.\n    intros. apply H. apply contains_cont. apply H0.\n  Qed.\n  \n  Theorem contains_contains'_coincide : forall (x : list) (t : A),\n    contains x t <-> contains' x t.\n  Proof.\n    split; intro; induction x.\n    \n    apply contains_nil in H. contradiction.\n    destruct H as [Hl | Hr].\n    rewrite Hl. apply contains_cons.\n    apply contains_cont, (IHx Hr).\n    \n    apply contains'_nil in H. contradiction.\n    inversion H as [w|w]. unfold contains. left. reflexivity.\n    simpl. apply contains'_cons in H.\n    destruct H as [Hl | Hr].\n    left; apply Hl. right; apply (IHx Hr).\n  Qed.\n  \n  Lemma contains_frequency_nil : forall (x : list) (a : A),\n    (contains x a -> False) <-> frequency x a = zero.\n  Proof.\n    split; intros; induction x.\n    \n    trivial. destruct_bool. destruct (a == t) eqn:G.\n    apply IHx. intro. apply H. right. apply H0.\n    intuition. apply beq_eq, H0 in G. contradiction.\n    \n    apply contains_nil in H0. contradiction.\n    simpl in H0. destruct (a == t) eqn:G.\n    unfold frequency in H. rewrite G in H.\n    fold frequency in H.\n    destruct H0. rewrite H0, beq_refl in G.\n    apply diff_true_false in G. contradiction.\n    apply (IHx H H0).\n    simpl in H. rewrite G in H. apply zero_not_succ in H.\n    contradiction.\n  Qed.\n  \n  Definition Permutation'' (x y : list) := forall (a : A),\n    (contains x a <-> contains y a) /\\ frequency x a = frequency y a.\n  \n  Lemma perm''_nil : Permutation'' nil_list nil_list.\n  Proof.\n    unfold Permutation''. intro. simpl.\n    split; try split; trivial.\n  Qed.\n  \n(* The following commented-out code is a work in progress.\n\n  Lemma perm''_skip : forall (x y : list) (t : A),\n    Permutation'' x y -> Permutation'' (cons_list t x) (cons_list t y).\n  Proof.\n    unfold Permutation''. intros. split. split.\n    destruct (H a) as [Hc Hf].\n    \n    simpl. destruct (t == k) eqn:G.\n    apply contains'_cons in Hy as G. destruct G.\n    simpl. rewrite H0, beq_refl.\n    apply f_equal with (f := fun t => succ t).\n    apply (H k).\n    \n    destruct_bool; destruct (t == k) eqn:G.\n    destruct Hx, Hy;\n    try ((rewrite H0 in G || rewrite H1 in G); rewrite beq_refl in G;\n    apply diff_true_false in G; contradiction).\n    apply (H t H0 H1).\n    \n    apply f_equal with (f := fun t => succ t).\n    apply (H t).\n    destruct Hx.\n  Qed.\n  \n  Lemma perm''_swap : forall (l : list) (a b : A),\n    Permutation'' (cons_list a (cons_list b l))\n                 (cons_list b (cons_list a l)).\n  Proof.\n    unfold Permutation'. intros.\n    destruct (a0 == a) eqn:Ha; destruct (a0 == b) eqn:Hb; simpl;\n    rewrite Ha, Hb; reflexivity.\n  Qed.\n  \n  Lemma perm''_trans : forall (x y z : list),\n    Permutation'' x y -> Permutation'' y z -> Permutation'' x z.\n  Proof.\n    unfold Permutation''. intros x y z Hxy Hyz a.\n    rewrite Hxy, Hyz. reflexivity.\n  Qed.\n  \n  Lemma perm''_of_nil : \n    forall (l : list), Permutation'' l nil_list -> l = nil_list.\n  Proof.\n    intros. unfold Permutation' in H. simpl in H.\n    apply frequency_nil in H. assumption.\n  Qed.\n  \n  Theorem Permutation'_Permutation''_coincide : forall (x y : list),\n    Permutation' x y <-> Permutation'' x y.\n  Proof.\n    split; intro. induction y.\n    apply perm'_of_nil in H. rewrite H.\n  Qed.\n  *)\n  \n  Inductive Sorted : list -> Prop :=\n  | nil_sorted : Sorted (nil_list)\n  | singleton_sorted a : Sorted (cons_list a (nil_list))\n  | list_sorted a b l : Sorted (cons_list b l) -> lt a b \n    -> Sorted (cons_list a (cons_list b l)).\n  \n  Fixpoint Sorted' (l : list) :=\n  match l with\n  | nil_list => True\n  | cons_list a x => match x with\n                     | nil_list => True\n                     | cons_list b y => (lt a b) /\\ Sorted' x\n                     end\n  end.\n  \n  Lemma Sorted_rem (l : list) : forall (a : A), \n    Sorted (cons_list a l) -> Sorted l.\n  Proof.\n    intros. inversion H.\n    apply f_equal with (f := fun t => length t) in H0.\n    simpl in H0. symmetry in H0. apply zero_not_succ in H0.\n    contradiction.\n    exact nil_sorted.\n    assumption.\n  Qed.\n  \n  Lemma Sorted'_rem (l : list) : forall (a : A),\n    Sorted' (cons_list a l) -> Sorted' l.\n  Proof.\n    intros. induction l. trivial. \n    simpl in H. destruct H as [lt S'bl].\n    induction l. trivial. apply S'bl.\n  Qed.\n  \n  Theorem Sorted_Sorted'_coincide : forall l, Sorted l <-> Sorted' l.\n  Proof.\n    split.\n    intro. induction H.\n    all: simpl; try apply yes.\n    split. assumption.\n    induction l. apply yes.\n    split. simpl in IHSorted.\n    destruct IHSorted as [lt S'tl].\n    apply lt. apply Sorted'_rem in IHSorted. assumption.\n    \n    intro. induction l. exact nil_sorted.\n    induction l. exact (singleton_sorted t).\n    apply Sorted'_rem in H as G.\n    apply IHl in G. simpl in H. destruct H as [lt S't0l].\n    apply (list_sorted t t0 l G lt).\n  Qed.\n  \n  Definition Is_Sorting_Algorithm (f : list -> list) := \n    forall (l : list), (Sorted (f l) /\\ Permutation l (f l)).\n  \n  Fixpoint insertion (n : A) (l : list) :=\n  match l return list with\n  | nil_list => cons_list n nil_list\n  | cons_list h k => if blt h n then\n                       cons_list n (cons_list h k)\n                       else cons_list h (insertion n k)\n  end.\n  \n  Fixpoint insertion_sort (l : list) :=\n  match l with\n  | nil_list => l\n  | cons_list h k => insertion h (insertion_sort k)\n  end.\n  \n  Lemma insertion_into_sorted_is_sorted : forall (l : list) (a : A),\n    Sorted l -> Sorted (insertion a l).\n  Proof.\n    intros l a S. induction S; simpl. exact (singleton_sorted a).\n    \n    destruct (blt a0 a) eqn:H. \n    apply lt_blt_antiequiv in H.\n    exact (list_sorted a a0 nil_list (singleton_sorted a0) H).\n    apply lt_blt_equiv in H.\n    exact (list_sorted a0 a nil_list (singleton_sorted a) H).\n    \n    destruct (blt a0 a) eqn:G.\n    apply lt_blt_antiequiv in G.\n    exact (list_sorted a a0 (cons_list b l) (list_sorted a0 b l S H) G).\n    \n    destruct (blt b a) eqn:K.\n    apply lt_blt_equiv in G. apply lt_blt_antiequiv in K.\n    exact (list_sorted a0 a (cons_list b l) (list_sorted a b l S K) G).\n    apply lt_blt_equiv in G, K. \n    unfold insertion in IHS.\n    destruct (blt b a) eqn:L in IHS.\n    apply lt_blt_antiequiv in L.\n    \n    exfalso.\n    destruct (lt_decidability a b) as [dl | dr].\n    destruct dl as [x y]. contradiction.\n    destruct dr as [x y]. contradiction.\n    \n    fold insertion in IHS.\n    exact (list_sorted a0 b (insertion a l) IHS H).\n  Qed.\n  \n  Lemma insertion_into_is_perm_of_cons : forall (a : A) (l : list),\n    Permutation (cons_list a l) (insertion a l).\n  Proof.\n    intros.\n    \n    induction l.\n    simpl. exact (perm_skip a nil_list nil_list perm_nil).\n    \n    unfold insertion. destruct (blt t a) eqn:H.\n    exact (perm_id (cons_list a (cons_list t l))). fold insertion.\n    \n    set (x := cons_list a (cons_list t l)).\n    set (y := cons_list t (cons_list a l)).\n    set (z := cons_list t (insertion a l)).\n    set (K := perm_swap a t l).\n    set (G := perm_skip t (cons_list a l) (insertion a l) IHl).\n    apply (perm_trans x y z K G).\n  Qed.\n  \n  Theorem Insertion_Sort_Is_Sorting_Alg : Is_Sorting_Algorithm insertion_sort.\n  Proof.\n    unfold Is_Sorting_Algorithm. intros.\n    \n    induction l. simpl. split. exact nil_sorted. exact perm_nil.\n    destruct IHl as [Hs Hp].\n    split. simpl. apply insertion_into_sorted_is_sorted.\n    assumption.\n    \n    simpl. apply (perm_skip t l (insertion_sort l)) in Hp.\n    \n    set (x := cons_list t l).\n    set (y := cons_list t (insertion_sort l)).\n    set (z := insertion t (insertion_sort l)).\n    set (G := insertion_into_is_perm_of_cons t (insertion_sort l)).\n    apply (perm_trans x y z Hp G).\n  Qed.\n  \n  Definition clear_list (l : @list A):= @nil_list A.\n  \n  Lemma Clear_List_Sorts : forall (l : list), \n    Sorted (clear_list l).\n  Proof.\n    intros. unfold clear_list. apply nil_sorted.\n  Qed.\n  \n  Lemma Clear_List_Not_Permutes : forall (l : list), \n    l <> nil_list -> Permutation l (clear_list l) -> False.\n  Proof.\n    intros. destruct l. contradiction.\n    unfold clear_list in H0.\n    apply perm_of_nil in H0. contradiction.\n  Qed.\n  \n  Theorem Clear_List_Not_Sorting_Alg : inhabited A -> Is_Sorting_Algorithm clear_list -> False.\n  Proof.\n    unfold Is_Sorting_Algorithm. intros Hin H.\n    apply forall_and in H. destruct H as [H G].\n    inversion Hin as [a].\n    set (l := cons_list a nil_list).\n    assert (l <> nil_list) as Heq by (apply nil_list_unique).\n    set (Hn := G l).\n    apply (Clear_List_Not_Permutes l Heq Hn).\n  Qed.\n  \n  \n  \n  \n  \n  \n  \n  ", "meta": {"author": "felixjhb", "repo": "rhul_coq", "sha": "d80f8120ce7ed796dc324597cac3a6dbb5e8d4a6", "save_path": "github-repos/coq/felixjhb-rhul_coq", "path": "github-repos/coq/felixjhb-rhul_coq/rhul_coq-d80f8120ce7ed796dc324597cac3a6dbb5e8d4a6/sorting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6952029654816108}}
{"text": "Require Import List.\nSection Last.\n\nVariable A : Set.\nSet Implicit Arguments.\n\nInductive last (a:A) : list A -> Prop :=\n   | last_hd : last a (a :: nil)\n   | last_tl : forall (b:A) (l:list A), last a l -> last a (b :: l).\n\n\nHint Resolve last_hd last_tl.\n\nFixpoint last_fun (l:list A) : option A :=\n  match l with\n  | nil => None (A:=A)\n  | a :: nil => Some a\n  | a :: l' => last_fun l'\n  end.\n\nTheorem last_fun_correct :\n forall (a:A) (l:list A), last a l -> last_fun l = Some a.\nProof.\n intros a l H; elim H; simpl; auto.\n intros b l0; case l0; simpl.\n discriminate 2.\n inversion_clear 1; auto.\nQed.\n\nTheorem last_fun_correct2 :\n forall (a:A) (l:list A), last_fun l = Some a -> last a l.\nProof.\n intros a l ; elim l; simpl.\n discriminate 1.\n intros a0 l0; case l0; simpl.\n injection 2.\n intro e; rewrite e; auto.\n auto.\nQed.\n\nLemma last_fun_of_cons : forall (l:list A) (a:A), last_fun (a :: l) <> None.\nProof.\n intros l ; elim l; simpl.\n intros a H; discriminate H.\n intros a l0 H0 b.\n auto.\nQed.\n\nTheorem last_fun_correct3 :\n forall l:list A, last_fun l = None -> forall b:A, ~ last b l.\nProof.\n intro l; case l.\n simpl.\n red; inversion 2.\n intros a l0 H. \n case (last_fun_of_cons l0 a H). \nQed.\n\nEnd Last.\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/last.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.6952029556650516}}
{"text": "Require Import Basics.\nRequire Import Types.\nRequire Import Algebra.Group.\nRequire Import Algebra.AbelianGroup.\nRequire Import Homotopy.Pi1S1.\nRequire Import Algebra.Z.\nRequire Import Pointed.\nRequire Import Spaces.Int.\nRequire Import HIT.Circle.\nRequire Import Truncations.\nRequire Import Homotopy.HomotopyGroup.\nRequire Import UnivalenceImpliesFunext.\nImport TrM.\n\nRequire Import Torus.\nRequire Import TorusEquivCircles.\n\nLocal Open Scope trunc_scope.\nLocal Open Scope pointed_scope.\n\n(** The torus is 1-truncated *)\n\nGlobal Instance is1type_Torus `{Univalence} : IsTrunc 1 Torus.\nProof.\n  refine (trunc_equiv _ equiv_torus_prod_S1^-1).\nQed.\n\n(** The torus is 0-connected *)\n\nGlobal Instance isconnected_Torus `{Univalence} : IsConnected 0 Torus.\nProof.\n  serapply (isconnected_equiv' _ _ equiv_torus_prod_S1^-1).\n  serapply (isconnected_equiv' _ _ (equiv_sigma_prod0 _ _)).\nQed.\n\n(** We give these notations for the pointed versions. *)\nLocal Notation T := (Build_pType Torus _).\nLocal Notation S1 := (Build_pType S1 _).\n\n(** Loop space of Torus *)\nTheorem loops_torus `{Univalence} : loops T <~>* Int * Int.\nProof.\n  srefine (_ o*E _).\n  1: exact (loops (S1 * S1)).\n  1: apply pequiv_loops_functor.\n  { serapply Build_pEquiv.\n    1: serapply Build_pMap.\n    1: exact equiv_torus_prod_S1.\n    1: reflexivity.\n    exact _. }\n  srefine (_ o*E _).\n  1: exact (loops S1 * loops S1).\n  1: apply loops_prod.\n  simple notypeclasses refine (Build_pEquiv _ _ _ _).\n  1: serapply Build_pMap.\n  { apply functor_prod.\n    1,2: apply equiv_loopS1_int. }\n  1: reflexivity.\n  exact _.\nDefined.\n\nLemma pequiv_torus_prod_circles `{Funext} : T  <~>* S1 * S1.\nProof.\n  serapply Build_pEquiv'.\n  1: apply equiv_torus_prod_S1.\n  reflexivity.\nDefined.\n\n(* Fundamental group of Torus *)\n\nTheorem Pi1Torus `{Univalence}\n  : GroupIsomorphism (Pi 1 T) (group_prod Z Z).\nProof.\n  etransitivity.\n  { apply groupiso_pi_functor.\n    apply pequiv_torus_prod_circles. }\n  etransitivity.\n  1: apply pi_prod.\n  apply grp_iso_prod.\n  1,2: apply Pi1Circle.\nDefined.\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/theories/Spaces/Torus/TorusHomotopy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.695126785458499}}
{"text": "Require Import MathClasses.interfaces.canonical_names.\nRequire Import BijNat.\nRequire Import Frame.\nRequire Import MeetSemiLattice.\nRequire Import PreorderEquiv.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Lists.List.\n\n(**\n This module constructs the free sigma-frame generated\n by a meet semilattice, with relations on the generators.\n\n It is a formalization of Theorem 3.3 in \n \n Thierry Coquand, Giovanni Sambin, Jan Smith, Silvio Valentini\n\n Inductively generated formal topologies\n \n #<a href=\"http://doai.io/10.1016/S0168-0072(03)00052-6\">http://doai.io/10.1016/S0168-0072(03)00052-6</a>#\n *)\n\nSection Free_Frame.\n  \n(** * Definition of the free frame *)\n\n  (** ** Assumptions *)\n  \n  (** First we assume a meet semilattice of generators, [T].  Note\n      that this structure comes with its own equality (setoid). As in\n      the rest of this development, setoid equalities are\n      denoted by [a = b], whereas coq's definitional equality is [a ≡\n      b] (because we use the setoid equality much more often\n      than the definitional one). *)\n  Variable T : Type.\n  Variable Tle : Le T.\n  Variable Tmsl : @MeetSemiLattice T Tle.\n  Existing Instance Feq_equiv.\n \n  (**\n      There are many ways to present the relations (called here\n      axioms) that we want to impose on the generated structure.\n      Following the paper, restrict the form of axioms to\n      inequalities [a ≤ U], where [a] is a generator and [U]\n      is a countable set of generators. Any axiom can be \n      written as a conjunction of these.\n      These basic axioms are written [a ◁_0 U] in the paper.\n\n      For each generator, we are given an index set for its coverings.\n      This formalization allows us to accept an arbitrary number\n      of axioms for each generator.\n\n   *)\n  Variable Idx : forall t:T, Set.\n  (**\n      For each generator and an index in its index set,\n      we associate a contable family of generators:\n      this is understood as enumerating the axiom [t ◁_0 CovAx t i]\n  *)\n  Variable CovAx : forall t:T, forall i:Idx t, (nat -> T).\n\n  (** ** Inductive covering relation \n    \n     The elements of our freely generated structure\n     are formal countable unions of generators. Our task\n     is therefore define the appropriate frame structure\n     on them, starting with the order relation. Again,\n     we first restrict the relation to the case where\n     the left-hand side is a generator.\n\n     The following inductive definition is very well\n     motivated in the paper.\n     *)\n  Inductive covrel (a : T) : (nat -> T) -> Prop :=\n  | cr_refl : forall (U : nat -> T) n, U n = a -> covrel a U\n  | cr_inf : forall U : nat -> T, forall b : T, forall i:Idx b, a ≤ b -> (forall n, covrel (a ⊓ (CovAx b i n)) U) -> covrel a U\n  | cr_left : forall U : nat -> T, forall b : T, a ≤ b -> covrel b U -> covrel a U.\n  (** We note [a ◁ U] when the generator [a] is \n      lower than the formal union [U] *)\n  Infix \"◁\" := (covrel) (at level 60).\n\n  Lemma cr_n : forall U n, U n ◁ U.\n  Proof. intros. apply cr_refl with (n := n). reflexivity. Qed.\n\n  (** The covering relation ◁ respects the equality\n      on the generators. *)\n  Lemma covrel_Teq : forall x U, x ◁ U -> forall y, x = y -> y ◁ U.\n  Proof.\n    intros.\n    destruct H0.\n    apply cr_left with (b := x) ; assumption.\n  Qed.\n    \n  Lemma covrel_proper : Proper ((=) ==> eq ==> iff) covrel.\n  Proof.\n    unfold Proper, respectful.\n    intros.\n    split ; intro.\n    \n    rewrite <- H0.\n    apply (covrel_Teq x x0 H1 y H).\n\n    rewrite H0.\n    apply (covrel_Teq y y0 H1 x).\n    symmetry. apply H.\n  Qed.\n  Add Parametric Morphism : covrel with signature ((=) ==> eq ==> iff) as covrel_morphism.\n  Proof.\n    intros. apply covrel_proper. apply H. reflexivity.\n  Qed.\n  \n \n  (** ** Preorder and equivalence between coverings\n      The [◁] relation can now be used to define\n      the order relation on terms.\n   *)\n  \n  Definition Covrel (U : nat -> T) (V : nat -> T) :=\n    forall n : nat, (U n) ◁ V.\n  Instance Covrel_le : Le (nat -> T) := Covrel.\n  Ltac unfold_Covrel := unfold le, Covrel_le, Covrel.\n\n  (** Transitivity is admissible, by induction\n      on [a ◁ U]. *)\n  Lemma cr_trans : forall a U W, a ◁ U -> U ≤ W -> a ◁ W.\n  Proof.\n    intros a U W CR.\n    generalize W ; clear W.\n    induction CR ; intros.\n\n    - (* cr_left *)\n      unfold Covrel in H0.\n      rewrite <- H. apply (H0 n).\n\n    - (* cr_inf *)\n      assert (forall n, (a ⊓ (CovAx b i n)) ◁ W).\n      intro n ; apply (H1 n). apply H2.\n      apply (cr_inf a W b i H H3).\n    \n    - (* cr_left *)\n      apply cr_left with (b := b).\n      apply H.\n      apply IHCR ; apply H0.\n  Qed.\n\n  (** We can now show that [≤] is a preorder *)\n  Lemma Covrel_refl : Reflexive Covrel.\n  Proof.\n    unfold Reflexive.\n    intros.\n    unfold Covrel.\n    intro. apply cr_refl with (n:=n).\n    reflexivity.\n  Qed.\n    \n  Lemma Covrel_trans : Transitive Covrel.\n  Proof.\n    unfold Transitive.\n    intros.\n    unfold Covrel; intro.\n    apply cr_trans with (U := y).\n    apply (H n). apply H0.\n  Qed.\n\n  Definition PO_for_FFrame : @Preorder (nat -> T) Covrel :=\n    MkPreorder\n      (nat -> T)\n      Covrel\n      Covrel_refl\n      Covrel_trans.\n  Existing Instance PO_for_FFrame.\n\n  (** This defines an equivalence relation [=]\n      on the terms: [a = b <-> a ≤ b /\\ b ≤ a].\n\n      The [◁] relation respects the equality\n      on the generators (left hand side) and\n      our new equality on terms (right hand side).\n   *)\n  \n  Add Morphism covrel : covrel_morphism2.\n  Proof.\n    intros x y Heq U W H.\n    destruct H as [Hl Hr].\n    split ; intro.\n    apply cr_left with (b := x).\n    rewrite Heq ; apply le_refl.\n    apply cr_trans with (U := U) ; auto.\n\n    apply cr_left with (b := y).\n    rewrite Heq ; apply le_refl.\n    apply cr_trans with (U := W) ; auto.\n  Qed.\n  \n  (** One simple case where [U ≤ W] is when\n      [U] is contained in [W].\n       *)\n  Definition cov_inj (U W : nat -> T) :=\n    forall n, exists m, U n = W m.\n\n  Lemma cov_inj_Covrel : forall U W, cov_inj U W -> U ≤ W.\n  Proof.\n    intros.\n    unfold Covrel ; intro.\n    unfold cov_inj in H.\n    destruct (H n) as [m Heq].\n    apply cr_refl with (n:=m).\n    symmetry. exact Heq.\n  Qed.\n\n  Ltac by_cov_inj :=\n    try (apply cov_inj_Covrel) ;\n    unfold cov_inj ;\n    intro.\n\n  (** If the terms contain the same generators, they are\n      equal. *)\n  Lemma covbij_coveq : forall U W : (nat -> T), (forall n, U n = W n) -> U = W.\n  Proof.\n    intros.\n    split ; by_cov_inj ; exists n.\n    apply H.\n    symmetry. apply H.\n  Qed.\n\n  (** A useful shortcut for later: *)\n  Lemma cr_right : forall a U W, a ◁ U -> cov_inj U W -> a ◁ W.\n  Proof.\n    intros.\n    apply cr_trans with (U := U).\n    apply H.\n    apply cov_inj_Covrel.\n    apply H0.\n  Qed.\n\n  (** ** Binary meet\n    We first show the admissibility of the localization rule,\n    which relates [◁] to the meet on the generators.\n    *)\n      \n  Definition down (a : T) (U : nat -> T) : nat -> T :=\n    fun n => a ⊓ (U n).\n\n  Infix \"↓\" := down (at level 50).\n  \n  Proposition cr_loc : forall a b U, a ◁ U -> b ⊓ a ◁ b ↓ U.\n  Proof.\n    intros a b U HR.\n    induction HR as [a | a | a].\n\n    - (* cr_refl *)\n      apply cr_refl with (n := n).\n      unfold down ; simpl.\n      rewrite H ; reflexivity.\n\n    - (* cr_inf *)\n      apply cr_inf with (b := b0) (i := i).\n      apply le_trans with (y := a).\n      apply meet_r. assumption.\n      intro n.\n      rewrite <- meet_assoc.\n      apply (H1 n).\n\n    - (* cr_left *)\n      apply cr_left with (b := b ⊓ b0).\n      apply meet_le_r ; assumption.\n      apply IHHR.    \n  Qed.\n\n  (** We can now define the meet on terms:\n      the set of meets of pairs of elements of\n      the two terms.\n    *)\n  \n  Definition CMeet (U : nat -> T) (W : nat -> T) : nat -> T :=\n    fun n => (U (bijNN1 n)) ⊓ (W (bijNN2 n)).\n\n  Instance CMeet_meet : Meet (nat -> T) | 50 := CMeet.\n\n  Ltac simpl_bijNN :=\n    try (rewrite bijNN1_eq) ; try (rewrite bijNN2_eq) ; simpl.\n  Ltac Meet_refl a b :=\n    apply cr_refl with (n := bijNN (a,b)) ;\n    try (unfold Meet) ;\n    simpl_bijNN.\n\n  Lemma CMeet_cov_inj_comm : forall U W : nat -> T, cov_inj (U ⊓ W) (W ⊓ U).\n  Proof.\n    intros.\n    unfold cov_inj.\n    intro.\n    exists (bijNN (bijNN2 n,bijNN1 n)).\n    unfold meet, CMeet_meet, CMeet.\n    simpl_bijNN.\n    rewrite meet_comm. reflexivity.\n  Qed.\n  \n  Lemma CMeet_comm : forall U W : nat -> T, U ⊓ W = W ⊓ U.\n  Proof.\n    intros.\n    split ; apply cov_inj_Covrel ; apply CMeet_cov_inj_comm.\n  Qed.\n  \n  Lemma CMeet_covrel_comm : forall a U W, a ◁ U ⊓ W -> a ◁ W ⊓ U.\n  Proof.\n    intros.\n    apply cr_right with (U := U ⊓ W).\n    apply H.\n    apply CMeet_cov_inj_comm.\n  Qed.\n  \n  (* Admissibility of the meet rule *)\n  Proposition cr_meet : forall a U W, a ◁ U -> a ◁ W -> a ◁ U ⊓ W.\n  Proof.\n    intros a U W TU TW.\n\n    assert (a ⊓ a ◁ a ↓ U).\n    apply (cr_loc a a U TU).\n    rewrite meet_idem in H.\n\n    apply cr_trans with (U := a ↓ U).\n    apply H.\n    \n    (* Covrel *)\n    unfold Covrel. intros p.\n    unfold down.\n    apply cr_right with (U := (U p) ↓ W).\n    rewrite meet_comm. apply cr_loc. apply TW.\n    (* cov_inj *)\n    by_cov_inj.\n    exists (bijNN (p,n)).\n    unfold meet, CMeet_meet, CMeet. simpl_bijNN.\n    unfold down. reflexivity.\n  Qed.\n\n  Proposition Meet_univ : forall U W Z : nat -> T,\n                            Z ≤ U -> Z ≤ W -> Z ≤ U ⊓ W.\n  Proof.\n    unfold_Covrel.\n    intros.\n    apply cr_meet.\n    apply (H n).\n    apply (H0 n).\n  Qed.\n\n  Proposition CMeet_l : forall U W, U ⊓ W ≤ U.\n  Proof.\n    unfold_Covrel.\n    intros.\n    unfold Meet.\n    apply cr_left with (b := U (bijNN1 n)).\n    apply meet_l.\n    apply cr_refl with (n := bijNN1 n).\n    reflexivity.\n  Qed.\n\n  Proposition CMeet_r : forall U W, U ⊓ W ≤ W.\n  Proof.\n    intros.\n    rewrite CMeet_comm.\n    apply CMeet_l.\n  Qed.\n\n  (* ** Countable join\n     We name it [Vc] because [V] looks like a big\n     join and [c] means countable. *)\n\n  Definition Vc (U : nat -> nat -> T) :=\n    fun n => U (bijNN1 n) (bijNN2 n).\n\n  Lemma V_le : forall U n, U n ≤ Vc U.\n  Proof.\n    intros.\n    by_cov_inj.\n    exists (bijNN (n,n0)).\n    unfold Vc.\n    rewrite bijNN1_eq, bijNN2_eq.\n    reflexivity.\n  Qed.\n\n  Lemma V_univ : forall U v, (forall n, U n ≤ v) -> Vc U ≤ v.\n  Proof.\n    intros.\n    unfold Vc, Covrel.\n    intro.\n    eapply cr_trans.\n    eapply cr_refl. reflexivity.\n    eapply H.\n  Qed.\n\n  (** ** Distributivity of meets over joins *)\n\n  Lemma Cdistr_l : forall a U, a ⊓ (Vc U) ≤ Vc (fun n => a ⊓ (U n)).\n  Proof.\n    intros.\n    unfold meet, CMeet_meet, CMeet, Covrel. intro.\n    apply cr_trans with (U := (a (bijNN1 n) ↓ (Vc U))).\n    apply cr_loc. eapply cr_refl. reflexivity.\n    by_cov_inj.\n    exists (bijNN (bijNN1 n0, bijNN (bijNN1 n, bijNN2 n0))).\n    unfold Vc, down.\n    repeat (rewrite bijNN1_eq, bijNN2_eq ; simpl).\n    reflexivity.\n  Qed.\n\n  (** ** Top and bottom elements *)\n\n  Definition Bot : nat -> T := fun n => ⊥.\n  Instance BotNatT : Bottom (nat -> T) := Bot.\n\n  Lemma Bot_le : forall U, ⊥ ≤ U.\n  Proof.\n    intro.\n    unfold Covrel.\n    intro.\n    apply cr_left with (b := U O).\n    unfold Bot. apply bot_le.\n    eapply cr_refl.\n    reflexivity.\n  Qed.\n\n  Definition Tp : nat -> T := fun n => ⊤.\n  Instance TopNatT : Top (nat -> T) := Tp.\n  Lemma Top_le : forall U, U ≤ ⊤.\n  Proof.\n    intro.\n    unfold Covrel.\n    intro.\n    apply cr_left with (b := ⊤).\n    apply top_le.\n    apply cr_refl with (n := O).\n    reflexivity.\n  Qed.\n\n  Proposition Top_n : forall U n, (U n = ⊤) -> U = ⊤.\n  Proof.\n    intros.\n    split.\n    apply Top_le.\n    intro. apply cr_refl with (n := n).\n    unfold Top. assumption.\n  Qed.\n\n  (** This allows us to define our frame. *)\n\n  Definition MSL_for_FFrame : @MeetSemiLattice (nat -> T) Covrel :=\n    MkMSL\n      (nat -> T)\n      Covrel\n      PO_for_FFrame\n      Tp\n      Top_le\n      Bot\n      Bot_le\n      CMeet\n      CMeet_l\n      CMeet_r\n      Meet_univ.\n  Existing Instance MSL_for_FFrame.\n\n  Definition FFrame : @Frame (nat -> T) Covrel :=\n    MkFrame\n      (nat -> T)\n      Covrel\n      MSL_for_FFrame\n      Vc\n      V_le\n      V_univ\n      Cdistr_l.\n  Existing Instance FFrame.\n\n  Definition FFeq := @Feq (nat -> T) Covrel.\n  Definition FFeq_setoid := Feq_equivalence PO_for_FFrame.\n\n  (** * Properties of the free frame\n     \n      Here, we prove the universal property of the\n      frame we have constructed. (This part of the\n      proof is implicit in the paper.)\n\n      ** Injection of the generators\n      \n      The generators inject in the free frame via\n      a meet semilattice morphism.\n    *)\n\n  Definition inj_gen (t : T) : (nat -> T) := fun _ => t.\n\n  Instance inj_gen_mslmorph : MSLMorphism Tmsl MSL_for_FFrame inj_gen.\n  Proof.\n    apply MkMSLMorphism ; unfold inj_gen.\n    - apply MkPOMorphism.\n      intros.\n      unfold le, Covrel. intro.\n      apply cr_left with (b := y) ; try assumption.\n      apply cr_refl with (n := O) ; reflexivity.\n    - intros.\n      reflexivity.\n    - reflexivity.\n    - reflexivity.\n  Qed.\n    \n  Lemma V_inj_gen : forall u : nat -> T, V (fun n => inj_gen (u n)) = u.\n  Proof.\n    intro.\n    unfold inj_gen.\n    unfold V, FFrame, Vc.\n    split ; unfold le, Covrel_le, Covrel ; intro.\n    apply cr_n.\n    set (g := fun a => u (bijNN1 a)).\n    assert (u n = g (bijNN (n,O))).\n    unfold g.\n    rewrite bijNN1_eq. simpl. reflexivity.\n    rewrite H.\n    apply cr_n.\n  Qed.\n  \n  Lemma inj_gen_le : forall t u, inj_gen t ≤ u <-> t ◁ u.\n  Proof.\n    intros.\n    unfold inj_gen.\n    unfold le, Covrel_le, Covrel.\n    firstorder.\n    apply (H O).\n  Qed.\n\n  Lemma inj_gen_meet : forall t u, inj_gen t ⊓ u = (fun x => t ⊓ x) ∘ u.\n  Proof.\n    intros.\n    unfold inj_gen, compose, meet, msl_meet, MSL_for_FFrame, CMeet.\n    split ; by_cov_inj.\n    - exists (bijNN2 n). reflexivity.\n    - exists (bijNN (O,n)). simpl_bijNN. reflexivity.\n  Qed.\n\n  (** ** Facts on finite joins *)\n\n  Require Import SeqOfList.\n\n  Definition Vl (u : list T) := seq_of_list u.\n\n  Existing Instance msl_preorder.\n  Existing Instance Feq_equivalence.\n  Existing Instance MSL_for_FFrame.\n  Existing Instance CMeet_meet.\n  Existing Instance Covrel_le.\n  Ltac unfold_meet := unfold meet, msl_meet, MSL_for_FFrame, CMeet_meet, CMeet.\n\n  Lemma V_cons_increasing : forall x y u v, x ≤ y -> u ≤ v -> x ::: u ≤ y ::: v.\n  Proof.\n    intros.\n    unfold V_cons, le, Covrel_le, Covrel ; intros.\n    destruct n.\n    apply cr_left with (b := y). assumption.\n    apply cr_refl with (n := O) ; reflexivity.\n    apply cr_trans with (U := v).\n    apply (H0 n).\n    unfold le, Covrel_le, Covrel. intro.\n    apply cr_refl with (n := S n0) ; reflexivity.\n  Qed.\n  \n  Add Morphism V_cons with signature (Feq ==> (=) ==> (=)) as V_cons_morphism.\n  Proof.\n    intros.\n    destruct H, H0.\n    split.\n    apply V_cons_increasing ; assumption.\n    apply V_cons_increasing ; assumption.\n  Qed.\n\n  Ltac rewrite_as_pair n :=\n    assert (HbijNN : n ≡ bijNN (bijNNinv n)) by (rewrite bijNN_bijNNinv ;\n                                                 reflexivity) ;\n    rewrite HbijNN.\n\n  Lemma V_cons_inj_gen : forall a b u, inj_gen a ⊓ (b ::: u) =\n                                  (a ⊓ b) ::: (inj_gen a ⊓ u).\n  Proof.\n    intros.\n    split ; by_cov_inj.\n    - rewrite_as_pair n.\n      destruct (bijNNinv n).\n      unfold_meet.\n      simpl_bijNN.\n      destruct n1 ; unfold inj_gen ; simpl.\n      + exists O. reflexivity.\n      + exists (S (bijNN (O,n1))). simpl.\n      simpl_bijNN. reflexivity.\n    - destruct n ; unfold inj_gen ; simpl.\n      + exists (bijNN (O,O)).\n        unfold_meet. reflexivity.\n      + rewrite_as_pair n.\n        unfold_meet ; simpl_bijNN.\n        exists (bijNN (O,S (snd (bijNNinv n)))).\n        simpl_bijNN. reflexivity.\n  Qed.\n    \n  Lemma Vl_meet : forall x u, inj_gen x ⊓ Vl u = Vl (map (fun y => x ⊓ y) u).\n  Proof.\n    intros.\n    unfold inj_gen, Vl.\n    induction u ; simpl.\n    - assert ((fun _ => ⊥) = ⊥) by reflexivity.\n      apply covbij_coveq ; intro.\n      unfold_meet.\n      meetsemilattice.\n    - rewrite <- IHu.\n      apply V_cons_inj_gen.\n  Qed.\n  \n  Lemma Vl_Vf : forall u, Vl u = Vf FFrame (map inj_gen u).\n  Proof.\n    intros.\n    unfold Vl, Vf.\n    assert (V (seq_of_list (map inj_gen u)) = V (inj_gen ∘ (seq_of_list u)) ).\n    apply V_morphism.\n    apply seq_of_list_compose.\n    apply Feq_equivalence.\n    apply msl_preorder.\n    reflexivity.\n    rewrite H.\n    unfold compose.\n    symmetry.\n    apply V_inj_gen.\n  Qed.\n\n  (** ** Alternative representation of binary joins\n      As we have all countable joins, binary ones\n      come for free, but they are computed with\n      our bijection [nat * nat -> nat], which is a\n      bit dirty. Here is an alternative definition.\n   \n   *)\n\n  Existing Instance joinb_join.\n  Proposition join_NpN : forall u v, u ⊔ v = (fun n => match bijNpNinv n with\n                                        | inl a => u a\n                                        | inr b => v b\n                                               end).\n  Proof.\n    intros.\n    unfold join, joinb_join, joinb, Vf, V, FFrame, Vc, seq_of_list.\n    split.\n    - unfold le, Covrel_le, Covrel. intro.\n      destruct (bijNN1 n) ; simpl.\n      apply cr_refl with (n := bijNpN (inl (bijNN2 n))).\n      rewrite bijNpN_bij2. reflexivity.\n      destruct n0.\n      apply cr_refl with (n := bijNpN (inr (bijNN2 n))).\n      rewrite bijNpN_bij2. reflexivity.\n      simpl.\n      apply Bot_le.\n    - by_cov_inj.\n      destruct (bijNpNinv n).\n      exists (bijNN (O,n0)). simpl_bijNN. reflexivity.\n      exists (bijNN (S O,n0)). simpl_bijNN. reflexivity.\n  Qed.\n\n  (** ** Equalities generated by the axioms *)\n\n  Proposition CovAx_meet_gen :\n    forall (b:T), forall (i : Idx b), inj_gen b = (inj_gen b) ⊓ (CovAx b i).\n  Proof.\n    intros.\n    rewrite inj_gen_meet.\n    split.\n    - rewrite inj_gen_le.\n      apply cr_inf with (b := b) (i := i).\n      apply le_refl.\n      intros. unfold compose.\n      apply cr_refl with (n := n).\n      reflexivity.\n    - intro. unfold compose, inj_gen.\n      apply cr_left with (b := b).\n      apply meet_l.\n      apply cr_refl with (n := O).\n      reflexivity.\n  Qed.\n\n  Proposition CovAx_le_eq :\n    forall (b:T), forall (i : Idx b), (forall n, CovAx b i n ≤ b) -> inj_gen b = CovAx b i.\n  Proof.\n    intros.\n    split.\n    - rewrite CovAx_meet_gen with (i := i).\n      apply (@meet_r (nat -> T) Covrel_le MSL_for_FFrame).\n    - intro.\n      apply cr_left with (b := b).\n      apply H.\n      apply cr_refl with (n := O).\n      reflexivity.\n  Qed.\n\n  (** ** Universality\n\n     Let us assume that we have a meet semilattice\n     morphism to an arbitrary frame R. *)\n  Context {R : Type}.\n  Context {Rle : Le R}.\n  Variable RFrame : @Frame R Rle.\n\n  Definition Rmsl := @frame_msl R Rle RFrame.\n  Definition Rpo := @msl_preorder R Rle Rmsl.\n  Variable f : T -> R.\n  Variable mslmorph : MSLMorphism Tmsl Rmsl f.\n  Existing Instance mslmorph.\n\n  (** We assume that the morphism respects the axioms\n      we have used to generate our free frame. *)\n  Definition respects_axioms : Prop :=\n    forall t : T, forall i : Idx t, f t ≤ V (f ∘ (CovAx t i)).\n  Variable resp_ax : respects_axioms.\n\n  (** We define a function from our free frame to R. *)\n  Definition fframe_ext (x : nat -> T) : R :=\n    V (f ∘ x).\n\n  (** We show that this function is a frame morphism. *)\n  Existing Instance Covrel_le.\n  \n  Lemma f_covrel : forall a U, a ◁ U -> f a ≤ V (f ∘ U).\n  Proof.\n    intros.\n    induction H.\n    - rewrite <- H.\n      assert (f (U n) = (f ∘ U) n) by reflexivity.\n      rewrite H0 ; apply v_le.\n    - unfold respects_axioms in resp_ax.\n      specialize (resp_ax b i).\n      set (K := (V (fun n => f (a ⊓ CovAx b i n)))).\n      apply le_trans with (y := K).\n      + assert (K = f a ⊓ V (f ∘ CovAx b i)).\n        * rewrite cdistr.\n          apply V_morphism ; intro.\n          unfold compose.\n          rewrite mslmorph_meet.\n          reflexivity.\n          apply mslmorph.\n        * rewrite H2.\n          apply le_trans with (y := f a ⊓ f b).\n          assert (f a ≤ f b) by (apply (pomorph_le a b H)).\n          assert (f a ⊓ f b = f a) by (apply order_meet ; assumption).\n          rewrite H4.\n          apply le_refl.\n          apply meet_le.\n          apply le_refl.\n          assumption.\n      + unfold K.\n        apply v_univ.\n        assumption.\n    - apply le_trans with (y := f b).\n      assert (f a ≤ f b) by (apply (pomorph_le a b H)).\n      assumption. assumption.\n  Qed.\n\n  Instance fframe_mor : FMorphism FFrame RFrame fframe_ext.\n  Proof.\n    unfold fframe_ext.\n    apply MkFMorphism.\n    \n    - apply MkMSLMorphism.\n      + apply MkPOMorphism.\n        intros.\n        apply v_univ ; intro.\n        unfold compose.\n        unfold le, Covrel in H.\n        specialize (H n).\n        apply f_covrel ; assumption.\n      + intros.\n        unfold meet, msl_meet, FFrame. simpl.\n        unfold CMeet, compose.\n        assert (forall n, f (x (bijNN1 n) ⊓ y (bijNN2 n)) = f (x (bijNN1 n)) ⊓ f (y (bijNN2 n))).\n        intro.\n        apply (@mslmorph_meet T R Tle Rle Tmsl Rmsl f mslmorph).\n        setoid_rewrite H.\n        symmetry.\n        apply V_meet.\n\n      + unfold compose.\n        unfold bottom, msl_bot, FFrame, Bot. simpl.\n        assert (pointwise_relation nat Feq (fun _ => f ⊥) (fun _ => ⊥)).\n        unfold pointwise_relation ; intro.\n        apply mslmorph_bot. assumption.\n        rewrite H.\n        apply V_bot.\n\n      + unfold compose.\n        unfold top, msl_top, FFrame. simpl.\n        rewrite V_top. reflexivity.\n        exists O. unfold Top. apply mslmorph_top.\n        apply mslmorph.\n\n    - intro.\n      unfold compose.\n      rewrite <- V_pair.\n      apply V_morphism ; intro.\n      unfold V, FFrame, Vc, bijNN1, bijNN2.\n      reflexivity.\n  Qed.\n  \n  Definition fframe_mslmorph := fmorph_mslmorph FFrame RFrame fframe_ext.\n  Proposition fframe_factoring : fframe_ext ∘ inj_gen = f.\n  Proof.\n    unfold equiv, ext_equiv, respectful.\n    intros.\n    unfold inj_gen, fframe_ext, compose.\n    rewrite <- H.\n    apply V_const.\n  Qed.\n\n  Arguments fframe_factoring : default implicits.\n\n  (** Now the uniqueness part of the universality:\n     if we have another such frame morphism,\n     then it is equal to fframe_ext. *)\n\n  Variable other_fact : (nat -> T) -> R.\n  Variable other_morph : FMorphism FFrame RFrame other_fact.\n  Existing Instance other_morph.\n  Instance other_mslmorph : MSLMorphism MSL_for_FFrame Rmsl other_fact := fmorph_mslmorph FFrame RFrame other_fact.\n  Instance other_morph_po : POMorphism other_fact.\n  Proof.\n    apply (mslmorph_pomorph MSL_for_FFrame Rmsl).\n  Qed.    \n    \n  Variable other_commutes : other_fact ∘ inj_gen = f.\n\n  Existing Instance Covrel_le.\n  Instance coveq_R : Equiv (nat -> R) := @ext_equiv nat (≡) R (=).\n  \n  Proposition other_fact_equal : forall u, other_fact u = fframe_ext u.\n  Proof.\n    intro.\n    assert (other_fact u = other_fact (V (fun n => inj_gen (u n)))).\n    rewrite V_inj_gen ; reflexivity.\n    rewrite H.\n    rewrite morph_V.\n    unfold fframe_ext, compose.\n    apply V_morphism.\n    intro.\n    unfold equiv, ext_equiv, respectful in other_commutes.\n    apply other_commutes ; reflexivity.\n    assumption.\n  Qed.\n\n  (** This shows the correctness of our construction. *)\n\nEnd Free_Frame.", "meta": {"author": "wetneb", "repo": "sigmalocales", "sha": "a42975000c9e505103e4321f7413af992fea5e0c", "save_path": "github-repos/coq/wetneb-sigmalocales", "path": "github-repos/coq/wetneb-sigmalocales/sigmalocales-a42975000c9e505103e4321f7413af992fea5e0c/FreeFrame.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6951267853365539}}
{"text": "(*Javier Enriquez Mendoza\nSemanal 6\nSemántica y Verificación*)\n\nVariable A:Type.\n\nInductive btree:Type :=\n  | empty : btree\n  | nodo : A -> btree -> btree -> btree.\n\nFixpoint inTree (a:A) (t:btree) : Prop :=\n  match t with \n    | empty => False\n    | nodo y l r => (eq y a) \\/ (inTree a l) \\/ (inTree a r)\n  end.\n\nFixpoint isEmpty (t:btree): bool :=\n  match t with \n    | empty => true\n    | nodo _ _ _ => false\n  end.\n\nLemma true_is_empty: forall (t:btree), ((isEmpty t) = true) -> (t = empty).\nProof.\n  intros.\n  destruct t.\n  trivial.\n  simpl in H.\n  inversion H.\nQed.\n\nTheorem cuatro : forall (t:btree), ((isEmpty t) = true) <-> (forall (x:A), ~(inTree x t)).\nProof.\n  intros.\n  split.\n  (*->*)\n  intros.\n  unfold not.\n  intros.\n  assert (t = empty).\n  apply true_is_empty.\n  trivial.\n  rewrite H1 in H0.\n  simpl in H0.\n  trivial.\n  (*<-*)\n  intros.\n  destruct t.\n  reflexivity.\n  simpl inTree in H.\n  edestruct H.\n  intuition. (*Como mi variable ?x esta libre en la meta es equivalente al forall de la \npremisa H por lo tanto lo que quiero probar es falso, Pero no supe como poner eso correctamente \nasi que mejor use intuition, pero entiendo que es lo que esta haciendo y por que asi que podria \ndecir que lo use correctamente jeje *) \nQed.\n", "meta": {"author": "jaeem006", "repo": "Semantica", "sha": "fdfdf544dd2d30b2f03a82849d78879762d48811", "save_path": "github-repos/coq/jaeem006-Semantica", "path": "github-repos/coq/jaeem006-Semantica/Semantica-fdfdf544dd2d30b2f03a82849d78879762d48811/Javier_Enriquez_ejs6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.7905303285397348, "lm_q1q2_score": 0.6949921879602703}}
{"text": "(**\n{0, 1}* のうち0の出現数が1の出現数の丁度2倍であるような列だけを集めた集合は、\nS = SS | 00S1 | 1S00 | 0S1S0 | ε というCFGで書き表せることを証明せよ。\n\nhttps://twitter.com/pi8027/status/476708668239384576\n\nこのCFDで生成される文字列の 0の数は 1の数の2倍であることを示す。\n（これで、問題の趣旨に合っている？）\n*)\n\nRequire Import ssreflect ssrnat ssrbool eqtype seq.\n\nInductive S : Set :=\n| ss of S & S\n| oosi of S\n| isoo of S\n| osiso of S\n| ε.\n\nFixpoint icount (l : S) : nat :=\n  match l with\n    | ss m n => (icount m) + (icount n)\n    | oosi m => (icount m).+1\n    | isoo m => (icount m).+1\n    | osiso m => (icount m).+1\n    | ε => 0\n  end.\n\nFixpoint ocount (l : S) : nat :=\n  match l with\n    | ss m n => (ocount m) + (ocount n)\n    | oosi m => (ocount m).+2\n    | isoo m => (ocount m).+2\n    | osiso m => (ocount m).+2\n    | ε => 0\n  end.\n\nGoal forall l : S, (icount l).*2 = ocount l.\nProof.\n  elim;\n  first                                     (* SS *)\n    (move=> l H l' H'; by rewrite /= doubleD H H');\n  last                                      (* ε *)\n    by [];\n  (move=> l H /=; by rewrite doubleS H).\nQed.\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/ssr/ssr_ooiseq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.6949921757783297}}
{"text": "Require Import set.\nRequire Import equal.\n\nInductive belong : set -> set -> Prop :=\n|   Belong  : forall (a:Type) (f:a -> set) (x:a), belong (f x) (mkset a f)\n|   BelongR : forall (x x' y:set), x == x' -> belong x' y -> belong x y\n.\n\n\nLemma BelongL: forall (x y' y:set), belong x y' -> y' == y -> belong x y'.\nProof.\n    intros x y' y H E. induction H. \n    - constructor.\n    - apply BelongR with x'.\n        + assumption.\n        + apply IHbelong. assumption.\nQed.\n\nNotation \"x % y\" := (belong x y) (at level 0, no associativity).\n\n(*\nLemma belong_crit : forall (x:set) (a:Type) (f:a -> set),\n    x % (mkset a f) -> exists (z:a), x = f z.\nProof.\n    intros x a f H. remember (mkset a f) as y eqn:E.\n    revert E. revert f. revert a. destruct H.\n    - intros b g H. inversion H. subst. exists x. reflexivity.\n    -\n\nShow.\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/hott/belong.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6949886488280389}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (lf1 : natural) (lf2 : natural)\n  : natural := plus Zero (plus lf2 z).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj125_coqofml_72WrcW.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6949886442769662}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Coq_Cats.Type_Cat.Type_Cat.\n\nSection Arrow.\n  Local Open Scope morphism_scope.\n  \n  (** The type accomodating all arrows of a category C. *)\n  Record Arrow (C : Category) :=\n    {\n      Orig : Obj;\n      Targ : Obj;\n      Arr : Orig –≻ Targ\n    }.\n\n  Arguments Orig {_} _ : clear implicits.\n  Arguments Targ {_} _ : clear implicits.\n  Arguments Arr {_} _ : clear implicits.\n\n  Coercion Arr : Arrow >-> Hom.\n  \n  (** An arrow (in the appropriate category, e.g., comma)\n    from arrow f : a -> b to arrow g : c -> d is a pair of arrows h1 : a -> c\n    and h2 : b -> d that makes the following diagram commute:\n#\n<pre>\n          f\n   a ———————————> b\n   |              |\nh1 |              | h2\n   |              |\n   ↓              ↓\n   c ———————————> d\n          g\n</pre>\n#\n *)\n  Record Arrow_Hom {C : Category} (a b : Arrow C) :=\n    {\n      Arr_H : (Orig a) –≻ (Orig b);\n      Arr_H' : (Targ a) –≻ (Targ b);\n      Arr_Hom_com : Arr_H' ∘ (Arr a) = (Arr b) ∘ Arr_H\n    }.\n  Arguments Arr_H {_ _ _} _ : clear implicits.\n  Arguments Arr_H' {_ _ _} _ : clear implicits.\n  Arguments Arr_Hom_com {_ _ _} _ : clear implicits.\n\n  Context (C : Category).\n\n  Section Arrow_Hom_eq_simplify.\n    Context {a b : Arrow C} (f g : Arrow_Hom a b).\n    \n    (** Two arrow homomorphisms are equal if the arrows between theor domains\n        and codomain are respectively equal. In other words, we don't care about\n        the proof of the diagram commuting. *)\n    Lemma Arrow_Hom_eq_simplify : Arr_H f = Arr_H g → Arr_H' f = Arr_H' g → f = g.\n    Proof.\n      destruct f; destruct g.\n      basic_simpl.\n      ElimEq.\n      PIR.\n      reflexivity.\n    Qed.\n\n  End Arrow_Hom_eq_simplify.\n\n  Section Compose_id.\n    Context {x y z} (h : Arrow_Hom x y) (h' : Arrow_Hom y z).\n\n    (** Composition of arrow homomorphisms. We basicall need to show that in the\n        following diagram, the bigger diagram commutes if the smaller ones do.\n#\n<pre>\n           f\n    a ———————————> b\n    |              |\n h1 |              | h2\n    |              |\n    ↓              ↓\n    c ———————————> d\n    |      g       |\nh1' |              | h2'\n    |              |\n    ↓              ↓\n    c ———————————> d\n           h\n</pre>\n#\n*)\n    Program Definition Arrow_Hom_compose : Arrow_Hom x z :=\n      {|\n        Arr_H := (Arr_H h') ∘ (Arr_H h);\n        Arr_H' := (Arr_H' h') ∘ (Arr_H' h)\n      |}.\n\n    Next Obligation. (* Arr_Hom_com *)\n    Proof.\n      destruct h as [hh hh' hc]; destruct h' as [h'h h'h' h'c]; cbn.\n      rewrite assoc.\n      rewrite hc.\n      repeat rewrite assoc_sym.\n      rewrite h'c.\n      auto.\n    Qed.\n\n    (** The identity arrow morphism. We simply need to show that the following\n        diagram commutes:\n#\n<pre>\n          f\n   a ———————————> b\n   |              |\nid |              | id\n   |              |\n   ↓              ↓\n   a ———————————> b\n          f\n</pre>\n#\nwhich is trivial.\n *)\n    Program Definition Arrow_id : Arrow_Hom x x :=\n      {|\n        Arr_H := id;\n        Arr_H' := id\n      |}.\n\n  End Compose_id.\n\nEnd Arrow.\n\nHint Extern 1 (?A = ?B :> Arrow_Hom _ _) => apply Arrow_Hom_eq_simplify; simpl.\n\nArguments Orig {_} _ : clear implicits.\nArguments Targ {_} _ : clear implicits.\nArguments Arr {_} _ : clear implicits.\n\nArguments Arr_H {_ _ _} _ : clear implicits.\nArguments Arr_H' {_ _ _} _ : clear implicits.\nArguments Arr_Hom_com {_ _ _} _ : clear implicits.\n\n(** an arrow in a category is also an arrow in the opposite category. \n    The domain and codomain are simply swapped. *)\nProgram Definition Arrow_to_Arrow_OP (C : Category) (ar : Arrow C) :\n  Arrow (C ^op) :=\n  {|\n    Arr := ar\n  |}.\n\n(** The type of arrows of a category and the type of arrows of its opposite are\n     isomorphic. *)\nProgram Definition Arrow_OP_Iso (C : Category) :\n  ((Arrow C) ≃≃ (Arrow (C ^op)) ::> Type_Cat)%isomorphism :=\n  {|\n    iso_morphism := Arrow_to_Arrow_OP C;\n    inverse_morphism := Arrow_to_Arrow_OP (C ^op)\n  |}.", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/Categories/Ext_Cons/Arrow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.6949253200086032}}
{"text": "Require Import Coq.Lists.List.\n\nLemma Forall_map:\n  forall {a b} P (f : a -> b) xs,\n  Forall P (map f xs) <-> Forall (fun x => P (f x)) xs.\nProof.\n  intros.\n  induction xs; simpl.\n  * split; intro; constructor.\n  * split; intro H; inversion_clear H; constructor; try apply IHxs; assumption.\nQed.\n\nLemma Forall_cons_iff:\n  forall  {a} (P : a -> Prop) x xs,\n  Forall P (x :: xs) <-> P x /\\ Forall P xs.\nProof.\n  intros.\n  intuition; inversion H; intuition.\nQed.\n\n(* The termination checker does not like recursion through [Forall], but\n   through [map] is fine... oh well. *)\nDefinition Forall' {a} (P : a -> Prop) xs := Forall id (map P xs).\n\nLemma Forall'_Forall:\n  forall  {a} (P : a -> Prop) xs,\n  Forall' P xs <-> Forall P xs.\nProof.\n  intros.\n  unfold Forall'.\n  unfold id.\n  rewrite Forall_map.\n  reflexivity.\nQed.\n", "meta": {"author": "DavidFHCh", "repo": "Tesis-FTW", "sha": "f84ab8eb92f3984e973ce6a441262d9a8a62e9b0", "save_path": "github-repos/coq/DavidFHCh-Tesis-FTW", "path": "github-repos/coq/DavidFHCh-Tesis-FTW/Tesis-FTW-f84ab8eb92f3984e973ce6a441262d9a8a62e9b0/tesis/hs-to-coq/examples/ghc/theories/Forall.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.8031737892899221, "lm_q1q2_score": 0.694925316153346}}
{"text": "(* https://softwarefoundations.cis.upenn.edu/lf-current/Lists.html *)\n\nFrom LF Require Export B_Induction.\n\nModule NatList.\n\nInductive natprod : Type :=\n    | pair (n_1 n_2 : nat).\n\nCheck (pair 3 5) : natprod.\n\nDefinition first (p : natprod) : nat :=\n    match p with\n    | pair x y => x\n    end.\n\nDefinition second (p : natprod) : nat :=\n    match p with\n    | pair x y => y\n    end.\n\nCompute (first (pair 5 3)).\nCompute (second (pair 5 3)).\n\nNotation \"( x , y )\" := (pair x y).\n\nCompute (first (3, 5)).\nCompute (second (3, 5)).\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 = (first p, second p).\nProof.\n    intros p. destruct p as [n m].\n    simpl. reflexivity.\nQed.\n\nTheorem second_first_is_swap : forall (p : natprod),\n    (second p, first p) = swap_pair p.\nProof.\n    intros p. destruct p as [n m].\n    simpl. reflexivity.\nQed.\n\nTheorem first_swap_is_second : forall (p : natprod),\n    first (swap_pair p) = second p.\nProof.\n    intros p. destruct p as [n m].\n    simpl. reflexivity.\nQed.\n\nInductive natlist : Type :=\n    | empty\n    | cons (n : nat) (l : natlist).\n\nCheck (cons 1 (cons 2 (cons 3 empty))) : natlist.\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\n\nNotation \"[ ]\" := empty.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y empty) ..).\n\nFixpoint repeat (n count : nat) : natlist :=\n    match count with \n    | 0 => empty\n    | S count' => n :: (repeat n count')\n    end.\n\nCompute repeat 5 10.\n\nFixpoint length (l : natlist) : nat :=\n    match l with \n    | empty => 0\n    | cons n cdr => 1 + (length cdr)\n    end.\n\nCompute length (repeat 5 10).\nCompute length empty.\n\nFixpoint append (l_1 l_2 : natlist) : natlist :=\n    match l_1 with\n    | empty => l_2\n    | h :: t => h :: (append t l_2)\n    end.\n\nCompute append [1;2;3] [4;5;6].\nCompute append [1;2;3] empty.\n\nNotation \"x ++ y\" := (append 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: empty ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ empty = [1;2;3].\nProof. reflexivity. Qed.\n\nDefinition car (default : nat) (l : natlist) : nat :=\n    match l with\n    | empty => default\n    | h :: t => h\n    end.\n\nDefinition cdr (l : natlist) : natlist :=\n    match l with\n    | empty => empty\n    | h :: t => t\n    end.\n\nExample test_hd1: car 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: car 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: cdr [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\nFixpoint nonzeros (l:natlist) : natlist :=\n    match l with\n    | empty => empty\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    | empty => empty\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 [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\nDefinition countoddmembers (l:natlist) : nat :=\n    length (oddmembers l).\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers3: countoddmembers empty = 0.\nProof. reflexivity. Qed.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n    match l1 with\n    | empty => l2\n    | h1 :: t1 => match l2 with \n        | empty => l1\n        | h2 :: t2 => h1 :: h2 :: (alternate t1 t2)\n        end\n    end.\n\nExample test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. reflexivity. Qed.\nExample test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\nExample test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].\nProof. reflexivity. Qed.\nExample test_alternate4: alternate [] [20;30] = [20;30].\nProof. reflexivity. Qed.\n\nDefinition bag := natlist.\n\nFixpoint count (v : nat) (s : bag) : nat :=\n    match s with \n    | empty => 0\n    | h :: t => (count v t) + match (v =? h) with\n        | true => 1\n        | false => 0\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    append.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v : nat) (s : bag) : bag :=\n    v :: s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nDefinition member (v : nat) (s : bag) : bool :=\n    match (count v s) with \n    | 0 => false\n    | _ => true\n    end.\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\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    | empty => empty\n    | h :: t => match (h =? v) with \n        | true => t\n        | false => h :: remove_one v t\n        end\n    end.\n\nExample test_remove_one1: 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    | empty => empty\n    | h :: t => match (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 included (s1 : bag) (s2 : bag) : bool :=\n    match s1 with\n    | empty => true\n    | h :: t => match (member h s2) with\n        | true => included t (remove_one h s2)\n        | false => false\n        end\n    end.\n\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\nLemma beq_nat_refl : forall n, \n    true = (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'. reflexivity.\nQed.\n\nTheorem add_inc_count : forall v : nat, forall s : bag,\n    count v (add v s) = 1 + (count v s).\nProof.\n    intros v s. simpl.\n    rewrite <- beq_nat_refl.\n    rewrite -> add_comm. 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 (cdr 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 l' IHl' ].\n    - (* l1 = empty *)\n        simpl. reflexivity.\n    - (* l1 = cons n l1' *)\n        simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nFixpoint rev (l:natlist) : natlist :=\n    match l with\n    | empty => empty\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 empty = empty.\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 : forall l : natlist,\n    length (rev l) = length l.\nProof.\n    intros l. induction l as [| n l' IHl' ].\n    - (* l = empty *)\n        simpl. reflexivity.\n    - (* l = cons n l' *)\n        simpl.\n        rewrite -> app_length, IHl', add_comm.\n        simpl. reflexivity.\nQed.\n\nTheorem app_nil_r : forall l : natlist,\n    l ++ [] = l.\nProof.\n    intros l. induction l as [| n l' IHl' ].\n    - (* l = empty *)\n        simpl. reflexivity.\n    - (* l = cons n l' *)\n        simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n    rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n    intros l1 l2. induction l1 as [| n1 l1' IHl1' ].\n    - (* l1 = empty *)\n        simpl. rewrite -> app_nil_r. reflexivity.\n    - (* l1 = cons n l1' *)\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 as [| n l' IHl' ].\n    - (* l = empty *)\n        simpl. reflexivity.\n    - (* l = cons n l' *)\n        simpl. rewrite -> rev_app_distr, IHl'.\n        simpl. reflexivity.\nQed.\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n    l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n    intros l1 l2 l3 l4.\n    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. induction l1 as [| n1 l1' IHl1' ].\n    - (* l1 = empty *)\n        simpl. reflexivity.\n    - (* l1 = cons n1 l1' *)\n        induction n1 as [| n1' IHn1' ].\n        -- (* n1 = 0 *)\n            simpl. rewrite -> IHl1'. reflexivity.\n        -- (* n1 = S n' *)\n            simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n    match l1 with\n    | empty => match l2 with \n        | empty => true\n        | _ => false\n        end\n    | h1 :: t1 => match l2 with\n        | empty => false\n        | h2 :: t2 => andb (eqb h1 h2) (eqblist t1 t2)\n        end\n    end.\n\nExample test_eqblist1 : (eqblist empty empty = true).\nProof. reflexivity. Qed.\nExample test_eqblist2 : eqblist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\nExample test_eqblist3 : eqblist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem eqblist_refl : forall l:natlist,\n    true = eqblist l l.\nProof.\n    intros l. induction l as [| n l' IHl' ].\n    - (* l = empty *)\n        simpl. reflexivity.\n    - (* l = cons n l' *)\n        simpl. rewrite -> eqb_refl. rewrite <- IHl'.\n        simpl. reflexivity.\nQed.\n\nTheorem count_member_nonzero : forall (s : bag),\n    1 <=? (count 1 (1 :: s)) = true.\nProof.\n    intros s. rewrite -> add_inc_count. \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    - (* n = 0 *)\n        simpl. reflexivity.\n    - (* n = S n' *)\n        simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem remove_does_not_increase_count: forall (s : bag),\n    (count 0 (remove_one 0 s)) <=? (count 0 s) = true.\nProof.\n    intros s. induction s as [| n s' IHs' ].\n    - (* s = empty *)\n        simpl. reflexivity.\n    - (* s = cons n s' *)\n        induction n as [| n' IHn' ].\n        -- (* n = 0 *)\n            simpl. rewrite -> add_comm. rewrite -> leb_n_Sn. reflexivity.\n        -- (* n = S n' *)\n            simpl. rewrite -> add_0_r, add_0_r, IHs'. reflexivity.\nQed.\n\nTheorem bag_count_sum  : forall (s1 s2 : bag) (v : nat),\n    count v (sum s1 s2) = (count v s1) + (count v s2).\nProof.\n    intros s1 s2 v. induction s1 as [| n1 s1' IHs1' ].\n    - (* s1 = empty *)\n        simpl. reflexivity.\n    - (* s1 = cons n s1' *)\n        simpl. destruct (v =? n1).\n        -- rewrite -> add_comm. assert (count v s1' + 1 = 1 + count v s1') as H.\n            {\n                rewrite -> add_comm. reflexivity.\n            }\n            rewrite -> H. rewrite -> IHs1'. rewrite -> add_assoc. reflexivity.\n        -- rewrite -> add_0_r, add_0_r. rewrite -> IHs1'. reflexivity.\nQed.\n\nTheorem involution_injective : forall (f : nat -> nat),\n    (forall n : nat, n = f (f n)) -> (forall n1 n2 : nat, f n1 = f n2 -> n1 = n2).\nProof.\n    intros f n n1 n2 H. assert (n1 = f (f n1)) as Hn1.\n        {\n            rewrite <- n. reflexivity.\n        }\n    rewrite -> Hn1. \n    assert (n2 = f (f n2)) as Hn2.\n        {\n            rewrite <- n. reflexivity.\n        }\n    rewrite -> Hn2.\n    rewrite -> H. 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. reflexivity.\nQed.\n\nInductive natoption : Type :=\n    | Some (n : nat)\n    | None.\n\nFixpoint nth_error (l : natlist) (n : nat) : natoption :=\n    match l with\n    | empty => None\n    | h :: t => match n with \n        | O => Some h\n        | S n' => nth_error t n'\n        end\n    end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n    match o with\n    | Some n' => n'\n    | None => d\n    end.\n\nDefinition hd_error (l : natlist) : natoption :=\n    match l with \n    | empty => 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\nTheorem option_elim_hd : forall (l : natlist) (default : nat),\n    car default l = option_elim default (hd_error l).\nProof.\n    intros l default. induction l as [| h t ].\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 : id), \n    eqb_id x x = true.\nProof.\n    intros x. destruct x. simpl.\n    rewrite -> eqb_refl. reflexivity.\nQed.\n\nModule PartialMap.\nExport NatList.\n\nInductive partial_map : Type :=\n    | empty\n    | record (i : id) (v : nat) (m : partial_map).\n\nDefinition update (d : partial_map) (x : id) (value : nat) : partial_map :=\n    record x value d.\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n    match d with\n    | empty => None\n    | record y v d' => if eqb_id x y\n                       then Some v\n                       else find x d'\n    end.\n\nTheorem update_eq : forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n    intros d x v. destruct x. simpl.\n    rewrite -> eqb_refl. reflexivity.\nQed.\n\nTheorem update_neq : forall (d : partial_map) (x y : id) (o: nat),\n    eqb_id x y = false -> find x (update d y o) = find x d.\nProof.\n    intros d x y o H. simpl. rewrite -> H. reflexivity.\nQed.\n\nEnd PartialMap.\n\nInductive baz : Type :=\n    | Baz1 (x : baz)\n    | Baz2 (y : baz) (b : bool).\n\n(*\n    The baz type cannot have any\n    elements. Because both of its \n    constructors take in a baz instance,\n    it is impossible to use either to\n    construct a baz instance. \n*)\n", "meta": {"author": "CharlesAverill", "repo": "SoftwareFoundationsExercises", "sha": "577a0ee051c393abc17bb0a5167139cb38366df4", "save_path": "github-repos/coq/CharlesAverill-SoftwareFoundationsExercises", "path": "github-repos/coq/CharlesAverill-SoftwareFoundationsExercises/SoftwareFoundationsExercises-577a0ee051c393abc17bb0a5167139cb38366df4/C_Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.8652240877899776, "lm_q1q2_score": 0.6949253152897134}}
{"text": "(** *** Advanced exercise sheet for lecture 4: Tactics in Coq. *)\n\n(**\n    This is the material for the advisors with solutions.\n*)\n\n(** Some exercises about equivalences - recall from the course that associativity\n    for products of types is not available \"on the nose\", i.e., just with equality.\n\n    Exercises originally suggested by Benedikt Ahrens and Anders Mörtberg\n    (for UniMath school 2017) and elaborated by Ralph Matthes (CNRS, IRIT,\n    Univ. Toulouse, France)\n*)\nRequire Import UniMath.Foundations.PartA.\n\nLocate \"≃\". (** typed in as [\\simeq] *)\nPrint weq.\nPrint isweq.\nPrint hfiber.\n\nSection weqdef.\n\nParameters (X Y: UU).\nEval compute in (X ≃ Y).\n(** there is a function [f] so that for given image [y] one can find the preimage [x] uniquely,\n    but not only as element of [X] but even the pair consisting of the preimage and the proof\n    that it is the preimage is unique. *)\nEnd weqdef.\n\n(** Prove that the identity function is an equivalence *)\nLemma idisweq (X : UU) : isweq (idfun X).\nProof.\n  unfold isweq.\n  intro y.\n  unfold iscontr.\n  unfold hfiber.\n  use tpair.\n  - exists y.\n    apply idpath.\n  - cbn.\n    intro p.\n    induction p as [x H].\n    rewrite H.\n    apply idpath.\nDefined.\n\n(** Package this up as an equivalence *)\nDefinition idweq (X : UU) : X ≃ X.\nProof.\n  exists (idfun X).\n  apply idisweq.\nDefined.\n\n(** alternative proof with [isweq_iso] that is extremely useful *)\nLemma idisweq_alt (X : UU) : isweq (idfun X).\nProof.\n  use isweq_iso.\n  - exact (fun x => x).\n  - cbn. intros x. apply idpath.\n  - cbn. intros x. apply idpath.\nDefined.\n\n(** Prove that any map to empty is an equivalence *)\nLemma isweqtoempty {X : UU} (f : X -> ∅) : isweq f.\nProof.\n  unfold isweq.\n  intro y.\n  induction y.\nDefined.\n\n(** Package this up as an equivalence *)\nDefinition weqtoempty {X : UU} (f : X -> ∅) : X ≃ ∅.\nProof.\n  use tpair.\n  - exact f.\n  - cbn. apply isweqtoempty.\nDefined.\n\n\n(** Prove that the composition of equivalences is an equivalence.\n\nThis is rather difficult to do directly from the definition. Important lemmas\nto reason on equality of pairs in a sigma type are given by [base_paths] and\n[fiber_paths] that are elimination rules (that use given equality of pairs)\nand [total2_paths2_f] that is an introduction rule allowing to establish an\nequation between pairs. There, transport arises, but transport along the\nidentity path is always the identity, and this already computationally, which\nmeans that [cbn] gets rid of it. *)\nTheorem compisweq {X Y Z : UU} (f : X -> Y) (g : Y -> Z)\n        (isf : isweq f) (isg : isweq g) : isweq (g ∘ f).\nProof.\n  unfold isweq.\n  intro z.\n  unfold iscontr.\n  unfold hfiber.\n  set (isginst := isg z).\n  induction isginst as [cntrg Hg].\n  induction cntrg as [y yeq].\n  induction yeq. (** do this as early as possible *)\n  set (isfinst := isf y).\n  induction isfinst as [cntrf Hf].\n  induction cntrf as [x xeq].\n  induction xeq. (** again an early induction on an equation *)\n  use tpair.\n  - exists x.\n    apply idpath. (** thanks to the induction on equations, this is trivial *)\n  - cbn.\n    intro p.\n    induction p as [x' Hx'].\n    set (hfg := (f x',, Hx'): hfiber g (g (f x))).\n    set (Hginst := Hg hfg).\n    set (x'eq := base_paths _ _ Hginst).\n    cbn in x'eq.\n    set (hff := (x',,x'eq): hfiber f (f x)).\n    set (Hfinst := Hf hff).\n    set (x'eq' := base_paths _ _ Hfinst).\n    cbn in x'eq'.\n    assert (Hypg := fiber_paths Hginst). (** use [assert] to forget the definition *)\n    cbn in Hypg.\n    change (base_paths hfg (f x,, idpath (g (f x))) Hginst) with x'eq in Hypg.\n    assert (Hypf := fiber_paths Hfinst).\n    cbn in Hypf.\n    change (base_paths hff (x,, idpath (f x)) Hfinst) with x'eq' in Hypf.\n    induction x'eq'. (** this is now possible, after sufficient abstraction *)\n    use total2_paths2_f. (** a rather trivial instance *)\n    + apply idpath.\n    + cbn.\n      cbn in Hypf.\n      rewrite Hypf in Hypg.\n      cbn in Hypg.\n      exact Hypg.\nDefined.\n\n(** a proof that is less aggressive on induction on identities - not completed *)\nLemma compisweq_alt_incomplete {X Y Z : UU} (f : X -> Y) (g : Y -> Z)\n        (isf : isweq f) (isg : isweq g) : isweq (g ∘ f).\nProof.\n  unfold isweq.\n  intro z.\n  unfold iscontr.\n  unfold hfiber.\n  set (isginst := isg z).\n  induction isginst as [cntrg Hg].\n  induction cntrg as [y yeq].\n  set (isfinst := isf y).\n  induction isfinst as [cntrf Hf].\n  induction cntrf as [x xeq].\n  use tpair.\n  - exists x.\n    unfold funcomp.\n    intermediate_path (g y).\n    + apply maponpaths.\n      apply xeq.\n    + apply yeq.\n  - cbn.\n    intro p.\n    induction p as [x' Hx'].\n    set (hfg := (f x',, Hx'): hfiber g z).\n    set (Hginst := Hg hfg).\n    set (x'eq := base_paths _ _ Hginst).\n    cbn in x'eq.\n    set (hff := (x',,x'eq): hfiber f y).\n    set (Hfinst := Hf hff).\n    set (x'eq' := base_paths _ _ Hfinst).\n    cbn in x'eq'.\n    set (Hypg := fiber_paths Hginst).\n    cbn in Hypg.\n    change (base_paths hfg (y,, yeq) Hginst) with x'eq in Hypg.\n    set (Hypf := fiber_paths Hfinst).\n    cbn in Hypf.\n    change (base_paths hff (x,, xeq) Hfinst) with x'eq' in Hypf.\n    use total2_paths2_f.\n    + exact x'eq'.\n    +\n\n      intermediate_path (transportf (λ x0 : hfiber f y, (g ∘ f) (pr1 x0) = z) Hfinst Hx').\n      { apply pathsinv0. unfold x'eq'. unfold base_paths. use functtransportf. }\n\n      assert (Hypg' : transportf (λ y0 : hfiber g z, g (pr1 y0) = z) Hginst Hx' = yeq).\n      { rewrite <- Hypg. unfold x'eq. unfold base_paths. use functtransportf. }\n\n      (** Who is willing to complete this proof? *)\nAbort.\n\n(** Package this up as an equivalence *)\nDefinition weqcomp {X Y Z : UU} (w1 : X ≃ Y) (w2 : Y ≃ Z) : X ≃ Z.\nProof.\n  induction w1 as [f isf].\n  induction w2 as [g isg].\n  use tpair.\n  - exact (g ∘ f).\n  - cbn.\n    exact (compisweq _ _ isf isg).\nDefined.\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/4_Tactics-UniMath/weq_exercises_with_solutions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.865224070413529, "lm_q1q2_score": 0.6949253094860991}}
{"text": "Require Import List.\n\nSection MapFilter.\n\n  Lemma not_in_map_not_in_map_filter :\n    forall (A B : Type) (l : list A) (f1 : A -> bool) (f2 : A -> B) (e : B),\n      ~ In e (map f2 l) -> ~ In e (map f2 (filter f1 l)).\n  Proof.\n    intros.\n    induction l.\n    - simpl; auto.\n    - simpl in H.\n      apply Decidable.not_or in H.\n      destruct H.\n      simpl.\n      remember (f1 a) as b; destruct b.\n      + simpl.\n        unfold not; intro.\n        destruct H1.\n        * apply H; apply H1.\n        * apply IHl.\n          apply H0.\n          apply H1.\n      + apply IHl.\n        apply H0.\n  Qed.\n\n  Lemma nodup_map_filter\n    : forall (A B : Type) (l : list A) (f1 : A -> bool) (f2 : A -> B),\n      NoDup (map f2 l) -> NoDup (map f2 (filter f1 l)).\n  Proof.\n    intros.\n    induction l.\n    - simpl; auto.\n    - simpl.\n      simpl in H.\n      rewrite NoDup_cons_iff in H.\n      destruct H.\n      remember (f1 a) as b; destruct b.\n      + simpl.\n        rewrite NoDup_cons_iff.\n        split.\n        apply not_in_map_not_in_map_filter.\n        apply H.\n        apply IHl.\n        apply H0.\n      + apply IHl.\n        simpl in H.\n        apply H0.\n  Qed.\n\nEnd MapFilter.\n", "meta": {"author": "takayuki988", "repo": "coq-proofs", "sha": "4ab9282c7e48177277b0cd58340ca16ef0fc1458", "save_path": "github-repos/coq/takayuki988-coq-proofs", "path": "github-repos/coq/takayuki988-coq-proofs/coq-proofs-4ab9282c7e48177277b0cd58340ca16ef0fc1458/map_filter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6949253075584713}}
{"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 NArith NPeano Ascii String.\n\nSet Implicit Arguments.\n\nLocal Open Scope string_scope.\n\nLocal Definition natToDigit (n : nat) : string :=\n  match n with\n    | 0 => \"0\"\n    | 1 => \"1\"\n    | 2 => \"2\"\n    | 3 => \"3\"\n    | 4 => \"4\"\n    | 5 => \"5\"\n    | 6 => \"6\"\n    | 7 => \"7\"\n    | 8 => \"8\"\n    | _ => \"9\"\n  end.\n\nLocal Definition NToDigit (n : N) := natToDigit (N.to_nat n).\n\nLocal Fixpoint writeNatAux (time n : nat) (acc : string) : string :=\n  let acc' := natToDigit (n mod 10) ++ acc in\n  match time with\n    | 0 => acc'\n    | S time' =>\n      match n / 10 with\n        | 0 => acc'\n        | n' => writeNatAux time' n' acc'\n      end\n  end.\n\nLocal Fixpoint writeNAux (time : nat) (n : N) (acc : string) : string :=\n  let acc' := NToDigit (n mod 10)%N ++ acc in\n  match time with\n    | 0 => acc'\n    | S time' =>\n      match (n / 10)%N with\n        | N0 => acc'\n        | n' => writeNAux time' n' acc'\n      end\n  end.\n\nSection N_to_string.\n  \n  Let loop := fix loop l n s :=\n    let (d,r) := N.div_eucl n 10 in\n    let s'    := String (ascii_of_N (48+r)) s\n    in match d, l with\n         | N0, _   => s'\n         | _ , 0   => s'\n         | _ , S l => loop l d s'\n    end.\n  \n  (* We limit the display of N to 10^12 *)\n \n  Definition string_of_N n := \n    match n with \n      | N0 => \"0\"\n      | _  => loop 12 n EmptyString\n    end.\n  \nEnd N_to_string.\n\nDefinition string_of_nat n := writeNatAux n n \"\".\n\n(*\nEval compute in string_of_N 123456789012309271072.\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/utils_string.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6949252978996008}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq path.\nFrom mathcomp Require Import fintype div bigop.\n\n(******************************************************************************)\n(* This file contains the definitions of:                                     *)\n(*        prime p <=> p is a prime.                                           *)\n(*       primes m == the sorted list of prime divisors of m > 1, else [::].   *)\n(*    pfactor p e == the value p ^ e of a prime factor (p, e).                *)\n(*    NumFactor f == print version of a prime factor, converting the prime    *)\n(*                   component to a Num (which can print large values).       *)\n(* prime_decomp m == the list of prime factors of m > 1, sorted by primes.    *)\n(*       logn p m == the e such that (p ^ e) \\in prime_decomp n, else 0.      *)\n(*  trunc_log p m == the largest e such that p ^ e <= m, or 0 if p or m is 0. *)\n(*         pdiv n == the smallest prime divisor of n > 1, else 1.             *)\n(*     max_pdiv n == the largest prime divisor of n > 1, else 1.              *)\n(*     divisors m == the sorted list of divisors of m > 0, else [::].         *)\n(*      totient n == the Euler totient (#|{i < n | i and n coprime}|).        *)\n(*       nat_pred == the type of explicit collective nat predicates.          *)\n(*                := simpl_pred nat.                                          *)\n(*    -> We allow the coercion nat >-> nat_pred, interpreting p as pred1 p.   *)\n(*    -> We define a predType for nat_pred, enabling the notation p \\in pi.   *)\n(*    -> We don't have nat_pred >-> pred, which would imply nat >-> Funclass. *)\n(*           pi^' == the complement of pi : nat_pred, i.e., the nat_pred such *)\n(*                   that (p \\in pi^') = (p \\notin pi).                       *)\n(*         \\pi(n) == the set of prime divisors of n, i.e., the nat_pred such  *)\n(*                   that (p \\in \\pi(n)) = (p \\in primes n).                  *)\n(*         \\pi(A) == the set of primes of #|A|, with A a collective predicate *)\n(*                   over a finite Type.                                      *)\n(*    -> The notation \\pi(A) is implemented with a collapsible Coercion. The  *)\n(*       type of A must coerce to finpred_sort (e.g., by coercing to {set T}) *)\n(*       and not merely implement the predType interface (as seq T does).     *)\n(*    -> The expression #|A| will only appear in \\pi(A) after simplification  *)\n(*       collapses the coercion, so it is advisable to do so early on.        *)\n(*     pi.-nat n <=> n > 0 and all prime divisors of n are in pi.             *)\n(*          n`_pi == the pi-part of n -- the largest pi.-nat divisor of n.    *)\n(*               := \\prod_(0 <= p < n.+1 | p \\in pi) p ^ logn p n.            *)\n(*    -> The nat >-> nat_pred coercion lets us write p.-nat n and n`_p.       *)\n(* In addition to the lemmas relevant to these definitions, this file also    *)\n(* contains the dvdn_sum lemma, so that bigop.v doesn't depend on div.v.      *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* The complexity of any arithmetic operation with the Peano representation *)\n(* is pretty dreadful, so using algorithms for \"harder\" problems such as    *)\n(* factoring, that are geared for efficient artihmetic leads to dismal      *)\n(* performance -- it takes a significant time, for instance, to compute the *)\n(* divisors of just a two-digit number. On the other hand, for Peano        *)\n(* integers, prime factoring (and testing) is linear-time with a small      *)\n(* constant factor -- indeed, the same as converting in and out of a binary *)\n(* representation. This is implemented by the code below, which is then     *)\n(* used to give the \"standard\" definitions of prime, primes, and divisors,  *)\n(* which can then be used casually in proofs with moderately-sized numeric  *)\n(* values (indeed, the code here performs well for up to 6-digit numbers).  *)\n\nModule Import PrimeDecompAux.\n\n(* We start with faster mod-2 and 2-valuation functions. *)\n\nFixpoint edivn2 q r := if r is r'.+2 then edivn2 q.+1 r' else (q, r).\n\nLemma edivn2P n : edivn_spec n 2 (edivn2 0 n).\nProof.\nrewrite -[n]odd_double_half addnC -{1}[n./2]addn0 -{1}mul2n mulnC.\nelim: n./2 {1 4}0 => [|r IHr] q; first by case (odd n) => /=.\nby rewrite addSnnS; apply: IHr.\nQed.\n\nFixpoint elogn2 e q r {struct q} :=\n  match q, r with\n  | 0, _ | _, 0 => (e, q)\n  | q'.+1, 1 => elogn2 e.+1 q' q'\n  | q'.+1, r'.+2 => elogn2 e q' r'\n  end.\n\nVariant elogn2_spec n : nat * nat -> Type :=\n  Elogn2Spec e m of n = 2 ^ e * m.*2.+1 : elogn2_spec n (e, m).\n\nLemma elogn2P n : elogn2_spec n.+1 (elogn2 0 n n).\nProof.\nrewrite -{1}[n.+1]mul1n -[1]/(2 ^ 0) -{1}(addKn n n) addnn.\nelim: n {1 4 6}n {2 3}0 (leqnn n) => [|q IHq] [|[|r]] e //=; last first.\n  by move/ltnW; apply: IHq.\nclear 1; rewrite subn1 -[_.-1.+1]doubleS -mul2n mulnA -expnSr.\nby rewrite -{1}(addKn q q) addnn; apply: IHq.\nQed.\n\nDefinition ifnz T n (x y : T) := if n is 0 then y else x.\n\nVariant ifnz_spec T n (x y : T) : T -> Type :=\n  | IfnzPos of n > 0 : ifnz_spec n x y x\n  | IfnzZero of n = 0 : ifnz_spec n x y y.\n\nLemma ifnzP T n (x y : T) : ifnz_spec n x y (ifnz n x y).\nProof. by case: n => [|n]; [right | left]. Qed.\n\n(* The list of divisors and the Euler function are computed directly from    *)\n(* the decomposition, using a merge_sort variant sort of the divisor list.   *)\n\nDefinition add_divisors f divs :=\n  let: (p, e) := f in\n  let add1 divs' := merge leq (map (NatTrec.mul p) divs') divs in\n  iter e add1 divs.\n\nImport NatTrec.\n\nDefinition add_totient_factor f m := let: (p, e) := f in p.-1 * p ^ e.-1 * m.\n\nDefinition cons_pfactor (p e : nat) pd := ifnz e ((p, e) :: pd) pd.\n\nNotation \"p ^? e :: pd\" := (cons_pfactor p e pd)\n  (at level 30, e at level 30, pd at level 60) : nat_scope.\n\nEnd PrimeDecompAux.\n\n(* For pretty-printing. *)\nDefinition NumFactor (f : nat * nat) := ([Num of f.1], f.2).\n\nDefinition pfactor p e := p ^ e.\n\nSection prime_decomp.\n\nImport NatTrec.\n\nLocal Fixpoint prime_decomp_rec m k a b c e :=\n  let p := k.*2.+1 in\n  if a is a'.+1 then\n    if b - (ifnz e 1 k - c) is b'.+1 then\n      [rec m, k, a', b', ifnz c c.-1 (ifnz e p.-2 1), e] else\n    if (b == 0) && (c == 0) then\n      let b' := k + a' in [rec b'.*2.+3, k, a', b', k.-1, e.+1] else\n    let bc' := ifnz e (ifnz b (k, 0) (edivn2 0 c)) (b, c) in\n    p ^? e :: ifnz a' [rec m, k.+1, a'.-1, bc'.1 + a', bc'.2, 0] [:: (m, 1)]\n  else if (b == 0) && (c == 0) then [:: (p, e.+2)] else p ^? e :: [:: (m, 1)]\nwhere \"[ 'rec' m , k , a , b , c , e ]\" := (prime_decomp_rec m k a b c e).\n\nDefinition prime_decomp n :=\n  let: (e2, m2) := elogn2 0 n.-1 n.-1 in\n  if m2 < 2 then 2 ^? e2 :: 3 ^? m2 :: [::] else\n  let: (a, bc) := edivn m2.-2 3 in\n  let: (b, c) := edivn (2 - bc) 2 in\n  2 ^? e2 :: [rec m2.*2.+1, 1, a, b, c, 0].\n\nEnd prime_decomp.\n\nDefinition primes n := unzip1 (prime_decomp n).\n\nDefinition prime p := if prime_decomp p is [:: (_ , 1)] then true else false.\n\nDefinition nat_pred := simpl_pred nat.\n\nDefinition pi_arg := nat.\nCoercion pi_arg_of_nat (n : nat) : pi_arg := n.\nCoercion pi_arg_of_fin_pred T pT (A : @fin_pred_sort T pT) : pi_arg := #|A|.\nArguments pi_arg_of_nat n /.\nArguments pi_arg_of_fin_pred {T pT} A /.\nDefinition pi_of (n : pi_arg) : nat_pred := [pred p in primes n].\n\nNotation \"\\pi ( n )\" := (pi_of n)\n  (at level 2, format \"\\pi ( n )\") : nat_scope.\nNotation \"\\p 'i' ( A )\" := \\pi(#|A|) \n  (at level 2, format \"\\p 'i' ( A )\") : nat_scope.\n\nDefinition pdiv n := head 1 (primes n).\n\nDefinition max_pdiv n := last 1 (primes n).\n\nDefinition divisors n := foldr add_divisors [:: 1] (prime_decomp n).\n\nDefinition totient n := foldr add_totient_factor (n > 0) (prime_decomp n).\n\n(* Correctness of the decomposition algorithm. *)\n\nLemma prime_decomp_correct :\n  let pd_val pd := \\prod_(f <- pd) pfactor f.1 f.2 in\n  let lb_dvd q m := ~~ has [pred d | d %| m] (index_iota 2 q) in\n  let pf_ok f := lb_dvd f.1 f.1 && (0 < f.2) in\n  let pd_ord q pd := path ltn q (unzip1 pd) in\n  let pd_ok q n pd := [/\\ n = pd_val pd, all pf_ok pd & pd_ord q pd] in\n  forall n, n > 0 -> pd_ok 1 n (prime_decomp n).\nProof.\nrewrite unlock => pd_val lb_dvd pf_ok pd_ord pd_ok.\nhave leq_pd_ok m p q pd: q <= p -> pd_ok p m pd -> pd_ok q m pd.\n  rewrite /pd_ok /pd_ord; case: pd => [|[r _] pd] //= leqp [<- ->].\n  by case/andP=> /(leq_trans _)->.\nhave apd_ok m e q p pd: lb_dvd p p || (e == 0) -> q < p ->\n     pd_ok p m pd -> pd_ok q (p ^ e * m) (p ^? e :: pd).\n- case: e => [|e]; rewrite orbC /= => pr_p ltqp.\n    by rewrite mul1n; apply: leq_pd_ok; apply: ltnW.\n  by rewrite /pd_ok /pd_ord /pf_ok /= pr_p ltqp => [[<- -> ->]].\ncase=> // n _; rewrite /prime_decomp.\ncase: elogn2P => e2 m2 -> {n}; case: m2 => [|[|abc]]; try exact: apd_ok.\nrewrite [_.-2]/= !ltnS ltn0 natTrecE; case: edivnP => a bc ->{abc}.\ncase: edivnP => b c def_bc /= ltc2 ltbc3; apply: (apd_ok) => //.\nmove def_m: _.*2.+1 => m; set k := {2}1; rewrite -[2]/k.*2; set e := 0.\npose p := k.*2.+1; rewrite -{1}[m]mul1n -[1]/(p ^ e)%N.\nhave{def_m bc def_bc ltc2 ltbc3}:\n   let kb := (ifnz e k 1).*2 in\n   [&& k > 0, p < m, lb_dvd p m, c < kb & lb_dvd p p || (e == 0)]\n    /\\ m + (b * kb + c).*2 = p ^ 2 + (a * p).*2.\n- rewrite -def_m [in lb_dvd _ _]def_m; split=> //=; last first.\n    by rewrite -def_bc addSn -doubleD 2!addSn -addnA subnKC // addnC.\n  rewrite ltc2 /lb_dvd /index_iota /= dvdn2 -def_m.\n  by rewrite [_.+2]lock /= odd_double.\nhave [n] := ubnP a.\nelim: n => // n IHn in a (k) p m b c (e) * => /ltnSE-le_a_n [].\nset kb := _.*2; set d := _ + c => /and5P[lt0k ltpm leppm ltc pr_p def_m].\nhave def_k1: k.-1.+1 = k := ltn_predK lt0k.\nhave def_kb1: kb.-1.+1 = kb by rewrite /kb -def_k1; case e.\nhave eq_bc_0: (b == 0) && (c == 0) = (d == 0).\n  by rewrite addn_eq0 muln_eq0 orbC -def_kb1.\nhave lt1p: 1 < p by rewrite ltnS double_gt0.\nhave co_p_2: coprime p 2 by rewrite /coprime gcdnC gcdnE modn2 /= odd_double.\nhave if_d0: d = 0 -> [/\\ m = (p + a.*2) * p, lb_dvd p p & lb_dvd p (p + a.*2)].\n  move=> d0; have{d0 def_m} def_m: m = (p + a.*2) * p.\n    by rewrite d0 addn0 -mulnn -!mul2n mulnA -mulnDl in def_m *.\n  split=> //; apply/hasPn=> r /(hasPn leppm); apply: contra => /= dv_r.\n    by rewrite def_m dvdn_mull.\n  by rewrite def_m dvdn_mulr.\ncase def_a: a => [|a'] /= in le_a_n *; rewrite !natTrecE -/p {}eq_bc_0.\n  case: d if_d0 def_m => [[//| def_m {pr_p}pr_p pr_m'] _ | d _ def_m] /=.\n    rewrite def_m def_a addn0 mulnA -2!expnSr.\n    by split; rewrite /pd_ord /pf_ok /= ?muln1 ?pr_p ?leqnn.\n  apply: apd_ok; rewrite // /pd_ok /= /pfactor expn1 muln1 /pd_ord /= ltpm.\n  rewrite /pf_ok !andbT /=; split=> //; apply: contra leppm.\n  case/hasP=> r /=; rewrite mem_index_iota => /andP[lt1r ltrm] dvrm; apply/hasP.\n  have [ltrp | lepr] := ltnP r p.\n    by exists r; rewrite // mem_index_iota lt1r.\n  case/dvdnP: dvrm => q def_q; exists q; last by rewrite def_q /= dvdn_mulr.\n  rewrite mem_index_iota -(ltn_pmul2r (ltnW lt1r)) -def_q mul1n ltrm.\n  move: def_m; rewrite def_a addn0 -(@ltn_pmul2r p) // mulnn => <-.\n  apply: (@leq_ltn_trans m); first by rewrite def_q leq_mul.\n  by rewrite -addn1 leq_add2l.\nhave def_k2: k.*2 = ifnz e 1 k * kb.\n  by rewrite /kb; case: (e) => [|e']; rewrite (mul1n, muln2).\ncase def_b': (b - _) => [|b']; last first.\n  have ->: ifnz e k.*2.-1 1 = kb.-1 by rewrite /kb; case e.\n  apply: IHn => {n le_a_n}//; rewrite -/p -/kb; split=> //.\n    rewrite lt0k ltpm leppm pr_p andbT /=.\n    by case: ifnzP; [move/ltn_predK->; apply: ltnW | rewrite def_kb1].\n  apply: (@addIn p.*2).\n  rewrite -2!addnA -!doubleD -addnA -mulSnr -def_a -def_m /d.\n  have ->: b * kb = b' * kb + (k.*2 - c * kb + kb).\n    rewrite addnCA addnC -mulSnr -def_b' def_k2 -mulnBl -mulnDl subnK //.\n    by rewrite ltnW // -subn_gt0 def_b'.\n  rewrite -addnA; congr (_ + (_ + _).*2).\n  case: (c) ltc; first by rewrite -addSnnS def_kb1 subn0 addn0 addnC.\n  rewrite /kb; case e => [[] // _ | e' c' _] /=; last first.\n    by rewrite subnDA subnn addnC addSnnS.\n  by rewrite mul1n -doubleB -doubleD subn1 !addn1 def_k1.\nhave ltdp: d < p.\n  move/eqP: def_b'; rewrite subn_eq0 -(@leq_pmul2r kb); last first.\n    by rewrite -def_kb1.\n  rewrite mulnBl -def_k2 ltnS -(leq_add2r c); move/leq_trans; apply.\n  have{ltc} ltc: c < k.*2.\n    by apply: (leq_trans ltc); rewrite leq_double /kb; case e.\n  rewrite -{2}(subnK (ltnW ltc)) leq_add2r leq_sub2l //.\n  by rewrite -def_kb1 mulnS leq_addr.\ncase def_d: d if_d0 => [|d'] => [[//|{def_m ltdp pr_p} def_m pr_p pr_m'] | _].\n  rewrite eqxx -doubleS -addnS -def_a doubleD -addSn -/p def_m.\n  rewrite mulnCA mulnC -expnSr.\n  apply: IHn => {n le_a_n}//; rewrite -/p -/kb; split.\n    rewrite lt0k -addn1 leq_add2l {1}def_a pr_m' pr_p /= def_k1 -addnn.\n    by rewrite leq_addr.\n  rewrite -addnA -doubleD addnCA def_a addSnnS def_k1 -(addnC k) -mulnSr.\n  rewrite -[_.*2.+1]/p mulnDl doubleD addnA -mul2n mulnA mul2n -mulSn.\n  by rewrite -/p mulnn.\nhave next_pm: lb_dvd p.+2 m.\n  rewrite /lb_dvd /index_iota 2!subSS subn0 -(subnK lt1p) iota_add.\n  rewrite has_cat; apply/norP; split=> //=; rewrite orbF subnKC // orbC.\n  apply/norP; split; apply/dvdnP=> [[q def_q]].\n     case/hasP: leppm; exists 2; first by rewrite /p -(subnKC lt0k).\n    by rewrite /= def_q dvdn_mull // dvdn2 /= odd_double.\n  move/(congr1 (dvdn p)): def_m; rewrite -mulnn -!mul2n mulnA -mulnDl.\n  rewrite dvdn_mull // dvdn_addr; last by rewrite def_q dvdn_mull.\n  case/dvdnP=> r; rewrite mul2n => def_r; move: ltdp (congr1 odd def_r).\n  rewrite odd_double -ltn_double {1}def_r -mul2n ltn_pmul2r //.\n  by case: r def_r => [|[|[]]] //; rewrite def_d // mul1n /= odd_double.\napply: apd_ok => //; case: a' def_a le_a_n => [|a'] def_a => [_ | lta] /=.\n  rewrite /pd_ok /= /pfactor expn1 muln1 /pd_ord /= ltpm /pf_ok !andbT /=.\n  split=> //; apply: contra next_pm.\n  case/hasP=> q; rewrite mem_index_iota => /andP[lt1q ltqm] dvqm; apply/hasP.\n  have [ltqp | lepq] := ltnP q p.+2.\n    by exists q; rewrite // mem_index_iota lt1q.\n  case/dvdnP: dvqm => r def_r; exists r; last by rewrite def_r /= dvdn_mulr.\n  rewrite mem_index_iota -(ltn_pmul2r (ltnW lt1q)) -def_r mul1n ltqm /=.\n  rewrite -(@ltn_pmul2l p.+2) //; apply: (@leq_ltn_trans m).\n    by rewrite def_r mulnC leq_mul.\n  rewrite -addn2 mulnn sqrnD mul2n muln2 -addnn addnCA -addnA addnCA addnA.\n  by rewrite def_a mul1n in def_m; rewrite -def_m addnS -addnA ltnS leq_addr.\nset bc := ifnz _ _ _; apply: leq_pd_ok (leqnSn _) _.\nrewrite -doubleS -{1}[m]mul1n -[1]/(k.+1.*2.+1 ^ 0)%N.\napply: IHn; first exact: ltnW.\nrewrite doubleS -/p [ifnz 0 _ _]/=; do 2?split => //.\n  rewrite orbT next_pm /= -(leq_add2r d.*2) def_m 2!addSnnS -doubleS leq_add.\n  - move: ltc; rewrite /kb {}/bc andbT; case e => //= e' _; case: ifnzP => //.\n    by case: edivn2P.\n  - by rewrite -{1}[p]muln1 -mulnn ltn_pmul2l.\n  by rewrite leq_double def_a mulSn (leq_trans ltdp) ?leq_addr.\nrewrite mulnDl !muln2 -addnA addnCA doubleD addnCA.\nrewrite (_ : _ + bc.2 = d); last first.\n  rewrite /d {}/bc /kb -muln2.\n  case: (e) (b) def_b' => //= _ []; first by case: edivn2P.\n  by case c; do 2?case; rewrite // mul1n /= muln2.\nrewrite def_m 3!doubleS addnC -(addn2 p) sqrnD mul2n muln2 -3!addnA.\ncongr (_ + _); rewrite 4!addnS -!doubleD; congr _.*2.+2.+2.\nby rewrite def_a -add2n mulnDl -addnA -muln2 -mulnDr mul2n.\nQed.\n\nLemma primePn n :\n  reflect (n < 2 \\/ exists2 d, 1 < d < n & d %| n) (~~ prime n).\nProof.\nrewrite /prime; case: n => [|[|p2]]; try by do 2!left.\ncase: (@prime_decomp_correct p2.+2) => //; rewrite unlock.\ncase: prime_decomp => [|[q [|[|e]]] pd] //=; last first; last by rewrite andbF.\n  rewrite {1}/pfactor 2!expnS -!mulnA /=.\n  case: (_ ^ _ * _) => [|u -> _ /andP[lt1q _]]; first by rewrite !muln0.\n  left; right; exists q; last by rewrite dvdn_mulr.\n  have lt0q := ltnW lt1q; rewrite lt1q -{1}[q]muln1 ltn_pmul2l //.\n  by rewrite -[2]muln1 leq_mul.\nrewrite {1}/pfactor expn1; case: pd => [|[r e] pd] /=; last first.\n  case: e => [|e] /=; first by rewrite !andbF.\n  rewrite {1}/pfactor expnS -mulnA.\n  case: (_ ^ _ * _) => [|u -> _ /and3P[lt1q ltqr _]]; first by rewrite !muln0.\n  left; right; exists q; last by rewrite dvdn_mulr.\n  by rewrite lt1q -{1}[q]mul1n ltn_mul // -[q.+1]muln1 leq_mul.\nrewrite muln1 !andbT => def_q pr_q lt1q; right=> [[]] // [d].\nby rewrite def_q -mem_index_iota => in_d_2q dv_d_q; case/hasP: pr_q; exists d.\nQed.\n\nLemma primeP p :\n  reflect (p > 1 /\\ forall d, d %| p -> xpred2 1 p d) (prime p).\nProof.\nrewrite -[prime p]negbK; have [npr_p | pr_p] := primePn p.\n  right=> [[lt1p pr_p]]; case: npr_p => [|[d n1pd]].\n    by rewrite ltnNge lt1p.\n  by move/pr_p=> /orP[] /eqP def_d; rewrite def_d ltnn ?andbF in n1pd.\nhave [lep1 | lt1p] := leqP; first by case: pr_p; left.\nleft; split=> // d dv_d_p; apply/norP=> [[nd1 ndp]]; case: pr_p; right.\nexists d; rewrite // andbC 2!ltn_neqAle ndp eq_sym nd1.\nby have lt0p := ltnW lt1p; rewrite dvdn_leq // (dvdn_gt0 lt0p).\nQed.\n\nLemma prime_nt_dvdP d p : prime p -> d != 1 -> reflect (d = p) (d %| p).\nProof.\ncase/primeP=> _ min_p d_neq1; apply: (iffP idP) => [/min_p|-> //].\nby rewrite (negPf d_neq1) /= => /eqP.\nQed.\n\nArguments primeP {p}.\nArguments primePn {n}.\n\nLemma prime_gt1 p : prime p -> 1 < p.\nProof. by case/primeP. Qed.\n\nLemma prime_gt0 p : prime p -> 0 < p.\nProof. by move/prime_gt1; apply: ltnW. Qed.\n\nHint Resolve prime_gt1 prime_gt0 : core.\n\nLemma prod_prime_decomp n :\n  n > 0 -> n = \\prod_(f <- prime_decomp n) f.1 ^ f.2.\nProof. by case/prime_decomp_correct. Qed.\n\nLemma even_prime p : prime p -> p = 2 \\/ odd p.\nProof.\nmove=> pr_p; case odd_p: (odd p); [by right | left].\nhave: 2 %| p by rewrite dvdn2 odd_p.\nby case/primeP: pr_p => _ dv_p /dv_p/(2 =P p).\nQed.\n\nLemma prime_oddPn p : prime p -> reflect (p = 2) (~~ odd p).\nProof.\nby move=> p_pr; apply: (iffP idP) => [|-> //]; case/even_prime: p_pr => ->.\nQed.\n\nLemma odd_prime_gt2 p : odd p -> prime p -> p > 2.\nProof. by move=> odd_p /prime_gt1; apply: odd_gt2. Qed.\n\nLemma mem_prime_decomp n p e :\n  (p, e) \\in prime_decomp n -> [/\\ prime p, e > 0 & p ^ e %| n].\nProof.\ncase: (posnP n) => [-> //| /prime_decomp_correct[def_n mem_pd ord_pd pd_pe]].\nhave /andP[pr_p ->] := allP mem_pd _ pd_pe; split=> //; last first.\n  case/splitPr: pd_pe def_n => pd1 pd2 ->.\n  by rewrite big_cat big_cons /= mulnCA dvdn_mulr.\nhave lt1p: 1 < p.\n  apply: (allP (order_path_min ltn_trans ord_pd)).\n  by apply/mapP; exists (p, e).\napply/primeP; split=> // d dv_d_p; apply/norP=> [[nd1 ndp]].\ncase/hasP: pr_p; exists d => //.\nrewrite mem_index_iota andbC 2!ltn_neqAle ndp eq_sym nd1.\nby have lt0p := ltnW lt1p; rewrite dvdn_leq // (dvdn_gt0 lt0p).\nQed.\n\nLemma prime_coprime p m : prime p -> coprime p m = ~~ (p %| m).\nProof.\ncase/primeP=> p_gt1 p_pr; apply/eqP/negP=> [d1 | ndv_pm].\n  case/dvdnP=> k def_m; rewrite -(addn0 m) def_m gcdnMDl gcdn0 in d1.\n  by rewrite d1 in p_gt1.\nby apply: gcdn_def => // d /p_pr /orP[] /eqP->.\nQed.\n\nLemma dvdn_prime2 p q : prime p -> prime q -> (p %| q) = (p == q).\nProof.\nmove=> pr_p pr_q; apply: negb_inj.\nby rewrite eqn_dvd negb_and -!prime_coprime // coprime_sym orbb.\nQed.\n\nLemma Euclid_dvd1 p : prime p -> (p %| 1) = false.\nProof. by rewrite dvdn1; case: eqP => // ->. Qed.\n\nLemma Euclid_dvdM m n p : prime p -> (p %| m * n) = (p %| m) || (p %| n).\nProof.\nmove=> pr_p; case dv_pm: (p %| m); first exact: dvdn_mulr.\nby rewrite Gauss_dvdr // prime_coprime // dv_pm.\nQed.\n\nLemma Euclid_dvd_prod (I : Type) (r : seq I) (P : pred I) (f : I -> nat) p :\n  prime p ->  \n  p %| \\prod_(i <- r | P i) f i = \\big[orb/false]_(i <- r | P i) (p %| f i).\nProof.\nmove=> pP; apply: big_morph=> [x y|]; [exact: Euclid_dvdM | exact: Euclid_dvd1].\nQed.\n\nLemma Euclid_dvdX m n p : prime p -> (p %| m ^ n) = (p %| m) && (n > 0).\nProof.\ncase: n => [|n] pr_p; first by rewrite andbF Euclid_dvd1.\nby apply: (inv_inj negbK); rewrite !andbT -!prime_coprime // coprime_pexpr.\nQed.\n\nLemma mem_primes p n : (p \\in primes n) = [&& prime p, n > 0 & p %| n].\nProof.\nrewrite andbCA; case: posnP => [-> // | /= n_gt0].\napply/mapP/andP=> [[[q e]]|[pr_p]] /=.\n  case/mem_prime_decomp=> pr_q e_gt0; case/dvdnP=> u -> -> {p}.\n  by rewrite -(prednK e_gt0) expnS mulnCA dvdn_mulr.\nrewrite {1}(prod_prime_decomp n_gt0) big_seq.\napply big_ind => [| u v IHu IHv | [q e] /= mem_qe dv_p_qe].\n- by rewrite Euclid_dvd1.\n- by rewrite Euclid_dvdM // => /orP[].\nexists (q, e) => //=; case/mem_prime_decomp: mem_qe => pr_q _ _.\nby rewrite Euclid_dvdX // dvdn_prime2 // in dv_p_qe; case: eqP dv_p_qe.\nQed.\n\nLemma sorted_primes n : sorted ltn (primes n).\nProof.\nby case: (posnP n) => [-> // | /prime_decomp_correct[_ _]]; apply: path_sorted.\nQed.\n\nLemma eq_primes m n : (primes m =i primes n) <-> (primes m = primes n).\nProof.\nsplit=> [eqpr| -> //].\nby apply: (eq_sorted_irr ltn_trans ltnn); rewrite ?sorted_primes.\nQed.\n\nLemma primes_uniq n : uniq (primes n).\nProof. exact: (sorted_uniq ltn_trans ltnn (sorted_primes n)). Qed.\n\n(* The smallest prime divisor *)\n\nLemma pi_pdiv n : (pdiv n \\in \\pi(n)) = (n > 1).\nProof.\ncase: n => [|[|n]] //; rewrite /pdiv !inE /primes.\nhave:= prod_prime_decomp (ltn0Sn n.+1); rewrite unlock.\nby case: prime_decomp => //= pf pd _; rewrite mem_head.\nQed.\n\nLemma pdiv_prime n : 1 < n -> prime (pdiv n).\nProof. by rewrite -pi_pdiv mem_primes; case/and3P. Qed.\n\nLemma pdiv_dvd n : pdiv n %| n.\nProof.\nby case: n (pi_pdiv n) => [|[|n]] //; rewrite mem_primes=> /and3P[].\nQed.\n\nLemma pi_max_pdiv n : (max_pdiv n \\in \\pi(n)) = (n > 1).\nProof.\nrewrite !inE -pi_pdiv /max_pdiv /pdiv !inE.\nby case: (primes n) => //= p ps; rewrite mem_head mem_last.\nQed.\n\nLemma max_pdiv_prime n : n > 1 -> prime (max_pdiv n).\nProof. by rewrite -pi_max_pdiv mem_primes => /andP[]. Qed.\n\nLemma max_pdiv_dvd n : max_pdiv n %| n.\nProof.\nby case: n (pi_max_pdiv n) => [|[|n]] //; rewrite mem_primes => /andP[].\nQed.\n\nLemma pdiv_leq n : 0 < n -> pdiv n <= n.\nProof. by move=> n_gt0; rewrite dvdn_leq // pdiv_dvd. Qed.\n\nLemma max_pdiv_leq n : 0 < n -> max_pdiv n <= n.\nProof. by move=> n_gt0; rewrite dvdn_leq // max_pdiv_dvd. Qed.\n\nLemma pdiv_gt0 n : 0 < pdiv n.\nProof. by case: n => [|[|n]] //; rewrite prime_gt0 ?pdiv_prime. Qed.\n\nLemma max_pdiv_gt0 n : 0 < max_pdiv n.\nProof. by case: n => [|[|n]] //; rewrite prime_gt0 ?max_pdiv_prime. Qed.\nHint Resolve pdiv_gt0 max_pdiv_gt0 : core.\n\nLemma pdiv_min_dvd m d : 1 < d -> d %| m -> pdiv m <= d.\nProof.\nmove=> lt1d dv_d_m; case: (posnP m) => [->|mpos]; first exact: ltnW.\nrewrite /pdiv; apply: leq_trans (pdiv_leq (ltnW lt1d)).\nhave: pdiv d \\in primes m.\n  by rewrite mem_primes mpos pdiv_prime // (dvdn_trans (pdiv_dvd d)).\ncase: (primes m) (sorted_primes m) => //= p pm ord_pm.\nrewrite inE => /predU1P[-> //|].\nby move/(allP (order_path_min ltn_trans ord_pm)); apply: ltnW.\nQed.\n\nLemma max_pdiv_max n p : p \\in \\pi(n) -> p <= max_pdiv n.\nProof.\nrewrite /max_pdiv !inE => n_p.\ncase/splitPr: n_p (sorted_primes n) => p1 p2; rewrite last_cat -cat_rcons /=.\nrewrite headI /= cat_path -(last_cons 0) -headI last_rcons; case/andP=> _.\nmove/(order_path_min ltn_trans); case/lastP: p2 => //= p2 q.\nby rewrite all_rcons last_rcons ltn_neqAle -andbA => /and3P[].\nQed.\n\nLemma ltn_pdiv2_prime n : 0 < n -> n < pdiv n ^ 2 -> prime n.\nProof.\ncase def_n: n => [|[|n']] // _; rewrite -def_n => lt_n_p2.\nsuffices ->: n = pdiv n by rewrite pdiv_prime ?def_n.\napply/eqP; rewrite eqn_leq leqNgt andbC pdiv_leq; last by rewrite def_n.\nmove: lt_n_p2; rewrite ltnNge; apply: contra => lt_pm_m.\ncase/dvdnP: (pdiv_dvd n) => q def_q.\nrewrite {2}def_q -mulnn leq_pmul2r // pdiv_min_dvd //.\n  by rewrite -[pdiv n]mul1n {2}def_q ltn_pmul2r in lt_pm_m.\nby rewrite def_q dvdn_mulr.\nQed.\n\nLemma primePns n :\n  reflect (n < 2 \\/ exists p, [/\\ prime p, p ^ 2 <= n & p %| n]) (~~ prime n).\nProof.\napply: (iffP idP) => [npr_p|]; last first.\n  case=> [|[p [pr_p le_p2_n dv_p_n]]]; first by case: n => [|[]].\n  apply/negP=> pr_n; move: dv_p_n le_p2_n; rewrite dvdn_prime2 //; move/eqP->.\n  by rewrite leqNgt -{1}[n]muln1 -mulnn ltn_pmul2l ?prime_gt1 ?prime_gt0.\ncase: leqP => [lt1p|]; [right | by left].\nexists (pdiv n); rewrite pdiv_dvd pdiv_prime //; split=> //.\nby case: leqP npr_p => //; move/ltn_pdiv2_prime->; auto.\nQed.\n\nArguments primePns {n}.\n\nLemma pdivP n : n > 1 -> {p | prime p & p %| n}.\nProof. by move=> lt1n; exists (pdiv n); rewrite ?pdiv_dvd ?pdiv_prime. Qed.\n\nLemma primes_mul m n p : m > 0 -> n > 0 ->\n  (p \\in primes (m * n)) = (p \\in primes m) || (p \\in primes n).\nProof.\nmove=> m_gt0 n_gt0; rewrite !mem_primes muln_gt0 m_gt0 n_gt0.\nby case pr_p: (prime p); rewrite // Euclid_dvdM.\nQed.\n\nLemma primes_exp m n : n > 0 -> primes (m ^ n) = primes m.\nProof.\ncase: n => // n _; rewrite expnS; case: (posnP m) => [-> //| m_gt0].\napply/eq_primes => /= p; elim: n => [|n IHn]; first by rewrite muln1.\nby rewrite primes_mul ?(expn_gt0, expnS, IHn, orbb, m_gt0).\nQed.\n\nLemma primes_prime p : prime p -> primes p = [::p].\nProof.\nmove=> pr_p; apply: (eq_sorted_irr ltn_trans ltnn) => // [|q].\n  exact: sorted_primes.\nrewrite mem_seq1 mem_primes prime_gt0 //=.\nby apply/andP/idP=> [[pr_q q_p] | /eqP-> //]; rewrite -dvdn_prime2.\nQed.\n\nLemma coprime_has_primes m n :\n  0 < m -> 0 < n -> coprime m n = ~~ has (mem (primes m)) (primes n).\nProof.\nmove=> m_gt0 n_gt0; apply/eqP/hasPn=> [mn1 p | no_p_mn].\n  rewrite /= !mem_primes m_gt0 n_gt0 /= => /andP[pr_p p_n].\n  have:= prime_gt1 pr_p; rewrite pr_p ltnNge -mn1 /=; apply: contra => p_m.\n  by rewrite dvdn_leq ?gcdn_gt0 ?m_gt0 // dvdn_gcd ?p_m.\ncase: (ltngtP (gcdn m n) 1) => //; first by rewrite ltnNge gcdn_gt0 ?m_gt0.\nmove/pdiv_prime; set p := pdiv _ => pr_p.\nmove/implyP: (no_p_mn p); rewrite /= !mem_primes m_gt0 n_gt0 pr_p /=.\nby rewrite !(dvdn_trans (pdiv_dvd _)) // (dvdn_gcdl, dvdn_gcdr).\nQed.\n\nLemma pdiv_id p : prime p -> pdiv p = p.\nProof. by move=> p_pr; rewrite /pdiv primes_prime. Qed.\n\nLemma pdiv_pfactor p k : prime p -> pdiv (p ^ k.+1) = p.\nProof. by move=> p_pr; rewrite /pdiv primes_exp ?primes_prime. Qed.\n\n(* Primes are unbounded. *)\n\nLemma prime_above m : {p | m < p & prime p}.\nProof.\nhave /pdivP[p pr_p p_dv_m1]: 1 < m`! + 1 by rewrite addn1 ltnS fact_gt0.\nexists p => //; rewrite ltnNge; apply: contraL p_dv_m1 => p_le_m.\nby rewrite dvdn_addr ?dvdn_fact ?prime_gt0 // gtnNdvd ?prime_gt1.\nQed.\n\n(* \"prime\" logarithms and p-parts. *)\n\nFixpoint logn_rec d m r :=\n  match r, edivn m d with\n  | r'.+1, (_.+1 as m', 0) => (logn_rec d m' r').+1\n  | _, _ => 0\n  end.\n\nDefinition logn p m := if prime p then logn_rec p m m else 0.\n\nLemma lognE p m :\n  logn p m = if [&& prime p, 0 < m & p %| m] then (logn p (m %/ p)).+1 else 0.\nProof.\nrewrite /logn /dvdn; case p_pr: (prime p) => //.\ncase def_m: m => // [m']; rewrite !andTb [LHS]/= -def_m /divn modn_def.\ncase: edivnP def_m => [[|q] [|r] -> _] // def_m; congr _.+1; rewrite [_.1]/=.\nhave{m def_m}: q < m'.\n  by rewrite -ltnS -def_m addn0 mulnC -{1}[q.+1]mul1n ltn_pmul2r // prime_gt1.\nelim/ltn_ind: m' {q}q.+1 (ltn0Sn q) => -[_ []|r IHr m] //= m_gt0 le_mr.\nrewrite -[m in logn_rec _ _ m]prednK //=.\ncase: edivnP => [[|q] [|_] def_q _] //; rewrite addn0 in def_q.\nhave{def_q} lt_qm1: q < m.-1.\n  by rewrite -[q.+1]muln1 -ltnS prednK // def_q ltn_pmul2l // prime_gt1.\nhave{le_mr} le_m1r: m.-1 <= r by rewrite -ltnS prednK.\nby rewrite (IHr r) ?(IHr m.-1) // (leq_trans lt_qm1).\nQed.\n\nLemma logn_gt0 p n : (0 < logn p n) = (p \\in primes n).\nProof. by rewrite lognE -mem_primes; case: {+}(p \\in _). Qed.\n\nLemma ltn_log0 p n : n < p -> logn p n = 0.\nProof. by case: n => [|n] ltnp; rewrite lognE ?andbF // gtnNdvd ?andbF. Qed.\n\nLemma logn0 p : logn p 0 = 0.\nProof. by rewrite /logn if_same. Qed.\n\nLemma logn1 p : logn p 1 = 0.\nProof. by rewrite lognE dvdn1 /= andbC; case: eqP => // ->. Qed.\n\nLemma pfactor_gt0 p n : 0 < p ^ logn p n.\nProof. by rewrite expn_gt0 lognE; case: (posnP p) => // ->. Qed.\nHint Resolve pfactor_gt0 : core.\n\nLemma pfactor_dvdn p n m : prime p -> m > 0 -> (p ^ n %| m) = (n <= logn p m).\nProof.\nmove=> p_pr; elim: n m => [|n IHn] m m_gt0; first exact: dvd1n.\nrewrite lognE p_pr m_gt0 /=; case dv_pm: (p %| m); last first.\n  apply/dvdnP=> [] [/= q def_m].\n  by rewrite def_m expnS mulnCA dvdn_mulr in dv_pm.\ncase/dvdnP: dv_pm m_gt0 => q ->{m}; rewrite muln_gt0 => /andP[p_gt0 q_gt0].\nby rewrite expnSr dvdn_pmul2r // mulnK // IHn.\nQed.\n\nLemma pfactor_dvdnn p n : p ^ logn p n %| n.\nProof.\ncase: n => // n; case pr_p: (prime p); first by rewrite pfactor_dvdn.\nby rewrite lognE pr_p dvd1n.\nQed.\n\nLemma logn_prime p q : prime q -> logn p q = (p == q).\nProof.\nmove=> pr_q; have q_gt0 := prime_gt0 pr_q; rewrite lognE q_gt0 /=.\ncase pr_p: (prime p); last by case: eqP pr_p pr_q => // -> ->.\nby rewrite dvdn_prime2 //; case: eqP => // ->; rewrite divnn q_gt0 logn1.\nQed.\n\nLemma pfactor_coprime p n :\n  prime p -> n > 0 -> {m | coprime p m & n = m * p ^ logn p n}.\nProof.\nmove=> p_pr n_gt0; set k := logn p n.\nhave dv_pk_n: p ^ k %| n by rewrite pfactor_dvdn.\nexists (n %/ p ^ k); last by rewrite divnK.\nrewrite prime_coprime // -(@dvdn_pmul2r (p ^ k)) ?expn_gt0 ?prime_gt0 //.\nby rewrite -expnS divnK // pfactor_dvdn // ltnn.\nQed.\n\nLemma pfactorK p n : prime p -> logn p (p ^ n) = n.\nProof.\nmove=> p_pr; have pn_gt0: p ^ n > 0 by rewrite expn_gt0 prime_gt0.\napply/eqP; rewrite eqn_leq -pfactor_dvdn // dvdnn andbT.\nby rewrite -(leq_exp2l _ _ (prime_gt1 p_pr)) dvdn_leq // pfactor_dvdn.\nQed.\n\nLemma pfactorKpdiv p n : prime p -> logn (pdiv (p ^ n)) (p ^ n) = n.\nProof. by case: n => // n p_pr; rewrite pdiv_pfactor ?pfactorK. Qed.\n\nLemma dvdn_leq_log p m n : 0 < n -> m %| n -> logn p m <= logn p n.\nProof.\nmove=> n_gt0 dv_m_n; have m_gt0 := dvdn_gt0 n_gt0 dv_m_n.\ncase p_pr: (prime p); last by do 2!rewrite lognE p_pr /=.\nby rewrite -pfactor_dvdn //; apply: dvdn_trans dv_m_n; rewrite pfactor_dvdn.\nQed.\n\nLemma ltn_logl p n : 0 < n -> logn p n < n.\nProof.\nmove=> n_gt0; have [p_gt1 | p_le1] := boolP (1 < p).\n  by rewrite (leq_trans (ltn_expl _ p_gt1)) // dvdn_leq ?pfactor_dvdnn.\nby rewrite lognE (contraNF (@prime_gt1 _)).\nQed.\n\nLemma logn_Gauss p m n : coprime p m -> logn p (m * n) = logn p n.\nProof.\nmove=> co_pm; case p_pr: (prime p); last by rewrite /logn p_pr.\nhave [-> | n_gt0] := posnP n; first by rewrite muln0.\nhave [m0 | m_gt0] := posnP m; first by rewrite m0 prime_coprime ?dvdn0 in co_pm.\nhave mn_gt0: m * n > 0 by rewrite muln_gt0 m_gt0.\napply/eqP; rewrite eqn_leq andbC dvdn_leq_log ?dvdn_mull //.\nset k := logn p _; have: p ^ k %| m * n by rewrite pfactor_dvdn.\nby rewrite Gauss_dvdr ?coprime_expl // -pfactor_dvdn.\nQed.\n\nLemma lognM p m n : 0 < m -> 0 < n -> logn p (m * n) = logn p m + logn p n.\nProof.\ncase p_pr: (prime p); last by rewrite /logn p_pr.\nhave xlp := pfactor_coprime p_pr.\ncase/xlp=> m' co_m' def_m /xlp[n' co_n' def_n] {xlp}.\nby rewrite {1}def_m {1}def_n mulnCA -mulnA -expnD !logn_Gauss // pfactorK.\nQed.\n\nLemma lognX p m n : logn p (m ^ n) = n * logn p m.\nProof.\ncase p_pr: (prime p); last by rewrite /logn p_pr muln0.\nelim: n => [|n IHn]; first by rewrite logn1.\nhave [->|m_gt0] := posnP m; first by rewrite exp0n // lognE andbF muln0.\nby rewrite expnS lognM ?IHn // expn_gt0 m_gt0.\nQed.\n\nLemma logn_div p m n : m %| n -> logn p (n %/ m) = logn p n - logn p m.\nProof.\nrewrite dvdn_eq => /eqP def_n.\ncase: (posnP n) => [-> |]; first by rewrite div0n logn0.\nby rewrite -{1 3}def_n muln_gt0 => /andP[q_gt0 m_gt0]; rewrite lognM ?addnK.\nQed.\n\nLemma dvdn_pfactor p d n : prime p ->\n  reflect (exists2 m, m <= n & d = p ^ m) (d %| p ^ n).\nProof.\nmove=> p_pr; have pn_gt0: p ^ n > 0 by rewrite expn_gt0 prime_gt0.\napply: (iffP idP) => [dv_d_pn|[m le_m_n ->]]; last first.\n  by rewrite -(subnK le_m_n) expnD dvdn_mull.\nexists (logn p d); first by rewrite -(pfactorK n p_pr) dvdn_leq_log.\nhave d_gt0: d > 0 by apply: dvdn_gt0 dv_d_pn.\ncase: (pfactor_coprime p_pr d_gt0) => q co_p_q def_d.\nrewrite {1}def_d ((q =P 1) _) ?mul1n // -dvdn1.\nsuff: q %| p ^ n * 1 by rewrite Gauss_dvdr // coprime_sym coprime_expl.\nby rewrite muln1 (dvdn_trans _ dv_d_pn) // def_d dvdn_mulr.\nQed.\n\nLemma prime_decompE n : prime_decomp n = [seq (p, logn p n) | p <- primes n].\nProof.\ncase: n => // n; pose f0 := (0, 0); rewrite -map_comp.\napply: (@eq_from_nth _ f0) => [|i lt_i_n]; first by rewrite size_map.\nrewrite (nth_map f0) //; case def_f: (nth _ _ i) => [p e] /=.\ncongr (_, _); rewrite [n.+1]prod_prime_decomp //.\nhave: (p, e) \\in prime_decomp n.+1 by rewrite -def_f mem_nth.\ncase/mem_prime_decomp=> pr_p _ _.\nrewrite (big_nth f0) big_mkord (bigD1 (Ordinal lt_i_n)) //=.\nrewrite def_f mulnC logn_Gauss ?pfactorK //.\napply big_ind => [|m1 m2 com1 com2| [j ltj] /=]; first exact: coprimen1.\n  by rewrite coprime_mulr com1.\nrewrite -val_eqE /= => nji; case def_j: (nth _ _ j) => [q e1] /=.\nhave: (q, e1) \\in prime_decomp n.+1 by rewrite -def_j mem_nth.\ncase/mem_prime_decomp=> pr_q e1_gt0 _; rewrite coprime_pexpr //.\nrewrite prime_coprime // dvdn_prime2 //; apply: contra nji => eq_pq.\nrewrite -(nth_uniq 0 _ _ (primes_uniq n.+1)) ?size_map //=.\nby rewrite !(nth_map f0) //  def_f def_j /= eq_sym.\nQed.\n\n(* Some combinatorial formulae. *)\n\nLemma divn_count_dvd d n : n %/ d = \\sum_(1 <= i < n.+1) (d %| i).\nProof.\nhave [-> | d_gt0] := posnP d; first by rewrite big_add1 divn0 big1.\napply: (@addnI (d %| 0)); rewrite -(@big_ltn _ 0 _ 0 _ (dvdn d)) // big_mkord.\nrewrite (partition_big (fun i : 'I_n.+1 => inord (i %/ d)) 'I_(n %/ d).+1) //=.\nrewrite dvdn0 add1n -{1}[_.+1]card_ord -sum1_card; apply: eq_bigr => [[q ?] _].\nrewrite (bigD1 (inord (q * d))) /eq_op /= !inordK ?ltnS -?leq_divRL ?mulnK //.\nrewrite dvdn_mull ?big1 // => [[i /= ?] /andP[/eqP <- /negPf]].\nby rewrite eq_sym dvdn_eq inordK ?ltnS ?leq_div2r // => ->.\nQed.\n\nLemma logn_count_dvd p n : prime p -> logn p n = \\sum_(1 <= k < n) (p ^ k %| n).\nProof.\nrewrite big_add1 => p_prime; case: n => [|n]; first by rewrite logn0 big_geq.\nrewrite big_mkord -big_mkcond (eq_bigl _ _ (fun _ => pfactor_dvdn _ _ _)) //=.\nby rewrite big_ord_narrow ?sum1_card ?card_ord // -ltnS ltn_logl.\nQed.\n\n(* Truncated real log. *)\n\nDefinition trunc_log p n :=\n  let fix loop n k :=\n    if k is k'.+1 then if p <= n then (loop (n %/ p) k').+1 else 0 else 0\n  in loop n n.\n\nLemma trunc_log_bounds p n :\n  1 < p -> 0 < n -> let k := trunc_log p n in p ^ k <= n < p ^ k.+1.\nProof.\nrewrite {+}/trunc_log => p_gt1; have p_gt0 := ltnW p_gt1.\nset loop := (loop in loop n n); set m := n; rewrite [in n in loop m n]/m.\nhave: m <= n by []; elim: n m => [|n IHn] [|m] //= /ltnSE-le_m_n _.\nhave [le_p_n | // ] := leqP p _; rewrite 2!expnSr -leq_divRL -?ltn_divLR //.\nby apply: IHn; rewrite ?divn_gt0 // -ltnS (leq_trans (ltn_Pdiv _ _)).\nQed.\n\nLemma trunc_log_ltn p n : 1 < p -> n < p ^ (trunc_log p n).+1.\nProof.\nhave [-> | n_gt0] := posnP n; first by move=> /ltnW; rewrite expn_gt0.\nby case/trunc_log_bounds/(_ n_gt0)/andP.\nQed.\n\nLemma trunc_logP p n : 1 < p -> 0 < n -> p ^ trunc_log p n <= n.\nProof. by move=> p_gt1 /(trunc_log_bounds p_gt1)/andP[]. Qed.\n\nLemma trunc_log_max p k j : 1 < p -> p ^ j <= k -> j <= trunc_log p k.\nProof.\nmove=> p_gt1 le_pj_k; rewrite -ltnS -(@ltn_exp2l p) //.\nexact: leq_ltn_trans (trunc_log_ltn _ _).\nQed.\n\n(* pi- parts *)\n\n(* Testing for membership in set of prime factors. *)\n\nCanonical nat_pred_pred := Eval hnf in [predType of nat_pred].\n\nCoercion nat_pred_of_nat (p : nat) : nat_pred := pred1 p.\n\nSection NatPreds.\n\nVariables (n : nat) (pi : nat_pred).\n\nDefinition negn : nat_pred := [predC pi].\n\nDefinition pnat : pred nat := fun m => (m > 0) && all (mem pi) (primes m).\n\nDefinition partn := \\prod_(0 <= p < n.+1 | p \\in pi) p ^ logn p n.\n\nEnd NatPreds.\n\nNotation \"pi ^'\" := (negn pi) (at level 2, format \"pi ^'\") : nat_scope.\n\nNotation \"pi .-nat\" := (pnat pi) (at level 2, format \"pi .-nat\") : nat_scope.\n\nNotation \"n `_ pi\" := (partn n pi) : nat_scope.\n\nSection PnatTheory.\n\nImplicit Types (n p : nat) (pi rho : nat_pred).\n\nLemma negnK pi : pi^'^' =i pi.\nProof. by move=> p; apply: negbK. Qed.\n\nLemma eq_negn pi1 pi2 : pi1 =i pi2 -> pi1^' =i pi2^'.\nProof. by move=> eq_pi n; rewrite 3!inE /= eq_pi. Qed.\n\nLemma eq_piP m n : \\pi(m) =i \\pi(n) <-> \\pi(m) = \\pi(n).\nProof.\nrewrite /pi_of; have eqs := eq_sorted_irr ltn_trans ltnn.\nby split=> [|-> //]; move/(eqs _ _ (sorted_primes m) (sorted_primes n)) ->.\nQed.\n\nLemma part_gt0 pi n : 0 < n`_pi.\nProof. exact: prodn_gt0. Qed.\nHint Resolve part_gt0 : core.\n\nLemma sub_in_partn pi1 pi2 n :\n  {in \\pi(n), {subset pi1 <= pi2}} -> n`_pi1 %| n`_pi2.\nProof.\nmove=> pi12; rewrite ![n`__]big_mkcond /=.\napply (big_ind2 (fun m1 m2 => m1 %| m2)) => // [*|p _]; first exact: dvdn_mul.\nrewrite lognE -mem_primes; case: ifP => pi1p; last exact: dvd1n.\nby case: ifP => pr_p; [rewrite pi12 | rewrite if_same].\nQed.\n\nLemma eq_in_partn pi1 pi2 n : {in \\pi(n), pi1 =i pi2} -> n`_pi1 = n`_pi2.\nProof.\nby move=> pi12; apply/eqP; rewrite eqn_dvd ?sub_in_partn // => p /pi12->.\nQed.\n\nLemma eq_partn pi1 pi2 n : pi1 =i pi2 -> n`_pi1 = n`_pi2.\nProof. by move=> pi12; apply: eq_in_partn => p _. Qed.\n\nLemma partnNK pi n : n`_pi^'^' = n`_pi.\nProof. by apply: eq_partn; apply: negnK. Qed.\n\nLemma widen_partn m pi n :\n  n <= m -> n`_pi = \\prod_(0 <= p < m.+1 | p \\in pi) p ^ logn p n.\nProof.\nmove=> le_n_m; rewrite big_mkcond /=.\nrewrite [n`_pi](big_nat_widen _ _ m.+1) // big_mkcond /=.\napply: eq_bigr => p _; rewrite ltnS lognE.\nby case: and3P => [[_ n_gt0 p_dv_n]|]; rewrite ?if_same // andbC dvdn_leq.\nQed.\n\nLemma partn0 pi : 0`_pi = 1.\nProof. by apply: big1_seq => [] [|n]; rewrite andbC. Qed.\n\nLemma partn1 pi : 1`_pi = 1.\nProof. by apply: big1_seq => [] [|[|n]]; rewrite andbC. Qed.\n\nLemma partnM pi m n : m > 0 -> n > 0 -> (m * n)`_pi = m`_pi * n`_pi.\nProof.\nhave le_pmul m' n': m' > 0 -> n' <= m' * n' by move/prednK <-; apply: leq_addr.\nmove=> mpos npos; rewrite !(@widen_partn (n * m)) 3?(le_pmul, mulnC) //.\nrewrite !big_mkord -big_split; apply: eq_bigr => p _ /=.\nby rewrite lognM // expnD.\nQed.\n\nLemma partnX pi m n : (m ^ n)`_pi = m`_pi ^ n.\nProof.\nelim: n => [|n IHn]; first exact: partn1.\nrewrite expnS; case: (posnP m) => [->|m_gt0]; first by rewrite partn0 exp1n.\nby rewrite expnS partnM ?IHn // expn_gt0 m_gt0.\nQed.\n\nLemma partn_dvd pi m n : n > 0 -> m %| n -> m`_pi %| n`_pi.\nProof.\nmove=> n_gt0 dvmn; case/dvdnP: dvmn n_gt0 => q ->{n}.\nby rewrite muln_gt0 => /andP[q_gt0 m_gt0]; rewrite partnM ?dvdn_mull.\nQed.\n\nLemma p_part p n : n`_p = p ^ logn p n.\nProof.\ncase (posnP (logn p n)) => [log0 |].\n  by rewrite log0 [n`_p]big1_seq // => q; case/andP; move/eqnP->; rewrite log0.\nrewrite logn_gt0 mem_primes; case/and3P=> _ n_gt0 dv_p_n.\nhave le_p_n: p < n.+1 by rewrite ltnS dvdn_leq.\nby rewrite [n`_p]big_mkord (big_pred1 (Ordinal le_p_n)).\nQed.\n\nLemma p_part_eq1 p n : (n`_p == 1) = (p \\notin \\pi(n)).\nProof.\nrewrite mem_primes p_part lognE; case: and3P => // [[p_pr _ _]].\nby rewrite -dvdn1 pfactor_dvdn // logn1.\nQed.\n\nLemma p_part_gt1 p n : (n`_p > 1) = (p \\in \\pi(n)).\nProof. by rewrite ltn_neqAle part_gt0 andbT eq_sym p_part_eq1 negbK. Qed.\n\nLemma primes_part pi n : primes n`_pi = filter (mem pi) (primes n).\nProof.\nhave ltnT := ltn_trans.\ncase: (posnP n) => [-> | n_gt0]; first by rewrite partn0.\napply: (eq_sorted_irr ltnT ltnn); rewrite ?(sorted_primes, sorted_filter) //.\nmove=> p; rewrite mem_filter /= !mem_primes n_gt0 part_gt0 /=.\napply/andP/and3P=> [[p_pr] | [pi_p p_pr dv_p_n]].\n  rewrite /partn; apply big_ind => [|n1 n2 IHn1 IHn2|q pi_q].\n  - by rewrite dvdn1; case: eqP p_pr => // ->.\n  - by rewrite Euclid_dvdM //; case/orP.\n  rewrite -{1}(expn1 p) pfactor_dvdn // lognX muln_gt0.\n  rewrite logn_gt0 mem_primes n_gt0 - andbA /=; case/and3P=> pr_q dv_q_n.\n  by rewrite logn_prime //; case: eqP => // ->.\nhave le_p_n: p < n.+1 by rewrite ltnS dvdn_leq.\nrewrite [n`_pi]big_mkord (bigD1 (Ordinal le_p_n)) //= dvdn_mulr //.\nby rewrite lognE p_pr n_gt0 dv_p_n expnS dvdn_mulr.\nQed.\n\nLemma filter_pi_of n m : n < m -> filter \\pi(n) (index_iota 0 m) = primes n.\nProof.\nmove=> lt_n_m; have ltnT := ltn_trans; apply: (eq_sorted_irr ltnT ltnn).\n- by rewrite sorted_filter // iota_ltn_sorted.\n- exact: sorted_primes.\nmove=> p; rewrite mem_filter mem_index_iota /= mem_primes; case: and3P => //.\nby case=> _ n_gt0 dv_p_n; apply: leq_ltn_trans lt_n_m; apply: dvdn_leq.\nQed.\n\nLemma partn_pi n : n > 0 -> n`_\\pi(n) = n.\nProof.\nmove=> n_gt0; rewrite {3}(prod_prime_decomp n_gt0) prime_decompE big_map.\nby rewrite -[n`__]big_filter filter_pi_of.\nQed.\n\nLemma partnT n : n > 0 -> n`_predT = n.\nProof.\nmove=> n_gt0; rewrite -{2}(partn_pi n_gt0) {2}/partn big_mkcond /=.\nby apply: eq_bigr => p _; rewrite -logn_gt0; case: (logn p _).\nQed.\n\nLemma partnC pi n : n > 0 -> n`_pi * n`_pi^' = n.\nProof.\nmove=> n_gt0; rewrite -{3}(partnT n_gt0) /partn.\ndo 2!rewrite mulnC big_mkcond /=; rewrite -big_split; apply: eq_bigr => p _ /=.\nby rewrite mulnC inE /=; case: (p \\in pi); rewrite /= (muln1, mul1n).\nQed.\n\nLemma dvdn_part pi n : n`_pi %| n.\nProof. by case: n => // n; rewrite -{2}[n.+1](@partnC pi) // dvdn_mulr. Qed.\n\nLemma logn_part p m : logn p m`_p = logn p m.\nProof.\ncase p_pr: (prime p); first by rewrite p_part pfactorK.\nby rewrite lognE (lognE p m) p_pr.\nQed.\n    \nLemma partn_lcm pi m n : m > 0 -> n > 0 -> (lcmn m n)`_pi = lcmn m`_pi n`_pi.\nProof.\nmove=> m_gt0 n_gt0; have p_gt0: lcmn m n > 0 by rewrite lcmn_gt0 m_gt0.\napply/eqP; rewrite eqn_dvd dvdn_lcm !partn_dvd ?dvdn_lcml ?dvdn_lcmr //.\nrewrite -(dvdn_pmul2r (part_gt0 pi^' (lcmn m n))) partnC // dvdn_lcm !andbT.\nrewrite -{1}(partnC pi m_gt0) andbC -{1}(partnC pi n_gt0).\nby rewrite !dvdn_mul ?partn_dvd ?dvdn_lcml ?dvdn_lcmr.\nQed.\n\nLemma partn_gcd pi m n : m > 0 -> n > 0 -> (gcdn m n)`_pi = gcdn m`_pi n`_pi.\nProof.\nmove=> m_gt0 n_gt0; have p_gt0: gcdn m n > 0 by rewrite gcdn_gt0 m_gt0.\napply/eqP; rewrite eqn_dvd dvdn_gcd !partn_dvd ?dvdn_gcdl ?dvdn_gcdr //=.\nrewrite -(dvdn_pmul2r (part_gt0 pi^' (gcdn m n))) partnC // dvdn_gcd.\nrewrite -{3}(partnC pi m_gt0) andbC -{3}(partnC pi n_gt0).\nby rewrite !dvdn_mul ?partn_dvd ?dvdn_gcdl ?dvdn_gcdr.\nQed.\n\nLemma partn_biglcm (I : finType) (P : pred I) F pi :\n    (forall i, P i -> F i > 0) ->\n  (\\big[lcmn/1%N]_(i | P i) F i)`_pi = \\big[lcmn/1%N]_(i | P i) (F i)`_pi.\nProof.\nmove=> F_gt0; set m := \\big[lcmn/1%N]_(i | P i) F i.\nhave m_gt0: 0 < m by elim/big_ind: m => // p q p_gt0; rewrite lcmn_gt0 p_gt0.\napply/eqP; rewrite eqn_dvd andbC; apply/andP; split.\n  by apply/dvdn_biglcmP=> i Pi; rewrite partn_dvd // (@biglcmn_sup _ i).\nrewrite -(dvdn_pmul2r (part_gt0 pi^' m)) partnC //.\napply/dvdn_biglcmP=> i Pi; rewrite -(partnC pi (F_gt0 i Pi)) dvdn_mul //.\n  by rewrite (@biglcmn_sup _ i).\nby rewrite partn_dvd // (@biglcmn_sup _ i).\nQed.\n\nLemma partn_biggcd (I : finType) (P : pred I) F pi :\n    #|SimplPred P| > 0 -> (forall i, P i -> F i > 0) ->\n  (\\big[gcdn/0]_(i | P i) F i)`_pi = \\big[gcdn/0]_(i | P i) (F i)`_pi.\nProof.\nmove=> ntP F_gt0; set d := \\big[gcdn/0]_(i | P i) F i.\nhave d_gt0: 0 < d.\n  case/card_gt0P: ntP => i /= Pi; have:= F_gt0 i Pi.\n  rewrite !lt0n -!dvd0n; apply: contra => dv0d.\n  by rewrite (dvdn_trans dv0d) // (@biggcdn_inf _ i).\napply/eqP; rewrite eqn_dvd; apply/andP; split.\n  by apply/dvdn_biggcdP=> i Pi; rewrite partn_dvd ?F_gt0 // (@biggcdn_inf _ i).\nrewrite -(dvdn_pmul2r (part_gt0 pi^' d)) partnC //.\napply/dvdn_biggcdP=> i Pi; rewrite -(partnC pi (F_gt0 i Pi)) dvdn_mul //.\n  by rewrite (@biggcdn_inf _ i).\nby rewrite partn_dvd ?F_gt0 // (@biggcdn_inf _ i).\nQed.\n\nLemma sub_in_pnat pi rho n :\n  {in \\pi(n), {subset pi <= rho}} -> pi.-nat n -> rho.-nat n.\nProof.\nrewrite /pnat => subpi /andP[-> pi_n].\nby apply/allP=> p pr_p; apply: subpi => //; apply: (allP pi_n).\nQed.\n\nLemma eq_in_pnat pi rho n : {in \\pi(n), pi =i rho} -> pi.-nat n = rho.-nat n.\nProof. by move=> eqpi; apply/idP/idP; apply: sub_in_pnat => p /eqpi->. Qed.\n\nLemma eq_pnat pi rho n : pi =i rho -> pi.-nat n = rho.-nat n.\nProof. by move=> eqpi; apply: eq_in_pnat => p _. Qed.\n\nLemma pnatNK pi n : pi^'^'.-nat n = pi.-nat n.\nProof. exact: eq_pnat (negnK pi). Qed.\n\nLemma pnatI pi rho n : [predI pi & rho].-nat n = pi.-nat n && rho.-nat n.\nProof. by rewrite /pnat andbCA all_predI !andbA andbb. Qed.\n\nLemma pnat_mul pi m n : pi.-nat (m * n) = pi.-nat m && pi.-nat n.\nProof.\nrewrite /pnat muln_gt0 andbCA -andbA andbCA.\ncase: posnP => // n_gt0; case: posnP => //= m_gt0.\napply/allP/andP=> [pi_mn | [pi_m pi_n] p].\n  by split; apply/allP=> p m_p; apply: pi_mn; rewrite primes_mul // m_p ?orbT.\nby rewrite primes_mul // => /orP[]; [apply: (allP pi_m) | apply: (allP pi_n)].\nQed.\n\nLemma pnat_exp pi m n : pi.-nat (m ^ n) = pi.-nat m || (n == 0).\nProof. by case: n => [|n]; rewrite orbC // /pnat expn_gt0 orbC primes_exp. Qed.\n\nLemma part_pnat pi n : pi.-nat n`_pi.\nProof.\nrewrite /pnat primes_part part_gt0.\nby apply/allP=> p; rewrite mem_filter => /andP[].\nQed.\n\nLemma pnatE pi p : prime p -> pi.-nat p = (p \\in pi).\nProof. by move=> pr_p; rewrite /pnat prime_gt0 ?primes_prime //= andbT. Qed.\n\nLemma pnat_id p : prime p -> p.-nat p.\nProof. by move=> pr_p; rewrite pnatE ?inE /=. Qed.\n\nLemma coprime_pi' m n : m > 0 -> n > 0 -> coprime m n = \\pi(m)^'.-nat n.\nProof.\nby move=> m_gt0 n_gt0; rewrite /pnat n_gt0 all_predC coprime_has_primes.\nQed.\n\nLemma pnat_pi n : n > 0 -> \\pi(n).-nat n.\nProof. by rewrite /pnat => ->; apply/allP. Qed.\n\nLemma pi_of_dvd m n : m %| n -> n > 0 -> {subset \\pi(m) <= \\pi(n)}.\nProof.\nmove=> m_dv_n n_gt0 p; rewrite !mem_primes n_gt0 => /and3P[-> _ p_dv_m].\nexact: dvdn_trans p_dv_m m_dv_n.\nQed.\n\nLemma pi_ofM m n : m > 0 -> n > 0 -> \\pi(m * n) =i [predU \\pi(m) & \\pi(n)].\nProof. by move=> m_gt0 n_gt0 p; apply: primes_mul. Qed.\n\nLemma pi_of_part pi n : n > 0 -> \\pi(n`_pi) =i [predI \\pi(n) & pi].\nProof. by move=> n_gt0 p; rewrite /pi_of primes_part mem_filter andbC. Qed.\n\nLemma pi_of_exp p n : n > 0 -> \\pi(p ^ n) = \\pi(p).\nProof. by move=> n_gt0; rewrite /pi_of primes_exp. Qed.\n\nLemma pi_of_prime p : prime p -> \\pi(p) =i (p : nat_pred).\nProof. by move=> pr_p q; rewrite /pi_of primes_prime // mem_seq1. Qed.\n\nLemma p'natEpi p n : n > 0 -> p^'.-nat n = (p \\notin \\pi(n)).\nProof. by case: n => // n _; rewrite /pnat all_predC has_pred1. Qed.\n\nLemma p'natE p n : prime p -> p^'.-nat n = ~~ (p %| n).\nProof.\ncase: n => [|n] p_pr; first by case: p p_pr.\nby rewrite p'natEpi // mem_primes p_pr.\nQed.\n\nLemma pnatPpi pi n p : pi.-nat n -> p \\in \\pi(n) -> p \\in pi.\nProof. by case/andP=> _ /allP; apply. Qed.\n\nLemma pnat_dvd m n pi : m %| n -> pi.-nat n -> pi.-nat m.\nProof. by case/dvdnP=> q ->; rewrite pnat_mul; case/andP. Qed.\n\nLemma pnat_div m n pi : m %| n -> pi.-nat n -> pi.-nat (n %/ m).\nProof.\ncase/dvdnP=> q ->; rewrite pnat_mul andbC => /andP[].\nby case: m => // m _; rewrite mulnK.\nQed.\n\nLemma pnat_coprime pi m n : pi.-nat m -> pi^'.-nat n -> coprime m n.\nProof.\ncase/andP=> m_gt0 pi_m /andP[n_gt0 pi'_n]; rewrite coprime_has_primes //.\nby apply/hasPn=> p /(allP pi'_n); apply/contra/allP.\nQed.\n\nLemma p'nat_coprime pi m n : pi^'.-nat m -> pi.-nat n -> coprime m n.\nProof. by move=> pi'm pi_n; rewrite (pnat_coprime pi'm) ?pnatNK. Qed.\n\nLemma sub_pnat_coprime pi rho m n :\n  {subset rho <= pi^'} -> pi.-nat m -> rho.-nat n -> coprime m n.\nProof.\nby move=> pi'rho pi_m; move/(sub_in_pnat (in1W pi'rho)); apply: pnat_coprime.\nQed.\n\nLemma coprime_partC pi m n : coprime m`_pi n`_pi^'.\nProof. by apply: (@pnat_coprime pi); apply: part_pnat. Qed.\n\nLemma pnat_1 pi n : pi.-nat n -> pi^'.-nat n -> n = 1.\nProof.\nby move=> pi_n pi'_n; rewrite -(eqnP (pnat_coprime pi_n pi'_n)) gcdnn.\nQed.\n\nLemma part_pnat_id pi n : pi.-nat n -> n`_pi = n.\nProof.\ncase/andP=> n_gt0 pi_n.\nrewrite -{2}(partnT n_gt0) /partn big_mkcond; apply: eq_bigr=> p _.\ncase: (posnP (logn p n)) => [-> |]; first by rewrite if_same.\nby rewrite logn_gt0 => /(allP pi_n)/= ->.\nQed.\n\nLemma part_p'nat pi n : pi^'.-nat n -> n`_pi = 1.\nProof.\ncase/andP=> n_gt0 pi'_n; apply: big1_seq => p /andP[pi_p _].\ncase: (posnP (logn p n)) => [-> //|].\nby rewrite logn_gt0; move/(allP pi'_n); case/negP.\nQed.\n\nLemma partn_eq1 pi n : n > 0 -> (n`_pi == 1) = pi^'.-nat n.\nProof.\nmove=> n_gt0; apply/eqP/idP=> [pi_n_1|]; last exact: part_p'nat.\nby rewrite -(partnC pi n_gt0) pi_n_1 mul1n part_pnat.\nQed.\n\nLemma pnatP pi n :\n  n > 0 -> reflect (forall p, prime p -> p %| n -> p \\in pi) (pi.-nat n).\nProof.\nmove=> n_gt0; rewrite /pnat n_gt0.\napply: (iffP allP) => /= pi_n p => [pr_p p_n|].\n  by rewrite pi_n // mem_primes pr_p n_gt0.\nby rewrite mem_primes n_gt0 /=; case/andP; move: p.\nQed.\n\nLemma pi_pnat pi p n : p.-nat n -> p \\in pi -> pi.-nat n.\nProof.\nmove=> p_n pi_p; have [n_gt0 _] := andP p_n.\nby apply/pnatP=> // q q_pr /(pnatP _ n_gt0 p_n _ q_pr)/eqnP->.\nQed.\n\nLemma p_natP p n : p.-nat n -> {k | n = p ^ k}.\nProof. by move=> p_n; exists (logn p n); rewrite -p_part part_pnat_id. Qed.\n\nLemma pi'_p'nat pi p n : pi^'.-nat n -> p \\in pi -> p^'.-nat n.\nProof.\nmove=> pi'n pi_p; apply: sub_in_pnat pi'n => q _.\nby apply: contraNneq => ->.\nQed.\n \nLemma pi_p'nat p pi n : pi.-nat n -> p \\in pi^' -> p^'.-nat n.\nProof. by move=> pi_n; apply: pi'_p'nat; rewrite pnatNK. Qed.\n \nLemma partn_part pi rho n : {subset pi <= rho} -> n`_rho`_pi = n`_pi.\nProof.\nmove=> pi_sub_rho; have [->|n_gt0] := posnP n; first by rewrite !partn0 partn1.\nrewrite -{2}(partnC rho n_gt0) partnM //.\nsuffices: pi^'.-nat n`_rho^' by move/part_p'nat->; rewrite muln1.\nby apply: sub_in_pnat (part_pnat _ _) => q _; apply/contra/pi_sub_rho.\nQed.\n\nLemma partnI pi rho n : n`_[predI pi & rho] = n`_pi`_rho.\nProof.\nrewrite -(@partnC [predI pi & rho] _`_rho) //.\nsymmetry; rewrite 2?partn_part; try by move=> p /andP [].\nrewrite mulnC part_p'nat ?mul1n // pnatNK pnatI part_pnat andbT.\nexact: pnat_dvd (dvdn_part _ _) (part_pnat _ _).\nQed.\n\nLemma odd_2'nat n : odd n = 2^'.-nat n.\nProof. by case: n => // n; rewrite p'natE // dvdn2 negbK. Qed.\n\nEnd PnatTheory.\nHint Resolve part_gt0 : core.\n\n(************************************)\n(* Properties of the divisors list. *)\n(************************************)\n\nLemma divisors_correct n : n > 0 ->\n  [/\\ uniq (divisors n), sorted leq (divisors n)\n    & forall d, (d \\in divisors n) = (d %| n)].\nProof.\nmove/prod_prime_decomp=> def_n; rewrite {4}def_n {def_n}.\nhave: all prime (primes n) by apply/allP=> p; rewrite mem_primes; case/andP.\nhave:= primes_uniq n; rewrite /primes /divisors; move/prime_decomp: n.\nelim=> [|[p e] pd] /=; first by split=> // d; rewrite big_nil dvdn1 mem_seq1.\nrewrite big_cons /=; move: (foldr _ _ pd) => divs.\nmove=> IHpd /andP[npd_p Upd] /andP[pr_p pr_pd].\nhave lt0p: 0 < p by apply: prime_gt0.\nhave {IHpd Upd}[Udivs Odivs mem_divs] := IHpd Upd pr_pd.\nhave ndivs_p m: p * m \\notin divs.\n  suffices: p \\notin divs; rewrite !mem_divs.\n    by apply: contra => /dvdnP[n ->]; rewrite mulnCA dvdn_mulr.\n  have ndv_p_1: ~~(p %| 1) by rewrite dvdn1 neq_ltn orbC prime_gt1.\n  rewrite big_seq; elim/big_ind: _ => [//|u v npu npv|[q f] /= pd_qf].\n    by rewrite Euclid_dvdM //; apply/norP.\n  elim: (f) => // f'; rewrite expnS Euclid_dvdM // orbC negb_or => -> {f'}/=.\n  have pd_q: q \\in unzip1 pd by apply/mapP; exists (q, f).\n  by apply: contra npd_p; rewrite dvdn_prime2 // ?(allP pr_pd) // => /eqP->.\nelim: e => [|e] /=; first by split=> // d; rewrite mul1n.\nhave Tmulp_inj: injective (NatTrec.mul p).\n  by move=> u v /eqP; rewrite !natTrecE eqn_pmul2l // => /eqP.\nmove: (iter e _ _) => divs' [Udivs' Odivs' mem_divs']; split=> [||d].\n- rewrite merge_uniq cat_uniq map_inj_uniq // Udivs Udivs' andbT /=.\n  apply/hasP=> [[d dv_d /mapP[d' _ def_d]]].\n  by case/idPn: dv_d; rewrite def_d natTrecE.\n- rewrite (merge_sorted leq_total) //; case: (divs') Odivs' => //= d ds.\n  rewrite (@map_path _ _ _ _ leq xpred0) ?has_pred0 // => u v _.\n  by rewrite !natTrecE leq_pmul2l.\nrewrite mem_merge mem_cat; case dv_d_p: (p %| d).\n  case/dvdnP: dv_d_p => d' ->{d}; rewrite mulnC (negbTE (ndivs_p d')) orbF.\n  rewrite expnS -mulnA dvdn_pmul2l // -mem_divs'.\n  by rewrite -(mem_map Tmulp_inj divs') natTrecE.\ncase pdiv_d: (_ \\in _).\n  by case/mapP: pdiv_d dv_d_p => d' _ ->; rewrite natTrecE dvdn_mulr.\nrewrite mem_divs Gauss_dvdr // coprime_sym.\nby rewrite coprime_expl ?prime_coprime ?dv_d_p.\nQed.\n\nLemma sorted_divisors n : sorted leq (divisors n).\nProof. by case: (posnP n) => [-> | /divisors_correct[]]. Qed.\n\nLemma divisors_uniq n : uniq (divisors n).\nProof. by case: (posnP n) => [-> | /divisors_correct[]]. Qed.\n\nLemma sorted_divisors_ltn n : sorted ltn (divisors n).\nProof. by rewrite ltn_sorted_uniq_leq divisors_uniq sorted_divisors. Qed.\n\nLemma dvdn_divisors d m : 0 < m -> (d %| m) = (d \\in divisors m).\nProof. by case/divisors_correct. Qed.\n\nLemma divisor1 n : 1 \\in divisors n.\nProof. by case: n => // n; rewrite -dvdn_divisors // dvd1n. Qed.\n\nLemma divisors_id n : 0 < n -> n \\in divisors n.\nProof. by move/dvdn_divisors <-. Qed.\n\n(* Big sum / product lemmas*)\n\nLemma dvdn_sum d I r (K : pred I) F :\n  (forall i, K i -> d %| F i) -> d %| \\sum_(i <- r | K i) F i.\nProof. by move=> dF; elim/big_ind: _ => //; apply: dvdn_add. Qed.\n\nLemma dvdn_partP n m : 0 < n ->\n  reflect (forall p, p \\in \\pi(n) -> n`_p %| m) (n %| m).\nProof.\nmove=> n_gt0; apply: (iffP idP) => n_dvd_m => [p _|].\n  by apply: dvdn_trans n_dvd_m; apply: dvdn_part.\nhave [-> // | m_gt0] := posnP m.\nrewrite -(partnT n_gt0) -(partnT m_gt0).\nrewrite !(@widen_partn (m + n)) ?leq_addl ?leq_addr // /in_mem /=.\nelim/big_ind2: _ => // [* | q _]; first exact: dvdn_mul.\nhave [-> // | ] := posnP (logn q n); rewrite logn_gt0 => q_n.\nhave pr_q: prime q by move: q_n; rewrite mem_primes; case/andP.\nby have:= n_dvd_m q q_n; rewrite p_part !pfactor_dvdn // pfactorK.\nQed.\n\nLemma modn_partP n a b : 0 < n ->\n  reflect (forall p : nat, p \\in \\pi(n) -> a = b %[mod n`_p]) (a == b %[mod n]).\nProof.\nmove=> n_gt0; wlog le_b_a: a b / b <= a.\n  move=> IH; case: (leqP b a) => [|/ltnW] /IH {IH}// IH.\n  by rewrite eq_sym; apply: (iffP IH) => eqab p; move/eqab.\nrewrite eqn_mod_dvd //; apply: (iffP (dvdn_partP _ n_gt0)) => eqab p /eqab;\n  by rewrite -eqn_mod_dvd // => /eqP.\nQed.\n\n(* The Euler totient function *)\n\nLemma totientE n :\n  n > 0 -> totient n = \\prod_(p <- primes n) (p.-1 * p ^ (logn p n).-1).\nProof.\nmove=> n_gt0; rewrite /totient n_gt0 prime_decompE unlock.\nby elim: (primes n) => //= [p pr ->]; rewrite !natTrecE.\nQed.\n\nLemma totient_gt0 n : (0 < totient n) = (0 < n).\nProof.\ncase: n => // n; rewrite totientE // big_seq_cond prodn_cond_gt0 // => p.\nby rewrite mem_primes muln_gt0 expn_gt0; case: p => [|[|]].\nQed.\n\nLemma totient_pfactor p e :\n  prime p -> e > 0 -> totient (p ^ e) = p.-1 * p ^ e.-1.\nProof.\nmove=> p_pr e_gt0; rewrite totientE ?expn_gt0 ?prime_gt0 //.\nby rewrite primes_exp // primes_prime // unlock /= muln1 pfactorK.\nQed.\n\nLemma totient_prime p : prime p -> totient p = p.-1.\nProof. by move=> p_prime; rewrite -{1}[p]expn1 totient_pfactor // muln1. Qed.\n\nLemma totient_coprime m n :\n  coprime m n -> totient (m * n) = totient m * totient n.\nProof.\nmove=> co_mn; have [-> //| m_gt0] := posnP m.\nhave [->|n_gt0] := posnP n; first by rewrite !muln0.\nrewrite !totientE ?muln_gt0 ?m_gt0 //.\nhave /(perm_big _)->: perm_eq (primes (m * n)) (primes m ++ primes n).\n  apply: uniq_perm => [||p]; first exact: primes_uniq.\n    by rewrite cat_uniq !primes_uniq -coprime_has_primes // co_mn.\n  by rewrite mem_cat primes_mul.\nrewrite big_cat /= !big_seq.\ncongr (_ * _); apply: eq_bigr => p; rewrite mem_primes => /and3P[_ _ dvp].\n  rewrite (mulnC m) logn_Gauss //; move: co_mn.\n  by rewrite -(divnK dvp) coprime_mull => /andP[].\nrewrite logn_Gauss //; move: co_mn.\nby rewrite coprime_sym -(divnK dvp) coprime_mull => /andP[].\nQed.\n\nLemma totient_count_coprime n : totient n = \\sum_(0 <= d < n) coprime n d.\nProof.\nelim/ltn_ind: n => // n IHn.\ncase: (leqP n 1) => [|lt1n]; first by rewrite unlock; case: (n) => [|[]].\npose p := pdiv n; have p_pr: prime p by apply: pdiv_prime.\nhave p1 := prime_gt1 p_pr; have p0 := ltnW p1.\npose np := n`_p; pose np' := n`_p^'.\nhave co_npp': coprime np np' by rewrite coprime_partC.\nhave [n0 np0 np'0]: [/\\ n > 0, np > 0 & np' > 0] by rewrite ltnW ?part_gt0.\nhave def_n: n = np * np' by rewrite partnC.\nhave lnp0: 0 < logn p n by rewrite lognE p_pr n0 pdiv_dvd.\npose in_mod k (k0 : k > 0) d := Ordinal (ltn_pmod d k0).\nrewrite {1}def_n totient_coprime // {IHn}(IHn np') ?big_mkord; last first.\n  by rewrite def_n ltn_Pmull // /np p_part -(expn0 p) ltn_exp2l.\nhave ->: totient np = #|[pred d : 'I_np | coprime np d]|.\n  rewrite [np in LHS]p_part totient_pfactor //=; set q := p ^ _.\n  apply: (@addnI (1 * q)); rewrite -mulnDl [1 + _]prednK // mul1n.\n  have def_np: np = p * q by rewrite -expnS prednK // -p_part.\n  pose mulp := [fun d : 'I_q => in_mod _ np0 (p * d)].\n  rewrite -def_np -{1}[np]card_ord -(cardC (mem (codom mulp))).\n  rewrite card_in_image => [|[d1 ltd1] [d2 ltd2] /= _ _ []]; last first.\n    move/eqP; rewrite def_np -!muln_modr ?modn_small //.\n    by rewrite eqn_pmul2l // => eq_op12; apply/eqP.\n  rewrite card_ord; congr (q + _); apply: eq_card => d /=.\n  rewrite !inE [np in coprime np _]p_part coprime_pexpl ?prime_coprime //.\n  congr (~~ _); apply/codomP/idP=> [[d' -> /=] | /dvdnP[r def_d]].\n    by rewrite def_np -muln_modr // dvdn_mulr.\n  do [rewrite mulnC; case: d => d ltd /=] in def_d *.\n  have ltr: r < q by rewrite -(ltn_pmul2l p0) -def_np -def_d.\n  by exists (Ordinal ltr); apply: val_inj; rewrite /= -def_d modn_small.\npose h (d : 'I_n) := (in_mod _ np0 d, in_mod _ np'0 d).\npose h' (d : 'I_np * 'I_np') := in_mod _ n0 (chinese np np' d.1 d.2).\nrewrite -!big_mkcond -sum_nat_const pair_big (reindex_onto h h') => [|[d d'] _].\n  apply: eq_bigl => [[d ltd] /=]; rewrite !inE /= -val_eqE /= andbC.\n  rewrite !coprime_modr def_n -chinese_mod // -coprime_mull -def_n.\n  by rewrite modn_small ?eqxx.\napply/eqP; rewrite /eq_op /= /eq_op /= !modn_dvdm ?dvdn_part //.\nby rewrite chinese_modl // chinese_modr // !modn_small ?eqxx ?ltn_ord.\nQed.\n\n\n\n", "meta": {"author": "gares", "repo": "mathcomp", "sha": "f4ea1abac523107baf16e3cf528752b22ad8fdb5", "save_path": "github-repos/coq/gares-mathcomp", "path": "github-repos/coq/gares-mathcomp/mathcomp-f4ea1abac523107baf16e3cf528752b22ad8fdb5/mathcomp/ssreflect/prime.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240721511739, "lm_q2_score": 0.8031737892899221, "lm_q1q2_score": 0.6949252966145153}}
{"text": "Require Import List.\nRequire Import Omega.\nRequire Import LibUtils.\n\nRequire Import VectorDef.\nRequire Vector.\n\nSection Vector.\n  \nDefinition vector (T:Type) (n:nat) := Vector.t T n.\n\nDefinition vnil {T} : vector T 0 := nil T.\n\nDefinition vcons {T} (n:nat) (c:T) (v:vector T n) : vector T (S n) :=\n  cons T c n v.\n\nDefinition vappend {T} (n1 n2:nat) (v1:vector T n1) (v2:vector T n2) : vector T (n1 + n2) \n  := append v1 v2.\n\nDefinition vmap {A B} {n} (f:A->B) (v : vector A n) : vector B n :=  map f v.\n\nDefinition vhd {T} {n:nat} (v : vector T (S n)):T := hd v.\n\nDefinition vtl {T} {n:nat} (v : vector T (S n)) : vector T n := tl v.\n\nDefinition vlast {T} {n:nat} (v : vector T (S n)) := last v.\n\nDefinition vnth {T} {n:nat}  (v : vector T n) (i:nat | i<n) : T\n  := nth v (Fin.of_nat_lt (proj2_sig i)).\n\nDefinition vec_fun {T} {n:nat} (v:vector T n) : {i:nat | i<n} -> T :=\n  fun i => vnth v i.\n\nProgram Definition ConstVector {T} (n:nat) (c:T) : vector T n\n  := of_list (repeat c n).\nNext Obligation.\n  now rewrite repeat_length.\nQed.  \n\nProgram Definition build_vector {T} {n:nat} (v:{n':nat | n' < n}%nat -> T) : vector T n\n  := of_list (Vector.vector_to_list v).\nNext Obligation.\n  apply Vector.vector_to_list_length.\nQed.\n\nLemma to_list_length {T} {n:nat} (v : vector T n) : length (to_list v) = n.\n  induction v; simpl; trivial.\n  now f_equal.\nQed.\n\nProgram Definition vcombine {T1 T2} {n:nat} (v1:vector T1 n) (v2:vector T2 n): vector (T1*T2) n :=\n  of_list (combine (to_list v1) (to_list v2)).\nNext Obligation.\n  rewrite combine_length.\n  rewrite to_list_length, to_list_length.\n  apply Nat.min_id.\nQed.\n\nDefinition vector_zip {T1 T2} {n:nat} (v1:vector T1 n) (v2:vector T2 n): vector (T1*T2) n :=\n  vcombine v1 v2.\n\nDefinition vmap2 {A B C} {n} (f:A->B->C) (v1 : vector A n) (v2 : vector B n) : vector C n\n  :=  Vector.map2 f v1 v2.\n\nDefinition vmap4 {A B} {n} (f:A->A->A->A->B) (v1 v2 v3 v4 : vector A n) : vector B n :=\n  vmap2 (fun '(a1,a2) '(a3,a4) => f a1 a2 a3 a4) (vcombine v1 v2) (vcombine v3 v4).\n\nProgram Definition vectoro_to_ovector {T} {n} (v:vector (option T) n) : option (vector T n) \n  := match listo_to_olist (to_list v) with\n     | None => None\n     | Some l => Some (of_list l)\n     end.\nNext Obligation.\n  symmetry in Heq_anonymous.\n  apply listo_to_olist_some in Heq_anonymous.\n  rewrite <- map_length with (f := Some).\n  rewrite <- Heq_anonymous.\n  now apply to_list_length.\nQed.\n\nDefinition vforall {A} {m:nat} (P: A -> Prop) (v:vector A m) : Prop\n  := Vector.Forall P v.\n\nEnd Vector.\n\nSection Matrix.\n  \nDefinition matrix (T:Type) (n m : nat) := vector (vector T m) n.\n\nDefinition mat_fun {T:Type} (n m : nat) (mat : matrix T n m ) :\n  {n':nat | n' < n}%nat -> {m':nat | m' < m}%nat -> T :=\n  fun i => fun j => vnth (vnth mat i) j.\n\nDefinition mmap {A B} {n m} (f:A->B) (mat : matrix A n m) : matrix B n m :=\n  vmap (vmap f) mat.\n\nDefinition mnth {T} {n m :nat}  (v : matrix T n m) (i:nat | i<n) (j:nat | j<m) : T\n  := vnth (vnth v i) j.\n\nDefinition mcombine {T1 T2} {n m : nat} (mat1 : matrix T1 n m) (mat2 : matrix T2 n m) : matrix (T1*T2) n m :=\n  vmap (fun '(a,b) => vcombine a b) (vcombine mat1 mat2).\n\nDefinition matrix_zip {T1 T2} {n m : nat} (mat1 : matrix T1 n m) (mat2 : matrix T2 n m) : matrix (T1*T2) n m := mcombine mat1 mat2.\n\nDefinition build_matrix {T} {n m:nat} \n        (mat:{n':nat | n' < n}%nat -> {m':nat | m' < m}%nat -> T) : matrix T n m\n  := vmap build_vector (build_vector mat).\n\nDefinition transpose {T} {m n : nat} (mat:matrix T m n) : matrix T n m\n  := build_matrix (fun i j => mnth mat j i).\n\nFixpoint ConstMatrix {T} (n m : nat) (c:T) : matrix T n m := \n  ConstVector n (ConstVector m c).\n\nDefinition matrixo_to_omatrix {T} {m n} (v:matrix (option T) m n) : option (matrix T m n)\n  := vectoro_to_ovector (vmap vectoro_to_ovector v).\n\nDefinition mmap2 {A B C} {n m} (f:A->B->C) (v1 : matrix A n m) (v2 : matrix B n m) : matrix C n m :=  vmap2 (fun r1 r2 => vmap2 f r1 r2) v1 v2.\n\nDefinition mforall {A} {m n:nat} (P: A -> Prop) (m:matrix A m n) : Prop\n  := vforall (fun x => vforall P x) m.\n\nEnd Matrix.\n\nSection Tensor.\nFixpoint tensor T (l:list nat) : Type\n  := match l with\n     | List.nil => T\n     | x::l' => vector (tensor T l') x\n     end.\n\nLemma tensor0 T : tensor T List.nil = T.\nProof.\n  reflexivity.\nQed.\n\nLemma tensor1 T n : tensor T (n::List.nil) = vector T n.\nProof.\n  reflexivity.\nQed.\n\nLemma tensor_app T l1 l2 : tensor (tensor T l1) l2 = tensor T (l2++l1).\nProof.\n  revert l1.\n  induction l2; intros l1; simpl; trivial.\n  now rewrite IHl2.\nQed.\n\nFixpoint ConstTensor {T} (l : list nat) (c:T) : (tensor T l) := \n  match l with \n  | List.nil => c\n  | x::l' => ConstVector x (ConstTensor l' c)\n  end.\n\nFixpoint Tensor_map {A B} {dims:list nat} (f:A->B) : tensor A dims -> tensor B dims\n  := match dims with\n     | List.nil => fun x => f x\n     | x::l' => vmap (Tensor_map f)\n     end.\n\nDefinition scalar {T} (c:T) : tensor T List.nil := c.\n\nEnd Tensor.\n\nInductive NumericType\n  := FloatType\n   | IntTYpe.\n\nDefinition ntype_interp (n:NumericType) : Type\n  := match n with\n     | FloatType => nat\n     | IntType => Z\n     end.\n\n  Structure BigArray (ln : list nat) (T : NumericType) : Type := \n    Tensor { tdata :> list (ntype_interp T); _ : length tdata = List.fold_right Nat.mul 1%nat ln }.\n\n  Structure Array1 (n : nat) (T : NumericType) : Type := \n    array1 { a1data :> list (ntype_interp T); _ : length a1data = n}.\n\n  Structure Array2 (n m : nat) (T : NumericType) : Type := \n    array2 { a2data :> list (ntype_interp T); _ : length a2data = n * m}.\n\nDefinition tensor_abs_type  (T:NumericType) (dims:list nat) := tensor (ntype_interp T) dims.\n\nClass TensorDef :=\n  {\n  tensor_t (T:NumericType) (dims:list nat) : Type\n  ; tensor_repr {T:NumericType} {dims:list nat} : tensor_t T dims -> tensor_abs_type T dims -> Prop\n\n  ; tensor_const {T} (dims : list nat) (c:ntype_interp T) : tensor_t T dims\n  ; tensor_const_p {T} (dims : list nat) (c:ntype_interp T) : tensor_repr (tensor_const dims c) (ConstTensor dims c)\n\n  ; tensor_map {A B} {dims : list nat} (f:ntype_interp A-> ntype_interp B) (t:tensor_t A dims) : tensor_t B dims\n  ; tensor_map_p {A B} {dims : list nat} (f:ntype_interp A-> ntype_interp B)  (t:tensor_t A dims) :\n      forall r, tensor_repr t r ->\n           tensor_repr (tensor_map f t) (Tensor_map f r)\n\n  (* ; tensor_nth {A} {dims : list nat} (indices:list nat) (indices_in_range:True) (t:tensor A dims) : A *)\n  (* ; tensor_nth_p {A:Type} {dims : list nat} (indices:list nat) (indices_in_range:True) (t:tensor_t A dims) : *)\n  (*   forall r, tensor_repr t r -> *)\n  (*          tensor_repr (tensor_nth indices indices_in_range t) (tensor_nth indices indices_in_range r) *)\n  }.\n\n(*\nClass TensorDefExt {base:TensorDef} :=\n  {\n  tensor_transpose;\n  }.\n*)\n  (* ; tensor_nth {A} {dims : list nat} (indices:list nat) (indices_in_range:True) (t:tensor A dims) : A *)\n  (* ; tensor_nth_p {A:Type} {dims : list nat} (indices:list nat) (indices_in_range:True) (t:tensor_t A dims) : *)\n  (*   forall r, tensor_repr t r -> *)\n  (*          tensor_repr (tensor_nth indices indices_in_range t) (tensor_nth indices indices_in_range r) *)\n\n(* Instance trivial_TensorDef : TensorDef := *)\n(*   { *)\n(*   tensor_t := tensor; *)\n(*   tensor_repr _ _ a b := a = b *)\n(*   }. *)\n(*\nFixpoint flat_list_represent_tensor {T} {dims} (l:list A) (t:tensor T dims) : Prop\n  := \n         \nInstance BigArray_TensorDef : TensorDef\n  := {\n  tensor_t A dims := list A;\n  tensor_repr T dims (l:list A) (tensor T dims)\n  := fix \n    }.\n*)\n\nSection float_ops.\n\nRequire Import Floatish.\n\n  Context {floatish_impl:floatish}.\n  Local Open Scope float.\n\n  Definition vsum {m:nat} (v:vector float m) : float\n      := List.fold_right Fplus 0 (to_list v).\n\n  Definition msum {m n:nat} (v:matrix float m n) : float :=\n    vsum (vmap vsum v).\n\n  Definition vdot {m:nat} (v1 v2 : vector float m) : float :=\n    List.fold_right Fplus 0\n               (List.map (fun '(a,b) => a * b) \n                    (combine (to_list v1) (to_list v2))).\n\n  Definition vadd {m:nat} (v1 v2 : vector float m) :=\n    vmap (fun '(a,b) => a+b) (vcombine v1 v2).\n\n  Definition madd {m n:nat} (mat1 mat2 : matrix float m n) :=\n    mmap (fun '(a,b) => a+b) (mcombine mat1 mat2).\n\n  Definition matrix_vector_mult {n m} (l : matrix float n m)(r : vector float m) : vector float n :=\n    vmap (fun l1 => vdot l1 r) l.\n\n  Definition matrix_vector_add {n m} (l : matrix float n m) (r : vector float n) : matrix float n m := \n    build_matrix (fun i j => (vnth (vnth l i) j) + (vnth r i)).\n    \n(*\n    transpose (vmap (fun l1 => vadd l1 r) (transpose l)).\n *)\n  \n  Definition matrix_mult {n m p} (l : matrix float n m)(r : matrix float m p) : matrix float n p :=\n      build_matrix (fun i k => vsum (build_vector \n                                       (fun j => (vnth (vnth l i) j) * \n                                                 (vnth (vnth r j) k)))).\n\n(*\n    transpose (vmap (fun r1 => matrix_vector_mult l r1) (transpose r)).\n*)\n\nEnd float_ops.\n\n  \n  \n\n  \n\n", "meta": {"author": "CertRL", "repo": "CertRLanon", "sha": "ba50abfb13c9c49abda8ffaad23fe76dcd4bf6ec", "save_path": "github-repos/coq/CertRL-CertRLanon", "path": "github-repos/coq/CertRL-CertRLanon/CertRLanon-ba50abfb13c9c49abda8ffaad23fe76dcd4bf6ec/coq/utils/nvector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.694914740059813}}
{"text": "(** * 6.822 Formal Reasoning About Programs, Spring 2018 - Pset 4 *)\n\nRequire Import Frap Datatypes Orders.\nExport Datatypes Orders.\n\n(* Note: This problem set is significantly more open-ended than\n * previous problem sets in this class: proving theorems may require\n * first conceiving and proving many auxiliary lemmas. We highly\n * recommend getting started early on the problem set and taking\n * advantage of office hours. Additionally, we will provide hints\n * on the class website. You may wish to first attempt the problem\n * set without consulting the hints, but they are available if\n * you wish.\n *)\n\n(* Authors: \n * Joonwon Choi (joonwonc@csail.mit.edu),\n * Adam Chlipala (adamc@csail.mit.edu),\n * Benjamin Sherman (sherman@csail.mit.edu), \n *)\n\n(** * Correctness of Binary Search Trees (BSTs) *)\n\n(* Here we prove some correctness theorems about binary search trees (BSTs),\n * a famous data structure for finite sets, allowing fast (log-time) lookup,\n * insertion, and deletion of items.  (Actually, we won't quite achieve\n * the worst-case log-time bound here, as we will ignore the need for balancing.)\n * In this problem set, we show that insertion and deletion functions are\n * correctly defined, by proving 1) both functions preserve the BST \n * invariant, and 2) relations between the two functions and a membership\n * checker.\n *)\n\n(* We define a polymorphic datatype [t] by including OrderedType, defined in the\n * Coq standard library. [t] should be ordered, in order to define some BST\n * operations. See the ingredients of [OrderedType] by [Print OrderedType].\n *)\nInclude OrderedType.\n(* Print OrderedType. *)\n\n(* Trees (not BSTs yet!) are an inductive structure, where [Leaf] doesn't have any\n * items, whereas [Node] has an item and two subtrees.\n *)\nInductive tree :=\n| Leaf\n| Node (d : t) (l r : tree).\n\n(* Then a singleton is just a node without subtrees. *)\nDefinition Singleton (v: t) := Node v Leaf Leaf.\n\n(* In order to define the BST spec, we define some predicates:\n * [tree_forall] is a higher-order predicate that says that all\n * items in a tree satisfy a particular predicate. This is used\n * to define [tree_lt] and [tree_gt], which say that all items\n * are less than or greater than a given value, respectively.\n * Note that we reference a less-than comparison\n * [lt] associated with the type [t]. Also note that these are\n * recursive functions returning logical predicates, built with\n * the usual connectives.\n *\n * Note that, like the definitions of [sum] and [all] that we\n * gave in problem set 3, [simplify] will not directly\n * simplify some terms involving [tree_lt] and [tree_gt] since\n * they are defined in terms of [tree_forall], so you may want\n * to use the [unfold] tactic to unfold these definitions\n * if you want [simplify] to reduce them using the definition\n * of [tree_forall].\n *)\n\nFixpoint tree_forall (P : t -> Prop) (tr: tree) :=\n  match tr with\n  | Leaf => True\n  | Node v ltr rtr => P v /\\ tree_forall P ltr /\\ tree_forall P rtr\n  end.\n\nDefinition tree_lt (n: t) := tree_forall (fun v => lt v n).\n\nDefinition tree_gt (n: t) := tree_forall (fun v => lt n v).\n\n(* Using [tree_lt] and [tree_gt], a predicate for BSTs is now defined naturally. *)\nFixpoint BST (tr: tree) :=\n  match tr with\n  | Leaf => True\n  | Node v lt rt =>\n    BST lt /\\ tree_lt v lt /\\\n    BST rt /\\ tree_gt v rt\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 the value reaches a certain [Leaf].\n * You may wonder whether the tree after an insertion also satisfies [BST]....\n * Yes! That is one of things you should prove.\n * Notice our use of a function [compare] over [t], which returns one of\n * three cases, based on the relative ordering of its argument.\n *)\nFixpoint 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(* Let's define some useful functions for deletion.\n * [rightmost], as the name says, finds the rightmost item for a given tree,\n * if it exists.\n *)\nFixpoint rightmost (tr: tree) : option t :=\n  match tr with\n  | Leaf => None\n  | Node v _ rt =>\n    match rt with\n    | Leaf => Some v\n    | _ => rightmost rt\n    end\n  end.\n\n(* [delete_rightmost] returns a new tree where the rightmost item is removed,\n * if it exists.\n *)\nFixpoint delete_rightmost (tr: tree) : tree :=\n  match tr with\n  | Leaf => Leaf\n  | Node v lt rt =>\n    match rt with\n    | Leaf => lt\n    | _ => Node v lt (delete_rightmost rt)\n    end\n  end.\n\n(* Using [rightmost] and [delete_rightmost], deletion is defined here.\n * It is your job to understand how an item is deleted from a tree, and to\n * think about how the function preserves [BST].\n *)\nFixpoint 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 =>\n      match rightmost lt with\n      | Some rv => Node rv (delete_rightmost lt) rt\n      | None => rt\n      end\n    | Gt => Node v lt (delete a rt)\n    end\n  end.\n\n(* Lastly, we define a simple membership checker, to find whether a given value\n * belongs to the tree or not.\n *)\nFixpoint 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(* Finally, here are the facts you should prove. *)\nModule Type S.\n\n  (* 1) After inserting a value, it should be found in the tree. *)\n  Axiom insert_member: forall tr n, BST tr -> member n (insert n tr) = true.\n\n  (* 2) Insertion preserves [BST]. *)\n  Axiom insert_ok: forall tr n, BST tr -> BST (insert n tr).\n\n  (* 3) Deletion also preserves [BST]. *)\n  Axiom delete_ok: forall tr n, BST tr -> BST (delete n tr).\nEnd S.\n\n\n(* Looking for another puzzle?  Here's an *optional* question. *)\nModule Type OPTIONAL.\n  (* 4) After deleting a value, it should not be found in the tree. *)\n  Axiom delete_member: forall tr n, BST tr -> member n (delete n tr) = false.\nEnd OPTIONAL.\n\n\n(* As a timesaver for this pset, here is a *complete* list of tactics we used\n * in our solution.\n * - [apply thm]: apply theorem/lemma or hypothesis [thm], when its conclusion\n *   matches the current goal.  Then we switch to proving the premises of [thm].\n * - [apply thm with (x := e)]: like above, but for cases where not all\n *   quantified variables of [thm] have their values determined just from the\n *   shape of the current goal.  Instead, we give manual instantiations for\n *   those variables.  Multiple [(x := e)] items can be specified, for different\n *   variables.\n * - [apply thm with (x := e) in H]: like above, but in the forward direction:\n *   match a hypothesis of [thm] against hypothesis [H], to replace [H] with the\n *   conclusion of [thm].  (We only used this one for the _optional_ part.)\n * - [assumption]: solve an easy case: the goal matches a hypothesis.\n * - [cases e]: proceed by case analysis on the top-level structure of term [e].\n *   Useful to invoke on applications of functions like [compare]!\n * - [equality]: solve a goal that follows just by properties of equality, including\n *   some generic facts about inductive types (e.g., all constructors are injective).\n * - [induct x]: induction on quantified variable [x] from the theorem statement.\n * - [propositional]: simplify by rules of propositional logic (e.g., for \"and\"\n *   connective [/\\]).\n * - [rewrite thm]: use quantified equality [thm] to replace all instances of its\n *   lefthand side with its righthand side.\n * - [simplify]: algebraic simplification everywhere, by applying definitions\n *   of functions.\n * - [cbn [ident]]: reduce only the applications of the definition whose \n *   name is [ident] in the goal.\n * - [cbn [ident] in *]: reduce only the applications of the definition whose \n *   name is [ident] in the goal and the context.\n * - [invert H]: we used it to derive an equality [x = y] from [Some x = Some y]\n *   (though the tactic is more general).\n * - [subst]: Given equalities like [x = e], where [x] is a variable, eliminates\n *   the variable [x] by substituting [e] for it everywhere.\n * - [unfold ident]: unfold a definition named [ident] to its body in the\n *   conclusion.\n * - [unfold ident in *]: unfold a definition named [ident] to its body\n *   in the conclusion and the context.\n *)\n", "meta": {"author": "mit-frap", "repo": "spring18", "sha": "f0f8b35613938e61e2c46f1c70f2fc6a9e04659f", "save_path": "github-repos/coq/mit-frap-spring18", "path": "github-repos/coq/mit-frap-spring18/spring18-f0f8b35613938e61e2c46f1c70f2fc6a9e04659f/pset4/Pset4Sig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.6949147325037214}}
{"text": "Inductive Var := x | y | n | i | sum.\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\nNotation \"A +' B\" := (aplus A B) (at level 50).\nNotation \"A *' B\" := (amul A B) (at level 46).\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\nInductive aeval_small_step : AExp -> State -> AExp -> Prop :=\n| aconst : forall n st, anum n =[ st ]=> n\n| alookup : forall v st, avar v =[ st ]=> (st v)\n| aadd_1 : forall a1 a2 a1' st,\n    a1 =[ st ]=> a1' ->\n    a1 +' a2 =[ st ]=> a1' +' a2\n| aadd_2 : forall a1 a2 a2' st,\n    a2 =[ st ]=> a2' ->\n    a1 +' a2 =[ st ]=> a1 +' a2'\n| aadd : forall i1 i2 st n,\n    n = anum (i1 + i2) ->\n    anum i1 +' anum i2 =[ st ]=> n\n| atimes_1 : forall a1 a2 a1' st,\n    a1 =[ st ]=> a1' ->\n    a1 *' a2 =[ st ]=> a1' *' a2\n| atimes_2 : forall a1 a2 a2' st,\n    a2 =[ st ]=> a2' ->\n    a1 *' a2 =[ st ]=> a1 *' a2'\n| atimes : forall i1 i2 st n,\n    n = anum (i1 + i2) ->\n    anum i1 *' anum i2 =[ st ]=> n\nwhere \"A =[ S ]=> N\" := (aeval_small_step A S N).\n\n\nExample e1 :\n  2 +' x =[ sigma1 ]=> 2 +' 10.\nProof.\n  eapply aadd_2.\n  eapply alookup.\nQed.\n\nReserved Notation \"A =[ S ]>* A'\" (at level 60).\nInductive aeval_clos : AExp -> State -> AExp -> Prop :=\n| a_refl : forall a st, a =[ st ]>* a\n| a_trans : forall a1 a2 a3 st,  (a1 =[st]=> a2) -> a2 =[ st ]>* a3  -> a1 =[ st ]>* a3\nwhere \"A =[ S ]>* A'\" := (aeval_clos A S A').\n\nExample e2 :\n  2 +' x =[ sigma1 ]>* anum 12.\nProof.\n  apply a_trans with (a2 := (2 +' 10)).\n  - apply aadd_2.\n    apply alookup.\n  - eapply a_trans.\n    + eapply aadd. eauto.\n    + simpl. eapply a_refl.\nQed.\n\n\nInductive BExp :=\n| btrue : BExp\n| bfalse : BExp\n| blessthan : AExp -> AExp -> BExp\n| bnot : BExp -> BExp\n| band : BExp -> BExp -> BExp.\n\nNotation \"A <=' B\" := (blessthan A B) (at level 53).\nReserved Notation \"B ={ State }=> B'\" (at level 61).\n\nInductive beval : BExp -> State -> BExp -> Prop :=\n| elessthan_1: forall a1 a2 a1' state,\n    a1 =[ state ]=> a1' ->\n    (a1 <=' a2) ={ state }=> a1' <=' a2\n| elessthan_2: forall i1 a2 a2' state,\n    a2 =[state]=> a2' ->\n    (anum i1) <=' a2 ={ state }=> (anum i1) <=' a2'\n| elessthan: forall i1 i2 state b,\n    b = (if Nat.leb i1 i2 then btrue else bfalse) ->\n    (anum i1) <=' (anum i2) ={ state }=> b\n| enot : forall b b' state,\n    b ={ state }=> b' ->\n    (bnot b) ={ state }=> (bnot b')\n| enottrue : forall state,\n    (bnot btrue) ={ state }=> bfalse\n| enotfalse : forall state,\n    (bnot bfalse) ={ state }=> btrue\n| eand_1 : forall b1 b1' b2 state,\n    b1 ={state}=> b1' ->\n    (band b1 b2) ={ state }=> (band b1' b2)\n| eandtrue : forall b2 state,\n    (band btrue b2) ={state}=> b2\n| eandfalse : forall b2 state,\n    (band bfalse b2) ={state}=> bfalse\nwhere \"B ={ State }=> B'\" := (beval B State B').\n\nReserved Notation \"A ={ S }>* A'\" (at level 61).\nInductive beval_clos : BExp -> State -> BExp -> Prop :=\n| b_refl : forall b st, b ={ st }>* b\n| b_trans : forall b1 b2 b3 st,  (b1 ={st}=> b2) -> (b2 ={ st }>* b3)  -> (b1 ={ st }>* b3)\nwhere \"A ={ S }>* A'\" := (beval_clos A S A').\n\n\nExample beval_lessthan:\n  1 +' 3 <=' 5 ={ sigma0 }>* btrue.\nProof.\n  eapply b_trans.\n  - eapply elessthan_1.\n    eapply aadd. simpl.  eauto.\n  - eapply b_trans.\n    + eapply elessthan. simpl. eauto.\n    + eapply b_refl.\nQed.\n\n\nInductive Stmt :=\n| assignment : Var -> AExp -> Stmt\n| sequence : Stmt -> Stmt -> Stmt\n| while : BExp -> Stmt -> Stmt\n| skip : Stmt\n| ifthenelse : BExp -> Stmt -> Stmt -> Stmt.\n\nNotation \"X ::= N\" := (assignment X N) (at level 60).\nNotation \"S ;; S'\" := (sequence S S')\n                        (at level 63, right associativity).\n\nReserved Notation \"Stmt -{ State }->[ Stmt' ; State' ]\" (at level 65).\n\nInductive eval : Stmt -> State -> Stmt -> State -> Prop :=\n| eassign_2: forall var a a' state,\n    a =[state]=> a' ->\n    (var ::= a) -{state}->[ var ::= a' ;  state ]\n| eassign: forall var state state' i,\n    state' = update state var i ->\n    (var ::= (anum i)) -{state}->[ skip ; state']\n| eseq_1 : forall s1 s1' s2 state1 state,\n    s1 -{state}->[ s1' ; state1 ] ->\n    (s1 ;; s2) -{state}->[ s1' ;; s2 ; state1 ]\n| eseq : forall s2 state,\n    (skip ;; s2) -{state}->[ s2 ; state ]\n| eifthenelse_1 : forall b b' s1 s2 state,\n    b ={ state }=> b' ->\n    (ifthenelse b s1 s2) -{ state }->[ ifthenelse b' s1 s2 ; state ]\n| eifthenelse_true : forall s1 s2 state,\n    (ifthenelse btrue s1 s2) -{ state }->[ s1 ; state ]\n| eifthenelse_false : forall s1 s2 state,\n    (ifthenelse bfalse s1 s2) -{ state }->[ s2 ; state ]\n| ewhile: forall state b s,\n    (while b s) -{state}->[ ifthenelse b (s ;; while b s) skip ; state ]\nwhere \"Stmt -{ State }->[ Stmt' ; State' ]\" := (eval Stmt State Stmt' State').\n\nReserved Notation \"Stmt -{ State }>*[ Stmt' ; State' ]\" (at level 65).\nInductive eval_clos : Stmt -> State -> Stmt -> State -> Prop :=\n| refl : forall stmt state, stmt -{ state }>*[ stmt ; state ]\n| trans : forall s1 s2 s3 state1 state2 state3 , \n    s1 -{ state1 }->[ s2 ; state2 ] ->\n    s2 -{ state2 }>*[ s3 ; state3 ] ->\n    s1 -{ state1 }>*[ s3 ; state3 ]\nwhere \"Stmt -{ State }>*[ Stmt' ; State' ]\" := (eval_clos Stmt State Stmt' State').\n\n\nExample eval_assign:\n  exists sigma,\n    (x ::= y +' 10) -{ sigma0 }>*[skip ; sigma] /\\ sigma x = 10.\nProof.\n  exists (update sigma0 x 10).\n  split.\n  - eapply trans.\n    + eapply eassign_2.\n      eapply aadd_1.\n      eapply alookup.\n    + eapply trans.\n      apply eassign_2.\n      * unfold sigma0.\n        eapply aadd. trivial.\n      * eapply trans.\n        ** eapply eassign. eauto.\n        ** eapply refl.\n  - unfold update.\n    simpl.\n    reflexivity.\nQed.\n\nDefinition seq_pgm := (x ::= 10);;(y ::= 1).\nExample eval_seq:\n  exists state,\n    seq_pgm -{sigma0}>*[ skip ; state ] /\\ state x = 10 /\\ state y = 1.\nProof.\n  eexists.\n  split.\n  - unfold seq_pgm.\n    eapply trans.\n    + eapply eseq_1.\n      eapply eassign.\n      reflexivity.\n    + eapply trans.\n      eapply eseq.\n      eapply trans.\n      * eapply eassign.\n        reflexivity.\n      * eapply refl.\n  - unfold update.\n    simpl.\n    split; trivial.\nQed.\n\nDefinition sumpgm_1 :=\n  n ::= 1 ;;\n  i ::= 1 ;;\n  sum ::= 0 ;;\n   while ( i <=' n)\n   (sum ::= sum +' i ;; i ::= i +' 1).\n\nExample eval_sumpgm_1:\n  exists state,\n    sumpgm_1 -{sigma0 }>*[skip ; state] /\\ state sum = 1.\nProof.\n  eexists.\n  unfold sumpgm_1.\n  split.\n  - eapply trans.\n    eapply eseq_1.\n    eapply eassign; trivial.\n    eapply trans.\n    eapply eseq.\n    eapply trans.\n    + eapply eseq_1.\n      eapply eassign; trivial.\n    + eapply trans.\n      eapply eseq.\n      eapply trans.\n      eapply eseq_1.\n      * eapply eassign; trivial.\n      * eapply trans.\n        eapply eseq.\n        eapply trans.\n        ** eapply ewhile.\n        ** eapply trans.\n           { eapply eifthenelse_1.\n             eapply elessthan_1.\n             eapply alookup. }\n           { unfold update. simpl.\n             eapply trans.\n             - eapply eifthenelse_1.\n               eapply elessthan_2.\n               eapply alookup.\n             - simpl.\n               eapply trans.\n               eapply eifthenelse_1.\n               + eapply elessthan.\n                 simpl. trivial.\n               + eapply trans.\n                 eapply eifthenelse_true.\n                 eapply trans.\n                 eapply eseq_1.\n                 eapply eseq_1.\n                 eapply eassign_2.\n                 * eapply aadd_1.\n                   eapply alookup.\n                 * simpl.\n                   eapply trans.\n                   eapply eseq_1.\n                   ** eapply eseq_1.\n                      eapply eassign_2.\n                      eapply aadd_2.\n                      eapply alookup.\n                   ** simpl.\n                      eapply trans.\n                      eapply eseq_1.\n                      eapply eseq_1.\n                      eapply eassign_2.\n                      eapply aadd. simpl. reflexivity.\n                      eapply trans.\n                      eapply eseq_1.\n                      eapply eseq_1.\n                      eapply eassign. eauto.\n                      eapply trans.\n                      eapply eseq_1.\n                      eapply eseq.\n                      eapply trans.\n                      eapply eseq_1.\n                      eapply eassign_2.\n                      eapply aadd_1.\n                      eapply alookup.\n                      eapply trans.\n                      eapply eseq_1.\n                      unfold update. simpl.\n                      eapply eassign_2.\n                      eapply aadd. eauto.\n                      eapply trans.\n                      eapply eseq_1.\n                      eapply eassign.\n                      simpl. eauto.\n                      eapply trans.\n                      eapply eseq.\n                      eapply trans.\n                      eapply ewhile.\n                      eapply trans.\n                      eapply eifthenelse_1.\n                      eapply elessthan_1. eapply alookup. unfold update. simpl.\n                      eapply trans.\n                      eapply eifthenelse_1.\n                      eapply elessthan_2. eapply alookup. unfold update. simpl.\n                      eapply trans.\n                      eapply eifthenelse_1.\n                      eapply elessthan. simpl. reflexivity.\n                      eapply trans.\n                      eapply eifthenelse_false.\n                      eapply refl.\n           }\n  - simpl. trivial.\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/SSP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.6949147268366523}}
{"text": "Require Import CoqStock.List.\n\nRequire Import Brzozowski.Alphabet.\nRequire Import Brzozowski.Null.\nRequire Import Brzozowski.Regex.\nRequire Import Brzozowski.Language.\n\n(*\n**Definition 3.1.**\nGiven a language $R$ of and a finite sequence $s$,\nthe derivative of $R$ with respect to $s$ is denoted by $D_s R$ and is\n$D_s R = \\{t | s.t \\in R \\}$.\n*)\nDefinition derive_langs (s: str) (R: lang) (t: str): Prop :=\n  (s ++ t) \\in R.\n\n(*\nD_a R = { t | a.t \\in R}\n*)\nDefinition derive_lang (a: alphabet) (R: lang) (t: str): Prop :=\n  (a :: t) \\in R.\n\n(* Alternative inductive predicate for derive_lang *)\nInductive derive_lang' (a: alphabet) (R: lang) (t: str): Prop :=\n  | mk_derive_lang:\n    (a :: t) \\in R ->\n    t \\in (derive_lang' a R)\n  .\n\n(*\n**THEOREM 3.1.** If $R$ is a regular expression,\nthe derivative of $R$ with respect to a character $a \\in \\Sigma_k$ is found\nrecursively as follows:\n\n$$\n\\begin{aligned}\n\\text{(3.4)}&\\ D_a a &=&\\ \\epsilon, \\\\\n\\text{(3.5)}&\\ D_a b &=&\\ \\emptyset,\\ \\text{for}\\ b = \\epsilon\\ \\text{or}\\ b = \\emptyset\\ \\text{or}\\ b \\in A_k\\ \\text{and}\\ b \\neq a, \\\\\n\\text{(3.6)}&\\ D_a (P^* ) &=&\\ (D_a P)P^*, \\\\\n\\text{(3.7)}&\\ D_a (PQ) &=&\\ (D_a P)Q + \\nu(P)(D_a Q). \\\\\n\\text{(3.8)}&\\ D_a (f(P, Q)) &=&\\ f(D_a P, D_a Q). \\\\\n\\end{aligned}\n$$\n*)\nFixpoint derive_def (r: regex) (a: alphabet) : regex :=\n  match r with\n  | emptyset => emptyset\n  | emptystr => emptyset\n  | symbol b =>\n    if (eqa b a)\n    then emptystr\n    else emptyset\n  | or s t => or (derive_def s a) (derive_def t a)\n  | neg s => neg (derive_def s a)\n  | concat s t =>\n    or (concat (derive_def s a) t)\n       (concat (null_def s) (derive_def t a))\n  | star s => concat (derive_def s a) (star s)\n  end.\n\nDefinition derive_defs (r: regex) (s: str) : regex :=\n  fold_left derive_def s r.\n", "meta": {"author": "awalterschulze", "repo": "regex-reexamined-coq", "sha": "71e4a82790f269814fc3eb33e9e9cd1b49b559c5", "save_path": "github-repos/coq/awalterschulze-regex-reexamined-coq", "path": "github-repos/coq/awalterschulze-regex-reexamined-coq/regex-reexamined-coq-71e4a82790f269814fc3eb33e9e9cd1b49b559c5/src/Brzozowski/Derive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.870597271765821, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.6948992394186124}}
{"text": "Require Import Utf8.\nRequire Import Omega.\nRequire Import Eqdep Eqdep_dec.\n\nSet Implicit Arguments.\n\n(** * Facts about Natural Numbers *)\nSection le_rel.\n  Lemma le_refl n : n <= n. trivial. Qed.\n\n  Lemma le_trans : forall n m p, n <= m -> m <= p -> n <= p.\n    intuition.\n  Qed.\nEnd le_rel.\n\nAdd Parametric Relation : _ @le\n  reflexivity proved by le_refl\n  transitivity proved by le_trans\n    as le_rel.\n\n(** Proof thanks to Robbert Krebbers <mailinglists@robbertkrebbers.nl>\n    on coq-club *)\n\nLemma nat_le_proofs_unicity : ∀ (x y : nat) (p q : x <= y), p = q.\nProof.\n  assert (∀ x y (p : x ≤ y) y' (q : x ≤ y'),\n            y = y' → eq_dep nat (le x) y p y' q) as aux;\n  [ | intros x y p q; now apply (eq_dep_eq_dec eq_nat_dec), aux ].\n  fix 3. intros x ? [|y p] ? [|y' q].\n  * easy.\n  * clear nat_le_proofs_unicity. omega.\n  * clear nat_le_proofs_unicity. omega.\n  * injection 1. intros Hy. now case (@nat_le_proofs_unicity x y p y' q Hy).\nQed.\n", "meta": {"author": "JasonGross", "repo": "ct4s", "sha": "fa17718be5c6f4fe25c447490f929f943a23f2fc", "save_path": "github-repos/coq/JasonGross-ct4s", "path": "github-repos/coq/JasonGross-ct4s/ct4s-fa17718be5c6f4fe25c447490f929f943a23f2fc/NatFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.6948992093013177}}
{"text": "Definition a := 3.\n\nDefinition myid (A : Type) (x : A) : A := x.\n\nDefinition id' : forall (A : Type), A -> A := fun A x => x.\n\nEval compute in myid nat 5.\nEval compute in 5.\nEval compute in id' nat 5.\n\n\nTheorem first_theorem : forall P: Prop, P -> P.\nProof.\n  intros P HP.\n  apply HP.\n\nQed.\n\n\n\nTheorem x_le_y_tauto : forall (x y: nat), x<y -> x<y.\nProof.\n  intros a b.\n  apply first_theorem.\nQed.\n\n\nTheorem p_q_p : forall P Q:Prop, P -> Q -> P.\nProof.\n  intro a.\n  intro b.\n  intro c.\n  intro d.\n  apply c.\nQed.\n\nTheorem eq2 : forall x a b, (x = a + b) -> (x + 5 = a + b + 5).\nProof.\n  intro p.\n  intro q.\n  intro r.\n  intro s.\n  rewrite s.\n  reflexivity.\nQed.\n\nRequire Import Arith List.\nTheorem injection_example : forall (a : nat),\n    forall (xs : list nat), 1 :: xs = a :: xs -> 1 <= a.\nProof.\n  intro p.\n  intro q.\n  intro r.\n  injection r.\n  intro s.\n  rewrite <- s.\n  apply le_refl.\nQed.\n\nTheorem fact5equal120 : fact 5 = 120.\nProof.\n  simpl.\n  reflexivity.\nQed.\n", "meta": {"author": "seizans", "repo": "coqtest", "sha": "2e106a3cc79338652b5af0d9692a16cb9aeb481e", "save_path": "github-repos/coq/seizans-coqtest", "path": "github-repos/coq/seizans-coqtest/coqtest-2e106a3cc79338652b5af0d9692a16cb9aeb481e/topse/theorem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6947057354260872}}
{"text": "Require Import HoTT Arith Nat FinSet.\nRequire Import UnivalenceAxiom.\n\nAxiom (gcard : Type -> nat).\nAxiom (gcard_unit : gcard Unit = (S O)).\nAxiom (gcard_sum : forall (X Y : Type), gcard (X + Y) = gcard X + gcard Y).\n\nLemma gcard_equiv (A B : Type) (f : A -> B) : IsEquiv f -> gcard A = gcard B.\nProof.\n  intro p. f_ap. apply (path_universe f).\nDefined.\n\nLemma gcard_equiv' (A B : Type) : A <~> B -> gcard A = gcard B.\nProof.\n  intro e. f_ap. apply (path_universe e).\nDefined.\n\nLemma gcard_prod (A B : Type) : gcard (A * B) = (gcard A) * (gcard B).\nAdmitted.\n\nLemma gcard_empty : gcard Empty = 0.\nProof.\n  apply (cancelR_plus 1).\n  path_via (gcard Empty + gcard Unit).\n  - apply (ap (plus (gcard Empty))).\n    symmetry. apply gcard_unit.\n  - path_via (gcard (Empty + Unit)).\n    + symmetry. apply gcard_sum.\n    + path_via (gcard Unit).\n      * apply gcard_equiv'. apply empty_sum.\n      * apply gcard_unit.\nDefined.\n\n                                              \n\nLemma gcard_fin (n : nat) : gcard (Fin n) = n.\nProof.\n  induction n.\n  - apply gcard_empty.\n  - path_via (gcard (Fin n) + gcard Unit).\n    + apply gcard_sum.\n    + path_via (gcard (Fin n) + 1).\n      * f_ap. apply gcard_unit.\n      * refine ((plus_n_Sm _ _) @ _). f_ap.\n        refine ((plus_O_r _) @ IHn).\nDefined.\n\n\nLemma gcard_card (A : FinSet) : gcard A.1 = card A.\nProof.\n  destruct A as [A [n p]]. strip_truncations.\n  path_via (gcard (Fin n)). f_ap. apply gcard_fin.\nDefined.\n\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/GCard.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6947057254151792}}
{"text": "\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div seq.\nFrom mathcomp Require Import ssralg fintype perm choice.\nFrom mathcomp Require Import matrix  bigop zmodp mxalgebra poly mxpoly.\n\nImport GRing.Theory.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nOpen Scope ring_scope.\n\nSection atomic_operations.\nVariable R: comRingType.\n\n(* describe simple line / column combination operators *)\n\n(* Operation to multiply Lk by a the scalar a *)\nDefinition line_scale n m k (a: R) (M: 'M[R]_(n,m)) :=\n  \\matrix_(i < n) ((if i == k then a else 1) *: row i M).\n\nLemma line_scale_row_eq n m k a (M: 'M[R]_(n,m)):\n  row k (line_scale k a M) = a *: row k M.\nProof.\nby apply/rowP => i; rewrite !mxE eqxx.\nQed.\n\nLemma line_scale_row_neq n m k l a (M: 'M[R]_(n,m)): k != l ->\n  row l (line_scale k a M) = row l M.\nProof.\nmove/negbTE => hkl.\nby apply/rowP => i; rewrite !mxE eq_sym hkl mul1r.\nQed.\n\n\n(* several application of the line_scale operation *)\nLemma lines_scale_row m n a (M: 'M[R]_(m,n)):\n  forall s, uniq s ->\n  (forall i, i \\in s ->\n    row i (foldl (fun N i => line_scale i a N) M s) = a *: row i M) /\\\n  (forall i, i \\notin s ->\n    row i (foldl (fun N i => line_scale i a N) M s) = row i M).\nProof.\nmove => s.\nelim : s n M => [ | hd tl hi] //= n M /andP [h1 h2].\nsplit => i; rewrite in_cons.\n- move/orP => [/eqP{i}-> | hin].\n  + case: (hi _ (line_scale hd a M) h2) => _ hr.\n    by rewrite hr // line_scale_row_eq.\n  case: (hi _ (line_scale hd a M) h2) => -> // _.\n  rewrite line_scale_row_neq //.\n  by apply: contraNneq h1 => ->.\nrewrite negb_or => /andP[hl hr].\ncase: (hi _ (line_scale hd a M)  h2) => _ hR.\nby rewrite hR // line_scale_row_neq // eq_sym.\nQed.\n\n(*\n  alternative definition of the same operation by matrix multiplication\n  this definition is easier to prove determinant property of the operator\n*)\nDefinition line_scale_mx n m k (a: R) (M: 'M[R]_(n,m)) :=\n  diag_mx (\\row_(i < n) (if i == k then a else 1)) *m M.\n\nLemma line_scale_eq : forall n m k a (M: 'M[R]_(n,m)),\n  line_scale k a M = line_scale_mx k a M.\nProof.\nmove => n m k a M; apply/matrixP => i j; rewrite !mxE.\nrewrite (bigD1 i) //= big1 /=; first by rewrite !mxE addr0 eqxx.\nby move => x /negbTE hx; rewrite !mxE [i == x]eq_sym hx mulr0n mul0r.\nQed.\n\n(* line_scale_mx scales the determinant by a *)\nLemma det_line_scale_mx : forall n k a (M: 'M[R]_n),\n  \\det (line_scale_mx k a M) = a * \\det M.\nProof.\nrewrite /line_scale_mx => n k a M.\nrewrite det_mulmx det_diag (bigD1 k) //= big1 /=;\n  first by rewrite !mxE mulr1 eqxx.\nby move => i /negbTE h; rewrite !mxE h.\nQed.\n\n(* line_scale scales the determinant by a *)\nLemma det_line_scale : forall n k a (M: 'M[R]_n),\n  \\det (line_scale k a M) = a * \\det M.\nProof.\nmove => n k a M.\nby rewrite line_scale_eq det_line_scale_mx.\nQed.\n\nLemma det_lines_scale m a (M: 'M[R]_m) s:\n  \\det (foldl (fun N i => line_scale i a N) M s) = a ^+ (size s) * \\det M.\nProof.\nelim : s M => [ | hd tl hi] M //=.\n- by rewrite expr0 mul1r.\nby rewrite hi det_line_scale mulrA exprSr.\nQed.\n\n\n(* Operation to change Lk by Lk + a Ll *)\nDefinition line_comb n m k l (a: R) (M: 'M[R]_(n,m)) :=\n  \\matrix_(i < n) if i == k then row k M + a*: row l M else row i M.\n\n\nLemma line_comb_row_eq n m k l a (M: 'M[R]_(n,m)):\n  row k (line_comb k l a M) = row k M + a *: row l M.\nProof.\nby apply/rowP => i; rewrite !mxE eqxx !mxE.\nQed.\n\nLemma line_comb_row_neq n m k k' l a (M: 'M[R]_(n,m)): k != k' ->\n  row k' (line_comb k l a M) = row k' M.\nProof.\nmove/negbTE => hkk'.\nby apply/rowP => i; rewrite !mxE eq_sym hkk' !mxE.\nQed.\n\n(* several application of the line_comb operation *)\nLemma lines_comb_row m n a l (M: 'M[R]_(m,n)):\n  forall s, uniq s -> l \\notin s ->\n  (forall i, i \\in s ->\n    row i (foldl (fun N i => line_comb i l a N) M s) =\n    row i M + a *: row l M) /\\\n  (forall i, i \\notin s ->\n    row i (foldl (fun N i => line_comb i l a N) M s) = row i M).\nProof.\nmove => s.\nelim : s M => [ | hd tl hi] //= M /andP [h1 h2].\nrewrite in_cons negb_or => /andP [hl1 hl2].\nsplit => i; rewrite in_cons.\n- move/orP => [/eqP{i}-> | hin].\n  + case: (hi (line_comb hd l a M) h2 hl2) => _ hr.\n    by rewrite hr // line_comb_row_eq.\n  case: (hi (line_comb hd l a M) h2 hl2) => -> // _.\n  rewrite !line_comb_row_neq // eq_sym // eq_sym.\n  by apply: contraNneq h1 => ->.\nrewrite negb_or => /andP [hl hr].\ncase: (hi (line_comb hd l a M)  h2 hl2) => _ hR.\nby rewrite hR // !line_comb_row_neq // eq_sym.\nQed.\n\n\nLemma lines_comb_row_dep m n (a: 'I_m -> R) l (M: 'M[R]_(m,n)):\n  forall s, uniq s -> l \\notin s ->\n  (forall i, i \\in s ->\n    row i (foldl (fun N i => line_comb i l (a i) N) M s) =\n    row i M + (a i) *: row l M) /\\\n  (forall i, i \\notin s ->\n    row i (foldl (fun N i => line_comb i l (a i) N) M s) = row i M).\nProof.\nmove => s.\nelim : s M => [ | hd tl hi] //= M /andP [h1 h2].\nrewrite in_cons negb_or => /andP [hl1 hl2].\nsplit => i; rewrite in_cons.\n- move/orP => [/eqP{i}-> | hin].\n  + case: (hi (line_comb hd l (a hd) M) h2 hl2) => _ hr.\n    by rewrite hr // line_comb_row_eq.\n  case: (hi (line_comb hd l (a hd) M) h2 hl2) => -> // _.\n  rewrite !line_comb_row_neq // eq_sym // eq_sym.\n  by apply: contraNneq h1 => ->.\nrewrite negb_or => /andP [hl hr].\ncase: (hi (line_comb hd l (a hd) M)  h2 hl2) => _ hR.\nby rewrite hR // !line_comb_row_neq // eq_sym.\nQed.\n\n(* if k != l, line_comb doesn't change the det *)\nLemma det_line_comb : forall n k l a (M: 'M[R]_n),\n  k != l -> \\det (line_comb k l a M) = \\det M.\nProof.\nmove => n k l a M hkl.\nhave h : row k (line_comb k l a M) = 1 *: row k M +\n  a *: row k (\\matrix_(i < n) if i == k then row l M else row i M).\n  by rewrite scale1r; apply/rowP => i; rewrite !mxE eqxx !mxE.\nrewrite (determinant_multilinear h).\n- rewrite mul1r [X in a * X](determinant_alternate hkl).\n  + by rewrite mulr0 addr0.\n  by move => x; rewrite !mxE eqxx eq_sym (negbTE hkl).\n- by apply/matrixP => i j; rewrite !mxE eq_sym (negbTE (neq_lift k i)) !mxE.\nby apply/matrixP => i j; rewrite !mxE eq_sym (negbTE (neq_lift k i)) !mxE.\nQed.\n\nLemma det_lines_comb m a l (M: 'M[R]_m) s:\n  l \\notin s ->\n  \\det (foldl (fun N i => line_comb i l a N) M s) = \\det M.\nProof.\nelim : s M => [ | hd tl hi] M //=.\nrewrite in_cons negb_or => /andP [hl1 hl2].\nby rewrite hi // det_line_comb // eq_sym.\nQed.\n\nLemma det_lines_comb_dep m (a: 'I_m -> R) l (M: 'M[R]_m) s:\n  l \\notin s ->\n  \\det (foldl (fun N i => line_comb i l (a i) N) M s) = \\det M.\nProof.\nelim : s M => [ | hd tl hi] M //=.\nrewrite in_cons negb_or => /andP [hl1 hl2].\nby rewrite hi // det_line_comb // eq_sym.\nQed.\n\n\n(* if k == l, line_comb == line_scale *)\nLemma det_line_comb_eq : forall n k l a (M: 'M[R]_n),\n  k == l -> \\det (line_comb k l a M) = (1 + a) * \\det M.\nProof.\nmove => n k l a M /eqP ->; clear k.\nhave h : row l (line_comb l l a M) = 1 *: row l M + a *: row l M.\n- rewrite /line_scale.\n  by apply/rowP => i; rewrite !mxE eqxx !mxE mul1r.\nrewrite (determinant_multilinear h) ?mulrDl //.\n  rewrite /line_scale; apply/matrixP => i j; rewrite !mxE.\n  by rewrite eq_sym (negbTE (neq_lift l i)) !mxE.\nrewrite /line_scale; apply/matrixP => i j; rewrite !mxE.\nby rewrite eq_sym (negbTE (neq_lift l i)) !mxE.\nQed.\n\nEnd atomic_operations.\n", "meta": {"author": "coq-community", "repo": "coqeal", "sha": "1063846268eb2c51fd0e8363dee9a247e3f70c7c", "save_path": "github-repos/coq/coq-community-coqeal", "path": "github-repos/coq/coq-community-coqeal/coqeal-1063846268eb2c51fd0e8363dee9a247e3f70c7c/theory/atomic_operations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.694705723862052}}
{"text": "Inductive Expr: Set :=\n| Cst(x: nat)\n| Pair(e1 e2: Expr)\n| Fst(e: Expr)\n| Snd(e: Expr).\n\nInductive Interp: forall T: Type, Expr -> T -> Prop :=\n| InterpCst: forall x,\n    Interp nat (Cst x) x\n| InterpPair: forall T1 T2 (e1 e2: Expr) e1' e2 e2',\n    Interp T1 e1 e1' ->\n    Interp T2 e2 e2' ->\n    Interp (T1 * T2) (Pair e1 e2) (e1', e2')\n| InterpFst: forall T1 T2 e e1' e2',\n    Interp (T1 * T2) e (e1', e2') ->\n    Interp T1 (Fst e) e1'\n| InterpSnd: forall T1 T2 e e1' e2',\n    Interp (T1 * T2) e (e1', e2') ->\n    Interp T2 (Snd e) e2'.\n\nExample e := (Fst (Snd (Pair (Pair (Cst 3) (Cst 4)) (Pair (Pair (Cst 5) (Cst 6)) (Cst 7))))).\n\nGoal Interp (nat * nat) e (5, 6).\n  repeat econstructor.\nQed.\n", "meta": {"author": "samuelgruetter", "repo": "counterexamples", "sha": "bb699361b12687fdc6323759745e75d3bf8720b8", "save_path": "github-repos/coq/samuelgruetter-counterexamples", "path": "github-repos/coq/samuelgruetter-counterexamples/counterexamples-bb699361b12687fdc6323759745e75d3bf8720b8/nunchaku/InterpInd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.694705713851144}}
{"text": "From Coq Require Import Arith Program Omega.\n\nInductive four_expr : Set :=\n| Four : four_expr\n| Factorial : four_expr -> four_expr\n| SqrtF : four_expr -> four_expr\n| SqrtC : four_expr -> four_expr\n| LogF : four_expr -> four_expr\n| LogC : four_expr -> four_expr\n.\n\nFixpoint fact (n : nat) : nat :=\n  match n with\n  | 0 => 1\n  | S n' => n * fact n'\n  end.\n\nLemma fact_pos : forall n, fact n > 0.\nProof.\n  induction n.\n  simpl; omega.\n  simpl.\n  apply Nat.lt_lt_add_r.\n  trivial.\nQed.\n\nLemma fact_inc : forall n, n > 0 -> fact (S n) > fact n.\nProof.\n  intros.\n  simpl.\n  assert (n * fact n > 0).\n  assert (fact n > 0).\n  apply fact_pos.\n  apply Nat.mul_pos_pos; trivial.\n  omega.\nQed.\n\nLemma fact_inc' : forall n m, n > 0 -> n < m -> fact n < fact m.\nProof.\n  intros.\n  induction H0.\n  apply fact_inc.\n  assumption.\n  assert (fact m < fact (S m)).\n  apply fact_inc.\n  omega.\n  omega.\nQed.\n\nLemma fact_nondec : forall n m, n < m -> fact n <= fact m.\nProof.\n  intros.\n  induction n.\n  simpl.\n  assert (fact m > 0).\n  apply fact_pos.\n  omega.\n  assert (fact (S n) < fact m).\n  apply fact_inc'; try assumption; try omega.\n  omega.\nQed.\n\nInductive Op : Type :=\n| EQ\n| LE\n| GE.\n\nFixpoint gwp (n : nat) (g : nat) (cond : nat -> nat -> nat) : nat :=\n  match g with\n  | 0 => 0\n  | S g' => match cond n g' with\n           | 0 => g\n           | S k => gwp n g' cond\n           end\n  end.\n    \nDefinition logf (n : nat) : nat :=\n  n - gwp n n (fun n g' => 1 + n - Nat.pow 10 (n - g')).\n\nDefinition logc (n : nat) : nat :=\n  n - gwp n n (fun n g' => n - Nat.pow 10 (n - S g')).\n\nCompute logc 10.\n\nFixpoint comp (f : four_expr) : nat :=\n  match f with\n  | Four => 4\n  | Factorial f' => fact (comp f')\n  | SqrtF f' => Nat.sqrt (comp f')\n  | SqrtC f' => Nat.sqrt_up (comp f')\n  | LogF f' => Nat.log2 (comp f')\n  | LogC f' => Nat.log2_up (comp f')\n  end.\n\nFixpoint fact_tower (n : nat) :=\n  match n with\n  | 0 => Four\n  | S n' => Factorial (fact_tower n')\n  end.\n\nLemma fact_tower_pos : forall n, comp (fact_tower n) > 0.\nProof.\n  intros.\n  induction n.\n  simpl; omega.\n  simpl.\n  apply fact_pos.\nQed.\n\nDefinition sqrt_ft (n : nat) :=\n  SqrtF (fact_tower n).\n\nLemma mul2_gt : forall n, n > 0 -> n < 2 * n.\nProof.\n  intros.\n  omega.\nQed.\n\nLemma sqrt_nondec : forall n, Nat.sqrt n <= Nat.sqrt (S n).\nProof.\n  intros.\n  apply Nat.sqrt_le_mono.\n  omega.\nQed.\n\nLemma sqrt_pos : forall n, n > 0 -> Nat.sqrt n > 0.\nProof.\n  intros.\n  induction H.\n  rewrite Nat.sqrt_1; omega.\n  assert (Nat.sqrt (S m) >= Nat.sqrt m).\n  apply sqrt_nondec.\n  omega.\nQed.\n\nLemma sqrt_lt' : forall n, n > 0 -> Nat.sqrt n < Nat.sqrt (4 * n).\nProof.\n  intros.\n  assert (Nat.sqrt 4 * Nat.sqrt n <= Nat.sqrt(4 * n)).\n  apply Nat.sqrt_mul_below.\n  assert (Nat.sqrt n < Nat.sqrt 4 * Nat.sqrt n).\n  apply mul2_gt.\n  apply sqrt_pos; trivial.\n  omega.\nQed.\n\nLemma sqrt_lt : forall m n, n > 0 -> m > 4 * n -> Nat.sqrt m > Nat.sqrt n.\nProof.\n  intros.\n  assert (Nat.sqrt n < Nat.sqrt (4 * n)).\n  apply sqrt_lt'; apply H.\n  assert (Nat.sqrt m >= Nat.sqrt (4 * n)).\n  apply Nat.sqrt_le_mono.\n  omega.\n  omega.\nQed.\n\nLemma sqrt_fold_below : forall m n, n * Nat.sqrt m <= Nat.sqrt (n * n * m).\nProof.\n  intros.\n  assert (Nat.sqrt (n * n) = n).\n  apply Nat.sqrt_square.\n  rewrite <- H at 1.\n  apply Nat.sqrt_mul_below.\nQed.\n  \nLemma sqrt_fold_above : forall m n, S n * S (Nat.sqrt m) >= S (Nat.sqrt (n * n * m)).\nProof.\n  intros.\n  assert (Nat.sqrt (n * n) = n).\n  apply Nat.sqrt_square.\n  rewrite <- H at 1.\n  apply Nat.sqrt_mul_above.\nQed.\n\nLemma sqrt_sqrt_lt : forall m n, n > 0 -> m > 25 * n -> Nat.sqrt (Nat.sqrt m) > Nat.sqrt (Nat.sqrt n).\nProof.\n  intros.\n  apply sqrt_lt.\n  apply sqrt_pos; trivial.\n  assert (Nat.sqrt m >= Nat.sqrt (25 * n)).\n  apply Nat.sqrt_le_mono; omega.\n  assert (Nat.sqrt (25 * n) >= 5 * Nat.sqrt n).\n  apply sqrt_fold_below.\n  assert (5 * Nat.sqrt n > 4 * Nat.sqrt n).\n  apply mult_lt_compat_r.\n  auto.\n  apply sqrt_pos.\n  trivial.\n  omega.\nQed.\n\nLemma mul_nondec : forall n p, p > 0 -> p * n >= n.\nProof.\n  intros.\n  induction p.\n  inversion H.\n  assert (S p * n = n + n * p).\n  simpl.\n  ring.\n  rewrite H0.\n  case (n * p).\n  omega.\n  intros.\n  omega.\nQed.\n\n\nTheorem exists_increasing_seq :\n  exists (f : nat -> four_expr),\n    comp (f 0) = 2\n    /\\ forall n, comp (f n) < comp (f (S n)).\nProof.\n  exists sqrt_ft.\n  split.\n  trivial.\n  intros.\n  simpl.\n  case n.\n  unfold Nat.sqrt; simpl; omega.\n  intros.\n  apply sqrt_lt.\n  apply fact_tower_pos.\n  assert (comp (fact_tower (S n0)) >= 24).\n  induction n0.\n  simpl; omega.\n  simpl in *.\n  assert (24 = fact 4).\n  simpl; trivial.\n  rewrite H.\n  apply fact_nondec.\n  omega.\n  induction H.\n  assert (fact 24 = 24 * (23 * fact 22)).\n  unfold fact.\n  trivial.\n  rewrite H.\n  assert (24 * (23 * fact 22) = 24 * 23 * fact 22).\n  omega.\n  rewrite H0.\n  assert (24 * 23 * 22 > 4 * 24).\n  omega.\n  assert (fact 22 > 0).\n  apply fact_pos.\n  omega.\n  simpl (fact (S m)).\n  assert (4 * S m = 4 + 4 * m).\n  omega.\n  rewrite H0.\n  assert (m * fact m > 25).\n  assert (fact m > 25).\n  omega.\n  assert (m * fact m >= fact m).\n  apply mul_nondec.\n  omega.\n  omega.\n  omega.\nQed.\n\nFixpoint sqrt_repeated' (l : nat) (n : four_expr) (c : nat) : four_expr :=\n  match c with\n  | 0 => n\n  | S c' => match comp n - l * l with\n           | 0 => n\n           | S k => sqrt_repeated' l (SqrtC n) c'\n           end\n  end.\n\n\nDefinition sqrt_repeated (l : nat) (n : four_expr) : four_expr :=\n  sqrt_repeated' l n (comp n).\n\nFixpoint sqrt_repeated_elem (seq : nat -> four_expr) (n : nat) :=\n  match n with\n  | 0 => seq 0\n  | S n' => sqrt_repeated (comp (sqrt_repeated_elem seq n')) (seq n)\n  end.\n\n\nLemma sqrt_repeated_increasing' :\n  forall x y z, x < comp y -> x < comp (sqrt_repeated' x y z).\nProof.\n  intros.\n  dependent induction z generalizing y.\n  simpl.\n  apply H.\n  simpl.\n  remember (comp y - x * x) as d.\n  destruct d.\n  apply H.\n  apply IHz.\n  simpl.\n  assert (x * x < comp y).\n  omega.\n  assert (comp y <= Nat.sqrt_up (comp y) * Nat.sqrt_up (comp y)).\n  apply Nat.sqrt_sqrt_up_spec.\n  omega.\n  assert (x * x < Nat.sqrt_up (comp y) * Nat.sqrt_up (comp y)).\n  omega.\n  apply Nat.square_lt_mono.\n  apply H2.\nQed.\n\nLemma sqrt_repeated_increasing :\n  forall x y, x < comp y -> x < comp (sqrt_repeated x y).\nProof.\n  intros.\n  unfold sqrt_repeated.\n  apply sqrt_repeated_increasing'.\n  apply H.\nQed.\n\nLemma sqrt_repeated_dec' :\n  forall l n z, comp (sqrt_repeated' l n z) <= comp n.\nProof.\n  intros.\n  dependent induction z generalizing n.\n  auto.\n  simpl.\n  destruct (comp n - l * l).\n  auto.\n  specialize IHz with (n := (SqrtC n)).\n  assert (comp (SqrtC n) <= comp n).\n  simpl.\n  apply Nat.sqrt_up_le_lin.\n  omega.\n  omega.\nQed.\n\n\nLemma sqrt_repeated_dec :\n  forall l n, comp (sqrt_repeated l n) <= comp n.\nProof.\n  intros.\n  apply sqrt_repeated_dec'.\nQed.\n\n\nLemma sqrt_repeated_elem_dec :\n  forall seq n, comp (sqrt_repeated_elem seq n) <= comp (seq n).\nProof.\n  intros.\n  induction n.\n  auto.\n  simpl.\n  apply sqrt_repeated_dec.\nQed.\n\nLemma sqrt_repeated_elem_inc :\n  forall seq n, comp (seq 0) = 2 -> (forall p, comp (seq p) < comp (seq (S p))) -> comp (sqrt_repeated_elem seq n) > 1.\nProof.\n  intros.\n  induction n.\n  simpl.\n  omega.\n  assert (comp (sqrt_repeated_elem seq (S n)) > comp (sqrt_repeated_elem seq n)).\n  simpl.\n  apply sqrt_repeated_increasing.\n  assert (comp (sqrt_repeated_elem seq n) <= comp (seq n)).\n  apply sqrt_repeated_elem_dec.\n  specialize H0 with (p := n).\n  omega.\n  omega.\nQed.\n\n\nLemma sqrt_repeated_bound' :\n  forall l n z , l > 1 -> z >= comp n \\/ comp n <= 2 -> l * l >= comp (sqrt_repeated' l n z).\nProof.\n  intros.\n  dependent induction z generalizing n.\n  simpl.\n  destruct H0.\n  inversion H0.\n  rewrite H2.\n  apply Nat.le_0_l.\n  assert (l * l >= l).\n  apply mul_nondec.\n  omega.\n  omega.\n  simpl.\n  remember (comp n - l * l) as d.\n  destruct d.\n  omega.\n  apply IHz.\n  assumption.\n  simpl.\n  destruct H0.\n  remember (comp n - 2) as c.\n  destruct c.\n  assert (comp n <= 2).\n  omega.\n  right.\n  assert (Nat.sqrt_up (comp n) <= (comp n)).\n  apply Nat.sqrt_up_le_lin.\n  omega.\n  omega.\n  assert (comp n > 2).\n  omega.\n  left.\n  assert (Nat.sqrt_up (comp n) < comp n).\n  apply Nat.sqrt_up_lt_lin.\n  trivial.\n  omega.\n  right.\n  assert (Nat.sqrt_up (comp n) <= comp n).\n  apply Nat.sqrt_up_le_lin.\n  omega.\n  omega.\nQed.\n\nLemma sqrt_repeated_bound :\n  forall l n, l > 1 -> l * l >= comp (sqrt_repeated l n).\nProof.\n  intros.\n  apply sqrt_repeated_bound'.\n  assumption.\n  left.\n  omega.\nQed.\n\n\nTheorem exists_square_bound_seq' :\n  (exists (f : nat -> four_expr),\n    comp (f 0) = 2\n    /\\ forall n, comp (f n) < comp (f (S n)))\n   -> (exists (f : nat -> four_expr),\n    comp (f 0) = 2\n    /\\ forall n, comp (f n) < comp (f (S n)) /\\ comp (f n) * comp (f n) >= comp (f (S n))).\nProof.\n  intros.\n  inversion H.\n  rename x into seq.\n  exists (sqrt_repeated_elem seq).\n  split.\n  simpl.\n  apply H0.\n  intros.\n  split.\n  simpl.\n  apply sqrt_repeated_increasing.\n  destruct H0.\n  specialize H1 with (n := n).\n  assert (comp (sqrt_repeated_elem seq n) <= comp (seq n)).\n  dependent induction n.\n  simpl.\n  trivial.\n  apply sqrt_repeated_elem_dec.\n  omega.\n  simpl.\n  remember (comp (sqrt_repeated_elem seq n)) as x.\n  destruct n.\n\n  apply sqrt_repeated_bound.\n  simpl in Heqx.\n  omega.\n  apply sqrt_repeated_bound.\n  induction n.\n  simpl in Heqx.\n  destruct H0.\n  rewrite H0 in Heqx.\n  assert (2 < comp (sqrt_repeated 2 (seq 1))).\n  apply sqrt_repeated_increasing.\n  specialize H1 with (n := 0).\n  omega.\n  omega.\n  rewrite Heqx.\n  apply sqrt_repeated_elem_inc.\n  apply H0.\n  apply H0.\nQed.\n\nTheorem exists_square_bound_seq :\n(exists (f : nat -> four_expr),\n    comp (f 0) = 2\n    /\\ forall n, comp (f n) < comp (f (S n)) /\\ comp (f n) * comp (f n) >= comp (f (S n))).\nProof.\n  apply exists_square_bound_seq'.\n  apply exists_increasing_seq.\nQed.\n\nDefinition logloglog_seq (seq : nat -> four_expr) (n : nat) :=\n  LogF (LogF (LogF (seq n))).\n\nLtac cases N :=\n  match type of N with\n  | ?n <= S ?k => remember (n - k) as n';\n                destruct n';\n                try assert (n = S k) as N' by omega;\n                try assert (n <= k) as N' by omega;\n                clear N;\n                rename N' into N\n  end.\n\nLemma loglog_ok_5 :\n  forall n, n <= 5 -> n > 3 -> Nat.log2 (Nat.log2 (n * n)) <= 2 * Nat.log2 (Nat.log2 n).\nProof.\n  intros.\n  do 2 try cases H; match goal with\n                | [ H : n = ?k |- _ ] => rewrite H; simpl; trivial\n                | _ => idtac\n                end.\nQed.\n\nLemma loglog_ok_10 :\n  forall n, n <= 10 -> n > 3 -> Nat.log2 (Nat.log2 (n * n)) <= 2 * Nat.log2 (Nat.log2 n).\nProof.\n  intros.\n  do 5 try cases H; match goal with\n                | [ H : n = ?k |- _ ] => rewrite H; simpl; trivial\n                | _ => idtac\n                end.\n  apply loglog_ok_5; trivial.\nQed.\n\nLemma loglog_ok_15 :\n  forall n, n <= 15 -> n > 3 -> Nat.log2 (Nat.log2 (n * n)) <= 2 * Nat.log2 (Nat.log2 n).\nProof.\n  intros.\n  do 5 try cases H; match goal with\n                | [ H : n = ?k |- _ ] => rewrite H; simpl; trivial\n                | _ => idtac\n                end.\n  apply loglog_ok_10;\n  trivial.\nQed.\n\nLemma loglog_ok :\n  forall n, n > 3 -> Nat.log2 (Nat.log2 (n * n)) <= 2 * (Nat.log2 (Nat.log2 n)).\nProof.\n  intros.\n  rename H into Hgt3.\n  assert (Nat.log2 (n * n) <= Nat.log2 n + Nat.log2 n + 1).\n  apply Nat.log2_mul_above; omega.\n  remember (n-1) as nm1.\n  destruct nm1.\n  assert (n = 1 \\/ n = 0).\n  omega.\n  destruct H0.\n  rewrite H0.\n  auto.\n  rewrite H0.\n  auto.\n  assert (n > 1).\n  omega.\n  assert (Nat.log2 n >= Nat.log2 2).\n  apply Nat.log2_le_mono.\n  omega.\n  assert (Nat.log2 2 = 1). auto.\n  assert (Nat.log2 n + Nat.log2 n + 1 <= 3 * Nat.log2 n).\n  omega.\n  assert (Nat.log2 (3 * Nat.log2 n) <= Nat.log2 3 + Nat.log2 (Nat.log2 n) + 1).\n  apply Nat.log2_mul_above; omega.\n  assert (Nat.log2 3 = 1); auto.\n  rewrite H5 in H4.\n  apply Nat.log2_le_mono in H.\n  apply Nat.log2_le_mono in H3.\n  assert (1 + Nat.log2 (Nat.log2 n) + 1 = Nat.log2 (Nat.log2 n) + 2).\n  omega.\n  rewrite H6 in H4.\n  remember (n - 15) as nm15.\n  destruct nm15.\n  2: {\n    assert (16 <= n).\n    omega.\n    assert (2 <= Nat.log2 (Nat.log2 n)).\n    apply Nat.log2_le_pow2.\n    omega.\n    simpl.\n    apply Nat.log2_le_pow2.\n    omega.\n    simpl.\n    trivial.\n    assert (Nat.log2 (Nat.log2 n) + 2 <= 2 * Nat.log2 (Nat.log2 n)).\n    omega.\n    omega.\n  }\n  assert (n <= 15) by omega.\n  apply loglog_ok_15; trivial.\nQed.  \n\n\nTheorem exists_cover_seq' : \n(exists (f : nat -> four_expr),\n    comp (f 0) = 2\n    /\\ (forall n, comp (f n) < comp (f (S n)) /\\ comp (f n) * comp (f n) >= comp (f (S n))))\n-> (exists (f : nat -> four_expr),\n      comp (f 0) = 0\n      /\\ (forall n, (comp (f n) <= comp (f (S n)) /\\ comp (f (S n)) <= S (comp (f n))))\n      /\\ forall n, exists m, comp (f m) > n).\n\nProof.\n  intros.\n  inversion H.\n  rename x into seq.\n  exists (logloglog_seq seq).\n  split.\n  simpl.\n  destruct H0.\n  rewrite H0.\n  auto.\n  split.\n  split.\n  simpl.\n  do 3 apply Nat.log2_le_mono.\n  destruct H0.\n  specialize (H1 n).\n  omega.\n  simpl.\n  destruct H0.\n  specialize (H1 n).\n  remember (comp (seq n)) as cn.\n  remember (comp (seq (S n))) as csn.\n  remember (cn - 3) as cnm3.\n  destruct H1.\n  destruct cnm3.\n  assert (cn <= 3).\n  omega.\n  do 4 try cases H3;\n  match type of H3 with\n  | cn <= 0 => assert (cn = 0) as H3'; try omega; clear H3; rename H3' into H3\n  | _ => idtac\n  end;\n  match type of H3 with\n  | cn = ?k =>\n      rewrite H3 in *;\n      assert (csn <= k * k);\n      try omega;\n      assert (Nat.log2 (Nat.log2 (Nat.log2 csn)) <= Nat.log2 (Nat.log2 (Nat.log2 (k * k))));\n      try do 3 apply Nat.log2_le_mono; auto\n  | _ => idtac\n  end.\n  assert (cn > 3).\n  omega.\n  rewrite <- Nat.log2_double.\n  apply Nat.log2_le_mono.\n  assert (Nat.log2 csn <= Nat.log2 (cn * cn)).\n  apply Nat.log2_le_mono.\n  omega.\n  apply Nat.log2_le_mono in H4.\n  assert (Nat.log2 (Nat.log2 (cn * cn)) <= 2 * Nat.log2 (Nat.log2 cn)).\n  apply loglog_ok.\n  trivial.\n  omega.\n  do 2 apply Nat.log2_le_mono in H3.\n  auto.\n  intros.\n  simpl.\n  destruct H0.\n  assert (forall n, comp (seq n) >= n).\n  intros.\n  induction n0.\n  omega.\n  assert (comp (seq (S n0)) > comp (seq n0)).\n  apply H1.\n  omega.\n  exists (2 ^ 2 ^ 2 ^ (n + 1)).\n  assert (comp (seq (2 ^ 2 ^ 2 ^ (n + 1))) >= 2 ^ 2 ^ 2 ^ (n + 1)).\n  trivial.\n  do 3 apply Nat.log2_le_mono in H3.\n  assert (Nat.log2 (2 ^ 2 ^ 2 ^ (n + 1)) = 2 ^ 2 ^ (n + 1)).\n  apply Nat.log2_pow2.\n  omega.\n  assert (Nat.log2 (2 ^ 2 ^ (n + 1)) = 2 ^ (n + 1)).\n  apply Nat.log2_pow2.\n  omega.\n  assert (Nat.log2 (2 ^ (n + 1)) = n + 1).\n  apply Nat.log2_pow2.\n  omega.\n  assert (Nat.log2 (Nat.log2 (Nat.log2 (2 ^ 2 ^ 2 ^ (n + 1)))) = (n + 1)).\n  rewrite H4.\n  rewrite H5.\n  rewrite H6.\n  trivial.\n  omega.\nQed.\n\nTheorem exists_cover_seq :\n  exists (f : nat -> four_expr),\n      comp (f 0) = 0\n      /\\ (forall n, (comp (f n) <= comp (f (S n)) /\\ comp (f (S n)) <= S (comp (f n))))\n      /\\ forall n, exists m, comp (f m) > n.\nProof.\n  apply exists_cover_seq'.\n  apply exists_square_bound_seq.\nQed.\n\nLemma seq_no_jump :\n  (forall seq,\n      (comp (seq 0) = 0\n      /\\ forall n, (comp (seq n) <= comp (seq (S n)) /\\ comp (seq (S n)) <= S (comp (seq n)))\n      /\\ forall n, exists m, comp (seq m) > n)\n  -> forall n, forall m, m < comp (seq n) -> exists p, comp (seq p) = m).\nProof.\n  intros until 1.\n  inversion H.\n  clear H.\n  induction n; intros.\n  rewrite H0 in H.\n  inversion H.\n  specialize (H1 n).\n  destruct H1.\n  destruct H1.\n  remember (comp (seq (S n)) - comp (seq n)) as dseq. \n  destruct dseq.\n  assert (comp (seq (S n)) = comp (seq n)).\n  omega.\n  rewrite <- H4 in IHn.\n  auto.\n  assert (comp (seq (S n)) = S (comp (seq n))).\n  omega.\n  assert (m <= comp (seq n)).\n  omega.\n  apply le_lt_or_eq in H5.\n  destruct H5.\n  auto.\n  exists n.\n  auto.\nQed.\n\n\nLemma seq_cover :\n  (forall seq,\n      comp (seq 0) = 0\n      -> (forall n, comp (seq n) <= comp (seq (S n)) /\\ comp (seq (S n)) <= S (comp (seq n)))\n      -> (forall n, exists m, comp (seq m) > n)\n      -> (forall n, exists p, comp (seq p) = n)).\nProof.\n  intros.\n  assert ((forall n, forall m, m < comp (seq n) -> exists p, comp (seq p) = m)).\n  apply seq_no_jump.\n  auto.\n  intros.\n  specialize (H1 n).\n  destruct H1.\n  specialize (H2 x n).\n  auto.\nQed.\n\nTheorem four_seq_express_all_n :\n  forall a, exists f, comp f = a.\nProof.\n  intros.\n  pose proof seq_cover.\n  pose proof exists_cover_seq.\n  destruct H0.\n  rename x into seq.\n  specialize (H seq).\n  destruct H0.\n  destruct H1.\n  assert (forall n0 : nat, exists p : nat, comp (seq p) = n0).\n  apply H.\n  apply H0.\n  apply H1.\n  apply H2.\n  clear H.\n  specialize (H3 a).\n  destruct H3.\n  exists (seq x).\n  auto.\nQed.\n", "meta": {"author": "Gab601", "repo": "one-four", "sha": "b486ecef335c4f31b6d84811e4cda95b71e91271", "save_path": "github-repos/coq/Gab601-one-four", "path": "github-repos/coq/Gab601-one-four/one-four-b486ecef335c4f31b6d84811e4cda95b71e91271/main.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6946992322163504}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq             *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later            *)\nFrom mathcomp Require Import all_ssreflect ssralg fingroup finalg matrix.\nRequire Import Reals Lra.\nFrom mathcomp Require Import Rstruct.\nRequire Import ssrZ ssrR Reals_ext ssr_ext logb ssralg_ext bigop_ext Rbigop.\nRequire Import fdist proba entropy aep typ_seq channel.\n\n(******************************************************************************)\n(*                        Jointly typical sequences                           *)\n(*                                                                            *)\n(* Definitions:                                                               *)\n(*   JTS P W n epsilon == epsilon-jointly typical sequences of size n for an  *)\n(*                        input distribution P and  a channel W               *)\n(*                        JTS(n,e) is a subset of TS_{P,W}(n,e) such that     *)\n(*                        (x,y) \\in JTS(n,e) <->                              *)\n(*                        x \\in TS_P(n,e) /\\ y \\in TS_{PW}(n,e)               *)\n(*                                                                            *)\n(* Lemmas:                                                                    *)\n(*  JTS_sup               == Upper-bound for the set of jointly typical       *)\n(*                           sequences                                        *)\n(*  JTS_1                 == when they are very long, the jointly typical     *)\n(*                           sequences coincide with the typical sequences of *)\n(*                           the joint distribution                           *)\n(*  non_typical_sequences == the probability of the same event (joint         *)\n(*                           typicality) taken over the product distribution  *)\n(*                           of the inputs and the out-puts considered        *)\n(*                           independently tends to 0 asngets large           *)\n(*                                                                            *)\n(* For details, see Reynald Affeldt, Manabu Hagiwara, and Jonas Sénizergues.  *)\n(* Formalization of Shannon's theorems. Journal of Automated Reasoning,       *)\n(* 53(1):63--103, 2014                                                        *)\n(******************************************************************************)\n\nDeclare Scope jtyp_seq_scope.\nReserved Notation \"'`JTS'\".\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope typ_seq_scope.\nLocal Open Scope fdist_scope.\nLocal Open Scope channel_scope.\nLocal Open Scope entropy_scope.\nLocal Open Scope R_scope.\n\nSection joint_typ_seq_definition.\n\nVariables A B : finType.\nVariable P : fdist A.\nVariable W : `Ch(A, B).\nVariable n : nat.\nVariable epsilon : R.\n\nDefinition jtyp_seq (t : 'rV[A * B]_n) :=\n  [&& typ_seq P epsilon (rV_prod t).1,\n      typ_seq (`O(P , W)) epsilon (rV_prod t).2 &\n      typ_seq ((P `X W)) epsilon t].\n\nDefinition set_jtyp_seq : {set 'rV[A * B]_n} := [set tab | jtyp_seq tab].\n\nLocal Notation \"'`JTS'\" := (set_jtyp_seq).\n\nLemma typical_sequence1_JTS x : prod_rV x \\in `JTS ->\n  exp2 (- INR n * (`H P + epsilon)) <= P `^ n x.1 <= exp2 (- INR n * (`H P - epsilon)).\nProof.\nrewrite inE => /and3P[/andP[/leRP JTS11 /leRP JTS12] _ _].\nby rewrite prod_rVK in JTS11, JTS12.\nQed.\n\nLemma typical_sequence1_JTS' x : prod_rV x \\in `JTS ->\n  exp2 (- INR n * (`H (`O( P , W)) + epsilon)) <= (`O( P , W)) `^ n x.2 <=\n  exp2 (- INR n * (`H (`O( P , W)) - epsilon)).\nProof.\nrewrite inE => /and3P[_ /andP[/leRP JTS11 /leRP JTS12] _].\nby rewrite prod_rVK in JTS11, JTS12.\nQed.\n\nEnd joint_typ_seq_definition.\n\nNotation \"'`JTS'\" := (set_jtyp_seq) : jtyp_seq_scope.\nLocal Open Scope jtyp_seq_scope.\n\nSection jtyp_seq_upper.\n\nVariables (A B : finType) (P : fdist A) (W : `Ch(A, B)).\nVariable n : nat.\nVariable epsilon : R.\n\nLemma JTS_sup : INR #| `JTS P W n epsilon| <= exp2 (INR n * (`H(P , W) + epsilon)).\nProof.\nhave : INR #|`JTS P W n epsilon| <= INR #|`TS ((P `X W)) n epsilon|.\n  suff : `JTS P W n epsilon \\subset `TS ((P `X W)) n epsilon.\n    by move/subset_leq_card/leP/le_INR.\n  apply/subsetP => tab.\n  by rewrite /set_jtyp_seq inE /jtyp_seq inE => /and3P[].\nmove/leR_trans; apply; exact: (@TS_sup _ ((P `X W)) epsilon n).\nQed.\n\nEnd jtyp_seq_upper.\n\nSection jtyp_seq_transmitted.\nVariables (A B : finType) (P : fdist A) (W : `Ch(A, B)).\nVariable epsilon : R.\n\nLocal Open Scope zarith_ext_scope.\n\nDefinition JTS_1_bound :=\n  maxn '| up (aep_bound P (epsilon / 3)) |\n (maxn '| up (aep_bound (`O(P , W)) (epsilon / 3)) |\n       '| up (aep_bound ((P `X W)) (epsilon / 3)) |).\n\nVariable n : nat.\nHypothesis He : 0 < epsilon.\n\nLemma JTS_1 : (JTS_1_bound <= n)%nat ->\n  1 - epsilon <= Pr ((P `X W) `^ n) (`JTS P W n epsilon).\nProof.\nhave : (JTS_1_bound <= n)%nat ->\n  Pr ( (P `^ n `X (W ``^ n)) )\n    [set x | x.1 \\notin `TS P n epsilon] +\n  Pr ( (P `^ n `X (W ``^ n)) )\n    [set x | x.2 \\notin `TS (`O(P , W)) n epsilon] +\n  Pr ( (P `^ n `X  (W ``^ n)))\n    [set x | prod_rV x \\notin `TS ( (P `X W) ) n epsilon] <= epsilon.\n  have H1 : forall n, Pr ((P `X W) `^ n) [set x | (rV_prod x).1 \\notin `TS P n epsilon ] <=\n    Pr (P `^ n) [set x | x \\notin `TS P n (epsilon / 3)].\n    move=> m.\n    have : 1 <= 3 by lra.\n    move/(set_typ_seq_incl P m (ltRW He)) => Hincl.\n    rewrite (Pr_DMC_fst P W (fun x => x \\notin `TS P m epsilon)).\n    apply/Pr_incl/subsetP => i /=; rewrite !inE.\n    apply contra.\n    by move/subsetP : Hincl => /(_ i); rewrite !inE.\n  have {H1}HnP : forall n, ('| up (aep_bound P (epsilon / 3)) | <= n)%nat ->\n    Pr ((P `X W) `^ n) [set x | (rV_prod x).1 \\notin `TS P n epsilon ] <= epsilon /3.\n    move=> m Hm.\n    apply: leR_trans; first exact: (H1 m).\n    have m_prednK : m.-1.+1 = m.\n      rewrite prednK // (leq_trans _ Hm) // (_ : O = '| 0 |) //.\n      by apply/ltP/Zabs_nat_lt; split; [by [] | apply/up_pos/aep_bound_ge0; lra].\n    have : 1 - (epsilon / 3) <= Pr (P `^ m) (`TS P m (epsilon/3)).\n      rewrite -m_prednK.\n      apply Pr_TS_1.\n      - by apply divR_gt0 => //; lra.\n      - rewrite m_prednK.\n        move/leP/le_INR : Hm; apply leR_trans.\n        rewrite INR_Zabs_nat; last first.\n          apply/ltZW/up_pos/aep_bound_ge0 => //.\n          apply divR_gt0 => //; lra.\n        exact/ltRW/(proj1 (archimed _ )).\n    rewrite leR_subl_addr addRC -leR_subl_addr; apply: leR_trans.\n    by rewrite Pr_to_cplt setCK; exact/leRR.\n  have H1 m :\n    Pr ((P `X W) `^ m) [set x | (rV_prod x).2 \\notin `TS ( `O(P , W) ) m epsilon ] <=\n    Pr ( (`O( P , W) ) `^ m) (~: `TS ( `O( P , W) ) m (epsilon / 3)).\n    have : 1 <= 3 by lra.\n    move/(set_typ_seq_incl (`O(P , W)) m (ltRW He)) => Hincl.\n    rewrite Pr_DMC_out.\n    apply/Pr_incl/subsetP => i /=; rewrite !inE.\n    apply contra.\n    move/subsetP : Hincl => /(_ i).\n    by rewrite !inE.\n  have {H1}HnPW m : ('| up (aep_bound (`O(P , W)) (epsilon / 3)) | <= m)%nat ->\n    Pr ((P `X W) `^ m) [set x | (rV_prod x).2 \\notin `TS (`O(P , W)) m epsilon] <= epsilon /3.\n    move=> Hm.\n    apply: leR_trans; first exact: (H1 m).\n    have m_prednK : m.-1.+1 = m.\n      rewrite prednK // (leq_trans _ Hm) // (_ : O = '| 0 |) //.\n      apply/ltP/Zabs_nat_lt (* TODO: ssrZ? *); split; [by []|apply/up_pos/aep_bound_ge0; lra].\n    have : 1 - epsilon / 3 <= Pr ((`O(P , W)) `^ m) (`TS (`O(P , W)) m (epsilon / 3)).\n      rewrite -m_prednK.\n      apply Pr_TS_1.\n      - apply divR_gt0 => //; lra.\n      - move/leP/le_INR : Hm.\n        rewrite m_prednK.\n        apply leR_trans.\n        rewrite INR_Zabs_nat; last first.\n          apply/ltZW/up_pos/aep_bound_ge0; lra.\n        exact/ltRW/(proj1 (archimed _ )).\n    rewrite leR_subl_addr addRC -leR_subl_addr; apply: leR_trans.\n    by rewrite Pr_to_cplt setCK; exact/leRR.\n  have H1 m : Pr ((P `X W) `^ m) (~: `TS ((P `X W)) m epsilon) <=\n    Pr (((P `X W) ) `^ m) (~: `TS ((P `X W)) m (epsilon / 3)).\n    have : 1 <= 3 by lra.\n    move/(set_typ_seq_incl ((P `X W)) m (ltRW He)) => Hincl.\n    apply/Pr_incl/subsetP => /= v; rewrite !inE.\n    apply contra.\n    by move/subsetP : Hincl => /(_ v); by rewrite !inE.\n  have {H1}HnP_W m : ('| up (aep_bound ((P `X W)) (epsilon / 3)) | <= m)%nat ->\n    Pr ((P `X W) `^ m) (~: `TS ((P `X W)) m epsilon) <= epsilon /3.\n    move=> Hm.\n    apply: leR_trans; first exact: (H1 m).\n    have m_prednK : m.-1.+1 = m.\n      rewrite prednK // (leq_trans _ Hm) // (_ : O = '| 0 |) //.\n      apply/ltP/Zabs_nat_lt; split; [by []|apply/up_pos/aep_bound_ge0; lra].\n    have : 1 - epsilon / 3 <= Pr (((P `X W)) `^ m) (`TS ((P `X W)) m (epsilon / 3)).\n      rewrite -m_prednK; apply Pr_TS_1.\n      - apply divR_gt0 => //; lra.\n      - rewrite m_prednK.\n        move/leP/le_INR : Hm; apply leR_trans.\n        rewrite INR_Zabs_nat; last first.\n          apply/ltZW/up_pos/aep_bound_ge0; lra.\n        exact/Rlt_le/(proj1 (archimed _ )).\n    rewrite leR_subl_addr addRC -leR_subl_addr; apply: leR_trans.\n    by rewrite Pr_to_cplt setCK; exact/leRR.\n  move=> Hn.\n  rewrite [in X in _ <= X](_ : epsilon = epsilon / 3 + epsilon / 3 + epsilon / 3)%R; last by field.\n  move: Hn; rewrite 2!geq_max => /andP[Hn1 /andP[Hn2 Hn3]].\n  rewrite !Pr_DMC_rV_prod.\n  apply leR_add; first by apply leR_add; [exact: HnP | exact: HnPW].\n  apply: leR_trans; last exact/HnP_W/Hn3.\n  by apply/Req_le; congr Pr; apply/setP => /= tab; by rewrite !inE rV_prodK.\nmove=> Hn_Pr Hn.\nsuff H : Pr ((P `X W) `^ n ) (~: `JTS P W n epsilon) <= epsilon.\n  rewrite -(Pr_cplt ((P `X W) `^ n) (`JTS P W n epsilon)).\n  by rewrite leR_subl_addr leR_add2l.\napply (@leR_trans (Pr ((P `X W) `^ n)\n                      ([set x | ((rV_prod x).1 \\notin `TS P n epsilon)] :|:\n                       ([set x | ((rV_prod x).2 \\notin `TS (`O( P , W)) n epsilon)] :|:\n                        (~: `TS ((P `X W)) n epsilon))))).\n  by apply Req_le; congr Pr; apply/setP => xy;  rewrite !inE 2!negb_and orbA.\napply: leR_trans; last exact: Hn_Pr.\napply (@leR_trans (\n Pr ((P `X W) `^ n) [set x | (rV_prod x).1 \\notin `TS P n epsilon] +\n Pr ((P `X W) `^ n) ([set x | ((rV_prod x).2 \\notin `TS (`O( P , W)) n epsilon)] :|:\n                      (~: `TS ((P `X W)) n epsilon)))).\n  exact: Pr_union.\nrewrite -addRA !Pr_DMC_rV_prod; apply/leR_add2l; apply: leR_trans (Pr_union _ _ _).\nby apply/Req_le; congr Pr; apply/setP => t; rewrite !inE rV_prodK.\nQed.\n\nEnd jtyp_seq_transmitted.\n\nSection non_typicality.\nVariables (A B : finType) (P : fdist A) (W : `Ch(A, B)) (n : nat) (epsilon : R).\n\nLemma non_typical_sequences : Pr ((P `^ n) `x ((`O(P , W)) `^ n))\n  [set x | prod_rV x \\in `JTS P W n epsilon] <= exp2 (- n%:R * (`I(P, W) - 3 * epsilon)).\nProof.\nrewrite /Pr /=.\napply (@leR_trans (\\sum_(i | i \\in `JTS P W n epsilon)\n    (exp2 (- INR n * (`H P - epsilon)) * exp2 (- n%:R * (`H( P `o W ) - epsilon))))) => /=.\n  rewrite (reindex_onto (fun y => prod_rV y) (fun x => rV_prod x)) /=; last first.\n    by move=> ? ?; rewrite rV_prodK.\n  apply: leR_sumRl => i; rewrite inE => iJTS.\n  - rewrite fdist_prodE; apply leR_pmul => //.\n    exact: proj2 (typical_sequence1_JTS iJTS).\n    exact: proj2 (typical_sequence1_JTS' iJTS).\n  - exact/mulR_ge0.\n  - by rewrite prod_rVK eqxx andbC.\nrewrite (_ : \\sum_(_ | _) _ =\n  INR #| `JTS P W n epsilon| *\n  exp2 (- n%:R * (`H P - epsilon)) * exp2 (- INR n * (`H( P `o W) - epsilon))); last first.\n  by rewrite big_const iter_addR mulRA.\napply (@leR_trans (exp2 (INR n * (`H( P , W ) + epsilon)) *\n  exp2 (- n%:R * (`H P - epsilon)) * exp2 (- INR n * (`H( P `o W ) - epsilon)))).\n  do 2 apply leR_wpmul2r => //.\n  exact/JTS_sup.\napply Req_le; rewrite -2!ExpD; congr (exp2 _).\nrewrite /mutual_info_chan !mulRDr 2!Rmult_opp_opp.\nby rewrite (_ : 3 * epsilon = epsilon + epsilon + epsilon); field.\nQed.\n\nEnd non_typicality.\n", "meta": {"author": "affeldt-aist", "repo": "infotheo", "sha": "5f9efb859dbadcbcae2330e2e21e76f9b632d879", "save_path": "github-repos/coq/affeldt-aist-infotheo", "path": "github-repos/coq/affeldt-aist-infotheo/infotheo-5f9efb859dbadcbcae2330e2e21e76f9b632d879/information_theory/joint_typ_seq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.6945918831892772}}
{"text": "From mathcomp Require Import all_ssreflect all_fingroup all_algebra.\nFrom mathcomp Require Import all_solvable all_field.\nFrom Abel Require Import char0 various.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory.\n\nLocal Open Scope ring_scope.\n\nLemma Cyclotomic1 : 'Phi_1 = 'X - 1.\nProof.\nby have := @prod_Cyclotomic 1%N isT; rewrite big_cons big_nil mulr1.\nQed.\n\nLemma Cyclotomic2 : 'Phi_2 = 'X + 1.\nProof.\nhave := @prod_Cyclotomic 2%N isT; rewrite !big_cons big_nil mulr1/=.\nrewrite Cyclotomic1 -(@expr1n [ringType of {poly int}] 2%N).\nby rewrite subr_sqr expr1n => /mulfI->//; rewrite polyXsubC_eq0.\nQed.\n\nLemma prim_root1 (F : fieldType) n : (n.-primitive_root (1 : F)) = (n == 1)%N.\nProof.\ncase: n => [|[|n]]//.\n  by apply/'forall_eqP => i; rewrite ord1//= eqxx; apply/unity_rootP.\napply/'forall_eqP => /= /(_ (@Ordinal _ n _))/=/(_ _)/unity_rootP.\nby rewrite !ltnS leqnSn ltn_eqF//; apply => //; rewrite expr1n.\nQed.\n\nLemma prim2_rootN1 (F : fieldType) : 2%:R != 0 :> F ->\n   2.-primitive_root (- 1 : F).\nProof.\nmove=> tow_neq0; apply/'forall_eqP => -[[|[|]]]//= _; last first.\n  by apply/unity_rootP; rewrite -signr_odd.\nby apply/unity_rootP/eqP; rewrite expr1 eq_sym -addr_eq0 -mulr2n.\nQed.\n\nSection PhiCyclotomic.\n\nVariable (F : fieldType).\n\nLocal Notation ZtoF := (intr : int -> F).\nLocal Notation pZtoF := (map_poly ZtoF).\n\nLemma Phi_cyclotomic (n : nat) (w : F) : n.-primitive_root w ->\n   pZtoF 'Phi_n = cyclotomic w n.\nProof.\nelim/ltn_ind: n w => n ihn w prim_w.\nhave n_gt0 := prim_order_gt0 prim_w.\npose P k := pZtoF 'Phi_k.\npose Q k := cyclotomic (w ^+ (n %/ k)) k.\nhave eP : \\prod_(d <- divisors n) P d = 'X^n - 1.\n  by rewrite -rmorph_prod /= prod_Cyclotomic // rmorphB /= map_polyC map_polyXn.\nhave eQ : \\prod_(d <- divisors n) Q d = 'X^n - 1 by rewrite -prod_cyclotomic.\nhave fact (u : nat -> {poly F}) : \\prod_(d <- divisors n) u d =\n              u n * \\prod_(d <- rem n (divisors n)) u d.\n  by rewrite [LHS](big_rem n) ?divisors_id.\npose p := \\prod_(d <- rem n (divisors n)) P d.\npose q := \\prod_(d <- rem n (divisors n)) Q d.\nhave ePp : P n * p = 'X^n - 1 by rewrite -eP fact.\nhave eQq : Q n * q = 'X^n - 1 by rewrite -eQ fact.\nhave Xnsub1N0 : 'X^n - 1 != 0 :> {poly F}.\n  by rewrite -size_poly_gt0 size_Xn_sub_1.\nhave pN0 : p != 0 by apply: dvdpN0 Xnsub1N0; rewrite -ePp dvdp_mulIr.\nhave epq : p = q.\n  case: (divisors_correct n_gt0) => uniqd sortedd dP.\n  apply: eq_big_seq=> i; rewrite mem_rem_uniq ?divisors_uniq // inE.\n  case/andP=> NiSn di; apply: ihn; last by apply: dvdn_prim_root; rewrite -?dP.\n  suff: (i <= n)%N by rewrite leq_eqVlt (negPf NiSn).\n  by apply: dvdn_leq => //; rewrite -dP.\nhave {epq} : P n * p = Q n * p by rewrite [in RHS]epq ePp eQq.\nby move/(mulIf pN0); rewrite /Q divnn n_gt0.\nQed.\n\nEnd PhiCyclotomic.\n\nSection CyclotomicExt.\n\nVariables (F0 : fieldType) (L : fieldExtType F0).\nVariables (E : {subfield L}) (w : L) (n : nat).\nHypothesis w_is_nth_root : n.-primitive_root w.\n\nLemma splitting_Fadjoin_cyclotomic :\n  splittingFieldFor E (cyclotomic w n) <<E; w>>.\nProof.\nexists [seq w ^+ val k | k <- enum 'I_n & coprime (val k) n].\n  by rewrite /cyclotomic big_map big_filter big_enum_cond/= eqpxx.\nrewrite map_comp -(filter_map _ (fun i => coprime i n)) val_enum_ord.\nhave [n_gt1|] := ltnP 1 n; last first.\n  case: n w_is_nth_root (prim_order_gt0 w_is_nth_root) => [|[|]]//= wnth _ _.\n  by rewrite adjoin_seq1 expr0 -[w]expr1 prim_expr_order.\nset s := (X in <<_ & X>>%VS); suff /eq_adjoin-> : s =i w :: s.\n  rewrite adjoin_cons (Fadjoin_seq_idP _)//.\n  by apply/allP => _/mapP[i _ ->]/=; rewrite rpredX// memv_adjoin.\nmove=> x; rewrite in_cons orbC; symmetry; have []//= := boolP (_ \\in _).\napply: contraNF => /eqP ->; rewrite -[w]expr1 map_f//.\nby rewrite mem_filter mem_iota// coprime1n.\nQed.\n\nLemma cyclotomic_over : cyclotomic w n \\is a polyOver E.\nProof.\nby apply/polyOverP=> i; rewrite -Phi_cyclotomic // coef_map /= rpred_int.\nQed.\n\nHint Resolve cyclotomic_over : core.\n\nEnd CyclotomicExt.\n\nSection Cyclotomic.\n\n(* MISSING *)\nLemma primitive_root_pow (F : fieldType) (m : nat) (w w' : F) :\n    m.-primitive_root w' -> m.-primitive_root w ->\n  exists2 k, coprime k m & w = w' ^+ k.\nProof.\nmove/root_cyclotomic<-.\nrewrite /cyclotomic -big_filter; have [t et [uniqs tP /= perms]] := big_enumP.\npose rs := [seq w' ^+ (val i) | i <- t]; set p := (X in root X).\nhave {p} -> :  p = \\prod_(w <- rs) ('X - w%:P) by rewrite /p big_map.\nrewrite root_prod_XsubC; case/mapP=> [[i ltim]]; rewrite tP /= => coprim ew.\nby exists i.\nQed.\n\nVariables (F0 : fieldType) (L : splittingFieldType F0).\nVariables (E : {subfield L}) (w : L) (n : nat).\nHypothesis w_is_nth_root : n.-primitive_root w.\n\n(** Easy **)\n(*     - E(x) is Galois                                                       *)\nLemma galois_Fadjoin_cyclotomic : galois E <<E; w>>.\nProof.\napply/splitting_galoisField; exists (cyclotomic w n).\nsplit; rewrite ?cyclotomic_over//; last exact: splitting_Fadjoin_cyclotomic.\nrewrite /cyclotomic -(big_image _ _ _ (fun x => 'X - x%:P))/=.\nrewrite separable_prod_XsubC map_inj_uniq ?enum_uniq// => i j /eqP.\nby rewrite (eq_prim_root_expr w_is_nth_root) !modn_small// => /eqP/val_inj.\nQed.\n\nLemma abelian_cyclotomic : abelian 'Gal(<<E; w>> / E)%g.\nProof.\ncase: (boolP (w \\in E)) => [w_in_E |w_notin_E].\n  suff -> : ('Gal(<<E; w>> / E) = 1)%g by apply: abelian1.\n  apply/eqP; rewrite -subG1; apply/subsetP => x x_in.\n  rewrite inE gal_adjoin_eq ?group1 // (fixed_gal _ x_in w_in_E) ?gal_id //.\n  by have /Fadjoin_idP H := w_in_E; rewrite -{1}H subvv.\nrewrite card_classes_abelian /classes.\napply/eqP; apply: card_in_imset => f g f_in g_in; rewrite -!orbitJ.\nmove/orbit_eqP/orbitP => [] h h_in <- {f f_in}; apply/eqP.\nrewrite gal_adjoin_eq //= /conjg /= ?groupM ?groupV //.\nrewrite ?galM ?memv_gal ?memv_adjoin //.\nhave hg_gal f : f \\in 'Gal(<<E; w>> / E)%g -> f w ^+ n = 1.\n  by move=> f_in; apply/prim_expr_order; rewrite fmorph_primitive_root.\nhave := svalP (prim_rootP w_is_nth_root (hg_gal _ g_in)).\nhave h1_in : (h ^-1)%g \\in 'Gal(<<E; w>> / E)%g by rewrite ?groupV.\nhave := svalP (prim_rootP w_is_nth_root (hg_gal _ h1_in)).\nset ih1 := sval _ => hh1; set ig := sval _ => hg.\nrewrite hh1 rmorphX /= hg exprAC -hh1 rmorphX /=.\nby rewrite -galM ?memv_adjoin // mulVg gal_id.\nQed.\n\n(*     - Gal(E(x) / E) is then solvable                                       *)\nLemma solvable_Fadjoin_cyclotomic : solvable 'Gal(<<E; w>> / E).\nProof. exact/abelian_sol/abelian_cyclotomic. Qed.\n\nEnd Cyclotomic.\n", "meta": {"author": "math-comp", "repo": "Abel", "sha": "94499667cc4464f7748a2fd909e628a8f86a998e", "save_path": "github-repos/coq/math-comp-Abel", "path": "github-repos/coq/math-comp-Abel/Abel-94499667cc4464f7748a2fd909e628a8f86a998e/theories/xmathcomp/cyclotomic_ext.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479465, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6945918814698165}}
{"text": "(* week-05_consec_even.v *)\n(* YSC3236 2017-2018, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 05 Sep 2017 *)\n\n(* ********** *)\n\n(* Paraphernalia: *)\nLtac unfold_tactic name := intros; unfold name; (* fold name; *) reflexivity.\n\nRequire Import Arith Bool.\n\nNotation \"A =n= B\" :=\n  (beq_nat A B) (at level 70, right associativity).\n\n\n(* ********** *)\n\n\nDefinition test_evenp (candidate : nat -> bool) : bool :=\n  (eqb (candidate 0) true)\n  &&\n  (eqb (candidate 1) false)\n  &&\n  (eqb (candidate 7) false)\n  &&\n  (eqb (candidate 8) true)\n  &&\n  (eqb (candidate 17) false)\n  .\n\nFixpoint evenp (n : nat) : bool :=\n  match n with\n  | 0 => true\n  | S n' => negb (evenp n')\n  end.\n\n  Compute (test_evenp evenp).\n  \n  Lemma sum_even_even_is_even (a b : nat) :\n    evenp(a) = true -> evenp(b) = true -> evenp(a + b) = true.\n    Admitted.\n    \nTheorem consec_is_even :\n  forall n: nat,\n   evenp(n * S n) = true. \n\n  intro n.\n  induction n as [ | n' IHn'].\n  Search (0 * _ = _).\n  rewrite (Nat.mul_0_l 1).\n  unfold evenp.\n  reflexivity.\n\n  Check Nat.add_1_l n'.\n  rewrite <- (Nat.add_1_l n').\n  rewrite <- (Nat.add_1_l (1 + n')).\n\n  Search (_ + (_ + _) = _).\n  Check (Nat.add_assoc 1 1 n').\n  rewrite -> (Nat.add_assoc 1 1 n').\n  \n  Search (_ * _ = _ + _).\n  Check (Nat.mul_add_distr_l (1 + n') (1 + 1) (n')).\n  rewrite -> (Nat.mul_add_distr_l (1 + n') (1 + 1) (n')).\n\n  Check (sum_even_even_is_even ((1 + n') * (1 + 1)) ((1 + n') * n')).\n  apply sum_even_even_is_even.\n  Check (Nat.add_1_l 1).\n  rewrite -> (Nat.add_1_l 1).\n\n  Restart.\n\n  Fixpoint evenp (n : nat) : bool :=\n  match n with\n  | 0 => true\n  | S n' => negb (evenp n')\n  end.\n\n  Compute (test_evenp evenp).\n  \n  \n  (* ********** *)\n\n(* end of week-05_consec_even.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-05_consec_even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.694591878046747}}
{"text": "Require Import\n  HoTT.Classes.interfaces.abstract_algebra\n  HoTT.Classes.interfaces.orders\n  HoTT.Classes.orders.maps\n  HoTT.Classes.theory.lattices.\n\nGeneralizable Variables K L f.\n\n(*\nWe prove that the algebraic definition of a lattice corresponds to the\norder theoretic one. Note that we do not make any of these instances global,\nbecause that would cause loops.\n*)\nSection join_semilattice_order.\n  Context `{JoinSemiLatticeOrder L}.\n\n  Lemma join_ub_3_r x y z : z ≤ x ⊔ y ⊔ z.\n  Proof.\n  apply join_ub_r.\n  Qed.\n\n  Lemma join_ub_3_m x y z : y ≤ x ⊔ y ⊔ z.\n  Proof.\n  transitivity (x ⊔ y).\n  - apply join_ub_r.\n  - apply join_ub_l.\n  Qed.\n\n  Lemma join_ub_3_l x y z : x ≤ x ⊔ y ⊔ z.\n  Proof.\n  transitivity (x ⊔ y); apply join_ub_l.\n  Qed.\n\n  Lemma join_ub_3_assoc_l x y z : x ≤ x ⊔ (y ⊔ z).\n  Proof.\n  apply join_ub_l.\n  Qed.\n\n  Lemma join_ub_3_assoc_m x y z : y ≤ x ⊔ (y ⊔ z).\n  Proof.\n  transitivity (y ⊔ z).\n  - apply join_ub_l.\n  - apply join_ub_r.\n  Qed.\n\n  Lemma join_ub_3_assoc_r x y z : z ≤ x ⊔ (y ⊔ z).\n  Proof.\n  transitivity (y ⊔ z); apply join_ub_r.\n  Qed.\n\n  Instance join_sl_order_join_sl: IsJoinSemiLattice L.\n  Proof.\n  repeat split.\n  - apply _.\n  - intros x y z. apply (antisymmetry (≤)).\n    + apply join_lub.\n      * apply join_ub_3_l.\n      * apply join_lub.\n        ** apply join_ub_3_m.\n        ** apply join_ub_3_r.\n    + apply join_lub.\n      * apply join_lub.\n        ** apply join_ub_3_assoc_l.\n        ** apply join_ub_3_assoc_m.\n      * apply join_ub_3_assoc_r.\n  - intros x y. apply (antisymmetry (≤)); apply join_lub;\n    first [apply join_ub_l | apply join_ub_r].\n  - intros x. red. apply (antisymmetry (≤)).\n    + apply join_lub; apply reflexivity.\n    + apply join_ub_l.\n  Qed.\n\n  Lemma join_le_compat_r x y z : z ≤ x -> z ≤ x ⊔ y.\n  Proof.\n  intros E. transitivity x.\n  - trivial.\n  - apply join_ub_l.\n  Qed.\n\n  Lemma join_le_compat_l x y z : z ≤ y -> z ≤ x ⊔ y.\n  Proof.\n  intros E. rewrite (commutativity (f:=join)).\n  apply join_le_compat_r.\n  trivial.\n  Qed.\n\n  Lemma join_l x y : y ≤ x -> x ⊔ y = x.\n  Proof.\n  intros E. apply (antisymmetry (≤)).\n  - apply join_lub;trivial. apply reflexivity.\n  - apply join_ub_l.\n  Qed.\n\n  Lemma join_r x y : x ≤ y -> x ⊔ y = y.\n  Proof.\n  intros E. rewrite (commutativity (f:=join)).\n  apply join_l.\n  trivial.\n  Qed.\n\n  Lemma join_sl_le_spec x y : x ≤ y <-> x ⊔ y = y.\n  Proof.\n  split; intros E.\n  - apply join_r. trivial.\n  - rewrite <-E. apply join_ub_l.\n  Qed.\n\n  Global Instance join_le_preserving_l : forall z, OrderPreserving (z ⊔).\n  Proof.\n  red;intros.\n  apply join_lub.\n  - apply join_ub_l.\n  - apply join_le_compat_l. trivial.\n  Qed.\n\n  Global Instance join_le_preserving_r : forall z, OrderPreserving (⊔ z).\n  Proof.\n  intros. apply maps.order_preserving_flip.\n  Qed.\n\n  Lemma join_le_compat x₁ x₂ y₁ y₂ : x₁ ≤ x₂ -> y₁ ≤ y₂ -> x₁ ⊔ y₁ ≤ x₂ ⊔ y₂.\n  Proof.\n  intros E1 E2. transitivity (x₁ ⊔ y₂).\n  - apply (order_preserving (x₁ ⊔)). trivial.\n  - apply (order_preserving (⊔ y₂));trivial.\n  Qed.\n\n  Lemma join_le x y z : x ≤ z -> y ≤ z -> x ⊔ y ≤ z.\n  Proof.\n  intros. rewrite <-(idempotency (⊔) z).\n  apply join_le_compat;trivial.\n  Qed.\n\n  Section total_join.\n  Context `{!TotalRelation le}.\n\n  Lemma total_join_either `{!TotalRelation le} x y : join x y = x |_| join x y = y.\n  Proof.\n  destruct (total le x y) as [E|E].\n  - right. apply join_r,E.\n  - left. apply join_l,E.\n  Qed.\n\n  Definition max x y :=\n    match total le x y with\n    | inl _ => y\n    | inr _ => x\n    end.\n\n  Lemma total_join_max x y : join x y = max x y.\n  Proof.\n  unfold max;destruct (total le x y) as [E|E].\n  - apply join_r,E.\n  - apply join_l,E.\n  Qed.\n  End total_join.\n\nEnd join_semilattice_order.\n\nSection bounded_join_semilattice.\n  Context `{JoinSemiLatticeOrder L} `{Bottom L} `{!IsBoundedJoinSemiLattice L}.\n\n  Lemma above_bottom x : ⊥ ≤ x.\n  Proof.\n  apply join_sl_le_spec.\n  rewrite left_identity.\n  reflexivity.\n  Qed.\n\n  Lemma below_bottom x : x ≤ ⊥ -> x = ⊥.\n  Proof.\n  intros E.\n  apply join_sl_le_spec in E. rewrite right_identity in E.\n  trivial.\n  Qed.\nEnd bounded_join_semilattice.\n\nSection meet_semilattice_order.\n  Context `{MeetSemiLatticeOrder L}.\n\n  Lemma meet_lb_3_r x y z : x ⊓ y ⊓ z ≤ z.\n  Proof.\n  apply meet_lb_r.\n  Qed.\n\n  Lemma meet_lb_3_m x y z : x ⊓ y ⊓ z ≤ y.\n  Proof.\n  transitivity (x ⊓ y).\n  - apply meet_lb_l.\n  - apply meet_lb_r.\n  Qed.\n\n  Lemma meet_lb_3_l x y z : x ⊓ y ⊓ z ≤ x.\n  Proof.\n  transitivity (x ⊓ y); apply meet_lb_l.\n  Qed.\n\n  Lemma meet_lb_3_assoc_l x y z : x ⊓ (y ⊓ z) ≤ x.\n  Proof.\n  apply meet_lb_l.\n  Qed.\n\n  Lemma meet_lb_3_assoc_m x y z : x ⊓ (y ⊓ z) ≤ y.\n  Proof.\n  transitivity (y ⊓ z).\n  - apply meet_lb_r.\n  - apply meet_lb_l.\n  Qed.\n\n  Lemma meet_lb_3_assoc_r x y z : x ⊓ (y ⊓ z) ≤ z.\n  Proof.\n  transitivity (y ⊓ z); apply meet_lb_r.\n  Qed.\n\n  Instance meet_sl_order_meet_sl: IsMeetSemiLattice L.\n  Proof.\n  repeat split.\n  - apply _.\n  - intros x y z. apply (antisymmetry (≤)).\n    + apply meet_glb.\n      * apply meet_glb.\n        ** apply meet_lb_3_assoc_l.\n        ** apply meet_lb_3_assoc_m.\n      * apply meet_lb_3_assoc_r.\n    + apply meet_glb.\n      ** apply meet_lb_3_l.\n      ** apply meet_glb.\n         *** apply meet_lb_3_m.\n         *** apply meet_lb_3_r.\n  - intros x y. apply (antisymmetry (≤)); apply meet_glb;\n    first [apply meet_lb_l | try apply meet_lb_r].\n  - intros x. red. apply (antisymmetry (≤)).\n    + apply meet_lb_l.\n    + apply meet_glb;apply reflexivity.\n  Qed.\n\n  Lemma meet_le_compat_r x y z : x ≤ z -> x ⊓ y ≤ z.\n  Proof.\n  intros E. transitivity x.\n  - apply meet_lb_l.\n  - trivial.\n  Qed.\n\n  Lemma meet_le_compat_l x y z : y ≤ z -> x ⊓ y ≤ z.\n  Proof.\n  intros E. rewrite (commutativity (f:=meet)).\n  apply meet_le_compat_r.\n  trivial.\n  Qed.\n\n  Lemma meet_l x y : x ≤ y -> x ⊓ y = x.\n  Proof.\n  intros E. apply (antisymmetry (≤)).\n  - apply meet_lb_l.\n  - apply meet_glb; trivial. apply reflexivity.\n  Qed.\n\n  Lemma meet_r x y : y ≤ x -> x ⊓ y = y.\n  Proof.\n  intros E. rewrite (commutativity (f:=meet)). apply meet_l.\n  trivial.\n  Qed.\n\n  Lemma meet_sl_le_spec x y : x ≤ y <-> x ⊓ y = x.\n  Proof.\n  split; intros E.\n  - apply meet_l;trivial.\n  - rewrite <-E. apply meet_lb_r.\n  Qed.\n\n  Global Instance: forall z, OrderPreserving (z ⊓).\n  Proof.\n  red;intros.\n  apply meet_glb.\n  - apply meet_lb_l.\n  - apply  meet_le_compat_l. trivial.\n  Qed.\n\n  Global Instance: forall z, OrderPreserving (⊓ z).\n  Proof.\n  intros. apply maps.order_preserving_flip.\n  Qed.\n\n  Lemma meet_le_compat x₁ x₂ y₁ y₂ : x₁ ≤ x₂ -> y₁ ≤ y₂ -> x₁ ⊓ y₁ ≤ x₂ ⊓ y₂.\n  Proof.\n  intros E1 E2. transitivity (x₁ ⊓ y₂).\n  - apply (order_preserving (x₁ ⊓)). trivial.\n  - apply (order_preserving (⊓ y₂)). trivial.\n  Qed.\n\n  Lemma meet_le x y z : z ≤ x -> z ≤ y -> z ≤ x ⊓ y.\n  Proof.\n  intros. rewrite <-(idempotency (⊓) z). apply meet_le_compat;trivial.\n  Qed.\n\n  Section total_meet.\n  Context `{!TotalRelation le}.\n\n  Lemma total_meet_either x y : meet x y = x |_| meet x y = y.\n  Proof.\n  destruct (total le x y) as [E|E].\n  - left. apply meet_l,E.\n  - right. apply meet_r,E.\n  Qed.\n\n  Definition min x y :=\n    match total le x y with\n    | inr _ => y\n    | inl _ => x\n    end.\n\n  Lemma total_meet_min x y : meet x y = min x y.\n  Proof.\n  unfold min. destruct (total le x y) as [E|E].\n  - apply meet_l,E.\n  - apply meet_r,E.\n  Qed.\n  End total_meet.\n\nEnd meet_semilattice_order.\n\nSection lattice_order.\n  Context `{LatticeOrder L}.\n\n  Instance: IsJoinSemiLattice L := join_sl_order_join_sl.\n  Instance: IsMeetSemiLattice L := meet_sl_order_meet_sl.\n\n  Instance: Absorption (⊓) (⊔).\n  Proof.\n  intros x y. apply (antisymmetry (≤)).\n  - apply meet_lb_l.\n  - apply meet_le.\n   + apply reflexivity.\n   + apply join_ub_l.\n  Qed.\n\n  Instance: Absorption (⊔) (⊓).\n  Proof.\n  intros x y. apply (antisymmetry (≤)).\n  - apply join_le.\n    + apply reflexivity.\n    + apply meet_lb_l.\n  - apply join_ub_l.\n  Qed.\n\n  Instance lattice_order_lattice: IsLattice L := {}.\n\n  Lemma meet_join_distr_l_le x y z : (x ⊓ y) ⊔ (x ⊓ z) ≤ x ⊓ (y ⊔ z).\n  Proof.\n  apply meet_le.\n  - apply join_le; apply meet_lb_l.\n  - apply join_le.\n    + transitivity y.\n      * apply meet_lb_r.\n      * apply join_ub_l.\n    + transitivity z.\n      * apply meet_lb_r.\n      * apply join_ub_r.\n  Qed.\n\n  Lemma join_meet_distr_l_le x y z : x ⊔ (y ⊓ z) ≤ (x ⊔ y) ⊓ (x ⊔ z).\n  Proof.\n  apply meet_le.\n  - apply join_le.\n    + apply join_ub_l.\n    + transitivity y.\n      * apply meet_lb_l.\n      * apply join_ub_r.\n  - apply join_le.\n    + apply join_ub_l.\n    + transitivity z.\n      * apply meet_lb_r.\n      * apply join_ub_r.\n  Qed.\nEnd lattice_order.\n\nDefinition default_join_sl_le `{IsJoinSemiLattice L} : Le L :=  fun x y => x ⊔ y = y.\n\nSection join_sl_order_alt.\n  Context `{IsJoinSemiLattice L} `{Le L} `{is_mere_relation L le}\n    (le_correct : forall x y, x ≤ y <-> x ⊔ y = y).\n\n  Lemma alt_Build_JoinSemiLatticeOrder : JoinSemiLatticeOrder (≤).\n  Proof.\n  repeat split.\n  - apply _.\n  - apply _.\n  - intros x.\n    apply le_correct. apply binary_idempotent.\n  - intros x y z E1 E2.\n    apply le_correct in E1;apply le_correct in E2;apply le_correct.\n    rewrite <-E2, simple_associativity, E1. reflexivity.\n  - intros x y E1 E2.\n    apply le_correct in E1;apply le_correct in E2.\n    rewrite <-E1, (commutativity (f:=join)).\n    apply symmetry;trivial.\n  - intros. apply le_correct.\n    rewrite simple_associativity,binary_idempotent.\n    reflexivity.\n  - intros;apply le_correct.\n    rewrite (commutativity (f:=join)).\n    rewrite <-simple_associativity.\n    rewrite (idempotency _ _).\n    reflexivity.\n  - intros x y z E1 E2.\n    apply le_correct in E1;apply le_correct in E2;apply le_correct.\n    rewrite <-simple_associativity, E2. trivial.\n  Qed.\nEnd join_sl_order_alt.\n\nDefinition default_meet_sl_le `{IsMeetSemiLattice L} : Le L :=  fun x y => x ⊓ y = x.\n\nSection meet_sl_order_alt.\n  Context `{IsMeetSemiLattice L} `{Le L} `{is_mere_relation L le}\n    (le_correct : forall x y, x ≤ y <-> x ⊓ y = x).\n\n  Lemma alt_Build_MeetSemiLatticeOrder : MeetSemiLatticeOrder (≤).\n  Proof.\n  repeat split.\n  - apply _.\n  - apply _.\n  - intros ?. apply le_correct. apply (idempotency _ _).\n  - intros ? ? ? E1 E2.\n    apply le_correct in E1;apply le_correct in E2;apply le_correct.\n    rewrite <-E1, <-simple_associativity, E2.\n    reflexivity.\n  - intros ? ? E1 E2.\n    apply le_correct in E1;apply le_correct in E2.\n    rewrite <-E2, (commutativity (f:=meet)).\n    apply symmetry,E1.\n  - intros ? ?. apply le_correct.\n    rewrite (commutativity (f:=meet)), simple_associativity, (idempotency _ _).\n    reflexivity.\n  - intros ? ?. apply le_correct.\n    rewrite <-simple_associativity, (idempotency _ _).\n    reflexivity.\n  - intros ? ? ? E1 E2.\n    apply le_correct in E1;apply le_correct in E2;apply le_correct.\n    rewrite associativity, E1.\n    trivial.\n  Qed.\nEnd meet_sl_order_alt.\n\nSection join_order_preserving.\n  Context `{JoinSemiLatticeOrder L} `{JoinSemiLatticeOrder K} (f : L -> K)\n    `{!IsJoinPreserving f}.\n\n  Lemma join_sl_mor_preserving: OrderPreserving f.\n  Proof.\n  intros x y E.\n  apply join_sl_le_spec in E. apply join_sl_le_spec.\n  rewrite <-preserves_join.\n  apply ap, E.\n  Qed.\n\n  Lemma join_sl_mor_reflecting `{!IsInjective f}: OrderReflecting f.\n  Proof.\n  intros x y E.\n  apply join_sl_le_spec in E. apply join_sl_le_spec.\n  rewrite <-preserves_join in E.\n  apply (injective f). assumption.\n  Qed.\nEnd join_order_preserving.\n\nSection meet_order_preserving.\n  Context `{MeetSemiLatticeOrder L} `{MeetSemiLatticeOrder K} (f : L -> K)\n    `{!IsMeetPreserving f}.\n\n  Lemma meet_sl_mor_preserving: OrderPreserving f.\n  Proof.\n  intros x y E.\n  apply meet_sl_le_spec in E. apply meet_sl_le_spec.\n  rewrite <-preserves_meet.\n  apply ap, E.\n  Qed.\n\n  Lemma meet_sl_mor_reflecting `{!IsInjective f}: OrderReflecting f.\n  Proof.\n  intros x y E.\n  apply meet_sl_le_spec in E. apply meet_sl_le_spec.\n  rewrite <-preserves_meet in E.\n  apply (injective f). assumption.\n  Qed.\nEnd meet_order_preserving.\n\nSection order_preserving_join_sl_mor.\n  Context `{JoinSemiLatticeOrder L} `{JoinSemiLatticeOrder K}\n    `{!TotalOrder (_ : Le L)} `{!TotalOrder (_ : Le K)}\n    `{!OrderPreserving (f : L -> K)}.\n\n  Lemma order_preserving_join_sl_mor: IsJoinPreserving f.\n  Proof.\n  intros x y. case (total (≤) x y); intros E.\n  - change (f (join x y) = join (f x) (f y)).\n    rewrite (join_r _ _ E),join_r;trivial.\n    apply (order_preserving _). trivial.\n  - change (f (join x y) = join (f x) (f y)).\n    rewrite 2!join_l; trivial. apply (order_preserving _). trivial.\n  Qed.\nEnd order_preserving_join_sl_mor.\n\nSection order_preserving_meet_sl_mor.\n  Context `{MeetSemiLatticeOrder L} `{MeetSemiLatticeOrder K}\n    `{!TotalOrder (_ : Le L)} `{!TotalOrder (_ : Le K)}\n    `{!OrderPreserving (f : L -> K)}.\n\n  Lemma order_preserving_meet_sl_mor: IsSemiGroupPreserving f.\n  Proof.\n  intros x y. case (total (≤) x y); intros E.\n  - change (f (meet x y) = meet (f x) (f y)).\n    rewrite 2!meet_l;trivial.\n    apply (order_preserving _). trivial.\n  - change (f (meet x y) = meet (f x) (f y)).\n    rewrite 2!meet_r; trivial.\n    apply (order_preserving _). trivial.\n  Qed.\nEnd order_preserving_meet_sl_mor.\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/Classes/orders/lattices.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6945918776168818}}
{"text": "(* -------------------------------------------------------------------- *)\nFrom mathcomp Require Import all_ssreflect all_algebra complex.\nRequire Import forms spectral.\nFrom mathcomp.analysis Require Import boolp reals.\nFrom mathcomp.real_closed Require Import complex.\n\nRequire Import mcextra prodvect hermitian tensor lfundef setdec.\nRequire Import mxpred mxtopology mxnorm quantum orthomodular.\n\n(************************************************************************)\n(* This file define subspace of Hilbert space and its theory            *)\n(*        {hspace H} == type of subspace ; coercion to linear function  *)\n(*\t\t\t'End(H) : the projection of the subspace        *)\n(*                      Canonical to pred : v \\in U                     *)\n(*  operations :                                                        *)\n(*      A `&` B : join (cup)                                            *)\n(*      A `|` B : meet (cap)                                            *)\n(*      A `\\` B : diff                                                  *)\n(*     A `<=` B : subseteq                                              *)\n(*      A `<` B : proper subset                                         *)\n(*          `0` : empty subspace                                        *)\n(* `1`  { : H } : full subspace                                         *)\n(*         ~` x : complement subspace                                   *)\n(*         \\cup : big operator of join                                  *)\n(*         \\cap : big operator of meet                                  *)\n(*      <[ v ]> : span of vector v                                      *)\n(*      << X >> : span of seq of vector v                               *)\n(*       kerh f : kernal of f , {v | f v = 0}                           *)\n(*     cokerh f : cokernal of f , {v | f^A v = 0}                       *)\n(*      supph f : support of f, = ~` kerh f                             *)\n(*    cosupph f : cosupport of f, = ~` cokerh f                         *)\n(************************************************************************)\n\n(* -------------------------------------------------------------------- *)\nImport Order.LTheory GRing.Theory Num.Theory ComplexField Num.Def complex Vector.InternalTheory.\n\n(* -------------------------------------------------------------------- *)\nSet   Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nUnset SsrOldRewriteGoalsOrder.\n\n(* -------------------------------------------------------------------- *)\nLocal Open Scope set_scope.\nLocal Open Scope ring_scope.\nLocal Open Scope lfun_scope.\n\nLocal Notation C := hermitian.C.\nLocal Notation R := hermitian.R.\n\nDeclare Scope hspace_scope.\nLocal Open Scope ring_scope.\n\nReserved Notation \"{ 'hspace' V }\" (at level 0, format \"{ 'hspace'  V }\").\n\n(* use notations of `<=` *)\nReserved Notation \"A `&` B\" (at level 48, left associativity).\nReserved Notation \"A `|` B\" (at level 52, left associativity).\nReserved Notation \"A `\\` B\" (at level 50, left associativity).\nReserved Notation \"A `<=` B\" (at level 70, no associativity).\nReserved Notation \"A `<` B\" (at level 70, no associativity).\nReserved Notation \"`0`\".\nReserved Notation \"`1`\".\nReserved Notation \"~` x\" (at level 35, right associativity).\n\n(* since we already use bigcup and bigcap for finset, we here use cup and cap for hspace *)\nReserved Notation \"\\cup_ i F\"\n  (at level 41, F at level 41, i at level 0,\n           format \"'[' \\cup_ i '/  '  F ']'\").\nReserved Notation \"\\cup_ ( i <- r | P ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\cup_ ( i  <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\cup_ ( i <- r ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\cup_ ( i  <-  r ) '/  '  F ']'\").\nReserved Notation \"\\cup_ ( m <= i < n | P ) F\"\n  (at level 41, F at level 41, m, i, n at level 50,\n           format \"'[' \\cup_ ( m  <=  i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\cup_ ( m <= i < n ) F\"\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\cup_ ( m  <=  i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\cup_ ( i | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\cup_ ( i  |  P ) '/  '  F ']'\").\nReserved Notation \"\\cup_ ( i : t | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\cup_ ( i   :  t   |  P ) '/  '  F ']'\").\nReserved Notation \"\\cup_ ( i : t ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\cup_ ( i   :  t ) '/  '  F ']'\").\nReserved Notation \"\\cup_ ( i < n | P ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\cup_ ( i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\cup_ ( i < n ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\cup_ ( i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\cup_ ( i 'in' A | P ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\cup_ ( i  'in'  A  |  P ) '/  '  F ']'\").\nReserved Notation \"\\cup_ ( i 'in' A ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\cup_ ( i  'in'  A ) '/  '  F ']'\").\n\nReserved Notation \"\\cap_ i F\"\n  (at level 41, F at level 41, i at level 0,\n           format \"'[' \\cap_ i '/  '  F ']'\").\nReserved Notation \"\\cap_ ( i <- r | P ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\cap_ ( i  <-  r  |  P )  F ']'\").\nReserved Notation \"\\cap_ ( i <- r ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\cap_ ( i  <-  r ) '/  '  F ']'\").\nReserved Notation \"\\cap_ ( m <= i < n | P ) F\"\n  (at level 41, F at level 41, m, i, n at level 50,\n           format \"'[' \\cap_ ( m  <=  i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\cap_ ( m <= i < n ) F\"\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\cap_ ( m  <=  i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\cap_ ( i | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\cap_ ( i  |  P ) '/  '  F ']'\").\nReserved Notation \"\\cap_ ( i : t | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\cap_ ( i   :  t   |  P ) '/  '  F ']'\").\nReserved Notation \"\\cap_ ( i : t ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\cap_ ( i   :  t ) '/  '  F ']'\").\nReserved Notation \"\\cap_ ( i < n | P ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\cap_ ( i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\cap_ ( i < n ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\cap_ ( i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\cap_ ( i 'in' A | P ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\cap_ ( i  'in'  A  |  P ) '/  '  F ']'\").\nReserved Notation \"\\cap_ ( i 'in' A ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\cap_ ( i  'in'  A ) '/  '  F ']'\").\n\nDelimit Scope hspace_scope with HS.\n\nLocal Open Scope hspace_scope.\nFact hspace_display : unit. Proof. by []. Qed.\n\nNotation \"x '`<=`' y\" := (@Order.le hspace_display _ x y) (at level 70, no associativity) : hspace_scope.\nNotation \"x '`<`' y\" := (@Order.lt hspace_display _ x y) (at level 70, no associativity) : hspace_scope.\nNotation \"x '`|`' y\" := (@Order.join hspace_display _ x y) (at level 52, left associativity) : hspace_scope.\nNotation \"x '`&`' y\" := (@Order.meet hspace_display _ x y) (at level 48, left associativity) : hspace_scope.\nNotation \"`0`\" := (@Order.bottom hspace_display _) : hspace_scope.\nNotation \"`1`\" := (@Order.top hspace_display _) : hspace_scope.\nNotation \"~` x\" := (@orthomodular.compl hspace_display _ x) (at level 35, right associativity) : hspace_scope.\nReserved Notation \"A `\\` B\" (at level 50, left associativity).\nNotation \"\\cup_ ( i <- r | P ) U\" :=\n  (\\big[ @Order.join hspace_display _ /`0`]_(i <- r | P%B) U%HS) : hspace_scope.\nNotation \"\\cup_ ( i <- r ) U\" :=\n  (\\big[ @Order.join hspace_display _ /`0`]_(i <- r) U%HS) : hspace_scope.\nNotation \"\\cup_ ( m <= i < n | P ) U\" :=\n  (\\big[ @Order.join hspace_display _ /`0`]_(m <= i < n | P%B) U%HS) : hspace_scope.\nNotation \"\\cup_ ( m <= i < n ) U\" :=\n  (\\big[ @Order.join hspace_display _ /`0`]_(m <= i < n) U%HS) : hspace_scope.\nNotation \"\\cup_ ( i | P ) U\" :=\n  (\\big[ @Order.join hspace_display _ /`0`]_(i | P%B) U%HS) : hspace_scope.\nNotation \"\\cup_ i U\" :=\n  (\\big[ @Order.join hspace_display _ /`0`]_i U%HS) : hspace_scope.\nNotation \"\\cup_ ( i : t | P ) U\" :=\n  (\\big[ @Order.join hspace_display _ /`0`]_(i : t | P%B) U%HS) (only parsing) : hspace_scope.\nNotation \"\\cup_ ( i : t ) U\" :=\n  (\\big[ @Order.join hspace_display _ /`0`]_(i : t) U%HS) (only parsing) : hspace_scope.\nNotation \"\\cup_ ( i < n | P ) U\" :=\n  (\\big[ @Order.join hspace_display _ /`0`]_(i < n | P%B) U%HS) : hspace_scope.\nNotation \"\\cup_ ( i < n ) U\" :=\n  (\\big[ @Order.join hspace_display _ /`0`]_(i < n) U%HS) : hspace_scope.\nNotation \"\\cup_ ( i 'in' A | P ) U\" :=\n  (\\big[ @Order.join hspace_display _ /`0`]_(i in A | P%B) U%HS) : hspace_scope.\nNotation \"\\cup_ ( i 'in' A ) U\" :=\n  (\\big[ @Order.join hspace_display _ /`0`]_(i in A) U%HS) : hspace_scope.\n\nNotation \"\\cap_ ( i <- r | P ) U\" :=\n  (\\big[ @Order.meet hspace_display _ /`1`]_(i <- r | P%B) U%HS) : hspace_scope.\nNotation \"\\cap_ ( i <- r ) U\" :=\n  (\\big[ @Order.meet hspace_display _ /`1`]_(i <- r) U%HS) : hspace_scope.\nNotation \"\\cap_ ( m <= i < n | P ) U\" :=\n  (\\big[ @Order.meet hspace_display _ /`1`]_(m <= i < n | P%B) U%HS) : hspace_scope.\nNotation \"\\cap_ ( m <= i < n ) U\" :=\n  (\\big[ @Order.meet hspace_display _ /`1`]_(m <= i < n) U%HS) : hspace_scope.\nNotation \"\\cap_ ( i | P ) U\" :=\n  (\\big[ @Order.meet hspace_display _ /`1`]_(i | P%B) U%HS) : hspace_scope.\nNotation \"\\cap_ i U\" :=\n  (\\big[ @Order.meet hspace_display _ /`1`]_i U%HS) : hspace_scope.\nNotation \"\\cap_ ( i : t | P ) U\" :=\n  (\\big[ @Order.meet hspace_display _ /`1`]_(i : t | P%B) U%HS) (only parsing) : hspace_scope.\nNotation \"\\cap_ ( i : t ) U\" :=\n  (\\big[ @Order.meet hspace_display _ /`1`]_(i : t) U%HS) (only parsing) : hspace_scope.\nNotation \"\\cap_ ( i < n | P ) U\" :=\n  (\\big[ @Order.meet hspace_display _ /`1`]_(i < n | P%B) U%HS) : hspace_scope.\nNotation \"\\cap_ ( i < n ) U\" :=\n  (\\big[ @Order.meet hspace_display _ /`1`]_(i < n) U%HS) : hspace_scope.\nNotation \"\\cap_ ( i 'in' A | P ) U\" :=\n  (\\big[ @Order.meet hspace_display _ /`1`]_(i in A | P%B) U%HS) : hspace_scope.\nNotation \"\\cap_ ( i 'in' A ) U\" :=\n  (\\big[ @Order.meet hspace_display _ /`1`]_(i in A) U%HS) : hspace_scope.\n\nSection HspaceType.\nVariable (V : chsType).\n(* projection as sub hilbert space *)\n\nVariant hspace_t := Hspace of 'FP(V).\nCoercion hspace_proj (M : hspace_t) := let: Hspace M := M in M.\nCanonical hspace_t_subType := Eval hnf in [newType for hspace_proj].\n\nDefinition hspace_t_eqMixin := Eval hnf in [eqMixin of hspace_t by <:].\nCanonical  hspace_t_eqType  := Eval hnf in EqType hspace_t hspace_t_eqMixin.\nDefinition hspace_t_choiceMixin := [choiceMixin of hspace_t by <:].\nCanonical  hspace_t_choiceType  := Eval hnf in ChoiceType hspace_t hspace_t_choiceMixin.\n\nDefinition projlf_lporderMixin := [porderMixin of 'FP(V) by <:].\nCanonical projlf_lporderType :=\n  Eval hnf in POrderType vorder_display 'FP(V) projlf_lporderMixin.\nDefinition hspace_t_porderMixin := [porderMixin of hspace_t by <:].\nCanonical hspace_t_porderType :=\n  Eval hnf in POrderType hspace_display hspace_t hspace_t_porderMixin.\n\nLemma hspace_inj : injective hspace_proj. Proof. exact: val_inj. Qed.\n\nDefinition hspace_of of phant V := hspace_t.\nIdentity Coercion type_hspace_of : hspace_of >-> hspace_t.\nEnd HspaceType.\n\nBind Scope ring_scope with hspace_of.\nBind Scope ring_scope with hspace_t.\n\nNotation \"{ 'hspace' V }\" := (@hspace_of _ (Phant V)).\n\nSection HspaceOf.\nVariable (V : chsType).\nCanonical hspace_subType    := Eval hnf in [subType    of {hspace V}].\nCanonical hspace_eqType     := Eval hnf in [eqType     of {hspace V}].\nCanonical hspace_choiceType := Eval hnf in [choiceType of {hspace V}].\nCanonical hspace_porderType := Eval hnf in [porderType of {hspace V}].\nEnd HspaceOf.\n\nSection HspaceOfProj.\nVariable (H : chsType).\n\nFact hspace_key : unit. Proof. by []. Qed.\nDefinition hspace_of_proj_def (P : 'FP(H)) : {hspace H} := Hspace P.\nDefinition hspace_of_proj := locked_with hspace_key hspace_of_proj_def.\nCanonical hspace_of_unlockable := [unlockable of hspace_of_proj].\n\nLemma hsE F : (hspace_of_proj F)%:VF = F.\nProof. by rewrite unlock/=. Qed.\n\nLemma hspaceP (A B : {hspace H}) : A =1 B <-> A = B.\nProof. by split=>[eqAB|->//]; apply/val_inj/val_inj=>/=; apply/lfunP. Qed.\n\nLemma eq_hs (F1 F2 : 'FP(H)) : \n  (F1 =1 F2) -> hspace_of_proj F1 = hspace_of_proj F2.\nProof. by move=> eq_F; apply/hspaceP => v; rewrite !hsE eq_F. Qed.\n\nEnd HspaceOfProj.\n\n\nNotation HSType P := (hspace_of_proj P).\n\nImport Vector.InternalTheory.\n\nSection HspacePred.\nVariable (H : chsType).\nImplicit Type (U V : {hspace H}).\n\nDefinition pred_of_hspace U : {pred H} :=\n  (fun v => U v == v).\nCanonical hspace_predType :=\n  @PredType _ {hspace H} (@pred_of_hspace).\n\nLemma memhE U x : x \\in U = (U x == x).\nProof. by []. Qed.\n\nEnd HspacePred.\n\nSection HspaceSupport.\nVariable (T : numClosedFieldType).\n\nDefinition boolmx_of m n (M : 'M[T]_(m,n)) : 'M[T]_(m,n) :=\n  \\matrix_(i,j) (M i j != 0)%:R.\nLemma boolmx_of_bool m n (M : 'M[T]_(m,n)) :\n  boolmx_of M \\is a boolmx.\nProof. by apply/boolmxP=>i j; rewrite !mxE; case: (M i j != 0); rewrite eqxx// orbT. Qed.\n\nLemma boolmx_of_map m n (M : 'M[T]_(m,n)) (f : {rmorphism T -> T}) :\n  map_mx f (boolmx_of M) = (boolmx_of M).\nProof. by apply/matrixP=>i j; rewrite !mxE; case: (M i j != 0); rewrite ?rmorph0 ?rmorph1. Qed.\n\nLemma boolmx_of_conj m n (M : 'M[T]_(m,n)) :\n  (boolmx_of M)^*m = (boolmx_of M).\nProof. exact: boolmx_of_map. Qed.\n\nLemma boolmx_of_idem m n (M : 'M[T]_(m,n)) :\n  (boolmx_of M) .* (boolmx_of M) = (boolmx_of M).\nProof. apply/boolmx_dmul/boolmx_of_bool. Qed.\n\nLemma boolmx_of_mulid m n (M : 'M[T]_(m,n)) :\n  (boolmx_of M) .* M = M.\nProof.\napply/matrixP=>i j; rewrite !mxE; case: eqP=>[->|_];\nby rewrite ?mulr0// mul1r.\nQed.\n\nLemma boolmx_of_diag m (M : 'rV[T]_m) :\n  boolmx_of (diag_mx M) = diag_mx (boolmx_of M).\nProof.\napply/matrixP=>i j; rewrite !mxE.\nby case: (i == j); rewrite ?mulr1n// ?mulr0n eqxx.\nQed.\n\nLemma boolmx_of_inv m n (A : 'M[T]_(m,n)) :\n  boolmx_of A = A .^-1 .* A.\nProof.\napply/matrixP=>i j; rewrite !mxE.\nby case: eqP=>[->|/eqP P1]; rewrite ?mulr0// mulVf.\nQed.\n\nLemma svd_d_invC m n (A : 'M[T]_(m,n)) :\n  ((svd_d A).^-1)^*m = (svd_d A).^-1.\nProof. \napply/matrixP=>i j; rewrite !mxE geC0_conj// invr_ge0 -nnegrE.\napply/nnegmxP/svd_diag_nneg/svd_d_svd_diag.\nQed.\n\nLemma svd_d_conj m n (A : 'M[T]_(m, n)) :\n  (svd_d A)^*m = svd_d A.\nProof.\napply/matrixP=>i j; rewrite mxE; apply/CrealP/realmxP/svd_diag_real/svd_d_svd_diag.\nQed.\n\nLemma svd_d_exdr_mul m n (M N : 'rV[T]_(minn m n)) :\n  svd_d_exdr M .* svd_d_exdr N = svd_d_exdr (M .* N).\nProof.\napply/matrixP=>i j; rewrite !mxE !castmxE/= cast_ord_id.\nset x := (cast_ord (esym (min_idr m n)) j).\nrewrite  -(splitK x); case: (fintype.split x)=>a/=;\nby rewrite ?row_mxEl ?row_mxEr mxE// mul0r.\nQed.\n\nLemma cdiag_diag_mul m n (A B : 'rV[T]_(minn m n)) :\n  cdiag_mx A *m diag_mx (svd_d_exdr B) = cdiag_mx (A .* B).\nProof.\nrewrite mul_mx_diag; apply/matrixP=>i j.\nrewrite mxE !castmxE/= cast_ord_id.\nset x := (cast_ord (esym (min_idl m n)) i).\nset y := (cast_ord (esym (min_idr m n)) j).\nrewrite  -(splitK x) -(splitK y).\ncase: (fintype.split x)=>a/=; case: (fintype.split y)=>b/=;\nrewrite ?block_mxEdl ?block_mxEdr ?block_mxEul ?block_mxEur ?row_mxEl ?row_mxEr;\nby rewrite !mxE ?mul0r//; case: eqP=>[->|_]; rewrite ?mulr1n// !mulr0n mul0r.\nQed.\n\nDefinition pinvmx_ m n (A : 'M[T]_(m,n)) :=\n  (svd_u A) *m cdiag_mx ((svd_d A).^-1) *m (svd_v A)^*t.\n\nLemma mxrank_cast (R : fieldType) p q p' q' (eqpq : (p = p') * (q = q')) (A : 'M[R]_(p,q)) :\n  \\rank (castmx eqpq A) = \\rank A.\nProof. by case: eqpq=>P Q; case: p' / P; case: q' / Q; rewrite castmx_id. Qed.\n\nLemma rank_cdiagmx p q (d : 'rV[T]_(minn p q)) :\n  \\rank (cdiag_mx d) = \\rank (diag_mx d).\nProof. by rewrite /cdiag_mx mxrank_cast rank_diag_block_mx mxrank0 addn0. Qed.\n\nLemma pinvmx_rank m n (A : 'M[T]_(m,n)) :\n  \\rank (pinvmx_ A) = \\rank A.\nProof. \nrewrite /pinvmx_ {4}(svdE A). do 2 rewrite mxrank_mulmxUC ?svd_pE// mxrank_mulUmx ?svd_pE//.\nrewrite !rank_cdiagmx !rank_diagmx; apply eq_bigr=>i _.\nby rewrite mxE invr_eq0.\nQed.\n\nLemma mxrank_conj m n (A : 'M[T]_(m,n)) :\n  \\rank (A^*m) = \\rank A.\nProof. by rewrite conjmxE mxrank_map. Qed.\n\nLemma mxrank_trmxC m n (A : 'M[T]_(m,n)) :\n  \\rank (A^*t) = \\rank A.\nProof. by rewrite adjmxEr mxrank_conj mxrank_tr. Qed.\n\nDefinition suppmx m n (A : 'M[T]_(m,n)) :=\n  A *m (pinvmx_ A)^*t.\n\nDefinition cosuppmx m n (A : 'M[T]_(m,n)) :=\n  (pinvmx_ A)^*t *m A.\n\nLemma suppmx_herm m n (A : 'M[T]_(m,n)) :\n  suppmx A \\is hermmx.\nProof.\napply/hermmxP; rewrite /suppmx {1 3}(svdE A) /pinvmx_ !adjmxM !adjmxK !mulmxA.\nrewrite !mulmxKtV ?svd_pE//; f_equal; rewrite -!mulmxA; f_equal.\nby rewrite !cdiag_mx_mull svd_d_invC svd_d_conj dmulmxC.\nQed.\n\nLemma cosuppmx_herm m n (A : 'M[T]_(m,n)) :\n  cosuppmx A \\is hermmx.\nProof.\napply/hermmxP; rewrite /cosuppmx {2 4}(svdE A) /pinvmx_ !adjmxM !adjmxK !mulmxA.\nrewrite !mulmxKtV ?svd_pE//; f_equal; rewrite -!mulmxA; f_equal.\nby rewrite !cdiag_mx_mulr svd_d_invC svd_d_conj dmulmxC.\nQed.\n\nLemma suppmx_id m n (A : 'M[T]_(m,n)) :\n  suppmx A *m A = A.\nProof.\nrewrite /suppmx {1 3 4}(svdE A) /pinvmx_ !adjmxM !adjmxK !mulmxA.\nrewrite !mulmxKtV ?svd_pE//; f_equal; rewrite -!mulmxA; f_equal.\nby rewrite cdiag_mx_mulr svd_d_invC svd_d_exdr_mul -boolmx_of_inv \n  cdiag_diag_mul dmulmxC boolmx_of_mulid.\nQed.\n\nLemma cosuppmx_id m n (A : 'M[T]_(m,n)) :\n  A *m cosuppmx A = A.\nProof. by move: (suppmx_id A); rewrite /cosuppmx mulmxA. Qed.\n\nLemma suppmx_rank m n (A : 'M[T]_(m,n)) :\n  \\rank (suppmx A) = \\rank A.\nProof.\napply/eqP; rewrite eq_le; apply/andP; split.\nrewrite /suppmx; exact: mxrankM_maxl.\nrewrite -{1}(suppmx_id A); exact: mxrankM_maxl.\nQed.\n\nLemma cosuppmx_rank m n (A : 'M[T]_(m,n)) :\n  \\rank (cosuppmx A) = \\rank A.\nProof.\napply/eqP; rewrite eq_le; apply/andP; split.\nrewrite /cosuppmx; exact: mxrankM_maxr.\nrewrite -{1}(cosuppmx_id A); exact: mxrankM_maxr.\nQed.\n\nLemma suppmx_proj m n (A : 'M[T]_(m,n)) :\n  suppmx A \\is projmx.\nProof.\napply/projmxP_id; split; first by apply suppmx_herm.\nby rewrite {2}/suppmx mulmxA suppmx_id.\nQed.\n\nLemma cosuppmx_proj m n (A : 'M[T]_(m,n)) :\n  cosuppmx A \\is projmx.\nProof.\napply/projmxP_id; split; first by apply cosuppmx_herm.\nby rewrite {1}/cosuppmx -mulmxA cosuppmx_id.\nQed.\n\nEnd HspaceSupport.\n\nSection HspaceSupportLf.\nVariable (H : chsType).\nImplicit Type (G : chsType).\n\nDefinition pinvlf G (A : 'Hom(H,G)) := Vector.Hom (pinvmx_ (f2mx A)).\n\nDefinition supplf G (A : 'Hom(H,G)) := (pinvlf A)^A \\o A.\n\nDefinition cosupplf G (A : 'Hom(H,G)) := A \\o (pinvlf A)^A.\n\nLemma pinvlf_rank G (A : 'Hom(H,G)) : \\Rank (pinvlf A) = \\Rank A.\nProof. exact: pinvmx_rank. Qed.\n\nLemma supplf_rank G (A : 'Hom(H,G)) : \\Rank (supplf A) = \\Rank A.\nProof. by rewrite /lfrank/supplf f2mx_comp/= -[RHS]suppmx_rank. Qed.\n\nLemma cosupplf_rank G (A : 'Hom(H,G)) : \\Rank (cosupplf A) = \\Rank A.\nProof. by rewrite /lfrank/cosupplf f2mx_comp/= -[RHS]cosuppmx_rank. Qed.\n\nLemma suppvlf G (A : 'Hom(H,G)) : A \\o supplf A = A.\nProof. apply/f2mx_inj; rewrite /supplf !f2mx_comp/=; exact: suppmx_id. Qed.\n\nLemma cosupplfv G (A : 'Hom(H,G)) : cosupplf A \\o A = A.\nProof. apply/f2mx_inj; rewrite /cosupplf !f2mx_comp/=; exact: cosuppmx_id. Qed.\n\nLemma supplf_proj G (A : 'Hom(H,G)) : supplf A \\is projlf.\nProof. rewrite qualifE /supplf f2mx_comp/=; exact: suppmx_proj. Qed.\nCanonical supplf_projfType G A := ProjfType (@supplf_proj G A).\nCanonical supplf_obsfType G (A : 'Hom(H,G)) := Eval hnf in \n  [obs of supplf A as [obs of [proj of supplf A]]].\nCanonical supplf_psdfType G (A : 'Hom(H,G)) := Eval hnf in \n  [psd of supplf A as [psd of [proj of supplf A]]].\nCanonical supplf_hermfType G (A : 'Hom(H,G)) := Eval hnf in \n  [herm of supplf A as [herm of [proj of supplf A]]].\n\nLemma cosupplf_proj G (A : 'Hom(H,G)) : cosupplf A \\is projlf.\nProof. rewrite qualifE /cosupplf f2mx_comp/=; exact: cosuppmx_proj. Qed.\nCanonical cosupplf_projfType G A := ProjfType (@cosupplf_proj G A).\nCanonical cosupplf_obsfType G (A : 'Hom(H,G)) := Eval hnf in \n  [obs of cosupplf A as [obs of [proj of cosupplf A]]].\nCanonical cosupplf_psdfType G (A : 'Hom(H,G)) := Eval hnf in \n  [psd of cosupplf A as [psd of [proj of cosupplf A]]].\nCanonical cosupplf_hermfType G (A : 'Hom(H,G)) := Eval hnf in \n  [herm of cosupplf A as [herm of [proj of cosupplf A]]].\n\nEnd HspaceSupportLf.\n\nSection MatrixExtra.\nVariable (R: numClosedFieldType) (m : nat).\nImplicit Type (A : 'M[R]_m).\n\nLemma uintmx_dexp p q (B : 'M[R]_(p,q)) n : B \\is a uintmx -> B.^+ n \\is a uintmx.\nProof.\nmove=>/uintmxP P1; apply/uintmxP=>i j; move: (P1 i j); \n  rewrite mxE=>/andP[P2 P3]; apply/andP; split.\nrewrite exprn_ge0//. by apply: exprn_ile1.\nQed.\n\nLemma obsmx_idem_obs A : A \\is obsmx -> A *m A \\is obsmx.\nProof.\nmove=>/obsmxP[Ah sA]; move: {+}Ah {+}Ah=>/hermmx_normal/unitarymx_spectralP Ad/hermmxP Aa.\napply/obsmxP; split. by apply/hermmxP; rewrite adjmxM -Aa.\nrewrite {1}Aa.\nhave /esym: A^*t *m A = (spectralmx A)^*t *m diag_mx ((spectral_diag A).^+2) *m spectralmx A.\nrewrite {1 2}Ad !adjmxM adjmxK !mulmxA  mulmxtVK ?spectral_unitarymx// diag_mx_adj mulmxACA diag_mx_dmul.\ndo ? f_equal; apply/matrixP=>i j; rewrite !mxE -normCKC ger0_norm//.\nby apply/nnegmxP/uintmx_nneg.\nmove=>/(spectral_unique (spectral_unitarymx _))[s Ps].\nby apply/uintmxP=>i j; rewrite -Ps mxE; apply/uintmxP/uintmx_dexp.\nQed.\nEnd MatrixExtra.\n\nSection Projlf.\nVariable (H : chsType).\nImplicit Type (U V W : {hspace H}).\n\nLemma ranklf_le_dom (G : chsType) (U : 'Hom(H,G)) : (\\Rank U <= Vector.dim H)%N.\nProof. by rewrite /lfrank rank_leq_row. Qed.\nLemma ranklf_le_codom (G : chsType) (U : 'Hom(H,G)) : (\\Rank U <= Vector.dim G)%N.\nProof. by rewrite /lfrank rank_leq_col. Qed.\n\nDefinition dimh U := \\Rank U.\nNotation \"\\Dim U\" := (dimh U) (at level 10, U at level 8, format \"\\Dim  U\").\n\nLemma dimh_rank U : \\Dim U = \\Rank U. Proof. by []. Qed.\nLemma dimh_trlf U : (\\Dim U)%:R = \\Tr U. \nProof. by rewrite dimh_rank projlf_trlf// projf_proj. Qed.\n\nLemma obslf_idem_obs (P : 'End(H)) : P \\is obslf -> P \\o P \\is obslf.\nProof. by rewrite qualifE=>/obsmx_idem_obs; rewrite [_ \\is obslf]qualifE f2mx_comp. Qed.\n\nLemma obslf_idem_obsV (P : 'End(H)) : P \\is psdlf -> P \\o P \\is obslf -> P \\is obslf.\nProof.\nmove=>P1/obslfP[_ P2]; apply/obslfP; split=>// u.\nrewrite -(@ler_pexpn2r _ 2%N)// ?nnegrE// ?ge0_dotp//.\n2: rewrite -[[< u; P u >]]ger0_norm. 1,2: by apply/psdlfP.\napply: (le_trans (CauchySchwartz _ _)); rewrite expr2 ler_pmul// ?ge0_dotp//.\nby rewrite hermlf_dotE ?psdlf_herm// -comp_lfunE.\nQed.\n\nLemma obslf_norm (P : 'End(H)) x : P \\is obslf -> `|P x| <= `|x|.\nProof.\nmove=>P1; rewrite -(@ler_pexpn2r _ 2%N)// ?nnegrE// -!dotp_norm.\nrewrite hermlf_dotE ?obslf_herm// -comp_lfunE.\nby move: P1=>/obslf_idem_obs/obslfP[].\nQed.\nLemma obsf_norm (P : 'FO(H)) x : `|P x| <= `|x|.\nProof. apply/obslf_norm/obsf_obs. Qed.\n\n(* we focus on projlf *)\nLemma projlf_norm (P : 'End(H)) x : P \\is projlf -> `|P x| <= `|x|.\nProof. by move=>P1; apply/obslf_norm/projlf_obs. Qed.\n\nLemma projf_norm (P : 'FP(H)) x : `|P x| <= `|x|.\nProof. exact: obsf_norm. Qed.\n\nLemma cplmt_dec (U : 'End(H)) x : x = U x + (cplmt U) x.\nProof. by rewrite /cplmt lfunE/= !lfunE/= addrC addrNK. Qed.\n\nLemma projf_cplmtMr (P : 'FP(H)) : P \\o P^⟂ = 0.\nProof. by rewrite /cplmt linearBr/= projf_idem comp_lfun1r subrr. Qed.\nLemma projf_cplmtMl (P : 'FP(H)) : P^⟂ \\o P = 0.\nProof. by rewrite /cplmt linearBl/= projf_idem comp_lfun1l subrr. Qed.\n\nLemma projf_lefCP (P1 P2 : 'FP(H)) : (forall x, P2 x == 0 -> (P1 x == 0)) -> P1%:VF ⊑ P2.\nProof.\nmove=>H1. apply/lef_dot=>v. rewrite !projf_dot/= ler_pexpn2r// ?nnegrE//.\nrewrite {1}(cplmt_dec P2 v) linearD/=.\nhave /H1/eqP-> : (P2 (P2^⟂ v) == 0) by rewrite -comp_lfunE projf_cplmtMr lfunE.\nby rewrite addr0 projf_norm.\nQed.\n\nLemma projf_lefP (P1 P2 : 'FP(H)) : (forall x, P1 x == x -> (P2 x == x)) -> P1%:VF ⊑ P2.\nProof.\nmove=>H1. rewrite cplmt_lef; apply/projf_lefCP=>x/=.\nby rewrite /cplmt !lfunE/= !lfunE/= subr_eq0 eq_sym=>/H1/eqP->; rewrite subrr.\nQed.\n\nLemma projf_eqCP (P1 P2 : 'FP(H)) : (forall x, P1 x == 0 = (P2 x == 0)) -> P1 = P2.\nProof. by move=>IH; apply/val_inj/le_anti/andP; split; apply/projf_lefCP=>x; rewrite IH. Qed.\n\nLemma projf_eqP (P1 P2 : 'FP(H)) : (forall x, P1 x == x = (P2 x == x)) -> P1 = P2.\nProof. by move=>IH; apply/val_inj/le_anti/andP; split; apply/projf_lefP=>x; rewrite IH. Qed.\n\nEnd Projlf.\n\nNotation \"\\Dim U\" := (dimh U) (at level 10, U at level 8, format \"\\Dim  U\").\n\nSection VS2Proj.\nVariable (H : chsType).\n\nLet memvK v (U : {vspace H}) : (v \\in U) = (v2r v <= vs2mx U)%MS.\nProof. by rewrite -genmxE. Qed.\n\nLemma vs2hs_proj (U : {vspace H}) : Vector.Hom (cosuppmx (vs2mx U)) \\is projlf.\nProof. by rewrite qualifE/= cosuppmx_proj. Qed.\n\nDefinition vs2hs (U : {vspace H}) := HSType (ProjfType (vs2hs_proj U)).\n\nLemma memv2h (U : {vspace H}) x : x \\in U = (x \\in vs2hs U).\nProof. \nrewrite memhE hsE -(can_eq v2rK) unlock/= r2vK memvK; apply/eqb_iff; split.\nrewrite /vs2hs; move=>/submxP[D]. set A := vs2mx U.\nmove=>->. rewrite -mulmxA cosuppmx_id//.\nmove=>/eqP; rewrite /cosuppmx mulmxA=>P.\napply/submxP; exists (v2r x *m (pinvmx_ (vs2mx U))^*t).\nby rewrite P.\nQed.\n\nDefinition hs2vs (P : {hspace H}) := mx2vs (f2mx P).\nLemma vs2hsK : cancel vs2hs hs2vs.\nProof.\nmove=>U. rewrite /hs2vs/= hsE/=.\napply/vspaceP=>x. rewrite [RHS]memv2h/vs2hs/= memhE hsE -(can_eq v2rK) unlock/= r2vK.\nmove: (cosuppmx_proj (vs2mx U))=>/projmxP_id[_] P.\nrewrite memvK mx2vsK; apply/eqb_iff; split.\nby move=>/submxP[D] ->; rewrite -mulmxA P.\nby move=>/eqP P1; apply/submxP; exists (v2r x); rewrite P1.\nQed.\n\nLemma vs2hs_inj : injective vs2hs.\nProof. exact: (can_inj vs2hsK). Qed.\n\nLemma memh2v (U : {hspace H}) x : (x \\in U) = (x \\in hs2vs U).\nProof. \nrewrite memhE -(can_eq v2rK) unlock/= /hs2vs r2vK memvK; apply/eqb_iff.\nmove: (mx2vsK (f2mx U))=>/eqmxP/andP[P1 P2].\nmove: (projf_idem U)=>/(f_equal f2mx); rewrite f2mx_comp=>P3.\nsplit=>[/eqP P4|P4].\nby apply: (submx_trans _ P2); apply/submxP; exists (v2r x); rewrite P4.\nby move: (submx_trans P4 P1)=>/submxP[D]->; rewrite -mulmxA P3.\nQed.\n\nLemma hs2vs_inj : injective hs2vs.\nProof.\nmove=>U1 U2 /vspaceP=>P. apply/val_inj/projf_eqP=>x.\nby move: (P x); rewrite -!memh2v.\nQed.\n\nLemma hs2vsK : cancel hs2vs vs2hs.\nProof. by move=>U; apply/hs2vs_inj/vs2hsK. Qed.\n\nEnd VS2Proj.\n\n\nModule HspaceOrthoModularLattice.\n\nModule Import BasicConstruct.\n\n(* this construct will be hide after Orthomodular lattices *)\nSection BasicConstruct.\nVariable (H : chsType).\nImplicit Type (U : {hspace H}).\n\nDefinition hspace0 := HSType (zero_projfType H).\nDefinition hspace1 := HSType (one_projfType H).\nDefinition hscmplt U := HSType (cplmt_projfType U).\nDefinition supph G A := HSType (@supplf_projfType H G A).\nDefinition cosupph G A := HSType (@cosupplf_projfType H G A).\n\nDefinition cuph U V := supph (U%:VF + V).\nDefinition caph U V := (hscmplt (cuph (hscmplt U) (hscmplt V))).\n\nLemma hscmpltE U : (hscmplt U)%:VF = U^⟂.\nProof. by rewrite hsE. Qed.\n\nLemma hs_vec_dec U x : x = U x + (hscmplt U) x.\nProof. by rewrite hsE/= /cplmt lfunE/= !lfunE/= addrC addrNK. Qed.\n\nEnd BasicConstruct.\nEnd BasicConstruct.\n\nNotation \"P '^⟂'\" := (hscmplt P) : hspace_scope.\nNotation hs1 := (@hspace1 _).\nNotation hs0 := (@hspace0 _).\n\n(* don't export *)\nModule Import HspacePredTheory.\n\nSection HspacePredTheory.\nVariable (H : chsType).\nImplicit Type (U V : {hspace H}) (x y : H).\n\nLemma hs_sub_t U V : (U `<=` V) = ((U : (hspace_t _)) `<=` V).\nProof. by []. Qed.\n\nLemma hs_sub_proj U V : (U `<=` V) = ((U : 'FP) ⊑ V).\nProof. by []. Qed.\n\nLemma leh_lef U V : (U `<=` V) = (U%:VF ⊑ V).\nProof. by rewrite hs_sub_t hs_sub_proj leEsub. Qed.\n\nLemma memhCE U x : x \\in U = ((U^⟂)%HS x == 0).\nProof. \nby rewrite memhE eq_sym -subr_eq0 hsE/= /cplmt lfunE/= !lfunE/=.\nQed.\n\nLemma memhP U x : reflect (U x = x) (x \\in U).\nProof. by rewrite memhE; exact: eqP. Qed.\n\nLemma memhCP U x : reflect ((U^⟂)%HS x = 0) (x \\in U).\nProof. by rewrite memhCE; exact: eqP. Qed.\n\nLemma memh_dotCE U x : x \\in U = ([< x ; (U^⟂)%HS x >] == 0).\nProof. by rewrite memhCE projf_dot expf_eq0/= normr_eq0. Qed.\n\nLemma memh_dotE U x : x \\in U = ([< x ; U x >] == [< x ; x >]).\nProof. by rewrite memh_dotCE hsE/= /cplmt/= lfunE/= !lfunE/= linearBr/= subr_eq0 eq_sym. Qed.  \n\nLemma memh_dotCP U x : reflect ([< x ; (U^⟂)%HS x >] = 0) (x \\in U).\nProof. rewrite memh_dotCE; exact: eqP. Qed.\n\nLemma memh_dotP U x : reflect ([< x ; U x >] = [< x ; x >]) (x \\in U).\nProof. rewrite memh_dotE; exact: eqP. Qed. \n\nLemma memh_proj U x : U x \\in U.\nProof. by rewrite memhE -comp_lfunE projf_idem. Qed.\n\nLemma memh_projC U x : (U^⟂)%HS (U x) = 0.\nProof. by apply/memhCP/memh_proj. Qed.\n\nLemma memh_normE U x : x \\in U = (`|U x| == `|x|).\nProof. by rewrite memh_dotE projf_dot dotp_norm eqr_expn2//. Qed.\n\nLemma memh_normCE U x : x \\in U = (`|(U^⟂)%HS x| == 0).\nProof. by rewrite memh_dotCE projf_dot expf_eq0/=. Qed.\n\nLemma memh_normP U x : reflect (`|U x| = `|x|) (x \\in U).\nProof. rewrite memh_normE; exact: eqP. Qed.\n\nLemma memh_normCP U x : reflect (`|(U^⟂)%HS x| = 0) (x \\in U).\nProof. rewrite memh_normCE; exact: eqP. Qed.\n\nLemma lehP U V : \n  reflect (forall x, (x \\in U) -> (x \\in V)) (U `<=` V).\nProof.\nrewrite leh_lef; apply/(iffP idP).\nrewrite cplmt_lef=>/lef_dot P x; rewrite !memh_normCE !hsE/==>/eqP P1; move: (P x).\nby rewrite !projf_dot/= ler_pexpn2r// ?nnegrE// P1 normr_le0=>/eqP->; rewrite normr0.\nmove=>P. rewrite cplmt_lef; apply/lef_dot=>x.\nrewrite -!hscmpltE !projf_dot ler_pexpn2r// ?nnegrE// (hs_vec_dec U x).\nrewrite !linearD/= memh_projC projlf_idemE.\nmove: (P _ (memh_proj U x))=>/memhCP->.\nby rewrite ?add0r projf_norm.\nQed.\n\nLemma lehCP U V : \n  reflect (forall x, (x \\in (V^⟂)%HS) -> (x \\in (U^⟂)%HS)) (U `<=` V).\nProof. rewrite leh_lef cplmt_lef -!hscmpltE -leh_lef; exact: lehP. Qed.\n\nLemma eqhP (U V : {hspace H}) : U =i V <-> U = V.\nProof. by split=>[P|->//]; apply/le_anti/andP; split; apply/lehP=>x; rewrite P. Qed.\n\nLemma mem0h U : 0 \\in U.\nProof. by rewrite memhE linear0. Qed.\n\nLemma memh1 x : x \\in hs1.\nProof. by rewrite memhE hsE/= lfunE. Qed.\n\nLemma memh0 x : x \\in hs0 = (x == 0).\nProof. by rewrite memhE hsE/= lfunE/= eq_sym. Qed.\n\nLemma le0h U : hs0 `<=` U.\nProof. by apply/lehP=>x; rewrite memh0=>/eqP->; apply/mem0h. Qed.\n\nLemma leh1 U : U `<=` hs1.\nProof. apply/lehP=>x _; apply/memh1. Qed.\n\nLemma hsC0 : (hs0^⟂)%HS = hs1 :> {hspace H}.\nProof. by apply/hspaceP=>x; rewrite hsE/=/cplmt !hsE/= subr0. Qed.\n\nLemma hsC1 : (hs1^⟂)%HS = hs0 :> {hspace H}.\nProof. by apply/hspaceP=>x; rewrite hsE/= /cplmt!hsE/= subrr. Qed.\n\nLemma hsCK U : ((U^⟂)%HS^⟂)%HS = U.\nProof. by apply/hspaceP=>v; rewrite hsE/= hsE/= cplmtK. Qed.\n\nLemma hsC_inj : injective (@hscmplt H).\nProof. exact: (can_inj hsCK). Qed.\n\nLemma hsC_eq U V : (U^⟂)%HS == (V^⟂)%HS = (U == V).\nProof. by rewrite (can_eq hsCK). Qed.\n\nLemma hsC_eq_sym U V : (U^⟂)%HS == V = (U == (V^⟂)%HS).\nProof. by rewrite -hsC_eq hsCK. Qed.\n\nLemma lehC U V : (U^⟂)%HS `<=` (V^⟂)%HS = (V `<=` U).\nProof. by apply/eqb_iff; split=>/lehCP; rewrite ?hsCK=>/lehP. Qed.\n\nLemma lehC_sym U V : (U^⟂)%HS `<=` V = ((V^⟂)%HS `<=` U).\nProof. by rewrite -lehC hsCK. Qed.\n\nLemma lehC_symV U V : U `<=` (V^⟂)%HS = (V `<=` (U^⟂)%HS).\nProof. by rewrite -lehC hsCK. Qed.\n\nLemma hs_ortho U x y : x \\in U -> y \\in (U^⟂)%HS -> [< x ; y >] = 0.\nProof. by move=>/memhP<-/memhP<-; rewrite -hermf_dotE/= memh_projC dot0p. Qed.   \n\nLemma memhN U v : (- v \\in U) = (v \\in U). \nProof. by rewrite !memhE linearN/= eqr_opp. Qed.\nLemma memhD U : {in U &, forall u v, u + v \\in U}.\nProof. by move=>u v; rewrite !memhE linearD/==>/eqP->/eqP->. Qed.\nLemma memhB U : {in U &, forall u v, u - v \\in U}.\nProof. by move=>u v Pu Pv; rewrite memhD// memhN. Qed.\nLemma memhZ U (c : C) : {in U, forall v, c *: v \\in U}.\nProof. by move=>v; rewrite !memhE linearZ/==>/eqP->. Qed.\n\nEnd HspacePredTheory.\nEnd HspacePredTheory.\n\n(* definition of supph cosupph cuph caph *)\n(* note that: hilbert space is not a distrLatticeType !! *)\n(* canonical to latticeType bLatticeType tbLatticeType *)\n(* complLatticeType oComplLatticeType oModularLatticeType *)\n\nModule Import HspaceSupport.\n\nSection HspaceSupport.\nVariable (H : chsType).\nImplicit Type (U V W : {hspace H}).\n\nLemma supph_rank (G : chsType) (A : 'Hom(H,G)) : \n  \\Dim (supph A) = \\Rank A.\nProof. by rewrite /dimh hsE/= supplf_rank. Qed.\n\nLemma cosupph_rank (G : chsType) (A : 'Hom(H,G)) : \n  \\Dim (cosupph A) = \\Rank A.\nProof. by rewrite /dimh hsE/= cosupplf_rank. Qed.\n\nLemma supphP (G : chsType) (A : 'Hom(H,G)) x :\n  (supph A x == 0) = (A x == 0).\nProof.\napply/eqb_iff; rewrite !eq_iff hsE/=; split.\nby rewrite -{2}(suppvlf A) comp_lfunE=>->; rewrite linear0.\nby rewrite lfunE/==>->; rewrite linear0.\nQed.\n\nLemma cosupphP (G K : chsType) (A : 'Hom(H,G)) (B : 'Hom(G,K)) :\n  (B \\o cosupph A == 0) = (B \\o A == 0).\nProof. \napply/eqb_iff; rewrite !eq_iff hsE/=; split;\n[rewrite -{2}(cosupplfv A) | rewrite /cosupplf];\nby rewrite comp_lfunA=>->; rewrite comp_lfun0l.\nQed.\n\nLemma memh_suppCE (G : chsType) (A : 'Hom(H,G)) x : \n  x \\in ((supph A)^⟂)%HS = (A x == 0).\nProof. by rewrite memhCE hsCK supphP. Qed.\n\nLemma supph_projK (E : 'FP(H)) : supph E = HSType E.\nProof. by apply/hsC_inj/eqhP=>x; rewrite memh_suppCE memhCE hsCK hsE. Qed.\n\nLemma supph_Pid (E : 'FP(H)) : (supph E)%:VF = E.\nProof. by apply/lfunP=>v; move: (supph_projK E)=>/hspaceP/(_ v); rewrite hsE. Qed.\n\nLemma supph_id U : supph U = U.\nProof. by apply/hsC_inj/eqhP=>x; rewrite memh_suppCE memhCE hsCK. Qed.\n\nLemma supplfK (A : 'FP(H)) : supplf A = A.\nProof.\nmove: (supph_projK A); move=>/hspaceP=>P.\nby apply/lfunP=>i; move: (P i); rewrite !hsE/=.\nQed.\n\nLemma projlfD_eq0 (A B : 'FP(H)) x: \n  (A%:VF + B) x == 0 = ((A x == 0) && (B x == 0)).\nProof.\napply/eqb_iff; split=>[/eqP/(f_equal (dotp x))|].\nrewrite linear0 lfunE/= dotpDr !projf_dot=>/eqP;\nrewrite addr_ss_eq0 ?sqrf_eq0 ?normr_eq0=>[|/andP[]//].\nby apply/orP; left; apply/andP; split; rewrite exprn_ge0.\nby rewrite lfunE/==>/andP[/eqP->/eqP->]; rewrite addr0 eqxx.\nQed.\n\nLemma eq_from_hs (G : chsType) U (f g : 'Hom(H,G)) :\n  (forall x, x \\in U -> f x = g x) -> (forall x, x \\in U^⟂ -> f x = g x)\n  -> f = g.\nProof.\nmove=>P1 P2; apply/lfunP=>v; rewrite (hs_vec_dec U v) !linearD/=.\nby move: (memh_proj U v) (memh_proj U^⟂ v)=>/P1->/P2->.\nQed.\n\n\nLemma leh2v (U V : {hspace H}) : U `<=` V = (hs2vs U <= hs2vs V)%VS.\nProof.\napply/eqb_iff; split. move=>/lehP P; apply/subvP=>i; rewrite -!memh2v; apply P.\nby move/subvP=>P; apply/lehP=>i; move: (P i); rewrite -!memh2v.\nQed.\nLemma subv2h (U V : {vspace H}) : (U <= V)%VS = (vs2hs U `<=` vs2hs V).\nProof. by rewrite leh2v !vs2hsK. Qed.\n\n(* relation to vspace *)\nLemma vs2hs0 : 0%VS = hs2vs (hs0 : {hspace H}).\nProof. by apply/vspaceP=>x; rewrite [RHS]memv2h hs2vsK memv0 memh0. Qed.\nLemma hs2vs0 : (hs0 : {hspace H}) = vs2hs 0%VS.\nProof. by apply/hs2vs_inj; rewrite vs2hsK vs2hs0. Qed.\nLemma vs2hs1 : fullv = hs2vs (hs1 : {hspace H}).\nProof. by apply/vspaceP=>x; rewrite [RHS]memv2h hs2vsK memh1 memvf. Qed.\nLemma hs2vs1 : (hs1 : {hspace H}) = vs2hs fullv.\nProof. by apply/hs2vs_inj; rewrite vs2hsK vs2hs1. Qed.\n\nLemma cuphP U V W : (cuph U V `<=` W) = (U `<=` W) && (V `<=` W).\nProof.\napply/eqb_iff; split.\n- by move=>P1; apply/andP; split; apply: (le_trans _ P1);\n  apply/lehCP=>x; rewrite/= memh_suppCE memhCE hsCK projlfD_eq0=>/andP[].\nmove=>/andP[]/lehCP P1/lehCP P2; apply/lehCP=>x Px; rewrite /cuph memh_suppCE.\nby move: (P1 _ Px) (P2 _ Px); rewrite !memhCE !hsCK lfunE/==>/eqP->/eqP->; rewrite addr0.\nQed.\n\nLemma caphP U V W : (U `<=` caph V W) = (U `<=` V) && (U `<=` W).\nProof. by rewrite /caph lehC_symV cuphP !lehC. Qed.\n\nLemma cuph2v (U V : {hspace H}) : (cuph U V) = vs2hs (hs2vs U + hs2vs V)%VS.\nProof.\napply/hs2vs_inj/eqP; rewrite eqEsubv vs2hsK; apply/andP; split.\nby rewrite subv2h hs2vsK cuphP !leh2v vs2hsK -subv_add.\nby rewrite subv_add !subv2h !hs2vsK -cuphP.\nQed.\n\nLemma addv2h (U V : {vspace H}) : (U + V)%VS = hs2vs (cuph (vs2hs U) (vs2hs V)).\nProof. by rewrite cuph2v !vs2hsK. Qed.\n\nLemma caph2v (U V : {hspace H}) : (caph U V) = vs2hs (hs2vs U :&: hs2vs V)%VS.\nProof.\napply/hs2vs_inj/eqP; rewrite eqEsubv vs2hsK; apply/andP; split.\nby rewrite subv_cap -!leh2v -caphP.\nby rewrite subv2h hs2vsK caphP !leh2v vs2hsK -subv_cap.\nQed.\n\nLemma capv2h (U V : {vspace H}) : (U :&: V)%VS = hs2vs (caph (vs2hs U) (vs2hs V)).\nProof. by rewrite caph2v !vs2hsK. Qed.\n\nEnd HspaceSupport.\nEnd HspaceSupport.\n\nModule Import HspaceOrthoModularLattice.\n\nSection Lehs_Alternative.\nVariable (H : chsType).\nImplicit Type (U V W : {hspace H}).\n\nLemma leh_compr U V : U `<=` V = (V \\o U == U).\nProof.\napply/eqb_iff; rewrite eq_iff; split.\n- move=>/lehP P; apply: (@eq_from_hs _ _ U)=>x Px; rewrite lfunE/=.\n  move: {+}Px; rewrite memhE=>/eqP->. \n  by move/P: Px; rewrite memhE=>/eqP->.\n  by move: Px; rewrite memhCE hsCK=>/eqP->; rewrite linear0.\nmove=>P; apply/lehP=>x; rewrite !memhE=>/eqP<-.\nby rewrite -comp_lfunE P.\nQed.\nLemma leh_compl U V : U `<=` V = (U \\o V == U).\nProof. by rewrite leh_compr -[LHS](can_eq (@adjfK _ _)) adjf_comp !hermf_adjE/=. Qed.\n\nLemma aux14 U V : U `<=` V -> (V%:VF - U%:VF \\is projlf).\nProof.\nmove=>P; apply/projlfP; split; first by rewrite hermf_adjE.\nrewrite linearBl/= !linearBr/=.\nmove: P {+}P; rewrite {1}leh_compr leh_compl=>/eqP->/eqP->; \nby rewrite !projf_idem subrr subr0.\nQed.\n\nLemma aux45 U V : (V%:VF - U%:VF \\is projlf) -> (forall x, [< x ; (V%:VF - U%:VF) x >] >= 0).\nProof.\nmove=>P x; move: (ge0_dotp ((Projlfun P) x)).\nby rewrite -adj_dotEV hermf_adjE/= -comp_lfunE projf_idem projfE.\nQed.\n\nLemma aux56 U V : (forall x, [< x ; (V%:VF - U%:VF) x >] >= 0) -> (forall x, `|V x| >= `|U x|).\nProof.\nby move=>+x; move=>/(_ x); rewrite lfunE/= lfunE/= linearBr/= \n  !projf_dot subr_ge0 ler_pexpn2r ?nnegrE// .\nQed.\n\nLemma aux61 U V : (forall x, `|V x| >= `|U x|) -> U `<=` V.\nProof. \nrewrite -lehC=>P; apply/lehP=>x.\nrewrite !memhCE !hsCK -normr_eq0=>/eqP P1.\nby move: (P x); rewrite P1 normr_le0.\nQed.\n\nLemma leh_sub_proj U V : U `<=` V <-> (V%:VF - U%:VF \\is projlf).\nProof. by split=>[/aux14|/aux45/aux56/aux61]. Qed.\n\nLemma leh_sub_dot U V : U `<=` V <-> (forall x, [< x ; (V%:VF - U%:VF) x >] >= 0).\nProof. by split=>[/aux14/aux45|/aux56/aux61]. Qed.\n\nLemma leh_norm U V : U `<=` V <-> (forall x, `|V x| >= `|U x|).\nProof. by split=>[/aux14/aux45/aux56|/aux61]. Qed.\n\nLemma supph_sub U V : U `<=` V -> \n  (supph (V%:VF - U%:VF))%:VF = V%:VF - U%:VF.\nProof. by move=>/aux14 P; rewrite -{1}(projfE tt P) supph_projK hsE projfE. Qed.\n\nEnd Lehs_Alternative.\n\nSection HspaceOrthoModularLattice.\nVariable (H : chsType).\nImplicit Type (U V W : {hspace H}).\n\n(* form branch haven't include meetJoinLeMixin; so do it directly *)\nLemma cuphC : commutative (@cuph H).\nProof. by move=>U V; rewrite /cuph addrC. Qed.\nLemma caphC : commutative (@caph H).\nProof. by move=>U V; rewrite /caph cuphC. Qed.\nLemma cuphA : associative (@cuph H).\nProof. by move=>U V W; rewrite !cuph2v !vs2hsK addvA. Qed.\nLemma caphA : associative (@caph H).\nProof. by move=>U V W; rewrite !caph2v !vs2hsK capvA. Qed.\nLemma cuphKI V U : caph U (cuph U V) = U.\nProof.\napply/hs2vs_inj/eqP; rewrite caph2v cuph2v !vs2hsK eqEsubv; apply/andP;\n  split; first by exact: capvSl.\nrewrite subv_cap; apply/andP; split=>//; exact: addvSl.\nQed.\nLemma caphKU V U : cuph U (caph U V) = U.\nProof.\napply/hs2vs_inj/eqP; rewrite caph2v cuph2v !vs2hsK eqEsubv; apply/andP; \n  split; last by exact: addvSl.\nrewrite subv_add; apply/andP; split=>//; exact: capvSl.\nQed.\nLemma lehEmeet U V : (U `<=` V) = (caph U V == U).\nProof.\nrewrite leh2v -(can_eq (@hs2vsK _)) caph2v vs2hsK.\nby apply/eqb_iff; rewrite eq_iff; split=>/capv_idPl.\nQed.\n\nDefinition hspace_latticeMixin :=\n  LatticeMixin caphC cuphC caphA cuphA cuphKI caphKU lehEmeet.\nCanonical hspace_latticeType := LatticeType {hspace H} hspace_latticeMixin.\nDefinition hspace_bottomMixin := BottomMixin (@le0h H).\nCanonical hspace_bLatticeType := BLatticeType {hspace H} hspace_bottomMixin.\nDefinition hspace_topMixin := TopMixin  (@leh1 H).\nCanonical hspace_tbLatticeType := TBLatticeType {hspace H} hspace_topMixin.\n\nLemma cupCh U : cuph (U^⟂)%HS U = hs1.\nProof.\napply/eqhP=>x; rewrite !memhCE !hsE/=/cplmt.\nby rewrite !hsE/= /cplmt addrNK supplfK/= !subrr.\nQed.\n\nLemma capCh U : caph (U^⟂)%HS U = hs0.\nProof. by apply/hsC_inj; rewrite hsC0 /caph !hsCK cuphC cupCh. Qed.\n\nLemma wlehC : {homo (@hscmplt H) : U V /~ U `<=` V}.\nProof. by move=>U V; rewrite lehC. Qed.\n\nDefinition hspace_complLatticeMixin := ComplLatticeMixin cupCh capCh.\nCanonical hspace_complLatticeType := ComplLatticeType {hspace H} hspace_complLatticeMixin.\nDefinition hspace_oComplLatticeMixin := OComplLatticeMixin (@hsCK H) wlehC.\nCanonical hspace_oComplLatticeType := OComplLatticeType {hspace H} hspace_oComplLatticeMixin.\n\nLemma hs_orthomodular U V : \n  U `<=` V -> cuph U (caph (U^⟂)%HS V) = V.\nProof.\nrewrite cuphC caphC -{3}[V]meetx1 -(joinCx U).\nrewrite leh2v=>/(vspace_modr (hs2vs U^⟂))/(f_equal (@vs2hs _)).\nby rewrite !addv2h !capv2h !hs2vsK.\nQed.\n\nDefinition hspace_oModularLatticeMixin := OModularLatticeMixin hs_orthomodular.\nCanonical hspace_oModularLatticeType := OModularLatticeType {hspace H} hspace_oModularLatticeMixin.\n\nEnd HspaceOrthoModularLattice.\nEnd HspaceOrthoModularLattice.\n\nModule Exports.\n\nExport BasicConstruct.\nExport HspaceSupport.\nCanonical hspace_latticeType.\nCanonical hspace_bLatticeType.\nCanonical hspace_tbLatticeType.\nCanonical hspace_complLatticeType.\nCanonical hspace_oComplLatticeType.\nCanonical hspace_oModularLatticeType.\n\n(* reformulate the theories in HspacePredTheory and HspaceOrthoModularLattice *)\n(* replacing the plain operator to lattice operator *)\nSection Theory.\nVariable (H : chsType).\nImplicit Type (U V W: {hspace H}) (x y : H).\n\nDefinition hs_sub_t := hs_sub_t.\nDefinition hs_sub_proj := hs_sub_proj. \nDefinition leh_lef := leh_lef.\nDefinition memhE := memhE.\nDefinition memhP := memhP.\nDefinition memh_dotE := memh_dotE.\nDefinition memh_dotP := memh_dotP.\nDefinition memh_proj := memh_proj.\nDefinition memh_normE := memh_normE.\nDefinition memh_normP := memh_normP.\nDefinition lehP := lehP.\nDefinition eqhP := eqhP.\nDefinition mem0h := mem0h.\nDefinition memhN := memhN.\nDefinition memhD := memhD.\nDefinition memhB := memhB.\nDefinition memhZ := memhZ.\nDefinition leh_compr := leh_compr. \nDefinition leh_compl := leh_compl. \nDefinition leh_sub_proj := leh_sub_proj. \nDefinition leh_sub_dot := leh_sub_dot. \nDefinition leh_norm := leh_norm. \nDefinition supph_sub := supph_sub. \n\nLemma hs_vec_dec U x : x = U x + (~` U) x.\nProof. exact: hs_vec_dec. Qed.\nLemma memhCE U x : x \\in U = ((~` U) x == 0).\nProof. exact: memhCE. Qed.\nLemma memhCP U x : reflect ((~` U) x = 0) (x \\in U).\nProof. exact: memhCP. Qed.\nLemma memh_dotCE U x : x \\in U = ([< x ; (~` U) x >] == 0).\nProof. exact: memh_dotCE. Qed.\nLemma memh_dotCP U x : reflect ([< x ; (~` U) x >] = 0) (x \\in U).\nProof. exact: memh_dotCP. Qed.\nLemma memh_projC U x : (~` U) (U x) = 0.\nProof. exact: memh_projC. Qed.\nLemma memh_normCE U x : x \\in U = (`|(~` U) x| == 0).\nProof. exact: memh_normCE. Qed.\nLemma memh_normCP U x : reflect (`|(~` U) x| = 0) (x \\in U).\nProof. Set Printing All.  exact: memh_normCP. Qed.\nLemma lehCP U V : reflect (forall x, (x \\in (~` V)) -> (x \\in (~` U))) (U `<=` V).\nProof. exact: lehCP. Qed.\nLemma memh1 x : x \\in (`1` : {hspace H}).\nProof. exact: memh1. Qed.\nLemma memh0 x : x \\in (`0` : {hspace H}) = (x == 0).\nProof. exact: memh0. Qed.\n\n(* here we rewrite the theory from lattice and others *)\nLocal Notation cap := (@Order.meet _ (hspace_latticeType H)) (only parsing).\nLocal Notation cup := (@Order.join _ (hspace_latticeType H)) (only parsing).\nLocal Notation cpl := (@compl _ (hspace_complLatticeType H)) (only parsing).\nLemma lehh U : U `<=` U. Proof. exact: lexx. Qed.\n(* ??? why lexx not work for // *)\n(* Hint Extern 0 (_ `<=` _) => solve [apply: lehh] : core. *)\n(* Hint Resolve lehh : core. *)\nLemma cuphC : commutative cup. Proof. exact: joinC. Qed.\nLemma caphC : commutative cap. Proof. exact: meetC. Qed.\nLemma cuphA : associative cup. Proof. exact: joinA. Qed.\nLemma caphA : associative cap. Proof. exact: meetA. Qed.\nLemma cuphKI V U : U `&` (U `|` V) = U.  Proof. exact: joinKI. Qed.\nLemma caphKU V U : U `|` (U `&` V) = U.  Proof. exact: meetKU. Qed.\nLemma cuphKIC V U : U `&` (V `|` U) = U. Proof. exact: joinKIC. Qed.\nLemma caphKUC V U : U `|` (V `&` U) = U. Proof. exact: meetKUC. Qed.\nLemma caphUK U V : (U `&` V) `|` V = V.  Proof. exact: meetUK. Qed.\nLemma cuphIK U V : (U `|` V) `&` V = V.  Proof. exact: joinIK. Qed.\nLemma caphUKC U V : (V `&` U) `|` V = V. Proof. exact: meetUKC. Qed.\nLemma cuphIKC U V : (V `|` U) `&` V = V. Proof. exact: joinIKC. Qed.\nLemma lehEcap U V : (U `<=` V) = (U `&` V == U). Proof. exact: leEmeet. Qed.\nLemma lehEcup U V : (U `<=` V) = (U `|` V == V). Proof. exact: leEjoin. Qed.\n\nLemma caphAC : right_commutative cap. Proof. exact: meetAC. Qed.\nLemma caphCA : left_commutative cap.  Proof. exact: meetCA. Qed.\nLemma caphACA : interchange cap cap.  Proof. exact: meetACA. Qed.\nLemma caphh U : U `&` U = U. Proof. exact: meetxx. Qed.\nLemma caphKI V U : U `&` (U `&` V) = U `&` V.  Proof. exact: meetKI. Qed.\nLemma caphIK V U : (U `&` V) `&` V = U `&` V.  Proof. exact: meetIK. Qed.\nLemma caphKIC V U : U `&` (V `&` U) = U `&` V. Proof. exact: meetKIC. Qed.\nLemma caphIKC V U : V `&` U `&` V = U `&` V.   Proof. exact: meetIKC. Qed.\nLemma lehI U V W : (U `<=` V `&` W) = (U `<=` V) && (U `<=` W).\nProof. exact: lexI. Qed.\nLemma lehIxl U V W : V `<=` U -> V `&` W `<=` U. Proof. exact: leIxl. Qed.\nLemma lehIxr U V W : W `<=` U -> V `&` W `<=` U. Proof. exact: leIxr. Qed.\nLemma lehIx2 U V W : (V `<=` U) || (W `<=` U) -> V `&` W `<=` U.\nProof. exact: leIx2. Qed.\nLemma lehIr U V : V `&` U `<=` U. Proof. exact: leIr. Qed.\nLemma lehIl U V : U `&` V `<=` U. Proof. exact: leIl. Qed.\nLemma caph_idPl {U V} : reflect (U `&` V = U) (U `<=` V).\nProof. exact: meet_idPl. Qed.\nLemma caph_idPr {U V} : reflect (V `&` U = U) (U `<=` V).\nProof. exact: meet_idPr. Qed.\nLemma caphl U V : U `<=` V -> U `&` V = U. Proof. exact: meet_l. Qed.\nLemma caphr U V : V `<=` U -> U `&` V = V. Proof. exact: meet_r. Qed.\nLemma lehIidl U V : (U `<=` U `&` V) = (U `<=` V). Proof. exact: leIidl. Qed.\nLemma lehIidr U V : (U `<=` V `&` U) = (U `<=` V). Proof. exact: leIidr. Qed.\nLemma eq_caphl U V : (U `&` V == U) = (U `<=` V). Proof. exact: eq_meetl. Qed.\nLemma eq_caphr U V : (U `&` V == V) = (V `<=` U). Proof. exact: eq_meetr. Qed.\nLemma lehI2 U V W t : U `<=` W -> V `<=` t -> U `&` V `<=` W `&` t.\nProof. exact: leI2. Qed.\nLemma lehI2l U V W : V `<=` W -> U `&` V `<=` U `&` W.\nProof. move=>P1; apply/lehI2=>[|//]; exact: lexx. Qed.\nLemma lehI2r U V W : V `<=` W -> V `&` U `<=` W `&` U.\nProof. rewrite !(caphC _ U); exact: lehI2l. Qed.\n\nLemma cuphAC : right_commutative cup. Proof. exact: joinAC. Qed.\nLemma cuphCA : left_commutative cup.  Proof. exact: joinCA. Qed.\nLemma cuphACA : interchange cup cup.  Proof. exact: joinACA. Qed.\nLemma cuphh U : U `|` U = U. Proof. exact: joinxx. Qed.\nLemma cuphKU V U : U `|` (U `|` V) = U `|` V.  Proof. exact: joinKU. Qed.\nLemma cuphUK V U : (U `|` V) `|` V = U `|` V.  Proof. exact: joinUK. Qed.\nLemma cuphKUC V U : U `|` (V `|` U) = U `|` V. Proof. exact: joinKUC. Qed.\nLemma cuphUKC V U : V `|` U `|` V = U `|` V.   Proof. exact: joinUKC. Qed.\nLemma leUh U V W : (U `|` V `<=` W) = (U `<=` W) && (V `<=` W).\nProof. exact: leUx. Qed.\nLemma lehxUl U V W : U `<=` V -> U `<=` V `|` W. Proof. exact: lexUl. Qed.\nLemma lehxUr U V W : U `<=` W -> U `<=` V `|` W. Proof. exact: lexUr. Qed.\nLemma lehxU2 U V W : (U `<=` V) || (U `<=` W) -> U `<=` V `|` W.\nProof. exact: lexU2. Qed.\nLemma lehUr U V : U `<=` V `|` U. Proof. exact: leUr. Qed.\nLemma lehUl U V : U `<=` U `|` V. Proof. exact: leUl. Qed.\nLemma cuph_idPr {U V} : reflect (U `|` V = V) (U `<=` V).\nProof. exact: join_idPr. Qed.\nLemma cuph_idPl {U V} : reflect (V `|` U = V) (U `<=` V).\nProof. exact: join_idPl. Qed.\nLemma cuphl U V : V `<=` U -> U `|` V = U. Proof. exact: join_l. Qed.\nLemma cuphr U V : U `<=` V -> U `|` V = V. Proof. exact: join_r. Qed.\nLemma lehUidl U V : (U `|` V `<=` V) = (U `<=` V). Proof. exact: leUidl. Qed.\nLemma lehUidr U V : (V `|` U `<=` V) = (U `<=` V). Proof. exact: leUidr. Qed.\nLemma eq_cuphl U V : (U `|` V == U) = (V `<=` U). Proof. exact: eq_joinl. Qed.\nLemma eq_cuphr U V : (U `|` V == V) = (U `<=` V). Proof. exact: eq_joinr. Qed.\nLemma lehU2 U V W t : U `<=` W -> V `<=` t -> U `|` V `<=` W `|` t.\nProof. exact: leU2. Qed.\nLemma lehU2l U V W : V `<=` W -> U `|` V `<=` U `|` W.\nProof. move=>P1; apply/lehU2=>[|//]; exact: lexx. Qed.\nLemma lehU2r U V W : V `<=` W -> V `|` U `<=` W `|` U.\nProof. rewrite !(cuphC _ U); exact: lehU2l. Qed.\n\n(* Non-distributive lattice theory with `0` & 1*)\nLemma le0h U : `0` `<=` U. Proof. exact: le0x. Qed.\nHint Resolve le0x : core.\nLemma leh0 U : (U `<=` `0`) = (U == `0`). Proof. exact: lex0. Qed.\nLemma lth0 U : (U `<` `0`) = false. Proof. exact: ltx0. Qed.\nLemma lt0h U : (`0` `<` U) = (U != `0`). Proof. exact: lt0x. Qed.\nLemma cap0h : left_zero  `0` cap.  Proof. exact: meet0x. Qed.\nLemma caph0 : right_zero `0` cap.  Proof. exact: meetx0. Qed.\nLemma cup0h : left_id    `0` cup.  Proof. exact: join0x. Qed.\nLemma cuph0 : right_id   `0` cup.  Proof. exact: joinx0. Qed.\nLemma cuph_eq0 U V : (U `|` V == `0`) = (U == `0`) && (V == `0`).\nProof. exact: join_eq0. Qed.\n\nCanonical cuph_monoid := Monoid.Law cuphA cup0h cuph0.\nCanonical cuph_comoid := Monoid.ComLaw cuphC.\n\nLemma leh1 U : U `<=` `1`. Proof. exact: lex1. Qed.\nHint Resolve leh1 : core.\nLemma caph1 : right_id   `1` cap. Proof. exact: meetx1. Qed.\nLemma cap1h : left_id    `1` cap. Proof. exact: meet1x. Qed.\nLemma cuph1 : right_zero `1` cup. Proof. exact: joinx1. Qed.\nLemma cup1h : left_zero  `1` cup. Proof. exact: join1x. Qed.\nLemma le1h U : (`1` `<=` U) = (U == `1`). Proof. exact: le1x. Qed.\nLemma caph_eq1 U V : (U `&` V == `1`) = (U == `1`) && (V == `1`).\nProof. exact: meet_eq1. Qed.\n\nCanonical caph_monoid := Monoid.Law caphA cap1h caph1.\nCanonical caph_comoid := Monoid.ComLaw caphC.\nCanonical caph_muloid := Monoid.MulLaw cap0h caph0.\nCanonical cuph_muloid := Monoid.MulLaw cup1h cuph1.\n\nSection CuphsCaphs.\nImplicit Types (I : finType) (T : eqType).\n\nLemma cuphs_sup_seq T (r : seq T) (P : {pred T}) (F : T -> {hspace H}) (x : T) :\n  x \\in r -> P x -> F x `<=` \\cup_(i <- r | P i) F i.\nProof. exact: joins_sup_seq. Qed.\n\nLemma cuphs_min_seq T (r : seq T) (P : {pred T}) (F : T -> {hspace H}) (x : T) U :\n  x \\in r -> P x -> U `<=` F x -> U `<=` \\cup_(i <- r | P i) F i.\nProof. exact: joins_min_seq. Qed.\n\nLemma cuphs_sup I (j : I) (P : {pred I}) (F : I -> {hspace H}) :\n  P j -> F j `<=` \\cup_(i | P i) F i.\nProof. exact: joins_sup. Qed.\n\nLemma cuphs_min I (j : I) U (P : {pred I}) (F : I -> {hspace H}) :\n  P j -> U `<=` F j -> U `<=` \\cup_(i | P i) F i.\nProof. exact: joins_min. Qed.\n\nLemma cuphs_le J (r : seq J) (P : {pred J}) (F : J -> {hspace H}) U :\n  (forall x : J, P x -> F x `<=` U) -> \\cup_(i <- r | P i) F i `<=` U.\nProof. by move=> leFm; elim/big_rec: _=>[//|] i x Px xu; rewrite leUx leFm. Qed.\n\nLemma cuphsP_seq T (r : seq T) (P : {pred T}) (F : T -> {hspace H}) U :\n  reflect (forall x : T, x \\in r -> P x -> F x `<=` U)\n          (\\cup_(i <- r | P i) F i `<=` U).\nProof. exact: joinsP_seq. Qed.\n\nLemma cuphsP I U (P : {pred I}) (F : I -> {hspace H}) :\n  reflect (forall i : I, P i -> F i `<=` U) (\\cup_(i | P i) F i `<=` U).\nProof. exact: joinsP. Qed.\n\nLemma le_cuphs I (A B : {set I}) (F : I -> {hspace H}) :\n  A \\subset B -> \\cup_(i in A) F i `<=` \\cup_(i in B) F i.\nProof. exact: le_joins. Qed.\n\nLemma cuphs_setU I (A B : {set I}) (F : I -> {hspace H}) :\n  \\cup_(i in (A :|: B)) F i = \\cup_(i in A) F i `|` \\cup_(i in B) F i.\nProof. exact: joins_setU. Qed.\n\nLemma cuphs_seq I (r : seq I) (F : I -> {hspace H}) :\n  \\cup_(i <- r) F i = \\cup_(i in r) F i.\nProof. exact: joins_seq. Qed.\n\nLemma caphs_inf I (j : I) (P : {pred I}) (F : I -> {hspace H}) :\n   P j -> \\cap_(i | P i) F i `<=` F j.\nProof. exact: meets_inf. Qed.\n\nLemma caphs_max I (j : I) U (P : {pred I}) (F : I -> {hspace H}) :\n   P j -> F j `<=` U -> \\cap_(i | P i) F i `<=` U.\nProof. exact: meets_max. Qed.\n\nLemma caphsP I U (P : {pred I}) (F : I -> {hspace H}) :\n   reflect (forall i : I, P i -> U `<=` F i) (U `<=` \\cap_(i | P i) F i).\nProof. exact: meetsP. Qed.\n\nLemma caphs_inf_seq T (r : seq T) (P : {pred T}) (F : T -> {hspace H}) (x : T) :\n  x \\in r -> P x -> \\cap_(i <- r | P i) F i `<=` F x.\nProof. exact: meets_inf_seq. Qed.\n\nLemma caphs_max_seq T (r : seq T) (P : {pred T}) (F : T -> {hspace H}) (x : T) U :\n  x \\in r -> P x -> F x `<=` U -> \\cap_(i <- r | P i) F i `<=` U.\nProof. exact: meets_max_seq. Qed.\n\nLemma caphsP_seq T (r : seq T) (P : {pred T}) (F : T -> {hspace H}) U :\n  reflect (forall x : T, x \\in r -> P x -> U `<=` F x)\n          (U `<=` \\cap_(x <- r | P x) F x).\nProof. exact: meetsP_seq. Qed.\n\nLemma le_meets I (A B : {set I}) (F : I -> {hspace H}) :\n   A \\subset B -> \\cap_(i in B) F i `<=` \\cap_(i in A) F i.\nProof. exact: le_meets. Qed.\n\nLemma caphs_setU I (A B : {set I}) (F : I -> {hspace H}) :\n   \\cap_(i in (A :|: B)) F i = \\cap_(i in A) F i `&` \\cap_(i in B) F i.\nProof. exact: meets_setU. Qed.\n\nLemma caphs_seq I (r : seq I) (F : I -> {hspace H}) :\n   \\cap_(i <- r) F i = \\cap_(i in r) F i.\nProof. exact: meets_seq. Qed.\n\nEnd CuphsCaphs.\n\nLemma leh_cupl U : {homo (cup U) : x y / x `<=` y}.   Proof. exact: le_joinl. Qed.\nLemma leh_cupr U : {homo (cup^~ U) : x y / x `<=` y}. Proof. exact: le_joinr. Qed.\nLemma leh_capl U : {homo (cap U) : x y / x `<=` y}.   Proof. exact: le_meetl. Qed.\nLemma leh_capr U : {homo (cap^~ U) : x y / x `<=` y}. Proof. exact: le_meetr. Qed.\nLemma lth_cupl U : {homo (cup U) : x y / x `<` y >-> x `<=` y}.\nProof. exact: lt_joinl. Qed.\nLemma lth_cupr U : {homo (cup^~ U) : x y / x `<` y >-> x `<=` y}.\nProof. exact: lt_joinr. Qed.\nLemma lth_capl U : {homo (cap U) : x y / x `<` y >-> x `<=` y}.\nProof. exact: lt_meetl. Qed.\nLemma lth_capr U : {homo (cap^~ U) : x y / x `<` y >-> x `<=` y}.\nProof. exact: lt_meetr. Qed.\nLemma cuphCx U : ~` U `|` U = `1`. Proof. exact: joinCx. Qed.\nLemma caphCx U : ~` U `&` U = `0`. Proof. exact: meetCx. Qed.\nLemma cuphxC U : U `|` ~` U = `1`. Proof. exact: joinxC. Qed.\nLemma caphxC U : U `&` ~` U = `0`. Proof. exact: meetxC. Qed.\nLemma hsC1 : ~` `1` = `0` :> {hspace H}. Proof. exact: compl1. Qed.\nLemma hsC0 : ~` `0` = `1` :> {hspace H}. Proof. exact: compl0. Qed.\nLemma hsCK : involutive cpl.    Proof. exact: complK. Qed.\nLemma hsC_inj : injective cpl. Proof. exact: compl_inj. Qed.\nLemma hsC_eq U V : (~` U) == (~` V) = (U == V). Proof. exact: hsC_eq. Qed.\nLemma hsCx_eq U V : (~` U) == V = (U == (~` V)). Proof. exact: hsC_eq_sym. Qed.\nLemma hsxC_eq U V : U == (~` V) = ((~` U) == V). Proof. by rewrite hsCx_eq. Qed.\nLemma wlehC : {homo cpl : a b /~ a `<=` b}. Proof. exact: leCP. Qed.\nLemma lehC U V : (~` U) `<=` (~` V) = (V `<=` U).  Proof. exact: leC. Qed.\nLemma lehCx U V : (~` U) `<=` V = ((~` V) `<=` U). Proof. exact: leCx. Qed.\nLemma lehxC U V : U `<=` (~` V) = (V `<=` (~` U)). Proof. exact: lexC. Qed.\nLemma hsCU U V : ~` (U `|` V) = ~` U `&` ~` V. Proof. exact: complU. Qed.\nLemma hsCI U V : ~` (U `&` V) = ~` U `|` ~` V. Proof. exact: complI. Qed.\nLemma hsUI U V : (U `|` V) = ~` (~` U `&` ~` V). Proof. by rewrite -hsCU hsCK. Qed.\nLemma hsIU U V : (U `&` V) = ~` (~` U `|` ~` V). Proof. by rewrite -hsCI hsCK. Qed.\nLemma lehxC_disj U V : (U `<=` ~` V) -> (U `&` V = `0`). Proof. exact: lexC_disj. Qed.\nLemma hsUCI U V : U `<=` V -> U `|` ((~` U) `&` V) = V. Proof. exact: le_joinIC. Qed.\nLemma hs_ortho U x y : x \\in U -> y \\in (~` U) -> [< x ; y >] = 0.\nProof. exact: hs_ortho. Qed.\nLemma caphsC I (r : seq I) (P : pred I) (f : I -> {hspace H}) :\n  ~` (\\cap_(i <- r | P i) f i) = \\cup_(i <- r | P i) ~` (f i).\nProof. by elim/big_rec2: _ =>/= [|i d vs _ eqd]; rewrite ?hsC1// -eqd hsCI. Qed.\nLemma cuphsC I (r : seq I) (P : pred I) (f : I -> {hspace H}) :\n  ~` (\\cup_(i <- r | P i) f i) = \\cap_(i <- r | P i) ~` (f i).\nProof. by elim/big_rec2: _ =>/= [|i d vs _ eqd]; rewrite ?hsC0// -eqd hsCU. Qed.\n\n(* basic construct -> lattice operator *)\nDefinition hs0E : hspace0 H = `0`.\nProof. by []. Qed.\nDefinition hs1E : hspace1 H = `1`.\nProof. by []. Qed.\nDefinition hsCE U : U^⟂ = ~` U.\nProof. by []. Qed.\nDefinition cuphE U V : cuph U V = U `|` V.\nProof. by []. Qed.\nDefinition caphE U V : caph U V = U `&` V.\nProof. by []. Qed.\nDefinition hs2lE := (hs0E, hs1E, hsCE, cuphE, caphE).\n\n(* lattice operator -> lfun operator *)\nLemma hs2lf0E : (`0` : {hspace H})%:VF = 0.\nProof. by rewrite -hs0E hsE. Qed.\nLemma hs2lf1E : (`1` : {hspace H})%:VF = \\1.\nProof. by rewrite -hs1E hsE. Qed.\nLemma hs2lfCE U : (~` U)%:VF = cplmt U.\nProof. by rewrite -hsCE hsE. Qed.\nLemma cuph2lfE U V : (U `|` V)%:VF = supplf (U%:VF + V%:VF).\nProof. by rewrite -cuphE hsE. Qed.\nLemma caph2lfE U V : (U `&` V)%:VF = cplmt (supplf (cplmt U%:VF + cplmt V%:VF)).\nProof. by rewrite -caphE /caph /cuph !hsE/=hsE. Qed.\nDefinition hs2lfE := (hs2lf0E, hs2lf1E, hs2lfCE, cuph2lfE, caph2lfE).\n\nLemma capCh_sub U V : U `<=` V -> \n  ((~` U) `&` V) = supph (V%:VF - U%:VF).\nProof.\nmove=>/supph_sub P; rewrite -[LHS]hsCK [X in ~` X]complI hsCK; apply/eqhP=>x.\nby rewrite memhCE hsCK memhCE hs2lfE supphP P !hsE/= /cplmt opprB !addrA [_ + \\1]addrC.\nQed.\nLemma cuph_lub U V W : U `<=` W -> V `<=` W -> U `|` V `<=` W.\nProof. by move=>P1 P2; rewrite leUx P1 P2. Qed.\nLemma caph_glb U V W : W `<=` U -> W `<=` V -> W `<=` U `&` V.\nProof. by move=>P1 P2; rewrite lexI P1 P2. Qed.\n\n(* extra difinition *)\nDefinition hline (v : H) := supph [> v ; v <].\nDefinition spanh (F : finType) (v : F -> H) :=\n  supph (\\sum_i [> v i ; v i <]).\nDefinition diffh U V := U `&` (~` (U `&` V)).\nDefinition kerh (G : chsType) (A : 'Hom(H,G)) := ~` (supph A).\nDefinition cokerh (G : chsType) (A : 'Hom(H,G)) := ~` (cosupph A).\n\nLemma kerhE (G : chsType) (A : 'Hom(H,G)) : kerh A = ~` (supph A).\nProof. by []. Qed.\nLemma cokerhE (G : chsType) (A : 'Hom(H,G)) : cokerh A = ~` (cosupph A).\nProof. by []. Qed.\nLemma supphE (G : chsType) (A : 'Hom(H,G)) : supph A = ~` (kerh A).\nProof. by rewrite kerhE hsCK. Qed.\nLemma cosupphE (G : chsType) (A : 'Hom(H,G)) : cosupph A = ~` (cokerh A).\nProof. by rewrite cokerhE complK. Qed.\n\nLemma memh_suppCE (G : chsType) (A : 'Hom(H,G)) x : \n  x \\in ~` (supph A) = (A x == 0).\nProof. exact: memh_suppCE. Qed.\n\nLemma eq_from_hs (G : chsType) U (f g : 'Hom(H,G)) :\n  (forall x, x \\in U -> f x = g x) -> (forall x, x \\in ~` U -> f x = g x)\n  -> f = g.\nProof. exact: eq_from_hs. Qed.\n\nLemma leh_memCP (U V : {hspace H}) : \n  reflect (forall x, V x == 0 -> U x == 0) (U `<=` V).\nProof.\napply/(iffP (lehCP _ _))=>+ x; move=>/(_ x);\nby rewrite !memhCE !hsCK=>P1 P2; apply P1.\nQed.\n\nLemma leh_memP (U V : {hspace H}) : \n  reflect (forall x, U x == x -> V x == x) (U `<=` V).\nProof.\napply/(iffP (lehP _ _))=>+ x; move=>/(_ x);\nby rewrite !memhE =>P1 P2; apply P1.\nQed.\n\nLemma outp_norm_proj (v : H) : `|v|^-2 *: [> v ; v <] \\is projlf.\nProof.\napply/projlfP. rewrite adjfZ adj_outp geC0_conj ?invr_ge0// ?exprn_ge0//; split=>//.\ncase E: (v == 0). by move: E=>/eqP->; rewrite normr0 expr0n/= invr0 scale0r comp_lfun0l.\nby rewrite linearZl/= linearZr/= outp_comp dotp_norm !scalerA -mulrA mulVf \n  ?mulr1// expf_eq0/= normr_eq0 E.\nQed.\n\nLemma hline_def (v : H) : (hline v) = HSType (ProjfType (outp_norm_proj v)).\nProof.\napply/hsC_inj/eqhP=>x; rewrite !memhCE !hsCK supphP !hsE/=.\nrewrite lfunE/= outpE [RHS]scaler_eq0. apply/eqb_iff; split.\nby move=>->; rewrite orbT. move/orP=>[|//].\nby rewrite invr_eq0 expf_eq0/= normr_eq0=>/eqP->; rewrite scaler0.\nQed.\n\nLemma hlineP (u v : H) : reflect (exists k : C, u = k *: v) (u \\in hline v).\nProof.\napply/(iffP idP); rewrite hline_def memhE hsE/= lfunE/= outpE scalerA.\nby move=>/eqP P; exists (`|v| ^- 2 * [< v; u >]); rewrite P.\nmove=>[k Pk]; rewrite Pk dotpZr dotp_norm mulrC -mulrA.\ncase E: (v == 0). by move/eqP: E=>->; rewrite !scaler0.\nby rewrite mulfV ?mulr1// expf_eq0/= normr_eq0 E.\nQed.\n\n(* relation between hspace <-> vspace *)\nLemma vs2hs0 : 0%VS = hs2vs (`0` : {hspace H}).\nProof. exact : vs2hs0. Qed.\nLemma hs2vs0 : (`0` : {hspace H}) = vs2hs 0%VS.\nProof. exact : hs2vs0. Qed.\nLemma vs2hs1 : fullv = hs2vs (`1` : {hspace H}).\nProof. exact : vs2hs1. Qed.\nLemma hs2vs1 : (`1` : {hspace H}) = vs2hs fullv.\nProof. exact : hs2vs1. Qed.\nLemma cuph2v U V : (U `|` V) = vs2hs (hs2vs U + hs2vs V)%VS.\nProof. exact : cuph2v. Qed.\nLemma addv2h (U V : {vspace H}) : (U + V)%VS = hs2vs ((vs2hs U) `|` (vs2hs V)).\nProof. exact : addv2h. Qed.\nLemma caph2v U V : (U `&` V) = vs2hs (hs2vs U :&: hs2vs V)%VS.\nProof. exact : caph2v. Qed.\nLemma capv2h (U V : {vspace H}) : (U :&: V)%VS = hs2vs ((vs2hs U) `&` (vs2hs V)).\nProof. exact: capv2h. Qed.\nLemma caphs2v I (r : seq I) (P : pred I) (f : I -> {hspace H}) :\n  \\cap_(i <- r | P i) f i = vs2hs (\\bigcap_(i <- r | P i) hs2vs (f i))%VS.\nProof.\nelim: r=>[|r x]; first by rewrite !big_nil hs2vs1.\nby rewrite !big_cons; case: (P r)=>//->; rewrite caph2v vs2hsK.\nQed.\nLemma cuphs2v I (r : seq I) (P : pred I) (f : I -> {hspace H}) :\n  \\cup_(i <- r | P i) f i = vs2hs (\\sum_(i <- r | P i) hs2vs (f i))%VS.\nProof.\nelim: r=>[|r x]; first by rewrite !big_nil hs2vs0.\nby rewrite !big_cons; case: (P r)=>//->; rewrite cuph2v vs2hsK.\nQed.\nLemma bigcapv2h I (r : seq I) (P : pred I) (f : I -> {vspace H}) :\n  (\\bigcap_(i <- r | P i) (f i))%VS = hs2vs (\\cap_(i <- r | P i) vs2hs (f i)).\nProof. by rewrite caphs2v vs2hsK; under [RHS]eq_bigr do rewrite vs2hsK. Qed.\nLemma sumv2h I (r : seq I) (P : pred I) (f : I -> {vspace H}) :\n  (\\sum_(i <- r | P i) (f i))%VS = hs2vs (\\cup_(i <- r | P i) vs2hs (f i)).\nProof. by rewrite cuphs2v vs2hsK; under [RHS]eq_bigr do rewrite vs2hsK. Qed.\nLemma dimh2v U : \\Dim U = \\dim (hs2vs U).\nProof. by rewrite /dimh /dimv /lfrank /hs2vs mx2vsK. Qed.\nLemma dimv2h (U : {vspace H}) : \\dim U = \\Dim (vs2hs U).\nProof. by rewrite dimh2v vs2hsK. Qed. \nLemma hs2vs_eq U V : (U == V) = (hs2vs U == hs2vs V)%VS.\nProof. by rewrite (can_eq (@hs2vsK _)). Qed.\nLemma vs2hs_eq (U V : {vspace H}) : (U == V)%VS = (vs2hs U == vs2hs V).\nProof. by rewrite (can_eq (@vs2hsK _)). Qed.\nLemma hline2v v : hline v = vs2hs (<[v]>)%VS.\nProof.\napply/eqhP=>x; rewrite -memv2h.\nby apply/eqb_iff; split=>[/hlineP P|/vlineP P]; [apply/vlineP|apply/hlineP].\nQed.\nLemma vline2h v : (<[v]>)%VS = hs2vs (hline v).\nProof. by apply/vs2hs_inj; rewrite hs2vsK hline2v. Qed.\n\nEnd Theory.\nArguments eq_from_hs {H G} U.\n\nLtac simph2v := do 1 ?[ apply/hs2vs_inj | ]; rewrite ?memh2v ?dimh2v ?hs2vs0 \n  ?hs2vs1 ?cuph2v ?caph2v ?hline2v ?caphs2v ?cuphs2v ?leh2v ?hs2vs_eq ?vs2hsK.\n\nLtac simpv2h := do 1 ?[ apply/vs2hs_inj | ]; rewrite ?memv2h ?dimv2h ?vs2hs0 \n  ?vs2hs1 ?addv2h ?capv2h ?vline2h ?bigcapv2h ?sumv2h ?subv2h ?vs2hs_eq ?hs2vsK.\n\nNotation \"{ : H }\" := (`1` : {hspace H}) (only parsing) : hspace_scope.\nNotation \"<[ v ]>\" := (hline v) : hspace_scope.\nNotation \"<< X >>\" := (spanh X) : hspace_scope.\nNotation \"U `\\` V\" := (diffh U V) : hspace_scope.\n\nEnd Exports.\n\nEnd HspaceOrthoModularLattice.\nExport HspaceOrthoModularLattice.Exports.\n\nSection CoHspace.\nImplicit Type (H G : chsType).\n\nLemma ponb_sum_eq0 G (F : finType) (f : 'PONB(F;G)) (l : F -> C) :\n  \\sum_i l i *: f i = 0 <-> forall i, l i = 0.\nProof. \nsplit=>[+ i|P]; last by rewrite big1// =>i _; rewrite P scale0r.\nmove/(f_equal (dotp (f i))).\nrewrite dotp_sumr (bigD1 i)//= big1=>[j/negPf nj|];\nby rewrite dotpZr ponb_dot 1?eq_sym ?nj?mulr0// eqxx mulr1 linear0 addr0.\nQed.\n\nLemma cosupph_memCE H G (A : 'Hom(H,G)) x : \n  x \\in ~` (cosupph A) = (A^A x == 0).\nProof.\nrewrite memhCE hsCK; move: (cosupphP A [>x; x<])=>/esym.\nrewrite !outp_compl hermf_adjE/= !outp_eq0.\nby case: eqP=>// ->; rewrite !linear0 !eqxx.\nQed.\n\nLemma cosupph_adj H G (A : 'Hom(H,G)) : \n  cosupph (A^A) = supph A.\nProof.\nby apply/hsC_inj/eqhP=>x; rewrite cosupph_memCE memh_suppCE adjfK.\nQed.\n\nLemma supph_adj H G (A : 'Hom(H,G)) : \n  supph (A^A) = cosupph A.\nProof. by rewrite -cosupph_adj adjfK. Qed.\n\nLemma cosupplf_adj H G (A : 'Hom(H,G)) : \n  cosupplf A^A = supplf A.\nProof. by apply/lfunP=>x; move: (cosupph_adj A)=>/hspaceP/(_ x); rewrite !hsE/=. Qed.\n\nLemma supplf_adj H G (A : 'Hom(H,G)) : \n  supplf A^A = cosupplf A.\nProof. by rewrite -cosupplf_adj adjfK. Qed.\n\nLemma memh_suppP H G (A : 'Hom(H,G)) x : \n  reflect (exists y, x = A^A y) (x \\in supph A).\nProof.\napply/(iffP idP)=>[|[y Py]].\nrewrite memhE hsE/= -cosupplf_adj /cosupplf lfunE/==>/eqP P1.\nexists ((pinvlf A^A)^A x); by rewrite P1.\nby rewrite memhE Py -comp_lfunE hsE/= -cosupplf_adj cosupplfv.\nQed.\n\nLemma memh_cosuppP H G (A : 'Hom(H,G)) x : \n  reflect (exists y, x = A y) (x \\in cosupph A).\nProof. by rewrite -supph_adj; apply/(iffP (memh_suppP _ _)); rewrite adjfK. Qed.\n\nLemma kerh_adj H G (A : 'Hom(H,G)) : \n  kerh A^A = cokerh A.\nProof. by rewrite /kerh supph_adj. Qed.\n\nLemma cokerh_adj H G (A : 'Hom(H,G)) :\n  cokerh A^A = kerh A.\nProof. by rewrite -kerh_adj adjfK. Qed.\n\nLemma memh_kerE H G (A : 'Hom(H,G)) x : \n  x \\in kerh A = (A x == 0).\nProof. exact: memh_suppCE. Qed.\n\nLemma memh_kerCP H G (A : 'Hom(H,G)) x : \n  reflect (exists y, x = A^A y) (x \\in ~` kerh A).\nProof. rewrite /kerh hsCK; exact: memh_suppP. Qed.\n\nLemma memh_cokerCP H G (A : 'Hom(H,G)) x : \n  reflect (exists y, x = A y) (x \\in ~` cokerh A).\nProof. rewrite /cokerh hsCK; exact: memh_cosuppP. Qed.\n\nLemma cosupph_id H (U : {hspace H}) : cosupph U = U.\nProof. by rewrite -supph_adj hermf_adjE/= supph_id. Qed.\n\nLemma kerhC H (U : {hspace H}) : kerh U = ~` U.\nProof. by rewrite /kerh supph_id. Qed.\nLemma kerhK H (U : {hspace H}) : kerh (kerh U) = U.\nProof. by rewrite !kerhC hsCK. Qed.\nLemma cokerhC H (U : {hspace H}) : cokerh U = ~` U. \nProof. by rewrite /cokerh cosupph_id. Qed.\nLemma cokerhK H (U : {hspace H}) : cokerh (cokerh U) = U.\nProof. by rewrite !cokerhC hsCK. Qed.\n\nEnd CoHspace.\n\n\n(* ?? merge to lfrepresent.v ?? *)\nSection CastFinFun.\n\nDefinition castfun (F G : finType) (eqc : #|F| = #|G|) (T : Type) (f : F -> T) :=\n  (fun i : G => f (enum_val (cast_ord (esym eqc) (enum_rank i)))).\nLemma castfun_id (F : finType) erefl_c T (f : F -> T) :\n  castfun erefl_c f = f.\nProof. by apply/funext=>i; rewrite/castfun cast_ord_id enum_rankK. Qed.\nLemma castfun_comp (F G K: finType) (eqf : #|F| = #|G|) (eqg : #|G| = #|K|) \n  T (f : F -> T) : \n  castfun eqg (castfun eqf f) = castfun (etrans eqf eqg) f.\nProof.\napply/funext=>i; rewrite /castfun enum_valK cast_ord_comp.\nby rewrite (eq_irrelevance (etrans (esym eqg) (esym eqf)) (esym (etrans eqf eqg))).\nQed.\nLemma castfun_const (F G : finType) (eqc : #|F| = #|G|) (T : Type) (x : T) :\n  castfun eqc (fun=>x) = (fun=>x).\nProof. by []. Qed.\n\nLemma castfun_ponb (H : chsType) (F G : finType) (eqc : #|F| = #|G|) (f : 'PONB(F;H)) :\n  ponbasis (castfun eqc f).\nProof.\nby move=>i j; rewrite /castfun ponb_dot enum_ord_eq enum_valK \n  cast_ord_comp cast_ord_id (can_eq enum_rankK).\nQed.\nCanonical castfun_ponbasis H F G eqc f := PONBasis (@castfun_ponb H F G eqc f).\n\nLemma castfun_onb (H : chsType) (F G : finType) (eqc : #|F| = #|G|) (f : 'ONB(F;H)) :\n  ponbasis (castfun eqc f).\nProof. exact: castfun_ponb. Qed.\nLemma castfun_card (H : chsType) (F G : finType) (eqc : #|F| = #|G|) (f : 'ONB(F;H)) :\n  #|G| = Vector.dim H.\nProof. by rewrite -eqc (onb_card f). Qed.\nCanonical castfun_onbasis H F G eqc f := ONBasis\n   (@castfun_onb H F G eqc f) (@castfun_card H F G eqc f).\n\n(* standard form of decomposition *)\nFact sumoutp_key : unit. Proof. by []. Qed.\nDefinition sumoutp (H G : chsType) (F : finType) (l : F -> C) \n  (f : F -> H) (g : F -> G) : 'Hom(H,G) := \n  locked_with sumoutp_key (\\sum_i (l i) *: [> g i ; f i <]).\nCanonical sumoutp_unlockable H G F l f g := [unlockable of @sumoutp H G F l f g].\n\nLemma sumoutpE H G F l f g : \n  @sumoutp H G F l f g = \\sum_i (l i) *: [> g i ; f i <].\nProof. by rewrite unlock. Qed.\n\nLemma sumoutp_adj (H G : chsType) (F : finType) (l : F -> C) \n  (f : F -> H) (g : F -> G) :\n  (sumoutp l f g)^A = sumoutp (fun i=>(l i)^*) g f.\nProof.\nrewrite !sumoutpE raddf_sum; apply eq_bigr=>i _.\nby rewrite/=adjfZ adj_outp; simpc.\nQed.\n\nLemma sumoutp_comp (H G K: chsType) (F : finType) (l l' : F -> C) \n  (f : 'PONB(F;H)) (g : F -> G) (h : F -> K):\n  (sumoutp l f g) \\o (sumoutp l' h f) = sumoutp (fun i=>l i * l' i) h g.\nProof.\nrewrite !sumoutpE linear_suml; apply eq_bigr=>i _.\nrewrite /= linear_sumr (bigD1 i)//= big1=>[j/negPf nj|];\nrewrite/= -!(comp_lfunZl, comp_lfunZr) outp_comp ponb_dot.\nby rewrite eq_sym nj scale0r !scaler0.\nby rewrite eqxx !scalerA mulr1 addr0.\nQed.\n\nLemma sumoutp_apply (H G : chsType) (F : finType) (l : F -> C) \n  (f : 'PONB(F;H)) (g : F -> G) i :\n  (sumoutp l f g) (f i) = l i *: g i.\nProof.\nby rewrite sumoutpE sum_lfunE (bigD1 i)//= big1=>[j/negPf nj|];\nrewrite -outpZl outpE ponb_dot ?nj ?scale0r// eqxx scale1r addr0.\nQed.\n\nEnd CastFinFun.\n\nSection SumoutpLinear.\nVariable (H G : chsType) (F : finType).\nImplicit Type (l : F -> C) (f : F -> H) (g : F -> G) (c : C).\n\nLemma sumoutpZ c l f g :\n  c *: (sumoutp l f g) = sumoutp (fun i=> c * (l i)) f g.\nProof.\nby rewrite !sumoutpE raddf_sum; apply eq_bigr=>i _; rewrite/= scalerA.\nQed.\n\nLemma sumoutpZl c l f g :\n  c *: (sumoutp l f g) = sumoutp l (fun i=>c^* *: f i) g.\nProof.\nby rewrite !sumoutpE raddf_sum; apply eq_bigr=>i _; rewrite/= outpZr conjCK !scalerA mulrC.\nQed.\n\nLemma sumoutpZr c l f g :\n  c *: (sumoutp l f g) = sumoutp l f (fun i=>c *: g i).\nProof.\nby rewrite !sumoutpE raddf_sum; apply eq_bigr=>i _; rewrite/= outpZl !scalerA mulrC.\nQed.\n\nLemma sumoutpD l l' f g :\n  (sumoutp l f g) + (sumoutp l' f g)= sumoutp (fun i=>l i + l' i) f g.\nProof.\nby rewrite !sumoutpE -big_split/=; under eq_bigr do rewrite -scalerDl.\nQed.\n\nLemma sumoutpDl l f f' g :\n  (sumoutp l f g) + (sumoutp l f' g)= sumoutp l (fun i=>f i + f' i) g.\nProof.\nby rewrite !sumoutpE -big_split/=; under eq_bigr do rewrite/= -scalerDr -outpDr.\nQed.\n\nLemma sumoutpDr l f g g' :\n  (sumoutp l f g) + (sumoutp l f g')= sumoutp l f (fun i=>g i + g' i).\nProof.\nby rewrite !sumoutpE -big_split/=; under eq_bigr do rewrite -scalerDr -outpDl.\nQed.\n\nLemma sumoutpN l f g :\n  - (sumoutp l f g)= sumoutp (fun i=>- l i) f g.\nProof.\nby rewrite !sumoutpE linear_sum/=; under eq_bigr do rewrite -scaleNr.\nQed.\n\nLemma sumoutpNl l f g :\n  - (sumoutp l f g)= sumoutp l (fun i=>- f i) g.\nProof.\nby rewrite !sumoutpE linear_sum/=; under [RHS]eq_bigr do rewrite/= outpNr scalerN.\nQed.\n\nLemma sumoutpNr l f g :\n  - (sumoutp l f g)= sumoutp l f (fun i=>- g i).\nProof.\nby rewrite !sumoutpE linear_sum/=; under [RHS]eq_bigr do rewrite/= outpNl scalerN.\nQed.\n\nEnd SumoutpLinear.\n\nSection Decomposition.\nVariable (H : chsType).\nImplicit Type (U V W : {hspace H}).\n\nLemma sumoutp_eq (G : chsType) (F : finType) (l l' : F -> C) \n  (f : F -> H) (g : F -> G) :\n    l =1 l' -> sumoutp l f g = sumoutp l' f g.\nProof. by move=>P; rewrite !sumoutpE; apply eq_bigr=>i _; rewrite P. Qed.\nLemma sumoutp_cast (G : chsType) (F K: finType) (eqc : #|F| = #|K|) \n  (l : F -> C) (f : F -> H) (g : F -> G) :\n  sumoutp (castfun eqc l) (castfun eqc f) (castfun eqc g) = sumoutp l f g.\nProof.\npose h i := enum_val (cast_ord (esym eqc) (enum_rank i)).\nrewrite /sumoutp (reindex h)//. \nexists (fun i=>enum_val (cast_ord eqc (enum_rank i)))=>i _;\nby rewrite /h enum_valK cast_ord_comp cast_ord_id enum_rankK.\nQed.\n\nLemma sumoutp_herm (F : finType) (f : F -> H) (l : F -> C) \n  (P : forall i, l i \\is Num.real) :\n  sumoutp l f f \\is hermlf.\nProof.\napply/hermlfP; rewrite sumoutpE raddf_sum; apply eq_bigr=>i _.\nby rewrite /=adjfZ adj_outp conj_Creal.\nQed.\nDefinition sumoutp_hermfType F f l P := HermfType (@sumoutp_herm F f l P).\nLemma sumoutp_proj (F : finType) (f : 'PONB(F;H)) :\n  sumoutp (fun=>1) f f \\is projlf.\nProof.\napply/projlfP; split; first by apply/hermlfP/sumoutp_herm=>x; rewrite real1.\nrewrite sumoutpE linear_suml; apply eq_bigr=>i _.\nby rewrite linear_sumr (bigD1 i)//= big1=>[j/negPf nj|];\nrewrite ?scale1r outp_comp ponb_dot ?eqxx ?addr0 ?scale1r// eq_sym nj scale0r.\nQed.\nCanonical sumoutp_projfType F f := ProjfType (@sumoutp_proj F f).\nCanonical sumoutp_obsfType (F : finType) (f : 'PONB(F;H)) := Eval hnf in \n  [obs of sumoutp (fun=>1) f f as [obs of [proj of sumoutp (fun=>1) f f]]].\nCanonical sumoutp_psdfType (F : finType) (f : 'PONB(F;H)) := Eval hnf in \n  [psd of sumoutp (fun=>1) f f as [psd of [proj of sumoutp (fun=>1) f f]]].\n\nLemma supph_sumoutp (G : chsType) (F : finType) (l : F -> C) \n  (f : 'PONB(F;H)) (g : 'PONB(F;G)) :\n  supph (sumoutp l f g) = supph (sumoutp (fun i=>(l i != 0)%:R) f f).\nProof.\napply/hsC_inj/eqhP=>x; rewrite !memh_suppCE.\nrewrite !sumoutpE !sum_lfunE; under eq_bigr do rewrite lfunE/= outpE scalerA.\nunder [in RHS]eq_bigr do rewrite lfunE/= outpE scalerA.\napply/eqb_iff; rewrite !eq_iff !ponb_sum_eq0; split=>P i; move: (P i);\ncase: eqP=>[->|/eqP/negPf P1]; rewrite ?mul0r// mul1r.\nby move=>/eqP; rewrite mulf_eq0 P1/==>/eqP.\nby move=>->; rewrite mulr0.\nQed.\n\nLemma lesupph_sumoutp (G : chsType) (F : finType) (l : F -> C) \n  (f : F -> H) (g : F -> G) :\n  supph (sumoutp l f g) `<=` supph (sumoutp (fun=>1) f f).\nProof.\napply/leh_memCP=>x; rewrite !supphP sumoutpE=>/eqP/(f_equal (dotp x))/eqP.\nrewrite sum_lfunE dotp_sumr linear0.\nunder eq_bigr do rewrite scale1r outpE dotpZr -conj_dotp -normCKC.\nrewrite psumr_eq0=>[i _|]. by rewrite exprn_ge0.\nrewrite -big_all big_andE=>/forallP/= P.\nhave P1: forall i, [< f i ; x >] = 0 by move=>i; move: (P i); \n  rewrite -conj_dotp norm_conjC expf_eq0/= normr_eq0=>/eqP.\napply/eqP; rewrite sumoutpE sum_lfunE big1// =>i _.\nby rewrite lfunE/= outpE P1 scale0r scaler0.\nQed.\n\nLemma sumoutp_trlf (F : finType) l (f : 'PONB(F;H)) :\n  \\Tr (sumoutp l f f) = \\sum_i (l i).\nProof.\nrewrite sumoutpE linear_sum/=;\nby under eq_bigr do rewrite/= linearZ/= outp_trlf ns_dot mulr1.\nQed.\n\nLemma sumoutp_cst_trlf (F : finType) (f : 'PONB(F;H)) (c : C):\n  \\Tr (sumoutp (fun=>c) f f) = c * #|F|%:R.\nProof. by rewrite sumoutp_trlf sumr_const mulr_natr. Qed.\n\nLemma sumoutp1_trlf (F : finType) (f : 'PONB(F;H)) :\n  \\Tr (sumoutp (fun=>1) f f) = #|F|%:R.\nProof. by rewrite sumoutp_cst_trlf mul1r. Qed.\n\nLemma dim_supp_sumoutp (F : finType) (f : 'PONB(F;H)) :\n  \\Dim (supph (sumoutp (fun=>1) f f)) = #|F|.\nProof.\napply/eqP; rewrite -(eqr_nat [numDomainType of C]).\nby rewrite/= -projf_trlf/= supph_projK hsE/= sumoutp1_trlf.\nQed.\n\nEnd Decomposition.\n\n(* unitarylf : spetralUE eigenvalU_norm1 *)\n(* projlf : spectralPE sumoutp (fun=>1) eigenvec eigenvec *)\n(* proj1lf : spetralP1E [> eigenvecP1 ; eigenvecP1 <] *)\n(* other case: spectralE eigenval_proj .. property of eigenval *)\nSection SpectralDecomposition.\nVariable (H : chsType).\n\nDefinition eigenvec_all (U : 'End(H)) i :=\n  r2v (row i (spectralmx (f2mx U))).\nDefinition eigenval_all (U : 'End(H)) i :=\n  spectral_diag (f2mx U) 0 i.\n\nLemma eigenvec_all_onb (U : 'End(H)) i j : \n  [< eigenvec_all U i ; eigenvec_all U j >] = (i == j)%:R.\nProof.\nrewrite dotp_mulmx -[_^*m]trmxK -trmx_mul mxE /eigenvec_all !r2vK.\nby rewrite conjmxE map_row tr_row -mulmx_rowcol map_trmx \n  -adjmxE unitarymxK ?spectral_unitarymx// mxE eq_sym.\nQed.\nCanonical eigenvec_all_ponbasis U := PONBasis (@eigenvec_all_onb U).\nCanonical eigenvec_all_onbasis U := ONBasis (@eigenvec_all_onb U) (@card_ord _).\nCanonical eigenvec_all_nsType U i := Eval hnf in \n  [NS of @eigenvec_all U i as [NS of [PONB of @eigenvec_all U] i]].\n\nDefinition spectral_all U := (sumoutp (eigenval_all U) (eigenvec_all U) (eigenvec_all U)).\n\nLemma spectral_all_trlf U : \\Tr (spectral_all U) = \\sum_i (eigenval_all U i).\nProof.\nrewrite /spectral_all sumoutpE linear_sum; apply eq_bigr=>i _.\nby rewrite/= linearZ/= outp_trlf onb_dot eqxx mulr1.\nQed.\n\nLemma spectral_allPmx U : f2mx U \\is normalmx -> U = spectral_all U.\nProof.\nrewrite qualifE=>/unitarymx_spectralP P.\napply/f2mx_inj. rewrite /spectral_all sumoutpE P linear_sum/=.\nrewrite mulmx_colrow; apply eq_bigr=>i _.\nrewrite col_diag_mul linearZ/= /eigenval_all /eigenvec_all r2vK -scalemxAl.\nby do 2 f_equal; rewrite !adjmxE -map_col -tr_row.\nQed.\n\nLemma spectral_allUP U : U \\is unitarylf -> U = spectral_all U.\nProof. rewrite qualifE=>/unitarymx_normal; exact: spectral_allPmx. Qed.\nLemma spectral_allP U : U \\is hermlf -> U = spectral_all U.\nProof. rewrite qualifE=>/hermmx_normal; exact: spectral_allPmx. Qed.\nLemma spectralUE (U : 'FU(H)) : U%:VF = spectral_all U.\nProof. apply/spectral_allUP/unitaryf_unitary. Qed.\nLemma spectral_allE (U : 'FH(H)) : U%:VF = spectral_all U.\nProof. apply/spectral_allP/hermf_herm. Qed.\n\nLemma eigenvalU_norm1 (U : 'FU(H)) i : `|@eigenval_all U i| = 1.\nProof.\nmove: (unitaryf_unitary U)=>/unitarylfP/lfunP/(_ (eigenvec_all U i))\n/(f_equal (dotp (eigenvec_all U i)))/eqP.\nrewrite lfunE/= adj_dotEV lfunE/= !dotp_norm {1}spectralUE /spectral_all sumoutp_apply.\nby rewrite normrZ ns_norm mulr1 expr1n sqrp_eq1// =>/eqP.\nQed.\n\nLemma spectral_all_herm (U : 'FH(H)) : spectral_all U \\is hermlf.\nProof. by rewrite -spectral_allP hermf_herm. Qed.\nCanonical spectral_all_hermfType U := HermfType (spectral_all_herm U).\nLemma spectral_all_psd (U : 'F+(H)) : spectral_all U \\is psdlf.\nProof. by rewrite -spectral_allP ?psdlf_herm ?psdf_psd. Qed.\nCanonical spectral_all_psdfType U := PsdfType (spectral_all_psd U).\nLemma spectral_all_obs (U : 'FO(H)) : spectral_all U \\is obslf.\nProof. by rewrite -spectral_allP ?obslf_herm ?obsf_obs. Qed.\nCanonical spectral_all_obsfType U := ObsfType (spectral_all_obs U).\nLemma spectral_all_den (U : 'FD(H)) : spectral_all U \\is denlf.\nProof. by rewrite -spectral_allP ?denlf_herm ?denf_den. Qed.\nCanonical spectral_all_denfType U := DenfType (spectral_all_den U).\nLemma spectral_all_den1 (U : 'FD1(H)) : spectral_all U \\is den1lf.\nProof. by rewrite -spectral_allP ?den1lf_herm ?den1f_den1. Qed.\nCanonical spectral_all_den1fType U := Den1fType (spectral_all_den1 U).\nLemma spectral_all_proj (U : 'FP(H)) : spectral_all U \\is projlf.\nProof. by rewrite -spectral_allP ?projlf_herm ?projf_proj. Qed.\nCanonical spectral_all_projfType U := ProjfType (spectral_all_proj U).\nLemma spectral_all_proj1 (U : 'FP1(H)) : spectral_all U \\is proj1lf.\nProof. by rewrite -spectral_allP ?proj1lf_herm ?proj1f_proj1. Qed.\nCanonical spectral_all_proj1fType U := Proj1fType (spectral_all_proj1 U).\nLemma spectral_all_unitary (U : 'FU(H)) : spectral_all U \\is unitarylf.\nProof. by rewrite -spectral_allUP ?unitaryf_unitary. Qed.\nCanonical spectral_all_unitaryfType U := UnitaryfType (spectral_all_unitary U).\n\n(* remark : for unitarylf, use spectral_all *)\n(* following : give decomposition : \\Rank U rather than the whole space *)\n\nDefinition eigen_index_sig (U : 'End(H)) := \n    [finType of {i : 'I_(Vector.dim H) | eigenval_all U i != 0}].\n\nDefinition eigen_index (U : 'End(H)) : 'I_(\\Rank U) -> 'I_(Vector.dim H) :=\n  match \\Rank U =P #|eigen_index_sig U| with\n  | ReflectT equ => fun i => val (enum_val (cast_ord equ i))\n  | ReflectF _ => fun i => widen_ord (ranklf_le_dom U) i\n  end.\n\nLemma widen_ord_inj n m le_n_m : injective (@widen_ord n m le_n_m).\nProof. by move=>i j /(f_equal val)/= P; apply/val_inj=>//. Qed.\n\nLemma eigen_index_inj (U : 'End(H)) : injective (@eigen_index U).\nProof.\nby move=>i j; rewrite /eigen_index; case: eqP=>\n  [?/val_inj/enum_val_inj/cast_ord_inj|?/widen_ord_inj].\nQed.\n\nDefinition eigenvec (U : 'End(H)) i := eigenvec_all U (@eigen_index U i).\nDefinition eigenval (U : 'End(H)) i := eigenval_all U (@eigen_index U i).\n\nLemma eigenvec_ponb (U : 'End(H)) i j : \n  [< @eigenvec U i ; @eigenvec U j >] = (i == j)%:R.\nProof. by rewrite/eigenvec onb_dot (inj_eq (@eigen_index_inj _)). Qed.\nCanonical eigenvec_ponbasis U := PONBasis (@eigenvec_ponb U).\nCanonical eigenvec_nsType U i := Eval hnf in \n  [NS of @eigenvec U i as [NS of [PONB of @eigenvec U] i]].\nDefinition spectral U := (sumoutp (@eigenval U) (@eigenvec U) (@eigenvec U)).\n\nLemma eigen_index_card (U : 'End(H)) : f2mx U \\is normalmx -> \n  \\Rank U = #|eigen_index_sig U|.\nProof.\nmove=>/unitarymx_spectralP P.\nrewrite /eigen_index_sig card_sig -[RHS]muln1 -sum_nat_const /lfrank.\nrewrite P mxrank_mulmxU ?mxrank_mulUCmx ?spectral_unitarymx// rank_diagmx /eigenval_all.\nrewrite (bigID (fun i=>(spectral_diag (f2mx U) 0 i != 0)))/= [X in (_ + X)%N]big1 ?addn0.\nby move=>i/negbNE/eqP->; rewrite eqxx.\nby apply eq_bigr=>i; rewrite inE=>->.\nQed.\n\nLemma spectralPA (U : 'End(H)) : f2mx U \\is normalmx -> U = spectral U.\nProof.\nmove=>P; rewrite {1}(spectral_allPmx P) /spectral_all sumoutpE.\nrewrite (bigID (fun i=>(spectral_diag (f2mx U) 0 i != 0))) [in LHS]/= [X in (_ + X)]big1 ?addr0.\nby rewrite /eigenval_all; move=>i/negbNE/eqP->; rewrite scale0r.\nrewrite /spectral sumoutpE -[LHS]big_sig /eigenval /eigenvec /eigen_index.\ncase: eqP=>//[P2|]; last by rewrite -eigen_index_card.\napply: reindex; exists (fun i=> cast_ord (esym P2) (enum_rank i));\nby move=>x _; rewrite 1?enum_valK cast_ord_comp cast_ord_id// enum_rankK.\nQed.\n\nLemma eigenval_neq0A (U : 'End(H)) : \n  f2mx U \\is normalmx -> (forall i, @eigenval U i != 0).\nProof.\nmove=>P i; rewrite /eigenval /eigen_index; case: eqP; last by rewrite -eigen_index_card.\nmove=>P1/=; case: (enum_val (cast_ord P1 i))=>x IH//.\nQed.\nLemma eigenval_eq0A (U : 'End(H)) : \n  f2mx U \\is normalmx -> (forall i, @eigenval U i == 0 = false).\nProof. by move=>/eigenval_neq0A +i; move=>/(_ i)/negPf. Qed.\n\n(* Lemma spectralUP U : U \\is unitarylf -> U = spectral U.\nProof. rewrite qualifE=>/unitarymx_normal; exact: spectralPA. Qed. *)\nLemma spectralP U : U \\is hermlf -> U = spectral U.\nProof. rewrite qualifE=>/hermmx_normal; exact: spectralPA. Qed.\n(* Lemma spectralUE (U : 'FU(H)) : U%:VF = spectral U.\nProof. apply/spectralUP/unitaryf_unitary. Qed. *)\nLemma spectralE (U : 'FH(H)) : U%:VF = spectral U.\nProof. apply/spectralP/hermf_herm. Qed.\n\nLemma eigenval_neq0 (U : 'FH(H)) i : @eigenval U i != 0.\nProof. by apply/eigenval_neq0A/hermmx_normal; move: (hermf_herm U); rewrite qualifE. Qed.\nLemma eigenval_eq0 (U : 'FH(H)) i : @eigenval U i == 0 = false.\nProof. apply/eqP/eqP; exact: eigenval_neq0. Qed.\n\nLemma eigenval_herm (U : 'FH(H)) i : @eigenval U i \\is Num.real.\nProof.\nmove: (hermf_herm U)=>/hermlfP.\nrewrite {1 2}spectralE /spectral sumoutp_adj=>/lfunP/(_ (eigenvec i)).\nby rewrite !sumoutp_apply=>/ns_scaleI/CrealP.\nQed.\nLemma eigenval_psd (U : 'F+(H)) i : @eigenval U i > 0.\nProof.\nby move: (psdf_psd U)=>/psdlfP/(_ (eigenvec i)); rewrite {2}spectralE \n  /spectral sumoutp_apply dotpZr ns_dot mulr1 le_eqVlt eq_sym eigenval_eq0.\nQed.\nLemma eigenval_obs (U : 'FO(H)) i : 0 < @eigenval U i <= 1.\nProof.\nmove: (obsf_obs U)=>/obslfP[_]/(_ (eigenvec i)).\nby rewrite {2}spectralE /spectral sumoutp_apply dotpZr ns_dot mulr1 eigenval_psd.\nQed.\nLemma eigenval_proj (U : 'FP(H)) i : @eigenval U i = 1.\nProof.\nmove: (projf_idem U)=>/lfunP/(_ (eigenvec i)).\nby rewrite {1 2 4}spectralE /spectral lfunE/= sumoutp_apply linearZ/= sumoutp_apply \n  scalerA -expr2=>/ns_scaleI/eqP; rewrite idemr_01 eigenval_eq0/==>/eqP.\nQed.\nLemma spectralPE (U : 'FP(H)) : U%:VF = sumoutp (fun=>1) (@eigenvec U) (@eigenvec U).\nrewrite {1}spectralE /spectral/=; apply/sumoutp_eq=>i; exact: eigenval_proj.\nQed.\nLemma rank_proj1 (U : 'FP1(H)) : \\Rank U = 1%N.\nProof. by move: (proj1f_proj1 U)=>/proj1lf_rankP[]. Qed.\nLemma trlf_proj1 (U : 'FP1(H)) : \\Tr U = 1.\nProof. by move: (proj1f_proj1 U)=>/proj1lfP[]. Qed.\nLemma eigen_index_P1 (U : 'FP1(H)) : #|'I_(\\Rank U) | = #|'I_1|.\nProof. by rewrite rank_proj1. Qed.\nDefinition eigenvecP1 (U : 'FP1(H)) := castfun (eigen_index_P1 U) (@eigenvec U) ord0.\nLemma spectralP1E (U : 'FP1(H)) : U%:VF = [> eigenvecP1 U ; eigenvecP1 U <].\nProof.\nrewrite {1}spectralE/=/spectral -(sumoutp_cast (eigen_index_P1 U)).\nby rewrite sumoutpE big_ord1 /castfun eigenval_proj scale1r.\nQed.\nLemma eigenvectP1_ns (U : 'FP1(H)) : [< eigenvecP1 U ; eigenvecP1 U >] == 1.\nProof. by rewrite -outp_trlf -spectralP1E trlf_proj1. Qed.\nCanonical eigenvectP1_nsType U := NSType (@eigenvectP1_ns U).\n\nLemma supph_eigenE (U : 'FH(H)) : \n  (supph U)%:VF = sumoutp (fun=>1) (@eigenvec U) (@eigenvec U).\nProof.\nrewrite {1}spectralE/spectral supph_sumoutp/=.\nsuff P: (fun i : 'I_(\\Rank U) => (eigenval i != 0)%:R) =1 (fun=>1 : C).\nby rewrite (sumoutp_eq _ _ P) supph_projK hsE.\nby move=>i; rewrite eigenval_neq0.\nQed.\n\nLemma spectral_herm (U : 'FH(H)) : spectral U \\is hermlf.\nProof. by rewrite -spectralP hermf_herm. Qed.\nCanonical spectral_hermfType U := HermfType (spectral_herm U).\nLemma spectral_psd (U : 'F+(H)) : spectral U \\is psdlf.\nProof. by rewrite -spectralP ?psdlf_herm ?psdf_psd. Qed.\nCanonical spectral_psdfType U := PsdfType (spectral_psd U).\nLemma spectral_obs (U : 'FO(H)) : spectral U \\is obslf.\nProof. by rewrite -spectralP ?obslf_herm ?obsf_obs. Qed.\nCanonical spectral_obsfType U := ObsfType (spectral_obs U).\nLemma spectral_den (U : 'FD(H)) : spectral U \\is denlf.\nProof. by rewrite -spectralP ?denlf_herm ?denf_den. Qed.\nCanonical spectral_denfType U := DenfType (spectral_den U).\nLemma spectral_den1 (U : 'FD1(H)) : spectral U \\is den1lf.\nProof. by rewrite -spectralP ?den1lf_herm ?den1f_den1. Qed.\nCanonical spectral_den1fType U := Den1fType (spectral_den1 U).\nLemma spectral_proj (U : 'FP(H)) : spectral U \\is projlf.\nProof. by rewrite -spectralP ?projlf_herm ?projf_proj. Qed.\nCanonical spectral_projfType U := ProjfType (spectral_proj U).\nLemma spectral_proj1 (U : 'FP1(H)) : spectral U \\is proj1lf.\nProof. by rewrite -spectralP ?proj1lf_herm ?proj1f_proj1. Qed.\n\n(* following for hspace *)\nDefinition heigen (U : {hspace H}) : 'I_(\\Dim U) -> H := (@eigenvec U).\nCanonical heigen_ponbasis U := Eval hnf in [PONB of @heigen U].\nCanonical heigen_nsType U i := Eval hnf in [NS of @heigen U i].\nLemma heigenE (U : {hspace H}) :\n  U%:VF = sumoutp (fun=>1) (@heigen U) (@heigen U).\nProof. exact: spectralPE. Qed.\n\n(* since heigen is a ponb, we can always extend it to the whole space *)\nLemma sumoutp_applyC (G : chsType) (F : finType) (l : F -> C) \n  (f : 'PONB(F;H)) (g : F -> G) i :\n  (sumoutp l f g) (ponb_compl f i) = 0.\nProof.\nrewrite sumoutpE sum_lfunE big1// =>j _.\nby rewrite lfunE/= outpE ponb_ortho_compl scale0r scaler0.\nQed.\n\nLemma sumoutp_compl (F : finType) (f : 'PONB(F;H)) :\n  sumoutp (fun=>1) f f + sumoutp (fun=>1) (ponb_compl f) (ponb_compl f) = \\1.\nProof.\napply/(intro_onb [ONB of (ponb_ext f)])=>/= i.\nrewrite !lfunE/=; case: i=>i; rewrite ?ponb_extCE ?ponb_extE \n  ?sumoutp_apply ?sumoutp_applyC scale1r ?add0r//.\nrewrite sumoutpE sum_lfunE big1 ?addr0// =>j _.\nby rewrite scale1r outpE ponb_ortho_complV scale0r.\nQed.\n\nLemma hspacelfP (A B : {hspace H}) : A%:VF = B <-> A = B.\nProof. by split=>[/lfunP|/hspaceP] P; [apply/hspaceP=>i|apply/lfunP=>i]. Qed.\n\nLemma sumoutp_hsC (U : {hspace H}) : \n  (~` U) = supph (sumoutp (fun=>1) (ponb_compl [PONB of @heigen U]) \n  (ponb_compl [PONB of @heigen U])).\nProof.\napply/hspacelfP; rewrite supph_projK hs2lfE hsE/= /cplmt.\nmove: (sumoutp_compl [PONB of @heigen U])=>/esym/eqP; rewrite addrC -subr_eq=>/eqP<-.\nby rewrite {1}spectralPE.\nQed.\n\nEnd SpectralDecomposition.\n\nSection RankExtra.\nVariable (F G H : chsType).\n\nLemma ranklfM_max (A : 'Hom(F,G)) (B : 'Hom(H,F)) :\n  (\\Rank (A \\o B) <= Vector.dim F)%N.\nProof. by rewrite /lfrank f2mx_comp; exact: mulmx_max_rank. Qed.\n\nLemma ranklfM_maxl (A : 'Hom(F,G)) (B : 'Hom(H,F)) :\n  (\\Rank (A \\o B) <= \\Rank A)%N.\nProof. by rewrite /lfrank f2mx_comp; exact: mxrankM_maxr. Qed.\n\nLemma ranklfM_maxr (A : 'Hom(F,G)) (B : 'Hom(H,F)) :\n  (\\Rank (A \\o B) <= \\Rank B)%N.\nProof. by rewrite /lfrank f2mx_comp; exact: mxrankM_maxl. Qed.\n\nLemma ranklfM_min (A : 'Hom(F,G)) (B : 'Hom(H,F)) :\n  (\\Rank A + \\Rank B - Vector.dim F <= \\Rank (A \\o B))%N.\nProof. rewrite /lfrank f2mx_comp addnC; exact: mxrank_mul_min. Qed.\n\nLemma ranklfM0_max (A : 'Hom(F,G)) (B : 'Hom(H,F)) :\n  A \\o B = 0 -> (\\Rank A + \\Rank B <= Vector.dim F)%N.\nProof. by move=>/(f_equal f2mx); rewrite /lfrank addnC f2mx_comp linear0; exact: mulmx0_rank_max. Qed.\n\nLemma ranklfM1_max (B : 'Hom(F,G)) (A : 'Hom(G,H)) (C : 'Hom(H,F)) :\n  A \\o B \\o C = \\1 -> (Vector.dim H <= \\Rank B)%N.\nProof. move=>/(f_equal f2mx); rewrite /lfrank !f2mx_comp f2mx1 mulmxA; exact: mulmx1_min_rank. Qed.\n\nLemma ranklf_Frobenius (I : chsType) (A : 'Hom(F,G)) (B : 'Hom(H,F)) (C : 'Hom(I,H)) :\n  (\\Rank (A \\o B) + \\Rank (B \\o C) <= \\Rank B + \\Rank (A \\o B \\o C))%N.\nProof. rewrite /lfrank !f2mx_comp mulmxA addnC; exact: mxrank_Frobenius. Qed.\n\nLemma ranklfM_free (A : 'Hom(F,G)) (B : 'Hom(H,F)) :\n  (Vector.dim F <= \\Rank A)%N -> \\Rank (A \\o B) = \\Rank B.\nProof.\nrewrite /lfrank row_leq_rank f2mx_comp; exact: mxrankMfree.\nQed.\n\nEnd RankExtra.\n\n\nSection CopyVspace.\nVariable (H : chsType).\nImplicit Type (U V W : {hspace H}).\n\nLemma lehPn {U V} : reflect (exists2 u, u \\in U & u \\notin V) (~~ (U `<=` V)).\nProof. \nby rewrite leh2v; apply/(iffP (@subvPn _ _ _ _)); \nmove=>[u P1 P2]; exists u; rewrite ?memh2v// -memh2v.\nQed.\n\n(* Picking a non-zero vector in a subspace. *)\n(* Lemma memv_pick U : vpick U \\in U. Proof. by rewrite mem_r2v nz_row_sub. Qed.\n\nLemma vpick0 U : (vpick U == 0) = (U == 0%VS).\nProof. by  rewrite -memv0 mem_r2v -subv0 /subV vs2mx0 !submx0 nz_row_eq0. Qed. *)\n\n(* Sum of subspaces. *)\nLemma memhU u v U V : u \\in U -> v \\in V -> u + v \\in U `|` V.\nProof. simph2v; exact: memv_add. Qed.\nLemma memhUP {w U V} :\n  reflect (exists2 u, u \\in U & exists2 v, v \\in V & w = u + v)\n          (w \\in U `|` V).\nProof.\nsimph2v; apply/(iffP (memv_addP)); move=>[u Pu[v Pv Puv]]; \nby (exists u; last exists v); simph2v=>//; simpv2h=>//.\nQed.\n\nLemma memh_cupsl I r (P : pred I) vs U :\n  (forall i, P i -> vs i \\in U) -> \\sum_(i <- r | P i) vs i \\in U.\nProof. by simph2v=>P1; apply/memv_suml=>i/P1; simph2v. Qed.\n\nLemma memh_cupsr I (r : seq I) (P : pred I) (vs : I -> H) (Us : I -> {hspace H}) :\n    (forall i, P i -> vs i \\in Us i) ->\n  \\sum_(i <- r | P i) vs i \\in (\\cup_(i <- r | P i) Us i).\nProof.\nmove=>Uv; elim: r=>[|r x IH]; first by rewrite !big_nil mem0h.\nby rewrite !big_cons; case E: (P r)=>//; apply/memhU=>//; apply Uv.\nQed.\n\nLemma memh_cupsP (I : finType) {P : pred I} {Us : I -> {hspace H}} {v} : \n  reflect (exists2 vs, forall i, P i ->  vs i \\in Us i\n                     & v = \\sum_(i | P i) vs i)\n          (v \\in \\cup_(i | P i) Us i).\nProof.\nrewrite memh2v cuphs2v vs2hsK; apply/(iffP memv_sumP); \nby move=>[vs P1 P2]; exists vs=>[i/P1|//]; simph2v.\nQed.\n\nLemma memhI w U V : (w \\in U `&` V) = (w \\in U) && (w \\in V).\nProof. simph2v; exact: memv_cap. Qed.\n\nLemma memhIP {w U V} : reflect (w \\in U /\\ w \\in V) (w \\in U `&` V).\nProof. simph2v; exact: memv_capP. Qed.\n\nLemma hs_modl U V W : U `<=` W -> U `|` (V `&` W) = (U `|` V) `&` W.\nProof. simph2v=>P; f_equal; exact: vspace_modl. Qed.\n\nLemma hs_modr  U V W : W `<=` U -> (U `&` V) `|` W = U `&` (V `|` W).\nProof. by rewrite -!(cuphC W) !(caphC U); apply: hs_modl. Qed.\n\nLemma diffhE U V : U `\\` V =  U `&` (~` (U `&` V)). Proof. by []. Qed.\nLemma leBh U V : U `\\` V `<=` U. Proof. exact: lehIl. Qed.\nLemma caphDx U V : (U `\\` V) `&` V = `0`.\nProof. by rewrite diffhE caphAC caphxC. Qed.\nLemma caphxD U V : V `&` (U `\\` V) = `0`.\nProof. by rewrite caphC caphDx. Qed.\nLemma cuphDI U V : (U `\\` V) `|` (U `&` V) = U.\nProof. by rewrite diffhE cuphC [_ `&` ~` _]caphC hsUCI ?lehIl. Qed.\nLemma cuphID U V : (U `&` V) `|` (U `\\` V) = U.\nProof. by rewrite cuphC cuphDI. Qed.\nLemma cuphDx U V : (U `\\` V) `|` V = U `|` V.\nProof. by rewrite -{2}(cuphDI U V) -cuphA caphUK. Qed.\nLemma cuphxD U V : V `|` (U `\\` V) = V `|` U.\nProof. by rewrite !(cuphC V) cuphDx. Qed.\n\n(* Subspace dimension. *)\nLemma dimh0 : \\Dim (`0` : {hspace H}) = 0%N.\nProof. by rewrite /dimh hs2lfE ranklf0. Qed.\nLemma dimh1 : \\Dim (`1` : {hspace H}) = Vector.dim H.\nProof. by rewrite /dimh hs2lfE ranklf1. Qed.\nLemma dimhC (U : {hspace H}) : \\Dim (~` U) = (\\Dim {:H} - \\Dim U)%N.\nProof. by rewrite sumoutp_hsC dim_supp_sumoutp !card_ord dimh1. Qed.\nLemma dimh_le U V : U `<=` V -> (\\Dim U <= \\Dim V)%N.\nProof. by rewrite leh_compr /dimh=>/eqP<-; exact: ranklfM_maxl. Qed.\nLemma dimhIl U V : (\\Dim (U `&` V) <= \\Dim U)%N.\nProof. apply/dimh_le; exact: leIl. Qed.\nLemma dimhIr U V : (\\Dim (U `&` V) <= \\Dim V)%N. \nProof. apply/dimh_le; exact: leIr. Qed.\nLemma dimhUl U V : (\\Dim U <= \\Dim (U `|` V))%N.\nProof. apply/dimh_le; exact: leUl. Qed.\nLemma dimhUr U V : (\\Dim V <= \\Dim (U `|` V))%N.\nProof. apply/dimh_le; exact: leUr. Qed.\n\nLemma dimh_eq0 U :  (\\Dim U == 0%N) = (U == `0`).\nProof. simph2v; exact: dimv_eq0. Qed.\nLemma dim_hline (v : H) : \\Dim <[v]> = (v != 0).\nProof. simph2v; exact: dim_vline. Qed.\nLemma dimh_leqif_sup U V : U `<=` V -> (\\Dim U <= \\Dim V ?= iff (V `<=` U))%N.\nProof. simph2v; exact: dimv_leqif_sup. Qed.\nLemma dimh_leqif_eq U V : U `<=` V -> (\\Dim U <= \\Dim V ?= iff (U == V))%N.\nProof. simph2v; exact: dimv_leqif_eq. Qed.\nLemma eqhEdim U V : (U == V) = (U `<=` V) && (\\Dim V <= \\Dim U)%N.\nProof. simph2v; exact: eqEdim. Qed.\nLemma dimhUI U V : (\\Dim (U `|` V) + \\Dim (U `&` V) = \\Dim U + \\Dim V)%N.\nProof. simph2v; exact: dimv_sum_cap. Qed.\nLemma dimhU_disjoint U V :\n  U `&` V = `0` -> \\Dim (U `|` V) = (\\Dim U + \\Dim V)%N.\nProof. simph2v=>/vs2hs_inj; exact: dimv_disjoint_sum. Qed.\nLemma dimhID U V : (\\Dim (U `&` V) + \\Dim (U `\\` V))%N = \\Dim U.\nProof.\nrewrite -[in RHS](cuphID U V) dimhU_disjoint//.\nby rewrite diffhE caphC -caphA caphCx caph0.\nQed.\nLemma dimhDI U V : (\\Dim (U `\\` V) + \\Dim (U `&` V))%N = \\Dim U.\nProof. by rewrite addnC dimhID. Qed.\nLemma dimhU_leqif U V :\n  (\\Dim (U `|` V) <= \\Dim U + \\Dim V ?= iff (U `&` V `<=` `0`))%N.\nProof. simph2v; exact: dimv_add_leqif. Qed.\nLemma hsD_eq0 U V : (U `\\` V == `0`) = (U `<=` V).\nProof.\nrewrite -dimh_eq0 -(eqn_add2l (\\Dim (U `&` V))) addn0 dimhID eq_sym.\nby rewrite (dimh_leqif_eq (lehIl _ _)) eq_caphl.\nQed.\nLemma dimv_leq_sum I r (P : pred I) (Us : I -> {hspace H}) : \n  (\\Dim (\\cup_(i <- r | P i) Us i) <= \\sum_(i <- r | P i) \\Dim (Us i))%N.\nProof.\nelim/big_rec2: _ =>/= [|i d vs _ le_vs_d]; first by rewrite dimh0.\nby apply: (leq_trans (dimhU_leqif _ _)); rewrite leq_add2l.\nQed.\n\nEnd CopyVspace.\n\n(* basis, onbasis *)\n\n(* ?? split part to orthomodular lattice ?? *)\n(* orthogonal between vector & space , space & space , vector & vector *)\n(* commutative , lattice commute <-> projection commute *)\nSection ProjectionLattice.\nVariable (H : chsType).\nEnd ProjectionLattice.\n\nSection Extra.\nVariable (H : chsType).\nImplicit Type (u v : H) (U V : {hspace H}).\n\n(* norm and dot compared to 1 *)\nLemma hnorm_le1 v : `|v| <= 1 = ([< v ; v >] <= 1).\nProof. by rewrite dotp_norm -{2}(expr1n _ 2%N) ler_pexpn2r// nnegrE. Qed.\nLemma hnorm_eq1 v : `|v| == 1 = ([<v ; v>] == 1).\nProof. by rewrite dotp_norm -{2}(expr1n _ 2%N) eqr_expn2//. Qed.\n\nLemma memh_line v : v \\in <[v]>.\nProof. by apply/hlineP; exists 1; rewrite scale1r. Qed.\nLemma memhZ_line (c : C) v : c *: v \\in <[v]>.\nProof. by apply/memhZ/memh_line. Qed.\nLemma memhE_line v U : (v \\in U) = (<[v]> `<=` U).\nProof. by simph2v; exact: memvE. Qed.\nLemma hline0 : <[0:H]> = `0`.\nProof. by rewrite hline_def; apply/hspacelfP; rewrite !hsE/= outp0 scaler0. Qed.\n\nLemma lef_hline v : `|v| <= 1 -> [> v ; v <] ⊑ <[v]>.\nProof.\ncase E: (v == 0); first by move: E=>/eqP-> _; rewrite outp0 psdf_ge0.\nby move=>lv; rewrite hline_def hsE/= lev_pescale// ?outp_ge0// \n  invf_ge1 ?exprn_ile1// exprn_gt0// normr_gt0 E.\nQed.\n\nLemma lef_outp v U : `|v| <= 1 -> v \\in U -> [> v ; v <] ⊑ U.\nProof. move=>/lef_hline; rewrite memhE_line leh_lef; exact: le_trans. Qed.\n\nLemma hlineD u v : <[u + v]> `<=` <[u]> `|` <[v]>.\nProof. by apply/lehP=>x; move=>/hlineP[k ->]; rewrite scalerDr; apply/memhU; apply/memhZ_line. Qed.\nLemma hlineD_sup u v U : u \\in U -> v \\in U -> <[u + v]> `<=` U.\nProof. by rewrite -memhE_line; exact: memhD. Qed.\nLemma hlineE u : <[u]> = supph [>u ; u<].\nProof. by []. Qed.\nLemma supphZ (c : C) (A : 'End(H)) : c != 0 -> supph (c *: A) = supph A.\nProof.\nby move=>/negPf P; apply/hsC_inj/eqhP=>x; apply/eqb_iff; \nrewrite !memh_suppCE lfunE/= scaler_eq0 P.\nQed.\nLemma hlineZ (c : C) u : c != 0 -> <[c *: u]> = <[u]>.\nProof. \nby move=>P; rewrite !hlineE outpZl outpZr scalerA -normCK; \n  apply/supphZ; rewrite expf_eq0/= normr_eq0.\nQed.\nLemma hline_sum_seq I (r : seq I) (P : pred I) (f : I -> H) U : \n  (forall i, P i -> f i \\in U) -> <[\\sum_(i <- r | P i) f i]> `<=` U.\nProof.\nmove=>P1; elim/big_rec : _=>[|x v Px IH]; first by rewrite hline0 le0h.\napply/hlineD_sup. by apply P1. by rewrite memhE_line.\nQed.\nLemma hline_sum (I : finType) (P : pred I) (f : I -> H) U : \n  (forall i, P i -> f i \\in U) -> <[\\sum_(i | P i) f i]> `<=` U.\nProof. exact: hline_sum_seq. Qed.\nLemma projf_comp_eq0 (U V : 'FP(H)) : U \\o V == 0 = (V \\o U == 0).\nProof. by rewrite -(inj_eq (@adjf_inj _ _)) linear0 adjf_comp !hermf_adjE/=. Qed.\nLemma projf_comp_eq0P (U V : 'FP(H)) : U \\o V = 0 -> (V \\o U = 0).\nProof. by move=>/eqP; rewrite projf_comp_eq0=>/eqP. Qed.\n\nLemma suppU_comp0 (U V : 'FP(H)) : U \\o V = 0 -> \n  (supph U `|` supph V)%:VF = U%:VF + V%:VF.\nProof.\nmove=>P1; have P2: U%:VF + V%:VF \\is projlf.\nby apply/projlfP; rewrite adjfD !hermf_adjE/= linearDl/= \n  !linearDr/= P1 !projf_idem projf_comp_eq0P// addr0 add0r.\nby rewrite hsE/= !supph_projK !hsE -{1}(projfE tt P2) supplfK.\nQed.\n\nLemma memhUl U V u : u \\in U -> u \\in U `|` V.\nProof. apply/lehP/lehUl. Qed.\nLemma memhUr U V u : u \\in V -> u \\in U `|` V.\nProof. apply/lehP/lehUr. Qed.\nLemma memhIl U V u : u \\in U `&` V -> u \\in U.\nProof. apply/lehP/lehIl. Qed.\nLemma memhIr U V u : u \\in U `&` V -> u \\in V.\nProof. apply/lehP/lehIr. Qed.\n\nEnd Extra.\n", "meta": {"author": "coq-quantum", "repo": "CoqQ", "sha": "95a24776c5e0df839f2c5a9133227eef56487065", "save_path": "github-repos/coq/coq-quantum-CoqQ", "path": "github-repos/coq/coq-quantum-CoqQ/CoqQ-95a24776c5e0df839f2c5a9133227eef56487065/src/hspace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6945918686214164}}
{"text": "From Theories Require Import\n  Tactics Chap_2_Framework.\n\n(** * Specification *)\n\n(** ** Syntax *)\n\nInductive Typ :=\n  | t_void\n  | t_arr (t1 t2 : Typ).\n\nInductive Exp :=\n  | e_var (x : nat)\n  | e_app (e1 e2 : Exp)\n  | e_abs (e : Exp).\n\nInductive Val :=\n  | v_abs (ve : List Val) (e : Exp).\n\n(** ** Type System *)\n\nDefinition TypEnv := List Typ.\n\nInductive ExpTyp : TypEnv -> Exp -> Typ -> Prop :=\n  | et_var :\n      forall x te t1,\n      indexr x te = some t1 ->\n      ExpTyp te (e_var x) t1\n  | et_app :\n      forall te e1 e2 t1 t2,\n      ExpTyp te e1 (t_arr t1 t2) ->\n      ExpTyp te e2 t1 ->\n      ExpTyp te (e_app e1 e2) t2\n  | et_abs :\n      forall te e t1 t2,\n      ExpTyp (t1 :: te) e t2 ->\n      ExpTyp te (e_abs e) (t_arr t1 t2).\n\n\n(** ** Semantics *)\n\nDefinition ValEnv := List Val.\n\nFixpoint eval (n : nat) (ve : ValEnv) (e : Exp) : CanTimeout (CanErr Val) :=\n  match n with\n  | 0 => none\n  | S n =>\n      match e with\n      | e_var x => done (indexr x ve)\n      | e_abs e => done (noerr (v_abs ve e))\n      | e_app e1 e2 =>\n          ' v_abs ve1' e1' <- eval n ve e1;\n          ' v2 <- eval n ve e2;\n          eval n (v2 :: ve1') e1'\n      end\n  end.\n\n(** ** Type Soundness *)\n\nInductive ValTyp : Val -> Typ -> Prop :=\n  | vt_abs :\n      forall ve te e t1 t2,\n      Forall2 ValTyp ve te ->\n      ExpTyp (t1 :: te) e t2 ->\n      ValTyp (v_abs ve e) (t_arr t1 t2)\n  .\n\nDefinition WfEnv : ValEnv -> TypEnv -> Prop :=\n  Forall2 ValTyp.\n\n(** * Theorems *)\n\nHint Constructors Typ Exp Val ExpTyp ValTyp Opt List.\nHint Unfold indexr length ValEnv TypEnv WfEnv.\nHint Resolve ex_intro.\n\nTheorem type_soundness :\n  forall n e te ve res t,\n  eval n ve e = done res ->\n  ExpTyp te e t ->\n  WfEnv ve te ->\n  exists v, res = noerr v /\\ ValTyp v t.\nProof.\n  intros n. induction n.\n  Case \"n = 0\". intros until 0. intros Heval. inversion Heval.\n  Case \"n = S n\". intros until 0. intros Heval Htype Hwf. destruct e.\n    Case2 \"var\".\n      inversion Heval as [Heval']; clear Heval Heval'.\n      inversion Htype; subst te0 x t1; rename H1 into Htype'.\n      destruct (fa2_indexr Hwf Htype') as [v [I V]].\n      rewrite I. eexists. split. reflexivity. exact V.\n    Case2 \"app\".\n      inversion Htype; subst t2 e0 e3 te0;\n        rename H2 into Htype1; rename H4 into Htype2; rename t into t2.\n      simpl in Heval.\n      remember (eval n ve e1) as mmv1.\n      destruct mmv1 as [mv1|].\n      Case3 \"mmv1 = some mv1\".\n        (** Apply [IHn] to [e1] *)\n        assert (exists v1, mv1 = some v1 /\\ ValTyp v1 (t_arr t1 t2)) as [v1 [E1 HVtype1]].\n          { eapply IHn; eauto. }\n        subst mv1.\n        (** Invert [v1] to closure [v_abs ve0 e] with [ExpTyp] evidence. *)\n        inversion HVtype1; subst t0 t3. subst v1.\n        remember (eval n ve e2) as mmv2.\n        destruct mmv2 as [mv2|].\n        Case4 \"mmv2 = some mv2\".\n          (** Apply [IHn] to [e2] *)\n          assert (exists v2, mv2 = some v2 /\\ ValTyp v2 t1) as [v2 [E2 HVtype2]].\n            { eapply IHn; eauto. }\n          subst mv2.\n          (** Apply [IHn] to closure body [e] *)\n          eapply IHn; eauto.\n        Case4 \"mmv2 = none  [contradiction]\".\n          inversion Heval.\n      Case3 \"mmv1 = none  [contradiction]\".\n        inversion Heval.\n    Case2 \"abs\".\n      inversion Htype; subst te0 e0. subst t.\n      inversion Heval as [Heval']; clear Heval Heval'.\n      eexists. split. eauto. eapply vt_abs; eauto.\nQed.\n", "meta": {"author": "m0rphism", "repo": "definitional", "sha": "2fcc4a0e923ed7ee2c9aef34e1d6b9ff34cd3aa5", "save_path": "github-repos/coq/m0rphism-definitional", "path": "github-repos/coq/m0rphism-definitional/definitional-2fcc4a0e923ed7ee2c9aef34e1d6b9ff34cd3aa5/theories/Chap_3_STLC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.8152324915965391, "lm_q1q2_score": 0.6945396085356917}}
{"text": "(* -*- mode: coq; mode: visual-line -*- *)\n(** * Comparing definitions of equivalence *)\n\nRequire Import HoTT.Basics HoTT.Types.\nRequire Import HProp.\nRequire Import HoTT.Tactics.\n\nLocal Open Scope nat_scope.\nLocal Open Scope path_scope.\n\nGeneralizable Variables A B f.\n\nSection AssumeFunext.\nContext `{Funext}.\n\n(** In this file we show that several different definitions of \"equivalence\" are all equivalent to the one we have chosen.  This also yields alternative proofs that [IsEquiv f] is an hprop. *)\n\n(** ** Contractible maps *)\n\n(** We say a map is \"contractible\" if all of its homotopy fibers are contractible.  (More generally, a map is n-truncated if all of its homotopy fibers are n-truncated.)  This was Voevodsky's first definition of equivalences in homotopy type theory.\n\n   It is fairly straightforward to show that this definition is *logically* equivalent to the one we have given.\n*)\n\nDefinition fcontr_isequiv `(f : A -> B)\n  : IsEquiv f -> (forall b:B, Contr {a : A & f a = b}).\nProof.\n  intros ? b.  exists (f^-1 b ; eisretr f b).  intros [a p].\n  refine (path_sigma' _ ((ap f^-1 p)^ @ eissect f a) _).\n  rewrite (transport_compose (fun y => y = b) f _ _), transport_paths_l.\n  rewrite ap_pp, ap_V, <- ap_compose, inv_Vp, concat_pp_p.\n  rewrite (concat_A1p (eisretr f) p).\n  rewrite eisadj.  by apply concat_V_pp.\nDefined.\n\nDefinition isequiv_fcontr `(f : A -> B)\n  : (forall b:B, Contr {a : A & f a = b}) -> IsEquiv f.\nProof.\n  intros ?. refine (Build_IsEquiv _ _ _\n    (fun b => (center {a : A & f a = b}).1)\n    (fun b => (center {a : A & f a = b}).2)\n    (fun a => (@contr {x : A & f x = f a} _ (a;1))..1)\n    _).\n  intros a. apply moveL_M1.\n  rewrite <- transport_paths_l, <- transport_compose.\n  exact ((@contr {x : A & f x = f a} _ (a;1))..2).\nDefined.\n\n(** It follows that when proving a map is an equivalence, we may assume its codomain is inhabited. *)\nDefinition isequiv_inhab_codomain\n           `(f : A -> B) (feq : B -> IsEquiv f)\n: IsEquiv f.\nProof.\n  apply isequiv_fcontr.\n  intros b.\n  apply fcontr_isequiv, (feq b).\nDefined.\n\n(** Therefore, since both are hprops, they are equivalent by [equiv_iff_hprop].  However, we can also use this to *prove* that [IsEquiv] is an hprop.  We begin by showing that if [f] is an equivalence, then the type of sections of [f] and the type of retractions of [f] are both contractible. *)\n\nDefinition contr_sect_equiv `(f : A -> B) `{IsEquiv A B f}\n  : Contr {g : B -> A & Sect g f}.\nProof.\n  (* First we turn homotopies into paths. *)\n  refine (contr_equiv' { g : B -> A & f o g = idmap } _).\n  - symmetry.\n    refine (equiv_functor_sigma' 1 _); intros g.\n    exact (equiv_path_forall (f o g) idmap).\n    (* Now this is just the fiber over [idmap] of postcomposition with [f], and the latter is an equivalence since [f] is. *)\n  - apply fcontr_isequiv; exact _.\nDefined.\n\nDefinition contr_retr_equiv `(f : A -> B) `{IsEquiv A B f}\n  : Contr {g : B -> A & Sect f g}.\nProof.\n  (* This proof is just like the previous one. *)\n  refine (contr_equiv' { g : B -> A & g o f = idmap } _).\n  - symmetry.\n    refine (equiv_functor_sigma' 1 _); intros g.\n    exact (equiv_path_forall (g o f) idmap).\n  - apply fcontr_isequiv; exact _.\nDefined.\n\n(** Using this, we can prove that [IsEquiv f] is an h-proposition.  We make this a [Local Definition] since we already have a [Global Instance] of it available in [types/Equiv].  *)\n\nLocal Definition hprop_isequiv `(f : A -> B) : IsHProp (IsEquiv f).\nProof.\n  apply hprop_inhabited_contr; intros ?.\n  (* Get rid of that pesky record. *)\n  refine (contr_equiv _ (issig_isequiv f)).\n  (* Now we claim that the top two elements, [s] and the coherence relation, taken together are contractible, so we can peel them off. *)\n  refine (contr_equiv' {g : B -> A & Sect g f}\n    (equiv_functor_sigma' 1\n      (fun g => (@equiv_sigma_contr (Sect g f)\n        (fun r => {s : Sect f g & forall x, r (f x) = ap f (s x) })\n        _)))^-1).\n  (* What remains afterwards is just the type of sections of [f]. *)\n  2:apply contr_sect_equiv; assumption.\n  intros r.\n  (* Now we claim this is equivalent to a certain space of paths. *)\n  refine (contr_equiv'\n    (forall x, (existT (fun a => f a = f x) x 1) = (g (f x); r (f x)))\n    _^-1).\n  (* The proof of this equivalence is basically just rearranging quantifiers and paths. *)\n  - refine (_ oE (equiv_sigT_coind (fun x => g (f x) = x)\n                                   (fun x p => r (f x) = ap f p))).\n    refine (equiv_functor_forall' 1 _); intros a; simpl.\n    refine (equiv_path_inverse _ _ oE _).\n    refine ((equiv_path_sigma (fun x => f x = f a)\n                              (g (f a) ; r (f a)) (a ; 1%path)) oE _); simpl.\n    refine (equiv_functor_sigma' 1 _); intros p; simpl.\n    rewrite (transport_compose (fun y => y = f a) f), transport_paths_l.\n    refine (equiv_moveR_Vp _ _ _ oE _).\n      by rewrite concat_p1; apply equiv_idmap.\n      (* Finally, this is a space of paths in a fiber of [f]. *)\n  - refine (@contr_forall _ _ _ _); intros a.\n    refine (@contr_paths_contr _ _ _ _).\n      by refine (fcontr_isequiv f _ _).\nQed.\n\n(** Now since [IsEquiv f] and the assertion that its fibers are contractible are both HProps, logical equivalence implies equivalence. *)\n\nDefinition equiv_fcontr_isequiv `(f : A -> B)\n  : (forall b:B, Contr {a : A & f a = b}) <~> IsEquiv f.\nProof.\n  apply equiv_iff_hprop.\n  - by apply isequiv_fcontr.\n  - by apply fcontr_isequiv.\nDefined.\n\n(** Alternatively, we could also construct this equivalence directly, and derive the fact that [IsEquiv f] is an HProp from that.  *)\n\nLocal Definition equiv_fcontr_isequiv' `(f : A -> B)\n  : (forall b:B, Contr {a : A & f a = b}) <~> IsEquiv f.\nProof.\n  (* First we get rid of those pesky records. *)\n  refine (_ oE (equiv_functor_forall_id \n    (fun b => (issig_contr {a : A & f a = b})^-1))).\n  refine (issig_isequiv f oE _).\n  (* Now we can really get to work.\n     First we peel off the inverse function and the [eisretr]. *)\n  refine (_ oE (equiv_sigT_coind _ _)^-1).\n  refine (_ oE\n    (@equiv_functor_sigma' _ _ _ (fun f0 => forall x y, f0 x = y)\n      (equiv_sigT_coind _ _)\n      (fun fg => equiv_idmap (forall x y,\n        (equiv_sigT_coind _ (fun b a => f a = b) fg x = y))))^-1).\n  refine (_ oE (equiv_sigma_assoc _ _)^-1).\n  refine (equiv_functor_sigma_id _). intros g.\n  refine (equiv_functor_sigma_id _). intros r. simpl.\n  (* Now we use the fact that Paulin-Mohring J is an equivalence. *)\n  refine (_ oE (@equiv_functor_forall' _ _\n    (fun x => forall a (y : f a = x),\n      (existT (fun a => f a = x) (g x) (r x)) = (a;y))\n    _ _ 1\n    (fun x:B => equiv_sigT_ind\n      (fun y:exists a:A, f a = x => (g x;r x) = y)))^-1).\n  refine (_ oE equiv_flip _).\n  refine (_ oE (@equiv_functor_forall' _ _\n    (fun a => existT (fun a' => f a' = f a) (g (f a)) (r (f a)) = (a;1%path))\n    _ _ 1\n    (fun a => equiv_paths_ind (f a)\n      (fun b y => (existT (fun a => f a = b) (g b) (r b)) = (a;y))))^-1).\n  (* We identify the paths in a Sigma-type. *)\n  refine (_ oE (@equiv_functor_forall' _ _\n    (fun a =>\n      exists p, transport (fun a' : A => f a' = f a) p (r (f a)) = 1%path)\n    _ _ 1\n    (fun a => equiv_path_sigma (fun a' => f a' = f a)\n      (g (f a);r (f a)) (a;1%path)))^-1).\n  (* Now we can peel off the [eissect]. *)\n  refine (_ oE (equiv_sigT_coind\n    (fun a => g (f a) = a)\n    (fun a p => transport (fun a' => f a' = f a) p (r (f a)) = 1%path))^-1).\n  refine (equiv_functor_sigma' 1 _). intros s.\n  (* And what's left is the [eisadj]. *)\n  refine (equiv_functor_forall' 1 _). intros a; simpl.\n  refine (_ oE (equiv_concat_l\n             (transport_compose (fun b => b = f a) f (s a) (r (f a))\n              @ transport_paths_l (ap f (s a)) (r (f a)))^ 1%path)).\n  exact ((equiv_concat_r (concat_p1 _) _)\n           oE ((equiv_moveR_Vp (r (f a)) 1 (ap f (s a)))^-1)).\nDefined.\n\n(** ** Bi-invertible maps *)\n\n(** A map is \"bi-invertible\" if it has both a section and a retraction, not necessarily the same.  This definition of equivalence was proposed by Andre Joyal. *)\n\nDefinition BiInv `(f : A -> B) : Type\n  := {g : B -> A & Sect f g} * {h : B -> A & Sect h f}.\n\n(** It seems that the easiest way to show that bi-invertibility is equivalent to being an equivalence is also to show that both are h-props and that they are logically equivalent. *)\n\nDefinition isequiv_biinv `(f : A -> B)\n  : BiInv f -> IsEquiv f.\nProof.\n  intros [[g s] [h r]].\n  exact (isequiv_adjointify f g\n    (fun x => ap f (ap g (r x)^ @ s (h x))  @ r x)\n    s).\nDefined.\n\nGlobal Instance isprop_biinv `(f : A -> B) : IsHProp (BiInv f) | 0.\nProof.\n  apply hprop_inhabited_contr.\n  intros bif; pose (fe := isequiv_biinv f bif).\n  apply @contr_prod.\n  (* For this, we've done all the work already. *)\n  - by apply contr_retr_equiv.\n  - by apply contr_sect_equiv.\nDefined.\n\nDefinition equiv_biinv_isequiv `(f : A -> B)\n  : BiInv f <~> IsEquiv f.\nProof.\n  apply equiv_iff_hprop.\n  - by apply isequiv_biinv.\n  - intros ?.  split.\n    + by exists (f^-1); apply eissect.\n    + by exists (f^-1); apply eisretr.\nDefined.\n\n(** ** n-Path-split maps.\n\nA map is n-path-split if its induced maps on the first n iterated path-spaces are split surjections.  Thus every map is 0-path-split, the 1-path-split maps are the split surjections, and so on.  It turns out that for n>1, being n-path-split is the same as being an equivalence. *)\n\nFixpoint PathSplit (n : nat) `(f : A -> B) : Type\n  := match n with\n       | 0 => Unit\n       | S n => (forall a, hfiber f a) *\n                forall (x y : A), PathSplit n (@ap _ _ f x y)\n     end.\n\nDefinition isequiv_pathsplit (n : nat) `{f : A -> B}\n: PathSplit n.+2 f -> IsEquiv f.\nProof.\n  intros [g k].\n  pose (h := fun x y p => (fst (k x y) p).1).\n  pose (hs := fun x y => (fun p => (fst (k x y) p).2)\n                         : Sect (h x y) (ap f)).\n  clearbody hs; clearbody h; clear k.\n  apply isequiv_fcontr; intros b.\n  apply contr_inhabited_hprop.\n  2:exact (g b).\n  apply hprop_allpath; intros [a p] [a' p'].\n  refine (path_sigma' _ (h a a' (p @ p'^)) _).\n  refine (transport_paths_Fl _ _ @ _).\n  refine ((inverse2 (hs a a' (p @ p'^)) @@ 1) @ _).\n  refine ((inv_pp p p'^ @@ 1) @ _).\n  refine (concat_pp_p _ _ _ @ _).\n  refine ((1 @@ concat_Vp _) @ _).\n  exact ((inv_V p' @@ 1) @ concat_p1 _).\nDefined.\n\nGlobal Instance contr_pathsplit_isequiv\n           (n : nat) `(f : A -> B) `{IsEquiv _ _ f}\n: Contr (PathSplit n f).\nProof.\n  generalize dependent B; revert A.\n  simple_induction n n IHn; intros A B f ?.\n  - exact _.\n  - refine contr_prod.\n    refine contr_forall.\n    intros; apply fcontr_isequiv; exact _.\nDefined.\n\nGlobal Instance ishprop_pathsplit (n : nat) `(f : A -> B)\n: IsHProp (PathSplit n.+2 f).\nProof.\n  apply hprop_inhabited_contr; intros ps.\n  pose (isequiv_pathsplit n ps).\n  exact _.\nDefined.\n\nDefinition equiv_pathsplit_isequiv (n : nat) `(f : A -> B)\n: PathSplit n.+2 f <~> IsEquiv f.\nProof.\n  refine (equiv_iff_hprop _ _).\n  - apply isequiv_pathsplit.\n  - intros ?; refine (center _).\nDefined.\n\n(** Path-splitness transfers across commutative squares of equivalences. *)\nLemma equiv_functor_pathsplit (n : nat) {A B C D}\n      (f : A -> B) (g : C -> D) (h : A <~> C) (k : B <~> D)\n      (p : g o h == k o f)\n: PathSplit n f <~> PathSplit n g.\nProof.\n  destruct n as [|n].\n  1:apply equiv_idmap.\n  destruct n as [|n].\n  - simpl.\n    refine (_ *E equiv_contr_contr).\n    refine (equiv_functor_forall' k^-1 _); intros d.\n    unfold hfiber.\n    refine (equiv_functor_sigma' h _); intros a.\n    refine (equiv_concat_l (p a) d oE _).\n    simpl; apply equiv_moveR_equiv_M.\n  - refine (_ oE equiv_pathsplit_isequiv n f).\n    refine ((equiv_pathsplit_isequiv n g)^-1 oE _).\n    apply equiv_iff_hprop; intros e.\n    + refine (isequiv_commsq f g h k (fun a => (p a)^)).\n    + refine (isequiv_commsq' f g h k p).\nDefined.\n\n(** A map is oo-path-split if it is n-path-split for all n.  This is also equivalent to being an equivalence. *)\n\nDefinition ooPathSplit `(f : A -> B) : Type\n  := forall n, PathSplit n f.\n\nDefinition isequiv_oopathsplit `{f : A -> B}\n: ooPathSplit f -> IsEquiv f\n  := fun ps => isequiv_pathsplit 0 (ps 2).\n\nGlobal Instance contr_oopathsplit_isequiv\n           `(f : A -> B) `{IsEquiv _ _ f}\n: Contr (ooPathSplit f).\nProof.\n  apply contr_forall.\nDefined.\n\nGlobal Instance ishprop_oopathsplit `(f : A -> B)\n: IsHProp (ooPathSplit f).\nProof.\n  apply hprop_inhabited_contr; intros ps.\n  pose (isequiv_oopathsplit ps).\n  exact _.\nDefined.\n\nDefinition equiv_oopathsplit_isequiv `(f : A -> B)\n: ooPathSplit f <~> IsEquiv f.\nProof.\n  refine (equiv_iff_hprop _ _).\n  - apply isequiv_oopathsplit.\n  - intros ?; refine (center _).\nDefined.\n\nEnd AssumeFunext.\n\n(** ** Relational equivalences *)\n(** This definition is due to Peter LeFanu Lumsdaine on the HoTT mailing list.  This definition gives more judgmental properties, though has the downside of jumping universe levels. *)\nSection relational.\n  Record RelEquiv A B :=\n    { equiv_rel : A -> B -> Type;\n      relequiv_contr_f : forall a, Contr { b : B & equiv_rel a b };\n      relequiv_contr_g : forall b, Contr { a : A & equiv_rel a b } }.\n\n  Arguments equiv_rel {A B} _ _ _.\n  Global Existing Instance relequiv_contr_f.\n  Global Existing Instance relequiv_contr_g.\n\n  Definition issig_relequiv {A B}\n  : { equiv_rel : A -> B -> Type\n    | { f : forall a, Contr { b : B & equiv_rel a b }\n      | forall b, Contr { a : A & equiv_rel a b } } }\n      <~> RelEquiv A B.\n  Proof.\n    issig.\n  Defined.\n\n  Definition relequiv_of_equiv {A B} (e : A <~> B) : RelEquiv A B.\n  Proof.\n    refine {| equiv_rel a b := e a = b |}.\n    { intro b.\n      exists (e^-1 b; eisretr e b).\n      intros [a H].\n      destruct H.\n      simple refine (path_sigma _ _ _ _ _).\n      { simpl; apply eissect. }\n      { simpl.\n        abstract (rewrite eisadj; destruct (eissect e a); reflexivity). } }\n  Defined.\n\n  Definition equiv_of_relequiv {A B} (e : RelEquiv A B) : A <~> B.\n  Proof.\n    refine (equiv_adjointify\n              (fun a => (center { b : B & equiv_rel e a b}).1)\n              (fun b => (center { a : A & equiv_rel e a b}).1)\n              _ _);\n    intro x; cbn.\n    { refine (ap pr1 (contr _) : _.1 = (x; _).1).\n      exact (center {a : A & equiv_rel e a x}).2. }\n    { refine (ap pr1 (contr _) : _.1 = (x; _).1).\n      exact (center {b : B & equiv_rel e x b}).2. }\n  Defined.\n\n  Definition RelIsEquiv {A B} (f : A -> B)\n    := { r : RelEquiv A B | forall x, (center { b : B & equiv_rel r x b }).1 = f x }.\n\n  (** TODO: Prove [ishprop_relisequiv `{Funext} {A B} f : IsHProp (@RelIsEquiv A B f)] *)\n\n  (** * Judgmental property *)\n  Definition inverse_relequiv {A B} (e : RelEquiv A B) : RelEquiv B A\n    := {| equiv_rel a b := equiv_rel e b a |}.\n\n  Definition reinv_V {A B} (e : RelEquiv A B)\n  : inverse_relequiv (inverse_relequiv e) = e\n    := 1.\n\n  (** TODO: Is there a definition of this that makes [inverse_relequiv (relequiv_idmap A)] be [relequiv_idmap A], judgmentally? *)\n  Definition relequiv_idmap A : RelEquiv A A\n    := {| equiv_rel a b := a = b |}.\n\n  (** TODO: Define composition; we probably need truncation to do this? *)\nEnd relational.\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/EquivalenceVarieties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.6945395959100712}}
{"text": "(** vectors and various lemmas *)\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* vec {A} B l is a B-list of the same size as l *)\nInductive vec {A : Type} (B : Type) : list A -> Type :=\n    NilV : vec B nil\n  | ConsV : forall a lA, B -> vec B lA -> vec B (a :: lA).\n\nArguments NilV {A}{B}.\n\nDefinition vec_hd {A B}(a : A)(l : list A)(v : vec B (a :: l)) : B :=\n  match v with ConsV _ b _ => b end.\nDefinition vec_tl {A B}(a : A)(l : list A)(v : vec B (a :: l)) : vec B l :=\n  match v with ConsV _ _ v => v end.\n\n  \nDeclare Scope vec_scope.\nDelimit Scope vec_scope with v.\n\nInfix \"::\" := (ConsV _) (only parsing) : vec_scope.\n\nDefinition vec_map {A B C : Type}(f : A -> B -> C) :=\n  fix rec (l : list A) (v : vec B l) : vec C l :=\n  match v with\n    NilV => NilV\n  | ConsV a b lB => ConsV a (f a b) (rec _ lB)\n    end.\n\nDefinition vec_hd_map  {A B C}(a : A)(l : list A)(f : A -> B -> C)\n                          (v : vec B (a :: l)) :\n                         vec_hd (vec_map f v) = f a (vec_hd v) :=\n  match v with ConsV _ b v' => eq_refl _ end.\n\nDefinition vec_tl_map  {A B C}(a : A)(l : list A)(f : A -> B -> C)\n                          (v : vec B (a :: l)) :\n                         vec_tl (vec_map f v) = vec_map f (vec_tl v) :=\n  match v with ConsV _ b v' => eq_refl _ end.\n\nFixpoint vec_map_id {A B : Type}{l : list A}(v : vec B l) : vec_map (fun _ x => x) v = v.\n  destruct v.\n  -  reflexivity.\n  -  cbn.\n     f_equal.\n     apply vec_map_id.\nDefined.\n\nLemma vec_map_map {A B C D : Type}(f : A -> B -> C) (g : A -> C -> D) {l : list A}\n      (v : vec B l) : vec_map g (vec_map f v) = vec_map (fun a b => g a (f a b)) v.\n  induction v; cbn; congruence.\nQed.\n\nDefinition vec_map_ext {A B C : Type}(f g : A -> B -> C) {l : list A}\n      (v : vec B l) (h : forall a b, f a b = g a b): vec_map f v = vec_map g v.\n  induction v; cbn; congruence.\nDefined.\n\nFixpoint vec_max {A : Type}(l : list A) (v : vec nat l) : nat :=\n  match v with\n    NilV => 0\n  | ConsV a b lB => Nat.max b (vec_max lB)\n    end.\n\nLemma commutes_if {A B : Type}(f : A -> B)(b : bool) x y :\n  (if b then f x else f y) = f (if b then x else y).\nProof.\ndestruct b; reflexivity.\nQed.\nLemma if_if {A : Type}(b : bool) (x y z : A) :\n  (if b then if b then x else y else z) = (if b then x else z).\n  destruct b ; reflexivity.\nQed.\n", "meta": {"author": "amblafont", "repo": "binding-debruijn", "sha": "3913051e53ec44821e92dd02f35f89c6af559dfc", "save_path": "github-repos/coq/amblafont-binding-debruijn", "path": "github-repos/coq/amblafont-binding-debruijn/binding-debruijn-3913051e53ec44821e92dd02f35f89c6af559dfc/Lib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245911726381, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.6944298846013985}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nTheorem append_nil: forall (l: lst), append l Nil = l.\nProof.\n   induction l.\n   { simpl. f_equal. assumption. }\n   { simpl. reflexivity. }\nQed.\n\nTheorem append_assoc:\n   forall (l1 l2 l3: lst), append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\n   induction l1; induction l2; induction l3; try (simpl; reflexivity).\n   { simpl. rewrite <- IHl1. f_equal. }\n   { simpl. rewrite 2 append_nil. reflexivity. }\n   { simpl. rewrite append_nil.  reflexivity. }\n   { simpl. lfind.  reflexivity.  }\nAdmitted.\n\nTheorem append_rev_cons:\n   forall (l1 l2: lst) (x: natural),\n   rev (append l1 (Cons x l2)) = append (rev l2) (Cons x (rev l1)).\nProof.\n   induction l1; induction l2; try (simpl; reflexivity).\n   { intro. simpl. rewrite IHl1. simpl. rewrite <- append_assoc.\n   f_equal. }\n   { intro. simpl. rewrite IHl1. simpl. reflexivity. }\nQed.\n\nTheorem rev_append: forall (l1 l2: lst), rev (append l1 l2) = append (rev l2) (rev l1).\nProof.\n   induction l1.\n   { induction l2.\n   { simpl. rewrite append_rev_cons.\n      rewrite <- 2 append_assoc.\n      f_equal. }\n   { simpl. rewrite append_nil. reflexivity. }\n   }\n   { intro. simpl. rewrite append_nil. reflexivity. }\nQed.\n\nTheorem rev_involutive : forall (x : lst), eq (rev (rev x)) x.\nProof.\n   induction x.\n   { simpl. rewrite rev_append. simpl. f_equal.\n   assumption. }\n   { simpl. reflexivity. }\nQed.\n\nTheorem theorem0 : forall (x : lst), eq (rev (append (rev x) Nil)) x.\nProof.\n   intro.\n   rewrite append_nil.\n   apply rev_involutive.\nQed.\n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/clam_lf_goal30_append_assoc_37_append_nil/goal30.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.6944298673541414}}
{"text": "From ZornsLemma Require Export DirectedSets.\nFrom Topology Require Export TopologicalSpaces InteriorsClosures Continuity.\n\nSet Asymmetric Patterns.\n\nSection Net.\n\nVariable I:DirectedSet.\nVariable X:TopologicalSpace.\n\nDefinition Net := DS_set I -> X.\n\nDefinition net_limit (x:Net) (x0:X) : Prop :=\n  forall U:Ensemble 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:X) : Prop :=\n  forall U:Ensemble 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:X),\n  net_limit x x0 -> net_cluster_point x x0.\nProof.\nintros.\nred. intros.\nred. intros.\ndestruct (H U H0 H1).\ndestruct (DS_join_cond i x1).\ndestruct H3.\nexists x2.\nsplit; trivial.\nnow apply H2.\nQed.\n\nLemma net_limit_in_closure: forall (S:Ensemble X)\n  (x:Net) (x0: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.\nintro.\npose proof (H0 (Complement (closure S))).\nmatch type of H2 with | ?A -> ?B -> ?C => assert (C) end.\n{ apply H2; trivial.\n  apply closure_closed. }\ndestruct H3, (H x1).\ncontradiction (H3 x2);\n  [ | apply closure_inflationary ];\n  tauto.\nQed.\n\nLemma net_cluster_point_in_closure: forall (S:Ensemble X)\n  (x:Net) (x0: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.\nintro.\npose proof (H0 (Complement (closure S))).\nmatch type of H2 with | ?A -> ?B -> ?C => assert (C) end.\n{ apply H2; trivial.\n  apply closure_closed. }\ndestruct H, (H3 x1), H4.\ncontradiction H5.\napply closure_inflationary.\nnow apply H.\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:X.\n\nInductive neighborhood_net_DS_set : Type :=\n  | intro_neighborhood_net_DS :\n    forall (U:Ensemble X) (y: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 _ _).\n- constructor;\n    red; intros;\n    destruct x0.\n  + simpl. auto with sets.\n  + destruct y, z.\n    simpl in H, H0.\n    simpl.\n    auto with sets.\n- intros.\n  destruct i, j.\n  assert (open (Intersection U U0)) by\n    now apply open_intersection2.\n  assert (In (Intersection U U0) x) by\n    auto with sets.\n  exists (intro_neighborhood_net_DS (Intersection U U0) x\n    H H0 H0).\n  simpl.\n  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 X)\n  (x0: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 X, open U -> In U x0 ->\n  Inhabited (Intersection S U)).\n{ intros.\n  apply NNPP. intro.\n  assert (Included (closure S) (Complement U)).\n  { apply closure_minimal; red.\n    - now rewrite Complement_Complement.\n    - intros.\n      intro.\n      contradiction H2.\n      exists x.\n      auto with sets. }\n  contradict H1.\n  now apply H3. }\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).\n{ constructor; red.\n  - intros. red.\n    apply preord_refl.\n    apply (@DS_ord_cond (neighborhood_net_DS X x0)).\n  - intros x y z.\n    unfold our_DS_ord. apply preord_trans.\n    apply (@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).\n{ destruct i, x, j.\n  destruct x.\n  assert (open (Intersection U U0)) by\n    now apply open_intersection2.\n  assert (In (Intersection U U0) x0) by\n    auto with sets.\n  assert (Inhabited (Intersection S (Intersection U U0))) by\n    now apply H0.\n  destruct H4.\n  destruct H4.\n  pose (k0 := intro_neighborhood_net_DS X x0\n    (Intersection U U0) x H2 H3 H5).\n  assert (Ssel k0).\n  { red. now unfold k0. }\n  exists (exist _ k0 H6).\n  split; red; simpl; auto with sets. }\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.\n- intros.\n  now destruct i, x.\n- red. intros.\n  assert (Inhabited (Intersection S U)) by\n    now apply H0.\n  destruct H5.\n  destruct H5.\n  pose (i0 := intro_neighborhood_net_DS X x0\n    U x H3 H4 H6).\n  assert (Ssel i0) by trivial.\n  exists (exist _ i0 H7).\n  intros.\n  destruct j, x1.\n  simpl in H8.\n  red in H8. simpl in H8.\n  simpl.\n  auto with sets.\nQed.\n\nSection Nets_and_continuity.\n\nVariable X Y:TopologicalSpace.\nVariable f:X -> Y.\n\nLemma continuous_func_preserves_net_limits:\n  forall {I:DirectedSet} (x:Net I X) (x0: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)).\n{ apply open_neighborhood_is_neighborhood.\n  now split. }\ndestruct (H0 V H3) 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)) by auto with sets.\nnow destruct H9.\nQed.\n\nLemma func_preserving_net_limits_is_continuous:\n  forall x0: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.\nintros.\ndestruct H1, (H0 V H1 H2).\ndestruct x as [U].\nexists U.\nrepeat split; trivial.\napply (H3 (intro_neighborhood_net_DS X x0 U x o i H4)).\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: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.\ndestruct (H U H2 H3).\ndestruct (H1 x1).\ndestruct H5, H6.\nexists x3.\nintros.\napply H4.\napply preord_trans with x2; trivial.\n- apply DS_ord_cond.\n- rewrite <- H6.\n  now apply H0.\nQed.\n\nLemma subnet_cluster_point: forall (x0: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.\ndestruct (h_dominant i).\ndestruct H2, H3.\ndestruct (H U H0 H1 x2).\ndestruct H4.\nexists (h x3).\nsplit; trivial.\napply preord_trans with x1; trivial.\n- apply DS_ord_cond.\n- rewrite <- H3.\n  now apply h_increasing.\nQed.\n\nSection cluster_point_subnet.\n\nVariable x0: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 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  _ _).\n- constructor.\n  + red. intros.\n    split; auto with sets.\n    apply preord_refl.\n    apply DS_ord_cond.\n  + red. intros.\n    destruct H, H0.\n    red. split; auto with sets.\n    apply preord_trans with (cps_i y); trivial.\n    apply DS_ord_cond.\n- intros.\n  destruct i as [i0 U0 ? ?].\n  destruct j as [i1 U1 ? ?].\n  destruct (DS_join_cond i0 i1).\n  destruct H.\n  pose proof (x0_cluster_point\n    (Intersection U0 U1)).\n  match type of H1 with | _ -> _ -> ?C =>\n    assert C end.\n  { apply H1.\n    - apply open_intersection2;\n        (apply cps_U_open_neigh0 ||\n         apply cps_U_open_neigh1).\n    - constructor.\n      + apply cps_U_open_neigh0.\n      + apply cps_U_open_neigh1. }\n  destruct (H2 x1), H3.\n  pose (ki := x2).\n  pose (kU := Intersection U0 U1).\n  assert (open_neighborhood kU x0).\n  { split.\n    - apply open_intersection2.\n      + apply cps_U_open_neigh0.\n      + apply cps_U_open_neigh1.\n    - constructor.\n      + apply cps_U_open_neigh0.\n      + apply cps_U_open_neigh1. }\n  assert (In kU (x ki)) by trivial.\n  exists (Build_cluster_point_subnet_DS_set\n    ki kU H5 H6).\n  split; red; simpl; split.\n  + apply preord_trans with x1; trivial.\n    apply DS_ord_cond.\n  + red. intros.\n    now destruct H7.\n  + apply preord_trans with x1; trivial.\n    apply DS_ord_cond.\n  + red. intros.\n    now destruct H7.\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.\n- intros.\n  destruct j1, j2.\n  simpl in H. simpl.\n  red in H. tauto.\n- red. intros.\n  exists i. split.\n  + apply preord_refl, DS_ord_cond.\n  + assert (open_neighborhood Full_set x0).\n    { repeat constructor.\n      apply open_full. }\n    assert (In Full_set (x i)) by\n      constructor.\n    now exists (Build_cluster_point_subnet_DS_set\n      i Full_set H H0).\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) by\n  now split.\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.\n- exact cluster_point_subnet_is_subnet.\n- exact cluster_point_subnet_converges.\nQed.\n\nEnd cluster_point_subnet.\n\nEnd Subnet.\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/Nets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6944231823359546}}
{"text": "Check not.\n\n(* overriding existing definition *)\nDefinition not (b:bool) :=\n  match b with\n    | true  =>  false\n    | false =>  true\n  end.\n\nCheck not.\n\n(* cannot override again in same file for some reason *)\nDefinition not' (b:bool) := if b then false else true.\n\nLemma not_same : forall b:bool, not b = not' b.\nProof.\n  intro b. elim b.\n    clear b. simpl. reflexivity.\n    clear b. simpl. reflexivity.\nQed.\n\n\nDefinition func1 := \n  fun (x:nat) (H:{x=0}+{x<>0}) =>\n    match H with\n      | left  _ => true\n      | right _ => false\n    end.\n \nCheck func1.\n\nDefinition func2 :=\n  fun (x:nat) (H:{x=0}+{x<>0}) =>\n    if H then true else false.\n\nCheck func2.\n\nLemma func_same: forall x:nat, forall H:{x=0}+{x<>0},\n  func1 x H = func2 x H.\nProof.\n  intros x H. elim H.\n    clear H. intro H. simpl. reflexivity.\n    clear H. intro H. simpl. reflexivity.\nQed.\n\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/not.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.694406348829459}}
{"text": "Require Import prosa.classic.util.tactics.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype.\n\n(* Lemmas about the exists for Ordinals: [exists x, P x]. *)\nSection OrdExists.\n\n  Lemma exists_ord0:\n    forall P,\n      [exists x in 'I_0, P x] = false.\n  Proof.\n    intros P.\n    apply negbTE; rewrite negb_exists; apply/forall_inP.\n    intros x; destruct x as [x LT].\n    by exfalso; rewrite ltn0 in LT.\n  Qed.\n\n  Lemma exists_recr:\n    forall n P,\n      [exists x in 'I_n.+1, P x] =\n      [exists x in 'I_n, P (widen_ord (leqnSn n) x)] || P (ord_max).\n  Proof.\n    intros n P.\n    apply/idP/idP.\n    {\n      move => /exists_inP EX; destruct EX as [x IN Px].\n      destruct x as [x LT].\n      remember LT as LT'; clear HeqLT'. \n      rewrite ltnS leq_eqVlt in LT; move: LT => /orP [/eqP EQ | LT].\n      {\n        apply/orP; right.\n        unfold ord_max; subst x.\n        apply eq_trans with (y := P (Ordinal LT')); last by done.\n        by f_equal; apply ord_inj.\n      }\n      {\n        apply/orP; left.\n        apply/exists_inP; exists (Ordinal LT); first by done.\n        apply eq_trans with (y := P (Ordinal LT')); last by done.\n        by f_equal; apply ord_inj.\n      }\n    }\n    {\n      intro OR; apply/exists_inP.\n      move: OR => /orP [/exists_inP EX | MAX].\n      {\n        by destruct EX as [x IN Px]; exists (widen_ord (leqnSn n) x).\n      }\n      by exists ord_max.\n    }\n  Qed.\n\nEnd OrdExists.\n\n(* Lemmas about the forall for Ordinals: [exists x, P x]. *)\nSection OrdForall.\n\n  Lemma forall_ord0:\n    forall P,\n      [forall x in 'I_0, P x].\n  Proof.\n    intros P; apply/forall_inP.\n    by intros x IN0; destruct x.\n  Qed.\n\n  Lemma forall_recr:\n    forall n P,\n      [forall x in 'I_n.+1, P x] =\n      [forall x in 'I_n, P (widen_ord (leqnSn n) x)] && P (ord_max).\n  Proof.\n    intros n P.\n    apply/idP/idP.\n    {\n      move => /forall_inP ALL.\n      apply/andP; split; last by apply ALL.\n      by apply/forall_inP; intros x IN; apply ALL.\n    }\n    {\n      move => /andP [/forall_inP ALL MAX].\n      apply/forall_inP; intros x IN.\n      destruct x as [x LT].\n      unfold ord_max in *.\n      remember LT as LT'; clear HeqLT'.\n      rewrite ltnS leq_eqVlt in LT; move: LT => /orP [/eqP EQ | LT].\n      {\n        subst n.\n        apply/eqP; rewrite -MAX; apply/eqP.\n        by unfold ord_max; apply f_equal, ord_inj.\n      }\n      {\n        feed (ALL (Ordinal LT)); first by done.\n        apply/eqP; rewrite -ALL; apply/eqP.\n        by apply f_equal, ord_inj.\n      }\n    }\n  Qed.\n\nEnd OrdForall.\n\n(* Tactics for simplifying exists and forall. *)\nLtac simpl_exists_ord := rewrite !exists_recr !exists_ord0 /=.\nLtac simpl_forall_ord := rewrite !forall_recr !forall_ord0 /=.", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/classic/util/ord_quantifier.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.6944063488294588}}
{"text": "(* ***************************************************************** *)\n(*                                                                   *)\n(* Released: 2020/03/26.                                             *)\n(* Due: 2020/03/30, 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 (Assignment3.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 \"Assignment3.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 PL.Imp.\nRequire Import PL.ImpExt1.\nRequire Import PL.ImpExt2.\nRequire Import Coq.micromega.Psatz.\n\n(* ################################################################# *)\n(** * Task 1: Hoare Logic Based Verification *)\n\nModule Task1.\nImport Assertion_S.\nImport Assertion_S_Tac.\nImport Assertion_S_Rules.\nImport Concrete_Pretty_Printing.\nImport Axiomatic_semantics.\nImport derived_rules.\n\nModule Task1_1.\nImport Axiomatic_semantics.\nImport derived_rules.\n\n(** **** Exercise: 3 stars, standard (tri_correct)  *)\n\n(** The following program try to find the smallest number [N] such\nthat [1 + 2 + 3 + .. + N > X].\n\n    S ::= 0;;\n    N ::= 0;;\n    While S <= X Do\n      N ::= N + 1;;\n      S ::= S + N\n    EndWhile.\n\nRemember, you can always add auxiliary lemmas before start proving\nthe main theorem in every subtasks. But of course, these lemmas needs\nto be proved. *)\n\nLocal Instance X: var := new_var().\nLocal Instance S: var := new_var().\nLocal Instance N: var := new_var().\n\nLemma enter_loop: \n0 <= {[X]} AND {[S]} = 0 AND {[N]} = 0 \n|-- 2 * {[S]} = {[N]} * ({[N]} + 1) AND {[N]} * ({[N]} - 1) <= 2 * {[X]}.\nProof.\n  entailer.\n  intros.\n  lia.\nQed.\n\nLemma after_loop:\n2 * {[S]} = {[N]} * ({[N]} + 1) AND {[N]} * ({[N]} - 1) <= 2 * {[X]}\nAND NOT {[S <= X]}\n|-- {[N]} * ({[N]} - 1) <= 2 * {[X]} AND 2 * {[X]} < {[N]} * ({[N]} + 1).\nProof.\n  entailer.\n  intros.\n  lia.\nQed.\n\nLemma loop_body:\n  EXISTS x,\n  2 * {[S]} = x * (x + 1) AND x * (x - 1) <= 2 * {[X]} AND {[S]} <= {[X]}\n  AND {[N]} = x + 1 \n|--   2 * {[S]} = ({[N]} - 1) * {[N]} \n AND ({[N]} - 1) * ({[N]} - 2) <= 2 * {[X]} AND {[S]} <= {[X]} .\nProof.\n  entailer.\n  intros.\n  destruct H as [k H].\n  lia.\nQed.\n\nLemma exit_loop:\nEXISTS x,\n(2 * {[S]} = ({[N]} - 1) * {[N]} AND ({[N]} - 1) * ({[N]} - 2) <= 2 * {[X]}\n AND {[S]} <= {[X]}) [S |-> x] AND {[S]} = {[(S + N) [S |-> x]]}\n|-- 2 * {[S]} = {[N]} * ({[N]} + 1) AND {[N]} * ({[N]} - 1) <= 2 * {[X]}.\nProof.\n  entailer.\n  intros.\n  destruct H as [k H].\n  lia.\nQed.\n\nFact tri_correct:\n  {{ 0 <= {[X]} }}\n    S ::= 0;;\n    N ::= 0;;\n    While S <= X Do\n      N ::= N + 1;;\n      S ::= S + N\n    EndWhile\n  {{ {[N * (N-1)]} <= 2 * {[X]} AND\n     2 * {[X]} < {[N * (N + 1)]} }}.\nProof.\n  apply hoare_asgn_seq.\n  apply hoare_asgn_seq.\n  assert_simpl.\n  eapply hoare_consequence;\n  [ apply enter_loop |\n  | apply after_loop].\n  apply hoare_while.\n  apply hoare_asgn_seq.\n  assert_subst. assert_simpl.\n  eapply hoare_consequence;\n  [ apply loop_body\n  | apply hoare_asgn_fwd\n  | apply exit_loop].\nQed.\n\n(** [] *)\n\nEnd Task1_1.\n\nModule Task1_2.\nImport Axiomatic_semantics.\nImport derived_rules.\n\n(** **** Exercise: 3 stars, standard (sqrt_correct)  *)\n\n(** The following program computes the integer part of [X]'s square\nroot.\n\n    I ::= 0;;\n    While (I+1)*(I+1) <= X Do\n      I ::= I+1\n    EndWhile.\n\nYour task is to prove its correctness. *)\n\nLocal Instance X: var := new_var().\nLocal Instance I: var := new_var().\n\nLemma into_loop: forall m:Z,\n0 <= {[X]} AND {[X]} = m AND {[I]} = 0\n|-- 0 <= {[X]} AND {[X]} = m AND  {[I]} * {[I]} <= m.\nProof.\n  intros.\n  entailer.\n  intros.\n  lia.\nQed.\n\nLemma after_loop: forall m:Z,\n0 <= {[X]} AND {[X]} = m AND {[I]} * {[I]} <= m AND NOT {[(I + 1) * (I + 1) <= X]}\n|-- {[I]} * {[I]} <= m AND m < ({[I]} + 1) * ({[I]} + 1).\nProof.\n  intros.\n  entailer.\n  intros. \n  lia.\nQed.\n\nLemma loop_body: forall m:Z,\nEXISTS x,\n(0 <= {[X]} AND {[X]} = m AND {[I]} * {[I]} <= m AND {[(I + 1) * (I + 1) <= X]})\n[I |-> x] AND {[I]} = {[(I + 1) [I |-> x]]}\n|-- 0 <= {[X]} AND {[X]} = m AND {[I]} * {[I]} <= m.\nProof.\n  intros.\n  entailer.\n  intros.\n  destruct H as [k H].\n  lia.\nQed.\n\nFact sqrt_correct: forall m: Z,\n  {{ 0 <= {[X]} AND {[X]} = m }}\n    I ::= 0;;\n    While (I+1)*(I+1) <= X Do\n      I ::= I+1\n    EndWhile\n  {{ {[I]} * {[I]} <= m AND m < ({[I]} + 1) * ({[I]} + 1) }}.\nProof.\n  intros.\n  apply hoare_asgn_seq.\n  assert_simpl.\n  eapply hoare_consequence;\n  [ apply into_loop |\n  | apply after_loop].\n  apply hoare_while.\n  eapply hoare_consequence_post;\n  [ apply hoare_asgn_fwd\n  | apply loop_body].\nQed.\n\n(** [] *)\n\nEnd Task1_2.\n\nEnd Task1.\n\n(* ################################################################# *)\n(** * Task 2: Understanding Denotations *)\n\n(** In this task, you will read descriptions about program states and decide\n    whether the following pairs of programs states belong to corresponding\n    programs' denotations. *)\n\n(** **** Exercise: 1 star, standard  *)\nModule Task2_1.\n\n(** Suppose [X] and [Y] are different program variables. If [st X = 1] and\n    [st Y = 2], then does (st, st) belong to the following program's denotation?\n\n    Y ::= X + 1\n\n    1: Yes. 2: No. *)\n\nDefinition my_choice: Z := 1.\n\nEnd Task2_1.\n(** [] *)\n\n(** **** Exercise: 1 star, standard  *)\nModule Task2_2.\n\n(** Suppose [X] is a program variables. If [st1 X = 100], [st2 X = 1] and all\n    other variables in [st1] and [st2] are zero, then does (st1, st2) belong to\n    the following program's denotation?\n\n    While 1 <= X Do X ::= X + 1 EndWhile\n\n    1: Yes. 2: No. *)\n\nDefinition my_choice: Z := 2.\n\nEnd Task2_2.\n(** [] *)\n\n(** **** Exercise: 1 star, standard  *)\nModule Task2_3.\n\n(** Suppose [X] and [Y] are different program variables. If [st1 X = 1],\n    [st1 Y = 2], [st2 X = 2], [st2 Y = 1] and all other variables in [st1] and\n    [st2] are zero, then does (st1, st2) belong to the following program's\n    denotation?\n\n    Z ::= X;; X ::= Y;; Y ::= Z\n\n    1: Yes. 2: No. *)\n\nDefinition my_choice: Z := 2.\n\nEnd Task2_3.\n(** [] *)\n\n(* ################################################################# *)\n(** * Task 3: Reasoning About Recursions *)\n\n(** Here is a recursive function about integer expressions. Try to understand\n    what it tries to do and prove related properties. *)\n\nFixpoint aexp_reverse (a: aexp): aexp :=\n  match a with\n  | ANum n => ANum n\n  | AId X => AId X\n  | APlus a1 a2 => APlus (aexp_reverse a2) (aexp_reverse a1)\n  | AMinus a1 a2  => AMinus (aexp_reverse a1) (aexp_reverse a2)\n  | AMult a1 a2 => AMult (aexp_reverse a2) (aexp_reverse a1)\n  end.\n\n(** **** Exercise: 2 stars, standard (reverse_equiv)  *)\nLemma reverse_equiv: forall a st, aeval (aexp_reverse a) st = aeval a st.\nProof.\n  intros.\n  induction a;simpl.\n  - reflexivity.\n  - reflexivity.\n  - unfold Func.add.\n    rewrite IHa1, IHa2.\n    lia.\n  - unfold Func.sub.\n    rewrite IHa1, IHa2.\n    lia.\n  - unfold Func.mul.\n    rewrite IHa1, IHa2.\n    lia.\nQed.\n\n(** **** Exercise: 2 stars, standard (reversed_reverse)  *)\nLemma reversed_reverse: forall a1 a2,\n  aexp_reverse a1 = a2 ->\n  a1 = aexp_reverse a2.  \nProof.\n  intros.\n  rewrite <- H. clear H.\n  induction a1; simpl; try reflexivity.\n  - rewrite IHa1_1, IHa1_2 at 1.\n    reflexivity.\n  - rewrite IHa1_1, IHa1_2 at 1.\n    reflexivity.\n  - rewrite IHa1_1, IHa1_2 at 1.\n    reflexivity.\nQed.\n\n\n(** You may wonder whether [aexp_reverse] is a meaningful operation. Well, it\n    might be. Try to answer the following questions about it. *)\n\n(** **** Exercise: 1 star, standard  *)\nModule Task3_3.\n\n(** In comparison, which one of the following is the better optimazation?\n\n    - do [fold_constants] directly;\n\n    - do [fold_constants] after [aexp_reverse].\n\n    Choose one correct statement:\n\n    0. They always generate results with the same length.\n\n    1. The first one always generates shorter (or equivalent) result and\n       statement 0 is wrong.\n\n    2. The second one always generates shorter (or equivalent) result and\n       statement 0 is wrong.\n\n    3. They are not comparable. *)\n\nDefinition my_choice: Z := 3.\n\nEnd Task3_3.\n(** [] *)\n\n(** **** Exercise: 1 star, standard  *)\nModule Task3_4.\n\n(** In comparison, which one of the following is the better optimazation?\n\n    - do [fold_constants] directly;\n\n    - do [fold_constants], then [aexp_reverse], and [fold_constants] again\n      in the end\n\n    Choose one correct statement:\n\n    0. They always generate results with the same length.\n\n    1. The first one always generates shorter (or equivalent) result and\n       statement 0 is wrong.\n\n    2. The second one always generates shorter (or equivalent) result and\n       statement 0 is wrong.\n\n    3. They are not comparable. *)\n\nDefinition my_choice: Z := 2.\n\nEnd Task3_4.\n(** [] *)\n\n(* ################################################################# *)\n(** * Task 4: Understanding Higher-Order Functions *)\n\n(** Suppose [f] and [g] are both functions from [A] to [A]. How shall we define\n    the function that applies [f] first and then applies [g]? *)\n\n(** **** Exercise: 2 stars, standard (compose)  *)\n\nDefinition compose {A: Type} (f g: A -> A): A -> A :=\n  fun x => g (f x).\n\n(** It is obvious that [ compose f (compose g h) ] is equivalent with\n    [ compose (compose f g) h ]. Your task is to prove it in Coq. *)\n\nTheorem compose_assoc: forall f g h: Z -> Z,\n  Func.equiv (compose f (compose g h)) (compose (compose f g) h).\nProof.\n  intros.\n  unfold Func.equiv.\n  intros.\n  unfold compose.\n  reflexivity.\nQed.\n\n(** [] *)\n\n\n(* Thu Mar 26 09:44:52 CST 2020 *)\n", "meta": {"author": "ltzone", "repo": "2020Spring", "sha": "bc7fdf60850c81d77825cdcc77a1ad265da98f11", "save_path": "github-repos/coq/ltzone-2020Spring", "path": "github-repos/coq/ltzone-2020Spring/2020Spring-bc7fdf60850c81d77825cdcc77a1ad265da98f11/CS263/Assignment3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.6944063351659253}}
{"text": "Require Import Coq.Lists.List.\n\nSection ListLexOrder.\n  Variable T : Type.\n  Variable cmp : T -> T -> comparison.\n\n  Fixpoint list_lex_cmp (ls rs : list T) : comparison :=\n    match ls , rs with\n      | nil , nil => Eq\n      | nil , _ => Lt\n      | _ , nil => Gt\n      | l :: ls , r :: rs =>\n        match cmp l r with\n          | Eq => list_lex_cmp ls rs\n          | x => x\n        end\n    end.\nEnd ListLexOrder.\n\nSection Sorting.\n  Variable T : Type.\n  Variable cmp : T -> T -> comparison.\n\n  Section insert.\n    Variable val : T.\n\n    Fixpoint insert_in_order (ls : list T) : list T :=\n      match ls with\n        | nil => val :: nil\n        | l :: ls' =>\n          match cmp val l with\n            | Gt => l :: insert_in_order ls'\n            | _ => val :: ls\n          end\n      end.\n  End insert.\n\n  Fixpoint sort (ls : list T) : list T :=\n    match ls with\n      | nil => nil\n      | l :: ls =>\n        insert_in_order l (sort ls)\n    end.\n\nEnd Sorting.\n\nLemma insert_in_order_inserts : forall T C x l,\n  exists h t, insert_in_order T C x l = h ++ x :: t /\\ l = h ++ t.\nProof.\n  clear. induction l; simpl; intros.\n  exists nil; exists nil; eauto.\n  destruct (C x a).\n  exists nil; simpl. eauto.\n  exists nil; simpl. eauto.\n  destruct IHl. destruct H. intuition. subst.\n  rewrite H0. exists (a :: x0). exists x1. simpl; eauto.\nQed.\n\nRequire Import Coq.Sorting.Permutation.\n\nLemma sort_permutation : forall T (C : T -> T -> _) x,\n  Permutation (sort _ C x) x.\nProof.\n  induction x; simpl.\n  { reflexivity. }\n  { destruct (insert_in_order_inserts T C a (sort T C x)) as [ ? [ ? ? ] ].\n    destruct H. rewrite H. rewrite <- Permutation_cons_app. reflexivity. rewrite H0 in *. symmetry; auto. }\nQed.\n", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/src/Ordering.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.6944063317163569}}
{"text": "Require Import String.\n\n(* Simply typed lambda calculus with pairs *)\n\nInductive STyp := \n  | STInt : STyp\n  | STFun : STyp -> STyp -> STyp\n  | STTuple : STyp -> STyp -> STyp.\n\nInductive SExp (A : Type) :=\n  | STVar   : A -> SExp A\n  | STLit   : nat -> SExp A\n  | STLam   : STyp -> (A -> SExp A) -> SExp A\n  | STApp   : SExp A -> SExp A -> SExp A\n  | STPair  : SExp A -> SExp A -> SExp A\n  | STProj1 : SExp A -> SExp A\n  | STProj2 : SExp A -> SExp A.\n\nFixpoint join A (e : SExp (SExp A)) : SExp A :=\n  match e with\n    | STVar x => x\n    | STLit n => STLit _ n\n    | STLam t f => STLam _ t (fun x => join _ (f (STVar _ x)))\n    | STApp e1 e2 => STApp _ (join _ e1) (join _ e2)\n    | STPair e1 e2 => STPair _ (join _ e1) (join _ e2)\n    | STProj1 e => STProj1 _ (join _ e)\n    | STProj2 e => STProj2 _ (join _ e)\n  end.\n\n(* STLC: Evaluation (incomplete rules, but sufficient?) *)\n\nInductive Ev : forall a, SExp (SExp a) -> SExp a -> Prop :=\n  | Beta : forall a t f e, Ev a (STApp _ (STLam _ t f) e) (join _ (f (join _ e))).\n\nDefinition Ev2 A (e : SExp (SExp A)) : option (SExp A) :=\n  match e with\n    | STApp (STLam t f) e => Some (join _ (f (join _ e))) (* beta *)\n    | e => Some (join _ e) (* wrong! *)\n  end.\n\nDefinition e1 A (p : SExp A) : SExp A := \n  STApp _ (STLam _ (STTuple STInt STInt) (fun pair => STPair _ (STProj1 _ (STVar _ pair)) (STProj2 _ (STVar _ pair)))) p.\n\nDefinition e2 A (p : SExp A) : SExp A := \n  STPair _ (STProj1 _ (STProj1 _ p)) (STProj2 _ (STProj1 _ p)).\n\nLemma equalExp : forall A (p : SExp (SExp A)), Ev2 _ (e1 _ p) = Ev2 _ (e2 _ p).\nProof.\nunfold e1. unfold e2. simpl. intros. \nadmit.\nDefined.\n\nDefinition Exp := forall A, SExp A.\n\n(* System I (no polymorphism yet) *)\n\nInductive PTyp : Type :=\n  | PInt : PTyp\n  | Fun : PTyp -> PTyp -> PTyp\n  | And : PTyp -> PTyp -> PTyp.\n\nFixpoint ptyp2styp (t : PTyp) : STyp :=\n  match t with\n    | PInt => STInt \n    | Fun t1 t2 => STFun (ptyp2styp t1) (ptyp2styp t2)\n    | And t1 t2 => STTuple (ptyp2styp t1) (ptyp2styp t2)\n  end.\n\nRequire Import Arith.\nRequire Import Setoid.\n\n(* Subtyping relation *)\n\nInductive Atomic : PTyp -> Prop :=\n  | AInt : Atomic PInt\n  | AFun : forall t1 t2, Atomic (Fun t1 t2).\n\nInductive sub : PTyp -> PTyp -> Exp -> Prop :=\n  | SInt : sub PInt PInt (fun A => STLam _ STInt (fun x => STVar _ x))\n  | SFun : forall o1 o2 o3 o4 c1 c2, sub o3 o1 c1 -> sub o2 o4 c2 -> \n     sub (Fun o1 o2) (Fun  o3 o4) (fun A => STLam _ (ptyp2styp (Fun o1 o2)) (fun f => \n       STLam _ (ptyp2styp o3) (fun x => STApp _ (c2 A) (STApp _ (STVar _ f) (STApp _ (c1 A) (STVar _ x))))))\n  | SAnd1 : forall t t1 t2 c1 c2, sub t t1 c1 -> sub t t2 c2 -> \n     sub t (And  t1 t2) (fun A => STLam _ (ptyp2styp t1) (fun x => \n       STPair _ (STApp _ (c1 A) (STVar _ x)) (STApp _ (c2 A) (STVar _ x))))\n  | SAnd2 : forall t t1 t2 c, sub t1 t c -> \n     sub (And  t1 t2) t (fun A => STLam _ (ptyp2styp (And t1 t2)) (fun x => \n       (STApp _ (c A) (STProj1 _ (STVar _ x)))))\n  | SAnd3 : forall t t1 t2 c, sub t2 t c -> \n     sub (And  t1 t2) t (fun A => STLam _ (ptyp2styp (And t1 t2)) (fun x => \n       (STApp _ (c A) (STProj2 _ (STVar _ x))))).\n\nDefinition Sub (t1 t2 : PTyp) : Prop := exists (e:Exp), sub t1 t2 e.\n\n(* Smart constructors for Sub *)\n\nDefinition sint : Sub PInt PInt.\nunfold Sub. exists (fun A => STLam _ STInt (fun x => STVar _ x)). \nexact SInt.\nDefined.\n\nDefinition sfun : forall o1 o2 o3 o4, Sub o3 o1 -> Sub o2 o4 -> Sub (Fun o1 o2) (Fun  o3 o4).\nunfold Sub; intros.\nadmit.\nDefined.\n\nDefinition sand1 : forall t t1 t2, Sub t t1 -> Sub t t2 -> Sub t (And t1 t2).\nadmit.\nDefined.\n\nDefinition sand2 : forall t t1 t2, Sub t1 t -> Sub (And  t1 t2) t.\nadmit.\nDefined.\n\nDefinition sand3 : forall t t1 t2, Sub t2 t -> Sub (And  t1 t2) t.\nadmit. \nDefined.\n\n(* Orthogonality: Implementation *)\n\nInductive Ortho : PTyp -> PTyp -> Prop :=\n  | OAnd1 : forall t1 t2 t3, Ortho t1 t3 -> Ortho t2 t3 -> Ortho (And t1 t2) t3\n  | OAnd2 : forall t1 t2 t3, Ortho t1 t2 -> Ortho t1 t3 -> Ortho t1 (And t2 t3)\n  | OFun  : forall t1 t2 t3 t4, Ortho t2 t4 -> Ortho (Fun t1 t2) (Fun t3 t4)\n  | OIntFun : forall t1 t2, Ortho PInt (Fun t1 t2)\n  | OFunInt : forall t1 t2, Ortho (Fun t1 t2) PInt.\n\n(*  | OLift : forall t1 t2, not (sub t1 t2) -> not (sub t2 t1) -> Atomic t1 -> Atomic t2 -> Ortho t1 t2. *)\n\n(* Orthogonality: Specification *)\n\nDefinition OrthoS (A B : PTyp) := not (exists C, Sub A C /\\ Sub B C).\n\n(* Well-formed types *)\n\nInductive WFTyp : PTyp -> Prop := \n  | WFInt : WFTyp PInt\n  | WFFun : forall t1 t2, WFTyp t1 -> WFTyp t2 -> WFTyp (Fun t1 t2)\n  | WFAnd : forall t1 t2, WFTyp t1 -> WFTyp t2 -> OrthoS t1 t2 -> WFTyp (And t1 t2).\n\n(* Reflexivity *)\nHint Resolve sint sfun sand1 sand2 sand3.\n\nLemma reflex : forall (t1 : PTyp), Sub t1 t1.\nProof.\n(*induction t1; auto. \nauto. apply sand1. inversion IHt1_1. induction H. apply sand2. auto. apply AInt. \napply sand2. auto. apply AFun.\napply sand1. admit. admit. apply sand2; auto. apply sand2; auto.  *)\ninduction t1; intros; auto.\nDefined.\n\n(* Orthogonality algorithm is complete *)\n\nLemma ortho_completness : forall (t1 t2 : PTyp), OrthoS t1 t2 -> Ortho t1 t2.\nProof.\ninduction t1; intros; unfold OrthoS in H.\n(* Case PInt *)\ninduction t2.\ndestruct H. exists PInt. split; apply reflex.\napply OIntFun.\napply OAnd2. \napply IHt2_1. unfold not. unfold not in H. intros; apply H.\ndestruct H0. destruct H0. \nexists x. split. exact H0. apply sand2. exact H1.\napply IHt2_2. unfold not. unfold not in H. intros. apply H.\ndestruct H0. destruct H0. exists x.\nsplit. auto. apply sand3.\nauto.\n(* Case Fun t1 t2 *)\ninduction t2.\napply OFunInt. \napply OFun.\napply IHt1_2. unfold OrthoS. unfold not. intros.\nunfold not in H. apply H.\ndestruct H0. destruct H0.\nexists (Fun (And t1_1 t2_1) x).\nsplit.\napply sfun.\napply sand2.\napply reflex.\nauto.\napply sfun.\napply sand3. apply reflex.\nauto.\n(* Case t11 -> t12 _|_ t21 & t22 *)\napply OAnd2.\napply IHt2_1.\nunfold not. unfold not in H. intros. apply H.\ndestruct H0. destruct H0.\nexists x. split. auto. apply sand2. exact H1.\napply IHt2_2.\nunfold not. unfold not in H. intros. apply H.\ndestruct H0. destruct H0.\nexists x. split. auto. apply sand3. exact H1.\n(* Case (t11 & t12) _|_ t2 *) \napply OAnd1.\napply IHt1_1.\nunfold OrthoS.\nunfold not. unfold not in H.\nintro.\napply H.\nclear H. destruct H0. destruct H.\nexists x.\nsplit.\napply sand2. exact H.\nexact H0.\napply IHt1_2.\nunfold OrthoS; unfold not; intro. unfold not in H.\napply H. clear H.\ndestruct H0.\ndestruct H.\nexists x.\nsplit.\napply sand3.\nexact H.\nexact H0.\nDefined.\n\nLemma nosub : forall t1 t2, OrthoS t1 t2 -> not (Sub t1 t2) /\\ not (Sub t2 t1).\nProof.\nintros; split; unfold not.\nunfold OrthoS in H. unfold not in H. intros.\napply H.\nexists t2.\nsplit. auto. apply reflex.\nunfold OrthoS in H. unfold not in H. intros.\napply H.\nexists t1. split. apply reflex. auto.\nDefined.\n\n\nLemma invAndS1 : forall t t1 t2, Sub t (And t1 t2) -> Sub t t1 /\\ Sub t t2.\nProof.\ninduction t; intros.\n(* Case Int *)\ninversion H. inversion H0. split; unfold Sub. exists c1. auto. exists c2. auto.\n(* Case Fun *)\ninversion H. inversion H0. split; unfold Sub. exists c1. auto. exists c2. auto.\n(* Case And *)\ninversion H. inversion H0. split; unfold Sub. exists c1. auto. exists c2. auto.\nassert (Sub t1 t0 /\\ Sub t1 t3).\napply IHt1.\nauto. unfold Sub. exists c. auto.\ndestruct H6.\nsplit.\napply sand2.\nauto.\napply sand2.\nauto.\nassert (Sub t2 t0 /\\ Sub t2 t3).\napply IHt2.\nunfold Sub. exists c. auto.\ndestruct H6.\nsplit.\napply sand3.\nauto.\napply sand3.\nauto.\nDefined.\n\nLemma uniquesub : forall A B C, \n  OrthoS A B -> Sub (And A B) C -> not (Sub A C /\\ Sub B C).\nProof.\nintros. unfold OrthoS in H. unfold not. intros. apply H. exists C. auto.\nDefined.\n\n(* Lemmas needed to prove soundness of the orthogonality algorithm *)\n\nLemma ortho_sym : forall A B, OrthoS A B -> OrthoS B A.\nProof.\nunfold OrthoS. unfold not.\nintros. apply H.\ndestruct H0. destruct H0.\nexists x.\nsplit; auto.\nDefined.\n\nLemma ortho_and : forall A B C, OrthoS A C -> OrthoS B C -> OrthoS (And A B) C.\nProof.\nintros. unfold OrthoS.\nunfold not. intros.\ndestruct H1. destruct H1.\ninduction x. \ninversion H1. inversion H3. unfold OrthoS in H. apply H. exists (PInt). split. \nunfold Sub. exists c. auto. unfold Sub.  unfold Sub in H2. destruct H2. exists x0. auto.\nunfold OrthoS in H0. apply H0. exists (PInt). split. \nunfold Sub. exists c. auto. unfold Sub.  unfold Sub in H2. destruct H2. exists x0. auto.\ninversion H1. inversion H3. unfold OrthoS in H. apply H. exists (Fun x1 x2). split. \nunfold Sub. exists c. auto. unfold Sub.  unfold Sub in H2. destruct H2. exists x0. auto.\nunfold OrthoS in H0. apply H0. exists (Fun x1 x2). split. \nunfold Sub. exists c. auto. unfold Sub.  unfold Sub in H2. destruct H2. exists x0. auto.\nassert (Sub C x1 /\\ Sub C x2). apply invAndS1. auto. destruct H3.\ninversion H1. inversion H5. apply IHx1. \nunfold Sub. exists c1. auto. unfold Sub.  unfold Sub in H3. destruct H3. exists x0. auto.\nunfold OrthoS in H. apply H. exists (And x1 x2). split. \nunfold Sub. exists c. auto. unfold Sub.  unfold Sub in H2. destruct H2. exists x0. auto.\nunfold OrthoS in H0. apply H0. exists (And x1 x2). split. \nunfold Sub. exists c. auto. unfold Sub.  unfold Sub in H2. destruct H2. exists x0. auto.\nDefined.\n\nLemma ortho_soundness : forall (t1 t2 : PTyp), Ortho t1 t2 -> OrthoS t1 t2.\nintros.\ninduction H.\n(* Hard case *)\nassert (OrthoS t1 t3). apply IHOrtho1; auto.\nassert (OrthoS t2 t3). apply IHOrtho2; auto.\napply ortho_and; auto.\nassert (OrthoS t2 t1). apply ortho_sym. apply IHOrtho1; auto.\nassert (OrthoS t3 t1). apply ortho_sym. apply IHOrtho2; auto.\napply ortho_sym.\napply ortho_and; auto.\n(* Case FunFun *)\nunfold OrthoS. unfold not. intros.\nunfold OrthoS in IHOrtho. apply IHOrtho.\ndestruct H0. destruct H0. generalize H0. generalize H1. clear H0. clear H1.\ninduction x; intros. inversion H1. inversion H2. exists x2.\nsplit. inversion H0. inversion H2. unfold Sub. exists c2. auto. unfold Sub. inversion H1. inversion H2. exists c2. auto.\napply IHx1.\ninversion H1. inversion H2. unfold Sub. exists c1. auto. \ninversion H0. inversion H2. exists c1. auto.\n(* Case IntFun *)\nunfold OrthoS. unfold not. intros.\ndestruct H. destruct H. induction x. inversion H0. inversion H1. inversion H. inversion H1.\napply IHx1.\ninversion H. inversion H1. unfold Sub. exists c1. auto.\ninversion H0. inversion H1. unfold Sub. exists c1. auto.\n(* Case FunInt *)\nunfold OrthoS. unfold not. intros.\ndestruct H. destruct H. induction x. inversion H. inversion H1. inversion H0. inversion H1.\napply IHx1. inversion H. inversion H1. unfold Sub. exists c1. auto.\ninversion H0. inversion H1. unfold Sub. exists c1. auto.\nDefined.\n\n(* coercive subtyping is coeherent *)\n\n\nLemma sub_coherent : forall A, WFTyp A -> forall B, WFTyp B -> forall C1, sub A B C1 -> forall C2, sub A B C2 -> C1 = C2.\nProof.\nintro. intro. intro. intro. intro. intro.\n(* Case: Int <: Int *)\ninduction H1; intros.\ninversion H1. \nreflexivity.\n(* Case: Fun t1 t2 <: Fun t3 t4 *)\ninversion H1; inversion H; inversion H0.\nassert (c2 = c3). apply IHsub2; auto.\nassert (c1 = c0). apply IHsub1; auto.\nrewrite H17. rewrite H18.\nreflexivity.\n(* Case: t <: And t1 t2 *) \ninversion H1; inversion H0.\nassert (c1 = c0). apply IHsub1; auto.\nassert (c2 = c3). apply IHsub2; auto.\nrewrite H13. rewrite H14.\nreflexivity.\n(* different coercion case*)\nrewrite <- H3 in H. inversion H.\nrewrite <- H3 in H1_. rewrite <- H3 in H1_0. rewrite <- H3 in H1.\nadmit.\n(* different coercion case*)\nadmit.\n(* Case: And t1 t2 <: t (first) *)\ninversion H2; inversion H.\n(* different coercion *)\nadmit.\n(* same coercion *)\nassert (c = c0). apply IHsub; auto. rewrite H13.\nreflexivity.\n(* contradiction: not orthogonal! *)\ndestruct H12. exists t. unfold Sub.\nsplit. exists c; auto. exists c0. auto.\n(* Case: And t1 t2 <: t (second) *)\ninversion H2; inversion H.\nadmit.\n(* contradiction: not orthogonal! *)\ndestruct H12. exists t. unfold Sub.\nsplit. exists c0; auto. exists c. auto.\n(* same coercion; no contradiction *)\nassert (c = c0). apply IHsub; auto. rewrite H13.\nreflexivity.\nDefined.\n\n\n(* Old theorems *)\n\nLemma invAndS1 : forall t t1 t2 i, sub i t (And nat t1 t2) -> sub i t t1 /\\ sub i t t2.\nProof.\n(*\ninduction t; intros; split; try (inversion H); auto.\n*)\ninduction t; intros.\n(* Case Var *)\ninversion H.\nsplit.\nexact H4.\nexact H5.\n(* Case Int *)\ninversion H.\nsplit.\nexact H4.\nexact H5.\n(* Case Forall *)\ninversion H0.\nsplit.\nexact H5.\nexact H6.\n(* Case Fun *)\ninversion H.\nsplit.\nexact H4.\nexact H5.\n(* Case And *)\ninversion H.\nsplit.\nexact H4.\nexact H5.\nassert (sub i t1 t0 /\\ sub i t1 t3).\napply IHt1.\nexact H4.\ndestruct H5.\nsplit.\napply SAnd2.\nexact H5.\napply SAnd2.\nexact H6.\nassert (sub i t2 t0 /\\ sub i t2 t3).\napply IHt2.\nexact H4.\ndestruct H5.\nsplit.\napply SAnd3.\nexact H5.\napply SAnd3.\nexact H6.\nDefined.\n\nDefinition transitivity_sub S Q T := forall i, sub i S Q -> sub i Q T -> sub i S T.\n\nLemma trans : forall Q T S, transitivity_sub S Q T.\ninduction Q.\nunfold transitivity_sub; intros.\ninduction T; try (inversion H0); auto.\nrewrite H4 in H. auto.\nunfold transitivity_sub; intros.\ninduction T; try (inversion H0); auto.\n(* Case Forall *)\nunfold transitivity_sub. intros.\ngeneralize H1 H0. clear H0. clear H1.\ngeneralize S. clear S.\ninduction T; intro; intro; try (inversion H1); auto.\ninduction S; intro; try (inversion H6); intros; auto.\napply SForall.\ninversion H7.\napply (H i); auto.\n(* Case Fun *)\nunfold transitivity_sub; intros.\ngeneralize H0 H. clear H0. clear H.\ngeneralize S. clear S.\ninduction T; intro; intro; try (inversion H0); auto.\ninduction S; intro; try (inversion H7); auto.\ninversion H8.\napply SFun.\napply IHQ1; auto.\napply IHQ2; auto.\n(* Case And *)\nunfold transitivity_sub; intros.\nassert (sub i S Q1 /\\ sub i S Q2).\napply invAndS1; auto.\ndestruct H1.\ngeneralize H1 H2.\ninduction T; intros.\ninversion H0.\napply IHQ1; auto.\napply IHQ2; auto.\ninversion H0.\napply IHQ1; auto.\napply IHQ2; auto.\ninversion H0.\napply IHQ1; auto.\napply IHQ2; auto.\ninversion H0.\napply IHQ1; auto.\napply IHQ2; auto.\ninversion H0.\napply SAnd1.\napply IHT1; auto.\napply IHT2; auto.\napply IHQ1; auto.\napply IHQ2; auto.\nDefined.\n\nDefinition Ortho A B := forall n, not (exists C, sub n A C /\\ sub n B C).\n\n\n\nLemma p1 : forall (A B C : Prop), (A \\/ B -> C) -> ((A -> C) /\\ (B -> C)).\nProof.\nintros.\nsplit; intros.\napply H.\nleft.\nexact H0.\napply H.\nright.\nexact H0.\nDefined.\n\nDefinition equiv i t1 t2 := sub i t1 t2 /\\ sub i t2 t1.\n\nDefinition contextEq i t1 t2 := (forall t, sub i t1 t -> sub i t2 t) /\\ (forall t, sub i t t1 -> sub i t t2).\n\nDefinition narrowing_sub P Q X S T := forall i, sub i P Q -> (sub i X Q -> sub i S T) -> sub i X P -> sub i S T.\n\nLemma narrowing : forall X P Q S T, transitivity_sub X P Q -> narrowing_sub P Q X S T.\nunfold narrowing_sub; intros.\napply H1.\napply H.\nexact H2.\nexact H0.\nDefined.\n\n\n\nDefinition substitutability :\n  forall t1 t2 i, equiv i t2 t1 -> contextEq i t2 t1 /\\ contextEq i t1 t2.\nintro. intro. intro. intro.\ndestruct H.\ninduction H; split; try split; intros.\n(* Case Int *)\nexact H.\nexact H.\nexact H.\nexact H.\n(* Case Var *)\nexact H.\nexact H.\nexact H.\nexact H.\n(* Case Forall *)\ninduction t; try (inversion H1).\napply SForall.\napply IHsub.\ninversion H0.\nexact H10.\nexact H6.\napply SAnd1.\napply IHt1.\napply H6.\napply IHt2.\napply H7.\ninduction t; try (inversion H1).\napply SForall.\napply IHsub.\ninversion H0.\nexact H10.\nexact H6.\napply SAnd2.\napply IHt1.\napply H6.\napply SAnd3.\napply IHt2.\napply H6.\ninduction t; try (inversion H1).\napply SForall.\napply IHsub.\ninversion H0.\nexact H10.\nexact H6.\napply SAnd1.\napply IHt1.\napply H6.\napply IHt2.\napply H7.\ninduction t; try (inversion H1).\napply SForall.\napply IHsub.\ninversion H0.\nexact H10.\nexact H6.\napply SAnd2.\napply IHt1.\napply H6.\napply SAnd3.\napply IHt2.\napply H6.\n(* Case Fun *)\ninduction t; try (inversion H2).\ninversion H0.\ninversion H2.\napply SFun.\napply IHsub1.\napply H14.\napply H7.\napply IHsub2.\nexact H16.\nexact H23.\napply SAnd1.\napply IHt1.\nexact H7.\napply IHt2.\nexact H8.\ninduction t; try (inversion H2).\ninversion H0.\ninversion H2.\napply SFun.\napply IHsub1.\napply H14.\napply H7.\napply IHsub2.\nexact H16.\nexact H23.\napply SAnd2.\napply IHt1.\nexact H7.\napply SAnd3.\napply IHt2.\nexact H7.\ninduction t; try (inversion H2).\ninversion H0.\ninversion H2.\napply SFun.\napply IHsub1.\napply H14.\napply H7.\napply IHsub2.\nexact H16.\nexact H23.\napply SAnd1.\napply IHt1.\nexact H7.\napply IHt2.\nexact H8.\ninduction t; try (inversion H2).\ninversion H0.\ninversion H2.\napply SFun.\napply IHsub1.\napply H14.\napply H7.\napply IHsub2.\nexact H16.\nexact H23.\napply SAnd2.\napply IHt1.\nexact H7.\napply SAnd3.\napply IHt2.\nexact H7.\n(* Case And1 *)\n(*\ngeneralize i, t1, t2, H, H1, H0, IHsub1, IHsub2, t0, H2.\nclear H2. clear t0. clear IHsub2. clear IHsub1. clear H0. clear H1. clear H. clear t2. clear t1. clear i. *)\ninduction t; intros.\ninversion H0.\napply SAnd2.\napply IHsub1.\nexact H7.\nexact H2.\napply SAnd3.\napply IHsub2.\nexact H7.\nexact H2.\ninversion H0.\napply SAnd2.\napply IHsub1.\nexact H7.\nexact H2.\napply SAnd3.\napply IHsub2.\nexact H7.\nexact H2.\ninversion H0. (*H2*)\napply SAnd2.\napply IHsub1.\nexact H8.\nexact H2. (*H3*)\napply SAnd3.\napply IHsub2.\nexact H8.\nexact H2. (*H3*)\ninversion H0.\napply SAnd2.\napply IHsub1.\nexact H7.\nexact H2.\napply SAnd3.\napply IHsub2.\nexact H7.\nexact H2.\nadmit.\nadmit.\nadmit.\nadmit.\nadmit.\nadmit.\nadmit.\nadmit.\nadmit.\nadmit.\nadmit.\nadmit.\nDefined.\n\nLemma ForallInv : forall t p g i, (forall t : PTyp nat, sub i (Forall nat p) t -> sub i (Forall nat g) t) ->\n                  sub (i + 1) (p i) t -> sub (i + 1) (g i) t.\nintros.\nassert (sub i (Forall nat g) (Forall nat (fun i => t))).\napply H.\napply SForall.\nexact H0.\ninversion H1.\nexact H5.\nDefined.\n\nLemma FunInv1 : forall o t t1 t2 t3 t4 i, (forall t : PTyp nat, sub i (Fun nat t1 t2) t -> sub i (Fun nat t3 t4) t) ->\n               sub i t1 t -> sub i o t.\nintros.\n(* assert (sub i (Fun nat t3 t4) (Fun )). *)\nadmit.\nDefined.\n\nLemma FunInv2 : forall t t1 t2 t3 t4 i, (forall t : PTyp nat, sub i (Fun nat t1 t2) t -> sub i (Fun nat t3 t4) t) ->\n               sub i t2 t -> sub i t4 t.\nintros.\nassert (exists t10, sub i (Fun nat t3 t4) (Fun nat t10 t)).\nexists t1.\napply H.\napply SFun.\napply reflex.\nexact H0.\ndestruct H1.\ninversion H1.\nexact H8.\nDefined.\n\nLemma funnyLemma : forall t1 t3 i (s : sub i t1 t3) t2, (forall t, sub i t2 t -> sub i t3 t) -> sub i t1 t2.\nintro. intro. intro. intro.\ninduction s; intros.\n(* Case PInt *)\napply H.\napply reflex.\n(* Case Var *)\napply H.\napply reflex.\n(* Case Forall *)\nassert (sub i (Forall nat g) t2).\napply H.\napply reflex.\ninduction t2; try (inversion H0).\nassert (sub (i+1) (f i) (p i)).\napply IHs. intro.\napply (ForallInv _ _ _ _ H).\napply SForall.\nexact H6.\napply SAnd1.\napply IHt2_1.\nintros.\napply H.\napply SAnd2.\nexact H7.\nexact H5.\napply IHt2_2.\nintros.\napply H.\napply SAnd3.\nexact H7.\nexact H6.\n(* Case Fun *)\n(*\ngeneralize i, o1, o2, o3, o4 , s1, s2, IHs1, IHs2, H.\nclear H. clear IHs2. clear IHs1. clear s2. clear s1. clear o4. clear o3. clear o2. clear o1. clear i.\ninduction t2; intros.\nassert (sub i (Fun nat o3 o4) (Var nat a)).\napply H. apply reflex.\ninversion H0.\nadmit.\nadmit.\napply SFun.\n*)\n\nassert (sub i (Fun nat o3 o4) t2).\napply H.\napply reflex.\ninduction t2; try (inversion H0).\napply SFun.\nassert (sub i o3 t2_1).\napply IHs1.\nintros.\nassert (sub i (Fun nat o3 o4) (Fun nat (Fun nat o1 o2) t2_1)).\napply H.\napply SFun.\napply IHt2_1.\nintros.\napply H.\n\n(* Using H! *)\nadmit.\nadmit.\nadmit.\nadmit.\nadmit.\nadmit.\nadmit.\nadmit.\nadmit.\nadmit.\nDefined.\n\n(* A functional definition : algorithm *)\n\nFixpoint size (t : PTyp nat) (i : nat) : nat :=\n  match t with\n      | PInt => 1\n      | Var x => 1\n      | Forall f => 1 + size (f i) (i+1)\n      | And o1 o2 => 1 + max (size o1 i) (size o2 i)\n      | Fun o1 o2 => 1 + max (size o1 i) (size o2 i)\n  end.\n\nFixpoint subTyp (n : nat) (t1 : PTyp nat) (t2 : PTyp nat) (i : nat) : Prop  :=\n  match n with\n      | 0 => False\n      | S m =>\n          match (t1,t2) with\n            | (PInt,PInt) => True\n            | (Var x, Var y) => if (eq_nat_dec x y) then True else False\n            | (Forall f, Forall g) => subTyp m (f i) (g i) (i+1)\n            | (And o1 o2, And o3 o4) => and (subTyp m o1 o3 i) (subTyp m o2 o4 i)\n            | (Fun o1 o2, Fun o3 o4) => and (subTyp m o3 o1 i) (subTyp m o2 o4 i)\n            | (_,_) => False\n          end\n  end.\n\nLemma implements : forall t1 t2 n i, subTyp (size t1 n) t1 t2 i -> sub i t1 t2.\nProof.\ninduction t1; intros.\nsimpl in H.\ndestruct t2; try destruct H.\ndestruct (eq_nat_dec a n0).\nrewrite e.\napply SVar. reflexivity.\ndestruct H.\ndestruct t2; try destruct H.\n", "meta": {"author": "zhiyuanshi", "repo": "intersection", "sha": "825f69cf7f70db7d0b829875f590fa38468bfad1", "save_path": "github-repos/coq/zhiyuanshi-intersection", "path": "github-repos/coq/zhiyuanshi-intersection/intersection-825f69cf7f70db7d0b829875f590fa38468bfad1/coq/Inter4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.694406314603254}}
{"text": "Require Import Relations.\n\nLemma wf_inclusion :\n forall (A:Set) (R S:A -> A -> Prop),\n   inclusion A R S -> well_founded S -> well_founded R.\nProof.\n intros A R S Hincl Hwf x.\n elim x using (well_founded_ind Hwf).\n intros x' Hrec; apply Acc_intro.\n intros y Hr; apply Hrec; apply Hincl; assumption.\nQed.", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/gen-rec/SRC/inclusionwf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88720460564669, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6943817604915254}}
{"text": "From Coq Require Import List Lia.\nFrom StructTact Require Import StructTactics ListTactics.\nFrom StructTact Require Import FilterMap RemoveAll.\nImport ListNotations.\n\nSet Implicit Arguments.\n\nFixpoint subseq {A} (xs ys : list A) : Prop :=\n  match xs, ys with\n    | [], _ => True\n    | x :: xs', y :: ys' => (x = y /\\ subseq xs' ys') \\/ subseq xs ys'\n    | _, _ => False\n  end.\n\nSection subseq.\n  Variable A B : Type.\n  Hypothesis A_eq_dec : forall x y : A, {x = y} + {x <> y}.\n\n  Lemma subseq_refl : forall (l : list A), subseq l l.\n  Proof using.\n    induction l; simpl; tauto.\n  Qed.\n\n  Lemma subseq_trans :\n    forall (zs xs ys : list A),\n      subseq xs ys ->\n      subseq ys zs ->\n      subseq xs zs.\n  Proof using.\n    induction zs; intros; simpl in *;\n      repeat break_match; subst; simpl in *; intuition; subst; eauto;\n        right; (eapply IHzs; [|eauto]); simpl; eauto.\n  Qed.\n\n  Lemma subseq_In :\n    forall (ys xs : list A) x,\n      subseq xs ys ->\n      In x xs ->\n      In x ys.\n  Proof using.\n    induction ys; intros.\n    - destruct xs; simpl in *; intuition.\n    - simpl in *.\n      break_match; simpl in *; intuition auto; subst; intuition eauto;\n        right; (eapply IHys; [eauto| intuition auto with datatypes]).\n  Qed.\n\n  Theorem subseq_NoDup :\n    forall (ys xs : list A),\n      subseq xs ys ->\n      NoDup ys ->\n      NoDup xs.\n  Proof using.\n    induction ys; intros.\n    - destruct xs; simpl in *; intuition.\n    - simpl in *. invc_NoDup.\n      break_match.\n      + constructor.\n      + intuition.\n        subst. constructor; eauto using subseq_In.\n  Qed.\n\n  Lemma subseq_remove :\n    forall (x : A) xs,\n      subseq (remove A_eq_dec x xs) xs.\n  Proof using.\n    induction xs; intros; simpl.\n    - auto.\n    - repeat break_match; auto.\n      + intuition congruence.\n      + find_inversion. auto.\n  Qed.\n\n  Lemma subseq_map :\n    forall (f : A -> B) ys xs,\n      subseq xs ys ->\n      subseq (map f xs) (map f ys).\n  Proof using.\n    induction ys; intros; simpl in *.\n    - repeat break_match; try discriminate; auto.\n    - repeat break_match; try discriminate; auto.\n      intuition.\n      + subst. simpl in *. find_inversion. auto.\n      + right. repeat find_reverse_rewrite. auto.\n  Qed.\n\n  Lemma subseq_cons_drop :\n    forall xs ys (a : A),\n      subseq (a :: xs) ys -> subseq xs ys.\n  Proof using.\n    induction ys; intros; simpl in *; intuition; break_match; eauto.\n  Qed.\n\n  Lemma subseq_length :\n    forall (ys xs : list A),\n      subseq xs ys ->\n      length xs <= length ys.\n  Proof using.\n    induction ys; intros; simpl in *; break_match;\n      intuition auto with datatypes arith.\n    subst. simpl in *. specialize (IHys l).\n    concludes. auto with arith.\n  Qed.\n\n  Lemma subseq_subseq_eq :\n    forall (xs ys : list A),\n      subseq xs ys ->\n      subseq ys xs ->\n      xs = ys.\n  Proof using.\n    induction xs; intros; destruct ys; simpl in *;\n      intuition eauto using f_equal2, subseq_cons_drop.\n    exfalso.\n    repeat find_apply_lem_hyp subseq_length.\n    simpl in *. lia.\n  Qed.\n\n  Lemma subseq_filter :\n    forall (f : A -> bool) xs,\n      subseq (filter f xs) xs.\n  Proof using.\n    induction xs; intros; simpl.\n    - auto.\n    - repeat break_match; intuition congruence.\n  Qed.\n\n  Lemma subseq_nil :\n    forall xs,\n      subseq (A:=A) [] xs.\n  Proof using.\n    destruct xs; simpl; auto.\n  Qed.\n\n  Lemma subseq_skip :\n    forall a xs ys,\n      subseq(A:=A) xs ys ->\n      subseq xs (a :: ys).\n  Proof using.\n    induction ys; intros; simpl in *; repeat break_match; intuition.\n  Qed.\n\n  Lemma subseq_filterMap :\n    forall (f : B -> option A) ys xs,\n      subseq xs ys ->\n      subseq (filterMap f xs) (filterMap f ys).\n  Proof using.\n    induction ys; intros; simpl in *; repeat break_match; auto; try discriminate; intuition; subst.\n    - simpl. find_rewrite. auto.\n    - auto using subseq_skip.\n    - auto using subseq_nil.\n    - simpl. find_rewrite. auto.\n  Qed.\n\n  Lemma subseq_app_r :\n    forall xs ys,\n      subseq (A:=A) ys (xs ++ ys).\n  Proof using.\n    induction xs; intros; simpl.\n    + auto using subseq_refl.\n    + break_match.\n      * auto.\n      * right. auto using subseq_nil.\n  Qed.\n\n  Lemma subseq_app_tail :\n    forall ys xs zs,\n      subseq (A:=A) xs ys ->\n      subseq (xs ++ zs) (ys ++ zs).\n  Proof using.\n    induction ys; intros; simpl in *.\n    - break_match; intuition auto using subseq_refl.\n    - repeat break_match.\n      + auto.\n      + discriminate.\n      + simpl in *. subst. right. auto using subseq_app_r.\n      + simpl in *. find_inversion. intuition.\n        rewrite app_comm_cons. auto.\n  Qed.\n\n  Lemma subseq_app_head :\n    forall xs ys zs,\n      subseq (A:=A) ys zs ->\n      subseq (A:=A) (xs ++ ys) (xs ++ zs).\n  Proof using.\n    induction xs; intros; simpl; intuition.\n  Qed.\n\n  Lemma subseq_2_3 :\n    forall xs ys zs x y,\n      subseq(A:=A) (xs ++ ys ++ zs) (xs ++ x :: ys ++ y :: zs).\n  Proof using.\n    auto using subseq_refl, subseq_skip, subseq_app_head.\n  Qed.\n\n  Lemma subseq_middle :\n    forall xs y zs,\n      subseq (A:=A) (xs ++ zs) (xs ++ y :: zs).\n  Proof using.\n    intros.\n    apply subseq_app_head.\n    apply subseq_skip.\n    apply subseq_refl.\n  Qed.\n\n  Lemma subseq_remove_all :\n    forall (ds l l' : list A),\n      subseq l l' ->\n      subseq (remove_all A_eq_dec ds l) l'.\n  Proof using.\n    induction ds; intros; simpl.\n    - auto.\n    - apply IHds.\n      eapply subseq_trans.\n      apply subseq_remove.\n      auto.\n  Qed.\nEnd subseq.\n", "meta": {"author": "uwplse", "repo": "StructTact", "sha": "2f2ff253be29bb09f36cab96d036419b18a95b00", "save_path": "github-repos/coq/uwplse-StructTact", "path": "github-repos/coq/uwplse-StructTact/StructTact-2f2ff253be29bb09f36cab96d036419b18a95b00/theories/Subseq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6943817513254833}}
{"text": "\nRequire Import MathClasses.interfaces.canonical_names.\nRequire Import Coq.Lists.List.\nRequire Import BijNat.\nRequire Import MeetSemiLattice.\nRequire Import DistrLattice.\nRequire Import PreorderEquiv.\n\n(** * Definition of sigma-frames\n    They are meet semilattices with countable joins, such\n    that meet distributes over joins.\n\n    We omit the sigma prefix in the coq development. *)\n\nSection Frame_Definition.\n\nClass Frame {t:Type} {le: Le t} :=\n  MkFrame {\n      frame_msl :> MeetSemiLattice le;\n\n      (* countable joins *)\n      V : (nat -> t) -> t;\n      v_le: forall u : (nat -> t), forall n: nat, u n ≤ V u;\n      v_univ: forall u : (nat -> t), forall z : t, (forall n : nat, u n ≤ z) -> V u ≤ z;\n\n      (* distributivity *)\n      cdistr_l: forall x u, x ⊓ (V u) ≤ (V (fun n => x ⊓ (u n)));\n    }.\n\n  Context {t : Type}.\n  Context {le : Le t}.\n\n  Variable (F : @Frame t le).\n  Existing Instance Feq_equiv.\n\n  (** ** Properties of the countable join *)\n  (* Countable join is a morphism *)\n\n  Lemma V_compat_le : forall a b, (forall n, a n ≤ b n) -> V a ≤ V b.\n  Proof.\n    intros.\n    apply v_univ.\n    intros.\n    apply (le_trans _ (b n) _ (H n)).\n    apply v_le.\n  Qed.\n\n  Lemma V_morphism : forall a b, (forall n, a n = b n) -> V a = V b.\n    unfold Feq.\n    intros.\n    split.\n    \n    apply V_compat_le.\n    firstorder.\n    apply V_compat_le.\n    firstorder.\n  Qed.\n\n  Add Morphism V : morphism_V.\n  Proof.\n    apply V_morphism.\n  Qed.\n\n  Lemma V_le_le : forall x t u, t ≤ u x -> t ≤ V u.\n  Proof.\n    intros.\n    apply le_trans with (y := u x).\n    apply H.\n    apply v_le.\n  Qed.\n\n  Ltac smart_V_le n :=\n    apply (V_le_le n);\n    simpl;\n    try (apply le_refl).\n\n  Lemma V_const : forall x, V (fun _ => x) = x.\n  Proof.\n    intros.\n    split.\n    apply v_univ. intro ; apply le_refl.\n    apply (V_le_le O).\n    apply le_refl.\n  Qed.\n\n  Lemma V_top : forall u, (exists n, u n = ⊤) -> V u = ⊤.\n  Proof.\n    intros.\n    destruct H as [n H].\n    split.\n    apply top_le.\n    setoid_rewrite <- H.\n    apply v_le.\n  Qed.\n\n  Lemma V_bot : V (fun _ => ⊥) = ⊥.\n  Proof.\n    apply V_const.\n  Qed.\n\n  Lemma V_comm : forall w : nat -> nat -> t,\n                   V (fun n => V (fun m => w n m)) = V (fun m => V (fun n => w n m)).\n  Proof.\n    intros.\n    unfold Feq.\n    split; repeat (apply v_univ; intro).\n    - (* <= *)\n      apply le_trans with (y := V (fun n1 => w n1 n0)).\n      smart_V_le n.\n      smart_V_le n0.\n\n    - (* >= *)\n      apply le_trans with (y := V (fun m => w n0 m)).\n      smart_V_le n.\n      smart_V_le n0.\n  Qed.\n\n  Definition my_pairer w (n : nat) : t := w (fst (bijNNinv n)) (snd (bijNNinv n)).\n\n  Lemma V_pair : forall w : nat -> nat -> t,\n                   V (fun n => w (fst (bijNNinv n)) (snd (bijNNinv n))) =\n                   V (fun n => V (fun m => w n m)).\n  Proof.\n    intro.\n    unfold Feq. split.\n\n    - (* <= *)\n      apply v_univ. intro.\n      smart_V_le (fst (bijNNinv n)).\n      smart_V_le (snd (bijNNinv n)).\n\n    - (* >= *)\n      repeat (apply v_univ; intro).\n      assert (w n n0 = (my_pairer w (bijNN (n,n0)))).\n      unfold my_pairer.\n      rewrite bijNNinv_bijNN.\n      reflexivity.\n      rewrite H.\n      apply v_le.\n  Qed.\n\n  (** ** Distributivity *)\n\n  Lemma cdistr_r: forall x u, V (fun n => x ⊓ (u n)) ≤ x ⊓ (V u).\n  Proof.\n    intros.\n    apply v_univ. intro.\n    apply meet_le.\n    apply le_refl.\n    eapply v_le.\n  Qed.\n\n  Lemma cdistr : forall x u, x ⊓ (V u) = V (fun n => x ⊓ (u n)).\n  Proof.\n    intros. split.\n    apply cdistr_l.\n    apply cdistr_r.\n  Qed.\n\n  Lemma V_meet : forall a b, V a ⊓ V b = V (fun n => a (bijNN1 n) ⊓ b (bijNN2 n)).\n  Proof.\n    intros.\n    split.\n    - rewrite cdistr.\n      apply v_univ.\n      intro.\n      assert (V a ⊓ b n = b n ⊓ V a) by (apply meet_comm).\n      rewrite H, cdistr.\n      apply v_univ.\n      intro.\n      set (h := (fun n1 => a (bijNN1 n1) ⊓ b (bijNN2 n1))).\n      assert (b n ⊓ a n0 = h (bijNN (n0,n))).\n      unfold h ; rewrite bijNN1_eq, bijNN2_eq ; apply meet_comm.\n      rewrite H0 ; apply v_le.\n\n    - apply v_univ. intro.\n      apply meet_univ.\n      + apply le_trans with (y := a (bijNN1 n)).\n        apply meet_l.\n        apply v_le.\n      + apply le_trans with (y := b (bijNN2 n)).\n        apply meet_r.\n        apply v_le.\n  Qed.\n\n  (** ** Finite joins\n      It seems easier to first define finite joins\n      and then to define binary joins, so that we \n      have a distributive lattice, even if this \n      distributive lattice gives us again the finite\n      joins.\n\n    *)\n  \n  Require Import SeqOfList.\n\n  Instance t_po : Preorder le.\n  Proof. apply msl_preorder. Defined.\n  Existing Instance setoid_msl.\n  \n  Definition Vf (l : list t) : t := V (seq_of_list l).\n\n  Add Morphism Vf : Vf_morphism.\n  Proof.\n    intros. unfold Vf.\n    apply V_morphism.\n    apply seq_of_list_morphism.\n    apply setoid_msl. apply t_po.\n    assumption.\n  Qed.\n\n  Lemma Vf_nil : Vf [] = ⊥.\n  Proof.\n    unfold Vf, seq_of_list.\n    apply V_bot.\n  Qed.\n\n  Hint Resolve Vf_nil.\n  \n  Definition joinf (u v : list t) := u ++ v.\n  Instance joinf_join : Join (list t) := joinf.\n\n  (** ** Binary joins *)\n  \n  Definition joinb (u v : t) := Vf [u ; v].\n  Instance joinb_join : Join t := joinb.\n\n  Ltac unfold_joinb :=\n    unfold join, joinb_join, joinb, Vf.\n  \n  Lemma joinb_l : forall u v : t, u ≤ u ⊔ v.\n  Proof.\n    intros.\n    unfold_joinb. simpl.\n    set (f := (u ::: v ::: (fun _ :nat => ⊥))).\n    assert (u = f O) by reflexivity.\n    rewrite H. apply v_le.\n  Qed.\n\n  Lemma joinb_r : forall u v : t, v ≤ u ⊔ v.\n  Proof.\n    intros ; unfold_joinb ; simpl.\n    set (f := (u ::: v ::: (fun _ : nat => ⊥))).\n    assert (v = f (S O)) by reflexivity.\n    rewrite H. apply v_le.\n  Qed.\n\n  Lemma joinb_univ : forall u v w : t, u ≤ w -> v ≤ w -> u ⊔ v ≤ w.\n  Proof.\n    intros ; unfold_joinb ; simpl.\n    apply v_univ ; intro.\n    destruct n ; simpl ; try assumption.\n    destruct n ; simpl ; try assumption.\n    apply bot_le.\n  Qed.\n\n  Lemma joinb_distr : forall u v w, u ⊓ (v ⊔ w) ≤ (u ⊓ v) ⊔ (u ⊓ w).\n  Proof.\n    intros.\n    unfold_joinb.\n    apply le_trans with (y := V (fun n => u ⊓ (seq_of_list [v;w] n))).\n    apply cdistr_l.\n    unfold seq_of_list.\n    apply v_univ. intro.\n    destruct n ; simpl.\n    smart_V_le O.\n    destruct n ; simpl.\n    smart_V_le (S O).\n    rewrite meet_bot_r.\n    apply bot_le.\n  Qed.\n\n  Instance dl_frame : DistrLattice le :=\n    MkDistrLattice\n      t\n      le\n      frame_msl\n      joinb\n      joinb_l\n      joinb_r\n      joinb_univ\n      joinb_distr.\n\n\n\n  (** ** Compactness *)\n\n  Fixpoint partial_V (u : (nat -> t)) (n : nat) : t :=\n    match n with\n      | 0 => ⊥\n      | S n => (u O) ⊔ (partial_V (V_tail u) n)\n    end.\n\n  Lemma partial_V_le : forall u n, partial_V u n ≤ V u.\n  Proof.\n    intros.\n    generalize u as w.\n    induction n.\n\n    - (* 0 *)\n      intros.\n      apply bot_le.\n\n    - (* S n *)\n      intros.\n      simpl.\n      apply joinb_univ.\n      apply v_le.\n      apply (le_trans _ (V (V_tail w)) _).\n      apply IHn.\n      apply v_univ.\n      intro. unfold V_tail.\n      apply v_le.\n  Qed.\n\n  Definition compact := forall u, (V u = ⊤) -> (exists n, partial_V u n = ⊤).\n\n(** One way to define finite or infinite enumerations would\n     be to use streams, like this:\n\n<<\n  CoInductive enumeration (T : Type) :=\n  | ENil : enumeration T\n  | ECons : T -> enumeration T -> enumeration T.\n>>\n \n  The problem with this definition is that we can't decide\n  whether the enumeration is finite or not.\n *)\n\nEnd Frame_Definition.\n\n\nAdd Parametric Morphism (T : Type) (Tle : Le T) (Tf : Frame) : V with signature (pointwise_relation nat Feq ==> Feq) as f_V_morphism.\nProof.\n  apply V_morphism.\nQed.\n\n\n(** * Frame 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 (FA : @Frame tA leA).\n  Variable (FB : @Frame tB leB).\n\n  Definition mslA := @frame_msl tA leA FA.\n  Definition mslB := @frame_msl tB leB FB.\n\n  Open Scope program_scope. (* for ∘ (function composition) *)\n  Existing Instance joinb_join.\n\n  Variable (f : tA -> tB).\n  Class FMorphism :=\n    MkFMorphism\n      {\n        fmorph_mslmorph :> MSLMorphism mslA mslB f;\n        (* preserves countable joins *)\n        morph_V: forall u : nat -> tA, f (V u) = V (f ∘ u)\n      }.\n\n  Existing Instance listeq_equiv.\n\n  Variable fmorph : FMorphism.\n  Existing Instance fmorph.\n\n  Proposition FMorphism_join : forall a b, f (a ⊔ b) = f a ⊔ f b.\n  Proof.\n    intros.\n    unfold join, joinb_join, joinb.\n    assert ([f a; f b] = map f [a; b]) by reflexivity.\n    unfold Vf.\n    rewrite H.\n    rewrite seq_of_list_compose.\n    apply morph_V.\n    apply Feq_equivalence.\n    apply msl_preorder.\n    apply mslmorph_bot.\n    apply fmorph_mslmorph.\n  Qed.\n\nEnd Frame_Morphism_Definition.\n\n\n\n(* exported_tactics *)\nLtac smart_V_le n :=\n  apply (V_le_le n);\n  simpl;\n  try (apply le_refl).\n", "meta": {"author": "wetneb", "repo": "sigmalocales", "sha": "a42975000c9e505103e4321f7413af992fea5e0c", "save_path": "github-repos/coq/wetneb-sigmalocales", "path": "github-repos/coq/wetneb-sigmalocales/sigmalocales-a42975000c9e505103e4321f7413af992fea5e0c/Frame.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6943817511546883}}
{"text": "Require Export List.\n \nInductive ltree (A : Set) : Set :=\n  lnode: A -> list (ltree A) ->  ltree A .\n \nInductive ntree (A : Set) : Set :=\n               nnode: A -> nforest A ->  ntree A\nwith nforest (A : Set) : Set :=\n          nnil: nforest A\n         | ncons: ntree A -> nforest A ->  nforest A.\n \nScheme\nntree_ind2 := Induction for ntree Sort Prop\n   with\n   nforest_ind2 := Induction for nforest Sort Prop.\n \nSection correct_ltree_ind.\nVariables (A : Set) (P : ltree A ->  Prop) (Q : list (ltree A) ->  Prop).\nHypotheses\n   (H : forall (a : A) (l : list (ltree A)), Q l ->  P (lnode A a l))\n   (H0 : Q nil)\n   (H1 : forall (t : ltree A),\n         P t -> forall (l : list (ltree A)), Q l ->  Q (cons t l)).\n \nFixpoint ltree_ind2 (t : ltree A) : P t :=\n match t as x return P x with\n    lnode a l =>\n      H a l ((fix l_ind (l' : list (ltree A)) : Q l' :=\n                     match l' as x return Q x with\n                        nil => H0\n                       | cons t1 tl => H1 t1 (ltree_ind2 t1) tl (l_ind tl)\n                     end) l)\n end.\n \nEnd correct_ltree_ind.\n \nFixpoint ltree_to_ntree (A : Set) (t : ltree A) {struct t} : ntree A :=\n match t with\n   lnode x l =>\n     nnode\n      A x\n      ((fix\n        list_tree_to_nforest (l' : list (ltree A)) : nforest A :=\n           match l' with\n             nil => nnil A\n            | t1 :: tl =>\n                ncons A (ltree_to_ntree A t1) (list_tree_to_nforest tl)\n           end) l)\n end.\nFixpoint\n ntree_to_ltree (A : Set) (t : ntree A) {struct t} : ltree A :=\n    match t with nnode x f => lnode A x (nforest_to_list_ltree A f) end\n with\n nforest_to_list_ltree (A : Set) (f : nforest A) {struct f} : list (ltree A) :=\n    match f with\n      nnil => nil\n     | ncons t f' => ntree_to_ltree A t :: nforest_to_list_ltree A f'\n    end.\n \nTheorem ltree_o_ntree:\n forall (A : Set) (t : ntree A),  ltree_to_ntree A (ntree_to_ltree A t) = t.\nintros A t;\n elim t\n  using ntree_ind2\n with ( P0 :=\n      fun l =>\n      (fix\n       list_tree_to_nforest (l' : list (ltree A)) : nforest A :=\n          match l' with\n            nil => nnil A\n           | t1 :: tl => ncons A (ltree_to_ntree A t1) (list_tree_to_nforest tl)\n          end) (nforest_to_list_ltree A l) = l ).\nsimpl.\nintros a f IHf; rewrite IHf; trivial.\nsimpl; trivial.\nsimpl.\nintros n IHn f IHf; rewrite IHn; rewrite IHf; trivial.\nQed.\n \nTheorem ntree_o_ltree:\n forall (A : Set) (t : ltree A),  ntree_to_ltree A (ltree_to_ntree A t) = t.\nintros A t;\n elim t\n  using ltree_ind2\n with ( Q :=\n      fun l =>\n      nforest_to_list_ltree\n       A\n       ((fix\n         list_tree_to_nforest (l' : list (ltree A)) : nforest A :=\n            match l' with\n              nil => nnil A\n             | t1 :: tl =>\n                 ncons A (ltree_to_ntree A t1) (list_tree_to_nforest tl)\n            end) l) = l ).\nsimpl; intros a l IHl; rewrite IHl; trivial.\nsimpl; trivial.\nsimpl; intros t' IHt' tl IHtl; rewrite IHt'; rewrite IHtl; trivial.\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/induc-fond/SRC/ltree_to_ntree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6943817421594407}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice.\nFrom mathcomp Require Import fintype finfun bigop finset fingroup perm.\nFrom mathcomp Require Import div prime binomial ssralg finalg zmodp matrix.\n\n(*****************************************************************************)\n(* In this file we develop the rank and row space theory of matrices, based  *)\n(* on an extended Gaussian elimination procedure similar to LUP              *)\n(* decomposition. This provides us with a concrete but generic model of      *)\n(* finite dimensional vector spaces and F-algebras, in which vectors, linear *)\n(* functions, families, bases, subspaces, ideals and subrings are all        *)\n(* represented using matrices. This model can be used as a foundation for    *)\n(* the usual theory of abstract linear algebra, but it can also be used to   *)\n(* develop directly substantial theories, such as the theory of finite group *)\n(* linear representation.                                                    *)\n(*   Here we define the following concepts and notations:                    *)\n(* Gaussian_elimination A == a permuted triangular decomposition (L, U, r)   *)\n(*                   of A, with L a column permutation of a lower triangular *)\n(*                   invertible matrix, U a row permutation of an upper      *)\n(*                   triangular invertible matrix, and r the rank of A, all  *)\n(*                   satisfying the identity L *m pid_mx r *m U = A.         *)\n(*        \\rank A == the rank of A.                                          *)\n(*    row_free A <=> the rows of A are linearly free (i.e., the rank and     *)\n(*                   height of A are equal).                                 *)\n(*    row_full A <=> the row-space of A spans all row-vectors (i.e., the     *)\n(*                   rank and width of A are equal).                         *)\n(*    col_ebase A == the extended column basis of A (the first matrix L      *)\n(*                   returned by Gaussian_elimination A).                    *)\n(*    row_ebase A == the extended row base of A (the second matrix U         *)\n(*                   returned by Gaussian_elimination A).                    *)\n(*     col_base A == a basis for the columns of A: a row-full matrix         *)\n(*                   consisting of the first \\rank A columns of col_ebase A. *)\n(*     row_base A == a basis for the rows of A: a row-free matrix consisting *)\n(*                   of the first \\rank A rows of row_ebase A.               *)\n(*       pinvmx A == a partial inverse for A in its row space (or on its     *)\n(*                   column space, equivalently). In particular, if u is a   *)\n(*                   row vector in the row_space of A, then u *m pinvmx A is *)\n(*                   the row vector of the coefficients of a decomposition   *)\n(*                   of u as a sub of rows of A.                             *)\n(*        kermx A == the row kernel of A : a square matrix whose row space   *)\n(*                   consists of all u such that u *m A = 0 (it consists of  *)\n(*                   the inverse of col_ebase A, with the top \\rank A rows   *)\n(*                   zeroed out). Also, kermx A is a partial right inverse   *)\n(*                   to col_ebase A, in the row space anihilated by A.       *)\n(*      cokermx A == the cokernel of A : a square matrix whose column space  *)\n(*                   consists of all v such that A *m v = 0 (it consists of  *)\n(*                   the inverse of row_ebase A, with the leftmost \\rank A   *)\n(*                   columns zeroed out).                                    *)\n(* eigenvalue g a <=> a is an eigenvalue of the square matrix g.             *)\n(* eigenspace g a == a square matrix whose row space is the eigenspace of    *)\n(*                   the eigenvalue a of g (or 0 if a is not an eigenvalue). *)\n(* We use a different scope %MS for matrix row-space set-like operations; to *)\n(* avoid confusion, this scope should not be opened globally. Note that the  *)\n(* the arguments of \\rank _ and the operations below have default scope %MS. *)\n(*    (A <= B)%MS <=> the row-space of A is included in the row-space of B.  *)\n(*                   We test for this by testing if cokermx B anihilates A.  *)\n(*     (A < B)%MS <=> the row-space of A is properly included in the         *)\n(*                   row-space of B.                                         *)\n(*  (A <= B <= C)%MS == (A <= B)%MS && (B <= C)%MS, and similarly for        *)\n(*                   (A < B <= C)%MS, (A < B <= C)%MS and (A < B < C)%MS.    *)\n(*    (A == B)%MS == (A <= B <= A)%MS (A and B have the same row-space).     *)\n(*   (A :=: B)%MS == A and B behave identically wrt. \\rank and <=. This      *)\n(*                   triple rewrite rule is the Prop version of (A == B)%MS. *)\n(*                   Note that :=: cannot be treated as a setoid-style       *)\n(*                   Equivalence because its arguments can have different    *)\n(*                   types: A and B need not have the same number of rows,   *)\n(*                   and often don't (e.g., in row_base A :=: A).            *)\n(*       <<A>>%MS == a square matrix with the same row-space as A; <<A>>%MS  *)\n(*                   is a canonical representation of the subspace generated *)\n(*                   by A, viewed as a list of row-vectors: if (A == B)%MS,  *)\n(*                   then <<A>>%MS = <<B>>%MS.                               *)\n(*     (A + B)%MS == a square matrix whose row-space is the sum of the       *)\n(*                   row-spaces of A and B; thus (A + B == col_mx A B)%MS.   *)\n(*  (\\sum_i <expr i>)%MS == the \"big\" version of (_ + _)%MS; as the latter   *)\n(*                   has a canonical abelian monoid structure, most generic  *)\n(*                   bigop lemmas apply (the other bigop indexing notations  *)\n(*                   are also defined).                                      *)\n(*   (A :&: B)%MS == a square matrix whose row-space is the intersection of  *)\n(*                   the row-spaces of A and B.                              *)\n(*  (\\bigcap_i <expr i>)%MS == the \"big\" version of (_ :&: _)%MS, which also *)\n(*                   has a canonical abelian monoid structure.               *)\n(*         A^C%MS == a square matrix whose row-space is a complement to the  *)\n(*                   the row-space of A (it consists of row_ebase A with the *)\n(*                   top \\rank A rows zeroed out).                           *)\n(*   (A :\\: B)%MS == a square matrix whose row-space is a complement of the  *)\n(*                   the row-space of (A :&: B)%MS in the row-space of A.    *)\n(*                   We have (A :\\: B := A :&: (capmx_gen A B)^C)%MS, where  *)\n(*                   capmx_gen A B is a rectangular matrix equivalent to     *)\n(*                   (A :&: B)%MS, i.e., (capmx_gen A B == A :&: B)%MS.      *)\n(*    proj_mx A B == a square matrix that projects (A + B)%MS onto A         *)\n(*                   parallel to B, when (A :&: B)%MS = 0 (A and B must also *)\n(*                   be square).                                             *)\n(*     mxdirect S == the sum expression S is a direct sum. This is a NON     *)\n(*                   EXTENSIONAL notation: the exact boolean expression is   *)\n(*                   inferred from the syntactic form of S (expanding        *)\n(*                   definitions, however); both (\\sum_(i | _) _)%MS and     *)\n(*                   (_ + _)%MS sums are recognized. This construct uses a   *)\n(*                   variant of the reflexive (\"quote\") canonical structure, *)\n(*                   mxsum_expr. The structure also recognizes sums of       *)\n(*                   matrix ranks, so that lemmas concerning the rank of     *)\n(*                   direct sums can be used bidirectionally.                *)\n(* The next set of definitions let us represent F-algebras using matrices:   *)\n(*   'A[F]_(m, n) == the type of matrices encoding (sub)algebras of square   *)\n(*                   n x n matrices, via mxvec; as in the matrix type        *)\n(*                   notation, m and F can be omitted (m defaults to n ^ 2). *)\n(*                := 'M[F]_(m, n ^ 2).                                       *)\n(*   (A \\in R)%MS <=> the square matrix A belongs to the linear set of       *)\n(*                    matrices (most often, a sub-algebra) encoded by the    *)\n(*                    row space of R. This is simply notation, so all the    *)\n(*                    lemmas and rewrite rules for (_ <= _)%MS can apply.    *)\n(*                := (mxvec A <= R)%MS.                                      *)\n(*     (R * S)%MS == a square n^2 x n^2 matrix whose row-space encodes the   *)\n(*                   linear set of n x n matrices generated by the pointwise *)\n(*                   product of the sets of matrices encoded by R and S.     *)\n(*       'C(R)%MS == a square matric encoding the centraliser of the set of  *)\n(*                   square matrices encoded by R.                           *)\n(*     'C_S(R)%MS := (S :&: 'C(R))%MS (the centraliser of R in S).           *)\n(*       'Z(R)%MS == the center of R (i.e., 'C_R(R)%MS).                     *)\n(*  left_mx_ideal R S <=> S is a left ideal for R (R * S <= S)%MS.           *)\n(* right_mx_ideal R S <=> S is a right ideal for R (S * R <= S)%MS.          *)\n(*       mx_ideal R S <=> S is a bilateral ideal for R.                      *)\n(*      mxring_id R e <-> e is an identity element for R (Prop predicate).   *)\n(*    has_mxring_id R <=> R has a nonzero identity element (bool predicate). *)\n(*           mxring R <=> R encodes a nontrivial subring.                    *)\n(*****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GroupScope.\nImport GRing.Theory.\nLocal Open Scope ring_scope.\n\nReserved Notation \"\\rank A\" (at level 10, A at level 8, format \"\\rank  A\").\nReserved Notation \"A ^C\"    (at level 8, format \"A ^C\").\n\nNotation \"''A_' ( m , n )\" := 'M_(m, n ^ 2)\n  (at level 8, format \"''A_' ( m ,  n )\") : type_scope.\n\nNotation \"''A_' ( n )\" := 'A_(n ^ 2, n)\n  (at level 8, only parsing) : type_scope.\n\nNotation \"''A_' n\" := 'A_(n)\n  (at level 8, n at next level, format \"''A_' n\") : type_scope.\n\nNotation \"''A' [ F ]_ ( m , n )\" := 'M[F]_(m, n ^ 2)\n  (at level 8, only parsing) : type_scope.\n\nNotation \"''A' [ F ]_ ( n )\" := 'A[F]_(n ^ 2, n)\n  (at level 8, only parsing) : type_scope.\n\nNotation \"''A' [ F ]_ n\" := 'A[F]_(n)\n  (at level 8, n at level 2, only parsing) : type_scope.\n\nDelimit Scope matrix_set_scope with MS.\n\nLocal Notation simp := (Monoid.Theory.simpm, oppr0).\n\n(*****************************************************************************)\n(******************** Rank and row-space theory ******************************)\n(*****************************************************************************)\n\nSection RowSpaceTheory.\n\nVariable F : fieldType.\nImplicit Types m n p r : nat.\n\nLocal Notation \"''M_' ( m , n )\" := 'M[F]_(m, n) : type_scope.\nLocal Notation \"''M_' n\" := 'M[F]_(n, n) : type_scope.\n\n(* Decomposition with double pivoting; computes the rank, row and column  *)\n(* images, kernels, and complements of a matrix.                          *)\n\nFixpoint Gaussian_elimination {m n} : 'M_(m, n) -> 'M_m * 'M_n * nat :=\n  match m, n with\n  | _.+1, _.+1 => fun A : 'M_(1 + _, 1 + _) =>\n    if [pick ij | A ij.1 ij.2 != 0] is Some (i, j) then\n      let a := A i j in let A1 := xrow i 0 (xcol j 0 A) in\n      let u := ursubmx A1 in let v := a^-1 *: dlsubmx A1 in\n      let: (L, U, r) := Gaussian_elimination (drsubmx A1 - v *m u) in\n      (xrow i 0 (block_mx 1 0 v L), xcol j 0 (block_mx a%:M u 0 U), r.+1)\n    else (1%:M, 1%:M, 0%N)\n  | _, _ => fun _ => (1%:M, 1%:M, 0%N)\n  end.\n\nSection Defs.\n\nVariables (m n : nat) (A : 'M_(m, n)).\n\nFact Gaussian_elimination_key : unit. Proof. by []. Qed.\n\nLet LUr := locked_with Gaussian_elimination_key (@Gaussian_elimination) m n A.\n\nDefinition col_ebase := LUr.1.1.\nDefinition row_ebase := LUr.1.2.\nDefinition mxrank := if [|| m == 0 | n == 0]%N then 0%N else LUr.2.\n\nDefinition row_free := mxrank == m.\nDefinition row_full := mxrank == n.\n\nDefinition row_base : 'M_(mxrank, n) := pid_mx mxrank *m row_ebase.\nDefinition col_base : 'M_(m, mxrank) := col_ebase *m pid_mx mxrank.\n\nDefinition complmx : 'M_n := copid_mx mxrank *m row_ebase.\nDefinition kermx : 'M_m := copid_mx mxrank *m invmx col_ebase.\nDefinition cokermx : 'M_n := invmx row_ebase *m copid_mx mxrank.\n\nDefinition pinvmx : 'M_(n, m) :=\n  invmx row_ebase *m pid_mx mxrank *m invmx col_ebase.\n\nEnd Defs.\n\nArguments mxrank {m%N n%N} A%MS.\nLocal Notation \"\\rank A\" := (mxrank A) : nat_scope.\nArguments complmx {m%N n%N} A%MS.\nLocal Notation \"A ^C\" := (complmx A) : matrix_set_scope.\n\nDefinition submx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  A *m cokermx B == 0).\nFact submx_key : unit. Proof. by []. Qed.\nDefinition submx := locked_with submx_key submx_def.\nCanonical submx_unlockable := [unlockable fun submx].\n\nArguments submx {m1%N m2%N n%N} A%MS B%MS : rename.\nLocal Notation \"A <= B\" := (submx A B) : matrix_set_scope.\nLocal Notation \"A <= B <= C\" := ((A <= B) && (B <= C))%MS : matrix_set_scope.\nLocal Notation \"A == B\" := (A <= B <= A)%MS : matrix_set_scope.\n\nDefinition ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  (A <= B)%MS && ~~ (B <= A)%MS.\nArguments ltmx {m1%N m2%N n%N} A%MS B%MS.\nLocal Notation \"A < B\" := (ltmx A B) : matrix_set_scope.\n\nDefinition eqmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  prod (\\rank A = \\rank B)\n       (forall m3 (C : 'M_(m3, n)),\n            ((A <= C) = (B <= C)) * ((C <= A) = (C <= B)))%MS.\nArguments eqmx {m1%N m2%N n%N} A%MS B%MS.\nLocal Notation \"A :=: B\" := (eqmx A B) : matrix_set_scope.\n\nSection LtmxIdentities.\n\nVariables (m1 m2 n : nat) (A : 'M_(m1, n)) (B : 'M_(m2, n)).\n\nLemma ltmxE : (A < B)%MS = ((A <= B)%MS && ~~ (B <= A)%MS). Proof. by []. Qed.\n\nLemma ltmxW : (A < B)%MS -> (A <= B)%MS. Proof. by case/andP. Qed.\n\nLemma ltmxEneq : (A < B)%MS = (A <= B)%MS && ~~ (A == B)%MS.\nProof. by apply: andb_id2l => ->. Qed.\n\nLemma submxElt : (A <= B)%MS = (A == B)%MS || (A < B)%MS.\nProof. by rewrite -andb_orr orbN andbT. Qed.\n\nEnd LtmxIdentities.\n\n(* The definition of the row-space operator is rigged to return the identity  *)\n(* matrix for full matrices. To allow for further tweaks that will make the   *)\n(* row-space intersection operator strictly commutative and monoidal, we      *)\n(* slightly generalize some auxiliary definitions: we parametrize the         *)\n(* \"equivalent subspace and identity\" choice predicate equivmx by a boolean   *)\n(* determining whether the matrix should be the identity (so for genmx A its  *)\n(* value is row_full A), and introduce a \"quasi-identity\" predicate qidmx     *)\n(* that selects non-square full matrices along with the identity matrix 1%:M  *)\n(* (this does not affect genmx, which chooses a square matrix).               *)\n(*   The choice witness for genmx A is either 1%:M for a row-full A, or else  *)\n(* row_base A padded with null rows.                                          *)\nLet qidmx m n (A : 'M_(m, n)) :=\n  if m == n then A == pid_mx n else row_full A.\nLet equivmx m n (A : 'M_(m, n)) idA (B : 'M_n) :=\n  (B == A)%MS && (qidmx B == idA).\nLet equivmx_spec m n (A : 'M_(m, n)) idA (B : 'M_n) :=\n  prod (B :=: A)%MS (qidmx B = idA).\nDefinition genmx_witness m n (A : 'M_(m, n)) : 'M_n :=\n  if row_full A then 1%:M else pid_mx (\\rank A) *m row_ebase A.\nDefinition genmx_def := idfun (fun m n (A : 'M_(m, n)) =>\n   choose (equivmx A (row_full A)) (genmx_witness A) : 'M_n).\nFact genmx_key : unit. Proof. by []. Qed.\nDefinition genmx := locked_with genmx_key genmx_def.\nCanonical genmx_unlockable := [unlockable fun genmx].\nLocal Notation \"<< A >>\" := (genmx A) : matrix_set_scope.\n\n(* The setwise sum is tweaked so that 0 is a strict identity element for      *)\n(* square matrices, because this lets us use the bigop component. As a result *)\n(* setwise sum is not quite strictly extensional.                             *)\nLet addsmx_nop m n (A : 'M_(m, n)) := conform_mx <<A>>%MS A.\nDefinition addsmx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  if A == 0 then addsmx_nop B else if B == 0 then addsmx_nop A else\n  <<col_mx A B>>%MS : 'M_n).\nFact addsmx_key : unit. Proof. by []. Qed.\nDefinition addsmx := locked_with addsmx_key addsmx_def.\nCanonical addsmx_unlockable := [unlockable fun addsmx].\nArguments addsmx {m1%N m2%N n%N} A%MS B%MS : rename.\nLocal Notation \"A + B\" := (addsmx A B) : matrix_set_scope.\nLocal Notation \"\\sum_ ( i | P ) B\" := (\\big[addsmx/0]_(i | P) B%MS)\n  : matrix_set_scope.\nLocal Notation \"\\sum_ ( i <- r | P ) B\" := (\\big[addsmx/0]_(i <- r | P) B%MS)\n  : matrix_set_scope.\n\n(* The set intersection is similarly biased so that the identity matrix is a  *)\n(* strict identity. This is somewhat more delicate than for the sum, because  *)\n(* the test for the identity is non-extensional. This forces us to actually   *)\n(* bias the choice operator so that it does not accidentally map an           *)\n(* intersection of non-identity matrices to 1%:M; this would spoil            *)\n(* associativity: if B :&: C = 1%:M but B and C are not identity, then for a  *)\n(* square matrix A we have A :&: (B :&: C) = A != (A :&: B) :&: C in general. *)\n(* To complicate matters there may not be a square non-singular matrix        *)\n(* different than 1%:M, since we could be dealing with 'M['F_2]_1. We         *)\n(* sidestep the issue by making all non-square row-full matrices identities,  *)\n(* and choosing a normal representative that preserves the qidmx property.    *)\n(* Thus A :&: B = 1%:M iff A and B are both identities, and this suffices for *)\n(* showing that associativity is strict.                                      *)\nLet capmx_witness m n (A : 'M_(m, n)) :=\n  if row_full A then conform_mx 1%:M A else <<A>>%MS.\nLet capmx_norm m n (A : 'M_(m, n)) :=\n  choose (equivmx A (qidmx A)) (capmx_witness A).\nLet capmx_nop m n (A : 'M_(m, n)) := conform_mx (capmx_norm A) A.\nDefinition capmx_gen m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  lsubmx (kermx (col_mx A B)) *m A.\nDefinition capmx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  if qidmx A then capmx_nop B else\n  if qidmx B then capmx_nop A else\n  if row_full B then capmx_norm A else capmx_norm (capmx_gen A B) : 'M_n).\nFact capmx_key : unit. Proof. by []. Qed.\nDefinition capmx := locked_with capmx_key capmx_def.\nCanonical capmx_unlockable := [unlockable fun capmx].\nArguments capmx {m1%N m2%N n%N} A%MS B%MS : rename.\nLocal Notation \"A :&: B\" := (capmx A B) : matrix_set_scope.\nLocal Notation \"\\bigcap_ ( i | P ) B\" := (\\big[capmx/1%:M]_(i | P) B)\n  : matrix_set_scope.\n\nDefinition diffmx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  <<capmx_gen A (capmx_gen A B)^C>>%MS : 'M_n).\nFact diffmx_key : unit. Proof. by []. Qed.\nDefinition diffmx := locked_with diffmx_key diffmx_def.\nCanonical diffmx_unlockable := [unlockable fun diffmx].\nArguments diffmx {m1%N m2%N n%N} A%MS B%MS : rename.\nLocal Notation \"A :\\: B\" := (diffmx A B) : matrix_set_scope.\n\nDefinition proj_mx n (U V : 'M_n) : 'M_n := pinvmx (col_mx U V) *m col_mx U 0.\n\nLocal Notation GaussE := Gaussian_elimination.\n\nFact mxrankE m n (A : 'M_(m, n)) : \\rank A = (GaussE A).2.\nProof. by rewrite /mxrank unlock /=; case: m n A => [|m] [|n]. Qed.\n\nLemma rank_leq_row m n (A : 'M_(m, n)) : \\rank A <= m.\nProof.\nrewrite mxrankE.\nelim: m n A => [|m IHm] [|n] //= A; case: pickP => [[i j] _|] //=.\nby move: (_ - _) => B; case: GaussE (IHm _ B) => [[L U] r] /=.\nQed.\n\nLemma row_leq_rank m n (A : 'M_(m, n)) : (m <= \\rank A) = row_free A.\nProof. by rewrite /row_free eqn_leq rank_leq_row. Qed.\n\nLemma rank_leq_col m n (A : 'M_(m, n)) : \\rank A <= n.\nProof.\nrewrite mxrankE.\nelim: m n A => [|m IHm] [|n] //= A; case: pickP => [[i j] _|] //=.\nby move: (_ - _) => B; case: GaussE (IHm _ B) => [[L U] r] /=.\nQed.\n\nLemma col_leq_rank m n (A : 'M_(m, n)) : (n <= \\rank A) = row_full A.\nProof. by rewrite /row_full eqn_leq rank_leq_col. Qed.\n\nLet unitmx1F := @unitmx1 F.\nLemma row_ebase_unit m n (A : 'M_(m, n)) : row_ebase A \\in unitmx.\nProof.\nrewrite /row_ebase unlock; elim: m n A => [|m IHm] [|n] //= A.\ncase: pickP => [[i j] /= nzAij | //=]; move: (_ - _) => B.\ncase: GaussE (IHm _ B) => [[L U] r] /= uU.\nrewrite unitmxE xcolE det_mulmx (@det_ublock _ 1) det_scalar1 !unitrM.\nby rewrite unitfE nzAij -!unitmxE uU unitmx_perm.\nQed.\n\nLemma col_ebase_unit m n (A : 'M_(m, n)) : col_ebase A \\in unitmx.\nProof.\nrewrite /col_ebase unlock; elim: m n A => [|m IHm] [|n] //= A.\ncase: pickP => [[i j] _|] //=; move: (_ - _) => B.\ncase: GaussE (IHm _ B) => [[L U] r] /= uL.\nrewrite unitmxE xrowE det_mulmx (@det_lblock _ 1) det1 mul1r unitrM.\nby rewrite -unitmxE unitmx_perm.\nQed.\nHint Resolve rank_leq_row rank_leq_col row_ebase_unit col_ebase_unit : core.\n\nLemma mulmx_ebase m n (A : 'M_(m, n)) :\n  col_ebase A *m pid_mx (\\rank A) *m row_ebase A = A.\nProof.\nrewrite mxrankE /col_ebase /row_ebase unlock.\nelim: m n A => [n A | m IHm]; first by rewrite [A]flatmx0 [_ *m _]flatmx0.\ncase=> [A | n]; first by rewrite [_ *m _]thinmx0 [A]thinmx0.\nrewrite -(add1n m) -?(add1n n) => A /=.\ncase: pickP => [[i0 j0] | A0] /=; last first.\n  apply/matrixP=> i j; rewrite pid_mx_0 mulmx0 mul0mx mxE.\n  by move/eqP: (A0 (i, j)).\nset a := A i0 j0 => nz_a; set A1 := xrow _ _ _.\nset u := ursubmx _; set v := _ *: _; set B : 'M_(m, n) := _ - _.\nmove: (rank_leq_col B) (rank_leq_row B) {IHm}(IHm n B); rewrite mxrankE.\ncase: (GaussE B) => [[L U] r] /= r_m r_n defB.\nhave ->: pid_mx (1 + r) = block_mx 1 0 0 (pid_mx r) :> 'M[F]_(1 + m, 1 + n).\n  rewrite -(subnKC r_m) -(subnKC r_n) pid_mx_block -col_mx0 -row_mx0.\n  by rewrite block_mxA castmx_id col_mx0 row_mx0 -scalar_mx_block -pid_mx_block.\nrewrite xcolE xrowE mulmxA -xcolE -!mulmxA.\nrewrite !(addr0, add0r, mulmx0, mul0mx, mulmx_block, mul1mx) mulmxA defB.\nrewrite addrC subrK mul_mx_scalar scalerA divff // scale1r.\nhave ->: a%:M = ulsubmx A1 by rewrite [_ A1]mx11_scalar !mxE !lshift0 !tpermR.\nrewrite submxK /A1 xrowE !xcolE -!mulmxA mulmxA -!perm_mxM !tperm2 !perm_mx1.\nby rewrite mulmx1 mul1mx.\nQed.\n\nLemma mulmx_base m n (A : 'M_(m, n)) : col_base A *m row_base A = A.\nProof. by rewrite mulmxA -[col_base A *m _]mulmxA pid_mx_id ?mulmx_ebase. Qed.\n\nLemma mulmx1_min_rank r m n (A : 'M_(m, n)) M N :\n  M *m A *m N = 1%:M :> 'M_r -> r <= \\rank A.\nProof. by rewrite -{1}(mulmx_base A) mulmxA -mulmxA; move/mulmx1_min. Qed.\nArguments mulmx1_min_rank [r m n A].\n\nLemma mulmx_max_rank r m n (M : 'M_(m, r)) (N : 'M_(r, n)) :\n  \\rank (M *m N) <= r.\nProof.\nset MN := M *m N; set rMN := \\rank _.\npose L : 'M_(rMN, m) := pid_mx rMN *m invmx (col_ebase MN).\npose U : 'M_(n, rMN) := invmx (row_ebase MN) *m pid_mx rMN.\nsuffices: L *m M *m (N *m U) = 1%:M by apply: mulmx1_min.\nrewrite mulmxA -(mulmxA L) -[M *m N]mulmx_ebase -/MN.\nby rewrite !mulmxA mulmxKV // mulmxK // !pid_mx_id /rMN ?pid_mx_1.\nQed.\nArguments mulmx_max_rank [r m n].\n\nLemma mxrank_tr m n (A : 'M_(m, n)) : \\rank A^T = \\rank A.\nProof.\napply/eqP; rewrite eqn_leq -{3}[A]trmxK -{1}(mulmx_base A) -{1}(mulmx_base A^T).\nby rewrite !trmx_mul !mulmx_max_rank.\nQed.\n\nLemma mxrank_add m n (A B : 'M_(m, n)) : \\rank (A + B)%R <= \\rank A + \\rank B.\nProof.\nby rewrite -{1}(mulmx_base A) -{1}(mulmx_base B) -mul_row_col mulmx_max_rank.\nQed.\n\nLemma mxrankM_maxl m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  \\rank (A *m B) <= \\rank A.\nProof. by rewrite -{1}(mulmx_base A) -mulmxA mulmx_max_rank. Qed.\n\nLemma mxrankM_maxr m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  \\rank (A *m B) <= \\rank B.\nProof. by rewrite -mxrank_tr -(mxrank_tr B) trmx_mul mxrankM_maxl. Qed.\n\nLemma mxrank_scale m n a (A : 'M_(m, n)) : \\rank (a *: A) <= \\rank A.\nProof. by rewrite -mul_scalar_mx mxrankM_maxr. Qed.\n\nLemma mxrank_scale_nz m n a (A : 'M_(m, n)) :\n   a != 0 -> \\rank (a *: A) = \\rank A.\nProof.\nmove=> nza; apply/eqP; rewrite eqn_leq -{3}[A]scale1r -(mulVf nza).\nby rewrite -scalerA !mxrank_scale.\nQed.\n\nLemma mxrank_opp m n (A : 'M_(m, n)) : \\rank (- A) = \\rank A.\nProof. by rewrite -scaleN1r mxrank_scale_nz // oppr_eq0 oner_eq0. Qed.\n\nLemma mxrank0 m n : \\rank (0 : 'M_(m, n)) = 0%N.\nProof. by apply/eqP; rewrite -leqn0 -(@mulmx0 _ m 0 n 0) mulmx_max_rank. Qed.\n\nLemma mxrank_eq0 m n (A : 'M_(m, n)) : (\\rank A == 0%N) = (A == 0).\nProof.\napply/eqP/eqP=> [rA0 | ->{A}]; last exact: mxrank0.\nmove: (col_base A) (row_base A) (mulmx_base A); rewrite rA0 => Ac Ar <-.\nby rewrite [Ac]thinmx0 mul0mx.\nQed.\n\nLemma mulmx_coker m n (A : 'M_(m, n)) : A *m cokermx A = 0.\nProof.\nby rewrite -{1}[A]mulmx_ebase -!mulmxA mulKVmx // mul_pid_mx_copid ?mulmx0.\nQed.\n\nLemma submxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS = (A *m cokermx B == 0).\nProof. by rewrite unlock. Qed.\n\nLemma mulmxKpV m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> A *m pinvmx B *m B = A.\nProof.\nrewrite submxE !mulmxA mulmxBr mulmx1 subr_eq0 => /eqP defA.\nrewrite -{4}[B]mulmx_ebase -!mulmxA mulKmx //.\nby rewrite (mulmxA (pid_mx _)) pid_mx_id // !mulmxA -{}defA mulmxKV.\nQed.\n\nLemma submxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (exists D, A = D *m B) (A <= B)%MS.\nProof.\napply: (iffP idP) => [/mulmxKpV | [D ->]]; first by exists (A *m pinvmx B).\nby rewrite submxE -mulmxA mulmx_coker mulmx0.\nQed.\nArguments submxP {m1 m2 n A B}.\n\nLemma submx_refl m n (A : 'M_(m, n)) : (A <= A)%MS.\nProof. by rewrite submxE mulmx_coker. Qed.\nHint Resolve submx_refl : core.\n\nLemma submxMl m n p (D : 'M_(m, n)) (A : 'M_(n, p)) : (D *m A <= A)%MS.\nProof. by rewrite submxE -mulmxA mulmx_coker mulmx0. Qed.\n\nLemma submxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  (A <= B)%MS -> (A *m C <= B *m C)%MS.\nProof. by case/submxP=> D ->; rewrite -mulmxA submxMl. Qed.\n\nLemma mulmx_sub m n1 n2 p (C : 'M_(m, n1)) A (B : 'M_(n2, p)) :\n  (A <= B -> C *m A <= B)%MS.\nProof. by case/submxP=> D ->; rewrite mulmxA submxMl. Qed.\n\nLemma submx_trans m1 m2 m3 n\n                 (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= B -> B <= C -> A <= C)%MS.\nProof. by case/submxP=> D ->{A}; apply: mulmx_sub. Qed.\n\nLemma ltmx_sub_trans m1 m2 m3 n\n                     (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A < B)%MS -> (B <= C)%MS -> (A < C)%MS.\nProof.\ncase/andP=> sAB ltAB sBC; rewrite ltmxE (submx_trans sAB) //.\nby apply: contra ltAB; apply: submx_trans.\nQed.\n\nLemma sub_ltmx_trans m1 m2 m3 n\n                     (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= B)%MS -> (B < C)%MS -> (A < C)%MS.\nProof.\nmove=> sAB /andP[sBC ltBC]; rewrite ltmxE (submx_trans sAB) //.\nby apply: contra ltBC => sCA; apply: submx_trans sAB.\nQed.\n\nLemma ltmx_trans m n : transitive (@ltmx m m n).\nProof. by move=> A B C; move/ltmxW; apply: sub_ltmx_trans. Qed.\n\nLemma ltmx_irrefl m n : irreflexive (@ltmx m m n).\nProof. by move=> A; rewrite /ltmx submx_refl andbF. Qed.\n\nLemma sub0mx m1 m2 n (A : 'M_(m2, n)) : ((0 : 'M_(m1, n)) <= A)%MS.\nProof. by rewrite submxE mul0mx. Qed.\n\nLemma submx0null m1 m2 n (A : 'M[F]_(m1, n)) :\n  (A <= (0 : 'M_(m2, n)))%MS -> A = 0.\nProof. by case/submxP=> D; rewrite mulmx0. Qed.\n\nLemma submx0 m n (A : 'M_(m, n)) : (A <= (0 : 'M_n))%MS = (A == 0).\nProof. by apply/idP/eqP=> [|->]; [apply: submx0null | apply: sub0mx]. Qed.\n\nLemma lt0mx m n (A : 'M_(m, n)) : ((0 : 'M_n) < A)%MS = (A != 0).\nProof. by rewrite /ltmx sub0mx submx0. Qed.\n\nLemma ltmx0 m n (A : 'M[F]_(m, n)) : (A < (0 : 'M_n))%MS = false.\nProof. by rewrite /ltmx sub0mx andbF. Qed.\n\nLemma eqmx0P m n (A : 'M_(m, n)) : reflect (A = 0) (A == (0 : 'M_n))%MS.\nProof. by rewrite submx0 sub0mx andbT; apply: eqP. Qed.\n\nLemma eqmx_eq0 m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B)%MS -> (A == 0) = (B == 0).\nProof. by move=> eqAB; rewrite -!submx0 eqAB. Qed.\n\nLemma addmx_sub m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m1, n)) (C : 'M_(m2, n)) :\n  (A <= C)%MS -> (B <= C)%MS -> ((A + B)%R <= C)%MS.\nProof.\nby case/submxP=> A' ->; case/submxP=> B' ->; rewrite -mulmxDl submxMl.\nQed.\n\nLemma summx_sub m1 m2 n (B : 'M_(m2, n))\n                I (r : seq I) (P : pred I) (A_ : I -> 'M_(m1, n)) :\n  (forall i, P i -> A_ i <= B)%MS -> ((\\sum_(i <- r | P i) A_ i)%R <= B)%MS.\nProof.\nby move=> leAB; elim/big_ind: _ => // [|C D]; [apply/sub0mx | apply/addmx_sub].\nQed.\n\nLemma scalemx_sub m1 m2 n a (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> (a *: A <= B)%MS.\nProof. by case/submxP=> A' ->; rewrite scalemxAl submxMl. Qed.\n\nLemma row_sub m n i (A : 'M_(m, n)) : (row i A <= A)%MS.\nProof. by rewrite rowE submxMl. Qed.\n\nLemma eq_row_sub m n v (A : 'M_(m, n)) i : row i A = v -> (v <= A)%MS.\nProof. by move <-; rewrite row_sub. Qed.\n\nLemma nz_row_sub m n (A : 'M_(m, n)) : (nz_row A <= A)%MS.\nProof. by rewrite /nz_row; case: pickP => [i|] _; rewrite ?row_sub ?sub0mx. Qed.\n\nLemma row_subP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (forall i, row i A <= B)%MS (A <= B)%MS.\nProof.\napply: (iffP idP) => [sAB i|sAB].\n  by apply: submx_trans sAB; apply: row_sub.\nrewrite submxE; apply/eqP/row_matrixP=> i; apply/eqP.\nby rewrite row_mul row0 -submxE.\nQed.\nArguments row_subP {m1 m2 n A B}.\n\nLemma rV_subP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (forall v : 'rV_n, v <= A -> v <= B)%MS (A <= B)%MS.\nProof.\napply: (iffP idP) => [sAB v Av | sAB]; first exact: submx_trans sAB.\nby apply/row_subP=> i; rewrite sAB ?row_sub.\nQed.\nArguments rV_subP {m1 m2 n A B}.\n\nLemma row_subPn m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (exists i, ~~ (row i A <= B)%MS) (~~ (A <= B)%MS).\nProof. by rewrite (sameP row_subP forallP); apply: forallPn. Qed.\n\nLemma sub_rVP n (u v : 'rV_n) : reflect (exists a, u = a *: v) (u <= v)%MS.\nProof.\napply: (iffP submxP) => [[w ->] | [a ->]].\n  by exists (w 0 0); rewrite -mul_scalar_mx -mx11_scalar.\nby exists a%:M; rewrite mul_scalar_mx.\nQed.\n\nLemma rank_rV n (v : 'rV_n) : \\rank v = (v != 0).\nProof.\ncase: eqP => [-> | nz_v]; first by rewrite mxrank0.\nby apply/eqP; rewrite eqn_leq rank_leq_row lt0n mxrank_eq0; apply/eqP.\nQed.\n\nLemma rowV0Pn m n (A : 'M_(m, n)) :\n  reflect (exists2 v : 'rV_n, v <= A & v != 0)%MS (A != 0).\nProof.\nrewrite -submx0; apply: (iffP idP) => [| [v svA]]; last first.\n  by rewrite -submx0; apply: contra (submx_trans _).\nby case/row_subPn=> i; rewrite submx0; exists (row i A); rewrite ?row_sub.\nQed.\n\nLemma rowV0P m n (A : 'M_(m, n)) :\n  reflect (forall v : 'rV_n, v <= A -> v = 0)%MS (A == 0).\nProof.\nrewrite -[A == 0]negbK; case: rowV0Pn => IH.\n  by right; case: IH => v svA nzv IH; case/eqP: nzv; apply: IH.\nby left=> v svA; apply/eqP; apply/idPn=> nzv; case: IH; exists v.\nQed.\n\nLemma submx_full m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  row_full B -> (A <= B)%MS.\nProof.\nby rewrite submxE /cokermx => /eqnP->; rewrite /copid_mx pid_mx_1 subrr !mulmx0.\nQed.\n\nLemma row_fullP m n (A : 'M_(m, n)) :\n  reflect (exists B, B *m A = 1%:M) (row_full A).\nProof.\napply: (iffP idP) => [Afull | [B kA]].\n  by exists (1%:M *m pinvmx A); apply: mulmxKpV (submx_full _ Afull).\nby rewrite [_ A]eqn_leq rank_leq_col (mulmx1_min_rank B 1%:M) ?mulmx1.\nQed.\nArguments row_fullP {m n A}.\n\nLemma row_full_inj m n p A : row_full A -> injective (@mulmx _ m n p A).\nProof.\ncase/row_fullP=> A' A'K; apply: can_inj (mulmx A') _ => B.\nby rewrite mulmxA A'K mul1mx.\nQed.\n\nLemma row_freeP m n (A : 'M_(m, n)) :\n  reflect (exists B, A *m B = 1%:M) (row_free A).\nProof.\nrewrite /row_free -mxrank_tr.\napply: (iffP row_fullP) => [] [B kA];\n  by exists B^T; rewrite -trmx1 -kA trmx_mul ?trmxK.\nQed.\n\nLemma row_free_inj m n p A : row_free A -> injective ((@mulmx _ m n p)^~ A).\nProof.\ncase/row_freeP=> A' AK; apply: can_inj (mulmx^~ A') _ => B.\nby rewrite -mulmxA AK mulmx1.\nQed.\n\nLemma row_free_unit n (A : 'M_n) : row_free A = (A \\in unitmx).\nProof.\napply/row_fullP/idP=> [[A'] | uA]; first by case/mulmx1_unit.\nby exists (invmx A); rewrite mulVmx.\nQed.\n\nLemma row_full_unit n (A : 'M_n) : row_full A = (A \\in unitmx).\nProof. exact: row_free_unit. Qed.\n\nLemma mxrank_unit n (A : 'M_n) : A \\in unitmx -> \\rank A = n.\nProof. by rewrite -row_full_unit => /eqnP. Qed.\n\nLemma mxrank1 n : \\rank (1%:M : 'M_n) = n.\nProof. by apply: mxrank_unit; apply: unitmx1. Qed.\n\nLemma mxrank_delta m n i j : \\rank (delta_mx i j : 'M_(m, n)) = 1%N.\nProof.\napply/eqP; rewrite eqn_leq lt0n mxrank_eq0.\nrewrite -{1}(mul_delta_mx (0 : 'I_1)) mulmx_max_rank.\nby apply/eqP; move/matrixP; move/(_ i j); move/eqP; rewrite !mxE !eqxx oner_eq0.\nQed.\n\nLemma mxrankS m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> \\rank A <= \\rank B.\nProof. by case/submxP=> D ->; rewrite mxrankM_maxr. Qed.\n\nLemma submx1 m n (A : 'M_(m, n)) : (A <= 1%:M)%MS.\nProof. by rewrite submx_full // row_full_unit unitmx1. Qed.\n\nLemma sub1mx m n (A : 'M_(m, n)) : (1%:M <= A)%MS = row_full A.\nProof.\napply/idP/idP; last exact: submx_full.\nby move/mxrankS; rewrite mxrank1 col_leq_rank.\nQed.\n\nLemma ltmx1 m n (A : 'M_(m, n)) : (A < 1%:M)%MS = ~~ row_full A.\nProof. by rewrite /ltmx sub1mx submx1. Qed.\n\nLemma lt1mx m n (A : 'M_(m, n)) : (1%:M < A)%MS = false.\nProof. by rewrite /ltmx submx1 andbF. Qed.\n\nLemma eqmxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :=: B)%MS (A == B)%MS.\nProof.\napply: (iffP andP) => [[sAB sBA] | eqAB]; last by rewrite !eqAB.\nsplit=> [|m3 C]; first by apply/eqP; rewrite eqn_leq !mxrankS.\nsplit; first by apply/idP/idP; apply: submx_trans.\nby apply/idP/idP=> sC; apply: submx_trans sC _.\nQed.\nArguments eqmxP {m1 m2 n A B}.\n\nLemma rV_eqP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (forall u : 'rV_n, (u <= A) = (u <= B))%MS (A == B)%MS.\nProof.\napply: (iffP idP) => [eqAB u | eqAB]; first by rewrite (eqmxP eqAB).\nby apply/andP; split; apply/rV_subP=> u; rewrite eqAB.\nQed.\n\nLemma eqmx_refl m1 n (A : 'M_(m1, n)) : (A :=: A)%MS.\nProof. by []. Qed.\n\nLemma eqmx_sym m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B)%MS -> (B :=: A)%MS.\nProof. by move=> eqAB; split=> [|m3 C]; rewrite !eqAB. Qed.\n\nLemma eqmx_trans m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A :=: B)%MS -> (B :=: C)%MS -> (A :=: C)%MS.\nProof. by move=> eqAB eqBC; split=> [|m4 D]; rewrite !eqAB !eqBC. Qed.\n\nLemma eqmx_rank m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A == B)%MS -> \\rank A = \\rank B.\nProof. by move/eqmxP->. Qed.\n\nLemma lt_eqmx m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n    (A :=: B)%MS ->\n  forall C : 'M_(m3, n), (((A < C) = (B < C))%MS * ((C < A) = (C < B))%MS)%type.\nProof. by move=> eqAB C; rewrite /ltmx !eqAB. Qed.\n\nLemma eqmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  (A :=: B)%MS -> (A *m C :=: B *m C)%MS.\nProof. by move=> eqAB; apply/eqmxP; rewrite !submxMr ?eqAB. Qed.\n\nLemma eqmxMfull m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  row_full A -> (A *m B :=: B)%MS.\nProof.\ncase/row_fullP=> A' A'A; apply/eqmxP; rewrite submxMl /=.\nby apply/submxP; exists A'; rewrite mulmxA A'A mul1mx.\nQed.\n\nLemma eqmx0 m n : ((0 : 'M[F]_(m, n)) :=: (0 : 'M_n))%MS.\nProof. by apply/eqmxP; rewrite !sub0mx. Qed.\n\nLemma eqmx_scale m n a (A : 'M_(m, n)) : a != 0 -> (a *: A :=: A)%MS.\nProof.\nmove=> nz_a; apply/eqmxP; rewrite scalemx_sub //.\nby rewrite -{1}[A]scale1r -(mulVf nz_a) -scalerA scalemx_sub.\nQed.\n\nLemma eqmx_opp m n (A : 'M_(m, n)) : (- A :=: A)%MS.\nProof.\nby rewrite -scaleN1r; apply: eqmx_scale => //; rewrite oppr_eq0 oner_eq0.\nQed.\n\nLemma submxMfree m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  row_free C -> (A *m C <= B *m C)%MS = (A <= B)%MS.\nProof.\ncase/row_freeP=> C' C_C'_1; apply/idP/idP=> sAB; last exact: submxMr.\nby rewrite -[A]mulmx1 -[B]mulmx1 -C_C'_1 !mulmxA submxMr.\nQed.\n\nLemma eqmxMfree m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  row_free C -> (A *m C :=: B *m C)%MS -> (A :=: B)%MS.\nProof.\nby move=> Cfree eqAB; apply/eqmxP; move/eqmxP: eqAB; rewrite !submxMfree.\nQed.\n\nLemma mxrankMfree m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  row_free B -> \\rank (A *m B) = \\rank A.\nProof.\nby move=> Bfree; rewrite -mxrank_tr trmx_mul eqmxMfull /row_full mxrank_tr.\nQed.\n\nLemma eq_row_base m n (A : 'M_(m, n)) : (row_base A :=: A)%MS.\nProof.\napply/eqmxP; apply/andP; split; apply/submxP.\n  exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\n  by rewrite -{8}[A]mulmx_ebase !mulmxA mulmxKV // pid_mx_id.\nexists (col_ebase A *m pid_mx (\\rank A)).\nby rewrite mulmxA -(mulmxA _ _ (pid_mx _)) pid_mx_id // mulmx_ebase.\nQed.\n\nLet qidmx_eq1 n (A : 'M_n) : qidmx A = (A == 1%:M).\nProof. by rewrite /qidmx eqxx pid_mx_1. Qed.\n\nLet genmx_witnessP m n (A : 'M_(m, n)) :\n  equivmx A (row_full A) (genmx_witness A).\nProof.\nrewrite /equivmx qidmx_eq1 /genmx_witness.\ncase fullA: (row_full A); first by rewrite eqxx sub1mx submx1 fullA.\nset B := _ *m _; have defB : (B == A)%MS.\n  apply/andP; split; apply/submxP.\n    exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\n    by rewrite -{3}[A]mulmx_ebase !mulmxA mulmxKV // pid_mx_id.\n  exists (col_ebase A *m pid_mx (\\rank A)).\n  by rewrite mulmxA -(mulmxA _ _ (pid_mx _)) pid_mx_id // mulmx_ebase.\nrewrite defB -negb_add addbF; case: eqP defB => // ->.\nby rewrite sub1mx fullA.\nQed.\n\nLemma genmxE m n (A : 'M_(m, n)) : (<<A>> :=: A)%MS.\nProof.\nby rewrite unlock; apply/eqmxP; case/andP: (chooseP (genmx_witnessP A)).\nQed.\n\nLemma eq_genmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B -> <<A>> = <<B>>)%MS.\nProof.\nmove=> eqAB; rewrite unlock.\nhave{eqAB} eqAB: equivmx A (row_full A) =1 equivmx B (row_full B).\n  by move=> C; rewrite /row_full /equivmx !eqAB.\nrewrite (eq_choose eqAB) (choose_id _ (genmx_witnessP B)) //.\nby rewrite -eqAB genmx_witnessP.\nQed.\n\nLemma genmxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (<<A>> = <<B>>)%MS (A == B)%MS.\nProof.\napply: (iffP idP) => eqAB; first exact: eq_genmx (eqmxP _).\nby rewrite -!(genmxE A) eqAB !genmxE andbb.\nQed.\nArguments genmxP {m1 m2 n A B}.\n\nLemma genmx0 m n : <<0 : 'M_(m, n)>>%MS = 0.\nProof. by apply/eqP; rewrite -submx0 genmxE sub0mx. Qed.\n\nLemma genmx1 n : <<1%:M : 'M_n>>%MS = 1%:M.\nProof.\nrewrite unlock; case/andP: (chooseP (@genmx_witnessP n n 1%:M)) => _ /eqP.\nby rewrite qidmx_eq1 row_full_unit unitmx1 => /eqP.\nQed.\n\nLemma genmx_id m n (A : 'M_(m, n)) : (<<<<A>>>> = <<A>>)%MS.\nProof. by apply: eq_genmx; apply: genmxE. Qed.\n\nLemma row_base_free m n (A : 'M_(m, n)) : row_free (row_base A).\nProof. by apply/eqnP; rewrite eq_row_base. Qed.\n\nLemma mxrank_gen m n (A : 'M_(m, n)) : \\rank <<A>> = \\rank A.\nProof. by rewrite genmxE. Qed.\n\nLemma col_base_full m n (A : 'M_(m, n)) : row_full (col_base A).\nProof.\napply/row_fullP; exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\nby rewrite !mulmxA mulmxKV // pid_mx_id // pid_mx_1.\nQed.\nHint Resolve row_base_free col_base_full : core.\n\nLemma mxrank_leqif_sup m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> \\rank A <= \\rank B ?= iff (B <= A)%MS.\nProof.\nmove=> sAB; split; first by rewrite mxrankS.\napply/idP/idP=> [| sBA]; last by rewrite eqn_leq !mxrankS.\ncase/submxP: sAB => D ->; set r := \\rank B; rewrite -(mulmx_base B) mulmxA.\nrewrite mxrankMfree // => /row_fullP[E kE].\nby rewrite -[rB in _ *m rB]mul1mx -kE -(mulmxA E) (mulmxA _ E) submxMl.\nQed.\n\nLemma mxrank_leqif_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> \\rank A <= \\rank B ?= iff (A == B)%MS.\nProof. by move=> sAB; rewrite sAB; apply: mxrank_leqif_sup. Qed.\n\nLemma ltmxErank m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A < B)%MS = (A <= B)%MS && (\\rank A < \\rank B).\nProof.\nby apply: andb_id2l => sAB; rewrite (ltn_leqif (mxrank_leqif_sup sAB)).\nQed.\n\nLemma rank_ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A < B)%MS -> \\rank A < \\rank B.\nProof. by rewrite ltmxErank => /andP[]. Qed.\n\nLemma eqmx_cast m1 m2 n (A : 'M_(m1, n)) e :\n  ((castmx e A : 'M_(m2, n)) :=: A)%MS.\nProof. by case: e A; case: m2 / => A e; rewrite castmx_id. Qed.\n\nLemma eqmx_conform m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (conform_mx A B :=: A \\/ conform_mx A B :=: B)%MS.\nProof.\ncase: (eqVneq m2 m1) => [-> | neqm12] in B *.\n  by right; rewrite conform_mx_id.\nby left; rewrite nonconform_mx ?neqm12.\nQed.\n\nLet eqmx_sum_nop m n (A : 'M_(m, n)) : (addsmx_nop A :=: A)%MS.\nProof.\ncase: (eqmx_conform <<A>>%MS A) => // eq_id_gen.\nexact: eqmx_trans (genmxE A).\nQed.\n\nSection AddsmxSub.\n\nVariable (m1 m2 n : nat) (A : 'M[F]_(m1, n)) (B : 'M[F]_(m2, n)).\n\nLemma col_mx_sub m3 (C : 'M_(m3, n)) :\n  (col_mx A B <= C)%MS = (A <= C)%MS && (B <= C)%MS.\nProof.\nrewrite !submxE mul_col_mx -col_mx0.\nby apply/eqP/andP; [case/eq_col_mx=> -> -> | case; do 2!move/eqP->].\nQed.\n\nLemma addsmxE : (A + B :=: col_mx A B)%MS.\nProof.\nhave:= submx_refl (col_mx A B); rewrite col_mx_sub; case/andP=> sAS sBS.\nrewrite unlock; do 2?case: eqP => [AB0 | _]; last exact: genmxE.\n  by apply/eqmxP; rewrite !eqmx_sum_nop sBS col_mx_sub AB0 sub0mx /=.\nby apply/eqmxP; rewrite !eqmx_sum_nop sAS col_mx_sub AB0 sub0mx andbT /=.\nQed.\n\nLemma addsmx_sub m3 (C : 'M_(m3, n)) :\n  (A + B <= C)%MS = (A <= C)%MS && (B <= C)%MS.\nProof. by rewrite addsmxE col_mx_sub. Qed.\n\nLemma addsmxSl : (A <= A + B)%MS.\nProof. by have:= submx_refl (A + B)%MS; rewrite addsmx_sub; case/andP. Qed.\n\nLemma addsmxSr : (B <= A + B)%MS.\nProof. by have:= submx_refl (A + B)%MS; rewrite addsmx_sub; case/andP. Qed.\n\nLemma addsmx_idPr : reflect (A + B :=: B)%MS (A <= B)%MS.\nProof.\nhave:= @eqmxP _ _ _ (A + B)%MS B.\nby rewrite addsmxSr addsmx_sub submx_refl !andbT.\nQed.\n\nLemma addsmx_idPl : reflect (A + B :=: A)%MS (B <= A)%MS.\nProof.\nhave:= @eqmxP _ _ _ (A + B)%MS A.\nby rewrite addsmxSl addsmx_sub submx_refl !andbT.\nQed.\n\nEnd AddsmxSub.\n\nLemma adds0mx m1 m2 n (B : 'M_(m2, n)) : ((0 : 'M_(m1, n)) + B :=: B)%MS.\nProof. by apply/eqmxP; rewrite addsmx_sub sub0mx addsmxSr /= andbT. Qed.\n\nLemma addsmx0 m1 m2 n (A : 'M_(m1, n)) : (A + (0 : 'M_(m2, n)) :=: A)%MS.\nProof. by apply/eqmxP; rewrite addsmx_sub sub0mx addsmxSl /= !andbT. Qed.\n\nLet addsmx_nop_eq0 m n (A : 'M_(m, n)) : (addsmx_nop A == 0) = (A == 0).\nProof. by rewrite -!submx0 eqmx_sum_nop. Qed.\n\nLet addsmx_nop0 m n : addsmx_nop (0 : 'M_(m, n)) = 0.\nProof. by apply/eqP; rewrite addsmx_nop_eq0. Qed.\n\nLet addsmx_nop_id n (A : 'M_n) : addsmx_nop A = A.\nProof. exact: conform_mx_id. Qed.\n\nLemma addsmxC m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A + B = B + A)%MS.\nProof.\nhave: (A + B == B + A)%MS.\n  by apply/andP; rewrite !addsmx_sub andbC -addsmx_sub andbC -addsmx_sub.\nmove/genmxP; rewrite [@addsmx]unlock -!submx0 !submx0.\nby do 2!case: eqP => [// -> | _]; rewrite ?genmx_id ?addsmx_nop0.\nQed.\n\nLemma adds0mx_id m1 n (B : 'M_n) : ((0 : 'M_(m1, n)) + B)%MS = B.\nProof. by rewrite unlock eqxx addsmx_nop_id. Qed.\n\nLemma addsmx0_id m2 n (A : 'M_n) : (A + (0 : 'M_(m2, n)))%MS = A.\nProof. by rewrite addsmxC adds0mx_id. Qed.\n\nLemma addsmxA m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A + (B + C) = A + B + C)%MS.\nProof.\nhave: (A + (B + C) :=: A + B + C)%MS.\n  by apply/eqmxP/andP; rewrite !addsmx_sub -andbA andbA -!addsmx_sub.\nrewrite {1 3}[in @addsmx m1]unlock [in @addsmx n]unlock !addsmx_nop_id -!submx0.\nrewrite !addsmx_sub ![@addsmx]unlock -!submx0; move/eq_genmx.\nby do 3!case: (_ <= 0)%MS; rewrite //= !genmx_id.\nQed.\n\nCanonical addsmx_monoid n :=\n  Monoid.Law (@addsmxA n n n n) (@adds0mx_id n n) (@addsmx0_id n n).\nCanonical addsmx_comoid n := Monoid.ComLaw (@addsmxC n n n).\n\nLemma addsmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  ((A + B)%MS *m C :=: A *m C + B *m C)%MS.\nProof. by apply/eqmxP; rewrite !addsmxE -!mul_col_mx !submxMr ?addsmxE. Qed.\n\nLemma addsmxS m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                            (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A <= C -> B <= D -> A + B <= C + D)%MS.\nProof.\nmove=> sAC sBD.\nby rewrite addsmx_sub {1}addsmxC !(submx_trans _ (addsmxSr _ _)).\nQed.\n\nLemma addmx_sub_adds m m1 m2 n (A : 'M_(m, n)) (B : 'M_(m, n))\n                               (C : 'M_(m1, n)) (D : 'M_(m2, n)) :\n  (A <= C -> B <= D -> (A + B)%R <= C + D)%MS.\nProof.\nmove=> sAC; move/(addsmxS sAC); apply: submx_trans.\nby rewrite addmx_sub ?addsmxSl ?addsmxSr.\nQed.\n\nLemma addsmx_addKl n m1 m2 (A : 'M_(m1, n)) (B C : 'M_(m2, n)) :\n  (B <= A)%MS -> (A + (B + C)%R :=: A + C)%MS.\nProof.\nmove=> sBA; apply/eqmxP; rewrite !addsmx_sub !addsmxSl.\nby rewrite -{3}[C](addKr B) !addmx_sub_adds ?eqmx_opp.\nQed.\n\nLemma addsmx_addKr n m1 m2 (A B : 'M_(m1, n)) (C : 'M_(m2, n)) :\n  (B <= C)%MS -> ((A + B)%R + C :=: A + C)%MS.\nProof. by rewrite -!(addsmxC C) addrC; apply: addsmx_addKl. Qed.\n\nLemma adds_eqmx m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                              (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A :=: C -> B :=: D -> A + B :=: C + D)%MS.\nProof. by move=> eqAC eqBD; apply/eqmxP; rewrite !addsmxS ?eqAC ?eqBD. Qed.\n\nLemma genmx_adds m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (<<(A + B)%MS>> = <<A>> + <<B>>)%MS.\nProof.\nrewrite -(eq_genmx (adds_eqmx (genmxE A) (genmxE B))).\nby rewrite [@addsmx]unlock !addsmx_nop_id !(fun_if (@genmx _ _)) !genmx_id.\nQed.\n\nLemma sub_addsmxP m1 m2 m3 n\n                  (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  reflect (exists u, A = u.1 *m B + u.2 *m C) (A <= B + C)%MS.\nProof.\napply: (iffP idP) => [|[u ->]]; last by rewrite addmx_sub_adds ?submxMl.\nrewrite addsmxE; case/submxP=> u ->; exists (lsubmx u, rsubmx u).\nby rewrite -mul_row_col hsubmxK.\nQed.\nArguments sub_addsmxP {m1 m2 m3 n A B C}.\n\nVariable I : finType.\nImplicit Type P : pred I.\n\nLemma genmx_sums P n (B_ : I -> 'M_n) :\n  <<(\\sum_(i | P i) B_ i)%MS>>%MS = (\\sum_(i | P i) <<B_ i>>)%MS.\nProof. exact: (big_morph _ (@genmx_adds n n n) (@genmx0 n n)). Qed.\n\nLemma sumsmx_sup i0 P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) :\n  P i0 -> (A <= B_ i0)%MS -> (A <= \\sum_(i | P i) B_ i)%MS.\nProof.\nby move=> Pi0 sAB; apply: submx_trans sAB _; rewrite (bigD1 i0) // addsmxSl.\nQed.\nArguments sumsmx_sup i0 [P m n A B_].\n\nLemma sumsmx_subP P m n (A_ : I -> 'M_n) (B : 'M_(m, n)) :\n  reflect (forall i, P i -> A_ i <= B)%MS (\\sum_(i | P i) A_ i <= B)%MS.\nProof.\napply: (iffP idP) => [sAB i Pi | sAB].\n  by apply: submx_trans sAB; apply: sumsmx_sup Pi _.\nby elim/big_rec: _ => [|i Ai Pi sAiB]; rewrite ?sub0mx // addsmx_sub sAB.\nQed.\n\nLemma summx_sub_sums P m n (A : I -> 'M[F]_(m, n)) B :\n    (forall i, P i -> A i <= B i)%MS ->\n  ((\\sum_(i | P i) A i)%R <= \\sum_(i | P i) B i)%MS.\nProof.\nby move=> sAB; apply: summx_sub => i Pi; rewrite (sumsmx_sup i) ?sAB.\nQed.\n\nLemma sumsmxS P n (A B : I -> 'M[F]_n) :\n    (forall i, P i -> A i <= B i)%MS ->\n  (\\sum_(i | P i) A i <= \\sum_(i | P i) B i)%MS.\nProof.\nby move=> sAB; apply/sumsmx_subP=> i Pi; rewrite (sumsmx_sup i) ?sAB.\nQed.\n\nLemma eqmx_sums P n (A B : I -> 'M[F]_n) :\n    (forall i, P i -> A i :=: B i)%MS ->\n  (\\sum_(i | P i) A i :=: \\sum_(i | P i) B i)%MS.\nProof. by move=> eqAB; apply/eqmxP; rewrite !sumsmxS // => i; move/eqAB->. Qed.\n\nLemma sub_sumsmxP P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) :\n  reflect (exists u_, A = \\sum_(i | P i) u_ i *m B_ i)\n          (A <= \\sum_(i | P i) B_ i)%MS.\nProof.\napply: (iffP idP) => [| [u_ ->]]; last first.\n  by apply: summx_sub_sums => i _; apply: submxMl.\nhave [b] := ubnP #|P|; elim: b => // b IHb in P A *.\ncase: (pickP P) => [i Pi | P0 _]; last first.\n  rewrite big_pred0 //; move/submx0null->.\n  by exists (fun _ => 0); rewrite big_pred0.\nrewrite (cardD1x Pi) (bigD1 i) //= => /IHb{b IHb} /= IHi /sub_addsmxP[u ->].\nhave [u_ ->] := IHi _ (submxMl u.2 _).\nexists [eta u_ with i |-> u.1]; rewrite (bigD1 i Pi) /= eqxx; congr (_ + _).\nby apply: eq_bigr => j /andP[_ /negPf->].\nQed.\n\nLemma sumsmxMr_gen P m n A (B : 'M[F]_(m, n)) :\n  ((\\sum_(i | P i) A i)%MS *m B :=: \\sum_(i | P i) <<A i *m B>>)%MS.\nProof.\napply/eqmxP/andP; split; last first.\n  by apply/sumsmx_subP=> i Pi; rewrite genmxE submxMr ?(sumsmx_sup i).\nhave [u ->] := sub_sumsmxP _ _ _ (submx_refl (\\sum_(i | P i) A i)%MS).\nby rewrite mulmx_suml summx_sub_sums // => i _; rewrite genmxE -mulmxA submxMl.\nQed.\n\nLemma sumsmxMr P n (A_ : I -> 'M[F]_n) (B : 'M_n) :\n  ((\\sum_(i | P i) A_ i)%MS *m B :=: \\sum_(i | P i) (A_ i *m B))%MS.\nProof.\nby apply: eqmx_trans (sumsmxMr_gen _ _ _) (eqmx_sums _) => i _; apply: genmxE.\nQed.\n\nLemma rank_pid_mx m n r : r <= m -> r <= n -> \\rank (pid_mx r : 'M_(m, n)) = r.\nProof.\ndo 2!move/subnKC <-; rewrite pid_mx_block block_mxEv row_mx0 -addsmxE addsmx0.\nby rewrite -mxrank_tr tr_row_mx trmx0 trmx1 -addsmxE addsmx0 mxrank1.\nQed.\n\nLemma rank_copid_mx n r : r <= n -> \\rank (copid_mx r : 'M_n) = (n - r)%N.\nProof.\nmove/subnKC <-; rewrite /copid_mx pid_mx_block scalar_mx_block.\nrewrite opp_block_mx !oppr0 add_block_mx !addr0 subrr block_mxEv row_mx0.\nrewrite -addsmxE adds0mx -mxrank_tr tr_row_mx trmx0 trmx1.\nby rewrite -addsmxE adds0mx mxrank1 addKn.\nQed.\n\nLemma mxrank_compl m n (A : 'M_(m, n)) : \\rank A^C = (n - \\rank A)%N.\nProof. by rewrite mxrankMfree ?row_free_unit ?rank_copid_mx. Qed.\n\nLemma mxrank_ker m n (A : 'M_(m, n)) : \\rank (kermx A) = (m - \\rank A)%N.\nProof. by rewrite mxrankMfree ?row_free_unit ?unitmx_inv ?rank_copid_mx. Qed.\n\nLemma kermx_eq0 n m (A : 'M_(m, n)) : (kermx A == 0) = row_free A.\nProof. by rewrite -mxrank_eq0 mxrank_ker subn_eq0 row_leq_rank. Qed.\n\nLemma mxrank_coker m n (A : 'M_(m, n)) : \\rank (cokermx A) = (n - \\rank A)%N.\nProof. by rewrite eqmxMfull ?row_full_unit ?unitmx_inv ?rank_copid_mx. Qed.\n\nLemma cokermx_eq0 n m (A : 'M_(m, n)) : (cokermx A == 0) = row_full A.\nProof. by rewrite -mxrank_eq0 mxrank_coker subn_eq0 col_leq_rank. Qed.\n\nLemma mulmx_ker m n (A : 'M_(m, n)) : kermx A *m A = 0.\nProof.\nby rewrite -{2}[A]mulmx_ebase !mulmxA mulmxKV // mul_copid_mx_pid ?mul0mx.\nQed.\n\nLemma mulmxKV_ker m n p (A : 'M_(n, p)) (B : 'M_(m, n)) :\n  B *m A = 0 -> B *m col_ebase A *m kermx A = B.\nProof.\nrewrite mulmxA mulmxBr mulmx1 mulmxBl mulmxK //.\nrewrite -{1}[A]mulmx_ebase !mulmxA => /(canRL (mulmxK (row_ebase_unit A))).\nrewrite mul0mx // => BA0; apply: (canLR (addrK _)).\nby rewrite -(pid_mx_id _ _ n (rank_leq_col A)) mulmxA BA0 !mul0mx addr0.\nQed.\n\nLemma sub_kermxP p m n (A : 'M_(m, n)) (B : 'M_(p, m)) :\n  reflect (B *m A = 0) (B <= kermx A)%MS.\nProof.\napply: (iffP submxP) => [[D ->]|]; first by rewrite -mulmxA mulmx_ker mulmx0.\nby move/mulmxKV_ker; exists (B *m col_ebase A).\nQed.\n\nLemma mulmx0_rank_max m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  A *m B = 0 -> \\rank A + \\rank B <= n.\nProof.\nmove=> AB0; rewrite -{3}(subnK (rank_leq_row B)) leq_add2r.\nby rewrite -mxrank_ker mxrankS //; apply/sub_kermxP.\nQed.\n\nLemma mxrank_Frobenius m n p q (A : 'M_(m, n)) B (C : 'M_(p, q)) :\n  \\rank (A *m B) + \\rank (B *m C) <= \\rank B + \\rank (A *m B *m C).\nProof.\nrewrite -{2}(mulmx_base (A *m B)) -mulmxA (eqmxMfull _ (col_base_full _)).\nset C2 := row_base _ *m C.\nrewrite -{1}(subnK (rank_leq_row C2)) -(mxrank_ker C2) addnAC leq_add2r.\nrewrite addnC -{1}(mulmx_base B) -mulmxA eqmxMfull //.\nset C1 := _ *m C; rewrite -{2}(subnKC (rank_leq_row C1)) leq_add2l -mxrank_ker.\nrewrite -(mxrankMfree _ (row_base_free (A *m B))).\nhave: (row_base (A *m B) <= row_base B)%MS by rewrite !eq_row_base submxMl.\ncase/submxP=> D defD; rewrite defD mulmxA mxrankMfree ?mxrankS //.\nby apply/sub_kermxP; rewrite -mulmxA (mulmxA D) -defD -/C2 mulmx_ker.\nQed.\n\nLemma mxrank_mul_min m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  \\rank A + \\rank B - n <= \\rank (A *m B).\nProof.\nby have:= mxrank_Frobenius A 1%:M B; rewrite mulmx1 mul1mx mxrank1 leq_subLR.\nQed.\n\nLemma addsmx_compl_full m n (A : 'M_(m, n)) : row_full (A + A^C)%MS.\nProof.\nrewrite /row_full addsmxE; apply/row_fullP.\nexists (row_mx (pinvmx A) (cokermx A)); rewrite mul_row_col.\nrewrite -{2}[A]mulmx_ebase -!mulmxA mulKmx // -mulmxDr !mulmxA.\nby rewrite pid_mx_id ?copid_mx_id // -mulmxDl addrC subrK mul1mx mulVmx.\nQed.\n\nLemma sub_capmx_gen m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= capmx_gen B C)%MS = (A <= B)%MS && (A <= C)%MS.\nProof.\napply/idP/andP=> [sAI | [/submxP[B' ->{A}] /submxP[C' eqBC']]].\n  rewrite !(submx_trans sAI) ?submxMl // /capmx_gen.\n   have:= mulmx_ker (col_mx B C); set K := kermx _.\n   rewrite -{1}[K]hsubmxK mul_row_col; move/(canRL (addrK _))->.\n   by rewrite add0r -mulNmx submxMl.\nhave: (row_mx B' (- C') <= kermx (col_mx B C))%MS.\n  by apply/sub_kermxP; rewrite mul_row_col eqBC' mulNmx subrr.\ncase/submxP=> D; rewrite -[kermx _]hsubmxK mul_mx_row.\nby case/eq_row_mx=> -> _; rewrite -mulmxA submxMl.\nQed.\n\nLet capmx_witnessP m n (A : 'M_(m, n)) : equivmx A (qidmx A) (capmx_witness A).\nProof.\nrewrite /equivmx qidmx_eq1 /qidmx /capmx_witness.\nrewrite -sub1mx; case s1A: (1%:M <= A)%MS => /=; last first.\n  rewrite !genmxE submx_refl /= -negb_add; apply: contra {s1A}(negbT s1A).\n  case: eqP => [<- _| _]; first by rewrite genmxE.\n  by case: eqP A => //= -> A; move/eqP->; rewrite pid_mx_1.\ncase: (m =P n) => [-> | ne_mn] in A s1A *.\n  by rewrite conform_mx_id submx_refl pid_mx_1 eqxx.\nby rewrite nonconform_mx ?submx1 ?s1A ?eqxx //; case: eqP.\nQed.\n\nLet capmx_normP m n (A : 'M_(m, n)) : equivmx_spec A (qidmx A) (capmx_norm A).\nProof. by case/andP: (chooseP (capmx_witnessP A)) => /eqmxP defN /eqP. Qed.\n\nLet capmx_norm_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx A = qidmx B -> (A == B)%MS -> capmx_norm A = capmx_norm B.\nProof.\nmove=> eqABid /eqmxP eqAB.\nhave{eqABid eqAB} eqAB: equivmx A (qidmx A) =1 equivmx B (qidmx B).\n  by move=> C; rewrite /equivmx eqABid !eqAB.\nrewrite {1}/capmx_norm (eq_choose eqAB).\nby apply: choose_id; first rewrite -eqAB; apply: capmx_witnessP.\nQed.\n\nLet capmx_nopP m n (A : 'M_(m, n)) : equivmx_spec A (qidmx A) (capmx_nop A).\nProof.\nrewrite /capmx_nop; case: (eqVneq m n) => [-> | ne_mn] in A *.\n  by rewrite conform_mx_id.\nby rewrite nonconform_mx ?ne_mn //; apply: capmx_normP.\nQed.\n\nLet sub_qidmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx B -> (A <= B)%MS.\nProof.\nrewrite /qidmx => idB; apply: {A}submx_trans (submx1 A) _.\nby case: eqP B idB => [-> _ /eqP-> | _ B]; rewrite (=^~ sub1mx, pid_mx_1).\nQed.\n\nLet qidmx_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx (A :&: B)%MS = qidmx A && qidmx B.\nProof.\nrewrite unlock -sub1mx.\ncase idA: (qidmx A); case idB: (qidmx B); try by rewrite capmx_nopP.\ncase s1B: (_ <= B)%MS; first by rewrite capmx_normP.\napply/idP=> /(sub_qidmx 1%:M).\nby rewrite capmx_normP sub_capmx_gen s1B andbF.\nQed.\n\nLet capmx_eq_norm m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx A = qidmx B -> (A :&: B)%MS = capmx_norm (A :&: B)%MS.\nProof.\nmove=> eqABid; rewrite unlock -sub1mx {}eqABid.\nhave norm_id m (C : 'M_(m, n)) (N := capmx_norm C) : capmx_norm N = N.\n  by apply: capmx_norm_eq; rewrite ?capmx_normP ?andbb.\ncase idB: (qidmx B); last by case: ifP; rewrite norm_id.\nrewrite /capmx_nop; case: (eqVneq m2 n) => [-> | neqm2n] in B idB *.\n  have idN := idB; rewrite -{1}capmx_normP !qidmx_eq1 in idN idB.\n  by rewrite conform_mx_id (eqP idN) (eqP idB).\nby rewrite nonconform_mx ?neqm2n ?norm_id.\nQed.\n\nLemma capmxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :&: B :=: capmx_gen A B)%MS.\nProof.\nrewrite unlock -sub1mx; apply/eqmxP.\nhave:= submx_refl (capmx_gen A B); rewrite !sub_capmx_gen => /andP[sIA sIB].\ncase idA: (qidmx A); first by rewrite !capmx_nopP submx_refl sub_qidmx.\ncase idB: (qidmx B); first by rewrite !capmx_nopP submx_refl sub_qidmx.\ncase s1B: (1%:M <= B)%MS; rewrite !capmx_normP ?sub_capmx_gen sIA ?sIB //=.\nby rewrite submx_refl (submx_trans (submx1 _)).\nQed.\n\nLemma capmxSl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B <= A)%MS.\nProof. by rewrite capmxE submxMl. Qed.\n\nLemma sub_capmx m m1 m2 n (A : 'M_(m, n)) (B : 'M_(m1, n)) (C : 'M_(m2, n)) :\n  (A <= B :&: C)%MS = (A <= B)%MS && (A <= C)%MS.\nProof. by rewrite capmxE sub_capmx_gen. Qed.\n\nLemma capmxC m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B = B :&: A)%MS.\nProof.\nhave [eqAB|] := eqVneq (qidmx A) (qidmx B).\n  rewrite (capmx_eq_norm eqAB) (capmx_eq_norm (esym eqAB)).\n  apply: capmx_norm_eq; first by rewrite !qidmx_cap andbC.\n  by apply/andP; split; rewrite !sub_capmx andbC -sub_capmx.\nby rewrite negb_eqb !unlock => /addbP <-; case: (qidmx A).\nQed.\n\nLemma capmxSr m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B <= B)%MS.\nProof. by rewrite capmxC capmxSl. Qed.\n\nLemma capmx_idPr n m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :&: B :=: B)%MS (B <= A)%MS.\nProof.\nhave:= @eqmxP _ _ _ (A :&: B)%MS B.\nby rewrite capmxSr sub_capmx submx_refl !andbT.\nQed.\n\nLemma capmx_idPl n m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :&: B :=: A)%MS (A <= B)%MS.\nProof. by rewrite capmxC; apply: capmx_idPr. Qed.\n\nLemma capmxS m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                           (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A <= C -> B <= D -> A :&: B <= C :&: D)%MS.\nProof.\nby move=> sAC sBD; rewrite sub_capmx {1}capmxC !(submx_trans (capmxSr _ _)).\nQed.\n\nLemma cap_eqmx m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                             (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A :=: C -> B :=: D -> A :&: B :=: C :&: D)%MS.\nProof. by move=> eqAC eqBD; apply/eqmxP; rewrite !capmxS ?eqAC ?eqBD. Qed.\n\nLemma capmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  ((A :&: B) *m C <= A *m C :&: B *m C)%MS.\nProof. by rewrite sub_capmx !submxMr ?capmxSl ?capmxSr. Qed.\n\nLemma cap0mx m1 m2 n (A : 'M_(m2, n)) : ((0 : 'M_(m1, n)) :&: A)%MS = 0.\nProof. exact: submx0null (capmxSl _ _). Qed.\n\nLemma capmx0 m1 m2 n (A : 'M_(m1, n)) : (A :&: (0 : 'M_(m2, n)))%MS = 0.\nProof. exact: submx0null (capmxSr _ _). Qed.\n\nLemma capmxT m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  row_full B -> (A :&: B :=: A)%MS.\nProof.\nrewrite -sub1mx => s1B; apply/eqmxP.\nby rewrite capmxSl sub_capmx submx_refl (submx_trans (submx1 A)).\nQed.\n\nLemma capTmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  row_full A -> (A :&: B :=: B)%MS.\nProof. by move=> Afull; apply/eqmxP; rewrite capmxC !capmxT ?andbb. Qed.\n\nLet capmx_nop_id n (A : 'M_n) : capmx_nop A = A.\nProof. by rewrite /capmx_nop conform_mx_id. Qed.\n\nLemma cap1mx n (A : 'M_n) : (1%:M :&: A = A)%MS.\nProof. by rewrite unlock qidmx_eq1 eqxx capmx_nop_id. Qed.\n\nLemma capmx1 n (A : 'M_n) : (A :&: 1%:M = A)%MS.\nProof. by rewrite capmxC cap1mx. Qed.\n\nLemma genmx_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  <<A :&: B>>%MS = (<<A>> :&: <<B>>)%MS.\nProof.\nrewrite -(eq_genmx (cap_eqmx (genmxE A) (genmxE B))).\ncase idAB: (qidmx <<A>> || qidmx <<B>>)%MS.\n  rewrite [@capmx]unlock !capmx_nop_id !(fun_if (@genmx _ _)) !genmx_id.\n  by case: (qidmx _) idAB => //= ->.\ncase idA: (qidmx _) idAB => //= idB; rewrite {2}capmx_eq_norm ?idA //.\nset C := (_ :&: _)%MS; have eq_idC: row_full C = qidmx C.\n  rewrite qidmx_cap idA -sub1mx sub_capmx genmxE; apply/andP=> [[s1A]].\n  by case/idP: idA; rewrite qidmx_eq1 -genmx1 (sameP eqP genmxP) submx1.\nrewrite unlock /capmx_norm eq_idC.\nby apply: choose_id (capmx_witnessP _); rewrite -eq_idC genmx_witnessP.\nQed.\n\nLemma capmxA m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A :&: (B :&: C) = A :&: B :&: C)%MS.\nProof.\nrewrite (capmxC A B) capmxC; wlog idA: m1 m3 A C / qidmx A.\n  move=> IH; case idA: (qidmx A); first exact: IH.\n  case idC: (qidmx C); first by rewrite -IH.\n  rewrite (@capmx_eq_norm n m3) ?qidmx_cap ?idA ?idC ?andbF //.\n  rewrite capmx_eq_norm ?qidmx_cap ?idA ?idC ?andbF //.\n  apply: capmx_norm_eq; first by rewrite !qidmx_cap andbAC.\n  by apply/andP; split; rewrite !sub_capmx andbAC -!sub_capmx.\nrewrite -!(capmxC A) [in @capmx m1]unlock idA capmx_nop_id.\nhave [eqBC |] :=eqVneq (qidmx B) (qidmx C).\n  rewrite (@capmx_eq_norm n) ?capmx_nopP // capmx_eq_norm //.\n  by apply: capmx_norm_eq; rewrite ?qidmx_cap ?capmxS ?capmx_nopP.\nby rewrite !unlock capmx_nopP capmx_nop_id; do 2?case: (qidmx _) => //.\nQed.\n\nCanonical capmx_monoid n :=\n   Monoid.Law (@capmxA n n n n) (@cap1mx n) (@capmx1 n).\nCanonical capmx_comoid n := Monoid.ComLaw (@capmxC n n n).\n\nLemma bigcapmx_inf i0 P m n (A_ : I -> 'M_n) (B : 'M_(m, n)) :\n  P i0 -> (A_ i0 <= B -> \\bigcap_(i | P i) A_ i <= B)%MS.\nProof. by move=> Pi0; apply: submx_trans; rewrite (bigD1 i0) // capmxSl. Qed.\n\nLemma sub_bigcapmxP P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) :\n  reflect (forall i, P i -> A <= B_ i)%MS (A <= \\bigcap_(i | P i) B_ i)%MS.\nProof.\napply: (iffP idP) => [sAB i Pi | sAB].\n  by apply: (submx_trans sAB); rewrite (bigcapmx_inf Pi).\nby elim/big_rec: _ => [|i Pi C sAC]; rewrite ?submx1 // sub_capmx sAB.\nQed.\n\nLemma genmx_bigcap P n (A_ : I -> 'M_n) :\n  (<<\\bigcap_(i | P i) A_ i>> = \\bigcap_(i | P i) <<A_ i>>)%MS.\nProof. exact: (big_morph _ (@genmx_cap n n n) (@genmx1 n)). Qed.\n\nLemma matrix_modl m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= C -> A + (B :&: C) :=: (A + B) :&: C)%MS.\nProof.\nmove=> sAC; set D := ((A + B) :&: C)%MS; apply/eqmxP.\nrewrite sub_capmx addsmxS ?capmxSl // addsmx_sub sAC capmxSr /=.\nhave: (D <= B + A)%MS by rewrite addsmxC capmxSl.\ncase/sub_addsmxP=> u defD; rewrite defD addrC addmx_sub_adds ?submxMl //.\nrewrite sub_capmx submxMl -[_ *m B](addrK (u.2 *m A)) -defD.\nby rewrite addmx_sub ?capmxSr // eqmx_opp mulmx_sub.\nQed.\n\nLemma matrix_modr m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (C <= A -> (A :&: B) + C :=: A :&: (B + C))%MS.\nProof. by rewrite !(capmxC A) -!(addsmxC C); apply: matrix_modl. Qed.\n\nLemma capmx_compl m n (A : 'M_(m, n)) : (A :&: A^C)%MS = 0.\nProof.\nset D := (A :&: A^C)%MS; have: (D <= D)%MS by [].\nrewrite sub_capmx andbC => /andP[/submxP[B defB]].\nrewrite submxE => /eqP; rewrite defB -!mulmxA mulKVmx ?copid_mx_id //.\nby rewrite mulmxA => ->; rewrite mul0mx.\nQed.\n\nLemma mxrank_mul_ker m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  (\\rank (A *m B) + \\rank (A :&: kermx B))%N = \\rank A.\nProof.\napply/eqP; set K := kermx B; set C := (A :&: K)%MS.\nrewrite -(eqmxMr B (eq_row_base A)); set K' := _ *m B.\nrewrite -{2}(subnKC (rank_leq_row K')) -mxrank_ker eqn_add2l.\nrewrite -(mxrankMfree _ (row_base_free A)) mxrank_leqif_sup.\n  rewrite sub_capmx -(eq_row_base A) submxMl.\n  by apply/sub_kermxP; rewrite -mulmxA mulmx_ker.\nhave /submxP[C' defC]: (C <= row_base A)%MS by rewrite eq_row_base capmxSl.\nrewrite defC submxMr //; apply/sub_kermxP.\nby rewrite mulmxA -defC; apply/sub_kermxP; rewrite capmxSr.\nQed.\n\nLemma mxrank_injP m n p (A : 'M_(m, n)) (f : 'M_(n, p)) :\n  reflect (\\rank (A *m f) = \\rank A) ((A :&: kermx f)%MS == 0).\nProof.\nrewrite -mxrank_eq0 -(eqn_add2l (\\rank (A *m f))).\nby rewrite mxrank_mul_ker addn0 eq_sym; apply: eqP.\nQed.\n\nLemma mxrank_disjoint_sum m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :&: B)%MS = 0 -> \\rank (A + B)%MS = (\\rank A + \\rank B)%N.\nProof.\nmove=> AB0; pose Ar := row_base A; pose Br := row_base B.\nhave [Afree Bfree]: row_free Ar /\\ row_free Br by rewrite !row_base_free.\nhave: (Ar :&: Br <= A :&: B)%MS by rewrite capmxS ?eq_row_base.\nrewrite {}AB0 submx0 -mxrank_eq0 capmxE mxrankMfree //.\nset Cr := col_mx Ar Br; set Crl := lsubmx _; rewrite mxrank_eq0 => /eqP Crl0.\nrewrite -(adds_eqmx (eq_row_base _) (eq_row_base _)) addsmxE -/Cr.\nsuffices K0: kermx Cr = 0.\n  by apply/eqP; rewrite eqn_leq rank_leq_row -subn_eq0 -mxrank_ker K0 mxrank0.\nmove/eqP: (mulmx_ker Cr); rewrite -[kermx Cr]hsubmxK mul_row_col -/Crl Crl0.\nrewrite mul0mx add0r -mxrank_eq0 mxrankMfree // mxrank_eq0 => /eqP->.\nexact: row_mx0.\nQed.\n\nLemma diffmxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :\\: B :=: A :&: (capmx_gen A B)^C)%MS.\nProof. by rewrite unlock; apply/eqmxP; rewrite !genmxE !capmxE andbb. Qed.\n\nLemma genmx_diff m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (<<A :\\: B>> = A :\\: B)%MS.\nProof. by rewrite [@diffmx]unlock genmx_id. Qed.\n\nLemma diffmxSl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :\\: B <= A)%MS.\nProof. by rewrite diffmxE capmxSl. Qed.\n\nLemma capmx_diff m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  ((A :\\: B) :&: B)%MS = 0.\nProof.\napply/eqP; pose C := capmx_gen A B; rewrite -submx0 -(capmx_compl C).\nby rewrite sub_capmx -capmxE sub_capmx andbAC -sub_capmx -diffmxE -sub_capmx.\nQed.\n\nLemma addsmx_diff_cap_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :\\: B + A :&: B :=: A)%MS.\nProof.\napply/eqmxP; rewrite addsmx_sub capmxSl diffmxSl /=.\nset C := (A :\\: B)%MS; set D := capmx_gen A B.\nsuffices sACD: (A <= C + D)%MS.\n  by rewrite (submx_trans sACD) ?addsmxS ?capmxE.\nhave:= addsmx_compl_full D; rewrite /row_full addsmxE.\ncase/row_fullP=> U /(congr1 (mulmx A)); rewrite mulmx1.\nrewrite -[U]hsubmxK mul_row_col mulmxDr addrC 2!mulmxA.\nset V := _ *m _ => defA; rewrite -defA; move/(canRL (addrK _)): defA => defV.\nsuffices /submxP[W ->]: (V <= C)%MS by rewrite -mul_row_col addsmxE submxMl.\nrewrite diffmxE sub_capmx {1}defV -mulNmx addmx_sub 1?mulmx_sub //.\nby rewrite -capmxE capmxSl.\nQed.\n\nLemma mxrank_cap_compl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (\\rank (A :&: B) + \\rank (A :\\: B))%N = \\rank A.\nProof.\nrewrite addnC -mxrank_disjoint_sum ?addsmx_diff_cap_eq //.\nby rewrite (capmxC A) capmxA capmx_diff cap0mx.\nQed.\n\nLemma mxrank_sum_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (\\rank (A + B) + \\rank (A :&: B) = \\rank A + \\rank B)%N.\nProof.\nset C := (A :&: B)%MS; set D := (A :\\: B)%MS.\nhave rDB: \\rank (A + B)%MS = \\rank (D + B)%MS.\n  apply/eqP; rewrite mxrank_leqif_sup; first by rewrite addsmxS ?diffmxSl.\n  by rewrite addsmx_sub addsmxSr -(addsmx_diff_cap_eq A B) addsmxS ?capmxSr.\nrewrite {1}rDB mxrank_disjoint_sum ?capmx_diff //.\nby rewrite addnC addnA mxrank_cap_compl.\nQed.\n\nLemma mxrank_adds_leqif m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  \\rank (A + B) <= \\rank A + \\rank B ?= iff (A :&: B <= (0 : 'M_n))%MS.\nProof.\nrewrite -mxrank_sum_cap; split; first exact: leq_addr.\nby rewrite addnC (@eqn_add2r _ 0) eq_sym mxrank_eq0 -submx0.\nQed.\n\n(* Subspace projection matrix *)\n\nLemma proj_mx_sub m n U V (W : 'M_(m, n)) : (W *m proj_mx U V <= U)%MS.\nProof. by rewrite !mulmx_sub // -addsmxE addsmx0. Qed.\n\nLemma proj_mx_compl_sub m n U V (W : 'M_(m, n)) :\n  (W <= U + V -> W - W *m proj_mx U V <= V)%MS.\nProof.\nrewrite addsmxE => sWUV; rewrite mulmxA -{1}(mulmxKpV sWUV) -mulmxBr.\nby rewrite mulmx_sub // opp_col_mx add_col_mx subrr subr0 -addsmxE adds0mx.\nQed.\n\nLemma proj_mx_id m n U V (W : 'M_(m, n)) :\n  (U :&: V = 0)%MS -> (W <= U)%MS -> W *m proj_mx U V = W.\nProof.\nmove=> dxUV sWU; apply/eqP; rewrite -subr_eq0 -submx0 -dxUV.\nrewrite sub_capmx addmx_sub ?eqmx_opp ?proj_mx_sub //= -eqmx_opp opprB.\nby rewrite proj_mx_compl_sub // (submx_trans sWU) ?addsmxSl.\nQed.\n\nLemma proj_mx_0 m n U V (W : 'M_(m, n)) :\n  (U :&: V = 0)%MS -> (W <= V)%MS -> W *m proj_mx U V = 0.\nProof.\nmove=> dxUV sWV; apply/eqP; rewrite -submx0 -dxUV.\nrewrite sub_capmx proj_mx_sub /= -[_ *m _](subrK W) addmx_sub // -eqmx_opp.\nby rewrite opprB proj_mx_compl_sub // (submx_trans sWV) ?addsmxSr.\nQed.\n\nLemma add_proj_mx m n U V (W : 'M_(m, n)) :\n    (U :&: V = 0)%MS -> (W <= U + V)%MS ->\n  W *m proj_mx U V + W *m proj_mx V U = W.\nProof.\nmove=> dxUV sWUV; apply/eqP; rewrite -subr_eq0 -submx0 -dxUV.\nrewrite -addrA sub_capmx {2}addrCA -!(opprB W).\nby rewrite !{1}addmx_sub ?proj_mx_sub ?eqmx_opp ?proj_mx_compl_sub // addsmxC.\nQed.\n\nLemma proj_mx_proj n (U V : 'M_n) :\n  let P := proj_mx U V in (U :&: V = 0)%MS -> P *m P = P.\nProof.\nby move=> P dxUV; rewrite -[P in P *m _]mul1mx proj_mx_id ?proj_mx_sub ?mul1mx.\nQed.\n\n(* Completing a partially injective matrix to get a unit matrix. *)\n\nLemma complete_unitmx m n (U : 'M_(m, n)) (f : 'M_n) :\n  \\rank (U *m f) = \\rank U -> {g : 'M_n | g \\in unitmx & U *m f = U *m g}.\nProof.\nmove=> injfU; pose V := <<U>>%MS; pose W := V *m f.\npose g := proj_mx V (V^C)%MS *m f + cokermx V *m row_ebase W.\nhave defW: V *m g = W.\n  rewrite mulmxDr mulmxA proj_mx_id ?genmxE ?capmx_compl //.\n  by rewrite mulmxA mulmx_coker mul0mx addr0.\nexists g; last first.\n  have /submxP[u ->]: (U <= V)%MS by rewrite genmxE.\n  by rewrite -!mulmxA defW.\nrewrite -row_full_unit -sub1mx; apply/submxP.\nhave: (invmx (col_ebase W) *m W <= V *m g)%MS by rewrite defW submxMl.\ncase/submxP=> v def_v; exists (invmx (row_ebase W) *m (v *m V + (V^C)%MS)).\nrewrite -mulmxA mulmxDl -mulmxA -def_v -{3}[W]mulmx_ebase -mulmxA.\nrewrite mulKmx ?col_ebase_unit // [_ *m g]mulmxDr mulmxA.\nrewrite (proj_mx_0 (capmx_compl _)) // mul0mx add0r 2!mulmxA.\nrewrite mulmxK ?row_ebase_unit // copid_mx_id ?rank_leq_row //.\nrewrite (eqmxMr _ (genmxE U)) injfU genmxE addrC -mulmxDl subrK.\nby rewrite mul1mx mulVmx ?row_ebase_unit.\nQed.\n\n(* Two matrices with the same shape represent the same subspace *)\n(* iff they differ only by a change of basis.                   *)\n\nLemma eqmxMunitP m n (U V : 'M_(m, n)) :\n  reflect (exists2 P, P \\in unitmx & U = P *m V) (U == V)%MS.\nProof.\napply: (iffP eqmxP) => [eqUV | [P Punit ->]]; last first.\n  by apply/eqmxMfull; rewrite row_full_unit.\nhave [D defU]: exists D, U = D *m V by apply/submxP; rewrite eqUV.\nhave{eqUV} [Pt Pt_unit defUt]: {Pt | Pt \\in unitmx & V^T *m D^T = V^T *m Pt}.\n  by apply/complete_unitmx; rewrite -trmx_mul -defU !mxrank_tr eqUV.\nby exists Pt^T; last apply/trmx_inj; rewrite ?unitmx_tr // defU !trmx_mul trmxK.\nQed.\n\n(* Mapping between two subspaces with the same dimension. *)\n\nLemma eq_rank_unitmx m1 m2 n (U : 'M_(m1, n)) (V : 'M_(m2, n)) :\n  \\rank U = \\rank V -> {f : 'M_n | f \\in unitmx & V :=: U *m f}%MS.\nProof.\nmove=> eqrUV; pose f := invmx (row_ebase <<U>>%MS) *m row_ebase <<V>>%MS.\nhave defUf: (<<U>> *m f :=: <<V>>)%MS.\n  rewrite -[<<U>>%MS]mulmx_ebase mulmxA mulmxK ?row_ebase_unit // -mulmxA.\n  rewrite genmxE eqrUV -genmxE -{3}[<<V>>%MS]mulmx_ebase -mulmxA.\n  move: (pid_mx _ *m _) => W; apply/eqmxP.\n  by rewrite !eqmxMfull ?andbb // row_full_unit col_ebase_unit.\nhave{defUf} defV: (V :=: U *m f)%MS.\n  by apply/eqmxP; rewrite -!(eqmxMr f (genmxE U)) !defUf !genmxE andbb.\nhave injfU: \\rank (U *m f) = \\rank U by rewrite -defV eqrUV.\nby have [g injg defUg] := complete_unitmx injfU; exists g; rewrite -?defUg.\nQed.\n\nSection SumExpr.\n\n(* This is the infrastructure to support the mxdirect predicate. We use a     *)\n(* bespoke canonical structure to decompose a matrix expression into binary   *)\n(* and n-ary products, using some of the \"quote\" technology. This lets us     *)\n(* characterize direct sums as set sums whose rank is equal to the sum of the *)\n(* ranks of the individual terms. The mxsum_expr/proper_mxsum_expr structures *)\n(* below supply both the decomposition and the calculation of the rank sum.   *)\n(* The mxsum_spec dependent predicate family expresses the consistency of     *)\n(* these two decompositions.                                                  *)\n(*   The main technical difficulty we need to overcome is the fact that       *)\n(* the \"catch-all\" case of canonical structures has a priority lower than     *)\n(* constant expansion. However, it is undesireable that local abbreviations   *)\n(* be opaque for the direct-sum predicate, e.g., not be able to handle        *)\n(* let S := (\\sum_(i | P i) LargeExpression i)%MS in mxdirect S -> ...).      *)\n(*   As in \"quote\", we use the interleaving of constant expansion and         *)\n(* canonical projection matching to achieve our goal: we use a \"wrapper\" type *)\n(* (indeed, the wrapped T type defined in ssrfun.v) with a self-inserting     *)\n(* non-primitive constructor to gain finer control over the type and          *)\n(* structure inference process. The innermost, primitive, constructor flags   *)\n(* trivial sums; it is initially hidden by an eta-expansion, which has been   *)\n(* made into a (default) canonical structure -- this lets type inference      *)\n(* automatically insert this outer tag.                                       *)\n(*   In detail, we define three types                                         *)\n(*  mxsum_spec S r <-> There exists a finite list of matrices A1, ..., Ak     *)\n(*                     such that S is the set sum of the Ai, and r is the sum *)\n(*                     of the ranks of the Ai, i.e., S = (A1 + ... + Ak)%MS   *)\n(*                     and r = \\rank A1 + ... + \\rank Ak. Note that           *)\n(*                     mxsum_spec is a recursive dependent predicate family   *)\n(*                     whose elimination rewrites simultaneaously S, r and    *)\n(*                     the height of S.                                       *)\n(*   proper_mxsum_expr n == The interface for proper sum expressions; this is *)\n(*                     a double-entry interface, keyed on both the matrix sum *)\n(*                     value and the rank sum. The matrix value is restricted *)\n(*                     to square matrices, as the \"+\"%MS operator always      *)\n(*                     returns a square matrix. This interface has two        *)\n(*                     canonical insances, for binary and n-ary sums.         *)\n(*   mxsum_expr m n == The interface for general sum expressions, comprising  *)\n(*                     both proper sums and trivial sums consisting of a      *)\n(*                     single matrix. The key values are WRAPPED as this lets *)\n(*                     us give priority to the \"proper sum\" interpretation    *)\n(*                     (see below). To allow for trivial sums, the matrix key *)\n(*                     can have any dimension. The mxsum_expr interface has   *)\n(*                     two canonical instances, for trivial and proper sums,  *)\n(*                     keyed to the Wrap and wrap constructors, respectively. *)\n(* The projections for the two interfaces above are                           *)\n(*   proper_mxsum_val, mxsum_val : these are respectively coercions to 'M_n   *)\n(*                     and wrapped 'M_(m, n); thus, the matrix sum for an     *)\n(*                     S : mxsum_expr m n can be written unwrap S.            *)\n(*   proper_mxsum_rank, mxsum_rank : projections to the nat and wrapped nat,  *)\n(*                     respectively; the rank sum for S : mxsum_expr m n is   *)\n(*                     thus written unwrap (mxsum_rank S).                    *)\n(* The mxdirect A predicate actually gets A in a phantom argument, which is   *)\n(* used to infer an (implicit) S : mxsum_expr such that unwrap S = A; the     *)\n(* actual definition is \\rank (unwrap S) == unwrap (mxsum_rank S).            *)\n(*   Note that the inference of S is inherently ambiguous: ANY matrix can be  *)\n(* viewed as a trivial sum, including one whose description is manifestly a   *)\n(* proper sum. We use the wrapped type and the interaction between delta      *)\n(* reduction and canonical structure inference to resolve this ambiguity in   *)\n(* favor of proper sums, as follows:                                          *)\n(*    - The phantom type sets up a unification problem of the form            *)\n(*         unwrap (mxsum_val ?S) = A                                          *)\n(*      with unknown evar ?S : mxsum_expr m n.                                *)\n(*    - As the constructor wrap is also a default Canonical instance for the  *)\n(*      wrapped type, so A is immediately replaced with unwrap (wrap A) and   *)\n(*      we get the residual unification problem                               *)\n(*         mxsum_val ?S = wrap A                                              *)\n(*    - Now Coq tries to apply the proper sum Canonical instance, which has   *)\n(*      key projection wrap (proper_mxsum_val ?PS) where ?PS is a fresh evar  *)\n(*      (of type proper_mxsum_expr n). This can only succeed if m = n, and if *)\n(*      a solution can be found to the recursive unification problem          *)\n(*         proper_mxsum_val ?PS = A                                           *)\n(*      This causes Coq to look for one of the two canonical constants for    *)\n(*      proper_mxsum_val (addsmx or bigop) at the head of A, delta-expanding  *)\n(*      A as needed, and then inferring recursively mxsum_expr structures for *)\n(*      the last argument(s) of that constant.                                *)\n(*    - If the above step fails then the wrap constant is expanded, revealing *)\n(*      the primitive Wrap constructor; the unification problem now becomes   *)\n(*         mxsum_val ?S = Wrap A                                              *)\n(*      which fits perfectly the trivial sum canonical structure, whose key   *)\n(*      projection is Wrap ?B where ?B is a fresh evar. Thus the inference    *)\n(*      succeeds, and returns the trivial sum.                                *)\n(* Note that the rank projections also register canonical values, so that the *)\n(* same process can be used to infer a sum structure from the rank sum. In    *)\n(* that case, however, there is no ambiguity and the inference can fail,      *)\n(* because the rank sum for a trivial sum is not an arbitrary integer -- it   *)\n(* must be of the form \\rank ?B. It is nevertheless necessary to use the      *)\n(* wrapped nat type for the rank sums, because in the non-trivial case the    *)\n(* head constant of the nat expression is determined by the proper_mxsum_expr *)\n(* canonical structure, so the mxsum_expr structure must use a generic        *)\n(* constant, namely wrap.                                                     *)\n\nInductive mxsum_spec n : forall m, 'M[F]_(m, n) -> nat -> Prop :=\n | TrivialMxsum m A\n    : @mxsum_spec n m A (\\rank A)\n | ProperMxsum m1 m2 T1 T2 r1 r2 of\n      @mxsum_spec n m1 T1 r1 & @mxsum_spec n m2 T2 r2\n    : mxsum_spec (T1 + T2)%MS (r1 + r2)%N.\nArguments mxsum_spec {n%N m%N} T%MS r%N.\n\nStructure mxsum_expr m n := Mxsum {\n  mxsum_val :> wrapped 'M_(m, n);\n  mxsum_rank : wrapped nat;\n  _ : mxsum_spec (unwrap mxsum_val) (unwrap mxsum_rank)\n}.\n\nCanonical trivial_mxsum m n A :=\n  @Mxsum m n (Wrap A) (Wrap (\\rank A)) (TrivialMxsum A).\n\nStructure proper_mxsum_expr n := ProperMxsumExpr {\n  proper_mxsum_val :> 'M_n;\n  proper_mxsum_rank : nat;\n  _ : mxsum_spec proper_mxsum_val proper_mxsum_rank\n}.\n\nDefinition proper_mxsumP n (S : proper_mxsum_expr n) :=\n  let: ProperMxsumExpr _ _ termS := S return mxsum_spec S (proper_mxsum_rank S)\n  in termS.\n\nCanonical sum_mxsum n (S : proper_mxsum_expr n) :=\n  @Mxsum n n (wrap (S : 'M_n)) (wrap (proper_mxsum_rank S)) (proper_mxsumP S).\n\nSection Binary.\nVariable (m1 m2 n : nat) (S1 : mxsum_expr m1 n) (S2 : mxsum_expr m2 n).\nFact binary_mxsum_proof :\n  mxsum_spec (unwrap S1 + unwrap S2)\n             (unwrap (mxsum_rank S1) + unwrap (mxsum_rank S2)).\nProof. by case: S1 S2 => [A1 r1 A1P] [A2 r2 A2P]; right. Qed.\nCanonical binary_mxsum_expr := ProperMxsumExpr binary_mxsum_proof.\nEnd Binary.\n\nSection Nary.\nContext J (r : seq J) (P : pred J) n (S_ : J -> mxsum_expr n n).\nFact nary_mxsum_proof :\n  mxsum_spec (\\sum_(j <- r | P j) unwrap (S_ j))\n             (\\sum_(j <- r | P j) unwrap (mxsum_rank (S_ j))).\nProof.\nelim/big_rec2: _ => [|j]; first by rewrite -(mxrank0 n n); left.\nby case: (S_ j); right.\nQed.\nCanonical nary_mxsum_expr := ProperMxsumExpr nary_mxsum_proof.\nEnd Nary.\n\nDefinition mxdirect_def m n T of phantom 'M_(m, n) (unwrap (mxsum_val T)) :=\n  \\rank (unwrap T) == unwrap (mxsum_rank T).\n\nEnd SumExpr.\n\nNotation mxdirect A := (mxdirect_def (Phantom 'M_(_,_) A%MS)).\n\nLemma mxdirectP n (S : proper_mxsum_expr n) :\n  reflect (\\rank S = proper_mxsum_rank S) (mxdirect S).\nProof. exact: eqnP. Qed.\nArguments mxdirectP {n S}.\n\nLemma mxdirect_trivial m n A : mxdirect (unwrap (@trivial_mxsum m n A)).\nProof. exact: eqxx. Qed.\n\nLemma mxrank_sum_leqif m n (S : mxsum_expr m n) :\n  \\rank (unwrap S) <= unwrap (mxsum_rank S) ?= iff mxdirect (unwrap S).\nProof.\nrewrite /mxdirect_def; case: S => [[A] [r] /= defAr]; split=> //=.\nelim: m A r / defAr => // m1 m2 A1 A2 r1 r2 _ leAr1 _ leAr2.\nby apply: leq_trans (leq_add leAr1 leAr2); rewrite mxrank_adds_leqif.\nQed.\n\nLemma mxdirectE m n (S : mxsum_expr m n) :\n  mxdirect (unwrap S) = (\\rank (unwrap S) == unwrap (mxsum_rank S)).\nProof. by []. Qed.\n\nLemma mxdirectEgeq m n (S : mxsum_expr m n) :\n  mxdirect (unwrap S) = (\\rank (unwrap S) >= unwrap (mxsum_rank S)).\nProof. by rewrite (geq_leqif (mxrank_sum_leqif S)). Qed.\n\nSection BinaryDirect.\n\nVariables m1 m2 n : nat.\n\nLemma mxdirect_addsE (S1 : mxsum_expr m1 n) (S2 : mxsum_expr m2 n) :\n   mxdirect (unwrap S1 + unwrap S2)\n    = [&& mxdirect (unwrap S1), mxdirect (unwrap S2)\n        & unwrap S1 :&: unwrap S2 == 0]%MS.\nProof.\nrewrite (@mxdirectE n) /=.\nhave:= leqif_add (mxrank_sum_leqif S1) (mxrank_sum_leqif S2).\nmove/(leqif_trans (mxrank_adds_leqif (unwrap S1) (unwrap S2)))=> ->.\nby rewrite andbC -andbA submx0.\nQed.\n\nLemma mxdirect_addsP (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :&: B = 0)%MS (mxdirect (A + B)).\nProof. by rewrite mxdirect_addsE !mxdirect_trivial; apply: eqP. Qed.\n\nEnd BinaryDirect.\n\nSection NaryDirect.\n\nVariables (P : pred I) (n : nat).\n\nLet TIsum A_ i := (A_ i :&: (\\sum_(j | P j && (j != i)) A_ j) = 0 :> 'M_n)%MS.\n\nLet mxdirect_sums_recP (S_ : I -> mxsum_expr n n) :\n  reflect (forall i, P i -> mxdirect (unwrap (S_ i)) /\\ TIsum (unwrap \\o S_) i)\n          (mxdirect (\\sum_(i | P i) (unwrap (S_ i)))).\nProof.\nrewrite /TIsum; apply: (iffP eqnP) => /= [dxS i Pi | dxS].\n  set Si' := (\\sum_(j | _) unwrap (S_ j))%MS.\n  have: mxdirect (unwrap (S_ i) + Si') by apply/eqnP; rewrite /= -!(bigD1 i).\n  by rewrite mxdirect_addsE => /and3P[-> _ /eqP].\nset Q := P; have [m] := ubnP #|Q|; have: Q \\subset P by [].\nelim: m Q => // m IHm Q /subsetP-sQP.\ncase: (pickP Q) => [i Qi | Q0]; last by rewrite !big_pred0 ?mxrank0.\nrewrite (cardD1x Qi) !((bigD1 i) Q) //=.\nmove/IHm=> <- {IHm}/=; last by apply/subsetP=> j /andP[/sQP].\ncase: (dxS i (sQP i Qi)) => /eqnP=> <- TiQ_0; rewrite mxrank_disjoint_sum //.\napply/eqP; rewrite -submx0 -{2}TiQ_0 capmxS //=.\nby apply/sumsmx_subP=> j /= /andP[Qj i'j]; rewrite (sumsmx_sup j) ?[P j]sQP.\nQed.\n\nLemma mxdirect_sumsP (A_ : I -> 'M_n) :\n  reflect (forall i, P i -> A_ i :&: (\\sum_(j | P j && (j != i)) A_ j) = 0)%MS\n          (mxdirect (\\sum_(i | P i) A_ i)).\nProof.\napply: (iffP (mxdirect_sums_recP _)) => dxA i /dxA; first by case.\nby rewrite mxdirect_trivial.\nQed.\n\nLemma mxdirect_sumsE (S_ : I -> mxsum_expr n n) (xunwrap := unwrap) :\n  reflect (and (forall i, P i -> mxdirect (unwrap (S_ i)))\n               (mxdirect (\\sum_(i | P i) (xunwrap (S_ i)))))\n          (mxdirect (\\sum_(i | P i) (unwrap (S_ i)))).\nProof.\napply: (iffP (mxdirect_sums_recP _)) => [dxS | [dxS_ dxS] i Pi].\n  by do [split; last apply/mxdirect_sumsP] => i; case/dxS.\nby split; [apply: dxS_ | apply: mxdirect_sumsP Pi].\nQed.\n\nEnd NaryDirect.\n\nSection SubDaddsmx.\n\nVariables m m1 m2 n : nat.\nVariables (A : 'M[F]_(m, n)) (B1 : 'M[F]_(m1, n)) (B2 : 'M[F]_(m2, n)).\n\nVariant sub_daddsmx_spec : Prop :=\n  SubDaddsmxSpec A1 A2 of (A1 <= B1)%MS & (A2 <= B2)%MS & A = A1 + A2\n                        & forall C1 C2, (C1 <= B1)%MS -> (C2 <= B2)%MS ->\n                          A = C1 + C2 -> C1 = A1 /\\ C2 = A2.\n\nLemma sub_daddsmx : (B1 :&: B2 = 0)%MS -> (A <= B1 + B2)%MS -> sub_daddsmx_spec.\nProof.\nmove=> dxB /sub_addsmxP[u defA].\nexists (u.1 *m B1) (u.2 *m B2); rewrite ?submxMl // => C1 C2 sCB1 sCB2.\nmove/(canLR (addrK _)) => defC1.\nsuffices: (C2 - u.2 *m B2 <= B1 :&: B2)%MS.\n  by rewrite dxB submx0 subr_eq0 -defC1 defA; move/eqP->; rewrite addrK.\nrewrite sub_capmx -opprB -{1}(canLR (addKr _) defA) -addrA defC1.\nby rewrite !(eqmx_opp, addmx_sub) ?submxMl.\nQed.\n\nEnd SubDaddsmx.\n\nSection SubDsumsmx.\n\nVariables (P : pred I) (m n : nat) (A : 'M[F]_(m, n)) (B : I -> 'M[F]_n).\n\nVariant sub_dsumsmx_spec : Prop :=\n  SubDsumsmxSpec A_ of forall i, P i -> (A_ i <= B i)%MS\n                        & A = \\sum_(i | P i) A_ i\n                        & forall C, (forall i, P i -> C i <= B i)%MS ->\n                          A = \\sum_(i | P i) C i -> {in SimplPred P, C =1 A_}.\n\nLemma sub_dsumsmx :\n    mxdirect (\\sum_(i | P i) B i) -> (A <= \\sum_(i | P i) B i)%MS ->\n  sub_dsumsmx_spec.\nProof.\nmove/mxdirect_sumsP=> dxB /sub_sumsmxP[u defA].\npose A_ i := u i *m B i.\nexists A_ => //= [i _ | C sCB defAC i Pi]; first exact: submxMl.\napply/eqP; rewrite -subr_eq0 -submx0 -{dxB}(dxB i Pi) /=.\nrewrite sub_capmx addmx_sub ?eqmx_opp ?submxMl ?sCB //=.\nrewrite -(subrK A (C i)) -addrA -opprB addmx_sub ?eqmx_opp //.\n  rewrite addrC defAC (bigD1 i) // addKr /= summx_sub // => j Pi'j.\n  by rewrite (sumsmx_sup j) ?sCB //; case/andP: Pi'j.\nrewrite addrC defA (bigD1 i) // addKr /= summx_sub // => j Pi'j.\nby rewrite (sumsmx_sup j) ?submxMl.\nQed.\n\nEnd SubDsumsmx.\n\nSection Eigenspace.\n\nVariables (n : nat) (g : 'M_n).\n\nDefinition eigenspace a := kermx (g - a%:M).\nDefinition eigenvalue : pred F := fun a => eigenspace a != 0.\n\nLemma eigenspaceP a m (W : 'M_(m, n)) :\n  reflect (W *m g = a *: W) (W <= eigenspace a)%MS.\nProof.\nrewrite (sameP (sub_kermxP _ _) eqP).\nby rewrite mulmxBr subr_eq0 mul_mx_scalar; apply: eqP.\nQed.\n\nLemma eigenvalueP a :\n  reflect (exists2 v : 'rV_n, v *m g = a *: v & v != 0) (eigenvalue a).\nProof. by apply: (iffP (rowV0Pn _)) => [] [v]; move/eigenspaceP; exists v. Qed.\n\nLemma mxdirect_sum_eigenspace (P : pred I) a_ :\n  {in P &, injective a_} -> mxdirect (\\sum_(i | P i) eigenspace (a_ i)).\nProof.\nhave [m] := ubnP #|P|; elim: m P => // m IHm P lePm inj_a.\napply/mxdirect_sumsP=> i Pi; apply/eqP/rowV0P => v.\nrewrite sub_capmx => /andP[/eigenspaceP def_vg].\nset Vi' := (\\sum_(i | _) _)%MS => Vi'v.\nhave dxVi': mxdirect Vi'.\n  rewrite (cardD1x Pi) in lePm; apply: IHm => //.\n  by apply: sub_in2 inj_a => j /andP[].\ncase/sub_dsumsmx: Vi'v => // u Vi'u def_v _.\nrewrite def_v big1 // => j Pi'j; apply/eqP.\nhave nz_aij: a_ i - a_ j != 0.\n  by case/andP: Pi'j => Pj ne_ji; rewrite subr_eq0 eq_sym (inj_in_eq inj_a).\ncase: (sub_dsumsmx dxVi' (sub0mx 1 _)) => C _ _ uniqC.\nrewrite -(eqmx_eq0 (eqmx_scale _ nz_aij)).\nrewrite (uniqC (fun k => (a_ i - a_ k) *: u k)) => // [|k Pi'k|].\n- by rewrite -(uniqC (fun _ => 0)) ?big1 // => k Pi'k; apply: sub0mx.\n- by rewrite scalemx_sub ?Vi'u.\nrewrite -{1}(subrr (v *m g)) {1}def_vg def_v scaler_sumr mulmx_suml -sumrB.\nby apply: eq_bigr => k /Vi'u/eigenspaceP->; rewrite scalerBl.\nQed.\n\nEnd Eigenspace.\n\nEnd RowSpaceTheory.\n\nHint Resolve submx_refl : core.\nArguments submxP {F m1 m2 n A B}.\nArguments eq_row_sub [F m n v A].\nArguments row_subP {F m1 m2 n A B}.\nArguments rV_subP {F m1 m2 n A B}.\nArguments row_subPn {F m1 m2 n A B}.\nArguments sub_rVP {F n u v}.\nArguments rV_eqP {F m1 m2 n A B}.\nArguments rowV0Pn {F m n A}.\nArguments rowV0P {F m n A}.\nArguments eqmx0P {F m n A}.\nArguments row_fullP {F m n A}.\nArguments row_freeP {F m n A}.\nArguments eqmxP {F m1 m2 n A B}.\nArguments genmxP {F m1 m2 n A B}.\nArguments addsmx_idPr {F m1 m2 n A B}.\nArguments addsmx_idPl {F m1 m2 n A B}.\nArguments sub_addsmxP {F m1 m2 m3 n A B C}.\nArguments sumsmx_sup [F I] i0 [P m n A B_].\nArguments sumsmx_subP {F I P m n A_ B}.\nArguments sub_sumsmxP {F I P m n A B_}.\nArguments sub_kermxP {F p m n A B}.\nArguments capmx_idPr {F n m1 m2 A B}.\nArguments capmx_idPl {F n m1 m2 A B}.\nArguments bigcapmx_inf [F I] i0 [P m n A_ B].\nArguments sub_bigcapmxP {F I P m n A B_}.\nArguments mxrank_injP {F m n} p [A f].\nArguments mxdirectP {F n S}.\nArguments mxdirect_addsP {F m1 m2 n A B}.\nArguments mxdirect_sumsP {F I P n A_}.\nArguments mxdirect_sumsE {F I P n S_}.\nArguments eigenspaceP {F n g a m W}.\nArguments eigenvalueP {F n g a}.\n\nArguments mxrank {F m%N n%N} A%MS.\nArguments complmx {F m%N n%N} A%MS.\nArguments row_full {F m%N n%N} A%MS.\nArguments submx {F m1%N m2%N n%N} A%MS B%MS : rename.\nArguments ltmx {F m1%N m2%N n%N} A%MS B%MS.\nArguments eqmx {F m1%N m2%N n%N} A%MS B%MS.\nArguments addsmx {F m1%N m2%N n%N} A%MS B%MS : rename.\nArguments capmx {F m1%N m2%N n%N} A%MS B%MS : rename.\nArguments diffmx {F m1%N m2%N n%N} A%MS B%MS : rename.\nArguments genmx {F m%N n%N} A%R : rename.\nNotation \"\\rank A\" := (mxrank A) : nat_scope.\nNotation \"<< A >>\" := (genmx A) : matrix_set_scope.\nNotation \"A ^C\" := (complmx A) : matrix_set_scope.\nNotation \"A <= B\" := (submx A B) : matrix_set_scope.\nNotation \"A < B\" := (ltmx A B) : matrix_set_scope.\nNotation \"A <= B <= C\" := ((submx A B) && (submx B C)) : matrix_set_scope.\nNotation \"A < B <= C\" := (ltmx A B && submx B C) : matrix_set_scope.\nNotation \"A <= B < C\" := (submx A B && ltmx B C) : matrix_set_scope.\nNotation \"A < B < C\" := (ltmx A B && ltmx B C) : matrix_set_scope.\nNotation \"A == B\" := ((submx A B) && (submx B A)) : matrix_set_scope.\nNotation \"A :=: B\" := (eqmx A B) : matrix_set_scope.\nNotation \"A + B\" := (addsmx A B) : matrix_set_scope.\nNotation \"A :&: B\" := (capmx A B) : matrix_set_scope.\nNotation \"A :\\: B\" := (diffmx A B) : matrix_set_scope.\nNotation mxdirect S := (mxdirect_def (Phantom 'M_(_,_) S%MS)).\n\nNotation \"\\sum_ ( i <- r | P ) B\" :=\n  (\\big[addsmx/0%R]_(i <- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i <- r ) B\" :=\n  (\\big[addsmx/0%R]_(i <- r) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( m <= i < n | P ) B\" :=\n  (\\big[addsmx/0%R]_(m <= i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( m <= i < n ) B\" :=\n  (\\big[addsmx/0%R]_(m <= i < n) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i | P ) B\" :=\n  (\\big[addsmx/0%R]_(i | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ i B\" :=\n  (\\big[addsmx/0%R]_i B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i : t | P ) B\" :=\n  (\\big[addsmx/0%R]_(i : t | P%B) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\sum_ ( i : t ) B\" :=\n  (\\big[addsmx/0%R]_(i : t) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\sum_ ( i < n | P ) B\" :=\n  (\\big[addsmx/0%R]_(i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i < n ) B\" :=\n  (\\big[addsmx/0%R]_(i < n) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i 'in' A | P ) B\" :=\n  (\\big[addsmx/0%R]_(i in A | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i 'in' A ) B\" :=\n  (\\big[addsmx/0%R]_(i in A) B%MS) : matrix_set_scope.\n\nNotation \"\\bigcap_ ( i <- r | P ) B\" :=\n  (\\big[capmx/1%:M]_(i <- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i <- r ) B\" :=\n  (\\big[capmx/1%:M]_(i <- r) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( m <= i < n | P ) B\" :=\n  (\\big[capmx/1%:M]_(m <= i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( m <= i < n ) B\" :=\n  (\\big[capmx/1%:M]_(m <= i < n) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i | P ) B\" :=\n  (\\big[capmx/1%:M]_(i | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ i B\" :=\n  (\\big[capmx/1%:M]_i B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i : t | P ) B\" :=\n  (\\big[capmx/1%:M]_(i : t | P%B) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\bigcap_ ( i : t ) B\" :=\n  (\\big[capmx/1%:M]_(i : t) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\bigcap_ ( i < n | P ) B\" :=\n  (\\big[capmx/1%:M]_(i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i < n ) B\" :=\n  (\\big[capmx/1%:M]_(i < n) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i 'in' A | P ) B\" :=\n  (\\big[capmx/1%:M]_(i in A | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i 'in' A ) B\" :=\n  (\\big[capmx/1%:M]_(i in A) B%MS) : matrix_set_scope.\n\nSection DirectSums.\nVariables (F : fieldType) (I : finType) (P : pred I).\n\nLemma mxdirect_delta n f : {in P &, injective f} ->\n  mxdirect (\\sum_(i | P i) <<delta_mx 0 (f i) : 'rV[F]_n>>).\nProof.\npose fP := image f P => Uf; have UfP: uniq fP by apply/dinjectiveP.\nsuffices /mxdirectP : mxdirect (\\sum_i <<delta_mx 0 i : 'rV[F]_n>>).\n  rewrite /= !(bigID [mem fP] predT) -!big_uniq //= !big_map !big_enum.\n  by move/mxdirectP; rewrite mxdirect_addsE => /andP[].\napply/mxdirectP=> /=; transitivity (mxrank (1%:M : 'M[F]_n)).\n  apply/eqmx_rank; rewrite submx1 mx1_sum_delta summx_sub_sums // => i _.\n  by rewrite -(mul_delta_mx (0 : 'I_1)) genmxE submxMl.\nrewrite mxrank1 -[LHS]card_ord -sum1_card.\nby apply/eq_bigr=> i _; rewrite /= mxrank_gen mxrank_delta.\nQed.\n\nEnd DirectSums.\n\nSection CardGL.\n\nVariable F : finFieldType.\n\nLemma card_GL n : n > 0 ->\n  #|'GL_n[F]| = (#|F| ^ 'C(n, 2) * \\prod_(1 <= i < n.+1) (#|F| ^ i - 1))%N.\nProof.\ncase: n => // n' _; set n := n'.+1; set p := #|F|.\nrewrite big_nat_rev big_add1 -triangular_sum expn_sum -big_split /=.\npose fr m := [pred A : 'M[F]_(m, n) | \\rank A == m].\nset m := n; rewrite [in m.+1]/m; transitivity #|fr m|.\n  by rewrite cardsT /= card_sub; apply: eq_card => A; rewrite -row_free_unit.\nhave: m <= n by []; elim: m => [_ | m IHm /ltnW-le_mn].\n  rewrite (@eq_card1 _ (0 : 'M_(0, n))) ?big_geq //= => A.\n  by rewrite flatmx0 !inE !eqxx.\nrewrite big_nat_recr // -{}IHm //= !subSS mulnBr muln1 -expnD subnKC //.\nrewrite -sum_nat_const /= -sum1_card -add1n.\nrewrite (partition_big dsubmx (fr m)) /= => [|A]; last first.\n  rewrite !inE -{1}(vsubmxK A); move: {A}(_ A) (_ A) => Ad Au Afull.\n  rewrite eqn_leq rank_leq_row -(leq_add2l (\\rank Au)) -mxrank_sum_cap.\n  rewrite {1 3}[@mxrank]lock addsmxE (eqnP Afull) -lock -addnA.\n  by rewrite leq_add ?rank_leq_row ?leq_addr.\napply: eq_bigr => A rAm; rewrite (reindex (col_mx^~ A)) /=; last first.\n  exists usubmx => [v _ | vA]; first by rewrite col_mxKu.\n  by case/andP=> _ /eqP <-; rewrite vsubmxK.\ntransitivity #|~: [set v *m A | v in 'rV_m]|; last first.\n  rewrite cardsCs setCK card_imset ?card_matrix ?card_ord ?mul1n //.\n  have [B AB1] := row_freeP rAm; apply: can_inj (mulmx^~ B) _ => v.\n  by rewrite -mulmxA AB1 mulmx1.\nrewrite -sum1_card; apply: eq_bigl => v; rewrite !inE col_mxKd eqxx.\nrewrite andbT eqn_leq rank_leq_row /= -(leq_add2r (\\rank (v :&: A)%MS)).\nrewrite -addsmxE mxrank_sum_cap (eqnP rAm) addnAC leq_add2r.\nrewrite (ltn_leqif (mxrank_leqif_sup _)) ?capmxSl // sub_capmx submx_refl.\nby congr (~~ _); apply/submxP/imsetP=> [] [u]; exists u.\nQed.\n\n(* An alternate, somewhat more elementary proof, that does not rely on the *)\n(* row-space theory, but directly performs the LUP decomposition.          *)\nLemma LUP_card_GL n : n > 0 ->\n  #|'GL_n[F]| = (#|F| ^ 'C(n, 2) * \\prod_(1 <= i < n.+1) (#|F| ^ i - 1))%N.\nProof.\ncase: n => // n' _; set n := n'.+1; set p := #|F|.\nrewrite cardsT /= card_sub /GRing.unit /= big_add1 /= -triangular_sum -/n.\nelim: {n'}n => [|n IHn].\n  rewrite !big_geq // mul1n (@eq_card _ _ predT) ?card_matrix //= => M.\n  by rewrite {1}[M]flatmx0 -(flatmx0 1%:M) unitmx1.\nrewrite !big_nat_recr //= expnD mulnAC mulnA -{}IHn -mulnA mulnC.\nset LHS := #|_|; rewrite -[n.+1]muln1 -{2}[n]mul1n {}/LHS.\nrewrite -!card_matrix subn1 -(cardC1 0) -mulnA; set nzC := predC1 _.\nrewrite -sum1_card (partition_big lsubmx nzC) => [|A]; last first.\n  rewrite unitmxE unitfE; apply: contra; move/eqP=> v0.\n  rewrite -[A]hsubmxK v0 -[n.+1]/(1 + n)%N -col_mx0.\n  rewrite -[rsubmx _]vsubmxK -det_tr tr_row_mx !tr_col_mx !trmx0.\n  by rewrite det_lblock [0]mx11_scalar det_scalar1 mxE mul0r.\nrewrite -sum_nat_const; apply: eq_bigr; rewrite /= -[n.+1]/(1 + n)%N => v nzv.\ncase: (pickP (fun i => v i 0 != 0)) => [k nza | v0]; last first.\n  by case/eqP: nzv; apply/colP=> i; move/eqP: (v0 i); rewrite mxE.\nhave xrkK: involutive (@xrow F _ _ 0 k).\n  by move=> m A /=; rewrite /xrow -row_permM tperm2 row_perm1.\nrewrite (reindex_inj (inv_inj (xrkK (1 + n)%N))) /= -[n.+1]/(1 + n)%N.\nrewrite (partition_big ursubmx xpredT) //= -sum_nat_const.\napply: eq_bigr => u _; set a : F := v _ _ in nza.\nset v1 : 'cV_(1 + n) := xrow 0 k v.\nhave def_a: usubmx v1 = a%:M.\n  by rewrite [_ v1]mx11_scalar mxE lshift0 mxE tpermL.\npose Schur := dsubmx v1 *m (a^-1 *: u).\npose L : 'M_(1 + n) := block_mx a%:M 0 (dsubmx v1) 1%:M.\npose U B : 'M_(1 + n) := block_mx 1 (a^-1 *: u) 0 B.\nrewrite (reindex (fun B => L *m U B)); last first.\n  exists (fun A1 => drsubmx A1 - Schur) => [B _ | A1].\n    by rewrite mulmx_block block_mxKdr mul1mx addrC addKr.\n  rewrite !inE mulmx_block !mulmx0 mul0mx !mulmx1 !addr0 mul1mx addrC subrK.\n  rewrite mul_scalar_mx scalerA divff // scale1r andbC; case/and3P => /eqP <- _.\n  rewrite -{1}(hsubmxK A1) xrowE mul_mx_row row_mxKl -xrowE => /eqP def_v.\n  rewrite -def_a block_mxEh vsubmxK /v1 -def_v xrkK.\n  apply: trmx_inj; rewrite tr_row_mx tr_col_mx trmx_ursub trmx_drsub trmx_lsub.\n  by rewrite hsubmxK vsubmxK.\nrewrite -sum1_card; apply: eq_bigl => B; rewrite xrowE unitmxE.\nrewrite !det_mulmx unitrM -unitmxE unitmx_perm det_lblock det_ublock.\nrewrite !det_scalar1 det1 mulr1 mul1r unitrM unitfE nza -unitmxE.\nrewrite mulmx_block !mulmx0 mul0mx !addr0 !mulmx1 mul1mx block_mxKur.\nrewrite mul_scalar_mx scalerA divff // scale1r eqxx andbT.\nby rewrite block_mxEh mul_mx_row row_mxKl -def_a vsubmxK -xrowE xrkK eqxx andbT.\nQed.\n\nLemma card_GL_1 : #|'GL_1[F]| = #|F|.-1.\nProof. by rewrite card_GL // mul1n big_nat1 expn1 subn1. Qed.\n\nLemma card_GL_2 : #|'GL_2[F]| = (#|F| * #|F|.-1 ^ 2 * #|F|.+1)%N.\nProof.\nrewrite card_GL // big_ltn // big_nat1 expn1 -(addn1 #|F|) -subn1 -!mulnA.\nby rewrite -subn_sqr.\nQed.\n\nEnd CardGL.\n\nLemma logn_card_GL_p n p : prime p -> logn p #|'GL_n(p)| = 'C(n, 2).\nProof.\nmove=> p_pr; have p_gt1 := prime_gt1 p_pr.\nhave p_i_gt0: p ^ _ > 0 by move=> i; rewrite expn_gt0 ltnW.\nrewrite (card_GL _ (ltn0Sn n.-1)) card_ord Fp_cast // big_add1 /=.\npose p'gt0 m := m > 0 /\\ logn p m = 0%N.\nsuffices [Pgt0 p'P]: p'gt0 (\\prod_(0 <= i < n.-1.+1) (p ^ i.+1 - 1))%N.\n  by rewrite lognM // p'P pfactorK // addn0; case n.\napply big_ind => [|m1 m2 [m10 p'm1] [m20]|i _]; rewrite {}/p'gt0 ?logn1 //.\n  by rewrite muln_gt0 m10 lognM ?p'm1.\nrewrite lognE -if_neg subn_gt0 p_pr /= -{1 2}(exp1n i.+1) ltn_exp2r // p_gt1.\nby rewrite dvdn_subr ?dvdn_exp // gtnNdvd.\nQed.\n\nSection MatrixAlgebra.\n\nVariables F : fieldType.\n\nLocal Notation \"A \\in R\" := (@submx F _ _ _ (mxvec A) R).\n\nLemma mem0mx m n (R : 'A_(m, n)) : 0 \\in R.\nProof. by rewrite linear0 sub0mx. Qed.\n\nLemma memmx0 n A : (A \\in (0 : 'A_n)) -> A = 0.\nProof. by rewrite submx0 mxvec_eq0; move/eqP. Qed.\n\nLemma memmx1 n (A : 'M_n) : (A \\in mxvec 1%:M) = is_scalar_mx A.\nProof.\napply/sub_rVP/is_scalar_mxP=> [[a] | [a ->]].\n  by rewrite -linearZ scale_scalar_mx mulr1 => /(can_inj mxvecK); exists a.\nby exists a; rewrite -linearZ scale_scalar_mx mulr1.\nQed.\n\nLemma memmx_subP m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (forall A, A \\in R1 -> A \\in R2) (R1 <= R2)%MS.\nProof.\napply: (iffP idP) => [sR12 A R1_A | sR12]; first exact: submx_trans sR12.\nby apply/rV_subP=> vA; rewrite -(vec_mxK vA); apply: sR12.\nQed.\nArguments memmx_subP {m1 m2 n R1 R2}.\n\nLemma memmx_eqP m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (forall A, (A \\in R1) = (A \\in R2)) (R1 == R2)%MS.\nProof.\napply: (iffP eqmxP) => [eqR12 A | eqR12]; first by rewrite eqR12.\nby apply/eqmxP; apply/rV_eqP=> vA; rewrite -(vec_mxK vA) eqR12.\nQed.\nArguments memmx_eqP {m1 m2 n R1 R2}.\n\nLemma memmx_addsP m1 m2 n A (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (exists D, [/\\ D.1 \\in R1, D.2 \\in R2 & A = D.1 + D.2])\n          (A \\in R1 + R2)%MS.\nProof.\napply: (iffP sub_addsmxP) => [[u /(canRL mxvecK)->] | [D []]].\n  exists (vec_mx (u.1 *m R1), vec_mx (u.2 *m R2)).\n  by rewrite /= linearD !vec_mxK !submxMl.\ncase/submxP=> u1 defD1 /submxP[u2 defD2] ->.\nby exists (u1, u2); rewrite linearD /= defD1 defD2.\nQed.\nArguments memmx_addsP {m1 m2 n A R1 R2}.\n\nLemma memmx_sumsP (I : finType) (P : pred I) n (A : 'M_n) R_ :\n  reflect (exists2 A_, A = \\sum_(i | P i) A_ i & forall i, A_ i \\in R_ i)\n          (A \\in \\sum_(i | P i) R_ i)%MS.\nProof.\napply: (iffP sub_sumsmxP) => [[C defA] | [A_ -> R_A] {A}].\n  exists (fun i => vec_mx (C i *m R_ i)) => [|i].\n    by rewrite -linear_sum -defA /= mxvecK.\n  by rewrite vec_mxK submxMl.\nexists (fun i => mxvec (A_ i) *m pinvmx (R_ i)).\nby rewrite linear_sum; apply: eq_bigr => i _; rewrite mulmxKpV.\nQed.\nArguments memmx_sumsP {I P n A R_}.\n\nLemma has_non_scalar_mxP m n (R : 'A_(m, n)) :\n    (1%:M \\in R)%MS ->\n  reflect (exists2 A, A \\in R & ~~ is_scalar_mx A)%MS (1 < \\rank R).\nProof.\ncase: (posnP n) => [-> | n_gt0] in R *; set S := mxvec _ => sSR.\n  by rewrite [R]thinmx0 mxrank0; right; case; rewrite /is_scalar_mx ?insubF.\nhave rankS: \\rank S = 1%N.\n  apply/eqP; rewrite eqn_leq rank_leq_row lt0n mxrank_eq0 mxvec_eq0.\n  by rewrite -mxrank_eq0 mxrank1 -lt0n.\nrewrite -{2}rankS (ltn_leqif (mxrank_leqif_sup sSR)).\napply: (iffP idP) => [/row_subPn[i] | [A sAR]].\n  rewrite -[row i R]vec_mxK memmx1; set A := vec_mx _ => nsA.\n  by exists A; rewrite // vec_mxK row_sub.\nby rewrite -memmx1; apply/contra/submx_trans.\nQed.\n\nDefinition mulsmx m1 m2 n (R1 : 'A[F]_(m1, n)) (R2 : 'A_(m2, n)) :=\n  (\\sum_i <<R1 *m lin_mx (mulmxr (vec_mx (row i R2)))>>)%MS.\n\nArguments mulsmx {m1%N m2%N n%N} R1%MS R2%MS.\n\nLocal Notation \"R1 * R2\" := (mulsmx R1 R2) : matrix_set_scope.\n\nLemma genmx_muls m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  <<(R1 * R2)%MS>>%MS = (R1 * R2)%MS.\nProof. by rewrite genmx_sums; apply: eq_bigr => i; rewrite genmx_id. Qed.\n\nLemma mem_mulsmx m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) A1 A2 :\n  (A1 \\in R1 -> A2 \\in R2 -> A1 *m A2 \\in R1 * R2)%MS.\nProof.\nmove=> R_A1 R_A2; rewrite -[A2]mxvecK; case/submxP: R_A2 => a ->{A2}.\nrewrite mulmx_sum_row !linear_sum summx_sub // => i _.\nrewrite !linearZ scalemx_sub {a}//= (sumsmx_sup i) // genmxE.\nrewrite -[A1]mxvecK; case/submxP: R_A1 => a ->{A1}.\nby apply/submxP; exists a; rewrite mulmxA mul_rV_lin.\nQed.\n\nLemma mulsmx_subP m1 m2 m n\n                 (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R : 'A_(m, n)) :\n  reflect (forall A1 A2, A1 \\in R1 -> A2 \\in R2 -> A1 *m A2 \\in R)\n          (R1 * R2 <= R)%MS.\nProof.\napply: (iffP memmx_subP) => [sR12R A1 A2 R_A1 R_A2 | sR12R A].\n  by rewrite sR12R ?mem_mulsmx.\ncase/memmx_sumsP=> A_ -> R_A; rewrite linear_sum summx_sub //= => j _.\nrewrite (submx_trans (R_A _)) // genmxE; apply/row_subP=> i.\nby rewrite row_mul mul_rV_lin sR12R ?vec_mxK ?row_sub.\nQed.\nArguments mulsmx_subP {m1 m2 m n R1 R2 R}.\n\nLemma mulsmxS m1 m2 m3 m4 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n))\n                            (R3 : 'A_(m3, n)) (R4 : 'A_(m4, n)) :\n  (R1 <= R3 -> R2 <= R4 -> R1 * R2 <= R3 * R4)%MS.\nProof.\nmove=> sR13 sR24; apply/mulsmx_subP=> A1 A2 R_A1 R_A2.\nby apply: mem_mulsmx; [apply: submx_trans sR13 | apply: submx_trans sR24].\nQed.\n\nLemma muls_eqmx m1 m2 m3 m4 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n))\n                              (R3 : 'A_(m3, n)) (R4 : 'A_(m4, n)) :\n  (R1 :=: R3 -> R2 :=: R4 -> R1 * R2 = R3 * R4)%MS.\nProof.\nmove=> eqR13 eqR24; rewrite -(genmx_muls R1 R2) -(genmx_muls R3 R4).\nby apply/genmxP; rewrite !mulsmxS ?eqR13 ?eqR24.\nQed.\n\nLemma mulsmxP m1 m2 n A (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (exists2 A1, forall i, A1 i \\in R1\n            & exists2 A2, forall i, A2 i \\in R2\n           & A = \\sum_(i < n ^ 2) A1 i *m A2 i)\n          (A \\in R1 * R2)%MS.\nProof.\napply: (iffP idP) => [R_A|[A1 R_A1 [A2 R_A2 ->{A}]]]; last first.\n  by rewrite linear_sum summx_sub // => i _; rewrite mem_mulsmx.\nhave{R_A}: (A \\in R1 * <<R2>>)%MS.\n  by apply: memmx_subP R_A; rewrite mulsmxS ?genmxE.\ncase/memmx_sumsP=> A_ -> R_A; pose A2_ i := vec_mx (row i <<R2>>%MS).\npose A1_ i := mxvec (A_ i) *m pinvmx (R1 *m lin_mx (mulmxr (A2_ i))) *m R1.\nexists (vec_mx \\o A1_) => [i|]; first by rewrite vec_mxK submxMl.\nexists A2_ => [i|]; first by rewrite vec_mxK -(genmxE R2) row_sub.\napply: eq_bigr => i _; rewrite -[_ *m _](mx_rV_lin (mulmxr_linear _ _)).\nby rewrite -mulmxA mulmxKpV ?mxvecK // -(genmxE (_ *m _)) R_A.\nQed.\nArguments mulsmxP {m1 m2 n A R1 R2}.\n\nLemma mulsmxA m1 m2 m3 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) :\n  (R1 * (R2 * R3) = R1 * R2 * R3)%MS.\nProof.\nrewrite -(genmx_muls (_ * _)%MS) -genmx_muls; apply/genmxP; apply/andP; split.\n  apply/mulsmx_subP=> A1 A23 R_A1; case/mulsmxP=> A2 R_A2 [A3 R_A3 ->{A23}].\n  by rewrite !linear_sum summx_sub //= => i _; rewrite mulmxA !mem_mulsmx.\napply/mulsmx_subP=> _ A3 /mulsmxP[A1 R_A1 [A2 R_A2 ->]] R_A3.\nrewrite mulmx_suml linear_sum summx_sub //= => i _.\nby rewrite -mulmxA !mem_mulsmx.\nQed.\n\nLemma mulsmx_addl m1 m2 m3 n\n                 (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) :\n  ((R1 + R2) * R3 = R1 * R3 + R2 * R3)%MS.\nProof.\nrewrite -(genmx_muls R2 R3) -(genmx_muls R1 R3) -genmx_muls -genmx_adds.\napply/genmxP; rewrite andbC addsmx_sub !mulsmxS ?addsmxSl ?addsmxSr //=.\napply/mulsmx_subP=> _ A3 /memmx_addsP[A [R_A1 R_A2 ->]] R_A3.\nby rewrite mulmxDl linearD addmx_sub_adds ?mem_mulsmx.\nQed.\n\nLemma mulsmx_addr m1 m2 m3 n\n                  (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) :\n  (R1 * (R2 + R3) = R1 * R2 + R1 * R3)%MS.\nProof.\nrewrite -(genmx_muls R1 R3) -(genmx_muls R1 R2) -genmx_muls -genmx_adds.\napply/genmxP; rewrite andbC addsmx_sub !mulsmxS ?addsmxSl ?addsmxSr //=.\napply/mulsmx_subP=> A1 _ R_A1 /memmx_addsP[A [R_A2 R_A3 ->]].\nby rewrite mulmxDr linearD addmx_sub_adds ?mem_mulsmx.\nQed.\n\nLemma mulsmx0 m1 m2 n (R1 : 'A_(m1, n)) : (R1 * (0 : 'A_(m2, n)) = 0)%MS.\nProof.\napply/eqP; rewrite -submx0; apply/mulsmx_subP=> A1 A0 _.\nby rewrite [A0 \\in 0]eqmx0 => /memmx0->; rewrite mulmx0 mem0mx.\nQed.\n\nLemma muls0mx m1 m2 n (R2 : 'A_(m2, n)) : ((0 : 'A_(m1, n)) * R2 = 0)%MS.\nProof.\napply/eqP; rewrite -submx0; apply/mulsmx_subP=> A0 A2.\nby rewrite [A0 \\in 0]eqmx0 => /memmx0->; rewrite mul0mx mem0mx.\nQed.\n\nDefinition left_mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :=\n  (R1 * R2 <= R2)%MS.\n\nDefinition right_mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :=\n  (R2 * R1 <= R2)%MS.\n\nDefinition mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :=\n  left_mx_ideal R1 R2 && right_mx_ideal R1 R2.\n\nDefinition mxring_id m n (R : 'A_(m, n)) e :=\n  [/\\ e != 0,\n      e \\in R,\n      forall A, A \\in R -> e *m A = A\n    & forall A, A \\in R -> A *m e = A]%MS.\n\nDefinition has_mxring_id m n (R : 'A[F]_(m , n)) :=\n  (R != 0) &&\n  (row_mx 0 (row_mx (mxvec R) (mxvec R))\n    <= row_mx (cokermx R) (row_mx (lin_mx (mulmx R \\o lin_mulmx))\n                                  (lin_mx (mulmx R \\o lin_mulmxr))))%MS.\n\nDefinition mxring m n (R : 'A_(m, n)) :=\n  left_mx_ideal R R && has_mxring_id R.\n\nLemma mxring_idP m n (R : 'A_(m, n)) :\n  reflect (exists e, mxring_id R e) (has_mxring_id R).\nProof.\napply: (iffP andP) => [[nzR] | [e [nz_e Re ideR idRe]]].\n  case/submxP=> v; rewrite -[v]vec_mxK; move/vec_mx: v => e.\n  rewrite !mul_mx_row; case/eq_row_mx => /eqP.\n  rewrite eq_sym -submxE => Re.\n  case/eq_row_mx; rewrite !{1}mul_rV_lin1 /= mxvecK.\n  set u := (_ *m _) => /(can_inj mxvecK) idRe /(can_inj mxvecK) ideR.\n  exists e; split=> // [ | A /submxP[a defA] | A /submxP[a defA]].\n  - by apply: contra nzR; rewrite ideR => /eqP->; rewrite !linear0.\n  - by rewrite -{2}[A]mxvecK defA idRe mulmxA mx_rV_lin -defA /= mxvecK.\n  by rewrite -{2}[A]mxvecK defA ideR mulmxA mx_rV_lin -defA /= mxvecK.\nsplit.\n  by apply: contraNneq nz_e => R0; rewrite R0 eqmx0 in Re; rewrite (memmx0 Re).\napply/submxP; exists (mxvec e); rewrite !mul_mx_row !{1}mul_rV_lin1.\nrewrite submxE in Re; rewrite {Re}(eqP Re).\ncongr (row_mx 0 (row_mx (mxvec _) (mxvec _))); apply/row_matrixP=> i.\n  by rewrite !row_mul !mul_rV_lin1 /= mxvecK ideR vec_mxK ?row_sub.\nby rewrite !row_mul !mul_rV_lin1 /= mxvecK idRe vec_mxK ?row_sub.\nQed.\nArguments mxring_idP {m n R}.\n\nSection CentMxDef.\n\nVariables (m n : nat) (R : 'A[F]_(m, n)).\n\nDefinition cent_mx_fun (B : 'M[F]_n) := R *m lin_mx (mulmxr B \\- mulmx B).\n\nLemma cent_mx_fun_is_linear : linear cent_mx_fun.\nProof.\nmove=> a A B; apply/row_matrixP=> i; rewrite linearP row_mul mul_rV_lin.\nrewrite /= [row i _ as v in a *: v]row_mul mul_rV_lin row_mul mul_rV_lin.\nby rewrite -linearP -(linearP [linear of mulmx _ \\- mulmxr _]).\nQed.\nCanonical cent_mx_fun_additive := Additive cent_mx_fun_is_linear.\nCanonical cent_mx_fun_linear := Linear cent_mx_fun_is_linear.\n\nDefinition cent_mx := kermx (lin_mx cent_mx_fun).\n\nDefinition center_mx := (R :&: cent_mx)%MS.\n\nEnd CentMxDef.\n\nLocal Notation \"''C' ( R )\" := (cent_mx R) : matrix_set_scope.\nLocal Notation \"''Z' ( R )\" := (center_mx R) : matrix_set_scope.\n\nLemma cent_rowP m n B (R : 'A_(m, n)) :\n  reflect (forall i (A := vec_mx (row i R)), A *m B = B *m A) (B \\in 'C(R))%MS.\nProof.\napply: (iffP sub_kermxP); rewrite mul_vec_lin => cBE.\n  move/(canRL mxvecK): cBE => cBE i A /=; move/(congr1 (row i)): cBE.\n  rewrite row_mul mul_rV_lin -/A; move/(canRL mxvecK).\n  by move/(canRL (subrK _)); rewrite !linear0 add0r.\napply: (canLR vec_mxK); apply/row_matrixP=> i.\nby rewrite row_mul mul_rV_lin /= cBE subrr !linear0.\nQed.\nArguments cent_rowP {m n B R}.\n\nLemma cent_mxP m n B (R : 'A_(m, n)) :\n  reflect (forall A, A \\in R -> A *m B = B *m A) (B \\in 'C(R))%MS.\nProof.\napply: (iffP cent_rowP) => cEB => [A sAE | i A].\n  rewrite -[A]mxvecK -(mulmxKpV sAE); move: (mxvec A *m _) => u.\n  rewrite !mulmx_sum_row !linear_sum mulmx_suml; apply: eq_bigr => i _ /=.\n  by rewrite !linearZ -scalemxAl /= cEB.\nby rewrite cEB // vec_mxK row_sub.\nQed.\nArguments cent_mxP {m n B R}.\n\nLemma scalar_mx_cent m n a (R : 'A_(m, n)) : (a%:M \\in 'C(R))%MS.\nProof. by apply/cent_mxP=> A _; apply: scalar_mxC. Qed.\n\nLemma center_mx_sub m n (R : 'A_(m, n)) : ('Z(R) <= R)%MS.\nProof. exact: capmxSl. Qed.\n\nLemma center_mxP m n A (R : 'A_(m, n)) :\n  reflect (A \\in R /\\ forall B, B \\in R -> B *m A = A *m B)\n          (A \\in 'Z(R))%MS.\nProof.\nrewrite sub_capmx; case R_A: (A \\in R); last by right; case.\nby apply: (iffP cent_mxP) => [cAR | [_ cAR]].\nQed.\nArguments center_mxP {m n A R}.\n\nLemma mxring_id_uniq m n (R : 'A_(m, n)) e1 e2 :\n  mxring_id R e1 -> mxring_id R e2 -> e1 = e2.\nProof.\nby case=> [_ Re1 idRe1 _] [_ Re2 _ ide2R]; rewrite -(idRe1 _ Re2) ide2R.\nQed.\n\nLemma cent_mx_ideal m n (R : 'A_(m, n)) : left_mx_ideal 'C(R)%MS 'C(R)%MS.\nProof.\napply/mulsmx_subP=> A1 A2 C_A1 C_A2; apply/cent_mxP=> B R_B.\nby rewrite mulmxA (cent_mxP C_A1) // -!mulmxA (cent_mxP C_A2).\nQed.\n\nLemma cent_mx_ring m n (R : 'A_(m, n)) : n > 0 -> mxring 'C(R)%MS.\nProof.\nmove=> n_gt0; rewrite /mxring cent_mx_ideal; apply/mxring_idP.\nexists 1%:M; split=> [||A _|A _]; rewrite ?mulmx1 ?mul1mx ?scalar_mx_cent //.\nby rewrite -mxrank_eq0 mxrank1 -lt0n.\nQed.\n\nLemma mxdirect_adds_center m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n    mx_ideal (R1 + R2)%MS R1 -> mx_ideal (R1 + R2)%MS R2 ->\n    mxdirect (R1 + R2) ->\n  ('Z((R1 + R2)%MS) :=: 'Z(R1) + 'Z(R2))%MS.\nProof.\ncase/andP=> idlR1 idrR1 /andP[idlR2 idrR2] /mxdirect_addsP dxR12.\napply/eqmxP/andP; split.\n  apply/memmx_subP=> z0; rewrite sub_capmx => /andP[].\n  case/memmx_addsP=> z [R1z1 R2z2 ->{z0}] Cz.\n  rewrite linearD addmx_sub_adds //= ?sub_capmx ?R1z1 ?R2z2 /=.\n    apply/cent_mxP=> A R1_A; have R_A := submx_trans R1_A (addsmxSl R1 R2).\n    have Rz2 := submx_trans R2z2 (addsmxSr R1 R2).\n    rewrite -{1}[z.1](addrK z.2) mulmxBr (cent_mxP Cz) // mulmxDl.\n    rewrite [A *m z.2]memmx0 1?[z.2 *m A]memmx0 ?addrK //.\n      by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\n    by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\n  apply/cent_mxP=> A R2_A; have R_A := submx_trans R2_A (addsmxSr R1 R2).\n  have Rz1 := submx_trans R1z1 (addsmxSl R1 R2).\n  rewrite -{1}[z.2](addKr z.1) mulmxDr (cent_mxP Cz) // mulmxDl.\n  rewrite mulmxN [A *m z.1]memmx0 1?[z.1 *m A]memmx0 ?addKr //.\n    by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\n  by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\nrewrite addsmx_sub; apply/andP; split.\n  apply/memmx_subP=> z; rewrite sub_capmx => /andP[R1z cR1z].\n  have Rz := submx_trans R1z (addsmxSl R1 R2).\n  rewrite sub_capmx Rz; apply/cent_mxP=> A0.\n  case/memmx_addsP=> A [R1_A1 R2_A2] ->{A0}.\n  have R_A2 := submx_trans R2_A2 (addsmxSr R1 R2).\n  rewrite mulmxDl mulmxDr (cent_mxP cR1z) //; congr (_ + _).\n  rewrite [A.2 *m z]memmx0 1?[z *m A.2]memmx0 //.\n    by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\n  by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\napply/memmx_subP=> z; rewrite !sub_capmx => /andP[R2z cR2z].\nhave Rz := submx_trans R2z (addsmxSr R1 R2); rewrite Rz.\napply/cent_mxP=> _ /memmx_addsP[A [R1_A1 R2_A2 ->]].\nrewrite mulmxDl mulmxDr (cent_mxP cR2z _ R2_A2) //; congr (_ + _).\nhave R_A1 := submx_trans R1_A1 (addsmxSl R1 R2).\nrewrite [A.1 *m z]memmx0 1?[z *m A.1]memmx0 //.\n  by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\nby rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\nQed.\n\nLemma mxdirect_sums_center (I : finType) m n (R : 'A_(m, n)) R_ :\n    (\\sum_i R_ i :=: R)%MS -> mxdirect (\\sum_i R_ i) ->\n    (forall i : I, mx_ideal R (R_ i)) ->\n  ('Z(R) :=: \\sum_i 'Z(R_ i))%MS.\nProof.\nmove=> defR dxR idealR.\nhave sR_R: (R_ _ <= R)%MS by move=> i; rewrite -defR (sumsmx_sup i).\nhave anhR i j A B : i != j -> A \\in R_ i -> B \\in R_ j -> A *m B = 0.\n  move=> ne_ij RiA RjB; apply: memmx0.\n  have [[_ idRiR] [idRRj _]] := (andP (idealR i), andP (idealR j)).\n  rewrite -(mxdirect_sumsP dxR j) // sub_capmx (sumsmx_sup i) //.\n    by rewrite (mulsmx_subP idRRj) // (memmx_subP (sR_R i)).\n  by rewrite (mulsmx_subP idRiR) // (memmx_subP (sR_R j)).\napply/eqmxP/andP; split.\n  apply/memmx_subP=> Z; rewrite sub_capmx => /andP[].\n  rewrite -{1}defR => /memmx_sumsP[z ->{Z} Rz cRz].\n  apply/memmx_sumsP; exists z => // i; rewrite sub_capmx Rz.\n  apply/cent_mxP=> A RiA; have:= cent_mxP cRz A (memmx_subP (sR_R i) A RiA).\n  rewrite (bigD1 i) //= mulmxDl mulmxDr mulmx_suml mulmx_sumr.\n  by rewrite !big1 ?addr0 // => j; last rewrite eq_sym; move/anhR->.\napply/sumsmx_subP => i _; apply/memmx_subP=> z; rewrite sub_capmx.\ncase/andP=> Riz cRiz; rewrite sub_capmx (memmx_subP (sR_R i)) //=.\napply/cent_mxP=> A; rewrite -{1}defR; case/memmx_sumsP=> a -> R_a.\nrewrite (bigD1 i) // mulmxDl mulmxDr mulmx_suml mulmx_sumr.\nrewrite !big1 => [|j|j]; first by rewrite !addr0 (cent_mxP cRiz).\n  by rewrite eq_sym => /anhR->.\nby move/anhR->.\nQed.\n\nEnd MatrixAlgebra.\n\nArguments mulsmx {F m1%N m2%N n%N} R1%MS R2%MS.\nArguments left_mx_ideal {F m1%N m2%N n%N} R%MS S%MS : rename.\nArguments right_mx_ideal {F m1%N m2%N n%N} R%MS S%MS : rename.\nArguments mx_ideal {F m1%N m2%N n%N} R%MS S%MS : rename.\nArguments mxring_id {F m%N n%N} R%MS e%R.\nArguments has_mxring_id {F m%N n%N} R%MS.\nArguments mxring {F m%N n%N} R%MS.\nArguments cent_mx {F m%N n%N} R%MS.\nArguments center_mx {F m%N n%N} R%MS.\n\nNotation \"A \\in R\" := (submx (mxvec A) R) : matrix_set_scope.\nNotation \"R * S\" := (mulsmx R S) : matrix_set_scope.\nNotation \"''C' ( R )\" := (cent_mx R) : matrix_set_scope.\nNotation \"''C_' R ( S )\" := (R :&: 'C(S))%MS : matrix_set_scope.\nNotation \"''C_' ( R ) ( S )\" := ('C_R(S))%MS (only parsing) : matrix_set_scope.\nNotation \"''Z' ( R )\" := (center_mx R) : matrix_set_scope.\n\nArguments memmx_subP {F m1 m2 n R1 R2}.\nArguments memmx_eqP {F m1 m2 n R1 R2}.\nArguments memmx_addsP {F m1 m2 n} A [R1 R2].\nArguments memmx_sumsP {F I P n A R_}.\nArguments mulsmx_subP {F m1 m2 m n R1 R2 R}.\nArguments mulsmxP {F m1 m2 n A R1 R2}.\nArguments mxring_idP F {m n R}.\nArguments cent_rowP {F m n B R}.\nArguments cent_mxP {F m n B R}.\nArguments center_mxP {F m n A R}.\n\n(* Parametricity for the row-space/F-algebra theory.                         *)\nSection MapMatrixSpaces.\n\nVariables (aF rF : fieldType) (f : {rmorphism aF -> rF}).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\n\nLemma Gaussian_elimination_map m n (A : 'M_(m, n)) :\n  Gaussian_elimination A^f = ((col_ebase A)^f, (row_ebase A)^f, \\rank A).\nProof.\nrewrite mxrankE /row_ebase /col_ebase unlock.\nelim: m n A => [|m IHm] [|n] A /=; rewrite ?map_mx1 //.\nset pAnz := [pred k | A k.1 k.2 != 0].\nrewrite (@eq_pick _ _ pAnz) => [|k]; last by rewrite /= mxE fmorph_eq0.\ncase: {+}(pick _) => [[i j]|]; last by rewrite !map_mx1.\nrewrite mxE -fmorphV  -map_xcol -map_xrow -map_dlsubmx -map_drsubmx.\nrewrite -map_ursubmx -map_mxZ -map_mxM -map_mx_sub {}IHm /=.\ncase: {+}(Gaussian_elimination _) => [[L U] r] /=; rewrite map_xrow map_xcol.\nby rewrite !(@map_block_mx _ _ f 1 _ 1) !map_mx0 ?map_mx1 ?map_scalar_mx.\nQed.\n\nLemma mxrank_map m n (A : 'M_(m, n)) : \\rank A^f = \\rank A.\nProof. by rewrite mxrankE Gaussian_elimination_map. Qed.\n\nLemma row_free_map m n (A : 'M_(m, n)) : row_free A^f = row_free A.\nProof. by rewrite /row_free mxrank_map. Qed.\n\nLemma row_full_map m n (A : 'M_(m, n)) : row_full A^f = row_full A.\nProof. by rewrite /row_full mxrank_map. Qed.\n\nLemma map_row_ebase m n (A : 'M_(m, n)) : (row_ebase A)^f = row_ebase A^f.\nProof. by rewrite {2}/row_ebase unlock Gaussian_elimination_map. Qed.\n\nLemma map_col_ebase m n (A : 'M_(m, n)) : (col_ebase A)^f = col_ebase A^f.\nProof. by rewrite {2}/col_ebase unlock Gaussian_elimination_map. Qed.\n\nLemma map_row_base m n (A : 'M_(m, n)) :\n  (row_base A)^f = castmx (mxrank_map A, erefl n) (row_base A^f).\nProof.\nmove: (mxrank_map A); rewrite {2}/row_base mxrank_map => eqrr.\nby rewrite castmx_id map_mxM map_pid_mx map_row_ebase.\nQed.\n\nLemma map_col_base m n (A : 'M_(m, n)) :\n  (col_base A)^f = castmx (erefl m, mxrank_map A) (col_base A^f).\nProof.\nmove: (mxrank_map A); rewrite {2}/col_base mxrank_map => eqrr.\nby rewrite castmx_id map_mxM map_pid_mx map_col_ebase.\nQed.\n\nLemma map_pinvmx m n (A : 'M_(m, n)) : (pinvmx A)^f = pinvmx A^f.\nProof.\nrewrite !map_mxM !map_invmx map_row_ebase map_col_ebase.\nby rewrite map_pid_mx -mxrank_map.\nQed.\n\nLemma map_kermx m n (A : 'M_(m, n)) : (kermx A)^f = kermx A^f.\nProof.\nby rewrite !map_mxM map_invmx map_col_ebase -mxrank_map map_copid_mx.\nQed.\n\nLemma map_cokermx m n (A : 'M_(m, n)) : (cokermx A)^f = cokermx A^f.\nProof.\nby rewrite !map_mxM map_invmx map_row_ebase -mxrank_map map_copid_mx.\nQed.\n\nLemma map_submx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A^f <= B^f)%MS = (A <= B)%MS.\nProof. by rewrite !submxE -map_cokermx -map_mxM map_mx_eq0. Qed.\n\nLemma map_ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A^f < B^f)%MS = (A < B)%MS.\nProof. by rewrite /ltmx !map_submx. Qed.\n\nLemma map_eqmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A^f :=: B^f)%MS <-> (A :=: B)%MS.\nProof.\nsplit=> [/eqmxP|eqAB]; first by rewrite !map_submx => /eqmxP.\nby apply/eqmxP; rewrite !map_submx !eqAB !submx_refl.\nQed.\n\nLemma map_genmx m n (A : 'M_(m, n)) : (<<A>>^f :=: <<A^f>>)%MS.\nProof. by apply/eqmxP; rewrite !(genmxE, map_submx) andbb. Qed.\n\nLemma map_addsmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (((A + B)%MS)^f :=: A^f + B^f)%MS.\nProof.\nby apply/eqmxP; rewrite !addsmxE -map_col_mx !map_submx !addsmxE andbb.\nQed.\n\nLemma map_capmx_gen m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (capmx_gen A B)^f = capmx_gen A^f B^f.\nProof. by rewrite map_mxM map_lsubmx map_kermx map_col_mx. Qed.\n\nLemma map_capmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  ((A :&: B)^f :=: A^f :&: B^f)%MS.\nProof.\nby apply/eqmxP; rewrite !capmxE -map_capmx_gen !map_submx -!capmxE andbb.\nQed.\n\nLemma map_complmx m n (A : 'M_(m, n)) : (A^C^f = A^f^C)%MS.\nProof. by rewrite map_mxM map_row_ebase -mxrank_map map_copid_mx. Qed.\n\nLemma map_diffmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  ((A :\\: B)^f :=: A^f :\\: B^f)%MS.\nProof.\napply/eqmxP; rewrite !diffmxE -map_capmx_gen -map_complmx.\nby rewrite -!map_capmx !map_submx -!diffmxE andbb.\nQed.\n\nLemma map_eigenspace n (g : 'M_n) a : (eigenspace g a)^f = eigenspace g^f (f a).\nProof. by rewrite map_kermx map_mx_sub ?map_scalar_mx. Qed.\n\nLemma eigenvalue_map n (g : 'M_n) a : eigenvalue g^f (f a) = eigenvalue g a.\nProof. by rewrite /eigenvalue -map_eigenspace map_mx_eq0. Qed.\n\nLemma memmx_map m n A (E : 'A_(m, n)) : (A^f \\in E^f)%MS = (A \\in E)%MS.\nProof. by rewrite -map_mxvec map_submx. Qed.\n\nLemma map_mulsmx m1 m2 n (E1 : 'A_(m1, n)) (E2 : 'A_(m2, n)) :\n  ((E1 * E2)%MS^f :=: E1^f * E2^f)%MS.\nProof.\nrewrite /mulsmx; elim/big_rec2: _ => [|i A Af _ eqA]; first by rewrite map_mx0.\napply: (eqmx_trans (map_addsmx _ _)); apply: adds_eqmx {A Af}eqA.\napply/eqmxP; rewrite !map_genmx !genmxE map_mxM.\napply/rV_eqP=> u; congr (u <= _ *m _)%MS.\nby apply: map_lin_mx => //= A; rewrite map_mxM // map_vec_mx map_row.\nQed.\n\nLemma map_cent_mx m n (E : 'A_(m, n)) : ('C(E)%MS)^f = 'C(E^f)%MS.\nProof.\nrewrite map_kermx //; congr (kermx _); apply: map_lin_mx => // A.\nrewrite map_mxM //; congr (_ *m _); apply: map_lin_mx => //= B.\nby rewrite map_mx_sub ? map_mxM.\nQed.\n\nLemma map_center_mx m n (E : 'A_(m, n)) : (('Z(E))^f :=: 'Z(E^f))%MS.\nProof. by rewrite /center_mx -map_cent_mx; apply: map_capmx. Qed.\n\nEnd MapMatrixSpaces.\n", "meta": {"author": "gares", "repo": "mathcomp", "sha": "f4ea1abac523107baf16e3cf528752b22ad8fdb5", "save_path": "github-repos/coq/gares-mathcomp", "path": "github-repos/coq/gares-mathcomp/mathcomp-f4ea1abac523107baf16e3cf528752b22ad8fdb5/mathcomp/algebra/mxalgebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6943692728964198}}
{"text": "Require Import Bool Recdef Equality FunctionalExtensionality.\nRequire Import List.\nImport ListNotations.\n\nInductive PTree (A : Type) : Type :=\n| L : A -> PTree A\n| N : PTree (A * A) -> PTree A.\n\nArguments L {A} _.\nArguments N {A} _.\n\nFixpoint map {A B : Type} (f : A -> B) (t : PTree A) : PTree B :=\nmatch t with\n| L x  => L (f x)\n| N t' => N (map (fun '(x, y) => (f x, f y)) t')\nend.\n\nDefinition swap {A B : Type} (p : A * B) : B * A :=\nmatch p with\n| (x, y) => (y, x)\nend.\n\nFixpoint mirror {A : Type} (t : PTree A) : PTree A :=\nmatch t with\n| L x  => L x\n| N t' => N (map swap (mirror t'))\nend.\n\nFunction leftmost {A : Type} (t : PTree A) : option A :=\nmatch t with\n| L x  => Some x\n| N t' =>\n  match leftmost t' with\n  | None        => None\n  | Some (x, _) => Some x\n  end\nend.\n\nFunction rightmost {A : Type} (t : PTree A) : option A :=\nmatch t with\n| L x  => Some x\n| N t' =>\n  match rightmost t' with\n  | None        => None\n  | Some (_, x) => Some x\n  end\nend.\n\nFixpoint size {A : Type} (t : PTree A) : nat :=\nmatch t with\n| L x  => 0\n| N t' => 1 + size t'\nend.\n\nFixpoint height {A : Type} (t : PTree A) : nat :=\nmatch t with\n| L x => 0\n| N t' => 1 + height t'\nend.\n\nFixpoint flatten {A : Type} (l : list (A * A)) : list A :=\nmatch l with\n| [] => []\n| (hl, hr) :: t => hl :: hr :: flatten t\nend.\n\nFixpoint bfs {A : Type} (t : PTree A) : list A :=\nmatch t with\n| L x => [x]\n| N t' => flatten (bfs t')\nend.\n\nFixpoint complete {A : Type} (n : nat) (x : A) : PTree A :=\nmatch n with\n| 0 => L x\n| S n' => N (complete n' (x, x))\nend.\n\nFixpoint any {A : Type} (p : A -> bool) (t : PTree A) : bool :=\nmatch t with\n| L x  => p x\n| N t' => any (fun '(x, y) => p x || p y) t'\nend.\n\nFixpoint all {A : Type} (p : A -> bool) (t : PTree A) : bool :=\nmatch t with\n| L x  => p x\n| N t' => all (fun '(x, y) => p x && p y) t'\nend.\n\nFixpoint find {A : Type} (p : A -> bool) (t : PTree A) : option A :=\nmatch t with\n| L x  => if p x then Some x else None\n| N t' =>\n  match find (fun '(x, y) => p x || p y) t' with\n  | None        => None\n  | Some (x, y) => if p x then Some x else Some y\n  end\nend.\n\n(*\nFixpoint zipWith {A B C : Type} (f : A -> B -> C) (ta : PTree A) (tb : PTree B) : PTree C :=\nmatch ta, tb with\n| L x, L y => L (f x y)\n| _, L x => L x\n| Layer a ta', Layer b tb' => Layer (f a b) (zipWith (fun '(al, ar) '(bl, br) => (f al bl, f ar br)) ta' tb')\nend.\n*)\n\nFixpoint left {A : Type} (t : PTree (A * A)) : PTree A :=\nmatch t with\n| L (x, _) => L x\n| N t'     => N (left t')\nend.\n\nFixpoint right {A : Type} (t : PTree (A * A)) : PTree A :=\nmatch t with\n| L (x, _) => L x\n| N t'     => N (right t')\nend.\n\nFixpoint count {A : Type} (p : A -> nat) (t : PTree A) : nat :=\nmatch t with\n| L x  => p x\n| N t' => count (fun '(x, y) => p x + p y) t'\nend.\n\n(* TODO\n\nParameter leaf : forall A : Type, A -> BTree A.\n\nParameter isL x : forall A : Type, BTree A -> bool.\n\nParameter root : forall A : Type, BTree A -> option A.\n\nParameter unN : forall A : Type, BTree A -> option (A * BTree A * BTree A).\n\nParameter inorder : forall A : Type, BTree A -> list A.\nParameter preorder : forall A : Type, BTree A -> list A.\nParameter postorder : forall A : Type, BTree A -> list A.\n\nParameter iterate : forall A : Type, (A -> A) -> nat -> A -> BTree A.\n\nParameter index : forall A : Type, list bool -> BTree A -> option A.\nParameter nth : forall A : Type, nat -> BTree A -> option A.\n\nParameter take : forall A : Type, nat -> BTree A -> BTree A.\nParameter drop : forall A : Type, nat -> BTree A -> list (BTree A).\nParameter takedrop :\n  forall A : Type, nat -> BTree A -> BTree A * list (BTree A).\n\nParameter intersperse : forall A : Type, A -> BTree A -> BTree A.\n\nParameter insertAtLeaf :\n  forall A : Type, list bool -> BTree A -> BTree A.\n\nParameter findIndex :\n  forall A : Type, (A -> bool) -> BTree A -> option (list bool).\n\nParameter takeWhile : forall A : Type, (A -> bool) -> BTree A -> BTree A.\n\nParameter findIndices :\n  forall A : Type, (A -> bool) -> BTree A -> list (list bool).\n\nParameter unzipWith :\n forall A B C : Type, (A -> B * C) -> BTree A -> BTree B * BTree C.\n*)\n\nLemma map_id :\n  forall {A : Type} (t : PTree A),\n    map id t = t.\nProof.\n  induction t; cbn; unfold id.\n    reflexivity.\n    rewrite <- IHt at 2. repeat f_equal.\n      extensionality p. destruct p. reflexivity.\nQed.\n\nLemma map_map :\n  forall {A B C : Type} (f : A -> B) (g : B -> C) (t : PTree A),\n    map g (map f t) = map (fun x => g (f x)) t.\nProof.\n  intros until t. revert B C f g.\n  induction t; cbn; intros.\n    reflexivity.\n    rewrite IHt. repeat f_equal.\n      extensionality x. destruct x. reflexivity.\nQed.\n\nLemma leftmost_map :\n  forall {A B : Type} (f : A -> B) (t : PTree A),\n    leftmost (map f t) =\n      match leftmost t with\n      | None   => None\n      | Some a => Some (f a)\n      end.\nProof.\n  intros. revert B f.\n  induction t; cbn; intros.\n    reflexivity.\n    rewrite IHt. destruct (leftmost t).\n      destruct p. reflexivity.\n      reflexivity.\nQed.\n\nLemma leftmost_mirror :\n  forall {A : Type} (t : PTree A),\n    leftmost (mirror t) = rightmost t.\nProof.\n  induction t; cbn.\n    reflexivity.\n    rewrite leftmost_map, IHt.\n      destruct (rightmost t) as [[] |]; cbn; reflexivity.\nQed.\n\nLemma map_mirror :\n  forall {A B : Type} (f : A -> B) (t : PTree A),\n    map f (mirror t) = mirror (map f t).\nProof.\n  intros until t. revert B f.\n  induction t; cbn; intros.\n    reflexivity.\n    rewrite <- IHt, !map_map. repeat f_equal.\n      extensionality p. destruct p. cbn. reflexivity.\nQed.\n\nLemma mirror_mirror :\n  forall {A : Type} (t : PTree A),\n    mirror (mirror t) = t.\nProof.\n  induction t; cbn.\n    reflexivity.\n    rewrite !map_mirror, map_map. rewrite <- IHt at 2.\n      repeat f_equal. rewrite <- map_id. f_equal.\n      extensionality p. destruct p. cbn. reflexivity.\nQed.\n\n\n(*\nInductive PTree' {A : Type} (P : A -> Type) : PTree A -> Type :=\n| L x' : PTree' P L x\n| Layer' :\n    forall (x : A) (t : PTree (prod A A)),\n      P x -> PTree' (fun '(x, y) => prod (P x) (P y)) t -> PTree' P (Layer x t).\n\nFixpoint PTree_ind_deep\n  (P : forall (A : Type) (Q : A -> Type), PTree A -> Type)\n  (empty : forall (A : Type) (Q : A -> Type),\n             P A Q L x)\n  (layer : forall (A : Type) (Q : A -> Type) (x : A) (t : PTree (A * A)),\n             Q x -> P (prod A A) (fun '(x, y) => prod (Q x) (Q y)) t -> P A Q (Layer x t))\n  {A : Type} (Q : A -> Type)\n  {t : PTree A} (t' : PTree' Q t) {struct t'} : P A Q t.\nProof.\n  destruct t' as [| x t Qx Ct].\n    apply empty.\n    apply layer.\n      exact Qx.\n      apply PTree_ind_deep; assumption.\nDefined.\n*)", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/code/IndRec/Nested/PTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.6943357046713002}}
{"text": "(** Let's prove a simple theorem **)\n\nTheorem thm : forall P Q:Prop, ((P->Q)/\\P)->Q.\nintros p q h.\ndestruct h.\napply H.\nassumption.\nQed.\n", "meta": {"author": "xavierdpt", "repo": "adventures", "sha": "038a17cf71d8f9690ad168b2592b12e61d2e6c32", "save_path": "github-repos/coq/xavierdpt-adventures", "path": "github-repos/coq/xavierdpt-adventures/adventures-038a17cf71d8f9690ad168b2592b12e61d2e6c32/trove/SF1Preface/nice/nice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6942519294300178}}
{"text": "(** * Maps: Total and Partial Maps *)\n\n(** Maps (or dictionaries) are ubiquitous data structures both *)\n(*     generally and in the theory of programming languages in *)\n(*     particular; we're going to need them in many places in the coming *)\n(*     chapters.  They also make a nice case study using ideas we've seen *)\n(*     in previous chapters, including building data structures out of *)\n(*     higher-order functions (from [Basics] and [Poly]) and the use of *)\n(*     reflection to streamline proofs (from [IndProp]). *)\n\n(*     We'll define two flavors of maps: _total_ maps, which include a *)\n(*     \"default\" element to be returned when a key being looked up *)\n(*     doesn't exist, and _partial_ maps, which return an [option] to *)\n(*     indicate success or failure.  The latter is defined in terms of *)\n(*     the former, using [None] as the default element. *)\n\n(* ################################################################# *)\n(** * The Coq Standard Library *)\n\n(** One small digression before we get to maps. *)\n\n(*     Unlike the chapters we have seen so far, this one does not *)\n(*     [Require Import] the chapter before it (and, transitively, all the *)\n(*     earlier chapters).  Instead, in this chapter and from now, on *)\n(*     we're going to import the definitions and theorems we need *)\n(*     directly from Coq's standard library stuff.  You should not notice *)\n(*     much difference, though, because we've been careful to name our *)\n(*     own definitions and theorems the same as their counterparts in the *)\n(*     standard library, wherever they overlap. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(** Documentation for the standard library can be found at *)\n(*     http://coq.inria.fr/library/.   *)\n\n(*     The [Search] command is a good way to look for theorems involving  *)\n(*     objects of specific types.  Take a minute now to experiment with it. *)\n\n(* ################################################################# *)\n(** * Identifiers *)\n\n(** First, we need a type for the keys that we use to index into our *)\n(*     maps.  For this purpose, we again use the type [id] from the *)\n(*     [Lists] chapter.  To make this chapter self contained, we repeat *)\n(*     its definition here, together with the equality comparison *)\n(*     function for [id]s and its fundamental property. *)\n\nInductive id : Type :=\n  | Id : string -> id.\n\nDefinition beq_id x y :=\n  match x,y with\n    | Id n1, Id n2 => if string_dec n1 n2 then true else false\n  end.\n\n(** (The function [string_dec] comes from Coq's string library. *)\n(*     If you check its result type, you'll see that it does not actually *)\n(*     return a [bool], but rather a type that looks like [{x = y} + {x *)\n(*     <> y}], called a [sumbool], which can be thought of as an *)\n(*     \"evidence-carrying boolean.\"  Formally, an element of [sumbool] is *)\n(*     either a proof that two things are equal or a proof that they are *)\n(*     unequal, together with a tag indicating which.  But for present *)\n(*     purposes you can think of it as just a fancy [bool].) *)\n\nTheorem beq_id_refl : forall id, true = beq_id id id.\nProof.\n  intros [n]. simpl. destruct (string_dec n n).\n  - reflexivity.\n  - destruct n0. reflexivity.\nQed.\n\n(** The following useful property of [beq_id] follows from an *)\n(*     analogous lemma about strings: *)\n\nTheorem beq_id_true_iff : forall x y : id,\n  beq_id x y = true <-> x = y.\nProof.\n   intros [n1] [n2].\n   unfold beq_id.\n   destruct (string_dec n1 n2).\n   - subst. split. reflexivity. reflexivity.\n   - split.\n     + intros contra. inversion contra.\n     + intros H. inversion H. subst. destruct n. reflexivity.\nQed.\n\n(** Similarly: *)\n\nTheorem beq_id_false_iff : forall x y : id,\n  beq_id x y = false\n  <-> x <> y.\nProof.\n  intros x y. rewrite <- beq_id_true_iff.\n  rewrite not_true_iff_false. reflexivity. Qed.\n\n(** This useful variant follows just by rewriting: *)\n\nTheorem false_beq_id : forall x y : id,\n   x <> y\n   -> beq_id x y = false.\nProof.\n  intros x y. rewrite beq_id_false_iff.\n  intros H. apply H. Qed.\n\n(* ################################################################# *)\n(** * Total Maps *)\n\n(** Our main job in this chapter will be to build a definition of *)\n(*     partial maps that is similar in behavior to the one we saw in the *)\n(*     [Lists] chapter, plus accompanying lemmas about its behavior. *)\n\n(*     This time around, though, we're going to use _functions_, rather *)\n(*     than lists of key-value pairs, to build maps.  The advantage of *)\n(*     this representation is that it offers a more _extensional_ view of *)\n(*     maps, where two maps that respond to queries in the same way will *)\n(*     be represented as literally the same thing (the very same function), *)\n(*     rather than just \"equivalent\" data structures.  This, in turn, *)\n(*     simplifies proofs that use maps. *)\n\n(** We build partial maps in two steps.  First, we define a type of *)\n(*     _total maps_ that return a default value when we look up a key *)\n(*     that is not present in the map. *)\n\nDefinition total_map (A:Type) := id -> A.\n\n(** Intuitively, a total map over an element type [A] is just a *)\n(*     function that can be used to look up [id]s, yielding [A]s. *)\n\n(** The function [t_empty] yields an empty total map, given a default *)\n(*     element; this map always returns the default element when applied *)\n(*     to any id. *)\n\nDefinition t_empty {A:Type} (v : A) : total_map A :=\n  (fun _ => v).\n\n(** More interesting is the [update] function, which (as before) takes *)\n(*     a map [m], a key [x], and a value [v] and returns a new map that *)\n(*     takes [x] to [v] and takes every other key to whatever [m] does. *)\n\nDefinition t_update {A:Type} (m : total_map A)\n                    (x : id) (v : A) :=\n  fun x' => if beq_id x x' then v else m x'.\n\n(** This definition is a nice example of higher-order programming: *)\n(*     [t_update] takes a _function_ [m] and yields a new function  *)\n(*     [fun x' => ...] that behaves like the desired map. *)\n\n(*     For example, we can build a map taking [id]s to [bool]s, where [Id *)\n(*     \"bar\"] is mapped to [true] and every other key is mapped to [false], *)\n(*     like this: *)\n\nDefinition examplemap :=\n  t_update (t_update (t_empty false) (Id \"foo\") false)\n           (Id \"bar\") true.\n\n(** This completes the definition of total maps.  Note that we *)\n(*     don't need to define a [find] operation because it is just *)\n(*     function application! *)\n\nExample update_example1 : examplemap (Id \"baz\") = false.\nProof. reflexivity. Qed.\n\nExample update_example2 : examplemap (Id \"foo\") = false.\nProof. reflexivity. Qed.\n\nExample update_example3 : examplemap (Id \"quux\") = false.\nProof. reflexivity. Qed.\n\nExample update_example4 : examplemap (Id \"bar\") = true.\nProof. reflexivity. Qed.\n\n(** To use maps in later chapters, we'll need several fundamental *)\n(*     facts about how they behave. *)\n\n(** Even if you don't work the following exercises, make sure *)\n(*     you thoroughly understand the statements of the lemmas! *)\n\n(** (Some of the proofs require the functional extensionality axiom, *)\n(*     which is discussed in the [Logic] chapter.) *)\n\n(** **** Exercise: 1 star, optional (t_apply_empty)  *)\n(** First, the empty map returns its default element for all keys: *)\n\nLemma t_apply_empty:  forall A x v, @t_empty A v x = v.\nProof.\n  auto.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_eq)  *)\n(** Next, if we update a map [m] at a key [x] with a new value [v] *)\n(*     and then look up [x] in the map resulting from the [update], we *)\n(*     get back [v]: *)\n\nLemma t_update_eq : forall A (m: total_map A) x v,\n  (t_update m x v) x = v.\nProof.\n  intros A m x v.\n  unfold t_update.\n  now rewrite <- beq_id_refl.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_neq)  *)\n(** On the other hand, if we update a map [m] at a key [x1] and then *)\n(*     look up a _different_ key [x2] in the resulting map, we get the *)\n(*     same result that [m] would have given: *)\n\nTheorem t_update_neq : forall (X:Type) v x1 x2\n                         (m : total_map X),\n  x1 <> x2 ->\n  (t_update m x1 v) x2 = m x2.\nProof.\n  intros X v x1 x2 m H.\n  unfold t_update.\n  rewrite <- beq_id_false_iff in H.\n  now rewrite H.\nQed.\n\n(** **** Exercise: 2 stars, optional (t_update_shadow)  *)\n(** If we update a map [m] at a key [x] with a value [v1] and then *)\n(*     update again with the same key [x] and another value [v2], the *)\n(*     resulting map behaves the same (gives the same result when applied *)\n(*     to any key) as the simpler map obtained by performing just *)\n(*     the second [update] on [m]: *)\n\nLemma t_update_shadow : forall A (m: total_map A) v1 v2 x,\n    t_update (t_update m x v1) x v2\n  = t_update m x v2.\nProof.\n  intros A m v1 v2 x.\n  unfold t_update.\n  apply functional_extensionality.\n  intros x0.\n  now destruct (beq_id x x0).\nQed.\n(** [] *)\n\n(** For the final two lemmas about total maps, it's convenient to use *)\n(*     the reflection idioms introduced in chapter [IndProp].  We begin *)\n(*     by proving a fundamental _reflection lemma_ relating the equality *)\n(*     proposition on [id]s with the boolean function [beq_id]. *)\n\n(** **** Exercise: 2 stars, optional (beq_idP)  *)\n(** Use the proof of [beq_natP] in chapter [IndProp] as a template to *)\n(*     prove the following: *)\n\nLemma beq_idP : forall x y, reflect (x = y) (beq_id x y).\nProof.\n  intros x y.\n  destruct (beq_id x y) eqn:Heq.\n  constructor. now apply beq_id_true_iff.\n  constructor. now apply beq_id_false_iff.\nQed.\n\n(** Now, given [id]s [x1] and [x2], we can use the [destruct (beq_idP *)\n(*     x1 x2)] to simultaneously perform case analysis on the result of *)\n(*     [beq_id x1 x2] and generate hypotheses about the equality (in the *)\n(*     sense of [=]) of [x1] and [x2]. *)\n\n(** **** Exercise: 2 stars (t_update_same)  *)\n(** With the example in chapter [IndProp] as a template, use *)\n(*     [beq_idP] to prove the following theorem, which states that if we *)\n(*     update a map to assign key [x] the same value as it already has in *)\n(*     [m], then the result is equal to [m]: *)\n\nTheorem t_update_same : forall X x (m : total_map X),\n  t_update m x (m x) = m.\nProof.\n  intros X x m.\n  unfold t_update.\n  apply functional_extensionality.\n  intros x0.\n  destruct (beq_id x x0) eqn:Heq; subst.\n  apply beq_id_true_iff in Heq; now subst.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (t_update_permute)  *)\n(** Use [beq_idP] to prove one final property of the [update] *)\n(*     function: If we update a map [m] at two distinct keys, it doesn't *)\n(*     matter in which order we do the updates. *)\n\nTheorem t_update_permute : forall (X:Type) v1 v2 x1 x2\n                             (m : total_map X),\n  x2 <> x1 ->\n    (t_update (t_update m x2 v2) x1 v1)\n  = (t_update (t_update m x1 v1) x2 v2).\nProof.\n  intros X v1 v2 x1 x2 m H.\n  unfold t_update.\n  apply functional_extensionality.\n  intros x.\n  destruct (beq_id x1 x) eqn:Heq1;\n    destruct (beq_id x2 x) eqn:Heq2;\n    try now auto.\n  apply beq_id_true_iff in Heq1;\n    apply beq_id_true_iff in Heq2;\n    congruence.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Partial maps *)\n\n(** Finally, we define _partial maps_ on top of total maps.  A partial *)\n(*     map with elements of type [A] is simply a total map with elements *)\n(*     of type [option A] and default element [None]. *)\n\nDefinition partial_map (A:Type) := total_map (option A).\n\nDefinition empty {A:Type} : partial_map A :=\n  t_empty None.\n\nDefinition update {A:Type} (m : partial_map A)\n                  (x : id) (v : A) :=\n  t_update m x (Some v).\n\n(** We now straightforwardly lift all of the basic lemmas about total *)\n(*     maps to partial maps.  *)\n\nLemma apply_empty : forall A x, @empty A x = None.\nProof.\n  intros. unfold empty. rewrite t_apply_empty.\n  reflexivity.\nQed.\n\nLemma update_eq : forall A (m: partial_map A) x v,\n  (update m x v) x = Some v.\nProof.\n  intros. unfold update. rewrite t_update_eq.\n  reflexivity.\nQed.\n\nTheorem update_neq : forall (X:Type) v x1 x2\n                       (m : partial_map X),\n  x2 <> x1 ->\n  (update m x2 v) x1 = m x1.\nProof.\n  intros X v x1 x2 m H.\n  unfold update. rewrite t_update_neq. reflexivity.\n  apply H. Qed.\n\nLemma update_shadow : forall A (m: partial_map A) v1 v2 x,\n  update (update m x v1) x v2 = update m x v2.\nProof.\n  intros A m v1 v2 x1. unfold update. rewrite t_update_shadow.\n  reflexivity.\nQed.\n\nTheorem update_same : forall X v x (m : partial_map X),\n  m x = Some v ->\n  update m x v = m.\nProof.\n  intros X v x m H. unfold update. rewrite <- H.\n  apply t_update_same.\nQed.\n\nTheorem update_permute : forall (X:Type) v1 v2 x1 x2\n                                (m : partial_map X),\n  x2 <> x1 ->\n    (update (update m x2 v2) x1 v1)\n  = (update (update m x1 v1) x2 v2).\nProof.\n  intros X v1 v2 x1 x2 m. unfold update.\n  apply t_update_permute.\nQed.\n\n(** $Date: 2017-07-14 19:07:15 -0400 (Fri, 14 Jul 2017) $ *)\n\n", "meta": {"author": "secure-compilation", "repo": "different_traces", "sha": "2319e1db2cc9ab1690badb04fc591d1744e1e09b", "save_path": "github-repos/coq/secure-compilation-different_traces", "path": "github-repos/coq/secure-compilation-different_traces/different_traces-2319e1db2cc9ab1690badb04fc591d1744e1e09b/ResourceExhaustion/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.8840392924390585, "lm_q1q2_score": 0.6942436421943349}}
{"text": "Require Export Ensembles.\nRequire Import EnsemblesImplicit.\nRequire Export Families.\nRequire Export IndexedFamilies.\nRequire Export FiniteTypes.\nRequire Import EnsemblesSpec.\n\nRecord TopologicalSpace: Type := {\n  point_set :> Type;\n  open: Ensemble point_set -> Prop;\n  open_family_union:  forall F: Family point_set,\n                     (forall S: Ensemble point_set, In F S -> open S) -> open (FamilyUnion F);\n  open_intersection2: forall U V:Ensemble point_set, open U -> open V -> open (Intersection U V);\n  open_full: open Full_set\n}.\n\nArguments open [t].\nArguments open_family_union [t].\nArguments open_intersection2 [t].\n\nLemma open_empty: forall X:TopologicalSpace,\n  open (@Empty_set (point_set X)).\nProof.\nintros.\nrewrite <- empty_family_union.\napply open_family_union.\nintros.\ndestruct H.\nQed.\n\nLemma open_union2: forall {X:TopologicalSpace}\n  (U V:Ensemble (point_set X)), open U -> open V -> open (Union U V).\nProof.\nintros.\nassert (Union U V = FamilyUnion (Couple U V)).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H1.\nexists U; auto with sets.\nexists V; auto with sets.\ndestruct H1.\ndestruct H1.\nleft; trivial.\nright; trivial.\n\nrewrite H1; apply open_family_union.\nintros.\ndestruct H2; trivial.\nQed.\n\nLemma open_indexed_union: forall {X:TopologicalSpace} {A:Type}\n  (F:IndexedFamily A (point_set X)),\n  (forall a:A, open (F a)) -> open (IndexedUnion F).\nProof.\nintros.\nrewrite indexed_to_family_union.\napply open_family_union.\nintros.\ndestruct H0.\nrewrite H1; apply H.\nQed.\n\nLemma open_finite_indexed_intersection:\n  forall {X:TopologicalSpace} {A:Type}\n    (F:IndexedFamily A (point_set X)),\n    FiniteT A -> (forall a:A, open (F a)) ->\n    open (IndexedIntersection F).\nProof.\nintros.\ninduction H.\nrewrite empty_indexed_intersection.\napply open_full.\n\nassert (IndexedIntersection F = Intersection\n  (IndexedIntersection (fun x:T => F (Some x)))\n  (F None)).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H1.\nconstructor.\nconstructor.\nintros; apply H1.\napply H1.\ndestruct H1.\ndestruct H1.\nconstructor.\ndestruct a.\napply H1.\napply H2.\nrewrite H1.\napply open_intersection2.\napply IHFiniteT.\nintros; apply H0.\napply H0.\n\ndestruct H1.\nassert (IndexedIntersection F =\n  IndexedIntersection (fun x:X0 => F (f x))).\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\ndestruct H3.\nintro; apply H3.\nconstructor.\ndestruct H3.\nintro; rewrite <- H2 with a.\napply H3.\nrewrite H3.\napply IHFiniteT.\nintro; apply H0.\nQed.\n\nDefinition closed {X:TopologicalSpace} (F:Ensemble (point_set X)) :=\n  open (Ensembles.Complement F).\n\nLemma closed_complement_open: forall {X:TopologicalSpace}\n  (U:Ensemble (point_set X)), closed (Ensembles.Complement U) ->\n  open U.\nProof.\nintros.\nred in H.\nrewrite Complement_Complement in H.\nassumption.\nQed.\n\nLemma closed_union2: forall {X:TopologicalSpace}\n  (F G:Ensemble (point_set X)),\n  closed F -> closed G -> closed (Union F G).\nProof.\nintros.\nred in H, H0.\nred.\nassert (Ensembles.Complement (Union F G) =\n  Intersection (Ensembles.Complement F)\n               (Ensembles.Complement G)).\nunfold Ensembles.Complement.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nauto with sets.\nauto with sets.\ndestruct H1.\nred; red; intro.\ndestruct H3.\napply (H1 H3).\napply (H2 H3).\n\nrewrite H1.\napply open_intersection2; assumption.\nQed.\n\nLemma closed_intersection2: forall {X:TopologicalSpace}\n  (F G:Ensemble (point_set X)),\n  closed F -> closed G -> closed (Intersection F G).\nProof.\nintros.\nred in H, H0.\nred.\nassert (Ensembles.Complement (Intersection F G) =\n  Union (Ensembles.Complement F)\n        (Ensembles.Complement G)).\napply Extensionality_Ensembles; split; red; intros.\napply NNPP.\nred; intro.\nunfold Ensembles.Complement in H1.\nunfold In in H1.\ncontradict H1.\nconstructor.\napply NNPP.\nred; intro.\nauto with sets.\napply NNPP.\nred; intro.\nauto with sets.\n\nred; red; intro.\ndestruct H2.\ndestruct H1; auto with sets.\n\nrewrite H1; apply open_union2; trivial.\nQed.\n\nLemma closed_family_intersection: forall {X:TopologicalSpace}\n  (F:Family (point_set X)),\n  (forall S:Ensemble (point_set X), In F S -> closed S) ->\n  closed (FamilyIntersection F).\nProof.\nintros.\nunfold closed in H.\nred.\nassert (Ensembles.Complement (FamilyIntersection F) =\n  FamilyUnion [ S:Ensemble (point_set X) |\n                  In F (Ensembles.Complement S) ]).\napply Extensionality_Ensembles; split; red; intros.\napply NNPP.\nred; intro.\nred in H0; red in H0.\ncontradict H0.\nconstructor.\nintros.\napply NNPP.\nred; intro.\ncontradict H1.\nexists (Ensembles.Complement S).\nconstructor.\nrewrite Complement_Complement; assumption.\nassumption.\ndestruct H0.\nred; red; intro.\ndestruct H2.\ndestruct H0.\npose proof (H2 _ H0).\ncontradiction H3.\n\nrewrite H0; apply open_family_union.\nintros.\ndestruct H1.\npose proof (H _ H1).\nrewrite Complement_Complement in H2; assumption.\nQed.\n\nLemma closed_indexed_intersection: forall {X:TopologicalSpace}\n  {A:Type} (F:IndexedFamily A (point_set X)),\n  (forall a:A, closed (F a)) -> closed (IndexedIntersection F).\nProof.\nintros.\nrewrite indexed_to_family_intersection.\napply closed_family_intersection.\nintros.\ndestruct H0.\nrewrite H1; trivial.\nQed.\n\nLemma closed_finite_indexed_union: forall {X:TopologicalSpace}\n  {A:Type} (F:IndexedFamily A (point_set X)),\n  FiniteT A -> (forall a:A, closed (F a)) ->\n  closed (IndexedUnion F).\nProof.\nintros.\nred.\nassert (Ensembles.Complement (IndexedUnion F) =\n  IndexedIntersection (fun a:A => Ensembles.Complement (F a))).\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nintros.\nred; red; intro.\ncontradiction H1.\nexists a.\nassumption.\ndestruct H1.\nred; red; intro.\ndestruct H2.\ncontradiction (H1 a).\n\nrewrite H1; apply open_finite_indexed_intersection; trivial.\nQed.\n\nHint Unfold closed : topology.\nHint Resolve (@open_family_union) (@open_intersection2) open_full\n  open_empty (@open_union2) (@open_indexed_union)\n  (@open_finite_indexed_intersection) (@closed_complement_open)\n  (@closed_union2) (@closed_intersection2) (@closed_family_intersection)\n  (@closed_indexed_intersection) (@closed_finite_indexed_union)\n  : topology.\n\nSection Build_from_closed_sets.\n\nVariable X:Type.\nVariable closedP : Ensemble X -> Prop.\nHypothesis closedP_empty: closedP Empty_set.\nHypothesis closedP_union2: forall F G:Ensemble X,\n  closedP F -> closedP G -> closedP (Union F G).\nHypothesis closedP_family_intersection: forall F:Family X,\n  (forall G:Ensemble X, In F G -> closedP G) ->\n  closedP (FamilyIntersection F).\n\nDefinition Build_TopologicalSpace_from_closed_sets : TopologicalSpace.\nrefine (Build_TopologicalSpace X\n  (fun U:Ensemble X => closedP (Ensembles.Complement U)) _ _ _).\nintros.\nreplace (Ensembles.Complement (FamilyUnion F)) with\n  (FamilyIntersection [ G:Ensemble X | In F (Ensembles.Complement G) ]).\napply closedP_family_intersection.\ndestruct 1.\nrewrite <- Complement_Complement.\napply H; trivial.\napply Extensionality_Ensembles; split; red; intros.\nintro.\ndestruct H1.\ndestruct H0.\nabsurd (In (Ensembles.Complement S) x).\nintro.\ncontradiction H3.\napply H0.\nconstructor.\nrewrite Complement_Complement; trivial.\nconstructor.\ndestruct 1.\napply NNPP; intro.\ncontradiction H0.\nexists (Ensembles.Complement S); trivial.\n\nintros.\nreplace (Ensembles.Complement (Intersection U V)) with\n  (Union (Ensembles.Complement U) (Ensembles.Complement V)).\napply closedP_union2; trivial.\napply Extensionality_Ensembles; split; red; intros.\nintro.\ndestruct H2.\ndestruct H1; contradiction H1.\napply NNPP; intro.\ncontradiction H1.\nconstructor; apply NNPP; intro; contradiction H2;\n  [ left | right ]; trivial.\n\napply eq_ind with (1 := closedP_empty).\napply Extensionality_Ensembles; split; auto with sets;\n  red; intros.\ncontradiction H.\nconstructor.\nDefined.\n\nLemma Build_TopologicalSpace_from_closed_sets_closed:\n  forall (F:Ensemble (point_set Build_TopologicalSpace_from_closed_sets)),\n  closed F <-> closedP F.\nProof.\nintros.\nunfold closed.\nsimpl.\nrewrite Complement_Complement.\nsplit; trivial.\nQed.\n\nEnd Build_from_closed_sets.\n\nArguments Build_TopologicalSpace_from_closed_sets [X].\n", "meta": {"author": "verimath", "repo": "topology", "sha": "9405aaf18d99c718769f1d2af8e030a902687837", "save_path": "github-repos/coq/verimath-topology", "path": "github-repos/coq/verimath-topology/topology-9405aaf18d99c718769f1d2af8e030a902687837/src/top/TopologicalSpaces.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.694243622157322}}
{"text": "(* This file tests:\n    forward_for_simple_bound on 64-bit long integers,\n    forward load with 64-bit integer array subscript, and\n    forward store with 64-bit integer array subscript.\n*)\n\nRequire Import VST.floyd.proofauto.\nRequire Import VST.progs.min64.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs.  mk_varspecs prog. Defined.\n\nRequire Import ZArith.\nRequire Import List.\nImport ListNotations.\nOpen Scope Z.\n\n\nTheorem fold_min_general:\n  forall (al: list Z)(i: Z),\n  In i (al) ->\n  forall x, List.fold_right Z.min x al <= i.\nProof.\ninduction al; intros.\ninversion H.\ndestruct H.\nsubst a.\nsimpl.\napply Z.le_min_l.\nsimpl. rewrite Z.le_min_r.\napply IHal.\napply H.\nQed.\n\nTheorem fold_min:\n  forall (al: list Z)(i: Z),\n  In i (al) ->\n  List.fold_right Z.min (hd 0 al) al <= i.\nProof.\nintros.\napply fold_min_general.\napply H.\nQed.\n\nLemma Forall_fold_min:\n  forall (f: Z -> Prop) (x: Z) (al: list Z),\n    f x -> Forall f al -> f (fold_right Z.min x al).\nProof.\n intros.\n induction H0.\n simpl. auto.\n simpl.\n unfold Z.min at 1.\n destruct (Z.compare x0 (fold_right Z.min x l)) eqn:?; auto.\nQed.\n\nLemma fold_min_another:\n  forall x al y,\n    fold_right Z.min x (al ++ [y]) = Z.min (fold_right Z.min x al) y.\nProof.\n intros.\n revert x; induction al; simpl; intros.\n apply Z.min_comm.\n rewrite <- Z.min_assoc. f_equal.\n apply IHal.\nQed.\n\nLemma is_int_I32_Znth_map_Vint:\n forall i s al,\n  0 <= i < Zlength al ->\n  is_int I32 s (Znth i (map Vint al)).\nProof.\nintros. rewrite Znth_map; auto.\nQed.\n#[export] Hint Extern 3 (is_int I32 _ (Znth _ (map Vint _))) =>\n  (apply  is_int_I32_Znth_map_Vint; rewrite ?Zlength_map; lia) : core.\n\nDefinition minimum_spec :=\n DECLARE _minimum\n  WITH a: val, n: Z, al: list Z\n  PRE [ tptr tint , tlong ]\n    PROP  (1 <= n <= Int64.max_signed; Forall repable_signed al)\n    PARAMS (a; Vlong (Int64.repr n))\n    SEP   (data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a)\n  POST [ tint ]\n    PROP ()\n    RETURN (Vint (Int.repr (fold_right Z.min (hd 0 al) al)))\n    SEP   (data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a).\n\nDefinition Gprog : funspecs :=\n      ltac:(with_library prog [minimum_spec]).\n\n(* First approach from \"Modular Verification for Computer Security\",\n  proved using forward_for_simple_bound *)\n\nLemma body_min: semax_body Vprog Gprog f_minimum minimum_spec.\nProof.\nstart_function.\nassert_PROP (Zlength al = n). {\n  entailer!. autorewrite with sublist; auto.\n}\nforward.  (* min = a[0]; *)\nforward_for_simple_bound n\n  (EX i:Z,\n    PROP()\n    LOCAL(temp _min (Vint (Int.repr (fold_right Z.min (Znth 0 al) (sublist 0 i al))));\n          temp _a a;\n          temp _n (Vlong (Int64.repr n)))\n    SEP(data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a)).\n* (* Prove that the precondition implies the loop invariant *)\n  entailer!.\n* (* Prove that the loop body preserves the loop invariant *)\n forward. (* j = a[i]; *)\n forward. (* a[i] = j; *)\n assert (repable_signed (Znth i al))\n     by (apply Forall_Znth; auto; lia).\n assert (repable_signed (fold_right Z.min (Znth 0 al) (sublist 0 i al)))\n   by (apply Forall_fold_min;\n          [apply Forall_Znth; auto; lia\n          |apply Forall_sublist; auto]).\n autorewrite with sublist.\n subst POSTCONDITION; unfold abbreviate.\n rewrite (sublist_split 0 i (i+1)) by lia.\n rewrite (sublist_one i (i+1) al) by lia.\n rewrite fold_min_another.\n replace  (upd_Znth i (map Vint (map Int.repr al)) (Vint (Int.repr (Znth i al))))\n  with (map Vint (map Int.repr al))\n  by list_solve.\n forward_if.\n +\n forward. (* min = j; *)\n entailer!.\n rewrite Z.min_r; auto; lia.\n +\n forward. (* skip; *)\n entailer!.\n rewrite Z.min_l; auto; lia.\n* (* After the loop *)\n forward. (* return *)\n entailer!.\n autorewrite with sublist.\n destruct al; simpl; auto.\nQed.\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/progs/verif_min64.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.6942436177153409}}
{"text": "(** * Chapter I *)\n\n\nModule I1.\n  Theorem I1 : forall A B C : Prop,\n    (A -> B) -> (B -> C) -> (A -> C).\n  Proof.\n    intros A B C.\n    intros a_imp_b b_imp_c.\n    intros a.\n    refine (b_imp_c _).\n      refine (a_imp_b _).\n        exact a.\n  Qed.\nEnd I1.\n\n\nModule I2.\n  Theorem I2 : forall A B C : Prop,\n    ((A \\/ B) -> C) -> ((A -> C) /\\ (B -> C)).\n  Proof.\n    intros A B C.\n    intros a_or_b_imp_c.\n    refine (conj _ _).\n      intros a.\n      refine (a_or_b_imp_c _).\n        exact (or_introl a).\n\n      intros b.\n      refine (a_or_b_imp_c _).\n        exact (or_intror b).\n  Qed.\nEnd I2.\n\n\nModule I3.\n  Theorem I3 : forall A B C : Prop,\n    (A -> (B -> C)) -> ((A /\\ B) -> C).\n  Proof.\n    intros A B C.\n    intros a_imp_b_imp_c.\n    intros a_and_b.\n    destruct a_and_b as [a b].\n    refine (a_imp_b_imp_c _ _).\n      exact a.\n\n      exact b.\n  Qed.\nEnd I3.\n\n\nModule I4.\n  Theorem I4a : forall A B : Prop,\n    (A -> B) -> (~ B -> ~ A).\n  Proof.\n    intros A B.\n    intros a_imp_b not_b.\n    intros a.\n    refine (not_b _).\n      refine (a_imp_b _).\n        exact a.\n  Qed.\n\n  Theorem I4b : forall A : Prop,\n      A -> ~ ~ A.\n  Proof.\n    intros A.\n    intros a.\n    intros not_a.\n    exact (not_a a).\n  Qed.\nEnd I4.\n\n\nModule I5.\n  Theorem I5 : forall A B : Prop,\n    (A \\/ B) -> ((A -> False) /\\ (B -> False) -> False).\n  Proof.\n    intros A B.\n    intros a_or_b.\n    intros not_a_and_not_b.\n    destruct not_a_and_not_b as [not_a not_b].\n    destruct a_or_b as [a | b].\n      exact (not_a a).\n\n      exact (not_b b).\n  Qed.\nEnd I5.\n\n\nModule I6.\n  Theorem I6a : forall A B : Prop,\n    (A -> B) /\\ (A -> ~ B) -> ~ A.\n  Proof.\n    intros A B.\n    intros a_imp_b_and_a_imp_not_b.\n    destruct a_imp_b_and_a_imp_not_b as [a_imp_b a_imp_not_b].\n    intros a.\n    refine (a_imp_not_b a _).\n      exact (a_imp_b a).\n  Qed.\n\n  Theorem I6b : forall A B : Prop,\n      A /\\ ~ A -> B.\n  Proof.\n    intros A B.\n    intros a_and_not_a.\n    destruct a_and_not_a as [a not_a].\n    pose (proof_of_False := not_a a).\n    case proof_of_False.\n  Qed.\nEnd I6.\n\n\nModule I7.\n  Definition EM (A : Prop) : Prop := A \\/ ~ A.\n\n  Definition DN (A : Prop) : Prop := ~ ~ A -> A.\n\n  Definition CC (A B : Prop) : Prop := (~ A -> B) -> (~ A -> ~ B) -> A.\n\n  Theorem I7a : forall A : Prop,\n      EM A -> DN A.\n  Proof.\n    unfold EM, DN.\n    intros A.\n    intros a_or_not_a.\n    intros not_not_a.\n    destruct a_or_not_a as [a | not_a].\n      exact a.\n\n      pose (proof_of_False := not_not_a not_a).\n      case proof_of_False.\n  Qed.\n\n  Theorem I7b : forall A B : Prop,\n      DN A -> CC A B.\n  Proof.\n    unfold DN, CC.\n    intros A B.\n    intros not_not_a_imp_a not_a_imp_b not_a_imp_not_b.\n    refine (not_not_a_imp_a _).\n      intros not_a.\n      pose (b := not_a_imp_b not_a).\n      pose (not_b := not_a_imp_not_b not_a).\n      pose (proof_of_False := not_b b).\n      case proof_of_False.\n  Qed.\n\n  Theorem I7c : forall (A : Prop),\n      CC (A \\/ ~ A) (~ A) -> EM A.\n  Proof.\n    unfold CC, EM.\n    intros A.\n    intros cc.\n    refine (cc _ _).\n      refine (I4.I4a A (A \\/ ~ A) _).\n        intros a. exact (or_introl a).\n\n      refine (I4.I4a (~ A) (A \\/ ~ A) _).\n        intros not_a. exact (or_intror not_a).\n  Qed.\nEnd I7.\n\n\nModule I8.\n  Export I7.\n\n  Definition Pierce (A B : Prop) : Prop := ((A -> B) -> A) -> A.\n\n  Theorem I8 : forall (A B : Prop),\n      EM A -> Pierce A B.\n  Proof.\n    unfold EM, Pierce.\n    intros A B.\n    intros em.\n    intros a_imp_b_imp_a.\n    destruct em as [a | not_a].\n      exact a.\n\n      refine (a_imp_b_imp_a _).\n        intros a.\n        pose (proof_of_False := not_a a).\n        case proof_of_False.\n  Qed.\nEnd I8.\n\n\nModule I9.\n  Definition I9 : Prop :=\n    forall (x y : nat), exists (z : nat), x <> y -> x < z /\\ z < y.\nEnd I9.\n\n\nModule I10.\n  Definition I10a (f : nat -> nat) : Prop :=\n    forall (x y : nat), f x = f y -> x = y.\n\n  Definition I10b (f : nat -> nat) : Prop :=\n    forall (y : nat), exists (x : nat), f x = y.\n\n  Definition I10c (f : nat -> nat) : Prop :=\n    forall (x y : nat), x < y -> f x < f y.\nEnd I10.\n\n\nModule I11.\n  Definition I11 (y : nat) : Prop :=\n    forall (x : nat), x < y /\\ forall (z : nat), y > z -> exists (x : nat), x > z.\n\n  (** I11\n\n    [y] is free.  the first [x] is bound by [forall x].  the second\n    [x] is bound by [forall z]. both [z]s are bound by [forall z].j\n   *)\nEnd I11.\n\n\nModule I12.\n  Definition I12 : Prop :=\n    forall (z : nat), exists (y : nat), z < y /\\ y < z.\n\n  (** I12\n\n    Suppose [s = y + 1].  Then if [i12 : I12], [i12 s] would result in\n    the capture of the [y] in [s] by [exists y].  We therefore replace [y]\n    with [w] in [exists y] so that if [i12 : I12], then [i12 s] is [exists\n    w, y + 1 < w /\\ w < y + 1].\n   *)\n\n  Hypothesis i12 : I12.\n\n  Variable y : nat.\n\n  Check i12 (y + 1).  (* note how [y] is renamed to [y0] *)\nEnd I12.\n\n\nModule I13.\n  Definition I13 (A : nat -> nat -> Prop) : Prop :=\n    (forall (x : nat), exists (y : nat), A x y) -> (exists (y : nat), forall (x : nat), A x y).\n\n  (** I13\n\n    We must show\n\n    (1) [exists y, forall x, A x y]\n\n    on the assumption that\n\n    (2)  [forall x, exists y, A x y].\n\n    What can we do with (2)?  First, we can see that\n\n    (3)  [exists y, A u y]\n\n    where [u] is free.  Then, if we can derive some [P] from the _assumption_\n    [A u y], where [y] does not occur free anywhere but [A u y], we can conclude [P]\n    from (3) and dismiss the assumption [A u y].\n\n    But now we are stuck--to show (1), we need first to show [forall u, A u y].  But\n    we can not do this from the _assumption_ [A u y], since [u] must be arbitrary, i.e.,\n    it must not appear in any assumptions from which we conclude [A u y] (which is itself\n    the assumption in this case.)\n   *)\n\n  Hypothesis A : nat -> nat -> Prop.\n\n  Theorem i13 : I13 A.\n  Proof.\n    unfold I13.\n    intros H.\n    refine (ex_intro (fun y => forall (x : nat), A x y) _ _).\n      intros x.\n      pose (H' := H x).\n      refine (ex_ind _ H').\n        intros x0.\n        intros H''.\n  Abort.\nEnd I13.\n\n\nModule I14.\n  Hypothesis A : nat -> Prop.\n  Hypothesis B : Prop.\n\n  Definition P : Prop :=\n    forall (x : nat), A x -> B.\n\n  Definition Q : Prop :=\n    (exists (x : nat), A x) -> B.\n\n  Theorem I14a : P -> Q.\n  Proof.\n    unfold P, Q.\n    intros f e.\n    exact (ex_ind f e).\n  Qed.\n\n  Theorem I14b : Q -> P.\n\n  Proof.\n    unfold P, Q.\n    intros p x Ax.\n    refine (p _).\n      exact (ex_intro _ x Ax).\n  Qed.\nEnd I14.\n\n\nModule I15.\n  Hypothesis A : nat -> Prop.\n\n  Definition P : Prop :=\n    ~ (exists x, A x).\n\n  Definition Q : Prop :=\n    forall x, ~ A x.\n\n  Theorem I15a : P -> Q.\n  Proof.\n    unfold P, Q.\n    intros p x Ax.\n    refine (p _).\n      exact (ex_intro _ x Ax).\n  Qed.\n\n  Theorem I15b : Q -> P.\n  Proof.\n    unfold P, Q.\n    intros q e.\n    exact (ex_ind q e).\n  Qed.\n\n  Theorem I15c : (exists (x : nat), ~ A x) -> ~ (forall (x : nat), A x).\n  Proof.\n    intros e f.\n    assert (g : forall x : nat, (A x -> False) -> False).\n      intros x not_Ax.\n      exact (not_Ax (f x)).\n      exact (ex_ind g e).\n  Qed.\n\n  (** I15\n    I would not expect it. . .if we have a proof that [A x] does not hold for all [x],\n    it does not mean we have a proof that [A x] does not hold for some particular [x].\n   *)\n\n  Theorem I15d : (~ forall x : nat, A x) -> (exists x : nat, ~ A x).\n  Proof.\n    intros f.\n  Abort.\nEnd I15.\n", "meta": {"author": "cjmazey", "repo": "ttfp", "sha": "7a407a110ac0409aa627773270fadc23345037a2", "save_path": "github-repos/coq/cjmazey-ttfp", "path": "github-repos/coq/cjmazey-ttfp/ttfp-7a407a110ac0409aa627773270fadc23345037a2/I.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6942286066577275}}
{"text": "(** * Decide: Programming with Decision Procedures *)\n\nSet Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom VFA Require Import Perm.\n\n(* ################################################################# *)\n(** * Using [reflect] to characterize decision procedures *)\n\n(** Thus far in _Verified Functional Algorithms_ we have been using\n   - propositions ([Prop]) such as [a<b] (which is Notation for [lt a b])\n   - booleans ([bool]) such as [a<?b] (which is Notation for [ltb a b]). *)\n\nCheck Nat.lt.  (* : nat -> nat -> Prop *)\nCheck Nat.ltb.  (* : nat -> nat -> bool *)\n\n(** The [Perm] chapter defined a tactic called [bdestruct] that\n    does case analysis on (x <? y) while giving you hypotheses (above\n    the line) of the form (x<y).   This tactic is built using the [reflect] \n    type and the [ltb_reflect] theorem. *)\n\nPrint reflect.\n(* Inductive reflect (P : Prop) : bool -> Set :=\n    | ReflectT : P -> reflect P true \n    | ReflectF : ~ P -> reflect P false  *)\n\nCheck ltb_reflect.  (* : forall x y, reflect (x<y) (x <? y) *)\n\n(** The name [reflect] for this type is a reference to _computational\n   reflection_,  a technique in logic.  One takes a logical formula, or \n   proposition, or predicate,  and designs a syntactic embedding of \n   this formula as an \"object value\" in the logic.  That is, _reflect_ the\n   formula back into the logic. Then one can design computations \n   expressible inside the logic that manipulate these syntactic object \n   values.  Finally, one proves that the computations make transformations\n   that are equivalent to derivations (or equivalences) in the logic.\n\n   The first use of computational reflection was by Goedel, in 1931:\n   his syntactic embedding encoded formulas as natural numbers, a \n   \"Goedel numbering.\"  The second and third uses of reflection were\n   by Church and Turing, in 1936: they encoded (respectively) \n   lambda-expressions and Turing machines.\n\n   In Coq it is easy to do reflection, because the Calculus of Inductive\n   Constructions (CiC) has Inductive data types that can easily encode \n   syntax trees.  We could, for example, take some of our propositional \n   operators such as [and], [or], and make an [Inductive] type that is an \n   encoding of these, and build a computational reasoning system for\n   boolean satisfiability.\n\n   But in this chapter I will show something much simpler.  When \n   reasoning about less-than comparisons on natural numbers, we have\n   the advantage that [nat] already an inductive type; it is \"pre-reflected,\"\n   in some sense.  (The same for [Z], [list], [bool], etc.)  *)\n\n(** Now, let's examine how [reflect] expresses the coherence between\n  [lt] and [ltb]. Suppose we have a value [v] whose type is \n  [reflect (3<7) (3<?7)].  What is [v]?  Either it is\n  - ReflectT [P] (3<?7), where [P] is a proof of [3<7],  and [3<?7] is [true], or\n  - ReflectF [Q] (3<?7), where [Q] is a proof of [~(3<7)], and [3<?7] is [false].\n  In the case of [3,7], we are well advised to use [ReflectT], because\n   (3<?7) cannot match the [false] required by [ReflectF]. *)\n\nGoal (3<?7 = true). Proof. reflexivity. Qed.\n\n(** So [v] cannot be [ReflectF Q (3<?7)] for any [Q], because that would\n   not type-check.  Now, the next question:  must there exist a value\n   of type [reflect (3<7) (3<?7)]  ?  The answer is yes; that is the\n   [ltb_reflect] theorem.  The result of [Check ltb_reflect], above, says that\n   for any [x,y], there does exist a value (ltb_reflect x y) whose type\n   is exactly [reflect (x<y)(x<?y)].     So let's look at that value!  That is,\n   examine what [H], and [P], and [Q] are equal to at \"Case 1\" and \"Case 2\": *)\n\nTheorem three_less_seven_1: 3<7.\nProof.\nassert (H := ltb_reflect 3 7).\nremember (3<?7) as b.\ndestruct H as [P|Q] eqn:?.\n* (* Case 1: H = ReflectT (3<7) P *)\napply P.\n* (* Case 2: H = ReflectF (3<7) Q *)\ncompute in Heqb.\ninversion Heqb.\nQed.\n\n(** Here is another proof that uses [inversion] instead of [destruct].\n   The [ReflectF] case is eliminated automatically by [inversion]\n   because [3<?7] does not match [false]. *)\n\nTheorem three_less_seven_2: 3<7.\nProof.\nassert (H := ltb_reflect 3 7).\ninversion H as [P|Q].\napply P.\nQed.\n\n(** The [reflect] inductive data type is a way of relating a _decision\n   procedure_ (a function from X to [bool]) with a predicate (a function\n   from X to [Prop]).   The convenience of [reflect], in the verification\n   of functional programs, is that we can do [destruct (ltb_reflect a b)],\n   which relates [a<?b] (in the program) to the [a<b] (in the proof).\n   That's just how the [bdestruct] tactic works; you can go back\n   to [Perm.v] and examine how it is implemented in the [Ltac]\n   tactic-definition language. *)\n\n(* ################################################################# *)\n(** * Using [sumbool] to Characterize Decision Procedures *)\n\nModule ScratchPad.\n\n(** An alternate way to characterize decision procedures,\n   widely used in Coq, is via the inductive type [sumbool].\n\n   Suppose [Q]  is a proposition, that is, [Q: Prop].  We say [Q] is\n   _decidable_ if there is an algorithm for computing a proof of\n   [Q] or [~Q].  More generally, when [P] is a predicate (a function \n   from some type [T] to [Prop]), we say [P] is decidable when \n   [forall x:T, decidable(P)].\n\n   We represent this concept in Coq by an inductive datatype: *)\n\nInductive sumbool (A B : Prop) : Set :=\n | left : A -> sumbool A B\n | right : B -> sumbool A B.\n\n(** Let's consider [sumbool] applied to two propositions: *)\n\nDefinition t1 := sumbool (3<7) (3>2).\nLemma less37: 3<7. Proof. lia. Qed.\nLemma greater23: 3>2. Proof. lia. Qed.\n\nDefinition v1a: t1 := left (3<7) (3>2) less37.\nDefinition v1b: t1 := right (3<7) (3>2) greater23.\n\n(** A value of type [sumbool (3<7) (3>2)] is either one of:\n  - [left] applied to a proof of (3<7), or\n  - [right] applied to a proof of (3>2).   *)\n\n(** Now let's consider: *)\n\nDefinition t2 := sumbool (3<7) (2>3).\nDefinition v2a: t2 := left (3<7) (2>3) less37.\n\n(** A value of type [sumbool (3<7) (2>3)] is either one of:\n  - [left] applied to a proof of (3<7), or\n  - [right] applied to a proof of (2>3).\n  But since there are no proofs of 2>3, only [left] values (such as [v2a])\n  exist.  That's OK. *)\n\n(** [sumbool] is in the Coq standard library, where there is [Notation] \n   for it:  the expression [ {A}+{B} ] means [sumbool A B]. *)\n\nNotation \"{ A } + { B }\" := (sumbool A B) : type_scope.\n\n(** A very common use of [sumbool] is on a proposition and its negation.\n   For example, *)\n\nDefinition t4 := forall a b, {a<b}+{~(a<b)}.\n\n(** That expression, [forall a b, {a<b}+{~(a<b)}], says that for any \n natural numbers [a] and [b], either [a<b] or [a>=b].  But it is _more_\n than that!  Because [sumbool] is an Inductive type with two constructors\n [left] and [right], then given the [{3<7}+{~(3<7)}] you can pattern-match\n on it and learn _constructively_ which thing is true.  *)\n\nDefinition v3: {3<7}+{~(3<7)} := left _ _ less37.\n\nDefinition is_3_less_7:  bool :=\n match v3 with\n | left _ _ _ => true\n | right _ _ _ => false\n end.\n\nEval compute in is_3_less_7. (* = true : bool *)\n\nPrint t4.  (* = forall a b : nat, {a < b} + {~ a < b} *)\n\n(** Suppose there existed a value [lt_dec] of type [t4].  That would be a \n  _decision procedure_ for the less-than function on natural numbers.\n  For any nats [a] and [b], you could calculate [lt_dec a b], which would\n  be either [left ...] (if [a<b] was provable) or [right ...] (if [~(a<b)] was\n  provable).\n\n  Let's go ahead and implement [lt_dec].  We can base it on the function\n  [ltb: nat -> nat -> bool] which calculates whether [a] is less than [b],\n  as a boolean.  We already have a theorem that this function on booleans\n  is related to the proposition [a<b]; that theorem is called [ltb_reflect]. *)\n\nCheck ltb_reflect.  (* : forall x y, reflect (x<y) (x<?y) *)\n\n(** It's not too hard to use [ltb_reflect] to define [lt_dec] *)\n\nDefinition lt_dec (a: nat) (b: nat) : {a<b}+{~(a<b)} :=\nmatch ltb_reflect a b with\n| ReflectT _ P => left (a < b) (~ a < b) P\n| ReflectF _ Q => right (a < b) (~ a < b) Q\nend.\n\n(** Another, equivalent way to define [lt_dec] is to use \n     definition-by-tactic: *)\n\nDefinition lt_dec' (a: nat) (b: nat) : {a<b}+{~(a<b)}.\n  destruct (ltb_reflect a b) as [P|Q]. left. apply P.  right. apply Q.\nDefined.\n\nPrint lt_dec.\nPrint lt_dec'.\n\nTheorem lt_dec_equivalent: forall a b, lt_dec a b = lt_dec' a b.\nProof.\nintros.\nunfold lt_dec, lt_dec'.\nreflexivity.\nQed.\n\n(** Warning: these definitions of [lt_dec] are not as nice as the\n  definition in the Coq standard library, because these are not\n  fully computable.  See the discussion below. *)\n\nEnd ScratchPad.\n\n(* ================================================================= *)\n(** ** [sumbool] in the Coq Standard Library *)\n\nModule ScratchPad2.\nLocate sumbool. (* Coq.Init.Specif.sumbool *)\nPrint sumbool.\n\n(** The output of [Print sumbool] explains that the first two arguments \n   of [left] and [right] are implicit.  We use them as follows (notice that\n   [left] has only one explicit argument [P]:  *)\n\nDefinition lt_dec (a: nat) (b: nat) : {a<b}+{~(a<b)} :=\nmatch ltb_reflect a b with\n| ReflectT _ P => left P\n| ReflectF _ Q => right Q\nend.\n\nDefinition le_dec (a: nat) (b: nat) : {a<=b}+{~(a<=b)} :=\nmatch leb_reflect a b with\n| ReflectT _ P => left P\n| ReflectF _ Q => right Q\nend.\n\n(** Now, let's use [le_dec] directly in the implementation of insertion\n   sort, without mentioning [ltb] at all. *)\n\nFixpoint insert (x:nat) (l: list nat) := \n  match l with\n  | nil => x::nil\n  | h::t => if le_dec x h then x::h::t else h :: insert x t\n end.\n\nFixpoint sort (l: list nat) : list nat :=\n  match l with\n  | nil => nil\n  | h::t => insert h (sort t)\nend.\n\nInductive sorted: list nat -> Prop := \n| sorted_nil:\n    sorted nil\n| sorted_1: forall x,\n    sorted (x::nil)\n| sorted_cons: forall x y l,\n   x <= y -> sorted (y::l) -> sorted (x::y::l).\n\n(** **** Exercise: 2 stars, standard (insert_sorted_le_dec) *)\nLemma insert_sorted:\n  forall a l, sorted l -> sorted (insert a l).\nProof.\n  intros a l H.\n  induction H.\n  - constructor.\n  - unfold insert.\n    destruct (le_dec a x) as [ Hle | Hgt].\n\n   (** Look at the proof state now.  In the first subgoal, we have\n      above the line, [Hle: a <= x].  In the second subgoal, we have\n      [Hgt: ~ (a < x)].  These are put there automatically by the \n      [destruct (le_dec a x)].  Now, the rest of the proof can proceed\n      as it did in [Sort.v], but using [destruct (le_dec _ _)] instead of\n      [bdestruct (_ <=? _)]. *)\n\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Decidability and Computability *)\n\n(** Before studying the rest of this chapter, it is helpful to study the\n   [ProofObjects] chapter of _Software Foundations volume 1_ if you\n   have not done so already.\n\n   A predicate [P: T->Prop] is _decidable_ if there is a computable\n   function [f: T->bool] such that, forall [x:T], [f x = true <-> P x].\n   The second and most famous example of an _undecidable_ predicate\n   is the Halting Problem (Turing, 1936): [T] is the type of Turing-machine\n   descriptions, and [P(x)] is, Turing machine [x] halts.  The first, and not\n   as famous, example is due to Church, 1936 (six months earlier): test\n   whether a lambda-expression has a normal form.  In 1936-37, as a \n   first-year PhD student before beginning his PhD thesis work, Turing\n   proved these two problems are equivalent.\n\n   Classical logic contains the axiom [forall P, P \\/ ~P].  This is not provable\n   in core Coq, that is, in the bare Calculus of Inductive Constructions.  But\n   its negation is not provable either.   You could add this axiom to Coq\n   and the system would still be consistent (i.e., no way to prove [False]).\n\n   But [P \\/ ~P] is a weaker statement than [ {P}+{~P} ], that is,\n   [sumbool P (~P)].  From [ {P}+{~P} ] you can actually _calculate_ or\n   [compute] either [left (x:P)] or [right(y: ~P)].     From [P \\/ ~P] you cannot \n   [compute] whether [P] is true.  Yes, you can [destruct] it in a proof, \n   but not in a calculation.  \n\n   For most purposes its unnecessary to add the axiom [P \\/ ~P] to Coq,\n   because for specific predicates there's a specific way to prove [P \\/ ~P]\n   as a theorem.  For example,  less-than on natural numbers is decidable,\n   and the existence of [ltb_reflect] or [lt_dec] (as a theorem, not as an axiom)\n   is a demonstration of that.\n\n   Furthermore, in this \"book\" we are interested in _algorithms_.  An axiom\n   [P \\/ ~P] does not give us an algorithm to compute whether P is true.  As\n   you saw in the definition of [insert] above, we can use [lt_dec] not only as\n   a theorem that either [3<7] or [~(3<7)], we can use it as a function to\n   compute whether [3<7].  In Coq, you can't compute with axioms!\n   Let's try it: *)\n\nAxiom lt_dec_axiom_1:  forall i j: nat, i<j \\/ ~(i<j).\n\n(** Now, can we use this axiom to compute with?  *)\n\n(* Uncomment and try this: \nDefinition max (i j: nat) : nat :=\n   if lt_dec_axiom_1 i j then j else i.\n*)\n\n(** That doesn't work, because an [if] statement requires an [Inductive]\n  data type with exactly two constructors; but [lt_dec_axiom_1 i j] has\n  type [i<j \\/ ~(i<j)],  which is not Inductive.  But let's try a different axiom: *)\n\nAxiom lt_dec_axiom_2:  forall i j: nat, {i<j} + {~(i<j)}.\n\nDefinition max_with_axiom (i j: nat) : nat :=\n   if lt_dec_axiom_2 i j then j else i.\n\n(** This typechecks, because [lt_dec_axiom_2 i j]  belongs to type\n     [sumbool (i<j) (~(i<j))]   (also written [ {i<j} + {~(i<j)} ]), which does have\n     two constructors.\n\n     Now, let's use this function: *)\n\nEval compute in max_with_axiom 3 7.\n  (*  = if lt_dec_axiom_2 3 7 then 7 else 3\n     : nat *)\n\n(** This [compute] didn't compute very much!  Let's try to evaluate it\n    using [unfold]: *)\n\nLemma prove_with_max_axiom:   max_with_axiom 3 7 = 7.\nProof.\nunfold max_with_axiom.\ntry reflexivity.  (* does not do anything, reflexivity fails *)\n(* uncomment this line and try it: \n   unfold lt_dec_axiom_2.\n*)\ndestruct (lt_dec_axiom_2 3 7).\nreflexivity.\ncontradiction n. lia.\nQed.\n\n(** It is dangerous to add Axioms to Coq: if you add one that's inconsistent,\n   then it leads to the ability to prove [False].  While that's a convenient way\n   to get a lot of things proved, it's unsound; the proofs are useless.  \n\n   The Axioms above, [lt_dec_axiom_1] and [lt_dec_axiom_2], are safe enough:\n   they are consistent.  But they don't help in computation.  Axioms are not\n   useful here. *)\n\nEnd ScratchPad2.\n\n(* ################################################################# *)\n(** * Opacity of [Qed] *)\n\n(** This lemma [prove_with_max_axiom] turned out to be _provable_, but the proof\n    could not go by _computation_.  In contrast, let's use [lt_dec], which was built\n    without any axioms: *)\n\nLemma compute_with_lt_dec:  (if ScratchPad2.lt_dec 3 7 then 7 else 3) = 7.\nProof.\ncompute.\n(* uncomment this line and try it:\n   unfold ltb_reflect.\n*)\nAbort.\n\n(** Unfortunately, even though [ltb_reflect] was proved without any axioms, it\n    is an _opaque theorem_  (proved with [Qed] instead of with [Defined]), and\n    one cannot compute with opaque theorems.  Not only that, but it is proved with\n    other opaque theorems such as [iff_sym] and [Nat.ltb_lt].  If we want to\n    compute with an implementation of [lt_dec] built from [ltb_reflect], then\n    we will have to rebuild [ltb_reflect] without using [Qed] anywhere, only [Defined].\n\n    Instead, let's use the version of [lt_dec] from the Coq standard library,\n    which _is_ carefully built without any opaque ([Qed]) theorems.\n*)\n\nLemma compute_with_StdLib_lt_dec:  (if lt_dec 3 7 then 7 else 3) = 7.\nProof.\ncompute.\nreflexivity.\nQed.\n\n(** The Coq standard library has many decidability theorems.  You can\n   examine them by doing the following [Search] command. The results\n   shown here are only for the subset of the library that's currently\n   imported (by the [Import] commands above); there's even more out there. *)\n\nSearch ({_}+{~_}).\n(*\nreflect_dec: forall (P : Prop) (b : bool), reflect P b -> {P} + {~ P}\nlt_dec: forall n m : nat, {n < m} + {~ n < m}\nlist_eq_dec:\n  forall A : Type,\n  (forall x y : A, {x = y} + {x <> y}) ->\n  forall l l' : list A, {l = l'} + {l <> l'}\nle_dec: forall n m : nat, {n <= m} + {~ n <= m}\nin_dec:\n  forall A : Type,\n  (forall x y : A, {x = y} + {x <> y}) ->\n  forall (a : A) (l : list A), {In a l} + {~ In a l}\ngt_dec: forall n m : nat, {n > m} + {~ n > m}\nge_dec: forall n m : nat, {n >= m} + {~ n >= m}\neq_nat_decide: forall n m : nat, {eq_nat n m} + {~ eq_nat n m}\neq_nat_dec: forall n m : nat, {n = m} + {n <> m}\nbool_dec: forall b1 b2 : bool, {b1 = b2} + {b1 <> b2}\nZodd_dec: forall n : Z, {Zodd n} + {~ Zodd n}\nZeven_dec: forall n : Z, {Zeven n} + {~ Zeven n}\nZ_zerop: forall x : Z, {x = 0%Z} + {x <> 0%Z}\nZ_lt_dec: forall x y : Z, {(x < y)%Z} + {~ (x < y)%Z}\nZ_le_dec: forall x y : Z, {(x <= y)%Z} + {~ (x <= y)%Z}\nZ_gt_dec: forall x y : Z, {(x > y)%Z} + {~ (x > y)%Z}\nZ_ge_dec: forall x y : Z, {(x >= y)%Z} + {~ (x >= y)%Z}\n*)\n\n(** The type of [list_eq_dec] is worth looking at.  It says that if you\n     have  a decidable equality for an element type [A], then\n    [list_eq_dec] calculates for you a decidable equality for type [list A].\n    Try it out: *)\n\nDefinition list_nat_eq_dec: \n    (forall al bl : list nat, {al=bl}+{al<>bl}) :=\n  list_eq_dec eq_nat_dec.\n\nEval compute in if list_nat_eq_dec [1;3;4] [1;4;3] then true else false.\n (* = false : bool *)\n\nEval compute in if list_nat_eq_dec [1;3;4] [1;3;4] then true else false.\n (* = true : bool *)\n\n(** **** Exercise: 2 stars, standard (list_nat_in)\n\n    Use [in_dec] to build this function. *)\n\nDefinition list_nat_in: forall (i: nat) (al: list nat), {In i al}+{~ In i al}\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample in_4_pi:  (if list_nat_in 4  [3;1;4;1;5;9;2;6] then true else false) = true.\nProof.\nsimpl.\n(* reflexivity. *)\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** In general, beyond [list_eq_dec] and [in_dec], one can construct a\n     whole programmable calculus of decidability, using the\n     programs-as-proof  language of Coq.  But is it a good idea?  Read on! *)\n\n(* ################################################################# *)\n(** * Advantages and Disadvantages of [reflect] Versus [sumbool] *)\n\n(** I have shown two ways to program decision procedures in Coq,\n    one using [reflect] and the other using [{_}+{~_}], i.e., [sumbool].\n\n   - With [sumbool], you define _two_ things: the operator in [Prop]\n      such as [lt: nat -> nat -> Prop] and the decidability \"theorem\"\n      in [sumbool], such as [lt_dec: forall i j, {lt i j}+{~ lt i j}].  I say\n      \"theorem\" in quotes because it's not _just_ a theorem, it's also\n      a (nonopaque) computable function.\n\n   - With [reflect], you define _three_ things:  the operator in [Prop],\n      the operator in [bool] (such as [ltb: nat -> nat -> bool], and the\n      theorem that relates them (such as [ltb_reflect]).  \n\n   Defining three things seems like more work than defining two.\n   But it may be easier and more efficient.  Programming in [bool],\n   you may have more control over how your functions are implemented,\n   you will have fewer difficult uses of dependent types, and you\n   will run into fewer difficulties with opaque theorems.\n\n   However, among Coq programmers, [sumbool] seems to be more\n   widely used, and it seems to have better support in the Coq standard\n   library.  So you may encounter it, and it is worth understanding what\n   it does.   Either of these two methods is a reasonable way of programming\n   with proof.  *)\n\n(* 2021-08-11 15:15 *)\n", "meta": {"author": "luisholanda", "repo": "software-foundations", "sha": "a9c5d7ddb3dca0465dee4ca8519b5de971e482de", "save_path": "github-repos/coq/luisholanda-software-foundations", "path": "github-repos/coq/luisholanda-software-foundations/software-foundations-a9c5d7ddb3dca0465dee4ca8519b5de971e482de/Volume3/Decide.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.6942285922193755}}
{"text": "Require\n  MathClasses.interfaces.naturals MathClasses.theory.naturals MathClasses.implementations.peano_naturals MathClasses.theory.integers.\nRequire Import\n  Coq.ZArith.BinInt Coq.setoid_ring.Ring Coq.Arith.Arith Coq.NArith.NArith Coq.ZArith.ZArith Coq.Numbers.Integer.Binary.ZBinary\n  MathClasses.interfaces.abstract_algebra MathClasses.interfaces.integers\n  MathClasses.implementations.natpair_integers MathClasses.implementations.stdlib_binary_naturals\n  MathClasses.interfaces.additional_operations MathClasses.interfaces.orders\n  MathClasses.implementations.nonneg_integers_naturals.\n\n(* canonical names: *)\n#[global]\nInstance Z_equiv: Equiv Z := eq.\n#[global]\nInstance Z_plus: Plus Z := Zplus.\n#[global]\nInstance Z_0: Zero Z := 0%Z.\n#[global]\nInstance Z_1: One Z := 1%Z.\n#[global]\nInstance Z_mult: Mult Z := Zmult.\n#[global]\nInstance Z_negate: Negate Z := Z.opp.\n  (* some day we'd like to do this with [Existing Instance] *)\n\n#[global]\nInstance: Ring Z.\nProof.\n  repeat (split; try apply _); repeat intro.\n           now apply Zplus_assoc.\n          now apply Zplus_0_r.\n         now apply Zplus_opp_l.\n        now apply Zplus_opp_r.\n       now apply Zplus_comm.\n      now apply Zmult_assoc.\n     now apply Zmult_1_l.\n    now apply Zmult_1_r.\n   now apply Zmult_comm.\n  now apply Zmult_plus_distr_r.\nQed.\n\n(* misc: *)\n#[global]\nInstance: ∀ x y : Z, Decision (x = y) := Z.eq_dec.\n\nAdd Ring Z: (rings.stdlib_ring_theory Z).\n\n(* * Embedding N into Z *)\n#[global]\nInstance inject_N_Z: Cast N Z := Z_of_N.\n\n#[global]\nInstance: SemiRing_Morphism Z_of_N.\nProof.\n  repeat (split; try apply _).\n   exact Znat.Z_of_N_plus.\n  exact Znat.Z_of_N_mult.\nQed.\n\n#[global]\nInstance: Injective Z_of_N.\nProof.\n  repeat (split; try apply _).\n  intros x y E. now apply Znat.Z_of_N_eq_iff.\nQed.\n\n(* SRpair N and Z are isomorphic *)\nDefinition Npair_to_Z (x : SRpair N) : Z := ('pos x - 'neg x)%mc.\n\n#[global]\nInstance: Proper (=) Npair_to_Z.\nProof.\n  intros [xp xn] [yp yn] E; do 2 red in E; unfold Npair_to_Z; simpl in *.\n  apply (right_cancellation (+) ('yn + 'xn)); ring_simplify.\n  now rewrite <-?rings.preserves_plus, E, commutativity.\nQed.\n\n#[global]\nInstance: SemiRing_Morphism Npair_to_Z.\nProof.\n  repeat (split; try apply _).\n   intros [xp xn] [yp yn].\n   change ('(xp + yp) - '(xn + yn) = 'xp - 'xn + ('yp - 'yn)).\n   rewrite ?rings.preserves_plus. ring.\n  intros [xp xn] [yp yn].\n  change ('(xp * yp + xn * yn) - '(xp * yn + xn * yp) = ('xp - 'xn) * ('yp - 'yn)).\n  rewrite ?rings.preserves_plus, ?rings.preserves_mult. ring.\nQed.\n\n#[global]\nInstance: Injective Npair_to_Z.\nProof.\n  split; try apply _.\n  intros [xp xn] [yp yn] E.\n  unfold Npair_to_Z in E. do 2 red. simpl in *.\n  apply (injective (cast N Z)).\n  rewrite ?rings.preserves_plus.\n  apply (right_cancellation (+) ('xp - 'xn)). rewrite E at 1. ring.\nQed.\n\n#[global]\nInstance Z_to_Npair: Inverse Npair_to_Z := λ x,\n  match x with\n  | Z0 => C 0 0\n  | Zpos p => C (Npos p) 0\n  | Zneg p => C 0 (Npos p)\n  end.\n\n#[global]\nInstance: Surjective Npair_to_Z.\nProof. split; try apply _. intros [|?|?] ? E; now rewrite <-E. Qed. \n\n#[global]\nInstance: Bijective Npair_to_Z := {}.\n\n#[global]\nInstance: SemiRing_Morphism Z_to_Npair.\nProof. change (SemiRing_Morphism (Npair_to_Z⁻¹)). split; apply _. Qed.\n\n#[global]\nInstance: IntegersToRing Z := integers.retract_is_int_to_ring Npair_to_Z.\n#[global]\nInstance: Integers Z := integers.retract_is_int Npair_to_Z.\n\n#[global]\nInstance Z_le: Le Z := Z.le.\n#[global]\nInstance Z_lt: Lt Z := Z.lt.\n\n#[global]\nInstance: SemiRingOrder Z_le.\nProof.\n  assert (PartialOrder Z_le).\n   repeat (split; try apply _).\n   exact Zorder.Zle_antisym.\n  rapply rings.from_ring_order.\n   repeat (split; try apply _).\n   intros x y E. now apply Zorder.Zplus_le_compat_l.\n  intros x E y F. now apply Zorder.Zmult_le_0_compat.\nQed.\n\n#[global]\nInstance: TotalRelation Z_le.\nProof.\n  intros x y.\n  destruct (Zorder.Zle_or_lt x y); intuition.\n  right. now apply Zorder.Zlt_le_weak.\nQed.\n\n#[global]\nInstance: FullPseudoSemiRingOrder Z_le Z_lt.\nProof.\n  rapply semirings.dec_full_pseudo_srorder.\n  split.\n   intro. split. now apply Zorder.Zlt_le_weak. now apply Zorder.Zlt_not_eq.\n  intros [E1 E2]. destruct (Zorder.Zle_lt_or_eq _ _ E1). easy. now destruct E2.\nQed.\n\n(* * Embedding of the Peano naturals into [Z] *)\n#[global]\nInstance inject_nat_Z: Cast nat Z := Z_of_nat.\n\n#[global]\nInstance: SemiRing_Morphism Z_of_nat.\nProof.\n  repeat (split; try apply _).\n   exact Znat.inj_plus.\n  exact Znat.inj_mult.\nQed.\n\n(* absolute value *)\n#[global]\nProgram Instance Z_abs_nat: IntAbs Z nat := λ x,\n  match x with\n  | Z0 => inl (0:nat)\n  | Zpos p => inl (nat_of_P p)\n  | Zneg p => inr (nat_of_P p)\n  end.\nNext Obligation. reflexivity. Qed.\nNext Obligation. now rewrite <-(naturals.to_semiring_unique Z_of_nat), Znat.Z_of_nat_of_P. Qed.\nNext Obligation. now rewrite <-(naturals.to_semiring_unique Z_of_nat), Znat.Z_of_nat_of_P. Qed.\n\n#[global]\nProgram Instance Z_abs_N: IntAbs Z N := λ x,\n  match x with\n  | Z0 => inl (0:N)\n  | Zpos p => inl (Npos p)\n  | Zneg p => inr (Npos p)\n  end.\nNext Obligation. reflexivity. Qed.\nNext Obligation. now rewrite <-(naturals.to_semiring_unique Z_of_N). Qed.\nNext Obligation. now rewrite <-(naturals.to_semiring_unique Z_of_N). Qed.\n\n(* Efficient nat_pow *)\n#[global]\nProgram Instance Z_pow: Pow Z (Z⁺) := Z.pow.\n\n#[global]\nInstance: NatPowSpec Z (Z⁺) Z_pow.\nProof.\n  split; unfold pow, Z_pow.\n    intros x1 y1 E1 [x2 Ex2] [y2 Ey2] E2.\n    unfold equiv, sig_equiv in E2.\n    simpl in *. now rewrite E1, E2.\n   intros. now apply Z.pow_0_r.\n  intros x n.\n  rewrite rings.preserves_plus, rings.preserves_1.\n  rewrite <-(Z.pow_1_r x) at 2. apply Z.pow_add_r.\n   auto with zarith.\n  now destruct n.\nQed.\n\n#[global]\nInstance Z_Npow: Pow Z N := λ x n, Z.pow x ('n).\n\n#[global]\nInstance: NatPowSpec Z N Z_Npow.\nProof.\n  split; unfold pow, Z_Npow.\n    solve_proper.\n   intros. now apply Z.pow_0_r.\n  intros x n.\n  rewrite rings.preserves_plus, rings.preserves_1.\n  rewrite <-(Z.pow_1_r x) at 2. apply Z.pow_add_r.\n   auto with zarith.\n  now destruct n.\nQed.\n\n(* Efficient shiftl *)\n#[global]\nProgram Instance Z_shiftl: ShiftL Z (Z⁺) := Z.shiftl.\n\n#[global]\nInstance: ShiftLSpec Z (Z⁺) Z_shiftl.\nProof.\n  apply shiftl_spec_from_nat_pow.\n  intros x [n En].\n  apply Z.shiftl_mul_pow2.\n  now apply En.\nQed.\n\n#[global]\nInstance Z_Nshiftl: ShiftL Z N := λ x n, Z.shiftl x ('n).\n\n#[global]\nInstance: ShiftLSpec Z N Z_Nshiftl.\nProof.\n  apply shiftl_spec_from_nat_pow.\n  intros x n.\n  apply Z.shiftl_mul_pow2.\n  now destruct n.\nQed.\n\n#[global]\nProgram Instance Z_abs: Abs Z := Z.abs.\nNext Obligation.\n  split; intros E.\n   now apply Z.abs_eq.\n  now apply Z.abs_neq.\nQed.\n\n#[global]\nInstance Z_div: DivEuclid Z := Z.div.\n#[global]\nInstance Z_mod: ModEuclid Z := Zmod.\n\n#[global]\nInstance: EuclidSpec Z _ _.\nProof.\n  split; try apply _.\n     exact Z.div_mod.\n    intros x y Ey. destruct (Z_mod_remainder x y); intuition.\n   now intros [].\n  now intros [].\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_integers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109622750986, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6942227155912315}}
{"text": "Require Export XR_lt_INR.\n\nLocal Open Scope R_scope.\n\nLemma lt_1_INR : forall n:nat,\n  (1 < n)%nat ->\n  R1 < INR n.\nProof.\n  intros n hn.\n  replace R1 with (INR 1%nat).\n  {\n    apply lt_INR.\n    exact hn.\n  }\n  {\n    simpl.\n    reflexivity.\n  }\nQed.", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_lt_1_INR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.694221423810797}}
{"text": "Require Import Recdef Div2 Lia FunctionalExtensionality.\n\n(** Counting the number of digits in binary representation. *)\n\n(** Show directly defining this function with Fixpoint is not acceptable.\n    Error: Cannot guess decreasing argument of fix. *)\nFail Fixpoint attempt_1 (n r : nat) : nat :=\n  match n with\n  | 0 => r\n  | _ => attempt_1 (Nat.div2 n) (r + 1)\n  end.\n\n(** function with decreasing measure. *)\nFunction attempt_2 (n r : nat) {measure (fun x => x) n} : nat :=\n  match n with\n  | 0 => r\n  | _ => attempt_2 (Nat.div2 n) (r + 1)\n  end.\nProof.\n  intros. apply lt_div2. lia.\nDefined.\n\nCompute attempt_2 1024 0.\n\n(** function with well-founded relation. *)\nFunction attempt_3 (n r : nat) {wf lt n} : nat :=\n  match n with\n  | 0 => r\n  | _ => attempt_3 (Nat.div2 n) (r + 1)\n  end.\nProof.\n  + intros. apply lt_div2. lia.\n  + apply Wf_nat.lt_wf.\nDefined.\n\nGoal\n  attempt_2 8 0 = 4.\nProof.\n  (** use [xx_equation] to expand the recursive function. *)\n  rewrite attempt_2_equation; simpl.\n  rewrite attempt_2_equation; simpl.\n  rewrite attempt_2_equation; simpl.\n  rewrite attempt_2_equation; simpl.\n  rewrite attempt_2_equation; simpl.\n  reflexivity.\nQed.\n\n(* note that the two above definitions are really just alternate ways of doing\nthe same thing ([measure] is just a convenience for leveraging the\nwell-foundedness of [nat]'s [lt]) *)\nTheorem attempts_2_and_3_are_the_same :\n  attempt_2 = attempt_3.\nProof.\n  reflexivity.\nQed.\n\n(** Now we'll redo the above using the standard library's [Fix] combinator,\nwhich provides general well-founded recursion.\n\n See CPDT's chapter http://adam.chlipala.net/cpdt/html/GeneralRec.html for an\n excellent overview, including a better description of how this approach itself\n works under the hood. *)\nCheck Fix.\n(*\nFix\n     : forall (A : Type) (R : A -> A -> Prop),\n       well_founded R ->\n       forall P : A -> Type,\n       (forall x : A, (forall y : A, R y x -> P y) -> P x) ->\n       forall x : A, P x\n\nTo read this, start at the bottom: we're writing a function of type [forall (x:A), P\nx]. The recursion is over [A] and decreases the relation [R], which must be\nwell-founded (think of [A = nat] and [R = lt] as examples). The body of the\nfunction has the type\n\n[forall (x:A) (F: forall (y:A), R y x -> P y), P x]\n\n[x] is simply the argument to the body. The second argument is what I've called\n[F] here: think of this as being the function being defined itself, in order to\nsupport recursion. The catch is in its signature: instead of just taking [y:A],\nit also takes [R y x]; that is, in order to call [F] recursively, you must pass\na proof that the argument used is smaller than the outer argument [x]. Because\n[R] is well-founded, eventually this body must stop calling itself recursively.\n *)\n\nLemma div2_smaller : forall n n',\n    n = S n' ->\n    Nat.div2 n < n.\nProof.\n  destruct n; intros.\n  discriminate.\n  apply lt_div2; lia.\nQed.\n\nDefinition numdigits (n: nat) : nat.\n  refine\n    (Fix Wf_nat.lt_wf (fun _ => nat)\n         (fun n (numdigits: forall (n':nat), n' < n -> nat) =>\n            (* unfortunately we need to convoy a proof to keep track of the\n            value of [n] when proving we decrease the argument to [numdigits] *)\n            match n as n0 return (n = n0 -> nat) with\n            | 0 => fun _ => 0\n            | S n' => fun H => 1 + numdigits (Nat.div2 n) _\n            end eq_refl) n).\n  eapply div2_smaller; eauto.\nDefined.\n\n(* We need to provide a wrapper around the standard library's [Fix_eq], which\ndescribes the computational behavior of a [Fix] as being the same as a one-step\nunfolding. However, the theorem also requires one to prove the body is unable to\ndistinguish between [F] arguments that are extensionally equal; this is true of\nany Gallina code but can't be proven within Coq once and for all. *)\nTheorem numdigits_eq : forall n,\n    numdigits n = match n with\n                  | 0 => 0\n                  | _ => 1 + numdigits (Nat.div2 n)\n                  end.\nProof.\n  intros.\n  match goal with\n  | [ |- ?lhs = _ ] =>\n    match eval unfold numdigits in lhs with\n    | Fix ?wf ?P ?F _ =>\n      rewrite (Fix_eq wf P F)\n    end\n  end.\n  destruct n; reflexivity.\n\n  intros.\n  destruct x; auto.\nQed.\n\nExample numdigits_5 : numdigits 8 = 4.\nProof.\n  repeat (rewrite numdigits_eq; cbn [Nat.div2 plus]).\n  reflexivity.\nQed.\n", "meta": {"author": "tchajed", "repo": "coq-tricks", "sha": "5de3ebeee8a196b0fe829d7c4cfe00cb9a28e58f", "save_path": "github-repos/coq/tchajed-coq-tricks", "path": "github-repos/coq/tchajed-coq-tricks/coq-tricks-5de3ebeee8a196b0fe829d7c4cfe00cb9a28e58f/src/Function.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.6942179716406085}}
{"text": "\nRequire Export Iron.Language.Calc.Exp.\n\n\nInductive EVAL : tm -> va -> Prop :=\n | EvVal    :  forall v\n            ,  EVAL (MVal v)      v\n\n | EvAdd    :  forall m1 m2 n1 n2\n            ,  EVAL m1 (VNat n1) -> EVAL m2 (VNat n2)\n            -> EVAL (MAdd m1 m2)   (VNat (n1 + n2))\n\n | EvLess   :  forall m1 m2 n1 n2\n            ,  EVAL m1 (VNat n1) -> EVAL m2 (VNat n2)\n            -> EVAL (MLess m1 m2)  (VBool (blt_nat n1 n2))\n\n | EvAnd    :  forall m1 m2 b1 b2\n            ,  EVAL m1 (VBool b1) -> EVAL m2 (VBool b2)\n            -> EVAL (MAnd m1 m2)   (VBool (andb b1 b2))\n\n | IfTrue   :  forall m1 m2 m3 v2\n            ,  EVAL m1 (VBool true)\n            -> EVAL m2 v2\n            -> EVAL (MIf m1 m2 m3) v2\n\n | IfFalse  :  forall m1 m2 m3 v3\n            ,  EVAL m1 (VBool false)\n            -> EVAL m3 v3\n            -> EVAL (MIf m1 m2 m3) v3.\n\nHint Constructors EVAL : core.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Language/Calc/Eval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761565, "lm_q2_score": 0.737158174177441, "lm_q1q2_score": 0.6941480572202455}}
{"text": "(*|\n###################################################\nHow to unfold a recursive function just once in Coq\n###################################################\n\n:Link: https://stackoverflow.com/q/24304345\n|*)\n\n(*|\nQuestion\n********\n\nHere is a recursive function ``all_zero`` that checks whether all\nmembers of a list of natural numbers are zero:\n|*)\n\nRequire Import Lists.List.\nRequire Import Arith.\n\nFixpoint all_zero (l : list nat) : bool :=\n  match l with\n  | nil => true\n  | n :: l' => andb (beq_nat n 0) (all_zero l')\n  end.\n\n(*| Now, suppose I had the following goal |*)\n\nGoal forall n l', true = all_zero (n :: l').\n\n(*|\nAnd I wanted to use the ``unfold`` tactic to transform it to\n\n.. coq:: none\n|*)\n\n  intros. unfold all_zero. fold all_zero.\n\n(*||*)\n\n  Show. (* .unfold .messages *)\nAbort. (* .none *)\n\n(*|\nUnfortunately, I can't do it with a simple ``unfold all_zero`` because\nthe tactic will eagerly find and replace all instances of\n``all_zero``, including the one in the once-unfolded form, and it\nturns into a mess. Is there a way to avoid this and unfold a recursive\nfunction just once?\n\nI know I can achieve the same results by proving an ad hoc equivalence\nwith ``assert (...) as X``, but it is inefficient. I'd like to know if\nthere's an easy way to do it similar to ``unfold``.\n\n----\n\n**A:** You could also prove\n|*)\n\nGoal forall n l, all_zero (n :: l) = andb (beq_nat n 0) (all_zero l).\nAdmitted. (* .none *)\n\n(*| and rewrite with that. |*)\n\n(*|\nAnswer (Volker Stolz)\n*********************\n\nTry\n|*)\n\nGoal forall n l', true = all_zero (n :: l'). (* .none *)\n  unfold all_zero. fold all_zero.\n\n(*| At least here for me that yields: |*)\n\n  Show. (* .unfold .messages *)\nAbort. (* .none *)\n\n(*|\n----\n\n**Q:** ``unfold`` followed by ``fold`` indeed works for ``all_zero``,\nbut not for polymorphic recursive functions. Here's one example:\n|*)\n\nFixpoint none {X : Type} (t : X -> bool) (l : list X) : bool :=\n  match l with\n  | nil => true\n  | h :: l' => andb (negb (t h)) (none t l')\n  end.\n\n(*|\n``unfold none`` followed by ``fold none`` results in the following\nerror message:\n\n.. coq:: none\n|*)\n\nGoal forall (X : Type) (t : X -> bool) h l',\n    true = none t l' -> false = t h -> true = none t (h :: l').\n  intros.\n\n(*||*)\n\n  unfold none. (* .none *) Fail fold none. (* .unfold .messages *)\n\n(*|\nSo I think a generic solution for unfolding a recursive function once\nwill have to avoid using ``unfold`` in the first place, unless there\nis some way to supply parametric information to ``fold``.\n\n**A:** You can make the implicit parameter ``X`` of ``none`` explicit\nby writing ``@none``. If you write ``fold @none.``, then Coq is able\nto give the argument explictly and searches for a suitable ``X`` in\nthe current context, just as it does for the other all-quantified\nvariables ``t`` and ``l``. If there is ambiguity you can also specify\nthe corresponding variables explicitly, i.e. ``fold (@none X)``.\n|*)\n\n(*|\nAnswer (Virgile)\n****************\n\nIt seems to me that ``simpl`` will do what you want. If you have a\nmore complicated goal, with functions that you want to apply and\nfunctions that you want to keep as they are, you might need to use the\nvarious options of the ``cbv`` tactic (see\nhttp://coq.inria.fr/distrib/current/refman/Reference-Manual010.html#hevea_tactic127).\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/how-to-unfold-a-recursive-function-just-once-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.6941177752031656}}
{"text": "Require Import List.\n\nTheorem map_length:\n  forall (A B : Type) (f : A -> B) (xs : list A),\n  length (map f xs) = length xs.\nProof.\n  intros A B f xs.\n  induction xs.\n    reflexivity.\n\n    simpl.\n    rewrite IHxs.\n    reflexivity.\nQed.\n", "meta": {"author": "nabe256", "repo": "proofcafe", "sha": "7a4ce0be0723126e6d0b10ee1e3c4a446261c72d", "save_path": "github-repos/coq/nabe256-proofcafe", "path": "github-repos/coq/nabe256-proofcafe/proofcafe-7a4ce0be0723126e6d0b10ee1e3c4a446261c72d/20140426/test01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.6941177749657804}}
{"text": "From Equations Require Import Equations.\nRequire Import Arith.\nRequire Import Lia.\nRequire Import Coq.Lists.SetoidList. (* For Sorted *)\nRequire Import Coq.Sorting.Permutation. (* For Permutation *)\nRequire Import Sumbool.\nImport Sigma_Notations.\nRequire Export JMeq.\nRequire Import Coq.Program.Tactics.\nRequire Import Vectors.VectorDef.\n\nArguments Vector.nil {A}.\nArguments Vector.cons {A} a {n} v : rename.\n\nNotation vector := Vector.t.\nNotation Vnil := Vector.nil.\nNotation Vcons := Vector.cons.\nNotation dec x := (sumbool_of_bool x).\n\n\nSet Program Mode.\n\n\nEquations app {A} {n m} (v : vector A n) (w : vector A m) : vector A (n + m) :=\n  app Vnil w := w ;\n  app (Vcons a v) w := Vcons a (app v w).\n  \n\nInductive filtered (f:nat->bool) : forall {n}, (vector nat n) -> Prop :=\n| filtered_nil : filtered f Vnil\n| filtered_cons {h n} {v:vector nat n}: f h = true -> filtered f v -> filtered f (Vcons h v).\n\n\nEquations len_filtered {n} (v:vector nat n)(f:nat->bool) : nat:=\nlen_filtered Vnil f := 0;\nlen_filtered (Vcons h t) f := match dec(f h) with\n   | left p0 => 1+len_filtered t f\n   | right q0 => len_filtered t f\n           end.\n\nTransparent len_filtered.\n\n\nEquations? filter {n} (v:vector nat n)(f:nat->bool) : \n  Σ (p : nat), {w:vector nat p|p = len_filtered v f /\\ p<=n /\\ filtered f w}:=\nfilter Vnil f := (0, Vnil);\nfilter (Vcons h t) f with dec(f h) :=\n   { | left p0 => (_, Vcons h ((filter t f).2)) ;\n     | right q0 => (_, (filter t f).2)}.\n     \nintuition.\napply filtered_nil.\ndestruct filter as [a [b [d e]]]. \nsimpl. \nintuition.\nconstructor.\nintuition.\nintuition.\nsplit.\ndestruct filter as [a [b c]]. \nintuition.\ndestruct filter as [a [b c]]. \nsimpl. \nintuition.\nDefined.\n\n\nTransparent filter.\n\nDefinition filter_lte {n} (a: nat) (v:vector nat n) := filter v (fun x => x <=? a).\nDefinition filter_gt {n} (a: nat) (v:vector nat n) := filter v (fun x=> negb(x <=? a)).\n\n\nLemma len_fixed {l}: \nforall (t: vector nat l) (h:nat),\n  len_filtered t (fun x : nat => x <=? h) + len_filtered t (fun x : nat => negb (x <=? h)) = l.\n\nintros.\ninduction t.\nintuition.\ndestruct (dec (h0 <=? h)) as []eqn:?.\nsimp len_filtered.\nrewrite Heqs. simpl.\nrewrite e. simpl.\nrewrite IHt.\ntrivial.\nsimp len_filtered.\nrewrite Heqs. simpl.\nrewrite e. simpl.\nrewrite Nat.add_succ_r.\nrewrite IHt.\ntrivial.\nQed.\n\n\nEquations? quicksort {n} (l : vector nat n) : vector nat n by wf n lt :=\n    quicksort Vnil := Vnil ;\n    quicksort (Vcons h t):= app (quicksort (filter_lte h t).2) (Vcons h (quicksort (filter_gt h t).2)).\n    \ndestruct filter_lte as [a [b [c d]]]. simpl. intuition.\ndestruct filter_gt as [a [b [c d]]]. simpl. intuition.\ndestruct filter_lte with (a:=h)(v:= t)as [a [b [c d]]]. \ndestruct filter_gt with (a0:=h)(v:= t) as [e [f [g i]]].\nsimpl.\nrewrite c. rewrite g.\nrewrite Nat.add_succ_r.\napply eq_S.\napply len_fixed.\nDefined.\n\nCheck quicksort_elim.\n\n\nEquations In {A n} (x : A) (v : vector A n) : Prop :=\n  In x Vnil := False;\n  In x (Vcons a v) := (x = a) \\/ In x v.\n\n\n(* From Sozeau *)\nInductive All {A : Type} (P : A -> Prop) : forall {n}, vector A n -> Prop :=\n| All_nil : All P Vnil\n| All_cons {a n} {v : vector A n} : P a -> All P v -> All P (Vcons a v).\n\n\n(* From Sozeau *)\nLemma All_impl {A : Type} (P Q : A -> Prop) {n} (v : vector A n) : \n(forall x, P x -> Q x) -> All P v -> All Q v.\n\nProof. \ninduction 2; \nconstructor; \nauto. \nQed.\n\nDerive Signature for All.\n\n\n(* From Sozeau *)\nLemma In_All {A P n} (v : vector A n) : \n    All P v \n  <-> \n    (forall x, In x v -> P x).\n    \nProof.\nsplit. \ninduction 1. \nintros. \ndepelim H. \nauto. \nintros x; simpl. \nsimp In. \nintuition. \nsubst; auto.\ninduction v; simpl; intros; auto; constructor. \napply H; simp In; auto.\nfirstorder.\nQed.\n\n\nLemma In_app {A n m} : \nforall (x: A) (v : vector A n) (w : vector A m),\n    In x (app v w)\n  -> \n    In x v \\/ In x w.\n    \nintros a l b.\nelim l; simpl; auto.\nintros.\nelim H0; auto.\nintro H1.\nsimp In. \nintuition.\nintuition.\nsimp In.\nintuition.\nQed.\n\n\n(* From Sozeau, except for the proof *)\nLemma All_app {A P n m} (v : vector A n) (w : vector A m) :\n    All P v \n  -> \n      All P w \n    -> \n      All P (app v w).\n      \nProof.\nintros.\nrewrite In_All.\nintros.\nrewrite In_All in H.\nrewrite In_All in H0.\napply In_app in H1.\ndestruct H1.\napply H.\napply H1.\napply H0.\napply H1.\nQed.\n\n\n(* From Sozeau *)\nInductive Sorted {A : Type} (R : A -> A -> Prop) : forall {n}, vector A n -> Prop :=\n| Sorted_nil : Sorted R Vnil\n| Sorted_cons {a n} {v : vector A n} : All (R a) v -> Sorted R v -> Sorted R (Vcons a v).\nImport Sigma_Notations.\n\nDerive Signature for Sorted.\n\nDefinition sorted {n } (v : vector nat n) := Sorted (fun x y => x <= y) v.\n\n\nLemma sorted_inv {n}: \nforall (a : nat) (v:vector nat n),\n    sorted (Vcons a v) \n  -> \n    sorted v /\\ All ((fun x y => x <= y)a) v.\n    \nintros.\ninversion H.\nreplace v with v0.\nauto.\napply Eqdep.EqdepTheory.inj_pair2 with (P:= (fun n : nat => vector nat n)) (p := n).\napply H2.\nQed.\n\n\nLemma filtered_All {n} : \nforall (x : nat) (R : nat -> bool) (v:vector nat n),\n    filtered (fun x : nat => R x ) v\n  ->\n      In x v \n    ->\n      R x = true.\n      \nintros.\ninduction H.\ncontradiction.\nsimp In in H0.\nelim H0.\nintros.\nrewrite H2.\nintuition.\napply IHfiltered.\nQed.\n\n\n(* -------------------------------------------------------------------------------\n    PERMUTATION \n------------------------------------------------------------------------------- *)\n\nPrint Permutation.\n\nInductive VPermutation {A}: forall {n m}, (vector A n) -> (vector A m) -> Prop :=\n    Vperm_nil : VPermutation Vnil Vnil\n  | Vperm_skip {x n m} {v:vector A n} {w:vector A m}:\n                VPermutation v w -> VPermutation (Vcons x v) (Vcons x w)\n  | Vperm_swap {x y n} {v:vector A n} : VPermutation (Vcons y (Vcons x v)) (Vcons x (Vcons y v))\n  | Vperm_trans {n m o} {u:vector A n} {v:vector A m} {w:vector A o}: \n                 VPermutation u v -> VPermutation v w -> VPermutation u w.\n                 \n                 \n                 \nTransparent In.\n\nLemma VPermutation_in {n m}: \nforall  (w: vector nat m) (v: vector nat n) (a : nat), \n    VPermutation v w\n  ->\n      In a v\n    -> \n      In a w.\n      \nintros w v a H.\ninduction H.\ntauto.\nsimpl.\ntauto.\nsimpl.\ntauto.\ntauto.\nQed.\n\n\nLemma VPermutation_refl {A n} : \nforall (v:vector A n), \n  VPermutation v v.\n  \nProof.\ninduction v; constructor.\nintuition.\nQed.\n\n\nLemma VPermutation_trans {A n m o}: \nforall (u:vector A n) (v:vector A m) (w:vector A o),\n    VPermutation u v \n  -> \n      VPermutation v w \n    -> \n      VPermutation u w.\n      \nProof.\nintros u v w.\nexact Vperm_trans.\nQed.\n\n\nLemma VPermutation_sym {n m}: \nforall  (v: vector nat m) (w: vector nat n),\n    VPermutation v w\n  ->\n    VPermutation w v.\n    \nintros l l' Hperm; induction Hperm; auto.\nconstructor.\napply Vperm_skip.\nintuition.\napply Vperm_swap.\napply VPermutation_trans with (v0:= v).\nintuition.\nintuition.\nQed.\n\n\nLemma V_app_comm_cons {n m}: \nforall  (v: vector nat m) (w: vector nat n) (a : nat), \n  Vcons a (app v w) = app (Vcons a v) w.\n  \nintros.\nsimp app.\ntrivial.\nQed.\n\n\nLemma VPermutation_app_tail {A n m o} : \nforall (v:vector A n) (v1:vector A m) (v2:vector A o),\n    VPermutation v1 v2 \n  -> \n    VPermutation (app v1 v) (app v2 v).\n    \nProof.\nintros.\ninduction H as [|x l l'|x y l|l l' l'']. \nsimp app.\nintuition.\napply VPermutation_refl.\nsimp app.\napply Vperm_skip.\nintuition.\nsimp app.\napply Vperm_swap.\napply VPermutation_trans with (v1:= app v0 v).\nintuition.\nintuition.\nQed.\n\n\nLemma VPermutation_app_head {A n m o} : \nforall (v:vector A n) (v1:vector A m) (v2:vector A o),\n    VPermutation v1 v2 \n  -> \n    VPermutation (app v v1) (app v v2).\n    \nProof.\nintros.\ninduction v.\nsimp app.\nsimp app.\napply Vperm_skip.\nintuition.\nQed.\n\n\nLemma VPermutation_app {A n m o p}: \nforall (u:vector A n) (v:vector A m) (w:vector A o) (x: vector A p),\n    VPermutation u w \n  -> \n      VPermutation v x \n    -> \n      VPermutation (app u v) (app w x).\n      \nProof.\nintros.\ninduction H as [|a u w|a y u|u q l'']; \nrepeat rewrite <- app_comm_cons; auto.\nsimp app.\napply Vperm_skip.\nintuition.\nsimp app.\napply VPermutation_trans with (v1 :=Vcons y (Vcons a (app v0 x))).\napply Vperm_skip.\napply Vperm_skip.\napply VPermutation_app_head.\napply H0.\napply Vperm_swap.\napply VPermutation_trans with (v1 := app v0 v).\napply VPermutation_app_tail.\nintuition. \nintuition. \nQed.\n\n\nLemma perm_app {m n o p q}: \nforall (v: vector nat m) (v1: vector nat n) (v2: vector nat o)\n(v3: vector nat p) (v4: vector nat q),\n    VPermutation v3 v1\n  -> \n      VPermutation v4 v2\n    -> \n        VPermutation v (app v3 v4)\n      -> \n        VPermutation v (app v1 v2).\n        \nintros.\napply VPermutation_trans with (v0 := (app v3 v4)).\nintuition.\napply VPermutation_app.\nintuition.\nintuition.\nQed.\n\n\nLemma VPermutation_middle {A n m }: \nforall (v1: vector A n) (v2: vector A m) (a : A),\n  VPermutation (Vcons a (app v1 v2)) (app v1 (Vcons a v2)).\n  \ninduction v1.\nintros.\nsimp app.\napply VPermutation_refl.\nintros.\nsimp app.\napply VPermutation_trans with (v:= (Vcons h (Vcons a (app v1 v2)))).\napply Vperm_swap.\napply Vperm_skip.\napply IHv1.\nQed.\n\n\nLemma VPermutation_cons_app {A n m o}: \nforall (v: vector A n) (v2: vector A m) (v1: vector A o) (a : A),\n    VPermutation v (app v1 v2) \n  -> \n    VPermutation (Vcons a v) (app v1 (Vcons a v2)).\n    \nintros.\napply VPermutation_trans with (v0 := Vcons a (app v1 v2)).\napply Vperm_skip.\nintuition.\napply VPermutation_middle.\nQed.\n\n\nLemma perm_lte_gt {n} : \nforall (v: vector nat n) (a : nat), \n  VPermutation v (app (filter_lte a v).2 (filter_gt a v).2).\n  \nintros.\ninduction v.\nsimpl.\nsimp app.\napply Vperm_nil.\napply VPermutation_trans \nwith (v0:= Vcons h ((app (proj1_sig (filter_lte a v).2) (proj1_sig (filter_gt a v).2)))).\napply Vperm_skip.\napply IHv.\nunfold filter_lte.\nunfold filter_gt.\nsimpl.\ndestruct (dec (h <=? a)) as []eqn:?.\ndestruct (dec (negb (h <=? a))) as []eqn:?.\ninversion e.\ninversion e0.\nrewrite H0 in H1.\ndiscriminate.\nsimpl.\nsimp app.\napply Vperm_skip.\napply VPermutation_refl.\ndestruct (dec (negb (h <=? a))) as []eqn:?.\nsimpl.\napply VPermutation_cons_app.\napply VPermutation_refl.\ninversion e.\ninversion e0.\nrewrite Bool.negb_false_iff in H1.\nrewrite H0 in H1.\ndiscriminate.\nQed.\n\n\nTheorem quicksort_permutation {n}: \nforall (v : vector nat n), \n  VPermutation v (quicksort v).\n  \nintros.\napply quicksort_elim.\napply Vperm_nil.\nintros.\ndestruct (quicksort_obligation_3 n0 h t0).\nsimpl.\napply perm_app with (v3:= (proj1_sig (filter_lte h t0).2)) (v4:= Vcons h (proj1_sig (filter_gt h t0).2)).\napply H.\napply Vperm_skip.\napply H0.\napply VPermutation_cons_app.\napply perm_lte_gt.\nQed.\n\n(* -------------------------------------------------------------------------------\n    SORTED\n------------------------------------------------------------------------------- *)\n\nLemma in_lte {n} : \nforall (h x: nat) (t: vector nat n),\n    In x (proj1_sig (filter_lte h t).2)\n  ->\n    x <= h.\n    \nintros.\ndestruct filter_lte as [a [b [c d]]]. \nsimpl in H.\nintuition.\napply leb_complete.\napply filtered_All with (v:= b) (R:= (fun x : nat => x <=? h)).\nintuition.\napply H.\nQed.\n\n\nLemma in_gt {n} : \nforall (h x : nat) (t: vector nat n),\n    In x (proj1_sig (filter_gt h t).2)\n  ->\n    x > h.\n    \nintros.\ndestruct filter_gt as [a [b [c d]]]. \nsimpl in H.\napply leb_complete_conv. \nrewrite <- Bool.negb_true_iff.\napply filtered_All with (v:= b) (R:= (fun x : nat => negb (x <=? h))).\nintuition.\napply H.\nQed.\n\n\nLemma in_qs {n} : \nforall (t: vector nat n) (elem : nat), \n    In elem t \n  <->\n    In elem (quicksort t).\n    \nintros.\nsplit.\nintros.\napply VPermutation_in with (v:= t).\napply quicksort_permutation.\napply H.\napply VPermutation_in.\napply VPermutation_sym.\napply quicksort_permutation.\nQed.\n\n\nLemma sort_app {l l'}: \nforall (v : vector nat l) (v': vector nat l') (n : nat), \n    sorted v\n  -> \n      sorted v' \n    -> \n        All (fun y : nat => y > n) v'\n      -> \n          All (fun y : nat => y <= n) v\n        -> \n          sorted (app v (Vcons n v')).\n          \nintros.\ninduction v.\nsimp app.\napply Sorted_cons.\napply All_impl with (P:=  (fun y : nat => y > n)).\nintros.\nintuition.\napply H1.\napply H0.\nsimp app.\napply Sorted_cons.\napply All_app.\napply sorted_inv in H.\nintuition.\nconstructor.\nrewrite In_All in H2.\napply H2.\nconstructor.\ntrivial.\napply In_All.\nintros.\napply Nat.le_trans with (m:= n).\nrewrite In_All in H2.\napply H2.\nconstructor.\ntrivial.\nrewrite In_All in H1.\napply Nat.lt_le_incl.\napply H1.\napply H3.\napply IHv.\napply sorted_inv in H.\nintuition.\napply In_All.\nintros.\nrewrite In_All in H2.\napply H2.\nsimp In.\nintuition.\nQed.\n\n\nTheorem quicksort_sorted {n} : \nforall (v : vector nat n), \n  sorted (quicksort v).\n  \nintros.\napply quicksort_elim.\nconstructor.\nintros.\ndestruct (quicksort_obligation_3 n0 h t0).\nsimpl.\napply sort_app.\napply H.\napply H0.\n\napply In_All.\nintros.\nrewrite <- in_qs in H1.\napply in_gt with (t := t0).\napply H1.\n\napply In_All.\nintros.\nrewrite <- in_qs in H1.\napply in_lte with (t := t0).\napply H1.\nQed.\n\n\n(* -------------------------------------------------------------------------------\n    CORRECTNESS\n------------------------------------------------------------------------------- *)\n\nTheorem quicksort_correct {n} : \nforall (v : vector nat n), \n  sorted (quicksort v) /\\ VPermutation v (quicksort v).\n  \nintros.\nsplit.\napply quicksort_sorted.\napply quicksort_permutation.\nQed.\n\n", "meta": {"author": "KirstenHagenaars", "repo": "BachelorThesis", "sha": "3c6dec361e51d635dd2e1cabc8dfcea9540891a0", "save_path": "github-repos/coq/KirstenHagenaars-BachelorThesis", "path": "github-repos/coq/KirstenHagenaars-BachelorThesis/BachelorThesis-3c6dec361e51d635dd2e1cabc8dfcea9540891a0/Code/QuicksortVector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.6941177693965354}}
{"text": "(* Ejercicio 5.5 *)\nSection ej55.\n\n(* Ejercicio 5.5.1 *)\nDefinition Var := nat.\n\nInductive BoolExpr :=\n  | V (x: nat)  : BoolExpr\n  | B (b: bool) : BoolExpr\n  | AND (e1 e2: BoolExpr) : BoolExpr\n  | NOT (e: BoolExpr) : BoolExpr.\n\nNotation \"x /\\ y\" := (AND x y) (at level 80, right associativity).\nNotation \"~ x\" := (NOT x) (at level 75, right associativity).\nNotation \"¿ x\" := (V x) (at level 70, right associativity).\n\n(* Ejercicio 5.5.2 *)\nDefinition Valor := bool.\nDefinition Memoria : Set := Var -> Valor.\n\nDefinition lookup (m: Memoria) (v: Var) : Valor := m v.\n\nInductive BEval (m: Memoria) : BoolExpr -> Valor -> Prop :=\n  | evar (v: Var)            : BEval m (¿ v) (lookup m v)\n  | eboolt                   : BEval m (B true) true\n  | eboolf                   : BEval m (B false) false\n  | eandl (e1 e2: BoolExpr)  : BEval m e1 false -> BEval m (e1 /\\ e2) false\n  | eandr (e1 e2: BoolExpr)  : BEval m e2 false -> BEval m (e1 /\\ e2) false\n  | eandrl (e1 e2: BoolExpr) : BEval m e1 true -> BEval m e2 true -> BEval m (e1 /\\ e2) true\n  | enott (e: BoolExpr)      : BEval m e true -> BEval m (~ e) false\n  | enotf (e: BoolExpr)      : BEval m e false -> BEval m (~ e) true.\n\n(* Ejercicio 5.5.3.a *)\nTheorem true_not_false : forall m: Memoria, ~BEval m (B true) false.\nProof.\nunfold not.\nintros.\ninversion H.\nQed.\n\n(* Ejercicio 5.5.3.b *)\nTheorem e1_true_w_and : forall (m: Memoria) (e1 e2: BoolExpr) (w: Valor), BEval m e1 true -> BEval m e2 w -> BEval m (e1 /\\ e2) w.\nProof.\nintros.\ndestruct w.\napply (eandrl m e1 e2 H H0).\napply (eandr m e1 e2 H0).\nQed.\n\n(* Ejercicio 5.5.3.c *)\nTheorem e1_e2_w1_w2_eq : forall (m: Memoria) (e: BoolExpr) (w1 w2: Valor), BEval m e w1 -> BEval m e w2 -> w1 = w2.\nProof.\ninduction e; intros; auto.\n  * inversion H.\n    inversion H0.\n    reflexivity.\n  * inversion H;\n    rewrite <- H2 in H0;\n    inversion H0;\n    reflexivity.\n  * inversion H;\n    inversion H0;\n    auto.\n  * inversion H;\n    inversion H0;\n    auto.\nQed.\n\n(* Ejercicio 5.5.3.d *)\nTheorem e1_false_then_not_and : forall (m: Memoria) (e1 e2: BoolExpr), BEval m e1 false -> ~BEval m (e1 /\\ e2) true.\nProof.\nunfold not.\nintros.\ninversion H0.\npose (e1_e2_w1_w2_eq m e1 false true H H3).\ndiscriminate.\nQed.\n\n\n(* Ejercicio 5.5.4 *)\nRequire Import Coq.Bool.Bool.\nFixpoint beval (m: Memoria) (e: BoolExpr) : Valor :=\n    match e with\n        | V x => lookup m x\n        | B v => v\n        | AND e1 e2 => (beval m e1) && (beval m e2)\n        | NOT e => negb (beval m e)\n    end.\n\n(* Ejercicio 5.5.5 *)\nTheorem beval_correct : forall (m: Memoria) (e: BoolExpr), BEval m e (beval m e).\nProof.\nintros.\ninduction e; simpl.\n  * constructor.\n  * case b; constructor.\n  * case (beval m e1), (beval m e2); simpl.\n    + apply (eandrl m e1 e2 IHe1 IHe2).\n    + apply (eandr m e1 e2 IHe2).\n    + apply (eandl m e1 e2 IHe1).\n    + apply (eandl m e1 e2 IHe1).\n  * destruct (beval m e); simpl.\n    + apply (enott m e); assumption.\n    + apply (enotf m e); assumption.\nQed.\n\nEnd ej55.\n\n\n(* Ejercicio 5.6 y 5.7 *)\nSection ej56_ej57.\n\n(* notación BoolExpr *)\nNotation \"x /\\ y\" := (AND x y) (at level 80, right associativity).\nNotation \"~ x\" := (NOT x) (at level 75, right associativity).\nNotation \"* x\" := (V x) (at level 70, right associativity).\nNotation \"'TRUE'\" := (B true).\nNotation \"'FALSE'\" := (B false).\n\n(* Ejercicio 5.6.1 *)\nInductive Instr :=\n  | NOOP : Instr\n  | ASSIGN (x: nat) (y: BoolExpr) : Instr\n  | IFS (b: BoolExpr) (t f: Instr) : Instr\n  | WHILE (e: BoolExpr) (c: Instr) : Instr\n  | REPEAT (n: nat) (c: Instr) : Instr\n  | BEGIN (l: LInstr)\nwith\n  LInstr :=\n  | EMPTY : LInstr\n  | CONS (x: Instr) (y: LInstr).\n\n(* Ejercicio 5.6.2 + extras *)\nNotation \"'SKIP'\" := NOOP.\nNotation \"x <- y\" := (ASSIGN x y) (at level 90, right associativity).\nNotation \"'IF?' b 'THEN' x 'ELSE' y\" := (IFS b x y) (at level 80, right associativity).\nNotation \"'WHILE' b 'DO' x\" := (WHILE b x) (at level 80, right associativity).\nNotation \"'BEGIN' l 'END'\" := (BEGIN l) (at level 90, right associativity).\nNotation \"x ; y\" := (CONS x y) (at level 100, right associativity).\nNotation \"x ; \" := (CONS x EMPTY) (at level 100, right associativity).\n\n(* Ejercicio 5.6.2.a *)\nDefinition PP (v1 v2: Var) := BEGIN \n    v1 <- TRUE; \n    v2 <- ~ *v1;\nEND.\n\n(* Ejercicio 5.6.2.b *)\nDefinition swap (aux v1 v2: Var) := BEGIN \n    aux <- *v1;\n    v1  <- *v2;\n    v2  <- *aux;  \nEND.\n\n(* Ejercicio 5.6.3 *)\nRequire Import Coq.Arith.EqNat.\n\nDefinition update (m: Memoria) (v: Var) (val: Valor) : Memoria :=\n  fun x => if beq_nat x v then val else lookup m x.\n\n(* Ejercicio 5.6.4 *)\nTheorem update_works : forall (m: Memoria) (v: Var) (val: Valor), lookup (update m v val) v = val.\nProof.\nintros.\nunfold lookup, update.\nrewrite <- (beq_nat_refl v).\nreflexivity.\nQed.\n\n(* Ejercicio 5.6.5 *)\nTheorem update_other_works : forall (m: Memoria) (v v': Var) (val: Valor), v <> v' -> lookup (update m v val) v' = lookup m v'.\nProof.\nintros.\nunfold lookup, update.\napply (beq_nat_false_iff v v') in H.\nrewrite <- PeanoNat.Nat.eqb_sym.\nrewrite H.\nreflexivity.\nQed.\n\n\n(* Ejercicio 5.7.1 *)\nInductive Execute (m: Memoria) : Instr -> Memoria -> Prop :=\n  | xAss (v: Var) (be: BoolExpr) (w: Valor)               : BEval m be w -> Execute m (v <- be) (update m v w)\n  | xSkip                                                 : Execute m SKIP m\n  | xIFthen (be: BoolExpr) (p1 p2: Instr) (m': Memoria)   : BEval m be true -> Execute m p1 m' -> Execute m (IF? be THEN p1 ELSE p2) m'\n  | xIFelse (be: BoolExpr) (p1 p2: Instr) (m': Memoria)   : BEval m be false -> Execute m p2 m' -> Execute m (IF? be THEN p1 ELSE p2) m'\n  | xWhileTrue (be: BoolExpr) (p: Instr) (m1 m2: Memoria) : BEval m be true -> Execute m p m1 -> Execute m1 (WHILE be DO p) m2 -> Execute m (WHILE be DO p) m2\n  | xWhileFalse (be: BoolExpr) (p: Instr)                 : BEval m be false -> Execute m (WHILE be DO p) m\n  | xRepeat0 (p: Instr)                                   : Execute m (REPEAT 0 p) m\n  | xRepeatS (p: Instr) (m1 m2: Memoria) (n: nat)         : Execute m p m1 -> Execute m1 (REPEAT n p) m2 -> Execute m (REPEAT (S n) p) m2\n  | xBeginEnd (pl: LInstr) (m': Memoria)                  : ExecuteL m pl m' -> Execute m (BEGIN pl END) m'\nwith ExecuteL (m: Memoria) : LInstr -> Memoria -> Prop :=\n  | xEmptyblock                                    : ExecuteL m EMPTY m\n  | xNext (p: Instr) (pl: LInstr) (m1 m2: Memoria) : Execute m p m1 -> ExecuteL m1 pl m2 ->ExecuteL m (p; pl) m2.\n\n(* Ejercicio 5.7.2 *)\nTheorem if_reversed : forall (m m': Memoria) (e1 e2: Instr), Execute m (IF? ~ FALSE THEN e1 ELSE e2) m' -> Execute m (IF? FALSE THEN e2 ELSE e1) m'.\nProof.\nintros.\ninversion_clear H.\n  * apply xIFelse; auto; constructor.\n  * inversion_clear H0.\n    inversion_clear H.\nQed.\n\n(* Ejercicio 5.7.3 *)\nLemma bool_contradict : forall (c: bool) (m: Memoria), ~BEval m (~ B c) c.\nProof.\nunfold not.\ninduction c; intros; inversion_clear H; inversion_clear H0.\nQed.\n\nTheorem gen_if_reversed : forall (c: bool) (m m': Memoria) (e1 e2: Instr), Execute m (IF? ~ (B c) THEN e1 ELSE e2) m' -> Execute m (IF? (B c) THEN e2 ELSE e1) m'.\nProof.\nintros.\ninduction c; intros.\ninversion_clear H.\n  * apply (bool_contradict true m) in H0; contradiction.\n  * apply xIFthen; auto; constructor.\n  * apply xIFelse; auto.\n    - constructor.\n    - inversion_clear H; auto.\n      apply (bool_contradict false m) in H0; contradiction.\nQed.\n\n(* Ejercicio 5.7.4 *)\nTheorem empty_false : forall (m m': Memoria) (p: Instr), Execute m (WHILE FALSE DO p) m' -> m = m'.\nProof.\nintros.\ninversion H.\n  * inversion H2.\n  * reflexivity.\nQed.\n\n(* Ejercicio 5.7.5 *)\nTheorem expand_while_eq : forall (m m': Memoria) (c: BoolExpr) (p: Instr), ExecuteL m ((IF? c THEN p ELSE SKIP); WHILE c DO p;) m' -> Execute m (WHILE c DO p) m'.\nProof.\nintros.\ninversion_clear H.\ninversion_clear H1.\ninversion H2.\nrewrite -> H3 in H.\ninversion_clear H0.\n  * apply (xWhileTrue m c p m1 m' H1 H4 H).\n  * inversion H4.\n    assumption.\nQed.\n\n(* Ejercicio 5.7.6 *)\nTheorem repeat_seq : forall (m m': Memoria) (n: nat) (i: Instr), ExecuteL m (i; REPEAT n i;) m' -> Execute m (REPEAT (S n) i) m'.\nProof.\nintros.\ninversion_clear H.\ninversion_clear H1.\ninversion H2.\nrewrite -> H3 in H.\napply (xRepeatS m i m1 m' n H0 H).\nQed.\n\n(* Ejercicio 5.7.7 *)\nTheorem repeat_sum : forall (n1 n2: nat) (i: Instr) (m1 m2 m3: Memoria), Execute m1 (REPEAT n1 i) m2 -> Execute m2 (REPEAT n2 i) m3 -> Execute m1 (REPEAT (n1+n2) i) m3.\nProof.\ninduction n1; intros.\n  * simpl.\n    inversion H.\n    assumption.\n  * simpl.\n    inversion H.\n    pose (IHn1 n2 i m0 m2 m3 H5 H0).\n    apply (xRepeatS m1 i m0 m3 (n1 + n2) H3 e).\nQed.\n\n(* Ejercicio 5.7.8 *)\nTheorem PProof : forall (v1 v2: Var) (m1 m2: Memoria), v1 <> v2 -> Execute m1 (PP v1 v2) m2 -> lookup m2 v1 = true /\\ lookup m2 v2 = false.\nProof.\nintros.\napply beq_nat_false_iff in H.\ninversion_clear H0.\ninversion_clear H1.\ninversion_clear H2.\ninversion H3.\nrewrite <- H4.\nclear H3.\nclear H4.\n\ninversion H0.\ninversion H5.\nrewrite <- H7 in H3.\nclear H7.\nclear H5.\nclear H4.\nclear H2.\n\ninversion H1.\nclear H2.\nclear H5.\ninversion H6.\n  * rewrite <- H7 in H4.\n    clear H7.\n    clear H2.\n    clear H5.\n    clear H6.\n    split; rewrite <- H3; simpl; unfold lookup, update.\n      + rewrite -> H.\n        unfold lookup.\n        rewrite <- (beq_nat_refl v1).\n        reflexivity.\n      + unfold lookup, update.\n        rewrite <- (beq_nat_refl v2).\n        reflexivity.\n  * rewrite <- H3 in H6.\n    rewrite <- H7 in H6.\n    inversion H6.\n    inversion H9.\n    unfold lookup, update in H12.\n    rewrite <- (beq_nat_refl v1) in H12.\n    discriminate.\nQed.\n\nEnd ej56_ej57.", "meta": {"author": "elopez", "repo": "CFPTT", "sha": "5df066218d0acba5a009db498e6125d69865096a", "save_path": "github-repos/coq/elopez-CFPTT", "path": "github-repos/coq/elopez-CFPTT/CFPTT-5df066218d0acba5a009db498e6125d69865096a/práctica 5/p5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6940902668801346}}
{"text": "Require Export section_08_contractible.\n\n(** Section 9.1 Families of equivalences *)\n\n(** Definition 9.1.1 *)\n\nDefinition tot {A} {B C : A -> Type} (f : forall x, B x -> C x) :\n  Sigma A B -> Sigma A C :=\n  fun t => pair (pr1 t) (f (pr1 t) (pr2 t)).\n\n(** Lemma 9.1.2 *)\n\nDefinition fib_tot_fib_fmap {A} {B C : A -> Type} (f : forall x, B x -> C x)\n           (t : Sigma A C) :\n  fib (f (pr1 t)) (pr2 t) -> fib (tot f) t.\nProof.\n  destruct t as [x z]; cbn.\n  intro y; destruct y as [y p]; destruct p.\n  exact (pair (pair x y) refl).\nDefined.\n\nDefinition fib_fmap_fib_tot {A} {B C : A -> Type} (f : forall x, B x -> C x)\n           (t : Sigma A C) :\n  fib (tot f) t -> fib (f (pr1 t)) (pr2 t).\nProof.\n  intro s; destruct s as [s p]; destruct p; destruct s as [x y].\n  exact (pair y refl).\nDefined.\n\nDefinition is_sec_fib_fmap_fib_tot {A} {B C : A -> Type}\n           (f : forall x, B x -> C x) (t : Sigma A C) :\n  comp (fib_tot_fib_fmap f t) (fib_fmap_fib_tot f t) ~ idmap.\nProof.\n  intro s; destruct s as [s p]; destruct p; now destruct s as [x y].\nDefined.\n\nDefinition is_retr_fib_fmap_fib_tot {A} {B C : A -> Type}\n           (f : forall x, B x -> C x) (t : Sigma A C) :\n  comp (fib_fmap_fib_tot f t) (fib_tot_fib_fmap f t) ~ idmap.\nProof.\n  destruct t as [x z]; cbn.\n  intro y; destruct y as [y p]; destruct p.\n  reflexivity.\nDefined.\n\nLemma is_equiv_fib_tot_fib_fmap {A} {B C : A -> Type}\n      (f : forall x, B x -> C x) (t : Sigma A C) :\n  is_equiv (fib_tot_fib_fmap f t).\nProof.\n  apply (is_equiv_has_inverse (fib_fmap_fib_tot f t)).\n  - exact (is_sec_fib_fmap_fib_tot f t).\n  - exact (is_retr_fib_fmap_fib_tot f t).\nDefined.\n\nDefinition fib_tot_fib_fmap_equiv {A} {B C : A -> Type}\n           (f : forall x, B x -> C x) (t : Sigma A C) :\n  (fib (f (pr1 t)) (pr2 t)) <~> (fib (tot f) t) :=\n  pair (fib_tot_fib_fmap f t) (is_equiv_fib_tot_fib_fmap f t).\n\nLemma is_equiv_fib_fmap_fib_tot {A} {B C : A -> Type}\n      (f : forall x, B x -> C x) (t : Sigma A C) :\n  is_equiv (fib_fmap_fib_tot f t).\nProof.\n  apply (is_equiv_has_inverse (fib_tot_fib_fmap f t)).\n  - exact (is_retr_fib_fmap_fib_tot f t).\n  - exact (is_sec_fib_fmap_fib_tot f t).\nDefined.\n\nDefinition fib_fmap_fib_tot_equiv {A} {B C : A -> Type}\n           (f : forall x, B x -> C x) (t : Sigma A C) :\n  (fib (tot f) t) <~> (fib (f (pr1 t)) (pr2 t)) :=\n  pair (fib_fmap_fib_tot f t) (is_equiv_fib_fmap_fib_tot f t).\n\n(** Theorem 9.1.3 *)\n\nTheorem is_equiv_is_equiv_tot {A} {B C : A -> Type} (f : forall x, B x -> C x) :\n  is_equiv (tot f) -> forall x, is_equiv (f x).\nProof.\n  intros H x.\n  apply is_equiv_is_contr_map.\n  intro z.\n  apply (is_contr_equiv (fib_tot_fib_fmap_equiv f (pair x z))).\n  now apply is_contr_map_is_equiv.\nDefined.\n\nTheorem is_equiv_tot_is_equiv {A} {B C : A -> Type} {f : forall x, B x -> C x} :\n  (forall x, is_equiv (f x)) -> is_equiv (tot f).\nProof.\n  intro H.\n  apply is_equiv_is_contr_map.\n  intro t; destruct t as [x z].\n  apply (is_contr_equiv (fib_fmap_fib_tot_equiv f (pair x z))); cbn.\n  now apply is_contr_map_is_equiv.\nDefined.\n\nDefinition tot_equiv {A} {B C : A -> Type} :\n  (forall x, (B x <~> C x)) -> ((Sigma A B) <~> (Sigma A C)) :=\n  fun e =>\n    pair\n      (tot (fun x => map_equiv (e x)))\n      (is_equiv_tot_is_equiv (fun x => is_equiv_map_equiv (e x))).\n\n(** Lemma 9.1.4 *)\n\nDefinition btot {A B} (f : A -> B) (C : B -> Type) :\n  Sigma A (fun x => C (f x)) -> Sigma B C :=\n  fun t => pair (f (pr1 t)) (pr2 t).\n\nDefinition fib_map_fib_btot {A B} (f : A -> B) (C : B -> Type) (t : Sigma B C) :\n  fib (btot f C) t -> fib f (pr1 t).\nProof.\n  intro s; destruct s as [s p]; destruct p; destruct s as [x z]; cbn.\n  exact (pair x refl).\nDefined.\n\nDefinition fib_btot_fib_map {A B} (f : A -> B) (C : B -> Type) (t : Sigma B C) :\n  fib f (pr1 t) -> fib (btot f C) t.\nProof.\n  destruct t as [y z]; cbn.\n  intro s; destruct s as [x p]; destruct p.\n  now apply (pair (pair x z)).\nDefined.\n\nDefinition is_sec_fib_btot_fib_map\n           {A B} (f : A -> B) (C : B -> Type) (t : Sigma B C) :\n  comp (fib_map_fib_btot f C t) (fib_btot_fib_map f C t) ~ idmap.\nProof.\n  destruct t as [y z]; cbn.\n  intro s; destruct s as [x p]; destruct p.\n  reflexivity.\nDefined.\n\nDefinition is_retr_fib_btot_fib_map\n           {A B} (f : A -> B) (C : B -> Type) (t : Sigma B C) :\n  comp (fib_btot_fib_map f C t) (fib_map_fib_btot f C t) ~ idmap.\nProof.\n  intro s; destruct s as [s p]; destruct p; destruct s as [x z]; cbn.\n  reflexivity.\nDefined.\n\nLemma is_equiv_fib_map_fib_btot\n      {A B} (f : A -> B) (C : B -> Type) (t : Sigma B C) :\n  is_equiv (fib_map_fib_btot f C t).\nProof.\n  apply (is_equiv_has_inverse (fib_btot_fib_map f C t)).\n  - exact (is_sec_fib_btot_fib_map f C t).\n  - exact (is_retr_fib_btot_fib_map f C t).\nDefined.\n\nDefinition fib_map_fib_btot_equiv\n           {A B} (f : A -> B) (C : B -> Type) (t : Sigma B C) :\n  fib (btot f C) t <~> fib f (pr1 t) :=\n  pair (fib_map_fib_btot f C t) (is_equiv_fib_map_fib_btot f C t).\n\nLemma is_equiv_fib_btot_fib_map\n      {A B} (f : A -> B) (C : B -> Type) (t : Sigma B C) :\n  is_equiv (fib_btot_fib_map f C t).\nProof.\n  apply (is_equiv_has_inverse (fib_map_fib_btot f C t)).\n  - exact (is_retr_fib_btot_fib_map f C t).\n  - exact (is_sec_fib_btot_fib_map f C t).\nDefined.\n\nDefinition fib_btot_fib_map_equiv\n           {A B} (f : A -> B) (C : B -> Type) (t : Sigma B C) :\n  fib f (pr1 t) <~> fib (btot f C) t :=\n  pair (fib_btot_fib_map f C t) (is_equiv_fib_btot_fib_map f C t).\n\nLemma is_equiv_btot_is_equiv {A B} {f : A -> B} (C : B -> Type) :\n  is_equiv f -> is_equiv (btot f C).\nProof.\n  intro H.\n  apply is_equiv_is_contr_map.\n  intro t; destruct t as [x z].\n  apply (is_contr_equiv (fib_map_fib_btot_equiv f C (pair x z))); cbn.\n  now apply is_contr_map_is_equiv.\nDefined.\n\nDefinition btot_equiv {A B} (e : A <~> B) (C : B -> Type) :\n  Sigma A (comp C (map_equiv e)) <~> Sigma B C :=\n  pair (btot (map_equiv e) C) (is_equiv_btot_is_equiv C (is_equiv_map_equiv e)).\n\n(** Definition 9.1.5 *)\n\nDefinition toto {A B} (f : A -> B) {C : A -> Type} (D : B -> Type) :\n  (forall x, C x -> D (f x)) -> Sigma A C -> Sigma B D :=\n  fun g t => pair (f (pr1 t)) (g (pr1 t) (pr2 t)).\n\n(** Theorem 9.1.6 *)\n\nDefinition triangle_toto {A B} (f : A -> B)\n           {C : A -> Type} (D : B -> Type) (g : forall x, C x -> D (f x)) :\n  toto f D g ~ comp (btot f D) (tot g).\nProof.\n  exact refl_htpy.\nDefined.\n\n(** Tactics were again too annoying, but the proof term is easy to write down. \n *)\n\nDefinition is_equiv_toto_is_equiv {A B} {f : A -> B}\n        {C : A -> Type} (D : B -> Type) {g : forall x, C x -> D (f x)} :\n  is_equiv f -> (forall x, is_equiv (g x)) -> is_equiv (toto f D g) :=\n  fun Ef Eg =>\n    @is_equiv_comp _ _ _\n                   (toto f D g)\n                   (btot f D)\n                   (pair (tot g) (triangle_toto f D g))\n                   (is_equiv_tot_is_equiv Eg)\n                   (is_equiv_btot_is_equiv D Ef).\n\nDefinition equiv_toto {A B} (e : A <~> B) {C : A -> Type} (D : B -> Type)\n           (g : forall x, (C x <~> D (map_equiv e x))) :\n  Sigma A C <~> Sigma B D :=\n  pair (toto (map_equiv e) D (fun x => map_equiv (g x)))\n       (is_equiv_toto_is_equiv D (is_equiv_map_equiv e)\n                                 (fun x => is_equiv_map_equiv (g x))).\n\nDefinition is_equiv_is_equiv_toto {A B} {f : A -> B}\n        {C : A -> Type} (D : B -> Type) {g : forall x, C x -> D (f x)} :\n  is_equiv f -> is_equiv (toto f D g) -> (forall x, is_equiv (g x)) :=\n  fun Ef Efg =>\n    is_equiv_is_equiv_tot g\n      (@is_equiv_right_factor _ _ _\n                              (toto f D g)\n                              (btot f D)\n                              (pair (tot g) (triangle_toto f D g))\n                              Efg\n                              (is_equiv_btot_is_equiv D Ef)).\n\n(** Section 9.2 The fundamental theorem *)\n\n(** Definition 9.2.1 *)\n\n(** We define a generalized ev_refl *)\nDefinition ev_refl_gen {A} (a : A) {B : A -> Type} (b : B a)\n           (C : forall x, B x -> Type) : (forall x y, C x y) -> C a b :=\n  fun h => h a b.\n\n(* We also say that a family B over A with b : B a is an identity system if\n   it satisfies the following path induction principle. *)\n\nDefinition Ind_path {A} {a : A} (B : A -> Type) (b : B a) : Type :=\n  forall (C : forall x, B x -> Type), sec (ev_refl_gen a b C).\n\nDefinition Identity_System {A} (a : A) : Type :=\n  Sigma (A -> Type) (fun B => Sigma (B a) (fun b => Ind_path B b)).\n\n(** Theorem 9.2.3 The fundamental theorem of identity types *)\n\nTheorem fundamental_thm_id {A} {a : A} {B : A -> Type} (b : B a)\n        (f : forall x, a == x -> B x) :\n  is_contr (Sigma A B) -> forall x, is_equiv (f x).\nProof.\n  intro c.\n  apply is_equiv_is_equiv_tot.\n  apply is_equiv_is_contr.\n  - apply is_contr_total_path.\n  - assumption.\nDefined.\n\nTheorem fundamental_thm_id' {A} {a : A} (B : A -> Type) (b : B a) :\n  is_contr (Sigma A B) -> forall x, is_equiv (fun (p : a == x) => tr B p b).\nProof.\n  now apply fundamental_thm_id.\nDefined.\n\nTheorem conv_fundamental_thm_id {A} {a : A} {B : A -> Type} (b : B a)\n        (f : forall x, a == x -> B x) :\n  (forall x, is_equiv (f x)) -> is_contr (Sigma A B).\nProof.\n  intro H.\n  apply (is_contr_is_equiv' (is_equiv_tot_is_equiv H)).\n  apply is_contr_total_path.\nDefined.\n\nDefinition fam_Sigma {A} {B : A -> Type} (C : forall x, B x -> Type) :\n  Sigma A B -> Type :=\n  fun t =>\n    match t with\n    | pair x y => C x y\n    end.\n\nDefinition ev_pair {A} {B : A -> Type} (C : Sigma A B -> Type) :\n  (forall (t : Sigma A B), C t) -> (forall x y, C (pair x y)) :=\n  fun h x y => h (pair x y).\n\nDefinition inv_ev_pair {A} {B : A -> Type} (C : Sigma A B -> Type) :\n  (forall x y, C (pair x y)) -> (forall (t : Sigma A B), C t).\nProof.\n  intros h t; destruct t as [x y].\n  exact (h x y).\nDefined.\n\nDefinition is_sec_inv_ev_pair {A} {B : A -> Type} (C : Sigma A B -> Type) :\n  comp (ev_pair C) (inv_ev_pair C) ~ idmap := refl_htpy.\n\nDefinition sec_ev_pair {A} {B : A -> Type} (C : Sigma A B -> Type) :\n  sec (ev_pair C) :=\n  pair (inv_ev_pair C) (is_sec_inv_ev_pair C).\n\nDefinition triangle_path_ind\n           {A} {a : A} {B : A -> Type} (b : B a) (C : Sigma A B -> Type) :\n  @ev_pt (Sigma A B) C (pair a b) ~\n         comp (ev_refl_gen a b (fun x y => C (pair x y))) (ev_pair C) :=\n  refl_htpy.\n\nDefinition hom_slice_path_ind\n           {A} {a : A} {B : A -> Type} (b : B a) (C : Sigma A B -> Type) :\n  hom_slice (ev_pt (pair a b)) (ev_refl_gen a b (fun x y => C (pair x y))) :=\n  pair (ev_pair C) (triangle_path_ind b C).\n\nTheorem Ind_path_is_contr_total\n        {A} {a : A} {B : A -> Type} (b : B a) (C : forall x, B x -> Type) :\n  is_contr (Sigma A B) -> sec (ev_refl_gen a b C).\nProof.\n  intro c.\n  apply section_comp with (hom_slice_path_ind b (fam_Sigma C)).\n  - exact (sec_ev_pair (fam_Sigma C)).\n  - exact (Ind_sing_is_contr c (pair a b) (fam_Sigma C)).\nDefined.\n\nDefinition ind_path_is_contr_total\n           {A} {a : A} {B : A -> Type} (b : B a) (C : forall x, B x -> Type) :\n  is_contr (Sigma A B) -> C a b -> forall x y, C x y :=\n  fun is_contr_AB => pr1 (Ind_path_is_contr_total b C is_contr_AB).\n\nDefinition comp_path_is_contr_total\n           {A} {a : A} {B : A -> Type} (b : B a) (C : forall x, B x -> Type)\n           (is_contr_AB : is_contr (Sigma A B)) (c : C a b) :\n  ind_path_is_contr_total b C is_contr_AB c a b == c :=\n  pr2 (Ind_path_is_contr_total b C is_contr_AB) c.\n\nTheorem is_contr_total_Ind_path\n        {A} {a : A} {B : A -> Type} (b : B a) :\n  Ind_path B b -> is_contr (Sigma A B).\nProof.\n  intro P.\n  apply (is_contr_Ind_sing (pair a b)).\n  intro C.\n  apply section_comp' with (hom_slice_path_ind b C).\n  exact (sec_ev_pair C).\n  exact (P (fun x y => C (pair x y))).\nDefined.\n\n(** Section 9.3 Embeddings *)\n\n(** Definition 9.3.1 *)\n\nDefinition is_emb {A B} (f : A -> B) : Type :=\n  forall x y, is_equiv (@ap A B f x y).\n\n(** Theorem 9.3.2 *)\n\nDefinition fib' {A B} (f : A -> B) (b : B) : Type :=\n  Sigma A (fun x => b == f x).\n\nDefinition fib_fib_equiv {A B} (f : A -> B) (b : B) :\n  fib' f b <~> fib f b :=\n  tot_equiv (fun x => @invmap_equiv B b (f x)).\n\nTheorem is_emb_is_equiv {A B} (f : A -> B) :\n  is_equiv f -> is_emb f.\nProof.\n  intros H x.\n  apply fundamental_thm_id.\n  - reflexivity.\n  - apply (is_contr_equiv (fib_fib_equiv f (f x))).\n    now apply is_contr_map_is_equiv.\nDefined.\n\n(** Section 9.4 Disjointness of coproducts *)\n\n(** Theorem 9.4.1 *)\n\n(** This theorem is stated at the beginning of the section, and proven at the\n    end. *)\n\n(** Definition 9.4.2 *)\n\nDefinition Eq_coprod {A B} (x y : coprod A B) : Type.\nProof.\n  destruct x as [a|b].\n  - destruct y as [a'|b'].\n    * exact (a == a').\n    * exact empty.\n  - destruct y as [a'|b'].\n    * exact empty.\n    * exact (b == b').\nDefined.\n\n(** Lemma 9.4.3 *)\n\nLemma refl_Eq_coprod {A B} (x : coprod A B) : Eq_coprod x x.\nProof.\n  now destruct x.\nDefined.\n\nDefinition Eq_coprod_eq {A B} {x y : coprod A B} (p : x == y) : Eq_coprod x y.\nProof.\n  destruct p. apply refl_Eq_coprod.\nDefined.\n\n(** Lemma 9.4.4 *)\n\n(** We show that Sigma distributes over coproducts *)\n\nDefinition map_distr_Sigma_coprod {A B} (P : coprod A B -> Type) :\n  Sigma (coprod A B) P ->\n  coprod (Sigma A (comp P inl)) (Sigma B (comp P inr)).\nProof.\n  intro t; destruct t as [[a | b] y].\n  - exact (inl (pair a y)).\n  - exact (inr (pair b y)).\nDefined.\n\nDefinition inv_map_distr_Sigma_coprod {A B} (P : coprod A B -> Type) :\n  coprod (Sigma A (comp P inl)) (Sigma B (comp P inr)) ->\n  Sigma (coprod A B) P.\nProof.\n  intro x; destruct x as [[a p]|[b p]].\n  - exact (pair (inl a) p).\n  - exact (pair (inr b) p).\nDefined.\n\nDefinition is_sec_inv_map_distr_Sigma_coprod {A B} (P : coprod A B -> Type) :\n  comp (map_distr_Sigma_coprod P) (inv_map_distr_Sigma_coprod P) ~ idmap.\nProof.\n    intro x; now destruct x as [[a p]|[b p]].\nDefined.\n\nDefinition is_retr_inv_map_distr_Sigma_coprod {A B} (P : coprod A B -> Type) :\n  comp (inv_map_distr_Sigma_coprod P) (map_distr_Sigma_coprod P) ~ idmap.\nProof.\n  intro t; now destruct t as [[a | b] y].\nDefined.\n\nLemma is_equiv_map_distr_Sigma_coprod {A B} (P : coprod A B -> Type) :\n  is_equiv (map_distr_Sigma_coprod P).\nProof.\n  simple refine (is_equiv_has_inverse _ _ _).\n  - exact (inv_map_distr_Sigma_coprod P).\n  - exact (is_sec_inv_map_distr_Sigma_coprod P).\n  - exact (is_retr_inv_map_distr_Sigma_coprod P).\nDefined.\n  \nDefinition distr_Sigma_coprod {A B} (P : coprod A B -> Type) :\n  Sigma (coprod A B) P\n        <~>\n        coprod (Sigma A (comp P inl)) (Sigma B (comp P inr)) :=\n  pair (map_distr_Sigma_coprod P) (is_equiv_map_distr_Sigma_coprod P).\n\nLemma is_contr_total_Eq_coprod_inl {A B} (x : A) :\n  is_contr (Sigma (coprod A B) (Eq_coprod (inl x))).\nProof.\n  apply (is_contr_equiv (distr_Sigma_coprod (Eq_coprod (inl x)))).\n  simple refine (is_contr_equiv _ _).\n  - exact (coprod (total_path x) empty).\n  - refine (coprod_equiv _ _).\n    * exact id_equiv.\n    * exact right_zero_law_prod.\n  - simple refine (is_contr_equiv' _ _).\n    * exact (total_path x).\n    * exact right_unit_law_coprod.\n    * apply is_contr_total_path.\nDefined.\n\nLemma is_contr_total_Eq_coprod_inr {A B} (y : B) :\n  is_contr (Sigma (coprod A B) (Eq_coprod (inr y))).\nProof.\n  apply (is_contr_equiv (distr_Sigma_coprod (Eq_coprod (inr y)))).\n  simple refine (is_contr_equiv _ _).\n  - exact (coprod empty (total_path y)).\n  - refine (coprod_equiv _ _).\n    * exact right_zero_law_prod.\n    * exact id_equiv.\n  - simple refine (is_contr_equiv' _ _).\n    * exact (total_path y).\n    * exact left_unit_law_coprod.\n    * apply is_contr_total_path.\nDefined.\n\nTheorem is_contr_total_Eq_coprod {A B} (x : coprod A B) :\n  is_contr (Sigma (coprod A B) (Eq_coprod x)).\nProof.\n  destruct x as [x|y].\n  - apply is_contr_total_Eq_coprod_inl.\n  - apply is_contr_total_Eq_coprod_inr.\nDefined.\n\nTheorem is_equiv_Eq_coprod_eq {A B} {x y : coprod A B} :\n  is_equiv (@Eq_coprod_eq A B x y).\nProof.\n  apply fundamental_thm_id.\n  - apply refl_Eq_coprod.\n  - apply is_contr_total_Eq_coprod.\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_09_fundamental_theorem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6940902668801346}}
{"text": "Require Import Bool Arith String List CpdtTactics.\nOpen Scope string_scope.\n\nDefinition var := string.\n\nInductive binop := Plus | Times | Minus.\n\nInductive aexp : Type := \n| Const : nat -> aexp\n| Var : var -> aexp\n| Binop : aexp -> binop -> aexp -> aexp.\n\nInductive bexp : Type := \n| Tt : bexp\n| Ff : bexp\n| Eq : aexp -> aexp -> bexp\n| Lt : aexp -> aexp -> bexp\n| And : bexp -> bexp -> bexp\n| Or : bexp -> bexp -> bexp\n| Not : bexp -> bexp.\n\nInductive com : Type := \n| Skip : com\n| Assign : var -> aexp -> com\n| Seq : com -> com -> com\n| If : bexp -> com -> com -> com\n| While : bexp -> com -> com.\n\nDefinition state := var -> nat.\n\nDefinition get (x:var) (s:state) : nat := s x.\n\nDefinition set (x:var) (n:nat) (s:state) : state := \n  fun y => \n    match string_dec x y with \n        | left H => n \n        | right H' => get y s\n    end.\n\nDefinition eval_binop (b:binop) : nat -> nat -> nat := \n  match b with \n    | Plus => plus\n    | Times => mult\n    | Minus => minus\n  end.\n\nFixpoint eval_aexp (e:aexp) (s:state) : nat := \n  match e with \n    | Const n => n\n    | Var x => get x s\n    | Binop e1 b e2 => (eval_binop b) (eval_aexp e1 s) (eval_aexp e2 s)\n  end.\n\nFixpoint eval_bexp (b:bexp) (s:state) : bool := \n  match b with \n    | Tt => true\n    | Ff => false\n    | Eq e1 e2 => NPeano.Nat.eqb (eval_aexp e1 s) (eval_aexp e2 s)\n    | Lt e1 e2 => NPeano.ltb (eval_aexp e1 s) (eval_aexp e2 s)\n    | And b1 b2 => eval_bexp b1 s && eval_bexp b2 s\n    | Or b1 b2 => eval_bexp b1 s || eval_bexp b2 s\n    | Not b => negb (eval_bexp b s)\n  end.\n\nInductive eval_com : com -> state -> state -> Prop := \n| Eval_skip : forall s, eval_com Skip s s\n| Eval_assign : forall s x e, eval_com (Assign x e) s (set x (eval_aexp e s) s)\n| Eval_seq : forall c1 s0 s1 c2 s2, \n               eval_com c1 s0 s1 -> eval_com c2 s1 s2 -> eval_com (Seq c1 c2) s0 s2\n| Eval_if_true : forall b c1 c2 s s',\n                   eval_bexp b s = true -> \n                   eval_com c1 s s' -> eval_com (If b c1 c2) s s'\n| Eval_if_false : forall b c1 c2 s s',\n                   eval_bexp b s = false -> \n                   eval_com c2 s s' -> eval_com (If b c1 c2) s s'\n| Eval_while_false : forall b c s, \n                       eval_bexp b s = false -> \n                       eval_com (While b c) s s\n| Eval_while_true : forall b c s1 s2 s3, \n                      eval_bexp b s1 = true -> \n                      eval_com c s1 s2 -> \n                      eval_com (While b c) s2 s3 -> \n                      eval_com (While b c) s1 s3.\n\nDefinition prog1 := \n  Seq (Assign \"y\" (Const 1))\n  (Seq (Assign \"x\" (Const 3))\n       (While (Lt (Const 0) (Var \"x\"))\n              (Seq (Assign \"y\" (Binop (Var \"y\") Times (Const 2)))\n                   (Assign \"x\" (Binop (Var \"x\") Minus (Const 1)))))).\n\nDefinition prog2 := While Tt Skip.\n\nLtac myinj H := injection H ; intros ; subst ; clear H.\n\nLemma while_true_imp_false : forall c s1 s2, eval_com c s1 s2 -> \n                                             forall b c', (forall s, eval_bexp b s = true) -> \n                                                          c = While b c' -> \n                                                          False. \nProof.\n  Ltac foo := \n  match goal with \n    | [ H : ?x _ _ = ?x _ _ |- _ ] => myinj H\n    | [ H : forall s, eval_bexp _ s = _,\n        H' : eval_bexp _ ?s0 = _ |- _] => \n      specialize (H s0) ; congruence\n    | [ H : forall b c, _ -> _ |- _ ] => eapply H ; eauto\n  end.\n\n  induction 1 ; intros ; try discriminate ; repeat foo.\nQed.\n  \nLemma prog2_div : forall s1 s2, eval_com prog2 s1 s2 -> False.\n\n  Lemma prog2_div' : forall c s1 s2, eval_com c s1 s2 -> c = prog2 -> False.\n  Proof.\n    unfold prog2 ; induction 1; crush.\n  Qed.\n  Show.\n  intros. apply (prog2_div' _ _ _ H eq_refl).\nQed.\n\n(* A simple chained tactic *)\nLtac myinv H := inversion H ; subst ; clear H ; simpl in *.\n\n(* This tactic applies when we have a hypothesis involving\n   eval_com of either a Seq or an Assign.  It inverts the\n   hypothesis, and performs substitution, simplifying things.\n*)\nLtac eval_inv := \n  match goal with \n    | [ H : eval_com (Seq _ _) _ _ |- _ ] => myinv H\n    | [ H : eval_com (Assign _ _) _ _ |- _ ] => myinv H\n  end.\n\n(* This tactic inverts an eval_com of a While, producing\n   two sub-goals.  It tries to eliminate one (or both) of the goals\n   through discrimination on the hypotheses.\n*)\nLtac eval_while_inv := \n  match goal with\n    | [ H : eval_com (While _ _) _ _ |- _ ] => myinv H ; try discriminate\n  end.\n\nTheorem prog1_prop : forall s1 s2, eval_com prog1 s1 s2 -> get \"x\" s2 = 0.\nProof.\n  unfold prog1 ; intros.\n  repeat ((repeat eval_inv) ; eval_while_inv).\n  auto.\nQed.\n\nTheorem seq_assoc : \n  forall c1 c2 c3 s1 s2, \n    eval_com (Seq (Seq c1 c2) c3) s1 s2 -> \n    eval_com (Seq c1 (Seq c2 c3)) s1 s2.\n  Lemma seq_assoc' : \n    forall c s1 s2, \n      eval_com c s1 s2 -> \n      forall c1 c2 c3,\n        c = Seq (Seq c1 c2) c3 -> \n        eval_com (Seq c1 (Seq c2 c3)) s1 s2.\n  Proof.\n    (* Adds all of the eval_com constructors as hints for auto/crush *)\n    Hint Constructors eval_com.\n    induction 1 ; crush.\n    inversion H ; clear H ; subst ; \n    econstructor ; eauto.\n  Qed.\n\n  intros. eapply seq_assoc' ; eauto.\nQed.\n\n(* Returns true when the variable x occurs as a subexpression of a *)\nFixpoint contains (x:var) (a:aexp) : bool := \n  match a with \n    | Const _ => false\n    | Var y => if string_dec x y then true else false\n    | Binop a1 _ a2 => contains x a1 || contains x a2\n  end.\n\n(* Changing a variable x that doesn't occur in a doesn't effect the \n   value of a. *)\nLemma eval_exp_set : \n  forall s x n a,\n    contains x a = false -> \n    eval_aexp a (set x n s) = eval_aexp a s.\nProof.\n  induction a ; unfold set, get ; simpl ; unfold get ; crush.\n  destruct (string_dec x v) ; crush.\n  destruct (contains x a1) ; crush.\nQed.  \n\n(* We can commute assignments x:=ax; y:=ay  as long as the\n   variables don't overlap. *)\nLemma assign_comm : \n  forall x ax y ay s1 s2,\n    eval_com (Seq (Assign x ax) (Assign y ay)) s1 s2 -> \n    contains x ay = false -> \n    contains y ax = false -> \n    x <> y -> \n    forall s3, eval_com (Seq (Assign y ay) (Assign x ax)) s1 s3 -> s2 = s3.\n(*\n               forall z, get z s3 = get z s2.\n*)\nProof.\n  intros.\n  repeat eval_inv.\n  repeat unfold set, get.\n  destruct (string_dec x z) ; destruct (string_dec y z) ; try congruence.\n  specialize (eval_exp_set s1 y (eval_aexp ay s1) ax H1).\n  unfold set. crush.\n  specialize (eval_exp_set s1 x (eval_aexp ax s1) ay H0).\n  unfold set. crush.\nQed.\n\n\nLemma assign_comm2 : \n  forall x ax y ay s1 s2,\n    eval_com (Seq (Assign x ax) (Assign y ay)) s1 s2 -> \n    contains x ay = false -> \n    contains y ax = false -> \n    x <> y -> \n    eval_com (Seq (Assign y ay) (Assign x ax)) s1 s2.\nProof.\n  intros.\n  remember (set x (eval_aexp ax (set y (eval_aexp ay s1) s1))\n                (set y (eval_aexp ay s1) s1)) as s3.\n  assert (eval_com (Seq (Assign y ay) (Assign x ax)) s1 s3).\n  rewrite Heqs3.\n  eauto.\n  specialize (assign_comm x ax y ay s1 s2 H H0 H1 H2 _ H3).\n  intro.\n  assert (s3 = s2).\n  Focus 2.\n  rewrite <- H5.\n  auto.\n  Admitted.\n", "meta": {"author": "Keno", "repo": "CS250", "sha": "5865c43b99d3acee956d610475445894851397f6", "save_path": "github-repos/coq/Keno-CS250", "path": "github-repos/coq/Keno-CS250/CS250-5865c43b99d3acee956d610475445894851397f6/notes/lecture6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6940902531451884}}
{"text": "Require Export NArith.\nRequire Import ZArith.\n\nOpen Scope N_scope.\n\nTheorem Nle_le: forall n  m, (N.to_nat n <= N.to_nat m)%nat -> n <= m.\nintros n m; case n; case m; unfold N.le; simpl; try (intros; discriminate).\nintros p; elim p using Pind; simpl.\nintros H1; inversion H1. \nintros n1 _; rewrite nat_of_P_succ_morphism.\nintros H1; inversion H1.\nintros p1 p2 H1 H2; absurd (nat_of_P p2 > nat_of_P p1)%nat; auto with arith.\napply nat_of_P_gt_Gt_compare_morphism; auto.\nQed.\n\nTheorem le_Nle: forall n m, N.of_nat n <= N.of_nat m -> (n <= m)%nat.\nintros n m; case n; case m; unfold N.le; simpl; auto with arith.\nintros n1 H1; case H1; auto.\nintros m1 n1 H1; case (le_or_lt n1 m1); auto with arith.\nintros H2; case H1.\napply nat_of_P_gt_Gt_compare_complement_morphism.\nrepeat rewrite  nat_of_P_o_P_of_succ_nat_eq_succ; auto with arith.\nQed.\n\nTheorem Nle_le_rev: forall n  m, n <= m -> (N.to_nat n <= N.to_nat m)%nat.\nintros; apply le_Nle; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Nlt_lt: forall n  m, (N.to_nat n < N.to_nat m)%nat -> n < m.\nintros n m; case n; case m; unfold N.lt; simpl; try (intros; discriminate); auto.\nintros H1; inversion H1.\nintros p H1; inversion H1.\nintros; apply nat_of_P_lt_Lt_compare_complement_morphism; auto.\nQed.\n\nTheorem lt_Nlt: forall n m, N.of_nat n < N.of_nat m -> (n < m)%nat.\nintros n m; case n; case m; unfold N.lt; simpl; try (intros; discriminate); auto with arith.\nintros m1 n1 H1.\nrewrite <- (Nat2N.id (S n1)); rewrite <- (Nat2N.id (S m1)).\nsimpl; apply nat_of_P_lt_Lt_compare_morphism; auto.\nQed.\n\nTheorem Nlt_lt_rev: forall n  m, n < m -> (N.to_nat n < N.to_nat m)%nat.\nintros; apply lt_Nlt; repeat rewrite N2Nat.id; auto.\nQed.\n\n\nTheorem Nge_ge: forall n  m, (N.to_nat n >= N.to_nat m)%nat -> n >= m.\nintros n m; case n; case m; unfold N.ge; simpl; try (intros; discriminate); auto.\nintros p; elim p using Pind; simpl.\nintros H1; inversion H1. \nintros n1 _; rewrite nat_of_P_succ_morphism.\nintros H1; inversion H1.\nintros p1 p2 H1 H2; absurd (nat_of_P p2 < nat_of_P p1)%nat; auto with arith.\napply nat_of_P_lt_Lt_compare_morphism; auto.\nQed.\n\nTheorem ge_Nge: forall n m, N.of_nat n >= N.of_nat m -> (n >= m)%nat.\nintros n m; case n; case m; unfold N.ge; simpl; try (intros; discriminate); auto with arith.\nintros n1 H1; case H1; auto.\nintros m1 n1 H1.\ncase (le_or_lt m1 n1); auto with arith.\nintros H2; case H1.\napply nat_of_P_lt_Lt_compare_complement_morphism.\nrepeat rewrite  nat_of_P_o_P_of_succ_nat_eq_succ; auto with arith.\nQed.\n\nTheorem Nge_ge_rev: forall n  m, n >= m -> (N.to_nat n >= N.to_nat m)%nat.\nintros; apply ge_Nge; repeat rewrite N2Nat.id; auto.\nQed.\n\n\nTheorem Ngt_gt: forall n  m, (N.to_nat n > N.to_nat m)%nat -> n > m.\nintros n m; case n; case m; unfold N.gt; simpl; try (intros; discriminate); auto.\nintros H1; inversion H1.\nintros p H1; inversion H1.\nintros; apply nat_of_P_gt_Gt_compare_complement_morphism; auto.\nQed.\n\nTheorem gt_Ngt: forall n m, N.of_nat n > N.of_nat m -> (n > m)%nat.\nintros n m; case n; case m; unfold N.gt; simpl; try (intros; discriminate); auto with arith.\nintros m1 n1 H1.\nrewrite <- (Nat2N.id (S n1)); rewrite <- (Nat2N.id (S m1)).\nsimpl; apply nat_of_P_gt_Gt_compare_morphism; auto.\nQed.\n\nTheorem Ngt_gt_rev: forall n  m, n > m -> (N.to_nat n > N.to_nat m)%nat.\nintros; apply gt_Ngt; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Neq_eq_rev: forall n  m, n = m -> (N.to_nat n = N.to_nat m)%nat.\nintros n m H; rewrite H; auto.\nQed.\n\nImport BinPos.\n\n\nLtac to_nat_op  :=\n  match goal with\n      H: (N.lt _ _) |- _ => generalize (Nlt_lt_rev _ _ H); clear H; intros H\n|     H: (N.gt _ _) |- _ => generalize (Ngt_gt_rev _ _ H); clear H; intros H\n|     H: (N.le _ _) |- _ => generalize (Nle_le_rev _ _ H); clear H; intros H\n|     H: (N.ge _ _) |- _ => generalize (Nge_ge_rev _ _ H); clear H; intros H\n|     H: (@eq N _ _) |- _ => generalize (Neq_eq_rev _ _ H); clear H; intros H\n|      |- (N.lt _ _)  => apply Nlt_lt\n|      |- (N.le _ _)  => apply Nle_le\n|      |- (N.gt _ _)  => apply Ngt_gt\n|      |- (N.ge _ _)  => apply Nge_ge\n|      |- (@eq N _ _)  => apply Nat2N.inj\nend.\n\nLtac set_to_nat :=\nlet nn := fresh \"nn\" in\nmatch goal with\n       |- context [(N.to_nat (?X + ?Y)%N)]  => rewrite N2Nat.inj_add\n|      |- context [(N.to_nat (?X * ?Y)%N)]  => rewrite N2Nat.inj_mul\n|      |- context [(N.to_nat ?X)]  => set (nn:=N.to_nat X) in * |- *\n|      H: context [(N.to_nat (?X + ?Y)%N)] |- _ => rewrite N2Nat.inj_add in H\n|      H: context [(N.to_nat (?X + ?Y)%N)] |- _ => rewrite N2Nat.inj_mul in H\n|      H: context [(N.to_nat ?X)] |- _ => set (nn:=N.to_nat X) in * |- *\nend.\n\nLtac to_nat := repeat to_nat_op; repeat set_to_nat.\n\nTheorem Nle_gt_trans: forall n m p, m <= n -> m > p -> n > p.\nintros; to_nat; apply le_gt_trans with nn1; auto.\nQed.\n\nTheorem Ngt_le_trans: forall n m p, n > m -> p <= m -> n > p.\nintros; to_nat; apply gt_le_trans with nn1; auto.\nQed.\n\nTheorem Nle_add_l :\n  forall x y, x <= y + x.\nintros; to_nat; auto with arith.\nQed.\n\nClose Scope N_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/PolTac/NAux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156295, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.6940902515588321}}
{"text": "(* This file implements a 'chained list'. This can essentially be\nthought of as the proof-relevant transitive reflexive closure of\na relation. That is, each link (element) has a \"from\" point that\nmust match the previous element's \"to\" point. *)\nRequire Import Automation.\nSection ChainedList.\nContext {Point : Type} {Link : Point -> Point -> Type}.\n\nInductive ChainedList : Point -> Point -> Type :=\n  | clnil : forall {p}, ChainedList p p\n  | snoc : forall {from mid to},\n      ChainedList from mid -> Link mid to -> ChainedList from to.\n\nFixpoint clist_app\n           {from mid to}\n           (xs : ChainedList from mid)\n           (ys : ChainedList mid to) : ChainedList from to :=\n  match ys with\n  | clnil => fun xs => xs\n  | snoc ys' y => fun xs => snoc (clist_app xs ys') y\n  end xs.\n\nInfix \"++\" := clist_app (right associativity, at level 60).\n\nDefinition clist_prefix\n           {from mid to}\n           (prefix : ChainedList from mid)\n           (full : ChainedList from to) : Prop :=\n  exists suffix, full = prefix ++ suffix.\n\nDefinition clist_suffix\n           {from mid to}\n           (suffix : ChainedList mid to)\n           (full : ChainedList from to) : Prop :=\n  exists prefix, full = prefix ++ suffix.\n\nInfix \"`prefix_of`\" := clist_prefix (at level 70).\nInfix \"`suffix_of`\" := clist_suffix (at level 70).\n\nSection Theories.\nLemma app_clnil_l {from to} (xs : ChainedList from to) :\n  clnil ++ xs = xs.\nProof. induction xs; auto; cbn; solve_by_rewrite. Qed.\n\nLemma clist_app_assoc\n      {c1 c2 c3 c4}\n      (xs : ChainedList c1 c2)\n      (ys : ChainedList c2 c3)\n      (zs : ChainedList c3 c4) :\n  xs ++ ys ++ zs = (xs ++ ys) ++ zs.\nProof. induction zs; intros; auto; cbn; solve_by_rewrite. Qed.\nEnd Theories.\n\nLemma prefix_of_app\n      {from mid to to'}\n      {prefix : ChainedList from mid}\n      {xs : ChainedList from to}\n      {suffix : ChainedList to to'} :\n  prefix `prefix_of` xs ->\n  prefix `prefix_of` xs ++ suffix.\nProof.\n  intros [ex_suffix ex_suffix_eq_app].\n  exists (ex_suffix ++ suffix).\n  rewrite clist_app_assoc; congruence.\nQed.\nEnd ChainedList.\n\nDelimit Scope clist_scope with trace.\nBind Scope clist_scope with ChainedList.\nInfix \"++\" := clist_app (right associativity, at level 60) : clist_scope.\n\nInfix \"`prefix_of`\" := clist_prefix (at level 70) : clist_scope.\nInfix \"`suffix_of`\" := clist_suffix (at level 70) : clist_scope.\n\nArguments ChainedList : clear implicits.\n", "meta": {"author": "malthelange", "repo": "CLVM", "sha": "e80aef02c3112b5b62db79bc2b233020367b0bde", "save_path": "github-repos/coq/malthelange-CLVM", "path": "github-repos/coq/malthelange-CLVM/CLVM-e80aef02c3112b5b62db79bc2b233020367b0bde/execution/theories/ChainedList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825635346563, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.6940531849910079}}
{"text": "Axiom classic : forall (P : Prop), {P} + {~P}.\n\nAxiom prop_ext : forall {P : Prop} (p q : P), p = q.\n\nAxiom fun_ext : forall {X Y} (f g : X -> Y), (forall x, f x = g x) -> f = g.\n\nTheorem not_not_elim P : ~~P -> P.\nProof. destruct (classic P); intuition. Qed.\n\nDefinition definite {T} (V : T -> Prop) := exists! y, V y.\nAxiom definite_description : forall {T} (V : T -> Prop), definite V -> sig V.\nDefinition the {T} (V : T -> Prop) {p : definite V} := proj1_sig (definite_description V p).\n\nTheorem definite_compat {T} (V P : T -> Prop) : definite V -> (exists x, V x /\\ P x) <-> (forall x, V x -> P x).\nProof.\n  intros [y [? eq]].\n  split.\n  + intros [x []] z ?.\n    replace x with y in *; auto.\n    replace z with y in *; auto.\n  + intros ?. exists y. auto.\nQed.\n", "meta": {"author": "mniip", "repo": "ZF", "sha": "870fa0012f33d373ae610772ca2620d78e3809db", "save_path": "github-repos/coq/mniip-ZF", "path": "github-repos/coq/mniip-ZF/ZF-870fa0012f33d373ae610772ca2620d78e3809db/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6940451506088517}}
{"text": "(** * Selection:  Selection Sort *)\n\n(** If you don't recall selection sort or haven't seen it in\n    a while, see Wikipedia or read any standard textbook; some\n    suggestions can be found in [Sort]. *)\n\n(** The specification for sorting algorithms we developed in\n    [Sort] can also be used to verify selection sort.  The\n    selection-sort program itself is interesting, because writing it\n    in Coq will cause us to explore a new technique for convincing Coq\n    that a function terminates. *)\n\n(** A couple of notes on efficiency:\n\n    - Selection sort, like insertion sort, runs in quadratic time.\n      But selection sort typically makes many more comparisons than\n      insertion sort, so insertion sort is usually preferable for\n      sorting small inputs.  Selection sort can beat insertion sort if\n      the cost of swapping elements is vastly higher than the cost of\n      comparing them, but that doesn't apply to functional lists.\n\n    - What you should really never use is bubble sort.  \"Bubble sort\n      would be the wrong way to go.\"  Everybody should know that!  See\n      this video for a definitive statement:\n        {https://www.youtube.com/watch?v=k4RRi_ntQc8&t=34} *)\n\nSet Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom VFA Require Import Perm.\nHint Constructors Permutation.\nFrom Coq Require Export Lists.List.  (* for exercise involving [List.length] *)\n\n(* ################################################################# *)\n(** * The Selection-Sort Program  *)\n\n(** Selection sort on lists is more challenging to code in Coq\n    than insertion sort was. First, we write a helper function\n    to select the smallest element. *)\n\n(* [select x l] is [(y, l')], where [y] is the smallest element\n   of [x :: l], and [l'] is all the remaining elements of [x :: l]\n   in their original order. *)\nFixpoint select (x: nat) (l: list nat) : nat * list nat :=\n  match l with\n  | [] => (x, [])\n  | h :: t =>\n    if x <=? h\n    then let (j, l') := select x t\n         in (j, h :: l')\n    else let (j, l') := select h t\n         in (j, x :: l')\n  end.\n\n(** Selection sort should repeatedly extract the smallest element and\n    make a list of the results. But the following attempted definition\n    fails: *)\n\nFail Fixpoint selsort (l : list nat) : list nat :=\n  match l with\n  | [] => []\n  | x :: r => let (y, r') := select x r\n            in y :: selsort r'\n  end.\n\n(** Coq rejects [selsort] because it doesn't satisfy Coq's\n    requirements for termination.  The problem is that the recursive\n    call in [selsort] is not _structurally decreasing_: the argument\n    [r'] at the call site is not known to be a smaller part of the\n    original input [l]. Indeed, [select] might not return such a list.\n    For example, [select 1 [0; 2]] is [(0, [1; 2])], but [[1; 2]] is\n    not a part of [[0; 2]]. *)\n\n(** There are severals ways to fix this problem. One programming\n    pattern is to provide _fuel_: an extra argument that has no use in\n    the algorithm except to bound the amount of recursion.  The [n]\n    argument, below, is the fuel. When it reaches [0], the recursion\n    terminates. *)\n\nFixpoint selsort (l : list nat) (n : nat) : list nat :=\n  match l, n with\n  | _, O => []  (* ran out of fuel *)\n  | [], _ => []\n  | x :: r, S n' => let (y, r') := select x r\n                  in y :: selsort r' n'\nend.\n\n(** If fuel runs out, we get the wrong output. *)\n\nExample out_of_fuel: selsort [3;1;4;1;5] 3 <> [1;1;3;4;5].\nProof.\n  simpl. intro. discriminate.\nQed.\n\n(** Extra fuel isn't a problem though. *)\n\nExample extra_fuel: selsort [3;1;4;1;5] 10 = [1;1;3;4;5].\nProof.\n  simpl. reflexivity.\nQed.\n\n(** The exact amount of fuel needed is the length of the input list.\n    So that's how we define [selection_sort]: *)\n\nDefinition selection_sort (l : list nat) : list nat :=\n  selsort l (length l).\n\nExample sort_pi :\n  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.\n  unfold selection_sort.\n  simpl. reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Proof of Correctness *)\n\n(** We begin by repeating from [Sort] the specification of a\n    correct sorting algorithm: it rearranges the elements into a list\n    that is totally ordered. *)\n\nInductive sorted: list nat -> Prop :=\n | sorted_nil: sorted []\n | sorted_1: forall i, sorted [i]\n | sorted_cons: forall i j l, i <= j -> sorted (j :: l) -> sorted (i :: j :: l).\n\nHint Constructors sorted.\n\nDefinition is_a_sorting_algorithm (f: list nat -> list nat) := forall al,\n    Permutation al (f al) /\\ sorted (f al).\n\n(** In the following exercises, you will prove that selection sort\n    is a correct sorting algorithm.  You might wish to keep track\n    of the lemmas you have proved, so that you can spot places to\n    use them later. *)\n\n(** Depending on the path you have followed through _Software\n    Foundations_ it might have been a while since you have worked with\n    pairs.  Here's a brief reminder of how [destruct] can be used to\n    break a pair apart into its components.  A similar technique\n    will be needed in many of the following proofs. *)\nExample pairs_example : forall (a c x : nat) (b d l : list nat),\n    (a, b) = (let (c, d) := select x l in (c, d)) ->\n    (a, b) = select x l.\nProof.\n  intros. destruct (select x l) eqn:E. auto.\nQed.\n\n(** **** Exercise: 3 stars, standard (select_perm) *)\n\n(** Prove that [select] returns a permutation of its\n    input. Proceed by induction on [l].  The [inv] tactic defined at\n    the end of [Perm] will be helpful. *)\n\nLemma select_perm: forall x l y r,\n  (y, r) = select x l -> Permutation (x :: l) (y :: r).\nProof.\n  intros x l.\n  generalize dependent x.\n  induction l; intros.\n  (* nil *) inv H. auto.\n  (* a :: l *)\n  inv H.\n  assert (Permutation (x :: a :: l) (a :: x :: l)) by constructor.\n  bdestruct (a >=? x).\n  - (* a >= x *)\n    destruct (select x l) eqn:E.\n    apply (Permutation_trans H).\n    inv H1.\n    assert (Permutation (x :: l) (n :: l0)) by auto.\n    assert (Permutation (n :: a :: l0) (a :: n :: l0)) by constructor.\n    apply Permutation_sym.\n    apply (Permutation_trans H2).\n    apply Permutation_sym.\n    auto.\n  - (* a < x *)\n    destruct (select a l) eqn:E.\n    inv H1.\n    assert (Permutation (n :: x :: l0) (x :: n :: l0)) by constructor.\n    apply Permutation_sym.\n    apply (Permutation_trans H1).\n    constructor.\n    apply Permutation_sym.\n    apply IHl.\n    auto.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (selsort_perm) *)\n\n(** Prove that if you provide sufficient fuel, [selsort] produces a\n    permutation.  Proceed by induction on [n]. *)\n\nLemma selsort_perm: forall n l,\n    length l = n -> Permutation l (selsort l n).\nProof.\n  intro. induction n; intros.\n  (* 0 *) apply length_zero_iff_nil in H. subst. auto.\n  (* S n *)\n  destruct l. auto.\n  simpl in H.\n  simpl.\n  destruct (select n0 l) eqn:E.\n  apply eq_sym in E.\n  apply select_perm in E.\n  apply (Permutation_trans E).\n  constructor.\n  apply IHn.\n  apply Permutation_length in E.\n  inv E. inv H. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard (selection_sort_perm) *)\n\n(** Prove that [selection_sort] produces a permutation. *)\n\nLemma selection_sort_perm: forall l,\n    Permutation l (selection_sort l).\nProof.\n  intro.\n  unfold selection_sort.\n  apply selsort_perm.\n  reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (select_rest_length) *)\n\n(** Prove that [select] returns a list that has the correct\n    length. You can do this without induction if you make use of\n    [select_perm]. *)\n\nLemma select_rest_length : forall x l y r,\n    select x l = (y, r) -> length l = length r.\nProof.\n  intros.\n  apply eq_sym in H.\n  apply select_perm in H.\n  apply Permutation_length in H.\n  inv H.\n  reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (select_fst_leq) *)\n\n(** Prove that the first component of [select x _] is no bigger than\n    [x]. Proceed by induction on [al]. *)\n\nLemma select_fst_leq: forall al bl x y,\n    select x al = (y, bl) ->\n    y <= x.\nProof.\n  intro. induction al; intros.\n  (* nil *) simpl in H. inv H. auto.\n  (* a :: al *)\n  simpl in H.\n  bdestruct (a >=? x).\n  - (* a >= x *)\n    destruct (select x al) eqn:E.\n    apply IHal in E.\n    inv H.\n    assumption.\n  - (* a < x*)\n    destruct (select a al) eqn:E.\n    apply IHal in E.\n    inv H.\n    lia.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (select_smallest) *)\n\n(** Prove that the first component of [select _ _] is no bigger\n    than any of the elements in the second component. To represent\n    that concept of comparing an element to a list, we introduce\n    a new notation: *)\n\nDefinition le_all x xs := Forall (fun y => x <= y) xs.\nInfix \"<=*\" := le_all (at level 70, no associativity).\n\n(** Proceed by induction on [al]. *)\n\nLemma select_smallest: forall al bl x y,\n    select x al = (y, bl) ->\n    y <=* bl.\nProof.\n  intro. induction al; intros.\n  (* nil *) simpl in H. inv H. constructor.\n  (* a :: al *)\n  simpl in H.\n  bdestruct (a >=? x).\n  - (* a >= x *)\n    destruct (select x al) eqn:E.\n    apply IHal in E as H1.\n    apply select_fst_leq in E.\n    inv H.\n    assert (y <= a) by lia.\n    constructor; assumption.\n  - (* a < x *)\n    destruct (select a al) eqn:E.\n    apply IHal in E as H1.\n    apply select_fst_leq in E.\n    inv H.\n    assert (y <= x) by lia.\n    constructor; assumption.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (select_in) *)\n\n(** Prove that the element returned by [select] must be one of the\n    elements in its input. Proceed by induction on [al]. *)\n\nLemma select_in : forall al bl x y,\n    select x al = (y, bl) ->\n    In y (x :: al).\nProof.\n  intro. induction al; intros.\n  (* nil *) inv H. constructor. reflexivity.\n  (* a :: al *)\n  apply select_fst_leq in H as H__yleqx.\n  apply select_smallest in H as H__yleallbl.\n  simpl in H.\n  bdestruct (a >=? x).\n  - (* a >= x *)\n    destruct (select x al) eqn:E.\n    inv H.\n    apply IHal in E.\n    apply in_cons with (a := a) in E.\n    assert (Permutation (a :: x :: al) (x :: a :: al)) by constructor.\n    apply (Permutation_in y H E).\n  - (* a < x *)\n    destruct (select a al) eqn:E.\n    inv H.\n    apply IHal in E.\n    apply in_cons with (a := x) in E.\n    assumption.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (cons_of_small_maintains_sort) *)\n\n(** Prove that adding an element to the beginning of a\n    selection-sorted list maintains sortedness, as long as the element\n    is small enough and enough fuel is provided. *)\n\nLemma cons_of_small_maintains_sort: forall bl y n,\n    n = length bl ->\n    y <=* bl ->\n    sorted (selsort bl n) ->\n    sorted (y :: selsort bl n).\nProof.\n  intro. induction bl; intros; subst.\n  (* nil *) auto.\n  (* a :: bl *)\n  simpl. simpl in H1.\n  destruct (select a bl) eqn:E.\n  apply select_smallest in E as H2.\n  apply select_in in E as H3.\n  assert (y <= n). {\n    unfold le_all in H0.\n    rewrite Forall_forall in H0.\n    specialize H0 with n.\n    apply H0 in H3.\n    assumption.\n  }\n  auto.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (selsort_sorted) *)\n\n(** Prove that [selsort] produced a sorted list when given\n    sufficient fuel.  Proceed by induction on [n].  This proof\n    will make use of a few previous lemmas. *)\n\nLemma selsort_sorted : forall n al,\n    length al = n -> sorted (selsort al n).\nProof.\n  intro n. induction n; intros.\n  (* 0 *) apply length_zero_iff_nil in H. inv H. auto.\n  (* S n *)\n  destruct al eqn:E.\n  (* nil *) discriminate.\n  (* n0 :: l *)\n  simpl in H.\n  apply eq_add_S in H.\n  assert (Hl__sorted: sorted (selsort l n))\n    by (apply IHn in H; assumption).\n  simpl. destruct (select n0 l) eqn:E0.\n  assert (Hl0__length: length l0 = n). {\n    apply select_rest_length in E0.\n    subst.\n    symmetry.\n    assumption.\n  }\n  assert (Hl0__sorted: sorted (selsort l0 n))\n    by (apply IHn in Hl0__length; assumption).\n  assert (Hn0__lealll0: n1 <=* l0)\n    by apply (select_smallest _ _ _ _ E0).\n  symmetry in Hl0__length.\n  apply cons_of_small_maintains_sort; assumption.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard (selection_sort_sorted) *)\n\n(** Prove that [selection_sort] produces a sorted list. *)\n\nLemma selection_sort_sorted : forall al,\n    sorted (selection_sort al).\nProof.\n  intro. unfold selection_sort.\n  apply (selsort_sorted (length al) al eq_refl).\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard (selection_sort_is_correct) *)\n\n(** Finish the proof of correctness! *)\n\nTheorem selection_sort_is_correct :\n  is_a_sorting_algorithm selection_sort.\nProof.\n  unfold is_a_sorting_algorithm.\n  intro. split.\n  apply (selsort_perm (length al) al eq_refl).\n  apply selection_sort_sorted.\nQed.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced, optional (selection_sort_is_correct_multiset) *)\n\n(** Uncomment the next line, and prove the correctness of\n    [selection_sort] using multisets instead of permutations.  We\n    haven't tried this yet!  Send us your proof so we can add it as a\n    solution. *)\n\n(* From VFA Require Import Multiset. *)\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Recursive Functions That are Not Structurally Recursive *)\n\n(** We used fuel above to create a structurally recursive\n    version of [selsort] that Coq would accept as terminating.  The\n    amount of fuel decreased at each call, until it reached zero.\n    Since the fuel argument was structurally decreasing, Coq accepted\n    the definition.  But it complicated the implementation of\n    [selsort] and the proofs about it.\n\n    Coq provides an experimental command [Function] that implements a\n    similar idea as fuel, but without requiring the function\n    definition to be structurally recursive.  Instead, the function is\n    annotated with a _measure_ that is decreasing at each recursive\n    call. To activate this experimental command, we need to load a\n    library. *)\n\nRequire Import Recdef.  (* needed for [measure] feature *)\n\n(** Now we can add a [measure] annotation on the definition of\n    [selsort] to tell Coq that each recursive call decreases the\n    length of [l]: *)\n\nFunction selsort' l {measure length l} :=\n  match l with\n  | [] => []\n  | x :: r => let (y, r') := select x r\n            in y :: selsort' r'\nend.\n\n(** The [measure] annotation takes two parameters, a measure\n    function and an argument name.  Above, the function is [length]\n    and the argument is [l].  The function must return a [nat] when\n    applied to the argument.  Coq then challenges us to prove that\n    [length] applied to [l] is actually decreasing at every recursive\n    call. *)\n\nProof.\n  intros.\n  assert (Hperm: Permutation (x :: r) (y :: r')).\n  { apply select_perm. auto. }\n  apply Permutation_length in Hperm.\n  inv Hperm. simpl. lia.\nDefined.\n\n(** The proof must end with [Defined] instead of [Qed].  That\n    ensures the function's body can be used in computation.  For\n    example, the following unit test succeeds, but try changing\n    [Defined] to [Qed] and see how it gets stuck. *)\n\nExample selsort'_example : selsort' [3;1;4;1;5;9;2;6;5] = [1;1;2;3;4;5;5;6;9].\nProof. reflexivity. Qed.\n\n(** The definition of [selsort'] is completed by the [Function]\n    command using a helper function that it generates,\n    [selsort'_terminate].  Neither of them is going to be useful to\n    unfold in proofs: *)\n\nPrint selsort'.\nPrint selsort'_terminate.\n\n(** Instead, anywhere you want to unfold or simplify [selsort'], you\n    should now rewrite with [selsort'_equation], which was\n    automatically defined by the [Function] command: *)\n\nCheck selsort'_equation.\n\n(** **** Exercise: 2 stars, standard (selsort'_perm) *)\n\n(** Hint: Follow the same strategy as [selsort_perm]. In our solution,\n    there was only a one-line change. *)\n\nLemma selsort'_perm : forall n l,\n    length l = n -> Permutation l (selsort' l).\nProof.\n  intro. induction n; intros.\n  (* 0 *) apply length_zero_iff_nil in H. subst. auto.\n  (* S n *)\n  destruct l; simpl in H; inv H.\n  rewrite selsort'_equation.\n  destruct (select n0 l) eqn:E.\n  apply eq_sym in E.\n  apply select_perm in E.\n  apply (Permutation_trans E).\n  constructor.\n  apply IHn.\n  apply Permutation_length in E.\n  inv E. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced, optional (selsort'_correct) *)\n\n(** Prove the correctness of [selsort']. We haven't tried this yet!\n    Send us your proof so we can add it as a solution. *)\n\n(** [] *)\n\n\n\n(* 2021-08-11 15:15 *)\n", "meta": {"author": "luisholanda", "repo": "software-foundations", "sha": "a9c5d7ddb3dca0465dee4ca8519b5de971e482de", "save_path": "github-repos/coq/luisholanda-software-foundations", "path": "github-repos/coq/luisholanda-software-foundations/software-foundations-a9c5d7ddb3dca0465dee4ca8519b5de971e482de/Volume3/Selection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.8807970826714614, "lm_q1q2_score": 0.6940074984680981}}
{"text": "Require Import Aux List Setoid Field VectorSpace.\n\nSection Kn.\n\n(* This is our scalar space with its dimension *)\nVariable p : params.\n(* The operations for scalar have the exprected properties *)\nHypothesis Hp : fparamsProp p.\n\n(* We recover the usual mathematical notation *)\nNotation \"'K'\" := (K p).\n\nDeclare Scope kn_scope.\nDelimit Scope kn_scope with k.\n\nOpen Scope vector_scope.\nOpen Scope kn_scope.\n\n(* A vector is a list of length n *)\n\nFixpoint kn (n: nat): Set := \n  match n with O => unit | S n1 => (K * kn n1)%type end.\n\n(** We first build the functions of the vector space *)\n\n(* Equality of two vectors as list *)\nFixpoint eq (n : nat) : kn n -> kn n -> bool :=\n  match n return (kn n -> kn n -> bool) with\n  | 0%nat => fun a b => true\n  | S n1 =>\n      fun l1 l2 =>\n      let (v1, l3) := l1 in\n      let (v2, l4) := l2 in \n      if (v1 ?= v2)%f then eq n1 l3 l4 else false\n  end.\n\n(* Generate the constant k for the dimension n *)\nFixpoint genk (n: nat) (k: K) {struct n}: (kn n) :=\n   match n return kn n with 0%nat => tt |  \n                            (S n1) => (k, genk n1 k) end.\n\nNotation \" [ k ] \" := (genk _ k) (at level 10): kn_scope.\n\n(* Adding two vectors as list *)\nFixpoint add (n : nat) : kn n -> kn n -> kn n :=\n  match n return (kn n -> kn n -> kn n) with\n  | 0%nat => fun a b => tt\n  | S n1 =>\n      fun l1 l2 =>\n      let (v1, l3) := l1 in\n      let (v2, l4) := l2 in ((v1 + v2)%f, add n1 l3 l4)\n  end.\n\n(* Multiplication by a scalar *)\nFixpoint scal (n : nat) (k: K) {struct n}: kn n -> kn n :=\n  match n return (kn n -> kn n) with\n  | 0%nat => fun a => tt\n  | S n1 =>\n      fun l1 =>\n      let (v1,l2) := l1 in ((k * v1)%f , scal n1 k l2)\n  end.\n\nCanonical Structure vn_eparams (n: nat) :=\n  Build_eparams (kn n) K (genk n 0%f) (eq n) (add n) (scal n).\n\nDefinition fn n : vparamsProp (vn_eparams n).\napply Build_vparamsProp; auto.\n(* eq Dec *)\ninduction n as [| n IH]; simpl.\n  intros [] []; auto.\nintros (v1,l1) (v2, l2); \n  generalize (eqK_dec _ Hp v1 v2); case eqK; intros HH; subst.\n  generalize (IH l1 l2); unfold eqE; simpl.\ncase eq; intros HH; subst; auto.\n  intros HH1; injection HH1; intros; case HH; auto.\nintros HH1; injection HH1; intros; case HH; auto.\n(* assoc *)\ninduction n as [| n IH]; simpl; auto.\nintros (v1,l3) (v2, l4) (v3, l5); simpl in IH; \n rewrite IH, (addK_assoc _ Hp); auto.\n(* comm *)\ninduction n as [| n IH]; simpl; auto.\nintros (v1,l3) (v2, l4); simpl in IH; \n  rewrite (addK_com _ Hp), (IH l3); auto.\n(* 0 is  a left neutral element for + *)\ninduction n as [| n IH]; simpl; auto.\n  intros []; auto.\nintros (l1,l2); simpl in IH; rewrite (addK0l _ Hp), IH; auto.\n(* Multiplication by 0 *)\ninduction n as [| n IH]; simpl; auto.\nintros (l1, l2); simpl in IH; rewrite (multK0l _ Hp), IH; auto.\n(* Multiplication by 1 *)\ninduction n as [| n IH]; simpl.\n  intros []; auto.\nintros (l1, l2); simpl in IH; rewrite (multK1l _ Hp), IH; auto.\n(* Left addition of the multiplication by a scalar *)\ninduction n as [| n IH]; simpl; auto.\nintros k1 k2 (l1, l2); simpl in IH; rewrite (add_multKl _ Hp), IH; auto.\n(* Right addition of the multiplication by a scalar *)\ninduction n as [| n IH]; simpl; auto.\nintros k (l1, l3) (l2, l4); simpl in IH; rewrite (add_multKr _ Hp), IH; auto.\n(* Composition of the multiplication by a scalar *)\ninduction n as [| n IH]; simpl; auto.\nintros k1 k2 (k, x); simpl in IH; rewrite (multK_assoc _ Hp), IH; auto.\nQed.\n\nHint Resolve fn : core.\n\nLtac Kfold n :=\n     change (add n) with (addE (vn_eparams n));\n     change (scal n) with (scalE (vn_eparams n));\n     change (genk n 0%f) with (E0 (vn_eparams n)).\n\n\n(* scal is integral *)\nLemma scal_integral n k (x: kn n) : k .* x = 0 -> k = 0%f \\/ x = 0.\nProof.\ninduction n as [| n IH]; simpl; auto.\n  destruct x; auto.\ndestruct x as (x1, x2); intros HH; injection HH; intros HH1 HH2.\ncase (IH _ _ HH1); case (multK_integral _ Hp k x1); auto.\nintros; right; apply f_equal2 with (f := @pair _ _); auto.\nQed.\n\nLemma genk_inj n k1 k2 : [k1] = [k2] :> kn n.+1 -> k1 = k2.\nProof.\nsimpl; intros HH; injection HH; auto.\nQed.\n\nLemma genk0_dec n (x: kn n) :  x = 0 \\/ x <> 0.\nProof.\ninduction n as [| n IH]; simpl; auto.\ndestruct x; auto.\ndestruct x as (x1, x2).\ncase (IH x2); intros H1; subst; auto.\ngeneralize (eqK_dec _ Hp x1 0%f); case eqK;intros H1; subst; auto.\nright; intro HH; case H1; injection HH; auto.\nright; intro HH; case H1; injection HH; auto.\nQed.\n\n(* Conversion from list to kn *)\nFixpoint l2kn (n:nat) (l:list K) {struct l} : kn n:=\n  match n return kn n with \n  | 0 => tt \n  | S n1 => match l with \n            | nil => genk (S n1) 0%f\n            | a::l1 =>  (a,l2kn n1 l1)\n            end\n  end.\n\nFixpoint kn2l (n : nat) : kn n -> list K :=\n  match n return (kn n -> list K) with\n  | 0 => fun x => nil\n  | S n1 => fun v => let (a, v1) := v in a :: kn2l n1 v1\n  end.\n\nLemma kn2ll2knE n x : l2kn n (kn2l n x) = x.\nProof.\ninduction n as [| n IH]; destruct x; simpl; auto.\nrewrite IH; auto.\nQed.\n\nLemma genk_id0 n i : In i (kn2l n (genk n 0%f)) -> i = 0%f.\nProof.\ninduction n as [| n IH]; simpl;\n  intros HH; case HH; auto.\nQed.\n\nInductive eql_t0 : list K -> list K -> Prop :=\n  eql_t0N: eql_t0 nil nil\n| eql_t0Nl: forall l, eql_t0 l nil -> eql_t0 (0%f :: l) nil\n| eql_t0Nr: forall l, eql_t0 nil l -> eql_t0 nil (0%f :: l) \n| eql_t0R: forall a l1 l2, eql_t0 l1 l2 -> eql_t0 (a :: l1) (a :: l2).\n\nHint Constructors eql_t0 : core.\n\nLemma eql_refl l : eql_t0 l l.\nProof. elim l; auto. Qed.\n\nLemma eql_sym l1 l2 : eql_t0 l1 l2 -> eql_t0 l2 l1.\nProof. intros HH; elim HH; auto.\nQed.\n\nLemma eql_trans l2 l1 l3 : eql_t0 l1 l2 -> eql_t0 l2 l3 -> eql_t0 l1 l3.\nProof.\nintros HH; generalize l3; elim HH; auto; clear l1 l2 l3 HH.\nintros l1 HH IH l3 HH1.\n  generalize (IH _ HH1); inversion_clear HH1; auto.\nintros l1 HH IH l3 HH1.\n  inversion_clear HH1; auto.\nintros a l1 l2 HH IH l3 HH1.\n  inversion_clear HH1; auto.\nQed.\n\nLemma dmap2_eql a l1 l2 l3 :\n  eql_t0 l2 l3 -> \n  eql_t0 (dmap2 (multK K) a l1 l2) (dmap2 (multK K) a l1 l3).\nProof.\nintros HH; generalize l1; elim HH; clear l1 l2 l3 HH; simpl; auto.\nintros [|b l1]; auto.\nintros l2 HH IH [|b l1].\n  rewrite multK0r; auto; apply eql_t0Nl.\n  generalize (IH nil); auto.\n  rewrite multK0r; auto; apply eql_t0Nl.\n  generalize (IH l1); auto; case l1; auto.\nintros l2 HH IH [|b l1].\n  rewrite multK0r; auto; apply eql_t0Nr.\n  generalize (IH nil); auto.\n  rewrite multK0r; auto; apply eql_t0Nr.\n  generalize (IH l1); auto; case l1; auto.\nintros b l2 l3 HH IH [|c l1].\n apply eql_t0R; auto.\n apply eql_t0R; auto.\nQed.\n\nLemma kn2l_0 n : eql_t0 (kn2l n 0) nil.\nProof. elim n; simpl; auto. Qed.\n\n(* Generate the p element of the base in dimension n *)\nFixpoint gen (n: nat) (p: nat) {struct n} : kn n :=\n  match n return kn n with O => tt | S n1 =>\n    match p with\n      0 => (1%f, genk n1 0%f)\n    | S p1 =>  (0%f, gen n1 p1) \n    end\n  end.\n\nNotation \" 'e_ p\" := (gen _ p) (at level 70): kn_scope.\n\nLemma gen_inj n p1 p2 : p1 < n -> p2 < n ->\n  'e_p1 = ('e_p2 : kn n)  -> p1 = p2.\nProof.\ngeneralize p1 p2; clear p1 p2.\ninduction n as [| n IH]; auto.\nintros p1 p2 Hp1; contradict Hp1; auto with arith.\nintros [|p1] [|p2] HH1 HH2; simpl; auto.\nintros HH; injection HH; intros; case (one_diff_zero _ Hp); auto.\nintros HH; injection HH; intros; case (one_diff_zero _ Hp); auto.\nintros HH; rewrite (IH p1 p2); auto with arith.\ninjection HH; auto.\nQed.\n\nLemma kn2l_e0 n : eql_t0 (kn2l n.+1 ('e_0)) (1%f :: nil).\nProof. \nsimpl; auto.\napply eql_t0R.\napply kn2l_0; auto.\nQed.\n\nLemma kn2l_ei n i :\n  eql_t0 (kn2l n.+1 ('e_i.+1))  (0%f :: kn2l n ('e_i)).\nProof.\napply eql_refl.\nQed.\n\n(* Lift a vector of dimension n into a vector of dimension n+1 whose\n   first component is 0 *)\nDefinition lift (n: nat) (v: kn n) : (kn (S n)) :=  (0%f, v).\n\nLemma lift0 n : lift n 0 = 0.\nProof. auto. Qed.\n\n(* Lift of generator of the base *)\nLemma lift_e : forall n i, 'e_(S i) = lift n ('e_i).\nProof. auto. Qed.\n\n(* Lift on add *)\nLemma lift_add n x y : lift n (x + y) = lift n x + lift n y.\nProof. unfold lift; simpl; rewrite addK0l; auto. Qed.\n\n(* Lift on scalar multiplication *)\nLemma lift_scal n k x :  lift n (k .* x) = scalE (vn_eparams (S n)) k (lift n x).\nProof. unfold lift; simpl; rewrite multK0r; auto. Qed.\n\n(* Lift on the multiple product *)\nLemma lift_mprod (n: nat) ks vs : ks *X* map (lift n) vs =\n  lift n (mprod (vn_eparams n) ks vs).\nProof.\ngeneralize vs; clear vs; induction ks as [| k ks IH].\n  intros vs; repeat rewrite mprod0l; auto.\nintros [| v vs]; simpl; try rewrite mprod0r; auto.\nrewrite (mprod_S (vn_eparams n.+1)); auto.\nrewrite mprod_S; auto.\nrewrite IH, lift_add, lift_scal; auto.\nQed.\n\n(* The base as the list of all the generators *)\nFixpoint base (n : nat) : list (kn n) :=\n  match n return list (kn n) with\n  | 0 => nil\n  | S n1 => ('e_0: kn (S n1)) :: map (lift n1) (base n1)\n  end.\n\n(* Each generator is in the base *)\nLemma e_in_base n i : i < n -> In ('e_i) (base n).\nProof.\ngeneralize i; clear i; induction n as [| n IH].\n  intros i HH; contradict HH; auto with arith.\nintros [| p1] Hp1; simpl; Kfold n; auto; right.\nrefine (in_map _ _ _ _); auto with arith.\nQed.\n\n(* An element of the base is a generator *)\nLemma e_in_base_ex n v : \n  In v (base n) -> exists p1, p1 < n /\\ v = 'e_p1.\nProof.\ngeneralize v; clear v; induction n as [| n IH].\n  intros v [].\nsimpl; intros [vv1 vv2] [H1 | H1].\n  exists 0%nat; auto with arith.\nrewrite in_map_iff in H1; case H1.\nintros vv3 [Hvv3 Hvv3'].\ncase (IH _ Hvv3'); intros p1 [Hp1 Hp2].\nexists (S p1); split; auto with arith.\nrewrite <- Hvv3; rewrite Hp2; auto.\nQed.\n\n(* The length of the base is n *)\nLemma base_length n : length (base n) = n.\nProof.\ninduction n as [| n IH]; simpl; auto.\nrewrite map_length; rewrite IH; auto.\nQed.\n\n(* The base is free *)\nLemma base_free n : free _ (base n).\nProof.\n  induction n as [|n IH].\n  *\n     intro. simpl. intros H H0 k H1.\n    assert (ks = nil) by (destruct ks; auto; discriminate).  subst.  inversion H1. \n  * intro. destruct ks as [| k ks].\n  - simpl. intros. discriminate.\n  -\n    intros H1. simpl base. rewrite mprod_S, lift_mprod; auto.\n    simpl. intros HH. injection HH. clear HH.\n    Kfold n.\n    rewrite scalE0r, addE0l, addK0r; auto.\n    intros H2 H3 k1 [Hk1 | Hk1].\n    +\n      case (multK_integral _ Hp _ _ H3); try subst; auto; intros Heq.\n      case (one_diff_zero (vn_eparams n)); auto; apply (vgenk_inj _ _ _ Heq).\n    +\n      injection H1; rewrite map_length; auto.\n      intros Hl; apply (IH ks); auto.\nQed.\n\n\nLemma k2l_mprod n (v: kn n) : kn2l n v *X* base n = v.\nProof.\ngeneralize v; clear v; induction n as [| n IH].\nsimpl; intros []; auto.\nsimpl; intros (x, v).\nrewrite (mprod_S (vn_eparams n.+1)); auto.\nrewrite lift_mprod, IH.\nsimpl; Kfold n; auto.\nKrm1; Vrm0.\nQed.\n\n(* Every vector is a linear combination of the base *)\nLemma cbl_base n v : cbl _ (base n) v.\nProof. rewrite <- (k2l_mprod n v); apply mprod_cbl; auto. Qed.\n\nLemma  kn_induct n (P: kn n -> Prop) :\n     P 0 -> \n     (forall p, p < n -> P ('e_p)) ->\n     (forall v1 v2, P v1 -> P v2 -> P (v1 + v2)) ->\n     (forall k v, P v -> P (k .* v)) ->\n     (forall x, P x).\nProof.\nintros H1 H2 H3 H4 x.\nelim (cbl_base n x); clear x; auto.\nintros v HH; case (e_in_base_ex _ _ HH); intros m (Hl,Hm).\nrewrite Hm; auto with arith.\nQed.\n\n(* Coordinates for k vector *)\nFixpoint proj (n: nat) k : (kn n) -> K :=\n  match n return kn n -> K with \n  | O => fun _ => 0%f\n  | S n1 => fun l => let (a,l1) := l in \n          match k with | O => a | S k1 => \n           proj n1 k1 l1\n          end\n  end.\n\nLemma proj0 n i : proj n i 0 = 0%f.\nProof.\ngeneralize i; clear i.\ninduction n as [| n IH]; intros [|i]; simpl; auto.\nQed.\n\nLemma proj_e n i j : j < n ->\n  proj n i ('e_j) = if (i ?= j)%nat then 1%f else 0%f.\nProof.\ngeneralize i j; clear i j.\ninduction n as [| n IH]; intros [|i] [|j] H; \n  simpl; auto with arith; try (contradict H; auto with arith; fail).\nrewrite proj0; auto.\nQed.\n\nLemma proj_scal n i k x :  proj n i (k .* x) = (k * proj n i x)%f.\nProof.\ngeneralize i x; clear i x.\ninduction n as [| n IH]; simpl; auto.\nKrm0.\nintros [| i] [x1 x2]; auto.\nexact (IH _ i x2).\nQed.\n\nLemma proj_add n i x y : \n proj n i (x + y) = (proj n i x + proj n i y)%f.\nProof.\ngeneralize  i x y; clear i x y.\ninduction n as [| n IH]; simpl; auto.\nintros [| i]; Krm0.\nintros [| i] (x1,x2) (x3,x4); auto.\nexact (IH i x2 x4).\nQed.\n\nFixpoint pscal (n: nat): (kn n) -> (kn n) -> K :=\n  match n return kn n -> kn n -> K with \n  | O => fun a b => 0%f\n  | S n1 => fun l1 l2 => let (a,l3) := l1 in let (b,l4) := l2 in\n                         (a * b + pscal n1 l3 l4)%f\n  end.\n\nNotation \"a  [.]  b\" := (pscal _ a b) (at level 40): kn_scope.\n\nLemma pscal0l n (x: kn n) : 0 [.] x = 0%f.\nProof.\ninduction n as [| n IH]; simpl.\n intros; Krm0.\ndestruct x; rewrite IH; Krm0.\nQed.\n\nLemma pscal0r n (x: kn n) : x [.] 0 = 0%f.\nProof.\ninduction n as [| n IH]; simpl.\n intros; Krm0.\ndestruct x; rewrite IH; Krm0.\nQed.\n\nLemma pscal_com n (x y: kn n) : x [.] y = y [.] x.\nProof.\ninduction n as [| n IH]; simpl.\n intros; Krm0.\ndestruct x; destruct y; rewrite multK_com, IH; auto.\nQed.\n\nLemma pscal_e n (i j: nat) : i < n -> j < n ->\n  ('e_i: kn n) [.] ('e_j) = if (i ?= j)%nat then 1%f else 0%f.\nProof.\ngeneralize i j; clear i j.\ninduction n as [| n IH].\n  intros i j HH; contradict HH; auto with arith.\nintros [|i] [|j] Hi Hj; \n  simpl; auto with arith; \n  try rewrite pscal0l; try rewrite pscal0r; Krm0; Krm1.\napply IH; auto with arith.\nQed.\n\nLemma pscal_scall n k (x y: kn n) :  \n  (k .* x) [.] y = (k * (x [.] y))%f.\nProof.\ninduction n as [| n IH]; simpl; auto; try Kfold n; Krm0.\ndestruct x; destruct y.\nrewrite add_multKr, multK_assoc, IH; auto.\nQed.\n\nLemma pscal_scalr n k (x y: kn n) :  \n  x [.] (k .* y) = (k * (x [.] y))%f.\nProof.\ninduction n as [| n IH]; simpl; auto; try Kfold n; Krm0.\ndestruct x as [a x]; destruct y.\nrewrite add_multKr, <-multK_assoc, (multK_com _ Hp a), multK_assoc, IH; auto.\nQed.\n\nLemma pscal_addl n (x y z: kn n) :  \n  (x + y) [.] z = (x [.] z + (y [.] z))%f.\nProof.\ninduction n as [| n IH]; simpl; auto; try Kfold n; Krm0.\ndestruct x; destruct y as [b y]; destruct z as [c z].\nrewrite add_multKl, IH; auto.\nrewrite !addK_assoc; auto.\nrewrite <-(addK_assoc _ Hp (b * c)%f), (addK_com _ Hp (b * c)%f),\n        !addK_assoc; auto.\nQed.\n\nLemma pscal_addr n (x y z: kn n) :  \n  z [.] (x + y) = (z [.] x + (z [.] y))%f.\nProof.\ninduction n as [| n IH]; simpl; auto; try Kfold n; Krm0.\ndestruct x; destruct y as [b y]; destruct z as [c z].\nrewrite add_multKr, IH; auto.\nrewrite !addK_assoc; auto.\nrewrite <-(addK_assoc _ Hp (c * b)%f), (addK_com _ Hp (c * b)%f),\n        !addK_assoc; auto.\nQed.\n\n(* Our final vector *)\nDefinition Kn := kn p.\nDefinition K0 := genk p 0%f.\nDefinition Keq: Kn -> Kn -> bool := eq p.\nDefinition Kadd: Kn -> Kn -> Kn := add p.\nDefinition Kscal: K -> Kn -> Kn := scal p.\nDefinition Kproj: nat -> Kn -> K := proj p.\nDefinition Ksprod: Kn -> Kn -> K := pscal p.\nDefinition Kgen := gen p.\n\nCanonical Structure v_eparams :=\n  Build_eparams Kn K K0 Keq Kadd Kscal.\nDefinition f : vparamsProp v_eparams := fn p.\n\n(* Prod of two vectors as list *)\nFixpoint kprod (n : nat) : kn n -> kn n -> kn n :=\n  match n with\n  | 0%nat => fun a b => tt\n  | S n1 =>\n      fun l1 l2 =>\n      let (v1, l3) := l1 in\n      let (v2, l4) := l2 in ((v1 * v2)%f, kprod n1 l3 l4)\n  end.\n\nLocal Notation \"a  [*]  b\" := (kprod _ a b) (at level 40).\n\nLemma kprod0l n a : 0 [*] a = 0 :> kn n.\nProof.\ninduction n as [|n IH]; simpl; auto.\ndestruct a; simpl; rewrite IH; Krm0.\nQed.\n\nLemma kprod0r n a : a [*] 0 = 0 :> kn n.\nProof.\ninduction n as [|n IH]; simpl; auto.\ndestruct a; simpl; rewrite IH; Krm0.\nQed.\n\nLemma kprodkl n k a : [k] [*] a = k .* a :> kn n.\nProof.\ninduction n as [|n IH]; destruct a; simpl; auto.\nrewrite IH; Krm1.\nQed.\n\nLemma kprodkr n k a : a [*] [k] = k .* a :> kn n.\nProof.\ninduction n as [|n IH]; destruct a; simpl; auto.\nrewrite IH, multK_com; Krm1.\nQed.\n\nLemma kprod1l n a : [1%f] [*] a = a :> kn n.\nProof.\nrewrite kprodkl, scalE1; auto.\nQed.\n\nLemma kprod1r n a : a [*] [1%f] = a :> kn n.\nProof.\nrewrite kprodkr, scalE1; auto.\nQed.\n\nLemma kprod_addl n a b c : \n  (a + b) [*] c = a [*] c + b [*] c :> kn n.\nProof.\ninduction n as [|n IH]; simpl; auto.\ndestruct a; destruct b; destruct c; simpl.\nKfold n; rewrite IH, add_multKl; Krm0.\nQed.\n\nLemma kprod_addr n a b c : \n  a [*] (b + c) = a [*] b + a [*] c :> kn n.\nProof.\ninduction n as [|n IH]; simpl; auto.\ndestruct a; destruct b; destruct c; simpl.\nKfold n; rewrite IH, add_multKr; Krm0.\nQed.\n\nLemma kprod_scall n k a b : \n  (k .* a) [*] b = k .* (a [*] b) :> kn n.\nProof.\ninduction n as [|n IH]; simpl; auto.\ndestruct a; destruct b; simpl.\nKfold n; rewrite IH, multK_assoc; Krm0.\nQed.\n\nLemma kprod_scalr n k a b : \n  a [*] (k .* b) = k .* (a [*] b) :> kn n.\nProof.\ninduction n as [|n IH]; simpl; auto.\ndestruct a; destruct b; simpl.\nKfold n; rewrite IH, multK_swap; Krm0.\nQed.\n\nLemma kprod_assoc n a b c : \n  (a [*] b) [*] c = a [*] (b [*] c) :> kn n.\nProof.\ninduction n as [|n IH]; simpl; auto.\ndestruct a; destruct b; destruct c; simpl.\nKfold n; rewrite IH, multK_assoc; Krm0.\nQed.\n\nEnd Kn.\n\nDeclare Scope Kn_scope.\n\nNotation \" 'e_ p\" := (gen _ _ p) (at level 8) : Kn_scope.\nNotation \" [ k ] \" := (genk _ _ k) (at level 9) : Kn_scope.\nNotation \"a  [.]  b\" := (pscal _ _ a b) (at level 40): Kn_scope.\nNotation \"a  [*]  b\" := (kprod _ _ a b) (at level 40): Kn_scope.\n\nDelimit Scope Kn_scope with Kn.\n\nGlobal Hint Constructors eql_t0 : core.\n", "meta": {"author": "olivierverdier", "repo": "GeometricAlgebra", "sha": "86105900b5c3e58e7b117f714037b173a9cdcc75", "save_path": "github-repos/coq/olivierverdier-GeometricAlgebra", "path": "github-repos/coq/olivierverdier-GeometricAlgebra/GeometricAlgebra-86105900b5c3e58e7b117f714037b173a9cdcc75/Kn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.6940074928491325}}
{"text": "Require Export Arith.\nRequire Export ArithRing.\nRequire Export Omega.\nRequire Export fib_ind.\n \nFixpoint exp2 (n : nat) : nat :=\n match n with 0 => 1 | S p => 2 * exp2 p end.\n\n(** An induction principle adapted to division by two *)\n\nTheorem div2_rect:\n forall (P : nat ->  Type),\n P 0 -> P 1 -> (forall n, P n ->  P (S (S n))) -> forall (n : nat),  P n.\nProof.\nintros P X0 X1 Xrec n; assert (P n * P (S n))%type.\n - elim n; intuition.\n - intuition.\nDefined.\n \nTheorem div2_spec:\n forall n,  ({x : nat | 2 * x = n}) + ({x : nat | 2 * x + 1 = n}).\nProof. \n  intros n; induction  n  as [ | | n Hrec] using div2_rect.\n  - left; now exists 0.\n  - right; now exists 0.\n  - destruct Hrec as  [[x Heq]|[x Heq]].\n     + left; exists (S x); rewrite <- Heq; ring.\n     + right; exists (S x); rewrite <- Heq; ring.\nQed.\n \nTheorem half_smaller0: forall n x, 2 * x = S n ->  (x < S n).\nProof.\n intros; omega.\nQed.\n \nTheorem half_smaller1: forall n x, 2 * x + 1 = n ->  (x < n).\nProof.\n intros; omega.\nQed.\n \nDefinition log2_F:\n  forall (n : nat),\n    (forall (y : nat),\n        y < n -> y <> 0 ->  ({p : nat | exp2 p <= y /\\ y < exp2 (p + 1)})) ->\n    n <> 0 ->  ({p : nat | exp2 p <= n /\\ n < exp2 (p + 1)}).\nProof. \n  intros n; case n.\n  - intros log2 Hn0; elim Hn0; trivial.\n  - intros n' log2 _; elim (div2_spec (S n')).\n    + intros [x]; case_eq x.\n      * simpl; intros. subst; discriminate.\n      * intros x' Heqx'; assert (Hn0: S x' <> 0) by auto with arith.\n        subst x;  destruct (log2 (S x') (half_smaller0 _ _ e) Hn0) as [v Heqv].\n        exists (S v); simpl;rewrite <- e;omega.\n    + intros [x].  destruct x; simpl.\n      *  rewrite <- e.  exists 0; simpl; auto with arith.\n      * rewrite <- e. \n        assert (Hn0: S x <> 0) by auto with arith.\n        destruct (log2 (S x)) as [a Ha];[ omega | auto | ].\n        exists (S a).  simpl.  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/log2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.6940074810664711}}
{"text": "Require Export Arith NPeano.\n\nDefinition point := prod nat nat.\nBind Scope point_scope with point.\nDelimit Scope point_scope with point.\nDefinition pt_x : point -> nat := @fst _ _.\nDefinition pt_y : point -> nat := @snd _ _.\nDefinition Build_point : nat -> nat -> point := pair.\nOpaque point pt_x pt_y Build_point.\nNotation \"( x , y , .. , z )\" := (Build_point .. (Build_point x y) .. z) : point_scope.\n\nNotation \"p '.(x)'\" := (pt_x p) (at level 5, no associativity).\nNotation \"p '.(y)'\" := (pt_y p) (at level 5, no associativity).\n\nSection distance.\n  Definition abs_minus (x y : nat) :=\n    if le_dec x y then y - x else x - y.\n  Local Infix \"-\" := abs_minus.\n\n  Definition square_distance (x1 y1 x2 y2 : nat) := (x1 - x2)^2 + (y1 - y2)^2.\nEnd distance.\n\nDefinition point_square_distance (p1 p2 : point) := square_distance p1.(x) p1.(y) p2.(x) p2.(y).\n\nNotation \"∥ p1 -- p2 ∥²\" := (point_square_distance p1 p2) : nat_scope.\n", "meta": {"author": "JasonGross", "repo": "ClosestPoints", "sha": "e8b3c06efa442523ff9e7da198da94f9f05b3593", "save_path": "github-repos/coq/JasonGross-ClosestPoints", "path": "github-repos/coq/JasonGross-ClosestPoints/ClosestPoints-e8b3c06efa442523ff9e7da198da94f9f05b3593/Point/NatPointCore2D.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6939809804683335}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(**********************************************************************\n    EGroup.v\n\n    Given an element a, create the group {e, a, a^2, ..., a^n}\n **********************************************************************)\nRequire Import ZArith.\nRequire Import Tactic.\nRequire Import List.\nRequire Import ZCAux.\nRequire Import ZArith Znumtheory.\nRequire Import Wf_nat.\nRequire Import UList.\nRequire Import FGroup.\nRequire Import Lagrange.\n\nOpen Scope Z_scope.\n\nSection EGroup.\n\nVariable A: Set.\n\nVariable A_dec: forall a b: A, {a = b} + {~ a = b}.\n\nVariable op: A -> A -> A.\n\nVariable a: A.\n\nVariable G: FGroup op.\n\nHypothesis a_in_G: In a G.(s).\n\n\n(**************************************\n  The power function for the group\n **************************************)\n\nSet Implicit Arguments.\nDefinition gpow n := match n with  Zpos p => iter_pos _ (op a) G.(e) p | _ => G.(e) end.\nUnset Implicit Arguments.\n\nTheorem gpow_0: gpow 0 = G.(e).\nsimpl; sauto.\nQed.\n\nTheorem gpow_1 : gpow 1 = a.\nsimpl; sauto.\nQed.\n\n(**************************************\n  Some properties of the power function\n **************************************)\n\nTheorem gpow_in: forall n, In (gpow n) G.(s).\nintros n; case n; simpl; auto.\nintros p; apply iter_pos_invariant with (Inv := fun x => In x G.(s)); auto.\nQed.\n\nTheorem gpow_op: forall b p, In b G.(s) -> iter_pos _ (op a) b p = op (iter_pos _ (op a) G.(e) p) b.\nintros b p; generalize b; elim p; simpl; auto; clear  b p.\nintros p Rec b Hb.\nassert (H: In (gpow (Zpos p)) G.(s)).\napply gpow_in.\nrewrite (Rec b); try rewrite (fun x y => Rec (op x y)); try rewrite (fun x y => Rec (iter_pos A x y p)); auto.\nrepeat rewrite G.(assoc); auto.\nintros p Rec b Hb.\nassert (H: In (gpow (Zpos p)) G.(s)).\napply gpow_in.\nrewrite (Rec b); try rewrite (fun x y => Rec (op x y)); try rewrite (fun x y => Rec (iter_pos A x y p)); auto.\nrepeat rewrite G.(assoc); auto.\nintros b H; rewrite e_is_zero_r; auto.\nQed.\n\nTheorem gpow_add: forall n m, 0 <= n -> 0 <= m -> gpow (n + m) = op (gpow n) (gpow m).\nintros n; case n.\nintros m _ _; simpl; apply sym_equal; apply e_is_zero_l; apply gpow_in.\n2: intros p m H; contradict H; auto with zarith.\nintros p1 m; case m.\nintros _ _; simpl; apply sym_equal; apply e_is_zero_r.\nexact (gpow_in (Zpos p1)).\n2: intros p2 _ H; contradict H; auto with zarith.\nintros p2 _ _; simpl.\nrewrite iter_pos_plus; rewrite (fun x y => gpow_op (iter_pos A x y p2)); auto.\nexact (gpow_in (Zpos p2)).\nQed.\n\nTheorem gpow_1_more:\n  forall n, 0 < n -> gpow n = G.(e) -> forall m, 0 <= m -> exists p, 0 <= p < n /\\ gpow m = gpow p.\nintros n H1 H2 m Hm;  generalize Hm; pattern m; apply Z_lt_induction; auto with zarith; clear m Hm.\nintros m Rec Hm.\ncase (Zle_or_lt n m); intros H3.\ncase (Rec (m - n)); auto with zarith.\nintros p (H4,H5); exists p; split; auto.\nreplace m with (n + (m - n)); auto with zarith.\nrewrite gpow_add; try rewrite H2; try rewrite H5; sauto; auto with zarith.\ngeneralize gpow_in; sauto.\nexists m; auto.\nQed.\n\nTheorem gpow_i: forall n m, 0 <= n -> 0 <= m -> gpow n = gpow (n + m) -> gpow m = G.(e).\nintros n m H1 H2 H3; generalize gpow_in; intro PI.\napply g_cancel_l with (g:= G) (a := gpow n); sauto.\nrewrite <- gpow_add; try rewrite <- H3; sauto.\nQed.\n\n(**************************************\n  We build the support by iterating the power function\n **************************************)\n\nSet Implicit Arguments.\n\nFixpoint support_aux (b: A) (n: nat) {struct n}: list A :=\nb::let c := op a b in\n    match n with\n       O => nil |\n      (S n1) =>if A_dec c G.(e) then nil else  support_aux c n1\n    end.\n\nDefinition support := support_aux G.(e) (Z.abs_nat (g_order G)).\n\nUnset Implicit Arguments.\n\n(**************************************\n  Some properties of the support that helps to prove that we have a group\n **************************************)\n\nTheorem support_aux_gpow:\n  forall n m b, 0 <=  m -> In b (support_aux (gpow m) n) ->\n        exists p, (0 <= p < length (support_aux (gpow m) n))%nat  /\\ b = gpow (m + Z_of_nat p).\nintros n; elim n; simpl.\nintros n1 b Hm [H1 | H1]; exists 0%nat; simpl; rewrite Zplus_0_r; auto; case H1.\nintros n1 Rec m b Hm [H1 | H1].\nexists 0%nat; simpl; rewrite Zplus_0_r; auto; auto with arith.\ngeneralize H1; case (A_dec (op a (gpow m)) G.(e)); clear H1; simpl; intros H1 H2.\ncase H2.\ncase (Rec (1 + m) b); auto with zarith.\nrewrite gpow_add; auto with zarith.\nrewrite gpow_1; auto.\nintros p (Hp1, Hp2); exists (S p); split; auto with zarith.\nrewrite <- gpow_1.\nrewrite <- gpow_add; auto with zarith.\nrewrite inj_S; rewrite Hp2; eq_tac; auto with zarith.\nQed.\n\nTheorem gpow_support_aux_not_e:\n  forall n m p, 0 <= m -> m < p < m + Z_of_nat (length (support_aux (gpow m) n)) -> gpow p <> G.(e).\nintros n; elim n; simpl.\nintros m p Hm (H1, H2); contradict H2; auto with zarith.\nintros n1 Rec m p Hm; case (A_dec (op a (gpow m)) G.(e)); simpl.\nintros _ (H1, H2); contradict H2; auto with zarith.\nassert (tmp: forall p, Zpos (P_of_succ_nat p) = 1 + Z_of_nat p).\nintros p1; apply trans_equal with (Z_of_nat (S p1)); auto; rewrite inj_S; auto with zarith.\nrewrite tmp.\nintros H1 (H2, H3); case (Zle_lt_or_eq (1 + m) p); auto with zarith; intros H4; subst.\napply (Rec (1 + m)); try split; auto with zarith.\nrewrite gpow_add; auto with zarith.\nrewrite gpow_1; auto with zarith.\nrewrite gpow_add; try rewrite gpow_1; auto with zarith.\nQed.\n\nTheorem support_aux_not_e: forall n m b, 0 <= m -> In b (tail (support_aux (gpow m) n)) -> ~ b = G.(e).\nintros n; elim n; simpl.\nintros m b Hm H; case H.\nintros n1 Rec m b Hm; case (A_dec (op a (gpow m)) G.(e)); intros H1 H2; simpl; auto.\nassert (Hm1: 0 <= 1 + m); auto with zarith.\ngeneralize( Rec (1 + m) b Hm1) H2; case n1; auto; clear Hm1.\nintros _ [H3 | H3]; auto.\ncontradict H1; subst; auto.\nrewrite gpow_add; simpl; try rewrite e_is_zero_r; auto with zarith.\nintros n2; case (A_dec (op a (op a (gpow m))) G.(e)); intros H3.\nintros _ [H4 | H4].\ncontradict H1; subst; auto.\ncase H4.\nintros H4 [H5 | H5]; subst; auto.\nQed.\n\nTheorem support_aux_length_le: forall n a, (length (support_aux a n) <= n + 1)%nat.\nintros n; elim n; simpl; auto.\nintros n1 Rec a1; case (A_dec (op a a1) G.(e)); simpl; auto with arith.\nQed.\n\nTheorem support_aux_length_le_is_e:\n   forall n m, 0 <= m ->  (length (support_aux (gpow m) n) <= n)%nat ->\n      gpow (m + Z_of_nat (length (support_aux (gpow m) n))) = G.(e) .\nintros n; elim n; simpl; auto.\nintros m _ H1; contradict H1; auto with arith.\nintros n1 Rec m Hm; case (A_dec (op a (gpow m)) G.(e)); simpl;  intros H1.\nintros H2; rewrite Zplus_comm; rewrite gpow_add; simpl; try rewrite e_is_zero_r; auto with zarith.\nassert (tmp: forall p, Zpos (P_of_succ_nat p) = 1 + Z_of_nat p).\nintros p1; apply trans_equal with (Z_of_nat (S p1)); auto; rewrite inj_S; auto with zarith.\nrewrite tmp; clear tmp.\nrewrite <- gpow_1.\nrewrite <- gpow_add; auto with zarith.\nrewrite  Zplus_assoc; rewrite (Zplus_comm 1); intros H2; apply Rec; auto with zarith.\nQed.\n\nTheorem support_aux_in:\n  forall n m p, 0 <= m ->  (p < length (support_aux (gpow m) n))% nat ->\n            (In (gpow (m + Z_of_nat p)) (support_aux (gpow m) n)).\nintros n; elim n; simpl; auto; clear n.\nintros m p Hm H1; replace p with 0%nat.\nleft; eq_tac; auto with zarith.\ngeneralize H1; case p; simpl; auto with arith.\nintros n H2; contradict H2; apply Nat.le_ngt; auto with arith.\nintros n1 Rec m p Hm; case (A_dec (op a (gpow m)) G.(e)); simpl; intros H1 H2; auto.\nreplace p with 0%nat.\nleft; eq_tac; auto with zarith.\ngeneralize H2; case p; simpl; auto with arith.\nintros n H3; contradict H3; apply Nat.le_ngt; auto with arith.\ngeneralize H2; case p; simpl; clear H2.\nrewrite Zplus_0_r; auto.\nintros n.\nassert (tmp: forall p, Zpos (P_of_succ_nat p) = 1 + Z_of_nat p).\nintros p1; apply trans_equal with (Z_of_nat (S p1)); auto; rewrite inj_S; auto with zarith.\nrewrite tmp; clear tmp.\nrewrite <- gpow_1; rewrite <- gpow_add; auto with zarith.\nrewrite  Zplus_assoc; rewrite (Zplus_comm 1); intros H2; right; apply Rec; auto with zarith.\nQed.\n\nTheorem support_aux_ulist:\n  forall n m, 0 <= m -> (forall p, 0 <= p < m -> gpow (1 + p) <> G.(e)) -> ulist (support_aux (gpow m) n).\nintros n; elim n; auto; clear n.\nintros m _ _; auto.\nsimpl; apply ulist_cons; auto.\nintros n1 Rec m Hm H.\nsimpl; case (A_dec (op a (gpow m)) G.(e)); auto.\nintros He; apply ulist_cons; auto.\nintros H1; case  (support_aux_gpow n1 (1 + m) (gpow m)); auto with zarith.\nrewrite gpow_add; try rewrite gpow_1; auto with zarith.\nintros p (Hp1, Hp2).\nassert (H2: gpow (1 + Z_of_nat p) = G.(e)).\napply gpow_i with m; auto with zarith.\nrewrite Hp2; eq_tac; auto with zarith.\ncase (Zle_or_lt m  (Z_of_nat p)); intros H3; auto.\n2: case (H (Z_of_nat p)); auto with zarith.\ncase (support_aux_not_e (S n1) m (gpow (1 + Z_of_nat p))); auto.\nrewrite gpow_add; auto with zarith; simpl; rewrite e_is_zero_r; auto.\ncase (A_dec (op a (gpow m)) G.(e)); auto.\nintros _; rewrite <- gpow_1; repeat rewrite <- gpow_add; auto with zarith.\nreplace (1 + Z_of_nat p) with ((1 + m) + (Z_of_nat (p - Z.abs_nat m))).\napply support_aux_in; auto with zarith.\nrewrite inj_minus1.\nrewrite inj_Zabs_nat.\nrewrite Z.abs_eq; auto with zarith.\napply inj_le_rev.\nrewrite inj_Zabs_nat.\nrewrite Z.abs_eq; auto with zarith.\nrewrite <- gpow_1; repeat rewrite <- gpow_add; auto with zarith.\napply (Rec (1 + m)); auto with zarith.\nintros p H1; case (Zle_lt_or_eq p m); intros; subst; auto with zarith.\nrewrite  gpow_add; auto with zarith.\nrewrite gpow_1; auto.\nQed.\n\nTheorem support_gpow: forall b, (In b support) -> exists p, 0 <= p < Z_of_nat (length support) /\\ b = gpow p.\nintros b H; case (support_aux_gpow  (Z.abs_nat (g_order G)) 0 b); auto with zarith.\nintros p ((H1, H2), H3); exists (Z_of_nat p); repeat split; auto with zarith.\napply inj_lt; auto.\nQed.\n\nTheorem support_incl_G: incl support G.(s).\nintros a1 H; case (support_gpow a1); auto; intros p (H1, H2); subst; apply gpow_in.\nQed.\n\nTheorem gpow_support_not_e: forall p, 0 < p < Z_of_nat (length support) -> gpow p <> G.(e).\nintros p (H1, H2); apply gpow_support_aux_not_e with (m := 0) (n := length G.(s)); simpl;\n  try split; auto with zarith.\nrewrite  <- (Zabs_nat_Z_of_nat (length G.(s))); auto.\nQed.\n\nTheorem support_not_e: forall b, In b (tail support) -> ~ b = G.(e).\nintros b H; apply (support_aux_not_e (Z.abs_nat (g_order G)) 0); auto with zarith.\nQed.\n\nTheorem support_ulist:  ulist support.\napply (support_aux_ulist (Z.abs_nat (g_order G)) 0); auto with zarith.\nQed.\n\nTheorem support_in_e:  In G.(e) support.\nunfold support; case (Z.abs_nat (g_order G)); simpl; auto with zarith.\nQed.\n\nTheorem gpow_length_support_is_e: gpow (Z_of_nat (length support)) = G.(e).\napply (support_aux_length_le_is_e (Z.abs_nat (g_order G)) 0); simpl; auto with zarith.\nunfold g_order; rewrite Zabs_nat_Z_of_nat; apply ulist_incl_length.\nrewrite  <- (Zabs_nat_Z_of_nat (length G.(s))); auto.\nexact support_ulist.\nrewrite  <- (Zabs_nat_Z_of_nat (length G.(s))); auto.\nexact support_incl_G.\nQed.\n\nTheorem support_in:  forall p, 0 <= p < Z_of_nat (length support) ->  In (gpow p) support.\nintros p (H, H1); unfold support.\nrewrite <-  (Z.abs_eq p); auto with zarith.\nrewrite <-  (inj_Zabs_nat p); auto.\ngeneralize (support_aux_in (Z.abs_nat (g_order G)) 0); simpl; intros H2; apply H2; auto with zarith.\nrewrite <-  (fun x => Zabs_nat_Z_of_nat (@length A x)); auto.\napply Zabs_nat_lt; split; auto.\nQed.\n\nTheorem support_internal: forall a b, In a support -> In b support -> In (op a b) support.\nintros a1 b1 H1 H2.\ncase support_gpow with (1 := H1); auto; intros p1 ((H3, H4), H5); subst.\ncase support_gpow with (1 := H2); auto; intros p2 ((H5, H6), H7); subst.\nrewrite <- gpow_add; auto with zarith.\ncase gpow_1_more with (m:= p1 + p2)   (2 := gpow_length_support_is_e); auto with zarith.\nintros p3 ((H8, H9), H10); rewrite H10; apply support_in; auto with zarith.\nQed.\n\nTheorem support_i_internal: forall a, In a support -> In (G.(i) a) support.\ngeneralize gpow_in; intros Hp.\nintros a1 H1.\ncase support_gpow with (1 := H1); auto.\nintros p1 ((H2, H3), H4); case Zle_lt_or_eq with (1 := H2); clear H2; intros H2; subst.\n2: rewrite gpow_0; rewrite i_e; apply support_in_e.\nreplace (G.(i) (gpow p1)) with (gpow (Z_of_nat (length support - Z.abs_nat p1))).\napply support_in.\nrewrite inj_minus1.\nrewrite inj_Zabs_nat.\nrewrite Z.abs_eq; auto with zarith.\napply inj_le_rev; rewrite inj_Zabs_nat.\nrewrite Z.abs_eq; auto with zarith.\napply g_cancel_l with (g:= G) (a := gpow p1); sauto.\nrewrite <- gpow_add; auto with zarith.\nreplace (p1 + Z_of_nat (length support - Z.abs_nat p1)) with (Z_of_nat (length support)).\nrewrite gpow_length_support_is_e; sauto.\nrewrite inj_minus1.\nrewrite inj_Zabs_nat.\nrewrite Z.abs_eq; auto with zarith.\napply inj_le_rev; rewrite inj_Zabs_nat.\nrewrite Z.abs_eq; auto with zarith.\nQed.\n\n(**************************************\n  We are now ready to build the group\n **************************************)\n\nDefinition Gsupport: (FGroup op).\ngeneralize support_incl_G; unfold incl; intros Ho.\napply mkGroup with support G.(e) G.(i); sauto.\napply support_ulist.\napply support_internal.\nintros a1 b1 c1 H1 H2 H3; apply G.(assoc); sauto.\napply support_in_e.\napply support_i_internal.\nDefined.\n\n(**************************************\n  Definition of the order of an element\n **************************************)\nSet Implicit Arguments.\n\nDefinition e_order := Z_of_nat (length support).\n\nUnset Implicit Arguments.\n\n(**************************************\n Some properties of the order of an element\n **************************************)\n\nTheorem gpow_e_order_is_e: gpow e_order = G.(e).\napply (support_aux_length_le_is_e (Z.abs_nat (g_order G)) 0); simpl; auto with zarith.\nunfold g_order; rewrite Zabs_nat_Z_of_nat; apply ulist_incl_length.\nrewrite  <- (Zabs_nat_Z_of_nat (length G.(s))); auto.\nexact support_ulist.\nrewrite  <- (Zabs_nat_Z_of_nat (length G.(s))); auto.\nexact support_incl_G.\nQed.\n\nTheorem gpow_e_order_lt_is_not_e: forall n, 1 <= n < e_order -> gpow n <> G.(e).\nintros n (H1, H2); apply gpow_support_not_e; auto with zarith.\nQed.\n\nTheorem e_order_divide_g_order:  (e_order | g_order G).\nchange ((g_order Gsupport) | g_order G).\napply lagrange; auto.\nexact support_incl_G.\nQed.\n\nTheorem e_order_pos: 0 < e_order.\nunfold e_order, support; case (Z.abs_nat (g_order G)); simpl; auto with zarith.\nQed.\n\nTheorem e_order_divide_gpow: forall n, 0 <= n -> gpow n = G.(e) -> (e_order | n).\ngeneralize gpow_in; intros Hp.\ngeneralize e_order_pos; intros Hp1.\nintros n Hn; generalize Hn; pattern n; apply Z_lt_induction; auto; clear n Hn.\nintros n Rec Hn H.\ncase (Zle_or_lt  e_order n); intros H1.\ncase (Rec (n - e_order)); auto with zarith.\napply g_cancel_l with (g:= G) (a := gpow e_order); sauto.\nrewrite G.(e_is_zero_r); auto with zarith.\nrewrite <- gpow_add; try (rewrite gpow_e_order_is_e; rewrite <- H; eq_tac); auto with zarith.\nintros k Hk; exists (1 + k).\nrewrite Zmult_plus_distr_l; rewrite <- Hk; auto with zarith.\ncase (Zle_lt_or_eq 0 n); auto with arith; intros H2; subst.\ncontradict H; apply support_not_e.\ngeneralize H1; unfold e_order, support.\ncase (Z.abs_nat (g_order G)); simpl; auto.\nintros H3; contradict H3; auto with zarith.\nintros n1; case (A_dec (op a G.(e)) G.(e)); simpl; intros _ H3.\ncontradict H3; auto with zarith.\ngeneralize H3; clear H3.\nassert (tmp: forall p, Zpos (P_of_succ_nat p) = 1 + Z_of_nat p).\nintros p1; apply trans_equal with (Z_of_nat (S p1)); auto; rewrite inj_S; auto with zarith.\nrewrite tmp; clear tmp; intros H3.\nchange (In (gpow n) (support_aux (gpow 1) n1)).\nreplace n with (1 + Z_of_nat (Z.abs_nat n - 1)).\napply support_aux_in; auto with zarith.\nrewrite <- (fun x => Zabs_nat_Z_of_nat (@length A x)).\nreplace (Z.abs_nat n - 1)%nat  with (Z.abs_nat (n - 1)).\napply Zabs_nat_lt; split; auto with zarith.\nrewrite G.(e_is_zero_r) in H3; try rewrite gpow_1; auto with zarith.\napply inj_eq_rev; rewrite inj_Zabs_nat.\nrewrite Z.abs_eq by auto with zarith.\nrewrite inj_minus1.\nrewrite inj_Zabs_nat.\nrewrite Z.abs_eq; auto with zarith.\napply inj_le_rev; rewrite inj_Zabs_nat; simpl.\nrewrite Z.abs_eq; auto with zarith.\nrewrite inj_minus1.\nrewrite inj_Zabs_nat.\nrewrite Z.abs_eq.\nrewrite Zplus_comm; simpl; auto with zarith.\nauto with zarith.\napply inj_le_rev; rewrite inj_Zabs_nat; simpl.\nrewrite Z.abs_eq; auto with zarith.\nexists 0; auto with arith.\nQed.\n\nEnd EGroup.\n\nTheorem gpow_gpow: forall (A : Set) (op : A -> A -> A) (a : A) (G : FGroup op),\n       In a (s G) -> forall n m, 0 <= n -> 0 <= m -> gpow a G (n * m ) = gpow (gpow a G n) G m.\nintros A op a G H n m; case n.\nsimpl; intros _ H1; generalize H1.\npattern m; apply natlike_ind; simpl; auto.\nintros x H2 Rec _; unfold Z.succ; rewrite gpow_add; simpl; auto with zarith.\nrepeat rewrite G.(e_is_zero_r); auto with zarith.\napply gpow_in; sauto.\nintros p1 _; case m; simpl; auto.\nassert(H1: In (iter_pos A (op a) (e G) p1) (s G)).\nrefine (gpow_in _ _ _ _ _ (Zpos p1)); auto.\nintros p2 _;  pattern p2; apply Pind; simpl; auto.\nrewrite Pmult_1_r; rewrite G.(e_is_zero_r); try rewrite G.(e_is_zero_r); auto.\nintros p3 Rec; rewrite Pplus_one_succ_r; rewrite Pmult_plus_distr_l.\nrewrite Pmult_1_r.\nsimpl; repeat rewrite iter_pos_plus; simpl.\nrewrite G.(e_is_zero_r); auto.\nrewrite gpow_op with (G:= G); try rewrite Rec; auto.\napply sym_equal; apply gpow_op; auto.\nintros p Hp; contradict Hp; auto with zarith.\nQed.\n\nTheorem gpow_e: forall (A : Set) (op : A -> A -> A) (G : FGroup op) n, 0 <= n -> gpow G.(e) G n = G.(e).\nintros A op G n; case n; simpl; auto with zarith.\nintros p _; elim p; simpl; auto; intros p1 Rec; repeat rewrite Rec; auto.\nQed.\n\nTheorem gpow_pow: forall (A : Set) (op : A -> A -> A) (a : A) (G : FGroup op),\n       In a (s G) -> forall n, 0 <= n -> gpow a G (2 ^ n) = G.(e) -> forall m, n <= m -> gpow a G (2 ^ m) = G.(e).\nintros A op a G H n H1 H2 m Hm.\nreplace m with (n + (m - n)); auto with zarith.\nrewrite Zpower_exp; auto with zarith.\nrewrite gpow_gpow; auto with zarith.\nrewrite H2; apply gpow_e.\napply Zpower_ge_0; auto with zarith.\nQed.\n\nTheorem gpow_mult: forall (A : Set) (op : A -> A -> A) (a b: A) (G : FGroup op)\n       (comm: forall a b,  In a (s G) -> In b (s G) -> op a b = op b a),\n       In a (s G) -> In b (s G) -> forall n, 0 <= n -> gpow (op a b) G n = op (gpow a G n) (gpow b G n).\nintros A op a  b G comm Ha Hb n; case n; simpl; auto.\nintros _; rewrite G.(e_is_zero_r); auto.\n2: intros p Hp; contradict Hp; auto with zarith.\nintros p _; pattern p; apply Pind; simpl; auto.\nrepeat rewrite G.(e_is_zero_r); auto.\nintros p3 Rec; rewrite Pplus_one_succ_r.\nrepeat rewrite iter_pos_plus; simpl.\nrepeat rewrite (fun x y H z => gpow_op A  op x G H (op y z)) ; auto.\nrewrite Rec.\nrepeat rewrite G.(e_is_zero_r); auto.\nassert(H1: In (iter_pos A (op a) (e G) p3) (s G)).\nrefine (gpow_in _ _ _ _ _ (Zpos p3)); auto.\nassert(H2: In (iter_pos A (op b) (e G) p3) (s G)).\nrefine (gpow_in _ _ _ _ _ (Zpos p3)); auto.\nrepeat rewrite <- G.(assoc); try eq_tac; auto.\nrewrite (fun x y => comm (iter_pos A x y p3) b); auto.\nrewrite (G.(assoc) a); try apply comm; auto.\nQed.\n\nTheorem Zdivide_mult_rel_prime:  forall a b c : Z, (a | c) -> (b | c) -> rel_prime a b -> (a * b | c).\nintros a b c (q1, H1) (q2, H2) H3.\nassert (H4: (a | q2)).\napply Gauss with (2 := H3).\nexists q1; rewrite <- H1; rewrite H2; auto with zarith.\ncase H4; intros q3 H5; exists q3; rewrite H2; rewrite H5; auto with zarith.\nQed.\n\nTheorem order_mult: forall (A : Set) (op : A -> A -> A) (A_dec: forall a b: A, {a = b} + {~ a = b}) (G : FGroup op)\n       (comm: forall a b,  In a (s G) -> In b (s G) -> op a b = op b a) (a b: A),\n       In a (s G) -> In b (s G) -> rel_prime (e_order A_dec a G) (e_order A_dec b G) ->\n        e_order A_dec (op a b) G = e_order A_dec a G * e_order A_dec b G.\nintros A op A_dec G comm a b Ha Hb Hab.\nassert (Hoat: 0 < e_order A_dec a G) by apply e_order_pos.\nassert (Hobt: 0 < e_order A_dec b G) by apply e_order_pos.\nassert (Hoabt: 0 < e_order A_dec (op a b) G) by apply e_order_pos.\nassert (Hoa: 0 <= e_order A_dec a G) by auto with zarith.\nassert (Hob: 0 <= e_order A_dec b G) by auto with zarith.\napply Zle_antisym; apply Zdivide_le. 1, 4-5: auto with zarith.\napply Zmult_lt_O_compat; auto.\napply e_order_divide_gpow; sauto; auto with zarith.\nrewrite gpow_mult; auto with zarith.\nrewrite gpow_gpow; auto with zarith.\nrewrite gpow_e_order_is_e; auto with zarith.\nrewrite gpow_e; auto.\nrewrite Zmult_comm.\nrewrite gpow_gpow; auto with zarith.\nrewrite gpow_e_order_is_e; auto with zarith.\nrewrite gpow_e; auto.\napply Zdivide_mult_rel_prime; auto.\napply Gauss with (2 := Hab).\napply e_order_divide_gpow; auto with zarith.\nrewrite <- (gpow_e _ _ G (e_order A_dec b G)); auto.\nrewrite <- (gpow_e_order_is_e _ A_dec  _ (op a b) G); auto with zarith.\nrewrite <- gpow_gpow; auto with zarith.\nrewrite (Zmult_comm (e_order A_dec (op a b) G)).\nrewrite gpow_mult; auto with zarith.\nrewrite gpow_gpow with (a := b); auto with zarith.\nrewrite gpow_e_order_is_e; auto with zarith.\nrewrite gpow_e; auto with zarith.\nrewrite G.(e_is_zero_r); auto with zarith.\napply gpow_in; auto.\napply Gauss with (2 := rel_prime_sym _ _ Hab).\napply e_order_divide_gpow; auto with zarith.\nrewrite <- (gpow_e _ _ G (e_order A_dec a G)); auto.\nrewrite <- (gpow_e_order_is_e _ A_dec  _ (op a b) G); auto with zarith.\nrewrite <- gpow_gpow; auto with zarith.\nrewrite (Zmult_comm (e_order A_dec (op a b) G)).\nrewrite gpow_mult; auto with zarith.\nrewrite gpow_gpow with (a := a); auto with zarith.\nrewrite gpow_e_order_is_e; auto with zarith.\nrewrite gpow_e; auto with zarith.\nrewrite G.(e_is_zero_l); auto with zarith.\napply gpow_in; auto.\nQed.\n\nTheorem fermat_gen: forall (A : Set) (A_dec: forall (a b: A), {a = b} + {a <>b}) (op : A -> A -> A) (a: A) (G : FGroup op),\n       In a G.(s) ->  gpow a G (g_order G) = G.(e).\nintros A A_dec op a G H.\nassert (H1: (e_order A_dec a G | g_order G)).\napply e_order_divide_g_order; auto.\ncase H1; intros q; intros Hq; rewrite Hq.\nassert (Hq1: 0 <= q).\napply Zmult_le_reg_r with (e_order A_dec a G); auto with zarith.\napply Z.lt_gt; apply e_order_pos.\nrewrite Zmult_0_l; rewrite <- Hq; apply Zlt_le_weak; apply g_order_pos.\nrewrite Zmult_comm; rewrite gpow_gpow; auto with zarith.\nrewrite gpow_e_order_is_e; auto with zarith.\napply gpow_e; auto.\napply Zlt_le_weak; apply e_order_pos.\nQed.\n\nTheorem order_div: forall (A : Set) (A_dec: forall (a b: A), {a = b} + {a <>b}) (op : A -> A -> A) (a: A) (G : FGroup op) m,\n 0 < m -> (forall p, prime p -> (p | m) -> gpow a G (m / p) <> G.(e)) ->\n In a G.(s) -> gpow a G m = G.(e) -> e_order A_dec a G = m.\nintros A Adec op a G m Hm H H1 H2.\nassert (F1: 0 <= m); auto with zarith.\ncase (e_order_divide_gpow A Adec op a G H1 m F1 H2); intros q Hq.\nassert (F2: 1 <= q).\n  case (Zle_or_lt 0 q); intros HH.\n    case (Zle_lt_or_eq _ _ HH). auto with zarith.\n    intros HH1; generalize Hm; rewrite Hq; rewrite <- HH1;\n      auto with zarith.\n  assert (F2: 0 <= (- q) * e_order Adec a G).\n    apply Zmult_le_0_compat; auto with zarith.\n    apply Zlt_le_weak; apply e_order_pos.\n  generalize F2; rewrite Zopp_mult_distr_l_reverse;\n      rewrite <- Hq; auto with zarith.\ncase (Zle_lt_or_eq _ _ F2); intros H3; subst; auto with zarith.\ncase (prime_dec q); intros Hq.\n  case (H q); auto with zarith.\n    rewrite Zmult_comm; rewrite Z_div_mult; auto with zarith.\n  apply gpow_e_order_is_e; auto.\ncase (Zdivide_div_prime_le_square _ H3 Hq); intros r (Hr1, (Hr2, Hr3)).\ncase (H _ Hr1); auto.\n  apply Z.divide_trans with (1 := Hr2).\n  apply Zdivide_factor_r.\ncase Hr2; intros q1 Hq1; subst.\nassert (F3: 0 < r).\n  generalize (prime_ge_2 _ Hr1); auto with zarith.\nrewrite <- Zmult_assoc; rewrite Zmult_comm; rewrite <- Zmult_assoc;\n  rewrite Zmult_comm; rewrite Z_div_mult; auto with zarith.\nrewrite gpow_gpow. 2: auto with zarith.\n  rewrite gpow_e_order_is_e; try rewrite gpow_e; auto.\n  apply Zmult_le_reg_r with r; auto with zarith.\n  apply Zlt_le_weak; apply e_order_pos.\napply Zmult_le_reg_r with r; auto with zarith.\nQed.\n", "meta": {"author": "thery", "repo": "coqprime", "sha": "431d7a66877cbe8688fc8864ef892369401440e1", "save_path": "github-repos/coq/thery-coqprime", "path": "github-repos/coq/thery-coqprime/coqprime-431d7a66877cbe8688fc8864ef892369401440e1/src/Coqprime/PrimalityTest/EGroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6939809804683333}}
{"text": "(** Tarea 2 Lógica Minimal\n    Autor: Luis Felipe Benítez Lluis\n      Script de proposiciones a demostrar de la \n      sección de lógica minimal  *)\n\n\nProposition LM_a: forall A: Prop, ~~~A <-> ~A.\nProof.\nintros.\nsplit.\n+ intros.\n  intro.\n  apply H.\n  intro.\n  apply H1.\n  assumption.\n+ intros.\n  unfold not.\n  intros.\n  apply H0 in H.\n  assumption.\nQed.\n\nProposition LM_b: forall A B: Prop, \n  ~~(A /\\ B) -> ~~A /\\ ~~B.\nProof.\nintros.\nsplit.\n+ intro.\n  apply H.\n  intro.\n  apply H0.\n  destruct H1.\n  assumption.\n+ intro.\n  apply H.\n  intro.\n  apply H0.\n  destruct H1.\n  assumption.\nQed.\n\nProposition LM_c: forall T, forall A : T->Prop,\n  ~~(forall x : T, A x)-> (forall x : T, ~~ A x).\nProof.\n  intros.\n  intro.\n  apply H.\n  intro.\n  apply H0.\n  apply H1.\nQed.\n  \nLemma PNNP: forall P : Prop, \n  P-> ~~P.\nProof.\n  intros. intro. apply H0. apply H.\nQed.\n\n  ", "meta": {"author": "LuisBLluis11", "repo": "Tarea2VFLuisBLluis", "sha": "ef1bfd244dc336dcf100ed923574247111ca719a", "save_path": "github-repos/coq/LuisBLluis11-Tarea2VFLuisBLluis", "path": "github-repos/coq/LuisBLluis11-Tarea2VFLuisBLluis/Tarea2VFLuisBLluis-ef1bfd244dc336dcf100ed923574247111ca719a/LogicaMinimal/Props_LM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6938822700630081}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Lia Extraction.\n\nRequire Import measure_ind.\n\nSet Implicit Arguments.\n\n(** Several ways to define simple interleaving in Coq\n    to get the algorithm defined by the two equations\n\n      itl [] m = m\n      itl (x::l) m = x::itl m l\n\n   as following extracted code in OCaml\n\n     let rec itl l m = match l with\n       | []   -> m\n       | x::l -> x::itl m l \n\n   1) first itl_s is a functional equivalent by structural induction\n      but of course with a different algorithm\n   2) itl gives the correct algorithm but with hard correctness proof\n   3) itl_paired follows the same recursive pattern but with paired\n      arguments\n   4) itl_f gives the correct algo. with simple correctness proof\n   5) itl_g gives the correct algo. with simple and delayed correctness proof\n\n *)\n\nSection interleave.\n\n  Variable X : Type.\n\n  Implicit Type l m : list X.\n\n  Section interleave_struct.\n\n    (** First an easily definable functional equivalent\n        of itl, by structural induction on l *)\n\n    Fixpoint itl_s l m := \n      match l, m with\n        | nil,  _    => m\n        | _::_, nil  => l \n        | x::l, y::m => x::y::itl_s l m \n      end.\n\n    (** And we show itl_s satisfies the fixpoint equations of itl *)\n\n    Fact itl_s_fix0 m : itl_s nil m = m.\n    Proof. trivial. Qed.\n\n    Fact itl_s_fix1 x l m : itl_s (x::l) m = x::itl_s m l.\n    Proof.\n      revert x.\n      induction on l m as IH with measure (length l + length m).\n      intros x; destruct m as [ | y m ]; trivial.\n      simpl itl_s at 1; f_equal.\n      symmetry; apply IH; simpl; lia.\n    Qed. \n\n  End interleave_struct.\n\n  Section interleave_measure.\n\n    (** Now by induction on the measure |l|+|m| *)\n\n    Definition itl l m : list X.\n    Proof.\n      induction on l m as itl with measure (length l + length m).\n      revert itl. \n      refine (match l with\n        | nil  => fun _   => m\n        | x::l => fun itl => x::itl m l _\n      end).\n      simpl; lia.  (** the measure decreases *)\n    Defined.\n\n    (** Showing that itl_mes is ext-equal to itl_s \n        is possible but NOT EASY because\n        you have to use and thus prove the fixpoint \n        equation for measure_double_rect... \n\n        see measure_ind.v for this non-trivial proof *)\n\n    Let itl_fix l m : \n        itl l m = match l with \n          | nil  => m\n          | x::l => x::itl m l\n        end.\n    Proof.\n      unfold itl at 1.\n      rewrite measure_double_rect_fix.\n      + destruct l; simpl; trivial.\n      + (* Proof that the functor is extensional \n           beware that the functor contains proofs\n           automated with lia hence it is ugly *)\n        clear l m.\n        intros [ | x l ] m H1 H2 H; auto.\n        rewrite H; trivial.\n    Qed.\n\n    Fact itl_fix0 m : itl nil m = m.\n    Proof. rewrite itl_fix; trivial. Qed.\n\n    Fact itl_fix1 x l m : itl (x::l) m = x::itl m l.\n    Proof. rewrite itl_fix; trivial. Qed.\n\n    (** Once the fixpoint equations are established, the\n        proof is immediate *)\n\n    Lemma itl_itl_s_eq l m : itl l m = itl_s l m.\n    Proof.\n      induction on l m as IH with measure (length l + length m).\n      destruct l as [ | x l ].\n      + rewrite itl_s_fix0, itl_fix0; trivial.\n      + rewrite itl_s_fix1, itl_fix1; f_equal.\n        apply IH; simpl; lia.\n    Qed.\n  \n  End interleave_measure.\n\n  Section interleave_measure_paired.\n\n    (** Now by induction on the measure |l|+|m| but with paired arguments *)\n\n    Definition itl_paired l m : list X.\n    Proof.\n      paired induction on l m as itl_mes with measure (length l + length m).\n      revert itl_mes; refine (match l with\n        | nil  => fun _       => m\n        | x::l => fun itl_mes => x::itl_mes m l _\n      end).\n      simpl; lia.  (** the measure decreases *)\n    Defined.\n\n  End interleave_measure_paired.\n\n  Section interleave_measure_full.\n\n    (** Using dependent full specification allows for easy avoidance\n        of the fixpoint equation of measure_double_rect *)\n\n    Local Definition itl_full l m : { k | k = itl_s l m }.\n    Proof.\n      induction on l m as loop with measure (length l + length m).\n      revert loop. \n      refine (match l with\n        | nil  => fun _    => exist _ m _\n        | x::l => fun loop => let (k,Hk) := loop m l _\n                              in  exist _ (x::k) _ \n      end).\n      + rewrite itl_s_fix0; trivial.\n      + simpl; lia.\n      + rewrite Hk, itl_s_fix1; trivial.\n    Defined.\n\n    Extraction Inline itl_full.\n\n    Definition itl_f l m := proj1_sig (itl_full l m).\n    \n    Fact itl_f_itl_s_eq l m : itl_f l m = itl_s l m.\n    Proof. apply (proj2_sig (itl_full _ _)). Qed.\n\n  End interleave_measure_full.\n\nEnd interleave.\n\nExtract Inductive prod => \"(*)\"  [ \"(,)\" ].\nExtract Inductive list => \"list\" [ \"[]\" \"(::)\" ].\n\nRecursive Extraction itl_s itl itl_paired itl_f.\n\nSection interleave_without_knowledge_of_semantics.\n\n  Variable X : Type.\n\n  Implicit Type l m : list X.\n\n  (** We implement interleave without knowledge of semantics \n      and show correctness afterwards *)\n\n  (** We use the graph (an always definable relation) to specify\n      the algorithm *)\n\n  Inductive itl_graph : list X -> list X -> list X -> Prop := \n    | in_itl_g0 : forall m, itl_graph nil m m\n    | in_itl_g1 : forall x l m r, itl_graph m l r -> itl_graph (x::l) m (x::r).\n\n  (** The graph is a functional relation by combined induction/inversion *)\n\n  Fact itl_graph_fun l m r1 r2 : itl_graph l m r1 -> itl_graph l m r2 -> r1 = r2.\n  Proof.\n    intros H1; revert H1 r2.\n    induction 1; inversion 1; f_equal; auto.\n  Qed.\n\n  (** We use more proving style for this the code.\n      Thus is just to show that programming with tactics \n      is just fine *)\n\n  Local Definition itl_g_full l m : { k | itl_graph l m k }.\n  Proof.\n    induction on l m as loop with measure (length l + length m).\n    destruct l as [ | x l ].\n    + exists m; constructor.\n    + refine (let (k,Hk) := loop m l _ in _). \n      (* destruct (loop m l) instead of \n         refine would introduce a \n         parasitic \"let in\" the extracted code *)\n      * simpl; lia.\n      * exists (x::k).\n        constructor; trivial.\n  Defined.\n\n  Extraction Inline itl_g_full.\n\n  Definition itl_g l m := proj1_sig (itl_g_full l m).\n    \n  Fact itl_g_spec l m : itl_graph l m (itl_g l m).\n  Proof. apply (proj2_sig _). Qed.\n\n  (** We can show correctness after the definition using the graph *)\n\n  Lemma itl_s_g_eq l m : itl_g l m = itl_s l m.\n  Proof. \n    apply itl_graph_fun with l m.\n    * apply itl_g_spec.\n    * induction on l m as IH with measure (length l + length m).\n      destruct l as [ | x l ].\n      + rewrite itl_s_fix0; constructor.\n      + rewrite itl_s_fix1; constructor.\n        apply IH; simpl; lia.\n  Qed.\n\nEnd interleave_without_knowledge_of_semantics.\n\nRecursive Extraction itl_g.\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/itl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189134878876, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.6938413842978397}}
{"text": "\nRequire Export ZArith.\nRequire Export List.\nRequire Export Arith.\n\nSection bad_proof_example_for_Induction1.\n\n Theorem le_plus_minus' : forall n m:nat, m <= n -> n = m+(n-m).\n Proof.\n  intros n m H;  induction n. \n  -   rewrite <- le_n_O_eq with (1 := H); simpl; trivial. \n  - (* dead end *) \n    Abort.\n\nEnd bad_proof_example_for_Induction1.\n\n\nTheorem lazy_example : forall n:nat, (S n) + 0 = S n.\nProof.\n intros n; lazy beta iota zeta delta. \n fold plus.\n rewrite plus_0_r; reflexivity.\nQed.\n\nHint Extern 4 (_ <> _) => discriminate : core.\n\nHint Resolve le_S_n : le_base.\n\nTheorem auto_le_example :\n forall n m:nat, S (S (S n)) <= S (S (S m)) ->  n <= m.\nProof.\n  intros n m H.\n  auto with le_base.\nQed.\n\nLemma unprovable_le : forall n m:nat, n <= m.\nProof.\n Time auto with arith.\n Time auto with le_base arith.\nAbort.\n\nSection bad_proof_for_auto.\n\n Section Trying_auto.\n  Variable l1 : forall n m:nat, S n <= S m -> n <= m.\n\n  Theorem unprovable_le2 : forall n m:nat, n <= m.\n  Proof.\n   Time auto with arith.\n   Time try (clear l1; auto with arith; fail).\n  Abort.\n\n End Trying_auto.\n\nEnd bad_proof_for_auto.\n\nSection combinatory_logic.\n\nVariables (CL:Set)(App:CL->CL->CL)(S:CL)(K:CL).\nHypotheses\n  (S_rule :\n   forall A B C:CL, App (App (App S A) B) C = App (App A C)(App B C))\n  (K_rule :\n   forall A B:CL, App (App K A) B = A).\n\nHint Rewrite  S_rule K_rule : CL_rules.\n\nTheorem obtain_I : forall A:CL, App (App (App S K) K) A = A.\nProof.\n intros; autorewrite with CL_rules.\n reflexivity.\nQed.\n\nEnd combinatory_logic.\n\nTheorem example_for_subst :\n  forall (a b c d:nat), a = b+c -> c = 1 -> a+b = d -> 2*a = d+c.\nProof.\n intros a b c d H H1 H2.\n subst a.\n subst.\n lazy delta [mult] iota zeta beta; \n  rewrite  plus_0_r; \n  repeat rewrite plus_assoc_reverse;\n   trivial.\nQed.\n\nOpen Scope Z_scope.\n\nTheorem ring_example1 : forall x y:Z, (x+y) * (x+y)=x*x + 2*x*y + y*y.\nProof.\n intros x y; ring.\nQed.\n\nDefinition square (z:Z) := z*z.\n\nTheorem ring_example2 :\n  forall x y:Z, square (x+y) = square x + 2*x*y + square y.\nProof.\n intros x y; unfold square; ring.\nQed.\n\nTheorem ring_example3 : \n  (forall x y:nat, (x+y)*(x+y) = x*x + 2*x*y + y*y)%nat.\nProof.\n intros x y; ring.\nQed.\n\nTheorem ring_example4 :\n (forall x:nat, (S x)*(x+1) = x*x + (x+x+1))%nat.\nProof.\n intro x; ring_simplify.\n trivial.\nQed.\n\nRequire Omega.\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.\nQed.\n\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 H0; 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 H0; omega.\nQed.\n\nCheck (fun (X y:Z) => 0 <= X -> 3*X <= 2*y  ->  X < y).\n\nRequire Export Reals.\n\nOpen Scope R_scope.\n\nTheorem example_for_field : forall x y:R, y <> 0 ->(x+y) / y = 1  +(x/y).\nProof.\n  intros x y H; field.\n  assumption.\nQed.\n\nRequire Import Fourier.\n\nTheorem example_for_Fourier : forall x y:R, x-y >1 -> x - 2*y < 0 -> x > 1.\nProof.\n  intros x y H H0.\n  fourier.\nQed.\n\nTheorem ex_tauto1 : forall A B:Prop, A/\\B->A.\nProof.\n tauto.\nQed.\n\nTheorem ex_tauto2 : forall A B:Prop, A/\\~A -> B.\nProof.\n tauto.\nQed.\n\nOpen Scope Z_scope.\nTheorem ex_tauto3 : forall x y:Z, x<=y -> ~(x<=y) -> x=3.\nProof.\n tauto.\nQed.\n\nTheorem ex_tauto4 : forall A B:Prop, A\\/B -> B\\/A.\nProof.\n tauto. \nQed.\n\nTheorem ex_tauto5 : \n forall A B C D:Prop, (A->B)\\/(A->C)->A->(B->D)->(C->D)->D.\nProof.\n tauto.\nQed.\n\nOpen Scope nat_scope.\n\nTheorem example_intuition :\n  (forall n p q:nat,  n <= p \\/ n <= q -> n <= p \\/ n <= S q).\nProof.\n intros n p q; intuition auto with arith.\nQed.\n\nLtac autoClear h := try (clear h; auto with arith; fail).\n\nLtac autoAfter tac := try (tac; auto with arith; fail).\n\nOpen Scope nat_scope.\n\nTheorem example_for_autoAfter : forall  n p:nat,\n   n < p -> n <= p -> 0 < p -> S n < S p.\nProof.\n intros n p H H0 H1.\n autoAfter ltac:(clear H0 H1).\nQed.\n\nOpen Scope nat_scope.\n\nLtac le_S_star := apply le_n || (apply le_S; le_S_star).\n\nTheorem le_5_25 : 5 <= 25.\nProof.\n le_S_star.\nQed.\n\nLtac contrapose H :=\n  match goal with\n  | id:(~_) |- (~_) => intro H; apply id\n  end.\n\nTheorem example_contrapose : \n  forall x y:nat, x <> y -> x <= y -> ~y <= x.\nProof.\n intros x y H H0.\n contrapose H'.\n auto with arith.\nQed.\n\n\n\nSection primes.\n\n Definition divides (n m:nat) := exists p:nat, p*n = m.\n\n Lemma divides_O : forall n:nat, divides n 0.\n Admitted. (** Left as an exercise, as well as the next 6 lemmas  *)\n\n\n Lemma divides_plus : forall n m:nat, divides n m -> divides n (n+m).\n Admitted.\n\n Lemma not_divides_plus : forall n m:nat, ~divides n m -> ~divides n (n+m).\n Admitted.\n\n Lemma not_divides_lt : forall n m:nat, 0<m -> m<n -> ~divides n m.\n Admitted.\n\n Lemma not_lt_2_divides : forall n m:nat, n<>1 -> n<2 -> 0 < m -> ~divides n m.\n Admitted.\n\n Lemma le_plus_minus : forall n m:nat, le n m -> m = n+(m-n).\n Admitted.\n\n Lemma lt_lt_or_eq : forall n m:nat, n < S m ->  n<m \\/ n=m.\n Admitted. \n\n Ltac check_not_divides :=\n   match goal with\n   | |- (~divides ?X1 ?X2) =>\n       cut (X1<=X2);[ idtac | le_S_star ]; intros Hle;\n        rewrite (le_plus_minus _ _ Hle); apply not_divides_plus; \n        simpl; clear Hle; check_not_divides\n   | |- _ => apply not_divides_lt; unfold lt; le_S_star\n\n  end.\nOpen Scope nat_scope.\n\nHint Resolve lt_O_Sn.\n\nLtac check_lt_not_divides :=\n  match goal with\n  | Hlt:(lt ?X1 2%nat) |- (~divides ?X1 ?X2) =>\n      apply not_lt_2_divides; auto\n  | Hlt:(lt ?X1 ?X2) |- (~divides ?X1 ?X3) =>\n      elim (lt_lt_or_eq _ _ Hlt);\n       [clear Hlt; intros Hlt; check_lt_not_divides\n        | intros Heq; rewrite Heq; check_not_divides]\n  end.\n\nDefinition is_prime (p:nat) : Prop := \n   forall n:nat, n <> 1 -> lt n p -> ~divides n p.\n\nTheorem prime37 : is_prime 37.\nProof.\n unfold is_prime; intros.\n check_lt_not_divides.\nTime Qed.\n\nEnd primes.\n\n\nLtac clear_all :=\n  match goal with\n  | id:_ |- _ => clear id; clear_all\n  | |- _ => idtac\n  end.\n\n\nTheorem clear_example_thm :\n  forall (x y z:nat), x<z->z=2*x->0<x->x=2*y->y<z->x>y.\nProof.\n intros x y z H H1 H2 H3.\n generalize H1 H2 H3; clear_all; intros; omega.\nQed.\n\nTheorem S_to_plus_one : forall n:nat, S n = n+1.\nProof.\n  intros; rewrite plus_comm; reflexivity.\nQed.\n\n\nLtac S_to_plus_simpl :=\n  match goal with\n  | |-  context [(S ?X1)] =>\n      match X1 with\n      | 0%nat => fail 1\n      | ?X2 => rewrite (S_to_plus_one X2); S_to_plus_simpl\n      end\n  | |- _ => idtac\n  end.\n\nLtac a_function X1 :=\n        match X1 with\n      | 0%nat => fail 1\n      | ?X2 => rewrite (S_to_plus_one X2); S_to_plus_simpl\n      end.\n\n\nLtac simpl_on e :=\n  let v := eval simpl in e in\n  match goal with\n  | |- context [e] => replace e with v; [idtac | auto]\n  end.\n\nTheorem simpl_on_example :\n  forall n:nat, exists m : nat, (1+n) + 4*(1+n) = 5*(S m).\nProof.\n  intros n; simpl_on (1+n). \n  exists n; auto with arith.\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/ch7_tactics_automation/SRC/chap7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.6938413723267569}}
{"text": "Theorem 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\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.", "meta": {"author": "TysonSir", "repo": "coq", "sha": "3d5cd319a377acbdad1bec34061d298043c9bc18", "save_path": "github-repos/coq/TysonSir-coq", "path": "github-repos/coq/TysonSir-coq/coq-3d5cd319a377acbdad1bec34061d298043c9bc18/week3/demo_2_simpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6936993942511619}}
{"text": "\n(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Sebastien Hinderer, 2004-05-20\n- Frederic Blanqui, 2005-02-25\n\nRing equipped with a decidable strict ordering.\n*)\n\nRequire Import Ring RingType1 RelUtil LogicUtil VecUtil Setoid BoolUtil\n  Wellfounded Morphisms RelExtras1.\n\n(***********************************************************************)\n(** Module type for building the theory module of an ordered ring *)\n\nClass OrdRing := {\n  (*o_ring :> Ring;*)\n  o_ring :> Ring;\n  o_gt : s_typ -> s_typ -> Prop;\n  o_gt_trans : transitive o_gt;\n  o_gt_irrefl : irreflexive o_gt;\n  o_bgt : s_typ -> s_typ -> bool;\n  o_bgt_ok : forall x y, o_bgt x y = true <-> o_gt x y;\n  o_one_gt_zero : o_gt ring_A1 ring_A0;\n  o_add_gt_mono_r : forall x y z, o_gt x y -> o_gt (ring_Aplus x z) (ring_Aplus y z);\n  o_mul_gt_mono_r : forall x y z, o_gt z ring_A0 -> o_gt x y -> o_gt (ring_Amult x z) (ring_Amult y z)                               \n}.\n\n(***********************************************************************)\n(* Integers as an order ring *)\n\nRequire Import ZArith.\n\nDefinition gtA_dec := Z_gt_dec. \n \nDefinition bgtA x y := \n  match gtA_dec x y with \n    |left _ => true \n    |right _ => false\n  end.\n\nInstance Z_as_OrdRing : OrdRing.\n\nProof.\n  apply Build_OrdRing with\n  (o_ring := Int_as_Ring)\n  (o_gt := Zgt)(o_bgt:= bgtA).\n  exact Zcompare_Gt_trans.\n  intros n H. apply (Zgt_asym n n H H).\n  intros. unfold bgtA. case (gtA_dec x y); intuition.\n  simpl. omega. simpl. intros. omega.\n  simpl.  intros x y z H H0. destruct z. contradiction (Zgt_irrefl 0). \n  rewrite (Zmult_comm x); rewrite (Zmult_comm y). \n  unfold Zgt in |- *; rewrite Zcompare_mult_compat; hyp. \n  discr.\nDefined.\n\n(***********************************************************************)\n(**Rational numbers as an order ring *)\n\nRequire Import QArith.\n\nDefinition Qgt x y := Qlt y x. \n\nDefinition Q_gt_dec x y : {x > y} + {~ x > y}.\nProof.\n  unfold Qlt in |- *. intros. \n  exact (Z_lt_dec (Qnum y * QDen x) (Qnum x * QDen y)).\nDefined.\n\nDefinition Qgt_dec := Q_gt_dec.\n\nDefinition Qbgt x y :=\n  match Qgt_dec x y with\n    |left _ => true\n    |right _ => false\n  end.\n\nInstance Q_as_OrdRing : OrdRing.\n\nProof.\n  apply Build_OrdRing with\n  (o_ring := Q_as_Ring)(o_gt:=Qgt)\n  (o_bgt:= Qbgt). (* FIXME *)\n  ", "meta": {"author": "fblanqui", "repo": "rainbow", "sha": "3c437c0d40f01038b1d82f2a9a8085e366de3f15", "save_path": "github-repos/coq/fblanqui-rainbow", "path": "github-repos/coq/fblanqui-rainbow/rainbow-3c437c0d40f01038b1d82f2a9a8085e366de3f15/devel/gwen/coq_old/OrdRingType1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6936720069661889}}
{"text": "(********************************************************************)\n(*                                                                  *)\n(*  The Why3 Verification Platform   /   The Why3 Development Team  *)\n(*  Copyright 2010-2019   --   Inria - CNRS - Paris-Sud University  *)\n(*                                                                  *)\n(*  This software is distributed under the terms of the GNU Lesser  *)\n(*  General Public License version 2.1, with the special exception  *)\n(*  on linking described in file LICENSE.                           *)\n(*                                                                  *)\n(********************************************************************)\n\n(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire int.Int.\n\nSection Exponentiation.\n\n(* Why3 goal *)\nVariable t : Type.\nHypothesis t_WhyType : WhyType t.\nExisting Instance t_WhyType.\n\n(* Why3 goal *)\nVariable one: t.\n\n(* Why3 goal *)\nVariable infix_as: t -> t -> t.\n\n(* Why3 goal *)\nHypothesis Assoc :\n  forall (x:t) (y:t) (z:t),\n  ((infix_as (infix_as x y) z) = (infix_as x (infix_as y z))).\n\n(* Why3 goal *)\nHypothesis Unit_def_l : forall (x:t), ((infix_as one x) = x).\n\n(* Why3 goal *)\nHypothesis Unit_def_r : forall (x:t), ((infix_as x one) = x).\n\n(* Why3 goal *)\nDefinition power : t -> Numbers.BinNums.Z -> t.\nintros x n.\nexact (iter_nat (Zabs_nat n) t (fun acc => infix_as x acc) one).\nDefined.\n\n(* Why3 goal *)\nLemma Power_0 : forall (x:t), ((power x 0%Z) = one).\nProof.\neasy.\nQed.\n\n(* Why3 goal *)\nLemma Power_s :\n  forall (x:t) (n:Numbers.BinNums.Z), (0%Z <= n)%Z ->\n  ((power x (n + 1%Z)%Z) = (infix_as x (power x n))).\nProof.\nintros x n h1.\nunfold power.\nfold (Zsucc n).\nnow rewrite Zabs_nat_Zsucc.\nQed.\n\n(* Why3 goal *)\nLemma Power_s_alt :\n  forall (x:t) (n:Numbers.BinNums.Z), (0%Z < n)%Z ->\n  ((power x n) = (infix_as x (power x (n - 1%Z)%Z))).\nProof.\nintros x n h1.\nrewrite <- Power_s; auto with zarith.\nf_equal; omega.\nQed.\n\n(* Why3 goal *)\nLemma Power_1 : forall (x:t), ((power x 1%Z) = x).\nProof.\nexact Unit_def_r.\nQed.\n\n(* Why3 goal *)\nLemma Power_sum :\n  forall (x:t) (n:Numbers.BinNums.Z) (m:Numbers.BinNums.Z), (0%Z <= n)%Z ->\n  (0%Z <= m)%Z -> ((power x (n + m)%Z) = (infix_as (power x n) (power x m))).\nProof.\nintros x n m Hn Hm.\nrevert n Hn.\napply natlike_ind.\napply sym_eq, Unit_def_l.\nintros n Hn IHn.\nreplace (Zsucc n + m)%Z with ((n + m) + 1)%Z by ring.\nrewrite Power_s by auto with zarith.\nrewrite IHn.\nnow rewrite <- Assoc, <- Power_s.\nQed.\n\n(* Why3 goal *)\nLemma Power_mult :\n  forall (x:t) (n:Numbers.BinNums.Z) (m:Numbers.BinNums.Z), (0%Z <= n)%Z ->\n  (0%Z <= m)%Z -> ((power x (n * m)%Z) = (power (power x n) m)).\nProof.\nintros x n m Hn Hm.\nrevert m Hm.\napply natlike_ind.\nnow rewrite Zmult_0_r, 2!Power_0.\nintros m Hm IHm.\nreplace (n * Zsucc m)%Z with (n + n * m)%Z by ring.\nrewrite Power_sum by auto with zarith.\nrewrite IHm.\nnow rewrite <- Power_s.\nQed.\n\n(* Why3 goal *)\nLemma Power_comm1 :\n  forall (x:t) (y:t), ((infix_as x y) = (infix_as y x)) ->\n  forall (n:Numbers.BinNums.Z), (0%Z <= n)%Z ->\n  ((infix_as (power x n) y) = (infix_as y (power x n))).\nProof.\nintros x y comm.\napply natlike_ind.\nnow rewrite Power_0, Unit_def_r, Unit_def_l.\nintros n Hn IHn.\nunfold Zsucc.\nrewrite (Power_s _ _ Hn).\nrewrite Assoc.\nrewrite IHn.\nrewrite <- Assoc.\nrewrite <- Assoc.\nnow rewrite comm.\nQed.\n\n(* Why3 goal *)\nLemma Power_comm2 :\n  forall (x:t) (y:t), ((infix_as x y) = (infix_as y x)) ->\n  forall (n:Numbers.BinNums.Z), (0%Z <= n)%Z ->\n  ((power (infix_as x y) n) = (infix_as (power x n) (power y n))).\nProof.\nintros x y comm.\napply natlike_ind.\nrewrite 3!Power_0.\nnow rewrite Unit_def_r.\nintros n Hn IHn.\nunfold Zsucc.\nrewrite 3!(Power_s _ _ Hn).\nrewrite IHn.\nrewrite <- Assoc.\nrewrite (Assoc x).\nrewrite <- (Power_comm1 _ _ comm _ Hn).\nnow rewrite <- 2!Assoc.\nQed.\n\nEnd Exponentiation.\n", "meta": {"author": "schrodibear", "repo": "why3", "sha": "9f8eb767380987a28e43b81729ae1d682363bb49", "save_path": "github-repos/coq/schrodibear-why3", "path": "github-repos/coq/schrodibear-why3/why3-9f8eb767380987a28e43b81729ae1d682363bb49/lib/coq/int/Exponentiation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658466, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6936493792991753}}
{"text": "From mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.\n\n(* Here we define a more verbose notation for projections of pairs... *)\nSection Pair.\n\n  Context {A B: Type}.\n  Variable p: A * B.\n  Definition pair_1st := fst p.\n  Definition pair_2nd := snd p.\n\nEnd Pair.\n\n(* ...and triples. *)\nSection Triple.\n\n  Context {A B C: Type}.\n  Variable p: A * B * C.\n  Definition triple_1st (p: A * B * C) := fst (fst p).\n  Definition triple_2nd := snd (fst p).\n  Definition triple_3rd := snd p.\n\nEnd Triple.\n\n(* Define a wrapper from an element to a singleton list. *)\nDefinition make_sequence {T: Type} (opt: option T) :=\n  match opt with\n    | Some j => [:: j]\n    | None => [::]\n  end.\n\n(* Next we define a notation for the big concatenation operator.*)\n  \nReserved Notation \"\\cat_ ( m <= i < n ) F\"\n  (at level 41, F at level 41, i, m, n at level 50,\n   format \"'[' \\cat_ ( m <= i < n ) '/ ' F ']'\").\n\nNotation \"\\cat_ ( m <= i < n ) F\" :=\n  (\\big[cat/[::]]_(m <= i < n) F%N) : nat_scope.\n\nReserved Notation \"\\cat_ ( m <= i < n | P ) F\"\n  (at level 41, F at level 41, P at level 41, i, m, n at level 50,\n   format \"'[' \\cat_ ( m <= i < n | P ) '/ ' F ']'\").\n\nNotation \"\\cat_ ( m <= i < n | P ) F\" :=\n  (\\big[cat/[::]]_(m <= i < n | P) F%N) : nat_scope.\n\nReserved Notation \"\\cat_ ( i < n ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n   format \"'[' \\cat_ ( i < n ) '/ ' F ']'\").\n\nNotation \"\\cat_ ( i < n ) F\" :=\n  (\\big[cat/[::]]_(i < n) F%N) : nat_scope.\n\nReserved Notation \"\\cat_ ( i < n | P ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n   format \"'[' \\cat_ ( i < n | P ) '/ ' F ']'\").\n\nNotation \"\\cat_ ( i < n | P ) F\" :=\n  (\\big[cat/[::]]_(i < n | P) F%N) : nat_scope.\n  \n(* Let's define big operators for lists of pairs. *)\n\nReserved Notation \"\\sum_ ( ( m , n ) <- r ) F\"\n  (at level 41, F at level 41, m, n at level 50,\n   format \"'[' \\sum_ ( ( m , n ) <- r ) '/ ' F ']'\").\n\nNotation \"\\sum_ ( ( m , n ) <- r ) F\" :=\n  (\\sum_(i <- r) (let '(m,n) := i in F)) : nat_scope.\n\nReserved Notation \"\\sum_ ( ( m , n ) <- r | P ) F\"\n  (at level 41, F at level 30, P at level 41, m, n at level 50,\n   format \"'[' \\sum_ ( ( m , n ) <- r | P ) '/ ' F ']'\").\n\nNotation \"\\sum_ ( ( m , n ) <- r | P ) F\" :=\n  (\\sum_(i <- r | (let '(m,n) := i in P))\n    (let '(m,n) := i in F)) : nat_scope.\n\nReserved Notation \"\\max_ ( ( m , n ) <- r ) F\"\n  (at level 41, F at level 41, m, n at level 50,\n   format \"'[' \\max_ ( ( m , n ) <- r ) '/ ' F ']'\").\n\nNotation \"\\max_ ( ( m , n ) <- r ) F\" :=\n  (\\max_(i <- r) (let '(m,n) := i in F)) : nat_scope.\n\nReserved Notation \"\\max_ ( ( m , n ) <- r | P ) F\"\n  (at level 41, F at level 30, P at level 41, m, n at level 50,\n   format \"'[' \\max_ ( ( m , n ) <- r | P ) '/ ' F ']'\").\n\nNotation \"\\max_ ( ( m , n ) <- r | P ) F\" :=\n  (\\max_(i <- r | (let '(m,n) := i in P))\n    (let '(m,n) := i in F)) : nat_scope.\n\nNotation \"[ 'pairs' ( x , y ) <- s | C ]\" :=\n  (filter (fun i => let '(x,y) := i in C%B) s)\n (at level 0, x at level 99,\n  format \"[ '[hv' 'pairs' ( x , y ) <- s '/ ' | C ] ']'\") : seq_scope.\n\nNotation \"[ 'pairs' ( E , F ) | x <- s ]\" :=\n    (map (fun y => ((fun x1 => let x := x1 in E) y, (fun x2 => let x := x2 in F) y)) s)\n  (at level 0, E at level 1, F at level 1, \n   format \"[ '[hv' 'pairs' ( E , F )  |  x  <-  s ] ']'\") : seq_scope.\n\n(* In case we use an (option list T), we can define membership\n   without having to match the option type. *)\nReserved Notation \"x \\In A\"\n  (at level 70, format \"'[hv' x '/ ' \\In A ']'\", no associativity).\nNotation \"x \\In A\" :=\n  (if A is Some B then in_mem x (mem B) else false) : bool_scope.\n", "meta": {"author": "cd-public", "repo": "rt-proofs", "sha": "ebef0b65460fe009c51f638fe2b459f16a6d1dd5", "save_path": "github-repos/coq/cd-public-rt-proofs", "path": "github-repos/coq/cd-public-rt-proofs/rt-proofs-ebef0b65460fe009c51f638fe2b459f16a6d1dd5/util/notation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.6936493164358072}}
{"text": "(** ** auto\n\nまず、forall (P : Prop), P -> P という命題を例として考えます。\nこの命題は auto 一発で証明できます。\n*)\n\nGoal forall (P : Prop), P -> P.\nProof.\n  auto.\n\n(** ここで No more subgoals. と表示されて、証明できたことがわかります。\n構築された証明項は Show Proof というコマンドで表示できます。*)\n  Show Proof.\n(**\n<<\n(fun (P : Prop) (H : P) => H)\n>>\n*)\n(** Show Proof とすると私の環境 (CoqIDE) では以下のように表示されます。\n<<\n(fun (P : Prop) (H : P) => H)\n>>\n\n(fun (P : Prop) (H : P) => H) は Gallina の式です。\nGallina というのは Coq に組み込まれている ML のような言語で、\nここで使っているように証明項にも用いますし、\nGallina で直接プログラムを書くこともあります。\n\n(fun (P : Prop) (H : P) => ...) というのは\nGallina の関数抽象で、カリー化されているのでじつは\n(fun (P : Prop) => (fun (H : P) => ...)) と同じものです。\n関数型言語を知っていればだいたいわかるとは思いますが、\n(fun (P : Prop) => ...) は Prop 型の値 P を受け取って ... の部分を返す関数抽象です。\n\nProp というのは命題の型です。\nですから、Prop 型の値である P は命題です。\nというわけでカリーハワード対応により P は型でもあります。\nですが、このように型を普通の引数として受け取るのはちょっと見慣れない形かもしれません。\nGallina では型も普通に引数として\n受けとることができ、受け取った型はそれ以降の引数の型などに使うことができます。\n\n(fun (P : Prop) (H : P) => H) は、\nプログラムの世界の言葉で表現するなら、\nProp 型の値Pを受け取り、P型の値Hを受け取り、Hを返す関数です。\n証明の世界の言葉で表現するなら、\n命題Pを受け取り、Pの証明Hを受け取り、Hを返す関数です。\nそのような関数が存在することが、forall (P : Prop), P -> P の証明である、ということです。\n\n*)\nQed.\n\n(* xxx: ここで説明する必然性はない\n証明を終えるとき、Qed は証明項があらためて正しいかどうか\n（ちゃんと正しい型がつく項になっているかどうか）\nあらためて検査します。\nそのため、怪しげなユーザ拡張の tactic が変な証明項を生成しても、\nそのような証明はQedの段階で拒否されます。\n*)\n\n(** ところで、Qed としたときに Unnamed_thm is defined と表示されます。\nつまり、Unnamed_thm という定理が定義された、ということですが、\nもちろん、後で使いたい定理にこういう内容に関係ない名前をつけるのはよくありません。\n自分で定理に名前をつけるときには Goal ではなく Lemma や Theorem で証明を始めます。\nLemmaというのは補題で、Theoremというのは定理ですが、\n機能的な違いはとくにありません。ここでは常に Lemma をつかうことにします。\n*)\n\nLemma LemmaPP: forall (P : Prop), P -> P.\n(** 証明しようとしているのは上と同じく forall (P : Prop), P -> P という命題であり、\nこれはその証明に LemmaPP という名前をつけよう、という指定です。\n*)\nProof. auto. Qed.\n\nPrint LemmaPP.\n(** 証明が終った後、Print LemmaPP とすると以下のように表示されます。\n<<\nLemmaPP = fun (P : Prop) (H : P) => H\n     : forall P : Prop, P -> P\n>>\nこれは、LemmaPP の値は fun (P : Prop) (H : P) => H という値であり、\nその型は forall P : Prop, P -> P である、という意味です。\nプログラムの世界で解釈すれば、まさに LemmaPP という定数は\n構築した証明項を値として定義されている、\nというわけです。\n*)\n\n\n", "meta": {"author": "akr", "repo": "coq-curry-howard", "sha": "37a7f3afc07bb17e49ec915be1a1a2ddb67a5ee5", "save_path": "github-repos/coq/akr-coq-curry-howard", "path": "github-repos/coq/akr-coq-curry-howard/coq-curry-howard-37a7f3afc07bb17e49ec915be1a1a2ddb67a5ee5/theories/auto.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893340314393, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.6935825690463634}}
{"text": "Require Import List.\nRequire Import Omega.\nRequire Import LibUtils.\n\nRequire Import ListAdd.\n\nSection Vector.\n\n  Definition Vector (T:Type) (n : nat) := {n':nat | n' < n}%nat -> T.\n  Definition Matrix (T:Type) (n m : nat) := \n    {n':nat | n' < n}%nat -> {m':nat | m' < m}%nat -> T.\n\n\n  Definition ConstVector {T} (n:nat) (c:T) : (Vector T n) := \n    fun (n': {n':nat | n' < n}%nat) => c.\n  Definition ConstMatrix {T} (n m : nat) (c:T) : (Matrix T n m) := \n    fun (n': {n':nat | n' < n}%nat) (m':{m':nat | m' < m}%nat) => c.\n\n(*  Definition vector_fold_right1_bounded_dep {A:nat->Type} {B} \n             (f:forall n,B->A n->A (S n)) (init:A 0%nat) (singleton:B->A 1%nat) {m:nat} \n             (v:Vector B m) (n:nat) (pf:(n<=m)%nat) {struct n}\n    : A n.\n  Proof.\n    destruct n.\n    - exact init.\n    - specialize (vector_fold_right1_bounded_dep A B f init singleton m v n (le_Sn_le _ _ pf)).\n      destruct n; intros.\n      + exact (singleton (v (exist _ 0 pf)%nat)).\n      + apply f.\n        * exact (v (exist _ n (le_Sn_le _ _ pf))).\n        * exact vector_fold_right1_bounded_dep.\n  Defined.c\n*)\n\n  Fixpoint vector_fold_right1_bounded_dep {A:nat->Type} {B} \n           (f:forall n,B->A n->A (S n)) (init:A 0%nat) (singleton:B->A 1%nat) {m:nat} \n           (v:Vector B m) (bound:nat) {struct bound}\n    : (bound <= m)%nat -> A bound :=\n    match bound as bound' return (bound' <= m -> A bound') with\n    | 0 => fun _ =>\n             init\n    | S bound1 =>\n      fun pf0 : S bound1 <= m =>\n        let an := vector_fold_right1_bounded_dep f init singleton v bound1 (le_Sn_le bound1 m pf0) in\n\n        match bound1 as bound1' return (A bound1' -> S bound1' <= m -> A (S bound1')) with\n        | 0 => fun (_ : A 0) (pf1 : 1 <= m) =>\n                 singleton (v (exist _ 0 pf1))\n        | S bound2 => fun (an' : A (S bound2)) (pf1 : S (S bound2) <= m) =>\n                        f (S bound2) (v (exist _ bound1 pf0)) an'\n        end an pf0\n    end.\n\n  Definition vector_fold_right_bounded_dep {A:nat->Type} {B}\n               (f:forall n,B->A n->A (S n)) (init:A 0%nat) {m:nat} (v:Vector B m) (n:nat)\n               (pf:(n<=m)%nat)\n      : A n.\n    Proof.\n      induction n.\n      - exact init.\n      - apply f.\n        + exact (v (exist _ n pf)).\n        + apply IHn.\n          exact (le_Sn_le _ _ pf).\n    Defined.\n\n  Definition vnil {T} : Vector T 0.\n  Proof.\n    intros [i pf].\n    omega.\n  Defined.\n\n  Definition vcons {T} {n} (x:T) (v:Vector T n) : (Vector T (S n)).\n  Proof.\n    intros [i pf].\n    destruct (Nat.eq_dec i n).\n    + exact x.\n    + apply v.\n      exists i.\n      apply NPeano.Nat.le_neq.\n      split; trivial.\n      now apply le_S_n in pf.\n  Defined.\n\n  \n  Definition vhd {T} {n} (v:Vector T (S n)) : T := v (exist _ (0%nat) (Nat.lt_0_succ n)).\n  Definition vlast {T} {n} (v:Vector T (S n)) : T := v (exist _ (n%nat) (Nat.lt_succ_diag_r n)).\n\n  Definition vdrop_last {T} {n} (v:Vector T (S n)) : Vector T n.\n  Proof.\n    intros [i pf]; apply v.\n    exists i.\n    apply NPeano.Nat.lt_lt_succ_r; trivial.\n  Defined.\n\n\n  Lemma vector_fold_right1_bounded_dep_as_vector_fold_right_bounded_dep {A:nat->Type} {B} \n           (f:forall n,B->A n->A (S n)) (init:A 0%nat) (singleton:B->A 1%nat) {m:nat} \n           (v:Vector B m) (bound:nat) pf\n    :\n      (forall x, singleton x = f _ x init) ->\n        vector_fold_right1_bounded_dep f init singleton v bound pf = \n        vector_fold_right_bounded_dep f init v bound pf.\n  Proof.\n    intros feq.\n    unfold vector_fold_right_bounded_dep.\n    induction bound; simpl; trivial.\n    rewrite IHbound.\n    destruct bound; simpl; auto.\n  Qed.\n\n  Lemma vector_fold_right_bounded_dep_as_vector_fold_right1_bounded_dep {A:nat->Type} {B} \n        (f:forall n,B->A n->A (S n)) (init:A 0%nat) {m:nat} \n        (v:Vector B m) (bound:nat) pf\n    :\n      vector_fold_right_bounded_dep f init v bound pf = \n      vector_fold_right1_bounded_dep f init (fun x => f 0 x init) v bound pf.\n  Proof.\n    unfold vector_fold_right_bounded_dep.\n    induction bound; simpl; trivial.\n    rewrite IHbound.\n    destruct bound; simpl; auto.\n  Qed.\n\n  Definition vector_fold_right1_dep {A:nat->Type} {B} (f:forall n, B->A n->A (S n)) \n             (init:A 0%nat) (singleton:B->A 1%nat) {m:nat} (v:Vector B m) : A m\n    := vector_fold_right1_bounded_dep f init singleton v m (le_refl _).\n\n  Definition vector_fold_right_dep {A:nat->Type} {B} (f:forall n, B->A n->A (S n)) \n             (init:A 0%nat) {m:nat} (v:Vector B m) : A m\n    := vector_fold_right_bounded_dep f init v m (le_refl _).\n\n  Definition vector_fold_right1 {A B:Type} (f:B->A->A) (init:A) (singleton:B->A) {m:nat} (v:Vector B m)\n    := vector_fold_right1_dep (A:=fun _ => A) (fun _ => f) init singleton v.\n\n  Definition vector_fold_right {A B:Type} (f:B->A->A) (init:A) {m:nat} (v:Vector B m)\n    := vector_fold_right_dep (fun _ => f) init v.\n\n\n  Lemma vector_fold_right1_dep_as_vector_fold_right_dep {A:nat->Type} {B} \n        (f:forall n,B->A n->A (S n)) (init:A 0%nat) (singleton:B->A 1%nat) {m:nat} \n        (v:Vector B m)\n    :\n      (forall x, singleton x = f _ x init) ->\n        vector_fold_right1_dep f init singleton v  = \n        vector_fold_right_dep f init v.\n  Proof.\n    apply vector_fold_right1_bounded_dep_as_vector_fold_right_bounded_dep.\n  Qed.\n\n  Lemma vector_fold_right_dep_as_vector_fold_right1_dep {A:nat->Type} {B} \n        (f:forall n,B->A n->A (S n)) (init:A 0%nat) {m:nat} \n        (v:Vector B m)\n    :\n      vector_fold_right_dep f init v = \n      vector_fold_right1_dep f init (fun x => f 0 x init) v.\n  Proof.\n    apply vector_fold_right_bounded_dep_as_vector_fold_right1_bounded_dep.\n  Qed.\n\n  Lemma vector_fold_right1_as_vector_fold_right {A:Type} {B} \n        (f:B->A->A) (init:A) (singleton:B->A) {m:nat} \n        (v:Vector B m)\n    :\n      (forall x, singleton x = f x init) ->\n        vector_fold_right1 f init singleton v  = \n        vector_fold_right f init v.\n  Proof.\n    apply (vector_fold_right1_dep_as_vector_fold_right_dep (fun _ => f)).\n  Qed.\n\n  Lemma vector_fold_right_as_vector_fold_right1 {A:Type} {B} \n        (f:B->A->A) (init:A) {m:nat} \n        (v:Vector B m)\n    :\n      vector_fold_right f init v = \n      vector_fold_right1 f init (fun x => f x init) v.\n  Proof.\n    apply (vector_fold_right_dep_as_vector_fold_right1_dep (fun _ => f)).\n  Qed.\n\n  Definition vectoro_to_ovector {T} {n} (v:Vector (option T) n) : option (Vector T n)\n    := vector_fold_right_dep (fun n => lift2 (@vcons _ n)) (Some vnil) v.\n\n  Definition matrixo_to_omatrix {T} {m n} (v:Matrix (option T) m n) : option (Matrix T m n)\n    := vectoro_to_ovector (fun i => vectoro_to_ovector (v i)).\n\n  Definition vmap {A B} {n} (f:A->B) (v:Vector A n) : Vector B n\n    := vector_fold_right_dep (fun n x y => vcons (n:=n) (f x) y) vnil v.\n\n\n  Definition mmap {A B} {m n} (f:A->B) (mat:Matrix A m n) : Matrix B m n\n    := vmap (fun mrow => vmap f mrow) mat.\n\n  Definition list_fold_right1_bounded_dep {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n             (init:A 0%nat) (singleton:B->A 1%nat) (l:list B) (n:nat) (pf:(n<=length l)%nat)\n    : A n.\n  Proof.\n    revert l pf.\n    induction n; intros l pf.\n    - exact init.\n    - destruct n.\n      + assert (pf2:(0 < length l)%nat) by omega.\n        destruct l.\n        * simpl in pf; omega.\n        * exact (singleton b).\n      + destruct l; simpl in *; try omega.\n        apply f.\n        * apply b.\n        * apply (IHn l).\n          omega.\n  Defined.\n\n  Definition list_fold_right1_dep {A:nat->Type} {B} (f:forall n, B->A n->A (S n)) \n             (init:A 0%nat) (singleton:B->A 1%nat) (l:list B) : A (length l)\n    := list_fold_right1_bounded_dep f init singleton l (length l) (le_refl _).\n\n  Definition list_fold_right_dep {A:nat->Type} {B} (f:forall n, B->A n->A (S n)) \n             (init:A 0%nat) (l:list B) : A (length l)\n    := list_fold_right1_dep f init (fun a => f _ a init) l.\n\n  Definition list_to_vector {A} (l:list A) : Vector A (length l)\n    := list_fold_right_dep (@vcons _) vnil l.\n\n  Definition vector_to_list {A} {n} (v:Vector A n) : list A\n    := vector_fold_right cons nil v.\n  \n  Definition matrix_to_list_list {T} {m n} (v:Matrix T m n) : (list (list T))\n    := vector_to_list (fun i => vector_to_list (v i)).\n\n  Definition matrix_to_list {T} {m n} (v:Matrix T m n) : (list T)\n    := concat (matrix_to_list_list v).\n\n  Definition vseq start len : Vector nat len\n    := eq_rect _ _ (list_to_vector (seq start len)) _ (seq_length _ _).\n\n  Definition vector_zip {A B} {m:nat} (v1:Vector A m) (v2:Vector B m) : Vector (A*B) m\n    := fun i => (v1 i, v2 i).\n\n  Definition matrix_zip {A B} {m n:nat} (mat1:Matrix A m n) (mat2:Matrix B m n) : Matrix (A*B) m n\n    := let mat12:Vector (Vector A n*Vector B n) m := vector_zip mat1 mat2 in\n       vmap (fun '(a,b) => vector_zip a b) mat12.\n  \n  Definition vector_split {A B} {m:nat} (v:Vector (A*B) m) : Vector A m * Vector B m\n    := (fun i => fst (v i), fun i => snd (v i)).\n\n  Program Definition vtake {A} {m:nat} (v:Vector (A) m) (n:nat) (pf:(n<=m)%nat) : Vector A n\n    := fun i => v i.\n  Next Obligation.\n    omega.\n  Defined.\n  \n  Program Definition vskip {A} {m:nat} (v:Vector (A) m) (n:nat) (pf:(n<=m)%nat) : Vector A (m-n)\n    := fun i => v (i+n).\n  Next Obligation.\n    omega.\n  Defined.\n\n  Definition transpose {A} {n m:nat} (mat:Matrix A n m) :=\n    fun i j => mat j i.\n\n  Definition vec_eq {A} {m:nat} (x y:Vector A m) := forall i, x i = y i.\n  Notation \"x =v= y\" := (vec_eq x y) (at level 70).\n  \n  (* If we are willing to assume an axiom *)\n  Lemma vec_eq_eq {A} {m:nat} (x y:Vector A m) : vec_eq x y -> x = y.\n  Proof.\n    intros.\n    apply FunctionalExtensionality.functional_extensionality.\n    apply H.\n  Qed.\n\n  Lemma index_pf_irrel n m pf1 pf2 : \n    exist (fun n' : nat => (n' < n)%nat) m pf1 =\n    exist (fun n' : nat => (n' < n)%nat) m pf2.\n    f_equal.\n    apply digit_pf_irrel.\n  Qed.\n\n  Ltac index_prover := erewrite index_pf_irrel; reflexivity.\n\n  Lemma vector_Sn_split {T} {n} (v:Vector T (S n)) :\n    v =v= vcons (vlast v) (vdrop_last v).\n  Proof.\n    intros [i pf].\n    unfold vcons, vlast, vdrop_last.\n    destruct (Nat.eq_dec i n)\n    ; subst\n    ; f_equal\n    ; apply index_pf_irrel.\n  Qed.\n\n  Lemma vector_split_zip {A B} {m:nat} (v:Vector (A*B) m) :\n    let '(va,vb):=vector_split v in vector_zip va vb =v= v.\n  Proof.\n    simpl.\n    intros i.\n    vm_compute.\n    now destruct (v i).\n  Qed.\n\n  Lemma split_vector_zip {A B} {m:nat} (va:Vector A m) (vb:Vector B m) :\n    vector_split (vector_zip va vb) = (va,vb).\n  Proof.\n    vm_compute.\n    f_equal.\n  Qed.\n\n  Definition vlconcat {A n} (v:Vector (list A) n) : list A\n    := concat (vector_to_list v).\n\n  Definition vlconcat_map {A B n} (f:A->list B) (v:Vector A n) : list B\n    := vlconcat (vmap f v).\n\n  Definition vin {A n} (x:A) (v:Vector A n) : Prop\n    := exists i, v i = x.\n\n  (*\n  Lemma nth_In :\n    forall (n:nat) (l:list A) (d:A), n < length l -> In (nth n l d) l.\n\n  Lemma In_nth l x d : In x l ->\n    exists n, n < length l /\\ nth n l d = x.\n   *)\n\n  Notation \"x =v= y\" := (vec_eq x y) (at level 70).\n\n  Lemma vector_fold_right_dep_bounded_pf_ext {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) {m:nat} (v:Vector B m) bound pf1 pf2 :\n    vector_fold_right_bounded_dep f init v bound pf1 = vector_fold_right_bounded_dep f init v bound pf2.\n  Proof.\n    revert pf1 pf2.\n    induction bound; trivial; intros.\n    simpl.\n    f_equal.\n    f_equal.\n    apply index_pf_irrel.\n    trivial.\n  Qed.\n  \n  Lemma vector_fold_right_dep_bounded_ext {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) {m:nat} (x y:Vector B m) bound pf :\n    x =v= y -> vector_fold_right_bounded_dep f init x bound pf = vector_fold_right_bounded_dep f init y bound pf.\n  Proof.\n    intros eqq.\n    induction bound; simpl; congruence.\n  Qed.\n\n  Lemma vector_fold_right_dep_bounded_cut_down {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) {m:nat} (x:Vector B (S m)) bound pf1 pf2 :\n    vector_fold_right_bounded_dep f init x bound pf1 = vector_fold_right_bounded_dep f init (vdrop_last x) bound pf2.\n  Proof.\n    induction bound; simpl; trivial.\n    f_equal.\n    - f_equal.\n      apply index_pf_irrel.\n    - apply IHbound.\n  Qed.\n\n  Lemma vector_fold_right_dep_ext {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) {m:nat} {x y:Vector B m} :\n    x =v= y -> vector_fold_right_dep f init x = vector_fold_right_dep f init y.\n  Proof.\n    apply vector_fold_right_dep_bounded_ext.\n  Qed.\n\n  Lemma vector_fold_right_ext {A:Type} {B} (f:B->A->A) (init:A) {m:nat} {x y:Vector B m} :\n    x =v= y -> vector_fold_right f init x = vector_fold_right f init y.\n  Proof.\n    apply (@vector_fold_right_dep_ext (fun _ => A)).\n  Qed.\n\n  Lemma veq_refl {T} {n} (x:Vector T n) : x =v= x.\n  Proof.\n    intros i; reflexivity.\n  Qed.\n\n  Lemma veq_sym {T} {n} {x y:Vector T n} : x =v= y -> y =v= x.\n  Proof.\n    intros eqq i; symmetry; trivial.\n  Qed.\n\n  Lemma veq_trans {T} {n} {x y z:Vector T n} : x =v= y -> y =v= z -> x =v= z.\n  Proof.\n    intros eqq1 eqq2 i; etransitivity; eauto.\n  Qed.\n\n  Lemma vcons_proper {T} {n} a b (x y:Vector T n) : a = b -> x =v= y -> vcons a x =v= vcons b y.\n  Proof.\n    intros; subst.\n    intros [i pf].\n    unfold vcons.\n    destruct (Nat.eq_dec i n); simpl; trivial.\n  Qed.\n\n  Lemma vdrop_last_proper {T} {n} (x y:Vector T (S n)) : x =v= y -> vdrop_last x =v= vdrop_last y.\n  Proof.\n    intros eqq [i pf].\n    apply eqq.\n  Qed.\n\n  Lemma vlast_vcons {T} {n} x (d:Vector T n) : vlast (vcons x d) = x.\n  Proof.\n    unfold vlast, vcons.\n    match_destr; congruence.\n  Qed.\n\n  Lemma vdrop_last_vcons {T} {n} x (d:Vector T n) : vdrop_last (vcons x d) = d.\n  Proof.\n    unfold vdrop_last, vcons.\n    apply vec_eq_eq; intros [i pf].\n    match_destr; [omega | ].\n    erewrite index_pf_irrel; eauto.\n  Qed.\n\n  Lemma vector_fold_right_dep_0 {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) (v:Vector B 0) : \n    vector_fold_right_dep f init v = init.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma vector_fold_right_dep_Sn {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) {m:nat} (v:Vector B (S m)) : \n    vector_fold_right_dep f init v = f m (vlast v) (vector_fold_right_dep f init (vdrop_last v)).\n  Proof.\n    rewrite (vector_fold_right_dep_ext _ _ (vector_Sn_split v)).\n    unfold vector_fold_right_dep.\n    simpl.\n    destruct (Nat.eq_dec m m) ; [ | congruence].\n    f_equal. \n    erewrite vector_fold_right_dep_bounded_pf_ext.\n    erewrite vector_fold_right_dep_bounded_cut_down.\n    apply vector_fold_right_dep_bounded_ext.\n    apply vdrop_last_proper.\n    apply veq_sym.\n    apply vector_Sn_split.\n    Unshelve.\n    omega.\n  Qed.\n\n  Lemma vector_fold_right_Sn {A:Type} {B} (f:B->A->A) (init:A%nat) {m:nat} (v:Vector B (S m)) : \n    vector_fold_right f init v = f (vlast v) (vector_fold_right f init (vdrop_last v)).\n  Proof.\n    unfold vector_fold_right.\n    apply (@vector_fold_right_dep_Sn (fun _ => A)).\n  Qed.\n\n  Lemma vector_fold_right_dep_vcons {A:nat->Type} {B}\n        (f:forall n,B->A n->A (S n)) (init:A 0%nat) {m:nat} \n        x (v:Vector B m) :\n    vector_fold_right_dep f init (vcons x v) = f m x (vector_fold_right_dep f init v).\n  Proof.\n    now rewrite vector_fold_right_dep_Sn, vlast_vcons, vdrop_last_vcons.\n  Qed.\n\n  Lemma vector_fold_right_vcons {A:Type} {B}\n        (f:B->A->A) (init:A) {m:nat} \n        x (v:Vector B m)  :\n    vector_fold_right f init (vcons x v) = f x (vector_fold_right f init v).\n  Proof.\n    apply (vector_fold_right_dep_vcons (fun _ => f)).\n  Qed.\n\n  Lemma vector_fold_right1_dep_bounded_ext {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) sing {m:nat} (x y:Vector B m) bound pf :\n    x =v= y -> vector_fold_right1_bounded_dep f init sing x bound pf = vector_fold_right1_bounded_dep f init sing y bound pf.\n  Proof.\n    intros eqq.\n    induction bound; simpl; trivial.\n    destruct bound; trivial.\n    - congruence.\n    - f_equal.\n      + erewrite index_pf_irrel; eauto.\n      + apply IHbound.\n    Unshelve.\n    omega.\n  Qed.\n\n  Lemma vector_fold_right1_dep_ext {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) sing {m:nat} {x y:Vector B m} :\n    x =v= y -> vector_fold_right1_dep f init sing x = vector_fold_right1_dep f init sing y.\n  Proof.\n    apply vector_fold_right1_dep_bounded_ext.\n  Qed.\n\n  Lemma vector_fold_right1_ext {A:Type} {B} (f:B->A->A) (init:A) sing {m:nat} {x y:Vector B m} :\n    x =v= y -> vector_fold_right1 f init sing x = vector_fold_right1 f init sing y.\n  Proof.\n    apply (@vector_fold_right1_dep_ext (fun _ => A)).\n  Qed.\n\n  Lemma vector_fold_right1_dep_bounded_f_ext {A:nat->Type} {B} (f1 f2:forall n,B->A n->A (S n)) \n        (init:A 0%nat) sing {m:nat} (v:Vector B m) bound pf :\n    (forall n pf a, f1 n (v (exist _ n pf)) a = f2 n (v (exist _ n pf)) a) -> vector_fold_right1_bounded_dep f1 init sing v bound pf = vector_fold_right1_bounded_dep f2 init sing v bound pf.\n  Proof.\n    intros eqq.\n    induction bound; simpl; trivial.\n    destruct bound; trivial.\n    f_equal.\n    eauto.\n  Qed.\n\n  Lemma vector_fold_right1_dep_f_ext {A:nat->Type} {B} (f1 f2:forall n,B->A n->A (S n)) \n        (init:A 0%nat) sing {m:nat} {v:Vector B m} :\n    (forall n pf a, f1 n (v (exist _ n pf)) a = f2 n (v (exist _ n pf)) a) -> vector_fold_right1_dep f1 init sing v = vector_fold_right1_dep f2 init sing v.\n  Proof.\n    apply vector_fold_right1_dep_bounded_f_ext.\n  Qed.\n\n  Lemma vector_fold_right1_f_ext {A:Type} {B} (f1 f2:B->A->A) (init:A) sing {m:nat} {v:Vector B m} :\n   (forall i a, f1 (v i) a = f2 (v i) a) -> vector_fold_right1 f1 init sing v = vector_fold_right1 f2 init sing v.\n  Proof.\n    intros.\n    apply (@vector_fold_right1_dep_f_ext (fun _ => A)); eauto.\n  Qed.\n\n  Lemma vector_fold_right1_dep_0 {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) sing (v:Vector B 0) : \n    vector_fold_right1_dep f init sing v = init.\n  Proof.\n    reflexivity.\n  Qed.\n  \n  Lemma vector_fold_right1_dep_1 {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) sing (v:Vector B 1) : \n    vector_fold_right1_dep f init sing v = sing (v (exist _ 0 Nat.lt_0_1)).\n  Proof.\n    unfold vector_fold_right1_dep.\n    simpl.\n    f_equal.\n    erewrite index_pf_irrel; eauto.\n  Qed.\n\n    Lemma vector_fold_right1_bounded_dep_pf_ext {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) sing {m:nat} (v:Vector B m) bound pf1 pf2 :\n    vector_fold_right1_bounded_dep f init sing v bound pf1 = vector_fold_right1_bounded_dep f init sing v bound pf2.\n  Proof.\n    revert pf1 pf2.\n    induction bound; trivial; intros.\n    simpl.\n    destruct bound; simpl.\n    - f_equal; index_prover.\n    - f_equal; try index_prover.\n      apply IHbound.\n  Qed.\n\n  Lemma vector_fold_right1_bounded_dep_SSn {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) sing {m:nat} (v:Vector B (S m)) bound pf1 pf2 pf4: \n    vector_fold_right1_bounded_dep f init sing v (S (S bound)) pf1 = f _ (v (exist _ (S bound) pf4)) (vector_fold_right1_bounded_dep f init sing v (S bound) pf2).\n  Proof.\n    revert pf4.\n    induction bound; simpl; trivial; intros.\n    f_equal; try index_prover.\n    simpl in *.\n    f_equal; try index_prover.\n    destruct bound.\n    - f_equal; try index_prover.\n    - destruct bound.\n      apply IHbound.\n      f_equal; try index_prover.\n      f_equal; try index_prover.\n      apply vector_fold_right1_bounded_dep_pf_ext.\n  Qed.\n\n  Lemma vector_fold_right1_bounded_dep_relevant {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) sing {m1:nat} (v1:Vector B m1) {m2:nat} (v2:Vector B m2) bound pf1 pf2:\n    (forall i, i <= bound -> forall pf1 pf2, v1 (exist _ i pf1) = v2 (exist _ i pf2)) ->\n    vector_fold_right1_bounded_dep f init sing v1 bound pf1 =\n    vector_fold_right1_bounded_dep f init sing v2 bound pf2.\n  Proof.\n    intros eqq.\n    induction bound; simpl; trivial.\n    destruct bound; simpl.\n    - f_equal; try index_prover.\n      apply eqq.\n      omega.\n    - f_equal.\n      + apply eqq.\n        omega.\n      + apply IHbound; auto.\n  Qed.\n\n  Lemma vector_fold_right1_bounded_dep_droplast {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) sing {m:nat} (v:Vector B (S m)) bound pf1 pf2:\n    bound < S m ->\n    vector_fold_right1_bounded_dep f init sing (vdrop_last v) bound pf1 =\n    vector_fold_right1_bounded_dep f init sing v bound pf2.\n  Proof.\n    intros.\n    apply vector_fold_right1_bounded_dep_relevant; intros.\n    unfold vdrop_last.\n    index_prover.\n  Qed.\n  \n  Lemma vector_fold_right1_dep_SSn {A:nat->Type} {B} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) sing {m:nat} (v:Vector B (S (S m))) : \n    vector_fold_right1_dep f init sing v = f (S m) (vlast v) (vector_fold_right1_dep f init sing (vdrop_last v)).\n  Proof.\n    unfold vector_fold_right1_dep.\n    unfold vlast.\n    erewrite vector_fold_right1_bounded_dep_SSn.\n    f_equal.\n    erewrite vector_fold_right1_bounded_dep_droplast; trivial.\n    omega.\n    Unshelve.\n    omega.\n  Qed.\n\n  Lemma vector_fold_right_bounded_dep_ind {A:nat->Type} {B} {P:forall m, A m -> Prop} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat)\n        (finit : P 0 init)\n        (ff: forall n b v, P n v -> P (S n) (f n b v)) :\n    forall {m:nat} (v:Vector B m) bound pf, P bound (vector_fold_right_bounded_dep f init v bound pf).\n  Proof.\n    intros m v bound pf.\n    revert m pf v.\n    induction bound; simpl; trivial; intros.\n    apply ff.\n    apply IHbound.\n  Qed.\n\n  Lemma vector_fold_right_dep_ind {A:nat->Type} {B} {P:forall m, A m -> Prop} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) \n        (finit : P 0 init)\n      (ff: forall n b v, P n v -> P (S n) (f n b v)) :\n    forall {m:nat} (v:Vector B m), P m (vector_fold_right_dep f init v).\n  Proof.\n    intros.\n    apply vector_fold_right_bounded_dep_ind; trivial.\n  Qed.\n\n  Lemma vector_fold_right_ind {A:Type} {B} {P:A -> Prop} (f:B->A ->A) \n        (init:A)\n        (finit : P init)\n      (ff: forall b v, P v -> P (f b v)) :\n    forall {m:nat} (v:Vector B m), P (vector_fold_right f init v).\n  Proof.\n    intros.\n    apply (vector_fold_right_dep_ind (P:=fun _ => P)); trivial.\n  Qed.\n\n\n  Lemma vector_fold_right1_bounded_dep_ind {A:nat->Type} {B} {P:forall m, A m -> Prop} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) sing\n        (finit : P 0 init)\n        (fsing: forall b, P 1 (sing b))\n        (ff: forall n b v, P n v -> P (S n) (f n b v)) :\n    forall {m:nat} (v:Vector B m) bound pf, P bound (vector_fold_right1_bounded_dep f init sing v bound pf).\n  Proof.\n    intros m v bound pf.\n    revert m pf v.\n    induction bound; simpl; trivial; intros.\n    destruct bound; simpl; trivial.\n    apply ff.\n    apply IHbound.\n  Qed.\n\n  Lemma vector_fold_right1_dep_ind {A:nat->Type} {B} {P:forall m, A m -> Prop} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) sing\n        (finit : P 0 init)\n       (fsing: forall b, P 1 (sing b))\n      (ff: forall n b v, P n v -> P (S n) (f n b v)) :\n    forall {m:nat} (v:Vector B m), P m (vector_fold_right1_dep f init sing v).\n  Proof.\n    intros.\n    apply vector_fold_right1_bounded_dep_ind; trivial.\n  Qed.\n\n  Lemma vector_fold_right1_ind {A:Type} {B} {P:A -> Prop} (f:B->A ->A) \n        (init:A) sing\n        (finit : P init)\n       (fsing: forall b, P (sing b))\n      (ff: forall b v, P v -> P (f b v)) :\n    forall {m:nat} (v:Vector B m), P (vector_fold_right1 f init sing v).\n  Proof.\n    intros.\n    apply (vector_fold_right1_dep_ind (P:=fun _ => P)); trivial.\n  Qed.\n  \n  Lemma vector_to_list_In {A} (x:A) {n} (v:Vector A n) :\n    vin x v -> In x (vector_to_list v).\n  Proof.\n    induction n.\n    - intros [[i pf] eqqi].\n      omega.\n    - intros [[i pf] eqqi].\n      unfold vector_to_list in *.\n      rewrite vector_fold_right_Sn; simpl.\n      destruct (Nat.eq_dec i n).\n      + left.\n        unfold vlast.\n        subst.\n        erewrite index_pf_irrel; eauto.\n      + right.\n        apply IHn.\n        eexists (exist _ i _).\n        simpl.\n        erewrite index_pf_irrel; eauto.\n        \n        Unshelve.\n        simpl; omega.\n  Qed.\n\n  Lemma vin_cons {A} x (a:A) {n} {v:Vector A n} : vin x (vcons a v) <-> (x = a \\/ vin x v).\n  Proof.\n    unfold vcons.\n    split.\n    - intros [[i pf] eqq].\n      destruct (Nat.eq_dec i n).\n      + subst; eauto.\n      + right.\n        eexists (exist _ i _).\n        erewrite index_pf_irrel; eauto.\n        \n        Unshelve.\n        simpl; omega.\n    - intros [eqq | inn].\n      + red.\n        eexists (exist _ n _).\n        destruct (Nat.eq_dec n n); congruence.\n      + destruct inn as [[i pf] eqq].\n        eexists (exist _ i _).\n        destruct (Nat.eq_dec i n); [omega | ].\n        erewrite index_pf_irrel; eauto.\n        Unshelve.\n        simpl; omega.\n        simpl; omega.\n  Qed.        \n\n  Lemma vin_proper {A} (x:A) {n} {v1 v2:Vector A n} : v1 =v= v2 -> vin x v1 <-> vin x v2.\n  Proof.\n    revert v1 v2.\n    cut (forall (v1 v2:Vector A n), v1 =v= v2 -> vin x v1 -> vin x v2).\n    { intros; split; [eauto| ].\n      apply veq_sym in H0; eauto.\n    }\n    intros v1 v2 eqq1 [i eqq2].\n    exists i.\n    rewrite <- eqq1; trivial.\n  Qed.\n  \n  Lemma vector_to_list_vin {A} (x:A) {n} (v:Vector A n) :\n    In x (vector_to_list v) -> vin x v.\n  Proof.\n    unfold vector_to_list.\n    revert v.\n    induction n; [simpl; tauto|].\n    intros v inn.\n    rewrite vector_fold_right_Sn in inn.\n    destruct inn as [eqq | inn].\n    - eexists.\n      apply eqq.\n    - apply (@vin_proper A _ (S n) _ _ (vector_Sn_split v)).\n      apply vin_cons.\n      eauto.\n  Qed.\n\n\n  Lemma vdrop_last_i {A} {n} (v:Vector A (S n)) i pf1 pf2 :\n    vdrop_last v (exist (fun n' : nat => (n' < n)%nat) i pf1) =\n    v (exist (fun n' : nat => (n' < S n)%nat) i pf2).\n  Proof.\n    unfold vdrop_last.\n    erewrite index_pf_irrel; eauto.\n  Qed.\n\n  Lemma vin_vlast {A n} (v:Vector A (S n)) : vin (vlast v) v.\n  Proof.\n    unfold vin, vlast.\n    eauto.\n  Qed.\n\n  Lemma vin_vdrop_last {A n} x (v:Vector A (S n)) : vin x (vdrop_last v) -> vin x v.\n  Proof.\n    unfold vin, vdrop_last.\n    intros [[??]?].\n    eauto.\n  Qed.\n\n  Lemma vmap_nth {A B : Type} (f : A -> B) {n} (v : Vector A n) i : \n    vmap f v i = f (v i).\n  Proof.\n    revert v i.\n    unfold vmap.\n    induction n; intros v [i pf].\n    - omega.\n    - rewrite vector_fold_right_dep_Sn.\n      simpl.\n      destruct (Nat.eq_dec i n).\n      + subst.\n        unfold vlast.\n        erewrite index_pf_irrel; eauto.\n      + specialize (IHn (vdrop_last v)).\n        unfold vdrop_last.\n        erewrite index_pf_irrel; rewrite IHn.\n        erewrite vdrop_last_i; eauto.\n        Unshelve.\n        omega.\n  Qed.\n\n  Lemma mmap_nth {A B : Type} (f : A -> B) {m n} (mat : Matrix A m n) i j : \n    mmap f mat i j = f (mat i j).\n  Proof.\n    unfold mmap.\n    now repeat rewrite vmap_nth.\n  Qed.\n     \n\n  Lemma vmap_ext {A B n} (f1 f2:A->B) (df:Vector A n) :\n    (forall x, vin x df -> f1 x = f2 x) ->\n    vmap f1 df = vmap f2 df.\n  Proof.\n    unfold vmap.\n    induction n.\n    - reflexivity.\n    - intros.\n      repeat rewrite vector_fold_right_dep_Sn.\n      f_equal.\n      + eapply H.\n        eapply vin_vlast.\n      + rewrite IHn; trivial.\n        intros.\n        eapply H.\n        now apply vin_vdrop_last.\n  Qed.\n\n  \n\n  Lemma vnil0 {A} (v:Vector A 0) : v = vnil.\n  Proof.\n    apply FunctionalExtensionality.functional_extensionality.\n    intros [i pf].\n    omega.\n  Qed.\n\n  Lemma vmap_id {A n} (df:Vector A n) :\n    vmap (fun x => x) df = df.\n  Proof.\n    unfold vmap.\n    induction n; simpl.\n    - now rewrite vnil0, vector_fold_right_dep_0.\n    - rewrite vector_fold_right_dep_Sn, IHn.\n      apply vec_eq_eq.\n      apply veq_sym.\n      apply vector_Sn_split.\n  Qed.\n\n  Definition bounded_seq_bounded (start len : nat) : forall bound, bound<=len -> list {n':nat | n' < start+len}%nat.\n  Proof.\n    refine (fix F bound :=\n             match bound as bound_ return bound_ <= len -> list {n':nat | n' < start+len}%nat with\n             | 0 => fun _ => nil\n             | S bound' => fun _ => exist _ (start + len-(S bound')) _ :: F bound' _\n             end); omega.\n  Defined.\n\n  Lemma bounded_seq_bounded_ext (start len : nat) (bound:nat) (pf1 pf2:bound<=len) :\n    bounded_seq_bounded start len bound pf1 = bounded_seq_bounded start len bound pf2.\n  Proof.\n    induction bound; simpl; trivial.\n    f_equal.\n    - eapply index_pf_irrel; eauto.\n    - eapply IHbound.\n  Qed.\n\n  Definition bounded_seq (start len : nat) : list {n':nat | n' < start+len}%nat\n    := bounded_seq_bounded start len len (le_refl _).\n\n  Definition bounded_seq0 len : list {n':nat | n' < len}%nat := bounded_seq 0 len.\n\n  Lemma bounded_seq_bounded_domain start len (bound:nat) (pf:bound<=len) : map (@proj1_sig _ _) (bounded_seq_bounded start len bound pf) = seq (start+(len-bound)) bound.\n  Proof.\n    revert start.\n    induction bound; simpl; intros start; trivial.\n    rewrite IHbound.\n    f_equal.\n    - omega.\n    - f_equal.\n      omega.\n  Qed.\n\n  Lemma bounded_seq_domain start len : map (@proj1_sig _ _) (bounded_seq start len) = seq start len.\n  Proof.\n    unfold bounded_seq.\n    rewrite bounded_seq_bounded_domain.\n    f_equal.\n    omega.\n  Qed.\n  \n  Lemma bounded_seq_strongly_sorted start len:\n    StronglySorted (fun x y => proj1_sig x < proj1_sig y) (bounded_seq start len).\n  Proof.\n    apply StronglySorted_compose.\n    rewrite bounded_seq_domain.\n    apply StronglySorted_seq.\n  Qed.\n\n  Lemma bounded_seq_break_at start len x :\n    proj1_sig x >= start ->\n    exists b c, bounded_seq start len = b++x::c /\\ Forall (fun y => (proj1_sig y) < (proj1_sig x)) b /\\ Forall (fun y => (proj1_sig x) < (proj1_sig y)) c.\n  Proof.\n    intros xge.\n    apply (StronglySorted_break (fun y x => (proj1_sig y) < (proj1_sig x)) (bounded_seq start len)).\n    - apply bounded_seq_strongly_sorted.\n    - destruct x as [x pf]; simpl in *.\n      assert (inn:In x (map (@proj1_sig _ _) (bounded_seq start len))).\n      + rewrite bounded_seq_domain.\n        apply in_seq.\n        omega.\n      + apply in_map_iff in inn.\n        destruct inn as [[??] [??]].\n        subst.\n        erewrite index_pf_irrel; eauto.\n  Qed.\n  \n  Definition vforall {A n} (P:A->Prop) (v:Vector A n) :=\n    vector_fold_right (fun x p => P x /\\ p) True v.\n\n  Lemma vforall_forall {A n} (P:A->Prop) (v:Vector A n) :\n    vforall P v <-> forall i, P (v i).\n  Proof.\n    unfold vforall.\n    split.\n    - induction n.\n      + intros ? [??].\n        omega.\n      + rewrite vector_fold_right_Sn.\n        intros [Plast Pdrop].\n        intros [i pf].\n        destruct (Nat.eq_dec i n).\n        * unfold vlast in Plast.\n          subst.\n          erewrite index_pf_irrel; eauto.\n        * assert (pf2:(i < n)%nat) by omega.\n          specialize (IHn _ Pdrop (exist _ i pf2)).\n          erewrite index_pf_irrel; eauto.\n    - induction n.\n      + vm_compute; trivial.\n      + rewrite vector_fold_right_Sn.\n        intros.\n        split.\n        * eauto.\n        * eapply IHn.\n          intros [i pf].\n          assert (pf2 : (i < S n)%nat) by omega.\n          specialize (H (exist _ i pf2)).\n          simpl in *.\n          erewrite index_pf_irrel; eauto.\n  Qed.\n\n  Lemma vectoro_to_ovector_forall_some_f {A n} {vo:Vector (option A) n} {v:Vector A n} :\n    vectoro_to_ovector vo = Some v ->\n    (forall i, vo i = Some (v i)).\n  Proof.\n    unfold vectoro_to_ovector.\n    induction n; simpl.\n    - intros ? [??]; omega.\n    - rewrite vector_fold_right_dep_Sn.\n      intros eqq.\n      apply some_lift2 in eqq.\n      destruct eqq as [x [y eqq1 [eqq2 eqq3]]].\n      subst.\n      intros [i pf].\n      rewrite vector_Sn_split.\n      specialize (IHn _ _ eqq2).\n      rewrite eqq1.\n      unfold vcons.\n      destruct (Nat.eq_dec i n); trivial.\n  Qed.\n\n  Lemma vectoro_to_ovector_forall_some_b {A n} (vo:Vector (option A) n) (v:Vector A n) :\n    (forall i, vo i = Some (v i)) ->\n    exists v', vectoro_to_ovector vo = Some v' /\\ v =v= v'.\n  Proof.\n    unfold vectoro_to_ovector.\n    induction n; simpl.\n    - intros eqq.\n      unfold vector_fold_right_dep.\n      simpl.\n      exists vnil; split; trivial.\n      intros [??]; omega.\n    - rewrite vector_fold_right_dep_Sn.\n      intros eqq.\n      specialize (IHn (vdrop_last vo) (vdrop_last v)).\n      destruct IHn as [v' [eqq2 eqq3]].\n      + intros [i pf].\n        simpl; eauto.\n      + rewrite eqq2.\n        unfold vlast.\n        rewrite eqq.\n        simpl.\n        eexists; split; [reflexivity | ].\n        eapply veq_trans; [eapply (vector_Sn_split v) | ].\n        apply vcons_proper; simpl; trivial.\n  Qed.\n\n  Lemma vectoro_to_ovector_forall_some_b_strong {A n} (vo:Vector (option A) n) (v:Vector A n) :\n    (forall i, vo i = Some (v i)) ->\n    vectoro_to_ovector vo = Some v.\n  Proof.\n    intros.\n    destruct (vectoro_to_ovector_forall_some_b _ _ H) as [? [??]].\n    rewrite H0.\n    f_equal.\n    apply FunctionalExtensionality.functional_extensionality.\n    intros.\n    symmetry.\n    apply H1.\n  Qed.\n\n  Lemma vectoro_to_ovector_not_none {A n} (vo : Vector (option A) n) :\n    (forall i, vo i <> None) -> vectoro_to_ovector vo <> None.\n  Proof.\n    unfold vectoro_to_ovector.\n    induction n; simpl.\n    - intros eqq.\n      unfold vector_fold_right_dep.\n      simpl.\n      congruence.\n    - rewrite vector_fold_right_dep_Sn.\n      intros eqq.\n      specialize (IHn (vdrop_last vo)).\n      unfold lift2 in *.\n      repeat match_option.\n      + elim IHn; trivial.\n        unfold vdrop_last.\n        now intros [i pf].\n      + unfold vlast in eqq0.\n        elim (eqq _ eqq0).\n  Qed.\n\n  Lemma vectoro_to_ovector_exists_None {A n} {vo:Vector (option A) n} :\n    vectoro_to_ovector vo = None ->\n    {i | vo i = None}.\n  Proof.\n    unfold vectoro_to_ovector.\n    induction n; simpl.\n    - unfold vector_fold_right_dep; simpl.\n      discriminate.\n    - rewrite vector_fold_right_dep_Sn.\n      intros eqq.\n      specialize (IHn (vdrop_last vo)).\n      unfold lift2 in *.\n      repeat match_option_in eqq.\n      + destruct (IHn eqq1) as [[i pf] ?].\n        eauto.\n      + eauto.\n  Qed.\n\n  Lemma vectoro_to_ovector_None_None {A n} {vo:Vector (option A) n} i :\n    vo i = None ->\n    vectoro_to_ovector vo = None.\n  Proof.\n    destruct i as [i pf].\n    unfold vectoro_to_ovector.\n    induction n; simpl.\n    - omega.\n    - intros eqq.\n      rewrite vector_fold_right_dep_Sn.\n      unfold vlast.\n      destruct (Nat.eq_dec i n).\n      + subst.\n        erewrite index_pf_irrel.\n        rewrite eqq; simpl; trivial.\n      + unfold lift2.\n        erewrite IHn; simpl.\n        * match_destr.\n        * erewrite index_pf_irrel; eauto.\n   Unshelve.\n   omega.\n  Qed.\n\n  Definition vfirstn {T} {n} (v:Vector T n) m (pf:(m<=n)%nat): Vector T m.\n  Proof.\n    intros [i pf2].\n    apply v.\n    exists i.\n    eapply NPeano.Nat.lt_le_trans; eassumption.\n  Defined.\n\n  Lemma vfirstn0 {T} {n} (v:Vector T n) pf : vfirstn v 0 pf = vnil.\n  Proof.\n    apply vec_eq_eq; intros [??]; simpl.\n    omega.\n  Qed.\n\n  Definition vfirstn_eq {T} {n} (v:Vector T n) pf : vfirstn v n pf = v.\n  Proof.\n    unfold vfirstn.\n    apply FunctionalExtensionality.functional_extensionality; intros [??].\n    erewrite index_pf_irrel; eauto.\n  Qed.\n\n  Lemma vfirstn_vdrop_last {T} {n} (v:Vector T n) bound pf pf2 :\n      vdrop_last (vfirstn v (S bound) pf) = vfirstn v bound pf2.\n  Proof.\n    apply FunctionalExtensionality.functional_extensionality; intros [??]; simpl.\n    erewrite index_pf_irrel; eauto.\n  Qed.\n\n  \n  Lemma vlast_vfirstn {T} {n} (d:Vector T n) bound pf pf2 :\n    (vlast (vfirstn d (S bound) pf)) = d ((exist _ bound pf2)).\n  Proof.\n    unfold vfirstn, vlast.\n    erewrite index_pf_irrel; eauto.\n  Qed.\n\n  Lemma vector_fold_right1_bounded_dep_gen_ind {A:nat->Type} {B} {P:forall m, Vector B m -> A m -> Prop} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) sing\n        (finit : P 0%nat vnil init)\n        (fsing: forall b, P 1%nat (vcons b vnil) (sing b))\n        (ff: forall n b v r, P n v r -> P (S n) (vcons b v) (f n b r)) :\n    forall {m:nat} (v:Vector B m) bound pf, P bound (vfirstn v _ pf) (vector_fold_right1_bounded_dep f init sing v bound pf).\n  Proof.\n    intros m v bound pf.\n    revert m pf v.\n    induction bound; simpl; trivial; intros.\n    - generalize (vfirstn v 0 pf); intros.\n      rewrite (vnil0 v0); trivial.\n    - destruct m; [omega | ].\n      destruct bound; simpl; trivial.\n      + replace (vfirstn v 1 pf) with (vcons (v (exist (fun n' : nat => (n' < S m)%nat) 0%nat pf)) vnil)\n        ; trivial.\n        apply FunctionalExtensionality.functional_extensionality; intros [??]; simpl.\n        destruct x; [ | omega].\n        simpl.\n        erewrite index_pf_irrel; eauto.\n      + assert (pf2:(S bound <= S m)%nat) by omega.\n        replace (vfirstn v (S (S bound)) pf)\n          with (vcons (v (exist (fun n' : nat => (n' < S m)%nat) (S bound) pf)) (vfirstn v (S bound) pf2)).\n        * apply ff.\n          replace (match bound as bound1' return (A bound1' -> (S bound1' <= S m)%nat -> A (S bound1')) with\n                   | 0%nat =>\n                     fun (_ : A 0%nat) (pf1 : (1 <= S m)%nat) =>\n                       sing (v (exist (fun n' : nat => (n' < S m)%nat) 0%nat pf1))\n                   | S bound2 =>\n                     fun (an' : A (S bound2)) (_ : (S (S bound2) <= S m)%nat) =>\n                       f (S bound2) (v (exist (fun n' : nat => (n' < S m)%nat) bound (le_Sn_le (S bound) (S m) pf))) an'\n                   end\n                     (vector_fold_right1_bounded_dep f init sing v bound\n                                                     (le_Sn_le bound (S m) (le_Sn_le (S bound) (S m) pf))) (le_Sn_le (S bound) (S m) pf)) with (vector_fold_right1_bounded_dep f init sing v (S bound) pf2); try eapply IHbound.\n          clear.\n          destruct bound; simpl.\n          -- erewrite index_pf_irrel; eauto.\n          -- f_equal.\n             ++ erewrite index_pf_irrel; eauto.\n             ++ destruct bound.\n                ** erewrite index_pf_irrel; eauto.\n                ** { f_equal.\n                     -- erewrite index_pf_irrel; eauto.\n                     -- apply vector_fold_right1_bounded_dep_pf_ext.\n                   } \n        * generalize (vector_Sn_split (vfirstn v (S (S bound)) pf)); intros eqq.\n          apply vec_eq_eq in eqq.\n          rewrite eqq.\n          f_equal.\n          -- unfold vlast; simpl.\n             erewrite index_pf_irrel; eauto.\n          -- erewrite vfirstn_vdrop_last; eauto.\n  Qed.\n\n  Lemma vector_fold_right1_dep_gen_ind {A:nat->Type} {B} {P:forall m, Vector B m -> A m -> Prop} (f:forall n,B->A n->A (S n)) \n        (init:A 0%nat) sing\n        (finit : P 0%nat vnil init)\n        (fsing: forall b, P 1%nat (vcons b vnil) (sing b))\n        (ff: forall n b v r, P n v r -> P (S n) (vcons b v) (f n b r)) :\n    forall {m:nat} (v:Vector B m), P m v (vector_fold_right1_dep f init sing v).\n  Proof.\n    intros.\n    rewrite <- (vfirstn_eq v (le_refl m)) at 1.\n    apply vector_fold_right1_bounded_dep_gen_ind; trivial.\n  Qed.\n\n  Program Definition vapp {A} {m n} (v1:Vector A m) (v2:Vector A n) : Vector A (m+n)\n    := fun i => if lt_dec i m then v1 i else v2 (i-m).\n  Next Obligation.\n    omega.\n  Defined.  \n\n  Lemma vtake_skip_app_eq_pf n m (pf:(n<=m)%nat) : n + (m - n) = m.\n  Proof.\n    rewrite Nat.add_sub_assoc by trivial.\n    now rewrite minus_plus.\n  Defined.\n\n  Lemma vtake_skip_app_lt_pf {m n i} (pf:(n<=m)%nat) (p2f:i < m) : i < n + (m - n).\n  Proof.\n    now rewrite vtake_skip_app_eq_pf.\n  Defined.\n\n  Lemma vtake_skip_app {A} {m:nat} (v:Vector (A) m) (n:nat) (pf:(n<=m)%nat) :\n    forall i, v i = vapp (vtake v n pf) (vskip v n pf) (exist _ (proj1_sig i) (vtake_skip_app_lt_pf pf (proj2_sig i))).\n  Proof.\n    intros.\n    unfold vapp, vtake, vskip.\n    destruct i; simpl.\n    match_destr.\n    - now erewrite index_pf_irrel.\n    -\n      match goal with\n        [|- _ = v (exist _ _ ?pff)] => generalize pff\n      end.\n      assert (HH:x - n + n = x) by omega.\n      rewrite HH.\n      intros.\n      now erewrite index_pf_irrel.\n  Qed.\n\n  Lemma vmap_vdrop_last {A B} {n} (f:A->B) (v:Vector A (S n))  : vmap f (vdrop_last v) = vdrop_last (vmap f v).\n  Proof.\n    unfold vdrop_last.\n    apply vec_eq_eq; intros [??]; simpl.\n    now repeat rewrite vmap_nth.\n  Qed.\n\n  Lemma map_vector_to_list_vmap {A B} {n}  (f:A->B) (v:Vector A n) :\n    map f (vector_to_list v) = vector_to_list (vmap f v).\n  Proof.\n    unfold vector_to_list, vector_fold_right.\n    induction n.\n    - rewrite vector_fold_right_dep_0; trivial.\n    - repeat rewrite vector_fold_right_dep_Sn.\n      simpl.\n      rewrite IHn, vmap_vdrop_last.\n      unfold vlast.\n      now rewrite vmap_nth.\n  Qed.\n\n  Lemma vector_to_list_ext {A} {n} (x y:Vector A n) :\n    vec_eq x y -> vector_to_list x = vector_to_list y.\n  Proof.\n    apply vector_fold_right_ext.\n  Qed.\n\n    \n  Lemma vector_to_list_length (n : nat) (A : Type) (v : Vector.Vector A n) :\n    length (Vector.vector_to_list v) = n.\n  Proof.\n    unfold vector_to_list, vector_fold_right.\n    revert v.\n    induction n; intros.\n    - simpl; trivial.\n    - rewrite vector_fold_right_dep_Sn.\n      simpl.\n      now rewrite IHn.\n  Qed.\n\nEnd Vector.\n\n", "meta": {"author": "CertRL", "repo": "CertRLanon", "sha": "ba50abfb13c9c49abda8ffaad23fe76dcd4bf6ec", "save_path": "github-repos/coq/CertRL-CertRLanon", "path": "github-repos/coq/CertRL-CertRLanon/CertRLanon-ba50abfb13c9c49abda8ffaad23fe76dcd4bf6ec/coq/utils/Vector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933403143929, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.6935825674541498}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nAdd LoadPath \"lf/\".\nRequire Import numbers.\nRequire Import induction.\nRequire Import poly.\nRequire Import tactics.\nRequire Import Coq.Lists.List.\nOpen Scope list_scope.\n\n(* Propositions are first class objects in Coq *)\nTheorem plus_2_2_is_4:\n  2 + 2 = 4.\n\nProof. reflexivity. Qed.\n\nDefinition plus_fact: Prop := 2 + 2 = 4.\nCheck plus_fact.\n\nTheorem plus_fact_is_true:\n  plus_fact.\n\nProof. reflexivity. Qed.\n\n(* Props can be parametrized *)\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\n\nCheck is_three 3. (* is_three defines properties of their arguments *)\n\nDefinition injective {A B} (f: A -> B) :=\n  forall x y : A,\n  f x = f y ->\n  x = y.\n\nLemma succ_inj : injective S.\n\nProof.\n  intros n m H.\n  inversion H.\n  reflexivity.\n  Qed.\n\nCheck @eq.\n\n(* Logical connectives *)\n\n(* Conjuction *)\nExample and_example:\n  3 + 4 = 7 /\\ 2 * 2 = 4.\n\nProof.\n  split.\n  - reflexivity.\n  - reflexivity.\n  Qed.\n\nLemma and_intro:\n  forall A B: Prop,\n  A -> B ->\n  A /\\ B.\n\nProof.\n  intros A B HA HB.\n  split.\n  - apply HA.\n  - apply HB.\n  Qed.\n\nExample and_example':\n  3 + 4 = 7 /\\ 2 * 2 = 4.\n\nProof.\n  apply and_intro.\n  - reflexivity.\n  - reflexivity.\n  Qed.\n\n(* Exercise *)\nExample and_exercise:\n  forall n m : nat,\n  n + m = 0 ->\n  n = 0 /\\ m = 0.\n\nProof.\n  intros n m.\n  split.\n  generalize dependent m.\n  - intros m. induction m as [| m' ].\n    + intro H.\n      rewrite plus_comm in H.\n      rewrite plus_0_n in H.\n      apply H.\n    + destruct n.\n      * simpl. intro H. reflexivity.\n      * simpl. intro H. inversion H.\n  - induction m as [| m' ].\n    + reflexivity.\n    + destruct n.\n      * simpl in H. inversion H.\n      * simpl in H. inversion H.\n  Qed.\n\n(* Demonstrating `destruct` for using a conjunctive hypothesis to help prove stuff *)\nLemma and_example_2:\n  forall n m : nat,\n  n = 0 /\\ m = 0 ->\n  n + m = 0.\n\nProof.\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\n  Qed.\n\nLemma and_example_3:\n  forall n m : nat,\n  n + m = 0 ->\n  n * m = 0.\n\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.\n  Qed.\n\nLemma proj1:\n  forall P Q : Prop,\n  P /\\ Q -> P.\n\nProof.\n  intros P Q [HP HQ].\n  apply HP.\n  Qed.\n\n(* Exercise *)\nLemma proj2:\n  forall P Q : Prop,\n  P /\\ Q -> Q.\n\nProof.\n  intros P Q [HP HQ].\n  apply HQ.\n  Qed.\n\nTheorem and_commut:\n  forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\n\nProof.\n  intros P Q [HP HQ].\n  split.\n  - apply HQ.\n  - apply HP.\n  Qed.\n\n(* Exercise *)\nTheorem and_assoc:\n  forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\n\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(* Disjunction *)\nLemma or_example:\n  forall n m : nat,\n  n = 0 \\/ m = 0 ->\n  n * m = 0.\n\nProof.\n  intros n m [Hn | Hm].\n  - rewrite Hn. reflexivity.\n  - rewrite Hm. \n    rewrite <- mult_n_O.\n    reflexivity.\n  Qed.\n\nLemma or_intro: \n  forall A B : Prop,\n  A -> A \\/ B.\n\nProof.\n  intros A B HA.\n  left.\n  apply HA.\n  Qed.\n\nLemma zero_or_succ:\n  forall n : nat,\n  n = 0 \\/ n = S (pred n).\n\nProof.\n  intros [| n ].\n  - left. reflexivity.\n  - right. reflexivity.\n  Qed.\n\n(* Demonstrating negation, falsehood *)\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_quodlibet:\n  forall (P : Prop),\n  False -> P.\n\nProof.\n  intros P contra.\n  destruct contra.\n  Qed.\n\n(* Exercise *)\nFact not_implies_our_not:\n  forall (P : Prop),\n  ~ P -> (forall (Q : Prop), P -> Q).\n\nProof.\n  intros.\n  destruct H.\n  apply H0.\n  Qed.\n\nTheorem zero_not_one: ~ (0 = 1).\n\nProof.\n  intros contra.\n  inversion contra.\n  Qed.\n\n(* Inequality notation *)\nCheck (0 <> 1).\n\nTheorem zero_not_one': 0 <> 1.\n\nProof.\n  intros H.\n  inversion H.\n  Qed.\n\nTheorem not_False:\n  ~ False.\n\nProof.\n  unfold not.\n  intros H.\n  apply H.\n  Qed.\n\nTheorem contradiction_implies_anything:\n  forall P Q : Prop,\n  (P /\\ ~ P) -> Q.\n\nProof.\n  intros P Q [HP HNA].\n  unfold not in HNA.\n  apply HNA in HP.\n  destruct HP.\n  Qed.\n\nTheorem double_neg:\n  forall P : Prop,\n  P -> ~~P.\n\nProof.\n  intros P H.\n  unfold not.\n  intros G.\n  apply G.\n  apply H.\n  Qed.\n\n(* Exercise *)\nTheorem contrapositive:\n  forall (P Q : Prop),\n  (P -> Q) -> (~Q -> ~P).\n\nProof.\n  intros P Q HP HNQ HNP.\n  unfold not in HNQ.\n  apply HNQ in HP.\n  - apply HP.\n  - apply HNP.\n  Qed.\n\n(* Exercise *)\nTheorem not_both_true_and_false:\n  forall P : Prop,\n  ~ (P /\\ ~P).\n\nProof.\n  intros P contra.\n  destruct contra as [H HN].\n  unfold not in HN.\n  apply HN in H.\n  apply H.\n  Qed.\n\nTheorem not_true_is_false:\n  forall b : bool,\n  b <> true -> b = false.\n\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.\n  Qed.\n\n(* Coq has a built-in tactic `exfalso` for applying reasoning with `ex_falso_quodlibet` *)\nTheorem not_true_is_false':\n  forall b : bool,\n  b <> true -> b = false.\n\nProof.\n  intros [] H.\n  - unfold not in H.\n    exfalso.\n    apply H. reflexivity.\n  - reflexivity.\n  Qed.\n\n(* Truth *)\n(* `I` is a predefined constant `I : True` *)\nLemma True_is_true : True.\n\nProof.\n  apply I. Qed.\n\n(* Logical equivalence *)\nModule MyIff.\n\nDefinition iff (P Q : Prop) := \n  (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q) (at level 95, no associativity) : type_scope.\n\nEnd MyIff.\n\nTheorem iff_sym:\n  forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\n\nProof.\n  intros P Q [HAB HBA].\n  split.\n  - apply HBA.\n  - apply HAB.\n  Qed.\n\nLemma not_true_iff_false:\n  forall b, b <> true <-> b = false.\n\nProof.\n  intros b.\n  split.\n  - unfold not. apply not_true_is_false.\n  - intros H. rewrite H. intros H'. inversion H'.\n  Qed.\n\n(* Exercise *)\nTheorem or_distributes_over_and:\n  forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\n\nProof.\n  Admitted.\n\n(* Existential quantification *)\nLemma four_is_even:\n  exists n : nat,\n  4 = n + n.\n\nProof.\n  exists 2. reflexivity.\n  Qed.\n\nTheorem exists_example_2:\n  forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\n\nProof.\n  intros n [m Hm].\n  exists (2 + m).\n  apply Hm.\n  Qed.\n\n(* Exercise *)\nTheorem dist_not_exists:\n  forall (X : Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\n\nProof.\n  intros.\n  unfold not. intros H2. destruct H2 as [x E].\n  apply E. apply H.\n  Qed.\n\nFixpoint In\n  {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\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" :=\n  (cons x .. (cons y nil) ..).\n\nExample In_example_1:\n  In 4 [ 1; 2; 3; 4; 5 ].\n\nProof.\n  simpl. right. right. right. left. reflexivity.\n  Qed.\n\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/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566559, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.6935825629467313}}
{"text": "(** Source: https://golem.ph.utexas.edu/category/2015/06/semigroup_puzzles.html *)\n\nRequire Import Setoid.\nRequire Import ssreflect.\n\nGeneralizable All Variables.\n\nSection puzzles.\n  Variable A : Type.\n  Variable op : A -> A -> A.\n  Local Infix \"*\" := op (at level 40, left associativity).\n\n  Hypothesis assoc  : `(x * y * z = x * (y * z)).\n  Hypothesis absorp : `(x * y * x = x).\n\n  Section vanilla.\n    Lemma puzzle1 : forall x y z, x * y * z = x * z.\n    Proof.\n      intros x y z.\n      rewrite <- (absorp x (y*z)) at 2.\n      rewrite (assoc _ x z).\n      rewrite (assoc x (y*z) (x*z)).\n      rewrite (assoc y _ _).\n      rewrite <- (assoc z x z).\n      now rewrite absorp.\n    Qed.\n\n    Lemma puzzle2 : forall x, x * x = x.\n    Proof.\n      intro x.\n      rewrite <- (absorp x x) at 1.\n      rewrite (assoc x _ x).\n      now rewrite absorp.\n    Qed.\n  End vanilla.\n\n  Section ssr.\n    Lemma puzzle1_ssr : forall x y z, x * y * z = x * z.\n    Proof.\n      move=> x y z.\n      rewrite -{2}(absorp x (y*z)) (assoc _ x z) (assoc x (y*z) (x*z)).\n      by rewrite (assoc y _ _) -(assoc z x z) absorp.\n    Qed.\n\n    Lemma puzzle2_ssr : forall x, x * x = x.\n    Proof.\n      move=> x.\n      by rewrite -{1}(absorp x x) (assoc x _ x) absorp.\n    Qed.\n  End ssr.\nEnd puzzles.\n\n", "meta": {"author": "mgrabovsky", "repo": "fm-notes", "sha": "6c38cee5a4390c4543d6a404bd88909f3116bafe", "save_path": "github-repos/coq/mgrabovsky-fm-notes", "path": "github-repos/coq/mgrabovsky-fm-notes/fm-notes-6c38cee5a4390c4543d6a404bd88909f3116bafe/sketches/SemigroupPuzzles.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.6934860532814066}}
{"text": "Require Export B7_Triangle_Equilateral.\n\nSection POINT_PROPERTIES.\n\nLemma ExistsHalfLineEquidistant : forall A B C D : Point,\n\tA <> B ->\n\tC <> D ->\n\t{E : Point |\n\t\tHalfLine A B E /\\\n\t\tDistance A E = Distance C D}.\nProof.\n\tintros A B C D Hab Hcd.\n\tsetLine A B Hab ipattern:(L) ipattern:(AB).\n\tsetCircle A C D Hcd ipattern:(G) ipattern:(ACD).\n\tsetLinterposC L G AB ACD ipattern:(E) ipattern:(H1) ipattern:(H2) ipattern:(H3) ipattern:(H4).\n\t apply CollinearABA.\n\t exists E; canonize.\nQed.\n\nLemma HalfLineEquidistantEqual : forall A B C : Point,\n\tA <> B ->\n\tHalfLine A B C ->\n\tDistance A B = Distance A C ->\n\tB = C.\nProof.\n\tintros.\n\tsetLine A B H ipattern:(L) ipattern:(AB).\n\tsetCircle A A B H ipattern:(G) ipattern:(Aab).\n\tsetLinterposC L G AB Aab ipattern:(D) ipattern:(H2) ipattern:(H3) ipattern:(H4) ipattern:(H5).\n\t apply CollinearABA.\n\t rewrite <- (H5 B).\n\t  apply H5.\n\t    canonize.\n\t   elim (NotClockwiseBAA C A); auto.\n\t   generalizeChangeSense.\n\t     elim (NotClockwiseABA C A); auto.\n\t  canonize.\n\t   exact (NotClockwiseBAA B A H2).\n\t   exact (NotClockwiseABA B A H2).\nQed.\n\nLemma ExistsBetweenEquidistant : forall A B C D : Point,\n\tA <> B ->\n\tC <> D ->\n\t{E : Point |\n\t\tBetween E A B /\\\n\t\tDistance A E = Distance C D}.\nProof.\n\tintros A B C D Hab Hcd.\n\tsetLine A B Hab ipattern:(L) ipattern:(AB).\n\tsetCircle A C D Hcd ipattern:(G) ipattern:(ACD).\n\tsetLinternegC L G AB ACD ipattern:(E) ipattern:(H1) ipattern:(H2) ipattern:(H3) ipattern:(H4).\n\t apply CollinearABA.\n\t exists E; canonize.\n\t  destruct (ClockwiseExists B A (sym_not_eq Hab)) as (F, H5).\n\t    subst; elim (NotClockwiseAAB A F); auto.\n\t  generalizeChangeSide.\nQed.\n\nLemma ExistsEquidistantBetween : forall A B C D : Point,\n\tA <> B ->\n\tC <> D ->\n\t{E : Point |\n\t\tBetween A B E  /\\\n\t\tDistance B E = Distance C D}.\nProof.\n\tintros A B C D Hab Hcd.\n\tsetLine A B Hab ipattern:(L) ipattern:(AB).\n\tsetCircle B C D Hcd ipattern:(G) ipattern:(BCD).\n\tsetLinterposC L G AB BCD ipattern:(E) ipattern:(H1) ipattern:(H2) ipattern:(H3)\n\t ipattern:(H4).\n\t apply CollinearABB.\n\t exists E; canonize.\nQed.\n\nLemma CentralSymetPoint : forall A B : Point,\n\tA <> B ->\n\t{C : Point | Distance A B = Distance B C /\\ Between A B C}.\nProof.\n\tintros.\n\tdestruct (ExistsBetweenEquidistant B A A B (sym_not_eq H) H) as (C, (H0, H1)).\n\texists C; generalizeChangeSide.\nQed.\n\nLemma CoordinatePoint : forall A B : Point,\n\tA <> B ->\n\t{C : Point | HalfLine Oo Uu C /\\ Distance Oo C = Distance A B}.\nProof.\n\tintros.\n\texact (ExistsHalfLineEquidistant Oo Uu A B DistinctOoUu H).\nQed.\n\nEnd POINT_PROPERTIES.\n", "meta": {"author": "coq-contribs", "repo": "ruler-compass-geometry", "sha": "ee36f5cd523abaa2e0b676c4100c02ec496c0bfd", "save_path": "github-repos/coq/coq-contribs-ruler-compass-geometry", "path": "github-repos/coq/coq-contribs-ruler-compass-geometry/ruler-compass-geometry-ee36f5cd523abaa2e0b676c4100c02ec496c0bfd/B8_Point_Def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346598, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.693486049735968}}
{"text": "(** * Bound semantics for correctness of Poly1305.\n\nPoly1305 is a high speed message authentication primitive\n<https://en.wikipedia.org/wiki/Poly1305> which makes use of finite\nfield arithmetic over the finite field F = GF(2^130 - 5). In this\nsample code, we demonstrate how one can use the bound semantics to\nverify correctness of the portions that implement this arithmetic on a\n64-bit machine.\n\nArithmetic over the field F the integer arithmetic done modulo the\nprime 2^130 - 5. One can think of these elements as bit vectors of\nsize 130 bits. Implementations of poly1305 on 64-bit machines store\nstore these 130-bit words in 5x64-bit variables each containing\n26-bits of the original word. The extra 36 bits in each of these\nvariables is meant to hold the overflow when performing arithmetic\noperations.\n\n\n*)\n\nRequire Import Verse.\n\n(** ** The program variables.\n\nConsider two elements [a] and [b] in the field represented via\n5x64-bit words each of 26-bit each [a0,...,a4] and [b0,...,b4]\nrespectively. Computing [a * b] in [F] results in 5x64-bit elements.\n[p0,...,p4]. In this file we only consider the correctness in the\nevaluation of p0. Let us first define our program variables for this.\n\n*)\nInductive var : VariableT :=\n| p0 : var _ Word64\n| a0 : var _ Word64\n| a1 : var _ Word64\n| a2 : var _ Word64\n| a3 : var _ Word64\n| a4 : var _ Word64\n| b0 : var _ Word64\n| b51 : var _ Word64\n| b52 : var _ Word64\n| b53 : var _ Word64\n| b54 : var _ Word64\n| tmp : var _ Word64\n.\n\nDefinition var_eqb k (ty : type k) (x y : var _ ty) : bool :=\n  match x, y with\n  | p0, p0\n  | a0, a0 | a1, a1 | a2, a2 | a3, a3 | a4, a4\n  | b0, b0\n  | b51, b51 | b52, b52 | b53, b53 | b54, b54\n  | tmp, tmp => true\n  | _, _ => false\n  end.\n\nRequire Import Verse.Semantics.\nRequire Import Verse.DecFacts.\nRequire Import Verse.Semantics.BoundSemantics.\nRequire Import Verse.Types.\nRequire Import Verse.Types.Internal.\nRequire Import List.\nImport VectorNotations.\nNotation SIZE := 5.\n\n\n(**\n\nThe formula for the [p0,...,p4] is given below\n\n<<\n\np0 = a0*b0                                    + 5 * ( a1*b4 + a2*b3 + a3*b2 + a4*b1);\np1 = a0*b1 + a1*b0                            + 5 * ( a2*b4 + a3*b3 + a4*b2 );\np2 = a0*b2 + a1*b1 + a2*b0                    + 5 * ( a3*b4 + a4*b3 );\np3 = a0*b3 + a1*b2 + a2*b1 + a3*b0            + 5 * ( a4*b54 );\np4 = a0*b4 + a1*b3 + a2*b2 + a3*b1 + a4*b0 ;\n\n>>\n\n *)\n\n(**\n\nNote that the first few terms (printed left aligned) are the usual\nterms that arise in the multiplication of\n\n<< a = a0 + 2^26 * a1 + ... + 2^(104) a4 >>\n\n<< b = b0 + 2^26 * b1 + ... + 2^(104) b4 >>\n\n\nThe additional terms that are of the form (5 * (...) ) arise because\n2^130 is 5 in the field F.  We refer to the blog post of\n<http://loup-vaillant.fr/tutorials/poly1305-design> for details.\n\n*)\n\nDefinition polymul : code var.\n  verse\n    [ p0 ::== Ox \"0000000000000000\";\n      tmp ::= a0 [*] b0;\n      p0 ::=+ tmp;\n      tmp ::= a1 [*] b54;\n      p0 ::=+ tmp;\n      tmp ::= a2 [*] b53;\n      p0 ::=+ tmp;\n      tmp ::= a3 [*] b52;\n      p0 ::=+ tmp;\n      tmp ::= a4 [*] b51;\n      p0 ::=+ tmp\n    ]%list.\nDefined.\n\nImport BoundSemantics.\n\nDefinition init : State var :=\n  fun k (ty : type k) (v : var _ ty) =>\n    match v in var _ ty0 return T.typeDenote ty0 + {VariableError var} with\n    | a0 | a1 | a2 | a3 | a4 => {- (0, 26) -}\n    | b0 => {- (0, 26) -}\n    | b54 | b53 | b52 | b51 => {- (0, 29) -}\n    | p0 => {- (0, 0) -}\n    | tmp => {- (0, 0) -}\n    end.\n\nDefinition finalS := (recover(codeDenote var_eqb init polymul)).\n\nCompute (finalS _ _ p0).\n\n(**\n\nThis computation gives the following response\n\n<<\n     = {-(0, 59) -}\n     : T.typeDenote Word64 + {VariableError var}\n>>\n *)\n\n(**\n\nWhat this means is that p0 has an upper bound of 2^59 and that none of\nthe arithmetic operations have overflowed.\n\n\n*)\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/Artifact/poly1305.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.6934860413940206}}
{"text": "From MyCoq.Lib Require Export Nat.\n\n\n(* 多态 *)\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.\nCheck (nil nat).\nCheck (cons nat (N 3) (nil nat)).\n\nCheck nil.\nCheck cons.\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 (N 4) (N 2) = cons nat (N 4) (cons nat (N 4) (nil nat)).\nProof. simpl. reflexivity. Qed.\n\nExample test_repeat2:\n  repeat bool false (N 1) = cons bool false (nil bool).\nProof. simpl. reflexivity. Qed.\n\nInductive mumble : Type :=\n  | a\n  | b (x : mumble) (y : nat)\n  | c.\nInductive grumble (X:Type) : Type :=\n  | d (m : mumble)\n  | e (x : X).\n\n(* Check d (b a (N 5)). *)\nCheck d mumble (b a (N 5)).\nCheck d bool (b a (N 5)).\nCheck e bool true.\nCheck e mumble (b c O).\n(* Check e bool (b c O). *)\n(* Check c. *)\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.\nCheck repeat'.\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(* 隐式参数 *)\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\nDefinition list_nat := cons (N 1) 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\nCheck repeat'''.\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(* 显式提供类型参数 *)\nFail Definition mynil := nil nat.\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 list_nat' := [true; false; false].\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\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\nNotation \"( x , y )\" := (pair x y).\n\n(* 积类型 Product Types *)\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\nDefinition fst {X Y :Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y :Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y) : list (X * Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\nCheck @combine.\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\nExample test_split:\n  split [(N 1,false);(N 2,false)] = ([N 1; N 2],[false;false]).\nProof. simpl. reflexivity. Qed.\n\n(* 多态候选 *)\nInductive option (X : Type) : Type :=\n  | Some (x : X)\n  | None.\nArguments Some {X} _.\nArguments None {X}.\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\nExample test_nth_error1: nth_error [N 4; N 5; N 6; N 7] (N 0) = Some (N 4).\nProof. simpl. reflexivity. Qed.\nExample test_nth_error2: nth_error [[N 1];[N 2]] (N 1) = Some [N 2].\nProof. simpl. reflexivity. Qed.\nExample test_nth_error3: nth_error [true] (N 2) = None.\nProof. simpl. reflexivity. Qed.\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\nCheck @hd_error.\nExample test_hd_error1: hd_error [N 1; N 2] = Some (N 1).\nProof. simpl. reflexivity. Qed.\nExample test_hd_error2: hd_error [[N 1]; [N 2]] = Some [N 1].\nProof. simpl. reflexivity. Qed.\n\n\n(* 函数作为数据 *)\n\n(* 高阶函数 *)\nDefinition doit3times {X : Type} (f : X -> X) (n : X) : X :=\n  f (f (f n)).\n\nCheck @doit3times.\nExample test_doit3times': doit3times negb true = false.\nProof. simpl. reflexivity. Qed.\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\nExample test_filter1: filter evenb [N 1; N 2; N 3; N 4] = [N 2; N 4].\nProof. simpl. reflexivity. Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  length l =? N 1.\n\n(* 匿名函数 *)\nExample test_anon_fun':\n  doit3times (fun n => n * n) (N 2) = N 256.\nProof. simpl. reflexivity. Qed.\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n => evenb n && ((N 7) <=? n)) l.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [N 1; N 2; N 6; N 9; N 10; N 3; N 12; N 8] = [N 10; N 12; N 8].\nProof. simpl. reflexivity. Qed.\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [N 5; N 2; N 6; N 19; N 129] = [].\nProof. simpl. reflexivity. Qed.\n\nFixpoint partition {X : Type} (test : X -> bool) (l : list X) : list X * list X :=\n  match l with\n  | [] => ([], [])\n  | x :: y => if test x\n              then match partition test y with\n                   | (l1, l2) => (x :: l1, l2)\n                   end\n              else match partition test y with\n                   | (l1, l2) => (l1, x :: l2)\n                   end\n  end.\n\nExample test_partition1: partition oddb [N 1; N 2; N 3; N 4; N 5] = ([N 1; N 3; N 5], [N 2; N 4]).\nProof. simpl. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [N 5; N 9; N 0] = ([], [N 5; N 9; N 0]).\nProof. simpl. reflexivity. Qed.\n\n(* 映射 *)\nFixpoint map {X Y: Type} (f : X -> Y) (l : list X) : (list Y) :=\n  match l with\n  | [] => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\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\nExample test_flat_map1: flat_map (fun n => [n; n; n]) [N 1; N 5; N 4] = [N 1; N 1; N 1; N 5; N 5; N 5; N 4; N 4; N 4].\nProof. simpl. reflexivity. Qed.\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X) : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\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\nExample test_fold: fold cons [true; true; false] [] = [true; true; false].\nProof. simpl. reflexivity. Qed.\n\n(* 用函数构造函数 *)\nDefinition constfun {X : Type} (x : X) : nat -> X :=\n  fun (k : nat) => x.\nDefinition ftrue := constfun true.\nExample constfun_example1: ftrue O = true.\nProof. simpl. reflexivity. Qed.\nExample constfun_example2: (constfun (N 5)) (N 99) = N 5.\nProof. simpl. reflexivity. Qed.\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l O.\nExample test_fold_length1: fold_length [N 4; N 7; N 0] = N 3.\nProof. simpl. reflexivity. Qed.\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\nExample test_fold_map: fold_map negb [true; true] = [false; false].\nProof. simpl. reflexivity. Qed.\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\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\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  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\nSet Universe Polymorphism.\nDefinition cnat := forall X : Type,\n  (X -> X) -> X -> X.\n\nCheck cnat.\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 :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f (f x)).\n\nCheck @one.\n\n(* match 行不通，cnat 本质上是一个函数，不是一个可归纳的数据类型 *)\nDefinition succ (n : cnat) : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (n X f x).\n\nExample succ1: succ zero = one.\nProof. simpl. reflexivity. Qed.\nExample succ2: succ one = two.\nProof. simpl. reflexivity. Qed.\nExample succ3: succ two = three.\nProof. simpl. reflexivity. Qed.\n\nDefinition succ_f (X : Type) (f f_0 : X -> X) (x : X) : X := f (f_0 x).\n\nDefinition plus (n m : cnat) : cnat :=\n  (* fun (X : Type) (f : X -> X) (x : X) => n X f (m X f x). *)\n  (* fun (X : Type) => (n cnat succ) m X. *)\n  fun (X : Type) (f : X -> X) => n (X -> X) (succ_f X f) (m X f).\n\nExample plus1: plus zero one = one.\nProof. simpl. reflexivity. Qed.\nExample plus2: plus two three = plus three two.\nProof. simpl. reflexivity. Qed.\nExample plus3:\n  plus (plus two two) three = plus one (plus three three).\nProof. simpl. reflexivity. Qed.\n\n(* 思考定义 *)\nDefinition mult (n m : cnat) : cnat :=\n  (* fun (X : Type) (f : X -> X) (x : X) => n X (m X f) x. *)\n  (* m X f 是对 X 类型的变量做 m 次 f 变换，其依然是 X -> X 的对 X 类型变量的变换，记作 f' *)\n  (* 之后 n X f' 意味着做 n 次 f' 变换，最终效果即 n * m 次 f 变换 *)\n  fun (X : Type) (f : X -> X) => n X (m X f).\n\nExample mult1: mult one one = one.\nProof. simpl. reflexivity. Qed.\nExample mult2: mult zero (plus three three) = zero.\nProof. simpl. reflexivity. Qed.\nExample mult3: mult two three = plus three three.\nProof. simpl. reflexivity. Qed.\n\n(* 如果直接令 m 接收 cnat 作为泛型参数会导致 universe inconsistency *)\n(* https://stackoverflow.com/questions/32153710/what-does-error-universe-inconsistency-mean-in-coq *)\n(* 1. 在 cnat 定义前添加 Set Universe Polymorphism. *)\nDefinition exp (n m : cnat) : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => m cnat (mult n) one X f x.\n(* 2. 注意和 mult 的区别 *)\nDefinition exp' (n m : cnat) : cnat :=\n  (* n X 代表对原变换重复 n 次，可以认为其是对 X -> X 的变换，即变换的变换 *)\n  (* 可以参看 plus 中使用 succ_f 的做法 *)\n  fun (X : Type) => m (X -> X) (n X).\n\nExample exp1: exp two two = plus two two.\nProof. simpl. reflexivity. Qed.\nExample exp2: exp three zero = one.\nProof. simpl. reflexivity. Qed.\nExample exp3: exp three two = plus (mult two (mult two two)) one.\nProof. simpl. reflexivity. Qed.\nExample exp'1: exp' two two = plus two two.\nProof. simpl. reflexivity. Qed.\nExample exp'2: exp' three zero = one.\nProof. simpl. reflexivity. Qed.\nExample exp'3: exp' three two = plus (mult two (mult two two)) one.\nProof. simpl. reflexivity. Qed.\n", "meta": {"author": "GanZiheng", "repo": "learn-coq", "sha": "6d915f299e0b483ba53a8184c9ec13ac275aeca6", "save_path": "github-repos/coq/GanZiheng-learn-coq", "path": "github-repos/coq/GanZiheng-learn-coq/learn-coq-6d915f299e0b483ba53a8184c9ec13ac275aeca6/Src/poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.8688267779364222, "lm_q1q2_score": 0.6934860379530225}}
{"text": "Require Export Induction.\n(* ((Polymorphism)) *)\n\nFixpoint snoc {X : Type} (l : list X) (n : X) : (list X) :=\n  match l with\n    | nil => (n :: nil)%list\n    | cons h t => (h :: snoc t n)%list\n  end.\n\nFixpoint rev {X : Type} (l : list X) : list X :=\n  match l with\n    | nil => nil\n    | cons h t => snoc (rev t) h\n  end.\n\n(* Exercise: 2 stars (mumble_grumble) *)\n\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\nWhich of the following are well-typed elements of grumble X for some type X?\n- d (b a 5)      // the type cannot be inferred\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) // (b c 0) is a mumble, not bool\n- c              // is a mumble\n*)\n\n(* END mumble_grumble. *)\n\n(* Exercise: 2 stars (baz_num_elts) *)\n\n(* None. There are no sinks. *)\n\n(* END baz_num_elts. *)\n\n(* Exercise: 2 stars, optional (poly_exercises) *)\n\nFixpoint repeat {X : Type} (n : X) (count : nat) : list X :=\n  match count with\n    | O => nil\n    | S c' => (n :: repeat n c')%list\n  end.\n\nExample test_repeat1 : repeat true 2 = (true :: true :: nil)%list.\nProof. reflexivity. Qed.\n\nTheorem nil_app : forall X : Type, forall l : list X,\n  app nil l = l.\nProof. reflexivity. Qed.\n\nTheorem rev_snoc : forall X : Type, forall v : X, forall l : list X,\n  rev (snoc l v) = (v :: rev l)%list.\nProof.\n  intros X v l.\n  induction l as [|n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    simpl.\n    rewrite -> IHl'.\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 [|n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    simpl.\n    assert (forall Z : Type, forall z : list Z, forall m : Z,\n            rev (snoc z m) = (m :: rev z)%list).\n    SCase \"proving rev (snoc l v) = v :: rev l\".\n      intros Z z m.\n      induction z as [|m' z'].\n      SSCase \"z = nil\".\n        reflexivity.\n      SSCase \"z = m' :: z'\".\n        simpl.\n        rewrite -> IHz'.\n        reflexivity.\n    rewrite -> H.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem snoc_with_append :\n  forall X : Type, forall l1 l2 : list X, forall v : X,\n  snoc (l1 ++ l2)%list v = (l1 ++ snoc l2 v)%list.\nProof.\n  intros X l1 l2 v.\n  induction l1 as [|n l1'].\n  Case \"l1 = nil\".\n    reflexivity.\n  Case \"l1 = n :: l1'\".\n    simpl.\n    rewrite -> IHl1'.\n    reflexivity.\nQed.\n\n(* END poly_exercises. *)\n\n(* Exercise: 1 star, optional (combine_checks) *)\n\n(* combine : forall X Y : Type, -> list X -> list Y -> list (X * Y) *)\n\n(* Eval compute in (combine [1; 2] [false; false; true; true])\n= [(1, false), (2, false)]\n*)\n\n(* END combine_checks. *)\n\n(* Exercise: 2 stars (split) *)\n\nFixpoint split {X Y : Type} (l : list (X * Y)) : (list X) * (list Y) :=\n  match l with\n    | nil => (nil, nil)\n    | cons (x, y) t => match split t with\n                         (xt, yt) => ((x :: xt)%list, (y :: yt)%list)\n                       end\n  end.\n\nExample test_split:\n  split ((1, false) :: (2, false) :: nil)%list =\n  ((1 :: 2 :: nil)%list, (false :: false :: nil)%list).\nProof. reflexivity. Qed.\n\n(* END split. *)\n\n(* Exercise: 1 star, optional (hd_opt_poly) *)\n\nDefinition hd_opt { X : Type } (l : list X) : option X :=\n  match l with\n    | nil => None\n    | cons h t => Some h\n  end.\n\nExample test_hd_opt1 : hd_opt (1 :: 2 :: nil)%list = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_opt2 :\n  hd_opt ((1 :: nil)%list :: (2 :: nil)%list :: nil)%list =\n  Some (1 :: nil)%list.\nProof. reflexivity. Qed.\n\n(* END hd_opt_poly. *)\n\n(* ((Functions as Data)) *)\n\nDefinition prod_curry { X Y Z : Type }\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(* Exercise: 2 stars, advanced (currying) *)\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\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  replace (prod_curry (prod_uncurry f) x y) with ((prod_uncurry f) (x, y)).\n    reflexivity.\n    reflexivity.\nQed.\n\nTheorem curry_uncurry : forall (X Y Z : Type) (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros X Y Z f p.\n  destruct p.\n  reflexivity.\nQed.\n\n(* END currying. *)\n\nFixpoint filter {X : Type} (f : X -> bool) (l : list X) : list X :=\n  match l with\n    | nil => nil\n    | cons h t => if f h then cons h (filter f t) else filter f t\n  end.\n\n(* Exercise: 2 stars (filter_even_gt7) *)\n\nDefinition filter_even_gt7_1 (l : list nat) : list nat :=\n  filter (fun x => ((evenb x) && negb (ble_nat 7 x))%bool) l.\n\n(* END filter_even_gt7. *)\n\n(* Exercise: 3 stars (partition) *)\n\nDefinition partition {X : Type} (f : X -> bool) (l : list X)\n  : 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 :: nil)%list =\n  ((1 :: 3 :: 5 :: nil)%list, (2 :: 4 :: nil)%list).\nProof. reflexivity. Qed.\n\nExample test_partition2 :\n  partition (fun x => false) (5 :: 9 :: 0 :: nil)%list =\n  (nil, (5 :: 9 :: 0 :: nil)%list).\nProof. reflexivity. Qed.\n\n(* END partition. *)\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 => (f h :: map f t)%list\n  end.\n\n(* Exercise: 3 stars (map_rev) *)\n\nTheorem map_app : forall (X Y : Type) (f : X -> Y) (l1 l2 : list X),\n  map f (l1 ++ l2) = (map f l1 ++ map f l2)%list.\nProof.\n  intros X Y f l1 l2.\n  induction l1 as [|n l1'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = n :: l1'\".\n    simpl.\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  intros X Y f l.\n  induction l as [|n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    simpl.\n    assert (forall (Z : Type) (j : list Z) (k : Z),\n            snoc j k = (j ++ (k :: nil))%list).\n      intros Z j k.\n      induction j as [|m j'].\n      SCase \"j = nil\".\n        reflexivity.\n      SCase \"j = m :: j'\".\n        simpl.\n        rewrite -> IHj'.\n        reflexivity.\n    rewrite -> H.\n    rewrite -> H.\n    rewrite <- IHl'.\n    rewrite -> map_app.\n    reflexivity.\nQed.\n\n(* END map_rev. *)\n\n(* Exercise: 2 stars (flat_map) *)\n\nFixpoint flat_map {X Y : Type} (f : X -> list Y) (l : list X) : list Y :=\n  match l with\n    | nil => nil\n    | cons h t => (f h ++ flat_map f t)%list\n  end.\n\nExample test_flat_map1:\n  flat_map (fun n => (n :: n :: n :: nil)%list) (1 :: 5 :: 4 :: nil)%list =\n  (1 :: 1 :: 1 :: 5 :: 5 :: 5 :: 4 :: 4 :: 4 :: nil)%list.\nProof. reflexivity. Qed.\n\n(* END flat_map. *)\n\n(* Exercise: 1 star, advanced (fold_types_different) *)\n\n(* rev = fold (fun x y => snoc y x) *)\n\n(* END fold_types_different. *)\n\nDefinition constfun {X : Type} (x : X) : nat -> X := fun k => x.\n\nDefinition override {X : Type} (f : nat -> X) (k : nat) (x : X) : nat -> X :=\n  fun (k' : nat) => if beq_nat k k' then x else f k'.\n\n(* Exercise: 1 star (override_example) *)\n\nTheorem override_example : forall (b : bool),\n  override (constfun b) 3 true 2 = b.\nProof.\n  intros b.\n  destruct b.\n    reflexivity.\n    reflexivity.\nQed.\n\n(* END override_example. *)\n\n(* Exercise: 2 stars (override_neq) *)\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 H1.\n  intros H2.\n  unfold override.\n  rewrite -> H2.\n  rewrite -> H1.\n  trivial.\nQed.\n\n(* END override_neq. *)\n\n(* ((Additional Exercises)) *)\n\nFixpoint fold { X Y : Type } (f : X -> Y -> Y) (l : list X) (b : Y) : Y :=\n  match l with\n    | nil => b\n    | cons h t => f h (fold f t b)\n  end.\n\n(* Exercise: 2 stars (fold_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 :: nil)%list = 3.\nProof. reflexivity. Qed.\n\nTheorem fold_length_correct : forall X (l : list X), fold_length l = length l.\nProof.\n  intros X l.\n  induction l as [|n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    simpl.\n    rewrite <- IHl'.\n    reflexivity.\nQed.\n\n(* END fold_length. *)\n\n(* Exercise: 3 stars (fold_map) *)\n\nDefinition fold_map {X Y : Type} (f : X -> Y) (l : list X) : list Y :=\n  fold (fun x y => cons (f x) y) l nil.\n\nTheorem fold_map_correct : forall (X Y : Type) (l : list X) (f : X -> Y),\n  map f l = fold_map f l.\nProof.\n  intros X Y l f.\n  induction l as [|n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    simpl.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\n(* END fold_map. *)\n\nFixpoint index { X : Type } (n : nat) (l : list X) : option X :=\n  match l with\n    | nil => None\n    | cons h t => if beq_nat n 0 then Some h else index (pred n) t\n  end.\n\n(* Exercise: 2 stars, advanced (index_informal) *)\n\n(* Performing an induction over the given list, we have the following cases.\n* If the list is empty, the case is trivial: no elements are present, and the\n* function returns None.\n* If the list is non-empty, then its length is not zero; thus the index in the\n* remaining list can't be zero, and the inductive step applies. *)\n\n(* END index_informal. *)\n\nModule Church.\n\nDefinition nat := forall X : Type, (X -> X) -> X -> X.\n\nDefinition zero : nat := fun (X : Type) (f : X -> X) (x : X) => x.\n\nDefinition one : nat := fun (X : Type) (f : X -> X) (x : X) => f x.\n\nDefinition two : nat := fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\nDefinition three : nat := fun (X : Type) (f : X -> X) (x : X) => f (f (f x)).\n\n(* Exercise: 4 stars, advanced (church_numerals) *)\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 : plus (plus two two) three = plus one (plus three three).\nProof. reflexivity. Qed.\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\nDefinition exp (n m : nat) : nat :=\n  fun (X : Type) (f : X -> X) => m (X -> X) (n X) (one X f).\n\nExample exp_1 : exp two two = plus two two.\nProof. reflexivity. Qed.\n\nExample exp_2 : exp three two = plus (mult two (mult two two)) one.\nProof. reflexivity. Qed.\n\nExample exp_3 : exp three zero = one.\nProof. reflexivity. Qed.\n\n(* END church_numerals. *)\n\nEnd Church.\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/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.6934535294955969}}
{"text": "Load FinSets.\nRequire Import Bool. \nRequire Import Arith. \nRequire Import List.\nRequire Import Notations.\n \n(*A finite set is described using an inductive definition, using 2 constructors.*)\n\nDefinition El:=Fin. \n\n(*A word is a list of elements *)\nVariable Alphabet : nat.\n(*Variable Sigma : Alphabet. *) \n(*A word is a list of elements *)\nDefinition Word := list (El Alphabet).\n\nDefinition Language := Word  -> Prop.\n(**empty word/string *)\nDefinition eps :Word :=nil.\n\n(**empty word/string *)\nDefinition lang_conc(l1:Language)(l2:Language):Language :=\n    fun w:Word => exists w1:Word, exists w2:Word,  w1 ++ w2=w /\\ l1 w1 /\\ l2 w2.\n\nDefinition lang_union (l1:Language)(l2:Language):Language :=\n    fun w:Word =>  l1 w \\/ l2 w.\n\n(* empty language imply [False] *)\nDefinition empty_lang :Language:= fun w:Word=>False.\n\n\n(** A language included into another language *)\nDefinition Included (l1:Language)(l2:Language) :Prop := forall (w:Word), l1 w -> l2 w.\nCheck Included.\n\nDefinition eps_lang :Language := fun w:Word => match w with \n   |nil => True\n  | _  => False\n   end.\n\n(* L1 conc empty = empty *)\nLemma empty_lr : forall (l1:Language)(w:Word) ,  (lang_conc l1 empty_lang) w<->  empty_lang w.\nintros.\nunfold iff.\nsplit.\nsimpl.\nintro.\nunfold lang_conc in H.\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H0.\nsimpl.\nsimpl in H1.\nunfold empty_lang.\nunfold empty_lang in H1.\ndestruct H1.\nintro.\n\nunfold empty_lang in H.\ndestruct H.\nQed.\n\nDefinition In_lang(w:Word)(l:Language) := l w.\n(* use the properties of existence quantifier to attribute the right values\nto the words *)\n\n(** distributivity property *)\nLemma distrib : forall (l1 l2 l3 :Language) (w:Word), In_lang w (lang_conc l1 (lang_union l2 l3)) <-> In_lang w (lang_union (lang_conc l1 l2) (lang_conc l1 l3)).\n(** -> *)\n\nintros.\nunfold iff.\nsplit.\nintro.\nunfold In_lang.\nunfold In_lang in H.\nunfold lang_conc.\nunfold lang_union.\nunfold lang_conc in H.\nunfold lang_union in H.\ndestruct H.\ndestruct H.\ndestruct H.\n\n(* use the properties of existence quantifier to attribute the right values\nto the words *)\ndestruct H0.\ndestruct H1.\nleft.\nexists x.\nexists x0.\nsplit.\nassumption.\nsplit.\nassumption.\nassumption.\nright.\nexists x.\nexists x0.\nsplit.\nexact H.\nsplit.\nassumption.\nassumption.\n\n(**  <- *)\nintro.\nunfold In_lang in H.\nunfold lang_union in H.\nunfold lang_conc in H.\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H0.\nunfold In_lang.\nunfold lang_conc.\nunfold lang_union.\nexists x.\nexists x0.\nsplit.\nexact H.\nsplit.\nexact H0.\nleft.\nexact H1.\n\n\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H0.\nunfold In_lang.\nunfold lang_conc.\nexists x.\nexists x0.\nsplit.\nexact H.\nsplit.\nexact H0.\nunfold lang_union.\nright.\nexact H1.\nQed.\n\nVariable x:Word.\n\nLemma eps_implies_nil : forall (w:Word) , eps_lang w -> w=nil.\nintros.\ninduction w.\nreflexivity.\nunfold eps_lang in H.\ndestruct H.\nQed.\n(** Found in the List library *)\nTheorem app_l_nil :  forall (A : Set)(l : list A),\n  l ++ nil = l.\nintros A l.\ninduction l.\nreflexivity.\nsimpl.\nrewrite IHl.\nreflexivity.\nQed.\n\n(* L conc epsilon = L *)\n\nTheorem lang_conc_neutral_left : forall (l:Language)(w:Word), In_lang w (lang_conc l eps_lang) <-> In_lang w l.\nintros.\nunfold iff.\nsplit.\nintro.\nunfold In_lang.\nunfold In_lang in H.\nunfold lang_conc in H.\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H0.\nrewrite <-H.\nassert (x1 = nil).\napply eps_implies_nil.\nexact H1.\nrewrite H2.\nsimpl.\nrewrite app_l_nil.\nexact H0.\n\nintro.\nunfold In_lang.\nunfold In_lang in H.\nunfold lang_conc.\nexists w. \nexists nil.\nsplit.\nrewrite app_l_nil.\nreflexivity.\nsplit.\nexact H.\nsplit.\nQed.\n\n\n(** epsilon language belongs to L*, if L belongs to the powerset of the word , L* bleongs to the\npowerset of the word (using concatenation) *)\n\nInductive Star(x:Language) : Language := \n  | nil0: (Star x) nil\n  | cons0 : forall (a: Word)(b:Word),Star x a /\\ x b -> Star x (app a b).\n\n\n(** the power of a language L : L^n = LLLL...L n times *)\nFixpoint lang_power (l:Language)(n:nat) : Language := \n     match n with \n     | 0 => eps_lang\n     | S n => lang_conc l (lang_power l n)\n     end.\n\n(** L1 conc(L2 conc L3) =(L1 conc L2) conc L3 \nassume w= v0++ v1, v0 in L1\nv1 in L2 conc L3\nv1 = v2++v3,\nv2 in L2 /\\ v3 in L3,\nw = v0++(v2++v3) = (v0++ v2)++v3 (associativity of lists) in L1 L2 L4\n*)\nAxiom app_ao : forall (A:Set)(l1 l2 l3 : list A) , l1 ++ app l2 l3 = (l1 ++ l2) ++ l3.\nLemma ab : forall (A:Set) (l1 l2 : list A) ,  app l1 l2 = l1 ++ l2.\nintros.\nreflexivity.\nQed.\nLemma abc : forall (A:Set) (l1 l2 l3: list A), app l1 l2 ++ l3 = l1 ++ (l2 ++l3).\nintros.\nsimpl.\nadmit.\nQed.\nLemma lang_assoc : forall (l1 l2 l3:Language)(w:Word), In_lang w (lang_conc l1 (lang_conc l2 l3)) <-> In_lang w (lang_conc (lang_conc l1 l2) l3).\n\n\nintros.\nunfold iff.\nsplit.\nintro.\nunfold In in H.\n\nunfold In_lang.\nunfold lang_conc.\nunfold lang_conc in H.\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H0.\ndestruct H1.\ndestruct H1.\ndestruct H1.\ndestruct H2.\nassert( In_lang x1 (lang_conc l2 l3)).\nunfold In_lang.\nunfold lang_conc.\nexists x2.\nexists x3.\nsplit.\nexact H1.\nsplit.\nassumption.\nassumption.\nrewrite <-H1 in H.\n\n\nrewrite app_ao in H.\nexists (x0 ++ x2).\nexists x3.\nsplit.\n\nrewrite <-H.\nsimpl.\nadmit.\n(* Coq does not recognise app x0 x2 ++ x3 as (x0 ++ x2) ++ x3 ??*)\nsplit.\nexists x0.\nexists x2.\nsplit.\nreflexivity.\nsplit.\nassumption.\nassumption.\nexact H3.\n\nintro.\nunfold In.\nunfold In in H.\nunfold lang_conc.\nunfold lang_conc in H.\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H0.\ndestruct H0.\ndestruct H0.\ndestruct H0.\ndestruct H2.\n\nrewrite <-H0 in H.\nrewrite abc in H.\nexists x2.\nexists (x3++ x1).\nsplit. (* x2 ++ app x3 x1 *)\nadmit. \nsplit.\nexact H2.\n\nexists x3.\nexists x1.\nsplit.\nreflexivity.\nsplit.\nassumption.\nassumption.\nQed.\n\n(** Star (Star L) = Star l.  we will prove this by using *) \n Lemma kleene1 : forall (l:Language) (w:Word), In_lang w (Star l) ->In_lang w (Star (Star l)).\n\nunfold In_lang.\nintros.\nrewrite <- app_nil_l.\nassert (Star (Star l) nil).\napply (nil0 ).\nassert ((Star (Star l) nil) /\\ ((Star l) w)).\nsplit.\nassumption.\nassumption.\napply (cons0) in H1.\nexact H1.\nQed.\n\nAxiom nil_O_r : forall (A:Set)(l:list A), l++nil = l.\nLemma lem : forall ( l:Language) (a b : Word) , In_lang a (Star l) /\\ In_lang b (Star l) -> In_lang (a ++ b) (Star l).\n\nintros.\nunfold In_lang.\nunfold In_lang in H.\ndestruct H.\ninduction H0.\nsimpl.\nrewrite nil_O_r.\nassumption.\nPrint Star.\nassert(Star l (a0 ++b )).\napply cons0.\nassumption.\ndestruct H0.\n\n\n\nintros.\nunfold In_lang in H.\nunfold In_lang.\ndestruct H.\n\ninduction H.\nsimpl.\nexact H0.\n\nPrint Star.\n\nassert(Star l (a++b0)).\napply cons0.\nexact H.\ndestruct H.\nassert (Star l b0).\n\nPrint Star.\n(*induction H0.\nsimpl.\nadmit.\nsimpl.\n\n\napply cons0.\nsplit.\ndestruct H.\nexact H.\ndestruct H.*) \nadmit.\nQed.\n\nLemma kleene2: forall (l:Language)(w:Word), In_lang w (Star(Star l)) -> In_lang w (Star l).\nintros.\nunfold In_lang.\nunfold In_lang in H.\ninduction w.\nsimpl.\napply nil0.\ndestruct H.\napply nil0.\ndestruct H.\n\napply cons0.\nsplit.\n\n\ninduction H.\n\n\napply nil0.\ndestruct H.\n\n\n\n \nassert(Star (Star l) (a++b)).\napply cons0.\nsplit.\nassumption.\nassumption.\nassert(Star(Star l) b).\napply kleene1.\nunfold In_lang.\nexact H0.\ninduction H.\nsimpl.\nassumption.\ndestruct H.\nassert (Star l (b0 ++ b)).\napply lem.\nunfold In_lang.\nsplit.\nassumption.\nassumption.\n\n\n\ninduction a.\nsimpl.\nexact H4.\n\nPrint Star.\n\ndestruct H.\nsimpl.\nassumption.\ndestruct H.\n\n\n\ninduction H0.\nsimpl.\nassert(a++nil = a).\nadmit.\nrewrite H0.\n\ninduction H.\n\n\n\n\n\n\n\ninduction H.\nexact (nil0 l).\nassert(Star (Star l ) (a++b)).\napply cons0.\nassumption.\n\nPrint Star.\n\ndestruct H.\ninduction H.\nsimpl.\nassumption.\ndestruct H.\nassert(Star l (b0++b)).\napply lem.\nunfold In_lang.\nsplit.\nassumption.\nassumption.\nadmit.\n(*\ninduction H0.\nassert (a++ nil = a).\nadmit.\nrewrite H0.\ninduction H.\napply nil0.\napply cons0.\nsplit. *)\n\n\ninduction H.\nsimpl.\nexact H0.\nPrint Star.\n\nassert(Star l (a++b0)).\ndestruct H.\n\n\nassert (Star (Star l) (a ++ b0)).\napply cons0.\nexact H.\nPrint Star.\n\nassert (Star (Star l) b).\napply kleene1.\nunfold In_lang.\nexact H0.\nPrint Star.\n\n\n\ninduction H.\nsimpl.\nexact H0.\n\napply cons0.\n", "meta": {"author": "radu07", "repo": "automat", "sha": "5d8c4ec7414025cb83ec094e45e09a7cd1d607da", "save_path": "github-repos/coq/radu07-automat", "path": "github-repos/coq/radu07-automat/automat-5d8c4ec7414025cb83ec094e45e09a7cd1d607da/auto/auto/Language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.6934535260501299}}
{"text": "Require Import VST.floyd.proofauto.\nRequire EV.max3 EV.swap EV.tri EV.gcd EV.append.\n\n(* ################################################################# *)\n(** * Task 1: The Max of Three *)\n\nModule Verif_max3.\n\nImport EV.max3.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n(** C function [max3]:\n\n      int max3(int x, int y, int z)\n      {\n        if (x < y)\n          if (y < z)\n            return z;\n          else\n            return y;\n        else\n          if (x < z)\n            return z;\n          else\n            return x;\n      }\n\n    Specification:\n*)\n\nDefinition max3_spec :=\n DECLARE _max3\n  WITH x: Z, y: Z, z: Z\n  PRE  [ _x OF tint, _y OF tint, _z OF tint ]\n     PROP  (Int.min_signed <= x <= Int.max_signed;\n            Int.min_signed <= y <= Int.max_signed;\n            Int.min_signed <= z <= Int.max_signed)\n     LOCAL (temp _x (Vint (Int.repr x));\n            temp _y (Vint (Int.repr y));\n            temp _z (Vint (Int.repr z)))\n     SEP   ()\n  POST [ tint ]\n    EX r: Z, \n     PROP  (r = x \\/ r = y \\/ r = z;\n            r >= x;\n            r >= y;\n            r >= z)\n     LOCAL (temp ret_temp (Vint (Int.repr r)))\n     SEP   ().\n\nDefinition Gprog : funspecs := ltac:(with_library prog [ max3_spec ]).\n\nLemma body_max3: semax_body Vprog Gprog f_max3 max3_spec.\nProof.\n  start_function.\n  forward_if.\n  {\n    forward_if.\n    {\n      forward.\n      Exists z.\n      entailer!.\n    }\n    {\n      forward.\n      Exists y.\n      entailer!.\n    }\n  }\n  {\n    forward_if.\n    {\n      forward.\n      Exists z.\n      entailer!.\n    }\n    {\n      forward.\n      Exists x.\n      entailer!.\n    }\n  }\nQed.\n\nEnd Verif_max3.\n(** [] *)\n\n(* ################################################################# *)\n(** * Task 2: Swap by Arith *)\n\nModule Verif_swap.\n\nImport EV.swap.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n(** C function [uint_swap_arith]:\n\n      void uint_swap_arith (unsigned int * px, unsigned int * py) {\n        * px = * px + * py;\n        * py = * px - * py;\n        * px = * px - * py;\n      }\n\n    Specification:\n*)\n\nDefinition uint_swap_arith_spec :=\n DECLARE _uint_swap_arith\n  WITH x: Z, y: Z, px: val, py: val\n  PRE  [ _px OF (tptr tuint), _py OF (tptr tuint) ]\n     PROP  ()\n     LOCAL (temp _px px; temp _py py)\n     SEP   (data_at Tsh tuint (Vint (Int.repr x)) px;\n            data_at Tsh tuint (Vint (Int.repr y)) py)\n  POST [ tvoid ]\n     PROP  ()\n     LOCAL ()\n     SEP   (data_at Tsh tuint (Vint (Int.repr x)) py;\n            data_at Tsh tuint (Vint (Int.repr y)) px).\n\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [ uint_swap_arith_spec ]).\n\nLemma body_uint_swap_arith: semax_body Vprog Gprog\n                              f_uint_swap_arith uint_swap_arith_spec.\nProof.\n  start_function.\n  repeat forward.\n  entailer!.\n  autorewrite with sublist. \n  entailer!.\nQed.\n\nEnd Verif_swap.\n(** [] *)\n\n(* ################################################################# *)\n(** * Task 3: Tri *)\n\nModule Verif_tri.\n\nImport EV.tri.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n(** C program:\n\n      unsigned int tri_for (int n) {\n        unsigned int s;\n        int i;\n        s = 0;\n        for (i = 0; i < n; ++ i)\n          s = s + i;\n        return s;\n      }\n\n      unsigned int tri_while (int n) {\n        unsigned int s;\n        s = 0;\n        while (n > 0) {\n          n = n - 1;\n          s = s + n;\n        }\n        return s;\n      }\n\n    Specification:\n*)\n\nDefinition tri_spec (_tri_name: ident) :=\n DECLARE _tri_name\n  WITH n: Z\n  PRE  [ _n OF tint ]\n     PROP  (0 <= n <=Int.max_signed)\n     LOCAL (temp _n (Vint (Int.repr n)))\n     SEP   ()\n  POST [ tuint ]\n     PROP  ()\n     LOCAL (temp ret_temp (Vint (Int.repr (n * (n-1)/2))))\n     SEP   ().\n\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [ tri_spec _tri_for; tri_spec _tri_while ]).\n\n(** Hint: in your proof, lemma [Z_div_plus_full] and tactic [ring] might be\n    helpful. (Ring is just a fancier version of omega which can also handle\n    multiplication. *)\nLemma body_tri_for: semax_body Vprog Gprog\n                            f_tri_for (tri_spec _tri_for).\nProof.\n  start_function.\n  forward.\n  forward_for_simple_bound n\n    (EX i: Z, EX i': nat,\n      PROP (i = Z.of_nat i')\n      LOCAL (temp _s (Vint (Int.repr (i * (i - 1) / 2)));\n             temp _n (Vint (Int.repr n)))\n      SEP ()).\n  {\n    Exists O.\n    entailer!.    \n  }\n  {\n    rename i'0 into i'.\n    forward.\n    Exists (S i').\n    entailer!.\n    split.\n    - rewrite Nat2Z.inj_succ; auto.\n    - f_equal.\n      f_equal.\n      replace (Z.of_nat i' + 1 - 1) with (Z.of_nat i'); [ | ring].\n      assert (forall z: Z, (z * (z - 1) / 2 + z = (z + 1) * z / 2)%Z). \n      {\n        intro. rewrite <- Z_div_plus; [ | omega].\n        assert (z * (z - 1) + z * 2 = (z + 1) * z)%Z; [ring | ].\n        rewrite <- H1; auto.\n      }\n      symmetry. auto.\n  }\n  Intros i'.\n  subst.\n  forward.\nQed.\n\nLemma body_tri_while: semax_body Vprog Gprog\n                            f_tri_while (tri_spec _tri_while).\nProof.\n  start_function.\n  forward.\n  forward_while \n    (EX n': Z, EX s': Z,\n      (PROP ((n' * (n' - 1) / 2 + s' = n * (n - 1) / 2)%Z; 0 <= n' <= Int.max_signed)\n       LOCAL (temp _n (Vint (Int.repr n'));\n              temp _s (Vint (Int.repr s')))\n       SEP ())).\n  {\n    Exists n.\n    Exists 0.\n    entailer!.\n  }\n  { \n    entailer!.\n  }\n  {\n    forward. (* n = n - 1 *)\n    forward. (* s = s + n *) \n    Exists (n' - 1 , s' + (n' - 1)).\n    entailer!.\n    split.\n    - rewrite <- H0.\n      rewrite Z.add_assoc, Z.add_shuffle0.\n      apply Z.add_cancel_r.\n      rewrite <- Z_div_plus; [ | omega].\n      assert ((n' - 1) * (n' - 1 - 1) + (n' - 1) * 2 = n' * (n' - 1))%Z; [ring | ].\n      rewrite H2; auto.\n    - split; [omega | f_equal; f_equal; omega].\n  }\n  assert (n' = 0); [omega | ].\n  subst.\n  replace (0 * (0 - 1) / 2 + s') with s' in H0; auto.\n  subst.\n  forward.\nQed.\n\nEnd Verif_tri.\n(** [] *)\n\n(* ################################################################# *)\n(** * Task 4: Greatst Common Divisor *)\n\nModule Verif_gcd.\n\nImport EV.gcd.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n(** C function [gcd]:\n\n      int gcd(int n, int m) {\n        int r = m % n;\n        if (r == 0)\n          return n;\n        else\n          return gcd(r, n);\n      }\n\n    This function calculates the greatest common divisor of two integers.\n    [Z.gcd] is defined as part of Coq's standard library. Using this definition,\n    we can write specification as follows:\n*)\n\nDefinition gcd_spec :=\n DECLARE _gcd\n  WITH n: Z, m: Z\n  PRE  [ _n OF tint, _m OF tint ]\n     PROP  (0 < n <= Int.max_signed;\n            0 <= m <= Int.max_signed)\n     LOCAL (temp _n (Vint (Int.repr n));\n            temp _m (Vint (Int.repr m)))\n     SEP   ()\n  POST [ tint ]\n     PROP  ()\n     LOCAL (temp ret_temp (Vint (Int.repr (Z.gcd n m))))\n     SEP   ().\n\nDefinition Gprog : funspecs := ltac:(with_library prog [ gcd_spec ]).\n\n(** We first provide three useful lemmas. You may use it in your proofs. *)\n\nLemma aux1: forall n, 0 < n <= Int.max_signed -> Int.repr n <> Int.zero.\nProof.\n  intros.\n  intro.\n  apply repr_inj_signed in H0.\n  + omega.\n  + rep_omega.\n    (* This VST tactic is used to handle linear programming with 32-bit bounds.\n       You can use it in your own proofs. *)\n  + rep_omega.\nQed.\n\nLemma aux2: forall m, 0 <= m <= Int.max_signed -> Int.repr m <> Int.repr Int.min_signed.\nProof.\n  intros.\n  intro.\n  apply repr_inj_signed in H0.\n  + rep_omega.\n    (* [rep_omega] can also solve normal linear proof goals. The proof goal\n       does not need to be [repable_signed]. *)\n  + rep_omega.\n  + rep_omega.\nQed.\n\nLemma mods_repr: forall n m,\n  Int.min_signed <= n <= Int.max_signed ->\n  Int.min_signed <= m <= Int.max_signed ->\n  Int.mods (Int.repr m) (Int.repr n) = Int.repr (Z.rem m n).\n(* Here [Z.rem] is the remainder of [m divides n]. *)\nProof.\n  intros.\n  unfold Int.mods.\n  rewrite Int.signed_repr by rep_omega.\n  rewrite Int.signed_repr by rep_omega.\n  reflexivity.\nQed.\n\n(** Now, fill in the holes in the following proof. *)\nLemma body_gcd: semax_body Vprog Gprog f_gcd gcd_spec.\nProof.\n  start_function.\n  forward.\n  {\n    (* Hint: remember that you can use [aux1] and [aux2]. *)\n    entailer!.\n    split; [apply aux1; auto | ].\n    intro.\n    assert (Int.repr m <> Int.repr Int.min_signed) by (apply aux2; auto).\n    tauto.\n  }\n  rewrite mods_repr by rep_omega.\n  forward_if.\n  {\n    (* Hint: you can always use [Search] to find useful theorems in Coq's\n       standard library and VST's library. For example, [Z.gcd_rem] may be\n       useful. *)\n    forward.\n    entailer!.\n    f_equal.\n    f_equal.\n    replace (Z.gcd n m) with (Z.gcd (Z.rem m n) n); [ | apply Z.gcd_rem; omega].\n    apply repr_inj_signed in H1.\n    replace (Z.rem m n) with 0.\n    rewrite Z.gcd_0_l.\n    symmetry. apply Z.abs_eq.\n    omega.\n    assert (Z.rem m n <= m); [apply Zquot.Zrem_le; omega | ].\n    assert (0 <= Z.rem m n); [apply Z.rem_nonneg; omega | ].\n    rep_omega.\n    rep_omega.\n  }\n  {\n    assert (Z.rem m n <> 0).\n    { \n      unfold not; intro.\n      rewrite H2 in H1.\n      apply H1; reflexivity.\n    }\n    forward_call (Z.rem m n, n).\n    {\n      split; [ | omega].\n      assert (0 <= Z.rem m n); [apply Z.rem_nonneg; omega | ].\n      assert (Z.rem m n <= m); [apply Zquot.Zrem_le; omega | ].\n      rep_omega.\n    }\n    forward.\n    entailer!.\n    f_equal.\n    f_equal.\n    apply Z.gcd_rem.\n    omega.\n  }\nQed.\n\nEnd Verif_gcd.\n\nModule List_seg.\n\n(* ################################################################# *)\n(** * Task 5. List Segments *)\n\nImport EV.append.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n(** In this part, we will verify two C functions:\n\n      struct list {\n        unsigned int head;\n        struct list * tail;\n      };\n\n      unsigned sumlist (struct list *p) {\n        unsigned s = 0;\n        struct list * t = p;\n        unsigned h;\n        while (t) {\n           h = t->head;\n           t = t->tail;\n           s = s + h;\n        }\n        return s;\n      }\n\n      struct list *append (struct list *x, struct list *y) {\n        struct list *t, *u;\n        if (x==NULL)\n          return y;\n        else {\n          t = x;\n          u = t->tail;\n          while (u!=NULL) {\n            t = u;\n            u = t->tail;\n          }\n          t->tail = y;\n          return x;\n        }\n      }\n\n    Using [listrep], we can state their specification.\n*)\n\nDefinition t_struct_list := Tstruct _list noattr.\n\nFixpoint listrep (sigma: list Z) (x: val) : mpred :=\n match sigma with\n | h::hs => \n    EX y:val, \n      data_at Tsh t_struct_list (Vint (Int.repr h),y) x  *  listrep hs y\n | nil => \n    !! (x = nullval) && emp\n end.\n\nArguments listrep sigma x : simpl never.\n\nDefinition sum_int (sigma: list Z): Z :=\n  fold_right Z.add 0 sigma.\n\nDefinition sumlist_spec :=\n DECLARE _sumlist\n  WITH sigma : list Z, p: val\n  PRE [ _p OF (tptr t_struct_list) ]\n     PROP  ()\n     LOCAL (temp _p p)\n     SEP   (listrep sigma p)\n  POST [ tuint ]\n     PROP  ()\n     LOCAL (temp ret_temp (Vint (Int.repr (sum_int sigma))))\n     SEP   (listrep sigma p).\n\nDefinition append_spec :=\n DECLARE _append\n  WITH x: val, y: val, s1: list Z, s2: list Z\n  PRE [ _x OF (tptr t_struct_list) , _y OF (tptr t_struct_list)]\n     PROP()\n     LOCAL (temp _x x; temp _y y)\n     SEP (listrep s1 x; listrep s2 y)\n  POST [ tptr t_struct_list ]\n    EX r: val,\n     PROP()\n     LOCAL(temp ret_temp r)\n     SEP (listrep (s1++s2) r).\n\n(** Both C functions traverse a linked list using a while loop. Thus, the\n    keypoint of verifying them is to write down the correct loop invariant.\n    The following diagram demonstrates an intermediate state in traversing.\n\n        +---+---+            +---+---+   +---+---+   +---+---+   \n  x ==> |   |  ===> ... ===> |   | y ==> |   | z ==> |   |  ===> ... \n        +---+---+            +---+---+   +---+---+   +---+---+\n\n      | <==== Part 1 of sigma =====> |            | <== Part 2 ==> |\n\n      | <========================== sigma =======================> |\n\n    To properly describe loop invariants, we need a predicate to describe\n    the partial linked list from address [x] to address [y]. We provide its\n    definition for you. But it is your task to prove its important properties.\n*)\n\nFixpoint lseg (sigma: list Z) (x y: val) : mpred :=\n  match sigma with\n  | nil => !! (x = y) && emp\n  | h::hs => EX u:val, data_at Tsh t_struct_list (Vint (Int.repr h), u) x * lseg hs u y\n  end.\n\nArguments lseg sigma x y : simpl never.\n\nLemma singleton_lseg: forall (a: Z) (x y: val),\n  data_at Tsh t_struct_list (Vint (Int.repr a), y) x |-- lseg [a] x y.\nProof.\n  intros.\n  unfold lseg.\n  Exists y.\n  entailer!.\nQed.\n(** [] *)\n\n(** In the next lemma, try to understand how to use [sep_apply]. *)\nLemma lseg_nullval: forall sigma x,\n  lseg sigma x nullval |-- listrep sigma x.\nProof.\n  intros.\n  revert x; induction sigma; intros.\n  + unfold listrep, lseg.\n    entailer!. \n  + unfold lseg; fold lseg. \n    unfold listrep; fold listrep.\n    Intros u.\n    Exists u.\n    (** The following tactic \"apply\" [IHsigma] on the left side of derivation. *)\n    sep_apply (IHsigma u).\n    entailer!.\nQed.\n\nLemma lseg_lseg: forall (s1 s2: list Z) (x y z: val),\n  lseg s1 x y * lseg s2 y z |-- lseg (s1 ++ s2) x z.\nProof.\n  intros.\n  revert x; induction s1; intros.\n  - unfold lseg; fold lseg.\n    entailer!.\n    rewrite app_nil_l.\n    entailer!.\n  - replace ((a :: s1) ++ s2) with (a :: s1 ++ s2); [ | apply app_comm_cons].\n    unfold lseg; fold lseg.\n    Intros u.\n    Exists u.\n    sep_apply (IHs1 u).\n    entailer!.\nQed.\n(** [] *)\n\nLemma lseg_list: forall (s1 s2: list Z) (x y: val),\n  lseg s1 x y * listrep s2 y |-- listrep (s1 ++ s2) x.\nProof.\n  intros.\n  revert x; induction s1; intros.\n  - unfold listrep; fold listrep.\n    unfold lseg; fold lseg.\n    rewrite app_nil_l.\n    entailer!.\n  - replace ((a :: s1) ++ s2) with (a :: s1 ++ s2); [ | apply app_comm_cons].\n    unfold lseg; fold lseg.\n    unfold listrep; fold listrep.\n    Intros u.\n    Exists u.\n    sep_apply (IHs1 u).\n    entailer!.\nQed.\n(** [] *)\n\n(** Try to use prove the following assertion derivation use the lemmas above.\n    The first step is done for you. *)\nExample lseg_ex: forall s1 s2 s3 x y z,\n  lseg s1 x y * lseg s2 y z * lseg s3 z nullval |-- listrep (s1 ++ s2 ++ s3) x.\nProof.\n  intros.\n  sep_apply lseg_lseg.\n  sep_apply lseg_nullval.\n  sep_apply lseg_list.\n  rewrite app_assoc.\n  entailer!.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Task 6. Sum of a List *)\n\n(** Now, you are going to prove [sumlist] correct. The following lemmas are\n    copied from [verif_reverse2] for proof automation. *)\n\nLemma listrep_local_facts:\n  forall sigma p,\n   listrep sigma p |--\n   !! (is_pointer_or_null p /\\ (p=nullval <-> sigma=nil)).\nProof.\n  intros.\n  revert p; induction sigma; \n  unfold listrep; fold listrep; intros; normalize.\n  apply prop_right; split; simpl; auto. intuition.\n  entailer!.\n  split; intro. subst p. destruct H; contradiction. inv H2.\nQed.\n\nHint Resolve listrep_local_facts : saturate_local.\n\nLemma listrep_valid_pointer:\n  forall sigma p,\n   listrep sigma p |-- valid_pointer p.\nProof.\n  destruct sigma; unfold listrep; fold listrep;\n  intros; normalize.\n  auto with valid_pointer.\n  apply sepcon_valid_pointer1.\n  apply data_at_valid_ptr; auto.\n  simpl; computable.\nQed.\n\nHint Resolve listrep_valid_pointer : valid_pointer.\n\nModule sumlist.\n\n(** Another auxiliary lemma. Hint: use [Search] when you need to find a\n    lemma. *)\nLemma sum_int_snoc:\n  forall a b, sum_int (a++b :: nil) = (sum_int a) + b.\nProof.\n  induction a; intros; [simpl; omega | ].\n  simpl. \n  rewrite <- Z.add_assoc.\n  apply Z.add_cancel_l.\n  apply IHa.\nQed.\n(** [] *)\n\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [ sumlist_spec ]).\n\n(** Hint: take a look at Verif_reverse and learn its proof strategy. *)\nLemma body_sumlist: semax_body Vprog Gprog f_sumlist sumlist_spec.\nProof.\n  start_function.\n  forward.\n  forward.\n  forward_while\n    (EX s1: list Z, EX s2: list Z,\n     EX t: val, EX s: Z,\n        PROP (sigma = s1 ++ s2; s = sum_int s1)\n        LOCAL (temp _t t; temp _p p; temp _s (Vint (Int.repr s)))\n        SEP (lseg s1 p t; listrep s2 t)).\n  {\n    Exists (@nil Z) sigma p 0.\n    unfold lseg; fold lseg.\n    entailer!.\n  }\n  {\n    entailer!.\n  }\n  {\n    assert_PROP(s2 <> nil). {\n      entailer!.\n      assert(t = nullval); [apply H1; auto | subst].\n      apply HRE.\n    }\n    destruct s2 as [ | s2a s2b]; [congruence | clear H1].\n    unfold listrep.\n    Intros y. \n    forward.\n    forward.\n    forward.\n    entailer!.\n    Exists ((s1 ++ [s2a]), s2b, y, sum_int (s1 ++ [s2a])).\n    entailer!.\n    - split.\n      + induction s1; auto; simpl.\n        apply cons_congr; auto.\n      + f_equal. f_equal. unfold sum_int.\n        apply sum_int_snoc.\n    - fold listrep. \n      sep_apply singleton_lseg.\n      entailer!.\n      sep_apply pull_left_special0.\n      sep_apply lseg_lseg.\n      entailer!.\n  }\n  forward.\n  entailer!.\n  f_equal.\n  f_equal.\n  assert(s2 = []); [apply H1; auto | subst].\n  rewrite app_nil_r; auto.\n  apply lseg_list.\nQed.\n(** [] *)\n\nEnd sumlist.\n\n(* ################################################################# *)\n(** * Task 7: Append *)\n\nModule append.\n\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [ append_spec ]).\n\nLemma body_append: semax_body Vprog Gprog f_append append_spec.\nProof.\n  start_function.\n  forward_if.\n  {\n    forward.\n    Exists y.\n    assert (s1 = []); [apply H0; auto | subst].\n    unfold listrep; fold listrep.\n    simpl. entailer!.\n  }\n  forward.\n  assert_PROP (exists s1a s1b, s1 = s1a :: s1b);\n    [entailer!; destruct s1; [tauto | eauto] | ].\n  destruct H0 as [s1a [s1b ?]].\n  subst s1.\n  unfold listrep at 1; fold listrep.\n  Intros u'.\n  forward.\n  forward_while\n    (EX (s11: list Z) (s12: list Z) (t: val) (u: val) (mid: Z),\n        PROP (s1a :: s1b = s11 ++ mid :: s12)\n        LOCAL (temp _t t; temp _u u; temp _x x; temp _y y)\n        SEP (lseg s11 x t; listrep s12 u; listrep s2 y;\n        data_at Tsh t_struct_list (Vint (Int.repr mid), u) t))%assert. \n  {\n    Exists (@nil Z) s1b x u' s1a.\n    unfold lseg. \n    entailer!.\n  }\n  {\n    entailer!.\n  }\n  {\n    forward.\n    assert_PROP(s12 <> nil); [entailer!; apply HRE, H1; auto | ].\n    destruct s12 as [ | s12a s12b]; [tauto | clear H1].\n    unfold listrep at 1; fold listrep.\n    Intros y0. \n    forward.\n    entailer!.\n    Exists (s11 ++ [mid], s12b, u, y0, s12a).\n    entailer!.\n    - rewrite H0.\n      rewrite <- app_assoc.\n      induction s11; auto.\n    - entailer!.\n      sep_apply singleton_lseg.\n      sep_apply pull_left_special0.\n      sep_apply lseg_lseg.\n      entailer!.\n  } \n  forward.\n  forward.\n  Exists x.\n  assert(s12 = []); [apply H1; auto | subst].\n  sep_apply singleton_lseg.\n  unfold listrep at 1; fold listrep.\n  sep_apply pull_left_special0.\n  sep_apply lseg_lseg.\n  sep_apply lseg_list.\n  rewrite H0.\n  entailer!.\nQed.\n(** [] *)\n\nEnd append.\n\n(* ################################################################# *)\n(** * Task 8: List box segments *)\n\n(** Now, consider this alternative implementation of append:\n\n      void append2(struct list * * x, struct list * y) {\n        struct list * h;\n        h = * x;\n        while (h != NULL) {\n          x = & (h -> tail);\n          h = * x;\n        }\n        * x = y;\n      }\n\n    You should prove:\n*)\n\nModule append2.\n\nDefinition append2_spec :=\n DECLARE _append2\n  WITH x: val, y: val, s1: list Z, s2: list Z, p :val\n  PRE [ _x OF (tptr (tptr t_struct_list)) , _y OF (tptr t_struct_list)]\n     PROP()\n     LOCAL (temp _x x; temp _y y)\n     SEP (data_at Tsh (tptr t_struct_list) p x;\n          listrep s1 p;\n          listrep s2 y)\n  POST [ tvoid ]\n     EX q: val,\n     PROP()\n     LOCAL()\n     SEP (data_at Tsh (tptr t_struct_list) q x;\n          listrep (s1 ++ s2) q).\n\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [ append2_spec ]).\n\n(** You may find it inconvenient to complete this proof directly using [listrep]\n    and [lseg]. You may need another predicate for [list box segment].\n\n         +---+---+            +---+---+   +---+---+   +---+---+   \n   p ==> |   |  ===> ... ===> |   |   ==> |   |   ==> |   |  ===> ... \n         +---+---+            +---+---+   +---+---+   +---+---+\n\n       | <====            list segment      =====> |\n\n | <====           list box segment     =====> |\n\n    Try to define this predicate by yourself and prove [lbseg_lseg].\n*)\n\nFixpoint lbseg (sigma: list Z) (x y: val) : mpred :=\n  match sigma with\n  | nil => !! (x = y) && emp\n  | h::hs => EX (u: val), data_at Tsh (tptr t_struct_list) u x *\n                          field_at Tsh t_struct_list [StructField _head] (Vint (Int.repr h)) u *\n                          lbseg hs (field_address t_struct_list [StructField _tail] u) y\n  end.\n(** [] *)\n\nLemma lbseg_lseg: forall s3 x y z,\n  lbseg s3 x y * data_at Tsh (tptr t_struct_list) z y |--\n  EX y', data_at Tsh (tptr t_struct_list) y' x * lseg s3 y' z.\nProof.\n  intros s3.\n  induction s3; intros.\n  - unfold lbseg; fold lbseg.\n    unfold lseg; fold lseg.\n    Exists z.\n    entailer!.\n  - unfold lbseg; fold lbseg.\n    unfold lseg; fold lseg.\n    Intros u. Exists u.\n    sep_apply IHs3.\n    Intros y'. Exists y'. \n    unfold_data_at (data_at Tsh t_struct_list _ _).\n    entailer!.\nQed.\n(** [] *)\n\nLemma lbseg_app_r: forall s v x x' h,\n  lbseg s x x' *\n  field_at Tsh t_struct_list [StructField _head] (Vint (Int.repr v)) h *\n  data_at Tsh (tptr t_struct_list) h x'\n  |-- lbseg (s ++ [v]) x\n      (field_address t_struct_list [StructField _tail] h).\nProof.\n  intros s.\n  induction s; intros.\n  - rewrite app_nil_l.\n    unfold lbseg; fold lbseg.\n    Exists h.\n    entailer!.\n  - unfold lseg; fold lseg.\n    rewrite <- app_comm_cons.\n    unfold lbseg; fold lbseg.\n    Intro u. Exists u.\n    entailer!.\n    sep_apply IHs.\n    entailer!.\nQed.\n\n(** Hint: adding more lemmas for [lbseg] may be useful. *)\nLemma body_append2: semax_body Vprog Gprog f_append2 append2_spec.\n  start_function.\n  forward.\n  forward_while\n    (EX (s11 s12: list Z) (h: val) (x': val),\n        PROP (s1 = s11 ++ s12)\n        LOCAL (temp _h h; temp _x x'; temp _y y)\n        SEP (lbseg s11 x x'; listrep s12 h; \n             listrep s2 y; data_at Tsh (tptr t_struct_list) h x'))%assert.\n  {\n    Exists (@nil Z) s1 p x.\n    unfold lbseg; fold lbseg.\n    entailer!.\n  }\n  {\n    entailer!.\n  }\n  {\n    assert_PROP (s12 <> []); [entailer!; apply HRE, H0; auto | ].\n    destruct s12 as [ | s12a s12b]; [exfalso; auto | subst].\n    unfold listrep; fold listrep.\n    forward.\n    - entailer!. unfold is_pointer_or_null in PNh.\n      unfold nullval in HRE.\n      destruct h; auto.\n      destruct (Archi.ptr64) eqn: HArchi; auto.\n      rewrite PNh in HRE; exfalso; auto.\n    - clear H0. simpl.\n      Intros y0.\n      unfold_data_at (data_at Tsh t_struct_list _ _).\n      Fail forward.\n      assert_PROP (offset_val 4 h = field_address t_struct_list [StructField _tail] h). {\n        entailer!.\n        rewrite field_address_offset; auto.\n      }\n      forward.\n      entailer!.\n      Exists (s11 ++ [s12a], s12b, y0, field_address t_struct_list [StructField _tail] h).\n      entailer!.\n      + rewrite <- app_assoc. induction s11; auto.\n      + entailer!. sep_apply lbseg_app_r. entailer!.\n  }\n  forward.\n  sep_apply lbseg_lseg.\n  Intro y'.\n  Exists y'.\n  entailer!.\n  assert (s12 = []); [apply H2; auto | subst].\n  unfold listrep; fold listrep.\n  rewrite app_nil_r.\n  entailer!.\n  sep_apply lseg_list.\n  entailer!.\nQed.\n(** [] *)\n\nEnd append2.\n\nEnd List_seg.\n", "meta": {"author": "Galaxies99", "repo": "VST-Tutorial", "sha": "8af993ec6342b84dd916fb79ad39e9543c979397", "save_path": "github-repos/coq/Galaxies99-VST-Tutorial", "path": "github-repos/coq/Galaxies99-VST-Tutorial/VST-Tutorial-8af993ec6342b84dd916fb79ad39e9543c979397/Exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.6934535128905075}}
{"text": "(* My first theorem. *)\n\nDefinition pierce := forall (p q : Prop),\n((p -> q) -> p) -> p.\n\nDefinition lem := forall p, p \\/ ~ p.\n\nTheorem pierce_equiv_lem: pierce <-> lem.\nProof.\n  unfold pierce, lem.\n  firstorder.\n  apply H with (q := ~ (p \\/ ~ p)).\n  tauto.\n  firstorder.\n  destruct (H p).\n  assumption.\n  tauto.\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/first_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252812, "lm_q2_score": 0.7549149813536516, "lm_q1q2_score": 0.6933744962920425}}
{"text": "Require Import Coq.Reals.Reals.\nRequire Import Coquelicot.Coquelicot.\nRequire Import Coq.micromega.Psatz.\nRequire Import ChargeCore.Logics.ILogic.\nRequire Import ChargeCore.Tactics.Tactics.\nRequire Import Control.Arithmetic.\nRequire Import Control.Barrier.\nRequire Import Control.Syntax.\nRequire Import Control.BarrierRules.\nRequire Import SMTC.Tactic.\n\nSet SMT Solver \"z3\".\nLocal Transparent ILInsts.ILFun_Ops.\n\nSection DblInt.\n\n  (* The state of the system, position and velocity. *)\n  (* Represented as a pair because Coquelicot has a NormedModule instance for pairs. *)\n  Definition stateT : Type := R * R.\n  Canonical state : NormedModule R_AbsRing :=\n    prod_NormedModule R_AbsRing R_NormedModule R_NormedModule.\n  Definition x : state -> R := fst.\n  Definition v : state -> R := snd.\n\n  (* The controller for the system. We leave it as a variable\n     and impose conditions on it, rather than making it a concrete\n     function. This allows one to instantiate it with anything\n     satisfying those conditions. *)\n  Variable u : state -> R.\n  (* The maximum control magnitude. *)\n  Variable umax : R.\n  Hypothesis umax_gt_0 : umax > 0.\n  Variable umin : R.\n  Hypothesis umin_gt_0 : umin > 0.\n  Hypothesis u_le_umax : forall st, u st <= umax.\n  Hypothesis neg_umax_le_u : forall st, -umin <= u st.\n\n  (* The bound between sample times. *)\n  Variable T : R.\n  Hypothesis T_gt_0 : T > 0.\n\n  (* Some design parameters of the control constraints. *)\n  Variable gamma : R.\n  Hypothesis gamma_gt_0 : gamma > 0.\n\n  (* Upper bound on u to enforce barrier invariance. *)\n  Definition u_ub (st : state) :=\n    if Rle_dec (v st) (umax * gamma)\n    then (-1 / T * (gamma * v st + x st) - v st)/gamma\n    else umax*(-1/T * (x st + umax * gamma * gamma/2 + v st * v st / (2 * umax)) - v st)/v st.\n  Hypothesis u_barrier_constraint : forall st,\n      u st <= u_ub st.\n\n  (* A relationship between the various parameters to ensure\n     that a control satisfying all constraints exists. *)\n  Hypothesis umax_le_f_umin : umax <= umin/(1 + 2 * T/gamma).\n\n  (* The sampled data evolution of the system, x' = v, v' = u *)\n  Definition ODE (st' st smpl : state) : Prop :=\n    x st' = v st /\\ v st' = u smpl.\n\n  (* The primary barrier function for this system. *)\n  (* x + (umaxc*gamma^2)/2 + v^2/(2umaxc^2) *)\n  Definition Barrier_sqr : barrier state :=\n    x [+] (#umax[*]#gamma[*]#gamma[/]#2) [+] v[*]v[/](#2[*]#umax).\n  (* gamma*v + x *)\n  Definition Barrier_lin : barrier state :=\n    (#gamma[*]v) [+] x.\n  Definition Barrier : barrier state :=\n    v ?<= umax*gamma [?] Barrier_lin [:] Barrier_sqr.\n\n  Definition violation := 2 * umax * T.\n  Lemma zero_le_violation : 0 <= violation.\n  Proof.\n    unfold violation. psatz R.\n  Qed.\n\n  Lemma exists_input :\n    forall st, Barrier st <= violation * T ->\n                 -umin <= u_ub st.\n  Proof.\n    unfold Barrier, violation, u_ub. intros. destruct st as [X V]. simpl in *.\n    assert (/gamma > 0) as gamma_inv by (apply Rlt_gt; apply Rinv_0_lt_compat; psatzl R).\n    assert (/T > 0) as T_inv by (apply Rlt_gt; apply Rinv_0_lt_compat; psatzl R).\n    destruct (Rle_dec V (umax * gamma)).\n    { unfold Barrier_lin in *. simpl in *.\n      transitivity ((-1 / T * 2 * umax * T * T - V) / gamma).\n      { unfold Rdiv. rewrite r by psatzl R. field_simplify; try psatzl R.\n        assert (-umin / (1 + 2 * T / gamma) <= -umax) by psatzl R.\n        unfold Rdiv. unfold Rminus. replace (-2 * T * umax) with (2 * T * -umax) by field.\n        replace (- (umax * gamma)) with (-umax * gamma) by field.\n        rewrite <- H0 by psatzl R. right. field. psatzl R. }\n      { unfold Rdiv. apply Rmult_le_compat_r; try psatzl R. apply Rplus_le_compat_r.\n        repeat rewrite Rmult_assoc. apply Rmult_le_compat_neg_l; [ psatzl R | ].\n        apply Rmult_le_compat_l; psatzl R. } }\n    { unfold Barrier_sqr in *. simpl in *.\n      assert (0 <= / V) as V_inv by (left; apply Rlt_gt; apply Rinv_0_lt_compat; psatz R).\n      transitivity (umax * (-1 / T * 2 * umax * T * T - V) / V).\n      { replace (umax * (-1 / T * 2 * umax * T * T - V) / V)\n        with (2 * (- umax) * umax * T * / V + - umax) by (field; psatz R).\n        assert (-umin / (1 + 2 * T / gamma) <= -umax) by psatzl R.\n        rewrite <- H0; try psatzl R.\n        { replace (2 * (- umin / (1 + 2 * T / gamma)) * umax * T * / V)\n          with (2 * (umin / (1 + 2 * T / gamma)) * umax * T * (/ -V)) by (field; psatz R).\n          assert (/( - umax * gamma) <= / - V).\n          { left. apply Rinv_lt_contravar.\n            { ring_simplify. repeat apply Rmult_lt_0_compat; psatz R. }\n            { psatzl R. } }\n          rewrite <- H1.\n          { right. field. psatz R. }\n          { apply Rle_ge. left. repeat (apply Rmult_lt_0_compat; [ | psatzl R]). psatzl R. } } }\n      { apply Rmult_le_compat_r; auto. apply Rmult_le_compat_l; [ psatzl R | ].\n        apply Rplus_le_compat_r. repeat rewrite Rmult_assoc.\n        apply Rmult_le_compat_neg_l; psatzl R. } }\n  Qed.\n\n  (* Derivative of the barrier function. *)\n  (* x' + v*v'/umaxc *)\n  Definition dBarrier_sqr : dbarrier state :=\n    d[x] [[+]] $[v][[*]]d[v][[/]]##umax.\n  (* gamma*v' + x' *)\n  Definition dBarrier_lin : dbarrier state :=\n    ##gamma[*]d[v] [[+]] d[x].\n  Definition dBarrier : dbarrier state :=\n    $[v] ??<= umax*gamma [?] dBarrier_lin [:] dBarrier_sqr.\n\n  Lemma dBarrier_valid :\n      derive_barrier Barrier dBarrier.\n  Proof.\n    eapply Proper_derive_barrier_dom\n    with (G1:=ltrue) (G2:=fun _ => True) (e1:=Barrier).\n    { reflexivity. }\n    { breakAbstraction. intros. reflexivity. }\n    { unfold Barrier, Barrier_sqr, Barrier_lin.\n      apply derive_barrier_piecewise.\n      { auto_derive_barrier.\n        { apply derive_barrier_snd_R. }\n        { apply derive_barrier_fst_R. } }\n      { auto_derive_barrier.\n        { apply derive_barrier_fst_R. }\n        { simpl. intros. psatzl R. }\n        { apply derive_barrier_snd_R. }\n        { apply derive_barrier_snd_R. }\n        { simpl. intros. psatzl R. } }\n      { simpl. intros. destruct H. rewrite H0. rewrite_R0.\n        unfold Rdiv at 1. rewrite_R0. field. psatzl R. }\n      { simpl. intros. destruct H. rewrite H0. field. psatzl R. }\n      { intros. apply continuous_snd. } }\n    { unfold dBarrier, dBarrier_sqr, dBarrier_lin.\n      simpl. intros. destruct (Rle_dec (v t0) (umax * gamma)).\n      { rewrite_R0. unfold v, x. reflexivity. }\n      { rewrite_R0. destruct t. destruct t0. simpl. field. psatzl R. } }\n  Qed.\n\n  (* The derivative of the barrier function is continuous. *)\n  Lemma continuous_dBarrier :\n    continuous_dB ltrue dBarrier.\n  Proof.\n    unfold dBarrier, dBarrier_sqr, dBarrier_lin.\n    apply continuous_dB_piecewise.\n    { auto_continuous_dB; try continuous_dB_vars. }\n    { auto_continuous_dB; try continuous_dB_vars.\n      simpl. intros. psatzl R. }\n    { simpl.  intros. rewrite H. field. psatzl R. }\n    { intros. apply continuous_snd. }\n  Qed.\n\n  (* The relation characterizing intersample behavior of the system. *)\n  Definition intersample (smpl st : state) : Prop :=\n    if Rle_dec 0 (u smpl)\n    then v smpl <= v st <= v smpl + u smpl * T\n    else v smpl + u smpl * T <= v st <= v smpl.\n\n  (* The intersample relation is a valid characterization of intersample behavior. *)\n  Lemma intersample_valid :\n    forall (sample : nat -> R),\n      bounded_samples sample T ->\n      sampled_data ODE sample |--\n      intersample_relation_valid2 intersample sample.\n  Proof.\n    intros. simpl. unfold sampled_data, intersample_relation_valid2.\n    intros F Hsol n t Ht. unfold intersample. destruct Hsol as [D [Dcont [DF DFf]]].\n    unfold ODE in DFf.\n    assert (forall t,\n               sample n <= t < sample (S n) ->\n               is_derive (fun t => v (F t)) t (u (F (sample n)))) as Hderive.\n    { intros. specialize (DFf n t0 H0). destruct DFf. rewrite <- H2. apply is_derive_snd; auto. }\n    assert (is_RInt (fun _ => (u (F (sample n)))) (sample n) t (v (F t) - v (F (sample n)))) as HRInt.\n    { apply is_RInt_derive with (f:=fun t => v (F t)).\n      { intros. apply Hderive. rewrite Rmin_left in H0 by psatzl R.\n        rewrite Rmax_right in H0 by psatzl R. psatzl R. }\n      { intros. apply continuous_const. } }\n    apply is_RInt_unique in HRInt. rewrite RInt_const in HRInt.\n    destruct (Rle_dec 0 (u (F (sample n))));\n      specialize (H n); psatz R.\n  Qed.\n\n  Lemma intersample_derive_bound :\n    forall st' stk' st stk : state,\n      intersample stk st ->\n      ODE st' st stk -> ODE stk' stk stk ->\n      dBarrier st' st <= Rmax (dBarrier stk' stk + violation) 0.\n  Proof.\n    unfold violation, intersample, ODE, dBarrier. simpl. intros. destruct H0. destruct H1.\n    assert (/umax > 0) as umax_inv by (apply Rlt_gt; apply Rinv_0_lt_compat; psatzl R).\n    destruct (Rle_dec (v st) (umax * gamma)).\n    { destruct (Rle_dec (v stk) (umax * gamma)).\n      { unfold dBarrier_lin. simpl. rewrite H0. rewrite H2.\n        rewrite H1. rewrite H3. rewrite <- Rmax_l. destruct (Rle_dec 0 (u stk)).\n        { destruct H. rewrite H4. rewrite u_le_umax at 2 by psatzl R. psatz R. }\n        { destruct H. rewrite H4. rewrite <- zero_le_violation. psatzl R. } }\n      { destruct (Rle_dec 0 (u stk)).\n        { psatzl R. }\n        { destruct (Rle_dec (u stk) (-umax)).\n          { rewrite <- Rmax_r. unfold dBarrier_lin. simpl. rewrite H0. rewrite H2.\n            rewrite r0 by psatzl R. rewrite r. psatzl R. }\n          { rewrite <- Rmax_l. unfold dBarrier_lin, dBarrier_sqr. simpl. rewrite H0.\n            rewrite H2. rewrite H3. rewrite H1.\n            assert (gamma * u stk - v stk * u stk / umax <= umax * T).\n            { replace (gamma * u stk - v stk * u stk / umax)\n              with ((- u stk) * (v stk / umax - gamma)) by (field; psatzl R).\n              unfold Rdiv. assert (v stk <= v st - u stk * T) by psatzl R. rewrite H4 by psatzl R.\n              rewrite r by psatzl R. assert (- u stk <= umax) by psatzl R.\n              unfold Rminus. replace (- (u stk * T)) with ((- u stk) * T) by field.\n              rewrite H5 at 2 by psatzl R. rewrite H5.\n              { field_simplify; try psatzl R. }\n              { field_simplify; try psatzl R. rewrite Rmult_comm. field_simplify; try psatzl R. } }\n            psatz R. } } } }\n    { destruct (Rle_dec (v stk) (umax * gamma)).\n      { unfold dBarrier_lin, dBarrier_sqr. simpl. rewrite H0. rewrite H2.\n        rewrite H1. rewrite H3. destruct (Rle_dec 0 (u stk)).\n        { rewrite <- Rmax_l. destruct H. rewrite H4 at 1.\n          assert (v st * u stk / umax + u stk * T - gamma * u stk <= 2 * umax * T).\n          { replace (v st * u stk / umax + u stk * T - gamma * u stk)\n            with (u stk * (v st / umax + T - gamma)) by (field; psatzl R).\n            unfold Rdiv. rewrite H4 by psatzl R. rewrite r by psatzl R.\n            rewrite u_le_umax at 1.\n            { field_simplify; try psatzl R. repeat rewrite Rdiv_1. rewrite u_le_umax by psatzl R.\n              right. field. }\n            { apply Rle_ge. rewrite <- r0 by psatzl R. rewrite Rmult_0_l. rewrite Rplus_0_r.\n              field_simplify; psatzl R. } }\n          psatzl R. }\n        { psatzl R. } }\n      { unfold dBarrier_sqr. simpl. rewrite H0. rewrite H1. rewrite H2. rewrite H3.\n        destruct (Rle_dec 0 (u stk)).\n        { rewrite <- Rmax_l. destruct H.\n          replace (v st + v st * u stk / umax) with (v st * (1 + u stk / umax)) by (field; psatzl R).\n          rewrite H4.\n          { replace ((v stk + u stk * T) * (1 + u stk / umax))\n            with (v stk + v stk * u stk / umax + u stk * T + u stk * u stk * T / umax)\n              by (field; psatzl R).\n            repeat rewrite Rplus_assoc. repeat apply Rplus_le_compat_l.\n            rewrite u_le_umax at 1 by psatzl R. unfold Rdiv. rewrite u_le_umax at 1 by psatzl R.\n            rewrite u_le_umax at 1 by psatzl R. field_simplify; psatzl R. }\n          { apply Rle_ge. unfold Rdiv. rewrite <- r by psatzl R. psatzl R. } }\n        { destruct (Rle_dec (u stk) (-umax)).\n          { rewrite <- Rmax_r. unfold Rdiv. rewrite r by psatz R. right. field. psatzl R. }\n          { rewrite <- Rmax_l.\n            replace (v st + v st * u stk / umax)\n            with (v st * (1 + u stk / umax)) by (field; psatzl R).\n            destruct H. rewrite H4.\n            { rewrite <- zero_le_violation. right. field. psatzl R.  }\n            { assert (-umax <= u stk) by psatzl R. apply Rle_ge. unfold Rdiv.\n              rewrite <- H5 by psatzl R. right. field. psatzl R. } } } } }\n  Qed.\n\n  (* The \"inductive\" condition on the barrier function, i.e. its derivative\n     is proportional to its value. *)\n  Lemma Barrier_inductive :\n      |-- exp_condition2 _ Barrier dBarrier ODE (-1/T).\n  Proof.\n    unfold exp_condition2, Barrier, dBarrier, ODE, u_ub in *.\n    simpl. intros x xk Blah H. destruct H. specialize (u_barrier_constraint xk).\n    destruct (Rle_dec (v xk) (umax * gamma)).\n    { unfold dBarrier_lin, Barrier_lin. simpl. rewrite H. rewrite H0.\n      rewrite u_barrier_constraint; try psatzl R. right. field. psatzl R. }\n    { unfold dBarrier_sqr, Barrier_sqr. simpl. rewrite H. rewrite H0.\n      unfold Rdiv. rewrite u_barrier_constraint.\n      { right. field. repeat split; try psatzl R. psatz R. }\n      { psatz R. }\n      { apply Rgt_lt in umax_gt_0. apply Rinv_0_lt_compat in umax_gt_0. psatzl R. } }\n  Qed.\n\n  (* Invariance of the barrier region. *)\n  Theorem barrier_inv :\n    forall (sample : nat -> R),\n      well_formed_samples sample ->\n      bounded_samples sample T ->\n      sampled_data ODE sample //\\\\\n      !(Barrier [<=] #(violation * T))\n      |-- [](Barrier [<=] #(violation * T)).\n  Proof.\n    intros. eapply barrier_exp_condition_sampled3 with (P:=ltrue); eauto.\n    { apply dBarrier_valid. }\n    { apply continuous_dBarrier. }\n    { charge_tauto. }\n    { rewrite intersample_valid; [ charge_tauto | assumption ]. }\n    { rewrite <- Barrier_inductive. charge_tauto. }\n    { apply intersample_derive_bound. }\n    { unfold violation. psatz R. }\n    { unfold always. simpl. auto. }\n    { charge_tauto. }\n  Qed.\n\n  Lemma gamma_inv_gt_0 :\n   / gamma > 0.\n  Proof.\n    apply Rlt_gt; apply Rinv_0_lt_compat; psatzl R.\n  Qed.\n\n  Lemma barrier_imp_x_lt_0 :\n    forall stk : state,\n      $[ Barrier [<=] # (violation * T)]\n       |-- exp_inductive state (fun st' st : state => ODE st' st stk)\n       (x [-] # (violation * T)) (d[x] [[-]] ## 0)\n       (-/gamma).\n  Proof.\n    unfold Barrier, Barrier_lin, Barrier_sqr, exp_inductive, ODE. simpl. intros.\n    destruct H0. rewrite H0. rewrite_R0. pose proof gamma_inv_gt_0.\n    destruct (Rle_dec (v t0) (umax * gamma)).\n    { replace (- / gamma * (x t0 - violation * T))\n      with (/ gamma * (violation * T - x t0)) by (field; psatzl R).\n      rewrite <- H by psatzl R. right. field. psatzl R. }\n    { rewrite Rmult_comm. rewrite <- Ropp_mult_distr_r. rewrite Ropp_mult_distr_l.\n      apply Rle_div_r; [ psatzl R | ].\n      replace (- (x t0 - violation * T)) with (violation * T - x t0) by (field; psatzl R).\n      rewrite <- H. unfold Rdiv. assert (umax * gamma <= v t0) by psatzl R.\n      clear H n H3 H2 H0 H1 umax_le_f_umin u_barrier_constraint T_gt_0 umin_gt_0\n            u_le_umax neg_umax_le_u gamma_gt_0. apply Rmult_le_reg_l with (r:=2*umax).\n      { psatz R. }\n      { field_simplify; try psatzl R. repeat rewrite Rdiv_1. simpl. psatz R. } }\n  Qed.\n\n  Theorem x_lt_0 :\n    forall (sample : nat -> R),\n      well_formed_samples sample ->\n      bounded_samples sample T ->\n      sampled_data ODE sample //\\\\\n      !(Barrier [<=] #(violation * T)) //\\\\\n      !(x [-] #(violation * T) [<=] #0)\n      |-- [](x [-] #(violation * T) [<=] #0).\n  Proof.\n    intros. eapply barrier_exp_condition_sampled_weak\n            with (P:=Barrier [<=] #(violation * T)) (lambda:=(-/gamma)); eauto.\n    { apply derive_barrier_minus; [apply derive_barrier_fst_R | apply derive_barrier_pure]. }\n    { auto_continuous_dB. apply continuous_dB_dfst. }\n    { charge_tauto. }\n    { apply barrier_imp_x_lt_0. }\n    { rewrite <- barrier_inv; eauto. charge_tauto. }\n    { charge_tauto. }\n  Qed.\n\nEnd DblInt.\n", "meta": {"author": "dricketts", "repo": "barrier-sampled-data", "sha": "cb1e99f5e68466426d7746126716f1099bbedf22", "save_path": "github-repos/coq/dricketts-barrier-sampled-data", "path": "github-repos/coq/dricketts-barrier-sampled-data/barrier-sampled-data-cb1e99f5e68466426d7746126716f1099bbedf22/examples/DoubleIntegrator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6933068039764525}}
{"text": "Require Import TestSuite.admit.\n(* File reduced by coq-bug-finder from 138 lines to 78 lines. *)\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Universe Polymorphism.\nDelimit Scope object_scope with object.\nDelimit Scope morphism_scope with morphism.\nDelimit Scope category_scope with category.\nRecord Category (obj : Type) :=\n  {\n    Object :> _ := obj;\n    Morphism : obj -> obj -> Type;\n\n    Identity : forall x, Morphism x x;\n    Compose : forall s d d', Morphism d d' -> Morphism s d -> Morphism s d'\n  }.\n\nArguments Identity {obj%type} [!C%category] x%object : rename.\nArguments Compose {obj%type} [!C%category s%object d%object d'%object] m1%morphism m2%morphism : rename.\nBind Scope category_scope with Category.\n\nRecord Functor `(C : @Category objC) `(D : @Category objD)\n  := { ObjectOf :> objC -> objD;\n       MorphismOf : forall s d, C.(Morphism) s d -> D.(Morphism) (ObjectOf s) (ObjectOf d) }.\n\nRecord NaturalTransformation `(C : @Category objC) `(D : @Category objD) (F G : Functor C D)\n  := { ComponentsOf :> forall c, D.(Morphism) (F c) (G c) }.\n\nDefinition ProductCategory `(C : @Category objC) `(D : @Category objD)\n: @Category (objC * objD)%type\n  := @Build_Category _\n                     (fun s d => (C.(Morphism) (fst s) (fst d) * D.(Morphism) (snd s) (snd d))%type)\n                     (fun o => (Identity (fst o), Identity (snd o)))\n                     (fun s d d' m2 m1 => (Compose (fst m2) (fst m1), Compose (snd m2) (snd m1))).\n\nInfix \"*\" := ProductCategory : category_scope.\n\nRecord IsomorphismOf `{C : @Category objC} {s d} (m : C.(Morphism) s d) :=\n  { IsomorphismOf_Morphism :> C.(Morphism) s d := m;\n    Inverse : C.(Morphism) d s }.\n\nRecord NaturalIsomorphism `(C : @Category objC) `(D : @Category objD) (F G : Functor C D)\n  := { NaturalIsomorphism_Transformation :> NaturalTransformation F G;\n       NaturalIsomorphism_Isomorphism : forall x : objC, IsomorphismOf (NaturalIsomorphism_Transformation x) }.\n\nSection PreMonoidalCategory.\n  Context `(C : @Category objC).\n  Definition TriMonoidalProductL : Functor (C * C * C) C.\n    admit.\n  Defined.\n  Definition TriMonoidalProductR : Functor (C * C * C) C.\n    admit.\n  Defined. (** Replacing [admit. Defined.] with [Admitted.] satisfies the constraints *)\n  Variable Associator : NaturalIsomorphism TriMonoidalProductL TriMonoidalProductR.\n  (* Toplevel input, characters 15-96:\nError: Unsatisfied constraints:\nCoq.Init.Datatypes.28 <= Coq.Init.Datatypes.29\nTop.168 <= Coq.Init.Datatypes.29\nTop.168 <= Coq.Init.Datatypes.28\nTop.169 <= Coq.Init.Datatypes.29\nTop.169 <= Coq.Init.Datatypes.28\n (maybe a bugged tactic). *)\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/bugs/closed/HoTT_coq_099.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336302, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6933067924796424}}
{"text": "From mathcomp Require Import ssreflect ssrbool eqtype.\nRequire Import Arith List String Lia.\nRequire Import Program Relations Wellfounded Lexicographic_Product.\nFrom QuickChick Require Import QuickChick.\nFrom QuickChick.stlc Require Import monad.\n\nImport ListNotations.\n\nDefinition tvar := nat.\nDefinition var := nat.\n\nInductive type : Type :=\n| N : type\n| Arrow : type -> type -> type.\n\nDefinition type_eq_dec (t1 t2 : type) : {t1 = t2} + {t1 <> t2}.\nProof. do 2 decide equality. Defined.\n\nFixpoint type_size (tau : type) : nat :=\n  match tau with\n    | N => 0\n    | Arrow tau1 tau2 =>\n      1 + (type_size tau1 + type_size tau2)\n  end.\n\nDefinition lt_type (tau1 tau2 : type) : Prop :=\n  type_size tau1 < type_size tau2.\n\nLemma wf_lt_type : well_founded lt_type.\nProof.\n  unfold lt_type. apply wf_inverse_image. apply lt_wf.\nQed.\n\nInductive term : Type :=\n| Const : nat -> term\n| Id : var -> term\n| App : term -> term -> term\n| Abs : term -> term.\n\n(* Terms that do not have applications *)\nInductive app_free : term -> Prop :=\n| ConsNoApp : forall n, app_free (Const n)\n| IdNoApp : forall x, app_free (Id x)\n| AbsNoApp : forall (t : term),\n               app_free t -> app_free (Abs t).\n\n(* Number of applications in a term *)\nFixpoint app_no (t : term) : nat :=\n  match t with\n    | Const _ | Id _ => 0\n    | Abs t => app_no t\n    | App t1 t2 => 1 + (app_no t1 + app_no t2)\n  end.\n\nDefinition env := list type.\n\nInductive bind : env -> nat -> type -> Prop :=\n| BindNow   : forall tau env, bind (tau :: env) 0 tau\n| BindLater : forall tau tau' x env,\n    bind env x tau -> bind (tau' :: env) (S x) tau.\n\nInductive typing (e : env) : term -> type -> Prop :=\n| TId :\n    forall x tau,\n      nth_error e x = Some tau ->\n      typing e (Id x) tau\n| TConst :\n    forall n,\n      typing e (Const n) N\n| TAbs :\n    forall t tau1 tau2,\n      typing (tau1 :: e) t tau2 ->\n      typing e (Abs t) (Arrow tau1 tau2)\n| TApp :\n    forall t1 t2 tau1 tau2,\n      typing e t1 (Arrow tau1 tau2) ->\n      typing e t2 tau1 ->\n      typing e (App t1 t2) tau2.\n\nInductive typing' (e : env) : term -> type -> Prop :=\n| TId' :\n    forall x tau,\n      bind e x tau ->\n      typing' e (Id x) tau\n| TConst' :\n    forall n,\n      typing' e (Const n) N\n| TAbs' :\n    forall t tau1 tau2,\n      typing' (tau1 :: e) t tau2 ->\n      typing' e (Abs t) (Arrow tau1 tau2)\n| TApp' :\n    forall t1 t2 tau1 tau2 tau12,\n      typing' e t2 tau1 ->\n      typing' e t1 tau12 ->\n      tau12 = Arrow tau1 tau2 ->      \n      typing' e (App t1 t2) tau2.\n\nDerive Arbitrary for type.\nInstance dec_type (t1 t2 : type) : Dec (t1 = t2).\nProof. dec_eq. Defined.\nDerive ArbitrarySizedSuchThat for (fun x => bind env x tau).\nDerive ArbitrarySizedSuchThat for (fun t => typing' env t tau).\n\nInstance ESST_A2 (t t1 : type) : EnumSizedSuchThat _ (fun t2 => t = Arrow t1 t2) :=\n  { enumSizeST := fun _ => match t with\n                           | Arrow t1' t2 =>\n                             if t1 = t1'? then\n                               returnEnum (Some t2)\n                             else returnEnum None\n                           | _ => returnEnum None\n                           end }.\n\nDerive EnumSized for type.\nDerive EnumSizedSuchThat for (fun tau => bind env x tau).\nDerive EnumSizedSuchThat for\n       (fun tau => typing' env t tau).\n\nDerive DecOpt for (bind env t tau).\nDerive DecOpt for (typing' env t tau).\n\n\n\n\n\nInductive option_le : option nat -> option nat -> Prop :=\n    | opt_le_1 : option_le None None\n    | opt_le_2 : forall n, option_le None (Some n)\n    | opt_le_3 : forall n m : nat,\n                   n <= m -> option_le (Some n) (Some m).\n\n(* The following keeps track of the size of largest type that appears in a cut\n   in the derivation tree. Needed for verification purposes *)\nInductive typing_max_tau (e : env) : term -> type -> nat -> Prop :=\n| TIdMax :\n    forall x tau,\n      nth_error e x = Some tau ->\n      typing_max_tau e (Id x) tau 0\n| TConstMax :\n    forall n,\n      typing_max_tau e (Const n) N 0\n| TAbsMax :\n    forall t tau1 tau2 m,\n      typing_max_tau (tau1 :: e) t tau2 m ->\n      typing_max_tau e (Abs t) (Arrow tau1 tau2) m\n| TAppMax :\n    forall t1 t2 tau1 tau2 m1 m2,\n      typing_max_tau e t1 (Arrow tau1 tau2) m1 ->\n      typing_max_tau e t2 tau1 m2 ->\n      typing_max_tau e (App t1 t2) tau2 (max (type_size tau1) (max m1 m2)).\n\nLemma typing_max_tau_correct :\n  forall e t tau,\n    (exists m, typing_max_tau e t tau m) <->\n    typing e t tau.\nProof.\n  intros. split.\n  - move => [maxt H]. induction H; econstructor; eauto.\n  - move => H.\n    induction H; (try now eexists; econstructor; eauto).\n    destruct IHtyping as [m H']. exists m. constructor; auto.\n    destruct IHtyping1 as [m1 H1];\n    destruct IHtyping2 as [m2 H2]. eexists. econstructor; eauto.\nQed.\n\nLemma typing_max_no_app :\n  forall e t tau,\n    app_free t ->\n    typing e t tau ->\n    typing_max_tau e t tau 0.\nProof.\n  intros e t tau H. generalize e tau. clear e tau.\n  induction H; intros e tau H1; inversion H1; subst; constructor; auto.\nQed.\n\n(* Small step CBV semantics *)\nFixpoint is_value (t : term) : bool :=\n  match t with\n    | Const _ | Abs _ => true\n    | _ => false\n  end.\n\nFixpoint subst (y : var) (t1 : term) (t2 : term) : term :=\n  match t2 with\n    | Const n => Const n\n    | Id x =>\n      if eq_nat_dec x y then t1 else t2\n    | App t t' =>\n      App (subst y t1 t) (subst y t1 t')\n    | Abs t =>\n      subst (S y) t1 t\n  end.\n\nFixpoint step (t : term) : option term :=\n  match t with\n    | Const _ | Id _ => None | Abs x => None\n    | App t1 t2 =>\n      if is_value t1 then\n        match t1 with\n          | Abs t =>\n            if is_value t2 then ret (subst 0 t1 t)\n            else\n              t2' <- step t2;;\n              ret (App t1 t2')\n          | _ => None\n        end\n      else\n        t1' <- step t1;;\n        ret (App t1' t2)\n  end.\n\n(* Generators *)\nModule DoNotation.\nNotation \"'do!' X <- A ; B\" :=\n  (bindGen A (fun X => B))\n    (at level 200, X ident, A at level 100, B at level 200).\nEnd DoNotation.\nImport DoNotation.\n\n(* Sized generator of simple types *)\nFixpoint gen_type_size (n : nat) : G type :=\n  match n with\n    | 0 => returnGen N\n    | S n' =>\n      do! m <- choose (0, n');\n          liftGen2 Arrow (gen_type_size (n' - m)) (gen_type_size (n' - (n' - m)))\n  end.\n\n(* Generator of simple types *)\nDefinition gen_type : G type := bindGen arbitrary gen_type_size.\n\n(* Returns the list of bindings that have type tau in e *)\nDefinition vars_with_type (e : env) (tau : type) : list term :=\n  map (fun p => Id (snd p))\n      (filter (fun p => proj1_sig (Sumbool.bool_of_sumbool (type_eq_dec tau (fst p))))\n              (combine e (seq 0 (List.length e)))).\n\nDefinition sigT_of_prod {A B : Type} (p : A * B) : {_ : A & B} :=\n  let (a, b) := p in existT (fun _ : A => B) a b.\n\nDefinition lt_pair (c1 c2 : (nat * type)) : Prop :=\n  lexprod nat (fun _ => type) lt (fun _ => lt_type) (sigT_of_prod c1) (sigT_of_prod c2).\n\nLemma wf_lt_pair : well_founded lt_pair.\nProof.\n  unfold lt_pair. apply wf_inverse_image.\n  apply wf_lexprod. now apply Wf_nat.lt_wf. intros _; now apply wf_lt_type.\nQed.\n\n\n(* Generator of app-free well-typed terms of type tau *)\nFixpoint gen_term_no_app (tau : type)  (e : env) : G term :=\n  match vars_with_type e tau with\n    | [] =>\n      match tau with\n        | N => liftGen Const arbitrary\n        | Arrow tau1 tau2 =>\n          liftGen Abs (gen_term_no_app tau2 (tau1 :: e))\n      end\n    | def :: vars =>\n      oneOf_ (returnGen def)\n            [ match tau with\n                | N => liftGen Const arbitrary\n                | Arrow tau1 tau2 =>\n                   liftGen Abs (gen_term_no_app tau2 (tau1 :: e))\n              end;\n              elems_ def (def :: vars)]\n  end.\n\n(* Generator of well-typed terms of type tau. [fst p] is the maximum number of applications *)\nProgram Fixpoint gen_term_size (p : nat * type) {wf lt_pair p} : env -> G term :=\n  fun (e : env) => (* apparently with this trick we get a more manageable term *)\n  match p with\n    | (0, tau) => gen_term_no_app tau e\n    | (S n', tau) =>\n      match vars_with_type e tau with\n        | [] =>\n            oneOf_ (gen_term_no_app tau e)\n            [ (do! tau' <- gen_type;\n               do! m <- choose (0, n');\n               do! m' <- choose (n' -  m, n');\n               liftGen2 App (@gen_term_size (n' - m, (Arrow tau' tau)) _ e)\n                        (@gen_term_size (n' - m', tau') _ e));\n              (match tau with\n                 | N => liftGen Const arbitrary\n                 | Arrow tau1 tau2 =>\n                   liftGen Abs (@gen_term_size (S n', tau2) _ (tau1 :: e))\n               end)]\n        | def :: vars =>\n            oneOf_ (gen_term_no_app tau e)\n            [ (do! tau' <- gen_type;\n               do! m <- choose (0, n');\n               do! m' <- choose (n' - m, n');\n               liftGen2 App (@gen_term_size (n' - m, (Arrow tau' tau)) _ e)\n                        (@gen_term_size (n' - m', tau') _ e));\n              (match tau with\n                 | N => liftGen Const arbitrary\n                 | Arrow tau1 tau2 =>\n                   liftGen Abs (@gen_term_size (S n', tau2) _ (tau1 :: e))\n               end);\n              elems_ def (def :: vars) ]\n      end\n  end.\nSolve Obligations with\n  program_simpl; unfold lt_pair; apply left_lex; lia.\nSolve Obligations with\n  program_simpl; unfold lt_pair; apply right_lex; unfold lt_type; simpl; lia.\nNext Obligation.\n  unfold MR. apply wf_inverse_image. apply wf_lt_pair.\nDefined.\n\n\nDefinition gen_term_size_unfold (p : nat * type) (e : env) : G term :=\n  match p with\n    | (0, tau) => gen_term_no_app tau e\n    | (S n', tau) =>\n      match vars_with_type e tau with\n        | [] =>\n            oneOf_ (gen_term_no_app tau e)\n            [ (do! tau' <- gen_type;\n               do! m <- choose (0, n');\n               do! m' <- choose (n' - m, n');\n               liftGen2 App (gen_term_size (n' - m, (Arrow tau' tau)) e)\n                        (gen_term_size (n' - m', tau') e));\n              (match tau with\n                 | N => liftGen Const arbitrary\n                 | Arrow tau1 tau2 =>\n                   liftGen Abs (@gen_term_size (S n', tau2) (tau1 :: e))\n               end)]\n        | def :: vars =>\n            oneOf_ (gen_term_no_app tau e)\n            [ (do! tau' <- gen_type;\n               do! m <- choose (0, n');\n               do! m' <- choose (n' - m, n');\n               liftGen2 App (gen_term_size (n' - m, (Arrow tau' tau)) e)\n                        (@gen_term_size (n' - m', tau') e));\n              (match tau with\n                 | N => liftGen Const arbitrary\n                 | Arrow tau1 tau2 =>\n                   liftGen Abs (gen_term_size (S n', tau2) (tau1 :: e))\n               end);\n              elems_ def (def :: vars) ]\n      end\n  end.\n\nImport WfExtensionality.\n\nLemma gen_term_size_eq (e : env) (p : nat * type) :\n  gen_term_size p e =\n  gen_term_size_unfold p e.\nProof.\n  unfold_sub gen_term_size (gen_term_size p e); simpl.\n  destruct p as [[|n] [|]]; try reflexivity;\n  destruct (vars_with_type e _) eqn:Heq; simpl;\n  repeat (rewrite !Heq /=; apply f_equal; try reflexivity).\nQed.\n\nGlobal Opaque gen_term_size.\n\nDefinition gen_term (tau : type) :=\n  sized (fun s => gen_term_size (s, tau) []).\n\n\nOpen Scope string.\n\nFixpoint show_type (tau : type) :=\n  match tau with\n    | N => \"Nat\"\n    | Arrow tau1 tau2 =>\n      \"(\" ++ show_type tau1 ++ \" -> \" ++ show_type tau2 ++ \")\"\n  end.\n\nInstance showType : Show type := { show := show_type }.\n\nFixpoint show_term (t : term) :=\n  match t with\n    | Const n => show n\n    | Id x => \"Id\" ++ show x\n    | App t1 t2 => \"(\" ++ show_term t1 ++ \" \" ++ show_term t2 ++ \")\"\n    | Abs t => \"λ.(\" ++ show_term t ++ \")\"\n  end.\n\nClose Scope string.\n\nInstance showTerm : Show term := { show := show_term }.\n", "meta": {"author": "QuickChick", "repo": "QuickChick", "sha": "ca56cc21ecc76bc0e1443e917ce26c010980ae2f", "save_path": "github-repos/coq/QuickChick-QuickChick", "path": "github-repos/coq/QuickChick-QuickChick/QuickChick-ca56cc21ecc76bc0e1443e917ce26c010980ae2f/examples/stlc/new.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6932968064266584}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Sorting.Permutation.\n\nSection ListLexOrder.\n  Variable T : Type.\n  Variable cmp : T -> T -> comparison.\n\n  Fixpoint list_lex_cmp (ls rs : list T) : comparison :=\n    match ls , rs with\n      | nil , nil => Eq\n      | nil , _ => Lt\n      | _ , nil => Gt\n      | l :: ls , r :: rs =>\n        match cmp l r with\n          | Eq => list_lex_cmp ls rs\n          | x => x\n        end\n    end.\nEnd ListLexOrder.\n\nSection Sorting.\n  Variable T : Type.\n  Variable cmp : T -> T -> comparison.\n\n  Section insert.\n    Variable val : T.\n\n    Fixpoint insert_in_order (ls : list T) : list T :=\n      match ls with\n        | nil => val :: nil\n        | l :: ls' =>\n          match cmp val l with\n            | Gt => l :: insert_in_order ls'\n            | _ => val :: ls\n          end\n      end.\n  End insert.\n\n  Fixpoint sort (ls : list T) : list T :=\n    match ls with\n      | nil => nil\n      | l :: ls =>\n        insert_in_order l (sort ls)\n    end.\n\nEnd Sorting.\n\nLemma insert_in_order_inserts : forall T C x l,\n  exists h t, insert_in_order T C x l = h ++ x :: t /\\ l = h ++ t.\nProof.\n  clear. induction l; simpl; intros.\n  exists nil; exists nil; eauto.\n  destruct (C x a).\n  exists nil; simpl. eauto.\n  exists nil; simpl. eauto.\n  destruct IHl. destruct H. intuition. subst.\n  rewrite H0. exists (a :: x0). exists x1. simpl; eauto.\nQed.\n\nLemma sort_permutation : forall T (C : T -> T -> _) x,\n  Permutation (sort _ C x) x.\nProof.\n  induction x; simpl.\n  { reflexivity. }\n  { destruct (insert_in_order_inserts T C a (sort T C x)) as [ ? [ ? ? ] ].\n    destruct H. rewrite H. rewrite <- Permutation_cons_app. reflexivity. rewrite H0 in *. symmetry; auto. }\nQed.\n", "meta": {"author": "gmalecha", "repo": "mirror-shard", "sha": "24f34dee2f78de731f4ef398733ff2c1f1551375", "save_path": "github-repos/coq/gmalecha-mirror-shard", "path": "github-repos/coq/gmalecha-mirror-shard/mirror-shard-24f34dee2f78de731f4ef398733ff2c1f1551375/src/Ordering.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.6932767921157081}}
{"text": "Require Import Coqlib.\nRequire Import Integers.\nRequire Import List. Import ListNotations.\nRequire Import pure_lemmas.\n\nLemma skipn_add {A}: forall t n (ch:list A),\n      skipn (t+n) ch = skipn n (skipn t ch).\nProof.\n  induction t; simpl. trivial.\n  intros. destruct ch. \n    rewrite skipn_nil; trivial. \n  rewrite IHt; trivial.\nQed.\n\nLemma firstn_app1 {A}: forall n (l t:list A),\n   (n >= length l)%nat -> firstn n (l++t) = l ++ firstn (n-length l) t.\nProof. intros n; induction n; simpl; intros.\n  destruct l; simpl in *; trivial. omega.\n  destruct l; simpl in *. trivial. rewrite IHn. trivial. omega.\nQed.\n\nLemma firstn_nil {A}: forall m, firstn m (nil:list A) = (nil:list A).\nProof. intros. rewrite firstn_same. trivial. simpl. omega. Qed.\n\nLemma skipn_all {A}: forall l, skipn (length l) l = (nil:list A).\nProof. intros l.\n  induction l; simpl; trivial.\nQed.\nLemma skipn_all' {A}: forall n l, (n>=length l)%nat -> skipn n l = (nil:list A).\nProof. intros n.\n  induction n; simpl; trivial. intros. destruct l; simpl in *; trivial. omega. \n  intros. destruct l; simpl in *; trivial. apply IHn. omega.\nQed.\n\nLemma firstn_list_repeat1 {A} k n (x:A) (N: (n>=k)%nat):\n      firstn n (list_repeat k x) = list_repeat k x.\nProof.\n  intros. specialize (firstn_app1 n (list_repeat k x) nil).\n  rewrite app_nil_r. intros. rewrite H. \n   rewrite firstn_nil. apply app_nil_r.\n  rewrite length_list_repeat. apply N. \nQed.\n\nLemma firstn_list_repeat2 {A}: forall k n (x:A) (N: (n<=k)%nat),\n      firstn n (list_repeat k x) = list_repeat n x.\nProof.\n  intros k.\n  induction k. simpl. intros. destruct n; simpl. trivial. omega.\n  simpl; intros. destruct n; simpl in *.  trivial.\n  rewrite IHk. trivial. omega. \nQed.\n\nLemma firstn_geq {A}: forall k (l:list A),\n    (k>=length l)%nat ->  firstn k l = l.\nProof. \n  induction k; simpl; intros. destruct l; trivial. simpl in *; omega.\ndestruct l. trivial. f_equal. apply IHk. simpl in *; omega.\nQed.\n\nLemma rev_list_repeat {A} (a:A): forall n, rev (list_repeat n a) = list_repeat n a.\nProof. induction n; simpl; trivial. rewrite IHn; clear IHn.\nspecialize (list_repeat_app A); intros Q.\nrewrite (Q n (1%nat)).\nspecialize (Q (1%nat) n). rewrite plus_comm in Q. simpl in Q. rewrite Q; trivial.\nQed.  \n\nLemma zadd_zero_nonneg p q: 0 = p + q -> 0 <=p -> q>= 0 -> p=0 /\\ q=0.\nProof. omega. Qed.\n\nLemma list_nil_length {A} (l:list A): l= [] -> (length l <= 0)%nat.\nProof. intros. subst. trivial. Qed.\n\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/bn_pure_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.6932767899171558}}
{"text": "\nRequire Import Bool.Bvector.\nRequire Import ZArith.\nRequire Import QArith.\nRequire Import ZArith.Znumtheory.\nRequire Import ZArith.BinInt.\nRequire Import QArith.Qabs.\nRequire Import Vectors.Fin.\nRequire Import Vectors.VectorDef.\nRequire Import Vectors.VectorSpec.\nRequire Import Vectors.Vector.\n\nOpen Scope nat_scope.\n\nDefinition div_eucl_z := BinIntDef.Z.div_eucl.\n\nFixpoint getAcc (n:nat) : Q :=\nmatch n with\n|O => 1#1\n|S m => Qmult (1#10) (getAcc m)\nend.\n\n(*double*)\n\nDefinition lenExp : nat := 11. \nDefinition lenSign : nat :=52. \nDefinition sqrtEps : Q := getAcc 50.\n\n(*single*)\n(*\nDefinition lenExp : nat := 8. \nDefinition lenSign : nat :=23.\n(*1e-10*)\nDefinition sqrtEps : Q := getAcc 25.\n*)\nFixpoint getPowerTwo (power : nat) :=\nmatch power with\n|O => 1\n|S m => 2* (getPowerTwo m)\nend.\n\nFixpoint getMaxExp (lenExp : nat) : nat :=\nmatch lenExp with\n|O => O\n|S m => let result := getPowerTwo m in\n        match result with\n        |O => O\n        |S n => n\n        end\nend.\n\nFixpoint getAllFalseVector (len : nat) : Bvector len :=\nmatch len with\n|O => Vector.nil bool\n|S m => Vector.cons bool false m (getAllFalseVector m)\nend.\n\nFixpoint getAllTrueVector (len : nat) : Bvector len :=\nmatch len with\n|O => Vector.nil bool\n|S m => Vector.cons bool true m (getAllTrueVector m)\nend.\n\nFixpoint getNotAllFalseVector (len:nat) : Bvector len :=\nmatch len with\n|O => Vector.nil bool\n|S m => Vector.cons bool true m (getAllFalseVector m)\nend.\n\nFixpoint getBiasVector (len:nat) : Bvector len :=\nmatch len with\n|O => Vector.nil bool\n|S m => Vector.cons bool false m (getAllTrueVector m)\nend.\n\nDefinition shiftExp : nat := getMaxExp lenExp.\nDefinition maxExp : nat := getMaxExp lenExp.\n\nDefinition allTrueExp : Bvector lenExp := getAllTrueVector lenExp.\n\nDefinition allFalseExp : Bvector lenExp := getAllFalseVector lenExp.\n\nDefinition zeroExp : Bvector lenExp := getBiasVector lenExp.\n\nDefinition bias : Bvector lenExp := getBiasVector lenExp.\n\nDefinition allFalseSignificant : Bvector lenSign := getAllFalseVector lenSign.\n\n\nDefinition notAllFalseSignificant : Bvector lenSign := \ngetNotAllFalseVector lenSign.\n\n\nRecord fp_num : Set := mkFp\n{\n sign : bool;\n exp : Bvector lenExp;\n significant : Bvector lenSign\n}.\n\n\n\nDefinition NaN : fp_num := mkFp true allTrueExp notAllFalseSignificant.\nDefinition plusInfinity : fp_num := mkFp false allTrueExp allFalseSignificant.\nDefinition minusInfinity : fp_num := mkFp true allTrueExp allFalseSignificant.\nDefinition plusZero : fp_num := mkFp false allFalseExp allFalseSignificant.\nDefinition minusZero : fp_num := mkFp true allFalseExp allFalseSignificant.\n\n\n(* BEGIN *)\n(* determine type number *)\nFixpoint isVectAllTrue (n:nat) (v : Bvector n) : bool :=\n match v with \n  | Vector.nil => true\n  | Vector.cons h m w => if h then (isVectAllTrue m w) else false\n end.\n\nFixpoint isVectAllFalse (n:nat) (v : Bvector n) : bool :=\n match v with \n  | Vector.nil => true\n  | Vector.cons h m w => if h  then false else (isVectAllFalse m w)\n end.\n\nFixpoint isExpforZero (v : Bvector lenExp) : bool :=\n isVectAllFalse lenExp v.\n\nFixpoint isNaN (fp : fp_num) : bool := \nif isVectAllTrue lenExp fp.(exp) then \n  negb (isVectAllFalse lenSign fp.(significant) )\nelse false.\n\nFixpoint isInfinite (fp : fp_num) : bool :=\nif isVectAllTrue lenExp fp.(exp) then \n  isVectAllFalse lenSign fp.(significant) \nelse false.\n\nFixpoint isFinite (fp : fp_num) : bool := negb (isNaN fp || isInfinite fp).\n\nFixpoint isZero (fp : fp_num) : bool := \n (isExpforZero fp.(exp) && isVectAllFalse lenSign fp.(significant)).\n\n(* determine type number *)\n(* END *)\n\n\n(* BEGIN *)\n(* compare fp_num *)\nFixpoint compareSys (n:nat) (m:nat) (v1 : Bvector n) (v2 : Bvector m) : comparison :=\nmatch v1 with\n  | Vector.nil => Eq\n  | Vector.cons h1 m1 w1 => \n  match v2 with\n   | Vector.nil => Eq\n   | Vector.cons h2 m2 w2 => if eqb h1 h2 then compareSys m1 m2 w1 w2 else if h1 then Gt else Lt\n  end\n end.\n\nFixpoint compareVect (n:nat) (v1 v2 : Bvector n) : comparison := compareSys n n v1 v2.\n\nFixpoint compareExp (fp1 fp2 : fp_num) : comparison := compareVect lenExp fp1.(exp) fp2.(exp).\n\nFixpoint compareSignificant (fp1 : fp_num) (fp2 : fp_num) : comparison := \ncompareVect lenSign fp1.(significant) fp2.(significant).\n\nFixpoint compareSign (fp1 fp2 : fp_num) : comparison :=\nif eqb fp1.(sign) fp2.(sign) then Eq\nelse if fp1.(sign) then Lt else Gt.\n\nFixpoint compareAbs (fp1 fp2 : fp_num) : comparison :=\nmatch compareExp fp1 fp2 with\n   | Lt => Lt\n   | Gt => Gt\n   | Eq => compareSignificant fp1 fp2\nend.\n\nFixpoint compare (fp1 fp2 : fp_num) : comparison :=\nmatch compareSign fp1 fp2 with \n| Lt => Lt\n| Gt => Gt\n| Eq => match compareExp fp1 fp2 with\n   | Lt => Lt\n   | Gt => Gt\n   | Eq => compareSignificant fp1 fp2\n  end\nend.\n\n(*<*)\nFixpoint isLt (c:comparison) : bool :=\nmatch c with\n|Lt => true\n|_ => false\nend.\n\n(*==*)\nFixpoint isEq (c:comparison) : bool :=\nmatch c with\n|Eq => true\n|_ => false\nend.\n\n(*>*)\nFixpoint isGt (c:comparison) : bool :=\nmatch c with\n|Gt => true\n|_ => false\nend.\n\n(*<=*)\nFixpoint isLE (c:comparison) : bool :=\nmatch c with\n|Gt => false\n|_ => true\nend.\n\n(*!=*)\nFixpoint isNE (c:comparison) : bool :=\nmatch c with\n|Eq => false\n|_ => true\nend.\n\n(*>=*)\nFixpoint isGE (c:comparison) : bool :=\nmatch c with\n|Lt => false\n|_ => true\nend.\n\nFixpoint isGeFp_bool (x y :fp_num) : bool := isGE (compare x y).\nFixpoint isNeFp_bool (x y :fp_num) : bool := isNE (compare x y).\nFixpoint isLeFp_bool (x y :fp_num) : bool := isLE (compare x y).\nFixpoint isGtFp_bool (x y :fp_num) : bool := isGt (compare x y).\nFixpoint isLtFp_bool (x y :fp_num) : bool := isLt (compare x y).\nFixpoint isEqFp_bool (x y :fp_num) : bool := isEq (compare x y).\n\n(* compare fp_num *)\n(* END *)\n\n(* compare Q*)\n(* BEGIN *)\nFixpoint isGeQ_bool (x y :Q) : bool := isGE (Qcompare x y).\nFixpoint isNeQ_bool (x y :Q) : bool := isNE (Qcompare x y).\nFixpoint isLeQ_bool (x y :Q) : bool := isLE (Qcompare x y).\nFixpoint isGtQ_bool (x y :Q) : bool := isGt (Qcompare x y).\nFixpoint isLtQ_bool (x y :Q) : bool := isLt (Qcompare x y).\nFixpoint isEqQ_bool (x y :Q) : bool := isEq (Qcompare x y).\n(* compare Q*)\n(* END *)\n\nDefinition invertV (n : nat) := nat_rect (fun n => Bvector n -> Bvector n) \n(fun v => Bnil)\n(fun k x v => Bcons (Vector.last v) _ (x (Vector.shiftout v))).\n\nDefinition neg (fp : fp_num) : fp_num := mkFp (negb fp.(sign)) fp.(exp) fp.(significant).\n\nFixpoint abs (fp:fp_num) : fp_num := mkFp false fp.(exp) fp.(significant).\n\nDefinition sumDigits (carry a b : bool) : bool * bool :=\nif carry then \n  if a then\n   if b then (true,true)\n   else (true,false)\n  else\n   if b then (true,false)\n   else (false,true)\nelse\n if a then \n   if b then (true,false)\n   else (false,true)\n else\n   if b then (false,true)\n   else (false,false).\n\n(* a -(b+carry) *)\nDefinition diffDigits (carry a b : bool) : bool * bool :=\nif carry then\n  if b then \n    if a then (true,true)\n    else (true,false)\n  else \n    if a then (false,false)\n    else (true,true)\nelse\n if b then \n   if a then (false,false)\n   else (true,true)\n else\n   if a then (false,true)\n   else (false,false).\n\nFixpoint plusBoolInvV (n:nat) (b:bool) (v :Bvector n) : Bvector n :=\nif b then\n match v with\n  | Vector.nil => []\n  | Vector.cons h m w => let res := sumDigits b h false in\n     if fst res \n     then Vector.cons bool (snd res) m  (plusBoolInvV m (fst res) w)\n     else Vector.cons bool (snd res) m w\n end \nelse v.\n\nFixpoint minusBoolInvV (n:nat) (b:bool) (v :Bvector n) : Bvector n :=\nif b then\n match v with\n  | Vector.nil => []\n  | Vector.cons h m w => let res:=diffDigits b h false in \n     if fst res  \n     then Vector.cons bool (snd res) m (minusBoolInvV m (fst res) w)\n     else Vector.cons bool (snd res) m w\n end \nelse v.\n\nFixpoint plusBoolV (n:nat) (b:bool) (v :Bvector n) : Bvector n := \ninvertV n n (plusBoolInvV n b (invertV n n v)).\n\nFixpoint minusBoolV (n:nat) (b:bool) (v :Bvector n) : Bvector n := \ninvertV n n (minusBoolInvV n b (invertV n n v)).\n\nFixpoint plusTrueToExp (fp : fp_num) : fp_num :=\nmkFp fp.(sign) (plusBoolV lenExp true fp.(exp) ) fp.(significant).\n\nFixpoint minusTrueFromExp (fp : fp_num) : fp_num :=\nmkFp fp.(sign) (minusBoolV lenExp true fp.(exp) ) fp.(significant).\n\n(* remove last shift right add head *)\nDefinition shiftReplaceR (val : bool) : forall n : nat, (Bvector n -> Bvector n) := \nnat_rect (fun n => (Bvector n -> Bvector n)) \n(fun x => Bnil)\n(fun k x w => Bcons val _ (Vector.shiftout w)).\n\n(* remove head shift left add last *)\nDefinition shiftReplaceL (val : bool) (n:nat) (v : Bvector n) : Bvector n := \ninvertV n n (shiftReplaceR val n (invertV n n v)).\n\n\nDefinition shiftSignificantR (val : bool) (fp:fp_num) : fp_num := \nmkFp fp.(sign) fp.(exp) (shiftReplaceR val lenSign fp.(significant)).  \n\nDefinition shiftSignificantL (val : bool) (fp:fp_num) : fp_num := \nmkFp fp.(sign) fp.(exp) (shiftReplaceL val lenSign fp.(significant)).  \n\nFixpoint vect2NatSys (pow :nat) (n:nat) (v:Bvector n) : nat :=\nmatch v with\n |Vector.nil => O\n |Vector.cons h m w => if h then pow + (vect2NatSys (2*pow) m w)%nat else vect2NatSys (2*pow) m w\nend.\n\nFixpoint vect2Nat (n:nat) (v:Bvector n) : nat := vect2NatSys 1 n (invertV n n v).\n\nFixpoint exp2Nat (fp: fp_num) : nat := vect2Nat lenExp  fp.(exp).\n\nFixpoint nat2Vect (n len:nat) (v:Bvector len) (minus:bool) :Bvector len :=\nmatch n with \n|O => v\n|S m => let newV := if minus then \n                       minusBoolV len true v \n                    else plusBoolV len true v \n        in nat2Vect m len newV minus\nend.\n \n\n(* fp1.(exp) < fp2.(exp) *)\nFixpoint difExp (fp1 fp2 : fp_num) : nat :=(exp2Nat fp2 - exp2Nat fp1)%nat.\n\nFixpoint countZero (n:nat) (v: Bvector n) : nat := \nmatch v with\n|Vector.nil => O\n|Vector.cons h m w => if h then O else S (countZero m w)\nend.\n\nFixpoint alignmentExpSys (n:nat) (val:bool) (fp: fp_num) : fp_num :=\nmatch n with\n| O => fp\n| S m => alignmentExpSys m false (shiftSignificantR val (plusTrueToExp fp))\nend.\n\nFixpoint normalizeFpSys (n:nat) (val:bool) (fp: fp_num) : fp_num :=\nmatch n with\n| O => fp\n| S m => normalizeFpSys m false (shiftSignificantL val (minusTrueFromExp fp))\nend. \n\n(* fp1.(exp) < fp2.(exp)*)\nFixpoint alignmentExp (fp1 fp2 :fp_num) : fp_num :=\nalignmentExpSys (difExp fp1 fp2) true fp1.\n\nFixpoint normalizeFp (count:nat) (fp : fp_num) : fp_num :=\nnormalizeFpSys count false fp.\n\nFixpoint sumVectors (n : nat) := Vector.rect2 (n:=n) (fun n l r => prod bool (Bvector n)) \n(false, [])\n(fun n l r prev a b => let (carry, result) := (sumDigits (fst prev) a b) in (carry, result :: (snd prev))).\n\n(* abs fp1 > abs fp2 *)\nFixpoint diffVectors (n : nat) := Vector.rect2 (n:=n) (fun n l r => prod bool (Bvector n)) \n(false, [])\n(fun n l r prev a b => let (carry, result) := (diffDigits (fst prev) a b) in (carry, result :: (snd prev))).\n\n(* fp1.(exp) < fp2.(exp) *)\nFixpoint sumOneSignFpSysNotEq (fp1 : fp_num) (fp2 : fp_num) : fp_num :=\nlet sumRes := sumVectors lenSign (alignmentExp fp1 fp2).(significant) fp2.(significant) in \nif fst sumRes then mkFp fp1.(sign) (plusBoolV lenExp true fp2.(exp) ) (shiftReplaceR false lenSign (snd sumRes)) \nelse mkFp fp2.(sign) fp2.(exp) (snd sumRes).\n\n(* fp1.(exp) = fp2.(exp) *)\nFixpoint sumOneSignFpSysEq (fp1 : fp_num) (fp2 : fp_num) : fp_num :=\nlet sumRes := sumVectors lenSign fp1.(significant) fp2.(significant) in \nif fst sumRes then mkFp fp1.(sign) (plusBoolV lenExp true fp1.(exp) ) (shiftReplaceR true lenSign (snd sumRes)) \nelse mkFp fp1.(sign) (plusBoolV lenExp true fp1.(exp) ) (shiftReplaceR false lenSign (snd sumRes)).\n\nFixpoint sumOneSignFp (fp1 : fp_num) (fp2 : fp_num) : fp_num :=\nmatch compareExp fp1 fp2 with \n|Lt => sumOneSignFpSysNotEq fp1 fp2\n|Gt => sumOneSignFpSysNotEq fp2 fp1\n|Eq => sumOneSignFpSysEq fp2 fp1\nend.\n\n(* abs fp1 > abs fp2 *)\nFixpoint diffNotEqExpFp (fp1 : fp_num) (fp2 : fp_num) : fp_num :=\nlet res := diffVectors lenSign fp1.(significant) (alignmentExp fp2 fp1).(significant)  in \nif fst res then normalizeFp (S (countZero lenSign (snd res))) (mkFp fp1.(sign) fp1.(exp) (snd res))\nelse normalizeFp (countZero lenSign (snd res)) (mkFp fp1.(sign) fp1.(exp) (snd res)).\n\n(* abs fp1 > abs fp2 *)\nFixpoint diffEqExpFp (fp1 : fp_num) (fp2 : fp_num) : fp_num :=\nlet res := diffVectors lenSign  fp1.(significant) fp2.(significant) in \nnormalizeFp (S (countZero lenSign (snd res))) (mkFp fp1.(sign) fp1.(exp) (snd res)).\n\n(* abs fp1 > abs fp2 *)\nFixpoint diffFpSys (fp1 : fp_num) (fp2 : fp_num) : fp_num :=\nmatch compareExp fp1 fp2 with \n|Lt =>  diffNotEqExpFp fp2 fp1\n|Gt =>  diffNotEqExpFp fp1 fp2\n|Eq =>  diffEqExpFp fp1 fp2\nend.\n\nFixpoint diffFp2 (fp1 : fp_num) (fp2 : fp_num) : fp_num :=\nmatch compareAbs fp1 fp2 with\n     | Lt => diffFpSys fp2 fp1\n     | Gt => diffFpSys fp1 fp2\n     | Eq => if fp1.(sign) then minusZero else plusZero\nend.\n\nFixpoint sumFinite (fp1 : fp_num) (fp2 : fp_num) : fp_num :=\nif isZero fp1 then\n   fp2\nelse\n   if isZero fp2 then\n      fp1\n   else \n      match compareSign fp1 fp2 with\n      |Eq => sumOneSignFp fp1 fp2\n      | _ => diffFp2 fp1 fp2\n      end.\n\nFixpoint sumInfinite (fp1 : fp_num) (fp2 : fp_num) : fp_num :=\nif isInfinite fp1 then \n   if isInfinite fp2 then \n      match compareSign fp1 fp2 with \n       | Eq => fp1\n       | _ => NaN\n      end\n   else fp1\nelse fp2.\n\n\n\n\n\nFixpoint sumFp (fp1 fp2 : fp_num) : fp_num :=\nif isNaN fp1 || isNaN fp2 then NaN\nelse if isInfinite fp1 || isInfinite fp2 then sumInfinite fp1 fp2\n     else sumFinite fp1 fp2.\n\nFixpoint diffFp (fp1 fp2 : fp_num) : fp_num := sumFp fp1 (neg fp2).\n\n\nFixpoint minusExponents (v1:Bvector lenExp) (v2 : Bvector lenExp) : Bvector lenExp := \nlet v2New := Vector.cons bool false lenExp v2 in\nlet v1New := Vector.cons bool false lenExp v1 in\nlet biasNew := Vector.cons bool false lenExp bias in\nlet tmp := snd (sumVectors (S lenExp) v1New biasNew) in\nlet result := snd (diffVectors (S lenExp) tmp v2New) in\nVector.tl result.\n\nFixpoint SSVector (lenV:nat) (w:Bvector 2) (v:Bvector lenV)  : Bvector (S (S lenV)) :=\nlet v1 := Vector.cons bool (Vector.last w) lenV v in\nVector.cons bool (Vector.hd w) (S lenV) v1.\n\nFixpoint PPVector (v:Bvector (S (S lenSign))) : (Bvector 2)*(Bvector lenSign) :=\nlet v1 := Vector.tl v in\n([(Vector.hd v);(Vector.hd v1)],(Vector.tl v1)).\n\n\nFixpoint divBit (n:nat) (div1:Bvector n) (div2:Bvector n) :bool*(Bvector n):=\nmatch compareVect n div1 div2 with\n|Lt => let w := shiftReplaceL false n div1 in \n       (false,w)\n|_ => let tmp := snd (diffVectors n div1 div2) in\n      (true,(shiftReplaceL false n tmp))\nend.\n\n(*head - number before floating point\n  last - for accuracy*)\nFixpoint divSys (m:nat) (div1:Bvector m) (div2:Bvector m) (result:Bvector m) (n:nat): \n         Bvector m :=\nlet res := divBit m div1 div2 in\nmatch n with\n|O =>  shiftReplaceL (fst res) m result\n|S l => divSys m (snd res) div2 (shiftReplaceL (fst res) m result) l\nend.\n\nFixpoint removeLast (n:nat) (v:Bvector (S n)) : Bvector n :=\nlet vv := invertV (S n) (S n) v in\ninvertV n n (Vector.tl vv).\n\nFixpoint divFinite (fp1 fp2: fp_num) : fp_num :=\nlet n := S (S lenSign) in\nlet v1 := SSVector lenSign [false;true] fp1.(significant) in\nlet v2 := SSVector lenSign [false;true] fp2.(significant) in\nlet zeroRes := SSVector lenSign [false;false] allFalseSignificant in\nlet res:= divSys n v1 v2 zeroRes (S lenSign) in\nlet resExp:= minusExponents fp1.(exp) fp2.(exp) in\nlet leftPart := Vector.hd res in\nif leftPart then\n let significantRes := removeLast lenSign (Vector.tl res) in\n mkFp (xorb fp1.(sign) fp2.(sign)) resExp significantRes\nelse\n let significantRes := Vector.tl (Vector.tl res) in\n mkFp (xorb fp1.(sign) fp2.(sign)) (minusBoolV lenExp true resExp) significantRes.\n\n\nFixpoint divideFp (fp1 fp2: fp_num) : fp_num :=\nif((isNaN fp1) || (isNaN fp2)) then NaN\nelse \n if (isZero fp1 && isZero fp2) then NaN \n else \n  if isZero fp2 then mkFp (xorb fp2.(sign) fp1.(sign)) plusInfinity.(exp) plusInfinity.(significant)\n  else \n   if isZero fp1 then\n      fp1\n   else\n      divFinite fp1 fp2.\n\n(**********************************MULTIPLICATION**********************************)\n\n\nFixpoint sumExponents (v1:Bvector lenExp) (v2 : Bvector lenExp) : Bvector lenExp := \nlet v2New := Vector.cons bool false lenExp v2 in\nlet v1New := Vector.cons bool false lenExp v1 in\nlet biasNew := Vector.cons bool false lenExp bias in\nlet tmp := snd (sumVectors (S lenExp) v1New v2New) in\nlet result := snd (diffVectors (S lenExp) tmp biasNew) in\nVector.tl result.\n\n(*num*bit+result\n  leftPoint,significant *)\nFixpoint multOnBitSignificant  (num:Bvector lenSign) (bit:bool) (result:Bvector lenSign) \n(leftPoint:Bvector 2) :(Bvector 2)*(Bvector lenSign) := \nlet shiftResult := shiftReplaceR (Vector.last leftPoint) lenSign result in\nmatch bit with\n|false => ([false;Vector.hd leftPoint],shiftResult)\n|true => \n let sum := sumVectors lenSign shiftResult num in\n let resultLeft := sumDigits true (fst sum) (Vector.hd leftPoint) in\n ([fst resultLeft;snd resultLeft],snd sum)\nend.\n\n\n\n(* num1*num2\n   num2 - reverse*)\nFixpoint multSignificantSysR (num1:Bvector lenSign) (n:nat) (num2:Bvector n) \n(result:Bvector lenSign) (leftPoint:Bvector 2) : (Bvector 2)*(Bvector lenSign) :=\nmatch num2 with \n|Vector.nil => multOnBitSignificant  num1 true result leftPoint\n|Vector.cons h m w => \nlet nextResult := multOnBitSignificant num1 h result leftPoint in\nmultSignificantSysR num1 m w (snd nextResult) (fst nextResult)\nend.  \n\n\nFixpoint getAllFalseVect (n:nat) : Bvector n :=\nmatch n with\n|O => []\n|S m => Vector.cons bool false m (getAllFalseVect m)\nend.\n\nFixpoint multSignificant (num1 num2 : Bvector lenSign):Bvector (S (S lenSign)):=\nlet num2R:= invertV lenSign lenSign num2 in\nlet res := multSignificantSysR num1 lenSign num2R allFalseSignificant [false;false] in\nSSVector lenSign (fst res) (snd res).\n\n\n\nFixpoint multFinite (fp1 fp2 : fp_num) : fp_num:=\nlet signRes := xorb fp1.(sign) fp2.(sign) in\nlet expRes := sumExponents fp1.(exp) fp2.(exp) in\nlet multRes := multSignificant fp1.(significant) fp2.(significant) in\nlet newRes := Vector.tl multRes in\nlet needShift := Vector.hd multRes in\nif needShift then\n let newExpRes := plusBoolV lenExp true expRes in\n let newSignificant := \n     shiftReplaceR (Vector.hd newRes) lenSign (Vector.tl newRes) in\n mkFp signRes newExpRes newSignificant\nelse\n mkFp signRes expRes (Vector.tl newRes).\n  \nFixpoint multFp (fp1 fp2 :fp_num) : fp_num :=\nif (isNaN fp1) || (isNaN fp2) then NaN \nelse \n if(isInfinite fp1) then \n  if(isInfinite fp2) then\n   mkFp (xorb fp1.(sign) fp2.(sign)) fp1.(exp) fp1.(significant)\n  else\n   if(isZero fp2) then\n    NaN\n   else  \n    fp1\n else \n  if(isInfinite fp2) then\n   if(isZero fp1) then\n    NaN\n   else\n    fp2\n  else\n   if isZero fp1 || isZero fp2 then\n      plusZero\n   else\n      multFinite fp1 fp2.\n\n\n\n(*******************************SQRT*******************************)\n\nFixpoint expSqrt (v:Bvector lenExp) : bool*(Bvector lenExp) :=\nmatch compareVect lenExp v bias with\n|Lt => let res := diffVectors lenExp bias v in \n       let tmp := shiftReplaceR false lenExp (snd res) in\n       let newRes := diffVectors lenExp bias tmp in\n       if (Vector.last v) then\n           (false,snd newRes)\n       else\n          (true,minusBoolV lenExp true (snd newRes))\n|_ =>  let res := diffVectors lenExp v bias in \n       let tmp := shiftReplaceR false lenExp (snd res) in\n       let newRes := sumVectors lenExp bias tmp in\n       if (Vector.last v) then\n           (false,snd newRes)\n       else\n           (true,snd newRes)\nend. \n\n\nFixpoint setValToNPositionVect (n:nat) (val:bool) (lenV:nat) (v:Bvector lenV) : Bvector lenV :=\nmatch nat_compare lenV n with\n|Lt => v\n|Eq => match v with\n       |Vector.nil => []\n       |Vector.cons h m w => Vector.cons bool val m w\n       end\n|Gt => match v with\n       |Vector.nil => []\n       |Vector.cons h m w => \n        let ww:= setValToNPositionVect n val m w in\n        Vector.cons bool h m ww\n       end\nend.\n\nFixpoint setTrueToNPositionVect (n:nat) (lenV:nat) (v:Bvector lenV) : Bvector lenV :=\nsetValToNPositionVect n true lenV v.\n\nFixpoint significantSqrtSys (evenExp:bool) (stepNum:nat) (num res:Bvector lenSign)  \n                            : Bvector lenSign :=\nmatch stepNum with\n|O=> res\n|S m => let newRes := setTrueToNPositionVect (S m) lenSign res in \n        let tmp :=  multSignificant newRes newRes in\n        let head := Vector.hd tmp in\n        let tmp2 := Vector.tl tmp in\n        if eqb head evenExp then\n           let squaredRes := shiftReplaceR (Vector.hd tmp2) lenSign (Vector.tl tmp2) in\n           match compareVect lenSign num squaredRes with\n              |Lt => significantSqrtSys evenExp m num res\n              |_ => significantSqrtSys evenExp m num newRes\n           end\n        else if(evenExp) then\n           significantSqrtSys evenExp m num newRes\n        else\n           significantSqrtSys evenExp m num res\nend.\n\n\n\n\nFixpoint significantSqrt (evenExp:bool) (significant:Bvector lenSign) : Bvector lenSign :=\nsignificantSqrtSys evenExp lenSign significant allFalseSignificant.\n\n\n\n\nFixpoint sqrtFpPos (fp:fp_num) : fp_num :=\nlet newExp := expSqrt fp.(exp) in\nlet evenExp := fst newExp in\nlet newSignificant := significantSqrt evenExp fp.(significant) in\nmkFp false (snd newExp) newSignificant.\n\nFixpoint sqrtFp(fp:fp_num) : fp_num :=\nif isNaN fp then fp\nelse \n if isZero fp then \n  fp\n else\n  if fp.(sign) then\n   NaN\n  else\n   if isInfinite fp then \n    fp\n   else\n    sqrtFpPos fp.\n\n\n(***************************CONVERSATION***************************)\n\nOpen Scope Z_scope.\nOpen Scope positive_scope.\nOpen Scope Q_scope.\n\n\n\nFixpoint Qgcd (q:Q) : Q :=\nlet qnum := q.(Qnum) in\nlet qden := Zpos q.(Qden) in\nlet gcdRes := Z.gcd qnum qden in\nmatch Z.compare gcdRes 1 with \n|Eq => q\n|_ => \n  let newNum := fst (div_eucl_z qnum gcdRes) in\n  let newDen := fst (div_eucl_z qden gcdRes) in\n  Qmake newNum (Z.to_pos newDen)\nend.\n\nClose Scope  Z_scope.\nClose Scope positive_scope.\n\nFixpoint vector2QSys (res:Q) (pow:Q) (n:nat) (v: Bvector n) : Q :=\nmatch v with\n|Vector.nil => res\n|Vector.cons h m w => let newPow := Qmult (1#2) pow in\nlet newRes := \n if h then\n  Qplus res newPow\n else\n  res\nin if h then\n vector2QSys (Qgcd newRes) newPow m w\nelse\n vector2QSys newRes newPow m w\nend.\n\nFixpoint vector2Q (n:nat) (v:Bvector n) : Q := vector2QSys 1 1 n v.\n\nFixpoint significant2Q (fp : fp_num) : Q :=\nvector2Q lenSign fp.(significant).\n\nFixpoint power (base: Q) (pow:nat) : Q :=\nmatch pow with\n|O => 1\n|S m => Qmult base (power base m)\nend.\n\n\nFixpoint exp2Q (fp: fp_num) : Q :=\nif isExpforZero fp.(exp) then\n 0#1\nelse\n let expNat := exp2Nat fp in\n let biasNat := vect2Nat lenExp bias in\n match nat_compare expNat biasNat with\n  |Lt => power (1#2) (biasNat - expNat) \n  |_ => power (2#1) (expNat-biasNat)\n end.\n\nFixpoint fp2Q (fp:fp_num) : Q :=\nlet qsign := significant2Q fp in\nlet qexp := exp2Q fp in\nlet res := Qgcd (Qmult qsign qexp) in\nif fp.(sign) then\n Qmult (-1#1) res\nelse\n res.\n\nFixpoint getSignificantFromQSys (num curPow:Q) (iter:nat)  : Bvector iter :=\nlet newPow := Qmult (1#2) curPow in\nmatch iter with\n|O => []\n|S m => match Qcompare num curPow with\n       |Lt => Vector.cons bool false m (getSignificantFromQSys num newPow m)\n       |_  => let newNum := Qgcd (Qminus num curPow) in \n           Vector.cons bool true m (getSignificantFromQSys newNum newPow m)\n       end\nend.  \n\nFixpoint getSignificantFromQ (num:Q) : Bvector lenSign :=\ngetSignificantFromQSys num (1#2) lenSign.\n\nFixpoint computeExpSmallSys (num:Q) (iter:nat) :nat*Q :=\nmatch iter with\n|O => (O,num)\n|S m => let newNum := Qmult num (2#1) in\n   match Qcompare newNum (1#1) with\n      |Lt => let res := computeExpSmallSys newNum m in (S (fst res),snd res)\n      |_ => (S O, newNum)\n   end\nend.\n\n\nFixpoint computeExpSmall (num:Q) : (Bvector lenExp)*Q :=\nlet res := computeExpSmallSys num shiftExp in\nlet secondRes := nat2Vect (fst res) lenExp bias true in\n(secondRes,snd res).\n\n\nFixpoint computeExpBigSys (num:Q) (iter:nat) :nat*Q :=\nmatch iter with\n|O => (O,num)\n|S m => let newNum := Qmult num (1#2) in\n   match Qcompare newNum (2#1) with\n      |Lt => (S O,newNum)\n      | _ => let res := computeExpBigSys newNum m in (S (fst res),snd res)\n   end\nend.\n\nFixpoint computeExpBig (num:Q) : (Bvector lenExp)*Q :=\nlet res :=computeExpBigSys num shiftExp in\nlet secondRes := nat2Vect (fst res) lenExp bias false in\n(secondRes,snd res).\n\n\nFixpoint getExp (num:Q) : (Bvector lenExp)*Q :=\nlet newNum := Qabs num in\nmatch Qcompare newNum (2#1) with\n|Lt => match Qcompare newNum (1#1) with\n       |Lt => computeExpSmall newNum\n       | _ => (bias,num)\n       end\n| _ => computeExpBig newNum\nend.\n\nFixpoint Q2Fp (num:Q): fp_num :=\nmatch Qcompare num (0#1) with\n|Eq => plusZero\n|_ => \n  let sign := match Qcompare num (0#1) with\n    |Lt => true\n    | _ => false\n   end in \n  let res := getExp num in\n  let significant := getSignificantFromQ (Qminus (snd res) (1#1)) in\n  mkFp sign (fst res) significant\nend.\n\nFixpoint sqrtStepQ (a res eps : Q) (step:nat) : Q := \nlet gcdRes := Qgcd res in\nmatch step with\n|O => gcdRes\n|S m => let sq:=Qabs (gcdRes*gcdRes-a) in \n match  Qcompare sq eps with\n  |Lt => gcdRes\n  | _ => let newRes := (1#2)*(gcdRes + a/gcdRes) in sqrtStepQ a newRes eps m\n end\nend.\n\nFixpoint sqrtAccQ ( acc a : Q) : Q :=\nmatch Qcompare a (0#1) with\n|Lt => (-1#1)\n| _ => match Qcompare acc (0#1) with\n |Gt => sqrtStepQ  a a acc lenSign\n | _ => (-1#1)\n end\nend.\n\nDefinition sqrtQ(a:Q) : Q :=\nsqrtAccQ  sqrtEps a.\n\nDefinition sqrtAccFp (acc:Q) (fp:fp_num) : fp_num:=\nsqrtFp fp.\n\nFixpoint reflectQ (num:Q) : Q := num.\n\nFixpoint max (n m:nat) : nat :=\nmatch n, m with\n  | O, _ => m\n  | S n', O => n\n  | S n', S m' => S (max n' m')\nend.\n\n\nRecord ApproxArith := mkApproxArith\n{\n Num : Set;\n sum  : Num -> Num -> Num;\n diff : Num -> Num -> Num;\n mult : Num -> Num -> Num;\n div  : Num -> Num -> Num;\n sqrt : Num -> Num;\n from_rational : Q -> Num;\n to_rational : Num -> Q; \n lt : Num -> Num -> bool;\n le : Num -> Num -> bool;\n eq : Num -> Num -> bool;\n ge : Num -> Num -> bool;\n gt : Num -> Num -> bool\n}.\n\n\nDefinition approxFp := mkApproxArith fp_num sumFp diffFp multFp divideFp sqrtFp Q2Fp fp2Q \n                                     isLtFp_bool isLeFp_bool isEqFp_bool isGeFp_bool isGtFp_bool.\nDefinition approxQ := mkApproxArith Q Qplus Qminus Qmult Qdiv sqrtQ reflectQ reflectQ \n                                      isLtQ_bool isLeQ_bool isEqQ_bool isGeQ_bool isGtQ_bool.\n\nInductive ArithExp (n: nat):=\n|Get (i: Fin.t n)\n|Const (c: Q)\n|Add(a b :ArithExp n)\n|Diff(a b:ArithExp n)\n|Mult(a b:ArithExp n)\n|Div(a b:ArithExp n)\n|Sqrt(a :ArithExp n)\n|Noting\n|If(cond:BoolExp n) (onTrue: ArithExp n) (onFalse: ArithExp n)\nwith BoolExp(n:nat) :=\n|And (a b : BoolExp n)\n|Or (a b :BoolExp n)\n|Eq (a b : ArithExp n)\n|Gt (a b : ArithExp n)\n|Ge (a b : ArithExp n)\n|Lt (a b : ArithExp n)\n|Le (a b : ArithExp n).\n\nClose Scope Q_scope.\n(*result_code,result*)\n(*result_code: 0-ok,1-don't put,x>1 - error *)\nDefinition ok_code: nat := 0.\nDefinition nothing_code : nat := 1.\nDefinition error_code : nat := 2.\n\nFixpoint computeExp (n:nat) (arith: ApproxArith) (exp: ArithExp n) \n                       (init : t (Num arith) n) : nat*(Num arith) :=\nlet error:= from_rational arith (-1#1) in\nlet zero := from_rational arith 0 in\nmatch exp with\n |Get x => (0,nth init x)\n |Const x => (0,from_rational arith x)\n |Add x1 x2 =>\n  let res1 := computeExp n arith x1 init in\n  let code_1 := fst res1 in\n  let result_1 := snd res1 in\n  let res2 := computeExp n arith x2 init in\n  let code_2 := fst res2 in\n  let result_2 := snd res2 in\n  if andb (leb code_1 ok_code) (leb code_2 ok_code) then\n   (ok_code, sum arith result_1 result_2)\n  else\n   (max code_1 code_2,error)\n |Diff x1 x2 =>\n  let res1 := computeExp n arith x1 init in\n  let code_1 := fst res1 in\n  let result_1 := snd res1 in\n  let res2 := computeExp n arith x2 init in\n  let code_2 := fst res2 in\n  let result_2 := snd res2 in\n  if andb (leb code_1 ok_code) (leb code_2 ok_code) then\n   (ok_code, diff arith result_1 result_2)\n  else\n   (max code_1 code_2,error)\n |Mult x1 x2 =>\n  let res1 := computeExp n arith x1 init in\n  let code_1 := fst res1 in\n  let result_1 := snd res1 in\n  let res2 := computeExp n arith x2 init in\n  let code_2 := fst res2 in\n  let result_2 := snd res2 in\n  if andb (leb code_1 ok_code) (leb code_2 ok_code) then\n   (ok_code, mult arith result_1 result_2)\n  else\n   (max code_1 code_2,error)\n |Div x1 x2 =>\n  let res1 := computeExp n arith x1 init in\n  let code_1 := fst res1 in\n  let result_1 := snd res1 in\n  let res2 := computeExp n arith x2 init in\n  let code_2 := fst res2 in\n  let result_2 := snd res2 in\n  if andb (leb code_1 ok_code) (leb code_2 ok_code) then\n   if (eq arith result_2 zero) then\n    (error_code,error)\n   else\n   (ok_code, div arith result_1 result_2)\n  else\n   (max code_1 code_2,error)\n |Sqrt x => \n  let res := computeExp n arith x init in\n  let code := fst res in\n  let result := snd res in\n  if (leb code ok_code) then\n   if (ge arith result zero) then\n    (ok_code,sqrt arith result)\n   else\n    (error_code,error)\n  else\n   (code,error)\n |If cond onTrue onFalse => \n  let cond_res := computeBoolExp n arith cond init in\n  let cond_code := fst cond_res in\n  let cond_val := snd cond_res in\n  if (leb cond_code ok_code) then\n   if cond_val then\n    computeExp n arith onTrue init\n   else\n    computeExp n arith onFalse init \n  else\n   (error_code,error)\n |Nothing => (nothing_code,error)\nend\nwith computeBoolExp (n:nat) (arith: ApproxArith) (exp: BoolExp n) \n                     (init : t (Num arith) n) : nat*bool :=\nmatch exp with\n|And x y => \n let res1 := computeBoolExp n arith x init in\n let res2 := computeBoolExp n arith y init in\n let code_1 := fst res1 in\n let code_2 := fst res2 in\n let result_1 := snd res1 in\n let result_2 := snd res2 in\n if  andb (leb code_1 ok_code) (leb code_2 ok_code) then\n  (ok_code,andb result_1 result_2)\n else\n  (error_code,false)\n|Or x y =>\n let res1 := computeBoolExp n arith x init in\n let res2 := computeBoolExp n arith y init in\n let code_1 := fst res1 in\n let code_2 := fst res2 in\n let result_1 := snd res1 in\n let result_2 := snd res2 in\n if  andb (leb code_1 ok_code) (leb code_2 ok_code) then\n  (ok_code,orb result_1 result_2)\n else\n  (error_code,false)\n|Eq x y => \n let res1 := computeExp n arith x init in\n let code_1 := fst res1 in\n let result_1 := snd res1 in\n let res2 := computeExp n arith y init in\n let code_2 := fst res2 in\n let result_2 := snd res2 in\n if andb (leb code_1 ok_code) (leb code_2 ok_code) then\n  (ok_code, eq arith result_1 result_2)\n else\n  (error_code,false)\n|Gt x y => \n let res1 := computeExp n arith x init in\n let code_1 := fst res1 in\n let result_1 := snd res1 in\n let res2 := computeExp n arith y init in\n let code_2 := fst res2 in\n let result_2 := snd res2 in\n if andb (leb code_1 ok_code) (leb code_2 ok_code) then\n  (ok_code, gt arith result_1 result_2)\n else\n  (error_code,false)\n|Ge x y => \n let res1 := computeExp n arith x init in\n let code_1 := fst res1 in\n let result_1 := snd res1 in\n let res2 := computeExp n arith y init in\n let code_2 := fst res2 in\n let result_2 := snd res2 in\n if andb (leb code_1 ok_code) (leb code_2 ok_code) then\n  (ok_code, ge arith result_1 result_2)\n else\n  (error_code,false)\n|Lt x y => \n let res1 := computeExp n arith x init in\n let code_1 := fst res1 in\n let result_1 := snd res1 in\n let res2 := computeExp n arith y init in\n let code_2 := fst res2 in\n let result_2 := snd res2 in\n if andb (leb code_1 ok_code) (leb code_2 ok_code) then\n  (ok_code, lt arith result_1 result_2)\n else\n  (error_code,false)\n|Le x y => \n let res1 := computeExp n arith x init in\n let code_1 := fst res1 in\n let result_1 := snd res1 in\n let res2 := computeExp n arith y init in\n let code_2 := fst res2 in\n let result_2 := snd res2 in\n if andb (leb code_1 ok_code) (leb code_2 ok_code) then\n  (ok_code, le arith result_1 result_2)\n else\n  (error_code,false)\nend.\n\n\nFixpoint interp (n:nat) (arith :ApproxArith) (prog : list ((Fin.t n) *(ArithExp n)))\n                  (init: t (Num arith) n) : nat*(t (Num arith) n)  := \nmatch prog with\n|List.nil => (ok_code,init)\n|List.cons h tl => \n let pos := fst h in\n let exp := snd h in\n let res := computeExp n arith exp init in \n let code := fst res in\n let val := snd res in\n if leb code ok_code then\n  interp n arith tl (replace init pos val)\n else\n  if leb code nothing_code then\n   interp n arith tl init\n  else\n   (error_code,init)\nend.\n\n\n\n", "meta": {"author": "antonovsergey93", "repo": "floating-point-model", "sha": "56badaf8442f2231c2fa95cf002b1bf223323fa2", "save_path": "github-repos/coq/antonovsergey93-floating-point-model", "path": "github-repos/coq/antonovsergey93-floating-point-model/floating-point-model-56badaf8442f2231c2fa95cf002b1bf223323fa2/model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.6932358707558273}}
{"text": "Axiom Tile : Type.\n\nAxiom haskell : Tile.\nAxiom sandy : Tile.\nAxiom cw : Tile -> Tile.\n\n\nAxiom cw'cw'cw'cw :\n  forall t : Tile,\n    cw (cw (cw (cw t))) = t.\n\nAxiom ccw : Tile -> Tile.\n\nAxiom ccw'cw :\n  forall t : Tile,\n    ccw (cw t) = t.\n\nAxiom cw'ccw :\n  forall t : Tile,\n    cw (ccw t) = t.\n\nTheorem ccw_is_redundant :\n  forall t : Tile,\n    ccw t = cw (cw (cw t)).\nProof.\nintros.\nsymmetry.\nrewrite <- cw'cw'cw'cw.\nrewrite cw'ccw.\nreflexivity.\nQed.\n\nAxiom flipH : Tile -> Tile.\n\nAxiom flipH'flipH :\n  forall t : Tile,\n    flipH (flipH t) = t.\n\nAxiom flipH'cw'cw'flipH :\n  forall t : Tile,\n    flipH (cw (cw (flipH t))) = cw (cw t).\n\n(* I need to define repeated composition *)\nFixpoint repeat_compose {a : Type}\n  (n : nat) (f : a -> a) (x : a) := \nmatch n with\n| 0 => x\n| S n => f (repeat_compose n f x)\nend.\n(* And give it the same ^ notation from the book *)\nNotation \"f ^ n\" := (repeat_compose n f).\n\nTheorem flipH_2ncw_flipH :\n  forall (n : nat) (t : Tile),\n    flipH ((cw^(n*2)) (flipH t)) = (cw^(n*2)) t.\nProof.\nintros.\ninduction n.\nsimpl.\nrewrite flipH'flipH.\nreflexivity.\nsimpl.\nrewrite <- IHn.\nsymmetry.\nrewrite <- flipH'cw'cw'flipH.\nrewrite flipH'flipH.\nreflexivity.\nQed.\n\nAxiom x_symmetry :\n  forall t : Tile,\n    flipH (cw t) = ccw (flipH t).\n\nAxiom flipV : Tile -> Tile.\n\n(*\nAxiom flipV'flipV :\n  forall t : Tile,\n    flipV (flipV t) = t.\n*)\n\nAxiom ccw'flipH'cw :\n  forall t : Tile,\n    flipV t = ccw (flipH (cw t)).\n\n(*\nAxiom flipV'flipH :\n  forall t : Tile,\n    flipV (flipH t) = cw (cw t).\n*)\n\nTheorem flipV'flipV :\n  forall t : Tile,\n    flipV (flipV t) = t.\nProof.\nintros.\nsymmetry.\nrewrite ccw'flipH'cw.\nrewrite ccw'flipH'cw.\nrewrite cw'ccw.\nrewrite flipH'flipH.\nrewrite ccw'cw.\nreflexivity.\nQed.\n\n\n\nTheorem flipV'flipH :\n  forall t : Tile,\n    flipV (flipH t) = cw (cw t).\nProof.\nintros.\nrewrite ccw'flipH'cw.\nrewrite <- flipH'cw'cw'flipH.\nrewrite <- x_symmetry.\nreflexivity.\nQed.", "meta": {"author": "dbramucci", "repo": "coq-proofs-algebra-driven-design", "sha": "0c896fe16dfad6d06e3d1d355810f8fb9d8ac082", "save_path": "github-repos/coq/dbramucci-coq-proofs-algebra-driven-design", "path": "github-repos/coq/dbramucci-coq-proofs-algebra-driven-design/coq-proofs-algebra-driven-design-0c896fe16dfad6d06e3d1d355810f8fb9d8ac082/chapter_2_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6932358686186078}}
{"text": "(* Exerpt from https://softwarefoundations.cis.upenn.edu/ for INF3034L course *)\n\n\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Import Coq.Strings.String.\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 Coq.omega.Omega.\n\n(* From Maps.v to have states *)\nInductive id : Type :=\n  | Id : string -> id.\n\nDefinition beq_id x y :=\n  match x,y with\n    | Id n1, Id n2 => if string_dec n1 n2 then true else false\n  end.\n\n\nTheorem beq_id_refl : forall id, true = beq_id id id.\nProof.\n  intros [n]. simpl. destruct (string_dec n n).\n  - reflexivity.\n  - destruct n0. reflexivity.\nQed.\n\n(** The following useful property of [beq_id] follows from an\n    analogous lemma about strings: *)\n\nTheorem beq_id_true_iff : forall x y : id,\n  beq_id x y = true <-> x = y.\nProof.\n   intros [n1] [n2].\n   unfold beq_id.\n   destruct (string_dec n1 n2).\n   - subst. split. reflexivity. reflexivity.\n   - split.\n     + intros contra. inversion contra.\n     + intros H. inversion H. subst. destruct n. reflexivity.\nQed.\n\n(** Similarly: *)\n\nTheorem beq_id_false_iff : forall x y : id,\n  beq_id x y = false\n  <-> x <> y.\nProof.\n  intros x y. rewrite <- beq_id_true_iff.\n  rewrite not_true_iff_false. reflexivity. Qed.\n\n(** This useful variant follows just by rewriting: *)\n\nTheorem false_beq_id : forall x y : id,\n   x <> y\n   -> beq_id x y = false.\nProof.\n  intros x y. rewrite beq_id_false_iff.\n  intros H. apply H. Qed.\n\n\nDefinition total_map (A:Type) := id -> A.\n\n\nDefinition t_empty {A:Type} (v : A) : total_map A :=\n  (fun _ => v).\n\nDefinition t_update {A:Type} (m : total_map A)\n                    (x : id) (v : A) :=\n  fun x' => if beq_id x x' then v else m x'.\n\n\n(******************************************************************)\n(* From Imp.v for the course                                      *)\n(******************************************************************)\n\nImport ListNotations.\n\n\nDefinition state := total_map nat.\n\nDefinition empty_state : state :=\n  t_empty 0.\n\nInductive aexp : Type :=\n  | ANum : nat -> aexp\n  | AId : id -> aexp              \n  | APlus : aexp -> aexp -> aexp\n  | AMinus : aexp -> aexp -> aexp\n  | AMult : aexp -> aexp -> aexp.\n\nInductive bexp : Type :=\n  | BTrue : bexp\n  | BFalse : bexp\n  | BEq : aexp -> aexp -> bexp\n  | BLe : aexp -> aexp -> bexp\n  | BNot : bexp -> bexp\n  | BAnd : bexp -> bexp -> bexp.\n\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\nAbout leb.\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   => 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\n(** Defining a few variable names as notational shorthands will make\n    examples easier to read: *)\n\nDefinition W : id := Id \"W\".\nDefinition X : id := Id \"X\".\nDefinition Y : id := Id \"Y\".\nDefinition Z : id := Id \"Z\".\n\n\nExample aexp1 :\n  aeval (t_update empty_state X 5)\n        (APlus (ANum 3) (AMult (AId X) (ANum 2)))\n  = 13.\nProof. reflexivity. Qed.\n\nExample bexp1 :\n  beval (t_update empty_state X 5)\n        (BAnd BTrue (BNot (BLe (AId X) (ANum 4))))\n  = true.\nProof. reflexivity. Qed.\n\nFixpoint optimize_0plus (a:aexp) : aexp :=\n  match a with\n  | ANum n =>\n      ANum n\n  | AId x =>\n      AId x\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\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\n\nTheorem optimize_0plus_sound: forall a, forall st,\n  aeval st (optimize_0plus a) = aeval st a.\nProof.\n  intros a st.\n  induction a.\n  - simpl.\n    reflexivity.\n  - simpl.\n    reflexivity.\n  - destruct a1.\n    + destruct n.\n      * simpl.\n        rewrite IHa2.\n        reflexivity.\n      * simpl.\n        rewrite IHa2.\n        reflexivity.\n    + simpl.\n      rewrite IHa2.\n      reflexivity.\n    + simpl.\n      simpl in IHa1.\n      rewrite IHa1.\n      rewrite IHa2.\n      reflexivity.\n    + simpl.\n      simpl in IHa1.\n      rewrite IHa1.\n      rewrite IHa2.\n      reflexivity.\n    + simpl.\n      simpl in IHa1.\n      rewrite IHa1.\n      rewrite IHa2.\n      reflexivity.\n  - simpl.\n    rewrite IHa1.\n    rewrite IHa2.\n    reflexivity.\n  - simpl.\n    rewrite IHa1.\n    rewrite IHa2.\n    reflexivity.\nQed.\n\n\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\n(** As usual, we can use a few [Notation] declarations to make things\n    more readable.  To avoid conflicts with Coq's built-in notations,\n    we keep this light -- in particular, we don't introduce any\n    notations for [aexps] and [bexps] to avoid confusion with the\n    numeric and boolean operators we've already defined. *)\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\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,\n      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\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  (* We must supply the intermediate state *)\n  apply E_Seq with (t_update empty_state X 2).\n  - (* assignment command *)\n    apply E_Ass. reflexivity.\n  - (* if command *)\n    apply E_IfFalse.\n      reflexivity.\n      apply E_Ass. reflexivity.\nQed.\n\n", "meta": {"author": "badbayard", "repo": "code_coq_logique_classique", "sha": "5e995971a26af2c502a5c04aefe9ba775580f3e5", "save_path": "github-repos/coq/badbayard-code_coq_logique_classique", "path": "github-repos/coq/badbayard-code_coq_logique_classique/code_coq_logique_classique-5e995971a26af2c502a5c04aefe9ba775580f3e5/CM7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.6932358574681606}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\nRequire Import mathcomp.ssreflect.seq mathcomp.ssreflect.prime.\n\n(** Example of computation involving Peano nats *)\nTime Eval vm_compute in filter prime (iota 1 100).\n\n(** Example of theorem proved using Coq tactics *)\nTheorem thm : forall P, not (iff P (not P)).\nProof.\nidtac \"proof in progress...\".\nnow intros P [H1 H2]; apply H1; apply H2; intros HP; apply H1.\nQed.\n", "meta": {"author": "erikmd", "repo": "docker-coq-travis-ci-demo-1", "sha": "9bbbe7f8801aa349d58de4842b0651906108ac69", "save_path": "github-repos/coq/erikmd-docker-coq-travis-ci-demo-1", "path": "github-repos/coq/erikmd-docker-coq-travis-ci-demo-1/docker-coq-travis-ci-demo-1-9bbbe7f8801aa349d58de4842b0651906108ac69/src/demo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.693227953373599}}
{"text": "Require Import rt.util.all.\nRequire Import rt.model.arrival.basic.job rt.model.arrival.basic.task.\nRequire Import rt.model.schedule.global.basic.schedule.\nFrom mathcomp Require Import ssreflect eqtype ssrbool ssrnat seq bigop.\n\n(* Definitions of deadline miss. *)\nModule Schedulability.\n\n  Import Schedule SporadicTaskset Job.\n\n  Section SchedulableDefs.\n\n    Context {sporadic_task: eqType}.\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 -> sporadic_task.\n    \n    (* Consider any job arrival sequence... *)\n    Variable arr_seq: arrival_sequence Job.\n    \n    (* ...and any multiprocessor schedule of these jobs. *)\n    Context {num_cpus: nat}.\n    Variable sched: schedule Job num_cpus.\n\n    Section ScheduleOfJobs.\n\n      (* Let j be any job. *)\n      Variable j: Job.\n\n      (* We say that job j misses no deadline in sched if it completed by its absolute deadline. *)\n      Definition job_misses_no_deadline :=\n        completed job_cost sched j (job_arrival j + job_deadline j).\n\n    End ScheduleOfJobs.\n\n    Section ScheduleOfTasks.\n\n      (* Consider any task tsk. *)\n      Variable tsk: sporadic_task.\n\n      (* Task tsk doesn't miss its deadline iff all of its jobs don't miss their deadline. *)\n      Definition task_misses_no_deadline :=\n        forall j,\n          arrives_in arr_seq j ->\n          job_task j = tsk ->\n          job_misses_no_deadline j.\n\n      (* Task tsk doesn't miss its deadline before time t' iff all of its jobs don't miss\n         their deadline by that time. *)\n      Definition task_misses_no_deadline_before (t': time) :=\n        forall j,\n          arrives_in arr_seq j ->\n          job_task j = tsk ->\n          job_arrival j + job_deadline j < t' ->\n          job_misses_no_deadline j.\n\n    End ScheduleOfTasks.\n\n  End SchedulableDefs.\n\n  Section BasicLemmas.\n\n    Context {sporadic_task: eqType}.\n    Variable task_cost: sporadic_task -> time.\n    Variable task_period: sporadic_task -> time.\n    Variable task_deadline: sporadic_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 -> sporadic_task.\n\n    (* Consider any job arrival sequence... *)\n    Variable arr_seq: arrival_sequence Job.\n    \n    (* ...and any schedule of these jobs... *)\n    Context {num_cpus : nat}.\n    Variable sched: schedule Job num_cpus.\n\n    (* ... where jobs dont execute after completion. *)\n    Hypothesis H_completed_jobs_dont_execute:\n      completed_jobs_dont_execute job_cost sched.\n\n    Section SpecificJob.\n\n      (* Then, for any job j ...*)\n      Variable j: Job.\n      Hypothesis H_j_arrives: arrives_in arr_seq j.\n\n      (* ...that doesn't miss a deadline in this schedule, ... *)\n      Hypothesis no_deadline_miss:\n        job_misses_no_deadline job_arrival job_cost job_deadline sched j.\n\n      (* the service received by j at any time t' after its deadline is 0. *)\n      Lemma service_after_job_deadline_zero :\n        forall t',\n          t' >= job_arrival j + job_deadline j ->\n          service_at sched j t' = 0.\n      Proof.\n        intros t' LE.\n        rename no_deadline_miss into NOMISS,\n               H_completed_jobs_dont_execute into EXEC.\n        unfold job_misses_no_deadline, completed, completed_jobs_dont_execute in *.\n        apply/eqP; rewrite -leqn0.\n        rewrite <- leq_add2l with (p := job_cost j).\n        move: NOMISS => /eqP NOMISS; rewrite -{1}NOMISS addn0.\n        apply leq_trans with (n := service sched j t'.+1); last by apply EXEC.\n        unfold service; rewrite -> big_cat_nat with\n                                   (p := t'.+1) (n := job_arrival j + job_deadline j);\n            [rewrite leq_add2l /= | by ins | by apply ltnW].\n          by rewrite big_nat_recr // /=; apply leq_addl.\n      Qed.\n\n      (* The same applies for the cumulative service of job j. *)\n      Lemma cumulative_service_after_job_deadline_zero :\n        forall t' t'',\n          t' >= job_arrival j + job_deadline j ->\n          \\sum_(t' <= t < t'') service_at sched j t = 0.\n      Proof.\n        ins; apply/eqP; rewrite -leqn0.\n        rewrite big_nat_cond; rewrite -> eq_bigr with (F2 := fun i => 0);\n          first by rewrite big_const_seq iter_addn mul0n addn0 leqnn.\n        intro i; rewrite andbT; move => /andP [LE _].\n        by rewrite service_after_job_deadline_zero;\n          [by ins | by apply leq_trans with (n := t')].\n      Qed.\n      \n    End SpecificJob.\n    \n    Section AllJobs.\n\n      (* Consider any task tsk ...*)\n      Variable tsk: sporadic_task.\n\n      (* ... that doesn't miss any deadline. *)\n      Hypothesis no_deadline_misses:\n        task_misses_no_deadline job_arrival job_cost job_deadline job_task arr_seq sched tsk.\n\n      (* Then, for any valid job j of this task, ...*)\n      Variable j: Job.\n      Hypothesis H_j_arrives: arrives_in arr_seq j.\n      Hypothesis H_job_of_task: job_task j = tsk.\n      Hypothesis H_valid_job:\n        valid_sporadic_job task_cost task_deadline job_cost job_deadline job_task j.\n      \n      (* the service received by job j at any time t' after the deadline is 0. *)\n      Lemma service_after_task_deadline_zero :\n        forall t',\n          t' >= job_arrival j + task_deadline tsk ->\n          service_at sched j t' = 0.\n      Proof.\n        rename H_valid_job into PARAMS; unfold valid_sporadic_job in *; des; intros t'.\n        rewrite -H_job_of_task -PARAMS1.\n        by apply service_after_job_deadline_zero, no_deadline_misses.\n      Qed.\n\n      (* The same applies for the cumulative service of job j. *)\n      Lemma cumulative_service_after_task_deadline_zero :\n        forall t' t'',\n          t' >= job_arrival j + task_deadline tsk ->\n          \\sum_(t' <= t < t'') service_at sched j t = 0.\n      Proof.\n        rename H_valid_job into PARAMS; unfold valid_sporadic_job in *; des; intros t' t''.\n        rewrite -H_job_of_task -PARAMS1.\n        by apply cumulative_service_after_job_deadline_zero, no_deadline_misses.\n      Qed.\n      \n    End AllJobs.\n\n  End BasicLemmas.\n\nEnd Schedulability.", "meta": {"author": "cd-public", "repo": "rt-proofs", "sha": "ebef0b65460fe009c51f638fe2b459f16a6d1dd5", "save_path": "github-repos/coq/cd-public-rt-proofs", "path": "github-repos/coq/cd-public-rt-proofs/rt-proofs-ebef0b65460fe009c51f638fe2b459f16a6d1dd5/model/schedule/global/schedulability.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6932279485452717}}
{"text": "Require Import prosa.classic.util.all.\nRequire Import prosa.classic.model.arrival.basic.job prosa.classic.model.arrival.basic.arrival_sequence.\nRequire Import prosa.classic.model.schedule.uni.schedule.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.\n\n(* In this file, we show how to compute the time instant after the last\n   execution of a job and prove several lemmas about that instant. This\n   notion is crucial for defining suspension intervals. *)\nModule LastExecution.\n\n  Export Job UniprocessorSchedule.\n\n  (* In this section we define the time after the last execution of a job (if exists). *)\n  Section TimeAfterLastExecution.\n\n    Context {Job: eqType}.\n    Variable job_arrival: Job -> time.\n    Variable job_cost: Job -> time.\n\n    (* Consider any uniprocessor schedule. *)\n    Variable sched: schedule Job.\n\n    (* For simplicity, let's define some local names. *)\n    Let job_scheduled_at := scheduled_at sched.\n    Let job_completed_by := completed_by job_cost sched.\n\n    Section Defs.\n      \n      (* Let j be any job in the arrival sequence. *)\n      Variable j: Job.\n\n      (* Next, we will show how to find the time after the most recent\n         execution of a given job j in the interval [job_arrival j, t).\n         (Note that this instant can be time t itself.) *)\n      Variable t: time.\n      \n      (* Let scheduled_before denote whether job j was scheduled in the interval [0, t). *)\n      Let scheduled_before :=\n        [exists t0: 'I_t, job_scheduled_at j t0].\n\n      (* In case j was scheduled before, we define the last time in which j was scheduled. *)\n      Let last_time_scheduled :=\n        \\max_(t_last < t | job_scheduled_at j t_last) t_last.\n\n      (* Then, the time after the last execution of job j in the interval [0, t), if exists,\n         occurs:\n           (a) immediately after the last time in which job j was scheduled, or,\n           (b) if j was never scheduled, at the arrival time of j. *)\n      Definition time_after_last_execution :=\n        if scheduled_before then\n          last_time_scheduled + 1\n        else job_arrival j.\n\n    End Defs.\n\n    (* Next, we prove lemmas about the time after the last execution. *)\n    Section Lemmas.\n\n      (* Assume that jobs do not execute before they arrived. *)\n      Hypothesis H_jobs_must_arrive_to_execute:\n        jobs_must_arrive_to_execute job_arrival sched.\n        \n      (* Let j be any job. *)\n      Variable j: Job.\n\n      (* In this section, we show that the time after the last execution occurs\n           no earlier than the arrival of the job. *)\n      Section JobHasArrived.\n\n        (* Then, the time following the last execution of job j in the\n             interval [0, t) occurs no earlier than the arrival of j. *)\n        Lemma last_execution_after_arrival:\n          forall t,\n            has_arrived job_arrival j (time_after_last_execution j t).\n        Proof.\n          unfold time_after_last_execution, has_arrived; intros t.\n          case EX: [exists _, _]; last by done.\n          move: EX => /existsP [t0 SCHED].\n          apply leq_trans with (n := t0 + 1);\n            last by rewrite leq_add2r; apply leq_bigmax_cond.\n          apply leq_trans with (n := t0); last by rewrite addn1.\n            by apply H_jobs_must_arrive_to_execute.\n        Qed.\n\n      End JobHasArrived.\n\n      (* Next, we establish the monotonicity of the function. *)\n      Section Monotonicity.\n\n        (* Let t1 be any time no earlier than the arrival of job j. *)\n        Variable t1: time.\n        Hypothesis H_after_arrival: has_arrived job_arrival j t1.\n\n        (* Then, (time_after_last_execution j) grows monotonically\n             after that point. *)\n        Lemma last_execution_monotonic:\n          forall t2,\n            t1 <= t2 ->\n            time_after_last_execution j t1 <= time_after_last_execution j t2.\n        Proof.\n          rename H_jobs_must_arrive_to_execute into ARR.\n          intros t2 LE12.\n          rewrite /time_after_last_execution.\n          case EX1: [exists _, _].\n          {\n            move: EX1 => /existsP [t0 SCHED0].\n            have EX2: [exists t:'I_t2, job_scheduled_at j t].\n            {\n              have LT: t0 < t2 by apply: (leq_trans _ LE12).\n                by apply/existsP; exists (Ordinal LT).\n            }\n            rewrite EX2 2!addn1.\n            set m1 := \\max_(_ < t1 | _)_.\n            have LTm1: m1 < t2.\n            {\n              apply: (leq_trans _ LE12).\n                by apply bigmax_ltn_ord with (i0 := t0).\n            }\n            apply leq_ltn_trans with (n := Ordinal LTm1); first by done.\n              by apply leq_bigmax_cond, (bigmax_pred _ _ t0).\n          }\n          {\n            case EX2: [exists _, _]; last by done.\n            move: EX2 => /existsP [t0 SCHED0].\n            set m2 := \\max_(_ < t2 | _)_.\n            rewrite addn1 ltnW // ltnS.\n            have SCHED2: scheduled_at sched j m2 by apply (bigmax_pred _ _ t0).\n              by apply ARR in SCHED2.\n          }\n        Qed.\n\n      End Monotonicity.\n\n      (* Next, we prove that the function is idempotent. *)\n      Section Idempotence.\n        \n        (* The time after the last execution of job j is an idempotent function. *)\n        Lemma last_execution_idempotent:\n          forall t,\n            time_after_last_execution j (time_after_last_execution j t)\n            = time_after_last_execution j t.\n        Proof.\n          rename H_jobs_must_arrive_to_execute into ARR.\n          intros t.\n          rewrite {2 3}/time_after_last_execution.\n          case EX: [exists _,_].\n          {\n            move: EX => /existsP [t0 SCHED].\n            rewrite /time_after_last_execution.\n            set ex := [exists t0, _].\n            have EX': ex.\n            {\n              apply/existsP; rewrite addn1.\n              exists (Ordinal (ltnSn _)).\n                by apply bigmax_pred with (i0 := t0).\n            }\n            rewrite EX'; f_equal.\n            rewrite addn1; apply/eqP.\n            set m := \\max_(_ < t | _)_.\n            have LT: m < m.+1 by done.\n            rewrite eqn_leq; apply/andP; split.\n            {\n              rewrite -ltnS; apply bigmax_ltn_ord with (i0 := Ordinal LT).\n                by apply bigmax_pred with (i0 := t0).\n            }\n            {\n              apply leq_trans with (n := Ordinal LT); first by done.\n                by apply leq_bigmax_cond, bigmax_pred with (i0 := t0).\n            }\n          }\n          {\n            apply negbT in EX; rewrite negb_exists in EX.\n            move: EX => /forallP EX.\n            rewrite /time_after_last_execution.\n            set ex := [exists _, _].\n            suff EX': ex = false; first by rewrite EX'.\n            apply negbTE; rewrite negb_exists; apply/forallP.\n            intros x.\n            apply/negP; intro SCHED.\n            apply ARR in SCHED.\n              by apply leq_ltn_trans with (p := job_arrival j) in SCHED;\n                first by rewrite ltnn in SCHED.\n          }\n        Qed.\n\n      End Idempotence.\n\n      (* Next, we show that time_after_last_execution is bounded by the identity function. *)\n      Section BoundedByIdentity.\n        \n        (* Let t be any time no earlier than the arrival of j. *)\n        Variable t: time.\n        Hypothesis H_after_arrival: has_arrived job_arrival j t.\n\n        (* Then, the time following the last execution of job j in the interval [0, t)\n           occurs no later than time t. *)\n        Lemma last_execution_bounded_by_identity:\n          time_after_last_execution j t <= t.\n        Proof.\n          unfold time_after_last_execution.\n          case EX: [exists _, _]; last by done.\n          move: EX => /existsP [t0 SCHED].\n            by rewrite addn1; apply bigmax_ltn_ord with (i0 := t0).\n        Qed.\n\n      End BoundedByIdentity.\n\n      (* In this section, we show that if the service received by a job\n           remains the same, the time after last execution also doesn't change. *)\n      Section SameLastExecution.\n        \n        (* Consider any time instants t and t'... *)\n        Variable t t': time.\n\n        (* ...in which job j has received the same amount of service. *)\n        Hypothesis H_same_service: service sched j t = service sched j t'.\n\n        (* Then, we prove that the times after last execution relative to\n             instants t and t' are exactly the same. *)\n        Lemma same_service_implies_same_last_execution:\n          time_after_last_execution j t = time_after_last_execution j t'.\n        Proof.\n          rename H_same_service into SERV.\n          have IFF := same_service_implies_scheduled_at_earlier_times\n                        sched j t t' SERV.\n          rewrite /time_after_last_execution.\n          rewrite IFF; case EX2: [exists _, _]; [f_equal | by done].\n          have EX1: [exists x: 'I_t, job_scheduled_at j x] by rewrite IFF.\n          clear IFF.\n          move: t t' SERV EX1 EX2 => t1 t2; clear t t'.\n          wlog: t1 t2 / t1 <= t2 => [EQ SERV EX1 EX2 | LE].\n            by case/orP: (leq_total t1 t2); ins; [|symmetry]; apply EQ.\n            \n            set m1 := \\max_(t < t1 | job_scheduled_at j t) t.\n            set m2 := \\max_(t < t2 | job_scheduled_at j t) t.\n            move => SERV /existsP [t1' SCHED1'] /existsP [t2' SCHED2'].\n            apply/eqP; rewrite eqn_leq; apply/andP; split.\n            {\n              have WID := big_ord_widen_cond t2\n                                             (fun x => job_scheduled_at j x) (fun x => x).\n                          rewrite /m1 /m2 {}WID //.\n                          rewrite big_mkcond [\\max_(t < t2 | _) _]big_mkcond.\n                          apply leq_big_max; intros i _.\n                          case AND: (_ && _); last by done.\n                            by move: AND => /andP [SCHED _]; rewrite SCHED.\n            }\n            {\n              destruct (leqP t2 m1) as [GEm1 | LTm1].\n              {\n                apply leq_trans with (n := t2); last by done.\n                  by apply ltnW, bigmax_ltn_ord with (i0 := t2').\n              }\n              destruct (ltnP m2 t1) as [LTm2 | GEm2].\n              {\n                apply leq_trans with (n := Ordinal LTm2); first by done.\n                  by apply leq_bigmax_cond, bigmax_pred with (i0 := t2').\n              }\n              have LTm2: m2 < t2 by apply bigmax_ltn_ord with (i0 := t2').\n              have SCHEDm2: job_scheduled_at j m2 by apply bigmax_pred with (i0 := t2').\n              exfalso; move: SERV => /eqP SERV.\n              rewrite -[_ == _]negbK in SERV.\n              move: SERV => /negP SERV; apply SERV; clear SERV.\n              rewrite neq_ltn; apply/orP; left.\n              rewrite /service /service_during.\n              rewrite -> big_cat_nat with (n := m2) (p := t2);\n                [simpl | by done | by apply ltnW].\n              rewrite -addn1; apply leq_add; first by apply extend_sum. \n              destruct t2; first by rewrite ltn0 in LTm1.\n              rewrite big_nat_recl; last by done.\n                by rewrite /service_at -/job_scheduled_at SCHEDm2.\n            }\n        Qed.\n\n      End SameLastExecution.\n\n      (* In this section, we show that the service received by a job\n         does not change since the last execution. *)\n      Section SameService.\n\n        (* We prove that, for any time t, the service received by job j\n           before (time_after_last_execution j t) is the same as the service\n           by j before time t. *)\n        Lemma same_service_since_last_execution:\n          forall t,\n            service sched j (time_after_last_execution j t) = service sched j t.\n        Proof.\n          intros t; rewrite /time_after_last_execution.\n          case EX: [exists _, _].\n          {\n            move: EX => /existsP [t0 SCHED0].\n            set m := \\max_(_ < _ | _) _; rewrite addn1.\n            have LTt: m < t by apply: (bigmax_ltn_ord _ _ t0).\n            rewrite leq_eqVlt in LTt.\n            move: LTt => /orP [/eqP EQ | LTt]; first by rewrite EQ.\n            rewrite {2}/service/service_during.\n            rewrite -> big_cat_nat with (n := m.+1);\n              [simpl | by done | by apply ltnW].\n            rewrite [X in _ + X]big_nat_cond [X in _ + X]big1 ?addn0 //.\n            move => i /andP [/andP [GTi LTi] _].\n            apply/eqP; rewrite eqb0; apply/negP; intro BUG.\n            have LEi: (Ordinal LTi) <= m by apply leq_bigmax_cond.\n              by apply (leq_ltn_trans LEi) in GTi; rewrite ltnn in GTi.\n          }\n          {\n            apply negbT in EX; rewrite negb_exists in EX.\n            move: EX => /forallP ALL.\n            rewrite /service /service_during.\n            rewrite (ignore_service_before_arrival job_arrival) // big_geq //.\n            rewrite big_nat_cond big1 //; move => i /andP [/= LTi _].\n            by apply/eqP; rewrite eqb0; apply (ALL (Ordinal LTi)).\n          }\n        Qed.\n\n      End SameService.\n\n      (* In this section, we show that for any smaller value of service, we can\n         always find the last execution that corresponds to that service. *)\n      Section ExistsIntermediateExecution.\n\n        (* Assume that job j has completed by time t. *)\n        Variable t: time.\n        Hypothesis H_j_has_completed: completed_by job_cost sched j t.\n\n        (* Then, for any value of service less than the cost of j, ...*)\n        Variable s: time.\n        Hypothesis H_less_than_cost: s < job_cost j.\n\n        (* ...there exists a last execution where the service received\n           by job j equals s. *)\n        Lemma exists_last_execution_with_smaller_service:\n          exists t0,\n            service sched j (time_after_last_execution j t0) = s.\n        Proof.\n          have SAME := same_service_since_last_execution.\n          rename H_jobs_must_arrive_to_execute into ARR.\n          move: H_j_has_completed => COMP.\n          feed (exists_intermediate_point (service sched j));\n            first by apply service_is_a_step_function.\n          move => EX; feed (EX (job_arrival j) t).\n          { feed (cumulative_service_implies_scheduled sched j 0 t).\n            apply leq_ltn_trans with (n := s); first by done.\n            apply leq_trans with (job_cost j); by done.\n            move => [t' [/= LTt SCHED]].\n            apply leq_trans with (n := t'); last by apply ltnW.\n              by apply ARR in SCHED.\n          }\n          feed (EX s).\n          { apply/andP; split. \n            - rewrite /service /service_during.\n                by rewrite (ignore_service_before_arrival job_arrival) // big_geq.\n            - apply leq_ltn_trans with (n := s); first by done.\n                by apply leq_trans with (job_cost j).\n          }\n          move: EX => [x_mid [_ SERV]]; exists x_mid.\n          by rewrite -SERV SAME.\n        Qed.\n\n      End ExistsIntermediateExecution.\n\n      (* In this section we prove that before the last execution the job\n         must have received strictly less service. *)\n      Section LessServiceBeforeLastExecution.\n\n        (* Let t be any time... *)\n        Variable t: time.\n\n        (* ...and consider any earlier time t0 no earlier than the arrival of job j... *)\n        Variable t0: time.\n        Hypothesis H_no_earlier_than_arrival: has_arrived job_arrival j t0.\n\n        (* ...and before the last execution of job j (with respect to time t). *)\n        Hypothesis H_before_last_execution: t0 < time_after_last_execution j t.\n\n        (* Then, we can prove that the service received by j before time t0\n           is strictly less than the service received by j before time t. *)\n        Lemma less_service_before_start_of_suspension:\n          service sched j t0 < service sched j t.\n        Proof.\n          rename H_no_earlier_than_arrival into ARR, H_before_last_execution into LT.\n          set ex := time_after_last_execution in LT.\n          set S := service sched.\n          case EX:([exists t0:'I_t, scheduled_at sched j t0]); last first.\n          {\n            rewrite /ex /time_after_last_execution EX in LT.\n            apply leq_trans with (p := t0) in LT; last by done.\n            by rewrite ltnn in LT.\n          }\n          {\n            rewrite /ex /time_after_last_execution EX in LT.\n            set m := (X in _ < X + 1) in LT.\n            apply leq_ltn_trans with (n := S j m);\n              first by rewrite -/m addn1 ltnS in LT; apply extend_sum.\n            move: EX => /existsP [t' SCHED'].\n            have LTt: m < t by apply bigmax_ltn_ord with (i0 := t').\n            rewrite /S /service /service_during.\n            rewrite -> big_cat_nat with (p := t) (n := m); [simpl | by done | by apply ltnW].\n            rewrite -addn1 leq_add2l; destruct t; first by done.\n            rewrite big_nat_recl //.\n            apply leq_trans with (n := scheduled_at sched j m); last by apply leq_addr.\n            rewrite lt0n eqb0 negbK.\n            by apply bigmax_pred with (i0 := t').\n          }\n        Qed.\n\n      End LessServiceBeforeLastExecution.\n      \n    End Lemmas.\n      \n  End TimeAfterLastExecution.\n\nEnd LastExecution.", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/classic/model/schedule/uni/susp/last_execution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.69322556040245}}
{"text": "(* Copyright (c) 2014, Robert Dockins *)\n\nRequire Import NArith.\n\nLocal Open Scope N_scope.\n\n(**  * Bitwise pairing function on [N].\n\n       Here we define a \"bitwise\" pairing isomorphism\n       on the nonnegative integers.  This is one of\n       many different ways to witness the isormporphism\n       between [N] and [N×N].\n\n       We will use the pairing function to define the union\n       of countable sets and other similar constructions.\n       The details of the isomorphism are unimportant\n       once the isomorphism is defined.  We prove this particular\n       isomorphism because it requires almost no facts about\n       arithmetic, and the proofs go by simple inductions on the\n       binary representation of positives.\n  *)\n\nFixpoint inflate (x:positive) : positive :=\n  match x with\n  | xH    => xO xH\n  | xO x' => xO (xO (inflate x'))\n  | xI x' => xO (xI (inflate x'))\n  end.\n\nFixpoint inflate' (x:positive) : positive :=\n  match x with\n  | xH    => xH\n  | xO x' => xO (xO (inflate' x'))\n  | xI x' => xI (xO (inflate' x'))\n  end.\n\nFixpoint deflate (x:positive) : N :=\n  match x with\n  | xH    => N0\n  | xO xH => Npos xH\n  | xI xH => Npos xH\n  | xO (xO x') => match deflate x' with N0 => N0 | Npos q => Npos (xO q) end\n  | xI (xO x') => match deflate x' with N0 => N0 | Npos q => Npos (xO q) end\n  | xO (xI x') => match deflate x' with N0 => Npos xH | Npos q => Npos (xI q) end\n  | xI (xI x') => match deflate x' with N0 => Npos xH | Npos q => Npos (xI q) end\n  end.\n\nFixpoint deflate' (x:positive) : N :=\n  match x with\n  | xH    => Npos xH\n  | xO xH => N0\n  | xI xH => Npos xH\n  | xO (xO x') => match deflate' x' with N0 => N0 | Npos q => Npos (xO q) end\n  | xI (xO x') => match deflate' x' with N0 => Npos xH | Npos q => Npos (xI q) end\n  | xO (xI x') => match deflate' x' with N0 => N0 | Npos q => Npos (xO q) end\n  | xI (xI x') => match deflate' x' with N0 => Npos xH | Npos q => Npos (xI q) end\n  end.\n\nLemma deflate_inflate0 : forall x,\n  deflate (inflate x) = Npos x.\nProof.\n  induction x; simpl; intros; auto.\n  rewrite IHx; auto.\n  rewrite IHx; auto.\nQed.\n\nLemma deflate_inflate0' : forall y,\n  deflate' (inflate' y) = Npos y.\nProof.\n  induction y; simpl; intros; auto.\n  rewrite IHy; auto.\n  rewrite IHy; auto.\nQed.\n\nLemma deflate_inflate1 : forall y,\n  deflate (inflate' y) = 0.\nProof.\n  induction y; simpl; auto.\n  rewrite IHy; auto.\n  rewrite IHy; auto.\nQed.\n\nLemma deflate_inflate1' : forall x,\n  deflate' (inflate x) = 0.\nProof.\n  induction x; simpl; auto.\n  rewrite IHx; auto.\n  rewrite IHx; auto.\nQed.\n\nLemma deflate_inflate : forall x y,\n  deflate (inflate x + inflate' y) = Npos x.\nProof.\n  induction x; simpl; intros.\n  destruct y; simpl; f_equal; auto.\n  rewrite IHx. auto.\n  rewrite IHx. auto.\n  rewrite deflate_inflate0. auto.\n  destruct y; simpl; f_equal; auto.\n  rewrite IHx. auto.\n  rewrite IHx. auto.\n  rewrite deflate_inflate0. auto.\n  destruct y; simpl; f_equal; auto.\n  rewrite deflate_inflate1. auto.\n  rewrite deflate_inflate1. auto.\nQed.  \n\nLemma deflate_inflate' : forall y x,\n  deflate' (inflate x + inflate' y) = Npos y.\nProof.\n  induction y; simpl; intros; auto.\n  destruct x; simpl.\n  rewrite IHy. auto.\n  rewrite IHy. auto.\n  rewrite deflate_inflate0'. auto.\n  destruct x; simpl.\n  rewrite IHy. auto.\n  rewrite IHy. auto.\n  rewrite deflate_inflate0'. auto.\n  destruct x; simpl.\n  rewrite deflate_inflate1'. auto.\n  rewrite deflate_inflate1'. auto.\n  auto.\nQed.\n\nLemma deflate00 : forall p, deflate (p~0~0) = 2*(deflate p).\nProof.\n  intros. simpl.\n  case_eq (deflate p); auto.\nQed.\n\nLemma deflate01 : forall p, deflate (p~0~1) = 2*(deflate p).\nProof.\n  intros. simpl.\n  case_eq (deflate p); auto.\nQed.\n\nLemma deflate10 : forall p, deflate (p~1~0) = 2*(deflate p) + 1 .\nProof.\n  intros. simpl.\n  case_eq (deflate p); auto.\nQed.\n\nLemma deflate11 : forall p, deflate (p~1~1) = 2*(deflate p) + 1 .\nProof.\n  intros. simpl.\n  case_eq (deflate p); auto.\nQed.\n\nLemma deflate00' : forall p, deflate' (p~0~0) = 2*(deflate' p).\nProof.\n  intros. simpl.\n  case_eq (deflate' p); auto.\nQed.\n\nLemma deflate01' : forall p, deflate' (p~0~1) = 2*(deflate' p)+1.\nProof.\n  intros. simpl.\n  case_eq (deflate' p); auto.\nQed.\n\nLemma deflate10' : forall p, deflate' (p~1~0) = 2*(deflate' p).\nProof.\n  intros. simpl.\n  case_eq (deflate' p); auto.\nQed.\n\nLemma deflate11' : forall p, deflate' (p~1~1) = 2*(deflate' p) + 1 .\nProof.\n  intros. simpl.\n  case_eq (deflate' p); auto.\nQed.\n\n\nDefinition pairing (p:N*N) : N :=\n  match p with\n  | (N0, N0) => N0\n  | (N0, Npos y) => Npos (inflate' y)\n  | (Npos x, N0) => Npos (inflate x)\n  | (Npos x, Npos y) => Npos (inflate x + inflate' y)\n  end.\n\nDefinition unpairing (z:N) : N*N :=\n  match z with\n  | N0 => (N0,N0)\n  | Npos z => (deflate z, deflate' z)\n  end.\n\nLemma pairing00 : forall p q,\n  pairing (2*p, 2*q) = 4*pairing (p,q).\nProof.\n  simpl; intros.\n  destruct p; destruct q; simpl; auto.\nQed.\n\nLemma pairing10 : forall p q,\n  pairing (2*p + 1, 2*q) = 4*pairing (p,q)+2.\nProof.\n  simpl; intros.\n  destruct p; destruct q; simpl; auto.\nQed.\n\nLemma pairing01 : forall p q,\n  pairing (2*p, 2*q + 1) = 4*pairing (p,q)+1.\nProof.\n  simpl; intros.\n  destruct p; destruct q; simpl; auto.\nQed.\n\nLemma pairing11 : forall p q,\n  pairing (2*p + 1, 2*q + 1) = 4*pairing (p,q)+3.\nProof.\n  simpl; intros.\n  destruct p; destruct q; simpl; auto.\nQed.\n\nLemma unpairing_pairing : forall p, unpairing (pairing p) = p.\nProof.\n  intros [x y].\n  destruct x; destruct y; simpl; auto.\n  rewrite deflate_inflate1. rewrite deflate_inflate0'. auto.\n  rewrite deflate_inflate1'. rewrite deflate_inflate0. auto.\n  rewrite deflate_inflate.\n  rewrite deflate_inflate'.\n  auto.\nQed.\n\nLemma pairing_unpairing : forall z, pairing (unpairing z) = z.\nProof.\n  intro z. destruct z. simpl; auto.\n  unfold unpairing.\n  revert p. fix 1. intro p.\n  destruct p. destruct p.\n  rewrite deflate11. rewrite deflate11'.\n  rewrite pairing11. rewrite pairing_unpairing.\n  auto.\n\n  rewrite deflate01. rewrite deflate01'.\n  rewrite pairing01. rewrite pairing_unpairing.\n  auto.\n  simpl. auto.\n\n  destruct p.\n  rewrite deflate10. rewrite deflate10'.\n  rewrite pairing10. rewrite pairing_unpairing.\n  auto.\n  rewrite deflate00. rewrite deflate00'.\n  rewrite pairing00. rewrite pairing_unpairing.\n  auto.\n  simpl. auto.\n  simpl. auto.\nQed.\n\nGlobal Opaque unpairing pairing.\n", "meta": {"author": "lastland", "repo": "DomainTheory", "sha": "e7bf598569efaafe9499a9334edc43c9659f82fa", "save_path": "github-repos/coq/lastland-DomainTheory", "path": "github-repos/coq/lastland-DomainTheory/DomainTheory-e7bf598569efaafe9499a9334edc43c9659f82fa/pairing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6932255535078099}}
{"text": "Require Export D.\n\n\n\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.  \n  intros. induction n. simpl. reflexivity.\n  simpl.\n  \n  Lemma plus_assoc : forall a b c : nat,\n   a + (b + c) = (a + b) + c.\n   Proof. \n     intros. induction a. reflexivity.\n     simpl. rewrite <- IHa. reflexivity. Qed.\n  \n  Lemma mult_dist : forall a b c : nat,\n    a * c + b * c = (a + b) * c.\n    Proof.\n      intros. induction a. simpl.  reflexivity.\n      simpl. rewrite <- plus_assoc. rewrite <- IHa. reflexivity. Qed.\n  \n  rewrite <- mult_dist. rewrite -> IHn. reflexivity. Qed.\n", "meta": {"author": "YeongjinOh", "repo": "Programming-language", "sha": "a235e30cec9cab33fa52a7f708ae15d84b869615", "save_path": "github-repos/coq/YeongjinOh-Programming-language", "path": "github-repos/coq/YeongjinOh-Programming-language/Programming-language-a235e30cec9cab33fa52a7f708ae15d84b869615/02/P08.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.6932255488602431}}
{"text": "Require Import List.\n\nTheorem length_is_linear_over_app :\n  forall (A : Type) (l1 l2 : list A),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros.\n  induction l1.\n    simpl.\n    reflexivity.\n\n    simpl.\n    rewrite IHl1.\n    reflexivity.\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/list/LengthIsLinearOverApp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6932255443660954}}
{"text": "Require Export Subbases.\nRequire Export Relation_Definitions_Implicit.\nRequire Export SeparatednessAxioms.\n\nSection OrderTopology.\n\nVariable X:Type.\nVariable R:relation X.\nHypothesis R_ord: order R.\n\nInductive order_topology_subbasis : Family X :=\n  | intro_lower_interval: forall x:X,\n    In order_topology_subbasis [ y:X | R y x /\\ y <> x ]\n  | intro_upper_interval: forall x:X,\n    In order_topology_subbasis [ y:X | R x y /\\ y <> x].\n\nDefinition OrderTopology : TopologicalSpace :=\n  Build_TopologicalSpace_from_subbasis X order_topology_subbasis.\n\nSection if_total_order.\n\nHypothesis R_total: forall x y:X, R x y \\/ R y x.\n\nLemma lower_closed_interval_closed: forall x:X,\n  closed [ y:X | R y x ] (X:=OrderTopology).\nProof.\nintro.\nred.\nmatch goal with |- open ?U => cut (U = interior U) end.\nintro.\nrewrite H; apply interior_open.\napply Extensionality_Ensembles; split.\n2:apply interior_deflationary.\nintros y ?.\nred in H.\nred in H.\nassert (R x y).\ndestruct (R_total x y); trivial.\ncontradiction H.\nconstructor; trivial.\nexists ([z:X | R x z /\\ z <> x]).\nconstructor; split.\napply (Build_TopologicalSpace_from_subbasis_subbasis\n  _ order_topology_subbasis).\nconstructor.\nred; intros z ?.\ndestruct H1.\ndestruct H1.\nintro.\ndestruct H3.\ncontradiction H2.\napply (ord_antisym R_ord); trivial.\nconstructor.\nsplit; trivial.\nintro.\ncontradiction H.\nconstructor.\ndestruct H1; apply (ord_refl R_ord).\nQed.\n\nLemma upper_closed_interval_closed: forall x:X,\n  closed [y:X | R x y] (X:=OrderTopology).\nProof.\nintro.\nred.\nmatch goal with |- open ?U => cut (U = interior U) end.\nintro.\nrewrite H; apply interior_open.\napply Extensionality_Ensembles; split.\n2:apply interior_deflationary.\nintros y ?.\nred in H.\nred in H.\nassert (R y x).\ndestruct (R_total x y); trivial.\ncontradiction H.\nconstructor; trivial.\nexists ([z:X | R z x /\\ z <> x]).\nconstructor; split.\napply (Build_TopologicalSpace_from_subbasis_subbasis\n  _ order_topology_subbasis).\nconstructor.\nred; intros z ?.\ndestruct H1.\ndestruct H1.\nintro.\ndestruct H3.\ncontradiction H2.\napply (ord_antisym R_ord); trivial.\nconstructor.\nsplit; trivial.\nintro.\ncontradiction H.\nconstructor.\ndestruct H1; apply (ord_refl R_ord).\nQed.\n\nLemma order_topology_Hausdorff: Hausdorff OrderTopology.\nProof.\nred.\nmatch goal with |- forall x y:point_set OrderTopology, ?P =>\n  cut (forall x y:point_set OrderTopology, R x y -> P)\n  end.\nintros.\ndestruct (R_total x y).\nexact (H x y H1 H0).\nassert (y <> x).\nauto.\ndestruct (H y x H1 H2) as [V [U [? [? [? []]]]]].\nexists U; exists V; repeat split; trivial.\ntransitivity (Intersection V U); trivial.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H8; constructor; trivial.\ndestruct H8; constructor; trivial.\n\nintros.\npose proof (Build_TopologicalSpace_from_subbasis_subbasis\n  _ order_topology_subbasis).\ndestruct (classic (exists z:X, R x z /\\ R z y /\\ z <> x /\\ z <> y)).\ndestruct H2 as [z [? [? []]]].\nexists ([w:X | R w z /\\ w <> z]);\nexists ([w:X | R z w /\\ w <> z]).\nrepeat split; trivial.\napply H1.\nconstructor.\napply H1.\nconstructor.\nauto.\nauto.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H6.\ndestruct H6.\ndestruct H7.\ndestruct H6.\ndestruct H7.\ncontradiction H8.\napply (ord_antisym R_ord); trivial.\ndestruct H6.\n\nexists ([w:X | R w y /\\ w <> y]);\nexists ([w:X | R x w /\\ w <> x]).\nrepeat split.\napply H1.\nconstructor.\napply H1.\nconstructor.\ntrivial.\ntrivial.\ntrivial.\nauto.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H3.\ndestruct H3.\ndestruct H4.\ndestruct H3.\ndestruct H4.\ncontradiction H2.\nexists x0; repeat split; trivial.\ndestruct H3.\nQed.\n\nEnd if_total_order.\n\nEnd OrderTopology.\n\nImplicit Arguments OrderTopology [[X]].\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/OrderTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6932255375225942}}
{"text": "Set Implicit Arguments.\nGeneralizable All Variables.\nFrom TLC Require Import LibTactics.\nFrom iris_time.union_find.math Require Import LibNatExtra Filter.\n\n(* [le m] can be understood as the semi-open interval of the natural numbers\n   that are greater than or equal to [m]. The subsets [le m] form a filter\n   base; that is, if we close them under inclusion, then we obtain a filter,\n   which intuitively represents going to infinity. We call this modality\n   [towards_infinity]. *)\n\nDefinition towards_infinity (F : nat -> Prop) :=\n  exists m, forall n, m <= n -> F n.\n\nInstance filter_towards_infinity : Filter towards_infinity.\nProof.\n  unfold towards_infinity. econstructor.\n  (* There exists an element in this filter, namely the universe, [le 0]. *)\n  exists (fun n => 0 <= n). eauto.\n  (* Every set of the form [le m] is nonempty. *)\n  introv [ m ? ]. exists m. eauto.\n  (* Closure by intersection and subset. *)\n  introv [ m1 ? ] [ m2 ? ] ?. exists (max m1 m2). intros.\n  max_case; eauto with lia.\nQed.\n\n(* Every subset of the form [le m] is a member of this filter. *)\n\nLemma towards_infinity_le:\n  forall m,\n  towards_infinity (le m).\nProof.\n  unfold towards_infinity. eauto.\nQed.\n\nHint Resolve towards_infinity_le : filter.\n\n(* The statement that [f x] tends towards infinity as [x] tends\n   towards infinity can be stated in its usual concrete form or\n   more abstractly using filters. *)\n\nLemma prove_tends_towards_infinity:\n  forall f : nat -> nat,\n  (forall y, exists x0, forall x, x0 <= x -> y <= f x) ->\n  limit towards_infinity towards_infinity f.\nProof.\n  introv h. intros F [ m ? ].\n  generalize (h m); intros [ x0 ? ].\n  exists x0. eauto.\nQed.\n\nLemma exploit_tends_towards_infinity:\n  forall f : nat -> nat,\n  limit towards_infinity towards_infinity f ->\n  (forall y, exists x0, forall x, x0 <= x -> y <= f x).\nProof.\n  intros ? hlimit y.\n  forwards [ x0 ? ]: hlimit (le y).\n    eapply towards_infinity_le.\n  eauto.\nQed.\n\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/FilterTowardsInfinity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624791, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6932046041786576}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat div seq choice fintype.\nRequire Import finfun bigops prime binomial.\n\n(*****************************************************************************)\n(*   The algebraic part of the Algebraic Hierarchy, as described in          *)\n(*          ``Packaging mathematical structures'', TPHOLs09, by              *)\n(*   Francois Garillot, Georges Gonthier, Assia Mahboubi, Laurence Rideau    *)\n(*                                                                           *)\n(* This file defines for each Structure (Zmodule, Ring, etc ...) its type,   *)\n(* its packers and its canonical properties :                                *)\n(*                                                                           *)\n(*  * Zmodule                                                                *)\n(*      zmodType        == type for Zmodule structure                        *)\n(*      ZmodMixin       == builds the mixin containing the definition        *)\n(*                         of a Zmodule                                      *)\n(*      ZmodType R M    == packs the mixin M to build a Zmodule of type      *)\n(*                         zmodType. (The underlying type R should have a    *)\n(*                         choiceType canonical structure)                   *)\n(*      0               == the additive identity element of a Zmodule        *)\n(*      x + y           == the addition operation of a Zmodule               *)\n(*      - x             == the opposite operation of a Zmodule               *)\n(*      x - y           == the substraction operation of a Zmodule           *)\n(*                      := x + - y                                           *)\n(*      x +* n , x -* n == the generic multiplication by a nat               *)\n(*      \\sum_<range> e  == iterated sum for a Zmodule (cf bigops.v)          *)\n(*      e`_i            == nth 0 e i, when e : seq M and M is a zmodType     *)\n(*      ... and a many classical Lemmas on these Zmodule laws                *)\n(*                                                                           *)\n(*  * Ring                                                                   *)\n(*      ringType      == type for ring structure                             *)\n(*      RingMixin     == builds the mixin containing the definitions of a    *)\n(*                       ring (the underlying type should have a zmodType    *)\n(*                       structure)                                          *)\n(*      RingType R M  == packs the ring mixin M to build a ring on type R    *)\n(*      RevRingType T == repacks T to build the ring where the               *)\n(*                       multiplicative law is reversed ( x *' y = y * x )   *)\n(*      1             == the multiplicative identity element of a Ring       *)\n(*      n%:R          == the ring image of a nat n (e.g., 1%:R := 1%R)       *)\n(*      x * y         == the multiplication operation of a ring              *)\n(*    \\prod_<range> e == iterated product for a ring (cf bigops.v)           *)\n(*      x ^+ y        == the exponentiation operation of a ring              *)\n(*     GRing.comm x y <=> x and y commute, i.e., x * y = y * x               *)\n(*      [char R]      == the characteristic of R, i.e., the set of prime     *)\n(*                       numbers p such that p%:R = 0 in R. The set [char p] *)\n(*                       has a most one element, and is represented as a     *)\n(*                       pred_nat collective predicate (see prime.v); thus   *)\n(*                       the statement p \\in [char R] can be read as ``R has *)\n(*                       characteristic p'', while [char R] =i pred0 means   *)\n(*                       ``R has characteristic 0'' when R is a field.       *)\n(* Frobenius_aut chRp == the Frobenius automorphism mapping x : R to x ^+ p, *)\n(*                       where chRp : p \\in [char R] is a proof that R has   *)\n(*                       indeed (non-zero) characteristic p.                 *)\n(*                                                                           *)\n(*  * Commutative Ring                                                       *)\n(*      comRingType      == type for commutative ring structure              *)\n(*    ComRingType R mulC == packs mulC to build a commutative ring.          *)\n(*                          (The underlying type R should have a ring        *)\n(*                          canonical structure)                             *)\n(*      ComRingMixin     == builds the mixin containing the definitions of a *)\n(*                          *non commutative* ring, using the commutativity  *)\n(*                          to decrease the number of axioms.                *)\n(*                                                                           *)\n(*  * Unit Ring                                                              *)\n(*      unitRingType   == type for unit ring structure                       *)\n(*      UnitRingMixin  == builds the mixin containing the definitions        *)\n(*                        of a unit ring. (The underlying type should        *)\n(*                        have a ring canonical structure)                   *)\n(*    UnitRingType R M == packs the unit ring mixin M to build a unit ring.  *)\n(*                        WARNING: while it is possible to omit R for most   *)\n(*                        of the xxxType functions, R MUST be explicitly     *)\n(*                        given when UnitRingType is used with a mixin       *)\n(*                        produced by ComUnitRingMixin, otherwise the        *)\n(*                        resulting structure will have the WRONG sort and   *)\n(*                        will not be used by type inference.                *)\n(*      GRing.unit x   == x is a unit (i.e., has an inverse)                 *)\n(*      x^-1           == the inversion operation element of a unit ring     *)\n(*                        (returns x if is x is not an unit)                 *)\n(*      x / y          := x * y^-1                                           *)\n(*      x ^- n         := (x ^+ n)^-1                                        *)\n(*                                                                           *)\n(*  * Commutative Unit Ring                                                  *)\n(*      comUnitRingType   == type for unit ring structure                    *)\n(*      ComUnitRingMixin  == builds the mixin containing the definitions     *)\n(*                           of a *non commutative unit ring*, but using     *)\n(*                           the commutative property. The underlying type   *)\n(*                           should have a commutative ring canonical        *)\n(*                           structure. WARNING: ALWAYS give an explicit     *)\n(*                           type argument to UnitRingType along with a      *)\n(*                           mixin produced by ComUnitRingMixin (see above). *)\n(*                                                                           *)\n(*  * Integral Domain (integral, commutative, unit ring)                     *)\n(*      idomainType       == type for integral domain structure              *)\n(*      IdomainType R M   == packs the idomain mixin M to build a integral   *)\n(*                           domain. (The underlying type R should have a    *)\n(*                           commutative unit ring canonical structure)      *)\n(*                                                                           *)\n(*  * Field                                                                  *)\n(*      fieldType         == type for field structure                        *)\n(*      FieldUnitMixin    == builds a *non commutative unit ring* mixin,     *)\n(*                           using some field properties. (The underlying    *)\n(*                           type should have a *commutative ring* canonical *)\n(*                           structure)                                      *)\n(*      FieldMixin        == builds the field mixin. (The underlying type    *)\n(*                           should have a *commutative ring* canonical      *)\n(*                           structure)                                      *)\n(*      FieldIdomainMixin == builds an *idomain* mixin, using a field mixin  *)\n(*      FieldType R M     == packs the field mixin M to build a field        *)\n(*                           (The underlying type R should have a            *)\n(*                           integral domain canonical structure)            *)\n(*                                                                           *)\n(*  * Decidable Field                                                        *)\n(*      decFieldType      == type for decidable field structure              *)\n(*      DecFieldMixin     == builds the mixin containing the definitions of  *)\n(*                           a decidable Field. (The underlying type should  *)\n(*                           have a unit ring canonical structure)           *)\n(*      DecFieldType R M  == packs the decidable field mixin M to build a    *)\n(*                           decidable field. (The underlying type R should  *)\n(*                           have a field canonical structure)               *)\n(*      GRing.term R      == the type of formal expressions in a unit ring R *)\n(*                           with formal variables 'X_k, k : nat, and        *)\n(*                           manifest constants x%:T, x : R. The notation of *)\n(*                           all the ring operations is redefined for terms, *)\n(*                           in scope %T.                                    *)\n(*      GRing.formula R   == the type of first order formulas over R; the %T *)\n(*                           scope binds the logical connectives /\\, \\/, ~,  *)\n(*                           ==>, ==, and != to formulae; GRing.True/False   *)\n(*                           and GRing.Bool b denote constant formulae, and  *)\n(*                           quantifiers are written 'forall/'exists 'X_k, f *)\n(*                           GRing.Unit x tests for ring units, and the      *)\n(*                           the construct Pick p_f t_f e_f can be used to   *)\n(*                           emulate the pick function defined in fintype.v. *)\n(*      GRing.eval e t    == the value of term t with valuation e : seq R    *)\n(*                           (e maps 'X_i to e`_i)                           *)\n(*  GRing.same_env e1 e2 <=> environments e1 and e2 are extensionally equal  *)\n(*    GRing.qf_eval e f   == the value (in bool) of a quantifier-free f.     *)\n(*      GRing.qf_form f   == f is quantifier-free.                           *)\n(*      GRing.holds e f   == the intuitionistic CiC interpretation of the    *)\n(*                           formula f holds with valuation e                *)\n(*      GRing.sat e f     == valuation e satisfies f (only in a decField)    *)\n(*      GRing.sol n f     == a sequence e of size n such that e satisfies f, *)\n(*                           if one exists, or [::] if there is no such e    *)\n(*                                                                           *)\n(*  * Closed Field                                                           *)\n(*      closedFieldType   == type for closed field structure                 *)\n(*    ClosedFieldType R M == packs the closed field mixin M to build a       *)\n(*                           closed field. (The underlying type R should     *)\n(*                           have a decidable field canonical structure.)    *)\n(*                                                                           *)\n(* * Morphism                                                                *)\n(*     GRing.morphism f <=> f is a ring morphism: f commutes with 0, +, -,   *)\n(*                          *, 1, and with ^-1 and / in integral domains.    *)\n(*                   x^f == the image of x under some morphism. This         *)\n(*                          notation is only reserved (not defined) here;    *)\n(*                          it is bound locally in sections where some       *)\n(*                          morphism is used heavily (e.g., the container    *)\n(*                          morphism in the parametricity sections of poly   *)\n(*                          and matrix, or the Frobenius section here).      *)\n(*  * Lmodule                                                                *)\n(*      lmodType R      == type for Lmodule structure over the ring R        *)\n(*      LmodMixin R     == builds the mixin containing the definition        *)\n(*                         of a Lmodule over the ring R                      *)\n(*      LmodType R T M  == packs the mixin M to build a Lmodule of type      *)\n(*                         lmodType R. (The underlying type T should have a  *)\n(*                         zmodType canonical structure)                     *)\n(*      a *: x          == the external operation of a Lmodule               *)\n(*                                                                           *)\n(* The Lemmas about theses structures are all contained in GRing.Theory.     *)\n(* Notations are defined in scope ring_scope (delimiter %R), except term and *)\n(* formula notations, which are in term_scope (delimiter %T).                *)\n(*                                                                           *)\n(* NB: The module GRing should not be imported, only the main module and     *)\n(*     GRing.Theory should be.                                               *)\n(*****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(* Abstract algebra framework for ssreflect.                          *)\n(* We define a number of structures that ``package'' common algebraic *)\n(* properties of operations. These extend the combinatorial classes   *)\n(* with notation and theory for classical algebraic structures.       *)\n\nReserved Notation \"+%R\" (at level 0).\nReserved Notation \"-%R\" (at level 0).\nReserved Notation \"*%R\" (at level 0).\nReserved Notation \"n %:R\" (at level 2, left associativity, format \"n %:R\").\nReserved Notation \"[ 'char' F ]\" (at level 0, format \"[ 'char'  F ]\").\n\nReserved Notation \"x %:T\" (at level 2, left associativity, format \"x %:T\").\nReserved Notation \"''X_' i\" (at level 8, i at level 2, format \"''X_' i\").\n(* Patch for recurring Coq parser bug: Coq seg faults when a level 200 *)\n(* notation is used as a pattern.                                      *)\nReserved Notation \"''exists' ''X_' i , f\"\n  (at level 199, i at level 2, right associativity,\n   format \"'[hv' ''exists'  ''X_' i , '/ '  f ']'\").\nReserved Notation \"''forall' ''X_' i , f\"\n  (at level 199, i at level 2, right associativity,\n   format \"'[hv' ''forall'  ''X_' i , '/ '  f ']'\").\n\nReserved Notation \"x ^f\" (at level 2, left associativity, format \"x ^f\").\n\nDelimit Scope ring_scope with R.\nDelimit Scope term_scope with T.\nLocal Open Scope ring_scope.\n\nModule GRing.\n\nImport Monoid.Theory.\n\nModule Zmodule.\n\nRecord mixin_of (M : Type) : Type := Mixin {\n  zero : M;\n  opp : M -> M;\n  add : M -> M -> M;\n  _ : associative add;\n  _ : commutative add;\n  _ : left_id zero add;\n  _ : left_inverse zero opp add\n}.\n\nRecord class_of (M : Type) : Type :=\n  Class { base :> Choice.class_of M; ext :> mixin_of M }.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition clone T cT c of phant_id (class cT) c := @Pack T c T.\n\nDefinition pack T m :=\n  fun bT b & phant_id (Choice.class bT) b => Pack (@Class T b m) T.\n\nCoercion eqType cT := Equality.Pack (class cT) cT.\nCoercion choiceType cT := Choice.Pack (class cT) cT.\n\nEnd Zmodule.\n\nCanonical Structure Zmodule.eqType.\nCanonical Structure Zmodule.choiceType.\nBind Scope ring_scope with Zmodule.sort.\n\nDefinition zero M := Zmodule.zero (Zmodule.class M).\nDefinition opp M := Zmodule.opp (Zmodule.class M).\nDefinition add M := Zmodule.add (Zmodule.class M).\n\nLocal Notation \"0\" := (zero _) : ring_scope.\nLocal Notation \"-%R\" := (@opp _) : ring_scope.\nLocal Notation \"- x\" := (opp x) : ring_scope.\nLocal Notation \"+%R\" := (@add _) : ring_scope.\nLocal Notation \"x + y\" := (add x y) : ring_scope.\nLocal Notation \"x - y\" := (x + - y) : ring_scope.\n\nDefinition natmul M x n := nosimpl iterop _ n +%R x (zero M).\n\nLocal Notation \"x *+ n\" := (natmul x n) : ring_scope.\nLocal Notation \"x *- n\" := ((- x) *+ n) : ring_scope.\n\nLocal Notation \"\\sum_ ( i <- r | P ) F\" := (\\big[+%R/0]_(i <- r | P) F).\nLocal Notation \"\\sum_ ( m <= i < n ) F\" := (\\big[+%R/0]_(m <= i < n) F).\nLocal Notation \"\\sum_ ( i < n ) F\" := (\\big[+%R/0]_(i < n) F).\nLocal Notation \"\\sum_ ( i \\in A ) F\" := (\\big[+%R/0]_(i \\in A) F).\n\nLocal Notation \"s `_ i\" := (nth 0 s i) : ring_scope.\n\nSection ZmoduleTheory.\n\nVariable M : Zmodule.type.\nImplicit Types x y : M.\n\nLemma addrA : @associative M +%R. Proof. by case M => T [? []]. Qed.\nLemma addrC : @commutative M M +%R. Proof. by case M => T [? []]. Qed.\nLemma add0r : @left_id M M 0 +%R. Proof. by case M => T [? []]. Qed.\nLemma addNr : @left_inverse M M M 0 -%R +%R. Proof. by case M => T [? []]. Qed.\n\nLemma addr0 : @right_id M M 0 +%R.\nProof. by move=> x; rewrite addrC add0r. Qed.\nLemma addrN : @right_inverse M M M 0 -%R +%R.\nProof. by move=> x; rewrite addrC addNr. Qed.\nDefinition subrr := addrN.\n\nCanonical Structure add_monoid := Monoid.Law addrA add0r addr0.\nCanonical Structure add_comoid := Monoid.ComLaw addrC.\n\nLemma addrCA : @left_commutative M M +%R. Proof. exact: mulmCA. Qed.\nLemma addrAC : @right_commutative M M +%R. Proof. exact: mulmAC. Qed.\n\nLemma addKr : @left_loop M M -%R +%R.\nProof. by move=> x y; rewrite addrA addNr add0r. Qed.\nLemma addNKr : @rev_left_loop M M -%R +%R.\nProof. by move=> x y; rewrite addrA addrN add0r. Qed.\nLemma addrK : @right_loop M M -%R +%R.\nProof. by move=> x y; rewrite -addrA addrN addr0. Qed.\nLemma addrNK : @rev_right_loop M M -%R +%R.\nProof. by move=> x y; rewrite -addrA addNr addr0. Qed.\nDefinition subrK := addrNK.\nLemma addrI : @right_injective M M M +%R.\nProof. move=> x; exact: can_inj (addKr x). Qed.\nLemma addIr : @left_injective M M M +%R.\nProof. move=> y; exact: can_inj (addrK y). Qed.\nLemma opprK : @involutive M -%R.\nProof. by move=> x; apply: (@addIr (- x)); rewrite addNr addrN. Qed.\nLemma oppr0 : -0 = 0 :> M.\nProof. by rewrite -[-0]add0r subrr. Qed.\nLemma oppr_eq0 : forall x, (- x == 0) = (x == 0).\nProof. by move=> x; rewrite (inv_eq opprK) oppr0. Qed.\n\nLemma subr0 : forall x, x - 0 = x. Proof. by move=> x; rewrite oppr0 addr0. Qed.\nLemma sub0r : forall x, 0 - x = - x. Proof. by move=> x; rewrite add0r. Qed.\n\nLemma oppr_add : {morph -%R: x y / x + y : M}.\nProof.\nby move=> x y; apply: (@addrI (x + y)); rewrite addrA subrr addrAC addrK subrr.\nQed.\n\nLemma oppr_sub : forall x y, - (x - y) = y - x.\nProof. by move=> x y; rewrite oppr_add addrC opprK. Qed.\n\nLemma subr_eq : forall x y z, (x - z == y) = (x == y + z).\nProof. by move=> x y z; rewrite (can2_eq (subrK _) (addrK _)). Qed.\n\nLemma subr_eq0 : forall x y, (x - y == 0) = (x == y).\nProof. by move=> x y; rewrite subr_eq add0r. Qed.\n\nLemma mulr0n : forall x, x *+ 0 = 0. Proof. by []. Qed.\nLemma mulr1n : forall x, x *+ 1 = x. Proof. by []. Qed.\n\nLemma mulrS : forall x n, x *+ n.+1 = x + x *+ n.\nProof. by move=> x [|n] //=; rewrite addr0. Qed.\n\nLemma mulrSr : forall x n, x *+ n.+1 = x *+ n + x.\nProof. by move=> x n; rewrite addrC mulrS. Qed.\n\nLemma mulrb : forall x (b : bool), x *+ b = (if b then x else 0).\nProof. by move=> x []. Qed.\n\nLemma mul0rn : forall n, 0 *+ n = 0 :> M.\nProof. by elim=> // n IHn; rewrite mulrS add0r. Qed.\n\nLemma oppr_muln : forall x n, - (x *+ n) = x *- n :> M.\nProof.\nby move=> x; elim=> [|n IHn]; rewrite ?oppr0 // !mulrS oppr_add IHn.\nQed.\n\nLemma mulrn_addl : forall n, {morph (fun x => x *+ n) : x y / x + y}.\nProof.\nmove=> n x y; elim: n => [|n IHn]; rewrite ?addr0 // !mulrS.\nby rewrite addrCA -!addrA -IHn -addrCA.\nQed.\n\nLemma mulrn_addr : forall x m n, x *+ (m + n) = x *+ m + x *+ n.\nProof.\nmove=> x n m; elim: n => [|n IHn]; first by rewrite add0r.\nby rewrite !mulrS IHn addrA.\nQed.\n\nLemma mulrnA : forall x m n, x *+ (m * n) = x *+ m *+ n.\nProof.\nmove=> x m n; rewrite mulnC.\nby elim: n => //= n IHn; rewrite mulrS mulrn_addr IHn.\nQed.\n\nLemma mulrnAC : forall x m n, x *+ m *+ n = x *+ n *+ m.\nProof. by move=> x m n; rewrite -!mulrnA mulnC. Qed.\n\nLemma sumr_opp : forall I r P (F : I -> M),\n  (\\sum_(i <- r | P i) - F i = - (\\sum_(i <- r | P i) F i)).\nProof. by move=> I r P F; rewrite (big_morph _ oppr_add oppr0). Qed.\n\nLemma sumr_sub : forall I r (P : pred I) (F1 F2 : I -> M),\n  \\sum_(i <- r | P i) (F1 i - F2 i)\n     = \\sum_(i <- r | P i) F1 i - \\sum_(i <- r | P i) F2 i.\nProof. by move=> *; rewrite -sumr_opp -big_split /=. Qed.\n\nLemma sumr_muln :  forall I r P (F : I -> M) n,\n  \\sum_(i <- r | P i) F i *+ n = (\\sum_(i <- r | P i) F i) *+ n.\nProof.\nby move=> I r P F n; rewrite (big_morph _ (mulrn_addl n) (mul0rn _)).\nQed.\n\nLemma sumr_muln_r :  forall x I r P (F : I -> nat),\n  \\sum_(i <- r | P i) x *+ F i = x *+ (\\sum_(i <- r | P i) F i).\nProof. by move=> x I r P F; rewrite (big_morph _ (mulrn_addr x) (erefl _)). Qed.\n\nLemma sumr_const : forall (I : finType) (A : pred I) (x : M),\n  \\sum_(i \\in A) x = x *+ #|A|.\nProof. by move=> I A x; rewrite big_const -iteropE. Qed.\n\nEnd ZmoduleTheory.\n\n\nModule Ring.\n\nRecord mixin_of (R : Zmodule.type) : Type := Mixin {\n  one : R;\n  mul : R -> R -> R;\n  _ : associative mul;\n  _ : left_id one mul;\n  _ : right_id one mul;\n  _ : left_distributive mul +%R;\n  _ : right_distributive mul +%R;\n  _ : one != 0\n}.\n\nDefinition EtaMixin R one mul mulA mul1x mulx1 mul_addl mul_addr nz1 :=\n  let _ := @Mixin R one mul mulA mul1x mulx1 mul_addl mul_addr nz1 in\n  @Mixin (Zmodule.Pack (Zmodule.class R) R) _ _\n     mulA mul1x mulx1 mul_addl mul_addr nz1.\n\nRecord class_of (R : Type) : Type := Class {\n  base :> Zmodule.class_of R;\n  ext :> mixin_of (Zmodule.Pack base R)\n}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition clone T cT c of phant_id (class cT) c := @Pack T c T.\n\nDefinition pack T b0 (m0 : mixin_of (@Zmodule.Pack T b0 T)) :=\n  fun bT b & phant_id (Zmodule.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m) T.\n\nCoercion eqType cT := Equality.Pack (class cT) cT.\nCoercion choiceType cT := Choice.Pack (class cT) cT.\nCoercion zmodType cT := Zmodule.Pack (class cT) cT.\n\nEnd Ring.\n\nBind Scope ring_scope with Ring.sort.\nCanonical Structure Ring.eqType.\nCanonical Structure Ring.choiceType.\nCanonical Structure Ring.zmodType.\n\nDefinition one (R : Ring.type) : R := Ring.one (Ring.class R).\nDefinition mul (R : Ring.type) : R -> R -> R := Ring.mul (Ring.class R).\nDefinition exp R x n := nosimpl iterop _ n (@mul R) x (one R).\n\nLocal Notation \"1\" := (one _).\nLocal Notation \"- 1\" := (- (1)).\nLocal Notation \"n %:R\" := (1 *+ n).\nLocal Notation \"*%R\" := (@mul _).\nLocal Notation \"x * y\" := (mul x y).\nLocal Notation \"x ^+ n\" := (exp x n).\n\nLocal Notation \"\\prod_ ( i <- r | P ) F\" := (\\big[*%R/1]_(i <- r | P) F).\nLocal Notation \"\\prod_ ( i \\in A ) F\" := (\\big[*%R/1]_(i \\in A) F).\n\n(* The ``field'' characteristic; the definition, and many of the theorems,   *)\n(* has to apply to rings as well; indeed, we need the Frobenius automorphism *)\n(* results for a non commutative ring in the proof of Gorenstein 2.6.3.      *)\nDefinition char (R : Ring.type) of phant R : nat_pred :=\n  [pred p | prime p && (p%:R == 0 :> R)].\n\nLocal Notation \"[ 'char' R ]\" := (char (Phant R)) : ring_scope.\n\nSection RingTheory.\n\nVariable R : Ring.type.\nImplicit Types x y : R.\n\nLemma mulrA : @associative R *%R. Proof. by case R => T [? []]. Qed.\nLemma mul1r : @left_id R R 1 *%R. Proof. by case R => T [? []]. Qed.\nLemma mulr1 : @right_id R R 1 *%R. Proof. by case R => T [? []]. Qed.\nLemma mulr_addl : @left_distributive R R *%R +%R.\nProof. by case R => T [? []]. Qed.\nLemma mulr_addr : @right_distributive R R *%R +%R.\nProof. by case R => T [? []]. Qed.\nLemma nonzero1r : 1 != 0 :> R. Proof. by case R => T [? []]. Qed.\nLemma oner_eq0 : (1 == 0 :> R) = false. Proof. exact: negbTE nonzero1r. Qed.\n\nLemma mul0r : @left_zero R R 0 *%R.\nProof.\nby move=> x; apply: (@addIr _ (1 * x)); rewrite -mulr_addl !add0r mul1r.\nQed.\nLemma mulr0 : @right_zero R R 0 *%R.\nProof.\nby move=> x; apply: (@addIr _ (x * 1)); rewrite -mulr_addr !add0r mulr1.\nQed.\nLemma mulrN : forall x y, x * (- y) = - (x * y).\nProof.\nby move=> x y; apply: (@addrI _ (x * y)); rewrite -mulr_addr !subrr mulr0.\nQed.\nLemma mulNr : forall x y, (- x) * y = - (x * y).\nProof.\nby move=> x y; apply: (@addrI _ (x * y)); rewrite -mulr_addl !subrr mul0r.\nQed.\nLemma mulrNN : forall x y, (- x) * (- y) = x * y.\nProof. by move=> x y; rewrite mulrN mulNr opprK. Qed.\nLemma mulN1r : forall x, -1 * x = - x.\nProof. by move=> x; rewrite mulNr mul1r. Qed.\nLemma mulrN1 : forall x, x * -1 = - x.\nProof. by move=> x; rewrite mulrN mulr1. Qed.\n\nCanonical Structure mul_monoid := Monoid.Law mulrA mul1r mulr1.\nCanonical Structure muloid := Monoid.MulLaw mul0r mulr0.\nCanonical Structure addoid := Monoid.AddLaw mulr_addl mulr_addr.\n\nLemma mulr_subl : forall x y z, (y - z) * x = y * x - z * x.\nProof. by move=> x y z; rewrite mulr_addl mulNr. Qed.\n\nLemma mulr_subr : forall x y z, x * (y - z) = x * y - x * z.\nProof. by move=> x y z; rewrite mulr_addr mulrN. Qed.\n\nLemma mulrnAl : forall x y n, (x *+ n) * y = (x * y) *+ n.\nProof.\nby move=> x y; elim=> [|n IHn]; rewrite ?mul0r // !mulrS mulr_addl IHn.\nQed.\n\nLemma mulrnAr : forall x y n, x * (y *+ n) = (x * y) *+ n.\nProof.\nby move=> x y; elim=> [|n IHn]; rewrite ?mulr0 // !mulrS mulr_addr IHn.\nQed.\n\nLemma mulr_natl : forall x n, n%:R * x = x *+ n.\nProof. by move=> x n; rewrite mulrnAl mul1r. Qed.\n\nLemma mulr_natr : forall x n, x * n%:R = x *+ n.\nProof. by move=> x n; rewrite mulrnAr mulr1. Qed.\n\nLemma natr_add : forall m n, (m + n)%:R = m%:R + n%:R :> R.\nProof. by move=> m n; exact: mulrn_addr. Qed.\n\nLemma natr_mul : forall m n, (m * n)%:R = m%:R * n%:R :> R.\nProof. by move=> m n; rewrite mulrnA -mulr_natr. Qed.\n\nLemma expr0 : forall x, x ^+ 0 = 1. Proof. by []. Qed.\nLemma expr1 : forall x, x ^+ 1 = x. Proof. by []. Qed.\n\nLemma exprS : forall x n, x ^+ n.+1 = x * x ^+ n.\nProof. by move=> x [] //; rewrite mulr1. Qed.\n\nLemma exp1rn : forall n, 1 ^+ n = 1 :> R.\nProof. by elim=> // n IHn; rewrite exprS mul1r. Qed.\n\nLemma exprn_addr : forall x m n, x ^+ (m + n) = x ^+ m * x ^+ n.\nProof.\nby move=> x m n; elim: m => [|m IHm]; rewrite ?mul1r // !exprS -mulrA -IHm.\nQed.\n\nLemma exprSr : forall x n, x ^+ n.+1 = x ^+ n * x.\nProof. by move=> x n; rewrite -addn1 exprn_addr expr1. Qed.\n\nDefinition commDef x y := x * y = y * x.\nNotation comm := commDef.\n\nLemma commr_sym : forall x y, comm x y -> comm y x. Proof. done. Qed.\nLemma commr_refl : forall x, comm x x. Proof. done. Qed.\n\nLemma commr0 : forall x, comm x 0.\nProof. by move=> x; rewrite /comm mulr0 mul0r. Qed.\n\nLemma commr1 : forall x, comm x 1.\nProof. by move=> x; rewrite /comm mulr1 mul1r. Qed.\n\nLemma commr_opp : forall x y, comm x y -> comm x (- y).\nProof. by move=> x y com_xy; rewrite /comm mulrN com_xy mulNr. Qed.\n\nLemma commrN1 : forall x, comm x (-1).\nProof. move=> x; apply: commr_opp; exact: commr1. Qed.\n\nLemma commr_add : forall x y z,\n  comm x y -> comm x z -> comm x (y + z).\nProof. by move=> x y z; rewrite /comm mulr_addl mulr_addr => -> ->. Qed.\n\nLemma commr_muln : forall x y n, comm x y -> comm x (y *+ n).\nProof.\nrewrite /comm => x y n com_xy.\nby elim: n => [|n IHn]; rewrite ?commr0 // mulrS commr_add.\nQed.\n\nLemma commr_mul : forall x y z,\n  comm x y -> comm x z -> comm x (y * z).\nProof.\nby move=> x y z com_xy; rewrite /comm mulrA com_xy -!mulrA => ->.\nQed.\n\nLemma commr_nat : forall x n, comm x n%:R.\nProof. move=> x n; apply: commr_muln; exact: commr1. Qed.\n\nLemma commr_exp : forall x y n, comm x y -> comm x (y ^+ n).\nProof.\nrewrite /comm => x y n com_xy.\nby elim: n => [|n IHn]; rewrite ?commr1 // exprS commr_mul.\nQed.\n\nLemma commr_exp_mull : forall x y n,\n  comm x y -> (x * y) ^+ n = x ^+ n * y ^+ n.\nProof.\nmove=> x y n com_xy; elim: n => /= [|n IHn]; first by rewrite mulr1.\nby rewrite !exprS IHn !mulrA; congr (_ * _); rewrite -!mulrA -commr_exp.\nQed.\n\nLemma commr_sign : forall x n, comm x ((-1) ^+ n).\nProof. move=> x n; exact: (commr_exp n (commrN1 x)). Qed.\n\nLemma exprn_mulnl : forall x m n, (x *+ m) ^+ n = x ^+ n *+ (m ^ n) :> R.\nProof.\nmove=> x m; elim=> [|n IHn]; first by rewrite mulr1n.\nrewrite exprS IHn -mulr_natr -mulrA -commr_nat mulr_natr -mulrnA -expnSr.\nby rewrite -mulr_natr mulrA -exprS mulr_natr.\nQed.\n\nLemma exprn_mulr : forall x m n, x ^+ (m * n) = x ^+ m ^+ n.\nProof.\nmove=> x m n; elim: m => [|m IHm]; first by rewrite exp1rn.\nby rewrite mulSn exprn_addr IHm exprS commr_exp_mull //; exact: commr_exp.\nQed.\n\nLemma natr_exp : forall n k, (n ^ k)%:R = n%:R ^+ k :> R.\nProof. by move=> n k; rewrite exprn_mulnl exp1rn. Qed.\n\nLemma signr_odd : forall n, (-1) ^+ (odd n) = (-1) ^+ n :> R.\nProof.\nelim=> //= n IHn; rewrite exprS -{}IHn.\nby case/odd: n; rewrite !mulN1r ?opprK.\nQed.\n\nLemma signr_eq0 :  forall n, ((-1) ^+ n == 0 :> R) = false.\nProof.\nby move=> n; rewrite -signr_odd; case: odd; rewrite ?oppr_eq0 oner_eq0.\nQed.\n\nLemma signr_addb : forall b1 b2,\n  (-1) ^+ (b1 (+) b2) = (-1) ^+ b1 * (-1) ^+ b2 :> R.\nProof. by do 2!case; rewrite ?expr1 ?mulN1r ?mul1r ?opprK. Qed.\n\nLemma exprN : forall x n, (- x) ^+ n = (-1) ^+ n * x ^+ n :> R.\nProof.\nby move=> x n; rewrite -mulN1r commr_exp_mull // /comm mulN1r mulrN mulr1.\nQed.\n\nLemma prodr_const : forall (I : finType) (A : pred I) (x : R),\n  \\prod_(i \\in A) x = x ^+ #|A|.\nProof. by move=> I A x; rewrite big_const -iteropE. Qed.\n\nLemma prodr_exp_r : forall x I r P (F : I -> nat),\n  \\prod_(i <- r | P i) x ^+ F i = x ^+ (\\sum_(i <- r | P i) F i).\nProof. by move=> x I r P F; rewrite (big_morph _ (exprn_addr _) (erefl _)). Qed.\n\nLemma prodr_opp : forall (I : finType) (A : pred I) (F : I -> R),\n  \\prod_(i \\in A) - F i = (- 1) ^+ #|A| * \\prod_(i \\in A) F i.\nProof.\nmove=> I A F; rewrite -sum1_card /= -!(big_filter _ A) !unlock.\nelim: {A}(filter _ _) => /= [|i r ->]; first by rewrite mul1r.\nby rewrite mulrA -mulN1r (commr_exp _ (commrN1 _)) exprSr !mulrA.\nQed.\n\nLemma exprn_addl_comm : forall x y n, comm x y ->\n  (x + y) ^+ n = \\sum_(i < n.+1) (x ^+ (n - i) * y ^+ i) *+ 'C(n, i).\nProof.\nmove=> x y n cxy.\nelim: n => [|n IHn]; rewrite big_ord_recl mulr1 ?big_ord0 ?addr0 //=.\nrewrite exprS {}IHn /= mulr_addl !big_distrr /= big_ord_recl mulr1 subn0.\nrewrite !big_ord_recr /= !binn !subnn !mul1r !subn0 bin0 !exprS -addrA.\ncongr (_ + _); rewrite addrA -big_split /=; congr (_ + _).\napply: eq_bigr => i _; rewrite !mulrnAr !mulrA -exprS -leq_subS ?(valP i) //.\nby rewrite  subSS (commr_exp _ (commr_sym cxy)) -mulrA -exprS -mulrn_addr.\nQed.\n\nLemma exprn_subl_comm : forall x y n, comm x y ->\n  (x - y) ^+ n =\n      \\sum_(i < n.+1) ((-1) ^+ i * x ^+ (n - i) * y ^+ i) *+ 'C(n, i).\nProof.\nmove=> x y n cxy; rewrite exprn_addl_comm; last exact: commr_opp.\nby apply: eq_bigr => i _; congr (_ *+ _); rewrite -commr_sign -mulrA -exprN.\nQed.\n\nLemma subr_expn_comm : forall x y n, comm x y ->\n  x ^+ n - y ^+ n = (x - y) * (\\sum_(i < n) x ^+ (n.-1 - i) * y ^+ i).\nProof.\nmove=> x y [|n] cxy; first by rewrite big_ord0 mulr0 subrr.\nrewrite mulr_subl !big_distrr big_ord_recl big_ord_recr /= subnn mulr1 mul1r.\nrewrite subn0 -!exprS oppr_add -!addrA; congr (_ + _); rewrite addrA -sumr_sub.\nrewrite big1 ?add0r // => i _; rewrite !mulrA -exprS -leq_subS ?(valP i) //.\nby rewrite subSS (commr_exp _ (commr_sym cxy)) -mulrA -exprS subrr.\nQed.\n\nLemma subr_expn_1 : forall x n, x ^+ n - 1 = (x - 1) * (\\sum_(i < n) x ^+ i).\nProof.\nmove=> x n; rewrite -!(oppr_sub 1) mulNr -{1}(exp1rn n).\nrewrite (subr_expn_comm _ (commr_sym (commr1 x))); congr (- (_ * _)).\nby apply: eq_bigr => i _; rewrite exp1rn mul1r.\nQed.\n\nDefinition Frobenius_aut p of p \\in [char R] := fun x => x ^+ p.\n\nSection Frobenius.\n\nVariable p : nat.\nHypothesis charFp : p \\in [char R].\n\nLemma charf0 : p%:R = 0 :> R. Proof. by apply/eqP; case/andP: charFp. Qed.\nLemma charf_prime : prime p. Proof. by case/andP: charFp. Qed.\nHint Resolve charf_prime.\n\nLemma dvdn_charf : forall n, (p %| n)%N = (n%:R == 0 :> R).\nProof.\nmove=> n; apply/idP/eqP=> [|n0].\n  by case/dvdnP=> n' ->; rewrite natr_mul charf0 mulr0.\napply/idPn; rewrite -prime_coprime //; move/eqnP=> pn1.\nhave [a _] := bezoutl n (prime_gt0 charf_prime); case/dvdnP=> b.\nmove/(congr1 (fun m => m%:R : R)); move/eqP.\nby rewrite natr_add !natr_mul charf0 n0 !mulr0 pn1 addr0 oner_eq0.\nQed.\n\nLemma charf_eq : [char R] =i (p : nat_pred).\nProof.\nmove=> q; apply/andP/eqP=> [[q_pr q0] | ->]; last by rewrite charf0.\nby apply/eqP; rewrite eq_sym -dvdn_prime2 // dvdn_charf.\nQed.\n\nLemma bin_lt_charf_0 : forall k, 0 < k < p -> 'C(p, k)%:R = 0 :> R.\nProof. by move=> k lt0kp; apply/eqP; rewrite -dvdn_charf prime_dvd_bin. Qed.\n\nLocal Notation \"x ^f\" := (Frobenius_aut charFp x).\n\nLemma Frobenius_autE : forall x, x^f = x ^+ p. Proof. by []. Qed.\nLocal Notation fE := Frobenius_autE.\n\nLemma Frobenius_aut_0 : 0^f = 0.\nProof. by rewrite fE -(prednK (prime_gt0 charf_prime)) exprS mul0r. Qed.\n\nLemma Frobenius_aut_1 : 1^f = 1.\nProof. by rewrite fE exp1rn. Qed.\n\nLemma Frobenius_aut_add_comm : forall x y, comm x y -> (x + y)^f = x^f + y^f.\nProof.\nmove=> x y cxy; have defp := prednK (prime_gt0 charf_prime).\nrewrite !fE exprn_addl_comm // big_ord_recr subnn -defp big_ord_recl /= defp.\nrewrite subn0 mulr1 mul1r bin0 binn big1 ?addr0 // => i _.\nby rewrite -mulr_natl bin_lt_charf_0 ?mul0r //= -{2}defp ltnS (valP i).\nQed.\n\nLemma Frobenius_aut_muln : forall x n, (x *+ n)^f = x^f *+ n.\nProof.\nmove=> x; elim=> [|n IHn]; first exact: Frobenius_aut_0.\nrewrite !mulrS Frobenius_aut_add_comm ?IHn //; exact: commr_muln.\nQed.\n\nLemma Frobenius_aut_nat : forall n, (n%:R)^f = n%:R.\nProof. by move=> n; rewrite Frobenius_aut_muln Frobenius_aut_1. Qed.\n\nLemma Frobenius_aut_mul_comm : forall x y, comm x y -> (x * y)^f = x^f * y^f.\nProof. by move=> x y; exact: commr_exp_mull. Qed.\n\nLemma Frobenius_aut_exp : forall x n, (x ^+ n)^f = x^f ^+ n.\nProof. by move=> x n; rewrite !fE -!exprn_mulr mulnC. Qed.\n\nLemma Frobenius_aut_opp : forall x, (- x)^f = - x^f.\nProof.\nmove=> x; apply/eqP; rewrite -subr_eq0 opprK addrC.\nby rewrite -(Frobenius_aut_add_comm (commr_opp _)) // subrr Frobenius_aut_0.\nQed.\n\nLemma Frobenius_aut_sub_comm : forall x y, comm x y -> (x - y)^f = x^f - y^f.\nProof.\nmove=> x y; move/commr_opp; move/Frobenius_aut_add_comm->.\nby rewrite Frobenius_aut_opp.\nQed.\n\nEnd Frobenius.\n\nDefinition RevRingMixin :=\n  let mul' x y := y * x in\n  let mulrA' x y z := esym (mulrA z y x) in\n  let mulr_addl' x y z := mulr_addr z x y in\n  let mulr_addr' x y z := mulr_addl y z x in\n  @Ring.Mixin R 1 mul' mulrA' mulr1 mul1r mulr_addl' mulr_addr' nonzero1r.\n\nDefinition RevRingType := Ring.Pack (Ring.Class RevRingMixin) R.\n\nEnd RingTheory.\n\nNotation comm := (@commDef _).\n\nNotation rev :=\n  (let R := _ in fun (x : Ring.sort R) => x : Ring.sort (RevRingType R)).\n\nDefinition morphism (aR rR : Ring.type) (f : aR -> rR) :=\n  [/\\ {morph f : x y / x - y}, {morph f : x y / x * y} & f 1 = 1].\n\nSection RingMorphTheory.\n\nVariables aR' aR rR : Ring.type.\nVariables (f : aR -> rR) (g : aR' -> aR).\nHypotheses (fM : morphism f) (gM : morphism g).\n\nLemma ringM_sub : {morph f : x y / x - y}.\nProof. by case fM. Qed.\n\nLemma ringM_0 : f 0 = 0.\nProof. by rewrite -(subrr 0) ringM_sub subrr. Qed.\n\nLemma ringM_1 : f 1 = 1.\nProof. by case fM. Qed.\n\nLemma ringM_opp : {morph f : x / - x}.\nProof. by move=> x /=; rewrite -[-x]add0r ringM_sub ringM_0 add0r. Qed.\n\nLemma ringM_add : {morph f : x y / x + y}.\nProof. by move=> x y /=; rewrite -(opprK y) ringM_opp ringM_sub. Qed.\n\nDefinition ringM_sum := big_morph f ringM_add ringM_0.\n\nLemma ringM_mul : {morph f : x y / x * y}.\nProof. by case fM. Qed.\n\nDefinition ringM_prod := big_morph f ringM_mul ringM_1.\n\nLemma ringM_natmul : forall n, {morph f : x / x *+ n}.\nProof. by elim=> [|n IHn] x; rewrite ?ringM_0 // !mulrS ringM_add IHn. Qed.\n\nLemma ringM_nat : forall n, f n%:R = n %:R.\nProof. by move=> n; rewrite ringM_natmul ringM_1. Qed.\n\nLemma ringM_exp : forall n, {morph f : x / x ^+ n}.\nProof. by elim=> [|n IHn] x; rewrite ?ringM_1 //  !exprS ringM_mul IHn. Qed.\n\nLemma ringM_sign : forall k, f ((- 1) ^+ k) = (- 1) ^+ k.\nProof. by move=> k; rewrite ringM_exp ringM_opp ringM_1. Qed.\n\nLemma ringM_char : forall p, p \\in [char aR] -> p \\in [char rR].\nProof.\nmove=> p; rewrite !inE -ringM_nat.\nby case/andP=> -> /=; move/eqP->; rewrite ringM_0.\nQed.\n\nLemma comp_ringM : morphism (f \\o g).\nProof.\ncase: fM gM => [fsub fmul f1] [gsub gmul g1].\nby split=> [x y | x y |] /=; rewrite ?g1 ?gsub ?gmul.\nQed.\n\nLemma ringM_isom :\n  bijective f -> exists f', [/\\ cancel f f', cancel f' f & morphism f'].\nProof.\ncase=> f' fK f'K; exists f'; split=> //.\nsplit=> [x y|x y|]; apply: (canLR fK);\n by rewrite (ringM_sub, ringM_mul, ringM_1) ?f'K.\nQed.\n\nEnd RingMorphTheory.\n\nModule ComRing.\n\nRecord class_of (R : Type) : Type :=\n  Class {base :> Ring.class_of R; _ : commutative (Ring.mul base)}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition clone T cT c of phant_id (class cT) c := @Pack T c T.\n\nDefinition pack T mul0 (m0 : @commutative T T mul0) :=\n  fun bT b & phant_id (Ring.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m) T.\n\nDefinition RingMixin R one mul mulA mulC mul1x mul_addl :=\n  let mulx1 := Monoid.mulC_id mulC mul1x in\n  let mul_addr := Monoid.mulC_dist mulC mul_addl in\n  @Ring.EtaMixin R one mul mulA mul1x mulx1 mul_addl mul_addr.\n\nCoercion eqType cT := Equality.Pack (class cT) cT.\nCoercion choiceType cT := Choice.Pack (class cT) cT.\nCoercion zmodType cT := Zmodule.Pack (class cT) cT.\nCoercion ringType cT := Ring.Pack (class cT) cT.\n\nEnd ComRing.\n\nCanonical Structure ComRing.eqType.\nCanonical Structure ComRing.choiceType.\nCanonical Structure ComRing.zmodType.\nCanonical Structure ComRing.ringType.\nBind Scope ring_scope with ComRing.sort.\n\nSection ComRingTheory.\n\nVariable R : ComRing.type.\nImplicit Types x y : R.\n\nLemma mulrC : @commutative R R *%R. Proof. by case: R => T []. Qed.\nCanonical Structure mul_comoid := Monoid.ComLaw mulrC.\nLemma mulrCA : @left_commutative R R *%R. Proof. exact: mulmCA. Qed.\nLemma mulrAC : @right_commutative R R *%R. Proof. exact: mulmAC. Qed.\n\nLemma exprn_mull : forall n, {morph (fun x => x ^+ n) : x y / x * y}.\nProof. move=> n x y; apply: commr_exp_mull; exact: mulrC. Qed.\n\nLemma prodr_exp : forall n I r (P : pred I) (F : I -> R),\n  \\prod_(i <- r | P i) F i ^+ n = (\\prod_(i <- r | P i) F i) ^+ n.\nProof.\nby move=> n I r P F; rewrite (big_morph _ (exprn_mull n) (exp1rn _ n)).\nQed.\n\nLemma exprn_addl : forall x y n,\n  (x + y) ^+ n = \\sum_(i < n.+1) (x ^+ (n - i) * y ^+ i) *+ 'C(n, i).\nProof. by move=> x y n; rewrite exprn_addl_comm //; exact: mulrC. Qed.\n\nLemma exprn_subl : forall x y n,\n  (x - y) ^+ n =\n     \\sum_(i < n.+1) ((-1) ^+ i * x ^+ (n - i) * y ^+ i) *+ 'C(n, i).\nProof. by move=> x y n; rewrite exprn_subl_comm //; exact: mulrC. Qed.\n\nLemma subr_expn : forall x y n,\n  x ^+ n - y ^+ n = (x - y) * (\\sum_(i < n) x ^+ (n.-1 - i) * y ^+ i).\nProof. by move=> x y n; rewrite -subr_expn_comm //; exact: mulrC. Qed.\n\nLemma ringM_comm : forall (rR : Ring.type) (f : R -> rR), \n  morphism f -> forall x y, comm (f x) (f y).\nProof. by move=> rR f fRM x y; red; rewrite -!ringM_mul // mulrC. Qed.\n\nLemma Frobenius_aut_RM : forall p (charRp : p \\in [char R]),\n  morphism (Frobenius_aut charRp).\nProof.\nmove=> p charRp; split=> [x y|x y|]; last exact: Frobenius_aut_1.\n  exact: Frobenius_aut_sub_comm (mulrC _ _).\nexact: Frobenius_aut_mul_comm (mulrC _ _).\nQed.\n\nEnd ComRingTheory.\n\nModule UnitRing.\n\nRecord mixin_of (R : Ring.type) : Type := Mixin {\n  unit : pred R;\n  inv : R -> R;\n  _ : {in unit, left_inverse 1 inv *%R};\n  _ : {in unit, right_inverse 1 inv *%R};\n  _ : forall x y, y * x = 1 /\\ x * y = 1 -> unit x;\n  _ : {in predC unit, inv =1 id}\n}.\n\nDefinition EtaMixin R unit inv mulVr mulrV unitP inv_out :=\n  let _ := @Mixin R unit inv mulVr mulrV unitP inv_out in\n  @Mixin (Ring.Pack (Ring.class R) R) unit inv mulVr mulrV unitP inv_out.\n\nRecord class_of (R : Type) : Type := Class {\n  base :> Ring.class_of R;\n  mixin :> mixin_of (Ring.Pack base R)\n}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition clone T cT c of phant_id (class cT) c := @Pack T c T.\n\nDefinition pack T b0 (m0 : mixin_of (@Ring.Pack T b0 T)) :=\n  fun bT b & phant_id (Ring.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m) T.\n\nCoercion eqType cT := Equality.Pack (class cT) cT.\nCoercion choiceType cT := Choice.Pack (class cT) cT.\nCoercion zmodType cT := Zmodule.Pack (class cT) cT.\nCoercion ringType cT := Ring.Pack (class cT) cT.\n\nEnd UnitRing.\n\nCanonical Structure UnitRing.eqType.\nCanonical Structure UnitRing.zmodType.\nCanonical Structure UnitRing.ringType.\nBind Scope ring_scope with UnitRing.sort.\n\nDefinition unitDef (R : UnitRing.type) : pred R :=\n  UnitRing.unit (UnitRing.class R).\nNotation unit := (@unitDef _).\nDefinition inv (R : UnitRing.type) : R -> R := UnitRing.inv (UnitRing.class R).\n\nNotation Local \"x ^-1\" := (inv x).\nNotation Local \"x / y\" := (x * y^-1).\nNotation Local \"x ^- n\" := ((x ^+ n)^-1).\n\nSection UnitRingTheory.\n\nVariable R : UnitRing.type.\nImplicit Types x y : R.\n\nLemma divrr : forall x, unit x -> x / x = 1.\nProof. by case: R => T [? []]. Qed.\nDefinition mulrV := divrr.\n\nLemma mulVr : forall x, unit x -> x^-1 * x = 1.\nProof. by case: R => T [? []]. Qed.\n\nLemma invr_out : forall x, ~~ unit x -> x^-1 = x.\nProof. by case: R => T [? []]. Qed.\n\nLemma unitrP : forall x, reflect (exists y, y * x = 1 /\\ x * y = 1) (unit x).\nProof.\nmove=> x; apply: (iffP idP) => [Ux | []]; last by case: R x => T [? []].\nby exists x^-1; rewrite divrr ?mulVr.\nQed.\n\nLemma mulKr : forall x, unit x -> cancel (mul x) (mul x^-1).\nProof. by move=> x Ux y; rewrite mulrA mulVr ?mul1r. Qed.\n\nLemma mulVKr : forall x, unit x -> cancel (mul x^-1) (mul x).\nProof. by move=> x Ux y; rewrite mulrA mulrV ?mul1r. Qed.\n\nLemma mulrK : forall x, unit x -> cancel ( *%R^~ x) ( *%R^~ x^-1).\nProof. by move=> x Ux y; rewrite -mulrA divrr ?mulr1. Qed.\n\nLemma mulrVK : forall x, unit x -> cancel ( *%R^~ x^-1) ( *%R^~ x).\nProof. by move=> x Ux y; rewrite -mulrA mulVr ?mulr1. Qed.\nDefinition divrK := mulrVK.\n\nLemma mulrI : forall x, unit x -> injective (mul x).\nProof. move=> x Ux; exact: can_inj (mulKr Ux). Qed.\n\nLemma mulIr : forall x, unit x -> injective ( *%R^~ x).\nProof. move=> x Ux; exact: can_inj (mulrK Ux). Qed.\n\nLemma commr_inv : forall x, comm x x^-1.\nProof.\nmove=> x; case Ux: (unit x); last by rewrite invr_out ?Ux.\nby rewrite /comm mulVr ?divrr.\nQed.\n\nLemma unitrE : forall x, unit x = (x / x == 1).\nProof.\nmove=> x; apply/idP/eqP=> [Ux | xx1]; first exact: divrr.\nby apply/unitrP; exists x^-1; rewrite -commr_inv.\nQed.\n\nLemma invrK : involutive (@inv R).\nProof.\nmove=> x; case Ux: (unit x); last by rewrite !invr_out ?Ux.\nrewrite -(mulrK Ux _^-1) -mulrA commr_inv mulKr //.\nby apply/unitrP; exists x; rewrite divrr ?mulVr.\nQed.\n\nLemma invr_inj : injective (@inv R).\nProof. exact: inv_inj invrK. Qed.\n\nLemma unitr_inv : forall x, unit x^-1 = unit x.\nProof. by move=> x; rewrite !unitrE invrK commr_inv. Qed.\n\nLemma unitr1 : unit (1 : R).\nProof. by apply/unitrP; exists (1 : R); rewrite mulr1. Qed.\n\nLemma invr1 : 1^-1 = 1 :> R.\nProof. by rewrite -{2}(mulVr unitr1) mulr1. Qed.\n\nLemma unitr0 : unit (0 : R) = false.\nProof.\nby apply/unitrP=> [[x [_]]]; apply/eqP; rewrite mul0r eq_sym nonzero1r.\nQed.\n\nLemma invr0 : 0^-1 = 0 :> R.\nProof. by rewrite invr_out ?unitr0. Qed.\n\nLemma unitr_opp : forall x, unit (- x) = unit x.\nProof.\nmove=> x; wlog Ux: x / unit x.\n  by move=> WHx; apply/idP/idP=> Ux; first rewrite -(opprK x); rewrite WHx.\nby rewrite Ux; apply/unitrP; exists (- x^-1); rewrite !mulrNN mulVr ?divrr.\nQed.\n\nLemma invrN : forall x, (- x)^-1 = - x^-1.\nProof.\nmove=> x; case Ux: (unit x) (unitr_opp x) => [] Unx.\n  by apply: (mulrI Unx); rewrite mulrNN !divrr.\nby rewrite !invr_out ?Ux ?Unx.\nQed.\n\nLemma unitr_mull : forall x y, unit y -> unit (x * y) = unit x.\nProof.\nmove=> x y Uy; wlog Ux: x y Uy / unit x => [WHxy|].\n  by apply/idP/idP=> Ux; first rewrite -(mulrK Uy x); rewrite WHxy ?unitr_inv.\nrewrite Ux; apply/unitrP; exists (y^-1 * x^-1).\nby rewrite -!mulrA mulKr ?mulrA ?mulrK ?divrr ?mulVr.\nQed.\n\nLemma unitr_mulr : forall x y, unit x -> unit (x * y) = unit y.\nProof.\nmove=> x y Ux; apply/idP/idP=> [Uxy | Uy]; last by rewrite unitr_mull.\nby rewrite -(mulKr Ux y) unitr_mull ?unitr_inv.\nQed.\n\nLemma invr_mul : forall x y, unit x -> unit y -> (x * y)^-1 = y^-1 * x^-1.\nProof.\nmove=> x y Ux Uy; have Uxy: unit (x * y) by rewrite unitr_mull.\nby apply: (mulrI Uxy); rewrite divrr ?mulrA ?mulrK ?divrr.\nQed.\n\nLemma commr_unit_mul : forall x y, comm x y -> unit (x * y) = unit x && unit y.\nProof.\nmove=> x y cxy; apply/idP/andP=> [Uxy | [Ux Uy]]; last by rewrite unitr_mull.\nsuffices Ux: unit x by rewrite unitr_mulr in Uxy.\napply/unitrP; case/unitrP: Uxy => z [zxy xyz]; exists (y * z).\nrewrite mulrA xyz -{1}[y]mul1r -{1}zxy cxy -!mulrA (mulrA x) (mulrA _ z) xyz.\nby rewrite mul1r -cxy.\nQed.\n\nLemma unitr_exp : forall x n, unit x -> unit (x ^+ n).\nProof.\nby move=> x n Ux; elim: n => [|n IHn]; rewrite ?unitr1 // exprS unitr_mull.\nQed.\n\nLemma unitr_pexp : forall x n, n > 0 -> unit (x ^+ n) = unit x.\nProof.\nmove=> x [//|n] _; rewrite exprS commr_unit_mul; last exact: commr_exp.\nby case Ux: (unit x); rewrite // unitr_exp.\nQed.\n\nLemma expr_inv : forall x n, x^-1 ^+ n = x ^- n.\nProof.\nmove=> x; elim=> [|n IHn]; first by rewrite !expr0 ?invr1.\ncase Ux: (unit x); first by rewrite exprSr exprS IHn -invr_mul // unitr_exp.\nby rewrite !invr_out ?unitr_pexp ?Ux.\nQed.\n\nLemma invr_neq0 : forall x, x != 0 -> x^-1 != 0.\nProof.\nmove=> x nx0; case Ux: (unit x); last by rewrite invr_out ?Ux.\nby apply/eqP=> x'0; rewrite -unitr_inv x'0 unitr0 in Ux.\nQed.\n\nLemma invr_eq0 : forall x, (x^-1 == 0) = (x == 0).\nProof.\nby move=> x; apply: negb_inj; apply/idP/idP; move/invr_neq0; rewrite ?invrK.\nQed.\n\nEnd UnitRingTheory.\n\nSection UnitRingMorphism.\n\nVariables (aR rR : UnitRing.type) (f : aR -> rR).\nHypothesis fM : morphism f.\n\nLemma ringM_unit : forall x, unit x -> unit (f x).\nProof.\nmove=> x; case/unitrP=> y [yx1 xy1]; apply/unitrP.\nby exists (f y); rewrite -!ringM_mul // yx1 xy1 ringM_1.\nQed.\n\nLemma ringM_inv : forall x, unit x -> f x^-1 = (f x)^-1.\nProof.\nmove=> x Ux; rewrite -[(f x)^-1]mul1r; apply: (canRL (mulrK (ringM_unit Ux))).\nby rewrite -ringM_mul // mulVr ?ringM_1.\nQed.\n\nLemma ringM_div : forall x y, unit y -> f (x / y) = f x / f y.\nProof. by move=> x y Uy; rewrite ringM_mul ?ringM_inv. Qed.\n\nEnd UnitRingMorphism.\n\n(* Reification of the theory of rings with units, in named style  *)\nSection TermDef.\n\nVariable R : Type.\n\nInductive term : Type :=\n| Var of nat\n| Const of R\n| NatConst of nat\n| Add of term & term\n| Opp of term\n| NatMul of term & nat\n| Mul of term & term\n| Inv of term\n| Exp of term & nat.\n\nInductive formula : Type :=\n| Bool of bool\n| Equal of term & term\n| Unit of term\n| And of formula & formula\n| Or of formula & formula\n| Implies of formula & formula\n| Not of formula\n| Exists of nat & formula\n| Forall of nat & formula.\n\nEnd TermDef.\n\nBind Scope term_scope with term.\nBind Scope term_scope with formula.\nArguments Scope Add [_ term_scope term_scope].\nArguments Scope Opp [_ term_scope].\nArguments Scope NatMul [_ term_scope nat_scope].\nArguments Scope Mul [_ term_scope term_scope].\nArguments Scope Mul [_ term_scope term_scope].\nArguments Scope Inv [_ term_scope].\nArguments Scope Exp [_ term_scope nat_scope].\nArguments Scope Equal [_ term_scope term_scope].\nArguments Scope Unit [_ term_scope].\nArguments Scope And [_ term_scope term_scope].\nArguments Scope Or [_ term_scope term_scope].\nArguments Scope Implies [_ term_scope term_scope].\nArguments Scope Not [_ term_scope].\nArguments Scope Exists [_ nat_scope term_scope].\nArguments Scope Forall [_ nat_scope term_scope].\n\nImplicit Arguments Bool [R].\nPrenex Implicits Const Add Opp NatMul Mul Exp Bool Unit And Or Implies Not.\nPrenex Implicits Exists Forall.\n\nNotation True := (Bool true).\nNotation False := (Bool false).\n\nLocal Notation \"''X_' i\" := (Var _ i) : term_scope.\nLocal Notation \"n %:R\" := (NatConst _ n) : term_scope.\nLocal Notation \"x %:T\" := (Const x) : term_scope.\nLocal Notation \"0\" := 0%:R%T : term_scope.\nLocal Notation \"1\" := 1%:R%T : term_scope.\nLocal Infix \"+\" := Add : term_scope.\nLocal Notation \"- t\" := (Opp t) : term_scope.\nLocal Notation \"t - u\" := (Add t (- u)) : term_scope.\nLocal Infix \"*\" := Mul : term_scope.\nLocal Infix \"*+\" := NatMul : term_scope.\nLocal Notation \"t ^-1\" := (Inv t) : term_scope.\nLocal Notation \"t / u\" := (Mul t u^-1) : term_scope.\nLocal Infix \"^+\" := Exp : term_scope.\nLocal Infix \"==\" := Equal : term_scope.\nLocal Infix \"/\\\" := And : term_scope.\nLocal Infix \"\\/\" := Or : term_scope.\nLocal Infix \"==>\" := Implies : term_scope.\nLocal Notation \"~ f\" := (Not f) : term_scope.\nLocal Notation \"x != y\" := (Not (x == y)) : term_scope.\nLocal Notation \"''exists' ''X_' i , f\" := (Exists i f) : term_scope.\nLocal Notation \"''forall' ''X_' i , f\" := (Forall i f) : term_scope.\n\nSection Substitution.\n\nVariable R : Type.\n\nFixpoint tsubst (t : term R) (s : nat * term R) :=\n  match t with\n  | 'X_i => if i == s.1 then s.2 else t\n  | _%:T | _%:R => t\n  | t1 + t2 => tsubst t1 s + tsubst t2 s\n  | - t1 => - tsubst t1 s\n  | t1 *+ n => tsubst t1 s *+ n\n  | t1 * t2 => tsubst t1 s * tsubst t2 s\n  | t1^-1 => (tsubst t1 s)^-1\n  | t1 ^+ n => tsubst t1 s ^+ n\n  end%T.\n\nFixpoint fsubst (f : formula R) (s : nat * term R) :=\n  match f with\n  | Bool _ => f\n  | t1 == t2 => tsubst t1 s == tsubst t2 s\n  | Unit t1 => Unit (tsubst t1 s)\n  | f1 /\\ f2 => fsubst f1 s /\\ fsubst f2 s\n  | f1 \\/ f2 => fsubst f1 s \\/ fsubst f2 s\n  | f1 ==> f2 => fsubst f1 s ==> fsubst f2 s\n  | ~ f1 => ~ fsubst f1 s\n  | ('exists 'X_i, f1) => 'exists 'X_i, if i == s.1 then f1 else fsubst f1 s\n  | ('forall 'X_i, f1) => 'forall 'X_i, if i == s.1 then f1 else fsubst f1 s\n  end%T.\n\nEnd Substitution.\n\nSection EvalTerm.\n\nVariable R : UnitRing.type.\n\n(* Evaluation of a reified term into R a ring with units *)\nFixpoint eval (e : seq R) (t : term R) {struct t} : R :=\n  match t with\n  | ('X_i)%T => e`_i\n  | (x%:T)%T => x\n  | (n%:R)%T => n%:R\n  | (t1 + t2)%T => eval e t1 + eval e t2\n  | (- t1)%T => - eval e t1\n  | (t1 *+ n)%T => eval e t1 *+ n\n  | (t1 * t2)%T => eval e t1 * eval e t2\n  | t1^-1%T => (eval e t1)^-1\n  | (t1 ^+ n)%T => eval e t1 ^+ n\n  end.\n\nDefinition same_env (e e' : seq R) := nth 0 e =1 nth 0 e'.\n\nLemma eq_eval : forall e e' t, same_env e e' -> eval e t = eval e' t.\nProof. by move=> e e' t eq_e; elim: t => //= t1 -> // t2 ->. Qed.\n\nLemma eval_tsubst : forall e t s,\n  eval e (tsubst t s) = eval (set_nth 0 e s.1 (eval e s.2)) t.\nProof.\nmove=> e t [i u]; elim: t => //=; do 2?[move=> ? -> //] => j.\nby rewrite nth_set_nth /=; case: (_ == _).\nQed.\n\n(* Evaluation of a reified formula *)\nFixpoint holds (e : seq R) (f : formula R) {struct f} : Prop :=\n  match f with\n  | Bool b => b\n  | (t1 == t2)%T => eval e t1 = eval e t2\n  | Unit t1 => unit (eval e t1)\n  | (f1 /\\ f2)%T => holds e f1 /\\ holds e f2\n  | (f1 \\/ f2)%T => holds e f1 \\/ holds e f2\n  | (f1 ==> f2)%T => holds e f1 -> holds e f2\n  | (~ f1)%T => ~ holds e f1\n  | ('exists 'X_i, f1)%T => exists x, holds (set_nth 0 e i x) f1\n  | ('forall 'X_i, f1)%T => forall x, holds (set_nth 0 e i x) f1\n  end.\n\nLemma same_env_sym : forall e e', same_env e e' -> same_env e' e.\nProof. by move=> e e'; exact: fsym. Qed.\n\n(* Extensionality of formula evaluation *)\nLemma eq_holds : forall e e' f, same_env e e' -> holds e f -> holds e' f.\nProof.\npose sv := set_nth (0 : R).\nhave eq_i: forall i v e e', same_env e e' -> same_env (sv e i v) (sv e' i v).\n  by move=> i v /= e e' eq_e j; rewrite !nth_set_nth /= eq_e.\nmove=> e e' t; elim: t e e' => //=.\n- by move=> t1 t2 e e' eq_e; rewrite !(eq_eval _ eq_e).\n- by move=> t e e' eq_e; rewrite (eq_eval _ eq_e).\n- by move=> f1 IH1 f2 IH2 e e' eq_e; move/IH2: (eq_e); move/IH1: eq_e; tauto.\n- by move=> f1 IH1 f2 IH2 e e' eq_e; move/IH2: (eq_e); move/IH1: eq_e; tauto.\n- by move=> f1 IH1 f2 IH2 e e' eq_e f12; move/IH1: (same_env_sym eq_e); eauto.\n- by move=> f1 IH1 e e'; move/same_env_sym; move/IH1; tauto.\n- by move=> i f1 IH1 e e'; move/(eq_i i)=> eq_e [x f_ex]; exists x; eauto.\nby move=> i f1 IH1 e e'; move/(eq_i i); eauto.\nQed.\n\n(* Evaluation and substitution by a constant *)\nLemma holds_fsubst : forall e f i v,\n  holds e (fsubst f (i, v%:T)%T) <-> holds (set_nth 0 e i v) f.\nProof.\nmove=> e f i v; elim: f e => //=; do [\n  by move=> *; rewrite !eval_tsubst\n| move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto\n| move=> f IHf e; move: (IHf e); tauto\n| move=> j f IHf e].\n- case eq_ji: (j == i); first rewrite (eqP eq_ji).\n    by split=> [] [x f_x]; exists x; rewrite set_set_nth eqxx in f_x *.\n  split=> [] [x f_x]; exists x; move: f_x; rewrite set_set_nth eq_sym eq_ji;\n     have:= IHf (set_nth 0 e j x); tauto.\ncase eq_ji: (j == i); first rewrite (eqP eq_ji).\n  by split=> [] f_ x; move: (f_ x); rewrite set_set_nth eqxx.\nsplit=> [] f_ x; move: (f_ x); rewrite set_set_nth eq_sym eq_ji;\n     have:= IHf (set_nth 0 e j x); tauto.\nQed.\n\n(* Boolean test selecting terms in the language of rings *)\nFixpoint rterm (t : term R) :=\n  match t with\n  | _^-1 => false\n  | t1 + t2 | t1 * t2 => rterm t1 && rterm t2\n  | - t1 | t1 *+ _ | t1 ^+ _ => rterm t1\n  | _ => true\n  end%T.\n\n(* Boolean test selecting formulas in the theory of rings *)\nFixpoint rformula (f : formula R) :=\n  match f with\n  | Bool _ => true\n  | t1 == t2 => rterm t1 && rterm t2\n  | Unit t1 => false\n  | f1 /\\ f2 | f1 \\/ f2 | f1 ==> f2 => rformula f1 && rformula f2\n  | ~ f1 | ('exists 'X__, f1) | ('forall 'X__, f1) => rformula f1\n  end%T.\n\n(* Upper bound of the names used in a term *)\nFixpoint ub_var (t : term R) :=\n  match t with\n  | 'X_i => i.+1\n  | t1 + t2 | t1 * t2 => maxn (ub_var t1) (ub_var t2)\n  | - t1 | t1 *+ _ | t1 ^+ _ | t1^-1 => ub_var t1\n  | _ => 0%N\n  end%T.\n\n(* Replaces inverses in the term t by fresh variables, accumulating the *)\n(* substitution. *)\nFixpoint to_rterm (t : term R) (r : seq (term R)) (n : nat) {struct t} :=\n  match t with\n  | t1^-1 =>\n    let: (t1', r1) := to_rterm t1 r n in\n      ('X_(n + size r1), rcons r1 t1')\n  | t1 + t2 =>\n    let: (t1', r1) := to_rterm t1 r n in\n    let: (t2', r2) := to_rterm t2 r1 n in\n      (t1' + t2', r2)\n  | - t1 =>\n   let: (t1', r1) := to_rterm t1 r n in\n     (- t1', r1)\n  | t1 *+ m =>\n   let: (t1', r1) := to_rterm t1 r n in\n     (t1' *+ m, r1)\n  | t1 * t2 =>\n    let: (t1', r1) := to_rterm t1 r n in\n    let: (t2', r2) := to_rterm t2 r1 n in\n      (Mul t1' t2', r2)\n  | t1 ^+ m =>\n       let: (t1', r1) := to_rterm t1 r n in\n     (t1' ^+ m, r1)\n  | _ => (t, r)\n  end%T.\n\nLemma to_rterm_id : forall t r n, rterm t -> to_rterm t r n = (t, r).\nProof.\nelim=> //.\n- by move=> t1 IHt1 t2 IHt2 r n /=; case/andP=> rt1 rt2; rewrite {}IHt1 // IHt2.\n- by move=> t IHt r n /= rt; rewrite {}IHt.\n- by move=> t IHt r n m /= rt; rewrite {}IHt.\n- by move=> t1 IHt1 t2 IHt2 r n /=; case/andP=> rt1 rt2; rewrite {}IHt1 // IHt2.\n- by move=> t IHt r n m /= rt; rewrite {}IHt.\nQed.\n\n(* A ring formula stating that t1 is equal to 0 in the ring theory. *)\n(* Also applies to non commutative rings.                           *)\nDefinition eq0_rform t1 :=\n  let m := ub_var t1 in\n  let: (t1', r1) := to_rterm t1 [::] m in\n  let fix loop r i := match r with\n  | [::] => t1' == 0\n  | t :: r' =>\n    let f := 'X_i * t == 1 /\\ t * 'X_i == 1 in\n     'forall 'X_i, (f \\/ 'X_i == t /\\ ~ ('exists 'X_i,  f)) ==> loop r' i.+1\n  end%T\n  in loop r1 m.\n\n(* Transformation of a formula in the theory of rings with units into an *)\n(* equivalent formula in the sub-theory of rings.                        *)\nFixpoint to_rform f :=\n  match f with\n  | Bool b => f\n  | t1 == t2 => eq0_rform (t1 - t2)\n  | Unit t1 => eq0_rform (t1 * t1^-1 - 1)\n  | f1 /\\ f2 => to_rform f1 /\\ to_rform f2\n  | f1 \\/ f2 =>  to_rform f1 \\/ to_rform f2\n  | f1 ==> f2 => to_rform f1 ==> to_rform f2\n  | ~ f1 => ~ to_rform f1\n  | ('exists 'X_i, f1) => 'exists 'X_i, to_rform f1\n  | ('forall 'X_i, f1) => 'forall 'X_i, to_rform f1\n  end%T.\n\n(* The transformation gives a ring formula. *)\nLemma to_rform_rformula : forall f, rformula (to_rform f).\nProof.\nsuffices eq0_ring : rformula (eq0_rform _) by elim=> //= => f1 ->.\nmove=> t1; rewrite /eq0_rform; move: (ub_var t1) => m; set tr := _ m.\nsuffices: all rterm (tr.1 :: tr.2).\n  case: tr => {t1} t1 r /=; case/andP=> t1_r.\n  elim: r m => [| t r IHr] m; rewrite /= ?andbT //.\n  case/andP=> ->; exact: IHr.\nhave: all rterm [::] by [].\nrewrite {}/tr; elim: t1 [::] => //=.\n- move=> t1 IHt1 t2 IHt2 r.\n  move/IHt1; case: to_rterm=> {t1 r IHt1} t1 r /=; case/andP=> t1_r.\n  move/IHt2; case: to_rterm=> {t2 r IHt2} t2 r /=; case/andP=> t2_r.\n  by rewrite t1_r t2_r.\n- by move=> t1 IHt1 r; move/IHt1; case: to_rterm.\n- by move=> t1 IHt1 n r; move/IHt1; case: to_rterm.\n- move=> t1 IHt1 t2 IHt2 r.\n  move/IHt1; case: to_rterm=> {t1 r IHt1} t1 r /=; case/andP=> t1_r.\n  move/IHt2; case: to_rterm=> {t2 r IHt2} t2 r /=; case/andP=> t2_r.\n  by rewrite t1_r t2_r.\n- move=> t1 IHt1 r.\n  by move/IHt1; case: to_rterm => {t1 r IHt1} t1 r /=; rewrite all_rcons.\n- by move=> t1 IHt1 n r; move/IHt1; case: to_rterm.\nQed.\n\n(* Correctness of the transformation. *)\nLemma to_rformP : forall e f, holds e (to_rform f) <-> holds e f.\nProof.\nsuffices equal0_equiv : forall e t1 t2,\n  holds e (eq0_rform (t1 - t2)) <-> (eval e t1 == eval e t2).\n- move=> e f; elim: f e => /=; try tauto.\n  + move => t1 t2 e.\n    by split; [move/equal0_equiv; move/eqP | move/eqP; move/equal0_equiv].\n  + move=> t1 e; rewrite unitrE; exact: equal0_equiv.\n  + move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto.\n  + move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto.\n  + move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto.\n  + move=> f1 IHf1 e; move: (IHf1 e); tauto.\n  + by move=> n f1 IHf1 e; split=> [] [x]; move/IHf1; exists x.\n  + by move=> n f1 IHf1 e; split=> Hx x; apply/IHf1.\nmove=> e t1 t2; rewrite -(add0r (eval e t2)) -(can2_eq (subrK _) (addrK _)).\nrewrite -/(eval e (t1 - t2)); move: (t1 - t2)%T => {t1 t2} t.\nhave sub_var_tsubst: forall s t, s.1 >= ub_var t -> tsubst t s = t.\n  move=> s; elim=> //=.\n  - by move=> n; case: ltngtP.\n  - move=> t1 IHt1 t2 IHt2; rewrite leq_maxl.\n    by case/andP; move/IHt1->; move/IHt2->.\n  - by move=> t1 IHt1; move/IHt1->.\n  - by move=> t1 IHt1 n; move/IHt1->.\n  - move=> t1 IHt1 t2 IHt2; rewrite leq_maxl.\n    by case/andP; move/IHt1->; move/IHt2->.\n  - by move=> t1 IHt1; move/IHt1->.\n  - by move=> t1 IHt1 n; move/IHt1->.\npose fix rsub t' m r : term R :=\n  if r is u :: r' then tsubst (rsub t' m.+1 r') (m, u^-1)%T else t'.\npose fix ub_sub m r : Prop :=\n  if r is u :: r' then ub_var u <= m /\\ ub_sub m.+1 r' else true.\nsuffices rsub_to_r: forall t0 r0 m, m >= ub_var t0 -> ub_sub m r0 ->\n  let: (t', r) := to_rterm t0 r0 m in\n  [/\\ take (size r0) r = r0,\n      ub_var t' <= m + size r, ub_sub m r & rsub t' m r = t0].\n- have:= rsub_to_r t [::] _ (leqnn _).\n  rewrite /eq0_rform.\n  case: (to_rterm _ _ _) => [t1' r1] [//|_ _ ub_r1 def_t].\n  rewrite -{2}def_t {def_t}.\n  elim: r1 (ub_var t) e ub_r1 => [|u r1 IHr1] m e /= => [_|[ub_u ub_r1]].\n    by split; move/eqP.\n  rewrite eval_tsubst /=; set y := eval e u; split=> t_eq0.\n    apply/IHr1=> //; apply: t_eq0.\n    rewrite nth_set_nth /= eqxx -(eval_tsubst e u (m, Const _)).\n    rewrite sub_var_tsubst //= -/y.\n    case Uy: (unit y); [left | right]; first by rewrite mulVr ?divrr.\n    split; first by rewrite invr_out ?Uy.\n    case=> z; rewrite nth_set_nth /= eqxx.\n    rewrite -!(eval_tsubst _ _ (m, Const _)) !sub_var_tsubst // -/y => yz1.\n    by case/unitrP: Uy; exists z.\n  move=> x def_x; apply/IHr1=> //; suff ->: x = y^-1 by []; move: def_x.\n  rewrite nth_set_nth /= eqxx -(eval_tsubst e u (m, Const _)).\n  rewrite sub_var_tsubst //= -/y; case=> [[xy1 yx1] | [xy nUy]].\n    by rewrite -[y^-1]mul1r -[1]xy1 mulrK //; apply/unitrP; exists x.\n  rewrite invr_out //; apply/unitrP=> [[z yz1]]; case: nUy; exists z.\n  rewrite nth_set_nth /= eqxx -!(eval_tsubst _ _ (m, _%:T)%T).\n  by rewrite !sub_var_tsubst.\nhave rsub_id : forall r t n, ub_var t <= n -> rsub t n r = t.\n  by elim=> //= t0 r IHr t1 n hn; rewrite IHr ?sub_var_tsubst ?leqW.\nhave rsub_acc : forall r s t1 m,\n  ub_var t1 <= m + size r -> rsub t1 m (r ++ s) = rsub t1 m r.\n  elim=> [|t1 r IHr] s t2 m /=; first by rewrite addn0; apply: rsub_id.\n  by move=> hleq; rewrite IHr // addSnnS.\nelim=> /=; try do [\n  by move=> n r m hlt hub; rewrite take_size (ltn_addr _ hlt) rsub_id\n| by move=> n r m hlt hub; rewrite leq0n take_size rsub_id\n| move=> t1 IHt1 t2 IHt2 r m; rewrite leq_maxl; case/andP=> hub1 hub2 hmr;\n  case: to_rterm {IHt1 hub1 hmr}(IHt1 r m hub1 hmr) => t1' r1;\n  case=> htake1 hub1' hsub1 <-;\n  case: to_rterm {IHt2 hub2 hsub1}(IHt2 r1 m hub2 hsub1) => t2' r2 /=;\n  rewrite leq_maxl; case=> htake2 -> hsub2 /= <-;\n  rewrite -{1 2}(cat_take_drop (size r1) r2) htake2; set r3 := drop _ _;\n  rewrite size_cat addnA (leq_trans _ (leq_addr _ _)) //;\n  split=> {hsub2}//;\n   first by [rewrite takel_cat // -htake1 size_take leq_minl leqnn orbT];\n  rewrite -(rsub_acc r1 r3 t1') {hub1'}// -{htake1}htake2 {r3}cat_take_drop;\n  by elim: r2 m => //= u r2 IHr2 m; rewrite IHr2\n| do [ move=> t1 IHt1 r m; do 2!move/IHt1=> {IHt1}IHt1\n     | move=> t1 IHt1 n r m; do 2!move/IHt1=> {IHt1}IHt1];\n  case: to_rterm IHt1 => t1' r1 [-> -> hsub1 <-]; split=> {hsub1}//;\n  by elim: r1 m => //= u r1 IHr1 m; rewrite IHr1].\nmove=> t1 IHt1 r m; do 2!move/IHt1=> {IHt1}IHt1.\ncase: to_rterm IHt1 => t1' r1 /= [def_r ub_t1' ub_r1 <-].\nrewrite size_rcons addnS leqnn -{1}cats1 takel_cat ?def_r; last first.\n  by rewrite -def_r size_take leq_minl leqnn orbT.\nelim: r1 m ub_r1 ub_t1' {def_r} => /= [|u r1 IHr1] m => [_|[->]].\n  by rewrite addn0 eqxx.\nby rewrite -addSnnS; move/IHr1=> IH; case/IH=> _ _ ub_r1 ->.\nQed.\n\n(* Boolean test selecting formulas which describe a constructable set, *)\n(* i.e. formulas without quantifiers.                                  *)\n\n(* The quantifier elimination check. *)\nFixpoint qf_form (f : formula R) :=\n  match f with\n  | Bool _ | _ == _ | Unit _ => true\n  | f1 /\\ f2 | f1 \\/ f2 | f1 ==> f2 => qf_form f1 && qf_form f2\n  | ~ f1 => qf_form f1\n  | _ => false\n  end%T.\n\n(* Boolean holds predicate for quantifier free formulas *)\nDefinition qf_eval e := fix loop (f : formula R) : bool :=\n  match f with\n  | Bool b => b\n  | t1 == t2 => (eval e t1 == eval e t2)%bool\n  | Unit t1 => unit (eval e t1)\n  | f1 /\\ f2 => loop f1 && loop f2\n  | f1 \\/ f2 => loop f1 || loop f2\n  | f1 ==> f2 => (loop f1 ==> loop f2)%bool\n  | ~ f1 => ~~ loop f1\n  |_ => false\n  end%T.\n\n(* qf_eval is equivalent to holds *)\nLemma qf_evalP : forall e f, qf_form f -> reflect (holds e f) (qf_eval e f).\nProof.\nmove=> e; elim=> //=; try by move=> *; exact: idP.\n- move=> t1 t2 _; exact: eqP.\n- move=> f1 IHf1 f2 IHf2 /=; case/andP; case/IHf1=> f1T; last by right; case.\n  by case/IHf2; [left | right; case].\n- move=> f1 IHf1 f2 IHf2 /=; case/andP; case/IHf1=> f1F; first by do 2 left.\n  by case/IHf2; [left; right | right; case].\n- move=> f1 IHf1 f2 IHf2 /=; case/andP; case/IHf1=> f1T; last by left.\n  by case/IHf2; [left | right; move/(_ f1T)].\nby move=> f1 IHf1; case/IHf1; [right | left].\nQed.\n\nImplicit Type bc : seq (term R) * seq (term R).\n\n(* Quantifier-free formula are normalized into DNF. A DNF is *)\n(* represented by the type seq (seq (term R) * seq (term R)), where we *)\n(* separate positive and negative literals *)\n\n(* DNF preserving conjunction *)\nDefinition and_dnf bcs1 bcs2 :=\n  \\big[cat/nil]_(bc1 <- bcs1)\n     map (fun bc2 => (bc1.1 ++ bc2.1, bc1.2 ++ bc2.2)) bcs2.\n\n(* Computes a DNF from a qf ring formula *)\nFixpoint qf_to_dnf (f : formula R) (neg : bool) {struct f} :=\n  match f with\n  | Bool b => if b (+) neg then [:: ([::], [::])] else [::]\n  | t1 == t2 => [:: if neg then ([::], [:: t1 - t2]) else ([:: t1 - t2], [::])]\n  | f1 /\\ f2 => (if neg then cat else and_dnf) [rec f1, neg] [rec f2, neg]\n  | f1 \\/ f2 => (if neg then and_dnf else cat) [rec f1, neg] [rec f2, neg]\n  | f1 ==> f2 => (if neg then and_dnf else cat) [rec f1, ~~ neg] [rec f2, neg]\n  | ~ f1 => [rec f1, ~~ neg]\n  | _ =>  if neg then [:: ([::], [::])] else [::]\n  end%T where \"[ 'rec' f , neg ]\" := (qf_to_dnf f neg).\n\n(* Conversely, transforms a DNF into a formula *)\nDefinition dnf_to_form :=\n  let pos_lit t := And (t == 0) in let neg_lit t := And (t != 0) in \n  let cls bc := Or (foldr pos_lit True bc.1 /\\ foldr neg_lit True bc.2) in\n  foldr cls False.\n\n(* Catenation of dnf is the Or of formulas *)\nLemma cat_dnfP : forall e bcs1 bcs2,\n  qf_eval e (dnf_to_form (bcs1 ++ bcs2))\n    = qf_eval e (dnf_to_form bcs1 \\/ dnf_to_form bcs2).\nProof.\nmove=> e.\nby elim=> //= bc1 bcs1 IH1 bcs2; rewrite -orbA; congr orb; rewrite IH1.\nQed.\n\n(* and_dnf is the And of formulas *)\nLemma and_dnfP : forall e bcs1 bcs2,\n  qf_eval e (dnf_to_form (and_dnf bcs1 bcs2))\n   = qf_eval e (dnf_to_form bcs1 /\\ dnf_to_form bcs2).\nProof.\nmove=> e; elim=> [|bc1 bcs1 IH1] bcs2 /=; first by rewrite /and_dnf big_nil.\nrewrite /and_dnf big_cons -/(and_dnf bcs1 bcs2) cat_dnfP  /=.\nrewrite {}IH1 /= andb_orl; congr orb.\nelim: bcs2 bc1 {bcs1} => [| bc2 bcs2 IH] bc1 /=; first by rewrite andbF.\nrewrite {}IH /= andb_orr; congr orb => {bcs2}.\nsuffices aux: forall (l1 l2 : seq (term R)) g (redg := foldr (And \\o g) True),\n  qf_eval e (redg (l1 ++ l2)) = qf_eval e (redg l1 /\\ redg l2)%T.\n+ by rewrite 2!aux /= 2!andbA -andbA -andbCA andbA andbCA andbA.\nby elim=> [| ? ? IHl1] * //=; rewrite -andbA IHl1.\nQed.\n\nLemma qf_to_dnfP : forall e,\n  let qev f b := qf_eval e (dnf_to_form (qf_to_dnf f b)) in\n  forall f, qf_form f && rformula f -> qev f false = qf_eval e f.\nProof.\nmove=> e qev; have qevT: forall f, qev f true = ~~ qev f false.\n  rewrite {}/qev; elim=> //=; do [by case | move=> f1 IH1 f2 IH2 | ].\n  - by move=> t1 t2; rewrite !andbT !orbF.\n  - by rewrite and_dnfP cat_dnfP negb_and -IH1 -IH2.\n  - by rewrite and_dnfP cat_dnfP negb_or -IH1 -IH2.\n  - by rewrite and_dnfP cat_dnfP /= negb_or IH1 -IH2 negbK.\n  by move=> t1 ->; rewrite negbK.\nrewrite /qev; elim=> //=; first by case.\n- by move=> t1 t2 _; rewrite subr_eq0 !andbT orbF.\n- move=> f1 IH1 f2 IH2; rewrite andbCA -andbA andbCA andbA; case/andP.\n  by rewrite and_dnfP /=; move/IH1->; move/IH2->.\n- move=> f1 IH1 f2 IH2; rewrite andbCA -andbA andbCA andbA; case/andP.\n  by rewrite cat_dnfP /=; move/IH1->; move/IH2->.\n- move=> f1 IH1 f2 IH2; rewrite andbCA -andbA andbCA andbA; case/andP.\n  by rewrite cat_dnfP /= [qf_eval _ _]qevT -implybE; move/IH1 <-; move/IH2->.\nby move=> f1 IH1; move/IH1 <-; rewrite -qevT.\nQed.\n\nLemma dnf_to_form_qf : forall bcs, qf_form (dnf_to_form bcs).\nProof. by elim=> //= [[clT clF] _ ->] /=; elim: clT => //=; elim: clF. Qed.\n\nDefinition dnf_rterm cl := all rterm cl.1 && all rterm cl.2.\n\nLemma qf_to_dnf_rterm : forall f b, rformula f -> all dnf_rterm (qf_to_dnf f b).\nProof.\nset ok := all dnf_rterm.\nhave cat_ok: forall bcs1 bcs2, ok bcs1 -> ok bcs2 -> ok (bcs1 ++ bcs2).\n  by move=> bcs1 bcs2 ok1 ok2; rewrite [ok _]all_cat; exact/andP.\nhave and_ok: forall bcs1 bcs2, ok bcs1 -> ok bcs2 -> ok (and_dnf bcs1 bcs2).\n  rewrite /and_dnf unlock; elim=> //= cl1 bcs1 IH1 bcs2; rewrite -andbA.\n  case/and3P=> ok11 ok12 ok1 ok2; rewrite cat_ok ?{}IH1 {bcs1 ok1}//.\n  elim: bcs2 ok2 => //= cl2 bcs2 IH2; case/andP=> ok2; move/IH2->.\n  by rewrite /dnf_rterm !all_cat ok11 ok12 /= !andbT.\nelim=> //=; try by [move=> _ ? ? [] | move=> ? ? ? ? [] /=; case/andP; auto].\n- by do 2!case.\n- by rewrite /dnf_rterm => ? ? [] /= ->.\nby auto.\nQed.\n\nLemma dnf_to_rform : forall bcs, rformula (dnf_to_form bcs) = all dnf_rterm bcs.\nProof.\nelim=> //= [[cl1 cl2] bcs ->]; rewrite {2}/dnf_rterm /=; congr (_ && _).\nby congr andb; [elim: cl1 | elim: cl2] => //= t cl ->; rewrite andbT.\nQed.\n\nSection Pick.\n\nVariables (I : finType) (pred_f then_f : I -> formula R) (else_f : formula R).\n\nDefinition Pick :=\n  \\big[Or/False]_(p : {ffun pred I})\n    ((\\big[And/True]_i (if p i then pred_f i else ~ pred_f i))\n    /\\ (if pick p is Some i then then_f i else else_f))%T.\n\nLemma Pick_form_qf :\n   (forall i, qf_form (pred_f i)) ->\n   (forall i, qf_form (then_f i)) ->\n    qf_form else_f ->\n  qf_form Pick.\nProof.\nmove=> qfp qft qfe; have mA := @big_morph _ _ _ true _ andb qf_form.\nrewrite mA // big1 //= => p _.\nrewrite mA // big1 => [|i _]; first by case: pick.\nby rewrite fun_if if_same /= qfp.\nQed.\n\nLemma eval_Pick : forall e (qev := qf_eval e),\n  let P i := qev (pred_f i) in\n  qev Pick = (if pick P is Some i then qev (then_f i) else qev else_f).\nProof.\nmove=> e qev P; rewrite (@big_morph _ _ _ false _ orb qev) //= big_orE /=.\napply/existsP/idP=> [[p] | true_at_P].\n  rewrite (@big_morph _ _ _ true _ andb qev) //= big_andE /=.\n  case/andP; move/forallP=> eq_p_P.\n  rewrite (@eq_pick _ _ P) => [|i]; first by case: pick.\n  by move/(_ i): eq_p_P => /=; case: (p i) => //=; move/negbTE.\nexists [ffun i => P i] => /=; apply/andP; split.\n  rewrite (@big_morph _ _ _ true _ andb qev) //= big_andE /=.\n  by apply/forallP=> i; rewrite /= ffunE; case Pi: (P i) => //=; apply: negbT.\nrewrite (@eq_pick _ _ P) => [|i]; first by case: pick true_at_P.\nby rewrite ffunE.\nQed.\n\nEnd Pick.\n\nSection MultiQuant.\n\nVariable f : formula R.\nImplicit Type I : seq nat.\nImplicit Type e : seq R.\n\nLemma foldExistsP : forall I e,\n  (exists2 e', {in [predC I], same_env e e'} & holds e' f)\n    <-> holds e (foldr Exists f I).\nProof.\nelim=> /= [|i I IHi] e.\n  by split=> [[e' eq_e] |]; [apply: eq_holds => i; rewrite eq_e | exists e].\nsplit=> [[e' eq_e f_e'] | [x]]; last set e_x := set_nth 0 e i x.\n  exists e'`_i; apply/IHi; exists e' => // j.\n  by have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP => // ->.\ncase/IHi=> e' eq_e f_e'; exists e' => // j.\nby have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP.\nQed.\n\nLemma foldForallP : forall I e,\n  (forall e', {in [predC I], same_env e e'} -> holds e' f)\n    <-> holds e (foldr Forall f I).\nProof.\nelim=> /= [|i I IHi] e.\n  by split=> [|f_e e' eq_e]; [exact | apply: eq_holds f_e => i; rewrite eq_e].\nsplit=> [f_e' x | f_e e' eq_e]; first set e_x := set_nth 0 e i x.\n  apply/IHi=> e' eq_e; apply: f_e' => j.\n  by have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP.\nmove/IHi: (f_e e'`_i); apply=> j.\nby have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP => // ->.\nQed.\n\nEnd MultiQuant.\n\nEnd EvalTerm.\n\nPrenex Implicits dnf_rterm.\n\nModule ComUnitRing.\n\nRecord class_of (R : Type) : Type := Class {\n  base1 :> ComRing.class_of R;\n  ext :> UnitRing.mixin_of (Ring.Pack base1 R)\n}.\n\nCoercion base2 R m := UnitRing.Class (@ext R m).\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\n\nSection Mixin.\n\nVariables (R : ComRing.type) (unit : pred R) (inv : R -> R).\nHypothesis mulVx : {in unit, left_inverse 1 inv *%R}.\nHypothesis unitPl : forall x y, y * x = 1 -> unit x.\n\nLemma mulC_mulrV : {in unit, right_inverse 1 inv *%R}.\nProof. by move=> x Ux /=; rewrite mulrC mulVx. Qed.\n\nLemma mulC_unitP : forall x y, y * x = 1 /\\ x * y = 1 -> unit x.\nProof. move=> x y [yx _]; exact: unitPl yx. Qed.\n\nDefinition Mixin := UnitRing.EtaMixin mulVx mulC_mulrV mulC_unitP.\n\nEnd Mixin.\n\nDefinition pack T :=\n  fun bT b & phant_id (ComRing.class bT) (b : ComRing.class_of T) =>\n  fun mT m & phant_id (UnitRing.class mT) (@UnitRing.Class T b m) =>\n  Pack (@Class T b m) T.\n\nCoercion eqType cT := Equality.Pack (class cT) cT.\nCoercion choiceType cT := Choice.Pack (class cT) cT.\nCoercion zmodType cT := Zmodule.Pack (class cT) cT.\nCoercion ringType cT := Ring.Pack (class cT) cT.\nCoercion comRingType cT := ComRing.Pack (class cT) cT.\nCoercion unitRingType cT := UnitRing.Pack (class cT) cT.\nDefinition com_unitRingType cT :=\n  @UnitRing.Pack (comRingType cT) (class cT) cT.\n\nEnd ComUnitRing.\n\nCanonical Structure ComUnitRing.eqType.\nCanonical Structure ComUnitRing.choiceType.\nCanonical Structure ComUnitRing.zmodType.\nCanonical Structure ComUnitRing.ringType.\nCanonical Structure ComUnitRing.unitRingType.\nCanonical Structure ComUnitRing.comRingType.\nBind Scope ring_scope with ComUnitRing.sort.\n\nSection ComUnitRingTheory.\n\nVariable R : ComUnitRing.type.\nImplicit Types x y : R.\n\nLemma unitr_mul : forall x y, unit (x * y) = unit x && unit y.\nProof. move=> x y; apply: commr_unit_mul; exact: mulrC. Qed.\n\nEnd ComUnitRingTheory.\n\nModule IntegralDomain.\n\nDefinition axiom (R : Ring.type) :=\n  forall x y : R, x * y = 0 -> (x == 0) || (y == 0).\n\nRecord class_of (R : Type) : Type :=\n  Class {base :> ComUnitRing.class_of R; ext : axiom (Ring.Pack base R)}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition clone T cT c of phant_id (class cT) c := @Pack T c T.\n\nDefinition pack T b0 (m0 : axiom (@Ring.Pack T b0 T)) :=\n  fun bT b & phant_id (ComUnitRing.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m) T.\n\nCoercion eqType cT := Equality.Pack (class cT) cT.\nCoercion choiceType cT := Choice.Pack (class cT) cT.\nCoercion zmodType cT := Zmodule.Pack (class cT) cT.\nCoercion ringType cT := Ring.Pack (class cT) cT.\nCoercion comRingType cT := ComRing.Pack (class cT) cT.\nCoercion unitRingType cT := UnitRing.Pack (class cT) cT.\nCoercion comUnitRingType cT := ComUnitRing.Pack (class cT) cT.\n\nEnd IntegralDomain.\n\nCanonical Structure IntegralDomain.eqType.\nCanonical Structure IntegralDomain.choiceType.\nCanonical Structure IntegralDomain.zmodType.\nCanonical Structure IntegralDomain.ringType.\nCanonical Structure IntegralDomain.unitRingType.\nCanonical Structure IntegralDomain.comRingType.\nCanonical Structure IntegralDomain.comUnitRingType.\nBind Scope ring_scope with IntegralDomain.sort.\n\nSection IntegralDomainTheory.\n\nVariable R : IntegralDomain.type.\nImplicit Types x y : R.\n\nLemma mulf_eq0 : forall x y, (x * y == 0) = (x == 0) || (y == 0).\nProof.\nmove=> x y; apply/eqP/idP; first by case: R x y => T [].\nby case/pred2P=> ->; rewrite (mulr0, mul0r).\nQed.\n\nLemma mulf_neq0 : forall x y, x != 0 -> y != 0 -> x * y != 0.\nProof. move=> x y x0 y0; rewrite mulf_eq0; exact/norP. Qed.\n\nLemma expf_eq0 : forall x n, (x ^+ n == 0) = (n > 0) && (x == 0).\nProof.\nmove=> x; elim=> [|n IHn]; first by rewrite oner_eq0.\nby rewrite exprS mulf_eq0 IHn andKb.\nQed.\n\nLemma expf_neq0 : forall x m, x != 0 -> x ^+ m != 0.\nProof. by move=> x n x_nz; rewrite expf_eq0; apply/nandP; right. Qed.\n\nLemma mulfI : forall x, x != 0 -> injective ( *%R x).\nProof.\nmove=> x nz_x y z; rewrite -[x * z]add0r; move/(canLR (addrK _)).\nmove/eqP; rewrite -mulrN -mulr_addr mulf_eq0 (negbTE nz_x) /=; move/eqP.\nby move/(canRL (subrK _)); rewrite add0r.\nQed.\n\nLemma mulIf : forall x, x != 0 -> injective ( *%R^~ x).\nProof. move=> x nz_x y z; rewrite -!(mulrC x); exact: mulfI. Qed.\n\nEnd IntegralDomainTheory.\n\nModule Field.\n\nDefinition mixin_of (F : UnitRing.type) := forall x : F, x != 0 -> unit x.\n\nRecord class_of (F : Type) : Type := Class {\n  base :> IntegralDomain.class_of F;\n  ext: mixin_of (UnitRing.Pack base F)\n}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition clone T cT c of phant_id (class cT) c := @Pack T c T.\n\nDefinition pack T b0 (m0 : mixin_of (@UnitRing.Pack T b0 T)) :=\n  fun bT b & phant_id (IntegralDomain.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m) T.\n\nLemma IdomainMixin : forall R, mixin_of R -> IntegralDomain.axiom R.\nProof.\nmove=> R m x y xy0; apply/norP=> [[]]; move/m=> Ux; move/m.\nby rewrite -(unitr_mulr _ Ux) xy0 unitr0.\nQed.\n\nSection Mixins.\n\nVariables (R : ComRing.type) (inv : R -> R).\n\nDefinition axiom := forall x, x != 0 -> inv x * x = 1.\nHypothesis mulVx : axiom.\nHypothesis inv0 : inv 0 = 0.\n\nLemma intro_unit : forall x y : R, y * x = 1 -> x != 0.\nProof.\nmove=> x y yx1; apply: contra (nonzero1r R); move/eqP=> x0.\nby rewrite -yx1 x0 mulr0.\nQed.\n\nLemma inv_out : {in predC (predC1 0), inv =1 id}.\nProof. by move=> x; move/negbNE; move/eqP->. Qed.\n\nDefinition UnitMixin := ComUnitRing.Mixin mulVx intro_unit inv_out.\n\nLemma Mixin : mixin_of (UnitRing.Pack (UnitRing.Class UnitMixin) R).\nProof. by []. Qed.\n\nEnd Mixins.\n\nCoercion eqType cT := Equality.Pack (class cT) cT.\nCoercion choiceType cT := Choice.Pack (class cT) cT.\nCoercion zmodType cT := Zmodule.Pack (class cT) cT.\nCoercion ringType cT := Ring.Pack (class cT) cT.\nCoercion comRingType cT := ComRing.Pack (class cT) cT.\nCoercion unitRingType cT := UnitRing.Pack (class cT) cT.\nCoercion comUnitRingType cT := ComUnitRing.Pack (class cT) cT.\nCoercion idomainType cT := IntegralDomain.Pack (class cT) cT.\n\nEnd Field.\n\nCanonical Structure Field.eqType.\nCanonical Structure Field.choiceType.\nCanonical Structure Field.zmodType.\nCanonical Structure Field.ringType.\nCanonical Structure Field.unitRingType.\nCanonical Structure Field.comRingType.\nCanonical Structure Field.comUnitRingType.\nCanonical Structure Field.idomainType.\nBind Scope ring_scope with Field.sort.\n\nSection FieldTheory.\n\nVariable F : Field.type.\nImplicit Types x y : F.\n\nLemma unitfE : forall x, unit x = (x != 0).\nProof.\nmove=> x; apply/idP/idP=> [Ux |]; last by case: F x => T [].\nby apply/eqP=> x0; rewrite x0 unitr0 in Ux.\nQed.\n\nLemma mulVf : forall x, x != 0 -> x^-1 * x = 1.\nProof. by move=> x; rewrite -unitfE; exact: mulVr. Qed.\nLemma divff : forall x, x != 0 -> x / x = 1.\nProof. by move=> x; rewrite -unitfE; exact: divrr. Qed.\nDefinition mulfV := divff.\nLemma mulKf : forall x, x != 0 -> cancel ( *%R x) ( *%R x^-1).\nProof. by move=> x; rewrite -unitfE; exact: mulKr. Qed.\nLemma mulVKf : forall x, x != 0 -> cancel ( *%R x^-1) ( *%R x).\nProof. by move=> x; rewrite -unitfE; exact: mulVKr. Qed.\nLemma mulfK : forall x, x != 0 -> cancel ( *%R^~ x) ( *%R^~ x^-1).\nProof. by move=> x; rewrite -unitfE; exact: mulrK. Qed.\nLemma mulfVK : forall x, x != 0 -> cancel ( *%R^~ x^-1) ( *%R^~ x).\nProof. by move=> x; rewrite -unitfE; exact: divrK. Qed.\nDefinition divfK := mulfVK.\n\nLemma invf_mul : {morph (fun x => x^-1) : x y / x * y}.\nProof.\nmove=> x y; case: (eqVneq x 0) => [-> |nzx]; first by rewrite !(mul0r, invr0).\ncase: (eqVneq y 0) => [-> |nzy]; first by rewrite !(mulr0, invr0).\nby rewrite mulrC invr_mul ?unitfE.\nQed.\n\nLemma prodf_inv : forall I r (P : pred I) (E : I -> F),\n  \\prod_(i <- r | P i) (E i)^-1 = (\\prod_(i <- r | P i) E i)^-1.\nProof. by move=> I r P E; rewrite (big_morph _ invf_mul (invr1 _)). Qed.\n\nLemma natf0_char : forall n,\n  n > 0 -> n%:R == 0 :> F -> exists p, p \\in [char F].\nProof.\nmove=> n; elim: {n}_.+1 {-2}n (ltnSn n) => // m IHm n; rewrite ltnS => le_n_m.\nrewrite leq_eqVlt -pi_pdiv mem_primes; move: (pdiv n) => p.\ncase/predU1P=> [<-|]; [by rewrite oner_eq0 | case/and3P=> p_pr n_gt0].\ncase/dvdnP=> n' def_n; rewrite def_n muln_gt0 andbC prime_gt0 // in n_gt0 *.\nrewrite natr_mul mulf_eq0 orbC; case/orP; first by exists p; exact/andP.\nby apply: IHm (leq_trans _ le_n_m) _; rewrite // def_n ltn_Pmulr // prime_gt1.\nQed.\n\nLemma charf'_nat : forall n, [char F]^'.-nat n = (n%:R != 0 :> F).\nProof.\nmove=> n; case: (posnP n) => [-> | n_gt0]; first by rewrite eqxx.\napply/idP/idP => [|nz_n]; last first.\n  by apply/pnatP=> // p p_pr p_dvd_n; apply: contra nz_n; move/dvdn_charf <-.\napply: contraL => n0; have [// | p charFp] := natf0_char _ n0.\nhave [p_pr _] := andP charFp; rewrite (eq_pnat _ (eq_negn (charf_eq charFp))).\nby rewrite p'natE // (dvdn_charf charFp) n0.\nQed.\n\nLemma charf0P : [char F] =i pred0 <-> (forall n, (n%:R == 0 :> F) = (n == 0)%N).\nProof.\nsplit=> charF0 n; last by rewrite !inE charF0 andbC; case: eqP => // ->.\ncase: posnP => [-> | n_gt0]; first exact: eqxx.\nby apply/negP; case/natf0_char=> // p; rewrite charF0.\nQed.\n\nSection FieldMorphismInj.\n\nVariables (R : Ring.type) (f : F -> R).\nHypothesis fRM : morphism f.\n\nLemma fieldM_eq0 : forall x, (f x == 0) = (x == 0).\nProof.\nmove=> x; case: (eqVneq x 0) => [-> | nz_x]; first by rewrite ringM_0 ?eqxx.\nrewrite (negbTE nz_x); apply/eqP; move/(congr1 ( *%R (f x^-1))); move/eqP.\nby rewrite -ringM_mul // mulVf // mulr0 ringM_1 ?oner_eq0.\nQed.\n\nLemma fieldM_inj : injective f.\nProof.\nmove=> x y eqfxy; apply/eqP; rewrite -subr_eq0 -fieldM_eq0 ringM_sub //.\nby rewrite eqfxy subrr.\nQed.\n\nLemma fieldM_char : [char R] =i [char F].\nProof. by move=> p; rewrite !inE -fieldM_eq0 ringM_nat. Qed.\n\nEnd FieldMorphismInj.\n\nSection FieldMorphismInv.\n\nVariables (R : UnitRing.type) (f : F -> R).\nHypothesis fRM : morphism f.\n\nLemma fieldM_unit : forall x, unit (f x) = (x != 0).\nProof.\nmove=> x; case: eqP => [-> |]; first by rewrite ringM_0 ?unitr0.\nby move/eqP; rewrite -unitfE; exact: ringM_unit.\nQed.\n\nLemma fieldM_inv : {morph f: x / x^-1}.\nProof.\nmove=> x; case (eqVneq x 0) => [-> | nzx]; last by rewrite ringM_inv ?unitfE.\nby rewrite !(invr0, ringM_0 fRM).\nQed.\n\nLemma fieldM_div : {morph f : x y / x / y}.\nProof. by move=> x y; rewrite ringM_mul ?fieldM_inv. Qed.\n\nEnd FieldMorphismInv.\n\nEnd FieldTheory.\n\nModule DecidableField.\n\nDefinition axiom (R : UnitRing.type) (s : seq R -> pred (formula R)) :=\n  forall e f, reflect (holds e f) (s e f).\n\nRecord mixin_of (R : UnitRing.type) : Type :=\n  Mixin { sat : seq R -> pred (formula R); satP : axiom sat}.\n\nRecord class_of (F : Type) : Type :=\n  Class {base :> Field.class_of F; mixin:> mixin_of (UnitRing.Pack base F)}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition clone T cT c of phant_id (class cT) c := @Pack T c T.\n\nDefinition pack T b0 (m0 : mixin_of (@UnitRing.Pack T b0 T)) :=\n  fun bT b & phant_id (Field.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m) T.\n\n(* Ultimately, there should be a QE Mixin constructor *)\n\nCoercion eqType cT := Equality.Pack (class cT) cT.\nCoercion choiceType cT := Choice.Pack (class cT) cT.\nCoercion zmodType cT := Zmodule.Pack (class cT) cT.\nCoercion ringType cT := Ring.Pack (class cT) cT.\nCoercion comRingType cT := ComRing.Pack (class cT) cT.\nCoercion unitRingType cT := UnitRing.Pack (class cT) cT.\nCoercion comUnitRingType cT := ComUnitRing.Pack (class cT) cT.\nCoercion idomainType cT := IntegralDomain.Pack (class cT) cT.\nCoercion fieldType cT := Field.Pack (class cT) cT.\n\nEnd DecidableField.\n\nCanonical Structure DecidableField.eqType.\nCanonical Structure DecidableField.choiceType.\nCanonical Structure DecidableField.zmodType.\nCanonical Structure DecidableField.ringType.\nCanonical Structure DecidableField.unitRingType.\nCanonical Structure DecidableField.comRingType.\nCanonical Structure DecidableField.comUnitRingType.\nCanonical Structure DecidableField.idomainType.\nCanonical Structure DecidableField.fieldType.\nBind Scope ring_scope with DecidableField.sort.\n\nSection DecidableFieldTheory.\n\nVariable F : DecidableField.type.\n\nDefinition sat := DecidableField.sat (DecidableField.class F).\n\nLemma satP : DecidableField.axiom sat.\nProof. exact: DecidableField.satP. Qed.\n\nLemma sol_subproof : forall n f,\n  reflect (exists s, (size s == n) && sat s f)\n          (sat [::] (foldr Exists f (iota 0 n))).\nProof.\nmove=> n f; apply: (iffP (satP _ _)) => [|[s]]; last first.\n  case/andP; move/eqP=> sz_s; move/satP=> f_s; apply/foldExistsP.\n  exists s => // i; rewrite !inE mem_iota -leqNgt add0n => le_n_i.\n  by rewrite !nth_default ?sz_s.\ncase/foldExistsP=> e e0 f_e; set s := take n (set_nth 0 e n 0).\nhave sz_s: size s = n by rewrite size_take size_set_nth leq_maxr leqnn.\nexists s; rewrite sz_s eqxx; apply/satP; apply: eq_holds f_e => i.\ncase: (leqP n i) => [le_n_i | lt_i_n].\n  by rewrite -e0 ?nth_default ?sz_s // !inE mem_iota -leqNgt.\nby rewrite nth_take // nth_set_nth /= eq_sym eqn_leq leqNgt lt_i_n.\nQed.\n\nDefinition sol n f :=\n  if sol_subproof n f is ReflectT sP then xchoose sP else nseq n 0.\n\nLemma size_sol : forall n f, size (sol n f) = n.\nProof.\nrewrite /sol => n f; case: sol_subproof => [sP | _]; last exact: size_nseq.\nby case/andP: (xchooseP sP); move/eqP.\nQed.\n\nLemma solP : forall n f,\n  reflect (exists2 s, size s = n & holds s f) (sat (sol n f) f).\nProof.\nrewrite /sol => n f; case: sol_subproof => [sP | sPn].\n  case/andP: (xchooseP sP) => _ ->; left.\n  by case: sP => s; case/andP; move/eqP=> <-; move/satP; exists s.\napply: (iffP (satP _ _)); first by exists (nseq n 0); rewrite ?size_nseq.\nby case=> s sz_s; move/satP=> f_s; case: sPn; exists s; rewrite sz_s eqxx.\nQed.\n\nLemma eq_sat : forall f1 f2,\n  (forall e, holds e f1 <-> holds e f2) -> sat^~ f1 =1 sat^~ f2.\nProof. by move=> f1 f2 eqf12 e; apply/satP/satP; case: (eqf12 e). Qed.\n\nLemma eq_sol : forall f1 f2,\n  (forall e, holds e f1 <-> holds e f2) -> sol^~ f1 =1 sol^~ f2.\nProof.\nrewrite /sol => f1 f2; move/eq_sat=> eqf12 n.\ndo 2![case: sol_subproof] => //= [f1s f2s | ns1 [s f2s] | [s f1s] []].\n- by apply: eq_xchoose => s; rewrite eqf12.\n- by case: ns1; exists s; rewrite -eqf12.\nby exists s; rewrite eqf12.\nQed.\n\nEnd DecidableFieldTheory.\n\nImplicit Arguments satP [F e f].\nImplicit Arguments solP [F n f].\n\n(* Structure of field with quantifier elimination *)\nModule QE.\n\nSection Axioms.\n\nVariable R : UnitRing.type.\nVariable proj : nat -> seq (term R) * seq (term R) -> formula R.\n(* proj is the elimination of a single existential quantifier *)\n\nDefinition wf_proj_axiom :=\n  forall i bc (bc_i := proj i bc), \n    dnf_rterm bc -> qf_form bc_i && rformula bc_i : Prop.\n\n(* The elimination operator p preserves  validity *)\nDefinition holds_proj_axiom :=\n  forall i bc (ex_i_bc := ('exists 'X_i, dnf_to_form [:: bc])%T) e,\n  dnf_rterm bc -> reflect (holds e ex_i_bc) (qf_eval e (proj i bc)).\n\nEnd Axioms.\n\nRecord mixin_of (R : UnitRing.type) : Type := Mixin {\n  proj : nat -> (seq (term R) * seq (term R)) -> formula R;\n  wf_proj : wf_proj_axiom proj;\n  holds_proj : holds_proj_axiom proj\n}.\n\nRecord class_of (F : Type) : Type :=\n  Class {base :> Field.class_of F; mixin:> mixin_of (UnitRing.Pack base F)}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition clone T cT c of phant_id (class cT) c := @Pack T c T.\n\nDefinition pack T b0 (m0 : mixin_of (@UnitRing.Pack T b0 T)) :=\n  fun bT b & phant_id (Field.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m) T.\n\nCoercion eqType cT := Equality.Pack (class cT) cT.\nCoercion choiceType cT := Choice.Pack (class cT) cT.\nCoercion zmodType cT := Zmodule.Pack (class cT) cT.\nCoercion ringType cT := Ring.Pack (class cT) cT.\nCoercion comRingType cT := ComRing.Pack (class cT) cT.\nCoercion unitRingType cT := UnitRing.Pack (class cT) cT.\nCoercion comUnitRingType cT := ComUnitRing.Pack (class cT) cT.\nCoercion idomainType cT := IntegralDomain.Pack (class cT) cT.\nCoercion fieldType cT := Field.Pack (class cT) cT.\n\nEnd QE.\n\nCanonical Structure QE.eqType.\nCanonical Structure QE.choiceType.\nCanonical Structure QE.zmodType.\nCanonical Structure QE.ringType.\nCanonical Structure QE.unitRingType.\nCanonical Structure QE.comRingType.\nCanonical Structure QE.comUnitRingType.\nCanonical Structure QE.idomainType.\nCanonical Structure QE.fieldType.\nBind Scope ring_scope with QE.sort.\n\nSection QE_theory.\n\nVariable F : QE.type.\n\nDefinition proj := QE.proj (QE.class F).\n\nLemma wf_proj : QE.wf_proj_axiom proj.\nProof. exact: QE.wf_proj. Qed.\n\nLemma holds_proj : QE.holds_proj_axiom proj.\nProof. exact: QE.holds_proj. Qed.\n\nImplicit Type f : formula F.\n\nLet elim_aux f n := foldr Or False (map (proj n) (qf_to_dnf f false)).\n\nFixpoint quantifier_elim (f : formula F) : formula F :=\n  match f with\n  | f1 /\\ f2 => (quantifier_elim f1) /\\ (quantifier_elim f2)\n  | f1 \\/ f2 => (quantifier_elim f1) \\/ (quantifier_elim f2)\n  | f1 ==> f2 => (~ quantifier_elim f1) \\/ (quantifier_elim f2)\n  | ~ f => ~ quantifier_elim f\n  | ('exists 'X_n, f) => elim_aux (quantifier_elim f) n\n  | ('forall 'X_n, f) => ~ elim_aux (~ quantifier_elim f) n\n  | _ => f\n  end%T.\n\nLemma quantifier_elim_wf : forall f (qf := quantifier_elim f),\n  rformula f -> qf_form qf && rformula qf.\nProof.\nsuffices aux_wf: forall f n (qf := elim_aux f n), \n     rformula f -> qf_form qf && rformula qf.\n  by elim=> //=; do ?[  move=> f1 IH1 f2 IH2;\n                     case/andP=> rf1 rf2;\n                     case/andP:(IH1 rf1)=> -> ->;\n                     case/andP:(IH2 rf2)=> -> -> //\n                  |  move=> n f1 IH rf1;\n                     case/andP: (IH rf1)=> qff rf;\n                     rewrite aux_wf ].\nrewrite /elim_aux => f n rf.\nsuff or_wf: forall fs (ofs := foldr Or False fs), \n  all (@qf_form F) fs && all (@rformula F) fs \n  -> qf_form ofs && rformula ofs.\n  apply: or_wf.\n  suff map_proj_wf: forall bcs (mbcs := map (proj n) bcs),\n    all dnf_rterm bcs \n    -> all (@qf_form _) mbcs && all (@rformula _) mbcs.\n    apply: map_proj_wf.\n    exact: qf_to_dnf_rterm.\n  elim=> [|bc bcs ihb] bcsr //=.\n  by case/andP=> rbc rbcs; rewrite andbAC andbA wf_proj //= andbC ihb.\nelim=> //= g gs ihg; rewrite -andbA; case/and4P=> -> qgs -> rgs /=.\nby apply: ihg; rewrite qgs rgs.\nQed.\n\nLemma quantifier_elim_rformP : forall e f,\n  rformula f -> reflect (holds e f) (qf_eval e (quantifier_elim f)).\nProof.\npose rc e n f := exists x, qf_eval (set_nth 0 e n x) f.\nhave auxP: forall f e n, qf_form f && rformula f ->\n  reflect (rc e n f) (qf_eval e (elim_aux f n)).\n+ rewrite /elim_aux => f e n cf; set bcs := qf_to_dnf f false.\n  apply: (@iffP (rc e n (dnf_to_form bcs))); last first.\n  - by case=> x; rewrite -qf_to_dnfP //; exists x.\n  - by case=> x; rewrite qf_to_dnfP //; exists x.\n  have: all dnf_rterm bcs by case/andP: cf => _; exact: qf_to_dnf_rterm.\n  elim: {f cf}bcs => [|bc bcs IHbcs] /=; first by right; case.\n  case/andP=> r_bc; move/IHbcs=> {IHbcs}bcsP.\n  have f_qf := dnf_to_form_qf [:: bc].\n  case: holds_proj => //= [ex_x|no_x].\n    left; case: ex_x => x; move/(qf_evalP _ f_qf); rewrite /= orbF => bc_x.\n    by exists x; rewrite /= bc_x.\n  apply: (iffP bcsP) => [[x bcs_x] | [x]] /=.\n    by exists x; rewrite /= bcs_x orbT.\n  case/orP => [bc_x|]; last by exists x.\n  by case: no_x; exists x; apply/(qf_evalP _ f_qf); rewrite /= bc_x.\nmove=> e f; elim: f e => //.\n- move=> b e _; exact: idP.\n- move=> t1 t2 e _; exact: eqP.\n- move=> f1 IH1 f2 IH2 e /=; case/andP; case/IH1=> f1e; last by right; case.\n  by case/IH2; [left | right; case].\n- move=> f1 IH1 f2 IH2 e /=; case/andP; case/IH1=> f1e; first by do 2!left.\n  by case/IH2; [left; right | right; case].\n- move=> f1 IH1 f2 IH2 e /=; case/andP; case/IH1=> f1e; last by left.\n  by case/IH2; [left | right; move/(_ f1e)].\n- by move=> f IHf e /=; case/IHf; [right | left].\n- move=> n f IHf e /= rf; have rqf := quantifier_elim_wf rf.\n  by apply: (iffP (auxP _ _ _ rqf)) => [] [x]; exists x; exact/IHf.\nmove=> n f IHf e /= rf; have rqf := quantifier_elim_wf rf.\ncase: auxP => // [f_x|no_x]; first by right=> no_x; case: f_x => x; case/IHf.\nby left=> x; apply/IHf=> //; apply/idPn=> f_x; case: no_x; exists x.\nQed.\n\nDefinition proj_sat e f := qf_eval e (quantifier_elim (to_rform f)).\n\nLemma proj_satP : DecidableField.axiom proj_sat.\nProof.\nmove=> e f; have fP := quantifier_elim_rformP e (to_rform_rformula f).\nby apply: (iffP fP); move/to_rformP.\nQed.\n\nDefinition QEDecidableFieldMixin := DecidableField.Mixin proj_satP.\n\nCanonical Structure QEDecidableField :=\n  DecidableField.Pack (DecidableField.Class QEDecidableFieldMixin) F.\n\nEnd QE_theory.\n\nModule ClosedField.\n\n(* Axiom == all non-constant monic polynomials have a root *)\nDefinition axiom (R : Ring.type) :=\n  forall n (P : nat -> R), n > 0 ->\n   exists x : R, x ^+ n = \\sum_(i < n) P i * (x ^+ i).\n\nRecord class_of (F : Type) : Type :=\n  Class {base :> DecidableField.class_of F; _ : axiom (Ring.Pack base F)}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition clone T cT c of phant_id (class cT) c := @Pack T c T.\n\nDefinition pack T b0 (m0 : axiom (@Ring.Pack T b0 T)) :=\n  fun bT b & phant_id (DecidableField.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m) T.\n\n(* There should eventually be a constructor from polynomial resolution *)\n(* that builds the DecidableField mixin using QE.                      *)\n\nCoercion eqType cT := Equality.Pack (class cT) cT.\nCoercion choiceType cT := Choice.Pack (class cT) cT.\nCoercion zmodType cT := Zmodule.Pack (class cT) cT.\nCoercion ringType cT := Ring.Pack (class cT) cT.\nCoercion comRingType cT := ComRing.Pack (class cT) cT.\nCoercion unitRingType cT := UnitRing.Pack (class cT) cT.\nCoercion comUnitRingType cT := ComUnitRing.Pack (class cT) cT.\nCoercion idomainType cT := IntegralDomain.Pack (class cT) cT.\nCoercion fieldType cT := Field.Pack (class cT) cT.\nCoercion decFieldType cT := DecidableField.Pack (class cT) cT.\n\nEnd ClosedField.\n\nCanonical Structure ClosedField.eqType.\nCanonical Structure ClosedField.choiceType.\nCanonical Structure ClosedField.zmodType.\nCanonical Structure ClosedField.ringType.\nCanonical Structure ClosedField.unitRingType.\nCanonical Structure ClosedField.comRingType.\nCanonical Structure ClosedField.comUnitRingType.\nCanonical Structure ClosedField.idomainType.\nCanonical Structure ClosedField.fieldType.\nCanonical Structure ClosedField.decFieldType.\n\nBind Scope ring_scope with ClosedField.sort.\n\nSection ClosedFieldTheory.\n\nVariable F : ClosedField.type.\n\nLemma solve_monicpoly : ClosedField.axiom F.\nProof. by case: F => ? []. Qed.\n\nEnd ClosedFieldTheory.\n\nModule Lmodule.\n\nSection Lmodule.\n\nVariable R : Ring.type.\nImplicit Type phR : phant R.\n\nStructure mixin_of (M : Zmodule.type) : Type := Mixin {\n  scale : R -> M -> M;\n  _ : forall a b m,  scale a (scale b m) = scale (a * b) m;\n  _ : left_id 1 scale;\n  _ : forall a, {morph scale a : m n / m + n};\n  _ : forall m, {morph scale^~ m : a b / a + b}\n}.\n\nStructure class_of M := Class {\n  base :> Zmodule.class_of M;\n  ext :> mixin_of (Zmodule.Pack base M)\n}.\n\nStructure type phR := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class phR (cT : type phR) :=\n  let: Pack _ c _ :=  cT return class_of cT in c.\nDefinition clone phR T cT c of phant_id (@class phR cT) c := @Pack phR T c T.\nDefinition pack phR T b0 (m0 : mixin_of (@Zmodule.Pack T b0 T)) :=\n  fun bT b & phant_id (Zmodule.class bT) b =>\n  fun    m & phant_id m0 m => Pack phR (@Class T b m) T.\n\nCoercion eqType phR cT := Equality.Pack (@class phR cT) cT.\nCoercion choiceType phR cT := Choice.Pack (@class phR cT) cT.\nCoercion zmodType phR cT := Zmodule.Pack (@class phR cT) cT.\n\nEnd Lmodule.\n\nEnd Lmodule.\n\nCanonical Structure Lmodule.eqType.\nCanonical Structure Lmodule.choiceType.\nCanonical Structure Lmodule.zmodType.\nBind Scope ring_scope with Lmodule.sort.\n\nDefinition scale R (M : @Lmodule.type R (Phant R)) : R -> M -> M := \n  Lmodule.scale (Lmodule.class M).\n\nLocal Notation \"*:%R\" := (@scale _ _) : ring_scope.\nLocal Notation \"a *: m\" := (scale a m) (at level 40) : ring_scope.\n\nSection LmoduleTheory.\n\nVariable (R : Ring.type) (M : Lmodule.type (Phant R)).\nImplicit Type a b c : R.\nImplicit Type m : M.\n\nLemma scalerA : forall a b m, a *: (b *: m) = a * b *: m.\nProof. by case: M => ? [] ? []. Qed.\n\nLemma scale1r : @left_id R M 1 *:%R.\nProof. by case: M => ? [] ? []. Qed.\n\nLemma scaler_addr : forall a, {morph (scale a : M -> M) : x y / x + y}.\nProof. by case: M => ? [] ? []. Qed.\n\nLemma scaler_addl : forall m, {morph (@scale _ _)^~ m : a b / a + b}.\nProof. by case: M => ? [] ? []. Qed.\n\nLemma scale0r : forall m, 0 *: m = 0.\nProof. by move=> m; apply: (@addIr _ (1 *:m)); rewrite -scaler_addl !add0r. Qed.\n\nLemma scaler0 : forall a, a *: 0 = 0 :> M.\nProof. by move=> a; rewrite -{1}(scale0r 0) scalerA mulr0 scale0r. Qed.\n\nLemma scaleNr : forall a m, - a *: m = - (a *: m).\nProof.\nby move=> a m; apply: (@addIr _ (a *: m)); rewrite -scaler_addl !addNr scale0r.\nQed.\n\nLemma scaleN1r : forall m, (- 1) *: m = - m.\nProof. by move=> m; rewrite scaleNr scale1r. Qed.\n\nLemma scalerN : forall a m, a *: (- m) = - (a *: m).\nProof.\nby move=> a v; apply: (@addIr _ (a *: v)); rewrite -scaler_addr !addNr scaler0.\nQed.\n\nLemma scaler_subl : forall a b m, (a - b) *: m = a *: m - b *: m.\nProof. by move=> a b m; rewrite scaler_addl scaleNr. Qed.\n\nLemma scaler_subr : forall a m1 m2, a *: (m1 - m2) = a *: m1 - a *: m2.\nProof. by move=> a m1 m2; rewrite scaler_addr scalerN. Qed.\n\nLemma scaler_nat : forall n m, n%:R *: m = m *+ n.\nProof.\nmove=> n v; elim: n => /= [|n ]; first by rewrite scale0r.\nby rewrite !mulrS scaler_addl ?scale1r => ->.\nQed.\n\nLemma scaler_suml : forall m I r (P : pred I) F,\n (\\sum_(i <- r | P i) F i) *: m = \\sum_(i <- r | P i) F i *: m.\nProof.\nmove=> m; exact: (big_morph _ (scaler_addl m) (scale0r m)).\nQed.\n\nLemma scaler_sumr : forall a I r (P : pred I) (F : I -> M),\n   a *: (\\sum_(i <- r | P i) F i) = \\sum_(i <- r | P i) a *: F i.\nProof.\nmove=> m; exact: (big_morph _ (scaler_addr m) (scaler0 m)).\nQed.\n\nEnd LmoduleTheory.\n\n\nModule NCalgebra.\n\nSection NCalgebra.\n\nVariable R : Ring.type.\nImplicit Type phR : phant R.\n\nNotation scale T L := (@scale R (@Lmodule.pack _ (Phant R) T _ L _ _ id _ id)).\nDefinition axiom (T: Ring.type) (L: Lmodule.mixin_of R T) :=\n  forall k x y, scale T L k (x * y) = scale T L k x * y.\n\nRecord class_of (T : Type) : Type := Class {\n  base1 :> Ring.class_of T;\n  mixin :> Lmodule.mixin_of R (Zmodule.Pack base1 T);\n  ext : @axiom (Ring.Pack base1 T) mixin\n}.\n\nCoercion base2 R m := Lmodule.Class (@mixin R m).\n\nStructure type phR := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class phR (cT : type phR) :=\n  let: Pack _ c _ :=  cT return class_of cT in c.\nDefinition clone phR T cT c of phant_id (@class phR cT) c := @Pack phR T c T.\nDefinition pack phR T b0 m0 (axT: @axiom (@Ring.Pack T b0 T) m0) :=\n  fun bT b & phant_id (Ring.class bT) (b : Ring.class_of T) =>\n  fun mT m & phant_id (@Lmodule.class R phR mT) (@Lmodule.Class R T b m) =>\n  fun ax &  phant_id axT ax =>\n  Pack  (Phant R) (@Class T b m ax) T.\n\nCoercion eqType phR cT := Equality.Pack (@class phR cT) cT.\nCoercion choiceType phR cT := Choice.Pack (@class phR cT) cT.\nCoercion zmodType phR cT := Zmodule.Pack (@class phR cT) cT.\nCoercion ringType phR cT := Ring.Pack (@class phR cT) cT.\nCoercion lmoduleType phR cT := Lmodule.Pack phR (@class phR cT) cT.\n\nDefinition lmod_ringType phR  cT :=\n  @Lmodule.Pack R phR  (Ring.sort (@ringType phR cT)) (base2 (class cT)) (Ring.sort (ringType cT)).\n\n(* Definition ring_lmodType phR cT  :=\n  @Ring.Pack  (Lmodule.sort (lmoduleType cT)) (@class phR cT) cT.\n*)\n\n\nEnd NCalgebra.\n\nEnd NCalgebra.\n\nCanonical Structure NCalgebra.eqType.\nCanonical Structure NCalgebra.choiceType.\nCanonical Structure NCalgebra.zmodType.\nCanonical Structure NCalgebra.ringType.\nCanonical Structure NCalgebra.lmoduleType.\nBind Scope ring_scope with NCalgebra.sort.\n\nSection NCalgebraTheory.\n\nVariable R : Ring.type.\nVariable A : NCalgebra.type (Phant R).\nImplicit Types k: R.\nImplicit Types x y: A.\n\nLemma scaler_mull: forall k x y, k *: (x * y) = k *: x * y.\nProof. exact: NCalgebra.ext. Qed.\n\nLemma morph_sunit: morphism (fun k => k *: (1: A)).\nProof.\nsplit=> [x y | x y |]; last by apply: scale1r.\n  by apply: scaler_subl.\nby rewrite -scaler_mull mul1r scalerA.\nQed.\n\nEnd NCalgebraTheory.\n\nModule Algebra.\n\nSection Algebra.\n\nVariable R : Ring.type.\nImplicit Type phR : phant R.\n\n(* Definition axiom (A: (NCalgebra.type (Phant R))) :=\n  forall k (x y:A),  k *: (x * y) = x * (k *: y).*)\n\n\nDefinition axiom T1 T2 (scalop: T1->T2->T2) (mulop: T2->T2->T2) :=  \n               forall k x y,  (scalop k (mulop  x  y)) = (mulop x (scalop k y)) .\n\n\n(*Record class_of (T : Type) : Type :=\n  Class {base :> NCalgebra.class_of R T; _ : axiom (NCalgebra.Pack  (Phant R)  base R)}.*)\n\n\nRecord class_of (T : Type) : Type :=\n  Class {base :> NCalgebra.class_of R T; \n         _ : axiom (Lmodule.scale (NCalgebra.mixin  base)) (Ring.mul (NCalgebra.base1 base))}.\n\n(* Coercion base2 b   c A := Lmodule.Class (@NCalgebra.mixin b c A).*)\n\n\nStructure type phR :Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class phR (cT : type phR) :=\n  let: Pack _ c _ :=  cT return class_of cT in c.\nDefinition clone phR T cT c of phant_id (@class phR cT) c := @Pack phR T c T.\n\n Definition pack phR T scale0 mul0 (axT : @axiom R T scale0 mul0) :=\n  fun bT b & phant_id (@NCalgebra.class R phR bT) b =>\n  fun    ax  & phant_id axT ax => Pack phR (@Class T b ax) T.\n\n(* Definition pack phR T  (axT : @axiom T ) :=\n  fun bT b & phant_id (@NCalgebra.class R phR bT) b =>\n  fun    ax  & phant_id axT ax => Pack phR (@Class T b ax) T.*)\n\n\nCoercion eqType phR cT := Equality.Pack (@class phR cT) cT.\nCoercion choiceType phR cT := Choice.Pack (@class phR cT) cT.\nCoercion zmodType phR cT := Zmodule.Pack (@class phR cT) cT.\nCoercion ringType phR cT := Ring.Pack (@class phR cT) cT.\nCoercion lmoduleType phR cT := Lmodule.Pack phR (@class phR cT) cT.\nCoercion ncalgebraType phR cT := NCalgebra.Pack phR (@class phR cT) cT.\n\nEnd Algebra.\n\nEnd Algebra.\n\nCanonical Structure Algebra.eqType.\nCanonical Structure Algebra.choiceType.\nCanonical Structure Algebra.zmodType.\nCanonical Structure Algebra.ringType.\nCanonical Structure Algebra.lmoduleType.\nCanonical Structure Algebra.ncalgebraType.\n\nBind Scope ring_scope with Algebra.sort.\n\nSection AlgebraTheory.\n\nVariable R : Ring.type.\nVariable A : Algebra.type (Phant R).\nImplicit Types k: R.\nImplicit Types x y: A.\n\n\nLemma scaler_com: forall (k:R)  (x y:A) , k *: (x * y) = x * (k *: y).\nProof. by case : A => T []. Qed.\n\n\nEnd AlgebraTheory.\n\nModule Theory.\n\nDefinition addrA := addrA.\nDefinition addrC := addrC.\nDefinition add0r := add0r.\nDefinition addNr := addNr.\nDefinition addr0 := addr0.\nDefinition addrN := addrN.\nDefinition subrr := subrr.\nDefinition addrCA := addrCA.\nDefinition addrAC := addrAC.\nDefinition addKr := addKr.\nDefinition addNKr := addNKr.\nDefinition addrK := addrK.\nDefinition addrNK := addrNK.\nDefinition subrK := subrK.\nDefinition addrI := addrI.\nDefinition addIr := addIr.\nDefinition opprK := opprK.\nDefinition oppr0 := oppr0.\nDefinition oppr_eq0 := oppr_eq0.\nDefinition oppr_add := oppr_add.\nDefinition oppr_sub := oppr_sub.\nDefinition subr0 := subr0.\nDefinition sub0r := sub0r.\nDefinition subr_eq := subr_eq.\nDefinition subr_eq0 := subr_eq0.\nDefinition sumr_opp := sumr_opp.\nDefinition sumr_sub := sumr_sub.\nDefinition sumr_muln := sumr_muln.\nDefinition sumr_muln_r := sumr_muln_r.\nDefinition sumr_const := sumr_const.\nDefinition mulr0n := mulr0n.\nDefinition mulrS := mulrS.\nDefinition mulr1n := mulr1n.\nDefinition mulrSr := mulrSr.\nDefinition mulrb := mulrb.\nDefinition mul0rn := mul0rn.\nDefinition oppr_muln := oppr_muln.\nDefinition mulrn_addl := mulrn_addl.\nDefinition mulrn_addr := mulrn_addr.\nDefinition mulrnA := mulrnA.\nDefinition mulrnAC := mulrnAC.\nDefinition mulrA := mulrA.\nDefinition mul1r := mul1r.\nDefinition mulr1 := mulr1.\nDefinition mulr_addl := mulr_addl.\nDefinition mulr_addr := mulr_addr.\nDefinition nonzero1r := nonzero1r.\nDefinition oner_eq0 := oner_eq0.\nDefinition mul0r := mul0r.\nDefinition mulr0 := mulr0.\nDefinition mulrN := mulrN.\nDefinition mulNr := mulNr.\nDefinition mulrNN := mulrNN.\nDefinition mulN1r := mulN1r.\nDefinition mulrN1 := mulrN1.\nDefinition mulr_subl := mulr_subl.\nDefinition mulr_subr := mulr_subr.\nDefinition mulrnAl := mulrnAl.\nDefinition mulrnAr := mulrnAr.\nDefinition mulr_natl := mulr_natl.\nDefinition mulr_natr := mulr_natr.\nDefinition natr_add := natr_add.\nDefinition natr_mul := natr_mul.\nDefinition natr_exp := natr_exp.\nDefinition expr0 := expr0.\nDefinition exprS := exprS.\nDefinition expr1 := expr1.\nDefinition exp1rn := exp1rn.\nDefinition exprn_addr := exprn_addr.\nDefinition exprSr := exprSr.\nDefinition commr_sym := commr_sym.\nDefinition commr_refl := commr_refl.\nDefinition commr0 := commr0.\nDefinition commr1 := commr1.\nDefinition commr_opp := commr_opp.\nDefinition commrN1 := commrN1.\nDefinition commr_add := commr_add.\nDefinition commr_muln := commr_muln.\nDefinition commr_mul := commr_mul.\nDefinition commr_nat := commr_nat.\nDefinition commr_exp := commr_exp.\nDefinition commr_exp_mull := commr_exp_mull.\nDefinition commr_sign := commr_sign.\nDefinition exprn_mulnl := exprn_mulnl.\nDefinition exprn_mulr := exprn_mulr.\nDefinition signr_odd := signr_odd.\nDefinition signr_eq0 := signr_eq0.\nDefinition signr_addb := signr_addb.\nDefinition exprN := exprN.\nDefinition exprn_addl_comm := exprn_addl_comm.\nDefinition exprn_subl_comm := exprn_subl_comm.\nDefinition subr_expn_comm := subr_expn_comm.\nDefinition subr_expn_1 := subr_expn_1.\nDefinition charf0 := charf0.\nDefinition charf_prime := charf_prime.\nDefinition dvdn_charf := dvdn_charf.\nDefinition charf_eq := charf_eq.\nDefinition bin_lt_charf_0 := bin_lt_charf_0.\nDefinition Frobenius_autE := Frobenius_autE.\nDefinition Frobenius_aut_0 := Frobenius_aut_0.\nDefinition Frobenius_aut_1 := Frobenius_aut_1.\nDefinition Frobenius_aut_add_comm := Frobenius_aut_add_comm.\nDefinition Frobenius_aut_muln := Frobenius_aut_muln.\nDefinition Frobenius_aut_nat := Frobenius_aut_nat.\nDefinition Frobenius_aut_mul_comm := Frobenius_aut_mul_comm.\nDefinition Frobenius_aut_exp := Frobenius_aut_exp.\nDefinition Frobenius_aut_opp := Frobenius_aut_opp.\nDefinition Frobenius_aut_sub_comm := Frobenius_aut_sub_comm.\nDefinition prodr_const := prodr_const.\nDefinition mulrC := mulrC.\nDefinition mulrCA := mulrCA.\nDefinition mulrAC := mulrAC.\nDefinition exprn_mull := exprn_mull.\nDefinition prodr_exp := prodr_exp.\nDefinition prodr_exp_r := prodr_exp_r.\nDefinition prodr_opp := prodr_opp.\nDefinition exprn_addl := exprn_addl.\nDefinition exprn_subl := exprn_subl.\nDefinition subr_expn := subr_expn.\nDefinition mulrV := mulrV.\nDefinition divrr := divrr.\nDefinition mulVr := mulVr.\nDefinition invr_out := invr_out.\nDefinition unitrP := unitrP.\nDefinition mulKr := mulKr.\nDefinition mulVKr := mulVKr.\nDefinition mulrK := mulrK.\nDefinition mulrVK := mulrVK.\nDefinition divrK := divrK.\nDefinition mulrI := mulrI.\nDefinition mulIr := mulIr.\nDefinition commr_inv := commr_inv.\nDefinition unitrE := unitrE.\nDefinition invrK := invrK.\nDefinition invr_inj := invr_inj.\nDefinition unitr_inv := unitr_inv.\nDefinition unitr1 := unitr1.\nDefinition invr1 := invr1.\nDefinition unitr0 := unitr0.\nDefinition invr0 := invr0.\nDefinition unitr_opp := unitr_opp.\nDefinition invrN := invrN.\nDefinition unitr_mull := unitr_mull.\nDefinition unitr_mulr := unitr_mulr.\nDefinition invr_mul := invr_mul.\nDefinition invr_eq0 := invr_eq0.\nDefinition invr_neq0 := invr_neq0.\nDefinition commr_unit_mul := commr_unit_mul.\nDefinition unitr_exp := unitr_exp.\nDefinition unitr_pexp := unitr_pexp.\nDefinition expr_inv := expr_inv.\nDefinition eq_eval := eq_eval.\nDefinition eval_tsubst := eval_tsubst.\nDefinition eq_holds := eq_holds.\nDefinition holds_fsubst := holds_fsubst.\nDefinition unitr_mul := unitr_mul.\nDefinition mulf_eq0 := mulf_eq0.\nDefinition mulf_neq0 := mulf_neq0.\nDefinition expf_eq0 := expf_eq0.\nDefinition expf_neq0 := expf_neq0.\nDefinition mulfI := mulfI.\nDefinition mulIf := mulIf.\nDefinition unitfE := unitfE.\nDefinition mulVf := mulVf.\nDefinition mulfV := mulfV.\nDefinition divff := divff.\nDefinition mulKf := mulKf.\nDefinition mulVKf := mulVKf.\nDefinition mulfK := mulfK.\nDefinition mulfVK := mulfVK.\nDefinition divfK := divfK.\nDefinition invf_mul := invf_mul.\nDefinition prodf_inv := prodf_inv.\nDefinition natf0_char := natf0_char.\nDefinition charf'_nat := charf'_nat.\nDefinition charf0P := charf0P.\nDefinition satP := @satP.\nDefinition eq_sat := eq_sat.\nDefinition solP := @solP.\nDefinition eq_sol := eq_sol.\nDefinition size_sol := size_sol.\nDefinition solve_monicpoly := solve_monicpoly.\nDefinition ringM_sub := ringM_sub.\nDefinition ringM_0 := ringM_0.\nDefinition ringM_1 := ringM_1.\nDefinition ringM_opp := ringM_opp.\nDefinition ringM_add := ringM_add.\nDefinition ringM_sum := ringM_sum.\nDefinition ringM_mul := ringM_mul.\nDefinition ringM_prod := ringM_prod.\nDefinition ringM_natmul := ringM_natmul.\nDefinition ringM_nat := ringM_nat.\nDefinition ringM_exp := ringM_exp.\nDefinition ringM_sign := ringM_sign.\nDefinition ringM_char := ringM_char.\nDefinition comp_ringM := comp_ringM.\nDefinition ringM_isom := ringM_isom.\nDefinition ringM_comm := ringM_comm.\nDefinition ringM_unit := ringM_unit.\nDefinition Frobenius_aut_RM := Frobenius_aut_RM.\nDefinition fieldM_eq0 := fieldM_eq0.\nDefinition fieldM_inj := fieldM_inj.\nDefinition ringM_inv := ringM_inv.\nDefinition fieldM_char := fieldM_char.\nDefinition ringM_div := ringM_div.\nDefinition fieldM_unit := fieldM_unit.\nDefinition fieldM_inv := fieldM_inv.\nDefinition fieldM_div := fieldM_div.\nDefinition scalerA := scalerA.\nDefinition scale1r := scale1r.\nDefinition scaler_addr := scaler_addr.\nDefinition scaler_addl := scaler_addl.\nDefinition scaler0 := scaler0.\nDefinition scale0r := scale0r.\nDefinition scaleNr := scaleNr.\nDefinition scaleN1r := scaleN1r.\nDefinition scalerN := scalerN.\nDefinition scaler_subl := scaler_subl.\nDefinition scaler_subr := scaler_subr.\nDefinition scaler_nat := scaler_nat.\nDefinition scaler_suml := scaler_suml.\nDefinition scaler_sumr := scaler_sumr.\nDefinition scaler_mull := scaler_mull.\nDefinition morph_sunit := morph_sunit.\n\nImplicit Arguments satP [F e f].\nImplicit Arguments solP [F n f].\nPrenex Implicits satP solP.\n\nEnd Theory.\n\nEnd GRing.\n\nCanonical Structure GRing.Zmodule.eqType.\nCanonical Structure GRing.Zmodule.choiceType.\nCanonical Structure GRing.Ring.eqType.\nCanonical Structure GRing.Ring.choiceType.\nCanonical Structure GRing.Ring.zmodType.\nCanonical Structure GRing.UnitRing.eqType.\nCanonical Structure GRing.UnitRing.choiceType.\nCanonical Structure GRing.UnitRing.zmodType.\nCanonical Structure GRing.UnitRing.ringType.\nCanonical Structure GRing.ComRing.eqType.\nCanonical Structure GRing.ComRing.choiceType.\nCanonical Structure GRing.ComRing.zmodType.\nCanonical Structure GRing.ComRing.ringType.\nCanonical Structure GRing.ComUnitRing.eqType.\nCanonical Structure GRing.ComUnitRing.choiceType.\nCanonical Structure GRing.ComUnitRing.zmodType.\nCanonical Structure GRing.ComUnitRing.ringType.\nCanonical Structure GRing.ComUnitRing.unitRingType.\nCanonical Structure GRing.ComUnitRing.comRingType.\nCanonical Structure GRing.ComUnitRing.com_unitRingType.\nCanonical Structure GRing.IntegralDomain.eqType.\nCanonical Structure GRing.IntegralDomain.choiceType.\nCanonical Structure GRing.IntegralDomain.zmodType.\nCanonical Structure GRing.IntegralDomain.ringType.\nCanonical Structure GRing.IntegralDomain.unitRingType.\nCanonical Structure GRing.IntegralDomain.comRingType.\nCanonical Structure GRing.IntegralDomain.comUnitRingType.\nCanonical Structure GRing.Field.eqType.\nCanonical Structure GRing.Field.choiceType.\nCanonical Structure GRing.Field.zmodType.\nCanonical Structure GRing.Field.ringType.\nCanonical Structure GRing.Field.unitRingType.\nCanonical Structure GRing.Field.comRingType.\nCanonical Structure GRing.Field.comUnitRingType.\nCanonical Structure GRing.Field.idomainType.\nCanonical Structure GRing.DecidableField.eqType.\nCanonical Structure GRing.DecidableField.choiceType.\nCanonical Structure GRing.DecidableField.zmodType.\nCanonical Structure GRing.DecidableField.ringType.\nCanonical Structure GRing.DecidableField.unitRingType.\nCanonical Structure GRing.DecidableField.comRingType.\nCanonical Structure GRing.DecidableField.comUnitRingType.\nCanonical Structure GRing.DecidableField.idomainType.\nCanonical Structure GRing.DecidableField.fieldType.\nCanonical Structure GRing.ClosedField.eqType.\nCanonical Structure GRing.ClosedField.choiceType.\nCanonical Structure GRing.ClosedField.zmodType.\nCanonical Structure GRing.ClosedField.ringType.\nCanonical Structure GRing.ClosedField.unitRingType.\nCanonical Structure GRing.ClosedField.comRingType.\nCanonical Structure GRing.ClosedField.comUnitRingType.\nCanonical Structure GRing.ClosedField.idomainType.\nCanonical Structure GRing.ClosedField.fieldType.\nCanonical Structure GRing.ClosedField.decFieldType.\n\nCanonical Structure GRing.add_monoid.\nCanonical Structure GRing.add_comoid.\nCanonical Structure GRing.mul_monoid.\nCanonical Structure GRing.mul_comoid.\nCanonical Structure GRing.muloid.\nCanonical Structure GRing.addoid.\n\nCanonical Structure GRing.Lmodule.eqType.\nCanonical Structure GRing.Lmodule.choiceType.\nCanonical Structure GRing.Lmodule.zmodType.\n\nCanonical Structure GRing.NCalgebra.eqType.\nCanonical Structure GRing.NCalgebra.choiceType.\nCanonical Structure GRing.NCalgebra.zmodType.\nCanonical Structure GRing.NCalgebra.ringType.\nCanonical Structure GRing.NCalgebra.lmoduleType.\n\nBind Scope ring_scope with GRing.Zmodule.sort.\nBind Scope ring_scope with GRing.Ring.sort.\nBind Scope ring_scope with GRing.ComRing.sort.\nBind Scope ring_scope with GRing.UnitRing.sort.\nBind Scope ring_scope with GRing.ComUnitRing.sort.\nBind Scope ring_scope with GRing.IntegralDomain.sort.\nBind Scope ring_scope with GRing.Field.sort.\nBind Scope ring_scope with GRing.DecidableField.sort.\nBind Scope ring_scope with GRing.ClosedField.sort.\nBind Scope ring_scope with GRing.Lmodule.sort.\nBind Scope ring_scope with GRing.NCalgebra.sort.\n\nNotation \"0\" := (GRing.zero _) : ring_scope.\nNotation \"-%R\" := (@GRing.opp _) : ring_scope.\nNotation \"- x\" := (GRing.opp x) : ring_scope.\nNotation \"+%R\" := (@GRing.add _).\nNotation \"x + y\" := (GRing.add x y) : ring_scope.\nNotation \"x - y\" := (GRing.add x (- y)) : ring_scope.\nNotation \"x *+ n\" := (GRing.natmul x n) : ring_scope.\nNotation \"x *- n\" := (GRing.natmul (- x) n) : ring_scope.\nNotation \"s `_ i\" := (seq.nth 0%R s%R i) : ring_scope.\n\nNotation \"1\" := (GRing.one _) : ring_scope.\nNotation \"- 1\" := (- (1))%R : ring_scope.\n\nNotation \"n %:R\" := (GRing.natmul 1 n) : ring_scope.\nNotation \"[ 'char' R ]\" := (GRing.char (Phant R)) : ring_scope.\nNotation Frobenius_aut chRp := (GRing.Frobenius_aut chRp).\nNotation \"*%R\" := (@GRing.mul _).\nNotation \"x * y\" := (GRing.mul x y) : ring_scope.\nNotation \"x ^+ n\" := (GRing.exp x n) : ring_scope.\nNotation \"x ^-1\" := (GRing.inv x) : ring_scope.\nNotation \"x ^- n\" := (x ^+ n)^-1%R : ring_scope.\nNotation \"x / y\" := (GRing.mul x y^-1) : ring_scope.\n\nImplicit Arguments GRing.unitDef [].\n\nBind Scope term_scope with GRing.term.\nBind Scope term_scope with GRing.formula.\n\nNotation \"''X_' i\" := (GRing.Var _ i) : term_scope.\nNotation \"n %:R\" := (GRing.NatConst _ n) : term_scope.\nNotation \"0\" := 0%:R%T : term_scope.\nNotation \"1\" := 1%:R%T : term_scope.\nNotation \"x %:T\" := (GRing.Const x) : term_scope.\nInfix \"+\" := GRing.Add : term_scope.\nNotation \"- t\" := (GRing.Opp t) : term_scope.\nNotation \"t - u\" := (GRing.Add t (- u)) : term_scope.\nInfix \"*\" := GRing.Mul : term_scope.\nInfix \"*+\" := GRing.NatMul : term_scope.\nNotation \"t ^-1\" := (GRing.Inv t) : term_scope.\nNotation \"t / u\" := (GRing.Mul t u^-1) : term_scope.\nInfix \"^+\" := GRing.Exp : term_scope.\nInfix \"==\" := GRing.Equal : term_scope.\nNotation \"x != y\" := (GRing.Not (x == y)) : term_scope.\nInfix \"/\\\" := GRing.And : term_scope.\nInfix \"\\/\" := GRing.Or : term_scope.\nInfix \"==>\" := GRing.Implies : term_scope.\nNotation \"~ f\" := (GRing.Not f) : term_scope.\nNotation \"''exists' ''X_' i , f\" := (GRing.Exists i f) : term_scope.\nNotation \"''forall' ''X_' i , f\" := (GRing.Forall i f) : term_scope.\n\nNotation \"*:%R\" := (@GRing.scale _ _) : ring_scope.\nNotation \"a *: m\" := (GRing.scale a m) (at level 40) : ring_scope.\n\nNotation \"\\sum_ ( <- r | P ) F\" :=\n  (\\big[+%R/0%R]_(<- r | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i <- r | P ) F\" :=\n  (\\big[+%R/0%R]_(i <- r | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i <- r ) F\" :=\n  (\\big[+%R/0%R]_(i <- r) F%R) : ring_scope.\nNotation \"\\sum_ ( m <= i < n | P ) F\" :=\n  (\\big[+%R/0%R]_(m <= i < n | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( m <= i < n ) F\" :=\n  (\\big[+%R/0%R]_(m <= i < n) F%R) : ring_scope.\nNotation \"\\sum_ ( i | P ) F\" :=\n  (\\big[+%R/0%R]_(i | P%B) F%R) : ring_scope.\nNotation \"\\sum_ i F\" :=\n  (\\big[+%R/0%R]_i F%R) : ring_scope.\nNotation \"\\sum_ ( i : t | P ) F\" :=\n  (\\big[+%R/0%R]_(i : t | P%B) F%R) (only parsing) : ring_scope.\nNotation \"\\sum_ ( i : t ) F\" :=\n  (\\big[+%R/0%R]_(i : t) F%R) (only parsing) : ring_scope.\nNotation \"\\sum_ ( i < n | P ) F\" :=\n  (\\big[+%R/0%R]_(i < n | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i < n ) F\" :=\n  (\\big[+%R/0%R]_(i < n) F%R) : ring_scope.\nNotation \"\\sum_ ( i \\in A | P ) F\" :=\n  (\\big[+%R/0%R]_(i \\in A | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i \\in A ) F\" :=\n  (\\big[+%R/0%R]_(i \\in A) F%R) : ring_scope.\n\nNotation \"\\prod_ ( <- r | P ) F\" :=\n  (\\big[*%R/1%R]_(<- r | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i <- r | P ) F\" :=\n  (\\big[*%R/1%R]_(i <- r | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i <- r ) F\" :=\n  (\\big[*%R/1%R]_(i <- r) F%R) : ring_scope.\nNotation \"\\prod_ ( m <= i < n | P ) F\" :=\n  (\\big[*%R/1%R]_(m <= i < n | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( m <= i < n ) F\" :=\n  (\\big[*%R/1%R]_(m <= i < n) F%R) : ring_scope.\nNotation \"\\prod_ ( i | P ) F\" :=\n  (\\big[*%R/1%R]_(i | P%B) F%R) : ring_scope.\nNotation \"\\prod_ i F\" :=\n  (\\big[*%R/1%R]_i F%R) : ring_scope.\nNotation \"\\prod_ ( i : t | P ) F\" :=\n  (\\big[*%R/1%R]_(i : t | P%B) F%R) (only parsing) : ring_scope.\nNotation \"\\prod_ ( i : t ) F\" :=\n  (\\big[*%R/1%R]_(i : t) F%R) (only parsing) : ring_scope.\nNotation \"\\prod_ ( i < n | P ) F\" :=\n  (\\big[*%R/1%R]_(i < n | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i < n ) F\" :=\n  (\\big[*%R/1%R]_(i < n) F%R) : ring_scope.\nNotation \"\\prod_ ( i \\in A | P ) F\" :=\n  (\\big[*%R/1%R]_(i \\in A | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i \\in A ) F\" :=\n  (\\big[*%R/1%R]_(i \\in A) F%R) : ring_scope.\n\nNotation zmodType := GRing.Zmodule.type.\nNotation ZmodType T m := (@GRing.Zmodule.pack T m _ _ id).\nNotation ZmodMixin := GRing.Zmodule.Mixin.\nNotation \"[ 'zmodType' 'of' T 'for' cT ]\" := (@GRing.Zmodule.clone T cT _ idfun)\n  (at level 0, format \"[ 'zmodType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'zmodType' 'of' T ]\" := (@GRing.Zmodule.clone T _ _ id)\n  (at level 0, format \"[ 'zmodType'  'of'  T ]\") : form_scope.\n\nNotation ringType := GRing.Ring.type.\nNotation RingType T m := (@GRing.Ring.pack T _ m _ _ id _ id).\nNotation RingMixin := GRing.Ring.Mixin.\nNotation RevRingType := GRing.RevRingType.\nNotation \"[ 'ringType' 'of' T 'for' cT ]\" := (@GRing.Ring.clone T cT _ idfun)\n  (at level 0, format \"[ 'ringType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'ringType' 'of' T ]\" := (@GRing.Ring.clone T _ _ id)\n  (at level 0, format \"[ 'ringType'  'of'  T ]\") : form_scope.\n\nNotation comRingType := GRing.ComRing.type.\nNotation ComRingType T m := (@GRing.ComRing.pack T _ m _ _ id _ id).\nNotation ComRingMixin := GRing.ComRing.RingMixin.\nNotation \"[ 'comRingType' 'of' T 'for' cT ]\" :=\n    (@GRing.ComRing.clone T cT _ idfun)\n  (at level 0, format \"[ 'comRingType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'comRingType' 'of' T ]\" := (@GRing.ComRing.clone T _ _ id)\n  (at level 0, format \"[ 'comRingType'  'of'  T ]\") : form_scope.\n\nNotation unitRingType := GRing.UnitRing.type.\nNotation UnitRingType T m := (@GRing.UnitRing.pack T _ m _ _ id _ id).\nNotation UnitRingMixin := GRing.UnitRing.EtaMixin.\nNotation \"[ 'unitRingType' 'of' T 'for' cT ]\" :=\n    (@GRing.UnitRing.clone T cT _ idfun)\n  (at level 0, format \"[ 'unitRingType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'unitRingType' 'of' T ]\" := (@GRing.UnitRing.clone T _ _ id)\n  (at level 0, format \"[ 'unitRingType'  'of'  T ]\") : form_scope.\n\nNotation comUnitRingType := GRing.ComUnitRing.type.\nNotation ComUnitRingMixin := GRing.ComUnitRing.Mixin.\nNotation \"[ 'comUnitRingType' 'of' T ]\" :=\n    (@GRing.ComUnitRing.pack T _ _ id _ _ id)\n  (at level 0, format \"[ 'comUnitRingType'  'of'  T ]\") : form_scope.\n\nNotation idomainType := GRing.IntegralDomain.type.\nNotation IdomainType T m := (@GRing.IntegralDomain.pack T _ m _ _ id _ id).\nNotation \"[ 'idomainType' 'of' T 'for' cT ]\" :=\n    (@GRing.IntegralDomain.clone T cT _ idfun)\n  (at level 0, format \"[ 'idomainType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'idomainType' 'of' T ]\" := (@GRing.IntegralDomain.clone T _ _ id)\n  (at level 0, format \"[ 'idomainType'  'of'  T ]\") : form_scope.\n\nNotation fieldType := GRing.Field.type.\nNotation FieldType T m := (@GRing.Field.pack T _ m _ _ id _ id).\nNotation FieldUnitMixin := GRing.Field.UnitMixin.\nNotation FieldIdomainMixin := GRing.Field.IdomainMixin.\nNotation FieldMixin := GRing.Field.Mixin.\nNotation \"[ 'fieldType' 'of' T 'for' cT ]\" := (@GRing.Field.clone T cT _ idfun)\n  (at level 0, format \"[ 'fieldType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'fieldType' 'of' T ]\" := (@GRing.Field.clone T _ _ id)\n  (at level 0, format \"[ 'fieldType'  'of'  T ]\") : form_scope.\n\nNotation decFieldType := GRing.DecidableField.type.\nNotation DecFieldType T m := (@GRing.DecidableField.pack T _ m _ _ id _ id).\nNotation DecFieldMixin := GRing.DecidableField.Mixin.\nNotation \"[ 'decFieldType' 'of' T 'for' cT ]\" :=\n    (@GRing.DecidableField.clone T cT _ idfun)\n  (at level 0, format \"[ 'decFieldType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'decFieldType' 'of' T ]\" := (@GRing.DecidableField.clone T _ _ id)\n  (at level 0, format \"[ 'decFieldType'  'of'  T ]\") : form_scope.\n\nNotation closedFieldType := GRing.ClosedField.type.\nNotation ClosedFieldType T m := (GRing.ClosedField.pack T _ m _ _ id _ id).\nNotation \"[ 'closedFieldType' 'of' T 'for' cT ]\" :=\n    (@GRing.ClosedField.clone T cT _ idfun)\n  (at level 0,\n   format \"[ 'closedFieldType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'closedFieldType' 'of' T ]\" := (@GRing.ClosedField.clone T _ _ id)\n  (at level 0, format \"[ 'closedFieldType'  'of'  T ]\") : form_scope.\n\nNotation lmodType R := (GRing.Lmodule.type (Phant R)).\nNotation LmodType R T m :=\n   (@GRing.Lmodule.pack _ (Phant R) T _ m _ _ id _ id).\nNotation LmodMixin := GRing.Lmodule.Mixin.\nNotation \"[ 'lmodType' [ R ] 'of' T 'for' cT ]\" :=\n  (@GRing.Lmodule.clone _ (Phant R) T cT _ idfun)\n  (at level 0, format \"[ 'lmodType' [ R ]  'of'  T  'for'  cT ]\")\n  : form_scope.\nNotation \"[ 'lmodType' [ R ] 'of' T ]\" :=\n  (@GRing.Lmodule.clone _ (Phant R) T _ _ id)\n  (at level 0, format \"[ 'lmodType' [ R ] 'of'  T ]\") : form_scope.\n\nNotation ncalgebraType R := (GRing.NCalgebra.type (Phant R)).\nNotation NCalgebraType R T m a :=\n   (@GRing.NCalgebra.pack _ (Phant R) T _ m a _ _ id _ _ id _ id).\nNotation \"[ 'ncalgebraType' [ R ] 'of' T 'for' cT ]\" :=\n  (@GRing.NCalgebra.clone _ (Phant R) T cT _ idfun)\n  (at level 0, format \"[ 'ncalgebraType' [ R ]  'of'  T  'for'  cT ]\")\n  : form_scope.\nNotation \"[ 'ncalgebraType' [ R ] 'of' T ]\" :=\n  (@GRing.NCalgebra.clone _ (Phant R) T _ _ id)\n  (at level 0, format \"[ 'ncalgebraType' [ R ] 'of'  T ]\") : form_scope.\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/ssreflect/attic/ssreflect12_trunk/theories/ssralg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6932046015517349}}
{"text": "Require Export GeoCoq.Axioms.euclidean_axioms.\n\nSection Definitions.\n\nContext `{Ax:euclidean_neutral}.\n\nDefinition Out A B C := exists X, BetS X A C /\\ BetS X A B.\nDefinition Lt A B C D := exists X, BetS C X D /\\ Cong C X A B.\nDefinition Midpoint A B C := BetS A B C /\\ Cong A B B C.\nDefinition CongA A B C a b c := exists U V u v, Out B A U /\\ Out B C V /\\ Out b a u /\\ Out b c v /\\ Cong B U b u /\\ Cong B V b v /\\ Cong U V u v /\\ nCol A B C.\nDefinition AdjacentAngle A B C D E F := eq B E /\\ BetS A B F /\\ Out B D C.\nDefinition VA A B C D E F := eq B E /\\ BetS A B D /\\ BetS C B F.\nDefinition Supp A B C D F := Out B C D /\\ BetS A B F.\nDefinition Per A B C := exists X, BetS A B X /\\ Cong A B X B /\\ Cong A C X C /\\ neq B C.\nDefinition Perp_at P Q A B C := exists X, Col P Q C /\\ Col A B C /\\ Col A B X /\\ Per X C P.\nDefinition Perp P Q A B := exists X, Perp_at P Q A B X.\nDefinition InAngle A B C P := exists X Y, Out B A X /\\ Out B C Y /\\ BetS X P Y.\nDefinition OS P Q A B := exists X U V, Col A B U /\\ Col A B V /\\ BetS P U X /\\ BetS Q V X /\\ nCol A B P /\\ nCol A B Q.\nDefinition IO A B C D := BetS A B C /\\ BetS A B D /\\ BetS A C D /\\ BetS B C D.\nDefinition isosceles A B C := Triangle A B C /\\ Cong A B A C.\nDefinition Cut A B C D E := BetS A E B /\\ BetS C E D /\\ nCol A B C /\\ nCol A B D.\nDefinition LtA A B C D E F := exists U X V, BetS U X V /\\ Out E D U /\\ Out E F V /\\ CongA A B C D E X.\nDefinition TG A B C D E F := exists X, BetS A B X /\\ Cong B X C D /\\ Lt E F A X.\nDefinition TT A B C D E F G H := exists X, BetS E F X /\\ Cong F X G H /\\ TG A B C D E X.\nDefinition RT A B C D E F := exists X Y Z U V, Supp X Y U V Z /\\ CongA A B C X Y U /\\ CongA D E F V Y Z.\nDefinition Meet A B C D := exists X, neq A B /\\ neq C D /\\ Col A B X /\\ Col C D X.\nDefinition CR A B C D := exists X, BetS A X B /\\ BetS C X D.\nDefinition TP A B C D := neq A B /\\ neq C D /\\ ~ Meet A B C D /\\ OS C D A B.\nDefinition Par A B C D := exists U V u v X, neq A B /\\ neq C D /\\ Col A B U /\\ Col A B V /\\ neq U V /\\ Col C D u /\\ Col C D v /\\ neq u v /\\ ~ Meet A B C D /\\ BetS U X v /\\ BetS u X V.\nDefinition SumA A B C D E F P Q R := exists X, CongA A B C P Q X /\\ CongA D E F X Q R /\\ BetS P X R.\nDefinition PG A B C D := Par A B C D /\\ Par A D B C.\nDefinition SQ A B C D := 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.\nDefinition RE A B C D := Per D A B /\\ Per A B C /\\ Per B C D /\\ Per C D A /\\ CR A C B D.\nDefinition RC A B C D a b c d := RE A B C D /\\ RE a b c d /\\ Cong A B a b /\\ Cong B C b c.\nDefinition ER A B C D a b c d := exists X Y Z U x z u w W, RC A B C D X Y Z U /\\ RC a b c d x Y z u /\\ BetS x Y Z /\\ BetS X Y z /\\ BetS W U w. \nDefinition equilateral A B C := Cong A B B C /\\ Cong B C C A.\n\nEnd Definitions.", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/euclidean_defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.693204599708483}}
{"text": "Require Import BinNums BinNat Nat List.\nRequire Import Lia.\n\nRequire Import LibUtils Isomorphism PairEncoding.\nImport ListNotations.\n\nRequire Import QArith Qcanon.\n\nGlobal Program Instance positive_N_iso : Isomorphism positive N\n  := {iso_f n := Pos.pred_N n ;\n      iso_b n := N.succ_pos n\n     }.\nNext Obligation.\n  apply N.pos_pred_succ.\nQed.\nNext Obligation.\n  destruct a; simpl; trivial.\n  apply Pos.succ_pred_double.\nQed.\n\n\n\nGlobal Program Instance Z_N_iso : Isomorphism Z N\n  := { iso_f n := (if Z_ge_lt_dec n 0 then (Z.to_N n)*2 else (Z.to_N (- n))*2-1)%N ;\n       iso_b n := if (n mod 2)%N then Z.of_N (n / 2)%N else (- (Z.of_N ((n+1) / 2)%N))%Z\n     }.\nNext Obligation.\n  case_eq ((b mod 2)%N); [intros modeq | intros ? modeq].\n  - generalize (N.div_mod b 2); intros HH.\n    destruct ( Z_ge_lt_dec (Z.of_N (b / 2)) 0); lia.\n  - assert (modeq2:(b mod 2 = 1)%N).\n    { generalize (N.mod_upper_bound b 2); lia. }\n    clear modeq.\n    generalize (N.div_mod b 2); intros HH.\n    rewrite modeq2 in HH.\n    cut_to HH; [| lia].\n    destruct (  Z_ge_lt_dec (- Z.of_N ((b + 1) / 2)) 0).\n    + generalize (N2Z.is_nonneg ((b+1) / 2)); intros HH2.\n      assert ((Z.of_N ((b+1)  / 2)%N = 0%Z)) by lia.\n      generalize (f_equal Z.to_N H); intros HH3.\n      rewrite N2Z.id in HH3.\n      rewrite Z2N.inj_0 in HH3.\n      generalize (N.div_str_pos (b+1) 2); intros HH4.\n      lia.\n    + rewrite Z.opp_involutive.\n      rewrite N2Z.id.\n      assert (modeq3:((b+1) mod 2 = 0)%N).\n      {\n        rewrite <- N.add_mod_idemp_l by lia.\n        rewrite modeq2.\n        simpl.\n        rewrite N.mod_same; lia.\n      }\n      generalize (N.div_mod (b+1) 2); intros HH5.\n      lia.\nQed.\nNext Obligation.\n  destruct (Z_ge_lt_dec a 0).\n  - rewrite N.mod_mul by lia.\n    rewrite N.div_mul by lia.\n    rewrite Z2N.id; lia.\n  - match_case; intros.\n    + apply N.mod_divide in H; [| lia].\n      destruct H as [k HH].\n      lia.\n    + rewrite N.sub_add by lia.\n      rewrite N.div_mul by lia.\n      rewrite Z2N.id by lia.\n      rewrite Z.opp_involutive; lia.\nQed.\n\nGlobal Program Instance Q_Zpos_iso : Isomorphism Q (Z*positive)\n  := { iso_f q := (Qnum q, Qden q) ;\n       iso_b '(z,p) := Qmake z p\n     }.\nNext Obligation.\n  now destruct a.\nQed.\n\nGlobal Instance Q_N_iso : Isomorphism Q N\n  := Isomorphism_trans\n       Q_Zpos_iso\n       (Isomorphism_trans\n          (Isomorphism_prod\n             Z_N_iso positive_N_iso) N_pair_encoder).\n\nGlobal Instance Q_nat_iso : Isomorphism Q nat\n  := Isomorphism_trans\n       Q_N_iso\n       (Isomorphism_symm nat_to_N_iso).\n\nRequire Import ZArith.\n\n\n\nProgram Instance Qc_Qpos_iso : Isomorphism Q (Qc*positive)\n  := {\n  iso_f q := (Q2Qc q, Z.to_pos (Z.gcd (Qnum q) (Zpos (Qden q))));\n  iso_b '(qc,m) := ((this qc) * (Z.pos m # m))%Q\n    }.\nNext Obligation.\n  f_equal.\n  - apply Qc_is_canon.\n    unfold Qeq; simpl.\n    case_eq ( (Z.ggcd (Qnum q * Z.pos p) (Z.pos (Qden q * p)))); intros; simpl.\n    generalize (Z.ggcd_correct_divisors (Qnum q * Z.pos p) (Z.pos (Qden q * p))); intros HH.\n    rewrite H in HH.\n    destruct p0.\n    destruct HH as [eqq1 eqq2].\n    simpl.\n    destruct q.\n    destruct this.\n    simpl in *.\n    rewrite Pos2Z.inj_mul in eqq2.\n    assert (eqq12:(Z.pos Qden * (Qnum * Z.pos p)%Z = Z.pos Qden * (z * z0)%Z)%Z)\n           by now rewrite eqq1.\n    assert (eqq22:(Z.pos Qden * (Qnum * Z.pos p)%Z = Qnum * (z * z1)%Z)%Z)\n      by (rewrite <- eqq2; lia).\n    rewrite eqq12 in eqq22.\n    assert (eqq3:( z * (Z.pos Qden * z0) = z * (Qnum * z1))%Z) by lia.\n    rewrite Z2Pos.id.\n    + apply Z.mul_cancel_l in eqq3; [ | lia].\n      lia.\n    + rewrite <- Pos2Z.inj_mul in eqq2.\n      generalize (Pos2Z.pos_is_pos (Qden * p)); intros HH1.\n      rewrite eqq2 in HH1.\n      rewrite Z.mul_comm in HH1.\n      generalize (Z.ggcd_gcd (Qnum * Z.pos p) (Z.pos (Qden * p))); intros HH2.\n      rewrite H in HH2; simpl in HH2.\n      \n      generalize (Z.gcd_nonneg (Qnum * Z.pos p) (Z.pos (Qden * p))); intros HH3.\n      rewrite <- HH2 in HH3.\n      assert (HH4:(z = 0 \\/ 0 < z)%Z) by lia.\n      destruct HH4.\n      * subst.\n        lia.\n      * eapply Zmult_gt_0_lt_0_reg_r.\n        -- apply Z.lt_gt.\n           apply H0.\n        -- lia.\n  - simpl.\n    rewrite Pos2Z.inj_mul.\n    rewrite Z.gcd_mul_mono_r.\n    destruct q; simpl.\n    apply Qred_iff in canon.\n    rewrite canon.\n    simpl.\n    trivial.\nQed.\nNext Obligation.\n  generalize (Qred_correct a); intros HH.\n  red in HH.\n  rewrite <- Z.ggcd_gcd.\n  unfold Qred.\n  destruct a.\n  generalize (Z.ggcd_correct_divisors Qnum (Z.pos Qden)).\n  case_eq (Z.ggcd Qnum (Z.pos Qden)).\n  intros z [p q] eqq [HH1 HH2].\n  simpl.\n  rewrite eqq, HH1; simpl.\n  unfold Qmult; simpl.\n  assert (zn:(z <> 0)%Z).\n  {\n    intro; subst.\n    simpl in HH2.\n    lia.\n  }\n  assert (zpos:(z > 0)%Z).\n  {\n    generalize (Z.gcd_nonneg Qnum (Z.pos Qden)); intros HH3.\n    rewrite <- Z.ggcd_gcd in HH3.\n    rewrite eqq in HH3; simpl in HH3.\n    lia.\n  }\n  assert (qpos:(q>0)%Z).\n  {\n    generalize (Pos2Z.is_pos Qden); intros HH3.\n    eapply Z.lt_gt.\n    eapply Zmult_lt_0_reg_r.\n    + eapply Z.gt_lt.\n      eapply zpos.\n    + lia.\n  } \n  rewrite Z2Pos.id by lia.\n  f_equal.\n  + lia.\n  + rewrite <- Z2Pos.inj_mul by lia.\n    apply Pos2Z.inj_pos.\n    rewrite HH2.\n    rewrite Z2Pos.id by lia.\n    lia.\nQed.\n", "meta": {"author": "IBM", "repo": "FormalML", "sha": "e399d096f1ad572420dbd1c638d593eee2129cbe", "save_path": "github-repos/coq/IBM-FormalML", "path": "github-repos/coq/IBM-FormalML/FormalML-e399d096f1ad572420dbd1c638d593eee2129cbe/coq/utils/NumberIso.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6932045928726097}}
{"text": "Global Set Asymmetric Patterns.\nSet Implicit Arguments.\nSet Strict Implicit.\nUnset Standard Proposition Elimination Names.\nRequire Export Setoid.\nRequire Import Omega.\n\n(** * Sets.v: Definition of sets as predicates over a type A *)\n\nSection sets.\nVariable A : Type.\nVariable decA : forall x y :A, {x=y}+{x<>y}. \n\nDefinition set := A->Prop.\nDefinition full : set := fun (x:A) => True.\nDefinition empty : set := fun (x:A) => False.\nDefinition add (a:A) (P:set) : set := fun (x:A) => x=a \\/ (P x).\nDefinition singl (a:A) :set := fun (x:A) => x=a.\nDefinition union (P Q:set) :set := fun (x:A) => (P x) \\/ (Q x).\nDefinition compl (P:set) :set := fun (x:A) => ~P x.\nDefinition inter (P Q:set) :set := fun (x:A) => (P x) /\\ (Q x).\nDefinition rem (a:A) (P:set) :set := fun (x:A) => x<>a /\\ (P x).\n\n(** ** Equivalence *)\nDefinition equiv (P Q:set) := forall (x:A), P x <-> Q x.\n\nImplicit Arguments full [].\nImplicit Arguments empty [].\n\nLemma equiv_refl : forall P:set, equiv P P.\nunfold equiv; intuition.\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.\nHint Immediate equiv_sym.\n\n(** ** Setoid structure *)\nLemma set_setoid : Setoid_Theory set equiv.\nsplit; red; auto.\nexact equiv_trans.\nQed.\n\nAdd Setoid set equiv set_setoid as Set_setoid.\n\nAdd Morphism add : equiv_add.\nunfold equiv,add; firstorder.\nQed.\n\nAdd Morphism rem : equiv_rem.\nunfold equiv,rem; firstorder.\nQed.\nHint Resolve equiv_add equiv_rem.\n\nAdd Morphism union : equiv_union.\nunfold equiv,union; firstorder.\nQed.\nHint Immediate equiv_union.\n\nLemma equiv_union_left : \n  forall P1 Q P2,\n   equiv P1 P2 -> equiv (union P1 Q) (union P2 Q).\nauto.\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.\n\nAdd Morphism inter : equiv_inter.\nunfold equiv,inter; firstorder.\nQed.\nHint Immediate equiv_inter.\n\nAdd Morphism compl : equiv_compl.\nunfold equiv,compl; firstorder.\nQed.\nHint Resolve equiv_compl.\n\nLemma equiv_add_empty : forall (a:A) (P:set), ~equiv (add a P) empty.\nred; unfold equiv,empty,add; intros a P eqH; assert (H:=eqH a);  intuition.\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.\n\nLemma fin_empty : (finite empty).\nauto.\nDefined.\n\nLemma fin_add : forall (x:A)(P:set),\n             ~ P x -> finite P -> finite (add x P).\neauto.\nDefined.\n\nLemma fin_equiv: forall (P Q : set), (equiv P Q)->(finite P)->(finite Q).\ninduction 2.\napply fin_eq_empty.\napply equiv_trans with P; auto.\napply fin_eq_add with x Q0; auto.\napply equiv_trans with P; auto.\nDefined.\n\nHint Resolve fin_empty fin_add.\n\n(** *** Emptyness is decidable for finite sets *)\nDefinition isempty (P:set) := equiv P empty.\nDefinition notempty (P:set) := not (equiv P empty).\n\nLemma isempty_dec : forall P, finite P -> {isempty P}+{notempty P}.\nunfold isempty,notempty; destruct 1; auto.\nright; red; intros.\napply (@equiv_add_empty x Q); auto.\napply equiv_trans with P; auto.\nQed.\n\n(** *** Size of a finite set *)\nFixpoint size (P:set) (f:finite P) {struct f}: nat :=\n   match f with fin_eq_empty _ => 0%nat\n              | fin_eq_add _ Q _ f' _ => S (size f')\n   end.\n\nLemma size_equiv : forall P Q  (f:finite P) (e:equiv P Q),\n    (size (fin_equiv e f)) = (size f).\ninduction f; simpl; intros; auto.\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. \nHint Immediate equiv_incl equiv_incl_sym. \n\n(** ** Properties of operations on sets *)\n\nLemma incl_empty : forall P, incl empty P.\nunfold incl,empty; intuition.\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.\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.\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.\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.\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.\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.\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.\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.\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.\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.\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.\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.\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\n(* bug lie a intuition\nLemma size_finite_rem: \n   forall (P:set) (a:A) (f:finite P), \n    (P a) -> size f = S (size (finite_rem a f)).\ninduction f;  intuition.\ncase (equiv_empty_false a e H).\nsimpl; case (decA x a); simpl; intros.\ncase e0; unfold eq_rect_r;simpl; auto.\nrewrite size_equiv; auto.\nrewrite IHf; auto.\ncase (e a); unfold add; intuition.\ncase f0; auto.\nQed.\n*)\nRequire Import Arith.\n\nLemma size_incl : \n  forall (P:set)(f:finite P) (Q:set)(g:finite Q), \n  (incl P Q)-> size f <= size g.\ninduction f; simpl; intros; auto with arith.\napply le_trans with (S (size (finite_rem x g))).\napply le_n_S.\napply IHf with (g:= finite_rem x g); auto.\napply incl_trans with (rem x P); auto.\napply incl_add_rem; auto.\napply incl_rem_stable; auto.\nrewrite <- size_finite_rem; auto.\ncase (e x); intuition.\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\nRequire Import Lt.\n\n(** *** Filter operation *)\n\nLemma finite_inter : forall P Q, dec P -> finite Q -> finite (inter P Q).\nintros P Q decP FQ.\ninduction FQ.\nconstructor 1.\napply equiv_trans with (inter P empty); auto.\ncase (decP x); intro.\nconstructor 2 with x (inter P Q); auto.\nunfold inter; intuition.\nrewrite e.\nunfold add,inter; red; intuition.\nsubst; auto.\napply fin_equiv with (inter P Q); auto.\nrewrite e.\nunfold add,inter; red; intuition.\nsubst; intuition.\nDefined.\n\nLemma size_inter_empty : forall P Q (decP:dec P) (e:equiv Q empty), \n   size (finite_inter decP (fin_eq_empty e))=O.\ntrivial.\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(** *** Selecting elements in a finite set *)\n\nFixpoint nth_finite (P:set) (k:nat) (PF : finite P) {struct PF}: (k < size PF) -> A := \n  match PF as F return (k < size F) -> A with \n       fin_eq_empty H => (fun (e : k<0) => match lt_n_O k e with end)\n     | fin_eq_add x Q nqx fq eqq => \n           match k as k0 return k0<S (size fq)->A with \n                O => fun e => x\n         | (S k1) => fun (e:S k1<S (size fq)) => nth_finite fq (lt_S_n k1 (size fq) e)\n           end\n  end.\n\n\n(** A set with size > 1 contains at least 2 different elements **)\n\nLemma select_non_empty : forall (P:set), finite P -> notempty P -> sigT P.\ndestruct 1; intros.\ncase H; auto.\nexists x; case (e x); intuition.\nDefined.\n\nLemma select_diff : forall (P:set) (FP:finite P),\n     (1 < size FP)%nat -> sigT (fun x => sigT (fun y => P x /\\ P y /\\ x<>y)).\ndestruct FP; simpl; intros.\nabsurd (1<0); omega.\nexists x; destruct FP; simpl in H.\nabsurd (1<1); omega.\nexists x0; intuition.\ncase (e x); auto.\ncase (e0 x0); case (e x0); unfold add; intuition.\nsubst; case (e0 x0); intuition.\nQed.\n\nEnd sets.\n\nHint Resolve equiv_refl.\nHint Resolve equiv_add equiv_rem.\nHint Immediate equiv_sym finite_dec finite_full_dec equiv_incl equiv_incl_sym equiv_incl_intro.\n\nHint Resolve incl_refl.\nHint Immediate incl_union_stable.\nHint Resolve union_incl_left union_incl_right union_incl_intro incl_empty rem_incl\nincl_rem_stable incl_add_stable.\n\nHint Constructors finite.\nHint Resolve add_in add_in_eq add_intro add_incl add_incl_intro union_sym union_empty_left union_empty_right\nunion_add_left union_add_right finite_union equiv_union_left \nequiv_union_right.\nImplicit Arguments full [].\nImplicit Arguments empty [].\n", "meta": {"author": "coq-contribs", "repo": "random", "sha": "e29ddb2860344bcaa750476ba26b786ee84afa4e", "save_path": "github-repos/coq/coq-contribs-random", "path": "github-repos/coq/coq-contribs-random/random-e29ddb2860344bcaa750476ba26b786ee84afa4e/Sets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979306, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.6931342972351809}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(**********************************************************************\n     Aux.v\n\n     Auxillary functions & Theorems\n **********************************************************************)\nRequire Export Arith.\n\n(**************************************\n  Some properties of minus\n**************************************)\n\nTheorem minus_O : forall a b : nat, a <= b -> a - b = 0.\nintros a; elim a; simpl in |- *; auto with arith.\nintros a1 Rec b; case b; elim b; auto with arith.\nQed.\n\n\n(**************************************\n  Definitions and properties of the power for nat\n**************************************)\n\nFixpoint pow (n m: nat)  {struct m} : nat := match m with O => 1%nat | (S m1) => (n * pow n m1)%nat  end.\n\nTheorem pow_add: forall n m p, pow n (m + p) = (pow n m * pow n p)%nat.\nintros n m; elim m; simpl.\nintros p; rewrite Nat.add_0_r; auto.\nintros m1 Rec p; rewrite Rec; auto with arith.\nQed.\n\n\nTheorem pow_pos: forall p n, (0 < p)%nat -> (0 < pow p n)%nat.\nintros p1 n H; elim n; simpl; auto with arith.\nintros n1 H1; replace 0%nat with (p1 * 0)%nat; auto with arith.\nrepeat rewrite (Nat.mul_comm p1); apply Nat.mul_lt_mono_pos_r; auto with arith.\nQed.\n\n\nTheorem pow_monotone: forall n p q, (1 < n)%nat -> (p < q)%nat -> (pow n p < pow n q)%nat.\nintros n p1 q1 H H1; elim H1; simpl.\npattern (pow n p1) at 1; rewrite <- (Nat.mul_1_l (pow n p1)).\napply Nat.mul_lt_mono_pos_r; auto.\napply pow_pos; auto with arith.\nintros n1 H2 H3.\napply Nat.lt_trans with (1 := H3).\npattern (pow n n1) at 1; rewrite <- (Nat.mul_1_l (pow n n1)).\napply Nat.mul_lt_mono_pos_r; auto.\napply pow_pos; auto with arith.\nQed.\n\n(************************************\n  Definition of the divisibility for nat\n**************************************)\n\nDefinition divide a b := exists c, b = a * c.\n\n\nTheorem divide_le: forall p q, (1 < q)%nat -> divide p q -> (p <= q)%nat.\nintros p1 q1 H (x, H1); subst.\napply Nat.le_trans with (p1 * 1)%nat; auto with arith.\nrewrite Nat.mul_1_r; auto with arith.\napply  Nat.mul_le_mono_l.\ndestruct x; auto with arith.\nrewrite  Nat.mul_0_r in H; auto with arith.\nQed.\n", "meta": {"author": "thery", "repo": "coqprime", "sha": "431d7a66877cbe8688fc8864ef892369401440e1", "save_path": "github-repos/coq/thery-coqprime", "path": "github-repos/coq/thery-coqprime/coqprime-431d7a66877cbe8688fc8864ef892369401440e1/src/Coqprime/N/NatAux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.6931342873232866}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. You may distribute   *)\n(* under the terms of either the CeCILL-B License or the CeCILL        *)\n(* version 2 License, as specified in the README file.                 *)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice fintype.\nRequire Import bigops ssralg.\n\n(***************************************************************************)\n(* This file provides a library for univariate polynomials over ring       *)\n(* structures and proposes a theory for these objects when coefficients    *)\n(* range over commutative rings and integral domains.                      *)\n(*                                                                         *)\n(*    polynomial R       == the type of polynomials over the ring R,       *)\n(*                          represented as lists with a non zero last      *)\n(*                          element (big endian representation)            *)\n(*      + objects in this type should be casted by the {poly R} annotation *)\n(*    c %:P              == the constant polynomial c, 'X and 'X^n the     *)\n(*                          monomials.                                     *)\n(*    \\poly_ ( i < n ) E == the polynomial of degree strictly less than n, *)\n(*                          whose coefficients are given by the general    *)\n(*                          term E                                         *)\n(*    p.[x]              == The evaluation of a polynomial p at a point x  *)\n(*                          following the Horner schema                    *)\n(*      + The multi-rule horner_lin (resp. horner_lin_com) unwinds horner  *)\n(*        evaluation of a polynomial expression (resp. in a non            *)\n(*        commutative case, under the appropriate assumptions)             *)\n(*                                                                         *)\n(* Degree is not defined as such, we rather use the size operation on      *)\n(* sequences. Hence the zero polynomial is the only polynomial of size 0.  *)\n(*                                                                         *)\n(*    We define pseudo division on polynomials over an integral domain :   *)\n(*        m %/ d == the pseudo-quotient                                    *)\n(*        m %% d == the pseudo remainder                                   *)\n(*        p %| q <=> q is a pseudo-divisor of p                            *)\n(*                                                                         *)\n(*    p %= q             == the equality modulo constant factors           *)\n(*                       := (p %| q) && (q %| p)                           *)\n(*       + In the case R is a field p and q are associate                  *)\n(*                                                                         *)\n(*       gcdp p q  == pseudo-gcd, for poly with coefficients in a ring,    *)\n(*          idomain is only require of indempotence and commutativity      *)\n(*                                                                         *)\n(*       roots p   == roots of poly with coefficients in an idomain.       *)\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(***************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\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\").\n\nNotation Local simp := Monoid.simpm.\n\nSection Polynomial.\n\nVariable R : ringType.\n\n(* Defines a polynomial as a sequence with <> 0 last element *)\nRecord polynomial : Type :=\n  Polynomial {polyseq :> seq R; _ : last 1 polyseq != 0}.\n\nDefinition poly_of of phant R := polynomial.\nIdentity Coercion type_poly_of : poly_of >-> polynomial.\nNotation \"{ 'poly' T }\" := (poly_of (Phant T)).\n\nImplicit Types p q : {poly R}.\n\nBind Scope ring_scope with poly_of.\n\nCanonical Structure polynomial_subType :=\n  Eval hnf in [subType for polyseq by polynomial_rect].\nDefinition polynomial_eqMixin := Eval hnf in [eqMixin of polynomial by <:].\nCanonical Structure polynomial_eqType := Eval hnf in EqType polynomial_eqMixin.\nDefinition polynomial_choiceMixin := [choiceMixin of polynomial by <:].\nCanonical Structure polynomial_choiceType :=\n  Eval hnf in ChoiceType polynomial_choiceMixin.\nCanonical Structure poly_subType := Eval hnf in [subType of {poly R}].\nCanonical Structure poly_eqType := Eval hnf in [eqType of {poly R}].\nCanonical Structure poly_choiceType := Eval hnf in [choiceType of {poly R}].\n\nLemma poly_inj : injective polyseq. Proof. exact: val_inj. Qed.\n\nDefinition lead_coef p := p`_(size p).-1.\nLemma lead_coefE : forall p, lead_coef p = p`_(size p).-1. Proof. by []. Qed.\n\nDefinition polyC c : {poly R} :=\n  insubd (@Polynomial [::] (nonzero1r _)) [:: c].\n\nNotation \"c %:P\" := (polyC c).\n\n(* Remember the boolean (c !=0) is coerced to 1 if true and 0 if false *)\nLemma polyseqC : forall c, c%:P = nseq (c != 0) c :> seq R.\nProof. by move=> c; rewrite val_insubd /=; case: (c == 0). Qed.\n\nLemma size_polyC : forall c, size c%:P = (c != 0).\nProof. by move=> c; rewrite polyseqC size_nseq. Qed.\n\nLemma coefC : forall c i, c%:P`_i = if i == 0%N then c else 0.\nProof. by move=> c [|[|i]]; rewrite polyseqC //=; case: eqP. 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 : forall c, lead_coef c%:P = c.\nProof. by move=> c; rewrite /lead_coef polyseqC; case: eqP. Qed.\n\n(* Extensional interpretation (poly <=> nat -> R) *)\nLemma polyP : forall p1 p2, nth 0 p1 =1 nth 0 p2 <-> p1 = p2.\nProof.\nmove=> p1 p2; split=> [eq_p12 | -> //]; apply: poly_inj.\nwithout loss lt_p12: p1 p2 eq_p12 / size p1 < size p2 => [wltn|].\n  case: (ltngtP (size p1) (size p2)); try by move/wltn->.\n  move/(@eq_from_nth _ 0); exact.\ncase: p2 => p2 nz_p2 /= in lt_p12 eq_p12 *; case/eqP: nz_p2.\nby rewrite (last_nth 0) -(subnKC lt_p12) /= -eq_p12 nth_default ?leq_addr.\nQed.\n\nLemma size1_polyC : forall p, size p <= 1 -> p = (p`_0)%:P.\nProof.\nmove=> p 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 poly_cons c p : {poly R} :=\n  if p is Polynomial ((_ :: _) as s) ns then @Polynomial (c :: s) ns else c%:P.\n\nLemma polyseq_cons : forall c p,\n  poly_cons c p = (if size p != 0%N then c :: p else c%:P) :> seq R.\nProof. by move=> c [[|c' s] ns] /=. Qed.\n\nLemma size_poly_cons : forall c p,\n  size (poly_cons c p) =\n    (if (size p == 0%N) && (c == 0) then 0%N else (size p).+1).\nProof. by move=> c [[|c' s] _] //=; rewrite size_polyC; case: eqP. Qed.\n\nLemma coef_cons : forall c p i,\n  (poly_cons c p)`_i = if i == 0%N then c else p`_i.-1.\nProof.\nby move=> c [[|c' s] _] [] //=; rewrite polyseqC; case: eqP => //= _ [].\nQed.\n\n(* Builds a polynomial from a bare list of coefficients *)\nDefinition Poly := foldr poly_cons 0%:P.\n\nLemma PolyK : forall c s, last c s != 0 -> Poly s = s :> seq R.\nProof.\nmove=> _ [_|/= c s]; first by rewrite polyseqC eqxx.\nelim: s c => [|c' s IHs] /= c nz_c; rewrite polyseq_cons ?IHs //.\nby rewrite !(polyseqC, eqxx) // nz_c.\nQed.\n\nLemma polyseqK : forall p, Poly p = p.\nProof. case=> s nz_s; apply: poly_inj; exact: PolyK nz_s. Qed.\n\nLemma size_Poly : forall s, size (Poly s) <= size s.\nProof.\nelim=> [|c s IHs] /=; first by rewrite polyseqC eqxx.\nby rewrite polyseq_cons; case: ifP => // _; rewrite size_polyC; case: (~~ _).\nQed.\n\nLemma coef_Poly : forall s i, (Poly s)`_i = s`_i.\nProof.\nby elim=> [|c s IHs] /= [|i]; rewrite !(coefC, eqxx, coef_cons) /=.\nQed.\n\n(* Builds a polynomial from an infinite seq of coef and a bound *)\nNotation \"\\poly_ ( i < n ) E\" := (Poly (mkseq (fun i : nat => E) n)).\n\nLemma polyseq_poly : forall n E,\n  E n.-1 != 0 -> \\poly_(i < n) E i = mkseq [eta E] n :> seq R.\nProof.\nmove=> [|n] E nzE; first by rewrite polyseqC eqxx.\nby rewrite (@PolyK 0) // -nth_last nth_mkseq size_mkseq /=.\nQed.\n\nLemma size_poly : forall n E, size (\\poly_(i < n) E i) <= n.\nProof. by move=> n E; rewrite (leq_trans (size_Poly _)) ?size_mkseq. Qed.\n\nLemma size_poly_eq : forall n E, E n.-1 != 0 -> size (\\poly_(i < n) E i) = n.\nProof. move=> n E; move/polyseq_poly->; exact: size_mkseq. Qed.\n\nLemma coef_poly : forall n E k,\n  (\\poly_(i < n) E i)`_k = (if k < n then E k else 0).\nProof.\nmove=> n E k; case: (ltnP k n) => ?; first by rewrite coef_Poly nth_mkseq.\nby rewrite coef_Poly nth_default // size_mkseq.\nQed.\n\nLemma lead_coef_poly : forall n E,\n  n > 0 -> E n.-1 != 0 -> lead_coef (\\poly_(i < n) E i) = E n.-1.\nProof.\nby case=> // n E _ nzE; rewrite /lead_coef size_poly_eq // coef_poly leqnn.\nQed.\n\nLemma coefK : forall p, \\poly_(i < size p) p`_i = p.\nProof.\nmove=> p; apply/polyP=> i; rewrite coef_poly.\nby case: ltnP => // le_p_i; rewrite nth_default.\nQed.\n\n(* Zmodule structure for polynomial *)\nDefinition add_poly p1 p2 :=\n  \\poly_(i < maxn (size p1) (size p2)) (p1`_i + p2`_i).\n\nDefinition opp_poly p := \\poly_(i < size p) - p`_i.\n\nLemma coef_add_poly : forall p1 p2 i, (add_poly p1 p2)`_i = p1`_i + p2`_i.\nProof.\nmove=> p1 p2 i; rewrite coef_poly /=; case: leqP => //.\nby rewrite leq_maxl; case/andP; do 2!move/(nth_default 0)->; rewrite add0r.\nQed.\n\nLemma coef_opp_poly : forall p i, (opp_poly p)`_i = - p`_i.\nProof.\nmove=> p i; rewrite coef_poly /=; case: leqP => //.\nby move/(nth_default 0)->; rewrite oppr0.\nQed.\n\nLemma add_polyA : associative add_poly.\nProof. by move=> p1 p2 p3; apply/polyP=> i; rewrite !coef_add_poly addrA. Qed.\n\nLemma add_polyC : commutative add_poly.\nProof. by move=> p1 p2; apply/polyP=> i; rewrite !coef_add_poly addrC. Qed.\n\nLemma 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\nLemma add_poly_opp : 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_poly_opp.\nCanonical Structure poly_zmodType := Eval hnf in ZmodType poly_zmodMixin.\nCanonical Structure polynomial_zmodType :=\n  Eval hnf in [zmodType of polynomial for poly_zmodType].\n\n(* Properties of the zero polynomial *)\n\nLemma polyC0 : 0%:P = 0 :> {poly R}. Proof. by []. Qed.\n\nLemma seq_poly0 : (0 : {poly R}) = [::] :> seq R.\nProof. by rewrite polyseqC eqxx. Qed.\n\nLemma size_poly0 : size (0 : {poly R}) = 0%N.\nProof. by rewrite seq_poly0. Qed.\n\nLemma coef0 : forall i, (0 : {poly R})`_i = 0.\nProof. by move=> i; rewrite coefC if_same. Qed.\n\nLemma lead_coef0 : lead_coef 0 = 0. Proof. exact: lead_coefC. Qed.\n\nLemma size_poly_eq0 : forall p, (size p == 0%N) = (p == 0).\nProof. by move=> p; rewrite size_eq0 -seq_poly0. Qed.\n\nLemma poly0Vpos : forall p, {p = 0} + {size p > 0}.\nProof. by move=> p; rewrite lt0n size_poly_eq0; exact: eqVneq. Qed.\n\nLemma polySpred : forall p, p != 0 -> size p = (size p).-1.+1.\nProof. by move=> p; rewrite -size_poly_eq0 -lt0n; move/prednK. Qed.\n\nLemma lead_coef_eq0 : forall p, (lead_coef p == 0) = (p == 0).\nProof. \nmove=> p; rewrite -size_poly_eq0 /lead_coef nth_last.\nby case: p => [[|x s] /=]; move/negbTE=> // _; rewrite eqxx.\nQed.\n\nLemma polyC_eq0 : forall c, (c%:P == 0) = (c == 0).\nProof. by move=> c; rewrite -size_poly_eq0 size_polyC; case: (c == 0). Qed.\n\n(* Size, leading coef, morphism properties of coef *)\nLemma leq_size_coef : forall p i,\n  (forall j, i <= j -> p`_j = 0) -> size p <= i.\nProof.\nmove=> p i p_i_0; case: leqP => lt_i_p //; have p1_1 := ltn_predK lt_i_p.\nhave: p != 0 by rewrite -size_poly_eq0 -p1_1.\nby rewrite -lead_coef_eq0 lead_coefE p_i_0 ?eqxx // -ltnS p1_1.\nQed.\n\nLemma leq_coef_size : forall p i, p`_i != 0 -> i < size p.\nProof. by move=> p i; case: leqP => //; move/(nth_default 0)->; case/eqP. Qed.\n\nLemma coef_add : forall p1 p2 i, (p1 + p2)`_i = p1`_i + p2`_i.\nProof. exact: coef_add_poly. Qed.\n\nLemma coef_opp : forall p i, (- p)`_i = - p`_i.\nProof. exact: coef_opp_poly. Qed.\n\nLemma coef_sub : forall p1 p2 i, (p1 - p2)`_i = p1`_i - p2`_i.\nProof. by move=> p1 p2 i; rewrite coef_add coef_opp. Qed.\n\nLemma coef_natmul : forall p n i, (p *+ n)`_i = p`_i *+ n.\nProof.\nby move=> p n i; elim: n => [|n IHn]; rewrite ?coef0 // !mulrS coef_add IHn.\nQed.\n\nLemma coef_negmul : forall p n i, (p *- n)`_i = p`_i *- n.\nProof. by move=> p n i; rewrite coef_natmul coef_opp. Qed.\n\nLemma coef_sum : forall I r (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.\nmove=> I r P F k.\nby apply: (big_morph (fun p => p`_k)) => [p q|]; rewrite (coef0, coef_add).\nQed.\n\nLemma polyC_add : {morph polyC : c1 c2 / c1 + c2}.\nProof.\nby move=> c1 c2; apply/polyP=> [[|i]]; rewrite coef_add !coefC ?addr0.\nQed.\n\nLemma polyC_opp : {morph polyC : c / - c}.\nProof.\nby move=> c; apply/polyP=> [[|i]]; rewrite coef_opp !coefC ?oppr0.\nQed.\n\nLemma polyC_sub : {morph polyC : c1 c2 / c1 - c2}.\nProof. by move=> c1 c2; rewrite polyC_add polyC_opp. Qed.\n\nLemma polyC_natmul : forall n, {morph polyC : c / c *+ n}.\nProof. by elim=> // n IHn c; rewrite !mulrS polyC_add IHn. Qed.\n\nLemma size_opp : forall p, size (- p) = size p.\nProof.\nhave le_sz: forall p, size (- p) <= size p by move=> p; exact: size_poly.\nby move=> p; apply/eqP; rewrite eqn_leq -{3}(opprK p) !le_sz.\nQed.\n\nLemma lead_coef_opp : forall p, lead_coef (- p) = - lead_coef p.\nProof. by move=> p; rewrite /lead_coef size_opp coef_opp. Qed.\n\nLemma size_add : forall p q, size (p + q) <= maxn (size p) (size q).\nProof. by move=> p q; exact: size_poly. Qed.\n\nLemma size_addl : forall p q, size p > size q -> size (p + q) = size p.\nProof.\nmove=> p q ltqp; rewrite size_poly_eq maxnl 1?ltnW //.\nby rewrite addrC nth_default ?simp ?nth_last; case: p ltqp => [[]].\nQed.\n\nLemma size_sum : forall I r (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.\nmove=> I r P F; pose K p := [fun n => size p <= n : Prop].\napply: (big_rel K) => //= [|p1 n1 p2 n2 IH1 IH2]; first by rewrite size_poly0.\napply: leq_trans (size_add p1 p2) _.\nby rewrite -eqn_maxl maxnAC !maxnA -maxnA (maxnl IH1) (maxnr IH2).\nQed.\n\nLemma lead_coef_addl : forall p q,\n  size p > size q -> lead_coef (p + q) = lead_coef p.\nProof.\nmove=> p q ltqp; rewrite /lead_coef coef_add size_addl //.\nby rewrite addrC nth_default ?simp // -ltnS (ltn_predK ltqp).\nQed.\n\n(* And now the Ring structure. *)\n\nDefinition mul_poly p1 p2 :=\n  \\poly_(i < (size p1 + size p2).-1) (\\sum_(j < i.+1) p1`_j * p2`_(i - j)).\n\nLemma coef_mul_poly : forall p1 p2 i,\n  (mul_poly p1 p2)`_i = \\sum_(j < i.+1) p1`_j * p2`_(i - j)%N.\nProof.\nmove=> p1 p2 i; rewrite coef_poly; case: leqP => // gtn_i.\nrewrite big1 // => j _; case: (leqP (size p2) (i - j)) => [ge_j | lt_j].\n  by rewrite {1}[nth]lock nth_default ?mulr0.\nrewrite nth_default ?mul0r // -(leq_add2r (size p2)); move: gtn_i (lt_j).\nrewrite -(ltn_predK lt_j) !addnS /= !ltnS leq_sub_add; exact: leq_trans.\nQed.\n\nLemma coef_mul_poly_rev : forall p1 p2 i,\n  (mul_poly p1 p2)`_i = \\sum_(j < i.+1) p1`_(i - j)%N * p2`_j.\nProof.\nmove=> p1 p2 i; rewrite coef_mul_poly (reindex ord_opp) /=.\n  by apply: eq_bigr => j _; rewrite (sub_ordK j).\nexists (@ord_opp _ : 'I_(i.+1) -> _) => j _; exact: ord_oppK.\nQed.\n\nLemma mul_polyA : associative mul_poly.\nProof.\nmove=> p1 p2 p3; apply/polyP=> i; rewrite coef_mul_poly coef_mul_poly_rev.\npose coef3 j k := p1`_j * (p2`_(i - j - k)%N * p3`_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) -!leq_subS ?leq_ord //.\n  by rewrite -subn_gt0 -(subn_gt0 j) !subn_sub addnC.\nrewrite (big_ord_narrow_leq (leq_subr _ _)) coef_mul_poly big_distrl /=.\nby apply: eq_bigr => j _; rewrite /coef3 !subn_sub addnC mulrA.\nQed.\n\nLemma 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\nLemma 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\nLemma mul_poly_addl : left_distributive mul_poly +%R.\nProof.\nmove=> p1 p2 p3; apply/polyP=> i; rewrite coef_add !coef_mul_poly -big_split.\nby apply: eq_bigr => j _; rewrite coef_add mulr_addl.\nQed.\n\nLemma mul_poly_addr : right_distributive mul_poly +%R.\nProof.\nmove=> p1 p2 p3; apply/polyP=> i; rewrite coef_add !coef_mul_poly -big_split.\nby apply: eq_bigr => j _; rewrite coef_add mulr_addr.\nQed.\n\nLemma nonzero_poly1 : 1%:P != 0. Proof. by rewrite polyC_eq0 nonzero1r. Qed.\n\nDefinition poly_ringMixin :=\n  RingMixin mul_polyA mul_1poly mul_poly1 mul_poly_addl mul_poly_addr\n            nonzero_poly1.\nCanonical Structure poly_ringType := Eval hnf in RingType poly_ringMixin.\nCanonical Structure polynomial_ringType :=\n   Eval hnf in [ringType of polynomial for poly_ringType].\n\nLemma polyC1 : 1%:P = 1. Proof. by []. Qed.\n\nLemma polyseq1 : (1 : {poly R}) = [:: 1] :> seq R.\nProof. by rewrite polyseqC nonzero1r. Qed.\n\nLemma size_poly1 : size (1 : {poly R}) = 1%N.\nProof. by rewrite polyseq1. Qed.\n\nLemma coef1 : forall i, (1 : {poly R})`_i = (i == 0%N)%:R.\nProof. by case=> [|i]; rewrite polyseq1 /= ?nth_nil. Qed. \n\nLemma lead_coef1 : lead_coef 1 = 1. Proof. exact: lead_coefC. Qed.\n\nLemma coef_mul : forall p1 p2 i,\n  (p1 * p2)`_i = \\sum_(j < i.+1) p1`_j * p2`_(i - j)%N.\nProof. exact: coef_mul_poly. Qed.\n\nLemma coef_mul_rev : forall p1 p2 i,\n  (p1 * p2)`_i = \\sum_(j < i.+1) p1`_(i - j)%N * p2`_j.\nProof. exact: coef_mul_poly_rev. Qed.\n\nLemma size_mul : forall p1 p2, size (p1 * p2) <= (size p1 + size p2).-1.\nProof. move=> p1 p2; exact: size_poly. Qed.\n\nLemma head_coef_mul : forall p q,\n  (p * q)`_(size p + size q).-2 = lead_coef p * lead_coef q.\nProof.\nmove=> p q; pose dp := (size p).-1; pose dq := (size q).-1.\ncase: (poly0Vpos p) => [->|nz_p]; first by rewrite !(simp, coef0, lead_coef0).\ncase: (poly0Vpos q) => [->|nz_q]; first by rewrite !(simp, coef0, lead_coef0).\nhave ->: (size p + size q).-2 = (dp + dq)%N.\n  by rewrite -(prednK nz_p) -(prednK nz_q) addnS.\nhave op: dp < (dp + dq).+1 by rewrite ltnS leq_addr.\nrewrite coef_mul (bigD1 (Ordinal op)) ?big1 ?simp ?addKn //= => i.\nrewrite -val_eqE neq_ltn /=; case/orP=> [lt_i_p | gt_i_p]; last first.\n  by rewrite nth_default ?simp //; rewrite prednK in gt_i_p.\nrewrite [q`__]nth_default ?simp //= -subSS -{1}addnS prednK //.\nby rewrite addnC -addn_subA ?leq_addr. \nQed.\n\nLemma size_proper_mul : forall p q,\n  lead_coef p * lead_coef q != 0 -> size (p * q) = (size p + size q).-1.\nProof.\nmove=> p q; rewrite -head_coef_mul.\ncase: (poly0Vpos p) => [-> | nz_p]; first by rewrite simp coef0 eqxx.\ncase: (poly0Vpos q) => [-> | nz_q]; first by rewrite simp coef0 eqxx.\nrewrite coef_poly {1}prednK ?leqnn => [? | ]; first by rewrite size_poly_eq.\nby rewrite -(prednK nz_p) -(prednK nz_q) addnS.\nQed.\n\nLemma lead_coef_proper_mul : forall p q,\n  let c := lead_coef p * lead_coef q in c != 0 -> lead_coef (p * q) = c.\nProof. by move=> p q /= nz_c; rewrite -head_coef_mul -size_proper_mul. Qed.\n\nLemma size_exp : forall p n, size (p ^+ n) <= ((size p).-1 * n).+1.\nProof.\nmove=> p n; case: (poly0Vpos p) => [-> | nzp].\n  by case: n => [|n]; rewrite ?exprS ?mul0r size_poly0 ?size_poly1.\nelim: n => [|n IHn]; first by rewrite size_poly1.\nrewrite exprS (leq_trans (size_mul _ _)) //.\nby rewrite -{1}(prednK nzp) mulnS -addnS leq_add2l.\nQed.\n\nLemma coef_Cmul : forall c p i, (c%:P * p)`_i = c * p`_i.\nProof.\nmove=> c p i; rewrite coef_mul big_ord_recl subn0.\nby rewrite big1 => [|j _]; rewrite coefC !simp.\nQed.\n\nLemma coef_mulC : forall c p i, (p * c%:P)`_i = p`_i * c.\nProof.\nmove=> c p i; rewrite coef_mul_rev big_ord_recl subn0.\nby rewrite big1 => [|j _]; rewrite coefC !simp.\nQed.\n\nLemma polyC_mul : {morph polyC : c1 c2 / c1 * c2}.\nProof.\nby move=> c1 c2; apply/polyP=> [[|i]]; rewrite coef_Cmul !coefC ?simp.\nQed.\n\nLemma polyC_exp : forall n, {morph polyC : c / c ^+ n}.\nProof. by elim=> // n IHn c; rewrite !exprS polyC_mul IHn. Qed.\n\n(* Indeterminate, at last! *)\n\nDefinition polyX := Poly [:: 0; 1].\n\nNotation \"'X\" := polyX.\n\nLemma polyseqX : 'X = [:: 0; 1] :> seq R.\nProof. by rewrite !polyseq_cons size_poly0 polyseq1. Qed.\n\nLemma size_polyX : size 'X = 2. Proof. by rewrite polyseqX. Qed.\n\nLemma coefX : forall i, 'X`_i = (i == 1%N)%:R.\nProof. by move=> [|[|i]]; rewrite polyseqX //= nth_nil. Qed.\n\nLemma lead_coefX : lead_coef 'X = 1.\nProof. by rewrite /lead_coef polyseqX. Qed.\n\nLemma comm_polyX : forall p, GRing.comm p 'X.\nProof.\nmove=> p; apply/polyP=> i; rewrite coef_mul_rev coef_mul.\nby apply: eq_bigr => j _; rewrite coefX commr_nat.\nQed.\n\nLemma coef_mulX : forall p i, (p * 'X)`_i = (if i is i'.+1 then p`_i' else 0).\nProof.\nmove=> p i; rewrite coef_mul_rev 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 coef_Xmul : forall p i, ('X * p)`_i = (if i is i'.+1 then p`_i' else 0).\nProof. by move=> p i; rewrite -comm_polyX coef_mulX. Qed.\n\nLemma poly_cons_def : forall p a, poly_cons a p = p * 'X + a%:P.\nProof.\nmove=> p a; apply/polyP=> i; rewrite coef_cons coef_add coef_mulX coefC.\nby case: i => [|i]; rewrite !simp.\nQed.\n\nLemma poly_ind : forall K : {poly R} -> Type,\n  K 0 -> (forall p c, K p -> K (p * 'X + c%:P)) -> (forall p, K p).\nProof.\nmove=> K K0 Kcons p; rewrite -[p]polyseqK.\nelim: {p}(p : seq R) => //= p c IHp; rewrite poly_cons_def; exact: Kcons.\nQed.\n\nLemma seq_mul_polyX : forall p, p != 0 -> p * 'X = 0 :: p :> seq R.\nProof.\nmove=> p nz_p.\nby rewrite -[p * _]addr0 -poly_cons_def polyseq_cons size_poly_eq0 nz_p.\nQed.\n\nLemma lead_coef_mulX : forall p, lead_coef (p * 'X) = lead_coef p.\nProof.\nmove=> p; case: (eqVneq p 0) => [-> | nzp]; first by rewrite simp.\nby rewrite /lead_coef !nth_last seq_mul_polyX.\nQed.\n\nNotation \"''X^' n\" := ('X ^+ n).\n\nLemma coef_Xn : forall n i, 'X^n`_i = (i == n)%:R.\nProof.\nelim=> [|n IHn] i; first exact: coef1.\nby rewrite exprS coef_Xmul; case: i.\nQed.\n\nLemma seq_polyXn : forall n, 'X^n = ncons n 0 [:: 1] :> seq R.\nProof.\nelim=> [|n IHn]; rewrite ?polyseq1 // exprSr seq_mul_polyX ?IHn //.\nby rewrite -size_poly_eq0 IHn size_ncons addnS.\nQed. \n\nLemma size_polyXn : forall n, size 'X^n = n.+1.\nProof. by move=> n; rewrite seq_polyXn size_ncons addn1. Qed.\n\nLemma comm_polyXn : forall p n, GRing.comm p 'X^n.\nProof. by move=> p n; apply: commr_exp; exact: comm_polyX. Qed.\n\nLemma lead_coefXn : forall n, lead_coef 'X^n = 1.\nProof. by elim=> [|n IHn]; rewrite ?lead_coef1 // exprSr lead_coef_mulX. Qed.\n\nLemma coef_Xn_mul : forall n p i, \n  ('X^n * p)`_i = if i < n then 0 else p`_(i - n).\nProof.\nmove=> n p; elim: n => [|n IHn] i; first by rewrite simp subn0.\nby rewrite exprS -mulrA coef_Xmul; case: i.\nQed.\n\nLemma coef_mulXn : forall n p i,\n  (p * 'X^n)`_i = if i < n then 0 else p`_(i - n).\nProof. by move=> n p i; rewrite comm_polyXn coef_Xn_mul. Qed.\n\n(* Expansion of a polynomial as an indexed sum *)\nLemma poly_def : forall n E, \\poly_(i < n) E i = \\sum_(i < n) (E i)%:P * 'X^i.\nProof.\nelim=> [|n IHn] E; first by rewrite big_ord0.\nrewrite big_ord_recl /= poly_cons_def addrC simp; congr (_ + _).\nrewrite (iota_addl 1 0) -map_comp IHn big_distrl /bump /=.\nby apply: eq_bigr => i _; rewrite -mulrA exprSr.  \nQed.\n\n(* Monic predicate *)\n\nDefinition monic p := lead_coef p == 1.\n\nLemma monic1 : monic 1. Proof. by rewrite /monic lead_coef1. Qed.\nLemma monicX : monic 'X. Proof. by rewrite /monic lead_coefX. Qed.\nLemma monicXn : forall n, monic 'X^n.\nProof. by move=> n; rewrite /monic lead_coefXn. Qed.\n\nLemma monic_neq0 : forall p, monic p -> p != 0.\nProof. move=> p; rewrite -lead_coef_eq0; move/eqP->; exact: nonzero1r. Qed.\n\nLemma lead_coef_monic_mul : forall p q,\n  monic p -> lead_coef (p * q) = lead_coef q.\nProof.\nmove=> p q; move/eqP=> lp1.\ncase: (eqVneq q 0) => [->|nzq]; first by rewrite simp.\nby rewrite lead_coef_proper_mul lp1 simp ?lead_coef_eq0.\nQed.\n\nLemma lead_coef_mul_monic : forall p q,\n  monic q -> lead_coef (p * q) = lead_coef p.\nProof.\nmove=> p q; move/eqP=> lq1.\ncase: (eqVneq p 0) => [->|nzp]; first by rewrite simp.\nby rewrite lead_coef_proper_mul lq1 simp ?lead_coef_eq0.\nQed.\n\nLemma size_monic_mul : forall p q,\n  monic p -> q != 0 -> size (p * q) = (size p + size q).-1.\nProof.\nmove=> p q; move/eqP=> lp1 nzq.\nby rewrite size_proper_mul // lp1 simp lead_coef_eq0.\nQed.\n\nLemma size_mul_monic : forall p q,\n  p != 0 -> monic q -> size (p * q) = (size p + size q).-1.\nProof.\nmove=> p q nzp; move/eqP=> lq1.\nby rewrite size_proper_mul // lq1 simp lead_coef_eq0.\nQed.\n\nLemma monic_mull : forall p q, monic p -> monic (p * q) = monic q.\nProof. by move=> p q mp; rewrite /monic lead_coef_monic_mul. Qed.\n\nLemma monic_mulr : forall p q, monic q -> monic (p * q) = monic p.\nProof. by move=> p q mq; rewrite /monic lead_coef_mul_monic. Qed.\n\nLemma monic_exp : forall p n, monic p -> monic (p ^+ n).\nProof.\nby move=> p [|n] mp; [exact: monic1 | elim: n => // n; rewrite monic_mull].\nQed.\n\n(* Pseudo division, defined on an arbitrary ring *)\nDefinition edivp_rec (q : {poly R})  :=\n  let sq := size q in\n  let cq := lead_coef q in\n  fix loop (n : nat) (c : R) (qq r : {poly R}) {struct n} :=\n    if size r < sq then (c, qq, r) else\n    let m := (lead_coef r)%:P * 'X^(size r - sq) in\n    let c1 := cq * c 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 n1 c1 qq1 r1 else (c1, qq1, r1).\n\nLemma edivp_mon_spec : forall p q n c qq r,\n   monic q -> let d := edivp_rec q n c qq r in\n p = qq * q + r -> p = (d.1).2 * q + d.2.\nProof.\nmove=> p q n c qq r; move/eqP=> lq1.\nelim: n => [|n IHn] /= in c qq r *; case: ltnP => Hp //= def_p.\n  by rewrite lq1 !simp /= mulr_addl addrAC addrK.\nby apply: IHn; rewrite lq1 !simp /= mulr_addl addrAC addrK.\nQed.\n\nLemma edivp_mod_spec : forall q n c (qq r : {poly R}),\n  q != 0 -> size r <= n -> size (edivp_rec q n c qq r).2 < size q.\nProof.\nmove=> q; elim=> [|n IHn] c qq r Hq Hqq /=; case: (ltnP (size r)) => [// | Hl].\n  by rewrite leqn0 in Hqq; rewrite (eqP Hqq) polySpred in Hl.\napply: IHn => //; apply: leq_size_coef => j Hj.\nrewrite coef_add coef_opp -!mulrA coef_mulC coef_Cmul coef_Xn_mul.\nmove: Hj; rewrite leq_eqVlt; case/predU1P => [<-{j} | Hj]; last first.\n  rewrite nth_default ?(leq_trans Hqq) // ?simp.\n  rewrite nth_default; first by rewrite if_same !simp oppr0.\n  by rewrite -{1}(subKn Hl) leq_sub2r // (leq_trans Hqq).\nmove: Hqq; rewrite leq_eqVlt ltnS; case/predU1P=> Hqq; last first.\n  rewrite !nth_default ?if_same ?simp ?oppr0 //.\n  by rewrite -{1}(subKn Hl) leq_sub2r // (leq_trans Hqq).\nrewrite {2}/lead_coef Hqq polySpred // subSS ltnNge leq_subr /=.\nby rewrite subKn ?addrN // -subn1 leq_sub_add add1n -Hqq.\nQed.\n\nLemma edivp_scal_spec: forall q n c (qq r : {poly R}),\n  exists m, (edivp_rec q n c qq r).1.1 = lead_coef q ^+ m * c.\nProof.\nmove=> q; elim=> [|n IHn] c qq r /=.\n  case: ifP; first by exists 0%N; rewrite mul1r.\n  by exists 1%N; rewrite expr1.\ncase: ifP => _; first by exists 0%N; rewrite mul1r.\nset c1 := _ * c; set qq1 := _ + _; set r1 := _ - _.\nby have [m ->]:= IHn c1 qq1 r1; exists m.+1; rewrite exprSr -mulrA.\nQed.\n\nDefinition edivp (p q : {poly R}) : R * {poly R} * {poly R} :=\n  if q == 0 then (1, 0, p) else edivp_rec q (size p) 1 0 p.\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.\n\nNotation \"m %/ d\" := (divp m d) (at level 40, no associativity).\nNotation \"m %% d\" := (modp m d) (at level 40, no associativity).\nNotation \"p %| q\" := (dvdp p q) (at level 70, no associativity).\n\nLemma divp_size : forall p q, size p < size q -> p %/ q = 0.\nProof.\nmove=> p q; rewrite /divp /edivp; case: eqP => Eq.\n  by rewrite Eq size_poly0.\nby case E1: (size p) => [| s] Hs /=; rewrite E1 Hs.\nQed.\n\nLemma modp_size : forall p q, size p < size q -> p %% q = p.\nProof.\nmove=> p q; rewrite /modp /edivp; case: eqP => Eq.\n  by rewrite Eq size_poly0.\nby case E1: (size p) => [| s] Hs /=; rewrite E1 Hs /=.\nQed.\n\nLemma divp_mon_spec : forall p q, monic q -> p = p %/ q * q + p %% q.\nProof.\nmove=> p q Mq.\nrewrite /divp /modp /scalp /edivp.\ncase: eqP => [->| Hq]; first by rewrite !simp.\nby apply: edivp_mon_spec; rewrite // !simp.\nQed.\n\nLemma modp_spec : forall p q, q != 0 -> size (p %% q) < size q.\nProof.\nmove=> p q Hq.\nrewrite /divp /modp /scalp /edivp.\ncase: eqP => He; first by case/negP: Hq; apply/eqP.\nby apply: edivp_mod_spec.\nQed.\n\nLemma scalp_spec : forall p q, exists m, scalp p q = lead_coef q ^+ m.\nProof.\nmove=> p q; rewrite /divp /modp /scalp /edivp.\ncase: eqP => He; first by exists 0%N.\nby have [m ->]:= (edivp_scal_spec q (size p) 1 0 p); rewrite mulr1; exists m.\nQed.\n\nLemma div0p : forall p, 0 %/ p = 0.\nProof.\nmove=> p; rewrite /divp /edivp; case: ifP => // Hp.\nby rewrite /edivp_rec !size_poly0 polySpred ?Hp.\nQed.\n\nLemma modp0 : forall p, p %% 0 = p.\nProof. by rewrite /modp /edivp eqxx. Qed.\n\nLemma mod0p : forall p, 0 %% p = 0.\nProof.\nmove=> p; rewrite /modp /edivp; case: ifP => // Hp.\nby rewrite /edivp_rec !size_poly0 polySpred ?Hp.\nQed.\n\nLemma dvdpPm : forall p q, monic q -> reflect (exists qq, p = qq * q) (q %| p).\nProof.\nmove=> p q Mq; apply: (iffP idP).\n  rewrite /dvdp; move/eqP=> Dqp.\n  by exists (p %/ q); rewrite {1}(divp_mon_spec p Mq) Dqp !simp.\ncase=> qq Dqq; rewrite /dvdp.\npose d := qq - p %/ q.\nhave Epq: p %% q = d * q.\n    rewrite mulr_addl mulNr -Dqq {2}(divp_mon_spec p Mq).\n    by rewrite -addrA addrC -addrA addNr !simp.\nhave:= modp_spec p (monic_neq0 Mq); rewrite Epq.\ncase: (eqVneq d 0) => [->|nz_p]; first by rewrite simp.\nby rewrite size_mul_monic // polySpred // ltnNge leq_addl.\nQed.\n\nLemma dvdp0: forall p, p %| 0.\nProof. move=> p; apply/eqP; exact: mod0p. Qed.\n\nLemma modpC: forall p c, c != 0 -> p %% c%:P = 0.\nProof.\nmove=> p c Hc; apply/eqP; rewrite -size_poly_eq0 -leqn0 -ltnS.\nby apply: leq_trans (modp_spec _ _) _; rewrite ?polyC_eq0 // size_polyC Hc.\nQed.\n\nLemma modp1: forall p, p %% 1 = 0.\nProof. move=> p; apply: modpC; exact: nonzero1r. Qed.\n\nLemma divp1: forall p, p %/ 1 = p.\nProof. by move=> p; rewrite {2}(divp_mon_spec p monic1) modp1 !simp. Qed. \n\nLemma dvd1p: forall p, 1 %| p.\nProof. move=> p; apply/eqP; exact: modp1. Qed.\n\nLemma modp_mon_mull : forall p q, monic q -> p * q %% q = 0.\nProof.\nmove=> p q Mq; have:= modp_spec (p * q) (monic_neq0 Mq).\npose qq := p - (p * q) %/ q.\nhave ->: (p * q) %% q = qq * q.\n  by rewrite mulr_addl {2}(divp_mon_spec (p * q) Mq) mulNr addrC addKr.\ncase: (eqVneq qq 0) => [->|nz_qq]; first by rewrite simp.\nby rewrite size_mul_monic // polySpred // ltnNge leq_addl.\nQed.\n\nLemma divp_mon_mull : forall p q, monic q -> p * q %/ q = p.\nProof.\nmove=> p q Mq.\npose qq := p - (p * q) %/ q.\ncase: (eqVneq qq 0) => [|nz_qq]; first by move/(canRL (subrK _)); rewrite simp.\nhave:= modp_spec (p * q) (monic_neq0 Mq).\nhave ->: (p * q) %% q = qq * q.\n  by rewrite mulr_addl {2}(divp_mon_spec (p * q) Mq) mulNr addrC addKr.\nby rewrite size_mul_monic // polySpred // ltnNge leq_addl.\nQed.\n\nLemma dvdp_mon_mull : forall p q, monic q -> q %| p * q.\nProof. move=> p q Mq; apply/eqP; exact: modp_mon_mull. Qed.\n\n(* Pseudo gcd *)\nDefinition gcdp 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 := 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 gcd0p : left_id 0 gcdp.\nProof.\nmove=> p; rewrite /gcdp size_poly0 lt0n size_poly_eq0 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 size_poly0 lt0n size_poly_eq0 if_neg.\nby case: ifP => /= p0; rewrite ?(eqxx, p0) // (eqP p0).\nQed.\n\nLemma gcdpE : forall p q, \n  gcdp p q = if size p < size q then gcdp (q %% p) p else gcdp (p %% q) q.\nProof.\npose gcdp_rec := fix gcdp_rec (n : nat) (pp qq : {poly R}) {struct n} := \n   let rr := pp %% qq in\n   if rr == 0 then qq else \n   if n is n1.+1 then gcdp_rec n1 qq rr else rr.\nhave Irec: forall m n p q, size q <= m -> size q <= n \n      -> size q < size p -> gcdp_rec m p q = gcdp_rec n p q.\n+ elim=> [|m Hrec] [|n] //= p q.\n  - rewrite leqn0 size_poly_eq0; move/eqP=> -> _.\n    rewrite size_poly0 lt0n size_poly_eq0 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 lt0n size_poly_eq0 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 q 0) => [->|nzq].\n    by case: n m {Sm Sn Hrec} => [|m] [|n] //=; rewrite mod0p eqxx.\n  apply: Hrec; last exact: modp_spec.\n    by rewrite -ltnS (leq_trans _ Sm) // modp_spec.\n  by rewrite -ltnS (leq_trans _ Sn) // modp_spec.\nmove=> p q; case: (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 modp_spec (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; apply: Irec => //; last exact: modp_spec.\n    by rewrite -ltnS (ltn_predK ltpq) (leq_trans _ ltpq) ?leqW // modp_spec.\n  by rewrite ltnW // modp_spec.\nmove=> leqp; rewrite modp_spec (negPf nzq) //=.\nhave p_gt0: size p > 0 by rewrite lt0n size_poly_eq0.\nrewrite -(prednK p_gt0) /=; case: eqP => [->|].\n  by case: (size q) => [|[|s]]; rewrite /= modp0 (negPf nzq) // mod0p eqxx.\nmove/eqP=> nzpq; apply: Irec => //; last exact: modp_spec.\n  by rewrite -ltnS (prednK p_gt0) (leq_trans _ leqp) // modp_spec.\nby rewrite ltnW // modp_spec.\nQed.\n\nEnd Polynomial.\n\nBind Scope ring_scope with polynomial.\nNotation \"{ 'poly' T }\" := (poly_of (Phant T)) : type_scope.\nNotation \"\\poly_ ( i < n ) E\" := (Poly (mkseq (fun i => E) n)) : ring_scope.\nNotation \"c %:P\" := (polyC c) : ring_scope.\nNotation \"'X\" := (polyX _) : ring_scope.\nNotation \"''X^' n\" := ('X ^+ n) : ring_scope.\nNotation \"m %/ d\" := (divp m d) (at level 40, no associativity) : ring_scope.\nNotation \"m %% d\" := (modp m d) (at level 40, no associativity) : ring_scope.\nNotation \"p %| q\" := (dvdp p q) (at level 70, no associativity) : ring_scope.\n\n(* Horner evaluation of polynomials *)\n\nSection EvalPolynomial.\n\nVariable R : ringType.\nImplicit Types p q : {poly R}.\nImplicit Types x a c : R.\n\nFixpoint horner s x {struct s} :=\n  if s is a :: s' then horner s' x * x + a else 0.\n\nNotation \"p .[ x ]\" := (horner (polyseq p) x) : ring_scope.\n\nLemma horner0 : forall x, (0 : {poly R}).[x] = 0.\nProof. by rewrite seq_poly0. Qed.\n\nLemma hornerC : forall c x, (c%:P).[x] = c.\nProof. by move=> c x; rewrite polyseqC; case: eqP; rewrite //= !simp. Qed.\n\nLemma hornerX : forall x, 'X.[x] = x.\nProof. by move=> x; rewrite polyseqX /= !simp. Qed.\n\nLemma horner_cons : forall p c x, (poly_cons c p).[x] = p.[x] * x + c.\nProof.\nmove=> p c x; rewrite polyseq_cons.\ncase/polyseq: p; rewrite //= !simp; exact: hornerC.\nQed.\n\nLemma horner_Poly : forall s x, (Poly s).[x] = horner s x.\nProof.\nby move=> s x; elim: s => [|a s /= <-] /=; rewrite (horner0, horner_cons).\nQed.\n\nLemma horner_coef : forall p x,\n  p.[x] = \\sum_(i < size p) p`_i * x ^+ i.\nProof.\nmove=> p x; elim: {p}(p : seq R) => /= [|a s ->]; first by rewrite big_ord0.\nrewrite big_ord_recl simp addrC big_distrl /=; congr (_ + _).\nby apply: eq_bigr => i _; rewrite -mulrA exprSr.\nQed.\n\nLemma horner_coef_wide : forall n p x,\n  size p <= n -> p.[x] = \\sum_(i < n) p`_i * x ^+ i.\nProof.\nmove=> n p x 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 : forall n E x,\n  (\\poly_(i < n) E i).[x] = \\sum_(i < n) E i * x ^+ i.\nProof.\nmove=> n E x; rewrite (@horner_coef_wide n) ?size_poly //.\nby apply: eq_bigr => i _; rewrite coef_poly ltn_ord.\nQed.\n\nLemma horner_opp : forall p x, (- p).[x] = - p.[x].\nProof.\nmove=> p x; rewrite horner_poly horner_coef -sumr_opp /=.\nby apply: eq_bigr => i _; rewrite mulNr.\nQed.\n\nLemma horner_add : forall p q x, (p + q).[x] = p.[x] + q.[x].\nProof.\nmove=> p q x; rewrite horner_poly; set m := maxn _ _.\nrewrite !(@horner_coef_wide m) ?leq_maxr ?leqnn ?orbT // -big_split /=.\nby apply: eq_bigr => i _; rewrite -mulr_addl.\nQed.\n\nLemma horner_sum : forall I r (P : pred I) F x,\n  (\\sum_(i <- r | P i) F i).[x] = \\sum_(i <- r | P i) (F i).[x].\nProof.\nmove=> I r P F x; pose appx p := p.[x].\napply: (big_morph appx) => [p q|]; [exact: horner_add | exact: horner0].\nQed.\n\nLemma horner_Cmul : forall c p x, (c%:P * p).[x] = c * p.[x].\nProof.\nmove=> c p x.\nelim/(@poly_ind R): p => [|p d IHp]; first by rewrite !(simp, horner0).\nrewrite mulr_addr -polyC_mul mulrA -!poly_cons_def !horner_cons IHp.\nby rewrite -mulrA -mulr_addr.\nQed.\n\nDefinition com_coef p (x : R) := forall i, p`_i * x = x * p`_i.\n\nDefinition com_poly p x := x * p.[x] = p.[x] * x.\n\nLemma com_coef_poly : forall p x, com_coef p x -> com_poly p x.\nProof.\nmove=> p x com; rewrite /com_poly !horner_coef big_distrl big_distrr /=.\nby apply: eq_bigr => i _; rewrite /= mulrA -com -!mulrA commr_exp.\nQed.\n\nLemma com_poly0 : forall x, com_poly 0 x.\nProof. by move=> *; rewrite /com_poly !horner0 !simp. Qed.\n\nLemma com_poly1 : forall x, com_poly 1 x.\nProof. by move=> *; rewrite /com_poly !hornerC !simp. Qed.\n\nLemma com_polyX : forall x, com_poly 'X x.\nProof. by move=> *; rewrite /com_poly !hornerX. Qed.\n\nLemma horner_mul_com : forall p q x,\n  com_poly q x -> (p * q).[x] = p.[x] * q.[x].\nProof.\nmove=> p q x com_qx.\nelim/(@poly_ind R): p => [|p c IHp]; first by rewrite !(simp, horner0).\nrewrite mulr_addl -poly_cons_def horner_cons mulr_addl -!mulrA.\nrewrite com_qx -comm_polyX !mulrA -{}IHp -[_ * 'X]addr0 -poly_cons_def.\nby rewrite horner_add horner_cons simp horner_Cmul.\nQed.\n\nLemma horner_exp_com : forall p x n, com_poly p x -> (p ^+ n).[x] = p.[x] ^+ n.\nProof.\nmove=> p x n com_px; elim: n => [|n IHn]; first by rewrite hornerC.\nby rewrite -addn1 !exprn_addr !expr1 -IHn horner_mul_com.\nQed.\n\nLemma hornerXn : forall x n, ('X^n).[x] = x ^+ n.\nProof. by move=> x n; rewrite horner_exp_com /com_poly hornerX. Qed.\n\nDefinition horner_lin_com :=\n  (horner_add, horner_opp, hornerX, hornerC, horner_cons,\n   simp, horner_Cmul, (fun p x => horner_mul_com p (com_polyX x))).\n\nLemma factor0 : forall c, ('X - c%:P).[c] = 0.\nProof. by move=> c; rewrite !horner_lin_com addrN. Qed.\n\nLemma seq_factor : forall c, 'X - c%:P = [:: - c; 1] :> seq R.\nProof.\nmove=> c; rewrite -['X]mul1r -polyC_opp -poly_cons_def.\nby rewrite polyseq_cons size_poly1 polyseq1.\nQed.\n\nLemma monic_factor : forall c, monic ('X - c%:P).\nProof. by move=> c; rewrite /monic /lead_coef seq_factor. Qed.\n\nTheorem factor_theorem : forall p c,\n  reflect (exists q, p = q * ('X - c%:P)) (p.[c] == 0).\nProof.\nmove=> p c; apply: (iffP eqP) => [root_p_c | [q -> {p}]]; last first.\n  by rewrite horner_mul_com /com_poly factor0 ?simp.\nset f := 'X - _; exists (p %/ f). \nhave mf: monic f by exact: monic_factor.\nmove: (divp_mon_spec p mf) root_p_c => def_p; rewrite {1 2}def_p.\nhave:= modp_spec p (monic_neq0 mf); move: (_ %% _) => c1.\nrewrite seq_factor ltnS; move/size1_polyC->.\nhave cfc: com_poly f c by rewrite /com_poly factor0 !simp.\nby rewrite !(factor0, horner_mul_com _ cfc, horner_lin_com) => ->; rewrite simp.\nQed.\n\n\nLemma root_factor_theorem : forall (p : {poly R}) x,\n  p.[x] == 0 = ('X - x%:P %| p).\nProof.\nmove=> p x; apply/factor_theorem/dvdpPm; first exact: monic_factor.\n  by case=> p1 ->; exists p1.\nby case=> p1 ->; exists p1.\nQed.\n\n\nEnd EvalPolynomial.\n\nNotation \"p .[ x ]\" := (horner p x) : ring_scope.\n\nSection PolynomialComRing.\n\nVariable R : comRingType.\n\nLemma horner_mul : forall (p q : {poly R}) x, \n  (p * q).[x] = p.[x] * q.[x].\nProof. move=> p q x; rewrite horner_mul_com //; exact: mulrC. Qed.\n\nLemma horner_exp : forall (p : {poly R}) x n, (p ^+ n).[x] = p.[x] ^+ n.\nProof. move=> p x n; rewrite horner_exp_com //; exact: mulrC. Qed.\n\nDefinition horner_lin :=\n  (horner_add, horner_opp, hornerX, hornerC, horner_cons,\n   simp, horner_Cmul, horner_mul).\n\nLemma poly_mulC : forall p1 p2 : {poly R}, p1 * p2 = p2 * p1.\nProof.\nmove=> p1 p2; apply/polyP=> i; rewrite coef_mul coef_mul_rev.\nby apply: eq_bigr => j _; rewrite mulrC.\nQed.\n\nCanonical Structure poly_comRingType := Eval hnf in ComRingType poly_mulC.\nCanonical Structure polynomial_comRingType :=\n  Eval hnf in [comRingType of polynomial R for poly_comRingType].\n\n(* Pseudo-division in a commutative setting *)\n\nLemma edivp_spec: forall (p q: {poly R}) n c qq r,\n  let d := edivp_rec q n c qq r in\n  c%:P * p = qq * q + r -> (d.1).1%:P * p = (d.1).2 * q + d.2.\nProof.\nmove=> p q; elim=> [| n Hrec] c qq r /=; case: ltnP => Hp //=.\n  rewrite polyC_mul -mulrA => ->.\n  rewrite mulr_addl mulr_addr !mulrA -!addrA !(mulrC _%:P).\n  by congr (_ + _) => //; rewrite addrC -addrA addrC -addrA addKr.\nmove=> HH; apply: Hrec.\nrewrite polyC_mul -mulrA HH.\nrewrite mulr_addl mulr_addr !mulrA -!addrA !(mulrC _%:P).\nby congr (_ + _) => //; rewrite addrC -addrA addrC -addrA addKr.\nQed.\n\nLemma divp_spec: forall p q : {poly R}, (scalp p q)%:P * p = p %/ q * q + p %% q.\nProof.\nmove=> p q.\nrewrite /divp /modp /scalp /edivp.\ncase: eqP => [->| Hq]; first by rewrite !simp.\nby apply: edivp_spec; rewrite !simp.\nQed.\n\nEnd PolynomialComRing.\n\nSection PolynomialIdomain.\n\nVariable R : idomainType.\nImplicit Types x y : R.\nImplicit Types p q : {poly R}.\n\nLemma size_mul_id : forall p q,\n  p != 0 -> q != 0 -> size (p * q) = (size p + size q).-1.\nProof.\nmove=> p q nzp nzq; apply: size_proper_mul.\nby rewrite mulf_eq0 !lead_coef_eq0 negb_or nzp nzq.\nQed.\n\nLemma size_polyC_mul: forall c p, c != 0 -> size (c%:P * p) = size p.\nProof.\nmove=> c p Ec; case: (eqVneq p 0) => [-> | nzp]; first by rewrite simp.\nby rewrite size_mul_id ?polyC_eq0 // size_polyC Ec.\nQed.\n\nLemma lead_coef_mul_id: forall p q, \n  lead_coef (p * q) = lead_coef p * lead_coef q.\nProof.\nmove=> p q.\ncase: (eqVneq p 0) => [->|nzp]; first by rewrite !(simp, lead_coef0).\ncase: (eqVneq q 0) => [->|nzq]; first by rewrite !(simp, lead_coef0).\nby rewrite lead_coef_proper_mul // mulf_eq0 !lead_coef_eq0 negb_or nzp nzq.\nQed.\n\nLemma scalp_id: forall p q, scalp p q != 0.\nProof.\nmove=> p q; case: (eqVneq q 0) => [->|nzq]. \n  by rewrite /scalp /edivp eqxx nonzero1r.\nby case (scalp_spec p q) => m ->; rewrite expf_neq0 ?lead_coef_eq0.\nQed.\n\n(* idomain structure on poly *)\n\nLemma poly_idomainMixin : forall p q, p * q = 0 -> (p == 0) || (q == 0).\nProof.\nmove=> p q pq0; apply/norP=> [[p_nz q_nz]]; move/eqP: (size_mul_id p_nz q_nz).\nrewrite eq_sym pq0 size_poly0 -leqn0 -subn1 leq_sub_add leqNgt -addnS.\nby rewrite leq_add // lt0n size_poly_eq0.\nQed.\n\nDefinition poly_unit : pred {poly R} :=\n  fun p => (size p == 1%N) && GRing.unit p`_0.\n\nDefinition poly_inv p := if poly_unit p then (p`_0)^-1%:P else p.\n\nLemma poly_mulVp : {in poly_unit, left_inverse 1 poly_inv *%R}.\nProof.\nmove=> p Up; rewrite /poly_inv [poly_unit p]Up.\ncase/andP: Up => szp1 Up.\nby rewrite {2}[p]size1_polyC ?(eqP szp1) // -polyC_mul mulVr.\nQed.\n\nLemma poly_intro_unit : forall p q, q * p = 1 -> poly_unit p.\nProof.\nmove=> p q pq1; have: size (q * p) == 1%N by rewrite pq1 size_poly1.\ncase: (eqVneq p 0) => [-> | p_nz]; first by rewrite mulr0 size_poly0.\ncase: (eqVneq q 0) => [-> | q_nz]; first by rewrite mul0r size_poly0.\nrewrite size_mul_id //.\nrewrite -1?[size p]prednK -1?[size q]prednK ?lt0n ?size_poly_eq0 //.\nrewrite addnS eqSS addn_eq0 -!subn1 !subn_eq0.\ncase/andP=> szq1 szp1; rewrite /poly_unit eqn_leq szp1 polySpred //.\napply/unitrP; exists q`_0; rewrite 2!mulrC.\nmove/(congr1 (fun r : {poly R} => r`_0)): pq1.\nby rewrite {1}(size1_polyC szp1) {1}(size1_polyC szq1) -polyC_mul !coefC.\nQed.\n\nLemma poly_inv_out : {in predC poly_unit, poly_inv =1 id}.\nProof. by move=> p nUp; rewrite /poly_inv -if_neg [~~ _]nUp. Qed.\n\nDefinition poly_unitRingMixin :=\n  ComUnitRingMixin poly_mulVp poly_intro_unit poly_inv_out.\n\nCanonical Structure poly_unitRingType :=\n   Eval hnf in UnitRingType poly_unitRingMixin.\n\nCanonical Structure poly_comUnitRingType :=\n   Eval hnf in ComUnitRingType poly_unitRingMixin.\n\nCanonical Structure poly_idomainType :=\n   Eval hnf in IdomainType poly_idomainMixin.\n\nCanonical Structure polynomial_unitRingType :=\n   Eval hnf in [unitRingType of polynomial R for poly_unitRingType].\n\nCanonical Structure polynomial_comUnitRingType :=\n   Eval hnf in [comUnitRingType of polynomial R for poly_comUnitRingType].\n\nCanonical Structure polynomial_idomainType :=\n   Eval hnf in [idomainType of polynomial R for poly_idomainType].\n\nLemma modp_mull : forall p q, p * q %% q = 0.\nProof.\nmove=> p q; pose qq := (scalp (p* q) q)%:P * p - (p * q) %/ q.\nhave Eq: (p * q) %% q = qq * q.\n   by rewrite mulr_addl -mulrA divp_spec mulNr addrC addKr.\ncase: (eqVneq q 0) => [-> | nz_q]; first by rewrite modp0 simp.\ncase: (eqVneq qq 0) => [qq0 | nz_qq]; first by rewrite Eq qq0 simp.\nhave:= modp_spec (p * q) nz_q.\nby rewrite Eq size_mul_id // polySpred // ltnNge leq_addl.\nQed.\n\nLemma modpp : forall p, p %% p = 0.\nProof. by move=> p; rewrite -{1}(mul1r p) modp_mull. Qed.\n\nLemma dvdpp : forall p, p %| p.\nProof. move=> p; apply/eqP; exact: modpp. Qed.\n\nLemma divp_mull : forall p q, q != 0 -> p * q %/ q = (scalp (p * q) q)%:P * p.\nProof.\nmove=> p q nz_q.\npose qq := (scalp (p* q) q)%:P * p - (p * q) %/ q.\nhave Eq: (p * q) %% q = qq * q.\n  by rewrite mulr_addl -mulrA divp_spec mulNr addrC addKr.\ncase: (eqVneq qq 0) => [| nz_qq].\n  by move/(canRL (subrK _)); rewrite simp.\nhave:= modp_spec (p * q) nz_q.\nby rewrite Eq size_mul_id // polySpred // ltnNge leq_addl.\nQed.\n\nLemma dvdpPc : forall p q, \n  reflect (exists c, exists qq, c != 0 /\\ c%:P * p = qq * q) (q %| p).\nProof.\nmove=> /= p q; apply: (iffP idP) => [|[c [qq [nz_c def_qq]]]].\n  move/(p %% q =P 0) => dv_qp; exists (scalp p q); exists (p %/ q).\n  by rewrite scalp_id divp_spec dv_qp !simp.\nhave Ecc: c%:P != 0 by rewrite polyC_eq0.\ncase: (eqVneq p 0) => [->|nz_p]; first by rewrite dvdp0.\npose p1 : {poly R} := (scalp p q)%:P  * qq - c%:P * (p %/ q).\nhave E1: c%:P * (p %% q) = p1 * q.\n  rewrite mulr_addl {1}mulNr -mulrA -def_qq mulrCA.\n  by rewrite divp_spec mulr_addr addrAC -mulrA addrN simp.\nrewrite /dvdp; apply/idPn=> m_nz.\nhave: p1 * q != 0 by rewrite -E1 mulf_neq0.\nrewrite mulf_eq0; case/norP=> p1_nz q_nz; have:= modp_spec p q_nz.\nrewrite -(size_polyC_mul _ nz_c) E1 size_mul_id //.\nby rewrite polySpred // ltnNge leq_addl.\nQed.\n\nLemma size_dvdp : forall p1 p2, p2 != 0 -> p1 %| p2 -> size p1 <= size p2.\nProof.\nmove=> p1 p2 Ep2; case/dvdpPc => c1 [q1 [Ec1 Ec1p2]].\nhave: q1 * p1 != 0 by rewrite -Ec1p2 -!size_poly_eq0 size_polyC_mul in Ep2 *. \nrewrite mulf_eq0; case/norP=> Eq1 Ep1.\nrewrite -(size_polyC_mul p2 Ec1) Ec1p2 size_mul_id //.\nby rewrite (polySpred Eq1) leq_addl.\nQed.\n\nLemma dvdp_mull : forall d m n : {poly R}, d %| n -> d %| m * n.\nProof.\nmove=> d m n; case/dvdpPc => c [q [Hc Hq]].\napply/dvdpPc; exists c; exists (m * q); split => //.\nby rewrite -mulrA -Hq !mulrA [m * _]mulrC.\nQed.\n\nLemma dvdp_mulr: forall d m n: {poly R}, d %| m -> d %|  m * n.\nProof. by move=> d m n d_m; rewrite mulrC dvdp_mull. Qed.\n\nLemma dvdp_mul: forall d1 d2 m1 m2 : {poly R}, \n  d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2.\nProof.\nmove=> d1 d2 m1 m2; case/dvdpPc=> c1 [q1 [Hc1 Hq1]];\n  case/dvdpPc=> c2 [q2 [Hc2 Hq2]].\napply/dvdpPc; exists (c1 * c2); exists (q1 * q2); split.\n  by rewrite mulf_neq0.\nby rewrite polyC_mul mulrCA -!mulrA mulrCA mulrA Hq1 Hq2 mulrCA -!mulrA mulrCA.\nQed.\n\nLemma dvdp_trans: forall n d m : {poly R}, d %| n -> n %| m -> d %| m.\nProof. \nmove=> n d m; case/dvdpPc=> c1 [q1 [Hc1 Hq1]];\n  case/dvdpPc=> c2 [q2 [Hc2 Hq2]].\napply/dvdpPc; exists (c2 * c1); exists (q2 * q1); split.\n  by apply: mulf_neq0.\nrewrite -mulrA -Hq1 [_ * n]mulrC mulrA -Hq2 polyC_mul -!mulrA; congr (_ * _).\nby rewrite mulrC.\nQed.\n\nLemma dvdp_addr : forall m d n : {poly R},\n  d %| m -> (d %| m + n) = (d %| n).\nProof.\nmove=> n d m; case/dvdpPc=> c1 [q1 [Hc1 Hq1]].\napply/dvdpPc/dvdpPc; case=> c2 [q2 [Hc2 Hq2]].\n  exists (c1 * c2); exists (c1%:P * q2 - c2%:P * q1).\n  rewrite mulf_neq0 // mulr_addl mulNr -2!mulrA -Hq1 -Hq2 (mulrCA c2%:P).\n  by rewrite !mulrA -polyC_mul addrC mulr_addr addKr.\nexists (c1 * c2); exists (c1%:P * q2 + c2%:P * q1).\nrewrite mulf_neq0 // mulr_addl -2!mulrA -Hq1 -Hq2 (mulrCA c2%:P).\nby rewrite !mulrA -polyC_mul addrC -mulr_addr.\nQed.\n\nLemma dvdp_addl : forall n d m : {poly R},\n  d %| n -> (d %| m + n) = (d %| m).\nProof. by move=> n d m; rewrite addrC; exact: dvdp_addr. Qed.\n\nLemma dvdp_add : forall d m n: {poly R}, d %| m -> d %| n -> d %| m + n.\nProof. by move=> n d m; move/dvdp_addr->. Qed.\n\nLemma dvdp_add_eq : forall d m n: {poly R},\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 : forall d m n: {poly R},\n  d %| m -> (d %| m - n) = (d %| n).\nProof. by move=> *; apply dvdp_add_eq; rewrite -addrA addNr simp. Qed.\n\nLemma dvdp_subl : forall d m n: {poly R},\n  d %| n -> (d %| m - n) = (d %| m).\nProof. by move=> d m n Hn; rewrite -(dvdp_addl _ Hn) subrK. Qed.\n\nLemma dvdp_sub : forall d m n: {poly R}, d %| m -> d %| n -> d %| m - n.\nProof.  by move=> d n m Dm Dn; rewrite dvdp_subl. Qed.\n\nLemma dvdp_mod : forall d m n : {poly R},\n  d %| m -> (d %| n) = (d %| n %% m).\nProof.\nmove=> d n m; case/dvdpPc => c1 [q1 [Ec1 Eq1]].\napply/dvdpPc/dvdpPc=> [] [] c2 [q2 [Ec2 Eq2]]; last first.\n  exists (c1 * c2 * scalp m n).\n  exists (c2%:P * (m  %/ n) * q1 + c1%:P * q2); split.\n    by rewrite !mulf_neq0 ?scalp_id.\n  rewrite polyC_mul -mulrA divp_spec polyC_mul mulr_addr -!mulrA.\n  by rewrite Eq2 2!(mulrCA c1%:P) Eq1 !mulrA -mulr_addl.\nexists (c1 * c2); exists (c1%:P * (scalp m n)%:P * q2 - c2%:P * (m %/ n) * q1).\nrewrite mulf_neq0 // mulr_addl mulNr -!mulrA -Eq1 -Eq2.\nrewrite -{1}(mulrCA c2%:P) divp_spec -addrC -2!{1}(mulrCA c1%:P).\nby rewrite 2!{1}(mulrA c1%:P) -polyC_mul mulr_addr addKr.\nQed.\n\nLemma gcdpp : idempotent (@gcdp R).\nProof. by move=> p; rewrite gcdpE ltnn modpp gcd0p. Qed.\n\nLemma dvdp_gcd2 : forall m n : {poly R}, (gcdp m n %| m) && (gcdp m n %| n).\nProof.\nmove=> m n.\nelim: {m n}minn {-2}m {-2}n (leqnn (minn (size n) (size m))) => [|r Hrec] m n.\n  rewrite leq_minl !leqn0 !size_poly_eq0.\n  by case/pred2P=> ->; rewrite (gcdp0, gcd0p) dvdpp dvdp0.\ncase: (eqVneq m 0) => [-> _|nz_m]; first by rewrite gcd0p dvdpp dvdp0.\ncase: (eqVneq n 0) => [->|nz_n]; first by rewrite gcdp0 dvdpp dvdp0.\nrewrite gcdpE minnC /minn; case: ltnP => [lt_mn | le_nm] le_nr.\n  suff: minn (size m) (size (n %% m)) <= r.\n    by move/Hrec; case/andP => E1 E2; rewrite E2 (dvdp_mod _ E2).\n  rewrite leq_minl orbC -ltnS (leq_trans _ le_nr) //.\n  by rewrite (leq_trans (modp_spec _ nz_m)) // leq_minr ltnW // leqnn.\nsuff: minn (size n) (size (m %% n)) <= r.\n  by move/Hrec; case/andP => E1 E2; rewrite E2 andbT (dvdp_mod _ E2).\nrewrite leq_minl orbC -ltnS (leq_trans _ le_nr) //.\nby rewrite (leq_trans (modp_spec _ nz_n)) // leq_minr leqnn.\nQed.\n\nLemma dvdp_gcdl : forall m n : {poly R}, gcdp m n %| m.\nProof. by move=> m n; case/andP: (dvdp_gcd2 m n). Qed.\n\nLemma dvdp_gcdr : forall m n : {poly R}, gcdp m n %| n.\nProof. by move=> m n; case/andP: (dvdp_gcd2 m n). Qed.\n\nLemma dvdp_gcd : forall p m n: {poly R}, p %| gcdp m n = (p %| m) && (p %| n).\nProof.\nmove=> p m n; apply/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 leq_minl !leqn0 !size_poly_eq0.\n  by case/pred2P=> ->; rewrite (gcdp0, gcd0p).\ncase: (eqVneq m 0) => [-> _|nz_m]; first by rewrite gcd0p dvdp0.\ncase: (eqVneq n 0) => [->|nz_n]; first by rewrite gcdp0 dvdp0.\nrewrite gcdpE minnC /minn; case: ltnP => Cnm le_r dv_m dv_n.\n  apply: Hrec => //; last by rewrite -(dvdp_mod _ dv_m).\n  rewrite leq_minl orbC -ltnS (leq_trans _ le_r) //.\n  by rewrite (leq_trans (modp_spec _ nz_m)) // leq_minr ltnW // leqnn.\napply: Hrec => //; last by rewrite -(dvdp_mod _ dv_n).\nrewrite leq_minl orbC -ltnS (leq_trans _ le_r) //.\nby rewrite (leq_trans (modp_spec _ nz_n)) // leq_minr leqnn.\nQed.\n\n(* Equality modulo constant factors *)\n\nDefinition eqp (R : ringType)(p1 p2: {poly R}) :=  (p1 %| p2) && (p2 %| p1).\n\nNotation \"p1 '%=' p2\" := (eqp p1 p2)\n  (at level 70, no associativity).\n\nLemma eqpP: forall m n: {poly R},\n  reflect (exists c1, exists c2, [/\\ c1 != 0, c2 != 0 & c1%:P * m = c2%:P * n])\n          (m %= n).\nProof.\nmove=> m n; apply: (iffP idP) => [|[c1 [c2 [nz_c1 nz_c2 eq_cmn]]]]; last first.\n  by apply/andP; split; apply/dvdpPc;\n      [exists c2; exists c1%:P | exists c1; exists c2%:P].\ncase/andP; case/dvdpPc=> /= c1 [q1 [Hc1 Hq1]].\ncase/dvdpPc=> /= c2 [q2 [Hc2 Hq2]].\ncase: (eqVneq m 0) => [m0 | m_nz].\n  by do 2!exists c1; rewrite Hq1 m0 !simp.\nhave def_q12: q1 * q2 = (c1 * c2)%:P.\n  by apply: (mulIf m_nz); rewrite polyC_mul -!mulrA mulrCA -Hq1 mulrCA -Hq2.\nhave: q1 * q2 != 0 by rewrite def_q12 -size_poly_eq0 size_polyC mulf_neq0.\nrewrite mulf_eq0; case/norP=> nz_q1 nz_q2.\nexists c2; exists q2`_0; rewrite Hc2 -polyC_eq0 -size1_polyC //.\nhave:= size_mul_id nz_q1 nz_q2; rewrite def_q12 size_polyC mulf_neq0 //=.\nby rewrite polySpred // => ->; rewrite leq_addl.\nQed.\n\nLemma eqpxx: forall p, p %= p.\nProof. by move=> p; rewrite /eqp dvdpp. Qed. \n\nLemma eqp_sym: forall p1 p2, (p1 %= p2) = (p2 %= p1).\nProof. by move=> p1 p2; rewrite /eqp andbC. Qed.\n\nLemma eqp_trans : forall p1 p2 p3, p1 %= p2 -> p2 %= p3 -> p1 %= p3.\nProof.\nmove=> p1 p2 p3; case/andP => Dp1 pD1; case/andP => Dp2 pD2.\nby rewrite /eqp (dvdp_trans Dp1) // (dvdp_trans pD2).\nQed.\n\nLemma eqp0E : 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 size_eqp: forall p1 p2, p1 %= p2 -> size p1 = size p2.\nProof.\nmove=> p1 p2.\ncase: (@eqP _ p2 0); move/eqP => Ep2.\n  by rewrite (eqP Ep2) eqp0E; move/eqP->.\nrewrite eqp_sym; case: (@eqP _ p1 0); move/eqP => Ep1.\n  by rewrite (eqP Ep1) eqp0E; move/eqP->.\nby case/andP => Dp1 Dp2; apply: anti_leq; rewrite !size_dvdp.\nQed.\n\n(* Now we can state that gcd is commutative modulo a factor *)\nLemma gcdpC: forall p1 p2, gcdp p1 p2 %= gcdp p2 p1.\nProof.\nby move=>p1 p2; rewrite /eqp !dvdp_gcd !dvdp_gcdl !dvdp_gcdr.\nQed.\n\nEnd PolynomialIdomain.\n\n\nSection MaxRoots.\n\nVariable R : unitRingType.\n\nDefinition roots (p : {poly R}) : pred R := fun x => p.[x] == 0.\n\nDefinition diff_root (x y : R) := (x * y == y * x) && GRing.unit (y - x).\n\nFixpoint uniq_roots (rs : seq R) {struct rs} :=\n  if rs is x :: rs' then all (diff_root x) rs' && uniq_roots rs' else true.\n\nTheorem max_ring_poly_roots : forall (p : {poly R}) rs,\n  p != 0 -> all (roots p) rs -> uniq_roots rs -> size rs < size p.\nProof.\nmove=> p rs; elim: rs p => [|x rs IHrs] p nzp /=; first by rewrite polySpred.\ncase/andP=> p_x p_rs; case/andP=> x_rs Urs.\ncase/factor_theorem: p_x => q def_p.\nhave nzq: q != 0 by apply: contra nzp => q0; rewrite def_p (eqP q0) mul0r.\nhave ->: size p = (size q).+1.\n  by rewrite def_p size_mul_monic ?monic_factor ?seq_factor //= addnC.\napply: IHrs Urs => //; apply/allP=> y rs_y.\ncase/andP: (allP x_rs _ rs_y) => cxy Uxy.\nhave:= allP p_rs _ rs_y; rewrite /roots def_p horner_mul_com; last first.\n  by rewrite /com_poly !horner_lin_com mulr_addl mulr_addr mulrN mulNr (eqP cxy).\nby rewrite !horner_lin_com (can2_eq (mulrK Uxy) (divrK Uxy)) mul0r.\nQed.\n\nEnd MaxRoots.\n\nTheorem max_poly_roots : forall (F : fieldType) (p : polynomial F) rs,\n  p != 0 -> all (roots p) rs -> uniq rs -> size rs < size p.\nProof.\nmove=> F p rs nzp p_rs Urs; apply: max_ring_poly_roots nzp p_rs _ => {p}//.\nelim: rs Urs => //= x rs IHrs; case/andP=> rs_x; move/IHrs->; rewrite andbT.\napply/allP=> y rs_y; rewrite /diff_root mulrC eqxx unitfE.\nby rewrite (can2_eq (subrK _) (addrK _)) add0r; apply: contra rs_x; move/eqP<-.\nQed.\n\n", "meta": {"author": "Wassasin", "repo": "ssreflect", "sha": "45cf056aa48bec1e7e2bbb77cb4458d4bddf43e4", "save_path": "github-repos/coq/Wassasin-ssreflect", "path": "github-repos/coq/Wassasin-ssreflect/ssreflect-45cf056aa48bec1e7e2bbb77cb4458d4bddf43e4/theories/poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768094082276, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.6931342677123925}}
{"text": "Require Export Arith.\nRequire Export ArithRing.\nRequire Export Omega.\nRequire Export Wf_nat.\nParameter div_it : forall (n m : nat), 0 < m ->  nat * nat.\n \nAxiom\n   div_it_fix_eqn :\n   forall (n m : nat) (h : 0 < m),\n    div_it n m h = match le_gt_dec m n with\n                     left H => let (q, r) := div_it (n - m) m h in (S q, r)\n                    | right H => (0, n)\n                   end.\n \nTheorem div_it_correct1:\n forall (m n : nat) (h : 0 < n),\n  m = fst (div_it m n h) * n + snd (div_it m n h).\nProof.\nintros m; elim m  using (well_founded_ind lt_wf).\nintros m' Hrec n h; rewrite div_it_fix_eqn.\ncase (le_gt_dec n m'); intros H; trivial.\npattern m' at 1; rewrite (le_plus_minus n m'); auto.\npattern (m' - n) at 1.\nrewrite Hrec with (m' - n) n h; auto with arith.\ncase (div_it (m' - n) n h); simpl; auto with arith.\nQed.\n \nTheorem div_it_correct2:\n forall (m n : nat) (h : 0 < n),  (snd (div_it m n h) < n).\nintros m; elim m  using (well_founded_ind lt_wf).\nintros m' Hrec n h; rewrite div_it_fix_eqn.\ncase (le_gt_dec n m'); intros H.\nassert (Hlt: m'-n < m').\nauto with arith.\ngeneralize (Hrec (m'- n) Hlt n h); case (div_it (m'-n) n h); simpl; auto.\nsimpl; 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/gen-rec/SRC/div_it_companion2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6930890592884121}}
{"text": "Require Classical.\n\nModule ClassicUtils.\n  Import Classical.\n  Lemma contra : forall (P Q : Prop), ((P -> Q) <-> ((not Q) -> (not P))).\n    Proof.\n      split.\n      - intro. eapply imply_to_or in H. destruct H as [Hp | Hq].\n        + intro. trivial.\n        + intro. eauto.\n      - intro. eapply imply_to_or in H. destruct H as [Hq | Hp].\n        + apply NNPP in Hq. intro. apply Hq.\n        + intro. unfold not in Hp. exfalso. apply Hp. apply H.\n    Qed.\n\n    Lemma NNPP_inv : forall (P : Prop), P <-> (not (not P)).\n      Proof.\n        intros.\n        split.\n        - intro. unfold not. intro. elim H0. exact H.\n        - eapply NNPP.\n      Qed.\nEnd ClassicUtils.\n \n", "meta": {"author": "matteobusi", "repo": "stv", "sha": "dbe11dace0353b185d7aba84788d440e1ac05f39", "save_path": "github-repos/coq/matteobusi-stv", "path": "github-repos/coq/matteobusi-stv/stv-dbe11dace0353b185d7aba84788d440e1ac05f39/ClassicUtils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894548800271, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.693089048732188}}
{"text": "Require Import Arith.\n\nGoal forall m n : nat, (n * 10) + m = (10 * n) + m.\nProof.\nintros.\napply (NPeano.Nat.add_cancel_r (n * 10) (10 * n) m).\nrewrite <- mult_comm. \nreflexivity.\nQed.\n", "meta": {"author": "ashiato45", "repo": "CoqEx2014", "sha": "83750632bf6a78db93ed493a739b4aeae8505df1", "save_path": "github-repos/coq/ashiato45-CoqEx2014", "path": "github-repos/coq/ashiato45-CoqEx2014/CoqEx2014-83750632bf6a78db93ed493a739b4aeae8505df1/2/8_rewrite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6930779254151339}}
{"text": "Require Import ZArith micromega.Lia.\n\nFrom BY Require Import Zpower_nat AppendixE PadicVal.\n\nLocal Open Scope Z.\n\nFixpoint Rtail R0 R1 i {struct i} :=\n  match i with\n  | 0%nat => R0\n  | S j => if R1 =? 0 then 0 else Rtail R1 (- ((split2 R0) mod2 R1) / 2 ^+ (ord2 R1)) j\n  end.\n\nLemma Rtail_S R0 R1 i :\n  Rtail R0 R1 (S i) = if R1 =? 0 then 0 else Rtail R1 (- ((split2 R0) mod2 R1) / 2 ^+ (ord2 R1)) i.\nProof. reflexivity. Qed.\n\nLemma Rtail_R_aux R0 R1 i j :\n  Rtail (R_ R0 R1 i) (R_ R0 R1 (S i)) j = R_ R0 R1 (j + i).\nProof.\n  revert R0 R1 i; induction j; intros R0 R1 i.\n  - reflexivity.\n  - rewrite Rtail_S.\n    destruct (R_ R0 R1 (S i) =? 0) eqn:E.\n    + symmetry; eapply R_zero'. apply Z.eqb_eq in E. apply E. lia.\n    + rewrite <- R_S_S' by assumption. rewrite IHj. apply f_equal. lia. Qed.\n\nLemma Rtail_R R0 R1 i :\n  Rtail R0 R1 i = R_ R0 R1 i.\nProof.\n  replace R0 with (R_ R0 R1 0) at 1 by reflexivity.\n  replace R1 with (R_ R0 R1 1) at 2 by reflexivity. rewrite Rtail_R_aux.\n  apply f_equal; lia. Qed.\n", "meta": {"author": "bshvass", "repo": "by-inversion", "sha": "281c10e6435a86e39b2c6e1829aa874e45147140", "save_path": "github-repos/coq/bshvass-by-inversion", "path": "github-repos/coq/bshvass-by-inversion/by-inversion-281c10e6435a86e39b2c6e1829aa874e45147140/src/Rtail.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6929781751187888}}
{"text": "Require Import Coq.micromega.Lia.\nRequire Import Coq.Init.Nat.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List.\nLocal Open Scope Z_scope.\n\nRequire Import Crypto.Algebra.Nsatz.\nRequire Import Crypto.Arithmetic.Core.\nRequire Import Crypto.Util.LetIn Crypto.Util.CPSUtil.\nRequire Import Crypto.Util.Tuple Crypto.Util.ListUtil.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Decidable Crypto.Util.ZUtil.\nRequire Import Crypto.Util.NatUtil.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\nLocal Notation \"A ^ n\" := (tuple A n) : type_scope.\n\n(***\n\nArithmetic on bignums that handles carry bits; this is useful for\nsaturated limbs. Compatible with mixed-radix bases.\n\nUses \"columns\" representation: a bignum has type [tuple (list Z) n].\nAssociated with a weight function w, the bignum B represents:\n\n    \\sum_{i=0}^{n}{w[i] * sum{B[i]}}\n\nExample: ([a21, a20],[],[a0]) with weight function (fun i => 10^i)\nrepresents\n\n    a0 + 10*0 + 100 * (a20 + a21)\n\nIf you picture this representation with the weights on the bottom and\nthe terms in each list stacked above the corresponding weight,\n\n                a20\n    a0          a21\n    ---------------\n     1    10    100\n\nit's easy to see how the lists can be called \"columns\".\n\nThis is a particularly useful representation for adding partial\nproducts after multiplication, particularly when we want to do this\nusing a carrying add. We want to add together the terms from each\ncolumn, accumulating the carries together along the way. Then we want\nto add the carry accumulator to the next column, and repeat, producing\na [tuple Z n] as output. This operation is called \"compact\".\n\nAs an example, let's compact the product of 571 and 645 in base 10.\nAt first, the partial products look like this:\n\n\n                   1*6\n            1*4    7*4     7*6\n     1*5    7*5    5*5     5*4      5*6\n    ------------------------------------\n       1     10    100    1000    10000\n\n                     6\n              4     28      42\n       5     35     25      20       30\n    ------------------------------------\n       1     10    100    1000    10000\n\nNow, we process the first column:\n\n     {carry_acc = 0; output =()}\n     STEP [5]\n     {carry_acc = 0; output=(5,)}\n\nSince we have only one term, there's no addition to do, and no carry\nbit. We add a 0 to the next column and continue.\n\n     STEP [0,4,35] (0 + 4 = 4)\n     {carry_acc = 0; output=(5,)}\n     STEP [4,35] (4 + 35 = 39)\n     {carry_acc = 3; output=(9,5)}\n\nThis time, we have a carry. We add it to the third column and process\nthat:\n\n     STEP [3,6,28,25] (3 + 6  = 9)\n     {carry_acc = 0; output=(9,5)}\n     STEP [9,28,25] (9 + 28 = 37)\n     {carry_acc = 3; output=(9,5)}\n     STEP [7,25] (7 + 25 = 32)\n     {carry_acc = 6; output=(2,9,5)}\n\nYou're probably getting the idea, but here are the fourth and fifth\ncolumns:\n\n     STEP [6,42,20] (6 + 42 = 48)\n     {carry_acc = 4; output=(2,9,5)}\n     STEP [8,20] (8 + 20 = 28)\n     {carry_acc = 6; output=(8,2,9,5)}\n\n     STEP [6,30] (6 + 30 = 36)\n     {carry_acc = 3; output=(6,8,2,9,5)}\n\nThe final result is the output plus the final carry, so we produce\n(6,8,2,9,5) and 3, representing the number 368295. A quick calculator\ncheck confirms our result.\n\n ***)\n\nModule Columns.\n  Section Columns.\n    Context (weight : nat->Z)\n            {weight_0 : weight 0%nat = 1}\n            {weight_nonzero : forall i, weight i <> 0}\n            {weight_positive : forall i, weight i > 0}\n            {weight_multiples : forall i, weight (S i) mod weight i = 0}\n            {weight_divides : forall i : nat, weight (S i) / weight i > 0}\n            (* add_get_carry takes in a number at which to split output *)\n            {add_get_carry_cps: forall {T}, Z ->Z -> Z -> (Z * Z -> T) -> T}\n            {div_cps modulo_cps : forall {T}, Z -> Z -> (Z -> T) -> T}.\n    Let add_get_carry s x y := add_get_carry_cps _ s x y id.\n    Let div x y := div_cps _ x y id.\n    Let modulo x y := modulo_cps _ x y id.\n    Context {add_get_carry_cps_id : forall {T} s x y f,\n                @add_get_carry_cps T s x y f = f (add_get_carry s x y)}\n            {add_get_carry_mod : forall s x y,\n                fst (add_get_carry s x y)  = (x + y) mod s}\n            {add_get_carry_div : forall s x y,\n                snd (add_get_carry s x y)  = (x + y) / s}\n            {div_cps_id : forall {T} x y f,\n                @div_cps T x y f = f (div x y)}\n            {modulo_cps_id : forall {T} x y f,\n                @modulo_cps T x y f = f (modulo x y)}\n            {div_correct : forall a b, div a b = a / b}\n            {modulo_correct : forall a b, modulo a b = a mod b}\n    .\n    Hint Rewrite div_correct modulo_correct add_get_carry_mod add_get_carry_div : div_mod.\n    Hint Rewrite add_get_carry_cps_id div_cps_id modulo_cps_id : uncps.\n\n    Definition eval {n} (x : (list Z)^n) : Z :=\n      B.Positional.eval weight (Tuple.map sum x).\n\n    Lemma eval_unit (x:unit) : eval (n:=0) x = 0.\n    Proof. reflexivity. Qed.\n    Hint Rewrite eval_unit : push_basesystem_eval.\n\n    Lemma eval_single (x:list Z) : eval (n:=1) x = sum x.\n    Proof.\n      cbv [eval]. simpl map. cbv - [Z.mul Z.add sum].\n      rewrite weight_0; ring.\n    Qed. Hint Rewrite eval_single : push_basesystem_eval.\n\n    Definition eval_from {n} (offset:nat) (x : (list Z)^n) : Z :=\n      B.Positional.eval (fun i => weight (i+offset)) (Tuple.map sum x).\n\n    Lemma eval_from_0 {n} x : @eval_from n 0 x = eval x.\n    Proof using Type. cbv [eval_from eval]. auto using B.Positional.eval_wt_equiv. Qed.\n\n    Lemma eval_from_S {n}: forall i (inp : (list Z)^(S n)),\n        eval_from i inp = eval_from (S i) (tl inp) + weight i * sum (hd inp).\n    Proof using Type.\n      intros i inp; cbv [eval_from].\n      replace inp with (append (hd inp) (tl inp))\n        by (simpl in *; destruct n; destruct inp; reflexivity).\n      rewrite map_append, B.Positional.eval_step, hd_append, tl_append.\n      autorewrite with natsimplify; ring_simplify; rewrite Group.cancel_left.\n      apply B.Positional.eval_wt_equiv; intros; f_equal; omega.\n    Qed.\n\n    (* Sums a list of integers using carry bits.\n     Output : carry, sum\n     *)\n    Section compact_digit_cps.\n      Context (n : nat) {T : Type}.\n\n      Fixpoint compact_digit_cps (digit : list Z) (f:Z * Z->T) :=\n        match digit with\n        | nil => f (0, 0)\n        | x :: nil => div_cps _ x (weight (S n) / weight n) (fun d =>\n                      modulo_cps _ x (weight (S n) / weight n) (fun m =>\n                      f (d, m)))\n        | x :: y :: nil =>\n            add_get_carry_cps _ (weight (S n) / weight n) x y (fun sum_carry =>\n            dlet sum_carry := sum_carry in\n            dlet carry := snd sum_carry in\n            f (carry, fst sum_carry))\n        | x :: tl =>\n          compact_digit_cps tl\n            (fun rec =>\n              add_get_carry_cps _ (weight (S n) / weight n) x (snd rec) (fun sum_carry =>\n              dlet sum_carry := sum_carry in\n              dlet carry' := (fst rec + snd sum_carry)%RT in\n              f (carry', fst sum_carry)))\n        end.\n    End compact_digit_cps.\n\n    Definition compact_digit n digit := compact_digit_cps n digit id.\n    Lemma compact_digit_id n digit: forall {T} f,\n        @compact_digit_cps n T digit f = f (compact_digit n digit).\n    Proof using add_get_carry_cps_id div_cps_id modulo_cps_id.\n      induction digit; intros; cbv [compact_digit]; [reflexivity|].\n      simpl compact_digit_cps; break_match; rewrite ?IHdigit; clear IHdigit;\n        cbv [Let_In]; autorewrite with uncps; reflexivity.\n    Qed.\n    Hint Opaque compact_digit : uncps.\n    Hint Rewrite compact_digit_id : uncps.\n\n    Definition compact_step_cps (index:nat) (carry:Z) (digit: list Z)\n               {T} (f:Z * Z->T) :=\n      compact_digit_cps index (carry::digit) f.\n\n    Definition compact_step i c d := compact_step_cps i c d id.\n    Lemma compact_step_id i c d T f :\n      @compact_step_cps i c d T f = f (compact_step i c d).\n    Proof using add_get_carry_cps_id div_cps_id modulo_cps_id. cbv [compact_step_cps compact_step]; autorewrite with uncps; reflexivity. Qed.\n    Hint Opaque compact_step : uncps.\n    Hint Rewrite compact_step_id : uncps.\n\n    Definition compact_cps {n} (xs : (list Z)^n) {T} (f:Z * Z^n->T) :=\n      Tuple.mapi_with_cps compact_step_cps 0 xs f.\n\n    Definition compact {n} xs := @compact_cps n xs _ id.\n    Lemma compact_id {n} xs {T} f : @compact_cps n xs T f = f (compact xs).\n    Proof using add_get_carry_cps_id div_cps_id modulo_cps_id. cbv [compact_cps compact]; autorewrite with uncps; reflexivity. Qed.\n\n    Lemma compact_digit_mod i (xs : list Z) :\n      snd (compact_digit i xs)  = sum xs mod (weight (S i) / weight i).\n    Proof using add_get_carry_div add_get_carry_mod div_correct modulo_correct add_get_carry_cps_id div_cps_id modulo_cps_id.\n      induction xs; cbv [compact_digit]; simpl compact_digit_cps;\n        cbv [Let_In];\n        repeat match goal with\n               | _ => progress autorewrite with div_mod\n               | _ => rewrite IHxs, <-Z.add_mod_r\n               | _ => progress (rewrite ?sum_cons, ?sum_nil in * )\n               | _ => progress (autorewrite with uncps push_id cancel_pair in * )\n               | _ => progress break_match; try discriminate\n               | _ => reflexivity\n               | _ => f_equal; ring\n               end.\n    Qed. Hint Rewrite compact_digit_mod : div_mod.\n\n    Lemma compact_digit_div i (xs : list Z) :\n      fst (compact_digit i xs)  = sum xs / (weight (S i) / weight i).\n    Proof using add_get_carry_div add_get_carry_mod div_correct modulo_correct weight_0 weight_divides add_get_carry_cps_id div_cps_id modulo_cps_id.\n      induction xs; cbv [compact_digit]; simpl compact_digit_cps;\n        cbv [Let_In];\n        repeat match goal with\n               | _ => progress autorewrite with div_mod\n               | _ => rewrite IHxs\n               | _ => progress (rewrite ?sum_cons, ?sum_nil in * )\n               | _ => progress (autorewrite with uncps push_id cancel_pair in * )\n               | _ => progress break_match; try discriminate\n               | _ => reflexivity\n               | _ => f_equal; ring\n               end.\n      assert (weight (S i) / weight i <> 0) by auto using Z.positive_is_nonzero.\n      match goal with |- _ = (?a + ?X) / ?D =>\n                      transitivity  ((a + X mod D + D * (X / D)) / D);\n                        [| rewrite (Z.div_mod'' X D) at 3; f_equal; auto; ring]\n      end.\n      rewrite Z.div_add' by auto; nsatz.\n    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    (* helper for some of the modular logic in compact *)\n    Lemma compact_mod_step a b c d: 0 < a -> 0 < b ->\n      a * ((c / a + d) mod b) + c mod a = (a * d + c) mod (a * b).\n    Proof.\n      clear.\n      intros Ha Hb. assert (a <= a * b) by (apply Z.le_mul_diag_r; omega).\n      pose proof (Z.mod_pos_bound c a Ha).\n      pose proof (Z.mod_pos_bound (c/a+d) b Hb).\n      apply small_mod_eq.\n      { rewrite <-(Z.mod_small (c mod a) (a * b)) by omega.\n        rewrite <-Z.mul_mod_distr_l with (c:=a) by omega.\n        rewrite Z.mul_add_distr_l, Z.mul_div_eq, <-Z.add_mod_full by omega.\n        f_equal; ring. }\n      { split; [zero_bounds|].\n        apply Z.lt_le_trans with (m:=a*(b-1)+a); [|ring_simplify; omega].\n        apply Z.add_le_lt_mono; try apply Z.mul_le_mono_nonneg_l; omega. }\n    Qed.\n\n    Lemma compact_div_step a b c d : 0 < a -> 0 < b ->\n      (c / a + d) / b = (a * d + c) / (a * b).\n    Proof.\n      clear. intros Ha Hb.\n      rewrite <-Z.div_div by omega.\n      rewrite Z.div_add_l' by omega.\n      f_equal; ring.\n    Qed.\n\n    Lemma compact_div_mod {n} inp :\n      (B.Positional.eval weight (snd (compact inp))\n       = (eval inp) mod (weight n))\n        /\\ (fst (compact inp) = eval (n:=n) inp / weight n).\n    Proof.\n      cbv [compact compact_cps compact_step compact_step_cps];\n        autorewrite with uncps push_id.\n      change (fun i s a => compact_digit_cps i (s :: a) id)\n        with (fun i s a => compact_digit i (s :: a)).\n\n      apply mapi_with'_linvariant; [|tauto].\n\n      clear n inp. intros n st x0 xs ys Hst Hys [Hmod Hdiv].\n      pose proof (weight_positive n). pose proof (weight_divides n).\n      autorewrite with push_basesystem_eval.\n      destruct n; cbv [mapi_with] in *; simpl tuple in *;\n        [destruct xs, ys; subst; simpl| cbv [eval] in *];\n        repeat match goal with\n               | _ => rewrite mapi_with'_left_step\n               | _ => rewrite compact_digit_div, sum_cons\n               | _ => rewrite compact_digit_mod, sum_cons\n               | _ => rewrite map_left_append\n               | _ => rewrite B.Positional.eval_left_append\n               | _ => rewrite weight_0, ?Z.div_1_r, ?Z.mod_1_r\n               | _ => rewrite Hdiv\n               | _ => rewrite Hmod\n               | _ => progress subst\n               | _ => progress autorewrite with natsimplify cancel_pair push_basesystem_eval\n               | _ => solve [split; ring_simplify; f_equal; ring]\n               end.\n        remember (weight (S (S n)) / weight (S n)) as bound.\n        replace (weight (S (S n))) with (weight (S n) * bound)\n          by (subst bound; rewrite Z.mul_div_eq by omega;\n              rewrite weight_multiples; ring).\n        split; [apply compact_mod_step | apply compact_div_step]; omega.\n    Qed.\n\n    Lemma compact_mod {n} inp :\n      (B.Positional.eval weight (snd (compact inp))\n       = (eval (n:=n) inp) mod (weight n)).\n    Proof. apply (proj1 (compact_div_mod inp)). Qed.\n    Hint Rewrite @compact_mod : push_basesystem_eval.\n\n    Lemma compact_div {n} inp :\n      fst (compact inp) = eval (n:=n) inp / weight n.\n    Proof. apply (proj2 (compact_div_mod inp)). Qed.\n    Hint Rewrite @compact_div : push_basesystem_eval.\n\n    (* TODO : move to tuple *)\n    Lemma hd_to_list {A n} a (t : A^(S n)) : List.hd a (to_list (S n) t) = hd t.\n    Proof.\n      rewrite (subst_append t), to_list_append, hd_append. reflexivity.\n    Qed.\n\n    Definition cons_to_nth_cps {n} i (x:Z) (t:(list Z)^n)\n               {T} (f:(list Z)^n->T) :=\n      @on_tuple_cps _ _ nil (update_nth_cps i (cons x)) n n t _ f.\n\n    Definition cons_to_nth {n} i x t := @cons_to_nth_cps n i x t _ id.\n    Lemma cons_to_nth_id {n} i x t T f :\n      @cons_to_nth_cps n i x t T f = f (cons_to_nth i x t).\n    Proof using Type.\n      cbv [cons_to_nth_cps cons_to_nth].\n      assert (forall xs : list (list Z), length xs = n ->\n                 length (update_nth_cps i (cons x) xs id) = n) as Hlen.\n      { intros. autorewrite with uncps push_id distr_length. assumption. }\n      rewrite !on_tuple_cps_correct with (H:=Hlen)\n        by (intros; autorewrite with uncps push_id; reflexivity). reflexivity.\n    Qed.\n    Hint Opaque cons_to_nth : uncps.\n    Hint Rewrite @cons_to_nth_id : uncps.\n\n    Lemma map_sum_update_nth l : forall i x,\n      List.map sum (update_nth i (cons x) l) =\n      update_nth i (Z.add x) (List.map sum l).\n    Proof using Type.\n      induction l as [|a l IHl]; intros i x; destruct i; simpl; rewrite ?IHl; reflexivity.\n    Qed.\n\n    Lemma cons_to_nth_add_to_nth n i x t :\n      map sum (@cons_to_nth n i x t) = B.Positional.add_to_nth i x (map sum t).\n    Proof using weight.\n      cbv [B.Positional.add_to_nth B.Positional.add_to_nth_cps cons_to_nth cons_to_nth_cps on_tuple_cps].\n      induction n; [simpl; rewrite !update_nth_cps_correct; reflexivity|].\n      specialize (IHn (tl t)). autorewrite with uncps push_id in *.\n      apply to_list_ext. rewrite <-!map_to_list.\n      erewrite !from_list_default_eq, !to_list_from_list.\n      rewrite map_sum_update_nth. reflexivity.\n      Unshelve.\n      distr_length.\n      distr_length.\n    Qed.\n\n    Lemma eval_cons_to_nth n i x t : (i < n)%nat ->\n      eval (@cons_to_nth n i x t) = weight i * x + eval t.\n    Proof using Type.\n      cbv [eval]; intros. rewrite cons_to_nth_add_to_nth.\n      auto using B.Positional.eval_add_to_nth.\n    Qed.\n    Hint Rewrite eval_cons_to_nth using omega : push_basesystem_eval.\n\n    Definition nils n : (list Z)^n := Tuple.repeat nil n.\n\n    Lemma map_sum_nils n : map sum (nils n) = B.Positional.zeros n.\n    Proof using Type.\n      cbv [nils B.Positional.zeros]; induction n as [|n]; [reflexivity|].\n      change (repeat nil (S n)) with (@nil Z :: repeat nil n).\n      rewrite Tuple.map_repeat, sum_nil. reflexivity.\n    Qed.\n\n    Lemma eval_nils n : eval (nils n) = 0.\n    Proof using Type. cbv [eval]. rewrite map_sum_nils, B.Positional.eval_zeros. reflexivity. Qed. Hint Rewrite eval_nils : push_basesystem_eval.\n\n    Definition from_associational_cps n (p:list B.limb)\n               {T} (f:(list Z)^n -> T) :=\n      fold_right_cps2\n        (fun t st T' f' =>\n           B.Positional.place_cps weight t (pred n)\n             (fun p=> cons_to_nth_cps (fst p) (snd p) st f'))\n        (nils n) p f.\n\n    Definition from_associational n p := from_associational_cps n p id.\n    Lemma from_associational_id n p T f :\n      @from_associational_cps n p T f = f (from_associational n p).\n    Proof using Type.\n      cbv [from_associational_cps from_associational].\n      autorewrite with uncps push_id; reflexivity.\n    Qed.\n    Hint Opaque from_associational : uncps.\n    Hint Rewrite from_associational_id : uncps.\n\n    Lemma eval_from_associational n p (n_nonzero:n<>0%nat):\n      eval (from_associational n p) = B.Associational.eval p.\n    Proof using weight_0 weight_nonzero.\n      cbv [from_associational_cps from_associational]; induction p;\n        autorewrite with uncps push_id push_basesystem_eval; [reflexivity|].\n        pose proof (B.Positional.weight_place_cps weight weight_0 weight_nonzero a (pred n)).\n        pose proof (B.Positional.place_cps_in_range weight a (pred n)).\n        rewrite Nat.succ_pred in * by assumption. simpl.\n        autorewrite with uncps push_id push_basesystem_eval in *.\n        rewrite eval_cons_to_nth by omega. nsatz.\n    Qed.\n  End Columns.\nEnd Columns.\nHint Rewrite\n     @Columns.compact_digit_id\n     @Columns.compact_step_id\n     @Columns.compact_id\n     using (assumption || (intros; autorewrite with uncps; reflexivity))\n  : uncps.\nHint Rewrite\n     @Columns.cons_to_nth_id\n     @Columns.from_associational_id\n  : uncps.\nHint Rewrite\n     @Columns.compact_mod\n     @Columns.compact_div\n     @Columns.eval_cons_to_nth\n     @Columns.eval_from_associational\n     @Columns.eval_nils\n  using (assumption || omega): push_basesystem_eval.\n\nHint Unfold\n     Columns.eval Columns.eval_from\n     Columns.compact_digit_cps Columns.compact_digit\n     Columns.compact_step_cps Columns.compact_step\n     Columns.compact_cps Columns.compact\n     Columns.cons_to_nth_cps Columns.cons_to_nth\n     Columns.nils\n     Columns.from_associational_cps Columns.from_associational\n  : basesystem_partial_evaluation_unfolder.\n\nLtac basesystem_partial_evaluation_unfolder t :=\n  let t :=\n      (eval\n         cbv\n         delta [\n           (* this list must contain all definitions referenced by t that reference [Let_In], [runtime_add], [runtime_opp], [runtime_mul], [runtime_shr], or [runtime_and] *)\n           Columns.eval Columns.eval_from\n                   Columns.compact_digit_cps Columns.compact_digit\n                   Columns.compact_step_cps Columns.compact_step\n                   Columns.compact_cps Columns.compact\n                   Columns.cons_to_nth_cps Columns.cons_to_nth\n                   Columns.nils\n                   Columns.from_associational_cps Columns.from_associational\n         ] in t) in\n  let t := Arithmetic.Core.basesystem_partial_evaluation_unfolder t in\n  t.\n\nLtac Arithmetic.Core.basesystem_partial_evaluation_default_unfolder t ::=\n  basesystem_partial_evaluation_unfolder t.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Arithmetic/Saturated/Core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6928802758801051}}
{"text": "Require Import Coq.NArith.NArith.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Crypto.Util.NatUtil Crypto.Util.Decidable.\nRequire bbv.WordScope.\nRequire Import bbv.NatLib.\nRequire Crypto.Util.WordUtil.\n\nModule N.\n  Lemma size_le a b : (a <= b -> N.size a <= N.size b)%N.\n  Proof.\n    destruct (dec (a=0)%N), (dec (b=0)%N); subst; auto using N.le_0_l.\n    { destruct a; auto. }\n    { rewrite !N.size_log2 by assumption.\n      rewrite <-N.succ_le_mono.\n      apply N.log2_le_mono. }\n  Qed.\n\n  Lemma le_to_nat a b : (a <= b)%N <-> (N.to_nat a <= N.to_nat b)%nat.\n  Proof.\n    rewrite <-N.lt_succ_r.\n    rewrite <-Nat.lt_succ_r.\n    rewrite <-Nnat.N2Nat.inj_succ.\n    rewrite <-NatUtil.Nat2N_inj_lt.\n    rewrite !Nnat.N2Nat.id.\n    reflexivity.\n  Qed.\n\n  Lemma size_nat_equiv : forall n, N.size_nat n = N.to_nat (N.size n).\n  Proof.\n    destruct n as [|p]; auto; simpl; induction p as [p IHp|p IHp|]; simpl; auto; rewrite IHp, Pnat.Pos2Nat.inj_succ; reflexivity.\n  Qed.\n\n  Lemma size_nat_le a b : (a <= b)%N -> (N.size_nat a <= N.size_nat b)%nat.\n  Proof.\n    rewrite !size_nat_equiv.\n    rewrite <-le_to_nat.\n    apply size_le.\n  Qed.\n\n  Lemma shiftr_size : forall n bound, N.size_nat n <= bound ->\n    N.shiftr_nat n bound = 0%N.\n  Proof.\n    intros n bound H.\n    rewrite <- (Nat2N.id bound).\n    rewrite Nshiftr_nat_equiv.\n    destruct (N.eq_dec n 0); subst; [apply N.shiftr_0_l|].\n    apply N.shiftr_eq_0.\n    rewrite size_nat_equiv in *.\n    rewrite N.size_log2 in * by auto.\n    apply N.le_succ_l.\n    rewrite <- N.compare_le_iff.\n    rewrite N2Nat.inj_compare.\n    rewrite <- Compare_dec.nat_compare_le.\n    rewrite Nat2N.id.\n    auto.\n  Qed.\n\n  Hint Rewrite\n    N.succ_double_spec\n    N.add_1_r\n    Nat2N.inj_succ\n    Nat2N.inj_mul\n    N2Nat.id: N_nat_conv\n .\n\n  Lemma succ_double_to_nat : forall n,\n    N.succ_double n = N.of_nat (S (2 * N.to_nat n)).\n  Proof.\n    intros.\n    replace 2 with (N.to_nat 2) by auto.\n    autorewrite with N_nat_conv.\n    reflexivity.\n  Qed.\n\n  Lemma double_to_nat : forall n,\n    N.double n = N.of_nat (2 * N.to_nat n).\n  Proof.\n    intros.\n    replace 2 with (N.to_nat 2) by auto.\n    autorewrite with N_nat_conv.\n    reflexivity.\n  Qed.\n\n  Lemma shiftr_succ : forall n i,\n    N.to_nat (N.shiftr_nat n i) =\n    if N.testbit_nat n i\n    then S (2 * N.to_nat (N.shiftr_nat n (S i)))\n    else (2 * N.to_nat (N.shiftr_nat n (S i))).\n  Proof.\n    intros n i.\n    rewrite Nshiftr_nat_S.\n    case_eq (N.testbit_nat n i); intro testbit_i;\n      pose proof (Nshiftr_nat_spec n i 0) as shiftr_n_odd;\n      rewrite Nbit0_correct in shiftr_n_odd; simpl in shiftr_n_odd;\n      rewrite testbit_i in shiftr_n_odd.\n    + pose proof (Ndiv2_double_plus_one (N.shiftr_nat n i) shiftr_n_odd) as Nsucc_double_shift.\n      rewrite succ_double_to_nat in Nsucc_double_shift.\n      apply Nat2N.inj.\n      rewrite Nsucc_double_shift.\n      apply N2Nat.id.\n    + pose proof (Ndiv2_double (N.shiftr_nat n i) shiftr_n_odd) as Nsucc_double_shift.\n      rewrite double_to_nat in Nsucc_double_shift.\n      apply Nat2N.inj.\n      rewrite Nsucc_double_shift.\n      apply N2Nat.id.\n  Qed.\n\n  Section ZN.\n    Import Coq.ZArith.ZArith.\n    Lemma ZToN_NPow2_lt : forall z n, (0 <= z < 2 ^ Z.of_nat n)%Z ->\n                                      (Z.to_N z < Npow2 n)%N.\n    Proof.\n      intros.\n      apply WordUtil.bound_check_nat_N.\n      apply Znat.Nat2Z.inj_lt.\n      rewrite Znat.Z2Nat.id by omega.\n      rewrite ZUtil.Z.pow_Zpow.\n      replace (Z.of_nat 2) with 2%Z by reflexivity.\n      omega.\n    Qed.\n\n    Let ZNWord sz x := Word.NToWord sz (BinInt.Z.to_N x).\n    Lemma combine_ZNWord : forall sz1 sz2 z1 z2,\n        (0 <= Z.of_nat sz1)%Z ->\n        (0 <= Z.of_nat sz2)%Z ->\n        (0 <= z1 < 2 ^ (Z.of_nat sz1))%Z ->\n        (0 <= z2 < 2 ^ (Z.of_nat sz2))%Z ->\n        Word.combine (ZNWord sz1 z1) (ZNWord sz2 z2) =\n        ZNWord (sz1 + sz2) (Z.lor z1 (Z.shiftl z2 (Z.of_nat sz1))).\n    Proof using Type.\n      cbv [ZNWord]; intros.\n      rewrite !Word.NToWord_nat.\n      match goal with |- ?a = _ => rewrite <- (Word.natToWord_wordToNat a) end.\n      rewrite WordUtil.wordToNat_combine.\n      rewrite !Word.wordToNat_natToWord_idempotent by (rewrite Nnat.N2Nat.id; auto using ZToN_NPow2_lt).\n      f_equal.\n      rewrite ZUtil.Z.lor_shiftl by auto.\n      rewrite !Z_N_nat.\n      rewrite Znat.Z2Nat.inj_add by (try apply Z.shiftl_nonneg; omega).\n      f_equal.\n      rewrite Z.shiftl_mul_pow2 by auto.\n      rewrite Znat.Z2Nat.inj_mul by omega.\n      rewrite <-ZUtil.Z.pow_Z2N_Zpow by omega.\n      rewrite Nat.mul_comm.\n      f_equal.\n    Qed.\n  End ZN.\n\nEnd N.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Util/NUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183444, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6928802711688007}}
{"text": "Require Import Reals Psatz.\nRequire Import Coquelicot.Hierarchy.\nRequire Import Coquelicot.Rbar.\nRequire Import Top.linear_map.\nRequire Import Top.continuous_linear_map. \nRequire Import Coquelicot.Coquelicot.\nRequire Import Decidable.\nRequire Import Coquelicot.Rbar.\n\n\nOpen Scope R_scope.\n\n(* Defining X, Y , Xh, Yh as Banach spaces (complete normed spaces)*)\nContext {X: CompleteNormedModule R_AbsRing}.\nContext {Xh: R -> CompleteNormedModule R_AbsRing}.\nContext {Y: CompleteNormedModule R_AbsRing}.\nContext {Yh: R -> CompleteNormedModule R_AbsRing}.\n\n\n(* Defining a linear mapping on Banach space*)\nDefinition is_linear_mapping (E F: CompleteNormedModule R_AbsRing) (phi: E -> F) :=\n  (forall (x y :E), phi (plus x y) = plus (phi x) (phi y))\n     /\\ (forall (x : E) (l:R_AbsRing), phi (scal l x) = scal l (phi x)).\n\n\n\n(* Defining linear bounded restriction operator from E to F*)\nDefinition is_bounded_linear (E F: CompleteNormedModule R_AbsRing)(phi:E->F):=\n     is_linear_mapping E F phi /\\ (exists K:R, 0<=K /\\ (forall x:E, norm(phi x) <= K* norm x)).\n\n\nContext {E : CompleteNormedModule R_AbsRing}.\nContext {F : CompleteNormedModule R_AbsRing}.\n\n(* Defining uniformly bounded opaartor from E to F*)\nDefinition is_uniformly_bounded (E F: CompleteNormedModule R_AbsRing) (phi:E->F):=\n (is_bounded_linear E F phi) /\\ (exists c1:Rbar ,forall h:R,(operator_norm (phi)) <= c1).\n\n\nVariable Aop: X->Y.\nVariable Ah_op: (forall (h:R), (Xh h)->(Yh h)).\n\n(*** This lemma uses the property of linear operator to prove that phi(x-y)= phi(x)-phi(y) ,\n      where x and Y belong to Banach spaces E and F respectively and phi: E->F ***************)\n\nLemma composition (E F:CompleteNormedModule R_AbsRing):\nforall (x y: E) (phi: E->F), is_linear_mapping E F phi ->  phi( minus x y) = minus (phi x) (phi y).\nProof.\nintros.\ndestruct H.\nunfold minus.\nspecialize (H x (opp y)).\ncut (opp(phi y)= phi(opp y)).\n+ intros. rewrite H1. apply  H.\n+ cut (scal (opp one) y= opp y).\n  * intros. rewrite <- H1.\n    cut (phi(scal (opp one) y)= scal (opp one) (phi y)).\n    - intros. rewrite H2. \n      cut (scal (opp one) (phi y)=opp (phi y)).\n      + intros. rewrite H3. reflexivity.\n      + apply (scal_opp_one (phi y)).\n    - apply (H0 y (opp one)).\n  * apply (scal_opp_one y).\nQed.\n\n\n(*Lemma as an argument for posreal*)\nLemma two_zero: 0<2.\nProof.\napply Rlt_R0_R2.\nQed.\n\n(* Define f=Au , u=Ef and EhAh=I*)\n\n(* Lax equivalence theorem to prove the convergence*)\nTheorem is_convergent:\nforall (u:X) (f:Y) (h:R) (uh: Xh h) (rh: forall (h:R), X -> (Xh h)) (sh: forall (h:R), Y->(Yh h))\n (E: Y->X) (Eh:forall (h:R), (Yh h)->(Xh h)), \n is_linear_mapping X Y Aop -> f=Aop u-> (* Hypothesis that A is a linear mapping from X to Y*)\n  (forall (h:R), is_linear_mapping (Xh h) (Yh h) (Ah_op h) )-> (* Hypothesis that Ah is a linear\n   mapping from Xh to Yh for each h*)\n  (forall (h:R), is_bounded_linear X (Xh h) (rh h))->(* Hypothesis that rh is a bounded linear\n  operatior (restriction) from X to Xh for each h*)  \n  (forall (h:R), is_bounded_linear Y (Yh h) (sh h))-> (* Hypothesis that sh is a bounded linear\n  operator (restriction) from Y to Yh*) \n  is_bounded_linear Y X E -> (* Hypothesis that E is a bounded linear operator from Y to X*)\n  u=E f-> (* Defining solution in continuous space (true solution)*)\n  (forall (h:R), is_bounded_linear (Yh h) (Xh h) (Eh h))-> (* Hypotheis that Eh is a bounded \n  linear operator from Yh to Xh for each h*)\n (forall h:R, is_finite (operator_norm(Eh h))) -> (* Hypothesis that ||Eh|| is finite*)\n   (uh= Eh h (sh h f))-> (* Defining a discrete solution uh*)\n   ( Ah_op h uh = sh h f)-> (*f =fh*)\n  (forall (h:R), rh h u= Eh h (Ah_op h (rh h u)))-> (*uh =Eh *Ah *uh, where Eh*Ah=I*)\n  (forall h:R,  minus (Ah_op h (rh h u)) (sh h (Aop u)) <> zero )->\n\n  (is_lim (fun h:R => \n      norm (minus (Ah_op h (rh h u)) (sh h (Aop u)))) 0 0 (*Consistency*) /\\ \n  ( exists K:R , forall (h:R), operator_norm(Eh h)<=K ) (* Stability*)-> \n  is_lim (fun h:R=>\n      norm (minus (rh h (E(f))) (Eh h (sh h (f))))) 0 0) (*Convergence*).\n\nProof.\nintros.\n\ndestruct H12 as [H12 H13].\ndestruct H13 as [p H13]. \napply (is_lim_ext ((fun h0 : R => norm (minus (Eh h0 (Ah_op h0 (rh h0 u))) (Eh h0 (sh h0 f))))) \n        (fun h0 : R => norm (minus (rh h0 (E0 f)) (Eh h0 (sh h0 f)))) 0 0).\n+ intros.\n  cut(Eh y (Ah_op y (rh y u)) = (rh y (E0 f))).\n  - intros. rewrite H14. reflexivity.\n  - symmetry. specialize (H10 y). rewrite <- H5. apply H10.\n+ apply (is_lim_ext (fun h0 : R => norm (Eh h0 (minus (Ah_op h0 (rh h0 u)) (sh h0 (Aop u)))))\n          (fun h0 : R => norm (minus (Eh h0 (Ah_op h0 (rh h0 u))) (Eh h0 (sh h0 f)))) 0 0).\n  - intros. \n    cut(Eh y (minus (Ah_op y (rh y u)) (sh y (Aop u)))= minus (Eh y (Ah_op y (rh y u))) (Eh y (sh y f))).\n    * intros. rewrite H14. reflexivity.\n    * rewrite H0. apply (composition (Yh y) (Xh y) (Ah_op y (rh y u)) (sh y (Aop u)) (Eh y)). \n      unfold is_bounded_linear in H6. specialize (H6 y). destruct H6 as [H14 H15]. apply H14.\n  -  cut (Rbar_locally' 0 (fun h0:R => 0 <=norm (Eh h0 (minus (Ah_op h0 (rh h0 u)) (sh h0 (Aop u))))\n                  <= operator_norm (Eh h0) * norm (minus (Ah_op h0 (rh h0 u)) (sh h0 (Aop u))))).\n     * intros. \n      (* Applying the sandwich theorem for limits\n              In Coq, this is expressed as:\n              Lemma is_lim_le_le_loc (f g h: R -> R) (x: Rbar) (l:Rbar):\n                Rbar_locally' x (fun y=> f y<= h y <= g y) ->\n                    is_lim f x l -> is_lim g x l -> is_lim h x l \n\n\n              Here, since the function g  is chosen as: \n                    ||Eh||*||Ah (rh u) - sh (A(u))|| (upper bound)\n                    and the function f is a constant function O since from property of\n                    norm 0<= ||.|| *)\n        apply (is_lim_le_le_loc (fun _ => 0) \n                    (fun h0:R =>operator_norm (Eh h0) * norm (minus (Ah_op h0 (rh h0 u)) (sh h0 (Aop u))))\n                        (fun h0:R => norm (Eh h0 (minus (Ah_op h0 (rh h0 u)) (sh h0 (Aop u))))) 0 0).\n        apply H14. \n        apply (is_lim_const 0 0). (* Applying property of limits for a constant function*)\n        cut(Rbar_locally' (Rbar_mult p 0) (fun h0:R => 0 <= operator_norm (Eh h0) * norm (minus (Ah_op h0 (rh h0 u)) (sh h0 (Aop u)))\n                              <= p* norm (minus (Ah_op h0 (rh h0 u)) (sh h0 (Aop u))))).\n        { intros. \n          cut(Rbar_mult p 0 = 0).\n          + intros. rewrite <-H16.\n             apply (is_lim_le_le_loc (fun _  =>0) (fun h0:R  => p* norm(minus (Ah_op h0 (rh h0 u)) (sh h0 (Aop u))))\n                        (fun h0:R  => operator_norm (Eh h0) * norm (minus (Ah_op h0 (rh h0 u)) (sh h0 (Aop u)))) (Rbar_mult p 0) (Rbar_mult p 0)).\n             apply H15.\n             rewrite H16.\n             apply (is_lim_const 0 0).\n              (* Applying the property of limit:\n                      lim_{x-> a} K*f(x)= K* lim_{x->a} f(x) *)\n             apply (is_lim_scal_l (fun h0:R => norm (minus (Ah_op h0 (rh h0 u)) (sh h0 (Aop u))))\n                         p (Rbar_mult p 0) 0).\n             rewrite H16.\n             apply H12.\n          + apply (Rbar_mult_0_r p).\n        }\n        { \n             unfold Rbar_locally'.\n                unfold locally'.\n                unfold within.\n                unfold locally.\n                exists (mkposreal 2 two_zero).\n                intros.\n                split.\n                cut(0*0=0).\n                + intros. rewrite <- H17.\n                  apply (Rmult_le_compat 0 (operator_norm (Eh y)) 0 (norm (minus (Ah_op y (rh y u)) (sh y (Aop u))))).\n                  apply Rle_refl. apply Rle_refl. \n                 (* Applying the property that operator norm of Eh >=0*)\n                  apply (operator_norm_ge_0' (Eh y)). \n                  (* Proving that ||a-b|| >=0 *)\n                  cut (Rabs (norm (Ah_op y (rh y u))- norm (sh y (Aop u)))<= norm (minus (Ah_op y (rh y u)) (sh y (Aop u)))).\n                  - intros. \n                    apply (Rle_trans 0 (Rabs (norm (Ah_op y (rh y u)) - norm (sh y (Aop u)))) \n                            (norm (minus (Ah_op y (rh y u)) (sh y (Aop u))))).\n                    apply Rabs_pos.\n                    apply H18.\n                  - apply (norm_triangle_inv (Ah_op y (rh y u))(sh y (Aop u))).\n                + nra.\n             \n            (* Proof that ||Eh||*||Ah (rh u) - sh (A u)|| <= K* ||Ah (rh u) -sh (A u)||\n                when ||Eh||<=K*)\n              apply (Rmult_le_compat_r (norm (minus (Ah_op y (rh y u)) (sh y (Aop u)))) \n                    (operator_norm (Eh y)) p).\n              cut (Rabs (norm (Ah_op y (rh y u))- norm (sh y (Aop u)))<= norm (minus (Ah_op y (rh y u)) (sh y (Aop u)))).\n              - intros. \n                apply (Rle_trans 0 (Rabs (norm (Ah_op y (rh y u)) - norm (sh y (Aop u)))) \n                        (norm (minus (Ah_op y (rh y u)) (sh y (Aop u))))).\n                apply Rabs_pos.\n                apply H17.\n              - apply (norm_triangle_inv (Ah_op y (rh y u))(sh y (Aop u))).\n              apply H13.\n        }\n        (* Proof that 0<=||Eh(Ah (rh u)- sh (A u)||<= ||Eh||||Ah rh u- sh A u||\n              in an open neighborhood of 0*)\n      *  unfold Rbar_locally'.\n            unfold locally'.\n            unfold within.\n            unfold locally.\n            exists (mkposreal 2 two_zero).\n            intros.\n            split.\n            (* Proof that 0 <= norm (Eh h (minus (Ah h (rh h u)) (sh h (A u)))) *)\n            cut(Eh y (minus (Ah_op y (rh y u)) (sh y (Aop u)))= minus (Eh y (Ah_op y (rh y u))) (Eh y (sh y f))).\n            { intros. rewrite H16. \n              cut( Rabs(norm (Eh y (Ah_op y (rh y u))) - norm (Eh y (sh y (Aop u)))) <= norm (minus (Eh y (Ah_op y (rh y u))) (Eh y (sh y (Aop u))))).\n              + intros. rewrite H0.\n                apply (Rle_trans 0 (Rabs (norm (Eh y (Ah_op y (rh y u))) - norm (Eh y (sh y (Aop u)))))\n                                    ( norm (minus (Eh y (Ah_op y (rh y u))) (Eh y (sh y (Aop u)))))).\n                apply Rabs_pos.\n                apply H17.\n              + apply (norm_triangle_inv (Eh y (Ah_op y (rh y u))) (Eh y (sh y (Aop u)))).\n            }\n            { rewrite H0. apply (composition (Yh y) (Xh y) (Ah_op y (rh y u)) (sh y (Aop u)) (Eh y)). \n              unfold is_bounded_linear in H6. specialize (H6 y). destruct H6 as [H16 H17]. apply H16. \n            }\n            \n          \n            (* Applying the lemma that ||Eh(Ah (rh u)- sh (A u)||<= ||Eh||||Ah rh u- sh A u||*)\n            apply (operator_norm_helper' (Eh y)).\n            specialize (H7 y). apply H7.\n            specialize (H11 y). apply H11.\nQed.\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/lax_equivalence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6928802648311958}}
{"text": "Definition LEM : Prop := forall (p:Prop), p \\/ ~p.\n \nDefinition PropExt : Prop := forall (p q:Prop), p <-> q -> p = q.\n\nLemma L1 : LEM -> forall (p:Prop), (p <-> True) \\/ (p <-> False).\nProof.\n    intros L p. destruct (L p) as [H1|H1].\n    - left. split; intros H2.\n        + trivial.\n        + assumption.\n    - right. split; intros H2.\n        +  apply H1. assumption.\n        + contradiction.\nQed.\n\nLemma PropostionalCompleteness : LEM -> PropExt ->\n    forall (p:Prop), p = True \\/ p = False.\nProof.\n    intros L P p. destruct (L1 L p) as [H|H].\n    - left. apply P. assumption.\n    - right. apply P. 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/complete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6927181467119874}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf1 : natural) : natural :=\n  plus (Succ Zero) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj257_coqofml_IU9TVt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.692718146513932}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := cons : Nat -> Lst -> Lst |  nil : Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : Lst) : Lst\n           := match rev_arg0 with\n              | nil => nil\n              | cons x y => append (rev y) (cons x nil)\n              end.\n\nTheorem theorem0 : forall (x : Lst) (y : Nat), eq (rev (append (append x (cons y nil)) nil)) (cons y (rev (append x nil))).\nProof.\ninduction x.\n- intros. simpl. rewrite IHx. reflexivity.\n- intros. 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/goal60.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480668, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6927181407734231}}
{"text": "(**********************************************************************************\n * PredomFix.v                                                                    *\n * Formalizing Domains, Ultrametric Spaces and Semantics of Programming Languages *\n * Nick Benton, Lars Birkedal, Andrew Kennedy and Carsten Varming                 *\n * Jan 2012                                                                       *\n * Build with Coq 8.3pl2 plus SSREFLECT                                           *\n **********************************************************************************)\n\n(*==========================================================================\n  Definition of fixpoints and associated lemmas\n  ==========================================================================*)\nRequire Import PredomCore.\nRequire Import PredomLift.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(** ** Fixpoints *)\n\nSection Fixpoints.\n Variable D : cppoType.\n\nVariable f : cpoCatType D D.\n\nFixpoint iter_ n : D := match n with O => PBot | S m => f (iter_ m) end.\n\nLemma iter_incr : forall n, iter_ n <= f (iter_ n).\nelim ; first by apply: leastP.\nmove => n L. simpl. apply: fmonotonic. by apply L.\nSave.\n\nHint Resolve iter_incr.\n\nLemma iter_m : monotonic iter_.\nmove => n n'. elim: n' n.\n- move => n. move => L. unfold Ole in L. simpl in L.\n  rewrite -> (leqn0 n) in L. by rewrite (eqP L).\n- move => n IH n' L. unfold Ole in L. simpl in L. rewrite leq_eqVlt in L.\n  case_eq (n' == n.+1) => E ; rewrite E in L. by rewrite (eqP E).\n  specialize (IH _ L). by rewrite -> IH ; simpl.\nQed.\n\nDefinition iter : natO =-> D := mk_fmono (iter_m).\n\nDefinition fixp : D := lub iter.\n\nLemma fixp_le : fixp <= f fixp.\nunfold fixp.\napply Ole_trans with (lub (ocomp f iter)).\n- apply: lub_le_compat. move => x. simpl. by apply iter_incr.\n- by rewrite -> lub_comp_le.\nSave.\nHint Resolve fixp_le.\n\nLemma fixp_eq : fixp =-= f fixp.\napply: Ole_antisym; first by [].\nunfold fixp. rewrite {2} (lub_lift_left iter (S O)).\nrewrite -> (fcontinuous f iter). by apply: lub_le_compat => i.\nSave.\n\nLemma fixp_inv : forall g, f g <= g -> fixp <= g.\nunfold fixp; intros g l.\napply: lub_le. elim. simpl. by apply: leastP.\nmove => n L. apply: (Ole_trans _ l). apply: (fmonotonic f). by apply L.\nSave.\n\nEnd Fixpoints.\nHint Resolve fixp_le fixp_eq fixp_inv.\n\nDefinition fixp_cte (D:cppoType) : forall (d:D), fixp (const D d) =-= d.\nintros; apply fixp_eq with (f:=const D d); red; intros; auto.\nSave.\nHint Resolve fixp_cte.\n\nAdd Parametric Morphism (D:cppoType) : (@fixp D)\nwith signature (@Ole _ : ((D:cpoType) =-> D) -> (D =-> D) -> Prop) ++> (@Ole _)\nas fixp_le_compat.\nmove => x y l. unfold fixp.\napply: lub_le_compat. elim ; first by [].\nmove => n IH. simpl. rewrite -> IH. by apply l.\nQed.\nHint Resolve fixp_le_compat.\n\nAdd Parametric Morphism (D:cppoType) : (@fixp D)\nwith signature (@tset_eq _) ==> (@tset_eq D)\nas fixp_eq_compat.\nby intros x y H; apply Ole_antisym ; apply: (fixp_le_compat _) ; case: H.\nSave.\nHint Resolve fixp_eq_compat.\n\nLemma fixp_mon (D:cppoType) : monotonic (@fixp D).\nmove => x y e. by rewrite -> e.\nQed.\n\nDefinition Fixp (D:cppoType) : ordCatType (D -=> D) D := Eval hnf in mk_fmono (@fixp_mon D).\n\nLemma Fixp_simpl (D:cppoType) : forall (f:D =-> D), Fixp D f = fixp f.\ntrivial.\nSave.\n\nLemma iter_mon (D:cppoType) : monotonic (@iter D).\nmove => x y l. elim ; first by [].\nmove => n IH. simpl. rewrite -> IH. by apply l.\nQed.\n\nDefinition Iter (D:cppoType) : ordCatType (D -=> D) (fmon_cpoType natO D) :=\n  Eval hnf in mk_fmono (@iter_mon D).\n\nLemma IterS_simpl (D:cppoType) : forall f n, Iter D f (S n) = f (Iter _ f n).\ntrivial.\nSave.\n\nLemma iterS_simpl (D:cppoType) : forall (f:cpoCatType D D) n, iter f (S n) = f (iter  f n).\ntrivial.\nSave.\n\nLemma iter_continuous (D:cppoType) :\n    forall h : natO =-> D -=> D,\n                  iter (lub h) <= lub (Iter D << h).\nmove => h. elim ; first by apply: leastP.\nmove => n IH. simpl. rewrite fcont_app_eq. rewrite -> IH. rewrite <- fcont_app_eq.\nrewrite fcont_app_continuous. rewrite lub_diag. by apply lub_le_compat => i.\nQed.\n\nHint Resolve iter_continuous.\n\nLemma iter_continuous_eq (D:cppoType) :\n    forall h : natO =-> (D -=> D),\n                  iter (lub h) =-= lub (Iter _ << h).\nintros; apply: Ole_antisym; auto.\nexact (lub_comp_le (Iter _ (*D*)) h).\nSave.\n\n\nLemma fixp_continuous (D:cppoType) : forall (h : natO =-> (D -=> D)), \n       fixp (lub h) <= lub (Fixp D << h).\nmove => h. unfold fixp. rewrite -> iter_continuous_eq.\napply: lub_le => n. simpl.\napply: lub_le => m. simpl. rewrite <- (le_lub _ m). simpl. unfold fixp. by rewrite <- (le_lub _ n).\nSave.\nHint Resolve fixp_continuous.\n\nLemma fixp_continuous_eq (D:cppoType) : forall (h : natO =-> (D -=> D)), \n        fixp (lub h) =-= lub (Fixp D << h).\nintros; apply: Ole_antisym; auto.\nby apply (lub_comp_le (Fixp D) h).\nSave.\n\nLemma Fixp_cont (D:cppoType) : continuous (@Fixp D).\nmove => c.\nrewrite Fixp_simpl. by rewrite -> fixp_continuous_eq.\nQed.\n\nDefinition FIXP (D:cppoType) : (D -=> D) =-> D := Eval hnf in  mk_fcont (@Fixp_cont D).\nImplicit Arguments FIXP [D].\n\nLemma FIXP_simpl (D:cppoType) : forall (f:D=->D), FIXP f = fixp f.\ntrivial.\nSave.\n\nLemma FIXP_le_compat (D:cppoType) : forall (f g : D =-> D),\n            f <= g -> FIXP f <= FIXP g.\nmove => f g l. by rewrite -> l.\nSave.\nHint Resolve FIXP_le_compat.\n\nLemma FIXP_eq (D:cppoType) : forall (f:D=->D), FIXP f =-= f (FIXP f).\nintros; rewrite FIXP_simpl.\nby apply: (fixp_eq).\nSave.\nHint Resolve FIXP_eq.\n\nLemma FIXP_com: forall E D (f:E =-> (D -=> D)) , FIXP << f =-= ev << <| f, FIXP << f |>.\nintros E D f. apply: fmon_eq_intro. intros e. simpl. by rewrite {1} fixp_eq.\nQed.\n\nLemma FIXP_inv (D:cppoType) : forall (f:D=->D)(g : D), f g <= g -> FIXP f <= g.\nintros; rewrite FIXP_simpl; apply: fixp_inv; auto.\nSave.\n\n(** *** Iteration of functional *)\nLemma FIXP_comp_com (D:cppoType) : forall (f g:D=->D),\n       g << f <= f << g-> FIXP g <= f (FIXP g).\nintros; apply FIXP_inv.\napply Ole_trans with (f (g (FIXP g))).\nassert (X:=H (FIXP g)). simpl. by apply X.\napply: fmonotonic.\ncase (FIXP_eq g); trivial.\nSave.\n\nLemma FIXP_comp (D:cppoType) : forall (f g:D=->D),\n       g << f <= f << g -> f (FIXP g) <= FIXP g -> FIXP (f << g) =-= FIXP g.\nintros; apply: Ole_antisym.\n- apply FIXP_inv. simpl.\n  apply Ole_trans with (f (FIXP g)) ; last by []. by rewrite <- (FIXP_eq g).\n- apply: FIXP_inv.\n  assert (g (f (FIXP  (f << g))) <= f (g (FIXP  (f << g)))).\n  specialize (H (FIXP (f << g))). apply H.\n  case (FIXP_eq (f<<g)); intros.\n  apply Ole_trans with (2:=H3).\n  apply Ole_trans with (2:=H1).\n  apply: fmonotonic.\n  apply FIXP_inv. simpl. apply: fmonotonic.\n  apply Ole_trans with (1:=H1); auto.\nSave.\n\nFixpoint fcont_compn (D:cppoType) (f:D =->D) (n:nat) {struct n} : D =->D := \n             match n with O => f | S p => fcont_compn f p << f end.\n\nAdd Parametric Morphism (D1 D2 D3 : cpoType) : (@ccomp D1 D2 D3)\nwith signature (@Ole (D2 -=> D3) : (D2 =-> D3) -> (D2 =-> D3) -> Prop ) ++> (@Ole (D1 -=> D2)) ++> (@Ole (D1 -=> D3)) \nas fcont_comp_le_compat.\nmove => f g l h k l' x. simpl. rewrite -> l. by rewrite -> l'.\nSave.\n\nLemma fcont_compn_com (D:cppoType) : forall (f:D =->D) (n:nat), \n            f << (fcont_compn f n) <= fcont_compn f n << f.\ninduction n; first by [].\nsimpl fcont_compn. rewrite -> comp_assoc. by apply: (fcont_comp_le_compat _ (Ole_refl f)).\nSave.\n\nLemma FIXP_compn (D:cppoType) : \n     forall  (f:D =->D) (n:nat), FIXP (fcont_compn f n) =-= FIXP f.\nmove => f. case ; first by []. simpl.\nmove => n. apply: FIXP_comp ; first by apply fcont_compn_com.\nelim: n. simpl. by rewrite <- (FIXP_eq f).\nmove => n IH. simpl. rewrite <- (FIXP_eq f). by apply IH.\nSave.\n\nLemma fixp_double (D:cppoType) : forall (f:D=->D), FIXP (f << f) =-= FIXP f.\nintros; exact (FIXP_compn f (S O)).\nSave.\n\n\n(** *** Induction principle *)\n(*=Adm *)\nDefinition admissible (D:cpoType) (P:D -> Prop) := \n             forall f : natO =-> D, (forall n, P (f n)) -> P (lub f).\nLemma fixp_ind (D:cppoType) : forall  (F: D =-> D)(P:D -> Prop),\n             admissible P -> P PBot -> (forall x, P x -> P (F x)) -> P (fixp F). (*CLEAR*)\nmove => F P Adm B I.\napply Adm. by elim ; simpl ; auto.\nQed.\n(*CLEARED*)\n(*=End *)\n\nDefinition admissibleT (D:cpoType) (P:D -> Type) :=\n          forall f : natO =-> D, (forall n, P (f n)) -> P (lub f).\n\nSection SubCPO.\nVariable D E:cpoType.\nVariable P : D -> Prop.\nVariable I:admissible P.\n\nDefinition Subchainlub (c:natO =-> (sub_ordType P)) : sub_ordType P.\nexists (@lub D (Forgetm P << c)).\nunfold admissible in I. specialize (@I (Forgetm P << c)).\napply I. intros i. simpl. case (c i). auto.\nDefined.\n\nLemma subCpoAxiom : CPO.axiom Subchainlub.\nintros c e n. unfold Subchainlub. split. case_eq (c n). intros x Px cn.\nrefine (Ole_trans _ (@le_lub _ (Forgetm P << c) n)).\nsimpl. rewrite cn. auto.\nintros C. simpl.\ncase_eq e. intros dd pd de.\nrefine (lub_le _). intros i. simpl. specialize (C i).\ncase_eq (c i). intros d1 pd1 cn. rewrite cn in C.\nsimpl in C. rewrite de in C. auto.\nQed.\n\nCanonical Structure sub_cpoMixin := CpoMixin subCpoAxiom.\nCanonical Structure sub_cpoType := Eval hnf in CpoType sub_cpoMixin.\n\nLemma InheritFun_cont (f:E =-> D) (p:forall d, P (f d)) : continuous (InheritFunm _ p).\nmove => c. simpl. unfold Ole. simpl. rewrite (fcontinuous f). by apply lub_le_compat => i.\nQed.\n\nDefinition InheritFun (f:E =-> D) (p:forall d, P (f d)) : E =-> sub_cpoType :=\n  Eval hnf in mk_fcont (InheritFun_cont p).\n\nLemma InheritFun_simpl (f:E =-> D) (p:forall d, P (f d)) d : InheritFun p d = InheritFunm _ p d.\nby [].\nQed.\n\nLemma Forgetm_cont : continuous (Forgetm P).\nby move => c.\nQed.\n\nDefinition Forget : sub_cpoType =-> D := Eval hnf in mk_fcont Forgetm_cont.\n\nLemma forgetlub (c:natO =-> (sub_ordType P)) : \n  Forget (Subchainlub c) = (@lub D (Forgetm P << c)).\nauto.\nQed.\n\nLemma ForgetP d : P (Forget d).\nintros. case d. auto.\nQed.\n\nEnd SubCPO.\n\nLemma Forget_leinj: forall (D:cpoType) (P:D -> Prop) (I:admissible P) (d:sub_cpoType I) e, Forget I d <= Forget I e -> d <= e.\nintros D P I d e. case e. clear e. intros e Pe. case d. clear d. intros d Pd.\nauto.\nQed.\n\nHint Resolve Forget_leinj.\n\nLemma Forget_inj : forall (D:cpoType) (P:D -> Prop) (I:admissible P) (d:sub_cpoType I) e, Forget I d =-= Forget I e -> d =-= e.\nintros. by split ; case: H ; case: d ; case: e.\nQed.\n\nHint Resolve Forget_inj.\n\nLemma Forget_leinjp: forall (D E:cpoType) (P:D -> Prop) (I:admissible P) (d:E =-> sub_cpoType I) e,\n      Forget I << d <= Forget I << e -> d <= e.\nintros D E P I d e C x. specialize (C x). simpl in C. unfold FCont.fmono. simpl.\ncase: (e x) C => e' Pe. case: (d x) => d' Pd l. by apply l.\nQed.\n\nLemma Forget_injp: forall (D E:cpoType) (P:D -> Prop) (I:admissible P) (d:E =-> sub_cpoType I) e,\n      Forget I << d =-= Forget I << e -> d =-= e.\nintros D E P I d e C.\napply: fmon_eq_intro. intros x. assert (CC:=fmon_eq_elim C x). simpl in CC.\nunfold FCont.fmono. simpl. clear C.\ncase: (e x) CC. clear e. intros e Pe. case (d x). clear d. intros d Pd.\nauto.\nQed.\n\nLemma InheritFun_eq_compat D E Q Qcc f g X XX : f =-= g ->\n    (@InheritFun D E Q Qcc f X) =-= (@InheritFun D E Q Qcc g XX).\nintros. refine (fmon_eq_intro _). intros d. have A:=fmon_eq_elim H d. clear H. by split ; case: A.\nQed.\n\nLemma ForgetInherit (D E:cpoType) (P:D -> Prop) PS f B : Forget PS << @InheritFun D E P PS f B =-= f.\nby refine (fmon_eq_intro _).\nQed.\n\nLemma InheritFun_comp: forall D E F P I (f:E =-> F) X (g:D =-> E) XX,\n      @InheritFun F _ P I f X << g =-= @InheritFun _ _ P I (f << g) XX.\nintros. refine (fmon_eq_intro _). intros d. simpl.\nsplit ; simpl ; by [].\nQed.\n\n", "meta": {"author": "nbenton", "repo": "coqdomains", "sha": "1ae7ec4af95e4fa44d35d7a5b2452ad123b3a75d", "save_path": "github-repos/coq/nbenton-coqdomains", "path": "github-repos/coq/nbenton-coqdomains/coqdomains-1ae7ec4af95e4fa44d35d7a5b2452ad123b3a75d/src/PredomFix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.787931185683219, "lm_q1q2_score": 0.692707162398137}}
{"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 Plus.\nRequire Import Mult.\nRequire Import Lt.\nOpen Local Scope nat_scope.\n\n(** Factorial *)\n\nFixpoint fact (n:nat) : nat :=\n  match n with\n    | O => 1\n    | S n => S n * fact n\n  end.\n\nArguments Scope fact [nat_scope].\n\nLemma lt_O_fact : forall n:nat, 0 < fact n.\nProof.\n  simple induction n; unfold lt in |- *; simpl in |- *; auto with arith.\nQed.\n\nLemma fact_neq_0 : forall n:nat, fact n <> 0.\nProof.\n  intro.\n  apply sym_not_eq.\n  apply lt_O_neq.\n  apply lt_O_fact.\nQed.\n\nLemma fact_le : forall n m:nat, n <= m -> fact n <= fact m.\nProof.\n  induction 1.\n  apply le_n.\n  assert (1 * fact n <= S m * fact m).\n  apply mult_le_compat.\n  apply lt_le_S; apply lt_O_Sn.\n  assumption.\n  simpl (1 * fact n) in H0.\n  rewrite <- plus_n_O in H0.\n  assumption.\nQed.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/Arith/Factorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.6927071586795128}}
{"text": "(** Formal Reasoning About Programs <http://adam.chlipala.net/frap/>\n  * Chapter 6: Transition Systems\n  * Author: Adam Chlipala\n  * License: https://creativecommons.org/licenses/by-nc-nd/4.0/ *)\n\nRequire Import Frap.\n\nSet Implicit Arguments.\n(* This command will treat type arguments to functions as implicit, like in\n * Haskell or ML. *)\n\n\n(* Here's a classic recursive, functional program for factorial. *)\nFixpoint fact (n : nat) : nat :=\n  match n with\n  | O => 1\n  | S n' => fact n' * S n'\n  end.\n\n(* But let's reformulate factorial relationally, as an example to explore\n * treatment of inductive relations in Coq.  First, these are the states of our\n * state machine. *)\nInductive fact_state :=\n| AnswerIs (answer : nat)\n| WithAccumulator (input accumulator : nat).\n\n(* *Initial* states *)\nInductive fact_init (original_input : nat) : fact_state -> Prop :=\n| FactInit : fact_init original_input (WithAccumulator original_input 1).\n\n(** *Final* states *)\nInductive fact_final : fact_state -> Prop :=\n| FactFinal : forall ans, fact_final (AnswerIs ans).\n\n(** The most important part: the relation to step between states *)\nInductive fact_step : fact_state -> fact_state -> Prop :=\n| FactDone : forall acc,\n  fact_step (WithAccumulator O acc) (AnswerIs acc)\n| FactStep : forall n acc,\n  fact_step (WithAccumulator (S n) acc) (WithAccumulator n (acc * S n)).\n\n(* We care about more than just single steps.  We want to run factorial to\n * completion, for which it is handy to define a general relation of\n * *transitive-reflexive closure*, like so. *)\nInductive trc {A} (R : A -> A -> Prop) : A -> A -> Prop :=\n| TrcRefl : forall x, trc R x x\n| TrcFront : forall x y z,\n  R x y\n  -> trc R y z\n  -> trc R x z.\n\n(* Transitive-reflexive closure is so common that it deserves a shorthand notation! *)\nSet Warnings \"-notation-overridden\". (* <-- needed while we play with defining one\n                                      * of the book's notations ourselves locally *)\nNotation \"R ^*\" := (trc R) (at level 0).\n\n(* Now let's use it to execute the factorial program. *)\nExample factorial_3 : fact_step^* (WithAccumulator 3 1) (AnswerIs 6).\nProof.\nAdmitted.\n\n(* It will be useful to give state machines more first-class status, as\n * *transition systems*, formalized by this record type.  It has one type\n * parameter, [state], which records the type of states. *)\nRecord trsys state := {\n  Initial : state -> Prop;\n  Step : state -> state -> Prop\n}.\n\n(* The example of our factorial program: *)\nDefinition factorial_sys (original_input : nat) : trsys fact_state := {|\n  Initial := fact_init original_input;\n  Step := fact_step\n|}.\n\n(* A useful general notion for transition systems: reachable states *)\nInductive reachable {state} (sys : trsys state) (st : state) : Prop :=\n| Reachable : forall st0,\n  sys.(Initial) st0\n  -> sys.(Step)^* st0 st\n  -> reachable sys st.\n\n(* To prove that our state machine is correct, we rely on the crucial technique\n * of *invariants*.  What is an invariant?  Here's a general definition, in\n * terms of an arbitrary transition system. *)\nDefinition invariantFor {state} (sys : trsys state) (invariant : state -> Prop) :=\n  forall s, sys.(Initial) s\n            -> forall s', sys.(Step)^* s s'\n                          -> invariant s'.\n(* That is, when we begin in an initial state and take any number of steps, the\n * place we wind up always satisfies the invariant. *)\n\n(* Here's a simple lemma to help us apply an invariant usefully,\n * really just restating the definition. *)\nLemma use_invariant' : forall {state} (sys : trsys state)\n  (invariant : state -> Prop) s s',\n  invariantFor sys invariant\n  -> sys.(Initial) s\n  -> sys.(Step)^* s s'\n  -> invariant s'.\nProof.\n  unfold invariantFor.\n  simplify.\n  eapply H.\n  eassumption.\n  assumption.\nQed.\n\nTheorem use_invariant : forall {state} (sys : trsys state)\n  (invariant : state -> Prop) s,\n  invariantFor sys invariant\n  -> reachable sys s\n  -> invariant s.\nProof.\n  simplify.\n  invert H0.\n  eapply use_invariant'.\n  eassumption.\n  eassumption.\n  assumption.\nQed.\n\n(* What's the most fundamental way to establish an invariant?  Induction! *)\nLemma invariant_induction' : forall {state} (sys : trsys state)\n  (invariant : state -> Prop),\n  (forall s, invariant s -> forall s', sys.(Step) s s' -> invariant s')\n  -> forall s s', sys.(Step)^* s s'\n     -> invariant s\n     -> invariant s'.\nProof.\n  induct 2; propositional.\n  (* [propositional]: simplify the goal according to the rules of propositional\n   *   logic. *)\n\n  apply IHtrc.\n  eapply H.\n  eassumption.\n  assumption.\nQed.\n\nTheorem invariant_induction : forall {state} (sys : trsys state)\n  (invariant : state -> Prop),\n  (forall s, sys.(Initial) s -> invariant s)\n  -> (forall s, invariant s -> forall s', sys.(Step) s s' -> invariant s')\n  -> invariantFor sys invariant.\nProof.\n  unfold invariantFor; intros.\n  eapply invariant_induction'.\n  eassumption.\n  eassumption.\n  apply H.\n  assumption.\nQed.\n\nDefinition fact_invariant (original_input : nat) (st : fact_state) : Prop :=\n  True.\n(* We must fill in a better invariant. *)\n\nTheorem fact_invariant_ok : forall original_input,\n  invariantFor (factorial_sys original_input) (fact_invariant original_input).\nProof.\nAdmitted.\n\n(* Therefore, every reachable state satisfies this invariant. *)\nTheorem fact_invariant_always : forall original_input s,\n  reachable (factorial_sys original_input) s\n  -> fact_invariant original_input s.\nProof.\n  simplify.\n  eapply use_invariant.\n  apply fact_invariant_ok.\n  assumption.\nQed.\n\n(* Therefore, any final state has the right answer! *)\nLemma fact_ok' : forall original_input s,\n  fact_final s\n  -> fact_invariant original_input s\n  -> s = AnswerIs (fact original_input).\nAdmitted.\n\nTheorem fact_ok : forall original_input s,\n  reachable (factorial_sys original_input) s\n  -> fact_final s\n  -> s = AnswerIs (fact original_input).\nProof.\n  simplify.\n  apply fact_ok'.\n  assumption.\n  apply fact_invariant_always.\n  assumption.\nQed.\n\n\n(** * A simple example of another program as a state transition system *)\n\n(* We'll formalize this pseudocode for one thread of a concurrent, shared-memory program.\n  lock();\n  local = global;\n  global = local + 1;\n  unlock();\n*)\n\n(* This inductive state effectively encodes all possible combinations of two\n * kinds of *local*state* in a thread:\n * - program counter\n * - values of local variables that may be read eventually *)\nInductive increment_program :=\n| Lock\n| Read\n| Write (local : nat)\n| Unlock\n| Done.\n\n(* Next, a type for state shared between threads. *)\nRecord inc_state := {\n  Locked : bool; (* Does a thread hold the lock? *)\n  Global : nat   (* A shared counter *)\n}.\n\n(* The combined state, from one thread's perspective, using a general\n * definition. *)\nRecord threaded_state shared private := {\n  Shared : shared;\n  Private : private\n}.\n\nDefinition increment_state := threaded_state inc_state increment_program.\n\n(* Now a routine definition of the three key relations of a transition system.\n * The most interesting logic surrounds saving the counter value in the local\n * state after reading. *)\n\nInductive increment_init : increment_state -> Prop :=\n| IncInit :\n  increment_init {| Shared := {| Locked := false; Global := O |};\n                    Private := Lock |}.\n\nInductive increment_step : increment_state -> increment_state -> Prop :=\n| IncLock : forall g,\n  increment_step {| Shared := {| Locked := false; Global := g |};\n                    Private := Lock |}\n                 {| Shared := {| Locked := true; Global := g |};\n                    Private := Read |}\n| IncRead : forall l g,\n  increment_step {| Shared := {| Locked := l; Global := g |};\n                    Private := Read |}\n                 {| Shared := {| Locked := l; Global := g |};\n                    Private := Write g |}\n| IncWrite : forall l g v,\n  increment_step {| Shared := {| Locked := l; Global := g |};\n                    Private := Write v |}\n                 {| Shared := {| Locked := l; Global := S v |};\n                    Private := Unlock |}\n| IncUnlock : forall l g,\n  increment_step {| Shared := {| Locked := l; Global := g |};\n                    Private := Unlock |}\n                 {| Shared := {| Locked := false; Global := g |};\n                    Private := Done |}.\n\nDefinition increment_sys := {|\n  Initial := increment_init;\n  Step := increment_step\n|}.\n\n\n(** * Running transition systems in parallel *)\n\n(* That last example system is a cop-out: it only runs a single thread.  We want\n * to run several threads in parallel, sharing the global state.  Here's how we\n * can do it for just two threads.  The key idea is that, while in the new\n * system the type of shared state remains the same, we take the Cartesian\n * product of the sets of private state. *)\n\nInductive parallel_init shared private1 private2\n  (init1 : threaded_state shared private1 -> Prop)\n  (init2 : threaded_state shared private2 -> Prop)\n  : threaded_state shared (private1 * private2) -> Prop :=\n| Pinit : forall sh pr1 pr2,\n  init1 {| Shared := sh; Private := pr1 |}\n  -> init2 {| Shared := sh; Private := pr2 |}\n  -> parallel_init init1 init2 {| Shared := sh; Private := (pr1, pr2) |}.\n\nInductive parallel_step shared private1 private2\n          (step1 : threaded_state shared private1 -> threaded_state shared private1 -> Prop)\n          (step2 : threaded_state shared private2 -> threaded_state shared private2 -> Prop)\n          : threaded_state shared (private1 * private2)\n            -> threaded_state shared (private1 * private2) -> Prop :=\n| Pstep1 : forall sh pr1 pr2 sh' pr1',\n  (* First thread gets to run. *)\n  step1 {| Shared := sh; Private := pr1 |} {| Shared := sh'; Private := pr1' |}\n  -> parallel_step step1 step2 {| Shared := sh; Private := (pr1, pr2) |}\n               {| Shared := sh'; Private := (pr1', pr2) |}\n| Pstep2 : forall sh pr1 pr2 sh' pr2',\n  (* Second thread gets to run. *)\n  step2 {| Shared := sh; Private := pr2 |} {| Shared := sh'; Private := pr2' |}\n  -> parallel_step step1 step2 {| Shared := sh; Private := (pr1, pr2) |}\n               {| Shared := sh'; Private := (pr1, pr2') |}.\n\nDefinition parallel shared private1 private2\n           (sys1 : trsys (threaded_state shared private1))\n           (sys2 : trsys (threaded_state shared private2)) := {|\n  Initial := parallel_init sys1.(Initial) sys2.(Initial);\n  Step := parallel_step sys1.(Step) sys2.(Step)\n|}.\n\n(* Example: composing two threads of the kind we formalized earlier *)\nDefinition increment2_sys := parallel increment_sys increment_sys.\n\n(* Let's prove that the counter is always 2 when the composed program terminates. *)\n\n(** We must write an invariant. *)\nInductive increment2_invariant :\n  threaded_state inc_state (increment_program * increment_program) -> Prop :=\n| Inc2Inv : forall sh pr1 pr2,\n  increment2_invariant {| Shared := sh; Private := (pr1, pr2) |}.\n(* This isn't it yet! *)\n\n(* Now, to show it really is an invariant. *)\nTheorem increment2_invariant_ok : invariantFor increment2_sys increment2_invariant.\nProof.\nAdmitted.\n\n(* Now, to prove our final result about the two incrementing threads, let's use\n * a more general fact, about when one invariant implies another. *)\nTheorem invariant_weaken : forall {state} (sys : trsys state)\n  (invariant1 invariant2 : state -> Prop),\n  invariantFor sys invariant1\n  -> (forall s, invariant1 s -> invariant2 s)\n  -> invariantFor sys invariant2.\nProof.\n  unfold invariantFor; simplify.\n  apply H0.\n  eapply H.\n  eassumption.\n  assumption.\nQed.\n\n(* Here's another, much weaker invariant, corresponding exactly to the overall\n * correctness property we want to establish for this system. *)\nDefinition increment2_right_answer\n  (s : threaded_state inc_state (increment_program * increment_program)) :=\n  s.(Private) = (Done, Done)\n  -> s.(Shared).(Global) = 2.\n\n(** Now we can prove that the system only runs to happy states. *)\nTheorem increment2_sys_correct : forall s,\n  reachable increment2_sys s\n  -> increment2_right_answer s.\nProof.\nAdmitted.\n(*simplify.\n  eapply use_invariant.\n  apply invariant_weaken with (invariant1 := increment2_invariant).\n  (* Note the use of a [with] clause to specify a quantified variable's\n   * value. *)\n\n  apply increment2_invariant_ok.\n\n  simplify.\n  invert H0.\n  unfold increment2_right_answer; simplify.\n  invert H0.\n  (* Here we use inversion on an equality, to derive more primitive\n   * equalities. *)\n  simplify.\n  equality.\n\n  assumption.\nQed.*)\n", "meta": {"author": "achlipala", "repo": "frap", "sha": "ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb", "save_path": "github-repos/coq/achlipala-frap", "path": "github-repos/coq/achlipala-frap/frap-ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb/TransitionSystems_template.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6927071518065762}}
{"text": "(********************************************************************)\n(*                                                                  *)\n(*  The Why3 Verification Platform   /   The Why3 Development Team  *)\n(*  Copyright 2010-2019   --   Inria - CNRS - Paris-Sud University  *)\n(*                                                                  *)\n(*  This software is distributed under the terms of the GNU Lesser  *)\n(*  General Public License version 2.1, with the special exception  *)\n(*  on linking described in file LICENSE.                           *)\n(*                                                                  *)\n(********************************************************************)\n\n(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire Reals.R_sqrt.\nRequire BuiltIn.\nRequire real.Real.\n\nImport R_sqrt.\n\n(* Why3 goal *)\nLemma sqr_def :\n  forall (x:Reals.Rdefinitions.R), ((Reals.RIneq.Rsqr x) = (x * x)%R).\nreflexivity.\nQed.\n\n(* Why3 comment *)\n(* sqrt is replaced with (Reals.R_sqrt.sqrt x) by the coq driver *)\n\n(* Why3 goal *)\nLemma Sqrt_positive :\n  forall (x:Reals.Rdefinitions.R), (0%R <= x)%R ->\n  (0%R <= (Reals.R_sqrt.sqrt x))%R.\nintros x _.\napply sqrt_pos.\nQed.\n\n(* Why3 goal *)\nLemma Sqrt_square :\n  forall (x:Reals.Rdefinitions.R), (0%R <= x)%R ->\n  ((Reals.RIneq.Rsqr (Reals.R_sqrt.sqrt x)) = x).\nexact sqrt_sqrt.\nQed.\n\n(* Why3 goal *)\nLemma Square_sqrt :\n  forall (x:Reals.Rdefinitions.R), (0%R <= x)%R ->\n  ((Reals.R_sqrt.sqrt (x * x)%R) = x).\nexact sqrt_square.\nQed.\n\n(* Why3 goal *)\nLemma Sqrt_mul :\n  forall (x:Reals.Rdefinitions.R) (y:Reals.Rdefinitions.R),\n  (0%R <= x)%R /\\ (0%R <= y)%R ->\n  ((Reals.R_sqrt.sqrt (x * y)%R) =\n   ((Reals.R_sqrt.sqrt x) * (Reals.R_sqrt.sqrt y))%R).\nintros x y (hx & hy); now apply sqrt_mult.\nQed.\n\n(* Why3 goal *)\nLemma Sqrt_le :\n  forall (x:Reals.Rdefinitions.R) (y:Reals.Rdefinitions.R),\n  (0%R <= x)%R /\\ (x <= y)%R ->\n  ((Reals.R_sqrt.sqrt x) <= (Reals.R_sqrt.sqrt y))%R.\nintros x y (h1 & h2); apply sqrt_le_1; auto.\napply Rle_trans with x; auto.\nQed.\n\n", "meta": {"author": "schrodibear", "repo": "why3", "sha": "9f8eb767380987a28e43b81729ae1d682363bb49", "save_path": "github-repos/coq/schrodibear-why3", "path": "github-repos/coq/schrodibear-why3/why3-9f8eb767380987a28e43b81729ae1d682363bb49/lib/coq/real/Square.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382004, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6926977855151808}}
{"text": "Section Ejercicio1.\n\nVariable U  : Set.\nVariable A B: U -> Prop.\nVariable P Q: Prop.\nVariable R S: U -> U -> Prop.\n\nTheorem e11 : (forall x:U, A(x)) -> forall y:U, A(y).\nProof.\nauto.\nQed.\n\nTheorem e12 : (forall x y:U, (R x y)) -> forall x y:U, (R y x).\nProof.\nauto.\nQed.\n\nTheorem e13 : (forall x: U, ((A x)->(B x)))\n                        -> (forall y:U, (A y))\n                          -> (forall z:U, (B z)).\nProof.\nauto.\nQed.\n\n\nEnd Ejercicio1.\n\n\n\nSection Ejercicio2.\n\nVariable U  : Set.\nVariable A B: U -> Prop.\nVariable P Q: Prop.\nVariable R S: U -> U -> Prop.\n\n\nTheorem e21 : (forall x:U, ((A x)-> ~(forall x:U, ~ (A x)))).\nProof.\nintros.\nunfold not.\nintro.\napply (H0 x).\nassumption.\nQed.\n\nTheorem e22 : (forall x y:U, ((R x y)))-> (forall x:U, (R x x)).\nProof.\nintros.\napply (H x x).\nQed.\n\nTheorem e23 : (forall x:U, ((P -> (A x))))\n                        -> (P -> (forall x: U, (A x))).\nProof.\nintros.\napply (H x).\nassumption.\nQed.\n\n\nTheorem e24 : (forall x:U, ((A x) /\\ (B x)))\n                        -> (forall x:U, (A x))\n                          -> (forall x:U, (B x)).\nProof.\nintros.\napply (H x).\nQed.\n\nEnd Ejercicio2.\n\n\n\nSection Ejercicio3.\n\nVariable U   : Set.\nVariable A B : U -> Prop.\nVariable P Q : Prop.\nVariable R S : U -> U -> Prop.\n\nHypothesis H1: forall x:U, (R x x).\nHypothesis H2: forall x y z:U, (R x y) /\\ (R x z) -> (R y z).\n\nTheorem reflexiva: forall x : U, R x x.\nProof.\nauto.\nQed.\n\nTheorem simetrica: forall x y : U, R x y -> R y x.\nProof.\nintros.\napply (H2 x y x).\nsplit; [ assumption | trivial ].\nQed.\n\nTheorem transitiva: forall x y z : U, R x y /\\ R y z -> R x z.\nProof.\nintros.\napply (H2 y x z).\nsplit; [ apply simetrica | idtac ]; elim H; auto.\nQed.\n\nEnd Ejercicio3.\n\nSection Ejercicio4.\n\nVariable U : Set.\nVariable A : U->Prop.\nVariable R : U->U->Prop.\n\nTheorem e41: (exists x:U, exists y:U, (R x y)) -> exists y:U, exists x:U, (R x y).\nProof.\nintros.\nelim H.\nintros.\nelim H0.\nintros.\nexists x0.\nexists x.\nassumption.\nQed.\n\nTheorem e42: (forall x:U, A(x)) -> ~ exists x:U, ~ A(x).\nProof.\nunfold not.\nintros.\nelim H0.\nintros.\napply (H1 (H x)).\nQed.\n\nTheorem e43: (exists x:U, ~(A x)) -> ~(forall x:U, (A x)).\nProof.\nunfold not.\nintros.\nelim H.\nintros.\napply (H1 (H0 x)).\nQed.\n\nEnd Ejercicio4.\n\n\n\nSection Ejercicio5.\n\nVariable nat      : Set.\nVariable S        : nat -> nat.\nVariable a b c    : nat.\nVariable odd even : nat -> Prop.\nVariable P Q      : nat -> Prop.\nVariable f        : nat -> nat.\n\nTheorem e51: forall x:nat, exists y:nat, (P(x)->P(y)).\nProof.\nintros.\nexists x.\ntrivial.\nQed.\n\nTheorem e52: exists x:nat, (P x)\n                            -> (forall y:nat, (P y)->(Q y))\n                               -> (exists z:nat, (Q z)).\nProof.\nexists a.\nintros.\nexists a.\napply ((H0 a) H).\nQed.\n\nTheorem e53: even(a) -> (forall x:nat, (even(x)->odd (S(x)))) -> exists y: nat, odd(y).\nProof.\nintros.\nexists (S a).\napply ((H0 a) H).\nQed.\n\n\nTheorem e54: (forall x:nat, P(x) /\\ odd(x) ->even(f(x)))\n                            -> (forall x:nat, even(x)->odd(S(x)))\n                            -> even(a)\n                            -> P(S(a))\n                            -> exists z:nat, even(f(z)).\nProof.\nintros.\nexists (S a).\napply (H (S a)).\nsplit; [ idtac | apply (H0 a)]; assumption.\nQed.\n\nEnd Ejercicio5.\n\n\n\nSection Ejercicio6.\n\nVariable nat : Set.\nVariable S   : nat -> nat.\nVariable le  : nat -> nat -> Prop.\nVariable f   : nat -> nat.\nVariable P   : nat -> Prop.\n\nAxiom le_n: forall n:nat, (le n n).\nAxiom le_S: forall n m:nat, (le n m) -> (le n (S m)).\nAxiom monoticity: forall n m:nat, (le n m) -> (le (f n) (f m)).\n\n\nLemma le_x_Sx: forall x:nat, (le x (S x)).\nProof.\nintro.\napply le_S.\napply le_n.\nQed.\n\nLemma le_x_SSx: forall x:nat, (le x (S (S x))).\nProof.\nintro.\napply le_S.\napply le_x_Sx.\nQed.\n\nTheorem T1_1: forall a:nat, exists b:nat, (le (f a) b).\nProof.\nintros.\nexists (f a).\napply monoticity.\napply le_n.\nQed.\n\nTheorem T1_2: forall a:nat, exists b:nat, (le (f a) b).\nProof.\nintros.\nexists (f (S a)).\napply monoticity.\napply le_x_Sx.\nQed.\n\nTheorem T1_3: forall a:nat, exists b:nat, (le (f a) b).\nProof.\nintros.\nexists (f (S (S a))).\napply monoticity.\napply le_x_SSx.\nQed.\n\nTheorem T1_a: forall a:nat, exists b:nat, (le (f a) b).\nProof.\nintros.\nexists ((S (S (S (S (S (f a))))))).\nrepeat apply le_S.\napply le_n.\nQed.\n\nTheorem T1_b: forall a:nat, exists b:nat, (le (f a) b).\nProof.\nintros.\nexists ((S (S (S (S (S (f a))))))).\ndo 5 apply le_S.\napply le_n.\nQed.\n\nEnd Ejercicio6.\n\nSection Ejercicio7.\n\nVariable U   : Set.\nVariable A B : U -> Prop.\n\nTheorem e71: (forall x:U, ((A x) /\\ (B x)))\n                       -> (forall x:U, (A x)) /\\ (forall x:U, (B x)).\nProof.\nintro; split; intro num; apply (H num).\nQed.\n\nTheorem e72: (exists x:U, (A x \\/ B x))->(exists x:U, A x )\\/(exists x:U, B x).\nProof. \nintro; elim H; intros; elim H0; intro; [left | right]; exists x; assumption.\nQed.\n\nEnd Ejercicio7.\n\nSection Ejercicio8.\n\nVariable U  : Set.\n\nVariable R : U -> U -> Prop.\nVariable T : U -> Prop.\nVariable V : U -> Prop.\n\nTheorem ej8_1 : (exists y : U, forall x : U, R x y) -> (forall x : U, exists y : U, R x y).\nProof.\nintros.\nelim H.\nintros.\nexists x0.\napply (H0 x).\nQed.\n\nTheorem ej8_2: (exists y:U, True)/\\(forall x:U, (T x) \\/ (V x)) ->  \n(exists z:U, (T z)) \\/ (exists w:U, (V w)).\nProof.\nintros.\napply e72.\nelim H.\nintros.\nelim H0.\nintros.\nexists x.\ntrivial.\nQed.\n\n\n(**\n  En la siguiente demostración pruebo que (exists y:U, True) es condición necesaria\n  para demostrar el teorema de arriba.\n**)\nTheorem ej8_3: (exists z:U, (T z)) \\/ (exists w:U, (V w)) -> (exists y:U, True).\nProof.\nintros.\nelim H; intro; elim H0; intros; exists x; trivial.\nQed.\n\nEnd Ejercicio8.\n\nSection Ejercicio9.\nRequire Import Classical.\nVariables U : Set.\nVariables A : U -> Prop.\n\nLemma not_ex_not_forall: (~exists x :U, ~A x) -> (forall x:U, A x).\nProof.\nunfold not.\nintros.\nelim (classic (A x));intro; [ | elim H; exists x ]; assumption.\nQed.\n\nLemma not_forall_ex_not: (~forall x :U, A x) -> (exists x:U,  ~A x).\nProof.\nunfold not.\nintros.\nelim (classic (exists x : U, not (A x))); [ trivial | intro ].\nassert (forall x:U, A x); [ apply not_ex_not_forall | elim H ]; assumption.\nQed.\n\nEnd Ejercicio9.\n\nSection Ejercicio10y11.\n\nVariable nat : Set.\nVariable  O  : nat.\nVariable  S  : nat -> nat.\n\nAxiom disc   : forall n:nat, ~O=(S n).\nAxiom inj    : forall n m:nat, (S n)=(S m) -> n=m.\n\nVariable sum prod : nat->nat->nat.\nAxiom sum0   : forall n :nat, (sum n O)=n.\nAxiom sumS   : forall n m :nat, (sum n (S m))=(S (sum n m)).\nAxiom prod0  : forall n :nat, (prod n O)=O.\nAxiom prodS  : forall n m :nat, (prod n (S m))=(sum n (prod n m)).\n\n\nLemma L10_1: (sum (S O) (S O)) = (S (S O)).\nProof.\nrewrite sumS.\nrewrite sum0.\nreflexivity.\nQed.\n\nLemma L10_2: forall n :nat, ~(O=n /\\ (exists m :nat, n = (S m))).\nProof.\nunfold not.\nintros.\nelim H.\nintros.\nelim H1.\nrewrite <- H0.\napply disc.\nQed.\n\nLemma prod_neutro: forall n :nat, (prod n (S O)) = n.\nProof.\nintros.\nrewrite prodS.\nrewrite prod0.\napply sum0.\nQed.\n\nLemma diff: forall n:nat, ~(S (S n))=(S O).\nProof.\nunfold not.\nintros.\ncut (O = S n); [ apply disc | symmetry; apply inj; assumption ].\nQed.\n\nAxiom induccion: forall (P : nat -> Prop) , P O -> (forall x , P\nx -> P (S x)) -> forall x , P x .\n\nVariable le : nat->nat->Prop.\nAxiom leinv: forall n m:nat, (le n m) -> n=O \\/\n      (exists p:nat, (exists q:nat, n=(S p)/\\ m=(S q) /\\ (le p q))).\n\nLemma notle_s_o: forall n:nat, ~(le (S n) O).\nProof.\nunfold not.\nintros.\nelim (leinv (S n) O); intros;\n  [ apply (disc n); auto\n  | elim H0;\n    intros;\n    elim H1;\n    intros;\n    elim H2;\n    elim (disc x0);\n    elim H2;\n    intros;\n    elim H4;\n    trivial\n  | assumption].\nQed.\n\nEnd Ejercicio10y11.", "meta": {"author": "nicodelpiano", "repo": "coq", "sha": "06344cda6995cdd9c5d44c52880b49a7ec280ebd", "save_path": "github-repos/coq/nicodelpiano-coq", "path": "github-repos/coq/nicodelpiano-coq/coq-06344cda6995cdd9c5d44c52880b49a7ec280ebd/TP2/tp2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6926977700490127}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) : natural := plus (Succ lf2) Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj62_coqofml_n4mQJC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178928, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6925796709293915}}
{"text": "(* fields *)\n\n(*\nSet Implicit Arguments.\n*)\n\nRequire Import Utf8.\nRequire Import Semiring.\n\nClass field_op T :=\n  { fld_inv : T → T }.\n\nDefinition fld_div T {fo : field_op T} {so : semiring_op T} a b :=\n  srng_mul a (fld_inv b).\n\nDeclare Scope field_scope.\n\nDelimit Scope field_scope with F.\nNotation \"0\" := (@srng_zero _ _) : field_scope.\nNotation \"1\" := (@srng_one _ _) : field_scope.\nNotation \"- a\" := (@rng_opp _ _ a) : field_scope.\nNotation \"/ a\" := (@fld_inv _ _ a) : field_scope.\nNotation \"a + b\" := (@srng_add _ _ a b) : field_scope.\nNotation \"a - b\" := (@rng_sub _ _ _ a b) : field_scope.\nNotation \"a * b\" := (@srng_mul _ _ a b) : field_scope.\nNotation \"a / b\" := (@fld_div _ _ _ a b) : field_scope.\n\nClass field_prop A {so : semiring_op A} {fo : field_op A} :=\n  { fld_mul_inv_l : ∀ a : A, a ≠ 0%F → (/ a * a = 1)%F }.\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/old/Field2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6925796655030275}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Arith.Compare_dec.\nImport ListNotations.\nSet Implicit Arguments.\n\n\nInductive Regex (n : Set) :=\n | Elem  : n -> Regex n\n | Empty :      Regex n\n | Seq   :      Regex n -> Regex n -> Regex n\n | Alt   :      Regex n -> Regex n -> Regex n\n | Star  :      Regex n -> Regex n\n .\n\nInductive Match (n : Set) : Regex n -> list n -> Prop :=\n | MElem  : forall e:n, Match (Elem e)  [e]\n | MEmpty :             Match (Empty _) []\n\n | MSeq   : forall r1 r2 l1 l2,\n            Match r1 l1\n         -> Match r2 l2\n         -> Match (Seq r1 r2) (l1 ++ l2)\n\n | MAlt_L : forall r1 r2 l,\n            Match r1 l\n         -> Match (Alt r1 r2) l\n | MAlt_R : forall r1 r2 l,\n            Match r2 l\n         -> Match (Alt r1 r2) l\n\n | MStar_0: forall r,\n            Match (Star r) []\n | MStar_1: forall r l l',\n            Match r l\n         -> Match (Star r) l'\n         -> Match (Star r) (l ++ l')\n .\n\nDefinition RegexEq (n : Set) (r1 r2 : Regex n) :=\n  forall l, Match r1 l -> Match r2 l\n   /\\       Match r2 l -> Match r1 l.\n\n(* I promise! *)\nAxiom RegexEq_dec : forall (n : Set) (r1 r2 : Regex n), RegexEq r1 r2 \\/ ~ RegexEq r1 r2.\n\n\nCheck filter.\n\nFixpoint filterRx (A : Set) (f : A -> bool) (rx : Regex A) :=\n match rx with\n | Empty => Empty _\n | Elem n => if f n then Elem n else Empty _\n | Seq p q => Seq (filterRx f p) (filterRx f q)\n | Alt p q => Alt (filterRx f p) (filterRx f q)\n | Star p  => Star (filterRx f p)\n end.\n\nTheorem filter_app_dist (A : Set) (f : A -> bool) (a b : list A) :\n   filter f (a ++ b) = filter f a ++ filter f b.\nProof.\n induction a; simpl;\n   try destruct (f a);\n   try rewrite IHa;\n   eauto.\nQed.\n\nTheorem filter_same (A : Set) (f : A -> bool) (rx : Regex A) (w : list A) :\n Match rx w -> Match (filterRx f rx) (filter f w).\nProof.\n intros.\n induction H; eauto; simpl;\n  try rewrite filter_app_dist;\n  try (destruct (f e));\n  try solve [constructor; eauto];\n  eauto.\n\n apply MAlt_R; eauto.\nQed.\n\n", "meta": {"author": "amosr", "repo": "coq", "sha": "7e8c28e2222d897884880c21ff71d29799e5b1f5", "save_path": "github-repos/coq/amosr-coq", "path": "github-repos/coq/amosr-coq/coq-7e8c28e2222d897884880c21ff71d29799e5b1f5/merges/Regex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6925796641099833}}
{"text": "Require Import init.\n\nRequire Export ord_order.\nRequire Import ord_plus.\nRequire Import ord_mult.\nRequire Import set.\nRequire Import nat.\n\nTheorem transfinite_induction :\n    ∀ S : ord → Prop, (∀ α, (∀ β, β < α → S β) → S α) → ∀ α, S α.\nProof.\n    intros S S_all α.\n    classic_contradiction contr.\n    pose (S' α := ¬S α).\n    assert (∃ β, S' β) as S'_nempty by (exists α; exact contr).\n    pose proof (well_ordered S' S'_nempty) as [β [S'β β_min]].\n    apply S'β.\n    apply S_all.\n    intros γ γ_lt.\n    classic_contradiction S'γ.\n    specialize (β_min _ S'γ).\n    destruct (lt_le_trans γ_lt β_min); contradiction.\nQed.\n\nDefinition suc_ord α := ∃ β, α = β + 1.\nDefinition lim_ord α := 0 ≠ α ∧ ¬suc_ord α.\n\nTheorem transfinite_induction2 :\n    ∀ S : ord → Prop,\n    (∀ α, suc_ord α → (∀ β, β < α → S β) → S α) →\n    (∀ α, ¬suc_ord α → (∀ β, β < α → S β) → S α) →\n    ∀ α, S α.\nProof.\n    intros S sucs lims α.\n    induction α using transfinite_induction.\n    classic_case (suc_ord α).\n    -   apply sucs; assumption.\n    -   apply lims; assumption.\nQed.\n\nTheorem transfinite_induction3 :\n    ∀ S : ord → Prop,\n    S 0 →\n    (∀ α, suc_ord α → (∀ β, β < α → S β) → S α) →\n    (∀ α, lim_ord α → (∀ β, β < α → S β) → S α) →\n    ∀ α, S α.\nProof.\n    intros S S0 sucs lims α.\n    induction α using transfinite_induction2.\n    -   apply sucs; assumption.\n    -   classic_case (0 = α) as [eq|neq].\n        +   rewrite <- eq.\n            exact S0.\n        +   apply lims; try assumption.\n            split; assumption.\nQed.\n\nTheorem ord_lt_plus1 : ∀ α, α < α + 1.\nProof.\n    intros α.\n    apply ord_lt_self_rplus.\n    apply ord_not_trivial.\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/Set/Ordinal/ord_induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.6925727989161038}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice fintype.\nRequire Import div finfun bigops prime binomial ssralg finset groups finalg.\nRequire Import perm zmodp.\n\n(*****************************************************************************)\n(* Basic concrete linear algebra : definition of type for matrices, and all  *)\n(* basic matrix operations, including determinant, trace, rank, support for  *)\n(* for block decomposition, and row space computation (the latter provides a *)\n(* computational basis for the construction of abstract vector spaces).      *)\n(* While matrices are represented by a row-major list of their coefficients, *)\n(* this is hidden by three levels of wrappers (Matrix/Finfun/Tuple) so the   *)\n(* matrix type should be treated as abstract and handled using only the      *)\n(* operations described below:                                               *)\n(*   'M[R]_(m, n) == the type of m rows by n columns matrices with           *)\n(*                   coefficients in R; the [R] is optional and usually      *)\n(*                   omitted.                                                *)\n(*   'M_n, 'rV_n, == n x n square matrices, 1 x n row vectors, and n x 1     *)\n(*   'cV_n           column vectors, respectively.                           *)\n(*  \\matrix_(i < m, j < n) Expr(i, j) ==                                     *)\n(*                   the m x n matrix with general coefficient Expr(i, j),   *)\n(*                   with i : 'I_m and j : 'I_n. the < m bound can be        *)\n(*                   omitted if it is equal to n, though usually both bounds *)\n(*                   are omitted as they can be inferred from the context.   *)\n(*  \\row_(j < n) Expr(j), \\col_(i < m) Expr(i)                               *)\n(*                   the row / column vectors with general term Expr; the    *)\n(*                   parentheses can be omitted along with the bound.        *)\n(* \\matrix_(i < m) RowExpr(i) ==                                             *)\n(*                   the m x n matrix with row i given by RowExpr(i) : 'rV_n *)\n(*          A i j == the coefficient of matrix A : 'M_(m, n) in column j of  *)\n(*                   row i, where i : 'I_m, and j : 'I_n (via the coercion   *)\n(*                   fun_of_matrix : matrix >-> Funclass).                   *)\n(*     const_mx a == the constant matrix whose entries are all a (dimensions *)\n(*                   should be determined by context).                       *)\n(*     map_mx f A == the pointwise image of A by f, i.e., the matrix Af      *)\n(*                   congruent to A with Af i j = f (A i j) for all i and j. *)\n(*            A^T == the matrix transpose of A                               *)\n(*        row i A == the i'th row of A (this is a row vector)                *)\n(*        col j A == the j'th column of A (a column vector)                  *)\n(*       row' i A == A with the i'th row spliced out                         *)\n(*       col' i A == A with the j'th column spliced out                      *)\n(*   xrow i1 i2 A == A with rows i1 and i2 interchanged.                     *)\n(*   xcol j1 j2 A == A with columns j1 and j2 interchanged.                  *)\n(*   row_perm s A == A : 'M_(m, n) with rows permuted by s : 'S_m            *)\n(*   col_perm s A == A : 'M_(m, n) with columns permuted by s : 'S_n         *)\n(*   row_mx Al Ar == the row block matrix <Al Ar> obtained by contatenating  *)\n(*                   two matrices Al and Ar of the same height.              *)\n(*   col_mx Au Ad == the column block matrix / Au \\ (Au and Ad must have the *)\n(*                   same width).            \\ Ad /                          *)\n(* block_mx Aul Aur Adl Adr == the block matrix / Aul Aur \\                  *)\n(*                                              \\ Adl Adr /                  *)\n(*   [l|r]submx A == the left/right submatrices of a row block matrix A.     *)\n(*                   Note that the type of A, 'M_(m, n1 + n2) indicatres     *)\n(*                   how A should be decomposed.                             *)\n(*   [u|d]submx A == the up/down submatrices of a column block matrix A.     *)\n(* [u|d][l|r]submx A == the upper left, etc submatrices of a block matrix A. *)\n(* castmx eq_mn A == A : 'M_(m, n) casted to 'M_(m', n') using the equation  *)\n(*                   pair eq_mn : (m = m') * (n = n'). This is the usual     *)\n(*                   workaround for the syntactic limitations of dependent   *)\n(*                   types in Coq, and can be used to introduce a block      *)\n(*                   decomposition. It simplifies to A when eq_mn is the     *)\n(*                   pair (erefl m, erefl n) (using rewrite /castmx /=).     *)\n(* conform_mx B A == A if A and B have the same dimensions, else B.          *)\n(* In 'M[R]_(m, n), R can be any type, but 'M[R]_(m, n) inherits the eqType, *)\n(* choiceType, countType, finType, and zmodType structures of R; however,    *)\n(* because the type of matrices specifies their dimension, only non-trivial  *)\n(* square matrices (of type 'M[R]_n.+1) can inherit the ring structure of R; *)\n(* they can also inherit the unit ring structure of R when R is commutative. *)\n(*   We thus provide separate syntax for the general matrix multiplication,  *)\n(* and other operations for matrices over a ringType R:                      *)\n(*         A *m B == the matrix product of A and B; the width of A must be   *)\n(*                   equal to the height of B.                               *)\n(*        a *m: A == the matrix A scaled by factor a. This will be subsumed  *)\n(*                   by the *: operation of the vector space structure, but  *)\n(*                   we need to define matrices first.                       *)\n(*           a%:M == the scalar matrix with a's on the main diagonal; in     *)\n(*                   particular 1%:M denotes the identity matrix, and is is  *)\n(*                   equal to 1%R when n is of the form n'.+1 (e.g., n = 1). *)\n(*      diag_mx d == the diagonal matrix whose main diagonal is d : 'rV_n.   *)\n(*   delta_mx i j == the matrix with a 1 in row i, column j and 0 elsewhere. *)\n(*       pid_mx r == the partial identity matrix with 1s only on the r first *)\n(*                   coefficients of the main diagonal; the dimensions of    *)\n(*                   pid_mx r are determined by the context, and can be      *)\n(*                   rectangular.                                            *)\n(*     copid_mx r == the complement to 1 of pid_mx r: a square matrix with   *)\n(*                   1s on all but the first r coefficients on its main      *)\n(*                   diagonal.                                               *)\n(*      perm_mx s == the n x n permutation matrix for s : 'S_n.              *)\n(* tperm_mx i1 i2 == the permutation matrix that exchanges i1 i2 : 'I_n.     *)\n(*   is_perm_mx A == A is a permutation matrix.                              *)\n(*     lift0_mx A == the 1 + n square matrix block_mx 1 0 0 A when A : 'M_n. *)\n(*          \\tr A == the trace of a square matrix A.                         *)\n(*         \\det A == the determinant of A, using the Leibnitz formula.       *)\n(* cofactor i j A == the i, j cofactor of A (the signed i, j minor of A),    *)\n(*         \\adj A == the adjugate matrix of A (\\adj A i j = cofactor j i A). *)\n(*   A \\in unitmx == A is invertible (R must be a comUnitRingType).          *)\n(*        invmx A == the inverse matrix of A if A \\in unitmx A, otherwise A. *)\n(* The definition of the triangular decomposition, rank and row space        *)\n(* operations are limited to matrices over a fieldType F:                    *)\n(*    cormenLUP A == the triangular decomposition (L, U, P) of a nontrivial  *)\n(*                   square matrix A into a lower triagular matrix L with 1s *)\n(*                   on the main diagonal, an upper matrix U, and a          *)\n(*                   permutation matrix P, such that P * A = L * U.          *)\n(*      erankmx A == the extended rank decomposition (L, U, r) of A, with L  *)\n(*                   a column permutation of a lower triangular invertible   *)\n(*                   matrix, U a row permutation of an upper triangular      *)\n(*                   invertible matrix, and r the rank of A, all satisfying  *)\n(*                   the identity L *m pid_mx r *m U = A.                    *)\n(*        \\rank A == the rank of A.                                          *)\n(*    row_free A <=> the rows of A are linearly free (i.e., the rank and     *)\n(*                   height of A are equal).                                 *)\n(*    row_full A <=> the row-space of A spans all row-vectors (i.e., the     *)\n(*                   rank and width of A are equal).                         *)\n(*    col_ebase A == the extended column basis of A (the first matrix L      *)\n(*                   returned by emxrank A).                                 *)\n(*    row_ebase A == the extended row base of A (the second matrix U         *)\n(*                   returned by emxrank A).                                 *)\n(*     col_base A == a basis for the columns of A: a row-full matrix         *)\n(*                   consisting of the first \\rank A columns of col_ebase A. *)\n(*     row_base A == a basis for the rows of A: a row-free matrix consisting *)\n(*                   of the first \\rank A rows of row_ebase A.               *)\n(*       pinvmx A == a partial inverse for A in its row space (or on its     *)\n(*                   column space, equivalently). In particular, if u is a   *)\n(*                   row vector in the row_space of A, then u *m pinvmx A is *)\n(*                   the row vector of the coefficients of a decomposition   *)\n(*                   of u as a sub of rows of A                              *)\n(*        kermx A == the row kernel of A : a square matrix whose row space   *)\n(*                   consists of all u such that u *m A = 0 (it consists of  *)\n(*                   the inverse of col_ebase A, with the top \\rank A rows   *)\n(*                   zeroed out). Also, kermx A is a partial right inverse   *)\n(*                   to col_ebase A, in the row space anihilated by A.       *)\n(*      cokermx A == the cokernel of A : a square matrix whose column space  *)\n(*                   consists of all v such that A *m v = 0 (it consists of  *)\n(*                   the inverse of row_ebase A, with the leftmost \\rank A   *)\n(*                   columns zeroed out).                                    *)\n(* We use a different scope %MS for matrix row-space set-like operations; to *)\n(* avoid confusion, this scope should not be opened globally. Note that the  *)\n(* the arguments of \\rank _ and the operations below have default scope %MS. *)\n(*    (A <= B)%MS <=> the row-space of A is included in the row-space of B.  *)\n(*                   We test for this by testing if cokermx B anihilates A.  *)\n(*  (A <= B <= C)%MS == (A <= B)%MS && (B && C)%MS                           *)\n(*    (A == B)%MS == (A <= B <= A)%MS (A and B have the same row-space).     *)\n(*   (A :=: B)%MS == A and B behave identically wrt. \\rank and <=. This      *)\n(*                   triple rewrite rule is the Prop version of (A == B)%MS. *)\n(*                   Note that :=: cannot be treated as a setoid-style       *)\n(*                   Equivalence because its arguments can have different    *)\n(*                   types: A and B need not have the same number of rows,   *)\n(*                   and often don't (e.g., in row_base A :=: A).            *)\n(*       <<A>>%MS == a square matrix with the same row-space as A; <<A>>%MS  *)\n(*                   is a canonical representation of the subspace generated *)\n(*                   by A, viewed as a list of row-vectors: if (A == B)%MS,  *)\n(*                   then <<A>>%MS = <<B>>%MS.                               *)\n(*     (A + B)%MS == a square matrix whose row-space is the sum of the       *)\n(*                   row-spaces of A and B; thus (A + B == col_mx A B)%MS.   *)\n(*  (\\sum_i <expr i>)%MS == the \"big\" version of (_ + _)%MS; as the latter   *)\n(*                   has a canonical abelian monoid structure, most generic  *)\n(*                   bigops lemmas apply (the other bigop indexing notations *)\n(*                   are also defined).                                      *)\n(*   (A :&: B)%MS == a square matrix whose row-space is the intersection of  *)\n(*                   the row-spaces of A and B.                              *)\n(*  (\\bigcap_i <expr i>)%MS == the \"big\" version of (_ :&: _)%MS, which also *)\n(*                   has a canonical abelian monoid structure.               *)\n(*         A^C%MS == a square matrix whose row-space is a complement to the  *)\n(*                   the row-space of A (it consists of row_ebase A with the *)\n(*                   top \\rank A rows zeroed out).                           *)\n(*   (A :\\: B)%MS == a square matrix whose row-space is a complement of the  *)\n(*                   the row-space of (A :&: B)%MS in the row-space of A.    *)\n(*                   We have (A :\\: B == A :&: (capmx_gen A B)^C)%MS, with   *)\n(*                   capmx_gen A B a recatangular matrix that generates      *)\n(*                   (A :&: B)%MS, i.e., (capmx_gen A B == A :&: B)%MS.      *)\n(*     mxdirect S == the sum expression S is a direct sum. This is a NON     *)\n(*                   EXTENSIONAL notation: the exact boolean expression is   *)\n(*                   inferred from the syntactic form of S (expanding        *)\n(*                   definitions, however); both (\\sum_(i | _) _)%MS and     *)\n(*                   (_ + _)%MS sums are recognized. This construct uses a   *)\n(*                   variant of the reflexive (\"quote\") canonical structure, *)\n(*                   mxsum_expr. The structure also recognizes sums of       *)\n(*                   matrix ranks, so that lemmas concerning the rank of     *)\n(*                   direct sums can be used bidirectionally.                *)\n(* Note that in this row-space theory, matrices represent vectors, subspaces *)\n(* and also linear transformations.                                          *)\n(*   We also extend any finType structure of R to 'M[R]_(m, n), and define   *)\n(*     {'GL_n[R]} == the finGroupType of units of 'M[R]_n.-1.+1              *)\n(*      'GL_n[R]  == the general linear group of all matrices in {'GL_n(R)}. *)\n(*      'GL_n(p)  == 'GL_n['F_p], the general linear group of a prime field. *)\n(*       GLval u  == the coercion of u : {'GL_n(R)} to a matrix.             *)\n(*   In addition to the lemmas relevant to these definitions, this file also *)\n(* proves several classic results, including :                               *)\n(* - The determinant is a multilinear alternate form.                        *)\n(* - The Laplace determinant expansion formulas: expand_det_[row|col].       *)\n(* - The Cramer rule : mul_mx_adj & mul_adj_mx                               *)\n(* - The Sylvester|Frobenius rank inequalities : mxrank_[mul_min|Frobenius]. *)\n(* - The order of 'GL_n[F].                                                  *)\n(*****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nImport GroupScope.\nImport GRing.Theory.\nOpen Local Scope ring_scope.\n\nReserved Notation \"''M_' n\"     (at level 8, n at level 2, format \"''M_' n\").\nReserved Notation \"''rV_' n\"    (at level 8, n at level 2, format \"''rV_' n\").\nReserved Notation \"''cV_' n\"    (at level 8, n at level 2, format \"''cV_' n\").\nReserved Notation \"''M_' ( n )\" (at level 8, only parsing).\nReserved Notation \"''M_' ( m , n )\" (at level 8, format \"''M_' ( m ,  n )\").\nReserved Notation \"''M[' R ]_ n\"    (at level 8, n at level 2, only parsing).\nReserved Notation \"''rV[' R ]_ n\"   (at level 8, n at level 2, only parsing).\nReserved Notation \"''cV[' R ]_ n\"   (at level 8, n at level 2, only parsing).\nReserved Notation \"''M[' R ]_ ( n )\"     (at level 8, only parsing).\nReserved Notation \"''M[' R ]_ ( m , n )\" (at level 8, only parsing).\n\nReserved Notation \"\\matrix_ i E\" \n  (at level 36, E at level 36, i at level 2,\n   format \"\\matrix_ i  E\").\nReserved Notation \"\\matrix_ ( i < n ) E\"\n  (at level 36, E at level 36, i, n at level 50,\n   format \"\\matrix_ ( i  <  n ) E\").\nReserved Notation \"\\matrix_ ( i , j ) E\"\n  (at level 36, E at level 36, i, j at level 50,\n   format \"\\matrix_ ( i ,  j )  E\").\nReserved Notation \"\\matrix_ ( i < m , j < n ) E\"\n  (at level 36, E at level 36, i, m, j, n at level 50,\n   format \"\\matrix_ ( i  <  m ,  j  <  n )  E\").\nReserved Notation \"\\matrix_ ( i , j < n ) E\"\n  (at level 36, E at level 36, i, j, n at level 50,\n   format \"\\matrix_ ( i ,  j  <  n )  E\").\nReserved Notation \"\\row_ j E\"\n  (at level 36, E at level 36, j at level 2,\n   format \"\\row_ j  E\").\nReserved Notation \"\\row_ ( j < n ) E\"\n  (at level 36, E at level 36, j, n at level 50,\n   format \"\\row_ ( j  <  n )  E\").\nReserved Notation \"\\col_ j E\"\n  (at level 36, E at level 36, j at level 2,\n   format \"\\col_ j  E\").\nReserved Notation \"\\col_ ( j < n ) E\"\n  (at level 36, E at level 36, j, n at level 50,\n   format \"\\col_ ( j  <  n )  E\").\n\nReserved Notation \"x %:M\"   (at level 8, format \"x %:M\").\nReserved Notation \"x *m: A\" (at level 40, format \"x  *m:  A\").\nReserved Notation \"A *m B\" (at level 40, left associativity, format \"A  *m  B\").\nReserved Notation \"A :+: B\" (at level 50, left associativity).\nReserved Notation \"A ^T\"    (at level 8, format \"A ^T\").\nReserved Notation \"A ^C\"    (at level 8, format \"A ^C\").\nReserved Notation \"\\tr A\"   (at level 10, A at level 8, format \"\\tr  A\").\nReserved Notation \"\\det A\"  (at level 10, A at level 8, format \"\\det  A\").\nReserved Notation \"\\adj A\"  (at level 10, A at level 8, format \"\\adj  A\").\nReserved Notation \"\\rank A\" (at level 10, A at level 8, format \"\\rank  A\").\n\nDelimit Scope matrix_set_scope with MS.\n\nNotation Local simp := (Monoid.Theory.simpm, oppr0).\n\n(*****************************************************************************)\n(****************************Type Definition**********************************)\n(*****************************************************************************)\n\nSection MatrixDef.\n\nVariable R : Type.\nVariables m n : nat.\n\n(* Basic linear algebra (matrices).                                       *)\n(* We use dependent types (ordinals) for the indices so that ranges are   *)\n(* mostly inferred automatically                                          *)\n\nInductive matrix : predArgType := Matrix of {ffun 'I_m * 'I_n -> R}.\n\nDefinition mx_val A := let: Matrix g := A in g.\n\nCanonical Structure matrix_subType :=\n  Eval hnf in [newType for mx_val by matrix_rect].\n\nDefinition matrix_of_fun F := locked Matrix [ffun ij => F ij.1 ij.2].\n\nDefinition fun_of_matrix A (i : 'I_m) (j : 'I_n) := mx_val A (i, j).\n\nCoercion fun_of_matrix  : matrix >-> Funclass.\n\nLemma mxE : forall F, matrix_of_fun F =2 F.\nProof. by unlock matrix_of_fun fun_of_matrix => F i j; rewrite /= ffunE. Qed.\n\nLemma matrixP : forall A B : matrix, A =2 B <-> A = B.\nProof.\nunlock fun_of_matrix => [] [A] [B]; split=> [/= eqAB | -> //].\ncongr Matrix; apply/ffunP=> [] [i j]; exact: eqAB.\nQed.\n\nEnd MatrixDef.\n\nBind Scope ring_scope with matrix.\n\nNotation \"''M[' R ]_ ( m , n )\" := (matrix R m n) (only parsing): type_scope.\nNotation \"''rV[' R ]_ n\"  := 'M[R]_(1, n) (only parsing) : type_scope.\nNotation \"''cV[' R ]_ n\"  := 'M[R]_(n, 1) (only parsing) : type_scope.\nNotation \"''M[' R ]_ n\"  := 'M[R]_(n, n) (only parsing) : type_scope.\nNotation \"''M[' R ]_ ( n )\" := 'M[R]_n (only parsing) : type_scope.\nNotation \"''M_' ( m , n )\" := 'M[_]_(m, n) : type_scope.\nNotation \"''rV_' n\"  := 'M_(1, n) : type_scope.\nNotation \"''cV_' n\"  := 'M_(n, 1) : type_scope.\nNotation \"''M_' n\"  := 'M_(n, n) : type_scope.\nNotation \"''M_' ( n )\" := 'M_n (only parsing) : type_scope.\n\nNotation \"\\matrix_ i E\" :=\n  (matrix_of_fun (fun i j => fun_of_matrix E (@GRing.zero (Zp_zmodType 0)) j))\n  : ring_scope.\n\nNotation \"\\matrix_ ( i < m , j < n ) E\" :=\n  (@matrix_of_fun _ m n (fun i j => E)) (only parsing) : ring_scope.\n\nNotation \"\\matrix_ ( i < m ) E\" :=\n  (\\matrix_(i < m, j < _) E 0 j) (only parsing) : ring_scope.\n\nNotation \"\\matrix_ ( i , j < n ) E\" :=\n  (\\matrix_(i < n, j < n) E) (only parsing) : ring_scope.\n\nNotation \"\\matrix_ ( i , j ) E\" := (\\matrix_(i < _, j < _) E) : ring_scope.\n\nNotation \"\\row_ j E\" := (@matrix_of_fun _ 1 _ (fun _ j => E)) : ring_scope.\nNotation \"\\row_ ( j < n ) E\" :=\n  (@matrix_of_fun _ 1 n (fun _ j => E)) (only parsing) : ring_scope.\n\nNotation \"\\col_ i E\" := (@matrix_of_fun _ _ 1 (fun i _ => E)) : ring_scope.\nNotation \"\\col_ ( i < n ) E\" :=\n  (@matrix_of_fun _ n 1 (fun i _ => E)) (only parsing) : ring_scope.\n\nDefinition matrix_eqMixin (R : eqType) m n :=\n  Eval hnf in [eqMixin of 'M[R]_(m, n) by <:].\nCanonical Structure matrix_eqType (R : eqType) m n:=\n  Eval hnf in EqType 'M[R]_(m, n) (matrix_eqMixin R m n).\nDefinition matrix_choiceMixin (R : choiceType) m n :=\n  [choiceMixin of 'M[R]_(m, n) by <:].\nCanonical Structure matrix_choiceType (R : choiceType) m n :=\n  Eval hnf in ChoiceType 'M[R]_(m, n) (matrix_choiceMixin R m n).\nDefinition matrix_countMixin (R : countType) m n :=\n  [countMixin of 'M[R]_(m, n) by <:].\nCanonical Structure matrix_countType (R : countType) m n :=\n  Eval hnf in CountType 'M[R]_(m, n) (matrix_countMixin R m n).\nCanonical Structure matrix_subCountType (R : countType) m n :=\n  Eval hnf in [subCountType of 'M[R]_(m, n)].\nDefinition matrix_finMixin (R : finType) m n :=\n  [finMixin of 'M[R]_(m, n) by <:].\nCanonical Structure matrix_finType (R : finType) m n :=\n  Eval hnf in FinType 'M[R]_(m, n) (matrix_finMixin R m n).\nCanonical Structure matrix_subFinType (R : finType) m n :=\n  Eval hnf in [subFinType of 'M[R]_(m, n)].\n\nLemma card_matrix : forall (F : finType) m n,\n  (#|{: 'M[F]_(m, n)}| = #|F| ^ (m * n))%N.\nProof. by move=> F m n; rewrite card_sub card_ffun card_prod !card_ord. Qed.\n\n(*****************************************************************************)\n(****** Matrix structural operations (transpose, permutation, blocks) ********)\n(*****************************************************************************)\n\nSection MatrixStructural.\n\nVariable R : Type.\n\n(* Constant matrix *)\nDefinition const_mx m n a : 'M[R]_(m, n) := \\matrix_(i, j) a.\nImplicit Arguments const_mx [[m] [n]].\n\nSection FixedDim.\n(* Definitions and properties for which we can work with fixed dimensions. *)\n\nVariables m n : nat.\nImplicit Type A : 'M[R]_(m, n).\n\n(* Reshape a matrix, to accomodate the block functions for instance. *)\nDefinition castmx m' n' (eq_mn : (m = m') * (n = n')) A : 'M_(m', n') :=\n  let: erefl in _ = m' := eq_mn.1 return 'M_(m', n') in\n  let: erefl in _ = n' := eq_mn.2 return 'M_(m, n') in A.\n\nDefinition conform_mx m' n' B A :=\n  match m =P m', n =P n' with\n  | ReflectT eq_m, ReflectT eq_n => castmx (eq_m, eq_n) A\n  | _, _ => B\n  end.\n\n(* Transpose a matrix *)\nDefinition trmx A := \\matrix_(i, j) A j i.\n\n(* Permute a matrix vertically (rows) or horizontally (columns) *)\nDefinition row_perm (s : 'S_m) A := \\matrix_(i, j) A (s i) j.\nDefinition col_perm (s : 'S_n) A := \\matrix_(i, j) A i (s j).\n\n(* Exchange two rows/columns of a matrix *)\nDefinition xrow i1 i2 := row_perm (tperm i1 i2).\nDefinition xcol j1 j2 := col_perm (tperm j1 j2).\n\n(* Row/Column sub matrices of a matrix *)\nDefinition row i0 A := \\row_j A i0 j.\nDefinition col j0 A := \\col_i A i j0.\n\n(* Removing a row/column from a matrix *)\nDefinition row' i0 A := \\matrix_(i, j) A (lift i0 i) j.\nDefinition col' j0 A := \\matrix_(i, j) A i (lift j0 j).\n\nLemma castmx_const : forall m' n' (eq_mn : (m = m') * (n = n')) a,\n  castmx eq_mn (const_mx a) = const_mx a.\nProof. by rewrite /castmx => m' n' []; case: m /; case: n /. Qed.\n\nLemma trmx_const : forall a, trmx (const_mx a) = const_mx a.\nProof. by move=> a; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma row_perm_const : forall s a, row_perm s (const_mx a) = const_mx a.\nProof. by move=> s a; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma col_perm_const : forall s a, col_perm s (const_mx a) = const_mx a.\nProof. by move=> s a; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma xrow_const : forall i1 i2 a, xrow i1 i2 (const_mx a) = const_mx a.\nProof. by move=> i1 i2; exact: row_perm_const. Qed.\n\nLemma xcol_const : forall j1 j2 a, xcol j1 j2 (const_mx a) = const_mx a.\nProof. by move=> j1 j2; exact: col_perm_const. Qed.\n\nLemma rowP : forall u v : 'rV[R]_n, u = v <-> u 0 =1 v 0.\nProof.\nby move=> u v; split=> [-> // | eq_uv]; apply/matrixP=> i; rewrite [i]ord1.\nQed.\n\nLemma rowK : forall u_ i0, row i0 (\\matrix_i u_ i) = u_ i0.\nProof. by move=> u_ i0; apply/rowP=> i'; rewrite !mxE. Qed.\n\nLemma row_matrixP : forall A B, (forall i, row i A = row i B) <-> A = B.\nProof.\nmove=> A B; split=> [eqAB | -> //]; apply/matrixP=> i j.\nby move/rowP: (eqAB i); move/(_ j); rewrite !mxE.\nQed.\n\nLemma colP : forall u v : 'cV[R]_m, u = v <-> u^~ 0 =1 v^~ 0.\nProof.\nby move=> u v; split=> [-> // | eq_uv]; apply/matrixP=> i j; rewrite [j]ord1.\nQed.\n\nLemma row_const : forall i0 a, row i0 (const_mx a) = const_mx a.\nProof. by move=> i0 a; apply/rowP=> j; rewrite !mxE. Qed.\n\nLemma col_const : forall j0 a, col j0 (const_mx a) = const_mx a.\nProof. by move=> j0 a; apply/colP=> i; rewrite !mxE. Qed.\n\nLemma row'_const : forall i0 a, row' i0 (const_mx a) = const_mx a.\nProof. by move=> i0 a; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma col'_const : forall j0 a, col' j0 (const_mx a) = const_mx a.\nProof. by move=> j0 a; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma col_perm1 : forall A, col_perm 1 A = A.\nProof. by move=> A; apply/matrixP=> i j; rewrite mxE perm1. Qed.\n\nLemma row_perm1 : forall A, row_perm 1 A = A.\nProof. by move=> A; apply/matrixP=> i j; rewrite mxE perm1. Qed.\n\nLemma col_permM : forall s t A, col_perm (s * t) A = col_perm s (col_perm t A).\nProof. by move=> s t A; apply/matrixP=> i j; rewrite !mxE permM. Qed.\n\nLemma row_permM : forall s t A, row_perm (s * t) A = row_perm s (row_perm t A).\nProof. by move=> s t A; apply/matrixP=> i j; rewrite !mxE permM. Qed.\n\nLemma col_row_permC : forall s t A,\n  col_perm s (row_perm t A) = row_perm t (col_perm s A).\nProof. by move=> s t A; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nEnd FixedDim.\n\nLocal Notation \"A ^T\" := (trmx A) : ring_scope.\n\nLemma castmx_id : forall m n erefl_mn (A : 'M_(m, n)), castmx erefl_mn A = A.\nProof. by move=> m n [e_m e_n]; rewrite [e_m]eq_axiomK [e_n]eq_axiomK. Qed.\n\nLemma castmx_comp : forall m1 n1 m2 n2 m3 n3,\n                    forall (eq_m1 : m1 = m2) (eq_n1 : n1 = n2),\n                    forall (eq_m2 : m2 = m3) (eq_n2 : n2 = n3) A,\n  castmx (eq_m2, eq_n2) (castmx (eq_m1, eq_n1) A)\n    = castmx (etrans eq_m1 eq_m2, etrans eq_n1 eq_n2) A.\nProof.\nby move=> m1 n1 m2 n2 m3 n3; case: m2 /; case: n2 /; case: m3 /; case: n3 /.\nQed.\n\nLemma castmxK : forall m1 n1 m2 n2 (eq_m : m1 = m2) (eq_n : n1 = n2),\n  cancel (castmx (eq_m, eq_n)) (castmx (esym eq_m, esym eq_n)).\nProof. by move=> m1 n1 m2 n2; case: m2 /; case: n2/. Qed.\n\nLemma castmxKV : forall m1 n1 m2 n2 (eq_m : m1 = m2) (eq_n : n1 = n2),\n  cancel (castmx (esym eq_m, esym eq_n)) (castmx (eq_m, eq_n)).\nProof. by move=> m1 n1 m2 n2; case: m2 /; case: n2/. Qed.\n\n(* This can be use to reverse an equation that involves a cast. *)\nLemma castmx_sym : forall m1 n1 m2 n2 (eq_m : m1 = m2) (eq_n : n1 = n2) A1 A2,\n  A1 = castmx (eq_m, eq_n) A2 -> A2 = castmx (esym eq_m, esym eq_n) A1.\nProof. by symmetry; apply: (canLR (castmxK _ _)). Qed.\n\nLemma castmxE : forall m1 n1 m2 n2 (eq_mn : (m1 = m2) * (n1 = n2)) A i j,\n  castmx eq_mn A i j =\n     A (cast_ord (esym eq_mn.1) i) (cast_ord (esym eq_mn.2) j).\nProof.\nby move=> m1 n1 m2 n2 []; case: m2 /; case: n2 / => A i j; rewrite !cast_ord_id.\nQed.\n\nLemma conform_mx_id : forall m n (B A : 'M_(m, n)), conform_mx B A = A.\nProof.\nby rewrite /conform_mx => m n B A; do 2!case: eqP => // *; rewrite castmx_id.\nQed.\n\nLemma nonconform_mx : forall m m' n n' (B : 'M_(m', n')) (A : 'M_(m, n)),\n  (m != m') || (n != n') -> conform_mx B A = B.\nProof. by rewrite /conform_mx => m m' n n' B A; do 2!case: eqP. Qed.\n\nLemma conform_castmx : forall m1 n1 m2 n2 m3 n3 (e : (m2 = m3) * (n2 = n3)),\n  forall (B : 'M_(m1, n1)) A, conform_mx B (castmx e A) = conform_mx B A.\nProof. by move=> m1 n1 m2 n2 m3 n3 []; case: m3 /; case: n3 /. Qed.\n\nLemma trmxK : forall m n, cancel (@trmx m n) (@trmx n m).\nProof. by move=> m n A; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma trmx_inj : forall m n, injective (@trmx m n).\nProof. move=> m n; exact: can_inj (@trmxK m n). Qed.\n\nLemma trmx_cast : forall m1 n1 m2 n2 (eq_mn : (m1 = m2) * (n1 = n2)) A,\n  (castmx eq_mn A)^T = castmx (eq_mn.2, eq_mn.1) A^T.\nProof.\nmove=> m1 n1 m2 n2 [eq_m eq_n] A; apply/matrixP=> i j.\nby rewrite !(mxE, castmxE).\nQed.\n\nLemma tr_row_perm : forall m n s (A : 'M_(m, n)),\n  (row_perm s A)^T = col_perm s A^T.\nProof. by move=> m n s A; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_col_perm : forall m n s (A : 'M_(m, n)),\n  (col_perm s A)^T = row_perm s A^T.\nProof. by move=> m n s A; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_xrow : forall m n i1 i2 (A : 'M_(m, n)),\n  (xrow i1 i2 A)^T = xcol i1 i2 A^T.\nProof. by move=> m n A i1 i2; exact: tr_row_perm. Qed.\n\nLemma tr_xcol : forall m n j1 j2 (A : 'M_(m, n)),\n  (xcol j1 j2 A)^T = xrow j1 j2 A^T.\nProof. by move=> m n A j1 j2; exact: tr_col_perm. Qed.\n\nLemma row_id : forall n i (V : 'rV_n), row i V = V.\nProof. by move=> n i V; apply/rowP=> j; rewrite mxE [i]ord1. Qed.\n\nLemma col_id : forall n j (V : 'cV_n), col j V = V.\nProof. by move=> n j V; apply/colP=> i; rewrite mxE [j]ord1. Qed.\n\nLemma row_eq : forall m1 m2 n i1 i2 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)),\n  row i1 A1 = row i2 A2 -> A1 i1 =1 A2 i2.\nProof.\nby move=> m1 m2 n i1 i2 A1 A2 eq12 j; move/rowP: eq12; move/(_ j); rewrite !mxE.\nQed.\n\nLemma col_eq : forall m n1 n2 j1 j2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)),\n  col j1 A1 = col j2 A2 -> A1^~ j1 =1 A2^~ j2.\nProof.\nby move=> m n1 n2 j1 j2 A1 A2 eq12 i; move/colP: eq12; move/(_ i); rewrite !mxE.\nQed.\n\nLemma row'_eq : forall m n i0 (A B : 'M_(m, n)),\n  row' i0 A = row' i0 B -> {in predC1 i0, A =2 B}.\nProof.\nmove=> m n i0 A B; move/matrixP=> eqAB' i.\nrewrite !inE eq_sym; case/unlift_some=> i' -> _  j.\nby have:= eqAB' i' j; rewrite !mxE.\nQed.\n\nLemma col'_eq : forall m n j0 (A B : 'M_(m, n)),\n  col' j0 A = col' j0 B -> forall i, {in predC1 j0, A i =1 B i}.\nProof.\nmove=> m n j0 A B; move/matrixP=> eqAB' i j.\nrewrite !inE eq_sym; case/unlift_some=> j' ->  _.\nby have:= eqAB' i j'; rewrite !mxE.\nQed.\n\nLemma tr_row : forall m n i0 (A : 'M_(m, n)),\n  (row i0 A)^T = col i0 A^T.\nProof. by move=> m n i0 A; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_row' : forall m n i0 (A : 'M_(m, n)),\n  (row' i0 A)^T = col' i0 A^T.\nProof. by move=> m n i0 A; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_col : forall m n j0 (A : 'M_(m, n)),\n  (col j0 A)^T = row j0 A^T.\nProof. by move=> m n j0 A; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_col' : forall m n j0 (A : 'M_(m, n)),\n  (col' j0 A)^T = row' j0 A^T.\nProof. by move=> m n j0 A; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLtac split_mxE := apply/matrixP=> i j; do ![rewrite mxE | case: split => ?].\n\nSection CutPaste.\n\nVariables m m1 m2 n n1 n2 : nat.\n\n(* Concatenating two matrices, in either direction. *)\n\nDefinition row_mx (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) : 'M[R]_(m, n1 + n2) :=\n  \\matrix_(i, j) match split j with inl j1 => A1 i j1 | inr j2 => A2 i j2 end.\n\nDefinition col_mx (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) : 'M[R]_(m1 + m2, n) :=\n  \\matrix_(i, j) match split i with inl i1 => A1 i1 j | inr i2 => A2 i2 j end.\n\n(* Left/Right | Up/Down submatrices of a rows | columns matrix.   *)\n(* The shape of the (dependent) width parameters of the type of A *)\n(* determines which submatrix is selected.                        *)\n\nDefinition lsubmx (A : 'M[R]_(m, n1 + n2)) := \\matrix_(i, j) A i (lshift n2 j).\n\nDefinition rsubmx (A : 'M[R]_(m, n1 + n2)) := \\matrix_(i, j) A i (rshift n1 j).\n\nDefinition usubmx (A : 'M[R]_(m1 + m2, n)) := \\matrix_(i, j) A (lshift m2 i) j.\n\nDefinition dsubmx (A : 'M[R]_(m1 + m2, n)) := \\matrix_(i, j) A (rshift m1 i) j.\n\nLemma row_mxEl : forall A1 A2 i j, row_mx A1 A2 i (lshift n2 j) = A1 i j.\nProof. by move=> A1 A2 i j; rewrite mxE (unsplitK (inl _ _)). Qed.\n\nLemma row_mxKl : forall A1 A2, lsubmx (row_mx A1 A2) = A1.\nProof. by move=> A1 A2; apply/matrixP=> i j; rewrite mxE row_mxEl. Qed.\n\nLemma row_mxEr : forall A1 A2 i j, row_mx A1 A2 i (rshift n1 j) = A2 i j.\nProof. by move=> A1 A2 i j; rewrite mxE (unsplitK (inr _ _)). Qed.\n\nLemma row_mxKr : forall A1 A2, rsubmx (row_mx A1 A2) = A2.\nProof. by move=> A1 A2; apply/matrixP=> i j; rewrite mxE row_mxEr. Qed.\n\nLemma hsubmxK : forall A, row_mx (lsubmx A) (rsubmx A) = A.\nProof.\nmove=> A; apply/matrixP=> i j; rewrite !mxE.\ncase: splitP => k Dk //=; rewrite !mxE //=; congr (A _ _); exact: val_inj.\nQed.\n\nLemma col_mxEu : forall A1 A2 i j, col_mx A1 A2 (lshift m2 i) j = A1 i j.\nProof. by move=> A1 A2 i j; rewrite mxE (unsplitK (inl _ _)). Qed.\n\nLemma col_mxKu : forall A1 A2, usubmx (col_mx A1 A2) = A1.\nProof. by move=> A1 A2; apply/matrixP=> i j; rewrite mxE col_mxEu. Qed.\n\nLemma col_mxEd : forall A1 A2 i j, col_mx A1 A2 (rshift m1 i) j = A2 i j.\nProof. by move=> A1 A2 i j; rewrite mxE (unsplitK (inr _ _)). Qed.\n\nLemma col_mxKd : forall A1 A2, dsubmx (col_mx A1 A2) = A2.\nProof. by move=> A1 A2; apply/matrixP=> i j; rewrite mxE col_mxEd. Qed.\n\nLemma eq_row_mx : forall A1 A2 B1 B2,\n  row_mx A1 A2 = row_mx B1 B2 -> A1 = B1 /\\ A2 = B2.\nProof.\nmove=> A1 A2 B1 B2 eqAB; move: (congr1 lsubmx eqAB) (congr1 rsubmx eqAB).\nby rewrite !(row_mxKl, row_mxKr).\nQed.\n\nLemma eq_col_mx : forall A1 A2 B1 B2,\n  col_mx A1 A2 = col_mx B1 B2 -> A1 = B1 /\\ A2 = B2.\nProof.\nmove=> A1 A2 B1 B2 eqAB; move: (congr1 usubmx eqAB) (congr1 dsubmx eqAB).\nby rewrite !(col_mxKu, col_mxKd).\nQed.\n\nLemma row_mx_const : forall a, row_mx (const_mx a) (const_mx a) = const_mx a.\nProof. by move=> a; split_mxE. Qed.\n\nLemma col_mx_const : forall a, col_mx (const_mx a) (const_mx a) = const_mx a.\nProof. by move=> a; split_mxE. Qed.\n\nEnd CutPaste.\n\nLemma trmx_lsub : forall m n1 n2 (A : 'M_(m, n1 + n2)),\n  (lsubmx A)^T = usubmx A^T.\nProof. by move=> m n1 n2 A; split_mxE. Qed.\n\nLemma trmx_rsub : forall m n1 n2 (A : 'M_(m, n1 + n2)),\n  (rsubmx A)^T = dsubmx A^T.\nProof. by move=> m n1 n2 A; split_mxE. Qed.\n\nLemma tr_row_mx : forall m n1 n2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)),\n  (row_mx A1 A2)^T = col_mx A1^T A2^T.\nProof. by move=> m n1 n2 A1 A2; split_mxE. Qed.\n\nLemma tr_col_mx : forall m1 m2 n (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)),\n  (col_mx A1 A2)^T = row_mx A1^T A2^T.\nProof. by move=> m1 m2 n A1 A2; split_mxE. Qed.\n\nLemma trmx_usub : forall m1 m2 n (A : 'M_(m1 + m2, n)),\n  (usubmx A)^T = lsubmx A^T.\nProof. by move=> m1 m2 n A; split_mxE. Qed.\n\nLemma trmx_dsub : forall m1 m2 n (A : 'M_(m1 + m2, n)),\n  (dsubmx A)^T = rsubmx A^T.\nProof. by move=> m1 m2 n A; split_mxE. Qed.\n\nLemma vsubmxK : forall m1 m2 n (A : 'M_(m1 + m2, n)),\n  col_mx (usubmx A) (dsubmx A) = A.\nProof.\nmove=> m1 m2 n A; apply: trmx_inj.\nby rewrite tr_col_mx trmx_usub trmx_dsub hsubmxK.\nQed.\n\nLemma cast_row_mx : forall m m' n1 n2 (eq_m : m = m') A1 A2,\n  castmx (eq_m, erefl _) (row_mx A1 A2)\n    = row_mx (castmx (eq_m, erefl n1) A1) (castmx (eq_m, erefl n2) A2).\nProof. by move=> m m' n1 n2; case: m' /. Qed.\n\nLemma cast_col_mx : forall m1 m2 n n' (eq_n : n = n') A1 A2,\n  castmx (erefl _, eq_n) (col_mx A1 A2)\n    = col_mx (castmx (erefl m1, eq_n) A1) (castmx (erefl m2, eq_n) A2).\nProof. by move=> m1 m2 n n'; case: n' /. Qed.\n\n(* This lemma has Prenex Implicits to help RL rewrititng with castmx_sym. *)\nLemma row_mxA : forall m n1 n2 n3,\n  forall (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) (A3 : 'M_(m, n3)),\n  let cast := (erefl m, esym (addnA n1 n2 n3)) in\n  row_mx A1 (row_mx A2 A3) = castmx cast (row_mx (row_mx A1 A2) A3).\nProof.\nmove=> m n1 n2 n3 A1 A2 A3; apply: (canRL (castmxKV _ _)); apply/matrixP=> i j.\nrewrite castmxE !mxE cast_ord_id; case: splitP => j1 /= def_j.\n  have: (j < n1 + n2) && (j < n1) by rewrite def_j lshift_subproof /=.\n  by move: def_j; do 2![case: splitP => // ? ->; rewrite ?mxE]; move/ord_inj->.\ncase: splitP def_j => j2 ->{j} def_j; rewrite !mxE.\n  have: ~~ (j2 < n1) by rewrite -leqNgt def_j leq_addr.\n  have: j1 < n2 by rewrite -(ltn_add2l n1) -def_j.\n  by move: def_j; do 2![case: splitP => // ? ->]; move/addnI; move/val_inj->.\nhave: ~~ (j1 < n2) by rewrite -leqNgt -(leq_add2l n1) -def_j leq_addr.\nby case: splitP def_j => // ? ->; rewrite addnA; move/addnI; move/val_inj->.\nQed.\nDefinition row_mxAx := row_mxA. (* bypass Prenex Implicits. *)\n\n(* This lemma has Prenex Implicits to help RL rewrititng with castmx_sym. *)\nLemma col_mxA : forall m1 m2 m3 n,\n  forall (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) (A3 : 'M_(m3, n)),\n  let cast := (esym (addnA m1 m2 m3), erefl n) in\n  col_mx A1 (col_mx A2 A3) = castmx cast (col_mx (col_mx A1 A2) A3).\nProof. by move=> *; apply: trmx_inj; rewrite trmx_cast !tr_col_mx -row_mxA. Qed.\nDefinition col_mxAx := col_mxA. (* bypass Prenex Implicits. *)\n\nLemma row_row_mx : forall m n1 n2 i0 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)),\n  row i0 (row_mx A1 A2) = row_mx (row i0 A1) (row i0 A2).\nProof.\nmove=> m n1 n2 i0 A1 A2; apply/matrixP=> i j; rewrite !mxE.\nby case: (split j) => j'; rewrite mxE.\nQed.\n\nLemma col_col_mx : forall m1 m2 n j0 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)),\n  col j0 (col_mx A1 A2) = col_mx (col j0 A1) (col j0 A2).\nProof.\nby move=> *; apply: trmx_inj; rewrite !(tr_col, tr_col_mx, row_row_mx).\nQed.\n\nLemma row'_row_mx : forall m n1 n2 i0 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)),\n  row' i0 (row_mx A1 A2) = row_mx (row' i0 A1) (row' i0 A2).\nProof.\nmove=> m n1 n2 i0 A1 A2; apply/matrixP=> i j; rewrite !mxE.\nby case: (split j) => j'; rewrite mxE.\nQed.\n\nLemma col'_col_mx : forall m1 m2 n j0 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)),\n  col' j0 (col_mx A1 A2) = col_mx (col' j0 A1) (col' j0 A2).\nProof.\nby move=> *; apply: trmx_inj; rewrite !(tr_col', tr_col_mx, row'_row_mx).\nQed.\n\nLemma colKl : forall m n1 n2 j1 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)),\n  col (lshift n2 j1) (row_mx A1 A2) = col j1 A1.\nProof. by move=> *; apply/matrixP=> i j; rewrite !(row_mxEl, mxE). Qed.\n\nLemma colKr : forall m n1 n2 j2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)),\n  col (rshift n1 j2) (row_mx A1 A2) = col j2 A2.\nProof. by move=> *; apply/matrixP=> i j; rewrite !(row_mxEr, mxE). Qed.\n\nLemma rowKu : forall m1 m2 n i1 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)),\n  row (lshift m2 i1) (col_mx A1 A2) = row i1 A1.\nProof. by move=> *; apply/matrixP=> i j; rewrite !(col_mxEu, mxE). Qed.\n\nLemma rowKd : forall m1 m2 n i2 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)),\n  row (rshift m1 i2) (col_mx A1 A2) = row i2 A2.\nProof. by move=> *; apply/matrixP=> i j; rewrite !(col_mxEd, mxE). Qed.\n\nLemma col'Kl : forall m n1 n2 j1 (A1 : 'M_(m, n1.+1)) (A2 : 'M_(m, n2)),\n  col' (lshift n2 j1) (row_mx A1 A2) = row_mx (col' j1 A1) A2.\nProof.\nmove=> m n1 n2 j1 A1 A2; apply/matrixP=> i /= j; symmetry; rewrite 2!mxE.\ncase: splitP => j' def_j'.\n  rewrite mxE -(row_mxEl _ A2); congr (row_mx _ _ _); apply: ord_inj.\n  by rewrite /= def_j'.\nrewrite -(row_mxEr A1); congr (row_mx _ _ _); apply: ord_inj => /=.\nby rewrite /bump def_j' -ltnS -addSn ltn_addr.\nQed.\n\nLemma row'Ku : forall m1 m2 n i1 (A1 : 'M_(m1.+1, n)) (A2 : 'M_(m2, n)),\n  row' (lshift m2 i1) (@col_mx m1.+1 m2 n A1 A2) = col_mx (row' i1 A1) A2.\nProof.\nmove=> m1 m2 n i1 A1 A2; apply: trmx_inj.\nby rewrite tr_col_mx !(@tr_row' _.+1) (@tr_col_mx _.+1) col'Kl.\nQed.\n\nLemma mx'_cast : forall m n, 'I_n -> (m + n.-1)%N = (m + n).-1.\nProof. by move=> m n [j]; move/ltn_predK <-; rewrite addnS. Qed.\n\nLemma col'Kr : forall m n1 n2 j2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)),\n  col' (rshift n1 j2) (@row_mx m n1 n2 A1 A2)\n    = castmx (erefl m, mx'_cast n1 j2) (row_mx A1 (col' j2 A2)).\nProof.\nmove=> m n1 n2 j2 A1 A2; apply/matrixP=> i j; symmetry.\nrewrite castmxE mxE cast_ord_id; case: splitP => j' /= def_j.\n  rewrite mxE -(row_mxEl _ A2); congr (row_mx _ _ _); apply: ord_inj.\n  by rewrite /= def_j /bump leqNgt ltn_addr.\nrewrite 2!mxE -(row_mxEr A1); congr (row_mx _ _ _ _); apply: ord_inj.\nby rewrite /= def_j /bump leq_add2l addnCA.\nQed.\n\nLemma row'Kd : forall m1 m2 n i2 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)),\n  row' (rshift m1 i2) (col_mx A1 A2)\n    = castmx (mx'_cast m1 i2, erefl n) (col_mx A1 (row' i2 A2)).\nProof.\nmove=> m n1 n2 j2 A1 A2; apply: trmx_inj.\nby rewrite trmx_cast !(tr_row', tr_col_mx) col'Kr.\nQed.\n\nSection Block.\n\nVariables m1 m2 n1 n2 : nat.\n\n(* Building a block matrix from 4 matrices :               *)\n(*  up left, up right, down left and down right components *)\n\nDefinition block_mx Aul Aur Adl Adr : 'M_(m1 + m2, n1 + n2) :=\n  col_mx (row_mx Aul Aur) (row_mx Adl Adr).\n\nLemma eq_block_mx : forall Aul Aur Adl Adr Bul Bur Bdl Bdr,\n block_mx Aul Aur Adl Adr = block_mx Bul Bur Bdl Bdr ->\n  [/\\ Aul = Bul, Aur = Bur, Adl = Bdl & Adr = Bdr].\nProof.\nmove=> Aul Aur Adl Adr Bul Bur Bdl Bdr.\nby case/eq_col_mx; do 2!case/eq_row_mx=> -> ->.\nQed.\n\nLemma block_mx_const : forall a,\n  block_mx (const_mx a) (const_mx a) (const_mx a) (const_mx a) = const_mx a.\nProof. by move=> a; split_mxE. Qed.\n\nSection CutBlock.\n\nVariable A : matrix R (m1 + m2) (n1 + n2).\n\nDefinition ulsubmx := lsubmx (usubmx A).\nDefinition ursubmx := rsubmx (usubmx A).\nDefinition dlsubmx := lsubmx (dsubmx A).\nDefinition drsubmx := rsubmx (dsubmx A).\n\nLemma submxK : block_mx ulsubmx ursubmx dlsubmx drsubmx = A.\nProof. by rewrite /block_mx !hsubmxK vsubmxK. Qed.\n\nEnd CutBlock.\n\nSection CatBlock.\n\nVariables (Aul : 'M[R]_(m1, n1)) (Aur : 'M[R]_(m1, n2)).\nVariables (Adl : 'M[R]_(m2, n1)) (Adr : 'M[R]_(m2, n2)).\n\nLet A := block_mx Aul Aur Adl Adr.\n\nLemma block_mxEul : forall i j, A (lshift m2 i) (lshift n2 j) = Aul i j.\nProof. by move=> i j; rewrite col_mxEu row_mxEl. Qed.\nLemma block_mxKul : ulsubmx A = Aul.\nProof. by rewrite /ulsubmx col_mxKu row_mxKl. Qed.\n\nLemma block_mxEur : forall i j, A (lshift m2 i) (rshift n1 j) = Aur i j.\nProof. by move=> i j; rewrite col_mxEu row_mxEr. Qed.\nLemma block_mxKur : ursubmx A = Aur.\nProof. by rewrite /ursubmx col_mxKu row_mxKr. Qed.\n\nLemma block_mxEdl : forall i j, A (rshift m1 i) (lshift n2 j) = Adl i j.\nProof. by move=> i j; rewrite col_mxEd row_mxEl. Qed.\nLemma block_mxKdl : dlsubmx A = Adl.\nProof. by rewrite /dlsubmx col_mxKd row_mxKl. Qed.\n\nLemma block_mxEdr : forall i j, A (rshift m1 i) (rshift n1 j) = Adr i j.\nProof. by move=> i j; rewrite col_mxEd row_mxEr. Qed.\nLemma block_mxKdr : drsubmx A = Adr.\nProof. by rewrite /drsubmx col_mxKd row_mxKr. Qed.\n\nLemma block_mxEv : A = col_mx (row_mx Aul Aur) (row_mx Adl Adr).\nProof. by []. Qed.\n\nEnd CatBlock.\n\nEnd Block.\n\nSection TrCutBlock.\n\nVariables m1 m2 n1 n2 : nat.\nVariable A : 'M[R]_(m1 + m2, n1 + n2).\n\nLemma trmx_ulsub : (ulsubmx A)^T =  ulsubmx A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma trmx_ursub : (ursubmx A)^T =  dlsubmx A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma trmx_dlsub : (dlsubmx A)^T =  ursubmx A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma trmx_drsub : (drsubmx A)^T = drsubmx A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nEnd TrCutBlock.\n\nSection TrBlock.\nVariables m1 m2 n1 n2 : nat.\nVariables (Aul : 'M[R]_(m1, n1)) (Aur : 'M[R]_(m1, n2)).\nVariables (Adl : 'M[R]_(m2, n1)) (Adr : 'M[R]_(m2, n2)).\n\nLemma tr_block_mx :\n (block_mx Aul Aur Adl Adr)^T = block_mx Aul^T Adl^T Aur^T Adr^T.\nProof.\nrewrite -[_^T]submxK -trmx_ulsub -trmx_ursub -trmx_dlsub -trmx_drsub.\nby rewrite block_mxKul block_mxKur block_mxKdl block_mxKdr.\nQed.\n\nLemma block_mxEh :\n  block_mx Aul Aur Adl Adr = row_mx (col_mx Aul Adl) (col_mx Aur Adr).\nProof. by apply: trmx_inj; rewrite tr_block_mx tr_row_mx 2!tr_col_mx. Qed.\nEnd TrBlock.\n\n(* This lemma has Prenex Implicits to help RL rewrititng with castmx_sym. *)\nLemma block_mxA : forall m1 m2 m3 n1 n2 n3,\n  forall (A11 : 'M_(m1, n1)) (A12 : 'M_(m1, n2)) (A13 : 'M_(m1, n3)),\n  forall (A21 : 'M_(m2, n1)) (A22 : 'M_(m2, n2)) (A23 : 'M_(m2, n3)),\n  forall (A31 : 'M_(m3, n1)) (A32 : 'M_(m3, n2)) (A33 : 'M_(m3, n3)),\n  let cast := (esym (addnA m1 m2 m3), esym (addnA n1 n2 n3)) in\n  let row1 := row_mx A12 A13 in let col1 := col_mx A21 A31 in\n  let row3 := row_mx A31 A32 in let col3 := col_mx A13 A23 in\n  block_mx A11 row1 col1 (block_mx A22 A23 A32 A33)\n    = castmx cast (block_mx (block_mx A11 A12 A21 A22) col3 row3 A33).\nProof.\nmove=> m1 m2 m3 n1 n2 n3 A11 A12 A13 A21 A22 A23 A31 A32 A33 /=.\nrewrite block_mxEh !col_mxA -cast_row_mx -block_mxEv -block_mxEh.\nrewrite block_mxEv block_mxEh !row_mxA -cast_col_mx -block_mxEh -block_mxEv.\nby rewrite castmx_comp etrans_id.\nQed.\nDefinition block_mxAx := block_mxA. (* Bypass Prenex Implicits *)\n\nEnd MatrixStructural.\n\nImplicit Arguments const_mx [R m n].\nImplicit Arguments row_mxA [R m n1 n2 n3 A1 A2 A3].\nImplicit Arguments col_mxA [R m1 m2 m3 n A1 A2 A3].\nImplicit Arguments block_mxA\n  [R m1 m2 m3 n1 n2 n3 A11 A12 A13 A21 A22 A23 A31 A32 A33].\nPrenex Implicits const_mx castmx trmx lsubmx rsubmx usubmx dsubmx row_mx col_mx.\nPrenex Implicits block_mx ulsubmx ursubmx dlsubmx drsubmx.\nPrenex Implicits row_mxA col_mxA block_mxA.\nNotation \"A ^T\" := (trmx A) : ring_scope.\n\n(* Matrix parametricity. *)\nSection MapMatrix.\n\nVariables (aT rT : Type) (f : aT -> rT).\n\nDefinition map_mx m n (A : 'M_(m, n)) := \\matrix_(i, j) f (A i j).\n\nNotation \"A ^f\" := (map_mx A) : ring_scope.\n\nSection OneMatrix.\n\nVariables (m n : nat) (A : 'M[aT]_(m, n)).\n\nLemma map_trmx : A^f^T = A^T^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_const_mx : forall a, (const_mx a)^f = const_mx (f a) :> 'M_(m, n).\nProof. by move=> a; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_row : forall i, (row i A)^f = row i A^f.\nProof. by move=> i; apply/rowP=> j; rewrite !mxE. Qed.\n\nLemma map_col : forall j, (col j A)^f = col j A^f.\nProof. by move=> j; apply/colP=> i; rewrite !mxE. Qed.\n\nLemma map_row' : forall i0, (row' i0 A)^f = row' i0 A^f.\nProof. by move=> i0; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_col' : forall j0, (col' j0 A)^f = col' j0 A^f.\nProof. by move=> j0; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_row_perm : forall s, (row_perm s A)^f = row_perm s A^f.\nProof. by move=> s; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_col_perm : forall s, (col_perm s A)^f = col_perm s A^f.\nProof. by move=> s; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_xrow : forall i1 i2, (xrow i1 i2 A)^f = xrow i1 i2 A^f.\nProof. by move=> i1 i2; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_xcol : forall j1 j2, (xcol j1 j2 A)^f = xcol j1 j2 A^f.\nProof. by move=> j1 j2; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_castmx : forall m' n' c, (castmx c A)^f = castmx c A^f :> 'M_(m', n').\nProof. by move=> m' n' c; apply/matrixP=> i j; rewrite !(castmxE, mxE). Qed.\n\nLemma map_conform_mx : forall m' n' (B : 'M_(m', n')),\n  (conform_mx B A)^f = conform_mx B^f A^f.\nProof.\nmove=> m' n'; case: (eqVneq (m, n) (m', n')) => [[<- <-] B|].\n  by rewrite !conform_mx_id.\nby rewrite negb_and => neq_mn B; rewrite !nonconform_mx.\nQed.\n\nEnd OneMatrix.\n\nSection Block.\n\nVariables m1 m2 n1 n2 : nat.\nVariables (Aul : 'M[aT]_(m1, n1)) (Aur : 'M[aT]_(m1, n2)).\nVariables (Adl : 'M[aT]_(m2, n1)) (Adr : 'M[aT]_(m2, n2)).\nVariables (Bh : 'M[aT]_(m1, n1 + n2)) (Bv : 'M[aT]_(m1 + m2, n1)).\nVariable B : 'M[aT]_(m1 + m2, n1 + n2).\n\nLemma map_row_mx : (row_mx Aul Aur)^f = row_mx Aul^f Aur^f.\nProof. by apply/matrixP=> i j; do 2![rewrite !mxE //; case: split => ?]. Qed.\n\nLemma map_col_mx : (col_mx Aul Adl)^f = col_mx Aul^f Adl^f.\nProof. by apply/matrixP=> i j; do 2![rewrite !mxE //; case: split => ?]. Qed.\n\nLemma map_block_mx :\n  (block_mx Aul Aur Adl Adr)^f = block_mx Aul^f Aur^f Adl^f Adr^f.\nProof. by apply/matrixP=> i j; do 3![rewrite !mxE //; case: split => ?]. Qed.\n\nLemma map_lsubmx : (lsubmx Bh)^f = lsubmx Bh^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_rsubmx : (rsubmx Bh)^f = rsubmx Bh^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_usubmx : (usubmx Bv)^f = usubmx Bv^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_dsubmx : (dsubmx Bv)^f = dsubmx Bv^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_ulsubmx : (ulsubmx B)^f = ulsubmx B^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_ursubmx : (ursubmx B)^f = ursubmx B^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_dlsubmx : (dlsubmx B)^f = dlsubmx B^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_drsubmx : (drsubmx B)^f = drsubmx B^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nEnd Block.\n\nEnd MapMatrix.\n\n(*****************************************************************************)\n(********************* Matrix Zmodule (additive) structure *******************)\n(*****************************************************************************)\n\nSection MatrixZmodule.\n\nVariable M : zmodType.\n\nSection FixedDim.\n\nVariables m n : nat.\nImplicit Types A B : 'M[M]_(m, n).\n\nDefinition oppmx A := \\matrix_(i, j) (- A i j).\nDefinition addmx A B := \\matrix_(i, j) (A i j + B i j).\n(* In principle, diag_mx and scalar_mx could be defined here, but since they *)\n(* only make sense with the graded ring operations, we defer them to the     *)\n(* next section.                                                             *)\n\nLemma addmxA : associative addmx.\nProof. by move=> A B C; apply/matrixP=> i j; rewrite !mxE addrA. Qed.\n\nLemma addmxC : commutative addmx.\nProof. by move=> A B; apply/matrixP=> i j; rewrite !mxE addrC. Qed.\n\nLemma add0mx : left_id (const_mx 0) addmx.\nProof. by move=> A; apply/matrixP=> i j; rewrite !mxE add0r. Qed.\n\nLemma addNmx : left_inverse (const_mx 0) oppmx addmx.\nProof. by move=> A; apply/matrixP=> i j; rewrite !mxE addNr. Qed.\n\nDefinition matrix_zmodMixin := ZmodMixin addmxA addmxC add0mx addNmx.\nCanonical Structure matrix_zmodType :=\n  Eval hnf in ZmodType 'M[M]_(m, n) matrix_zmodMixin.\n\nLemma const_mx0 : const_mx 0 = 0. Proof. by []. Qed.\nLemma const_mxN : forall a, const_mx (- a) = - const_mx a.\nProof. by move=> a; apply/matrixP=> i j; rewrite !mxE. Qed.\nLemma const_mx_add : forall a b, const_mx (a + b) = const_mx a + const_mx b.\nProof. by move=> a b; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma mulmxnE : forall A d i j, (A *+ d) i j = A i j *+ d.\nProof. by move=> A d i j; elim: d => [|d IHd]; rewrite ?mulrS mxE ?IHd. Qed.\n\nLemma summxE : forall I r (P : pred I) (E : I -> 'M_(m, n)) i j,\n  (\\sum_(k <- r | P k) E k) i j = \\sum_(k <- r | P k) E k i j.\nProof.\nmove=> I r P E i j.\nby apply: (big_morph (fun A => A i j)) => [A B|]; rewrite mxE.\nQed.\n\nEnd FixedDim.\n\nLemma flatmx0 : forall n, all_equal_to (0 : 'M_(0, n)).\nProof. by move=> n A; apply/matrixP=> [] []. Qed.\n\nLemma thinmx0 : forall n, all_equal_to (0 : 'M_(n, 0)).\nProof. by move=> n A; apply/matrixP=> i []. Qed.\n\nLemma trmx0 : forall m n, (0 : 'M_(m, n))^T = 0.\nProof. by move=> m n; exact: trmx_const. Qed.\n\nLemma trmx_add : forall m n (A B : 'M_(m, n)), (A + B)^T = A^T + B^T .\nProof. by move=> m n A B; apply/matrixP=> i j; rewrite !mxE. Qed.\n\n(* Interaction of permx/xrow/xcol with the Zmodule operations should be *)\n(* handled via the decomposition to product with a permutation matrix.  *)\n\nLemma row0 : forall m n i0, row i0 (0 : 'M_(m, n)) = 0.\nProof. by move=> m n i0; exact: row_const. Qed.\n\nLemma col0 : forall m n j0, col j0 (0 : 'M_(m, n)) = 0.\nProof. by move=> m n j0; exact: col_const. Qed.\n\nLemma row'0 : forall m n i0, row' i0 (0 : 'M_(m, n)) = 0.\nProof. by move=> m n i0; exact: row'_const. Qed.\n\nLemma col'0 : forall m n j0, col' j0 (0 : 'M_(m, n)) = 0.\nProof. by move=> m n j0; exact: col'_const. Qed.\n\nLemma row_mx0 : forall m n1 n2, row_mx 0 0 = 0 :> 'M_(m, n1 + n2).\nProof. by move=> m n1 n2; exact: row_mx_const. Qed.\n\nLemma col_mx0 : forall m1 m2 n, col_mx 0 0 = 0 :> 'M_(m1 + m2, n).\nProof. by move=> m1 m2 n; exact: col_mx_const. Qed.\n\nLemma block_mx0 : forall m1 m2 n1 n2,\n  block_mx 0 0 0 0 = 0 :> 'M_(m1 + m2, n1 + n2).\nProof. by move=> m1 m2 n1 n2; exact: block_mx_const. Qed.\n\nLtac split_mxE := apply/matrixP=> i j; do ![rewrite mxE | case: split => ?].\n\nLemma opp_row_mx : forall m n1 n2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)),\n  - row_mx A1 A2 = row_mx (- A1) (- A2).\nProof. by move=> *; split_mxE. Qed.\n\nLemma opp_col_mx : forall m1 m2 n (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)),\n  - col_mx A1 A2 = col_mx (- A1) (- A2).\nProof. by move=> *; split_mxE. Qed.\n\nLemma opp_block_mx : forall m1 m2 n1 n2,\n  forall (Aul : 'M_(m1, n1)) Aur Adl (Adr : 'M_(m2, n2)),\n  - block_mx Aul Aur Adl Adr = block_mx (- Aul) (- Aur) (- Adl) (- Adr).\nProof. by move=> *; rewrite opp_col_mx !opp_row_mx. Qed.\n\nLemma add_row_mx : forall m n1 n2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) B1 B2,\n  row_mx A1 A2 + row_mx B1 B2 = row_mx (A1 + B1) (A2 + B2).\nProof. by move=> *; split_mxE. Qed.\n\nLemma add_col_mx : forall m1 m2 n (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) B1 B2,\n  col_mx A1 A2 + col_mx B1 B2 = col_mx (A1 + B1) (A2 + B2).\nProof. by move=> *; split_mxE. Qed.\n\nLemma add_block_mx : forall m1 m2 n1 n2,\n  forall (Aul : 'M_(m1, n1)) Aur Adl (Adr : 'M_(m2, n2)) Bul Bur Bdl Bdr,\n  let A := block_mx Aul Aur Adl Adr  in let B := block_mx Bul Bur Bdl Bdr in\n  A + B = block_mx (Aul + Bul) (Aur + Bur) (Adl + Bdl) (Adr + Bdr).\nProof. by move=> *; rewrite add_col_mx !add_row_mx. Qed.\n\nEnd MatrixZmodule.\n\nSection FinZmodMatrix.\nVariables (M : finZmodType) (m n : nat).\nLocal Notation MM := 'M[M]_(m, n).\nCanonical Structure matrix_finZmodType := Eval hnf in [finZmodType of MM].\nCanonical Structure matrix_baseFinGroupType :=\n  Eval hnf in [baseFinGroupType of MM for +%R].\nCanonical Structure matrix_finGroupType :=\n  Eval hnf in [finGroupType of MM for +%R].\nEnd FinZmodMatrix.\n\n(*****************************************************************************)\n(*********** Matrix ring module, graded ring, and ring structures ************)\n(*****************************************************************************)\n\nSection MatrixAlgebra.\n\nVariable R : ringType.\n\nSection RingModule.\n\n(* The ring module/vector space structure *)\n\nVariables m n : nat.\nImplicit Types A B : 'M[R]_(m, n).\n\nDefinition scalemx x A := \\matrix_(i < m, j < n) (x * A i j).\n\n(* Basis *)\nDefinition delta_mx i0 j0 : 'M[R]_(m, n) :=\n  \\matrix_(i < m, j < n) ((i == i0) && (j == j0))%:R.\n\nLocal Notation \"x *m: A\" := (scalemx x A) : ring_scope.\n\nLemma scalemx_const : forall a b, a *m: const_mx b = const_mx (a * b).\nProof. by move=> a b; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma scale0mx : forall A, 0 *m: A = 0.\nProof. by move=> A; apply/matrixP=> i j; rewrite !mxE mul0r. Qed.\n\nLemma scalemx0 : forall x, x *m: 0 = 0.\nProof. by move=> x; apply/matrixP=> i j; rewrite !mxE mulr0. Qed.\n\nLemma scale1mx : forall A, 1 *m: A = A.\nProof. by move=> A; apply/matrixP=> i j; rewrite !mxE mul1r. Qed.\n\nLemma scaleNmx : forall x A, (- x) *m: A = - (x *m: A).\nProof. by move=> x A; apply/matrixP=> i j; rewrite !mxE mulNr. Qed.\n\nLemma scaleN1mx : forall A, (- 1) *m: A = - A.\nProof. by move=> A; rewrite scaleNmx scale1mx. Qed.\n\nLemma scalemxN : forall x A, x *m: (- A) = - (x *m: A).\nProof. by move=> x A; apply/matrixP=> i j; rewrite !mxE mulrN. Qed.\n\nLemma scalemx_addl : forall x y A, (x + y) *m: A = x *m: A + y *m: A.\nProof. by move=> x y A; apply/matrixP=> i j; rewrite !mxE mulr_addl. Qed.\n\nLemma scalemx_addr : forall x A B, x *m: (A + B) = x *m: A + x *m: B.\nProof. by move=> x A B; apply/matrixP=> i j; rewrite !mxE mulr_addr. Qed.\n\nLemma scalemx_subl : forall x y A, (x - y) *m: A = x *m: A - y *m: A.\nProof. by move=> x y A; rewrite scalemx_addl scaleNmx. Qed.\n\nLemma scalemx_subr : forall x A B, x *m: (A - B) = x *m: A - x *m: B.\nProof. by move=> x A B; rewrite scalemx_addr scalemxN. Qed.\n\nLemma scalemxA : forall x y A, x *m: (y *m: A) = (x * y) *m: A.\nProof. by move=> x y A; apply/matrixP=> i j; rewrite !mxE mulrA. Qed.\n\nLemma scalemx_nat : forall d A, d%:R *m: A = A *+ d.\nProof.\nmove=> d A; elim: d => [|d IHd]; rewrite ?scale0mx //.\nby rewrite !mulrS scalemx_addl scale1mx IHd.\nQed.\n\nLemma scalemx_suml : forall A I r (P : pred I) a_,\n   (\\sum_(i <- r | P i) a_ i) *m: A = \\sum_(i <- r | P i) a_ i *m: A.\nProof.\nmove=> A; apply: (big_morph (scalemx^~ A)) => [a b|]; last exact: scale0mx.\nby rewrite scalemx_addl.\nQed.\n\nLemma scalemx_sumr : forall a I r (P : pred I) eA_,\n   a *m: (\\sum_(i <- r | P i) eA_ i) = \\sum_(i <- r | P i) a *m: eA_ i.\nProof.\nmove=> a; apply: (big_morph (scalemx a)) => [A B|]; last exact: scalemx0.\nby rewrite scalemx_addr.\nQed.\n\nLemma matrix_sum_delta : forall A,\n  A = \\sum_(i < m) \\sum_(j < n) A i j *m: delta_mx i j.\nProof.\nmove=> A; apply/matrixP=> i j.\nrewrite summxE (bigD1 i) // summxE (bigD1 j) //= !mxE !eqxx mulr1.\nrewrite !big1 ?addr0 //= => [i' | j']; rewrite eq_sym; move/negbTE=> diff.\n  by rewrite summxE big1 // => j' _; rewrite !mxE diff mulr0.\nby rewrite !mxE eqxx diff mulr0.\nQed.\n\nEnd RingModule.\n\nNotation \"x *m: A\" := (scalemx x A) : ring_scope.\n\nLemma trmx_delta : forall m n i j,\n  (delta_mx i j)^T = delta_mx j i :> 'M[R]_(n, m).\nProof. by move=> m n i j; apply/matrixP=> i' j'; rewrite !mxE andbC. Qed.\n\nLemma trmx_scale : forall m n a (A  : 'M_(m, n)), (a *m: A)^T = a *m: A^T.\nProof. by move=> m n a A; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma row_sum_delta : forall n (u : 'rV_n),\n  u = \\sum_(j < n) u 0 j *m: delta_mx 0 j.\nProof. by move=> n u; rewrite {1}[u]matrix_sum_delta big_ord1. Qed.\n\nLtac split_mxE := apply/matrixP=> i j; do ![rewrite mxE | case: split => ?].\n\nLemma scale_row_mx : forall m n1 n2 a (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)),\n  a *m: row_mx A1 A2 = row_mx (a *m: A1) (a *m: A2).\nProof. by move=> *; split_mxE. Qed.\n\nLemma scale_col_mx : forall m1 m2 n a (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)),\n  a *m: col_mx A1 A2 = col_mx (a *m: A1) (a *m: A2).\nProof. by move=> *; split_mxE. Qed.\n\nLemma scale_block_mx : forall m1 m2 n1 n2 a,\n                       forall (Aul : 'M_(m1, n1)) (Aur : 'M_(m1, n2)),\n                       forall (Adl : 'M_(m2, n1)) (Adr : 'M_(m2, n2)),\n  a *m: block_mx Aul Aur Adl Adr\n     = block_mx (a *m: Aul) (a *m: Aur) (a *m: Adl) (a *m: Adr).\nProof. by move=> *; rewrite scale_col_mx !scale_row_mx. Qed.\n\n(* Diagonal matrices *)\n\nLemma mulrb : forall (x : R) (b : bool), x *+ b = (if b then x else 0).\nProof. by move=> x []. Qed.\n\nDefinition diag_mx n (d : 'rV[R]_n) := \\matrix_(i, j) (d 0 i *+ (i == j)).\n\nLemma tr_diag_mx : forall n (d : 'rV_n), (diag_mx d)^T = diag_mx d.\nProof.\nby move=> n d; apply/matrixP=> i j; rewrite !mxE eq_sym; case: eqP => // ->.\nQed.\n\nLemma diag_mx0 : forall n, diag_mx 0 = 0 :> 'M_n.\nProof. by move=> n; apply/matrixP=> i j; rewrite !mxE mul0rn. Qed.\n\nLemma diag_mx_opp : forall n (d : 'rV_n), diag_mx (- d) = - diag_mx d.\nProof. by move=> n d; apply/matrixP=> i j; rewrite !mxE oppr_muln. Qed.\n\nLemma diag_mx_add : forall n (d e : 'rV_n),\n  diag_mx (d + e) = diag_mx d + diag_mx e.\nProof. by move=> n d e; apply/matrixP=> i j; rewrite !mxE mulrn_addl. Qed.\n\nLemma scale_diag_mx : forall n a (d : 'rV_n),\n  a *m: diag_mx d = diag_mx (a *m: d).\nProof. by move=> n a d; apply/matrixP=> i j; rewrite !mxE mulrnAr. Qed.\n\nLemma diag_mx_sum_delta : forall n (d : 'rV_n),\n  diag_mx d = \\sum_i d 0 i *m: delta_mx i i.\nProof.\nmove=> n d; apply/matrixP=> i j; rewrite summxE (bigD1 i) //= !mxE eqxx /=.\nrewrite eq_sym mulr_natr big1 ?addr0 // => i' ne_i'i.\nby rewrite !mxE eq_sym (negbTE ne_i'i) mulr0.\nQed.\n\n(* Scalar matrix : a diagonal matrix with a constant on the diagonal *)\nDefinition scalar_mx n x : 'M[R]_n := \\matrix_(i , j) (x *+ (i == j)).\nNotation \"x %:M\" := (scalar_mx _ x) : ring_scope.\n\nLemma diag_const_mx : forall n a, diag_mx (const_mx a) = a%:M :> 'M_n.\nProof. by move=> n a; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma mx11_scalar : forall A : 'M_1, A = (A 0 0)%:M.\nProof. by move=> A; apply/rowP=> j; rewrite [j]ord1 mxE. Qed.\n\nLemma tr_scalar_mx : forall n a, (a%:M)^T = a%:M :> 'M_n.\nProof. by move=> n a; apply/matrixP=> i j; rewrite !mxE eq_sym. Qed.\n\nLemma trmx1 : forall n, (1%:M)^T = 1%:M :> 'M_n.\nProof. move=> n; exact: tr_scalar_mx. Qed.\n\nLemma scalar_mx0 : forall n, 0%:M = 0 :> 'M_n.\nProof. by move=> n; apply/matrixP=> i j; rewrite !mxE mul0rn. Qed.\n\nLemma scalar_mx_opp : forall n a, (- a)%:M = - a%:M :> 'M_n.\nProof. by move=> n a; apply/matrixP=> i j; rewrite !mxE oppr_muln. Qed.\n\nLemma scalar_mx_add : forall n a b, (a + b)%:M = a%:M + b%:M :> 'M_n.\nProof. by move=> n a b; apply/matrixP=> i j; rewrite !mxE mulrn_addl. Qed.\n\nLemma scale_scalar_mx : forall n a1 a2, a1 *m: a2%:M = (a1 * a2)%:M :> 'M_n.\nProof. by move=> n a1 a2; apply/matrixP=> i j; rewrite !mxE mulrnAr. Qed.\n\nLemma scalemx1 : forall n a, a *m: 1%:M = a%:M :> 'M_n.\nProof. by move=> n a; rewrite scale_scalar_mx mulr1. Qed.\n\nLemma scalar_mx_block : forall n1 n2 a,\n  a%:M = block_mx a%:M 0 0 a%:M :> 'M_(n1 + n2).\nProof.\nmove=> n1 n2 a; apply/matrixP=> i j; rewrite !mxE -val_eqE /=.\nby do 2![case: splitP => ? ->; rewrite !mxE];\n   rewrite ?eqn_addl // -?(eq_sym (n1 + _)%N) eqn_leq leqNgt lshift_subproof.\nQed.\n\nLemma scalar_mx_sum_delta : forall n a,\n  a%:M = \\sum_i a *m: delta_mx i i :> 'M_n.\nProof.\nmove=> n a; rewrite -diag_const_mx diag_mx_sum_delta.\nby apply: eq_bigr => i _; rewrite mxE.\nQed.\n\nLemma mx1_sum_delta : forall n, 1%:M = \\sum_i delta_mx i i :> 'M_n.\nProof.\nby move=> n; rewrite [1%:M]scalar_mx_sum_delta -scalemx_sumr scale1mx.\nQed.\n\nLemma row1 : forall n (i : 'I_n), row i 1%:M = delta_mx 0 i.\nProof. by move=> n i; apply/rowP=> j; rewrite !mxE eq_sym. Qed.\n\n(* Matrix multiplication with the bigops *)\nDefinition mulmx {m n p} (A : 'M_(m, n)) (B : 'M_(n, p)) : 'M[R]_(m, p) :=\n  \\matrix_(i, k) \\sum_j (A i j * B j k).\n\nLocal Notation \"A *m B\" := (mulmx A B) : ring_scope.\n\nLemma mulmxA : forall m n p q (A : 'M_(m, n)) (B : 'M_(n, p)) (C : 'M_(p, q)),\n  A *m (B *m C) = A *m B *m C.\nProof.\nmove=> m n p q A B C; apply/matrixP=> i l; rewrite !mxE.\ntransitivity (\\sum_j (\\sum_k (A i j * (B j k * C k l)))).\nby apply: eq_bigr => j _; rewrite mxE big_distrr.\nrewrite exchange_big; apply: eq_bigr => j _; rewrite mxE big_distrl /=.\nby apply: eq_bigr => k _; rewrite mulrA.\nQed.\n\nLemma mul0mx : forall m n p (A : 'M_(n, p)), 0 *m A = 0 :> 'M_(m, p).\nProof.\nmove=> m n p A; apply/matrixP=> i k.\nby rewrite !mxE big1 //= => j _; rewrite mxE mul0r.\nQed.\n\nLemma mulmx0 : forall m n p (A : 'M_(m, n)), A *m 0 = 0 :> 'M_(m, p).\nProof.\nmove=> m n p A; apply/matrixP=> i k; rewrite !mxE big1 // => j _.\nby rewrite mxE mulr0.\nQed.\n\nLemma mulmxN : forall m n p (A : 'M_(m, n)) (B : 'M_(n, p)),\n  A *m (- B) = - (A *m B).\nProof.\nmove=> m n p A B; apply/matrixP=> i k; rewrite !mxE -sumr_opp.\nby apply: eq_bigr => j _; rewrite mxE mulrN.\nQed.\n\nLemma mulNmx : forall m n p (A : 'M_(m, n)) (B : 'M_(n, p)),\n  - A *m B = - (A *m B).\nProof.\nmove=> m n p A B; apply/matrixP=> i k; rewrite !mxE -sumr_opp.\nby apply: eq_bigr => j _; rewrite mxE mulNr.\nQed.\n\nLemma mulmx_addl : forall m n p (A1 A2 : 'M_(m, n)) (B : 'M_(n, p)),\n  (A1 + A2) *m B = A1 *m B + A2 *m B.\nProof.\nmove=> m n p A1 A2 B; apply/matrixP=> i k; rewrite !mxE -big_split /=.\nby apply: eq_bigr => j _; rewrite !mxE -mulr_addl.\nQed.\n\nLemma mulmx_addr : forall m n p (A : 'M_(m, n)) (B1 B2 : 'M_(n, p)),\n  A *m (B1 + B2) = A *m B1 + A *m B2.\nProof.\nmove=> m n p A B1 B2; apply/matrixP=> i k; rewrite !mxE -big_split /=.\nby apply: eq_bigr => j _; rewrite mxE mulr_addr.\nQed.\n\nLemma mulmx_subl : forall m n p (A1 A2 : 'M_(m, n)) (B : 'M_(n, p)),\n  (A1 - A2) *m B = A1 *m B - A2 *m B.\nProof. by move=> m n p A1 A2 B; rewrite mulmx_addl mulNmx. Qed.\n\nLemma mulmx_subr : forall m n p (A : 'M_(m, n)) (B1 B2 : 'M_(n, p)),\n  A *m (B1 - B2) = A *m B1 - A *m B2.\nProof. by move=> m n p A1 A2 B; rewrite mulmx_addr mulmxN. Qed.\n\nLemma mulmx_suml : forall m n p (A : 'M_(n, p)) I r P (B_ : I -> 'M_(m, n)),\n   (\\sum_(i <- r | P i) B_ i) *m A = \\sum_(i <- r | P i) B_ i *m A.\nProof.\nmove=> m n p A; apply: (big_morph (mulmx^~ A)) => [B C|]; last exact: mul0mx.\nby rewrite mulmx_addl.\nQed.\n\nLemma mulmx_sumr : forall m n p (A : 'M_(m, n)) I r P (B_ : I -> 'M_(n, p)),\n   A *m (\\sum_(i <- r | P i) B_ i) = \\sum_(i <- r | P i) A *m B_ i.\nProof.\nmove=> m n p A; apply: (big_morph (mulmx A)) => [B C|]; last exact: mulmx0.\nby rewrite mulmx_addr.\nQed.\n\nLemma scalemxAl : forall m n p a (A : 'M_(m, n)) (B : 'M_(n, p)),\n  a *m: (A *m B) = (a *m: A) *m B.\nProof.\nmove=> m n p a A B; apply/matrixP=> i k; rewrite !mxE big_distrr /=.\nby apply: eq_bigr => j _; rewrite mulrA mxE.\nQed.\n(* Right scaling associativity requires a commutative ring *)\n\nLemma rowE : forall m n i (A : 'M_(m, n)), row i A = delta_mx 0 i *m A.\nProof.\nmove=> m n i A; apply/rowP=> j; rewrite !mxE (bigD1 i) //= mxE !eqxx mul1r.\nby rewrite big1 ?addr0 // => i' ne_i'i; rewrite mxE /= (negbTE ne_i'i) mul0r.\nQed.\n\nLemma row_mul : forall m n p (i : 'I_m) A (B : 'M_(n, p)),\n  row i (A *m B) = row i A *m B.\nProof. by move=> m n p i A B; rewrite !rowE mulmxA. Qed.\n\nLemma mulmx_sum_row : forall m n (u : 'rV_m) (A : 'M_(m, n)),\n  u *m A = \\sum_i u 0 i *m: row i A.\nProof.\nmove=> m n u A; apply/rowP=> j; rewrite mxE summxE; apply: eq_bigr => i _.\nby rewrite !mxE.\nQed.\n\nLemma mul_delta_mx_cond : forall m n p (j1 j2 : 'I_n) (i1 : 'I_m) (k2 : 'I_p),\n  delta_mx i1 j1 *m delta_mx j2 k2 = delta_mx i1 k2 *+ (j1 == j2).\nProof.\nmove=> m n p j1 j2 i1 k2; apply/matrixP=> i k; rewrite !mxE (bigD1 j1) //=.\nrewrite mulmxnE !mxE !eqxx andbT -natr_mul -mulrnA !mulnb !andbA andbAC.\nby rewrite big1 ?addr0 // => j; rewrite !mxE andbC -natr_mul; move/negbTE->.\nQed.\n\nLemma mul_delta_mx : forall m n p (j : 'I_n) (i : 'I_m) (k : 'I_p),\n  delta_mx i j *m delta_mx j k = delta_mx i k.\nProof. by move=> m n p j i k; rewrite mul_delta_mx_cond eqxx. Qed.\n\nLemma mul_delta_mx_0 : forall m n p (j1 j2 : 'I_n) (i1 : 'I_m) (k2 : 'I_p),\n  j1 != j2 -> delta_mx i1 j1 *m delta_mx j2 k2 = 0.\nProof.\nby move=> m n p j1 j2 i1 k2; rewrite mul_delta_mx_cond; move/negbTE->.\nQed.\n\nLemma mul_diag_mx : forall m n d (A : 'M_(m, n)),\n  diag_mx d *m A = \\matrix_(i, j) (d 0 i * A i j).\nProof.\nmove=> m n d A; apply/matrixP=> i j.\nrewrite !mxE (bigD1 i) //= mxE eqxx big1 ?addr0 // => i'.\nby rewrite mxE eq_sym mulrnAl; move/negbTE->.\nQed.\n\nLemma mul_mx_diag : forall m n (A : 'M_(m, n)) d,\n  A *m diag_mx d = \\matrix_(i, j) (A i j * d 0 j).\nProof.\nmove=> m n A d; apply/matrixP=> i j.\nrewrite !mxE (bigD1 j) //= mxE eqxx big1 ?addr0 // => i'.\nby rewrite mxE eq_sym mulrnAr; move/negbTE->.\nQed.\n\nLemma mulmx_diag : forall n (d e : 'rV_n),\n  diag_mx d *m diag_mx e = diag_mx (\\row_j (d 0 j * e 0 j)).\nProof.\nby move=> n d e; apply/matrixP=> i j; rewrite mul_diag_mx !mxE mulrnAr.\nQed.\n\nLemma mul_scalar_mx : forall m n a (A : 'M_(m, n)), a%:M *m A = a *m: A.\nProof.\nmove=> m n a A; rewrite -diag_const_mx mul_diag_mx.\nby apply/matrixP=> i j; rewrite !mxE.\nQed.\n\nLemma scalar_mxM : forall n a b, (a * b)%:M = a%:M *m b%:M :> 'M_n.\nProof. by move=> n a b; rewrite mul_scalar_mx scale_scalar_mx. Qed.\n\nLemma mul1mx : forall m n (A : 'M_(m, n)), 1%:M *m A = A.\nProof. by move=> m n A; rewrite mul_scalar_mx scale1mx. Qed.\n\nLemma mulmx1 : forall m n (A : 'M_(m, n)), A *m 1%:M = A.\nProof.\nmove=> m n A; rewrite -diag_const_mx mul_mx_diag.\nby apply/matrixP=> i j; rewrite !mxE mulr1.\nQed.\n\nLemma mul_col_perm : forall m n p s (A : 'M_(m, n)) (B : 'M_(n, p)),\n  col_perm s A *m B = A *m row_perm s^-1 B.\nProof.\nmove=> m n p s A B; apply/matrixP=> i k; rewrite !mxE.\nrewrite (reindex_inj (@perm_inj _ s^-1)); apply: eq_bigr => j _ /=.\nby rewrite !mxE permKV.\nQed.\n\nLemma mul_row_perm : forall m n p s (A : 'M_(m, n)) (B : 'M_(n, p)),\n  A *m row_perm s B = col_perm s^-1 A *m B.\nProof. by move=> m n p s A B; rewrite mul_col_perm invgK. Qed.\n\nLemma mul_xcol : forall m n p j1 j2 (A : 'M_(m, n)) (B : 'M_(n, p)),\n  xcol j1 j2 A *m B = A *m xrow j1 j2 B.\nProof. by move=> m n p j1 j2 A B; rewrite mul_col_perm tpermV. Qed.\n\n(* Permutation matrix *)\n\nDefinition perm_mx n s : 'M_n := row_perm s 1%:M.\n\nDefinition tperm_mx n i1 i2 : 'M_n := perm_mx (tperm i1 i2).\n\nLemma col_permE : forall m n s (A : 'M_(m, n)),\n  col_perm s A = A *m perm_mx s^-1.\nProof. by move=> m n s A; rewrite mul_row_perm mulmx1 invgK. Qed.\n\nLemma row_permE : forall m n s (A : 'M_(m, n)), row_perm s A = perm_mx s *m A.\nProof.\nmove=> m n s a; rewrite -[perm_mx _]mul1mx mul_row_perm mulmx1.\nby rewrite -mul_row_perm mul1mx.\nQed.\n\nLemma xcolE : forall m n j1 j2 (A : 'M_(m, n)),\n  xcol j1 j2 A = A *m tperm_mx j1 j2.\nProof. by move=> m n j1 j2 A; rewrite /xcol col_permE tpermV. Qed.\n\nLemma xrowE : forall m n i1 i2 (A : 'M_(m, n)),\n  xrow i1 i2 A = tperm_mx i1 i2 *m A.\nProof. by move=> m n i1 i2 A; exact: row_permE. Qed.\n\nLemma tr_perm_mx : forall n (s : 'S_n), (perm_mx s)^T = perm_mx s^-1.\nProof.\nby move=> n s; rewrite -[_^T]mulmx1 tr_row_perm mul_col_perm trmx1 mul1mx.\nQed.\n\nLemma tr_tperm_mx : forall n i1 i2, (tperm_mx i1 i2)^T = tperm_mx i1 i2 :> 'M_n.\nProof. by move=> n i1 i2; rewrite tr_perm_mx tpermV. Qed.\n\nLemma perm_mx1 : forall n, perm_mx 1 = 1%:M :> 'M_n.\nProof. move=> n; exact: row_perm1. Qed.\n\nLemma perm_mxM : forall n (s t : 'S_n),\n  perm_mx (s * t) = perm_mx s *m perm_mx t.\nProof. by move=> n s t; rewrite -row_permE -row_permM. Qed.\n\nDefinition is_perm_mx n (A : 'M_n) := existsb s, A == perm_mx s.\n\nLemma is_perm_mxP : forall n (A : 'M_n),\n  reflect (exists s, A = perm_mx s) (is_perm_mx A).\nProof. by move=> n A; apply: (iffP existsP) => [] [s]; move/eqP; exists s. Qed.\n\nLemma perm_mx_is_perm : forall n (s : 'S_n), is_perm_mx (perm_mx s).\nProof. by move=> n s; apply/is_perm_mxP; exists s. Qed.\n\nLemma is_perm_mx1 : forall n, is_perm_mx (1%:M : 'M_n).\nProof. by move=> n; rewrite -perm_mx1 perm_mx_is_perm. Qed.\n\nLemma is_perm_mxMl : forall n (A B : 'M_n),\n  is_perm_mx A -> is_perm_mx (A *m B) = is_perm_mx B.\nProof.\nmove=> n A B; case/is_perm_mxP=> s ->.\napply/is_perm_mxP/is_perm_mxP=> [[t def_t] | [t ->]]; last first.\n  by exists (s * t)%g; rewrite perm_mxM.\nexists (s^-1 * t)%g.\nby rewrite perm_mxM -def_t -!row_permE -row_permM mulVg row_perm1.\nQed.\n\nLemma is_perm_mx_tr : forall n (A : 'M_n), is_perm_mx A^T = is_perm_mx A.\nProof.\nmove=> n A; apply/is_perm_mxP/is_perm_mxP=> [[t def_t] | [t ->]]; exists t^-1%g.\n  by rewrite -tr_perm_mx -def_t trmxK.\nby rewrite tr_perm_mx.\nQed.\n\nLemma is_perm_mxMr : forall n (A B : 'M_n),\n  is_perm_mx B -> is_perm_mx (A *m B) = is_perm_mx A.\nProof.\nmove=> n A B; case/is_perm_mxP=> s ->.\nrewrite -[s]invgK -col_permE -is_perm_mx_tr tr_col_perm row_permE.\nby rewrite is_perm_mxMl (perm_mx_is_perm, is_perm_mx_tr).\nQed.\n\n(* Partial identity matrix (used in rank decomposition). *)\n\nDefinition pid_mx {m n} r : 'M[R]_(m, n) :=\n  \\matrix_(i, j) ((i == j :> nat) && (i < r))%:R.\n\nLemma pid_mx_0 : forall m n, pid_mx 0 = 0 :> 'M_(m, n).\nProof. by move=> m n; apply/matrixP=> i j; rewrite !mxE andbF. Qed.\n\nLemma pid_mx_1 : forall r, pid_mx r = 1%:M :> 'M_r.\nProof. by move=> r; apply/matrixP=> i j; rewrite !mxE ltn_ord andbT. Qed.\n\nLemma pid_mx_row : forall n r, pid_mx r = row_mx 1%:M 0 :> 'M_(r, r + n).\nProof.\nmove=> n r; apply/matrixP=> i j; rewrite !mxE ltn_ord andbT.\ncase: splitP => j' ->; rewrite !mxE // .\nby rewrite eqn_leq andbC leqNgt lshift_subproof.\nQed.\n\nLemma pid_mx_col : forall m r, pid_mx r = col_mx 1%:M 0 :> 'M_(r + m, r).\nProof.\nmove=> m r; apply/matrixP=> i j; rewrite !mxE andbC.\nby case: splitP => i' ->; rewrite !mxE // eq_sym.\nQed.\n\nLemma pid_mx_block : forall m n r,\n  pid_mx r = block_mx 1%:M 0 0 0 :> 'M_(r + m, r + n).\nProof.\nmove=> m n r; apply/matrixP=> i j; rewrite !mxE row_mx0 andbC.\ncase: splitP => i' ->; rewrite !mxE //; case: splitP => j' ->; rewrite !mxE //=.\nby rewrite eqn_leq andbC leqNgt lshift_subproof.\nQed.\n\nLemma tr_pid_mx : forall m n r, (pid_mx r)^T = pid_mx r :> 'M_(n, m).\nProof.\nby move=> m n r; apply/matrixP=> i j; rewrite !mxE eq_sym; case: eqP => // ->.\nQed.\n\nLemma pid_mx_minv : forall m n r, pid_mx (minn m r) = pid_mx r :> 'M_(m, n).\nProof. by move=> m n r; apply/matrixP=> i j; rewrite !mxE leq_minr ltn_ord. Qed.\n \nLemma pid_mx_minh : forall m n r, pid_mx (minn n r) = pid_mx r :> 'M_(m, n).\nProof. by move=> m n r; apply: trmx_inj; rewrite !tr_pid_mx pid_mx_minv. Qed.\n\nLemma mul_pid_mx : forall m n p q r,\n  (pid_mx q : 'M_(m, n)) *m (pid_mx r : 'M_(n, p)) = pid_mx (minn n (minn q r)).\nProof.\nmove=> m n p q r; apply/matrixP=> i k; rewrite !mxE !leq_minr.\ncase: leqP => [le_n_i | lt_i_n].\n  rewrite andbF big1 // => j _.\n  by rewrite -pid_mx_minh !mxE leq_minr ltnNge le_n_i andbF mul0r.\nrewrite (bigD1 (Ordinal lt_i_n)) //= big1 ?addr0 => [|j].\n  by rewrite !mxE eqxx /= -natr_mul mulnb andbCA.\nby rewrite -val_eqE /= !mxE eq_sym -natr_mul; move/negbTE=> ->.\nQed.\n\nLemma pid_mx_id : forall m n p r,\n  r <= n -> (pid_mx r : 'M_(m, n)) *m (pid_mx r : 'M_(n, p)) = pid_mx r.\nProof. by move=> m n p r le_r_n; rewrite mul_pid_mx minnn minnr. Qed.\n\nDefinition copid_mx {n} r : 'M_n := 1%:M - pid_mx r.\n\nLemma mul_copid_mx_pid : forall m n r,\n  r <= m -> copid_mx r *m pid_mx r = 0 :> 'M_(m, n).\nProof. by move=> m n r le_r_m; rewrite mulmx_subl mul1mx pid_mx_id ?subrr. Qed.\n\nLemma mul_pid_mx_copid : forall m n r,\n  r <= n -> pid_mx r *m copid_mx r = 0 :> 'M_(m, n).\nProof. by move=> m n r le_r_n; rewrite mulmx_subr mulmx1 pid_mx_id ?subrr. Qed.\n\nLemma copid_mx_id : forall n r,\n  r <= n -> copid_mx r *m copid_mx r = copid_mx r :> 'M_n.\nProof.\nby move=> n r le_r_n; rewrite mulmx_subl mul1mx mul_pid_mx_copid // oppr0 addr0.\nQed.\n\n(* Block products; we cover all 1 x 2, 2 x 1, and 2 x 2 block products. *)\n\nLemma mul_mx_row : forall m n p1 p2,\n    forall (A : 'M_(m, n)) (Bl : 'M_(n, p1)) (Br : 'M_(n, p2)),\n  A *m row_mx Bl Br = row_mx (A *m Bl) (A *m Br).\nProof.\nmove=> m n p1 p2 A Bl Br; apply/matrixP=> i k; rewrite !mxE.\nby case defk: (split k); rewrite mxE; apply: eq_bigr => j _; rewrite mxE defk.\nQed.\n\nLemma mul_col_mx : forall m1 m2 n p,\n    forall (Au : 'M_(m1, n)) (Ad : 'M_(m2, n)) (B : 'M_(n, p)),\n  col_mx Au Ad *m B = col_mx (Au *m B) (Ad *m B).\nProof.\nmove=> m1 m2 n p Au Ad B; apply/matrixP=> i k; rewrite !mxE.\nby case defi: (split i); rewrite mxE; apply: eq_bigr => j _; rewrite mxE defi.\nQed.\n\nLemma mul_row_col : forall m n1 n2 p,\n    forall (Al : 'M_(m, n1)) (Ar : 'M_(m, n2)),\n    forall (Bu : 'M_(n1, p)) (Bd : 'M_(n2, p)),\n  row_mx Al Ar *m col_mx Bu Bd = Al *m Bu + Ar *m Bd.\nProof.\nmove=> m n1 n2 p Al Ar Bu Bd.\napply/matrixP=> i k; rewrite !mxE big_split_ord /=.\ncongr (_ + _); apply: eq_bigr => j _; first by rewrite row_mxEl col_mxEu.\nby rewrite row_mxEr col_mxEd.\nQed.\n\nLemma mul_col_row : forall m1 m2 n p1 p2,\n    forall (Au : 'M_(m1, n)) (Ad : 'M_(m2, n)),\n    forall (Bl : 'M_(n, p1)) (Br : 'M_(n, p2)),\n  col_mx Au Ad *m row_mx Bl Br\n     = block_mx (Au *m Bl) (Au *m Br) (Ad *m Bl) (Ad *m Br).\nProof. by move=> *; rewrite mul_col_mx !mul_mx_row. Qed.\n\nLemma mul_row_block : forall m n1 n2 p1 p2,\n    forall (Al : 'M_(m, n1)) (Ar : 'M_(m, n2)),\n    forall (Bul : 'M_(n1, p1)) (Bur : 'M_(n1, p2)),\n    forall (Bdl : 'M_(n2, p1)) (Bdr : 'M_(n2, p2)),\n  row_mx Al Ar *m block_mx Bul Bur Bdl Bdr\n   = row_mx (Al *m Bul + Ar *m Bdl) (Al *m Bur + Ar *m Bdr).\nProof. by move=> *; rewrite block_mxEh mul_mx_row !mul_row_col. Qed.\n\nLemma mul_block_col : forall m1 m2 n1 n2 p,\n    forall (Aul : 'M_(m1, n1)) (Aur : 'M_(m1, n2)),\n    forall (Adl : 'M_(m2, n1)) (Adr : 'M_(m2, n2)),\n    forall (Bu : 'M_(n1, p)) (Bd : 'M_(n2, p)),\n  block_mx Aul Aur Adl Adr *m col_mx Bu Bd\n   = col_mx (Aul *m Bu + Aur *m Bd) (Adl *m Bu + Adr *m Bd).\nProof. by move=> *; rewrite mul_col_mx !mul_row_col. Qed.\n\nLemma mulmx_block : forall m1 m2 n1 n2 p1 p2,\n    forall (Aul : 'M_(m1, n1)) (Aur : 'M_(m1, n2)),\n    forall (Adl : 'M_(m2, n1)) (Adr : 'M_(m2, n2)),\n    forall (Bul : 'M_(n1, p1)) (Bur : 'M_(n1, p2)),\n    forall (Bdl : 'M_(n2, p1)) (Bdr : 'M_(n2, p2)),\n  block_mx Aul Aur Adl Adr *m block_mx Bul Bur Bdl Bdr\n    = block_mx (Aul *m Bul + Aur *m Bdl) (Aul *m Bur + Aur *m Bdr)\n               (Adl *m Bul + Adr *m Bdl) (Adl *m Bur + Adr *m Bdr).\nProof. by move=> *; rewrite mul_col_mx !mul_row_block. Qed.\n\n(* The trace. *)\nDefinition mxtrace n (A : 'M[R]_n) := \\sum_i A i i.\nNotation \"'\\tr' A\" := (mxtrace A) : ring_scope.\n\nLemma mxtrace_tr : forall n (A : 'M_n), \\tr A^T = \\tr A.\nProof. by move=> n A; apply: eq_bigr=> i _; rewrite mxE. Qed.\n\nLemma mxtrace0 : forall n, \\tr (0 : 'M_n) = 0.\nProof. by move=> n; apply: big1 => i _; rewrite mxE. Qed.\n\nLemma mxtrace_add : forall n (A B : 'M_n), \\tr (A + B) = \\tr A + \\tr B.\nProof.\nby move=> n A B; rewrite -big_split; apply: eq_bigr => i _; rewrite mxE.\nQed.\n\nLemma mxtrace_scale : forall n a (A : 'M_n), \\tr (a *m: A) = a * \\tr A.\nProof.\nby move=> n a A; rewrite big_distrr; apply: eq_bigr => i _; rewrite mxE.\nQed.\n\nLemma mxtrace_diag : forall n (D : 'rV_n), \\tr (diag_mx D) = \\sum_j D 0 j.\nProof. by move=> n D; apply: eq_bigr => j _; rewrite mxE eqxx. Qed.\n\nLemma mxtrace_scalar : forall n a, \\tr (a%:M : 'M_n) = a *+ n.\nProof.\nmove=> n a; rewrite -diag_const_mx mxtrace_diag.\nby rewrite (eq_bigr _ (fun j _ => mxE _ 0 j)) sumr_const card_ord.\nQed.\n\nLemma mxtrace1 : forall n, \\tr (1%:M : 'M_n) = n%:R.\nProof. by move=> n; exact: mxtrace_scalar. Qed.\n\nLemma trace_mx11 : forall A : 'M_1, \\tr A = A 0 0.\nProof. by move=> A; rewrite {1}[A]mx11_scalar mxtrace_scalar. Qed.\n\nLemma mxtrace_block : forall n1 n2 (Aul : 'M_n1) Aur Adl (Adr : 'M_n2),\n  \\tr (block_mx Aul Aur Adl Adr) = \\tr Aul + \\tr Adr.\nProof.\nmove=> n1 n2 Aul Aur Adl Adr; rewrite /(\\tr _) big_split_ord /=.\nby congr (_ + _); apply: eq_bigr => i _; rewrite (block_mxEul, block_mxEdr).\nQed.\n\n(* Matrix ring Structure : now structural (dimension of the form n.+1) *)\nSection MatrixRing.\n\nVariable n' : nat.\nLocal Notation n := n'.+1.\n\nLemma matrix_nonzero1 : 1%:M != 0 :> 'M_n.\nProof.\nby apply/eqP; move/matrixP; move/(_ 0 0); move/eqP; rewrite !mxE oner_eq0.\nQed.\n\nDefinition matrix_ringMixin :=\n  RingMixin (@mulmxA n n n n) (@mul1mx n n) (@mulmx1 n n)\n            (@mulmx_addl n n n) (@mulmx_addr n n n) matrix_nonzero1.\nCanonical Structure matrix_ringType :=\n  Eval hnf in RingType 'M[R]_n  matrix_ringMixin.\n\nLemma mulmxE : mulmx = *%R. Proof. by []. Qed.\nLemma idmxE : 1%:M = 1 :> 'M_n. Proof. by []. Qed.\n\nLemma scalar_mxRM : GRing.morphism (@scalar_mx n).\nProof.\nby split=> // a b; rewrite ?scalar_mxM ?scalar_mx_add ?scalar_mx_opp.\nQed.\n\nEnd MatrixRing.\n\nSection LiftPerm.\n\n(* Block expresssion of a lifted permutation matrix, for the Cormen LUP. *)\n\nVariable n : nat.\n\n(* These could be in zmodp, that would introduce a dependency of on perm. *)\n\nDefinition lift0_perm s : 'S_n.+1 := lift_perm 0 0 s.\n\nLemma lift0_perm0 : forall s, lift0_perm s 0 = 0.\nProof. by move=> s; exact: lift_perm_id. Qed.\n\nLemma lift0_perm_lift : forall s k',\n  lift0_perm s (lift 0 k') = lift (0 : 'I_n.+1) (s k').\nProof. by move=> s i; exact: lift_perm_lift. Qed.\n\nLemma lift0_permK : forall s, cancel (lift0_perm s) (lift0_perm s^-1).\nProof. by move=> s i; rewrite /lift0_perm -lift_permV permK. Qed.\n\nLemma lift0_perm_eq0 : forall s i, (lift0_perm s i == 0) = (i == 0).\nProof. by move=> s i; rewrite (canF_eq (lift0_permK s)) lift0_perm0. Qed.\n\n(* Block expresssion of a lifted permutation matrix *)\n\nDefinition lift0_mx A : 'M_(1 + n) := block_mx 1 0 0 A.\n\nLemma lift0_mx_perm : forall s, lift0_mx (perm_mx s) = perm_mx (lift0_perm s).\nProof.\nmove=> s; apply/matrixP=> /= i j.\nrewrite !mxE split1 /=; case: unliftP => [i'|] -> /=.\n  rewrite lift0_perm_lift !mxE split1 /=.\n  by case: unliftP => [j'|] ->; rewrite ?(inj_eq (@lift_inj _ _)) /= !mxE.\nrewrite lift0_perm0 !mxE split1 /=.\nby case: unliftP => [j'|] ->; rewrite /= mxE.\nQed.\n\nLemma lift0_mx_is_perm : forall s, is_perm_mx (lift0_mx (perm_mx s)).\nProof. by move=> s; rewrite lift0_mx_perm perm_mx_is_perm. Qed.\n\nEnd LiftPerm.\n\n(* Determinants and adjugates are defined here, but most of their properties *)\n(* only hold for matrices over a commutative ring, so their theory is        *)\n(* deferred to that section.                                                 *)\n\n(* The determinant, in one line with the Leibniz Formula *)\nDefinition determinant n (A : 'M_n) : R :=\n  \\sum_(s : 'S_n) (-1) ^+ s * \\prod_i A i (s i).\n\n(* The cofactor of a matrix on the indexes i and j *)\nDefinition cofactor n A (i j : 'I_n) : R :=\n  (-1) ^+ (i + j) * determinant (row' i (col' j A)).\n\n(* The adjugate matrix : defined as the transpose of the matrix of cofactors *)\nDefinition adjugate n (A : 'M_n) := \\matrix_(i, j) cofactor A j i.\n\nEnd MatrixAlgebra.\n\nImplicit Arguments delta_mx [R m n].\nImplicit Arguments scalar_mx [R n].\nImplicit Arguments perm_mx [R n].\nImplicit Arguments tperm_mx [R n].\nImplicit Arguments pid_mx [R m n].\nImplicit Arguments copid_mx [R n].\nPrenex Implicits delta_mx diag_mx scalar_mx perm_mx tperm_mx pid_mx copid_mx.\nPrenex Implicits scalemx mulmx mxtrace determinant cofactor adjugate.\nNotation \"a *m: A\" := (scalemx a A) : ring_scope.\nNotation \"a %:M\" := (scalar_mx a) : ring_scope.\nNotation \"A *m B\" := (mulmx A B) : ring_scope.\nNotation \"\\tr A\" := (mxtrace A) : ring_scope.\nNotation \"'\\det' A\" := (determinant A) : ring_scope.\nNotation \"'\\adj' A\" := (adjugate A) : ring_scope.\nImplicit Arguments mul_delta_mx [R m n p].\nImplicit Arguments scalar_mxRM [R n'].\nPrenex Implicits mul_delta_mx scalar_mxRM.\n\n(* Non-commutative transpose requires multiplication in the converse ring.   *)\nLemma trmx_mul_rev : forall (R : ringType) m n p,\n    let R' := RevRingType R in forall (A : 'M[R]_(m, n)) (B : 'M[R]_(n, p)),\n  (A *m B)^T = (B : 'M[R']_(n, p))^T *m (A : 'M[R']_(m, n))^T.\nProof.\nmove=> R m n p /= A B; apply/matrixP=> k i; rewrite !mxE.\nby apply: eq_bigr => j _; rewrite !mxE.\nQed.\n\nCanonical Structure matrix_finRingType (R : finRingType) n' :=\n  Eval hnf in [finRingType of 'M[R]_n'.+1].\n\n(* Parametricity over the algebra structure; since ssralg does't have        *)\n(* support for purely additive morphisms, we only work at the ring level.    *)\nSection MapRingMatrix.\n\nVariables (aR rR : ringType) (f : aR -> rR).\nHypothesis fRM : GRing.morphism f.\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\n\nSection FixedSize.\n\nVariables m n p : nat.\nImplicit Type A : 'M[aR]_(m, n).\n\nLemma map_mx0 : 0^f = 0 :> 'M_(m, n).\nProof. by rewrite map_const_mx ringM_0. Qed.\n\nLemma map_mxN : forall A,  (- A)^f = - A^f.\nProof. by move=> A; apply/matrixP=> i j; rewrite !mxE ringM_opp. Qed.\n\nLemma map_mxD : forall A B, (A + B)^f = A^f + B^f.\nProof. by move=> A B; apply/matrixP=> i j; rewrite !mxE ringM_add. Qed.\n\nLemma map_mx_mulnat : forall A d, (A *+ d)^f = A^f *+ d.\nProof. by move=> A; elim=> [|d IHd]; rewrite ?map_mx0 ?mulrS ?map_mxD ?IHd. Qed.\n\nLemma map_mx_sub : forall A B, (A - B)^f =  A^f - B^f.\nProof. by move=> A B; rewrite map_mxD map_mxN. Qed.\n\nDefinition map_mx_sum := big_morph _ map_mxD map_mx0.\n\nLemma map_mxZ : forall a A, (a *m: A)^f = f a *m: A^f.\nProof. by move=> a A; apply/matrixP=> i j; rewrite !mxE ringM_mul. Qed.\n\nLemma map_mxM : forall A B, (A *m B)^f = A^f *m B^f :> 'M_(m, p).\nProof.\nmove=> A B; apply/matrixP=> i k; rewrite !mxE ringM_sum //.\nby apply: eq_bigr => j; rewrite !mxE ringM_mul.\nQed.\n\nLemma map_delta_mx : forall i j, (delta_mx i j)^f = delta_mx i j :> 'M_(m, n).\nProof. by move=> i j; apply/matrixP=> i' j'; rewrite !mxE ringM_nat. Qed.\n\nLemma map_diag_mx : forall d, (diag_mx d)^f = diag_mx d^f :> 'M_n.\nProof. by move=> d; apply/matrixP=> i j; rewrite !mxE ringM_natmul. Qed.\n\nLemma map_scalar_mx : forall a, a%:M^f = (f a)%:M :> 'M_n.\nProof. by move=> a; apply/matrixP=> i j; rewrite !mxE ringM_natmul. Qed.\n\nLemma map_mx1 : 1%:M^f = 1%:M :> 'M_n.\nProof. by rewrite map_scalar_mx ringM_1. Qed.\n\nLemma map_perm_mx : forall s : 'S_n, (perm_mx s)^f = perm_mx s.\nProof. by move=> s; apply/matrixP=> i j; rewrite !mxE ringM_nat. Qed.\n\nLemma map_tperm_mx : forall i1 i2 : 'I_n, (tperm_mx i1 i2)^f = tperm_mx i1 i2.\nProof. by move=> i j; exact: map_perm_mx. Qed.\n\nLemma map_pid_mx : forall r, (pid_mx r)^f = pid_mx r :> 'M_(m, n).\nProof. by move=> r; apply/matrixP=> i j; rewrite !mxE ringM_nat. Qed.\n\nLemma trace_map_mx : forall A : 'M_n, \\tr A^f = f (\\tr A).\nProof.\nby move=> A; rewrite ringM_sum //; apply: eq_bigr => i _; rewrite mxE.\nQed.\n\nLemma det_map_mx : forall n' (A : 'M_n'), \\det A^f = f (\\det A).\nProof.\nmove=> n' A; rewrite ringM_sum //; apply: eq_bigr => s _.\nrewrite ringM_mul // ringM_sign // (ringM_prod fRM); congr (_ * _).\nby apply: eq_bigr => i _; rewrite mxE.\nQed.\n\nLemma cofactor_map_mx : forall (A : 'M_n) i j,\n  cofactor A^f i j = f (cofactor A i j).\nProof.\nby move=> A i j; rewrite ringM_mul ?ringM_sign // -det_map_mx map_row' map_col'.\nQed.\n\nLemma map_mx_adj : forall A : 'M_n, (\\adj A)^f = \\adj A^f.\nProof. by move=> A; apply/matrixP=> i j; rewrite !mxE cofactor_map_mx. Qed.\n\nEnd FixedSize.\n\nLemma map_copid_mx : forall n r, (copid_mx r)^f = copid_mx r :> 'M_n.\nProof. by move=> n r; rewrite map_mx_sub map_mx1 map_pid_mx. Qed.\n\nLemma map_mxRM : forall n', GRing.morphism ((map_mx f) n'.+1 n'.+1).\nProof. split; [exact: map_mx_sub | exact: map_mxM | exact: map_mx1]. Qed.\n\nEnd MapRingMatrix.\n\nSection ComMatrix.\n(* Lemmas for matrices with coefficients in a commutative ring *)\nVariable R : comRingType.\n\nLemma trmx_mul : forall m n p (A : 'M[R]_(m, n)) (B : 'M_(n, p)),\n  (A *m B)^T = B^T *m A^T.\nProof.\nmove=> m n p A B; rewrite trmx_mul_rev; apply/matrixP=> k i; rewrite !mxE.\nby apply: eq_bigr => j _; rewrite mulrC.\nQed.\n\nLemma scalemxAr : forall m n p a (A : 'M[R]_(m, n)) (B : 'M_(n, p)),\n  a *m: (A *m B) = A *m (a *m: B).\nProof.\nmove=> m n p a A B.\nby apply: trmx_inj; rewrite !(trmx_scale, trmx_mul) scalemxAl.\nQed.\n\nLemma diag_mxC : forall n (d e : 'rV[R]_n),\n  diag_mx d *m diag_mx e = diag_mx e *m diag_mx d.\nProof.\nmove=> n d e; rewrite !mulmx_diag; congr (diag_mx _).\nby apply/rowP=> i; rewrite !mxE mulrC.\nQed.\n\nLemma diag_mx_comm : forall n' (d e : 'rV[R]_n'.+1),\n  GRing.comm (diag_mx d) (diag_mx e).\nProof. move=> n'; exact: diag_mxC. Qed.\n\nLemma scalar_mxC : forall m n a (A : 'M[R]_(m, n)), A *m a%:M = a%:M *m A.\nProof.\nmove=> m n a A; apply: trmx_inj.\nby rewrite trmx_mul tr_scalar_mx !mul_scalar_mx trmx_scale.\nQed.\n\nLemma scalar_mx_comm : forall n' a (A : 'M[R]_n'.+1), GRing.comm A a%:M.\nProof. move=> n; exact: scalar_mxC. Qed.\n\nLemma mul_mx_scalar : forall m n a (A : 'M[R]_(m, n)), A *m a%:M = a *m: A.\nProof. by move=> m n a A; rewrite scalar_mxC mul_scalar_mx. Qed.\n\nLemma mxtrace_mulC : forall m n (A : 'M[R]_(m, n)) (B : 'M_(n, m)),\n  \\tr (A *m B) = \\tr (B *m A).\nProof.\nmove=> m n A B; transitivity (\\sum_i \\sum_j A i j * B j i).\n  by apply: eq_bigr => i _; rewrite mxE.\nrewrite exchange_big; apply: eq_bigr => i _ /=; rewrite mxE.\napply: eq_bigr => j _; exact: mulrC.\nQed.\n\n(* The theory of determinants *)\n\nLemma determinant_multilinear : forall n (A B C : 'M[R]_n) i0 b c,\n    row i0 A = b *m: row i0 B + c *m: row i0 C ->\n    row' i0 B = row' i0 A ->\n    row' i0 C = row' i0 A ->\n  \\det A = b * \\det B + c * \\det C.\nProof.\nmove=> n A B C i0 b c; rewrite -[_ + _](row_id 0); move/row_eq=> ABC.\nmove/row'_eq=> BA; move/row'_eq=> CA.\nrewrite !big_distrr -big_split; apply: eq_bigr => s _ /=.\nrewrite -!(mulrCA (_ ^+s)) -mulr_addr; congr (_ * _).\nrewrite !(bigD1 i0 (_ : predT i0)) //= {}ABC !mxE mulr_addl !mulrA.\nby congr (_ * _ + _ * _); apply: eq_bigr => i i0i; rewrite ?BA ?CA.\nQed.\n\nLemma determinant_alternate : forall n (A : 'M[R]_n) i1 i2,\n  i1 != i2 -> A i1 =1 A i2 -> \\det A = 0.\nProof.\nmove=> n A i1 i2 Di12 A12; pose t := tperm i1 i2.\nhave oddMt: forall s, (t * s)%g = ~~ s :> bool.\n  by move=> s; rewrite odd_permM odd_tperm Di12.\nrewrite /(\\det _) (bigID (@odd_perm _)) /=.\napply: canLR (subrK _) _; rewrite add0r -sumr_opp.\nrewrite (reindex_inj (mulgI t)); apply: eq_big => //= s.\nrewrite oddMt; move/negPf->; rewrite mulN1r mul1r; congr (- _).\nrewrite (reindex_inj (@perm_inj _ t)); apply: eq_bigr => /= i _.\nby rewrite permM tpermK /t; case: tpermP => // ->; rewrite A12.\nQed.\n\nLemma det_tr : forall n (A : 'M[R]_n), \\det A^T = \\det A.\nProof.\nmove=> n A; rewrite /(\\det _) (reindex_inj (@invg_inj _)) /=.\napply: eq_bigr => s _ /=; rewrite !odd_permV (reindex_inj (@perm_inj _ s)) /=.\nby congr (_ * _); apply: eq_bigr => i _; rewrite mxE permK.\nQed.\n\nLemma det_perm : forall n (s : 'S_n), \\det (perm_mx s) = (-1) ^+ s :> R.\nProof.\nmove=> n s; rewrite /(\\det _) (bigD1 s) //=.\nrewrite big1 => [|i _]; last by rewrite /= !mxE eqxx.\nrewrite mulr1 big1 ?addr0 => //= t Dst.\ncase: (pickP (fun i => s i != t i)) => [i ist | Est].\n  by rewrite (bigD1 i) // mulrCA /= !mxE (negbTE ist) mul0r.\nby case/eqP: Dst; apply/permP => i; move/eqP: (Est i).\nQed.\n\nLemma det1 : forall n, \\det (1%:M : 'M[R]_n) = 1.\nProof. by move=> n; rewrite -perm_mx1 det_perm odd_perm1. Qed.\n\nLemma det_scalemx : forall n x (A : 'M[R]_n), \\det (x *m: A) = x ^+ n * \\det A.\nProof.\nmove=> n x A; rewrite big_distrr /=; apply: eq_bigr => s _.\nrewrite mulrCA; congr (_ * _).\nrewrite -{10}[n]card_ord -prodr_const -big_split /=.\nby apply: eq_bigr=> i _; rewrite mxE.\nQed.\n\nLemma det0 : forall n', \\det (0 : 'M[R]_n'.+1) = 0.\nProof. by move=> n'; rewrite -(scale0mx 0) det_scalemx exprS !mul0r. Qed.\n\nLemma det_scalar : forall n a, \\det (a%:M : 'M[R]_n) = a ^+ n.\nProof.\nby move=> n a; rewrite -{1}(mulr1 a) -scale_scalar_mx det_scalemx det1 mulr1.\nQed.\n\nLemma det_scalar1 : forall a, \\det (a%:M : 'M[R]_1) = a.\nProof. exact: det_scalar. Qed.\n\nLemma det_mulmx : forall n (A B : 'M[R]_n), \\det (A *m B) = \\det A * \\det B.\nProof.\nmove=> n A B; rewrite big_distrl /=.\npose F := {ffun 'I_n -> 'I_n}; pose AB s i j := A i j * B j (s i).\ntransitivity (\\sum_(f : F) \\sum_(s : 'S_n) (-1) ^+ s * \\prod_i AB s i (f i)).\n  rewrite exchange_big; apply: eq_bigr => /= s _; rewrite -big_distrr /=.\n  congr (_ * _); rewrite -(bigA_distr_bigA (AB s)) /=.\n  by apply: eq_bigr => x _; rewrite mxE.\nrewrite (bigID (fun f : F => injectiveb f)) /= addrC big1 ?add0r => [|f Uf].\n  rewrite (reindex (@pval _)) /=; last first.\n    pose in_Sn := insubd (1%g : 'S_n).\n    by exists in_Sn => /= f Uf; first apply: val_inj; exact: insubdK.\n  apply: eq_big => /= [s | s _]; rewrite ?(valP s) // big_distrr /=.\n  rewrite (reindex_inj (mulgI s)); apply: eq_bigr => t _ /=.\n  rewrite big_split /= mulrA mulrCA mulrA mulrCA mulrA.\n  rewrite -signr_addb odd_permM !pvalE; congr (_ * _); symmetry.\n  by rewrite (reindex_inj (@perm_inj _ s)); apply: eq_bigr => i; rewrite permM.\ntransitivity (\\det (\\matrix_(i, j) B (f i) j) * \\prod_i A i (f i)).\n  rewrite mulrC big_distrr /=; apply: eq_bigr => s _.\n  rewrite mulrCA big_split //=; congr (_ * (_ * _)).\n  by apply: eq_bigr => x _; rewrite mxE.\ncase/injectivePn: Uf => i1 [i2 Di12 Ef12].\nby rewrite (determinant_alternate Di12) ?simp //= => j; rewrite !mxE Ef12.\nQed.\n\nLemma detM : forall n' (A B : 'M[R]_n'.+1), \\det (A * B) = \\det A * \\det B.\nProof. move=> n'; exact: det_mulmx. Qed.\n\nLemma det_diag : forall n (d : 'rV[R]_n), \\det (diag_mx d) = \\prod_i d 0 i.\nProof.\nmove=> n d; rewrite /(\\det _) (bigD1 1%g) //= addrC big1 => [|p p1].\n  by rewrite add0r odd_perm1 mul1r; apply: eq_bigr => i; rewrite perm1 mxE eqxx.\nhave{p1}: ~~ perm_on set0 p.\n  apply: contra p1; move/subsetP=> p1; apply/eqP; apply/permP=> i.\n  by rewrite perm1; apply/eqP; apply/idPn; move/p1; rewrite inE.\ncase/subsetPn=> i; rewrite !inE eq_sym; move/negbTE=> p_i _.\nby rewrite (bigD1 i) //= mulrCA mxE p_i mul0r.\nQed.\n\n(* Laplace expansion lemma *)\nLemma expand_cofactor : forall n (A : 'M[R]_n) i j,\n  cofactor A i j =\n    \\sum_(s : 'S_n | s i == j) (-1) ^+ s * \\prod_(k | i != k) A k (s k).\nProof.\nmove=> [_ [] //|n] A i0 j0; rewrite (reindex (lift_perm i0 j0)); last first.\n  pose ulsf i (s : 'S_n.+1) k := odflt k (unlift (s i) (s (lift i k))).\n  have ulsfK: forall i (s : 'S__) k, lift (s i) (ulsf i s k) = s (lift i k).\n    rewrite /ulsf => i s k; have:= neq_lift i k.\n    by rewrite -(inj_eq (@perm_inj _ s)); case/unlift_some=> ? ? ->.\n  have inj_ulsf: injective (ulsf i0 _).\n    move=> s; apply: can_inj (ulsf (s i0) s^-1%g) _ => k'.\n    by rewrite {1}/ulsf ulsfK !permK liftK.\n  exists (fun s => perm (inj_ulsf s)) => [s _ | s].\n    by apply/permP=> k'; rewrite permE /ulsf lift_perm_lift lift_perm_id liftK.\n  move/(s _ =P _) => si0; apply/permP=> k.\n  case: (unliftP i0 k) => [k'|] ->; rewrite ?lift_perm_id //.\n  by rewrite lift_perm_lift -si0 permE ulsfK.\nrewrite /cofactor big_distrr /=.\napply: eq_big => [s | s _]; first by rewrite lift_perm_id eqxx.\nrewrite -signr_odd mulrA -signr_addb odd_add -odd_lift_perm; congr (_ * _).\ncase: (pickP 'I_n) => [k0 _ | n0]; last first.\n  by rewrite !big1 // => [j | i _]; first case/unlift_some=> i; have:= n0 i.\nrewrite (reindex (lift i0)).\n  by apply: eq_big => [k | k _] /=; rewrite ?neq_lift // !mxE lift_perm_lift.\nexists (fun k => odflt k0 (unlift i0 k)) => k; first by rewrite liftK.\nby case/unlift_some=> k' -> ->.\nQed.\n\nLemma expand_det_row : forall n (A : 'M[R]_n) i0,\n  \\det A = \\sum_j A i0 j * cofactor A i0 j.\nProof.\nmove=> n A i0; rewrite /(\\det A).\nrewrite (partition_big (fun s : 'S_n => s i0) predT) //=.\napply: eq_bigr => j0 _; rewrite expand_cofactor big_distrr /=.\napply: eq_bigr => s; move/eqP=> Dsi0.\nrewrite mulrCA (bigID (pred1 i0)) /= big_pred1_eq Dsi0; congr (_ * (_ * _)).\nby apply: eq_bigl => i; rewrite eq_sym.\nQed.\n\nLemma cofactor_tr : forall n (A : 'M[R]_n) i j,\n  cofactor A^T i j = cofactor A j i.\nProof.\nmove=> n A i j; rewrite /cofactor addnC; congr (_ * _).\nrewrite -tr_row' -tr_col' det_tr; congr (\\det _).\nby apply/matrixP=> ? ?; rewrite !mxE.\nQed.\n\nLemma expand_det_col : forall n (A : 'M[R]_n) j0,\n  \\det A = \\sum_i (A i j0 * cofactor A i j0).\nProof.\nmove=> n A j0; rewrite -det_tr (expand_det_row _ j0).\nby apply: eq_bigr => i _; rewrite cofactor_tr mxE.\nQed.\n\n(* Cramer Rule : adjugate on the left *)\nLemma mul_mx_adj : forall n (A : 'M[R]_n), A *m \\adj A = (\\det A)%:M.\nProof.\nmove=> n A; apply/matrixP=> i1 i2; rewrite !mxE; case Di: (i1 == i2).\n  rewrite (eqP Di) (expand_det_row _ i2) //=.\n  by apply: eq_bigr => j _; congr (_ * _); rewrite mxE.\npose B := \\matrix_(i, j) (if i == i2 then A i1 j else A i j).\nhave EBi12: B i1 =1 B i2 by move=> j; rewrite /= !mxE Di eq_refl.\nrewrite -[_ *+ _](determinant_alternate (negbT Di) EBi12) (expand_det_row _ i2).\napply: eq_bigr => j _; rewrite !mxE eq_refl; congr (_ * (_ * _)).\napply: eq_bigr => s _; congr (_ * _); apply: eq_bigr => i _.\nby rewrite !mxE eq_sym -if_neg neq_lift.\nQed.\n\nLemma trmx_adj : forall n (A : 'M[R]_n), (\\adj A)^T = \\adj A^T.\nProof. by move=> n A; apply/matrixP=> i j; rewrite !mxE cofactor_tr. Qed.\n\n(* Cramer rule : adjugate on the right *)\nLemma mul_adj_mx : forall n (A : 'M[R]_n), \\adj A *m A = (\\det A)%:M.\nProof.\nmove=> n A; apply: trmx_inj; rewrite trmx_mul trmx_adj mul_mx_adj.\nby rewrite det_tr tr_scalar_mx.\nQed.\n\n(* Left inverses are right inverses. *)\nLemma mulmx1C : forall n (A B : 'M[R]_n), A *m B = 1%:M -> B *m A = 1%:M.\nProof.\nmove=> n A B AB1; pose A' := \\det B *m: \\adj A.\nsuffices kA: A' *m A = 1%:M by rewrite -[B]mul1mx -kA -(mulmxA A') AB1 mulmx1.\nby rewrite -scalemxAl mul_adj_mx scale_scalar_mx mulrC -det_mulmx AB1 det1.\nQed.\n\n(* Only tall matrices have inverses. *)\nLemma mulmx1_min : forall m n (A : 'M[R]_(m, n)) B, A *m B = 1%:M -> m <= n.\nProof.\nmove=> m n A B AB1; rewrite leqNgt; apply/negP; move/subnKC; rewrite addSnnS.\nmove: (_ - _)%N => m' def_m; move: AB1; rewrite -{m}def_m in A B *.\nrewrite -(vsubmxK A) -(hsubmxK B) mul_col_row scalar_mx_block.\ncase/eq_block_mx; move/mulmx1C=> BlAu1 AuBr0 _; move/eqP; case/idPn.\nby rewrite -[_ B]mul1mx -BlAu1 -mulmxA AuBr0 !mulmx0 eq_sym nonzero1r.\nQed.\n\nLemma det_ublock : forall n1 n2 Aul (Aur : 'M[R]_(n1, n2)) Adr,\n  \\det (block_mx Aul Aur 0 Adr) = \\det Aul * \\det Adr.\nProof.\nmove=> n1 n2 Aul Aur Adr; elim: n1 => [|n1 IHn1] in Aul Aur *.\n  have ->: Aul = 1%:M by apply/matrixP=> i [].\n  rewrite det1 mul1r; congr (\\det _); apply/matrixP=> i j.\n  by do 2![rewrite !mxE; case: splitP => [[]|k] //=; move/val_inj=> <- {k}].\nrewrite (expand_det_col _ (lshift n2 0)) big_split_ord /=.\nrewrite addrC big1 1?simp => [|i _]; last by rewrite block_mxEdl mxE simp.\nrewrite (expand_det_col _ 0) big_distrl /=; apply eq_bigr=> i _.\nrewrite block_mxEul -!mulrA; do 2!congr (_ * _).\nby rewrite col'_col_mx !col'Kl col'0 row'Ku row'_row_mx IHn1.\nQed.\n\nLemma det_lblock : forall n1 n2 Aul (Adl : 'M[R]_(n2, n1)) Adr,\n  \\det (block_mx Aul 0 Adl Adr) = \\det Aul * \\det Adr.\nProof. by move=> *; rewrite -det_tr tr_block_mx trmx0 det_ublock !det_tr. Qed.\n\nEnd ComMatrix.\n\n(*****************************************************************************)\n(********************** Matrix unit ring and inverse marices *****************)\n(*****************************************************************************)\n\nSection MatrixInv.\n\nVariables R : comUnitRingType.\n\nSection Defs.\n\nVariable n : nat.\n\nDefinition unitmx : pred 'M[R]_n := fun A => GRing.unit (\\det A).\nDefinition invmx A := if A \\in unitmx then (\\det A)^-1 *m: \\adj A else A.\n\nLemma unitmxE : forall A, (A \\in unitmx) = GRing.unit (\\det A).\nProof. by []. Qed.\n\nLemma unitmx1 : 1%:M \\in unitmx. Proof. by rewrite unitmxE det1 unitr1. Qed.\n\nLemma unitmx_perm : forall s, perm_mx s \\in unitmx.\nProof. by move=> s; rewrite unitmxE det_perm unitr_exp ?unitr_opp ?unitr1. Qed.\n\nLemma unitmx_tr : forall A, (A^T \\in unitmx) = (A \\in unitmx).\nProof. by move=> A; rewrite unitmxE det_tr. Qed.\n\nLemma mulVmx : {in unitmx, left_inverse 1%:M invmx mulmx}.\nProof.\nby move=> A nsA; rewrite /invmx nsA -scalemxAl mul_adj_mx scale_scalar_mx mulVr.\nQed.\n\nLemma mulmxV : {in unitmx, right_inverse 1%:M invmx mulmx}.\nProof.\nby move=> A nsA; rewrite /invmx nsA -scalemxAr mul_mx_adj scale_scalar_mx mulVr.\nQed.\n\nLemma mulKmx : forall m, {in unitmx, @left_loop _ 'M_(n, m) invmx mulmx}.\nProof. by move=> m A uA /= B; rewrite mulmxA mulVmx ?mul1mx. Qed.\n\nLemma mulKVmx : forall m, {in unitmx, @rev_left_loop _ 'M_(n, m) invmx mulmx}.\nProof. by move=> m A uA /= B; rewrite mulmxA mulmxV ?mul1mx. Qed.\n\nLemma mulmxK : forall m, {in unitmx, @right_loop 'M_(m, n) _ invmx mulmx}.\nProof. by move=> m A uA /= B; rewrite -mulmxA mulmxV ?mulmx1. Qed.\n\nLemma mulmxKV : forall m, {in unitmx, @rev_right_loop 'M_(m, n) _ invmx mulmx}.\nProof. by move=> m A uA /= B; rewrite -mulmxA mulVmx ?mulmx1. Qed.\n\nLemma det_inv : forall A, \\det (invmx A) = (\\det A)^-1.\nProof.\nmove=> A; case uA: (A \\in unitmx); last by rewrite /invmx uA invr_out ?negbT.\nby apply: (mulrI uA); rewrite -det_mulmx mulmxV ?divrr ?det1.\nQed.\n\nLemma unitmx_inv : forall A, (invmx A \\in unitmx) = (A \\in unitmx).\nProof. by move=> A; rewrite !unitmxE det_inv unitr_inv. Qed.\n\nLemma trmx_inv : forall A : 'M_n, (invmx A)^T = invmx (A^T).\nProof.\nby move=> A; rewrite (fun_if trmx) trmx_scale trmx_adj -unitmx_tr -det_tr.\nQed.\n\nLemma invmxK : involutive invmx.\nProof.\nmove=> A; case uA : (A \\in unitmx); last by rewrite /invmx !uA.\nby apply: (can_inj (mulKVmx uA)); rewrite mulVmx // mulmxV ?unitmx_inv.\nQed.\n\nLemma mulmx1_unit : forall A B, A *m B = 1%:M -> A \\in unitmx /\\ B \\in unitmx.\nProof.\nby move=> A B AB1; apply/andP; rewrite -unitr_mul -det_mulmx AB1 det1 unitr1.\nQed.\n\nLemma intro_unitmx : forall A B, B *m A = 1%:M /\\ A *m B = 1%:M -> unitmx A.\nProof. by move=> A B [_]; case/mulmx1_unit. Qed.\n\nLemma invmx_out : {in predC unitmx, invmx =1 id}.\nProof. by move=> A; rewrite inE /= /invmx -if_neg => ->. Qed.\n\nEnd Defs.\n\nVariable n' : nat.\nLocal Notation n := n'.+1.\n\nDefinition matrix_unitRingMixin :=\n  UnitRingMixin (@mulVmx n) (@mulmxV n) (@intro_unitmx n) (@invmx_out n).\nCanonical Structure matrix_unitRing :=\n  Eval hnf in UnitRingType 'M[R]_n matrix_unitRingMixin.\n\n(* Lemmas requiring that the coefficients are in a unit ring *)\n\nLemma detV : forall A : 'M_n, \\det A^-1 = (\\det A)^-1.\nProof. exact: det_inv. Qed.\n\nLemma unitr_trmx : forall A : 'M_n, GRing.unit A^T = GRing.unit A.\nProof. exact: unitmx_tr. Qed.\n\nLemma trmxV : forall A : 'M_n, A^-1^T = (A^T)^-1.\nProof. exact: trmx_inv. Qed.\n\nLemma perm_mxV : forall s : 'S_n, perm_mx s^-1 = (perm_mx s)^-1.\nProof.\nmove=> s; rewrite -[_^-1]mul1r; apply: (canRL (mulmxK (unitmx_perm s))).\nby rewrite -perm_mxM mulVg perm_mx1.\nQed.\n\nLemma is_perm_mxV : forall A : 'M_n, is_perm_mx A^-1 = is_perm_mx A.\nProof.\nmove=> A; apply/is_perm_mxP/is_perm_mxP=> [] [s defA]; exists s^-1%g.\n  by rewrite -(invrK A) defA perm_mxV.\nby rewrite defA perm_mxV.\nQed.\n\nEnd MatrixInv.\n\nPrenex Implicits unitmx invmx.\n\n(* Finite inversible matrices and the general linear group. *)\nSection FinUnitMatrix.\n\nVariables (n : nat) (R : finComUnitRingType).\n\nCanonical Structure matrix_finUnitRingType n' :=\n  Eval hnf in [finUnitRingType of 'M[R]_n'.+1].\n\nDefinition GLtype of phant R := {unit 'M[R]_n.-1.+1}.\n\nCoercion GLval ph (u : GLtype ph) : 'M[R]_n.-1.+1 :=\n  let: FinRing.Unit A _ := u in A.\n\nEnd FinUnitMatrix.\n\nBind Scope group_scope with GLtype.\nArguments Scope GLval [nat_scope _ _ group_scope].\nPrenex Implicits GLval.\n\nNotation \"{ ''GL_' n [ R ] }\" := (GLtype n (Phant R))\n  (at level 0, n at level 2, format \"{ ''GL_' n [ R ] }\") : type_scope.\nNotation \"{ ''GL_' n ( p ) }\" := {'GL_n['F_p]}\n  (at level 0, n at level 2, p at level 10,\n    format \"{ ''GL_' n ( p ) }\") : type_scope.\n\nSection GL_unit.\n\nVariables (n : nat) (R : finComUnitRingType).\n\nCanonical Structure GL_subType := [subType for @GLval n _ (Phant R)].\nDefinition GL_eqMixin := Eval hnf in [eqMixin of {'GL_n[R]} by <:].\nCanonical Structure GL_eqType := Eval hnf in EqType {'GL_n[R]} GL_eqMixin.\nCanonical Structure GL_choiceType := Eval hnf in [choiceType of {'GL_n[R]}].\nCanonical Structure GL_countType := Eval hnf in [countType of {'GL_n[R]}].\nCanonical Structure GL_subCountType :=\n  Eval hnf in [subCountType of {'GL_n[R]}].\nCanonical Structure GL_finType := Eval hnf in [finType of {'GL_n[R]}].\nCanonical Structure GL_subFinType := Eval hnf in [subFinType of {'GL_n[R]}].\nCanonical Structure GL_baseFinGroupType :=\n  Eval hnf in [baseFinGroupType of {'GL_n[R]}].\nCanonical Structure GL_finGroupType :=\n  Eval hnf in [finGroupType of {'GL_n[R]}].\nDefinition GLgroup of phant R := [set: {'GL_n[R]}].\nCanonical Structure GLgroup_group ph := Eval hnf in [group of GLgroup ph].\n\nImplicit Types u v : {'GL_n[R]}.\n\nLemma GL_1E : GLval 1 = 1. Proof. by []. Qed.\nLemma GL_VE : forall u, GLval u^-1 = (GLval u)^-1. Proof. by []. Qed.\nLemma GL_VxE : forall u, GLval u^-1 = invmx u. Proof. by []. Qed.\nLemma GL_ME : forall u v, GLval (u * v) = GLval u * GLval v. Proof. by []. Qed.\nLemma GL_MxE : forall u v, GLval (u * v) = u *m v. Proof. by []. Qed.\nLemma GL_unit : forall u, GRing.unit (GLval u). Proof. exact: valP. Qed.\nLemma GL_unitmx : forall u, val u \\in unitmx. Proof. exact: GL_unit. Qed.\n\nLemma GL_det : forall u, \\det u != 0.\nProof.\nmove=> u; apply: contraL (GL_unitmx u); rewrite unitmxE; move/eqP->.\nby rewrite unitr0.\nQed.\n\nEnd GL_unit.\n\nNotation \"''GL_' n [ R ]\" := (GLgroup n (Phant R))\n  (at level 8, n at level 2, format \"''GL_' n [ R ]\") : group_scope.\nNotation \"''GL_' n ( p )\" := 'GL_n['F_p]\n  (at level 8, n at level 2, p at level 10,\n   format \"''GL_' n ( p )\") : group_scope.\nNotation \"''GL_' n [ R ]\" := (GLgroup_group n (Phant R)) : subgroup_scope.\nNotation \"''GL_' n ( p )\" := (GLgroup_group n (Phant 'F_p)) : subgroup_scope.\n\n(*****************************************************************************)\n(****************************** LUP decomposion ******************************)\n(*****************************************************************************)\n\nSection CormenLUP.\n\nVariable F : fieldType.\n\n(* Decomposition of the matrix A to P A = L U with *)\n(*   - P a permutation matrix                      *)\n(*   - L a unipotent lower triangular matrix       *)\n(*   - U an upper triangular matrix                *)\n\nFixpoint cormen_lup {n} :=\n  match n return let M := 'M[F]_n.+1 in M -> M * M * M with\n  | 0 => fun A => (1, 1, A)\n  | _.+1 => fun A =>\n    let k := odflt 0 (pick [pred k | A k 0 != 0]) in\n    let A1 : 'M_(1 + _) := xrow 0 k A in\n    let P1 : 'M_(1 + _) := tperm_mx 0 k in\n    let Schur := ((A k 0)^-1 *m: dlsubmx A1) *m ursubmx A1 in\n    let: (P2, L2, U2) := cormen_lup (drsubmx A1 - Schur) in\n    let P := block_mx 1 0 0 P2 *m P1 in\n    let L := block_mx 1 0 ((A k 0)^-1 *m: (P2 *m dlsubmx A1)) L2 in\n    let U := block_mx (ulsubmx A1) (ursubmx A1) 0 U2 in\n    (P, L, U)\n  end.\n\nLemma cormen_lup_perm : forall n (A : 'M_n.+1), is_perm_mx (cormen_lup A).1.1.\nProof.\nelim=> [| n IHn] A /=; first exact: is_perm_mx1.\nset A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/=.\nrewrite (is_perm_mxMr _ (perm_mx_is_perm _ _)).\ncase/is_perm_mxP => s ->; exact: lift0_mx_is_perm.\nQed.\n\nLemma cormen_lup_correct : forall n (A : 'M_n.+1),\n  let: (P, L, U) := cormen_lup A in P * A  = L * U.\nProof.\nelim=> [|n IHn] A /=; first by rewrite !mul1r.\nset k := odflt _ _; set A1 : 'M_(1 + _) := xrow _ _ _.\nset A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P' L' U']] /= IHn.\nrewrite -mulrA -!mulmxE -xrowE -/A1 /= -[n.+2]/(1 + n.+1)%N -{1}(submxK A1).\nrewrite !mulmx_block !mul0mx !mulmx0 !add0r !addr0 !mul1mx -{L' U'}[L' *m _]IHn.\nrewrite -scalemxAl !scalemxAr -!mulmxA addrC -mulr_addr {A'}subrK.\ncongr (block_mx _ _ (_ *m _) _).\nrewrite [_ *m: _]mx11_scalar !mxE lshift0 tpermL {}/A1 {}/k.\ncase: pickP => /= [k nzAk0 | no_k]; first by rewrite mulVf ?mulmx1.\nrewrite (_ : dlsubmx _ = 0) ?mul0mx //; apply/colP=> i.\nby rewrite !mxE lshift0 (elimNf eqP (no_k _)).\nQed.\n\nLemma cormen_lup_detL : forall n (A : 'M_n.+1), \\det (cormen_lup A).1.2 = 1.\nProof.\nelim=> [|n IHn] A /=; first by rewrite det1.\nset A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/= detL.\nby rewrite (@det_lblock _ 1) det1 mul1r.\nQed.\n\nLemma cormen_lup_lower : forall n A (i j : 'I_n.+1),\n  i <= j -> (cormen_lup A).1.2 i j = (i == j)%:R.\nProof.\nelim=> [|n IHn] A /= i j; first by rewrite [i]ord1 [j]ord1 mxE.\nset A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/= Ll.\nrewrite !mxE split1; case: unliftP => [i'|] -> /=; rewrite !mxE split1.\n  by case: unliftP => [j'|] -> //; exact: Ll.\nby case: unliftP => [j'|] ->; rewrite /= mxE.\nQed.\n\nLemma cormen_lup_upper : forall n A (i j : 'I_n.+1),\n  j < i -> (cormen_lup A).2 i j = 0 :> F.\nProof.\nelim=> [|n IHn] A /= i j; first by rewrite [i]ord1.\nset A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/= Uu.\nrewrite !mxE split1; case: unliftP => [i'|] -> //=; rewrite !mxE split1.\nby case: unliftP => [j'|] ->; [exact: Uu | rewrite /= mxE].\nQed.\n\nEnd CormenLUP.\n\n(*****************************************************************************)\n(******************** Rank and row-space theory ******************************)\n(*****************************************************************************)\n\nSection RowSpaceTheory.\n\nVariable F : fieldType.\n\n(* Decomposition with double pivoting; computes the rank, row and column  *)\n(* images, kernels, and complements of a matrix.                          *)\n\nFixpoint emxrank {m n} : 'M[F]_(m, n) -> 'M_m * 'M_n * nat :=\n  match m, n return 'M_(m, n) -> 'M_m * 'M_n * nat with\n  | _.+1, _.+1 => fun A : 'M_(1 + _, 1 + _) =>\n    if pick (fun k => A k.1 k.2 != 0) is Some (i, j) then\n      let a := A i j in let A1 := xrow i 0 (xcol j 0 A) in\n      let u := ursubmx A1 in let v :=  a^-1 *m: dlsubmx A1 in\n      let: (L, U, r) := emxrank (drsubmx A1 - v *m u) in\n      (xrow i 0 (block_mx 1 0 v L), xcol j 0 (block_mx a%:M u 0 U), r.+1)\n    else (1%:M, 1%:M, 0%N)\n  | _, _ => fun _ => (1%:M, 1%:M, 0%N)\n  end.\n\nSection Defs.\n\nVariables (m n : nat) (A : 'M[F]_(m, n)).\n\nDefinition col_ebase := (emxrank A).1.1.\nDefinition row_ebase := (emxrank A).1.2.\nDefinition mxrank := (emxrank A).2.\n\nDefinition row_free := mxrank == m.\nDefinition row_full := mxrank == n.\n\nDefinition row_base : 'M_(mxrank, n) := pid_mx mxrank *m row_ebase.\nDefinition col_base : 'M_(m, mxrank) := col_ebase *m pid_mx mxrank.\n\nDefinition complmx : 'M_n := copid_mx mxrank *m row_ebase.\nDefinition kermx : 'M_m := copid_mx mxrank *m invmx col_ebase.\nDefinition cokermx : 'M_n := invmx row_ebase *m copid_mx mxrank.\n\nDefinition pinvmx : 'M_(n, m) :=\n  invmx row_ebase *m pid_mx mxrank *m invmx col_ebase.\n\nEnd Defs.\n\nArguments Scope mxrank [nat_scope nat_scope matrix_set_scope].\nLocal Notation \"\\rank A\" := (mxrank A) : nat_scope.\nArguments Scope complmx [nat_scope nat_scope matrix_set_scope].\nLocal Notation \"A ^C\" := (complmx A) : matrix_set_scope.\n\nLet mxopE : forall k opty (op : forall m : nat, opty m) m1,\n  (let f := let: tt := k in fun m => op m in f) m1 = op m1.\nProof. by case. Qed.\n\nDefinition subsetmx_def m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  A *m cokermx B == 0.\nFact subsetmx_key : unit. Proof. by []. Qed.\nDefinition subsetmx := let: tt := subsetmx_key in subsetmx_def.\nArguments Scope subsetmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits subsetmx.\nLocal Notation \"A <= B\" := (subsetmx A B) : matrix_set_scope.\nLocal Notation \"A <= B <= C\" := ((A <= B) && (B <= C))%MS : matrix_set_scope.\nLocal Notation \"A == B\" := (A <= B <= A)%MS : matrix_set_scope.\n\nDefinition eqmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  prod (\\rank A = \\rank B)\n       (forall m3 (C : 'M_(m3, n)),\n            ((A <= C) = (B <= C)) * ((C <= A) = (C <= B)))%MS.\nArguments Scope eqmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nLocal Notation \"A :=: B\" := (eqmx A B) : matrix_set_scope.\n\n(* The choice witness for genmx is row_base padded with null rows. *)\nDefinition genmx_witness m n (A : 'M_(m, n)) : 'M_n :=\n  pid_mx (\\rank A) *m row_ebase A.\nDefinition genmx_def m n (A : 'M_(m, n)) :=\n  choose (fun B => B == A)%MS (genmx_witness A).\nFact genmx_key : unit. Proof. by []. Qed.\nDefinition genmx := let: tt := genmx_key in genmx_def.\nLocal Notation \"<< A >>\" := (genmx A) : matrix_set_scope.\n\n(* The setwise sum is tweaked so that 0 is a strict identity element for      *)\n(* square matrices, because this lets us use the bigops component. As a       *)\n(* result, setwise sum is not quite strictly extensional.                     *)\nLet sumsmx_nop m n (A : 'M_(m, n)) := conform_mx <<A>>%MS A.\nDefinition sumsmx_def m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  if A == 0 then sumsmx_nop B else if B == 0 then sumsmx_nop A else\n  <<col_mx A B>>%MS.\nFact sumsmx_key : unit. Proof. by []. Qed.\nDefinition sumsmx := let: tt := sumsmx_key in sumsmx_def.\nArguments Scope sumsmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits sumsmx.\nLocal Notation \"A + B\" := (sumsmx A B) : matrix_set_scope.\nLocal Notation \"\\sum_ ( i | P ) B\" := (\\big[sumsmx/0]_(i | P) B%MS)\n  : matrix_set_scope.\n\n(* The set intersection is similarly biased so that the identity matrix is a  *)\n(* strict identity. This is somewhat more delicate than for the sum, because  *)\n(* the test for the identity is non-extensional. This forces us to actually   *)\n(* bias the choice operator so that it does not accidentally map an           *)\n(* intersection of non-identity matrices to 1%:M; this would spoil            *)\n(* associativity: if B :&: C = 1%:M but B and C are not identity, then for a  *)\n(* square matrix A we have A :&: (B :&: C) = A != (A :&: B) :&: C in general. *)\n(* To complicate matters there may not be a square non-singular matrix        *)\n(* different than 1%:M, since we could be dealing with 'M['F_2]_1. We         *)\n(* sidestep the issue by making all non-square row-full matrices identities,  *)\n(* and choosing a normal representative that preserves the capmx_id property. *)\n(* Thus A :&: B = 1%:M iff A and B are both identities, and this suffices for *)\n(* showing that associativity is strict.                                      *)\nLet capmx_id m n (A : 'M_(m, n)) :=\n  if m == n then A == pid_mx n else row_full A.\nLet capmx_equivb m n (A : 'M_(m, n)) (B : 'M_n) :=\n  (B == A)%MS && (capmx_id B == capmx_id A).\nLet capmx_equiv m n (A : 'M_(m, n)) (B : 'M_n) :=\n  prod (B :=: A)%MS (capmx_id B = capmx_id A).\nLet capmx_witness m n (A : 'M_(m, n)) :=\n  if row_full A then conform_mx 1%:M A else <<A>>%MS.\nLet capmx_norm m n (A : 'M_(m, n)) :=\n  choose (capmx_equivb A) (capmx_witness A).\nLet capmx_nop m n (A : 'M_(m, n)) := conform_mx (capmx_norm A) A.\nDefinition capmx_gen m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  lsubmx (kermx (col_mx A B)) *m A.\nDefinition capmx_def m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  if capmx_id A then capmx_nop B else\n  if capmx_id B then capmx_nop A else\n  if row_full B then capmx_norm A else capmx_norm (capmx_gen A B).\nFact capmx_key : unit. Proof. by []. Qed.\nDefinition capmx := let: tt := capmx_key in capmx_def.\nArguments Scope capmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits capmx.\nLocal Notation \"A :&: B\" := (capmx A B) : matrix_set_scope.\nLocal Notation \"\\bigcap_ ( i | P ) B\" := (\\big[capmx/1%:M]_(i | P) B)\n  : matrix_set_scope.\n\nDefinition diffmx_def m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  <<capmx_gen A (capmx_gen A B)^C>>%MS.\nFact diffmx_key : unit. Proof. by []. Qed.\nDefinition diffmx := let: tt := diffmx_key in diffmx_def.\nArguments Scope diffmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits diffmx.\nLocal Notation \"A :\\: B\" := (diffmx A B) : matrix_set_scope.\n\nLemma rank_leq_row : forall m n (A : 'M_(m, n)), \\rank A <= m.\nProof.\nrewrite /mxrank; elim=> [|m IHm] [|n] //= A; case: pickP=> [[i j] _|] //=.\nby move: (_ - _) => B; case: emxrank (IHm _ B) => [[L U] r] /=.\nQed.\n\nLemma row_leq_rank : forall m n (A : 'M_(m, n)), (m <= \\rank A) = row_free A.\nProof. by move=> m n A; rewrite /row_free eqn_leq rank_leq_row. Qed.\n\nLemma rank_leq_col : forall m n (A : 'M_(m, n)), \\rank A <= n.\nProof.\nrewrite /mxrank; elim=> [|m IHm] [|n] //= A; case: pickP=> [[i j] _|] //=.\nby move: (_ - _) => B; case: emxrank (IHm _ B) => [[L U] r] /=.\nQed.\n\nLemma col_leq_rank : forall m n (A : 'M_(m, n)), (n <= \\rank A) = row_full A.\nProof. by move=> m n A; rewrite /row_full eqn_leq rank_leq_col. Qed.\n\nLet unitmx1F := @unitmx1 F.\nLemma row_ebase_unit : forall m n (A : 'M_(m, n)), row_ebase A \\in unitmx.\nProof.\nrewrite /row_ebase; elim=> [|m IHm] [|n] //= A.\ncase: pickP => [[i j] /= nzAij | //=]; move: (_ - _) => B.\ncase: emxrank (IHm _ B) => [[L U] r] /= uU.\nrewrite unitmxE xcolE det_mulmx (@det_ublock _ 1) det_scalar1 !unitr_mul.\nby rewrite unitfE nzAij -!unitmxE uU  unitmx_perm.\nQed.\n\nLemma col_ebase_unit : forall m n (A : 'M_(m, n)), col_ebase A \\in unitmx.\nProof.\nrewrite /col_ebase; elim=> [|m IHm] [|n] //= A; case: pickP => [[i j] _|] //=.\nmove: (_ - _) => B; case: emxrank (IHm _ B) => [[L U] r] /= uL.\nrewrite unitmxE xrowE det_mulmx (@det_lblock _ 1) det1 mul1r unitr_mul.\nby rewrite -unitmxE unitmx_perm.\nQed.\nHint Resolve rank_leq_row rank_leq_col row_ebase_unit col_ebase_unit.\n\nLemma mulmx_ebase : forall m n (A : 'M_(m, n)),\n  col_ebase A *m pid_mx (\\rank A) *m row_ebase A = A.\nProof.\nrewrite /col_ebase /row_ebase /mxrank.\nelim=> [n A | m IHm]; first by rewrite [A]flatmx0 [_ *m _]flatmx0.\ncase=> [A | n]; first by rewrite [_ *m _]thinmx0 [A]thinmx0.\nrewrite -(add1n m) -?(add1n n) => A /=.\ncase: pickP => [[i0 j0] | A0] /=; last first.\n  apply/matrixP=> i j; rewrite pid_mx_0 mulmx0 mul0mx mxE.\n  by move/eqP: (A0 (i, j)).\nset a := A i0 j0 => nz_a; set A1 := xrow _ _ _.\nset u := ursubmx _; set v := _ *m: _; set B : 'M_(m, n) := _ -  _.\nmove: (rank_leq_col B) (rank_leq_row B) {IHm}(IHm n B); rewrite /mxrank.\ncase: (emxrank B) => [[L U] r] /= r_m r_n defB.\nhave ->: pid_mx (1 + r) = block_mx 1 0 0 (pid_mx r) :> 'M[F]_(1 + m, 1 + n).\n  rewrite -(subnKC r_m) -(subnKC r_n) pid_mx_block -col_mx0 -row_mx0.\n  by rewrite block_mxA castmx_id col_mx0 row_mx0 -scalar_mx_block -pid_mx_block.\nrewrite xcolE xrowE  mulmxA -xcolE -!mulmxA.\nrewrite !(addr0, add0r, mulmx0, mul0mx, mulmx_block, mul1mx) mulmxA defB.\nrewrite addrC subrK mul_mx_scalar scalemxA divff // scale1mx.\nhave ->: a%:M = ulsubmx A1 by rewrite [_ A1]mx11_scalar !mxE !lshift0 !tpermR.\nrewrite submxK /A1 xrowE !xcolE -!mulmxA mulmxA -!perm_mxM !tperm2 !perm_mx1.\nby rewrite mulmx1 mul1mx.\nQed.\n\nLemma mulmx_base : forall m n (A : 'M_(m, n)), col_base A *m row_base A = A.\nProof.\nby move=> m n A; rewrite mulmxA -[col_base A *m _]mulmxA pid_mx_id ?mulmx_ebase.\nQed.\n\nLemma mulmx1_min_rank : forall r m n (A : 'M_(m, n)) M N,\n  M *m A *m N = 1%:M :> 'M_r -> r <= \\rank A.\nProof.\nmove=> r m n A M N.\nby rewrite -{1}(mulmx_base A) mulmxA -mulmxA; move/mulmx1_min.\nQed.\nImplicit Arguments mulmx1_min_rank [r m n A].\n\nLemma mulmx_max_rank : forall r m n (M : 'M_(m, r)) (N : 'M_(r, n)),\n  \\rank (M *m N) <= r.\nProof.\nmove=> r m n M N; set MN := M *m N; set rMN := \\rank _.\npose L : 'M_(rMN, m) := pid_mx rMN *m invmx (col_ebase MN).\npose U : 'M_(n, rMN) := invmx (row_ebase MN) *m pid_mx rMN.\nsuffices: L *m M *m (N *m U) = 1%:M by exact: mulmx1_min.\nrewrite mulmxA -(mulmxA L) -[M *m N]mulmx_ebase -/MN.\nby rewrite !mulmxA mulmxKV // mulmxK // !pid_mx_id /rMN ?pid_mx_1.\nQed.\nImplicit Arguments mulmx_max_rank [r m n].\n\nLemma mxrank_tr : forall m n (A : 'M_(m, n)), \\rank A^T = \\rank A.\nProof.\nmove=> m n A; apply/eqP; rewrite eqn_leq -{3}[A]trmxK.\nby rewrite -{1}(mulmx_base A) -{1}(mulmx_base A^T) !trmx_mul !mulmx_max_rank.\nQed.\n\nLemma mxrank_add : forall m n (A B : 'M_(m, n)),\n  \\rank (A + B)%R <= \\rank A + \\rank B.\nProof.\nmove=> m n A B; rewrite -{1}(mulmx_base A) -{1}(mulmx_base B) -mul_row_col.\nexact: mulmx_max_rank.\nQed.\n\nLemma mxrankM_maxl : forall m n p (A : 'M_(m, n)) (B : 'M_(n, p)),\n  \\rank (A *m B) <= \\rank A.\nProof.\nby move=> m n p A B; rewrite -{1}(mulmx_base A) -mulmxA mulmx_max_rank.\nQed.\n\nLemma mxrankM_maxr : forall m n p (A : 'M_(m, n)) (B : 'M_(n, p)),\n  \\rank (A *m B) <= \\rank B.\nProof.\nby move=> m n p A B; rewrite -mxrank_tr -(mxrank_tr B) trmx_mul mxrankM_maxl.\nQed.\n\nLemma mxrank_scale : forall m n a (A : 'M_(m, n)),\n  \\rank (a *m: A) <= \\rank A.\nProof. by move=> m n a A; rewrite -mul_scalar_mx mxrankM_maxr. Qed.\n\nLemma mxrank_scale_nz : forall m n a (A : 'M_(m, n)),\n  a != 0 -> \\rank (a *m: A) = \\rank A.\nProof.\nmove=> m n a A nza; apply/eqP; rewrite eqn_leq -{3}[A]scale1mx -(mulVf nza).\nby rewrite -scalemxA !mxrank_scale.\nQed.\n\nLemma mxrank_opp : forall m n (A : 'M_(m, n)), \\rank (- A) = \\rank A.\nProof.\nby move=> m n A; rewrite -scaleN1mx mxrank_scale_nz // oppr_eq0 oner_eq0.\nQed.\n\nLemma mxrank0 : forall m n, \\rank (0 : 'M_(m, n)) = 0%N.\nProof.\nby move=> m n; apply/eqP; rewrite -leqn0 -(@mulmx0 _ m 0 n 0) mulmx_max_rank.\nQed.\n\nLemma mxrank_eq0 : forall m n (A : 'M_(m, n)), (\\rank A == 0%N) = (A == 0).\nProof.\nmove=> m n A; apply/eqP/eqP=> [rA0 | ->{A}]; last exact: mxrank0.\nmove: (col_base A) (row_base A) (mulmx_base A); rewrite rA0 => Ac Ar <-.\nby rewrite [Ac]thinmx0 mul0mx.\nQed.\n\nLemma mulmx_coker : forall m n (A : 'M_(m, n)), A *m cokermx A = 0.\nProof.\nmove=> m n A; rewrite -{1}[A]mulmx_ebase -!mulmxA mulKVmx //.\nby rewrite mul_pid_mx_copid ?mulmx0.\nQed.\n\nLemma subsetmxE : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A <= B)%MS = (A *m cokermx B == 0).\nProof. by move=> m1; rewrite mxopE. Qed.\n\nLemma mulmxKpV : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A <= B)%MS -> A *m pinvmx B *m B = A.\nProof.\nmove=> m n p A B; rewrite subsetmxE !mulmxA mulmx_subr mulmx1 subr_eq0.\nmove/eqP=> defA; rewrite -{4}[B]mulmx_ebase -!mulmxA mulKmx //.\nby rewrite (mulmxA (pid_mx _)) pid_mx_id // !mulmxA -{}defA mulmxKV.\nQed.\n\nLemma subsetmxP : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  reflect (exists D, A = D *m B) (A <= B)%MS.\nProof.\nmove=> m1 m2 n A B; apply: (iffP idP) => [|[D ->]].\n  by move/mulmxKpV; exists (A *m pinvmx B).\nby rewrite subsetmxE -mulmxA mulmx_coker mulmx0.\nQed.\nImplicit Arguments subsetmxP [m1 m2 n A B].\n\nLemma subsetmx_refl : forall m n (A : 'M_(m, n)), (A <= A)%MS.\nProof. by move=> m n A; rewrite subsetmxE mulmx_coker. Qed.\nHint Resolve subsetmx_refl.\n\nLemma subsetmxMl : forall m n p (D : 'M_(m, n)) (A : 'M_(n, p)),\n  (D *m A <= A)%MS.\nProof. by move=> m n p D A; rewrite subsetmxE -mulmxA mulmx_coker mulmx0. Qed.\n\nLemma subsetmxMr : forall m1 m2 n p,\n                   forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)),\n  (A <= B)%MS -> (A *m C <= B *m C)%MS.\nProof.\nby move=> m1 m2 n p A B C; case/subsetmxP=> D ->; rewrite -mulmxA subsetmxMl.\nQed.\n\nLemma subsetmxMtrans : forall m n1 n2 p (C : 'M_(m, n1)) A (B : 'M_(n2, p)),\n  (A <= B -> C *m A <= B)%MS.\nProof.\nby move=> m n1 n2 p C A B; case/subsetmxP=> D ->; rewrite mulmxA subsetmxMl.\nQed.\n\nLemma subsetmx_trans : forall m1 m2 m3 n,\n    forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)),\n  (A <= B -> B <= C -> A <= C)%MS.\nProof.\nmove=> m1 m2 m3 n A B C; case/subsetmxP=> D ->{A}; exact: subsetmxMtrans.\nQed.\n\nLemma subset0mx : forall m1 m2 n (A : 'M_(m2, n)),\n  ((0 : 'M_(m1, n)) <= A)%MS.\nProof. by move=> m1 m2 n A; rewrite subsetmxE mul0mx. Qed.\n\nLemma subsetmx0null : forall m1 m2 n (A : 'M[F]_(m1, n)),\n  (A <= (0 : 'M_(m2, n)))%MS -> A = 0.\nProof. by move=> m1 m2 n A; case/subsetmxP=> D; rewrite mulmx0. Qed.\n\nLemma subsetmx0 : forall m n (A : 'M_(m, n)), (A <= (0 : 'M_n))%MS = (A == 0).\nProof.\nmove=> m n A; apply/idP/eqP=> [|->]; [exact: subsetmx0null | exact: subset0mx].\nQed.\n\nLemma subsetmx_add : forall m1 m2 n,\n                  forall (A : 'M_(m1, n)) (B : 'M_(m1, n)) (C : 'M_(m2, n)),\n  (A <= C)%MS -> (B <= C)%MS -> ((A + B)%R <= C)%MS.\nProof.\nmove=> m1 m2 n A B C; case/subsetmxP=> A' ->; case/subsetmxP=> B' ->.\nby rewrite -mulmx_addl subsetmxMl.\nQed.\n\nLemma subsetmx_sum : forall m1 m2 n (B : 'M_(m2, n)),\n                     forall I r (P : pred I) (A_ : I -> 'M_(m1, n)),\n  (forall i, P i -> A_ i <= B)%MS -> ((\\sum_(i <- r | P i) A_ i)%R <= B)%MS.\nProof.\nmove=> m1 m2 n B; pose leB (A : 'M_(m1, n)) := (A <= B)%MS.\napply: (@big_prop _ leB) => [| A1 A2]; [exact: subset0mx | exact: subsetmx_add].\nQed.\n\nLemma subsetmx_scale : forall m1 m2 n a (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A <= B)%MS -> (a *m: A <= B)%MS.\nProof.\nby move=> m1 m2 n a A B; case/subsetmxP=> A' ->; rewrite scalemxAl subsetmxMl.\nQed.\n\nLemma row_sub : forall m n i (A : 'M_(m, n)), (row i A <= A)%MS.\nProof. by move=> m n i A; rewrite rowE subsetmxMl. Qed.\n\nLemma eq_row_sub : forall m n v (A : 'M_(m, n)) i, row i A = v -> (v <= A)%MS.\nProof. by move=> m n v A i <-; rewrite row_sub. Qed.\n\nLemma row_subP : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  reflect (forall i, row i A <= B)%MS (A <= B)%MS.\nProof.\nmove=> m1 m2 n A B; apply: (iffP idP) => [sAB i|sAB].\n  by apply: subsetmx_trans sAB; exact: row_sub.\nrewrite subsetmxE; apply/eqP; apply/row_matrixP=> i; apply/eqP.\nby rewrite row_mul row0 -subsetmxE.\nQed.\nImplicit Arguments row_subP [m1 m2 n A B].\n\nLemma row_subPn : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  reflect (exists i, ~~ (row i A <= B)%MS) (~~ (A <= B)%MS).\nProof.\nmove=> m1 m2 n A B; rewrite (sameP row_subP forallP) negb_forall.\nexact: existsP.\nQed.\n\nLemma sub_rVP : forall n (u v : 'rV_n),\n  reflect (exists a, u = a *m: v) (u <= v)%MS.\nProof.\nmove=> n u v; apply: (iffP subsetmxP) => [[w ->] | [a ->]].\n  by exists (w 0 0); rewrite -mul_scalar_mx -mx11_scalar.\nby exists a%:M; rewrite mul_scalar_mx.\nQed.\n\nLemma rowV0Pn : forall m n (A : 'M_(m, n)),\n  reflect (exists2 v : 'rV_n, v <= A & v != 0)%MS (A != 0).\nProof.\nmove=> m n A; rewrite -subsetmx0; apply: (iffP idP) => [| [v svA]]; last first.\n  by rewrite -subsetmx0; exact: contra (subsetmx_trans _).\nby case/row_subPn=> i; rewrite subsetmx0; exists (row i A); rewrite ?row_sub.\nQed.\n\nLemma rowV0P : forall m n (A : 'M_(m, n)),\n  reflect (forall v : 'rV_n, v <= A -> v = 0)%MS (A == 0).\nProof.\nmove=> m n A; rewrite -[A == 0]negbK; case: rowV0Pn => IH.\n  by right; case: IH => v svA nzv IH; case/eqP: nzv; exact: IH.\nby left=> v svA; apply/eqP; apply/idPn=> nzv; case: IH; exists v.\nQed.  \n\nLemma subsetmx_full : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  row_full B -> (A <= B)%MS.\nProof.\nmove=> m1 m2 n A B; rewrite subsetmxE /cokermx; move/eqnP->.\nby rewrite /copid_mx pid_mx_1 subrr !mulmx0.\nQed.\n\nLemma row_fullP : forall m n (A : 'M_(m, n)),\n  reflect (exists B, B *m A = 1%:M) (row_full A).\nProof.\nmove=> m n A; apply: (iffP idP) => [Afull | [B kA]].\n  by exists (1%:M *m pinvmx A); apply: mulmxKpV (subsetmx_full _ Afull).\nby rewrite [_ A]eqn_leq rank_leq_col (mulmx1_min_rank B 1%:M) ?mulmx1.\nQed.\nImplicit Arguments row_fullP [m n A].\n\nLemma row_freeP : forall m n (A : 'M_(m, n)),\n  reflect (exists B, A *m B = 1%:M) (row_free A).\nProof.\nmove=> m n A; rewrite /row_free -mxrank_tr.\napply: (iffP row_fullP) => [] [B kA];\n  by exists B^T; rewrite -trmx1 -kA trmx_mul ?trmxK.\nQed.\n\nLemma row_free_unit : forall n (A : 'M_n), row_free A = (A \\in unitmx).\nProof.\nmove=> n A; apply/row_fullP/idP=> [[A'] | uA]; first by case/mulmx1_unit.\nby exists (invmx A); rewrite mulVmx.\nQed.\n\nLemma row_full_unit : forall n (A : 'M_n), row_full A = (A \\in unitmx).\nProof. exact: row_free_unit. Qed.\n  \nLemma mxrank_unit : forall n (A : 'M_n), A \\in unitmx -> \\rank A = n.\nProof. by move=> n A; rewrite -row_full_unit; move/eqnP. Qed.\n\nLemma mxrank1 : forall n, \\rank (1%:M : 'M_n) = n.\nProof. move=> n; apply: mxrank_unit; exact: unitmx1. Qed.\n\nLemma mxrankS : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A <= B)%MS -> \\rank A <= \\rank B.\nProof. by move=> m1 m2 n A B; case/subsetmxP=> D ->; rewrite mxrankM_maxr. Qed.\n\nLemma subsetmx1 : forall m n (A : 'M[F]_(m, n)), (A <= 1%:M)%MS.\nProof. by move=> m n A; rewrite subsetmx_full // row_full_unit unitmx1. Qed.\n\nLemma subset1mx : forall m n (A : 'M[F]_(m, n)), (1%:M <= A)%MS = row_full A.\nProof.\nmove=> m n A; apply/idP/idP; last exact: subsetmx_full.\nby move/mxrankS; rewrite mxrank1 col_leq_rank.\nQed.\n\nLemma eqmxP : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  reflect (A :=: B)%MS (A == B)%MS.\nProof.\nmove=> m1 m2 n A B.\napply: (iffP andP) => [[sAB sBA] | eqAB]; last by rewrite !eqAB.\nsplit=> [|m3 C]; first by apply/eqP; rewrite eqn_leq !mxrankS.\nsplit; first by apply/idP/idP; exact: subsetmx_trans.\nby apply/idP/idP=> sC; exact: subsetmx_trans sC _.\nQed.\n\nLemma eqmx_refl : forall m1 n (A : 'M_(m1, n)), (A :=: A)%MS.\nProof. by []. Qed.\n\nLemma eqmx_sym : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A :=: B)%MS -> (B :=: A)%MS.\nProof. by move=> m1 m2 n A B eqAB; split=> [|m3 C]; rewrite !eqAB. Qed.\n\nLemma eqmx_trans : forall m1 m2 m3 n,\n                   forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)),\n  (A :=: B)%MS -> (B :=: C)%MS -> (A :=: C)%MS.\nProof.\nby move=> m1 m2 m3 n A B C eqAB eqBC; split=> [|m4 D]; rewrite !eqAB !eqBC.\nQed.\n\nLemma eqmx_rank : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A == B)%MS -> \\rank A = \\rank B.\nProof. by move=> m1 m2 n A B; move/eqmxP->. Qed.\n\nLemma eqmxMr : forall m1 m2 n p,\n               forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)),\n  (A :=: B)%MS -> (A *m C :=: B *m C)%MS.\nProof.\nby move=> m1 m2 n p A B C eqAB; apply/eqmxP; rewrite !subsetmxMr ?eqAB.\nQed.\n\nLemma eqmxMfull : forall m n p (A : 'M_(m, n)) (B : 'M_(n, p)),\n  row_full A -> (A *m B :=: B)%MS.\nProof.\nmove=> m n p A B; case/row_fullP=> A' A'A; apply/eqmxP; rewrite subsetmxMl /=.\nby apply/subsetmxP; exists A'; rewrite mulmxA A'A mul1mx.\nQed.\n\nLemma eqmx0 : forall m n, ((0 : 'M[F]_(m, n)) :=: (0 : 'M_n))%MS.\nProof. by move=> m n; apply/eqmxP; rewrite !subset0mx. Qed.\n\nLemma eqmx_scale : forall m n a (A : 'M_(m, n)), a != 0 -> (a *m: A :=: A)%MS.\nProof.\nmove=> m n a A nz_a; apply/eqmxP; rewrite subsetmx_scale //.\nby rewrite -{1}[A]scale1mx -(mulVf nz_a) -scalemxA subsetmx_scale.\nQed.\n\nLemma eqmx_opp : forall m n (A : 'M_(m, n)), (- A :=: A)%MS.\nProof.\nmove=> m n A; rewrite -scaleN1mx; apply: eqmx_scale => //.\nby rewrite oppr_eq0 oner_eq0.\nQed.\n\nLemma subsetmxMfree : forall m1 m2 n p,\n                     forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)),\n  row_free C -> (A *m C <= B *m C)%MS = (A <= B)%MS.\nProof.\nmove=> m1 m2 n p A B C; case/row_freeP=> C' C_C'_1.\napply/idP/idP=> sAB; last exact: subsetmxMr.\nby rewrite -[A]mulmx1 -[B]mulmx1 -C_C'_1 !mulmxA subsetmxMr.\nQed.\n\nLemma eqmxMfree : forall m1 m2 n p,\n               forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)),\n  row_free C -> (A *m C :=: B *m C)%MS -> (A :=: B)%MS.\nProof.\nmove=> m1 m2 n p A B C Cfree eqAB; apply/eqmxP; move/eqmxP: eqAB.\nby rewrite !subsetmxMfree.\nQed.\n\nLemma mxrankMfree : forall m n p (A : 'M_(m, n)) (B : 'M_(n, p)),\n  row_free B -> \\rank (A *m B) = \\rank A.\nProof.\nmove=> m n p A B Bfree.\nby rewrite -mxrank_tr trmx_mul eqmxMfull /row_full mxrank_tr.\nQed.\n\nLemma eq_row_base : forall m n (A : 'M_(m, n)), (row_base A :=: A)%MS.\nProof.\nmove=> m n A; apply/eqmxP; apply/andP; split; apply/subsetmxP.\n  exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\n  by rewrite -{8}[A]mulmx_ebase !mulmxA mulmxKV // pid_mx_id.\nexists (col_ebase A *m pid_mx (\\rank A)).\nby rewrite mulmxA -(mulmxA _ _ (pid_mx _)) pid_mx_id // mulmx_ebase.\nQed.\n\nLet genmx_witnessP : forall m n (A : 'M_(m, n)), (genmx_witness A == A)%MS.\nProof.\nmove=> m n A; apply/andP; split; apply/subsetmxP.\n  exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\n  by rewrite -{4}[A]mulmx_ebase !mulmxA mulmxKV // pid_mx_id.\nexists (col_ebase A *m pid_mx (\\rank A)).\nby rewrite mulmxA -(mulmxA _ _ (pid_mx _)) pid_mx_id // mulmx_ebase.\nQed.\n\nLemma genmxE : forall m n (A : 'M_(m, n)), (<<A>> :=: A)%MS.\nProof.\nmove=> m n A; rewrite mxopE; set eqA := fun _ => _; apply/eqmxP.\nby rewrite [_ && _](@chooseP _ eqA) //; exact: genmx_witnessP.\nQed.\n\nLemma gen_eqmx : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A :=: B -> <<A>> = <<B>>)%MS.\nProof.\nmove=> m1 m2 n A B eqAB; rewrite ![@genmx _]mxopE.\npose eqABr := (genmx_witnessP, eqAB).\nby apply: etrans (choose_id _ _) (eq_choose _ _) => [||C]; rewrite !eqABr.\nQed.\n\nLemma genmxP : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  reflect (<<A>> = <<B>>)%MS (<<A>> == <<B>>)%MS.\nProof.\nmove=> m1 m2 n A B; apply: (iffP idP) => [|->]; last exact/andP.\nby rewrite !genmxE; move/eqmxP; exact: gen_eqmx.\nQed.\n\nLemma genmx0 : forall m n, <<0 : 'M_(m, n)>>%MS = 0.\nProof. by move=> m n; apply/eqP; rewrite -subsetmx0 genmxE subset0mx. Qed.\n\nLemma genmx_id : forall m n (A : 'M_(m, n)), (<<<<A>>>> = <<A>>)%MS.\nProof. by move=> m n A; apply: gen_eqmx; exact: genmxE. Qed.\n\nLemma row_base_free : forall m n (A : 'M_(m, n)), row_free (row_base A).\nProof. by move=> m n A; apply/eqnP; rewrite eq_row_base. Qed.\n\nLemma mxrank_gen : forall m n (A : 'M_(m, n)), \\rank <<A>>%MS = \\rank A.\nProof. by move=> m n A; rewrite genmxE. Qed.\n\nLemma col_base_full : forall m n (A : 'M_(m, n)), row_full (col_base A).\nProof.\nmove=> m n A; apply/row_fullP.\nexists (pid_mx (\\rank A) *m invmx (col_ebase A)).\nby rewrite !mulmxA mulmxKV // pid_mx_id // pid_mx_1.\nQed.\nHint Resolve row_base_free col_base_full.\n\nLemma mxrank_leqif_sup : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A <= B)%MS -> \\rank A <= \\rank B ?= iff (B <= A)%MS.\nProof.\nmove=> m1 m2 n A B sAB; split; first by rewrite mxrankS.\napply/idP/idP=> [| sBA]; last by rewrite eqn_leq !mxrankS.\ncase/subsetmxP: sAB => D ->; rewrite -{-2}(mulmx_base B) mulmxA.\nrewrite mxrankMfree //; case/row_fullP=> E kE.\nby rewrite -{1}[row_base B]mul1mx -kE -(mulmxA E) (mulmxA _ E) subsetmxMl.\nQed.\n\nLemma mxrank_leqif_eq : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A <= B)%MS -> \\rank A <= \\rank B ?= iff (A == B)%MS.\nProof. by move=> m1 m2 n A B sAB; rewrite sAB; exact: mxrank_leqif_sup. Qed.\n\nLemma eqmx_cast : forall m1 m2 n (A : 'M_(m1, n)) e,\n  ((castmx e A : 'M_(m2, n)) :=: A)%MS.\nProof. by move=> m1 m2 n A [e]; case: m2 / e A => A e; rewrite castmx_id. Qed.\n\nLemma eqmx_conform : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (conform_mx A B :=: A \\/ conform_mx A B :=: B)%MS.\nProof.\nmove=> m1 m2 n A; case: (eqVneq m2 m1) => [-> | neqm12] B.\n  by right; rewrite conform_mx_id.\nby left; rewrite nonconform_mx ?neqm12.\nQed.\n\nLet eqmx_sum_nop : forall m n (A : 'M_(m, n)), (sumsmx_nop A :=: A)%MS.\nProof.\nmove=> m n A; case: (eqmx_conform <<A>>%MS A) => // eq_id_gen.\nexact: eqmx_trans (genmxE A).\nQed.\n\nSection SumsmxSub.\n\nVariable (m1 m2 n : nat) (A : 'M[F]_(m1, n)) (B : 'M[F]_(m2, n)).\n\nLemma col_mx_sub : forall m3 (C : 'M_(m3, n)),\n  (col_mx A B <= C)%MS = (A <= C)%MS && (B <= C)%MS.\nProof.\nmove=> m3 C; rewrite !subsetmxE mul_col_mx -col_mx0.\nby apply/eqP/andP; [case/eq_col_mx=> -> -> | case; do 2!move/eqP->].\nQed.\n\nLemma sumsmxE : (A + B :=: col_mx A B)%MS.\nProof.\nhave:= subsetmx_refl (col_mx A B); rewrite col_mx_sub; case/andP=> sAS sBS.\nrewrite mxopE; do 2?case: eqP => [AB0 | _]; last exact: genmxE.\n  by apply/eqmxP; rewrite !eqmx_sum_nop sBS col_mx_sub AB0 subset0mx /=.\nby apply/eqmxP; rewrite !eqmx_sum_nop sAS col_mx_sub AB0 subset0mx andbT /=.\nQed.\n\nLemma sumsmx_sub : forall m3 (C : 'M_(m3, n)),\n  (A + B <= C)%MS = (A <= C)%MS && (B <= C)%MS.\nProof. by move=> m3 C; rewrite sumsmxE col_mx_sub. Qed.\n\nLemma sumsmxSl : (A <= A + B)%MS.\nProof. by have:= subsetmx_refl (A + B)%MS; rewrite sumsmx_sub; case/andP. Qed.\n\nLemma sumsmxSr : (B <= A + B)%MS.\nProof. by have:= subsetmx_refl (A + B)%MS; rewrite sumsmx_sub; case/andP. Qed.\n\nEnd SumsmxSub.\n\nLemma sums0mx: forall m1 m2 n (B : 'M_(m2, n)),\n  ((0 : 'M_(m1, n)) + B :=: B)%MS.\nProof.\nby move=> *; apply/eqmxP; rewrite sumsmx_sub subset0mx sumsmxSr /= andbT.\nQed.\n\nLemma sumsmx0: forall m1 m2 n (A : 'M_(m1, n)),\n  (A + (0 : 'M_(m2, n)) :=: A)%MS.\nProof.\nby move=> *; apply/eqmxP; rewrite sumsmx_sub subset0mx sumsmxSl /= !andbT.\nQed.\n\nLet sumsmx_nop_eq0 : forall m n (A : 'M_(m, n)), (sumsmx_nop A == 0) = (A == 0).\nProof. by move=> m n A; rewrite -!subsetmx0 eqmx_sum_nop. Qed.\n\nLet sumsmx_nop0 : forall m n, sumsmx_nop (0 : 'M_(m, n)) = 0.\nProof. by move=> m n; apply/eqP; rewrite sumsmx_nop_eq0. Qed.\n\nLet sumsmx_nop_id : forall n (A : 'M_n), sumsmx_nop A = A.\nProof. by move=> n A; exact: conform_mx_id. Qed.\n\nLemma sumsmxC : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A + B = B + A)%MS.\nProof.\nmove=> m1 m2 n A B; have: (A + B == B + A)%MS.\n  by apply/andP; rewrite !sumsmx_sub andbC -sumsmx_sub andbC -sumsmx_sub.\nrewrite ![@sumsmx _]mxopE.\ncase A0: (A == 0); case B0: (B == 0) => //; last by move/genmxP.\nby rewrite (eqP A0) (eqP B0) !sumsmx_nop0.\nQed.\n\nLemma sums0mx_id : forall m1 n (B : 'M_n), ((0 : 'M_(m1, n)) + B)%MS = B.\nProof. by move=> m2 n B; rewrite mxopE eqxx sumsmx_nop_id. Qed.\n\nLemma sumsmx0_id : forall m2 n (A : 'M_n), (A + (0 : 'M_(m2, n)))%MS = A.\nProof. by move=> m2 n A; rewrite sumsmxC sums0mx_id. Qed.\n\nLemma sumsmxA : forall m1 m2 m3 n,\n                forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)),\n  (A + (B + C) = A + B + C)%MS.\nProof.\nmove=> m1 m2 m3 n A B C; have: (A + (B + C) :=: A + B + C)%MS.\n  by apply/eqmxP; apply/andP; rewrite !sumsmx_sub -andbA andbA -!sumsmx_sub.\nrewrite {1 3}[@sumsmx m1]mxopE [@sumsmx n]mxopE !sumsmx_nop_id -!subsetmx0.\nrewrite !sumsmx_sub ![@sumsmx _]mxopE -!subsetmx0; move/gen_eqmx.\nby do 3!case: (_ <= 0)%MS; rewrite //= !genmx_id.\nQed.\n\nCanonical Structure sumsmx_monoid n :=\n  Monoid.Law (@sumsmxA n n n n) (@sums0mx_id n n) (@sumsmx0_id n n).\nCanonical Structure sumsmx_comoid n := Monoid.ComLaw (@sumsmxC n n n).\n\nLemma sumsmxMr : forall m1 m2 n p,\n                forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)),\n  ((A + B)%MS *m C :=: A *m C + B *m C)%MS.\nProof.\nmove=> m1 m2 n p A B C; apply/eqmxP; rewrite !sumsmxE -!mul_col_mx.\nby rewrite !subsetmxMr ?sumsmxE.\nQed.\n\nLemma sumsmxS : forall m1 m2 m3 m4 n,\n    forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) (D : 'M_(m4, n)),\n  (A <= C -> B <= D -> A + B <= C + D)%MS.\nProof.\nmove=> m1 m2 m3 m4 n A B C D sAC sBD.\nby rewrite sumsmx_sub {1}sumsmxC !(subsetmx_trans _ (sumsmxSr _ _)).\nQed.\n\nLemma subsetmx_add_sums : forall m m1 m2 n,\n    forall (A : 'M_(m, n)) (B : 'M_(m, n)) (C : 'M_(m1, n)) (D : 'M_(m2, n)),\n  (A <= C -> B <= D -> (A + B)%R <= C + D)%MS.\nProof.\nmove=> m m1 m2 n A B C D sAC; move/(sumsmxS sAC); apply: subsetmx_trans.\nby rewrite subsetmx_add ?sumsmxSl ?sumsmxSr.\nQed.\n\nLemma sums_eqmx : forall m1 m2 m3 m4 n,\n    forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) (D : 'M_(m4, n)),\n  (A :=: C -> B :=: D -> A + B :=: C + D)%MS.\nProof.\nmove=> m1 m2 m3 m4 n A B C D eqAC eqBD.\nby apply/eqmxP; rewrite !sumsmxS ?eqAC ?eqBD.\nQed.\n\nLemma sub_sumsmxP : forall m1 m2 m3 n,\n                    forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)),\n  reflect (exists2 A', A - A' <= B & A' <= C)%MS (A <= B + C)%MS.\nProof.\nmove=> m1 m2 m3 n A B C; apply: (iffP idP) => [|[A' sAA'B sA'C]]; last first.\n  by rewrite -(subrK A' A) subsetmx_add_sums.\nrewrite sumsmxE; case/subsetmxP=> u ->; rewrite -[u]hsubmxK mul_row_col.\nby exists (rsubmx u *m C); rewrite ?addrK subsetmxMl.\nQed.\nImplicit Arguments sub_sumsmxP [m1 m2 m3 n A B C].\n\nVariable I : finType.\nImplicit Type P : pred I.\n\nLemma bigsumsmx_sup : forall i0 P m n (A : 'M_(m, n)) (B_ : I -> 'M_n),\n  P i0 -> (A <= B_ i0)%MS -> (A <= \\sum_(i | P i) B_ i)%MS.\nProof.\nmove=> i0 P m n A B_ Pi0 sAB; apply: subsetmx_trans sAB _.\nby rewrite (bigD1 i0) // sumsmxSl.\nQed.\nImplicit Arguments bigsumsmx_sup [P m n A B_].\n\nLemma bigsumsmx_subP : forall P m n (A_ : I -> 'M_n) (B : 'M_(m, n)),\n  reflect (forall i, P i -> A_ i <= B)%MS (\\sum_(i | P i) A_ i <= B)%MS.\nProof.\nmove=> P m n A_ B; apply: (iffP idP) => [sAB i Pi | sAB].\n  by apply: subsetmx_trans sAB; apply: bigsumsmx_sup Pi _.\nby apply big_prop => // [|A1 A2 sA1B]; rewrite ?subset0mx // sumsmx_sub sA1B.\nQed.\n\nLemma sub_bigsumsmxP : forall P m n (A : 'M_(m, n)) (B_ : I -> 'M_n),\n  reflect (exists C_, A = \\sum_(i | P i) C_ i *m B_ i)\n          (A <= \\sum_(i | P i) B_ i)%MS.\nProof.\nmove=> P m n A B_; elim: {P}_.+1 {-2}P A (ltnSn #|P|) => // b IHb P A.\ncase: (pickP P) => [i Pi | P0 _]; last first.\n  rewrite big_pred0 // subsetmx0.\n  apply: (iffP eqP) => [-> | [C_ ->]]; last by rewrite big_pred0.\n  by exists (fun _ => 0); rewrite big_pred0.\nrewrite (cardD1x Pi) (bigD1 i) //=; move/IHb=> {b IHb} /= IHi.\napply: (iffP sub_sumsmxP) => [[A'] | [C_]]; last first.\n  rewrite (bigD1 i) //=; set A' := \\sum_(<- _ | _) _ => ->.\n  by exists A'; [rewrite addrK subsetmxMl | apply/IHi; exists C_].\ncase/subsetmxP=> Ci defCi; case/IHi=> C_ defA' {IHi}.\nexists [eta C_ with i |-> Ci]; rewrite (bigD1 i) //= eqxx -defCi.\nrewrite addrAC -addrA defA' -sumr_sub big1 ?addr0 // => j /=; case/andP=> _.\nby case: eqP => // _ _; rewrite subrr.\nQed.\n\nLemma rank_pid_mx : forall m n r,\n  r <= m -> r <= n -> \\rank (pid_mx r : 'M_(m, n)) = r.\nProof.\nmove=> m n r; do 2!move/subnKC <-; rewrite pid_mx_block block_mxEv row_mx0.\nrewrite -sumsmxE sumsmx0 -mxrank_tr tr_row_mx trmx0 trmx1 -sumsmxE sumsmx0.\nexact: mxrank1.\nQed.\n\nLemma rank_copid_mx : forall n r,\n  r <= n -> \\rank (copid_mx r : 'M_n) = (n - r)%N.\nProof.\nmove=> n r; move/subnKC <-; rewrite /copid_mx pid_mx_block scalar_mx_block.\nrewrite opp_block_mx !oppr0 add_block_mx !addr0 subrr block_mxEv row_mx0.\nrewrite -sumsmxE sums0mx -mxrank_tr tr_row_mx trmx0 trmx1.\nby rewrite -sumsmxE sums0mx mxrank1 addKn.\nQed.\n\nLemma mxrank_compl : forall m n (A : 'M_(m, n)), \\rank A^C%MS = (n - \\rank A)%N.\nProof. by move=> m n A; rewrite mxrankMfree ?row_free_unit ?rank_copid_mx. Qed.\n\nLemma mxrank_ker : forall m n (A : 'M_(m, n)),\n  \\rank (kermx A) = (m - \\rank A)%N.\nProof.\nby move=> m n A; rewrite mxrankMfree ?row_free_unit ?unitmx_inv ?rank_copid_mx.\nQed.\n\nLemma mxrank_coker : forall m n (A : 'M_(m, n)),\n  \\rank (cokermx A) = (n - \\rank A)%N.\nProof.\nby move=> m n A; rewrite eqmxMfull ?row_full_unit ?unitmx_inv ?rank_copid_mx.\nQed.\n\nLemma mulmx_ker : forall m n (A : 'M_(m, n)), kermx A *m A = 0.\nProof.\nmove=> m n A; rewrite -{2}[A]mulmx_ebase !mulmxA mulmxKV //.\nby rewrite mul_copid_mx_pid ?mul0mx.\nQed.\n\nLemma mulmxKV_ker : forall m n p (A : 'M_(n, p)) (B : 'M_(m, n)),\n  B *m A = 0 -> B *m col_ebase A *m kermx A = B.\nProof.\nmove=> m n p A B; rewrite mulmxA mulmx_subr mulmx1 mulmx_subl mulmxK //.\nrewrite -{1}[A]mulmx_ebase !mulmxA; move/(canRL (mulmxK (row_ebase_unit A))).\nrewrite mul0mx // => BA0; apply: (canLR (addrK _)).\nby rewrite -(pid_mx_id _ _ n (rank_leq_col A)) mulmxA BA0 !mul0mx addr0.\nQed.\n\nLemma sub_kermxP : forall p m n (A : 'M_(m, n)) (B : 'M_(p, m)),\n  reflect (B *m A = 0) (B <= kermx A)%MS.\nProof.\nmove=> p m n A B; apply: (iffP subsetmxP) => [[D ->]|].\n  by rewrite -mulmxA mulmx_ker mulmx0.\nby move/mulmxKV_ker; exists (B *m col_ebase A).\nQed.\n\nLemma det0P : forall n (A : 'M_n),\n  reflect (exists2 v : 'rV[F]_n, v != 0 & v *m A = 0) (\\det A == 0).\nProof.\nmove=> n A; rewrite -[_ == _]negbK -unitfE -unitmxE.\napply: (iffP idP) => [| [v n0v vA0]]; last first.\n  by apply: contra n0v => uA; rewrite -(mulmxK uA v) vA0 mul0mx.\nrewrite -row_free_unit /row_free eqn_leq rank_leq_row -subn_eq0.\nrewrite -mxrank_ker mxrank_eq0 -subsetmx0; case/row_subPn=> i.\nby exists (row i (kermx A)); rewrite -?subsetmx0 // -row_mul mulmx_ker row0.\nQed.\n\nLemma mulmx0_rank_max : forall m n p (A : 'M_(m, n)) (B : 'M_(n, p)),\n  A *m B = 0 -> \\rank A + \\rank B <= n.\nProof.\nmove=> m n p A B AB0; rewrite -{3}(subnK (rank_leq_row B)) leq_add2r.\nrewrite -mxrank_ker mxrankS //; exact/sub_kermxP.\nQed.\n\nLemma mxrank_Frobenius : forall m n p q (A : 'M_(m, n)) B (C : 'M_(p, q)),\n  \\rank (A *m B) + \\rank (B *m C) <= \\rank B + \\rank (A *m B *m C).\nProof.\nmove=> m n p q A B C; rewrite -{2}(mulmx_base (A *m B)) -mulmxA.\nrewrite (eqmxMfull _ (col_base_full _)); set C2 := row_base _ *m C.\nrewrite -{1}(subnK (rank_leq_row C2)) -(mxrank_ker C2) addnAC leq_add2r. \nrewrite addnC -{1}(mulmx_base B) -mulmxA eqmxMfull //.\nset C1 := _ *m C; rewrite -{2}(subnKC (rank_leq_row C1)) leq_add2l -mxrank_ker.\nrewrite -(mxrankMfree _ (row_base_free (A *m B))).\nhave: (row_base (A *m B) <= row_base B)%MS by rewrite !eq_row_base subsetmxMl.\ncase/subsetmxP=> D defD; rewrite defD mulmxA mxrankMfree ?mxrankS //.\nby apply/sub_kermxP; rewrite -mulmxA (mulmxA D) -defD -/C2 mulmx_ker.\nQed.\n\nLemma mxrank_mul_min : forall m n p (A : 'M_(m, n)) (B : 'M_(n, p)),\n  \\rank A + \\rank B - n <= \\rank (A *m B).\nProof.\nmove=> m n p A B; have:= mxrank_Frobenius A 1%:M B.\nby rewrite mulmx1 mul1mx mxrank1 leq_sub_add.\nQed.\n\nLemma sumsmx_compl_full : forall m n (A : 'M_(m, n)), row_full (A + A^C)%MS.\nProof.\nmove=> m n A; rewrite /row_full sumsmxE; apply/row_fullP.\nexists (row_mx (pinvmx A) (cokermx A)); rewrite mul_row_col.\nrewrite -{2}[A]mulmx_ebase -!mulmxA mulKmx // -mulmx_addr !mulmxA.\nby rewrite pid_mx_id ?copid_mx_id // -mulmx_addl addrC subrK mul1mx mulVmx.\nQed.\n\nLemma sub_capmx_gen : forall m1 m2 m3 n,\n    forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)),\n  (A <= capmx_gen B C)%MS = (A <= B)%MS && (A <= C)%MS.\nProof.\nmove=> m1 m2 m3 n A B C; apply/idP/andP=> [sAI | []].\n  rewrite !(subsetmx_trans sAI) ?subsetmxMl // /capmx_gen.\n   have:= mulmx_ker (col_mx B C); set K := kermx _.\n   rewrite -{1}[K]hsubmxK mul_row_col; move/(canRL (addrK _))->.\n   by rewrite add0r -mulNmx subsetmxMl.\ncase/subsetmxP=> B' ->{A}; case/subsetmxP=> C' eqBC'.\nhave: subsetmx (row_mx B' (- C')) (kermx (col_mx B C)).\n  by apply/sub_kermxP; rewrite mul_row_col eqBC' mulNmx subrr.\ncase/subsetmxP=> D; rewrite -[kermx _]hsubmxK mul_mx_row.\nby case/eq_row_mx=> -> _; rewrite -mulmxA subsetmxMl.\nQed.\n\nLet capmx_id_eq1 : forall n (A : 'M_n), capmx_id A = (A == 1%:M).\nProof. by move=> A; rewrite /capmx_id eqxx pid_mx_1. Qed.\n\nLet capmx_witnessP : forall m n (A : 'M_(m, n)),\n  capmx_equivb A (capmx_witness A).\nProof.\nmove=> m n A; rewrite /capmx_equivb capmx_id_eq1 /capmx_id /capmx_witness.\nrewrite -subset1mx; case s1A: (1%:M <= A)%MS => /=; last first.\n  rewrite !genmxE subsetmx_refl /= -negb_add; apply: contra {s1A}(negbT s1A).\n  case: eqP => [<- _| _]; first by rewrite genmxE.\n  by case: eqP A => //= -> A; move/eqP->; rewrite pid_mx_1.\ncase: (m =P n) => [-> | ne_mn] in A s1A *.\n  by rewrite conform_mx_id subsetmx_refl pid_mx_1 eqxx.\nby rewrite nonconform_mx ?subsetmx1 ?s1A ?eqxx //; case: eqP.\nQed.\n\nLet capmx_normP: forall m n (A : 'M_(m, n)), capmx_equiv A (capmx_norm A).\nProof.\nmove=> m n A; case/andP: (chooseP (capmx_witnessP A)).\nby move/eqmxP=> defN; move/eqP.\nQed.\n\nLet capmx_norm_eq : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  capmx_id A = capmx_id B -> (A == B)%MS -> capmx_norm A = capmx_norm B.\nProof.\nmove=> m1 m2 n A B eqABid; move/eqmxP=> eqAB.\nhave{eqABid eqAB} eqAB: capmx_equivb A =1 capmx_equivb B.\n  by move=> C; rewrite /capmx_equivb eqABid !eqAB.\nrewrite {1}/capmx_norm (eq_choose eqAB).\nby apply: choose_id; first rewrite -eqAB; exact: capmx_witnessP.\nQed.\n\nLet capmx_nopP : forall m n (A : 'M_(m, n)), capmx_equiv A (capmx_nop A).\nProof.\nrewrite /capmx_nop => m n; case: (eqVneq m n) => [-> | ne_mn] A.\n  by rewrite conform_mx_id.\nrewrite nonconform_mx ?ne_mn //; exact: capmx_normP.\nQed.\n\nLet sub_capmx_id : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  capmx_id B -> (A <= B)%MS.\nProof.\nrewrite /capmx_id => m1 m2 n A B idB; apply: {A}subsetmx_trans (subsetmx1 A) _.\ncase: eqP B idB => [-> | _] B; first by move/eqP->; rewrite pid_mx_1.\nby rewrite subset1mx.\nQed.\n\nLet capmx_id_cap : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  capmx_id (A :&: B)%MS = capmx_id A && capmx_id B.\nProof.\nmove=> m1 m2 n A B; rewrite mxopE -subset1mx.\ncase idA: (capmx_id A); case idB: (capmx_id B); try by rewrite capmx_nopP.\ncase s1B: (_ <= B)%MS; first by rewrite capmx_normP.\napply/idP; move/(sub_capmx_id 1%:M).\nby rewrite capmx_normP sub_capmx_gen s1B andbF.\nQed.\n\nLet capmx_eq_norm : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  capmx_id A = capmx_id B -> (A :&: B)%MS = capmx_norm (A :&: B)%MS.\nProof.\nmove=> m1 m2 n A B eqABid; rewrite mxopE -subset1mx {}eqABid.\nhave norm_id: forall m (C : 'M_(m, n)) (N := capmx_norm C), capmx_norm N = N.\n  by move=> m C; apply: capmx_norm_eq; rewrite ?capmx_normP ?andbb.\ncase idB: (capmx_id B); last by case: ifP; rewrite norm_id.\nrewrite /capmx_nop; case: (eqVneq m2 n) => [-> | neqm2n] in B idB *.\n  have idN := idB; rewrite -{1}capmx_normP !capmx_id_eq1 in idN idB.\n  by rewrite conform_mx_id (eqP idN) (eqP idB).\nby rewrite nonconform_mx ?neqm2n ?norm_id.\nQed.\n\nLemma capmxE : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A :&: B :=: capmx_gen A B)%MS.\nProof.\nmove=> m1 m2 n A B; rewrite mxopE -subset1mx; apply/eqmxP.\nhave:= subsetmx_refl (capmx_gen A B).\nrewrite !sub_capmx_gen; case/andP=> sIA sIB.\ncase idA: (capmx_id A); first by rewrite !capmx_nopP subsetmx_refl sub_capmx_id.\ncase idB: (capmx_id B); first by rewrite !capmx_nopP subsetmx_refl sub_capmx_id.\ncase s1B: (1%:M <= B)%MS; rewrite !capmx_normP ?sub_capmx_gen sIA ?sIB //=.\nby rewrite subsetmx_refl (subsetmx_trans (subsetmx1 _)).\nQed.\n\nLemma capmxSl : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A :&: B <= A)%MS.\nProof. by move=> m1 m2 n A B; rewrite capmxE subsetmxMl. Qed.\n\nLemma sub_capmx : forall m m1 m2 n,\n    forall (A : 'M_(m, n)) (B : 'M_(m1, n)) (C : 'M_(m2, n)),\n  (A <= B :&: C)%MS = (A <= B)%MS && (A <= C)%MS.\nProof. by move=> m m1 m2 n A B C; rewrite capmxE sub_capmx_gen. Qed.\n\nLemma capmxC : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A :&: B = B :&: A)%MS.\nProof.\nmove=> m1 m2 n A B; case: (eqVneq (capmx_id A) (capmx_id B)) => [eqAB|].\n  rewrite (capmx_eq_norm eqAB) (capmx_eq_norm (esym eqAB)).\n  apply: capmx_norm_eq; first by rewrite !capmx_id_cap andbC.\n  by apply/andP; split; rewrite !sub_capmx andbC -sub_capmx.\nby rewrite negb_eqb !mxopE; move/addbP <-; case: (capmx_id A).\nQed.\n\nLemma capmxSr : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A :&: B <= B)%MS.\nProof. by move=> m1 m2 n A B; rewrite capmxC capmxSl. Qed.\n\nLemma capmxS : forall m1 m2 m3 m4 n,\n    forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) (D : 'M_(m4, n)),\n  (A <= C -> B <= D -> A :&: B <= C :&: D)%MS.\nProof.\nmove=> m1 m2 m3 m4 n A B C D sAC sBD; rewrite sub_capmx.\nby rewrite {1}capmxC !(subsetmx_trans (capmxSr _ _)).\nQed.\n\nLemma cap_eqmx : forall m1 m2 m3 m4 n,\n    forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) (D : 'M_(m4, n)),\n  (A :=: C -> B :=: D -> A :&: B :=: C :&: D)%MS.\nProof.\nby move=> m1 m2 m3 m4 n A B C D sAC sBD; apply/eqmxP; rewrite !capmxS ?sAC ?sBD.\nQed.\n\nLemma capmxMr : forall m1 m2 n p,\n    forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)),\n  ((A :&: B) *m C <= A *m C :&: B *m C)%MS.\nProof.\nby move=> m1 m2 n p A B C; rewrite sub_capmx !subsetmxMr ?capmxSl ?capmxSr.\nQed.\n\nLemma cap0mx : forall m1 m2 n (A : 'M_(m2, n)), ((0 : 'M_(m1, n)) :&: A)%MS = 0.\nProof. by move=> m1 m2 n A; exact: subsetmx0null (capmxSl _ _). Qed.\n\nLemma capmx0 : forall m1 m2 n (A : 'M_(m1, n)), (A :&: (0 : 'M_(m2, n)))%MS = 0.\nProof. by move=> m1 m2 n A; exact: subsetmx0null (capmxSr _ _). Qed.\n\nLemma capmxT : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  row_full B -> (A :&: B :=: A)%MS.\nProof.\nmove=> m1 m2 n A B; rewrite -subset1mx => s1B; apply/eqmxP.\nby rewrite capmxSl sub_capmx subsetmx_refl (subsetmx_trans (subsetmx1 A)).\nQed.\n\nLemma capTmx : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  row_full A -> (A :&: B :=: B)%MS.\nProof.\nby move=> m1 m2 n A B Afull; apply/eqmxP; rewrite capmxC !capmxT ?andbb.\nQed.\n\nLet capmx_nop_id : forall n (A : 'M_n), capmx_nop A = A.\nProof. by move=> n A; rewrite /capmx_nop conform_mx_id. Qed.\n\nLemma cap1mx : forall n (A : 'M_n), (1%:M :&: A = A)%MS.\nProof. by move=> n A; rewrite mxopE capmx_id_eq1 eqxx capmx_nop_id. Qed.\n\nLemma capmx1 : forall n (A : 'M_n), (A :&: 1%:M = A)%MS.\nProof. by move=> n A; rewrite capmxC cap1mx. Qed.\n\nLemma capmxA : forall m1 m2 m3 n,\n               forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)),\n  (A :&: (B :&: C) = A :&: B :&: C)%MS.\nProof.\nmove=> m1 m2 m3 n A B C; rewrite (capmxC A B) capmxC.\nwlog idA: m1 m3 A C / (capmx_id A).\n  move=> IH; case idA: (capmx_id A); first exact: IH.\n  case idC: (capmx_id C); first by rewrite -IH.\n  rewrite (@capmx_eq_norm n m3) ?capmx_id_cap ?idA ?idC ?andbF //.\n  rewrite capmx_eq_norm ?capmx_id_cap ?idA ?idC ?andbF //.\n  apply: capmx_norm_eq; first by rewrite !capmx_id_cap andbAC.\n  by apply/andP; split; rewrite !sub_capmx andbAC -!sub_capmx.\nrewrite -!(capmxC A) ![@capmx m1]mxopE idA capmx_nop_id.\ncase: (eqVneq (capmx_id B) (capmx_id C)) => [eqBC |].\n  rewrite (@capmx_eq_norm n) ?capmx_nopP // capmx_eq_norm //.\n  by apply: capmx_norm_eq; rewrite ?capmx_id_cap ?capmxS ?capmx_nopP.\nby rewrite !mxopE capmx_nopP capmx_nop_id; do 2?case: capmx_id => //.\nQed.\n\nCanonical Structure capmx_monoid n :=\n  Monoid.Law (@capmxA n n n n) (@cap1mx n) (@capmx1 n).\nCanonical Structure capmx_comoid n := Monoid.ComLaw (@capmxC n n n).\n\nLemma bigcapmx_inf : forall i0 P m n (A_ : I -> 'M_n) (B : 'M_(m, n)),\n  P i0 -> (A_ i0 <= B -> \\bigcap_(i | P i) A_ i <= B)%MS.\nProof.\nmove=> i0 P m n A_ B Pi0; apply: subsetmx_trans.\nby rewrite (bigD1 i0) // capmxSl.\nQed.\n\nLemma sub_bigcapmxP : forall P m n (A : 'M_(m, n)) (B_ : I -> 'M_n),\n  reflect (forall i, P i -> A <= B_ i)%MS (A <= \\bigcap_(i | P i) B_ i)%MS.\nProof.\nmove=> P m n A B_; apply: (iffP idP) => [sAB i Pi | sAB].\n  by apply: (subsetmx_trans sAB); rewrite (bigcapmx_inf Pi).\nby apply big_prop => // [|B C sAC]; rewrite ?subsetmx1 // sub_capmx sAC.\nQed.\n\nLemma matrix_modl : forall m1 m2 m3 n,\n                    forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)),\n  (A <= C -> A + (B :&: C) :=: (A + B) :&: C)%MS.\nProof.\nmove=> m1 m2 m3 n A B C sAC; set D := ((A + B) :&: C)%MS; apply/eqmxP.\nrewrite sub_capmx sumsmxS ?capmxSl // sumsmx_sub sAC capmxSr /=.\nhave: (D <= B + A)%MS by rewrite sumsmxC capmxSl.\ncase/sub_sumsmxP=> A' sDA'B sA'A; rewrite -(addNKr A' D) subsetmx_add_sums //.\nrewrite addrC sub_capmx sDA'B subsetmx_add ?capmxSr // eqmx_opp.\nexact: subsetmx_trans sA'A sAC.\nQed.\n\nLemma matrix_modr : forall m1 m2 m3 n,\n                    forall (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)),\n  (C <= A -> (A :&: B) + C :=: A :&: (B + C))%MS.\nProof.\nmove=> m1 m2 m3 n A B C; rewrite !(capmxC A) -!(sumsmxC C); exact: matrix_modl.\nQed.\n\nLemma capmx_compl : forall m n (A : 'M_(m, n)), (A :&: A^C)%MS = 0.\nProof.\nmove=> m n A; set D := (A :&: A^C)%MS; have: (D <= D)%MS by [].\nrewrite sub_capmx andbC; case/andP; case/subsetmxP=> B defB.\nrewrite subsetmxE; move/eqP; rewrite defB -!mulmxA mulKVmx ?copid_mx_id //.\nby rewrite mulmxA => ->; rewrite mul0mx.\nQed.\n\nLemma mxrank_mul_ker : forall m n p (A : 'M_(m, n)) (B : 'M_(n, p)),\n  (\\rank (A *m B) + \\rank (A :&: kermx B))%N = \\rank A.\nProof.\nmove=> m n p A B; apply/eqP; set K := kermx B; set C := (A :&: K)%MS.\nrewrite -(eqmxMr B (eq_row_base A)); set K' := _ *m B.\nrewrite -{2}(subnKC (rank_leq_row K')) -mxrank_ker eqn_addl.\nrewrite -(mxrankMfree _ (row_base_free A)) mxrank_leqif_sup.\n  rewrite sub_capmx -(eq_row_base A) subsetmxMl. \n  by apply/sub_kermxP; rewrite -mulmxA mulmx_ker.\nhave: (C <= row_base A)%MS by rewrite eq_row_base capmxSl.\ncase/subsetmxP=> C' defC; rewrite defC subsetmxMr //; apply/sub_kermxP.\nby rewrite mulmxA -defC; apply/sub_kermxP; rewrite capmxSr.\nQed.\n\nLemma mxrank_disjoint_sum : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A :&: B)%MS = 0  -> \\rank (A + B)%MS = (\\rank A + \\rank B)%N.\nProof.\nmove=> m1 m2 n A B AB0; pose Ar := row_base A; pose Br := row_base B.\nhave [Afree Bfree]: row_free Ar /\\ row_free Br by rewrite !row_base_free.\nhave: (Ar :&: Br <= A :&: B)%MS by rewrite capmxS ?eq_row_base.\nrewrite {}AB0 subsetmx0 -mxrank_eq0 capmxE mxrankMfree //.\nset Cr := col_mx Ar Br; set Crl := lsubmx _; rewrite mxrank_eq0 => Crl0.\nrewrite -(sums_eqmx (eq_row_base _) (eq_row_base _)) sumsmxE -/Cr.\nsuffices K0: kermx Cr = 0.\n  by apply/eqP; rewrite eqn_leq rank_leq_row -subn_eq0 -mxrank_ker K0 mxrank0.\nmove/eqP: (mulmx_ker Cr); rewrite -[kermx Cr]hsubmxK mul_row_col -/Crl.\nrewrite (eqP Crl0) mul0mx add0r -mxrank_eq0 mxrankMfree // mxrank_eq0.\nby move/eqP->; rewrite row_mx0.\nQed.\n\nLemma diffmxE : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A :\\: B :=: A :&: (capmx_gen A B)^C)%MS.\nProof.\nmove=> m1 m2 n A B; rewrite mxopE; apply/eqmxP.\nby rewrite !genmxE !capmxE andbb.\nQed.\n\nLemma diffmxSl : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A :\\: B <= A)%MS.\nProof. by move=> m1 m2 n A B; rewrite diffmxE capmxSl. Qed.\n\nLemma capmx_diff : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  ((A :\\: B) :&: B)%MS = 0.\nProof.\nmove=> m1 m2 n A B; apply/eqP; pose C := capmx_gen A B.\nrewrite -subsetmx0 -(capmx_compl C) sub_capmx -capmxE sub_capmx andbAC.\nby rewrite -sub_capmx -diffmxE -sub_capmx.\nQed.\n\nLemma sumsmx_diff_cap_eq : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A :\\: B + A :&: B :=: A)%MS.\nProof.\nmove=> m1 m2 n A B; apply/eqmxP; rewrite sumsmx_sub capmxSl diffmxSl /=.\nset C := (A :\\: B)%MS; set D := capmx_gen A B.\nsuffices sACD: (A <= C + D)%MS.\n  by rewrite (subsetmx_trans sACD) ?sumsmxS ?capmxE.\nhave:= sumsmx_compl_full D; rewrite /row_full sumsmxE.\ncase/row_fullP=> U; move/(congr1 (mulmx A)); rewrite mulmx1.\nrewrite -[U]hsubmxK mul_row_col mulmx_addr addrC 2!mulmxA.\nset V := _ *m _ => defA; rewrite -defA; move/(canRL (addrK _)): defA => defV.\nhave: (V <= C)%MS.\n  rewrite diffmxE sub_capmx {1}defV -mulNmx subsetmx_add 1?subsetmxMtrans //.\n  by rewrite -capmxE capmxSl.\nby case/subsetmxP=> W ->; rewrite -mul_row_col sumsmxE subsetmxMl.\nQed.\n\nLemma mxrank_cap_compl : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (\\rank (A :&: B) + \\rank (A :\\: B))%N = \\rank A.\nProof.\nmove=> m1 m2 n A B; rewrite addnC -mxrank_disjoint_sum ?sumsmx_diff_cap_eq //.\nby rewrite (capmxC A) capmxA capmx_diff cap0mx.\nQed.\n\nLemma mxrank_sum_cap : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (\\rank (A + B) + \\rank (A :&: B) = \\rank A + \\rank B)%N.\nProof.\nmove=> m1 m2 n A B; set C := (A :&: B)%MS; set D := (A :\\: B)%MS.\nhave rDB: \\rank (A + B)%MS = \\rank (D + B)%MS.\n  apply/eqP; rewrite mxrank_leqif_sup; first by rewrite sumsmxS ?diffmxSl.\n  by rewrite sumsmx_sub sumsmxSr -(sumsmx_diff_cap_eq A B) sumsmxS ?capmxSr.\nrewrite {1}rDB mxrank_disjoint_sum ?capmx_diff //.\nby rewrite addnC addnA mxrank_cap_compl.\nQed.\n\nLemma mxrank_sums_leqif : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  \\rank (A + B) <= \\rank A + \\rank B ?= iff (A :&: B <= (0 : 'M_n))%MS.\nProof.\nmove=> m1 m2 n A B; rewrite -mxrank_sum_cap; split; first exact: leq_addr.\nby rewrite addnC (@eqn_addr _ 0) eq_sym mxrank_eq0 -subsetmx0.\nQed.\n\nSection SumExpr.\n\n(* This is the infrastructure to support the mxdirect predicate. We use a     *)\n(* bespoke canonical structure to decompose a matrix expression into binary   *)\n(* and n-ary products, using some of the \"quote\" technology. This lets us     *)\n(* characterize direct sums as set sums whose rank is equal to the sum of the *)\n(* ranks of the individual terms. The mxsum_expr/proper_mxsum_expr structures *)\n(* below supply both the decomposition and the calculation of the rank sum.   *)\n(* The mxsum_spec dependent predicate family expresses the consistency of     *)\n(* these two decompositions.                                                  *)\n(*   The main technical difficulty we need to overcome is the fact that       *)\n(* the \"catch-all\" case of canonical structures has a priority lower than     *)\n(* constant expansion. However, it is undesireable that local abbreviations   *)\n(* be opaque for the direct-sum predicate, e.g., not be able to handle        *)\n(* let S := (\\sum_(i | P i) LargeExpression i)%MS in mxdirect S -> ...).      *)\n(*   As in \"quote\", we use the interleaving of constant expansion and         *)\n(* canonical projection matching to achieve our goal: we use a \"wrapper\" type *)\n(* (indeed, the wrapped T type defined in ssrfun.v) with a self-inserting     *)\n(* non-primitive constructor to gain finer control over the type and          *)\n(* structure inference process. The innermost, primitive, constructor flags   *)\n(* trivial sums; it is initially hidden by an eta-expansion, which has been   *)\n(* made into a (default) canonical structure -- this lets type inference      *)\n(* automatically insert this outer tag.                                       *)\n(*   In detail, we define three types                                         *)\n(*  mxsum_spec S r <-> There exists a finite list of matrices A1, ..., Ak     *)\n(*                     such that S is the set sum of the Ai, and r is the sum *)\n(*                     of the ranks of the Ai, i.e., S = (A1 + ... + Ak)%MS   *)\n(*                     and r = \\rank A1 + ... + \\rank Ak. Note that           *)\n(*                     mxsum_spec is a recursive dependent predicate family   *)\n(*                     whose elimination rewrites simultaneaously S, r and    *)\n(*                     the height of S.                                       *)\n(*   proper_mxsum_expr n == The interface for proper sum expressions; this is *)\n(*                     a double-entry interface, keyed on both the matrix sum *)\n(*                     value and the rank sum. The matrix value is restricted *)\n(*                     to square matrices, as the \"+\"%MS operator always      *)\n(*                     returns a square matrix. This interface has two        *)\n(*                     canonical insances, for binary and n-ary sums.         *)\n(*   mxsum_expr m n == The interface for general sum expressions, comprising  *)\n(*                     both proper sums and trivial sums consisting of a      *)\n(*                     single matrix. The key values are WRAPPED as this lets *)\n(*                     us give priority to the \"proper sum\" interpretation    *)\n(*                     (see below). To allow for trivial sums, the matrix key *)\n(*                     can have any dimension. The mxsum_expr interface has   *)\n(*                     two canonical instances, for trivial and proper sums,  *)\n(*                     keyed to the Wrap and wrap constructors, respectively. *)\n(* The projections for the two interfaces above are                           *)\n(*   proper_mxsum_val, mxsum_val : these are respectively coercions to 'M_n   *)\n(*                     and wrapped 'M_(m, n); thus, the matrix sum for an     *)\n(*                     S : mxsum_expr m n can be written unwrap S.            *)\n(*   proper_mxsum_rank, mxsum_rank : projections to the nat and wrapped nat,  *)\n(*                     respectively; the rank sum for S : mxsum_expr m n is   *)\n(*                     thus written unwrap (mxsum_rank S).                    *)\n(* The mxdirect A predicate actually gets A in a phantom argument, which is   *)\n(* used to infer an (implicit) S : mxsum_expr such that unwrap S = A; the     *)\n(* actual definition is \\rank (unwrap S) == unwrap (mxsum_rank S).            *)\n(*   Note that the inference of S is inherently ambiguous: ANY matrix can be  *)\n(* viewed as a trivial sum, including one whose description is manifestly a   *)\n(* proper sum. We use the wrapped type and the interaction between delta      *)\n(* reduction and canonical structure inference to resolve this ambiguity in   *)\n(* favor of proper sums, as follows:                                          *)\n(*    - The phantom type sets up a unification problem of the form            *)\n(*         unwrap (mxsum_val ?S) = A                                          *)\n(*      with unknown evar ?S : mxsum_expr m n.                                *)\n(*    - As the constructor wrap is also a default Canonical Structure for the *)\n(*      wrapped type, so A is immediately replaced with unwrap (wrap A) and   *)\n(*      we get the residual unification problem                               *)\n(*         mxsum_val ?S = wrap A                                              *)\n(*    - Now Coq tries to apply the proper sum Canonical Structure, which has  *)\n(*      key projection wrap (proper_mxsum_val ?PS) where ?PS is a fresh evar  *)\n(*      (of type proper_mxsum_expr n). This can only succeed if m = n, and if *)\n(*      a solution can be found to the recursive unification problem          *)\n(*         proper_mxsum_val ?PS = A                                           *)\n(*      This causes Coq to look for one of the two canonical constants for    *)\n(*      proper_mxsum_val (sumsmx or bigop) at the head of A, delta-expanding  *)\n(*      A as needed, and then inferring recursively mxsum_expr structures for *)\n(*      the last argument(s) of that constant.                                *)\n(*    - If the above step fails then the wrap constant is expanded, revealing *)\n(*      the primitive Wrap constructor; the unification problem now becomes   *)\n(*         mxsum_val ?S = Wrap A                                              *)\n(*      which fits perfectly the trivial sum canonical structure, whose key   *)\n(*      projection is Wrap ?B where ?B is a fresh evar. Thus the inference    *)\n(*      succeeds, and returns the trivial sum.                                *)\n(* Note that the rank projections also register canonical values, so that the *)\n(* same process can be used to infer a sum structure from the rank sum. In    *)\n(* that case, however, there is no ambiguity and the inference can fail,      *)\n(* because the rank sum for a trivial sum is not an arbitrary integer -- it   *)\n(* must be of the form \\rank ?B. It is nevertheless necessary to use the      *)\n(* wrapped nat type for the rank sums, because in the non-trivial case the    *)\n(* head constant of the nat expression is determined by the proper_mxsum_expr *)\n(* canonical structure, so the mxsum_expr structure must use a generic        *)\n(* constant, namely wrap.                                                     *)\n\nInductive mxsum_spec n : forall m, 'M[F]_(m, n) -> nat -> Prop :=\n | TrivialMxsum m A\n    : @mxsum_spec n m A (\\rank A)\n | ProperMxsum m1 m2 T1 T2 r1 r2 of\n      @mxsum_spec n m1 T1 r1 & @mxsum_spec n m2 T2 r2\n    : mxsum_spec (T1 + T2)%MS (r1 + r2)%N.\nArguments Scope mxsum_spec [nat_scope nat_scope matrix_set_scope nat_scope].\n\nStructure mxsum_expr m n := Mxsum {\n  mxsum_val :> wrapped 'M_(m, n);\n  mxsum_rank : wrapped nat;\n  _ : mxsum_spec (unwrap mxsum_val) (unwrap mxsum_rank)\n}.\n\nCanonical Structure trivial_mxsum m n A :=\n  @Mxsum m n (Wrap A) (Wrap (\\rank A)) (TrivialMxsum A).\n\nStructure proper_mxsum_expr n := ProperMxsumExpr {\n  proper_mxsum_val :> 'M_n;\n  proper_mxsum_rank : nat;\n  _ : mxsum_spec proper_mxsum_val proper_mxsum_rank\n}.\n\nDefinition proper_mxsumP n (S : proper_mxsum_expr n) :=\n  let: ProperMxsumExpr _ _ termS := S return mxsum_spec S (proper_mxsum_rank S)\n  in termS.\n\nCanonical Structure sum_mxsum n (S : proper_mxsum_expr n) :=\n  @Mxsum n n (wrap (S : 'M_n)) (wrap (proper_mxsum_rank S)) (proper_mxsumP S).\n\nSection Binary.\nVariable (m1 m2 n : nat) (S1 : mxsum_expr m1 n) (S2 : mxsum_expr m2 n).\nFact binary_mxsum_proof :\n  mxsum_spec (unwrap S1 + unwrap S2)\n             (unwrap (mxsum_rank S1) + unwrap (mxsum_rank S2)).\nProof. by case: S1 S2 => [A1 r1 A1P] [A2 r2 A2P]; right. Qed.\nCanonical Structure binary_mxsum_expr := ProperMxsumExpr binary_mxsum_proof.\nEnd Binary.\n\nSection Nary.\nVariables (P : pred I) (n : nat) (S_ : I -> mxsum_expr n n).\nFact nary_mxsum_proof :\n  mxsum_spec (\\sum_(i | P i) unwrap (S_ i))\n             (\\sum_(i | P i) unwrap (mxsum_rank (S_ i))).\nProof.\nrewrite -!(big_filter _ P) !unlock.\nelim: filter => /= [|i e IHe]; first by rewrite -(mxrank0 n n); left.\nby right=> //; case: (S_ i) => A r; exact.\nQed.\nCanonical Structure nary_mxsum_expr := ProperMxsumExpr nary_mxsum_proof.\nEnd Nary.\n\nDefinition mxdirect_def m n T of phantom 'M_(m, n) (unwrap (mxsum_val T)) :=\n  \\rank (unwrap T) == unwrap (mxsum_rank T).\n\nEnd SumExpr.\n\nNotation mxdirect A := (mxdirect_def (Phantom 'M_(_,_) A%MS)).\n\nLemma mxdirectP : forall n (S : proper_mxsum_expr n),\n  reflect (\\rank S = proper_mxsum_rank S) (mxdirect S).\nProof. move=> n S; exact: eqnP. Qed.\nImplicit Arguments mxdirectP [n S].\n\nLemma mxdirect_trivial : forall m n A,\n  mxdirect (unwrap (@trivial_mxsum m n A)).\nProof. move=> m n A; exact: eqxx. Qed.\n\nLemma mxrank_sum_leqif : forall m n (S : mxsum_expr m n),\n  \\rank (unwrap S) <= unwrap (mxsum_rank S) ?= iff mxdirect (unwrap S).\nProof.\nrewrite /mxdirect_def => m n [[A] [r] /= defAr]; split=> //=.\nelim: m A r / defAr => // m1 m2 A1 A2 r1 r2 _ leAr1 _ leAr2.\nby apply: leq_trans (leq_add leAr1 leAr2); rewrite mxrank_sums_leqif.\nQed.\n\nLemma mxdirectE : forall m n (S : mxsum_expr m n),\n  mxdirect (unwrap S) = (\\rank (unwrap S) == unwrap (mxsum_rank S)).\nProof. by []. Qed.\n\nLemma mxdirectEgeq : forall m n (S : mxsum_expr m n),\n  mxdirect (unwrap S) = (\\rank (unwrap S) >= unwrap (mxsum_rank S)).\nProof.\nby move=> m n S; rewrite leq_eqVlt ltnNge eq_sym !mxrank_sum_leqif orbF.\nQed.\n\nSection BinaryDirect.\n\nVariables m1 m2 n : nat.\n\nLemma mxdirect_sumsE : forall (S1 : mxsum_expr m1 n) (S2 : mxsum_expr m2 n),\n   mxdirect (unwrap S1 + unwrap S2)\n    = [&& mxdirect (unwrap S1), mxdirect (unwrap S2)\n        & unwrap S1 :&: unwrap S2 == 0]%MS.\nProof.\nmove=> S1 S2; rewrite (@mxdirectE n) /=.\nhave:= leqif_add (mxrank_sum_leqif S1) (mxrank_sum_leqif S2).\nmove/(leqif_trans (mxrank_sums_leqif (unwrap S1) (unwrap S2)))=> ->.\nby rewrite andbC -andbA subsetmx0.\nQed.\n\nLemma mxdirect_sumsP : forall (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  reflect (A :&: B = 0)%MS (mxdirect (A + B)).\nProof. move=> A B; rewrite mxdirect_sumsE !mxdirect_trivial; exact: eqP. Qed.\n\nEnd BinaryDirect.\n\nSection NaryDirect.\n\nVariables (P : pred I) (n : nat).\n\nLet TIsum A_ i := (A_ i :&: (\\sum_(j | P j && (j != i)) A_ j) = 0 :> 'M_n)%MS.\n\nLet mxdirect_bigsums_recP : forall S_ : I -> mxsum_expr n n,\n  reflect (forall i, P i -> mxdirect (unwrap (S_ i)) /\\ TIsum (unwrap \\o S_) i)\n          (mxdirect (\\sum_(i | P i) (unwrap (S_ i)))).\nProof.\nrewrite /TIsum => S_; apply: (iffP eqnP) => /= [dxS i Pi | dxS].\n  set Si' := (\\sum_(j | _) unwrap (S_ j))%MS.\n  suffices: mxdirect (unwrap (S_ i) + Si').\n    by rewrite mxdirect_sumsE; case/and3P=> -> _; move/eqP.\n  by apply/eqnP; rewrite /= -!(bigD1 i).\nelim: _.+1 {-2 4}P (subxx P) (ltnSn #|P|) => // m IHm Q; move/subsetP=> sQP.\ncase: (pickP Q) => [i Qi | Q0]; last by rewrite !big_pred0 ?mxrank0.\nrewrite (cardD1x Qi) !((bigD1 i) Q) //=.\nmove/IHm=> <- {IHm}/=; last by apply/subsetP=> j; case/andP; move/sQP.\ncase: (dxS i (sQP i Qi)); move/eqnP=> <- TiQ_0; rewrite mxrank_disjoint_sum //.\napply/eqP; rewrite -subsetmx0 -{2}TiQ_0 capmxS //=; apply/bigsumsmx_subP=> j /=.\nby case/andP=> Qj i'j; rewrite (bigsumsmx_sup j) ?[P j]sQP.\nQed.\n\nLemma mxdirect_bigsumsP : forall A_ : I -> 'M_n,\n  reflect (forall i, P i -> A_ i :&: (\\sum_(j | P j && (j != i)) A_ j) = 0)%MS\n          (mxdirect (\\sum_(i | P i) A_ i)).\nProof.\nmove=> A_; apply: (iffP (mxdirect_bigsums_recP _)) => dxA i; case/dxA=> //.\nby rewrite mxdirect_trivial.\nQed.\n\nLemma mxdirect_bigsumsE : forall (S_ : I -> mxsum_expr n n) (xunwrap := unwrap),\n  reflect (and (forall i, P i -> mxdirect (unwrap (S_ i)))\n               (mxdirect (\\sum_(i | P i) (xunwrap (S_ i)))))\n          (mxdirect (\\sum_(i | P i) (unwrap (S_ i)))).\nProof.\nmove=> S_; apply: (iffP (mxdirect_bigsums_recP _)) => [dxS | [dxS_ dxS] i Pi].\n  by do [split; last apply/mxdirect_bigsumsP] => i; case/dxS.\nby split; [exact: dxS_ | exact: mxdirect_bigsumsP Pi].\nQed.\n\nEnd NaryDirect.\n\nSection SubDsumsmx.\n\nVariables m m1 m2 n : nat.\nVariables (A : 'M[F]_(m, n)) (B1 : 'M[F]_(m1, n)) (B2 : 'M[F]_(m2, n)).\n\nCoInductive sub_dsumsmx_spec : Prop :=\n  SubDsumsmxSpec A1 A2 of (A1 <= B1)%MS & (A2 <= B2)%MS & A = A1 + A2\n                        & forall C1 C2, (C1 <= B1)%MS -> (C2 <= B2)%MS ->\n                          A = C1 + C2 -> C1 = A1 /\\ C2 = A2.\n\nLemma sub_dsumsmx : (B1 :&: B2 = 0)%MS -> (A <= B1 + B2)%MS -> sub_dsumsmx_spec.\nProof.\nmove=> dxB; case/sub_sumsmxP=> A2 sAB1 sAB2.\nexists (A - A2) A2; rewrite ?subrK // => C1 C2 sCB1 sCB2 defA.\nsuff: (C2 - A2 <= B1 :&: B2)%MS.\n  by rewrite dxB subsetmx0 subr_eq0 defA; move/eqP->; rewrite addrK.\nrewrite sub_capmx -{1}(canLR (addKr _) defA) -addrA.\nby rewrite andbC 2?subsetmx_add ?eqmx_opp.\nQed.\n\nEnd SubDsumsmx.\n\nSection SubDbigsumsmx.\n\nVariables (P : pred I) (m n : nat) (A : 'M[F]_(m, n)) (B : I -> 'M[F]_n).\n\nCoInductive sub_bigdsumsmx_spec : Prop :=\n  SubDbigsumsmxSpec A_ of forall i, P i -> (A_ i <= B i)%MS\n                        & A = \\sum_(i | P i) A_ i\n                        & forall C, (forall i, P i -> C i <= B i)%MS ->\n                          A = \\sum_(i | P i) C i -> {in SimplPred P, C =1 A_}.\n\nLemma sub_bigdsumsmx :\n    mxdirect (\\sum_(i | P i) B i) -> (A <= \\sum_(i | P i) B i)%MS ->\n  sub_bigdsumsmx_spec.\nProof.\nmove/mxdirect_bigsumsP=> dxB; case/sub_bigsumsmxP=> u defA.\npose A_ i := u i *m B i.\nexists A_ => //= [i _ | C sCB defAC i Pi]; first exact: subsetmxMl.\napply/eqP; rewrite -subr_eq0 -subsetmx0 -{dxB}(dxB i Pi) /=.\nrewrite sub_capmx subsetmx_add ?eqmx_opp ?subsetmxMl ?sCB //=.\nrewrite -(subrK A (C i)) -addrA -oppr_sub subsetmx_add ?eqmx_opp //.\n  rewrite addrC defAC (bigD1 i) // addKr /= subsetmx_sum // => j Pi'j.\n  by rewrite (bigsumsmx_sup j) ?sCB //; case/andP: Pi'j.\nrewrite addrC defA (bigD1 i) // addKr /= subsetmx_sum // => j Pi'j.\nby rewrite (bigsumsmx_sup j) ?subsetmxMl.\nQed.\n\nEnd SubDbigsumsmx.\n\nEnd RowSpaceTheory.\n\nHint Resolve subsetmx_refl.\nImplicit Arguments subsetmxP [F m1 m2 n A B].\nImplicit Arguments eq_row_sub [F m n v A].\nImplicit Arguments row_subP [F m1 m2 n A B].\nImplicit Arguments row_subPn [F m1 m2 n A B].\nImplicit Arguments sub_rVP [F n u v].\nImplicit Arguments rowV0Pn [F m n A].\nImplicit Arguments rowV0P [F m n A].\nImplicit Arguments row_fullP [F m n A].\nImplicit Arguments row_freeP [F m n A].\nImplicit Arguments eqmxP [F m1 m2 n A B].\nImplicit Arguments genmxP [F m1 m2 n A B].\nImplicit Arguments sub_sumsmxP [F m1 m2 m3 n A B C].\nImplicit Arguments bigsumsmx_sup [F I P m n A B_].\nImplicit Arguments bigsumsmx_subP [F I P m n A_ B].\nImplicit Arguments sub_bigsumsmxP [F I P m n A B_].\nImplicit Arguments sub_kermxP [F p m n A B].\nImplicit Arguments det0P [F n A].\nImplicit Arguments bigcapmx_inf [F I P m n A_ B].\nImplicit Arguments sub_bigcapmxP [F I P m n A B_].\nImplicit Arguments mxdirectP [F n S].\nImplicit Arguments mxdirect_sumsP [F m1 m2 n A B].\nImplicit Arguments mxdirect_bigsumsP [F I P n A_].\nImplicit Arguments mxdirect_bigsumsE [F I P n S_].\n\nArguments Scope mxrank [_ nat_scope nat_scope matrix_set_scope].\nArguments Scope complmx [_ nat_scope nat_scope matrix_set_scope].\nArguments Scope row_full [_ nat_scope nat_scope matrix_set_scope].\nArguments Scope subsetmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope eqmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope sumsmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope capmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope diffmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits mxrank genmx complmx subsetmx sumsmx capmx.\nNotation \"\\rank A\" := (mxrank A) : nat_scope.\nNotation \"<< A >>\" := (genmx A) : matrix_set_scope.\nNotation \"A ^C\" := (complmx A) : matrix_set_scope.\nNotation \"A <= B\" := (subsetmx A B) : matrix_set_scope.\nNotation \"A <= B <= C\" := ((subsetmx A B) && (subsetmx B C)) : matrix_set_scope.\nNotation \"A == B\" := ((subsetmx A B) && (subsetmx B A)) : matrix_set_scope.\nNotation \"A :=: B\" := (eqmx A B) : matrix_set_scope.\nNotation \"A + B\" := (sumsmx A B) : matrix_set_scope.\nNotation \"A :&: B\" := (capmx A B) : matrix_set_scope.\nNotation \"A :\\: B\" := (diffmx A B) : matrix_set_scope.\nNotation mxdirect S := (mxdirect_def (Phantom 'M_(_,_) S%MS)).\n\nNotation \"\\sum_ ( <- r | P ) B\" :=\n  (\\big[sumsmx/0%R]_(<- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i <- r | P ) B\" :=\n  (\\big[sumsmx/0%R]_(i <- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i <- r ) B\" :=\n  (\\big[sumsmx/0%R]_(i <- r) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( m <= i < n | P ) B\" :=\n  (\\big[sumsmx/0%R]_(m <= i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( m <= i < n ) B\" :=\n  (\\big[sumsmx/0%R]_(m <= i < n) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i | P ) B\" :=\n  (\\big[sumsmx/0%R]_(i | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ i B\" :=\n  (\\big[sumsmx/0%R]_i B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i : t | P ) B\" :=\n  (\\big[sumsmx/0%R]_(i : t | P%B) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\sum_ ( i : t ) B\" :=\n  (\\big[sumsmx/0%R]_(i : t) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\sum_ ( i < n | P ) B\" :=\n  (\\big[sumsmx/0%R]_(i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i < n ) B\" :=\n  (\\big[sumsmx/0%R]_(i < n) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i \\in A | P ) B\" :=\n  (\\big[sumsmx/0%R]_(i \\in A | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i \\in A ) B\" :=\n  (\\big[sumsmx/0%R]_(i \\in A) B%MS) : matrix_set_scope.\n\nNotation \"\\bigcap_ ( <- r | P ) B\" :=\n  (\\big[capmx/1%:M]_(<- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i <- r | P ) B\" :=\n  (\\big[capmx/1%:M]_(i <- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i <- r ) B\" :=\n  (\\big[capmx/1%:M]_(i <- r) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( m <= i < n | P ) B\" :=\n  (\\big[capmx/1%:M]_(m <= i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( m <= i < n ) B\" :=\n  (\\big[capmx/1%:M]_(m <= i < n) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i | P ) B\" :=\n  (\\big[capmx/1%:M]_(i | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ i B\" :=\n  (\\big[capmx/1%:M]_i B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i : t | P ) B\" :=\n  (\\big[capmx/1%:M]_(i : t | P%B) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\bigcap_ ( i : t ) B\" :=\n  (\\big[capmx/1%:M]_(i : t) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\bigcap_ ( i < n | P ) B\" :=\n  (\\big[capmx/1%:M]_(i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i < n ) B\" :=\n  (\\big[capmx/1%:M]_(i < n) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i \\in A | P ) B\" :=\n  (\\big[capmx/1%:M]_(i \\in A | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i \\in A ) B\" :=\n  (\\big[capmx/1%:M]_(i \\in A) B%MS) : matrix_set_scope.\n\nSection CardGL.\n\nVariable F : finFieldType.\n\nLemma card_GL : forall n, n > 0 ->\n  #|'GL_n[F]| = (#|F| ^ 'C(n, 2) * \\prod_(1 <= i < n.+1) (#|F| ^ i - 1))%N.\nProof.\ncase=> // n' _; set n := n'.+1; set p := #|F|.\nrewrite big_nat_rev big_add1 -triangular_sum expn_sum -big_split /=.\npose fr m := [pred A : 'M[F]_(m, n) | \\rank A == m].\nset m := {-7}n; transitivity #|fr m|.\n  by rewrite cardsT /= card_sub; apply: eq_card => A; rewrite -row_free_unit.\nelim: m (leqnn m : m <= n) => [_|m IHm]; last move/ltnW=> le_mn.\n  rewrite (@eq_card1 _ (0 : 'M_(0, n))) ?big_geq //= => A.\n  by rewrite [A]flatmx0 !inE !eqxx.\nrewrite big_nat_recr -{}IHm //= !subSS muln_subr muln1 -expn_add subnKC //.\nrewrite -sum_nat_const /= -sum1_card -add1n.\nrewrite (partition_big dsubmx (fr m)) /= => [|A]; last first.\n  rewrite !inE -{1}(vsubmxK A); move: {A}(_ A) (_ A) => Ad Au Afull.\n  rewrite eqn_leq rank_leq_row -(leq_add2l (\\rank Au)) -mxrank_sum_cap.\n  rewrite {1 3}[@mxrank]lock sumsmxE (eqnP Afull) -lock -addnA.\n  by rewrite leq_add ?rank_leq_row ?leq_addr.\napply: eq_bigr => A rAm; rewrite (reindex (col_mx^~ A)) /=; last first.\n  exists usubmx => [v _ | vA]; first by rewrite col_mxKu.\n  by case/andP=> _; move/eqP <-; rewrite vsubmxK.\ntransitivity #|~: [set v *m A | v <- 'rV_m]|; last first.\n  rewrite cardsCs setCK card_imset ?card_matrix ?card_ord ?mul1n //.\n  have [B AB1] := row_freeP rAm; apply: can_inj (mulmx^~ B) _ => v.\n  by rewrite -mulmxA AB1 mulmx1.\nrewrite -sum1_card; apply: eq_bigl => v; rewrite !inE col_mxKd eqxx.\nrewrite andbT eqn_leq rank_leq_row /= -(leq_add2r (\\rank (v :&: A)%MS)).\nrewrite -sumsmxE mxrank_sum_cap (eqnP rAm) addnAC leq_add2r ltn_neqAle andbC.\nrewrite !mxrank_leqif_sup ?capmxSl // sub_capmx subsetmx_refl /=.\nby congr (~~ _); apply/subsetmxP/imsetP=> [] [u]; exists u.\nQed.\n\n(* An alternate, somewhat more elementary proof, that does not rely on the *)\n(* row-space theory, but directly performs the LUP decomposition.          *)\nLemma LUP_card_GL : forall n, n > 0 ->\n  #|'GL_n[F]| = (#|F| ^ 'C(n, 2) * \\prod_(1 <= i < n.+1) (#|F| ^ i - 1))%N.\nProof.\ncase=> // n' _; set n := n'.+1; set p := #|F|.\nrewrite cardsT /= card_sub /GRing.unit /= big_add1 /= -triangular_sum -/n.\nelim: {n'}n => [|n IHn].\n  rewrite !big_geq // mul1n (@eq_card _ _ predT) ?card_matrix //= => M.\n  by rewrite {1}[M]flatmx0 -(flatmx0 1%:M) unitmx1.\nrewrite !big_nat_recr /= expn_add mulnAC mulnA -{}IHn -mulnA mulnC.\nset LHS := #|_|; rewrite -[n.+1]muln1 -{2}[n]mul1n {}/LHS.\nrewrite -!card_matrix subn1 -(cardC1 0) -mulnA; set nzC := predC1 _.\nrewrite -sum1_card (partition_big lsubmx nzC) => [|A]; last first.\n  rewrite unitmxE unitfE; apply: contra; move/eqP=> v0.\n  rewrite -[A]hsubmxK v0 -[n.+1]/(1 + n)%N -col_mx0.\n  rewrite -[rsubmx _]vsubmxK -det_tr tr_row_mx !tr_col_mx !trmx0.\n  by rewrite det_lblock [0]mx11_scalar det_scalar1 mxE mul0r.\nrewrite -sum_nat_const; apply: eq_bigr; rewrite /= -[n.+1]/(1 + n)%N => v nzv.\ncase: (pickP (fun i => v i 0 != 0)) => [k nza | v0]; last first.\n  by case/eqP: nzv; apply/colP=> i; move/eqP: (v0 i); rewrite mxE.\nhave xrkK: involutive (@xrow F _ _ 0 k).\n  by move=> m A /=; rewrite /xrow -row_permM tperm2 row_perm1.\nrewrite (reindex_inj (inv_inj (xrkK (1 + n)%N))) /= -[n.+1]/(1 + n)%N.\nrewrite (partition_big ursubmx xpredT) //= -sum_nat_const.\napply: eq_bigr => u _; set a : F := v _ _ in nza.\nset v1 : 'cV_(1 + n) := xrow 0 k v.\nhave def_a: usubmx v1 = a%:M.\n  by rewrite [_ v1]mx11_scalar mxE lshift0 mxE tpermL.\npose Schur := dsubmx v1 *m (a^-1 *m: u).\npose L : 'M_(1 + n) := block_mx a%:M 0 (dsubmx v1) 1%:M.\npose U B : 'M_(1 + n) := block_mx 1 (a^-1 *m: u) 0 B.\nrewrite (reindex (fun B => L *m U B)); last first.\n  exists (fun A1 => drsubmx A1 - Schur) => [B _ | A1].\n    by rewrite mulmx_block block_mxKdr mul1mx addrC addKr.\n  rewrite !inE mulmx_block !mulmx0 mul0mx !mulmx1 !addr0 mul1mx addrC subrK.\n  rewrite mul_scalar_mx scalemxA divff // scale1mx andbC; case/and3P.\n  move/eqP=> <- _; rewrite -{1}(hsubmxK A1) xrowE mul_mx_row row_mxKl -xrowE.\n  move/eqP=> def_v; rewrite -def_a block_mxEh vsubmxK /v1 -def_v xrkK.\n  apply: trmx_inj; rewrite tr_row_mx tr_col_mx trmx_ursub trmx_drsub trmx_lsub.\n  by rewrite hsubmxK vsubmxK.\nrewrite -sum1_card; apply: eq_bigl => B; rewrite xrowE unitmxE.\nrewrite !det_mulmx unitr_mul -unitmxE unitmx_perm det_lblock det_ublock.\nrewrite !det_scalar1 det1 mulr1 mul1r unitr_mul unitfE nza -unitmxE.\nrewrite mulmx_block !mulmx0 mul0mx !addr0 !mulmx1 mul1mx block_mxKur.\nrewrite mul_scalar_mx scalemxA divff // scale1mx eqxx andbT.\nby rewrite block_mxEh mul_mx_row row_mxKl -def_a vsubmxK -xrowE xrkK eqxx andbT.\nQed.\n\nLemma card_GL_1 : #|'GL_1[F]| = #|F|.-1.\nProof. by rewrite card_GL // mul1n big_nat1 expn1 subn1. Qed.\n\nLemma card_GL_2 : #|'GL_2[F]| = (#|F| * #|F|.-1 ^ 2 * #|F|.+1)%N.\nProof.\nrewrite card_GL // big_ltn // big_nat1 expn1 -(addn1 #|F|) -subn1 -!mulnA.\nby rewrite -subn_sqr.\nQed.\n\nEnd CardGL.\n\nLemma logn_card_GL_p : forall n p, prime p -> logn p #|'GL_n(p)| = 'C(n, 2).\nProof.\nmove=> n p p_pr; have p_gt1 := prime_gt1 p_pr.\nhave p_i_gt0: p ^ _ > 0 by move=> i; rewrite expn_gt0 ltnW.\nrewrite (card_GL _ (ltn0Sn n.-1)) card_ord Fp_cast // big_add1 /=.\npose p'gt0 m := m > 0 /\\ logn p m = 0%N.\nsuffices [Pgt0 p'P]: p'gt0 (\\prod_(0 <= i < n.-1.+1) (p ^ i.+1 - 1))%N.\n  by rewrite logn_mul // p'P pfactorK //; case n.\napply big_prop => [|m1 m2 [m10 p'm1] [m20]|i _]; rewrite {}/p'gt0 ?logn1 //.\n  by rewrite muln_gt0 m10 logn_mul ?p'm1.\nrewrite lognE -if_neg subn_gt0 p_pr /= -{1 2}(exp1n i.+1) ltn_exp2r // p_gt1.\nby rewrite dvdn_subr ?dvdn_exp // gtnNdvd.\nQed.\n\n(* Parametricity at the field level (note that the unit/inverse are only     *)\n(* mapped at this level).                                                    *)\nSection MapFieldMatrix.\n\nVariables (aF rF : fieldType) (f : aF -> rF).\nHypothesis fRM : GRing.morphism f.\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\n\nLemma map_mx_inj : forall m n, injective ((map_mx f) m n).\nProof.\nmove=> m n A B; move/matrixP=> eq_AB; apply/matrixP=> i j.\nby move/(_ i j): eq_AB; rewrite !mxE; exact: fieldM_inj.\nQed.\n\nLemma map_unitmx : forall n (A : 'M_n), (A^f \\in unitmx) = (A \\in unitmx).\nProof. by move=> n A; rewrite unitmxE det_map_mx // fieldM_unit // -unitfE. Qed.\n\nLemma map_mx_unit : forall n' (A : 'M_n'.+1), GRing.unit A^f = GRing.unit A.\nProof. by move=> n'; exact: map_unitmx. Qed.\n\nLemma map_invmx : forall n (A : 'M_n), (invmx A)^f = invmx A^f.\nProof.\nmove=> n A; rewrite /invmx map_unitmx (fun_if ((map_mx f) n n)).\nby rewrite map_mxZ // map_mx_adj // det_map_mx // fieldM_inv. \nQed.\n\nLemma map_mx_inv : forall n' (A : 'M_n'.+1), A^-1^f = A^f^-1.\nProof. by move=> n'; exact: map_invmx. Qed.\n\nLemma emxrank_map : forall m n (A : 'M_(m, n)),\n  emxrank A^f = ((col_ebase A)^f, (row_ebase A)^f, \\rank A).\nProof.\nrewrite /row_ebase /col_ebase /mxrank.\nelim=> [|m IHm] [|n] A /=; rewrite ?map_mx1 //.\nset pAnz := fun k => A k.1 k.2 != 0.\nrewrite (@eq_pick _ _ pAnz) => [|k]; last by rewrite mxE fieldM_eq0.\ncase: {+}(pick _) => [[i j]|]; last by rewrite !map_mx1.\nrewrite mxE -fieldM_inv // -map_xcol -map_xrow -map_dlsubmx -map_drsubmx.\nrewrite -map_ursubmx -map_mxZ // -map_mxM // -map_mx_sub // {}IHm /=.\ncase: {+}(emxrank _) => [[L U] r] /=; rewrite map_xrow map_xcol.\nby rewrite !(@map_block_mx _ _ f 1 _ 1) !map_mx0 ?map_mx1 ?map_scalar_mx.\nQed.\n\nLemma mxrank_map : forall m n (A : 'M_(m, n)), \\rank A^f = \\rank A.\nProof. by move=> m n A; rewrite {1}/mxrank emxrank_map. Qed.\n\nLemma map_mx_eq0 : forall m n (A : 'M_(m, n)), (A^f == 0) = (A == 0).\nProof. by move=> m n A; rewrite -!mxrank_eq0 mxrank_map. Qed.\n\nLemma row_free_map : forall m n (A : 'M_(m, n)), row_free A^f = row_free A.\nProof. by move=> m n A; rewrite /row_free mxrank_map. Qed.\n\nLemma row_full_map : forall m n (A : 'M_(m, n)), row_full A^f = row_full A.\nProof. by move=> m n A; rewrite /row_full mxrank_map. Qed.\n\nLemma map_row_ebase : forall m n (A : 'M_(m, n)),\n  (row_ebase A)^f = row_ebase A^f.\nProof. by move=> m n A; rewrite {2}/row_ebase emxrank_map. Qed.\n\nLemma map_col_ebase : forall m n (A : 'M_(m, n)),\n  (col_ebase A)^f = col_ebase A^f.\nProof. by move=> m n A; rewrite {2}/col_ebase emxrank_map. Qed.\n\nLemma map_row_base : forall m n (A : 'M_(m, n)),\n  (row_base A)^f = castmx (mxrank_map A, erefl n) (row_base A^f).\nProof.\nmove=> m n A; move: (mxrank_map A); rewrite {2}/row_base mxrank_map => eqrr.\nby rewrite castmx_id map_mxM // map_pid_mx // map_row_ebase.\nQed.\n\nLemma map_col_base : forall m n (A : 'M_(m, n)),\n  (col_base A)^f = castmx (erefl m, mxrank_map A) (col_base A^f).\nProof.\nmove=> m n A; move: (mxrank_map A); rewrite {2}/col_base mxrank_map => eqrr.\nby rewrite castmx_id map_mxM // map_pid_mx // map_col_ebase.\nQed.\n\nLemma map_pinvmx : forall m n (A : 'M_(m, n)), (pinvmx A)^f = pinvmx A^f.\nProof.\nmove=> m n A; rewrite !map_mxM // !map_invmx map_row_ebase map_col_ebase.\nby rewrite map_pid_mx // -mxrank_map.\nQed.\n\nLemma map_kermx : forall m n (A : 'M_(m, n)), (kermx A)^f = kermx A^f.\nProof.\nmove=> m n A; rewrite !map_mxM // map_invmx map_col_ebase -mxrank_map.\nby rewrite map_copid_mx.\nQed.\n\nLemma map_cokermx : forall m n (A : 'M_(m, n)), (cokermx A)^f = cokermx A^f.\nProof.\nmove=> m n A; rewrite !map_mxM // map_invmx map_row_ebase -mxrank_map.\nby rewrite map_copid_mx.\nQed.\n\nLemma subsetmx_map : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A^f <= B^f)%MS = (A <= B)%MS.\nProof.\nby move=> m1 m2 n A B; rewrite !subsetmxE -map_cokermx -map_mxM // map_mx_eq0.\nQed.\n\nLemma eqmx_map : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (A^f :=: B^f)%MS <-> (A :=: B)%MS.\nProof.\nmove=> m1 m2 n A B; split=> [|eqAB].\n  by move/eqmxP; rewrite !subsetmx_map; move/eqmxP.\nby apply/eqmxP; rewrite !subsetmx_map !eqAB !subsetmx_refl.\nQed.\n\nLemma map_genmx : forall m n (A : 'M_(m, n)), (<<A>>^f :=: <<A^f>>)%MS.\nProof.\nby move=> m n A; apply/eqmxP; rewrite !(genmxE, subsetmx_map) andbb.\nQed.\n\nLemma map_sumsmx : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (((A + B)%MS)^f :=: A^f + B^f)%MS.\nProof.\nmove=> m1 m2 n A B; apply/eqmxP; rewrite !sumsmxE -map_col_mx !subsetmx_map.\nby rewrite !sumsmxE andbb.\nQed.\n\nLet map_capmx_gen : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  (capmx_gen A B)^f = capmx_gen A^f B^f.\nProof.\nby move=> m1 m2 n A B; rewrite map_mxM // map_lsubmx map_kermx map_col_mx.\nQed.\n\nLemma map_capmx : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  ((A :&: B)^f :=: A^f :&: B^f)%MS.\nProof.\nmove=> m1 m2 n A B; apply/eqmxP; rewrite !capmxE -map_capmx_gen.\nby rewrite !subsetmx_map -!capmxE andbb.\nQed.\n\nLemma map_complmx : forall m n (A : 'M_(m, n)), (A^C^f = A^f^C)%MS.\nProof.\nby move=> m n A; rewrite map_mxM // map_row_ebase -mxrank_map map_copid_mx.\nQed.\n\nLemma map_diffmx : forall m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)),\n  ((A :\\: B)^f :=: A^f :\\: B^f)%MS.\nProof.\nmove=> m1 m2 n A B; apply/eqmxP; rewrite !diffmxE -map_capmx_gen -map_complmx.\nby rewrite -!map_capmx !subsetmx_map -!diffmxE andbb.\nQed.\n\nEnd MapFieldMatrix.", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/ssreflect/attic/ssreflect12_trunk/theories/matrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.6925727949042982}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Well-founded relations                                                  *\n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibTactics LibLogic\n LibProd LibSum LibRelation LibNat LibInt.\n\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Compatibility *)\n\n(** Coq's stdlib Prelude defines:\n\n Inductive Acc A (R:A->A->Prop) (x:A) : Prop :=\n   | Acc_intro : (forall (y:A), R y x -> Acc y) -> Acc x.\n\n Definition well_founded A (R:A->A->Prop) := \n    forall (x:A), Acc x.\n\n*)\n\n(** TLC introduces [wf] as a shorter name for [well_founded], both\n    for conciseness and for tactics to specifically recognize \n    this symbol. *)\n\nDefinition wf := well_founded.\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Tactics *)\n\n(** [auto with wf] attempts to unfold the names of \n    the relations given as argument to [wf]. *)\n\nHint Extern 1 (wf ?R) => progress (unfold R) : wf.\n\n(** [solve_wf] is a shorthand for solving goals using\n    [auto with wf], aimed to prove goals of the form [wf R]. *)\n\nTactic Notation \"solve_wf\" :=\n  solve [ auto with wf ].\n\n\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(* * Measures *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Definition *)\n\n(** [measure f] is a well-founded binary relation which \n    relates [x] to [y] when [f x < f y], at type [nat]. *)\n\nDefinition measure A (f:A->nat) : binary A :=\n  fun x1 x2 => (f x1 < f x2).\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Properties *)\n\nSection Measure.\nVariables (A : Type).\nImplicit Type f : A -> nat.\n\nLemma wf_measure : forall f, \n  wf (measure f).\nProof using.\n  intros f a. gen_eq n: (f a). gen a. pattern n.\n  apply peano_induction. clear n. introv IH Eq.\n  apply Acc_intro. introv H. unfolds in H.\n  rewrite <- Eq in H. apply* IH.\nQed.\n\nLemma trans_measure : forall (f : A -> nat), \n  trans (measure f).\nProof using. intros. unfold measure, trans. intros. nat_math. Qed.\n\n(* -- LATER: Lemma order_measure *)\n\nEnd Measure.\n\nHint Resolve wf_measure : wf.\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Measure on pairs *)\n\nDefinition measure2 A1 A2 (f : A1 -> A2 -> nat) : binary (A1*A2) :=\n  fun p1 p2 => let (x1,y1) := p1 in \n               let (x2,y2) := p2 in \n               (f x1 y1 < f x2 y2).\n\nLemma wf_measure2 : forall A1 A2 (f:A1->A2->nat), \n  wf (measure2 f).\nProof using.\n  intros A1 A2 f [x1 x2]. apply (@measure_induction _ (uncurry2 f)). clear x1 x2.\n  intros [x1 x2] H. apply Acc_intro. intros [y1 y2] Lt. apply~ H.\nQed.\n\nHint Resolve wf_measure2 : wf.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Extension of LibTactic's [induction_wf] tactic for [measure] *)\n\n(** -- LATER: introduce a hook in LibTactics to reduce copy-paste *)\n\nLtac induction_wf_core_then IH E X cont ::=\n  let T := type of E in\n  let T := eval hnf in T in\n  let clearX tt :=\n    first [ clear X | fail 3 \"the variable on which the induction is done appears in the hypotheses\" ] in\n  match T with\n  (* To support for [measure] from LibWf, we add the next two lines: *)\n  | ?A -> nat =>\n     induction_wf_core_then IH (wf_measure E) X cont\n  (* End of modification *)\n  | ?A -> ?A -> Prop =>\n     pattern X;\n     first [\n       applys well_founded_ind E;\n       clearX tt;\n       [ (* Support for [wf] from LibWf *)\n         change well_founded with wf; auto with wf\n       | intros X IH; cont tt ]\n     | fail 2 ]\n  | _ =>\n    pattern X;\n    applys well_founded_ind E;\n    clearX tt;\n    intros X IH;\n    cont tt\n  end.\n\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Construction of well-founded relations *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Empty relation *)\n\nLemma wf_empty : forall A,\n  wf (@empty A).\nProof using. intros_all. constructor. introv H. false. Qed.\n\nHint Resolve wf_empty : wf.\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Inclusion *)\n\n(** Well-foundedness preserved by inclusion *)\n\nLemma wf_of_rel_incl : forall A (R1 R2 : binary A),\n  wf R1 -> \n  rel_incl R2 R1 -> \n  wf R2.\nProof using.\n  introv W1 Inc. intros x.\n  pattern x. apply (well_founded_ind W1). clear x.\n  intros x IH. constructor. intros. apply IH. apply~ Inc.\nQed.\n\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(* * Classic well-founded relations on [nat] *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** [Peano.lt] on [nat] *)\n\n(** The relation \"less than\" on natural numbers is well_founded. *)\n\nLemma wf_peano_lt : wf Peano.lt.\nProof using.\n  intros x.\n  induction x using peano_induction. apply~ Acc_intro.\n    intros. applys H. math.\nQed.\n\nHint Resolve wf_peano_lt : wf.\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** [lt] on [nat] *)\n\n(** The relation \"less than\" on natural numbers is well_founded. *)\n\nLemma wf_lt : @wf nat lt.\nProof using.\n  intros x.\n  induction x using peano_induction. apply~ Acc_intro.\nQed.\n\nHint Resolve wf_lt : wf.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** The relation \"greater than\" on the set of\n       natural number lower than a fixed upper bound. *)\n\nDefinition nat_upto (b:nat) :=\n  fun (n m:nat) => (n <= b)%nat /\\ (m < n)%nat.\n\nLemma nat_upto_eq : forall (b n m:nat),\n  nat_upto b n m = ((n <= b)%nat /\\ (m < n)%nat).\nProof using. auto. Qed.\n\nLemma wf_nat_upto : forall (b:nat),\n  wf (nat_upto b).\nProof using.\n  intros b n.\n  induction_wf: (wf_measure (fun n => (b-n)%nat)) n.\n  apply Acc_intro. introv [H1 H2]. apply IH.\n  hnf. nat_math.\nQed.\n\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(* * Classic well-founded relations on [int] *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** The relation \"less than\" on the set of\n       integers greater than a fixed lower bound. *)\n\nDefinition downto (b:int) :=\n  fun (n m:int) => (b <= n) /\\ (n < m).\n\nLemma downto_eq : forall (b n m:int),\n  downto b n m = (b <= n /\\ n < m).\nProof using. auto. Qed.\n\nLemma downto_intro : forall (b n m:int),\n  b <= n ->\n  n < m -> \n  downto b n m.\nProof using. split~. Qed.\n\nLemma wf_downto : forall (b:int), \n  wf (downto b).\nProof using.\n  intros b n.\n  induction_wf: (wf_measure (fun n => Zabs_nat (n-b))) n.\n  apply Acc_intro. introv [H1 H2]. apply IH.\n  unfolds. applys lt_abs_abs; math.\nQed.\n\nHint Resolve wf_downto : wf.\nHint Unfold downto.\nHint Extern 1 (downto _ _ _) => math : maths.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** The relation \"greater than\" on the set of\n       integers lower than a fixed upper bound. *)\n\nDefinition upto (b:int) :=\n  fun (n m:int) => (n <= b) /\\ (m < n).\n\nLemma upto_eq : forall b n m,\n  upto b n m = ((n <= b) /\\ (m < n)).\nProof using. auto. Qed.\n\nLemma upto_intro : forall b n m,\n  n <= b -> \n  m < n -> \n  upto b n m.\nProof using. split~. Qed.\n\nLemma wf_upto : forall n, \n  wf (upto n).\nProof using.\n  intros b n.\n  induction_wf: (wf_measure (fun n => Zabs_nat (b-n))) n.\n  apply Acc_intro. introv [H1 H2]. apply IH.\n  applys lt_abs_abs; math.\nQed.\n\nHint Resolve wf_upto : wf.\nHint Unfold upto.\nHint Extern 1 (upto _ _ _) => math : maths.\n\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Inverse projections *)\n\nSection UnprojWf.\nVariables (A1 A2 A3 A4 A5 : Type).\n\nLemma wf_unproj21 : forall (R:binary A1),\n  wf R ->\n  wf (unproj21 A2 R).\nProof using.\n  intros R H [x1 x2]. gen x2.\n  induction_wf IH: H x1. constructor. intros [y1 y2]. auto.\nQed.\n\nLemma wf_unproj22 : forall (R:binary A2),\n  wf R ->\n  wf (unproj22 A1 R).\nProof using.\n  intros R H [x1 x2]. gen x1.\n  induction_wf IH: H x2. constructor. intros [y1 y2]. auto.\nQed.\n\nLemma wf_unproj31 : forall (R:binary A1),\n  wf R ->\n  wf (unproj31 A2 A3 R).\nProof using.\n  intros R H [[x1 x2] x3]. gen x2 x3.\n  induction_wf IH: H x1. constructor. intros [[y1 y2] y3]. auto.\nQed.\n\nLemma wf_unproj32 : forall (R:binary A2),\n  wf R ->\n  wf (unproj32 A1 A3 R).\nProof using.\n  intros R H [[x1 x2] x3]. gen x1 x3.\n  induction_wf IH: H x2. constructor. intros [[y1 y2] y3]. auto.\nQed.\n\nLemma wf_unproj33 : forall (R:binary A3),\n  wf R ->\n  wf (unproj33 A1 A2 R).\nProof using.\n  intros R H [[x1 x2] x3]. gen x1 x2.\n  induction_wf IH: H x3. constructor. intros [[y1 y2] y3]. auto.\nQed.\n\nLemma wf_unproj41 : forall (R:binary A1),\n  wf R ->\n  wf (unproj41 A2 A3 A4 R).\nProof using.\n  intros R H [[[x1 x2] x3] x4]. gen x2 x3 x4.\n  induction_wf IH: H x1. constructor. intros [[[y1 y2] y3] y4]. auto.\nQed.\n\nLemma wf_unproj42 : forall (R:binary A2),\n  wf R ->\n  wf (unproj42 A1 A3 A4 R).\nProof using.\n  intros R H [[[x1 x2] x3] x4]. gen x1 x3 x4.\n  induction_wf IH: H x2. constructor. intros [[[y1 y2] y3] y4]. auto.\nQed.\n\nLemma wf_unproj43 : forall (R:binary A3),\n  wf R ->\n  wf (unproj43 A1 A2 A4 R).\nProof using.\n  intros R H [[[x1 x2] x3] x4]. gen x1 x2 x4.\n  induction_wf IH: H x3. constructor. intros [[[y1 y2] y3] y4]. auto.\nQed.\n\nLemma wf_unproj44 : forall (R:binary A4),\n  wf R ->\n  wf (unproj44 A1 A2 A3 R).\nProof using.\n  intros R H [[[x1 x2] x3] x4]. gen x1 x2 x3.\n  induction_wf IH: H x4. constructor. intros [[[y1 y2] y3] y4]. auto.\nQed.\n\nLemma wf_unproj51 : forall (R:binary A1),\n  wf R ->\n  wf (unproj51 A2 A3 A4 A5 R).\nProof using.\n  intros R H [[[[x1 x2] x3] x4] x5]. gen x2 x3 x4 x5.\n  induction_wf IH: H x1. constructor. intros [[[[y1 y2] y3] y4] y5]. auto.\nQed.\n\nEnd UnprojWf.\n\nHint Resolve\n  wf_unproj21 wf_unproj22\n  wf_unproj31 wf_unproj32 wf_unproj33\n  wf_unproj41 wf_unproj42 wf_unproj43 wf_unproj44\n  wf_unproj51 : wf.\n\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Lexicographical product *)\n\nLemma wf_lexico2 : forall A1 A2\n (R1:binary A1) (R2:binary A2),\n  wf R1 -> \n  wf R2 -> \n  wf (lexico2 R1 R2).\nProof using.\n  introv W1 W2. intros [x1 x2]. gen x2.\n  induction_wf IH1: W1 x1. intros.\n  induction_wf IH2: W2 x2. constructor. intros [y1 y2] H.\n  simpls. destruct H as [H1|[H1 H2]].\n  apply~ IH1. rewrite H1. apply~ IH2.\nQed.\n\nLemma wf_lexico3 : forall A1 A2 A3\n (R1:binary A1) (R2:binary A2) (R3:binary A3),\n  wf R1 -> \n  wf R2 -> \n  wf R3 ->\n  wf (lexico3 R1 R2 R3).\nProof using.\n  intros. apply~ wf_lexico2. apply~ wf_lexico2.\nQed.\n\nLemma wf_lexico4 : forall A1 A2 A3 A4\n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4),\n  wf R1 -> \n  wf R2 -> \n  wf R3 -> \n  wf R4 ->\n  wf (lexico4 R1 R2 R3 R4).\nProof using.\n  intros. apply~ wf_lexico3. apply~ wf_lexico2.\nQed.\n\nHint Resolve wf_lexico2 wf_lexico3 wf_lexico4 : wf.\n\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Symmetric product *)\n\nLemma wf_prod2_of_wf_1 : forall (A1 A2:Type)\n (R1:binary A1) (R2:binary A2),\n  wf R1 -> \n  wf (prod2 R1 R2).\nProof using.\n  introv W1. intros [x1 x2].\n  gen x2. induction_wf IH: W1 x1. intros.\n  constructor. intros [y1 y2] [E1 E2]. apply~ IH.\nQed.\n\nLemma wf_prod2_of_wf_2 : forall (A1 A2:Type)\n (R1:binary A1) (R2:binary A2),\n  wf R2 -> \n  wf (prod2 R1 R2).\nProof using.\n  introv W2. intros [x1 x2].\n  gen x1. induction_wf IH: W2 x2. intros.\n  constructor. intros [y1 y2] [E1 E2]. apply~ IH.\nQed.\n\nLemma wf_prod3_of_wf_1 : forall (A1 A2 A3:Type)\n (R1:binary A1) (R2:binary A2) (R3:binary A3),\n  wf R1 -> \n  wf (prod3 R1 R2 R3).\nProof using. intros. apply wf_prod2_of_wf_1. apply~ wf_prod2_of_wf_1. Qed.\n\nLemma wf_prod3_of_wf_2 : forall (A1 A2 A3:Type)\n (R1:binary A1) (R2:binary A2) (R3:binary A3),\n  wf R2 -> \n  wf (prod3 R1 R2 R3).\nProof using. intros. apply wf_prod2_of_wf_1. apply~ wf_prod2_of_wf_2. Qed.\n\nLemma wf_prod3_of_wf_3 : forall (A1 A2 A3:Type)\n (R1:binary A1) (R2:binary A2) (R3:binary A3),\n  wf R3 -> \n  wf (prod3 R1 R2 R3).\nProof using. intros. apply~ wf_prod2_of_wf_2. Qed.\n\nLemma wf_prod4_of_wf_1 : forall (A1 A2 A3 A4:Type)\n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4),\n  wf R1 -> \n  wf (prod4 R1 R2 R3 R4).\nProof using. intros. apply wf_prod2_of_wf_1. apply~ wf_prod3_of_wf_1. Qed.\n\nLemma wf_prod4_of_wf_2 : forall (A1 A2 A3 A4:Type)\n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4),\n  wf R2 -> \n  wf (prod4 R1 R2 R3 R4).\nProof using. intros. apply wf_prod2_of_wf_1. apply~ wf_prod3_of_wf_2. Qed.\n\nLemma wf_prod4_of_wf_3 : forall (A1 A2 A3 A4:Type)\n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4),\n  wf R3 -> \n  wf (prod4 R1 R2 R3 R4).\nProof using. intros. apply wf_prod2_of_wf_1. apply~ wf_prod3_of_wf_3. Qed.\n\nLemma wf_prod4_of_wf_4 : forall (A1 A2 A3 A4:Type)\n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4),\n  wf R4 -> \n  wf (prod4 R1 R2 R3 R4).\nProof using. intros. apply~ wf_prod2_of_wf_2. Qed.\n\nHint Resolve\n  wf_prod2_of_wf_1 wf_prod2_of_wf_2\n  wf_prod3_of_wf_1 wf_prod3_of_wf_2 wf_prod3_of_wf_3\n  wf_prod4_of_wf_1 wf_prod4_of_wf_2 wf_prod4_of_wf_3 wf_prod4_of_wf_4 : wf.\n\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Well-foundedness of a function image *)\n\nLemma wf_rel_preimage : forall A B (R:binary B) (f:A->B),\n  wf R -> \n  wf (rel_preimage R f).\nProof using.\n  introv W. intros x. gen_eq a: (f x). gen x.\n  induction_wf: W a. introv E. constructors.\n  intros y Hy. subst a. hnf in Hy. applys* IH.\nQed.\n\nHint Resolve wf_rel_preimage : wf.\n\n\n(* ********************************************************************** *)\n(* ********************************************************************** *)\n(* ********************************************************************** *)\n(* TEMPORARY *)\n\n(* begin hide *)\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Union *)\n\n(* --TODO..\n\nSection WfUnion.\n  Variables (A : Type).\n  Variables R1 R2 : binary A.\n\n  Notation Union := (union A R1 R2).\n\n  Remark strip_commut :\n    commut A R1 R2 ->\n    forall x y:A,\n      clos_trans A R1 y x ->\n      forall z:A, R2 z y ->  exists2 y' : A, R2 y' x & clos_trans A R1 z y'.\n  Proof using.\n    induction 2 as [x y| x y z H0 IH1 H1 IH2]; intros.\n    elim H with y x z; auto with sets; intros x0 H2 H3.\n    exists x0; auto with sets.\n\n    elim IH1 with z0; auto with sets; intros.\n    elim IH2 with x0; auto with sets; intros.\n    exists x1; auto with sets.\n    apply t_trans with x0; auto with sets.\n  Qed.\n\n\n  Lemma Acc_union :\n    commut A R1 R2 ->\n    (forall x:A, Acc R2 x -> Acc R1 x) -> forall a:A, Acc R2 a -> Acc Union a.\n  Proof using.\n    induction 3 as [x H1 H2].\n    apply Acc_intro; intros.\n    elim H3; intros; auto with sets.\n    cut (clos_trans A R1 y x); auto with sets.\n    elimtype (Acc (clos_trans A R1) y); intros.\n    apply Acc_intro; intros.\n    elim H8; intros.\n    apply H6; auto with sets.\n    apply t_trans with x0; auto with sets.\n\n    elim strip_commut with x x0 y0; auto with sets; intros.\n    apply Acc_inv_trans with x1; auto with sets.\n    unfold union in |- *.\n    elim H11; auto with sets; intros.\n    apply t_trans with y1; auto with sets.\n\n    apply (Acc_clos_trans A).\n    apply Acc_inv with x; auto with sets.\n    apply H0.\n    apply Acc_intro; auto with sets.\n  Qed.\n\n\n  Theorem wf_union :\n    commut A R1 R2 -> well_founded R1 -> well_founded R2 -> well_founded Union.\n  Proof using.\n    unfold well_founded in |- *.\n    intros.\n    apply Acc_union; auto with sets.\n  Qed.\n\nEnd WfUnion.\n\n*)\n\n(* --TODO: Disjoint union, useful? *)\n\n(* end hide *)\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Transitive closure *)\n\nLemma wf_tclosure : forall A (R:binary A),\n  wf R ->\n  wf (tclosure R).\nProof using.\n  unfold wf, well_founded.\n  introv HAcc. intro a. specializes HAcc a. generalize dependent a.\n  induction 1 as [ a _ IH ].\n  constructor. intros b Hba.\n  generalize a b Hba IH. clear a b Hba IH.\n  induction 1; eauto using Acc_inv.\nQed.\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/LibWf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.6925647344099359}}
{"text": "MacBook-Air:~ billw$ /Applications/CoqIDE_8.4pl5.app/Contents/Resources/bin/coqtop\nWelcome to Coq 8.4pl5 (October 2014)\n\nCoq < Section predicate_calculus.\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 < 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\nCoq < \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/convert/002.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.6925647276186842}}
{"text": "Require Import Vector.\n\n\nFixpoint vector_nth {A:Type}(n:nat)(p:nat)(v:t A p){struct v}\n                  : option A :=\n  match n,v  with\n    _   , nil _ => None\n  | 0   , cons _ b  _ _ => Some b\n  | S n', cons _ _  p' v' => vector_nth  n'  p' v'\n  end.\n\n(* examples *)\n\nArguments cons {A} h {n}  _ .\nArguments nil {A}.\nArguments vector_nth {A} n {p} v.\n\nDefinition v0 := cons true  (cons false  (cons false  nil)).\n\nLemma test0 : vector_nth 2 v0  = Some false.\nProof. trivial. Qed.\n\nLemma test1 : vector_nth 7 v0  = None.\nProof. trivial. Qed.\n\n\nTheorem nth_size : forall {A:Type}(p:nat)(v:t A p)(n:nat), \n  vector_nth n v  = None <-> p <= n.\nProof.\n induction v;simpl; auto. \n - intro n; case n; simpl; split; auto with arith. \n - intro n0;case n0;simpl;split.\n   +  discriminate.\n   +  inversion 1.\n   +  case (IHv n1);auto with arith.\n   +  case (IHv n1);auto with arith.\nQed.\n\n\n\n\n\n\n\n \n\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/vectors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.6925647243581415}}
{"text": "(** Transparent versions of wf_incl and wf_inverse_image \n*)\n\n\nRequire Export Relation_Definitions.\n\nLemma wf_incl_transparent  :\nforall (A : Type) (R1 R2 : A -> A -> Prop),\nRelation_Definitions.inclusion A R1 R2 -> well_founded R2 -> well_founded R1.\nProof.\n intros A R1 R2 H H0 a;  induction (H0 a). \n split;  auto.\nDefined.\n\n\nSection Inverse_Image_transp. (* adapted from S.L. *)\n\n  Variables A B : Type.\n  Variable R : B -> B -> Prop.\n  Variable f : A -> B.\n\n  Let Rof (x y:A) : Prop := R (f x) (f y).\n\n  Remark Acc_lemma : forall y:B, Acc R y -> forall x:A, y = f x -> Acc Rof x.\n  Proof.\n    induction 1 as [y _ IHAcc]; intros x H.\n    apply Acc_intro; intros y0 H1.\n    apply (IHAcc (f y0)); try trivial.\n    rewrite H; trivial.\n   Defined.\n\n  Lemma Acc_inverse_image : forall x:A, Acc R (f x) -> Acc Rof x.\n  Proof.\n    intros; apply (Acc_lemma (f x)); trivial.\n  Defined.\n\n  Theorem wf_inverse_image_transparent : well_founded R -> well_founded Rof.\n  Proof.\n    red; intros; apply Acc_inverse_image; auto.\n  Defined.\n\nEnd Inverse_Image_transp.\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/Wf_transparent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.6925246032133766}}
{"text": "(* Chap 12 Imp *)\n(* SIMPLE IMPERATIVE PROGRAMS *)\nSet Warnings \"-notation-overridden,-parsing\".\nFrom Coq Require Import Bool.Bool.\nFrom Coq Require Import Init.Nat.\nFrom Coq Require Import Arith.Arith.\nFrom Coq Require Import Arith.EqNat.\nFrom Coq Require Import omega.Omega.\nFrom Coq Require Import Lists.List.\nFrom Coq Require Import Strings.String.\nImport ListNotations.\nFrom LF Require Import Maps.\n\n(* Chap 12.1 Arithmetic and Boolean Expressions *)\n(* Chap 12.1.1 Syntax *)\nModule AExp.\n\nInductive aexp : Type :=\n  | ANum (n: nat)\n  | APlus (a1 a2: aexp)\n  | AMinus (a1 a2: aexp)\n  | AMult (a1 a2: aexp).\n\nInductive bexp : Type :=\n  | BTrue\n  | BFalse\n  | BEq (a1 a2: aexp)\n  | BLe (a1 a2: aexp)\n  | BNot (b: bexp)\n  | BAnd (b1 b2: bexp).\n\n(* Chap 12.1.2 Evaluation *)\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.\n  simpl. reflexivity.\nQed.\n\nFixpoint beval (b: bexp) : bool :=\n  match b with\n  | BTrue => true\n  | BFalse => false\n  | BEq a1 a2 => (aeval a1) =? (aeval a2)\n  | BLe a1 a2 => (aeval a1) <=? (aeval a2)\n  | BNot b1 => negb (beval b1)\n  | BAnd b1 b2 => andb (beval b1) (beval b2)\n  end.\n\n(* Chap 12.1.3 Optimization *)\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) (APlus (ANum 0) (APlus (ANum 0) (ANum 1)))) = APlus (ANum 2) (ANum 1).\nProof.\n  simpl. reflexivity.\nQed.\n\nTheorem optimize_0plus_sound: forall a,\n  aeval (optimize_0plus a) = aeval a.\nProof.\n  intros.\n  induction a.\n  - simpl. reflexivity.\n  - destruct a1 eqn: Ea1.\n    + destruct n eqn: En.\n      * simpl. apply IHa2.\n      * simpl. rewrite <- IHa2. reflexivity.\n    + simpl in *. rewrite IHa1.\n      rewrite <- IHa2. reflexivity.\n    + simpl in *. rewrite IHa1. rewrite IHa2. reflexivity.\n    + simpl in *. rewrite IHa1. rewrite IHa2. reflexivity.\n  - simpl. rewrite <- IHa1, IHa2. reflexivity.\n  - simpl. rewrite <- IHa1, IHa2. reflexivity.\nQed.\n\n(* Chap 12.2 Coq Automation *)\n(* Chap 12.2.1 Tacticals *)\n(* Chap 12.2.1.1 The 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.\n  apply H.\nQed.\n\n(* Chap 12.2.1.2 The ; Tactical (Simple Form) *)\nLemma foo: forall n, 0 <=? n = true.\nProof.\n  intros.\n  destruct n.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nLemma foo': forall n, 0 <=? n = true.\nProof.\n  intros.\n  destruct n; simpl; reflexivity.\nQed.\n\nTheorem optimize_0plus_sound': forall a,\n  aeval (optimize_0plus a) = aeval a.\nProof.\n  intros.\n  induction a;\n  try (simpl; rewrite IHa1; rewrite IHa2; reflexivity).\n  - reflexivity.\n  - destruct a1 eqn: Ea1;\n    try (simpl in *; rewrite IHa1; rewrite IHa2; reflexivity).\n    + destruct n eqn: En; simpl; rewrite IHa2; reflexivity.\nQed.\n\nTheorem optimize_0plus_sound'': forall a,\n  aeval (optimize_0plus a) = aeval a.\nProof.\n  intros a.\n  induction a;\n  try (simpl; rewrite IHa1; rewrite IHa2; reflexivity);\n  try reflexivity.\n  - destruct a1; try (simpl in *; rewrite IHa1; rewrite IHa2; reflexivity).\n    + destruct n; simpl; rewrite IHa2; reflexivity.\nQed.\n\n(* Chap 12.2.1.3 The ; Tactical (General Form) *)\n\n(* Chap 12.2.1.4 The repeat Tactical *)\nTheorem In10: In 10 [1;2;3;4;5;6;7;8;9;10].\nProof. repeat (try (left; reflexivity); right). Qed.\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 optimize_0plus_b_sound *)\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 b1\n  | BAnd b1 b2 => BAnd b1 b2\n  end.\n\nTheorem optimize_0plus_b_sound: forall b,\n  beval (optimize_0plus_b b) = beval b.\nProof.\n  intros.\n  induction b; simpl;\n  try (rewrite optimize_0plus_sound);\n  try (rewrite optimize_0plus_sound);\n  reflexivity.\nQed.\n\n(* Exercise optimize *)\nFixpoint optimize_and_false (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_and_false b1)\n  | BAnd b1 b2 =>\n    match b1 with\n    | BTrue => b2\n    | BFalse => BFalse\n    | _ => BAnd (optimize_and_false b1) (optimize_and_false b2)\n    end\n  end.\n\nTheorem optimize_and_false_sound: forall b,\n  beval (optimize_and_false b) = beval b.\nProof.\n  intros.\n  induction b; simpl;\n  try (rewrite optimize_0plus_sound);\n  try (rewrite optimize_0plus_sound);\n  try (rewrite IHb);\n  try (reflexivity).\n  - destruct b1; simpl in *;\n    try (rewrite IHb1);\n    try (rewrite IHb2);\n    try (rewrite optimize_0plus_sound);\n    try (rewrite optimize_0plus_sound);\n    try (reflexivity).\nQed.\n\n(* Chap 12.2.2 Defining New Tactic Notations *)\nTactic Notation \"simpl_and_try\" tactic(c) :=\n  simpl; try c.\n\n(* Chap 12.2.3 The omega Tactic *)\nExample silly_presburger_example: forall m n o p,\n  m + n <= n + o /\\ o + 3 = p + 3 -> m <= p.\nProof.\n  intros.\n  omega.\nQed.\n\n(* Chap 12.2.4 A Few More Handy Tactics *)\n(*\n  clear H: Delete hypothesis H from the context.\n  subst x: For a variable x, find an assumption x = e or e = x in the context, \n    replace x with e throughout the context and current goal, and clear the \n    assumption.\n  subst: Substitute away all assumptions of the form x = e or e = x (where x is\n    a variable).\n  rename... into...: Change the name of a hypothesis in the proof context. For \n    example, if the context includes a variable named x, then rename x into y \n    will change all occurrences of x to y.\n  assumption: Try to find a hypothesis H in the context that exactly matches the\n    goal; if one is found, behave like apply H.\n  contradiction: Try to find a hypothesis H in the current context that is logically\n    equivalent to False. If one is found, solve the goal.\n  constructor: Try to find a constructor c (from some Inductive definition in the \n    current environment) that can be applied to solve the current goal. If one is \n    found, behave like apply c.\n*)\n\n(* Chap 12.3 Evaluation as a Relation *)\nModule aevalR_first_try.\nInductive aevalR: aexp -> nat -> Prop :=\n  | E_ANum n: aevalR (ANum n) n\n  | E_APlus (e1 e2: aexp) (n1 n2: nat): aevalR e1 n1 -> aevalR e2 n2 -> aevalR (APlus e1 e2) (n1 + n2)\n  | E_AMinus (e1 e2: aexp) (n1 n2: nat): aevalR e1 n1 -> aevalR e2 n2 -> aevalR (AMinus e1 e2) (n1 - n2)\n  | E_AMult (e1 e2: aexp) (n1 n2: nat): aevalR e1 n1 -> aevalR e2 n2 -> aevalR (AMult e1 e2) (n1 * n2).\n\nModule TooHardToRead.\nInductive aevalR: aexp -> nat -> Prop :=\n  | E_ANum n: aevalR (ANum n) n\n  | E_APlus (e1 e2: aexp) (n1 n2: nat) (H1: aevalR e1 n1) (H2: aevalR e2 n2):\n      aevalR (APlus e1 e2) (n1 + n2)\n  | E_AMinus (e1 e2: aexp) (n1 n2: nat) (H1: aevalR e1 n1) (H2: aevalR e2 n2):\n      aevalR (AMinus e1 e2) (n1 - n2)\n  | E_AMult (e1 e2: aexp) (n1 n2: nat) (H1: aevalR e1 n1) (H2: aevalR e2 n2):\n      aevalR (AMult e1 e2) (n1 * n2).\nEnd TooHardToRead.\n\nNotation \"e ‘\\\\' n\" := (aevalR e n)\n  (at level 50, left associativity) : 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): (ANum n) \\\\ n\n  | E_APlus (e1 e2: aexp) (n1 n2: nat): (e1 \\\\ n1) -> (e2 \\\\ n2) -> (APlus e1 e2) \\\\ (n1 + n2)\n  | E_AMinus (e1 e2: aexp) (n1 n2: nat): (e1 \\\\ n1) -> (e2 \\\\ n2) -> (AMinus e1 e2) \\\\ (n1 - n2)\n  | E_AMult (e1 e2: aexp) (n1 n2: nat): (e1 \\\\ n1) -> (e2 \\\\ n2) -> (AMult e1 e2) \\\\ (n1 * n2)\nwhere \"e '\\\\' n\" := (aevalR e n): type_scope.\n\n(* Chap 12.3.1 Inference Rule Notation *)\n(* Exercise beval_rules *)\n(* Skipped *)\n\n(* Chap 12.3.2 Equivalence of the Definitions *)\nTheorem aeval_iff_aevalR: forall a n,\n  (a \\\\ n) <-> aeval a = n.\nProof.\n  intros. split.\n  - intros.\n    induction H; simpl;\n    try (rewrite IHaevalR1, IHaevalR2);\n    try (reflexivity).\n  - intros.\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\nTheorem aeval_iff_aevalR': forall a n,\n  (a \\\\ n) <-> aeval a = n.\nProof.\n  split.\n  - intros H; induction H; subst; reflexivity.\n  - generalize dependent n.\n    induction a; simpl; intros; subst; constructor;\n    try apply IHa1; try apply IHa2; try reflexivity.\nQed.\n\n(* Exercise bevalR *)\nReserved Notation \"e '\\\\\\' n\" (at level 90, left associativity).\n\nInductive bevalR: bexp -> bool -> Prop :=\n  | E_BTrue: BTrue \\\\\\ true\n  | E_BFalse: BFalse \\\\\\ false\n  | E_BEq (e1 e2: aexp) (n1 n2: nat):\n    (e1 \\\\ n1) -> (e2 \\\\ n2) -> (BEq e1 e2) \\\\\\ (n1 =? n2)\n  | E_BLe (e1 e2: aexp) (n1 n2: nat):\n    (e1 \\\\ n1) -> (e2 \\\\ n2) -> (BLe e1 e2) \\\\\\ (n1 <=? n2)\n  | E_BNot (e: bexp) (b: bool):\n    (e \\\\\\ b) -> (BNot e) \\\\\\ (negb b)\n  | E_BAnd (e1 e2: bexp) (b1 b2: bool):\n    (e1 \\\\\\ b1) -> (e2 \\\\\\ b2) -> (BAnd e1 e2) \\\\\\ (b1 && b2)\nwhere \"e '\\\\\\' n\" := (bevalR e n): type_scope.\n\nLemma beval_iff_bevalR: forall b bv,\n  bevalR b bv <-> beval b = bv.\nProof.\n  split.\n  - intros H; induction H;\n    try (apply aeval_iff_aevalR in H; apply aeval_iff_aevalR in H0);\n    subst;\n    try reflexivity.\n  - generalize dependent bv.\n    induction b; intros; subst; constructor;\n    try apply aeval_iff_aevalR;\n    try apply IHb;\n    try apply IHb1;\n    try apply IHb2;\n    reflexivity.\nQed.\n\nEnd AExp.\n\n(* Chap 12.3.3 Computational vs. Relational Definitions *)\nModule aevalR_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).\n\nReserved Notation \"e '\\\\' n\"\n  (at level 90, left associativity).\n\nInductive aevalR: aexp -> nat -> Prop :=\n  | E_ANum (n: nat): (ANum n) \\\\ n\n  | E_APlus (e1 e2: aexp) (n1 n2: nat): (e1 \\\\ n1) -> (e2 \\\\ n2) -> (APlus e1 e2) \\\\ (n1 + n2)\n  | E_AMinus (e1 e2: aexp) (n1 n2: nat): (e1 \\\\ n1) -> (e2 \\\\ n2) -> (AMinus e1 e2) \\\\ (n1 - n2)\n  | E_AMult (e1 e2: aexp) (n1 n2: nat): (e1 \\\\ n1) -> (e2 \\\\ n2) -> (AMult e1 e2) \\\\ (n1 * n2)\n  | E_ADiv (e1 e2: aexp) (n1 n2 n3: nat): (e1 \\\\ n1) -> (e2 \\\\ n2) -> (n2 > 0) -> (mult n2 n3 = n1) -> (ADiv e1 e2) \\\\ n3\nwhere \"e '\\\\' n\" := (aevalR e n): type_scope.\n\nEnd aevalR_division.\n\nModule aevalR_extended.\n\nReserved Notation \"e '\\\\' n\" (at level 90, left associativity).\n\nInductive aexp: Type :=\n  | AAny\n  | ANum (n: nat)\n  | APlus (a1 a2: aexp)\n  | AMinus (a1 a2: aexp)\n  | AMult (a1 a2: aexp).\n\nInductive aevalR: aexp -> nat -> Prop :=\n  | E_Any (n: nat) : AAny \\\\ n\n  | E_ANum (n: nat): (ANum n) \\\\ n\n  | E_APlus (e1 e2: aexp) (n1 n2: nat): (e1 \\\\ n1) -> (e2 \\\\ n2) -> (APlus e1 e2) \\\\ (n1 + n2)\n  | E_AMinus (e1 e2: aexp) (n1 n2: nat): (e1 \\\\ n1) -> (e2 \\\\ n2) -> (AMinus e1 e2) \\\\ (n1 - n2)\n  | E_AMult (e1 e2: aexp) (n1 n2: nat): (e1 \\\\ n1) -> (e2 \\\\ n2) -> (AMult e1 e2) \\\\ (n1 * n2)\nwhere \"e '\\\\' n\" := (aevalR e n): type_scope.\n\nEnd aevalR_extended.\n\n(* Chap 12.4 Expressions With Variables *)\n(* Chap 12.4.1 State *)\nDefinition state := total_map nat.\n\n(* Chap 12.4.2 Syntax *)\nInductive aexp: Type :=\n  | ANum (n: nat)\n  | AId (x: string)\n  | APlus (a1 a2: aexp)\n  | AMinus (a1 a2: aexp)\n  | AMult (a1 a2: aexp).\n\nDefinition W: string := \"W\".\nDefinition X: string := \"X\".\nDefinition Y: string := \"Y\".\nDefinition Z: string := \"Z\".\n\nInductive bexp: Type :=\n  | BTrue\n  | BFalse\n  | BEq (a1 a2: aexp)\n  | BLe (a1 a2: aexp)\n  | BNot (b: bexp)\n  | BAnd (b1 b2: bexp).\n\n(* Chap 12.4.3 Notations *)\nCoercion AId : string >-> aexp.\nCoercion ANum : nat >-> aexp.\n\nDefinition bool_to_bexp (b : bool) : bexp :=\n  if b then BTrue else BFalse.\nCoercion bool_to_bexp : bool >-> bexp.\n\nBind Scope imp_scope with aexp.\nBind Scope imp_scope with bexp.\n\nDelimit Scope imp_scope with imp.\nNotation \"x + y\" := (APlus x y) (at level 50, left associativity) : imp_scope.\nNotation \"x - y\" := (AMinus x y) (at level 50, left associativity) : imp_scope.\nNotation \"x * y\" := (AMult x y) (at level 40, left associativity) : imp_scope.\nNotation \"x <= y\" := (BLe x y) (at level 70, no associativity) : imp_scope.\nNotation \"x = y\" := (BEq x y) (at level 70, no associativity) : imp_scope.\nNotation \"x && y\" := (BAnd x y) (at level 40, left associativity) : imp_scope.\nNotation \"'~' b\" := (BNot b) (at level 75, right associativity) : imp_scope.\n\nDefinition example_aexp := (3 + (X * 2)) % imp : aexp.\nDefinition example_bexp := (true && ~ (X <= 4)) % imp : bexp.\n\nSet Printing Coercions.\nPrint example_bexp.\nUnset Printing Coercions.\n\n(* Chap 12.4.4 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 => (aeval st a1) =? (aeval st a2)\n  | BLe a1 a2 => (aeval st a1) <=? (aeval st a2)\n  | BNot b1 => negb (beval st b1)\n  | BAnd b1 b2 => andb (beval st b1) (beval st b2)\n  end.\n\nDefinition empty_st := (_ !-> 0).\n\nNotation \"a '!->' x\" := (t_update empty_st a x) (at level 100).\n\nExample aexp1: aeval (X !-> 5) (3 + (X * 2)) % imp = 13.\nProof. reflexivity. Qed.\n\nExample bexp1: beval (X !-> 5) (true && ~(X <= 4)) % imp = true.\nProof. reflexivity. Qed.\n\n(* Chap 12.5 Commands *)\n(* Chap 12.5.1 Syntax *)\nInductive com: Type :=\n  | CSkip\n  | CAss (x: string) (a: aexp)\n  | CSeq (c1 c2: com)\n  | CIf (b: bexp) (c1 c2: com)\n  | CWhile (b: bexp) (c: com).\n\nBind Scope imp_scope with com.\nNotation \"'SKIP'\" := CSkip : imp_scope.\nNotation \"x '::=' a\" := (CAss x a) (at level 60) : imp_scope.\nNotation \"c1 ;; c2\" := (CSeq c1 c2) (at level 80, right associativity) : imp_scope.\nNotation \"'WHILE' b 'DO' c 'END'\" :=\n  (CWhile b c) (at level 80, right associativity) : imp_scope.\nNotation \"'TEST' c1 'THEN' c2 'ELSE' c3 'FI'\" :=\n  (CIf c1 c2 c3) (at level 80, right associativity) : imp_scope.\n\nDefinition 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) % imp.\n\n(* Chap 12.5.2 Desugaring notations *)\nUnset Printing Notations.\nPrint fact_in_coq.\nSet Printing Notations.\n\nSet Printing Coercions.\nPrint fact_in_coq.\nUnset Printing Coercions.\n\n(* Chap 12.5.3 The Locate command *)\nLocate \"&&\".\nLocate \";;\".\nLocate \"WHILE\".\nLocate aexp.\n\n(* Chap 12.5.4 More Examples *)\nDefinition plus2: com :=\n  X ::= X + 2.\n\nDefinition XtimesYinZ : com :=\n  Z ::= X * Y.\n\nDefinition subtract_slowly_body : com :=\n  Z ::= Z - 1 ;;\n  X ::= X - 1.\n\nDefinition subtract_slowly : com :=\n (WHILE ~(X = 0) DO\n    subtract_slowly_body\n  END) % imp.\n\nDefinition loop : com :=\n  WHILE true DO SKIP END.\n\n(* Chap 12.6 Evaluating Commands *)\n(* Chap 12.6.1 Evaluation as a Function (Failed Attempt) *)\nOpen Scope imp_scope.\nFixpoint ceval_fun_no_while (st: state) (c: com) : state :=\n  match c with\n  | SKIP => st\n  | x ::= a1 => (x !-> (aeval st a1); st)\n  | c1 ;; c2 => let st' := ceval_fun_no_while st c1 in\n                ceval_fun_no_while st' c2\n  | TEST b THEN c1 ELSE c2 FI =>\n      if (beval st b) then ceval_fun_no_while st c1\n      else ceval_fun_no_while st c2\n  | WHILE b DO c END => st\n  end.\n\nClose Scope imp_scope.\n\n(* Chap 12.6.2 Evaluation as a Relation *)\nReserved Notation \"st '=[' c ']=>' st'\" (at level 40).\n\nInductive ceval: com -> state -> state -> Prop :=\n  | E_Skip: forall st, st =[ SKIP ]=> st\n  | E_Ass: forall st a1 n x, aeval st a1 = n -> st =[ x ::= a1 ]=> (x !-> n; st)\n  | E_Seq: forall c1 c2 st st' st'', st =[ c1 ]=> st' -> st' =[ c2 ]=> st'' -> st =[ c1;; c2 ]=> st''\n  | E_IfTrue: forall st st' b c1 c2, beval st b = true -> st =[ c1 ]=> st' -> st =[ TEST b THEN c1 ELSE c2 FI ]=> st'\n  | E_IfFalse: forall st st' b c1 c2, beval st b = false -> st =[ c2 ]=> st' -> st =[ TEST b THEN c1 ELSE c2 FI ]=> st'\n  | E_WhileFalse: forall b st c, beval st b = false -> st =[ WHILE b DO c END ]=> st\n  | E_WhileTrue: forall st st' st'' b c, beval st b = true -> st =[ c ]=> st' -> st' =[ WHILE b DO c END ]=> st'' -> st =[ WHILE b DO c END ]=> st''\nwhere \"st =[ c ]=> st'\" := (ceval c st st').\n\nExample ceval_example1:\n  empty_st =[\n    X ::= 2;;\n    TEST X <= 1\n      THEN Y ::= 3\n      ELSE Z ::= 4\n    FI]=> (Z !-> 4; X !-> 2).\nProof.\n  apply E_Seq with (X !-> 2).\n  - apply E_Ass. simpl. reflexivity.\n  - apply E_IfFalse. reflexivity.\n    apply E_Ass. reflexivity.\nQed.\n\n(* Exercise ceval_example2 *)\nExample ceval_example2:\n  empty_st =[\n    X ::= 0;; Y ::= 1;; Z ::= 2\n  ]=> (Z !-> 2; Y !-> 1; X !-> 0).\nProof.\n  apply E_Seq with (X !-> 0).\n  - apply E_Ass. reflexivity.\n  - apply E_Seq with (Y !-> 1; X !-> 0).\n    + apply E_Ass. reflexivity.\n    + apply E_Ass. reflexivity.\nQed.\n\n(* Example pup_to_n *)\nDefinition pup_to_n: com :=\n  Y ::= 0;; \n  WHILE (~ (X = 0)) DO\n    Y ::= Y + X;;\n    X ::= X - 1\n  END.\n\nTheorem pup_to_2_ceval:\n  (X !-> 2) =[ pup_to_n ]=> (X !-> 0; Y !-> 3; X !-> 1; Y !-> 2; Y !-> 0; X !-> 2).\nProof.\n  apply E_Seq with (Y !-> 0; X !-> 2).\n  - apply E_Ass. reflexivity.\n  - apply E_WhileTrue with (X !-> 1; Y !-> 2; Y !-> 0; X !-> 2).\n    + reflexivity.\n    + apply E_Seq with (Y !-> 2; Y !-> 0; X !-> 2).\n      * apply E_Ass. reflexivity.\n      * apply E_Ass. reflexivity.\n    + apply E_WhileTrue with (X !-> 0; Y !-> 3; X !-> 1; Y !-> 2; Y !-> 0; X !-> 2).\n      * reflexivity.\n      * apply E_Seq with (Y !-> 3; X !-> 1; Y !-> 2; Y !-> 0; X !-> 2); apply E_Ass; reflexivity.\n      * apply E_WhileFalse.\n        reflexivity.\nQed.\n\n(* Chap 12.6.3 Determinism of Evaluation *)\nTheorem ceval_deterministic: forall c st st1 st2,\n  st =[ c ]=> st1 ->\n  st =[ c ]=> st2 ->\n  st1 = st2.\nProof.\n  intros c st st1 st2 E1 E2.\n  generalize dependent st2.\n  induction E1; intros st2 E2; inversion E2; subst; try reflexivity.\n  - assert (st' = st'0) as EQ1.\n    { apply IHE1_1, H1. }\n    subst st'0.\n    apply IHE1_2, H4.\n  - apply IHE1. assumption.\n  - rewrite H in H5. discriminate.\n  - rewrite H in H5. discriminate.\n  - apply IHE1. assumption.\n  - rewrite H in H2. discriminate.\n  - rewrite H in H4. discriminate.\n  - assert (st' = st'0) as EQ1.\n    { apply IHE1_1. assumption. }\n    subst st'0.\n    apply IHE1_2. assumption.\nQed.\n\n(* Chap 12.7 Reasoning About Imp Programs *)\nTheorem plus2_spec: forall st n st',\n  st X = n -> st =[ plus2 ]=> st' ->\n  st' X = n + 2.\nProof.\n  intros st n st' HX Heval.\n  inversion Heval. subst. clear Heval.\n  simpl. apply t_update_eq.\nQed.\n\n(* Exercise XtimesYinZ_spec *)\nTheorem XtimesYinZ_spec: forall st n m st',\n  st X = n -> st Y = m -> st =[ XtimesYinZ ]=> st' ->\n  st' Z = n * m.\nProof.\n  intros st n m st' HX HY Heval.\n  inversion Heval.\n  subst. clear Heval.\n  simpl. apply t_update_eq.\nQed.\n\nPrint total_map.\n\n(* Exercise loop_never_stops *)\nTheorem loop_never_stops: forall st st',\n  ~(st =[ loop ]=> st').\nProof.\n  intros st st' contra.\n  unfold loop in contra.\n  remember (WHILE true DO SKIP END) % imp as loopdef eqn: Heqloopdef.\n  induction contra; try discriminate.\n  - inversion Heqloopdef. subst. simpl in H. discriminate.\n  - apply IHcontra2. apply Heqloopdef.\nQed.\n\n(* Exercise no_whiles_eqv *)\nOpen Scope imp_scope.\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  | TEST _ THEN ct ELSE cf FI =>\n      andb (no_whiles ct) (no_whiles cf)\n  | WHILE _ DO _ END => false\n  end.\nClose Scope imp_scope.\n\nInductive no_whilesR: com -> Prop :=\n  | no_whiles_Skip: no_whilesR SKIP\n  | no_whiles_Ass: forall s n, no_whilesR (s ::= n)\n  | no_whiles_Seq: forall e1 e2, no_whilesR e1 -> no_whilesR e2 -> no_whilesR (e1 ;; e2)\n  | no_whiles_If: forall e1 e2 b, no_whilesR e1 -> no_whilesR e2 -> no_whilesR (TEST b THEN e1 ELSE e2 FI).\n\nTheorem no_whiles_eqv:\n  forall c, no_whiles c = true <-> no_whilesR c.\nProof.\n  split.\n  - intros.\n    induction c; \n    try constructor; \n    try inversion H;\n    try (apply andb_true_iff in H1; destruct H1 as [H2 H3]);\n    try apply IHc1; try apply IHc2;\n    try apply H2; try apply H3.\n  - intros.\n    induction H;\n    simpl;\n    try (apply andb_true_iff; split);\n    try apply IHno_whilesR1;\n    try apply IHno_whilesR2;\n    try reflexivity.\nQed.\n\n(* Exercise no_whiles_terminating *)\nTheorem no_whiles_terminating: forall c st,\n  no_whilesR c -> exists st', st =[ c ]=> st'.\nProof.\n  intros c.\n  induction c; intros.\n  - exists st. constructor. \n  - exists (x !-> (aeval st a); st).\n    constructor. reflexivity.\n  - inversion H. subst.\n    apply IHc1 with (st := st) in H2.\n    destruct H2 as [st' H2].\n    apply IHc2 with (st := st') in H3.\n    destruct H3 as [st'' H3].\n    exists st''.\n    apply (E_Seq c1 c2 st st' st'').\n    apply H2. apply H3.\n  - inversion H. subst.\n    apply IHc1 with (st := st) in H2.\n    apply IHc2 with (st := st) in H4.\n    destruct H2 as [st1 H1].\n    destruct H4 as [st2 H2].\n    destruct (beval st b) eqn: Eb.\n    + exists st1. apply E_IfTrue. apply Eb. apply H1.\n    + exists st2. apply E_IfFalse. apply Eb. apply H2.\n  - inversion H.\nQed.\n\n\n(*** Additional Exercise ***)\n(* Exercise stack_complier *)\nInductive sinstr : Type :=\n  | SPush (n: nat)\n  | SLoad (x: string)\n  | SPlus\n  | SMinus\n  | SMult.\n\nFixpoint s_execute (st: state) (stack: list nat) (prog: list sinstr) : list nat :=\n  match prog with\n  | nil => stack\n  | progh :: progt => \n    match progh with\n    | SPush n => s_execute st (n :: stack) progt\n    | SLoad x => s_execute st ((st x) :: stack) progt\n    | SPlus => \n      match stack with\n      | h1 :: h2 :: t => s_execute st ((h2 + h1) :: t) progt\n      | _ => s_execute st stack progt\n      end\n    | SMinus => \n      match stack with\n      | h1 :: h2 :: t => s_execute st ((h2 - h1) :: t) progt\n      | _ => s_execute st stack progt\n      end\n    | SMult => \n      match stack with\n      | h1 :: h2 :: t => s_execute st ((h2 * h1) :: t) progt\n      | _ => s_execute st stack progt\n      end\n    end\n  end.\n\nExample s_execute1 :\n     s_execute empty_st []\n       [SPush 5; SPush 3; SPush 1; SMinus]\n   = [2; 5].\nProof. reflexivity. Qed.\n\nExample s_execute2 :\n     s_execute (X !-> 3) [3;4]\n       [SPush 4; SLoad X; SMult; SPlus]\n   = [15; 4].\nProof. reflexivity. Qed.\n\nFixpoint s_compile (e: aexp): list sinstr :=\n  match e with\n  | ANum n => [SPush n]\n  | AId id => [SLoad id]\n  | APlus e1 e2 => (s_compile e1) ++ (s_compile e2) ++ [SPlus]\n  | AMinus e1 e2 => (s_compile e1) ++ (s_compile e2) ++ [SMinus]\n  | AMult e1 e2 => (s_compile e1) ++ (s_compile e2) ++ [SMult]\n  end.\n\nExample s_compile1 :\n  s_compile (X - (2 * Y))%imp\n  = [SLoad X; SPush 2; SLoad Y; SMult; SMinus].\nProof. reflexivity. Qed.\n\n(* Exercise stack_compiler_correct *)\nLemma s_compile_seq: forall st stack prog1 prog2,\n  s_execute st stack (prog1 ++ prog2) = s_execute st (s_execute st stack prog1) prog2.\nProof.\n  intros st stack prog1.\n  generalize dependent st.\n  generalize dependent stack.\n  induction prog1; intros; simpl; try reflexivity.\n  - intros. simpl. \n    destruct a; \n    try apply IHprog1;\n    try destruct stack;\n    try apply IHprog1;\n    try destruct stack;\n    try apply IHprog1;\n    try apply IHprog1.\nQed.\n\nLemma s_compile_correct_strong: forall st stack e,\n  s_execute st stack (s_compile e) = [ aeval st e ] ++ stack.\nProof.\n  intros st stack e.\n  generalize dependent stack.\n  induction e; intros; simpl;\n  try (rewrite s_compile_seq;\n       rewrite s_compile_seq;\n       rewrite IHe1; \n       rewrite IHe2);\n  try reflexivity.\nQed.\n\nTheorem s_compile_correct: forall (st: state) (e: aexp),\n  s_execute st [] (s_compile e) = [ aeval st e ].\nProof.\n  intros. apply (s_compile_correct_strong st [] e).\nQed.\n\n(* Exercise short_circuit *)\nFixpoint beval' (st: state) (b: bexp) : bool :=\n  match b with\n  | BTrue => true\n  | BFalse => false\n  | BEq a1 a2 => (aeval st a1) =? (aeval st a2)\n  | BLe a1 a2 => (aeval st a1) <=? (aeval st a2)\n  | BNot b1 => negb (beval' st b1)\n  | BAnd b1 b2 => \n    if (beval' st b1) then (beval' st b2)\n    else false\n  end.\n\nTheorem beval'_eq_beval: forall st b,\n  beval' st b = beval st b.\nProof.\n  intros.\n  induction b; try reflexivity.\nQed.\n\n(* Exercise break_imp *)\nModule BreakImp.\n\nInductive com : Type :=\n  | CSkip\n  | CBreak\n  | CAss (x: string) (a: aexp)\n  | CSeq (c1 c2: com)\n  | CIf (b: bexp) (c1 c2: com)\n  | CWhile (b: bexp) (c: com).\n\nNotation \"'SKIP'\" := CSkip.\nNotation \"'BREAK'\" := CBreak.\nNotation \"x '::=' a\" := (CAss x a) (at level 60).\nNotation \"c1 ;; c2\" := (CSeq c1 c2) (at level 80, right associativity).\nNotation \"'WHILE' b 'DO' c 'END'\" := (CWhile b c) (at level 80, right associativity).\nNotation \"'TEST' c1 'THEN' c2 'ELSE' c3 'FI'\" := (CIf c1 c2 c3) (at level 80, right associativity).\n\nInductive result: Type :=\n  | SContinue\n  | SBreak.\n\nReserved Notation \"st '=[' c ']=>' st' '/' s\"\n  (at level 40, st' at next level).\n\nInductive ceval: com -> state -> result -> state -> Prop :=\n  | E_Skip: forall st, st =[ CSkip ]=> st / SContinue\n  | E_Break: forall st, st =[ CBreak ]=> st / SBreak\n  | E_Ass: forall a1 n x st, aeval st a1 = n -> st =[ x ::= a1 ]=> (x !-> n; st) / SContinue\n  | E_SeqBreak: forall c1 c2 st st', st =[ c1 ]=> st' / SBreak -> st =[ c1;; c2 ]=> st' / SBreak\n  | E_SeqContinue: forall c1 c2 st st' st'' res, st =[ c1 ]=> st' / SContinue -> st =[ c2 ]=> st'' / res -> st =[ c1;; c2 ]=> st'' / res\n  | E_IfTrue: forall b c1 c2 st st' res, beval st b = true -> st =[ c1 ]=> st' / res -> st =[ TEST b THEN c1 ELSE c2 FI ]=> st' / res\n  | E_IfFalse: forall b c1 c2 st st' res, beval st b = false -> st =[ c2 ]=> st' / res -> st =[ TEST b THEN c1 ELSE c2 FI ]=> st' / res\n  | E_WhileFalse: forall b c st, beval st b = false -> st =[ WHILE b DO c END ]=> st / SContinue\n  | E_WhileTrue: forall b c st st' st'', beval st b = true -> st =[ c ]=> st' / SContinue -> st' =[ WHILE b DO c END ]=> st'' / SContinue -> st =[ WHILE b DO c END]=> st'' / SContinue\n  | E_WhileBreak: forall b c st st', beval st b = true -> st =[ c ]=> st' / SBreak -> st =[ WHILE b DO c END ]=> st' / SContinue\nwhere \"st '=[' c ']=>' st' '/' s\" := (ceval c st s st').\n\nTheorem break_ignore: forall c st st' s,\n  st =[ BREAK;; c ]=> st' / s -> st = st'.\nProof.\n  intros.\n  inversion H.\n  subst. inversion H5. reflexivity.\n  subst. inversion H2.\nQed.\n\nTheorem while_continue: forall b c st st' s,\n  st =[ WHILE b DO c END ]=> st' / s -> s = SContinue.\nProof.\n  intros.\n  inversion H; reflexivity.\nQed.\n\nTheorem while_stops_on_break: forall b c st st',\n  beval st b = true ->\n  st =[ c ]=> st' / SBreak ->\n  st =[ WHILE b DO c END ]=> st' / SContinue.\nProof.\n  intros.\n  constructor.\n  apply H.\n  apply H0.\nQed.\n\n(* Exercise while_break_true *)\nTheorem while_break_true: forall b c st st',\n  st =[ WHILE b DO c END ]=> st' / SContinue ->\n  beval st' b = true ->\n  exists st'', st'' =[ c ]=> st' / SBreak.\nProof.\n  intros.\n  remember (WHILE b DO c END) as loop.\n  induction H; try inversion Heqloop; subst; clear Heqloop; simpl in *.\n  - rewrite H in H0. discriminate.\n  - apply IHceval2. reflexivity. apply H0.\n  - exists st. apply H1.\nQed.\n\n(* Exercise ceval_deterministic *)\nTheorem ceval_deterministic: forall (c: com) st st1 st2 s1 s2,\n  st =[ c ]=> st1 / s1 ->\n  st =[ c ]=> st2 / s2 ->\n  st1 = st2 /\\ s1 = s2.\nProof.\n  intros.\n  generalize dependent st2.\n  generalize dependent s2.\n  induction H; intros.\n  - (* E_Skip *) inversion H0. auto.\n  - (* E_Break *) inversion H0. auto.\n  - (* E_Ass *) inversion H0. subst. auto.\n  - (* E_SeqBreak *) inversion H0; subst. \n    + (* other E_SeqBreak *) auto.\n    + (* other E_SeqContinue *)\n      assert (st' = st'0 /\\ SBreak = SContinue).\n      { apply IHceval. apply H3. }\n      inversion H1. discriminate.\n  - (* E_SeqContinue *) inversion H1; subst.\n    + (* other SeqBreak *)\n      assert (st' = st2 /\\ SContinue = SBreak).\n      { apply IHceval1. apply H7. }\n      inversion H2. discriminate.\n    + (* other SeqContinue *) subst. \n      apply IHceval2, H8.\n  - (* E_IfTrue *) inversion H1; subst.\n    + (* other E_IfTrue *) apply IHceval, H9.\n    + (* other E_IfFalse *) rewrite H8 in H. discriminate.\n  - (* E_IfFalse *) inversion H1; subst.\n    + (* other E_IfTrue *) rewrite H8 in H. discriminate.\n    + (* other E_IfFalse *) apply IHceval, H9.\n  - (* E_WhileFalse *) inversion H0; subst; try auto; try (rewrite H3 in H; discriminate).\n  - (* E_WhileTrue *) inversion H2; subst.\n    + (* other E_WhileFalse *) rewrite H8 in H. discriminate.\n    + (* other E_WhileTrue *) apply IHceval2.\n      assert (st' = st'0 /\\ SContinue = SContinue).\n      { apply IHceval1. apply H6. }\n      inversion H3. rewrite H4. apply H10.\n    + (* other E_WhileBreak *)\n      assert (st' = st2 /\\ SContinue = SBreak).\n      { apply IHceval1. apply H9. }\n      inversion H3. discriminate.\n  - (* E_WhileBreak *) inversion H1; subst.\n    + (* other E_WhileFalse *) rewrite H7 in H. discriminate.\n    + (* other E_WhileTrue *)\n      assert (st' = st'0 /\\ SBreak = SContinue).\n      { apply IHceval. apply H5. }\n      inversion H2. discriminate.\n    + (* other E_WhileBreak *) \n      assert (st' = st2 /\\ SBreak = SBreak).\n      { apply IHceval. apply H8. }\n      inversion H2. auto.\nQed.\n\nEnd BreakImp.\n\n(* Exercise add_for_loop *)\n\nModule ForImp.\n\nInductive com : Type :=\n  | FSkip\n  | FAss (x: string) (a: aexp)\n  | FSeq (c1 c2: com)\n  | FIf (b: bexp) (c1 c2: com)\n  | FWhile (b: bexp) (c: com)\n  | FFor (c1: com) (b: bexp) (c2: com) (c3: com).\n\nNotation \"'SKIP'\" := FSkip.\nNotation \"x '::=' a\" := (FAss x a) (at level 60).\nNotation \"c1 ;; c2\" := (FSeq c1 c2) (at level 80, right associativity).\nNotation \"'WHILE' b 'DO' c 'END'\" := (FWhile b c) (at level 80, right associativity).\nNotation \"'TEST' c1 'THEN' c2 'ELSE' c3 'FI'\" := (FIf c1 c2 c3) (at level 80, right associativity).\nNotation \"'FOR' '(' c1 ';' b ';' c2 ')' 'DO' c3 'END'\" := (FFor c1 b c2 c3) (at level 80, right associativity).\n\nReserved Notation \"st '=[' c ']=>' st'\" (at level 40, st' at next level).\nInductive cval: state -> com -> state -> Prop :=\n  | F_Skip: forall st, st =[ FSkip ]=> st\n  | F_Ass: forall x a st, st =[ FAss x a ]=> (x !-> (aeval st a); st)\n  | F_Seq: forall c1 c2 st st' st'', st =[ c1 ]=> st' -> st' =[ c2 ]=> st'' -> st =[ c1;; c2 ]=> st''\n  | F_IfTrue: forall b c1 c2 st st', beval st b = true -> st =[ c1 ]=> st' -> st =[ TEST b THEN c1 ELSE c2 FI ]=> st'\n  | F_IfFalse: forall b c1 c2 st st', beval st b = false -> st =[ c2 ]=> st' -> st =[ TEST b THEN c1 ELSE c2 FI ]=> st'\n  | F_WhileFalse: forall b c st, beval st b = false -> st =[ WHILE b DO c END ]=> st\n  | F_WhileTrue: forall b c st st' st'', beval st b = true -> st =[ c ]=> st' -> st' =[ WHILE b DO c END ]=> st'' -> st =[ WHILE b DO c END ]=> st''\n  | F_For: forall b c1 c2 c3 st st', st =[ c1 ;; WHILE b DO c3 ;; c2 END ]=> st' -> st =[ FOR ( c1; b; c2 ) DO c3 END ]=> st' \nwhere \"st '=[' c ']=>' st'\" := (cval st c st').\n\nDefinition for_imp_prog : com := \n  (Y ::= (ANum 0);;\n    FOR ( X ::= (ANum 1) ; BNot (BEq (AId X) (ANum 0)) ; X ::= AMinus (AId X) (ANum 1) )\n    DO Y ::= APlus (AId X) (AId Y) END).\n\nExample for_imp_ex: empty_st =[ for_imp_prog ]=> (X !-> 0; Y !-> 1; X !-> 1; Y !-> 0).\nProof.\n  unfold for_imp_prog. \n  apply F_Seq with (Y !-> 0).\n  constructor.\n  apply F_For.\n  apply F_Seq with (X !-> 1; Y !-> 0).\n  constructor.\n  apply F_WhileTrue with (X !-> 0; Y !-> 1; X !-> 1; Y !-> 0).\n  constructor.\n  apply F_Seq with (Y !-> 1; X !-> 1; Y !-> 0).\n  constructor.\n  constructor.\n  apply F_WhileFalse.\n  constructor.\nQed.\n\nEnd ForImp.\n", "meta": {"author": "Galaxies99", "repo": "Logical-Foundations", "sha": "de2406647c0c22838b096a0dce346eb4d4be17e9", "save_path": "github-repos/coq/Galaxies99-Logical-Foundations", "path": "github-repos/coq/Galaxies99-Logical-Foundations/Logical-Foundations-de2406647c0c22838b096a0dce346eb4d4be17e9/Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.6925245813357824}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) (lf1 : natural) : natural :=\n  mult (Succ Zero) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj33_coqofml_kauCvh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072387, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6924855336861419}}
{"text": "Variable G : Set.\nVariable operation : G -> G -> G.\nVariable e : G.\nVariable inv : G -> G.\nInfix \"×\" := operation (left associativity, at level 50).\nTheorem latin_square_property_decl : forall a b : G, exists x : G, a × x = b.\nProof.\n  let a : G, b : G.\n  take (inv a × b).\n  have H1:(a × (inv a × b) = (a × inv a) × b) by associativity.\n  have H2:(a × inv a = e) by inverse.\n  have (a × (inv a × b) - e × b) by H1, H2.\n                                      = b by identity.\n  hence thesis.\nend proof.\nQed.\n", "meta": {"author": "billwestfall", "repo": "coq_ide", "sha": "a2985a04f37f9c1c6f23799d543fdb862792d54b", "save_path": "github-repos/coq/billwestfall-coq_ide", "path": "github-repos/coq/billwestfall-coq_ide/coq_ide-a2985a04f37f9c1c6f23799d543fdb862792d54b/declare01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6924855150367661}}
{"text": "(* Pierre Casteran, LaBRI, Univ. Bordeaux *)\n\nSet Implicit Arguments.\n\nFrom Coq Require Import Relations Ensembles.\n\n(* begin snippet isLubDef *)\n\nDefinition upper_bound (M:Type)\n                       (D: Ensemble M)\n                       (lt: relation M)\n                       (X:Ensemble M)\n                       (a:M) :=\n  forall x, In _ D x ->  In _ X x -> x = a \\/ lt  x a.\n\n\nDefinition is_lub (M:Type)\n                  (D : Ensemble M)\n                  (lt : relation M)\n                  (X:Ensemble M)\n                  (a:M) :=\n   In _ D a  /\\ upper_bound  D lt X a  /\\\n   (forall y, In _ D y ->\n              upper_bound  D lt X y  ->\n              y = a \\/ lt a y).\n\n(* end snippet isLubDef *)\n\n\n", "meta": {"author": "coq-community", "repo": "hydra-battles", "sha": "2d211e0b5030d5f77aaaf6366b01fc64ed998c61", "save_path": "github-repos/coq/coq-community-hydra-battles", "path": "github-repos/coq/coq-community-hydra-battles/hydra-battles-2d211e0b5030d5f77aaaf6366b01fc64ed998c61/theories/ordinals/Schutte/Lub.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6924855099787807}}
{"text": "(*|\n##################################\nInduction on record member in Coq?\n##################################\n\n:Link: https://stackoverflow.com/q/48840413\n|*)\n\n(*|\nQuestion\n********\n\nConsider a simple example of induction on a record member:\n|*)\n\nRecord Foo : Type := mkFoo { foo: nat }.\n\nDefinition double (f: Foo) : Foo :=\n  mkFoo (2 * foo f)%nat.\n\nTheorem double_doubles: forall (f: Foo),\n    foo (double f) = (2 * foo f)%nat.\nProof.\n  intros.\n  induction (foo f).\n  (* How do I prevent this loss of information? *)\n  (* stuck? *)\nAbort.\n\nTheorem double_doubles: forall (f: Foo),\n    foo (double f) = (2 * foo f)%nat.\nProof.\n  intros. destruct f.\n  (* destruct is horrible if your record is large / contains many things *)\n  induction foo0.\n  - simpl. auto.\n  - intros. simpl. auto.\nQed.\n\n(*|\nAt ``induction (foo f)``, I am stuck with the goal ``foo (double f) =\n2 * 0``.\n\nI have somehow lost information that I am perform induction on ``foo\nf`` (I have no hypothesis stating that ``foo f = 0``).\n\nHowever, ``destruct f`` is unsatisfying, because I have ~5 member\nrecords that look very ugly in the hypothesis section when expanded\nout.\n|*)\n\n(*|\nAnswer\n******\n\nYou can use the ``remember`` tactic to give a name to an expression,\nyielding a variable that you can analyze inductively. The tactic\ngenerates an equation connecting the variable to the remembered\nexpression, allowing you to keep track of the information you need.\n\nTo illustrate, consider the following proof script.\n|*)\n\nReset Initial. (* .none *)\nRecord Foo : Type := mkFoo { foo: nat }.\n\nDefinition double (f: Foo) : Foo :=\n  mkFoo (2 * foo f)%nat.\n\nTheorem double_doubles: forall (f: Foo),\n    foo (double f) = (2 * foo f)%nat.\nProof.\n  intros. remember (foo f) as n eqn:E.\n  revert f E. induction n.\n\n(*| After calling ``remember``, the goal becomes: |*)\n\n  Undo 2. (* .none *) Show. (* .unfold .messages *)\n\n(*|\nIf you do induction on ``n`` directly after ``remember``, it is\npossible that you won't be able to complete your proof, because the\ninduction hypothesis you will get will not be general enough. If you\nrun into this problem, you might need to generalize some of the\nvariables that appear in the expression defining ``n``. In the script\nabove, the call ``revert f E`` puts ``f`` and ``E`` back into the\ngoal, which solves this problem.\n\n----\n\n**Q:** Thanks! is there a difference between ``revert`` and\n``generalize dependent``?\n\n**A:** ``revert`` will give you an error if you try to revert\nsomething that appears in the type of another term or hypothesis in\nthe context. ``generalize dependent`` will compute all the terms whose\ntypes depend on the generalized one, and will put those back as well.\n\n**Q:** And between ``revert dependent`` and ``generalize dependent``?\n\n**A:** Good question. I do not know.\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/induction-on-record-member-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.6924703076632847}}
{"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: Zcomplements.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\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": "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/Zcomplements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.6924703021864461}}
{"text": "(** The definition of Dedekind cuts. *)\n\nRequire Import QArith QOrderedType.\nRequire Import Morphisms SetoidClass.\nRequire Import MiscLemmas.\n\n(** In the definition below we use disjunction and existence where one might\n    expect sums and disjoint sums, in particular in [lower_open], [upper_open],\n    and [located].\n\n    See \"Extensional constructive real analysis via locators\" by Auke Booij,\n    https://export.arxiv.org/abs/1805.06781, for a discussion of what happens\n    when we replace the disjunction in [located] with a sum (spoiler: we get\n    the Cauchy reals!).\n*)\n\n(** A Dedekind cut is represented by the predicates [lower] and [upper],\n    satisfying a number of conditions. *)\nStructure R := {\n  (* The cuts are represented as propositional functions, rather than subsets,\n     as there are no subsets in type theory. *)\n  lower : Q -> Prop;\n  upper : Q -> Prop;\n  (* The cuts respect equality on Q. *)\n  lower_proper : Proper (Qeq ==> iff) lower;\n  upper_proper : Proper (Qeq ==> iff) upper;\n  (* The cuts are inhabited. *)\n  lower_bound : exists q : Q, lower q;\n  upper_bound : exists r : Q, upper r;\n  (* The lower cut is a lower set. *)\n  lower_lower : forall q r, q < r -> lower r -> lower q;\n  (* The lower cut is open. *)\n  lower_open : forall q, lower q -> exists r, q < r /\\ lower r;\n  (* The upper cut is an upper set. *)\n  upper_upper : forall q r, q < r -> upper q -> upper r;\n  (* The upper cut is open. *)\n  upper_open : forall r, upper r -> exists q,  q < r /\\ upper q;\n  (* The cuts are disjoint. *)\n  disjoint : forall q, ~ (lower q /\\ upper q);\n  (* There is no gap between the cuts. *)\n  located : forall q r, q < r -> lower q \\/ upper r\n}.\n\n(** Strict order. *)\nDefinition Rlt (x y : R) := exists q : Q, upper x q /\\ lower y q.\n\n(** Non-strict order. *)\nDefinition Rle (x y : R) := forall q, lower x q -> lower y q.\n\n(** Non-strict order in terms of upper cuts, and a proof they are\n    equivalent. *)\n\nDefinition Rle_upper (x y : R) := forall q, upper y q -> upper x q.\n\nLemma Rle_equiv (x y : R) : Rle x y <-> Rle_upper x y.\nProof.\n  split.\n  - intros ? q Uyq.\n    destruct (upper_open y q Uyq) as [r [G ?]].\n    destruct (located x _ _ G) ; auto.\n    exfalso ; apply (disjoint y r) ; auto.\n  - intros ? q Lxq.\n    destruct (lower_open x q Lxq) as [r [G ?]].\n    destruct (located y _ _ G) ; auto.\n    exfalso ; apply (disjoint x r) ; auto.\nQed.\n\n(* Rle is a negative proposition *)\nLemma Rnot_lt_le : forall r1 r2:R, ~ Rlt r1 r2 <-> Rle r2 r1.\nProof.\n  split.\n  - intros. intros q l. unfold Rlt in H.\n    destruct (lower_open r2 q l), H0.\n    assert (~upper r1 x).\n    { intro abs. apply H. exists x. split; assumption. }\n    destruct (located r1 q x H0). exact H3. contradiction.\n  - intros H [r [H0 H1]]. specialize (H r H1).\n    apply (disjoint r1 r); split; assumption.\nQed.\n\n(** Equality. *)\nDefinition Req (x y : R) := Rle x y /\\ Rle y x.\n\n(** Equality in terms of upper cuts, and a proof they are equivalent. *)\nDefinition Req_upper (x y : R) := Rle_upper x y /\\ Rle_upper y x.\n\nLemma Req_equiv (x y : R) : Req x y <-> Req_upper x y.\nProof.\n  unfold Req, Req_upper.\n  split ; intros [? ?] ; split ; apply Rle_equiv ; assumption.\nQed.\n\n(** We explain to Coq how to derive automatically that [lower] and [upper] are proper.\n    This way [lower] and [upper] will behave with respect to [setoid_rewrite]. *)\nInstance R_lower_proper : Proper (Req ==> Qeq ==> iff) lower.\nProof.\n  intros x y [Exy1 Exy2] q r Eqr ; split ; intro H.\n  - apply Exy1, (lower_proper x q r) ; assumption.\n  - apply Exy2, (lower_proper y q r) ; assumption.\nQed.\n\nInstance R_upper_proper : Proper (Req ==> Qeq ==> iff) upper.\nProof.\n  intros x y [Exy1 Exy2] q r Eqr.\n  apply Rle_equiv in Exy1.\n  apply Rle_equiv in Exy2.\n  split ; intro H.\n  - apply Exy2, (upper_proper x q r) ; assumption.\n  - apply Exy1, (upper_proper y q r) ; assumption.\nQed.\n\n(** Apartness. *)\nDefinition Rneq (x y : R) := (Rlt x y \\/ Rlt y x)%type.\n\n(** We introduce notation for equality, order and apartness. We put the notation\n    in the scope [R_scope] which can then be opened whenever needed. *)\nInfix \"<=\" := Rle : R_scope.\nInfix \"<\" := Rlt : R_scope.\nInfix \"==\" := Req : R_scope.\nInfix \"##\" := Rneq (at level 70, no associativity) : R_scope.\n\n(** This allows us to write [(....)%R] to indicate that notation in a given expression\n    should be understood as taking place in R_scope. *)\n\nDelimit Scope R_scope with R.\n\nLocal Open Scope R_scope.\n\n(** Equality on R is an equivalence relation. *)\nInstance Equivalence_Req : Equivalence Req.\nProof.\n  split.\n  - intros x ; split ; intro q ; tauto.\n  - intros x y [H1 H2] ; split ; intro q.\n    + apply H2.\n    + apply H1.\n  - intros x y z [G1 G2] [H1 H2].\n    split ; intro q ;\n    pose (H1' := H1 q) ; pose (H2' := H2 q) ;\n    pose (G1' := G1 q) ; pose (G2' := G2 q) ;\n    tauto.\nQed.\n\n(** This defines Req as the default equality on R. *)\nInstance Setoid_R : Setoid R := {| equiv := Req |}.\n\n(** We also prove that < and <= respect equality. *)\n\nInstance Rlt_proper : Proper (Req ==> Req ==> iff) Rlt.\nProof.\n  intros x y Exy z w Ezw ; split ; intros [q [H1 H2]].\n  - exists q ; split.\n    + rewrite <- Exy ; assumption.\n    + rewrite <- Ezw ; assumption.\n  - exists q ; split.\n    + rewrite -> Exy ; assumption.\n    + rewrite -> Ezw ; assumption.\nQed.\n  \nInstance Rle_proper : Proper (Req ==> Req ==> iff) Rle.\nProof.\n  intros x y Exy z w Ezw ; split ; intros H g.\n  - setoid_rewrite <- Exy ; setoid_rewrite <- Ezw ; apply H.\n  - setoid_rewrite -> Exy ; setoid_rewrite -> Ezw ; apply H.\nQed.\n\n(* A lower bound is smaller than an upper bound. *)\nLemma lower_below_upper (x : R) (q r : Q) : lower x q -> upper x r -> (q < r)%Q.\nProof.\n  intros Lq Ur.\n  destruct (Q_dec q r) as [[E1 | E2] | E3].\n  - assumption.\n  - exfalso. apply (disjoint x r).\n    auto using (lower_lower x r q).\n  - exfalso. apply (disjoint x r).\n    split; [idtac | assumption].\n    rewrite <- E3; assumption.\nQed.\n\n(* The lower cut is closed for [Rle]. *)\nLemma lower_le (x : R) (q r : Q) : lower x r -> (q <= r)%Q -> lower x q.\nProof.\n  intros H G.\n  destruct (proj1 (Qle_lteq q r) G) as [E|E].\n  + apply (lower_lower x q r) ; assumption.\n  + rewrite E ; assumption.\nQed.\n\n(* The upper cut is closed for [Rle]. *)\nLemma upper_le (x : R) (q r : Q) : upper x q -> (q <= r)%Q -> upper x r.\nProof.\n  intros H G.\n  destruct (proj1 (Qle_lteq q r) G) as [E|E].\n  + apply (upper_upper x q r) ; assumption.\n  + rewrite <- E ; assumption.\nQed.\n\n(** Injection of rational numbers into reals. *)\nDefinition R_of_Q : Q -> R.\nProof.\n  intro s.\n  refine {| lower := (fun q => (q < s)%Q) ; upper := (fun r => (s < r)%Q) |}.\n  - intros ? ? E. rewrite E. tauto.\n  - intros ? ? E. rewrite E. tauto.\n  - exists (s + (-1#1)) ; apply Qlt_minus_1.\n  - exists (s + 1) ; apply Qlt_plus_1.\n  - intros q r ? ? ; apply (Qlt_trans _ r); assumption.\n  - intros q H.\n    exists ((q + s) * (1#2)). split.\n    + apply (Qmult_lt_r _ _ (2#1)); [reflexivity | idtac].\n      apply (Qplus_lt_r _ _ (-q)).\n      ring_simplify.\n      exact H.\n    + apply (Qmult_lt_r _ _ (2#1)); [reflexivity | idtac].\n      apply (Qplus_lt_r _ _ (-s)).\n      ring_simplify.\n      exact H.\n  - intros. apply (Qlt_trans _ q); assumption.\n  - intros r H.\n    exists ((s + r) * (1#2)). split.\n    + apply (Qmult_lt_r _ _ (2#1)); [reflexivity | idtac].\n      apply (Qplus_lt_r _ _ (-r)).\n      ring_simplify.\n      exact H.\n    + apply (Qmult_lt_r _ _ (2#1)); [reflexivity | idtac].\n      apply (Qplus_lt_r _ _ (-s)).\n      ring_simplify.\n      exact H.\n  - intros q [H G].\n    apply (Qlt_irrefl q).\n    transitivity s; assumption.\n  - intros q r H.\n    destruct (Qlt_le_dec q s) as [G | G].\n    + left; assumption.\n    + right. apply (Qle_lt_trans _ q); assumption.\nDefined.\n\n(** The injection of Q into R respects equality. *)\nInstance R_of_Q_proper : Proper (Qeq ==> Req) R_of_Q.\nProof.\n  intros s t E.\n  unfold Req, Rle.\n  simpl; split; intro; rewrite E; tauto.\nQed.\n\n(** We declare that [R_of_Q] can be used automatically to coerce\n    rational numbers to real numbers. *)\nCoercion R_of_Q : Q >-> R.\n\nLemma R_is_Q_iff : forall (x:R) (q:Q),\n    x == q <-> (forall r:Q, (Qlt q r -> upper x r) /\\ (Qlt r q -> lower x r)).\nProof.\n  split.\n  - split.\n    + intro. apply Req_equiv in H. destruct H.\n      apply (H r). simpl. exact H0.\n    + intro. destruct H. apply (H1 r). simpl. exact H0.\n  - split.\n    + intros s H0. simpl. destruct (Qlt_le_dec s q). exact q0.\n      exfalso. \n      destruct (lower_open x s H0). specialize (H x0) as [H _].\n      apply (disjoint x x0). split. apply H1. apply H.\n      apply (Qle_lt_trans q s _ q0). apply H1.\n    + intros s H0. simpl in H0. pose proof (H s) as [_ H1].\n      apply H1. exact H0.\nQed.\n\n(** Definition of common constants. *)\nDefinition Rzero : R := R_of_Q 0.\nDefinition Zone : R := R_of_Q 1.\n\nNotation \"0\" := (Rzero) : R_scope.\nNotation \"1\" := (Zone) : R_scope.\n", "meta": {"author": "andrejbauer", "repo": "dedekind-reals", "sha": "662d194291e181d50b623f47e49782353aba9baf", "save_path": "github-repos/coq/andrejbauer-dedekind-reals", "path": "github-repos/coq/andrejbauer-dedekind-reals/dedekind-reals-662d194291e181d50b623f47e49782353aba9baf/Cut.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.6924702995107163}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Lia.\n\nFrom Undecidability.Shared.Libs.DLW \n  Require Import utils gcd prime pos vec.\n\nSet Implicit Arguments.\nSet Default Goal Selector \"!\".\n\n#[local] Notation \"e #> x\" := (vec_pos e x).\n#[local] Notation \"e [ v / x ]\" := (vec_change e x v).\n\nRecord godel_coding n := {\n  gc_pr : pos n -> nat;\n  gc_enc : vec nat n -> nat;\n  gc_pr_nz : forall p, 0 < gc_pr p;\n  gc_not_div : forall p v, v#>p = 0 -> ~ divides (gc_pr p) (gc_enc v);\n  gc_succ : forall p v, gc_pr p * gc_enc v = gc_enc (v[(S (v#>p))/p])\n}.\n\nArguments godel_coding : clear implicits.\n\nSection powers_of_2357_props.\n\n  (* We use prime_bool_spec which is a crude Boolean primility test *)\n\n  Local Fact prime_2 : prime 2.   Proof. apply prime_bool_spec; trivial. Qed.\n  Local Fact prime_3 : prime 3.   Proof. apply prime_bool_spec; trivial. Qed.\n  Local Fact prime_5 : prime 5.   Proof. apply prime_bool_spec; trivial. Qed.\n  Local Fact prime_7 : prime 7.   Proof. apply prime_bool_spec; trivial. Qed.\n\n  Hint Resolve prime_2 prime_3 prime_5 prime_7 : core.\n\n  Ltac does_not_divide_1 := now intros H%divides_pow%prime_divides.\n\n  Local Fact not_divides_2_3 x : ~ divides 2 (3^x).   Proof. does_not_divide_1. Qed.\n  Local Fact not_divides_2_5 x : ~ divides 2 (5^x).   Proof. does_not_divide_1. Qed.\n  Local Fact not_divides_2_7 x : ~ divides 2 (7^x).   Proof. does_not_divide_1. Qed.\n\n  Local Fact not_divides_3_2 x : ~ divides 3 (2^x).   Proof. does_not_divide_1. Qed.\n  Local Fact not_divides_3_5 x : ~ divides 3 (5^x).   Proof. does_not_divide_1. Qed.\n  Local Fact not_divides_3_7 x : ~ divides 3 (7^x).   Proof. does_not_divide_1. Qed.\n\n  Local Fact not_divides_5_2 x : ~ divides 5 (2^x).   Proof. does_not_divide_1. Qed.\n  Local Fact not_divides_5_3 x : ~ divides 5 (3^x).   Proof. does_not_divide_1. Qed.\n  Local Fact not_divides_5_7 x : ~ divides 5 (7^x).   Proof. does_not_divide_1. Qed.\n\n  Local Fact not_divides_7_2 x : ~ divides 7 (2^x).   Proof. does_not_divide_1. Qed.\n  Local Fact not_divides_7_3 x : ~ divides 7 (3^x).   Proof. does_not_divide_1. Qed.\n  Local Fact not_divides_7_5 x : ~ divides 7 (5^x).   Proof. does_not_divide_1. Qed.\n\n  Hint Resolve not_divides_2_3 not_divides_2_5 not_divides_2_7\n               not_divides_3_2 not_divides_3_5 not_divides_3_7\n               not_divides_5_2 not_divides_5_3 not_divides_5_7 \n               not_divides_7_2 not_divides_7_3 not_divides_7_5 : core.\n\n  Local Fact not_divides_5_1 : ~ divides 5 1.\n  Proof. apply not_divides_5_3 with (x := 0). Qed.\n\n  Ltac fold_not := match goal with |- ?t -> False => change (~ t) end.\n  Ltac does_not_divide_2 :=\n    let H := fresh \n    in intros [H|H]%prime_div_mult; auto; revert H; fold_not; auto.\n\n  Local Fact not_divides_2_35 x y : ~ divides 2 (3^x*5^y).   Proof. does_not_divide_2. Qed.\n  Local Fact not_divides_3_25 x y : ~ divides 3 (2^x*5^y).   Proof. does_not_divide_2. Qed.\n  Local Fact not_divides_5_23 x y : ~ divides 5 (2^x*3^y).   Proof. does_not_divide_2. Qed.\n  Local Fact not_divides_7_23 x y : ~ divides 7 (2^x*3^y).   Proof. does_not_divide_2. Qed.\n\n  Hint Resolve not_divides_2_35 not_divides_3_5 not_divides_5_1 : core.\n\n  Ltac does_not_divide_3 :=\n    let H := fresh \n    in intros H; do 2 try apply prime_div_mult in H as [H|H]; auto; revert H; fold_not; auto.\n\n  Local Fact not_divides_2_357 x y z : ~ divides 2 (3^x*5^y*7^z). Proof. does_not_divide_3. Qed.\n  Local Fact not_divides_3_257 x y z : ~ divides 3 (2^x*5^y*7^z). Proof. does_not_divide_3. Qed.\n  Local Fact not_divides_5_237 x y z : ~ divides 5 (2^x*3^y*7^z). Proof. does_not_divide_3. Qed.\n  Local Fact not_divides_7_235 x y z : ~ divides 7 (2^x*3^y*5^z). Proof. does_not_divide_3. Qed.\n\nEnd powers_of_2357_props.\n\nSection godel_coding_235.\n\n  Definition combi_235 a b c := 2^a*(3^b*5^c).\n\n  Notation \"⦉ x , y , z ⦊ \" := (combi_235 x y z) (at level 1, format \"⦉ x , y , z ⦊ \").\n\n  Ltac combi_235_x_0 := unfold combi_235; rewrite Nat.pow_0_r; ring.\n\n  Local Fact combi_235_2_0 b c : ⦉0,b,c⦊ = 3^b*5^c.   Proof. combi_235_x_0. Qed.\n  Local Fact combi_235_3_0 a c : ⦉a,0,c⦊ = 2^a*5^c.   Proof. combi_235_x_0. Qed.\n  Local Fact combi_235_5_0 a b : ⦉a,b,0⦊ = 2^a*3^b.   Proof. combi_235_x_0. Qed.\n\n  Ltac combi_235_multx := unfold combi_235; rewrite Nat.pow_succ_r'; ring.\n\n  Local Fact combi_235_mult2 a b c : 2*⦉a,b,c⦊ = ⦉S a,b,c⦊ .   Proof. combi_235_multx. Qed.\n  Local Fact combi_235_mult3 a b c : 3*⦉a,b,c⦊ = ⦉a,S b,c⦊ .   Proof. combi_235_multx. Qed.\n  Local Fact combi_235_mult5 a b c : 5*⦉a,b,c⦊ = ⦉a,b,S c⦊ .   Proof. combi_235_multx. Qed.\n\n  Local Definition pos3_235 : pos 3 -> nat.\n  Proof.\n    intro p; repeat invert pos p.\n    + exact 2.\n    + exact 3.\n    + exact 5.\n  Defined.\n\n  Local Fact pos3_235_gt_0 x : 0 < pos3_235 x.\n  Proof. repeat invert pos x; cbn; lia. Qed.\n\n  Theorem godel_coding_235 : godel_coding 3.\n  Proof.\n    exists pos3_235 (fun v => ⦉v#>pos0,v#>pos1,v#>pos2⦊).\n    + apply pos3_235_gt_0.\n    + intros p; repeat invert pos p; intros v ->.\n      * rewrite combi_235_2_0; apply not_divides_2_35.\n      * rewrite combi_235_3_0; apply not_divides_3_25.\n      * rewrite combi_235_5_0; apply not_divides_5_23.\n    + intros p; repeat invert pos p; intros v; rew vec.\n      * apply combi_235_mult2.\n      * apply combi_235_mult3.\n      * apply combi_235_mult5.\n  Qed.\n\nEnd godel_coding_235.\n\nSection godel_coding_2357.\n\n  Definition combi_2357 a b c d := 2^a*(3^b*(5^c*7^d)).\n\n  Notation \"⦉ x , y , z , u ⦊\" := (combi_2357 x y z u) (at level 1, format \"⦉ x , y , z , u ⦊\").\n\n  Ltac combi_2357_x_0 := unfold combi_2357; rewrite Nat.pow_0_r; ring.\n\n  Local Fact combi_2357_2_0 b c d : ⦉0,b,c,d⦊ = 3^b*5^c*7^d.   Proof. combi_2357_x_0. Qed.\n  Local Fact combi_2357_3_0 a c d : ⦉a,0,c,d⦊ = 2^a*5^c*7^d.   Proof. combi_2357_x_0. Qed.\n  Local Fact combi_2357_5_0 a b d : ⦉a,b,0,d⦊ = 2^a*3^b*7^d.   Proof. combi_2357_x_0. Qed.\n  Local Fact combi_2357_7_0 a b c : ⦉a,b,c,0⦊ = 2^a*3^b*5^c.   Proof. combi_2357_x_0. Qed.\n\n  Ltac combi_2357_multx := unfold combi_2357; rewrite Nat.pow_succ_r'; ring.\n\n  Local Fact combi_2357_mult2 a b c d : 2*⦉a,b,c,d⦊ = ⦉S a,b,c,d⦊.   Proof. combi_2357_multx. Qed.\n  Local Fact combi_2357_mult3 a b c d : 3*⦉a,b,c,d⦊ = ⦉a,S b,c,d⦊.   Proof. combi_2357_multx. Qed.\n  Local Fact combi_2357_mult5 a b c d : 5*⦉a,b,c,d⦊ = ⦉a,b,S c,d⦊.   Proof. combi_2357_multx. Qed.\n  Local Fact combi_2357_mult7 a b c d : 7*⦉a,b,c,d⦊ = ⦉a,b,c,S d⦊.   Proof. combi_2357_multx. Qed.\n\n  Local Definition pos4_2357 : pos 4 -> nat.\n  Proof.\n    intro p; repeat invert pos p.\n    + exact 2.\n    + exact 3.\n    + exact 5.\n    + exact 7.\n  Defined.\n\n  Local Fact pos4_2357_gt_0 x : 0 < pos4_2357 x.\n  Proof. repeat invert pos x; cbn; lia. Qed.\n\n  Theorem godel_coding_2357 : godel_coding 4.\n  Proof.\n    exists pos4_2357 (fun v => ⦉v#>pos0,v#>pos1,v#>pos2,v#>pos3⦊).\n    + apply pos4_2357_gt_0.\n    + intros p; repeat invert pos p; intros v ->.\n      * rewrite combi_2357_2_0; apply not_divides_2_357.\n      * rewrite combi_2357_3_0; apply not_divides_3_257.\n      * rewrite combi_2357_5_0; apply not_divides_5_237.\n      * rewrite combi_2357_7_0; apply not_divides_7_235.\n    + intros p; repeat invert pos p; intros v; rew vec.\n      * apply combi_2357_mult2.\n      * apply combi_2357_mult3.\n      * apply combi_2357_mult5.\n      * apply combi_2357_mult7.\n  Qed.\n\nEnd godel_coding_2357.\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/godel_coding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856297, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6924454154791233}}
{"text": "(* Codes credit : Yves Bertot https://www-sop.inria.fr/members/Yves.Bertot/  *)\n(* Most comments are written by me which may not be accurate nor correct!    *)\n(* Mathematical components has an intuitive and consistent naming system:    *)\n(* 'A' for associative, 'C' for commutative, 'D' for addition, 'r' for ring  *)\n(* For more, see `ssralg.v` file in https://github.com/math-comp/math-comp   *)\n(* In this file we will see how to use basic manipulations of an algebraic   *)\n(* expression such as  move/collect a term, remove equal terms from the both *)\n(* sides of an identity, distribute addition over multiplication, etc        *)\n\n(* ------------------------------- setup ----------------------------------- *)\nFrom mathcomp Require Import all_ssreflect all_algebra.\nRequire Import QArith.\nFrom Coq Require Extraction.\n\nImport GRing.Theory Num.Theory Num.ExtraDef.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\nSection ab1.\n\n(* The following variables are used to make the code independent of          *)\n(* mathematical components.                                                  *)\n\nOpen Scope ring_scope.\n\nVariable (R : rcfType).\n\nDefinition R' := (R : Type).\n\nDefinition mul : R' -> R' -> R' := @GRing.mul _.\nDefinition add : R' -> R' -> R' := @GRing.add _.\nDefinition sub : R' -> R' -> R' := (fun x y => x - y).\nDefinition opp : R' -> R' := @GRing.opp _.\nDefinition zero : R' := 0.\nDefinition one : R' := 1.\n\nDefinition R2_theory :=\n  @mk_rt R' zero one add mul sub opp\n   (@eq R')\n   (@add0r R) (@addrC R) (@addrA R) (@mul1r R) (@mulrC R)\n     (@mulrA R) (@mulrDl R) (fun x y : R => erefl (x - y)) (@addrN R).\n\nAdd Ring R2_Ring : R2_theory.\n\n(* This tactic automates proving identities in a ring                        *)\nLtac mc_ring :=\nrewrite ?mxE /= ?(expr0, exprS, mulrS, mulr0n) -?[@GRing.add _]/add -?[@GRing.mul _]/mul\n   -?[@GRing.opp _]/opp -?[1]/one -?[0]/zero;\nmatch goal with |- @eq ?X _ _ => change X with R' end; try ring.\n\n(* ------------------------------------------------------------------------- *)\n(*                                   DEMOS                                   *)\n\nTheorem toto (x : R) :\n  sqrtr ((x - 1) ^+ 3) = \n  sqrtr (x ^+ 3 - 3%:R * x ^+ 2 + x  + x + x - 1%:R).\nProof.\n(* this works too :                                                          *)\n(* congr (sqrtr _).\nby mc_ring. *)\n\n(* rewrite [expr](_ : _ = expr2) means replace expr with expr2, this         *)\n(* replacement needs to be proved                                            *)\nrewrite [(x - 1) ^+ 3](_ : _ =\n              (x ^+ 3 - 3%:R * x ^+ 2 + x  + x + x - 1%:R)); last by mc_ring.\nby [].\nQed.\n\nTheorem toto2 (x : R) :\n   (x - 1) ^+ 3 = x ^+ 3 - 3%:R * x ^+ 2 + x  + x + x - 1%:R.\nProof.\n(* ! means do it as many as possible, (tac1, tac2, ..., tacn) means apply    *)\n(* any of these tactics when it is possible                                  *)\nrewrite !(exprS, expr0, mulr1, mulrBl, mulrBr, mul1r, addrA, opprB).\nrewrite [1%:R](_ : _ = 1); last by []. (* 1%R and 1 live in different places *)\n(* push the 1 to the right. *)\nrewrite !(addrAC _ (- 1)).\n(* get rid of both ones. *)\n congr (_ + _).\n(* push the parentheses in additions to the right. *)\nrewrite -!addrA.\n(* the first and second terms, that are equal. *)\nrewrite !(mulrS, addr0, mulrDl) .\nrewrite mulr0n.\nrewrite mul0r.\nrewrite addr0.\nrewrite !mul1r.\nrewrite !opprD.\nrewrite -!addrA.\ncongr (_ + (_ + _)).\nrewrite (addrC x).\nrewrite !addrA.\nrewrite !(addrAC _ x).\nby [].\nQed.\n\nTheorem toto3 (x : R) :\n   (x - 1) ^+ 3 = x ^+ 3 - 3%:R * x ^+ 2 + x  + x + x - 1%:R.\nProof.\nby rewrite !(exprS, expr0, mulr1, mulrBl, mulrBr, mul1r, addrA, opprB,\n    mulrS, addr0, mulrDl, opprD, mulr0n, subr0,\n    (fun y => addrAC y (-1)), (fun y z => addrAC y z (- (x * x)))).\nQed.\n", "meta": {"author": "akaalharbi", "repo": "voronoi-fortune", "sha": "e18cf31905e4ff7e1304360ea91c9474a510990d", "save_path": "github-repos/coq/akaalharbi-voronoi-fortune", "path": "github-repos/coq/akaalharbi-voronoi-fortune/voronoi-fortune-e18cf31905e4ff7e1304360ea91c9474a510990d/doc/polynomial-equalities-experiment.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6923361687904119}}
{"text": "(* Software Foundations *)\n(* Exercice 3 stars, app_length_cons *)\n\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nTheorem app_length_cons : forall (X : Type) (l1 l2 : list X) (x : X) (n : nat), \n      length (l1 ++(x :: l2))=n -> S (length (l1 ++ l2)) = n.\nProof.\n    intros X l1. induction l1 as [|h1 t1].\n    intros. generalize dependent n.\n    simpl. intros. apply H.\n    simpl. induction n as [|n'].\n    intros contra. inversion contra.\n    intros H. inversion H. apply IHt1 in H1. rewrite H1. rewrite H. reflexivity.\nQed.\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter7_Library_MoreCoq/app_length_cons.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639065, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6923361644683766}}
{"text": "Require Export Utf8.\nRequire Export Arith.\nRequire Export Lia.\nRequire Export Recdef.\n\nFixpoint Sum (n0 : nat) :=\n  match n0 with\n  | 0   => 0\n  | S n => S (n + Sum n)\n  end.\n\nLemma le_sum : forall n, n <= Sum n.\nProof.\n  induction n.\n  simpl. lia.\n  simpl.\n  lia.\nQed.\n\nDefinition cpair (n m : nat) : nat := n + Sum (n + m).\nNotation \"( x ; y )\" := (cpair x y) (at level 0).\n\nLemma le_cpair_fst n m : n <= cpair n m.\nProof.\n  unfold cpair.\n  lia.\nQed.\n\nLemma le_cpair_snd n m : m <= cpair n m.\nProof.\n  unfold cpair.\n  assert(H := le_sum (n + m)).\n  lia.\nQed.\n\n(* Sum (summax n) <= n < n + Sum (summax n) *)\n\nFixpoint summax (n0 : nat) :=\n  match n0 with\n  | 0 => 0\n  | S n =>\n    let m := summax n in\n    match (le_lt_dec (Sum (S m)) (S n)) with\n    | left _  => S m\n    | right _ => m\n    end\n  end.\n\nDefinition fst (n : nat) := n - Sum (summax n).\nDefinition snd (n : nat) := summax n - fst n.\n\nCompute fst 5.\nCompute snd 5.\n\nLemma lt_I_lt_sum_sum : forall n m,\n  n < m -> Sum n < Sum m.\nProof.\n  assert(forall n m, Sum m < Sum (S n + m)).\n  {\n    induction n.\n    simpl. lia.\n    simpl.\n    intros.\n    specialize (IHn m).\n    simpl in IHn.\n    lia.\n  }\n  intros.\n  pose (l := m - S n).\n  assert (m = S l + n). lia.\n  rewrite H1.\n  auto.\nQed.\n\nLemma lt_sum_sum_I_lt : forall n m,\n  Sum n < Sum m -> n < m.\nProof.\n  assert(forall n m, Sum m <= Sum (n + m)).\n  {\n    induction n.\n    simpl. lia.\n    simpl.\n    intros.\n    specialize (IHn m).\n    lia.\n  }\n  intros.\n  destruct(le_lt_dec m n).\n  - assert(Sum m <= Sum n).\n    pose (s := n - m).\n    assert (n = s + m). lia.\n    rewrite H1. auto.\n    lia.\n  - lia.\nQed.\n\nLemma le_sum_sum_I_le : forall n m,\n  Sum n <= Sum m -> n <= m.\nProof.\n  intros.\n  destruct (le_lt_eq_dec (Sum n) (Sum m) H).\n  apply lt_sum_sum_I_lt in l.\n  lia.\n  destruct(le_lt_dec n m).\n  lia.\n  apply lt_I_lt_sum_sum in l.\n  lia.\nQed.\n    \nLemma le_sum_summax_A_lt_sum_s_summax : forall n,\n  Sum (summax n) <= n < Sum (S (summax n)).\nProof.\n  induction n.\n  - simpl. lia.\n  - destruct IHn.\n    Opaque Sum.\n    simpl.\n    Transparent Sum.\n    destruct (le_lt_dec (Sum (S (summax n))) (S n)).\n    split. lia.\n    simpl. simpl in H0. simpl in l.\n    lia.\n    split.\n    lia.\n    lia.\nQed.\n\nLemma summax_cpair_E_plus : forall n m,\n  summax (cpair n m) = n + m.\nProof.\n  unfold cpair.\n  intros.\n  assert (H := le_sum_summax_A_lt_sum_s_summax (n + Sum (n + m))).\n  destruct H.\n  assert (n + Sum (n + m) < Sum (S (n + m))).\n  simpl. lia.\n  assert (summax (n + Sum (n + m)) < S (n + m)).\n  apply lt_sum_sum_I_lt. lia.\n  assert (n + m < S (summax (n + Sum (n + m)))).\n  apply lt_sum_sum_I_lt. lia.\n  lia.\nQed.\n\nTheorem pairing_fst : forall n m, fst (n; m) = n.\nProof.\n  unfold fst.\n  intros.\n  rewrite summax_cpair_E_plus.\n  unfold cpair.\n  lia.\nQed.\n\nTheorem pairing_snd : forall n m, snd (n; m) = m.\nProof.\n  intros.\n  unfold snd.\n  rewrite pairing_fst.\n  rewrite summax_cpair_E_plus.\n  lia.\nQed.\n\nTheorem pairing_inj_fst : forall x y u v,\n  cpair x y = cpair u v -> x = u.\nProof.\n  intros.\n  assert(H0 := pairing_fst x y).\n  rewrite <- H0.\n  rewrite H.\n  apply pairing_fst.\nQed.\n\nTheorem pairing_inj_snd : forall x y u v,\n  cpair x y = cpair u v -> y = v.\nProof.\n  intros.\n  assert(H0 := pairing_snd x y).\n  rewrite <- H0.\n  rewrite H.\n  apply pairing_snd.\nQed.\n\nTheorem n_E_cpair_fst_snd : forall n,\n  n = (fst n; snd n).\nProof.\n  intros.\n  unfold cpair, snd, fst.\n  assert (H := le_sum_summax_A_lt_sum_s_summax n).\n  destruct H.\n  simpl in H0.\n  assert (n - Sum (summax n) + (summax n - (n - Sum (summax n))) = summax n). lia.\n  rewrite H1.\n  lia.\nQed.\n\nLemma fst_descending : forall n,\n  fst n < S n.\nProof.\n  unfold fst.\n  intros.\n  lia.\nQed.\n\nLemma snd_descending : forall n,\n  snd n < S n.\nProof.\n  intros.\n  rewrite (n_E_cpair_fst_snd n) at 2.\n  assert (H := le_cpair_snd (fst n) (snd n)).\n  lia.\nQed.\n\nDefinition cnil := 0.\nDefinition ccons (n m : nat) := S (n; m).\n\nNotation \"`( x ; y ; .. ; z )\" := (ccons x (ccons y .. (ccons z cnil) ..)).\n\nCompute `(0;1;0;0).\n\nFixpoint nth (n0 m0 : nat) : nat :=\n  match n0, m0 with\n  | 0, S m   => S (fst m)\n  | S n, S m => nth n (snd m)\n  | _, 0     => 0 \n  end.\n\nFunction lh (n0 : nat) {wf lt n0}: nat :=\n  match n0 with\n  | 0 => 1\n  | S n => S (lh (snd n))\n  end.\nProof.\n  intros.\n  apply snd_descending.\n  exact lt_wf.\nQed.", "meta": {"author": "iehality", "repo": "Computability", "sha": "5d8ef310d53ecaf6b2aca9f9963ebcb21266dcc2", "save_path": "github-repos/coq/iehality-Computability", "path": "github-repos/coq/iehality-Computability/Computability-5d8ef310d53ecaf6b2aca9f9963ebcb21266dcc2/Pairing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6923361601463416}}
{"text": "Require Import List.\n\nInductive binop : Set := \n| Plus  : binop\n| Times : binop\n.\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Binop : binop -> exp-> exp -> exp\n.\n\nDefinition binopDenote (b:binop) : nat -> nat -> nat :=\n    match b with \n    | Plus  => plus\n    | Times => mult\n    end.\n\n(* type inference at play *) \nDefinition binopDenote' := fun b => \n    match b with\n    | Plus  => plus\n    | Times => mult\n    end.\n\nFixpoint expDenote (e:exp) : nat :=\n    match e with\n    | Const n       => n\n    | Binop b e1 e2 => binopDenote b (expDenote e1) (expDenote e2)\n    end.\n\nInductive instr : Set :=\n| iConst : nat   -> instr\n| iBinop : binop -> instr\n.\n\nDefinition prog  : Set := list instr.\nDefinition stack : Set := 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        | x1 :: x2 :: s'    => Some ((binopDenote b) x1 x2 :: 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 :: q    => \n        match instrDenote i s with\n        | None      => None\n        | Some s'   => progDenote q s'\n        end\n    end.\n\nFixpoint compile (e:exp) : prog :=\n    match e with\n    | Const n       => iConst n :: nil\n    | Binop b e1 e2 => compile e2 ++ compile e1 ++ iBinop b :: nil\n    end.\n\n\nDefinition eval (e:exp) : option nat :=\n    match progDenote (compile e) nil with\n    | Some (n::nil) => Some n\n    | _             => None\n    end.\n\nLemma compile_correct' : forall (e:exp) (p:prog) (s:stack),\n    progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\nProof.\n    intros e. induction e as [n|b e1 H1 e2 H2]; intros p s; simpl.\n    - reflexivity.\n    - rewrite app_assoc_reverse. rewrite H2. \n      rewrite app_assoc_reverse. rewrite H1.\n      reflexivity.\nQed.\n\nTheorem compile_correct : forall (e:exp), eval e = Some (expDenote e).\nProof.\n    intros e. unfold eval. rewrite <- (app_nil_r (compile e)).\n    rewrite compile_correct'. reflexivity.\nQed.\n\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/cpdt/untyped.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.6923286876225565}}
{"text": "Require Import Coq.Program.Tactics.\nRequire Import Coq.Program.Wf.\nRequire Import Lia.\nRequire Export Nat.\n\n(* Variables *)\nDefinition var := nat.\n\n(* Predicate expressions *)\nInductive expr : Type :=\n| PNat (n : nat)\n| PVar (x : var)\n| PAdd (e1 e2 : expr).\n\n(* Change of variables in exprs *)\nFixpoint change_var_expr (e : expr) (from to : var) : expr :=\n  match e with\n  | PNat _ => e\n  | PVar x =>\n      if x =? from then PVar to else e\n  | PAdd e1 e2 =>\n      PAdd (change_var_expr e1 from to) (change_var_expr e2 from to)\n  end.\n\n(* Substitute a nat for a var in an expr *)\nFixpoint subst_expr (e : expr) (from : var) (to : nat) : expr :=\n  match e with\n  | PNat _ => e\n  | PVar x =>\n      if x =? from then PNat to else e\n  | PAdd e1 e2 =>\n      PAdd (subst_expr e1 from to) (subst_expr e2 from to)\n  end.\n\n(* Simplify an expr *)\nFixpoint simpl_expr (e : expr) : expr :=\n  match e with\n  | PAdd e1 e2 =>\n      let e1' := simpl_expr e1 in\n      let e2' := simpl_expr e2 in\n      match e1', e2' with\n      | PNat n, PNat m => PNat (n + m)\n      | _, _ => PAdd e1' e2'\n      end\n  | _ => e\n  end.\n\n(* Predicates *)\nInductive pred : Type :=\n| PBool (b : bool)\n| PEq (e1 e2 : expr)\n| PAnd (p1 p2 : pred)\n| POr (p1 p2 : pred).\n\n(* Change of variables in preds *)\nFixpoint change_var_pred (p : pred) (from to : var) : pred :=\n  match p with\n  | PBool _ => p\n  | PEq e1 e2 =>\n      PEq (change_var_expr e1 from to) (change_var_expr e2 from to)\n  | PAnd p1 p2 =>\n      PAnd (change_var_pred p1 from to) (change_var_pred p2 from to)\n  | POr p1 p2 =>\n      POr (change_var_pred p1 from to) (change_var_pred p2 from to)\n  end.\n\n(* Substitute a nat for a var in a pred *)\nFixpoint subst_pred (p : pred) (from : var) (to : nat) : pred :=\n  match p with\n  | PBool _ => p\n  | PEq e1 e2 =>\n      PEq (subst_expr e1 from to) (subst_expr e2 from to)\n  | PAnd p1 p2 =>\n      PAnd (subst_pred p1 from to) (subst_pred p2 from to)\n  | POr p1 p2 =>\n      POr (subst_pred p1 from to) (subst_pred p2 from to)\n  end.\n\n(* Simplify a pred *)\nFixpoint simpl_pred (p : pred) : pred :=\n  match p with\n  | PBool _ => p\n  | PEq e1 e2 =>\n      PEq (simpl_expr e1) (simpl_expr e2)\n  | PAnd p1 p2 =>\n      PAnd (simpl_pred p1) (simpl_pred p2)\n  | POr p1 p2 =>\n      POr (simpl_pred p1) (simpl_pred p2)\n  end.\n\n(* Convert a pred into its equivalent Prop *)\nFixpoint pred_prop (p : pred) : Prop :=\n  match p with\n  | PBool true => True\n  | PBool false => False\n  | PEq e1 e2 => e1 = e2\n  | PAnd p1 p2 => (pred_prop p1) /\\ (pred_prop p2)\n  | POr p1 p2 => (pred_prop p1) \\/ (pred_prop p2)\n  end.\n\n(* Substitution satisfies a simplified predicate *)\nDefinition sat_pred p x n := pred_prop (simpl_pred (subst_pred p x n)).\n\n(* Constraints *)\nInductive cnst : Type :=\n| CPred (p : pred)\n| CAnd (c1 c2 : cnst)\n| CImpl (x : var) (p : pred) (c : cnst).\n\n(* Substitute a nat for a var in a cnst *)\nFixpoint subst_cnst (c : cnst) (from : var) (to : nat) : cnst :=\n  match c with\n  | CPred p =>\n      CPred (subst_pred p from to)\n  | CAnd c1 c2 =>\n      CAnd (subst_cnst c1 from to) (subst_cnst c2 from to)\n  | CImpl x p c' =>\n      if x =? from then\n        c\n      else\n        CImpl x (subst_pred p from to) (subst_cnst c' from to)\n  end.\n\n(* Height of a cnst, needed to prove termination below *)\nFixpoint cnst_height (c : cnst) : nat :=\n  match c with\n  | CPred _ => 1\n  | CAnd c1 c2 =>\n      1 + max (cnst_height c1) (cnst_height c2)\n  | CImpl x p c' => 1 + cnst_height c'\n  end.\n\n(* Convert a cnst into its equivalent Prop *)\nProgram Fixpoint cnst_prop (c : cnst) {measure (cnst_height c)} : Prop :=\n  match c with\n  | CPred p => pred_prop (simpl_pred p)\n  | CAnd c1 c2 =>\n      (cnst_prop c1) /\\ (cnst_prop c2)\n  | CImpl x p c' =>\n      forall n, sat_pred p x n -> cnst_prop (subst_cnst c' x n)\n  end.\nNext Obligation.\n  destruct c1; simpl; destruct c2; simpl; lia.\nQed.\nNext Obligation.\n  destruct c2; simpl; destruct c1; simpl; lia.\nQed.\nNext Obligation.\n  assert (H: forall c y m, cnst_height (subst_cnst c y m) = cnst_height c).\n  {\n    intros. induction c; simpl.\n    - reflexivity.\n    - rewrite IHc1, IHc2. reflexivity.\n    - destruct (x0 =? y); simpl.\n      + reflexivity.\n      + rewrite IHc. reflexivity.\n  }\n  simpl. rewrite H. lia.\nQed.\n\n(* Useful results *)\n\nLemma same_var_change_expr : forall e x, change_var_expr e x x = e.\nProof.\n  intros. induction e.\n  - reflexivity.\n  - simpl. destruct (x0 =? x) eqn:E0.\n    + apply PeanoNat.Nat.eqb_eq in E0.\n      rewrite E0. reflexivity.\n    + reflexivity.\n  - simpl. rewrite IHe1, IHe2. reflexivity.\nQed.\n\nLemma same_var_change_pred : forall p x, change_var_pred p x x = p.\nProof.\n  intros. induction p.\n  - reflexivity.\n  - simpl. repeat rewrite same_var_change_expr. reflexivity.\n  - simpl. rewrite IHp1, IHp2. reflexivity.\n  - simpl. rewrite IHp1, IHp2. reflexivity.\nQed.\n", "meta": {"author": "ikretz", "repo": "srtc", "sha": "aa903eee7a764d4be0287a81cbecf1346f96c9e1", "save_path": "github-repos/coq/ikretz-srtc", "path": "github-repos/coq/ikretz-srtc/srtc-aa903eee7a764d4be0287a81cbecf1346f96c9e1/Pred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.6923286810090177}}
{"text": "\nRequire Import Omega.\n\n(* Submitted by Xavier Urbain 18 Jan 2002 *)\n\nLemma lem1 :\n forall x y : Z, (-5 < x < 5)%Z -> (-5 < y)%Z -> (-5 < x + y + 5)%Z.\nProof.\nintros x y.\n omega.\nQed.\n\n(* Proposed by Pierre Crégut *)\n\nLemma lem2 : forall x : Z, (x < 4)%Z -> (x > 2)%Z -> x = 3%Z.\nintro.\n omega.\nQed.\n\n(* Proposed by Jean-Christophe Filliâtre *)\n\nLemma lem3 : forall x y : Z, x = y -> (x + x)%Z = (y + y)%Z.\nProof.\nintros.\n omega.\nQed.\n\n(* Proposed by Jean-Christophe Filliâtre: confusion between an Omega *)\n(* internal variable and a section variable (June 2001) *)\n\nSection A.\nVariable x y : Z.\nHypothesis H : (x > y)%Z.\nLemma lem4 : (x > y)%Z.\n omega.\nQed.\nEnd A.\n\n(* Proposed by Yves Bertot: because a section var, L was wrongly renamed L0 *)\n(* May 2002 *)\n\nSection B.\nVariable R1 R2 S1 S2 H S : Z.\nHypothesis I : (R1 < 0)%Z -> R2 = (R1 + (2 * S1 - 1))%Z.\nHypothesis J : (R1 < 0)%Z -> S2 = (S1 - 1)%Z.\nHypothesis K : (R1 >= 0)%Z -> R2 = R1.\nHypothesis L : (R1 >= 0)%Z -> S2 = S1.\nHypothesis M : (H <= 2 * S)%Z.\nHypothesis N : (S < H)%Z.\nLemma lem5 : (H > 0)%Z.\n omega.\nQed.\nEnd B.\n\n(* From Nicolas Oury (BZ#180): handling -> on Set (fixed Oct 2002) *)\nLemma lem6 :\n forall (A : Set) (i : Z), (i <= 0)%Z -> ((i <= 0)%Z -> A) -> (i <= 0)%Z.\nintros.\n omega.\nQed.\n\n(* Adapted from an example in Nijmegen/FTA/ftc/RefSeparating (Oct 2002) *)\nRequire Import Omega.\nSection C.\nParameter g : forall m : nat, m <> 0 -> Prop.\nParameter f : forall (m : nat) (H : m <> 0), g m H.\nVariable n : nat.\nVariable ap_n : n <> 0.\nLet delta := f n ap_n.\nLemma lem7 : n = n.\n omega.\nQed.\nEnd C.\n\n(* Problem of dependencies *)\nRequire Import Omega.\nLemma lem8 : forall H : 0 = 0 -> 0 = 0, H = H -> 0 = 0.\nintros;  omega.\nQed.\n\n(* Bug that what caused by the use of intro_using in Omega *)\nRequire Import Omega.\nLemma lem9 :\n forall p q : nat, ~ (p <= q /\\ p < q \\/ q <= p /\\ p < q) -> p < p \\/ p <= p.\nintros;  omega.\nQed.\n\n(* Check that the interpretation of mult on nat enforces its positivity *)\n(* Submitted by Hubert Thierry (BZ#743) *)\n(* Postponed... problem with goals of the form \"(n*m=0)%nat -> (n*m=0)%Z\" *)\nLemma lem10 : forall n m:nat, le n (plus n (mult n m)).\nProof.\nintros; omega with *.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/success/Omega.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733955639775, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.6923286728996478}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\nSet Implicit Arguments.\n\nRequire Import Notations.\nRequire Import Logic.\nDeclare ML Module \"nat_syntax_plugin\".\n\n(********************************************************************)\n(** * Datatypes with zero and one element *)\n\n(** [Empty_set] is a datatype with no inhabitant *)\n\nInductive Empty_set : Set :=.\n\n(** [unit] is a singleton datatype with sole inhabitant [tt] *)\n\nInductive unit : Set :=\n    tt : unit.\n\n\n(********************************************************************)\n(** * The boolean datatype *)\n\n(** [bool] is the datatype of the boolean values [true] and [false] *)\n\nInductive bool : Set :=\n  | true : bool\n  | false : bool.\n\nAdd Printing If bool.\n\nDelimit Scope bool_scope with bool.\n\nBind Scope bool_scope with bool.\n\n(** Basic boolean operators *)\n\nDefinition andb (b1 b2:bool) : bool := if b1 then b2 else false.\n\nDefinition orb (b1 b2:bool) : bool := if b1 then true else b2.\n\nDefinition implb (b1 b2:bool) : bool := if b1 then b2 else true.\n\nDefinition xorb (b1 b2:bool) : bool :=\n  match b1, b2 with\n    | true, true => false\n    | true, false => true\n    | false, true => true\n    | false, false => false\n  end.\n\nDefinition negb (b:bool) := if b then false else true.\n\nInfix \"||\" := orb : bool_scope.\nInfix \"&&\" := andb : bool_scope.\n\n(** Basic properties of [andb] *)\n\nLemma andb_prop : forall a b:bool, andb a b = true -> a = true /\\ b = true.\nProof.\n  destruct a, b; repeat split; assumption.\nQed.\nHint Resolve andb_prop: bool.\n\nLemma andb_true_intro :\n  forall b1 b2:bool, b1 = true /\\ b2 = true -> andb b1 b2 = true.\nProof.\n  destruct b1; destruct b2; simpl; intros [? ?]; assumption.\nQed.\nHint Resolve andb_true_intro: bool.\n\n(** Interpretation of booleans as propositions *)\n\nInductive eq_true : bool -> Prop := is_eq_true : eq_true true.\n\nHint Constructors eq_true : eq_true.\n\n(** Another way of interpreting booleans as propositions *)\n\nDefinition is_true b := b = true.\n\n(** [is_true] can be activated as a coercion by\n   ([Local]) [Coercion is_true : bool >-> Sortclass].\n*)\n\n(** Additional rewriting lemmas about [eq_true] *)\n\nLemma eq_true_ind_r :\n  forall (P : bool -> Prop) (b : bool), P b -> eq_true b -> P true.\nProof.\n  intros P b H H0; destruct H0 in H; assumption.\nDefined.\n\nLemma eq_true_rec_r :\n  forall (P : bool -> Set) (b : bool), P b -> eq_true b -> P true.\nProof.\n  intros P b H H0; destruct H0 in H; assumption.\nDefined.\n\nLemma eq_true_rect_r :\n  forall (P : bool -> Type) (b : bool), P b -> eq_true b -> P true.\nProof.\n  intros P b H H0; destruct H0 in H; assumption.\nDefined.\n\n(** The [BoolSpec] inductive will be used to relate a [boolean] value\n    and two propositions corresponding respectively to the [true]\n    case and the [false] case.\n    Interest: [BoolSpec] behave nicely with [case] and [destruct].\n    See also [Bool.reflect] when [Q = ~P].\n*)\n\nInductive BoolSpec (P Q : Prop) : bool -> Prop :=\n  | BoolSpecT : P -> BoolSpec P Q true\n  | BoolSpecF : Q -> BoolSpec P Q false.\nHint Constructors BoolSpec.\n\n\n(********************************************************************)\n(** * Peano natural numbers *)\n\n(** [nat] is the datatype of natural numbers built from [O] and successor [S];\n    note that the constructor name is the letter O.\n    Numbers in [nat] can be denoted using a decimal notation;\n    e.g. [3%nat] abbreviates [S (S (S O))] *)\n\nInductive nat : Set :=\n  | O : nat\n  | S : nat -> nat.\n\nDelimit Scope nat_scope with nat.\nBind Scope nat_scope with nat.\nArguments S _%nat.\n\n\n(********************************************************************)\n(** * Container datatypes *)\n\n(* Set Universe Polymorphism. *)\n\n(** [option A] is the extension of [A] with an extra element [None] *)\n\nInductive option (A:Type) : Type :=\n  | Some : A -> option A\n  | None : option A.\n\nArguments Some {A} a.\nArguments None {A}.\n\nDefinition option_map (A B:Type) (f:A->B) (o : option A) : option B :=\n  match o with\n    | Some a => @Some B (f a)\n    | None => @None B\n  end.\n\n(** [sum A B], written [A + B], is the disjoint sum of [A] and [B] *)\n\nInductive sum (A B:Type) : Type :=\n  | inl : A -> sum A B\n  | inr : B -> sum A B.\n\nNotation \"x + y\" := (sum x y) : type_scope.\n\nArguments inl {A B} _ , [A] B _.\nArguments inr {A B} _ , A [B] _.\n\n(** [prod A B], written [A * B], is the product of [A] and [B];\n    the pair [pair A B a b] of [a] and [b] is abbreviated [(a,b)] *)\n\nInductive prod (A B:Type) : Type :=\n  pair : A -> B -> prod A B.\n\nAdd Printing Let prod.\n\nNotation \"x * y\" := (prod x y) : type_scope.\nNotation \"( x , y , .. , z )\" := (pair .. (pair x y) .. z) : core_scope.\n\nArguments pair {A B} _ _.\n\nSection projections.\n  Context {A : Type} {B : Type}.\n\n  Definition fst (p:A * B) := match p with\n\t\t\t\t| (x, y) => x\n                              end.\n  Definition snd (p:A * B) := match p with\n\t\t\t\t| (x, y) => y\n                              end.\nEnd projections.\n\nHint Resolve pair inl inr: core.\n\nLemma surjective_pairing :\n  forall (A B:Type) (p:A * B), p = pair (fst p) (snd p).\nProof.\n  destruct p; reflexivity.\nQed.\n\nLemma injective_projections :\n  forall (A B:Type) (p1 p2:A * B),\n    fst p1 = fst p2 -> snd p1 = snd p2 -> p1 = p2.\nProof.\n  destruct p1; destruct p2; simpl; intros Hfst Hsnd.\n  rewrite Hfst; rewrite Hsnd; reflexivity.\nQed.\n\nDefinition prod_uncurry (A B C:Type) (f:prod A B -> C)\n  (x:A) (y:B) : C := f (pair x y).\n\nDefinition prod_curry (A B C:Type) (f:A -> B -> C)\n  (p:prod A B) : C := match p with\n                       | pair x y => f x y\n                       end.\n\n(** Polymorphic lists and some operations *)\n\nInductive list (A : Type) : Type :=\n | nil : list A\n | cons : A -> list A -> list A.\n\nArguments nil {A}.\nArguments cons {A} a l.\nInfix \"::\" := cons (at level 60, right associativity) : list_scope.\nDelimit Scope list_scope with list.\nBind Scope list_scope with list.\n\nLocal Open Scope list_scope.\n\nDefinition length (A : Type) : list A -> nat :=\n  fix length l :=\n  match l with\n   | nil => O\n   | _ :: l' => S (length l')\n  end.\n\n(** Concatenation of two lists *)\n\nDefinition app (A : Type) : list A -> list A -> list A :=\n  fix app l m :=\n  match l with\n   | nil => m\n   | a :: l1 => a :: app l1 m\n  end.\n\n\nInfix \"++\" := app (right associativity, at level 60) : list_scope.\n\n(* Unset Universe Polymorphism. *)\n\n(********************************************************************)\n(** * The comparison datatype *)\n\nInductive comparison : Set :=\n  | Eq : comparison\n  | Lt : comparison\n  | Gt : comparison.\n\nLemma comparison_eq_stable : forall c c' : comparison, ~~ c = c' -> c = c'.\nProof.\n  destruct c, c'; intro H; reflexivity || destruct H; discriminate.\nQed.\n\nDefinition CompOpp (r:comparison) :=\n  match r with\n    | Eq => Eq\n    | Lt => Gt\n    | Gt => Lt\n  end.\n\nLemma CompOpp_involutive : forall c, CompOpp (CompOpp c) = c.\nProof.\n  destruct c; reflexivity.\nQed.\n\nLemma CompOpp_inj : forall c c', CompOpp c = CompOpp c' -> c = c'.\nProof.\n  destruct c; destruct c'; auto; discriminate.\nQed.\n\nLemma CompOpp_iff : forall c c', CompOpp c = c' <-> c = CompOpp c'.\nProof.\n  split; intros; apply CompOpp_inj; rewrite CompOpp_involutive; auto.\nQed.\n\n(** The [CompareSpec] inductive relates a [comparison] value with three\n   propositions, one for each possible case. Typically, it can be used to\n   specify a comparison function via some equality and order predicates.\n   Interest: [CompareSpec] behave nicely with [case] and [destruct]. *)\n\nInductive CompareSpec (Peq Plt Pgt : Prop) : comparison -> Prop :=\n | CompEq : Peq -> CompareSpec Peq Plt Pgt Eq\n | CompLt : Plt -> CompareSpec Peq Plt Pgt Lt\n | CompGt : Pgt -> CompareSpec Peq Plt Pgt Gt.\nHint Constructors CompareSpec.\n\n(** For having clean interfaces after extraction, [CompareSpec] is declared\n    in Prop. For some situations, it is nonetheless useful to have a\n    version in Type. Interestingly, these two versions are equivalent. *)\n\nInductive CompareSpecT (Peq Plt Pgt : Prop) : comparison -> Type :=\n | CompEqT : Peq -> CompareSpecT Peq Plt Pgt Eq\n | CompLtT : Plt -> CompareSpecT Peq Plt Pgt Lt\n | CompGtT : Pgt -> CompareSpecT Peq Plt Pgt Gt.\nHint Constructors CompareSpecT.\n\nLemma CompareSpec2Type : forall Peq Plt Pgt c,\n CompareSpec Peq Plt Pgt c -> CompareSpecT Peq Plt Pgt c.\nProof.\n destruct c; intros H; constructor; inversion_clear H; auto.\nDefined.\n\n(** As an alternate formulation, one may also directly refer to predicates\n [eq] and [lt] for specifying a comparison, rather that fully-applied\n propositions. This [CompSpec] is now a particular case of [CompareSpec]. *)\n\nDefinition CompSpec {A} (eq lt : A->A->Prop)(x y:A) : comparison -> Prop :=\n CompareSpec (eq x y) (lt x y) (lt y x).\n\nDefinition CompSpecT {A} (eq lt : A->A->Prop)(x y:A) : comparison -> Type :=\n CompareSpecT (eq x y) (lt x y) (lt y x).\nHint Unfold CompSpec CompSpecT.\n\nLemma CompSpec2Type : forall A (eq lt:A->A->Prop) x y c,\n CompSpec eq lt x y c -> CompSpecT eq lt x y c.\nProof. intros. apply CompareSpec2Type; assumption. Defined.\n\n(******************************************************************)\n(** * Misc Other Datatypes *)\n\n(** [identity A a] is the family of datatypes on [A] whose sole non-empty\n    member is the singleton datatype [identity A a a] whose\n    sole inhabitant is denoted [identity_refl A a] *)\n\nInductive identity (A:Type) (a:A) : A -> Type :=\n  identity_refl : identity a a.\nHint Resolve identity_refl: core.\n\nArguments identity_ind [A] a P f y i.\nArguments identity_rec [A] a P f y i.\nArguments identity_rect [A] a P f y i.\n\n(** Identity type *)\n\nDefinition ID := forall A:Type, A -> A.\nDefinition id : ID := fun A x => x.\n\nDefinition IDProp := forall A:Prop, A -> A.\nDefinition idProp : IDProp := fun A x => x.\n\n\n(* begin hide *)\n\n(* Compatibility *)\n\nNotation prodT := prod (only parsing).\nNotation pairT := pair (only parsing).\nNotation prodT_rect := prod_rect (only parsing).\nNotation prodT_rec := prod_rec (only parsing).\nNotation prodT_ind := prod_ind (only parsing).\nNotation fstT := fst (only parsing).\nNotation sndT := snd (only parsing).\nNotation prodT_uncurry := prod_uncurry (only parsing).\nNotation prodT_curry := prod_curry (only parsing).\n\n(* end hide *)\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Init/Datatypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.6923286677819394}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (z : natural) (x : natural) (lf1 : natural)\n  : natural := plus lf1 Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj64_coqofml_22zzhO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6921886172444994}}
{"text": "Require Import bf_stack bf bf_semantics.\nRequire Import Lists.Streams.\n\nInductive ae : Set :=\n| Int : nat -> ae\n| Plus : ae -> ae -> ae\n| Minus : ae -> ae -> ae\n| Mult : ae -> ae -> ae.\n\nCoercion Int : nat >-> ae.\nNotation \"a + b\" := (Plus a b) : ae_scope.\nNotation \"a - b\" := (Minus a b) : ae_scope.\nNotation \"a * b\" := (Mult a b) : ae_scope.\nDelimit Scope ae_scope with ae.\n\nFixpoint interpret (ae : ae) : nat :=\n  match ae with\n    | Int n => n\n    | Plus e1 e2 => interpret e1 + interpret e2\n    | Minus e1 e2 => interpret e1 - interpret e2\n    | Mult e1 e2 => interpret e1 * interpret e2\n  end.\n\nFixpoint compile (ae : ae) : Instr.instruction :=\n  match ae with\n    | Int 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; mult\n  end.\n\nExample interpret_compile_example1 :\n  iter (compile (4+5-2*3)%ae, init zeroes)\n       (END, state[zeroes, interpret (4+5-2*3), zeroes, zeroes, nil]).\nProof.\n  unfold init, compile, interpret.\n  repeat bf_step.\n  unfold sub.\n  repeat bf_step.\nQed.\n\nTheorem compiler_correctness :\n  forall ae ls x,\n    iter (compile ae, state[ls, x, zeroes, zeroes, nil])\n         (END, state[Cons x ls, interpret ae, zeroes, zeroes, nil]).\nProof.\n  intro ae.\n  induction ae.\n  simpl.\n  intros.\n  apply (iter_trans _\n                    (END, state[Cons x ls, n, zeroes, zeroes, nil])).\n  apply (about_push n ls x zeroes nil).\n  bf_step.  \n\n  intros.\n  simpl.\n  apply (about_sequence (compile ae1) (compile ae2; add)\n                        _ state[Cons x ls, interpret ae1, zeroes, zeroes, nil]).\n  apply IHae1.  \n  apply (about_sequence (compile ae2) (add)\n                        _ state[Cons (interpret ae1) (Cons x ls),\n                                interpret ae2, zeroes, zeroes, nil]).\n  apply IHae2.\n  rewrite Arith.Plus.plus_comm.\n  apply about_add.\n\n  intros.\n  simpl.\n  apply (about_sequence (compile ae1) (compile ae2; sub)\n                        _ state[Cons x ls, interpret ae1, zeroes, zeroes, nil]).\n  apply IHae1.\n  apply (about_sequence (compile ae2) sub\n                        _ state[Cons (interpret ae1) (Cons x ls),\n                                interpret ae2, zeroes, zeroes, nil]).\n  apply IHae2.\n  apply about_sub.\n\n  intros.\n  simpl.\n  apply (about_sequence (compile ae1) (compile ae2; mult)\n                        _ state[Cons x ls, interpret ae1, zeroes, zeroes, nil]).\n  apply IHae1.\n  apply (about_sequence (compile ae2) mult\n                        _ state[Cons (interpret ae1) (Cons x ls),\n                                interpret ae2, zeroes, zeroes, nil]).\n  apply IHae2.\n  apply about_mult.\nQed.\n", "meta": {"author": "reynir", "repo": "Brainfuck", "sha": "13c1ea7bf376b36f94a542deaadbb7f5d2e2f0db", "save_path": "github-repos/coq/reynir-Brainfuck", "path": "github-repos/coq/reynir-Brainfuck/Brainfuck-13c1ea7bf376b36f94a542deaadbb7f5d2e2f0db/ae_compiler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6921886112597179}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) (y : natural) (lf1 : natural)\n  : natural := plus x lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj195_coqofml_gDuu8h.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6921886036124687}}
{"text": "(*** Predicates on a list ***)\n\nRequire Import Arith.\nRequire Import Bool.\nRequire Import List.\nRequire Import ott_list_base.\nRequire Import ott_list_core.\nRequire Import ott_list_takedrop.\n\n\n\nSection List_predicate_inductive.\n(* Properties of [Forall_list] and [Exists_list] *)\n\nVariables A : Set.\nImplicit Types x : A.\nImplicit Types xs l : list A.\nImplicit Types p : A -> bool.\nImplicit Types P : A -> Prop.\nSet Implicit Arguments.\n\nLemma not_Exists_list_nil : forall P, ~(Exists_list P nil).\nProof. intros P H; inversion H. Qed.\nHint Resolve not_Exists_list_nil.\n\nLemma Forall_list_dec :\n  forall P (dec : forall x, {P x} + {~P x}) l,\n    {Forall_list P l} + {~Forall_list P l}.\nProof.\n  induction l; simpl in * . solve [auto].\n  destruct (dec a); [destruct IHl | idtac]; auto;\n    right; intro; inversion_clear H; tauto.\nQed.\n\nLemma Exists_list_dec :\n  forall P (dec : forall x, {P x} + {~P x}) l,\n    {Exists_list P l} + {~Exists_list P l}.\nProof.\n  induction l; simpl in * . solve [auto].\n  destruct (dec a); [idtac | destruct IHl]; auto;\n    right; intro; inversion_clear H; tauto.\nQed.\n\nLemma Forall_Exists_list_dec :\n  forall P Q (dec : forall x, {P x} + {Q x}) l,\n    {Forall_list P l} + {Exists_list Q l}.\nProof.\n  induction l; simpl in * . solve [auto].\n  destruct (dec a); destruct IHl; auto.\nQed.\n\nLemma Forall_list_In :\n  forall P x l, In x l -> Forall_list P l -> P x.\nProof.\n  induction l; intros; simpl in *; destruct H;\n    inversion H0; subst; auto.\nQed.\n\nLemma In_Forall_list :\n  forall P l, (forall x, In x l -> P x) -> Forall_list P l.\nProof.\n  induction l; firstorder.\nQed.\n\nLemma exists_In_Exists_list :\n  forall P l, Exists_list P l -> exists x, In x l /\\ P x.\nProof.\n  induction 1.\n  exists x; simpl; tauto.\n  elim IHExists_list; intros. exists x0; simpl; tauto.\nQed.\n\nLemma Forall_list_app_left :\n  forall P l l', Forall_list P (l++l') -> Forall_list P l.\nProof.\n  intros; induction l; simpl in * . auto.\n  inversion_clear H. auto.\nQed.\nLemma Forall_list_app_right :\n  forall P l l', Forall_list P (l++l') -> Forall_list P l'.\nProof.\n  induction l; intros. auto. inversion_clear H; auto.\nQed.\nLemma app_Forall_list :\n  forall P l l', Forall_list P l -> Forall_list P l' -> Forall_list P (l++l').\nProof.\n  intros; induction l; simpl in * . assumption.\n  inversion_clear H. auto.\nQed.\nHint Resolve app_Forall_list Forall_list_app_left Forall_list_app_right.\n\nLemma Exists_list_app_or :\n  forall P l l', Exists_list P (l++l') ->\n    Exists_list P l \\/ Exists_list P l'.\nProof.\n  intros; induction l; simpl in * . solve [auto].\n  inversion_clear H. solve [auto].\n  destruct (IHl H0); solve [auto].\nQed.\nLemma app_Exists_list_left :\n  forall P l l', Exists_list P l -> Exists_list P (l++l').\nProof.\n  intros; induction l; inversion_clear H; simpl; auto.\nQed.\nLemma app_Exists_list_right :\n  forall P l l', Exists_list P l' -> Exists_list P (l++l').\nProof.\n  intros; induction l; simpl; auto.\nQed.\nHint Resolve Exists_list_app_or app_Exists_list_left app_Exists_list_right.\n\nLemma rev_Forall_list :\n  forall P l, Forall_list P l -> Forall_list P (rev l).\nProof. induction 1; simpl; auto. Qed.\nLemma rev_Exists_list :\n  forall P l, Exists_list P l -> Exists_list P (rev l).\nProof. induction 1; simpl; auto. Qed.\nLemma Forall_list_rev :\n  forall P l, Forall_list P (rev l) -> Forall_list P l.\nProof.\n  intros. rewrite <- (rev_involutive l). apply rev_Forall_list; assumption.\nQed.\nLemma Exists_list_rev :\n  forall P l, Exists_list P (rev l) -> Exists_list P l.\nProof.\n  intros. rewrite <- (rev_involutive l). apply rev_Exists_list; assumption.\nQed.\n\nLemma take_Forall_list :\n  forall P n l, Forall_list P l -> Forall_list P (take n l).\nProof.\n  intros; generalize dependent n; induction l; intros;\n    inversion_clear H; destruct n; simpl; auto.\nQed.\nLemma drop_Forall_list :\n  forall P n l, Forall_list P l -> Forall_list P (drop n l).\nProof.\n  intros; generalize dependent n; induction l; intros;\n    inversion_clear H; destruct n; simpl; auto.\nQed.\nLemma Forall_list_take_drop :\n  forall P n l,\n    Forall_list P (take n l) -> Forall_list P (drop n l) -> Forall_list P l.\nProof. intros; rewrite <- (take_app_drop l n); auto. Qed.\n\nLemma take_drop_Exists_list :\n  forall P n l, Exists_list P l ->\n    Exists_list P (take n l) \\/ Exists_list P (drop n l).\nProof. intros; rewrite <- (take_app_drop l n) in H; auto. Qed.\nLemma Exists_list_take :\n  forall P n l, Exists_list P (take n l) -> Exists_list P l.\nProof. intros; rewrite <- (take_app_drop l n); auto. Qed.\nLemma Exists_list_drop :\n  forall P n l, Exists_list P (drop n l) -> Exists_list P l.\nProof. intros; rewrite <- (take_app_drop l n); auto. Qed.\n\nLemma Forall_list_implies :\n  forall (P Q:A->Prop) xs,\n    (forall x, In x xs -> P x -> Q x) ->\n    Forall_list P xs -> Forall_list Q xs.\nProof. induction 2; firstorder. Qed.\nLemma Exists_list_implies :\n  forall (P Q:A->Prop) xs,\n    (forall x, In x xs -> P x -> Q x) ->\n    Exists_list P xs -> Exists_list Q xs.\nProof. induction 2; firstorder. Qed.\n\nEnd List_predicate_inductive.\n\nHint Resolve not_Exists_list_nil : lists.\nHint Resolve In_Forall_list : lists.\nHint Resolve Forall_list_app_left Forall_list_app_right : lists.\nHint Resolve app_Forall_list Exists_list_app_or : lists.\nHint Resolve app_Exists_list_left app_Exists_list_right : lists.\nHint Resolve rev_Forall_list rev_Exists_list : lists.\nHint Resolve Forall_list_rev Exists_list_rev : lists.\nHint Resolve take_Forall_list drop_Forall_list Forall_list_take_drop\n             take_drop_Exists_list Exists_list_take Exists_list_drop\n             : take_drop.\nHint Resolve Forall_list_implies Exists_list_implies : lists.\n\n\n\nSection List_predicate_fold.\n(* Properties of [forall_list] and [exists_list] *)\n\nVariables A : Set.\nImplicit Types x : A.\nImplicit Types xs l : list A.\nImplicit Types p : A -> bool.\nImplicit Types P : A -> Prop.\nSet Implicit Arguments.\n\nLemma forall_list_eq_fold_left_map :\n  forall p l,\n    forall_list p l = fold_left andb (map p l) true.\nProof.\n  unfold forall_list; intros. generalize true.\n  induction l; intros; simpl in * . reflexivity.\n  rewrite IHl. reflexivity.\nQed.\nLemma forall_list_eq_fold_right_map :\n  forall p l,\n    forall_list p l = fold_right andb true (map p l).\nProof.\n  intros. rewrite forall_list_eq_fold_left_map.\n  apply fold_symmetric; auto with bool.\nQed.\nLemma forall_list_eq_fold_left :\n  forall p l,\n    forall_list p l = fold_left (fun b z => b && p z) l true.\nProof. auto. Qed.\nLemma forall_list_eq_fold_right :\n  forall p l,\n    forall_list p l = fold_right (fun z b => b && p z) true l.\nProof.\n  intros; rewrite forall_list_eq_fold_right_map.\n  induction l; simpl. reflexivity. rewrite IHl. auto with bool.\nQed.\n\nLemma exists_list_eq_fold_left_map :\n  forall p l,\n    exists_list p l = fold_left orb (map p l) false.\nProof.\n  unfold exists_list; intros. generalize false.\n  induction l; intros; simpl in * . reflexivity.\n  rewrite IHl. reflexivity.\nQed.\nLemma exists_list_eq_fold_right_map :\n  forall p l,\n    exists_list p l = fold_right orb false (map p l).\nProof.\n  intros. rewrite exists_list_eq_fold_left_map.\n  apply fold_symmetric; auto with bool.\nQed.\nLemma exists_list_eq_fold_left :\n  forall p l,\n    exists_list p l = fold_left (fun b z => b || p z) l false.\nProof. auto. Qed.\nLemma exists_list_eq_fold_right :\n  forall p l,\n    exists_list p l = fold_right (fun z b => b || p z) false l.\nProof.\n  intros; rewrite exists_list_eq_fold_right_map.\n  induction l; simpl. reflexivity. rewrite IHl. auto with bool.\nQed.\n\nLemma forall_list_extensionality :\n  forall p p' l, (forall x, p x = p' x) -> forall_list p l = forall_list p' l.\nProof.\n  intros; repeat rewrite forall_list_eq_fold_right.\n  induction l; simpl. reflexivity. rewrite IHl; rewrite H. reflexivity.\nQed.\n\nLemma exists_list_extensionality :\n  forall p p' l, (forall x, p x = p' x) -> exists_list p l = exists_list p' l.\nProof.\n  intros; repeat rewrite exists_list_eq_fold_right.\n  induction l; simpl. reflexivity. rewrite IHl; rewrite H. reflexivity.\nQed.\n\nEnd List_predicate_fold.\n\n\n\nSection List_predicate_relationship.\n\nVariables A : Set.\nImplicit Types x : A.\nImplicit Types xs l : list A.\nImplicit Types p : A -> bool.\nImplicit Types P : A -> Prop.\nSet Implicit Arguments.\n\n(* TODO: lemmas relating Forall_list and forall_list, Exists_list\n   and exists_list, forall_list and exists_list. *)\n\nLemma Forall_if_implies_if_forall :\n  forall P p l,\n    Forall_list (fun z => if p z then P z else ~P z) l ->\n    if forall_list p l then Forall_list P l else ~Forall_list P l.\nProof.\n  intros; rewrite forall_list_eq_fold_right.\n  induction H; simpl in * . apply Forall_nil.\n  destruct (fold_right (fun (z : A) (b : bool) => b && p z) true l).\n  destruct (p x); simpl. apply Forall_cons; assumption.\n  intro No; inversion No; tauto.\n  simpl; intro No; inversion No; tauto.\nQed.\n\nEnd List_predicate_relationship.\n\n\n\n(*** More about maps ***)\n\nSection List_predicate_map.\n\nVariables A B C : Set.\nImplicit Types x : A.\nImplicit Types y : B.\nImplicit Types z : C.\nImplicit Types xs l : list A.\nImplicit Types ys : list B.\nImplicit Types zs : list C.\nImplicit Types f : A -> B.\nImplicit Types g : B -> C.\nImplicit Types P : A -> Prop.\nImplicit Types Q : B -> Prop.\nImplicit Types R : C -> Prop.\nImplicit Types m n : nat.\nSet Implicit Arguments.\n\nLemma map_take :\n  forall f l n, map f (take n l) = take n (map f l).\nProof.\n  intros. generalize dependent n; induction l; intros.\n  destruct n; reflexivity.\n  destruct n. reflexivity. simpl; rewrite IHl; reflexivity.\nQed.\n\nLemma map_drop :\n  forall f l n, map f (drop n l) = drop n (map f l).\nProof.\n  intros. generalize dependent n; induction l; intros.\n  destruct n; reflexivity.\n  destruct n. reflexivity. simpl; rewrite IHl; reflexivity.\nQed.\n\nLemma Forall_list_implies_map :\n  forall P Q f l,\n    (forall x, P x -> Q (f x)) ->\n    Forall_list P l -> Forall_list Q (map f l).\nProof. induction 2; simpl; auto with lists. Qed.\nLemma Exists_list_implies_map :\n  forall P Q f l,\n    (forall x, P x -> Q (f x)) ->\n    Exists_list P l -> Exists_list Q (map f l).\nProof. induction 2; simpl; auto with lists. Qed.\n\nLemma Forall_list_map_implies :\n  forall P Q f l,\n    (forall x, Q (f x) -> P x) ->\n    Forall_list Q (map f l) -> Forall_list P l.\nProof.\n  intros. induction l; simpl in * . apply Forall_nil.\n  inversion_clear H0. auto with lists.\nQed.\nLemma Exists_list_map_implies :\n  forall P Q f l,\n    (forall x, Q (f x) -> P x) ->\n    Exists_list Q (map f l) -> Exists_list P l.\nProof.\n  intros. induction l; simpl in *;\n    inversion_clear H0; auto with lists.\nQed.\n\nLemma Forall_list_map_intro :\n  forall Q f l,\n    Forall_list (fun x => Q (f x)) l -> Forall_list Q (map f l).\nProof. induction 1; simpl; auto with lists. Qed.\nLemma Exists_list_map_intro :\n  forall Q f l,\n    Exists_list (fun x => Q (f x)) l -> Exists_list Q (map f l).\nProof. induction 1; simpl; auto with lists. Qed.\n\nLemma Forall_list_map_elim :\n  forall Q f l,\n    Forall_list Q (map f l) -> Forall_list (fun x => Q (f x)) l.\nProof.\n  intros. induction l; simpl in * . apply Forall_nil.\n  inversion_clear H. auto with lists.\nQed.\nLemma Exists_list_map_elim :\n  forall Q f l,\n    Exists_list Q (map f l) -> Exists_list (fun x => Q (f x)) l.\nProof.\n  intros. induction l; simpl in *;\n    inversion_clear H; auto with lists.\nQed.\n\nEnd List_predicate_map.\n\nHint Rewrite map_take map_drop : take_drop.\nHint Resolve Forall_list_implies_map Exists_list_implies_map : lists.\nHint Resolve Forall_list_map_implies Exists_list_map_implies : lists.\nHint Resolve Forall_list_map_intro Exists_list_map_intro : lists.\nHint Resolve Forall_list_map_elim Exists_list_map_elim : lists.\n\n(* Simplify hypotheses and goals involving [Forall_list]. Simplifications\n   involve rewriting [Forall_list ?P ?l] into equivalent statements\n   where [?l] is simpler. Recognised ``complex'' constructors for [?l]\n   are [nil], [cons], [app], [map], [rev]. In the goal, only\n   simplifications that do not solve or split the goal are considered.\n *)\nLtac simplify_Forall_list :=\n  let tmp := fresh \"tmp\" in (\n    repeat match goal with\n             | H : Forall_list ?P nil |- _ => clear H\n             | H : Forall_list ?P (cons ?a ?l) |- _ =>\n               inversion_clear H;\n               match goal with H':_ |- _ => rename H' into H end\n             | H : Forall_list ?P (app ?l0 ?l1) |- _ =>\n               rename H into tmp;\n               assert (H := Forall_list_app_right l0 l1 tmp);\n               generalize H; clear H;\n               assert (H := Forall_list_app_left l0 l1 tmp);\n               intro; match goal with H':_ |- _ =>\n                        move H' after tmp; simpl in H'\n                      end;\n               move H after tmp; clear tmp; simpl in H\n             | H : Forall_list ?P (map ?f ?l) |- _ =>\n               (*apply Forall_list_map_elim in H*) (*>=V8.1 only*)\n               rename H into tmp;\n               assert (H := Forall_list_map_elim f l tmp);\n               move H after tmp; clear tmp; simpl in H\n             | H : Forall_list ?P (rev ?l) |- _ =>\n               rename H into tmp;\n               assert (tmp := Forall_list_rev l H);\n               move H after tmp; clear tmp; simpl in H\n           end;\n    repeat ((apply Forall_list_map_intro ||\n             apply rev_Forall_list\n            ); simpl)\n  ).\n\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_predicate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189134878876, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.6921399006326168}}
{"text": "Require Export BaseLists Dupfree.\n\nDefinition elAt := nth_error.\nNotation \"A '.[' i  ']'\" := (elAt A i) (no associativity, at level 50).\n\nSection Fix_X.\n\n  Variable X : eqType.\n  \n  Fixpoint pos (s : X) (A : list X) :=\n    match A with\n    | nil => None\n    | a :: A => if Dec (s = a) then Some 0 else match pos s A with None => None | Some n => Some (S n) end\n    end.\n  \n  Lemma el_pos s A : s el A -> exists m, pos s A = Some m.\n  Proof.\n    revert s; induction A; simpl; intros s H.\n    - contradiction.\n    - decide (s = a) as [D | D]; eauto; \n        destruct H; try congruence.\n      destruct (IHA s H) as [n Hn]; eexists; now rewrite Hn.\n  Qed.\n  \n  Lemma pos_elAt s A i : pos s A = Some i -> A .[i] = Some s.\n  Proof.\n    revert i s. induction A; intros i s.\n    - destruct i; inversion 1.\n    - simpl. decide (s = a).\n      + inversion 1; subst; reflexivity.\n      + destruct i; destruct (pos s A) eqn:B; inversion 1; subst; eauto. \n  Qed.\n  \n  Lemma elAt_app (A : list X) i B s : A .[i] = Some s -> (A ++ B).[i] = Some s.\n  Proof.\n    revert s B i. induction A; intros s B i H; destruct i; simpl; intuition; inv H.\n  Qed.\n  \n  Lemma elAt_el  A (s : X) m : A .[ m ] = Some s -> s el A.\n  Proof.\n    revert A. induction m; intros []; inversion 1; eauto.\n  Qed.\n  \n  Lemma el_elAt (s : X) A : s el A -> exists m, A .[ m ] = Some s.\n  Proof.\n    intros H; destruct (el_pos H);  eexists; eauto using pos_elAt.\n  Qed.\n\n  Lemma dupfree_elAt (A : list X) n m s : dupfree A -> A.[n] = Some s -> A.[m] = Some s -> n = m.\n  Proof with try tauto.\n    intros H; revert n m; induction A; simpl; intros n m H1 H2.\n    - destruct n; inv H1.\n    - destruct n, m; inv H...\n      + inv H1. simpl in H2. eapply elAt_el in H2...\n      + inv H2. simpl in H1. eapply elAt_el in H1... \n      + inv H1. inv H2. rewrite IHA with n m... \n  Qed.\n\n  Lemma nth_error_none A n l : nth_error l n = @None A -> length l <= n.\n  Proof. revert n;\n           induction l; intros n.\n         - simpl; omega.\n         - simpl. intros. destruct n. inv H. inv H. assert (| l | <= n). eauto. omega.\n  Qed.\n\n  Lemma pos_None (x : X) l l' : pos x l = None-> pos x l' = None -> pos x (l ++ l') = None.\n  Proof.\n    revert x l'; induction l; simpl; intros; eauto.\n    have (x = a).\n    destruct (pos x l) eqn:E; try congruence.\n    rewrite IHl; eauto.\n  Qed.\n\n  Lemma pos_first_S (x : X)  l l' i  : pos x l = Some i -> pos x (l ++ l') = Some i.\n  Proof.\n    revert x i; induction l; intros; simpl in *.\n    - inv H.\n    - decide (x = a); eauto.\n      destruct (pos x l) eqn:E.\n      + eapply IHl in E. now rewrite E.\n      + inv H.\n  Qed.\n\n  Lemma pos_second_S x l l' i : pos x l = None ->\n                                pos x l' = Some i ->\n                                pos x (l ++ l') = Some ( i + |l| ).\n  Proof.\n    revert i l'; induction l; simpl; intros.\n    - rewrite plus_comm. eauto.\n    - destruct _; subst; try congruence.\n      destruct (pos x l) eqn:EE. congruence.\n      erewrite IHl; eauto.\n  Qed.\n\n  Lemma pos_length (e : X) n E : pos e E = Some n -> n < |E|.\n  Proof.\n    revert e n; induction E; simpl; intros.\n    - inv H.\n    - decide (e = a).\n      + inv H. simpl. omega.\n      + destruct (pos e E) eqn:EE.\n        * inv H. assert (n1 < |E|) by eauto.  omega.\n        * inv H.\n  Qed.\n\n  Fixpoint replace (xs : list X) (y y' : X) :=\n    match xs with\n    | nil => nil\n    | x :: xs' => (if Dec (x = y) then y' else x) :: replace xs' y y'\n    end.\n\n  Lemma replace_same xs x : replace xs x x = xs.\n  Proof.\n    revert x; induction xs; intros; simpl; [ | destruct _; subst ]; congruence.\n  Qed.\n\n  Lemma replace_diff xs x y : x <> y -> ~ x el replace xs x y.\n  Proof.\n    revert x y; induction xs; intros; simpl; try destruct _; firstorder. \n  Qed.\n\n  Lemma replace_pos xs x y y' : x <> y -> x <> y' -> pos x xs = pos x (replace xs y y').\n  Proof.\n    induction xs; intros; simpl.\n    - reflexivity.\n    - repeat destruct Dec; try congruence; try omega; subst. \n      + rewrite IHxs; eauto. + rewrite IHxs; eauto.\n  Qed.\n\nEnd Fix_X.\n\nArguments replace {_} _ _ _.\n\n\n\n(* Fixpoint  getPosition {E: eqType} (A: list E) x := match A with *)\n(*                                                    | nil => 0 *)\n(*                                                    | cons x' A' => if Dec (x=x') then 0 else 1 + getPosition A' x end. *)\n\n(* Lemma getPosition_correct {E: eqType} (x:E) A: if Dec (x el A) then forall z, (nth (getPosition A x) A z) = x else getPosition A x = |A |. *)\n(* Proof. *)\n(*   induction A;cbn. *)\n(*   -dec;tauto. *)\n(*   -dec;intuition; congruence. *)\n(* Qed. *)\n", "meta": {"author": "uds-psl", "repo": "base-library", "sha": "d9f3b8abf379d4c12049dd25c8d1fdf1973dab48", "save_path": "github-repos/coq/uds-psl-base-library", "path": "github-repos/coq/uds-psl-base-library/base-library-d9f3b8abf379d4c12049dd25c8d1fdf1973dab48/Lists/Position.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.6921398932970734}}
{"text": "(** * FlipG : Hofstadter's flipped G tree *)\n\nRequire Import Arith Omega Wf_nat List Program Program.Wf NPeano.\nRequire Import DeltaList Fib FunG.\nSet Implicit Arguments.\n\n(** See first the file [FunG] for the study of:\n\n     - [G (S n) + G (G n) = S n]\n     - [G 0 = 0]\n\n   and the associated tree where nodes are labeled breadth-first\n   from left to right.\n\n   Now, question by Hofstadter: what if we still label the nodes\n   from right to left, but for the mirror tree ?\n   What is the algebraic definition of the \"parent\" function\n   for this flipped tree ?\n\n<<\n9 10 11 12  13\n \\/   |  \\ /\n  6   7   8\n   \\   \\ /\n    4   5\n     \\ /\n      3\n      |\n      2\n      |\n      1\n>>\n\n   References:\n    - Hofstadter's book: Goedel, Escher, Bach, page 137.\n    - Sequence A123070 on the Online Encyclopedia of Integer Sequences\n      #<a href=\"http://oeis.org/A123070\">#http://oeis.org/A123070#</a>#\n*)\n\n(*=============================================================*)\n\n(** * The [flip] function *)\n\n(** If we label the node from right to left, the effect\n   on node numbers is the [flip] function below.\n   The idea is to map a row [ [1+fib (k+1);...;fib (k+2)] ]\n   to the flipped row [ [fib (k+2);...;1+fib (k+1)] ].\n*)\n\nDefinition flip n :=\n  if n <=? 1 then n else S (fib (S (S (S (depth n))))) - n.\n\nLtac tac_leb := rewrite <- ?Bool.not_true_iff_false, leb_le.\n\nLemma flip_depth n : depth (flip n) = depth n.\nProof.\n unfold flip.\n case_eq (n <=? 1); tac_leb; trivial.\n intros.\n assert (depth n <> 0) by (rewrite depth_0; omega).\n apply depth_carac; trivial.\n set (k := depth n) in *.\n assert (S (fib (S k)) <= n <= fib (S (S k)))\n  by now apply depth_carac.\n rewrite fib_eqn.\n omega.\nQed.\n\nLemma flip_eqn0 n : depth n <> 0 ->\n flip n = S (fib (S (S (S (depth n))))) - n.\nProof.\n intros.\n rewrite depth_0 in *.\n unfold flip.\n case_eq (n <=? 1); tac_leb; omega.\nQed.\n\nLemma flip_eqn k n : 1 <= n <= fib k ->\n flip (fib (S k) + n) = S (fib (S (S k))) - n.\nProof.\n intros Hn.\n unfold flip.\n case_eq (fib (S k) + n <=? 1); tac_leb.\n - generalize (@fib_nz (S k)); omega.\n - intros H.\n   replace (depth (fib (S k) + n)) with k.\n   + rewrite fib_eqn. omega.\n   + assert (k<>0).\n     { intros ->. simpl in Hn; omega. }\n     symmetry. apply depth_carac; auto.\n     rewrite fib_eqn; omega.\nQed.\n\n(** Two special cases : leftmost and rightmost node at a given depth *)\n\nLemma flip_Sfib k : 1<k -> flip (S (fib k)) = fib (S k).\nProof.\n intros H.\n destruct k.\n - omega.\n - rewrite <- Nat.add_1_r.\n   rewrite flip_eqn.\n   omega.\n   split; trivial. apply fib_nz. omega.\nQed.\n\nLemma flip_fib k : 1<k -> flip (fib (S k)) = S (fib k).\nProof.\n intros H.\n destruct k.\n - omega.\n - rewrite fib_eqn' by omega.\n   rewrite flip_eqn; auto.\n   rewrite fib_eqn'; auto. omega.\n   replace (S k - 1) with k by omega.\n   split; auto. apply fib_nz. omega.\nQed.\n\n(** flip is involutive (and hence a bijection) *)\n\nLemma flip_flip n : flip (flip n) = n.\nProof.\n unfold flip at 2.\n case_eq (n <=? 1).\n - unfold flip. now intros ->.\n - tac_leb.\n   intros Hn.\n   set (k := depth n).\n   assert (k<>0).\n   { contradict Hn. unfold k in *. rewrite depth_0 in Hn. omega. }\n   assert (Hn' : S (fib (S k)) <= n <= fib (S (S k))).\n   { apply depth_carac; auto. }\n   rewrite fib_eqn.\n   replace (S (fib (S (S k)) + fib (S k)) - n) with\n    (fib (S k) + (S (fib (S (S k))) - n)) by omega.\n   rewrite flip_eqn; auto. omega.\n   split. omega. rewrite fib_eqn'; auto.\n   replace (S k - 1) with k by omega.\n   omega.\nQed.\n\nLemma flip_eq n m : flip n = flip m <-> n = m.\nProof.\n split; intros H.\n - rewrite <- (flip_flip n), <- (flip_flip m). now f_equal.\n - now subst.\nQed.\n\nLemma flip_swap n m : flip n = m <-> n = flip m.\nProof.\n rewrite <- (flip_flip m) at 1. apply flip_eq.\nQed.\n\nLemma flip_low n : n <= 1 <-> flip n <= 1.\nProof.\n split; intros.\n - assert (EQ : n = 0 \\/ n = 1) by omega.\n   destruct EQ as [-> | ->]; compute; auto.\n - assert (EQ : flip n = 0 \\/ flip n = 1) by omega.\n   rewrite !flip_swap in EQ. compute in EQ. omega.\nQed.\n\nLemma flip_high n : 1 < n <-> 1 < flip n.\nProof.\n generalize (flip_low n). omega.\nQed.\n\n(** flip and neighbors *)\n\nLemma flip_S n : 1<n -> depth (S n) = depth n ->\n  flip (S n) = flip n - 1.\nProof.\n intros Hn EQ.\n assert (depth n <> 0) by (rewrite depth_0; omega).\n rewrite !flip_eqn0, EQ; omega.\nQed.\n\nLemma flip_pred n : 1<n -> depth (n-1) = depth n ->\n  flip (n-1) = S (flip n).\nProof.\n intros Hn EQ.\n assert (depth n <> 0) by (rewrite depth_0; omega).\n rewrite !flip_eqn0, EQ; try omega.\n assert (n <= fib (S (S (depth n)))) by (apply depth_carac; auto).\n rewrite fib_eqn; omega.\nQed.\n\n\n(*=============================================================*)\n\n(** * The [fg] function corresponding to the flipped [G] tree *)\n\nDefinition fg n := flip (g (flip n)).\n\n(* Compute map fg (seq 0 10). *)\n\nLemma fg_depth n : depth (fg n) = depth n - 1.\nProof.\n unfold fg. now rewrite flip_depth, g_depth, flip_depth.\nQed.\n\nLemma fg_fib k : k<>0 -> fg (fib (S k)) = fib k.\nProof.\n destruct k as [|[|[|k]]].\n - omega.\n - reflexivity.\n - reflexivity.\n - intros _.\n   unfold fg.\n   now rewrite flip_fib, g_Sfib, flip_Sfib by omega.\nQed.\n\nLemma fg_Sfib k : 1<k -> fg (S (fib (S k))) = S (fib k).\nProof.\n intros Hk.\n unfold fg.\n rewrite flip_Sfib by omega.\n rewrite g_fib by omega.\n rewrite flip_fib; auto.\nQed.\n\nLemma fg_fib' k : 1<k -> fg (fib k) = fib (k-1).\nProof.\n destruct k.\n - omega.\n - intros. rewrite fg_fib; f_equal; omega.\nQed.\n\nLemma fg_Sfib' k : 2<k -> fg (S (fib k)) = S (fib (k-1)).\nProof.\n destruct k.\n - inversion 1.\n - intros. rewrite Nat.sub_1_r. apply fg_Sfib. simpl. omega.\nQed.\n\nLemma fg_step n : fg (S n) = fg n \\/ fg (S n) = S (fg n).\nProof.\n destruct (le_lt_dec n 1) as [LE|LT].\n - assert (EQ : n = 0 \\/ n = 1) by omega.\n   destruct EQ as [-> | ->]; compute; auto.\n - set (k := depth n).\n   assert (k<>0) by (unfold k; rewrite depth_0; omega).\n   assert (S (fib (S k)) <= n <= fib (S (S k))).\n   { apply depth_carac; auto. }\n   destruct (eq_nat_dec n (fib (S (S k)))) as [EQ|NE].\n   + rewrite EQ. rewrite fg_Sfib, fg_fib; auto. omega.\n   + assert (depth (S n) = k). { apply depth_carac; omega. }\n     assert (depth (flip (S n)) = k). { rewrite flip_depth; auto. }\n     assert (1 < flip n). { now apply (flip_high n). }\n     unfold fg.\n     rewrite flip_S in *; auto.\n     destruct (eq_nat_dec (g (flip n - 1)) (g (flip n))) as [EQ|NE'].\n     * left; f_equal; trivial.\n     * right.\n       rewrite g_prev in NE' by omega.\n       rewrite NE'.\n       apply flip_pred.\n       { unfold lt. change 2 with (g 3). apply g_mono.\n         assert (flip n <> 2).\n         { intros EQ. rewrite EQ in *. now compute in NE'. }\n         omega. }\n       { rewrite <- NE'. rewrite !g_depth. rewrite flip_depth.\n         unfold k in *; omega. }\nQed.\n\nLemma fg_mono_S n : fg n <= fg (S n).\nProof.\n generalize (fg_step n). omega.\nQed.\n\nLemma fg_mono n m : n<=m -> fg n <= fg m.\nProof.\ninduction 1.\n- trivial.\n- transitivity (fg m); auto using fg_mono_S.\nQed.\n\nLemma fg_lipschitz n m : fg m - fg n <= m - n.\nProof.\ndestruct (le_ge_dec n m) as [H|H].\n- induction H; try generalize (fg_step m); omega.\n- generalize (fg_mono H). omega.\nQed.\n\nLemma fg_nonzero n : 0 < n -> 0 < fg n.\nProof.\n unfold lt. intros. change 1 with (fg 1). now apply fg_mono.\nQed.\n\nLemma fg_0_inv n : fg n = 0 -> n = 0.\nProof.\ndestruct n; trivial.\nassert (0 < fg (S n)) by (apply fg_nonzero; auto with arith).\nomega.\nQed.\n\nLemma fg_nz n : n <> 0 -> fg n <> 0.\nProof.\nintros H. contradict H. now apply fg_0_inv.\nQed.\n\nLemma fg_fix n : fg n = n <-> n <= 1.\nProof.\n unfold fg.\n now rewrite flip_low, <- g_fix, flip_swap.\nQed.\n\nLemma fg_le n : fg n <= n.\nProof.\n generalize (fg_lipschitz 0 n). change (fg 0) with 0. omega.\nQed.\n\nLemma fg_lt n : 1<n -> fg n < n.\nProof.\nintros H.\ndestruct (le_lt_or_eq _ _ (fg_le n)); trivial.\nrewrite fg_fix in *. omega.\nQed.\n\nLemma fg_onto a : exists n, fg n = a.\nProof.\n unfold fg. destruct (g_onto (flip a)) as (x,H).\n exists (flip x). now rewrite flip_swap, flip_flip.\nQed.\n\nLemma fg_nonflat n : fg (S n) = fg n -> fg (S (S n)) = S (fg n).\nProof.\n intros H.\n destruct (le_lt_dec n 1) as [Hn|Hn].\n - assert (EQ : n = 0 \\/ n = 1) by omega.\n   destruct EQ as [-> | ->]; reflexivity.\n - destruct (fg_step (S n)) as [H'|H']; [|omega].\n   exfalso.\n   set (k := depth n).\n   assert (Hk : k<>0) by (unfold k; rewrite depth_0; omega).\n   assert (Hnk : S (fib (S k)) <= n <= fib (S (S k))).\n   { apply depth_carac; auto. }\n   destruct (eq_nat_dec n (fib (S (S k)))) as [EQ|NE].\n   + rewrite EQ in H. rewrite fg_fib, fg_Sfib in H; omega.\n   + destruct (eq_nat_dec (S n) (fib (S (S k)))) as [EQ|NE'].\n     * rewrite EQ in H'. rewrite fg_fib, fg_Sfib in H'; omega.\n     * revert H'. rewrite H; clear H. unfold fg. rewrite flip_eq.\n       assert (depth (S n) = k). { apply depth_carac; omega. }\n       assert (depth (flip (S n)) = k). { rewrite flip_depth; auto. }\n       assert (depth (S (S n)) = k). { apply depth_carac; omega. }\n       assert (depth (flip (S (S n))) = k). { rewrite flip_depth; auto. }\n       rewrite flip_S by omega.\n       rewrite flip_S by (unfold k in H; omega).\n       assert (HH : forall m, 1<m -> g (m-1-1) <> g m).\n       { intros.\n         generalize (@g_max_two_antecedents (g m) (m-1-1) m).\n         omega. }\n       apply HH. apply flip_high in Hn. auto.\nQed.\n\nLemma fg_max_two_antecedents n m :\n fg n = fg m -> n < m -> m = S n.\nProof.\n intros H LT.\n unfold lt in LT.\n assert (LE := fg_mono LT).\n rewrite <- H in LE.\n destruct (fg_step n) as [EQ|EQ]; [|omega].\n apply fg_nonflat in EQ.\n destruct (le_lt_dec m (S n)) as [LE'|LT']; [omega|].\n unfold lt in LT'. apply fg_mono in LT'. omega.\nQed.\n\nLemma fg_inv n m : fg n = fg m -> n = m \\/ n = S m \\/ m = S n.\nProof.\n intros H.\n destruct (lt_eq_lt_dec n m) as [[LT|EQ]|LT]; auto.\n - apply fg_max_two_antecedents in LT; auto.\n - apply fg_max_two_antecedents in LT; auto.\nQed.\n\nLemma fg_eqn n : 3 < n -> fg n + fg (S (fg (n-1))) = S n.\nProof.\n intros Hn.\n set (k := depth n).\n assert (3<=k).\n { unfold k. change 3 with (depth 4).\n   apply depth_mono; auto. }\n assert (LE : S (fib (S k)) <= n <= fib (S (S k))).\n { apply depth_carac. omega. auto. }\n destruct (eq_nat_dec (S (fib (S k))) n) as [EQ|NE].\n - (* n = S (fib (S k)) *)\n   replace (n-1) with (fib (S k)) by omega.\n   rewrite <- EQ.\n   rewrite fg_fib, !fg_Sfib' by omega.\n   replace (S k - 1) with k by omega.\n   rewrite fib_eqn'; omega.\n - (* n > S (fib (S k)) *)\n   assert (Hk : depth (n-1) = k).\n   { apply depth_carac; omega. }\n   assert (Hk' : depth (fg (n-1)) = k-1).\n   { now rewrite fg_depth, Hk. }\n   assert (LE' : S (fib k) <= fg (n-1) <= fib (S k)).\n   { replace k with (S (k-1)) by omega.\n     apply depth_carac; auto. omega. }\n   destruct (eq_nat_dec (fg (n-1)) (fib (S k))) as [EQ|NE'].\n   + (* fg(n-1) = fib (S k) *)\n     rewrite EQ.\n     rewrite fg_Sfib' by omega.\n     assert (EQ' : fg n = fib (S k)).\n     { destruct (fg_step (n-1)) as [EQ'|EQ'];\n       replace (S (n-1)) with n in EQ'; try omega.\n       rewrite EQ in EQ'.\n       assert (H' : depth (fg n) = k) by (apply depth_carac; omega).\n       rewrite fg_depth in H'. unfold k in *. omega. }\n     rewrite EQ'.\n     rewrite Nat.add_succ_r. rewrite <- fib_eqn' by omega.\n     f_equal.\n     assert (EQ'' : fg (n-1) = fg (fib (S (S k)))) by now rewrite EQ, fg_fib.\n     apply fg_max_two_antecedents in EQ''; omega.\n   + (* fg(n-1) <> fib (S k) *)\n     assert (Hk'' : depth (S (fg (n-1))) = k-1).\n     { apply depth_carac. omega.\n       replace (S (k-1)) with k by omega.\n       omega. }\n     unfold fg at 2.\n     rewrite flip_eqn0;\n     rewrite g_depth, flip_depth, Hk''; [|omega].\n     replace (S (S (k-1-1))) with k by omega.\n     assert (LT : 1 < fg (n-1)).\n     { unfold lt. change 2 with (fg 3). apply fg_mono. omega. }\n     rewrite flip_S by omega.\n     unfold fg at 2. rewrite flip_flip.\n     rewrite flip_pred; try (unfold k in Hk; omega).\n     clear LT Hk'' NE' LE' Hk Hk'.\n     replace (g (g (S (flip n)) - 1)) with (flip n - g (flip n))\n     by (generalize (g_alt_eqn (flip n)); omega).\n     rewrite <- (flip_flip (g (flip n))).\n     fold (fg n).\n     rewrite !flip_eqn0 by (rewrite ?fg_depth; unfold k in H; omega).\n     rewrite fg_depth.\n     change (depth n) with k.\n     replace (S (k-1)) with k by omega.\n     rewrite fib_eqn.\n     assert (Hnk : depth (fg n) = k-1).\n     { rewrite fg_depth. unfold k. omega. }\n     apply depth_carac in Hnk; [|omega].\n     replace (S (k-1)) with k in Hnk by omega.\n     replace (fib k) with (fib (S (S k)) - fib (S k)) in Hnk;\n      [|rewrite fib_eqn; omega].\n     set (FSSK := fib (S (S k))) in *.\n     set (FSK := fib (S k)) in *.\n     replace (S (FSSK+FSK) -n - (S FSSK - fg n))\n      with (FSK + fg n - n) by omega.\n     omega.\nQed.\n\n(** This equation, along with initial values up to [n=3],\n    characterizes [fg] entirely. It can hence be used to\n    give an algebraic recursive definition to [fg], answering\n    the Hofstader's question. *)\n\nLemma fg_eqn_unique f :\n  f 0 = 0 ->\n  f 1 = 1 ->\n  f 2 = 1 ->\n  f 3 = 2 ->\n  (forall n, 3<n -> f n + f (S (f (n-1))) = S n) ->\n  forall n, f n = fg n.\nProof.\n intros F0 F1 F2 F3 Fn.\n induction n as [n IH] using lt_wf_rec.\n destruct (le_lt_dec n 3) as [Hn|Hn].\n - destruct n as [|[|[|n]]]; try assumption.\n   replace n with 0 by omega. assumption.\n - assert (E := fg_eqn Hn).\n   specialize (Fn n Hn).\n   rewrite (IH (n-1)) in Fn by omega.\n   rewrite (IH (S (fg (n-1)))) in Fn.\n   + generalize (@fg_lt n). omega.\n   + generalize (@fg_lt (n-1)). omega.\nQed.\n\n(*=============================================================*)\n\n(** * [fg] and the shape of its tree\n\n    We already know that [fg] is onto, hence each node has\n    at least a child. Moreover, [fg_max_two_antecedents] says\n    that we have at most two children per node.\n*)\n\nLemma unary_flip a : Unary fg a <-> Unary g (flip a).\nProof.\n split; intros U n m Hn Hm; apply flip_eq; apply U;\n unfold fg in *; rewrite ?flip_flip; now apply flip_swap.\nQed.\n\nLemma multary_flip a : Multary fg a <-> Multary g (flip a).\nProof.\n unfold Multary.\n now rewrite unary_flip.\nQed.\n\nLemma fg_multary_binary a : Multary fg a <-> Binary fg a.\nProof.\n unfold Multary.\n split.\n - intros U.\n   assert (Ha : a<>0).\n   { contradict U.\n     subst.\n     intros u v Hu Hv. apply fg_0_inv in Hu. apply fg_0_inv in Hv.\n     now subst. }\n   destruct (fg_onto a) as (n,Hn).\n   assert (Hn' : n<>0).\n   { contradict Ha. now subst. }\n   destruct (eq_nat_dec (fg (S n)) a);\n   destruct (eq_nat_dec (fg (n-1)) a).\n   + exfalso.\n     generalize (@fg_max_two_antecedents (n-1) (S n)). omega.\n   + exists n; exists (S n); repeat split; auto.\n     intros k Hk.\n     destruct (fg_inv n k) as [H|[H|H]]; try omega.\n     subst n. simpl in *. rewrite Nat.sub_0_r in *. omega.\n   + exists n; exists (n-1); repeat split; auto; try omega.\n     intros k Hk.\n     destruct (fg_inv n k) as [H|[H|H]]; try omega.\n     subst k. omega.\n   + elim U.\n     intros u v Hu Hv.\n     assert (u = n).\n     { destruct (fg_inv n u) as [H|[H|H]]; subst;\n       simpl in *; rewrite ?Nat.sub_0_r in *; omega. }\n     assert (v = n).\n     { destruct (fg_inv n v) as [H'|[H'|H']]; subst;\n       simpl in *; rewrite ?Nat.sub_0_r in *; omega. }\n     omega.\n - intros (n & m & Hn & Hm & Hnm & H) U.\n   apply Hnm. now apply (U n m).\nQed.\n\nLemma unary_or_multary n : Unary fg n \\/ Multary fg n.\nProof.\n rewrite unary_flip, multary_flip.\n apply unary_or_multary.\nQed.\n\nLemma unary_xor_multary n : Unary fg n -> Multary fg n -> False.\nProof.\n unfold Multary. intuition.\nQed.\n\n(** We could even exhibit at least one child for each node *)\n\nDefinition rchild n :=\n if eq_nat_dec n 1 then 2 else n + fg (S n) - 1.\n (** rightmost son, always there *)\n\nLemma rightmost_child_carac a n : fg n = a ->\n (fg (S n) = S a <-> n = rchild a).\nProof.\n intros Hn.\n destruct (le_lt_dec n 2).\n - rewrite <- Hn.\n   destruct n as [|[|n]].\n   + compute. auto.\n   + compute. auto.\n   + replace n with 0 by omega. compute. auto.\n - assert (2 <= a).\n   { change 2 with (fg 3). rewrite <- Hn. apply fg_mono. assumption. }\n   unfold rchild.\n   destruct eq_nat_dec.\n   + destruct a as [|[|[|a]]]; trivial; omega.\n   + assert (Hn' : 3 < S n) by omega.\n     assert (H' := fg_eqn Hn').\n     replace (S n - 1) with n in H' by omega.\n     rewrite Hn in H'.\n     omega.\nQed.\n\nLemma fg_onto_eqn a : fg (rchild a) = a.\nProof.\ndestruct (fg_onto a) as (n,Hn).\ndestruct (fg_step n) as [H|H].\n- assert (H' := fg_nonflat _ H).\n  rewrite Hn in *.\n  rewrite rightmost_child_carac in H'; auto.\n  now rewrite <- H'.\n- rewrite Hn in *.\n  rewrite rightmost_child_carac in H; auto.\n  now rewrite <- H.\nQed.\n\nDefinition lchild n :=\n if eq_nat_dec n 1 then 1 else flip (FunG.rchild (flip n)).\n (** leftmost son, always there (but might be equal to\n     the rightmost son for unary nodes) *)\n\nLemma lchild'_alt n : n<>1 -> lchild n = flip (flip n + flip (fg n)).\nProof.\n unfold lchild, FunG.rchild, fg.\n destruct eq_nat_dec; [intros; omega|intros].\n f_equal. f_equal.\n symmetry. apply flip_flip.\nQed.\n\nLemma fg_onto_eqn' n : fg (lchild n) = n.\nProof.\n unfold fg, lchild.\n destruct eq_nat_dec.\n - now subst.\n - rewrite flip_flip, g_onto_eqn.\n   apply flip_flip.\nQed.\n\nLemma lchild_leftmost n : fg (lchild n - 1) = n - 1.\nProof.\n destruct (le_lt_dec n 1).\n - destruct n as [|n].\n   + now compute.\n   + replace n with 0 by omega; now compute.\n - set (k:=depth n).\n   assert (k<>0) by (unfold k; rewrite depth_0; omega).\n   assert (S (fib (S k)) <= n <= fib (S (S k))).\n   { apply depth_carac; auto. }\n   destruct (eq_nat_dec n (S (fib (S k)))) as [E|N].\n   + rewrite E.\n     replace (S (fib (S k)) - 1) with (fib (S k)) by omega.\n     unfold lchild.\n     destruct eq_nat_dec.\n     * generalize (@fib_nz k); intros; omega.\n     * rewrite flip_Sfib by omega.\n       unfold FunG.rchild. rewrite g_fib by omega.\n       rewrite <- fib_eqn.\n       rewrite flip_fib by omega.\n       replace (S (fib (S (S k))) - 1) with (fib (S (S k))) by omega.\n       apply fg_fib; omega.\n   + unfold fg. apply flip_swap.\n     assert (1 < lchild n).\n     { generalize (fg_onto_eqn' n).\n       generalize (@fg_mono (lchild n) 2). change (fg 2) with 1.\n       omega. }\n     rewrite !flip_pred; auto.\n     * unfold lchild.\n       destruct eq_nat_dec; [omega|].\n       rewrite flip_flip.\n       rewrite FunG.rightmost_child_carac; auto.\n       apply g_onto_eqn.\n     * change (depth n) with k; apply depth_carac; omega.\n     * assert (D : depth (lchild n) = S k).\n       { unfold k. rewrite <- (fg_onto_eqn' n) at 2.\n         rewrite fg_depth. generalize (depth_0 (lchild n)).\n         omega. }\n       rewrite D.\n       apply depth_carac in D; auto.\n       assert (lchild n <> S (fib (S (S k)))).\n       { contradict N.\n         rewrite <- (fg_onto_eqn' n), N. rewrite fg_Sfib; omega. }\n       apply depth_carac; auto. omega.\nQed.\n\nLemma lchild_leftmost' n a :\n  fg n = a -> n = lchild a \\/ n = S (lchild a).\nProof.\n intros Hn.\n destruct (fg_inv (lchild a) n) as [H|[H|H]]; try omega.\n - rewrite <- Hn. apply fg_onto_eqn'.\n - exfalso.\n   generalize (lchild_leftmost a).\n   rewrite H. simpl. rewrite Nat.sub_0_r, Hn.\n   intros. replace a with 0 in * by omega.\n   discriminate.\nQed.\n\nLemma rchild_lchild n :\n rchild n = lchild n \\/ rchild n = S (lchild n).\nProof.\n apply lchild_leftmost'. apply fg_onto_eqn.\nQed.\n\nLemma lchild_rchild n : lchild n <= rchild n.\nProof.\n destruct (rchild_lchild n); omega.\nQed.\n\nLemma fg_children a n :\n  fg n = a -> (n = lchild a \\/ n = rchild a).\nProof.\n intros H.\n destruct (lchild_leftmost' _ H) as [Hn|Hn]; auto.\n destruct (rchild_lchild a) as [Ha|Ha]; try omega.\n exfalso.\n symmetry in Ha. apply rightmost_child_carac in Ha.\n rewrite <- Hn in Ha. omega.\n apply fg_onto_eqn'.\nQed.\n\nLemma binary_lchild_is_unary n :\n 1<n -> Multary fg n -> Unary fg (lchild n).\nProof.\n rewrite multary_flip, unary_flip.\n unfold lchild.\n destruct eq_nat_dec; try omega.\n rewrite flip_flip.\n intros. now apply binary_rchild_is_unary.\nQed.\n\nLemma rightmost_son_is_binary n :\n  1<n -> Multary fg (rchild n).\nProof.\n intros.\n rewrite multary_flip.\n apply leftmost_son_is_binary with (flip n).\n - apply flip_swap. apply fg_onto_eqn.\n - rewrite <- flip_swap.\n   set (k:=depth n).\n   assert (k<>0) by (unfold k; rewrite depth_0; omega).\n   assert (S (fib (S k)) <= n <= fib (S (S k))).\n   { apply depth_carac; auto. }\n   destruct (eq_nat_dec n (fib (S (S k)))) as [E|N].\n   + assert (E' : rchild n = fib (S (S (S k)))).\n     { symmetry.\n       apply rightmost_child_carac.\n       - now rewrite fg_fib.\n       - rewrite fg_Sfib; omega. }\n     rewrite E'.\n     rewrite flip_fib by omega.\n     replace (S (fib (S (S k))) - 1) with (fib (S (S k))) by omega.\n     rewrite g_fib by omega.\n     rewrite E, flip_swap, flip_fib; omega.\n   + assert (1 < rchild n).\n     { generalize (fg_onto_eqn n).\n       generalize (@fg_mono (rchild n) 2). change (fg 2) with 1.\n       omega. }\n     rewrite <- flip_S; auto.\n     * change (fg (S (rchild n)) <> n).\n       assert (H' := fg_onto_eqn n).\n       destruct (fg_step (rchild n)); try omega.\n       apply rightmost_child_carac in H'. omega.\n     * assert (D : depth (rchild n) = S k).\n       { unfold k. rewrite <- (fg_onto_eqn n) at 2.\n         rewrite fg_depth. generalize (depth_0 (rchild n)).\n         omega. }\n       rewrite D.\n       apply depth_carac in D; auto.\n       assert (rchild n <> fib (S (S (S k)))).\n       { contradict N.\n         rewrite <- (fg_onto_eqn n), N. now rewrite fg_fib. }\n       apply depth_carac; auto. omega.\nQed.\n\nLemma unary_child_is_binary n :\n n <> 0 -> Unary fg n -> Multary fg (rchild n).\nProof.\n intros Hn H.\n destruct (le_lt_dec n 1).\n - replace n with 1 in * by omega.\n   exfalso.\n   specialize (H 1 2). compute in H. omega.\n - now apply rightmost_son_is_binary.\nQed.\n\nLemma binary_rchild_is_binary n :\n 1<n -> Multary fg n -> Multary fg (rchild n).\nProof.\n intros. now apply rightmost_son_is_binary.\nQed.\n\n(** Hence the shape of the [fg] tree is a repetition of\n    this pattern:\n<<\n    r\n    |\n    p   q\n     \\ /\n      n\n>>\n  where [n] and [q] and [r] are binary nodes and [p] is unary.\n\n  As expected, this is the mirror of the [G] tree.\n  We hence retrieve the fractal aspect of [G], flipped.\n*)\n\n\n(*=============================================================*)\n\n(** * Comparison of [fg] and [g] *)\n\n(** First, a few technical lemmas *)\n\nLemma fg_g_S_inv n : 3<n ->\n fg (S (fg (n-1))) = g (g (n-1)) ->\n fg n = S (g n).\nProof.\n intros Hn H.\n replace (fg n) with (S n - fg (S (fg (n-1))))\n   by (rewrite <- fg_eqn; omega).\n replace n with (S (n-1)) at 3 by omega.\n rewrite g_S.\n replace (S (n-1)) with n by omega.\n rewrite H.\n assert (g (g (n-1)) <= n).\n { transitivity (g (n-1)). apply g_le.\n   generalize (g_le (n-1)); omega. }\n omega.\nQed.\n\nLemma fg_g_eq_inv n : 3<n ->\n fg (S (fg (n-1))) = S (g (g (n-1))) ->\n fg n = g n.\nProof.\n intros Hn H.\n replace (fg n) with (S n - fg (S (fg (n-1))))\n   by (rewrite <- fg_eqn; omega).\n replace n with (S (n-1)) at 3 by omega.\n rewrite g_S.\n replace (S (n-1)) with n by omega.\n rewrite H. omega.\nQed.\n\n(** Now, the proof that [fg(n)] is either [g(n)] or [g(n)+1].\n    This proof is split in many cases according to the shape\n    of the Fibonacci decomposition of [n]. *)\n\nDefinition IHeq n :=\n forall m, m<n -> ~Fib.ThreeOdd 2 m -> fg m = g m.\nDefinition IHsucc n :=\n forall m, m<n -> Fib.ThreeOdd 2 m -> fg m = S (g m).\n\nLemma fg_g_aux0 n : IHeq n -> Fib.ThreeOdd 2 n -> fg n = S (g n).\nProof.\n intros IH TE.\n assert (6 <= n) by now apply ThreeOdd_le.\n apply fg_g_S_inv; try omega.\n rewrite (IH (n-1)), IH; try (generalize (@g_lt (n-1)); omega).\n - rewrite Odd_gP by auto. apply g_Two, Three_g; auto.\n - rewrite Odd_gP by auto.\n   now apply ThreeEven_not_ThreeOdd', ThreeOdd_Sg.\n - apply Two_not_ThreeOdd, Odd_pred_Two; auto.\nQed.\n\nLemma fg_g_aux1 n : IHeq n -> 3<n -> Fib.Two 2 n -> fg n = g n.\nProof.\n intros IH N FO.\n apply fg_g_eq_inv; auto.\n assert (High 2 (n-1)). { apply Two_pred_High; auto; omega. }\n assert (Even 2 (g n)) by now apply Two_g.\n rewrite (IH (n-1)) by (auto;omega).\n rewrite 2 Even_gP; auto using Two_Even.\n assert (g n <> 0) by (apply g_nz; omega).\n assert (g (g n) <> 0) by now apply g_nz.\n replace (S (g n - 1)) with (g n) by omega.\n rewrite IH; auto; try apply g_lt; omega.\nQed.\n\nLemma fg_g_aux2 n :\n IHeq n -> IHsucc n -> 3<n -> Fib.ThreeEven 2 n -> fg n = g n.\nProof.\n intros IH1 IH2 N TO.\n apply fg_g_eq_inv; try omega.\n assert (H' := @g_lt (n-1)).\n rewrite (IH1 (n-1)), IH2; try omega.\n - rewrite Odd_gP by auto.\n   f_equal. apply g_Two. apply Three_g; auto.\n - rewrite Odd_gP by auto. now apply ThreeEven_Sg.\n - apply Two_not_ThreeOdd, Three_pred_Two; auto.\nQed.\n\nLemma fg_g_aux3 n : IHeq n -> IHsucc n -> 3<n ->\n Fib.High 2 n -> fg n = g n.\nProof.\n intros IH1 IH2 Hn (k & K & L).\n apply fg_g_eq_inv; auto.\n destruct (Nat.Even_or_Odd k) as [(p,Hp)|(p,Hp)]; subst k.\n - (* even *)\n   assert (E1 : g (n-1) = g n - 1) by (apply Even_gP; now exists p).\n   assert (S (fg (n-1)) < n) by (generalize (@fg_lt (n-1)); omega).\n   assert (g n <> 0) by (apply g_nz; omega).\n   assert (E2 : S (g n - 1) = g n) by omega.\n   destruct p as [|[|[|p]]].\n   + omega.\n   + omega.\n   + (* four *)\n     simpl in *.\n     assert (T : Three 2 (g n)) by (revert L; apply g_Low; auto).\n     rewrite E1, Odd_gP by auto.\n     destruct L as (l & E & D & _).\n     destruct l as [|k l]; [simpl in E; omega|].\n     destruct (Nat.Even_or_Odd k) as [(p,Hp)|(p,Hp)]; subst k.\n     * (* next term after 3 is even *)\n       assert (ThreeEven 2 (n-1)).\n       { exists p; exists l; auto. subst; split; auto.\n         eapply Delta_low_hd with 4; auto. }\n       rewrite (IH1 (n-1)) in * by (auto; omega).\n       rewrite E1, E2, IH2 in *; auto.\n       replace n with (S (n-1)) by omega.\n       rewrite g_not_Two. now apply ThreeEven_Sg.\n       intro. eapply Two_not_Three; eauto using ThreeEven_Three.\n     * (* next term after 4 is odd *)\n       assert (ThreeOdd 2 (n-1)).\n       { exists p; exists l; auto. subst; split; auto.\n         eapply Delta_low_hd with 4; auto. }\n       rewrite (IH2 (n-1)) in * by (auto; omega).\n       rewrite E1, E2, IH1 in *; auto using Odd_succ_Even.\n       apply g_not_Two.\n       intro. eapply Even_xor_Odd; eauto using Two_Even.\n   + (* high odd *)\n     remember (S (S p)) as k eqn:K'.\n     assert (1<k) by omega. clear K K'.\n     assert (Even 2 n) by now exists (S k).\n     assert (~Two 2 n).\n     { intro O. generalize (Low_unique L O). omega. }\n     assert (~Four 2 n).\n     { intro T. generalize (Low_unique L T). omega. }\n     assert (ThreeOdd 2 (n-1)) by now apply EvenHigh_pred_ThreeOdd.\n     rewrite (IH2 (n-1)) in *; auto; try omega.\n     rewrite E1, E2 in *.\n     assert (Ev : Odd 2 (g n)) by now apply Even_g.\n     rewrite Odd_gP by auto.\n     rewrite IH1; auto using Odd_succ_Even.\n     apply g_not_Two.\n     intro. apply Even_xor_Odd with (g n); eauto using Two_Even.\n - (* odd *)\n   assert (High 2 n) by (exists (2*p+1); auto).\n   assert (Odd 2 n) by now exists p.\n   rewrite (IH1 (n-1));\n     [ | omega | now apply Two_not_ThreeOdd, Odd_pred_Two ].\n   assert (S (g (n-1)) < n) by (generalize (@g_lt (n-1)); omega).\n   rewrite Odd_gP in * by auto.\n   rewrite IH1; try omega.\n   + apply g_not_Two. now apply High_g.\n   + now apply Even_not_ThreeOdd, High_Sg.\nQed.\n\n(** The main result: *)\n\nLemma fg_g n :\n (Fib.ThreeOdd 2 n -> fg n = S (g n)) /\\\n (~Fib.ThreeOdd 2 n -> fg n = g n).\nProof.\n induction n  as [n IH] using lt_wf_rec.\n assert (IH1 := fun m (H:m<n) => proj1 (IH m H)).\n assert (IH2 := fun m (H:m<n) => proj2 (IH m H)).\n clear IH.\n split.\n - now apply fg_g_aux0.\n - intros.\n   destruct (le_lt_dec n 3) as [LE|LT].\n   + destruct n as [|[|[|n]]]; try reflexivity.\n     replace n with 0 by omega. reflexivity.\n   + assert (LT' : 2 < n) by omega.\n     destruct (decomp_complete' LT') as [X|[X|[X|X]]].\n     * now apply fg_g_aux1.\n     * now apply fg_g_aux2.\n     * intuition.\n     * now apply fg_g_aux3.\nQed.\n\n(** Note: the positions where [fg] and [g] differ start at 7\n    and then are separated by 5 or 8 (see [Fib.ThreeOdd_next]\n    and related lemmas). Moreover these positions are always\n    unary nodes in [G] (see [FunG.decomp_unary]).\n\n    In fact, the [g] tree can be turned into the [fg] tree\n    by repeating the following transformation whenever [s] below\n    is ThreeOdd:\n<<\n  r   s t             r s   t\n   \\ /  |             |  \\ /\n    p   q   becomes   p   q\n     \\ /               \\ /\n      n                 n\n>>\n\n    In the left pattern above, [s] is ThreeOdd, hence [r] and\n    [p] and [n] are Two, [q] is ThreeEven and [t] is High.\n*)\n\n(** Some immediate consequences: *)\n\nLemma fg_g_step n : fg n = g n \\/ fg n = S (g n).\nProof.\n destruct (le_lt_dec n 3) as [LE|LT].\n - left.\n   destruct n as [|[|[|n]]]; try reflexivity.\n   replace n with 0 by omega. reflexivity.\n - assert (LT' : 2 < n) by omega.\n   destruct (decomp_complete' LT') as [X|[X|[X|X]]].\n   * left. apply fg_g. now apply Two_not_ThreeOdd.\n   * left. apply fg_g. now apply ThreeEven_not_ThreeOdd.\n   * right. now apply fg_g.\n   * left. apply fg_g. now apply High_not_ThreeOdd.\nQed.\n\nLemma g_le_fg n : g n <= fg n.\nProof.\n destruct (fg_g_step n); omega.\nQed.\n\n\n(*=============================================================*)\n\n(** * [fg] and \"delta\" equations *)\n\n(** We can characterize [fg] via its \"delta\" (a.k.a increments).\n   Let [d(n) = fg(n+1)-fg(n)].  For [n>3] :\n\n    - a) if [d(n-1) = 0] then [d(n) = 1]\n    - b) if [d(n-1) <> 0] and [d(fg(n)) = 0] then [d(n) = 1]\n    - c) if [d(n-1) <> 0] and [d(fg(n)) <> 0] then [d(n) = 0]\n\n   In fact these deltas are always 0 or 1.\n*)\n\n(** [FD] is a relational presentation of these \"delta\" equations. *)\n\nInductive FD : nat -> nat -> Prop :=\n | FD_0 : FD 0 0\n | FD_1 : FD 1 1\n | FD_2 : FD 2 1\n | FD_3 : FD 3 2\n | FD_4 : FD 4 3\n | FD_a n x : 4<n -> FD (n-2) x -> FD (n-1) x -> FD n (S x)\n | FD_b n x y z : 4<n -> FD (n-2) x -> FD (n-1) y -> x<>y ->\n                   FD y z -> FD (S y) z -> FD n (S y)\n | FD_c n x y z t : 4<n -> FD (n-2) x -> FD (n-1) y -> x<>y ->\n                     FD y z -> FD (S y) t -> z <> t -> FD n y.\nHint Constructors FD.\n\nLemma FD_le n k : FD n k -> k <= n.\nProof.\ninduction 1; auto with arith; omega.\nQed.\n\nLemma FD_nz n k : FD n k -> 0<n -> 0<k.\nProof.\ninduction 1; auto with arith; omega.\nQed.\n\nLemma FD_lt n k : FD n k -> 1<n -> 0<k<n.\nProof.\ninduction 1; auto with arith; omega.\nQed.\n\n(* begin hide *)\nLtac uniq :=\nmatch goal with\n| U:forall k, FD ?x k -> _, V:FD ?x ?y |- _ =>\n   apply U in V; try subst y; uniq\n| U:?x<>?x |- _ => now elim U\nend.\n(* end hide *)\n\nLemma FD_unique n k k' : FD n k -> FD n k' -> k = k'.\nProof.\nintros H1.\nrevert k'.\ninduction H1; inversion 1; subst; auto; try omega; uniq.\nQed.\n\nLemma FD_step n k k' : FD n k -> FD (S n) k' -> k'=k \\/ k' = S k.\nProof.\ninversion 2; subst; intros; simpl in *; rewrite ?Nat.sub_0_r in *.\n- replace k with 0 by (apply FD_unique with 0; auto). auto.\n- replace k with 1 by (apply FD_unique with 1; auto). auto.\n- replace k with 1 by (apply FD_unique with 2; auto). auto.\n- replace k with 2 by (apply FD_unique with 3; auto). auto.\n- replace x with k by (apply FD_unique with n; auto). omega.\n- replace y with k by (apply FD_unique with n; auto). omega.\n- replace k' with k by (apply FD_unique with n; auto). omega.\nQed.\n\n(** [fg] is an implementation of [FD] (hence the only one). *)\n\nLemma fg_implements_FD n : FD n (fg n).\nProof.\ninduction n as [n IH] using lt_wf_rec.\ndestruct (le_lt_dec n 4) as [Hn|Hn].\n- destruct n as [|[|[|[|n]]]]; try constructor.\n  replace n with 0 by omega. constructor.\n- assert (FD (n-2) (fg (n-2))) by (apply IH; omega).\n  assert (FD (n-1) (fg (n-1))) by (apply IH; omega).\n  destruct (fg_step (n-2)) as [E|N].\n  + replace n with (S (S (n-2))) at 2 by omega.\n    rewrite (fg_nonflat (n-2)); auto.\n    constructor; auto. rewrite <- E.\n    replace (S (n-2)) with (n-1) by omega. auto.\n  + replace (S (n-2)) with (n-1) in N by omega.\n    set (x := fg (n-2)) in *.\n    set (y := fg (n-1)) in *.\n    assert (FD y (fg y)).\n    { apply IH. unfold y. generalize (fg_le (n-1)); omega. }\n    assert (FD (S y) (fg (S y))).\n    { apply IH. unfold y. generalize (@fg_lt (n-1)); omega. }\n    assert (Hn' : 3 < n) by omega.\n    assert (Hn'' : 3 < n-1) by omega.\n    assert (EQ := fg_eqn Hn').\n    assert (EQ' := fg_eqn Hn'').\n    change (fg(n-1)) with y in EQ,EQ'.\n    replace (n-1-1) with (n-2) in EQ' by omega.\n    change (fg(n-2)) with x in EQ'.\n    rewrite <- N in EQ'.\n    destruct (fg_step y) as [E'|N'].\n    * replace (fg n) with (S y) by omega.\n      eapply FD_b; eauto. omega. rewrite <- E'; auto.\n    * replace (fg n) with y by omega.\n      eapply FD_c; eauto. omega. omega.\nQed.\n\nLemma fg_unique n k : FD n k <-> k = fg n.\nProof.\nsplit.\n- intros. eapply FD_unique; eauto. apply fg_implements_FD.\n- intros ->. apply fg_implements_FD.\nQed.\n\n(** The three situations a) b) c) expressed in terms of [fg]. *)\n\nLemma fg_a n : 0<n -> fg (n-2) = fg (n-1) -> fg n = S (fg (n-1)).\nProof.\ndestruct (le_lt_dec n 4).\n- destruct n as [|[|[|[|n]]]].\n  + omega.\n  + reflexivity.\n  + discriminate.\n  + reflexivity.\n  + replace n with 0 by omega. compute. reflexivity.\n- intros.\n  symmetry. apply fg_unique.\n  apply FD_a; auto using fg_implements_FD.\n  now apply fg_unique.\nQed.\n\nLemma fg_b n y : 4<n ->\n y = fg (n-1) ->\n fg (n-2) <> y ->\n fg (S y) = fg y ->\n fg n = S y.\nProof.\n intros.\n symmetry. apply fg_unique.\n apply (@FD_b n (fg (n-2)) y (fg y));\n  auto using fg_implements_FD.\n - subst. apply fg_implements_FD.\n - now apply fg_unique.\nQed.\n\nLemma fg_c n y : 4<n ->\n y = fg (n-1) ->\n fg (n-2) <> y ->\n fg (S y) <> fg y ->\n fg n = y.\nProof.\n intros.\n symmetry. apply fg_unique.\n apply (@FD_c n (fg (n-2)) y (fg y) (fg (S y)));\n  auto using fg_implements_FD.\n subst. apply fg_implements_FD.\nQed.\n\n(** An old auxiliary lemma stating the converse of the c) case *)\n\nLemma fg_c_inv n :\n  2<n -> fg n = fg (n-1) -> fg (S (fg n)) = S (fg (fg n)).\nProof.\n intros Hn Hg.\n symmetry in Hg. apply fg_unique in Hg.\n remember fg as f eqn:Hf.\n inversion Hg; subst.\n - reflexivity.\n - compute in H1. discriminate.\n - omega.\n - compute in H1. discriminate.\n - compute in H1. discriminate.\n - assert (x = fg(n-1)).\n   { eapply FD_unique; eauto using fg_implements_FD. }\n   omega.\n - assert (y = fg(n-1)).\n   { eapply FD_unique; eauto using fg_implements_FD. }\n   omega.\n - set (y := fg(n-1)) in *.\n   assert (y = fg n).\n   { eapply FD_unique with n; eauto using fg_implements_FD. }\n   assert (z = fg y).\n   { eapply FD_unique; eauto using fg_implements_FD. }\n   assert (t = fg (S y)).\n   { eapply FD_unique; eauto using fg_implements_FD. }\n   destruct (fg_step y); congruence.\nQed.\n\n(** Presentation via a \"delta\" function *)\n\nDefinition d n := fg (S n) - fg n.\n\nLemma delta_0_1 n : d n = 0 \\/ d n = 1.\nProof.\n unfold d. destruct (fg_step n); omega.\nQed.\n\nLemma delta_a n : n<>0 -> d (n-1) = 0 -> d n = 1.\nProof.\n intro Hn.\n unfold d in *.\n generalize (fg_nonflat (n-1)).\n generalize (fg_mono_S (n-1)).\n replace (S (n-1)) with n by omega.\n omega.\nQed.\n\nLemma delta_b n : 4<=n ->\n d (n-1) = 1 -> d (fg n) = 0 -> d n = 1.\nProof.\n unfold d.\n intros.\n replace (S (n-1)) with n in * by omega.\n rewrite (@fg_b (S n) (fg n)); try omega.\n f_equal. omega.\n simpl. omega.\n generalize (fg_step (fg n)). omega.\nQed.\n\nLemma delta_c n : 4<=n ->\n d (n-1) = 1 -> d (fg n) = 1 -> d n = 0.\nProof.\n unfold d.\n intros.\n replace (S (n-1)) with n in * by omega.\n rewrite (@fg_c (S n) (fg n)); try omega.\n f_equal. omega.\n simpl. omega.\nQed.\n\nLemma delta_bc n : 4<=n -> d (n-1) = 1 -> d n = 1 - d (fg n).\nProof.\n intros.\n destruct (delta_0_1 (fg n)) as [E|E]; rewrite E.\n - now apply delta_b.\n - now apply delta_c.\nQed.\n\n(* A short formula giving delta:\n   This could be used to define fg. *)\n\nLemma delta_eqn n : 4<=n ->\n d n = 1 - d (n-1) * d (fg n).\nProof.\n intros.\n destruct (delta_0_1 (n-1)) as [E|E]; rewrite E.\n - simpl. apply delta_a; auto; omega.\n - rewrite Nat.mul_1_l. now apply delta_bc.\nQed.\n\n(*============================================================*)\n\n(** * An alternative equation for [fg]\n\n   Another short equation for [fg], but this one cannot be used\n   for defining [fg] recursively :-(\n*)\n\nLemma fg_alt_eqn n : 3 < n -> fg (fg n) + fg (n-1) = n.\nProof.\n intros.\n set (k := depth n).\n assert (Hk : 3<=k).\n { unfold k. change 3 with (depth 4).\n   apply depth_mono; auto. }\n assert (LE : S (fib (S k)) <= n <= fib (S (S k))).\n { apply depth_carac. omega. auto. }\n unfold fg. rewrite flip_flip.\n rewrite flip_eqn0; rewrite !g_depth, flip_depth; [|unfold k in *; omega].\n fold k.\n replace (S (S (k-1-1))) with k by omega.\n destruct (eq_nat_dec n (S (fib (S k)))) as [EQ|NE].\n - rewrite EQ.\n   replace (S (fib (S k)) - 1) with (fib (S k)) by omega.\n   rewrite flip_Sfib by omega.\n   replace k with (S (k-1)) by omega.\n   rewrite flip_fib by omega.\n   rewrite !g_fib by omega.\n   replace (k-1) with (S (k-2)) at 3 by omega.\n   rewrite g_Sfib by omega.\n   rewrite flip_Sfib by omega.\n   replace (S (k-2)) with (k-1) by omega.\n   rewrite fib_eqn'; omega.\n - assert (Hk' : depth (n-1) = k).\n   { apply depth_carac; omega. }\n   rewrite (flip_eqn0 (g _)); rewrite g_depth, flip_depth, Hk';\n    [|omega].\n   replace (S (k-1)) with k by omega.\n   rewrite flip_pred by (unfold k in Hk'; omega).\n   rewrite g_S.\n   rewrite (flip_eqn0 n) at 2 by (unfold k in Hk; omega).\n   fold k.\n   assert (Hk'' : depth (g (g (flip n))) = k-2).\n   { rewrite !g_depth, flip_depth. unfold k; omega. }\n   apply depth_carac in Hk'' ; [|omega].\n   rewrite (fib_eqn (S k)).\n   replace (S (S (k-2))) with k in * by omega.\n   assert (fib k <= fib (S k)).\n   { apply fib_mono. omega. }\n   omega.\nQed.\n\n(** This last equation f(f(n)) + f(n-1) = n for n > 3\n    is nice and short, but unfortunately it doesn't define\n    a unique function, even if the first values are fixed to\n    0 1 1 2. For instance: *)\n\nDefinition oups n :=\n match n with\n | 0 => 0\n | 1 => 1\n | 2 => 1\n | 3 => 2\n | 4 => 3\n | 5 => 3\n | 6 => 5\n | 7 => 3\n | _ => if even n then n-2 else 4\n end.\n\nLemma oups_def n : 7<n -> oups n = if even n then n-2 else 4.\nProof.\n do 8 (destruct n; try omega). reflexivity.\nQed.\n\nLemma oups_alt_eqn n : 3<n -> oups (oups n) + oups (n-1) = n.\nProof.\nintros.\ndestruct (le_lt_dec n 9).\n- do 10 (destruct n; simpl; try omega).\n- case_eq (even n); intros E.\n  + rewrite (@oups_def n),E,!oups_def by omega.\n    rewrite !Nat.even_sub,E by omega. simpl. omega.\n  + rewrite (@oups_def n),E by omega. simpl.\n    rewrite oups_def by omega.\n    rewrite !Nat.even_sub,E by omega. simpl. omega.\nQed.\n\n(** We will show below that if we require this equation along\n    with a monotonicity constraint, then there is a unique\n    solution (which is hence [fg]). *)\n\n(** Study of the alternative equation and its consequences. *)\n\nDefinition AltSpec (f:nat->nat) :=\n  (f 0 = 0 /\\ f 1 = 1 /\\ f 2 = 1 /\\ f 3 = 2) /\\\n  (forall n, 3<n -> f (f n) + f (n-1) = n).\n\nLemma alt_spec_fg : AltSpec fg.\nProof.\nsplit. now compute. apply fg_alt_eqn.\nQed.\n\nLemma alt_spec_oups : AltSpec oups.\nProof.\nsplit. now compute. apply oups_alt_eqn.\nQed.\n\nLemma alt_bound f : AltSpec f -> forall n, 1<n -> 0 < f n < n.\nProof.\nintros ((H0 & H1 & H2 & H3),Hf).\ninduction n as [n IH] using lt_wf_rec.\nintros Hn.\ndestruct (le_lt_dec n 3) as [Hn'|Hn'].\n- destruct n as [|[|[|n]]]; try omega. replace n with 0; omega.\n- assert (1 < f (f n) < n).\n  { generalize (IH (n-1)) (Hf n). omega. }\n  assert (f (f (S n)) + f n = S n).\n  { replace n with (S n - 1) at 2 by omega. apply Hf; omega. }\n  assert (f n <> 0). { intros E. rewrite E in *. omega. }\n  assert (f n <> n). { intros E. rewrite !E in *. omega. }\n  assert (f n <> S n).\n  { intros E. rewrite E in *. specialize (IH (f (S n))). omega. }\n  omega.\nQed.\n\nLemma alt_bound' f : AltSpec f -> forall n, 0 <= f n <= n.\nProof.\nintros Hf [|[|n]].\n- replace (f 0) with 0. auto. symmetry. apply Hf.\n- replace (f 1) with 1. auto. symmetry. apply Hf.\n- generalize (@alt_bound _ Hf (S (S n))). omega.\nQed.\n\nLemma alt_4 f : AltSpec f -> f 4 = 3.\nProof.\n intros Hf.\n assert (0 < f 4 < 4) by (apply alt_bound; auto).\n assert (f (f 4) + f 3 = 4) by (apply Hf; auto).\n destruct Hf as ((F0 & F1 & F2 & F3),_).\n destruct (f 4) as [|[|[|[|n]]]]; omega.\nQed.\n\nLemma alt_5 f : AltSpec f -> f 5 = 3.\nProof.\n intros Hf.\n assert (0 < f 5 < 5) by (apply alt_bound; auto).\n assert (f (f 5) + f 4 = 5) by (apply Hf; auto).\n assert (f 4 = 3) by (apply alt_4; auto).\n destruct Hf as ((F0 & F1 & F2 & F3),_).\n destruct (f 5) as [|[|[|[|[|n]]]]]; omega.\nQed.\n\n(** Alas, [f(n)] isn't unique for [n>5] (e.g 4 or 5 for [n=6]) *)\n\nLemma monotone_equiv f :\n (forall n, f n <= f (S n)) ->\n (forall n m, n <= m -> f n <= f m).\nProof.\nintros Mon.\ninduction 1.\n- reflexivity.\n- now transitivity (f m).\nQed.\n\nLemma alt_mono_bound f : AltSpec f ->\n  (forall n, f n <= f (S n)) ->\n  forall n m, n <= m -> f m - f n <= m-n.\nProof.\nintros Hf Mon.\nassert (main : forall n m, 3 < n <= m -> f m - f n <= m - n).\n{\n  intros.\n  destruct Hf as (_,Hf).\n  generalize (Hf (S n)) (Hf (S m)); simpl; intros.\n  rewrite Nat.sub_0_r in *.\n  generalize (@monotone_equiv _ Mon (S n) (S m)).\n  generalize (@monotone_equiv _ Mon (f (S n)) (f (S m))).\n  omega.\n}\nintros n m. destruct (le_lt_dec n 3); intros.\n- destruct (le_lt_dec m 3); intros.\n  + destruct Hf as ((F0 & F1 & F2 & F3), _).\n    destruct m as [|[|[|[|m]]]], n as [|[|[|[|n]]]]; omega.\n  + specialize (main 4 m). rewrite alt_4 in main; auto.\n    destruct Hf as ((F0 & F1 & F2 & F3), _).\n    destruct n as [|[|[|[|n]]]]; omega.\n- apply main; auto.\nQed.\n\nLemma alt_mono_unique f1 f2 :\n  AltSpec f1 -> (forall n, f1 n <= f1 (S n)) ->\n  AltSpec f2 -> (forall n, f2 n <= f2 (S n)) ->\n  forall n, f1 n = f2 n.\nProof.\nintros Hf1 Mon1 Hf2 Mon2.\ninduction n as [n IH] using lt_wf_rec.\ndestruct (le_lt_dec n 3).\n- destruct Hf1 as ((F10 & F11 & F12 & F13),_),\n           Hf2 as ((F20 & F21 & F22 & F23),_).\n  destruct n as [|[|[|[|n]]]]; omega.\n- assert (f1 (n-1) = f2 (n-1)) by (apply IH; omega).\n  assert (f1 (f1 n) = f2 (f2 n)).\n  { destruct Hf1 as (_,Hf1), Hf2 as (_,Hf2).\n    specialize (Hf1 n). specialize (Hf2 n). omega. }\n  set (x1:=f1 n) in *.\n  set (x2:=f2 n) in *.\n  assert (f1 x1 = f2 x1).\n  { apply IH. apply alt_bound; auto. omega. }\n  assert (f1 x2 = f2 x2).\n  { apply IH. apply alt_bound; auto. omega. }\n  assert (f2 (n-1) <= x2 /\\ x2-f2(n-1) <= 1).\n  { unfold x2; split.\n    - generalize (Mon2 (n-1)); replace (S (n-1)) with n; omega.\n    - generalize (@alt_mono_bound _ Hf2 Mon2 (n-1) n); omega. }\n  assert (f1 (n-1) <= x1 /\\ x1-f1(n-1) <= 1).\n  { unfold x1; split.\n    - generalize (Mon1 (n-1)); replace (S (n-1)) with n; omega.\n    - generalize (@alt_mono_bound _ Hf1 Mon1 (n-1) n); omega. }\n  destruct (lt_eq_lt_dec x1 x2) as [[LT|EQ]|LT]; trivial; exfalso.\n  + (* x1 < x2 *)\n    assert (f1 (S x1) <= f1 x2).\n    { apply monotone_equiv. apply Mon1. apply LT. }\n    assert (f1 (f1 (S n)) = S (f1 x1)).\n    { destruct Hf1 as (_,Hf1).\n      generalize (Hf1 (S n)) (Hf1 n); simpl.\n      rewrite Nat.sub_0_r.\n      unfold x1 in *; omega. }\n    assert (f1 (f1 (S n)) = f1 (S x1)).\n    { f_equal.\n      generalize\n        (@alt_mono_bound _ Hf1 Mon1 n (S n))\n        (@alt_mono_bound _ Hf1 Mon1 x1 (f1 (S n)) (Mon1 n)).\n      unfold x1 in *; omega. }\n    omega.\n  + (* x2 < x1 *)\n    assert (f2 (S x2) <= f2 x1).\n    { apply monotone_equiv. apply Mon2. apply LT. }\n    assert (f2 (f2 (S n)) = S (f2 x2)).\n    { destruct Hf2 as (_,Hf2).\n      generalize (Hf2 (S n)) (Hf2 n); simpl.\n      rewrite Nat.sub_0_r.\n      unfold x2 in *; omega. }\n    assert (f2 (f2 (S n)) = f2 (S x2)).\n    { f_equal.\n      generalize\n        (@alt_mono_bound _ Hf2 Mon2 n (S n))\n        (@alt_mono_bound _ Hf2 Mon2 (f2 n) (f2 (S n)) (Mon2 n)).\n      unfold x2 in *; omega. }\n    omega.\nQed.\n\nLemma alt_mono_is_fg f :\n  AltSpec f -> (forall n, f n <= f (S n)) ->\n  forall n, f n = fg n.\nProof.\n intros Hg Mon. apply alt_mono_unique; auto.\n - split. now compute. apply fg_alt_eqn.\n - apply fg_mono_S.\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/FlipG.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.6920782800209428}}
{"text": "(*******************************************************************************\n\nTitle: CommutativeSquares.v\nAuthors: Jeremy Avigad, Chris Kapulkin, Peter LeFanu Lumsdaine\nDate: 1 March 2013\n\nSome basic results on commutative squares, considered as maps of\narrows.\n\n*******************************************************************************)\n\nRequire Import HoTT.\nRequire Import Auxiliary.\n\nSection Comm_Squares.\n\n(* Commutative squares compose. *)\nLemma comm_square_comp\n  {A B} {f:A->B} {A' B'} {f':A'->B'} {A'' B''} {f'':A''->B''}\n  {h' : A' -> A''} {g' : B' -> B''} (comm' : f'' o h' == g' o f')\n  {h : A -> A'} {g : B -> B'} (comm : f' o h == g o f)\n: f'' o (h' o h) == (g' o g) o f.\nProof.\n  intros x. path_via (g' (f' (h x))).\n  apply ap, comm.\nDefined.\n\n(* We show that given any commutative square from [f] to [f'] whose verticals\n[wA, wB] are equivalences, the equiv_inv square from [f'] to [f] with verticals\n[wA ^-1, wB ^-1] also commutes. *)\nLemma comm_square_inverse\n  {A B : Type} {f : A -> B}\n  {A' B' : Type} {f' : A' -> B'}\n  {wA : A <~> A'} {wB : B <~> B'}\n  (wf : f' o wA == wB o f)\n: f o (wA ^-1) == (wB ^-1) o f'.\nProof.\n  intros a'.\n  path_via (wB ^-1 (wB (f (wA ^-1 a')))).\n    apply inverse, eissect.\n  apply ap, (concat (wf _)^). \n  apply ap, eisretr.\nDefined.\n\n(* Up to naturality, the result of [comm_square_inverse] really is a\nretraction (aka left inverse); *)\nLemma comm_square_inverse_is_sect\n  {A B : Type} {f : A -> B}\n  {A' B' : Type} {f' : A' -> B'}\n  (wA : A <~> A') (wB : B <~> B')\n  (wf : f' o wA == wB o f)\n: (fun a:A => (comm_square_comp (comm_square_inverse wf) wf a)\n             @ eissect wB (f a))\n   == fun a:A => (ap f (eissect wA a)).\nProof.\n  intros a; simpl. unfold comm_square_inverse, comm_square_comp; simpl.\n  repeat apply (concat (concat_pp_p)). apply moveR_Vp.\n  path_via' (ap (wB ^-1 o wB) (ap f (eissect wA a)) @ eissect wB (f a)).\n    Focus 2. apply (concat (concat_Ap (eissect wB) _)). apply ap, ap_idmap.\n  apply (concat (concat_p_pp)), whiskerR.\n  apply (concat (ap_pp (wB ^-1) _ _)^), (concatR (ap_compose wB _ _)^). \n  apply ap, (concat concat_pp_p), moveR_Vp.\n  path_via (ap (f' o wA) (eissect wA a) @ wf a).\n    apply whiskerR.  apply (concatR (ap_compose wA f' _)^).\n    apply ap, eisadj.\n  apply (concat (concat_Ap wf _)).\n  apply whiskerL, (ap_compose f wB).\nDefined.\n\n(* and similarly, [comm_square_inverse] is a section (aka right equiv_inv). *)\n(* TODO (low) : simplify proof!? *)\nLemma comm_square_inverse_is_retr\n  {A B : Type} {f : A -> B}\n  {A' B' : Type} {f' : A' -> B'}\n  (wA : A <~> A') (wB : B <~> B')\n  (wf : f' o wA == wB o f)\n: (fun a:A' => (comm_square_comp wf (comm_square_inverse wf) a)\n             @ eisretr wB (f' a))\n   == fun a:A' => (ap f' (eisretr wA a)).\nProof.\n  intros a; simpl. unfold comm_square_inverse, comm_square_comp; simpl.\n  rewrite !ap_pp. rewrite <- !concat_pp_p.\n  rewrite concat_pp_p.\n  set (p := (ap wB (ap (wB ^-1) (ap f' (eisretr wA a)))\n            @ eisretr wB (f' a))).\n  path_via ((eisretr wB _)^ @ p).\n  apply whiskerR.\n    apply moveR_pM.\n    path_via ((eisretr wB (f' (wA (wA ^-1 a))))^ @\n       ap (wB o wB ^-1) (wf ((wA ^-1) a))).\n      rewrite ap_V. rewrite <- eisadj.\n      path_via' (ap idmap (wf ((wA ^-1) a))\n        @ (eisretr wB (wB (f ((wA ^-1) a))))^).\n      apply whiskerR. apply inverse. apply ap_idmap.\n      apply (concat_Ap\n         (fun b' => (eisretr wB b')^) (wf ((wA ^-1) a)) ).\n    apply ap. rewrite ap_compose. rewrite !ap_V.\n    apply inverse. apply inv_V.\n  apply moveR_Vp. subst p. rewrite <- ap_compose.\n  path_via (eisretr wB (f' (wA ((wA ^-1) a)))\n            @ ap idmap (ap f' (eisretr wA a))).\n  apply (concat_Ap\n    (eisretr wB) (ap f' (eisretr wA a)) ).\n  apply ap. apply ap_idmap.\nDefined.\n\nEnd Comm_Squares.\n\n(*\nLocal Variables:\ncoq-prog-name: \"hoqtop\"\nEnd:\n*)\n", "meta": {"author": "peterlefanulumsdaine", "repo": "hott-limits", "sha": "188e627b0bd27b5252c1a7c2b405220077780eb7", "save_path": "github-repos/coq/peterlefanulumsdaine-hott-limits", "path": "github-repos/coq/peterlefanulumsdaine-hott-limits/hott-limits-188e627b0bd27b5252c1a7c2b405220077780eb7/CommutativeSquares.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.6920782715922754}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  zNil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nLemma append_assoc: forall l1 l2 l3, \n  append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\ninduction l1.\n  - simpl. intros. rewrite IHl1. reflexivity.\n  - reflexivity.\nQed.\n\nLemma lem: forall l n, Cons n (rev l) = rev (append l (Cons n Nil)).\nProof.\nintros. induction l.\n  - simpl. rewrite <- IHl. reflexivity.\n  - reflexivity.\nQed.\n\nLemma lem2: forall l, rev (rev l) = l.\nProof.\ninduction l.\n  - simpl. lfind.  rewrite IHl.  reflexivity. \nAdmitted.\n\nLemma lem3: forall l, append l Nil = l.\nProof.\ninduction l.\n  - simpl. rewrite IHl. reflexivity.\n  - reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : lst) (y : lst), eq (rev (append (rev x) (rev y))) (append y x).\nProof.\n induction x.\n - intros. simpl. rewrite <- append_assoc. simpl. \n   rewrite lem. rewrite IHx. rewrite <- append_assoc. reflexivity.\n - intros. simpl. rewrite lem2. rewrite lem3. reflexivity.\nQed.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/clam_lf_goal11_lem2_41_lem/goal11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.6920564738167729}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Poly.\n\n(* apply tactics *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n  apply eq2. Qed.\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1. Qed.\n\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\nTheorem silly_ex :\n  (forall n, evenb n=true -> oddb (S n)=true) ->\n  oddb 3=true ->\n  evenb 4=true.\nProof.\n  intros eq1 eq2.\n  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.\n  symmetry.\n  apply H. Qed.\n\nTheorem rev_ex1 : forall(l l': list nat),\n    l = rev l' ->\n    l' = rev l.\nProof.\n  intros.\n  rewrite H.\n  symmetry.\n  apply rev_involutive. 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\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\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)).\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\nTheorem injection_ex1 : forall(n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H.\n  injection H. intros H1 H2.\n  rewrite H1. rewrite H2. reflexivity.\nQed.\n\nExample injection_ex3 : forall(X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  intros.\n  injection H0.\n  intros sH1 sH2.\n  symmetry. apply sH2.\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 H. discriminate H.\nQed.\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.\n  discriminate H.\nQed.\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq. reflexivity. Qed.\n\n\nTheorem S_inj : forall(n m: nat)(b: bool),\n    (S n)=?(S m) = b ->\n    n=?m = b.\nProof.\n  intros.\n  simpl in H.\n  apply H. Qed.\n\nTheorem plus_n_n_injective : forall n m,\n    n+n = m+m ->\n    n = m.\nProof.\n  intros n. induction n as [| n'].\n  intros m H. destruct m as [|m'].\n    reflexivity.\n    inversion H.\n  intros m. destruct m as [|m'].\n    intros. inversion H.\n    intros eq. inversion eq.\n    rewrite <- plus_n_Sm in H0. rewrite <- plus_n_Sm in H0.\n    inversion H0. apply IHn' in H1. rewrite -> H1. reflexivity.\nQed.\n      \nDefinition square n := n * n.\n\nTheorem plus_assoc : forall n m p : nat, n + (m + p) = (n + m) + p.\nProof.\n  intros n m p. induction n as [| n'].\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\n\n\nLemma mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof.\n  intros n m p.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite IHn.\n  rewrite plus_assoc.\n  reflexivity.\nQed.\n\n\nTheorem mult_assoc: forall n m p: nat,\n    n*(m*p)=(n*m)*p.\nProof.\n  intros.\n  induction n.\n  - reflexivity.\n  - simpl.\n    rewrite IHn. rewrite mult_plus_distr_r.\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  assert (H: n + m = m + n).\n  - rewrite plus_comm. reflexivity.\n  - rewrite plus_assoc. rewrite H. rewrite plus_assoc. reflexivity.\nQed.\n\n\nTheorem mult_plus : forall n m : nat, n * S m = n + (n * m).\nProof.\n  intros n m.\n  induction n as [| n'].\n  - reflexivity.\n  - simpl. rewrite IHn'. rewrite plus_swap. reflexivity.\nQed.\n\nTheorem mult_0_r : forall n : nat, n * 0 = 0.\nProof.\n  intros n. induction n as [| n'].\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\n\n\nTheorem mult_comm : forall m n : nat, m * n = n * m.\nProof.\n  intros m n. induction m as [| m'].\n  - rewrite mult_0_r. reflexivity.\n  - simpl. rewrite mult_plus. rewrite IHm'. reflexivity.\nQed.\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\n\n", "meta": {"author": "StarGazerM", "repo": "my-foolish-code", "sha": "2991997f9be4523bf190ef4143df8b0d89e528cf", "save_path": "github-repos/coq/StarGazerM-my-foolish-code", "path": "github-repos/coq/StarGazerM-my-foolish-code/my-foolish-code-2991997f9be4523bf190ef4143df8b0d89e528cf/lf/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.867035752930664, "lm_q1q2_score": 0.6920564738167729}}
{"text": "(** * Induction: Proof by Induction *)\n\n(** First, we import all of our definitions from the previous\n    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         Run [coqc Basics.v]\n\n    *)\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.  The fact that it is also a neutral element on the\n    _right_... *)\n\nTheorem plus_n_O_firsttry : forall n:nat,\n  n = n + 0.\n\n(** ... cannot be proved in the same simple way.  Just applying\n  [reflexivity] doesn't work, since the [n] in [n + 0] is an arbitrary\n  unknown number, so the [match] in the definition of [+] can't be\n  simplified.  *)\n\nProof.\n  intros n.\n  simpl. (* Does nothing! *)\nAbort.\n\n(** And reasoning by cases using [destruct n] doesn't get us much\n   further: the branch of the case analysis where we assume [n = 0]\n   goes through fine, but in the branch where [n = S n'] for some [n'] we\n   get stuck in exactly the same way.  We could use [destruct n'] to\n   get one step further, but, since [n] can be arbitrarily large, if we\n   try to keep on like this we'll never be done. *)\n\nTheorem plus_n_O_secondtry : forall n:nat,\n  n = n + 0.\nProof.\n  intros n. destruct n as [| n'].\n  - (* n = 0 *)\n    reflexivity. (* so far so good... *)\n  - (* n = S n' *)\n    simpl.       (* ...but here we are stuck again *)\nAbort.\n\n(** To prove interesting facts about numbers, lists, and other\n    inductively defined sets, we usually need a more powerful\n    reasoning principle: _induction_.\n\n    Recall (from high school, a discrete math course, etc.) the\n    principle of induction over natural numbers: If [P(n)] is some\n    proposition involving a natural number [n] and we want to show\n    that [P] holds for _all_ numbers [n], we can reason like this:\n         - show that [P(O)] holds;\n         - show that, for any [n'], if [P(n')] holds, then so does\n           [P(S n')];\n         - conclude that [P(n)] holds for all [n].\n\n    In Coq, the steps are the same but the order is backwards: we\n    begin with the goal of proving [P(n)] for all [n] and break it\n    down (by applying the [induction] tactic) into two separate\n    subgoals: first showing [P(O)] and then showing [P(n') -> P(S\n    n')].  Here's how this works for the theorem at hand: *)\n\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)    reflexivity.\n  - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity.  Qed.\n\n(** Like [destruct], the [induction] tactic takes an [as...]\n    clause that specifies the names of the variables to be introduced\n    in the subgoals.  In the first branch, [n] is replaced by [0] and\n    the goal becomes [0 + 0 = 0], which follows by simplification.  In\n    the second, [n] is replaced by [S n'] and the assumption [n' + 0 =\n    n'] is added to the context (with the name [IHn'], i.e., the\n    Induction Hypothesis for [n'] -- notice that this name is\n    explicitly chosen in the [as...] clause of the call to [induction]\n    rather than letting Coq choose one arbitrarily). The goal in this\n    case becomes [(S n') + 0 = S n'], which simplifies to [S (n' + 0)\n    = S n'], which in turn follows from [IHn']. *)\n\nTheorem minus_diag : forall n,\n  minus n n = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl. reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n\n(** (The use of the [intros] tactic in these proofs is actually\n    redundant.  When applied to a goal that contains quantified\n    variables, the [induction] tactic will automatically move them\n    into the context as needed.) *)\n\n(** **** Exercise: 2 stars, recommended (basic_induction)  *)\n(** Prove the following using induction. You might need previously\n    proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  (* 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 that it\n    may need to perform a recursive call on [n - 2]. This makes proofs\n    about [evenb n] harder when done by induction on [n], since we may\n    need an induction hypothesis about [n - 2]. The following lemma\n    gives a better characterization of [evenb (S n)]: *)\n\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(** The [assert] tactic is handy in many sorts of situations.  For\n    example, suppose we want to prove that [(n + m) + (p + q) = (m +\n    n) + (p + q)]. The only difference between the two sides of the\n    [=] is that the arguments [m] and [n] to the first inner [+] are\n    swapped, so it seems we should be able to use the commutativity of\n    addition ([plus_comm]) to rewrite one into the other.  However,\n    the [rewrite] tactic is a little stupid about _where_ it applies\n    the rewrite.  There are three uses of [+] here, and it turns out\n    that doing [rewrite -> plus_comm] will affect only the _outer_\n    one... *)\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  (* We just need to swap (n + m) for (m + n)...\n     it seems like plus_comm should do the trick! *)\n  rewrite -> plus_comm.\n  (* Doesn't work...Coq rewrote the wrong plus! *)\nAbort.\n\n(** To get [plus_comm] to apply at the point where we want it to, we\n    can introduce a local lemma stating that [n + m = m + n] (for the\n    particular [m] and [n] that we are talking about here), prove this\n    lemma using [plus_comm], and then use it to do the desired\n    rewrite. *)\n\nTheorem plus_rearrange : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (H: n + m = m + n).\n  { rewrite -> plus_comm. reflexivity. }\n  rewrite -> H. reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, recommended (mult_comm)  *)\n(** Use [assert] to help prove this theorem.  You shouldn't need to\n    use induction on [plus_swap]. *)\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  (* 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               bin --------- incr -------> bin\n                |                           |\n            bin_to_nat                  bin_to_nat\n                |                           |\n                v                           v\n               nat ---------- S ---------> nat\n\n    That is, incrementing a binary number and then converting it to \n    a (unary) natural number yields the same result as first converting\n    it to a natural number and then incrementing.  \n    Name your theorem [bin_to_nat_pres_incr] (\"pres\" for \"preserves\").\n\n    Before you start working on this exercise, please copy the\n    definitions from your solution to the [binary] exercise here so\n    that this file can be graded on its own.  If you find yourself\n    wanting to change your original definitions to make the property\n    easier to prove, feel free to do so! *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced (binary_inverse)  *)\n(** This exercise is a continuation of the previous exercise about\n    binary numbers.  You will need your definitions and theorems from\n    there to complete this one.\n\n    (a) First, write a function to convert natural numbers to binary\n        numbers.  Then prove that starting with any natural number,\n        converting to binary, then converting back yields the same\n        natural number you started with.\n\n    (b) You might naturally think that we should also prove the\n        opposite direction: that starting with a binary number,\n        converting to a natural, and then back to binary yields the\n        same number we started with.  However, this is not true!\n        Explain what the problem is.\n\n    (c) Define a \"direct\" normalization function -- i.e., a function\n        [normalize] from binary numbers to binary numbers such that,\n        for any binary number b, converting to a natural and then back\n        to binary yields [(normalize b)].  Prove it.  (Warning: This\n        part is tricky!)\n\n    Again, feel free to change your earlier definitions if this helps\n    here. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ################################################################# *)\n(** * Formal vs. Informal Proof (Optional) *)\n\n(** \"_Informal proofs are algorithms; formal proofs are code_.\" *)\n\n(** The question of what constitutes a proof of a mathematical\n    claim has challenged philosophers for millennia, but a rough and\n    ready definition could be this: A proof of a mathematical\n    proposition [P] is a written (or spoken) text that instills in the\n    reader or hearer the certainty that [P] is true.  That is, a proof\n    is an act of communication.\n\n    Acts of communication may involve different sorts of readers.  On\n    one hand, the \"reader\" can be a program like Coq, in which case\n    the \"belief\" that is instilled is that [P] can be mechanically\n    derived from a certain set of formal logical rules, and the proof\n    is a recipe that guides the program in checking this fact.  Such\n    recipes are _formal_ proofs.\n\n    Alternatively, the reader can be a human being, in which case the\n    proof will be written in English or some other natural language,\n    and will thus necessarily be _informal_.  Here, the criteria for\n    success are less clearly specified.  A \"valid\" proof is one that\n    makes the reader believe [P].  But the same proof may be read by\n    many different readers, some of whom may be convinced by a\n    particular way of phrasing the argument, while others may not be.\n    Some readers may be particularly pedantic, inexperienced, or just\n    plain thick-headed; the only way to convince them will be to make\n    the argument in painstaking detail.  But other readers, more\n    familiar in the area, may find all this detail so overwhelming\n    that they lose the overall thread; all they want is to be told the\n    main ideas, since it is easier for them to fill in the details for\n    themselves than to wade through a written presentation of them.\n    Ultimately, there is no universal standard, because there is no\n    single way of writing an informal proof that is guaranteed to\n    convince every conceivable reader.\n\n    In practice, however, mathematicians have developed a rich set of\n    conventions and idioms for writing about complex mathematical\n    objects that -- at least within a certain community -- make\n    communication fairly reliable.  The conventions of this stylized\n    form of communication give a fairly clear standard for judging\n    proofs good or bad.\n\n    Because we are using Coq in this course, we will be working\n    heavily with formal proofs.  But this doesn't mean we can\n    completely forget about informal ones!  Formal proofs are useful\n    in many ways, but they are _not_ very efficient ways of\n    communicating ideas between human beings. *)\n\n(** For example, here is a proof that addition is associative: *)\n\nTheorem plus_assoc' : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n' IHn']. reflexivity.\n  simpl. rewrite -> IHn'. reflexivity.  Qed.\n\n(** Coq is perfectly happy with this.  For a human, however, it\n    is difficult to make much sense of it.  We can use comments and\n    bullets to show the structure a little more clearly... *)\n\nTheorem plus_assoc'' : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity.   Qed.\n\n(** ... and if you're used to Coq you may be able to step\n    through the tactics one after the other in your mind and imagine\n    the state of the context and goal stack at each point, but if the\n    proof were even a little bit more complicated this would be next\n    to impossible.\n\n    A (pedantic) mathematician might write the proof something like\n    this: *)\n\n(** - _Theorem_: For any [n], [m] and [p],\n\n      n + (m + p) = (n + m) + p.\n\n    _Proof_: By induction on [n].\n\n    - First, suppose [n = 0].  We must show\n\n        0 + (m + p) = (0 + m) + p.\n\n      This follows directly from the definition of [+].\n\n    - Next, suppose [n = S n'], where\n\n        n' + (m + p) = (n' + m) + p.\n\n      We must show\n\n        (S n') + (m + p) = ((S n') + m) + p.\n\n      By the definition of [+], this follows from\n\n        S (n' + (m + p)) = S ((n' + m) + p),\n\n      which is immediate from the induction hypothesis.  _Qed_. *)\n\n\n(** The overall form of the proof is basically similar, and of\n    course this is no accident: Coq has been designed so that its\n    [induction] tactic generates the same sub-goals, in the same\n    order, as the bullet points that a mathematician would write.  But\n    there are significant differences of detail: the formal proof is\n    much more explicit in some ways (e.g., the use of [reflexivity])\n    but much less explicit in others (in particular, the \"proof state\"\n    at any given point in the Coq proof is completely implicit,\n    whereas the informal proof reminds the reader several times where\n    things stand). *)\n\n(** **** Exercise: 2 stars, advanced, recommended (plus_comm_informal)  *)\n(** Translate your solution for [plus_comm] into an informal proof:\n\n    Theorem: Addition is commutative.\n\n    Proof: (* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl_informal)  *)\n(** Write an informal proof of the following theorem, using the\n    informal proof of [plus_assoc] as a model.  Don't just\n    paraphrase the Coq tactics into English!\n\n    Theorem: [true = beq_nat n n] for any [n].\n\n    Proof: (* FILL IN HERE *)\n[] *)\n\n(** $Date: 2016-05-26 16:17:19 -0400 (Thu, 26 May 2016) $ *)\n", "meta": {"author": "coqoon", "repo": "Software-Foundations", "sha": "a327b63aa8ff8543ae2cedee7a5960da05bbfaa7", "save_path": "github-repos/coq/coqoon-Software-Foundations", "path": "github-repos/coq/coqoon-Software-Foundations/Software-Foundations-a327b63aa8ff8543ae2cedee7a5960da05bbfaa7/Software Foundations/src/SF/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.8902942203004185, "lm_q1q2_score": 0.6920255830300667}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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) : natural := plus (Succ Zero) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj238_coqofml_KFQdvT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788077, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6920255739119687}}
{"text": "(*Section Univ.\n*)\n\nVariable U : Type.\n\nDefinition set := U -> Prop.\nDefinition element (x : U) (S : set) := S x.\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.\n\n", "meta": {"author": "kawaharasouta", "repo": "coq_exp", "sha": "aad20566e02cf61344a58d32060c1fcc2370ee4c", "save_path": "github-repos/coq/kawaharasouta-coq_exp", "path": "github-repos/coq/kawaharasouta-coq_exp/coq_exp-aad20566e02cf61344a58d32060c1fcc2370ee4c/lecture/1-5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6920255738441453}}
{"text": "From HoTT Require Import HFiber Algebra.Groups Algebra.AbGroups.\n\n(* Given a group [G], we define the centralizer of an element [g : G] as a subgroup and use this to show that the cyclic subgroup generated by [g] is abelian. *)\n\nOpen Scope mc_mult_scope.\n\n(* First we show that the collection of elements that commute with a fixed element [g] is a subgroup. *)\n\nDefinition centralizer {G : Group} (g : G)\n  := fun h => g * h = h * g.\n\nDefinition centralizer_unit {G : Group} (g : G) : centralizer g mon_unit.\nProof.\n  exact (grp_unit_r _ @ (grp_unit_l _)^).\nDefined.\n\nDefinition centralizer_sgop {G : Group} (g h k : G)\n           (p : centralizer g h) (q : centralizer g k)\n  : centralizer g (h * k).\nProof.\n  refine (grp_assoc _ _ _ @ _).\n  refine (ap (fun x => x * k) p @ _).\n  refine ((grp_assoc _ _ _)^ @ _).\n  refine (ap (fun x => h * x) q @ _).\n  apply grp_assoc.\nDefined.\n\nDefinition centralizer_inverse {G : Group} (g h : G)\n           (p : centralizer g h)\n  : centralizer g (-h).\nProof.\n  unfold centralizer in *.\n  symmetry.\n  refine ((grp_unit_r _)^ @ _ @ grp_unit_l _).\n  refine (ap (fun x => (-h * g * x)) (grp_inv_r h)^ @ _ @ ap (fun x => x * (g * -h)) (grp_inv_l h)).\n  refine (grp_assoc _ _ _ @ _ @ (grp_assoc _ _ _)^).\n  refine (ap (fun x => x * (-h)) _).\n  refine ((grp_assoc _ _ _)^ @ _ @ grp_assoc _ _ _).\n  exact (ap (fun x => (-h) * x) p).\nDefined.\n\nGlobal Instance issubgroup_centralizer {G : Group} (g : G)\n  : IsSubgroup (centralizer g).\nProof.\n  srapply Build_IsSubgroup.\n  - apply centralizer_unit.\n  - apply centralizer_sgop.\n  - apply centralizer_inverse.\nDefined.\n\nDefinition centralizer_subgroup {G : Group} (g : G)\n  := Build_Subgroup G (centralizer g) _.\n\n(* Now we define cyclic subgroups.  We allow any map [Unit -> G] in this definition, because in applications (such as [Z_commutative]) we have no control over the map. *)\nDefinition cyclic_subgroup_from_unit {G : Group} (gen : Unit -> G) := subgroup_generated (hfiber gen).\n\n(* When we have a particular element [g] of [G], we could choose the predicate to be [fun h => h = g], but to fit into the above definition, we use [unit_name g], which gives the predicate [fun h => hfiber (unit_name g) h]. *)\nDefinition cyclic_subgroup {G : Group} (g : G) := cyclic_subgroup_from_unit (unit_name g).\n\n(* Any cyclic subgroup is commutative. *)\nGlobal Instance commutative_cyclic_subgroup {G : Group} (gen : Unit -> G)\n  : Commutative (@group_sgop (cyclic_subgroup_from_unit gen)).\nProof.\n  intros h k.\n  destruct h as [h H]; cbn in H.\n  destruct k as [k K]; cbn in K.\n  strip_truncations.\n  (* It's enough to check equality after including into G: *)\n  apply (equiv_ap_isembedding (subgroup_incl _) _ _)^-1.  cbn.\n  induction H as [h [[] p]| |h1 h2 H1 H2 IHH1 IHH2].\n  - (* The case when h = g: *)\n    induction p.\n    induction K as [k [[] q]| |k1 k2 K1 K2 IHK1 IHK2].\n    + (* The case when k = g: *)\n      induction q.\n      reflexivity.\n    + (* The case when k = mon_unit: *)\n      apply centralizer_unit.\n    + (* The case when k = k1 (-k2): *)\n      srapply (issubgroup_in_op_inv (H:=centralizer (gen tt))); assumption.\n  - (* The case when h = mon_unit: *)\n    symmetry; apply centralizer_unit.\n  - (* The case when h = h1 (-h2): *)\n    symmetry.\n    srapply (issubgroup_in_op_inv (H:=centralizer k)); unfold centralizer; symmetry; assumption.\nDefined.\n\nDefinition abgroup_cyclic_subgroup {G : Group} (g : G) : AbGroup\n  := Build_AbGroup (cyclic_subgroup g) _.\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/Centralizer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220294, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6920255737763217}}
{"text": "Require Import Nat Arith Bool.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : 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 mem (mem_arg0 : Nat) (mem_arg1 : Lst) : bool\n           := match mem_arg0, mem_arg1 with\n              | x, nil => false\n              | x, cons y z => orb (Nat_beq x y) (mem x z)\n              end.\n\nDefinition lst_mem := mem.\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\nTheorem theorem0 : forall (x : Nat) (y : Lst) (z : Lst), eq (lst_mem x y) true -> eq (lst_mem x (lst_union z y)) true.\nProof.\n  intros.\n  induction z.\n  - assumption.\n  - simpl. destruct (lst_mem n y).\n    + assumption.\n    + simpl. rewrite IHz. apply orb_true_r.\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/goal43.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6920255692511844}}
{"text": "From Tealeaves.Classes Require Import\n  Monoid Monad Applicative.\nFrom Tealeaves Require Export\n  Data.Sets.\n\nImport Product.Notations.\nImport Applicative.Notations.\nImport Data.Sets.Notations.\n\n#[local] Generalizable Variables A B.\n\n(** * The <<set>> monad *)\n(******************************************************************************)\n\n(** ** Functor instance *)\n(******************************************************************************)\n\n(** [fmap f s] is the image of a set [s] under a morphism [f] *)\n#[export] Instance Fmap_set : Fmap set :=\n  fun A B (f : A -> B) (x : A -> Prop) (b : B) => exists a : A, x a /\\ f a = b.\n\n(** *** Rewriting lemmas for [fmap] *)\n(******************************************************************************)\nDefinition fmap_set_nil `{f : A -> B} :\n  fmap set f ∅ = ∅ := ltac:(solve_basic_set).\n\nDefinition fmap_set_add `{f : A -> B} {x y} :\n  fmap set f (x ∪ y) = fmap set f x ∪ fmap set f y\n  := ltac:(solve_basic_set).\n\n#[export] Hint Rewrite @fmap_set_nil @fmap_set_add : tea_set.\n\n(** *** Functor laws *)\n(******************************************************************************)\nDefinition fun_fmap_id_set {A} : fmap set id = @id (set A) :=\n  ltac:(solve_basic_set).\n\nDefinition fun_fmap_fmap_set {A B C} : forall (f : A -> B) (g : B -> C),\n    fmap set g ∘ fmap set f = fmap set (g ∘ f)\n    := ltac:(solve_basic_set).\n\n#[export] Instance Functor_set : Functor set :=\n  ltac:(constructor; solve_basic_set).\n\n(** ** [fmap] is a monoid homomorphism *)\n(******************************************************************************)\n#[export, program] Instance Monmor_set_fmap `(f : A -> B) :\n  Monoid_Morphism (fmap set f) :=\n  {| monmor_unit := @fmap_set_nil A B f;\n    monmor_op := @fmap_set_add A B f;\n  |}.\n\n(** ** Monad operations *)\n(******************************************************************************)\n#[export] Instance Return_set : Return set := fun A a b => a = b.\n\n#[export] Instance Join_set : Join set :=\n  fun A (x : (A -> Prop) -> Prop) => fun a => exists (y : A -> Prop) , x y /\\ y a.\n\n#[local] Notation \"{{ x }}\" := (ret set x).\n\nTheorem set_ret_injective : forall A (a b : A),\n    {{ a }} = {{ b }} -> a = b.\nProof.\n  intros. assert (lemma : forall x, {{ a }} x = {{ b }} x).\n  intros. now rewrite H. specialize (lemma a).\n  cbv in lemma. symmetry. now rewrite <- lemma.\nQed.\n\n(** ** Rewriting laws for [join] and [ret] *)\n(******************************************************************************)\nDefinition set_in_ret : forall A (a b : A),\n    (ret set a) b = (a = b)\n  := ltac:(solve_basic_set).\n\nLemma join_set_nil : forall A,\n    join (A:=A) set ∅ = ∅.\nProof.\n  solve_basic_set.\nQed.\n\nLemma join_set_one : forall A (x : set A),\n    join set {{ x }} = x.\nProof.\n  solve_basic_set.\nQed.\n\nLemma join_set_add : forall A (x y : set (set A)),\n    join set (x ∪ y) = join set x ∪ join set y.\nProof.\n  solve_basic_set.\nQed.\n\nLemma fmap_set_one `{f : A -> B} {a : A} :\n  fmap set f {{ a }} = {{ f a }}.\nProof.\n  solve_basic_set.\nQed.\n\n#[export] Hint Rewrite @set_in_ret @join_set_nil @join_set_one @join_set_add\n     @fmap_set_add @fmap_set_one : tea_set.\n\n(** ** Monad laws *)\n(******************************************************************************)\nTheorem join_ret {A} :\n  join set ∘ ret set = @id (A -> Prop).\nProof.\n  solve_basic_set.\nQed.\n\nTheorem join_fmap_ret {A} :\n  join set ∘ fmap set (ret set) = @id (A -> Prop).\nProof.\n  unfold transparent tcs; unfold_set. unfold compose. setext.\n  - firstorder (do 2 subst; auto).\n  - firstorder eauto.\nQed.\n\nTheorem join_join {A} :\n  join set ∘ join set =\n  join set ∘ fmap set (join set (A:=A)).\nProof.\n  unfold transparent tcs; unfold_set. unfold compose. setext.\n  - intros. preprocess. repeat eexists; eauto.\n  - intros. preprocess. repeat eexists; eauto.\nQed.\n\n#[export] Instance Natural_ret : Natural (@ret set _) :=\n  ltac:(constructor; try typeclasses eauto;\n       unfold compose; solve_basic_set).\n\n#[export] Instance Natural_join : Natural (@join set _).\nProof.\n  ltac:(constructor; try typeclasses eauto).\n  intros. unfold compose. ext SS. ext b.\n  propext.\n  - unfold transparent tcs.\n    intros [a [a_in_join a_to_b]].\n    destruct a_in_join as [S [S1 S2]].\n    exists (fmap set f S). split.\n    + now (exists S).\n    + unfold transparent tcs. now (exists a).\n  - unfold transparent tcs.\n    intros [Sb [H1 H2]].\n    destruct H1 as [S [SS1 SS2]].\n    rewrite <- SS2 in H2. destruct H2 as [a [a1 a2]].\n    subst. exists a. split; auto. now (exists S).\nQed.\n\n#[export] Instance Monad_set : Monad set :=\n  {| mon_join_ret := @join_ret;\n     mon_join_fmap_ret := @join_fmap_ret;\n     mon_join_join := @join_join;\n  |}.\n\n(** * Set as an applicative functor *)\n(******************************************************************************)\n(*\nTODO: This isn't really necessary because it is inferred from the monad instance.\n *)\nSection set_applicative.\n  \n  Instance Pure_set : Pure set := @eq.\n\n  #[export] Instance Mult_set : Mult set :=\n    fun (A B : Type) (p : set A * set B) (v : A * B) =>\n      (fst p) (fst v) /\\ (snd p) (snd v).\n\n  Theorem app_mult_pure_set : forall (A B : Type) (a : A) (b : B),\n      mult set (pure set a, pure set b) = pure set (a, b).\n  Proof.\n    intros. unfold transparent tcs.\n    ext [a1 b1]. cbn. propext; now rewrite pair_equal_spec.\n  Qed.\n\n  Theorem app_pure_natural_set : forall (A B : Type) (f : A -> B) (x : A),\n      fmap set f (pure set x) = pure set (f x).\n  Proof.\n    intros. unfold transparent tcs. ext b.\n    propext; firstorder (now subst).\n  Qed.\n\n  Theorem app_mult_natural_set : forall (A B C D: Type) (f : A -> C) (g : B -> D) (x : set A) (y : set B),\n      mult set  (fmap set f x, fmap set g y) = fmap set (map_tensor f g) (mult set (x, y)).\n  Proof.\n    intros. unfold transparent tcs. ext [c d].\n    cbn. propext.\n    - intros [[a ?] [b ?]].\n      exists (a, b). firstorder (now subst).\n    - intros [[a b] rest]. cbn in *.\n      rewrite pair_equal_spec in rest.\n      split. exists a; tauto. exists b; tauto.\n  Qed.\n\n  Theorem app_assoc_set : forall (A B C : Type) (x : set A) (y : set B) (z : set C),\n      fmap set α (x ⊗ y ⊗ z) = x ⊗ (y ⊗ z).\n  Proof.\n    intros. ext [a [b c]]. unfold transparent tcs.\n    cbn. propext.\n    - intros [[[a1 b1] c1]]. cbn in *.\n      now preprocess.\n    - intros. now exists (a, b, c).\n  Qed.\n\n  Theorem app_unital_l_set : forall (A : Type) (x : set A),\n      fmap set left_unitor (pure set tt ⊗ x) = x.\n  Proof.\n    intros. ext a. unfold transparent tcs. cbn. propext.\n    + intros [[? a1] rest]. cbn in rest. now preprocess.\n    + exists (tt, a). easy.\n  Qed.\n\n  Theorem app_unital_r_set : forall (A : Type) (x : set A),\n      fmap set right_unitor (x ⊗ pure set tt) = x.\n  Proof.\n    intros. ext a. unfold transparent tcs. cbn. propext.\n    + intros [[? a1] rest]. cbn in rest. now preprocess.\n    + intros. exists (a, tt). easy.\n  Qed.\n\n  Instance Applicative_set : Applicative set :=\n    {| app_mult_pure := app_mult_pure_set;\n      app_pure_natural := app_pure_natural_set;\n      app_mult_natural := app_mult_natural_set;\n      app_assoc := app_assoc_set;\n      app_unital_l := app_unital_l_set;\n      app_unital_r := app_unital_r_set;\n    |}.\n\nEnd set_applicative.\n\nImport Tealeaves.Classes.Kleisli.Monad.\nImport Tealeaves.Classes.Monad.ToKleisli.\n\n(** ** [set]/[set] right module *)\n(******************************************************************************)\n#[export] Instance Bind_set: Bind set set := Monad.ToKleisli.Bind_join set.\n#[export] Instance KleisliMonad_list : Kleisli.Monad.Monad set := Kleisli_Monad set.\n\n(** ** Rewriting lemmas for <<bind>> *)\n(******************************************************************************)\nLemma bind_set_nil `{f : A -> set B} :\n  bind set f ∅ = ∅.\nProof.\n  solve_basic_set.\nQed.\n\nLemma bind_set_one `{f : A -> set B} (a : A) :\n  bind set f {{ a }} = f a.\nProof.\n  unfold_ops @Bind_set.\n  unfold_ops @Bind_join.\n  unfold compose; cbn.\n  rewrite fmap_set_one.\n  rewrite join_set_one.\n  reflexivity.\nQed.\n\nLemma bind_set_add `{f : A -> set B} {x y} :\n  bind set f (x ∪ y) = bind set f x ∪ bind set f y.\nProof.\n  solve_basic_set.\nQed.\n\n(** Since [bind] is defined tediously by composing <<join>> and\n    <<fmap>>, we give a characterization of <<set>>'s <<bind>> that is\n    easier to use. N.B. be mindful that this rewriting would have to\n    be done ~before~ calling <<unfold transparent tcs>>, otherwise <<bind set>>\n    will be unfolded to its definition first. *)\nLemma bind_set_spec : forall `(f : A -> set B) (s : set A) (b : B),\n    bind set f s b = exists (a : A), s a /\\ f a b.\nProof.\n  unfold_ops @Bind_set.\n  unfold_ops @Bind_join.\n  solve_basic_set.\nQed.\n\n#[export] Hint Rewrite @bind_set_nil @bind_set_one @bind_set_add : tea_set.\n\n(** ** <<bind>> is a monoid homomorphism *)\n(******************************************************************************)\n#[export] Instance Monmor_bind {A B f} : Monoid_Morphism (bind set f) :=\n  {| monmor_unit := @bind_set_nil A B f;\n     monmor_op := @bind_set_add A B f;\n  |}.\n", "meta": {"author": "dunnl", "repo": "tealeaves", "sha": "8dd6ba8acdd097f6e474ae2a1a9b10f5cc9ca65b", "save_path": "github-repos/coq/dunnl-tealeaves", "path": "github-repos/coq/dunnl-tealeaves/tealeaves-8dd6ba8acdd097f6e474ae2a1a9b10f5cc9ca65b/Tealeaves/Functors/Sets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6920132911509155}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type :=   Nil : lst | Cons : natural -> lst -> lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint len (len_arg0 : lst) : natural\n           := match len_arg0 with\n              | Nil => Zero\n              | Cons x y => Succ (len y)\n              end.\n\nFixpoint rotate (rotate_arg0 : natural) (rotate_arg1 : lst) : lst\n           := match rotate_arg0, rotate_arg1 with\n              | Zero, x => x\n              | Succ n, Nil => Nil\n              | Succ n, Cons y x => rotate n (append x (Cons y Nil))\n              end.\n\nLemma append_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 rotate_len_append : forall (x y : lst), rotate (len x) (append x y) = append y x.\nProof.\n   intro.\n   induction x.\n   - intros. simpl. rewrite append_nil. reflexivity.\n   - intros.  simpl. lfind.  rewrite IHx. lfind.  reflexivity. \nAdmitted.\n\nTheorem rotate_len : forall (x : lst), eq (rotate (len x) x) x.\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite rotate_len_append. 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_goal32_rotate_len_append_51_append_assoc/goal32.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6920132887095116}}
{"text": "From Hammer Require Import Hammer.\n\n\n\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 Export Relations_1.\n\nDefinition Complement (U:Type) (R:Relation U) : Relation U :=\nfun x y:U => ~ R x y.\n\nTheorem Rsym_imp_notRsym :\nforall (U:Type) (R:Relation U),\nSymmetric U R -> Symmetric U (Complement U R).\nProof. hammer_hook \"Relations_1_facts\" \"Relations_1_facts.Rsym_imp_notRsym\".  \nunfold Symmetric, Complement.\nintros U R H' x y H'0; red; intro H'1; apply H'0; auto with sets.\nQed.\n\nTheorem Equiv_from_preorder :\nforall (U:Type) (R:Relation U),\nPreorder U R -> Equivalence U (fun x y:U => R x y /\\ R y x).\nProof. hammer_hook \"Relations_1_facts\" \"Relations_1_facts.Equiv_from_preorder\".  \nintros U R H'; elim H'; intros H'0 H'1.\napply Definition_of_equivalence.\nred in H'0; auto 10 with sets.\n2: red; intros x y h; elim h; intros H'3 H'4; auto 10 with sets.\nred in H'1; red; auto 10 with sets.\nintros x y z h; elim h; intros H'3 H'4; clear h.\nintro h; elim h; intros H'5 H'6; clear h.\nsplit; apply H'1 with y; auto 10 with sets.\nQed.\nHint Resolve Equiv_from_preorder.\n\nTheorem Equiv_from_order :\nforall (U:Type) (R:Relation U),\nOrder U R -> Equivalence U (fun x y:U => R x y /\\ R y x).\nProof. hammer_hook \"Relations_1_facts\" \"Relations_1_facts.Equiv_from_order\".  \nintros U R H'; elim H'; auto 10 with sets.\nQed.\nHint Resolve Equiv_from_order.\n\nTheorem contains_is_preorder :\nforall U:Type, Preorder (Relation U) (contains U).\nProof. hammer_hook \"Relations_1_facts\" \"Relations_1_facts.contains_is_preorder\".  \nauto 10 with sets.\nQed.\nHint Resolve contains_is_preorder.\n\nTheorem same_relation_is_equivalence :\nforall U:Type, Equivalence (Relation U) (same_relation U).\nProof. hammer_hook \"Relations_1_facts\" \"Relations_1_facts.same_relation_is_equivalence\".  \nunfold same_relation at 1; auto 10 with sets.\nQed.\nHint Resolve same_relation_is_equivalence.\n\nTheorem cong_reflexive_same_relation :\nforall (U:Type) (R R':Relation U),\nsame_relation U R R' -> Reflexive U R -> Reflexive U R'.\nProof. hammer_hook \"Relations_1_facts\" \"Relations_1_facts.cong_reflexive_same_relation\".  \nunfold same_relation; intuition.\nQed.\n\nTheorem cong_symmetric_same_relation :\nforall (U:Type) (R R':Relation U),\nsame_relation U R R' -> Symmetric U R -> Symmetric U R'.\nProof. hammer_hook \"Relations_1_facts\" \"Relations_1_facts.cong_symmetric_same_relation\".  \ncompute; intros; elim H; intros; clear H;\napply (H3 y x (H0 x y (H2 x y H1))).\n\nQed.\n\nTheorem cong_antisymmetric_same_relation :\nforall (U:Type) (R R':Relation U),\nsame_relation U R R' -> Antisymmetric U R -> Antisymmetric U R'.\nProof. hammer_hook \"Relations_1_facts\" \"Relations_1_facts.cong_antisymmetric_same_relation\".  \ncompute; intros; elim H; intros; clear H;\napply (H0 x y (H3 x y H1) (H3 y x H2)).\n\nQed.\n\nTheorem cong_transitive_same_relation :\nforall (U:Type) (R R':Relation U),\nsame_relation U R R' -> Transitive U R -> Transitive U R'.\nProof. hammer_hook \"Relations_1_facts\" \"Relations_1_facts.cong_transitive_same_relation\".  \nintros U R R' H' H'0; red.\nelim H'.\nintros H'1 H'2 x y z H'3 H'4; apply H'2.\napply H'0 with y; auto with sets.\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/quick/Relations_1_facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.6919649143752521}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect.\nRequire Import ssrbool.\nRequire Import funs.\nRequire Import dataset.\nRequire Import ssrnat.\nRequire Import seq.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(* The basic theory of paths over a dataSet; this is essentially a   *)\n(* complement to seq.v.                                              *)\n(* Paths are non-empty sequences that obey a progression relation.   *)\n(* They are passed around in three parts : the head and tail of the  *)\n(* sequence, and a (boolean) predicate asserting the progression.    *)\n(* This is rarely embarrassing, as the first two are usually         *)\n(* implicit parameters inferred from the predicate, and it saves the *)\n(* hassle of constantly constructing and destructing a dependent     *)\n(* record. We allow duplicates; uniqueness, if desired (as is the    *)\n(* case for several geometric constructions), must be asserted       *)\n(* separately. We do provide shorthand, but for cycles only, because *)\n(* the equational properties of \"path\" and \"uniq\" are unfortunately  *)\n(* incompatible (esp. wrt \"cat\").                                    *)\n(*    We define similarly cycles, but in this case we allow the      *)\n(* empty sequence (which is a non-rooted empty cycle; by contrast,   *)\n(* the empty path from x is the one-item sequence containing only x) *)\n(*    We define notations for the common cases of function paths,    *)\n(* where the progress relation is actually a function. We also       *)\n(* define additional traversal/surgery operations, many of which     *)\n(* could have been in seq.v, but are here because they only really   *)\n(* are useful for sequences considered as paths :                    *)\n(*  - directed surgery : splitPl, splitP, splitPr are dependent      *)\n(*    predicates whose elimination splits a path x0:p at one of its  *)\n(*    elements (say x). The three variants differ as follows:        *)\n(*      - splitPl applies when x in in x0:p, generates two paths p1  *)\n(*        and p2, along with the equation x = (last x0 p), and       *)\n(*        replaces p with (cat p1 p2) in the goal (the patterned     *)\n(*        Elim can be used to select occurrences and generate an     *)\n(*        equation p = (cat p1 p2).                                  *)\n(*      - splitP applies when x is in p, and replaces p with         *)\n(*        (cat (add_last p1 x) p2), where x appears explicitly at    *)\n(*        the end of the left part.                                  *)\n(*      - splitPr similarly replaces p with (cat p1 (Adds x p2)),    *)\n(*        where appears explicitly at the right of the split, when x *)\n(*        is actually in p.                                          *)\n(*    The parts p1 and p2 are computed using index/take/drop. The    *)\n(*    splitP variant (but not the others) attempts to replace the    *)\n(*    explicit expressions for p1 and p2 by p1 and p2, respectively. *)\n(*    This is moderately useful, allows for defining other splitting *)\n(*    lemmas with conclusions of the form (split x p p1 p2), with    *)\n(*    other expressions for p1 and p2 that might be known to occur.  *)\n(*  - function trajectories: traject, and a looping predicate.       *)\n(*  - cycle surgery : arc extracts the sub-arc between two points    *)\n(*    (including the first, excluding the second). (arc p x y) is    *)\n(*    thus only meaningful if x and y are different points in p.     *)\n(*  - cycle traversal : next, prev                                   *)\n(*  - path order: mem2 checks whether two points belong to a         *)\n(*    and appear in order (i.e., (mem2 p x y) checks that y appears  *)\n(*    after an occurrence of x in p). This predicate a crucial part  *)\n(*    of the definition of the abstract Jordan property.             *)\n(*  - loop removal : shorten returns a shorter, duplicate-free path  *)\n(*    with the same endpoints as its argument. The related shortenP  *)\n(*    dependent predicate simultaneously substitutes a new path p',  *)\n(*    for (shorten e x p), (last x p') for (last x p), and generates *)\n(*    predicates asserting that p' is a duplicate-free subpath of p. *)\n(* Although these functions operate on the underlying sequences, we  *)\n(* provide a series of lemmas that define their interaction with the *)\n(* path and cycle predicates, e.g., the path_cat equation can be     *)\n(* used to split the path predicate after splitting the underlying   *)\n(* sequence.                                                         *)\n\nSection Paths.\n\nVariables (n0 : nat) (d : dataSet) (x0 : d).\n\nNotation dsub := (sub x0).\n\nSection Path.\n\nVariable e : rel d.\n\nFixpoint path (x : d) (p : seq d) {struct p} : bool :=\n  if p is Adds y p' then e x y && path y p' else true.\n\nLemma path_cat : forall x p1 p2,\n  path x (cat p1 p2) = path x p1 && path (last x p1) p2.\nProof.\nby move=> x p1 p2; elim: p1 x => [|y p1 Hrec] x //=; rewrite Hrec -!andbA.\nQed.\n\nInductive split (x : d) : seq d -> seq d -> seq d -> Set :=\n  Split : forall p1 p2 : seq d, split x (cat (add_last p1 x) p2) p1 p2.\n\nLemma splitP : forall (p : seq d) x, p x ->\n   let i := index x p in split x p (take i p) (drop (S i) p).\nProof.\nmove=> p x Hx i; have := esym (cat_take_drop i p).\nhave Hi := Hx; rewrite -index_mem -/i in Hi; rewrite (drop_sub x Hi) -cat_add_last.\nby rewrite {2}/i (sub_index x Hx) => Dp; rewrite {1}Dp.\nQed.\n\nInductive splitl (x1 x : d) : seq d -> Set :=\n  Splitl : forall p1 p2 : seq d, last x1 p1 = x -> splitl x1 x (cat p1 p2).\n\nLemma splitPl : forall x1 p x, Adds x1 p x -> splitl x1 x p.\nProof.\nmove=> x1 p x; rewrite /= /setU1.\ncase: (x1 =P x) => [<-|_]; first by rewrite -(cat0s p).\ncase/splitP; split; exact: last_add_last.\nQed.\n\nInductive splitr (x : d) : seq d -> Set :=\n  Splitr : forall p1 p2 : seq d, splitr x (cat p1 (Adds x p2)).\n\nLemma splitPr : forall (p : seq d) x, p x -> splitr x p.\nProof. by move=> p x H; case (splitP H); move=> p1 p2; rewrite cat_add_last. Qed.\n\nLemma pathPx : forall x p,\n reflect (forall i, i < size p -> e (dsub (Adds x p) i) (dsub p i)) (path x p).\nProof.\nmove=> x p; elim: p x => [|y p Hrec] x /=; first by left.\napply: (iffP andP) => [[Hxy Hp]|Hp].\n  move=> [|i] Hi //; exact: Hrec _ Hp i Hi.\nsplit; first exact: Hp 0 (leq0n (size p)).\napply/(Hrec y) => i; exact: Hp (S i).\nQed.\n\nFixpoint next_at (x y0 y : d) (p : seq d) {struct p} : d :=\n  match p with\n  | Seq0 => if x =d y then y0 else x\n  | Adds y' p' => if x =d y then y' else next_at x y0 y' p'\n  end.\n\nDefinition next p x := if p is Adds y p' then next_at x y y p' else x.\n\nFixpoint prev_at (x y0 y : d) (p : seq d) {struct p} : d :=\n  match p with\n  | Seq0 => if x =d y0 then y else x\n  | Adds y' p' => if x =d y' then y else prev_at x y0 y' p'\n  end.\n\nDefinition prev p x := if p is Adds y p' then prev_at x y y p' else x.\n\nLemma next_sub : forall p x,\n  next p x = if p x then if p is Adds y p' then sub y p' (index x p) else x else x.\nProof.\nmove=> [|y0 p] x //=; elim: p {2 3 5}y0 => [|y' p Hrec] y /=;\n  by rewrite /setU1 -(eqd_sym x); case (x =d y); try exact: Hrec.\nQed.\n\nLemma prev_sub : forall p x,\n  prev p x = if p x then if p is Adds y p' then sub y p (index x p') else x else x.\nProof.\nmove=> [|y0 p] x //=; rewrite /setU1 eqd_sym orbC.\nelim: p {2 5}y0 => [|y' p Hrec] y; rewrite /= /setU1 eqd_sym //.\ncase (y' =d x); simpl; auto.\nQed.\n\nLemma mem_next : forall (p : seq d) x, p (next p x) = p x.\nProof.\nmove=> p x; rewrite next_sub; case Hpx: (p x) => [|] //.\ncase: p (index x p) Hpx => [|y0 p'] //= i _; rewrite /setU1.\ncase: (ltnP i (size p')) => Hi; first by rewrite (mem_sub y0 Hi) orbT.\nby rewrite (sub_default y0 Hi) set11.\nQed.\n\nLemma mem_prev : forall (p : seq d) x, p (prev p x) = p x.\nProof.\nmove=> p x; rewrite prev_sub; case Hpx: (p x) => [|] //.\ncase: p Hpx => [|y0 p'] Hpx //.\nby apply mem_sub; rewrite /= ltnS index_size.\nQed.\n\nDefinition cycle p := if p is Adds x p' then path x (add_last p' x) else true.\n\n(* ucycleb is the boolean predicate, but ucycle is defined as a Prop *)\n(* so that it can be used as a coercion target. *)\nDefinition ucycleb p := cycle p && uniq p.\nDefinition ucycle p : Prop := cycle p && uniq p.\n\n(* Projections, used for creating local lemmas. *)\nLemma ucycle_cycle : forall p, ucycle p -> cycle p.\nProof. by move=> p; case/andP. Qed.\n\nLemma ucycle_uniq : forall p, ucycle p -> uniq p.\nProof. by move=> p; case/andP. Qed.\n\nLemma cycle_path : forall p, cycle p = path (last x0 p) p.\nProof. by move=> [|x p] //=; rewrite -cats1 path_cat /= andbT andbC. Qed.\n\nLemma next_cycle : forall p x, cycle p -> p x -> e x (next p x).\nProof.\nmove=> [|y0 p] //= x.\nelim: p {1 3 5}y0 => [|y' p Hrec] y /=; rewrite eqd_sym /setU1.\n  by rewrite andbT orbF=> Hy Dy; rewrite Dy -(eqP Dy).\nmove/andP=> [Hy Hp]; case: (y =P x) => [<-|_] //; exact: Hrec.\nQed.\n\nLemma prev_cycle : forall p x, cycle p -> p x -> e (prev p x) x.\nProof.\nmove=> [|y0 p] //= x; rewrite /setU1 orbC.\nelim: p {1 5}y0 => [|y' p Hrec] y /=; rewrite /= ?(eqd_sym x) /setU1.\n  by rewrite andbT=> Hy Dy; rewrite Dy -(eqP Dy).\nmove/andP=> [Hy Hp]; case: (y' =P x) => [<-|_] //; exact: Hrec.\nQed.\n\nLemma cycle_rot : forall p, cycle (rot n0 p) = cycle p.\nProof.\ncase: (n0) => [|n] [|y0 p] //=; first by rewrite /rot /= cats0.\nrewrite /rot /= -{3}(cat_take_drop n p) -cats1 -catA path_cat.\ncase: (drop n p) => [|z0 q]; rewrite /= -cats1 !path_cat /= !andbT andbC //.\nby rewrite last_cat; repeat BoolCongr.\nQed.\n\nLemma ucycle_rot : forall p, ucycle (rot n0 p) = ucycle p.\nProof. by move=> *; rewrite /ucycle uniq_rot cycle_rot. Qed.\n\nLemma cycle_rotr : forall p, cycle (rotr n0 p) = cycle p.\nProof. by move=> p; rewrite -cycle_rot rot_rotr. Qed.\n\nLemma ucycle_rotr : forall p, ucycle (rotr n0 p) = ucycle p.\nProof. by move=> *; rewrite /ucycle uniq_rotr cycle_rotr. Qed.\n\n(* The \"appears no later\" partial preorder defined by a path. *)\n\nDefinition mem2 (p : seq d) x y : bool := drop (index x p) p y.\n\nLemma mem2l : forall p x y, mem2 p x y -> p x.\nProof.\nmove=> p x y; rewrite /mem2 -!index_mem size_drop; move=> Hxy.\nby rewrite ltn_lt0sub -(ltnSpred Hxy) ltnS leq0n.\nQed.\n\nLemma mem2lf : forall (p : seq d) x, p x = false -> forall y, mem2 p x y = false.\nProof. move=> p x Hx y; apply/idP => [Hp]; case/idP: Hx; apply: mem2l Hp. Qed.\n\nLemma mem2r : forall p x y, mem2 p x y -> p y.\nProof.\nrewrite /mem2; move=> p x y Hxy.\nby rewrite -(cat_take_drop (index x p) p) mem_cat /setU Hxy orbT.\nQed.\n\nLemma mem2rf : forall (p : seq d) y, p y = false -> forall x, mem2 p x y = false.\nProof. move=> p y Hy x; apply/idP => [Hp]; case/idP: Hy; apply: mem2r Hp. Qed.\n\nLemma mem2_cat : forall p1 p2 x y,\n mem2 (cat p1 p2) x y = mem2 p1 x y || mem2 p2 x y || p1 x && p2 y.\nProof.\nmove=> p1 p2 x y; rewrite {1}/mem2 index_cat drop_cat; case Hp1x: (p1 x).\n  rewrite index_mem Hp1x mem_cat /setU /= -orbA.\n  by case Hp2: (p2 y); [ rewrite !orbT // | rewrite (mem2rf Hp2) ].\nby rewrite ltnNge leq_addr /= orbF subn_addr (mem2lf Hp1x).\nQed.\n\nLemma mem2_splice : forall p1 p3 x y p2,\n  mem2 (cat p1 p3) x y -> mem2 (cat p1 (cat p2 p3)) x y.\nProof.\nmove=> p1 p3 x y p2 Hxy; move: Hxy; rewrite !mem2_cat mem_cat /setU.\ncase: (mem2 p1 x y) (mem2 p3 x y) => [|] // [|] /=; first by rewrite orbT.\nby case: (p1 x) => [|] //= Hy; rewrite Hy !orbT.\nQed.\n\nLemma mem2_splice1 : forall p1 p3 x y z,\n  mem2 (cat p1 p3) x y -> mem2 (cat p1 (Adds z p3)) x y.\nProof. move=> p1 p3 x y z; apply: (mem2_splice (seq1 z)). Qed.\n\nLemma mem2_adds : forall x p y,\n  mem2 (Adds x p) y =1 (if x =d y then setU1 x p else mem2 p y).\nProof. by move=> x p y z; rewrite {1}/mem2 /= eqd_sym; case (x =d y). Qed.\n\nLemma mem2_last : forall y0 p x, mem2 (Adds y0 p) x (last y0 p) = Adds y0 p x.\nProof.\nmove=> y0 p x; apply/idP/idP; first by apply mem2l.\nrewrite -index_mem /mem2; move: (index x (Adds y0 p)) => i Hi.\nby rewrite lastI drop_add_last ?size_belast // mem_add_last /= setU11.\nQed.\n\nLemma mem2l_cat : forall (p1 : seq d) x, p1 x = false ->\n  forall p2, mem2 (cat p1 p2) x =1 mem2 p2 x.\nProof. by move=> p1 x Hx p2 y; rewrite mem2_cat (Hx) (mem2lf Hx) /= orbF. Qed.\n\nLemma mem2r_cat : forall (p2 : seq d) y, p2 y = false ->\n   forall p1 x, mem2 (cat p1 p2) x y = mem2 p1 x y.\nProof. by move=> p2 y Hy p1 x; rewrite mem2_cat (Hy) (mem2rf Hy) andbF !orbF. Qed.\n\nLemma mem2lr_splice : forall (p2 : seq d) x y, p2 x = false -> p2 y = false ->\n  forall p1 p3, mem2 (cat (cat p1 p2) p3) x y = mem2 (cat p1 p3) x y.\nProof.\nmove=> p2 x y Hx Hy p1 p3.\nby rewrite !mem2_cat !mem_cat /setU (Hx) Hy (mem2lf Hx) !andbF !orbF.\nQed.\n\nInductive split2r (x y : d) : seq d -> Set :=\n  Split2l : forall p1 p2, Adds x p2 y -> split2r x y (cat p1 (Adds x p2)).\n\nLemma splitP2r : forall p x y, mem2 p x y -> split2r x y p.\nProof.\nmove=> p x y Hxy; have Hx := mem2l Hxy.\nhave Hi := Hx; rewrite -index_mem in Hi.\nmove: Hxy; rewrite /mem2 (drop_sub x Hi) (sub_index x Hx).\nby case (splitP Hx); move=> p1 p2; rewrite cat_add_last; split.\nQed.\n\nFixpoint shorten (x : d) (p : seq d) {struct p} : seq d :=\n  if p is Adds y p' then\n    if p x then shorten x p' else Adds y (shorten y p')\n  else seq0.\n\nInductive shorten_spec (x : d) (p : seq d) : d -> seq d -> Set :=\n   ShortenSpec : forall p', path x p' -> uniq (Adds x p') -> sub_set p' p ->\n                 shorten_spec x p (last x p') p'.\n\nLemma shortenP : forall x p, path x p -> shorten_spec x p (last x p) (shorten x p).\nProof.\nmove=> x p Hp; elim: p x {1 2 5}x Hp (setU11 x p) => [|y2 p Hrec] y0 y1.\n  by rewrite /setU1 orbF; move=> _ Dy1; rewrite (eqP Dy1); repeat split; move.\nrewrite /setU1 /= orbC; case/andP=> [Hy12 Hp].\ncase Hpy0: (setU1 y2 p y0).\ncase: (Hrec _ _ Hp Hpy0) => [p' Hp' Up' Hp'p] _; split; auto; simpl.\n  move=> z; move/Hp'p; apply: setU1r.\ncase: (Hrec _ _ Hp (setU11 y2 p)) => [p' Hp' Up' Hp'p] Dy1.\nhave Hp'p2: sub_set (setU1 y2 p') (setU1 y2 p).\n  move=> z; rewrite /= /setU1; case: (y2 =d z) => [|] //; apply: Hp'p.\nrewrite -[last y2 p']/(last y0 (Adds y2 p')); split; auto.\n  by rewrite -(eqP Dy1) /= Hy12.\nby simpl; case Hy0: (setU1 y2 p' y0); first by rewrite (Hp'p2 _ Hy0) in Hpy0.\nQed.\n\nEnd Path.\n\nLemma eq_path : forall e e', e =2 e' -> path e =2 path e'.\nProof.\nby move=> e e' Ee x p; elim: p x => [|y p Hrec] x //=; rewrite Ee Hrec.\nQed.\n\nLemma sub_path : forall e e', sub_rel e e' ->\n  forall x p, path e x p -> path e' x p.\nProof.\nmove=> e e' He x p; elim: p x => [|y p Hrec] x //=.\nby case/andP=> [Hx Hp]; rewrite (He _ _ Hx) (Hrec _ Hp).\nQed.\n\nEnd Paths.\n\nNotation \"'pathP' x0\" := (pathPx x0 _ _ _) (at level 10, x0 at level 8).\n\nNotation \"'fpath' f\" := (path (eqdf f)) (at level 10, f at level 8).\n\nNotation \"'fcycle' f\" := (cycle (eqdf f)) (at level 10, f at level 8).\n\nNotation \"'ufcycle' f\" := (ucycle (eqdf f)) (at level 10, f at level 8).\n\nPrenex Implicits path next prev cycle ucycle mem2.\n\nSection Trajectory.\n\nVariables (d : dataSet) (f : d -> d).\n\nFixpoint traject (x : d) (n : nat) {struct n} : seq d :=\n  if n is S n' then Adds x (traject (f x) n') else seq0.\n\nLemma size_traject : forall x n, size (traject x n) = n.\nProof. by move=> x n; elim: n x => [|n Hrec] x //=; NatCongr. Qed.\n\nLemma last_traject : forall x n, last x (traject (f x) n) = iter n f x.\nProof. by move=> x n; elim: n x => [|n Hrec] x //; rewrite -iter_f -Hrec. Qed.\n\nLemma fpathPx : forall x p, reflect (exists n, traject (f x) n = p) (fpath f x p).\nProof.\nmove=> x p; elim: p x => [|y p Hrec] x; first by left; exists 0.\nrewrite /= andbC; case: {Hrec}(Hrec y) => Hrec.\n  apply: (iffP eqP); first by case: Hrec => [n <-] <-; exists (S n).\n  by case=> [] [|n] // [Dp].\nby right; move=> [[|n] Dp] //; case: Hrec; exists n; case: Dp => <- <-.\nQed.\n\nLemma fpath_traject : forall x n, fpath f x (traject (f x) n).\nProof. by move=> x n; apply/(fpathPx x _); exists n. Qed.\n\nDefinition looping x n := traject x n (iter n f x).\n\nLemma loopingPx : forall x n,\n  reflect (forall m, traject x n (iter m f x)) (looping x n).\nProof.\nmove=> x n; apply introP; last by move=> Hn Hn'; rewrite /looping Hn' in Hn.\ncase: n => [|n] Hn //; elim=> [|m Hrec]; first by apply: setU11.\nmove: (fpath_traject x n) Hn; rewrite /looping -!f_iter -last_traject /=.\nrewrite /= in Hrec; case/splitPl: Hrec; move: (iter m f x) => y p1 p2 Ep1.\nrewrite path_cat last_cat Ep1; case: p2 => [|z p2] //; case/and3P=> [_ Dy _] _.\nby rewrite /setU1 mem_cat /setU /= (eqP Dy) /= setU11 !orbT.\nQed.\n\nLemma sub_traject : forall i n, i < n ->\n  forall x, sub x (traject x n) i = iter i f x.\nProof.\nmove=> i n Hi x; elim: n {2 3}x i Hi => [|n Hrec] y [|i] Hi //=.\nby rewrite Hrec ?iter_f.\nQed.\n\nLemma trajectPx : forall x n y,\n  reflect (exists2 i, i < n & iter i f x = y) (traject x n y).\nProof.\nmove=> x n y; elim: n x => [|n Hrec] x; first by right; case.\n  rewrite /= /setU1 orbC; case: {Hrec}(Hrec (f x)) => Hrec.\n  by left; case: Hrec => [i Hi <-]; exists (S i); last by rewrite iter_f.\napply: (iffP eqP); first by exists 0; first by rewrite ltnNge.\nby move=> [[|i] Hi Dy] //; case Hrec; exists i; last by rewrite iter_f.\nQed.\n\nLemma looping_uniq : forall x n, uniq (traject x (S n)) = negb (looping x n).\nProof.\nmove=> x n; rewrite /looping; elim: n x => [|n Hrec] x //.\nrewrite -iter_f {2}[S]lock /= -lock {}Hrec -negb_orb /setU1; BoolCongr.\nset y := iter n f (f x); case (trajectPx (f x) n y); first by rewrite !orbT.\nrewrite !orbF; move=> Hy; apply/idP/eqP => [Hx|Dy].\n  case/trajectPx: Hx => [m Hm Dx].\n  have Hx': looping x (S m) by rewrite /looping -iter_f Dx /= setU11.\n  case/trajectPx: (loopingPx _ _ Hx' (S n)); rewrite -iter_f -/y.\n  move=> [|i] Hi //; rewrite -iter_f; move=> Dy.\n  by case: Hy; exists i; first by exact (leq_trans Hi Hm).\nby rewrite {2}Dy /(y) -last_traject /= mem_lastU.\nQed.\n\nEnd Trajectory.\n\nNotation fpathP := (fpathPx _ _ _).\nNotation loopingP := (loopingPx _ _ _).\nNotation trajectP := (trajectPx _ _ _ _).\n\nPrenex Implicits traject.\n\nSection UniqCycle.\n\nVariables (n0 : nat) (d : dataSet) (e : rel d) (p : seq d).\n\nHypothesis Up : uniq p.\n\nLemma prev_next : forall x, prev p (next p x) = x.\nProof.\nmove=> x; rewrite prev_sub mem_next next_sub.\ncase Hpx: (p x) => [|] //; case Dp: p Up Hpx => [|y p'] //.\nrewrite -(Dp) {1}Dp /=; move/andP=> [Hpy Hp'] Hx.\nset i := index x p; rewrite -(sub_index y Hx) -/i; congr (sub y).\nrewrite -index_mem -/i Dp /= ltnS leq_eqVlt in Hx.\ncase/setU1P: Hx => [Di|Hi]; last by apply: index_uniq.\nrewrite Di (sub_default y (leqnn _)).\nrewrite -index_mem -leqNgt in Hpy.\nby apply: eqP; rewrite eqn_leq Hpy /index find_size.\nQed.\n\nLemma next_prev : forall x, next p (prev p x) = x.\nProof.\nmove=> x; rewrite next_sub mem_prev prev_sub.\ncase Hpx: (p x) => [|] //; case Dp: p Up Hpx => [|y p'] //.\nrewrite -(Dp); move=> Hp Hpx; set i := index x p'.\nhave Hi: i < size p by rewrite Dp /= ltnS /i /index find_size.\nrewrite (index_uniq y Hi Hp); case Hx: (p' x); first by apply: sub_index.\nrewrite Dp /= /setU1 (Hx) orbF in Hpx; rewrite (eqP Hpx).\nrewrite -index_mem ltnNge -/i in Hx; exact (sub_default _ (negbEf Hx)).\nQed.\n\nLemma cycle_next : fcycle (next p) p.\nProof.\ncase: p Up => [|x p'] Up' //; apply/(pathP x) => [i Hi].\nrewrite size_add_last in Hi.\nrewrite -cats1 -cat_adds sub_cat /= (Hi) /eqdf next_sub mem_sub //.\nrewrite index_uniq // sub_cat /=; rewrite ltnS leq_eqVlt in Hi.\ncase/setU1P: Hi => [Di|Hi]; last by rewrite Hi set11.\nby rewrite Di ltnn subnn sub_default ?leqnn /= ?set11.\nQed.\n\nLemma cycle_prev : cycle (fun x y => x =d (prev p y)) p.\nProof.\napply: etrans cycle_next; symmetry; case Dp: p => [|x p'] //.\napply: eq_path; rewrite -Dp; exact (monic2_eqd prev_next next_prev).\nQed.\n\nLemma cycle_from_next : (forall x, p x -> e x (next p x)) -> cycle e p.\nProof.\nmove=> He; case Dp: p cycle_next => [|x p'] //; rewrite -(Dp) !(cycle_path x).\nhave Hx: p (last x p) by rewrite Dp /= mem_lastU.\nmove: (next p) He {Hx}(He _ Hx) => np.\nelim: (p) {x p' Dp}(last x p) => [|y p' Hrec] x He Hx //=.\ncase/andP=> [Dy Hp']; rewrite -{1}(eqP Dy) Hx /=.\napply: Hrec Hp' => [z Hz|]; apply: He; [exact: setU1r | exact: setU11].\nQed.\n\nLemma cycle_from_prev : (forall x, p x -> e (prev p x) x) -> cycle e p.\nProof.\nmove=> He; apply: cycle_from_next => [x Hx].\nby rewrite -{1}[x]prev_next He ?mem_next.\nQed.\n\nLemma next_rot : next (rot n0 p) =1 next p.\nProof.\nmove=> x; have Hp := cycle_next; rewrite -(cycle_rot n0) in Hp.\ncase Hx: (p x); last by rewrite !next_sub mem_rot Hx.\nrewrite -(mem_rot n0) in Hx; exact (esym (eqP (next_cycle Hp Hx))).\nQed.\n\nLemma prev_rot : prev (rot n0 p) =1 prev p.\nProof.\nmove=> x; have Hp := cycle_prev; rewrite -(cycle_rot n0) in Hp.\ncase Hx: (p x); last by rewrite !prev_sub mem_rot Hx.\nrewrite -(mem_rot n0) in Hx; exact (eqP (prev_cycle Hp Hx)).\nQed.\n\nEnd UniqCycle.\n\nSection UniqRotrCycle.\n\nVariables (n0 : nat) (d : dataSet) (p : seq d).\n\nHypothesis Up : uniq p.\n\nLemma next_rotr : next (rotr n0 p) =1 next p. Proof. exact: next_rot. Qed.\n\nLemma prev_rotr : prev (rotr n0 p) =1 prev p. Proof. exact: prev_rot. Qed.\n\nEnd UniqRotrCycle.\n\nSection UniqCycleRev.\n\nVariable d : dataSet.\n\nLemma prev_rev : forall p : seq d, uniq p -> prev (rev p) =1 next p.\nProof.\nmove=> p Up x; case Hx: (p x); last by rewrite next_sub prev_sub mem_rev Hx.\ncase/rot_to: Hx (Up) => [i p' Dp] Urp; rewrite -uniq_rev in Urp.\nrewrite -(prev_rotr i Urp); do 2 rewrite -(prev_rotr 1) ?uniq_rotr //.\nrewrite -rev_rot -(next_rot i Up) {i p Up Urp}Dp.\ncase: p' => [|y p'] //; rewrite !rev_adds rotr1_add_last /= set11.\nby rewrite -add_last_adds rotr1_add_last /= set11.\nQed.\n\nLemma next_rev : forall p : seq d, uniq p -> next (rev p) =1 prev p.\nProof. by move=> p Up x; rewrite -{2}[p]rev_rev prev_rev // uniq_rev. Qed.\n\nEnd UniqCycleRev.\n\nSection MapPath.\n\nVariables (d d' : dataSet) (h : d' -> d) (e : rel d) (e' : rel d').\n\nDefinition rel_base (b : set d) :=\n  forall x' y', negb (b (h x')) -> e (h x') (h y') = e' x' y'.\n\nLemma path_maps : forall b x' p',\n   rel_base b -> negb (has (comp b h) (belast x' p')) ->\n path e (h x') (maps h p') = path e' x' p'.\nProof.\nmove=> b x' p' Hb; elim: p' x' => [|y' p' Hrec] x' //=; move/norP=> [Hbx Hbp].\ncongr andb; auto.\nQed.\n\nHypothesis Hh : injective h.\n\nLemma mem2_maps : forall x' y' p', mem2 (maps h p') (h x') (h y') = mem2 p' x' y'.\nProof. by move=> *; rewrite {1}/mem2 (index_maps Hh) -maps_drop mem_maps. Qed.\n\nLemma next_maps : forall p, uniq p ->\n  forall x, next (maps h p) (h x) = h (next p x).\nProof.\nmove=> p Up x; case Hx: (p x); last by rewrite !next_sub (mem_maps Hh) Hx.\ncase/rot_to: Hx => [i p' Dp].\nrewrite -(next_rot i Up); rewrite -(uniq_maps Hh) in Up.\nrewrite -(next_rot i Up) -maps_rot {i p Up}Dp /=.\nby case: p' => [|y p] //=; rewrite !set11.\nQed.\n\nLemma prev_maps : forall p, uniq p ->\n  forall x, prev (maps h p) (h x) = h (prev p x).\nProof.\nmove=> p Up x; rewrite -{1}[x](next_prev Up) -(next_maps Up).\nby rewrite prev_next ?uniq_maps.\nQed.\n\nEnd MapPath.\n\nDefinition fun_base d d' h f f' := @rel_base d d' h (eqdf f) (eqdf f').\n\nSection CycleArc.\n\nVariable d : dataSet.\n\nDefinition arc (p : seq d) x y :=\n  let px := rot (index x p) p in take (index y px) px.\n\nLemma arc_rot : forall p x, uniq p -> p x -> forall i, arc (rot i p) x =1 arc p x.\nProof.\nmove=> p x Up Hx i y; congr (fun q => take (index y q) q); move: Up Hx {y}.\nrewrite -{1 2 5 6}(cat_take_drop i p) /rot uniq_cat; case/and3P=> [_ Hp _].\nrewrite !drop_cat !take_cat !index_cat mem_cat /setU orbC.\ncase Hx: (drop i p x) => [|] /=.\n  move=> _; rewrite (negbE (hasPn Hp _ Hx)).\n  by rewrite index_mem Hx ltnNge leq_addr /= subn_addr catA.\nby move=> Hx'; rewrite Hx' index_mem Hx' ltnNge leq_addr /= subn_addr catA.\nQed.\n\nLemma left_arc : forall x y p1 p2, let p := Adds x (cat p1 (Adds y p2)) in\n  uniq p -> arc p x y = Adds x p1.\nProof.\nmove=> x y p1 p2 p Up; rewrite /arc {1}/p /= set11 rot0.\nmove: Up; rewrite /p -cat_adds uniq_cat index_cat; move: (Adds x p1) => xp1.\nrewrite /= negb_orb -!andbA; case/and3P=> [_ Hy _].\nby rewrite (negbE Hy) set11 addn0 take_size_cat.\nQed.\n\nLemma right_arc : forall x y p1 p2, let p := Adds x (cat p1 (Adds y p2)) in\n   uniq p -> arc p y x = Adds y p2.\nProof.\nmove=> x y p1 p2 p Up; set n := size (Adds x p1); rewrite -(arc_rot Up _ n).\n  move: Up; rewrite -(uniq_rot n) /p -cat_adds /n rot_size_cat.\n  by move=> *; rewrite /= left_arc.\nby rewrite /p -cat_adds mem_cat /setU /= setU11 orbT.\nQed.\n\nInductive rot_to_arc_spec (p : seq d) (x y : d) : Set :=\n    RotToArcSpec : forall i p1 p2,\n      Adds x p1 = arc p x y ->\n      Adds y p2 = arc p y x ->\n      rot i p = Adds x (cat p1 (Adds y p2)) ->\n    rot_to_arc_spec p x y.\n\nLemma rot_to_arc : forall p x y,\n uniq p -> p x -> p y -> negb (x =d y) -> rot_to_arc_spec p x y.\nProof.\nmove=> p x y Up Hx Hy Hxy; case: (rot_to Hx) (Hy) (Up) => [i p' Dp] Hy'.\nrewrite -(mem_rot i) (Dp) /= /setU1 (negbE Hxy) in Hy'; rewrite -(uniq_rot i) Dp.\ncase/splitPr: p' / Hy' Dp => [p1 p2] Dp Up'; exists i p1 p2; auto.\n  by rewrite -(arc_rot Up Hx i) Dp (left_arc Up').\nby rewrite -(arc_rot Up Hy i) Dp (right_arc Up').\nQed.\n\nEnd CycleArc.\n\nPrenex Implicits arc.\n\nUnset Implicit Arguments.\n\n", "meta": {"author": "tangentforks", "repo": "FourColorTheorem", "sha": "eb30720f9e773fdcbf13dc6c61fdb245587cf401", "save_path": "github-repos/coq/tangentforks-FourColorTheorem", "path": "github-repos/coq/tangentforks-FourColorTheorem/FourColorTheorem-eb30720f9e773fdcbf13dc6c61fdb245587cf401/paths.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6919649066349984}}
{"text": "Require Import Classical.\nRequire Import ClassicalChoice.\nRequire Import FunctionalExtensionality.\nRequire Import PropExtensionality.\nRequire Import Description.\nRequire Import ClassicalDescription.\n\n\n\nLemma set_ext {E} :\n  forall (A B : E -> Prop), (forall x, A x <-> B x) -> A = B.\nProof.\n  intros A B. intro H.\n  extensionality x. apply propositional_extensionality.\n  destruct (H x). split ; assumption.\nQed.\n\nDefinition compl {E} (A : E -> Prop) := (fun x => ~ (A x)).\n\nDefinition subset {E} (A B : E -> Prop) := forall x, (B x) -> (A x).\nCheck subset.\n\nLemma compl_decreasing {E} : forall X Y : E -> Prop, subset X Y -> subset (compl Y) (compl X).\nProof.\n  firstorder.\nQed.\n(*intros X Y. intro H. unfold subset in *. unfold compl. intro x. specialize (H x). tauto. *)\n\nDefinition union {E} (A B : E -> Prop) := (fun x => (A x) \\/ (B x)).\nDefinition union_gen {E} (X : (E -> Prop) -> Prop) := (fun x => exists A, X A /\\ A x).\nCheck union_gen. \n\n\nDefinition set_of_subsets {E} (A : E -> Prop) := (fun x => (subset A x)).\nDefinition image_set {E F} (f : E -> F) (A : E -> Prop) := (fun y => (exists x, (A x) /\\ (f x) = y)).\nDefinition pre_image {E F} (f : E -> F) (B : F -> Prop) := (fun x => B (f x)).\n\n\n\nLemma image_increasing {E F} : forall X Y : E -> Prop, forall f : E -> F, subset X Y -> subset (image_set f X) (image_set f Y).\nProof.\n  firstorder.\nQed.\n\nDefinition inj {E F} (f : E -> F) := forall x y, f x = f y -> x = y.\nDefinition surj {E F} (f : E -> F) := forall y, exists x, f x = y.\nDefinition bij {E F} (f : E -> F)  := (inj f) /\\ (surj f).\n\nDefinition is_recip {E F} (f : E -> F) (g : F -> E) :=\n  (forall x, (g (f x)) = x) /\\ (forall y, (f (g y)) = y).\n\nLemma bij_exists_recip {E F} (f : E -> F) :\n  (bij f) -> exists (g : F -> E), (is_recip f g).\nProof.\n  intro H. unfold bij in H. destruct H as [H1 H2].\n  unfold surj in H2.\n  assert (exists g, forall x, x = f (g x)).\n  - apply unique_choice with (R := fun x gx => x = f gx).\n    intro y. destruct (H2 y). exists x. unfold unique. split.\n    + symmetry ; assumption.\n    + intro x'. intro H0. symmetry in H.\n      unfold inj in H1. destruct (H1 x x').\n      * rewrite <- H. rewrite H0. reflexivity.\n      * reflexivity.\n  - destruct H as [g0]. exists g0.\n    unfold is_recip. split.\n    + intro x. unfold inj in H1. destruct (H1 x (g0 (f x))).\n      * rewrite <- H. reflexivity.\n      * reflexivity.\n    + intro y. symmetry. rewrite <- H. reflexivity.\nQed.\n\nLemma is_in_image {E F} (f : E -> F) (A : E -> Prop) (x : E) : (A x) -> (image_set f A) (f x).\nProof.\n  intro H. unfold image_set. exists x. split ; [assumption |reflexivity].\nQed.\n\nLemma is_in_image_all {E F} (f : E -> F) (x : E) : image_set f (fun _ => True) (f x).\nProof.\n  apply is_in_image. constructor.\nQed.\n\n\nDefinition is_fixpoint {E} (f : (E -> Prop) -> (E -> Prop)) (A : E -> Prop) := f A = A.\nDefinition is_increasing {E} (f : (E -> Prop) -> (E -> Prop)) := forall X Y, subset X Y -> subset (f X) (f Y).\nCheck is_increasing.\n\nLemma union_increasing {E} (f : (E -> Prop) -> (E -> Prop)) :\n  is_increasing f -> forall A, subset (f (union_gen A)) (union_gen (image_set f A)).\nProof.\n  intro H_inc. intro A. intro x. intro Hx.\n  unfold union_gen in *.\n  destruct Hx as [A0 [H1 H2]]. unfold image_set in H1. destruct H1 as [A1 [ H3 H4]].\n  apply (H_inc _  A1).\n  - intro x'. intro H0.\n    exists A1. split ; assumption.\n  - rewrite H4 ; assumption.\nQed.\n\n\nLemma proj1_inj : forall (E : Type) (P : E -> Prop) (x y : sig P), proj1_sig x = proj1_sig y -> x = y.\nProof.\n  intros E P x y. intro H_eq.\n  destruct x as [x Px]. destruct y as [y Py]. simpl in H_eq.\n  subst. f_equal. apply proof_irrelevance.\nQed.\n\n\nLemma bij_on_image {E F : Type} (h : E -> F)  :\n  (inj h) -> bij (fun x => exist (image_set h (fun _ => True)) (h x) (is_in_image_all h x)).\nProof.\n  intro H_inj. unfold bij. split.\n  - unfold inj.\n    intros x y H_eq.\n    injection H_eq. apply H_inj.\n  - unfold surj. intro y. destruct y as [y Py]. destruct Py as [x Hx].\n    exists x. apply proj1_inj. simpl. apply Hx.\nQed.\n\n\nDefinition potential_fixpoint {E} (f : (E -> Prop) -> (E -> Prop)) := union_gen (fun A => (subset (f A) A)).\n\nLemma first_inclusion {E} (f : (E -> Prop) -> ( E -> Prop)) :\n  (is_increasing f) -> subset (f (potential_fixpoint f)) (potential_fixpoint f).\nProof.\n  intros H_inc x H.\n  unfold potential_fixpoint in *. apply union_increasing.\n  - exact H_inc.\n  - unfold union_gen in H. destruct H as [A [H0]].\n    unfold union_gen. exists (f A). unfold image_set. split.\n    + exists A. split.\n      * assumption.\n      * reflexivity.\n    + apply H0 ; assumption.\nQed.\n\nLemma second_inclusion {E} (f : (E -> Prop) -> (E -> Prop)) :\n  (is_increasing f) -> subset (potential_fixpoint f) (f (potential_fixpoint f)).\nProof.\n  intros H_inc x H.\n  assert (subset (f (f (potential_fixpoint f))) (f (potential_fixpoint f))).\n  - apply H_inc. apply first_inclusion. assumption.\n  - unfold potential_fixpoint. unfold union_gen. exists (f (potential_fixpoint f)).\n    split ; assumption.\nQed.\n\nLemma exists_fixpoint {E} (f : ((E -> Prop) -> (E -> Prop))) :\n  (is_increasing f) -> exists U, (is_fixpoint f U). \nProof.\n  intro H_inc. exists (potential_fixpoint f). unfold is_fixpoint.\n  apply set_ext. intro x. split.\n  - apply second_inclusion ; assumption.\n  - apply first_inclusion ; assumption.\nQed.\n\nDefinition interesting_function {E F} (f : E -> F) (g : F -> E) (X : E -> Prop) :=\n  compl (image_set g (compl (image_set f X))).\n\n\nTheorem Cantor_Schröder_Bernstein {E F} (f : E -> F) (g : F -> E) :\n  (inj f) -> (inj g) -> exists h : E -> F, bij h.\nProof.\n  intros Hf Hg. assert (exists U, is_fixpoint (interesting_function f g) U).\n  {\n    apply exists_fixpoint. intros X Y. intro H. apply compl_decreasing.\n    apply image_increasing. apply compl_decreasing. apply image_increasing. assumption.\n  }\n  destruct H as [U Hu].\n  assert (Hg2 := bij_on_image g Hg).\n  apply bij_exists_recip in Hg2. destruct Hg2 as [g' [Hg'1 Hg'2]].\n  assert (H_excl_mid : forall x, ~ (U x) -> image_set g (fun _ => True) x).\n  - intros x H. unfold is_fixpoint in Hu. rewrite <- Hu in H.\n    unfold interesting_function in H.\n    apply NNPP in H.\n    destruct H as [y Py]. exists y ; tauto.\n  - exists (fun x => match (excluded_middle_informative (U x)) with | left _ => (f x) | right H => g' (exist _ x (H_excl_mid x H)) end).\n    split.\n    + intros x y.\n      destruct (excluded_middle_informative (U x)) as [Hx | Hx] ; destruct (excluded_middle_informative (U y)) as [Hy | Hy].\n      * apply Hf.\n      * intro H_eq. exfalso.\n        assert (H_eq2 := f_equal g H_eq).\n        specialize (Hg'2 (exist (image_set g (fun _ => True)) y (H_excl_mid y Hy))).\n        injection Hg'2. intro H_eq3. rewrite H_eq3 in H_eq2.\n        clear Hg'2 H_eq H_eq3.\n        rewrite <- H_eq2 in Hy.\n        unfold is_fixpoint in Hu. rewrite <- Hu in Hy. unfold interesting_function in Hy.\n        apply NNPP in Hy. destruct Hy as [z [Hz1 Hz2]].\n        apply Hg in Hz2. apply Hz1. exists x. split.\n        -- assumption.\n        -- symmetry ; assumption.\n      *  intro H_eq. exfalso.\n        assert (H_eq2 := f_equal g H_eq).\n        specialize (Hg'2 (exist (image_set g (fun _ => True)) x (H_excl_mid x Hx))).\n        injection Hg'2. intro H_eq3. rewrite H_eq3 in H_eq2.\n        clear Hg'2 H_eq H_eq3.\n        rewrite H_eq2 in Hx.\n        unfold is_fixpoint in Hu. rewrite <- Hu in Hx. unfold interesting_function in Hx.\n        apply NNPP in Hx. destruct Hx as [z [Hz1 Hz2]].\n        apply Hg in Hz2. apply Hz1. exists y. split.\n        -- assumption.\n        -- symmetry ; assumption.\n      * intro H_eq.\n        assert (H_eq2 := f_equal (fun z => exist (image_set g (fun _ => True)) (g z) (is_in_image_all g z)) H_eq). simpl in H_eq2. rewrite !Hg'2 in H_eq2. injection H_eq2. tauto.\n    + intro y.\n      destruct (excluded_middle_informative (image_set f U y)) as [Hy | Hy].\n      * destruct Hy as [x [Hx1 Hx2]].\n        exists x. destruct (excluded_middle_informative (U x)).\n        -- assumption.\n        -- exfalso. tauto.\n      * exists (g y). destruct (excluded_middle_informative (U (g y))) as [Hgy | Hgy].\n        -- exfalso.\n           unfold is_fixpoint in Hu. rewrite <- Hu in Hgy.\n           unfold interesting_function in Hgy.\n           apply Hgy. exists y. split.\n           ++ exact Hy.\n           ++ reflexivity.\n        -- rewrite <- Hg'1. f_equal. apply proj1_inj. simpl. reflexivity.\nQed.\n", "meta": {"author": "Upkco", "repo": "Coq_proofs", "sha": "fc0189a80435d40ba011ce20d4da8dd76edae548", "save_path": "github-repos/coq/Upkco-Coq_proofs", "path": "github-repos/coq/Upkco-Coq_proofs/Coq_proofs-fc0189a80435d40ba011ce20d4da8dd76edae548/Cantor_Schröder_Bernstein.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.6919649058091076}}
{"text": "\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** \n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Lesson 4: summary\n\n- Curry Howard: the big picture\n  + dependent function space\n- Predicates and connectives\n  + introduction\n  + elimination\n- Induction\n- Consistency\n- Dependent elimination\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Curry Howard\n\nWe link typed programs to statements with a proof.\n\nLet's play a game in which we use inductive types\nas our satements.\n\n#<div>#\n*)\n\nCheck nat : Type.\n\nDefinition zero : nat := 0.\n\nLemma zero_bis : nat.\nProof.\napply: 0.\nQed.\n\nPrint zero.\nPrint zero_bis.\n\n\n(**\n#</div>#\n\nWe learn that 0 is a term of type nat, but Coq\nalso accepts it as a proof of nat.\n\n#<div style='color: red; font-size: 150%;'>#\nIn type theory: [p] is a proof of [T] \nmeans that [p] inhabits the type [T].\n#</div>#\n\nNow let's look at the function space.\n\n#<div>#\n*)\n\nCheck nat -> nat  :  Type.\n\nDefinition silly : nat -> nat := fun x => x.\n\nLemma sillier : nat -> nat.\nProof. move=> x. apply: x. Qed.\n\nPrint silly.\nPrint sillier.\n\n(**\n#</div>#\n\nThe function space [->] can represent implication.\nAn inhabitant of [A -> B] is a function turning\na proof of [A] into a proof of [B] (a program\ntaking in input a term of type [A] and returning\na term of type [B]).\n\nThe function space of type theory is *dependent*.\n\n#<div>#\n*)\n\nSection DependentFunction.\n\nVariable P : nat -> Type.\nVariable p1 : P 1.\n\n\nCheck forall x, P x.\nCheck forall x : nat, P 1.\n\nCheck fun x : nat => p1.\n     \n\n(**\n#</div>#\n\nWe managed to build (introduce) an arrow and a forall using [fun].\nLet's see how we can use (eliminate) an arrow or a forall.\n\n#<div>#\n*)\n\nCheck factorial.\nCheck factorial 2.\n\nVariable px1 : forall x, P x.+1.\n\nCheck px1.\nCheck px1 3.\n\nEnd DependentFunction.\n\n(**\n#</div>#\n\nFollowing the Curry Howard correspondence *application*\nlets one call a function [f : A -> B] on [a : A] to\nobtain a term of type [B]. If the type of [f] is\na dependent arrow (forall) [f : forall x : A, B x]\nthen the argument [a] appears in the type of\nterm we obtain, that is [f a] has type [B a].\n\nIn other words application instantiates universally\nquantified lemmas and implements modus ponens.\n\nLemmas can be seen as views to transform assumptions.\n\n#<div>#\n*)\n\nSection Views.\n\nVariable P : nat -> Type.\nVariable Q : nat -> Type.\nVariable p2q : forall x, P x -> Q x.\n\nGoal P 3 -> True.\nProof.\nmove=> (*/p2q*) p3.\nAbort.\n\nEnd Views.\n\n(**\n#</div>#\n\nSo far we used [nat] (and [P]) as a predicate and [->] for implication.\n\nCan we use inductive types to model other predicates or connectives?\n\n#<p><br/><p>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\n\nThis slide corresponds to\nsection 4.x of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Predicates and connectives\n\nLet's start with #$$ \\top $$#\n\nNote: here the label [Prop] could be a synonym of [Type].\n\n#<div>#\n*)\n\nPrint True.\n\nDefinition trivial1 : True := I.\n\nDefinition trivial2 : True -> nat :=\n  fun t =>\n    match t with I => 3 end.\n\nLemma trivial3 : True -> nat.\nProof.\nmove=> t. case: t. apply: 3.\nQed.\n\n(**\n#</div>#\n\nNow let's look at #$$ \\bot $$#\n\n#<div>#\n*)\n\nPrint False.\n\nFail Definition hard1 : False := what.\n\nDefinition ex_falso A : False -> A :=\n  fun abs => match abs with end.\n\nLemma ex_falso2 A : False -> A.\nProof.\nmove=> abs. case: abs.\nQed.\n\n(**\n#</div>#\n\nConnectives: #$$ \\land $$# and #$$\\lor $$#\n\n#<div>#\n*)\n\nSection Connectives.\n\nPrint and.\n\nVariable A : Prop.\nVariable B : Prop.\nVariable C : Prop.\n\nVariable a : A.\nVariable b : B.\n\nCheck conj a b.\n\nDefinition and_elim_left : and A B -> A :=\n  fun ab => match ab with conj a b => a end.\n\n\nLemma and_elim_left2 : and A B -> A.\nProof. case=> l r. apply: l. Qed.\n\nPrint or.\n\nCheck or_introl a : or A B.\nCheck or_intror b : or A B.\n\nDefinition or_elim :\n  A \\/ B -> (A -> C) -> (B -> C) -> C :=\n fun aob a2c b2c =>\n   match aob with\n   | or_introl a => a2c a\n   | or_intror b => b2c b\n   end.\n\nLemma or_elim_example : A \\/ B -> C.\nProof.\nmove=> aob.\ncase: aob.\nAbort.\n\n(**\n#</div>#\n\nQuantifier #$$ \\exists $$#\n\n#<div>#\n*)\n\nPrint ex.\n\nLemma ex_elim P : (exists x : A, P x) -> True.\nProof.\ncase => x px.\nAbort.\n\nEnd Connectives.\n\n(**\n#</div>#\n\n#<p><br/><p>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\n\nThis slide corresponds to\nsection 4.x of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n\n#</div>#\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Induction\n\nWe want to prove theorems by induction, right?\nHence there must be a term that corresponds to the induction principle.\nThis term is a recursive function.\n\nNote: [Fixpoint] is just sugar for [Definition] followed by [fix].\n\n#<div>#\n*)\n\nAbout nat_ind.\n\nDefinition ind :\n  forall P : nat -> Prop,\n    P 0 -> (forall n : nat, P n -> P n.+1) -> forall n : nat, P n :=\n  fun P p0 pS =>\n    fix IH n : P n :=\n      match n with\n      | O => p0\n      | S p => pS p (IH p)\n      end.\n\n(**\n#</div>#\n\n#<p><br/><p>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\n\nThis slide corresponds to\nsection 4.x of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Consistency\n\nWe give here the intuition why some terms that are in principle\nwell typed are rejected by Coq and why Coq is consistent.\n\n#<div>#\n*)\nPrint False.\nPrint True.\n(**\n#</div>#\n\nWhat does it mean that [t : T] and [T] is not [False]?\n\n#<div>#\n*)\nCheck (match 3 with O => I | S _ => I end) : True.\n(**\n#</div>#\n\nConstructors are not the only terms that can inhabit a type.\nHence we cannot simply look at terms, but we could look at\ntheir normal form.\n\nSubject reduction: [t : T] and [t ~> t1] then [t1 : T].\nWe claim there is not such [t1] (normal form) that\ninhabits [False].\n\nWe have to reject [t] that don't have a normal form.\n\nExaustiveness of pattern matching:\n\n#<div>#\n*)\n\nLemma helper x : S x = 0 -> False. Proof. by []. Qed.\n\nFail Definition partial n : n = 0 -> False :=\n  match n with\n  | S x => fun p : S x = 0 => helper x p\n(*  | 0 => fun _ => I*)\n  end.\n\nFail Check partial 0 (erefl 0). (* : False *)\n\nFail Compute partial 0 (erefl 0). (* = ??? : False *)\n\n(**\n#</div>#\n\nAccording to Curry Howard this means that in a case\nsplit we did not forget to consider a branch!\n\nTermination of recursion:\n\n#<div>#\n*)\n\nFail Fixpoint oops (n : nat) : False := oops n.+1.\n\nFail Check oops 3. (* : False *)\n\nFail Compute oops 3. (* = ??? : False *)\n\n(**\n#</div>#\n\nAccording to Curry Howard this means that we did not\ndo any circular argument.\n\nNon termination is subtle since a recursive call could\nbe hidden in a box.\n\n#<div>#\n*)\n\nFail Inductive hidden := Hide (f : hidden -> False).\n\nFail Definition oops (hf : hidden) : False :=\n  match hf with Hide f => f hf end.\n\nFail Check oops (Hide oops). (* : False *)\n\nFail Compute oops (Hide oops). (* = ??? : False *)\n\n(**\n#</div>#\n\nThis condition of inductive types is called positivity:\nThe type of [Hide] would be [(hidden -> False) -> hidden],\nwhere the first occurrence of [hidden] is on the left (negative)\nof the arrow.\n\n#<p><br/><p>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\n\nThis slide corresponds to\nsection 3.2.3 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Inductive types with indexes (casse-tête)\n\n... and their elimination.\n\nThe intuition, operationally.\n\nInductive types can express tricky invariants:\n\n#<div>#\n*)\n\n(* Translucent box, we know if it is empty or not without opening it *)\nInductive tbox : bool -> Type :=\n  | Empty          : tbox false\n  | Full (n : nat) : tbox true.\n\nCheck Empty.\nCheck Full 3.\n\nDefinition default (d : nat) (f : bool) (b : tbox f) : nat :=\n  match b with\n  | Empty => d\n  | Full x => x\n  end.\n\n(* Why this complication? (believe me, not worth it) *)\nDefinition get (b : tbox true) : nat :=\n  match b with Full x => x end.\n\n(* the meat: why is the elimination tricky? *)\nLemma default_usage f (b : tbox f) : 0 <= default 3 b .\nProof.\ncase: b.\nFail Check @default 3 f Empty.\n  by [].\nby [].\nQed.\n\n(**\n#</div>#\n\nTake home:\n- the elimination of an inductive data type with indexes\n  expresses equations between the value of the indexes\n  in the type of the eliminated term and the value of the\n  indexes prescribed in the declatation of the inductive data\n- the implicit equations are substituted automatically at\n  elimination time\n- working with indexed data is hard, too hard :-/\n- we can still make good use of indexes when we define \"spec\" lemmas,\n  argument of the next lecture\n\n#<p><br/><p>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\n\nThis slide corresponds to\nsection 4.x of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Lesson 4: sum up\n\n- In Coq terms/types play a double role:\n  + programs and their types\n  + statements and their proofs\n- Inductives can be used to model predicates and\n  connectives\n- Pattern machind and recursion can model induction\n- The empty type is, well, empty, hence Coq is consistent\n- Inductives with indexes\n\n#</div>#\n\n*)\n", "meta": {"author": "gares", "repo": "COQWS18", "sha": "2d438b94357d4be0baf47808db111214f08db467", "save_path": "github-repos/coq/gares-COQWS18", "path": "github-repos/coq/gares-COQWS18/COQWS18-2d438b94357d4be0baf47808db111214f08db467/lesson4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6919426299446714}}
{"text": "Fixpoint Tree(A: Type)(d: nat): Type :=\n  match d with\n  | O => A\n  | S n => Tree A n * Tree A n\n  end.\n\nDefinition ChildType(A: Type)(d: nat): Type :=\n  match d with\n  | O => unit\n  | S n => Tree A n\n  end.\n\nDefinition leftChild{A: Type}{d: nat}(t: Tree A d): ChildType A d :=\n  match d as n return (Tree A n -> ChildType A n) with\n  | O => fun _ => tt\n  | S n => fun t => fst t\n  end t.\n", "meta": {"author": "samuelgruetter", "repo": "counterexamples", "sha": "bb699361b12687fdc6323759745e75d3bf8720b8", "save_path": "github-repos/coq/samuelgruetter-counterexamples", "path": "github-repos/coq/samuelgruetter-counterexamples/counterexamples-bb699361b12687fdc6323759745e75d3bf8720b8/nunchaku/ReturnTypeIsAFunction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6919426230961235}}
{"text": "Definition e:=Set.\nSet Implicit Arguments. \nDefinition Ensemble :=(e -> Prop)->Prop.\nDefinition In (A:Ensemble) (x:e->Prop) : Prop := A x. \nDefinition Included (B C:Ensemble) : Prop := forall x:e->Prop, In B x -> In C x.\n\nDefinition Strict_Included (B C:Ensemble) : Prop := Included B C /\\ B <> C.\n\n\n\nInductive Empty_set : Ensemble :=.\n\nInductive Full_set : Ensemble :=\n Full_intro : forall x:e->Prop, In Full_set x.\n\nInductive Singleton (x:e->Prop) : Ensemble :=\n    In_singleton : In (Singleton x) x.\n\nInductive Union (B C:Ensemble) : Ensemble :=\n    | Union_introl : forall x:e->Prop, In B x -> In (Union B C) x\n    | Union_intror : forall x:e->Prop, In C x -> In (Union B C) x.\n\nDefinition Add (B:Ensemble) (x:e->Prop) : Ensemble := Union B (Singleton x).\n\nInductive Intersection (B C:Ensemble) : Ensemble :=\n    Intersection_intro :\n    forall x:e->Prop, In B x -> In C x -> In (Intersection B C) x.\n\nInductive Couple (x y:e->Prop) : Ensemble :=\n    | Couple_l : In (Couple x y) x\n    | Couple_r : In (Couple x y) y.\n\nInductive Triple (x y z:e->Prop) : 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\nDefinition Complement (A:Ensemble) : Ensemble := fun x:e->Prop => ~ In A x.\n\n  Definition Setminus (B C:Ensemble) : Ensemble :=\n    fun x:e->Prop => In B x /\\ ~ In C x.\n\n  Definition Subtract (B:Ensemble) (x:e->Prop) : Ensemble := Setminus B (Singleton x).\n\n  Inductive Disjoint (B C:Ensemble) : Prop :=\n    Disjoint_intro : (forall x:e->Prop, ~ In (Intersection B C) x) -> Disjoint B C.\n\n \n\n  Definition Same_set (B C:Ensemble) : Prop := Included B C /\\ Included C B.\n    Axiom Extensionality_Ensembles : forall A B:Ensemble, Same_set A B -> A = B.\n\nDefinition ensemble :=e->Prop.\nDefinition In_s (A:ensemble) (x:e) : Prop := A x.\nDefinition included (B C:ensemble) : Prop := forall x:e, In_s B x -> In_s C x.\n\nDefinition strict_Included (B C:ensemble) : Prop := included B C /\\ B <> C.\n\n\nInductive empty_set : ensemble :=.\n\nInductive full_set : ensemble :=\nfull_intro : forall x:e, In_s full_set x.\n\n  Inductive singleton (x:e) : ensemble :=\n    in_singleton : In_s (singleton x) x.\n\n\n  Inductive union (B C:ensemble) : ensemble :=\n    | union_introl : forall x:e, In_s B x -> In_s (union B C) x\n    | union_intror : forall x:e, In_s C x -> In_s (union B C) x.\n\nDefinition add (B:ensemble) (x:e) : ensemble := union B (singleton x).\n\nInductive intersection (B C:ensemble) : ensemble :=\n    intersection_intro :\n    forall x:e, In_s B x -> In_s C x -> In_s (intersection B C) x.\n\nInductive couple (x y:e) : ensemble :=\n    | couple_l : In_s (couple x y) x\n    | couple_r : In_s (couple x y) y.\n\nInductive triple (x y z:e) : ensemble :=\n    | triple_l : In_s (triple x y z) x\n    | triple_m : In_s (triple x y z) y\n    | triple_r : In_s (triple x y z) z.\n\nDefinition complement (A:ensemble) : ensemble := fun x:e => ~ In_s A x.\n\nDefinition setminus (B C:ensemble) : ensemble :=\n    fun x:e => In_s B x /\\ ~ In_s C x.\n\n\nDefinition subtract (B:ensemble) (x:e) : ensemble := setminus B (singleton x).\n\nInductive disjoint (B C:ensemble) : Prop :=\n    disjoint_intro : (forall x:e, ~ In_s (intersection B C) x) -> disjoint B C.\n\nInductive inhabited (B:ensemble) : Prop :=\n    inhabited_intro : forall x:e, In_s B x -> inhabited B.\n\nDefinition strict_included (B C:ensemble) : Prop := included B C /\\ B <> C.\n\nDefinition same_set (B C:ensemble) : Prop := included B C /\\ included C B.\n    Axiom extensionality_ensembles : forall A B:ensemble, same_set A B -> A = B.\n\n \n\n", "meta": {"author": "StergiosCha", "repo": "CoqNL", "sha": "cb1c929ac45d4b447de66b6a8bc90d5da06c6c9c", "save_path": "github-repos/coq/StergiosCha-CoqNL", "path": "github-repos/coq/StergiosCha-CoqNL/CoqNL-cb1c929ac45d4b447de66b6a8bc90d5da06c6c9c/Code/Tutorial2_FS_in_Coq/Set_theoretic_Defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.6919426137992675}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra.\nRequire Import forms.\nFrom mathcomp.analysis Require Import boolp ereal reals cardinality mathcomp_extra.\nFrom mathcomp.analysis Require Import \n  signed classical_sets functions topology prodnormedzmodule normedtype sequences.\nFrom mathcomp.real_closed Require Import complex.\nRequire Import mcextra mxpred hermitian.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport Order Order.Theory GRing.Theory.\nImport numFieldTopology.Exports.\n\nLocal Open Scope classical_set_scope.\nLocal Open Scope ring_scope.\n\n(* compact R set has maximum and minimum *)\nSection R_compact_max_min.\nVariable (R: realType).\nImport Num.Theory numFieldNormedType.Exports.\n\nLemma compact_max (S: set R) : \n  compact S -> S !=set0 -> exists2 x, S x & (forall y, S y -> y <= x).\nProof.\nmove=>P1 P2; move: {+}P2=>[x Px].\nhave PF : ProperFilter (globally S) by apply: (@globally_properfilter _ _ x).\nhave ubS : has_ubound S.\nmove: P1=>/compact_bounded/=/(ex_bound)/==>[[M PM]].\nexists M=>y Py; apply: (le_trans (ler_norm _)); by apply PM.\nexists (sup S); last by apply/ubP/sup_upper_bound; split.\nby move: (compact_closed (@Rhausdorff R) P1)=>/closure_id{1}->; apply closure_sup.\nQed.\n\nLemma compact_min (S: set R) : \n  compact S -> S !=set0 -> exists2 x, S x & (forall y, S y -> x <= y).\nProof.\nmove=>P1 P2; have cS : compact [set - x | x in S]\n  by apply/continuous_compact=>//; apply/continuous_subspaceT=>x _; apply: opp_continuous.\nhave nS : [set - x | x in S] !=set0 by by apply nonemptyN.\nhave inS: forall x, [set - x | x in S] (-x) <-> S x.\nmove=>x; split=>[[y Py /oppr_inj<-//]|Px]; by exists x.\nmove: (compact_max cS nS)=>[x Px lex].\nexists (- x)=>[|y]; first by rewrite -inS opprK.\nby rewrite -inS Num.Theory.ler_oppl =>/lex.\nQed.\nEnd R_compact_max_min.\n\n(* Prove the completeness of C *)\nModule CTopology.\n\nSection CTopology.\nImport GRing.Theory ComplexField Order.TTheory.\nImport Pointed.Exports Filtered.Exports Topological.Exports Uniform.Exports PseudoMetric.Exports.\nImport Complete.Exports CompletePseudoMetric.Exports.\nImport numFieldTopology.Exports numFieldNormedType.Exports.\n\nVariable (R: realType).\nLocal Notation C := R[i].\nLocal Canonical C_pointedType := [pointedType of C for [pointedType of C^o]].\nLocal Canonical C_filteredType := [filteredType C of C for [filteredType C of C^o]].\nLocal Canonical C_topologicalType := [topologicalType of C for [topologicalType of C^o]].\nLocal Canonical C_uniformType := [uniformType of C for [uniformType of C^o]].\nLocal Canonical C_pseudoMetricType := [pseudoMetricType [numDomainType of C] of C for [pseudoMetricType [numDomainType of C] of C^o]].\nLocal Canonical C_pseudoMetricNormedZmodType := [pseudoMetricNormedZmodType C of C for [pseudoMetricNormedZmodType C of C^o]].\nLocal Canonical C_normedModType := [normedModType C of C for [normedModType C of C^o]].\nLocal Open Scope classical_set_scope.\nLocal Open Scope complex_scope.\nLocal Open Scope ring_scope.\n\nLemma C_complete (F : set (set C)) : ProperFilter F -> cauchy F -> cvg F.\nProof.\nmove=> FF /cauchyP F_cauchy. \nsuff P1: cauchy (fmap (@Re _) F).\nsuff P2: cauchy (fmap (@Im _) F).\nmove: (R_complete (fmap_proper_filter (@Re _) FF) P1) (R_complete (fmap_proper_filter (@Im _) FF) P2)=>\n/cvg_ex[relim /(@cvg_dist _ _ _ (fmap_proper_filter (@Re _) FF)) cvgRe] \n/cvg_ex[imlim /(@cvg_dist _ _ _ (fmap_proper_filter (@Im _) FF)) cvgIm].\napply/cvg_ex=>/=; exists (relim +i* imlim).\napply: (cvg_distW)=>/= e egt0; move: (real_gt0 egt0)=>ree.\nhave regt0 : (Re e) / 2%:R > 0 by apply cauchyreals.divrn_gt0. \nmove: (cvgRe _ regt0) (cvgIm _ regt0). \nrewrite /prop_near1 !nbhs_filterE/= !nbhs_filterE/= =>P3 P4.\nmove: (@filterI _ _ FF _ _ P3 P4)=>P5.\napply: (@filterS _ _ FF _ _ _ P5) => x /=; rewrite normc_def/= !linearB/=.\n  rewrite -{3}(cgt0_real egt0) lecR -(Num.Theory.gtr0_norm regt0) -{3}(Num.Theory.gtr0_norm ree)\n    -!Num.Theory.sqrtr_sqr !Num.Theory.ltr_sqrt ?Num.Theory.ler_sqrt.\n  move=>[Pt1] /(Num.Theory.ltr_add Pt1) Pt2; apply/ltW; apply (lt_trans Pt2).\n  by rewrite {3}(mathcomp_extra.splitr (Re e)) sqrrD addrC addrA Num.Theory.ltr_addl mulr2n \n    Num.Theory.addr_gt0//; apply Num.Theory.mulr_gt0.\n  1,2,3: by apply Num.Theory.exprn_gt0.\nall: apply/cauchyP; move: F_cauchy; rewrite /cauchy_ex/= =>P e egt0;\nhave ecgt0 : 0 < e%:C by move: egt0; rewrite -ltcR.\nall: move: (P _ ecgt0)=>[x Px]. 1: exists (Im x). 2: exists (Re x).\nall: apply: (filterS _ Px)=>y; rewrite /ball/= normc_def ltcR=>Pt;\napply: (le_lt_trans _ Pt); rewrite !linearB/= -Num.Theory.sqrtr_sqr;\napply Num.Theory.ler_wsqrtr; by rewrite ?Num.Theory.ler_addl \n?Num.Theory.ler_addr Num.Theory.sqr_ge0.\nQed.\n\nLocal Canonical C_completeType :=\n  CompleteType C (@C_complete).\nLocal Canonical C_CompleteNormedModule :=\n  [completeNormedModType C of C].\n\nEnd CTopology.\n\nModule Exports.\nCanonical C_pointedType.\nCanonical C_filteredType.\nCanonical C_topologicalType.\nCanonical C_uniformType.\nCanonical C_pseudoMetricType.\nCanonical C_pseudoMetricNormedZmodType.\nCanonical C_normedModType.\nCanonical C_completeType.\nCanonical C_CompleteNormedModule.\nEnd Exports.\nEnd CTopology.\nImport CTopology.Exports.\n\n(*Cauchy Seq Characterization*)\nSection CauchySeq.\nImport Num.Def Num.Theory.\nVariable (R: numFieldType) (V: completeNormedModType R).\n\n(* to use cauchy_seq for other functions *)\nDefinition cauchy_seq  (u: nat -> V) := \n  forall e : R, 0 < e -> exists N : nat, \n    forall s t, (N <= s)%N -> (N <= t)%N -> `| u s - u t | < e.\n\nLemma cauchy_seqP  (u: nat -> V) : cauchy_seq u <-> cvg u.\nProof.\nsplit=>[P1|/cvg_cauchy/cauchyP].\n  apply: (@cauchy_cvg _ [filter of u]); apply/cauchyP.\n  rewrite /cauchy_ex=>e egt0 /=; move: (P1 _ egt0)=>[N Pn].\n  exists (u N); exists N=>// s/= Ps.\n  rewrite -ball_normE/=; apply Pn=>//.\nrewrite /cauchy_ex=>P e egt0 /=.\nhave: e / 2%:R > 0 by rewrite divr_gt0// ltr0n.\nmove/(P _) =>[x /= [N _ PN]]; exists N=>s t Ps Pt.\nmove: (PN s) (PN t)=>/= /(_ Ps) P1 /(_ Pt) P2.\nby move: (ball_splitr P1 P2); rewrite -ball_normE.\nQed.\n\n(* to use cauchy_seq for other functions *)\nDefinition cvg_seq  (u: nat -> V) a := \n  forall e : R, 0 < e -> exists N : nat, \n    forall s, (N <= s)%N -> `| a - u s | < e.\n\nLemma cvg_seqP  (u: nat -> V) a : cvg_seq u a <-> u --> a.\nProof.\nsplit=>[P1|/cvg_dist +e egt0].\napply: cvg_distW=>/= e egt0; rewrite/prop_near1 nbhs_filterE/=.\nby move: (P1 _ egt0)=>[N PN]; exists N=>//= i/=/PN/ltW.\nmove=>/(_ e egt0); rewrite/prop_near1 nbhs_filterE=>[[N _ PN]].\nby exists N=>n Pn; move: (PN n)=>/=/(_ Pn).\nQed.\n\nLemma nchain_ge (h: nat -> nat) :\n  (forall n, (h n.+1 > h n)%N) -> forall n, (h n >= n)%N.\nProof. by move=>P1 n; elim: n=>[|n IH]; [rewrite leq0n| apply/(leq_ltn_trans IH)]. Qed.\n\nLemma nchain_mono (h: nat -> nat) :\n  (forall n, (h n.+1 > h n)%N) -> forall n m, (n > m)%N -> (h n > h m)%N.\nProof.\nmove=>P1 n m; elim: n=>// n IH /ltnSE. \nrewrite leq_eqVlt=>/orP[/eqP->//|/IH H].\nby apply (ltn_trans H).\nQed.\n\nFixpoint nseq_sig Q (P : forall n, {m : nat | Q n m}) m :=\n  match m with\n  | O => projT1 (P O)\n  | S n => projT1 (P (nseq_sig P n))\n  end.\n\nLemma nseq_sigE Q (P : forall n, {m : nat | Q n m}) m :\n  nseq_sig P m.+1 = projT1 (P (nseq_sig P m)).\nProof. by []. Qed.\n\nLemma nseq_sigP Q (P : forall n, {m : nat | Q n m}) (m:nat) :\n  Q (nseq_sig P m) (projT1 (P (nseq_sig P m))).\nProof. by move: (projT2 (P (nseq_sig P m))). Qed.\n\nLemma implyE (P Q : Prop) : (P -> Q) = ~ P \\/ Q.\nProof. by rewrite -(notK (P -> Q)) not_implyE propeqE not_andP notK. Qed.\n\nLemma implyNE (P Q : Prop) : (P -> ~ Q) = (~ (P /\\ Q)).\nProof. by rewrite implyE propeqE not_andP. Qed.\n\n(* not exists subseq -> there is a bound *)\nLemma non_exists_nseq (P : nat -> Prop) :\n  ~ (exists (h : nat -> nat), (forall n, (h n.+1 > h n)%N) /\\ (forall n, P (h n)))\n  -> exists N, forall n, (n >= N)%N -> ~ (P n).\nProof.\napply contra_notP. rewrite not_existsP !notK=>H.\nsuff H1: forall n, {m : nat | (n < m /\\ P m)%N}.\nexists (nseq_sig H1); split=>n.\nby move: (nseq_sigP H1 n)=>[+_]; rewrite nseq_sigE.\nrewrite /=; case: n=>[|n]. \nby rewrite /nseq_sig; move: (projT2 (H1 0%N))=>[].\nby rewrite nseq_sigE; move: (projT2 (H1 (nseq_sig H1 n)))=>[].\nmove=>n; apply/cid; move: (H n.+1); apply contra_notP; \nby rewrite not_existsP notK=>H1 m; move: (H1 m); rewrite -implyNE.\nQed.\n\nLemma cvg_limP (f: nat -> V) (a: V) :\n  f --> a <-> forall e, 0 < e -> exists N, forall n,  (N <= n)%N -> `|f n - a| < e.\nProof.\nrewrite cvg_ballP; split=>+e egt0; move=>/(_ e egt0); rewrite near_map=>[[N Pn]].\nmove=>P1; exists N=>n ltNn; move: (P1 n)=>/=. \n2: exists N=>// n/=/Pn.\nall: rewrite -ball_normE/= -Num.Theory.normrN opprB// =>P2.\nby apply P2.\nQed.\n\nLemma cvg_subseqP (f: nat -> V) (a: V) : \n  f --> a <-> (forall (h: nat -> nat), (forall n, (h n.+1 > h n)%N) -> (f \\o h) --> a).\nProof.\nsplit=>[|H].\nrewrite cvg_limP=>H h Ph; rewrite cvg_limP=>e egt0.\nmove: (H _ egt0)=>[N H1]; exists N=>n IH.\napply H1; by apply/(leq_trans IH)/nchain_ge.\nhave /H: forall n, (id n < id n.+1)%N by [].\nsuff ->: f \\o id = f by []. by apply/funext=>n.\nQed.\n\nLemma cvg_subseqPN (f: nat -> V) (a: V) :\n  ~ (f --> a) <-> exists e (h: nat -> nat), \n    (forall n, (h n.+1 > h n)%N) /\\ 0 < e /\\ (forall n, `|(f \\o h) n - a| >= e).\nsplit; last first.\n- apply contraPnot. rewrite -forallNP.\n  move=>/cvg_limP H1 e. rewrite -forallNP=>h [P1 [P2]] /not_forallP P3.\n  apply P3. move: (H1 _ P2)=>[N PN]. exists N.+1. apply/negP.\n  rewrite -real_ltNge//= ?gtr0_real//. apply/PN.\n  by apply: (leq_trans _ (nchain_ge P1 _)).\nrewrite cvg_limP -existsNE=>[[e]].\nrewrite not_implyP -forallNP=>[[egt0 P]].\nexists e. pose P1 n := (e <= `|f n - a|) : Prop.\nsuff: (exists h, (forall n, (h n.+1 > h n)%N) /\\ (forall n, P1 (h n))).\nby move=>[h [Ph1 Ph2]]; exists h; split=>//.\nmove: P; apply contraPP=>/non_exists_nseq[N PN].\nrewrite not_forallP notK; exists N; rewrite notK=>n/PN.\nby rewrite /P1=>/negP; rewrite -real_ltNge// gtr0_real.\nQed.\n\nLemma cvg_limE (f: nat -> V) (a: V) : hausdorff_space V -> f --> a <-> lim f = a /\\ cvg f.\nProof. \nsplit=>[P1|[ <-]//]. split. apply/cvg_lim. apply H.\napply P1. by move: P1=>/cvgP.\nQed.\n\nEnd CauchySeq.\n\n(* I don't know why cvgD ... are difficult to use;   *)\n(* maybe due to the canonical of R[i]?               *)\n(* for convenience, I write some of the theorems here*)\nSection complex_seq_composition.\nVariable (R: realType).\nLocal Notation C := R[i].\nImplicit Type (f g: nat -> C) (n: nat) (s a b : C).\n\nLemma Chausdorff : hausdorff_space [topologicalType of C].\nProof. apply: norm_hausdorff. Qed.\n\nLemma ccvg_limE f a : f --> a <-> lim f = a /\\ cvg f.\nProof. exact: (cvg_limE f a Chausdorff). Qed.\n\nLemma ccvg_cst a : (fun n:nat=>a) --> a. Proof. exact: cvg_cst. Qed.\nLemma is_ccvg_cst a : cvg (fun n:nat=>a). Proof. exact: is_cvg_cst. Qed.\nLemma clim_cst a : lim (fun n:nat=>a) = a. Proof. exact: lim_cst. Qed.\nLemma ccvgN f a : f --> a -> (- f) --> - a. Proof. exact: cvgN. Qed.\nLemma is_ccvgN f : cvg f -> cvg (- f). Proof. exact: is_cvgN. Qed.\nLemma is_ccvgNE f : cvg (- f) = cvg f. Proof. exact: is_cvgNE. Qed.\nLemma ccvgMn f n a : f --> a -> ((@GRing.natmul _)^~n \\o f) --> a *+ n. Proof. exact: cvgMn. Qed.\nLemma is_ccvgMn f n : cvg f -> cvg ((@GRing.natmul _)^~n \\o f). Proof. exact: is_cvgMn. Qed.\nLemma ccvgD f g a b : f --> a -> g --> b -> (f + g) --> a + b. Proof. exact: cvgD. Qed.\nLemma is_ccvgD f g : cvg f -> cvg g -> cvg (f + g). Proof. exact: is_cvgD. Qed.\nLemma ccvgB f g a b : f --> a -> g --> b -> (f - g) --> a - b. Proof. exact: cvgB. Qed.\nLemma is_ccvgB f g : cvg f -> cvg g -> cvg (f - g). Proof. exact: is_cvgB. Qed.\nLemma is_ccvgDlE f g : cvg g -> cvg (f + g) = cvg f. Proof. exact: is_cvgDlE. Qed.\nLemma is_ccvgDrE f g : cvg f -> cvg (f + g) = cvg g. Proof. exact: is_cvgDrE. Qed.\nLemma ccvgM f g a b : f --> a -> g --> b -> (f * g) --> a * b. Proof. exact: cvgZ. Qed.\nLemma is_ccvgM f g : cvg f -> cvg g -> cvg (f * g). Proof. exact: is_cvgZ. Qed.\nLemma ccvgMl f a b (g := fun=>b): f --> a -> f * g --> a * b. Proof. exact: cvgZl. Qed.\nLemma ccvgMr g a b (f := fun=>a): g --> b -> f * g --> a * b. Proof. exact: cvgZr. Qed.\nLemma is_ccvgMr g a (f := fun=> a) : cvg g -> cvg (f * g). Proof. exact: is_cvgZr. Qed.\nLemma is_ccvgMrE g a (f := fun=> a) : a != 0 -> cvg (f * g) = cvg g. Proof. exact: is_cvgZrE. Qed.\nLemma is_ccvgMl f a (g := fun=> a) : cvg f -> cvg (f * g). Proof. exact: is_cvgMl. Qed.\nLemma is_ccvgMlE f a (g := fun=> a) : a != 0 -> cvg (f * g) = cvg f. Proof. exact: is_cvgMlE. Qed.\nLemma ccvg_norm f a : f --> a -> (Num.norm \\o f) --> `|a|. Proof. exact: cvg_norm. Qed.\nLemma is_ccvg_norm f : cvg f -> cvg (Num.norm \\o f). Proof. exact: is_cvg_norm. Qed.\nLemma climN f : cvg f -> lim (- f) = - lim f. Proof. exact: limN. Qed.\nLemma climD f g : cvg f -> cvg g -> lim (f + g) = lim f + lim g. Proof. exact: limD. Qed.\nLemma climB f g : cvg f -> cvg g -> lim (f - g) = lim f - lim g. Proof. exact: limB. Qed.\nLemma climM f g : cvg f -> cvg g -> lim (f * g) = lim f * lim g. Proof. exact: limM. Qed.\nLemma clim_norm f : cvg f -> lim (Num.norm \\o f) = `|lim f|. Proof. exact: lim_norm. Qed.\nLemma climV f : cvg f -> lim f != 0 -> lim ((fun x => (f x)^-1)) = (lim f)^-1. Proof. exact: limV. Qed.\n\nLemma ccvg_map f a (V : completeType) (h : C -> V) :\n  continuous h -> f --> a -> (h \\o f) --> h a.\nProof. \nmove=>ch cvgf; apply: (@cvg_fmap _ _ [filter of f] a h).\nby apply ch. by apply cvgf.\nQed.\n\nLemma ccvg_mapV (V : completeType) (h : V -> C) (h' : nat -> V) (a : V) :\n  continuous h -> h' --> a -> (h \\o h') --> h a.\nProof. \nmove=>ch cvgf; apply: (@cvg_fmap _ _ [filter of h'] a h).\nby apply ch. by apply cvgf.\nQed.\n\nLemma is_ccvg_map f (V : completeType) (h : C -> V) :\n  continuous h -> cvg f -> cvg (h \\o f).\nProof.\nmove=>P1 /cvg_ex=>[/= [a Pa]]. apply/cvg_ex.\nexists (h a). by move: (ccvg_map P1 Pa).\nQed.\n\nLemma is_ccvg_mapV (V : completeType) (h : V -> C) (h' : nat -> V) :\n  continuous h -> cvg h' -> cvg (h \\o h').\nProof.\nmove=>P1 /cvg_ex=>[/= [a Pa]]. apply/cvg_ex.\nexists (h a). by move: (ccvg_mapV P1 Pa).\nQed.\n\nLemma clim_map f a (V : completeType) (h : C -> V) :\n  hausdorff_space V -> continuous h -> cvg f -> lim (h \\o f) = h (lim f).\nProof. by move=>hV ch; move/(ccvg_map ch)/cvg_lim=>/(_ hV). Qed.\n\nLemma clim_mapV (V : completeType) (h : V -> C) (h' : nat -> V) :\n  continuous h -> cvg h' -> lim (h \\o h') = h (lim h').\nProof. by move=>ch; move/(ccvg_mapV ch)/cvg_lim=>/(_ Chausdorff). Qed.\n\nLemma ccvg_limP f a :\n  f --> a <-> forall e, 0 < e -> exists N, forall n,  (N <= n)%N -> `|f n - a| < e.\nProof. exact: cvg_limP. Qed.\n\nLemma ccvg_subseqP f a : \n  f --> a <-> (forall (h: nat -> nat), (forall n, (h n.+1 > h n)%N) -> (f \\o h) --> a).\nProof. exact: cvg_subseqP. Qed.\n\nLemma ccvg_subseqPN f a :\n  ~ (f --> a) <-> exists e (h: nat -> nat), \n    (forall n, (h n.+1 > h n)%N) /\\ 0 < e /\\ (forall n, `|(f \\o h) n - a| >= e).\nProof. exact: cvg_subseqPN. Qed.\n\nDefinition ccauchy_seq f := forall e, 0 < e -> exists N, forall i j, \n  (N <= i)%N -> (N <= j)%N -> `| f i - f j | < e.\n\nLemma ccauchy_seqP f : ccauchy_seq f <-> cvg f.\nProof. exact: cauchy_seqP. Qed.\n\nDefinition ccvg_seq f a := \n  forall e, 0 < e -> exists N : nat, \n    forall i, (N <= i)%N -> `| a - f i | < e.\n\nLemma ccvg_seqP f a : ccvg_seq f a <-> f --> a.\nProof. exact: cvg_seqP. Qed.\n\nLemma re_continuous : continuous (@Re R).\nProof. \nmove=> x s/= /nbhs_ballP [/=e egt0 Pb].\napply/nbhs_ballP. exists e%:C =>//=. by rewrite ltcR.\nmove=> y /= Pxy. apply (Pb (Re y)). move: Pxy.\nrewrite -ball_normE/= /ball/= -raddfB/= -ltcR.\napply: (le_lt_trans (normc_ge_Re _)).\nQed.\n\nLemma im_continuous : continuous (@Im R).\nProof. \nmove=> x s/= /nbhs_ballP [/=e egt0 Pb].\napply/nbhs_ballP. exists e%:C =>//=. by rewrite ltcR.\nmove=> y /= Pxy. apply (Pb (Im y)). move: Pxy.\nrewrite -ball_normE/= /ball/= -raddfB/= -ltcR.\napply: (le_lt_trans (normc_ge_Im _)).\nQed.\n\nLemma rc_continuous : continuous (@real_complex R).\nProof. \nmove=> x s/= /nbhs_ballP [/=e egt0 Pb].\napply/nbhs_ballP. exists (Re e) =>//=. by apply real_gt0.\nmove=> y /= Pxy. apply (Pb y%:C). move: Pxy.\nby rewrite -ball_normE/= /ball/= -raddfB/= -ltcR cgt0_real// normc_real.\nQed.\n\nLemma ic_continuous : continuous (@im_complex R).\nProof. \nmove=> x s/= /nbhs_ballP [/=e egt0 Pb].\napply/nbhs_ballP. exists (Re e) =>//=. by apply real_gt0.\nmove=> y /= Pxy. apply (Pb y%:Ci). move: Pxy.\nrewrite -ball_normE/= /ball/= -(@raddfB _ _ (im_complex_additive R))/=.\nby rewrite normc_im -ltcR cgt0_real// normc_real.\nQed.\n\nLemma cseq_split (u : C ^nat) : ((@real_complex R) \\o ((@Re R) \\o u)) + \n  ((@im_complex R) \\o ((@Im R) \\o u)) = u.\nProof. by apply/funext=>i; rewrite /GRing.add/= complex_split. Qed.\n\nLemma conjC_continuous (K : numClosedFieldType) : continuous (@Num.Theory.conjC K).\nProof.\nmove=> x s/= /nbhs_ballP [/=e egt0 Pb].\napply/nbhs_ballP. exists (e) =>//=.\nmove=> y /= Pxy. apply (Pb (@Num.Theory.conjC K y)). move: Pxy.\nby rewrite /ball/= -rmorphB Num.Theory.norm_conjC.\nQed.\nLemma ccvg_conj f a : f --> a -> (Num.Theory.conjC \\o f) --> (Num.Theory.conjC a).\nProof. by apply: continuous_cvg; apply conjC_continuous. Qed.\nLemma is_ccvg_conj f : cvg f -> cvg (Num.Theory.conjC \\o f).\nProof. by move=> /ccvg_conj /cvgP. Qed.\nLemma is_ccvg_conjE f : cvg (Num.Theory.conjC \\o f) = cvg f.\nProof. \nrewrite propeqE; split.\nhave P1: f = (Num.Theory.conjC \\o (Num.Theory.conjC \\o f))\nby apply/funext=>x/=; rewrite Num.Theory.conjCK.\nrewrite [in X in _ -> X]P1. all: apply is_ccvg_conj.\nQed.\nLemma clim_conj f : cvg f -> lim (Num.Theory.conjC \\o f) = Num.Theory.conjC (lim f).\nProof. by move=> ?; apply: cvg_lim; [apply: Chausdorff | apply: ccvg_conj]. Qed.\n\nEnd complex_seq_composition.\n\nLemma compA U V W T (f: U -> V) (g : V -> W) (h : W -> T) :\n  h \\o (g \\o f) = h \\o g \\o f.\nProof. exact. Qed.\n\nSection complex_monotone.\nVariable (R : realType).\nLocal Notation C := R[i].\n\nLemma cnondecreasing_split (u_ : C ^nat) :\n  nondecreasing_seq u_ <-> (nondecreasing_seq ((@Re _) \\o u_)) /\\ \n    (@Im _) \\o u_ = (fun=> Im (u_ 0%N)).\nProof.\nsplit=>[homc|[homr csti m n /homr]]/=.\nsplit=>[m n /homc|]/=. by rewrite lecE=>/andP[_].\napply/funext=>n. move: (homc _ _ (leq0n n)). by rewrite lecE/==>/andP[/eqP->].\nmove: csti. rewrite lecE funeqE=> Pi->.\nmove: (Pi n) (Pi m)=>/=-> ->. by rewrite eqxx.\nQed.\n\nLemma cubounded_split (u_ : C ^nat) (M : C):\n  (forall n : nat, u_ n <= M) <-> (forall n : nat, ((@Re _) \\o u_) n <= Re M) /\\ \n    (@Im _) \\o u_ = (fun=> Im M).\nProof.\nsplit=>[ub|[ubr csti]]. split.\nmove=>n. move: (ub n)=>/=. by rewrite lecE/==>/andP[_].\napply/funext=>n. move: (ub n).\nby rewrite !lecE/==>/andP[/eqP<- _].\nmove=>n. move: csti. rewrite lecE funeqE=>csti.\nby move: (ubr n) (csti n)=>/=->/esym/eqP->.\nQed.\n\nLemma cnonincreasing_split (u_ : C ^nat) :\n  nonincreasing_seq u_ <-> (nonincreasing_seq ((@Re _) \\o u_)) /\\ \n    (@Im _) \\o u_ = (fun=> Im (u_ 0%N)).\nProof.\nsplit=>[homc|[homr csti m n /homr]]/=.\nsplit=>[m n /homc|]/=. by rewrite lecE=>/andP[_].\napply/funext=>n. move: (homc _ _ (leq0n n)). by rewrite lecE/==>/andP[/eqP->].\nmove: csti. rewrite lecE funeqE=> Pi->.\nmove: (Pi n) (Pi m)=>/=-> ->. by rewrite eqxx.\nQed.\n\nLemma clbounded_split (u_ : C ^nat) (M : C):\n  (forall n : nat, M <= u_ n) <-> (forall n : nat, Re M <= ((@Re _) \\o u_) n) /\\ \n    (@Im _) \\o u_ = (fun=> Im M).\nProof.\nsplit=>[ub|[ubr csti]]. split.\nmove=>n. move: (ub n)=>/=. by rewrite lecE/==>/andP[_].\napply/funext=>n. move: (ub n).\nby rewrite !lecE/==>/andP[/eqP<- _].\nmove=>n. move: csti. rewrite lecE funeqE=>csti.\nby move: (ubr n) (csti n)=>/=->/eqP->.\nQed.\n\nLemma ccvg_split (u_ : C ^nat) :\n  cvg u_ -> cvg ((@Re _) \\o u_) /\\ cvg ((@Im _) \\o u_).\nProof. split; apply/is_ccvg_map=>//; [apply re_continuous| apply im_continuous]. Qed.\n\nLemma clim_split (u_ : C ^nat) :\n  cvg u_ -> lim u_ = (lim ((@Re _) \\o u_))%:C + (lim ((@Im _) \\o u_))%:Ci.\nProof.\nmove=>Pcvg; move: Pcvg {+}Pcvg.\nmove=>/(ccvg_map (@re_continuous R))/(cvg_lim (@Rhausdorff _))->.\nmove=>/(ccvg_map (@im_continuous R))/(cvg_lim (@Rhausdorff _))->.\nby rewrite complex_split.\nQed.\n\n\nLemma cnondecreasing_is_cvg (u_ : C ^nat) (M : C) :\n       nondecreasing_seq u_ -> (forall n : nat, u_ n <= M) -> cvg u_.\nProof.\nmove/cnondecreasing_split=>[P1 P2] /cubounded_split [P3 _].\nrewrite -(cseq_split u_). apply/is_ccvgD; apply is_ccvg_mapV=>//.\napply rc_continuous. apply: (nondecreasing_is_cvg P1 _). by exists (Re M) => _ [n _ <-].\napply ic_continuous. rewrite P2. apply: is_cvg_cst.\nQed.\n\nLemma cnondecreasing_cvg (u_ : C ^nat) (M : C) :\n       nondecreasing_seq u_ -> (forall n : nat, u_ n <= M) -> \n        u_ --> (lim ((@Re _) \\o u_))%:C + (Im M)%:Ci.\nProof.\nmove=>P1 P2. move: (cnondecreasing_is_cvg P1 P2)=>P3.\nrewrite ccvg_limE; split=>//. rewrite clim_split//.\nmove: P2=>/cubounded_split [_ P4]. rewrite P4 lim_cst//. \napply Rhausdorff.\nQed.\n\nLemma cnonincreasing_is_cvg (u_ : C ^nat) (M : C) :\n       nonincreasing_seq u_ -> (forall n : nat, M <= u_ n) -> cvg u_.\nProof.\nrewrite -nondecreasing_opp -is_ccvgNE =>P1 P2.\napply: (@cnondecreasing_is_cvg _ (- M) P1 _)=>n.\nby rewrite {1}/GRing.opp/= Num.Theory.ler_opp2.\nQed.\n\nLemma cnonincreasing_cvg (u_ : C ^nat) (M : C) :\n       nonincreasing_seq u_ -> (forall n : nat, M <= u_ n) -> \n        u_ --> (lim ((@Re _) \\o u_))%:C + (Im M)%:Ci.\nProof.\nmove=>P1 P2. move: (cnonincreasing_is_cvg P1 P2)=>P3.\nrewrite ccvg_limE; split=>//. rewrite clim_split//.\nmove: P2=>/clbounded_split [_ P4]. rewrite P4 lim_cst//. \napply Rhausdorff.\nQed.\n\nLemma cnondecreasing_cvg_le (u_ : C ^nat) :\n       nondecreasing_seq u_ -> cvg u_ -> (forall n : nat, u_ n <= lim u_).\nProof.\nmove/cnondecreasing_split=>[P1 P2] P0.\nmove: P0 {+}P0=>/ccvg_split[P3 _] /clim_split-> n.\nrewrite lecE/= P2/= lim_cst ?addr0 ?add0r; last by apply Rhausdorff.\napply/andP; split; first by move: P2; rewrite funeqE=>/(_ n)/=->.\nby apply: nondecreasing_cvg_le.\nQed.\n\nLemma cnonincreasing_cvg_ge (u_ : C ^nat) : \n  nonincreasing_seq u_ -> cvg u_ -> (forall n, lim u_ <= u_ n).\nProof.\nrewrite -nondecreasing_opp -is_ccvgNE =>P1 P2 n.\nrewrite -(opprK u_) climN// Num.Theory.ler_opp2.\nby apply cnondecreasing_cvg_le.\nQed.\n\nLemma Cnng_open (t : C) : t \\isn't Num.nneg -> \n  exists2 e, 0 < e & forall s, `|s - t| < e -> s \\isn't Num.nneg.\nProof.\nrewrite Num.Theory.nnegrE lecE/= negb_and -Num.Theory.real_ltNge \n  ?Num.Theory.real0// ?Num.Theory.num_real// =>/orP[P1|P1].\nexists (`|Im t|)%:C=>[|s]; first by rewrite ltcR Num.Theory.normr_gt0.\n2: exists (`|Re t|)%:C=>[|s]; first by move: P1; rewrite ltcR !lt_def \n  Num.Theory.normr_ge0 Num.Theory.normr_eq0 eq_sym=>/andP[->].\nall: rewrite Num.Theory.nnegrE lecE negb_and/= -Num.Theory.normr_gt0=>P2.\nmove: (le_lt_trans (normc_ge_Im _) P2). 2: move: (le_lt_trans (normc_ge_Re _) P2).\nall: rewrite ltcR raddfB/= -Num.Theory.normrN opprB =>P3.\nmove: (le_lt_trans (Num.Theory.ler_sub_dist _ _) P3).\nby rewrite Num.Theory.ltr_subl_addl -Num.Theory.ltr_subl_addr addrN=>->.\nmove/Num.Theory.ltr_distlC_addr: P3. \nby rewrite Num.Theory.ltr0_norm// addrN -Num.Theory.real_ltNge \n  ?real0// ?Num.Theory.num_real// orbC=>->.\nQed.\n\nLemma cclosed_ge (y:C) : closed [set x : C | y <= x].\nProof.\nrewrite (_ : mkset _ = ~` [set x | ~ 0 <= x - y]); last first.\nby rewrite predeqE=>x /=; rewrite notK Num.Theory.subr_ge0.\nrewrite closedC. move=> x /= /negP /Cnng_open [e egt0 Pe].\nexists e. by apply egt0. rewrite ball_normE=>z.\nrewrite /ball/=. suff ->: `|x-z|=`|(z-y)-(x-y)| by move=>/Pe/negP.\nby rewrite opprB addrA addrNK -Num.Internals.normrN opprB.\nQed.\n\nLemma cclosed_le (y : C) : closed [set x : C | x <= y].\nProof.\nrewrite (_ : mkset _ = ~` [set x | ~ 0 <= y - x]); last first.\nby rewrite predeqE=>x /=; rewrite notK Num.Theory.subr_ge0.\nrewrite closedC. move=> x /= /negP/Cnng_open [e egt0 Pe].\nexists e. by apply egt0. rewrite ball_normE=>z.\nrewrite /ball/=. suff ->: `|x-z|=`|(y-z)-(y-x)| by move=>/Pe/negP.\nby rewrite opprB [in RHS]addrC addrA addrNK.\nQed.\n\nLemma cclosed_eq (y : C) : closed [set x : C | x = y].\nProof.\nrewrite (_ : mkset _ = [set x | x <= y] `&` [set x | y <= x]).\napply closedI. apply cclosed_le. apply cclosed_ge.\napply/funext=>x /=. rewrite propeqE. split=>[->//|[P1 P2]].\nby apply/eqP; rewrite eq_le P1 P2.\nQed.\n\nLemma clim_ge_near (x : C) (u : C ^nat) : \n  cvg u -> (\\forall n \\near \\oo, x <= u n) -> x <= lim u.\nProof. by move=> /[swap] /(closed_cvg (>= x))P; apply/P/cclosed_ge. Qed.\n\nLemma clim_le_near (x : C) (u : C ^nat) : \n  cvg u -> (\\forall n \\near \\oo, x >= u n) -> x >= lim u.\nProof. by move=> /[swap] /(closed_cvg (fun y => y <= x))P; apply/P/cclosed_le. Qed.\n\nLemma lt_clim (u : C ^nat) (x : C) : nondecreasing_seq u -> cvg u -> x < lim u ->\n  \\forall n \\near \\oo, x <= u n.\nProof.\nmove=> ndu cu Ml; have [[n Mun]|/forallNP Mu] := pselect (exists n, x <= u n).\n  near=> m; suff : u n <= u m by exact: le_trans.\n  by near: m; exists n.+1 => // p q; apply/ndu/ltnW.\nhave Cn n : comparable x (u n) by apply/(Num.Theory.comparabler_trans \n  (lt_comparable Ml))/ge_comparable/cnondecreasing_cvg_le.\nhave {}Mu : forall y, x > u y. move=> y. rewrite comparable_ltNge. by apply/negP.\nby rewrite comparable_sym.\nhave : lim u <= x by apply clim_le_near => //; near=> m; apply/ltW/Mu.\nby move/(lt_le_trans Ml); rewrite ltxx.\nUnshelve. all: by end_near.\nQed.\n\nLemma gt_clim (u : C ^nat) (x : C) : nonincreasing_seq u -> cvg u -> x > lim u ->\n  \\forall n \\near \\oo, x >= u n.\nProof.\nrewrite -nondecreasing_opp=>P1 P2.\nrewrite -Num.Theory.ltr_opp2 -climN// =>P3.\nmove: (lt_clim P1 (is_ccvgN P2) P3)=>[N Sn Pn].\nexists N=>// n. move: (Pn n). \nby rewrite /= {2}/GRing.opp/= Num.Theory.ler_opp2.\nQed.\n\nLemma ler_clim_near (u_ v_ : C ^nat) : cvg u_ -> cvg v_ ->\n  (\\forall n \\near \\oo, u_ n <= v_ n) -> lim u_ <= lim v_.\nProof.\nmove=> uv cu cv; rewrite -Num.Theory.subr_ge0 -climB=>[|//|]; last by apply uv.\napply: clim_ge_near; first by apply: is_ccvgB;[| apply uv].\nby apply: filterS cv => n; rewrite Num.Theory.subr_ge0.\nQed.\n\nLemma clim_ge (x : C) (u : C ^nat) : cvg u -> (forall n, x <= u n) -> x <= lim u.\nProof. by move=>P1 P2; apply/clim_ge_near=>//; exists 0%N=>//. Qed.\n\nLemma clim_le (x : C) (u : C ^nat) : cvg u -> (forall n, u n <= x) -> lim u <= x.\nProof. by move=>P1 P2; apply/clim_le_near=>//; exists 0%N=>//. Qed.\n\nLemma ler_clim (u_ v_ : C^nat) : cvg u_ -> cvg v_ ->\n  (forall n, u_ n <= v_ n) -> lim u_ <= lim v_.\nProof. by move=>P1 P2 P3; apply/ler_clim_near=>//; exists 0%N=>//. Qed.\n\nEnd complex_monotone.\n\nSection matrix_CompleteNormedModule.\nVariables (R: realType) (m n : nat).\n\nCanonical matrix_completeNormedModule :=\n  [completeNormedModType R of 'M[R]_(m.+1, n.+1)].\n\nEnd matrix_CompleteNormedModule.\n\nModule VNorm.\n\nSection Definitions.\nVariables (R: numDomainType) (T : lmodType R).\n\nStructure vnorm := Vnorm {\n  operator : T -> R;\n  _ : forall x y, operator (x + y) <= operator x + operator y;\n  _ : forall x, operator x = 0 -> x = 0;\n  _ : forall a x, operator (a *: x) = `|a| * operator x;\n}.\nLocal Coercion operator : vnorm >-> Funclass.\n\nLet op_id (op1 op2 : T -> R) := phant_id op1 op2.\n\nDefinition clone_vnorm op :=\n  fun (opL : vnorm) & op_id opL op =>\n  fun optr op0 opz (opL' := @Vnorm op optr op0 opz)\n    & phant_id opL' opL => opL'.\n\nEnd Definitions.\n\nModule Import Exports.\nCoercion operator : vnorm >-> Funclass.\nNotation vnorm := vnorm.\nNotation Vnorm := Vnorm.\nNotation \"[ 'vnorm' 'of' f ]\" := (@clone_vnorm _ _ f _ id _ _ _ id)\n  (at level 0, format\"[ 'vnorm'  'of'  f ]\") : form_scope.\nEnd Exports.\n\nEnd VNorm.\nImport VNorm.Exports.\n\nSection VNormTheory.\nImport Num.Def Num.Theory.\nVariable (R: numDomainType) (V: lmodType R) (mnorm : vnorm V).\nLocal Notation \"`[ x ]\" := (mnorm x).\n\nLemma lev_norm_add x y : (`[ x + y ]) <= (`[ x ] + `[ y ]).\nProof. by case: mnorm x y. Qed.\n\nLemma normv0_eq0 x: `[ x ] = 0 -> x = 0.\nProof. by case: mnorm x. Qed.\n\nLemma normvZ a x: `[ a *: x ] = `|a| * `[ x ].\nProof. by case: mnorm a x. Qed.\n\nLemma normv0 : `[ 0 ] = 0.\nProof. have <-: 0 *: 0 = (0 : V) by rewrite scaler0.\nby rewrite normvZ normr0 mul0r. Qed.\n\nLemma normv0P A : reflect (`[ A ] = 0) (A == 0).\nProof. by apply: (iffP eqP)=> [->|/normv0_eq0 //]; apply: normv0. Qed.\n\nDefinition normv_eq0 A := sameP (`[ A ] =P 0) (normv0P A).\n\nLemma normvMn x n : `[ x *+ n] = `[x] *+ n.\nProof. by rewrite -scaler_nat normvZ normr_nat mulr_natl. Qed.\n  \nLemma normvN x : `[ - x ] = `[ x ].\nProof. by rewrite -scaleN1r normvZ normrN normr1 mul1r. Qed.\n\nLemma normv_ge0 : forall x, `[ x ] >= 0.\nProof.\nmove=>x; move: (lev_norm_add x (-x)).\nby rewrite addrN normvN -mulr2n normv0 pmulrn_lge0.\nQed.\n\nLemma normv_nneg A : `[ A ] \\is Num.nneg.\nProof. by rewrite qualifE normv_ge0. Qed.\n\nLemma normv_real x : `[ x ] \\is Num.real.\nProof. apply/ger0_real/normv_ge0. Qed.\n\nLemma normv_gt0 x : `[ x ] > 0 = (x != 0).\nProof. by rewrite lt_def normv_ge0 andbT normv_eq0. Qed.\n\nLemma lev_norm_sub v w : `[v - w] <= `[v] + `[w].\nProof. by rewrite (le_trans (lev_norm_add _ _)) ?normvN. Qed.\n\nLemma lev_dist_add u v w : `[v-w] <= `[v-u] + `[u-w].\nProof. by rewrite (le_trans _ (lev_norm_add _ _)) // addrA addrNK. Qed.\n\nLemma lev_sub_norm_add v w : `[v] - `[w] <= `[v+w].\nProof.\nrewrite -{1}[v](addrK w) lter_sub_addl.\nby rewrite (le_trans (lev_norm_add _ _)) // addrC normvN.\nQed.\n\nLemma lev_sub_dist v w : `[v] - `[w] <= `[v-w].\nProof. by rewrite -[`[w]]normvN lev_sub_norm_add. Qed.\n\nLemma lev_dist_dist v w : `| `[v] - `[w] | <= `[v-w].\nProof.\nhave [ | | _ | _ ] // := @real_leP _ (mnorm v) (mnorm w); last by rewrite lev_sub_dist.\n1,2: by rewrite realE normv_ge0. by rewrite -(normvN (v-w)) opprB lev_sub_dist.\nQed.\n\nLemma normv_sum (I: finType) (r : seq I) (P: pred I) f :\n  mnorm (\\sum_(i <- r | P i) f i) <= \\sum_(i <- r | P i) mnorm (f i).\nProof.\nelim: r => [|x r IH]; first by rewrite !big_nil normv0.\nrewrite !big_cons. case: (P x)=>//.\napply (le_trans (lev_norm_add _ _)). by apply ler_add.\nQed.\n\nDefinition cauchy_seqv  (u: nat -> V) := \n  forall e : R, 0 < e -> exists N : nat, \n    forall s t, (N <= s)%N -> (N <= t)%N -> mnorm (u s - u t) < e.\n\nLemma cauchy_seqv_cst x : cauchy_seqv (fun=>x).\nby move=>e egt0; exists 0%N=> s t _ _; rewrite subrr normv0. Qed.\n\nEnd VNormTheory.\n\n(* vorder is regarded as operator rather than a type *)\n(* so we can use different vorder of the same type   *)\n\nFact vorder_display : unit. Proof. by []. Qed.\nNotation \"x '⊑' y\" := (@Order.le vorder_display _ x y) (at level 70, y at next level).\nNotation \"x '⊏' y\" := (@Order.lt vorder_display _ x y) (at level 70, y at next level).\nNotation \"x '⊑' y '⊑' z\" := ((x ⊑ y) && (y ⊑ z)) (at level 70, y at next level).\nNotation \"'ubounded_by' b f\" := (forall i, f i ⊑ b) (at level 10, b, f at next level).\nNotation \"'lbounded_by' b f\" := (forall i, b ⊑ f i) (at level 10, b, f at next level).\nNotation \"'nondecreasing_seq' f\" := ({homo f : n m / (n <= m)%nat >-> (n <= m)%O})\n  (at level 10).\nNotation \"'nonincreasing_seq' f\" := ({homo f : n m / (n <= m)%nat >-> (n >= m)%O})\n  (at level 10).\nNotation \"'increasing_seq' f\" := ({mono f : n m / (n <= m)%nat >-> (n <= m)%O})\n  (at level 10).\nNotation \"'decreasing_seq' f\" := ({mono f : n m / (n <= m)%nat >-> (n >= m)%O})\n  (at level 10).\n\nModule VOrder.\n\nRecord mixin_of (R: numFieldType) (T: lmodType R)\n       (Rorder : Order.POrder.mixin_of (Equality.class T))\n       (le_op := Order.POrder.le Rorder) (lt_op := Order.POrder.lt Rorder)\n  := Mixin {\n  _  : forall (z x y : T), le_op x y -> le_op (x + z) (y + z);\n  _  : forall (e : R) (x y : T), 0 < e -> le_op x y -> le_op (e *: x) (e *: y);\n}.\n\nSection ClassDef.\nVariable (R: numFieldType).\nSet Primitive Projections.\nRecord class_of T := Class {\n  base : GRing.Lmodule.class_of R T;\n  order_mixin : Order.POrder.mixin_of (Equality.class (GRing.Lmodule.Pack _ base));\n  mixin : mixin_of order_mixin;\n}.\nUnset Primitive Projections.\n\nLocal Coercion base : class_of >-> GRing.Lmodule.class_of.\nLocal Coercion order_base T (class_of_T : class_of T) :=\n  @Order.POrder.Class _ class_of_T (order_mixin class_of_T).\n\nStructure type (phR : phant R) := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariables (phR : phant R) (T : Type) (cT : type phR).\nDefinition class := let: Pack _ c  as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack phR T c.\nLet xT := let: Pack T _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack (b0 : GRing.Lmodule.class_of R T) om0\n           (m0 : @mixin_of R (GRing.Lmodule.Pack _ b0) om0) := \n  fun bT (b : GRing.Lmodule.class_of R T)\n      & phant_id (@GRing.Lmodule.class R (Phant R) bT) b =>\n  fun om & phant_id om0 om =>\n  fun m & phant_id m0 m =>\n  @Pack phR T (@Class T b om m).\n\nDefinition eqType := @Equality.Pack cT xclass.\nDefinition choiceType := @Choice.Pack cT xclass.\nDefinition zmodType := @GRing.Zmodule.Pack cT xclass.\nDefinition lmodType := @GRing.Lmodule.Pack R phR cT xclass.\nDefinition porderType := @Order.POrder.Pack vorder_display cT xclass.\nDefinition porder_zmodType := @GRing.Zmodule.Pack porderType xclass.\nDefinition porder_lmodType := @GRing.Lmodule.Pack R phR porderType xclass.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion sort : type >-> Sortclass.\nCoercion base  : class_of >-> GRing.Lmodule.class_of.\nCoercion order_base : class_of >-> Order.POrder.class_of.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> GRing.Zmodule.type.\nCanonical zmodType.\nCoercion lmodType : type >-> GRing.Lmodule.type.\nCanonical lmodType.\nCoercion porderType : type >-> Order.POrder.type.\nCanonical porderType.\nCanonical porder_zmodType.\nCanonical porder_lmodType.\nNotation vorderType R := (type (Phant R)).\nNotation VOrderType R T m := (@pack _ (Phant R) T _ _ m _   _ id _ id _ id).\nNotation VOrderMixin := Mixin.\nNotation \"[ 'vorderType' R 'of' T 'for' cT ]\" := (@clone _ (Phant R) T cT _ idfun)\n  (at level 0, format \"[ 'vorderType'  R  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'vorderType' R 'of' T ]\" := (@clone _ (Phant R) T _ _ id)\n  (at level 0, format \"[ 'vorderType'  R  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd VOrder.\nImport VOrder.Exports.\n\nModule CanVOrder.\n\nRecord mixin_of (R: numFieldType) (T: vorderType R)\n  := Mixin {\n  _  : forall (x : T) (e : R), (0 : T) ⊏ x -> (0 : T) ⊑ (e *: x) = (0 <= e);\n}.\n\nSection ClassDef.\nVariable (R: numFieldType).\nSet Primitive Projections.\nRecord class_of T := Class {\n  base : VOrder.class_of R T;\n  mixin : mixin_of (VOrder.Pack _ base);\n}.\nUnset Primitive Projections.\n\nLocal Coercion base : class_of >-> VOrder.class_of.\n\nStructure type (phR : phant R) := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariables (phR : phant R) (T : Type) (cT : type phR).\nDefinition class := let: Pack _ c  as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack phR T c.\nLet xT := let: Pack T _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack b0 (m0 : mixin_of (@VOrder.Pack _ (Phant R) T b0)) :=\n  fun bT b & phant_id (@VOrder.class _ (Phant R) bT) b =>\n  fun    m & phant_id m0 m => Pack phR (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT xclass.\nDefinition choiceType := @Choice.Pack cT xclass.\nDefinition zmodType := @GRing.Zmodule.Pack cT xclass.\nDefinition lmodType := @GRing.Lmodule.Pack R phR cT xclass.\nDefinition porderType := @Order.POrder.Pack vorder_display cT xclass.\nDefinition porder_zmodType := @GRing.Zmodule.Pack porderType xclass.\nDefinition porder_lmodType := @GRing.Lmodule.Pack R phR porderType xclass.\nDefinition vorderType := @VOrder.Pack R phR cT xclass.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion sort : type >-> Sortclass.\nCoercion base  : class_of >-> VOrder.class_of.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> GRing.Zmodule.type.\nCanonical zmodType.\nCoercion lmodType : type >-> GRing.Lmodule.type.\nCanonical lmodType.\nCoercion porderType : type >-> Order.POrder.type.\nCanonical porderType.\nCanonical porder_zmodType.\nCanonical porder_lmodType.\nCoercion vorderType : type >-> VOrder.type.\nCanonical vorderType.\nNotation canVOrderType R := (type (Phant R)).\nNotation CanVOrderType R T m := (@pack _ (Phant R) T _ m _ _ id _ id).\nNotation CanVOrderMixin := Mixin.\nNotation \"[ 'canVOrderType' R 'of' T 'for' cT ]\" := (@clone _ (Phant R) T cT _ idfun)\n  (at level 0, format \"[ 'canVOrderType'  R  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'canVOrderType' R 'of' T ]\" := (@clone _ (Phant R) T _ _ id)\n  (at level 0, format \"[ 'canVOrderType'  R  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd CanVOrder.\nImport CanVOrder.Exports.\n\nLemma scalerNN (R : ringType) (V : lmodType R) (a : R) (x : V) : \n  (- a) *: (- x) = a *: x.\nProof. by rewrite scalerN scaleNr opprK. Qed.\n\nSection VOrderTheory.\nVariable (R: numFieldType) (T : vorderType R).\nImplicit Type (x y z : T) (a b c : R).\nLocal Notation \"'0\" := (0 : T).\n\nLemma lev_add2rP z x y : x ⊑ y -> x + z ⊑ y + z.\nProof. by move: x y z; case: T=>?[??[P?]] x y z; apply P. Qed.\nLemma lev_pscale2lP (e : R) x y : 0 < e -> x ⊑ y -> (e *: x) ⊑ (e *: y).\nProof. by move: e x y; case: T=>?[??[? P]] e x y; apply P. Qed.\n\nLemma subv_ge0 x y : ('0 ⊑ x - y) = (y ⊑ x).\nProof. \napply/Bool.eq_iff_eq_true; split=>[/(@lev_add2rP y)|/(@lev_add2rP (-y))];\nby rewrite ?addrNK ?add0r// addrN.\nQed.\n\nLemma subv_gt0 x y : ('0 ⊏ y - x) = (x ⊏ y).\nProof. by rewrite !lt_def subr_eq0 subv_ge0. Qed.\nLemma subv_le0  x y : (y - x ⊑ 0) = (y ⊑ x).\nProof. by rewrite -subv_ge0 opprB add0r subv_ge0. Qed.\nLemma subv_lt0  x y : (y - x ⊏ 0) = (y ⊏ x).\nProof. by rewrite -subv_gt0 opprB add0r subv_gt0. Qed.\n\nDefinition subv_lte0 := (subv_le0, subv_lt0).\nDefinition subv_gte0 := (subv_ge0, subv_gt0).\nDefinition subv_cp0 := (subv_lte0, subv_gte0).\n\nLemma lev_opp2 : {mono (-%R : T -> T) : x y /~ x ⊑ y }.\nProof. by move=>x y; rewrite -subv_ge0 opprK addrC subv_ge0. Qed.\nHint Resolve lev_opp2 : core.\n\nLemma ltv_opp2 : {mono (-%R : T -> T) : x y /~ x ⊏ y }.\nProof. by move=> x y /=; rewrite leW_nmono. Qed.\nHint Resolve ltv_opp2 : core.\nDefinition ltev_opp2 := (lev_opp2, ltv_opp2).\n\nLemma addv_ge0 x y : '0 ⊑ x -> '0 ⊑ y -> '0 ⊑ x + y.\nProof.\nby move=>P1 P2; apply: (le_trans P1); rewrite -subv_ge0 addrC addrA addNr add0r.\nQed.\n\nLemma addv_gt0 x y : '0 ⊏ x -> '0 ⊏ y -> '0 ⊏ x + y.\nProof.\nrewrite !lt_def=>/andP[/negPf Pf Pf1]/andP[Pg Pg1]; rewrite (addv_ge0 Pf1 Pg1) andbT.\ncase: eqP=>//= P1; move: Pg1; rewrite -P1 -subv_ge0 opprD addrC addrNK -oppr0 lev_opp2=>P2.\nby rewrite -Pf eq_le Pf1 P2.\nQed.\n\nLemma le0v x : ('0 ⊑ x) = (x == 0) || ('0 ⊏ x).\nProof. by rewrite lt_def; case: eqP => // ->; rewrite lexx. Qed.\n\nLemma lev_add2r x : {mono +%R^~ x : y z / y ⊑ z}.\nProof. by move=>y z; rewrite -subv_ge0 opprD addrACA addrN addr0 subv_ge0. Qed.\n\nLemma lev_oppr x y : (x ⊑ - y) = (y ⊑ - x).\nProof. by rewrite (monoRL opprK lev_opp2). Qed.\n\nLemma ltv_oppr x y : (x ⊏ - y) = (y ⊏ - x).\nProof. by rewrite (monoRL opprK (leW_nmono lev_opp2)). Qed.\n\nDefinition ltev_oppr := (lev_oppr, ltv_oppr).\n\nLemma lev_oppl x y : (- x ⊑ y) = (- y ⊑ x).\nProof. by rewrite (monoLR opprK lev_opp2). Qed.\n\nLemma ltv_oppl x y : (- x ⊏ y) = (- y ⊏ x).\nProof. by rewrite (monoLR opprK (leW_nmono lev_opp2)). Qed.\n\nDefinition ltev_oppl := (lev_oppl, ltv_oppl).\n\nLemma oppv_ge0 x : ('0 ⊑ - x) = (x ⊑ 0).\nProof. by rewrite ltev_oppr oppr0. Qed.\n\nLemma oppv_gt0 x : ('0 ⊏ - x) = (x ⊏ 0).\nProof. by rewrite ltev_oppr oppr0. Qed.\n\nDefinition oppv_gte0 := (oppv_ge0, oppv_gt0).\n\nLemma oppv_le0 x : (- x ⊑ 0) = ('0 ⊑ x).\nProof. by rewrite ltev_oppl oppr0. Qed.\n\nLemma oppv_lt0 x : (- x ⊏ 0) = ('0 ⊏ x).\nProof. by rewrite ltev_oppl oppr0. Qed.\n\nDefinition oppv_lte0 := (oppv_le0, oppv_lt0).\nDefinition oppv_cp0 := (oppv_gte0, oppv_lte0).\nDefinition ltev_oppE := (oppv_cp0, ltev_opp2).\n\nLemma gev0_cp x : '0 ⊑ x -> (- x ⊑ 0) * (- x ⊑ x).\nProof. by move=> hx; rewrite oppv_cp0 hx (@le_trans _ _ '0) ?oppv_cp0. Qed.\n\nLemma gtv0_cp x : '0 ⊏ x ->\n  ('0 ⊑ x) * (- x ⊑ 0) * (- x ⊑ x) * (- x ⊏ 0) * (- x ⊏ x).\nProof.\nmove=> hx; move: (ltW hx) => hx'; rewrite !gev0_cp hx'=>[|//|//].\nby rewrite oppv_cp0 hx (@lt_trans _ _ '0) ?oppv_cp0.\nQed.\n\nLemma lev0_cp x : x ⊑ 0 -> ('0 ⊑ - x) * (x ⊑ - x).\nProof. by move=> hx; rewrite oppv_cp0 hx (@le_trans _ _ '0) ?oppv_cp0. Qed.\n\nLemma ltv0_cp x :\n  x ⊏ 0 -> (x ⊑ 0) * ('0 ⊑ - x) * (x ⊑ - x) * ('0 ⊏ - x) * (x ⊏ - x).\nProof.\nmove=> hx; move: (ltW hx) => hx'; rewrite !lev0_cp hx' =>[|//|//].\nby rewrite oppv_cp0 hx (@lt_trans _ _ '0) ?oppv_cp0.\nQed.\n\n(* Monotony of addition *)\nLemma lev_add2l x : {mono +%R x : y z / y ⊑ z}.\nProof. by move=>y z; rewrite ![x + _]addrC lev_add2r. Qed.\n\nLemma ltv_add2l x : {mono +%R x : y z / y ⊏ z}.\nProof. by move=> y z /=; rewrite (leW_mono (lev_add2l _)). Qed.\n\nLemma ltv_add2r x : {mono +%R^~ x : y z / y ⊏ z}.\nProof. by move=> y z /=; rewrite (leW_mono (lev_add2r _)). Qed.\n\nDefinition lev_add2 := (lev_add2l, lev_add2r).\nDefinition ltv_add2 := (ltv_add2l, ltv_add2r).\nDefinition ltev_add2 := (lev_add2, ltv_add2).\n\n(* Addition, subtraction and transitivity *)\nLemma lev_add x y z t : x ⊑ y -> z ⊑ t -> x + z ⊑ y + t.\nProof. by move=> lxy lzt; rewrite (@le_trans _ _ (y + z)) ?ltev_add2. Qed.\n\nLemma lev_lt_add x y z t : x ⊑ y -> z ⊏ t -> x + z ⊏ y + t.\nProof. by move=> lxy lzt; rewrite (@le_lt_trans _ _ (y + z)) ?ltev_add2. Qed.\n\nLemma ltv_le_add x y z t : x ⊏ y -> z ⊑ t -> x + z ⊏ y + t.\nProof. by move=> lxy lzt; rewrite (@lt_le_trans _ _ (y + z)) ?ltev_add2. Qed.\n\nLemma ltv_add x y z t : x ⊏ y -> z ⊏ t -> x + z ⊏ y + t.\nProof. by move=> lxy lzt; rewrite ltv_le_add ?ltW. Qed.\n\nLemma lev_sub x y z t : x ⊑ y -> t ⊑ z -> x - z ⊑ y - t.\nProof. by move=> lxy ltz; rewrite lev_add ?ltev_opp2. Qed.\n\nLemma lev_lt_sub x y z t : x ⊑ y -> t ⊏ z -> x - z ⊏ y - t.\nProof. by move=> lxy lzt; rewrite lev_lt_add ?ltev_opp2. Qed.\n\nLemma ltv_le_sub x y z t : x ⊏ y -> t ⊑ z -> x - z ⊏ y - t.\nProof. by move=> lxy lzt; rewrite ltv_le_add ?ltev_opp2. Qed.\n\nLemma ltv_sub x y z t : x ⊏ y -> t ⊏ z -> x - z ⊏ y - t.\nProof. by move=> lxy lzt; rewrite ltv_add ?ltev_opp2. Qed.\n\nLemma lev_subl_addr x y z : (x - y ⊑ z) = (x ⊑ z + y).\nProof. by rewrite (monoLR (addrK _) (lev_add2r _)). Qed.\n\nLemma ltv_subl_addr x y z : (x - y ⊏ z) = (x ⊏ z + y).\nProof. by rewrite (monoLR (addrK _) (ltv_add2r _)). Qed.\n\nLemma lev_subr_addr x y z : (x ⊑ y - z) = (x + z ⊑ y).\nProof. by rewrite (monoLR (addrNK _) (lev_add2r _)). Qed.\n\nLemma ltv_subr_addr x y z : (x ⊏ y - z) = (x + z ⊏ y).\nProof. by rewrite (monoLR (addrNK _) (ltv_add2r _)). Qed.\n\nDefinition lev_sub_addr := (lev_subl_addr, lev_subr_addr).\nDefinition ltv_sub_addr := (ltv_subl_addr, ltv_subr_addr).\nDefinition ltev_sub_addr := (lev_sub_addr, ltv_sub_addr).\n\nLemma lev_subl_addl x y z : (x - y ⊑ z) = (x ⊑ y + z).\nProof. by rewrite ltev_sub_addr addrC. Qed.\n\nLemma ltv_subl_addl x y z : (x - y ⊏ z) = (x ⊏ y + z).\nProof. by rewrite ltev_sub_addr addrC. Qed.\n\nLemma lev_subr_addl x y z : (x ⊑ y - z) = (z + x ⊑ y).\nProof. by rewrite ltev_sub_addr addrC. Qed.\n\nLemma ltv_subr_addl x y z : (x ⊏ y - z) = (z + x ⊏ y).\nProof. by rewrite ltev_sub_addr addrC. Qed.\n\nDefinition lev_sub_addl := (lev_subl_addl, lev_subr_addl).\nDefinition ltv_sub_addl := (ltv_subl_addl, ltv_subr_addl).\nDefinition ltev_sub_addl := (lev_sub_addl, ltv_sub_addl).\n\nLemma lev_addl x y : (x ⊑ x + y) = ('0 ⊑ y).\nProof. by rewrite -{1}[x]addr0 ltev_add2. Qed.\n\nLemma ltv_addl x y : (x ⊏ x + y) = ('0 ⊏ y).\nProof. by rewrite -{1}[x]addr0 ltev_add2. Qed.\n\nLemma lev_addr x y : (x ⊑ y + x) = ('0 ⊑ y).\nProof. by rewrite -{1}[x]add0r ltev_add2. Qed.\n\nLemma ltv_addr x y : (x ⊏ y + x) = ('0 ⊏ y).\nProof. by rewrite -{1}[x]add0r ltev_add2. Qed.\n\nLemma gev_addl x y : (x + y ⊑ x) = (y ⊑ 0).\nProof. by rewrite -{2}[x]addr0 ltev_add2. Qed.\n\nLemma gtv_addl x y : (x + y ⊏ x) = (y ⊏ 0).\nProof. by rewrite -{2}[x]addr0 ltev_add2. Qed.\n\nLemma gev_addr x y : (y + x ⊑ x) = (y ⊑ 0).\nProof. by rewrite -{2}[x]add0r ltev_add2. Qed.\n\nLemma gtv_addr x y : (y + x ⊏ x) = (y ⊏ 0).\nProof. by rewrite -{2}[x]add0r ltev_add2. Qed.\n\nDefinition cpv_add := (lev_addl, lev_addr, gev_addl, gev_addl,\n                       ltv_addl, ltv_addr, gtv_addl, gtv_addl).\n\n(* Addition with levt member knwon to be positive/negative *)\nLemma lev_paddl y x z : '0 ⊑ x -> y ⊑ z -> y ⊑ x + z.\nProof. by move=> *; rewrite -[y]add0r lev_add. Qed.\n\nLemma ltv_paddl y x z : '0 ⊑ x -> y ⊏ z -> y ⊏ x + z.\nProof. by move=> *; rewrite -[y]add0r lev_lt_add. Qed.\n\nLemma ltv_spaddl y x z : '0 ⊏ x -> y ⊑ z -> y ⊏ x + z.\nProof. by move=> *; rewrite -[y]add0r ltv_le_add. Qed.\n\nLemma ltv_spsaddl y x z : '0 ⊏ x -> y ⊏ z -> y ⊏ x + z.\nProof. by move=> *; rewrite -[y]add0r ltv_add. Qed.\n\nLemma lev_naddl y x z : x ⊑ 0 -> y ⊑ z -> x + y ⊑ z.\nProof. by move=> *; rewrite -[z]add0r lev_add. Qed.\n\nLemma ltv_naddl y x z : x ⊑ 0 -> y ⊏ z -> x + y ⊏ z.\nProof. by move=> *; rewrite -[z]add0r lev_lt_add. Qed.\n\nLemma ltv_snaddl y x z : x ⊏ 0 -> y ⊑ z -> x + y ⊏ z.\nProof. by move=> *; rewrite -[z]add0r ltv_le_add. Qed.\n\nLemma ltv_snsaddl y x z : x ⊏ 0 -> y ⊏ z -> x + y ⊏ z.\nProof. by move=> *; rewrite -[z]add0r ltv_add. Qed.\n\n(* Addition with right member we know positive/negative *)\nLemma lev_paddr y x z : '0 ⊑ x -> y ⊑ z -> y ⊑ z + x.\nProof. by move=> *; rewrite [_ + x]addrC lev_paddl. Qed.\n\nLemma ltv_paddr y x z : '0 ⊑ x -> y ⊏ z -> y ⊏ z + x.\nProof. by move=> *; rewrite [_ + x]addrC ltv_paddl. Qed.\n\nLemma ltv_spaddr y x z : '0 ⊏ x -> y ⊑ z -> y ⊏ z + x.\nProof. by move=> *; rewrite [_ + x]addrC ltv_spaddl. Qed.\n\nLemma ltv_spsaddr y x z : '0 ⊏ x -> y ⊏ z -> y ⊏ z + x.\nProof. by move=> *; rewrite [_ + x]addrC ltv_spsaddl. Qed.\n\nLemma lev_naddr y x z : x ⊑ 0 -> y ⊑ z -> y + x ⊑ z.\nProof. by move=> *; rewrite [_ + x]addrC lev_naddl. Qed.\n\nLemma ltv_naddr y x z : x ⊑ 0 -> y ⊏ z -> y + x ⊏ z.\nProof. by move=> *; rewrite [_ + x]addrC ltv_naddl. Qed.\n\nLemma ltv_snaddr y x z : x ⊏ 0 -> y ⊑ z -> y + x ⊏ z.\nProof. by move=> *; rewrite [_ + x]addrC ltv_snaddl. Qed.\n\nLemma ltv_snsaddr y x z : x ⊏ 0 -> y ⊏ z -> y + x ⊏ z.\nProof. by move=> *; rewrite [_ + x]addrC ltv_snsaddl. Qed.\n\n(* x and y have the same sign and their sum is null *)\nLemma paddv_eq0 x y :\n  '0 ⊑ x -> '0 ⊑ y -> (x + y == 0) = (x == 0) && (y == 0).\nProof.\nrewrite le0v; case/orP=> [/eqP->|hx]; first by rewrite add0r eqxx.\nby rewrite (gt_eqF hx) /= => hy; rewrite gt_eqF ?ltv_spaddl.\nQed.\n\nLemma naddv_eq0 x y :\n  x ⊑ 0 -> y ⊑ 0 -> (x + y == 0) = (x == 0) && (y == 0).\nProof.\nby move=> lex0 ley0; rewrite -oppr_eq0 opprD paddv_eq0 ?oppv_cp0 ?oppr_eq0.\nQed.\n\nLemma addv_ss_eq0 x y :\n    ('0 ⊑ x) && ('0 ⊑ y) || (x ⊑ 0) && (y ⊑ 0) ->\n  (x + y == 0) = (x == 0) && (y == 0).\nProof. by case/orP=> /andP []; [apply: paddv_eq0 | apply: naddv_eq0]. Qed.\n\n(* big sum and lev *)\nLemma sumv_ge0 I (r : seq I) (P : pred I) (F : I -> T) :\n  (forall i, P i -> ('0 ⊑ F i)) -> '0 ⊑ \\sum_(i <- r | P i) (F i).\nProof. exact: (@big_ind T _ '0 _ (lexx '0) (@lev_paddl '0)). Qed.  \n\nLemma lev_sum I (r : seq I) (P : pred I) (F G : I -> T) :\n    (forall i, P i -> F i ⊑ G i) ->\n  \\sum_(i <- r | P i) F i ⊑ \\sum_(i <- r | P i) G i.\nProof. exact: (big_ind2 _ (lexx _) lev_add). Qed.\n\nLemma lev_sum_nat (m n : nat) (F G : nat -> T) :\n  (forall i, (m <= i < n)%N -> F i ⊑ G i) ->\n  \\sum_(m <= i < n) F i ⊑ \\sum_(m <= i < n) G i.\nProof. by move=> le_FG; rewrite !big_nat lev_sum. Qed.\n\nLemma psumv_eq0 (I : eqType) (r : seq I) (P : pred I) (F : I -> T) :\n    (forall i, P i -> '0 ⊑ F i) ->\n  (\\sum_(i <- r | P i) (F i) == 0) = (all (fun i => (P i) ==> (F i == 0)) r).\nProof.\nelim: r=> [|a r ihr hr] /=; rewrite (big_nil, big_cons); first by rewrite eqxx.\nby case: ifP=> pa /=; rewrite ?paddv_eq0 ?ihr ?hr ?sumv_ge0.\nQed.\n\n(* :TODO: Cyril : See which form to keep *)\nLemma psumv_eq0P (I : finType) (P : pred I) (F : I -> T) :\n     (forall i, P i -> '0 ⊑ F i) -> \\sum_(i | P i) F i = 0 ->\n  (forall i, P i -> F i = 0).\nProof.\nmove=> F_ge0 /eqP; rewrite psumv_eq0=>[|//].\nrewrite -big_all big_andE => /forallP hF i Pi.\nby move: (hF i); rewrite implyTb Pi /= => /eqP.\nQed.\n\nLemma lt0v x : ('0 ⊏ x) = (x != 0) && ('0 ⊑ x). Proof. by rewrite lt_def. Qed.\n\nLemma lt0v_neq0 x : '0 ⊏ x -> x != 0.\nProof. by rewrite lt0v; case/andP. Qed.\n\nLemma ltv0_neq0 x : x ⊏ 0 -> x != 0.\nProof. by rewrite lt_neqAle; case/andP. Qed.\n\nImport Num.Theory.\n\nLemma pscalev_rge0 a y : 0 < a -> ('0 ⊑ a *: y) = ('0 ⊑ y).\nProof.\nmove=>Pa; apply/Bool.eq_iff_eq_true; split=>P.\nhave P1 : (a^-1 * a) = 1 by rewrite mulVf// lt0r_neq0.\nby rewrite -[y]scale1r -(scaler0 _ a^-1) -P1 -scalerA lev_pscale2lP// invr_gt0.\nby rewrite -(scaler0 _ a) lev_pscale2lP.\nQed.\n\nLemma pscalev_rgt0 a y : 0 < a -> ('0 ⊏ a *: y) = ('0 ⊏ y).\nProof.\nby move=>Pa; move: {+}Pa; rewrite !lt_def \n  scaler_eq0 negb_or pscalev_rge0// =>/andP[->_/=].\nQed.\n\n(* mulr and lev/ltv *)\nLemma lev_pscale2l a : 0 < a -> {mono ( *:%R a : T -> T) : x y / x ⊑ y}.\nProof.\nby move=> x_gt0 y z /=; rewrite -subv_ge0 -scalerBr pscalev_rge0// subv_ge0.\nQed.\n\nLemma ltv_pscale2l a : 0 < a -> {mono ( *:%R a : T -> T) : x y / x ⊏ y}.\nProof. by move=> x_gt0; apply: leW_mono (lev_pscale2l _). Qed.\n\nDefinition ltev_pscale2l := (lev_pscale2l, ltv_pscale2l).\n\nLemma lev_nscale2l a : a < 0 -> {mono ( *:%R a : T -> T) : x y /~ x ⊑ y}.\nProof.\nby move=> x_lt0 y z /=; rewrite -lev_opp2 -!scaleNr lev_pscale2l ?oppr_gt0.\nQed.\n\nLemma ltv_nscale2l a : a < 0 -> {mono ( *:%R a : T -> T) : x y /~ x ⊏ y}.\nProof. by move=> x_lt0; apply: leW_nmono (lev_nscale2l _). Qed.\n\nDefinition ltev_nscale2l := (lev_nscale2l, ltv_nscale2l).\n\nLemma lev_wpscale2l a : 0 <= a -> {homo ( *:%R a : T -> T) : y z / y ⊑ z}.\nProof.\nby rewrite le0r => /orP[/eqP-> y z | /lev_pscale2l/mono2W//]; rewrite !scale0r.\nQed.\n\nLemma lev_wpscale2r x : '0 ⊑ x -> {homo *:%R^~ x : y z / (y <= z)%O}.\nProof.\nmove=>x_ge0 a b; rewrite -subr_ge0 -subv_ge0 -scalerBl le0r.\nby move=>/orP[/eqP->|/(pscalev_rge0 x)->//]; rewrite scale0r.\nQed.\n\nLemma lev_wnscale2l a : a <= 0 -> {homo ( *:%R a : T -> T) : y z /~ y ⊑ z}.\nProof.\nby move=> x_le0 y z leyz; rewrite -![a *: _]scalerNN lev_wpscale2l ?ltev_oppE// lter_oppE.\nQed.\n\nLemma lev_wnscale2r x : x ⊑ 0 -> {homo *:%R^~ x : y z /~ (y <= z)%O}.\nProof.\nby move=> x_le0 y z leyz; rewrite -![_ *: x]scalerNN lev_wpscale2r ?ltev_oppE// lter_oppE.\nQed.\n\n(* Binary forms, for backchaining. *)\n\nLemma lev_pscale2 a b x y :\n  0 <= a -> '0 ⊑ x -> a <= b -> x ⊑ y -> a *: x ⊑ b *: y.\nProof.\nmove=> x1ge0 x2ge0 le_xy1 le_xy2; have y1ge0 := le_trans x1ge0 le_xy1.\nexact: le_trans (lev_wpscale2r x2ge0 le_xy1) (lev_wpscale2l y1ge0 le_xy2).\nQed.\n\nLemma ltv_pscale2 a b x y :\n  0 <= a -> '0 ⊑ x -> a < b -> x ⊏ y -> a *: x ⊏ b *: y.\nProof.\nmove=> x1ge0 x2ge0 lt_xy1 lt_xy2; have y1gt0 := le_lt_trans x1ge0 lt_xy1.\nby rewrite (le_lt_trans (lev_wpscale2r x2ge0 (ltW lt_xy1))) ?ltv_pscale2l.\nQed.\n\n(* complement for x *+ n and <= or < *)\nLocal Notation natmul := (@GRing.natmul T).\n\nLemma lev_pmuln2r n : (0 < n)%N -> {mono natmul^~ n : x y / x ⊑ y}.\nProof.\nby case: n => // n _ x y /=; rewrite -!scaler_nat lev_pscale2l ?ltr0n.\nQed.\n\nLemma ltv_pmuln2r n : (0 < n)%N -> {mono natmul^~ n : x y / x ⊏ y}.\nProof. by move/lev_pmuln2r/leW_mono. Qed.\n\nLemma pmulvnI n : (0 < n)%N -> injective (natmul^~ n).\nProof. by move/lev_pmuln2r/inc_inj. Qed.\n\nLemma eqr_pmuln2r n : (0 < n)%N -> {mono natmul^~ n : x y / x == y}.\nProof. by move/pmulvnI/inj_eq. Qed.\n\nLemma pmulvn_lgt0 x n : (0 < n)%N -> ('0 ⊏ x *+ n) = ('0 ⊏ x).\nProof. by move=> n_gt0; rewrite -(mul0rn _ n) ltv_pmuln2r // mul0rn. Qed.\n\nLemma pmulvn_llt0 x n : (0 < n)%N -> (x *+ n ⊏ 0) = (x ⊏ 0).\nProof. by move=> n_gt0; rewrite -(mul0rn _ n) ltv_pmuln2r // mul0rn. Qed.\n\nLemma pmulvn_lge0 x n : (0 < n)%N -> ('0 ⊑ x *+ n) = ('0 ⊑ x).\nProof. by move=> n_gt0; rewrite -(mul0rn _ n) lev_pmuln2r // mul0rn. Qed.\n\nLemma pmulvn_lle0 x n : (0 < n)%N -> (x *+ n ⊑ 0) = (x ⊑ 0).\nProof. by move=> n_gt0; rewrite -(mul0rn _ n) lev_pmuln2r // mul0rn. Qed.\n\nLemma ltv_wmuln2r x y n : x ⊏ y -> (x *+ n ⊏ y *+ n) = (0 < n)%N.\nProof. by move=> ltxy; case: n=> // n; rewrite ltv_pmuln2r. Qed.\n\nLemma ltv_wpmuln2r n : (0 < n)%N -> {homo natmul^~ n : x y / x ⊏ y}.\nProof. by move=> n_gt0 x y /= / ltv_wmuln2r ->. Qed.\n\nLemma lev_wmuln2r n : {homo natmul^~ n : x y / x ⊑ y}.\nProof. by move=> x y hxy /=; case: n=> // n; rewrite lev_pmuln2r. Qed.\n\nLemma mulvn_wge0 x n : '0 ⊑ x -> '0 ⊑ x *+ n.\nProof. by move=> /(lev_wmuln2r n); rewrite mul0rn. Qed.\n\nLemma mulvn_wle0 x n : x ⊑ 0 -> x *+ n ⊑ 0.\nProof. by move=> /(lev_wmuln2r n); rewrite mul0rn. Qed.\n\nLemma lev_muln2r n x y : (x *+ n ⊑ y *+ n) = ((n == 0%N) || (x ⊑ y)).\nProof. by case: n => [|n]; rewrite ?lexx ?eqxx // lev_pmuln2r. Qed.\n\nLemma ltv_muln2r n x y : (x *+ n ⊏ y *+ n) = ((0 < n)%N && (x ⊏ y)).\nProof. by case: n => [|n]; rewrite ?lexx ?eqxx // ltv_pmuln2r. Qed.\n\nLemma eqv_muln2r n x y : (x *+ n == y *+ n) = (n == 0)%N || (x == y).\nProof. by rewrite {1}eq_le [x == _]eq_le !lev_muln2r -orb_andr. Qed.\n\n(* More characteristic zero properties. *)\n\nLemma mulvn_eq0 x n : (x *+ n == 0) = ((n == 0)%N || (x == 0)).\nProof. by rewrite -{1}(mul0rn [zmodType of T] n) eqv_muln2r. Qed.\n\nLemma eqNv x : (- x == x) = (x == 0).\nProof. by rewrite eq_sym -addr_eq0 -mulr2n mulvn_eq0. Qed.\n\nLemma mulvIn x : x != 0 -> injective (GRing.natmul x).\nProof.\nmove=> x_neq0 m n; without loss /subnK <-: m n / (n <= m)%N.\n  by move=> IH eq_xmn; case/orP: (leq_total m n) => /IH->.\nby move/eqP; rewrite mulrnDr -subr_eq0 addrK mulvn_eq0 => /predU1P[-> | /idPn].\nQed.\n\nLemma lev_wpmuln2l x :\n  '0 ⊑ x -> {homo (natmul x) : m n / (m <= n)%N >-> m ⊑ n}.\nProof. by move=> xge0 m n /subnK <-; rewrite mulrnDr lev_paddl ?mulvn_wge0. Qed.\n\nLemma lev_wnmuln2l x :\n  x ⊑ 0 -> {homo (natmul x) : m n / (n <= m)%N >-> m ⊑ n}.\nProof.\nby move=> xle0 m n hmn /=; rewrite -lev_opp2 -!mulNrn lev_wpmuln2l // oppv_cp0.\nQed.\n\nLemma mulvn_wgt0 x n : '0 ⊏ x -> '0 ⊏ x *+ n = (0 < n)%N.\nProof. by case: n => // n hx; rewrite pmulvn_lgt0. Qed.\n\nLemma mulvn_wlt0 x n : x ⊏ 0 -> x *+ n ⊏ 0 = (0 < n)%N.\nProof. by case: n => // n hx; rewrite pmulvn_llt0. Qed.\n\nLemma lev_pmuln2l x :\n  '0 ⊏ x -> {mono (natmul x) : m n / (m <= n)%N >-> m ⊑ n}.\nProof.\nmove=> x_gt0 m n /=; case: leqP => hmn; first by rewrite lev_wpmuln2l // ltW.\nrewrite -(subnK (ltnW hmn)) mulrnDr gev_addr lt_geF //.\nby rewrite mulvn_wgt0 // subn_gt0.\nQed.\n\nLemma ltv_pmuln2l x :\n  '0 ⊏ x -> {mono (natmul x) : m n / (m < n)%N >-> m ⊏ n}.\nProof. by move=> x_gt0; apply: leW_mono (lev_pmuln2l _). Qed.\n\nLemma lev_nmuln2l x :\n  x ⊏ 0 -> {mono (natmul x) : m n / (n <= m)%N >-> m ⊑ n}.\nProof.\nby move=> x_lt0 m n /=; rewrite -lev_opp2 -!mulNrn lev_pmuln2l // oppv_gt0.\nQed.\n\nLemma ltv_nmuln2l x :\n  x ⊏ 0 -> {mono (natmul x) : m n / (n < m)%N >-> m ⊏ n}.\nProof. by move=> x_lt0; apply: leW_nmono (lev_nmuln2l _). Qed.\n\nLemma pmulvn_rgt0 x n : '0 ⊏ x -> '0 ⊏ x *+ n = (0 < n)%N.\nProof. by move=> x_gt0; rewrite -(mulr0n x) ltv_pmuln2l. Qed.\n\nLemma pmulvn_rlt0 x n : '0 ⊏ x -> x *+ n ⊏ 0 = false.\nProof. by move=> x_gt0; rewrite -(mulr0n x) ltv_pmuln2l. Qed.\n\nLemma pmulvn_rge0 x n : '0 ⊏ x -> '0 ⊑ x *+ n.\nProof. by move=> x_gt0; rewrite -(mulr0n x) lev_pmuln2l. Qed.\n\nLemma pmulvn_rle0 x n : '0 ⊏ x -> x *+ n ⊑ 0 = (n == 0)%N.\nProof. by move=> x_gt0; rewrite -(mulr0n x) lev_pmuln2l ?leqn0. Qed.\n\nLemma nmulvn_rgt0 x n : x ⊏ 0 -> '0 ⊏ x *+ n = false.\nProof. by move=> x_lt0; rewrite -(mulr0n x) ltv_nmuln2l. Qed.\n\nLemma nmulvn_rge0 x n : x ⊏ 0 -> '0 ⊑ x *+ n = (n == 0)%N.\nProof. by move=> x_lt0; rewrite -(mulr0n x) lev_nmuln2l ?leqn0. Qed.\n\nLemma nmulvn_rle0 x n : x ⊏ 0 -> x *+ n ⊑ 0.\nProof. by move=> x_lt0; rewrite -(mulr0n x) lev_nmuln2l. Qed.\n\n(* Remark : pscalev_rgt0 and pscalev_rge0 are defined above *)\n\n(* a positive and y right *)\nLemma pscalev_rlt0 a y : 0 < a -> (a *: y ⊏ 0) = (y ⊏ 0).\nProof. by move=> x_gt0; rewrite -!oppv_gt0 -scalerN pscalev_rgt0 // oppr_gt0. Qed.\n\nLemma pscalev_rle0 a y : 0 < a -> (a *: y ⊑ 0) = (y ⊑ 0).\nProof. by move=> x_gt0; rewrite -!oppv_ge0 -scalerN pscalev_rge0 // oppr_ge0. Qed.\n\n(* a negative and y right *)\nLemma nscalev_rgt0 a y : a < 0 -> ('0 ⊏ a *: y) = (y ⊏ 0).\nProof. by move=> x_lt0; rewrite -scalerNN pscalev_rgt0 ?ltev_oppE// lter_oppE. Qed.\n\nLemma nscalev_rge0 a y : a < 0 -> ('0 ⊑ a *: y) = (y ⊑ 0).\nProof. by move=> x_lt0; rewrite -scalerNN pscalev_rge0 ?ltev_oppE// lter_oppE. Qed.\n\nLemma nscalev_rlt0 a y : a < 0 -> (a *: y ⊏ 0) = ('0 ⊏ y).\nProof. by move=> x_lt0; rewrite -scalerNN pscalev_rlt0 ?ltev_oppE// lter_oppE. Qed.\n\nLemma nscalev_rle0 a y : a < 0 -> (a *: y ⊑ 0) = ('0 ⊑ y).\nProof. by move=> x_lt0; rewrite -scalerNN pscalev_rle0 ?ltev_oppE// lter_oppE. Qed.\n\n(* weak and symmetric lemmas *)\nLemma scalev_ge0 a y : 0 <= a -> '0 ⊑ y -> '0 ⊑ a *: y.\nProof. by move=> x_ge0 y_ge0; rewrite -(scaler0 _ a) lev_wpscale2l. Qed.\n\nLemma scalev_le0 a y : a <= 0 -> y ⊑ 0 -> '0 ⊑ a *: y.\nProof. by move=> x_le0 y_le0; rewrite -(scaler0 _ a) lev_wnscale2l. Qed.\n\nLemma scalev_ge0_le0 a y : 0 <= a -> y ⊑ 0 -> a *: y ⊑ 0.\nProof. by move=> x_le0 y_le0; rewrite -(scaler0 _ a) lev_wpscale2l. Qed.\n\nLemma scalev_le0_ge0 a y : a <= 0 -> '0 ⊑ y -> a *: y ⊑ 0.\nProof. by move=> x_le0 y_le0; rewrite -(scaler0 _ a) lev_wnscale2l. Qed.\n\n(* scalev_gt0 with only one case *)\n\nLemma scalev_gt0 a x : 0 < a -> '0 ⊏ x -> '0 ⊏ a *: x.\nProof. by move=> x_gt0 y_gt0; rewrite pscalev_rgt0. Qed.\n\nLemma scalev_lt0 a x : a < 0 -> x ⊏ 0 -> '0 ⊏ a *: x.\nProof. by move=> x_le0 y_le0; rewrite nscalev_rgt0. Qed.\n\nLemma scalev_gt0_lt0 a x : 0 < a -> x ⊏ 0 -> a *: x ⊏ 0.\nProof. by move=> x_le0 y_le0; rewrite pscalev_rlt0. Qed.\n\nLemma scalev_lt0_gt0 a x : a < 0 -> '0 ⊏ x -> a *: x ⊏ 0.\nProof. by move=> x_le0 y_le0; rewrite nscalev_rlt0. Qed.\n\n(* lev/ltv and multiplication between a positive/negative\n   and a exterior (1 <= _) or interior (0 <= _ <= 1) *)\n\nLemma lev_pescale a x : '0 ⊑ x -> 1 <= a -> x ⊑ a *: x.\nProof. by move=> hy hx; rewrite -{1}[x]scale1r lev_wpscale2r. Qed.\n\nLemma lev_nescale a x : x ⊑ 0 -> 1 <= a -> a *: x ⊑ x.\nProof. by move=> hy hx; rewrite -{2}[x]scale1r lev_wnscale2r. Qed.\n\nLemma lev_piscale a x : '0 ⊑ x -> a <= 1 -> a *: x ⊑ x.\nProof. by move=> hy hx; rewrite -{2}[x]scale1r lev_wpscale2r. Qed.\n\nLemma lev_niscale a x : x ⊑ 0 -> a <= 1 -> x ⊑ a *: x.\nProof. by move=> hy hx; rewrite -{1}[x]scale1r lev_wnscale2r. Qed.\n\nEnd VOrderTheory.\n\nSection CanVOrderTheory.\nVariable (R: numFieldType) (T : canVOrderType R).\nImplicit Type (x y z : T) (a b c : R).\nLocal Notation \"'0\" := (0 : T).\n\nLemma pscalev_lge0 x a : '0 ⊏ x -> '0 ⊑ a *: x = (0 <= a).\nProof. by move: x a; case: T=>?[?[P]] x a; apply P. Qed.\n\nLemma pscalev_lgt0 y a : '0 ⊏ y -> ('0 ⊏ a *: y) = (0 < a).\nProof.\nby move=>Py; rewrite !lt_def scaler_eq0 negb_or pscalev_lge0// lt0v_neq0// andbT.\nQed.\n\nImport Num.Theory.\n\nLemma lev_pscale2r x : '0 ⊏ x -> {mono *:%R^~ x : x y / (x <= y)%O}.\nProof.\nby move=>Px a b; rewrite -subv_ge0 -scalerBl pscalev_lge0// subr_ge0.\nQed.  \n\nLemma ltv_pscale2r x : '0 ⊏ x -> {mono *:%R^~ x : x y / (x < y)%O}.\nProof. by move=> x_gt0; apply: leW_mono (lev_pscale2r _). Qed.\n\nDefinition ltev_pscale2r := (lev_pscale2r, ltv_pscale2r).\n\n\nLemma lev_nscale2r x : x ⊏ 0 -> {mono *:%R^~ x : x y /~ (x <= y)%O}.\nProof.\nby move=> x_lt0 y z /=; rewrite -lev_opp2 -!scalerN lev_pscale2r// oppv_gt0.\nQed.\n\nLemma ltv_nscale2r x : x ⊏ 0 -> {mono *:%R^~ x : x y /~ (x < y)%O}.\nProof. by move=> x_lt0; apply: leW_nmono (lev_nscale2r _). Qed.\n\nDefinition ltev_nscale2r := (lev_nscale2r, ltv_nscale2r).\n\n(* x positive and y left *)\nLemma pscalev_llt0 x a : '0 ⊏ x -> (a *: x ⊏ 0) = (a < 0).\nProof. by move=> x_gt0; rewrite -!oppv_gt0 -scaleNr pscalev_lgt0 // oppr_gt0. Qed.\n\nLemma pscalev_lle0 x a : '0 ⊏ x -> (a *: x ⊑ 0) = (a <= 0).\nProof. by move=> x_gt0; rewrite -!oppv_ge0 -scaleNr pscalev_lge0 // oppr_ge0. Qed.\n\n(* x negative and y left *)\nLemma nscalev_lgt0 x a : x ⊏ 0 -> ('0 ⊏ a *: x) = (a < 0).\nProof. by move=> x_lt0; rewrite -scalerNN pscalev_lgt0 ?ltev_oppE// lter_oppE. Qed.\n\nLemma nscalev_lge0 x a : x ⊏ 0 -> ('0 ⊑ a *: x) = (a <= 0).\nProof. by move=> x_lt0; rewrite -scalerNN pscalev_lge0 ?ltev_oppE// lter_oppE. Qed.\n\nLemma nscalev_llt0 x a : x ⊏ 0 -> (a *: x ⊏ 0) = (0 < a).\nProof. by move=> x_lt0; rewrite -scalerNN pscalev_llt0 ?ltev_oppE// lter_oppE. Qed.\n\nLemma nscalev_lle0 x a : x ⊏ 0 -> (a *: x ⊑ 0) = (0 <= a).\nProof. by move=> x_lt0; rewrite -scalerNN pscalev_lle0 ?ltev_oppE// lter_oppE. Qed.\n\n(* lev/ltv and multiplication between a positive/negative *)\n\nLemma gev_pscale a x : '0 ⊏ x -> (a *: x ⊑ x) = (a <= 1).\nProof. by move=> hy; rewrite -{2}[x]scale1r lev_pscale2r. Qed.\n\nLemma gtv_pscale a x : '0 ⊏ x -> (a *: x ⊏ x) = (a < 1).\nProof. by move=> hy; rewrite -{2}[x]scale1r ltv_pscale2r. Qed.\n\nLemma lev_pscale a x : '0 ⊏ x -> (x ⊑ a *: x) = (1 <= a).\nProof. by move=> hy; rewrite -{1}[x]scale1r lev_pscale2r. Qed.\n\nLemma ltv_pscale a x : '0 ⊏ x -> (x ⊏ a *: x) = (1 < a).\nProof. by move=> hy; rewrite -{1}[x]scale1r ltv_pscale2r. Qed.\n\nLemma gev_nscale a x : x ⊏ 0 -> (a *: x ⊑ x) = (1 <= a).\nProof. by move=> hy; rewrite -{2}[x]scale1r lev_nscale2r. Qed.\n\nLemma gtv_nscale a x : x ⊏ 0 -> (a *: x ⊏ x) = (1 < a).\nProof. by move=> hy; rewrite -{2}[x]scale1r ltv_nscale2r. Qed.\n\nLemma lev_nscale a x : x ⊏ 0 -> (x ⊑ a *: x) = (a <= 1).\nProof. by move=> hy; rewrite -{1}[x]scale1r lev_nscale2r. Qed.\n\nLemma ltv_nscale a x : x ⊏ 0 -> (x ⊏ a *: x) = (a < 1).\nProof. by move=> hy; rewrite -{1}[x]scale1r ltv_nscale2r. Qed.\n\nEnd CanVOrderTheory.\n\nDefinition applyar_head U V W t (f : U -> V -> W) u v := let: tt := t in f v u.\nNotation applyar := (@applyar_head _ _ _ tt).\n\nModule BRegVOrder.\n\nSection ClassDef.\nVariable (R: numFieldType) (U V W : vorderType R).\nImplicit Type phUVW : phant (U -> V -> W).\n\nRecord mixin_of (op : U -> V -> W) := Mixin {\n  _ : forall x y, op x y == 0 = (x == 0) || (y == 0);\n  _ : forall x y, (0 : U) ⊏ x -> ((0 : W) ⊑ op x y) = ((0 : V) ⊑ y);\n  _ : forall y x, (0 : V) ⊏ y -> ((0 : W) ⊑ op x y) = ((0 : U) ⊑ x);\n}.\n\nRecord class_of f : Prop := Class {\n  basel : forall u', GRing.Additive.axiom (f^~ u');\n  baser : forall u, GRing.Additive.axiom (f u);\n  mixin : mixin_of f\n}.\n\nStructure map phUVW := Pack {apply; _ : class_of apply}.\nLocal Coercion apply : map >-> Funclass.\n\nDefinition class phUVW (cF : map phUVW) := \n    let: Pack _ c as cF' := cF return class_of cF' in c.\nDefinition clone phUVW (f g : U -> V -> W) (cF : map phUVW) \n  fL of phant_id g (apply cF) & phant_id fL class := @Pack phUVW f fL.\n\nDefinition pack (phUW : phant (U -> W)) (phVW : phant (V -> W))\n           (revf : V -> U -> W) (rf : revop revf) f (g : U -> V -> W) m0 of (g = fun_of_revop rf) :=\n  fun (bFl : V -> GRing.Additive.map phUW) flc of (forall v, revf v = bFl v) &\n      (forall v, phant_id (GRing.Additive.class (bFl v)) (flc v)) =>\n  fun (bFr : U -> GRing.Additive.map phVW) frc of (forall u, g u = bFr u) &\n      (forall u, phant_id (GRing.Additive.class (bFr u)) (frc u)) =>\n  @Pack (Phant _) f (Class flc frc m0).\n\nDefinition additiver phVW phUVW (u : U) cF := GRing.Additive.Pack phVW \n  (baser (@class phUVW cF) u).\nDefinition additivel phUW phUVW (v : V) (cF : map phUVW) :=\n  @GRing.Additive.Pack _ _ phUW (applyar cF v) (basel (@class phUVW cF) v).\n\nEnd ClassDef.\n\nModule Exports.\nCoercion baser : class_of >-> Funclass.\nCoercion apply : map >-> Funclass.\nNotation bregVOrderMixin := Mixin.\nNotation bregVOrderType f M := (@pack _ _ _ _ _ _ _ _ f f M erefl _ _ \n(fun=> erefl) (fun=> idfun) _ _ (fun=> erefl) (fun=> idfun)).\nNotation \"{ 'bregVOrder' fUV }\" := (map (Phant fUV))\n  (at level 0, format \"{ 'bregVOrder'  fUV }\") : ring_scope.\nNotation \"[ 'bregVOrder' 'of' f 'as' g ]\" := (@clone _ _ _ _ _ f g _ _ idfun id)\n  (at level 0, format \"[ 'bregVOrder'  'of'  f  'as'  g ]\") : form_scope.\nNotation \"[ 'bregVOrder' 'of' f ]\" := (@clone _ _ _ _ _ f f _ _ id id)\n  (at level 0, format \"[ 'bregVOrder'  'of'  f ]\") : form_scope.\nCanonical additiver.\nCanonical additivel.\nEnd Exports.\n\nEnd BRegVOrder.\nExport BRegVOrder.Exports.\n\nSection BRegVOrderTheory.\nVariable (R: numFieldType) (U V W : vorderType R) (f : {bregVOrder U -> V -> W}).\nImplicit Type (a b c : U) (x y z : V).\n\nLocal Notation l0 := (0 : U).\nLocal Notation r0 := (0 : V).\nLocal Notation b0 := (0 : W).\n\n(* it is additive, additiver *)\nLemma applyarE x : applyar f x =1 f^~ x. Proof. by []. Qed.\n\nLemma bregv0r a : f a 0 = 0. Proof. by rewrite raddf0. Qed.\nLemma bregvNr a : {morph f a : x / - x}. Proof. exact: raddfN. Qed.\nLemma bregvDr a : {morph f a : x y / x + y}. Proof. exact: raddfD. Qed.\nLemma bregvBr a : {morph f a : x y / x - y}. Proof. exact: raddfB. Qed.\nLemma bregvMnr a n : {morph f a : x / x *+ n}. Proof. exact: raddfMn. Qed.\nLemma bregvMNnr a n : {morph f a : x / x *- n}. Proof. exact: raddfMNn. Qed.\nLemma bregv_sumr a I r (P : pred I) E :\n  f a (\\sum_(i <- r | P i) E i) = \\sum_(i <- r | P i) f a (E i).\nProof. exact: raddf_sum. Qed.\nLemma bregv0l x : f 0 x = 0. Proof. by rewrite -applyarE raddf0. Qed.\nLemma bregvNl x : {morph f^~ x : x / - x}.\nProof. by move=> ?; rewrite -applyarE raddfN. Qed.\nLemma bregvDl x : {morph f^~ x : x y / x + y}.\nProof. by move=> ??; rewrite -applyarE raddfD. Qed.\nLemma bregvBl x : {morph f^~ x : x y / x - y}.\nProof. by move=> ??; rewrite -applyarE raddfB. Qed.\nLemma bregvMnl x n : {morph f^~ x : x / x *+ n}.\nProof. by move=> ?; rewrite -applyarE raddfMn. Qed.\nLemma bregvMNnl x n : {morph f^~ x : x / x *- n}.\nProof. by move=> ?; rewrite -applyarE raddfMNn. Qed.\nLemma bregv_suml x I r (P : pred I) E :\n  f (\\sum_(i <- r | P i) E i) x = \\sum_(i <- r | P i) f (E i) x.\nProof. by rewrite -applyarE raddf_sum. Qed.\nLemma bregvNN a x : f (-a) (-x) = f a x.\nProof. by rewrite bregvNl bregvNr opprK. Qed.\n\nLemma bregv_eq0 a x : f a x == 0 = (a == 0) || (x == 0).\nProof. by move: a x; case: f=>/=?[??[???]]. Qed.\n\nLemma pbregv_rge0 a x : l0 ⊏ a -> (b0 ⊑ f a x) = (r0 ⊑ x).\nProof. move: a x; case: f=>/=?[??[? P?]]; apply P. Qed.\n\nLemma pbregv_lge0 x a : r0 ⊏ x -> (b0 ⊑ f a x) = (l0 ⊑ a).\nProof. move: x a; case: f=>/=?[??[?? P]]; apply P. Qed.\n\nLemma pbregv_rgt0 a x : l0 ⊏ a -> (b0 ⊏ f a x) = (r0 ⊏ x).\nProof.\nmove=>xgt0. rewrite !lt0v (pbregv_rge0 _ xgt0) bregv_eq0//.\nby move: xgt0; rewrite lt_def=>/andP[/negPf->].\nQed.\n\nLemma pbregv_lgt0 x a : r0 ⊏ x -> (b0 ⊏ f a x) = (l0 ⊏ a).\nProof.\nmove=>xgt0. rewrite !lt0v (pbregv_lge0 _ xgt0) bregv_eq0//.\nby move: xgt0; rewrite lt_def orbC=>/andP[/negPf->].\nQed.\n\nLemma bregvI_eq0 a x : a != 0 -> (f a x == 0) = (x == 0).\nProof. by rewrite bregv_eq0; move=>/negPf->. Qed.\n\nLemma bregvI a : a != 0 -> injective (f a).\nProof. by move=>Pa x y /eqP; rewrite -subr_eq0 -bregvBr/= bregvI_eq0// subr_eq0=>/eqP. Qed.\n\nLemma bregIv_eq0 x a : x != 0 -> (f a x == 0) = (a == 0).\nProof. by rewrite bregv_eq0 orbC; move=>/negPf->. Qed.\n\nLemma bregIv x : x != 0 -> injective (f^~ x).\nProof. by move=>Px a y /eqP; rewrite -subr_eq0 -bregvBl/= bregIv_eq0// subr_eq0=>/eqP. Qed.\n\nLemma lev_pbreg2lP a x y : l0 ⊏ a -> x ⊑ y -> (f a x) ⊑ (f a y).\nProof. by move=>Pa Pxy; rewrite -subv_ge0 -bregvBr/= pbregv_rge0// subv_ge0. Qed.\n\n(* mulr and lev/ltv *)\nLemma lev_pbreg2l a : l0 ⊏ a -> {mono (f a) : x y / x ⊑ y}.\nProof.\nby move=> x_gt0 y z /=; rewrite -subv_ge0 -bregvBr pbregv_rge0// subv_ge0.\nQed.\n\nLemma ltv_pbreg2l a : l0 ⊏ a -> {mono (f a) : x y / x ⊏ y}.\nProof. by move=> x_gt0; apply: leW_mono (lev_pbreg2l _). Qed.\n\nDefinition ltev_pbreg2l := (lev_pbreg2l, ltv_pbreg2l).\n\nLemma lev_pbreg2r x : r0 ⊏ x -> {mono f^~ x : x y / x ⊑ y}.\nProof.\nby move=> x_gt0 y z /=; rewrite -subv_ge0 -bregvBl pbregv_lge0// subv_ge0.\nQed.  \n\nLemma ltv_pbreg2r x : r0 ⊏ x -> {mono f^~ x : x y / x ⊏ y}.\nProof. by move=> x_gt0; apply: leW_mono (lev_pbreg2r _). Qed.\n\nDefinition ltev_pbreg2r := (lev_pbreg2r, ltv_pbreg2r).\n\nLemma lev_nbreg2l a : a ⊏ 0 -> {mono (f a) : x y /~ x ⊑ y}.\nProof.\nby move=> x_lt0 y z /=; rewrite -lev_opp2 -!bregvNl/= lev_pbreg2l ?oppv_gt0.\nQed.\n\nLemma ltv_nbreg2l a : a ⊏ 0 -> {mono (f a) : x y /~ x ⊏ y}.\nProof. by move=> x_lt0; apply: leW_nmono (lev_nbreg2l _). Qed.\n\nDefinition ltev_nbreg2l := (lev_nbreg2l, ltv_nbreg2l).\n\nLemma lev_nbreg2r x : x ⊏ 0 -> {mono f^~ x : x y /~ x ⊑ y}.\nProof.\nby move=> x_lt0 y z /=; rewrite -lev_opp2 -!bregvNr lev_pbreg2r// oppv_gt0.\nQed.\n\nLemma ltv_nbreg2r x : x ⊏ 0 -> {mono f^~ x : x y /~ x ⊏ y}.\nProof. by move=> x_lt0; apply: leW_nmono (lev_nbreg2r _). Qed.\n\nDefinition ltev_nbreg2r := (lev_nbreg2r, ltv_nbreg2r).\n\nLemma lev_wpbreg2l a : l0 ⊑ a -> {homo (f a) : y z / y ⊑ z}.\nProof.\nby rewrite le0v => /orP[/eqP-> y z | /lev_pbreg2l/mono2W//]; rewrite !bregv0l.\nQed.\n\nLemma lev_wnbreg2l a : a ⊑ 0 -> {homo (f a) : y z /~ y ⊑ z}.\nProof.\nby move=> x_le0 y z leyz; rewrite -![f a _]bregvNN lev_wpbreg2l ?ltev_oppE.\nQed.\n\nLemma lev_wpbreg2r x : r0 ⊑ x -> {homo f^~ x : y z / y ⊑ z}.\nProof.\nby rewrite le0v => /orP[/eqP-> y z | /lev_pbreg2r/mono2W//]; rewrite !bregv0r.\nQed.\n\nLemma lev_wnbreg2r x : x ⊑ 0 -> {homo f^~ x : y z /~ y ⊑ z}.\nProof.\nby move=> x_le0 y z leyz; rewrite -![f _ x]bregvNN lev_wpbreg2r ?ltev_oppE.\nQed.\n\n(* Binary forms, for backchaining. *)\nLemma lev_pbreg2 a b x y :\n  l0 ⊑ a -> r0 ⊑ x -> a ⊑ b -> x ⊑ y -> f a x ⊑ f b y.\nProof.\nmove=> x1ge0 x2ge0 le_xy1 le_xy2; have y1ge0 := le_trans x1ge0 le_xy1.\nexact: le_trans (lev_wpbreg2r x2ge0 le_xy1) (lev_wpbreg2l y1ge0 le_xy2).\nQed.\n\nLemma ltv_pbreg2 a b x y :\n  l0 ⊑ a -> r0 ⊑ x -> a ⊏ b -> x ⊏ y -> f a x ⊏ f b y.\nProof.\nmove=> x1ge0 x2ge0 lt_xy1 lt_xy2; have y1gt0 := le_lt_trans x1ge0 lt_xy1.\nby rewrite (le_lt_trans (lev_wpbreg2r x2ge0 (ltW lt_xy1))) ?ltv_pbreg2l.\nQed.\n\nLemma pbregv_rlt0 a x : l0 ⊏ a -> (f a x ⊏ 0) = (x ⊏ 0).\nProof. by move=> x_gt0; rewrite -!oppv_gt0 -bregvNr pbregv_rgt0// oppv_gt0. Qed.\n\nLemma pbregv_rle0 a x : l0 ⊏ a -> (f a x ⊑ 0) = (x ⊑ 0).\nProof. by move=> x_gt0; rewrite -!oppv_ge0 -bregvNr pbregv_rge0// oppr_ge0. Qed.\n\nLemma nbregv_rgt0 a x : a ⊏ 0 -> (b0 ⊏ f a x) = (x ⊏ 0).\nProof. by move=> x_lt0; rewrite -bregvNN pbregv_rgt0 ?ltev_oppE. Qed.\n\nLemma nbregv_rge0 a x : a ⊏ 0 -> (b0 ⊑ f a x) = (x ⊑ 0).\nProof. by move=> x_lt0; rewrite -bregvNN pbregv_rge0 ?ltev_oppE. Qed.\n\nLemma nbregv_rlt0 a x : a ⊏ 0 -> (f a x ⊏ 0) = (r0 ⊏ x).\nProof. by move=> x_lt0; rewrite -bregvNN pbregv_rlt0 ?ltev_oppE. Qed.\n\nLemma nbregv_rle0 a x : a ⊏ 0 -> (f a x ⊑ 0) = (r0 ⊑ x).\nProof. by move=> x_lt0; rewrite -bregvNN pbregv_rle0 ?ltev_oppE. Qed.\n\nLemma pbregv_llt0 x a : r0 ⊏ x -> (f a x ⊏ 0) = (a ⊏ 0).\nProof. by move=> x_gt0; rewrite -!oppv_gt0 -bregvNl pbregv_lgt0// oppv_gt0. Qed.\n\nLemma pbregv_lle0 x a : r0 ⊏ x -> (f a x ⊑ 0) = (a ⊑ 0).\nProof. by move=> x_gt0; rewrite -!oppv_ge0 -bregvNl pbregv_lge0// oppr_ge0. Qed.\n\nLemma nbregv_lgt0 x a : x ⊏ 0 -> (b0 ⊏ f a x) = (a ⊏ 0).\nProof. by move=> x_lt0; rewrite -bregvNN pbregv_lgt0 ?ltev_oppE. Qed.\n\nLemma nbregv_lge0 x a : x ⊏ 0 -> (b0 ⊑ f a x) = (a ⊑ 0).\nProof. by move=> x_lt0; rewrite -bregvNN pbregv_lge0 ?ltev_oppE. Qed.\n\nLemma nbregv_llt0 x a : x ⊏ 0 -> (f a x ⊏ 0) = (l0 ⊏ a).\nProof. by move=> x_lt0; rewrite -bregvNN pbregv_llt0 ?ltev_oppE. Qed.\n\nLemma nbregv_lle0 x a : x ⊏ 0 -> (f a x ⊑ 0) = (l0 ⊑ a).\nProof. by move=> x_lt0; rewrite -bregvNN pbregv_lle0 ?ltev_oppE. Qed.\n\n(* weak and symmetric lemmas *)\nLemma bregv_ge0 a x : l0 ⊑ a -> r0 ⊑ x -> b0 ⊑ f a x.\nProof. by move=> x_ge0 y_ge0; rewrite -(bregv0r a) lev_wpbreg2l. Qed.\n\nLemma bregv_le0 a x : a ⊑ 0 -> x ⊑ 0 -> b0 ⊑ f a x.\nProof. by move=> x_le0 y_le0; rewrite -(bregv0r a) lev_wnbreg2l. Qed.\n\nLemma bregv_ge0_le0 a x : l0 ⊑ a -> x ⊑ 0 -> f a x ⊑ 0.\nProof. by move=> x_le0 y_le0; rewrite -(bregv0r a) lev_wpbreg2l. Qed.\n\nLemma bregv_le0_ge0 a x : a ⊑ 0 -> r0 ⊑ x -> f a x ⊑ 0.\nProof. by move=> x_le0 y_le0; rewrite -(bregv0r a) lev_wnbreg2l. Qed.\n\n(* bregv_gt0 with only one case *)\n\nLemma bregv_gt0 a x : l0 ⊏ a -> r0 ⊏ x -> b0 ⊏ f a x.\nProof. by move=> x_gt0 y_gt0; rewrite pbregv_rgt0. Qed.\n\nLemma bregv_lt0 a x : a ⊏ 0 -> x ⊏ 0 -> b0 ⊏ f a x.\nProof. by move=> x_le0 y_le0; rewrite nbregv_rgt0. Qed.\n\nLemma bregv_gt0_lt0 a x : l0 ⊏ a -> x ⊏ 0 -> f a x ⊏ 0.\nProof. by move=> x_le0 y_le0; rewrite pbregv_rlt0. Qed.\n\nLemma bregv_lt0_gt0 a x : a ⊏ 0 -> r0 ⊏ x -> f a x ⊏ 0.\nProof. by move=> x_le0 y_le0; rewrite nbregv_rlt0. Qed.\n\nEnd BRegVOrderTheory.\n\nSection mx_norm_vnorm.\nVariable (K: numDomainType) (m n: nat).\n\nLemma mx_normvZ (l : K) (x : 'M[K]_(m,n)) : mx_norm (l *: x) = `| l | * mx_norm x.\nProof.\nrewrite /= !mx_normE (eq_bigr (fun i => (`|l| * `|x i.1 i.2|)%:nng)); last first.\n  by move=> i _; rewrite mxE //=; apply/eqP; rewrite -num_eq /= Num.Theory.normrM.\nelim/big_ind2 : _ => // [|a b c d bE dE]; first by rewrite mulr0.\nby rewrite !num_max bE dE Num.Theory.maxr_pmulr.\nQed.\nCanonical mx_norm_vnorm := Vnorm (@ler_mx_norm_add _ _ _) (@mx_norm_eq0 _ _ _) mx_normvZ.\nEnd mx_norm_vnorm.\nArguments mx_norm_vnorm {K m n}.\n\nSection TrivialMatrix.\nVariable (R: ringType).\n\nLemma mx_dim0n p : all_equal_to (0 : 'M[R]_(0,p)).\nProof. by move=>x/=; apply/matrixP=>i j; destruct i. Qed.\nLemma mx_dimn0 p : all_equal_to (0 : 'M[R]_(p,0)).\nProof. by move=>x/=; apply/matrixP=>i j; destruct j. Qed.\nDefinition mx_dim0E := (mx_dim0n,mx_dimn0).\nLemma mxf_dim0n T p : all_equal_to ((fun=>0) : T -> 'M[R]_(0,p)).\nProof. by move=>h/=; apply/funext=>i; rewrite mx_dim0E. Qed.\nLemma mxf_dimn0 T p : all_equal_to ((fun=>0) : T -> 'M[R]_(p,0)).\nProof. by move=>h/=; apply/funext=>i; rewrite mx_dim0E. Qed.\nDefinition mxf_dim0E := (mxf_dim0n,mxf_dimn0).\n\nDefinition mx_dim0 := (mx_dim0n,mx_dimn0,mxf_dim0n,mxf_dimn0).\n\nLemma big_card0 (T : Type) (idx : T) (op : T -> T -> T) (I : finType) \n  (r: seq I) (P : pred I) \n  (F: I -> T): #|I| = 0%N ->\n  \\big[op/idx]_(i <- r | P i) F i = idx.\nProof.\nelim: r. by rewrite big_nil.\nmove=>a l _ PI. exfalso. move: (fintype0 a)=>//.\nQed.\n\nEnd TrivialMatrix.\n\n\n(******************Module for Real matrix********************)\n(* show the equivalence between mx_norm and any vector norm *)\n(* i.e., exists c1 c2, c1 > 0 & c2 > 0 &                    *)\n(*             forall x, c1 * `|x| <= mnorm x <= c2 * `|x|  *)\n(* Some lemmas are commented since they are not used        *)\nModule realTypeMxCvg.\n\nSection mxvec_norm.\nVariable (R: numDomainType) (m n : nat).\nLocal Notation M := 'M[R]_(m.+1,n.+1).\nImport Num.Def Num.Theory.\n\nLemma mxvec_norm (x : M) : `|x| = `|mxvec x|.\nProof.\napply/le_anti/andP; split; rewrite /normr/=/mx_norm;\nrewrite (bigmax_eq_arg (ord0, ord0))// ?ord1 ?num_le.\n2,4: by move=>i _; rewrite/= -num_le/=.\nby rewrite -mxvecE; apply: (le_trans _ (@ler_bigmax_cond _ _ _ _ _ _ \n  (ord0,(mxvec_index [arg max_(i > (ord0, ord0))`|x i.1 i.2|%:nng]%O.1\n  [arg max_(i > (ord0, ord0))`|x i.1 i.2|%:nng]%O.2)) _)).\nset k := [arg max_(i > (ord0, ord0))`|mxvec x i.1 i.2|%:nng]%O.2 : 'I_(m.+1*n.+1).\ncase/mxvec_indexP: k => i j /=; rewrite (mxvecE x i j).\nby apply: (le_trans _ (@ler_bigmax_cond _ _ _ _ _ _ (i,j) _)).\nQed.\n\nLemma mxvec_normV x : `|(vec_mx x : M)| = `|x|.\nProof. by rewrite -{2}(vec_mxK x) mxvec_norm. Qed.\nEnd mxvec_norm.\n\nSection mxvec_continuous.\nVariable (R : numFieldType) (m n : nat).\n\nLemma vec_mx_continuous : continuous (@vec_mx R m.+1 n.+1).\nProof.\nmove=> x s/= /nbhs_ballP [/=e egt0 Pb].\napply/nbhs_ballP. exists e =>//=.\nmove=> y /= Pxy. apply (Pb (vec_mx y)). move: Pxy.\nby rewrite -!ball_normE/= -linearB/= mxvec_normV.\nQed.\n\nLemma mxvec_continuous : continuous (@mxvec R m.+1 n.+1).\nProof.\nmove=> x s/= /nbhs_ballP [/=e egt0 Pb].\napply/nbhs_ballP. exists e =>//=.\nmove=> y /= Pxy. apply (Pb (mxvec y)). move: Pxy.\nby rewrite -!ball_normE/= -{1}(mxvecK x) -{1}(mxvecK y) -linearB/= mxvec_normV.\nQed.\nEnd mxvec_continuous.\n\nSection equal_mx_norm.\nImport Num.Def Num.Theory.\nVariable (R: realType) (m n : nat).\nLocal Notation M := 'M[R]_(m.+1,n.+1).\nVariable (mnorm : vnorm [lmodType R of M]).\n\nLemma bound_unit_sphere : bounded_set [set x : M | `|x| = 1%:R].\nProof.\nexists 1%:R. split. by rewrite real1.\nmove=>e egt1 v/= ->. by apply/ltW.\nQed.\n\nLemma mnorm_sum (I: finType) (r : seq I) (P: pred I) f :\n  mnorm (\\sum_(i <- r | P i) f i) <= \\sum_(i <- r | P i) mnorm (f i).\nProof.\nelim: r => [|x r IH]; first by rewrite !big_nil normv0.\nrewrite !big_cons. case: (P x)=>//.\napply (le_trans (lev_norm_add _ _ _)). by apply ler_add.\nQed.\n\nLemma mnorm_ubounded : exists c : R, (0 < c /\\ forall x, mnorm x <= c * `|x|).\nProof.\npose c := \\big[maxr/0]_i (mnorm (delta_mx i.1 i.2)).\nexists ((m.+1 * n.+1)%:R * c). split; last first.\nmove=>x; rewrite {1}(matrix_sum_delta x) pair_big/=.\napply: (le_trans (mnorm_sum _ _ _)).\nhave <-: \\sum_(i: 'I_m.+1 * 'I_n.+1) (c * `|x|) = (m.+1 * n.+1)%:R * c * `|x|.\nby rewrite sumr_const card_prod !card_ord -mulr_natl mulrA.\napply: ler_sum=>/= i _; rewrite normvZ mulrC; apply ler_pmul.\nby apply normv_ge0. by apply normr_ge0. rewrite /c. 2: rewrite {2}/normr/= mx_normrE.\n1,2: by apply: ler_bigmax_cond.\napply mulr_gt0. by rewrite ltr0n.\nrewrite /c. apply/bigmax_gtrP. right. exists (ord0, ord0)=>//=.\nrewrite lt_def normv_ge0 andbT. have: (delta_mx ord0 ord0 != (0 : M)).\napply/negP=>/eqP/matrixP/(_ ord0 ord0). rewrite !mxE !eqxx/=.\nmove/eqP. apply/negP. by apply oner_neq0.\napply contraNN. by move/eqP/normv0_eq0=>->.\nQed.\n\nLemma open_unit_ball1 (y : R) : open [set x : M | `|x| > y].\nProof.\nmove=> x /=; rewrite -subr_gt0 => xDy_gt0.\napply/nbhs_ballP; exists (`|x| - y) => // z.\nrewrite -ball_normE/= ltr_subr_addl -ltr_subr_addr=>P.\napply (lt_le_trans P). rewrite -{1}(normrN x).\nmove: (ler_sub_norm_add (-x) (x-z)).\nby rewrite addKr !normrN.\nQed.\n\nLemma open_unit_ball2 (y : R) : open [set x : M | `|x| < y].\nProof.\nmove=> x /=; rewrite -subr_gt0 => xDy_gt0.\napply/nbhs_ballP; exists (y - `|x|) => // z.\nrewrite -ball_normE/= ltr_subr_addl=>P.\napply: (le_lt_trans _ P).\nmove: (ler_norm_add (-x) (x-z)).\nby rewrite addKr !normrN.\nQed.\n\nLemma closed_unit_sphere : closed [set x : M | `|x| = 1%:R].\nProof.\nrewrite (_ : mkset _ = ~` [set x | `| x | > 1%:R] `&` ~` [set x | `| x | < 1%:R]).\napply closedI; rewrite closedC. apply open_unit_ball1. apply open_unit_ball2.\nrewrite predeqE => x /=; split; first by move=>->; rewrite !ltxx.\nmove=>[/negP P1 /negP P2].\nmove: P1 P2. rewrite !real_ltNge ?real1// !negbK=>/le_gtF P1.\nby rewrite le_eqVlt P1 orbF=>/eqP <-.\nQed.\n\nLemma mxvec_bounded_set (A: set M) :\n  bounded_set A <-> bounded_set (mxvec @` A).\nProof.\nsplit; move=>[e [P1 P2]]; exists e; split=>// x Px y/=.\nmove=> [z Pz eqzy]. move: (P2 x Px)=>/(_ z Pz)/=. \nby rewrite -eqzy mxvec_norm.\nmove: (P2 x Px)=>/(_ (mxvec y))/= P Py.\nrewrite mxvec_norm. apply P. by exists y.\nQed.\n\nLemma mxvec_open_set (A: set M) :\n  open A <-> open (mxvec @` A).\nProof.\nrewrite !openE; split=>/=.\nmove=>P1 y/= [x Px eqxy].\nmove: (P1 x Px) => /=. rewrite /interior.\nmove/nbhs_ballP=>[/=e egt0 Pb].\napply/nbhs_ballP. exists e=>// z/= Pz.\nexists (vec_mx z). apply Pb. move: Pz.\nby rewrite -!ball_normE/= -(mxvecK x) -linearB/= mxvec_normV eqxy.\nby rewrite vec_mxK.\nmove=>P1 y/= Py. \nhave P3: (exists2 x : 'M_(m.+1, n.+1), A x & mxvec x = mxvec y) by exists y.\nmove: (P1 (mxvec y) P3). rewrite /interior.\nmove/nbhs_ballP=>[/=e egt0 Pb].\napply/nbhs_ballP. exists e=>// z/= Pz.\nmove: Pz (Pb (mxvec z)).\nrewrite -!ball_normE/= mxvec_norm linearB/= =>P4 P5.\nmove: (P5 P4)=>[t Pt] /eqP. by rewrite (inj_eq (can_inj mxvecK))=>/eqP <-.\nQed.\n\nLemma mxvec_setN (A: set M) : ~` [set mxvec x | x in A] = [set mxvec x | x in ~` A].\nProof.\nrewrite seteqP. split=>x/=; rewrite -forall2NP.\nmove=>/(_ (vec_mx x)). rewrite vec_mxK =>[[|//]]. exists (vec_mx x)=>//.\nby rewrite vec_mxK.\nmove=>[y Py eqxy] z. case E: (y == z).\nleft. by move/eqP: E=><-. right. \nrewrite -eqxy=>/eqP. by rewrite (inj_eq (can_inj mxvecK)) eq_sym E.\nQed.\n\nLemma mxvec_closed_set (A: set M) :\n  closed A <-> closed (mxvec @` A).\nProof.\nsplit. by rewrite -openC mxvec_open_set -closedC -{2}(setCK A) -mxvec_setN.\nby rewrite -openC mxvec_setN -mxvec_open_set -closedC setCK.\nQed.\n\nLemma bounded_closed_compact_mx (A : set M) :\n  bounded_set A -> closed A -> compact A.\nProof.\nmove=>/mxvec_bounded_set P1 /mxvec_closed_set P2.\nhave: compact (vec_mx @` (mxvec @` A)).\napply: (continuous_compact _ (bounded_closed_compact P1 P2)). \napply/continuous_subspaceT=>x _; apply: vec_mx_continuous.\nhave ->//: [set vec_mx x | x in [set mxvec x | x in A]] = A.\nrewrite seteqP. split=>x/=.\nmove=>[y [z Pz]] <- <-. by rewrite mxvecK.\nmove=>Px. exists (mxvec x). by exists x. by rewrite mxvecK.\nQed.\n\nLemma compact_unit_sphere : compact [set x : M | `|x| = 1%:R].\nProof. apply (bounded_closed_compact_mx bound_unit_sphere closed_unit_sphere). Qed.\n\nLemma continuous_mnorm : continuous mnorm.\nProof.\nmove: mnorm_ubounded => [c [cgt0 mnormb]].\nmove=> x s/= /nbhs_ballP [/=e egt0 Pb].\napply/nbhs_ballP. exists (e / c) =>//=; first by apply divr_gt0.\nmove=> y /= Pxy. apply (Pb (mnorm y)). move: Pxy. \nrewrite mx_norm_ball /ball /= => P1.\napply (le_lt_trans (lev_dist_dist _ x y)). \napply (le_lt_trans (mnormb (x - y))).\nby rewrite mulrC -ltr_pdivl_mulr.\nQed.\n\nLemma compact_unit_sphere_vint : compact (mnorm @` [set x : M | `|x| = 1%:R]).\nProof. apply continuous_compact. apply/continuous_subspaceT.\nmove=>x _; apply continuous_mnorm.\napply compact_unit_sphere.\nQed.\n\nLemma mx_norm_natmul (x : M) k : mx_norm (x *+ k) = (mx_norm x) *+ k.\nProof.\nrewrite [in RHS]/mx_norm; elim: k => [|k ih]; first by rewrite !mulr0n mx_norm0.\nrewrite !mulrS; apply/eqP; rewrite eq_le; apply/andP; split.\n  by rewrite -ih; exact/ler_mx_norm_add.\nhave [/mx_norm_eq0->|x0] := eqVneq (mx_norm x) 0.\n  by rewrite -/(mx_norm 0) -/(mx_norm 0) !(mul0rn,addr0,mx_norm0).\nrewrite -/(mx_norm x) -num_abs_le; last by rewrite mx_normE.\napply/bigmax_gerP; right => /=.\nhave [i Hi] := mx_norm_neq0 x0.\nexists i => //; rewrite Hi -!mulrS -normrMn mulmxnE.\nby rewrite le_eqVlt; apply/orP; left; apply/eqP/val_inj => /=; rewrite normr_id.\nQed.\n\nLemma unit_sphere_neq0 : (mnorm @` [set x : M | `|x| = 1%:R]) !=set0.\nProof.\nexists (mnorm (const_mx 1))=>/=. exists (const_mx 1)=>//.\nrewrite /normr/= mx_normrE. under eq_bigr do rewrite mxE.\napply/eqP. rewrite eq_le. apply/andP. split; last first.\nby apply/bigmax_gerP=>/=; right; exists (ord0,ord0)=>//; rewrite normr1.\nby apply/bigmax_lerP; split=>// i j; rewrite normr1.\nQed.\n\nLemma mnorm_lbounded : exists c : R, (0 < c /\\ forall x,  c * `|x| <= mnorm x).\nProof.\nmove: (compact_min compact_unit_sphere_vint unit_sphere_neq0)=>[c [v /= Pv1 Pv2] Py].\nhave Pc: 0 < c by rewrite -Pv2 normv_gt0 -normr_gt0 Pv1 ltr01.\nexists c. split=>//.\nmove=>x. case E: (x == 0).\nmove: E=>/eqP ->. by rewrite normr0 normv0 mulr0.\nhave E1: `|x| > 0 by rewrite normr_gt0 E.\nrewrite -{2}(scale1r x) -(@mulfV _ `|x|); last by move: E1; rewrite lt_def=>/andP[->].\nrewrite -scalerA normvZ normr_id mulrC. apply ler_pmul=>//.\nby apply ltW. apply Py. exists (`|x|^-1 *: x)=>//.\nrewrite mx_normZ ger0_norm ?inv_nng_ge0// mulVf//.\nby move: E1; rewrite lt_def=>/andP[->].\nQed.\n\nEnd equal_mx_norm. \nEnd realTypeMxCvg.\n\n\n(***********************Complex Matrix***********************)\nImport realTypeMxCvg.\n\n(*Remark: 'M_(0,m) and 'M_(m,0) are not canonical to normedZmodType \n  (normedtype does not adopt it) and matrix_normedModType\n  (this is impossible without changing the definition of ball of matrix).\n  On the other hand, we can talk about convergence on 'M_(0,m) and 'M_(m,0);\n  In particular, when dimension is packed, we are not able to always find \n  .+1 structure. So in this section, all the properties are proved for 'M_(m,n)\n  even if it's trivial  *)\n\nSection cmx_seq_composition.\nVariable (R: realType) (m n : nat).\nLocal Notation C := R[i].\nLocal Notation M := 'M[C]_(m,n).\nImplicit Type (f g: nat -> M) (r: nat) (a b : M) (s : nat -> C) (k: C).\n\nLemma Cmxhausdorff p q : hausdorff_space [topologicalType of 'M[C]_(p,q)].\nProof.\ncase: p=>[|p]; last first. case: q=>[|q]; last by apply: norm_hausdorff.\nall: rewrite ball_hausdorff=>/=a b /negP Pab; exfalso; apply Pab; apply/eqP;\napply/matrixP=>i j. by destruct j. by destruct i.\nQed.\n\nLemma cmxcvg_limE f a : f --> a <-> lim f = a /\\ cvg f.\nProof. \nsplit=>[P1|[ <-]//]. split. apply/cvg_lim. apply Cmxhausdorff.\napply P1. by move: P1=>/cvgP.\nQed.\n\nLemma cmxcvg_dim0n p (h: nat -> 'M[C]_(0,p)) (x : 'M[C]_(0,p)) : h --> x.\nProof. by rewrite !mx_dim0; apply: cvg_cst. Qed.\nLemma cmxcvg_dimn0 p (h: nat -> 'M[C]_(p,0)) (x : 'M[C]_(p,0)) : h --> x.\nProof. by rewrite !mx_dim0; apply: cvg_cst. Qed.\nLemma is_cmxcvg_dim0n p (h: nat -> 'M[C]_(0,p)) : cvg h.\nProof. by apply/cvg_ex; exists 0; apply cmxcvg_dim0n. Qed.\nLemma is_cmxcvg_dimn0 p (h: nat -> 'M[C]_(p,0)) : cvg h.\nProof. by apply/cvg_ex; exists 0; apply cmxcvg_dimn0. Qed.\n\n(* for quick use. directly use these lemmas have the problem on different canonical routes *)\n\nLemma cmxcvg_cst a : (fun n:nat=>a) --> a. Proof. exact: cvg_cst. Qed.\nLemma is_cmxcvg_cst a : cvg (fun n:nat=>a). Proof. exact: is_cvg_cst. Qed.\nLemma cmxlim_cst a : lim (fun n:nat=>a) = a. Proof. apply: lim_cst. apply Cmxhausdorff. Qed.\n\nLemma cmxcvgN f a : f --> a -> (- f) --> - a.\nProof.\ncase: m f a=>[f a _|m' f a]; [apply cmxcvg_dim0n|].\ncase: n f a=>[f a _|n' f a]; [apply cmxcvg_dimn0|exact: cvgN].\nQed.\n\nLemma is_cmxcvgN f : cvg f -> cvg (- f).\nProof. by move=> /cmxcvgN /cvgP. Qed.\n\nLemma is_cmxcvgNE f : cvg (- f) = cvg f.\nProof. by rewrite propeqE; split=> /cmxcvgN; rewrite ?opprK => /cvgP. Qed.\n\nLemma cmxcvgMn f r a : f --> a -> ((@GRing.natmul _)^~r \\o f) --> a *+ r.\nProof.\ncase: m f a=>[f a _|m' f a]; [apply cmxcvg_dim0n|].\ncase: n f a=>[f a _|n' f a]; [apply cmxcvg_dimn0|exact: cvgMn].\nQed.\n\nLemma is_cmxcvgMn f r : cvg f -> cvg ((@GRing.natmul _)^~r \\o f).\nProof. by move=> /(@cmxcvgMn _ r) /cvgP. Qed.\n\nLemma cmxcvgD f g a b : f --> a -> g --> b -> (f + g) --> a + b.\nProof.\ncase: m f g a b=>[f g a b _ _|m' f g a b]; [apply cmxcvg_dim0n|].\ncase: n f g a b=>[f g a b _ _|n' f g a b]; [apply cmxcvg_dimn0|exact: cvgD].\nQed.\n\nLemma is_cmxcvgD f g : cvg f -> cvg g -> cvg (f + g).\nProof. by have := cvgP _ (cmxcvgD _ _); apply. Qed.\n\nLemma cmxcvgB f g a b : f --> a -> g --> b -> (f - g) --> a - b.\nProof. by move=> ? ?; apply: cmxcvgD=>[//|]; apply: cmxcvgN. Qed.\n\nLemma is_cmxcvgB f g : cvg f -> cvg g -> cvg (f - g).\nProof. by have := cvgP _ (cmxcvgB _ _); apply. Qed.\n\nLemma is_cmxcvgDlE f g : cvg g -> cvg (f + g) = cvg f.\nProof.\nmove=> g_cvg; rewrite propeqE; split; last by move=> /is_cmxcvgD; apply.\nby move=> /is_cmxcvgB /(_ g_cvg); rewrite addrK.\nQed.\n\nLemma is_cmxcvgDrE f g : cvg f -> cvg (f + g) = cvg g.\nProof. by rewrite addrC; apply: is_cmxcvgDlE. Qed.\n\nLemma cmxcvgZ s f k a : s --> k -> f --> a -> (fun x => s x *: f x) --> k *: a.\nProof.\ncase: m f a=>[f a _ _|m' f a]; [apply cmxcvg_dim0n|].\ncase: n f a=>[f a _ _|n' f a]; [apply cmxcvg_dimn0|exact: cvgZ].\nQed.\n\nLemma is_cmxcvgZ s f : cvg s -> cvg f -> cvg (fun x => s x *: f x).\nProof. by have := cvgP _ (cmxcvgZ _ _); apply. Qed.\n\nLemma cmxcvgZl s k a : s --> k -> (fun x => s x *: a) --> k *: a.\nProof. by move=> ?; apply: cmxcvgZ => //; exact: cvg_cst. Qed.\n\nLemma is_cmxcvgZl s a : cvg s -> cvg (fun x => s x *: a).\nProof. by have := cvgP _ (cmxcvgZl  _); apply. Qed.\n\nLemma cmxcvgZr k f a : f --> a -> k \\*: f --> k *: a.\nProof. apply: cmxcvgZ => //; exact: cvg_cst. Qed.\n\nLemma is_cmxcvgZr k f : cvg f -> cvg (k *: f ).\nProof. by have := cvgP _ (cmxcvgZr  _); apply. Qed.\n\nLemma is_cmxcvgZrE k f : k != 0 -> cvg (k *: f) = cvg f.\nProof.\nmove=> k_neq0; rewrite propeqE; split => [/(@cmxcvgZr k^-1)|/(@cmxcvgZr k)/cvgP//].\nby under [_ \\*: _]funext => x /= do rewrite scalerK//; apply: cvgP.\nQed.\n\nLemma cmxlimN f : cvg f -> lim (- f) = - lim f.\nProof. by move=> ?; apply: cvg_lim; [apply Cmxhausdorff|apply: cmxcvgN]. Qed.\n\nLemma cmxlimD f g : cvg f -> cvg g -> lim (f + g) = lim f + lim g.\nProof. move=> Pf Pg; apply: cvg_lim; [apply Cmxhausdorff|apply: cmxcvgD;[apply Pf|apply Pg]]. Qed.\n\nLemma cmxlimB f g : cvg f -> cvg g -> lim (f - g) = lim f - lim g.\nProof. move=> Pf Pg; apply: cvg_lim; [apply Cmxhausdorff|apply: cmxcvgB;[apply Pf|apply Pg]]. Qed.\n\nLemma cmxlimZ s f : cvg s -> cvg f -> lim (fun x => s x *: f x) = lim s *: lim f.\nProof. move=> Ps Pf; apply: cvg_lim; [apply Cmxhausdorff|apply: cmxcvgZ;[apply Ps|apply Pf]]. Qed.\n\nLemma cmxlimZl s a : cvg s -> lim (fun x => s x *: a) = lim s *: a.\nProof. by move=> ?; apply: cvg_lim; [apply Cmxhausdorff|apply: cmxcvgZl]. Qed.\n\nLemma cmxlimZr k f : cvg f -> lim (k *: f) = k *: lim f.\nProof. by move=> ?; apply: cvg_lim; [apply Cmxhausdorff|apply: cmxcvgZr]. Qed.\n\n(* since only nontrivial matrix are canonical to normZmodType *)\nLemma cmxcvg_norm (h : nat->'M[C]_(m.+1,n.+1)) (x : 'M[C]_(m.+1,n.+1)) : \n  h --> x -> (Num.norm \\o h) --> `|x|.\nProof. exact: cvg_norm. Qed.\nLemma is_cmxcvg_norm (h : nat->'M[C]_(m.+1,n.+1)) : \n  cvg h -> cvg (Num.norm \\o h).\nProof. exact: is_cvg_norm. Qed.\nLemma cmxlim_norm (h : nat->'M[C]_(m.+1,n.+1)) : \n  cvg h -> lim (Num.norm \\o h) = `|lim h|.\nProof. exact: lim_norm. Qed.\n\nLemma cmxcvg_map f a (V : completeType) (h : M -> V) :\n  continuous h -> f --> a -> (h \\o f) --> h a.\nProof. \nmove=>ch cvgf; apply: (@cvg_fmap _ _ [filter of f] a h).\nby apply ch. by apply cvgf.\nQed.\n\nLemma cmxcvg_mapV (V : completeType) (h : V -> M) (h' : nat -> V) (a : V) :\n  continuous h -> h' --> a -> (h \\o h') --> h a.\nProof. \nmove=>ch cvgf; apply: (@cvg_fmap _ _ [filter of h'] a h).\nby apply ch. by apply cvgf.\nQed.\n\nLemma is_cmxcvg_map f (V : completeType) (h : M -> V) :\n  continuous h -> cvg f -> cvg (h \\o f).\nProof.\nmove=>P1 /cvg_ex=>[/= [a Pa]]. apply/cvg_ex.\nexists (h a). by move: (cmxcvg_map P1 Pa).\nQed.\n\nLemma is_cmxcvg_mapV (V : completeType) (h : V -> M) (h' : nat -> V) :\n  continuous h -> cvg h' -> cvg (h \\o h').\nProof.\nmove=>P1 /cvg_ex=>[/= [a Pa]]. apply/cvg_ex.\nexists (h a). by move: (cmxcvg_mapV P1 Pa).\nQed.\n\nLemma cmxlim_map f a (V : completeType) (h : M -> V) :\n  hausdorff_space V -> continuous h -> cvg f -> lim (h \\o f) = h (lim f).\nProof. by move=>hV ch; move/(cmxcvg_map ch)/cvg_lim=>/(_ hV). Qed.\n\nLemma cmxlim_mapV (V : completeType) (h : V -> M) (h' : nat -> V) :\n  continuous h -> cvg h' -> lim (h \\o h') = h (lim h').\nProof. by move=>ch; move/(cmxcvg_mapV ch)/cvg_lim=>/(_ (@Cmxhausdorff _ _)). Qed.\n\nLemma is_cmxcvgZlE s a : a != 0 -> cvg (fun x => s x *: a) = cvg s.\nProof.\nmove=> a_neq0; rewrite propeqE; split; last by apply is_cmxcvgZl.\nhave [i [j Pij]] : exists i j, a i j != 0.\nmove: a_neq0. apply contraPP. rewrite -forallNP=>P.\napply/negP. rewrite negbK. apply/eqP/matrixP=>i j.\nmove: (P i). rewrite -forallNP=>/(_ j)/negP. by rewrite mxE negbK=>/eqP->.\nset t := (fun x : M => (x i j) / (a i j)).\nhave P1: s = t \\o (fun x : nat => s x *: a).\nrewrite funeqE=>p. rewrite /= /t mxE mulrK//.\nmove=>P. rewrite P1. apply/is_cmxcvg_map=>//.\nmove=>/= x w/= /nbhs_ballP [/=e egt0 Pb].\napply/nbhs_ballP. have P2: 0 < `|a i j|.\nrewrite lt_def Num.Theory.normr_ge0 andbT.\nby move: Pij; apply contraNN=>/eqP/Num.Theory.normr0P.\nexists (e * `|a i j|) =>//=. apply Num.Theory.mulr_gt0=>//.\nmove=> y /= Pxy. apply (Pb (t y)). move: Pxy.\nrewrite /ball/= /mx_ball=>/(_ i j). rewrite /ball/=.\nrewrite /t -mulrBl Num.Theory.normrM Num.Theory.normrV ?GRing.unitfE//.\nrewrite Num.Theory.ltr_pdivr_mulr// =>P3.\nQed.\n\nLemma mx_normEV p q : (@mx_norm _ _ _ : 'M[C]_(p.+1,q.+1) -> C) = (@Num.Def.normr _ _).\nProof. by apply/funext. Qed.\n\nLemma cmxcvg_limP p q (h: nat -> 'M[C]_(p,q)) (x : 'M[C]_(p,q)) :\n  h --> x <-> forall e, 0 < e -> exists N, forall n,  (N <= n)%N -> mx_norm (h n - x) < e.\nProof.\ncase: p h x=>[h x|p]; last case: q=>[h x|q h x].\n1,2: split=>_; [move=>e Pe; exists 0%N=>r _; rewrite !mx_dim0 mx_norm0//|].\napply cmxcvg_dim0n. apply cmxcvg_dimn0. rewrite mx_normEV.\nexact: (@cvg_limP _ [completeNormedModType C of 'M_(p.+1, q.+1)] h x).\nQed.\n\nLemma cmxcvg_subseqP p q (h: nat -> 'M[C]_(p,q)) (x : 'M[C]_(p,q)) : \n  h --> x <-> (forall (h': nat -> nat), (forall n, (h' n.+1 > h' n)%N) -> (h \\o h') --> x).\nProof.\ncase: p h x=>[h x|p]; last case: q=>[h x|q h x].\n1,2: split=>_; [move=>??|]; rewrite !mx_dim0; apply: cvg_cst.\nexact: (@cvg_subseqP _ [completeNormedModType C of 'M_(p.+1, q.+1)] h x).\nQed.\n\nLemma cmxcvg_subseqPN p q (h: nat -> 'M[C]_(p,q)) (x : 'M[C]_(p,q)) :\n  ~ (h --> x) <-> exists e (h': nat -> nat), \n    (forall n, (h' n.+1 > h' n)%N) /\\ 0 < e /\\ (forall n, mx_norm ((h \\o h') n - x) >= e).\nProof.\ncase: p h x=>[h x|p]; last case: q=>[h x|q h x].\n1,2: rewrite not_existsP; rewrite iff_not2; split=>_;[|rewrite !mx_dim0; apply: cvg_cst].\n1,2: move=>c; rewrite -forallNP=> h'; rewrite !not_andP; right.\n1,2: case E: (0 < c); [right|left=>//]; rewrite -existsNP; exists 0%N; rewrite !mx_dim0 mx_norm0.\n1,2: by apply/negP; rewrite -Num.Theory.real_ltNge// ?Num.Theory.real0// Num.Theory.gtr0_real.\nrewrite mx_normEV.\nexact: (@cvg_subseqPN _ [completeNormedModType C of 'M_(p.+1, q.+1)] h x).\nQed.\n\nLemma cmxnatmul_continuous p : continuous (fun x : M => x *+ p).\nProof.\ncase: m=>/=[x|m']; last case: n=>/=[x|n' x].\n1,2: rewrite !mx_dim0; apply: cst_continuous.\nexact: natmul_continuous.\nQed.\n\nLemma cmxscale_continuous : continuous (fun z : C * M => z.1 *: z.2).\nProof.\ncase: m=>/=[x|m']; last case: n=>/=[x|n' x].\n1,2: rewrite !mx_dim0; apply: cst_continuous.\nexact: scale_continuous.\nQed.\n\nArguments cmxscale_continuous _ _ : clear implicits.\n\nLemma cmxscaler_continuous k : continuous (fun x : M => k *: x).\nProof.\nby move=> x; apply: (cvg_comp2 (cvg_cst _) cvg_id (cmxscale_continuous (_, _))).\nQed.\n\nLemma cmxscalel_continuous (x : M) : continuous (fun k : C => k *: x).\nProof.\nby move=> k; apply: (cvg_comp2 cvg_id (cvg_cst _) (cmxscale_continuous (_, _))).\nQed.\n\n(* TODO: generalize to pseudometricnormedzmod *)\nLemma cmxopp_continuous : continuous (fun x : M => -x).\nProof.\ncase: m=>/=[x|m']; last case: n=>/=[x|n' x].\n1,2: rewrite !mx_dim0; apply: cst_continuous.\nexact: opp_continuous.\nQed.\n\nLemma cmxadd_continuous : continuous (fun z : M * M => z.1 + z.2).\nProof.\ncase: m=>/=[x|m']; last case: n=>/=[x|n' x].\n1,2: rewrite !mx_dim0; apply: cst_continuous.\nexact: add_continuous.\nQed.\n\nArguments cmxadd_continuous _ _ : clear implicits.\n\nLemma cmxaddr_continuous a : continuous (fun z : M => a + z).\nProof.\nby move=> x; apply: (cvg_comp2 (cvg_cst _) cvg_id (cmxadd_continuous (_, _))).\nQed.\n\nLemma cmxaddl_continuous a : continuous (fun z : M => z + a).\nProof.\nby move=> x; apply: (cvg_comp2 cvg_id (cvg_cst _) (cmxadd_continuous (_, _))).\nQed.\n\n(* Variable (f : nat -> 'M[R[i]]_(m,n)) (a : 'M[R[i]]_(m,n)). *)\nDefinition cmxcauchy_seq f := \n  forall e, 0 < e -> exists N, forall i j, \n  (N <= i)%N -> (N <= j)%N -> mx_norm (f i - f j) < e.\n\nDefinition cmxcvg_seq f a := \n  forall e, 0 < e -> exists N : nat, \n    forall i, (N <= i)%N -> mx_norm (a - f i) < e.\n\nLemma cmxcauchy_seqP f : cmxcauchy_seq f <-> cvg f.\nProof.\nrewrite /cmxcauchy_seq; case: m f=>[f|]; last case: n=>[m' f|m' n' f].\n1,2: split=>_. apply/is_cmxcvg_dim0n. 2: apply/is_cmxcvg_dimn0.\n1,2: by move=>e egt0; exists 0%N=>i j _ _; rewrite !mx_dim0 mx_norm0.\nexact: (@cauchy_seqP _ [completeNormedModType R[i] of 'M[R[i]]_(n'.+1,m'.+1)]).\nQed.\n\nLemma cmxcvg_seqP f a : cmxcvg_seq f a <-> f --> a.\nProof.\nrewrite /cmxcvg_seq; case: m f a=>[f a|]; last case: n=>[m' f a|m' n' f a].\n1,2: split=>[_ |_ e egt0]; last exists 0%N=>i _. \n1,2,3,4: rewrite !mx_dim0 ?mx_norm0//. apply/cmxcvg_dim0n. apply/cmxcvg_dimn0.\nexact: (@cvg_seqP _ [completeNormedModType R[i] of 'M[R[i]]_(n'.+1,m'.+1)]).\nQed.\n\nEnd cmx_seq_composition.\n\nSection cmx_linear_continuous.\nVariable (R: realType).\nLocal Notation C := R[i].\n\nImport Num.Theory ComplexField Num.Def complex.\n\nLemma mx_normcE m n (x : 'M[C]_(m,n)) :\n  mx_norm x = \\big[maxr/0]_ij `| x ij.1 ij.2|.\nProof.\nrewrite /mx_norm; apply/esym.\nelim/big_ind2 : _ => //= a a' b b' ->{a'} ->{b'}.\ncase: (leP a b) => ab; by [rewrite max_r | rewrite max_l // ltW].\nQed.\n\nLemma bigmax_eqc I (r : seq I) (F : I -> R) (x : R) :\n  \\big[maxr/x%:C]_(i <- r) (F i)%:C = (\\big[maxr/x]_(i <- r) (F i))%:C.\nProof.\nelim: r. by rewrite !big_nil.\nmove=>a r IH. rewrite !big_cons IH /maxr ltcR /maxr.\nby case: ltP.\nQed.\n\nLemma mx_normcE1 m n (x : 'M[C]_(m,n)) :\n  mx_norm x = (\\big[maxr/0]_ij Re `| x ij.1 ij.2|)%:C.\nrewrite mx_normcE -bigmax_eqc.\napply eq_bigr=>i _. set t := `|x i.1 i.2|.\nhave: 0 <= t. rewrite /t normr_ge0//.\nrewrite -{2}(complex_split t) lecE=>/andP[/eqP-> _].\nby rewrite addr0.\nQed.\n\nLemma mx_norm_element m n (x : 'M[C]_(m.+1,n.+1)) :\n  forall i, `|x i.1 i.2| <= `|x|.\nProof.\nmove=>i. rewrite {2}/normr/= mx_normcE1.\nrewrite lecE/= eqxx/=. apply: ler_bigmax.\nQed.\n\nLemma ltr_sum n (F G : 'I_n.+1 -> C) :\n    (forall i, F i < G i) ->\n  \\sum_(i < n.+1) F i < \\sum_(i < n.+1) G i.\nProof.\nmove: F G. elim: n.\nby move=>F G IH; rewrite !big_ord1 IH.\nmove=>m IH F G IH1.\nrewrite big_ord_recl [\\sum_(i < m.+2) G i]big_ord_recl.\napply ltr_add. by apply IH1.\napply IH=>i. apply IH1.\nQed.\n\nLemma ler_sum_const (T: numDomainType) m (f : 'I_m -> T) c :\n  (forall i, f i <= c) ->\n  \\sum_i f i <= m%:R * c.\nProof.\nmove=>P1; have P2: \\sum_i f i <= \\sum_(i<m) c. by apply ler_sum.\napply: (le_trans P2); by rewrite sumr_const card_ord mulr_natl.\nQed.\n\nLemma cmxlinear_continuous m n p q (f : 'M[C]_(m,n) -> 'M[C]_(p,q)) :\n  linear f -> continuous f.\nProof.\nmove: f; case: m=>[|m]; last first. case: n=>[|n]; last first. \ncase: p=>[|p]; last first. case: q=>[|q]; last first.\nall: move=>f Lf; set LfT := Linear Lf; have P0 : f = LfT by [].\nsuff: continuous LfT by [].\nrewrite -linear_bounded_continuous -bounded_funP=>r/=.\nhave Pu : exists c, forall i j, `|LfT (delta_mx i j)| <= c.\nexists (\\sum_i\\sum_j`|LfT (delta_mx i j)|)=>i j.\nrewrite (bigD1 i)//= (bigD1 j)//= -addrA Num.Theory.ler_addl Num.Theory.addr_ge0//.\n1,2: rewrite Num.Theory.sumr_ge0//. move=>k _; rewrite Num.Theory.sumr_ge0//.\nmove: Pu=>[c Pc]. exists ((m.+1)%:R * ((n.+1)%:R * (r * c)))=>x Px.\nhave Pij i j : `|x i j| <= r by apply (le_trans (mx_norm_element _ (i,j))).\nrewrite (matrix_sum_delta x) P0 linear_sum/=.\napply: (le_trans (ler_norm_sum _ _ _)). apply/ler_sum_const=>i.\nrewrite P0 linear_sum/=.\napply: (le_trans (ler_norm_sum _ _ _)). apply/ler_sum_const=>j.\nby rewrite P0 linearZ/= normmZ ler_pmul.\nall: have ->: f = (fun=>0). 2,4,6,8: apply: cst_continuous.\nall: apply/funext=>i. all: rewrite mx_dim0E// P0 linear0//.\nQed.\n\nLemma cmxcvg_lfun m n p q (f : 'M[C]_(m,n) -> 'M[C]_(p,q))\n  (u : nat -> 'M[C]_(m,n)) (a : 'M[C]_(m,n)) : \n  linear f -> u --> a -> (fun x=> f (u x)) --> (f a).\nProof. by move/cmxlinear_continuous=>P1; apply: continuous_cvg; apply: P1. Qed.\n\nLemma is_cmxcvg_lfun m n p q (f : 'M[C]_(m,n) -> 'M[C]_(p,q))\n(u : nat -> 'M[C]_(m,n))  : linear f -> cvg u -> cvg (f \\o u).\nProof. by move=>P1; have := cvgP _ (cmxcvg_lfun P1 _); apply. Qed.\n\nLemma cmxlim_lfun m n p q (f : 'M[C]_(m,n) -> 'M[C]_(p,q))\n  (u : nat -> 'M[C]_(m,n)) : \n  linear f -> cvg u -> lim (f \\o u) = f (lim u).\nProof. move=>P1 ?; apply: cvg_lim => //. apply Cmxhausdorff. by apply: cmxcvg_lfun. Qed.\n\nLemma cmxclosed_comp m n p q (f : 'M[C]_(m,n) -> 'M[C]_(p,q))\n  (A : set 'M[C]_(p,q)) :\n  linear f -> closed A -> closed (f @^-1` A).\nProof. by move=>lf; apply closed_comp=>x _; apply (cmxlinear_continuous lf). Qed.\n\nLemma cmxopen_comp m n p q (f : 'M[C]_(m,n) -> 'M[C]_(p,q))\n  (A : set 'M[C]_(p,q)) :\n  linear f -> open A -> open (f @^-1` A).\nProof. by move=>lf; apply open_comp=>x _; apply (cmxlinear_continuous lf). Qed.\n\nLemma cmxscalar_continuous m n (f : 'M[C]_(m,n) -> C) :\n  scalar f -> continuous f.\nProof.\nmove: f; case: m=>[|m]; last first. case: n=>[|n]; last first.\nall: move=>f Lf; set LfT := Linear Lf; have P0 : f = LfT by [].\nsuff: continuous LfT by [].\nrewrite -linear_bounded_continuous -bounded_funP=>r/=.\nhave Pu : exists c, forall i j, `|LfT (delta_mx i j)| <= c.\nexists (\\sum_i\\sum_j`|LfT (delta_mx i j)|)=>i j.\nrewrite (bigD1 i)//= (bigD1 j)//= -addrA ler_addl addr_ge0//.\n1,2: rewrite sumr_ge0//. move=>k _. rewrite sumr_ge0//.\nmove: Pu=>[c Pc]. exists ((m.+1)%:R * ((n.+1)%:R * (r * c)))=>x Px.\nhave Pij i j : `|x i j| <= r by apply (le_trans (mx_norm_element _ (i,j))).\nrewrite (matrix_sum_delta x) P0 linear_sum/=.\napply: (le_trans (ler_norm_sum _ _ _)). apply/ler_sum_const=>i.\nrewrite P0 linear_sum/=.\napply: (le_trans (ler_norm_sum _ _ _)). apply/ler_sum_const=>j.\nby rewrite P0 linearZ/= normmZ ler_pmul.\nall: have ->: f = (fun=>0). 2,4: apply: cst_continuous.\nall: apply/funext=>i. all: rewrite mx_dim0E// P0 linear0//.\nQed.\n\nLemma cmxcvg_sfun m n (f : 'M[C]_(m,n) -> C)\n  (u : nat -> 'M[C]_(m,n)) (a : 'M[C]_(m,n)) : \n  scalar f -> u --> a -> (fun x=> f (u x)) --> (f a).\nProof. by move/cmxscalar_continuous=>P1; apply: continuous_cvg; apply: P1. Qed.\n\nLemma is_cmxcvg_sfun m n (f : 'M[C]_(m,n) -> C)\n(u : nat -> 'M[C]_(m,n)) : scalar f -> cvg u -> cvg (f \\o u).\nProof. by move=>P1; have := cvgP _ (cmxcvg_sfun P1 _); apply. Qed.\n\nLemma cmxlim_sfun m n (f : 'M[C]_(m,n) -> C)\n  (u : nat -> 'M[C]_(m,n)) : \n  scalar f -> cvg u -> lim (f \\o u) = f (lim u).\nProof. move=>P1 ?; apply: cvg_lim => //. by apply: cmxcvg_sfun. Qed.\n\nLemma cmxcclosed_comp m n (f : 'M[C]_(m,n) -> C)\n  (A : set C) :\n  scalar f -> closed A -> closed (f @^-1` A).\nProof. by move=>lf; apply closed_comp=>x _; apply (cmxscalar_continuous lf). Qed.\n\nLemma cmxcopen_comp m n (f : 'M[C]_(m,n) -> C)\n  (A : set C) :\n  scalar f -> open A -> open (f @^-1` A).\nProof. by move=>lf; apply open_comp=>x _; apply (cmxscalar_continuous lf). Qed.\n\nEnd cmx_linear_continuous.\n\n(* construct linear bijective functions: complex matrix <--> real vector *)\nSection complex_mx2vec.\nImport ComplexField.\nVariable (R: realType) (m n : nat).\nLocal Notation C := R[i].\n\nDefinition cmxvec (x : 'M[C]_(m,n)) := \n    row_mx (mxvec (map_mx (@Re _) x)) (mxvec (map_mx (@Im _) x)).\n\nDefinition cvec_mx (u : 'rV[R]_(m * n + m * n)) := \n  map_mx (fun x=> x%:C) (vec_mx (lsubmx u)) + \n    map_mx (fun x=> x%:Ci) ( vec_mx (rsubmx u)).\n\nLemma cmxvec_is_additive : additive cmxvec.\nProof. by move=>x y; rewrite /cmxvec -!map_mxvec !raddfB/= opp_row_mx add_row_mx. Qed.\n\nLemma cvec_mx_is_additive : additive cvec_mx.\nProof.\nmove=>x y; rewrite /cvec_mx !map_vec_mx.\nrewrite !raddfB/= (@map_mxB _ _ (im_complex_additive R))/= !linearB/= linearD/= !addrA.\ncongr (_ + _). rewrite -!addrA. congr (_ + _). by rewrite addrC.\nQed.\n\nCanonical cmxvec_additive := Additive cmxvec_is_additive.\nCanonical cvec_mx_additive := Additive cvec_mx_is_additive.\n\nLemma cvec_mxK : cancel cvec_mx cmxvec.\nProof. \nmove=>x. rewrite /cvec_mx raddfD/= /cmxvec add_row_mx -!map_mxvec !vec_mxK.\nby rewrite -[RHS]hsubmxK; congr (row_mx _ _); rewrite /map_mx; \n  apply/matrixP=>i j; rewrite !mxE/= ?addr0 ?add0r. \nQed.\n\nLemma cmxvecK : cancel cmxvec cvec_mx.\nProof.\nmove=>x. rewrite /cvec_mx /cmxvec row_mxKl row_mxKr !mxvecK.\nby apply/matrixP=>i j; rewrite !mxE/= complex_split.\nQed.\n\nLemma cmxvecZ (c : R) x : cmxvec (c%:C *: x) = c *: cmxvec x.\nProof.\nrewrite /cmxvec scale_row_mx -!linearZ/=. \nby congr (row_mx (mxvec _) (mxvec _)); apply/matrixP=>i j; rewrite !mxE; \nset y := x i j; destruct y=>/=; rewrite mul0r ?subr0 ?addr0.\nQed.\n\nLemma cvec_mxZ (c : R) x : cvec_mx (c *: x) = c%:C *: cvec_mx x.\nProof. by rewrite -[RHS]cmxvecK cmxvecZ cvec_mxK. Qed.\n\nEnd complex_mx2vec.\n\n(* TODO: please pack mnorm later, perhaps an alias of matrix?     *)\n(* equivalent norms : mnorm (complex matrix) <--> `|real vector| *)\nSection complex_mx2vec_vnorm.\nVariable (R: realType) (m n : nat).\nLocal Notation C := R[i].\nLocal Notation M := 'M[C]_(m.+1,n.+1).\nVariable (mnorm : vnorm [lmodType C of M]).\n\nDefinition cm2rvnorm x := Re (mnorm (cvec_mx x)).\n(* relation of cm2rvnorm and mnorm *)\nLemma cm2rvnormE x : mnorm x = (cm2rvnorm (cmxvec x))%:C.\nProof. rewrite /cm2rvnorm cmxvecK RRe_real//. apply/Num.Theory.ger0_real/normv_ge0. Qed.\n\nLocal Lemma hv1 : forall x y, cm2rvnorm (x + y) <= cm2rvnorm x + cm2rvnorm y.\nProof.\nmove=>x y. rewrite /cm2rvnorm -raddfD/= raddfD/=. \nmove: (lev_norm_add mnorm (cvec_mx x) (cvec_mx y)).\nby rewrite lecE=>/andP[_].\nQed.\n\nLocal Lemma hv2 : forall x, cm2rvnorm x = 0 -> x = 0.\nProof.\nmove=>x. rewrite /cm2rvnorm -{2}(cvec_mxK x). move/(f_equal (real_complex R)).\nrewrite RRe_real. move/normv0_eq0=>->. apply: raddf0.\napply/Num.Theory.ger0_real/normv_ge0.\nQed.\n\nLocal Lemma hv4 : forall a x, cm2rvnorm (a *: x) = `|a| * cm2rvnorm x.\nProof.\nmove=>a x; rewrite /cm2rvnorm cvec_mxZ normvZ. set y := mnorm (cvec_mx x).\nsuff ->: `|a%:C| = `|a|%:C by destruct y; simpc=>/=.\nby rewrite normc_def/= expr0n/= addr0 Num.Theory.sqrtr_sqr.\nQed.\n\nCanonical cm2rvVnorm := Vnorm hv1 hv2 hv4.\n\nLemma ubound1 : exists2 c, 0 < c & forall x, mnorm x <= (c * `|cmxvec x|)%:C.\nProof.\nmove: (mnorm_ubounded cm2rvVnorm)=>[c [cgt0 Pc]].\nexists c=>// x. rewrite cm2rvnormE lecR. apply Pc.\nQed.\n\nLemma lbound1 : exists2 c : R, 0 < c & forall x : 'M[C]_(m.+1,n.+1), (c * `|cmxvec x|)%:C <= mnorm x.\nProof.\nmove: (mnorm_lbounded cm2rvVnorm)=>[c [cgt0 Pc]].\nexists c=>// x. rewrite cm2rvnormE lecR. apply Pc.\nQed.\n\nEnd complex_mx2vec_vnorm.\n\n\n(* equivalent norms : mnorm (complex matrix) <--> `|complex matrix| *)\n(* `| | default norm, i.e., the maximum norm                        *)\n(* thus prove the equivalence between mx_norm and any vector norm   *)\n(* i.e., exists c1 c2, c1 > 0 & c2 > 0 &                            *)\n(*                forall x, c1 * `|x| <= mnorm x <= c2 * `|x|       *)\n(* then shows that the cauchy seq w.r.t. mnorm converge             *)\nSection vnorm_eq_mx_norm.\nImport realTypeMxCvg Num.Theory.\nLocal Open Scope complex_scope.\nVariable (R: realType) (m n : nat).\nLocal Notation C := R[i].\nLocal Notation M := 'M[C]_(m.+1,n.+1).\nVariable (mnorm : vnorm [lmodType C of M]).\n\nLemma hn1: forall (x y : M), `| x + y | <= `| x | + `| y |.\nProof. by apply: ler_norm_add. Qed.\nLemma hn2: forall (x : M), `| x | = 0 -> x = 0.\nProof. by apply: normr0_eq0. Qed.\nLemma hn4: forall a (x : M), `| a *: x | = `|a| * `| x |.\nProof. by move=>x a; rewrite normmZ. Qed.\nDefinition matrix_normedVnorm := Vnorm hn1 hn2 hn4.\n\nLemma mulcR (x y : R) : (x * y)%:C = x%:C * y%:C.\nProof. by simpc. Qed.\n\nLemma cmxnorm_ubounded : exists2 c, 0 < c & forall x, mnorm x <= c * `| x |.\nProof.\nmove: (ubound1 mnorm)=>[c1 c1gt0 Pc1].\nmove: (lbound1 matrix_normedVnorm)=>[c2 c2gt0 Pc2].\nhave Pc12 : 0 < (c1 / c2)%:C by rewrite ltcR; apply divr_gt0.\nexists (c1 / c2)%:C => // x. \napply (le_trans (Pc1 x)).\nrewrite [_ * `|x|]mulrC -ler_pdivr_mulr//.\napply: (le_trans _ (Pc2 x)).\nrewrite ler_pdivr_mulr// -mulcR lecR [_ * (_ / _)]mulrC !mulrA.\napply ler_pmul=>//. by apply ltW. \nby rewrite -ler_pdivr_mulr.\nQed.\n\nLemma cmxnorm_lbounded : exists2 c, 0 < c & forall x, c * `| x | <= mnorm x.\nProof.\nmove: (lbound1 mnorm)=>[c1 c1gt0 Pc1].\nmove: (ubound1 matrix_normedVnorm)=>[c2 c2gt0 Pc2].\nhave Pc12 : 0 < (c1 / c2)%:C by rewrite ltcR; apply divr_gt0.\nexists (c1 / c2)%:C => // x. \napply: (le_trans _ (Pc1 x)).\nrewrite mulrC -ler_pdivl_mulr//.\napply (le_trans (Pc2 x)).\nrewrite ler_pdivl_mulr// -mulcR lecR mulrC mulrA.\napply ler_pmul=>//; rewrite mulrVK=>//. by apply/ltW. all: by apply/unitf_gt0.\nQed.\n\nDefinition cauchy_seq_cmxmnorm (f : nat -> M) := \n  forall e : C, 0 < e -> exists N : nat, \n    forall s t, (N <= s)%N -> (N <= t)%N -> mnorm (f s - f t) < e.\n\n(* cauchy seq characterization *)\nLemma cmxcauchy_seq_eq (f : nat -> M) :\ncauchy_seq_cmxmnorm f <-> cmxcauchy_seq f.\nProof. split.\nmove: cmxnorm_lbounded => [c Pc le_mn] P e Pe.\nhave Pec: 0 < (e * c) by apply mulr_gt0.\nmove: (P _ Pec)=>[N PN]. exists N=>s t Ps Pt.\nmove: (le_lt_trans (le_mn (f s - f t)) (PN s t Ps Pt)).\nset x := `|f s - f t|.\nby rewrite mulrC -subr_gt0 -mulrBl (pmulr_lgt0 _ Pc) subr_gt0.\nmove: cmxnorm_ubounded => [c Pc le_mn] P e Pe.\nhave Pec: 0 < (e / c) by apply divr_gt0.\nmove: (P (e/c) Pec )=>[N PN]. exists N=>s t Ps Pt.\napply: (le_lt_trans (le_mn (f s - f t))).\nmove: (PN s t Ps Pt).\nset x := `|f s - f t|.\nby rewrite ltr_pdivl_mulr// mulrC.\nQed.\n\nLemma cmxcauchy_seq_cvg (f : nat -> M) :\n  cauchy_seq_cmxmnorm f <-> cvg f.\nProof. by rewrite cmxcauchy_seq_eq; apply: cmxcauchy_seqP. Qed.\n\nEnd vnorm_eq_mx_norm.\n\nSection CauchySeqVnorm.\nVariable (R: realType) (m n : nat) (mnorm : vnorm [lmodType R[i] of 'M[R[i]]_(m,n)]).\n\nLemma cmxcauchy_seqv_cvg (f : nat -> 'M[R[i]]_(m,n)) :\n  cauchy_seqv mnorm f <-> cvg f.\nProof.\ncase: m mnorm f=>[mnorm' f|m']; last case: n=>[mnorm' f|n' mnorm' f].\n1,2: by rewrite !mx_dim0; split=>_; [apply: cmxcvg_cst | apply cauchy_seqv_cst].\nby rewrite -(cmxcauchy_seq_cvg mnorm').\nQed.\n\nEnd CauchySeqVnorm.\n\nSection EquivalenceVnorm.\nVariable (R: realType) (m n : nat).\nVariable (mnorm1 mnorm2 : vnorm [lmodType R[i] of 'M[R[i]]_(m,n)]).\n\nLemma cmxnormv_bounded :\n  exists2 c : R[i], 0 < c & forall x, mnorm1 x <= c * mnorm2 x.\nProof.\ncase: m mnorm1 mnorm2; clear m mnorm1 mnorm2. 2: case: n=>m.\n1,2: by move=>mnorm1 mnorm2; exists 1=>//= x; rewrite !mx_dim0 !normv0 mulr0.\nmove=>p mnorm1 mnorm2; move: (cmxnorm_ubounded mnorm1)=>/=[c1 Pc1 P1].\nmove: (cmxnorm_lbounded mnorm2)=>/=[c2 Pc2 P2].\nexists (c1 / c2)=>[|x]; first by apply Num.Theory.divr_gt0.\napply (le_trans (P1 x)). \nrewrite -mulrA Num.Theory.ler_pmul2l// Num.Theory.ler_pdivl_mull//.\nQed.\n\nLemma cmxcauchy_seqv_eq (f : nat -> 'M[R[i]]_(m,n)) :\n  cauchy_seqv mnorm1 f <-> cauchy_seqv mnorm2 f.\nProof. by rewrite !cmxcauchy_seqv_cvg. Qed.\n\nEnd EquivalenceVnorm.\n\nSection cmvnorm_cvg.\nImport realTypeMxCvg Num.Theory.\nLocal Open Scope complex_scope.\nVariable (R: realType) (m n : nat).\nLocal Notation C := R[i].\nVariable (mnorm : vnorm [lmodType C of 'M[C]_(m,n)]).\n\nLemma cmxnormv_continuous : continuous mnorm.\nProof.\ncase: m mnorm; clear m mnorm. 2: case: n; clear n=>n.\n1,2: move=>mnorm;\nsuff ->: (mnorm : 'M_(_,_) -> C) = (fun=>mnorm 0) by apply: cst_continuous.\n1,2: by apply/funext=>x; rewrite mx_dim0E.\nmove=>m mnorm x s/= /nbhs_ballP [/=e egt0 Pb]; apply/nbhs_ballP.\nmove: (cmxnorm_ubounded mnorm) => [c Pc le_mn].\nexists (e / c)=>/=[|y Py/=]. by apply divr_gt0.\napply Pb. move: Py. rewrite mx_norm_ball /ball/=.\nmove=>P1; apply: (le_lt_trans (lev_dist_dist mnorm _ _)).\nby apply: (le_lt_trans (le_mn _)); rewrite mulrC -ltr_pdivl_mulr.\nQed.\n\nLemma cmxcvg_normv (f : 'M[C]_(m,n) ^nat) (a: 'M[C]_(m,n)) : \n  f --> a -> (fun x=> mnorm (f x)) --> (mnorm a).\nProof. by apply: continuous_cvg; apply: cmxnormv_continuous. Qed.\n\nLemma is_cmxcvg_normv (f : 'M[C]_(m,n) ^nat) : cvg f -> cvg (mnorm \\o f).\nProof. by have := cvgP _ (cmxcvg_normv _); apply. Qed.\n\nLemma cmxlim_normv (f : 'M[C]_(m,n) ^nat) : \n  cvg f -> lim (mnorm \\o f) = mnorm (lim f).\nProof. by move=> ?; apply: cvg_lim => //; apply: cmxcvg_normv. Qed.\n\nEnd cmvnorm_cvg.\n\nRequire Import cpo.\n\nSection Bolzano_Weierstrass.\nVariables (R: realType).\nLocal Notation C := R[i].\nImport Num.Def Num.Theory.\n\nLemma nonincreasing_homo {d : unit} [T : porderType d] (c : nat -> T) :\n  (forall n, c n >= c n.+1)%O -> {homo c : x y / (x <= y)%N >-> (y <= x)%O}.\nProof.\nmove=> cc x y /subnK => <-; elim: (y - x)%N => //= n ih.\nby rewrite addSn; apply: (le_trans _ ih); apply: cc.\nQed.\n\nLemma R_bound_subcvg (f : nat -> R) (M : R) :\n  (forall n, `|f n| <= M) -> exists (h: nat -> nat), \n    (forall n, (h n.+1 > h n)%N) /\\ cvg (f \\o h).\nProof.\nmove=>sb; pose Q n := forall m, (n <= m)%N -> (f m <= f n).\npose Esub := (exists h : nat -> nat,\n(forall n : nat, (h n < h n.+1)%N) /\\ (forall n : nat, Q (h n))).\nmove: (EM Esub)=>[[h [Ph1 Ph2]]|/non_exists_nseq[N P1]].\nexists h; split=>//. apply: nonincreasing_is_cvg.\nby apply/nonincreasing_homo=> n/=; apply/(Ph2 n (h n.+1))/ltnW/Ph1.\nby exists (-M)=>n/=[m _] <-; move: (sb (h m)); rewrite ler_norml=>/andP[].\nhave P2 n: {m : nat | (n < m)%N /\\ f (N + n)%N <= f (N + m)%N}.\napply/cid. move: (P1 _ (leq_addr n N)); rewrite/Q.\napply contra_notP; rewrite not_existsP notK=>IH m.\nrewrite leq_eqVlt=>/orP[/eqP<-//|Pm].\nhave E1: (N < m)%N by apply/(leq_ltn_trans _ Pm)/leq_addr.\napply/ltW; rewrite -(subnKC (ltnW E1)) real_ltNge ?num_real//; apply/negP.\nmove: (IH (m-N)%N); rewrite -implyNE=>P2; apply P2; by rewrite ltn_subRL.\nexists ((fun n=>N+n)%N \\o (nseq_sig P2)); split.\nmove=>n; rewrite /comp ltn_add2l nseq_sigE.\nby move: (projT2 (P2 (nseq_sig P2 n)))=>[+_].\napply: nondecreasing_is_cvg.\napply/chain_homo=>n; rewrite/comp nseq_sigE.\nby move: (projT2 (P2 (nseq_sig P2 n)))=>[].\nby exists M=>n/=[m _] <-; move: (sb (N + nseq_sig P2 m)%N); rewrite ler_norml=>/andP[].\nQed.\n\nLemma normc_ge_Im (x : R[i]) : `|complex.Im x|%:C <= `|x|.\nProof.\nby case: x => a b; simpc; rewrite -sqrtr_sqr ler_wsqrtr // ler_addr sqr_ge0.\nQed.\n\nLemma C_bound_subcvg (f : nat -> C) (M : C) :\n  (forall n, `|f n| <= M) -> exists (h: nat -> nat), \n    (forall n, (h n.+1 > h n)%N) /\\ cvg (f \\o h).\nProof.\nmove=>P1. have PM : (complex.Re M)%:C = M.\nby apply/RRe_real/ger0_real; apply: (le_trans (normr_ge0 _) (P1 0%N)).\nhave P2 n : `|complex.Re (f n)| <= complex.Re M.\nby rewrite -lecR; apply: (le_trans (normc_ge_Re _)); rewrite PM.\nmove: (R_bound_subcvg P2)=>[h1 [Ph1 cvg1]].\nhave P3 n : `|complex.Im ((f \\o h1) n)| <= complex.Re M.\nby rewrite -lecR; apply: (le_trans (normc_ge_Im _)); rewrite PM/=.\nmove: (R_bound_subcvg P3)=>[h2 [Ph2 cvg2]].\nmove: cvg1=>/cvg_subseqP/(_ _ Ph2)=>cvg1/=.\nexists (h1\\o h2); split; first by move=>n/=; apply nchain_mono.\nrewrite -(cseq_split (f \\o (h1 \\o h2))). apply is_ccvgD.\napply/is_ccvg_mapV. exact: rc_continuous.\nhave ->: (complex.Re (R:=R) \\o (f \\o (h1 \\o h2))) = \n((fun n : nat => complex.Re (f n)) \\o h1) \\o h2 by apply/funext=>i/=.\napply/cvg_ex; exists (lim ((fun n : nat => complex.Re (f n)) \\o h1)); exact: cvg1.\napply/is_ccvg_mapV; [exact: ic_continuous | exact: cvg2].\nQed.\n\nLemma row_mx_norm (T : numDomainType) p m n (M1 : 'M[T]_(p.+1,m.+1)) (M2 : 'M[T]_(p.+1,n.+1)) :\n  mx_norm (row_mx M1 M2) = maxr (mx_norm M1) (mx_norm M2).\nProof.\nrewrite /mx_norm; apply/le_anti/andP; split.\nrewrite (bigmax_eq_arg (ord0,ord0))// =>[|i _]; last by rewrite -num_le//=.\nset i := [arg max_(i > (ord0, ord0))`|row_mx M1 M2 i.1 i.2|%:nng]%O : 'I_p.+1 * 'I_(m.+1 + n.+1).\ncase: i=>a b/=; rewrite -(splitK b); case: (fintype.split b)=>/= c;\nrewrite ?row_mxEl ?row_mxEr num_le_maxr; apply/orP; [left|right];\nrewrite -num_abs_le//; apply/bigmax_gerP; right;\nby exists (a,c)=>//=; rewrite -num_le/= normr_id.\nrewrite num_le_maxl; apply/andP; split;\nrewrite (bigmax_eq_arg (ord0,ord0))// =>[|i _].\n2,4: by rewrite -num_le//=. all: rewrite -num_abs_le//.\nset i := [arg max_(i > (ord0, ord0))`|M1 i.1 i.2|%:nng]%O.\nhave: `|(`|M1 i.1 i.2|%:nng)%:num|%:nng <= `|row_mx M1 M2 \n  (i.1,lshift n.+1 i.2).1 (i.1,lshift _ i.2).2|%:nng\n  by rewrite/= row_mxEl -num_le/= normr_id.\nby apply/bigmax_sup.\nset i := [arg max_(i > (ord0, ord0))`|M2 i.1 i.2|%:nng]%O.\nhave: `|(`|M2 i.1 i.2|%:nng)%:num|%:nng <= `|row_mx M1 M2 \n  (i.1,rshift m.+1 i.2).1 (i.1,rshift _ i.2).2|%:nng\n  by rewrite/= row_mxEr -num_le/= normr_id.\nby apply/bigmax_sup.\nQed.\n\nLemma big_card1 T (idx : T) (op : Monoid.law idx) (I : finType) i0 (F : I -> T) :\n  #|I| = 1%N -> \\big[op/idx]_i F i = F i0.\nProof.\nmove=>Pi. suff: (fun=>true) =1 pred1 i0. by apply big_pred1.\nby move=>i; rewrite/=; move/eqP/fintype1P: Pi=>[x Px]; rewrite !Px eqxx.\nQed.\nArguments big_card1 [T idx op I] i0 [F].\n\nLemma index_enum1 (I : finType) i0 :\n  #|I| = 1%N -> index_enum I = [:: i0].\nProof.\nmove=>Pi. move: Pi {+}Pi=>/mem_card1[x Px] /eqP/fintype1P[y Py].\nby rewrite/index_enum/= -fintype.enumT (fintype.eq_enum Px) fintype.enum1 !Py.\nQed.\n\nLemma max_card1 T (idx : T) (op : T -> T -> T) (I : finType) i0 (F : I -> T) :\n  #|I| = 1%N -> \\big[op/idx]_i F i = op (F i0) idx.\nProof. by move=>P1; rewrite unlock/= (index_enum1 i0). Qed.\n\nLemma mx_norm1 (T : numDomainType) (M : 'M[T]_1) :\n  `|M| = `|M ord0 ord0|.\nProof.\nrewrite {1}/normr/= mx_normE.\nset i0 := (ord0,ord0) : 'I_1 * 'I_1.\nhave ->: \\big[maxr/0%:nng]_i `|M i.1 i.2|%:nng = \n  maxr `|M i0.1 i0.2|%:nng 0%:nng.\n  by apply: max_card1; rewrite card_prod card_ord mul1n.\nby rewrite max_l -?num_le//=.\nQed.\n\nLemma rV1_bound_subcvg (f : nat -> 'rV[C]_1) (M : C) :\n  (forall n, `|(f n)| <= M) -> exists (h: nat -> nat), \n    (forall n, (h n.+1 > h n)%N) /\\ cvg (f \\o h).\nProof.\nmove=>P. pose u i := f i 0 0.\nhave: forall n, `|u n| <= M by move=>n; move: (P n); rewrite mx_norm1.\nmove=>/C_bound_subcvg[h [Ph1 /cvg_ex/=[x /cvg_seqP Px]]].\nexists h; split=>//. set xm := (\\matrix_(i,j) x : 'M[C]_1).\napply/cvg_ex; exists xm; suff: f \\o h --> xm by [].\napply/cmxcvg_seqP =>e egt0; move: (Px _ egt0)=>[N PN].\nby exists N=>i /PN; rewrite mx_normEV mx_norm1 !mxE.\nQed.\n\nLemma castmx_norm (T : numDomainType) m n m' n' (eqmn : (m = m') * (n = n')) \n  (M : 'M[T]_(m,n)) : mx_norm (castmx eqmn M) = mx_norm M.\nProof. by case: eqmn=>eqm eqn; case: m'/eqm; case: n'/eqn; rewrite castmx_id. Qed.\n\nLemma rV_bound_subcvg  (m : nat) (f : nat -> 'rV[C]_m.+1) (M : C) :\n  (forall n, `|(f n)| <= M) -> exists (h: nat -> nat), \n    (forall n, (h n.+1 > h n)%N) /\\ cvg (f \\o h).\nelim: m f =>[f|m IH f bf]. exact: rV1_bound_subcvg.\npose fl n := lsubmx (castmx (erefl, esym (addn1 m.+1)) (f n)).\npose fr n := rsubmx (castmx (erefl, esym (addn1 m.+1)) (f n)).\nhave cf n : f n = castmx (erefl, (addn1 m.+1)) (row_mx (fl n) (fr n))\n by rewrite /fl/fr hsubmxK castmx_comp castmx_id.\nsuff bfl n : `|fl n| <= M. suff bfr n : `|fr n| <= M.\n2,3: move: (bf n); rewrite /normr/= cf castmx_norm row_mx_norm.\n2,3: by rewrite num_le_maxl=>/andP[].\nmove: (IH _ bfl)=>[hl [hl1 /cmxcvg_seqP hl2]].\nhave bfr' n : `|(fr \\o hl) n| <= M by rewrite/=.\nmove: (rV1_bound_subcvg bfr')=>[hr [hr1 /cmxcvg_seqP hr2]].\nexists (hl \\o hr); split; first by move=>n/=; apply nchain_mono.\npose lm := (castmx (erefl, (addn1 m.+1)) \n(row_mx (lim (fl \\o hl)) (lim ((fr \\o hl) \\o hr)))).\napply/cvg_ex; exists lm; suff: (f \\o (hl \\o hr)) --> lm by [].\napply/cmxcvg_seqP=>e egt0. move: (hl2 _ egt0) (hr2 _ egt0)=>[N1 P1] [N2 P2].\nset N := maxn N1 N2. exists N=>i Pi.\nrewrite/= /lm cf -linearB /normr/= castmx_norm opp_row_mx add_row_mx \n  row_mx_norm num_lt_maxl -!mx_normE; apply/andP; split.\nby apply/P1/(leq_trans _ (nchain_ge hr1 i))/(leq_trans _ Pi)/leq_maxl.\napply/P2/(leq_trans _ Pi)/leq_maxr.\nQed.\n\nLemma cmx_Bolzano_Weierstrass  (m n : nat) (f : nat -> 'M[C]_(m,n)) (M : C) :\n  (forall n, mx_norm (f n) <= M) -> exists (h: nat -> nat), \n    (forall n, (h n.+1 > h n)%N) /\\ cvg (f \\o h).\nProof.\ncase: m f. move=>f _; exists id; split=>//; exact: is_cmxcvg_dim0n.\ncase: n. move=>n f _; exists id; split=>//; exact: is_cmxcvg_dimn0.\nmove=>n m f P1.\nhave P2 i : `|(mxvec \\o f) i| <= M.\nby rewrite/= -mxvec_norm /normr/=.\nmove: (rV_bound_subcvg P2)=>[h [P3 P4]].\nexists h; split=>//. have ->: f \\o h = vec_mx \\o ((mxvec \\o f) \\o h).\nby apply/funext=>i; rewrite/= mxvecK.\napply/is_cmxcvg_mapV. exact: vec_mx_continuous. exact: P4.\nQed.\n\n(* bounded seq: cvg <-> any cvg subseq to a *)\nLemma ccvg_subseqP_cvg (m n : nat) (f : nat -> 'M[C]_(m,n)) (a : 'M[C]_(m,n)) (M : C): \n  (forall n, mx_norm (f n) <= M) ->\n  f --> a <-> (forall (h: nat -> nat), (forall n, (h n.+1 > h n)%N) \n    -> cvg (f \\o h) -> lim (f \\o h) = a).\nsplit.\nmove=>/cmxcvg_subseqP + h Ph _. move=>/(_ h Ph).\napply: cvg_lim. apply Cmxhausdorff.\nmove=>P. apply contrapT. rewrite cmxcvg_subseqPN.\nrewrite -forallNP=> e. rewrite -forallNP=> h.\nrewrite -!implyNE=>Ph Pe Pc.\nhave P1: forall n0 : nat, mx_norm ((f \\o h) n0) <= M by move=>n0; apply H.\nmove: (cmx_Bolzano_Weierstrass P1)=>[h' [Ph']]. rewrite -compA=>Pc'.\nhave P2: ~ ((f \\o (h \\o h')) --> a).\nrewrite cmxcvg_subseqPN; exists e; exists id; do 2 split=>//.\nmove=>n'; apply Pc.\napply P2. rewrite cmxcvg_limE; split=>[|//].\napply P=>[|//]. move=>n'/=. by apply nchain_mono.\nQed.\n\nEnd Bolzano_Weierstrass.\n\n(* TODO :                                                                   *)\n(* 1. pack the vporder (vector preorder)                                    *)\n(* 2. pack closed vporder, i.e., closed [set x : M | 0 ⊑ x ]                *)\n(* Q: maybe is better to do everything in vect k? since 'M[C] is canonical  *)\n(*   to vect C; but need to deal with trivial vector space (0-dim)          *)\n(* it's better to redefine nosimpl of cvg and lim after packing things, in  *)\n(* order to prevent searching the canonical structure which is much slower  *)\n(* *** This section works for any matrix, even it is trivial                *)\n\n(* TODO : norm is never used; please clean the code *)\nModule CmxNormCvg.\n\nSection Definitions.\nVariables (R: realType) (m n : nat) (B : POrder.class_of 'M[R[i]]_(m,n)) (disp: unit).\n\nLocal Notation M := 'M[R[i]]_(m,n).\nLocal Notation \"x '⊏' y\" := (@Order.lt disp (@POrder.Pack disp M B) x y) \n  (at level 70, y at next level).\nLocal Notation \"x '⊑' y\" := (@Order.le disp (@POrder.Pack disp M B) x y) \n  (at level 70, y at next level).\n\nStructure cmxnormcvg := Cmxnormcvg {\n  mnorm : vnorm [lmodType R[i] of M];\n  _ : forall (z x y : M), x ⊑ y -> x + z ⊑ y + z;\n  _ : forall (e : R[i]) (x y : M), 0 < e -> x ⊑ y -> e *: x ⊑ e *: y;\n  _ : closed [set x : M | (0 : M) ⊑ x];\n  (* _ : forall (x y : M), (0 : M) ⊑ x -> (0 : M) ⊑ y \n        -> mnorm x + mnorm y = mnorm (x + y); *)\n}.\nLocal Coercion mnorm : cmxnormcvg >-> vnorm.\n\nLet op_id (op1 op2 : vnorm [lmodType R[i] of M]) := phant_id op1 op2.\n\nDefinition clone_vnormcvg op :=\n  fun (opL : cmxnormcvg) & op_id opL op =>\n  fun opd opz opc optr (opL' := @Cmxnormcvg op opd opz opc optr)\n    & phant_id opL' opL => opL'.\n\nEnd Definitions.\n\nModule Import Exports.\nCoercion mnorm : cmxnormcvg >-> vnorm.\nNotation \"[ 'cmxnormcvg' 'of' f ]\" := (@clone_vnormcvg _ _ _ _ _ f _ id _ _ _ _ id)\n  (at level 0, format\"[ 'cmxnormcvg'  'of'  f ]\") : form_scope.\nEnd Exports.\n\nModule Theory.\n\nSection Property.\nImport realTypeMxCvg Num.Theory.\nLocal Open Scope complex_scope.\nVariable (R: realType) (m n : nat).\nLocal Notation C := R[i].\nLocal Notation M := 'M[C]_(m,n).\nVariable (B : POrder.class_of M) (disp: unit).\nVariable (mxnorm : cmxnormcvg B disp).\n\nLocal Notation \"x '⊏' y\" := (@Order.lt disp (@POrder.Pack disp M B) x y) (at level 70, y at next level).\nLocal Notation \"x '⊑' y\" := (@Order.le disp (@POrder.Pack disp M B) x y) (at level 70, y at next level).\nNotation \"'ubounded_by' b f\" := (forall i, f i ⊑ b) (at level 10, b, f at next level).\nNotation \"'lbounded_by' b f\" := (forall i, b ⊑ f i) (at level 10, b, f at next level).\nNotation \"'cmxnondecreasing_seq' f\" := ({homo f : n m / (n <= m)%nat >-> (n ⊑ m)})\n  (at level 10).\nNotation \"'cmxnonincreasing_seq' f\" := ({homo f : n m / (n <= m)%nat >-> (m ⊑ n)})\n  (at level 10).\n\nLemma lecmx_add2r (z x y : M) : x ⊑ y -> x + z ⊑ y + z.\nProof. by move: z x y; case: mxnorm. Qed.\nLemma lecmx_pscale2lP (e : R[i]) (x y : M) : 0 < e -> x ⊑ y -> e *: x ⊑ e *: y.\nProof. by move: e x y; case: mxnorm. Qed.\nLemma lecmx_pscale2l: forall (e : R[i]) (x y : M), 0 < e -> x ⊑ y = (e *: x ⊑ e *: y).\nProof. \nmove=> e x y egt0. apply/Bool.eq_true_iff_eq.\nsplit. by apply lecmx_pscale2lP. rewrite -{2}(scale1r x) -{2}(scale1r y) -(@mulVf _ e).\nrewrite -!scalerA. apply lecmx_pscale2lP. rewrite invr_gt0//. by apply/lt0r_neq0.\nQed.\nLemma closed_gecmx0: closed [set x : M | (0 : M) ⊑ x].\nProof. by case: mxnorm. Qed.\n\nImplicit Type (u v : M^nat).\n\nLemma subcmx_ge0 (x y : M) : ((0 : M) ⊑ x - y) = (y ⊑ x).\nProof. \napply/Bool.eq_iff_eq_true; split=>[/(@lecmx_add2r y)|/(@lecmx_add2r (-y))];\nby rewrite ?addrNK ?add0r// addrN.\nQed.\n\nLemma lecmx_opp2 : {mono (-%R : M -> M) : x y /~ x ⊑ y }.\nProof. by move=>x y; rewrite -subcmx_ge0 opprK addrC subcmx_ge0. Qed.\n\nLemma cmxnondecreasing_opp u :\n  cmxnondecreasing_seq (- u) = cmxnonincreasing_seq u.\nProof. by rewrite propeqE; split => du x y /du; rewrite lecmx_opp2. Qed.\n\nLemma cmxnonincreasing_opp u :\n  cmxnonincreasing_seq (- u) = cmxnondecreasing_seq u.\nProof. by rewrite propeqE; split => du x y /du; rewrite lecmx_opp2. Qed.\n\nLemma cmxlbounded_by_opp (b : M) u :\n  lbounded_by (-b) (- u) = ubounded_by b u.\nProof. \nby rewrite propeqE; split => bu i; move: (bu i); \n  rewrite {2}/GRing.opp/= lecmx_opp2.\nQed.\n\nLemma cmxubounded_by_opp (b : M) u :\n  ubounded_by (-b) (- u) = lbounded_by b u.\nProof. \nby rewrite propeqE; split => bu i; move: (bu i); \n  rewrite {2}/GRing.opp/= lecmx_opp2.\nQed.\n\n(* following proof is quite difficult, prove it in future *)\n(* unit sphere : compact ; [x | 0 ⊑ x] : closed *)\n(* subclosed_compact: A := unit sphere `&` [x | 0 ⊑ x] -> compact A *)\n(* A = empty : trivial case, 0 ⊑ x iff x = 0 ; only consider nontrivial case *)\n(* convex hull B generated by A is compact https://en.wikipedia.org/wiki/Convex_hull *)\n(* forall X : A, X ⊑ Y -> Y \\in B or |Y| >= 1 *)\n(* compact B -> compact C := mx_norm @` B *)\n(* c := min C ; c > 0 & c <= 1 *)\n(* 0 <= c <= 1 : since all x : C, 0 <= x <= 1 *)\n(* c > 0 : if c = 0, then 0 \\in B, 0 = \\sum_i a_i *: x_i where \n  \\sum_i a_i = 1 and a_i >= 0 & x_i \\in A *)\n(* at least one a_k > 0, 0 = a_k *: x_k + \\sum_(i != k) a_i *: x_i *)\n(* 0 ⊑ a_k *: x_k ⊑ a_k *: x_k + \\sum_(i != k) a_i *: x_i = 0 *)\n(* then a_k *: x_k = 0, contradiction since a_k > 0 and x_k != 0 *)\n(* forall 0 ⊑ X ⊑ Y, c * mx_norm X <= mx_norm Y *)\n\n\n(* different canonical route. prevent eq_op porderType ringType *)\nLemma ltcmx_def (x y : M) : (x ⊏ y) = (y != x) && (x ⊑ y).\nProof.\nrewrite lt_def; congr (~~ _ && _); apply/Bool.eq_iff_eq_true.\nsplit=>/eqP/=->; by rewrite eqxx.\nQed.\n\nLemma subcmx_gt0 (x y : M) : ((0 : M) ⊏ y - x) = (x ⊏ y).\nProof. by rewrite !ltcmx_def subcmx_ge0 subr_eq0. Qed.\n\nLemma cmxopen_nge0 : open [set x : M | ~ (0 : M) ⊑ x].\nProof. rewrite openC; apply closed_gecmx0. Qed.\n\nLemma cmxopen_nge y :  open [set x : M | ~ y ⊑ x].\nProof.\nmove: (@cmxaddr_continuous R m n (-y))=>/continuousP/=/(_ _ cmxopen_nge0).\nsuff ->: [set x : M | ~ y ⊑ x] = [set t | [set x | ~ (0 : M) ⊑ x] (- y + t)] by [].\nby apply/funext=>x; rewrite /= addrC subcmx_ge0.\nQed.\n\nLemma cmxopen_nle0 : open [set x : M | ~ x ⊑ (0 : M)].\nProof.\nmove: (@cmxopp_continuous R m n)=>/continuousP/=/(_ _ cmxopen_nge0).\nsuff ->: [set x | ~ x ⊑ (0 : M)] = [set t | [set x | ~ (0 : M) ⊑ x] (- t)] by [].\nby apply/funext=>x; rewrite /= -{2}oppr0 lecmx_opp2. \nQed.\n\nLemma cmxopen_nle y :  open [set x : M | ~ x ⊑ y].\nProof.\nmove: (@cmxopp_continuous R m n)=>/continuousP/=/(_ _ (@cmxopen_nge (-y))).\nsuff ->: [set x : M | ~ x ⊑ y] = [set t | [set x : M | ~ - y ⊑ x] (- t)] by [].\nby apply/funext=>x; rewrite /= lecmx_opp2.\nQed.\n\nLemma cmxclosed_ge (x : M) : closed [set y : M | x ⊑ y ].\nProof. \nset A := ~` [set y : M | ~ (x ⊑ y)].\nhave ->: (fun x0 : 'M_(m, n) => is_true (x ⊑ x0)) = A.\nby rewrite predeqE /A => y/=; rewrite notK.\nrewrite closedC. apply/cmxopen_nge. \nQed.\n\nLemma cmxclosed_le (x : M) : closed [set y : M | y ⊑ x ].\nProof. \nset A := ~` [set y : M | ~ (y ⊑ x)].\nhave ->: (fun x0 : 'M_(m, n) => is_true (x0 ⊑ x)) = A.\nby rewrite predeqE /A => y/=; rewrite notK.\nrewrite closedC. apply/cmxopen_nle. \nQed.\n\nLemma cmxlim_ge_near (x : M) (u : M ^nat) : \n  cvg u -> (\\forall n \\near \\oo, x ⊑ u n) -> x ⊑ lim u.\nProof.\nmove=> /[swap] /(closed_cvg ((@Order.le disp (@POrder.Pack disp M B) x)))/= P1;\napply P1. apply: cmxclosed_ge.\nQed.\n\nLemma cmxlim_le_near (x : M) (u : M ^nat) : \n  cvg u -> (\\forall n \\near \\oo, u n ⊑ x) -> lim u ⊑ x.\nProof.\nmove=> /[swap] /(closed_cvg (fun y =>(@Order.le disp (@POrder.Pack disp M B) y x)))/= P1;\napply P1. apply: cmxclosed_le.\nQed.\n\nLemma cmxler_lim_near (u_ v_ : M ^nat) : cvg u_ -> cvg v_ ->\n  (\\forall n \\near \\oo, u_ n ⊑ v_ n) -> lim u_ ⊑ lim v_.\nProof.\nmove=> uv cu cv; rewrite -(subcmx_ge0) -cmxlimB.\napply: cmxlim_ge_near. apply: is_cmxcvgB.\n3: by apply: filterS cv => k; rewrite (subcmx_ge0).\n1,3: by []. all: apply uv.\nQed.\n\nLemma cmxlim_ge (x : M) (u : M ^nat) : cvg u -> lbounded_by x u -> x ⊑ lim u.\nProof.\nby move=>P1 P2; apply: (cmxlim_ge_near P1); apply: nearW.\nQed.\n\nLemma cmxlim_le (x : M) (u : M ^nat) : cvg u -> ubounded_by x u -> lim u ⊑ x.\nProof.\nby move=>P1 P2; apply: (cmxlim_le_near P1); apply: nearW.\nQed.\n\nLemma ler_cmxlim (u v : M^nat) : cvg u -> cvg v ->\n  (forall n, u n ⊑ v n) -> lim u ⊑ lim v.\nProof.\nby move=>P1 P2 P3; apply: (cmxler_lim_near P1 P2); apply: nearW.\nQed.\n\nLemma cmxnondecreasing_cvg_le (u : M ^nat) :\n       cmxnondecreasing_seq u -> cvg u -> ubounded_by (lim u) u.\nProof.\nmove=>Ph Pc i; apply: cmxlim_ge_near=>//; exists i=>// j; apply Ph.\nQed.\n\nLemma cmxnonincreasing_cvg_ge (u : M ^nat) : \n  cmxnonincreasing_seq u -> cvg u -> lbounded_by (lim u) u.\nProof.\nmove=>Ph Pc i; apply: cmxlim_le_near=>//; exists i=>// j; apply Ph.\nQed.\n\nLemma nchain_mono1 (h: nat -> nat) :\n  (forall n, (h n.+1 > h n)%N) -> forall n m, (n <= m)%N -> (h n <= h m)%N.\nProof.\nmove=>P1 n' m'; rewrite leq_eqVlt=>/orP[/eqP->//|P2].\nby apply/ltnW/nchain_mono.\nQed.\n\nLemma ha (X Y : M) a : ((0 : M) ⊑ X) && (X ⊑ Y) -> 0 < a < 1 ->\n  ((0 : M) ⊑ a*:X) && (a*:X ⊑ Y).\nProof.\nmove=>/andP[P1 P2]/andP[P3]; rewrite -subr_gt0=>P4; apply/andP; split.\nby move: (lecmx_pscale2lP P3 P1); rewrite scaler0.\napply: (le_trans (lecmx_pscale2lP P3 P2)).\nmove: (le_trans P1 P2)=>/(lecmx_pscale2lP P4).\nby rewrite scaler0 scalerBl scale1r=>/(lecmx_add2r (a*:Y)); rewrite addrNK add0r.\nQed.\n\nLemma hb (e : C) : 0 < e -> exists k, k.+1%:R^-1 < e.\nProof.\nmove=>egt0. have ->: e = (complex.Re e)%:C.\nby case: e egt0=>/= x y; rewrite ltcE/==>/andP[]/eqP->.\nhave regt0 : 0 < (complex.Re e) by case: e egt0=>x y; rewrite ltcE/==>/andP[].\nmove/ltr_add_invr: regt0=>[k Pk]; exists k.\nby rewrite -natrC -realcI ltcR; move: Pk; rewrite add0r.\nQed.\n\nLemma ler1Sn (T : numDomainType) i : 1 <= i.+1%:R :> T.\nProof. by rewrite -addn1 natrD ler_addr. Qed.\n\nLemma porder_mx_norm_bound (Y : M) : exists c, c > 0 /\\ \n  (forall X, ((0 : M) ⊑ X) && (X ⊑ Y) -> c * mx_norm X <= mx_norm Y).\nProof.\ncase E: (Y == 0); first by move/eqP: E=>->; exists 1; split=>// x; \n  rewrite -eq_le=>/eqP<-; rewrite normv0 mulr0.\nhave Q1: mx_norm Y > 0 by rewrite normv_gt0 E.\npose c i := i.+1%:R * (1 + mx_norm Y).\nhave cinc i : c i >= 1 + mx_norm Y by rewrite/c ler_pmull ?addr_gt0// ler1Sn.\nhave Q2 i : c i > i.+1%:R by rewrite/c ltr_pmulr// ltr_addl.\nhave Q3 i : c i > 0 by rewrite /c mulr_gt0// addr_gt0.\nhave Q4 i : 0 < mx_norm Y / c i by rewrite divr_gt0.\nrewrite not_existsP=>P1.\nhave P2 i: {X : M | ((0 : M) ⊑ X) && (X ⊑ Y) /\\ (mx_norm X > c i)}.\napply/cid; move: (P1 (mx_norm Y/c i)); rewrite -implyNE=>/(_ (Q4 i)).\nrewrite not_existsP; apply contra_not=>P2 x P3; move: (P2 x).\nrewrite -implyNE=>/(_ P3)/negP; rewrite -mulrA ger_pmulr// ler_pdivr_mull// mulr1.\nby rewrite real_leNgt// ger0_real// ?normv_ge0//; apply/ltW.\npose x i := projT1 (P2 i).\nhave P7 i : ((0 : M) ⊑ x i) && (x i ⊑ Y) by move: (projT2 (P2 i))=>[].\nhave P4 i : c i < mx_norm (x i) by move: (projT2 (P2 i))=>[].\nhave P5 i : 0 < mx_norm (x i) by apply: (lt_trans _ (P4 _)).\npose nx i := (mx_norm (x i))^-1 *: (x i).\nhave norm_nx i : mx_norm (nx i) = 1.\nby rewrite /nx normvZ/= gtr0_norm ?mulVf// ?invr_gt0//; apply: lt0r_neq0.\nhave bound_nx i : mx_norm (nx i) <= 1 by rewrite norm_nx.\nmove: (cmx_Bolzano_Weierstrass bound_nx)=>[h [mn]].\nmove: (nchain_ge mn)=>hgen.\nset y := nx \\o h=>Cy; pose ly := lim y : M.\nhave cy : y --> ly by [].\nhave P3 i : ((0 : M) ⊑ y i) && (y i ⊑ Y).\nrewrite /y/=/nx; apply/ha=>//.\nrewrite invr_gt0 invf_lt1// P5/=; apply: (lt_trans _ (P4 _)).\napply: (le_lt_trans _ (Q2 _)); by rewrite -addn1 natrD ler_addr.\nhave ly_ge0: ((0 : M) ⊑ ly) by apply: cmxlim_ge=>[//|i]; move: (P3 i)=>/andP[].\nhave Q5 i: mx_norm (Y - x i) > i.+1%:R.\nrewrite addrC; move: (lev_sub_norm_add mx_norm_vnorm (- x i) Y)=>/=.\napply: lt_le_trans; rewrite mx_normN ltr_subr_addl.\napply: (le_lt_trans _ (P4 _)); rewrite addrC/c mulrDr.\nby rewrite mulr1 ler_add2l ler_pmull// ler1Sn.\nhave Q6 i: mx_norm (Y - x i) > 0 by apply: (lt_trans _ (Q5 _)).\npose nnx i := (mx_norm (Y - x (h i)))^-1 *: (Y - x (h i)).\npose nnx1 i := (mx_norm (Y - x (h i)))^-1 *: Y.\npose nnx2 i := (mx_norm (Y - x (h i)))^-1 * mx_norm (x (h i)).\nhave: nnx --> 0 - 1 *: ly.\nhave ->: nnx = nnx1 - (fun i=>nnx2 i *: y i).\napply/funext=>i; rewrite/nnx/nnx1 {3}/GRing.add/={4}/GRing.opp/=/nnx2/nx.\nby rewrite scalerA -mulrA mulfV ?mulr1 ?scalerBr// lt0r_neq0.\nhave Q7 e: 0 < e -> exists N : nat, forall i : nat, (N <= i)%N -> \n  mx_norm Y / (mx_norm (Y - x (h i))) < e.\n  move=>egt0; have /hb: e / mx_norm Y > 0 by rewrite divr_gt0.\n  move=>[k Pk]; exists k=>i Pi; rewrite/=mulrC -ltr_pdivl_mulr//; apply: (le_lt_trans _ Pk).\n  rewrite lef_pinv ?posrE//; apply/ltW; apply: (le_lt_trans _ (Q5 _)).\n  by rewrite ler_nat ltnS; apply: (leq_trans Pi).\napply cmxcvgB. 2: apply cmxcvgZ=>[|//].\napply/cmxcvg_seqP=>e egt0; move: (Q7 e egt0)=>[k Pk]; exists k=>i/Pk.\nby rewrite add0r mx_normN/nnx1 normvZ/= gtr0_norm ?invr_gt0// mulrC.\napply ccvg_seqP=>e egt0; move: (Q7 e egt0)=>[k Pk]; exists k=>i/Pk.\nrewrite ltr_pdivr_mulr// =>P6.\nrewrite/nnx2 -(@mulfV _ (mx_norm (Y - x (h i))) _); last by apply/lt0r_neq0.\nrewrite mulrC -mulrBr normrM gtr0_norm ?ltr_pdivr_mull// ?invr_gt0// mulrC.\napply: (le_lt_trans _ P6); rewrite -[mx_norm (x (h i))]normvN/= \n  -{2}[Y](addrNK (x (h i))) -{4}(opprK (x (h i))); apply: lev_dist_dist.\nrewrite scale1r add0r=>cny. have Cny: cvg nnx by apply/cvg_ex; exists (-ly). \nhave nly_ge0: ((0 : M) ⊑ - ly). rewrite -(cvg_lim _ cny); last by apply Cmxhausdorff.\napply: cmxlim_ge=>[//|i].\nsuff: ((0 : M) ⊑ nnx i) && (nnx i ⊑ Y) by move=>/andP[].\nrewrite /nnx; apply/ha; apply/andP; split.\nrewrite subcmx_ge0. 2: rewrite -subcmx_ge0 opprB addrC addrNK.\n1,2: by move: (P7 (h i))=>/andP[].\nrewrite invr_gt0//. rewrite invf_lt1//; apply/(le_lt_trans _ (Q5 _))/ler1Sn.\nhave : mx_norm ly = 1.\nrewrite -(cmxlim_normv (mx_norm_vnorm) Cy)=>/=.\nsuff ->: mx_norm (n:=n) \\o y = fun=>1 by apply/lim_cst/Chausdorff.\nby apply/funext=>i; rewrite/=/y//=.\nhave: ((0 : M) ⊑ ly) && (ly ⊑ 0) by rewrite ly_ge0/= -subcmx_ge0 add0r.\nby rewrite -eq_le eq_sym=>/eqP->/eqP; rewrite normv0 eq_sym oner_eq0.\nQed.\n\nLemma lubounded_cmxnorm (bl br : M) u :\n  lbounded_by bl u -> ubounded_by br u -> \n  exists c : C, forall n, mx_norm (u n) <= c.\nProof.\nmove: (porder_mx_norm_bound (br-bl))=>[c [Pc P]] Pl Pr.\nexists (mx_norm (br - bl) / c + mx_norm bl)=>i.\nrewrite -[u i](addrNK bl). apply: (le_trans (ler_mx_norm_add _ _)).\nrewrite ler_add2r ler_pdivl_mulr// mulrC P//; apply/andP; split.\nby rewrite subcmx_ge0. by apply lecmx_add2r.\nQed.\n\nLemma cmxnondecreasing_is_cvg (f : nat -> M) (b : M) :\n  cmxnondecreasing_seq f -> ubounded_by b f -> cvg f.\nmove=>P1 P2.\nhave P3: lbounded_by (f 0%N) f by move=>i; by apply/P1.\nmove: (lubounded_cmxnorm P3 P2)=>[c Pc].\nmove: (cmx_Bolzano_Weierstrass Pc)=>[h0 [Ph0 cvgh0]].\napply/cvg_ex. exists (lim (f \\o h0)).\napply/(ccvg_subseqP_cvg (lim (f \\o h0)) Pc)=>h1 Ph1 cvgh1.\nsuff: (lim (f \\o h1) ⊑ lim (f \\o h0)) && (lim (f \\o h0) ⊑ lim (f \\o h1)).\nby rewrite -eq_le=>/eqP.\napply/andP; split; apply: (cmxlim_le)=>[|i].\n2: have P4: (f \\o h1) i ⊑ (f \\o h0) (h1 i) by apply/P1/nchain_ge.\n4: have P4: (f \\o h0) i ⊑ (f \\o h1) (h0 i) by apply/P1/nchain_ge.\n2,4: apply: (le_trans P4 _); apply (cmxnondecreasing_cvg_le).\n1,5: apply cvgh1. 2,4: apply cvgh0.\nall: by move=>x y Pxy; apply P1; apply/nchain_mono1.\nQed.\n\nLemma cmxnonincreasing_is_cvg (f : nat -> M) (b : M) :\n    cmxnonincreasing_seq f -> lbounded_by b f -> cvg f.\nProof.\nrewrite -(cmxnondecreasing_opp) -(cmxubounded_by_opp) -is_cmxcvgNE.\nexact: cmxnondecreasing_is_cvg.\nQed.\n\nEnd Property.\n\nEnd Theory.\nInclude Theory.\n\nEnd CmxNormCvg.\nImport CmxNormCvg.Exports.\n\nImport CmxNormCvg.\n\n(* FinNormedModType *)\n(* VOrderFinNormedModType *)\nModule FinNormedModule.\n\nSection ClassDef.\n\nVariable R : realType.\n\nRecord class_of (T : Type) := Class {\n  base : NormedModule.class_of [numDomainType of R[i]] T ;\n  mixin : Vector.mixin_of (GRing.Lmodule.Pack _ base);\n}.\nLocal Coercion base : class_of >-> NormedModule.class_of.\nDefinition base2 T (cT : class_of T) := @Vector.Class _ _ (@base T cT) (@mixin T cT).\nLocal Coercion base2 : class_of >-> Vector.class_of.\n\nStructure type (phR : phant R[i]) := Pack { sort; _ : class_of sort }.\nLocal Coercion sort : type >-> Sortclass.\n\nVariables (phR : phant R[i]) (T : Type) (cT : type phR).\nDefinition class := let: Pack _ c  as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack phR T c.\nLet xT := let: Pack T _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack :=\n  fun bT (b : NormedModule.class_of _ T) & phant_id (@NormedModule.class _ (Phant R[i]) bT) b =>\n  fun mT m & phant_id (@Vector.class _ (Phant R[i]) mT) (@Vector.Class _ T b m) =>\n    @Pack phR T (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT xclass.\nDefinition choiceType := @Choice.Pack cT xclass.\nDefinition zmodType := @GRing.Zmodule.Pack cT xclass.\nDefinition normedZmodType := @Num.NormedZmodule.Pack _ phR cT xclass.\nDefinition lmodType := @GRing.Lmodule.Pack _ phR cT xclass.\nDefinition pointedType := @Pointed.Pack cT xclass.\nDefinition filteredType := @Filtered.Pack cT cT xclass.\nDefinition topologicalType := @Topological.Pack cT xclass.\nDefinition uniformType := @Uniform.Pack cT xclass.\nDefinition pseudoMetricType := @PseudoMetric.Pack _ cT xclass.\nDefinition pseudoMetricNormedZmodType :=\n  @PseudoMetricNormedZmodule.Pack _ phR cT xclass.\nDefinition normedModType := @NormedModule.Pack _ phR cT xclass.\nDefinition vectType := @Vector.Pack _ phR cT xclass.\nDefinition normedMod_zmodType := @GRing.Zmodule.Pack normedModType xclass.\nDefinition normedMod_lmodType := @GRing.Lmodule.Pack _ phR normedModType xclass.\nDefinition normedMod_vectType := @Vector.Pack _ phR normedModType xclass.\n\nEnd ClassDef.\n\nModule Import Exports.\nCoercion base : class_of >-> NormedModule.class_of.\nCoercion base2 : class_of >-> Vector.class_of.\nCoercion sort : type >-> Sortclass.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> GRing.Zmodule.type.\nCanonical zmodType.\nCoercion pseudoMetricNormedZmodType : type >-> PseudoMetricNormedZmodule.type.\nCanonical pseudoMetricNormedZmodType.\nCoercion normedZmodType : type >-> Num.NormedZmodule.type.\nCanonical normedZmodType.\nCoercion lmodType : type >-> GRing.Lmodule.type.\nCanonical lmodType.\nCoercion pointedType : type >-> Pointed.type.\nCanonical pointedType.\nCoercion filteredType : type >-> Filtered.type.\nCanonical filteredType.\nCoercion topologicalType : type >-> Topological.type.\nCanonical topologicalType.\nCoercion uniformType : type >-> Uniform.type.\nCanonical uniformType.\nCoercion pseudoMetricType : type >-> PseudoMetric.type.\nCanonical pseudoMetricType.\nCoercion normedModType : type >-> NormedModule.type.\nCanonical normedModType.\nCoercion vectType : type >-> Vector.type.\nCanonical vectType.\nCanonical normedMod_zmodType.\nCanonical normedMod_lmodType.\nCanonical normedMod_vectType.\nNotation finNormedModType R := (type (Phant R)).\nNotation FinNormedModType R T := (@pack _ (Phant R) T _ _ id _ _ id).\nNotation \"[ 'finNormedModType' R 'of' T 'for' cT ]\" :=  (@clone _ (Phant R) T cT _ idfun)\n  (at level 0, format \"[ 'finNormedModType'  R  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'finNormedModType' R 'of' T ]\" :=  (@clone _ (Phant R) T _ _ id)\n  (at level 0, format \"[ 'finNormedModType'  R  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd FinNormedModule.\n\nImport FinNormedModule.Exports.\n\nCanonical C_regular_finNormedModType (R : realType) := \n  Eval hnf in (FinNormedModType R[i] R[i]^o).\nCanonical C_finNormedModType (R : realType) :=\n  Eval hnf in [finNormedModType R[i] of R[i] for [finNormedModType R[i] of R[i]^o]].\n\nModule VOrderFinNormedModule.\n\nSection ClassDef.\n\nRecord mixin_of (R : realType) (V : finNormedModType R[i])\n  (Rorder : POrder.mixin_of (Equality.class V))\n  (le_op := POrder.le Rorder)\n  := Mixin {\n  _ : closed [set x : V | (le_op 0 x)] ;\n}.\n\nVariable R : realType.\n\nRecord class_of (T : Type) := Class {\n  base : FinNormedModule.class_of R T;\n  order_mixin : POrder.mixin_of (Equality.class (FinNormedModule.Pack _ base));\n  vorder_mixin : VOrder.mixin_of order_mixin;\n  mixin : mixin_of order_mixin;\n}.\nLocal Coercion base : class_of >-> FinNormedModule.class_of.\nDefinition vorder_base T (cT : class_of T) :=\n  @VOrder.Class _ _ (@base T cT) (order_mixin cT) (vorder_mixin cT).\nLocal Coercion vorder_base : class_of >-> VOrder.class_of.\n\nStructure type (phR : phant R[i]) := Pack { sort; _ : class_of sort }.\nLocal Coercion sort : type >-> Sortclass.\n\nVariables (phR : phant R[i]) (T : Type) (cT : type phR).\nDefinition class := let: Pack _ c  as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack phR T c.\nLet xT := let: Pack T _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack (b0 : FinNormedModule.class_of R T)\n           (om0 : POrder.mixin_of (Equality.class (FinNormedModule.Pack (Phant R[i]) b0)))\n           (m0 : @mixin_of R (@FinNormedModule.Pack R (Phant R[i]) T b0) om0) :=\n  fun bT (b : FinNormedModule.class_of R T)\n      & phant_id (@FinNormedModule.class R (Phant R[i]) bT) b =>\n  fun om & phant_id om0 om =>\n  fun vmT vm & phant_id (@VOrder.class _ (Phant R[i]) vmT) (@VOrder.Class _ T b om vm) =>\n  fun m & phant_id m0 m =>\n  @Pack phR T (@Class T b om vm m).\n\nDefinition eqType := @Equality.Pack cT xclass.\nDefinition choiceType := @Choice.Pack cT xclass.\nDefinition zmodType := @GRing.Zmodule.Pack cT xclass.\nDefinition normedZmodType := @Num.NormedZmodule.Pack _ phR cT xclass.\nDefinition lmodType := @GRing.Lmodule.Pack _ phR cT xclass.\nDefinition pointedType := @Pointed.Pack cT xclass.\nDefinition filteredType := @Filtered.Pack cT cT xclass.\nDefinition topologicalType := @Topological.Pack cT xclass.\nDefinition uniformType := @Uniform.Pack cT xclass.\nDefinition pseudoMetricType := @PseudoMetric.Pack _ cT xclass.\nDefinition pseudoMetricNormedZmodType :=\n  @PseudoMetricNormedZmodule.Pack _ phR cT xclass.\nDefinition normedModType := @NormedModule.Pack _ phR cT xclass.\nDefinition finNormedModType := @FinNormedModule.Pack _ phR cT xclass.\nDefinition vectType := @Vector.Pack _ phR cT xclass.\nDefinition porderType := @POrder.Pack vorder_display cT xclass.\nDefinition vorderType := @VOrder.Pack _ phR cT xclass.\nDefinition finNormedMod_zmodType := @GRing.Zmodule.Pack finNormedModType xclass.\nDefinition finNormedMod_lmodType := @GRing.Lmodule.Pack _ phR finNormedModType xclass.\nDefinition finNormedMod_vectType := @Vector.Pack _ phR finNormedModType xclass.\nDefinition finNormedMod_porderType := @POrder.Pack vorder_display finNormedModType xclass.\nDefinition finNormedMod_vorderType := @VOrder.Pack _ phR finNormedModType xclass.\n\nEnd ClassDef.\n\nModule Import Exports.\nCoercion base : class_of >-> FinNormedModule.class_of.\nCoercion vorder_base : class_of >-> VOrder.class_of.\nCoercion sort : type >-> Sortclass.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> GRing.Zmodule.type.\nCanonical zmodType.\nCoercion pseudoMetricNormedZmodType : type >-> PseudoMetricNormedZmodule.type.\nCanonical pseudoMetricNormedZmodType.\nCoercion normedZmodType : type >-> Num.NormedZmodule.type.\nCanonical normedZmodType.\nCoercion lmodType : type >-> GRing.Lmodule.type.\nCanonical lmodType.\nCoercion pointedType : type >-> Pointed.type.\nCanonical pointedType.\nCoercion filteredType : type >-> Filtered.type.\nCanonical filteredType.\nCoercion topologicalType : type >-> Topological.type.\nCanonical topologicalType.\nCoercion uniformType : type >-> Uniform.type.\nCanonical uniformType.\nCoercion pseudoMetricType : type >-> PseudoMetric.type.\nCanonical pseudoMetricType.\nCoercion normedModType : type >-> NormedModule.type.\nCanonical normedModType.\nCoercion finNormedModType : type >-> FinNormedModule.type.\nCanonical finNormedModType.\nCoercion vectType : type >-> Vector.type.\nCanonical vectType.\nCoercion porderType : type >-> POrder.type.\nCanonical porderType.\nCoercion vorderType : type >-> VOrder.type.\nCanonical vorderType.\nCanonical finNormedMod_zmodType.\nCanonical finNormedMod_lmodType.\nCanonical finNormedMod_vectType.\nCanonical finNormedMod_porderType.\nCanonical finNormedMod_vorderType.\nNotation vorderFinNormedModType R := (type (Phant R)).\nNotation VOrderFinNormedModType R T m := \n  (@pack _ (Phant R) T _ _ m _ _ id _ id _ _ id _ id).\nNotation VOrderFinNormedModMixin := Mixin.\nNotation \"[ 'vorderFinNormedModType' R 'of' T 'for' cT ]\" := (@clone _ (Phant R) T cT _ idfun)\n  (at level 0, format \"[ 'vorderFinNormedModType'  R  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'vorderFinNormedModType' R 'of' T ]\" := (@clone _ (Phant R) T _ _ id)\n  (at level 0, format \"[ 'vorderFinNormedModType'  R  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd VOrderFinNormedModule.\n\nImport VOrderFinNormedModule.Exports.\n\nLemma continuous_comp_simp (R S T : topologicalType) (f : R -> S) (g : S -> T) :\n  continuous f -> continuous g -> continuous (g \\o f)%FUN.\nProof. \nmove=>cf cg; suff: forall x, {for x, continuous (g \\o f)%FUN} by [].\nmove=>x. apply continuous_comp. apply cf. apply cg.\nQed.\n\nSection FinNormedModTypeComplete.\nVariable (R : realType).\nLocal Notation C := R[i].\nImport Vector.InternalTheory Num.Def Num.Theory.\n\nLemma bounded_normr_cmxnorm (V : normedModType C) \n  m n (f: V -> 'M[C]_(m,n)) (lf: linear f) (bf: bijective f) :\n  (exists c, c > 0 /\\ forall x : V, `|x| <= c * mx_norm (f x))\n  /\\ (exists c, c > 0 /\\ forall x : V, mx_norm (f x) <= c * `|x|).\nmove: bf=>[g fK gK]; move: (can2_linearP lf fK gK)=>lg.\npose mn x := `|g x|.\nhave meq0 : forall x, mn x = 0 -> x = 0.\n  by move=>x/normr0_eq0; rewrite -{2}(gK x)/==>->; rewrite (linearlfE lf) linear0.\nhave mtrg : forall x y, mn (x + y) <= mn x + mn y.\n  by move=>x y; rewrite /mn (linearlfE lg) linearD ler_norm_add.\nhave mZ : forall (a: C) (x : 'M_(m,n)), mn (a *: x) = `|a| * mn x.\n  by move=>a x; rewrite /mn (linearlfE lg) linearZ normmZ.\npose mvn := Vnorm mtrg meq0 mZ.\nhave x2m : forall x, `|x| = mn (f x) by move=>x; rewrite /mn fK.\nsplit.\nmove: (cmxnormv_bounded mvn (@mx_norm_vnorm _ _ _))=>[c /= cgt0 Pml].\nexists c; split=>// x. by rewrite x2m.\nmove: (cmxnormv_bounded (@mx_norm_vnorm _ _ _) mvn)=>[c /= cgt0 Pml].\nexists c; split=>// x. by rewrite x2m.\nQed.\n\nLemma bounded_cmxnorm_normr (V : normedModType C) \n  (m n: nat) (g: 'M[C]_(m,n) -> V) (lg: linear g) (bg: bijective g) :\n  (exists c, c > 0 /\\ forall x : 'M[C]_(m,n), mx_norm x <= c * `|g x|)\n  /\\ (exists c, c > 0 /\\ forall x : 'M[C]_(m,n), `|g x| <= c * mx_norm x).\nProof.\nmove: bg=>[f gK fK]. move: (bounded_normr_cmxnorm (can2_linearP lg gK fK) \n  (can2_bij gK fK))=>[[c1 [c1gt0 Pc1]] [c2 [c2gt0 Pc2]]].\nsplit. exists c2. split=>// x. by rewrite -{1}(gK x).\nexists c1. split=>// x. by rewrite -{2}(gK x).\nQed.\n\nLemma bijective_to_cmx_continuous (V : normedModType C) \n  (m n: nat) (f: V -> 'M[C]_(m,n)) (lf: linear f) (bf: bijective f) :\n  continuous f.\nProof.\ncase: m f lf bf=>[f _ _|]; last case: n=>[m f _ _|].\n1,2: by rewrite mx_dim0=>x; apply: cst_continuous.\nmove=>m n f lf bf.\nrewrite (linearlfE lf) -linear_bounded_continuous -bounded_funP=>r/=.\nmove: (bounded_normr_cmxnorm lf bf)=>[_ [c2 [c2gt0 Pc2]]].\nexists (c2 * r)=>x. rewrite -(ler_pmul2l c2gt0) {2}/normr/=.\napply (le_trans (Pc2 _)).\nQed.\n\nLemma bijective_of_cmx_continuous (V : normedModType C) \n  (m n: nat) (g: 'M[C]_(m,n) -> V) (lg: linear g) (bg: bijective g) :\n  continuous g.\nProof.\ncase: m g lg bg=>[g _ _|]; last case: n=>[m g _ _|].\n1,2: have ->: g = (fun=>g 0) by apply/funext=>i; rewrite mx_dim0.\n1,2: apply: cst_continuous.\nmove=>m n g lg bg.\nrewrite (linearlfE lg) -linear_bounded_continuous -bounded_funP=>r/=.\nmove: (bounded_cmxnorm_normr lg bg)=>[_ [c2 [c2gt0 Pc2]]].\nexists (c2 * r)=>x. rewrite -(ler_pmul2l c2gt0) {1}/normr/=.\napply (le_trans (Pc2 _)).\nQed.\n\nLemma bijective_to_cmx_cvgE (V : normedModType C) \n  (m n: nat) (f: V -> 'M[C]_(m,n)) (u : nat -> V) (a : V)\n  (lf: linear f) (bf: bijective f) :\n  u --> a = ((f \\o u)%FUN --> f a).\nProof.\nrewrite propeqE; split; last move: {+}bf=>[g fK gK].\nby apply: continuous_cvg; apply/(bijective_to_cmx_continuous lf bf).\nhave P: u = (g \\o (f \\o u))%FUN by apply/funext=>i/=; rewrite fK.\nhave P1: a = g (f a) by rewrite fK. \nrewrite [in X in _ -> X]P [in X in _ -> X]P1; apply: continuous_cvg. \napply (bijective_of_cmx_continuous (can2_linearP lf fK gK) (can2_bij fK gK)).\nQed.\n\nLemma bijective_of_cmx_cvgE (V : normedModType C) \n  (m n: nat) (f: 'M[C]_(m,n) -> V) (u : nat -> 'M[C]_(m,n)) (a : 'M[C]_(m,n))\n  (lf: linear f) (bf: bijective f) :\n  u --> a = ((f \\o u)%FUN --> f a).\nProof.\nrewrite propeqE; split; last move: {+}bf=>[g fK gK].\nby apply: continuous_cvg; apply/(bijective_of_cmx_continuous lf bf).\nhave P: u = (g \\o (f \\o u))%FUN by apply/funext=>i/=; rewrite fK.\nhave P1: a = g (f a) by rewrite fK. \nrewrite [in X in _ -> X]P [in X in _ -> X]P1; apply: continuous_cvg. \napply (bijective_to_cmx_continuous (can2_linearP lf fK gK) (can2_bij fK gK)).\nQed.\n\nLemma bijective_to_cmx_is_cvgE (V : normedModType C) \n  (m n: nat) (f: V -> 'M[C]_(m,n)) (u : nat -> V)\n  (lf: linear f) (bf: bijective f) :\n  cvg u = cvg (f \\o u)%FUN.\nProof.\nrewrite propeqE; split; last move: {+}bf=>[g fK gK].\nmove/cvg_ex=>[a Pa]. apply/cvg_ex. exists (f a). by rewrite -bijective_to_cmx_cvgE.\nmove/cvg_ex=>[a Pa]. apply/cvg_ex. exists (g a).\nhave P1: a = f (g a) by []. \nmove: Pa. by rewrite [in X in X -> _]P1 -bijective_to_cmx_cvgE.\nQed.\n\nLemma bijective_of_cmx_is_cvgE (V : normedModType C) \n  (m n: nat) (f: 'M[C]_(m,n) -> V) (u : nat -> 'M[C]_(m,n))\n  (lf: linear f) (bf: bijective f) :\n  cvg u = cvg (f \\o u)%FUN.\nProof.\nrewrite propeqE; split; last move: {+}bf=>[g fK gK].\nmove/cvg_ex=>[a Pa]. apply/cvg_ex. exists (f a). by rewrite -bijective_of_cmx_cvgE.\nmove/cvg_ex=>[a Pa]. apply/cvg_ex. exists (g a).\nhave P1: a = f (g a) by []. \nmove: Pa. by rewrite [in X in X -> _]P1 -bijective_of_cmx_cvgE.\nQed.\n\nLemma bijective_to_cmx_limE (V : normedModType C) \n  (m n: nat) (f: V -> 'M[C]_(m,n)) (u : nat -> V)\n  (lf: linear f) (bf: bijective f) :\n  cvg u -> lim (f \\o u)%FUN = f (lim u).\nProof.\nmove=> ?; apply: cvg_lim; first by apply: Cmxhausdorff.\nby rewrite -bijective_to_cmx_cvgE.\nQed.\n\nLemma bijective_of_cmx_limE (V : normedModType C) \n  (m n: nat) (f: 'M[C]_(m,n) -> V) (u : nat -> 'M[C]_(m,n))\n  (lf: linear f) (bf: bijective f) :\n  cvg u -> lim (f \\o u)%FUN = f (lim u).\nProof.\nmove=> ?; apply: cvg_lim; first by apply: norm_hausdorff.\nby rewrite -bijective_of_cmx_cvgE.\nQed.\n\nLemma V_complete_sub (V : normedModType C) (m n: nat) (f: V -> 'M[C]_(m,n)) (lf: linear f) (bf : bijective f)\n  (F : set (set V)) :\n  ProperFilter F -> cauchy F -> cvg F.\nProof.\nmove: bf=>[g fK gK]; move: (can2_linearP lf fK gK)=>lg.\nmove=> PF /cauchyP F_cauchy.\ncase Em: (m == m.-1.+1); [move/eqP:Em=>Em|]; last first.\n2: case En: (n == n.-1.+1); [move/eqP:En=>En|]; last first.\n- have P1: 0%N = m by move: Em; clear -m; case: m=>/=[|k']; [case: eqP|rewrite eqxx].\n2:have P1: 0%N = n by move: En; clear -n; case: n=>/=[|k']; [case: eqP|rewrite eqxx].\n1,2: apply/cvg_ex=>/=; exists 0; apply: (cvg_distW)=>/= e egt0;\n     apply: filter_near_of => x Hx; rewrite -(fK x) (linearlfE lg).\n1:  clear -P1 egt0; case: m / P1 f g lg=> f g lg.\n2:  clear -P1 egt0; case: n / P1 f g lg=> f g lg.\n1,2: by rewrite mx_dim0 linear0 subr0 normr0 ltW.\npose vf := (fun v : V =>castmx (Em, En) (f v) ).\npose vg := (fun r=>g (castmx (esym Em, esym En) r)).\nhave lvf : linear vf by move=>a x y; rewrite /vf (linearlfE lf) !linearP.\nhave lvg : linear vg by move=>a x y; rewrite /vg (linearlfE lg) !linearP.\nhave bvf : bijective vf by exists vg=>x;rewrite /vf/vg ?gK castmx_comp castmx_id ?fK.\nhave bvg : bijective vg by exists vf=>x;rewrite /vf/vg ?gK castmx_comp castmx_id ?fK.\n(* have cf: continuous vf by exact: (bijective_to_cmx_continuous lvf bvf). *)\nhave cg: continuous vg by exact: (bijective_of_cmx_continuous lvg bvg).\nsuff fgK: (vg \\o vf)%FUN = id. suff ccf: cauchy_ex (vf @ F).\n- move: ccf=>/cauchy_exP/cauchy_cvg P1.\n  suff: cvg ((vg \\o vf)%FUN x @[x --> F])%classic by rewrite fgK.\n  by move: P1=>/cvg_ex/=[a Pa]; apply/cvg_ex; exists (vg a); \n  apply: continuous_cvg=>[|//]; apply cg.\n- move: (bounded_normr_cmxnorm lvf bvf)=>[[c1 [c1gt0 Pc1]] [c2 [c2gt0 Pc2]]].\n  move=>e egt0; have ecgt0: e / c2 > 0 by apply divr_gt0.\n  move: (F_cauchy _ ecgt0)=>[x Px].\n  exists (vf x); rewrite /= /nbhs/= -filterP_strong.\n  exists (ball x (e/c2)); exists Px; move=>y. rewrite /= -!ball_normE/= =>P2.\n  rewrite (linearlfE lvf) -linearB/= /normr/=. apply (le_lt_trans (Pc2 _)).\n  by rewrite mulrC -ltr_pdivl_mulr.\nUnshelve. 2,3:  end_near.\n- by apply/funext=>x; rewrite /vf/vg/= castmx_comp castmx_id fK.\nQed.\n\nLemma V_complete (V : finNormedModType C) (F : set (set V)) : \n  ProperFilter F -> cauchy F -> cvg F.\nProof. apply: (@V_complete_sub _ _ _ (@v2r _ V) _ v2r_bij); exact: linearP. Qed.\n\nLocal Canonical finNormedMod_completeType (V : finNormedModType C) := \n  CompleteType V (@V_complete V).\nLocal Canonical finNormedMod_CompleteNormedModule (V : finNormedModType C) := \n  Eval hnf in [completeNormedModType C of V].\nLocal Canonical vorderFinNormedMod_completeType (V : vorderFinNormedModType C) := \n  CompleteType V (@V_complete V).\nLocal Canonical vorderFinNormedMod_CompleteNormedModule (V : vorderFinNormedModType C) := \n  Eval hnf in [completeNormedModType C of V].\n\nEnd FinNormedModTypeComplete.\n\nArguments bijective_to_cmx_cvgE [R V m n f u a].\nArguments bijective_of_cmx_cvgE [R V m n f u a].\nArguments bijective_to_cmx_is_cvgE [R V m n f u].\nArguments bijective_of_cmx_is_cvgE [R V m n f u].\nArguments bijective_to_cmx_limE [R V m n f u].\nArguments bijective_of_cmx_limE [R V m n f u].\n\nLemma addr_continuous {K : numFieldType} {V : pseudoMetricNormedZmodType K} a : \n  continuous (fun z : V => a + z).\nProof.\nby move=> x; apply: (cvg_comp2 (cvg_cst _) cvg_id (@add_continuous _ _ (_, _))).\nQed.\n\nLemma addl_continuous {K : numFieldType} {V : pseudoMetricNormedZmodType K} a : \n  continuous (fun z : V => z + a).\nProof.\nby move=> x; apply: (cvg_comp2 cvg_id (cvg_cst _) (@add_continuous _ _ (_, _))).\nQed.\n\nSection FinNormedModTheory.\nVariable (R : realType) (V : finNormedModType R[i]).\nImport Num.Theory Vector.InternalTheory.\nImplicit Type (f g: nat -> V) (n: nat) (s a b : V).\n\n(* default norm is a vnorm  *)\nCanonical finNormedMod_vnorm := Vnorm (@ler_norm_add _ V) (@normr0_eq0 _ V) (@normmZ _ V).\n\nLocal Canonical finNormedMod_CompleteNormedModule.\n\nLemma Vhausdorff : hausdorff_space V.\nProof. exact: norm_hausdorff. Qed.\n\nLemma vcvg_limE f a : f --> a <-> lim f = a /\\ cvg f.\nProof. exact: (cvg_limE f a Vhausdorff). Qed.\n\nLemma vcvg_map f a (U : completeType) (h : V -> U) :\n  continuous h -> f --> a -> (h \\o f) --> h a.\nProof. \nmove=>ch cvgf; apply: (@cvg_fmap _ _ [filter of f] a h).\nby apply ch. by apply cvgf.\nQed.\n\nLemma vcvg_mapV (U : completeType) (h : U -> V) (h' : nat -> U) (a : U) :\n  continuous h -> h' --> a -> (h \\o h') --> h a.\nProof. \nmove=>ch cvgf; apply: (@cvg_fmap _ _ [filter of h'] a h).\nby apply ch. by apply cvgf.\nQed.\n\nLemma is_vcvg_map f (U : completeType) (h : V -> U) :\n  continuous h -> cvg f -> cvg (h \\o f).\nProof.\nmove=>P1 /cvg_ex=>[/= [a Pa]]. apply/cvg_ex.\nexists (h a). by move: (vcvg_map P1 Pa).\nQed.\n\nLemma is_vcvg_mapV (U : completeType) (h : U -> V) (h' : nat -> U) :\n  continuous h -> cvg h' -> cvg (h \\o h').\nProof.\nmove=>P1 /cvg_ex=>[/= [a Pa]]. apply/cvg_ex.\nexists (h a). by move: (vcvg_mapV P1 Pa).\nQed.\n\nLemma vlim_map f a (U : completeType) (h : V -> U) :\n  hausdorff_space U -> continuous h -> cvg f -> lim (h \\o f) = h (lim f).\nProof. by move=>hV ch; move/(vcvg_map ch)/cvg_lim=>/(_ hV). Qed.\n\nLemma vlim_mapV (U : completeType) (h : U -> V) (h' : nat -> U) :\n  continuous h -> cvg h' -> lim (h \\o h') = h (lim h').\nProof. by move=>ch; move/(vcvg_mapV ch)/cvg_lim=>/(_ Vhausdorff). Qed.\n\nLemma vcvg_limP f a :\n  f --> a <-> forall e, 0 < e -> exists N, forall n,  (N <= n)%N -> `|f n - a| < e.\nProof. exact: cvg_limP. Qed.\n\nLemma vcvg_subseqP f a : \n  f --> a <-> (forall (h: nat -> nat), (forall n, (h n.+1 > h n)%N) -> (f \\o h) --> a).\nProof. exact: cvg_subseqP. Qed.\n\nLemma vcvg_subseqPN f a :\n  ~ (f --> a) <-> exists e (h: nat -> nat), \n    (forall n, (h n.+1 > h n)%N) /\\ 0 < e /\\ (forall n, `|(f \\o h) n - a| >= e).\nProof. exact: cvg_subseqPN. Qed.\n\n(* vnorm V transform to vnorm of matrix *)\nProgram Definition v2r_vnorm (f : vnorm V) := @VNorm.Vnorm _ _ (fun x=>f (r2v x)) _ _ _.\nNext Obligation.\nby move=>f x y /=; rewrite linearD/= lev_norm_add.\nQed.\nNext Obligation.\nby move=>f x /= /normv0_eq0; rewrite -{2}(r2vK x)=>->; rewrite linear0.\nQed.\nNext Obligation.\nby move=>f a x/=; rewrite !linearZ/= normvZ.\nQed.\n\nProgram Definition r2v_vnorm (f : vnorm _) := @VNorm.Vnorm _ V (fun x=>f (v2r x)) _ _ _.\nNext Obligation.\nby move=>f x y /=; rewrite linearD/= lev_norm_add.\nQed.\nNext Obligation.\nby move=>f x /= /normv0_eq0; rewrite -{2}(v2rK x)=>->; rewrite linear0.\nQed.\nNext Obligation.\nby move=>f a x/=; rewrite !linearZ/= normvZ.\nQed.\n\nLemma r2vK_vnorm (f : vnorm _) x : v2r_vnorm (r2v_vnorm f) x = f x.\nProof. by rewrite /= r2vK. Qed.\nLemma v2rK_vnorm (f : vnorm V) x : r2v_vnorm (v2r_vnorm f) x = f x.\nProof. by rewrite /= v2rK. Qed.\nLemma r2v_vnormE (f : vnorm _) x : f x = r2v_vnorm f (r2v x).\nProof. by rewrite /= r2vK. Qed.\nLemma v2r_vnormE (f : vnorm V) x : f x = v2r_vnorm f (v2r x).\nProof. by rewrite /= v2rK. Qed.\n\n(* equivalence of vnorm of V *)\n(* linear continuous *)\nLemma normv_bounded (f g : vnorm V):\n  exists2 c : R[i], 0 < c & forall x, f x <= c * g x.\nProof.\nmove: (cmxnormv_bounded (v2r_vnorm f) (v2r_vnorm g))=>[c cgt0 Pc].\nexists c=>// x; by rewrite !v2r_vnormE.\nQed.\n\nLemma v2r_continuous : continuous (@v2r _ V).\nProof. apply: (bijective_to_cmx_continuous _ v2r_bij); exact: linearP. Qed.\n\nLemma r2v_continuous : continuous (@r2v _ V).\nProof. apply: (bijective_of_cmx_continuous _ r2v_bij); exact: linearP. Qed.\n\nLemma normv_ubounded (f : vnorm V) : \n  exists2 c, 0 < c & forall x, f x <= c * `| x |.\nProof. exact: normv_bounded. Qed.\n\nLemma normv_lbounded (f : vnorm V) : \n  exists2 c, 0 < c & forall x, c * `| x | <= f x.\nProof.\nmove: (normv_bounded finNormedMod_vnorm f)=>[c cgt0 Pc].\nby exists (c^-1)=>[|x]; rewrite ?ler_pdivr_mull// ?Pc// invr_gt0.\nQed.\n\nLemma cauchy_seqv_defaultE f :\n  cauchy_seqv finNormedMod_vnorm f <-> cauchy_seq f.\nProof. by []. Qed.\n\nLemma cauchy_seqv_eq (nv1 nv2 : vnorm V) f :\n  cauchy_seqv nv1 f <-> cauchy_seqv nv2 f.\nsplit.\nmove: (normv_bounded nv2 nv1). 2: move: (normv_bounded nv1 nv2).\nall: move=> [c Pc le_mn] P e Pe.\nall: have Pec: 0 < (e / c) by apply divr_gt0.\nall: move: (P (e/c) Pec )=>[N PN]; exists N=>s t Ps Pt.\nall: apply: (le_lt_trans (le_mn (f s - f t))).\nall: by rewrite -ltr_pdivl_mull// mulrC PN.\nQed.\n\nLemma cauchy_seqv_cvg (nv : vnorm V) f :\n  cauchy_seqv nv f <-> cvg f.\nProof.\nrewrite (@cauchy_seqv_eq _ finNormedMod_vnorm).\nexact: cauchy_seqP.\nQed.\n\nLemma normv_continuous (nv : vnorm V) : continuous nv.\nProof.\nsuff <-: (v2r_vnorm nv) \\o v2r = nv.\napply: continuous_comp_simp. apply: v2r_continuous.\napply cmxnormv_continuous.\nby apply/funext=>x /=; rewrite v2rK.\nQed.\n\nLocal Notation MV := 'rV[R[i]]_(Vector.dim V).\n\nLemma v2r_cvgE (u : nat -> V) (a : V): u --> a = ((v2r \\o u)%FUN --> v2r a).\nProof. apply: (bijective_to_cmx_cvgE _ v2r_bij); exact: linearP. Qed.\n\nLemma r2v_cvgE (u : nat -> MV) (a : MV) : u --> a = ((r2v \\o u)%FUN --> r2v a).\nProof. apply: (bijective_of_cmx_cvgE _ r2v_bij); exact: linearP. Qed.\n\nLemma v2r_is_cvgE (u : nat -> V) : cvg u = cvg (v2r \\o u)%FUN.\nProof. apply: (bijective_to_cmx_is_cvgE _ v2r_bij); exact: linearP. Qed.\n\nLemma r2v_is_cvgE (u : nat -> MV) : cvg u = cvg (r2v \\o u)%FUN.\nProof. apply: (bijective_of_cmx_is_cvgE _ r2v_bij). exact: linearP. Qed.\n\nLemma v2r_limE (u : nat -> V) : cvg u -> lim (v2r \\o u)%FUN = v2r (lim u).\nProof. apply: (bijective_to_cmx_limE _ v2r_bij); exact: linearP. Qed.\n\nLemma r2v_limE (u : nat -> MV) : cvg u -> lim (r2v \\o u)%FUN = r2v (lim u).\nProof. apply: (bijective_of_cmx_limE _ r2v_bij); exact: linearP. Qed.\n\nEnd FinNormedModTheory.\n\nLemma scalarlfE (R : ringType) (U : lmodType R) (f : U -> R) (lf: scalar f) :\n  f = Linear lf. Proof. by []. Qed.\n\nSection LinearContinuous.\nVariable (R : realType).\nImport Vector.InternalTheory.\n\nLemma linear_continuous (U V: finNormedModType R[i]) (f : {linear U -> V}) :\n  continuous f.\nProof.\npose g x := v2r (f (r2v x)); suff <-: r2v \\o g \\o v2r = f.\napply: continuous_comp_simp; first by apply: v2r_continuous.\napply: continuous_comp_simp; last by apply: r2v_continuous.\nby apply/cmxlinear_continuous=>a x y; rewrite /g !linearP.\nby apply/funext=>x; rewrite /g/= !v2rK.\nQed.\n\nLemma linear_continuousP (U V: finNormedModType R[i]) (f : U -> V) :\n  linear f -> continuous f.\nProof. move=>lf; rewrite (linearlfE lf); exact: linear_continuous. Qed.\n\nLemma linear_cvg (U V: finNormedModType R[i]) (f : {linear U -> V}) (u : nat -> U) (a : U) :\n  u --> a -> f \\o u --> f a.\nProof. move=>cu. apply: continuous_cvg=>//. apply: linear_continuous. Qed.\n\nLemma linear_cvgP (U V: finNormedModType R[i]) (f : U -> V) (u : nat -> U) (a : U) :\n  linear f -> u --> a -> f \\o u --> f a.\nProof. move=>lf; rewrite (linearlfE lf); exact: linear_cvg. Qed.\n\nLemma linear_is_cvg (U V: finNormedModType R[i]) (f : {linear U -> V}) (u : nat -> U) :\n  cvg u -> cvg (f \\o u).\nProof. move/cvg_ex=>[a Pa]; apply/cvg_ex; exists (f a); by apply: linear_cvg. Qed.\n\nLemma linear_is_cvgP (U V: finNormedModType R[i]) (f : U -> V) (u : nat -> U) :\n  linear f -> cvg u -> cvg (f \\o u).\nProof. move=>lf; rewrite (linearlfE lf); exact: linear_is_cvg. Qed.\n\nLemma linear_lim (U V: finNormedModType R[i]) (f : {linear U -> V}) (u : nat -> U) :\n  cvg u -> lim (f \\o u) = f (lim u).\nProof. by move=>cu; apply: cvg_lim; [apply: Vhausdorff | apply: linear_cvg]. Qed.\n\nLemma linear_limP (U V: finNormedModType R[i]) (f : U -> V) (u : nat -> U) :\n  linear f -> cvg u -> lim (f \\o u) = f (lim u).\nProof. move=>lf; rewrite (linearlfE lf); exact: linear_lim. Qed.\n\nLemma scalar_continuous (U: finNormedModType R[i]) (f : {scalar U}) :\n  continuous f.\nProof.\npose g x := (f (r2v x)); suff <-: g \\o v2r = f.\napply: continuous_comp_simp; first by apply: v2r_continuous.\nby apply/cmxscalar_continuous=>a x y; rewrite /g linearP/= !scalarP.\nby apply/funext=>x; rewrite /g/= !v2rK.\nQed.\n\nLemma scalar_continuousP (U: finNormedModType R[i]) (f : U -> R[i]) :\n  scalar f -> continuous f.\nProof. move=>lf; rewrite (scalarlfE lf); exact: scalar_continuous. Qed.\n\nLemma scalar_cvg (U: finNormedModType R[i]) (f : {scalar U}) (u : nat -> U) (a : U) :\n  u --> a -> f \\o u --> f a.\nProof. move=>cu. apply: continuous_cvg=>//. apply: scalar_continuous. Qed.\n\nLemma scalar_cvgP (U: finNormedModType R[i]) (f : U -> R[i]) (u : nat -> U) (a : U) :\n  scalar f -> u --> a -> f \\o u --> f a.\nProof. move=>lf; rewrite (scalarlfE lf); exact: scalar_cvg. Qed.\n\nLemma scalar_is_cvg (U: finNormedModType R[i]) (f : {scalar U}) (u : nat -> U) :\n  cvg u -> cvg (f \\o u).\nProof. move/cvg_ex=>[a Pa]; apply/cvg_ex; exists (f a); by apply: scalar_cvg. Qed.\n\nLemma scalar_is_cvgP (U: finNormedModType R[i]) (f : U -> R[i]) (u : nat -> U) :\n  scalar f -> cvg u -> cvg (f \\o u).\nProof. move=>lf; rewrite (scalarlfE lf); exact: scalar_is_cvg. Qed.\n\nLemma scalar_lim (U: finNormedModType R[i]) (f : {scalar U}) (u : nat -> U) :\n  cvg u -> lim (f \\o u) = f (lim u).\nProof. by move=>cu; apply: cvg_lim; [apply: Vhausdorff | apply: scalar_cvg]. Qed.\n\nLemma scalar_limP (U: finNormedModType R[i]) (f : U -> R[i]) (u : nat -> U) :\n  scalar f -> cvg u -> lim (f \\o u) = f (lim u).\nProof. move=>lf; rewrite (scalarlfE lf); exact: scalar_lim. Qed.\n\nLemma linearl_continuous (U V W: finNormedModType R[i]) (f : {bilinear U -> V -> W}) (x : V):\n  continuous (f^~ x).\nProof. have <-: applyr f x = f^~x by apply/funext/applyrE. apply: linear_continuous. Qed. \n\nLemma linearl_cvg (U V W: finNormedModType R[i]) (f : {bilinear U -> V -> W}) (x : V)\n  (u : nat -> U) (a : U):\n  u --> a -> (f^~x) \\o u --> f a x.\nProof. have <-: applyr f x = f^~x by apply/funext/applyrE. apply: linear_cvg. Qed.\n\nLemma linearl_is_cvg (U V W: finNormedModType R[i]) (f : {bilinear U -> V -> W}) (x : V) \n  (u : nat -> U) :\n  cvg u -> cvg (f^~x \\o u).\nProof. have <-: applyr f x = f^~x by apply/funext/applyrE. apply: linear_is_cvg. Qed.\n\nLemma linearl_lim (U V W: finNormedModType R[i]) (f : {bilinear U -> V -> W}) (x : V) \n  (u : nat -> U) :\n  cvg u -> lim (f^~x \\o u) = f (lim u) x.\nProof. have <-: applyr f x = f^~x by apply/funext/applyrE. apply: linear_lim. Qed.\n\nLemma linearr_continuous (U V W: finNormedModType R[i]) (f : {bilinear U -> V -> W}) (x : U):\n  continuous (f x).\nProof. exact: linear_continuous. Qed. \n\nLemma linearr_cvg (U V W: finNormedModType R[i]) (f : {bilinear U -> V -> W}) (x : U)\n  (u : nat -> V) (a : V):\n  u --> a -> (f x) \\o u --> f x a.\nProof. exact: linear_cvg. Qed.\n\nLemma linearr_is_cvg (U V W: finNormedModType R[i]) (f : {bilinear U -> V -> W}) (x : U) \n  (u : nat -> V) :\n  cvg u -> cvg (f x \\o u).\nProof. exact: linear_is_cvg. Qed.\n\nLemma linearr_lim (U V W: finNormedModType R[i]) (f : {bilinear U -> V -> W}) (x : U) \n  (u : nat -> V) :\n  cvg u -> lim (f x \\o u) = f x (lim u).\nProof. exact: linear_lim. Qed.\n\nLemma linear_to_cmx_continuous (U : finNormedModType R[i]) m n \n  (f : {linear U -> 'M[R[i]]_(m,n)}) :\n  continuous f.\nProof.\npose g x := (f (r2v x)); suff <-: g \\o v2r = f.\napply: continuous_comp_simp; first by apply: v2r_continuous.\nby apply/cmxlinear_continuous=>a x y; rewrite /g !linearP.\nby apply/funext=>x; rewrite /g/= !v2rK.\nQed.\n\nLemma linear_to_cmx_continuousP (U : finNormedModType R[i]) m n (f : U -> 'M[R[i]]_(m,n)) :\n  linear f -> continuous f.\nProof. move=>lf; rewrite (linearlfE lf); exact: linear_to_cmx_continuous. Qed.\n\nLemma linear_of_cmx_continuous (U : finNormedModType R[i]) m n \n  (f : {linear 'M[R[i]]_(m,n) -> U}) :\n  continuous f.\nProof.\npose g x := v2r (f x); suff <-: r2v \\o g = f.\napply: continuous_comp_simp; last by apply: r2v_continuous.\nby apply/cmxlinear_continuous=>a x y; rewrite /g !linearP.\nby apply/funext=>x; rewrite /g/= !v2rK.\nQed.\n\nLemma linear_of_cmx_continuousP (U : finNormedModType R[i]) m n (f : 'M[R[i]]_(m,n) -> U) :\n  linear f -> continuous f.\nProof. move=>lf; rewrite (linearlfE lf); exact: linear_of_cmx_continuous. Qed.\n\nLemma closed_linearP (U V : finNormedModType R[i]) (f : U -> V)\n  (A : set V) :\n  linear f -> closed A -> closed (f @^-1` A).\nProof. by move=>lf; apply closed_comp=>x _; apply linear_continuousP. Qed.\n\nLemma open_linearP (U V : finNormedModType R[i]) (f : U -> V)\n  (A : set V) :\n  linear f -> open A -> open (f @^-1` A).\nProof. by move=>lf; apply open_comp=>x _; apply linear_continuousP. Qed.\n\nLemma closed_linear (U V : finNormedModType R[i]) (f : {linear U -> V})\n  (A : set V) : closed A -> closed (f @^-1` A).\nProof. apply closed_linearP; exact: linearP. Qed. \n\nLemma open_linear (U V : finNormedModType R[i]) (f : {linear U -> V})\n  (A : set V) : open A -> open (f @^-1` A).\nProof. apply open_linearP; exact: linearP. Qed. \n\nLemma closed_to_cmx_linearP (U : finNormedModType R[i]) m n \n  (f : U -> 'M[R[i]]_(m,n)) (A : set 'M[R[i]]_(m,n)):\n  linear f -> closed A -> closed (f @^-1` A).\nProof. by move=>lf; apply closed_comp=>x _; apply linear_to_cmx_continuousP. Qed.\n\nLemma closed_to_cmx_linear (U : finNormedModType R[i]) m n \n  (f : {linear U -> 'M[R[i]]_(m,n)}) (A : set 'M[R[i]]_(m,n)):\n  closed A -> closed (f @^-1` A).\nProof. apply closed_to_cmx_linearP; exact: linearP. Qed.\n\nLemma open_to_cmx_linearP (U : finNormedModType R[i]) m n \n  (f : U -> 'M[R[i]]_(m,n)) (A : set 'M[R[i]]_(m,n)):\n  linear f -> open A -> open (f @^-1` A).\nProof. by move=>lf; apply open_comp=>x _; apply linear_to_cmx_continuousP. Qed.\n\nLemma open_to_cmx_linear (U : finNormedModType R[i]) m n \n  (f : {linear U -> 'M[R[i]]_(m,n)}) (A : set 'M[R[i]]_(m,n)):\n  open A -> open (f @^-1` A).\nProof. apply open_to_cmx_linearP; exact: linearP. Qed.\n\nLemma closed_of_cmx_linearP (U : finNormedModType R[i]) m n \n  (f : 'M[R[i]]_(m,n) -> U) (A : set U):\n  linear f -> closed A -> closed (f @^-1` A).\nProof. by move=>lf; apply closed_comp=>x _; apply linear_of_cmx_continuousP. Qed.\n\nLemma closed_of_cmx_linear (U : finNormedModType R[i]) m n \n  (f : {linear 'M[R[i]]_(m,n) -> U}) (A : set U):\n  closed A -> closed (f @^-1` A).\nProof. apply closed_of_cmx_linearP; exact: linearP. Qed.\n\nLemma open_of_cmx_linearP (U : finNormedModType R[i]) m n \n  (f : 'M[R[i]]_(m,n) -> U) (A : set U):\n  linear f -> open A -> open (f @^-1` A).\nProof. by move=>lf; apply open_comp=>x _; apply linear_of_cmx_continuousP. Qed.\n\nLemma open_of_cmx_linear (U : finNormedModType R[i]) m n \n  (f : {linear 'M[R[i]]_(m,n) -> U}) (A : set U):\n  open A -> open (f @^-1` A).\nProof. apply open_of_cmx_linearP; exact: linearP. Qed.\n\nEnd LinearContinuous.\n\nSection VOrderFinNormedModTheory.\nVariable (R : realType) (V : vorderFinNormedModType R[i]).\nLocal Notation M := 'rV[R[i]]_(Vector.dim V).\nImport Vector.InternalTheory.\n\nLemma closed_gev0: closed [set x : V | (0 : V) ⊑ x].\nProof. by case: V=>?[???[?]]. Qed.\n\nDefinition v2r_vorderle (x y : M) := r2v x ⊑ r2v y.\nDefinition v2r_vorderlt (x y : M) := r2v x ⊏ r2v y.\n\nLemma v2r_vorderlt_def (x y : M): v2r_vorderlt x y = (y != x) && (v2r_vorderle x y).\nProof. by rewrite /v2r_vorderlt lt_def (can_eq r2vK). Qed.\n\nLemma v2r_vorderle_anti : antisymmetric v2r_vorderle.\nProof. by move=>x y; rewrite /v2r_vorderle=>/le_anti/r2v_inj. Qed.\n\nLemma v2r_vorderle_refl : reflexive v2r_vorderle.\nProof. by move=>x; exact: le_refl. Qed.\n\nLemma v2r_vorderle_trans : transitive v2r_vorderle.\nProof. by move=>x y z; exact: le_trans. Qed. \n\nDefinition v2r_vorderle_porderMixin := LePOrderMixin \n  v2r_vorderlt_def v2r_vorderle_refl v2r_vorderle_anti v2r_vorderle_trans.\nDefinition v2r_vorderle_porderType := \n  POrderType vorder_display M v2r_vorderle_porderMixin.\nLocal Canonical v2r_vorderle_porderType.\n\nLemma v2r_lemx_add2r : forall (z x y : M), x ⊑ y -> x + z ⊑ y + z.\nProof. by move=>z x y; rewrite /Order.le/= /v2r_vorderle !linearD/= lev_add2r. Qed.\n\nLemma v2r_lemx_pscale2lP : forall (e : R[i]) (x y : M), 0 < e -> x ⊑ y -> e *: x ⊑ e *: y.\nProof. \nby move=>e x y egt0; rewrite /Order.le/= \n  /v2r_vorderle !linearZ/=; apply lev_pscale2lP.\nQed.\n\nLemma v2r_closed_gemx0: closed [set x : M | (0 : M) ⊑ x].\nProof.\nrewrite (_ : mkset _ = r2v @^-1` [set x : V | (0 : V) ⊑ x]).\napply: closed_comp=>[? _|]; [apply: r2v_continuous | apply: closed_gev0].\nby rewrite predeqE {1}/Order.le/= /v2r_vorderle linear0.\nQed.\n\nDefinition v2r_mxnormcvg := Cmxnormcvg (v2r_vnorm (finNormedMod_vnorm V))\n  v2r_lemx_add2r v2r_lemx_pscale2lP v2r_closed_gemx0.\n\nLemma nondecreasing_oppv (u_ : V ^nat) :\n  nondecreasing_seq (- u_) = nonincreasing_seq u_.\nProof. by rewrite propeqE; split => du x y /du; rewrite lev_opp2. Qed.\n\nLemma nonincreasing_oppv (u_ : V ^nat) :\n  nonincreasing_seq (- u_) = nondecreasing_seq u_.\nProof. by rewrite propeqE; split => du x y /du; rewrite lev_opp2. Qed.\n\nLemma decreasing_oppv (u_ : V ^nat) :\n  decreasing_seq (- u_) = increasing_seq u_.\nProof. by rewrite propeqE; split => du x y; rewrite -du lev_opp2. Qed.\n\nLemma increasing_oppv (u_ : V ^nat) :\n  increasing_seq (- u_) = decreasing_seq u_.\nProof. by rewrite propeqE; split => du x y; rewrite -du lev_opp2. Qed.\n\nLemma lbounded_by_opp (b : V) (u : V ^nat) :\n  lbounded_by (-b) (- u) = ubounded_by b u.\nProof. \nby rewrite propeqE; split => bu i; move: (bu i); \n  rewrite {2}/GRing.opp/= lev_opp2.\nQed.\n\nLemma ubounded_by_opp (b : V) (u : V ^nat) :\n  ubounded_by (-b) (- u) = lbounded_by b u.\nProof. \nby rewrite propeqE; split => bu i; move: (bu i); \n  rewrite {2}/GRing.opp/= lev_opp2.\nQed.\n\nLemma open_ngev0 : open [set x : V | ~ (0 : V) ⊑ x].\nProof. rewrite openC; apply closed_gev0. Qed.\n\nLemma open_ngev y :  open [set x : V | ~ y ⊑ x].\nProof.\nrewrite (_ : mkset _ = [set t | [set x | ~ (0 : V) ⊑ x] (- y + t)]).\nby move: (@addr_continuous _ _ (-y))=>/continuousP/=/(_ _ open_ngev0).\nby apply/funext=>x; rewrite /= addrC subv_ge0.\nQed.\n\nLemma open_nlev0 : open [set x : V | ~ x ⊑ (0 : V)].\nProof.\nrewrite (_ : mkset _ = [set t | [set x | ~ (0 : V) ⊑ x] (- t)]).\nby move: (@opp_continuous _ V)=>/continuousP/=/(_ _ open_ngev0).\nby apply/funext=>x; rewrite /= -{2}oppr0 lev_opp2. \nQed.\n\nLemma open_nlev y :  open [set x : V | ~ x ⊑ y].\nProof.\nrewrite (_ : mkset _ = [set t | [set x : V | ~ - y ⊑ x] (- t)]).\nby move: (@opp_continuous _ V)=>/continuousP/=/(_ _ (open_ngev (-y))).\nby apply/funext=>x; rewrite /= lev_opp2.\nQed.\n\nLemma closed_gev x : closed [set y : V | x ⊑ y ].\nProof. \nset A := ~` [set y : V | ~ (x ⊑ y)].\nhave ->: (fun x0 : V => is_true (x ⊑ x0)) = A.\nby rewrite predeqE /A => y/=; rewrite notK.\nrewrite closedC. apply/open_ngev. \nQed.\n\nLemma closed_lev x : closed [set y : V | y ⊑ x ].\nProof. \nset A := ~` [set y : V | ~ (y ⊑ x)].\nhave ->: (fun x0 : V => is_true (x0 ⊑ x)) = A.\nby rewrite predeqE /A => y/=; rewrite notK.\nrewrite closedC. apply/open_nlev. \nQed.\n\nLemma lim_gev_near (x : V) (u : V ^nat) : \n  cvg u -> (\\forall n \\near \\oo, x ⊑ u n) -> x ⊑ lim u.\nProof.\nmove=> /[swap] /(closed_cvg (fun y=>x ⊑ y))/= P1; apply/P1/closed_gev.\nQed.\n\nLemma lim_lev_near (x : V) (u : V ^nat) : \n  cvg u -> (\\forall n \\near \\oo, u n ⊑ x) -> lim u ⊑ x.\nProof.\nmove=> /[swap] /(closed_cvg (fun y : V=>y ⊑ x))/= P1;apply/P1/closed_lev.\nQed.\n\nLemma lev_lim_near (u_ v_ : V ^nat) : cvg u_ -> cvg v_ ->\n  (\\forall n \\near \\oo, u_ n ⊑ v_ n) -> lim u_ ⊑ lim v_.\nProof.\nmove=> uv cu cv; rewrite -(subv_ge0) -limB//.\napply: lim_gev_near=>//. apply: is_cvgB=>//.\nby apply: filterS cv => k; rewrite (subv_ge0).\nQed.\n\nLemma lim_gev (x : V) (u : V ^nat) : cvg u -> lbounded_by x u -> x ⊑ lim u.\nProof.\nby move=>P1 P2; apply: (lim_gev_near P1); apply: nearW.\nQed.\n\nLemma lim_lev (x : V) (u : V ^nat) : cvg u -> ubounded_by x u -> lim u ⊑ x.\nProof.\nby move=>P1 P2; apply: (lim_lev_near P1); apply: nearW.\nQed.\n\nLemma lev_lim (u v : V^nat) : cvg u -> cvg v ->\n  (forall n, u n ⊑ v n) -> lim u ⊑ lim v.\nProof.\nby move=>P1 P2 P3; apply: (lev_lim_near P1 P2); apply: nearW.\nQed.\n\nLemma nondecreasing_cvg_lev (u : V ^nat) :\n       nondecreasing_seq u -> cvg u -> ubounded_by (lim u) u.\nProof.\nmove=>Ph Pc i; apply: lim_gev_near=>//; exists i=>// j; apply Ph.\nQed.\n\nLemma nonincreasing_cvg_gev (u : V ^nat) : \n  nonincreasing_seq u -> cvg u -> lbounded_by (lim u) u.\nProof.\nmove=>Ph Pc i; apply: lim_lev_near=>//; exists i=>// j; apply Ph.\nQed.\n\nLemma vnondecreasing_is_cvg (f : nat -> V) (b : V) :\n  nondecreasing_seq f -> ubounded_by b f -> cvg f.\nProof.\nmove=>P1 P2. pose g := (v2r \\o f).\nhave P3: nondecreasing_seq g by move=>n m /P1; rewrite {2}/Order.le/= /v2r_vorderle !v2rK.\nhave P4: ubounded_by (v2r b) g by move=>i; rewrite /Order.le/= /v2r_vorderle !v2rK.\nmove: (cmxnondecreasing_is_cvg v2r_mxnormcvg P3 P4).\nhave <-: r2v \\o g = f by apply/funext=>x/=; rewrite v2rK.\nmove=> /cvg_ex[l fxl]; apply/cvg_ex; exists (r2v l).\nby apply: continuous_cvg => //; apply: r2v_continuous.\nQed.\n\nLemma vnonincreasing_is_cvg (f : nat -> V) (b : V) :\n    nonincreasing_seq f -> lbounded_by b f -> cvg f.\nProof.\nrewrite -(nondecreasing_oppv) -(ubounded_by_opp) -is_cvgNE.\nexact: vnondecreasing_is_cvg.\nQed.\n\nEnd VOrderFinNormedModTheory.\n\n\n", "meta": {"author": "coq-quantum", "repo": "CoqQ", "sha": "95a24776c5e0df839f2c5a9133227eef56487065", "save_path": "github-repos/coq/coq-quantum-CoqQ", "path": "github-repos/coq/coq-quantum-CoqQ/CoqQ-95a24776c5e0df839f2c5a9133227eef56487065/src/mxtopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.691941921563868}}
{"text": "Require Import Paths Equivalences UsefulEquivalences Funext UnivalenceAxiom HLevel.\n\n(** This file defines some useful equivalences that require functional\n   extensionality, usually involving equivalences between function\n   spaces. *)\n\n(** Currying and uncurrying are equivalences. *)\n\nDefinition curry_equiv A B C : (A * B -> C) <~> (A -> B -> C).\nProof.\n  exists (fun f => fun a b => f (a,b)).\n  apply (hequiv_is_equiv (fun f => fun (a : A)(b :B) => f (a, b))\n                                   (fun g => fun x => g (fst x) (snd x))).\n  intro f; apply funext; intro a; apply funext; intro b; auto.\n  intro g; apply funext; intros [a b]; auto.\nDefined.\n\n(** Flipping the arguments of a two-variable function is an equivalence. *)\n\nDefinition flip_equiv A B C : (A -> B -> C) <~> (B -> A -> C).\nProof.\n  exists (fun f => fun b a => f a b).\n  apply hequiv_is_equiv with (fun g => fun a b => g b a).\n  intro g; apply funext; intro a; apply funext; intro b; auto.\n  intro f; apply funext; intro b; apply funext; intro a; auto.\nDefined.\n\n(** Pre- and post-composing by an equivalence is an equivalence. *)\n\nLemma precomp_equiv A B C (g : A <~> B) : (B -> C) <~> (A -> C).\nProof.\n  exists (fun h => h o g).\n  apply @hequiv_is_equiv with (g := fun k => k o (g ^-1));\n    intros k; apply funext; intros a; unfold compose; simpl; apply map.\n  apply inverse_is_retraction.\n  apply inverse_is_section.\nDefined.\n\nLemma postcomp_equiv A B C (g : B <~> C) : (A -> B) <~> (A -> C).\nProof.\n  exists (fun h => g o h).\n  apply @hequiv_is_equiv with (g := fun k => (g ^-1) o k);\n    intros k; apply funext; intros a; unfold compose; simpl.\n  apply inverse_is_section.\n  apply inverse_is_retraction.\nDefined.\n\nLemma postcomp_equiv_dep A P Q (g : forall a:A, P a <~> Q a) :\n  (forall a, P a) <~> (forall a, Q a).\nProof.\n  exists (fun f a => g a (f a)).\n  apply @hequiv_is_equiv with (g := fun k a => (g a ^-1) (k a));\n    intros k; apply funext_dep; intros a; unfold compose; simpl.\n  apply inverse_is_section.\n  apply inverse_is_retraction.\nDefined.\n\n(** The space of factorizations through an equivalence is contractible. *)\n\nLemma equiv_postfactor_contr A B C (g : B <~> C) (h : A -> C) :\n  is_contr { f : A -> B &  g o f === h }.\nProof.\n  apply contr_equiv_contr with ({f : A -> B & g o f == h}).\n  unfold \"===\".\n  apply total_equiv with (fun f => happly).\n  intros f; apply strong_funext.\n  refine (pr2 (postcomp_equiv _ _ _ g) h).\nDefined.\n\nLemma equiv_prefactor_contr A B C (f : A <~> B) (h : A -> C) :\n  is_contr { g : B -> C &  g o f === h }.\nProof.\n  apply contr_equiv_contr with ({g : B -> C & g o f == h}).\n  unfold \"===\".\n  apply total_equiv with (fun g => happly).\n  intros g; apply strong_funext.\n  refine (pr2 (precomp_equiv _ _ _ f) h).\nDefined.\n\n(** It follows that [is_hiso] is a prop, and hence equivalent to [is_equiv].  *)\n\nTheorem is_hiso_is_prop A B (f : A -> B) : is_prop (is_hiso f).\nProof.\n  apply allpath_prop.\n  intros [g1 h1] [g2 h2].\n  set (feq := (f ; hiso_to_equiv f (g1,h1)) : A <~> B).\n  apply prod_path; apply contr_path.\n  refine (equiv_prefactor_contr _ _ _ feq (idmap A)).\n  refine (equiv_postfactor_contr _ _ _ feq (idmap B)).\nDefined.\n\nTheorem is_equiv_is_hiso_equiv A B (f : A -> B) : is_equiv f <~> is_hiso f.\nProof.\n  apply prop_iff_equiv.\n  apply is_equiv_is_prop.\n  apply is_hiso_is_prop.\n  intros fiseq; exact (equiv_to_hiso (f; fiseq)).\n  apply hiso_to_equiv.\nDefined.\n\n(** Cartesian products have the correct universal property. *)\n\nLemma prod_equiv A B T :\n  (T -> A) * (T -> B) <~> (T -> A * B).\nProof.\n  exists (fun fg => fun t => (fst fg t, snd fg t)).\n  apply @hequiv_is_equiv with\n    (fun h => (fun t => fst (h t), fun t => snd (h t))).\n  intros h; apply funext; intros t; simpl.\n  destruct (h t) as [a b]; auto.\n  intros [f g]; apply prod_path; apply funext; intros t; auto.\nDefined.\n\n(** Given an iterated fibration, to give a section of the composite\n   fibration is equivalent to giving a section of the first fibration and\n   a section over that of the second.  *)\n\nLemma section_total_equiv A (P : A -> Type) (Q : forall a, P a -> Type) :\n  (forall a, sigT (Q a)) <~> {s : forall a, P a & forall a, Q a (s a) }.\nProof.\n  exists (fun f => (existT (fun s => forall a, Q a (s a))\n    (fun a => pr1 (f a)) (fun a => pr2 (f a)))).\n  apply hequiv_is_equiv with\n    (g := fun sr:{s : forall a, P a & forall a, Q a (s a) } =>\n      let (s,r) := sr in (fun a => existT (Q a) (s a) (r a))).\n  intros [s r].\n  set (p := funext_dep (f := eta_dep s) (g := s) (fun a => idpath (s a))).\n  apply total_path with p; simpl.\n  apply funext_dep; intros a.\n  apply (concat (trans_map p\n    (fun s' (r': forall a, Q a (s' a)) => r' a) (eta_dep r))).\n  path_via (transport (happly_dep p a) (eta_dep r a)).\n  unfold happly_dep.\n  apply @map_trans with (f := fun h : forall a' : A, P a' => h a).\n  path_via (transport (idpath (s a)) (eta_dep r a)).\n  apply happly, map.\n  apply funext_dep_compute with\n    (f := eta_dep s) (g := s) (p := fun a' : A => idpath (s a')).\n  intros f.\n  apply funext_dep; intros a.\n  destruct (f a); auto.\nDefined.\n\n(** The space of sections of fibrations is \"associative\". *)\n\nSection SectionAssoc.\n\n  Hypotheses (A:Type) (P : A -> Type) (Q : forall x, P x -> Type).\n\n  Let sa1 : (forall (x:A) (p:P x), Q x p)\n    -> forall xp:sigT P, Q (pr1 xp) (pr2 xp).\n  Proof.\n    intros f [x p]; exact (f x p).\n  Defined.\n\n  Let sa2 : (forall xp:sigT P, Q (pr1 xp) (pr2 xp))\n    -> forall (x:A) (p:P x), Q x p.\n  Proof.\n    intros f x p; exact (f (x;p)).\n  Defined.\n    \n  Definition section_assoc :\n    (forall (x:A) (p:P x), Q x p) <~> (forall xp:sigT P, Q (pr1 xp) (pr2 xp)).\n  Proof.\n    exists sa1.\n    apply hequiv_is_equiv with sa2.\n    intros f; apply funext_dep; intros [x p]; auto.\n    intros f; apply funext_dep; intros p; apply funext_dep; intros x; auto.\n  Defined.\n\nEnd SectionAssoc.\n\nSection SectionAssocSum.\n\n  Hypotheses (A:Type) (P : A -> Type) (Q : sigT P -> Type).\n\n  Let sa1 : (forall (x:A) (p:P x), Q (x;p))\n    -> forall xp:sigT P, Q xp.\n  Proof.\n    intros f [x p]; exact (f x p).\n  Defined.\n\n  Let sa2 : (forall xp:sigT P, Q xp)\n    -> forall (x:A) (p:P x), Q (x;p).\n  Proof.\n    intros f x p; exact (f (x;p)).\n  Defined.\n    \n  Definition section_assoc_sum :\n    (forall (x:A) (p:P x), Q (x;p)) <~> (forall xp:sigT P, Q xp).\n  Proof.\n    exists sa1.\n    apply hequiv_is_equiv with sa2.\n    intros f; apply funext_dep; intros [x p]; auto.\n    intros f; apply funext_dep; intros p; apply funext_dep; intros x; auto.\n  Defined.\n\nEnd SectionAssocSum.\n\n(* And \"commutative\". *)\n\nDefinition section_comm (A:Type) (B:Type) (P : A -> B -> Type) :\n  (forall a b, P a b) <~> (forall b a, P a b).\nProof.\n  exists (fun f b a => f a b).\n  apply hequiv_is_equiv with (fun f a b => f b a).\n  intros f; apply funext_dep; intros y; apply funext_dep; intros x; auto.\n  intros f; apply funext_dep; intros x; apply funext_dep; intros y; auto.\nDefined.\n\n(* The space of sections of a type dependent on paths with one end\n   free is equivalent, by the eliminator, to the fiber over the\n   identity path. *)\n\nProgram Definition section_paths_equiv A (x:A)\n  (P : forall (b:A), x==b -> Type) :\n  (forall (y:A) (p: x == y), P y p) <~> P x (idpath x)\n  := (_ ; hequiv_is_equiv _ _ _ _).\nNext Obligation.\n  intros A x P Z.\n  exact (Z x (idpath x)).\nDefined.\nNext Obligation.\n  intros A x P z y p.\n  induction p. exact z.\nDefined.\nNext Obligation.\n  intros A x P z;\n    unfold section_paths_equiv_obligation_1, section_paths_equiv_obligation_2.\n  auto.\nDefined.\nNext Obligation.\n  unfold section_paths_equiv_obligation_1, section_paths_equiv_obligation_2.\n  intros A x P Z; apply funext_dep; intros y; apply funext_dep; intros p.\n  induction p. auto.\nDefined.\n\n(* Finally, we can prove that [is_adjoint_equiv] is equivalent to [is_equiv]. *)\n\nTheorem is_adjoint_equiv_equiv A B (f : A -> B) :\n  is_equiv f <~> is_adjoint_equiv f.\nProof.\n  unfold is_equiv, is_contr.\n  apply @equiv_compose with\n    (B := {g: forall y:B, hfiber f y & forall y y0, y0 == g y}).\n  apply section_total_equiv.\n  unfold hfiber.\n  set (X := {g : B -> A & forall y:B, f (g y) == y}).\n  set (Y := forall y : B, {x : A & f x == y}).\n  set (k := equiv_inverse\n    (section_total_equiv B (fun _ => A) (fun y x => f x == y)) : X <~> Y).\n  apply @equiv_compose with\n    (B := {gs : X & forall y y0, y0 == k gs y}).\n  apply equiv_inverse.\n  exists (total_map k (fun gs => idmap\n    (forall (y : B) (y0 : {x : A & f x == y}), y0 == k gs y))).\n  apply pullback_total_is_equiv with (f := k)\n    (Q := fun g => forall (y : B) (y0 : {x : A & f x == y}), y0 == g y).\n  unfold X.\n  apply @equiv_compose with\n    (B := {g : B -> A & { s : forall y, f (g y) == y &\n      forall (y : B) (y0 : {x : A & f x == y}), y0 == k (g;s) y}}).\n  apply equiv_inverse.\n  apply total_assoc_sum with\n    (Q := fun gs => forall (y : B) (y0 : {x : A & f x == y}), y0 == k gs y).\n  unfold is_adjoint_equiv.\n  cut (forall g,\n    {s : forall y : B, f (g y) == y &\n      forall (y : B) (y0 : {x : A & f x == y}), y0 == k (g ; s) y}\n    <~>\n    {is_section : forall y : B, f (g y) == y &\n      {is_retraction : forall x : A, g (f x) == x &\n        forall x : A, map f (is_retraction x) == is_section (f x)}}).\n  intros H. apply total_equiv with (g := H). intros g; apply (pr2 (H g)).\n  intros g.\n  cut (forall s,\n    (forall (y : B) (y0 : {x : A & f x == y}), y0 == k (g ; s) y)\n    <~>\n    {is_retraction : forall x : A, g (f x) == x &\n      forall x : A, map f (is_retraction x) == s (f x)}).\n  intros H. apply total_equiv with H.  intros s; apply (pr2 (H s)).\n  intros s.\n  apply @equiv_compose with\n    (B := forall (y : B) (x : A) (p : f x == y), (x;p) == k (g;s) y).\n  apply postcomp_equiv_dep. intros y.\n  apply equiv_inverse.\n  apply section_assoc_sum with (Q := fun y0 => y0 == k (g;s) y).\n  apply @equiv_compose with\n    (B := forall (y : B) (x : A) (p : f x == y),\n      { q : x == pr1 (k (g;s) y) &\n        transport q p == pr2 (k (g;s) y)}).\n  apply postcomp_equiv_dep; intros y.\n  apply postcomp_equiv_dep; intros x.\n  apply postcomp_equiv_dep; intros p.\n  apply total_paths_equiv.\n  unfold k; simpl. clear X Y k.\n  apply @equiv_compose with\n    (B := forall (x : A) (y : B) (p : f x == y),\n      {q : x == g y & transport (P := fun x0 : A => f x0 == y) q p == s y}).\n  apply section_comm.\n  apply @equiv_compose with\n    (B := forall x:A, { r : g (f x) == x & map f r == s (f x)}).\n  2:apply section_total_equiv.\n  apply postcomp_equiv_dep; intros x.\n  apply @equiv_compose with\n    (B := forall (y : B) (p : f x == y),\n      {q : x == g y & !map f q @ p == s y}).\n  apply postcomp_equiv_dep; intros y.\n  apply postcomp_equiv_dep; intros p.\n  apply equiv_inverse.\n  apply @equiv_compose with\n    (B := {q : x == g y &\n      transport (P := fun y0 => y0 == y) (map f q) p == s y}).\n  apply total_equiv with\n    (g := fun q:x == g y => concat (trans_is_concat_opp (map f q) p)).\n  intros q; apply concat_is_equiv_left.\n  apply total_equiv with\n    (g := fun q:x == g y => concat (map_trans (fun y0 => y0 == y) f q p)).\n  intros q; apply concat_is_equiv_left.\n  apply @equiv_compose with\n    (B := {r : x == g (f x) & !map f r @ idpath (f x) == s (f x)}).\n  Focus 2.\n  apply @equiv_compose with\n    (B := {r : x == g (f x) & map f (!r) == s (f x)}).\n  apply @equiv_compose with\n    (B := {r : x == g (f x) & !map f r == s (f x)}).\n  apply total_equiv with (fun r:x == g (f x) =>\n    concat (!idpath_right_unit _ _ _ (!map f r))).\n  intros r; apply concat_is_equiv_left.\n  apply total_equiv with (fun r:x == g (f x) =>\n    concat (opposite_map _ _ f _ _ r)).\n  intros r; apply concat_is_equiv_left.\n  exists (total_map\n    (P := fun r => map f (!r) == s (f x))\n    (Q := fun r => map f r == s (f x))\n    (opposite_equiv x (g (f x)))\n    (fun r => idmap (map f (!r) == s (f x)))).\n  refine (pullback_total_is_equiv\n    (fun r => map f r == s (f x)) (opposite_equiv x (g (f x)))).\n  refine (section_paths_equiv B (f x)\n    (fun y p => {q : x == g y & !map f q @ p == s y})).\nDefined.\n\n(** And therefore it is a prop. *)\n\nTheorem is_adjoint_equiv_is_prop A B (f : A -> B) :\n  is_prop (is_adjoint_equiv f).\nProof.\n  apply allpath_prop; intros e1 e2.\n  apply equiv_injective with\n    (V := is_equiv f)\n    (w := equiv_inverse (is_adjoint_equiv_equiv A B f)).\n  apply is_equiv_is_prop.\nDefined.\n", "meta": {"author": "jcmckeown", "repo": "HoTT-local", "sha": "6f6aec6dc86148181fd30f58f671e3007e1212b0", "save_path": "github-repos/coq/jcmckeown-HoTT-local", "path": "github-repos/coq/jcmckeown-HoTT-local/HoTT-local-6f6aec6dc86148181fd30f58f671e3007e1212b0/Coq/FunextEquivalences.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6919043775328246}}
{"text": "(** *   Euclidean chains *)\n\n(** ** Introduction\n\n  In this module, we study a way to build efficiently efficient chains.\n  Our approach is recursive (compositional?). Chains associated with big exponents are built by composition of smaller chains. Thus, the construction of a \nsmall computation may be parameterized by the context in which it will be \n  used. In other terms, we shall use Continuation Passing Style \n\n  Euclidean chains are introduced by %\\textbf{Add reference to litterature by Srecko, Pierre et al.}.  \n\n\n*)\n\n\n\nRequire Import Inverse_Image  Inclusion  Wf_nat.\nRequire Import Addition_Chains  NArith  Arith PArith  Compatibility.  \nRequire Import More_on_positive.\nImport Monoid_def  Pow.\nRequire Import Recdef Wf_nat.\nRequire Import  More_on_positive .\nRequire Import Wf_transparent Lexicographic_Product  Dichotomy BinaryStrat.\nGeneralizable All Variables.\nImport Morphisms.\nImport Monoid_def.\n\n\n\nLtac add_op_proper M H := \n let h := fresh H in\n   generalize (@Eop_proper _ _ _ _ M); intro h.\n\n\n(**  * CPS chain construction\n*)\n\n(** Type of chain continuations *)\n\n(* begin snippet FchainDef *)\nDefinition Fkont (A:Type) := A -> @computation A.\n\nDefinition Fchain := forall A, Fkont A -> A -> @computation A.\n(* end snippet FchainDef *)\n\n(** [F3 k x] computes $z = x^3$, then executes the computation associated\n   with [k z] *)\n\n(* begin snippet F3Def *)\nDefinition F3 : Fchain := \n fun  A k  (x:A) =>\n  y <--- x times x ;\n  z <--- y times x ;\n  k  z.\n(* end snippet F3Def *)\n\n(* begin snippet F1F2 *)\nDefinition F1 : Fchain := \n fun A k (x:A) => k x.\n\nDefinition F2 : Fchain := \nfun  A k  (x:A) =>\n  y <--- x times x ;\n  k  y.\n(* end snippet F1F2 *)\n\n\n(** An Fchain [f] can be considered as a function that takes as \n    argument another chain [c] for continueing the computation.\n*)\n\n(* begin snippet Fapply *)\nDefinition Fapply (f : Fchain) (c: chain) : chain  :=\n fun (A:Type) (x: A)  =>  f A (c A) x.\n(* end snippet Fapply *)\n\n(* begin snippet Fcompose *)\nDefinition Fcompose (f1 f2: Fchain) : Fchain  :=\n fun   A k x =>  f1  A (fun y => f2 A k y) x.\n(* end snippet Fcompose *)\n\n(** Any Fchain can be transformed into a plain chain *)\n\n(* begin snippet F2C *)\nDefinition F2C (f : Fchain) : chain :=\n fun (A:Type) => f A Return .\n\nCompute the_exponent (F2C F3).\n(* end snippet F2C *)\n\n(** Composition of Fchains \n\nFchains are used for building correct exponentiation schemes by composition \nof correct components. So, we have to define composition of Fchains.\n\n*)\n\n(* begin snippet F9Def *)\nExample F9 := Fcompose F3 F3.\n\nCompute F9.\n(* end snippet F9Def *)\n\n(** Fchains associated with powers of 2 *)\n\n\n(** computes $x^{2^n}$ then send this value to $k$ *)\n\n(** The neutral element for Fcompose *)\n\n\n\n(* begin snippet F1Neutral:: no-out  *)\nLemma F1_neutral_l : forall f, Fcompose F1 f = f.\nProof. reflexivity. Qed.\n\nLemma F1_neutral_r : forall f, Fcompose f F1 = f.\nProof. reflexivity. Qed.\n(* end snippet F1Neutral *)\n\n(* begin snippet Fexp2 *)\nFixpoint  Fexp2_of_nat (n:nat) : Fchain :=\n match n with O => F1\n            | S p => Fcompose F2 (Fexp2_of_nat p)\n end.\n\nDefinition Fexp2 (p:positive) : Fchain :=\n  Fexp2_of_nat (Pos.to_nat p). \n\nCompute Fexp2 4.\n\nCompute the_exponent (F2C (Fexp2 4)).\n(* end snippet Fexp2 *)\n\n\n(*\nCompute F9.\n\n= fun (A : Type) (x : Fkont A) (x0 : A) =>\n       x1 <--- x0 times x0;\n       x2 <--- x1 times x0; x3 <--- x2 times x2; x4 <--- x3 times x2; x x4\n     : Fchain\n\n*)\n\n(* begin snippet F9Ok:: no-out *)\nRemark F9_correct :chain_correct 9 (F2C F9).\nparam_chain_correct.\nQed.\n(* end snippet F9Ok *)\n\n\nCompute the_exponent (F2C F9).\n(*\n= 9\n     : nat\n\n*)\n\n\n\n\n\n\n\n(** A first attempt to define Fchain correctness *)\n\n(* begin snippet BadDefa *)\nModule Bad.\n  \nDefinition Fchain_correct (n:nat) (fc : Fchain) :=\n  forall A `(M : @EMonoid A op E_one E_equiv) k (a:A),\n    computation_execute op (fc A k  a)==\n    computation_execute op (k  (a ^ n)).\n(* end snippet BadDefa *)\n\n(* begin snippet BadDefb *)\nTheorem F3_correct : Fchain_correct 3 F3. (* .no-out *)\nProof.  (* .no-out *)\n  intros  A op E_one E_equiv M k  a ; cbn. (* .no-out *)\n  monoid_simpl M.\nAbort.\nEnd Bad.\n\n(* end snippet BadDefb *)\n\n(** Equivalence on computations *)\n\nDefinition computation_equiv {A:Type} (op: Mult_op A)\n           (equiv : Equiv A)\n           (c c': @computation A) :=\n   computation_execute op c == computation_execute op c'.\n\n\n#[ global ] Instance Comp_equiv {A:Type} (op: Mult_op A) (equiv : Equiv A):\n  Equiv (@computation A) :=\n  @computation_equiv A op equiv.\n\n#[ global ] Instance comp_equiv_equivalence {A:Type} (op: Mult_op A)\n           (equiv : Equiv A) : Equivalence  equiv ->\n                               Equivalence (computation_equiv op equiv).   \nProof.\nintro H; split; red in equiv.\n - intro c; red;reflexivity.\n - intros x y H0; red; symmetry; auto.\n -intros x y z H0 H1; red;  transitivity (computation_execute op y);auto. \n Qed.\n\n\n\n(** Fkonts that respect E_equiv *)\n\n(* begin snippet FkontProper *)\nClass Fkont_proper\n      `(M : @EMonoid A op E_one E_equiv) (k: Fkont A )  :=\n  Fkont_proper_prf:\n    Proper (equiv ==> computation_equiv op E_equiv) k.\n(* end snippet FkontProper *)\n\n\n\n#[ global ] Instance Return_proper `(M : @EMonoid A op E_one E_equiv) :\n  Fkont_proper M (@Return A).\nProof.\n intros x y Hxy; assumption.\nQed.\n\n\n\n(** Fchain correctness (for exponent of type [nat] *)\n\n\n(* begin snippet GoodFchainCorrect *)\nDefinition Fchain_correct_nat (n:nat) (f : Fchain) :=\n forall A `(M : @EMonoid A op E_one E_equiv) k\n        (Hk :Fkont_proper M k)\n        (a : A) ,\n computation_execute op (f A k  a) ==\n computation_execute op (k  (a ^ n)).\n\nDefinition Fchain_correct (p:positive) (f : Fchain) :=\n Fchain_correct_nat (Pos.to_nat p) f.\n(* end snippet GoodFchainCorrect *)\n\n(* begin snippet F1Ok:: no-out *)\nLemma F1_correct : Fchain_correct 1 F1.\nProof.\n  intros until M ; intros k Hk a ; unfold F1; simpl.\n  apply Hk; monoid_simpl M; reflexivity.\nQed.\n(* end snippet F1Ok:: no-out *)\n\n(* begin snippet F3Ok *)\nLemma F3_correct : Fchain_correct 3 F3. (* .no-out *)\nProof. (* .no-out *)\n  intros until M; intros k Hk a; simpl.\n  apply Hk.\n  monoid_simpl M;  reflexivity.\nQed.\n(* end snippet F3Ok *)\n\n(* begin snippet F2Ok:: no-out *)\nLemma F2_correct : Fchain_correct 2 F2.\nProof. \n  intros until M; intros k Hk a; simpl;\n  apply  Hk;  monoid_simpl M;  reflexivity.\nQed.\n(* end snippet F2Ok *)\n\n(** F2C preserves correctness *)\n\nLemma F2C_correct (p:positive) (fc : Fchain) :\n  Fchain_correct p fc ->  chain_correct p (F2C fc).\nProof.\n  split;auto with chains;  intros until M;intro x; unfold F2C;\n  specialize (H _ _ _ _ M (@Return A));\n  unfold  Fapply, C1; red; unfold chain_apply;\n  rewrite computation_eval_rw;\n  apply H; apply Return_proper.\nQed.\n\n(* begin snippet Bad2a:: no-out *)\nModule Bad2.\n\nLemma Fcompose_correct :\n  forall f1 f2 n1 n2,\n    Fchain_correct n1 f1 ->\n    Fchain_correct n2 f2 ->\n    Fchain_correct (n1 * n2) (Fcompose f1 f2).\nProof.\n  (* ... *)\n(* end snippet Bad2a *) \n unfold Fchain_correct, Fcompose, Fchain_correct_nat; intros.\n specialize (H _  _ _ _ M (fun y : A => f2 A k y) ).  \n specialize (H0 _ _ _ _ M).\n rewrite  H.\n rewrite H0.\n apply Hk.\n rewrite Pos2Nat.inj_mul.\n rewrite power_of_power.  rewrite Nat.mul_comm;reflexivity.\n auto.\n (* begin snippet Bad2b:: -.h#* .h#Hk .h#a .h#x .h#y .h#Hxy  *)\n intros x y Hxy;  red.\n (* end snippet Bad2b *)\n (* begin snippet Bad2c:: no-out *)\nAbort.\n \nEnd Bad2.\n(* end snippet Bad2c *)\n\n\n\n(** Fisrt attempt to define Fchain_proper *)\n\n(* begin snippet Bad3 *)\nModule Bad3.\n  \nClass Fchain_proper (fc : Fchain) := Fchain_proper_bad_prf : \n forall  `(M : @EMonoid A op E_one E_equiv) k  ,\n    Fkont_proper M k ->\n    forall x y, x == y ->\n               @computation_equiv _ op E_equiv\n                                  (fc A k x)\n                                  (fc A k y).\n\n(* end snippet Bad3 *)\n\n(* begin snippet Bad3b:: no-out *)\n#[ global ] Instance Fcompose_proper (f1 f2 : Fchain)\n         (_ : Fchain_proper f1)\n         (_ : Fchain_proper f2) :\n  Fchain_proper (Fcompose f1 f2).\nProof. \n intros until M;intros k Hk x y Hxy; unfold Fcompose;cbn. \n apply (H _ _ _ _ M); auto.\n intros u v Huv;apply (H0 _ _ _ _ M);auto.\nQed.\n(* end snippet Bad3b *)\n\n(* begin snippet Bad3c *)\nEnd Bad3.\n(* end snippet Bad3c *)\n\n(** Correct definition *)\n\n(* begin snippet correctProper *)\nDefinition Fkont_equiv  `(M : @EMonoid A op E_one E_equiv)\n (k k': Fkont A )  := \n forall x y : A, x == y ->\n                 computation_equiv op E_equiv  (k x) (k' y).\n\n\nClass Fchain_proper (fc : Fchain) := Fchain_proper_prf : \n forall  `(M : @EMonoid A op E_one E_equiv) k k' ,\n    Fkont_proper M k -> Fkont_proper M k' ->    \n    Fkont_equiv M k k' ->\n   forall x y,  x == y ->\n               @computation_equiv _ op E_equiv\n                                  (fc A k x)\n                                  (fc A k' y).\n(* end snippet correctProper *)\n\n(* begin snippet F1proper:: no-out *)\n#[ global ] Instance F1_proper : Fchain_proper F1.\nProof.\n  intros until M ; intros k k' Hk Hk' H a b H0; unfold F1; cbn;\n  now apply H.  \nQed.\n(* end snippet F1proper *)\n\n(* begin snippet F3proper:: no-out *)\n#[ global ] Instance F3_proper : Fchain_proper F3.\n(* end snippet F3proper *)\nProof.\n  intros  A op one equiv M  k k' Hk Hk'  Hkk' x y Hxy;  \n  apply Hkk'; add_op_proper M H; repeat rewrite Hxy;\n  reflexivity.\nQed.\n\n(* begin snippet F2proper:: no-out *)\n#[ global ] Instance F2_proper : Fchain_proper F2.\n(* end snippet F2proper *)\nProof.\n  intros  A op one equiv M  k k' Hk Hk'  Hkk' x y Hxy;  \n  apply Hkk'; add_op_proper M H; repeat rewrite Hxy;\n  reflexivity.\nQed.\n\n\n\n\n(**  Fcompose respects correctness and properness *)\n\nLemma Fcompose_correct_nat : forall fc1 fc2 n1 n2,\n                           Fchain_correct_nat n1 fc1 ->\n                           Fchain_correct_nat n2 fc2 ->\n                           Fchain_proper fc2 -> \n                           Fchain_correct_nat (n1 * n2)%nat\n                                              (Fcompose fc1 fc2).\nProof.\n unfold  Fcompose, Fchain_correct_nat; intros.\n assert (Fkont_proper M (fun y : A => fc2 A k y)).\n -  intros x y Hxy; apply H1 with E_one M;auto.\n - rewrite  (H _  _ _ _ M (fun y : A => fc2 A k y) H2 a).  \n   + rewrite (H0 _ _ _ _ M k Hk).\n     * apply  Hk.  \n       rewrite power_of_power;auto;\n       rewrite Nat.mul_comm;reflexivity.\nQed.\n\n(* begin snippet FcomposeCorrect:: no-out *)\nLemma Fcompose_correct :\n  forall fc1 fc2 n1 n2,\n    Fchain_correct n1 fc1 ->\n    Fchain_correct n2 fc2 ->\n    Fchain_proper fc2 -> \n    Fchain_correct (n1 * n2) (Fcompose fc1 fc2).\n(* end snippet FcomposeCorrect *)\nProof.\n unfold Fchain_correct; intros.\n rewrite Pos2Nat.inj_mul.\n  apply Fcompose_correct_nat;auto.\nQed.\n\n(* begin snippet FcomposeProper:: no-out *)\n#[ global ] Instance Fcompose_proper (fc1 fc2: Fchain)\n                         (_ : Fchain_proper fc1)\n                         (_ : Fchain_proper fc2) :\n  Fchain_proper (Fcompose fc1 fc2).\n(* end snippet FcomposeProper *)\nProof.\n  unfold Fcompose; red;  intros. \n  apply   (H _  _ _ _ M);\n    (assumption || \n                intros u v Huv;  apply (H0 _ _ _ _ M);auto).\nQed.\n\n\n#[ global ] Instance Fexp2_nat_proper (n:nat) : \n                           Fchain_proper (Fexp2_of_nat n).\nProof.\n  induction n; cbn.\n   - apply F1_proper.\n   - apply Fcompose_proper ; [apply F2_proper | apply IHn].\nQed.\n\nLemma  Fexp2_nat_correct (n:nat) : \n                           Fchain_correct_nat (2  ^ n) \n                                              (Fexp2_of_nat n).\nProof.\n  induction n; cbn.\n - apply F1_correct.\n -  rewrite Nat.add_0_r;\n   replace (2 ^ n + 2 ^ n)%nat with (2 * 2 ^n)%nat by  lia;\n   apply Fcompose_correct_nat;auto.\n   +  apply F2_correct.\n   +  apply  Fexp2_nat_proper.\nQed.\n\n(* begin snippet Fexp2Correct:: no-out *)\nLemma  Fexp2_correct (p:positive) : \n  Fchain_correct (2 ^ p) (Fexp2 p).\n(* end snippet Fexp2Correct *)\nProof.\n intros;red.\n  rewrite Pos_pow_power, Pos2Nat_morph.\n generalize (Fexp2_nat_correct (Pos.to_nat p)).\n unfold Fexp2.\n change (Pos.to_nat 2) with 2%nat.\n  replace (2 ^ Pos.to_nat p)%nat with (2%nat ^ Pos.to_nat p)%M.\n auto.\n now rewrite nat_power_ok.\nQed.\n\n(* begin snippet Fexp2Proper:: no-out *)\n#[ global ] Instance  Fexp2_proper (p:positive) : Fchain_proper (Fexp2 p).\n(* end snippet Fexp2Proper *)\nProof.\n  unfold  Fexp2; apply Fexp2_nat_proper.\nQed.\n\n\n(** ** Remark\n\n\nWe are now  able to build chains for any exponent of the form \n$2^k.3^p$, using Fcompose and previous lemmas.\n\nLet us look at a simple example *)\n\n(* begin snippet F144 *)\n#[global] Hint Resolve F1_correct F1_proper\n     F3_correct F3_proper Fcompose_correct Fcompose_proper\n     Fexp2_correct Fexp2_proper : chains.\n\nExample F144:  {f : Fchain | Fchain_correct 144 f /\\\n                             Fchain_proper f}. (* .no-out *)\nProof. (* .no-out *)\n change 144 with ( (3 * 3) * (2 ^ 4))%positive.\n exists (Fcompose (Fcompose F3 F3) (Fexp2 4)); auto with chains.\nDefined.\n\n\nCompute proj1_sig F144.\n(* end snippet F144 *)\n\n(*** K chains \n\n Not every chain can be built efficiently  with [Fcompose]\n For instance, consider the exponent $n=87 = 3 \\times 29$. \n29 is a prime \n  number, thus it cannot be decomposed  as a product \n  $p\\times q$. \n  On the other hand, consider the equality  $87 = 10 \\times 8 + 7$.  We can plan to build a chain $c_1$ for computing $y = x^10$, then\n compose it with a chain $c_2$ for computing $y^8$, and finally \n multiply the result by $x^7$.\n But, if the chain $c_1$ contains also a computation of $x^7$,\n this value can be used for computing $x^{87} = x^{80}\\times x^7$.\n \n In simpler words, we want to build computation schemes that \n compute two distinct powers of a given value $x$. \n  Like in some programming languages\n that allow  \"multiple values\", we chosed to express this feature \n in terms of continuations that accept two arguments\n\n*)\n\n\n(** Bad solution *)\n\nModule Bad4.\n\n(* begin snippet Fplus:: no-out *)\nDefinition Fplus (f1 f2 : Fchain) : Fchain :=\n  fun A k x => f1 A\n                  (fun y =>\n                     f2 A\n                        (fun z => t <--- z times y; k t) x) x.\n\nExample F23 := Fplus F3 (Fplus (Fexp2 4) (Fexp2 2)).\n\n\nLemma  F23_ok : chain_correct 23 (F2C F23).\nProof. \n param_chain_correct.\nQed.\n\n(* end snippet Fplus *)\n\n(* begin snippet Fplusb *)\nCompute F23.\n(* end snippet Fplusb *)\n\nEnd Bad4.\n\n(* begin snippet KchainDef *)\n(** Continuations with two arguments *)\n\nDefinition Kkont A:=  A -> A -> @computation A.\n\n(** CPS chain builders for  two exponents  *)\n\nDefinition Kchain :=  forall A, Kkont A -> A -> @computation A.\n\n(* end snippet KchainDef *)\n\n(** Kchain for $x^3$ and $x$ *)\n(* begin snippet K31 *)\n\nExample k3_1 : Kchain := fun A (k:Kkont A) (x:A) =>\n  x2 <--- x times x ;\n  x3 <--- x2 times x ;\n  k x3 x.\n\n(* end snippet K31 *)\n\n(** Kchain for $x^37$ and $x^3$ *)\n\n(* begin snippet K73 *)\nExample k7_3 : Kchain := fun A (k:Kkont A)   (x:A) =>\n  x2 <--- x times x;\n  x3 <--- x2 times x ;\n  x6 <--- x3 times x3 ;\n  x7 <--- x6 times x ;\n  k  x7 x3.\n(* end snippet K73 *)\n\n\n(** The Definition of correct chains and proper chains and \n  continuations are adapted to Kchains *)\n\n(* begin snippet KkontDefs *)\nDefinition Kkont_proper `(M : @EMonoid A op E_one E_equiv)\n           (k : Kkont A) :=\n Proper (equiv ==> equiv ==> computation_equiv op E_equiv) k . \n\nDefinition Kkont_equiv  `(M : @EMonoid A op E_one E_equiv)\n           (k k': Kkont A )  := \n forall x y : A, x == y -> forall z t, z == t -> \n         computation_equiv op E_equiv   (k  x z) (k' y t).\n(* end snippet KkontDefs *)\n\n\n(** A Kchain is correct with respect to two exponents $n$ and $p$ \n  if it computes $a ^ n$ and $a ^ p$ for every $a$ *)\n\nAbout EMonoid.\n\n(* begin snippet KchainCorrectDef *)\nDefinition Kchain_correct_nat (n p : nat) (kc : Kchain) :=\n  forall  (A : Type) (op : Mult_op A) (E_one : A) (E_equiv : Equiv A)\n          (M : EMonoid op E_one E_equiv)\n          (k : Kkont A),\n    Kkont_proper M k ->\n    forall  (a : A) ,\n      computation_execute op (kc  A k  a) ==\n      computation_execute op (k  (a ^ n) (a ^ p)).\n\n\nDefinition Kchain_correct (n p : positive) (kc : Kchain) :=\n  Kchain_correct_nat  (Pos.to_nat n) (Pos.to_nat p) kc.\n\nClass Kchain_proper (kc : Kchain) :=\nKchain_proper_prf : \n forall `(M : @EMonoid A op E_one E_equiv) k k' x y ,\n   Kkont_proper M k ->\n   Kkont_proper M k' -> \n   Kkont_equiv M k k' ->\n   E_equiv x y ->\n   computation_equiv op E_equiv (kc A k x) (kc A k' y).\n(* end snippet KchainCorrectDef *)\n\n(* begin snippet K73Ok:: no-out *)\n#[ global ] Instance k7_3_proper : Kchain_proper k7_3.\nProof.\n  intros until M; intros; red; unfold k7_3; cbn;\n  add_op_proper M H3; apply H1;  rewrite H2;   reflexivity. \nQed.\n\nLemma k7_3_correct : Kchain_correct 7 3 k7_3.\nProof.\nintros until M; intros; red; unfold k7_3; simpl.\n  apply H;  monoid_simpl M;  reflexivity.\nQed. \n(* end snippet K73Ok *)\n\n (** conversion between several definitions of correctness *)\n\nLemma Kchain_correct_conv (kc : Kchain) (n p : nat) :\n  0%nat <> n -> 0%nat <> p ->\n  Kchain_correct_nat n p kc ->\n  Kchain_correct (Pos.of_nat n) (Pos.of_nat p) kc.\nProof.\n  red; intros; repeat rewrite Nat2Pos.id; auto.\nQed.\n\n(** ** More chain combinators \n\n  Since we are working with two types of functional chains, we have to define\n  several ways of composing them. Each of these operators is certified to\n preserve correctnes and properness *)\n\n\n(** Conversion of Kchains into Fchains *)\n\n(* begin snippet K2FDef *)\nDefinition K2F (knp : Kchain) : Fchain :=\n  fun A (k:Fkont A) => knp A (fun  y _ => k y).\n(* end snippet K2FDef *)\n\n\nLemma K2F_correct_nat :\n  forall knp n p, Kchain_correct_nat  n p knp ->\n                 Fchain_correct_nat n (K2F knp).\nProof.\n red;intros; unfold K2F;\n apply  (H _ _ _ _ M (fun x y => k x));\n intros x1 y1 H1 x2 y2 H2; apply Hk;  auto.\nQed.\n\n(* begin snippet K2FCorrect:: no-out *)\nLemma K2F_correct :\n  forall kc n p, Kchain_correct n p kc ->\n                 Fchain_correct n (K2F kc).\n(* end snippet K2FCorrect *)\nProof.\n red;intros; unfold K2F, Fchain_correct. \n apply K2F_correct_nat with (Pos.to_nat p);\n apply H.\nQed.\n\n(* begin snippet K2FProper:: no-out *)\n#[ global ] Instance K2F_proper (kc : Kchain)(_ : Kchain_proper kc) :\n  Fchain_proper (K2F kc).\n(* end snippet K2FProper *)\nProof.\n red;intros; unfold K2F;red.  \n apply (H _ _ _ _ M).  \n - red;intros; red;intros.\n   intros x1 y1 Hx1 x2 y2 Hx2; now apply H0.\n - intros x1 y1 Hx1 x2 y2 Hx2; now apply H1.\n - red;intros;now apply H2.\n -  assumption.\nQed. \n\n\n(** \n  Using [kbr] for  computing $x^b$ and $x^r$, then using [Cq] for\n  computing $x^{bq}$, then sending $x^{bq+r}$ and $x^b$ to the continuation\n*)\n\n(* begin snippet KFKDef *)\nDefinition KFK (kbr : Kchain) (fq : Fchain) : Kchain  :=\n  fun A k a =>\n    kbr A  (fun xb xr =>\n              fq A (fun y =>\n                      z <--- y times xr; k z xb) xb) a.\n(* end snippet KFKDef *)\n\n\n(* begin snippet KFFDef *)\nDefinition KFF (kbr : Kchain) (fq : Fchain) : Fchain :=\n  K2F (KFK kbr fq).\n(* end snippet KFFDef *)\n\n(* begin snippet FFKDef *)\nDefinition FFK (fp fq : Fchain) : Kchain :=\n  fun A k a =>  fp A (fun xb  => fq A (fun y => k y xb) xb) a. \n(* end snippet FFKDef *)\n\n(* begin snippet FKDef *)\nDefinition FK (f : Fchain) : Kchain :=\n  fun (A : Type) (k : Kkont A) (a : A) =>\n    f A (fun y => k y a) a.\n(* end snippet FKDef *)\n\n\nExample k17_7 := KFK k7_3 (Fexp2 1).\n\n\n(** In the following section, we prove that the constructions KFK and KFF\n   respect properness and correctness *)\n\nSection KFK_proof.\n Variables b q r: nat.\n Variable kbr : Kchain.\n Variable fq : Fchain.\n Hypothesis Hbr : Kchain_correct_nat b r kbr.\n Hypothesis Hq : Fchain_correct_nat q fq.\n Hypothesis Hbr_prop : Kchain_proper kbr.\n Hypothesis Hq_prop : Fchain_proper fq.\n\n Lemma KFK_correct_nat : Kchain_correct_nat (b * q + r)%nat b (KFK kbr fq).\n Proof.\n  intros until M; intros k H a;  unfold KFK;   simpl.\n  add_op_proper M Hop.\n  \n  (** simplifying the hypotheses *)\n  specialize (Hq _ _ _ _ M).\n  specialize (Hbr_prop _ _ _ _ M).\n  specialize (Hq_prop _ _ _ _ M).\n  specialize (Hbr _ _ _ _ M (fun xb xr : A =>\n          fq A (fun y : A => z <--- y times xr; k z xb) xb)).\n\n  assert\n    (Kkont_proper M\n                  (fun xb xr : A =>\n                     fq A\n                        (fun y : A => z <--- y times xr; k z xb)\n                        xb)).\n - intros x y Hxy z t Hzt;simpl; red;simpl.\n   assert\n     (forall X Y,\n        X == Y ->\n        computation_equiv op E_equiv\n                          ((fun y0 : A =>\n                              z0 <--- y0 times z; k z0 x) X)\n                               ((fun y0 : A =>\n                                   z0 <--- y0 times t; k z0 y) Y)).\n   +  intros;  simpl;  red;  simpl;   apply H; auto.\n      rewrite H0, Hzt; reflexivity.\n   +  specialize (H0 x y Hxy); red in H0; simpl; simpl in H0.\n      assert (Proper (computation_equiv op E_equiv  ==> equiv)\n                     (computation_execute op)).\n     *  intros X Y HXY; red in HXY; auto.\n     *   apply H1; red;apply Hq_prop.\n        red;intros;simpl;red;simpl; intros x1 y1 Hx1;  apply H.\n        rewrite Hzt, Hx1;reflexivity. \n        reflexivity.\n        intros x1 y1 Hx1 ;apply H.\n        rewrite Hx1;reflexivity. \n        reflexivity.\n        intros x1 y1 Hx1;simpl;red;simpl.\n        apply H.\n        rewrite Hx1, Hzt; reflexivity.\n        assumption.\n        assumption.\n   -  specialize (Hbr H0 a); rewrite Hbr.\n      specialize (Hq\n                    (fun y : A =>\n                       z <--- y times a ^ r; k z (a ^ b))).\n      assert ( Fkont_proper M\n                            (fun y : A =>\n                               z <--- y times a ^ r; k z (a ^ b))).\n   +  red; intros  x y Hxy; red; simpl.\n       apply H.\n       rewrite Hxy;reflexivity.\n       reflexivity. \n   + rewrite  (Hq  H1);simpl;apply H.\n     monoid_simpl M.\n     rewrite  (power_of_power M a b q).\n     rewrite (Nat.mul_comm q b). \n     rewrite power_of_plus; reflexivity.\n     reflexivity.\nQed.\n\n\n Lemma KFF_correct_nat : Fchain_correct_nat (b * q + r)%nat (KFF kbr fq).\n Proof.\n   apply K2F_correct_nat with b;  apply KFK_correct_nat.\n Qed.\n\nLemma KFK_proper : Kchain_proper (KFK kbr fq).\n Proof.\n   intros until M; intros k k' x y Hk Hk' ;  unfold KFK;   simpl.\n   add_op_proper M Hop.\n   specialize (Hbr_prop _ _ _ _ M).\n   specialize (Hq_prop _ _ _ _ M).\n    red; simpl; intros; apply Hbr_prop;auto.\n    - intros  x1 y1 Hx1 x2 y2 Hx2; apply Hq_prop;auto.\n      + red; intros;simpl; intros x' y' H'; red;simpl; apply Hk.\n        rewrite H';reflexivity.\n        reflexivity.\n      +  intros x' y' H'; red;simpl; apply Hk.\n         rewrite H';reflexivity.\n         reflexivity. \n      + intros y0 y3 H3;red;simpl; apply Hk.\n        rewrite H3,Hx2;reflexivity.\n        assumption.\n    -  red;intros;intros u v Huv w t Hwt.\n       apply Hq_prop;auto.\n       + intros X Y HXY;red;simpl; apply Hk'.\n         * rewrite HXY;reflexivity.\n         * reflexivity.\n       + intros X Y HXY;red;simpl; apply Hk'.\n         * rewrite HXY;reflexivity.\n         * reflexivity.\n       + red;intros;red;simpl; apply Hk';auto.\n         rewrite H1, Hwt; reflexivity.\n    -  red;intros;apply Hq_prop;auto.\n       + intros X Y HXY;red;simpl;  apply Hk.\n         * rewrite HXY;reflexivity.\n         * reflexivity. \n       + intros X Y HXY;red;simpl;  apply Hk'.\n         * rewrite HXY;reflexivity.\n         * reflexivity. \n       + red;intros;red;simpl;  apply H; auto.\n         * rewrite H2, H3;reflexivity. \nQed.\n\n#[global] Instance KFF_proper : Fchain_proper (KFF kbr fq).\n Proof.\n   intros until M; intros k k' Hk Hk' H x y Hxy;\n   unfold KFF;   simpl.\n   add_op_proper M Hop.\n   specialize (Hbr_prop _ _ _ _ M).\n   specialize (Hq_prop _ _ _ _ M).\n    red; simpl; intros; apply Hbr_prop;auto.\n    - intros  x1 y1 Hx1 x2 y2 Hx2; apply Hq_prop;auto.\n      + red; intros;simpl; intros x' y' H'; red;simpl.  apply Hk.\n        rewrite H';reflexivity.\n      +   intros x' y' H'; red;simpl; apply Hk.\n         rewrite H';reflexivity.\n      +  intros y0 y3 H3;red;simpl; apply Hk.\n        rewrite H3,Hx2;reflexivity.\n    -  red;intros;intros u v Huv w t Hwt.\n       apply Hq_prop;auto.\n       + intros X Y HXY;red;simpl; apply Hk'.\n         * rewrite HXY;reflexivity.\n       + intros X Y HXY;red;simpl; apply Hk'.\n         * rewrite HXY;reflexivity.\n       + red;intros;red;simpl; apply Hk';auto.\n         rewrite H0, Hwt; reflexivity.\n    -  red;intros;apply Hq_prop;auto.\n       + intros X Y HXY;red;simpl;  apply Hk.\n         * rewrite HXY;reflexivity.\n       + intros X Y HXY;red;simpl;  apply Hk'.\n         * rewrite HXY;reflexivity.\n       + red;intros;red;simpl;  apply H; auto.\n         * rewrite H2, H1;reflexivity. \nQed.\n\nEnd KFK_proof.  \n(* begin snippet KFKCorrect:: no-out *)\nLemma KFK_correct :\n  forall (b q r : positive) (kbr : Kchain) (fq : Fchain),\n    Kchain_correct  b r kbr ->\n    Fchain_correct q fq ->\n    Kchain_proper kbr ->\n    Fchain_proper fq ->\n    Kchain_correct  (b * q + r) b (KFK kbr fq).\n(* end snippet KFKCorrect *)\nProof.\n red; intros; rewrite Pos2Nat.inj_add, Pos2Nat.inj_mul;\n apply KFK_correct_nat;assumption.\nQed.\n\n(* begin snippet KFKProper *)\nCheck  KFK_proper.\n(* end snippet KFKProper *)\n\n(* begin snippet KFFProper *)\nCheck  KFK_proper.\n(* end snippet KFFProper *)\n\n\n(* begin snippet KFFCorrect:: no-out *)\nLemma KFF_correct :\n  forall (b q r : positive) (kbr : Kchain) (fq : Fchain),\n    Kchain_correct b r kbr  ->\n    Fchain_correct q fq ->\n    Kchain_proper kbr ->\n    Fchain_proper fq ->\n    Fchain_correct (b * q + r) (KFF kbr fq).\n(* end snippet KFFCorrect *)\nProof.\n  red; intros;  rewrite Pos2Nat.inj_add, Pos2Nat.inj_mul;\n  apply KFF_correct_nat;assumption.\nQed.\n\n\nLemma FFK_correct_nat :\n  forall (p q  : nat) (fp fq : Fchain),\n    Fchain_correct_nat p fp  ->\n    Fchain_correct_nat q fq ->\n    Fchain_proper fp ->\n    Fchain_proper fq -> Kchain_correct_nat  (p * q) p (FFK fp fq).\nProof.\nintros.   \nred;intros.\n unfold FFK;   simpl.\n  add_op_proper M Hop.\n  \n  (** simplifying the hypotheses *)\n  specialize (H _ _ _ _ M).\n  specialize (H0 _ _ _ _ M).  \n  specialize (H1 _ _ _ _ M).\n  specialize (H2 _ _ _ _ M).\n  specialize (H (fun xb : A => fq A (fun y : A => k y xb) xb)).\n  assert (Fkont_proper M\n                        (fun xb  : A => fq A\n                                             (fun y : A =>  k y xb)\n                                             xb)).\n - intros x y Hxy ;simpl; red;simpl.\n   apply H2.\n   +   intros  u v Huv; apply H3; (assumption || reflexivity).  \n   + intros  u v Huv; apply H3; (assumption || reflexivity). \n   + intros  u v Huv; apply H3; (assumption || reflexivity). \n   + assumption. \n\n -  specialize (H  H4 a); rewrite H.\n    specialize (H0  (fun y => k y (a ^ p))).\n    assert (Fkont_proper M (fun y : A => k y (a ^ p))).\n      +  red; intros  x y Hxy; red; simpl;  apply H3;\n         (assumption || reflexivity). \n      + rewrite (H0 H5);  apply H3; [| reflexivity].\n        rewrite  (power_of_power M a p q), (Nat.mul_comm q p);\n       reflexivity.\nQed.\n\n(* begin snippet FFKCorrect:: no-out *)\nLemma FFK_correct  (p q  : positive) (fp fq : Fchain):\n    Fchain_correct p fp  ->\n    Fchain_correct q fq ->\n    Fchain_proper fp ->\n    Fchain_proper fq ->\n    Kchain_correct  (p * q ) p (FFK fp fq).\n(* end snippet FFKCorrect *)\nProof.\n intros;red; rewrite  Pos2Nat.inj_mul; now apply FFK_correct_nat. \nQed.\n\n(* begin snippet FFKProper:: no-out *)\n#[ global ] Instance FFK_proper \n         (fp fq : Fchain)\n         (_ :   Fchain_proper fp)\n         (_ :  Fchain_proper fq)\n  :  Kchain_proper (FFK fp fq).\n(* end snippet FFKProper *)\nProof.\n red;intros;\n specialize (H _ _ _ _ M); specialize (H0 _ _ _ _ M).\n  add_op_proper M Hop; unfold FFK;simpl.\n  red; simpl; intros;  apply H;auto.\n - intros  x1 y1 Hx1 ; apply H0;auto.\n      +  intros x' y' H'; red;simpl;  apply H1;\n        (assumption || reflexivity). \n      +   intros x' y' H'; red;simpl; apply H1;\n          (assumption || reflexivity).\n      +  intros y0 y3 H5;red;simpl; apply H1; auto.\n -  intros u v Huv ;  apply H0;auto.\n    + intros X Y HXY;red;simpl; apply H2;\n      (assumption || reflexivity).\n    + intros X Y HXY;red;simpl; apply H2;\n      (assumption || reflexivity).\n    + red;intros;red;simpl; apply H2;auto.\n -  red;intros; apply H0;auto.\n    + intros X Y HXY;red;simpl;  apply H1;\n      (assumption || reflexivity).\n    + intros X Y HXY;red;simpl;  apply H2;\n      (assumption || reflexivity).\n    + red;intros;red;simpl; apply H3; auto.\nQed.\n\n\n\nLemma FK_correct : forall (p: positive) (Fp : Fchain),\n                     Fchain_correct  p Fp ->\n                     Fchain_proper Fp ->\n                     Kchain_correct  p 1 (FK Fp).\nProof.\n  intros;red; unfold FK;  red; intros until M;intros k H1 a.\n  specialize (H _ _ _ _ M (fun y : A => k y a)).\n  specialize (H0 _ _ _ _ M);\n  add_op_proper M Hop.\n  assert (Fkont_proper M (fun y : A => k y a)).\n -   intros x y Hxy; apply H1; (assumption || reflexivity).\n -  specialize (H H2 a);rewrite H;apply H1.\n    + reflexivity.\n    + generalize (power_eq3 a);simpl;now symmetry.\nQed.\n\n#[ global ] Instance  FK_proper  (Fp : Fchain) (_ : Fchain_proper Fp):\n  Kchain_proper (FK Fp).\nProof.\n  unfold FK; intros until M; intros k k' x y  H0 H1 H2 H3. \n  apply (H _ _ _ _ M).  \n  -  intros u v Huv;  apply H0; (assumption || reflexivity). \n  - intros u v Huv;  apply H1; (assumption || reflexivity).     \n  - intros  u v Huv; apply H2; auto.\n  -  assumption.\nQed.\n\n(* begin snippet HintKchains *)\n#[global] Hint Resolve KFF_correct KFF_proper KFK_correct KFK_proper : chains.\n(* end snippet HintKchains *)\n\nLemma k3_1_correct : Kchain_correct 3 1 k3_1.\nProof.\n  intros until M;intros k H a.\n  unfold k3_1; simpl;  apply H; monoid_simpl M;reflexivity.\nQed.\n\nLemma k3_1_proper : Kchain_proper k3_1.\nProof.\n  intros until M; intros k k' x y H H0 H1 H2.\n  unfold k3_1;simpl.\n  apply H1;auto.\n  add_op_proper M H3; rewrite H2; reflexivity.\nQed.\n\n#[global] Hint Resolve k3_1_correct k3_1_proper : chains.\n\n(** an example of correct chain construction  *)\n\n(* begin snippet F87 *)\n\nDefinition F87 :=\n let k7_3 :=  KFK k3_1 (Fexp2 1) in\n let k10_7 := KFK k7_3 F1 in\n KFF k10_7 (Fexp2 3).\n\nCompute the_exponent (F2C F87).\n(* end snippet F87 *)\n\n(* begin snippet F87Correct:: no-out *)\n\nLemma OK87 : Fchain_correct 87 F87.\nProof.\n unfold F87; change 87 with (10 * (2 ^ 3) + 7)%positive.\n apply KFF_correct;auto with chains.\n change 10 with (7 * 1 + 3);\n   apply KFK_correct;auto with chains.\n change 7 with (3 * 2 ^ 1 + 1)%positive;\n   apply KFK_correct;auto with chains.\nQed.\n(* end snippet F87Correct *)\n\nLtac compute_chain ch := \n   let X := fresh \"x\" in \n   let Y := fresh \"y\" in\n   let X := constr:(ch) in \n   let Y := (eval vm_compute in  X) \n   in exact Y.\n\n\nDefinition C87' := ltac:( compute_chain C87 ).\n\n\nPrint C87'.\n\nLemma PF87:  parametric C87'.\nProof. parametric_tac. Qed.\n\n(** *** Automatic generation of correct euclidean chains \n\nWe want to define a function that builds a correct chain\nfor any positive exponent, using the previously defined\nand certified composition operators : Fcompose, KFK, etc.\n\nObviously, we have to define total mutually recursive functions:\n\n - A function that builds an Fchain for any positive exponent p\n - A function that builds a Kchain for any pair of exponents\n   (n,p) where $1<p<n$\n\n In Coq, various ways of building functions are available:\n  - Structural [mutual] recursion with [Fixpoint]\n  - Using [Program Fixpoint]  \n  - Using [Function]\n\n For simplicity's sake, we chosed to avoid dependent elimination\n and used [Function] with a decreasing measure.\n For this purpose, we define a single data-type for associated with\n the generation of F- and K-chains.\n\nFor specifying the computation of a Kchain for $n$ and $p$\nwhere $p<n$, we use the pair of positive numbers $(p,n-p)$,\nthus avoiding to propagate the constraint $p<n$ in \nour definitions.\n*)\n\n(* begin snippet signature *)\n\nInductive signature : Type :=\n| gen_F (n:positive) (** Fchain for the exponent n *)\n| gen_K (p d: positive) (** Kchain for the exponents p+d  and p *). \n(* end snippet signature *)\n\n\n\n(** Unifying  statements about chain generation *)\n\n(* begin snippet dependentlyTypedFuns *)\n\nDefinition signature_exponent (s:signature) : positive :=\n match s with \n| gen_F n => n \n| gen_K p d  =>  p + d\nend.\n\nDefinition kont_type (s: signature)(A:Type) : Type :=\nmatch s with \n| gen_F _  => Fkont A \n| gen_K _ _   => Kkont A\nend.\n\nDefinition chain_type (s: signature) : Type :=\n match s with \n| gen_F _   => Fchain\n|  gen_K _ _  => Kchain\nend.\n\nDefinition correctness_statement (s: signature) : \nchain_type s -> Prop :=\nmatch s  with\n  | gen_F p => fun ch => Fchain_correct p ch\n  | gen_K p d   => fun ch => Kchain_correct  (p + d) p ch\nend.\n\n\nDefinition proper_statement (s: signature) : \nchain_type s -> Prop :=\nmatch s  with\n  | gen_F _ => fun ch => Fchain_proper ch \n  | gen_K _ _   => fun ch => Kchain_proper ch \nend.\n\n\n(** ** Full correctness *)\n\nDefinition  OK (s: signature) \n  := fun c: chain_type s => correctness_statement s c /\\\n                            proper_statement s c.\n\n(* end snippet dependentlyTypedFuns *)\n\n#[global] Hint Resolve pos_gt_3 : chains.\n\n(* begin snippet GammaContext *)\nSection Gamma.\nVariable gamma: positive -> positive.\nContext (Hgamma : Strategy gamma).\n\nDefinition signature_measure (s : signature) : nat :=\nmatch s with\n  | gen_F n => 2 * Pos.to_nat n \n  | gen_K  p d => 2 * Pos.to_nat (p + d) +1\nend.\n(* end snippet GammaContext *)\n\n(* Proof obligations for chain generation (generated by Function) *)\n(* These lemmas are also applied in AM *)\n\n Lemma PO1 :forall (s : signature) (i : positive),\n  s = gen_F i ->\n  forall anonymous : i <> 1,\n  pos_eq_dec i 1 = right anonymous ->\n  forall anonymous0 : i <> 3,\n  pos_eq_dec i 3 = right anonymous0 ->\n  exact_log2 i = None ->\n  forall q r : N,\n  r = 0%N ->\n  N.pos_div_eucl i (N.pos (gamma i)) = (q, 0%N) ->\n  (signature_measure (gen_F (N2pos q)) < signature_measure (gen_F i))%nat.\n\n   intros; unfold signature_measure.\n     generalize (N.pos_div_eucl_spec i (N.pos (gamma i))).\n      rewrite H4; N2pos_destruct q p. (*destruct q; [discriminate | ].*)\n\n    subst r; repeat rewrite  N.add_0_r.\n    injection 1.  intro H5 ;rewrite H5.\n    gamma_bounds gamma i H12 H14.\n    assert (H13 : p <> 1).\n \n   +  intro Hp ; subst p.  simpl in H5.\n       destruct (Pos.lt_irrefl i).\n       now rewrite H5 at 1.\n\n   +  assert (H11 := pos_lt_mul p (gamma i) H12).\n      rewrite Pos2Nat.inj_lt in  H11.\n      rewrite  Pos2Nat.inj_mul in *;  lia.\n      Qed. \n\n Lemma PO2 :  forall (s : signature) (i : positive),\n     s = gen_F i ->\n     forall anonymous : i <> 1,\n       pos_eq_dec i 1 = right anonymous ->\n       forall anonymous0 : i <> 3,\n         pos_eq_dec i 3 = right anonymous0 ->\n         exact_log2 i = None ->\n         forall q r : N,\n           r = 0%N ->\n           N.pos_div_eucl i (N.pos (gamma i)) = (q, 0%N) ->\n           (signature_measure (gen_F (gamma i)) < signature_measure (gen_F i))%nat.\n Proof.\n   intros; unfold signature_measure.\n   rewrite <- Nat.mul_lt_mono_pos_l;\n     [ apply Pos2Nat.inj_lt; apply gamma_lt|] ;  auto with chains.\n Qed.\n\n\n Lemma PO3 :  forall (s : signature) (i : positive),\n  s = gen_F i ->\n  forall anonymous : i <> 1,\n  pos_eq_dec i 1 = right anonymous ->\n  forall anonymous0 : i <> 3,\n  pos_eq_dec i 3 = right anonymous0 ->\n  exact_log2 i = None ->\n  forall (q r : N) (p : positive),\n  r = N.pos p ->\n  N.pos_div_eucl i (N.pos (gamma i)) = (q, N.pos p) ->\n  (signature_measure (gen_F (N2pos q)) < signature_measure (gen_F i))%nat.\n Proof.\n    intros; unfold signature_measure.\n    gamma_bounds gamma i H12 H14.  quotient_small H4  H5.\n    rewrite <- Nat.mul_lt_mono_pos_l ; [ | auto with arith chains].\n    apply Pos2Nat.inj_lt.\n      destruct q; simpl in *.\n      transitivity (gamma i);auto.\n      now rewrite pos2N_inj_lt.\n      Qed.\n\n\n Lemma PO4 : forall (s : signature) (i : positive),\n  s = gen_F i ->\n  forall anonymous : i <> 1,\n  pos_eq_dec i 1 = right anonymous ->\n  forall anonymous0 : i <> 3,\n  pos_eq_dec i 3 = right anonymous0 ->\n  exact_log2 i = None ->\n  forall (q r : N) (p : positive),\n  r = N.pos p ->\n  N.pos_div_eucl i (N.pos (gamma i)) = (q, N.pos p) ->\n  (signature_measure (gen_K (N2pos (N.pos p)) (gamma i - N2pos (N.pos p))) <\n   signature_measure (gen_F i))%nat.\nintros; unfold signature_measure.\n    apply lt_S_2i;  rewrite Pplus_minus. \n    gamma_bounds gamma i H5 H6.\n    +  apply Pos2Nat.inj_lt;  auto.\n    +  rest_small H4 H5; now  apply Pos.lt_gt.\nQed.\n\n Lemma PO6: forall (s : signature) (p d : positive),\n  s = gen_K p d ->\n  forall anonymous : p <> 1,\n  pos_eq_dec p 1 = right anonymous ->\n  forall q r : N,\n  r = 0%N ->\n  N.pos_div_eucl (p + d) (N.pos p) = (q, 0%N) ->\n  (signature_measure (gen_F (N2pos q)) < signature_measure (gen_K p d))%nat.\nProof.\nintros; unfold signature_measure.\n    quotient_small H2 H5.\n    destruct p; (discriminate || reflexivity).\n    N2pos_destruct q q.\n    +       destruct (pos_div_eucl_quotient_pos _ _ _ _ H2);auto with chains.\n           rewrite pos2N_inj_add; apply N.le_add_r.\n    +  simpl; rewrite <- pos2N_inj_lt in H5;\n       rewrite Pos2Nat.inj_lt in H5.\n       lia.\nQed.       \n\nLemma PO8 :forall (s : signature) (p d : positive),\n  s = gen_K p d ->\n  forall anonymous : p <> 1,\n  pos_eq_dec p 1 = right anonymous ->\n  forall (q r : N) (p0 : positive),\n  r = N.pos p0 ->\n  N.pos_div_eucl (p + d) (N.pos p) = (q, N.pos p0) ->\n  (signature_measure (gen_F (N2pos q)) < signature_measure (gen_K p d))%nat.\nProof.\n  intros; unfold signature_measure.\n     assert (N2pos q < p+d)%positive.\n    quotient_small H2 H5.\n    generalize anonymous; \n      destruct p; simpl; try reflexivity.\n    now destruct 1.\n    generalize (pos_div_eucl_quotient_pos  _ _ _ _ H2).\n    intros H6;  destruct q;auto.\n    destruct H6;auto with chains.\n    rewrite pos2N_inj_add;  apply N.le_add_r;auto with chains.\n    + revert H3; pos2nat_inj_tac; intros;lia.\nQed.\n\n Lemma PO9 :forall (s : signature) (p d : positive),\n  s = gen_K p d ->\n  forall anonymous : p <> 1,\n  pos_eq_dec p 1 = right anonymous ->\n  forall (q r : N) (p0 : positive),\n  r = N.pos p0 ->\n  N.pos_div_eucl (p + d) (N.pos p) = (q, N.pos p0) ->\n  (signature_measure (gen_K (N2pos (N.pos p0)) (p - N2pos (N.pos p0))) <\n   signature_measure (gen_K p d))%nat.\nProof.\nintros; unfold signature_measure.\n    apply Nat.add_lt_mono_r.  \n    rewrite <- (Nat.mul_lt_mono_pos_l (S _)); [| auto with arith].\n\n    rewrite Pplus_minus.\n    +  apply Pos2Nat.inj_lt; apply Pos.lt_add_diag_r; cbn.\n    +  generalize (N.pos_div_eucl_remainder (p + d) (N.pos p) );\n      rewrite H2; cbn; unfold N.lt ; intro H5; red.\n       simpl in H5; now rewrite Pos.compare_antisym, H5.\nQed.\n(* begin snippet chainGen:: no-out *)\nFunction chain_gen  (s:signature) {measure signature_measure}\n:  chain_type s :=\n  match s  return chain_type s with\n    | gen_F i =>\n      if pos_eq_dec i 1 then F1 else\n        if pos_eq_dec i 3\n        then F3\n        else \n          match exact_log2 i with\n              Some p => Fexp2 p\n            | _ =>\n              match N.pos_div_eucl i (Npos (gamma i))\n              with\n                | (q, 0%N) => \n                  Fcompose  (chain_gen (gen_F (gamma i)))\n                            (chain_gen (gen_F (N2pos q)))\n                | (q,r)  => KFF (chain_gen\n                                   (gen_K (N2pos r)\n                                          (gamma i - N2pos r)))\n                                (chain_gen (gen_F (N2pos q)))\n              end end\n    | gen_K p d =>\n      if pos_eq_dec p 1 then FK (chain_gen (gen_F (1 + d)))\n      else\n        match N.pos_div_eucl (p + d)  (Npos p) with\n          | (q, 0%N) => FFK   (chain_gen (gen_F p))\n                              (chain_gen (gen_F (N2pos q)))\n          | (q,r)  => KFK (chain_gen (gen_K (N2pos r)\n                                            (p - N2pos r)))\n                          (chain_gen (gen_F (N2pos q)))\n        end\n  end.\n(* 9 Proof Obligations generated *)\n(* end snippet chainGen *)\nProof.\n  - intros; eapply PO1; eauto. \n  - intros; eapply PO2; eauto. \n  - intros; eapply PO3; eauto.\n  - intros; eapply PO4; eauto.\n  - intros; unfold signature_measure; subst p;  lia.\n  - intros; eapply PO6; eauto.\n  - intros; unfold signature_measure; pos2nat_inj_tac; lia.\n  - intros; eapply PO8; eauto.\n  - intros; eapply PO9; eauto.\nDefined.\n\n(* begin snippet makeChain *)\nDefinition make_chain (n:positive) : chain :=\n F2C (chain_gen (gen_F n)).\n(* end snippet makeChain *)\n\n(* begin snippet chainGenOK:: no-out *)\nLemma chain_gen_OK : forall s:signature,\n    OK s (chain_gen  s).\nProof.\n  intro s; functional induction chain_gen s.\n  (*  A lot of arithmetic sub-proofs ... *)\n  (* end snippet chainGenOK *) \n  - split; [apply F1_correct | apply F1_proper].\n\n  - split; [apply F3_correct | apply F3_proper].\n\n  - generalize (exact_log2_spec _ _ e2);intro; subst i; split;\n      [apply Fexp2_correct | apply Fexp2_proper].\n\n  -  destruct IHc, IHc0.\n     generalize (N_pos_div_eucl_divides _ _ _ e3); intro eq_i.\n     split.\n     + cbn.   rewrite <- eq_i at 1 ; apply Fcompose_correct;auto.\n     +  pattern i at 1 ; rewrite <- eq_i at 1; apply Fcompose_proper;auto.\n\n\n  -  pattern i at 1;\n       replace i with (gamma i * (N2pos q) + N2pos r).\n     + destruct IHc, IHc0;split.\n       *  apply KFF_correct;auto.\n          simpl; simpl in H.\n          replace (gamma i) with  \n              (N2pos r + (gamma i - N2pos r)) at 1.\n          apply H.\n          rewrite Pplus_minus;auto with chains.\n          apply Pos.lt_gt;   rewrite  N2pos_lt_switch2. \n          generalize \n            (N.pos_div_eucl_remainder i (N.pos (gamma i) )); \n            rewrite e3;  simpl;auto with chains.\n          destruct r; [ contradiction | auto with chains].\n       *  apply KFF_proper;auto with chains.\n\n     + apply  N_pos_div_eucl_rest; auto with chains.\n       destruct r;try contradiction; auto with chains. \n       apply (div_gamma_pos   _ _ _ e3); auto with chains.\n       apply pos_gt_3;auto with chains.\n       destruct (exact_log2 i); [contradiction | reflexivity].\n\n\n  - destruct IHc; split.\n    +   apply FK_correct; auto with chains.\n    +  apply FK_proper; auto with chains.\n       \n\n  - destruct IHc, IHc0;split.\n    +   red; replace (p + d)%positive with (p * N2pos q)%positive.\n        * apply FFK_correct; auto with chains.\n        *  generalize  (N.pos_div_eucl_spec   (p + d) (N.pos p));\n             rewrite e1;    rewrite N.add_0_r ; intro  H3;\n               case_eq (q * N.pos p)%N.\n           intro H4;  rewrite H4 in H3 ; discriminate.\n           intros p0 H4; rewrite H4 in H3; injection H3;\n             intro H5;   rewrite H5.\n           N2pos_destruct q q.\n           injection H4;auto with chains.\n           rewrite  Pos.mul_comm;  auto with chains.\n    +   apply FFK_proper;auto with chains.\n\n  -   destruct IHc, IHc0; split.\n      + red; replace (p+d) with (p * N2pos q + N2pos r).\n        * apply KFK_correct;auto with chains.\n          red in H;   replace (N2pos r + (p - N2pos r))%positive with p in H.\n          apply H.  \n          rewrite Pplus_minus;  auto.\n          generalize  (N.pos_div_eucl_remainder (p + d) (N.pos p));\n            rewrite e1; cbn;  intro H3.\n          apply Pos.lt_gt;  rewrite  N2pos_lt_switch2;auto with chains.\n          destruct r; [contradiction | auto with chains].\n\n        *   generalize  (N.pos_div_eucl_spec   (p + d) (N.pos p));\n              rewrite e1; intros H3; clear H H0 H1 H2.\n            case_eq q.\n            {intro;   generalize (pos_div_eucl_quotient_pos _ _ _ _ e1).\n             destruct 1;auto with chains.\n             rewrite pos2N_inj_add;  apply N.le_add_r.\n            }\n            {\n              intros p0 Hp0;subst q; cbn; destruct r; [ contradiction | ].\n              simpl;  simpl in H3;  injection H3.\n              rewrite Pos.mul_comm; auto with chains.\n            }\n      +   apply KFK_proper;  auto with chains.\nQed. \n\n(* begin snippet makeChainCorrect:: no-out *)\nTheorem make_chain_correct : forall p, chain_correct p (make_chain p).\nProof.\n  intro p; destruct (chain_gen_OK (gen_F p)).\n  unfold make_chain; apply F2C_correct; apply H.\nQed.\n\nEnd Gamma.\n(* end snippet makeChainCorrect *)\nArguments make_chain gamma {_} _ _ _ .\n\n(* begin snippet C87Dicho *)\nCompute the_exponent (make_chain  dicho 87).\n(* end snippet C87Dicho *)\n\n(** cf Coq workshop 2014 by Jason Grosss *)\n\nModule  Examples.\n\nImport Int31.\nCompute cpower (make_chain dicho) 10 12.\nCompute cpower (make_chain dicho) 87 12.\n\nDefinition fast_int31_power (x :positive)(n:N) : Z :=\n  Int31.phi (cpower (make_chain dicho) n (snd (positive_to_int31 x))).\n\nDefinition slow_int31_power (x :positive)(n:N) : Z :=\n  Int31.phi (power (snd (positive_to_int31 x)) (N.to_nat n) ).\n\nDefinition binary_int31_power (x :positive)(n:N) : Z :=\nInt31.phi (N_bpow (snd (positive_to_int31 x)) n ).\n\n\n\nAbout make_chain.\n\n(** long computations ... *)\n(**\nDefinition big_chain := ltac:(compute_chain  (make_chain dicho 6145319)).\n\nPrint big_chain.\n\n(*\nbig_chain = \nfun (A : Type) (x : A) =>\nx0 <--- x times x;\nx1 <--- x0 times x0;\nx2 <--- x1 times x1;\nx3 <--- x2 times x1;\nx4 <--- x3 times x3;\nx5 <--- x4 times x;\nx6 <--- x5 times x5;\nx7 <--- x6 times x6;\nx8 <--- x7 times x1;\nx9 <--- x8 times x5;\nx10 <--- x9 times x8;\nx11 <--- x10 times x9;\nx12 <--- x11 times x11;\nx13 <--- x12 times x11;\nx14 <--- x13 times x10;\nx15 <--- x14 times x14;\nx16 <--- x15 times x11;\nx17 <--- x16 times x16;\nx18 <--- x17 times x17;\nx19 <--- x18 times x18;\nx20 <--- x19 times x19;\nx21 <--- x20 times x20;\nx22 <--- x21 times x21;\nx23 <--- x22 times x22;\nx24 <--- x23 times x23;\nx25 <--- x24 times x24;\nx26 <--- x25 times x25;\nx27 <--- x26 times x26; x28 <--- x27 times x14; Return x28\n     : forall A : Type, A -> computation\n\nArguments big_chain _%type_scope\n *)\n\n\n\n\n\n\nRemark RM : (1 < 56789)%N. Proof. reflexivity. Qed.\n\nDefinition M := Nmod_Monoid _ RM.\n\nDefinition exp56789 x := chain_apply big_chain (M:=M) x.\n\n\n\nTime Compute chain_apply big_chain (M:=M) 13%N.\n\n\nEval cbv iota  match delta [big_chain chain_apply computation_eval  ]  zeta beta in  fun x => chain_apply  big_chain (M:=M) x.\n\n\nDefinition C87' := ltac:( compute_chain C87 ).\n\n\nPrint big_chain.\nTime   Compute  Int31.phi\n   (chain_apply big_chain (snd (positive_to_int31  67777))) .\n\n\nCompute  Int31.phi (chain_apply big_chain (snd (positive_to_int31  67777))) .\n\nCompute chain_length  big_chain.\n\n\n\n\n\nGoal parametric (make_chain dicho 45319).\nTime parametric_tac.\nQed.\n\n\nRemark big_correct :chain_correct 45319 (make_chain dicho 45319).\nTime param_chain_correct.\n(* Finished transaction in 4.054 secs (4.051u,0.s) (successful) *)\nQed.\n\nRemark big_correct' : chain_correct 453 (make_chain dicho 453).\nTime reflection_correct_tac.\nQed.\n\n(*** Too long :-(\nRemark big_correct'' : chain_correct (make_chain 45319) 45319.\nTime reflection_correct_tac.\n\n\nThat's normal. The reflection tactic builds a linear term w.r.t. the exponent !\n\n*)\n\n\nRemark big_correct''' : chain_correct 453 (make_chain dicho 453).\nTime apply make_chain_correct.\n(* Finished transaction in 0. secs (0.u,0.s) (successful)\n*)\nQed.\n\n\nCompute make_chain dicho 87.\n(*\n fun (A : Type) (x : A) =>\n       x0 <--- x times x; (* x^2 *)\n       x1 <--- x0 times x; (* x^3 *)\n       x2 <--- x1 times x1; (* x ^6 *)\n       x3 <--- x2 times x;  (* x ^7 *)\n       x4 <--- x3 times x1; (* x ^10 *)\n       x5 <--- x4 times x4; (* x ^20 *)\n       x6 <--- x5 times x5; (* x ^40 *)\n       x7 <--- x6 times x6; (* x ^80 *)\n       x8 <--- x7 times x3;  (* x ^87 *) \n        Return x8\n     : chain\n *)\n\nCompute make_chain half 87.\n\n(*\n\n    = fun (A : Type) (x : A) =>\n       x0 <--- x times x; (* x ^ 2 *)\n       x1 <--- x0 times x0; (* x ^ 4 *)\n       x2 <--- x1 times x;  (* x ^ 5 *)\n       x3 <--- x2 times x2; (* x ^ 10 *)\n       x4 <--- x3 times x3; (* x ^ 20 *)\n       x5 <--- x4 times x;  (* x ^ 21 *)\n       x6 <--- x5 times x5; (* x ^42 *)\n       x7 <--- x6 times x; (* x ^ 43 *)\n       x8 <--- x7 times x7; (* x ^86 *)\n       x9 <--- x8 times x; (* x ^87 *) \n  Return x9\n     : chain\n *)\n\nCompute make_chain two 87.\n\n(*\nfun (A : Type) (x : A) =>\n       x0 <--- x times x;  (* x ^2 *)\n       x1 <--- x0 times x0; (* x ^ 4 *)\n       x2 <--- x1 times x1; (* x ^ 8 *)\n       x3 <--- x2 times x2; (* x ^ 16 *)\n       x4 <--- x3 times x3; (* x ^ 32 *)\n       x5 <--- x4 times x4; (* x ^ 64 *)\n       x6 <--- x5 times x3; (* x ^ 80 *)\n       x7 <--- x6 times x1; (* x ^ 84 *)\n       x8 <--- x7 times x0; (* x ^ 86 *)  \n       x9 <--- x8 times x; (*  x ^ 87 *) \n     Return x9\n     : chain\n\n *)\n(** \nCompute chain_length (make_chain two 56789).\n(* 25%nat *)\n\nCompute chain_length (make_chain half 56789).\n(* 25%nat *)\n\nCompute chain_length (make_chain dicho 56789).\n(* 21%nat *)\n\nCompute chain_length (make_chain two 3456789).\n(* 33%nat *)\n\n Compute chain_length (make_chain half 3456789).\n(* 33%nat *)\n*)\nCompute chain_length (make_chain dicho 3456789).\n(* 29%nat *)\n\n\n\nEnd Examples.\n\nRequire Import Extraction.\nLocate exp56789.\nExtraction Language OCaml.\nExtraction \"bigmod\" Examples.exp56789.\n\n\n*)\n\nEnd Examples.\nRecursive Extraction cpower.\nRecursive Extraction make_chain.\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/Euclidean_Chains.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.6919039795842689}}
{"text": "(** This file corresponds to [FSetEqProperties.v] in the standard\n   library and provides the same results for the typeclass-based\n   version.\n   *)\n\n(** This module proves many properties of finite sets that\n    are consequences of the axiomatization in [FsetInterface]\n    Contrary to the functor in [FsetProperties] it uses\n    sets operations instead of predicates over sets, i.e.\n    [mem x s=true] instead of [In x s],\n    [equal s s'=true] instead of [Equal s s'], etc. *)\nRequire Import SetInterface SetFacts SetDecide SetProperties.\nRequire Import Bool Zerob Sumbool Omega Structures.DecidableTypeEx.\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nGeneralizable All Variables.\nLocal Open Scope set_scope.\n\nSection BasicProperties.\n(** Some old specifications written with boolean equalities. *)\n  Context `{HF : @FSetSpecs elt Helt F}.\n  Variables s s' s'' : set elt.\n  Variables x y z : elt.\n\n  Lemma mem_eq : x === y -> mem x s = mem y s.\n  Proof.\n    intros; rewrite H; auto.\n  Qed.\n\n  Lemma equal_mem_1 : (forall a, mem a s = mem a s') -> equal s s' = true.\n  Proof.\n    intros; apply equal_1; unfold Equal; intros.\n    do 2 rewrite mem_iff; rewrite H; tauto.\n  Qed.\n\n  Lemma equal_mem_2 : equal s s'=true -> forall a, mem a s=mem a s'.\n  Proof.\n    intros; rewrite (equal_2 H); auto.\n  Qed.\n\n  Lemma subset_mem_1 :\n    (forall a, mem a s=true->mem a s'=true) -> subset s s'=true.\n  Proof.\n    intros; apply subset_1; unfold Subset; intros a.\n    do 2 rewrite mem_iff; auto.\n  Qed.\n\n  Lemma subset_mem_2 :\n    subset s s'=true -> forall a, mem a s=true -> mem a s'=true.\n  Proof.\n    intros H a; do 2 rewrite <- mem_iff; apply subset_2; auto.\n  Qed.\n\n  Lemma empty_mem : mem x empty=false.\n  Proof.\n    intros; rewrite <- not_mem_iff; auto with set.\n    intro abs; contradiction (empty_1 abs).\n  Qed.\n\n  Lemma is_empty_equal_empty : is_empty s = equal s empty.\n  Proof.\n    intros; apply bool_1; split; intros.\n    auto with set.\n    rewrite <- is_empty_iff; auto with set.\n  Qed.\n\n  Lemma choose_mem_1 : choose s=Some x -> mem x s=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma choose_mem_2 : choose s=None -> is_empty s=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma add_mem_1 : mem x (add x s)=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma add_mem_2 : x =/= y -> mem y (add x s)=mem y s.\n  Proof.\n    apply add_neq_b.\n  Qed.\n\n  Lemma remove_mem_1 : mem x (remove x s)=false.\n  Proof.\n    intros; rewrite <- not_mem_iff; auto with set.\n  Qed.\n\n  Lemma remove_mem_2 : x =/= y -> mem y (remove x s)=mem y s.\n  Proof.\n    apply remove_neq_b.\n  Qed.\n\n  Lemma singleton_equal_add : equal (singleton x) (add x empty)=true.\n  Proof.\n    intros; rewrite (singleton_equal_add x); auto with set.\n  Qed.\n\n  Lemma union_mem : mem x (union s s')=mem x s || mem x s'.\n  Proof.\n    apply union_b.\n  Qed.\n\n  Lemma inter_mem : mem x (inter s s')=mem x s && mem x s'.\n  Proof.\n    apply inter_b.\n  Qed.\n\n  Lemma diff_mem : mem x (diff s s')=mem x s && negb (mem x s').\n  Proof.\n    apply diff_b.\n  Qed.\n\n  (** properties of [mem] *)\n\n  Lemma mem_3 : ~In x s -> mem x s=false.\n  Proof.\n    intros; rewrite <- not_mem_iff; auto.\n  Qed.\n\n  Lemma mem_4 : mem x s=false -> ~In x s.\n  Proof.\n    intros; rewrite not_mem_iff; auto.\n  Qed.\n\n  (** Properties of [equal] *)\n\n  Lemma equal_refl : equal s s=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma equal_sym : equal s s'=equal s' s.\n  Proof.\n    intros; apply bool_1; do 2 rewrite <- equal_iff; intuition.\n  Qed.\n\n  Lemma equal_trans : equal s s'=true -> equal s' s''=true -> equal s s''=true.\n  Proof.\n    intros; rewrite (equal_2 H); auto.\n  Qed.\n\n  Lemma equal_equal : equal s s'=true -> equal s s''=equal s' s''.\n  Proof.\n    intros; rewrite (equal_2 H); auto.\n  Qed.\n\n  Lemma equal_cardinal : equal s s'=true -> cardinal s=cardinal s'.\n  Proof.\n    auto with set.\n  Qed.\n\n  (* Properties of [subset] *)\n\n  Lemma subset_refl : subset s s=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma subset_antisym :\n    subset s s'=true -> subset s' s=true -> equal s s'=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma subset_trans :\n    subset s s'=true -> subset s' s''=true -> subset s s''=true.\n  Proof.\n    intros; rewrite <- !subset_iff; intros.\n    apply subset_trans with s'; auto with set.\n  Qed.\n\n  Lemma subset_equal : equal s s'=true -> subset s s'=true.\n  Proof.\n    auto with set.\n  Qed.\n\n(** Properties of [choose] *)\n\n  Lemma choose_mem_3 :\n    is_empty s=false -> {x:elt|choose s=Some x /\\ mem x s=true}.\n  Proof.\n    intros.\n    generalize (@choose_1 _ _ _ _ s) (@choose_2 _ _ _ _ s).\n    destruct (choose s);intros.\n    exists e;auto with set.\n    generalize (H1 (refl_equal None)); clear H1.\n    intros; rewrite (is_empty_1 H1) in H; discriminate.\n  Qed.\n\n  Lemma choose_mem_4 : choose empty=None.\n  Proof.\n    intros; generalize (@choose_1 _ _ _ _ empty).\n    case (@choose _ _ _ empty);intros;auto.\n    elim (@empty_1 _ _ _ _ e); auto.\n  Qed.\n\n  (** Properties of [add] *)\n\n  Lemma add_mem_3 : mem y s=true -> mem y (add x s)=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma add_equal : mem x s=true -> equal (add x s) s=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  (** Properties of [remove] *)\n\n  Lemma remove_mem_3 : mem y (remove x s)=true -> mem y s=true.\n  Proof.\n    rewrite remove_b; auto; intros H;destruct (andb_prop _ _ H); auto.\n  Qed.\n\n  Lemma remove_equal : mem x s=false -> equal (remove x s) s=true.\n  Proof.\n    intros; apply equal_1; apply remove_equal.\n    rewrite not_mem_iff; auto.\n  Qed.\n\n  Lemma add_remove : mem x s=true -> equal (add x (remove x s)) s=true.\n  Proof.\n    intros; apply equal_1; apply add_remove; auto with set.\n  Qed.\n\n  Lemma remove_add : mem x s=false -> equal (remove x (add x s)) s=true.\n  Proof.\n    intros; apply equal_1; apply remove_add; auto.\n    rewrite not_mem_iff; auto.\n  Qed.\n\n  (** Properties of [is_empty] *)\n\n  Lemma is_empty_cardinal: is_empty s = zerob (cardinal s).\n  Proof.\n    intros; apply bool_1; split; intros.\n    rewrite cardinal_1; simpl; auto with set.\n    assert (cardinal s = 0) by (apply zerob_true_elim; auto).\n    auto with set.\n  Qed.\n\n  (** Properties of [singleton] *)\n\n  Lemma singleton_mem_1 : mem x (singleton x)=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma singleton_mem_2 : x =/= y -> mem y (singleton x)=false.\n  Proof.\n    intros; rewrite singleton_b; auto.\n    unfold eqb; destruct (eq_dec x y); intuition contradiction.\n  Qed.\n\n  Lemma singleton_mem_3 : mem y (singleton x)=true -> x === y.\n  Proof.\n    intros; apply singleton_1; auto with set.\n  Qed.\n\n  (** Properties of [union] *)\n\n  Lemma union_sym : equal (union s s') (union s' s)=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma union_subset_equal : subset s s'=true -> equal (union s s') s'=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma union_equal_1 :\n    equal s s'=true-> equal (union s s'') (union s' s'')=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma union_equal_2 :\n    equal s' s''=true-> equal (union s s') (union s s'')=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma union_assoc :\n    equal (union (union s s') s'') (union s (union s' s''))=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma add_union_singleton : equal (add x s) (union (singleton x) s)=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma union_add : equal (union (add x s) s') (add x (union s s'))=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  (* caracterisation of [union] via [subset] *)\n\n  Lemma union_subset_1 : subset s (union s s')=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma union_subset_2 : subset s' (union s s')=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma union_subset_3  :\n    subset s s''=true -> subset s' s''=true -> subset (union s s') s''=true.\n  Proof.\n    intros; apply subset_1; apply union_subset_3; auto with set.\n  Qed.\n\n  (** Properties of [inter] *)\n\n  Lemma inter_sym : equal (inter s s') (inter s' s)=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma inter_subset_equal : subset s s'=true -> equal (inter s s') s=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma inter_equal_1 :\n    equal s s'=true -> equal (inter s s'') (inter s' s'')=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma inter_equal_2 :\n    equal s' s''=true -> equal (inter s s') (inter s s'')=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma inter_assoc :\n    equal (inter (inter s s') s'') (inter s (inter s' s''))=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma union_inter_1 :\n      equal (inter (union s s') s'') (union (inter s s'') (inter s' s''))=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma union_inter_2 :\n      equal (union (inter s s') s'') (inter (union s s'') (union s' s''))=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma inter_add_1 :\n    mem x s'=true -> equal (inter (add x s) s') (add x (inter s s'))=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma inter_add_2 :\n    mem x s'=false -> equal (inter (add x s) s') (inter s s')=true.\n  Proof.\n    intros; apply equal_1; apply inter_add_2.\n    rewrite not_mem_iff; auto.\n  Qed.\n\n  (* caracterisation of [union] via [subset] *)\n\n  Lemma inter_subset_1 : subset (inter s s') s=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma inter_subset_2 : subset (inter s s') s'=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma inter_subset_3 :\n    subset s'' s=true -> subset s'' s'=true -> subset s'' (inter s s')=true.\n  Proof.\n    intros; apply subset_1; apply inter_subset_3; auto with set.\n  Qed.\n\n  (** Properties of [diff] *)\n\n  Lemma diff_subset : subset (diff s s') s=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma diff_subset_equal : subset s s'=true -> equal (diff s s') empty=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma remove_inter_singleton :\n    equal (remove x s) (diff s (singleton x))=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma diff_inter_empty : equal (inter (diff s s') (inter s s')) empty=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma diff_inter_all : equal (union (diff s s') (inter s s')) s=true.\n  Proof.\n    auto with set.\n  Qed.\n\nEnd BasicProperties.\n\nHint Immediate @empty_mem @is_empty_equal_empty @add_mem_1\n  @remove_mem_1 @singleton_equal_add @union_mem @inter_mem\n  @diff_mem @equal_sym @add_remove @remove_add : set.\nHint Resolve @equal_mem_1 @subset_mem_1 @choose_mem_1\n  @choose_mem_2 @add_mem_2 @remove_mem_2 @equal_refl @equal_equal\n  @subset_refl @subset_equal @subset_antisym\n  @add_mem_3 @add_equal @remove_mem_3 @remove_equal : set.\n\n(** General recursion principle *)\n\nLemma set_rec `{HF : @FSetSpecs A HA F} :\n  forall (P: set A -> Type),\n (forall s s', equal s s'=true -> P s -> P s') ->\n (forall s x, mem x s=false -> P s -> P (add x s)) ->\n P empty -> forall s, P s.\nProof.\n  intros.\n  apply set_induction; auto; intros.\n  apply X with empty; auto with set.\n  apply X with (add x s0); auto with set.\n  apply equal_1; intro a; rewrite add_iff; rewrite (H0 a); tauto.\n  apply X0; auto with set; apply mem_3; auto.\nQed.\n\n(** Properties of [fold] *)\n\nLemma exclusive_set `{HF : @FSetSpecs A HA F} :\n  forall s s' x, ~(In x s/\\In x s') <-> mem x s && mem x s'=false.\nProof.\n  intros; do 2 rewrite mem_iff.\n  destruct (mem x s); destruct (mem x s'); intuition.\nQed.\n\nSection Fold.\n  Context `{HF : @FSetSpecs elt Helt F}.\n\n  Variable A : Type.\n  Variable eqA : relation A.\n  Context {st : Equivalence eqA}.\n\n  Variable (f:elt->A->A).\n  Context {Comp : Proper (_eq ==> eqA ==> eqA) f}.\n  Hypothesis Ass :transpose eqA f.\n\n  Variable (i:A).\n  Variables (s s':set elt)(x:elt).\n\n  Lemma fold_empty : (fold f empty i) = i.\n  Proof.\n    intros; apply (fold_empty); auto.\n  Qed.\n\n  Lemma fold_equal : equal s s'=true -> eqA (fold f s i) (fold f s' i).\n  Proof.\n    intros; apply (fold_equal (eqA:=eqA)); auto with set.\n  Qed.\n\n  Lemma fold_add :\n    mem x s=false -> eqA (fold f (add x s) i) (f x (fold f s i)).\n  Proof.\n    intros; apply (fold_add (eqA:=eqA)); auto.\n    rewrite not_mem_iff; auto.\n  Qed.\n\n  Lemma add_fold : mem x s=true -> eqA (fold f (add x s) i) (fold f s i).\n  Proof.\n    intros; apply (add_fold (eqA:=eqA)); auto with set.\n  Qed.\n\n  Lemma remove_fold_1 :\n    mem x s=true -> eqA (f x (fold f (remove x s) i)) (fold f s i).\n  Proof.\n    intros; apply (remove_fold_1 (eqA:=eqA)); auto with set.\n  Qed.\n\n  Lemma remove_fold_2 :\n    mem x s=false -> eqA (fold f (remove x s) i) (fold f s i).\n  Proof.\n    intros; apply (remove_fold_2 (eqA:=eqA)); auto.\n    rewrite not_mem_iff; auto.\n  Qed.\n\n  Lemma fold_union :\n    (forall x, mem x s && mem x s'=false) ->\n    eqA (fold f (union s s') i) (fold f s (fold f s' i)).\n  Proof.\n    intros; apply (fold_union (eqA:=eqA)); auto.\n    intros; rewrite exclusive_set; auto.\n  Qed.\nEnd Fold.\n\n(** Properties of [cardinal] *)\n\nLemma add_cardinal_1 `{HF : @FSetSpecs A HA F} :\n forall s x, mem x s=true -> cardinal (add x s)=cardinal s.\nProof.\n  auto with set.\nQed.\n\nLemma add_cardinal_2 `{HF : @FSetSpecs A HA F} :\n  forall s x, mem x s=false -> cardinal (add x s)=S (cardinal s).\nProof.\n  intros; apply add_cardinal_2; auto.\n  rewrite not_mem_iff; auto.\nQed.\n\nLemma remove_cardinal_1 `{HF : @FSetSpecs A HA F} :\n  forall s x, mem x s=true -> S (cardinal (remove x s))=cardinal s.\nProof.\n  intros; apply remove_cardinal_1; auto with set.\nQed.\n\nLemma remove_cardinal_2 `{HF : @FSetSpecs A HA F} :\n  forall s x, mem x s=false -> cardinal (remove x s)=cardinal s.\nProof.\n  intros; apply Equal_cardinal; apply equal_2; auto with set.\nQed.\n\nLemma union_cardinal `{HF : @FSetSpecs A HA F} :\n  forall s s', (forall x, mem x s && mem x s'=false) ->\n    cardinal (union s s')=cardinal s+cardinal s'.\nProof.\n  intros; apply union_cardinal; auto; intros.\n  rewrite exclusive_set; auto.\nQed.\n\nLemma subset_cardinal `{HF : @FSetSpecs A HA F} :\n  forall s s', subset s s'=true -> cardinal s<=cardinal s'.\nProof.\n  intros; apply subset_cardinal; auto with set.\nQed.\n\nSection Bool.\n(** Properties of [filter] *)\n  Context `{HF : @FSetSpecs elt Helt F}.\n\n  Variable (f : elt -> bool).\n  Context {Comp : Proper (_eq ==> @eq bool) f}.\n\n  Definition Comp' : Proper (_eq ==> @eq bool) (fun x => negb (f x)).\n  Proof.\n    repeat intro; f_equal; auto.\n  Qed.\n  Hint Immediate Comp'.\n\n  Lemma filter_mem : forall s x, mem x (filter f s)=mem x s && f x.\n  Proof.\n    intros; apply filter_b; auto.\n  Qed.\n\n  Lemma for_all_filter :\n    forall s, for_all f s=is_empty (filter (fun x => negb (f x)) s).\n  Proof.\n    intros; apply bool_1; split; intros.\n    apply is_empty_1.\n    unfold Empty; intros.\n    rewrite filter_iff; auto using Comp'.\n    red; destruct 1.\n    rewrite <- for_all_iff in H; auto.\n    rewrite (H a H0) in H1; discriminate.\n    apply for_all_1; auto; red; intros.\n    revert H; rewrite <- is_empty_iff.\n    unfold Empty; intro H; generalize (H x); clear H.\n    rewrite filter_iff; auto using Comp'.\n    destruct (f x); auto.\n  Qed.\n\n  Lemma exists_filter : forall s, exists_ f s=negb (is_empty (filter f s)).\n  Proof.\n    intros; apply bool_1; split; intros.\n    destruct (exists_2 H) as (a,(Ha1,Ha2)).\n    apply bool_6.\n    red; intros; apply (@is_empty_2 _ _ _ _ _ H0 a); auto with set.\n    generalize (@choose_1 _ _ _ _ (filter f s))\n      (@choose_2 _ _ _ _ (filter f s)).\n    destruct (choose (filter f s)).\n    intros H0 _; apply exists_1; auto.\n    exists e; generalize (H0 e); rewrite filter_iff; auto.\n    intros _ H0.\n    rewrite (is_empty_1 (H0 (refl_equal None))) in H; auto; discriminate.\n  Qed.\n\n  Lemma partition_filter_1 :\n    forall s, equal (fst (partition f s)) (filter f s)=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma partition_filter_2 :\n    forall s, equal (snd (partition f s)) (filter (fun x => negb (f x)) s)=true.\n  Proof.\n    auto with set.\n  Qed.\n\n  Lemma filter_add_1 :\n    forall s x, f x = true -> filter f (add x s) [=] add x (filter f s).\n  Proof.\n    red; intros; set_iff; do 2 (rewrite filter_iff; auto); set_iff.\n    intuition.\n    rewrite <- H; apply Comp; auto.\n  Qed.\n\n  Lemma filter_add_2 :\n    forall s x, f x = false -> filter f (add x s) [=] filter f s.\n  Proof.\n    red; intros; do 2 (rewrite filter_iff; auto); set_iff.\n    intuition.\n    assert (f x = f a) by (apply Comp; auto).\n    rewrite H in H1; rewrite H2 in H1; discriminate.\n  Qed.\n\n  Lemma add_filter_1 :\n    forall s s' x,\n      f x=true -> (Add x s s') -> (Add x (filter f s) (filter f s')).\n  Proof.\n    unfold Add; intros.\n    repeat rewrite filter_iff; auto.\n    rewrite H0; clear H0.\n    assert (x === y -> f y = true) by\n      (intro H0; rewrite <- (Comp H0); auto).\n    tauto.\n  Qed.\n\n  Lemma add_filter_2 :\n    forall s s' x, f x=false -> (Add x s s') -> filter f s [=] filter f s'.\n  Proof.\n    unfold Add, Equal; intros.\n    repeat rewrite filter_iff; auto.\n    rewrite H0; clear H0.\n    assert (f a = true -> x =/= a).\n    intros H0 H1.\n    rewrite (Comp H1) in H.\n    rewrite H in H0; discriminate.\n    intuition contradiction.\n  Qed.\n\n  Lemma union_filter\n    (g : elt -> bool) `{Compg : Proper _ (_eq ==> @eq bool) g} :\n    forall s,\n      union (filter f s) (filter g s) [=] filter (fun x=>orb (f x) (g x)) s.\n  Proof.\n    intros.\n    unfold Equal; intros; set_iff; repeat rewrite filter_iff; auto.\n    assert (f a || g a = true <-> f a = true \\/ g a = true).\n    split; auto with bool.\n    intro H3; destruct (orb_prop _ _ H3); auto.\n    tauto.\n    repeat intro; rewrite H; auto.\n  Qed.\n\n  Lemma filter_union :\n    forall s s', filter f (union s s') [=] union (filter f s) (filter f s').\n  Proof.\n    unfold Equal; intros; set_iff;\n      repeat rewrite filter_iff; auto; set_iff; tauto.\n  Qed.\n\n  (** Properties of [for_all] *)\n\n  Lemma for_all_mem_1 :\n    forall s, (forall x, (mem x s)=true->(f x)=true) -> (for_all f s)=true.\n  Proof.\n    intros.\n    rewrite for_all_filter; auto.\n    rewrite is_empty_equal_empty.\n    apply equal_mem_1;intros.\n    rewrite filter_b; auto using Comp'.\n    rewrite empty_mem.\n    generalize (H a); case (mem a s);intros;auto.\n    rewrite H0;auto.\n  Qed.\n\n  Lemma for_all_mem_2 :\n    forall s, (for_all f s)=true -> forall x,(mem x s)=true -> (f x)=true.\n  Proof.\n    intros.\n    rewrite for_all_filter in H; auto.\n    rewrite is_empty_equal_empty in H.\n    generalize (equal_mem_2 H x).\n    rewrite filter_b; auto using Comp'.\n    rewrite empty_mem.\n    rewrite H0; simpl;intros.\n    replace true with (negb false);auto;apply negb_sym;auto.\n  Qed.\n\n  Lemma for_all_mem_3 :\n    forall s x,(mem x s)=true -> (f x)=false -> (for_all f s)=false.\n  Proof.\n    intros.\n    apply (bool_eq_ind (for_all f s));intros;auto.\n    rewrite for_all_filter in H1; auto.\n    rewrite is_empty_equal_empty in H1.\n    generalize (equal_mem_2 H1 x).\n    rewrite filter_b; auto using Comp'.\n    rewrite empty_mem.\n    rewrite H.\n    rewrite H0.\n    simpl;auto.\n  Qed.\n\n  Lemma for_all_mem_4 :\n    forall s, for_all f s=false -> {x:elt | mem x s=true /\\ f x=false}.\n  Proof.\n    intros.\n    rewrite for_all_filter in H; auto.\n    destruct (choose_mem_3 H) as (x,(H0,H1));intros.\n    exists x.\n    rewrite filter_b in H1; eauto.\n    elim (andb_prop _ _ H1).\n    split;auto.\n    replace false with (negb true);auto;apply negb_sym;auto.\n    exact Comp'.\n  Qed.\n\n  (** Properties of [exists] *)\n\n  Lemma for_all_exists :\n    forall s, exists_ f s = negb (for_all (fun x =>negb (f x)) s).\n  Proof.\n    intros.\n    rewrite for_all_b; auto using Comp'.\n    rewrite exists_b; auto.\n    induction (elements s); simpl; auto.\n    destruct (f a); simpl; auto.\n  Qed.\n\nEnd Bool.\n\nSection Bool'.\n  Context `{HF : @FSetSpecs elt Helt F}.\n\n  Variable (f : elt -> bool).\n  Context {Comp : Proper (_eq ==> @eq bool) f}.\n\n  Lemma exists_mem_1 :\n    forall s, (forall x, mem x s=true->f x=false) -> exists_ f s=false.\n  Proof.\n    intros.\n    rewrite for_all_exists; auto.\n    rewrite for_all_mem_1;auto with bool; auto using Comp'.\n    intros;generalize (H x H0);intros.\n    symmetry;apply negb_sym;simpl;auto.\n  Qed.\n\n  Lemma exists_mem_2 :\n    forall s, exists_ f s=false -> forall x, mem x s=true -> f x=false.\n  Proof.\n    intros; set (C' := Comp' (f:=f)).\n    rewrite for_all_exists in H; auto.\n    replace false with (negb true);auto;apply negb_sym;symmetry.\n    eapply (for_all_mem_2 (f:= fun x => negb (f x)) (s:=s)); simpl; auto.\n    replace true with (negb false);auto;apply negb_sym;auto.\n  Qed.\n\n  Lemma exists_mem_3 :\n    forall s x, mem x s=true -> f x=true -> exists_ f s=true.\n  Proof.\n    intros.\n    rewrite for_all_exists; auto.\n    symmetry;apply negb_sym;simpl.\n    apply for_all_mem_3 with x;auto using Comp'.\n    rewrite H0;auto.\n  Qed.\n\n  Lemma exists_mem_4 :\n    forall s, exists_ f s=true -> {x:elt | (mem x s)=true /\\ (f x)=true}.\n  Proof.\n    intros; set (C' := Comp' (f:=f)).\n    rewrite for_all_exists in H; auto.\n    elim (for_all_mem_4 (f:=(fun x =>negb (f x))) (s:=s));intros.\n    elim p;intros.\n    exists x;split;auto.\n    replace true with (negb false);auto;apply negb_sym;auto.\n    replace false with (negb true);auto;apply negb_sym;auto.\n  Qed.\nEnd Bool'.\n\nSection Sum.\n  Context `{HF : @FSetSpecs elt Helt F}.\n\n  (** Adding a valuation function on all elements of a set. *)\n  Definition sum (f:elt -> nat)(s:set elt) := fold (fun x => plus (f x)) s 0.\n  Notation compat_opL := (Proper (_eq ==> @eq nat ==> @eq nat)).\n  Notation transposeL := (transpose (@Logic.eq _)).\n\n  Lemma sum_plus :\n    forall (f g : elt -> nat)\n      `{Proper _ (_eq ==> @eq nat) f, Proper _ (_eq ==> @eq nat) g},\n      forall s, sum (fun x =>f x+g x) s = sum f s + sum g s.\n  Proof.\n    unfold sum.\n    intros f g Hf Hg.\n    assert (fc : compat_opL (fun x:elt =>plus (f x))). repeat intro;  auto.\n    assert (ft : transposeL (fun x:elt =>plus (f x))). red; repeat intro; omega.\n    assert (gc : compat_opL (fun x:elt => plus (g x))). repeat intro; auto.\n    assert (gt : transposeL (fun x:elt =>plus (g x))). red; repeat intro; omega.\n    assert (fgc : compat_opL (fun x:elt =>plus ((f x)+(g x)))).\n    repeat intro; auto.\n    assert (fgt : transposeL (fun x:elt=>plus ((f x)+(g x)))).\n    red; repeat intro; omega.\n    assert (st : Equivalence (@Logic.eq nat)) by (split; congruence).\n    intros s;pattern s; apply set_rec.\n    intros.\n    rewrite <- (fold_equal ft 0 H).\n    rewrite <- (fold_equal gt 0 H).\n    rewrite <- (fold_equal fgt 0 H); auto.\n    intros; do 3 (rewrite fold_add;auto).\n    rewrite H0;simpl;omega.\n    repeat rewrite (fold_empty); auto.\n  Qed.\n\n  Lemma sum_filter :\n    forall f `{Proper _ (_eq ==> @eq bool) f},\n      forall s,\n        (sum (fun x => if f x then 1 else 0) s) = (cardinal (filter f s)).\n  Proof.\n    unfold sum; intros f Hf.\n    assert (st : Equivalence (@Logic.eq nat)) by (split; congruence).\n    assert (cc : compat_opL (fun x => plus (if f x then 1 else 0))).\n    red; repeat intro. rewrite (Hf _ _ H); auto.\n    assert (ct : transposeL (fun x => plus (if f x then 1 else 0))).\n    red; intros; omega.\n    intros s;pattern s; apply set_rec.\n    intros.\n    rewrite <- (fold_equal ct 0 H).\n    rewrite (filter_m (equal_2 H)) in H0; auto.\n    intros; rewrite (fold_add ct); auto.\n    generalize (@add_filter_1 _ _ _ _ f _ s0 (add x s0) x)\n      (@add_filter_2 _ _ _ _ f _ s0 (add x s0) x) .\n    assert (~ In x (filter f s0)).\n    intro H1; rewrite (mem_1 (filter_1 H1)) in H; discriminate H.\n    case (f x); simpl; intros.\n    rewrite (cardinal_2 H1 (H2 (refl_equal true) (Add_add s0 x))); auto.\n    rewrite <- (Equal_cardinal (H3 (refl_equal false) (Add_add s0 x))); auto.\n    intros; rewrite (fold_empty);auto.\n    rewrite cardinal_1; auto.\n    unfold Empty; intros.\n    rewrite filter_iff; auto; set_iff; tauto.\n  Qed.\n\n  Lemma fold_compat : forall\n    (A : Type) (eqA : relation A) `{st : Equivalence A eqA}\n    (f g : elt -> A -> A)\n    `{Compf : Proper _ (_eq ==> eqA ==> eqA) f,\n      Compg : Proper _ (_eq ==> eqA ==> eqA) g}\n    (Assf : transpose eqA f) (Assg : transpose eqA g),\n    forall (i:A)(s:set elt),\n      (forall x:elt, (In x s) -> forall y, (eqA (f x y) (g x y))) ->\n      (eqA (fold f s i) (fold g s i)).\n  Proof.\n    intros A eqA st f g fc ft gc gt i.\n    intro s; pattern s; apply set_rec; intros.\n    transitivity (fold f s0 i).\n    apply (fold_equal (eqA:=eqA)); auto.\n    rewrite equal_sym; auto.\n    transitivity (fold g s0 i).\n    apply H0; intros; apply H1; auto with set.\n    elim  (equal_2 H x); auto with set; intros.\n    apply (fold_equal (eqA:=eqA)); auto with set.\n    transitivity (f x (fold f s0 i)).\n    apply (fold_add (eqA:=eqA)); auto with set.\n    transitivity (g x (fold f s0 i)); auto with set.\n    transitivity (g x (fold g s0 i)); auto with set.\n    apply ft; auto. apply H0. intros; apply H1; auto with set.\n    symmetry; apply (fold_add (eqA:=eqA)); auto.\n    repeat rewrite (fold_empty); auto; reflexivity.\n  Qed.\n\n  Lemma sum_compat\n    (f g : elt -> nat)\n    `{Compf : Proper _ (_eq ==> @eq nat) f,\n      Compg : Proper _ (_eq ==> @eq nat) g} :\n    forall s, (forall x, In x s -> f x=g x) -> sum f s=sum g s.\n  Proof.\n    intros.\n    unfold sum; apply (fold_compat (eqA:=@eq nat)); auto.\n    red; repeat intro; auto; omega.\n    red; repeat intro; auto; omega.\n    red; repeat intro; auto; omega.\n    red; repeat intro; auto; omega.\n  Qed.\nEnd Sum.", "meta": {"author": "coq-contribs", "repo": "containers", "sha": "105a3ca030f0dc9712c88bfc87c39c33e168f1a2", "save_path": "github-repos/coq/coq-contribs-containers", "path": "github-repos/coq/coq-contribs-containers/containers-105a3ca030f0dc9712c88bfc87c39c33e168f1a2/theories/SetEqProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893340314393, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.6919039712894642}}
{"text": "\nInductive tree (A : Type) : Type :=\n| leaf : A -> tree A\n| branch : A -> tree A -> tree A -> tree A.\n\nArguments leaf {A}.\nArguments branch {A} _ _ _.\n\nFixpoint flip_tree {A : Type} (t : tree A) : tree A :=\n  match t with\n  | leaf _ => t\n  | branch a l r => branch a (flip_tree r) (flip_tree l)\n  end.\n\nTheorem flip_tree_sym : forall {A : Type} (t : tree A),\n    t = flip_tree (flip_tree t).\nProof.\n  intros.\n  induction t.\n  compute.\n  reflexivity.\n  simpl.\n  rewrite <- IHt1.\n  rewrite <- IHt2.\n  reflexivity.\nQed.\n", "meta": {"author": "HaroldVemeno", "repo": "coq-stuff", "sha": "c233fca4c766781bb1f90d3356708f0519310fb5", "save_path": "github-repos/coq/HaroldVemeno-coq-stuff", "path": "github-repos/coq/HaroldVemeno-coq-stuff/coq-stuff-c233fca4c766781bb1f90d3356708f0519310fb5/flip_tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.6919039689376087}}
{"text": "Require Export XR_R.\nRequire Export XR_Rlt.\nRequire Export XR_total_order_T.\n\nImplicit Type r : R.\nLocal Open Scope R_scope.\n\nLemma Rtotal_order : forall r1 r2, r1 < r2 \\/ r1 = r2 \\/ r2 < r1.\nProof.\n  intros x y.\n  destruct (total_order_T x y) as [ [ hxy | heq ] | hyx ].\n  { left. exact hxy. }\n  { right. left. exact heq. }\n  { right. right. exact hyx. }\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_Rtotal_order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.6918638964901139}}
{"text": "(***************************************************************************\n\n Connected categories and groupoids\n\n A category is called connected if it is inhabited and for every two objects\n there is a zig-zag between them. A groupoid is called connected if it is\n inhabited and if for every two objects there is a morphism between them.\n\n Note: these two notions are in general not a proposition. The reason for\n that is that the choice of the zig-zag or of the morphism is not required\n to be natural. As such, different choices do not have to be equal up to\n isomorphism.\n\n Contents\n 1. Definition of connected categories\n 2. Categories with a (weak) terminal object are connected\n 3. Categories with a (weak) initial object are connected\n 4. Connected groupoids and connected categories\n\n ***************************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.Univalence.\nRequire Import UniMath.CategoryTheory.categories.StandardCategories.\nRequire Import UniMath.CategoryTheory.categories.HSET.All.\nRequire Import UniMath.CategoryTheory.limits.terminal.\nRequire Import UniMath.CategoryTheory.limits.initial.\nRequire Import UniMath.CategoryTheory.Groupoids.\nRequire Import UniMath.CategoryTheory.ZigZag.\n\nLocal Open Scope cat.\n\n(**\n 1. Definition of connected categories\n *)\nDefinition connected_category\n           (C : category)\n  : UU\n  := ob C × ∏ (x y : C), zig_zag x y.\n\nDefinition ob_of_connected_category\n           {C : category}\n           (H : connected_category C)\n  : C\n  := pr1 H.\n\nDefinition zig_zag_of_connected_category\n           {C : category}\n           (H : connected_category C)\n           (x y : C)\n  : zig_zag x y\n  := pr2 H x y.\n\nDefinition make_connected_category\n           {C : category}\n           (c : C)\n           (zs : ∏ (x y : C), zig_zag x y)\n  : connected_category C\n  := c ,, zs.\n\n(**\n 2. Categories with a (weak) terminal object are connected\n *)\nDefinition weakly_terminal_to_connected\n           {C : category}\n           (c : C)\n           (fs : ∏ (w : C), w --> c)\n  : connected_category C.\nProof.\n  use make_connected_category.\n  - exact c.\n  - exact (λ x y, x -[ fs x ]-> c <-[ fs y ]- y ■).\nDefined.\n\nDefinition terminal_to_connected\n           {C : category}\n           (T : Terminal C)\n  : connected_category C.\nProof.\n  use weakly_terminal_to_connected.\n  - exact T.\n  - exact (λ x, TerminalArrow T x).\nDefined.\n\nDefinition HSET_connected_terminal\n  : connected_category HSET.\nProof.\n  use terminal_to_connected.\n  exact TerminalHSET.\nDefined.\n\n(**\n 3. Categories with a (weak) initial object are connected\n *)\nDefinition weakly_initial_to_connected\n           {C : category}\n           (c : C)\n           (fs : ∏ (w : C), c --> w)\n  : connected_category C.\nProof.\n  use make_connected_category.\n  - exact c.\n  - exact (λ x y, x <-[ fs x ]- c -[ fs y ]-> y ■).\nDefined.\n\nDefinition initial_to_connected\n           {C : category}\n           (I : Initial C)\n  : connected_category C.\nProof.\n  use weakly_initial_to_connected.\n  - exact I.\n  - exact (λ x, InitialArrow I x).\nDefined.\n\nDefinition HSET_connected_initial\n  : connected_category HSET.\nProof.\n  use initial_to_connected.\n  exact InitialHSET.\nDefined.\n\n(**\n 4. Connected groupoids and connected categories\n *)\nDefinition connected_groupoid\n           (G : groupoid)\n  : UU\n  := ob G × ∏ (x y : G), x --> y.\n\nDefinition ob_of_connected_groupoid\n           {G : groupoid}\n           (H : connected_groupoid G)\n  : G\n  := pr1 H.\n\nDefinition mor_of_connected_groupoid\n           {G : groupoid}\n           (H : connected_groupoid G)\n           (x y : G)\n  : x --> y\n  := pr2 H x y.\n\nDefinition make_connected_groupoid\n           {G : groupoid}\n           (c : G)\n           (zs : ∏ (x y : G), x --> y)\n  : connected_groupoid G\n  := c ,, zs.\n\nDefinition connected_groupoid_to_connected_category\n           {G : groupoid}\n           (H : connected_groupoid G)\n  : connected_category G.\nProof.\n  use make_connected_category.\n  - exact (ob_of_connected_groupoid H).\n  - exact (λ x y, x -[ mor_of_connected_groupoid H x y ]-> y ■).\nDefined.\n\nDefinition connected_category_to_connected_groupoid\n           {G : groupoid}\n           (H : connected_category G)\n  : connected_groupoid G.\nProof.\n  use make_connected_groupoid.\n  - exact (ob_of_connected_category H).\n  - exact (λ x y, zig_zag_in_grpd_to_mor (zig_zag_of_connected_category H x y)).\nDefined.\n\nDefinition unit_connected_category\n  : connected_category unit_category.\nProof.\n  apply connected_groupoid_to_connected_category.\n  use make_connected_groupoid.\n  - exact tt.\n  - apply isapropunit.\nDefined.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/CategoryTheory/Connected.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.7931059438487662, "lm_q1q2_score": 0.6918638958544203}}
{"text": "(** * Vector type with dependent length and arbitrary-length constructor *)\n\nInductive vec (A : Type) : nat -> Type :=\n  | VecNil : vec A 0\n  | VecCons (x : A) (n : nat) : vec A n -> vec A (S n).\n\nArguments VecNil {_}.\nArguments VecCons {_} _ _.\n\nCheck VecCons true _ (VecCons false _ (VecCons false _ VecNil)).\n\nFixpoint append {A n m} (v : vec A n) (w : vec A m) : vec A (n + m) :=\n  match v with\n  | VecNil => w\n  | VecCons x _ v' => VecCons x _ (append v' w)\n  end.\n\nFixpoint mkvec_type_ (A : Type) (n m : nat) : Type :=\n  match n with\n  | 0 => vec A m\n  | S n => A -> mkvec_type_ A n (S m)\n  end.\nDefinition mkvec_type (A : Type) (n : nat) : Type := mkvec_type_ A n 0.\n\nCompute mkvec_type nat 0.\nCompute mkvec_type nat 5.\n\nFixpoint mkvec_ (A : Type) (n m : nat) (v : vec A m) : mkvec_type_ A n m :=\n  match n with\n  | 0 => v\n  | S n => fun a : A => mkvec_ A n (S m) (VecCons a _ v)\n  end.\nDefinition mkvec (A : Type) (n : nat) : mkvec_type A n := mkvec_ A n 0 VecNil.\n\nCompute mkvec nat 0.\nCompute mkvec nat 5.\nCompute mkvec nat 5 1 2 3 4 5.\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/coc/vec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.6918638943571241}}
{"text": "From QuickChick Require Import QuickChick.\n\nRequire Import List. Import ListNotations.\nRequire Import String. Open Scope string.\n\nInductive Ty :=\n| Unt : Ty\n| Arr : Ty -> Ty -> Ty.\n\nDerive (Arbitrary, Sized) for Ty.\n\nProgram Instance show_Ty : Show Ty := {\n  show :=\n    fix show' (ty: Ty) := \n    match ty with \n    | Unt => \"*\"\n    | Arr A B => \"(\" ++ show' A ++ \" -> \" ++ show' B ++ \")\"\n    end\n}.\n\nInstance eq_Ty (t1 t2 : Ty) : Dec (t1 = t2).\nProof. dec_eq. Qed.\n\nInductive Tm :=\n| Tt : Tm (* : Unt *)\n| Var : nat -> Tm\n| Lam : Ty -> Tm -> Tm\n| App : Tm -> Tm -> Tm.\n\nDerive (Arbitrary, Sized) for Tm.\n\nProgram Instance show_Tm : Show Tm := {\n  show :=\n    fix show' (tm: Tm) :=\n    match tm with \n    | Tt => \"*\"\n    | Var n => show n\n    | Lam A b => \"(λ \" ++ show A ++ \" => \" ++ show' b ++ \")\"\n    | App f a => \"(\" ++ show' f ++ \" \" ++ show' a ++ \")\"\n    end\n}.\n\nDefinition Ctx := list Ty.\n\nInductive typed_var : Ctx -> Ty -> nat -> Prop :=\n| typed_var_O : forall gamma alpha, \n    typed_var (alpha :: gamma) alpha O\n| typed_var_S : forall gamma alpha beta n, \n    typed_var gamma alpha n -> \n    typed_var (beta :: gamma) alpha (S n).\n\nInductive typed : Ctx -> Ty -> Tm -> Prop :=\n| typed_Tt : forall gamma, \n    typed gamma Unt Tt\n| typed_Var : forall gamma alpha n, \n    typed_var gamma alpha n -> \n    typed gamma alpha (Var n)\n| typed_Lam : forall gamma alpha beta bod,\n    typed (alpha :: gamma) beta bod ->\n    typed gamma (Arr alpha beta) (Lam alpha bod)\n| typed_App : forall gamma alpha beta apl arg,\n    typed gamma (Arr alpha beta) apl ->\n    typed gamma alpha arg ->\n    typed gamma beta (App apl arg).\n\nFixpoint infer_type_var (gamma: Ctx) (n: nat): option Ty :=\n  match gamma with\n  | [] => None \n  | alpha :: gamma' => \n    match n with \n    | O => Some alpha\n    | S n' => infer_type_var gamma' n'\n    end \n  end.\n\n(* TODO: is this sufficient? *)\nDerive DecOpt for (typed_var gamma alpha n).\n\nFixpoint is_typed_var (gamma: Ctx) (ty: Ty) (n: nat): bool :=\n  match infer_type_var gamma n with \n  | Some ty' => (ty = ty')?\n  | None => false\n  end.\n\n(* TODO: why fail? *)\nFail Derive DecOpt for (typed gamma alpha t).\n  \nFixpoint infer_type (gamma: Ctx) (tm: Tm): option Ty :=\n  match tm with \n  | Tt => Some Unt\n  | Var n => infer_type_var gamma n\n  | Lam alpha b => \n    match infer_type (alpha :: gamma) b with \n    | None => None \n    | Some beta => Some (Arr alpha beta)\n    end \n  | App f a =>\n    match infer_type gamma f with \n    | Some (Arr alpha beta) =>\n      if is_typed gamma alpha a \n        then Some beta\n        else None\n    | _ => None\n    end\n  end\n\nwith is_typed (gamma: Ctx) (ty: Ty) (tm: Tm): bool :=\n  match tm with\n  | Tt => (ty = Unt)?\n  | Var n => is_typed_var gamma ty n \n  | Lam alpha b => \n    match ty with\n    | Arr alpha' beta => \n      andb ((alpha = alpha')?)\n           (is_typed (alpha :: gamma) beta b)\n    | _ => false\n    end\n  | App f a =>\n    match infer_type gamma f with \n    | Some (Arr alpha beta) =>\n      andb (is_typed gamma alpha a)\n           ((beta = ty)?)\n    | _ => false\n    end\n  end. \n\nDerive ArbitrarySizedSuchThat for (fun n => typed_var gamma alpha n).\nDerive ArbitrarySizedSuchThat for (fun t => typed gamma alpha t).\n\n(* mutation *)\n\nFixpoint mut_typed (gamma: Ctx) (ty: Ty) (tm: Tm): G (option Tm) :=\n  let mut_here: G (option Tm) :=\n        bind (genST (fun tm' => typed gamma ty tm')) (fun opt_tm' =>\n        match opt_tm' with \n        | None => ret (Some tm)\n        | Some tm' => ret (Some tm')\n        end)\n  in\n  match tm return G (option Tm) with \n  | Tt => genST (fun t => typed gamma Unt t)\n  | Var n =>\n    freq_ (ret (Some tm))\n      [ (* mut here *)\n        (1, mut_here)\n      ; (* mut n *)\n        ( List.length gamma\n        , bind (genST (fun n' => typed_var gamma ty n')) (fun opt_n' =>\n          match opt_n' return G (option Tm) with \n          | None => ret (Some tm)\n          | Some n' => ret (Some (Var n'))\n          end)\n        )\n      ]\n  | Lam alpha b =>\n    freq_ (ret (Some tm))\n      [ (* mut here *)\n        (1, mut_here)\n      ; (* mut b *)\n        ( size b\n        , match ty with \n          | Arr alpha beta =>\n            bind (mut_typed gamma beta b) (fun opt_b' =>\n            match opt_b' with \n            | None => ret None\n            | Some b' => ret (Some (Lam alpha b'))\n            end)\n          | _ => ret None\n          end\n        (* can't mut alpha since fixed by rel *)\n        )\n      ]\n  | App f a =>\n    freq_ (ret (Some tm))\n      [ (* mut here *)\n        (1, mut_here)\n      ; (* mut f *)\n        ( size f\n        , match infer_type gamma f with \n          | None => ret None\n          | Some phi =>\n            bind (mut_typed gamma phi f) (fun opt_f' =>\n            match opt_f' with \n            | None => ret None\n            | Some f' => ret (Some (App f' a))\n            end)\n          end\n        )\n      ; (* mut a *)\n        ( size a \n        , match infer_type gamma a with \n          | None => ret None\n          | Some alpha =>\n            bind (mut_typed gamma alpha a) (fun opt_a' =>\n            match opt_a' with \n            | None => ret None\n            | Some a' => ret (Some (App f a'))\n            end)\n          end\n        )\n      ] \n  end.\n\nDefinition mut_preserves_typed_prop gamma ty :=\n  forAllMaybe (genST (fun tm => typed gamma ty tm)) (fun tm =>\n  forAllMaybe (mut_typed gamma ty tm) (fun tm' =>\n  is_typed gamma ty tm')).\n\nQuickChick (mut_preserves_typed_prop [Unt] (Unt)).\n(* QuickChick (mut_preserves_typed_prop [Unt] (Arr Unt Unt) (Lam Unt (Var 0))). *)\n\nDefinition G1 := [Unt; (Arr Unt Unt)].\nDefinition A1 := (Arr Unt Unt).\nDefinition T1 := \n  (App \n    (Lam Unt (Var 1)) \n    (App \n      (Lam Unt (Var 1))\n      (Var 0))).\nDefinition T2 :=\n  (App\n    (Lam Unt (Var 1))\n    (Var 0)).\n\n(* QuickChick (ret (is_typed G1 A1 T2)). *)\n\nQuickChick \n  (mut_preserves_typed_prop\n    [Unt; (Arr Unt Unt)]\n    (Arr Unt Unt)\n    (App \n      (Lam Unt (Var 1)) \n      (App \n        (Lam Unt (Var 1))\n        (Var 0)))\n  ).\n\nSample (genST (fun tm => typed [] Unt tm)).\n\nDefinition gen_is_typed (gamma: Ctx) (ty: Ty): G bool :=\n  bind (genST (fun tm => typed gamma ty tm)) (fun opt_tm =>\n  match opt_tm with \n  | None => ret true \n  | Some tm => ret (is_typed gamma ty tm)\n  end). \n\n(* QuickChick gen_is_typed. *)\n\nDefinition mut_preserves_typed (gamma: Ctx) (ty: Ty): G bool :=\n  bind (genST (fun tm => typed gamma ty tm)) (fun opt_tm =>\n  match opt_tm with \n  | None => ret true \n  | Some tm =>\n    bind (mut_typed gamma ty tm) (fun opt_tm' =>\n    match opt_tm' with \n    | None => ret true \n    | Some tm' => ret (is_typed gamma ty tm')\n    end)\n  end).\n\n(* QuickChick mut_preserves_typed. *)\n", "meta": {"author": "Bazinga9000", "repo": "QuickTarget", "sha": "d7bae541f210af1183a040172216568ab4074e8b", "save_path": "github-repos/coq/Bazinga9000-QuickTarget", "path": "github-repos/coq/Bazinga9000-QuickTarget/QuickTarget-d7bae541f210af1183a040172216568ab4074e8b/examples/smart-mutators/stlc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6918638927232331}}
{"text": "(** Polymorphic versions of exponentiation functions *)\n\nRequire Import Arith ZArith.\nRequire Import String.\n\n(** \n  Polymorphic exponentiation functions \n *)\n\n(* begin snippet Defs *)\nSection Definitions.\n\n Variables (A : Type)\n           (mult : A -> A -> A)\n           (one : A).\n\n#[local] Infix \"*\" := mult.\n#[local] Notation \"1\" := one.\n\n(**  Naive (linear) implementation *)\n\nFixpoint power (x:A)(n:nat) : A :=\n  match n with\n    | 0%nat => 1\n    | S p =>   x * x ^ p\n  end\nwhere \"x ^ n\" := (power x n).\n(* end snippet Defs *)\n\n\n(** Logarithmic implementation (with exponents in [N])  *)\n\n(* begin snippet bpowDef *)\n\nFixpoint binary_power_mult (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\nFixpoint Pos_bpow   (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\n\nDefinition N_bpow  x (n:N) := \n  match n with \n  | 0%N => 1\n  | Npos p => Pos_bpow x p\n  end.\n\n(* end snippet bpowDef *)\n\n(* begin snippet EndDefs *)\nEnd Definitions.\n\nArguments N_bpow  {A}.\nArguments power  {A}.\n(* end snippet EndDefs *)\n\n\n\n(** **  Examples *)\n\n(* begin snippet PowerCompute *)\nCompute power Z.mul 1%Z 2%Z 10.\n\nCompute N_bpow Z.mul 1%Z 2%Z 10.\n\nOpen Scope string_scope.\n\nCompute power append  \"\" \"ab\"  12.\n\nCompute N_bpow append  \"\" \"ab\"  12.\n(* end snippet PowerCompute *)\n\n(** Exponentiation on 2x2 matrices *)\n\n(* begin snippet M2a *)\n\nModule M2.\nSection M2_Definitions.\n  \n  Variables (A: Type)\n           (zero one : A) \n           (plus mult  : A -> A -> A).\n  \n  Variable rt : semi_ring_theory  zero one plus mult   (@eq A).\n  Add Ring Aring : rt.\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 t : Type := mat{c00 : A;  c01 : A;\n                            c10 : A;  c11 : A}.\n  \n  Definition Id2 : t := mat 1 0 0 1.\n\n(* end snippet M2a *)\n\n(* begin snippet M2Mult *)\n  Definition M2_mult (M M':t) : t :=\n    mat (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\nEnd M2_Definitions.\nEnd M2.\n\nImport M2.\n\nArguments M2_mult {A} plus mult  _  _.\nArguments mat {A} _ _ _ _.\nArguments Id2 {A}  _ _.\n(* end snippet M2Mult *)\n\nDefinition fibonacci (n:N) :=\n c00 N  (N_bpow  (M2_mult Nplus Nmult) (Id2  0%N 1%N)(mat  1 1 1 0)%N n).\n\n Compute fibonacci 20.\n\n\n(* begin snippet powerTDef *)\nDefinition power_t := forall (A:Type)\n                             (mult : A -> A -> A)\n                             (one:A)\n                             (x:A)\n                             (n:N), A.\n(* end snippet powerTDef *)\n\n(** * A wrong definition of correctness *)\n\n(* begin snippet Bada *)\nModule Bad.\n\n  Definition correct_expt_function (f : power_t) : Prop :=\n    forall A (mult : A -> A -> A) (one:A)\n           (x:A) (n:N), power mult one x (N.to_nat n) =\n                        f A mult one x n.\n  (* end snippet Bada *)\n  \n(* begin snippet Badb:: no-out *)\n  Section CounterExample.\n    Let mul (n p : nat) := n + 2 * p.\n    Let one := 0.\n\n    (** With our fake definition, [N_bpow] is not correct! *)\n    \n    Remark mul_not_associative :\n      exists  n p q,  mul n (mul p q) <> mul (mul n p) q.\n    Proof.\n      exists 1, 1, 1; discriminate. \n    Qed.\n\n    Remark one_not_neutral  :\n      exists n : nat, mul one n <> n.\n    Proof.\n      exists 1; discriminate.\n    Qed.\n\n    Lemma correct_exp_too_strong : ~ correct_expt_function (@N_bpow).\n    Proof.\n      intro H; specialize (H _ mul one 1  7%N).\n      discriminate H.\n    Qed.\n\n  End CounterExample.\n\nEnd Bad.\n(* end snippet Badb *)\n\n(** Fibonacci matrices *)\n(*\n\nOpen Scope Z_scope. \nDefinition encode (p: Z*Z) := let (a,b) := p in  mat (a+b)%Z a a b.\n\nDefinition id2 := (0,1).\nDefinition matfib2 := (1, 0).\nDefinition mul2 (m m' : Z*Z) := let (a,b) := m in\n                        let (c,d) := m' in\n                        ((a+b)*c + a*d, a*c + b*c).\n\n\nCompute mul2 id2 matfib2.\nCompute mul2 matfib2 id2.\n\n\nLemma mul2_assoc (m m' m'': Z*Z):\n      mul2 (mul2 m m') m'' = mul2 m (mul2 m' m'').\ndestruct m,m',m''.\n  unfold mul2.\n f_equal. ring_simplify.\nAbort.\n\nDefinition yves_fib (n:nat) := let p := power mul2 id2 matfib2 n in\n                               fst p + snd p.\n\nCompute yves_fib 10.\nCompute yves_fib 0.\nCompute yves_fib 20.\n\nCompute power mul2 id2 matfib2 4%nat.\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/FirstSteps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.691863891089342}}
{"text": "Theorem plus_id_exercise : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\n intros n m o. intros H. intros I. rewrite H. rewrite I. reflexivity. Qed.\n", "meta": {"author": "spinute", "repo": "PierceSoftwareFoundationEx", "sha": "6b71d21101a3f44e4b20afb6a7ca0e50bcae51a1", "save_path": "github-repos/coq/spinute-PierceSoftwareFoundationEx", "path": "github-repos/coq/spinute-PierceSoftwareFoundationEx/PierceSoftwareFoundationEx-6b71d21101a3f44e4b20afb6a7ca0e50bcae51a1/plus_id_exercise.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6918638879581546}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) : natural := plus Zero (Succ lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj62_coqofml_QcMUyL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6917657947825271}}
{"text": "Require Import Rsequence_def Rsequence_sums_facts Rsequence_rewrite_facts.\nRequire Import MyNat.\nRequire Import Rfunction_def.\n\nLocal Open Scope R_scope.\n\nDefinition D (f : R -> R) : R -> R := fun x => f (x + 1) - f x.\nDefinition Int (a b: nat) (f : R -> R) : R :=\n  Rseq_sum (Rseq_shifts (fun n => f (INR n)) a) (b - a).\n\nLemma D_opp_compat : forall f, D (- f)%F == (- D f)%F.\nProof.\nintros f x ; unfold D, opp_fct ; ring.\nQed.\n\nLemma D_plus_compat : forall f g, D (f + g)%F == (D f + D g)%F.\nProof.\nintros f g x ; unfold D, plus_fct ; ring.\nQed.\n\nLemma D_minus_compat : forall f g, D (f - g)%F == (D f - D g)%F.\nProof.\nintros f g x ; unfold D, minus_fct, Rminus ; ring.\nQed.\n\nLemma Int_D: forall a b f, (a <= b)%nat -> Int a b (D f) = f (INR b + 1) - f (INR a).\nProof.\nintros a b ; revert a ; induction b ; intros a f altb.\n inversion altb ; reflexivity.\n unfold Int in * ; destruct a ; simpl minus.\n  rewrite Rseq_sum_simpl ; rewrite (minus_n_O b), IHb ; [| apply le_0_n].\n  unfold Rseq_shifts, D ; rewrite <- minus_n_O ; simpl plus ;\n  rewrite S_INR ; ring.\n  erewrite Rseq_sum_ext ; [| apply Rseq_shift_shifts] ;\n  rewrite Rseq_sum_shift_compat.\n  unfold Rseq_shift ; rewrite Rseq_sum_simpl, IHb ; unfold Rseq_shifts, D.\n  rewrite minus_Sn_m, le_plus_minus_r, plus_0_r, S_INR, S_INR.\n   ring.\n   transitivity (S a) ; [apply le_n_Sn | assumption].\n   apply le_S_n ; assumption.\n   apply le_S_n ; assumption.\nQed.\n\nFixpoint Fp (n : nat) : R -> R := fun x =>\nmatch n with\n  | O   => 1\n  | S m => (x - INR m) * Fp m x\nend.\n\nLemma D_Fp_S_simpl : forall x n, D (Fp (S n)) x = INR (S n) * Fp n x.\nProof.\nintros x n ; induction n.\n unfold D, Fp ; simpl ; ring.\n\n replace (INR(S(S n))) with (1+ INR(S n)) by (simpl; auto with *). \n rewrite Rmult_plus_distr_r; simpl Fp at 3.\n rewrite Rmult_comm with  (x - INR n) (Fp n x).\n rewrite <- Rmult_assoc.\n rewrite <- IHn.\n unfold D, Fp.\n replace (INR (S n)) with (1 + INR n) by (simpl; case n; auto with *).\n ring.\nQed.", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/src/Reals/Finite_Calculus/Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6917657862269057}}
{"text": "Require Import UnivalentParametricity.theories.Basics UnivalentParametricity.theories.StdLib.Basics.\nRequire Import NatBinDefs.\n\nRequire Import BinNat.\n\nSet Universe Polymorphism.\n\nDefinition nat := Datatypes.nat.\nDefinition S := Datatypes.S.\n\nRecord Monoid A :=\n  Build_Monoid {\n      mon_e : A;\n      mon_m : A -> A -> A;\n      mon_unitL : forall x, mon_m x mon_e = x;\n      mon_unitR : forall x, mon_m mon_e x = x;\n      mon_assoc : forall x y z, mon_m x (mon_m y z) = mon_m (mon_m x y) z\n    }.\n\n(* The fact that it is univalent can be almost automatically inferred\n   using its equivalent presentation with dependent sums *)\n\nInstance issig_monoid {A : Type} :\n  { e:A & {m:A -> A -> A & {uL : forall x, m x e = x & { uR : forall x, m e x = x &\n                                            forall x y z, m x (m y z) = m (m x y) z}}}}\n  ≃ Monoid A.\nProof.\n  issig (Build_Monoid A) (@mon_e A) (@mon_m A) (@mon_unitL A) (@mon_unitR A) (@mon_assoc A).\nDefined.\n\nInstance issig_monoid_inv {A : Type} :\n  Monoid A ≃\n         { e:A & {m:A -> A -> A & {uL : forall x, m x e = x & { uR : forall x, m e x = x &\n                                                                               forall x y z, m x (m y z) = m (m x y) z}}}}\n         := Equiv_inverse _.\n\n\nDefinition FP_Monoid : Monoid ≈ Monoid.\nProof.\n  univ_param_record.\nDefined. \n\n#[export] Hint Extern 0 (Monoid ≈ Monoid) => exact (ur_type FP_Monoid) : typeclass_instances. \n\n#[export] Hint Extern 0 (Monoid _ ≃ Monoid _) => unshelve refine (equiv (ur_type FP_Monoid _ _ _)) : typeclass_instances. \n\n(* we define the monoid structure on N *)\n\nDefinition N_mon : Monoid N.\nProof.\n  unshelve refine (Build_Monoid _ _ _ _ _ _).\n  - exact N0.\n  - exact N.add.\n  - intro x. destruct x; reflexivity. \n  - intro x. destruct x; reflexivity.\n  - intros. cbn. apply logic_eq_is_eq. exact (N.add_assoc x y z).  \nDefined.\n\n(* Then we can deduce automatically a monoid structure on nat *)\n\nDefinition n_mon : Monoid nat := ↑ N_mon.\n", "meta": {"author": "CoqHott", "repo": "univalent_parametricity", "sha": "3137f7f35f905bdb40c1215e7df9876e45682bdd", "save_path": "github-repos/coq/CoqHott-univalent_parametricity", "path": "github-repos/coq/CoqHott-univalent_parametricity/univalent_parametricity-3137f7f35f905bdb40c1215e7df9876e45682bdd/examples/NatBinMonoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6917657836620849}}
{"text": "From Categories Require Import Essentials.Notations.\nFrom Categories Require Import Essentials.Types.\nFrom Categories Require Import Essentials.Facts_Tactics.\nFrom Categories Require Import Category.Main.\n\n(** The solution set condition. In Freyd's adjoint functor theorem\nit is assumed that (Comma (Func_From_SingletonCat x) G) satisfies\nsolution set condition. \n\nA category C satisfies solution set condition if there is a type A,\na function f : A → C such that for any object (c : C) there exists\na (t : A) such that there is a morphism h : (f t) –≻ c. In short,\nf is jointly weakly initial.\n*)\nRecord Solution_Set_Cond (C : Category) :=\n  {\n    SSC_Type : Type;\n    SSC_Objs : SSC_Type → C;\n    SSC_jointly_weakly_initial :>\n      ∀ (c : C), {t : SSC_Type & ((SSC_Objs t) –≻ c)%morphism}\n  }\n.\n\nArguments SSC_Type {_} _.\nArguments SSC_Objs {_} _ _.\nArguments SSC_jointly_weakly_initial {_} _ _.\n\nFrom Categories Require Import Limits.Limit Limits.GenProd_GenSum.\nFrom Categories Require Import Functor.Functor.\nFrom Categories Require Import NatTrans.NatTrans.\nFrom Categories Require Import\n        Basic_Cons.Terminal\n        Basic_Cons.Equalizer\n        Basic_Cons.Limits\n        Basic_Cons.Facts.Equalizer_Monic\n.\nFrom Categories Require Import Archetypal.Discr.Discr.\n\n\n(** We show that a category that is complete and satisfies solution \n    set condition has an initial object. This initial object is the\n    equalizer of all endo-morphisms d : W –≻ W,\n    where W is the generalized product of the function (SSC_Objs) of\n    the solution set condition. *)\nSection Complete_SSC_Initial.\n  Context\n    {C : Category}\n    (CC : Complete C)\n    (SSC : Solution_Set_Cond C)\n  .\n\n  (** The product of objects producing SSC. *)\n  Definition SSC_Prod : (Π (SSC_Objs SSC))%object\n    :=\n      (LimitOf (Discr_Func (SSC_Objs SSC))).\n\n  (** SSC_Prod is weakly initial. I.e., it has an arrow (not necessarily unique)\nto any other object. *)\n  Definition SSC_Prod_WI (c : C) :\n    (SSC_Prod –≻ c)%morphism\n    :=\n      (\n        (projT2 (SSC_jointly_weakly_initial SSC c))\n          ∘\n          (\n            Trans\n              (cone_edge SSC_Prod)\n              (projT1 (SSC_jointly_weakly_initial SSC c))\n          )\n      )%morphism\n  .\n\n  (** The constant function from endomorphisms of SSC_Prod that\nreturns SSC_Prod.  *)\n  Definition endomorph_const (h : (SSC_Prod –≻ SSC_Prod)%morphism) : C\n    :=\n      SSC_Prod\n  .\n\n  (** The product of SSC_Prod with endomorphisms as index. *)\n  Definition Endo_Prod : (Π endomorph_const)%object\n    :=\n      (LimitOf (Discr_Func endomorph_const)).\n\n\n  (** Cone to (Discr_Func endomorph_const) that maps to ids. *)\n  Program Definition Cone_Endo_Prod_ids : Cone (Discr_Func endomorph_const)\n    :=\n      {|\n        cone_apex :=\n          {|\n            FO := fun _ => SSC_Prod;\n            FA := fun _ _ _ => id\n          |};\n        cone_edge :=\n          {|\n            Trans := fun _ => id\n          |}\n      |}\n  .\n\n  (** Morphism that projects to ids. *)\n  Definition morph_to_Endo_Prod_ids : (SSC_Prod –≻ Endo_Prod)%morphism\n    :=\n      Trans (LRKE_morph_ex Endo_Prod Cone_Endo_Prod_ids) tt.\n\n  (** Cone to (Discr_Func endomorph_const) that maps to ids. *)\n  Program Definition Cone_Endo_Prod_endomorphs :\n    Cone (Discr_Func endomorph_const)\n    :=\n      {|\n        cone_apex :=\n          {|\n            FO := fun _ => SSC_Prod;\n            FA := fun _ _ _ => id\n          |};\n        cone_edge :=\n          {|\n            Trans := fun h => h\n          |}\n      |}\n  .\n\n  (** Morphism that projects to endomorphisms. *)\n  Definition morph_to_Endo_Prod_endomorphs : (SSC_Prod –≻ Endo_Prod)%morphism\n    :=\n      Trans (LRKE_morph_ex Endo_Prod Cone_Endo_Prod_endomorphs) tt.\n\n  Definition ids_endomorphs_equalizer :\n    Equalizer\n      morph_to_Endo_Prod_endomorphs\n      morph_to_Endo_Prod_ids\n    :=\n      Equalizer_as_Limit\n        morph_to_Endo_Prod_endomorphs\n        morph_to_Endo_Prod_ids\n        (LimitOf\n           (Equalizer_Producing_Func\n              morph_to_Endo_Prod_endomorphs\n              morph_to_Endo_Prod_ids)\n        )\n  .\n\n  (** ids_endomorphs_equalizer is weakly initial. I.e., it has an arrow \n(not necessarily unique) to any other object. *)\n  Definition ids_endomorphs_equalizer_WI (c : C) :\n    (ids_endomorphs_equalizer –≻ c)%morphism\n    :=\n      (SSC_Prod_WI c ∘ equalizer_morph ids_endomorphs_equalizer)%morphism\n  .\n\n  (** composing any endomorphism after equalizer morphism of \n      ids_endomorphs_equalizer is the same as the equalizer\n      morphism of ids_endomorphs_equalizer.\n*)\n  Theorem ids_endomorphs_equalizer_morph_neutralizes_endomorphs\n          (d : (SSC_Prod –≻ SSC_Prod)%morphism)\n    :\n      (d ∘ equalizer_morph ids_endomorphs_equalizer)%morphism\n      = equalizer_morph ids_endomorphs_equalizer\n  .\n  Proof.\n    assert (H :=\n              f_equal\n                (fun w => ((Trans Endo_Prod d) ∘ w)%morphism)\n                (equalizer_morph_com ids_endomorphs_equalizer)\n           ).\n    cbn -[equalizer_morph ids_endomorphs_equalizer Endo_Prod] in H.\n    unfold morph_to_Endo_Prod_endomorphs, morph_to_Endo_Prod_ids in H.\n    repeat rewrite assoc_sym in H.\n    assert (V :=\n           f_equal\n             (fun w :\n                    ((Functor_Ops.Functor_compose\n                        (Functor_To_1_Cat\n                           (Discr_Cat (SSC_Prod –≻ SSC_Prod)%morphism))\n                        Cone_Endo_Prod_endomorphs)\n                       –≻ Discr_Func endomorph_const)%nattrans\n              => Trans w d)\n             (cone_morph_com\n                (LRKE_morph_ex Endo_Prod Cone_Endo_Prod_endomorphs))\n        ).\n    cbn -[LRKE_morph_ex Endo_Prod] in V.\n    rewrite From_Term_Cat in V.\n    simpl_ids in V.\n    rewrite <- V in H.\n    clear V.\n    assert (V :=\n           f_equal\n             (fun w :\n                    ((Functor_Ops.Functor_compose\n                       (Functor_To_1_Cat\n                          (Discr_Cat (SSC_Prod –≻ SSC_Prod)%morphism))\n                       Cone_Endo_Prod_ids)\n                       –≻ Discr_Func endomorph_const)%nattrans\n              => Trans w d)\n             (cone_morph_com (LRKE_morph_ex Endo_Prod Cone_Endo_Prod_ids))\n        ).\n    cbn -[LRKE_morph_ex Endo_Prod] in V.\n    rewrite From_Term_Cat in V.\n    simpl_ids in V.\n    rewrite <- V in H.\n    clear V.\n    auto.\n  Qed.\n\n  Section equalizer_of_morphs_from_ids_endomorphs_equalizer_iso.\n    Context\n      {d : C}\n      (f g : (ids_endomorphs_equalizer –≻ d)%morphism)\n    .\n\n    (** Let's show ids_endomorphs_equalizer with V, we construct for any pair of\n         morphisms f, g : V –≻ d, their equalizer (U, e : U –≻ V).\n     *)\n    Definition equalizer_of_morphs_from_ids_endomorphs_equalizer\n      :\n        Equalizer f g\n      :=\n        Equalizer_as_Limit\n          f\n          g\n          (LimitOf (Equalizer_Producing_Func f g))\n    .\n\n    Theorem equalizer_of_morphs_from_ids_endomorphs_equalizer_iso_RI :\n      ((equalizer_morph (equalizer_of_morphs_from_ids_endomorphs_equalizer))\n         ∘\n         ((SSC_Prod_WI _)\n            ∘ (equalizer_morph ids_endomorphs_equalizer)))%morphism\n      =\n      id.\n    Proof.\n      apply (\n          mono_morphism_monomorphic\n            (@Equalizer_Monic _ _ _ _ _ ids_endomorphs_equalizer)\n        ).\n      rewrite id_unit_right.\n      repeat rewrite assoc_sym.\n      apply ids_endomorphs_equalizer_morph_neutralizes_endomorphs.      \n    Qed.\n\n    Theorem equalizer_of_morphs_from_ids_endomorphs_equalizer_iso_LI :\n      (((SSC_Prod_WI _) ∘ (equalizer_morph ids_endomorphs_equalizer))\n         ∘\n         (equalizer_morph (equalizer_of_morphs_from_ids_endomorphs_equalizer))\n      )%morphism\n      =\n      id.\n    Proof.\n      apply (\n          mono_morphism_monomorphic\n            (@Equalizer_Monic _ _ _ _ _\n                              equalizer_of_morphs_from_ids_endomorphs_equalizer)\n        ).\n      unfold Equalizer_Monic.\n      cbn [mono_morphism].\n      rewrite assoc_sym.\n      simpl_ids.\n      trivial.\n      apply equalizer_of_morphs_from_ids_endomorphs_equalizer_iso_RI.\n    Qed.\n    \n    (** Let's show ids_endomorphs_equalizer with V, then, for any pair of\n        morphisms f, g : V –≻ d, we have their equalizer (U, e : U –≻ V)\n        forms an isomorphism (U ≃ V).\n     *)\n    Program Definition equalizer_of_morphs_from_ids_endomorphs_equalizer_iso\n      :\n        ((equalizer_of_morphs_from_ids_endomorphs_equalizer)\n           ≃ ids_endomorphs_equalizer)%isomorphism\n      :=\n        {|\n          iso_morphism := equalizer_morph\n                            (equalizer_of_morphs_from_ids_endomorphs_equalizer);\n          inverse_morphism :=\n            ((SSC_Prod_WI _)\n               ∘ (equalizer_morph ids_endomorphs_equalizer))%morphism;\n          left_inverse :=\n            equalizer_of_morphs_from_ids_endomorphs_equalizer_iso_LI;\n          right_inverse :=\n            equalizer_of_morphs_from_ids_endomorphs_equalizer_iso_RI\n        |}\n    .\n\n  End equalizer_of_morphs_from_ids_endomorphs_equalizer_iso.\n\n  Local Obligation Tactic := idtac.\n  \n  Program Definition Complete_SSC_Initial : (𝟘_ C)%object\n    :=\n      {|\n        terminal := ids_endomorphs_equalizer;\n        t_morph := ids_endomorphs_equalizer_WI\n      |}\n  .\n\n  Next Obligation.\n  Proof.\n    intros d f g.\n    cbn -[ids_endomorphs_equalizer] in *.\n    assert (H :=\n              f_equal\n                (fun w => (f ∘ w)%morphism)\n                (equalizer_of_morphs_from_ids_endomorphs_equalizer_iso_RI f g)).\n    cbn -[ids_endomorphs_equalizer\n            equalizer_of_morphs_from_ids_endomorphs_equalizer] in H.\n    simpl_ids in H.\n    rewrite <- H.\n    clear H.\n    assert (H :=\n              f_equal\n                (fun w => (g ∘ w)%morphism)\n                (equalizer_of_morphs_from_ids_endomorphs_equalizer_iso_RI f g)).\n    cbn -[ids_endomorphs_equalizer\n            equalizer_of_morphs_from_ids_endomorphs_equalizer] in H.\n    simpl_ids in H.\n    etransitivity; [|apply H].\n    clear H.\n    repeat rewrite assoc_sym.\n    match goal with\n      [|- (((f ∘ ?A) ∘ ?B) ∘ ?C = _)%morphism] =>\n      apply (f_equal (fun w => ((w ∘ B) ∘ C)%morphism))\n    end.\n    apply (equalizer_morph_com\n             (equalizer_of_morphs_from_ids_endomorphs_equalizer f g)).\n  Qed.\n\nEnd Complete_SSC_Initial.\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/Adjunction/AFT/Solution_Set_Cond.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6917657832361691}}
{"text": "(* Exercise 104 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n(* de Morgan's conjunction law inverse variant *)\n\nTheorem exercise_104 : (A \\/ B) -> ~(~A /\\ ~B).\nProof.\nimp_i a1.\nneg_i (1=1) a2.\ndis_e (A \\/ B) a3 a3.\nhyp a1.\nneg_e (A).\ncon_e1 (~B).\nhyp a2.\nhyp a3.\nneg_e (B).\ncon_e2 (~A).\nhyp a2.\nhyp a3.\nlin_solve.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop104.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6917085178082168}}
{"text": "\nRequire Import Arith.\nRequire Import List.\n\nFixpoint rcons {X : Type} (s : list X) (x : X) :=\n  match s with\n  | nil => x :: nil\n  | y :: ys => y :: (rcons ys x)\n  end.\n\n\nFixpoint timechart_elem {A : Type} (x0 : nat*A) (s : list (nat*A)) (t : nat) :=\n  match s with\n  | nil =>\n    let (t', a) := x0 in (t, a)\n  | x :: xs =>\n    let (t', a) := x in\n    if t <? t' then let (t0, a0) := x0 in (t,a0) else timechart_elem x xs t\n  end.\n\n\nFixpoint timechart {A : Type} (x0 : nat*A) (s : list (nat*A)) (t : nat) :=\n  match t with\n  | S t' => rcons (timechart x0 s t') (timechart_elem x0 s t) \n  | O => timechart_elem x0 s O :: nil\n  end.\n\n", "meta": {"author": "morita-hm", "repo": "mbd_coq", "sha": "cd5cd9d9666721ca253b10a435007cac63bec194", "save_path": "github-repos/coq/morita-hm-mbd_coq", "path": "github-repos/coq/morita-hm-mbd_coq/mbd_coq-cd5cd9d9666721ca253b10a435007cac63bec194/MultiStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6917085178082168}}
{"text": "Require Import\n  ssreflect ssrfun ssrbool eqtype ssrnat seq path choice fintype fingraph finfun\n  bigop finset.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nSection regular.\n\nVariable (Sigma : finType).\n\nRecord DFA := {\n  DFA_states    : finType ;\n  DFA_start     : DFA_states ;\n  DFA_accept    : {set DFA_states} ;\n  DFA_delta     : {ffun DFA_states -> {ffun Sigma -> DFA_states}} }.\n\nRecord NFA := {\n  NFA_states    : finType ;\n  NFA_start     : NFA_states ;\n  NFA_accept    : {set NFA_states} ;\n  NFA_delta     : {ffun NFA_states -> {ffun Sigma -> {set NFA_states}}} }.\n\nRecord eNFA := {\n  eNFA_states   : finType ;\n  eNFA_start    : eNFA_states ;\n  eNFA_accept   : {set eNFA_states} ;\n  eNFA_epsilon  : {ffun eNFA_states -> {set eNFA_states}} ;\n  eNFA_delta    : {ffun eNFA_states -> {ffun Sigma -> {set eNFA_states}}} }.\n\nInductive RE : Type :=\n  | re_emptyset\n  | re_singleton of Sigma\n  | re_concat of RE & RE\n  | re_union of RE & RE\n  | re_star of RE.\n\nSection DFA.\n\nVariable (dfa dfa' : DFA).\n\nDefinition DFA_delta' (xs : seq Sigma) (q : DFA_states dfa) : DFA_states dfa :=\n  foldl (fun_of_fin (DFA_delta dfa)) q xs.\n\nDefinition DFA_match (xs : seq Sigma) : bool :=\n  DFA_delta' xs (DFA_start dfa) \\in DFA_accept dfa.\n\nDefinition NFA_of_DFA : NFA :=\n  Build_NFA\n    (DFA_start dfa)\n    (DFA_accept dfa)\n    [ffun q => [ffun x => [set DFA_delta dfa q x]]].\n\nDefinition DFA_reverse : eNFA :=\n  @Build_eNFA\n    (option_finType (DFA_states dfa))\n    None\n    [set Some (DFA_start dfa)]\n    [ffun q => if q is None then (@Some _) @: DFA_accept dfa else set0]\n    [ffun q => [ffun x =>\n      [set Some q' | q' in [pred q' | Some (DFA_delta dfa q' x) == q]]]].\n\nDefinition DFA_complement : DFA :=\n  Build_DFA (DFA_start dfa) (~: DFA_accept dfa) (DFA_delta dfa).\n\nDefinition DFA_intersection : DFA :=\n  @Build_DFA\n    (prod_finType (DFA_states dfa) (DFA_states dfa'))\n    (DFA_start dfa, DFA_start dfa')\n    [set (q, q') | q in DFA_accept dfa, q' in DFA_accept dfa']\n    [ffun q => [ffun x => (DFA_delta dfa q.1 x, DFA_delta dfa' q.2 x)]].\n\nEnd DFA.\n\nSection NFA.\n\nVariable (nfa : NFA).\n\nDefinition NFA_delta'\n  (xs : seq Sigma) (qs : {set NFA_states nfa}) : {set NFA_states nfa} :=\n  @foldl _ {set NFA_states nfa}\n    (fun qs' x => cover [set NFA_delta nfa q x | q in qs'])\n    qs xs.\n\nDefinition NFA_match (xs : seq Sigma) : bool :=\n  NFA_accept nfa :&: NFA_delta' xs [set NFA_start nfa] != set0.\n\nDefinition eNFA_of_NFA : eNFA :=\n  Build_eNFA (NFA_start nfa) (NFA_accept nfa) [ffun q => set0] (NFA_delta nfa).\n\nDefinition subset_construction_next qs x :=\n  cover [set NFA_delta nfa q x | q in pred_of_set qs].\n\nDefinition subset_construction_filter : pred {set NFA_states nfa} :=\n  connect\n    (fun q1 q2 => q2 \\in [set subset_construction_next q1 x | x in Sigma])\n    [set NFA_start nfa].\n\nLemma subset_construction_next_proof (qs : {set NFA_states nfa}) x :\n  subset_construction_filter qs ->\n  subset_construction_filter (subset_construction_next qs x).\nProof.\n  case/connectP => path1 H H0; apply/connectP.\n  exists (path1 ++ [:: subset_construction_next qs x]).\n  - by rewrite cat_path H /= andbT -H0; apply/imsetP; exists x.\n  - by rewrite last_cat.\nQed.\n\nDefinition DFA_of_NFA : DFA :=\n  @Build_DFA\n    [finType of {qs : {set NFA_states nfa} | subset_construction_filter qs}]\n    (exist subset_construction_filter [set NFA_start nfa] (connect0 _ _))\n    [set st | sval st :&: NFA_accept nfa != set0]\n    [ffun qs => [ffun x => exist subset_construction_filter\n     (subset_construction_next (sval qs) x)\n     (subset_construction_next_proof _ (proj2_sig qs))]].\n\nEnd NFA.\n\nSection eNFA.\n\nVariable (enfa : eNFA).\n\nDefinition eclose (q : eNFA_states enfa) : {set eNFA_states enfa} :=\n  [set q' | connect (fun x y => y \\in eNFA_epsilon enfa x) q q'].\n\nDefinition eNFA_delta'\n  (xs : seq Sigma) (qs : {set eNFA_states enfa}) : {set eNFA_states enfa} :=\n  @foldl _ {set eNFA_states enfa}\n    (fun qs' x => cover (eclose @: cover [set eNFA_delta enfa q x | q in qs']))\n    qs xs.\n\nDefinition eNFA_match (xs : seq Sigma) : bool :=\n  eNFA_accept enfa :&: eNFA_delta' xs (eclose (eNFA_start enfa)) != set0.\n\nDefinition subset_construction_next' qs x :=\n  cover (eclose @: cover [set eNFA_delta enfa q x | q in pred_of_set qs]).\n\nDefinition subset_construction_filter' : pred {set eNFA_states enfa} :=\n  connect\n    (fun q1 q2 : {set eNFA_states enfa} =>\n      q2 \\in (subset_construction_next' q1 @: setT))\n    (cover (eclose @: [set eNFA_start enfa])).\n\nLemma subset_construction_next_proof' (qs : {set eNFA_states enfa}) x :\n  subset_construction_filter' qs ->\n  subset_construction_filter' (subset_construction_next' qs x).\nProof.\n  case/connectP => path1 H H0; apply/connectP.\n  exists (path1 ++ [:: subset_construction_next' qs x]).\n  - by rewrite cat_path H /= andbT -H0; apply/imsetP; exists x.\n  - by rewrite last_cat.\nQed.\n\nDefinition DFA_of_eNFA :=\n  @Build_DFA\n    [finType of {qs : {set eNFA_states enfa} | subset_construction_filter' qs}]\n    (exist subset_construction_filter'\n     (cover (eclose @: [set eNFA_start enfa])) (connect0 _ _))\n    [set st | sval st :&: eNFA_accept enfa != set0]\n    [ffun qs => [ffun x => exist subset_construction_filter'\n     (subset_construction_next' (sval qs) x)\n     (subset_construction_next_proof' _ (proj2_sig qs))]].\n\nEnd eNFA.\n\nDefinition regular_language (P : seq Sigma -> Prop) : Prop :=\n  exists dfa, forall xs, DFA_match dfa xs <-> P xs.\n\nLemma NFA_of_DFA_eq dfa xs q :\n  [set @DFA_delta' dfa xs q] = @NFA_delta' (NFA_of_DFA dfa) xs [set q].\nProof.\n  rewrite /NFA_of_DFA /NFA_delta' /DFA_delta' /=.\n  elim: xs q => //= x xs IH q.\n  rewrite IH; f_equal.\n  apply setP => q'; rewrite inE cover_imset; apply/esym/bigcupP; case: ifP.\n  - by move/eqP => -> {q'}; exists q; rewrite ?ffunE inE.\n  - by move/eqP => H H0; apply: H; case: H0 => q''; rewrite inE;\n      move/eqP => H; subst q''; rewrite !ffunE inE; move/eqP.\nQed.\n\nLemma DFA_reverse_correct dfa xs (qs : {set DFA_states dfa}) :\n  @eNFA_delta' (DFA_reverse dfa) (rev xs) [set Some q | q in qs] =\n  [set Some q | q in predT & @DFA_delta' dfa xs q \\in qs].\nProof.\n  rewrite /DFA_reverse /eNFA_delta' /DFA_delta' /=.\n  elim: xs qs => /= [| x xs IH] qs.\n  - apply setP => q; apply/imsetP; case: ifP.\n    + by case/imsetP => q'; rewrite inE => H H0; subst q; exists q'.\n    + by move/negP => H H0; apply: H; case: H0 => q' H H0; subst q;\n        apply/imsetP; exists q' => //; rewrite inE.\n  - rewrite rev_cons -cats1 foldl_cat /= {}IH cover_imset.\n    apply setP => q; apply/bigcupP; case: ifP.\n    + case/imsetP => q'; rewrite inE => H H0; subst q; exists (Some q').\n      * rewrite cover_imset; apply/bigcupP; exists (Some (DFA_delta dfa q' x)).\n        - by apply/imsetP; exists (DFA_delta dfa q' x) => //; rewrite inE.\n        - by rewrite !ffunE; apply/imsetP; exists q' => //; rewrite inE.\n      * by rewrite /eclose /= inE connect0.\n    + move/negP => H H0; apply: H; case: H0 => q'; rewrite cover_imset;\n        case/bigcupP => q''; rewrite !ffunE; case/imsetP => q''';\n        rewrite inE => H H0; subst q''; case/imsetP => q''; rewrite inE;\n        case/eqP => H0 H1; subst q''' q'; rewrite /eclose /= inE;\n        case/connectP; case; last by move => ? ? /=; rewrite ffunE inE.\n      by move => /= _ H0; subst q; apply/imsetP; exists q'' => //; rewrite inE.\nQed.\n\nLemma DFA_complement_correct dfa xs :\n  DFA_match dfa xs != DFA_match (DFA_complement dfa) xs.\nProof. by rewrite /DFA_match /DFA_complement negb_eqb inE addbN addbb. Qed.\n\nLemma DFA_intersection_correct dfa dfa' xs :\n  DFA_match dfa xs && DFA_match dfa' xs =\n  DFA_match (DFA_intersection dfa dfa') xs.\nProof.\n  rewrite /DFA_intersection /DFA_match /DFA_delta' /=.\n  elim: xs (DFA_start dfa) (DFA_start dfa') => /=.\n  - move => q q'; apply/esym/imset2P; case: ifP.\n    + by case/andP => H H0; apply: (Imset2spec H H0 erefl).\n    + by move/negP => H H0; apply: H;\n        case: H0 => q'' q''' H H0 [H1 H2]; subst; rewrite H H0.\n  - by move => x xs IH qs qs'; rewrite !ffunE /= -IH.\nQed.\n\nLemma eNFA_of_NFA_eq nfa xs qs :\n  @NFA_delta' nfa xs qs = @eNFA_delta' (eNFA_of_NFA nfa) xs qs.\nProof.\n  elim: xs qs => //= x xs IH qs; rewrite {}IH; f_equal.\n  apply/esym/setP; rewrite cover_imset => q; apply/bigcupP; case: ifP.\n  - by move => H; exists q => //; rewrite /eclose /= inE connect0.\n  - move/negP => H H0; apply: H; case: H0 => q' H; rewrite /eclose /= inE;\n      case/connectP; case; last by move => ? ? /=; rewrite ffunE inE.\n    by move => /= _ H0; subst q'.\nQed.\n\nLemma DFA_of_NFA_eq nfa xs (qs : {qs | subset_construction_filter qs}) :\n  @NFA_delta' nfa xs (sval qs) = sval (@DFA_delta' (DFA_of_NFA nfa) xs qs).\nProof. by elim: xs qs => //= x xs IH [qs H] /=; rewrite !ffunE /= -IH. Qed.\n\nLemma DFA_of_eNFA_eq enfa xs (qs : {qs | subset_construction_filter' qs}) :\n  @eNFA_delta' enfa xs (sval qs) = sval (@DFA_delta' (DFA_of_eNFA enfa) xs qs).\nProof. by elim: xs qs => //= x xs IH [qs H] /=; rewrite !ffunE /= -IH /=. Qed.\n\nDefinition DFA_minimization dfa : DFA :=\n  DFA_of_eNFA (DFA_reverse (DFA_of_eNFA (DFA_reverse dfa))).\n\nEnd regular.\n", "meta": {"author": "pi8027", "repo": "sandpit", "sha": "4d2b2f2a1d4f63ea6b77c0d9fb063c9d391b98cb", "save_path": "github-repos/coq/pi8027-sandpit", "path": "github-repos/coq/pi8027-sandpit/sandpit-4d2b2f2a1d4f63ea6b77c0d9fb063c9d391b98cb/coq/regular.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6916975072937309}}
{"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(** * ugregex_dec: simple decision procedure for untyped generalised regular expressions *)\n\n(** We implement a rather basic algorithm consisting in trying to\n   build a bisimulation on-the-fly, using partial derivatives.\n   \n   We prove the correctness of this algorithm, but not completeness\n   (\"it merely let you sleep better\" according to Krauss and Nipkow).\n   \n   This very simple algorithm seems to be sufficient for reasonable\n   expressions; we plan to improve it to be able to handle larger\n   ones. *)\n\nRequire Import lset kat positives sums glang boolean comparisons powerfix.\nRequire Export ugregex.\nSet Implicit Arguments.\n\n\nSection l.\nVariable Pred: nat.\nNotation Sigma := positive.\nNotation Atom := (ord (pow2 Pred)).\nNotation tt := ugregex_tt. \nNotation ugregex := (ugregex_monoid_ops Pred tt tt).\nNotation uglang := (glang_kat_ops Pred Sigma traces_tt traces_tt).\nNotation lang := (@lang Pred).\n\nLtac fold_ugregex_type := change (@ugregex.ugregex Pred) with (@car ugregex) in *.\nLtac fold_ugregex := ra_fold ugregex_monoid_ops tt; fold_ugregex_type.\n\n(** * Partial derivatives *)\n\n(** reversed product *)\nNotation tod e := (fun f => u_dot f e) (only parsing).\n\n(** [pderiv a i e] returns the set of partial derivatives of [e] along\n   transition [(a,i)] (since we work with KAT regular expressions,\n   labels are composed of an atom together with a letter) *)\nFixpoint pderiv a i (e: ugregex): list ugregex :=\n  match e with\n    | u_prd _ => []\n    | u_var _ j => if eqb_pos i j then [u_one _] else []\n    | u_pls e f => union (pderiv a i e) (pderiv a i f)\n    | u_dot e f => \n        if epsilon a e then union (map (tod f) (pderiv a i e)) (pderiv a i f)\n        else map (tod f) (pderiv a i e)\n    | u_itr e => map (tod (u_str e)) (pderiv a i e)\n  end.\n\n(** [epsilon] was defined in [ugregex], \n   we now to extend both notions to sets of expressions, homomorphically: *)\n\nDefinition epsilon' a (l: list ugregex): bool :=\n  fold_right (fun e b => b ||| epsilon a e) false l.\n\nDefinition pderiv' a i (l: list ugregex): list ugregex :=\n  fold_right (fun e => union (pderiv a i e)) [] l.\n\n\n(** specification of [epsilon'] *)\nLemma epsilon'_eq a l: epsilon a (sup id l) == epsilon' a l.\nProof.\n  induction l. reflexivity. simpl.\n  rewrite <- IHl. unfold id. \n  rewrite <-2Bool.orb_lazy_alt. apply Bool.orb_comm.\nQed.\n\n(** correctness of partial derivatives *)\nLemma deriv_eq a i e: deriv a i e == sup id (pderiv (set.mem a) i e).\nProof.\n  induction e; simpl; fold_ugregex.\n   case eqb_pos. 2: reflexivity. now rewrite sup_singleton. \n   reflexivity.\n   rewrite union_app, sup_app. now apply cup_weq.\n   assert (H: deriv a i e1 * e2 == sup id (map (tod e2) (pderiv (set.mem a) i e1))).\n    rewrite sup_map. setoid_rewrite <-(dotsumx (X:=ugregex_monoid_ops _)).\n    now apply dot_weq.\n   case epsilon.\n    rewrite union_app, sup_app.\n    setoid_rewrite dot1x. now apply cup_weq.\n    setoid_rewrite dot0x. now rewrite cupxb.\n   rewrite sup_map. setoid_rewrite <-(dotsumx (X:=ugregex_monoid_ops _)).\n    now apply dot_weq.\nQed.\n\nLemma deriv'_eq a i l: deriv a i (sup id l) == sup id (pderiv' (set.mem a) i l).\nProof.\n  induction l. reflexivity. simpl (sup _ _).\n  rewrite union_app, sup_app.\n  apply cup_weq. apply deriv_eq. assumption.\nQed.\n\n(** Kleene variables of an expression *)\nFixpoint vars (e: ugregex) : list _ :=\n  match e with\n    | u_prd _ => []\n    | u_var _ i => [i]\n    | u_pls e f | u_dot e f => union (vars e) (vars f)\n    | u_itr e => vars e\n  end.\n\n(** partial derivatives do not increase the set of Kleene variables *)\nLemma deriv_vars a i (e: ugregex): \\sup_(x\\in pderiv a i e) vars x <== vars e. \nProof.\n  induction e; simpl pderiv; simpl vars. \n   case eqb_pos; apply leq_bx. \n   apply leq_bx. \n   rewrite 2union_app, sup_app. now apply cup_leq.\n   setoid_rewrite union_app at 2.\n   assert (H: \\sup_(x\\in map (tod e2) (pderiv a i e1)) vars x <== vars e1 ++ vars e2).\n    rewrite sup_map. simpl vars. setoid_rewrite union_app. rewrite supcup. \n    apply cup_leq. assumption. now apply leq_supx.\n   case epsilon. rewrite union_app, sup_app, H. hlattice. assumption. \n   rewrite sup_map. simpl vars. setoid_rewrite union_app. rewrite supcup. \n    apply leq_cupx. assumption. now apply leq_supx.\nQed.\n \nLemma deriv'_vars a i l: \\sup_(x\\in pderiv' a i l) vars x <== sup vars l.\nProof.\n  induction l. reflexivity. setoid_rewrite union_app. rewrite sup_app. \n  apply cup_leq. apply deriv_vars. assumption.\nQed.\n\n\n(** deriving an expression w.r.t. a letter it does not contain necessarily gives [0] *)\nLemma deriv_out a i e I: vars e <== I -> ~In i I -> deriv a i e == 0. \nProof.\n  intros He Hi. induction e; simpl deriv; simpl vars in He; fold_ugregex. \n   case eqb_spec. 2: reflexivity. intros <-. apply Hi in He as []. now left. \n   reflexivity. \n   rewrite union_app in He. \n    rewrite IHe1, IHe2 by (rewrite <-He; lattice). apply cupI. \n   rewrite union_app in He. \n    rewrite IHe1, IHe2 by (rewrite <-He; lattice). rewrite dot0x, dotx0. apply cupI. \n   rewrite IHe by assumption. apply dot0x. \nQed.\n\n\n(** we need binary relations on sets of expressions, we represent them\n   as lists of pairs (this could easily be optimised) *)\nDefinition rel_mem (p: list ugregex * list ugregex) := existsb (eqb p).\nNotation rel_insert p rel := (p::rel).\nNotation rel_empty := [].\n(* OPT *)\n(* Definition rel_mem := trees.mem (pair_compare (list_compare compare)).  *)\n(* Definition rel_insert := trees.insert (pair_compare (list_compare compare)).  *)\n(* Notation rel_empty := (@trees.L _) *)\n\nLemma rel_mem_spec p rel: reflect (In p rel) (rel_mem p rel).\nProof.\n  induction rel. constructor. tauto.\n  simpl rel_mem. case eqb_spec. \n  intros <-. constructor. now left.\n  case IHrel; constructor. now right. intros [?|?]; congruence.\nQed.\n\n\n(** * Main loop for the on-the-fly bisimulation algorithm *)\n\n(** [epsilon'] and [deriv'] provide us with a (generalised) DFA whose\n   states are sets of generalised expressions ([list ugregex]). We\n   simply try compute bisimulations in this DFA. *)\n\nSection a.\n\n(** we assume a set of Kleene variable, and a set of atoms; the\n   following algorithm tries to compute bisimulations w.r.t. those\n   sets. *)\nVariable I: list positive.\nVariable A: list (ord Pred -> bool).\n\nDefinition obind X Y (f: X -> option Y) (x: option X): option Y := \n  match x with Some x => f x | _ => None end.\n\nFixpoint ofold X Y (f: X -> Y -> option Y) (l: list X) (y: Y): option Y :=\n  match l with\n    | [] => Some y\n    | x::q => obind (f x) (ofold f q y)\n  end.\n\n(** [loop_aux e f a todo] checks the accepting status of [e] and [f] along [a], \n   - if a mismatch is found, we can stop (a counter example has bee found)\n   - otherwise, it inserts all derivatives of the pair [(e,f)] along [{a}*I] into [todo] *)\nDefinition loop_aux e f := \n  fun a todo => \n    if eqb_bool (epsilon' a e) (epsilon' a f) \n    then Some (fold_right (fun i => cons (pderiv' a i e, pderiv' a i f)) todo I)\n    else None.\n\n(** [ofold (loop_aux e f) A todo] does the same, for all [a\\in A] *)\n\n(** [loop n rel todo] is the main loop of the algorithm:\n   it tries to prove that all pairs in [todo] are bisimilar, assuming\n   that those in [rel] are bisimilar.\n   - if a pair of [todo] was already in [rel], it can be skipped;\n   - otherwise, its accepting status is checked, all derivatives are\n     inserted in [todo], and the pair is added to [rel]\n   The number of iterations is bounded by [2^n], using the [powerfix] operator. *)\nDefinition loop n := powerfix n (fun loop rel todo =>\n  match todo with\n    | [] => Some true\n    | (e,f)::todo => \n      if rel_mem (e,f) rel then loop rel todo else \n        match ofold (loop_aux e f) A todo with\n          | Some todo => loop (rel_insert (e,f) rel) todo\n          | None => Some false\n        end\n    end\n) (fun _ _ => None).\n\n\n\n\n(** * Correctness of the main loop *)\n\n(** [prog] is a predicate on binary relations:\n\n   [prog rel (rel++todo)] is the invariant of the main loop *)\n\nDefinition prog R S :=\n  forall e f, In (e,f) R -> sup vars (e++f) <== I /\\\n    forall a, In a A -> epsilon' a e = epsilon' a f /\\ \n      forall i, In i I -> In (pderiv' a i e, pderiv' a i f) S.\n\nLemma prog_cup_x R R' S: prog R S -> prog R' S -> prog (R++R') S.\nProof. intros H H' e f Hef. apply in_app_iff in Hef as [?|?]. now apply H. now apply H'. Qed.\n\nLemma prog_x_leq R S S': prog R S -> S <== S' -> prog R S'.\nProof. \n  intros H H' e f Hef. apply H in Hef as [? Hef]. \n  split. assumption. split. now apply Hef. intros. now apply H', Hef. \nQed.\n\nDefinition below_I todo := forall e f, In (e,f) todo -> sup vars (e++f) <== I.\n\n(** specification of the inner loop *)\n\nLemma loop_aux_spec e f a todo todo': \n  below_I ((e,f)::todo) ->\n  loop_aux e f a todo = Some todo' -> \n  epsilon' a e = epsilon' a f /\\\n  todo <== todo' /\\\n  below_I todo' /\\\n  forall i, In i I -> In (pderiv' a i e, pderiv' a i f) todo'.\nProof.\n  unfold loop_aux. case eqb_bool_spec. 2: discriminate. intros Heps Hvars E. \n  split. assumption. injection E. clear E Heps. revert todo'. \n  induction I as [|i J IH]; simpl fold_right; intro todo'. \n   intros <-. split. reflexivity. split. intros ? ? ?. apply Hvars; now right. intros _ []. \n   intro E. destruct todo' as [|p todo']. discriminate. \n   injection E. intros H <-. clear E. apply IH in H as [H1 [H2 H3]]. clear IH. \n   split. fold_cons. rewrite <- H1. lattice.\n   split. intros ? ? [E|H]. \n    injection E; intros <- <-. rewrite sup_app, 2deriv'_vars, <-sup_app. apply Hvars. now left.\n    now apply H2. \n   intros b [<-|Hb]. now left. right. now apply H3. \nQed.\n\nLemma fold_loop_aux_spec e f todo: forall todo',\n  below_I ((e,f)::todo) ->\n  ofold (loop_aux e f) A todo = Some todo' -> \n  todo <== todo' /\\\n  below_I todo' /\\\n  forall a, In a A -> epsilon' a e = epsilon' a f /\\\n  forall i, In i I -> In (pderiv' a i e, pderiv' a i f) todo'.\nProof.\n  induction A as [|b B IH]; simpl ofold; intros todo'.\n   intros Hvars H. injection H. intros <-. split. reflexivity. \n   split. intros ? ? ?. apply Hvars. now right. intros _ []. \n  unfold obind. fold_ugregex_type. case_eq (ofold (X:=ord Pred -> bool) (loop_aux e f) B todo). \n   2: discriminate. \n  intros todo'' Htodo'' Hvars Htodo'.\n  apply IH in Htodo'' as [Htodo''_leq [Hvars' Htodo'']]. 2: assumption. clear IH. \n  apply loop_aux_spec in Htodo' as (Heps&Htodo'_leq&Hvars''&Htodo'). \n  split. etransitivity; eassumption. \n  split. assumption. \n  intros a [<-|Ha]. now split. \n  apply Htodo'' in Ha as [Haeps Ha]. split. assumption. \n  intros. now apply Htodo'_leq, Ha. \n  intros ? ? [E|?]. injection E; intros <- <-. apply Hvars; now left. now apply Hvars'.\nQed.\n\nLemma In_cons X (a: X) l: In a l -> [a]++l <== l. \nProof. now intros ? ? [<-|?]. Qed.\n\n(** specification of the outer loop *)\n\nLemma prog_loop n: forall rel todo,\n  loop n rel todo = Some true ->\n  prog rel (rel++todo) -> \n  below_I todo ->\n  exists rel', rel++todo <== rel' /\\ prog rel' rel'.\nProof.\n  (* TODO: use powerfix_invariant *)\n  unfold loop. rewrite powerfix_linearfix. generalize (pow2 n). clear n. intro n.\n  induction n; intros rel todo Hloop Hrel Hvars. discriminate. \n  simpl in Hloop. destruct todo as [|[e f] todo]. \n   exists rel. split. now rewrite <- app_nil_end. now rewrite <-app_nil_end in Hrel. \n   revert Hloop. case rel_mem_spec. \n   intros Hef Hloop. apply IHn in Hloop as (rel'&H1&H2).\n    eexists. split. 2: eassumption. \n     rewrite <- H1. rewrite <-(In_cons Hef) at 2. fold_cons. lattice. \n    eapply prog_x_leq. apply Hrel. \n     rewrite <-(In_cons Hef) at 2. fold_cons. lattice. \n    intros ? ? ?. apply Hvars. now right. \n   intros _. fold_ugregex_type. case_eq (ofold (X:=ord Pred -> bool) (loop_aux e f) A todo). \n    2: discriminate. \n   intros todo' Htodo' Hloop. \n   apply fold_loop_aux_spec in Htodo' as [Htodo' [Hvars' Hef]]. 2: assumption.\n   destruct (IHn _ _ Hloop) as (rel'&Hrel'&Hrel''). 2: assumption. \n   clear - Hef Hvars Hvars' Hrel Htodo'. \n   apply (@prog_cup_x [_]). eapply prog_x_leq. \n    intros ? ? [E|[]]. injection E; intros <- <-; clear E. \n    split. apply Hvars. now left. apply Hef. lattice.\n   eapply prog_x_leq. apply Hrel. rewrite <- Htodo'. fold_cons. lattice. \n   eexists. split. 2: eassumption. rewrite <-Hrel', <-Htodo'. fold_cons. lattice.\nQed.\n\nEnd a.\n\nExisting Instance lang'_weq.\n\n(** correctness of the bisimulation proof method, at the abstract level *)\n\nLemma prog_correct I l rel: \n  (forall a, In (set.mem a) l) ->\n  prog I l rel rel -> below_I I rel -> \n  forall e f, In (e,f) rel -> sup lang e == sup lang f.\nProof.\n  intros Hl Hrel Hvars e f Hef. \n  rewrite <-2lang_sup, 2lang_lang'. \n  intro w. revert e f Hef. induction w; simpl lang'; intros e f Hef. \n  - apply Hrel in Hef as [_ Hef]. \n    rewrite 2epsilon'_eq. destruct (Hef _ (Hl a)) as [-> _]. reflexivity. \n  - destruct (fun H => In_dec H i I) as [Hi|Hi]. decide equality.\n    etransitivity. apply lang'_weq. apply deriv'_eq. \n    etransitivity. 2: apply lang'_weq; symmetry; apply deriv'_eq. \n    apply IHw. apply Hrel. assumption. apply Hl. assumption. \n    clear IHw. revert w. apply lang'_weq. rewrite 2deriv_sup.\n    rewrite 2sup_b. reflexivity. \n     intros f' Hf. eapply deriv_out. 2: eassumption. \n      etransitivity. 2: apply Hvars. 2: apply Hef. apply leq_xsup. apply in_app_iff. now right. \n     intros e' He. eapply deriv_out. 2: eassumption. \n      etransitivity. 2: apply Hvars. 2: apply Hef. apply leq_xsup. apply in_app_iff. now left. \nQed.\n\n(** * Final algorithm, correctness *)\n\n(** the final algorithm is obtained by callign the main loop with\n   appropriate arguments *)\n\nDefinition eqb_kat (e f: ugregex) :=\n  let atoms := map (@set.mem _) (seq _) in\n  let vars := vars (e+f) in\n    loop vars atoms 1000 rel_empty [([e],[f])]%list.\n(* stated as this, the algorithm is not complete: we would need to\n   replace 1000 with the size of [e+f]... bzzz *)\n\n(** correctness of the algorithm *)\n\nTheorem eqb_kat_correct e f: eqb_kat e f = Some true -> e == f. \nProof.\n  unfold eqb_kat. intro H. apply prog_loop in H as [rel [Hef Hrel]]. \n  2: intros _ _ []. \n  2: simpl vars; intros ? ? [E|[]]; injection E; intros <- <-; \n      rewrite union_app, sup_app, 2sup_singleton; reflexivity.\n  eapply prog_correct in Hrel. \n   2: intro; apply in_map, in_seq. \n   3: apply Hef; now left.\n  rewrite 2sup_singleton in Hrel. assumption. \n  intros ? ? ?. now apply Hrel. \nQed.\n\nEnd l. \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/ugregex_dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6916974964739327}}
{"text": "(* infotheo (c) AIST. R. Affeldt, M. Hagiwara, J. Senizergues. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrfun ssrnat.\nRequire Import Reals Fourier.\nRequire Import Reals_ext Ranalysis_ext Rssr.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope R_scope.\n\nLemma ln_2_pos : 0 < ln 2.\nProof. rewrite -ln_1; apply ln_increasing; fourier. Qed.\n\nLemma ln_2_neq0 : ln 2 <> 0.\nProof. by apply nesym, Rlt_not_eq, ln_2_pos. Qed.\n\nLemma ln_increasing_le a b : 0 < a -> a <= b -> ln a <= ln b.\nProof.\nmove=> Ha.\ncase/Rle_lt_or_eq_dec; last by move=> ->; apply Rle_refl.\nmove/(ln_increasing _ _ Ha)/Rlt_le => a_b //.\nQed.\n\nLemma exp_le_inv x y : exp x <= exp y -> x <= y.\nProof.\ncase/Rle_lt_or_eq_dec; [move/exp_lt_inv => ?; by apply Rlt_le |\n  move/exp_inv => ->; by apply Rle_refl].\nQed.\n\nLemma exp_pow n : forall k, exp (INR k * n) = (exp n) ^ k.\nProof.\nelim => [|k IH].\nby rewrite Rmult_0_l exp_0.\nby rewrite S_INR mulRDl mul1R exp_plus IH mulRC.\nQed.\n\n(** * Log base 2 *)\n\n(* NB: log is 0 for input < 0 *)\nDefinition log x := ln x / ln 2.\n\nLemma log_1 : log 1 = 0.\nProof. by rewrite /log ln_1 /Rdiv Rmult_0_l. Qed.\n\nLemma log_2 : log 2 = 1.\nProof. rewrite /log /Rdiv -Rinv_r_sym //; by apply ln_2_neq0. Qed.\n\nLemma log_exp1_Rle_0 : 0 <= log (exp 1).\nProof. rewrite /log ln_exp /Rdiv ; apply Rle_mult_inv_pos ; [fourier | apply ln_2_pos]. Qed.\n\nLemma log_mult x y : 0 < x -> 0 < y -> log (x * y) = log x + log y.\nProof. move=> *; rewrite /log ln_mult //; field; by apply ln_2_neq0. Qed.\n\nLemma log_Rinv x : 0 < x -> log (/ x) = - log x.\nProof. move=> ?; rewrite /log ln_Rinv //; field; by apply ln_2_neq0. Qed.\n\nLemma log_increasing_le a b : 0 < a -> a <= b -> log a <= log b.\nProof.\nmove=> Ha.\ncase/Rle_lt_or_eq_dec; last by move=> ->; apply Rle_refl.\nmove/(ln_increasing _ _ Ha)/Rlt_le => a_b.\napply Rmult_le_compat_r => //; by apply Rlt_le, Rinv_0_lt_compat, ln_2_pos.\nQed.\n\nLemma log_increasing a b : 0 < a -> a < b -> log a < log b.\nProof.\nmove=> Ha a_b.\nrewrite /log.\napply Rmult_lt_compat_r; last by apply ln_increasing.\nby apply Rinv_0_lt_compat, ln_2_pos.\nQed.\n\nLemma log_inv x y : 0 < x -> 0 < y -> log x = log y -> x = y.\nProof.\nmove=> Hx Hy.\nrewrite /log /Rdiv => H.\napply Rmult_eq_reg_r in H.\nby apply ln_inv in H.\nby apply Rinv_neq_0_compat, ln_2_neq0.\nQed.\n\nLemma log_lt_inv x y : 0 < x -> 0 < y -> log x < log y -> x < y.\nProof.\nmove=> Hx Hy.\nrewrite /log /Rdiv.\nhave H : 0 < / ln 2 by apply Rinv_0_lt_compat, ln_2_pos.\nmove/(Rmult_lt_reg_r _ _ _ H) => {H}?.\nby apply ln_lt_inv.\nQed.\n\nLemma log_le_inv x y : 0 < x -> 0 < y -> log x <= log y -> x <= y.\nProof.\nmove=> Hx Hy.\ncase/Rle_lt_or_eq_dec; first by by move/(log_lt_inv Hx Hy)/Rlt_le.\nmove/(log_inv Hx Hy) => ->; by apply Rle_refl.\nQed.\n\nLemma derivable_pt_log : forall x : R, 0 < x -> derivable_pt log x.\nmove=> x Hx.\nrewrite /log.\nrewrite /Rdiv.\napply derivable_pt_mult.\nby apply derivable_pt_ln.\napply derivable_pt_const.\nDefined.\n\nLemma derive_pt_log\n     : forall (a : R) (Ha : 0 < a), derive_pt log a (derivable_pt_log Ha) = / a * / ln 2.\nmove=> a Ha.\nrewrite /log.\nrewrite /Rdiv.\nrewrite derive_pt_mult.\nrewrite derive_pt_const.\nrewrite derive_pt_ln.\nrewrite Rmult_0_r Rplus_0_r.\nreflexivity.\nDefined.\n\n(** * 2 ^ x *)\n\nDefinition exp2 (x : R) := exp (x * ln 2).\n\nLemma exp2_pos x : 0 < exp2 x.\nProof. rewrite /exp2; by apply exp_pos. Qed.\n\nLemma exp2_not_0 l : exp2 l <> 0.\nProof. apply not_eq_sym, Rlt_not_eq ; exact (exp2_pos l). Qed.\n\nLemma exp2_0 : exp2 0 = 1.\nProof. by rewrite /exp2 Rmult_0_l exp_0. Qed.\n\nLemma exp2_plus x y : exp2 (x + y) = exp2 x * exp2 y.\nProof. by rewrite /exp2 mulRDl exp_plus. Qed.\n\nLemma exp2_pow2 : forall m, exp2 (INR m) = INR (expn 2 m).\nProof.\nelim => [|m IH]; first by rewrite /exp2 Rmult_0_l exp_0.\nrewrite S_INR exp2_plus expnS mult_INR IH /exp2 Rmult_1_l exp_ln; [by rewrite mulRC | fourier].\nQed.\n\nLemma exp2_pow n k : exp2 (INR k * n) = (exp2 n) ^ k.\nProof. by rewrite /exp2 -mulRA exp_pow. Qed.\n\nLemma exp2_Ropp x : exp2 (- x) = / exp2 x.\nProof. by rewrite /exp2 Ropp_mult_distr_l_reverse exp_Ropp. Qed.\n\nLemma exp2_le_inv x y : exp2 x <= exp2 y -> x <= y.\nProof.\nrewrite /exp2 => HH.\napply Rmult_le_reg_l with (ln 2).\nby apply ln_2_pos.\napply exp_le_inv in HH.\nby rewrite mulRC -(mulRC y).\nQed.\n\nLemma exp2_increasing x y : x < y -> exp2 x < exp2 y.\nProof.\nmove=> x_y.\nrewrite /exp2.\napply exp_increasing, Rmult_lt_compat_r => //.\nby apply ln_2_pos.\nQed.\n\nLemma exp2_le_increasing x y : x <= y -> exp2 x <= exp2 y.\nProof.\ncase/Rle_lt_or_eq_dec.\nmove/exp2_increasing => x_y; by apply Rlt_le.\nmove=> ->; by apply Rle_refl.\nQed.\n\nLemma exp2_log x : 0 < x -> exp2 (log x) = x.\nProof.\nmove=> Hx.\nrewrite /exp2 /log /Rdiv mulRC mulRA Rinv_r_simpl_m.\nby rewrite exp_ln.\nby apply ln_2_neq0.\nQed.\n\nLemma log_exp2 x : log (exp2 x) = x.\nProof.\nrewrite /log /exp2 ln_exp /Rdiv -mulRA mulRC Rinv_r_simpl_r //.\nby apply ln_2_neq0.\nQed.\n\nLocal Open Scope Rb_scope.\n\nLemma Rle_exp2_log1_L a b : 0 < b -> exp2 a <b= b = (a <b= log b).\nProof.\nmove=> Hb; move H1 : (_ <b= _ ) => [|] /=.\n- move/RleP in H1.\n  have {H1}H1 : a <= log b.\n    rewrite (_ : a = log (exp2 a)); last by rewrite log_exp2.\n    apply log_increasing_le => //; by apply exp2_pos.\n  move/RleP in H1; by rewrite H1.\n- move H2 : (_ <b= _ ) => [|] //=.\n  move/RleP in H2.\n  rewrite -(log_exp2 a) in H2.\n  apply log_le_inv in H2 => //; last by apply exp2_pos.\n  move/RleP in H2.\n  by rewrite H2 in H1.\nQed.\n\nLemma Rle_exp2_log2_R b c : 0 < b -> b <b= exp2 c = (log b <b= c).\nProof.\nmove=> Hb; move H1 : (_ <b= _ ) => [|] /=.\n- move/RleP in H1.\n  have {H1}H1 : log b <= c.\n    rewrite (_ : c = log (exp2 c)); last by rewrite log_exp2.\n    apply log_increasing_le => //; by apply exp2_pos.\n  by move/RleP in H1.\n- move H2 : (_ <b= _ ) => [|] //=.\n  move/RleP in H2.\n  rewrite -(log_exp2 c) in H2.\n  apply log_le_inv in H2 => //; last by apply exp2_pos.\n  move/RleP in H2.\n  by rewrite H2 in H1.\nQed.\n\nLemma Rle2_exp2_log a b c : 0 < b ->\n  exp2 a <b= b <b= exp2 c = (a <b= log b <b= c).\nProof.\nmove=> Hb; move H1 : (_ <b= _ ) => [|] /=.\n- rewrite Rle_exp2_log1_L // in H1.\n  by rewrite H1 /= Rle_exp2_log2_R.\n- move H2 : (_ <b= _ ) => [|] //=.\n  rewrite -Rle_exp2_log1_L // in H2.\n  by rewrite H2 in H1.\nQed.\n\nLemma exists_frac_part (P : nat -> Prop) : (exists n, P n) ->\n  forall num den, (0 < num)%nat -> (0 < den)%nat ->\n  (forall n m, (n <= m)%nat -> P n -> P m) ->\n  exists n, P n /\\\n    frac_part (exp2 (INR n * (log (INR num) / INR den))) = 0.\nProof.\ncase=> n Pn num den Hden HP.\nexists (n * den)%nat.\nsplit.\n  apply H with n => //.\n  by rewrite -{1}(muln1 n) leq_mul2l HP orbC.\nrewrite mult_INR -mulRA (mulRA (INR den)) Rinv_r_simpl_m; last first.\n  apply not_0_INR.\n  move=> ?; by subst den.\nrewrite exp2_pow exp2_log; last first.\n  apply lt_0_INR.\n  by apply/ltP.\nby apply frac_part_pow, frac_part_INR.\nQed.\n", "meta": {"author": "johnbender", "repo": "shannon", "sha": "552c66f7c76ad687430f4fb8122a2a2b94b741ee", "save_path": "github-repos/coq/johnbender-shannon", "path": "github-repos/coq/johnbender-shannon/shannon-552c66f7c76ad687430f4fb8122a2a2b94b741ee/log2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.6916209418970622}}
{"text": "(* \nCopyright 2022 Anthony Johnson\n\nPermission is hereby granted, free of charge, to any person obtaining a copy \nof this software and associated documentation files (the \"Software\"), to deal \nin the Software without restriction, including without limitation the rights \nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell \ncopies of the Software, and to permit persons to whom the Software is furnished \nto do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in \nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, \nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES \nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. \nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR \nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR \nTHE USE OR OTHER DEALINGS IN THE SOFTWARE.\n(*\n*)\n\n  This file contains code that proves various theorems from the\n  Metamath site (http://us.metamath.org/) in the Coq Proof Assistant \n  (https://coq.inria.fr/)\n*)\n\n(* http://us.metamath.org/ileuni/mpd.html *)\n\nTheorem mpd : forall P Q R: Prop, ((P -> Q) /\\ (P -> (Q -> R))) -> (P -> R).\nProof.\n    intros P.\n    intros Q.\n    intros R.\n    intros h1.\n    destruct h1.\n    intros h2.\n    apply H0.\n    exact h2.\n    apply H.\n    exact h2.\nQed.\n\nPrint mpd.\n\nTheorem mpd2 : forall P Q R: Prop, ((P -> Q) /\\ (P -> (Q -> R))) -> (P -> R).\nProof.\nexact (fun (P Q R : Prop) (h1 : (P -> Q) /\\ (P -> Q -> R)) => match h1 with\n                                                       | conj H H0 => fun h2 : P => H0 h2 (H h2)\n                                                       end).\nQed.\n\n(* http://us.metamath.org/ileuni/mpi.html *) \nTheorem mpi : forall P Q R:Prop, (Q /\\ (P -> (Q -> R))) -> (P -> R).\nProof.\n  intros P.\n  intros Q.\n  intros R.\n  intros h1.\n  destruct h1.\n  intros h2.\n  apply H0.\n  exact h2.\n  exact H.\nQed.\n\n(* http://us.metamath.org/ileuni/mpd.html *)\nTheorem mpd2a : forall P Q R:Prop,(P /\\ Q /\\ (P -> (Q -> R))) -> R.\nProof.\n  intros P.\n  intros Q.\n  intros R.\n  intros h1.\n  destruct h1.\n  destruct H0.\n  apply H1.\n  apply H.\n  apply H0.\nQed.\n\n(* http://us.metamath.org/ileuni/3syl.html *)\nTheorem threesly : forall P Q R S:Prop,((P -> Q) /\\ (Q -> R) /\\ (R -> S)) -> (P -> S) .\nProof.\n  intros P Q R S.\n  intros h1.\n  intros h2.\n  destruct h1.\n  destruct H0.\n  apply H1.\n  apply H0.\n  apply H.\n  exact h2.   \nQed. \n\n(* http://us.metamath.org/ileuni/id.html *)\nTheorem identity1 : forall P:Prop,P -> P.\nProof.\n  intros P.\n  intros h.\n  exact h.\nQed.\n\nPrint identity1.\n\nEval cbv in (fun (P : Prop) (h : P) => h) True.\n\n(* http://us.metamath.org/ileuni/id.html *)\nTheorem identity2 : forall P:Prop,P -> P.\nProof.\n  exact (fun (P : Prop) (h : P) => h).\nQed.\n\n(* http://us.metamath.org/ileuni/idd.html *)\nTheorem idd : forall P Q:Prop,P -> (Q -> Q).\nProof.\n  intros P Q.\n  intros H.\n  intros H0.\n  exact H0. \nQed.\n\n(* http://us.metamath.org/ileuni/a1d.html *)\nTheorem ad1 : forall P Q R:Prop,(P -> Q) -> (P -> (R -> Q)).\nProof.\n  intros P Q R.\n  intros H.\n  intros H0.\n  intros H1.\n  apply H.\n  exact H0. \nQed.\n\nPrint ad1.\n\nTheorem ad1b : forall P Q R:Prop,(P -> Q) -> (P -> (R -> Q)).\nProof.\n  exact (fun (P Q R : Prop) (H : P -> Q) (H0 : P) (_ : R) => H H0).\nQed.\n\n(* http://us.metamath.org/ileuni/2a1d.html *)\nTheorem TwoA1D: forall P Q R S:Prop, (P -> Q) -> (P ->(R -> (S -> Q))).\nProof.\n  intros P Q R S.\n  intros H.\n  intros H0.\n  intros H1.\n  intros H2.\n  apply H.\n  exact H0.\nQed.\n\nPrint TwoA1D.\n\nTheorem TwoA1Db: forall P Q R S:Prop, (P -> Q) -> (P ->(R -> (S -> Q))).\nProof.\n  exact (fun (P Q R S : Prop) (H : P -> Q) (H0 : P) (_ : R) (_ : S) => H H0).\nQed.\n\n(* http://us.metamath.org/ileuni/a1i13.html *)\nTheorem a1i13: forall P Q R S:Prop, (Q -> S) -> (P -> (Q -> (R -> S))).\nProof.\n  intros P Q R S.\n  intros H.\n  intros H0.\n  intros H1.\n  intros H2.\n  apply H.\n  exact H1.\nQed.\n\nPrint a1i13.\n\nTheorem a1i13b: forall P Q R S:Prop, (Q -> S) -> (P -> (Q -> (R -> S))).\nProof.\n  exact (fun (P Q R S : Prop) (H : Q -> S) (_ : P) (H1 : Q) (_ : R) => H H1).\nQed.\n\n\n(* http://us.metamath.org/ileuni/jarr.html *)\nTheorem jarr: forall P Q R:Prop,(((P -> Q) -> R) -> (Q -> R)).\nProof.\n  intros P Q R.\n  intros H.\n  intros H0.\n  apply H.\n  intros H1.\n  exact H0.\nQed.\n\nPrint jarr.\n\nTheorem jarr2: forall P Q R:Prop,(((P -> Q) -> R) -> (Q -> R)).\nProof.\n  exact (fun (P Q R : Prop) (H : (P -> Q) -> R) (H0 : Q) => H (fun _ : P => H0)).\nQed.\n\n(* http://us.metamath.org/ileuni/pm2.86i.html *)\nTheorem pm268i1: forall P Q R:Prop,(((P -> Q) -> (P -> R)) -> (P -> (Q -> R))).\nProof.\n  intros P Q R.\n  intros H0.\n  intros H1.\n  intros H2.\n  apply H0.\n  intros H3.\n  exact H2.\n  exact H1.\nQed.\n\nPrint pm268i1.\n\nTheorem pm268i1b: forall P Q R:Prop,(((P -> Q) -> (P -> R)) -> (P -> (Q -> R))).\nProof.\n  exact (fun (P Q R : Prop) (H0 : (P -> Q) -> P -> R) (H1 : P) (H2 : Q) =>\n          H0 (fun _ : P => H2) H1).  \nQed.\n\n(* http://us.metamath.org/ileuni/pm2.86d.html *)\n(* ⊢ (𝜑 → ((𝜓 → 𝜒) → (𝜓 → 𝜃))) *)\n(* ⊢ (𝜑 → (𝜓 → (𝜒 → 𝜃))) *)\nTheorem pm286d: \n  forall P Q R S:Prop, ((P -> ((Q -> R) -> (Q -> S))) -> (P -> (Q -> (R -> S)))).\nProof.\n  intros P Q R S.\n  intros H0.\n  intros H1.\n  intros H2.\n  intros H3.\n  apply H0.\n  exact H1.\n  intros H4.\n  exact H3.\n  exact H2.\nQed.\n\nPrint pm286d.\n\nTheorem pm286db: \n  forall P Q R S:Prop, ((P -> ((Q -> R) -> (Q -> S))) -> (P -> (Q -> (R -> S)))).\nProof.\n  exact (fun (P Q R S : Prop) (H0 : P -> (Q -> R) -> Q -> S) \n          (H1 : P) (H2 : Q) (H3 : R) => H0 H1 (fun _ : Q => H3) H2).\nQed.\n\n(* http://us.metamath.org/ileuni/pm2.86.html *)\n(* ⊢ (((𝜑 → 𝜓) → (𝜑 → 𝜒)) → (𝜑 → (𝜓 → 𝜒))) *)\nTheorem pm286: forall P Q R:Prop,(((P -> Q) -> (P -> R)) -> (P -> (Q -> R))).\nProof.\n  intros P Q R.\n  intros H0.\n  intros H1.\n  intros H2.\n  apply H0.\n  intros H3.\n  apply H2.\n  apply H1.\nQed.\n\nPrint pm286.\n\nTheorem pm286b: forall P Q R:Prop,(((P -> Q) -> (P -> R)) -> (P -> (Q -> R))).\nProof.\n  exact (fun (P Q R : Prop) (H0 : (P -> Q) -> P -> R) (H1 : P) (H2 : Q) =>\n          H0 (fun _ : P => H2) H1).\nQed.\n\n(* http://us.metamath.org/ileuni/loolin.html *)\n(* ⊢ (((𝜑 → 𝜓) → (𝜓 → 𝜑)) → (𝜓 → 𝜑)) *)\nTheorem loolin: forall P Q:Prop,(((P -> Q) -> (Q -> P)) -> (Q -> P)).\nProof.\n  intros P Q.\n  intros H0 H1.\n  apply H0.\n  intros H2.\n  exact H1.\n  exact H1.\nQed.\n\nPrint loolin.\n\nTheorem loolinb: forall P Q:Prop,(((P -> Q) -> (Q -> P)) -> (Q -> P)).\nProof.\n  exact (fun (P Q : Prop) (H0 : (P -> Q) -> Q -> P) (H1 : Q) =>\n              H0 (fun _ : P => H1) H1).\nQed.\n\n(* http://us.metamath.org/ileuni/loowoz.html *)\n(* ⊢ (((𝜑 → 𝜓) → (𝜑 → 𝜒)) → ((𝜓 → 𝜑) → (𝜓 → 𝜒))) *)\nTheorem loowoz: forall P Q R:Prop, (((P -> Q) -> (P -> R)) -> ((P -> Q) -> (P -> R))).\nProof.\n  intros P Q R.\n  intros H0 H1 H2.\n  apply H0.\n  intros H3.\n  apply H1.\n  exact H2.\n  exact H2.\nQed.\n\nPrint loowoz.\n\nTheorem loowozb: forall P Q R:Prop, (((P -> Q) -> (P -> R)) -> ((P -> Q) -> (P -> R))).\nProof.\n  exact (fun (P Q R : Prop) (H0 : (P -> Q) -> P -> R) (H1 : P -> Q) (H2 : P) =>\n          H0 (fun _ : P => H1 H2) H2).\nQed.\n\n(* http://us.metamath.org/ileuni/ax-ia1.html *)\n(* ⊢ ((𝜑 ∧ 𝜓) → 𝜑) *)\nTheorem axia1: forall P Q:Prop,((P /\\ Q) -> P).\nProof.\n  intros P Q.\n  intros H0.\n  destruct H0.\n  exact H.\nQed.\n\nPrint axia1.\n\nTheorem axia1b: forall P Q:Prop,((P /\\ Q) -> P).\nProof.\n  exact (fun (P Q : Prop) (H0 : P /\\ Q) =>\n          match H0 with\n          | conj x x0 => (fun (H : P) (_ : Q) => H) x x0\n          end).\nQed. \n\n(* http://us.metamath.org/ileuni/ax-ia3.html *)\n(* ⊢ (𝜑 → (𝜓 → (𝜑 ∧ 𝜓))) *)\nTheorem axia3: forall P Q:Prop,(P -> (Q -> (P /\\ Q))).\nProof.\n  intros P Q.\n  intros H0 H1.\n  split.\n  exact H0.\n  exact H1.\nQed.\n\nPrint axia3.\n\nTheorem axia3_2: forall P Q:Prop,(P -> (Q -> (P /\\ Q))).\nProof.\n  exact (\n    fun (P Q : Prop) (H0 : P) (H1 : Q) => conj H0 H1\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/simpld.html *)\n(* ⊢ (𝜑 → (𝜓 ∧ 𝜒)) *)\n(* ⊢ (𝜑 → 𝜓) *)\nTheorem simpld: forall P Q R:Prop,(P -> (Q /\\ R)) -> (P -> Q).\nProof.\n  intros P Q R.\n  intros H0.\n  intros H1.\n  destruct H0.\n  exact H1.\n  exact H.\nQed.\n\nPrint simpld.\n\nTheorem simpld_2: forall P Q R:Prop,(P -> (Q /\\ R)) -> (P -> Q).\nProof.\n  exact (\n    fun (P Q R : Prop) (H0 : P -> Q /\\ R) (H1 : P) =>\n      let a : Q /\\ R := H0 H1 in\n        match a with\n        | conj x x0 => (fun (H : Q) (_ : R) => H) x x0\n        end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/ex.html *)\n(* ⊢ ((𝜑 ∧ 𝜓) → 𝜒) *)\n(* ⊢ (𝜑 → (𝜓 → 𝜒)) *)\nTheorem ex01: forall P Q R:Prop, (((P /\\ Q) -> R) -> (P -> (Q -> R))).\nProof.\n  intros P Q R.\n  intros H0 H1 H2.\n  apply H0; split.\n  exact H1.\n  exact H2.\nQed.\n\nPrint ex01.\n\nTheorem ex01_2: forall P Q R:Prop, (((P /\\ Q) -> R) -> (P -> (Q -> R))).\nProof.\n  exact (\n    fun (P Q R : Prop) (H0 : P /\\ Q -> R) (H1 : P) (H2 : Q) => H0 (conj H1 H2)\n  ).\nQed.\n\n(*http://us.metamath.org/ileuni/bi1.html*)\n(* ⊢ ((𝜑 ↔ 𝜓) → (𝜑 → 𝜓)) *)\nTheorem bi1: forall P Q:Prop, ((P <-> Q) -> (P -> Q)).\nProof.\n  intros P Q.\n  intros H0 H1.\n  destruct H0.\n  apply H.\n  exact H1.\nQed.\n\nPrint bi1.\n\nTheorem bi1_02: forall P Q:Prop, ((P <-> Q) -> (P -> Q)).\nProof.\n  exact (\n    fun (P Q : Prop) (H0 : P <-> Q) (H1 : P) =>\n      match H0 with\n      | conj x x0 => (fun (H : P -> Q) (_ : Q -> P) => H H1) x x0\n      end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/bi3.html *)\n(* ⊢ ((𝜑 → 𝜓) → ((𝜓 → 𝜑) → (𝜑 ↔ 𝜓))) *)\nTheorem bi3: forall P Q:Prop, ((P -> Q) -> ((Q -> P) -> (P <-> Q))).\nProof.\n  intros P Q.\n  intros H0 H1.\n  split.\n  intros H2.\n  apply H0.\n  exact H2.\n  intros H3.\n  apply H1.\n  exact H3.\nQed.\n\nPrint bi3.\n\nTheorem bi3_02: forall P Q:Prop, ((P -> Q) -> ((Q -> P) -> (P <-> Q))).\nProof.\n  exact (\n    fun (P Q : Prop) (H0 : P -> Q) (H1 : Q -> P) =>\n      conj (fun H2 : P => H0 H2) (fun H3 : Q => H1 H3)\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/impbidd.html *)\n(* ⊢ (𝜑 → (𝜓 → (𝜒 → 𝜃))) *)\n(* ⊢ (𝜑 → (𝜓 → (𝜃 → 𝜒))) *)\n(* ----------------------*)\n(* ⊢ (𝜑 → (𝜓 → (𝜒 ↔ 𝜃))) *)\nTheorem impidd: forall P Q R S: Prop,((P -> (Q -> (R -> S))) /\\ (P -> (Q -> (S -> R)))) -> (P -> (Q -> (R <-> S))).\nProof.\n  intros P Q R S.\n  intros H0.\n  intros H1 H2.\n  split.\n  destruct H0.\n  intros H3.\n  apply H.\n  exact H1.\n  exact H2.\n  exact H3.\n  intros H4.\n  destruct H0.\n  apply H0.\n  exact H1.\n  exact H2.\n  exact H4. \nQed.\n\nPrint impidd.\n\nTheorem impidd_2: forall P Q R S: Prop,((P -> (Q -> (R -> S))) /\\ (P -> (Q -> (S -> R)))) -> (P -> (Q -> (R <-> S))).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : (P -> Q -> R -> S) /\\ (P -> Q -> S -> R)) \n    (H1 : P) (H2 : Q) =>\n  conj\n    match H0 with\n    | conj x x0 =>\n      (fun (H : P -> Q -> R -> S) (_ : P -> Q -> S -> R) (H4 : R) =>\n         H H1 H2 H4) x x0\n    end\n    (fun H4 : S =>\n     match H0 with\n     | conj x x0 =>\n         (fun (_ : P -> Q -> R -> S) (H3 : P -> Q -> S -> R) => H3 H1 H2 H4) x\n           x0\n     end)\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/impbid21d.html *)\n(* ⊢ (𝜓 → (𝜒 → 𝜃)) *)\n(* ⊢ (𝜑 → (𝜃 → 𝜒)) *)\n(* =================*)\n(* ⊢ (𝜑 → (𝜓 → (𝜒 ↔ 𝜃))) *)\nTheorem impid21d: forall P Q R S:Prop,((P -> (Q -> R)) /\\ (S -> (R -> Q))) -> (S -> (P -> (Q <-> R))).\nProof.\n  intros P Q R S.\n  intros H0 H1 H2.\n  split.\n  intros H3.\n  destruct H0.\n  apply H.\n  exact H2.\n  exact H3.\n  intros H4.\n  destruct H0.\n  apply H0.\n  exact H1.\n  exact H4.\nQed.\n\nPrint impid21d.\n\nTheorem impid21d_02: forall P Q R S:Prop,((P -> (Q -> R)) /\\ (S -> (R -> Q))) -> (S -> (P -> (Q <-> R))).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : (P -> Q -> R) /\\ (S -> R -> Q)) (H1 : S) (H2 : P)\n    =>\n    conj\n      (fun H3 : Q =>\n       match H0 with\n       | conj x x0 => (fun (H : P -> Q -> R) (_ : S -> R -> Q) => H H2 H3) x x0\n       end)\n      (fun H4 : R =>\n       match H0 with\n       | conj x x0 => (fun (_ : P -> Q -> R) (H3 : S -> R -> Q) => H3 H1 H4) x x0\n       end)    \n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/bicomi.html *)\n(* ⊢ (𝜑 ↔ 𝜓) *)\n(* ===========*)\n(* ⊢ (𝜓 ↔ 𝜑) *)\nTheorem bicomi: forall P Q: Prop,((P <-> Q) -> (Q <-> P)).\nProof.\n  intros P Q.\n  intros H0.\n  split.\n  destruct H0.\n  intros H1.\n  apply H0.\n  exact H1.\n  intros H2.\n  destruct H0.\n  apply H.\n  exact H2.\nQed.\n\nPrint bicomi.\n\nTheorem bicomi_02: forall P Q: Prop,((P <-> Q) -> (Q <-> P)).\nProof.\n   exact (\n    fun (P Q : Prop) (H0 : P <-> Q) =>\n    conj\n      match H0 with\n      | conj x x0 => (fun (_ : P -> Q) (H1 : Q -> P) (H2 : Q) => H1 H2) x x0\n      end\n      (fun H2 : P =>\n       match H0 with\n       | conj x x0 => (fun (H : P -> Q) (_ : Q -> P) => H H2) x x0\n       end)\n   ).\nQed.\n\nCheck fun (P Q:Prop) (H0 : P <-> Q) => \n        match H0 with\n        | conj x x0 => x0\n        end.\n\n(* http://us.metamath.org/ileuni/3imtr3i.html *)\n(* ⊢ (𝜑 → 𝜓) *)\n(* ⊢ (𝜑 ↔ 𝜒) *)\n(* ⊢ (𝜓 ↔ 𝜃) *)\n(* ------------*)\n(* ⊢ (𝜒 → 𝜃) *)\nTheorem threeimtr3i: forall P Q R S:Prop,\n    ((P  -> Q) /\\ \n     (P <-> R) /\\ \n     (Q <-> S)) -> (R -> S).\nProof.\n  intros P Q R S.\n  intros H0 H1.\n  destruct H0.\n  destruct H0.\n  apply H2.\n  apply H.\n  destruct H2.\n  destruct H0.\n  apply H4.\n  exact H1.\nQed.\n\nPrint threeimtr3i.\n\nTheorem threeimtr3i_02: forall P Q R S:Prop,\n    ((P  -> Q) /\\ \n     (P <-> R) /\\ \n     (Q <-> S)) -> (R -> S).\nProof.\n exact (\n  fun (P Q R S : Prop) (H0 : (P -> Q) /\\ (P <-> R) /\\ (Q <-> S)) (H1 : R) =>\n  match H0 with\n  | conj x x0 =>\n    (fun (H : P -> Q) (H2 : (P <-> R) /\\ (Q <-> S)) =>\n       match H2 with\n       | conj x1 x2 =>\n           (fun (H3 : P <-> R) (H4 : Q <-> S) =>\n            let H5 : Q -> S :=\n              match H4 with\n              | conj x3 x4 => (fun (H5 : Q -> S) (_ : S -> Q) => H5) x3 x4\n              end in\n            H5\n              (H\n                 match H4 with\n                 | conj x3 x4 =>\n                     (fun (_ : Q -> S) (_ : S -> Q) =>\n                      match H3 with\n                      | conj x5 x6 =>\n                          (fun (_ : P -> R) (H9 : R -> P) => H9 H1) x5 x6\n                      end) x3 x4\n                 end)) x1 x2\n       end) x x0\n  end\n ).\nQed.\n\n(* http://us.metamath.org/ileuni/expd.html *)\n(* ⊢ (𝜑 → ((𝜓 ∧ 𝜒) → 𝜃)) *)\n(* ---------------------- *)\n(* ⊢ (𝜑 → (𝜓 → (𝜒 → 𝜃))) *)\nTheorem expd:forall P Q R S:Prop, \n  (P -> ((Q /\\ R) -> S)) -> \n  (P -> (Q -> (R -> S))).\nProof.\n  intros P Q R S.\n  intros H0 H1 H2 H3.\n  apply H0.\n  exact H1.\n  split.\n  exact H2.\n  exact H3.\nQed.\n\nPrint expd.\n\n(* http://us.metamath.org/ileuni/expd.html *)\n(* ⊢ (𝜑 → ((𝜓 ∧ 𝜒) → 𝜃)) *)\n(* ---------------------- *)\n(* ⊢ (𝜑 → (𝜓 → (𝜒 → 𝜃))) *)\nTheorem expd_01:forall P Q R S:Prop, \n  (P -> ((Q /\\ R) -> S)) -> \n  (P -> (Q -> (R -> S))).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : P -> Q /\\ R -> S) (H1 : P) (H2 : Q) (H3 : R) =>\n    H0 H1 (conj H2 H3)\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/expdimp.html *)\n(* ⊢ (𝜑 → ((𝜓 ∧ 𝜒) → 𝜃)) *)\n(* ---------------------- *)\n(* ⊢ ((𝜑 ∧ 𝜓) → (𝜒 → 𝜃)) *)\nTheorem ileuni:forall P Q R S:Prop,\n      (P -> ((Q /\\ R) -> S)) -> \n      ((P /\\ Q) -> (R -> S)).\nProof.\n  intros P Q R S.\n  intros H0 H1 H2.\n  apply H0.\n  destruct H1.\n  exact H.\n  split.\n  destruct H1.\n  exact H1.\n  exact H2.\nQed.\n\nPrint ileuni.\n\nTheorem ileuni_02:forall P Q R S:Prop,\n      (P -> ((Q /\\ R) -> S)) -> \n      ((P /\\ Q) -> (R -> S)).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : P -> Q /\\ R -> S) (H1 : P /\\ Q) (H2 : R) =>\n    H0 match H1 with\n       | conj x x0 => (fun (H : P) (_ : Q) => H) x x0\n       end\n      (conj match H1 with\n          | conj x x0 => (fun (_ : P) (H3 : Q) => H3) x x0\n            end H2)\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/impancom.html *)\n(* ⊢ ((𝜑 ∧ 𝜓) → (𝜒 → 𝜃)) *)\n(* ---------------------- *)\n(* ⊢ ((𝜑 ∧ 𝜒) → (𝜓 → 𝜃)) *)\nTheorem impancom: forall P Q R S:Prop,\n    ((P /\\ Q) -> (R -> S)) -> \n    ((P /\\ R) -> (Q -> S)).\nProof.\n  intros P Q R S.\n  intros H0 H1 H2.\n  apply H0.\n  split.\n  destruct H1.\n  exact H.\n  exact H2.\n  destruct H1.\n  exact H1.\nQed.\n\nPrint impancom.\n\nTheorem impancom_01: forall P Q R S:Prop,\n    ((P /\\ Q) -> (R -> S)) -> \n    ((P /\\ R) -> (Q -> S)).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : P /\\ Q -> R -> S) (H1 : P /\\ R) (H2 : Q) =>\n    H0 (conj match H1 with\n           | conj x x0 => (fun (H : P) (_ : R) => H) x x0\n             end H2)\n      match H1 with\n      | conj x x0 => (fun (_ : P) (H3 : R) => H3) x x0\n      end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/pm3.3.html *)\n(* ⊢ (((𝜑 ∧ 𝜓) → 𝜒) → (𝜑 → (𝜓 → 𝜒))) *)\nTheorem pm33: forall P Q R:Prop,(((P /\\ Q) -> R) -> (P -> (Q -> R))).\nProof.\n  intros P Q R.\n  intros H0 H1 H2.\n  apply H0.\n  split.\n  exact H1.\n  exact H2.\nQed.\n\nPrint pm33.\n\nTheorem pm33_02: forall P Q R:Prop,(((P /\\ Q) -> R) -> (P -> (Q -> R))).\nProof.\n  exact (\n    fun (P Q R : Prop) (H0 : P /\\ Q -> R) (H1 : P) (H2 : Q) => H0 (conj H1 H2)\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/pm3.31.html *)\n(* ⊢ ((𝜑 → (𝜓 → 𝜒)) → ((𝜑 ∧ 𝜓) → 𝜒) *)\nTheorem pm331: forall P Q R:Prop,((P -> (Q -> R)) -> ((P /\\ Q) -> R)).\nProof.\n  intros P Q R.\n  intros H0.\n  intros H1.\n  apply H0.\n  destruct H1.\n  exact H.\n  destruct H1.\n  exact H1. \nQed.\n\nPrint pm331.\n\nTheorem pm331_02: forall P Q R:Prop,((P -> (Q -> R)) -> ((P /\\ Q) -> R)).\nProof.\n  exact (\n    fun (P Q R : Prop) (H0 : P -> Q -> R) (H1 : P /\\ Q) =>\n    H0 match H1 with\n       | conj x x0 => (fun (H : P) (_ : Q) => H) x x0\n       end match H1 with\n         | conj x x0 => (fun (_ : P) (H2 : Q) => H2) x x0\n           end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/pm3.22.html *)\n(* ⊢ ((𝜑 ∧ 𝜓) → (𝜓 ∧ 𝜑)) *)\nTheorem pm322: forall P Q:Prop,((P /\\ Q) -> (Q /\\ P)).\nProof.\n  intros P Q.\n  intros H0.\n  split.\n  destruct H0.\n  exact H0.\n  destruct H0.\n  exact H.\nQed.\n\nPrint pm322.\n\nTheorem pm322_02: forall P Q:Prop,((P /\\ Q) -> (Q /\\ P)).\nProof.\nexact (\n  fun (P Q : Prop) (H0 : P /\\ Q) =>\n  conj match H0 with\n     | conj x x0 => (fun (_ : P) (H1 : Q) => H1) x x0\n       end match H0 with\n           | conj x x0 => (fun (H : P) (_ : Q) => H) x x0\n           end\n).\nQed.\n\n(* http://us.metamath.org/ileuni/ancomd.html *)\n(* ⊢ (𝜑 → (𝜓 ∧ 𝜒)) *)\n(* ================ *)\n(* ⊢ (𝜑 → (𝜒 ∧ 𝜓)) *)\nTheorem ancomd:forall P Q R:Prop,((P -> (Q /\\ R)) -> (P -> (R /\\ Q))).\nProof.\n  intros P Q R.\n  intros H0 H1.\n  split.\n  destruct H0.\n  exact H1.\n  exact H0.\n  destruct H0.\n  exact H1.\n  exact H.\nQed.\n\n(* http://us.metamath.org/ileuni/ancomsd.html *)\n(* ⊢ (𝜑 → ((𝜓 ∧ 𝜒) → 𝜃)) *)\n(* -----------------------*)\n(* ⊢ (𝜑 → ((𝜒 ∧ 𝜓) → 𝜃)) *)\nTheorem ancomsd:forall P Q R S:Prop,(P -> ((Q /\\ R) -> S)) -> (P -> ((R /\\ Q) -> S)).\nProof.\n  intros P Q R S.\n  intros H0 H1 H2.\n  apply H0.\n  exact H1.\n  split.\n  destruct H2.\n  exact H2.\n  destruct H2.\n  exact H.\nQed.\n\nPrint ancomsd.\n\nTheorem ancomsd_01:forall P Q R S:Prop,(P -> ((Q /\\ R) -> S)) -> (P -> ((R /\\ Q) -> S)).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : P -> Q /\\ R -> S) (H1 : P) (H2 : R /\\ Q) =>\n    H0 H1\n      (conj match H2 with\n          | conj x x0 => (fun (_ : R) (H3 : Q) => H3) x x0\n            end match H2 with\n                | conj x x0 => (fun (H : R) (_ : Q) => H) x x0\n                end)\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/pm3.43i.html *)\n(* ⊢ ((𝜑 → 𝜓) → ((𝜑 → 𝜒) → (𝜑 → (𝜓 ∧ 𝜒)))) *)\nTheorem pm343i:forall P Q R S:Prop,((P -> Q) -> ((P -> R) -> (P -> (Q /\\ R)))).\nProof.\n  intros P Q R S.\n  intros H0 H1 H2.\n  split.\n  apply H0.\n  exact H2.\n  apply H1.\n  exact H2.\nQed.\n\nPrint pm343i.\n\nTheorem pm343i_02:forall P Q R S:Prop,((P -> Q) -> ((P -> R) -> (P -> (Q /\\ R)))).\nProof.\n  exact (\n    fun (P Q R _ : Prop) (H0 : P -> Q) (H1 : P -> R) (H2 : P) =>\n    conj (H0 H2) (H1 H2)\n  ).\nQed.\n(* ⊢ (𝜑 ↔ (𝜓 ∧ 𝜒)) *)\n(* ---------------- *)\n(* ⊢ (𝜑 → 𝜓) *)\nTheorem simplbi:forall P Q R:Prop,((P <-> (Q /\\ R)) -> (P -> Q)).\nProof.\n  intros P Q R.\n  intros H0 H1.\n  destruct H0.\n  destruct H.\n  exact H1.\n  exact H.\nQed.\n\nPrint simplbi.\n\nTheorem simplbi_02:forall P Q R:Prop,((P <-> (Q /\\ R)) -> (P -> Q)).\nProof.\n  exact (\n    fun (P Q R : Prop) (H0 : P <-> Q /\\ R) (H1 : P) =>\n    match H0 with\n    | conj x x0 =>\n      (fun (H : P -> Q /\\ R) (_ : Q /\\ R -> P) =>\n         let a : Q /\\ R := H H1 in\n         match a with\n         | conj x1 x2 => (fun (H3 : Q) (_ : R) => H3) x1 x2\n         end) x x0\n    end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/simprbi.html *)\n(* ⊢ (𝜑 ↔ (𝜓 ∧ 𝜒)) *)\n(* ---------------- *)\n(* ⊢ (𝜑 → 𝜒) *)\nTheorem simprbi:forall P Q R:Prop,((P <-> (Q /\\ R)) -> (P -> R)).\nProof.\n  intros P Q R.\n  intros H0 H1.\n  destruct H0.\n  destruct H.\n  exact H1.\n  exact H2.\nQed.\n\nPrint simprbi.\n\nTheorem simprbi_01:forall P Q R:Prop,((P <-> (Q /\\ R)) -> (P -> R)).\nProof.\n  exact (\n    fun (P Q R : Prop) (H0 : P <-> Q /\\ R) (H1 : P) =>\n    match H0 with\n    | conj x x0 =>\n      (fun (H : P -> Q /\\ R) (_ : Q /\\ R -> P) =>\n         let a : Q /\\ R := H H1 in\n         match a with\n         | conj x1 x2 => (fun (_ : Q) (H4 : R) => H4) x1 x2\n         end) x x0\n    end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/adantr.html *)\n(* ⊢ (𝜑 → 𝜓) *)\n(* ⊢ ((𝜑 ∧ 𝜒) → 𝜓) *)\nTheorem adantr:forall P Q R:Prop,((P -> R) -> ((P /\\ Q) -> R)).\nProof.\n  intros P Q R.\n  intros H0.\n  intros H1.\n  apply H0.\n  destruct H1.\n  exact H.\nQed.\n\nPrint adantr.\n\nTheorem adantr_02:forall P Q R:Prop,((P -> R) -> ((P /\\ Q) -> R)).\nProof.\n  exact (\n    fun (P Q R : Prop) (H0 : P -> R) (H1 : P /\\ Q) => H0 \n      match H1 with\n      | conj x x0 => (fun (H : P) (_ : Q) => H) x x0\n      end\n  ).\nQed.\n\nSection proof_of_tripl_impl.\n  Variables P Q S:Prop.\n  Hypothesis H : ((P -> Q) -> Q) -> Q.\n  Hypothesis p : P.\n\n  Lemma Rem : (P -> Q) -> Q.\n  Proof (fun H0:P -> Q => H0 p).\n\n  Definition  Rem_f := (fun H0:P -> Q => H0 p).\n  \n  Eval cbv in (Rem_f).\n  \nEnd proof_of_tripl_impl.\n\n(* https://cs.stackexchange.com/questions/80590/is-possible-to-prove-undecidability-of-the-halting-problem-in-coq *)\nRecord bijection A B :=\n  {  to   : A -> B\n  ; from : B -> A\n  ; to_from : forall b, to (from b) = b\n  ; from_to : forall a, from (to a) = a\n  }.\n\nTheorem cantor :\n  bijection nat (nat -> nat) ->\n  False.\nProof.\n  destruct 1 as [seq index ? ?].\n  (* define a function which differs from the nth sequence at the nth index *)\n  pose (f := fun n => S (seq n n)).\n  (* prove f differs from every sequence *)\n  assert (forall n, f <> seq n). {\n    unfold not; intros.\n    assert (f n = seq n n) by congruence.\n    subst f; cbn in H0.\n    eapply n_Sn; eauto.\n  }\n  rewrite <- (to_from0 f) in H.\n  apply (H (index f)).\n  reflexivity.\nQed.\n\nPrint cantor.\n\nTheorem cator_02 : (bijection nat (nat -> nat)) -> False.\nProof.\nexact (\n  fun H : bijection nat (nat -> nat) =>\n  match H with\n  | {| to := to; from := from; to_from := to_from; from_to := from_to |} =>\n    (fun (seq : nat -> nat -> nat) (index : (nat -> nat) -> nat)\n         (to_from0 : forall b : nat -> nat, seq (index b) = b)\n         (_ : forall a : nat, index (seq a) = a) =>\n       let f := fun n : nat => S (seq n n) in\n       let H0 : forall n : nat, f <> seq n :=\n         (fun (n : nat) (H0 : f = seq n) =>\n          let H1 : f n = seq n n :=\n            eq_trans (f_equal (fun f0 : nat -> nat => f0 n) H0)\n              (f_equal (seq n) eq_refl) in\n          n_Sn (seq n n) (eq_sym H1))\n          :\n          forall n : nat, f <> seq n in\n        let H1 : forall n : nat, seq (index f) <> seq n :=\n          eq_ind_r (fun f0 : nat -> nat => forall n : nat, f0 <> seq n) H0\n            (to_from0 f) in\n        H1 (index f) eq_refl) to from to_from from_to\n   end\n).\nQed.\n\n(*http://us.metamath.org/ileuni/adantl.html*)\n(* ⊢ (𝜑 → 𝜓) *)\n(* -----------*)\n(* ⊢ ((𝜒 ∧ 𝜑) → 𝜓) *)\nTheorem adanl:forall P Q R:Prop, (Q -> R) -> ((P /\\ Q) -> R).\nProof.\n  intros P Q R.\n  intros H0.\n  intros H1.\n  apply H0.\n  destruct H1.\n  trivial.\nQed.\n\nPrint adanl.\n\nTheorem adanl_01:forall P Q R:Prop, (Q -> R) -> ((P /\\ Q) -> R).\nProof.\n  exact (\n    fun (P Q R : Prop) (H0 : Q -> R) (H1 : P /\\ Q) =>\n    H0 match H1 with\n       | conj x x0 => (fun (_ : P) (H2 : Q) => H2) x x0\n       end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/adantld.html *)\n(* ⊢ (𝜑 → (𝜓 → 𝜒))  *)\n(* ----------------- *)\n(* ⊢ (𝜑 → ((𝜃 ∧ 𝜓) → 𝜒)) *)\nTheorem adantld:forall P Q R S:Prop,(P -> (R -> S)) -> (P -> ((Q /\\ R) -> S)).\nProof.\n  intros P Q R S.\n  intros H0.\n  intros H1.\n  intros H2.\n  apply H0.\n  exact H1.\n  destruct H2.\n  trivial.\nQed.\n\nPrint adantld.\n\nTheorem adantld_02:forall P Q R S:Prop,(P -> (R -> S)) -> (P -> ((Q /\\ R) -> S)).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : P -> R -> S) (H1 : P) (H2 : Q /\\ R) =>\n    H0 H1 match H2 with\n        | conj x x0 => (fun (_ : Q) (H3 : R) => H3) x x0\n          end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/adantrd.html *)\n(* ⊢ (𝜑 → (𝜓 → 𝜒)) *)\n(* ---------------- *)\n(* ⊢ (𝜑 → ((𝜓 ∧ 𝜃) → 𝜒)) *)\nTheorem adantrd:forall P Q R S:Prop,(P -> (Q -> S)) -> (P -> ((Q /\\ R) -> S)).\nProof.\n  intros P Q R S;intros H0;intros H1;intros H2.\n  apply H0.\n  exact H1.\n  destruct H2.\n  trivial.\nQed.\n\nPrint adantrd.\n\nTheorem adantrd_02:forall P Q R S:Prop,(P -> (Q -> S)) -> (P -> ((Q /\\ R) -> S)).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : P -> Q -> S) (H1 : P) (H2 : Q /\\ R) =>\n    H0 H1 match H2 with\n        | conj x x0 => (fun (H : Q) (_ : R) => H) x x0\n          end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/impel.html *)\n(* ⊢ (P → (Q → S)) *)\n(* ⊢ (R → Q) *)\n(* ------------------*)\n(* ⊢ ((P ∧ R) → S) *)\nTheorem impel:forall P Q R S:Prop,((P -> (Q -> S)) /\\ (R -> Q)) -> ((P /\\ R) -> S).\nProof.\n  intros P Q R S.\n  intros H0.\n  intros H1.\n  destruct H0.\n  apply H.\n  destruct H1.\n  exact H1.\n  apply H0.\n  destruct H1.\n  trivial.\nQed.\n\nPrint impel.\n\nTheorem impel2:forall P Q R S:Prop,((P -> (Q -> S)) /\\ (R -> Q)) -> ((P /\\ R) -> S).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : (P -> Q -> S) /\\ (R -> Q)) (H1 : P /\\ R) =>\n    match H0 with\n    | conj x x0 =>\n      (fun (H : P -> Q -> S) (H2 : R -> Q) =>\n         H match H1 with\n           | conj x1 x2 => (fun (H3 : P) (_ : R) => H3) x1 x2\n           end\n           (H2\n              match H1 with\n              | conj x1 x2 => (fun (_ : P) (H4 : R) => H4) x1 x2\n              end)) x x0\n    end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/mpan9.html *)\n(* ⊢ (P → R) *)\n(* ⊢ (Q → (R → S)) *)\n(* --------------- *)\n(* ⊢ ((P ∧ Q) → S) *)\nTheorem mpan9:forall P Q R S:Prop,((P -> R) /\\ (Q -> (R -> S))) -> ((P /\\ Q) -> S).\nProof.\n  intros P Q R S.\n  intros H0.\n  intros H1.\n  destruct H0.\n  apply H0.\n  destruct H1.\n  exact H2.\n  apply H.\n  destruct H1.\n  trivial.\nQed.\n\nPrint mpan9.\n\nTheorem mpan9_01:forall P Q R S:Prop,((P -> R) /\\ (Q -> (R -> S))) -> ((P /\\ Q) -> S).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : (P -> R) /\\ (Q -> R -> S)) (H1 : P /\\ Q) =>\n      match H0 with\n      | conj x x0 =>\n        (fun (H : P -> R) (H2 : Q -> R -> S) =>\n          H2 match H1 with\n              | conj x1 x2 => (fun (_ : P) (H4 : Q) => H4) x1 x2\n              end\n            (H\n                match H1 with\n                | conj x1 x2 => (fun (H3 : P) (_ : Q) => H3) x1 x2\n                end)) x x0\n      end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/syldan.html *)\n(* ⊢ ((P ∧ Q) → R) *)\n(* ⊢ ((P ∧ R) → S) *)\n(* ---------------- *)\n(* ⊢ ((P ∧ Q) → S) *)\nTheorem syldan:forall P Q R S:Prop,(((P /\\ Q) -> R) /\\ ((P /\\ R) -> S)) -> ((P /\\ Q) -> S).\nProof.\n  intros P Q R S.\n  intros H0.\n  intros H1.\n  destruct H0.\n  apply H0.\n  split.\n  destruct H1.\n  exact H1.\n  apply H.\n  trivial.\nQed.\n\nPrint syldan.\n\nTheorem syldan_02:forall P Q R S:Prop,(((P /\\ Q) -> R) /\\ ((P /\\ R) -> S)) -> ((P /\\ Q) -> S).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : (P /\\ Q -> R) /\\ (P /\\ R -> S)) (H1 : P /\\ Q) =>\n    match H0 with\n    | conj x x0 =>\n      (fun (H : P /\\ Q -> R) (H2 : P /\\ R -> S) =>\n         H2\n           (conj\n              match H1 with\n              | conj x1 x2 => (fun (H3 : P) (_ : Q) => H3) x1 x2\n              end (H H1))) x x0\n    end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/sylan.html *)\n(* ⊢ (P → Q) *)\n(* ⊢ ((Q ∧ R) → S) *)\n(* ---------------- *)\n(* ⊢ ((P ∧ R) → S) *)\nTheorem sylan:forall P Q R S:Prop,\n  ((P -> Q) /\\ ((Q /\\ R) -> S)) -> ((P /\\ R) -> S).\nProof.\n  intros P Q R S.\n  intros H0;intros H1.\n  destruct H0.\n  apply H0.\n  split.\n  apply H.\n  destruct H1.\n  exact H1.\n  destruct H1.\n  trivial.\nQed.\n\nPrint sylan.\n\nTheorem sylan_02:forall P Q R S:Prop,\n  ((P -> Q) /\\ ((Q /\\ R) -> S)) -> ((P /\\ R) -> S).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : (P -> Q) /\\ (Q /\\ R -> S)) (H1 : P /\\ R) =>\n    match H0 with\n    | conj x x0 =>\n      (fun (H : P -> Q) (H2 : Q /\\ R -> S) =>\n         H2\n           (conj\n              (H\n                 match H1 with\n                 | conj x1 x2 => (fun (H3 : P) (_ : R) => H3) x1 x2\n                 end)\n              match H1 with\n              | conj x1 x2 => (fun (_ : P) (H4 : R) => H4) x1 x2\n              end)) x x0\n    end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/sylanb.html *)\n(* ⊢ (P ↔ Q) *)\n(* ⊢ ((Q ∧ R) → S) *)\n(* ---------------- *)\n(* ⊢ ((P ∧ R) → S) *)\nTheorem sylanb:\n  forall P Q R S:Prop,\n  ((P <-> Q) /\\\n  ((Q /\\ R) -> S)) \n  -> ((P /\\ R) -> S).\nProof.\n  intros P Q R S.\n  intros H0; intros H1.\n  destruct H0.\n  apply H0.\n  split.\n  destruct H as (H2 & H3).\n  apply H2.\n  destruct H1 as (H4 & H5).\n  exact H4.\n  destruct H1 as (H4 & H5).\n  trivial.\nQed.\n\n(* http://us.metamath.org/ileuni/sylanbr.html *)\n(* ⊢ (P ↔ Q) *)\n(* ⊢ ((P ∧ R) → S) *)\n(* ---------------- *)\n(* ⊢ ((Q ∧ R) → S) *)\nTheorem sylanbr:forall P Q R S:Prop,\n  ((P <-> Q) /\\ \n   ((P /\\ Q) -> S)) -> \n  ((Q /\\ R) -> S).\nProof.\n  intros P Q R S.\n  intros H0 H1.\n  destruct H0 as (H2 & H3).\n  apply H3.\n  split.\n  destruct H2 as (H4 & H5).\n  apply H5.\n  destruct H1 as (H6 & H7).\n  trivial.\n  destruct H1 as (H6 & H7).\n  trivial.\nQed.\n\nPrint sylanbr.\n\nTheorem sylanbr_02:forall P Q R S:Prop,\n  ((P <-> Q) /\\ \n   ((P /\\ Q) -> S)) -> \n  ((Q /\\ R) -> S).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : (P <-> Q) /\\ (P /\\ Q -> S)) (H1 : Q /\\ R) =>\n    match H0 with\n    | conj x x0 =>\n      (fun (H2 : P <-> Q) (H3 : P /\\ Q -> S) =>\n         H3\n           (conj\n              match H2 with\n              | conj x1 x2 =>\n                  (fun (_ : P -> Q) (H5 : Q -> P) =>\n                   H5\n                     match H1 with\n                     | conj x3 x4 => (fun (H6 : Q) (_ : R) => H6) x3 x4\n                     end) x1 x2\n              end\n              match H1 with\n              | conj x1 x2 => (fun (H6 : Q) (_ : R) => H6) x1 x2\n              end)) x x0\n    end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/sylan2.html *)\n(* ⊢ (P → Q) *)\n(* ⊢ ((R ∧ Q) → S) *)\n(* ---------------- *)\n(* ⊢ ((R ∧ P) → S) *)\nTheorem sylan2:forall P Q R S:Prop,\n    ((P -> Q) /\\ \n     ((R /\\ Q) -> S)) ->\n    ((R /\\ P) -> S).\nProof.\n  intros P Q R S.\n  intros H0 H1.\n  destruct H0 as (H2 & H3).\n  apply H3.\n  split.\n  destruct H1 as (H4 & H5).\n  trivial.\n  apply H2.\n  destruct H1 as (H4 & H5).\n  exact H5.\nQed.\n\nPrint sylan2.\n\nTheorem sylan2_02:forall P Q R S:Prop,\n    ((P -> Q) /\\ \n     ((R /\\ Q) -> S)) ->\n    ((R /\\ P) -> S).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : (P -> Q) /\\ (R /\\ Q -> S)) (H1 : R /\\ P) =>\n    match H0 with\n    | conj x x0 =>\n      (fun (H2 : P -> Q) (H3 : R /\\ Q -> S) =>\n         H3\n           (conj\n              match H1 with\n              | conj x1 x2 => (fun (H4 : R) (_ : P) => H4) x1 x2\n              end\n              (H2\n                 match H1 with\n                 | conj x1 x2 => (fun (_ : R) (H5 : P) => H5) x1 x2\n                 end))) x x0\n    end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/sylan2b.html *)\n(* ⊢ (P ↔ Q) *)\n(* ⊢ ((R ∧ Q) → S) *)\n(* ---------------- *)\n(* ⊢ ((R ∧ P) → S) *)\nTheorem sylan2b:forall P Q R S:Prop,\n   ((P <-> Q) /\\ \n    ((R /\\ Q) -> S)) -> \n   ((R /\\ P) -> S).\nProof.\n  intros P Q R S.\n  intros H0 H1.\n  destruct H0 as (H2 & H3).\n  apply H3.\n  destruct H2 as (H4 & H5).\n  split.\n  destruct H1 as (H6 & H7).\n  exact H6.\n  apply H4.\n  destruct H1 as (H6 & H7).\n  exact H7.\nQed.\n\nPrint sylan2b.\n\nTheorem sylan2b_02:forall P Q R S:Prop,\n   ((P <-> Q) /\\ \n    ((R /\\ Q) -> S)) -> \n   ((R /\\ P) -> S).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : (P <-> Q) /\\ (R /\\ Q -> S)) (H1 : R /\\ P) =>\n    match H0 with\n    | conj x x0 =>\n      (fun (H2 : P <-> Q) (H3 : R /\\ Q -> S) =>\n         H3\n           match H2 with\n           | conj x1 x2 =>\n               (fun (H4 : P -> Q) (_ : Q -> P) =>\n                conj\n                  match H1 with\n                  | conj x3 x4 => (fun (H6 : R) (_ : P) => H6) x3 x4\n                  end\n                  (H4\n                     match H1 with\n                     | conj x3 x4 => (fun (_ : R) (H7 : P) => H7) x3 x4\n                     end)) x1 x2\n           end) x x0\n    end\n  ).\nQed.\n\n(* http://us.metamath.org/ileuni/sylan2br.html *)\n(* ⊢ (P ↔ Q) *)\n(* ⊢ ((R ∧ P) → S) *)\n(* ---------------- *)\n(* ⊢ ((R ∧ Q) → S) *)\nTheorem sylan2br:forall P Q R S:Prop,\n   ((P <-> Q) /\\ \n    ((R /\\ P) -> S)) -> \n   ((R /\\ Q) -> S).\nProof.\n  intros P Q R S.  \n  intros H0 H1.\n  destruct H0 as (H2 & H3).\n  apply H3.\n  split.\n  destruct H1 as (H4 & H5).\n  exact H4.\n  destruct H2 as (H6 & H7).\n  apply H7.\n  destruct H1 as (H4 & H5).\n  trivial.\nQed.\n\nPrint sylan2br.\n\nTheorem sylan2br_01:forall P Q R S:Prop,\n   ((P <-> Q) /\\ \n    ((R /\\ P) -> S)) -> \n   ((R /\\ Q) -> S).\nProof.\n  exact (\n    fun (P Q R S : Prop) (H0 : (P <-> Q) /\\ (R /\\ P -> S)) (H1 : R /\\ Q) =>\n    match H0 with\n    | conj x x0 =>\n      (fun (H2 : P <-> Q) (H3 : R /\\ P -> S) =>\n         H3\n           (conj\n              match H1 with\n              | conj x1 x2 => (fun (H4 : R) (_ : Q) => H4) x1 x2\n              end\n              match H2 with\n              | conj x1 x2 =>\n                  (fun (_ : P -> Q) (H7 : Q -> P) =>\n                   H7\n                     match H1 with\n                     | conj x3 x4 => (fun (_ : R) (H5 : Q) => H5) x3 x4\n                     end) x1 x2\n              end)) x x0\n    end\n  ).\nQed.\n\nPrint prod.\n(*\nInductive prod (A B : Type) : Type :=  \n   pair : A -> B -> A * B.\n*)\n\nDefinition add1 : nat -> nat.\nintro n.\nShow Proof.\napply S.\nShow Proof.\napply n. Defined.\nPrint add1.\n\n(*\nFrom ReductionEffect Require Import PrintingEffect.\nEval cbv in (fun f x => f (f (f x))) (fun x => S (print_id x)) 0.\nEval cbn in (fun f x => f (f (f x))) print_id 0. (* Not so interesting *)\nEval hnf in (fun f x => f (f (f x))) print_id 0. (* Not so interesting *)\nEval simpl in (fun f x => f (f (f x))) (fun x => print_id (1+x) + 1) 0.\nEval cbv in let x := print 3 in let y := print 4 in tt.\n*)\nModule NatPlayground2.\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n  | O => m\n  | S n' => S (plus n' m)\n  end.\n\n(*\n  Eval cbv in (fun f x => (plus 3 2)) (fun x => S (print_id x)) 0.\n\n  End NatPlayground2.\n*)\n(* detour with https://softwarefoundations.cis.upenn.edu/*)\n\nInductive day : Type :=\n  | monday\n  | tuesday\n  | wednesday\n  | thursday\n  | friday\n  | saturday\n  | sunday.\n\nDefinition next_weekday (d:day) : day :=\n  match d with\n  | monday => tuesday\n  | tuesday => wednesday\n  | wednesday => thursday\n  | thursday => friday\n  | friday => monday\n  | saturday => monday\n  | sunday => monday\n  end.\n\nTheorem plus_0_n : forall n : nat,0 + n = n.\nProof.\n  intros n.\n  simpl.\n  reflexivity.\nQed.\n\nPrint plus_0_n.\n\nTheorem plus_0_n_02 : forall n : nat,0 + n = n.\nProof.\n  exact (\n    fun n : nat => eq_refl : 0 + n = n\n  ).\nQed.\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. simpl. reflexivity. Qed.\n\nTheorem mult_0_l : forall n:nat, 0 * n = 0.\n  Proof.\n    intros n. simpl. reflexivity. Qed.\n\nTheorem plus_2_2_is_4 : 2 + 2 = 4.\nProof. \n  reflexivity. \nQed.\n\nDefinition plus_claim : Prop := 2 + 2 = 4.\nCheck plus_claim : Prop.\n\nTheorem plus_claim_is_true : plus_claim.\nProof. reflexivity. Qed.\n\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\nCheck is_three : nat -> Prop.   \n\nCheck @eq : forall A : Type, A -> A -> Prop.\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\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  Show Proof.\n  - reflexivity.\n  Show Proof.\n  - reflexivity.\n  Show Proof.\nQed.\n\nPrint and_example.\nPrint conj. \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\nPrint and_intro.\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 m n.\n  induction m.\n  split.\n  - reflexivity.\n  - apply H.\n  - intros H0.\nAbort.\n  \n  \nTheorem add_0_r_firsttry : forall n:nat, n + 0 = n.  \nProof.\n  intros n.\n  simpl.\nAbort.\n\nTheorem add_0_r_secondtry : forall n:nat,n + 0 = n.\nProof.\n  intros n.\n  Show Proof.\n  destruct n as [| n'] eqn:E.\n  Show Proof.\n  - reflexivity.\n  Show Proof.\n  - simpl.\n  Show Proof.\nAbort.\n\nTheorem add_0_r : forall n:nat, n + 0 = n.\nProof.\n  intros n.\n  induction n as [| n' IHn'].\n  - (* n = 0 *)\n  { \n    simpl. \n    reflexivity.\n  }\n  - { (* n = S n' *)\n    Show Proof.\n    simpl.\n    Show Proof.\n    rewrite -> IHn'.\n    Show Proof.\n    reflexivity.\n    Show Proof.\n  }\nQed.\nPrint eq_ind_r.\nPrint add_0_r.\nPrint nat_ind.\nCheck (fun n : nat =>\nnat_ind (fun n0 : nat => n0 + 0 = n0) (eq_refl : 0 + 0 = 0)\n  (fun (n' : nat) (IHn' : n' + 0 = n') =>\n   eq_ind_r (fun n0 : nat => S n0 = S n') eq_refl IHn' : S n' + 0 = S n') n).\nCheck eq_ind_r.\n   Check fun n' => S (n' + 0) = S n'.\nCheck fun (n : nat) (n' : nat) (IHn' : n' + 0 = n) => eq_refl IHn'.\n\nSection eq_ind_r_proof.  \n   Hypothesis n' : nat. \n   Hypothesis n : nat.   \n   Hypothesis IHn' : n' + 0 = n'. \n   Print eq_ind_r.\n   Check (fun n0: nat => S n0 = S n'). \n   Check eq_ind_r.\n   Check (fun x:nat => x = x).\n   Check eq_ind_r (fun x:nat => x = x).\n   Check eq_ind_r (fun n0: nat => S n0 = S n').\n   Check eq_ind_r (fun n0: nat => S n0 = S n') eq_refl.\n   Check eq_ind_r (fun n0: nat => S n0 = S n') eq_refl IHn'.\n   Definition f := eq_ind_r (fun n0: nat => S n0 = S n') eq_refl IHn'.\n   Print f.\nEnd eq_ind_r_proof.\n\nTheorem minus_n_n : forall n,\n  minus n n = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros n. \n  induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl. reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity. \n  Qed.\n\nTheorem mul_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros n.\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 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  - (* n = 0 *)\n    simpl.\n    reflexivity.\n  - (* n = S n*)\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 m.\n  induction n as [| n' IHn'].\n  - \n  {\n    simpl.\n    rewrite -> add_0_r.\n    reflexivity.\n  }\n  - \n  {\n    simpl.\n    rewrite -> IHn'.\n    rewrite -> plus_n_Sm.\n    reflexivity.\n  } \nQed.\nPrint add_comm.\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  - {\n    simpl.\n    reflexivity.\n  }\n  - {\n    simpl.\n    rewrite -> IHn'.\n    reflexivity.\n  }\nQed.\nPrint add_assoc.\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  intros n m H.\n  rewrite <- H.\n  reflexivity.\nQed.\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. *)\nTheorem plus_id_exercise : forall n m o : nat,\n   n = m -> m = o -> n + m = m + o.\nProof.\n  intros m n o H0 H1.\n  rewrite -> H0.\n  rewrite -> H1.\n  reflexivity.\nQed.\n\nCheck mult_n_O.\nCheck mult_n_Sm.\n\nTheorem mult_n_0_m_0 : forall p q : nat,\n  (p * 0) + (q * 0) = 0.\nProof.\n  intros p q.\n  repeat rewrite <- mult_n_O.\n  simpl.\n  reflexivity.\nQed.\nPrint mult_n_0_m_0.\n\nTheorem mult_n_1 : forall p : nat,\n  p * 1 = p.\nProof.\n  intros p.\n  Check mult_n_Sm.\n  Check mult_n_O.\n  rewrite <- mult_n_Sm.\n  rewrite <- mult_n_O.\n  simpl. \n  reflexivity.\nQed.\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\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nFixpoint eqb (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => eqb n' m'\n            end\n  end.\n\nFixpoint leb (n m : nat) : bool :=\n    match n with\n    | O => true\n    | S n' =>\n        match m with\n        | O => false\n        | S m' => leb n' m'\n        end\n    end.\n\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n  \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.\n  destruct n as [| n'] eqn:E.\n   - {\n    simpl.\n    reflexivity.\n   }\n   - {\n    simpl.\n    reflexivity.\n   }\nQed.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. \n  destruct b eqn:E.\n  - {\n    simpl.\n    reflexivity.\n  }\n  - {\n    simpl.\n    reflexivity.\n  }\nQed.\n\nTheorem andb_commutative : forall b c, andb b c = andb c b.\nProof.\n  intros b c.\n  destruct b eqn:Eb.\n  - {\n    destruct c eqn:Ec.\n    + {\n      simpl.\n      reflexivity. \n    }\n    + {\n      simpl. \n      reflexivity.\n    }\n  }\n  - {\n    destruct c eqn:Ec.\n    + {\n      simpl.\n      reflexivity.\n    }\n    + {\n      simpl.\n      reflexivity.\n    }\n  }\nQed.\n\nTheorem andb3_exchange :\n  forall b c d, andb (andb b c) d = andb (andb b d) c.\nProof.\n  intros b c d.\n  destruct b eqn:Eb.\n  - {\n    destruct c eqn:Ec.\n    + {\n      destruct d eqn:Ed. \n      * {\n        simpl.\n        reflexivity.\n      }\n      * {\n        simpl.\n        reflexivity.\n      }\n    }\n    + {\n      destruct d eqn:Ed. \n      * {\n        simpl.\n        reflexivity.\n      }\n      * {\n        simpl.\n        reflexivity.\n      }\n    }\n  }\n  - {\n    destruct c eqn:Ec.\n    + {\n      destruct d eqn:Ed. \n      * {\n        simpl.\n        reflexivity.\n      }\n      * {\n        simpl.\n        reflexivity.\n      }\n    }\n    + {\n      destruct d eqn:Ed. \n      * {\n        simpl.\n        reflexivity.\n      }\n      * {\n        simpl.\n        reflexivity.\n      }\n    }\n  }\nQed.\n\n(* http://us.metamath.org/ileuni/sylan2br.html *)\n(*\n  ⊢ (P → Q)\n  ⊢ (R → S)\n  ⊢ ((Q ∧ S) → T)\n  ----------------\n  ⊢ ((P ∧ R) → T)\n*)\nTheorem sylan2br2 : forall P Q R S T:Prop,\n  ((P -> Q) /\\\n   (R -> S) /\\\n   ((Q /\\ S) -> T)) ->\n  ((P /\\ R) -> T).\nProof.\n  intros P Q R S T.\n  intros H0 H1.\n  destruct H0.\n  destruct H0.\n  apply H2.\n  split.\n  apply H.\n  destruct H1.\n  exact H1.\n  apply H0.\n  destruct H1.\n  exact H3.\nQed.\n\n(* https://us.metamath.org/ileuni/syl2anr.html *)\n(*\n  ⊢ (P → Q)\n  ⊢ (R → S)\n  ⊢ ((Q ∧ S) → T)\n  ----------------\n  ⊢ ((R ∧ P) → T)\n*)\nTheorem syl2anr: forall P Q R S T:Prop,\n  (\n    (P -> Q) /\\\n    (R -> S) /\\\n    ((Q /\\ S) -> T)\n  ) ->\n  (\n    (R /\\ P) -> T\n  ).\nProof.\n  intros P Q R S T H0 H1.\n  destruct H0 as [H2 H3].\n  destruct H3 as [H4 H5].\n  destruct H1 as [H6 H7].\n  apply H5.\n  split.\n  apply H2.\n  exact H7.\n  apply H4.\n  exact H6.\nQed.\n\n(*\n   https://us.metamath.org/ileuni/syl2anb.html\n   ⊢ (P <-> Q)\n   ⊢ (R <-> S)\n   ⊢ ((Q ∧ S) → T)\n  -----------------\n   ⊢ ((P ∧ R) → T)\n*)\nTheorem syl2anb3 : forall P Q R S T:Prop,\n(\n  (P <-> Q) /\\\n  (R <-> S) /\\\n  ((Q /\\ S) -> T)\n) \n  ->\n(\n  ((P /\\ R) -> T)\n).\nProof.\n  intros P Q R S T H0 H1.\n  destruct H0 as [H2 H3].\n  destruct H3 as [H4 H5].\n  apply H5.\n  split.\n  apply H2.\n  destruct H1 as [H6 H7].\n  exact H6.\n  apply H4.\n  destruct H1 as [H6 H7].\n  exact H7.\nQed.\n\n(*\n  https://us.metamath.org/ileuni/syl2anbr.html]\n  ⊢ (P ↔ Q)\n  ⊢ (R ↔ S)\n  ⊢ ((P ∧ R) → T)\n  ----------------\n  ⊢ ((Q ∧ S) → T)\n*)\nTheorem syl2andbr: forall P Q R S T:Prop,\n(\n  (P <-> Q) /\\\n  (R <-> S) /\\\n  ((P /\\ R) -> T)\n) -> (\n  ((Q /\\ S) -> T)\n).\nProof.\n  intros P Q R S T H0 H1.\n  destruct H0 as [H2 H3].\n  destruct H3 as [H4 H5].\n  destruct H1 as [H6 H7].\n  apply H5.\n  split.\n  apply H2.\n  exact H6.\n  apply H4.\n  exact H7.\nQed.\n\n(*\n  https://us.metamath.org/ileuni/syland.html\n  ⊢ (P → (Q → R))\n  ⊢ (P → ((R ∧ S) → T))\n  ----------------------\n  ⊢ (P → ((Q ∧ S) → T))  \n*)\nTheorem syland : forall P Q R S T:Prop,\n(\n   (P -> (Q -> R)) /\\\n   (P -> ((R /\\ S) -> T))\n)\n  ->\n(  \n   (P -> ((Q /\\ S) -> T))\n).\nProof.\n  intros P Q R S T H0 H1 H2.\n  destruct H0 as [H3 H4].\n  destruct H2 as [H5 H6].\n  apply H4.\n  apply H1.\n  split.\n  apply H3.\n  exact H1.\n  exact H5.\n  exact H6.\nQed.\n\n(*\n   https://us.metamath.org/ileuni/sylan2d.html\n   ⊢ (P → (Q → S))\n   ⊢ (P → ((R ∧ S) → T))\n   ----------------------\n   ⊢ (P → ((R ∧ Q) → T))\n*)\nTheorem sylan2d : forall P Q R S T:Prop,\n(\n  (P -> (Q -> S)) /\\\n  (P -> ((R /\\ S) -> T))\n) -> (\n  (P -> ((R /\\ Q) -> T))\n).\nProof.\n  intros P Q R S T H0 H1 H2.\n  destruct H0 as [H3 H4].\n  destruct H2 as [H5 H6].\n  apply H4.\n  exact H1.\n  split.\n  exact H5.\n  apply H3.\n  exact H1.\n  exact H6.\nQed.\n\n(*\n   https://us.metamath.org/ileuni/syl2and.html\n   ⊢ (P → (Q → R))\n   ⊢ (P → (S → T))\n   ⊢ (P → ((R ∧ T) → U))\n   ----------------------\n   ⊢ (P → ((Q ∧ S) → U))\n*)\nTheorem syl2and : forall P Q R S T U:Prop,\n(\n  (P -> (Q -> R)) /\\\n  (P -> (S -> T)) /\\\n  (P -> ((R /\\ T) -> U))\n) -> (\n  (P -> ((Q /\\ S) -> U))\n).\nProof.\n  intros P Q R S T U H0 H1 H2.\n  destruct H0 as [H3 H4].\n  destruct H2 as [H6 H7].\n  destruct H4 as [H8 H9].\n  apply H9.\n  exact H1.\n  split.\n  apply H3.\n  exact H1.\n  exact H6.\n  apply H8.\n  exact H1.\n  exact H7.\nQed.\n\n(*\n  https://us.metamath.org/ileuni/biimpa.html\n  ⊢ (P → (Q ↔ R))\n  ----------------------\n  ⊢ ((P ∧ Q) → R)\n*)\nTheorem biimpa : forall P Q R:Prop,\n(\n  P -> (Q <-> R)  \n) -> (\n  (P /\\ Q) -> R\n).\nProof.\n  intros P Q R H0 H1.\n  destruct H1 as [H2 H3].\n  apply H0.\n  exact H2.\n  exact H3.\nQed.\n\n(*\nhttps://us.metamath.org/ileuni/biimpar.html\n⊢ (P → (Q ↔ R))\n----------------\n⊢ ((P ∧ R) → Q)\n*)\nTheorem biimpar: forall P Q R:Prop,\n(\n  (P -> (Q <-> R))\n) -> (\n  ((P /\\ R) -> Q)\n).\nProof.\n  intros P Q R.\n  intros H0.\n  intros H1.\n  destruct H0.\n  destruct H1.\n  exact H.\n  apply H0.\n  destruct H1.\n  exact H2.\nQed.\n\nPrint biimpar.\n\n(*\nhttps://us.metamath.org/ileuni/biimpac.html\n⊢ (P → (Q ↔ R))\n----------------\n⊢ ((Q ∧ P) → R)\n*)\nTheorem biimpac : forall P Q R:Prop,\n(\n  (P -> (Q <-> R))\n) -> (\n  ((Q /\\ P) -> R)\n).\nProof.\n  intros P Q R H0 H1.\n  apply H0.\n  destruct H1 as [H2 H3].\n  exact H3.\n  destruct H1 as [H2 H3].\n  exact H2.\nQed.\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  destruct contra. \nQed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H. Qed.\n\n(*\nhttps://us.metamath.org/ileuni/ax-in1.html\n  ⊢ ((P → ¬P) → ¬P)\n*)\nTheorem ax_in1 : forall P:Prop,\n(\n  (P -> ~P)\n) -> (\n  ~P\n).\nProof.\n  Show Proof.\n  intros P H0.\n  Show Proof.\n  intros H1.\n  Show Proof.\n  apply H0.\n  Show Proof.\n  exact H1.\n  Show Proof.\n  exact H1.\n  Show Proof.\nQed.\n\nPrint ax_in1.\n\nSection ax_in1_section.  \n  Hypothesis P : Prop. \n  Hypothesis H0 : P -> ~P.   \n  Hypothesis H1 : P. \n  Definition H2 := (fun H1 => H0 H1 H1).\n  Print H2.\n  Check H0.\n  Check H0 H1.\n  Check H0 H1 H1.\n  Check (fun H1 => H0 H1 H1).\nEnd ax_in1_section.\n\nTheorem and_elim1 : forall P Q:Prop,\n(\n  (P /\\ Q)\n) -> (\n  P\n).\nProof.\n  Show Proof.\n  intros P. \n  Show Proof.\n  intros Q.\n  Show Proof.\n  intros H0.\n  Show Proof.\n  destruct H0.\n  Show Proof.\n  apply H.\n  Show Proof.\nQed.\n\nPrint and_elim1.\nPrint conj.\n\nSection conj_explore.\n  Hypothesis P : Prop.\n  Hypothesis Q : Prop.\n  Hypothesis H : P.\n  Hypothesis H0 : P /\\ Q.\n  Check match H0 with\n        | conj x x0 => (fun (H : P) (_ : Q) => H) x x0\n        end.\n  Check match H0 with\n        | conj x x0 => conj x0 x\n        end.\n  Check conj H _.\n  Check conj H.\nEnd conj_explore.\n\n\nTheorem law_of_contradiction : forall (P Q : Prop),\n  P /\\ ~P -> Q.\nProof.\n  Show Proof.\n  intros P Q P_and_not_P.\n  Show Proof.\n  destruct P_and_not_P as [P_holds not_P].\n  Show Proof.\n  contradiction.\n  Show Proof.\nQed.\n\n(*\nhttps://us.metamath.org/ileuni/ax-in2.html\nDescription: 'Not' elimination\n⊢ (¬ P → (P → Q))\n*)\nTheorem ax_in2 : forall P Q:Prop,\n(\n  (~P)\n  ->\n  (P -> Q)\n).\nProof.\n  Show Proof.\n  intros P Q. \n  Show Proof.\n  intros H0 H1.\n  Show Proof.\n  contradiction. \n  Show Proof.\nQed.\nPrint ax_in2.\n\nCheck False_ind.\n\nSection contra_explore.\n  Hypothesis P : Prop.\n  Hypothesis Q : Prop.\n  Hypothesis H0 : P.\n  Hypothesis H1 : ~P.\n  Check False_ind.\n  Check False_ind P.\n  Check (H1 H0).\n  Check False_ind P (H1 H0).\nEnd contra_explore.\n\n(*\nhttps://us.metamath.org/ileuni/pm2.01.html\n⊢ ((P → ¬P) → ¬P)\n*)\nTheorem pm2_01 : forall P:Prop,\n(\n  (P -> ~P)\n) -> (\n  ~P\n).\nProof.\n  Show Proof.\n  intros P. \n  Show Proof.\n  intros H0. \n  Show Proof.\n  intros H1.\n  Show Proof.\n  apply H0.\n  Show Proof.\n  exact H1.\n  Show Proof.\n  exact H1.\n  Show Proof.\nQed.\n\n(*\nhttps://us.metamath.org/ileuni/pm2.21.html\n⊢ (¬ P → (P → Q))\n*)\nTheorem pm2_21 : forall P Q : Prop,\n(\n  ~P\n) -> (\n  P -> Q\n).\nProof.\n  Show Proof.\n  intros P Q.\n  Show Proof.\n  intros H0.\n  Show Proof.\n  intros H1.\n  Show Proof.\n  contradiction.\n  Show Proof.\nQed.\nCheck pm2_21.\n\nSection contra_explore2.\n  Hypothesis P : Prop.\n  Hypothesis Q : Prop.\n  Hypothesis H0 : ~P.\n  Hypothesis H1 : P.\n  Check False_ind.\n  Check False_ind Q.\n  Check (H0 H1).\n  Check False_ind Q (H0 H1).\nEnd contra_explore2.\n\n(*\nhttps://us.metamath.org/ileuni/pm2.01d.html\n⊢ (P → (Q → ¬Q))\n------------------\n⊢ (P → ¬Q)\n*)\nTheorem pm2_01d : forall P Q:Prop,\n(\n  (P -> (Q -> ~Q))\n) -> (\n  (P -> ~Q) \n).\nProof.\n  Show Proof.\n  intros P Q.\n  Show Proof.\n  intros H0.\n  Show Proof.\n  intros H1.\n  Show Proof.\n  intros H2.\n  Show Proof.\n  apply H0.\n  Show Proof.\n  exact H1.\n  Show Proof.\n  exact H2.\n  Show Proof.\n  exact H2.\n  Show Proof.\nQed. \n\n(*\nhttps://us.metamath.org/ileuni/pm2.21d.html\n⊢ (P → ¬Q)\n------------\n⊢ (P → (Q → R))\n*)\nTheorem pm2_21d : forall P Q R:Prop,\n(\n  (P -> ~Q)\n) -> (\n  (P -> (Q -> R)) \n).\nProof.\n  intros P Q R.\n  intros P_implies_not_Q.\n  intros P_holds.\n  intros Q_holds.\n  Show Proof.\n  (*https://www.cs.cornell.edu/courses/cs3110/2018sp/a5/coq-tactics-cheatsheet.html*)\n  apply P_implies_not_Q in P_holds as not_Q_holds.\n  Show Proof.\n  contradiction.\n  Show Proof.\n    Check False_ind.\nQed.\nPrint pm2_21d.\n\n(* https://us.metamath.org/ileuni/pm2.21dd.html \n⊢ (P → Q)\n⊢ (P → ¬Q)\n------------\n⊢ (P → R)\n*)\nTheorem pm2_21dd : forall P Q R:Prop,\n(\n  (P -> Q) /\\\n  (P -> ~Q)\n) -> (\n  (P -> R)\n).\nProof.\n  intros P Q R.\n  intros H0.\n  Show Proof.\n  destruct H0 as [P_implies_Q_holds P_implies_not_Q_holds].\n  Show Proof.\n  intros P_holds.\n  Show Proof.\n  apply P_implies_not_Q_holds in P_holds as not_Q_holds.\n  Show Proof.\n  apply P_implies_Q_holds in P_holds as Q_holds.\n  Show Proof.\n  contradiction.\n  Show Proof.\nQed.\n\n(*\nhttps://us.metamath.org/ileuni/pm2.24.html\n⊢ (P → (¬P → Q))\n*)\nTheorem pm2_24 : forall P Q:Prop,\n(P -> (~P -> Q)).\nProof.\n  intros P Q.\n  intros P_holds.\n  Show Proof.\n  intros not_P_holds.\n  Show Proof.\n  contradiction.\n  Show Proof.\nQed.\n\n(*\nhttps://us.metamath.org/ileuni/pm2.24d.html\n   ⊢ (P → Q)\n------------------\n⊢ (P → (¬Q → R))\n*)\nTheorem pm2_24d: forall P Q R:Prop,\n(\n   P -> Q\n) -> (\n   P -> (~Q -> R)\n).\nProof.\n  intros P Q R.\n  intros P_implies_Q_holds.\n  Show Proof.\n  intros P_holds.\n  Show Proof.\n  intros not_Q_holds.\n  Show Proof.\n  apply P_implies_Q_holds in P_holds as Q_holds.\n  Show Proof.\n  contradiction.\n  Show Proof.\nQed.\n\n(* Contrapositive \n\t⊢ (Q → ¬ R))\n  ------------------\n  ⊢ (R → ¬ Q))\n*)\nTheorem my_contrapositive: forall Q R:Prop,\n(\n  Q -> ~R\n) -> (\n  R -> ~Q\n).\nProof.\n  intros Q R.\n  intros Q_implies_not_R_holds.\n  intros R_holds.\n  intros Q_holds.\n  apply Q_implies_not_R_holds in Q_holds as not_R_holds.\n  contradiction.\nQed.\n\n\n(*https://us.metamath.org/ileuni/con2d.html\n\t⊢ (P → (Q → ¬ R))\n  ------------------\n  ⊢ (P → (R → ¬ Q))\n*)\nTheorem con2d: forall P Q R:Prop,\n(\n  (P -> (Q -> ~R))\n) -> (\n  (P -> (R -> ~Q))\n).\nProof.\n  intros P Q R.\n  Show Proof.\n  intros H0.\n  Show Proof.\n  intros P_holds.\n  Show Proof.\n  apply my_contrapositive.\n  Show Proof.\n  intros Q_holds.\n  Show Proof.\n  apply H0 in P_holds as not_R_holds.\n  Show Proof.\n  apply not_R_holds.\n  Show Proof.\n  apply Q_holds.\n  Show Proof.\nQed.\nPrint con2d.\n\n(*\nhttps://us.metamath.org/ileuni/mt2d.html\n⊢ (P → Q)\n⊢ (P → (R → ¬ Q))\n------------------\n⊢ (P → ¬R)\n*)\nTheorem mt2d: forall P Q R:Prop,\n(\n  (P -> Q) /\\\n  (P -> (R -> ~Q))\n) -> (\n  (P -> ~R)\n).\nProof.\n  intros P Q R H0 H1 R_holds.\n  destruct H0 as [P_implies_Q P_implies_R_implies_not_Q].\n  apply P_implies_Q in H1 as H3. \n  apply P_implies_R_implies_not_Q in H1 as H4.\n  contradiction.\n  exact R_holds.\nQed.\n\nRequire Import Classical.\n\nTheorem drinker : forall (A : Set) (r : A -> Prop) (e : A),\n  exists x, (r x -> forall y, r y).\nProof. \n   intros A r e.\n   Show Proof.\nAdmitted.\n\nTheorem add_0_r_secondtry : forall n:nat,\n  n + 0 = n.\nProof.\n  intros n.\n  Show Proof.\n  induction n as [| n' IHn'].\n  Show Proof.\n  - reflexivity.\n  Show Proof.\n  - simpl.\n  Show Proof.\n    rewrite -> IHn'.\n    Show Proof.\n    reflexivity. \n    Show Proof.\nQed.\nPrint nat_ind.\n(* Print eq_ind_r. *)\n\nSection ind_explore.\n  Hypothesis P : nat -> Prop.\n  Hypothesis f : P 0.\n  Hypothesis f0 : forall n:nat, P n -> P (S n).\n  Check nat_ind P f f0.\n\n  Definition my_nat_ind := fun (P : nat -> Prop) (f : P 0) (f0 : forall n : nat, P n -> P (S n)) =>\n  fix F (n : nat) : P n :=\n    match n as n0 return (P n0) with\n    | 0 => f\n    | S n0 => f0 n0 (F n0)\n    end.\n\n  Fixpoint F_my_nat (n : nat) : P n :=\n    match n as n0 return (P n0) with\n    | 0 => f\n    | S n0 => f0 n0 (F_my_nat n0)\n    end.\n\n   Print F_my_nat.\n\n   (* coq reference manual page *)\n   Hypothesis x:nat.\n   Hypothesis H:{1=0}+{1<>0}.\n   Check (fun x (H:{x=0}+{x<>0}) =>\n   match H with\n   | left _ => true\n   | right _ => false\n   end) 1 H.\n   Eval cbv in (fun x (H:{x=0}+{x<>0}) =>\n   match H with\n   | left _ => true\n   | right _ => false\n   end) 1 H.\n  Check my_nat_ind P f f0.\n    \n  Definition fst (A B:Set) (H:A * B) := match H with\n  | pair x y => x\n  end.\n    \nEnd ind_explore.", "meta": {"author": "trj2059", "repo": "MetamathToCoq", "sha": "d4b95cde6b9a84b1e29ad683f9240cfa11938166", "save_path": "github-repos/coq/trj2059-MetamathToCoq", "path": "github-repos/coq/trj2059-MetamathToCoq/MetamathToCoq-d4b95cde6b9a84b1e29ad683f9240cfa11938166/CoqMetamath.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566559, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.6916209411864285}}
{"text": "Module Exercise1.\n\n(* This exercise was done using MathClasses. I'll stick to mathcomp in the future. *)\n\nRequire Import\n  MathClasses.interfaces.abstract_algebra\n  MathClasses.interfaces.vectorspace\n  MathClasses.theory.groups.\n\nLemma f_equiv' `{Equiv A} `{f : A -> A} :\n  f = f -> forall x y, x = y -> f x = f y.\nProof.\n  intros.\n  f_equiv.\n  assumption.\nQed.\n\nLemma one : forall `{HVS : VectorSpace K V}, forall (u : V), 0 · u = mon_unit.\nProof.\n  intros.\n  setoid_rewrite <- left_identity.\n  setoid_rewrite <- left_inverse with (x := 1 · u).\n  setoid_rewrite <- associativity.\n  apply f_equiv'.\n  { cbv; intros ?? Hxy; now rewrite Hxy. }\n  setoid_rewrite <- distribute_r.\n  cbv; now group.\nQed.\n\nLemma two : forall `{HVS : VectorSpace K V}, forall (α : K), α · mon_unit = mon_unit.\nProof.\n  intros.\n  rewrite <- right_identity.\n  rewrite <- (right_inverse (α · mon_unit)) at 2 3.\n  rewrite associativity.\n  apply (f_equiv' (f := fun v => v & - (α · mon_unit)));\n    [ cbv; intros ?? Hxy; now rewrite Hxy |].\n  rewrite <- distribute_l.\n  pose scalar_mult_proper.\n  rewrite left_identity.\n  reflexivity.\nQed.\n\nLemma three : forall `{HVS : VectorSpace K V}, forall (u : V), -1 · u = -u.\nProof.\n  intros.\n  setoid_rewrite <- right_identity.\n  setoid_rewrite <- (right_inverse u).\n  setoid_rewrite associativity.\n  apply (f_equiv' (f := fun v => v & - u));\n    [ cbv; intros ?? Hxy; now rewrite Hxy |].\n  rewrite left_inverse.\n  rewrite <- (left_identity u (op := (·))) at 2.\n  rewrite <- distribute_r.\n  pose scalar_mult_proper.\n  rewrite left_inverse.\n  apply one.\nQed.\n\nEnd Exercise1.\n\nModule Exercise2.\n  Module i.\n    (** The exercice statement is simply (translated) :\n     Prove that the set K^n with the following operations :\n            (x_1, ..., x_n) + (y_1, ..., y_n) = (x_1 + y_1, ..., x_n + y_n)\n         and\n            λ·(x_1, ..., x_n) = (λ × x_1, ..., λ × x_n)\n     is a vector space.\n\n     So I figured that would be the occasion the learn how to properly define Mathclasses structures.\n     That's why this Module is so long, apologies. *)\n    \n    Require Import\n      Coq.Vectors.Vector\n      MathClasses.theory.dec_fields\n      Field.\n    Import VectorNotations.\n\n    Open Scope vector_scope.\n\n    Context F `{DecField F}.\n    Add Field F: (stdlib_field_theory F).\n\n    Definition vec := Vector.t F.\n\n    Definition vec_constant {n : nat} (c : F) : vec n := Vector.const c n.\n\n    Instance vec_zero {n : nat} : Zero (vec n) := Vector.const 0 n.\n\n    Instance vec_eq {n : nat} : Equiv (vec n) :=\n      fold_right2 (fun α β S => α = β /\\ S) True n.\n\n    Instance vec_add {n : nat} : Plus (vec n) :=\n      map2 (fun α β => α + β).\n\n    Instance vec_neg {n : nat} : Negate (vec n) :=\n      map (fun α => - α).\n\n    Instance vec_scal {n : nat} : ScalarMult F (vec n) :=\n      fun α => map (fun β => α * β).\n\n    Instance: forall {n : nat}, Reflexive (vec_eq (n := n)).\n    Proof.\n      intros n x.\n      induction x.\n      - simpl. apply I.\n      - split; [reflexivity | assumption].\n    Qed.\n\n    Lemma vec0_eq_nil : forall v : vec 0, v ≡ [].\n    Proof with reflexivity. apply case0... Qed.\n\n    Lemma vec_cons_eq : forall {n : nat} (u v : vec n) (α β : F), (α::u = β::v) <-> α = β /\\ u = v.\n    Proof. split; intros; assumption. Qed.\n\n    Lemma vec0_eq_proper : Proper (equiv ==> equiv ==> flip impl) (vec_eq (n := 0)).\n    Proof.\n      repeat intro.\n      assert (nil F ≡ nil F) by reflexivity.\n      rewrite (vec0_eq_nil x), (vec0_eq_nil x0).\n      reflexivity.\n    Qed.\n\n    Instance: forall {n : nat}, Symmetric (vec_eq (n := n)).\n    Proof.\n      intros n u v Heq.\n      induction n.\n      - pose vec0_eq_proper.\n        rewrite (vec0_eq_nil v), (vec0_eq_nil u).\n        reflexivity.\n      - rewrite (eta u), (eta v) in *.\n        apply vec_cons_eq.\n        destruct (vec_cons_eq (tl u) (tl v) (hd u) (hd v)) as [Hi _].\n        pose proof (Hi Heq) as [Hs_hd Hs_tl].\n        split.\n        + symmetry.\n          exact Hs_hd.\n        + apply IHn.\n          exact Hs_tl.\n    Qed.\n\n    Instance: forall {n : nat}, Transitive (vec_eq (n := n)).\n    Proof.\n      intros n u v z Heq_uv Heq_vz.\n      (* Maybe I'll avoid writing a [vec_eq_ind] function eternally *)\n      induction n.\n      - pose vec0_eq_proper as Hp.\n        rewrite (vec0_eq_nil u), (vec0_eq_nil v) in *.\n        exact Heq_vz.\n      - rewrite (eta u), (eta v), (eta z) in *.\n        destruct (vec_cons_eq (tl u) (tl v) (hd u) (hd v)) as [Hi_uv _].\n        destruct (vec_cons_eq (tl v) (tl z) (hd v) (hd z)) as [Hi_vz _].\n        pose proof (Hi_uv Heq_uv) as [Hs_hd_uv Hs_tl_uv].\n        pose proof (Hi_vz Heq_vz) as [Hs_hd_vz Hs_tl_vz].\n        split.\n        + transitivity (hd v).\n          * exact Hs_hd_uv.\n          * exact Hs_hd_vz.\n        + apply IHn with (v := (tl v)).\n          * exact Hs_tl_uv.\n          * exact Hs_tl_vz.\n    Qed.\n\n    Instance: forall {n : nat}, Setoid (vec n).\n    Proof. split; apply _. Qed.\n\n    Lemma vec0_add_proper : Proper (equiv ==> equiv ==> equiv) (vec_add (n := 0)).\n    Proof.\n      repeat intro.\n      assert (nil F ≡ nil F) by reflexivity.\n      rewrite (vec0_eq_nil x),\n        (vec0_eq_nil x0),\n        (vec0_eq_nil y),\n        (vec0_eq_nil y0).\n      reflexivity.\n    Qed.\n\n    Instance vec_add_commutative {n : nat} : Commutative (vec_add (n := n)).\n    Proof.\n      intros u v.\n      induction n.\n      - pose vec0_add_proper as Hp.\n        rewrite (case0 (fun v => v = []) I v), (vec0_eq_nil u).\n        reflexivity.\n      - rewrite (eta u), (eta v) in *.\n        split.\n        + apply commutativity.\n        + apply IHn.\n    Qed.\n\n    Instance vec_add_associative {n : nat} : Associative (vec_add (n := n)).\n    Proof.\n      intros u v z.\n      induction n.\n      - pose vec0_add_proper as Hp.\n        rewrite (vec0_eq_nil v), (vec0_eq_nil u), (vec0_eq_nil z).\n        reflexivity.\n      - rewrite (eta u), (eta v), (eta z) in *.\n        split.\n        + apply associativity.\n        + apply IHn.\n    Qed.\n\n    Lemma vec_add_proper {n : nat} : Proper (equiv ==> equiv ==> equiv) (vec_add (n := n)).\n    Proof.\n      induction n.\n      - apply vec0_add_proper; assumption.\n      - intros u v Heq_uv x y Heq_xy.\n        rewrite (eta u), (eta v), (eta x), (eta y) in *.\n        split; [apply sg_op_proper | apply IHn];\n          try apply Heq_uv; try apply Heq_xy.\n    Qed.\n    \n    Instance: forall {n : nat}, SemiGroup (vec n).\n    Proof.\n      split.\n      apply _.\n      apply _.\n      apply vec_add_proper.\n    Qed.\n\n    Instance: forall {n : nat}, LeftIdentity (vec_add (n := n)) vec_zero.\n    Proof.\n      intros n v.\n      induction n.\n      - rewrite (vec0_eq_nil v).\n        reflexivity.\n      - rewrite (eta v), (eta vec_zero).\n        split.\n        + group.\n        + apply IHn.\n    Qed.\n\n    Instance: forall {n : nat}, RightIdentity (vec_add (n := n)) vec_zero.\n    Proof.\n      intros n v.\n      rewrite commutativity.\n      apply left_identity.\n    Qed.\n    \n    Instance: forall {n : nat}, Monoid (vec n).\n    Proof. split; apply _. Qed.\n\n    Instance: forall {n : nat}, Proper (equiv ==> equiv) (vec_neg (n := n)).\n    Proof.\n      intros n u v Heq.\n      induction n.\n      - rewrite (vec0_eq_nil u), (vec0_eq_nil v).\n        reflexivity.\n      - rewrite (eta u), (eta v) in *.\n        split.\n        + apply (negate_proper F).(sm_proper).\n          apply Heq.\n        + apply IHn.\n          apply Heq.\n    Qed.  \n\n    Instance: forall {n : nat}, Setoid_Morphism (vec_neg (n := n)).\n    Proof. split; apply _. Qed.\n\n    Instance: forall {n : nat}, LeftInverse (vec_add (n := n)) (vec_neg (n := n)) vec_zero.\n    Proof.\n      intros n v.\n      induction n.\n      - rewrite (vec0_eq_nil v).\n        reflexivity.\n      - rewrite (eta v) in *.\n        split.\n        + apply left_inverse.\n        + apply IHn.\n    Qed.\n\n    Instance: forall {n : nat}, RightInverse (vec_add (n := n)) (vec_neg (n := n)) vec_zero.\n    Proof.\n      intros n v.\n      rewrite commutativity.\n      apply left_inverse.\n    Qed.\n\n    Instance: forall {n : nat}, Group (vec n).\n    Proof. split; apply _. Qed.\n    \n    Instance: forall {n : nat}, AbGroup (vec n).\n    Proof. split; apply _. Qed.\n\n    Instance: forall {n : nat}, LeftHeteroDistribute (vec_scal (n := n)) (vec_add (n := n)) (vec_add (n := n)).\n    Proof.\n      intros n α u v.\n      induction n.\n      - rewrite (vec0_eq_nil u), (vec0_eq_nil v).\n        reflexivity.\n      - rewrite (eta u), (eta v).\n        split.\n        + apply distribute_l.\n        + apply IHn.\n    Qed.\n\n    (* Is there a Lemma I can prove to \"automate\" this ? Besides using Ltac. *)\n    Instance: forall {n : nat}, RightHeteroDistribute (vec_scal (n := n)) (+) (vec_add (n := n)).\n    Proof.\n      intros n α β v.\n      induction n.\n      - rewrite (vec0_eq_nil v).\n        reflexivity.\n      - rewrite (eta v).\n        split.\n        + apply distribute_r.\n        + apply IHn.\n    Qed.\n\n    Instance: forall {n : nat}, HeteroAssociative (vec_scal (n := n)) (vec_scal (n := n)) (vec_scal (n := n)) mult.\n    Proof.\n      intros n α β v.\n      induction n.\n      - rewrite (vec0_eq_nil v).\n        reflexivity.\n      - rewrite (eta v).\n        split.\n        + apply associativity.\n        + apply IHn.\n    Qed.\n\n    Instance: forall {n : nat}, LeftIdentity (vec_scal (n := n)) 1.\n    Proof.\n      intros n v.\n      induction n.\n      - rewrite (vec0_eq_nil v).\n        reflexivity.\n      - rewrite (eta v).\n        split.\n        + apply left_identity.\n        + apply IHn.\n    Qed.\n\n    Instance: forall {n : nat}, Proper (equiv ==> equiv ==> equiv) (vec_scal (n := n)).\n    Proof.\n      intros n α β Heq_αβ u v Heq_uv.\n      induction n.\n      - rewrite (vec0_eq_nil u), (vec0_eq_nil v).\n        reflexivity.\n      - rewrite (eta u), (eta v) in *.\n        split.\n        + apply sg_op_proper.\n          * exact Heq_αβ.\n          * apply Heq_uv.\n        + apply IHn.\n          apply Heq_uv.\n    Qed.\n\n    Instance: forall {n : nat}, Module F (vec n).\n    Proof. split; apply _. Qed.\n\n    Instance: forall {n : nat}, VectorSpace F (vec n).\n    Proof. split; apply _. Qed.\n  End i.\n\nEnd Exercise2.\n\n", "meta": {"author": "0poss", "repo": "CoqL1", "sha": "43ac59ff9913cc7467b804165d72230116da0756", "save_path": "github-repos/coq/0poss-CoqL1", "path": "github-repos/coq/0poss-CoqL1/CoqL1-43ac59ff9913cc7467b804165d72230116da0756/LinAlg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.6915852594739915}}
{"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* Epsilon operator                                                        *\n**************************************************************************)\n\nSet Implicit Arguments.\nFrom SLF Require Import LibTactics LibLogic LibRelation.\nGeneralizable Variables A B.\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Definition and specification of Hilbert's epsilon operator *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Definition of epsilon *)\n\n(** [epsilon P] where [P] is a predicate over an inhabited type [A],\n    returns a value [x] of type [A] that satisfies [P], if there exists\n    one such value, else it returns an arbitrary value of type [A]. *)\n\nDefinition epsilon_def : forall A {IA:Inhab A} (P:A->Prop),\n  { x : A | (exists y, P y) -> P x }.\nProof using.\n  intros A IA P. destruct (classicT (exists y, P y)) as [H|H].\n  { apply indefinite_description. destruct H as [x H].\n    exists x. intros _. apply H. }\n  { exists (@arbitrary A IA). intros N. false H. apply N. }\nQed.\n\nDefinition epsilon A {IA: Inhab A} (P:A->Prop) : A :=\n  sig_val (epsilon_def P).\n\nLemma pred_epsilon : forall A {IA:Inhab A} (P:A->Prop),\n  (exists x, P x) ->\n  P (epsilon P).\nProof using. intros. apply~ (sig_proof (epsilon_def P)). Qed.\n\nOpaque epsilon.\n\n(* Remark: the proof term associated with the definition *)\n\nDefinition epsilon_def' A {IA:Inhab A} (P:A->Prop) :\n  { x : A | (exists y, P y) -> P x } :=\n  match classicT (exists y, P y) with\n  | left H =>\n      indefinite_description\n        (let (x,H0) := H in\n         ex_intro (fun x0 => (exists y, P y) -> P x0)\n                   x\n                  (fun N => H0))\n  | right H =>\n      exist (fun x => (exists y, P y) -> P x)\n            arbitrary\n            (fun N => False_ind (P arbitrary) (H N))\n  end.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Lemmas about epsilon *)\n\nLemma pred_epsilon_weaken : forall A {IA:Inhab A} (P Q : A->Prop),\n  (exists x, P x) ->\n  (forall x, P x -> Q x) ->\n  Q (epsilon P).\nProof using. introv E M. apply M. apply* pred_epsilon. Qed.\n\nLemma pred_epsilon_of_val : forall A (x:A) (P:A->Prop) {IA:Inhab A},\n  P x ->\n  P (epsilon P).\nProof using. intros. apply* pred_epsilon. Qed.\n\nLemma pred_epsilon_of_val_weaken : forall A (x:A) (P Q:A->Prop) {IA:Inhab A},\n  P x ->\n  (forall x, P x -> Q x) ->\n  Q (epsilon P).\nProof using. introv Px W. apply W. apply* pred_epsilon. Qed.\n\nLemma epsilon_eq : forall A {IA:Inhab A} (P Q:A->Prop),\n  (forall x, P x <-> Q x) ->\n  epsilon P = epsilon Q.\nProof using. introv H. fequals. extens*. Qed.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** (Private) tactic [epsilon_find] *)\n\n(** [epsilon_find cont] locates an expression of the form [epsilon P]\n    in the goal and invokes the continuation [cont] on [P].\n\n    [epsilon_find_in H cont] is similar but looks for the expression\n    only in the hypothesis named [H]. *)\n\nLtac epsilon_find cont :=\n  match goal with\n  | |- context [epsilon ?P] => cont P\n  | H: context [epsilon ?P] |- _ => cont P\n  end.\n\nLtac epsilon_find_in H cont :=\n  match type of H with context [epsilon ?P] => cont P end.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Tactics [epsilon_name] *)\n\n(** [epsilon_name X] assigns a name [X] to an expression of the\n    form [epsilon P] that appears in the goal or an hypothesis,\n    by calling [set (X := epsilon P)].\n\n    [epsilon_name X in H] assignes a name [X] to an expression of the\n    form [epsilon P] that appears in hypothesis [H]. *)\n\nLtac epsilon_name_core X :=\n  epsilon_find ltac:(fun P => sets X: (epsilon P)).\n\nLtac epsilon_name_in_core X H :=\n  epsilon_find_in H ltac:(fun P => sets X: (epsilon P)).\n\nTactic Notation \"epsilon_name\" ident(X) :=\n  epsilon_name_core X.\n\nTactic Notation \"epsilon_name\" ident(X) \"in\" hyp(H)  :=\n  epsilon_name_in_core X H.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Tactics to work with [epsilon] *)\n\n(** [epsilon X] locates an expression of the form [epsilon P] in the goal,\n    names [X] this expression (like [epsilon_name X]), then produces\n    a subgoal [exists x, P x], and leaves at the head of the main goal\n    an hypothesis [P X].\n\n    [epsilon X in H] is similar, but looks for [epsilon P] only in\n    hypothesis [H]. *)\n\nLemma pred_epsilon' : forall A (P:A->Prop) (IA:Inhab A),\n  (exists x, P x) ->\n  P (epsilon P).\nProof using. intros. applys* pred_epsilon. Qed.\n\nLtac epsilon_cont X P :=\n  let I := fresh \"H\" X in\n  lets I: (>> (@pred_epsilon' _ P) __ __);\n    [ | sets X: (epsilon P); revert I ].\n\nLtac epsilon_core X :=\n  epsilon_find ltac:(fun P => epsilon_cont X P).\n\nLtac epsilon_in_core X H :=\n  epsilon_find_in H ltac:(fun P => epsilon_cont X P).\n\nTactic Notation \"epsilon\" ident(X) :=\n  epsilon_core X.\nTactic Notation \"epsilon\" ident(X) \"in\" hyp(H) :=\n  epsilon_in_core X H.\n\nTactic Notation \"epsilon\" \"~\" ident(X) :=\n  epsilon X; auto_tilde.\nTactic Notation \"epsilon\" \"~\" ident(X) \"in\" hyp(H) :=\n  epsilon X in H; auto_tilde.\n\nTactic Notation \"epsilon\" \"*\" ident(X) :=\n  epsilon X; auto_star.\nTactic Notation \"epsilon\" \"*\" ident(X) \"in\" hyp(H) :=\n  epsilon X in H; auto_star.\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Construction of a function from a relation, using [epsilon] *)\n\n(* Given a relation [R] of type [A->B->Prop], [rel_to_fun R] returns a\n   function [f] of type [A->B] that satisfies the relation [R], i.e.\n   such that [R x (f x)] forall [x] that has an image by [R]. *)\n\nDefinition rel_to_fun A `{IB:Inhab B} (R:A->B->Prop) : A -> B :=\n  fun (a:A) => epsilon (fun b => R a b).\n\nSection Rel_to_fun.\nContext (A B : Type) {IB:Inhab B}.\nImplicit Types R : A -> B -> Prop.\n\n(* Every [a] in the domain of [R] is related by [R] with [rel_to_fun a]. *)\n\nLemma rel_rel_to_fun_of_exists : forall R a,\n  (exists b, R a b) ->\n  R a (rel_to_fun R a).\nProof using IB. introv [x H]. unfold rel_to_fun. epsilon* y. Qed.\n\nLemma rel_rel_to_fun_of_rel : forall R a b,\n  R a b ->\n  R a (rel_to_fun R a).\nProof using IB. intros. applys* rel_rel_to_fun_of_exists. Qed.\n\nLemma rel_rel_to_fun_of_not_forall : forall R a,\n  ~ (forall b, ~ R a b) ->\n  R a (rel_to_fun R a).\nProof using IB.\n  introv. rew_logic. intros [x H]. applys* rel_rel_to_fun_of_exists.\nQed.\n\nLemma rel_in_fun_rel_to_fun : forall R,\n  functional R ->\n  rel_in_fun R (rel_to_fun R).\nProof using IB. unfold rel_in_fun, rel_to_fun. introv M H. epsilon* z. Qed.\n\n(** Reformulation of above *)\n\nLemma rel_to_fun_eq_of_functional : forall x y R,\n  functional R ->\n  R x y ->\n  rel_to_fun R x = y.\nProof using IB. introv M E. applys* rel_in_fun_rel_to_fun. Qed.\n\nEnd Rel_to_fun.\n\n(* Remark: in the special case where [R] has type [A->A->Prop],\n   one may get away without providing a proof of [Inhab A].\n\n  Definition rel_to_fun' A (R : A -> A -> Prop) (a : A) : A :=\n    @rel_to_fun A A (Inhab_of_val a) R a.\n*)\n\n\n\n\n\n\n\n\n(* 2021-08-11 15:24 *)\n", "meta": {"author": "blainehansen", "repo": "coq-playground", "sha": "93619e132a7fabf9d3b796465e253469815a0266", "save_path": "github-repos/coq/blainehansen-coq-playground", "path": "github-repos/coq/blainehansen-coq-playground/coq-playground-93619e132a7fabf9d3b796465e253469815a0266/SLF/LibEpsilon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.6915852545085855}}
{"text": "Require Import List.\nImport ListNotations.\n\nInductive ForallT {A : Type} (P : A -> Type) : list A -> Type :=\n| ForallT_nil : ForallT P []\n| ForallT_cons (x : A) (l : list A) : P x -> ForallT P l -> ForallT P (x :: l).\nHint Constructors ForallT : core.\n\nDefinition fold_ForallT {A R : Type} {P: A -> Type}\n    (hnil : R) (hcons : forall (a : A), P a -> R -> R)\n    xs (pxs : ForallT P xs): R :=\n  ForallT_rect A P (fun _ _ => R) hnil (fun x xs px _ => hcons x px) xs pxs.\n\nDefinition fold_ForallT_manual {A R : Type} {P: A -> Type}\n  (hnil : R) (hcons : forall (a : A), P a -> R -> R) :\n  forall xs, ForallT P xs -> R :=\n    fix F xs pxs :=\n      match pxs return _ with\n      | ForallT_nil _ => hnil\n      | ForallT_cons _ x xs px pxs => hcons x px (F xs pxs)\n      end.\n\n(** To be able to reuse lemmas on Forall, show that ForallT is equivalent to Forall for predicates in Prop.\n    The proof is a bit subtler than you'd think because it can't look into Prop\n    to produce proof-relevant part of the result (and that's why I can't inversion until very late.\n *)\nLemma ForallT_Forall {X} (P: X -> Prop) xs: (ForallT P xs -> Forall P xs) * (Forall P xs -> ForallT P xs).\nProof.\n  split; (induction xs; intro H; constructor; [|apply IHxs]); inversion H; trivial.\nQed.\n", "meta": {"author": "Blaisorblade", "repo": "Coq-playground", "sha": "add7e5b75cfc127b7a76012325a68ddfd9dc463e", "save_path": "github-repos/coq/Blaisorblade-Coq-playground", "path": "github-repos/coq/Blaisorblade-Coq-playground/Coq-playground-add7e5b75cfc127b7a76012325a68ddfd9dc463e/bugs-misc/ForallT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.808067208930584, "lm_q1q2_score": 0.6915852475898724}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Functor.Functor.\n\n(** A constant functor maps all objects to a single object and all arrows to identity arrow of that object. *)\nSection Const_Func.\n  Context (C : Category) {D : Category} (a : @Obj D).\n\n  Program Definition Const_Func : (C –≻ D)%functor :=\n    {|\n      FO := fun _ => a;\n      FA := fun _ _ _ => id a\n    |}.\n\nEnd Const_Func.", "meta": {"author": "amintimany", "repo": "Categories-HoTT", "sha": "fd6018c7abd496b44fd31b1119f6b31795c251d8", "save_path": "github-repos/coq/amintimany-Categories-HoTT", "path": "github-repos/coq/amintimany-Categories-HoTT/Categories-HoTT-fd6018c7abd496b44fd31b1119f6b31795c251d8/Functor/Const_Func.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.691496495060676}}
{"text": "Require Import\n  HoTT.Classes.interfaces.abstract_algebra\n  HoTT.Classes.interfaces.orders\n  HoTT.Classes.orders.orders\n  HoTT.Classes.theory.apartness.\n\nGeneralizable Variables A B C R S f g z.\n\n(* If a function between strict partial orders is order preserving (back), we can\n  derive that it is strictly order preserving (back) *)\nSection strictly_order_preserving.\n  Context `{FullPartialOrder A} `{FullPartialOrder B}.\n\n  Global Instance strictly_order_preserving_inj  `{!OrderPreserving (f : A -> B)}\n    `{!IsStrongInjective f} :\n    StrictlyOrderPreserving f | 20.\n  Proof.\n  intros x y E.\n  apply lt_iff_le_apart in E. apply lt_iff_le_apart.\n  destruct E as [E1 E2]. split.\n  - apply (order_preserving f);trivial.\n  - apply (strong_injective f);trivial.\n  Qed.\n\n  Global Instance strictly_order_reflecting_mor `{!OrderReflecting (f : A -> B)}\n    `{!StrongExtensionality f} :\n    StrictlyOrderReflecting f | 20.\n  Proof.\n  intros x y E.\n  apply lt_iff_le_apart in E. apply lt_iff_le_apart.\n  destruct E as [E1 E2]. split.\n  - apply (order_reflecting f);trivial.\n  - apply (strong_extensionality f);trivial.\n  Qed.\nEnd strictly_order_preserving.\n\n(* For structures with a trivial apartness relation\n   we have a stronger result of the above *)\nSection strictly_order_preserving_dec.\n  Context `{FullPartialOrder A} `{!TrivialApart A}\n          `{FullPartialOrder B} `{!TrivialApart B}.\n\n  Local Existing Instance strict_po_apart.\n\n  Global Instance dec_strictly_order_preserving_inj\n    `{!OrderPreserving (f : A -> B)}\n    `{!IsInjective f} :\n    StrictlyOrderPreserving f | 19.\n  Proof.\n  pose proof (dec_strong_injective f).\n  apply _.\n  Qed.\n\n  Global Instance dec_strictly_order_reflecting_mor\n    `{!OrderReflecting (f : A -> B)}\n    : StrictlyOrderReflecting f | 19.\n  Proof.\n  pose proof (dec_strong_morphism f). apply _.\n  Qed.\nEnd strictly_order_preserving_dec.\n\nSection pseudo_injective.\n  Context `{PseudoOrder A} `{PseudoOrder B}.\n\n  Local Existing Instance pseudo_order_apart.\n\n  Instance pseudo_order_embedding_ext `{!StrictOrderEmbedding (f : A -> B)} :\n    StrongExtensionality f.\n  Proof.\n  intros x y E.\n  apply apart_iff_total_lt;apply apart_iff_total_lt in E.\n  destruct E; [left | right]; apply (strictly_order_reflecting f);trivial.\n  Qed.\n\n  Lemma pseudo_order_embedding_inj `{!StrictOrderEmbedding (f : A -> B)} :\n    IsStrongInjective f.\n  Proof.\n  split;try apply _.\n  intros x y E.\n  apply apart_iff_total_lt;apply apart_iff_total_lt in E.\n  destruct E; [left | right]; apply (strictly_order_preserving f);trivial.\n  Qed.\nEnd pseudo_injective.\n\n(* If a function between pseudo partial orders is strictly order preserving (back),\n   we can derive that it is order preserving (back) *)\nSection full_pseudo_strictly_preserving.\n  Context `{FullPseudoOrder A} `{FullPseudoOrder B}.\n\n  Local Existing Instance pseudo_order_apart.\n\n  Lemma full_pseudo_order_preserving `{!StrictlyOrderReflecting (f : A -> B)}\n    : OrderPreserving f.\n  Proof.\n  intros x y E1.\n  apply le_iff_not_lt_flip;apply le_iff_not_lt_flip in E1.\n  intros E2. apply E1.\n  apply (strictly_order_reflecting f).\n  trivial.\n  Qed.\n\n  Lemma full_pseudo_order_reflecting `{!StrictlyOrderPreserving (f : A -> B)}\n    : OrderReflecting f.\n  Proof.\n  intros x y E1.\n  apply le_iff_not_lt_flip;apply le_iff_not_lt_flip in E1.\n  intros E2. apply E1.\n  apply (strictly_order_preserving f).\n  trivial.\n  Qed.\nEnd full_pseudo_strictly_preserving.\n\n(* Some helper lemmas to easily transform order preserving instances. *)\nSection order_preserving_ops.\n  Context `{Le R}.\n\n  Lemma order_preserving_flip {op} `{!Commutative op} `{!OrderPreserving (op z)}\n    : OrderPreserving (fun y => op y z).\n  Proof.\n  intros x y E.\n  rewrite 2!(commutativity _ z).\n  apply order_preserving;trivial.\n  Qed.\n\n  Lemma order_reflecting_flip {op} `{!Commutative op}\n    `{!OrderReflecting (op z) }\n    : OrderReflecting (fun y => op y z).\n  Proof.\n  intros x y E.\n  apply (order_reflecting (op z)).\n  rewrite 2!(commutativity (f:=op) z).\n  trivial.\n  Qed.\n\n  Lemma order_preserving_nonneg (op : R -> R -> R) `{!Zero R}\n    `{forall z, PropHolds (0 ≤ z) -> OrderPreserving (op z)} z\n    : 0 ≤ z -> forall x y, x ≤ y -> op z x ≤ op z y.\n  Proof.\n  auto.\n  Qed.\n\n  Lemma order_preserving_flip_nonneg (op : R -> R -> R) `{!Zero R}\n    {E:forall z, PropHolds (0 ≤ z) -> OrderPreserving (fun y => op y z)} z\n    : 0 ≤ z -> forall x y, x ≤ y -> op x z ≤ op y z.\n  Proof.\n  apply E.\n  Qed.\n\n  Context `{Lt R}.\n\n  Lemma order_reflecting_pos (op : R -> R -> R) `{!Zero R}\n    {E:forall z, PropHolds (0 < z) -> OrderReflecting (op z)} z\n    : 0 < z -> forall x y, op z x ≤ op z y -> x ≤ y.\n  Proof.\n  apply E.\n  Qed.\n\n  Lemma order_reflecting_flip_pos (op : R -> R -> R) `{!Zero R}\n    {E:forall z, PropHolds (0 < z) -> OrderReflecting (fun y => op y z)} z\n    : 0 < z -> forall x y, op x z ≤ op y z -> x ≤ y.\n  Proof.\n  apply E.\n  Qed.\n\nEnd order_preserving_ops.\n\nSection strict_order_preserving_ops.\n  Context `{Lt R}.\n\n  Lemma strictly_order_preserving_flip {op} `{!Commutative op}\n    `{!StrictlyOrderPreserving (op z)}\n    : StrictlyOrderPreserving (fun y => op y z).\n  Proof.\n  intros x y E.\n  rewrite 2!(commutativity _ z).\n  apply strictly_order_preserving;trivial.\n  Qed.\n\n  Lemma strictly_order_reflecting_flip {op} `{!Commutative op}\n    `{!StrictlyOrderReflecting (op z) }\n    : StrictlyOrderReflecting (fun y => op y z).\n  Proof.\n  intros x y E.\n  apply (strictly_order_reflecting (op z)).\n  rewrite 2!(commutativity (f:=op) z).\n  trivial.\n  Qed.\n\n  Lemma strictly_order_preserving_pos (op : R -> R -> R) `{!Zero R}\n    {E:forall z, PropHolds (0 < z) -> StrictlyOrderPreserving (op z)} z\n    : 0 < z -> forall x y, x < y -> op z x < op z y.\n  Proof.\n  apply E.\n  Qed.\n\n  Lemma strictly_order_preserving_flip_pos (op : R -> R -> R) `{!Zero R}\n    {E:forall z, PropHolds (0 < z) -> StrictlyOrderPreserving (fun y => op y z)} z\n    : 0 < z -> forall x y, x < y -> op x z < op y z.\n  Proof.\n  apply E.\n  Qed.\n\nEnd strict_order_preserving_ops.\n\nLemma projected_partial_order `{IsHSet A} {Ale : Le A}\n  `{is_mere_relation A Ale} `{Ble : Le B}\n  (f : A -> B) `{!IsInjective f} `{!PartialOrder Ble}\n  : (forall x y, x ≤ y <-> f x ≤ f y) -> PartialOrder Ale.\nProof.\nintros P. repeat split.\n- apply _.\n- apply _.\n- intros x. apply P. apply reflexivity.\n- intros x y z E1 E2. apply P.\n  transitivity (f y); apply P;trivial.\n- intros x y E1 E2. apply (injective f).\n  apply (antisymmetry (≤)); apply P;trivial.\nQed.\n\nLemma projected_total_order `{Ale : Le A} `{Ble : Le B}\n  (f : A -> B) `{!TotalRelation Ble}\n  : (forall x y, x ≤ y <-> f x ≤ f y) -> TotalRelation Ale.\nProof.\nintros P x y.\ndestruct (total (≤) (f x) (f y)); [left | right]; apply P;trivial.\nQed.\n\nLemma projected_strict_order `{Alt : Lt A} `{is_mere_relation A lt} `{Blt : Lt B}\n  (f : A -> B) `{!StrictOrder Blt}\n  : (forall x y, x < y <-> f x < f y) -> StrictOrder Alt.\nProof.\nintros P. split.\n- apply _.\n- intros x E. destruct (irreflexivity (<) (f x)). apply P. trivial.\n- intros x y z E1 E2. apply P. transitivity (f y); apply P;trivial.\nQed.\n\nLemma projected_pseudo_order `{IsApart A} `{Alt : Lt A} `{is_mere_relation A lt}\n  `{Apart B} `{Blt : Lt B}\n  (f : A -> B) `{!IsStrongInjective f} `{!PseudoOrder Blt}\n  : (forall x y, x < y <-> f x < f y) -> PseudoOrder Alt.\nProof.\npose proof (strong_injective_mor f).\nintros P. split; try apply _.\n- intros x y E. apply (pseudo_order_antisym (f x) (f y)).\n  split; apply P,E.\n- intros x y E z. apply P in E.\n  apply (merely_destruct (cotransitive E (f z)));\n  intros [?|?];apply tr; [left | right]; apply P;trivial.\n- intros x y; split; intros E.\n  + apply (strong_injective f) in E.\n    apply apart_iff_total_lt in E.\n    destruct E; [left | right]; apply P;trivial.\n  + apply (strong_extensionality f).\n    apply apart_iff_total_lt.\n    destruct E; [left | right]; apply P;trivial.\nQed.\n\nLemma projected_full_pseudo_order `{IsApart A} `{Ale : Le A} `{Alt : Lt A}\n  `{is_mere_relation A le} `{is_mere_relation A lt}\n  `{Apart B} `{Ble : Le B} `{Blt : Lt B}\n  (f : A -> B) `{!IsStrongInjective f} `{!FullPseudoOrder Ble Blt}\n  : (forall x y, x ≤ y <-> f x ≤ f y) -> (forall x y, x < y <-> f x < f y) ->\n    FullPseudoOrder Ale Alt.\nProof.\nintros P1 P2. split.\n- apply _.\n- apply (projected_pseudo_order f);assumption.\n- intros x y; split; intros E.\n  + intros F. destruct (le_not_lt_flip (f y) (f x));[apply P1|apply P2];trivial.\n  + apply P1. apply not_lt_le_flip.\n    intros F. apply E,P2. trivial.\nQed.\n\nGlobal Instance id_order_preserving `{PartialOrder A} : OrderPreserving (@id A).\nProof.\nred;trivial.\nQed.\n\nGlobal Instance id_order_reflecting `{PartialOrder A} : OrderReflecting (@id A).\nProof.\nred;trivial.\nQed.\n\nSection composition.\n  Context {A B C} `{Le A} `{Le B} `{Le C} (f : A -> B) (g : B -> C).\n\n  Instance compose_order_preserving:\n    OrderPreserving f -> OrderPreserving g -> OrderPreserving (g ∘ f).\n  Proof.\n  red;intros. unfold Compose.\n  do 2 apply (order_preserving _).\n  trivial.\n  Qed.\n\n  Instance compose_order_reflecting:\n    OrderReflecting f -> OrderReflecting g -> OrderReflecting (g ∘ f).\n  Proof.\n  intros ?? x y E. unfold Compose in E.\n  do 2 apply (order_reflecting _) in E.\n  trivial.\n  Qed.\n\n  Instance compose_order_embedding:\n    OrderEmbedding f -> OrderEmbedding g -> OrderEmbedding (g ∘ f) := {}.\nEnd composition.\n\n#[export]\nHint Extern 4 (OrderPreserving (_ ∘ _)) =>\n  class_apply @compose_order_preserving : typeclass_instances.\n#[export]\nHint Extern 4 (OrderReflecting (_ ∘ _)) =>\n  class_apply @compose_order_reflecting : typeclass_instances.\n#[export]\nHint Extern 4 (OrderEmbedding (_ ∘ _)) =>\n  class_apply @compose_order_embedding : typeclass_instances.\n\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Classes/orders/maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636752, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6914964825871146}}
{"text": "\n\nRequire Import PeanoNat.\n\n(*nvalue Data Structure*)\nInductive nvalue (A:Type):Type:=\n| default (n:A) : nvalue A\n| device (n:nat) (y:A) : nvalue A -> nvalue A.\n\n\n(*get single device value*)\nFixpoint get {A} (pos:nat) (n:nvalue A):A:=\nmatch n with\n| default _ x => x\n| device _ i x m => if (pos=?i) then x else (get pos m)\nend.\n\nFixpoint getDefault {A} (n:nvalue A): A :=\nmatch n with\n| default _ x => x\n| device _ i x m => getDefault m\nend.\n\n(*ordered predicate*)\nInductive ordered {A} :nvalue A -> Prop :=\n| ordered0 : forall x, ordered (default A x)\n| ordered1 : forall a0 b0 b1, ordered ((device A a0 b0 (default A b1)))\n| ordered2 : forall a0 a1 m b0 b1, lt a0 a1 -> ordered (device A a1 b1 m) -> ordered ((device A a0 b0 (device A a1 b1 m))).\n\n\n\n\n(*\nFixpoint defaultV {A} (n:nvalue A): A :=\nmatch n with\n| default _ x => x\n| device _ _ _ m => defaultV m\nend.\n(*Operation between two nvalues*)\n(*A is the type of nvalue, op is the point-wise operation*)\n(*nvalues need to be ordered, this is achieved by a properly insertion in the data type*)\n(*It's possible to define a pointwise operation on non order nvalues,\nbut we must to assure that the nvalue don't contains duplicates*)\nFixpoint pointWise {A} (op:A->A->A) (w0:nvalue A) {struct w0}: nvalue A -> nvalue A:=\nfix pointWise1 (w1:nvalue A) {struct w1}: nvalue A :=\nmatch w0,w1 with\n| default _ x , default _ y => default A (op x y)\n| default _ x , device _ a b m  =>  device A a b (pointWise1 m) \n| device _ a b m , default _ x  => device A a b (pointWise op  m (default A x)) \n| device _ a0 b0 m0 , device _ a1 b1 m1  => if (a0=?a1) then device A a0 (op b0 b1) (pointWise op m0 m1)\n                                            else (if (a0<?a1) then device A a0 (op b0 (defaultV m1)) (pointWise op m0 (device A a1 b1 m1))\n                                            else device A a1 (op (defaultV m0) b1) (pointWise1 m1 ))\nend.\n\n\n(*check*)\nDefinition int_sum (x:nat) (y:nat) : nat :=  x + y.\nCompute(pointWise int_sum (device nat 1 2(device nat 3 5(device nat 5 7(device nat 7 3(default nat 1))))) (device nat 2 2(device nat 4 5(device nat 6 7(device nat 7 3(default nat 2)))))).\n\n\n\n\nLemma first: ordered (default nat 5).\nProof.\napply ordered0.\nQed.\n\nLemma second: ordered(device nat 3 5(default nat 4)).\nProof.\napply ordered1.\nQed.\n\nSearch lt.\nLemma third: ordered(device nat 2 5(device nat 3 5(default nat 4))).\nProof.\napply ordered2. apply Nat.lt_succ_diag_r. apply ordered1.\nQed.\n*)\n\n\n", "meta": {"author": "fcpp-experiments", "repo": "coq-formalisation", "sha": "edd650963f47184ee1f67c5f2b4833bdc93f8608", "save_path": "github-repos/coq/fcpp-experiments-coq-formalisation", "path": "github-repos/coq/fcpp-experiments-coq-formalisation/coq-formalisation-edd650963f47184ee1f67c5f2b4833bdc93f8608/lib/nvalue.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6914389987654105}}
{"text": "Require Import Setoid Morphisms Vector.\n\nClass Equiv A := equiv : A -> A -> Prop.\nClass Setoid A `{Equiv A} := setoid_equiv:> Equivalence (equiv).\n\nGlobal Declare Instance vec_equiv {A} `{Equiv A} {n}: Equiv (Vector.t A n).\nGlobal Declare Instance vec_setoid A `{Setoid A} n : Setoid (Vector.t A n).\n\nGlobal Declare Instance tl_proper1 {A} `{Equiv A} n:\n  Proper ((equiv) ==> (equiv))\n         (@tl A n).\n\nLemma test:\n  forall {A} `{Setoid A} n (xa ya: Vector.t A (S n)),\n    (equiv xa ya) -> equiv (tl xa) (tl ya).\nProof.\n  intros A R HA n xa ya Heq.\n  setoid_rewrite Heq.\n  reflexivity.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/bugs/closed/4232.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6914389865568709}}
{"text": "Require Import Wellfounded Wf_nat Lexicographic_Product Relation_Operators.\nRequire Import base generic_set_theory.\nRequire Import NArith NArith.Nnat.\n\nSection LIM_CARD.\n\n  Variable A:Type.\n  Context `{AOrd : OrderedType A}.\n    \n  Inductive lim_card (z:nat) : set A -> set A -> Prop :=\n  | in_re_set : forall x y:set A, \n    z - (cardinal x) < z - (cardinal y) -> lim_card z x y.\n\n  Definition lim_cardN (z:N) : relation (set A) :=\n  fun x y:set A => nat_of_N z - (cardinal x) < nat_of_N z - (cardinal y).\n\n  Theorem le_trans1 : forall n m p, n <= m -> m <= p -> n <= p.\n  Proof.\n    induction 2; auto.\n  Defined.\n\n  Theorem le_S_n1 : forall n m, S n <= S m -> n <= m.\n  Proof.\n    intros n m H; change (pred (S n) <= pred (S m)) in |- *.\n    destruct H; simpl. \n    constructor.\n    apply (le_trans1 _ (S n) _).\n    constructor.\n    constructor.\n    exact H.\n  Defined.\n\n  Lemma lim_card_wf : forall z,  well_founded (lim_card z).\n  Proof.\n    unfold well_founded.\n    intros.\n    cut(forall n a, lt (z - (cardinal a)) n -> Acc (lim_card z) a).\n    intros.\n    eapply H with (S (z - (cardinal a))).\n    unfold lt.\n    constructor.\n      \n    induction n;intros.\n    inversion H.\n    constructor;intros.\n    inversion_clear H0.\n    apply IHn.\n    unfold lt in H, H1.\n    unfold lt.\n    apply (@le_trans1 _ _ _ H1).\n    apply le_S_n1 in H.\n    exact H.\n  Defined.\n\n  Lemma lim_card_lim_cardN_inclusion :\n    forall z, inclusion (set A) (lim_cardN z) (lim_card (nat_of_N z)).\n  Proof.\n    repeat red.\n    intros.\n    unfold lim_cardN in H.\n    constructor.\n    assumption.\n  Qed.\n\n  Lemma lim_cardN_wf : forall z, well_founded (lim_cardN z).\n  Proof.\n    intro z.\n    red.\n    eapply wf_incl.\n    eapply lim_card_lim_cardN_inclusion.\n    apply lim_card_wf.\n  Qed.\n\n  (* Definition dec_H (x y:set A) := *)\n  (*   cardinal x < cardinal y. *)\n\n  (* Lemma dec_H_wf : well_founded dec_H. *)\n  (* Proof. *)\n  (*   red. *)\n  (*   intros. *)\n  (*   apply Acc_inverse_image. *)\n  (*   apply Wf_nat.lt_wf. *)\n  (* Defined. *)\n  \n  Open Scope N_scope.\n\n  Fixpoint pow2N(n:nat):N :=\n    match n with\n      | O => 1\n      | S m => 2 * pow2N m\n    end.\n\n  Lemma pow2N_S : forall n,\n    pow2N (S n) = 2*pow2N n.\n  Proof.\n    induction n.\n    reflexivity.\n    destruct n;auto with arith.\n  Qed.\n\n  Close  Scope N_scope.\n\n  Lemma pow2N_S_nat : forall n,\n    nat_of_N (pow2N (S n)) = 2*nat_of_N (pow2N n).\n  Proof.\n    induction n.\n    reflexivity.\n    rewrite pow2N_S.\n    rewrite nat_of_Nmult.\n    rewrite IHn.\n    reflexivity.\n  Qed.\n\n  Fixpoint pow2(n:nat):nat :=\n    match n with\n      | O => 1\n      | S m => 2 * pow2 m\n    end.\n\n  Lemma pow2_pow2N_equiv : forall n,\n    nat_of_N (pow2N n) = pow2 n.\n  Proof.\n    induction n.\n    simpl.\n    reflexivity.\n    rewrite pow2N_S_nat.\n    rewrite IHn.\n    simpl.\n    omega.\n  Qed.\n\n  Lemma pow2_S : forall n, \n    pow2 (S n) = 2*pow2 n.\n  Proof.\n    induction n;simpl;omega.\n  Qed.\n\n  Lemma pow2_le : forall n m,\n    n <= m -> pow2 n <= pow2 m.\n  Proof.\n    induction 1;simpl;try omega.\n  Qed.\n\n  Lemma add_plus_nat :\n    forall x y,\n      (S x)* y = y + x*y.\n  Proof.\n    induction x;simpl;intros.\n    reflexivity.\n    omega.\n  Qed.\n\n  (*Transparent cart_prod.*)\n\n  Lemma cart_prod_add_right :\n    forall x x1 s,\n    cart_prod {x} {x1; s} === cart_prod {x} {x1} ++ cart_prod {x} s.\n  Proof.\n    split;intros.\n    apply cart_prod_spec in H.\n    destruct H.\n    apply add_iff in H0.\n    destruct H0.\n    apply union_2.\n    apply cart_prod_spec.\n    split;auto with typeclass_instances.\n    rewrite H0.\n    apply singleton_2;auto.\n    apply union_3.\n    apply cart_prod_spec.\n    split;auto.\n    apply union_1 in H.\n    destruct H;apply cart_prod_spec in H;apply cart_prod_spec;destruct H;split;auto.\n    apply add_1.\n    apply singleton_1 in H0.\n    assumption.\n    apply add_2;auto.\n  Qed.       \n\n  Corollary map_singleton : \n    forall x0 x,\n      cart_prod {x0} {x} === singleton (pair x0 x).\n  Proof.\n    split;intros.\n    apply cart_prod_spec in H;destruct H as [H1 H2];\n    apply singleton_1 in H1;apply singleton_1 in H2.\n    apply singleton_2.\n    destruct a;simpl in *.\n    constructor;auto.\n    apply singleton_1 in H;destruct a;simpl in *.\n    apply cart_prod_spec;simpl;split;apply singleton_2;\n    inversion H;normalize_notations;auto.\n  Qed.\n\n  Lemma cardinal_cart_prod_singleton : \n    forall s2 x,\n      cardinal (cart_prod {x} s2) = cardinal s2.\n  Proof.\n    induction s2 using set_induction;intros.\n    cut(cart_prod {x} s2 === {}).\n    abstract(intros;rewrite (@Equal_cardinal _ _ _ _ _ _ H0);symmetry;rewrite cardinal_fold;\n             rewrite fold_1b;eauto).\n    abstract(\n        split;intros;[apply cart_prod_spec in H0;destruct H0;apply H in H1;elim H1|inversion H0]).\n\n    cut(cart_prod {x0} s2_2 === cart_prod {x0} {x;s2_1}).\n    intro;\n    rewrite (@Equal_cardinal _ _ _ _ _ _ H1);\n    pose proof cart_prod_add_right x0 x s2_1;\n    rewrite (@Equal_cardinal _ _ _ _ _ _ H2);\n    rewrite map_singleton;\n    apply Add_Equal in H0;\n    rewrite H0;\n    apply Add_Equal in H0;\n    rewrite union_cardinal_inter.\n    assert(inter {(x0, x)} (cart_prod {x0} s2_1) === {}) by \n    abstract(split;intros;try (now (inversion H3));\n    apply inter_iff in H3;destruct H3;apply cart_prod_spec in H4;\n    destruct H4;\n    apply singleton_1 in H3;\n    apply singleton_1 in H4;\n    destruct a ;simpl in *;inversion H3;subst;rewrite <- H11 in H5;\n    contradiction).\n    rewrite H3, singleton_cardinal,empty_cardinal.\n    simpl.\n    rewrite add_cardinal_2;eauto.\n    apply Add_Equal in H0;apply cart_prod_m;eauto.\n  Qed.\n\n  Lemma cart_prod_add :\n    forall x s1 s2, \n      cart_prod {x;s1} s2 === cart_prod {x} s2 ++ cart_prod s1 s2.\n  Proof.\n    split;intros.\n    apply cart_prod_spec in H.\n    destruct H.\n    apply add_iff in H.\n    destruct H.\n    apply union_2.\n    apply cart_prod_spec.\n    split;auto.\n    apply singleton_2.\n    assumption.\n    apply union_3.\n    apply cart_prod_spec.\n    split;auto.\n    apply union_iff in H;destruct H.\n    apply cart_prod_spec in H.\n    apply cart_prod_spec.\n    destruct H.\n    split;auto.\n    apply add_1.\n    apply singleton_1 in H.\n    assumption.\n    apply cart_prod_spec in H.\n    apply cart_prod_spec.\n    destruct H.\n    split;eauto.\n    apply add_2;eauto.\n  Qed.\n\n  Lemma cart_prod_empty :\n    forall s1 s2, s1 === {} -> cart_prod s1 s2 === {}.\n  Proof.\n    split;intros.\n    apply cart_prod_spec in H0.\n    destruct H0.\n    apply H in H0.\n    abstract(inversion H0).\n    abstract(inversion H0).\n  Qed.\n\n  Lemma cart_prod_card : forall s1 s2,\n    cardinal (cart_prod s1 s2) = cardinal s1 * cardinal s2.\n  Proof.\n    induction s1 using set_induction.\n    intros.\n    symmetry.\n    rewrite cardinal_fold.\n    rewrite fold_1b;auto.\n    simpl.\n    apply empty_is_empty_1 in H.\n    pose proof cart_prod_empty s1 s2 H.\n    symmetry.\n    apply empty_is_empty_2 in H0.\n    rewrite cardinal_fold.\n    rewrite fold_1b;auto.\n    intros.\n    specialize IHs1_1 with s2.\n    cut(cart_prod s1_2 s2 === cart_prod {x;s1_1} s2).\n    intro.\n    pose proof @Equal_cardinal _ _ _ _ _ _ H1.\n    rewrite H2.\n    rewrite cart_prod_add.\n    pose proof H0.\n    apply Add_Equal in H3.\n    rewrite H3.\n    pose proof @add_cardinal_2 _ _ _ _ s1_1 x H. \n    rewrite H4.\n    rewrite add_plus_nat.\n    rewrite <- IHs1_1.\n    assert((inter (cart_prod {x} s2) (cart_prod s1_1 s2)) === {}).\n    split;intros.\n    apply inter_iff in H5.\n    destruct H5.\n    apply cart_prod_spec in H5.\n    destruct H5.\n    apply singleton_1 in H5.\n    apply cart_prod_spec in H6.\n    destruct H6.\n    rewrite <- H5 in H6.\n    contradiction.\n    inversion H5.\n    rewrite union_cardinal_inter.\n    rewrite H5.\n    rewrite empty_cardinal.\n    rewrite IHs1_1.\n    rewrite cardinal_cart_prod_singleton.\n    rewrite <- minus_n_O;reflexivity.\n    apply Add_Equal in H0.\n    apply cart_prod_m;auto.\n  Qed.\n\n  Lemma powerset_empty :\n    (powerset {}) === singleton (empty).\n  Proof.\n    split;intros.\n    apply powerset_spec in H.\n    apply singleton_2.\n    split;intros.\n    inv H0.\n    apply H;auto.\n    apply singleton_1 in H.\n    apply powerset_spec.\n    red;intros.\n    apply H in H0.\n    assumption.\n  Qed.\n\n  Lemma powerset_Empty :\n    forall s,\n      s === {} -> powerset s === singleton empty.\n  Proof.\n    intros.\n    split;intros.\n    apply powerset_spec in H0.\n    rewrite H in H0.\n    apply singleton_2.\n    split;intros.\n    inversion H1.\n    apply H0 in H1.\n    assumption.\n\n    apply singleton_1 in H0.\n    apply powerset_spec.\n    red;intros.\n    apply H.\n    rewrite <- H0 in H1.\n    assumption.\n  Qed.\n\n  Transparent powerset.\n\n  Instance add_vals_m : \n    forall x, Proper (_eq ==> Equal ==> Equal) (fun y : set A => add {x; y}).\n  Proof.\n    repeat red.\n    split;intros.\n    apply add_iff in H1;destruct H1.\n    rewrite <- H1.\n    rewrite H.\n    apply add_1;auto.\n    rewrite H0 in H1.\n    apply add_2;auto.\n    apply add_iff in H1;destruct H1.\n    rewrite <- H1.\n    rewrite H.\n    apply add_1;auto.\n    rewrite H0.\n    apply add_2;auto.\n  Qed.\n\n  Lemma add_vals_transp : \n    forall x, transpose Equal (fun y : set A => add {x; y}).\n  Proof.\n    repeat red.\n    split;intros.\n    apply add_iff in H;destruct H.\n    rewrite <- H.\n    apply add_2;apply add_1;auto.\n    apply add_iff in H;destruct H.\n    apply add_1;auto.\n    do 2 apply add_2;auto.\n    apply add_iff in H;destruct H.\n    rewrite <- H.\n    apply add_2;apply add_1;auto.\n    apply add_iff in H;destruct H.\n    rewrite <- H.\n    apply add_1;auto.\n    do 2 apply add_2;auto.\n  Qed.\n\n  Property subset_empty :\n  forall s, \n    s[<=]{} -> s === {}.\n  Proof.\n    induction s using set_induction;intros.\n    split;intros.\n    apply H0;auto.\n    inversion H1.\n    split;intros.\n    apply H0 in H2.\n    destruct H2.\n    apply H1.\n    apply H0.\n    left;auto.\n    assert(a \\In s2).\n    apply H0.\n    right;auto.\n    apply H1 in H3.\n    assumption.\n    inversion H2.\n  Qed.\n\n  Lemma empty_in_powerset :\n    forall s, \n      {} \\In powerset s.\n  Proof.\n    intros.\n    apply powerset_spec.\n    red;intros.\n    inv H.\n  Qed.\n\n  Lemma add_not_empty :\n    forall x s,\n      {} =/= {x;s}.\n  Proof.\n    intros;intro.\n    destruct(H x).\n    assert(x \\In {x;s}).\n    apply add_1;auto.\n    apply H1 in H2.\n    inversion H2.\n  Qed.\n\n  Instance powerset_add_m : forall x, \n    Proper (_eq ==> _eq) (fun y : set A => {x; y}).\n  Proof.\n    repeat red;split;intros;apply add_iff in H0;destruct H0.\n    rewrite <- H0;apply add_1;auto.\n    apply H in H0;apply add_2;auto.\n    rewrite H0;apply add_1;auto.\n    rewrite H;apply add_2;auto.\n  Qed.\n\n  Instance add_one_m : Proper (_eq ==> _eq ==> _eq) add_one.\n  Proof.\n    repeat red.\n    intros.\n    split;intros.\n    apply add_one_spec in H1.\n    apply add_one_spec.\n    rewrite H0 in H1.\n    destruct H1;auto.\n    right.\n    destruct H1.\n    exists x1.\n    rewrite H0 in H1.\n    rewrite H in H1.\n    assumption.\n    apply add_one_spec in H1.\n    apply add_one_spec.\n    rewrite H0.\n    destruct H1;auto.\n    right.\n    destruct H1.\n    exists x1.\n    rewrite H;auto.\n    rewrite H0.\n    assumption.\n  Qed.\n\n\n  Lemma transpose_add_one : transpose equiv add_one.\n  Proof.\n    red;intros.\n    split;intros.\n    apply add_one_spec in H.\n    destruct H.\n    apply add_one_spec in H.\n    destruct H.\n    apply add_one_spec.\n    left;apply add_one_spec;auto.\n    destruct H as [a' [H1 H2]].\n    apply add_one_spec.\n    right.\n    exists a';split;auto.\n    apply add_one_spec;auto.\n    destruct H as [a' [H1 H2]].\n    eapply add_one_spec in H1.\n    destruct H1.\n    apply add_one_spec.\n    left.\n    apply add_one_spec.\n    right;exists a';auto.\n    destruct H as [a'' [H3 H4]].\n    assert(a[=]{y;{x;a''}}).\n    split;intros.\n    apply H2 in H.\n    rewrite H4 in H.\n    apply add_iff in H.\n    destruct H.\n    rewrite H.\n    apply add_2;apply add_1;auto.\n    apply add_iff in H.\n    destruct H.\n    rewrite H;apply add_1;auto.\n    apply add_2;apply add_2;auto.\n    apply add_iff in H;destruct H.\n    rewrite H2,H4.\n    rewrite <- H.\n    apply add_2;apply add_1;auto.\n    apply add_iff in H;destruct H.\n    rewrite H2.\n    rewrite <- H.\n    apply add_1;auto.\n    rewrite H2,H4.\n    apply add_2;apply add_2;auto.\n    apply add_one_spec.\n    right.\n    exists {x;a''}.\n    split;auto.\n    apply add_one_spec.\n    right.\n    exists a'';split;auto.\n    reflexivity.\n    apply add_one_spec in H.\n    destruct H.\n    apply add_one_spec in H.\n    destruct H.\n    apply add_one_spec.\n    left;apply add_one_spec;auto.\n    destruct H as [a' [H1 H2]].\n    apply add_one_spec.\n    right.\n    exists a';split;auto.\n    apply add_one_spec;auto.\n    destruct H as [a' [H1 H2]].\n    eapply add_one_spec in H1.\n    destruct H1.\n    apply add_one_spec.\n    left.\n    apply add_one_spec.\n    right;exists a';auto.\n    destruct H as [a'' [H3 H4]].\n    assert(a[=]{x;{y;a''}}).\n    split;intros.\n    apply H2 in H.\n    rewrite H4 in H.\n    apply add_iff in H.\n    destruct H.\n    rewrite H.\n    apply add_2;apply add_1;auto.\n    apply add_iff in H.\n    destruct H.\n    rewrite H;apply add_1;auto.\n    apply add_2;apply add_2;auto.\n    apply add_iff in H;destruct H.\n    rewrite H2,H4.\n    rewrite <- H.\n    apply add_2;apply add_1;auto.\n    apply add_iff in H;destruct H.\n    rewrite H2.\n    rewrite <- H.\n    apply add_1;auto.\n    rewrite H2,H4.\n    apply add_2;apply add_2;auto.\n    apply add_one_spec.\n    right.\n    exists {y;a''}.\n    split;auto.\n    apply add_one_spec.\n    right.\n    exists a'';split;auto.\n    reflexivity.\n  Qed.\n\n  Lemma powerset_step :\n    forall s2 s1 x,\n      ~x \\In s1 ->\n      Add x s1 s2 ->\n      powerset s2 === powerset s1 ++ map (fun y => add x y) (powerset s1).\n  Proof.\n    intros.\n    unfold powerset.\n    rewrite (@fold_2 A AOrd _ _ s1 s2 x);auto with typeclass_instances.\n    split;intros.\n    apply add_one_spec in H1.\n    destruct H1.\n    apply union_2;auto.\n    apply union_3.\n    apply map_spec;auto with typeclass_instances.\n    apply union_iff in H1;destruct H1.\n    apply add_one_spec.\n    left;auto.\n    apply add_one_spec.\n    apply map_iff in H1;auto with typeclass_instances.\n    unfold equiv;auto with typeclass_instances.\n    apply transpose_add_one.\n  Qed.\n\n  Lemma map_add : forall s s' x,\n                    s' \\In (map (fun y : set A => {x; y}) s) <->\n                      x \\In s' /\\ (s' \\In s \\/ (remove x s') \\In  s).\n  Proof.\n    intros.\n    split;intros.\n    apply map_iff in H;auto with typeclass_instances.\n    destruct H.\n    destruct H.\n    split.\n    rewrite H0.\n    apply add_1;auto.\n    destruct(In_dec x x0).\n    rewrite add_equal in H0;auto.\n    left.\n    rewrite H0.\n    assumption.\n    right.\n    rewrite H0.\n    pose proof @remove_add _ _ _ _ x0 x n.\n    rewrite H1.\n    assumption.\n\n    destruct H.\n    destruct H0.\n    apply map_iff;auto with typeclass_instances.\n    exists s'.\n    split.\n    assumption.\n    rewrite add_equal;auto.\n    apply map_iff;auto with typeclass_instances.\n    exists (remove x s').\n    split;auto.\n    split;intros.\n    destruct(eq_dec x a).\n    rewrite <- H2.\n    apply add_1;auto.\n    apply add_2.\n    apply remove_iff.\n    split;auto.\n    apply add_iff in H1.\n    destruct H1.\n    rewrite <- H1;auto.\n    apply remove_iff in H1.\n    destruct H1;auto.\n  Qed.\n \n  Transparent map.\n\n  Lemma powerset_cardinal : forall s,\n    cardinal (powerset s) = pow2 (cardinal s).\n  Proof.\n    induction s using set_induction;intros.\n   \n    symmetry ; rewrite cardinal_fold.\n    rewrite fold_1b;auto.\n    simpl.\n    pose proof powerset_empty.\n    apply Equal_cardinal in H0.\n    assert(powerset s === powerset {}).\n    apply empty_is_empty_1 in H.\n    split;intros.\n    apply powerset_spec.\n    apply powerset_spec in H1.\n    red;intros.\n    apply H1 in H2.\n    apply H in H2.\n    assumption.\n    apply powerset_spec in H1.\n    apply powerset_spec.\n    rewrite <- H in H1.\n    assumption.\n    apply Equal_cardinal in H1.\n    rewrite H1.\n    rewrite H0.\n    vm_compute.\n    reflexivity.\n\n    pose proof powerset_step _ _ _ H H0.\n    rewrite H1.\n    rewrite union_cardinal.\n    rewrite map_cardinal;auto with typeclass_instances.\n    rewrite IHs1.\n    rewrite (cardinal_2 H H0).\n    simpl;auto with arith.\n    intros u v.\n    rewrite 2 powerset_spec.\n    red;red;intros.\n    simpl.\n    red.\n    intro.\n    red.\n    generalize (H4 a) (H2 a) (H3 a).\n    set_iff.\n    clear H2 H3 H4.\n    intuition;auto with sets. \n    rewrite <- H7 in H9;apply H in H9;elim H9.\n    rewrite <- H7 in H9;apply H in H9;elim H9.\n    rewrite <- H8 in H9;apply H in H9;elim H9.    \n    rewrite <- H8 in H9;apply H in H9;elim H9.\n    intros u (X,Y).\n    apply powerset_spec in X.\n    rewrite map_add in Y.\n    destruct Y as (Y,_).\n    apply X in Y.\n    contradiction.\n  Qed.\n\n  (* Definition of the well_founded relation *)\n  (*Definition lex (MAX:nat) := (lexprod (set A) (fun _:set A => set A)\n    (lim_card MAX) (fun _:set A => dec_H)). \n\n\n  Lemma lex_wf : forall M:nat, well_founded (lex M).\n  Proof.\n    intro.\n    apply wf_lexprod.\n    apply lim_card_wf.\n    intro.\n    apply dec_H_wf.\n  Defined.*)\n\nEnd LIM_CARD.\n\n\n", "meta": {"author": "dmrpereira", "repo": "PDCoq", "sha": "c0f6a96177538eae3e933f35265522a5f05582fa", "save_path": "github-repos/coq/dmrpereira-PDCoq", "path": "github-repos/coq/dmrpereira-PDCoq/PDCoq-c0f6a96177538eae3e933f35265522a5f05582fa/RegExprs/wf_extra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6914389847524877}}
{"text": "(*Daniel Rivas*)\nVariables A : Set.\nVariables P Q : A -> A -> Prop.\n(*first validation*)\nLemma proof1: (forall y x:A, P x y) -> (forall z x y:A, Q z x ->\nQ z y) -> (forall x:A, P x x).\nProof.\nintros.\napply H.\nQed.\n(*second validation*)\nLemma proof2: (forall z x y:A, Q z x -> Q z y) -> \n(forall y x:A, P x y) ->  (forall x:A, P x x).\nProof.\nintros.\napply H0.\nQed.\n\n\n", "meta": {"author": "JoanDaniel18", "repo": "Coq_Test-Projects", "sha": "56142f09f040332abe1d4462488a1a389fd412ab", "save_path": "github-repos/coq/JoanDaniel18-Coq_Test-Projects", "path": "github-repos/coq/JoanDaniel18-Coq_Test-Projects/Coq_Test-Projects-56142f09f040332abe1d4462488a1a389fd412ab/quiz3_danielrivas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6914389793393377}}
{"text": "Require Export TopologicalSpaces.\nFrom ZornsLemma Require Export CountableTypes.\nRequire Export NeighborhoodBases.\nFrom ZornsLemma Require Import EnsemblesSpec.\n\nGlobal Set Asymmetric Patterns.\n\nDefinition first_countable (X:TopologicalSpace) : Prop :=\n  forall x:point_set X, exists NBx:Family (point_set X),\n    neighborhood_basis NBx x /\\ Countable NBx.\n\nLemma first_countable_open_neighborhood_bases:\n  forall X:TopologicalSpace, first_countable X ->\n    forall x:point_set X, exists NBx:Family (point_set X),\n      open_neighborhood_basis NBx x /\\ Countable NBx.\nProof.\nintros.\ndestruct (H x) as [NBx [? ?]].\nexists (@Im (Ensemble (point_set X)) (Ensemble (point_set X)) NBx (@interior X)).\nsplit.\nconstructor.\nintros.\ndestruct H2 as [U].\nsplit.\nrewrite H3; apply interior_open.\nrewrite H3; apply neighborhood_interior.\napply H0; trivial.\nintros.\ndestruct H0.\ndestruct (neighborhood_basis_cond U) as [N].\napply open_neighborhood_is_neighborhood; trivial.\ndestruct H0.\nexists (interior N).\nsplit.\nexists N; trivial.\npose proof (interior_deflationary N).\nauto with sets.\n\napply countable_img; trivial.\nQed.\n\nRequire Export Nets.\n\nLemma first_countable_sequence_closure:\n  forall (X:TopologicalSpace) (S:Ensemble (point_set X)) (x:point_set X),\n  first_countable X -> In (closure S) x ->\n  exists y:Net nat_DS X, (forall n:nat, In S (y n)) /\\\n                         net_limit y x.\nProof.\nintros.\ndestruct (first_countable_open_neighborhood_bases _ H x) as [NB []].\ndestruct H2 as [g].\npose (U (n:nat) := IndexedIntersection\n  (fun x: {x:{x:Ensemble (point_set X) | In NB x} | (g x < n)%nat} =>\n     proj1_sig (proj1_sig x))).\nassert (forall n:nat, open (U n)).\nintros.\napply open_finite_indexed_intersection.\napply inj_finite with _ (fun x:{x:{x:Ensemble (point_set X) | In NB x}\n                           | (g x < n)%nat} =>\n  exist (fun m:nat => (m<n)%nat) (g (proj1_sig x)) (proj2_sig x)).\nFrom ZornsLemma Require Import InfiniteTypes.\napply finite_nat_initial_segment.\nred.\nintros [[x0 P] p] [[y0 Q] q] ?.\nsimpl in H3.\nFrom ZornsLemma Require Import Proj1SigInjective.\napply subset_eq_compatT.\napply subset_eq_compatT.\ninjection H3; intros.\napply H2 in H4.\ninjection H4; trivial.\nintros; apply classic.\nintros.\ndestruct a as [[x0]].\nsimpl.\nOpaque In. apply H1; trivial. Transparent In.\n\nRequire Import ClassicalChoice.\ndestruct (choice (fun (n:nat) (x:point_set X) => In (U n) x /\\\n                                                 In S x)) as [y].\nintros n.\ndestruct (closure_impl_meets_every_open_neighborhood _ _ _ H0 (U n))\n  as [y]; trivial.\nconstructor; trivial.\ndestruct a as [[x0]].\nsimpl.\napply H1; trivial.\nexists y; destruct H4; split; trivial.\nexists y.\nsplit.\napply H4.\n\nred; intros V ? ?.\ndestruct H1.\ndestruct (open_neighborhood_basis_cond V) as [W []].\nsplit; trivial.\npose (a := (exist _ W H1 : {x:Ensemble (point_set X)|In NB x})).\nexists (Datatypes.S (g a)).\nintros.\nsimpl in j.\nsimpl in H8.\napply H7.\nassert (Included (U j) W).\nred; intros.\ndestruct H9.\nexact (H9 (exist _ a H8)).\napply H9.\napply H4.\nQed.\n\nInductive separable (X:TopologicalSpace) : Prop :=\n  | intro_dense_ctbl: forall S:Ensemble (point_set X),\n    Countable S -> dense S -> separable X.\n\nDefinition Lindelof (X:TopologicalSpace) : Prop :=\n  forall cover:Family (point_set X),\n    (forall U:Ensemble (point_set X),\n       In cover U -> open U) ->\n    FamilyUnion cover = Full_set ->\n  exists subcover:Family (point_set X), Included subcover cover /\\\n     Countable subcover /\\ FamilyUnion subcover = Full_set.\n\nInductive second_countable (X:TopologicalSpace) : Prop :=\n  | intro_ctbl_basis: forall B:Family (point_set X),\n    open_basis B -> Countable B -> second_countable X.\n\nLemma second_countable_impl_first_countable:\n  forall X:TopologicalSpace, second_countable X -> first_countable X.\nProof.\nintros.\ndestruct H.\nred; intros.\nexists [ U:Ensemble (point_set X) | In B U /\\ In U x ]; split.\napply open_neighborhood_basis_is_neighborhood_basis.\napply open_basis_to_open_neighborhood_basis; trivial.\napply countable_downward_closed with B; trivial.\nred; intros.\ndestruct H1 as [[? ?]]; trivial.\nQed.\n\nLemma second_countable_impl_separable:\n  forall X:TopologicalSpace, second_countable X -> separable X.\nProof.\nintros.\ndestruct H.\nRequire Import ClassicalChoice.\ndestruct (choice (fun (U:{U:Ensemble (point_set X) | In B U /\\ Inhabited U})\n  (x:point_set X) => In (proj1_sig U) x)) as [choice_fun].\nintros.\ndestruct x as [U [? ?]].\nsimpl.\ndestruct i0.\nexists x; trivial.\n\nexists (Im Full_set choice_fun).\napply countable_img.\nred.\nmatch goal with |- CountableT ?S =>\n  pose (g := fun (x:S) =>\n    match x return {U:Ensemble (point_set X) | In B U} with\n    | exist (exist U (conj i _)) _ => exist _ U i\n    end)\nend.\napply inj_countable with g.\nassumption.\nred; intros.\nunfold g in H2.\ndestruct x1 as [[U [? ?]]].\ndestruct x2 as [[V [? ?]]].\nFrom ZornsLemma Require Import Proj1SigInjective.\napply subset_eq_compatT.\napply subset_eq_compatT.\ninjection H2; trivial.\n\napply meets_every_nonempty_open_impl_dense.\nintros.\ndestruct H3.\ndestruct H.\ndestruct (open_basis_cover x U) as [V [? [? ?]]]; trivial.\nassert (In B V /\\ Inhabited V).\nsplit; trivial.\nexists x; trivial.\nexists (choice_fun (exist _ V H6)).\n\nconstructor.\n(* apply H4. *)\npose proof (H1 (exist _ V H6)).\nsimpl in H7.\n(* assumption. *)\nexists (exist (fun U0:Ensemble (point_set X) => In B U0 /\\ Inhabited U0) V H6).\nconstructor.\nreflexivity.\napply H4.\npose proof (H1 (exist _ V H6)).\nsimpl in H7.\nassumption.\nQed.\n\nLemma second_countable_impl_Lindelof:\n  forall X:TopologicalSpace, second_countable X -> Lindelof X.\nProof.\nintros.\ndestruct H.\nred; intros.\n\npose (basis_elts_contained_in_cover_elt :=\n  [ U:Ensemble (point_set X) | In B U /\\ Inhabited U /\\\n    exists V:Ensemble (point_set X), In cover V /\\ Included U V ]).\ndestruct (choice (fun (U:{U | In basis_elts_contained_in_cover_elt U})\n  (V:Ensemble (point_set X)) => In cover V /\\ Included (proj1_sig U) V))\n  as [choice_fun].\nintros.\ndestruct x.\nsimpl.\ndestruct i as [[? [? ?]]].\nexact H5.\nexists (Im Full_set choice_fun).\nrepeat split.\nred; intros.\ndestruct H4.\ndestruct (H3 x).\nrewrite H5; assumption.\napply countable_img.\napply countable_type_ensemble.\napply countable_downward_closed with B; trivial.\nred; intros.\ndestruct H4 as [[]].\nassumption.\n\napply Extensionality_Ensembles; red; split; red; intros.\nconstructor.\nclear H4.\nassert (In (FamilyUnion cover) x).\nrewrite H2; constructor.\ndestruct H4.\n\ndestruct H.\ndestruct (open_basis_cover x S) as [V]; trivial.\napply H1; trivial.\n\ndestruct H as [? [? ?]].\n\nassert (In basis_elts_contained_in_cover_elt V).\nconstructor.\nrepeat split; trivial.\nexists x; trivial.\nexists S; split; trivial.\n\nexists (choice_fun (exist _ V H8)).\nexists (exist _ V H8).\nconstructor.\nreflexivity.\n\npose proof (H3 (exist _ V H8)).\ndestruct H9.\nsimpl in H10.\napply H10; trivial.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/topology/CountabilityAxioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6914368387687383}}
{"text": "Require Omega.\n\nModule Part1.\n    (* Coq's standard library's ordering on peano nats defines <= as given by the rules (forall n, n <= n) and (forall n m, n <= m -> n <= S m) (i.e. reflexivity and right-successor).\n        (x < y) is an alias for (S x <= y), and (y < x) is an alias for (x < y). *)\n\n    (* nat_compare is a decideable trichotomy for peano naturals (i.e. given two nats, it computes which ordering holds between them) *)\n    Definition or_inj1 {P Q R : Prop} : P -> {P} + {Q} + {R} := ltac:(tauto).\n    Definition or_inj2 {P Q R : Prop} : Q -> {P} + {Q} + {R} := ltac:(tauto).\n    Definition or_inj3 {P Q R : Prop} : R -> {P} + {Q} + {R} := ltac:(tauto).\n    Fixpoint nat_compare (n m : nat) : {n < m} + {n = m} + {n > m} :=\n        match n with\n        | 0 => match m with\n            | 0 => or_inj2 eq_refl\n            | S m' => or_inj1 (le_n_S _ _ (le_0_n m'))\n            end\n        | S n' => match m with\n            | 0 => or_inj3 (le_n_S _ _ (le_0_n n'))\n            | S m' => match nat_compare n' m' with\n                | inleft (left less) => inleft (left (le_n_S _ _ less))\n                | inleft (right equal) => inleft (right (f_equal S equal))\n                | inright greater => inright (le_n_S _ _ greater)\n                end\n            end\n        end.\n\n    (* trichotomy is an Ltac script that flattens the structure of the result of nat-compare, to be used in proofs/definitions by cases *)\n    Ltac trichotomy x y := destruct (nat_compare x y) as [s | ?g]; [destruct s as [?l | ?e]|].\n\n    Definition max' : nat -> nat -> nat.\n        intros n m. trichotomy n m.\n        - (* n < m *) exact m.\n        - (* n = m *) exact n.\n        - (* n > m *) exact n.\n        Defined.\n        \n    (* Idempotence is easy to prove; running the comparison on x and x yields a goal of showing x = x, which is discharged by reflexivity in all 3 cases. *)\n    Theorem max'_idempotent : forall x, max' x x = x.\n        intro x; unfold max'; trichotomy x x; reflexivity.\n        Qed.\n\n    (* Some helper lemmas on inequalities *)\n    Lemma lt_irreflexive : forall x, ~(x < x).\n        intros x e. unfold lt in e. induction x; inversion e.\n        - rewrite H0 in e. exact (IHx e).\n        - subst. exact (IHx (le_pred _ _ (le_S _ _ H0))).\n        Qed.\n\n    Lemma not_le_plus_l : forall n k, ~((S k) + n <= n).\n        induction k; intro e.\n        - exact (lt_irreflexive _ e).\n        - exact (IHk (le_pred _ _ (le_S _ _ e))).\n        Qed.\n\n    Lemma le_trans : forall x y z, x <= y -> y <= z -> x <= z.\n        induction x, y, z; try easy; intros Hxy Hyz.\n        - apply le_0_n.\n        - exact (le_n_S _ _ (IHx y z (le_pred _ _ Hxy) (le_pred _ _ Hyz))).\n        Qed.\n\n    (* fully-automatic versions of the above lemmas, with the omega tactic (a Presburger arithmetic solver) *)\n    Module Omega_demo.\n        Import Omega.\n        Lemma lt_irreflexive' : forall x, ~(x < x). intros; omega. Qed.\n        Lemma not_le_plus_l' : forall n k, ~((S k) + n <= n). intros; omega. Qed.\n        Lemma le_trans' : forall x y z, x <= y -> y <= z -> x <= z. intros; omega. Qed.\n    End Omega_demo.\n    \n\n    (* reduction lemmas for max, max'_0_l and max'_S are the ones that ended up being used, the ones with disjunctions in their RHS ended up being too cumbersome to use *)\n    Lemma max'_0_l : forall x, max' 0 x = x.\n        destruct x.\n        - reflexivity.\n        - unfold max'. trichotomy 0 (S x).\n          + reflexivity.\n          + exact e.\n          + inversion g.\n        Qed.\n\n    Lemma max'_S_l : forall x y, max' (S x) y = S (max' x y) \\/ max' (S x) y = y.\n        intros x y. unfold max'. trichotomy (S x) y.\n        - right. reflexivity.\n        - right. exact e.\n        - left. trichotomy x y; try easy. destruct (lt_irreflexive _ (le_trans _ _ _ g l)).\n        Qed.\n    Lemma max'_S_l' : forall x y, max' (S x) y = S x \\/ max' (S x) y = y.\n        intros x y. unfold max'. trichotomy (S x) y.\n        - right. reflexivity.\n        - right. exact e.\n        - left. reflexivity.\n        Qed.\n\n    Ltac double_inversion H := inversion H as [| ? ?H' ]; inversion H'.\n    Ltac recursive_inversion H := inversion H as [| ? ?H' ]; try recursive_inversion H'.\n\n    Lemma max'_S : forall x y, max' (S x) (S y) = S (max' x y).\n        induction x; intro y.\n        - rewrite max'_0_l. unfold max'.\n            trichotomy 1 (S y); try easy. recursive_inversion g.\n        - unfold max'. trichotomy (S x) y; trichotomy (S (S x)) (S y); try easy.\n            + set (H := le_trans _ _ _ g l). destruct (not_le_plus_l y 1 H).\n            + subst. reflexivity.\n            + set (H := le_trans _ _ _ l g). destruct (not_le_plus_l (S x) 1 H).\n        Qed.\n\n    (* max_compat_max' shows that max' defined via trichotomy has the same behavior as a version defined directly via recursion on peano naturals; the latter is more transparent to Coq's reduction machinery.\n        This makes use of the reduction lemmas defined above. *)\n    \n    Lemma max_compat_max' : forall n m, max' n m = Nat.max n m.\n        induction n; intro m.\n        - apply max'_0_l.\n        - induction m.\n            + trichotomy (S n) 0; easy.\n            + simpl. rewrite <- (IHn m). rewrite max'_S. reflexivity.\n        Qed.\n\n    (* once max_compat_max' has been proven, max'_associative is proven by routine induction on peano naturals (with some care taken to ensure that the generated inductive hypothesis is general enough *)\n    Theorem max'_associative : forall x y z, max' x (max' y z) = max' (max' x y) z.\n        intros x y z.\n        repeat rewrite max_compat_max'.\n        revert z; revert y; induction x; destruct y, z; try reflexivity.\n        simpl. rewrite (IHx y z).\n        reflexivity.\n        Qed.\n\nEnd Part1.\n\nLoad ListBackedSet.\n(* ListBackedSet contains functions that deal with lists-as-sets via decideable equality, that I developed for the lattice project. *)\nImport ListBackedSet.\n(* ListBackedSet' contains functions that deal with lists-as-sets via the Elem inductive predicate and unification, developed for this project.\n    The various _compat lemmas proven in it show that the original versions are correct relative to the (new, shorter) specifications. *)\nImport ListBackedSet'.\n\nModule Part2.\n    Definition relation (S T : Type) := list (S * T).\n\n    (* The domain and range of a relation are both implemented via map, which I defined in ListBackedSet. *)\n    Definition domain {S T} (rel : relation S T) := map fst rel.\n    Definition range {S T} (rel : relation S T) := map snd rel.\n\n    (* There were a lot of false starts/proof attempts for range_theorem_2, which eventually lead to discovering the following lemmas (proved in ListBackedSet.v): \n        Lemma map_elem {A B} (f : A -> B) : forall x xs, Elem x xs -> Elem (f x) (map f xs).\n        Lemma co_map_elem_inhabited {A B} (f : A -> B) : forall y xs, Elem y (map f xs) -> exists x, Elem x xs /\\ f x = y.\n\n        These ended up making the finished proofs relatively short.\n    *)\n    Lemma range_theorem_2_lemma_1 {S T} : forall (r1 r2 : relation S T) xs ys (x : S * T), Intersection r1 r2 xs -> Intersection (range r1) (range r2) ys -> Elem x xs -> Elem (snd x) ys.\n        intros r1 r2 xs ys x Int_xs Int_ys x_in_xs.\n        unfold Intersection in *.\n        destruct (proj1 (Int_xs x) x_in_xs) as [xr1 xr2].\n        apply (map_elem snd) in xr1; apply (map_elem snd) in xr2.\n        fold (range r1) in xr1; fold (range r2) in xr2.\n        exact (proj2 (Int_ys (snd x)) (conj xr1 xr2)).\n        Qed.\n\n    Theorem range_theorem_2 {S T} : forall (r1 r2 : relation S T) xs ys, Intersection r1 r2 xs -> Intersection (range r1) (range r2) ys -> Subset (range xs) ys.\n        intros r1 r2 xs ys Int_xs Int_ys y y_in_rxs.\n        destruct (co_map_elem_inhabited snd _ _ y_in_rxs) as [st [ist est]].\n        set (H := range_theorem_2_lemma_1 r1 r2 _ _ st Int_xs Int_ys ist).\n        rewrite est in H. exact H.\n        Qed.\n\n    (* I proved domain_theorem_3' next, and then realized that its proof could be generalized to handle the range case as well *)\n    Theorem domain_theorem_3' {S T} : forall (r1 r2 : relation S T) xs ys, Difference (domain r1) (domain r2) xs -> Difference r1 r2 ys -> Subset xs (domain ys).\n        unfold Difference.\n        intros r1 r2 xs ys diff_xs diff_ys x x_in_xs.\n        destruct (proj1 (diff_xs x) x_in_xs) as [e1 e2].\n        destruct (co_map_elem_inhabited _ _ _ e1) as [a [Ha1 Ha2]].\n        assert (Hb : ~(Elem a r2)). { intros H. apply e2. rewrite <- Ha2. apply (map_elem _ _ _ H). }\n        rewrite <- Ha2.\n        exact (map_elem fst _ _ (proj2 (diff_ys a) (conj Ha1 Hb))).\n        Qed.\n\n    (* the generalized map_theorem_3 differs from domain_theorem_3' only in that it replaces fst with an arbitrary f *)\n    Lemma map_theorem_3 {S T U} : forall (f : S * T -> U) (r1 r2 : relation S T) xs ys, Difference (map f r1) (map f r2) xs -> Difference r1 r2 ys -> Subset xs (map f ys).\n        unfold Difference.\n        intros f r1 r2 xs ys diff_xs diff_ys x x_in_xs.\n        destruct (proj1 (diff_xs x) x_in_xs) as [e1 e2].\n        destruct (co_map_elem_inhabited _ _ _ e1) as [a [Ha1 Ha2]].\n        assert (Hb : ~(Elem a r2)). { intros H. apply e2. rewrite <- Ha2. apply (map_elem _ _ _ H). }\n        rewrite <- Ha2.\n        exact (map_elem f _ _ (proj2 (diff_ys a) (conj Ha1 Hb))).\n        Qed.\n\n    (* domain_theorem_3 and range_theorem_3 are both trivial corollaries of map_theorem_3 *)\n    Theorem domain_theorem_3 {S T} : forall (r1 r2 : relation S T) xs ys, Difference (domain r1) (domain r2) xs -> Difference r1 r2 ys -> Subset xs (domain ys).\n        exact (map_theorem_3 fst). Qed.\n    Theorem range_theorem_3 {S T} : forall (r1 r2 : relation S T) xs ys, Difference (range r1) (range r2) xs -> Difference r1 r2 ys -> Subset xs (range ys).\n        exact (map_theorem_3 snd). Qed.\n\nEnd Part2.\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/softwareverification_homework2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.6913913430488369}}
{"text": "\nRequire Import Coq.Arith.Arith.\nRequire Export Coq.Vectors.Vector.\nRequire Import Coq.Program.Equality. (* for dependent induction *)\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Logic.ProofIrrelevance.\n\n\n(* CoLoR: `opam install coq-color`  *)\nRequire Export CoLoR.Util.Vector.VecUtil.\n\nOpen Scope vector_scope.\n\n(* Re-define :: List notation for vectors. Probably not such a good idea *)\nNotation \"h :: t\" := (cons h t) (at level 60, right associativity)\n                     : vector_scope.\n\nImport VectorNotations.\n\nSection VPermutation.\n\n  Variable A:Type.\n\n  Inductive VPermutation: forall n, vector A n -> vector A n -> Prop :=\n  | vperm_nil: VPermutation 0 [] []\n  | vperm_skip {n} x l l' : VPermutation n l l' -> VPermutation (S n) (x::l) (x::l')\n  | vperm_swap {n} x y l : VPermutation (S (S n)) (y::x::l) (x::y::l)\n  | vperm_trans {n} l l' l'' :\n      VPermutation n l l' -> VPermutation n l' l'' -> VPermutation n l l''.\n\n  Local Hint Constructors VPermutation : vperm_hints.\n\n  (** Some facts about [VPermutation] *)\n\n  Theorem VPermutation_nil : forall (l : vector A 0), VPermutation 0 [] l -> l = [].\n  Proof.\n    intros l HF.\n    dependent destruction l.\n    reflexivity.\n  Qed.\n\n  (** VPermutation over vectors is a equivalence relation *)\n\n  Theorem VPermutation_refl : forall {n} (l: vector A n), VPermutation n l l.\n  Proof.\n    induction l; constructor. exact IHl.\n  Qed.\n\n  Theorem VPermutation_sym : forall {n} (l l' : vector A n),\n      VPermutation n l l' -> VPermutation n l' l.\n  Proof.\n    intros n l l' Hperm.\n    induction Hperm; auto with vperm_hints.\n    apply vperm_trans with (l'0:=l'); auto.\n  Qed.\n\n  Theorem VPermutation_trans : forall {n} (l l' l'' : vector A n),\n      VPermutation n l l' -> VPermutation n l' l'' -> VPermutation n l l''.\n  Proof.\n    intros n l l' l''.\n    apply vperm_trans.\n  Qed.\n\nEnd VPermutation.\n\nHint Resolve VPermutation_refl vperm_nil vperm_skip : vperm_hints.\n\n(* These hints do not reduce the size of the problem to solve and they\n   must be used with care to avoid combinatoric explosions *)\n\nLocal Hint Resolve vperm_swap vperm_trans : vperm_hints.\nLocal Hint Resolve VPermutation_sym VPermutation_trans : vperm_hints.\n\n(* This provides reflexivity, symmetry and transitivity and rewriting\n   on morphims to come *)\n\nInstance VPermutation_Equivalence A n : Equivalence (@VPermutation A n) | 10 :=\n  {\n    Equivalence_Reflexive := @VPermutation_refl A n ;\n    Equivalence_Symmetric := @VPermutation_sym A n ;\n    Equivalence_Transitive := @VPermutation_trans A n\n  }.\n\nRequire Import Coq.Sorting.Permutation.\nRequire Import Helix.Util.VecUtil.\n\nSection VPermutation_properties.\n\n  Variable A:Type.\n\n  Lemma ListVecPermutation {n} {l1 l2} {v1 v2}:\n    l1 = list_of_vec v1 ->\n    l2 = list_of_vec v2 ->\n    Permutation l1 l2 <->\n    VPermutation A n v1 v2.\n  Proof.\n    intros H1 H2.\n    split.\n    -\n      intros P; revert n v1 v2 H1 H2.\n      dependent induction P; intros n v1 v2 H1 H2.\n      + dependent destruction v1; inversion H1; subst.\n        dependent destruction v2; inversion H2; subst.\n        apply vperm_nil.\n      + dependent destruction v1; inversion H1; subst.\n        dependent destruction v2; inversion H2; subst.\n        apply vperm_skip.\n        now apply IHP.\n      + do 2 (dependent destruction v1; inversion H1; subst).\n        do 2 (dependent destruction v2; inversion H2; subst).\n        apply list_of_vec_eq in H5; subst.\n        apply vperm_swap.\n      + assert (n = length l').\n        { pose proof (Permutation_length P1) as len.\n          subst.\n          now rewrite list_of_vec_length in len.\n        }\n        subst.\n        apply vperm_trans with (l' := vec_of_list l').\n        * apply IHP1; auto.\n          now rewrite list_of_vec_vec_of_list.\n        * apply IHP2; auto.\n          now rewrite list_of_vec_vec_of_list.\n    -\n      subst l1 l2.\n      intros P.\n      dependent induction P.\n      +\n        subst; auto.\n      +\n        simpl.\n        apply perm_skip.\n        apply IHP.\n      +\n        simpl.\n        apply perm_swap.\n      +\n        apply perm_trans with (l':=list_of_vec l'); auto.\n  Qed.\n\nEnd VPermutation_properties.\n\nLemma Vsig_of_forall_cons\n      {A : Type}\n      {n : nat}\n      (P : A->Prop)\n      (x : A)\n      (l : vector A n)\n      (P1h : P x)\n      (P1x : @Vforall A P n l):\n  (@Vsig_of_forall A P (S n) (@cons A x n l) (@conj (P x) (@Vforall A P n l) P1h P1x)) =\n  (Vcons (@exist A P x P1h) (Vsig_of_forall P1x)).\nProof.\n  simpl.\n  f_equal.\n  apply subset_eq_compat.\n  reflexivity.\n  f_equal.\n  apply proof_irrelevance.\nQed.\n\nLemma VPermutation_Vsig_of_forall\n      {n: nat}\n      {A: Type}\n      (P: A->Prop)\n      (v1 v2 : vector A n)\n      (P1 : Vforall P v1)\n      (P2 : Vforall P v2):\n  VPermutation A n v1 v2\n  -> VPermutation {x : A | P x} n (Vsig_of_forall P1) (Vsig_of_forall P2).\nProof.\n  intros V.\n  revert P1 P2.\n  dependent induction V; intros P1 P2.\n  -\n    apply vperm_nil.\n  -\n    destruct P1 as [P1h P1x].\n    destruct P2 as [P2h P2x].\n    rewrite 2!Vsig_of_forall_cons.\n    replace P1h with P2h by apply proof_irrelevance.\n    apply vperm_skip.\n    apply IHV.\n  -\n    destruct P1 as [P1y [P1x P1l]].\n    destruct P2 as [P1x' [P1y' P1l']].\n\n    repeat rewrite Vsig_of_forall_cons.\n\n    replace P1y' with P1y by apply proof_irrelevance.\n    replace P1x' with P1x by apply proof_irrelevance.\n    replace P1l' with P1l by apply proof_irrelevance.\n    apply vperm_swap.\n  -\n    assert(Vforall P l').\n    {\n      apply Vforall_intro.\n      intros x H.\n      apply list_of_vec_in in H.\n      eapply ListVecPermutation in V1; auto.\n      apply Permutation_in with (l':=(list_of_vec l)) in H.\n      +\n        apply Vforall_lforall in P1.\n        apply ListUtil.lforall_in with (l:=(list_of_vec l)); auto.\n      +\n        symmetry.\n        auto.\n    }\n    (* Looks like a coq bug here. It should find H automatically *)\n    unshelve eauto with vperm_hints.\n    apply H.\nQed.\n\n", "meta": {"author": "vzaliva", "repo": "helix", "sha": "5d0a71df99722d2011c36156f12b04875df7e1cb", "save_path": "github-repos/coq/vzaliva-helix", "path": "github-repos/coq/vzaliva-helix/helix-5d0a71df99722d2011c36156f12b04875df7e1cb/coq/Util/VecPermutation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940974, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6913913418832499}}
{"text": "Require Import Func.\n\nDefinition lem (p:Prop) : Prop := p \\/ ~p.\n\nDefinition ifRel (a b:Type) (p:Prop) (f g:a ==> b) (x:a) (y:b) : Prop :=\n    (p /\\ rel f x y) \\/ (~p /\\ rel g x y).\n\nArguments ifRel {a} {b} _ _ _ _ _.\n\n\nLemma ifRelFunctional : forall (a b:Type) (p:Prop) (f g:a ==> b),\n    Functional (ifRel p f g).\nProof.\n    unfold Functional. intros a b p [fr fTot fFunc] [gr gTot gFunc] x y y'. \n    unfold ifRel. simpl. intros [[Hp H1]|[Hp H1]] [[Hq H2]|[Hq H2]].\n    - unfold Functional in fFunc. apply (fFunc x).\n        + exact H1.\n        + exact H2.\n    - exfalso. apply Hq. exact Hp.\n    - exfalso. apply Hp. exact Hq.\n    - unfold Functional in gFunc. apply (gFunc x).\n        + exact H1.\n        + exact H2.\nQed.\n\n\nArguments ifRelFunctional {a} {b} _ _ _ _ _ _ _ _.\n\n\nLemma ifRelTotal : forall (a b:Type) (p:Prop) (f g:a ==> b),\n    lem p -> Total (ifRel p f g).\nProof.\n    unfold Total, ifRel. intros a b p [fr fTot fFunc] [gr gTot gFunc] [H|H] x.\n    - simpl. unfold Total in fTot. destruct (fTot x) as [y Hy].\n        exists y. left. split.\n            + exact H.\n            + exact Hy.\n    - simpl. unfold Total in fTot. destruct (gTot x) as [y Hy].\n        exists y. right. split.\n            + exact H.\n            + exact Hy.\nQed.\n\nArguments ifRelTotal {a} {b} _ _ _ _ _.\n\n\n(* not that useful but good to know. Only applies if type a is not empty*)\nLemma ifRelTotal_converse : forall (a b:Type) (p:Prop) (f g:a ==> b),\n    (exists (x:a), True) -> Total (ifRel p f g) -> lem p.\nProof.\n    unfold Total, ifRel, lem. intros a b p f g [x _] H.\n    destruct (H x) as [y [[Hp H']|[Hp H']]].\n    - left.  exact Hp.\n    - right. exact Hp.\nQed.\n\n\nDefinition ifFunc (a b:Type) (p:Prop) (q: lem p) (f g:a ==> b) : a ==> b :=\n    func (ifRel p f g) (ifRelTotal p f g q) (ifRelFunctional p f g). \n\nArguments ifFunc {a} {b} _ _ _ _.\n\nLemma ifFunc_correct_true : forall (a b:Type) (p:Prop) (q:lem p) (f g:a ==> b),\n    forall (x:a) (y:b), p -> (rel (ifFunc p q f g) x y <-> rel f x y).\nProof.\n    intros a b p q f g x y H. unfold ifFunc. simpl. unfold ifRel.\n    remember (rel f) as r. split.\n    - intros [[Hp H']|[Hp H']].\n        + exact H'.\n        + exfalso. apply Hp. exact H.\n    - intros H'. left. split.\n        + exact H.\n        + exact H'.\nQed.\n\nLemma ifFunc_correct_false : forall (a b:Type) (p:Prop) (q:lem p) (f g:a ==> b),\n    forall (x:a) (y:b), ~p -> (rel (ifFunc p q f g) x y <-> rel g x y).\nProof.\n    intros a b p q f g x y H. unfold ifFunc. simpl. unfold ifRel.\n    remember (rel g) as r. split.\n    - intros [[Hp H']|[Hp H']].\n        + exfalso.  apply H. exact Hp.\n        + exact H'.\n    - intros H'. right. split.\n        +  exact H.\n        +  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/cat/Func_If.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.691391339358651}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat.\nFrom mathcomp Require Import eqtype choice order.\nRequire Import Equations.Prop.Loader.\n\n(******************************************************************************)\n(* This file contains the definitions of:                                     *)\n(*             wfType d == the structure for types with                       *)\n(*                         well-founded partial order.                        *)\n(*  well_founded_bool r <-> r is a decidable well-founded relation.           *)\n(*                  wfb <-> wfType's order relation is well-founded.          *)\n(*              wfb_ind <-> well-founded induction principle for wfType.      *)\n(* This file also contains canonical instance of wfType for nat.              *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection WfBool.\n\nContext {T : Type} (r : rel T).\n\nInductive acc_bool (x : T) :=\n  acc_bool_intro of (forall y : T, r y x -> acc_bool y).\n\nDefinition well_founded_bool := forall x, acc_bool x.\n\nEnd WfBool.\n\nOpen Scope order_scope.\n\nModule WellFounded.\n\nSection ClassDef.\n\nRecord mixin_of T0 (b : Order.POrder.class_of T0)\n  (T := Order.POrder.Pack tt b) := Mixin {\n  _ : well_founded_bool (<%O : rel T);\n}.\n\nSet Primitive Projections.\n\nRecord class_of (T : Type) := Class {\n  base   : Order.POrder.class_of T;\n  mixin  : mixin_of base;\n}.\n\nUnset Primitive Projections.\n\nLocal Coercion base : class_of >-> Order.POrder.class_of.\n\nStructure type (disp : unit) := Pack { sort; _ : class_of sort }.\n\nLocal Coercion sort : type >-> Sortclass.\n\nVariables (T : Type) (disp : unit) (cT : type disp).\n\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack disp T c.\n\nDefinition pack :=\n  fun bT b & phant_id (@Order.POrder.class disp bT) b =>\n  fun m => Pack disp (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition porderType := @Order.POrder.Pack disp cT class.\nEnd ClassDef.\n\nModule Exports.\n\nNotation wfType := type.\nCoercion base : class_of >-> Order.POrder.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nCoercion eqType : type >-> Equality.type.\nCoercion choiceType : type >-> Choice.type.\nCoercion porderType : type >-> Order.POrder.type.\nCanonical eqType.\nCanonical choiceType.\nCanonical porderType.\nNotation WfType disp T m := (@pack T disp _ _ id m).\n\nEnd Exports.\n\nEnd WellFounded.\n\nExport WellFounded.Exports.\n\n\nSection WfInduction.\n\nContext {disp : unit} {T : wfType disp}.\n\nLemma wfb : well_founded_bool (<%O : rel T).\nProof. by case: T=> ? [] ? []. Qed.\n\nLemma wfb_ind (P : T -> Type) :\n  (forall n, (forall m, m < n -> P m) -> P n) ->\n  forall n, P n.\nProof. by move=> accP M; elim: (wfb M) => ?? /accP. Qed.\n\nEnd WfInduction.\n\nGlobal Instance wf_wfType {disp : unit} {T : wfType disp} :\n  Equations.Prop.Classes.WellFounded (<%O : rel T).\nProof. by apply: wfb_ind; constructor. Qed.\n\n\n(* Canonical well-founded order for nat *)\n\nImport Order.NatOrder.\n\nLemma nat_well_founded_bool:  well_founded_bool (<%O : rel nat).\nProof. by elim/ltn_ind=> n IHn; constructor=> m /IHn. Qed.\n\nDefinition nat_wfMixin := @WellFounded.Mixin nat _ nat_well_founded_bool.\nCanonical nat_wfType := Eval hnf in WfType nat_display nat nat_wfMixin.\n", "meta": {"author": "Event-Structures", "repo": "event-struct", "sha": "7a9b8b6f26621997d6c091beb1fd760dabb77ed9", "save_path": "github-repos/coq/Event-Structures-event-struct", "path": "github-repos/coq/Event-Structures-event-struct/event-struct-7a9b8b6f26621997d6c091beb1fd760dabb77ed9/theories/common/wftype.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.6913913356684644}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\n\nArguments fst : default implicits.\nArguments snd : default implicits.\n\nModule Type PO.\n  Parameter T : Set.\n  Parameter le : T -> T -> Prop.\n\n  Axiom le_refl : forall x : T, le x x.\n  Axiom le_trans : forall x y z : T, le x y -> le y z -> le x z.\n  Axiom le_antis : forall x y : T, le x y -> le y x -> x = y.\n\n  Hint Resolve le_refl le_trans le_antis.\nEnd PO.\n\n\nModule Pair (X: PO) (Y: PO) <: PO.\n  Definition T := (X.T * Y.T)%type.\n  Definition le p1 p2 := X.le (fst p1) (fst p2) /\\ Y.le (snd p1) (snd p2).\n\n  Hint Unfold le.\n\n  Lemma le_refl : forall p : T, le p p.\n    info auto.\n  Qed.\n\n  Lemma le_trans : forall p1 p2 p3 : T, le p1 p2 -> le p2 p3 -> le p1 p3.\n    unfold le;  intuition; info  eauto.\n  Qed.\n\n  Lemma le_antis : forall p1 p2 : T, le p1 p2 -> le p2 p1 -> p1 = p2.\n    destruct p1.\n    destruct p2.\n    unfold le.\n     intuition.\n     cutrewrite (t = t1).\n     cutrewrite (t0 = t2).\n    reflexivity.\n\n    info auto.\n\n    info auto.\n  Qed.\n\nEnd Pair.\n\n\n\nRequire Nat.\n\nModule NN := Pair Nat Nat.\n\nLemma zz_min : forall p : NN.T, NN.le (0, 0) p.\n  info auto with arith.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/modules/PO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6913913299397609}}
{"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: EqNat.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\n(** Equality on natural numbers *)\n\nOpen Local Scope nat_scope.\n\nImplicit Types m n x y : nat.\n\n(** * Propositional equality  *)\n\nFixpoint eq_nat n m : Prop :=\n  match n, m with\n    | O, O => True\n    | O, S _ => False\n    | S _, O => False\n    | S n1, S m1 => eq_nat n1 m1\n  end.\n\nTheorem eq_nat_refl : forall n, eq_nat n n.\n  induction n; simpl in |- *; auto.\nQed.\nHint Resolve eq_nat_refl: arith v62.\n\n(** [eq] restricted to [nat] and [eq_nat] are equivalent *)\n\nLemma eq_eq_nat : forall n m, n = m -> eq_nat n m.\n  induction 1; trivial with arith.\nQed.\nHint Immediate eq_eq_nat: arith v62.\n\nLemma eq_nat_eq : forall n m, eq_nat n m -> n = m.\n  induction n; induction m; simpl in |- *; contradiction || auto with arith.\nQed.\nHint Immediate eq_nat_eq: arith v62.\n\nTheorem eq_nat_is_eq : forall n m, eq_nat n m <-> n = m.\nProof.\n  split; auto with arith.\nQed.\n\nTheorem eq_nat_elim :\n  forall n (P:nat -> Prop), P n -> forall m, eq_nat n m -> P m.\nProof.\n  intros; replace m with n; auto with arith.\nQed.\n\nTheorem eq_nat_decide : forall n m, {eq_nat n m} + {~ eq_nat n m}.\nProof.\n  induction n.\n  destruct m as [| n].\n  auto with arith.\n  intros; right; red in |- *; trivial with arith.\n  destruct m as [| n0].\n  right; red in |- *; auto with arith.\n  intros.\n  simpl in |- *.\n  apply IHn.\nDefined.\n\n\n(** * Boolean equality on [nat] *)\n\nFixpoint beq_nat n m : bool :=\n  match n, m with\n    | O, O => true\n    | O, S _ => false\n    | S _, O => false\n    | S n1, S m1 => beq_nat n1 m1\n  end.\n\nLemma beq_nat_refl : forall n, true = beq_nat n n.\nProof.\n  intro x; induction x; simpl in |- *; auto.\nQed.\n\nDefinition beq_nat_eq : forall x y, true = beq_nat x y -> x = y.\nProof.\n  double induction x y; simpl in |- *.\n    reflexivity.\n    intros n H1 H2. discriminate H2.\n    intros n H1 H2. discriminate H2.\n    intros n H1 z H2 H3. case (H2 _ H3). reflexivity.\nDefined.\n\nLemma beq_nat_true : forall x y, beq_nat x y = true -> x=y.\nProof.\n induction x; destruct y; simpl; auto; intros; discriminate.\nQed.\n\nLemma beq_nat_false : forall x y, beq_nat x y = false -> x<>y.\nProof.\n induction x; destruct y; simpl; auto; intros; discriminate.\nQed.\n\nLemma beq_nat_true_iff : forall x y, beq_nat x y = true <-> x=y.\nProof.\n split. apply beq_nat_true.\n intros; subst; symmetry; apply beq_nat_refl.\nQed.\n\nLemma beq_nat_false_iff : forall x y, beq_nat x y = false <-> x<>y.\nProof.\n intros x y.\n split. apply beq_nat_false.\n generalize (beq_nat_true_iff x y).\n destruct beq_nat; auto.\n intros IFF NEQ. elim NEQ. apply IFF; 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/EqNat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324938410783, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.6912908703591838}}
{"text": "Require Export Coq.Relations.Relation_Definitions.\nRequire Import Coq.Classes.Morphisms.\nRequire Export Coq.Classes.Equivalence.\nRequire Coq.Setoids.Setoid.\n\nDefinition full_relation {A} : relation A := fun _ _ => True.\n\nLemma inclusion_full_relation: forall {A} P, inclusion A P full_relation.\nProof.\n  intros.\n  hnf; intros.\n  hnf.\n  auto.\nQed.\n\nLemma same_relation_spec: forall {A} a1 a2, same_relation A a1 a2 <-> pointwise_relation A (pointwise_relation A iff) a1 a2.\nProof.\n  intros.\n  unfold same_relation, inclusion, pointwise_relation.\n  firstorder.\nQed.\n\nLemma same_relation_Reflexive {A}: Reflexive (same_relation A).\nProof.\n  hnf; intros.\n  rewrite same_relation_spec.\n  unfold pointwise_relation.\n  firstorder.\nQed.\n\nLemma same_relation_Symmetric {A}: Symmetric (same_relation A).\nProof.\n  hnf; intros.\n  rewrite same_relation_spec in *.\n  unfold pointwise_relation in *.\n  firstorder.\nQed.\n\nLemma same_relation_Transitive {A}: Transitive (same_relation A).\nProof.\n  hnf; intros.\n  rewrite same_relation_spec in *.\n  unfold pointwise_relation in *.\n  intros a b. specialize (H a b). specialize (H0 a b).\n  firstorder.\nQed.\n\nInstance same_relation_Equivalence {A}: Equivalence (same_relation A).\nProof.\n  split.\n  + apply same_relation_Reflexive.\n  + apply same_relation_Symmetric.\n  + apply same_relation_Transitive.\nQed.\n\nInstance inclusion_proper {A}: Proper (same_relation A ==> same_relation A ==> iff) (inclusion A).\nProof.\n  intros.\n  do 2 (hnf; intros ?F ?G ?H).\n  unfold inclusion.\n  rewrite same_relation_spec in H, H0.\n  split; intros HH x y; specialize (HH x y).\n  + rewrite (H x y), (H0 x y) in HH.\n    auto.\n  + rewrite (H x y), (H0 x y).\n    auto.\nQed.\n\nLemma app_same_relation: forall {A: Type} (R1 R2: relation A) (a1 a2: A),\n  same_relation A R1 R2 ->\n  (R1 a1 a2 <-> R2 a1 a2).\nProof.\n  intros.\n  rewrite same_relation_spec in H.\n  specialize (H a1 a2).\n  tauto.\nQed.\n\nInductive compond_relation {A: Type} (R1 R2: relation A) : relation A :=\n  | compond_intro: forall x y z, R1 x y -> R2 y z -> compond_relation R1 R2 x z.\n\nLemma compond_relation_spec: forall {A} (R1 R2: relation A) x z,\n  compond_relation R1 R2 x z ->\n  exists y, R1 x y /\\ R2 y z.\nProof.\n  intros.\n  inversion H; subst.\n  eauto.\nQed.\n\nLemma compond_relation_inclusion: forall {A} (R1 R2 R3 R4: relation A),\n  inclusion _ R1 R2 ->\n  inclusion _ R3 R4 ->\n  inclusion _ (compond_relation R1 R3) (compond_relation R2 R4).\nProof.\n  intros.\n  hnf; intros.\n  inversion H1; subst.\n  apply compond_intro with y0; auto.\nQed.\n\nInstance compond_relation_proper {A: Type}: Proper (same_relation A ==> same_relation A ==> same_relation A) compond_relation.\nProof.\n  do 2 (hnf; intros).\n  destruct H, H0.\n  split; apply compond_relation_inclusion; auto.\nDefined.\n\nLemma compond_assoc: forall {A: Type} (R1 R2 R3: relation A),\n  same_relation _ (compond_relation (compond_relation R1 R2) R3) (compond_relation R1 (compond_relation R2 R3)).\nProof.\n  intros.\n  split; hnf; intros;\n  do 2\n  match goal with\n  | H : compond_relation _ _ _ _ |- _ => inversion H; subst; clear H\n  end;\n  do 2 (econstructor; eauto).\nQed.\n\nLemma compond_eq_right: forall {A: Type} (R: relation A), same_relation _(compond_relation R eq) R.\nProof.\n  intros.\n  split; hnf; intros.\n  + inversion H; subst.\n    auto.\n  + econstructor; eauto.\nQed.\n\nLemma compond_eq_left: forall {A: Type} (R: relation A), same_relation _(compond_relation eq R) R.\nProof.\n  intros.\n  split; hnf; intros.\n  + inversion H; subst.\n    auto.\n  + econstructor; eauto.\nQed.\n\nLemma relation_conjunction_inclusion: forall {A} (R1 R2 R3 R4: relation A),\n  inclusion _ R1 R2 ->\n  inclusion _ R3 R4 ->\n  inclusion _ (relation_conjunction R1 R3) (relation_conjunction R2 R4).\nProof.\n  intros.\n  hnf; intros.\n  inversion H1; subst.\n  split; auto.\nQed.\n\nInstance relation_conjunction_proper {A: Type}: Proper (same_relation A ==> same_relation A ==> same_relation A) relation_conjunction.\nProof.\n  do 2 (hnf; intros).\n  destruct H, H0.\n  split; apply relation_conjunction_inclusion; auto.\nDefined.\n\nLemma relation_conjunction_iff: forall {A} (R R': relation A) x y,\n  relation_conjunction R R' x y <-> R x y /\\ R' x y.\nProof.\n  intros.\n  reflexivity.\nQed.\n\nLemma relation_disjunction_iff: forall {A} (R R': relation A) x y,\n  relation_disjunction R R' x y <-> R x y \\/ R' x y.\nProof.\n  intros.\n  reflexivity.\nQed.\n\nLemma relation_disjunction_inclusion_left: forall {A} (R R': relation A),\n  inclusion _ R (relation_disjunction R R').\nProof.\n  intros.\n  intros ? ? ?.\n  rewrite relation_disjunction_iff.\n  tauto.\nQed.\n\nLemma relation_disjunction_inclusion_right: forall {A} (R R': relation A),\n  inclusion _ R' (relation_disjunction R R').\nProof.\n  intros.\n  intros ? ? ?.\n  rewrite relation_disjunction_iff.\n  tauto.\nQed.\n\nDefinition respectful_relation {A B} (f: A -> B) (R: relation B): relation A := fun x y => R (f x) (f y).\n\nDefinition fst_relation {A B}: relation A -> relation (A * B) := respectful_relation (@fst A B).\n\nDefinition snd_relation {A B}: relation B -> relation (A * B) := respectful_relation (@snd A B).\n\nInstance respectful_relation_proper {A B} (f: A -> B): Proper (same_relation _ ==> same_relation _) (respectful_relation f).\nProof.\n  hnf; intros.\n  rewrite @same_relation_spec in H |- *.\n  intros b1 b2.\n  unfold respectful_relation.\n  apply H.\nDefined.\n\nLemma respectful_compond_relation: forall {A B} (f: A -> B) R1 R2,\n  inclusion _\n    (compond_relation (respectful_relation f R1) (respectful_relation f R2))\n    (respectful_relation f (compond_relation R1 R2)).\nProof.\n  intros.\n  intros a1 a2 ?.\n  inversion H; subst.\n  apply compond_intro with (f y); auto.\nQed.\n\n", "meta": {"author": "johndoe20190406", "repo": "RamifyCoq", "sha": "72fb538b40ee8ea641e4bf5fe6cd232756d0929c", "save_path": "github-repos/coq/johndoe20190406-RamifyCoq", "path": "github-repos/coq/johndoe20190406-RamifyCoq/RamifyCoq-72fb538b40ee8ea641e4bf5fe6cd232756d0929c/lib/Relation_ext.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6912890716803912}}
{"text": "(* A basic implementation of left-leaning red-black trees. *)\n(* See: https://mew.org/~kazu/proj/red-black-tree/ *)\n\nRequire Import Lia.\nFrom larith Require Import A_setup B1_utils C2_order.\n\nSection Red_black_tree.\n\nVariable X : Type.\nVariable cmp : X -> X -> comparison.\nHypothesis ord : Order cmp.\n\nInductive rb_color := Red | Black.\nInductive rb_tree :=\n  | Leaf\n  | Fork (c : rb_color) (l : rb_tree) (x : X) (r : rb_tree).\n\nNotation Rd := (Fork Red).\nNotation Bk := (Fork Black).\n\nDefinition rb_col t :=\n  match t with\n  | Leaf => Black\n  | Fork c _ _ _ => c\n  end.\n\nDefinition rb_balance_l c l z r :=\n  match c, l with\n  (* Rotation for double red fork. *)\n  | Black, Rd (Rd xl x xr) y yr =>\n    Rd (Bk xl x xr) y (Bk yr z r)\n  (* No rotation needed. *)\n  | _, _ => Fork c l z r\n  end.\n\nDefinition rb_balance_r c l y r :=\n  match c, l, r with\n  (* Propagate red fork upward. *)\n  | Black, Rd xl x xr, Rd zl z zr =>\n    Rd (Bk xl x xr) y (Bk zl z zr)\n  (* Rotation to make tree left-leaning. *)\n  | _, _, Rd zl z zr =>\n    Fork c (Rd l y zl) z zr\n  (* No rotation needed. *)\n  | _, _, _ => Fork c l y r\n  end.\n\nFixpoint rb_ins x t :=\n  match t with\n  | Leaf => Rd Leaf x Leaf\n  | Fork c l y r =>\n    match cmp x y with\n    | Eq => t\n    | Lt => rb_balance_l c (rb_ins x l) y r\n    | Gt => rb_balance_r c l y (rb_ins x r)\n    end\n  end.\n\nDefinition rb_insert x t :=\n  match rb_ins x t with\n  | Fork _ l x r => Bk l x r\n  | Leaf => Leaf (* never reached. *)\n  end.\n\nFixpoint rb_contains x t :=\n  match t with\n  | Leaf => false\n  | Fork _ l y r =>\n    match cmp x y with\n    | Eq => true\n    | Lt => rb_contains x l\n    | Gt => rb_contains x r\n    end\n  end.\n\nFixpoint rb_height t :=\n  match t with\n  | Leaf => 0\n  | Fork _ l _ r => S (max (rb_height l) (rb_height r))\n  end.\n\n(* Prove that the algorithm obeys the invariants that keep the tree balanced. *)\nSection Tree_invariants.\n\n(* A red node has two black children; there are no red nodes on the right. *)\nFixpoint LLRB_col c t :=\n  match c, t with\n  | _, Leaf => True\n  | Black, Bk l _ r => LLRB_col (rb_col l) l /\\ LLRB_col Black r\n  | Red, Rd l _ r => LLRB_col Black l /\\ LLRB_col Black r\n  | _, _ => False\n  end.\n\n(* The root is red and its left child is as well. *)\nNotation Quasi_LLRB_col t :=\n  match t with\n  | Rd l _ r => LLRB_col Red l /\\ LLRB_col Black r\n  | _ => False\n  end.\n\n(* The black nodes are equally balanced. *)\nInductive Bk_balanced : nat -> rb_tree -> Prop :=\n  | Bk_balanced_Leaf :\n    Bk_balanced 0 Leaf\n  | Bk_balanced_Rd n l x r :\n    Bk_balanced n l -> Bk_balanced n r -> Bk_balanced n (Rd l x r)\n  | Bk_balanced_Bk n l x r :\n    Bk_balanced n l -> Bk_balanced n r -> Bk_balanced (S n) (Bk l x r).\n\nDefinition LLRB p n t := LLRB_col p t /\\ Bk_balanced n t.\nDefinition Quasi_LLRB n t := Quasi_LLRB_col t /\\ Bk_balanced n t.\n\nLemma LLRB_0_Bk_inv c l x r :\n  ¬LLRB Black 0 (Fork c l x r).\nProof.\nintros []; inv H0.\nQed.\n\nLemma LLRB_Rd_inv c n l x r :\n  LLRB Red n (Fork c l x r) -> LLRB Black n l /\\ LLRB Black n r.\nProof.\nintros []. inv H0; simpl in H. easy.\nQed.\n\nLemma LLRB_Bk_inv c n l x r :\n  LLRB Black (S n) (Fork c l x r) -> LLRB (rb_col l) n l /\\ LLRB Black n r.\nProof.\nintros []. inv H0; simpl in H. easy.\nQed.\n\nTheorem rb_height_upper_bound c n t :\n  LLRB c n t ->\n  match c with\n  | Red => rb_height t <= 1 + 2 * n\n  | Black => rb_height t <= 2 * n\n  end.\nProof.\nrevert n c; induction t; simpl; intros.\n- destruct c, H; inv H0; simpl; auto.\n- destruct c0.\n  + apply LLRB_Rd_inv in H as [].\n    apply IHt1 in H; apply IHt2 in H0; lia.\n  + destruct n. apply LLRB_0_Bk_inv in H; easy.\n    apply LLRB_Bk_inv in H as [].\n    apply IHt1 in H; apply IHt2 in H0.\n    destruct (rb_col t1); lia.\nQed.\n\nTheorem LLRB_rb_insert n x t :\n  LLRB Black n t ->\n  LLRB Black n (rb_insert x t) \\/\n  LLRB Black (S n) (rb_insert x t).\nProof.\nAdmitted.\n\nEnd Tree_invariants.\n\n(* Prove that the algorithm maintains a binary-search tree structure. *)\nSection Correct_insertion.\n\nDefinition In_interval lwb upb y :=\n  match lwb with\n  | Some x => cmp x y = Lt\n  | None => True\n  end /\\\n  match upb with\n  | Some z => cmp y z = Lt\n  | None => True\n  end.\n\nFixpoint BST lwb upb t :=\n  match t with\n  | Leaf => True\n  | Fork _ l y r =>\n    BST lwb (Some y) l /\\\n    BST (Some y) upb r /\\\n    In_interval lwb upb y\n  end.\n\nTheorem rb_insert_BST upb lwb x t :\n  In_interval upb lwb x -> BST lwb upb t -> BST lwb upb (rb_insert x t).\nProof.\nAdmitted.\n\nTheorem rb_insert_contains x t :\n  rb_contains x (rb_insert x t) = true.\nProof.\nAdmitted.\n\nEnd Correct_insertion.\n\nEnd Red_black_tree.\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/C3_rbtree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6912890686655458}}
{"text": "From Equations Require Import Equations.\nFrom Coq Require Import ssreflect ssrbool ssrfun.\nFrom mathcomp Require Import ssrnat eqtype seq div.\nFrom favssr Require Import prelude.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Basics.\nContext {T : Type}.\nImplicit Types (xs ys zs: seq T).\n\n(* 1.2.3 Multisets *)\n\n(* We'll be using perm_eq instead of msets. *)\n\n(* 1.4 Proofs *)\n\n(* GCD is terminating as the second argument is decreasing *)\nEquations? gcd' (m n : nat) : nat by wf n lt :=\ngcd' m 0 => m;\ngcd' m n => gcd' n (m %% n).\nProof. by apply/ssrnat.ltP/ltn_pmod. Qed.\n\nLemma gcd_ind P :\n  (forall m n, (n != 0 -> P n (m %% n)) -> P m n) -> forall m n, P m n.\nProof.\nmove=>H m n; elim/ltn_ind: n m=>n IH m; apply: H.\nby move=>Hn; apply/IH/ltn_pmod; rewrite lt0n.\nQed.\n\n(* Equations generates a more detailed principle (uncomment to run): *)\n\n(* Check gcd'_elim. *)\n\n(***********************************************************)\n(* gcd'_elim                                               *)\n(*      : forall P : nat -> nat -> nat -> Type,            *)\n(*          (forall m : nat, P m 0 m) ->                   *)\n(*          (forall m n : nat,                             *)\n(*           P n.+1 (m %% n.+1) (gcd' n.+1 (m %% n.+1)) -> *)\n(*           P m n.+1 (gcd' n.+1 (m %% n.+1))) ->          *)\n(*          forall m n : nat, P m n (gcd' m n)             *)\n(***********************************************************)\n\n(* 1.5 Running time *)\n\nFixpoint T_app xs ys : nat :=\n  if xs is _ :: xs' then (T_app xs' ys).+1 else 1.\n\n(* A simplified implementation compared to the lib *)\nFixpoint rev' xs :=\n  if xs is x :: xs' then rcons (rev' xs') x else [::].\n\nLemma rev'_size xs : size (rev' xs) = size xs.\nProof. by elim: xs=>//=x xs IH; rewrite size_rcons IH. Qed.\n\nFixpoint T_rev xs : nat :=\n  if xs is x :: xs' then (T_rev xs' + T_app (rev' xs') [:: x]).+1 else 1.\n\nLemma T_app_complexity xs ys : T_app xs ys = (size xs).+1.\nProof. by elim: xs=>//= x xs ->. Qed.\n\nLemma T_rev_bound xs : T_rev xs <= (size xs).+1 ^2.\nProof.\nelim: xs=>//=x xs IH.\nrewrite T_app_complexity rev'_size -[in _.+2]addn1\n  sqrnD -(mulnn 1) !muln1 -addnA.\napply: leq_ltn_add=>//.\nby rewrite addnC addn1 ltnS; apply: leq_addr.\nQed.\n\n(* Exercise 1.5.1: exact complexity for T_rev *)\nLemma T_rev_complexity xs : T_rev xs = (size xs).+1 ^2. (* FIXME *)\nProof.\nAdmitted.\n\n(* itrev is called catrev in the lib *)\n\nFixpoint T_catrev xs ys : nat :=\n  if xs is x :: xs' then (T_catrev xs' (x :: ys)).+1 else 1.\n\nLemma T_catrev_complexity xs ys : T_catrev xs ys = (size xs).+1.\nProof. by elim: xs ys=>//=x xs IH ys; rewrite IH. Qed.\n\nLemma catrev_rev_eq xs ys : catrev xs ys = rev' xs ++ ys.\nProof.\nelim: xs ys =>//= x xs IH ys.\nby rewrite IH -cats1 -catA.\nQed.\n\nEnd Basics.\n", "meta": {"author": "clayrat", "repo": "fav-ssr", "sha": "ec672bc001f6ace70cfc971990631371263b40f1", "save_path": "github-repos/coq/clayrat-fav-ssr", "path": "github-repos/coq/clayrat-fav-ssr/fav-ssr-ec672bc001f6ace70cfc971990631371263b40f1/src/basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.6912890641705968}}
{"text": "Require Export prosa.util.notation.\nRequire Export prosa.util.nat.\n\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop path.\n\n(* Lemmas about sum. *)\nSection ExtraLemmas.\n\n  Lemma leq_sum_seq (I: eqType) (r: seq I) (P : pred I) (E1 E2 : I -> nat) :\n    (forall i, i \\in r -> P i -> E1 i <= E2 i) ->\n    \\sum_(i <- r | P i) E1 i <= \\sum_(i <- r | P i) E2 i.\n  Proof.\n    intros LE.\n    rewrite big_seq_cond [\\sum_(_ <- _| P _)_]big_seq_cond.\n      by apply leq_sum; move => j /andP [IN H]; apply LE.\n  Qed.\n\n  Lemma eq_sum_seq: forall (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; rewrite eqn_leq; apply/andP; split.\n    - apply leq_sum_seq; intros.\n        by move: (H i H0 H1) => /eqP EQ; rewrite EQ.\n    - apply leq_sum_seq; intros.\n        by move: (H i H0 H1) => /eqP EQ; rewrite EQ.\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    - 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    - 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  Qed.\n\n\n  Lemma sum_seq_gt0P:\n    forall (T:eqType) (r: seq T) (F: T -> nat),\n      reflect (exists i, i \\in r /\\ 0 < F i) (0 < \\sum_(i <- r) F i).\n  Proof.\n    intros; apply: (iffP idP); intros.\n    {\n      induction r; first by rewrite big_nil in H.\n      destruct (F a > 0) eqn:POS.\n      exists a; split; [by rewrite in_cons; apply/orP; left | by done].\n      apply negbT in POS; rewrite -leqNgt leqn0 in POS; move: POS => /eqP POS.\n      rewrite big_cons POS add0n in H. clear POS.\n      feed IHr; first by done. move: IHr => [i [IN POS]].\n      exists i; split; [by rewrite in_cons; apply/orP;right | by done].\n    }\n    {\n      move: H => [i [IN POS]].\n      rewrite (big_rem i) //=.\n      apply leq_trans with (F i); [by done | by rewrite leq_addr].\n    }\n  Qed.\n\n  Lemma sum_notin_rem_eqn:\n    forall (T:eqType) (a: T) xs P F,\n      a \\notin xs ->\n      \\sum_(x <- xs | P x && (x != a)) F x = \\sum_(x <- xs | P x) F x.\n  Proof.\n    intros ? ? ? ? ? NOTIN.\n    induction xs; first by rewrite !big_nil.\n    rewrite !big_cons.\n    rewrite IHxs; clear IHxs; last first.\n    { apply/memPn; intros y IN.\n      move: NOTIN => /memPn NOTIN.\n        by apply NOTIN; rewrite in_cons; apply/orP; right.\n    }\n    move: NOTIN => /memPn NOTIN. \n    move: (NOTIN a0) => NEQ.\n    feed NEQ; first by (rewrite in_cons; apply/orP; left).\n      by rewrite NEQ Bool.andb_true_r.\n  Qed.\n  \n  (* Trivial identity: any sum of zeros is zero. *)\n  Lemma sum0 m n:\n    \\sum_(m <= i < n) 0 = 0.\n  Proof.\n    by rewrite big_const_nat iter_addn mul0n addn0 //.\n  Qed.\n\n  (* A sum of natural numbers equals zero iff all terms are zero. *)\n  Lemma big_nat_eq0 m n F:\n    \\sum_(m <= i < n) F i = 0 <-> (forall i, m <= i < n -> F i = 0).\n  Proof.\n    split.\n    - rewrite /index_iota => /eqP.\n      rewrite -sum_nat_eq0_nat => /allP ZERO i.\n      rewrite -mem_index_iota /index_iota => IN.\n      by apply/eqP; apply ZERO.\n    - move=> ZERO.\n      have ->: \\sum_(m <= i < n) F i = \\sum_(m <= i < n) 0\n        by apply eq_big_nat => //.\n      by apply sum0.\n  Qed.\n\n  (* We prove that if any element of a set r is bounded by constant [const], \n     then the sum of the whole set is bounded by [const * size r]. *)\n  Lemma sum_majorant_constant:\n    forall (T: eqType) (r: seq T) (P: pred T) F const,\n      (forall a,  a \\in r -> P a -> F a <= const) -> \n      \\sum_(j <- r | P j) F j <= const * (size [seq j <- r | P j]).\n  Proof.\n    clear; intros.\n    induction r; first by rewrite big_nil.\n    feed IHr.\n    { intros; apply H.\n      - by rewrite in_cons; apply/orP; right.\n      - by done. } \n    rewrite big_cons.\n    destruct (P a) eqn:EQ.\n    { rewrite -cat1s filter_cat size_cat.\n      rewrite mulnDr.\n      apply leq_add; last by done.\n      rewrite size_filter.\n      simpl; rewrite addn0.\n      rewrite EQ muln1.\n      apply H; last by done. \n        by rewrite in_cons; apply/orP; left. \n    }\n    { apply leq_trans with (const * size [seq j <- r | P j]); first by done.\n      rewrite leq_mul2l; apply/orP; right.\n      rewrite -cat1s filter_cat size_cat.\n        by rewrite leq_addl.\n    }\n  Qed.\n\n  (* We prove that if for any element x of a set [xs] the following two statements hold \n     (1) [F1 x] is less than or equal to [F2 x] and (2) the sum [F1 x_1, ..., F1 x_n] \n     is equal to the sum of [F2 x_1, ..., F2 x_n], then [F1 x] is equal to [F2 x] for \n     any element x of [xs]. *)\n  Lemma sum_majorant_eqn:\n    forall (T: eqType) xs F1 F2 (P: pred T),\n      (forall x, x \\in xs -> P x -> F1 x <= F2 x) -> \n      \\sum_(x <- xs | P x) F1 x = \\sum_(x <- xs | P x) F2 x ->\n      (forall x, x \\in xs -> P x -> F1 x = F2 x).\n  Proof.\n    intros T xs F1 F2 P H1 H2 x IN PX.\n    induction xs; first by done.\n    have Fact: \\sum_(j <- xs | P j) F1 j <= \\sum_(j <- xs | P j) F2 j.\n    { rewrite [in X in X <= _]big_seq_cond [in X in _ <= X]big_seq_cond leq_sum //.\n      move => y /andP [INy PY].\n      apply: H1; last by done. \n        by rewrite in_cons; apply/orP; right. }\n    feed IHxs.\n    { intros x' IN' PX'.\n      apply H1; last by done.\n        by rewrite in_cons; apply/orP; right. }\n    rewrite big_cons [RHS]big_cons in H2.\n    have EqLeq: forall a b c d, a + b = c + d -> a <= c -> b >= d.\n    { clear; intros; ssromega. } \n    move: IN; rewrite in_cons; move => /orP [/eqP EQ | IN]. \n    { subst a.\n      rewrite PX in H2.\n      specialize (H1 x).\n      feed_n 2 H1; [ by rewrite in_cons; apply/orP; left | by done | ].\n      move: (EqLeq\n               (F1 x) (\\sum_(j <- xs | P j) F1 j)\n               (F2 x) (\\sum_(j <- xs | P j) F2 j) H2 H1) => Q.\n      have EQ: \\sum_(j <- xs | P j) F1 j = \\sum_(j <- xs | P j) F2 j. \n      { by apply/eqP; rewrite eqn_leq; apply/andP; split. }\n        by move: H2 => /eqP; rewrite EQ eqn_add2r; move => /eqP EQ'.\n    }\n    { destruct (P a) eqn:PA; last by apply IHxs.\n      apply: IHxs; last by done.\n      specialize (H1 a).\n      feed_n 2 (H1); [ by rewrite in_cons; apply/orP; left | by done | ].\n      move: (EqLeq\n               (F1 a) (\\sum_(j <- xs | P j) F1 j)\n               (F2 a) (\\sum_(j <- xs | P j) F2 j) H2 H1) => Q.\n        by apply/eqP; rewrite eqn_leq; apply/andP; split.\n    }\n  Qed.\n\n  (* We prove that the sum of Δ ones is equal to Δ. *)\n  Lemma sum_of_ones:\n    forall t Δ,\n      \\sum_(t <= x < t + Δ) 1 = Δ. \n  Proof.\n    intros.\n    rewrite big_const_nat iter_addn_0 mul1n.\n    rewrite addnC -addnBA; last by done.\n      by rewrite subnn addn0.  \n  Qed.\n\n  (* We show that the fact that the sum is smaller than the range \n     of the summation implies the existence of a zero element. *)\n  Lemma sum_le_summation_range :\n    forall f t Δ,\n      \\sum_(t <= x < t + Δ) f x < Δ ->\n      exists x, t <= x < t + Δ /\\ f x = 0.\n  Proof.\n    induction Δ; intros; first by rewrite ltn0 in H.\n    destruct (f (t + Δ)) eqn: EQ.\n    { exists (t + Δ); split; last by done.\n        by apply/andP; split; [rewrite leq_addr | rewrite addnS ltnS].\n    }\n    { move: H; rewrite addnS big_nat_recr //= ?leq_addr // EQ addnS ltnS; move => H.\n      feed IHΔ.\n      { by apply leq_ltn_trans with (\\sum_(t <= i < t + Δ) f i + n); first rewrite leq_addr. }\n      move: IHΔ => [z [/andP [LE GE] ZERO]].\n      exists z; split; last by done.\n      apply/andP; split; first by done.\n        by rewrite ltnS ltnW.\n    }\n  Qed.\n  \nEnd ExtraLemmas.\n\n(* Lemmas about arithmetic with sums. *)\nSection SumArithmetic.\n\n  Lemma sum_seq_diff:\n    forall (T:eqType) (rs: seq T) (F G : T -> nat),\n      (forall i : T, i \\in rs -> G i <= F i) ->\n      \\sum_(i <- rs) (F i - G i) = \\sum_(i <- rs) F i - \\sum_(i <- rs) G i.\n  Proof.\n    intros.\n    induction rs; first by rewrite !big_nil subn0. \n    rewrite !big_cons subh2.\n    - apply/eqP; rewrite eqn_add2l; apply/eqP; apply IHrs.\n        by intros; apply H; rewrite in_cons; apply/orP; right.\n    - by apply H; rewrite in_cons; apply/orP; left.\n    - rewrite big_seq_cond [in X in _ <= X]big_seq_cond.\n      rewrite leq_sum //; move => i /andP [IN _].\n        by apply H; rewrite in_cons; apply/orP; right.\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    rewrite sum_seq_diff; first by done.\n    move => i; rewrite mem_index_iota; move => /andP [_ LT].\n      by apply ALL.\n  Qed.\n\n  Lemma sum_pred_diff:\n    forall (T: eqType) (rs: seq T) (P: T -> bool) (F: T -> nat),\n      \\sum_(r <- rs | P r) F r =\n      \\sum_(r <- rs) F r - \\sum_(r <- rs | ~~ P r) F r.\n  Proof.\n    clear; intros.\n    induction rs; first by rewrite !big_nil subn0.\n    rewrite !big_cons !IHrs; clear IHrs.\n    case (P a); simpl; last by rewrite subnDl.\n    rewrite addnBA; first by done.\n    rewrite big_mkcond leq_sum //.\n    intros t _.\n      by case (P t).\n  Qed.\n  \nEnd SumArithmetic.", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/util/sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.6912890614681635}}
{"text": "Require Import Arith.\nRequire Import Omega.\n\n\nDefinition prop1 (P Q R : Prop) : (P -> Q) -> (Q -> R) -> (P -> R).\nProof.\nintros.\napply (H0 (H H1)).\nQed.\n\n", "meta": {"author": "aidatorajiro", "repo": "WorksOfProof", "sha": "e65dd026f5e700ce37ca5ffab86e863616af8641", "save_path": "github-repos/coq/aidatorajiro-WorksOfProof", "path": "github-repos/coq/aidatorajiro-WorksOfProof/WorksOfProof-e65dd026f5e700ce37ca5ffab86e863616af8641/test2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6911407888072125}}
{"text": "Require Import ZArith.\n\nDefinition var := nat.\n\nInductive expr: Type :=\n  | impp : expr -> expr -> expr\n  | varp : var -> expr.\n\nDeclare Scope syntax.\nNotation \"x --> y\" := (impp x y) (at level 55, right associativity) : syntax.\nLocal Open Scope syntax.\n\nInductive provable: expr -> Prop :=\n| modus_ponens: forall x y, provable (x --> y) -> provable x -> provable y\n| axiom1: forall x y, provable (x --> (y --> x))\n| axiom2: forall x y z, provable ((x --> y --> z) --> (x --> y) --> (x --> z)).\n\nModule NaiveLang.\n  Definition expr := expr.\n  Definition impp := impp.\n  Definition provable := provable.\nEnd NaiveLang.\n\nRequire Import interface_2.\n\nModule NaiveRule.\n  Include DerivedNames (NaiveLang).\n  Lemma modus_ponens :\n    forall x y : expr, provable (impp x y) -> provable x -> provable y.\n  Proof. intros. eapply modus_ponens; eauto. Qed.\n\n  Lemma axiom1 : forall x y : expr, provable (impp x (impp y x)).\n  Proof. exact axiom1. Qed.\n\n  Lemma axiom2 : forall x y z : expr,\n      provable (impp (impp x (impp y z)) (impp (impp x y) (impp x z))).\n  Proof. exact axiom2. Qed.\n\nEnd NaiveRule.\n\nModule T := LogicTheorem NaiveLang NaiveRule.\nModule Solver := IPSolver NaiveLang.\nImport T.\nImport Solver.\n\n", "meta": {"author": "QinxiangCao", "repo": "LOGIC", "sha": "d1476d57345c87447ea500b3d5ea99ee6d0f6863", "save_path": "github-repos/coq/QinxiangCao-LOGIC", "path": "github-repos/coq/QinxiangCao-LOGIC/LOGIC-d1476d57345c87447ea500b3d5ea99ee6d0f6863/LogicGenerator/demo/implementation_2b.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6911360825391489}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (z : natural) (x : natural)\n  : natural := plus z lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj255_coqofml_XZguKS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6911360809923747}}
{"text": "Require Import Reals.\n\nOpen Scope R_scope.\n\nTheorem example_for_field: forall x y:R, y <> 0 -> (x+y)/y = 1+(x/y).\nProof.\n  intros x y H. field. exact H.\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/field.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6911360713648597}}
{"text": "Require Import\n  Coq.Relations.Relation_Definitions Coq.setoid_ring.Ring\n  MathClasses.interfaces.abstract_algebra MathClasses.interfaces.orders MathClasses.theory.rings MathClasses.theory.dec_fields.\nRequire Export\n  MathClasses.orders.rings.\n\nSection contents.\nContext `{DecField F} `{Apart F} `{!TrivialApart F} `{!FullPseudoSemiRingOrder Fle Flt} `{∀ x y : F, Decision (x = y)}.\nAdd Ring F : (stdlib_ring_theory F).\n\nInstance pos_dec_recip_compat x : PropHolds (0 < x) → PropHolds (0 < /x).\nProof.\n  intros E.\n  apply (strictly_order_reflecting (x *.)).\n  rewrite dec_recip_inverse by now apply orders.lt_ne_flip.\n  rewrite mult_0_r. solve_propholds.\nQed.\n\nInstance nonneg_dec_recip_compat x : PropHolds (0 ≤ x) → PropHolds (0 ≤ /x).\nProof.\n  intros E. red.\n  destruct (decide (x = 0)) as [E2 | E2].\n   now rewrite E2, dec_recip_0.\n  apply lt_le. apply pos_dec_recip_compat.\n  apply lt_iff_le_ne. split. easy. now apply not_symmetry.\nQed.\n\nLemma neg_dec_recip_compat x : x < 0 → /x < 0.\nProof.\n  intros. apply flip_neg_negate.\n  rewrite dec_recip_negate.\n  apply pos_dec_recip_compat.\n  now apply flip_neg_negate.\nQed.\n\nLemma nonpos_dec_recip_compat x : x ≤ 0 → /x ≤ 0.\nProof.\n  intros. apply flip_nonpos_negate.\n  rewrite dec_recip_negate.\n  apply nonneg_dec_recip_compat.\n  now apply flip_nonpos_negate.\nQed.\n\nLemma flip_le_dec_recip x y : 0 < y → y ≤ x  → /x ≤ /y.\nProof with trivial.\n  intros E1 E2.\n  apply (order_reflecting_pos (.*.) x)...\n   now apply lt_le_trans with y.\n  rewrite dec_recip_inverse.\n   apply (order_reflecting_pos (.*.) y)...\n   rewrite (commutativity x), associativity, dec_recip_inverse.\n    now ring_simplify.\n   now apply lt_ne_flip.\n  apply lt_ne_flip.\n  now apply lt_le_trans with y.\nQed.\n\nLemma flip_le_dec_recip_l x y : 0 < y → /y ≤ x  → /x ≤ y.\nProof with trivial.\n  intros E1 E2.\n  rewrite <-(dec_recip_involutive y).\n  apply flip_le_dec_recip...\n  now apply pos_dec_recip_compat.\nQed.\n\nLemma flip_le_dec_recip_r x y : 0 < y → y ≤ /x  → x ≤ /y.\nProof.\n  intros E1 E2.\n  rewrite <-(dec_recip_involutive x).\n  now apply flip_le_dec_recip.\nQed.\n\nLemma flip_lt_dec_recip x y : 0 < y → y < x  → /x < /y.\nProof.\n  intros E1 E2.\n  assert (0 < x) by now transitivity y.\n  apply (strictly_order_reflecting (x *.)).\n  rewrite dec_recip_inverse.\n   apply (strictly_order_reflecting (y *.)).\n   rewrite (commutativity x), associativity, dec_recip_inverse.\n    now ring_simplify.\n   now apply lt_ne_flip.\n  now apply lt_ne_flip.\nQed.\n\nLemma flip_lt_dec_recip_l x y : 0 < y → /y < x  → /x < y.\nProof.\n  intros E1 E2.\n  rewrite <-(dec_recip_involutive y).\n  apply flip_lt_dec_recip; trivial.\n  now apply pos_dec_recip_compat.\nQed.\n\nLemma flip_lt_dec_recip_r x y : 0 < y → y < /x  → x < /y.\nProof.\n  intros E1 E2.\n  rewrite <-(dec_recip_involutive x).\n  now apply flip_lt_dec_recip.\nQed.\nEnd contents.\n\n(* Due to bug #2528 *)\n#[global]\nHint Extern 12 (PropHolds (0 ≤ _)) => eapply @nonneg_dec_recip_compat : typeclass_instances.\n#[global]\nHint Extern 12 (PropHolds (0 < _)) => eapply @pos_dec_recip_compat : typeclass_instances.\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/orders/dec_fields.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.6909845617271875}}
{"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 ZArithRing.\nRequire Import ZArith_base.\nRequire Export Omega.\nRequire Import Wf_nat.\nLocal Open Scope Z_scope.\n\n\n(**********************************************************************)\n(** About parity *)\n\nNotation two_or_two_plus_one := Z_modulo_2 (only parsing).\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. reflexivity. Qed.\n\nLemma floor_ok : forall p:positive, floor p <= Zpos p < 2 * floor p.\nProof.\n unfold floor. induction p; simpl.\n - rewrite !Pos2Z.inj_xI, (Pos2Z.inj_xO (xO _)), Pos2Z.inj_xO. omega.\n - rewrite (Pos2Z.inj_xO (xO _)), (Pos2Z.inj_xO p), Pos2Z.inj_xO. omega.\n - 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, Z.abs m < Z.abs 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)).\n  enough (H:Q (Z.abs p)) by\n    (destruct (Zabs_dec p) as [-> | ->]; elim H; auto with zarith).\n  apply (Z_lt_rec Q); auto with zarith.\n  subst Q; intros x H.\n  split; apply HP.\n  - rewrite Z.abs_eq; auto; intros.\n    destruct (H (Z.abs m)); auto with zarith.\n    destruct (Zabs_dec m) as [-> | ->]; trivial.\n  - rewrite Z.abs_neq, Z.opp_involutive; auto with zarith; intros.\n    destruct (H (Z.abs m)); auto with zarith.\n    destruct (Zabs_dec m) as [-> | ->]; trivial.\nQed.\n\nTheorem Z_lt_abs_induction :\n  forall P:Z -> Prop,\n    (forall n:Z, (forall m:Z, Z.abs m < Z.abs 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  enough (Q (Z.abs p)) by\n    (destruct (Zabs_dec p) as [-> | ->]; elim H; auto with zarith).\n  apply (Z_lt_induction Q); auto with zarith.\n  subst Q; intros.\n  split; apply HP.\n  - rewrite Z.abs_eq; auto; intros.\n    elim (H (Z.abs m)); intros; auto with zarith.\n    elim (Zabs_dec m); intro eq; rewrite eq; trivial.\n  - rewrite Z.abs_neq, Z.opp_involutive; auto with zarith; intros.\n    destruct (H (Z.abs m)); auto with zarith.\n    destruct (Zabs_dec m) as [-> | ->]; 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  destruct x; [apply Hzero|apply Hpos|apply Hneg]; easy.\nQed.\n\nLemma sqr_pos n : n * n >= 0.\nProof.\n Z.swap_greater. apply Z.square_nonneg.\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 (Z.succ acc) A l\n  end.\n\nDefinition Zlength := Zlength_aux 0.\nArguments Zlength [A] l.\n\nSection Zlength_properties.\n\n  Variable A : Type.\n\n  Implicit Type l : list A.\n\n  Lemma Zlength_correct l : Zlength l = Z.of_nat (length l).\n  Proof.\n    assert (H : forall l acc, Zlength_aux acc A l = acc + Z.of_nat (length l)).\n    clear l. induction l.\n    auto with zarith.\n    intros. simpl length; simpl Zlength_aux.\n     rewrite IHl, Nat2Z.inj_succ; auto with zarith.\n    unfold Zlength. now rewrite H.\n  Qed.\n\n  Lemma Zlength_nil : Zlength (A:=A) nil = 0.\n  Proof. reflexivity. Qed.\n\n  Lemma Zlength_cons (x:A) l : Zlength (x :: l) = Z.succ (Zlength l).\n  Proof.\n    intros. now rewrite !Zlength_correct, <- Nat2Z.inj_succ.\n  Qed.\n\n  Lemma Zlength_nil_inv l : Zlength l = 0 -> l = nil.\n  Proof.\n    rewrite Zlength_correct.\n    destruct l as [|x l]; auto.\n    now rewrite <- Nat2Z.inj_0, Nat2Z.inj_iff.\n  Qed.\n\nEnd Zlength_properties.\n\nArguments Zlength_correct [A] l.\nArguments Zlength_cons [A] x l.\nArguments Zlength_nil_inv [A] l _.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/ZArith/Zcomplements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.690984546629596}}
{"text": "(* In this file some more useful facts about finite posets are proved as lemmas. \n   Following is a partial list of some of them  -------------------------------\n     \nDEFINITIONS: ------------------------------------------------------------------\n1. Inside P1 P2: it is a binary relation which becomes true when the carrier set of \n                 poset P1 is strictly included in the carrier set of poset P2.   \n2. Included_in P2 P1: it is a binary relation which becomes true when the carrier set\n                      of poset P1 is included in carrier set of poset P2. \n3. Is_largest_set E e: e is the largest set among all the sets present in E.\n\n4. Is_smallest_set E e: e is the smallest set among all the sets present in E.\n\nSOME IMP RESULTS: -------------------------------------------------------------\n1. Lemma Inside_is_WF: Inside relation on finite posets is well founded.\n\n2. Lemma Largest_Chain_remains: If P1 is included in P2 and e is a largest chain in P2\n                                then e is also a largest chain in P1 provided e is con-\n                                -tained in P1.\n\n3. Lemma Largest_Antichain_remains: If P1 is included in P2 and e is a largest antichain \n                                 in P2 then e is also a largest antichain in P1 provided e\n                                 is contained in P1.\n\n4. Lemma MaxExists: Every Finite non-empty subset of natural numbers has a maximum.\n\n5. Lemma MinExists: Every Finite non-empty subset of natural numbers has a minimum.\n\n6. Lemma Largest_set_exists: Let E be a non-empty finite collection of finite sets.\n                             Then, there exists a largest cardinality set e in E.\n\n7. Lemma Smallest_set_exists: Let E be a non-empty finite collection of finite sets.\n                             Then, there exists a smallest cardinality set e in E.\n\n8. Lemma exists_largest_antichain: There exists a largest antichain in every finite poset.\n\n9. Lemma exists_largest_chain: There exists a largest chain in every finite poset.\n\n10.Lemma exists_disjoint_cover: If cv is a smallest chain cover of poset P of size m,\n                                then there also exists a disjoint chain cover of P of\n                                size m.  *)\n    \n\n\nRequire Export PigeonHole.\nRequire Export BasicFacts.\n\nRequire Export FPO_Facts.\nRequire Export omega.Omega.\n\n\n\n    (* ----------------------INSIDE RELATION AND SOME PROPERTIES OF IT ----------------------- *)\n    (* --------------------------------------------------------------------------------------- *)\n\nSection Inside_Property.\n\n  Variable U: Type.\n\nDefinition Inside (P1: FPO U)(P2: FPO U):Prop:=\n  Strict_Included _ (Carrier_of _ P1) (Carrier_of _ P2) /\\  Rel_of U P1 = Rel_of U P2 .\n\nDefinition Included_in (P2: FPO U)(P1: FPO U): Prop:=\n  Included _ (Carrier_of _ P1) (Carrier_of _ P2) /\\ Rel_of U P1 = Rel_of U P2 .\n\n\nLemma Inside_is_WF: well_founded Inside.\nProof. {\n        - unfold well_founded. intro P'. \n       \n          assert(H: exists n:nat, cardinal _ (Carrier_of _ P') n ).  \n            { apply finite_cardinal;\n              apply Finite_PO. }\n            \n          destruct H as [n0 H]. (*let n0 be cardinality of P' *)\n          generalize H. generalize P'. generalize n0 as n.\n          induction n using strong_induction.\n          intros P2 H1.  (* cardinality of P2 is n *)\n          apply Acc_intro.\n          intros P1 H2. (*let P1 be Included in P2 *)\n          \n          assert(H3: exists m:nat, cardinal _ (Carrier_of _ P1) m).\n            { apply finite_cardinal. apply Finite_PO. }\n          \n          destruct H3 as [m H3]. (*let m be the cardinality of P1 *)\n          apply H0 with (k:= m).\n        (* GOAL: to prove that m <n . i,e Carrier of P1 is strict_included in P2  *)\n          assert(H4: Strict_Included _ (Carrier_of _ P1) (Carrier_of _ P2)).\n           { unfold Inside in H2. destruct H2 as [H2a H2]. assumption. }\n\n          + { apply strict_included_card_less with\n              (U:=U) (e1:= Carrier_of _ P1)(e2:= Carrier_of _ P2).\n            \n            * assumption.\n            * assumption.\n            * assumption. }\n\n          + assumption.  } Qed.\n\n \n\n  Lemma Chain_remains: forall (P1 P2: FPO U)(e: Ensemble U),\n                       Inside P1 P2 -> Is_a_chain_in P1 e -> Is_a_chain_in P2 e.\n  Proof. { intros. unfold Is_a_chain_in. unfold Is_a_chain_in in H0.\n           unfold Inside in H. destruct H0 as [H0 H1]. destruct H0 as [H0 H2].\n           destruct H as [T1 T2]. unfold Strict_Included in T1.\n           destruct T1 as [T0 T1]. \n           split.\n           { split.\n             {  auto with sets.  }\n             { auto. }  }\n\n           rewrite <- T2. apply H1.  }  Qed.\n\n  Lemma Chain_remains1: forall (P1 P2: FPO U)(e: Ensemble U),\n                       Included_in P2 P1 -> Is_a_chain_in P1 e -> Is_a_chain_in P2 e.\n  Proof.  { intros. unfold Is_a_chain_in. unfold Is_a_chain_in in H0.\n           unfold Included_in in H. destruct H0 as [H0 H1]. destruct H0 as [H0 H2].\n           destruct H as [T1 T2].  \n           split.\n           { split.\n             {  auto with sets.  }\n             { auto. }  }\n\n           rewrite <- T2. apply H1.  }  Qed. \n\n  Lemma Chain_remains2:  forall (P1 P2: FPO U)(e: Ensemble U),\n      Included_in P2 P1 -> Included _ e (Carrier_of _ P1) -> Is_a_chain_in P2 e ->\n      Is_a_chain_in P1 e.\n    Proof.  { intros. unfold Is_a_chain_in. unfold Is_a_chain_in in H1.\n           unfold Included_in in H. destruct H as [F0 F1]. destruct H1 as [H1 H2].\n           destruct H1 as [T1 T2].  \n           split.\n           { split.\n             {  auto with sets.  }\n             { auto. }  }\n\n           rewrite  F1. apply H2.  }  Qed.\n\n  Lemma Largest_Chain_remains:  forall (P1 P2: FPO U)(e: Ensemble U),\n    Included_in P2 P1 -> Included _ e (Carrier_of _ P1) ->\n    Is_largest_chain_in  P2 e -> Is_largest_chain_in  P1 e.\n  Proof. { intros. apply_fpo_def.\n           { eapply Chain_remains2 with (P2:=P2);(tauto || apply H1). }\n           { intros. destruct H1. apply H5 with (e1:=e1).\n             eapply Chain_remains1 with (P1:=P1); tauto. tauto. tauto. }  } Qed. \n\n\n\n\n Lemma  Antichain_not_changed:\n         forall (P1 P2: FPO U)(e: Ensemble U),\n           Inside  P1 P2 -> Included _ e (Carrier_of _ P1) ->\n           (Is_an_antichain_in  P2 e <-> Is_an_antichain_in P1 e ).\n Proof. {\n   intros. unfold iff. split.\n  * (* CASE1: Is_an_antichain_in U P2 e -> Is_an_antichain_in U P1 e *)\n   intro. destruct H1.\n   destruct H1 as [H1a H1]. \n   unfold Is_an_antichain_in. split.\n   \n   + { split.  - assumption. - assumption. }\n   + { unfold Inside in H. destruct H as [Ha Hb].\n       rewrite Hb. assumption. }\n  * (* CASE2:  Is_an_antichain_in U P1 e -> Is_an_antichain_in U P2 e *)\n       intro. destruct H1. destruct H1 as [H1a H1].\n       unfold Is_an_antichain_in. split.\n    +  split.\n       -  destruct H. destruct H.\n          apply Included_transitive with (e2:= (Carrier_of U P1)).\n          assumption. assumption.\n       -  assumption.\n     + unfold Inside in H.\n          destruct H as [Ha H]. rewrite H in H2.\n          assumption.  } Qed.\n\n Lemma Antichain_not_changed1:  forall (P1 P2: FPO U)(e: Ensemble U),\n           Inside  P1 P2 -> Included _ e (Carrier_of _ P1) ->\n           Is_an_antichain_in  P2 e -> Is_an_antichain_in  P1 e .\n Proof. { apply Antichain_not_changed. } Qed.\n\n\n \n Lemma Antichain_not_changed2: forall (P1 P2: FPO U)(e: Ensemble U),\n           Inside  P1 P2 -> Included _ e (Carrier_of _ P1) ->\n           Is_an_antichain_in  P1 e ->  Is_an_antichain_in  P2 e .\n Proof.  apply Antichain_not_changed. Qed.\n\n Lemma Antichain_remains1:  forall (P1 P2: FPO U)(e: Ensemble U),\n           Included_in  P2 P1 -> Included _ e (Carrier_of _ P1) ->\n           Is_an_antichain_in  P2 e -> Is_an_antichain_in  P1 e.\n Proof.  { intros. destruct H1.\n           destruct H1 as [H1a H1]. \n           unfold Is_an_antichain_in. split.\n   \n          { split.  - assumption. - assumption. }\n          { unfold Included_in in H. destruct H as [Ha Hb].\n            rewrite Hb. assumption. }   } Qed.\n\n  Lemma Antichain_remains2:  forall (P1 P2: FPO U)(e: Ensemble U),\n           Included_in  P2 P1 -> Included _ e (Carrier_of _ P1) ->\n           Is_an_antichain_in  P1 e ->  Is_an_antichain_in  P2 e.\n  Proof. { intros.  destruct H1. destruct H1 as [H1a H1].\n          unfold Is_an_antichain_in. split.\n          +  split.\n          -  destruct H. \n             apply Included_transitive with (e2:= (Carrier_of U P1)).\n             assumption. assumption.\n          -  assumption.\n             + unfold Included_in in H.\n               destruct H as [Ha H]. rewrite H in H2.\n               assumption.  } Qed.\n\n  Lemma Largest_Antichain_remains:  forall (P1 P2: FPO U)(e: Ensemble U),\n    Included_in P2 P1 -> Included _ e (Carrier_of _ P1) ->\n    Is_largest_antichain_in  P2 e -> Is_largest_antichain_in  P1 e.\n  Proof. {  intros P1 P2 la.  intros.\n (* We will prove it by contradiction. we assume that la is not a largest antichain in P1\n  and therefore there is some chain la' larger than la and an antichain in P1. This must\n  also be an antichain in P2. Hence la is also not the largest antichain of P2. This \n  contradicts the assumption H1 that la is largest antichain of P2. *)\n  elim (EM (Is_largest_antichain_in  P1 la)).\n  Focus 2.\n- intro.\n  absurd(Is_largest_antichain_in  P2 la).\n  \n    + assert(H3: ~ forall (la' : Ensemble U),\n               forall (n n':nat),  Is_an_antichain_in  P1 la' ->\n                                   cardinal _ la n -> cardinal _ la' n' -> n'<= n).\n      { intro. absurd (Is_largest_antichain_in  P1 la).\n       assumption.\n       apply largest_antichain_cond.\n\n       destruct H1. apply Antichain_remains1 with (P2:=P2).\n       assumption. assumption. assumption. assumption. } \n     \n      (* assertion H3 proved *)\n      \n     intro.\n     destruct H4.\n      \n     assert(H3a: exists (la': Ensemble U), ~ forall (n n':nat),\n         Is_an_antichain_in  P1 la' ->\n        cardinal U la n -> cardinal U la' n' -> n' <= n).\n        { apply Negation6. assumption. } \n     assert(H4a: exists e1: Ensemble U, ~ (forall n n1:nat, Is_an_antichain_in  P2 e1 ->\n                                         cardinal U la n -> cardinal U e1 n1 -> n1 <= n ) ).\n        { destruct H3a as [la' H3a]. exists la'.\n          intro. elim H3a.\n          intros n n1 H7. apply H6. generalize H7. apply Antichain_remains2.\n          assumption. destruct H7. apply H7. } \n     absurd (forall (e1 : Ensemble U) (n n1 : nat),\n       Is_an_antichain_in  P2 e1 ->\n       cardinal U la n -> cardinal U e1 n1 -> n1 <= n).\n       { apply Negation7. assumption. } { assumption. }\n\n   + assumption.\n- trivial.  } Qed.   \n \n\n\nLemma Largest_antichain_remains:\n  forall (P1 P2: FPO U)(e: Ensemble U),\n    Inside P1 P2 -> Included _ e (Carrier_of _ P1) ->\n    Is_largest_antichain_in  P2 e -> Is_largest_antichain_in  P1 e.\nProof. {\n  intros P1 P2 la.  intros.\n  (* We will prove it by contradiction. we assume that la is not a largest antichain in P1\n  and therefore there is some chain la' larger than la and an antichain in P1. This must\n  also be an antichain in P2. Hence la is also not the largest antichain of P2. This \n  contradicts the assumption H1 that la is largest antichain of P2. *)\n  elim (EM (Is_largest_antichain_in  P1 la)).\n  Focus 2.\n- intro.\n  absurd(Is_largest_antichain_in  P2 la).\n  \n    + assert(H3: ~ forall (la' : Ensemble U),\n               forall (n n':nat),  Is_an_antichain_in  P1 la' ->\n                                   cardinal _ la n -> cardinal _ la' n' -> n'<= n).\n      { intro. absurd (Is_largest_antichain_in  P1 la).\n       assumption.\n       apply largest_antichain_cond.\n\n       destruct H1. apply Antichain_not_changed1 with (P2:=P2).\n       assumption. assumption. assumption. assumption. }\n     \n      (* assertion H3 proved *)\n      \n     intro.\n     destruct H4.\n      \n     assert(H3a: exists (la': Ensemble U), ~ forall (n n':nat),\n         Is_an_antichain_in  P1 la' ->\n        cardinal U la n -> cardinal U la' n' -> n' <= n).\n        { apply Negation6. assumption. } \n     assert(H4a: exists e1: Ensemble U, ~ (forall n n1:nat, Is_an_antichain_in  P2 e1 ->\n                                         cardinal U la n -> cardinal U e1 n1 -> n1 <= n ) ).\n        { destruct H3a as [la' H3a]. exists la'.\n          intro. elim H3a.\n          intros n n1 H7. apply H6. generalize H7. apply Antichain_not_changed2.\n          assumption. destruct H7. apply H7. }\n     absurd (forall (e1 : Ensemble U) (n n1 : nat),\n       Is_an_antichain_in  P2 e1 ->\n       cardinal U la n -> cardinal U e1 n1 -> n1 <= n).\n       { apply Negation7. assumption. } { assumption. }\n\n   + assumption.\n- trivial.  } Qed.\n\nEnd Inside_Property.    \n\nHint Resolve Chain_remains1 Chain_remains2 Largest_Chain_remains : fpo_facts.\nHint Resolve Antichain_remains1 Antichain_remains2 Largest_Antichain_remains: fpo_facts.\n\n(* ----------------------------- EXISTENCE OF LARGEST ELEMENTS-----------------------------  *)\n\n\nSection Largest_members.\n\n  Variable U: Type.\n\n\nHint Resolve Singleton_is_finite: sets_card.\nLemma MaxExists: forall e: Ensemble nat,\n    Finite _ e -> Inhabited _ e -> (exists max: nat, In _ e max /\\ (forall x: nat, In _ e x -> x<= max)).\nProof. { intros.\n       \n       assert (Order _ le).\n       { Print Order. apply Definition_of_order.\n         {  unfold Reflexive. auto with arith. }\n         { unfold Transitive. apply le_trans. }\n         {unfold Antisymmetric. auto with arith. } }\n       Print PO.\n\n       pose (P:= {|Carrier_of:= e ; Rel_of:= le ; PO_cond1:= H0 ; PO_cond2:= H1 |}).\n\n       pose (FP:= {|PO_of := P; FPO_cond:= H |}).\n       pose (C:= Carrier_of _ FP).\n       pose (R:= Rel_of _ FP).\n\n       assert (Totally_ordered _ FP C ).\n       { Print Totally_ordered. apply Totally_ordered_definition.\n         intros. simpl. omega.   }\n\n       elim Largest_element_exists with (FP:=FP).\n       intro max. intros.\n\n       exists max. unfold Is_the_largest_element_in in H3. simpl in H3. tauto.\n       simpl. apply H2.  } Qed.\n\nLemma MinExists:  forall e: Ensemble nat,\n    Finite _ e -> Inhabited _ e -> (exists min: nat, In _ e min /\\ (forall x: nat, In _ e x -> min <= x)).\nProof.  { intros.\n       \n       assert (Order _ le).\n       { Print Order. apply Definition_of_order.\n         {  unfold Reflexive. auto with arith. }\n         { unfold Transitive. apply le_trans. }\n         {unfold Antisymmetric. auto with arith. } }\n       Print PO.\n\n       pose (P:= {|Carrier_of:= e ; Rel_of:= le ; PO_cond1:= H0 ; PO_cond2:= H1 |}).\n\n       pose (FP:= {|PO_of := P; FPO_cond:= H |}).\n       pose (C:= Carrier_of _ FP).\n       pose (R:= Rel_of _ FP).\n\n       assert (Totally_ordered _ FP C ).\n       { Print Totally_ordered. apply Totally_ordered_definition.\n         intros. simpl. omega.  }\n\n       elim Smallest_element_exists with (FP:=FP).\n       intro min. intros.\n\n       exists min. unfold Is_the_smallest_element_in in H3. simpl in H3. tauto.\n       simpl. apply H2.  } Qed.  \n\n    Definition numbers_lte (n: nat): Ensemble nat := fun (x:nat)=> x<=n.\n    Check numbers_lte.\n\n    Notation \"[ n ]\" := (numbers_lte n).\n\n    Lemma Finite_n: forall n: nat, Finite _ [n]. \n    Proof. { intro. induction n.\n           assert ( Included _ [0]  (Singleton _ 0)).\n           { unfold Included. intros. unfold In in H.  unfold numbers_lte in H.\n            Print Singleton. cut (x=0). intro. rewrite H0.\n            auto with sets. auto with arith.  } \n           eapply Finite_downward_closed with (A:= (Singleton _ 0)).\n           auto with sets_card. auto with sets_card. \n           assert ( Included _ [S n] (Add _ [n] (S n)) ).\n           { unfold Included. intros. unfold In in H.  unfold numbers_lte in H.\n             unfold Add.\n             assert ( x< S n \\/ x= S n). generalize H.\n             SearchPattern (?x <=  ?n -> ?x < ?n \\/ ?x =  ?n). apply le_lt_or_eq.\n             elim H0.\n             { intro. apply Union_introl. unfold In. unfold numbers_lte. generalize H1.\n               auto with arith.  }\n             { intro. apply Union_intror. rewrite H1. auto with sets. }\n           }\n           eapply Finite_downward_closed with (A:= (Add nat [n] (S n)) ).\n           { eapply Union_is_finite with (A:= [n]). auto.\n           intro. unfold In in H0. unfold numbers_lte in H0.\n           absurd ( S n <= n). auto with arith.  auto. }\n           { auto. }  } Qed.  \n\n    Lemma MaxExists1:\n      forall n:nat, forall e: Ensemble nat, Inhabited _ e ->\n          Included _ e [ n ] -> (exists max:nat, In _ e max /\\ (forall x: nat, In _ e x -> x<= max)).\n    Proof. { intros n e.   intro T. intros.\n           assert(H1: Finite _ e).\n           { Check Finite_downward_closed.\n             apply Finite_downward_closed with (A:= [n] ).  apply Finite_n. auto. }\n           generalize T. generalize H1. apply MaxExists. } Qed.\n\n    Set Implicit Arguments.\n\n\n\n Inductive Is_largest_set (U: Type) (E: Ensemble (Ensemble U)) (e: Ensemble U): Prop:=\n  Larg_cond:  In _ E e ->\n   (forall (e1 : Ensemble U)(n n1 : nat), (In _ E e1 /\\ cardinal _ e1 n1 /\\ cardinal _ e n) -> n1 <= n) ->\n   Is_largest_set  E e.\n\n Inductive Is_smallest_set (U: Type) (E: Ensemble (Ensemble U)) (e: Ensemble U): Prop:=\n  Small_cond:  In _ E e ->\n   (forall (e1 : Ensemble U)(n n1 : nat), (In _ E e1 /\\ cardinal _ e1 n1 /\\ cardinal _ e n) -> n <= n1) ->\n   Is_smallest_set  E e.\n\n Unset Implicit Arguments. \n\n Lemma Largest_set_exists: forall U:Type, forall E: Ensemble (Ensemble U),\n         Finite _ E -> Inhabited _ E ->\n         (forall e: Ensemble U, In _ E e -> Finite _ e) ->\n         exists e_max: Ensemble U, Is_largest_set E e_max.\n Proof. {\n (* Proof Idea: We consider the subset of Natural numbers which has the size\n    of each set in E. We call it N. we can prove that N has a maximum number.\n    hence the set corresponding to it will be the largest set.  *)\n   clear U. intros. Check my_choice.\n   assert ( exists f : Ensemble U -> nat, forall x : Ensemble U, In _ E x -> cardinal _ x (f x)).\n   { apply my_choice. exists 0. trivial. intros. apply finite_cardinal. auto. }\n\n   destruct H2 as [size H2].\n   pose (N:= Im _ _ E size).\n\n   assert (Finite _ N ).\n   { apply finite_image. auto. }\n\n   assert (exists max: nat, In _ N max /\\ (forall x: nat, In _ N x -> x<= max)).\n   { Print MaxExists. apply MaxExists. auto.\n     destruct H0. eapply Inhabited_intro with (x:= size x).\n     unfold N. eapply Im_def. auto. }\n\n   destruct H4 as [n H4]. destruct H4.\n   assert (exists e : Ensemble U, In _ E e /\\ size e = n).\n   { apply Im_inv . apply H4. } destruct H6 as [e_max H6]. destruct H6. \n\n   exists e_max.\n   { apply Larg_cond.  tauto. intros. destruct H8. destruct H9.\n     assert (n= n0).\n     { cut (cardinal U e_max (size e_max) ).  rewrite H7. intro.\n       eapply cardinal_unicity. exact H11.  auto. auto. }\n     rewrite <- H11. apply H5. apply Im_intro with (x:=e1). auto.\n     cut ( cardinal _ e1 (size e1)). intro. eapply cardinal_unicity. exact H9. auto.\n     apply H2. auto.  }   } Qed.\n\n Lemma Smallest_set_exists:  forall U:Type, forall E: Ensemble (Ensemble U),\n         Finite _ E -> Inhabited _ E ->\n         (forall e: Ensemble U, In _ E e -> Finite _ e) ->\n         exists e_min: Ensemble U, Is_smallest_set E e_min.\n Proof. {\n (* Proof Idea: We consider the subset of Natural numbers which has the size\n    of each set in E. We call it N. we can prove that N has a minimum number.\n    hence the set corresponding to it will be the smallest set.  *) \n   clear U. intros. Check my_choice.\n   assert ( exists f : Ensemble U -> nat, forall x : Ensemble U, In _ E x -> cardinal _ x (f x)).\n   { apply my_choice. exists 0. trivial. intros. apply finite_cardinal. auto. }\n\n   destruct H2 as [size H2].\n   pose (N:= Im _ _ E size).\n\n   assert (Finite _ N ).\n   { apply finite_image. auto. }\n\n   assert (exists min: nat, In _ N min /\\ (forall x: nat, In _ N x -> min <= x)).\n   { Print  MinExists. apply MinExists. auto.\n     destruct H0. eapply Inhabited_intro with (x:= size x).\n     unfold N. eapply Im_def. auto. }\n\n   destruct H4 as [n H4]. destruct H4.\n   assert (exists e : Ensemble U, In _ E e /\\ size e = n).\n   { apply Im_inv . apply H4. } destruct H6 as [e_min H6]. destruct H6. \n\n   exists e_min.\n   { apply Small_cond.  tauto. intros. destruct H8. destruct H9.\n     assert (n= n0).\n     { cut (cardinal U e_min (size e_min) ).  rewrite H7. intro.\n       eapply cardinal_unicity. exact H11.  auto. auto. }\n     rewrite <- H11. apply H5. apply Im_intro with (x:=e1). auto.\n     cut ( cardinal _ e1 (size e1)). intro. eapply cardinal_unicity. exact H9. auto.\n     apply H2. auto.  }   } Qed. \n\n\nLemma exists_largest_antichain: forall (P: FPO U), exists (m: nat)(la: Ensemble U),\n      (Is_largest_antichain_in P la) /\\ (cardinal _ la m).\nProof. { intros.\n         pose (C:= Carrier_of _ P).\n         pose (E:= fun (e: Ensemble U)=> Is_an_antichain_in  P e).\n       assert (H_Finite: Finite _ E).\n       { assert (H: Included _ E (Power_set _ C) ).\n         { unfold E. unfold Included.  unfold In.\n           intros la H.  destruct H.  unfold C.\n           apply Definition_of_Power_set. tauto. }\n         apply Finite_downward_closed with (A:= Power_set U C).\n         apply Power_set_finite. unfold C. apply FPO_cond. tauto. } \n       \n       assert (All_Finite: forall e: Ensemble U, In _ E e -> Finite _ e).\n       { intros la H.\n         assert (H0: Included _ la C).\n         { unfold E in H. unfold In in H. apply H. }\n         apply Finite_downward_closed with (A:= C). apply FPO_cond.\n         auto. }\n\n       assert (Inhabited_E: Inhabited _ E).\n       { elim Antichain_exists with (FP:=P). intro a. intro.\n         eapply Inhabited_intro with (x:= a).\n         unfold In. unfold E. auto.  }\n       \n       assert (H: exists e_max: Ensemble U, Is_largest_set E e_max).\n       { apply Largest_set_exists.  auto. auto. auto. }\n\n       destruct H as [e_max H]. destruct H.\n       assert (H1: exists m: nat, cardinal _ e_max m).\n       { apply finite_cardinal. auto. }\n       destruct H1  as [m H1].\n       exists m. exists e_max.\n       split.\n       { apply largest_antichain_cond. auto.  unfold E in H0. unfold In in H0.\n         intros e1 n n1. intros.\n         apply H0 with (e1:= e1). tauto. } \n       tauto. } Qed.\n\n\nLemma exists_largest_chain: forall (P: FPO U), exists (m: nat)(lc: Ensemble U),\n      (Is_largest_chain_in P lc) /\\ (cardinal _ lc m).\nProof. { intros.\n         pose (C:= Carrier_of _ P).\n         pose (E:= fun (e: Ensemble U)=> Is_a_chain_in P e).\n\n       assert (H_Finite: Finite _ E).\n       { assert (H: Included _ E (Power_set _ C) ).\n         { unfold E. unfold Included.  unfold In.\n           intros la H.  destruct H.  unfold C.\n           apply Definition_of_Power_set. tauto. }\n         apply Finite_downward_closed with (A:= Power_set U C).\n         apply Power_set_finite. unfold C. apply FPO_cond. tauto. }\n       \n       assert (All_Finite: forall e: Ensemble U, In _ E e -> Finite _ e).\n       { intros la H.\n         assert (H0: Included _ la C).\n         { unfold E in H. unfold In in H. apply H. }\n         apply Finite_downward_closed with (A:= C). apply FPO_cond.\n         auto. }\n\n       assert (Inhabited_E: Inhabited _ E).\n       { elim Chain_exists with (FP:=P). intro a. intro.\n         eapply Inhabited_intro with (x:= a).\n         unfold In. unfold E. auto.  }\n       \n       assert (H: exists e_max: Ensemble U, Is_largest_set E e_max).\n       { apply Largest_set_exists.  auto. auto.  auto. }\n\n       destruct H as [e_max H]. destruct H.\n       assert (H1: exists m: nat, cardinal _ e_max m).\n       { apply finite_cardinal. auto. }\n       destruct H1  as [m H1].\n       exists m. exists e_max.\n       split.\n       { apply largest_chain_cond. auto.  unfold E in H0. unfold In in H0.\n         intros e1 n n1. intros.\n         apply H0 with (e1:= e1). tauto. }\n       tauto. } Qed. \n\n\n\nEnd Largest_members.\n\n\nSection More_FPO.\n   Variable U: Type.\n\n   Ltac apply_equal:= (apply Extensionality_Ensembles; unfold Same_set; split).\n   Set Implicit Arguments. \n  \n   Inductive Is_a_smallest_chain_cover (P: FPO U) (scover: Ensemble (Ensemble U)): Prop:=\n    smallest_cover_cond: (Is_a_chain_cover P scover) ->  \n                        ( forall (cover: Ensemble (Ensemble U))(sn n: nat),\n                           (Is_a_chain_cover P cover /\\ cardinal _ scover sn /\\\n                           cardinal _ cover n) -> (sn <=n) ) ->\n                        Is_a_smallest_chain_cover P scover.\n   Lemma Chain_cover_included_in_PC: forall (P: FPO U) (cv: Ensemble (Ensemble U)),\n       Is_a_chain_cover P cv -> Included _ cv (Power_set _ (Carrier_of _ P)).\n   Proof. { intros. unfold Included. intros. Print Power_set.\n          apply  Definition_of_Power_set. apply H. auto. } Qed. \n\n   \n   Lemma Exists_smallest_chain_cover: forall (P: FPO U), exists cover: Ensemble (Ensemble U),\n         Is_a_smallest_chain_cover P cover.\n   Proof.  { intros.\n         pose (C:= Carrier_of _ P).\n         pose (E:= fun (e : Ensemble( Ensemble U)) => Is_a_chain_cover P e).\n         pose (PC:= Power_set _ C). \n       assert (H_Finite: Finite _ E).\n       { assert (H: Included _ E (Power_set _ PC) ).\n         { unfold E. unfold Included.  unfold In.\n           intros cv H.  (* destruct H. *)  unfold PC.\n           apply Definition_of_Power_set. unfold C.  apply Chain_cover_included_in_PC. tauto. } \n         apply Finite_downward_closed with (A:= Power_set _ PC).\n         apply Power_set_finite.  unfold PC. apply Power_set_finite.\n         unfold C. apply FPO_cond. tauto. } \n       \n       assert (All_Finite: forall e: Ensemble (Ensemble U), In _ E e -> Finite _ e).\n       { intros cv H.\n         assert (H0: Included _ cv PC).\n         { unfold E in H. unfold In in H. unfold PC. unfold C.\n           apply Chain_cover_included_in_PC. apply H. } \n         apply Finite_downward_closed with (A:= PC). unfold PC.\n         apply Power_set_finite. apply FPO_cond. auto. }\n\n       assert (Inhabited_E: Inhabited _ E).\n       { elim Chain_cover_exists with (FP:=P). intro cv. intro.\n         eapply Inhabited_intro with (x:= cv).\n         unfold In. unfold E. auto.  }\n       \n       assert (H: exists cv_min: Ensemble (Ensemble U), Is_smallest_set E cv_min).\n       { apply Smallest_set_exists.  auto. auto.  auto. }\n\n       destruct H as [cv_min H]. destruct H.\n       assert (H1: exists m: nat, cardinal _ cv_min m).\n       { apply finite_cardinal. auto. }\n       destruct H1  as [m H1].\n       exists cv_min. apply smallest_cover_cond.\n       { unfold In in H. unfold E in H. auto. }\n       { intros e1 n n1. intros. apply H0 with (e1:=e1) (n1:= n1). tauto. }  } Qed.\n\n    Lemma Union_over_cv_is_C: forall (P: FPO U) (cv: Ensemble (Ensemble U)),\n       Is_a_chain_cover P cv -> ( (Carrier_of _ P) = (Union_over cv)).\n    Proof. { intros. apply_equal.\n           { unfold Included. intros. unfold In. unfold Union_over. apply H. auto. }\n           { unfold Included. intros.  unfold In in H0. unfold Union_over in H0.\n             destruct H. destruct H0 as [e H0].\n             assert (Is_a_chain_in P e). apply H. tauto. apply H2. tauto.  } } Qed.\n\n    \n   Lemma Inhabited_chain_cover: forall (P: FPO U)(cv: Ensemble (Ensemble U)),\n       Is_a_chain_cover P cv -> Inhabited _ cv.\n   Proof. { intros. elim (classic (Inhabited _ cv)). tauto. \n          { intro.\n            assert (cv = Empty_set _ ). eapply Not_Inh_Empty. auto. \n            absurd (Inhabited _ (Carrier_of _ P)).\n            replace (Carrier_of _ P) with (Union_over cv).\n            replace (Union_over cv) with (Empty_set U ). intro. inversion H2.\n            inversion H3.\n            rewrite H1. symmetry. apply Union_over_empty. symmetry.\n            apply Union_over_cv_is_C. auto. Print PO. apply PO_cond1.  }  } Qed. \n\n   \n   Lemma exists_disjoint_cover: forall (P: FPO U) (m:nat),\n     (exists cv: Ensemble (Ensemble U), Is_a_smallest_chain_cover P cv /\\ cardinal _ cv m )->\n    (exists cv': Ensemble (Ensemble U), Is_a_disjoint_cover P cv' /\\ cardinal _ cv' m).\n   Proof. {  intros P0 m. generalize P0 as P. clear P0.\n           induction m.\n           (* Base case when cv is empty . It is not possible. *)\n           { intros. destruct H as [cv H]. destruct H.\n             assert (0>0). eapply inh_card_gt_O with (X:=cv).\n             eapply Inhabited_chain_cover. apply H. auto. inversion H1. } \n           \n           (* Induction Step *) \n           intros. destruct H as [cv H].   destruct H.\n           assert (H1: Is_a_chain_cover P cv). apply H.\n           apply cardinal_invert with (p:= (S m)) in H0  as H2. \n          \n           destruct H2 as [cv0 H2]. destruct H2 as [c H2].\n           assert (H_cv:  cv = Add (Ensemble U) cv0 c ). tauto.\n           assert (T0: In _ cv c).\n           { rewrite H_cv.  auto with sets. } \n           assert (T1: Is_a_chain_in P c ).\n           { apply H1. auto. }  \n           assert (T2: Included _ c (Carrier_of _ P)).\n           { apply T1. } \n          \n           destruct H2. destruct H3. \n           pose (C:= Carrier_of _ P).\n           assert (H5: C = Union_over cv).\n           { unfold C. apply Union_over_cv_is_C. auto. }\n           pose (C0:= Union_over cv0).\n           assert (H6: C = Union _ C0 c).\n           { rewrite H5. unfold C0. rewrite H2. eapply Union_over_P1. } \n\n           (* We break the proof in two cases *)\n           elim (classic (cv0= Empty_set _)).\n           (* CASE1: when C0 is empty. In this case chain cover cv has only one chain \n                     and hence it is minimal as well as disjoint *)\n           { intro.\n           \n           assert (H8: cv= Singleton _ c).\n           { rewrite H2. rewrite H7. auto with sets. }\n           exists cv. split.\n           { unfold Is_a_disjoint_cover.  split. auto.\n             intros.  rewrite H8 in H9. destruct H9. destruct H9;destruct H10.\n             left. reflexivity. }\n           { auto. } } \n           \n           (* CASE2: when C0 is not empty. Then cv0 is the smallest chain cover. \n                    Then it must have a disjoint chain cover of same size as cv0 by IHn. \n                     we consider the chain c':= Setminus c C0. then Union {c'} cv0' will be the \n                     disjoint chain cover for the whole poset. *)\n           { intro. Print PO.\n             pose (R:= Rel_of _ P).\n             assert (Inh_cv0: Inhabited _ cv0).\n             { apply Not_Empty_Inh. auto. }\n             destruct Inh_cv0 as [e0 Inh_cv0].\n             \n             assert (H8: Inhabited _ C0).\n             { assert (T4: In _ cv e0).\n               { rewrite H2. unfold Add. apply Union_introl. auto. }\n               assert (T5: Inhabited _ e0).\n               { cut (Is_a_chain_in P e0 ).  intro. apply H8. apply H1. auto. }\n               destruct T5 as [x0 T5].\n               apply Inhabited_intro with (x:=x0). unfold C0.   unfold In.\n               unfold Union_over. exists e0;tauto. } \n             \n             pose (PO_P0:= {| Carrier_of := C0; Rel_of :=R; PO_cond1 := H8;\n                              PO_cond2 := PO_cond2 _ P |}). Print FPO.\n             \n             assert (H9:Finite _ C0).\n             { cut (Included _ C0 C). apply Finite_downward_closed.  apply FPO_cond.\n               rewrite H6. auto with sets. } \n             pose (P0:= {| PO_of:= PO_P0; FPO_cond:= H9 |} ).\n\n             assert (Fact: Included_in _ P P0).\n             { unfold Included_in. split.\n               simpl. replace (Carrier_of U P) with C.  rewrite H6.  auto with sets.\n               unfold C. reflexivity. simpl. unfold R. reflexivity. }\n\n             assert ( H10: Is_a_smallest_chain_cover P0 cv0).\n             (* otherwise cv cannot be Smallest Chain Cover of P *)\n             { Print Is_a_smallest_chain_cover.\n               assert (H11: Is_a_chain_cover P0 cv0). \n               { apply cover_cond.\n                 \n                 { intros. \n                   assert (T3: In _ cv e).\n                   { rewrite H_cv. unfold In. unfold Add. apply Union_introl. auto. }\n                   assert (T4: Is_a_chain_in P e).\n                   { destruct H. destruct H. apply H. auto. }\n                   apply Chain_remains2 with (P2:= P).\n                   auto.\n                   { simpl. unfold C0. apply Union_over1. auto. }\n                   auto. }\n                 { simpl. unfold C0. intros. destruct H10. exists x0; tauto. } }  \n                \n             assert (H12: (forall (cover : Ensemble (Ensemble U)) (sn n : nat),\n                           Is_a_chain_cover P0 cover /\\\n                           cardinal (Ensemble U) cv0 sn /\\ cardinal (Ensemble U) cover n ->\n                           sn <= n)).\n               { intros.\n                 assert (sn= m).\n                 { eapply cardinal_unicity with (X:= cv0);tauto. }\n                 rewrite H12 in H10. rewrite H12.\n                 elim (classic ( m<= n)).\n                 { tauto. }\n                 { intro.\n                   assert ( H14: ~ S m <= S n).\n                   { intro. apply H13. auto with arith. }\n                   destruct H10. destruct H15.\n                   destruct H.\n                   elim (classic (In _ cover c)).\n                   { intro.\n                     assert (H19: Is_a_chain_cover P cover).\n                     { apply cover_cond.\n                       { intros.\n                         assert (H20: Is_a_chain_in P0 e).\n                         { apply H10. auto. }\n                         unfold Is_a_chain_in. apply Chain_remains1 with (P1:= P0).\n                         auto.  auto. }\n                       { replace (Carrier_of U P) with C.  intros.\n                         rewrite H6 in H19. destruct H19. destruct H10.\n                         apply H20. simpl. auto.\n                         exists c. tauto. unfold C. reflexivity.  }  } \n                     assert (H20: S m <= n).\n                     { eapply H17 with (cover:= cover). tauto.  }\n                       auto with arith.   } \n                   { intro. pose (cover' := Add _ cover c).\n                     assert (H19: cardinal _ cover' (S n)).\n                     { apply card_add. auto. auto. }\n                     assert (H20: Is_a_chain_cover P cover').\n                     { apply cover_cond.\n                       { intros. unfold cover' in H20. destruct H20.\n                         { assert (Is_a_chain_in P0 x). apply H10. auto.\n                         apply Chain_remains1 with (P1:= P0).\n                         auto. auto. }\n                         { destruct H20. auto. }  }\n                       { replace (Carrier_of U P) with C.  intros. rewrite H6 in H20.\n                         destruct H20. destruct H10.\n                         assert ( exists e : Ensemble U, In (Ensemble U) cover e /\\ In U e x).\n                         { apply H21. simpl. auto. } destruct H22.\n                         exists x0. split. unfold cover'. unfold Add. apply Union_introl.\n                         apply H22. apply H22.  exists c. unfold cover'.\n                         unfold Add. split. apply Union_intror. auto with sets. tauto.\n                         unfold C. reflexivity.  }  } \n                     assert (H21: S m <= S n).\n                     { eapply H17 with (cover:= cover'). tauto. }\n                     contradiction.  }    }   } \n               \n                 apply smallest_cover_cond. auto. auto. \n             } \n\n             assert ( H11: exists cv0' : Ensemble (Ensemble U), Is_a_disjoint_cover P0 cv0' /\\\n                                                      cardinal (Ensemble U) cv0' m).\n             { apply IHm. exists cv0. tauto. }\n\n             destruct H11 as [cv0' H11]. destruct H11. \n\n             assert (H13: C0= Union_over cv0').\n             { replace C0 with (Carrier_of _ P0). eapply Union_over_cv_is_C. apply H11.\n               simpl. reflexivity. }\n             (* Lemma: Union_over_cv_is_C *)\n\n             pose (c' := Setminus _ c C0).\n             assert (Fact1:  c = Union _ c' (Intersection _ c C0) ).\n             { apply_equal.\n               { unfold c'. unfold Included.  intros.\n                 elim (classic (In _ C0 x)).\n                 { intro. apply Union_intror. auto with sets. }\n                 { intro. apply Union_introl. auto with sets. }  }\n               { unfold Included. intros. destruct H14. apply H14.\n                 destruct H14. apply H14. } } \n             assert (F0: Included _ c' c).\n             { unfold c'. apply Included_setminus. } \n             assert (H14:  ~ In (Ensemble U) cv0' c'). \n             { intro.\n               assert (H15: Included _ c' C0). (* since c' belongs to cv0' due to H14. *)\n               { rewrite H13. apply Union_over1. auto. }\n               assert (H16: Inhabited _ c'). (* since it is a chain in cv0' *)\n               { cut (Is_a_chain_in P0 c').  intro. apply H16. apply H11. auto. }\n               destruct H16 as [x' H16].\n               absurd (Disjoint _ c' C0).\n               { intro. destruct H17.\n                 assert ( In _ C0 x'). apply H15. auto. \n                 assert (In U (Intersection U c' C0) x'). auto with sets.\n                 absurd (In U (Intersection U c' C0) x'). apply H17. tauto.  }\n               { unfold c'. apply Disj_Setminus. }  }  \n              \n             assert (H15: forall x: Ensemble U, In _ cv0' x -> Disjoint _ x c').\n             { intro e. intro.\n               assert ( Included _ e C0).\n               { rewrite H13.  apply Union_over1. auto. } \n               apply Disj_comm. eapply Disj_set_inc_disj with (B:= C0).\n               unfold c'. apply Disj_Setminus. auto. } \n\n             assert (H16: Inhabited _ c').\n             (* otherwise cv0 will be smallest chain cover of P *)\n             {  elim (classic (Inhabited _ c')).\n                { tauto. }\n                { intro.\n                  assert (H17: Included _ c C0).\n                  {  rewrite Fact1. unfold Included.\n                     intros. destruct H17.\n                     { absurd (Inhabited U c'). auto. eapply Inhabited_intro. apply H17. }\n                     { Print Intersection. destruct H17. auto.  }  } \n                  assert (H18: Is_a_chain_cover P cv0).\n                  { apply cover_cond.\n                    { intros. apply Chain_remains1 with (P1:= P0). auto.  destruct H10.\n                      apply H10. auto. }\n                    { replace (Carrier_of U P) with C. replace C with C0. unfold C0.\n                      intros. unfold In in H18. unfold Union_over in H18. apply H18.\n                      rewrite H6. symmetry. apply Union_absorbs. auto. unfold C.\n                      reflexivity.  }  } \n                  assert (H19: S m <= m).\n                  { destruct H. apply H19 with (cover:= cv0) . tauto. }\n                  absurd(S m <= m). auto with arith. auto. } }  \n                  \n\n             \n\n             pose (cv' := Add _ cv0' c' ).\n             destruct H10 as [F1 H10]. destruct F1 as [F1 F2].\n             destruct H11 as [F3 H11]. destruct F3 as [F3 F4].\n\n             exists cv'. split. \n             { unfold Is_a_disjoint_cover.  split.\n               { apply cover_cond.\n                 { intros. unfold cv' in H17.  destruct H17.\n                  { assert (H18: Is_a_chain_in P0 x).\n                  { apply F3.  auto. }\n                  unfold Is_a_chain_in in H18.\n                  assert (H19: Is_a_chain_in P x ). \n                  { unfold Is_a_chain_in.\n                  split.\n                  { split.\n                    { cut (Included _ (Carrier_of U P0) (Carrier_of U P)).\n                  apply Inclusion_is_transitive.  tauto.  simpl.\n                  cut (Included U C0 C). unfold C. tauto. rewrite H6. auto with sets. } \n                    { tauto. }  }\n                  { simpl in H18. unfold R in H18. tauto. } }\n                  tauto. }\n                  { destruct H17.  cut (Is_a_chain_in P c).\n                    { intro.\n                    unfold Is_a_chain_in. split.   split.\n                    cut (Included _ c (Carrier_of U P)). apply Inclusion_is_transitive. auto.\n                    apply H17. auto. intros.\n                    assert (H19: Included _ (Couple _ x y) c).\n                    generalize F0. apply Inclusion_is_transitive. auto. apply H17. auto. }\n                    auto. } }\n                 { intros. replace (Carrier_of U P) with C in H17.\n                   { assert (H18: C= Union _ C0 c').\n                     { rewrite H6. unfold c'. apply Union_setminus.  }\n                     rewrite H18 in H17. destruct H17.\n                     { unfold cv'.\n                       assert (H19:  exists e : Ensemble U, In (Ensemble U) cv0' e /\\ In U e x).\n                       apply F4. apply H17. destruct H19 as [e H19]. exists e.\n                       split. unfold Add. apply Union_introl; tauto. tauto.  }\n                     { unfold cv'.  exists c'.  split. auto with sets. auto. } }  \n                   { unfold C. reflexivity. }   }   } \n               \n               { intros.  unfold cv' in H16. destruct H17.\n                 destruct H17; destruct H18.\n                 apply H11;tauto.\n                 destruct H18.  right. auto.\n                 destruct H17. right. cut (Disjoint _ x0 c').\n                 { intro.  destruct H17. Print Disjoint. apply  Disjoint_intro.\n                  cut (Intersection _ x0 c' = Intersection _ c' x0). intro.\n                  rewrite <- H19. apply H17. apply Intersection_commutative. }\n                 apply H15. auto. left. destruct H17; destruct H18. reflexivity. } } \n             unfold cv'. eapply card_add. auto. auto.     }            }   Qed. \n\n\n\n\n\n\n    \n  End More_FPO.\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/FPO_Facts2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.6909137897960219}}
{"text": "Require Import Streams.\nPrint Stream.\n\n(* take a look at Standard Library\nCoInductive Stream (a : Type) : Type :=\nCons : a -> Stream a -> Stream a\n.\n\nCoFixpoint from n := Cons n (from (n+1) ).\n*)\n\n\nRequire Import List.\n\nFixpoint take {a : Type} n (xs : Stream a) :=\n  match (n, xs) with\n  | (0, _) => nil\n  | (S n', Cons x xs) => x :: take n' xs\n  end.\n\nCoFixpoint from n := Cons n (from (n + 1) ).\n\nEval compute in take 10 (from 0).\nEval compute in from 0.\n\nCoFixpoint repeat {a : Type} (x : a) :=\n  Cons x (repeat x)\n.\n\nEval compute in take 10 (repeat 3).\n\n\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/21.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.6909137716593186}}
{"text": "Require Import Reals.\nRequire Import Lra.\n\nOpen Scope R_scope.\n\nLemma l1 : forall x y z : R, Rabs (x - z) <= Rabs (x - y) + Rabs (y - z).\nintros; split_Rabs; lra.\nQed.\n\nLemma l2 :\n forall x y : R, x < Rabs y -> y < 1 -> x >= 0 -> - y <= 1 -> Rabs x <= 1.\nintros.\nsplit_Rabs; lra.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/success/LraTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6909015509492475}}
{"text": "Theorem 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", "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/back_large.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6909015469700064}}
{"text": "Inductive 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.\n intros A x; elim x.\n apply Acc_intro.\n intros y Hsub; inversion Hsub.\n intros a t1 Hrec1 t2 Hrec2; apply Acc_intro.\n intros y Hsub; inversion Hsub; 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/gen-rec/SRC/btreewf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6908320959650693}}
{"text": "(****************************************************************************\n                                                                             \n          IEEE754  :  Zenum                                                  \n                                                                             \n          Laurent Thery                                                      \n                                                                             \n  *****************************************************************************\n  Simple functions to enumerate relative numbers *)\nRequire Export Faux.\nRequire Export Omega.\nRequire Export List.\n(* \n   Returns the list of relative numbers from z to z+n *)\n \nFixpoint mZlist_aux (p : Z) (n : nat) {struct n} : \n list Z :=\n  match n with\n  | O => p :: nil\n  | S n1 => p :: mZlist_aux (Zsucc p) n1\n  end.\n \nTheorem mZlist_aux_correct :\n forall (n : nat) (p q : Z),\n (p <= q)%Z -> (q <= p + Z_of_nat n)%Z -> In q (mZlist_aux p n).\nintros n; elim n; clear n; auto.\nintros p q; try rewrite <- Zplus_0_r_reverse.\nintros H' H'0; simpl in |- *; left.\napply Zle_antisym; auto.\nintros n H' p q H'0 H'1; case (Zle_lt_or_eq _ _ H'0); intros H'2.\nsimpl in |- *; right.\napply H'; auto with zarith.\nrewrite Zplus_succ_comm.\nrewrite <- inj_S; auto.\nsimpl in |- *; auto.\nQed.\n \nTheorem mZlist_aux_correct_rev1 :\n forall (n : nat) (p q : Z), In q (mZlist_aux p n) -> (p <= q)%Z.\nintros n; elim n; clear n; simpl in |- *; auto.\nintros p q H'; elim H'; auto with zarith.\nintros n H' p q H'0; elim H'0; auto with zarith.\nintros H'1; apply Zle_succ_le; auto with zarith.\nQed.\n \nTheorem mZlist_aux_correct_rev2 :\n forall (n : nat) (p q : Z),\n In q (mZlist_aux p n) -> (q <= p + Z_of_nat n)%Z.\nintros n; elim n; clear n; auto.\nintros p q H'; elim H'; auto with zarith.\nintros H'0; elim H'0.\nintros n H' p q H'0; elim H'0; auto with zarith.\nintros H'1; rewrite inj_S; rewrite <- Zplus_succ_comm; auto.\nQed.\n(* Return the list of of relative numbres from p to p+q if p=<q,\n   otherwise the empty list *)\n \nDefinition mZlist (p q : Z) : list Z :=\n  match (q - p)%Z with\n  | Z0 => p :: nil\n  | Zpos d => mZlist_aux p (nat_of_P d)\n  | Zneg _ => nil (A:=Z)\n  end.\n \nTheorem mZlist_correct :\n forall p q r : Z, (p <= r)%Z -> (r <= q)%Z -> In r (mZlist p q).\nintros p q r H' H'0; unfold mZlist in |- *; CaseEq (q - p)%Z;\n auto with zarith.\nintros H'1; rewrite (Zle_antisym r p); auto with datatypes.\nauto with zarith.\nintros p0 H'1; apply mZlist_aux_correct; auto.\nrewrite inject_nat_convert with (1 := H'1); auto with zarith.\nintros p0 H'1; absurd (p <= q)%Z; auto.\napply Zlt_not_le; auto.\napply Zlt_O_minus_lt; auto.\nreplace (p - q)%Z with (- (q - p))%Z; auto with zarith.\nrewrite H'1; simpl in |- *; auto with zarith.\nunfold Zlt in |- *; simpl in |- *; auto.\napply Zle_trans with (m := r); auto.\nQed.\n \nTheorem mZlist_correct_rev1 :\n forall p q r : Z, In r (mZlist p q) -> (p <= r)%Z.\nintros p q r; unfold mZlist in |- *; CaseEq (q - p)%Z.\nintros H' H'0; elim H'0; auto with zarith.\nintros H'1; elim H'1.\nintros p0 H' H'0.\napply mZlist_aux_correct_rev1 with (n := nat_of_P p0); auto.\nintros p0 H' H'0; elim H'0.\nQed.\n \nTheorem mZlist_correct_rev2 :\n forall p q r : Z, In r (mZlist p q) -> (r <= q)%Z.\nintros p q r; unfold mZlist in |- *; CaseEq (q - p)%Z.\nintros H' H'0; elim H'0; auto with zarith.\nintros H'1; elim H'1.\nintros p0 H' H'0.\nrewrite <- (Zplus_minus p q).\nrewrite <- inject_nat_convert with (1 := H').\napply mZlist_aux_correct_rev2; auto.\nintros p0 H' H'0; elim H'0.\nQed.\n(* Given two list returns the list of possible product of an element\n   of the first list with an element of the second list *)\n \nFixpoint mProd (A B C : Set) (l1 : list A) (l2 : list B) {struct l2} :\n list (A * B) :=\n  match l2 with\n  | nil => nil\n  | b :: l2' => map (fun a : A => (a, b)) l1 ++ mProd A B C l1 l2'\n  end.\n \nTheorem mProd_correct :\n forall (A B C : Set) (l1 : list A) (l2 : list B) (a : A) (b : B),\n In a l1 -> In b l2 -> In (a, b) (mProd A B C l1 l2).\nintros A B C l1 l2; elim l2; simpl in |- *; auto.\nintros a l H' a0 b H'0 H'1; elim H'1;\n [ intros H'2; rewrite <- H'2; clear H'1 | intros H'2; clear H'1 ];\n auto with datatypes.\napply in_or_app; left; auto with datatypes.\ngeneralize H'0; elim l1; simpl in |- *; auto with datatypes.\nintros a1 l0 H'1 H'3; elim H'3; clear H'3; intros H'4;\n [ rewrite <- H'4 | idtac ]; auto with datatypes.\nQed.\n \nTheorem mProd_correct_rev1 :\n forall (A B C : Set) (l1 : list A) (l2 : list B) (a : A) (b : B),\n In (a, b) (mProd A B C l1 l2) -> In a l1.\nintros A B C l1 l2; elim l2; simpl in |- *; auto.\nintros a H' H'0; elim H'0.\nintros a l H' a0 b H'0.\ncase (in_app_or _ _ _ H'0); auto with datatypes.\nelim l1; simpl in |- *; auto with datatypes.\nintros a1 l0 H'1 H'2; elim H'2; clear H'2; intros H'3;\n [ inversion H'3 | idtac ]; auto with datatypes.\nintros H'1; apply H' with (b := b); auto.\nQed.\n \nTheorem mProd_correct_rev2 :\n forall (A B C : Set) (l1 : list A) (l2 : list B) (a : A) (b : B),\n In (a, b) (mProd A B C l1 l2) -> In b l2.\nintros A B C l1 l2; elim l2; simpl in |- *; auto.\nintros a l H' a0 b H'0.\ncase (in_app_or _ _ _ H'0); auto with datatypes.\nelim l1; simpl in |- *; auto with datatypes.\nintros H'1; elim H'1; auto.\nintros a1 l0 H'1 H'2; elim H'2; clear H'2; intros H'3;\n [ inversion H'3 | idtac ]; auto with datatypes.\nintros H'1; right; apply H' with (a := a0); auto.\nQed.\n \nTheorem in_map_inv :\n forall (A B : Set) (f : A -> B) (l : list A) (x : A),\n (forall a b : A, f a = f b -> a = b) -> In (f x) (map f l) -> In x l.\nintros A B f l; elim l; simpl in |- *; auto.\nintros a l0 H' x H'0 H'1; elim H'1; clear H'1; intros H'2; auto.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "float", "sha": "b3bfbd67f7be553f169a5b257a848ea13654bbb3", "save_path": "github-repos/coq/coq-contribs-float", "path": "github-repos/coq/coq-contribs-float/float-b3bfbd67f7be553f169a5b257a848ea13654bbb3/Zenum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6908320913845123}}
{"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 Rdefinitions.\n\nFixpoint pow (r:R) (n:nat) : R :=\n  match n with\n    | O => 1\n    | S n => Rmult r (pow r n)\n  end.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Reals/Rpow_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6908320913755467}}
{"text": "(* Prime numbers *)\n\nSet Nested Proofs Allowed.\nRequire Import Utf8 Arith SetoidList Permutation.\nRequire Import Misc.\nImport List ListNotations.\n\nFixpoint prime_test cnt n d :=\n  match cnt with\n  | 0 => true\n  | S c =>\n      match n mod d with\n      | 0 => n <=? d\n      | S _ => prime_test c n (d + 1)\n      end\n  end.\n\nDefinition is_prime n :=\n  match n with\n  | 0 | 1 => false\n  | S (S c) => prime_test c n 2\n  end.\n\nDefinition prime p := is_prime p = true.\n\nTheorem prime_test_false_exists_div_iff : ∀ n k,\n  2 ≤ k\n  → (∀ d, 2 ≤ d < k → n mod d ≠ 0)\n  → prime_test (n - k) n k = false\n  ↔ ∃ a b : nat, 2 ≤ a ∧ 2 ≤ b ∧ n = a * b.\nProof.\nintros * Hk Hd.\nsplit.\n-intros Hp.\n remember (n - k) as cnt eqn:Hcnt; symmetry in Hcnt.\n revert n k Hk Hd Hcnt Hp.\n induction cnt; intros; [ easy | ].\n cbn in Hp.\n remember (n mod k) as m eqn:Hm; symmetry in Hm.\n destruct m. {\n   destruct k; [ easy | ].\n   apply Nat.mod_divides in Hm; [ | easy ].\n   destruct Hm as (m, Hm).\n   destruct m; [ now rewrite Hm, Nat.mul_0_r in Hcnt | ].\n   destruct k; [ flia Hk | ].\n   destruct m. {\n     now rewrite Hm, Nat.mul_1_r, Nat.sub_diag in Hcnt.\n   }\n   exists (S (S k)), (S (S m)).\n   rewrite Hm.\n   replace (S (S k) * S (S m)) with (S (S k) + k * m + k + 2 * m + 2) by flia.\n   split; [ flia | ].\n   split; [ flia | easy ].\n }\n destruct n; [ flia Hcnt | ].\n apply (IHcnt (S n) (k + 1)); [ flia Hk | | flia Hcnt | easy ].\n intros d Hdk.\n destruct (Nat.eq_dec d k) as [Hdk1| Hdk1]. {\n   now intros H; rewrite <- Hdk1, H in Hm.\n }\n apply Hd; flia Hdk Hdk1.\n-intros (a & b & Han & Hbn & Hnab).\n remember (n - k) as cnt eqn:Hcnt; symmetry in Hcnt.\n revert n a b k Hk Hd Hcnt Han Hbn Hnab.\n induction cnt; intros. {\n   specialize (Hd a) as H1.\n   assert (H : 2 ≤ a < k). {\n     split. {\n       destruct a; [ flia Hnab Han | ].\n       destruct a; [ flia Hnab Han Hbn | flia ].\n     }\n     rewrite Hnab in Hcnt.\n     apply Nat.sub_0_le in Hcnt.\n     apply (Nat.lt_le_trans _ (a * b)); [ | easy ].\n     destruct a; [ flia Han | ].\n     destruct b; [ flia Hbn | ].\n     destruct b; [ flia Hbn | flia ].\n   }\n   specialize (H1 H).\n   exfalso; apply H1; rewrite Hnab, Nat.mul_comm.\n   apply Nat.mod_mul; flia H.\n }\n cbn.\n remember (n mod k) as m eqn:Hm; symmetry in Hm.\n destruct m; [ apply Nat.leb_gt; flia Hcnt | ].\n apply (IHcnt _ a b); [ flia Hk | | flia Hcnt | easy | easy | easy ].\n intros d (H2d, Hdk).\n destruct (Nat.eq_dec d k) as [Hdk1| Hdk1]. {\n   now intros H; rewrite <- Hdk1, H in Hm.\n }\n apply Hd.\n flia H2d Hdk Hdk1.\nQed.\n\nTheorem not_prime_decomp : ∀ n, 2 ≤ n →\n  ¬ prime n\n  → ∃ a b, 2 ≤ a ∧ 2 ≤ b ∧ n = a * b.\nProof.\nintros n Hn Hp.\napply Bool.not_true_iff_false in Hp.\nunfold is_prime in Hp.\ndestruct n; [ flia Hn | ].\ndestruct n; [ flia Hn | ].\nreplace n with (S (S n) - 2) in Hp at 1 by flia.\napply (prime_test_false_exists_div_iff _ 2); [ easy | | easy ].\nintros * H; flia H.\nQed.\n\nTheorem not_prime_exists_div : ∀ n, 2 ≤ n →\n  ¬ prime n\n  → ∃ a, 2 ≤ a < n ∧ Nat.divide a n.\nProof.\nintros n Hn Hp.\nspecialize (not_prime_decomp n Hn Hp) as (a & b & Ha & Hb & Hab).\nexists a.\nsplit; [ | now rewrite Hab; apply Nat.divide_mul_l ].\nsplit; [ easy | ].\nrewrite Hab, Nat.mul_comm.\ndestruct a; [ flia Ha | ].\ndestruct b; [ flia Hb | ].\ndestruct b; [ flia Hb | flia ].\nQed.\n\nTheorem exist_prime_divisor : ∀ n, 2 ≤ n →\n  ∃ d, prime d ∧ Nat.divide d n.\nProof.\nintros * Hn.\ninduction n as (n, IHn) using (well_founded_ind lt_wf).\nremember (is_prime n) as b eqn:Hb; symmetry in Hb.\ndestruct b; [ now exists n | ].\napply Bool.not_true_iff_false in Hb.\nspecialize (not_prime_exists_div n Hn Hb) as (a & Han & Hd).\nspecialize (IHn a (proj2 Han) (proj1 Han)) as H1.\ndestruct H1 as (d & Hpd & Hda).\nexists d.\nsplit; [ easy | ].\nnow transitivity a.\nQed.\n\nTheorem Nat_le_divides_fact : ∀ n d, d ≤ n → Nat.divide (fact d) (fact n).\nProof.\nintros * Hdn.\nreplace d with (n - (n - d)) by flia Hdn.\napply Nat_divide_fact_fact.\nQed.\n\nTheorem Nat_fact_divides_small : ∀ n d,\n  1 ≤ d ≤ n\n  → fact n = fact n / d * d.\nProof.\nintros * (Hd, Hdn).\nspecialize (Nat_le_divides_fact n d Hdn) as H1.\ndestruct H1 as (c, Hc).\nrewrite Hc at 2.\ndestruct d; [ easy | ].\nrewrite Nat_fact_succ.\nrewrite (Nat.mul_comm (S d)).\nrewrite Nat.mul_assoc.\nrewrite Nat.div_mul; [ | easy ].\nrewrite Hc, Nat_fact_succ.\nnow rewrite Nat.mul_assoc, Nat.mul_shuffle0.\nQed.\n\nLemma next_prime_bounded : ∀ n, ∃ m, n < m ≤ fact n + 1 ∧ prime m.\nProof.\nintros.\nspecialize (exist_prime_divisor (fact n + 1)) as H1.\nassert (H : 2 ≤ fact n + 1). {\n  clear.\n  induction n; [ easy | ].\n  rewrite Nat_fact_succ.\n  apply (Nat.le_trans _ (fact n + 1)); [ easy | ].\n  apply Nat.add_le_mono_r.\n  cbn; flia.\n}\nspecialize (H1 H); clear H.\ndestruct H1 as (d & Hd & Hdn).\nexists d.\nsplit; [ | easy ].\nsplit.\n-destruct (lt_dec n d) as [Hnd| Hnd]; [ easy | ].\n apply Nat.nlt_ge in Hnd; exfalso.\n assert (Ht : Nat.divide d (fact n)). {\n   exists (fact n / d).\n   apply Nat_fact_divides_small.\n   split; [ | easy ].\n   destruct d; [ easy | flia ].\n }\n destruct Hdn as (z, Hz).\n destruct Ht as (t, Ht).\n rewrite Ht in Hz.\n apply Nat.add_sub_eq_l in Hz.\n rewrite <- Nat.mul_sub_distr_r in Hz.\n apply Nat.eq_mul_1 in Hz.\n now destruct Hz as (Hz, H); subst d.\n-apply Nat.divide_pos_le; [ flia | easy ].\nQed.\n\nTheorem infinitely_many_primes : ∀ n, ∃ m, m > n ∧ prime m.\nProof.\nintros.\nspecialize (next_prime_bounded n) as (m & (Hnm & _) & Hp).\nnow exists m.\nQed.\n\nLemma prime_test_mod_ne_0 : ∀ n k,\n  2 ≤ n\n  → prime_test (n - k) n k = true\n  → ∀ d, k ≤ d < n → n mod d ≠ 0.\nProof.\nintros * Hn Hp d Hd.\nremember (n - k) as cnt eqn:Hcnt; symmetry in Hcnt.\nrevert n k d Hn Hcnt Hp Hd.\ninduction cnt; intros; [ flia Hcnt Hd | ].\ncbn in Hp.\nremember (n mod k) as m eqn:Hm; symmetry in Hm.\ndestruct m; [ apply Nat.leb_le in Hp; flia Hp Hd | ].\ndestruct n; [ flia Hcnt | ].\ndestruct (Nat.eq_dec k d) as [Hkd| Hkd]. {\n  now intros H; rewrite Hkd, H in Hm.\n}\napply (IHcnt (S n) (k + 1)); [ easy | flia Hcnt | easy | flia Hd Hkd ].\nQed.\n\nTheorem prime_only_divisors : ∀ p,\n  prime p → ∀ a, Nat.divide a p → a = 1 ∨ a = p.\nProof.\nintros * Hp a * Hap.\ndestruct (lt_dec p 2) as [Hp2| Hp2]. {\n  destruct p; [ easy | ].\n  destruct p; [ easy | flia Hp2 ].\n}\napply Nat.nlt_ge in Hp2.\ndestruct (zerop a) as [Ha| Ha]. {\n  subst a.\n  apply Nat.divide_0_l in Hap; flia Hap Hp2.\n}\napply Nat.neq_0_lt_0 in Ha.\napply Nat.mod_divide in Hap; [ | easy ].\napply Nat.mod_divides in Hap; [ | easy ].\ndestruct Hap as (k, Hk).\nsymmetry in Hk.\ndestruct p; [ easy | ].\ndestruct p; [ easy | ].\nspecialize (prime_test_mod_ne_0 (S (S p)) 2 Hp2) as H1.\nreplace (S (S p) - 2) with p in H1 by flia.\nspecialize (H1 Hp).\ndestruct k; [ now rewrite Nat.mul_0_r in Hk | ].\ndestruct k; [ now rewrite Nat.mul_1_r in Hk; right | left ].\ndestruct a; [ easy | ].\ndestruct a; [ easy | exfalso ].\nspecialize (H1 (S (S k))) as H2.\nassert (H : 2 ≤ S (S k) < S (S p)). {\n  split; [ flia Hp2 | flia Hk ].\n}\nspecialize (H2 H); clear H.\napply H2; rewrite <- Hk.\nnow rewrite Nat.mod_mul.\nQed.\n\nTheorem prime_prop : ∀ p, prime p → ∀ i, 2 ≤ i ≤ p - 1 → ¬ Nat.divide i p.\nProof.\nintros * Hp i Hi Hdiv.\nspecialize (prime_only_divisors p Hp i Hdiv) as H1.\nflia Hi H1.\nQed.\n\nTheorem eq_primes_gcd_1 : ∀ a b,\n  prime a → prime b → a ≠ b → Nat.gcd a b = 1.\nProof.\nintros p q Hp Hq Hpq.\nspecialize (prime_only_divisors _ Hp) as Hpp.\nspecialize (prime_only_divisors _ Hq) as Hqp.\nspecialize (Hpp (Nat.gcd p q) (Nat.gcd_divide_l _ _)) as H1.\nspecialize (Hqp (Nat.gcd p q) (Nat.gcd_divide_r _ _)) as H2.\ndestruct H1 as [H1| H1]; [ easy | ].\ndestruct H2 as [H2| H2]; [ easy | ].\nnow rewrite H1 in H2.\nQed.\n\nFixpoint prime_decomp_aux cnt n d :=\n  match cnt with\n  | 0 => []\n  | S c =>\n      match n mod d with\n      | 0 => d :: prime_decomp_aux c (n / d) d\n      | _ => prime_decomp_aux c n (S d)\n      end\n  end.\n\nDefinition prime_decomp n :=\n  match n with\n  | 0 | 1 => []\n  | _ => prime_decomp_aux n n 2\n  end.\n\nLemma prime_decomp_aux_of_prime_test : ∀ n k,\n  2 ≤ n\n  → prime_test (n - 2) (k + n) (k + 2) = true\n  → prime_decomp_aux n (k + n) (k + 2) = [k + n].\nProof.\nintros * Hn Hpn.\ndestruct n; [ easy | ].\ndestruct n; [ flia Hn | clear Hn ].\nreplace (S (S n) - 2) with n in Hpn by flia.\nrevert k Hpn.\ninduction n; intros. {\n  cbn - [ \"/\" \"mod\" ].\n  rewrite Nat.mod_same; [ | flia ].\n  rewrite Nat.div_same; [ | flia ].\n  rewrite Nat.mod_1_l; [ easy | flia ].\n}\nremember (S (S n)) as sn.\ncbn - [ \"/\" \"mod\" ].\ncbn - [ \"/\" \"mod\" ] in Hpn.\nremember ((k + S sn) mod (k + 2)) as b eqn:Hb; symmetry in Hb.\ndestruct b; [ apply Nat.leb_le in Hpn; flia Heqsn Hpn | ].\nreplace (k + S sn) with (S k + sn) in Hpn |-* by flia.\nreplace (S (k + 2)) with (S k + 2) by flia.\nreplace (k + 2 + 1) with (S k + 2) in Hpn by flia.\nnow apply IHn.\nQed.\n\nTheorem prime_neq_0 : ∀ p, prime p → p ≠ 0.\nProof. now intros * Hp H; subst p. Qed.\n\nTheorem prime_ge_2 : ∀ n, prime n → 2 ≤ n.\nProof.\nintros * Hp.\ndestruct n; [ easy | ].\ndestruct n; [ easy | flia ].\nQed.\n\nTheorem prime_decomp_of_prime : ∀ n, prime n → prime_decomp n = [n].\nProof.\nintros * Hpn.\nspecialize (prime_ge_2 _ Hpn) as Hn.\nunfold prime, is_prime in Hpn.\nunfold prime_decomp.\nreplace n with (S (S (n - 2))) in Hpn at 1 by flia Hn.\nreplace n with (S (S (n - 2))) at 1 by flia Hn.\nreplace n with (0 + n) in Hpn at 2 by flia.\nreplace 2 with (0 + 2) in Hpn at 2 by flia.\nnow apply prime_decomp_aux_of_prime_test in Hpn; [ | easy ].\nQed.\n\nLemma prime_decomp_aux_le : ∀ cnt n d d',\n  d ≤ d' → HdRel le d (prime_decomp_aux cnt n d').\nProof.\nintros * Hdd.\nrevert n d d' Hdd.\ninduction cnt; intros; [ constructor | cbn ].\ndestruct (n mod d') as [| Hnd]; [ now constructor | ].\napply IHcnt, (le_trans _ d'); [ easy | ].\napply Nat.le_succ_diag_r.\nQed.\n\nLemma Sorted_prime_decomp_aux : ∀ cnt n d,\n  Sorted le (prime_decomp_aux cnt n d).\nProof.\nintros.\nrevert n d.\ninduction cnt; intros; [ constructor | cbn ].\nremember (n mod d) as b eqn:Hb; symmetry in Hb.\ndestruct b. {\n  constructor; [ apply IHcnt | ].\n  now apply prime_decomp_aux_le.\n}\napply IHcnt.\nQed.\n\nTheorem Sorted_prime_decomp : ∀ n, Sorted le (prime_decomp n).\nProof.\nintros.\ndestruct n; [ constructor | ].\ncbn - [ \"/\" \"mod\" ].\ndestruct n; [ constructor | ].\ndestruct (S (S n) mod 2) as [| b]. {\n  constructor; [ apply Sorted_prime_decomp_aux | ].\n  now apply prime_decomp_aux_le.\n}\napply Sorted_prime_decomp_aux.\nQed.\n\nLemma in_prime_decomp_aux_le : ∀ cnt n d d',\n  d' ∈ prime_decomp_aux cnt n d\n  → d ≤ d'.\nProof.\nintros * Hd'.\nrevert n d d' Hd'.\ninduction cnt; intros; [ easy | ].\ncbn in Hd'.\ndestruct (n mod d) as [| b]. {\n  destruct Hd' as [Hd'| Hd']; [ now subst d' | ].\n  now apply (IHcnt (n / d)).\n}\ntransitivity (S d); [ apply Nat.le_succ_diag_r | now apply (IHcnt n) ].\nQed.\n\nTheorem in_prime_decomp_ge_2 : ∀ n d,\n  d ∈ prime_decomp n\n  → 2 ≤ d.\nProof.\nintros * Hd.\ndestruct n; [ easy | ].\ndestruct n; [ easy | ].\nunfold prime_decomp in Hd.\neapply in_prime_decomp_aux_le.\napply Hd.\nQed.\n\nTheorem prime_decomp_param_ge_2 : ∀ n d,\n  d ∈ prime_decomp n\n  → 2 ≤ n.\nProof.\nintros * Hd.\ndestruct n; [ easy | ].\ndestruct n; [ easy | flia ].\nQed.\n\nLemma in_prime_decomp_aux_divide : ∀ cnt n d p,\n  d ≠ 0\n  → p ∈ prime_decomp_aux cnt n d\n  → Nat.divide p n.\nProof.\nintros * Hdz Hp.\nspecialize (in_prime_decomp_aux_le cnt n d _ Hp) as Hdp.\nassert (Hpz : p ≠ 0) by flia Hdz Hdp.\nmove Hpz before Hdz.\nrevert n d p Hdz Hp Hpz Hdp.\ninduction cnt; intros; [ easy | ].\ncbn in Hp.\nremember (n mod d) as b eqn:Hb; symmetry in Hb.\ndestruct b. {\n  destruct Hp as [Hp| Hp]; [ now subst d; apply Nat.mod_divide | ].\n  apply (Nat.divide_trans _ (n / d)). 2: {\n    apply Nat.mod_divides in Hb; [ | easy ].\n    destruct Hb as (c, Hc).\n    rewrite Hc, Nat.mul_comm, Nat.div_mul; [ | easy ].\n    apply Nat.divide_factor_l.\n  }\n  now apply (IHcnt _ d).\n}\nspecialize (in_prime_decomp_aux_le _ _ _ _ Hp) as H1.\nnow apply (IHcnt _ (S d)).\nQed.\n\nTheorem in_prime_decomp_divide : ∀ n d,\n  d ∈ prime_decomp n → Nat.divide d n.\nProof.\nintros * Hd.\nassert (H2n : 2 ≤ n). {\n  destruct n; [ easy | ].\n  destruct n; [ easy | flia ].\n}\nspecialize (in_prime_decomp_ge_2 n d Hd) as H2d.\nmove Hd at bottom.\nunfold prime_decomp in Hd.\nreplace n with (S (S (n - 2))) in Hd by flia H2n.\nreplace (S (S (n - 2))) with n in Hd by flia H2n.\nnow apply in_prime_decomp_aux_divide in Hd.\nQed.\n\nTheorem in_prime_decomp_le : ∀ n d : nat, d ∈ prime_decomp n → d ≤ n.\nProof.\nintros * Hd.\napply Nat.divide_pos_le; [ | now apply in_prime_decomp_divide ].\ndestruct n; [ easy | flia ].\nQed.\n\nLemma prime_decomp_aux_at_1 : ∀ cnt d, 2 ≤ d → prime_decomp_aux cnt 1 d = [].\nProof.\nintros * H2d.\ndestruct d; [ flia H2d | ].\ndestruct d; [ flia H2d | clear H2d ].\nrevert d.\ninduction cnt; intros; [ easy | cbn ].\ndestruct d; [ apply IHcnt | ].\nreplace (S d - d) with 1 by flia.\napply IHcnt.\nQed.\n\nLemma prime_decomp_aux_more_iter : ∀ k cnt n d,\n  2 ≤ n\n  → 2 ≤ d\n  → n + 2 ≤ cnt + d\n  → prime_decomp_aux cnt n d = prime_decomp_aux (cnt + k) n d.\nProof.\nintros * H2n H2d Hnc.\nrevert n k d H2n H2d Hnc.\ninduction cnt; intros. {\n  cbn in Hnc; cbn.\n  revert d H2d Hnc.\n  induction k; intros; [ easy | cbn ].\n  rewrite Nat.mod_small; [ | flia Hnc ].\n  destruct n; [ flia H2n | ].\n  apply IHk; flia Hnc.\n}\ncbn - [ \"/\" \"mod\" ].\nremember (n mod d) as b eqn:Hb; symmetry in Hb.\ndestruct b. {\n  f_equal.\n  apply Nat.mod_divides in Hb; [ | flia H2d ].\n  destruct Hb as (b, Hb); rewrite Nat.mul_comm in Hb.\n  rewrite Hb, Nat.div_mul; [ | flia H2d ].\n  destruct (le_dec 2 b) as [H2b| H2b]. {\n    apply IHcnt; [ easy | easy | ].\n    transitivity (n + 1); [ | flia H2n Hnc ].\n    rewrite Hb.\n    destruct b; [ flia H2n Hb | ].\n    destruct d; [ easy | ].\n    destruct d; [ flia H2d | ].\n    cbn; rewrite Nat.mul_comm; cbn.\n    flia.\n  }\n  apply Nat.nle_gt in H2b.\n  destruct b; [ cbn in Hb; subst n; flia H2n | ].\n  destruct b; [ | flia H2b ].\n  rewrite prime_decomp_aux_at_1; [ | easy ].\n  now rewrite prime_decomp_aux_at_1.\n}\napply IHcnt; [ easy | | flia Hnc ].\nflia H2d Hnc.\nQed.\n\nLemma prime_test_more_iter : ∀ k cnt n d,\n  2 ≤ n\n  → n ≤ cnt + d\n  → prime_test cnt n d = prime_test (cnt + k) n d.\nProof.\nintros * H2n Hnc.\nrevert n k d H2n Hnc.\ninduction cnt; intros. {\n  cbn in Hnc; cbn.\n  revert d Hnc.\n  induction k; intros; [ easy | cbn ].\n  remember (n mod d) as b eqn:Hb; symmetry in Hb.\n  destruct b; [ now symmetry; apply Nat.leb_le | ].\n  destruct n; [ flia H2n | ].\n  apply IHk; flia Hnc.\n}\ncbn - [ \"/\" \"mod\" ].\nremember (n mod d) as b eqn:Hb; symmetry in Hb.\ndestruct b; [ easy | ].\napply IHcnt; [ easy | flia Hnc ].\nQed.\n\nLemma hd_prime_decomp_aux_ge : ∀ cnt n d,\n  2 ≤ d\n  → 2 ≤ hd 2 (prime_decomp_aux cnt n d).\nProof.\nintros * H2d.\nrevert d H2d.\ninduction cnt; intros; [ easy | cbn ].\nremember (n mod d) as b eqn:Hb; symmetry in Hb.\ndestruct b; [ easy | ].\napply IHcnt; flia H2d.\nQed.\n\nLemma prev_not_div_prime_test_true : ∀ cnt n d,\n  2 ≤ n\n  → 2 ≤ d\n  → n ≤ cnt + d\n  → (∀ e, 2 ≤ e < n → n mod e ≠ 0)\n  → prime_test cnt n d = true.\nProof.\nintros * H2n H2d Hcnt Hn.\nrevert n d H2n H2d Hcnt Hn.\ninduction cnt; intros; [ easy | cbn ].\nremember (n mod d) as b1 eqn:Hb1; symmetry in Hb1.\ndestruct b1. {\n  apply Nat.leb_le.\n  apply Nat.mod_divides in Hb1; [ | flia H2d ].\n  destruct Hb1 as (b1, Hb1).\n  destruct b1; [ flia H2d Hb1 | ].\n  destruct b1; [ flia Hb1 | ].\n  specialize (Hn (S (S b1))) as H1.\n  assert (H : 2 ≤ S (S b1) < n). {\n    split; [ flia | ].\n    rewrite Hb1; remember (S (S b1)) as b.\n    destruct d; [ flia H2d | cbn ].\n    destruct d; [ flia H2d | flia Heqb ].\n  }\n  specialize (H1 H).\n  exfalso; apply H1; clear H1.\n  rewrite Hb1.\n  now apply Nat.mod_mul.\n}\napply IHcnt; [ easy | flia H2d | flia Hcnt | easy ].\nQed.\n\nLemma hd_prime_decomp_aux_prime_test_true : ∀ cnt n b d,\n  2 ≤ n\n  → 2 ≤ d\n  → n + 2 ≤ cnt + d\n  → (∀ e : nat, 2 ≤ e < d → n mod e ≠ 0)\n  → b = hd 2 (prime_decomp_aux cnt n d)\n  → prime_test (b - 2) b 2 = true.\nProof.\nintros * H2n H2d Hcnt Hnd Hb.\nrevert d H2d Hcnt Hnd Hb.\ninduction cnt; intros; [ now subst b | ].\ncbn - [ \"/\" \"mod\" ] in Hb.\nremember (n mod d) as b1 eqn:Hb1; symmetry in Hb1.\ndestruct b1. {\n  cbn in Hb; subst b.\n  apply Nat.mod_divides in Hb1; [ | flia H2d ].\n  destruct Hb1 as (b1, Hb1).\n  destruct b1; [ flia H2n Hb1 | ].\n  destruct b1. {\n    rewrite Nat.mul_1_r in Hb1; subst n.\n    apply prev_not_div_prime_test_true; [ easy | easy | flia H2d | easy ].\n  }\n  apply prev_not_div_prime_test_true; [ easy | easy | flia H2n | ].\n  intros e He.\n  specialize (Hnd e He) as H1.\n  intros H2; apply H1; clear H1.\n  apply Nat.mod_divides in H2; [ | flia He ].\n  destruct H2 as (b2, Hb2); rewrite Nat.mul_comm in Hb2.\n  rewrite Hb1, Hb2, Nat.mul_shuffle0.\n  apply Nat.mod_mul; flia He.\n}\nassert (H : ∀ e, 2 ≤ e < 1 + d → n mod e ≠ 0). {\n  intros e He.\n  destruct (Nat.eq_dec e d) as [Hed| Hed]. {\n    now subst e; intros H; rewrite H in Hb1.\n  }\n  apply Hnd; flia He Hed.\n}\nmove H before Hnd; clear Hnd; rename H into Hnd.\nclear b1 Hb1.\nreplace (S cnt + d) with (cnt + S d) in Hcnt by flia.\napply (IHcnt (S d)); [ flia H2d | easy | easy | easy ].\nQed.\n\nTheorem first_in_decomp_is_prime : ∀ n, prime (List.hd 2 (prime_decomp n)).\nProof.\nintros.\nunfold is_prime, prime_decomp.\ndestruct n; [ easy | ].\ndestruct n; [ easy | ].\nassert (H2n : 2 ≤ S (S n)) by flia.\nremember (S (S n)) as n'.\nclear n Heqn'; rename n' into n.\nspecialize (hd_prime_decomp_aux_ge n n 2 (le_refl _)) as H2b.\nunfold prime, is_prime.\nremember (hd 2 (prime_decomp_aux n n 2)) as b eqn:Hb.\nmove b before n; move H2b before H2n.\nreplace b with (S (S (b - 2))) by flia H2b.\nreplace (S (S (b - 2))) with b by flia H2b.\napply (hd_prime_decomp_aux_prime_test_true n n b 2);\n  [ easy | easy | easy | | easy ].\nintros e He; flia He.\nQed.\n\nLemma prime_decomp_aux_not_nil : ∀ cnt n d,\n  2 ≤ n\n  → 2 ≤ d\n  → n + 2 ≤ cnt + d\n  → (∀ e : nat, 2 ≤ e < d → n mod e ≠ 0)\n  → prime_decomp_aux cnt n d ≠ [].\nProof.\nintros * H2n H2d Hcnt Hnd.\nrevert d H2d Hcnt Hnd.\ninduction cnt; intros. {\n  assert (H : 2 ≤ n < d) by flia H2n Hcnt.\n  specialize (Hnd n H); clear H.\n  rewrite Nat.mod_same in Hnd; [ easy | flia H2n ].\n}\ncbn - [ \"/\" \"mod\" ].\nremember (n mod d) as b eqn:Hb; symmetry in Hb.\ndestruct b; [ easy | ].\nrewrite Nat.add_succ_comm in Hcnt.\napply IHcnt; [ flia H2d | easy | ].\nintros e He.\ndestruct (Nat.eq_dec e d) as [Hed| Hed]. {\n  now subst e; intros H; rewrite H in Hb.\n}\napply Hnd; flia He Hed.\nQed.\n\nTheorem prime_decomp_nil_iff : ∀ n, prime_decomp n = [] ↔ n = 0 ∨ n = 1.\nProof.\nintros.\nsplit.\n-intros Hn.\n unfold prime_decomp in Hn.\n destruct n; [ now left | ].\n destruct n; [ now right | exfalso ].\n revert Hn.\n apply prime_decomp_aux_not_nil; [ flia | easy | easy | ].\n intros e He; flia He.\n-now intros [Hn| Hn]; subst n.\nQed.\n\nLemma prime_decomp_aux_cons_nil : ∀ cnt n d l,\n  2 ≤ n\n  → 2 ≤ d\n  → n + 2 ≤ cnt + d\n  → (∀ e, 2 ≤ e < d → n mod e ≠ 0)\n  → prime_decomp_aux cnt n d = n :: l\n  → l = [].\nProof.\nintros * H2n H2d Hcnt Hdn Hnd.\nrevert d l H2d Hcnt Hdn Hnd.\ninduction cnt; intros; [ easy | ].\ncbn in Hnd.\nremember (n mod d) as b eqn:Hb; symmetry in Hb.\ndestruct b. {\n  injection Hnd; clear Hnd; intros Hl Hd; subst d.\n  rewrite Nat.div_same in Hl; [ | flia H2n ].\n  now rewrite prime_decomp_aux_at_1 in Hl.\n}\nrewrite Nat.add_succ_comm in Hcnt.\napply (IHcnt (S d)); [ flia H2d | easy | | easy ].\nintros e He.\ndestruct (Nat.eq_dec e d) as [Hed| Hed]. {\n  now subst e; intros H; rewrite H in Hb.\n}\napply Hdn; flia He Hed.\nQed.\n\nLemma prime_decomp_aux_cons : ∀ p b l n d cb cn,\n  2 ≤ n\n  → 2 ≤ b\n  → 2 ≤ d\n  → 2 ≤ p\n  → b + 2 ≤ cb + d\n  → n + 2 ≤ cn + d\n  → n * p = b\n  → prime_decomp_aux cb b d = p :: l\n  → prime_decomp_aux cn n d = l.\nProof.\nintros * H2n H2b H2d H2p Hcb Hcn Hb Hbp.\nrevert p b n d cn H2n H2b H2d H2p Hcb Hcn Hb Hbp.\ninduction cb; intros; [ easy | ].\ncbn in Hbp.\nremember (b mod d) as b1 eqn:Hb1; symmetry in Hb1.\ndestruct b1. {\n  injection Hbp; clear Hbp; intros Hl Hp; subst d.\n  rewrite <- Hb, Nat.div_mul in Hl; [ | flia H2b Hb ].\n  rewrite (prime_decomp_aux_more_iter cn) in Hl; [ | easy | easy | ]. 2: {\n    apply Nat.succ_le_mono.\n    replace (S (cb + p)) with (S cb + p) by flia.\n    transitivity (b + 2); [ | easy ].\n    replace (S (n + 2)) with (S n + 2) by flia.\n    apply Nat.add_le_mono_r.\n    rewrite <- Hb.\n    destruct p; [ flia H2p | ].\n    destruct p; [ flia H2p | ].\n    rewrite Nat.mul_comm; cbn.\n    destruct n; [ easy | flia ].\n  }\n  rewrite Nat.add_comm in Hl.\n  now rewrite (prime_decomp_aux_more_iter cb).\n}\nrewrite (prime_decomp_aux_more_iter 1); try easy.\nrewrite Nat.add_1_r; cbn.\nremember (n mod d) as b2 eqn:Hb2; symmetry in Hb2.\ndestruct b2. {\n  apply Nat.mod_divides in Hb2; [ | flia H2d ].\n  destruct Hb2 as (b2, Hb2).\n  rewrite <- Hb, Hb2 in Hb1.\n  rewrite <- Nat.mul_assoc, Nat.mul_comm in Hb1.\n  rewrite Nat.mod_mul in Hb1; [ easy | flia H2d ].\n}\nrewrite Nat.add_succ_comm in Hcb.\napply (IHcb p b); try easy; [ flia H2d | flia Hcn ].\nQed.\n\nTheorem prime_decomp_mul : ∀ n d l,\n  2 ≤ d\n  → prime_decomp (n * d) = d :: l\n  → prime_decomp n = l.\nProof.\nintros * H2d Hnd.\nunfold prime_decomp in Hnd.\nunfold prime_decomp.\ndestruct n; [ easy | ].\ndestruct n. {\n  rewrite Nat.mul_1_l in Hnd.\n  destruct d; [ easy | ].\n  cbn - [ \"/\" \"mod\" ] in Hnd.\n  destruct d; [ easy | ].\n  remember (S (S d)) as d'.\n  replace (S d) with (d' - 1) in Hnd by flia Heqd'.\n  clear d Heqd'; rename d' into d; move H2d after Hnd.\n  remember (d mod 2) as b eqn:Hb; symmetry in Hb.\n  destruct b. {\n    remember (prime_decomp_aux _ _ _) as x.\n    injection Hnd; clear Hnd; intros Hl Hd; subst x.\n    now subst d.\n  }\n  symmetry.\n  apply prime_decomp_aux_cons_nil in Hnd; [ easy | easy | flia | flia | ].\n  intros e He H.\n  replace e with 2 in H by flia He.\n  now rewrite H in Hb.\n}\nassert (H2n : 2 ≤ S (S n)) by flia.\nremember (S (S n)) as n'; clear n Heqn'; rename n' into n.\nremember (n * d) as b eqn:Hb; symmetry in Hb.\ndestruct b; [ easy | ].\ndestruct b; [ easy | ].\nassert (H2b : 2 ≤ S (S b)) by flia.\nremember (S (S b)) as b'; clear b Heqb'; rename b' into b.\nmove H2n after Hb; move H2b after Hb.\nnow apply (prime_decomp_aux_cons) with (n := n) (cn := n) in Hnd.\nQed.\n\nTheorem prime_decomp_cons : ∀ n a l,\n  prime_decomp n = a :: l\n  → prime_decomp (n / a) = l.\nProof.\nintros * Hl.\nassert (Hap : prime a). {\n  specialize (first_in_decomp_is_prime n) as H1.\n  now rewrite Hl in H1.\n}\nassert (H2a : 2 ≤ a) by now apply prime_ge_2.\napply (prime_decomp_mul (n / a) a); [ easy | ].\nspecialize (in_prime_decomp_divide n a) as H1.\nrewrite Hl in H1.\nspecialize (H1 (or_introl eq_refl)).\ndestruct H1 as (b, Hb).\nrewrite Hb, Nat.div_mul; [ | flia H2a ].\nnow rewrite <- Hb.\nQed.\n\nTheorem prime_decomp_inj : ∀ a b,\n  a ≠ 0 → b ≠ 0 → prime_decomp a = prime_decomp b → a = b.\nProof.\nintros * Ha0 Hb0 Hab.\nremember (prime_decomp b) as l eqn:Hb; symmetry in Hb.\nrename Hab into Ha; move Ha after Hb.\nrevert a b Ha0 Hb0 Ha Hb.\ninduction l as [| d]; intros. {\n  apply prime_decomp_nil_iff in Ha.\n  apply prime_decomp_nil_iff in Hb.\n  destruct Ha as [Ha| Ha]; [ easy | ].\n  destruct Hb as [Hb| Hb]; [ easy | ].\n  now subst a b.\n}\nspecialize (in_prime_decomp_divide a d) as Hda.\nrewrite Ha in Hda; cbn in Hda.\nspecialize (Hda (or_introl (eq_refl _))) as (da, Hda).\nspecialize (in_prime_decomp_divide b d) as Hdb.\nrewrite Hb in Hdb; cbn in Hdb.\nspecialize (Hdb (or_introl (eq_refl _))) as (db, Hdb).\nmove db before da.\nrewrite Hda, Hdb; f_equal.\napply IHl.\n-now intros H; rewrite H in Hda.\n-now intros H; rewrite H in Hdb.\n-rewrite Hda in Ha.\n apply (prime_decomp_mul _ d); [ | easy ].\n destruct d; [ flia Ha0 Hda | ].\n destruct d; [ | flia ].\n apply (in_prime_decomp_ge_2 b 1).\n now rewrite Hb; left.\n-rewrite Hdb in Hb.\n apply (prime_decomp_mul _ d); [ | easy ].\n destruct d; [ flia Ha0 Hda | ].\n destruct d; [ | flia ].\n apply (in_prime_decomp_ge_2 a 1).\n now rewrite Ha; left.\nQed.\n\nTheorem in_prime_decomp_is_prime : ∀ n d, d ∈ prime_decomp n → prime d.\nProof.\nintros * Hdn.\nspecialize (In_nth (prime_decomp n) d 2 Hdn) as (i & Hilen & Hid).\nclear Hdn; subst d.\nrevert n Hilen.\ninduction i; intros. {\n  rewrite <- List_hd_nth_0.\n  apply first_in_decomp_is_prime.\n}\nremember (prime_decomp n) as l eqn:Hl; symmetry in Hl.\ndestruct l as [| a l]; [ easy | ].\ncbn in Hilen; cbn.\napply Nat.succ_lt_mono in Hilen.\nspecialize (prime_decomp_cons n a l Hl) as H1.\nrewrite <- H1.\napply IHi.\nnow rewrite H1.\nQed.\n\nTheorem prime_decomp_prod : ∀ n, n ≠ 0 →\n  fold_left Nat.mul (prime_decomp n) 1 = n.\nProof.\nintros * Hnz.\nremember (prime_decomp n) as l eqn:Hl; symmetry in Hl.\nrevert n Hnz Hl.\ninduction l as [| a l]; intros. {\n  now apply prime_decomp_nil_iff in Hl; destruct Hl.\n}\nremember 1 as one; cbn; subst one.\nspecialize (in_prime_decomp_divide n a) as H1.\nrewrite Hl in H1; specialize (H1 (or_introl eq_refl)).\ndestruct H1 as (k, Hk).\nrewrite Hk in Hl.\nassert (H2a : 2 ≤ a). {\n  apply (in_prime_decomp_ge_2 (k * a)).\n  now rewrite Hl; left.\n}\napply prime_decomp_mul in Hl; [ | easy ].\napply IHl in Hl; [ | now intros H; subst k ].\napply (Nat.mul_cancel_r _ _ a) in Hl; [ | flia H2a ].\nrewrite Hk, <- Hl.\nsymmetry; apply List_fold_left_mul_assoc.\nQed.\n\nTheorem eq_gcd_prime_small_1 : ∀ p n,\n  prime p\n  → 0 < n < p\n  → Nat.gcd p n = 1.\nProof.\nintros * Hp Hnp.\nremember (Nat.gcd p n) as g eqn:Hg; symmetry in Hg.\ndestruct g; [ now apply Nat.gcd_eq_0 in Hg; rewrite (proj1 Hg) in Hp | ].\ndestruct g; [ easy | exfalso ].\nspecialize (Nat.gcd_divide_l p n) as H1.\nrewrite Hg in H1.\ndestruct H1 as (d, Hd).\nspecialize (prime_only_divisors p Hp (S (S g))) as H1.\nassert (H : Nat.divide (S (S g)) p). {\n  rewrite Hd; apply Nat.divide_factor_r.\n}\nspecialize (H1 H); clear H.\ndestruct H1 as [H1| H1]; [ easy | ].\ndestruct d; [ now rewrite Hd in Hp | ].\nrewrite Hd in H1.\ndestruct d. {\n  rewrite Nat.mul_1_l in Hd.\n  rewrite <- Hd in Hg.\n  specialize (Nat.gcd_divide_r p n) as H2.\n  rewrite Hg in H2.\n  destruct H2 as (d2, Hd2).\n  destruct d2; [ rewrite Hd2 in Hnp; flia Hnp | ].\n  rewrite Hd2 in Hnp; flia Hnp.\n}\nreplace (S (S d)) with (1 + S d) in H1 by flia.\nrewrite Nat.mul_add_distr_r, Nat.mul_1_l in H1.\nrewrite <- (Nat.add_0_r (S (S g))) in H1 at 1.\nnow apply Nat.add_cancel_l in H1.\nQed.\n\nTheorem prime_divisor_in_decomp : ∀ n d,\n  2 ≤ n\n  → prime d\n  → Nat.divide d n\n  → d ∈ prime_decomp n.\nProof.\nintros * H2n Hd Hdn.\nunfold prime_decomp.\nreplace n with (S (S (n - 2))) at 1 by flia H2n.\nassert (prime_divisor_in_decomp_aux : ∀ cnt n d p,\n  2 ≤ n\n  → 2 ≤ d\n  → d ≤ p\n  → n + 2 ≤ cnt + d\n  → prime p\n  → Nat.divide p n\n  → p ∈ prime_decomp_aux cnt n d). {\n  clear.\n  intros * H2n H2d Hdp Hcnt Hp Hpn.\n  revert n d p H2n H2d Hdp Hcnt Hp Hpn.\n  induction cnt; intros. {\n    cbn in Hcnt; cbn.\n    destruct Hpn as (k, Hk); subst n.\n    apply Nat.nlt_ge in Hcnt; apply Hcnt; clear Hcnt.\n    destruct k; [ flia H2n | flia Hdp ].\n  }\n  cbn.\n  remember (n mod d) as b eqn:Hb; symmetry in Hb.\n  assert (Hdz : d ≠ 0) by flia H2d.\n  destruct b. 2: {\n    apply IHcnt; [ easy | flia H2d | | flia Hcnt | easy | easy ].\n    destruct (Nat.eq_dec p d) as [Hpd| Hpd]; [ | flia Hdp Hpd ].\n    subst d; exfalso.\n    apply Nat.mod_divide in Hpn; [ | easy ].\n    now rewrite Hpn in Hb.\n  }\n  destruct (Nat.eq_dec p d) as [Hpd| Hpd]; [ now left | right ].\n  apply IHcnt; [ | easy | easy | | easy | ]. {\n    apply Nat.mod_divide in Hb; [ | easy ].\n    destruct Hb as (k, Hk).\n    rewrite Hk, Nat.div_mul; [ | easy ].\n    destruct k; [ flia H2n Hk | ].\n    destruct k; [ exfalso | flia ].\n    rewrite Nat.mul_1_l in Hk; subst n.\n    destruct Hpn as (k, Hk).\n    destruct k; [ easy | ].\n    destruct k; [ rewrite Nat.mul_1_l in Hk; flia Hk Hpd | ].\n    apply Nat.nlt_ge in Hdp; apply Hdp; clear Hdp.\n    rewrite Hk; cbn.\n    destruct p; [ now rewrite Nat.mul_0_r in Hk | flia ].\n  } {\n    transitivity (n + 1); [ | flia Hcnt ].\n    apply Nat.mod_divide in Hb; [ | easy ].\n    destruct Hb as (k, Hk).\n    rewrite Hk.\n    rewrite Nat.div_mul; [ | easy ].\n    destruct d; [ easy | ].\n    destruct d; [ flia H2d | ].\n    destruct k; [ flia H2n Hk | flia ].\n  }\n  apply Nat.mod_divide in Hb; [ | easy ].\n  destruct Hpn as (k, Hk).\n  rewrite Hk in Hb.\n  rewrite Nat.mul_comm in Hb.\n  apply Nat.gauss in Hb. {\n    destruct Hb as (k', Hk').\n    subst n k.\n    rewrite Nat.mul_shuffle0.\n    rewrite Nat.div_mul; [ | easy ].\n    apply Nat.divide_factor_r.\n  }\n  rewrite Nat.gcd_comm.\n  apply eq_gcd_prime_small_1; [ easy | ].\n  flia Hdz Hdp Hpd.\n}\napply prime_divisor_in_decomp_aux; [ easy | easy | | easy | easy | easy ].\nnow apply prime_ge_2.\nQed.\n\nTheorem prime_decomp_in_iff : ∀ n d,\n  d ∈ prime_decomp n ↔ n ≠ 0 ∧ prime d ∧ Nat.divide d n.\nProof.\nintros.\nsplit; intros Hd. {\n  split; [ now intros H; subst n | ].\n  split; [ now apply in_prime_decomp_is_prime in Hd | ].\n  now apply in_prime_decomp_divide in Hd.\n} {\n  destruct Hd as (Hn & Hd & Hdn).\n  destruct (lt_dec n 2) as [Hn2| Hn2]. {\n    destruct n; [ easy | ].\n    destruct n; [ | flia Hn2 ].\n    destruct Hdn as (k, Hk).\n    symmetry in Hk.\n    apply Nat.eq_mul_1 in Hk.\n    now destruct Hk; subst d.\n  }\n  apply Nat.nlt_ge in Hn2.\n  now apply prime_divisor_in_decomp.\n}\nQed.\n\nTheorem prime_divide_mul : ∀ p, prime p →\n  ∀ a b, Nat.divide p (a * b) → Nat.divide p a ∨ Nat.divide p b.\nProof.\nintros * Hp * Hab.\ndestruct (Nat.eq_dec p 0) as [Hzp| Hzp]; [ now subst p | ].\ndestruct (Nat.eq_dec (Nat.gcd p a) 1) as [Hpa| Hpa]. {\n  specialize (Nat.gauss _ _ _ Hab) as H1.\n  right; apply H1, Hpa.\n} {\n  left.\n  apply Nat.mod_divide; [ easy | ].\n  destruct (Nat.eq_dec (a mod p) 0) as [Ha| Ha]; [ easy | exfalso ].\n  apply Hpa; clear Hpa.\n  rewrite <- Nat.gcd_mod; [ | easy ].\n  rewrite Nat.gcd_comm.\n  apply eq_gcd_prime_small_1; [ easy | ].\n  split; [ now apply Nat.neq_0_lt_0 | ].\n  now apply Nat.mod_upper_bound.\n}\nQed.\n\nTheorem prime_divides_fact_ge : ∀ n m,\n  prime n\n  → Nat.divide n (fact m)\n  → n ≤ m.\nProof.\nintros * Hn Hnm.\ninduction m; intros. {\n  destruct Hnm as (c, Hc).\n  symmetry in Hc.\n  apply Nat.eq_mul_1 in Hc.\n  now rewrite (proj2 Hc) in Hn.\n}\nrewrite Nat_fact_succ in Hnm.\nspecialize (Nat.gauss _ _ _ Hnm) as H1.\napply Nat.nlt_ge; intros Hnsm.\nassert (H : Nat.gcd n (S m) = 1). {\n  apply eq_gcd_prime_small_1; [ easy | ].\n  split; [ flia | easy ].\n}\nspecialize (H1 H); clear H.\napply Nat.nle_gt in Hnsm; apply Hnsm.\ntransitivity m; [ | flia ].\napply IHm, H1.\nQed.\n\n(* https://en.wikipedia.org/wiki/Factorial#Number_theory *)\nTheorem Wilson_on_composite :\n  ∀ n, 5 < n → ¬ prime n ↔ fact (n - 1) mod n = 0.\nProof.\nintros * H5n.\nsplit.\n-intros Hn.\n specialize (not_prime_decomp n) as H1.\n assert (H : 2 ≤ n) by flia H5n.\n specialize (H1 H Hn) as (a & b & Ha & Hb & Hab); clear H.\n apply Nat.mod_divide; [ flia H5n | ].\n assert (Han : 0 < a ≤ n - 1). {\n   rewrite Hab.\n   destruct a; [ easy | ].\n   split; [ flia | ].\n   destruct b; [ easy | ].\n   destruct a; [ flia Ha | ].\n   destruct b; [ flia Hb | ].\n   rewrite Nat.mul_comm; flia.\n }\n destruct (Nat.eq_dec a b) as [Haeb| Haeb]. {\n   subst b; clear Hb.\n   rewrite Hab at 1.\n   remember (a * (a - 1)) as b eqn:Hb.\n   apply (Nat.divide_trans _ (a * b)). {\n     subst b.\n     rewrite Nat.mul_assoc.\n     apply Nat.divide_factor_l.\n   }\n   assert (Haa : a ≠ b). {\n     intros H.\n     rewrite <- (Nat.mul_1_r a) in H; subst b.\n     apply Nat.mul_cancel_l in H; [ | flia Ha ].\n     replace a with 2 in Hab by flia H.\n     flia H5n Hab.\n   }\n   assert (Hbn : 0 < b ≤ n - 1). {\n     rewrite Hb, Hab.\n     split. {\n       destruct a; [ easy | ].\n       rewrite Nat.sub_succ, Nat.sub_0_r.\n       destruct a; [ flia Ha | flia ].\n     }\n     rewrite Nat.mul_sub_distr_l, Nat.mul_1_r.\n     apply Nat.sub_le_mono_l; flia Ha.\n   }\n   clear - Haa Han Hbn.\n   remember (n - 1) as m; clear n Heqm.\n   rename m into n; move n at top.\n   destruct (lt_dec a b) as [Hab| Hab].\n   -now apply Nat_divide_mul_fact.\n   -assert (H : b < a) by flia Haa Hab.\n    rewrite Nat.mul_comm.\n    now apply Nat_divide_mul_fact.\n }\n rewrite Hab at 1.\n assert (Hbn : 0 < b ≤ n - 1). {\n   rewrite Hab.\n   destruct b; [ easy | ].\n   split; [ flia | ].\n   destruct a; [ easy | ].\n   destruct b; [ flia Hb | ].\n   destruct a; [ flia Ha | flia ].\n }\n destruct (lt_dec a b) as [Halb| Halb].\n +now apply Nat_divide_mul_fact.\n +assert (H : b < a) by flia Halb Haeb.\n  rewrite Nat.mul_comm.\n  now apply Nat_divide_mul_fact.\n-intros Hn Hp.\n apply Nat.mod_divide in Hn; [ | flia H5n ].\n specialize (prime_divides_fact_ge _ _ Hp Hn) as H1.\n flia H5n H1.\nQed.\n\n(* Questions\n   - How to write a function \"next_prime\" computing the prime number\n     after a given n ?\n   - How to be able to test \"Compute (next_prime n)\" without having to\n     give (and compute) a too big upper bound, like this famous n! + 1 ?\n   - How to give an proved correct upper bound such that the proof is\n     not too complicated ?\n   Solution\n     The function \"next_prime\" below.\n   How does it work ?\n     It first makes n iterations. Bertrand's Postulate claims that,\n     inside these n iterations (up to 2n), a prime number is found.\n     So we can do \"Compute (next_prime n)\" fast enough.\n       If n iterations are reached, the function calls a function\n     named \"phony_prime_after\", giving it n! + 1 as maximum number\n     of iterations. It is proven that it is a sufficient upper\n     bound. But, in practice, when testing \"Compute (next_prime n)\",\n     this function is never called.\n       So this computation remains fast and proven that it returns\n     a prime number, with a short proof.\n *)\n\nFixpoint phony_prime_after niter n :=\n  if is_prime n then n\n  else\n    match niter with\n    | 0 => 0\n    | S niter' => phony_prime_after niter' (n + 1)\n    end.\n\nFixpoint prime_after_aux niter n :=\n  if is_prime n then n\n  else\n    match niter with\n    | 0 =>\n        (* point never reached and phony_prime_after never called\n           thanks to Bertrand's Postulate *)\n        (* except, actually when n = 0, and then fact n + 1 = 2,\n           not a big deal, fastly computed *)\n        (* this code serves to prove that prime_after always\n           answers a prime number, i.e. phony_prime_after never\n           answers 0 *)\n        (* something: after the iterations of the present function,\n           the value of n is twice the value of the initial n,\n           so we are actually searching the next prime number\n           after 2n; no important, this code is just for proofs. *)\n        phony_prime_after (fact n + 1) n\n    | S niter' =>\n        prime_after_aux niter' (n + 1)\n    end.\n\nDefinition prime_after n := prime_after_aux n n.\n\n(* \"prime_after n\" is indeed a prime *)\n\nLemma bounded_phony_prime_after : ∀ n p,\n  n < p\n  → prime p\n  → prime (phony_prime_after (p - n) n).\nProof.\nintros * Hnm Hm.\nremember (p - n) as niter eqn:Hniter.\nreplace p with (niter + n) in * by flia Hniter Hnm.\nclear p Hnm Hniter.\nrevert n Hm.\ninduction niter; intros. {\n  cbn in Hm; cbn.\n  remember (is_prime n) as b eqn:Hb; symmetry in Hb.\n  destruct b; [ easy |].\n  now apply Bool.not_true_iff_false in Hb.\n}\ncbn.\nremember (is_prime n) as b eqn:Hb; symmetry in Hb.\ndestruct b; [ easy | ].\napply IHniter.\nnow replace (S niter + n) with (niter + (n + 1)) in Hm by flia.\nQed.\n\nLemma phony_prime_after_is_prime : ∀ n,\n  prime (phony_prime_after (fact n + 1) n).\nProof.\nintros.\nspecialize (next_prime_bounded n) as (m & Hm & Hmp).\nspecialize (bounded_phony_prime_after n m (proj1 Hm) Hmp) as H1.\nremember (fact n + 1) as niter1.\nremember (m - n) as niter2.\nassert (Hni : niter2 ≤ niter1). {\n  subst niter1 niter2; flia Hm.\n}\nclear Hm Heqniter1 Heqniter2 Hmp.\nmove niter2 before niter1.\nrevert n niter2 H1 Hni.\ninduction niter1; intros. {\n  now apply Nat.le_0_r in Hni; subst niter2.\n}\ncbn.\ndestruct niter2; cbn in H1; [ now destruct (is_prime n) | ].\napply Nat.succ_le_mono in Hni.\ndestruct (is_prime n); [ easy | ].\nnow apply IHniter1 in H1.\nQed.\n\nLemma prime_after_aux_is_prime : ∀ niter n,\n  prime (prime_after_aux niter n).\nProof.\nintros.\nrevert n.\ninduction niter; intros. {\n  cbn - [ \"/\" ].\n  remember (is_prime n) as b eqn:Hb; symmetry in Hb.\n  destruct b; [ easy | ].\n  apply phony_prime_after_is_prime.\n}\ncbn.\nremember (is_prime n) as b eqn:Hb; symmetry in Hb.\ndestruct b; [ easy | ].\napply IHniter.\nQed.\n\nTheorem prime_after_is_prime : ∀ n, prime (prime_after n).\nProof.\nintros.\napply prime_after_aux_is_prime.\nQed.\n\n(* \"prime_after n\" is indeed after (greater or equal to) n *)\n\nLemma bounded_phony_prime_after_is_after : ∀ n p,\n  n ≤ p\n  → prime p\n  → n ≤ phony_prime_after (p - n) n.\nProof.\nintros * Hnm Hm.\nremember (p - n) as niter eqn:Hniter.\nreplace p with (niter + n) in * by flia Hniter Hnm.\nclear p Hnm Hniter.\nrevert n Hm.\ninduction niter; intros. {\n  cbn in Hm; cbn.\n  unfold prime in Hm.\n  now destruct (is_prime n).\n}\ncbn.\ndestruct (is_prime n); [ easy | ].\ntransitivity (n + 1); [ flia | ].\napply IHniter.\nnow replace (S niter + n) with (niter + (n + 1)) in Hm by flia.\nQed.\n\nLemma phony_prime_after_is_after : ∀ n,\n  n ≤ phony_prime_after (fact n + 1) n.\nProof.\nintros.\nspecialize (next_prime_bounded n) as (m & Hm & Hmp).\nspecialize (bounded_phony_prime_after_is_after n m) as H1.\nspecialize (H1 (Nat.lt_le_incl _ _ (proj1 Hm)) Hmp).\netransitivity; [ apply H1 | ].\nclear H1.\nremember (m - n) as k eqn:Hk.\nreplace m with (n + k) in Hmp by flia Hk Hm.\nreplace (fact n + 1) with (k + (fact n + 1 - k)) by flia Hm Hk.\nremember (fact n + 1 - k) as l eqn:Hl.\nclear m Hm Hk Hl; move l before k.\nrevert n l Hmp.\ninduction k; intros; cbn. {\n  rewrite Nat.add_0_r in Hmp.\n  unfold prime in Hmp.\n  now destruct l; cbn; destruct (is_prime n).\n}\ndestruct (is_prime n); [ easy | ].\nreplace (n + S k) with (n + 1 + k) in Hmp by flia.\nnow apply IHk.\nQed.\n\nLemma prime_after_aux_is_after : ∀ niter n, n ≤ prime_after_aux niter n.\nProof.\nintros.\nrevert n.\ninduction niter; intros; cbn. {\n  destruct (is_prime n); [ easy | ].\n  apply phony_prime_after_is_after.\n}\ndestruct (is_prime n); [ easy | ].\ntransitivity (n + 1); [ flia | apply IHniter ].\nQed.\n\nTheorem prime_after_is_after : ∀ n, n ≤ prime_after n.\nProof.\nintros.\napply prime_after_aux_is_after.\nQed.\n\n(* there is no prime between \"n\" and \"next_prime n\" *)\n\nLemma no_prime_before_phony_prime_after : ∀ n i,\n  ¬ prime n\n  → n ≤ i < phony_prime_after (fact n + 1) n\n  → ¬ prime i.\nProof.\nintros * Hb Hni.\nspecialize (next_prime_bounded n) as (p & Hp & Hpp).\nspecialize (phony_prime_after_is_prime n) as Hpq.\nremember (phony_prime_after (fact n + 1) n) as q eqn:Hq.\nclear p Hp Hpp.\nremember (fact n + 1) as it eqn:Hit; clear Hit.\nremember (i - n) as j eqn:Hj.\nreplace i with (n + j) in * by flia Hj Hni.\nclear i Hj.\ndestruct Hni as (_, Hnj).\nrevert it q n Hb Hnj Hq Hpq.\ninduction j; intros; [ now rewrite Nat.add_0_r | ].\nrewrite <- Nat.add_succ_comm in Hnj |-*.\napply Bool.not_true_iff_false in Hb.\ndestruct it; cbn in Hq. {\n  destruct (is_prime n); [ easy | now subst q ].\n}\nrewrite Nat.add_1_r in Hq.\ndestruct (is_prime n); [ easy | clear Hb ].\ndestruct it. {\n  remember (S n) as sn; cbn in Hq; subst sn.\n  destruct (is_prime (S n)); subst q; [ flia Hnj | easy ].\n}\nremember (S n) as sn; cbn in Hq; subst sn.\nremember (is_prime (S n)) as b eqn:Hb; symmetry in Hb.\ndestruct b; [ now subst q; flia Hnj | ].\neapply (IHj (S it)); [ | apply Hnj | | easy ]. {\n  now apply Bool.not_true_iff_false in Hb.\n}\nnow remember (S n) as sn; cbn; rewrite Hb.\nQed.\n\nTheorem phony_prime_after_more_iter : ∀ k n niter,\n  fact n + 1 ≤ niter\n  → phony_prime_after niter n = phony_prime_after (niter + k) n.\nProof.\nintros * Hnit.\nspecialize (next_prime_bounded n) as (p & Hnp & Hpp).\nremember (p - n) as i eqn:Hi.\nreplace p with (n + i) in * by flia Hi Hnp.\nclear Hi; destruct Hnp as (_, Hnp).\nassert (Hni : i ≤ niter) by flia Hnit Hnp.\nclear p Hnit Hnp.\nrevert i k n Hpp Hni.\ninduction niter; intros. {\n  apply Nat.le_0_r in Hni.\n  rewrite Hni, Nat.add_0_r in Hpp; cbn.\n  unfold prime in Hpp.\n  rewrite Hpp.\n  now destruct k; cbn; rewrite Hpp.\n}\ncbn.\nremember (is_prime n) as b eqn:Hb; symmetry in Hb.\ndestruct b; [ easy | ].\napply Bool.not_true_iff_false in Hb.\nunfold prime in Hpp.\ndestruct i; [ now rewrite Nat.add_0_r in Hpp | ].\napply Nat.succ_le_mono in Hni.\nreplace (n + S i) with (n + 1 + i) in Hpp by flia.\nnow apply (IHniter i).\nQed.\n\nLemma no_prime_before_after_aux : ∀ niter n i,\n  n ≤ i < prime_after_aux niter n → ¬ prime i.\nProof.\nintros * Hni.\ndestruct niter. {\n  cbn - [ \"/\" ] in Hni.\n  remember (is_prime n) as b eqn:Hb; symmetry in Hb.\n  destruct b; [ flia Hni | ].\n  apply Bool.not_true_iff_false in Hb.\n  now apply (no_prime_before_phony_prime_after n).\n}\ncbn in Hni.\nremember (is_prime n) as b eqn:Hb; symmetry in Hb.\ndestruct b; [ flia Hni | ].\nrevert n i Hb Hni.\ninduction niter; intros. {\n  cbn in Hni.\n  remember (is_prime (n + 1)) as b eqn:Hb1; symmetry in Hb1.\n  apply Bool.not_true_iff_false in Hb.\n  destruct b; [ now replace i with n by flia Hni | ].\n  apply (no_prime_before_phony_prime_after n); [ easy | ].\n  split; [ easy | ].\n  eapply lt_le_trans; [ apply Hni | ].\n  rewrite (phony_prime_after_more_iter (fact (n + 1) - fact n + 1) n);\n    [ | easy ].\n  replace (fact n + 1 + (fact (n + 1) - fact n + 1)) with\n      (S (fact (n + 1) + 1)). 2: {\n    rewrite (Nat.add_1_r n).\n    cbn; flia.\n  }\n  cbn.\n  now destruct (is_prime n).\n}\ncbn in Hni.\nremember (is_prime (n + 1)) as b1 eqn:Hb1; symmetry in Hb1.\napply Bool.not_true_iff_false in Hb.\ndestruct b1; [ now replace i with n by flia Hni | ].\ndestruct (Nat.eq_dec n i) as [Hni1| Hni1]; [ now subst i | ].\napply (IHniter (n + 1)); [ easy | ].\nsplit; [ | easy ].\nflia Hni Hni1.\nQed.\n\nTheorem no_prime_before_after : ∀ n i,\n  n ≤ i < prime_after n → ¬ prime i.\nProof.\nintros * Hni.\nnow apply (no_prime_before_after_aux n n i).\nQed.\n\n(* thanks to the code, 510! + 1 is not computed in this example;\n   otherwise this would not answer *)\n\n(*\nCompute (prime_after 510).\n*)\n\nTheorem Nat_gcd_prime_fact_lt : ∀ p,\n  prime p → ∀ k, k < p → Nat.gcd p (fact k) = 1.\nProof.\nintros * Hp * Hkp.\ninduction k; [ apply Nat.gcd_1_r | ].\nrewrite Nat_fact_succ.\napply Nat_gcd_1_mul_r; [ | apply IHk; flia Hkp ].\napply eq_gcd_prime_small_1; [ easy | flia Hkp ].\nQed.\n\n(* nth prime *)\n\nFixpoint nth_prime_aux cnt n :=\n  let p := prime_after n in\n  match cnt with\n  | 0 => p\n  | S c => nth_prime_aux c (p + 1)\n  end.\n\nDefinition nth_prime n := nth_prime_aux (n - 1) 0.\n\n(*\nCompute (nth_prime 30).\n*)\n\n(* slow but simple *)\n\nDefinition firstn_primes n := map nth_prime (seq 1 n).\n\n(* fast but complicated *)\n\nFixpoint firstn_primes_loop n p :=\n  match n with\n  | 0 => []\n  | S n' =>\n      let p' := prime_after p in\n      p' :: firstn_primes_loop n' (p' + 1)\n  end.\n\nDefinition firstn_primes' n := firstn_primes_loop n 0.\n\n(*\nTime Compute (let n := 50 in firstn_primes n).\nTime Compute (let n := 50 in firstn_primes' n).\nTime Compute (let n := 100 in firstn_primes' n).\n*)\n\n(*\nTime Compute (firstn_primes 100).   (* slow *)\nTime Compute (firstn_primes' 100).  (* fast *)\n*)\n\nNotation \"a ^ b\" := (Nat.pow a b) : nat_scope.\n\n(* binomial *)\n\nFixpoint binomial n k :=\n  match k with\n  | 0 => 1\n  | S k' =>\n      match n with\n      | 0 => 0\n      | S n' => binomial n' k' + binomial n' k\n     end\n  end.\n\nTheorem binomial_succ_succ : ∀ n k,\n  binomial (S n) (S k) = binomial n k + binomial n (S k).\nProof. easy. Qed.\n\nTheorem binomial_succ_r : ∀ n k,\n  binomial n (S k) =\n    match n with\n    | 0 => 0\n    | S n' => binomial n' k + binomial n' (S k)\n    end.\nProof.\nintros.\nnow destruct n.\nQed.\n\nTheorem binomial_lt : ∀ n k, n < k → binomial n k = 0.\nProof.\nintros * Hnk.\nrevert k Hnk.\ninduction n; intros; [ now destruct k | cbn ].\ndestruct k; [ flia Hnk | ].\napply Nat.succ_lt_mono in Hnk.\nrewrite IHn; [ | easy ].\nrewrite Nat.add_0_l.\napply IHn; flia Hnk.\nQed.\n\nTheorem binomial_succ_diag_r : ∀ n, binomial n (S n) = 0.\nProof.\nintros.\napply binomial_lt; flia.\nQed.\n\nTheorem binomial_0_r : ∀ n, binomial n 0 = 1.\nProof. now intros; destruct n. Qed.\n\nTheorem binomial_diag : ∀ n, binomial n n = 1.\nProof.\nintros.\ninduction n; [ easy | cbn ].\nnow rewrite IHn, binomial_succ_diag_r, Nat.add_0_r.\nQed.\n\n(* Code by Ralph D. Jeffords at math.stackexchange.com *)\n\n(* product of k consecutive numbers from n to n+k-1 *)\n(* prod_consec (m,k) = m...(m+k-1) *)\nDefinition prod_consec k n := fact (n + k - 1) / fact (n - 1).\n\nLemma prod_consec_rec_formula : ∀ m k,\n  2 ≤ m\n  → 2 ≤ k\n  → prod_consec k m = k * prod_consec (k - 1) m + prod_consec k (m - 1).\nProof.\nintros * H2m H2k.\nreplace (prod_consec k m) with (prod_consec (k - 1) m * (k + (m - 1))). 2: {\n  unfold prod_consec.\n  replace (m + (k - 1) - 1) with (m + k - 2) by flia H2k.\n  replace (m + k - 1) with (S (m + k - 2)) by flia H2m.\n  rewrite Nat_fact_succ.\n  replace (S (m + k - 2)) with (m + k - 1) by flia H2m.\n  rewrite Nat.divide_div_mul_exact; [ | apply fact_neq_0 | ]. 2: {\n    apply Nat_le_divides_fact; flia H2k.\n  }\n  rewrite Nat.mul_comm; f_equal; flia H2m.\n}\nrewrite Nat.mul_comm, Nat.mul_add_distr_r; f_equal.\nunfold prod_consec.\nreplace (m - 1 - 1) with (m - 2) by flia H2m.\nreplace (m + (k - 1) - 1) with (m + k - 2) by flia H2k.\nreplace (m - 1 + k - 1) with (m + k - 2) by flia H2m.\nspecialize (Nat_le_divides_fact (m + k - 2) (m - 1)) as H1.\nassert (H :  m - 1 ≤ m + k - 2) by flia H2k.\nspecialize (H1 H) as (c, Hc); clear H.\nrewrite Hc, Nat.div_mul; [ | apply fact_neq_0 ].\nreplace (m - 1) with (S (m - 2)) by flia H2m.\nrewrite Nat_fact_succ, Nat.mul_assoc.\nrewrite Nat.div_mul; [ | apply fact_neq_0 ].\napply Nat.mul_comm.\nQed.\n\nTheorem divide_fact_prod_consec : ∀ k m,\n  1 ≤ m\n  → 1 ≤ k\n  → Nat.divide (fact k) (prod_consec k m).\nProof.\nintros * H1m H1k.\nremember (m + k) as n eqn:Hn.\nassert (H : m + k ≤ n) by flia Hn.\nclear Hn; rename H into Hn.\nrevert k m Hn H1m H1k.\ninduction n as (n, IHn) using lt_wf_rec; intros.\ndestruct (Nat.eq_dec n 2) as [Hn2| Hn2]. {\n  replace m with 1 by flia Hn H1m H1k Hn2.\n  replace k with 1 by flia Hn H1m H1k Hn2.\n  apply Nat.divide_refl.\n}\ndestruct (Nat.eq_dec m 1) as [Hm1| Hm1]. {\n  subst m; unfold prod_consec.\n  rewrite Nat.add_comm, Nat.add_sub, Nat.sub_diag.\n  rewrite Nat.div_1_r.\n  apply Nat.divide_refl.\n}\ndestruct (Nat.eq_dec k 1) as [Hk1| Hk1]. {\n  subst k; apply Nat.divide_1_l.\n}\nassert (H2m : 2 ≤ m) by flia H1m Hm1.\nassert (H2k : 2 ≤ k) by flia H1k Hk1.\nspecialize (prod_consec_rec_formula m k H2m H2k) as H1.\nassert (Hmn : m + (k - 1) < n) by flia Hn H2k.\nassert (H1k1 : 1 ≤ k - 1) by flia H2k.\nspecialize (IHn (m + (k - 1)) Hmn (k - 1) m (le_refl _) H1m H1k1) as H2.\napply (Nat.mul_divide_mono_l _ _ k) in H2.\nreplace k with (S (k - 1)) in H2 at 1 by flia H1k.\nrewrite <- Nat_fact_succ in H2.\nreplace (S (k - 1)) with k in H2 by flia H1k.\nrewrite H1.\napply Nat.divide_add_r; [ easy | ].\napply (IHn (m - 1 + k)); [ flia Hn H2m | easy | flia H2m | easy ].\nQed.\n\nTheorem fact_divides_fact_over_fact : ∀ k n,\n  k ≤ n\n  → Nat.divide (fact k) (fact n / fact (n - k)).\nProof.\nintros * Hkn.\ndestruct (Nat.eq_dec k 0) as [Hkz| Hkz]. {\n  subst k; apply Nat.divide_1_l.\n}\nspecialize (divide_fact_prod_consec k (n - k + 1)) as H1.\nunfold prod_consec in H1.\nrewrite Nat.add_shuffle0 in H1.\ndo 2 rewrite Nat.add_sub in H1.\nrewrite Nat.sub_add in H1; [ | easy ].\napply H1; [ flia Hkn | flia Hkz ].\nQed.\n\nTheorem fact_fact_divides_fact : ∀ k n,\n  k ≤ n\n  → Nat.divide (fact k * fact (n - k)) (fact n).\nProof.\nintros * Hkn.\nspecialize (fact_divides_fact_over_fact k n Hkn) as H1.\napply (Nat.mul_divide_cancel_r _ _ (fact (n - k))) in H1. 2: {\n  apply fact_neq_0.\n}\neapply Nat.divide_trans; [ apply H1 | ].\nrewrite Nat.mul_comm.\nrewrite <- (proj2 (Nat.div_exact _ _ (fact_neq_0 _))). 2: {\n  apply Nat.mod_divide; [ apply fact_neq_0 | ].\n  apply Nat_divide_fact_fact.\n}\napply Nat.divide_refl.\nQed.\n\nTheorem binomial_fact : ∀ n k,\n  k ≤ n\n  → binomial n k = fact n / (fact k * fact (n - k)).\nProof.\nintros * Hkn.\nrevert k Hkn.\ninduction n; intros; [ now apply Nat.le_0_r in Hkn; subst k | ].\ndestruct k. {\n  cbn; rewrite Nat.add_0_r.\n  symmetry; apply Nat.div_same.\n  intros H; apply Nat.eq_add_0 in H.\n  destruct H as (H, _).\n  now apply fact_neq_0 in H.\n}\napply Nat.succ_le_mono in Hkn.\nrewrite Nat.sub_succ.\nrewrite binomial_succ_r.\nrewrite IHn; [ | easy ].\ndestruct (Nat.eq_dec k n) as [Hken| Hken]. {\n  rewrite Hken.\n  rewrite Nat.sub_diag.\n  rewrite Nat.mul_1_r, Nat.div_same; [ | apply fact_neq_0 ].\n  rewrite Nat.mul_1_r, Nat.div_same; [ | apply fact_neq_0 ].\n  now rewrite binomial_succ_diag_r, Nat.add_0_r.\n}\nassert (H : k < n) by flia Hkn Hken.\nclear Hkn Hken; rename H into Hkn.\nrewrite IHn; [ | flia Hkn ].\n(* lemma to do, perhaps? *)\nreplace (n - k) with (S (n - S k)) by flia Hkn.\ndo 3 rewrite Nat_fact_succ.\nreplace (S (n - S k)) with (n - k) by flia Hkn.\nrewrite (Nat.mul_comm (fact k)).\nrewrite Nat.mul_shuffle0.\ndo 2 rewrite <- Nat.mul_assoc.\nrewrite <- Nat.div_div; [ | flia Hkn | ]. 2: {\n  apply Nat.neq_mul_0; split; apply fact_neq_0.\n}\nrewrite <- (Nat.div_div _ (S k)); [ | easy | ]. 2: {\n  apply Nat.neq_mul_0; split; apply fact_neq_0.\n}\nrewrite Nat_add_div_same. 2: {\n  replace (fact (n - S k)) with (fact (n - k) / (n - k)). 2: {\n    replace (n - k) with (S (n - S k)) by flia Hkn.\n    rewrite Nat_fact_succ.\n    rewrite Nat.mul_comm, Nat.div_mul; [ easy | ].\n    flia Hkn.\n  }\n  rewrite <- Nat.divide_div_mul_exact; [ | flia Hkn | ]. 2: {\n    apply Nat_divide_small_fact; flia Hkn.\n  }\n  apply (Nat.mul_divide_cancel_l _ _ (n - k)); [ flia Hkn | ].\n  rewrite <- Nat.divide_div_mul_exact; [ | flia Hkn | ]. 2: {\n    apply (Nat.divide_trans _ (fact (n - k))). {\n      apply Nat_divide_small_fact; flia Hkn.\n    }\n    apply Nat.divide_factor_r.\n  }\n  rewrite Nat.mul_comm, Nat.div_mul; [ | flia Hkn ].\n  rewrite <- Nat.divide_div_mul_exact; [ | flia Hkn | ]. 2: {\n    apply Nat_divide_small_fact; flia Hkn.\n  }\n  rewrite (Nat.mul_comm (n - k)), Nat.div_mul; [ | flia Hkn ].\n  now apply fact_fact_divides_fact, Nat.lt_le_incl.\n}\nrewrite Nat.mul_shuffle1.\nrewrite <- (Nat.div_div (S n * _)); cycle 1. {\n  apply Nat.neq_mul_0; split; [ easy | flia Hkn ].\n} {\n  apply Nat.neq_mul_0; split; apply fact_neq_0.\n}\nf_equal.\n(* lemma to do, perhaps? *)\nrewrite <- (Nat.div_mul_cancel_l _ _ (S k)); [ | flia Hkn | easy ].\nrewrite <- (Nat.div_mul_cancel_r (fact n) _ (n - k)); [ | easy | flia Hkn ].\nrewrite Nat_add_div_same. 2: {\n  apply Nat.mul_divide_cancel_l; [ easy | ].\n  apply Nat_divide_small_fact; flia Hkn.\n}\nf_equal.\nrewrite (Nat.mul_comm (fact n)), <- Nat.mul_add_distr_r.\nf_equal.\nflia Hkn.\nQed.\n\nTheorem newton_binomial : ∀ n a b,\n  (a + b) ^ n = Σ (k = 0, n), binomial n k * a ^ (n - k) * b ^ k.\nProof.\nintros.\ninduction n; [ easy | ].\ncbn - [ \"-\" binomial ].\nrewrite IHn.\nrewrite mul_summation_distr_l.\nrewrite mul_add_distr_r_in_summation.\nrewrite summation_add.\ndo 2 rewrite <- double_mul_assoc_in_summation.\nrewrite power_shuffle1_in_summation.\nrewrite power_shuffle2_in_summation.\nsymmetry.\nrewrite summation_split_first; [ | flia ].\nunfold binomial at 1.\nrewrite Nat.mul_1_l, Nat.sub_0_r, Nat.pow_0_r, Nat.mul_1_r at 1.\nrewrite summation_succ_succ.\ncbn - [ \"-\" \"^\" ].\nrewrite mul_assoc_in_summation.\nrewrite mul_add_distr_r_in_summation.\nrewrite summation_add.\nrewrite Nat.add_assoc.\ndo 2 rewrite <- mul_assoc_in_summation.\nrewrite Nat.add_shuffle0.\nf_equal.\nrewrite <- (summation_succ_succ 0 n (λ i, binomial n i * a ^ (S n - i) * b ^ i)).\nrewrite summation_split_last; [ | flia | flia ].\nreplace (S n - 1) with n by flia.\nrewrite binomial_succ_diag_r, Nat.mul_0_l, Nat.add_0_r.\nsymmetry.\nrewrite summation_split_first; [ | flia ].\nnow rewrite binomial_0_r, Nat.mul_1_l, Nat.sub_0_r, Nat.pow_0_r, Nat.mul_1_r.\nQed.\n\nTheorem binomial_prime : ∀ p k,\n  prime p\n  → 1 ≤ k ≤ p - 1\n  → Nat.divide p (binomial p k).\nProof.\nintros * Hp Hkp.\nrewrite binomial_fact; [ | flia Hkp ].\nassert (Hffz : fact k * fact (p - k) ≠ 0). {\n  apply Nat.neq_mul_0; split; apply fact_neq_0.\n}\napply (Nat.gauss _ (fact k * fact (p - k))). {\n  rewrite <- (proj2 (Nat.div_exact _ _ Hffz)). 2: {\n    apply Nat.mod_divide; [ easy | ].\n    apply fact_fact_divides_fact; flia Hkp.\n  }\n  apply Nat_divide_small_fact; flia Hkp.\n}\nassert (Hjp : p - k ≤ p - 1) by flia Hkp.\nremember (p - k) as j; move j before p.\nclear Hffz Heqj; destruct Hkp as (_, Hkp).\nmove Hjp before Hkp; rewrite Nat.mul_comm.\n(* lemma, perhaps? *)\nrevert j Hjp.\ninduction k; intros. {\n  rewrite Nat.mul_1_r.\n  clear Hkp.\n  induction j; [ apply Nat.gcd_1_r | ].\n  rewrite Nat_fact_succ.\n  apply Nat_gcd_1_mul_r. {\n    apply eq_gcd_prime_small_1; [ easy | flia Hjp ].\n  }\n  apply IHj; flia Hjp.\n}\nrewrite Nat_fact_succ, Nat.mul_comm, <- Nat.mul_assoc.\napply Nat_gcd_1_mul_r. {\n  apply eq_gcd_prime_small_1; [ easy | flia Hkp ].\n}\nrewrite Nat.mul_comm.\napply IHk; [ flia Hkp | easy ].\nQed.\n\nTheorem sum_power_prime_mod : ∀ p, prime p →\n  ∀ a b, (a + b) ^ p mod p = (a ^ p + b ^ p) mod p.\nProof.\nintros * Hp *.\nrewrite newton_binomial.\nrewrite summation_split_first; [ | flia ].\nrewrite binomial_0_r, Nat.mul_1_l, Nat.sub_0_r, Nat.pow_0_r, Nat.mul_1_r.\nspecialize (prime_ge_2 p Hp) as H2p.\nrewrite summation_split_last; [ | flia H2p | flia H2p ].\nrewrite binomial_diag.\nrewrite Nat.sub_diag, Nat.pow_0_r, Nat.mul_1_r, Nat.mul_1_l.\nrewrite Nat.add_assoc, Nat.add_shuffle0.\nsymmetry.\nremember (a ^ p + b ^ p) as x.\nreplace x with (x + 0) at 1 by flia.\nrewrite <- Nat.add_mod_idemp_r; [ symmetry | flia H2p ].\nrewrite <- Nat.add_mod_idemp_r; [ symmetry | flia H2p ].\nf_equal; f_equal; clear x Heqx; symmetry.\nrewrite Nat.mod_0_l; [ | flia H2p ].\nrewrite summation_mod_idemp.\nrewrite all_0_summation_0. {\n  rewrite Nat.mod_0_l; [ easy | flia H2p ].\n}\nintros i Hi.\nspecialize (binomial_prime _ _ Hp Hi) as (c, Hc).\nrewrite Hc, (Nat.mul_comm c).\ndo 2 rewrite <- Nat.mul_assoc.\nrewrite Nat.mul_comm.\napply Nat.mod_mul; flia H2p.\nQed.\n\nTheorem smaller_than_prime_all_different_multiples : ∀ p,\n  prime p\n  → ∀ a, 1 ≤ a < p\n  → ∀ i j, i < j < p → (i * a) mod p ≠ (j * a) mod p.\nProof.\nintros * Hp * Hap * Hijp.\nintros Haa; symmetry in Haa.\napply Nat_mul_mod_cancel_r in Haa. 2: {\n  rewrite Nat.gcd_comm.\n  now apply eq_gcd_prime_small_1.\n}\nrewrite Nat.mod_small in Haa; [ | easy ].\nrewrite Nat.mod_small in Haa; [ | flia Hijp ].\nflia Hijp Haa.\nQed.\n\nTheorem fold_left_mul_map_mod : ∀ a b l,\n  fold_left Nat.mul (map (λ i, i mod a) l) b mod a =\n  fold_left Nat.mul l b mod a.\nProof.\nintros.\ndestruct (Nat.eq_dec a 0) as [Haz| Haz]. {\n  now subst a; rewrite map_id.\n}\ninduction l as [| c l]; [ easy | cbn ].\nrewrite <- List_fold_left_mul_assoc.\nrewrite Nat.mul_mod_idemp_r; [ | easy ].\nrewrite <- Nat.mul_mod_idemp_l; [ | easy ].\nrewrite IHl.\nrewrite Nat.mul_mod_idemp_l; [ | easy ].\nnow rewrite List_fold_left_mul_assoc.\nQed.\n\nTheorem fold_left_mul_map_mul : ∀ b c l,\n  fold_left Nat.mul (map (λ a, a * b) l) c =\n  fold_left Nat.mul l c * b ^ length l.\nProof.\nintros.\ninduction l as [| a l]; [ now cbn; rewrite Nat.mul_1_r | cbn ].\ndo 2 rewrite <- List_fold_left_mul_assoc.\nrewrite IHl; flia.\nQed.\n\nTheorem fact_eq_fold_left : ∀ n,\n  fact n = fold_left Nat.mul (seq 1 n) 1.\nProof.\ninduction n; intros; [ easy | ].\nrewrite <- (Nat.add_1_r n) at 2.\nrewrite seq_app.\nrewrite fold_left_app.\nnow rewrite <- IHn, Nat_fact_succ, Nat.mul_comm.\nQed.\n\nTheorem fermat_little : ∀ p,\n  prime p → ∀ a, 1 ≤ a < p → a ^ (p - 1) mod p = 1.\nProof.\nintros * Hp * Hap.\nspecialize (smaller_than_prime_all_different_multiples p Hp a Hap) as H1.\nassert (Hpz : p ≠ 0) by now intros H; rewrite H in Hp.\nassert\n  (Hperm :\n     Permutation (map (λ i, (i * a) mod p) (seq 1 (p - 1)))\n       (seq 1 (p - 1))). {\n(**)\n  apply NoDup_Permutation_bis; cycle 1. {\n    now rewrite map_length, seq_length.\n  } {\n    intros i Hi.\n    apply in_map_iff in Hi.\n    destruct Hi as (j & Hji & Hj).\n    apply in_seq in Hj.\n    rewrite <- Hji.\n    apply in_seq.\n    replace (1 + (p - 1)) with p in Hj |-* by flia Hpz.\n    split; [ | now apply Nat.mod_upper_bound ].\n    apply Nat.neq_0_lt_0.\n    intros Hi.\n    apply Nat.mod_divide in Hi; [ | easy ].\n    specialize (Nat.gauss _ _ _ Hi) as H2.\n    assert (H : Nat.gcd p j = 1) by now apply eq_gcd_prime_small_1.\n    specialize (H2 H); clear H.\n    destruct H2 as (c, Hc).\n    rewrite Hc in Hap.\n    destruct c; [ easy | ].\n    cbn in Hap; flia Hap.\n  } {\n    remember (λ i, (i * a) mod p) as f eqn:Hf.\n    assert (H2 : ∀ i j, i < j < p → f i ≠ f j) by now rewrite Hf.\n    assert\n      (H : ∀ {A} start len (f : nat → A),\n         (∀ i j, i < j < start + len → f i ≠ f j)\n         → NoDup (map f (seq start len))). {\n      clear; intros * Hij.\n      remember (seq start len) as l eqn:Hl; symmetry in Hl.\n      revert start len Hij Hl; induction l as [| i l]; intros; [ constructor | ].\n      rewrite map_cons; constructor. {\n        intros H1.\n        apply in_map_iff in H1.\n        destruct H1 as (j & Hji & Hj).\n        destruct len; [ easy | cbn in Hl ].\n        injection Hl; clear Hl; intros Hl Hb; subst i.\n        specialize (Hij start j) as H1.\n        assert (H : start < j < start + S len). {\n          rewrite <- Hl in Hj.\n          apply in_seq in Hj; flia Hj.\n        }\n        specialize (H1 H); clear H.\n        now symmetry in Hji.\n      }\n      destruct len; [ easy | ].\n      injection Hl; clear Hl; intros Hl Hi.\n      apply (IHl (S start) len); [ | easy ].\n      intros j k Hjk.\n      apply Hij; flia Hjk.\n    }\n    apply H.\n    now replace (1 + (p - 1)) with p by flia Hpz.\n  }\n}\nremember (λ i : nat, (i * a) mod p) as f eqn:Hf.\nremember (fold_left Nat.mul (map f (seq 1 (p - 1))) 1) as x eqn:Hx.\nassert (Hx1 : x mod p = fact (p - 1) mod p). {\n  subst x.\n  erewrite Permutation_fold_mul; [ | apply Hperm ].\n  f_equal.\n  clear.\n  (* lemma perhaps? *)\n  remember (p - 1) as n; clear p Heqn.\n  symmetry.\n  apply fact_eq_fold_left.\n}\nassert (Hx2 : x mod p = (fact (p - 1) * a ^ (p - 1)) mod p). {\n  subst x; rewrite Hf.\n  rewrite <- (map_map (λ i, i * a) (λ j, j mod p)).\n  rewrite fold_left_mul_map_mod.\n  rewrite fold_left_mul_map_mul.\n  rewrite seq_length.\n  f_equal; f_equal.\n  symmetry.\n  apply fact_eq_fold_left.\n}\nrewrite Hx2 in Hx1.\nrewrite <- (Nat.mul_1_r (fact _)) in Hx1 at 2.\napply Nat_mul_mod_cancel_l in Hx1. 2: {\n  rewrite Nat.gcd_comm.\n  apply Nat_gcd_prime_fact_lt; [ easy | flia Hpz ].\n}\nrewrite (Nat.mod_small 1) in Hx1; [ easy | flia Hap ].\nQed.\n\n(* proof simpler than fermat_little; but could be a corollary *)\nTheorem fermat_little_1 : ∀ p, prime p → ∀ a, a ^ p mod p = a mod p.\nProof.\nintros * Hp *.\ninduction a. {\n  rewrite Nat.pow_0_l; [ easy | ].\n  now intros H; rewrite H in Hp.\n}\nrewrite <- Nat.add_1_r.\nrewrite sum_power_prime_mod; [ | easy ].\nrewrite Nat.pow_1_l.\nrewrite <- Nat.add_mod_idemp_l; [ | now intros H; rewrite H in Hp ].\nrewrite IHa.\nrewrite Nat.add_mod_idemp_l; [ easy | now intros H; rewrite H in Hp ].\nQed.\n\n(* inverse modulo (true when n is prime) *)\n\nDefinition inv_mod i n := Nat_pow_mod i (n - 2) n.\n\nTheorem pow_mod_prime_ne_0 : ∀ i n p,\n  prime p\n  → 1 ≤ i < p\n  → i ^ n mod p ≠ 0.\nProof.\nintros * Hp Hip Hinp.\nassert (Hpz : p ≠ 0) by now intros H; rewrite H in Hp.\napply Nat.mod_divide in Hinp; [ | easy ].\ninduction n. {\n  cbn in Hinp.\n  destruct Hinp as (c, Hc).\n  symmetry in Hc.\n  apply Nat.eq_mul_1 in Hc.\n  now rewrite (proj2 Hc) in Hp.\n}\ncbn in Hinp.\nspecialize (Nat.gauss _ _ _ Hinp) as H1.\nassert (H : Nat.gcd p i = 1) by now apply eq_gcd_prime_small_1.\nspecialize (H1 H); clear H.\napply IHn, H1.\nQed.\n\nTheorem inv_mod_interv : ∀ p, prime p →\n  ∀ i, 2 ≤ i ≤ p - 2 → 2 ≤ inv_mod i p ≤ p - 2.\nProof.\nintros * Hp * Hip.\nassert (Hpz : p ≠ 0) by now intros H; rewrite H in Hp.\nunfold inv_mod.\nrewrite Nat_pow_mod_is_pow_mod; [ | now intros H; subst p ].\nsplit. {\n  apply Nat.nlt_ge; intros Hi.\n  remember (i ^ (p - 2) mod p) as j eqn:Hj; symmetry in Hj.\n  destruct j. {\n    revert Hj.\n    apply pow_mod_prime_ne_0; [ easy | flia Hip ].\n  }\n  destruct j; [ clear Hi | flia Hi ].\n  specialize (fermat_little p Hp i) as H1.\n  assert (H : 1 ≤ i < p) by flia Hip.\n  specialize (H1 H); clear H.\n  replace (p - 1) with (S (p - 2)) in H1 by flia Hip.\n  cbn in H1.\n  rewrite <- Nat.mul_mod_idemp_r in H1; [ | easy ].\n  rewrite Hj, Nat.mul_1_r in H1.\n  rewrite Nat.mod_small in H1; [ flia Hip H1 | flia Hip ].\n} {\n  apply Nat.nlt_ge; intros Hi.\n  remember (i ^ (p - 2) mod p) as j eqn:Hj; symmetry in Hj.\n  replace j with (p - 1) in Hj. 2: {\n    specialize (Nat.mod_upper_bound (i ^ (p - 2)) p Hpz) as H1.\n    rewrite Hj in H1; flia Hi H1.\n  }\n  clear j Hi.\n  specialize (fermat_little p Hp i) as H1.\n  assert (H : 1 ≤ i < p) by flia Hip.\n  specialize (H1 H); clear H.\n  replace (p - 1) with (S (p - 2)) in H1 by flia Hip.\n  cbn in H1.\n  rewrite <- Nat.mul_mod_idemp_r in H1; [ | easy ].\n  rewrite Hj in H1.\n  replace 1 with (1 mod p) in H1 at 2; [ | rewrite Nat.mod_small; flia Hip ].\n  apply Nat_eq_mod_sub_0 in H1.\n  apply Nat.mod_divide in H1; [ | easy ].\n  destruct H1 as (c, Hc).\n  rewrite Nat.mul_sub_distr_l, Nat.mul_1_r in Hc.\n  rewrite <- Nat.sub_add_distr in Hc.\n  assert (H : Nat.divide p (i + 1)). {\n    exists (i - c).\n    rewrite Nat.mul_sub_distr_r, <- Hc.\n    rewrite Nat_sub_sub_distr. 2: {\n      split; [ | easy ].\n      destruct p; [ easy | ].\n      rewrite Nat.mul_succ_r.\n      destruct i; [ easy | ].\n      destruct p; [ easy | flia ].\n    }\n    now rewrite Nat.sub_diag, Nat.add_0_l.\n  }\n  clear Hc; rename H into Hc.\n  apply Nat.divide_pos_le in Hc; [ | flia ].\n  flia Hip Hc.\n}\nQed.\n\nTheorem inv_mod_neq : ∀ p, prime p → ∀ i, 2 ≤ i ≤ p - 2 → inv_mod i p ≠ i.\nProof.\nintros * Hp * Hip Hcon.\nassert (Hpz : p ≠ 0) by now intros H; rewrite H in Hp.\nunfold inv_mod in Hcon.\nrewrite Nat_pow_mod_is_pow_mod in Hcon; [ | now intros H; subst p ].\nspecialize (fermat_little_1 p Hp i) as H1.\nrewrite (Nat.mod_small i) in H1; [ | flia Hip ].\nrewrite <- Hcon in H1 at 2.\napply Nat_eq_mod_sub_0 in H1.\nreplace p with (p - 2 + 2) in H1 at 1 by flia Hip.\nrewrite <- (Nat.mul_1_r (_ ^ (p - 2))) in H1.\nrewrite Nat.pow_add_r in H1.\nrewrite <- Nat.mul_sub_distr_l in H1.\nrewrite <- Nat.mul_mod_idemp_l in H1; [ | easy ].\nrewrite Hcon in H1.\napply Nat.mod_divide in H1; [ | easy ].\nspecialize (Nat.gauss _ _ _ H1) as H2.\nassert (H : Nat.gcd p i = 1). {\n  apply eq_gcd_prime_small_1; [ easy | flia Hip ].\n}\nspecialize (H2 H); clear H.\nrewrite Nat_sqr_sub_1 in H2.\nspecialize (Nat.gauss _ _ _ H2) as H3.\nassert (H : Nat.gcd p (i + 1) = 1). {\n  apply eq_gcd_prime_small_1; [ easy | flia Hip ].\n}\nspecialize (H3 H); clear H.\napply Nat.divide_pos_le in H3; [ flia Hip H3 | flia Hip ].\nQed.\n\nTheorem mul_inv_diag_l_mod : ∀ p,\n  prime p → ∀i, 1 ≤ i ≤ p - 1 → (inv_mod i p * i) mod p = 1.\nProof.\nintros * Hp * Hip.\nassert (Hpz : p ≠ 0) by now intros H; rewrite H in Hp.\nunfold inv_mod.\nrewrite Nat_pow_mod_is_pow_mod; [ | easy ].\nrewrite Nat.mul_mod_idemp_l; [ | easy ].\nreplace i with (i ^ 1) at 2 by now rewrite Nat.pow_1_r.\nrewrite <- Nat.pow_add_r.\nreplace (p - 2 + 1) with (p - 1) by flia Hip.\napply fermat_little; [ easy | flia Hip ].\nQed.\n\nTheorem mul_inv_diag_r_mod : ∀ p,\n  prime p → ∀ i, 1 ≤ i ≤ p - 1 → (i * inv_mod i p) mod p = 1.\nProof. now intros; rewrite Nat.mul_comm; apply mul_inv_diag_l_mod. Qed.\n\nLemma eq_fold_left_mul_seq_2_prime_sub_3_1 : ∀ p,\n  prime p\n  → 3 ≤ p\n  → fold_left Nat.mul (seq 2 (p - 3)) 1 mod p = 1.\nProof.\nintros * Hp H3p.\nassert (Hpz : p ≠ 0) by now intros H; rewrite H in Hp.\nspecialize (seq_NoDup (p - 3) 2) as Hnd.\nremember (seq 2 (p - 3)) as l eqn:Hl.\nassert\n  (Hij : ∀ i, i ∈ l →\n   ∃j, j ∈ l ∧ i ≠ j ∧ (i * j) mod p = 1 ∧\n        ∀ k, k ∈ l → k ≠ i → (k * j) mod p ≠ 1). {\n  intros i Hi.\n  exists (inv_mod i p).\n  subst l.\n  apply in_seq in Hi.\n  assert (H1 : inv_mod i p ∈ seq 2 (p - 3)). {\n    apply in_seq.\n    specialize (inv_mod_interv p Hp i) as H1.\n    assert (H : 2 ≤ i ≤ p - 2) by flia Hi.\n    specialize (H1 H); flia H1.\n  }\n  split; [ easy | ].\n  assert (H2 : i ≠ inv_mod i p). {\n    apply not_eq_sym.\n    apply inv_mod_neq; [ easy | flia Hi ].\n  }\n  split; [ easy | ].\n  assert (H3 : (i * inv_mod i p) mod p = 1). {\n    apply mul_inv_diag_r_mod; [ easy | flia Hi ].\n  }\n  split; [ easy | ].\n  intros k Hkl Hki Hk.\n  apply Hki; clear Hki.\n  rewrite <- H3 in Hk.\n  destruct (Nat.eq_dec i k) as [Hink| Hink]; [ easy | ].\n  destruct (le_dec i k) as [Hik| Hik]. {\n    apply Nat_mul_mod_cancel_r in Hk. 2: {\n      rewrite Nat.gcd_comm.\n      apply in_seq in H1.\n      apply eq_gcd_prime_small_1; [ easy | flia H1 ].\n    }\n    apply in_seq in Hkl.\n    rewrite Nat.mod_small in Hk; [ | flia Hkl ].\n    rewrite Nat.mod_small in Hk; [ easy | ].\n    apply (le_lt_trans _ k); [ easy | flia Hkl ].\n  }\n  apply Nat.nle_gt in Hik.\n  symmetry in Hk.\n  apply Nat_eq_mod_sub_0 in Hk.\n  rewrite <- Nat.mul_sub_distr_r in Hk.\n  apply Nat.mod_divide in Hk; [ | easy ].\n  specialize (Nat.gauss _ _ _ Hk) as H4.\n  assert (H : Nat.gcd p (i - k) = 1). {\n    apply eq_gcd_prime_small_1; [ easy | ].\n    apply in_seq in Hkl.\n    flia Hi Hkl Hink Hik.\n  }\n  specialize (H4 H); clear H.\n  apply Nat.mod_divide in H4; [ | easy ].\n  rewrite Nat.mod_small in H4. 2: {\n    unfold inv_mod.\n    rewrite Nat_pow_mod_is_pow_mod; [ | easy ].\n    now apply Nat.mod_upper_bound.\n  }\n  rewrite H4 in H1.\n  apply in_seq in H1; flia H1.\n}\nclear Hl.\nremember (length l) as len eqn:Hlen; symmetry in Hlen.\nrevert l Hnd Hij Hlen.\ninduction len as (len, IHlen) using lt_wf_rec; intros.\ndestruct len. {\n  apply length_zero_iff_nil in Hlen.\n  subst l; cbn; rewrite Nat.mod_1_l; flia H3p.\n}\ndestruct l as [| a l]; [ easy | ].\nspecialize (Hij a (or_introl (eq_refl _))) as H1.\ndestruct H1 as (i2 & Hi2l & Hai2 & Hai2p & Hk).\ndestruct Hi2l as [Hi2l| Hi2l]; [ easy | ].\nspecialize (in_split i2 l Hi2l) as (l1 & l2 & Hll).\nrewrite Hll.\ncbn; rewrite Nat.add_0_r.\nrewrite fold_left_app; cbn.\nrewrite fold_left_mul_from_1.\nrewrite Nat.mul_shuffle0, Nat.mul_comm.\nrewrite fold_left_mul_from_1.\ndo 2 rewrite Nat.mul_assoc.\nremember (i2 * 2) as x.\nrewrite <- Nat.mul_assoc; subst x.\nrewrite <- Nat.mul_mod_idemp_l; [ | flia H3p ].\nrewrite (Nat.mul_comm i2).\nrewrite Hai2p, Nat.mul_1_l.\nrewrite Nat.mul_comm.\nrewrite List_fold_left_mul_assoc, Nat.mul_1_l.\nrewrite <- fold_left_app.\napply (IHlen (len - 1)); [ flia | | | ]. 3: {\n  cbn in Hlen.\n  apply Nat.succ_inj in Hlen.\n  rewrite <- Hlen, Hll.\n  do 2 rewrite app_length.\n  cbn; flia.\n} {\n  apply NoDup_cons_iff in Hnd.\n  destruct Hnd as (_, Hnd).\n  rewrite Hll in Hnd.\n  now apply NoDup_remove_1 in Hnd.\n}\nintros i Hi.\nspecialize (Hij i) as H1.\nassert (H : i ∈ a :: l). {\n  right; rewrite Hll.\n  apply in_app_or in Hi.\n  apply in_or_app.\n  destruct Hi as [Hi| Hi]; [ now left | now right; right ].\n}\nspecialize (H1 H); clear H.\ndestruct H1 as (j & Hjall & Hinj & Hijp & Hk').\nexists j.\nsplit. {\n  destruct Hjall as [Hjall| Hjall]. {\n    subst j; exfalso.\n    specialize (Hk' i2) as H1.\n    assert (H : i2 ∈ a :: l). {\n      now rewrite Hll; right; apply in_or_app; right; left.\n    }\n    specialize (H1 H); clear H.\n    assert (H : i2 ≠ i). {\n      intros H; subst i2.\n      move Hnd at bottom; move Hi at bottom.\n      apply NoDup_cons_iff in Hnd.\n      destruct Hnd as (_, Hnd).\n      rewrite Hll in Hnd.\n      now apply NoDup_remove_2 in Hnd.\n    }\n    specialize (H1 H).\n    now rewrite Nat.mul_comm in H1.\n  }\n  rewrite Hll in Hjall.\n  apply in_app_or in Hjall.\n  apply in_or_app.\n  destruct Hjall as [Hjall| Hjall]; [ now left | ].\n  destruct Hjall as [Hjall| Hjall]; [ | now right ].\n  subst j.\n  destruct (Nat.eq_dec a i) as [Hai| Hai]. {\n    subst i.\n    move Hnd at bottom.\n    apply NoDup_cons_iff in Hnd.\n    destruct Hnd as (Hnd, _).\n    exfalso; apply Hnd; clear Hnd.\n    rewrite Hll.\n    apply in_app_or in Hi.\n    apply in_or_app.\n    destruct Hi as [Hi| Hi]; [ now left | now right; right ].\n  }\n  now specialize (Hk' a (or_introl eq_refl) Hai) as H2.\n}\nsplit; [ easy | ].\nsplit; [ easy | ].\nintros k Hkll Hki.\napply Hk'; [ | easy ].\nright.\nrewrite Hll.\napply in_app_or in Hkll.\napply in_or_app.\ndestruct Hkll as [Hkll| Hkll]; [ now left | now right; right ].\nQed.\n\nTheorem Wilson : ∀ n, 2 ≤ n → prime n ↔ fact (n - 1) mod n = n - 1.\nProof.\nintros * H2n.\nsplit.\n-intros Hn.\n destruct (lt_dec n 3) as [H3n| H3n]. {\n   now replace n with 2 by flia H2n H3n.\n }\n apply Nat.nlt_ge in H3n.\n replace (n - 1) with (S (n - 2)) at 1 by flia H3n.\n rewrite Nat_fact_succ.\n replace (S (n - 2)) with (n - 1) by flia H3n.\n rewrite <- Nat.mul_mod_idemp_r; [ | flia H3n ].\n enough (H : fact (n - 2) mod n = 1). {\n   rewrite H, Nat.mul_1_r.\n   apply Nat.mod_small; flia H3n.\n }\n rewrite fact_eq_fold_left.\n enough (H : fold_left Nat.mul (seq 2 (n - 3)) 1 mod n = 1). {\n   replace (seq 1 (n - 2)) with (1 :: seq 2 (n - 3)). 2: {\n     clear - H3n.\n     destruct n; [ flia H3n | ].\n     destruct n; [ flia H3n | ].\n     destruct n; [ flia H3n | ].\n     now cbn; rewrite Nat.sub_0_r.\n   }\n   easy.\n }\n (* now we must prove that the multiplication can be done by\n    associating pairs of (a, b) in interval [2, n-2] such that\n    a * b ≡ 1 (mod n). We know by Fermat's little theorem that\n    a * a^(n-2) indeed equals 1 mod n. So b=a^(n-2) mod n. All\n    these pairs are supposed to cover [2, n-2] *)\n now apply eq_fold_left_mul_seq_2_prime_sub_3_1.\n-intros Hf.\n destruct (lt_dec 5 n) as [H5n| H5n]. {\n   unfold prime.\n   apply Bool.not_false_iff_true; intros H1.\n   assert (H : ¬ prime n) by now unfold prime; rewrite H1.\n   apply Wilson_on_composite in H; [ | easy ].\n   rewrite H in Hf.\n   flia Hf H5n.\n }\n apply Nat.nlt_ge in H5n.\n destruct n; [ easy | ].\n destruct n; [ flia H2n | ].\n destruct n; [ easy | ].\n destruct n; [ easy | ].\n destruct n; [ easy | ].\n destruct n; [ easy | flia H5n ].\nQed.\n\n(* *)\n\nTheorem inv_mod_prime_involutive : ∀ p,\n  prime p\n  → ∀ i, 2 ≤ i ≤ p - 2\n  → inv_mod (inv_mod i p) p = i.\nProof.\nintros * Hp * Hip.\nassert (Hpz : p ≠ 0) by now intros H; rewrite H in Hp.\nunfold inv_mod.\nrewrite Nat_pow_mod_is_pow_mod; [ | now intros H; subst p ].\nrewrite Nat_pow_mod_is_pow_mod; [ | now intros H; subst p ].\nrewrite Nat_mod_pow_mod.\nrewrite <- Nat.pow_mul_r.\nrewrite <- Nat.pow_2_r.\nrewrite Nat_sqr_sub; [ | flia Hip ].\nrewrite Nat.mul_shuffle0.\nreplace (2 ^ 2) with 4 by easy.\nreplace (2 * 2) with 4 by easy.\nrewrite Nat.pow_2_r.\nrewrite Nat.add_sub_swap. 2: {\n  apply Nat.mul_le_mono_r.\n  flia Hip.\n}\nrewrite <- Nat.mul_sub_distr_r.\nrewrite Nat.pow_add_r.\nrewrite Nat.pow_mul_r.\nrewrite <- Nat.mul_mod_idemp_l; [ | easy ].\nrewrite <- Nat_mod_pow_mod.\nrewrite fermat_little_1; [ | easy ].\nrewrite Nat.mod_mod; [ | easy ].\nrewrite Nat.mul_mod_idemp_l; [ | easy ].\nrewrite <- Nat.pow_add_r.\nrewrite Nat.sub_add; [ | flia Hip ].\nrewrite fermat_little_1; [ | easy ].\napply Nat.mod_small; flia Hip.\nQed.\n\nTheorem odd_prime : ∀ p, prime p → p ≠ 2 → p mod 2 = 1.\nProof.\nintros * Hp Hp2.\nremember (p mod 2) as r eqn:Hp2z; symmetry in Hp2z.\ndestruct r. 2: {\n  destruct r; [ easy | ].\n  specialize (Nat.mod_upper_bound p 2 (Nat.neq_succ_0 _)) as H1.\n  flia Hp2z H1.\n}\nexfalso.\napply Nat.mod_divides in Hp2z; [ | easy ].\ndestruct Hp2z as (d, Hd).\ndestruct (lt_dec d 2) as [Hd2| Hd2]. {\n  destruct d; [ now subst p; rewrite Nat.mul_0_r in Hp | ].\n  destruct d; [ now subst p | flia Hd2 ].\n}\napply Nat.nlt_ge in Hd2.\nspecialize (prime_prop p Hp d) as H1.\nassert (H : 2 ≤ d ≤ p - 1). {\n  split; [ easy | flia Hd ].\n}\nspecialize (H1 H); clear H.\napply H1; clear H1.\nrewrite Hd.\napply Nat.divide_factor_r.\nQed.\n\nTheorem prime_not_mul : ∀ p q, prime (p * q) → p = 1 ∨ q = 1.\nProof.\nintros * Hpq.\ndestruct (lt_dec p 2) as [H2p| H2p]. {\n  destruct p; [ easy | ].\n  destruct p; [ now left | flia H2p ].\n}\ndestruct (lt_dec q 2) as [H2q| H2q]. {\n  rewrite Nat.mul_comm in Hpq.\n  destruct q; [ easy | ].\n  destruct q; [ now right | flia H2q ].\n}\napply Nat.nlt_ge in H2p.\napply Nat.nlt_ge in H2q.\nexfalso.\napply prime_only_divisors with (a := p) in Hpq. {\n  destruct Hpq as [Hpq| Hpq]; [ flia Hpq H2p | ].\n  replace p with (p * 1) in Hpq at 1 by flia.\n  apply Nat.mul_cancel_l in Hpq; [ | flia H2p ].\n  flia Hpq H2q.\n}\napply Nat.divide_factor_l.\nQed.\n\nDefinition divisors n := List.filter (λ a, n mod a =? 0) (List.seq 1 n).\n\nDefinition prime_divisors n :=\n  filter (λ d, (is_prime d && (n mod d =? 0))%bool) (seq 1 n).\n", "meta": {"author": "roglo", "repo": "coq_euler_prod_form", "sha": "30dae9698b21909f0d2cf84ca20995fcd491b50b", "save_path": "github-repos/coq/roglo-coq_euler_prod_form", "path": "github-repos/coq/roglo-coq_euler_prod_form/coq_euler_prod_form-30dae9698b21909f0d2cf84ca20995fcd491b50b/Primes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318195, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.6908320890852682}}
{"text": "\nSet Implicit Arguments.\n\nCoInductive LList (A:Type) : Type :=\n  | LNil : LList A\n  | LCons : A -> LList A -> LList A.\n\nImplicit Arguments LNil [A].\n\nCoInductive Infinite {A:Type} : LList A -> Prop :=\n    Infinite_LCons :\n      forall (a:A) (l:LList A), Infinite l -> Infinite (LCons a l).\n\nHint Constructors Infinite.\n\n \n\nDefinition Infinite_ok {A:Type} (X:LList A -> Prop) : Prop :=\n  forall l:LList A,\n    X l ->  exists a : A, exists l' : LList A, l = LCons a l' /\\ X l'.\n\nDefinition Infinite_alt {A:Type} (l:LList A) :=\n   exists X : LList A -> Prop, Infinite_ok X /\\ X l.\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/ch13_co_inductive_types/SRC/infinite_impred_prelude.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6908320867994727}}
{"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 drop (drop_arg0 : natural) (drop_arg1 : lst) : lst\n           := match drop_arg0, drop_arg1 with\n              | x, Nil => Nil\n              | Zero, x => x\n              | Succ x, Cons y z => drop x z\n              end.\n\nLemma lem: forall n1 n2 l, drop (Succ n1) (drop n2 l) = drop n1 (drop (Succ n2) l).\nProof.\nintros. generalize dependent n1. generalize dependent n2. induction l.\n- intros. assert (forall n x l, drop (Succ n) (Cons x l) = drop n l). \n  + intros. reflexivity.\n  + destruct n2.\n    * rewrite H. rewrite H. rewrite <- IHl. reflexivity.\n    * simpl. destruct l. reflexivity. reflexivity.\n- intros. assert (forall n, drop n Nil = Nil).\n  + intros. destruct n. reflexivity. reflexivity.\n  + rewrite H. rewrite H. rewrite H. reflexivity.\nQed.\n\nTheorem theorem0 : forall (u : natural) (v : natural) (w : natural) (x : natural) (y : natural) (z : lst),\n  eq (drop (Succ u) (drop v (drop (Succ w) (Cons x (Cons y z))))) (drop (Succ u) (drop v (drop w (Cons x z)))).\nProof.\nintros. \nrewrite lem. \nrewrite lem. \nrewrite lem.\nrewrite lem. 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/goal57.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530937, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6908320799286369}}
{"text": "(*|\n#########################################\nCoq QArith division by zero is zero, why?\n#########################################\n\n:Link: https://stackoverflow.com/q/29282819\n|*)\n\n(*|\nQuestion\n********\n\nI noticed that in Coq's definition of rationals the inverse of zero is\ndefined to zero. (Usually, division by zero is not\nwell-defined/legal/allowed.)\n|*)\n\nRequire Import QArith.\nLemma inv_zero_is_zero: (/ 0) == 0.\nProof. unfold Qeq. reflexivity. Qed.\n\n(*|\nWhy is it so?\n\nCould it cause problems in calculations with rationals, or is it safe?\n|*)\n\n(*|\nAnswer\n******\n\nThe short answer is: yes, it is absolutely safe.\n\nWhen we say that division by zero is not well-defined, what we\nactually mean is that zero doesn't have a multiplicative inverse. In\nparticular, we can't have a function that computes a multiplicative\ninverse for zero. However, it is possible to write a function that\ncomputes the multiplicative inverse for all other elements, and\nreturns some arbitrary value when such an inverse doesn't exists (e.g.\nfor zero). This is exactly what this function is doing.\n\nHaving this inverse operator be defined everywhere means that we'll be\nable to define other functions that compute with it without having to\nargue explicitly that its argument is different from zero, making it\nmore convenient to use. Indeed, imagine what a pain it would be if we\nmade this function return an ``option`` instead, failing when we pass\nit zero: we would have to make our entire code monadic, making it\nharder to understand and reason about. We would have a similar problem\nif writing a function that requires a proof that its argument is\nnon-zero.\n\nSo, what's the catch? Well, when trying to prove anything about a\nfunction that uses the inverse operator, we will have to add explicit\nhypotheses saying that we're passing it an argument that is different\nfrom zero, or argue that its argument can never be zero. The lemmas\nabout this function then get additional preconditions, e.g.\n|*)\n\nCheck Qmult_inv_r. (* .unfold .messages *)\n\n(*|\nMany other libraries are structured like that, cf. for instance the\ndefinition of the `field axioms\n<http://ssr.msr-inria.inria.fr/~jenkins/current/Ssreflect.ssralg.html>`__\nin the algebra library of MathComp.\n\nThere *are* some cases where we want to internalize the additional\npreconditions required by certain functions as type-level constraints.\nThis is what we do for instance when we use *length-indexed vectors*\nand a safe ``get`` function that can only be called on numbers that\nare in bounds. So how do we decide which one to go for when designing\na library, i.e. whether to use a rich type with a lot of extra\ninformation and prevent bogus calls to certain functions (as in the\nlength-indexed case) or to leave this information out and require it\nas explicit lemmas (as in the multiplicative inverse case)? Well,\nthere's no definite answer here, and one really needs to analyze each\ncase individually and decide which alternative will be better for that\nparticular case.\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-qarith-division-by-zero-is-zero-why.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.6907987555742311}}
{"text": "Require Import Bool Arith List Cpdt.CpdtTactics.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nSection list.\n  Variable T : Set.\n\n  Inductive list : Set :=\n  | Nil : list\n  | Cons : T -> list -> list.\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) = plus (length ls1) (length ls2).\n    induction ls1; crush.\n  Qed.\nEnd list.\n\nArguments Nil [T].\n\nPrint list.\n\nCheck length.\n\nCheck list_ind.\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-4-2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181876, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6907862618197672}}
{"text": "Require Export FilterLimits.\nRequire Export Nets.\n\nSection net_tail_filter.\n\nVariable X:TopologicalSpace.\nVariable J:DirectedSet.\nVariable x:Net J X.\nHypothesis J_nonempty: inhabited (DS_set J).\n\nDefinition net_tail (j:DS_set J) :=\n  Im [ i:DS_set J | DS_ord j i ] x.\n\nDefinition tail_filter_basis : Family (point_set X) :=\n  Im Full_set net_tail.\n\nDefinition tail_filter : Filter (point_set X).\nrefine (Build_Filter_from_basis tail_filter_basis _ _ _).\ndestruct J_nonempty as [j].\nexists (net_tail j).\nexists j; trivial.\nconstructor.\nintro.\ninversion H as [j].\nassert (In Empty_set (x j)).\nrewrite H1.\nexists j; trivial.\nconstructor.\napply preord_refl; apply DS_ord_cond.\ndestruct H3.\n\nintros.\ndestruct H.\ndestruct H0.\ndestruct (DS_join_cond x0 x1) as [k []].\nexists (net_tail k); split.\nexists k; trivial.\nconstructor.\nred; intros.\nconstructor.\ndestruct H5 as [i0].\ndestruct H5.\nrewrite H1.\nexists i0; trivial.\nconstructor.\napply preord_trans with k; trivial.\napply DS_ord_cond.\ndestruct H5 as [i0].\ndestruct H5.\nrewrite H2.\nexists i0; trivial.\nconstructor.\napply preord_trans with k; trivial.\napply DS_ord_cond.\nDefined.\n\nLemma net_limit_impl_tail_filter_limit: forall x0:point_set X,\n  net_limit x x0 -> filter_limit tail_filter x0.\nProof.\nintros.\nred; intros.\nred; intros U ?.\ndestruct H0.\ndestruct H0 as [V []].\ndestruct H0.\npose proof (H V H0 H2).\ndestruct H3 as [j0].\napply filter_upward_closed with (net_tail j0).\nconstructor.\nexists (net_tail j0).\nsplit.\nexists j0; trivial.\nconstructor.\nauto with sets.\nintros y ?.\napply H1.\ndestruct H4 as [j].\nrewrite H5.\napply H3.\ndestruct H4; assumption.\nQed.\n\nLemma tail_filter_limit_impl_net_limit: forall x0:point_set X,\n  filter_limit tail_filter x0 -> net_limit x x0.\nProof.\nintros.\nintros U ? ?.\nassert (In (filter_family tail_filter) U).\napply H.\nconstructor.\napply open_neighborhood_is_neighborhood.\nsplit; trivial.\ndestruct H2.\ndestruct H2 as [T []].\ndestruct H2 as [j0].\nexists j0.\nintros.\napply H3.\nrewrite H4.\nexists j; trivial.\nconstructor; assumption.\nQed.\n\nLemma net_cluster_point_impl_tail_filter_cluster_point:\n  forall x0:point_set X,\n  net_cluster_point x x0 -> filter_cluster_point tail_filter x0.\nProof.\nintros.\nred; intros.\ndestruct H0.\ndestruct H0 as [T []].\ndestruct H0 as [j0].\napply meets_every_open_neighborhood_impl_closure.\nintros.\npose proof (H U H3 H4).\ndestruct (H5 j0) as [j' []].\nexists (x j').\nconstructor; trivial.\napply H1.\nrewrite H2.\nexists j'.\nconstructor; trivial.\nreflexivity.\nQed.\n\nLemma tail_filter_cluster_point_impl_net_cluster_point:\n  forall x0:point_set X,\n  filter_cluster_point tail_filter x0 -> net_cluster_point x x0.\nProof.\nintros.\nred; intros.\nred; intros.\nassert (In (closure (net_tail i)) x0).\napply H.\nconstructor.\nexists (net_tail i).\nsplit.\nexists i; trivial.\nconstructor.\nauto with sets.\npose proof (closure_impl_meets_every_open_neighborhood _ _ _ H2\n  U H0 H1).\ndestruct H3.\ndestruct H3.\ndestruct H3.\nexists x1; split.\ndestruct H3; trivial.\nrewrite <- H5; trivial.\nQed.\n\nEnd net_tail_filter.\n\nImplicit Arguments net_tail [[X] [J]].\nImplicit Arguments tail_filter [[X] [J]].\n\nSection filter_to_net.\n\nVariable X:TopologicalSpace.\nVariable F:Filter (point_set X).\n\nRecord filter_to_net_DS_set : Type := {\n  ftn_S : Ensemble (point_set X);\n  ftn_x : point_set X;\n  ftn_S_in_F : In (filter_family F) ftn_S;\n  ftn_x_in_S : In ftn_S ftn_x\n}.\n\nDefinition filter_to_net_DS : DirectedSet.\nrefine (Build_DirectedSet filter_to_net_DS_set\n  (fun x1 x2:filter_to_net_DS_set =>\n     Included (ftn_S x2) (ftn_S x1)) _ _).\nconstructor.\nred; intros.\nauto with sets.\nred; intros.\nauto with sets.\nintros.\ndestruct i.\ndestruct j.\nassert (In (filter_family F) (Intersection ftn_S0 ftn_S1)).\napply filter_intersection; trivial.\nassert (Inhabited (Intersection ftn_S0 ftn_S1)).\napply NNPP; red; intro.\nassert (Intersection ftn_S0 ftn_S1 = Empty_set).\napply Extensionality_Ensembles; split; red; intros.\ncontradiction H0.\nexists x; trivial.\ndestruct H1.\nrewrite H1 in H.\ncontradiction (filter_empty _ F).\ndestruct H0 as [ftn_x'].\nexists (Build_filter_to_net_DS_set\n  (Intersection ftn_S0 ftn_S1) ftn_x' H H0).\nsimpl.\nsplit; auto with sets.\nDefined.\n\nDefinition filter_to_net : Net filter_to_net_DS X :=\n  ftn_x.\n\nLemma filter_limit_impl_filter_to_net_limit: forall x0:point_set X,\n  filter_limit F x0 -> net_limit filter_to_net x0.\nProof.\nintros.\nintros U ? ?.\nassert (In (filter_family F) U).\napply H.\nconstructor.\napply open_neighborhood_is_neighborhood.\nsplit; trivial.\nexists (Build_filter_to_net_DS_set U x0 H2 H1).\ndestruct j.\nsimpl.\nauto.\nQed.\n\nLemma filter_to_net_limit_impl_filter_limit: forall x0:point_set X,\n  net_limit filter_to_net x0 -> filter_limit F x0.\nProof.\nintros.\nintros U ?.\ndestruct H0.\ndestruct H0 as [V []].\napply filter_upward_closed with V; trivial.\ndestruct H0.\ndestruct (H V H0 H2) as [[]].\napply filter_upward_closed with ftn_S0.\ntrivial.\nred; intros.\npose proof (H3\n  (Build_filter_to_net_DS_set ftn_S0 x ftn_S_in_F0 H4)).\nsimpl in H5.\napply H5; auto with sets.\nQed.\n\nLemma filter_cluster_point_impl_filter_to_net_cluster_point:\n  forall x0:point_set X,\n  filter_cluster_point F x0 -> net_cluster_point filter_to_net x0.\nProof.\nintros.\nred; intros.\nred; intros.\ndestruct i.\npose proof (H ftn_S0 ftn_S_in_F0).\npose proof (closure_impl_meets_every_open_neighborhood _ _\n  _ H2 U H0 H1).\ndestruct H3.\ndestruct H3.\nexists (Build_filter_to_net_DS_set ftn_S0 x ftn_S_in_F0 H3).\nsimpl.\nsplit; auto with sets.\nQed.\n\nLemma filter_to_net_cluster_point_impl_filter_cluster_point:\n  forall x0:point_set X,\n  net_cluster_point filter_to_net x0 -> filter_cluster_point F x0.\nProof.\nintros.\nred; intros.\napply meets_every_open_neighborhood_impl_closure; intros.\nassert (Inhabited S).\napply NNPP; red; intro.\nassert (S = Empty_set).\napply Extensionality_Ensembles; split; red; intros.\ncontradiction H3.\nexists x; trivial.\ndestruct H4.\nrewrite H4 in H0.\ncontradiction (filter_empty _ F).\ndestruct H3 as [y].\npose (j0 := Build_filter_to_net_DS_set S y H0 H3).\ndestruct (H U H1 H2 j0) as [j' []].\nexists (filter_to_net j').\nconstructor; trivial.\ndestruct j'.\nsimpl.\nsimpl in H5.\nsimpl in H4.\nauto.\nQed.\n\nEnd filter_to_net.\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/FiltersAndNets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6907862616400431}}
{"text": "Require Export DevCoq.Dev.basic_matroid_list.\n\nParameter rk_singleton_ge : forall P, rk (P :: nil)  >= 1.\nParameter rk_couple_ge : forall P Q, ~ P = Q -> rk(P :: Q :: nil) >= 2.\nParameter rk_three_points_on_lines : forall A B, exists C, rk (A :: B :: C :: nil) = 2 /\\ rk (B :: C :: nil) = 2 /\\ rk (A :: C :: nil) = 2.\nParameter rk_inter : forall A B C D, exists J, rk (A :: B :: J :: nil) = 2 /\\ rk (C :: D :: J :: nil) = 2.\nParameter rk_lower_dim : exists P0 P1 P2, rk( P0 :: P1 :: P2 :: nil) >=3.\n\nLemma rk_singleton_1 : forall A, rk(A :: nil) <= 1.\nProof.\nintros.\napply matroid1_b_useful.\nintuition.\nQed.\n\nLemma rk_singleton : forall A, rk(A :: nil) = 1.\nProof.\nintros.\nassert(H := rk_singleton_ge A).\nassert(HH := rk_singleton_1 A).\nomega.\nQed.\n\nLemma rk_couple_2 : forall A B, rk(A :: B :: nil) <= 2.\nProof.\nintros.\napply matroid1_b_useful.\nintuition.\nQed.\n\nLemma rk_couple : forall A B : Point,~ A = B -> rk(A :: B :: nil) = 2.\nProof.\nintros.\nassert(HH := rk_couple_2 A B).\nassert(HH0 := rk_couple_ge A B H).\nomega.\nQed.\n\nLemma rk_triple_3 : forall A B C : Point, rk (A :: B :: C :: nil) <= 3.\nProof.\nintros.\napply matroid1_b_useful.\nintuition.\nQed.\n\nLemma couple_rk1 : forall A B, rk(A :: B :: nil) = 2 -> ~ A = B.\nProof.\nintros.\nintro.\nrewrite H0 in H.\nassert(HH : equivlist (B :: B :: nil) (B :: nil));[my_inO|].\nrewrite HH in H.\nassert(HH0 := rk_singleton_1 B).\nomega.\nQed.\n\nLemma couple_rk2 : forall A B, rk(A :: B :: nil) = 1 -> A = B.\nProof.\nintros.\ncase_eq(eq_dec A B).\nintros.\nassumption.\nintros.\nassert(HH := rk_couple A B n).\nomega.\nQed.\n\nLemma rk_quadruple_inter_aux : forall A B C D E,\n~ A = C ->\n~ A = D ->\n~ B = C ->\n~ B = D -> \nrk(A :: B :: E :: nil) = 2 -> \nrk(C :: D :: E :: nil) = 2 ->\nrk(A :: B :: C :: D :: nil) = 2 \\/ rk(A :: B :: C :: D :: nil) = 3.\nProof.\nintros.\n\nassert (HH0 : rk((A :: B :: E :: nil) ++ (C :: D :: E :: nil)) + rk(list_inter (A :: B :: E :: nil) (C :: D :: E :: nil)) <=\n       rk(A :: B :: E :: nil) + rk(C :: D :: E :: nil)).\napply matroid3_useful;my_inO.\nassert(HH1 : equivlist (list_inter (A :: B :: E :: nil) (C :: D :: E :: nil))  (E :: nil)).\nmy_inO.\nassert(HH2 := rk_singleton E).\nrewrite HH1 in HH0.\nrewrite HH2 in HH0.\nrewrite H3 in HH0.\nrewrite H4 in HH0.\n\nassert(HH3 : rk(A :: B :: E :: C :: D :: E :: nil) = 2 \\/ rk(A :: B :: E :: C :: D :: E :: nil) = 3).\napply le_lt_or_eq in HH0;simpl in HH0.\ndestruct HH0.\nassert(HH4 : rk(A :: B :: E :: C :: D :: E :: nil) < 3).\nsolve[intuition].\nassert(HH5 : incl (A :: B :: E :: nil) (A :: B :: E :: C :: D :: E :: nil));[my_inO|].\nassert(HH6 := matroid2 (A :: B :: E :: nil) (A :: B :: E :: C :: D :: E :: nil) HH5).\nomega.\nomega.\n\ndestruct HH3.\n\nassert(HH3 := rk_couple A C H).\nassert(HH4 : incl (A :: C :: nil) (A :: B :: C :: D :: nil));[my_inO|].\nassert(HH5 : incl (A :: B :: C :: D :: nil) (A :: B :: E :: C :: D :: E :: nil));[my_inO|].\nassert(HH6 := matroid2 (A :: C :: nil) (A :: B :: C :: D :: nil) HH4).\nassert(HH7 := matroid2 (A :: B :: C :: D :: nil) (A :: B :: E :: C :: D :: E :: nil) HH5).\nomega.\n\nassert(HH3 : incl (A :: B :: C :: D :: nil) (A :: B :: E :: C :: D :: E :: nil));[my_inO|].\nassert(HH4 := matroid2 (A :: B :: C :: D :: nil) (A :: B :: E :: C :: D :: E :: nil) HH3).\nrewrite H5 in HH4.\napply le_lt_or_eq in HH4.\ndestruct HH4.\nassert(HH5 := rk_couple A C H).\nassert(HH6 : incl (A :: C :: nil) (A :: B :: C :: D :: nil));[my_inO|].\nassert(HH7 := matroid2 (A :: C :: nil) (A :: B :: C :: D :: nil) HH6).\nomega.\nomega.\nQed.\n\nLemma rk_quadruple_inter_aux2 : forall B C D E,\n~ B = C ->\n~ B = D -> \nrk(D :: B :: E :: nil) = 2 -> \nrk(C :: D :: E :: nil) = 2 ->\nrk(D :: B :: C :: D :: nil) = 2 \\/ rk(D :: B :: C :: D :: nil) = 3.\nProof.\nintros.\n\nassert (HH0 : rk((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) + rk(list_inter (D :: B :: E :: nil) (C :: D :: E :: nil)) <=\n       rk(D :: B :: E :: nil) + rk(C :: D :: E :: nil)).\napply matroid3_useful;my_inO.\nassert (HH1 : equivlist (list_inter (D :: B :: E :: nil) (C :: D :: E :: nil)) (D :: E :: nil));[my_inO|].\nrewrite HH1 in HH0.\ncase_eq(eq_dec D E).\nintros;subst.\nrewrite H1 in HH0;rewrite H2 in HH0.\nassert(HH2 : equivlist (E :: E :: nil) (E :: nil));[my_inO|].\nreplace (rk (E :: E :: nil)) with (rk(E :: nil)) in HH0.\n2:rewrite HH2;intuition.\nassert(HH3 := rk_singleton E).\nrewrite HH3 in HH0.\n\nassert(HH4 : rk(E :: B :: E :: C :: E :: E :: nil) = 2 \\/ rk((E :: B :: E :: C :: E :: E :: nil)) = 3).\napply le_lt_or_eq in HH0;simpl in HH0.\ndestruct HH0.\nassert(HH5 : rk((E :: B :: E :: C :: E :: E :: nil)) < 3).\nsolve[intuition].\nassert(HH4 : incl (E :: B :: E :: nil) (E :: B :: E :: C :: E :: E :: nil));[my_inO|].\nassert(HH6 := matroid2 (E :: B :: E :: nil) (E :: B :: E :: C :: E :: E :: nil) HH4).\nomega.\nomega.\n\nassert(HH5 : equivlist (E :: B :: E :: C :: E :: E :: nil) (E :: B :: C :: E :: nil));[my_inO|].\nrewrite HH5 in HH4.\nomega.\n\nintros.\nrewrite H1 in HH0;rewrite H2 in HH0.\nassert(HH2 := rk_couple D E n).\nrewrite HH2 in HH0.\nassert(HH3 : rk((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) = 2).\nassert(HH4 : incl (D :: E :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil))).\nmy_inO.\n\nassert(HH5 := matroid2 (D :: E :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) HH4). \nomega.\nassert(HH4 := rk_couple B C H).\nassert(HH5 : incl (B :: C :: nil) (D :: B :: C :: D :: nil));[my_inO|].\nassert(HH6 := matroid2 (B :: C :: nil) (D :: B :: C :: D :: nil) HH5).\nassert(HH7 : incl (D :: B :: C :: D :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil)));[my_inO|].\nassert(HH8 := matroid2 (D :: B :: C :: D :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) HH7).\nomega.\nQed.\n\nLemma rk_quadruple_inter : forall A B C D E,\nrk(A :: B :: E :: nil) = 2 -> \nrk(C :: D :: E :: nil) = 2 ->\nrk(A :: B :: C :: D :: nil) = 1 \\/ rk(A :: B :: C :: D :: nil) = 2 \\/ rk(A :: B :: C :: D :: nil) = 3.\nProof.\nintros.\ncase_eq(eq_dec A C);\ncase_eq(eq_dec A D);\ncase_eq(eq_dec B C);\ncase_eq(eq_dec B D).\n\nintros.\nrewrite e;rewrite e1.\ncase_eq(eq_dec C D).\nintros;rewrite e3.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n);assert(HH : equivlist (D :: D :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e;rewrite e1.\ncase_eq(eq_dec C D).\nintros;rewrite e2.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n0);assert(HH : equivlist (C :: C :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e;rewrite e1.\ncase_eq(eq_dec C D).\nintros;rewrite e2.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n0);assert(HH : equivlist (C :: D :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e in *.\nassert(HH0 := rk_quadruple_inter_aux2 B C D E n0 n H H0).\nomega.\n\nintros.\nrewrite e0;rewrite e1.\ncase_eq(eq_dec C D).\nintros;rewrite e2.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n0);assert(HH : equivlist (C :: C :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e;rewrite e0.\ncase_eq(eq_dec C D).\nintros;rewrite e1.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n1);assert(HH : equivlist (C :: C :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e;rewrite e0.\ncase_eq(eq_dec C D).\nintros;rewrite e1.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n1);assert(HH : equivlist (C :: D :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e in *.\nassert(HH0 : equivlist (C :: D :: E :: nil) (D :: C :: E :: nil));[my_inO|].\nrewrite HH0 in H0.\nassert(HH1 := rk_quadruple_inter_aux2 B D C E n n0 H H0).\nassert(HH2 : equivlist (C :: B :: C :: D :: nil) (C :: B :: D :: C :: nil));[my_inO|].\nrewrite HH2.\nomega.\n\nintros.\nrewrite e;rewrite e1.\ncase_eq(eq_dec C D).\nintros;rewrite e2.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n0);assert(HH : equivlist (D :: D :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e;rewrite e0.\ncase_eq(eq_dec C D).\nintros;rewrite e1.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n1);assert(HH : equivlist (D :: C :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e;rewrite e0.\ncase_eq(eq_dec C D).\nintros;rewrite e1.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n1);assert(HH : equivlist (D :: D :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e in *.\nassert(HH0 := rk_quadruple_inter_aux2 B C D E n0 n H H0).\nomega.\n\nintros.\nrewrite e in  *.\nassert(HH0 : equivlist (A :: D :: E :: nil) (D :: A :: E :: nil));[my_inO|].\nrewrite HH0 in H.\nassert(HH1 := rk_quadruple_inter_aux2 A C D E n0 n H H0).\nassert(HH2 : equivlist (D :: A :: C :: D :: nil) (A :: D :: C :: D :: nil));[my_inO|].\nrewrite HH2 in HH1.\nomega.\n\nintros.\nrewrite e in  *.\nassert(HH0 : equivlist (A :: C :: E :: nil) (C :: A :: E :: nil));[my_inO|].\nrewrite HH0 in H.\nassert(HH1 : equivlist (C :: D :: E :: nil) (D :: C :: E :: nil));[my_inO|].\nrewrite HH1 in H0.\nassert(HH2 := rk_quadruple_inter_aux2 A D C E n0 n1 H H0).\nassert(HH3 : equivlist (C :: A :: D :: C :: nil) (A :: C :: C :: D :: nil));[my_inO|].\nrewrite HH3 in HH2.\nomega.\n\nintros.\nrewrite e in *.\nassert(HH0 : equivlist (A :: D :: E :: nil) (D :: A :: E :: nil));[my_inO|].\nrewrite HH0 in H.\nassert(HH1 := rk_quadruple_inter_aux2 A C D E n1 n0 H H0).\nassert(HH2 : equivlist (A :: D :: C :: D :: nil) (D :: A :: C :: D :: nil));[my_inO|].\nrewrite HH2.\nomega.\n\nintros.\nassert(HH0 := rk_quadruple_inter_aux A B C D E n2 n1 n0 n H H0).\nomega.\nQed.\n\nLemma rk_quadruple_max_3 : forall X Y Z W: Point,rk(X :: Y :: Z :: W :: nil) <= 3.\nintros.\nassert(HH0 := rk_inter X Y Z W).\ndestruct HH0.\ndestruct H.\nassert(HH1 := rk_quadruple_inter X Y Z W x H H0).\nomega.\nQed.\n\nLemma rk_quintuple_inter_aux : forall A B C D E,\n~ A = C ->\n~ A = D ->\n~ B = C ->\n~ B = D -> \nrk(A :: B :: E :: nil) = 2 -> \nrk(C :: D :: E :: nil) = 2 ->\nrk(A :: B :: C :: D :: E :: nil) = 2 \\/ rk(A :: B :: C :: D :: E :: nil) = 3.\nProof.\nintros.\n\nassert (HH0 : rk((A :: B :: E :: nil) ++ (C :: D :: E :: nil)) + rk(list_inter (A :: B :: E :: nil) (C :: D :: E :: nil)) <=\n       rk(A :: B :: E :: nil) + rk(C :: D :: E :: nil)).\napply matroid3_useful;my_inO.\nassert(HH1 : equivlist (list_inter (A :: B :: E :: nil) (C :: D :: E :: nil))  (E :: nil)).\nmy_inO.\nassert(HH2 := rk_singleton E).\nrewrite HH1 in HH0.\nrewrite HH2 in HH0.\nrewrite H3 in HH0.\nrewrite H4 in HH0.\n\nassert(HH3 : rk(A :: B :: E :: C :: D :: E :: nil) = 2 \\/ rk(A :: B :: E :: C :: D :: E :: nil) = 3).\napply le_lt_or_eq in HH0;simpl in HH0.\ndestruct HH0.\nassert(HH4 : rk(A :: B :: E :: C :: D :: E :: nil) < 3).\nsolve[intuition].\nassert(HH5 : incl (A :: B :: E :: nil) (A :: B :: E :: C :: D :: E :: nil));[my_inO|].\nassert(HH6 := matroid2 (A :: B :: E :: nil) (A :: B :: E :: C :: D :: E :: nil) HH5).\nomega.\nomega.\n\ndestruct HH3.\n\nassert(HH3 := rk_couple A C H).\nassert(HH4 : incl (A :: C :: nil) (A :: B :: C :: D :: E :: nil));[my_inO|].\nassert(HH5 : incl (A :: B :: C :: D :: E :: nil) (A :: B :: E :: C :: D :: E :: nil));[my_inO|].\nassert(HH6 := matroid2 (A :: C :: nil) (A :: B :: C :: D :: E :: nil) HH4).\nassert(HH7 := matroid2 (A :: B :: C :: D :: E :: nil) (A :: B :: E :: C :: D :: E :: nil) HH5).\nomega.\n\nassert(HH3 : incl (A :: B :: C :: D :: E :: nil) (A :: B :: E :: C :: D :: E :: nil));[my_inO|].\nassert(HH4 := matroid2 (A :: B :: C :: D :: E :: nil) (A :: B :: E :: C :: D :: E :: nil) HH3).\nrewrite H5 in HH4.\napply le_lt_or_eq in HH4.\ndestruct HH4.\nassert(HH5 := rk_couple A C H).\nassert(HH6 : incl (A :: C :: nil) (A :: B :: C :: D :: E :: nil));[my_inO|].\nassert(HH7 := matroid2 (A :: C :: nil) (A :: B :: C :: D :: E :: nil) HH6).\nomega.\nomega.\nQed.\n\nLemma rk_quintuple_inter_aux2 : forall B C D E,\n~ B = C ->\n~ B = D -> \nrk(D :: B :: E :: nil) = 2 -> \nrk(C :: D :: E :: nil) = 2 ->\nrk(D :: B :: C :: D :: E :: nil) = 2 \\/ rk(D :: B :: C :: D :: E :: nil) = 3.\nProof.\nintros.\n\nassert (HH0 : rk((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) + rk(list_inter (D :: B :: E :: nil) (C :: D :: E :: nil)) <=\n       rk(D :: B :: E :: nil) + rk(C :: D :: E :: nil)).\napply matroid3_useful;my_inO.\nassert (HH1 : equivlist (list_inter (D :: B :: E :: nil) (C :: D :: E :: nil)) (D :: E :: nil));[my_inO|].\nrewrite HH1 in HH0.\ncase_eq(eq_dec D E).\nintros;subst.\nrewrite H1 in HH0;rewrite H2 in HH0.\nassert(HH2 : equivlist (E :: E :: nil) (E :: nil));[my_inO|].\nreplace (rk (E :: E :: nil)) with (rk(E :: nil)) in HH0.\n2:rewrite HH2;intuition.\nassert(HH3 := rk_singleton E).\nrewrite HH3 in HH0.\n\nassert(HH4 : rk(E :: B :: E :: C :: E :: E :: nil) = 2 \\/ rk((E :: B :: E :: C :: E :: E :: nil)) = 3).\napply le_lt_or_eq in HH0;simpl in HH0.\ndestruct HH0.\nassert(HH5 : rk((E :: B :: E :: C :: E :: E :: nil)) < 3).\nsolve[intuition].\nassert(HH4 : incl (E :: B :: E :: nil) (E :: B :: E :: C :: E :: E :: nil));[my_inO|].\nassert(HH6 := matroid2 (E :: B :: E :: nil) (E :: B :: E :: C :: E :: E :: nil) HH4).\nomega.\nomega.\n\nassert(HH5 : equivlist (E :: B :: E :: C :: E :: E :: nil) (E :: B :: C :: E :: E :: nil));[my_inO|].\nrewrite HH5 in HH4.\nomega.\n\nintros.\nrewrite H1 in HH0;rewrite H2 in HH0.\nassert(HH2 := rk_couple D E n).\nrewrite HH2 in HH0.\nassert(HH3 : rk((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) = 2).\nassert(HH4 : incl (D :: E :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil)));[my_inO|].\nassert(HH5 := matroid2 (D :: E :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) HH4). \nomega.\nassert(HH4 := rk_couple B C H).\nassert(HH5 : incl (B :: C :: nil) (D :: B :: C :: D :: E :: nil));[my_inO|].\nassert(HH6 := matroid2 (B :: C :: nil) (D :: B :: C :: D :: E :: nil) HH5).\nassert(HH7 : incl (D :: B :: C :: D :: E :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil)));[my_inO|].\nassert(HH8 := matroid2 (D :: B :: C :: D :: E :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) HH7).\nomega.\nQed.\n\nLemma rk_quintuple_inter : forall A B C D E,\nrk(A :: B :: E :: nil) = 2 -> \nrk(C :: D :: E :: nil) = 2 ->\nrk(A :: B :: C :: D :: E :: nil) = 1 \\/ rk(A :: B :: C :: D :: E :: nil) = 2 \\/ rk(A :: B :: C :: D :: E :: nil) = 3.\nProof.\nintros.\ncase_eq(eq_dec A C);\ncase_eq(eq_dec A D);\ncase_eq(eq_dec B C);\ncase_eq(eq_dec B D).\n\nintros;rewrite <-e2;rewrite e;rewrite e1.\ncase_eq(eq_dec D E).\nintros;rewrite e3.\nassert(HH0 : equivlist (E :: E :: E :: E :: E :: nil) (E :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton E);omega.\nintros.\nassert(HH0 := rk_couple D E n);assert(HH : equivlist (D :: D :: D :: D :: E :: nil) (D :: E :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros;apply False_ind;apply n;rewrite e;rewrite <-e0;rewrite e1;reflexivity.\n\nintros;apply False_ind;apply n;rewrite e;rewrite <-e0;rewrite e1;reflexivity.\n\nintros;rewrite e in *.\nassert(HH := rk_quintuple_inter_aux2 B C D E n0 n H H0);intuition.\n\nintros;apply False_ind;apply n;rewrite <-e;rewrite e0;rewrite <-e1;reflexivity.\n\nintros;rewrite e;rewrite e0.\nassert(HH0 : equivlist (C :: C :: C :: D :: E :: nil) (C :: D :: E :: nil));[my_inO|].\nrewrite HH0;right;left;assumption.\n\nintros;rewrite e;rewrite e0.\nassert(HH0 : equivlist (C :: D :: C :: D :: E :: nil) (C :: D :: E :: nil));[my_inO|].\nrewrite HH0;right;left;assumption.\n\nintros;rewrite e in *.\nassert(HH : equivlist (C :: D :: E :: nil) (D :: C :: E :: nil));[my_inO|];rewrite HH in H0.\nassert(HH0 := rk_quintuple_inter_aux2 B D C E n n0 H H0).\nassert(HH1 : equivlist (C :: B :: D :: C :: E :: nil) (C :: B :: C :: D :: E :: nil));[my_inO|].\nrewrite HH1 in HH0;intuition.\n\nintros;apply False_ind;apply n;rewrite <-e0;rewrite e;rewrite e1;reflexivity.\n\nintros;rewrite e;rewrite e0.\nassert(HH0 : equivlist (D :: C :: C :: D :: E :: nil) (C :: D :: E :: nil));[my_inO|].\nrewrite HH0;right;left;assumption.\n\nintros;rewrite e;rewrite e0.\nassert(HH0 : equivlist (D :: D :: C :: D :: E :: nil) (C :: D :: E :: nil));[my_inO|].\nrewrite HH0;right;left;assumption.\n\nintros;rewrite e in *.\nassert(HH0 := rk_quintuple_inter_aux2 B C D E n0 n H H0);intuition.\n\nintros;rewrite e in *.\nassert(HH : equivlist (A :: D :: E :: nil) (D :: A :: E :: nil));[my_inO|];rewrite HH in H.\nassert(HH0 := rk_quintuple_inter_aux2 A C D E n0 n H H0). \nassert(HH1 : equivlist (D :: A :: C :: D :: E :: nil) (A :: D :: C :: D :: E :: nil));[my_inO|].\nrewrite HH1 in HH0;intuition.\n\nintros;rewrite e in *.\nassert(HH : equivlist (A :: C :: E :: nil) (C :: A :: E :: nil));[my_inO|];rewrite HH in H.\nassert(HH0 : equivlist (C :: D :: E :: nil) (D :: C :: E :: nil));[my_inO|];rewrite HH0 in H0.\nassert(HH1 := rk_quintuple_inter_aux2 A D C E n0 n1 H H0). \nassert(HH2 : equivlist (C :: A :: D :: C :: E :: nil) (A :: C :: C :: D :: E :: nil));[my_inO|].\nrewrite HH2 in HH1;intuition.\n\nintros;rewrite e in *.\nassert(HH : equivlist (A :: D :: E :: nil) (D :: A :: E :: nil));[my_inO|];rewrite HH in H.\nassert(HH0 := rk_quintuple_inter_aux2 A C D E n1 n0 H H0).\nassert(HH1 : equivlist (D :: A :: C :: D :: E :: nil) (A :: D :: C :: D :: E :: nil));[my_inO|].\nrewrite HH1 in HH0;intuition.\n\nintros.\nassert(HH := rk_quintuple_inter_aux A B C D E n2 n1 n0 n H H0);intuition.\nQed.\n\nLemma rk_quintuple_max_3 : forall X Y Z W V: Point, rk(X :: Y :: Z :: W :: V :: nil) <= 3.\nProof.\nintros.\n\nassert(HH := rk_lower_dim).\ndestruct HH;destruct H;destruct H.\nassert(HH := rk_triple_3 x x0 x1).\nassert(HH0 : rk (x :: x0 :: x1 :: nil) = 3);[omega|].\nassert(HH1 := rk_quadruple_max_3 x x0 x1 X).\nassert(HH2 := rk_quadruple_max_3 x x0 x1 Y).\nassert(HH3 := rk_quadruple_max_3 x x0 x1 Z).\nassert(HH4 := rk_quadruple_max_3 x x0 x1 W).\nassert(HH5 := rk_quadruple_max_3 x x0 x1 V).\nassert(HH6 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: nil));[my_inO|].\nassert(HH7 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: Y :: nil));[my_inO|].\nassert(HH8 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: Z :: nil));[my_inO|].\nassert(HH9 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: W :: nil));[my_inO|].\nassert(HH10 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: V :: nil));[my_inO|].\nassert(HH11 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: nil) HH6).\nassert(HH12 : rk (x :: x0 :: x1 :: X :: nil) = 3);[omega|].\nassert(HH13 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: Y :: nil) HH7).\nassert(HH14 : rk (x :: x0 :: x1 :: Y :: nil) = 3);[omega|].\nassert(HH15 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: Z :: nil) HH8).\nassert(HH16 : rk (x :: x0 :: x1 :: Z :: nil) = 3);[omega|].\nassert(HH17 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: W :: nil) HH9).\nassert(HH18 : rk (x :: x0 :: x1 :: W :: nil) = 3);[omega|].\nassert(HH19 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: V :: nil) HH10).\nassert(HH20 : rk (x :: x0 :: x1 :: V :: nil) = 3);[omega|].\nclear H HH HH1 HH2 HH3 HH4 HH5 HH6 HH7 HH8 HH9 HH10 HH11 HH13 HH15 HH17 HH19.\n\ncase_eq(eq_dec X Y);intros.\nrewrite e;assert(HH21 : equivlist (Y :: Y :: Z :: W :: V :: nil) (Y :: Z :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 Y Z W V);assumption.\ncase_eq(eq_dec X Z);intros.\nrewrite e;assert(HH21 : equivlist (Z :: Y :: Z :: W :: V :: nil) (Y :: Z :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 Y Z W V);assumption.\ncase_eq(eq_dec X W);intros.\nrewrite e;assert(HH21 : equivlist (W :: Y :: Z :: W :: V :: nil) (Y :: Z :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 Y Z W V);assumption.\ncase_eq(eq_dec X V);intros.\nrewrite e;assert(HH21 : equivlist (V :: Y :: Z :: W :: V :: nil) (Y :: Z :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 Y Z W V);assumption.\ncase_eq(eq_dec Y Z);intros.\nrewrite e;assert(HH21 : equivlist (X :: Z :: Z :: W :: V :: nil) (X :: Z :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 X Z W V);assumption.\ncase_eq(eq_dec Y W);intros.\nrewrite e;assert(HH21 : equivlist (X :: W :: Z :: W :: V :: nil) (X :: Z :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 X Z W V);assumption.\ncase_eq(eq_dec Y V);intros.\nrewrite e;assert(HH21 : equivlist (X :: V :: Z :: W :: V :: nil) (X :: Z :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 X Z W V);assumption.\ncase_eq(eq_dec Z W);intros.\nrewrite e;assert(HH21 : equivlist (X :: Y :: W :: W :: V :: nil) (X :: Y :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 X Y W V);assumption.\ncase_eq(eq_dec Z V);intros.\nrewrite e;assert(HH21 : equivlist (X :: Y :: V :: W :: V :: nil) (X :: Y :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 X Y W V);assumption.\ncase_eq(eq_dec W V);intros.\nrewrite e;assert(HH21 : equivlist (X :: Y :: Z :: V :: V :: nil) (X :: Y :: Z :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 X Y Z V);assumption.\nclear H H0 H1 H2 H3 H4 H5 H6 H7 H8.\n\nassert (HH23 : rk((x :: x0 :: x1 :: X :: nil) ++ (x :: x0 :: x1 :: Y :: nil)) + rk(list_inter (x :: x0 :: x1 :: X :: nil) (x :: x0 :: x1 :: Y :: nil)) <=\n       rk(x :: x0 :: x1 :: X :: nil) + rk(x :: x0 :: x1 :: Y :: nil)).\napply matroid3_useful;my_inO.\nassert(HH24 : equivlist (list_inter (x :: x0 :: x1 :: X :: nil) (x :: x0 :: x1 :: Y :: nil))  (x :: x0 :: x1 :: nil));[my_inO|].\nrewrite HH24 in HH23;clear HH24.\nassert(HH25 : equivlist ((x :: x0 :: x1 :: X :: nil) ++ x :: x0 :: x1 :: Y :: nil) (x :: x0 :: x1 :: X :: Y :: nil));[my_inO|].\nrewrite HH25 in HH23;clear HH25.\nassert(HH26 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y :: nil));[my_inO|].\nassert(HH27 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y :: nil) HH26).\nassert(HH28 : rk(x :: x0 :: x1 :: X :: Y :: nil) = 3);[omega|].\nclear HH12 HH14 HH23 HH26 HH27.\n\nassert (HH29 : rk((x :: x0 :: x1 :: X :: Y :: nil) ++ (x :: x0 :: x1 :: Z :: nil)) + rk(list_inter (x :: x0 :: x1 :: X :: Y :: nil) (x :: x0 :: x1 :: Z :: nil)) <=\n       rk(x :: x0 :: x1 :: X :: Y :: nil) + rk(x :: x0 :: x1 :: Z :: nil)).\napply matroid3_useful;my_inO.\nassert(HH30 : equivlist (list_inter (x :: x0 :: x1 :: X :: Y :: nil) (x :: x0 :: x1 :: Z :: nil))  (x :: x0 :: x1 :: nil));[my_inO|].\nrewrite HH30 in HH29;clear HH30.\nassert(HH31 : equivlist ((x :: x0 :: x1 :: X :: Y :: nil) ++ x :: x0 :: x1 :: Z :: nil) (x :: x0 :: x1 :: X :: Y :: Z :: nil));[my_inO|].\nrewrite HH31 in HH29;clear HH31.\nassert(HH32 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y :: Z :: nil));[my_inO|].\nassert(HH33 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y ::  Z :: nil) HH32).\nassert(HH34 : rk(x :: x0 :: x1 :: X :: Y :: Z :: nil) = 3);[omega|].\nclear HH16 HH28 HH29 HH32 HH33.\n\nassert (HH35 : rk((x :: x0 :: x1 :: X :: Y :: Z :: nil) ++ (x :: x0 :: x1 :: W :: nil)) + rk(list_inter (x :: x0 :: x1 :: X :: Y :: Z :: nil) (x :: x0 :: x1 :: W :: nil)) <=\n       rk(x :: x0 :: x1 :: X :: Y :: Z :: nil) + rk(x :: x0 :: x1 :: W :: nil)).\napply matroid3_useful;my_inO.\nassert(HH36 : equivlist (list_inter (x :: x0 :: x1 :: X :: Y :: Z :: nil) (x :: x0 :: x1 :: W :: nil))  (x :: x0 :: x1 :: nil));[my_inO|].\nrewrite HH36 in HH35;clear HH36.\nassert(HH37 : equivlist ((x :: x0 :: x1 :: X :: Y :: Z :: nil) ++ x :: x0 :: x1 :: W :: nil) (x :: x0 :: x1 :: X :: Y :: Z :: W :: nil));[my_inO;left;my_inO|].\nrewrite HH37 in HH35;clear HH37.\nassert(HH38 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y :: Z :: W :: nil));[my_inO|].\nassert(HH39 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y ::  Z :: W :: nil) HH38).\nassert(HH40 : rk(x :: x0 :: x1 :: X :: Y :: Z :: W ::nil) = 3);[omega|].\nclear HH18 HH34 HH35 HH38 HH39.\n\nassert (HH41 : rk((x :: x0 :: x1 :: X :: Y :: Z :: W :: nil) ++ (x :: x0 :: x1 :: V :: nil)) + rk(list_inter (x :: x0 :: x1 :: X :: Y :: Z :: W ::nil) (x :: x0 :: x1 :: V :: nil)) <=\n       rk(x :: x0 :: x1 :: X :: Y :: Z :: W :: nil) + rk(x :: x0 :: x1 :: V :: nil)).\napply matroid3_useful;my_inO.\nassert(HH42 : equivlist (list_inter (x :: x0 :: x1 :: X :: Y :: Z :: W :: nil) (x :: x0 :: x1 :: V :: nil))  (x :: x0 :: x1 :: nil));[my_inO|].\nrewrite HH42 in HH41;clear HH42.\nassert(HH43 : equivlist ((x :: x0 :: x1 :: X :: Y :: Z :: W :: nil) ++ x :: x0 :: x1 :: V :: nil) (x :: x0 :: x1 :: X :: Y :: Z :: W :: V :: nil));[my_inO;left;my_inO|].\nrewrite HH43 in HH41;clear HH43.\nassert(HH44 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y :: Z :: W :: V :: nil));[my_inO|].\nassert(HH45 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y ::  Z :: W :: V :: nil) HH44).\nassert(HH46 : rk(x :: x0 :: x1 :: X :: Y :: Z :: W ::V :: nil) = 3);[omega|].\nclear HH20 HH40 HH41 HH44 HH45.\nassert(HH47 : incl (X :: Y :: Z :: W :: V :: nil)(x :: x0 :: x1 :: X :: Y :: Z :: W :: V :: nil));[my_inO|].\nassert(HH48 := matroid2 (X :: Y :: Z :: W :: V :: nil)(x :: x0 :: x1 :: X :: Y :: Z :: W :: V :: nil) HH47).\nomega.\nQed.\n", "meta": {"author": "pascalschreck", "repo": "MatroidIncidenceProver", "sha": "e492d375a2264e6c908c9c47fe719c39e3f847f8", "save_path": "github-repos/coq/pascalschreck-MatroidIncidenceProver", "path": "github-repos/coq/pascalschreck-MatroidIncidenceProver/MatroidIncidenceProver-e492d375a2264e6c908c9c47fe719c39e3f847f8/matroidbasedIGprover/matroid_C_Coq/DevCoq/Dev/basic_rank_plane_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6907862551156881}}
{"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 Max Wellfounded Coq.Setoids.Setoid.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac utils_list finite.\n\nFrom Undecidability.Shared.Libs.DLW.Vec \n  Require Import pos vec.\n\nFrom Undecidability.TRAKHTENBROT\n  Require Import notations fol_ops fo_sig fo_terms fo_logic.\n\nImport fol_notations.\n\nSet Default Proof Using \"Type\".\n\nSet Implicit Arguments.\n\nLocal Notation ø := vec_nil.\nLocal Infix \"∊\" := In (at level 70, no associativity).\nLocal Infix \"⊑\" := incl (at level 70, no associativity). \n\n(* * The first order theory of membership *)\n\nSection membership.\n\n  (* We develop a theory of finitary and computable and \n      extensional membership. We build pair, ordered pairs\n      and ordered triples and show their properties *)\n\n  Variable (X : Type) (mem : X -> X -> Prop).\n\n  Infix \"∈\" := mem.\n  Notation \"x ∉ y\" := (~ x ∈ y).\n\n  Definition mb_incl x y := forall a, a ∈ x -> a ∈ y.\n  Definition mb_equiv x y := forall a, a ∈ x <-> a ∈ y.\n\n  Infix \"⊆\" := mb_incl.\n  Infix \"≈\" := mb_equiv. \n  Notation \"x ≉ y\" := (~ x ≈ y).\n\n  Definition mb_transitive t := forall x y, x ∈ y -> y ∈ t -> x ∈ t.\n\n  Fact mb_incl_refl x : x ⊆ x.\n  Proof. red; auto. Qed.\n\n  Fact mb_incl_trans x y z : x ⊆ y -> y ⊆ z -> x ⊆ z.\n  Proof. unfold mb_incl; auto. Qed.\n\n  Fact mb_equiv_eq x y : x ≈ y <-> x ⊆ y /\\ y ⊆ x.\n  Proof. firstorder. Qed.\n\n  Fact mb_equiv_refl_True x : x ≈ x <-> True.    Proof. unfold mb_equiv; tauto. Qed.\n  Fact mb_equiv_refl x : x ≈ x.                  Proof. unfold mb_equiv; tauto. Qed.\n\n  Fact mb_equiv_sym x y : x ≈ y -> y ≈ x.\n  Proof. do 2 rewrite mb_equiv_eq; tauto. Qed.\n\n  Fact mb_equiv_trans x y z : x ≈ y -> y ≈ z -> x ≈ z.\n  Proof. repeat rewrite mb_equiv_eq; unfold mb_incl; intros [] []; split; auto. Qed.\n\n  Add Parametric Relation: (X) (mb_equiv)\n      reflexivity proved by mb_equiv_refl\n      symmetry proved by mb_equiv_sym\n      transitivity proved by mb_equiv_trans\n    as mb_equiv_equivalence.\n\n  Hint Resolve mb_equiv_refl mb_equiv_sym : core.\n\n  (* The only FOL axiom: sets are characterized by their elements *)\n\n  Definition mb_member_ext := forall x y z, x ≈ y -> x ∈ z -> y ∈ z.\n\n  Variable (mb_axiom_ext : mb_member_ext).\n\n  Fact mb_equiv_mem x y : x ≈ y -> forall z, x ∈ z <-> y ∈ z.\n  Proof using mb_axiom_ext. split; apply mb_axiom_ext; auto. Qed.\n  \n   Add Parametric Morphism: (mem) with signature \n     (mb_equiv) ==> (mb_equiv) ==> (iff) as mb_mem_congruence.\n  Proof using mb_axiom_ext.\n    intros x y H1 a b H2; red in H1, H2; split;\n     rewrite <- H2; apply mb_axiom_ext; auto.\n  Qed.\n\n  Add Parametric Morphism: (fun x y => x ⊆ y) with signature \n     (mb_equiv) ==> (mb_equiv) ==> (iff) as mb_incl_congruence.\n  Proof using mb_axiom_ext.\n    intros x y H1 a b H2; split; intros H z.\n    + rewrite <- H1, <- H2; auto.\n    + rewrite H1, H2; auto.\n  Qed.\n\n  Reserved Notation \"p ≋ ⦃ a , b ⦄\" (at level 70, format \"p  ≋  ⦃ a , b ⦄\").\n  Reserved Notation \"p ≋ ⦅ a , b ⦆\" (at level 70, format \"p  ≋  ⦅ a , b ⦆\").\n  Reserved Notation \"t ≋ ⦉ v ⦊\" (at level 70, format \"t  ≋  ⦉ v ⦊\").\n\n  Definition mb_is_pair p x y := forall a, a ∈ p <-> a ≈ x \\/ a ≈ y.\n\n  Notation \"p ≋ ⦃ a , b ⦄\" := (mb_is_pair p a b).\n\n  Fact mb_is_pair_comm p x y : p ≋ ⦃x,y⦄ -> p ≋ ⦃y,x⦄.\n  Proof. unfold mb_is_pair; fol equiv fa; intro; tauto. Qed.\n\n  Add Parametric Morphism: (mb_is_pair) with signature \n     (mb_equiv) ==> (mb_equiv) ==> (mb_equiv) ==> (iff) as mb_is_pair_congruence.\n  Proof using mb_axiom_ext.\n    intros p q H1 x x' H2 y y' H3.\n    fol equiv fa; intro.\n    rewrite H1, H2, H3; tauto.\n  Qed.\n\n  Fact mb_is_pair_fun p q x y : p ≋ ⦃x,y⦄ -> q ≋ ⦃x,y⦄ -> p ≈ q.\n  Proof. intros H1 H2; red in H1, H2; intro; rewrite H1, H2; tauto. Qed.\n\n  (* Many cases here, automation helps !! *)\n\n  Fact mb_is_pair_inj p x y x' y' : \n         p ≋ ⦃x,y⦄  \n      -> p ≋ ⦃x',y'⦄ \n      -> x ≈ x' /\\ y ≈ y'\n      \\/ x ≈ y' /\\ y ≈ x'.\n  Proof.\n    unfold mb_is_pair; intros H1 H2.\n    generalize (proj1 (H2 x)) (proj1 (H2 y)); rewrite H1, H1, mb_equiv_refl_True, mb_equiv_refl_True.\n    generalize (proj1 (H1 x')) (proj1 (H1 y')); rewrite H2, H2, mb_equiv_refl_True, mb_equiv_refl_True.\n    intros [] [] [] []; auto.\n  Qed.\n\n  Fact mb_is_pair_inj' p x y : p ≋ ⦃x,x⦄ -> p ≋ ⦃y,y⦄ -> x ≈ y.\n  Proof. intros H1 H2; generalize (mb_is_pair_inj H1 H2); tauto. Qed.\n\n  (* Ordered pairs (x,y) := {{x},{x,y}}, Kuratowski encoding *)\n\n  Definition mb_is_opair p x y := exists a b, a ≋ ⦃x,x⦄ /\\ b ≋ ⦃x,y⦄ /\\ p ≋ ⦃a,b⦄.\n\n  Notation \"p ≋ ⦅ a , b ⦆\" := (mb_is_opair p a b).\n\n  Add Parametric Morphism: (mb_is_opair) with signature \n     (mb_equiv) ==> (mb_equiv) ==> (mb_equiv) ==> (iff) as mb_is_opair_congruence.\n  Proof using mb_axiom_ext.\n    intros p q H1 x x' H2 y y' H3.\n    do 2 (fol equiv ex; intro).\n    rewrite H1, H2, H3; tauto.\n  Qed.\n\n  Fact mb_is_opair_fun p q x y : p ≋ ⦅x,y⦆ -> q ≋ ⦅x,y⦆  -> p ≈ q.\n  Proof using mb_axiom_ext.\n    intros (a & b & H1 & H2 & H3) (u & v & G1 & G2 & G3).\n    generalize (mb_is_pair_fun H1 G1) (mb_is_pair_fun H2 G2); intros E1 E2.\n    rewrite E1, E2 in H3.\n    revert H3 G3; apply mb_is_pair_fun.\n  Qed.\n\n  Fact mb_is_opair_inj p x y x' y' : p ≋ ⦅x,y⦆  -> p ≋ ⦅x',y'⦆ -> x ≈ x' /\\ y ≈ y'.\n  Proof using mb_axiom_ext.\n    intros (a & b & H1 & H2 & H3) (u & v & G1 & G2 & G3).\n    generalize (mb_is_pair_inj H3 G3); intros [ (E1 & E2) | (E1 & E2) ].\n    + rewrite E1 in H1; rewrite E2 in H2.\n      generalize (mb_is_pair_inj' H1 G1); intros E; split; auto.\n      rewrite E in H2.\n      generalize (mb_is_pair_inj H2 G2); intros [ | (E3 & E4) ]; try tauto.\n      rewrite E4; auto.\n    + rewrite E1 in H1; rewrite E2 in H2.\n      generalize (mb_is_pair_inj H2 G1) (mb_is_pair_inj H1 G2).\n      intros [ (E3 & E4) | (E3 & E4) ] [ (E5 & E6) | (E5 & E6) ];\n        rewrite E4, <- E5; auto.\n  Qed.  \n \n  (* n-tuples *)\n\n  Fixpoint mb_is_tuple t n (v : vec X n) :=\n    match v with \n      | vec_nil => forall z, z ∉ t\n      | x##v    => exists t', t ≋ ⦅x,t'⦆ /\\ t' ≋ ⦉v⦊\n    end\n  where \"t ≋ ⦉ v ⦊\" := (mb_is_tuple t v).\n\n  Fact mb_is_tuple_congr p q n (v : vec X n) : p ≈ q -> p ≋ ⦉v⦊ -> q ≋ ⦉v⦊ .\n  Proof using mb_axiom_ext.\n    revert p q; induction v as [ | n x v IHv ]; intros p q.\n    + simpl; intros E H x; rewrite <- E; auto.\n    + intros E (t & H1 & H2); exists t; split; auto.\n      rewrite <- E; auto.\n  Qed.\n\n  Fact mb_is_tuple_fun p q n (v : vec _ n) : p ≋ ⦉v⦊  -> q ≋ ⦉v⦊  -> p ≈ q.\n  Proof using mb_axiom_ext.\n    revert p q; induction v as [ | n x v IHv ]; intros p q.\n    + simpl; intros H1 H2.\n      apply mb_equiv_eq; split.\n      * intros z Hz; apply H1 in Hz; tauto.\n      * intros z Hz; apply H2 in Hz; tauto.\n    + intros (p' & H1 & H2) (q' & H3 & H4).\n      generalize (IHv _ _ H2 H4); intros E.\n      rewrite E in H1.\n      revert H1 H3; apply mb_is_opair_fun.\n  Qed.\n\n  Fact mb_is_tuple_inj t n (v w : vec _ n) p : \n         t ≋ ⦉v⦊  -> t ≋ ⦉w⦊  -> vec_pos v p ≈ vec_pos w p.\n  Proof using mb_axiom_ext.\n    intros H1 H2; revert t w H1 H2 p; induction v as [ | n x v IHv ]; intros t w.\n    + intros _ _ p; invert pos p.\n    + vec split w with y.\n      intros (p & H1 & H2) (q & H3 & H4).\n      destruct (mb_is_opair_inj H1 H3) as (E1 & E2).\n      apply mb_is_tuple_congr with (1 := E2) in H2.\n      specialize (IHv _ _ H2 H4).\n      intros j; invert pos j; auto.\n  Qed.\n\n  (* mb_has_* from elements in l *)\n\n  Definition mb_has_pairs (l : X) :=\n     forall x y, x ∈ l -> y ∈ l -> exists p, p ≋ ⦃x,y⦄ .\n\n  Definition mb_has_tuples (l : X) n :=\n    forall v : vec _ n, (forall p, vec_pos v p ∈ l) -> exists t, t ≋ ⦉v⦊.\n\n  Definition mb_is_tuple_in r n (v : vec _ n) :=\n    exists t, t ≋ ⦉v⦊ /\\ t ∈ r.\n\n  Notation \"t ∋ ⦉ v ⦊\" := (mb_is_tuple_in t v) (at level 70, format \"t  ∋  ⦉ v ⦊\").\n\n  Fact mb_is_tuple_in_congr x y n (v : vec _ n) : y ≈ x -> x ∋ ⦉v⦊ -> y ∋ ⦉v⦊ .\n  Proof using mb_axiom_ext.\n    intros E (t & H1 & H2); exists t; split; auto.\n    rewrite  E; auto.\n  Qed.\n\n  (* mb total and functional *)\n\n  Definition mb_is_tot n (l s : X) :=\n    forall v, (forall p : pos n, vec_pos v p ∈ l) \n            -> exists x p t, x ∈ l /\\ p ∈ s /\\ p ≋ ⦅x,t⦆  /\\ t ≋ ⦉v⦊.\n\n  Definition mb_is_fun (l s : X) :=\n    forall p q x x' y, x ∈ l -> x' ∈ l \n                    -> p ∈ s -> q ∈ s\n                    -> p ≋ ⦅x,y⦆ \n                    -> q ≋ ⦅x',y⦆\n                    -> x ≈ x'.\n\n  (* Meta-level properties on the model *)\n\n  Variable (Rdec : forall x y, { x ∈ y } + { x ∉ y }) \n           (Xfin : finite_t X).\n\n  Local Definition lX : list X := proj1_sig Xfin.\n  Local Definition HX : forall x, In x lX := proj2_sig Xfin.\n\n  Hint Resolve HX : core.\n\n  Fact mb_incl_choose x y : { z | z ∈ x /\\ z ∉ y } + { x ⊆ y }.\n  Proof using Xfin Rdec.\n    set (P z := z ∈ x /\\ z ∉ y).\n    set (Q z := z ∈ x -> z ∈ y).\n    destruct list_dec with (P := P) (Q := Q) (l := lX)\n      as [ (z & _ & H2 & H3) | H ]; unfold P, Q in *; clear P Q.\n    + intros z; destruct (Rdec z x); destruct (Rdec z y); tauto.\n    + left; exists z; auto.\n    + right; intros z; apply H; auto.\n  Qed.  \n\n  Fact mb_incl_dec x y : { x ⊆ y } + { ~ x ⊆ y }.\n  Proof using Xfin Rdec.\n    destruct (mb_incl_choose x y) as [ (?&?&?) |]; auto.\n  Qed.\n\n  Fact mb_equiv_dec x y : { x ≈ y } + { x ≉ y }.\n  Proof using Xfin Rdec.\n    destruct (mb_incl_dec x y); [ destruct (mb_incl_dec y x) | ].\n    1: left; apply mb_equiv_eq; auto. \n    all: right; rewrite mb_equiv_eq; tauto.\n  Qed.\n\n  Hint Resolve mb_equiv_dec : core.\n\n  Fact mb_is_pair_dec p x y : { p ≋ ⦃x,y⦄ } + { ~ p ≋ ⦃x,y⦄ }.\n  Proof using Xfin Rdec.\n    unfold mb_is_pair.\n    apply (fol_quant_sem_dec fol_fa); auto; intros u.\n    apply fol_equiv_dec; auto.\n    apply (fol_bin_sem_dec fol_disj); auto.\n  Qed.\n\n  Hint Resolve mb_is_pair_dec : core.\n\n  Fact mb_is_opair_dec p x y : { p ≋ ⦅x,y⦆  } + { ~ p ≋ ⦅x,y⦆  }.\n  Proof using Xfin Rdec.\n    unfold mb_is_opair.\n    do 2 (apply (fol_quant_sem_dec fol_ex); auto; intro).\n    repeat (apply (fol_bin_sem_dec fol_conj); auto).\n  Qed.\n\n  Hint Resolve mb_is_opair_dec : core.\n\n  Fact mb_is_tuple_dec t n (v : vec _ n) : { t ≋ ⦉v⦊  } + { ~ t ≋ ⦉v⦊  }.\n  Proof using Xfin Rdec.\n    revert t; induction v as [ | x n v IHv ]; intros t.\n    + apply (fol_quant_sem_dec fol_fa); auto; intro.\n      apply (fol_bin_sem_dec fol_imp); auto.\n    + simpl; apply (fol_quant_sem_dec fol_ex); auto; intro.\n      apply (fol_bin_sem_dec fol_conj); auto.\n  Qed.\n\n  Hint Resolve mb_is_tuple_dec : core.\n\n  Fact mb_is_tuple_in_dec r n (v : vec _ n) : { r ∋ ⦉v⦊  } + { ~ r ∋ ⦉v⦊  }.\n  Proof using Xfin Rdec.\n    apply (fol_quant_sem_dec fol_ex); auto; intro.\n    apply (fol_bin_sem_dec fol_conj); auto.\n  Qed.\n\nEnd membership.\n\nSection FOL_encoding.\n\n  (* First order encoding here *)\n\n  (* Maybe we can redo the whole devel here with fo_definable.v *)\n\n  Notation Σ2 := (Σrel 2).\n  Variable (Y : Type) (M2 : fo_model Σ2 Y).\n\n  Let mem a b := fom_rels M2 tt (a##b##ø).\n  Infix \"∈ₘ\" := mem (at level 59, no associativity).\n\n  Definition Σ2_mem x y := @fol_atom Σ2 tt (£x##£y##ø).\n  Infix \"∈\" := Σ2_mem.\n\n  Definition Σ2_non_empty l := ∃ 0 ∈ (1+l). \n  Definition Σ2_incl x y := ∀ 0 ∈ (S x) ⤑ 0 ∈ (S y).\n  Definition Σ2_equiv x y := ∀ 0 ∈ (S x) ↔ 0 ∈ (S y).\n\n  Infix \"⊆\" := Σ2_incl.\n  Infix \"≈\" := Σ2_equiv.\n\n  Definition Σ2_transitive t := ∀∀ 1 ∈ 0 ⤑ 0 ∈ (2+t) ⤑ 1 ∈ (2+t).\n\n  Definition Σ2_extensional := ∀∀∀ 2 ≈ 1 ⤑ 2 ∈ 0 ⤑ 1 ∈ 0.\n\n  Definition Σ2_is_pair p x y := ∀ 0 ∈ (S p) ↔ 0 ≈ S x ⟇ 0 ≈ S y.\n\n  Definition Σ2_is_opair p x y := \n         ∃∃   Σ2_is_pair 1    (2+x) (2+x)\n            ⟑ Σ2_is_pair 0    (2+x) (2+y)\n            ⟑ Σ2_is_pair (2+p) 1     0.\n\n  Fact Σ2_is_opair_vars p x y : fol_vars (Σ2_is_opair p x y) ⊑ p::x::y::nil.\n  Proof. cbv; tauto. Qed.\n\n  (* A 0-tuple <> is the empty set\n     A (1+n)-tuple <x##v> is a pair (x,k) where k is the n-tuple <v>\n   *)\n\n  Fixpoint Σ2_is_tuple t n : vec nat n -> fol_form Σ2 :=\n    match n with \n      | 0       => fun _ => ∀ 0 ∈ (S t) ⤑ ⊥\n      | S n     => fun v => ∃ Σ2_is_opair (S t) (S (vec_head v)) 0 \n                            ⟑ Σ2_is_tuple 0 (vec_map S (vec_tail v))\n    end.\n\n  Fact Σ2_is_tuple_vars t n v : fol_vars (@Σ2_is_tuple t n v) ⊑ t::vec_list v.\n  Proof.\n    revert t v; induction n as [ | n IHn ]; intros t v.\n    + vec nil v; cbv; tauto.\n    + vec split v with x; simpl Σ2_is_tuple.\n      intros i; rewrite fol_vars_quant, in_flat_map.\n      intros (j & H1 & H2).\n      rewrite fol_vars_bin, in_app_iff in H1.\n      destruct H1 as [ H1 | H1 ].\n      * apply Σ2_is_opair_vars in H1.\n        destruct H1 as [ | [ | [ | [] ] ] ]; subst j; simpl in *; tauto.\n      * apply IHn in H1.\n        destruct H1 as [ <- | H1 ].\n        - simpl in *; tauto.\n        - rewrite vec_list_vec_map, in_map_iff in H1.\n          destruct H1 as (y & <- & H1); simpl in *.\n          destruct H2 as [ -> | [] ]; tauto.\n  Qed.\n\n  (* v is n-tuple belonging to r *) \n\n  Definition Σ2_is_tuple_in r n v := ∃ @Σ2_is_tuple 0 n (vec_map S v) ⟑ 0 ∈ (S r).\n\n  Fact Σ2_is_tuple_in_vars r n v : fol_vars (@Σ2_is_tuple_in r n v) ⊑ r::vec_list v.\n  Proof.\n    unfold Σ2_is_tuple_in.\n    intros x; rewrite fol_vars_quant, in_flat_map.\n    intros (y & H1 & H2).\n    rewrite fol_vars_bin, in_app_iff in H1.\n    destruct H1 as [ H1 | H1 ].\n    + apply Σ2_is_tuple_vars in H1.\n      simpl in H1; rewrite vec_list_vec_map, in_map_iff in H1.\n      destruct H1 as [ <- | (z & <- & H1) ]; simpl in *; try tauto.\n      destruct H2 as [ <- | [] ]; auto.\n    + simpl in H1.\n      destruct H1 as [ <- | [ <- | [] ] ]; simpl in *; tauto.\n  Qed.\n\n  Definition Σ2_has_tuples l n :=\n       fol_mquant fol_fa n ( (fol_vec_fa (vec_set_pos (fun p : pos n => pos2nat p ∈ (l+n))))\n                                         ⤑ ∃ Σ2_is_tuple 0 (vec_set_pos (fun p : pos n => S (pos2nat p)))).\n\n  Definition Σ2_is_tot n l s :=\n       fol_mquant fol_fa n ( (fol_vec_fa (vec_set_pos (fun p : pos n => pos2nat p ∈ (l+n))))\n                                         ⤑ ∃∃∃ 2 ∈ ((3+l)+n) ⟑ 1 ∈ ((3+s)+n) ⟑ Σ2_is_opair 1 2 0 ⟑ @Σ2_is_tuple 0 n (vec_set_pos (fun p : pos n => 3+pos2nat p)) ).\n\n  Definition Σ2_is_fun l s :=\n    ∀∀∀∀∀ 2 ∈ (5+l) ⤑ 1 ∈ (5+l) ⤑\n          4 ∈ (5+s) ⤑ 3 ∈ (5+s) ⤑\n          Σ2_is_opair 4 2 0 ⤑\n          Σ2_is_opair 3 1 0 ⤑\n          2 ≈ 1.\n\n  Definition Σ2_list_in l lv := fol_lconj (map (fun x => x ∈ l) lv).\n\n  Notation \"⟪ A ⟫\" := (fun ψ => fol_sem M2 ψ A).\n\n  Section semantics.\n\n    Fact Σ2_transitive_spec t ψ : ⟪Σ2_transitive t⟫ ψ = mb_transitive mem (ψ t).\n    Proof. reflexivity. Qed.\n \n    Fact Σ2_non_empty_spec l ψ : ⟪Σ2_non_empty l⟫ ψ = exists x, x ∈ₘ ψ l.\n    Proof. reflexivity. Qed.\n\n    Fact Σ2_incl_spec x y ψ : ⟪Σ2_incl x y⟫ ψ = mb_incl mem (ψ x) (ψ y).\n    Proof. reflexivity. Qed.\n\n    Fact Σ2_equiv_spec x y ψ : ⟪Σ2_equiv x y⟫ ψ = mb_equiv mem (ψ x) (ψ y).\n    Proof. reflexivity. Qed. \n\n    Fact Σ2_extensional_spec ψ : ⟪Σ2_extensional⟫ ψ = mb_member_ext mem.\n    Proof. reflexivity. Qed.\n\n    Fact Σ2_is_pair_spec p x y ψ : ⟪Σ2_is_pair p x y⟫ ψ = mb_is_pair mem (ψ p) (ψ x) (ψ y).\n    Proof. reflexivity. Qed.\n\n    Fact Σ2_is_opair_spec p x y ψ : ⟪Σ2_is_opair p x y⟫ ψ = mb_is_opair mem (ψ p) (ψ x) (ψ y).\n    Proof. reflexivity. Qed.\n\n    Fact Σ2_is_tuple_spec t n v ψ : ⟪@Σ2_is_tuple t n v⟫ ψ <-> mb_is_tuple mem (ψ t) (vec_map ψ v).\n    Proof.\n      induction n as [ | n IHn ] in t, v, ψ |- *.\n      + vec nil v; reflexivity.\n      + vec split v with x.\n        simpl Σ2_is_tuple.\n        simpl mb_is_tuple.\n        rewrite fol_sem_quant_fix.\n        fol equiv ex; intros y.\n        rewrite fol_sem_bin_fix.\n        fol equiv conj.\n        * reflexivity.\n        * rewrite IHn, vec_map_map; reflexivity. \n    Qed.\n\n    Fact Σ2_is_tuple_in_spec r n v ψ : ⟪@Σ2_is_tuple_in r n v⟫ ψ <-> mb_is_tuple_in mem (ψ r) (vec_map ψ v).\n    Proof.\n      simpl; fol equiv ex; intro; fol equiv conj.\n      + rewrite Σ2_is_tuple_spec, vec_map_map; simpl; reflexivity.\n      + reflexivity.\n    Qed.\n\n    Fact Σ2_has_tuples_spec l n ψ : ⟪Σ2_has_tuples l n⟫ ψ <-> mb_has_tuples mem (ψ l) n.\n    Proof.\n      unfold Σ2_has_tuples.\n      rewrite fol_sem_mforall.\n      fol equiv fa; intros v.\n      rewrite fol_sem_bin_fix.\n      fol equiv imp.\n      + rewrite fol_sem_vec_fa.\n        fol equiv; intros p.\n        rew vec; simpl.\n        now rewrite env_vlift_fix0, env_vlift_fix1.\n      + rewrite fol_sem_quant_fix.\n        fol equiv ex; intros x.\n        rewrite Σ2_is_tuple_spec; simpl.\n        fol equiv rel.\n        apply vec_pos_ext; intros p.\n        rew vec; simpl.\n        rewrite env_vlift_fix0; auto.\n    Qed.\n\n    Fact Σ2_is_fun_spec l s ψ : ⟪Σ2_is_fun l s⟫ ψ = mb_is_fun mem (ψ l) (ψ s).\n    Proof. reflexivity. Qed.\n\n    Fact Σ2_is_tot_spec n l s ψ : ⟪Σ2_is_tot n l s⟫ ψ <-> mb_is_tot mem n (ψ l) (ψ s).\n    Proof. \n      unfold Σ2_is_tot, mb_is_tot.\n      rewrite fol_sem_mforall.\n      fol equiv; intros v.\n      rewrite fol_sem_bin_fix.\n      fol equiv imp.\n      + rewrite fol_sem_vec_fa.\n        fol equiv; intros p.\n        rew vec; simpl. \n        rewrite env_vlift_fix0, env_vlift_fix1; tauto.\n      + rewrite fol_sem_quant_fix; fol equiv ex; intros x.\n        rewrite fol_sem_quant_fix; fol equiv ex; intros p.\n        rewrite fol_sem_quant_fix; fol equiv ex; intros t.\n        do 3 (rewrite fol_sem_bin_fix).\n        repeat fol equiv conj.\n        * simpl; rewrite env_vlift_fix1; tauto.\n        * simpl; rewrite env_vlift_fix1; tauto.\n        * rewrite Σ2_is_opair_spec; simpl; tauto.\n        * rewrite Σ2_is_tuple_spec; simpl.\n          fol equiv.\n          apply vec_pos_ext; intros q; rew vec.\n          simpl; rewrite env_vlift_fix0; auto.\n    Qed.\n\n    Fact Σ2_list_in_spec l lv ψ : ⟪Σ2_list_in l lv⟫ ψ <-> forall x, x ∊ lv -> ψ x ∈ₘ ψ l.\n    Proof.\n      unfold Σ2_list_in; rewrite fol_sem_lconj.\n      split.\n      + intros H x Hx.\n        apply (H (_ ∈ _)), in_map_iff.\n        exists x; auto.\n      + intros H f; rewrite in_map_iff.\n        intros (x & <- & ?); apply H; auto.\n    Qed.\n\n  End semantics.\n\nEnd FOL_encoding. \n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/TRAKHTENBROT/membership.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6907820131564174}}
{"text": "\nTheorem Ex022 (A B C : Prop): (A -> B) -> (A -> B -> C) -> (A -> C).\nProof.\n  intros.\n  apply H0.\n  + exact H1.\n  + apply H. exact H1.\nQed.\n\n", "meta": {"author": "SvenWille", "repo": "CoqLogicExercises", "sha": "b4c1aea30abb95dc7ba81fa42ccb914d534d65e5", "save_path": "github-repos/coq/SvenWille-CoqLogicExercises", "path": "github-repos/coq/SvenWille-CoqLogicExercises/CoqLogicExercises-b4c1aea30abb95dc7ba81fa42ccb914d534d65e5/src/propLogic/Ex022.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6907820129703385}}
{"text": "(******************************************************************************)\n\n(* Original author: Russell O'Connor *)\n(* This file is Public Domain *)\n\n\nFrom Coq Require Import Lists.List  Ensembles  Peano_dec  Eqdep_dec\n  Arith Compare_dec.\n\nRequire Import misc  Compat815 (* provisional *).\n\n(* begin snippet LanguageDef *)\n(* change suggested in the article by Russel O'Connor \n   P. Casteran *)\n\nRecord Language : Type := language\n { Relations : Set; \n   Functions : Set; \n   arityR : Relations -> nat;\n   arityF : Functions -> nat}.\n\n(* end snippet LanguageDef *)\n\n\n\n(* begin snippet TermDef *)\nSection First_Order_Logic.\n\nVariable L : Language.\n\nInductive Term : Set :=\n  | var : nat -> Term\n  | apply : forall f : Functions L, Terms  (arityF L f) -> Term\nwith Terms : nat -> Set :=\n  | Tnil : Terms 0\n  | Tcons : forall n : nat, Term -> Terms n -> Terms (S n).\n (* end snippet TermDef *)\n\n\n\nScheme Term_Terms_ind := Induction for Term Sort Prop\n  with Terms_Term_ind := Induction for Terms Sort Prop.\n\nScheme Term_Terms_rec := Minimality for Term Sort Set\n  with Terms_Term_rec := Minimality for Terms Sort Set.\n\nScheme Term_Terms_rec_full := Induction for Term  Sort Set\n  with Terms_Term_rec_full := Induction for Terms Sort Set.\n\n(* begin snippet FormulaDef *)\nInductive Formula : Set :=\n  | equal : Term -> Term -> Formula\n  | atomic : forall r : Relations L, \n      Terms (arityR L r) -> Formula\n  | impH : Formula -> Formula -> Formula\n  | notH : Formula -> Formula\n  | forallH : nat -> Formula -> Formula.\n(* end snippet FormulaDef *)\n\n(* begin snippet SystemDef *)\nDefinition Formulas := list Formula.\nDefinition System := Ensemble Formula.\nDefinition mem := Ensembles.In.\n(* end snippet SystemDef *)\n\n(* begin snippet FolFull *)\nDefinition orH (A B : Formula) := impH (notH A) B.\nDefinition andH (A B : Formula) := notH (orH (notH A) (notH B)).\nDefinition iffH (A B : Formula) := andH (impH A B) (impH B A).\nDefinition existH (x : nat) (A : Formula) := \n  notH (forallH x (notH A)).\n\n(* end snippet FolFull *)\n\n(* begin snippet FolPlus *)\nDefinition ifThenElseH (A B C : Formula) := andH (impH A B) (impH (notH A) C).\n(* end snippet FolPlus *)\n\n\n(* begin snippet formDec1:: no-out *)\nSection Formula_Decidability.\n\nDefinition language_decidable :=\n  ((forall x y : Functions L, {x = y} + {x <> y}) *\n   (forall x y : Relations L, {x = y} + {x <> y}))%type.\n\nHypothesis language_dec : language_decidable.\n(* end snippet formDec1 *)\n\nLet nilTermsHelp : forall n : nat, n = 0 -> Terms n.\nProof. \n  intros n H; induction n as [| n Hrecn].\n  - apply Tnil.\n  - discriminate H.\nDefined.\n\nLemma nilTerms : forall x : Terms 0, Tnil = x.\nProof.\n  assert (H: forall (n : nat) (p : n = 0) (x : Terms n), \n             nilTermsHelp n p = x).\n  { intros n p x; induction x as [| n t x Hrecx].\n    - reflexivity.\n    - discriminate p.\n  }\n  replace Tnil with (nilTermsHelp 0 (refl_equal 0)).\n  - apply H.\n  - auto.\nQed.\n\n(** Decomposition Lemma for [Terms] *)\nLet consTermsHelp : forall n : nat, Terms n -> Set.\nProof. \n  intros n H; case n.\n  - exact\n      (forall p : 0 = n, \n          {foo : unit | eq_rec _ (fun z => Terms z) Tnil _ p = H}).\n  - intros n0;\n      exact\n        (forall p : S n0 = n,\n            {t : Term * Terms n0 |\n              eq_rec _ (fun z => Terms z) (Tcons n0 (fst t) (snd t)) _ p = H}).\nDefined.\n\nLemma consTerms :\n forall (n : nat) (x : Terms (S n)),\n {t : Term * Terms n | Tcons n (fst t) (snd t) = x}.\nProof.\n  assert (H: forall (n : nat) (x : Terms n), consTermsHelp n x).\n  { intros n x; induction x as [| n t x Hrecx].\n    - simpl in |- *; intros p; exists tt.\n      elim p using K_dec_set.\n      + apply eq_nat_dec.\n      + reflexivity.\n    - simpl in |- *; intro p; exists (t, x).\n      elim p using K_dec_set.\n      + apply eq_nat_dec.\n      + simpl in |- *; reflexivity.\n  }\n  intros n x; assert (H0: consTermsHelp _ x) by apply H.\n  simpl in H0; apply (H0 (refl_equal (S n))).\nQed.\n\nArguments Term_Terms_rec_full P P0: rename.\n\n(* TODO --> term_eqdec *)\n(* begin snippet formDec2:: no-out *)\nLemma term_dec : forall x y : Term, {x = y} + {x <> y}.\n(* end snippet formDec2 *)\nProof.\n  destruct language_dec as [a b].\n  assert\n    (H: forall (f g : Functions L) (p : f = g) \n               (ts : Terms (arityF L f))\n               (ss : Terms (arityF L g))\n               (q : arityF L f = arityF L g),\n        eq_rec _ (fun x => Terms x) ts _ q = ss <-> \n          apply f ts = apply g ss).\n  { intros f g p;  eapply eq_ind\n      with\n      (x := g)\n      (P := \n         fun a =>\n           forall (ts : Terms (arityF L a))\n                  (ss : Terms (arityF L g))\n                  (q : arityF L a = arityF L g),\n             eq_rec (arityF L a)\n               (fun x : nat => Terms x) ts\n               (arityF L g) q = ss <-> \n               apply a ts = apply g ss).\n    - intros ts ss q; \n        apply\n          K_dec_set\n        with\n        (x := arityF L g)\n        (P := fun z =>\n                eq_rec (arityF L g)\n                  (fun x : nat => Terms x) ts\n                  (arityF L g) z = ss <->\n                  apply g ts = apply g ss).\n      apply eq_nat_dec; simpl in |- *.\n      split.\n      + intros H; rewrite <- H; auto.\n      + intros H; inversion H as [H1].\n        eapply\n          inj_right_pair2 with\n          (P := \n             fun f : Functions L =>\n               Terms (arityF L f)); assumption.\n    - auto.\n  }\n  intro x; elim x using\n             Term_Terms_rec_full\n    with\n    (P0 := fun (n : nat) (ts : Terms n) =>\n             forall ss : Terms n, {ts = ss} + {ts <> ss}).\n  intros n y; induction y as [n0| f t].\n  induction (eq_nat_dec n n0) as [a0 | b0].\n  + rewrite a0; left; auto.\n  + right; intro H0; inversion H0; contradiction.\n  + right; discriminate.\n  + intros f t H0 y; induction y as [n| f0 t0].\n    * right; discriminate.\n    * induction (a f f0).\n      assert (H1: arityF L f0 = arityF L f).\n      { rewrite a0. reflexivity. }\n      set (ss' := eq_rec _ (fun z : nat => Terms z) t0 _ H1) in *.\n      assert (H2: f0 = f) by auto.\n      induction (H0 ss').\n      -- left; induction (H _ _ H2 t0 t H1).\n         symmetry  in |- *; apply H3; symmetry  in |- *.\n         apply a1.\n      -- right.\n         intros H3.  induction (H _ _ H2 t0 t H1) as [H4 H5].\n         elim b0;  symmetry  in |- *; apply H5.\n         symmetry  in |- *; assumption.\n      -- right. intro H1; inversion H1.\n         contradiction. \n  + left; apply nilTerms.\n  + intros n t H0 t0 H1 ss.\n    induction (consTerms _ ss).\n    induction x0 as (a0, b0); simpl in p.\n    induction (H1 b0)  as [a1 | b1].\n    * induction (H0 a0).\n      -- left; rewrite a1, a2; assumption.\n      -- right; intro H2.\n         elim b1.\n         rewrite <- p in H2; inversion H2; reflexivity. \n    * right; intro H2; elim b1.\n      rewrite <- p in H2; inversion H2.\n      eapply inj_right_pair2 with (P := fun n : nat => Terms n).\n      apply eq_nat_dec.\n      assumption.\nQed.\n\n(* TODO -> terms_eqdec *)\n(* begin snippet formDec3:: no-out *)\nLemma terms_dec n  (x y : Terms n): {x = y} + {x <> y}.\n(* end snippet formDec3 *)\nProof.\n  induction x as [| n t x Hrecx].\n  - left; apply nilTerms.\n  - induction (consTerms _ y) as [(a,b) p].\n    simpl in p.\n    induction (Hrecx b) as [a0 | b0].\n    + induction (term_dec t a) as [a1| b0].\n      * left; now rewrite a1, a0.\n      * right. intro H; elim b0.\n        rewrite <- p in H.\n        inversion H; reflexivity.\n    + right. intro H; elim b0.\n      rewrite <- p in H.\n      inversion H.\n      eapply inj_right_pair2 with (P := fun n : nat => Terms n).\n      * apply eq_nat_dec.\n      * assumption.\nQed.\n\n(*  -> formula_eqdec *)\n\n(* begin snippet formDec4:: no-out *)\nLemma formula_dec : forall x y : Formula, {x = y} + {x <> y}.\n(* end snippet formDec4 *)\nProof.\n  induction language_dec as [a b].\n  simple induction x; simple induction y;\n    (right; discriminate) || intros.\n  - induction (term_dec t t1) as [a0 | b0].\n    + induction (term_dec t0 t2) as [a1 | b0].\n      * left; now rewrite a0, a1.\n      * right; unfold not in |- *. intros H. elim b0.\n        inversion H; reflexivity.\n    + right; unfold not in |- *; intros H; elim b0.\n      inversion H; reflexivity.\n  - induction (b r r0) as [a0 | b0].\n    assert\n (H: forall (f g : Relations L) (p : f = g) \n            (ts : Terms (arityR L f))\n            (ss : Terms (arityR L g))\n            (q : arityR L f = arityR L g),\n     eq_rec _ (fun x => Terms x) ts _ q = ss <-> \n       atomic f ts = atomic g ss).\n    { intros f g p; eapply eq_ind with\n        (x := g)\n        (P := \n           fun a =>\n             forall (ts : Terms (arityR L a))\n                    (ss : Terms (arityR L g))\n                    (q : arityR L a = arityR L g),\n               eq_rec _ (fun x => Terms x) ts _ q = ss <->\n                 atomic a ts = atomic g ss).\n      - intros ts ss q; elim q using K_dec_set.\n        + apply eq_nat_dec.\n        + simpl in |- *; split.\n          * intros H; rewrite H; reflexivity.\n          * intros H; inversion H.\n            eapply inj_right_pair2 with\n              (P := \n                 fun f : Relations L =>\n                   Terms (arityR L f)).\n            -- assumption.\n            -- assumption.\n      - auto.\n    } \n    assert (H0: arityR L r = arityR L r0)\n    by (rewrite a0; reflexivity). \n    induction\n      (terms_dec _\n         (eq_rec (arityR L r) (fun x : nat => Terms x) t\n            (arityR L r0) H0) t0) as [a1 | b1].\n    + left; induction (H _ _ a0 t t0 H0); auto.\n    + right; induction (H _ _ a0 t t0 H0); tauto.\n    + right. intro H; inversion H; auto.\n  - destruct (H f1) as [a0 | b0].\n    + destruct (H0 f2) as [a1 | b1].\n      * left; now rewrite a0, a1.\n      * right; intro H3; inversion H3; auto.\n    + right;  intro H3; inversion H3; auto.\n  - destruct (H f0) as [e | ne].\n    + left; now rewrite e.\n    + right; intro H1; inversion H1; auto.\n  - destruct (eq_nat_dec n n0) as [e | ne]. \n    + destruct (H f0) as [a0 | b0].\n      * left; now rewrite a0, e. \n      * right;  intro H1; inversion H1; auto.\n    + right; inversion 1; auto.\nQed.\n\n(* begin snippet formDec5:: no-out *)\nEnd Formula_Decidability.\n(* end snippet formDec5 *)\n\nSection Formula_Depth_Induction.\n\n(* begin snippet depthDef *)\nFixpoint depth (A : Formula) : nat :=\n  match A with\n  | equal _ _ => 0\n  | atomic _ _ => 0\n  | impH A B => S (Nat.max (depth A) (depth B))\n  | notH A => S (depth A)\n  | forallH _ A => S (depth A)\n  end.\n\nDefinition lt_depth (A B : Formula) : Prop := depth A < depth B.\n(* end snippet depthDef *)\n\nLemma depthImp1 : forall A B : Formula, lt_depth A (impH A B).\nProof.\n  intros A B; red; apply Nat.lt_succ_r, Nat.le_max_l.\nQed.\n\nLemma depthImp2 : forall A B : Formula, lt_depth B (impH A B).\nProof.\n  intros A B; red; apply Nat.lt_succ_r, Nat.le_max_r.\nQed.\n\nLemma depthNot : forall A : Formula, lt_depth A (notH A).\nProof. intro A; red; auto. Qed.\n\nLemma depthForall : forall (A : Formula) (v : nat), \n    lt_depth A (forallH v A).\nProof. intros A v; red; auto. Qed.\n\nLemma eqDepth :\n forall A B C : Formula, depth B = depth A ->\n                         lt_depth B C -> lt_depth A C.\nProof. intros A B C H; red; now rewrite <- H. Qed.\n\n(* Todo: upgrade to Type/rect  *)\nDefinition Formula_depth_rec_rec :\n  forall P : Formula -> Set,\n  (forall a : Formula, (forall b : Formula, lt_depth b a -> P b) -> P a) ->\n  forall (n : nat) (b : Formula), depth b <= n -> P b.\nProof. \n intros P H n; induction n as [| n Hrecn].\n - intros b H0; apply H.\n   intros b0 H1; unfold lt_depth in H1.\n   rewrite Nat.le_0_r in H0; rewrite H0 in H1. \n   apply Nat.nlt_0_r in H1. contradiction.\n - intros b H0; apply H.\n   intros b0 H1; apply Hrecn; apply Nat.lt_succ_r .\n   apply Nat.lt_le_trans with (depth b).\n   + apply H1.\n   + apply H0.\nDefined.\n\n(* Todo: upgrade to Type/rect  *)\nDefinition Formula_depth_rec (P : Formula -> Set)\n  (rec : forall a : Formula, \n      (forall b : Formula, lt_depth b a -> P b) -> P a)\n  (a : Formula) : P a :=\n  Formula_depth_rec_rec P rec (depth a) a (le_n (depth a)).\n\n(* solves a compatibility issue *)\n\n(* Todo: upgrade to Type/rect  *)\nLemma Formula_depth_rec_indep :\n forall (Q P : Formula -> Set)\n   (rec : forall a : Formula,\n          (forall b : Formula, lt_depth b a -> Q b -> P b) -> Q a -> P a),\n (forall (a : Formula)\n    (z1 z2 : forall b : Formula, lt_depth b a -> Q b -> P b),\n  (forall (b : Formula) (p : lt_depth b a) (q : Q b), z1 b p q = z2 b p q) ->\n  forall q : Q a, rec a z1 q = rec a z2 q) ->\n forall (a : Formula) (q : Q a),\n Formula_depth_rec (fun x : Formula => Q x -> P x) rec a q =\n rec a\n   (fun (b : Formula) _ =>\n    Formula_depth_rec (fun x : Formula => Q x -> P x) rec b) q.\nProof.\n  intros Q P rec H.\n  unfold Formula_depth_rec in |- *.\n  set (H0 := Formula_depth_rec_rec (fun x : Formula => Q x -> P x) rec) \n    in *.\n  assert\n    (H1: forall (n m : nat) (b : Formula) (l1 : depth b <= n) \n                (l2 : depth b <= m) (q : Q b), H0 n b l1 q = H0 m b l2 q).\n  { simple induction n.\n    - simpl in |- *.\n      intros m b l1 l2 q; induction m as [| m Hrecm].\n      + simpl in |- *; apply H.\n        intros b0 p q0. \n        induction  (* Warning to fix *)\n          (Nat.nlt_0_r (depth b0)\n             (eq_ind_r (fun n0 : nat => depth b0 < n0) p\n                (Compat815.le_n_0_eq (depth b) l1))).\n      + intros; simpl ; apply H.\n        intros b0 p q0.\n        induction (* warning to fix *)\n          (Nat.nlt_0_r (depth b0)\n             (eq_ind_r (fun n0 : nat => depth b0 < n0) p\n                (Compat815.le_n_0_eq (depth b) l1))).\n    - simple induction m.\n      + intros b l1 l2 q; simpl in |- *; apply H.\n        intros  b0 p q0.\n        induction (*warning to fix *)\n          (Nat.nlt_0_r  (depth b0)\n             (eq_ind_r (fun n1 : nat => depth b0 < n1) p\n                (Compat815.le_n_0_eq (depth b) l2))).\n      + intros n1 H2 b l1 l2 q;  simpl in |- *; apply H.\n        intros  b0 p q0.\n        apply H1.\n  } \n  intros a q;\n    replace (H0 (depth a) a (le_n (depth a)) q) with\n    (H0 (S (depth a)) a (Nat.le_succ_diag_r (depth a)) q).\n  - simpl in |- *; apply H.\n    intros; apply H1.\n  - apply H1.\nQed.\n\n(* Todo: upgrade to Type/rect  *)\nDefinition Formula_depth_rec2rec (P : Formula -> Set)\n  (f1 : forall t t0 : Term, P (equal t t0))\n  (f2 : forall (r : Relations L) \n               (t : Terms (arityR L r)),\n        P (atomic r t))\n  (f3 : forall f : Formula, P f -> forall f0 : Formula, P f0 -> P (impH f f0))\n  (f4 : forall f : Formula, P f -> P (notH f))\n  (f5 : forall (v : nat) (a : Formula),\n        (forall b : Formula, lt_depth b (forallH v a) -> P b) ->\n        P (forallH v a)) (a : Formula) :\n  (forall b : Formula, lt_depth b a -> P b) -> P a :=\n  match a return ((forall b : Formula, lt_depth b a -> P b) -> P a) with\n  | equal t s => fun _ => f1 t s\n  | atomic r t => fun _ => f2 r t\n  | impH f g =>\n      fun hyp => f3 f (hyp f (depthImp1 f g)) g (hyp g (depthImp2 f g))\n  | notH f => fun hyp => f4 f (hyp f (depthNot f))\n  | forallH n f => fun hyp => f5 n f hyp\n  end.\n\n(* Todo: upgrade to Type/rect  *)\nDefinition Formula_depth_rec2 (P : Formula -> Set)\n  (f1 : forall t t0 : Term, P (equal t t0))\n  (f2 : forall (r : Relations L) (t : Terms (arityR L r)),\n        P (atomic r t))\n  (f3 : forall f : Formula, P f -> forall f0 : Formula, P f0 -> P (impH f f0))\n  (f4 : forall f : Formula, P f -> P (notH f))\n  (f5 : forall (v : nat) (a : Formula),\n        (forall b : Formula, lt_depth b (forallH v a) -> P b) ->\n        P (forallH v a)) (a : Formula) : P a :=\n  Formula_depth_rec P (Formula_depth_rec2rec P f1 f2 f3 f4 f5) a.\n\n(* Todo: upgrade to Type/rect  *)\nRemark Formula_depth_rec2rec_nice :\n forall (Q P : Formula -> Set)\n   (f1 : forall t t0 : Term, Q (equal t t0) -> P (equal t t0))\n   (f2 : forall (r : Relations L) \n                (t : Terms (arityR L r)),\n         Q (atomic r t) -> P (atomic r t))\n   (f3 : forall f : Formula,\n         (Q f -> P f) ->\n         forall f0 : Formula,\n         (Q f0 -> P f0) -> Q (impH f f0) -> P (impH f f0)),\n (forall (f g : Formula) (z1 z2 : Q f -> P f),\n  (forall q : Q f, z1 q = z2 q) ->\n  forall z3 z4 : Q g -> P g,\n  (forall q : Q g, z3 q = z4 q) ->\n  forall q : Q (impH f g), f3 f z1 g z3 q = f3 f z2 g z4 q) ->\n forall f4 : forall f : Formula, (Q f -> P f) -> Q (notH f) -> P (notH f),\n (forall (f : Formula) (z1 z2 : Q f -> P f),\n  (forall q : Q f, z1 q = z2 q) ->\n  forall q : Q (notH f), f4 f z1 q = f4 f z2 q) ->\n forall\n   f5 : forall (v : nat) (a : Formula),\n        (forall b : Formula, lt_depth b (forallH v a) -> Q b -> P b) ->\n        Q (forallH v a) -> P (forallH v a),\n (forall (v : nat) (a : Formula)\n    (z1 z2 : forall b : Formula, lt_depth b (forallH v a) -> Q b -> P b),\n  (forall (b : Formula) (q : lt_depth b (forallH v a)) (r : Q b),\n   z1 b q r = z2 b q r) ->\n  forall q : Q (forallH v a), f5 v a z1 q = f5 v a z2 q) ->\n forall (a : Formula)\n   (z1 z2 : forall b : Formula, lt_depth b a -> Q b -> P b),\n (forall (b : Formula) (p : lt_depth b a) (q : Q b), z1 b p q = z2 b p q) ->\n forall q : Q a,\n Formula_depth_rec2rec (fun x : Formula => Q x -> P x) f1 f2 f3 f4 f5 a z1 q =\n Formula_depth_rec2rec (fun x : Formula => Q x -> P x) f1 f2 f3 f4 f5 a z2 q.\nProof.\n  intros Q P f1 f2 f3 H f4 H0 f5 H1 a z1 z2 H2 q.\n  induction a as [t t0| r t| a1 Hreca1 a0 Hreca0| a Hreca| n a Hreca].\n  - auto.\n  - auto.\n  - simpl in |- *; apply H.\n    + intros q0; apply H2.\n    + intros q0; apply H2.\n  - simpl in |- *; apply H0; intros q0; apply H2.\n  - simpl in |- *; apply H1, H2.\nQed.\n\n(* Todo: upgrade to Type/rect  *)\nLemma Formula_depth_rec2_imp :\n  forall (Q P : Formula -> Set)\n         (f1 : forall t t0 : Term, Q (equal t t0) -> P (equal t t0))\n         (f2 : forall (r : Relations L) \n                      (t : Terms (arityR L r)),\n             Q (atomic r t) -> P (atomic r t))\n         (f3 : forall f : Formula,\n             (Q f -> P f) ->\n             forall f0 : Formula,\n               (Q f0 -> P f0) -> Q (impH f f0) -> P (impH f f0)),\n    (forall (f g : Formula) (z1 z2 : Q f -> P f),\n        (forall q : Q f, z1 q = z2 q) ->\n        forall z3 z4 : Q g -> P g,\n          (forall q : Q g, z3 q = z4 q) ->\n          forall q : Q (impH f g), f3 f z1 g z3 q = f3 f z2 g z4 q) ->\n    forall f4 : forall f : Formula, (Q f -> P f) -> Q (notH f) -> P (notH f),\n      (forall (f : Formula) (z1 z2 : Q f -> P f),\n          (forall q : Q f, z1 q = z2 q) ->\n          forall q : Q (notH f), f4 f z1 q = f4 f z2 q) ->\n      forall\n        f5 : forall (v : nat) (a : Formula),\n        (forall b : Formula, lt_depth b (forallH v a) -> Q b -> P b) ->\n        Q (forallH v a) -> P (forallH v a),\n        (forall (v : nat) (a : Formula)\n                (z1 z2 : forall b : Formula, \n                    lt_depth b (forallH v a) -> Q b -> P b),\n            (forall (b : Formula) (q : lt_depth b (forallH v a)) (r : Q b),\n                z1 b q r = z2 b q r) ->\n            forall q : Q (forallH v a), f5 v a z1 q = f5 v a z2 q) ->\n        forall (a b : Formula) (q : Q (impH a b)),\n          Formula_depth_rec2 (fun x : Formula => Q x -> P x) f1 f2 f3 f4 f5 \n            (impH a b) q =\n            f3 a (Formula_depth_rec2 (fun x : Formula => Q x -> P x) f1 f2 f3 f4 f5 a) b\n              (Formula_depth_rec2 (fun x : Formula => Q x -> P x) f1 f2 f3 f4 f5 b) q.\nProof.\n  intros; unfold Formula_depth_rec2 at 1 in |- *; \n    rewrite Formula_depth_rec_indep.\n  - simpl in |- *; reflexivity.\n  - intros; apply Formula_depth_rec2rec_nice; auto.\nQed.\n\n(* Todo: upgrade to Type/rect  *)\nLemma Formula_depth_rec2_not :\n forall (Q P : Formula -> Set)\n   (f1 : forall t t0 : Term, Q (equal t t0) -> P (equal t t0))\n   (f2 : forall (r : Relations L) \n                (t : Terms (arityR L r)),\n         Q (atomic r t) -> P (atomic r t))\n   (f3 : forall f : Formula,\n         (Q f -> P f) ->\n         forall f0 : Formula,\n         (Q f0 -> P f0) -> Q (impH f f0) -> P (impH f f0)),\n (forall (f g : Formula) (z1 z2 : Q f -> P f),\n  (forall q : Q f, z1 q = z2 q) ->\n  forall z3 z4 : Q g -> P g,\n  (forall q : Q g, z3 q = z4 q) ->\n  forall q : Q (impH f g), f3 f z1 g z3 q = f3 f z2 g z4 q) ->\n forall f4 : forall f : Formula, (Q f -> P f) -> Q (notH f) -> P (notH f),\n (forall (f : Formula) (z1 z2 : Q f -> P f),\n  (forall q : Q f, z1 q = z2 q) ->\n  forall q : Q (notH f), f4 f z1 q = f4 f z2 q) ->\n forall\n   f5 : forall (v : nat) (a : Formula),\n        (forall b : Formula, lt_depth b (forallH v a) -> Q b -> P b) ->\n        Q (forallH v a) -> P (forallH v a),\n (forall (v : nat) (a : Formula)\n    (z1 z2 : forall b : Formula, lt_depth b (forallH v a) -> Q b -> P b),\n  (forall (b : Formula) (q : lt_depth b (forallH v a)) (r : Q b),\n   z1 b q r = z2 b q r) ->\n  forall q : Q (forallH v a), f5 v a z1 q = f5 v a z2 q) ->\n forall (a : Formula) (q : Q (notH a)),\n Formula_depth_rec2 \n   (fun x : Formula => Q x -> P x) f1 f2 f3 f4 f5 (notH a) q =\n   f4 a (Formula_depth_rec2 (fun x : Formula => Q x -> P x) \n           f1 f2 f3 f4 f5 a) q.\nProof.\n  intros; unfold Formula_depth_rec2 at 1; rewrite Formula_depth_rec_indep.\n  - reflexivity.\n  - apply Formula_depth_rec2rec_nice; auto.\nQed.\n\n(* Formula_depth_rec2_forall is used in\ncodeSubFormula.v:917: (Formula_depth_rec2_forall L) (in a Proof) \ncodeSubFormula.v:6279: (Formula_depth_rec2_forall L)\nfolProp.v:558: (Formula_depth_rec2_forall L)\n*)\n\n(* Todo: upgrade to Type/rect  *)\nLemma Formula_depth_rec2_forall :\n forall (Q P : Formula -> Set)\n   (f1 : forall t t0 : Term, Q (equal t t0) -> P (equal t t0))\n   (f2 : forall (r : Relations L) (t : Terms (arityR L r)),\n         Q (atomic r t) -> P (atomic r t))\n   (f3 : forall f : Formula,\n         (Q f -> P f) ->\n         forall f0 : Formula,\n         (Q f0 -> P f0) -> Q (impH f f0) -> P (impH f f0)),\n (forall (f g : Formula) (z1 z2 : Q f -> P f),\n  (forall q : Q f, z1 q = z2 q) ->\n  forall z3 z4 : Q g -> P g,\n  (forall q : Q g, z3 q = z4 q) ->\n  forall q : Q (impH f g), f3 f z1 g z3 q = f3 f z2 g z4 q) ->\n forall f4 : forall f : Formula, (Q f -> P f) -> Q (notH f) -> P (notH f),\n (forall (f : Formula) (z1 z2 : Q f -> P f),\n  (forall q : Q f, z1 q = z2 q) ->\n  forall q : Q (notH f), f4 f z1 q = f4 f z2 q) ->\n forall\n   f5 : forall (v : nat) (a : Formula),\n        (forall b : Formula, lt_depth b (forallH v a) -> Q b -> P b) ->\n        Q (forallH v a) -> P (forallH v a),\n (forall (v : nat) (a : Formula)\n    (z1 z2 : forall b : Formula, lt_depth b (forallH v a) -> Q b -> P b),\n  (forall (b : Formula) (q : lt_depth b (forallH v a)) (r : Q b),\n   z1 b q r = z2 b q r) ->\n  forall q : Q (forallH v a), f5 v a z1 q = f5 v a z2 q) ->\n forall (v : nat) (a : Formula) (q : Q (forallH v a)),\n Formula_depth_rec2 (fun x : Formula => Q x -> P x) f1 f2 f3 f4 f5\n   (forallH v a) q =\n f5 v a\n   (fun (b : Formula) _ (q : Q b) =>\n    Formula_depth_rec2 (fun x : Formula => Q x -> P x) f1 f2 f3 f4 f5 b q) q.\nProof. \n  intros Q P f1 f2 f3 H f4 H0 f5 H1 v a q. \n  unfold Formula_depth_rec2 at 1 in |- *; \n    rewrite Formula_depth_rec_indep.\n  - simpl in |- *; apply H1; reflexivity. \n  - apply Formula_depth_rec2rec_nice; auto.\nQed.\n\n(* Todo: use the Type version (when done)  *)\nDefinition Formula_depth_ind :\n  forall P : Formula -> Prop,\n  (forall a : Formula, (forall b : Formula, lt_depth b a -> P b) -> P a) ->\n  forall a : Formula, P a.\nProof.\n  intros P H a; \n    assert (H0: forall (n : nat) (b : Formula), depth b <= n -> P b).\n  { induction n as [| n Hrecn].\n    - intros b H0; apply H.\n      intros b0 H1; unfold lt_depth in H1.\n      rewrite  (Nat.le_0_r) in H0; rewrite H0 in H1.\n      destruct (Nat.nlt_0_r _ H1).\n    - intros b H0; apply H; intros b0 H1.\n      apply Hrecn.\n      apply Nat.lt_succ_r.\n      apply Nat.lt_le_trans with (depth b).\n      + apply H1.\n      + apply H0.\n  }\n  eapply H0; apply le_n.\nQed.\n\nLemma Formula_depth_ind2 :\n forall P : Formula -> Prop,\n (forall t t0 : Term, P (equal t t0)) ->\n (forall (r : Relations L) \n         (t : Terms (arityR L r)),\n     P (atomic r t)) ->\n (forall f : Formula, P f -> forall f0 : Formula, P f0 -> P (impH f f0)) ->\n (forall f : Formula, P f -> P (notH f)) ->\n (forall (v : nat) (a : Formula),\n  (forall b : Formula, lt_depth b (forallH v a) -> P b) -> P (forallH v a)) ->\n forall f : Formula, P f.\nProof.\n  intros P H H0 H1 H2 H3 f; apply Formula_depth_ind.\n  simple induction a; auto.\n  - intros f0 H4 f1 H5 H6; apply H1.\n    + apply H6, depthImp1.\n    + apply H6, depthImp2.\n  - intros f0 H4 H5; apply H2, H5.\n    apply depthNot.\nQed.\n\nEnd Formula_Depth_Induction.\n\nEnd First_Order_Logic.\n\n\nArguments Term_Terms_ind  L P P0 : rename.\nArguments Terms_Term_ind L P P0 : rename.\n\nArguments Term_Terms_rec L P P0 : rename.\nArguments Terms_Term_rec L P P0 : rename.\n\nArguments Term_Terms_rec_full L P P0 : rename.\nArguments Terms_Term_rec_full L P P0 : rename.\n\n(** Changes by PC *)\n\n(* begin snippet implicitArguments *)\nArguments impH {L} _ _.\nArguments notH {L} _.\nArguments forallH {L} _ _.\nArguments orH {L} _ _.\nArguments andH {L} _ _.\nArguments iffH {L} _ _.\nArguments equal {L} _ _.\nArguments existH {L} _ _.\nArguments var {L} _.\nArguments atomic {L} _ _.\nArguments apply {L} _ _.\nArguments ifThenElseH {L} _ _ _.\nArguments Tnil {L}.\nArguments Tcons {L} {n} _ _.\n(* end snippet implicitArguments *)\n\n(** Experimental, unstable !!! \n\nThe original code of this library contains some redefinitions like \n\n<<\nDefinition Formula := Formula LNN.\n>>\n\nWe plan to use systematically implicit arguments and avoid such redefinitions, which make more complex formula and term displaying, e.g. in goals or results of computation.\n\n*)\n\nModule FolNotations.\nDeclare Scope fol_scope.\nDelimit Scope fol_scope with fol.\n\nInfix \"=\" := (equal _): fol_scope.\nInfix \"\\/\" := (orH): fol_scope.\nInfix \"/\\\" := (andH):fol_scope.\nInfix \"->\" := (impH): fol_scope.\nNotation \"~ A\" := (@notH _ A): fol_scope. \nNotation \"A <-> B\" := (@iffH _ A B): fol_scope.\n\n\nNotation k_ t := (apply  (t:Functions _)  (Tnil)).\n\nNotation app1 f arg := \n  (apply  (f: Functions _)  (Tcons arg (Tnil))).\nAbout Tnil.\nNotation app2 f arg1 arg2 := \n  (apply   (f: Functions _) \n     (Tcons  arg1 (Tcons  arg2 (Tnil)))).\n\nNotation \"t = u\" := (@equal _ t u): fol_scope.\nNotation \"t <> u\" := (~ t = u)%fol : fol_scope.\n\n(** the following notations may be used if some computation expands a disjunction, conjuction, etc. in terms of implication and negation *)\n\nReserved Notation \"x '\\/'' y\" (at level 85, right associativity).\nReserved Notation \"x '/\\'' y\" (at level 80, right associativity).\nReserved Notation \"x '<->'' y\" (at level 95, no associativity).\nReserved Notation \"x '<->''' y\" (at level 95, no associativity).\n\n\n\nNotation \"x \\/' y\" := (~ x -> y)%fol : fol_scope. \nNotation \"x /\\' y\" := (~ (~ x \\/'  ~ y))%fol : fol_scope.\nNotation \"x <->'' y\" := ((x -> y) /\\ (y -> x))%fol:  fol_scope.\nNotation \"x <->' y\" := (~ (~ (x -> y) \\/' ~(y -> x)))%fol : fol_scope.\n\n\nNotation exH' v A := (~ (forallH v (~ A)))%fol.\n\nNotation \"'v_' i\" := (var i) (at level 3) : fol_scope.\n\nNotation \"'exH' x .. y , p\" := (existH  x .. (existH y p) ..)\n  (x at level 0, y at level 0, at level 200, right associativity) : fol_scope. \n\nNotation \"'allH' x .. y , p\" := (forallH  x .. (forallH y p) ..)\n  (x at level 0, y at level 0, at level 200, right associativity) : fol_scope. \n\nEnd FolNotations.\n\nExport FolNotations. \n\n\nSection LExamples. \nVariable L: Language. \nVariables P Q : Formula L. \n\nLet ex1 : Formula L :=  (P /\\ Q)%fol. \nAbout impH.\nLet ex2 : Formula L := (~ (~~P -> ~Q))%fol. \nPrint ex2. \nLet ex3 : Formula L:= (~(~P \\/ ~Q))%fol. \nPrint ex3. \nCompute ex3. \nPrint ex1. \nCompute ex1. \n\nCheck (forallH 5 (v_ 5 = v_ 5) -> forallH 0 (v_ 0 = v_ 0))%fol.\n\nEnd LExamples.\n\n(*\n\n\nNotation \"t = u\" := (@equal _ t u): cfol_scope.\n\nNotation app1 f arg := \n  (apply  (f: Functions _) \n     (Tcons  arg Tnil)).\n\nNotation app2 f arg1 arg2 := \n  (apply   (f: Functions _) \n     (Tcons arg1 (Tcons arg2 Tnil))).\n\nNotation v_ := (var).\n\n Section Consistance. \n  Goal forall L A B, @orH L A B = (A \\/ B)%cfol. \n   reflexivity. Qed. \n  \n  Goal forall L A B, andH (L:=L) A B = (A /\\ B)%cfol. \n    reflexivity. Qed.  \n  \n\n End Consistance. \n\nEnd CFOL_notations.\n*)\n\nSection Correctness. \n Variable L: Language.\n Variables P Q R : Formula L. \n\n Goal (P \\/ Q)%fol = (P \\/' Q)%fol.\n reflexivity. \n Qed. \n\nGoal (P /\\ Q)%fol = (P /\\' Q)%fol.\nProof. reflexivity. Qed. \n\n\nEnd Correctness.\n\nSection JustTry.\nVariable L: Language.\nCheck (@var L 1 = var 2)%fol.\nCheck (v_ 1 = v_ 2)%fol: Formula L.\nCheck (exH 1, (v_ 1 = v_ 1))%fol : Formula L.\nCompute (exH 1, (v_ 1 = v_ 1))%fol : Formula L.\n\n\nCheck (v_ 1 = v_ 1 \\/ v_ 2 = v_ 2)%fol: Formula L. \nCompute (v_ 1 = v_ 1 \\/ v_ 2 = v_ 2)%fol: Formula L.\n\nCheck (v_ 1 = v_ 1 \\/ v_ 2 = v_ 2)%fol: Formula L. \nCompute (v_ 1 = v_ 1 \\/ v_ 2 = v_ 2)%fol: Formula L.\n\nCheck (v_ 1 = v_ 1 \\/ v_ 2 = v_ 2)%fol: Formula L. \nCompute (v_ 1 = v_ 1 \\/ v_ 2 = v_ 2)%fol: Formula L.\n\nCheck (v_ 1 = v_ 1 \\/ v_ 2 = v_ 2)%fol: Formula L. \nCompute (v_ 1 = v_ 1 \\/ v_ 2 = v_ 2)%fol: Formula L.\n\nCheck (v_ 1 = v_ 1 <-> ~ v_ 2 = v_ 2)%fol: Formula L. \nCompute (v_ 1 = v_ 1 <-> ~ v_ 2 = v_ 2)%fol: Formula L.\n\nEnd JustTry.\n", "meta": {"author": "coq-community", "repo": "hydra-battles", "sha": "2d211e0b5030d5f77aaaf6366b01fc64ed998c61", "save_path": "github-repos/coq/coq-community-hydra-battles", "path": "github-repos/coq/coq-community-hydra-battles/hydra-battles-2d211e0b5030d5f77aaaf6366b01fc64ed998c61/theories/ordinals/Ackermann/fol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.6907751091729915}}
{"text": "(** * The very classical example of GCD computation in Hoare logic.\n\n This file is part of the \"Tutorial on Hoare Logic\".\n For an introduction to this Coq library,\n see README #or <a href=index.html>index.html</a>#.\n\n This file illustrates how to use the Hoare logic described in file\n #<a href=\"hoarelogicsemantics.html\">#[hoarelogicsemantics]#</a>#\n\n\n I use here the very classical example of \"great common divisor\"\n computations through successive subtractions.\n*)\n\nSet Implicit Arguments.\n\nRequire Import ZArith.\nRequire Import Znumtheory.\nRequire Import hoarelogic.\nRequire Import Zwf.\nRequire Import Wellfounded.\nRequire Import Lia.\n\n(** * Implementation of the expression language *)\nModule Example <: ExprLang.\n\n(** Here, I use only two global variables [VX] and [VY] of type [Z]\n(binary integers). *)\nInductive ExVar: Type -> Type :=\n  VX: (ExVar Z) |\n  VY: (ExVar Z).\n\nDefinition Var:=ExVar.\n\n(** An environment is just a pair of integers. First component\nrepresents [VX] and second component represents [VY].  This is\nexpressed in [upd] and [get] below. *)\nDefinition Env:= (Z*Z)%type.\n\nDefinition upd (A:Type): (ExVar A) -> A -> Env -> Env :=\n fun x =>\n   match x in (ExVar A) return A -> Env -> Env with\n   | VX => fun vx e => (vx,snd e)\n   | VY => fun vy e => (fst e,vy)\n   end.\n\nDefinition get (A:Type): (ExVar A) -> Env -> A :=\n fun x =>\n   match x in (ExVar A) return Env -> A with\n   | VX => fun e => fst e\n   | VY => fun e => snd e\n   end.\n\n(** I consider only two binary operators [PLUS] and [MINUS]. Their\nmeaning is given by [eval_binOP] below *)\nInductive binOP: Type := PLUS | MINUS.\n\nDefinition eval_binOP: binOP -> Z -> Z -> Z :=\n fun op => match op with\n  | PLUS => Zplus\n  | MINUS => Zminus\n end.\n\n(** I consider only three comparison operators [EQ], [NEQ] and\n[LE]. Their meaning is given by [eval_relOP] below *)\nInductive relOP: Type := EQ | NEQ | LE.\n\nDefinition eval_relOP: relOP -> Z -> Z -> bool :=\n fun op => match op with\n  | EQ => Zeq_bool\n  | NEQ => Zneq_bool\n  | LE => Zle_bool\n end.\n\n(** Here is the abstract syntax of expressions. The semantics is given\nby [eval] below *)\nInductive ExExpr: Type -> Type :=\n | const: forall (A:Type), A -> (ExExpr A)\n | binop: binOP -> (ExExpr Z) -> (ExExpr Z) -> (ExExpr Z)\n | relop: relOP -> (ExExpr Z) -> (ExExpr Z) -> (ExExpr bool)\n | getvar: forall (A:Type), (ExVar A) -> (ExExpr A).\n\nDefinition Expr:= ExExpr.\n\nFixpoint eval (A:Type) (expr:Expr A) (e:Env) { struct expr } : A :=\n match expr in ExExpr A return A with\n | const A v => v\n | binop op e1 e2 => eval_binOP op (eval e1 e) (eval e2 e)\n | relop op e1 e2 => eval_relOP op (eval e1 e) (eval e2 e)\n | getvar A x => (get x e)\nend.\n\nEnd Example.\n\n(** * Instantiation of the Hoare logic on this language. *)\nModule HL :=  HoareLogic(Example).\nImport HL.\nImport Example.\n\n(** These coercions makes the abstract syntax more user-friendly *)\nCoercion getvar: ExVar >-> ExExpr.\nCoercion binop: binOP >-> Funclass.\nCoercion relop: relOP >-> Funclass.\n\n(** A last coercion useful for assertions *)\nCoercion get: ExVar >-> Funclass.\n\n(** ** A [gcd] computation in this language *)\nDefinition gcd :=\n  (Iwhile (NEQ VX VY)\n          (Iif (LE VX VY)\n               (Iset VY (MINUS VY VX))\n               (Iset VX (MINUS VX VY)))).\n\n(** A small technical lemma on the mathematical notion of gcd (called\n[Zis_gcd]) *)\nLemma Zgcd_minus: forall a b d:Z, Zis_gcd a (b - a) d -> Zis_gcd a b d.\nProof.\n  intros a b d H; case H; constructor; intuition (auto with zarith).\n  replace b with (b-a+a)%Z.\n  auto with zarith.\n  lia.\nQed.\n\nGlobal Hint Resolve Zgcd_minus: zarith.\n\n(** Two other lemmas relating [Zneq_bool] function with inequality\nrelation *)\nLemma Zneq_bool_false: forall x y, Zneq_bool x y=false -> x=y.\nProof.\n intros x y H0; apply Zcompare_Eq_eq; generalize H0; clear H0; unfold Zneq_bool. case (x ?= y)%Z; auto;\n try (intros; discriminate); auto.\nQed.\n\nLemma Zneq_bool_true: forall x y, Zneq_bool x y=true -> x<>y.\nProof.\n intros x y; unfold Zneq_bool.\n intros H H0; subst.\n rewrite Z.compare_refl in H.\n discriminate.\nQed.\n\nGlobal Hint Resolve Zneq_bool_true Zneq_bool_false Zle_bool_imp_le Zis_gcd_intro: zarith.\n\n(** ** Partial correctness proof of [gcd] *)\nLemma gcd_partial_proof:\n forall x0 y0, (fun e => (VX e)=x0 /\\ (VY e)=y0)\n   |= gcd  {= fun e => (Zis_gcd x0 y0 (VX e)) =}.\nProof.\n intros x0 y0.\n apply PHL.soundness.\n simpl.\n intros e; intuition subst.\n (** after PO generation, I provide the invariant and simplify the goal *)\n constructor 1 with (x:=fun e'=>\n  forall d, (Zis_gcd (VX e') (VY e') d)\n              ->(Zis_gcd (VX e) (VY e) d)); simpl.\n intuition auto with zarith.\n (** - invariant => postcondition *)\n replace (snd e') with (fst e') in H; auto with zarith.\nQed.\n\n\n(** ** Total correctness proof of [gcd] *)\n\nLemma gcd_total_proof:\n forall x0 y0, (fun e => (VX e)=x0 /\\ (VY e)=y0 /\\ x0 > 0 /\\ y0 > 0)\n  |= gcd  [= fun e => (Zis_gcd x0 y0 (VX e)) =].\nProof.\n intros x0 y0.\n apply THL.soundness.\n simpl.\n intros e; intuition subst.\n (** after simplification, I provide the invariant and then the variant *)\n constructor 1 with (x:=fun e' => (VX e') > 0 /\\ (VY e') > 0 /\\\n  forall d, (Zis_gcd (VX e') (VY e') d)\n              ->(Zis_gcd (VX e) (VY e) d)); simpl.\n constructor 1 with (x:=fun e1 e0 => Zwf 0 ((VX e1)+(VY e1)) ((VX e0)+(VY e0))).\n (** - proof that my variant is a well_founded relation *)\n constructor 1.\n apply wf_inverse_image with (f:=fun e=>(VX e)+(VY e)).\n auto with datatypes.\n (** - other goals *)\n  unfold Zwf; simpl; (intuition auto with zarith).\n (** -- invariant => postcondition\n      --- gcd part like in partial correctness proof\n *)\n  replace (snd e') with (fst e') in H5; auto with zarith.\n  (** --- new VY in branch \"then\" is positive *)\n  cut ((fst e')<=(snd e')); auto with zarith.\n  cut ((fst e')<>(snd e')); auto with zarith.\nQed.\n\n(** ** Another example: infinite loops in partial correctness.\n\nBasic Hoare logic is not well-suited for reasoning about non-terminating programs.\nIn total correctness, postconditions of non-terminating programs are not provable.\nIn partial correctness, a non-terminating program satisfies any (unsatisfiable) postcondition.\n\nFor example, in an informal \"meaning\", the program below enumerates all multiples of 3. But this meaning\ncan not be expressed here (even in partial correctness).\n*)\n\nDefinition enum_3N :=\n  (Iseq (Iset VX (const 0))\n        (Iwhile (const true)\n                (Iset VX (PLUS VX (const 3))))).\n\nLemma enum_3N_stupid:\n (fun e => True) |= enum_3N  {= fun e => False =}.\nProof.\n apply PHL.soundness.\n simpl.\n constructor 1 with (x:=fun _:Env => True).\n intuition (discriminate || auto).\nQed.\n\n\n(** \"Tutorial on Hoare Logic\" Library. Copyright 2007 Sylvain Boulme.\n\nThis file is distributed under the terms of the\n \"GNU LESSER GENERAL PUBLIC LICENSE\" version 3.\n*)\n", "meta": {"author": "coq-community", "repo": "hoare-tut", "sha": "66dfb255c9e8bb49269d83b3577b285288f39928", "save_path": "github-repos/coq/coq-community-hoare-tut", "path": "github-repos/coq/coq-community-hoare-tut/hoare-tut-66dfb255c9e8bb49269d83b3577b285288f39928/exgcd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246077301781, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.6907751019943862}}
{"text": "Require Import ssreflect ssrfun seq ssrbool ssrnat fintype eqtype choice.\nRequire Import Setoid Morphisms RelationClasses.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nSection Regex.\n\nVariable sym: eqType.\n\nInductive Regex :=\n| RAny | RSym (sym:sym) | REmp | RVoid | RSeq (r s: Regex) | RAlt (r s: Regex)\n| RStar (r: Regex).\n\n(* Size, depth *)\nFixpoint rsize r :=\nmatch r with\n| RSeq r1 r2 => 1 + rsize r1 + rsize r2\n| RAlt r1 r2 => 1 + rsize r1 + rsize r2\n| RStar r => 1 + rsize r\n| _ => 1\nend.\n\nFixpoint rdepth r :=\nmatch r with\n| RSeq r1 r2 => 1 + max (rdepth r1) (rdepth r2)\n| RAlt r1 r2 => 1 + max (rdepth r1) (rdepth r2)\n| RStar r => 1 + rdepth r\n| _ => 1\nend.\n\n(* Smart constructors *)\nFixpoint rSeq r1 r2 :=\nmatch r1, r2 with\n| _, RVoid => RVoid\n| RVoid, _ => RVoid\n| REmp, _ => r2\n| _, REmp => r1\n| RSeq r1a r1b, _ => RSeq r1a (rSeq r1b r2)\n| _, _ => RSeq r1 r2\nend.\n\n(* This one does balancing too *)\nFixpoint rAlt r1 r2 :=\nmatch r1, r2 with\n| _, RVoid => r1\n| RVoid, _ => r2\n| RAlt r1a r1b, _ => RAlt r1a (rAlt r1b r2)\n| _, _ => RAlt r1 r2\nend.\n\nFixpoint rStar r :=\nmatch r with\n| RVoid => REmp\n| REmp => REmp\n| RStar r => RStar (rStar r)\n| _ => r\nend.\n\n(*======================================================================================\n  Semantic interpretation\n  ======================================================================================*)\nInductive rinterp : Regex -> seq sym -> Prop :=\n| rinterp_RAny b : rinterp RAny [::b]\n| rinterp_REmp : rinterp REmp nil\n| rinterp_RSym b : rinterp (RSym b) [::b]\n| rinterp_RAlt1 r1 r2 l : rinterp r1 l -> rinterp (RAlt r1 r2) l\n| rinterp_RAlt2 r1 r2 l : rinterp r2 l -> rinterp (RAlt r1 r2) l\n| rinterp_RSeq r1 r2 l1 l2 : rinterp r1 l1 -> rinterp r2 l2 -> rinterp (RSeq r1 r2) (l1++l2)\n| rinterp_RStarNil r : rinterp (RStar r) nil\n| rinterp_RStarCons r c l1 l2 : rinterp r (c::l1) -> rinterp (RStar r) l2 -> rinterp (RStar r) (c::(l1++l2)).\n\nLemma rinterpRAny l :\n  rinterp RAny l <-> exists b, l = [::b].\nProof. split => H. inversion H. subst. by exists b.\ndestruct H. subst. apply rinterp_RAny. Qed.\n\nLemma rinterpREmp l :\n  rinterp REmp l <-> l = nil.\nProof. split => H. by inversion H. subst; constructor.\nQed.\n\nLemma rinterpRSym b l :\n  rinterp (RSym b) l <-> l = [::b].\nProof. split => H. inversion H. by subst.\nsubst. apply rinterp_RSym. Qed.\n\nLemma rinterpRVoid l :\n  rinterp RVoid l <-> False.\nProof. split => H. inversion H. done. Qed.\n\nLemma rinterpRAlt (r1 r2: Regex) (l: seq sym) :\n  rinterp (RAlt r1 r2) l <-> rinterp r1 l \\/ rinterp r2 l.\nProof. split => H. inversion H. by left. by right.\ndestruct H. by apply rinterp_RAlt1. by apply rinterp_RAlt2. Qed.\n\nLemma rinterpRSeq (r1 r2: Regex) (l: seq sym) :\n  rinterp (RSeq r1 r2) l <-> exists l1 l2, l = l1++l2 /\\ rinterp r1 l1 /\\ rinterp r2 l2.\nProof. split => H. inversion H. subst. by exists l1, l2.\ndestruct H as [l1 [l2 [-> [H2 H3]]]].  by constructor. Qed.\n\nLemma rinterpRSeqSym (r: Regex) s (l: seq sym) :\n  rinterp (RSeq (RSym s) r) l <-> exists l', l = s::l' /\\ rinterp r l'.\nProof. rewrite rinterpRSeq. simpl.\nsplit. move => [l1 [l2 [H1 [H2 H3]]]]. inversion H2. subst. by exists l2.\nmove => [l' [H1 H2]]. subst. exists [::s]. exists l'. split => //. split => //. constructor.\nQed.\n\nLemma rinterpRStar (r: Regex) (l: seq sym) :\n  rinterp (RStar r) l <->\n  if l is c::l' then\n  (exists l1 l2, l' = l1++l2 /\\ rinterp r (c::l1) /\\ rinterp (RStar r) l2) else True.\nProof. split => H.\n+ destruct l => //. inversion H; subst. by exists l1, l2.\n+ destruct l => //. constructor.\n  destruct H as [l1 [l2 [H1 [H2 H3]]]]. subst. by constructor.\nQed.\n\nHint Rewrite rinterpRAny rinterpREmp rinterpRSym rinterpRVoid rinterpRAlt\n  rinterpRSeqSym rinterpRSeq rinterpRStar : rinterp.\n\n(*======================================================================================\n  Semantic equivalence\n  ======================================================================================*)\nDefinition regexEq (r1 r2: Regex) := forall l, rinterp r1 l <-> rinterp r2 l.\n\nNotation \"x '===' y\" := (regexEq x y) (at level 70, no associativity).\n\nGlobal Instance regexEqEqu : Equivalence regexEq.\nProof. constructor; red => //.\n+ move => r1 r2 H l. firstorder.\n+ move => r1 r2 r3 H1 H2 l. firstorder.\nQed.\n\nGlobal Instance regexEq_RSeq_m: Proper (regexEq ==> regexEq ==> regexEq) RSeq.\nProof. move => r1 r2 EQ1 q1 q2 EQ2 .\nrewrite /regexEq in EQ1, EQ2.\nmove => l.\nsplit => /= H /=.\n+ inversion H. subst. constructor; firstorder.\n+ inversion H. subst. constructor; firstorder.\nQed.\n\nGlobal Instance regexEq_RAlt_m:  Proper (regexEq ==> regexEq ==> regexEq) RAlt.\nProof. move => p1 p2 EQ1 q1 q2 EQ2 .\nmove => l.\nsplit => /= H /=. inversion H; subst.\napply rinterp_RAlt1. firstorder.\napply rinterp_RAlt2. firstorder.\ninversion H; subst.\napply rinterp_RAlt1. firstorder.\napply rinterp_RAlt2. firstorder.\nQed.\n\nGlobal Instance regexEq_rinterp_m: Proper (regexEq ==> eq ==> iff) rinterp.\nProof. move => r1 r2 EQ l1 l2 ->.\nrewrite /regexEq in EQ. firstorder.\nQed.\n\nLemma regexEq_RSeqREmp r : RSeq r REmp === r.\nProof. rewrite /regexEq => l. rewrite rinterpRSeq. simpl (rinterp REmp). simpl.\nsplit => //.  move => [l1 [l2 [H1 [H2 H3]]]]. subst. inversion H3; subst. by rewrite cats0.\nmove => H. exists l, nil. rewrite cats0. firstorder. constructor. Qed.\n\nLemma regexEq_REmpRSeq r : RSeq REmp r === r.\nProof. rewrite /regexEq => l. rewrite rinterpRSeq. simpl (rinterp REmp). simpl.\nsplit => //.  move => [l1 [l2 [H1 [H2 H3]]]]. subst. inversion H2; subst. done.\nmove => H. exists nil, l. firstorder. constructor. Qed.\n\nLemma regexEq_RSeqRVoid r : RSeq r RVoid === RVoid.\nProof. rewrite /regexEq => l. rewrite rinterpRSeq. split => //.\nmove => [l1 [l2 [H1 [H2 H3]]]]. inversion H3. move => H. inversion H.\nQed.\n\nLemma regexEq_RVoidRSeq r : RSeq RVoid r === RVoid.\nProof. rewrite /regexEq => l. rewrite rinterpRSeq. split => //.\nmove => [l1 [l2 [H1 [H2 H3]]]]. inversion H2. move => H. inversion H.\nQed.\n\nLemma regexEq_RAltRVoid r : RAlt r RVoid === r.\nProof. rewrite /regexEq => l. rewrite rinterpRAlt. firstorder. inversion H. Qed.\n\nLemma regexEq_RVoidRAlt r : RAlt RVoid r === r.\nProof. rewrite /regexEq => l. rewrite rinterpRAlt. firstorder. inversion H. Qed.\n\nLemma regexEq_RSeqAssoc r1 r2 r3 : RSeq r1 (RSeq r2 r3) === RSeq (RSeq r1 r2) r3.\nProof. rewrite /regexEq => l. rewrite !rinterpRSeq. split.\n+ move => [l1 [l2 [H1 [H2 H3]]]]. rewrite -> rinterpRSeq in H3.\ndestruct H3 as [l3 [l4 [H4 [H5 H6]]]]. subst. exists (l1++l3), l4. rewrite catA.\nfirstorder. by constructor.\n+ move => [l1 [l2 [H1 [H2 H3]]]]. rewrite -> rinterpRSeq in H2.\ndestruct H2 as [l3 [l4 [H4 [H5 H6]]]]. subst. exists l3, (l4++l2). rewrite catA.\nfirstorder. by constructor.\nQed.\n\nLemma regexEq_RAltAssoc r1 r2 r3 : RAlt r1 (RAlt r2 r3) === RAlt (RAlt r1 r2) r3.\nProof. rewrite /regexEq => l. rewrite !rinterpRAlt. firstorder. Qed.\n\nLemma regexEq_RAltComm r1 r2 : RAlt r1 r2 === RAlt r2 r1.\nProof. rewrite /regexEq => l. rewrite !rinterpRAlt. firstorder. Qed.\n\nLemma regexEq_RStarVoid : RStar RVoid === REmp.\nProof. move => l. autorewrite with rinterp. destruct l => //.\nsplit => // H. destruct H as [l1 [l2 [H1 [H2 H3]]]]. by rewrite -> rinterpRVoid in H2.\nQed.\n\nLemma regexEq_RStarEmp : RStar REmp === REmp.\nProof. move => l. autorewrite with rinterp. destruct l => //.\nsplit => // H. destruct H as [l1 [l2 [H1 [H2 H3]]]]. subst.\nby rewrite -> rinterpREmp in H2.\nQed.\n\n(*\nLemma regexEq_RStarRStar r : RStar (RStar r) === RStar r.\nProof. induction r => l; autorewrite with rinterp.\n+ destruct l => //.\nsplit => H. destruct H as [l1 [l2 [H1 [H2 H3]]]]. subst.\nrewrite -> rinterpRStar in H2.\ndestruct H2 as [l3 [l4 [H4 [H5 H6]]]]. subst.\nrewrite -catA. exists l3, (l4 ++ l2).\n*)\n\nLemma rSeqDef r1 : forall r2, rSeq r1 r2 === RSeq r1 r2.\nProof. induction r1 => r2.\n(* RAny *)\n+ destruct r2 => //.\n  - by rewrite regexEq_RSeqREmp.\n  - by rewrite regexEq_RSeqRVoid.\n(* RSym *)\n+ destruct r2 => //.\n  - by rewrite regexEq_RSeqREmp.\n  - by rewrite regexEq_RSeqRVoid.\n(* REmp *)\n+ rewrite regexEq_REmpRSeq. by destruct r2 => //.\n(* RVoid *)\n+ rewrite regexEq_RVoidRSeq. by destruct r2 => //.\n(* RSeq *)\n+ destruct r2 => //.\n  - by rewrite /= -regexEq_RSeqAssoc IHr1_2.\n  - by rewrite /= -regexEq_RSeqAssoc IHr1_2.\n  - by rewrite -regexEq_RSeqAssoc regexEq_RSeqREmp.\n  - by rewrite regexEq_RSeqRVoid.\n  - by rewrite /= IHr1_2 regexEq_RSeqAssoc.\n  - by rewrite /= IHr1_2 regexEq_RSeqAssoc.\n  - by rewrite /= IHr1_2 regexEq_RSeqAssoc.\n(* RAlt *)\n+ destruct r2 => //.\n  - by rewrite regexEq_RSeqREmp.\n  - by rewrite regexEq_RSeqRVoid.\n(* RStar *)\n+ destruct r2 => //.\n  - by rewrite regexEq_RSeqREmp.\n  - by rewrite regexEq_RSeqRVoid.\nQed.\n\nLemma rAltDef r1 r2 : rAlt r1 r2 === RAlt r1 r2.\nProof. induction r1 => //=.\n+ destruct r2 => //. by rewrite regexEq_RAltRVoid.\n+ destruct r2 => //. by rewrite regexEq_RAltRVoid.\n+ destruct r2 => //. by rewrite regexEq_RAltRVoid.\n+ rewrite regexEq_RVoidRAlt. by destruct r2.\n+ destruct r2 => //. by rewrite regexEq_RAltRVoid.\n+ destruct r2 => //.\n  - by rewrite IHr1_2 regexEq_RAltAssoc.\n  - by rewrite IHr1_2 regexEq_RAltAssoc.\n  - by rewrite IHr1_2 regexEq_RAltAssoc.\n  - by rewrite regexEq_RAltRVoid.\n  - by rewrite IHr1_2 regexEq_RAltAssoc.\n  - by rewrite IHr1_2 regexEq_RAltAssoc.\n  - by rewrite IHr1_2 regexEq_RAltAssoc.\n+ destruct r2 => //.\n  - by rewrite regexEq_RAltRVoid.\nQed.\n\n\n(*======================================================================================\n  Derivatives\n  ======================================================================================*)\n\n(* Nullable transformation *)\nFixpoint rnull (r: Regex) : Regex :=\nmatch r with\n| REmp     => REmp\n| RAlt c1 c2 => rAlt (rnull c1) (rnull c2)\n| RSeq c1 c2 => rSeq (rnull c1) (rnull c2)\n| RStar c => REmp\n| _ => RVoid\nend.\n\nFixpoint rnullable (r: Regex) : bool :=\nmatch r with\n| REmp | RStar _ => true\n| RAlt r1 r2 => rnullable r1 || rnullable r2\n| RSeq r1 r2 => rnullable r1 && rnullable r2\n| _ => false\nend.\n\n(* Derivative of a regexp wrt a symbol *)\nFixpoint rderivSym (s:sym) (r: Regex) : Regex :=\nmatch r with\n| RAny     => REmp\n| RSym b   => if b==s then REmp else RVoid\n| RAlt c d => rAlt (rderivSym s c) (rderivSym s d)\n| RSeq c1 c2 => rAlt (rSeq (rderivSym s c1) c2) (rSeq (rnull c1) (rderivSym s c2))\n| RStar r => rSeq (rderivSym s r) (RStar r)\n| _ => RVoid\nend.\n\n(* Partial Antimirov-style derivative wrt a symbol *)\nDefinition nilRegexes: seq Regex := nil.\nDefinition singletonRegex r: seq Regex := [::r].\nDefinition unionRegexes s1 s2: seq Regex := s1 ++ s2.\n\nFixpoint arderivSym (s:sym) (r: Regex) : seq Regex :=\nmatch r with\n| RAny     => singletonRegex REmp\n| RSym b   => if b==s then singletonRegex REmp else nilRegexes\n| RAlt c d => unionRegexes (arderivSym s c) (arderivSym s d)\n| RSeq r1 r2 => unionRegexes (map (fun r1' => RSeq r1' r2) (arderivSym s r1))\n                             (if rnullable r1 then arderivSym s r2 else nilRegexes)\n| RStar r => map (fun r' => RSeq r' (RStar r)) (arderivSym s r)\n| _ => nilRegexes\nend.\n\n(* Generalization to strings *)\nFixpoint rderivSyms (ss: seq sym) r :=\nif ss is s::ss' then rderivSyms ss' (rderivSym s r) else r.\n\nInductive matches : Regex -> seq sym -> Prop :=\n| matchesEmp r : rinterp r nil -> matches r nil\n| matchesCons r a s : matches (rderivSym a r) s -> matches r (a::s).\n\n\n(* Semantic interpretation of nullable *)\nLemma rinterpNull r : forall l, rinterp (rnull r) l <-> (l = nil /\\ rinterp r nil).\nProof. induction r => l/=; autorewrite with rinterp.\n+ split => //. move => [H1 H2]. by destruct H2.\n+ split => //. by move => [H1 H2].\n+ intuition.\n+ intuition.\n+ rewrite rSeqDef. autorewrite with rinterp.\nsplit.\nmove => H. destruct H as [l1 [l2 [H1 [H2 H3]]]]. subst.\ndestruct (proj1 (IHr1 _) H2) as [H4 H5]. subst.\ndestruct (proj1 (IHr2 _) H3) as [H6 H7]. subst.\nsplit => //. exists nil, nil. intuition.\nmove => [H [l1 [l2 [H3 [H4 H5]]]]].\nsubst. exists l1, l2. split => //.\nsplit. destruct l1 => //.  destruct l2 => //.\nspecialize (IHr1 nil). destruct IHr1 as [I1 I2]. apply I2. intuition.\nspecialize (IHr2 nil). destruct IHr2 as [I1 I2]. destruct l1 => //. destruct l2 => //.\napply I2. intuition.\n+ rewrite rAltDef. autorewrite with rinterp.\nsplit. move => H. destruct H.\n+ destruct (proj1 (IHr1 _) H) as [H1 H2]. intuition.\n+ destruct (proj1 (IHr2 _) H) as [H1 H2]. intuition.\nmove => [H1 H2].\nsubst. destruct H2.\n+ specialize (IHr1 nil). left. by apply (proj2 IHr1).\n+ specialize (IHr2 nil). right. by apply (proj2 IHr2).\n+ intuition.\nQed.\n\n\n(* Semantic interpretation of rderivSym *)\nLemma rinterpDerivSym c r : forall s, rinterp (rderivSym c r) s <-> rinterp r (c::s).\nProof. induction r => s; autorewrite with rinterp.\n(* RAny *)\nsplit => //=. move => ->. by exists c. move => [b H]. congruence.\n(* RSym *)\nsplit => //=.\ncase E: (sym0 == c). rewrite rinterpREmp. move => ->. by rewrite (eqP E).\nby rewrite rinterpRVoid.\ncase E: (sym0 == c). rewrite rinterpREmp. rewrite (eqP E). by move => /=[H].\nmove => [H]/=. by rewrite H eq_refl in E.\n(* REmp *)\nsplit => //=.\n(* RVoid *)\ndone.\n(* RSeq *)\n+ rewrite /= rAltDef 2!rSeqDef rinterpRAlt !rinterpRSeq. split => //= H.\n(* => *)\ndestruct H.\n-\ndestruct H as [l1 [l2 [H1 [H2 H3]]]].\nexists (c::l1), l2. split. by subst. split => //.\nby apply (IHr1 _).\n-\ndestruct H as [l1 [l2 [H1 [H2 H3]]]]. subst.\napply rinterpNull in H2. destruct H2 as [H4 H5]. subst.\nsimpl. exists nil, (c::l2). split => //. split => //.\nby apply (IHr2 l2).\n(* <= *)\ndestruct H as [l1 [l2 [H1 [H2 H3]]]].\ncase E: l1 => [| c' l3].\n-\nsubst. simpl in H1. subst.\nright.\nspecialize (IHr2 s).\ndestruct IHr2 as [I1 I2]. specialize (I2 H3). exists nil, s. split => //. split => //.\nby apply rinterpNull.\n-\nsubst. injection H1 => [H4 H5]. subst. clear H1.\nspecialize (IHr1 l3). destruct IHr1 as [I1 I2].\nspecialize (I2 H2). left.\nexists l3,l2. split => //.\n(* RAlt *)\nrewrite /= rAltDef !rinterpRAlt.\nsplit => //= H.\n(* => *)\ndestruct H.\nleft. by apply IHr1.\nright. by apply IHr2.\n(* <= *)\ndestruct H.\nleft. by apply IHr1.\nright. by apply IHr2.\n(* RStar *)\nrewrite /= rSeqDef rinterpRSeq.\nfirstorder.\nQed.\n\nLemma rinterpDerivSyms s: forall r l, rinterp (rderivSyms s r) l <-> rinterp r (s++l).\nProof. induction s => //= r l. by rewrite IHs rinterpDerivSym. Qed.\n\nGlobal Instance regexEq_rderivSym_m c :\n  Proper (regexEq ==> regexEq) (rderivSym c).\nProof. move => r1 r2 EQ l. by rewrite 2!rinterpDerivSym EQ. Qed.\n\nFixpoint starfree (r: Regex) :=\nmatch r with\n| RAlt r s => starfree r && starfree s\n| RSeq r s => starfree r && starfree s\n| RStar _ => false\n| _ => true\nend.\n\n(* r is expected to be star-free *)\nFixpoint DrvAny (r: Regex) :=\nmatch r with\n| REmp     => RVoid\n| RSym b   => REmp\n| RAny     => REmp\n| RVoid    => RVoid\n| RAlt c1 c2 => rAlt (DrvAny c1) (DrvAny c2)\n| RSeq c1 c2 => rAlt (rSeq (DrvAny c1) c2) (rSeq (rnull c1) (DrvAny c2))\n| RStar c => RVoid\nend.\n\n(* Derivative of a regexp g wrt another regexp r *)\nFixpoint deriv (r: Regex) g :=\nmatch r with\n| REmp     => g\n| RSym b   => rderivSym b g\n| RAny     => DrvAny g\n| RVoid    => RVoid\n| RAlt c1 c2 => rAlt (deriv c1 g) (deriv c2 g)\n| RSeq c1 c2 => deriv c2 (deriv c1 g)\n| RStar c => RVoid\nend.\n\nLemma starfreerSeq r1 r2 : starfree r1 -> starfree r2 -> starfree (rSeq r1 r2).\nProof. move => SF1 SF2. induction r1 => //=. destruct r2 => //;destruct r2 => //.\ndestruct r2 => //; destruct r2 => //. destruct r2 => //. destruct r2 => //=.\nsimpl in SF1. destruct (andP SF1) as [SF1a SF1b]. destruct r2 => //=.\nrewrite IHr1_2 => //. by rewrite SF1a. rewrite SF1a. rewrite IHr1_2 => //.\nrewrite SF1a. rewrite IHr1_2 => //. rewrite SF1a. rewrite IHr1_2 => //.\nsimpl in SF1. destruct (andP SF1) as [SF1a SF1b]. destruct r2 => //=.\nrewrite SF1a. by rewrite SF1b.\nrewrite SF1a. by rewrite SF1b.\nsimpl in SF2. destruct (andP SF2) as [SF2a SF2b].\nby rewrite SF1a SF1b SF2a SF2b.\nsimpl in SF2. destruct (andP SF2) as [SF2a SF2b].\nby rewrite SF1a SF1b SF2a SF2b.\nQed.\n\nLemma starfreerAlt r1 r2 : starfree r1 -> starfree r2 -> starfree (rAlt r1 r2).\nProof. move => SF1 SF2. induction r1 => //=.\ndestruct r2 => //; destruct r2 => //.\ndestruct r2 => //; destruct r2 => //.\ndestruct r2 => //; destruct r2 => //.\ndestruct r2 => //; destruct r2 => //.\nsimpl in SF1. destruct (andP SF1) as [SF1a SF1b]. destruct r2 => //=.\nby rewrite SF1a SF1b.\nby rewrite SF1a SF1b.\nby rewrite SF1a SF1b.\nsimpl in SF2. destruct (andP SF2) as [SF2a SF2b].\nby rewrite SF1a SF1b SF2a SF2b.\nsimpl in SF2. destruct (andP SF2) as [SF2a SF2b].\nby rewrite SF1a SF1b SF2a SF2b.\ndestruct r2 => //=.\nsimpl in SF1. destruct (andP SF1) as [SF1a SF1b].\nrewrite SF1a. rewrite IHr1_2 => //.\nsimpl in SF1. destruct (andP SF1) as [SF1a SF1b].\nrewrite SF1a. rewrite IHr1_2 => //.\nsimpl in SF1. destruct (andP SF1) as [SF1a SF1b].\nrewrite SF1a. rewrite IHr1_2 => //.\nsimpl in SF1. destruct (andP SF1) as [SF1a SF1b].\nsimpl in SF2. destruct (andP SF2) as [SF2a SF2b].\nrewrite SF1a. rewrite IHr1_2 => //.\nsimpl in SF1. destruct (andP SF1) as [SF1a SF1b].\nrewrite SF1a. rewrite IHr1_2 => //.\nQed.\n\nLemma starfreeNull r : starfree r -> starfree (rnull r).\nProof. induction r => //=. move/andP => [R1 R2].\nrewrite starfreerSeq => //. rewrite IHr1 => //.\nrewrite IHr2 => //.\nmove/andP => [R1 R2].\nrewrite starfreerAlt => //. rewrite IHr1 => //. rewrite IHr2 => //.\nQed.\n\nLemma starfreeDrvAny r : starfree r -> starfree (DrvAny r).\nProof. induction r => //=. move/andP => [R1 R2].\napply starfreerAlt => //. apply starfreerSeq => //. apply IHr1 => //.\napply starfreerSeq => //. apply starfreeNull => //.\napply IHr2 => //.\nmove/andP => [R1 R2].\napply starfreerAlt. apply IHr1 => //. apply IHr2 => //.\nQed.\n\nLemma starfreeDerivSym r : forall c, starfree r -> starfree (rderivSym c r).\nProof. induction r => //= c R.\nby destruct (sym0 == c).\ndestruct (andP R) as [R1 R2].\napply starfreerAlt => //. apply starfreerSeq => //. apply IHr1 => //.\napply starfreerSeq => //. apply starfreeNull => //. apply IHr2 => //.\ndestruct (andP R) as [R1 R2].\napply starfreerAlt => //. apply IHr1 => //. apply IHr2 => //.\nQed.\n\nLemma starfreeDeriv r1 : forall r2, starfree r1 -> starfree r2 -> starfree (deriv r1 r2).\nProof. induction r1 => //=.\ndestruct r2 => //=.\nmove => _. move/andP => [R1 R2].\nrewrite starfreerAlt => //. rewrite starfreerSeq => //. apply starfreeDrvAny => //.\nrewrite starfreerSeq => //. apply starfreeNull => //. apply starfreeDrvAny => //.\nmove => _. move/andP => [R1 R2].\nrewrite starfreerAlt => //. apply starfreeDrvAny => //. apply starfreeDrvAny => //.\nmove => r _ R. apply starfreeDerivSym => //.\nmove => r2. move/andP => [R1 R2] R3. apply IHr1_2 => //.\napply IHr1_1 => //.\nmove => r2. move/andP => [R1 R2] R3. apply starfreerAlt.\napply IHr1_1 => //.\napply IHr1_2 => //.\nQed.\n\n(* Semantic definition of non-overlapping *)\nDefinition nonOverlapping r1 r2 := forall l1 l2, rinterp r1 l1 -> rinterp r2 (l1++l2) -> False.\n\n(* This syntactic criterion implies a sensible semantic one *)\nDefinition NonOverlapping r1 r2 := match deriv r1 r2 with RVoid => true | _ => false end.\n\nFixpoint req (r1 r2: Regex) :bool :=\n  match r1, r2 with\n  | RAny, RAny => true\n  | RSym s1, RSym s2 => s1==s2\n  | RVoid, RVoid => true\n  | REmp, REmp => true\n  | RSeq r1a r1b, RSeq r2a r2b => req r1a r2a && req r1b r2b\n  | RAlt r1a r1b, RAlt r2a r2b => req r1a r2a && req r1b r2b\n  | RStar r1, RStar r2 => req r1 r2\n  | _, _ => false\n  end.\n\nDefinition States := seq Regex.\nFixpoint tryLookupState (ss: States) (r: Regex) :=\n  if ss is r'::ss' then\n    if req r r' then Some (size ss') else tryLookupState ss' r\n  else None.\n\nDefinition lookupState (ss: States) (r: Regex) : States * nat :=\n  if tryLookupState ss r is Some i then (ss, i)\n  else (r::ss, size ss).\n\nEnd Regex.\n\nFixpoint explore n (r: Regex bool_eqType) (ss: States _) (t: seq (nat*nat*nat)) :=\n  if tryLookupState ss r is Some i then (ss,t,i)\n  else\n    let ss' := r::ss in\n    let i := size ss in\n\n    if n isn't n.+1 then (ss', t, i)\n    else\n    (* Derivatives wrt 0 and 1 symbols *)\n      let r0 := rderivSym false r in\n      let r1 := rderivSym true r in\n      let: (ss0, t0, i0) := explore n r0 ss' t in\n      let: (ss1, t1, i1) := explore n r1 ss0 t0 in\n      (ss1, (i,i0,i1)::t1, i).\n\nDefinition iterations := 100.\nDefinition MAKEDFA r := explore iterations r nil nil.\n\nExample r := RSeq (RStar (RSeq (RSym false) (RSym true))) (RSym true).\n\nCompute MAKEDFA r.\n\n(* Semantic interpretation of DrvAny *)\nLemma rinterpDrvAny r : starfree r -> forall l,\n  rinterp (DrvAny r) l <-> exists b:bool, rinterp r (b::l).\nProof. move => SF.\ninduction r => l/=.\n+ rewrite rinterpREmp. split => H. subst. exists true. rewrite rinterpRAny. by exists true.\n  destruct H as [b H]. rewrite -> rinterpRAny in H. destruct H as [b2 H]. congruence.\n+ rewrite rinterpREmp. split => H. subst. exists sym. by rewrite rinterpRSym.\n  destruct H as [b H]. rewrite -> rinterpRSym in H. congruence.\n+ split => //. rewrite rinterpRVoid. by move => [b H].\n  move => [b H]. by rewrite -> rinterpREmp in H.\n+ split => //. rewrite rinterpRVoid. by move => [_ H].\n  move => [b H]. by rewrite -> rinterpRVoid in H.\n+ rewrite rAltDef !rSeqDef rinterpRAlt 2!rinterpRSeq.\n  simpl in SF. destruct (andP SF) as [SF1 SF2].\n  split => // H. destruct H.\n  - destruct H as [l1 [l2 [H1 [H2 H3]]]]. subst.\n    destruct (proj1 (IHr1 SF1 _) H2) as [b H4]. exists b. rewrite rinterpRSeq.\n    exists (b::l1), l2. intuition.\n    destruct H as [l1 [l2 [H1 [H2 H3]]]]. subst. rewrite -> rinterpNull in H2.\n    destruct H2 as [H4 H5]. subst. simpl.\n    destruct (proj1 (IHr2 SF2 _) H3) as [b H4]. exists b. rewrite rinterpRSeq.\n    exists nil, (b::l2). intuition.\n  - destruct H as [b H]. rewrite ->rinterpRSeq in H.\n    destruct H as [l1 [l2 [H1 [H2 H3]]]].\n    destruct l1.\n    - right. exists nil, l. split => //. rewrite rinterpNull. split => //.\n      rewrite (IHr2 SF2). simpl in H1. subst. by exists b.\n    - left. inversion H1. subst. exists l1, l2. split => //.\n      rewrite (IHr1 SF1). split => //. by exists s.\n+ simpl in SF. destruct (andP SF) as [SF1 SF2].\nrewrite rAltDef rinterpRAlt. rewrite (IHr1 SF1) (IHr2 SF2).\nsplit => //. move => H. destruct H; destruct H as [b H]; exists b. by apply rinterp_RAlt1.\nby apply rinterp_RAlt2. move => [b H]. rewrite -> rinterpRAlt in H. firstorder.\nby simpl in SF.\nQed.\n\n(* Semantic interpretation of deriv *)\nLemma rinterpDeriv (r2:Regex bool_eqType) : forall r1 s2, starfree r1 -> starfree r2 -> (rinterp (deriv r2 r1) s2 <-> exists s1, rinterp r2 s1 /\\ rinterp r1 (s1 ++ s2)).\nProof. induction r2 => r1 l1 SF1 SF2 //=.\n+ rewrite rinterpDrvAny. split => H. destruct H as [b H]. exists [::b].\n  rewrite rinterpRAny. split => //.  by exists b.\n  destruct H as [l2 H]. rewrite -> rinterpRAny in H. destruct H as [[b H1] H2].\n  subst. by exists b. done.\n+ rewrite -> rinterpDerivSym. split => H. eexists [::sym].\n  rewrite rinterpRSym. by intuition.\n+ destruct H as [s1 [H1 H2]]. rewrite -> rinterpRSym in H1. by subst.\n+ split => H. exists nil. rewrite rinterpREmp. done.\n+ destruct H as [s1 [H1 H2]]. rewrite -> rinterpREmp in H1. by subst.\n+ split => // H. by rewrite -> rinterpRVoid in H.\n  destruct H as [s1 [H1 H2]]. by rewrite -> rinterpRVoid in H1.\n+ simpl in SF2. destruct (andP SF2) as [SF2a SF2b]. rewrite IHr2_2 => //. split.\n  move => [l1' [H1 H2]]. specialize (IHr2_1 r1 (l1'++l1) SF1 SF2a).\n  rewrite -> IHr2_1 in H2.\n  destruct H2 as [l3 [H3 H4]]. exists (l3++l1'). rewrite -catA.  split => //.\n  rewrite rinterpRSeq. exists l3, l1'. intuition.\n  move => [l1' [H1 H2]]. rewrite -> rinterpRSeq in H1.\n  destruct H1 as [l3 [l4 [H3 [H4 H5]]]]. subst.\n  exists l4. split => //.\n  apply IHr2_1 => //.\n  exists l3. rewrite catA. intuition. apply starfreeDeriv => //.\n+ simpl in SF2. destruct (andP SF2) as [SF2a SF2b].\n  rewrite rAltDef rinterpRAlt. rewrite (IHr2_2 _ _ SF1 SF2b). rewrite (IHr2_1 _ _ SF1 SF2a).\n  split => H. destruct H. destruct H as [s1 [H1 H2]]. exists s1. rewrite rinterpRAlt.\n  intuition.\n  destruct H as [s1 [H1 H2]]. exists s1. rewrite rinterpRAlt. intuition.\n  destruct H as [l1' [H1 H2]].\n  rewrite -> rinterpRAlt in H1. destruct H1. left. by exists l1'. right. by exists l1'.\nQed.\n\n(*\nCorollary regexEq_deriv_m :\n  Proper (@regexEq _ ==> @regexEq _ ==> @regexEq _) (@deriv bool_eqType).\nProof. rewrite /regexEq. move => r1 r2 /=EQ q1 q2 /=EQ' l.\nsplit. rewrite -> rinterpDeriv. move => [l' [H1 H2]]. rewrite rinterpDeriv.\nexists l'.  rewrite -EQ' -EQ. intuition.\nmove => [l' [H1 H2]]. exists l'.\nrewrite EQ' EQ. intuition.\nQed.\n\nLemma rinterpSeqSymDeriv (c:bool) r : forall l,\n  rinterp (RSeq (RSym c) (rderivSym c r)) l <-> exists l', l = c::l' /\\ rinterp r l.\nProof.\nmove => l. rewrite rinterpRSeq.  simpl (rinterp _ _).\nsplit.\n+ move => [l1 [l2 [H1 [H2 H3]]]]. subst. rewrite -> rinterpDerivSym in H3. by exists l2.\n+ move => [l' [H1 H2]]. subst. exists [::c], l'. by rewrite rinterpDerivSym.\nQed.\n*)\n\nLemma NonOverlappingSound (r1 r2: Regex bool_eqType) : starfree r1 -> starfree r2 -> NonOverlapping r1 r2 -> nonOverlapping r1 r2.\nProof. rewrite /NonOverlapping/nonOverlapping. move => SF1 SF2 H l1 l2 R1 R2.\ncase E1: (deriv r1 r2); rewrite E1 in H => //.\nhave RDR := @rinterpDeriv r1 r2 l2 SF2 SF1. rewrite E1/= in RDR.\ndestruct RDR as [_ R].\nrewrite -> rinterpRVoid in R. destruct R.\nby exists l1.\nQed.\n\nDefinition onestep (r: Regex _) :=\n  rAlt (rnull r) (\n  rAlt (rSeq (RSym false) (rderivSym false r))\n       (rSeq (RSym true) (rderivSym true r))).\n\nNotation \"x '===' y\" := (regexEq x y) (at level 70, no associativity).\n\n(*\nLemma rinterpOnestep r : onestep r === r.\nProof. rewrite /onestep. rewrite !rAltDef !rSeqDef. elim.\nsimpl. split => H. destruct H. apply rinterpNull in H. intuition.\ndestruct H. destruct H as [l1 [l2 [H1 [H2 H3]]]]. by subst.\ndestruct H as [l1 [l2 [H1 [H2 H3]]]]. by subst.\nleft.\napply rinterpNull.  intuition.\n\nmove => a l.\nrewrite !rinterpRAlt !rinterpNull !rinterpSeqSymDeriv.\nmove => [H1 H2]. split.\nmove => H'. destruct H'. by destruct H.\ndestruct H; firstorder.\nmove => H3.\nright. destruct a. - right. by exists l. - left. by exists l.\nQed.\n\n*)\n\n", "meta": {"author": "jbj", "repo": "x86proved", "sha": "d314fa6d23c064a2be4bf686ac7da16a591fda01", "save_path": "github-repos/coq/jbj-x86proved", "path": "github-repos/coq/jbj-x86proved/x86proved-d314fa6d23c064a2be4bf686ac7da16a591fda01/src/regex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.6907750797361006}}
{"text": "(** * Article 2: A Little Sentential Calculus *)\n\nModule Article_2_A_Little_Sentential_Calculus.\n\n(** printing -> %->% #-># *)\n(** If you take an undergraduate course in\nformal mathematical logic, you might start\nwith analogies to the real world.\nIt's an effective teaching strategy.\nFormal logic has a lot of rules and\na few symbols to learn, and the student\nmight feel anxious about them.\nBut if the student can make a connection\nbetween the familiar and the unfamiliar,\nthen ... well ... there should be less anxiety.\n\nAnalogies have their limits, of course,\nand some analogies are so self-evidently contrived.\nI have to admit that I am about to pose\na contrived example.\n\nLet us suppose that there is an entrepreneur\nnamed Patricia, who makes the most wonderful\nmarmalade out of quinces.\nPatricia always buys her quinces from one\ngrocer, her childhood friend Robert.\nRobert currently runs one store in the fabled\ncity of Sarnia, Ontario, and Patricia has to\ngo to Robert's store to buy her quinces.\n(This would be in the days before DoorDash,\nand I should remind you that other\nfood-delivery services are available.)\nThe question is, if Patricia is about to make\nher new batch of quince marmalade,\nhas she been in Sarnia?\n\nLet's work this out first:\nPatricia is ready to make quince marmalade.\nIf Patricia is ready to make quince marmalade,\nthen it follows that she must have bought quinces.\nIf she bought quinces, and she always buys them from\nRobert, then she must have been in Robert's store.\nIf she was in Robert's store, then she must have\nbeen in Sarnia.\n\nNow, we can write this formally in what is known\nas the Sentential Calculus.  (Keep in mind, this\nis only a little Sentential Calculus.)\nWe do this by assigning letters to sentences\nthat can be either true or false.\n\nLike Article 1, this article is written as\na script in the vernacular of #Coq&#185;,#\nand the text\nthat you are reading is actually written\nas comments delimited by #&#40;&#42;&#42;#\nand #&#42;&#41;# in the script.\n(The coqdoc tool normally does not include\nthe #&#40;&#42;&#42;# and #&#42;&#41;#\ndelimiters, and I have used a trick so\nthat you can see them here.)\n\nThere will also be comments that are\ndelimited by #&#40;&#42;# and #&#42;&#41;;#\nthese comments are what Coq script writers\nwould normally include in a script.\n(The coqdoc tool will include the\n#&#40;&#42;# and #&#42;&#41;# delimiters.)\n\nIn this case, we have four statements:\n\n*)\n\n(* P stands for \"Patricia is prepared to make quince marmalade.\" *)\n\nAxiom P : Prop.\n\n(* Q stands for \"Patricia has bought quinces.\" *)\n\nAxiom Q : Prop.\n\n(* R stands for \"Patricia was in Robert's store.\" *)\n\nAxiom R : Prop.\n\n(* S stands for \"Patricia was in Sarnia.\" *)\n\nAxiom S : Prop.\n\n(**\n\nNote that these sentences are not necessarily True.\nThey could be True, but they could be False as well.\n\nEach sentence is represented by a single letter,\nand each letter is declared to be a [Prop]\n(this word is short for #<em>proposition</em>#).\nIn Coq, a proposition is considered to either\nbe provable or not provable.\n\nIt is now obvious how contrived this example is;\nI needed something for which the letters P, Q, R, and S\ncould stand, and I settled on Patricia, quinces, Robert,\nand Sarnia. I'll come back to that later.\n\nThe Axiom command means that Coq should assume\nsomething without proof.\nIn this case, Coq should assume that\nP, Q, R, and S are propositions.\n\nTo repeat the point about the sentences,\nCoq is not instructed to assume that P\nis True; it is only to assume that P is\na proposition (which we are associating\nwith the sentence\n\"Patricia is prepared to make quince marmalade\").\nSimilarly, Coq is instructed to assume\nthat Q, R, and S are propositions,\nbut not to assume that they are True.\n\nWe now tell Coq to assume that P is true:\n\n**)\n\n(* Pr1 means it is true that \"Patricia is\nprepared to make quince marmalade.\" *)\n\nAxiom Pr1 : P.\n\n(**\n\nThis axiom is called a \"premise\",\nand I have chosen to begin the name of a\npremise with the prefix \"Pr\".\nThis premise states that Coq should\nassume, because of Pr1, that P is True\n(or more correctly, P is provably True).\nBased on his #tutorial,&#178;#\nMichael Nahas would refer to Pr1 as\na proof of P.\n\nBasically, a formal proof of a\nproposition in Coq is constructed\nby listing proofs of other propositions\n(these proofs of other propositions\nare the premises) and then using tactics\nto demonstrate how the premises lead\nto the proposition we want to prove.\nIn our case, the goal is to get a\nproof of S.\nWe cannot get this proof with only\nthe one premise, which is a proof of P.\nWe need more premises.\n\nWe got the first premise from the\nstatement \"Patricia is ready to make\nquince marmalade.\"  As you recall,\nwe had four statements; we therefore\nneed four premises, one for each statement.\n\nSo now, let us make a premise for the\nsecond statement:\n\n**)\n\n(* Pr2 means that \"if Patricia is prepared to make\nquince marmalade, then she must have bought quinces.\" *)\n\nAxiom Pr2 : P -> Q.\n\n(**\n\nThe arrow pointing to the right is read \"implies\".\nHere, we are stating that \"P implies Q\" or\n\"if P is true then Q is true\", or \"P is true only\nif Q is true\".\n\nBut what it really means: if you have a proof of P,\nyou can apply Pr2 to that proof\nand you get another proof, this time a proof of Q.\nWe have a proof of #P&#160;&#8212;#\nthat is, #Pr1&#160;&#8212;#\nso we should be able to get a proof of Q.\n\nWe have converted two of the four sentences\ninto premises.  Now we convert the other two:\n\n**)\n\n(* Pr3 means that \"if Patricia has bought quinces,\nthen she must have been in Robert's store.\" *)\n\nAxiom Pr3 : Q -> R.\n\n(* Pr4 means that \"if Patricia was in Robert's store,\nthen she was in Sarnia.\" *)\n\nAxiom Pr4 : R -> S.\n\n(**\n\nHaving listed our propositions and premises,\nwe now write our theorem.\nRemember that we want to prove that Patricia\nwas in Sarnia, which is designated by S.\nSo we proceed this way:\n\n**)\n\nTheorem T1 : S.\n\nProof.\n\n    assert (MPP5 := Pr2 (Pr1) : Q).\n\n    assert (MPP6 := Pr3 (MPP5) : R).\n\n    assert (MPP7 := Pr4 (MPP6) : S).\n\n    exact MPP7.\n\nQed.\n\n(**\n\nHere, unfortunately, is the complicated bit.\n\nWe have started with four premises,\nnumbered one through four.\nThe first assertion is therefore\nnumbered five.\n\nEach new statement is derived from\ntwo other statements by a method called\n\"Modus Ponendo Ponens\" (which is a Latin phrase\nthat means \"the method that affirms by affirming\").\n\nThe assertion MPP5 affirms Q from\n[ P -> Q ] (Pr2) by affirming P (Pr1).\nThe order is important:\nThe premise with the arrow is named first,\nand the premise proving the left-hand\nside of the arrow is named next,\nand the proposition for which we want\nthe proof is named last.\n\nThe assertion MPP6 affirms R from\n[ Q -> R ] (Pr3) by affirming Q (MPP5).\nThe assertion MPP6 is like MPP5,\nexcept that the proof of the left-hand side\nis not a premise.  The proof of the left-hand\nside is an earlier assertion (MPP5 in particular).\nThis is how proofs work in Coq: you assert\nproofs of some propositions from the premises,\nthen you assert proofs of other propositions\nfrom proofs that you already asserted.\n\nThe assertion MPP7 affirms S from\n[ R -> S ] (Pr4) by affirming R (MPP6).\nDerivation MPP7 affirms S,\nwhich was what we want,\nso we use exact to tell Coq to check\nthat it is indeed what we want.\nWe then end the proof with \"Qed\",\nwhich is short for another Latin phrase,\n\"quod erat demonstrandum\".\n(Mathematical logic employs a lot of Latin.\n\"Quod erat demonstrandum\" means\n\"which was to be demonstrated\".)\nWe could read the \"exact MPP7. Qed.\"\nas \"MPP7 is exactly what was to be demonstrated.\"\n\nNow, the above proof is reminiscent of the way that\nproofs are presented in symbolic logic courses,\nwhere you have to write down a numbered list of formulas,\nand each formula must be justified as a premise,\nan assumption, or as the result of applying a\nrule of inference.  This proof is based\non an exercise in G. M. Hardegree's\n\"Symbolic Logic\" #textbook.&#179;#\nIt's great if you're writing proofs down by hand,\nbecause it's easier to write single letters\nthan whole words.\nBut in the computer age, where typing words is easy,\nwe can be more expressive in formal proofs, like so:\n\n**)\n\nAxiom Patricia_is_prepared_to_make_marmalade : Prop.\n\nAxiom Patricia_has_bought_quinces : Prop.\n\nAxiom Patricia_was_in_Robert's_store : Prop.\n\nAxiom Patricia_was_in_Sarnia : Prop.\n\nAxiom Patricia_is_indeed_prepared_to_make_marmalade\n    : Patricia_is_prepared_to_make_marmalade.\n\nAxiom Patricia_needs_quinces_to_make_marmalade\n    : Patricia_is_prepared_to_make_marmalade\n        -> Patricia_has_bought_quinces.\n\nAxiom Patricia_always_buys_quinces_from_Robert\n    : Patricia_has_bought_quinces\n        -> Patricia_was_in_Robert's_store.\n\nAxiom Robert's_store_is_in_Sarnia\n    : Patricia_was_in_Robert's_store\n        -> Patricia_was_in_Sarnia.\n\nTheorem Patricia_was_indeed_in_Sarnia : Patricia_was_in_Sarnia.\n\nProof.\n\nassert (She_has_indeed_bought_quinces\n    := Patricia_needs_quinces_to_make_marmalade\n        ( Patricia_is_indeed_prepared_to_make_marmalade )\n    : Patricia_has_bought_quinces).\n\nassert (She_was_indeed_in_Robert's_store\n    := Patricia_always_buys_quinces_from_Robert\n        ( She_has_indeed_bought_quinces )\n    : Patricia_was_in_Robert's_store).\n\nassert (She_was_indeed_in_Sarnia\n    := Robert's_store_is_in_Sarnia\n        ( She_was_indeed_in_Robert's_store )\n    : Patricia_was_in_Sarnia).\n\nexact She_was_indeed_in_Sarnia.\n\nQed.\n\n(**\n\nTheorem T1 and theorem [Patricia_was_indeed_in_Sarnia]\nare the same theorem, but in different forms.\nThe first theorem uses abbreviations and is very terse,\nand it has comments explaining everything.\nThe second theorem uses whole words,\nand doesn't need comments, but it is very verbose,\nand I've had to use some conventions.\n(For example, X_was_indeed_Y means that X_was_Y is true.)\n\nSo is theorem [Patricia_was_indeed_in_Sarnia]\neasier to read and follow than theorem T1?\nI would say yes, but [Patricia_was_indeed_in_Sarnia]\nis easier to read than T1 much like the\nthree of clubs ranks higher than the two of clubs.\nIt's only marginally better.\n\nI would say that there is more than one art of\ncomputer programming #(cf. Knuth&#8308;)#\nand one of those arts must be that happy medium\nbetween terse and verbose.\n\nSo that's the second article. My plan for the\nthird article is to strike towards the happy medium.\n\n** References:\n\n#&#185;# Institut national de recherche en\nsciences et technologies du numérique (Inria).\n\"The Coq Proof Assistant.\"\nhttps://coq.inria.fr/\n\n#&#178;# Nahas, Michael.  \"Mike Nahas's Coq Tutorial.\"\nhttps://mdnahas.github.io/doc/nahas_tutorial.v\n\n#&#179;# Hardegree, G. M. (1999)\n    \"Symbolic Logic: A First Course.\"\n    McGraw-Hill College.\n    Section 5.22, exercise 1.\n    <https://courses.umass.edu/phil110-gmh/MAIN/IHome-5.htm>\n\n#&#8308;# Knuth, D. E. (1997, 1998, 2011)\n    \"The Art of Computer Programming.\"\n    Addison-Wesley. Four volumes.\n\n**)\n\nEnd Article_2_A_Little_Sentential_Calculus.\n\n", "meta": {"author": "nullpointersetc", "repo": "Coq_sessions", "sha": "97c9cbae67d17a3ed91d4ce572690efe96a13f10", "save_path": "github-repos/coq/nullpointersetc-Coq_sessions", "path": "github-repos/coq/nullpointersetc-Coq_sessions/Coq_sessions-97c9cbae67d17a3ed91d4ce572690efe96a13f10/Articles/Article_2_A_Little_Sentential_Calculus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.6907040974423604}}
{"text": "(** 4 optional exercises attempted and 4 completed *)\n\n(** Exercise 1(and_assoc) *)\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(** Exercise 2 (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. intros H. inversion H as [[HP | HQ] [HP' | HR]].\n  apply or_introl. apply HP.\n  apply or_introl. apply HP.\n  apply or_introl. apply HP'.\n  apply or_intror. split. apply HQ. apply HR.\nQed.\n\n\n(** Exercise 3 (contrapositive) *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H. unfold not. intros HQF. \n  intros HP. apply H in HP. apply HQF in HP.\n  apply HP.\nQed.\n\n\n(** Exercise 4 ((false_beq_nat) *)\nTheorem beq_nat_false : forall n m,\n  beq_nat n m = false -> n <> m.\nProof.\n  intros n. unfold not. induction n as [| n'].\n  Case \"n = 0\".\n    intros m H. destruct m as [| m'].\n    SCase \"m = 0\". simpl in H. inversion H.\n    SCase \"m = S m'\". intros. inversion H0.\n  Case \"n = S n'\".\n    intros m H. destruct m as [| m'].\n    SCase \"m = 0\". intros. inversion H0.\n    SCase \"m = S m'\". intros. simpl in H. apply IHn' in H. apply H. inversion H0. reflexivity.\nQed.\n\n(** Exercise 5 (optional (proj2))*)\nTheorem proj2 : forall P Q : Prop, \n  P /\\ Q -> Q.\nProof.\n  intros. inversion H. apply H1.\nQed.\n\n(** Exercise 6 (optional (iff_properties)) *)\nTheorem iff_refl : forall P : Prop, \n  P <-> P.\nProof.\n  intros. unfold iff. split.\n    intros. apply H.\n    intros. apply H.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop, \n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R HPQ HQR.\n  inversion HPQ.\n  inversion HQR.\n  unfold iff. split.\n  intros. apply H in H3. apply H1 in H3. apply H3.\n  intros. apply H2 in H3. apply H0 in H3. apply H3.\nQed.\n\n\n(** Exercise 7 (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  apply or_distributes_over_and_1.\n  apply or_distributes_over_and_2.\nQed.\n\n\n(** Exercise 8 (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.\n  Case \"b = true\".\n    destruct c.\n    SCase \"c = true\". inversion H.\n    SCase \"c = false\". right. apply H.\n  Case \"b = false\".\n    destruct c.\n    SCase \"c = true\". left. apply H.\n    SCase \"c = false\". left. apply H.\nQed.\n\n(** Exercise 9 (not_both_true_and_false) *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros P. unfold not. \n  apply contradiction_implies_anything. \nQed.\n\n(** Exercise 10 (excluded_middle_irrefutable) *)\nTheorem excluded_middle_irrefutable:  forall (P:Prop), ~ ~ (P \\/ ~ P).\nProof.\n  intros. unfold not. intros. apply H.\n  right. intros. apply H.\n  left. apply H0.\nQed.\n", "meta": {"author": "surenz20", "repo": "CS6463", "sha": "2325abfb1d5c18104c05d4d29bf9fe1bd7de0558", "save_path": "github-repos/coq/surenz20-CS6463", "path": "github-repos/coq/surenz20-CS6463/CS6463-2325abfb1d5c18104c05d4d29bf9fe1bd7de0558/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.6907040936947316}}
{"text": "(* \n  Autor(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\n(* \n  Problem(s):\n    Recognizing axiomatizations of Hilbert-style calculi (HSC_AX)\n    (Linial-Post theorem, strengthened by Bokov [1,2])\n\n  HSC_AX:\n    Given a list s₁,...,sₙ of formulae such that \n    [a → b → a] ⊢ sᵢ is derivable for i = 1...n,\n    is [s₁,...,sₙ] ⊢ a → b → a derivable?\n  \n  References:\n    [1] Grigoriy V. Bokov: Undecidable problems for propositional calculi with implication. \n      Logic Journal of the IGPL, 24(5):792–806, 2016. doi:10.1093/jigpal/jzw013\n    [2] Andrej Dudenhefner, Jakob Rehof: Lower End of the Linial-Post Spectrum. \n      TYPES 2017: 2:1-2:15. doi: 10.4230/LIPIcs.TYPES.2017.2\n*)\n\nRequire Import PeanoNat.\nRequire Import List.\nImport ListNotations.\n\nFrom Undecidability.HSC Require Import HSC_prelim.\n\n(* the formula a → b → a *)\nDefinition a_b_a : formula := arr (var 0) (arr (var 1) (var 0)).\n\n(* list of formulae derivable from a → b → a *)\nDefinition HSC_AX_PROBLEM := { Gamma: list formula | forall s, In s Gamma -> hsc [a_b_a] s}.\n\n(* is the formula a → b → a derivable? *)\nDefinition HSC_AX (l: HSC_AX_PROBLEM) := hsc (proj1_sig l) a_b_a.\n", "meta": {"author": "uds-psl", "repo": "2020-types-propositional-calculi", "sha": "87d61951f216881ccb45984349031915b2f842ee", "save_path": "github-repos/coq/uds-psl-2020-types-propositional-calculi", "path": "github-repos/coq/uds-psl-2020-types-propositional-calculi/2020-types-propositional-calculi-87d61951f216881ccb45984349031915b2f842ee/HSC/HSC_AX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505376715777, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.690685992334449}}
{"text": "Require Import Reals.\nLocal Open Scope R_scope.\nFrom ValidSDP Require Import validsdp.\n\nLet p (x0 x1 x2 x3 x4 x5 : R) :=\n  (0 - x1) * x2 - x0 * x3 + x1 * x4 + x2 * x5 - x4 * x5\n  + x0 * (0 - x0 + x1 + x2 - x3 + x4 + x5).\n\nLet b1 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x0 - 4/1) * (40401/10000 - x0).\n\nLet b2 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x1 - 4/1) * (40401/10000 - x1).\n\nLet b3 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x2 - 784/100) * (8/1 - x2).\n\nLet b4 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x3 - 4/1) * (40401/10000 - x3).\n\nLet b5 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x4 - 4/1) * (40401/10000 - x4).\n\nLet b6 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x5 - 784/100) * (8/1 - x5).\n\nTheorem p_nonneg (x0 x1 x2 x3 x4 x5 : R) :\n  b1 x0 x1 x2 x3 x4 x5 >= 0 ->\n  b2 x0 x1 x2 x3 x4 x5 >= 0 ->\n  b3 x0 x1 x2 x3 x4 x5 >= 0 ->\n  b4 x0 x1 x2 x3 x4 x5 >= 0 ->\n  b5 x0 x1 x2 x3 x4 x5 >= 0 ->\n  b6 x0 x1 x2 x3 x4 x5 >= 0 ->\n  p x0 x1 x2 x3 x4 x5 >= 0.\nProof.\nunfold b1, b2, b3, b4, b5, b6, p.\nvalidsdp.\nQed.\n", "meta": {"author": "validsdp", "repo": "validsdp", "sha": "135dd32a2b1166f357df764b469ce14e24711536", "save_path": "github-repos/coq/validsdp-validsdp", "path": "github-repos/coq/validsdp-validsdp/validsdp-135dd32a2b1166f357df764b469ce14e24711536/benchs/flyspeck/fs8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6906521298922499}}
{"text": "(* This file was tested with coq 8.10.0 and coquelicot 3.0.4 *)\n\nRequire Import Reals Coquelicot.Coquelicot Psatz.\n\nLemma lim_atan_p_infty :\n  filterlim atan (Rbar_locally p_infty) (at_left (PI/2)).\nProof.\nassert (0 < PI) by (assert (t := PI2_RGT_0); psatzl R).\nintros S [ep Pep].\nset (e' := Rmin (PI/2) ep).\nassert (0 < e') by now apply Rmin_glb_lt; destruct ep; auto; psatzl R.\nassert (e' <= PI/2) by apply Rmin_l.\nexists (tan (PI/2 - e')); intros x Px.\nassert (atan x < PI/2) by (destruct (atan_bound x); psatzl R).\napply Pep;[|psatzl R].\nchange (Rabs (atan x - PI/2) < ep).\nrewrite Rabs_left, Ropp_minus_distr;[| psatzl R].\napply Rlt_le_trans with (PI / 2 - atan (tan (PI / 2 - e'))).\n  now apply Rplus_lt_compat_l, Ropp_lt_contravar, atan_increasing.\nreplace (atan (tan (PI / 2 - e'))) with (PI / 2 - e').\n  now ring_simplify; apply Rmin_r.\napply tan_is_inj;[psatzl R | apply atan_bound | now rewrite atan_right_inv].\nQed.\n\nLemma lim_atan_m_infty :\n  filterlim atan (Rbar_locally m_infty) (at_right (-PI/2)).\nProof.\napply filterlim_ext with (fun x => - (atan (- x))).\n  now intros; rewrite atan_opp, Ropp_involutive.\napply (filterlim_comp _ _ _ (fun x => atan (- x)) Ropp _ (at_left (PI/2))).\n  apply (filterlim_comp _ _ _ Ropp atan _ (Rbar_locally p_infty)).\n    now apply filterlim_Rbar_opp.\n  now apply lim_atan_p_infty.\nreplace (- PI / 2) with (- (PI / 2)) by field.\napply filterlim_Ropp_left.\nQed.\n\nLemma atan_left_inv x : -PI / 2 < x < PI / 2 -> atan (tan x) = x.\nProof.\nintros [intx1 intx2].\ndestruct (atan_bound (tan x)).\ndestruct (Rtotal_order (atan (tan x)) x) as [abs | [ it | abs]]; auto;\n  apply tan_increasing in abs; try lra; rewrite atan_right_inv in abs;\n  lra.\nQed.\n\nLemma atan_lim_pinfty : Lim atan p_infty = PI/2.\nProof. \nassert (t := PI2_RGT_0).\napply is_lim_unique; intros P [eps Peps].\nassert (ep2 : 0 < Rmin eps (PI/4)).\n  apply Rmin_glb_lt;[apply cond_pos | lra].\nset (eps' := mkposreal _ ep2).\nassert (eps' < PI / 2).\n  unfold eps'; simpl.\n  apply Rle_lt_trans with (PI/4).\n    now apply Rmin_r.\n  lra.\nassert (eps' <= eps).\n  now unfold eps'; simpl; apply Rmin_l.\nassert (0 < eps') by apply cond_pos.\nexists (tan (PI / 2 - eps')); intros x cx.\napply Peps. change (Rabs (atan x -PI/2) < eps).\n  rewrite Rabs_left; cycle 1.\n  destruct (atan_bound x); lra.\nenough (PI / 2 - eps' < atan x) by lra.\nrewrite <- (atan_left_inv (PI/2 - eps')); cycle 1.\n  now split; psatzl R.\nnow apply atan_increasing.\nQed.\n\nLemma atan_lim_minfty : Lim atan m_infty = -PI/2.\nProof. \nassert (t := PI2_RGT_0).\napply is_lim_unique; intros P [eps Peps].\nassert (ep2 : 0 < Rmin eps (PI/4)).\n  apply Rmin_glb_lt;[apply cond_pos | lra].\nset (eps' := mkposreal _ ep2).\nassert (eps' < PI / 2).\n  unfold eps'; simpl.\n  apply Rle_lt_trans with (PI/4).\n    now apply Rmin_r.\n  lra.\nassert (eps' <= eps).\n  now unfold eps'; simpl; apply Rmin_l.\nassert (0 < eps') by apply cond_pos.\nexists (tan (-PI / 2 + eps')); intros x cx.\napply Peps; change (Rabs (atan x - -PI/2) < eps).\n  rewrite Rabs_right; cycle 1.\n  destruct (atan_bound x); lra.\nenough (atan x < -PI / 2 + eps') by lra.\nrewrite <- (atan_left_inv (-PI/2 + eps')); cycle 1.\n  now split; psatzl R.\nnow apply atan_increasing.\nQed.\n\nLemma integral_atan_comp_scal m : 0 < m ->\n   is_RInt_gen (fun x => /m * /((x / m) ^ 2 + 1)) \n       (Rbar_locally m_infty) (Rbar_locally p_infty) PI.\nProof.\n(* assert (tmp := PI2_RGT_0). *)\nintros m0.\nassert (is_derive_atan_scal : forall x,  \n           is_derive (fun x => atan (x / m)) x (/ m * /((x/m)^2 + 1))).\n  intros x; auto_derive; auto; field.\n  split; apply Rgt_not_eq; auto; apply Rplus_le_lt_0_compat.\n    now apply pow2_ge_0.\n  now apply pow2_gt_0, Rgt_not_eq.\nintros P [eps Peps].\n(* assert (ep2 : 0 < Rmin eps (PI/2)).\n  apply Rmin_glb_lt;[apply cond_pos | psatzl R].\nassert (eps' := mkposreal _ ep2).\n*)\nassert (atle : at_left (PI/2) (ball (PI/2) (pos_div_2 eps))).\n  now exists (pos_div_2 eps); intros; tauto.\nassert (atri : at_right (-PI/2) (ball (-PI/2) (pos_div_2 eps))).\n  now exists (pos_div_2 eps); intros; tauto.\nassert (H0 := lim_atan_p_infty _ atle).\nassert (H0' := lim_atan_m_infty _ atri).\nassert (abs' : 0 < / m) by now apply Rinv_0_lt_compat.\nassert (H1 : filterlim (fun x => x / m) (Rbar_locally p_infty)\n                (Rbar_locally p_infty)).\n  replace (Rbar_locally p_infty) with (Rbar_locally (Rbar_mult p_infty (/ m))) at 2.\n    now apply filterlim_Rbar_mult_r.\n  apply f_equal; simpl; case (Rle_dec 0 (/ m)).\n    intros r; case (Rle_lt_or_eq_dec 0 (/ m) r); auto.\n    now intros abs; rewrite <- abs in abs'; case (Rlt_irrefl 0).\n  now intros abs; case abs; apply Rlt_le.\nassert (H2 : filterlim (fun x => x / m) (Rbar_locally m_infty)\n                (Rbar_locally m_infty)).\n  replace (Rbar_locally m_infty) with (Rbar_locally (Rbar_mult m_infty (/ m))) at 2.\n    now apply filterlim_Rbar_mult_r.\n  apply f_equal; simpl; case (Rle_dec 0 (/ m)).\n    intros r; case (Rle_lt_or_eq_dec 0 (/ m) r); auto.\n    now intros abs; rewrite <- abs in abs'; case (Rlt_irrefl 0).\n  now intros abs; case abs; apply Rlt_le.\nassert (t := filterlim_comp R R R (fun x => x / m) atan (Rbar_locally p_infty)\n              (Rbar_locally p_infty) (at_left (PI/2)) H1 lim_atan_p_infty).\nassert (t' := filterlim_comp R R R (fun x => x / m) atan (Rbar_locally m_infty)\n              (Rbar_locally m_infty) (at_right (-PI/2)) H2 lim_atan_m_infty ).\nspecialize (t _ atle).\nspecialize (t' _ atri).\nunfold filtermapi, filtermap in t, t' |- *.\napply (Filter_prod _ _ _ _ _ t' t).\nintros x y; exists (atan (y/m) - atan (x/m)); split.\n  apply (is_RInt_derive (fun x => atan (x / m))).\n    intros z _; exact (is_derive_atan_scal z).\n  intros z _; apply (ex_derive_continuous (fun x1 => /m * / ((x1 / m) ^ 2 + 1))).\n  auto_derive; change ((z / m) ^ 2 + 1 <> 0).\n  now apply Rgt_not_eq, Rplus_le_lt_0_compat;\n           [apply pow2_ge_0 | apply Rlt_0_1].\napply Peps.\nchange (Rabs ((atan (y / m) - atan (x / m)) - PI) < eps).\nreplace ((atan (y / m) - atan (x / m)) - PI) with\n    ((atan (y / m) - PI / 2) - (atan (x / m) + PI / 2)) by field.\napply Rle_lt_trans with (1 := Rabs_triang _ _).\nreplace (pos eps) with (pos_div_2 eps + pos_div_2 eps) by (simpl; field).\napply Rplus_lt_compat.\n  exact H3.\nrewrite <- Rabs_Ropp, !Ropp_plus_distr, Ropp_involutive, <- Ropp_div.\nexact H.\nQed.\n\nLemma atan_derivative_improper_integral :\n  is_RInt_gen (fun x => /(x ^ 2 + 1))\n     (Rbar_locally m_infty) (Rbar_locally p_infty) PI.\nProof.\napply is_RInt_gen_ext with (fun x =>  /1 * /((x/1)^2 + 1)).\n  exists (Rgt 0) (Rlt 0); try (exists 0; intros; psatzl R).\n  intros x y _ _ z _; rewrite Rdiv_1, Rinv_1, Rmult_1_l; reflexivity.\napply integral_atan_comp_scal; psatzl R.\nQed.\n", "meta": {"author": "ybertot", "repo": "pi-agm", "sha": "2a44cb16a321ff224555aeea34106435e2afd872", "save_path": "github-repos/coq/ybertot-pi-agm", "path": "github-repos/coq/ybertot-pi-agm/pi-agm-2a44cb16a321ff224555aeea34106435e2afd872/atan_derivative_improper_integral.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6906431725096068}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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) : natural := plus (Succ y) Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj238_coqofml_034LvC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6906374382077045}}
{"text": "Require Export Recdef.\n\nFrom FormalSystems Require Export Base.\n\nInductive AExp : Type :=\n    | AConst : nat -> AExp\n    | Var : Loc -> AExp\n    | ABinOp : (nat -> nat -> nat) -> AExp -> AExp -> AExp.\n\nInductive BExp : Type :=\n    | BConst : bool -> BExp\n    | BRelOp : (nat -> nat -> bool) -> AExp -> AExp -> BExp\n    | Not : BExp -> BExp\n    | BBinOp : (bool -> bool -> bool) -> BExp -> BExp -> BExp.\n\nInductive Com : Type :=\n    | Skip : Com\n    | Asgn : Loc -> AExp -> Com\n    | Seq : Com -> Com -> Com\n    | If : BExp -> Com -> Com -> Com\n    | While : BExp -> Com -> Com.\n\nDefinition State : Type := Loc -> nat.\n\nDefinition initialState : State := fun _ => 0.\n\nDefinition changeState (s : State) (x : Loc) (n : nat) : State :=\n  fun y : Loc => if x =? y then n else s y.\n\nFixpoint loca (a : AExp) : list Loc :=\nmatch a with\n    | AConst _ => []\n    | Var x => [x]\n    | ABinOp f a1 a2 => loca a1 ++ loca a2\nend.\n\nDefinition acompatible (a : AExp) (s1 s2 : State) : Prop :=\n  forall x : Loc, In x (loca a) -> s1 x = s2 x.\n\nFixpoint locb (b : BExp) : list Loc :=\nmatch b with\n    | BConst _ => []\n    | BRelOp _ a1 a2 => loca a1 ++ loca a2\n    | Not b' => locb b'\n    | BBinOp _ b1 b2 => locb b1 ++ locb b2\nend.\n\nDefinition bcompatible (b : BExp) (s1 s2 : State) : Prop :=\n  forall x : Loc, In x (locb b) -> s1 x = s2 x.\n\n(* The list of all variables which are assigned to by the instruction c. *)\nFixpoint locw (c : Com) : list Loc :=\nmatch c with\n    | Skip => []\n    | Asgn v _ => [v]\n    | Seq c1 c2 => locw c1 ++ locw c2\n    | If _ c1 c2 => locw c1 ++ locw c2\n    | While _ c => locw c\nend.\n\nDefinition wcompatible (c : Com) (s1 s2 : State) : Prop :=\n  forall x : Loc, In x (locw c) -> s1 x = s2 x.\n\n(* The list of all variables mentioned in c. *)\nFixpoint loc (c : Com) : list Loc :=\nmatch c with\n    | Skip => []\n    | Asgn v a => v :: loca a\n    | Seq c1 c2 => loc c1 ++ loc c2\n    | If b c1 c2 => locb b ++ loc c1 ++ loc c2\n    | While b c => locb b ++ loc c\nend.\n\nDefinition ccompatible (c : Com) (s1 s2 : State) : Prop :=\n  forall x : Loc, In x (loc c) -> s1 x = s2 x.", "meta": {"author": "wkolowski", "repo": "FormalSystems", "sha": "f8bc7338315b0b19010952b111924e52bede7920", "save_path": "github-repos/coq/wkolowski-FormalSystems", "path": "github-repos/coq/wkolowski-FormalSystems/FormalSystems-f8bc7338315b0b19010952b111924e52bede7920/Imps/Imp/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025423, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6906374360421982}}
{"text": "Require Import Classical.\nRequire Export Ensembles.\nRequire Import EnsemblesImplicit.\nRequire Export Relation_Definitions.\nRequire Import Relation_Definitions_Implicit.\nRequire Import EnsemblesSpec.\n\nUnset Standard Proposition Elimination Names.\n\nSection MinimalElements.\n\nVariable T:Type.\nVariable R:relation T.\n\n(* R is well-founded if and only if every nonempty subset of\n   T has a minimal element *)\n\nDefinition minimal_element_property : Prop :=\n  forall S:Ensemble T, Inhabited S -> exists x:T, In S x /\\\n    forall y:T, In S y -> ~ R y x.\n\nLemma WF_implies_MEP: well_founded R -> minimal_element_property.\nProof.\nunfold well_founded.\nunfold minimal_element_property.\nintros WF S Hinh.\ndestruct Hinh.\nrevert x H.\napply (@well_founded_ind T R WF\n (fun x:T =>\n  In S x -> exists y:T, In S y /\\ (forall z:T, In S z -> ~ R z y))).\nintros.\ncase (classic (forall y:T, In S y -> ~ R y x)).\nexists x.\nsplit.\nassumption.\nassumption.\n\nintro.\napply not_all_ex_not in H1.\ndestruct H1.\napply imply_to_and in H1.\ndestruct H1.\napply H with x0.\napply NNPP.\nassumption.\nassumption.\nQed.\n\nLemma MEP_implies_WF: minimal_element_property -> well_founded R.\nProof.\nunfold well_founded.\nunfold minimal_element_property.\nintro MEP.\napply NNPP.\nintuition.\napply not_all_ex_not in H.\ndestruct H.\nassert (Inhabited [x:T | ~ Acc R x]).\nexists x.\nconstructor; assumption.\napply MEP in H0.\ndestruct H0.\ndestruct H0.\ndestruct H0.\ncontradict H0.\nconstructor.\nintros.\napply NNPP.\nintuition.\napply H1 with y.\nconstructor; assumption.\nassumption.\nQed.\n\nEnd MinimalElements.\n\nSection DecreasingSequences.\n\n(* R is well-founded if and only if there is no infinite strictly\n   decreasing sequence of elements of T *)\n\nVariable T:Type.\nVariable R:relation T.\n\nDefinition decreasing_sequence_property :=\n  forall a:nat->T, exists n:nat, ~ R (a (S n)) (a n).\n\nLemma WF_implies_DSP: well_founded R -> decreasing_sequence_property.\nProof.\nunfold decreasing_sequence_property.\nintros WF a.\nremember (a 0) as a0.\nrevert a0 a Heqa0.\napply (well_founded_ind WF (fun x:T =>\n  forall a:nat->T, x = a 0 -> exists n:nat, ~ R (a (S n)) (a n))).\nintros.\ncase (classic (R (a 1) (a 0))).\nintro.\npose (b := fun n:nat => a (S n)).\nassert (exists n:nat, ~ R (b (S n)) (b n)).\napply H with (a 1).\nrewrite H0.\nassumption.\ntrivial.\ndestruct H2.\nexists (S x0).\nunfold b in H2.\nassumption.\n\nexists 0.\nassumption.\nQed.\n\nRequire Import ClassicalChoice.\n\nLemma DSP_implies_WF: decreasing_sequence_property -> well_founded R.\nProof.\nunfold decreasing_sequence_property.\nintro DSP.\napply MEP_implies_WF.\nunfold minimal_element_property.\nintro S0.\nintros.\napply NNPP.\nintuition.\nassert (forall x:T, In S0 x -> exists y:T, In S0 y /\\ R y x).\nintros.\napply NNPP.\nintuition.\nassert (forall y:T, ~(In S0 y /\\ R y x)).\napply not_ex_all_not.\nassumption.\napply H0.\nexists x.\nsplit.\nassumption.\nintros.\napply H3 with y.\ntauto.\n\npose (S_type := {x:T | In S0 x}).\nassert (exists f:S_type -> S_type, forall x:S_type,\n  R (proj1_sig (f x)) (proj1_sig x)).\napply choice with (R:=fun x y:S_type => R (proj1_sig y) (proj1_sig x)).\nintro.\ndestruct x.\nsimpl.\npose proof (H1 x i).\ndestruct H2.\ndestruct H2.\nexists (exist (fun x:T => In S0 x) x0 H2).\nsimpl.\nassumption.\n\ndestruct H2 as [f Hf].\n\ndestruct H.\npose (b := nat_rect (fun n:nat => S_type)\n  (exist (fun x:T => In S0 x) x H)\n  (fun (n:nat) (x:S_type) => f x)).\nsimpl in b.\npose (a := fun n:nat => (proj1_sig (b n))).\nassert (forall n:nat, R (a (S n)) (a n)).\nunfold a.\nintro.\nsimpl.\napply Hf.\n\ncontradict DSP.\napply ex_not_not_all.\nexists a.\napply all_not_not_ex.\nauto.\nQed.\n\nEnd DecreasingSequences.\n", "meta": {"author": "verimath", "repo": "topology", "sha": "9405aaf18d99c718769f1d2af8e030a902687837", "save_path": "github-repos/coq/verimath-topology", "path": "github-repos/coq/verimath-topology/topology-9405aaf18d99c718769f1d2af8e030a902687837/src/zorn/Classical_Wf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6906374223190779}}
{"text": "Require Export Relations.\n\nRequire Export List.\n\n(* Dictionaries : a dictionary is roughly a partial maping from\n   keys to values  *)\n\nModule Type DEC_ORDER.\n Parameter A : Set.\n Parameter le : A -> A -> Prop.\n Parameter lt : A -> A -> Prop.\n Axiom ordered : order A le.\n Axiom lt_le_weak : forall a b:A, lt a b -> le a b.\n Axiom lt_diff : forall a b:A, lt a b -> a <> b.\n Axiom le_lt_or_eq : forall a b:A, le a b -> lt a b \\/ a = b.\n Parameter lt_eq_lt_dec : forall a b:A, {lt a b} + {a = b} + {lt b a}.\nEnd DEC_ORDER.\n\n(* some derived theorems on dec_orders *)\n\nModule Type MORE_DEC_ORDERS.\n Parameter A : Set.\n Parameter le : A -> A -> Prop.\n Parameter lt : A -> A -> Prop.\n Axiom le_trans : transitive A le.\n Axiom le_refl : reflexive A le.\n Axiom le_antisym : antisymmetric A le.\n Axiom lt_irreflexive : forall a:A, ~ lt a a.\n Axiom lt_trans : transitive A lt.\n Axiom lt_not_le : forall a b:A, lt a b -> ~ le b a.\n Axiom le_not_lt : forall a b:A, le a b -> ~ lt b a.\n Axiom lt_intro : forall a b:A, le a b -> a <> b -> lt a b.\n Parameter le_lt_dec : forall a b:A, {le a b} + {lt b a}.\n Parameter le_lt_eq_dec : forall a b:A, le a b -> {lt a b} + {a = b}.\nEnd MORE_DEC_ORDERS.\n\n\n(* A functor for getting some useful derived properties on decidable\n   orders *)\n\nModule More_Dec_Orders (D: DEC_ORDER) : MORE_DEC_ORDERS with Definition\n  A := D.A with Definition le := D.le with Definition lt := D.lt.\n                                       \n Definition A := D.A.\n Definition le := D.le.\n Definition lt := D.lt.\n \n Theorem le_trans : transitive A le.\n Proof.\n   case D.ordered; auto.\n Qed.\n\n Theorem le_refl : reflexive A le.\n  Proof.\n   case D.ordered; auto.\n Qed.\n \n Theorem le_antisym : antisymmetric A le.\n Proof.\n   case D.ordered; auto.\n Qed.\n\n Theorem lt_intro : forall a b:A, le a b -> a <> b -> lt a b.\n Proof.\n   intros a b H diff; case (D.le_lt_or_eq a b H); tauto.\n Qed.\n \n Theorem lt_irreflexive : forall a:A, ~ lt a a.  \n Proof.\n  intros a H.\n  case (D.lt_diff _ _ H); trivial.\n Qed.\n\n Theorem lt_not_le : forall a b:A, lt a b -> ~ le b a.\n Proof.\n  intros a b H H0.\n  absurd (a = b).\n  apply D.lt_diff; trivial.\n  apply le_antisym; auto; apply D.lt_le_weak; assumption.\n Qed.\n\n Theorem le_not_lt : forall a b:A, le a b -> ~ lt b a.\n Proof.\n  intros a b H H0; apply (lt_not_le b a); auto.  \n Qed.\n\n Theorem lt_trans : transitive A lt.\n Proof.    \n  unfold A, transitive in |- *.\n  intros x y z H H0.\n  apply (lt_intro x z).\n  apply le_trans with y; apply D.lt_le_weak; assumption.\n  intro e; rewrite e in H.\n  absurd (y = z).\n  intro e'; rewrite e' in H. \n  apply (lt_irreflexive _ H). \n  apply le_antisym; apply D.lt_le_weak; trivial.\n Qed.\n\n Definition le_lt_dec : forall a b:A, {le a b} + {lt b a}.\n  intros a b; case (D.lt_eq_lt_dec a b).\n  intro d; case d; auto.  \n  left; apply D.lt_le_weak; trivial. \n  simple induction 1; left; apply le_refl.\n  right; trivial.\n Defined.\n\n Definition le_lt_eq_dec : forall a b:A, le a b -> {lt a b} + {a = b}.\n  intros a b H.\n  case (D.lt_eq_lt_dec a b).\n  trivial. \n  intro H0; case (le_not_lt a b H H0).\n Defined.\n\nEnd More_Dec_Orders.\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/modules/SRC/DecOrders.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.6906104266485683}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Coq_Cats.Type_Cat.Type_Cat.\n\nSection Arrow.\n  Local Open Scope morphism_scope.\n  \n  (** The type accomodating all arrows of a category C. *)\n  Record Arrow (C : Category) :=\n    {\n      Orig : Obj;\n      Targ : Obj;\n      Arr : Orig –≻ Targ\n    }.\n\n  Arguments Orig {_} _ : clear implicits.\n  Arguments Targ {_} _ : clear implicits.\n  Arguments Arr {_} _ : clear implicits.\n\n  Coercion Arr : Arrow >-> Hom.\n  \n  (** An arrow (in the appropriate category, e.g., comma) from arrow f : a -> b to arrow g : c -> d is a pair of arrows h1 : a -> c and h2 : b -> d that makes the following diagram commute:\n#\n<pre>\n          f\n   a ———————————> b\n   |              |\nh1 |              | h2\n   |              |\n   ↓              ↓\n   c ———————————> d\n          g\n</pre>\n#\n *)\n  Record Arrow_Hom {C : Category} (a b : Arrow C) :=\n    {\n      Arr_H : (Orig a) –≻ (Orig b);\n      Arr_H' : (Targ a) –≻ (Targ b);\n      Arr_Hom_com : Arr_H' ∘ (Arr a) = (Arr b) ∘ Arr_H\n    }.\n  Arguments Arr_H {_ _ _} _ : clear implicits.\n  Arguments Arr_H' {_ _ _} _ : clear implicits.\n  Arguments Arr_Hom_com {_ _ _} _ : clear implicits.\n\n  Context (C : Category).\n\n  Section Arrow_Hom_eq_simplify.\n    Context {a b : Arrow C} (f g : Arrow_Hom a b).\n    \n    (** Two arrow homomorphisms are equal if the arrows between theor domains and codomain are respectively equal. In other words, we don't cate about the proof of the diagram commuting. *)\n    Lemma Arrow_Hom_eq_simplify : Arr_H f = Arr_H g → Arr_H' f = Arr_H' g → f = g.\n    Proof.\n      destruct f; destruct g.\n      basic_simpl.\n      ElimEq.\n      doHomPIR.\n      reflexivity.\n    Qed.\n\n  End Arrow_Hom_eq_simplify.\n\n  Section Compose_id.\n    Context {x y z} (h : Arrow_Hom x y) (h' : Arrow_Hom y z).\n\n    (** Composition of arrow homomorphisms. We basicall need to show that in the following diagram, the bigger diagram commutes if the smaller ones do.\n#\n<pre>\n           f\n    a ———————————> b\n    |              |\n h1 |              | h2\n    |              |\n    ↓              ↓\n    c ———————————> d\n    |      g       |\nh1' |              | h2'\n    |              |\n    ↓              ↓\n    c ———————————> d\n           h\n</pre>\n#\n*)\n    Program Definition Arrow_Hom_compose : Arrow_Hom x z :=\n      {|\n        Arr_H := (Arr_H h') ∘ (Arr_H h);\n        Arr_H' := (Arr_H' h') ∘ (Arr_H' h)\n      |}.\n\n    Next Obligation. (* Arr_Hom_com *)\n    Proof.\n      destruct h as [hh hh' hc]; destruct h' as [h'h h'h' h'c]; cbn.\n      rewrite assoc.\n      rewrite hc.\n      repeat rewrite assoc_sym.\n      rewrite h'c.\n      auto.\n    Qed.\n\n    (** The identity arrow morphism. We simply need to show that the following diagram commutes:\n#\n<pre>\n          f\n   a ———————————> b\n   |              |\nid |              | id\n   |              |\n   ↓              ↓\n   a ———————————> b\n          f\n</pre>\n#\nwhich is trivial.\n *)\n    Program Definition Arrow_id : Arrow_Hom x x :=\n      {|\n        Arr_H := id;\n        Arr_H' := id\n      |}.\n\n  End Compose_id.\n\nEnd Arrow.\n\nHint Extern 1 (?A = ?B :> Arrow_Hom _ _) => apply Arrow_Hom_eq_simplify; simpl.\n\nArguments Orig {_} _ : clear implicits.\nArguments Targ {_} _ : clear implicits.\nArguments Arr {_} _ : clear implicits.\n\nArguments Arr_H {_ _ _} _ : clear implicits.\nArguments Arr_H' {_ _ _} _ : clear implicits.\nArguments Arr_Hom_com {_ _ _} _ : clear implicits.\n\n(** an arrow in a category is also an arrow in the opposite category. The domain and codomain are simply swapped. *)\nProgram Definition Arrow_to_Arrow_OP (C : Category) (ar : Arrow C) : Arrow (C ^op) :=\n  {|\n    Arr := ar\n  |}.\n\nLocal Hint Extern 1 => unfold Sect.\n\n(** The type of arrows of a category and the type of arrows of its opposite are isomorphic. *)\nProgram Definition Arrow_OP_Iso (C : Category) : (Arrow C) <~> (Arrow (C ^op)) :=\n  {|\n    equiv_fun := Arrow_to_Arrow_OP C;\n    equiv_isequiv :=\n      {|\n        equiv_inv := Arrow_to_Arrow_OP (C ^op)\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/Ext_Cons/Arrow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.6906104169470293}}
{"text": "\nFrom mathcomp Require Import ssreflect.\nFrom Category.Base Require Import Logic Category Functor NatTran.\n\nSet Universe Polymorphism.\n\nOpen Scope type_scope.\n\nProgram Definition ProductCat (C D : Category) : Category :=\n  {|\n    Obj := (Obj C) * (Obj D);\n    Hom := fun X Y => Hom (fst X) (fst Y) * Hom (snd X) (snd Y);\n    Hom_Id := fun X => pair (\\Id (fst X)) (\\Id (snd X));\n    Hom_comp :=\n      fun (X Y Z : (Obj C) * (Obj D)) =>\n        fun\n          (f1 : Hom (fst Y) (fst Z) * Hom (snd Y) (snd Z))\n          (f2 : Hom (fst X) (fst Y) * Hom (snd X) (snd Y))\n        => pair (fst f1 \\o fst f2) (snd f1 \\o snd f2)\n          \n  |}.\nNext Obligation.\nProof.  \n  rewrite /=.\n  by repeat rewrite Hom_assoc.\nQed.\nNext Obligation.\n  rewrite /=.\n  by repeat rewrite Hom_IdL.\nQed.\nNext Obligation.\n  rewrite /=.\n  by repeat rewrite Hom_IdR.\nQed.\n\n\nProgram Definition DiagonalFunctor (C : Category) : Functor C (ProductCat C C) :=\n  {|\n    FApp := fun (X : Obj C) => pair X X;\n    FAppH := fun (X Y : Obj C) (f : Hom X Y) => pair f f\n  |}.\n\n                                    \n", "meta": {"author": "k27c8ff627uxz", "repo": "category_theory", "sha": "d5568b2ba04120a4f0e5bc7f2d61297c3cf42b9e", "save_path": "github-repos/coq/k27c8ff627uxz-category_theory", "path": "github-repos/coq/k27c8ff627uxz-category_theory/category_theory-d5568b2ba04120a4f0e5bc7f2d61297c3cf42b9e/src/Instances/Product/ProductCategory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6905998699164616}}
{"text": "Require Import Relations.\n\nLemma wf_inclusion :\n forall (A:Set) (R S:A -> A -> Prop),\n   inclusion A R S -> well_founded S -> well_founded R.\nProof.\n intros A R S Hincl Hwf x.\n  induction  x as [x IHx] using (well_founded_ind Hwf).\n  constructor;  auto. \nQed.", "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/inclusionwf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6905998579811847}}
{"text": "(**************************************************************************\n\n Preservation of certain colimits by pullbacks\n\n The pullback functor always has a left biadjoint, which is given by\n composition. For that reason, pullbacks always preserve limits such as\n terminal objects, products, inserters, and equifiers. However, in general,\n the pullback functor does not have a right adjoint (this is even not the\n case in the bicategory of categories), and this pseudofunctor does not\n even preserve all colimits. If we have some additional assumptions, then\n we can show that certain colimits are preserved.\n If the bicategory has a strict biinitial (i.e., all maps into that object\n are equivalents), then the pullback pseudofunctor preserves biinitial\n objects.\n\n Contents\n 1. Pullbacks preserve strict biinitial objects\n\n **************************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.Bicategories.Core.Bicat.\nImport Bicat.Notations.\nRequire Import UniMath.Bicategories.Core.Invertible_2cells.\nRequire Import UniMath.Bicategories.Core.Univalence.\nRequire Import UniMath.Bicategories.Morphisms.Adjunctions.\nRequire Import UniMath.Bicategories.DisplayedBicats.DispBicat.\nRequire Import UniMath.Bicategories.DisplayedBicats.Examples.Slice.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.PseudoFunctorBicat.\nRequire Import UniMath.Bicategories.PseudoFunctors.PseudoFunctor.\nImport PseudoFunctor.Notations.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.PullbackFunctor.\nRequire Import UniMath.Bicategories.PseudoFunctors.Biadjunction.\nRequire Import UniMath.Bicategories.PseudoFunctors.Preservation.Preservation.\nRequire Import UniMath.Bicategories.Modifications.Modification.\nRequire Import UniMath.Bicategories.Colimits.Initial.\nRequire Import UniMath.Bicategories.Colimits.Extensive.\nRequire Import UniMath.Bicategories.Colimits.Examples.SliceBicategoryColimits.\nRequire Import UniMath.Bicategories.Limits.Pullbacks.\nRequire Import UniMath.Bicategories.Limits.PullbackFunctions.\n\nLocal Open Scope cat.\n\n(**\n 1. Pullbacks preserve strict biinitial objects\n *)\nDefinition pullback_preserves_biinitial\n           (B : bicat_with_pb)\n           (HI : strict_biinitial_obj B)\n           {b₁ b₂ : B}\n           (f : b₁ --> b₂)\n  : preserves_biinitial\n      (pb_psfunctor B f).\nProof.\n  pose (H := map_to_strict_biinitial_is_biinitial\n               (pr2 HI)\n               (pb_pr2 f (is_biinitial_1cell_property (pr12 HI) b₂))).\n  use (preserves_chosen_biinitial_to_preserve_biinitial\n         (_ ,, _)\n         (pb_psfunctor B f)).\n  - apply biinitial_in_slice.\n    exact (pr1 HI ,, pr12 HI).\n  - use (equiv_from_biinitial\n           (is_biinitial_slice\n              (pb_obj f (is_biinitial_1cell_property (pr12 HI) b₂)\n               ,,\n               H)\n              b₁)).\n    + use make_1cell_slice.\n      * apply id₁.\n      * cbn.\n        use is_biinitial_invertible_2cell_property.\n        exact H.\n    + use left_adjoint_equivalence_in_slice_bicat.\n      cbn.\n      apply internal_adjoint_equivalence_identity.\nDefined.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/Bicategories/PseudoFunctors/Preservation/PullbackPreservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6905998512100642}}
{"text": "(* Types and Functions *)\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\nLet 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\nDefinition prev_day d :=\n  match d with\n  | sun => sat\n  | mon => sun\n  | tue => mon\n  | wed => tue\n  | thu => wed\n  | fri => thu\n  | sat => fri\n  end.\n\n(* Theorems and proofs *)\n\nTheorem wed_after_tue : next_day tue = wed.\nProof.\n  auto.\nQed.\n\nPrint wed_after_tue.\n\n(* eq_refl -- from Coq stdlib. Says \"Equality is reflexive\" *)\n\nTheorem wed_after_tue' : next_day tue = wed.\nProof.\n  (* new tactics -- simpl, trivial *)\n  \n  simpl. trivial.\nQed.\n\nPrint wed_after_tue'.\n(* same proof as using [auto] *)\n\n\n(* The day of the week never repeats. *)\nTheorem day_never_repeats : forall d : day, next_day d <> d.\n\nProof. auto. (* stuck? *)\n\n  (* new tactics -- intros, destruct, discriminate *)\n\n  intros d. destruct d.\n  simpl. discriminate.\n  simpl. discriminate.\n  simpl. discriminate.\n  simpl. discriminate.\n  simpl. discriminate.\n  simpl. discriminate.\n  simpl. discriminate.\n\nQed.\n\n(* Same as previous; avoid tedium *)\nTheorem day_never_repeats' : forall d : day, next_day d <> d.\nProof.\n  intros d. destruct d.\n  all: discriminate.\n  (* discriminate does simplification as well! *)\nQed.\n\n\n(* Introduce a \"tactical\" ; which combines tactics *)\nTheorem day_never_repeats'' : forall d : day, next_day d <> d.\nProof.\n  intros d. destruct d; discriminate.\nQed.\n\nTheorem mon_preceds_tues : forall d : day,\n  next_day d = tue -> d = mon.\n\n(* What's the intuitive proof? \n   - Consider every day one by one\n   - precondition (LHS of implication) is false in 6 cases. Hence, holds.\n   - The other d is mon.\n*)\nProof.\n  (* naming introductions explicitly *)\n  intros d next_day_is_tue.\n  destruct d; discriminate || trivial.\n\n  (* || is a tactical. In t1 || t2, if t1 fails, then try t2. *)\nQed.\n\n(**********************************************************************)\n\n\n(* Lists *)\n\n(* Import full list library; by default some parts are included *)\nRequire Import List.\nImport ListNotations.\n\n\nModule MyList. (* We can have modules within files *)\n\nInductive list (A : Type) : Type :=\n| nil : list A\n| cons : A -> list A -> list A.\n\nEnd MyList.\n\n(* What is the Coq stdlib definition of \"list\" *)\nCheck list.\n(* [list] is a type constructor *)\n\nDefinition is_empty (A : Type) (lst : list A) :=\n  match lst with\n  | nil => true\n  | cons _ _ => false\n  end.\n(* Need explicit types for [is_empty]. Coq's type system _vastly_ more\n   expressive than OCaml's. Type inference is not possible always. *)\n\nDefinition is_empty_sugar (A : Type) (lst : list A) :=\n  match lst with\n  | [] => true\n  | _::_ => false\n  end.\n(* [], :: are syntactic sugar for list constructors nil and cons *)\n\nCompute is_empty nat [1].\n\nCompute is_empty nat [].\n\n(* Implicit arguments -- infer type from context; mostly works) *)\nDefinition is_empty' {A : Type} (lst : list A) :=\n  match lst with\n  | [] => true\n  | _::_ => false\n  end.\n\nCompute is_empty' [1].\n\nCheck is_empty'.\n\nCompute @is_empty' nat [1]. (* provide implcit argument explicitly! *)\n\n\nModule MyLength.\n\n(* Fixpoint in Coq = let rec in OCaml *)\nFixpoint length {A : Type} (lst : list A) :=\n  match lst with\n  | nil => 0\n  | _::t => 1 + length t\n  end.\n\nCompute length [1;2].\n\nEnd MyLength.\n\n(**********************************************************************)\n\n(* Options *)\n\nModule MyOption.\n\nInductive option (A:Type) : Type :=\n  | Some : A -> option A\n  | None : option A.\n\nEnd MyOption.\n\nDefinition hd_opt {A : Type} (lst : list A) : option A :=\n  match lst  with\n  | nil => None\n  | x :: _ => Some x\n  end.\n\nCompute hd_opt [1].\n\nCompute hd_opt [].\n\nCompute @hd_opt nat [].\n\n(* When [hd_opt] is applied to a list of length 0, it returns [None]. *)\nTheorem length0_implies_hdopt_is_none :\n  forall A : Type, forall lst : list A,\n    length lst = 0 -> hd_opt lst = None.\nProof.\n  intros A lst length_lst_is_0.\n  destruct lst.\n    simpl. trivial. (* trivial does simplification *)\n    simpl in length_lst_is_0. discriminate.\nQed.\n\nTheorem length0_implies_hdopt_is_none' :\nforall A : Type, forall lst : list A,\n  length lst = 0 -> hd_opt lst = None.\nProof.\n  intros A lst length_lst_is_0.\n  destruct lst.\n    - trivial.\n    - discriminate. (* skipped explicit simplification *)\nQed.\n\n(** The characters [+] and [*] can also be used as bullets, as can [--], [---],\netc.\n\n(**********************************************************************)\n\n** Summary\n\n- Coq is a proof assistant\n  + Includes a OCaml like FP langauge (Gallina)\n  + Type system more advanced than OCaml\n  + Tactic language (Ltac) for proving things about programs\n  + Simple proofs about lists and options\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/lectures/FunctionalProgramming_lecture.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199673867851, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.6905857682704295}}
{"text": "(** We use Coq's definitions for falsity, truth, \n    conjunctions, and disjunctions. *)\n\nModule Show_Definitions.\n  Inductive False := .\n  Inductive True := I.\n  (** We cheat with negation.  Will be explained later. *)\n  Notation \"~ P\" := (P -> False).\n  Inductive and (P Q: Prop) : Prop :=\n  | conj: P -> Q -> and P Q.\n  Inductive or (P Q: Prop) : Prop :=\n  | or_introl: P -> or P Q\n  | or_intror: Q -> or P Q.\nEnd Show_Definitions.\n\nPrint False.\nPrint True.\nPrint and.\nPrint or.\n\nDefinition elim_False\n  : forall Z: Type, False -> Z\n  := fun Z a => match a with end.\n\nLocate \"/\\\".\nCheck and.\nPrint and.\nPrint or.\nAbout or.  (* Overloaded implicit arguments *)\n\nDefinition match_and\n  : forall X Y Z: Prop, X /\\ Y -> (X -> Y -> Z) -> Z\n  := fun X Y Z a e => match a with conj x y => e x y end.\n\nDefinition match_or\n  : forall X Y Z: Prop, X \\/ Y -> (X -> Z) -> (Y -> Z) -> Z\n  := fun X Y Z a e1 e2 => match a with or_introl x => e1 x | or_intror y => e2 y end.\n\nSection Demo.\n  Variables X Y Z: Prop.\n\n  (** We type check normal proofs.  Note how \n      implicit arguments are supplied if necessary.\n      Also note how parentheses are ommitted in the types derived. **)      \n\n  Check fun x:X => x.\n  Check fun (x: X) (y: Y) => x.\n  Check fun (x: X) (y: Y) => y.\n  Check fun (f: X -> Y -> Z) y x => f x y.\n  Check fun h: X /\\ Y => match h with conj x y => x end.\n  Check fun h: X /\\ Y => match h with conj x y => y end.\n  Check fun h: X /\\ Y => match h with conj x y => conj y x end.\n  Check fun h: (X /\\ Y) /\\ Z => match h with\n                             conj (conj x y) z => conj x (conj y z)\n                           end.\n\n  (** Note implicit argument overloading of or_introl and or_intror *)\n  \n  Check fun h: X \\/ Y => match h with\n                       or_introl x => or_intror Y x\n                     | or_intror y => or_introl X y\n                     end.\n  Check fun h: (X \\/ Y) \\/ Z => match h with\n                             or_introl (or_introl x) => or_introl (Y \\/ Z) x\n                           | or_introl (or_intror y) => or_intror (or_introl y)\n                           | or_intror z => or_intror (or_intror z)\n                           end.\n  Check conj\n        (fun h: X /\\ Y => match h with conj x y => conj y x end)\n        (fun h: Y /\\ X => match h with conj y x => conj x y end).\n  \n  Check fun h: False => match h return X with end.  (* exfalso quodlibet *)\n\n  Check fun x (f: ~X) => f x.\n  Check fun x (f: ~X) => elim_False Y (f x).\n  Check fun x (f: ~X) => match f x return Y with end.\n  Check fun (f: X -> ~X) g => let x := g (fun x => f x x) in f x x.\n\n  (** Proof construction with tactics **)\n\n  Goal ~ ~X -> (X -> ~X) -> False.\n  Proof.\n    refine (fun f g => _).\n    refine (f _).\n    refine (fun x => _).\n    exact (g x x).\n    Show Proof.\n  Qed.\n\n  Goal ~ ~X -> (X -> ~X) -> False.\n  Proof.\n    intros f g.\n    apply f.\n    intros x.\n    exact (g x x).\n    Show Proof.\n  Qed.\n\n  Goal ~(X <-> ~X).\n  Proof.\n    refine (fun a => match a with conj f g => _ end).\n    refine (let x:X := _ in f x x).\n    refine (g (fun x => _)).\n    exact (f x x).\n    Show Proof.\n  Qed.\n  \n  Fact Russell :\n    ~(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 /\\ (Y \\/ Z) <-> (X /\\ Y) \\/ (X /\\ Z).\n  Proof.\n    refine (conj _ _).\n    - refine (fun a => match a with\n                    | conj x b => match b with\n                                 | or_introl y => _\n                                 | or_intror z => _\n                                 end\n                    end).\n      + exact (or_introl (conj x y)). \n      + exact (or_intror (conj x z)). \n    - refine (fun a => match a with\n                    | or_introl b => match b with conj x y => _ end\n                    | or_intror b => match b with conj x z => _ end\n                    end).\n      + exact (conj x (or_introl y)).\n      + exact (conj x (or_intror z)).\n    Show Proof.\n  Qed.\n  \n  Goal X /\\ (Y \\/ Z) <-> (X /\\ Y) \\/ (X /\\ Z).\n  Proof.\n    split.\n    - intros [x [y|z]].\n      + left. split.\n        * exact x.\n        * exact y.\n      + right. split.\n        * exact x.\n        * exact z.\n    - intros [[x y]|[x z]].\n      + split.\n        * exact x.\n        * left. exact y.\n      + split.\n        * exact x.\n        * right. exact z.\n    Show Proof.\n  Qed.\n  \n  Goal X /\\ (Y \\/ Z) <-> (X /\\ Y) \\/ (X /\\ Z).\n  Proof.\n    split.\n    - intros [x [y|z]].\n      + auto.\n      + auto.\n    - intros [[x y]|[x z]].\n      + auto.\n      + auto.\n    Show Proof.\n  Qed.\n  \n  Goal X /\\ (Y \\/ Z) <-> (X /\\ Y) \\/ (X /\\ Z).\n  Proof.\n    tauto.\n    Show Proof.  (* Uses match functions *)\n  Qed.\n\n  Goal ~ ~(X -> Y) <-> (~ ~X -> ~ ~Y).\n  Proof.\n    apply conj.\n    - intros f g h.\n      apply f. intros f'.\n      apply g. intros x.\n      exact (h (f' x)).\n    - intros f g.\n      apply g. intros x.\n      exfalso.\n      apply f.\n      + intros h. exact (h x).\n      + intros y. exact (g (fun _ => y)).\n   Show Proof.\n  Qed.\n\n  Goal X <-> Y -> Y <-> Z -> X <-> Z.\n  Proof.\n    refine (fun a => match a with conj f g => _ end).\n    refine (fun a' => match a' with conj f' g' => _ end).\n    refine (conj (fun x => _) (fun z => _)).\n    - exact (f' (f x)).\n    - exact (g (g' z)).\n    Show Proof.\n  Qed.\n\n  Goal X <-> Y -> Y <-> Z -> X <-> Z.\n  Proof.\n    intros [f g] [f' g'].\n    split.\n    - intros x. exact (f' (f x)).\n    - intros z. exact (g (g' z)).\n  Show Proof.\n  Qed.\n\nEnd Demo.\n\n(** Assumed variables are now taken as leading arguments *)\n\nCheck Russell.\n\nGoal forall X (p q: X -> Prop),\n    (forall x, p x <-> q x) -> (forall x, q x) -> forall x, p x.\nProof.\n  intros X p q f g x.\n  destruct (f x) as [_ h].\n  exact (h (g x)).\n  Show Proof.\nQed.\n\nGoal forall X (p q: X -> Prop),\n    (forall x, p x <-> q x) -> (forall x, q x) -> forall x, p x.\nProof.\n  intros X p q f g x.\n  refine (match f x with conj _ h => _ end).\n  exact (h (g x)).\n  Show Proof.\nQed.\n\n(** Impredicative characterizations *)\n\nGoal False <-> forall Z: Prop, Z.\nProof.\n  split.\n  - intros [].\n  - intros f. exact (f False).\n  Show Proof.\nQed.\n\nGoal forall X Y: Prop,\n    X /\\ Y <-> forall Z: Prop, (X -> Y -> Z) -> Z.\nProof.\n  intros X Y.\n  split.\n  - intros [x y] Z f. exact (f x y).\n  - intros f.  exact (f (X /\\ Y) (@conj X Y)).\nQed.\n\nGoal forall X Y: Prop,\n    X \\/ Y <-> forall Z: Prop, (X -> Z) -> (Y -> Z) -> Z.\nProof.\n  intros X Y.\n  split.\n  - intros [x|y] Z f g.\n    + exact (f x).\n    + exact (g y).\n  - intros f.\n    exact (f (X \\/ Y) (@or_introl X Y) (@or_intror X Y)).\n  Show Proof.\nQed.\n", "meta": {"author": "uds-psl", "repo": "MPCTT", "sha": "8ab02bcad069d29105794e2a8fe03b07dcecb86e", "save_path": "github-repos/coq/uds-psl-MPCTT", "path": "github-repos/coq/uds-psl-MPCTT/MPCTT-8ab02bcad069d29105794e2a8fe03b07dcecb86e/coq/pat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.6904897841244471}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom Coq Require Import Bool.Bool.\nFrom Coq Require Import Init.Nat.\nFrom Coq Require Import Arith.Arith.\nFrom Coq Require Import omega.Omega.\nFrom Coq Require Import Lists.List.\nFrom Coq Require Import Strings.String.\nImport ListNotations.\n\nFrom LF Require Import Maps.\nFrom Coq Require Import Logic.FunctionalExtensionality.\n\nModule AExp.\n\n  Inductive aexp : Type :=\n  | ANum (n : nat)\n  | APlus (a1 a2 : aexp)\n  | AMinus (a1 a2 : aexp)\n  | AMult (a1 a2 : aexp).\n\n  Inductive bexp : Type :=\n  | BTrue\n  | BFalse\n  | BEq (a1 a2 : aexp)\n  | BLe (a1 a2 : aexp)\n  | BNot (b : bexp)\n  | BAnd (b1 b2 : bexp).\n\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 => (aeval a1) =? (aeval a2)\n    | BLe a1 a2 => (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 => 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))))\n    = APlus (ANum 2) (ANum 1).\n  Proof. reflexivity. Qed.\n\n  Example test_optimize_0plus1 :\n    optimize_0plus (APlus (ANum 2) (ANum 0)) = APlus (ANum 2) (ANum 0).\n  Proof. reflexivity. Qed.\n  \n  Theorem optimize_0plus_sound : forall a,\n      aeval (optimize_0plus a) = aeval a.\n  Proof.\n    apply aexp_ind.\n    - reflexivity.\n    - intros a1 H1 a2 H2. simpl.\n      destruct a1.\n      + destruct n as [| n'].\n        * simpl. rewrite H2. reflexivity.\n        * simpl. rewrite H2. reflexivity.\n      + rewrite <- H1. simpl. rewrite H2. reflexivity.\n      + rewrite <- H1. simpl. rewrite H2. reflexivity.\n      + rewrite <- H1. simpl. rewrite H2. reflexivity.\n    - intros a1 H1 a2 H2. simpl.\n      destruct a1.\n      + simpl. destruct n as [| n'].\n        * rewrite H2. simpl. reflexivity.\n        * simpl. rewrite H2. reflexivity.\n      + rewrite <- H1. simpl. rewrite H2. reflexivity.\n      + rewrite <- H1. simpl. rewrite H2. reflexivity.\n      + rewrite <- H1. simpl. rewrite H2. reflexivity.\n    - intros a1 H1 a2 H2. simpl.\n      destruct a1.\n      + simpl. destruct n as [| n'].\n        * rewrite H2. simpl. reflexivity.\n        * simpl. rewrite H2. reflexivity.\n      + rewrite <- H1. simpl. rewrite H2. reflexivity.\n      + rewrite <- H1. simpl. rewrite H2. reflexivity.\n      + rewrite <- H1. simpl. rewrite H2. reflexivity.\n  Qed.\n\n  Fixpoint optimize_0plus_b (b : bexp) : bexp :=\n    match b with\n    | BTrue | BFalse => b\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 b,\n      beval (optimize_0plus_b b) = beval b.\n  Proof.\n    apply bexp_ind.\n    - reflexivity.\n    - reflexivity.\n    - intros a1 a2. simpl. repeat (rewrite optimize_0plus_sound).\n      reflexivity.\n    - intros a1 a2. simpl. repeat (rewrite optimize_0plus_sound).\n      reflexivity.\n    - intros b H. simpl. rewrite H. reflexivity.\n    - intros b1 H1 b2 H2. simpl. rewrite H1, H2. reflexivity.\n  Qed.\n\n  Fixpoint optimize_plus0 (a:aexp) : aexp :=\n    match a with\n    | ANum n => ANum n\n    | APlus e1 (ANum 0) => optimize_plus0 e1\n    | APlus e1 e2 => APlus (optimize_plus0 e1) (optimize_plus0 e2)\n    | AMinus e1 e2 => AMinus (optimize_plus0 e1) (optimize_plus0 e2)\n    | AMult e1 e2 => AMult (optimize_plus0 e1) (optimize_plus0 e2)\n    end.\n\n  Example test_optimize_plus0 :\n    optimize_plus0 (APlus (ANum 2) (ANum 0)) = ANum 2.\n  Proof. reflexivity. Qed.\n  \n  Theorem optimize_plus0_sound : forall a,\n      aeval (optimize_plus0 a) = aeval a.\n  Proof.\n    intro a. induction a.\n    - reflexivity.\n    - simpl. destruct a2 eqn:Ea2.\n      + destruct n as [| n'].\n        * simpl. rewrite IHa1. Search plus. rewrite <- plus_n_O.\n          reflexivity.\n        * simpl. rewrite IHa1. reflexivity.\n      + simpl in IHa2. simpl. rewrite IHa1, IHa2. reflexivity.\n      + simpl in IHa2. simpl. rewrite IHa1, IHa2. reflexivity.\n      + simpl in IHa2. simpl. rewrite IHa1, IHa2. reflexivity.\n    - simpl. rewrite IHa1, IHa2. reflexivity.\n    - simpl. rewrite IHa1, IHa2. reflexivity.\n  Qed.\n\n  Fixpoint optimize_plus0_b (b : bexp) : bexp :=\n    match b with\n    | BTrue | BFalse => b\n    | BEq a1 a2 => BEq (optimize_plus0 a1) (optimize_plus0 a2)\n    | BLe a1 a2 => BLe (optimize_plus0 a1) (optimize_plus0 a2)\n    | BNot b1 => BNot (optimize_plus0_b b1)\n    | BAnd b1 b2 => BAnd (optimize_plus0_b b1) (optimize_plus0_b b2)\n    end.\n  \n  Theorem optimize_plus0_b_sound : forall b,\n      beval (optimize_plus0_b b) = beval b.\n  Proof.\n    apply bexp_ind.\n    - reflexivity.\n    - reflexivity.\n    - intros a1 a2. simpl. repeat (rewrite optimize_plus0_sound).\n      reflexivity.\n    - intros a1 a2. simpl. repeat (rewrite optimize_plus0_sound).\n      reflexivity.\n    - intros b H. simpl. rewrite H. reflexivity.\n    - intros b1 H1 b2 H2. simpl. rewrite H1, H2. reflexivity.\n  Qed.\n\n  Reserved Notation \"e '\\\\' n\" (at level 90, left associativity).\n\n  Inductive aevalR : aexp -> nat -> Prop :=\n  | E_ANum (n : nat) :\n      (ANum n) \\\\ n\n  | E_APlus (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  Inductive bevalR : bexp -> bool -> Prop :=\n  | E_BTrue : bevalR BTrue true\n  | E_BFalse : bevalR BFalse false\n  | E_BEq (a1 a2 : aexp) (n1 n2 : nat)\n          (H1 : a1 \\\\ n1) (H2 : a2 \\\\ n2) :\n      bevalR (BEq a1 a2) (n1 =? n2)\n  | E_BLe (a1 a2 : aexp) (n1 n2 : nat)\n          (H1 : a1 \\\\ n1) (H2 : a2 \\\\ n2) :\n      bevalR (BLe a1 a2) (n1 <=? n2)\n  | E_BNot (be : bexp) (b : bool)\n           (H : bevalR be b) :\n      bevalR (BNot be) (negb b)\n  | E_BAnd (be1 be2 : bexp) (b1 b2 : bool)\n           (H1 : bevalR be1 b1)\n           (H2 : bevalR be2 b2) :\n      bevalR (BAnd be1 be2) (andb b1 b2).\n\n  Theorem aeval_iff_aevalR : forall a n, (a \\\\ n) <-> aeval a = n.\n  Proof.\n    intros a n. split.\n    - intro H. induction H; try (simpl; subst); reflexivity.\n    - generalize dependent n.\n      induction a; simpl; intros n0 H; rewrite <- H; constructor;\n      try (apply IHa1); try apply IHa2; reflexivity.\n  Qed.\n\n  Theorem beval_iff_bevalR : forall b bv,\n      bevalR b bv <-> beval b = bv.\n  Proof.\n    intros b bv. split.\n    - intro H. induction H.\n      + reflexivity.\n      + reflexivity.\n      + simpl. rewrite aeval_iff_aevalR in H1.\n        rewrite aeval_iff_aevalR in H2. rewrite H1. rewrite H2.\n        reflexivity.\n      + simpl. rewrite aeval_iff_aevalR in H1.\n        rewrite aeval_iff_aevalR in H2. rewrite H1. rewrite H2.\n        reflexivity.\n      + simpl. rewrite IHbevalR. reflexivity.\n      + simpl. rewrite IHbevalR1. rewrite IHbevalR2. reflexivity.\n    - generalize dependent bv. induction b.\n      + simpl. intros bv H. rewrite <- H. constructor.\n      + simpl. intros bv H. rewrite <- H. constructor.\n      + simpl. intros bv H. rewrite <- H.\n        constructor; apply aeval_iff_aevalR; reflexivity.\n      + simpl. intros bv H. rewrite <- H.\n        constructor; apply aeval_iff_aevalR; reflexivity.\n      + simpl. intros bv H. rewrite <- H.\n        constructor. apply IHb. reflexivity.\n      + simpl. intros bv H. rewrite <- H.\n        constructor.\n        * apply IHb1. reflexivity.\n        * apply IHb2. reflexivity.\n  Qed.\n  \nEnd AExp.\n\nModule aevalR_division.\n\n  Inductive aexp : Type :=\n  | ANum (n : nat)\n  | APlus (a1 a2 : aexp)\n  | AMinus (a1 a2 : aexp)\n  | AMult (a1 a2 : aexp)\n  | ADiv (a1 a2 : aexp).\n\n  Reserved Notation \"e '\\\\' n\"\n           (at level 90, left associativity).\n  Inductive aevalR : aexp -> nat -> Prop :=\n  | E_ANum (n : nat) :\n      (ANum n) \\\\ n\n  | E_APlus (a1 a2 : aexp) (n1 n2 : nat) :\n      (a1 \\\\ n1) -> (a2 \\\\ n2) -> (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) :\n      (a1 \\\\ n1) -> (a2 \\\\ n2) -> (n2 > 0) ->\n      (mult n2 n3 = n1) -> (ADiv a1 a2) \\\\ n3\n                                        \n  where \"a '\\\\' n\" := (aevalR a n) : type_scope.\n  \nEnd aevalR_division.\n\nModule aevalR_extended.\n\n  Reserved Notation \"e '\\\\' n\" (at level 90, left associativity).\n\n  Inductive aexp : Type :=\n  | AAny (* <--- NEW *)\n  | ANum (n : nat)\n  | APlus (a1 a2 : aexp)\n  | AMinus (a1 a2 : aexp)\n  | AMult (a1 a2 : aexp).\n  \n  Inductive aevalR : aexp -> nat -> Prop :=\n  | E_Any (n : nat) :\n      AAny \\\\ n (* <--- NEW *)\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                                              \n  where \"a '\\\\' n\" := (aevalR a n) : type_scope.\n  \nEnd aevalR_extended.\n\nDefinition state := total_map nat.\n\nInductive aexp : Type :=\n| ANum (n : nat)\n| AId (x : string)\n| APlus (a1 a2 : aexp)\n| AMinus (a1 a2 : aexp)\n| AMult (a1 a2 : aexp).\n\nDefinition W : string := \"W\".\nDefinition X : string := \"X\".\nDefinition Y : string := \"Y\".\nDefinition Z : string := \"Z\".\n\nInductive bexp : Type :=\n| BTrue\n| BFalse\n| BEq (a1 a2 : aexp)\n| BLe (a1 a2 : aexp)\n| BNot (b : bexp)\n| BAnd (b1 b2 : bexp).\n\nCoercion AId : string >-> aexp.\nCoercion ANum : nat >-> aexp.\n\nDefinition bool_to_bexp (b : bool) : bexp :=\n  if b then BTrue else BFalse.\n\nCoercion bool_to_bexp : bool >-> bexp.\n\nDeclare Scope imp_scope.\nBind Scope imp_scope with aexp.\nBind Scope imp_scope with bexp.\nDelimit Scope imp_scope with imp.\n\nNotation \"x + y\" := (APlus x y) (at level 50, left associativity)\n                    : imp_scope.\nNotation \"x - y\" := (AMinus x y) (at level 50, left associativity)\n                    : imp_scope.\nNotation \"x * y\" := (AMult x y) (at level 40, left associativity)\n                    : imp_scope.\nNotation \"x <= y\" := (BLe x y) (at level 70, no associativity)\n                     : imp_scope.\nNotation \"x < y\" := (BLe (APlus x (ANum 1)) y) (at level 70, no associativity)\n                    : imp_scope.\nNotation \"x >= y\" := (BLe y x) (at level 70, no associativity)\n                     : imp_scope.\nNotation \"x > y\" := (BLe (APlus y (ANum 1)) x) (at level 70, no associativity)\n                    : imp_scope.\nNotation \"x = y\" := (BEq x y) (at level 70, no associativity)\n                    : imp_scope.\nNotation \"x && y\" := (BAnd x y) (at level 40, left associativity)\n                     : imp_scope.\nNotation \"'~' b\" := (BNot b) (at level 75, right associativity)\n                    : imp_scope.\n\nDefinition example_aexp := (3 + (X * 2))%imp.\nCheck example_aexp.\nDefinition example_bexp := (true && ~(X <= 4))%imp.\nCheck example_bexp.\n\nSet Printing Coercions.\n\nPrint example_bexp.\nPrint example_aexp.\n\nUnset Printing Coercions.\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\nFixpoint beval (st : state) (b : bexp) : bool :=\n  match b with\n  | BTrue => true\n  | BFalse => false\n  | BEq a1 a2 => (aeval st a1) =? (aeval st a2)\n  | BLe a1 a2 => (aeval st a1) <=? (aeval st a2)\n  | BNot b1 => negb (beval st b1)\n  | BAnd b1 b2 => andb (beval st b1) (beval st b2)\n  end.\n\nDefinition empty_st := (_ !-> 0).\n\nNotation \"a '!->' x\" := (t_update empty_st a x) (at level 100).\n\nExample aexp1 : aeval (X !-> 5) ( 3 + (X * 2))%imp = 13.\nProof. reflexivity. Qed.\n\nExample bexp1 : beval (X !-> 5) (true && ~(X <= 4))%imp = true.\nProof. reflexivity. Qed.\n\nInductive com : Type :=\n| CSkip\n| CAss (x : string) (a : aexp)\n| CSeq (c1 c2 : com)\n| CIf (b : bexp) (c1 c2 : com)\n| CWhile (b : bexp) (c : com).\n\nBind Scope imp_scope with com.\n\nNotation \"'SKIP'\" := CSkip : imp_scope.\nNotation \"x '::=' a\" := (CAss x a) (at level 60) : imp_scope.\nNotation \"c1 ;; c2\" := (CSeq c1 c2) (at level 80, right associativity)\n                      : imp_scope.\nNotation \"'WHILE' b 'DO' c 'END'\" :=\n  (CWhile b c) (at level 80, right associativity) : imp_scope.\nNotation \"'TEST' c1 'THEN' c2 'ELSE' c3 'FI'\" :=\n  (CIf c1 c2 c3) (at level 80, right associativity) : imp_scope.\n\nDefinition fact_in_coq : com :=\n  (\n    Z ::= X;;\n    Y ::= 1;;\n    WHILE ~(Z = 0) DO\n      Y ::= Y * Z;;\n      Z ::= Z - 1\n    END    \n  )%imp.\n\nPrint fact_in_coq.\nUnset Printing Notations.\nPrint fact_in_coq.\nSet Printing Notations.\n\nSet Printing Coercions.\nPrint fact_in_coq.\nUnset Printing Coercions.\nLocate aexp.\n\nDefinition plus2 : com :=\n  X ::= X + 2.\n\nDefinition XtimesYinZ : com :=\n  Z ::= X * Y.\n\nDefinition subtract_slowly_body : com :=\n  Z ::= Z - 1;;\n  X ::= X - 1.\n\nDefinition subtract_slowly : com :=\n  (WHILE ~(X = 0) DO\n    subtract_slowly_body\n   END)%imp.\n\nDefinition subtract_3_from_5_slowly : com :=\n  X ::= 3 ;;\n  Z ::= 5 ;;\n  subtract_slowly.\n\nDefinition loop : com :=\n  WHILE true DO\n    SKIP\n  END.\n\nReserved Notation \"st '=[' c ']=>' st'\" (at level 40).\n\nInductive ceval : com -> state -> state -> Prop :=\n| E_Skip : forall st, st =[ SKIP ]=> st\n| E_Ass : forall st a1 n x,\n    aeval st a1 = n ->\n    st =[ x ::= a1 ]=> (x !-> n ; st)\n| E_Seq : forall c1 c2 st st' st'',\n    st =[ c1 ]=> st' ->\n    st' =[ c2 ]=> st'' ->\n    st =[ c1 ;; c2]=> st''\n| E_IfTrue : forall st st' b c1 c2,\n    beval st b = true ->\n    st =[ c1 ]=> st' ->\n    st =[ TEST b THEN c1 ELSE c2 FI]=> st'\n| E_IfFalse : forall st st' b c1 c2,\n    beval st b = false ->\n    st =[ c2 ]=> st' ->\n    st =[ TEST b THEN c1 ELSE c2 FI]=> st'\n| E_WhileFalse : forall b st c,\n    beval st b = false ->\n    st =[ WHILE b DO c END ]=> st\n| E_WhileTrue : forall b st st' st'' c,\n    beval st b = true ->\n    st =[ c ]=> st' ->\n    st' =[ WHILE b DO c END ]=> st'' ->\n    st =[ WHILE b DO c END]=> st''\nwhere \"st =[ c ]=> st'\" := (ceval c st st').\n\nExample ceval_example1 :\n  empty_st =[\n    X ::= 2;;\n      TEST X <= 1\n        THEN Y ::= 3\n        ELSE Z ::= 4\n      FI\n  ]=> (Z !-> 4; X !-> 2).\nProof.\n  apply (E_Seq _ _ _ (X !-> 2)).\n  - apply E_Ass. reflexivity.\n  - apply E_IfFalse.\n    + reflexivity.\n    + apply E_Ass. reflexivity.\nQed.\n\nExample ceval_example2 :\n  empty_st =[\n    X ::= 0;; Y ::= 1;; Z ::= 2\n  ]=> (Z !-> 2; Y !-> 1; X !-> 0).\nProof.\n  apply (E_Seq _ _ _ (X !-> 0)).\n  - apply E_Ass. reflexivity.\n  - apply (E_Seq _ _ _ (Y !-> 1; X !-> 0)); apply E_Ass; reflexivity.\nQed.\n\nDefinition pup_to_n : com :=\n  Y ::= 0;;\n  WHILE X > 0 DO\n    Y ::= Y + X;;\n    X ::= X - 1\n  END.\n\nTheorem pup_to_2_ceval :\n  (X !-> 2) =[\n    pup_to_n\n  ]=> (X !-> 0; Y !-> 3; X !-> 1; Y !-> 2; Y !-> 0; X !-> 2).\nProof.\n  unfold pup_to_n.\n  apply (E_Seq _ _ _ (Y !-> 0; X !-> 2)).\n  - apply E_Ass; reflexivity.\n  - apply E_WhileTrue with (X !-> 1; Y !-> 2; Y !-> 0; X !-> 2).\n    + reflexivity.\n    + apply E_Seq with (Y !-> 2; Y !-> 0; X !-> 2).\n      * apply E_Ass; reflexivity.\n      * apply E_Ass; reflexivity.\n    + apply E_WhileTrue with (X !-> 0; Y !-> 3; X !-> 1; Y !-> 2; Y !-> 0; X !-> 2).\n      * reflexivity.\n      * apply E_Seq with (Y !-> 3; X !-> 1; Y !-> 2; Y !-> 0; X !-> 2).\n        { apply E_Ass; reflexivity. }\n        { apply E_Ass; reflexivity. }\n      * apply E_WhileFalse. reflexivity.\nQed.\n\nTheorem ceval_deterministic : forall c st st1 st2,\n    st =[ c ]=> st1 ->\n    st =[ c ]=> st2 ->\n    st1 = st2.\nProof.\n  intros c st st1 st2 H1.\n  generalize dependent st2.\n  induction H1.\n  - intros st2 H2. inversion H2. reflexivity.\n  - intros st2 H2. inversion H2. subst. reflexivity.\n  - intros st2 H2. inversion H2.\n    apply IHceval1 in H1. rewrite <- H1 in H5.\n    apply IHceval2 in H5. apply H5.\n  - intros st2 H2. inversion H2.\n    + apply IHceval. apply H8.\n    + rewrite H in H7. discriminate H7.\n  - intros st2 H2. inversion H2.\n    + rewrite H in H7. discriminate H7.\n    + apply IHceval. apply H8.\n  - intros st2 H2. inversion H2.\n    + reflexivity.\n    + rewrite H in H3. discriminate H3.\n  - intros st2 H2. inversion H2.\n    + subst. rewrite H in H5. discriminate H5.\n    + apply IHceval1 in H4. apply IHceval2.\n      subst. apply H7.\nQed.\n\nTheorem plus2_spec : forall st n st',\n    st X = n ->\n    st =[ plus2 ]=> st' ->\n    st' X = n + 2.\nProof.\n  intros st n st' H1 H2. inversion H2.\n  simpl in H5. rewrite H1 in H5. subst.\n  apply t_update_eq.\nQed.\n\nTheorem XtimesYinZ_spec : forall st m n st',\n    st X = m ->\n    st Y = n ->\n    st =[ XtimesYinZ ]=> st' ->\n    st' Z = m * n.\nProof.\n  intros st m n st' H1 H2 H3.\n  inversion H3. simpl in H6. rewrite H1 in H6. rewrite H2 in H6.\n  subst. apply t_update_eq.\nQed.\n\nTheorem loop_never_stops : forall st st',\n    ~(st =[ loop ]=> st').\nProof.\n  intros st st' constra. unfold loop in constra.\n  remember (WHILE true DO SKIP END)%imp as loopdef eqn:Heqloopdef.\n  induction constra.\n  - inversion Heqloopdef.\n  - inversion Heqloopdef.\n  - inversion Heqloopdef.\n  - inversion Heqloopdef.\n  - inversion Heqloopdef.\n  - inversion Heqloopdef. rewrite H1 in H. simpl in H. discriminate H.\n  - apply IHconstra2. apply Heqloopdef.\nQed.\n\nOpen Scope imp_scope.\n\nFixpoint no_whiles (c : com) : bool :=\n  match c with\n  | SKIP => true\n  | _ ::= _ => true\n  | c1 ;; c2 =>\n    andb (no_whiles c1) (no_whiles c2)\n  | TEST _ THEN ct ELSE cf FI =>\n    andb (no_whiles ct) (no_whiles cf)\n  | WHILE _ DO _ END => false\n  end.\n\nClose Scope imp_scope.\n\nInductive no_whilesR : com -> Prop :=\n| NW_Skip : no_whilesR SKIP\n| NW_Ass (x : string) (a : aexp) : no_whilesR (x ::= a)\n| NW_Seq (c1 c2 : com) (H1 : no_whilesR c1) (H2 : no_whilesR c2) :\n    no_whilesR (c1 ;; c2)\n| NW_SIf (b : bexp) (ct cf : com) (H1 : no_whilesR ct) (H2 : no_whilesR cf) :\n    no_whilesR (TEST b THEN ct ELSE cf FI).\n\nTheorem no_whiles_eqv :\n  forall c, no_whiles c = true <-> no_whilesR c.\nProof.\n  intro c. split.\n  - intro H. induction c.\n    + constructor.\n    + constructor.\n    + simpl in H. rewrite andb_true_iff in H. destruct H.\n      constructor.\n      * apply IHc1. assumption.\n      * apply IHc2. assumption.\n    + simpl in H. rewrite andb_true_iff in H. destruct H.\n      constructor.\n      * apply IHc1. assumption.\n      * apply IHc2. assumption.\n    + simpl in H. discriminate H.\n  - intro H. induction H.\n    + reflexivity.\n    + reflexivity.\n    + simpl. rewrite andb_true_iff. split; assumption.\n    + simpl. rewrite andb_true_iff. split; assumption.\nQed.\n\nTheorem no_whiles_terminating : forall c st,\n    no_whilesR c ->\n    exists st', st =[ c ]=> st'.\nProof.\n  intros c st H. generalize dependent st.\n  induction H.\n  - eexists. constructor.\n  - eexists. eapply E_Ass. eexists.\n  - intro st. destruct IHno_whilesR1 with st.\n    destruct IHno_whilesR2 with x.\n    exists x0. apply E_Seq with x; assumption.\n  - intro st. destruct IHno_whilesR1 with st.\n    destruct IHno_whilesR2 with st.\n    destruct (beval st b) eqn:Eb.\n    + exists x. apply E_IfTrue.\n      * apply Eb.\n      * apply H1.\n    + exists x0. apply E_IfFalse.\n      * apply Eb.\n      * apply H2.\nQed.\n\nInductive sinstr : Type :=\n| SPush (n : nat)\n| SLoad (x : string)\n| SPlus\n| SMinus\n| SMult.\n\nFixpoint s_execute (st : state) (stack : list nat) (prog : list sinstr)\n  : list nat :=\n  match prog with\n  | [] => stack\n  | hd :: tl =>\n    match hd with\n    | SPush n => s_execute st (n :: stack) tl\n    | SLoad x => s_execute st (st x :: stack) tl\n    | SPlus => match stack with\n               | m :: n :: stack' =>\n                 s_execute st ((n + m) :: stack') tl\n               | _ => []\n               end\n    | SMinus => match stack with\n               | m :: n :: stack' =>\n                 s_execute st ((n - m) :: stack') tl\n               | _ => []\n                end\n    | SMult => match stack with\n                | m :: n :: stack' =>\n                  s_execute st ((n * m) :: stack') tl\n                | _ => []\n               end\n    end\n  end.\n\nExample s_execute1 :\n  s_execute empty_st [] [SPush 5; SPush 3; SPush 1; SMinus] = [2; 5].\nProof. reflexivity. Qed.\n\nExample s_execute2 :\n  s_execute (X !-> 3) [3; 4] [SPush 4; SLoad X; SMult; SPlus]\n  = [15; 4].\nProof. reflexivity. Qed.\n\nFixpoint s_compile (e : aexp) : list sinstr :=\n  match e with\n  | ANum n => [SPush n]\n  | AId x => [SLoad x]\n  | APlus a1 a2 => (s_compile a1) ++ (s_compile a2) ++ [SPlus]\n  | AMinus a1 a2 => (s_compile a1) ++ (s_compile a2) ++ [SMinus]\n  | AMult a1 a2 => (s_compile a1) ++ (s_compile a2) ++ [SMult]\n  end.\n\nExample s_compile1 :\n  s_compile (X - (2 * Y))%imp\n  = [SLoad X; SPush 2; SLoad Y; SMult; SMinus].\nProof. reflexivity. Qed.\n\nTheorem s_compile_correct_help :\n  forall (st : state) (e : aexp) (stack : list nat) (l : list sinstr),\n    s_execute st stack ((s_compile e) ++ l) =\n    s_execute st ((aeval st e) :: stack) l.\nProof.\n  intros st e. induction e.\n  - reflexivity.\n  - simpl. destruct (st x); reflexivity.\n  - simpl. intros stack l.\n    assert (eq : (s_compile e1 ++ s_compile e2 ++ [SPlus]) ++ l\n                 = s_compile e1 ++ (s_compile e2 ++ [SPlus] ++ l)).\n    { repeat (rewrite app_assoc_reverse). reflexivity. }\n    rewrite eq.\n    rewrite (IHe1 stack (s_compile e2 ++ [SPlus] ++ l)).\n    rewrite (IHe2 (aeval st e1 :: stack) ([SPlus] ++ l)).\n    simpl. reflexivity.\n  - simpl. intros stack l.\n    assert (eq : (s_compile e1 ++ s_compile e2 ++ [SMinus]) ++ l\n                 = s_compile e1 ++ (s_compile e2 ++ [SMinus] ++ l)).\n    { repeat (rewrite app_assoc_reverse). reflexivity. }\n    rewrite eq.\n    rewrite (IHe1 stack (s_compile e2 ++ [SMinus] ++ l)).\n    rewrite (IHe2 (aeval st e1 :: stack) ([SMinus] ++ l)).\n    simpl. reflexivity.\n  - simpl. intros stack l.\n    assert (eq : (s_compile e1 ++ s_compile e2 ++ [SMult]) ++ l\n                 = s_compile e1 ++ (s_compile e2 ++ [SMult] ++ l)).\n    { repeat (rewrite app_assoc_reverse). reflexivity. }\n    rewrite eq.\n    rewrite (IHe1 stack (s_compile e2 ++ [SMult] ++ l)).\n    rewrite (IHe2 (aeval st e1 :: stack) ([SMult] ++ l)).\n    simpl. reflexivity.\nQed.\n\nTheorem s_compile_correct : forall (st : state) (e : aexp),\n    s_execute st [] (s_compile e) = [ aeval st e ].\nProof.\n  intros st e.\n  assert (eq : s_compile e = (s_compile e) ++ []).\n  { rewrite app_nil_r. reflexivity. }\n  rewrite eq.\n  apply (s_compile_correct_help st e [] []).\nQed.\n\nFixpoint beval_short (st : state) (b : bexp) : bool :=\n  match b with\n  | BTrue => true\n  | BFalse => false\n  | BEq a1 a2 => (aeval st a1) =? (aeval st a2)\n  | BLe a1 a2 => (aeval st a1) <=? (aeval st a2)\n  | BNot b1 => negb (beval_short st b1)\n  | BAnd b1 b2 => if beval_short st b1 then beval_short st b2 else false\n  end.\n\nTheorem beval_eq_beval_short : beval = beval_short.\nProof.\n  apply functional_extensionality.\n  intro st.\n  apply functional_extensionality.\n  intro b.\n  induction b.\n  - reflexivity.\n  - reflexivity.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. rewrite IHb. reflexivity.\n  - simpl. rewrite IHb1. rewrite IHb2.\n    destruct (beval_short st b1) eqn:E.\n    + simpl. reflexivity.\n    + simpl. reflexivity.\nQed.\n\nModule BreakImp.\n\n  Inductive com : Type :=\n  | CSkip\n  | CBreak\n  | CAss (x : string) (a : aexp)\n  | CSeq (c1 c2 : com)\n  | CIf (b : bexp) (c1 c2 : com)\n  | CWhile (b : bexp) (c : com).\n\n  Notation \"'SKIP'\" :=\n    CSkip.\n  Notation \"'BREAK'\" :=\n    CBreak.\n  Notation \"x '::=' a\" :=\n    (CAss x a) (at level 60).\n  Notation \"c1 ;; c2\" :=\n    (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 \"'TEST' c1 'THEN' c2 'ELSE' c3 'FI'\" :=\n    (CIf c1 c2 c3) (at level 80, right associativity).\n\n  Inductive result : Type :=\n  | SContinue\n  | SBreak.\n  \n  Reserved Notation \"st '=[' c ']=>' st' '/' s\"\n           (at level 40, st' at next level).\n\n  Inductive ceval : com -> state -> result -> state -> Prop :=\n  | E_Skip : forall st, st =[ SKIP ]=> st / SContinue\n  | E_Break : forall st, st =[ BREAK ]=> st / SBreak\n  | E_Ass : forall st x a n,\n      aeval st a = n ->\n      st =[ x ::= a ]=> (x !-> n; st) / SContinue\n  | E_Seq_Continue : forall st st' st'' r c1 c2,\n      st =[ c1 ]=> st' / SContinue ->\n      st' =[ c2 ]=> st'' / r ->\n      st =[ c1 ;; c2 ]=> st'' / r\n  | E_Seq_Break : forall st st' c1 c2,\n      st =[ c1 ]=> st' / SBreak ->\n      st =[ c1 ;; c2 ]=> st' / SBreak \n  | E_IfTrue : forall st st' b r c1 c2,\n      beval st b = true ->\n      st =[ c1 ]=> st' / r ->\n      st =[ TEST b THEN c1 ELSE c2 FI]=> st' / r\n  | E_IfFalse : forall st st' b r c1 c2,\n      beval st b = false ->\n      st =[ c2 ]=> st' / r ->\n      st =[ TEST b THEN c1 ELSE c2 FI]=> st' / r\n  | E_WhileFalse : forall b st c,\n      beval st b = false ->\n      st =[ WHILE b DO c END ]=> st / SContinue\n  | E_WhileTrue_Break : forall b st st' c,\n      beval st b = true ->\n      st =[ c ]=> st' / SBreak ->\n      st =[ WHILE b DO c END ]=> st' / SContinue\n  | E_WhileTrue_Continue : forall b st st' st'' r c,\n      beval st b = true ->\n      st =[ c ]=> st' / SContinue ->\n      st' =[ WHILE b DO c END ]=> st'' / r ->\n      st =[ WHILE b DO c END ]=> st'' / r\n                                                                  \n  where \"st '=[' c ']=>' st' '/' s\" := (ceval c st s st').\n  \n  Theorem break_ignore : forall c st st' s,\n      st =[ BREAK ;; c]=> st' / s ->\n      st = st'.\n  Proof.\n    intros c st st' s H. inversion H.\n    - inversion H2.\n    - inversion H5. reflexivity.\n  Qed.\n\n  Theorem while_continue : forall b c st st' s,\n      st =[ WHILE b DO c END ]=> st' / s ->\n      s = SContinue.\n  Proof.\n    intros b c st st' s. destruct s.\n    - intros. reflexivity.\n    - intro H. remember (WHILE b DO c END) as while eqn:Heqwhile.\n      induction H; try reflexivity; try (inversion Heqwhile).\n      apply IHceval2. apply Heqwhile.\n  Qed.\n\n  Theorem while_stops_on_break : forall b c st st',\n      beval st b = true ->\n      st =[ c ]=> st' / SBreak ->\n      st =[ WHILE b DO c END ]=> st' / SContinue.\n  Proof.\n    intros b c st st' H1 H2. constructor; assumption.\n  Qed.\n\n  Theorem while_break_true : forall b c st st',\n      st =[ WHILE b DO c END ]=> st' / SContinue ->\n      beval st' b = true ->\n      exists st'', st'' =[ c ]=> st' / SBreak.\n  Proof.\n    intros b c st st' H1 H2. remember (WHILE b DO c END) as while eqn:Heqwhile.\n    induction H1.\n    - inversion Heqwhile.\n    - inversion Heqwhile.\n    - inversion Heqwhile.\n    - inversion Heqwhile.\n    - inversion Heqwhile.\n    - inversion Heqwhile.\n    - inversion Heqwhile.\n    - inversion Heqwhile. subst. rewrite H in H2. discriminate H2.\n    - inversion Heqwhile. subst. exists st. apply H1.\n    - apply IHceval2.\n      + apply Heqwhile.\n      + apply H2.\n  Qed.\n\n  Theorem ceval_deterministic : forall (c : com) st st1 st2 s1 s2,\n      st =[ c ]=> st1 / s1 ->\n      st =[ c ]=> st2 / s2 ->\n      st1 = st2 /\\ s1 = s2.\n  Proof.\n    intros c st st1 st2 s1 s2 H1.\n    generalize dependent s2.\n    generalize dependent st2.\n    induction H1.\n    - intros st2 s2 H2. inversion H2. split; reflexivity.\n    - intros st2 s2 H2. inversion H2. split; reflexivity.\n    - intros st2 s2 H2. inversion H2. subst; split; reflexivity.\n    - intros st2 s2 H2. inversion H2.\n      + subst.\n        apply IHceval2. apply IHceval1 in H1.\n        destruct H1. subst. apply H6.\n      + subst. apply IHceval1 in H5. destruct H5. inversion H0.\n    - intros st2 s2 H2. inversion H2.\n      + subst. apply IHceval in H3. destruct H3. inversion H0.\n      + subst. apply IHceval. apply H6.\n    - intros st2 s2 H2. inversion H2.\n      + subst. apply IHceval. apply H9.\n      + rewrite H in H8. discriminate H8.\n    - intros st2 s2 H2. inversion H2.\n      + rewrite H in H8. discriminate H8.\n      + subst. apply (IHceval _ _ H9).\n    - intros st2 s2 H2. inversion H2.\n      + split; reflexivity.\n      + rewrite H in H3. discriminate H3.\n      + rewrite H in H3. discriminate H3.\n    - intros st2 s2 H2. inversion H2.\n      + subst. rewrite H in H7. discriminate H7.\n      + subst. apply IHceval in H8. destruct H8.\n        split.\n        * apply H0.\n        * reflexivity.\n      + subst. apply IHceval in H5. destruct H5. inversion H3.\n    - intros st2 s2 H2. inversion H2.\n      + subst. rewrite H in H6. discriminate H6.\n      + subst. apply IHceval1 in H7. destruct H7. inversion H1.\n      + subst. apply IHceval1 in H4. destruct H4. clear H1.\n        subst. apply IHceval2. apply H8.\n  Qed.\n\nEnd BreakImp.\n\nModule ForLoopImp.\n\n  Inductive com : Type :=\n  | CSkip\n  | CBreak\n  | CAss (x : string) (a : aexp)\n  | CSeq (c1 c2 : com)\n  | CIf (b : bexp) (c1 c2 : com)\n  | CWhile (b : bexp) (c : com)\n  | CFor (c1 c2 c3 : com) (b : bexp).\n\n  Notation \"'SKIP'\" :=\n    CSkip.\n  Notation \"'BREAK'\" :=\n    CBreak.\n  Notation \"x '::=' a\" :=\n    (CAss x a) (at level 60).\n  Notation \"c1 ;; c2\" :=\n    (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 \"'TEST' c1 'THEN' c2 'ELSE' c3 'FI'\" :=\n    (CIf c1 c2 c3) (at level 80, right associativity).\n  Notation \"'FOR' c1 ; b ; c2 'DO' c3 'END'\" :=\n    (CFor c1 c2 c3 b) (at level 80, right associativity).\n  \n  Inductive result : Type :=\n  | SContinue\n  | SBreak.\n  \n  Reserved Notation \"st '=[' c ']=>' st' '/' s\"\n           (at level 40, st' at next level).\n\n  Inductive ceval : com -> state -> result -> state -> Prop :=\n  | E_Skip : forall st, st =[ SKIP ]=> st / SContinue\n  | E_Break : forall st, st =[ BREAK ]=> st / SBreak\n  | E_Ass : forall st x a n,\n      aeval st a = n ->\n      st =[ x ::= a ]=> (x !-> n; st) / SContinue\n  | E_Seq_Continue : forall st st' st'' r c1 c2,\n      st =[ c1 ]=> st' / SContinue ->\n      st' =[ c2 ]=> st'' / r ->\n      st =[ c1 ;; c2 ]=> st'' / r\n  | E_Seq_Break : forall st st' c1 c2,\n      st =[ c1 ]=> st' / SBreak ->\n      st =[ c1 ;; c2 ]=> st' / SBreak \n  | E_IfTrue : forall st st' b r c1 c2,\n      beval st b = true ->\n      st =[ c1 ]=> st' / r ->\n      st =[ TEST b THEN c1 ELSE c2 FI]=> st' / r\n  | E_IfFalse : forall st st' b r c1 c2,\n      beval st b = false ->\n      st =[ c2 ]=> st' / r ->\n      st =[ TEST b THEN c1 ELSE c2 FI]=> st' / r\n  | E_WhileFalse : forall b st c,\n      beval st b = false ->\n      st =[ WHILE b DO c END ]=> st / SContinue\n  | E_WhileTrue_Break : forall b st st' c,\n      beval st b = true ->\n      st =[ c ]=> st' / SBreak ->\n      st =[ WHILE b DO c END ]=> st' / SContinue\n  | E_WhileTrue_Continue : forall b st st' st'' r c,\n      beval st b = true ->\n      st =[ c ]=> st' / SContinue ->\n      st' =[ WHILE b DO c END ]=> st'' / r ->\n      st =[ WHILE b DO c END ]=> st'' / r\n  | E_For : forall b st st' c1 c2 c3 r,\n      st =[ c1 ;; WHILE b DO c2;; c3 END ]=> st' / r ->\n      st =[ FOR c1 ; b ; c3 DO c2 END ]=> st' / r           \n                                                                  \n  where \"st '=[' c ']=>' st' '/' s\" := (ceval c st s st').\n\nEnd ForLoopImp.", "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/Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.8104789109591831, "lm_q1q2_score": 0.6904897760813562}}
{"text": "(**\n  This module defines concrete expressions that can be used to\n  represent monoid values and operations, and includes a collection\n  of functions that can be used to manipulate these expressions,\n  and a set of theorems describing these functions.\n\n  Copyright (C) 2018 Larry D. Lee Jr. <llee454@gmail.com>\n\n  This program is free software: you can redistribute it and/or modify\n  it under the terms of the GNU Lesser General Public License as\n  published by the Free Software Foundation, either version 3 of the\n  License, or (at your option) any later version.\n\n  This program is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with this program. If not, see\n  <https://www.gnu.org/licenses/>.\n*)\n\nRequire Import Description.\nRequire Import base.\nRequire Import function.\nRequire Import ProofIrrelevance.\nRequire Import Bool.\nRequire Import List.\nImport ListNotations.\nRequire Import monoid.\nImport Monoid.\n\nModule MonoidExpr.\n\nOpen Scope monoid_scope.\n\n(**\n  I. This section defines binary trees.\n*)\nSection binary_trees.\n\n(** Represents the values stored in binary trees. *)\nVariable Term : Set.\n\n(**\n  Represents binary trees.\n\n  Binary trees can be used to represent\n  many different types of algebraic\n  expressions. Importantly, when flattened,\n  they are isomorphic with lists. Flattening,\n  projecting onto lists, sorting, and folding\n  may be used normalize (\"simplify\") algebraic\n  expressions.\n*)\nInductive BTree : Set\n  := leaf : Term -> BTree\n  |  node : BTree -> BTree -> BTree.\n\n(**\n  Accepts a binary tree and returns true iff\n  the tree is a node term.\n*)\nDefinition BTree_is_node\n  :  BTree -> bool\n  := BTree_rec\n       (fun _ => bool)\n       (fun _ => false)\n       (fun _ _ _ _ => true).\n\n(**\n  Accepts a binary tree and returns true iff\n  the tree is a leaf term.\n*)\nDefinition BTree_is_leaf\n  :  BTree -> bool\n  := BTree_rec\n       (fun _ => bool)\n       (fun _ => true)\n       (fun _ _ _ _ => false).\n\n(**\n  Accepts a binary tree and returns true\n  iff the tree is right associative.\n\n  Note: right associative trees are isomorphic\n  to lists.\n*)\nDefinition BTree_is_rassoc\n  :  BTree -> bool\n  := BTree_rec\n       (fun _ => bool)\n       (fun _ => true)\n       (fun t _ _ f\n         => BTree_is_leaf t && f).\n\n(**\n  Proves that the right subtree in a right\n  associative binary tree is also right\n  associative.\n*)\nTheorem BTree_rassoc_thm\n  :  forall t u : BTree, BTree_is_rassoc (node t u) = true -> BTree_is_rassoc u = true.\nProof\n  fun t u H\n    => proj2 (\n            andb_prop \n              (BTree_is_leaf t)\n              (BTree_is_rassoc u)\n              H).\n\nEnd binary_trees.\n\nArguments leaf {Term} x.\n\nArguments node {Term} t u.\n\nArguments BTree_is_leaf {Term} t.\n\nArguments BTree_is_node {Term} t.\n\nArguments BTree_is_rassoc {Term} t.\n\nArguments BTree_rassoc_thm {Term} t u H.\n\n(**\n  II. Defines term maps which allow us to\n    interpret abstract terms as monoid values.\n*)\n\n(**\n  Represents a mapping from abstract terms\n  to monoid set elements.\n*)\nStructure Term_map : Type := term_map {\n  (**\n    Represents the monoid set that terms will be \n    projected onto. \n  *)\n  term_map_m: Monoid;\n\n  (**\n    Represents the set of terms that will be\n    used to represent monoid values.\n  *)\n  term_map_term : Set;\n\n  (**\n    Accepts a term and returns its projection\n    in E.\n  *)\n  term_map_eval : term_map_term -> E term_map_m;\n\n  (**\n    Accepts a term and returns true iff the term\n    represents the monoid identity element (0).\n  *)\n  term_map_is_zero : term_map_term -> bool;\n\n  (**\n    Accepts a term and proves that zero terms\n    evaluate to 0.\n  *)\n  term_map_is_zero_thm : forall t, term_map_is_zero t = true -> term_map_eval t = 0\n}.\n\nArguments term_map_eval {t} x.\n\nArguments term_map_is_zero {t} x.\n\nArguments term_map_is_zero_thm {t} t0 H.\n\n(**\n  III. Defines functions for evaluating and\n    transforming binary trees using term maps.\n*) \n\nSection term_tree_functs.\n\n(**\n  Represents an arbitrary homomorphism mapping\n  binary trees onto some set.\n*)\nVariable map : Term_map.\n\n(** Represents the set of monoid values. *)\nLet E := E (term_map_m map).\n\n(** Represents the set of terms. *)\nLet Term := term_map_term map.\n\n(**\n  Accepts a term and returns true iff it is not\n  a zero constant term.\n*)\nDefinition Term_is_nonzero\n  :  Term -> bool\n  := fun t => negb (term_map_is_zero t).\n\n(** Maps binary trees onto monoid expressions. *)\nDefinition BTree_eval\n  :  BTree Term -> E\n  := BTree_rec Term\n       (fun _ => E)\n       (fun t => term_map_eval t)\n       (fun _ f _ g => f + g).\n\n(**\n  Accepts two monoid expressions and returns\n  true iff they are denotationally equivalent -\n  I.E. represent the same monoid value.\n*)\nDefinition BTree_eq\n  :  BTree Term -> BTree Term -> Prop\n  := fun t u => BTree_eval t = BTree_eval u.\n\n(**\n  Accepts two binary trees, t and u, where u is\n  right associative, prepends t onto u in a way\n  that produces a flat list.\n\n  <<\n        *          *\n       / \\        / \\\n      *   v => (t)   *\n     / \\             / \\ \n    t   u          (u)  v\n  >>\n*)\nDefinition BTree_shift\n  :  forall (t u : BTree Term), BTree_is_rassoc u = true -> { v : BTree Term | BTree_is_rassoc v = true /\\ BTree_eq (node t u) v }\n  := let P t u v\n       := BTree_is_rassoc v = true /\\ BTree_eq (node t u) v in\n     let T t u\n       := BTree_is_rassoc u = true -> { v | P t u v } in\n     BTree_rec Term\n       (fun t => forall u, T t u)\n       (fun x u H\n         => let v := node (leaf x) u in\n            exist\n              (P (leaf x) u)\n              v\n              (conj\n                (andb_true_intro\n                  (conj\n                    (eq_refl true : BTree_is_leaf (leaf x) = true)\n                    H))\n                (eq_refl (BTree_eval v))))\n       (fun t f u g v H\n         => let (w, H0) := g v H in\n            let (x, H1) := f w (proj1 H0) in\n            exist\n              (P (node t u) v)\n              x\n              (conj\n                (proj1 H1)\n                (proj2 H1\n                  || BTree_eval t + a = BTree_eval x @a by proj2 H0\n                  || a = BTree_eval x @a by <- op_is_assoc (BTree_eval t) (BTree_eval u) (BTree_eval v)))).\n\n(**\n  Accepts a binary tree and returns an equivalent\n  tree that is right associative.\n*)\nDefinition BTree_rassoc\n  :  forall t : BTree Term, { u : BTree Term | BTree_is_rassoc u = true /\\ BTree_eq t u }\n  := let P t u\n       := BTree_is_rassoc u = true /\\ BTree_eq t u in\n     let T t\n       := { u | P t u } in\n     BTree_rec Term\n       (fun t => T t)\n       (fun x\n         => let t := leaf x in\n            exist\n              (P t)\n              t\n              (conj\n                (eq_refl true : BTree_is_leaf t = true) \n                (eq_refl (BTree_eval t))))\n       (fun t _ u g\n         => let (v, H) := g in\n            let (w, H0) := BTree_shift t v (proj1 H) in\n            exist\n              (P (node t u))\n              w\n              (conj\n                (proj1 H0)\n                (proj2 H0\n                  || BTree_eval t + a = BTree_eval w @a by (proj2 H)))).\n\n(**\n  IV. Defines functions for evaluating and\n    transforming lists of terms that can be mapped\n    onto monoid values using a term map.\n\n\n  In the following section, we use the\n  isomorphism between right associative binary\n  trees and lists to represent monoid expressions\n  as lists and to use list filtering to eleminate\n  identity elements. This is part of a larger\n  effort to \"simplify\" momoid expressions.\n*)\n\n(**\n  Accepts a list of monoid elements and computes\n  their sum.\n*)\nDefinition list_eval\n  :  forall xs : list Term, E\n  := list_rec\n       (fun _ => E)\n       0\n       (fun x _ f => (term_map_eval x) + f).\n\n(**\n  Accepts two term lists and asserts that they\n  are equivalent.\n*)\nDefinition list_eq : list Term -> list Term -> Prop\n  := fun xs ys : list Term\n       => list_eval xs = list_eval ys.\n\n(**\n  Accepts a right associative binary tree and\n  returns an equivalent list.\n*)\nDefinition RABTree_list\n  :  forall t : BTree Term, BTree_is_rassoc t = true -> { xs : list Term | BTree_eval t = list_eval xs }\n  := let P t xs := BTree_eval t = list_eval xs in\n     let T t := BTree_is_rassoc t = true -> { xs | P t xs } in\n     BTree_rect Term\n       (fun t => T t)\n       (fun x _\n         => let xs := [x] in\n            exist\n              (P (leaf x))\n              xs\n              (eq_sym (op_id_r (term_map_eval x))))\n       (BTree_rect Term\n         (fun t => T t -> forall u, T u -> T (node t u))\n         (fun x _ u (g : T u) H\n           => let H0\n                :  BTree_is_rassoc u = true\n                := BTree_rassoc_thm (leaf x) u H in\n              let (ys, H1) := g H0 in\n              let xs := x :: ys in\n              exist\n                (P (node (leaf x) u))\n                xs\n                (eq_refl ((term_map_eval x) + (BTree_eval u))\n                  || (term_map_eval x) + (BTree_eval u) = (term_map_eval x) + a @a by <- H1))\n         (fun t _ u _ _ v _ H\n           => False_rec\n                { xs | P (node (node t u) v) xs }\n                (diff_false_true H))).\n\n(**\n  Accepts a list of monoid elements and filters\n  out the 0 (identity) elements.\n\n  Note: to define this function we must have\n  a way to recognize identity elements. The\n  original definition for monoids did not declare\n  0 to be a distinguished element. In part this\n  followed from the fact that the set of monoid\n  elements was not declared inductively.\n\n  While we cannot assume that models of monoids\n  will define their element sets inductively\n  (for example, note that reals are not defined\n  inductively), we can reasonably expect these\n  models to define 0 as a distinguished element.\n\n  As this is somewhat conjectural however,\n  we do not add this as a requirement to the\n  monoid specification, but instead accept the\n  decision procedure here.\n*)\nDefinition list_filter_0\n  :  forall xs : list Term, {ys : list Term | list_eq xs ys /\\ Is_true (forallb Term_is_nonzero ys)}\n  := let P xs ys := list_eq xs ys /\\ Is_true (forallb Term_is_nonzero ys) in\n     let T xs := { ys | P xs ys } in\n     list_rec\n       T\n       (exist\n         (P [])\n         []\n         (conj\n           (eq_refl E_0)\n           I))\n       (fun x\n         => (sumbool_rec\n              (fun _ => forall xs : list Term, T xs -> T (cons x xs))\n              (fun (H : term_map_is_zero x = true) xs f\n                => let H0\n                     :  term_map_eval x = 0\n                     := term_map_is_zero_thm x H in\n                   let (ys, H1) := f in\n                   exist\n                     (P (x :: xs))\n                     ys\n                     (conj\n                       (op_id_l (list_eval xs)\n                         || 0 + (list_eval xs) = a @a by <- (proj1 H1)\n                         || a + (list_eval xs) = list_eval ys @a by H0)\n                       (proj2 H1)))\n              (fun (H : term_map_is_zero x = false) xs f\n                => let (ys, H0) := f in\n                   let zs := x :: ys in\n                   exist\n                     (P (x :: xs))\n                     zs\n                     (conj\n                       (eq_refl (list_eval (x :: xs))\n                         || term_map_eval x + (list_eval xs) = term_map_eval x + a @a by <- (proj1 H0))\n                       (Is_true_eq_left\n                         (forallb Term_is_nonzero zs)\n                         (andb_true_intro\n                           (conj\n                             (eq_refl (Term_is_nonzero x)\n                               || Term_is_nonzero x = negb a @a by <- H)\n                             (Is_true_eq_true\n                               (forallb Term_is_nonzero ys)\n                               (proj2 H0)))))))\n              (bool_dec0 (term_map_is_zero x)))).\n\n(**\n  Accepts a binary tree and returns an equivalent\n  terms list in which all identity elements have\n  been eliminated.\n*)\nDefinition reduce\n  :  forall t : BTree Term, { xs : list Term | BTree_eval t = list_eval xs }\n  := fun t\n       => let (u, H) := BTree_rassoc t in\n          let (xs, H0) := RABTree_list u (proj1 H) in\n          let (ys, H1) := list_filter_0 xs in\n          exist\n            (fun ys => BTree_eval t = list_eval ys)\n            ys\n            ((proj2 H)\n              || BTree_eval t = a @a by <- H0\n              || BTree_eval t = a @a by <- (proj1 H1)).\n\nEnd term_tree_functs.\n\n(**\n  V. Defines a abstract terms to represent monoid\n    expressions, and a term map for mapping these\n    terms onto monoid values.\n*)\nSection monoid_term_map.\n\n(** Represents an arbitrary monoid. *)\nVariable m : Monoid.\n\n(** Represents the set of monoid elements. *)\nLet E := E m.\n\n(**\n  Represents monoid values.\n\n  Note: In the development that follows, we\n  will use binary trees and lists to represent\n  monoid expressions. We will effectively flatten\n  a tree and filter a list to \"simplify\"\n  a given expression.\n\n  The code that flattens the tree representation\n  does not need to care whether or not the\n  leaves in the tree represent 0 (the monoid\n  identity element), inverses, etc. Accordingly,\n  distinguishing these elements in the definition\n  of BTree would unnecessarily complicate the\n  tree algorithms by adding more recursion cases.\n\n  Instead of doing this, we use two types\n  to represent monoid expressions - trees to\n  represent \"terms\" (expressions that are summed\n  together) and Term. Term tracks whether or\n  not a monoid value equals 0 (and later we will\n  use a similar structure to indicate whether or\n  not a given group element is an inverse). This\n  makes this information available when needed\n  (specifically when we eliminate 0s using\n  list filtering) without complicating the\n  tree algorithms.\n*)\nInductive Term : Set\n  := term_0 : Term\n  |  term_const : E -> Term.\n\n(**\n  Accepts a term and returns the monoid value\n  that it represents.\n*)\nDefinition Term_eval\n  :  Term -> E\n  := Term_rec\n       (fun _ => E)\n       0\n       (fun x => x).\n\n(**\n  Accepts a term and returns true iff the term\n  is zero.\n*)\nDefinition Term_is_zero\n  :  Term -> bool\n  := Term_rec\n       (fun _ => bool)\n       true\n       (fun _ => false).\n\n(** Proves that Term_is_zero is correct. *)\nTheorem Term_is_zero_thm\n  :  forall t, Term_is_zero t = true -> Term_eval t = 0.\nProof\n  Term_ind\n    (fun t => Term_is_zero t = true -> Term_eval t = 0)\n       (fun _ => eq_refl 0)\n       (fun x H\n         => False_ind\n              (Term_eval (term_const x) = 0)\n              (diff_false_true H)).\n\n(** Defines a map from Term to monoid elements. *)\nDefinition MTerm_map\n  :  Term_map\n  := term_map m Term Term_eval Term_is_zero Term_is_zero_thm.\n\nEnd monoid_term_map.\n\nArguments term_0 {m}.\n\nArguments term_const {m} x.\n\n(*\n  Accepts a monoid term and returns an equivalent\n  monoid expression.\n\n  Note: This Ltac expression is an example of\n  lightweight ltac. The idea behind this style\n  is to use Gallina functions to generate proofs\n  through reflection and then to use Ltac only\n  as syntactic sugar to generate abstract terms.\n*)\nLtac encode m x \n  := lazymatch x with\n       | (0)\n         => exact (MonoidExpr.leaf (MonoidExpr.term_0 (m:=m)))\n       | ({+} ?X ?Y)\n         => exact\n              (MonoidExpr.node\n                (ltac:(encode m X))\n                (ltac:(encode m Y)))\n       | (?X)\n         => exact (MonoidExpr.leaf (MonoidExpr.term_const X))\n     end.\n\nEnd MonoidExpr.\n\n(**\n  Defines a notation that can be used to prove\n  that two monoid expressions are equal using\n  proof by reflection.\n\n  We represent both expressions as binary trees\n  and reduce both trees to the same canonical\n  form demonstrating that their associated monoid\n  expressions are equivalent.\n*)\nNotation \"'reflect' x 'as' t ==> y 'as' u 'using' m\"\n  := (let r := MonoidExpr.reduce m t in\n      let s := MonoidExpr.reduce m u in\n      let v := proj1_sig r in\n      let w := proj1_sig s in\n      let H\n        :  MonoidExpr.list_eval m v = MonoidExpr.list_eval m w\n        := eq_refl (MonoidExpr.list_eval m v) : MonoidExpr.list_eval m v = MonoidExpr.list_eval m w in\n      let H0\n        :  MonoidExpr.BTree_eval m t = MonoidExpr.list_eval m v\n        := proj2_sig r in\n      let H1\n        :  MonoidExpr.BTree_eval m u = MonoidExpr.list_eval m w\n        := proj2_sig s in\n      let H2\n        :  MonoidExpr.BTree_eval m t = x\n        := eq_refl (MonoidExpr.BTree_eval m t) : MonoidExpr.BTree_eval m t = x in\n      let H3\n        :  MonoidExpr.BTree_eval m u = y\n        := eq_refl (MonoidExpr.BTree_eval m u) : MonoidExpr.BTree_eval m u = y in\n      H\n      || a = MonoidExpr.list_eval m w @a by H0\n      || a = MonoidExpr.list_eval m w @a by H2\n      || x = a @a by H1\n      || x = a @a by H3\n      : x = y)\n      (at level 40, left associativity).\n\n(**\n  Defines a notation that can be used to prove\n  that two monoid expressions, A and B, are\n  equal given the term map C.\n*)\nNotation \"'rewrite' A ==> B 'using' C\"\n  := (reflect A\n       as (ltac:(MonoidExpr.encode (MonoidExpr.term_map_m C) A))\n      ==> B\n       as (ltac:(MonoidExpr.encode (MonoidExpr.term_map_m C) B)) using C\n      : A = B)\n     (at level 40, left associativity).\n\nSection Unittests.\n\nVariable m : Monoid.\n\nVariables a b c d : E m.\n\nLet map := MonoidExpr.MTerm_map m.\n\nLet reflect_test_0\n  :  (a + 0) = (0 + a)\n  := rewrite (a + 0) ==> (0 + a) using map.\n\nLet reflect_test_1\n  :  (a + 0) + (0 + b) = a + b\n  := rewrite ((a + 0) + (0 + b)) ==> (a + b) using map.\n\nLet reflect_test_2\n  :  (0 + a) + b = (a + b)\n  := rewrite ((0 + a) + b) ==> (a + b) using map.\n\nLet reflect_test_3\n  :  (a + b) + (c + d) = a + ((b + c) + d)\n  := rewrite (a + b) + (c + d) ==> a + ((b + c) + d) using map.\n\nLet reflect_test_4\n  :  (a + b) + (0 + c) = (a + 0) + (b + c)\n  := rewrite (a + b) + (0 + c) ==> (a + 0) + (b + c) using map.\n\nLet reflect_test_5\n  :  (((a + b) + c) + 0) = (((0 + a) + b) + c)\n  := rewrite (((a + b) + c) + 0) ==> (((0 + a) + b) + c) using map.\n\nEnd Unittests.\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/monoid_expr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.8104789040926007, "lm_q1q2_score": 0.690489770231352}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf3 : natural) (z : natural) (lf2 : natural)\n  : natural := plus lf1 Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj133_coqofml_nSHQoa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6904868641062597}}
{"text": "Definition 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\nCheck true.\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).\nNotation \"~ x\" := (negb x) (at level 75, right associativity).\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  | true => ~ b2\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\nCheck negb.\n\nInductive rgb : Type :=\n| red\n| green\n| blue.\n\nInductive color : Type :=\n| black\n| white\n| primary (p : rgb).\n\nInductive megacolor : Type :=\n| non_visible\n| visible (v: color).\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 : megacolor) : bool :=\n  match c with\n  | visible (primary red) => true\n  | _ => false\n  end.\n\nCheck visible (primary red).\n\nCompute isred(visible (primary blue)).\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\nDefinition all_zero (nb : nybble) : bool :=\n  match nb with\n  | (bits B0 B0 B0 B0) => true\n  | (bits _ _ _ _) => false\n  end.\n\nCompute (all_zero (bits B1 B0 B1 B0)).\n\nCompute (all_zero (bits B0 B0 B0 B0)).\n\nModule NatPlayground.\n\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.\n\n  Compute (pred (S (S O))).\n\nEnd NatPlayground.\n\nCheck (S (S (S (S O)))).\n\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n  | O => O\n  | S O => O\n  | S (S n') => n'\n  end.\n\nCompute (minustwo 1).\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\nCheck evenb.\n\nDefinition oddb (n : nat) : bool := negb (evenb n).\n\n\nExample test_oddb1: oddb 1 = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_oddb2: oddb 4 = false.\nProof. simpl. reflexivity. Qed.\n\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\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.\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  | 0 => S 0\n  | S n' => mult n (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\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.\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 leb n m with\n  | false => false\n  | true => leb (S n) m\n  end.\n\n\n                             \nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\nExample test_ltb1: (ltb 2 2) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_ltb2: (ltb 2 3) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_ltb3: (ltb 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\nAxiom plus_O_n : forall n : nat, 0 + n = n.\n\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. simpl. 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 k:nat,\n  n = m ->\n  n + n = m + m.\n\nProof.\n  intros a b c H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_id_exercise : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o H1 H2.\n  rewrite -> H1.\n  rewrite <- H2.\n  reflexivity.\nQed.\n\nTheorem mult_0_plus : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite plus_O_n.\n  reflexivity. Qed.\n\n\n\nTheorem mult_S_1 : forall n m : nat,\n  m = S n ->\n  m * (1 + n) = m * m.\n\nProof.\n  intros n m H.\n  rewrite -> H.\n  rewrite <- plus_1_l.\n  reflexivity.\nQed.\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\nCompute 1 + 1 =? S (S O).\n\n\n\nTheorem plus_comm : forall a b: nat, a + b = b + a.\nProof.\n  induction a as [| a0 a1].\n  (* Case Z *)\n  - induction b as [| b0 b1].\n    + reflexivity.\n    (* Case S b *)\n    + simpl. rewrite <- b1. simpl. reflexivity.\n  (* Case a = S a *)\n  - induction b as [| b0 b1].\n    (* Case Z  *)\n    + simpl. rewrite (a1 0). reflexivity.\n    (* Case S b *)\n    + simpl. rewrite <- b1.\n      simpl. rewrite (a1 (S b0)).\n      simpl. rewrite (a1 b0).\n      reflexivity.\nQed.\n\nTheorem plus1: forall n, n + 1 = S n.\nProof. intros n. rewrite -> plus_comm. reflexivity. Qed.\n  \nTheorem plus_1_neq_0 : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n.\n  destruct n as [|n'] eqn:E.\n  - simpl plus.\n    reflexivity.\n  - simpl plus.\n    rewrite plus1.\n    reflexivity.\nQed.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b eqn:E.\n  - simpl (negb true). reflexivity.\n  - simpl. reflexivity.\nQed.\n\nTheorem andb_commutative : forall b c, andb b c = andb c b.\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 andb_commutative' : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b eqn:Eb.\n  { destruct c eqn:Ec.\n    { reflexivity. }\n    { reflexivity. } }\n  { destruct c eqn:Ec.\n    { reflexivity. }\n    { reflexivity. } }\nQed.\n\nTheorem andb3_exchange :\n  forall b c d, andb (andb b c) d = andb (andb b d) c.\nProof.\n  intros b c d. destruct b eqn:Eb.\n  - destruct c eqn:Ec.\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\n  - destruct c eqn:Ec.\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\nQed.\n\nTheorem plus_1_neq_0' :\n  forall n : nat,\n    (n + 1) =? 0 = false.\n\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity. Qed.\n\nTheorem andb_commutative'' :\n  forall b c, andb b c = andb c b.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_true_elim2 :\n  forall b c : bool, b && c = true -> c = true.\n\nProof.\n  intros b c H.\n  destruct b.\n  - destruct c.\n    + reflexivity. \n    + rewrite <- H. reflexivity.\n  - destruct c.\n    + reflexivity.\n    + rewrite <- H. reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1 :\n  forall n : nat, 0 =? (n + 1) = false.\n\nProof.\n  intros []; repeat 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.\n\nProof.\n  intros f H 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), f x = negb x) ->\n  forall (b : bool), f (f b) = b.\n\nProof.\n  intros f H b.\n  rewrite -> H.\n  rewrite -> H.\n  destruct b; repeat reflexivity.\nQed.\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\n\nProof.\n  \n  intros b c H.\n  destruct b, c; try reflexivity; try (simpl in H; rewrite H; reflexivity).\nQed.\n\nTheorem andb_eq_orb' :\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\n\nProof.\n  \n  intros b c.\n  destruct b.\n  \n  - simpl. intros H1. rewrite H1. reflexivity.\n  - simpl. intros H2. rewrite H2. reflexivity.\nQed.\n\nInductive bin : Type :=\n  | Z\n  | A (n : bin)\n  | B (n : bin).\n\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\nExample test_incr_1: incr(Z) = B Z.\nProof. simpl. reflexivity. Qed.\n\nExample test_incr_2: incr(B (B Z)) = A (A (B Z)).\nProof. simpl. reflexivity. Qed.\n\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\n\nExample test_bin_nat_1: bin_to_nat(A (B (B Z))) = 6.\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_nat_2: bin_to_nat(A (A (A (B Z)))) = 8.\nProof. simpl. reflexivity. Qed.\n\nCompute incr(A (B (B Z))).\n\nExample test_bin_inc_nat: bin_to_nat(incr(A (B (B Z)))) = 7.\nProof. simpl. reflexivity. Qed.\n\nTheorem plus_n_O_firsttry : forall n:nat,\n    n = n + 0.\n\nProof.\n  intros n.\n  simpl. (* Does nothing! *)\nAbort.\n\nTheorem plus_n_O_secondtry : forall n:nat,\n  n = n + 0.\nProof.\n  intros n. destruct n as [| n'] eqn:E.\n  - (* n = 0 *)\n    reflexivity. (* so far so good... *)\n  - (* n = S n' *)\n    simpl. (* ...but here we are stuck again *)\nAbort.\n\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\nTheorem minus_diag : forall n,\n  minus n n = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl. reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity. 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_comm2 : forall n m : nat,\n    n + m = m + n.\n\nProof.\n  intros n m.\n  induction n as [| n' Ihn'], m as [ | m'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- plus_n_O. reflexivity.\n  - simpl. rewrite <- plus_n_O. reflexivity.\n  - simpl.  rewrite -> Ihn'. simpl. rewrite plus_n_Sm. reflexivity.\n\nQed.\n\nTheorem plus_comm3 : forall n m : nat,\n    n + m = m + n.\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'. simpl. reflexivity.\nQed.\n\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p.\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, double n = n + n .\n\nProof.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- plus_n_Sm. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem evenb_S :\n  forall n : nat,\n    evenb (S n) = negb (evenb n).\n\nProof.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - rewrite -> IHn'. simpl. rewrite -> negb_involutive. 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). { reflexivity. }\n  rewrite -> H.\n  reflexivity.\nQed.\n\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  (* We just need to swap (n + m) for (m + n)... seems\n     like plus_comm should do the trick! *)\n  rewrite -> plus_comm.\n  (* Doesn't work...Coq rewrites the wrong plus! *)\nAbort.\n\nTheorem plus_rearrange : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (H: n + m = m + n).\n  { rewrite -> plus_comm. reflexivity. }\n  rewrite -> H. reflexivity.\nQed.\n\n\nModule Prods.\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.\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\nCompute (fst (pair 3 5)).\n\nNotation \"( x , y )\" := (pair x y).\n\nCompute (fst (3,5)).\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.\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity. Qed.\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAbort.\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\nTheorem snd_fst_is_swap :\n  forall (p : natprod),\n    (snd p, fst p) = swap_pair p.\n\nProof.\n  intros p. destruct p as [n m]. simpl. reflexivity.\nQed.\n\nTheorem fst_swap_is_snd :\n  forall (p : natprod),\n    fst (swap_pair p) = snd p.\n\nProof.\n  intros p. destruct p as [n m].\n  simpl.\n  reflexivity.\nQed.\n\nEnd Prods.\n\nModule NatList.\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 (snd (pair 3 5)).\n\nNotation \"( x , y )\" := (pair x y).\n\n\n\nCompute (fst (3, 5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.\nQed.\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  destruct p. simpl. reflexivity.\nQed.\n\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  destruct p.\n  simpl swap_pair. simpl fst. simpl snd.\n  reflexivity.\nQed.\n\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  destruct p.\n  simpl swap_pair.\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\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.\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  | 0 :: t => nonzeros t\n  | h :: t => h :: nonzeros t\n  end.\n\n\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n\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:\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\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\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\n  end.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. reflexivity. Qed.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof. reflexivity. Qed.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof. reflexivity. Qed.\n\nDefinition bag := natlist.\n\nFixpoint count (v: nat) (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | h :: t => match (eqb v h) with\n            | true => 1 + count(v) (t)\n            | false => count(v) (t)\n            end\n  end.\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. simpl. 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 (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 (count v s) with\n  | 0 => false\n  | _ => true\n  end.\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil\n  | h :: t => match (eqb h v) with\n            | true => t\n            | false => h :: (remove_one v t)\n            end\n  end.\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\n  end.\n\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\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\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, s2 with\n  | nil, _ => true\n  | _ , nil => false\n  | h :: t, _  => match (member h s2) with\n                | true => subset t (remove_one h s2)\n                | false => false\n                end\n  end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity. Qed.\n\n\n\nTheorem equality: forall (n: nat), eqb n n = true.\nProof. induction n. auto. auto. Qed.\n\nTheorem bag_theorem: forall (n : nat) (bb : bag), (eqb (count n (n :: bb)) O) = false.\n\nProof.\n\nsimpl.\ndestruct n as [|n0].\n- simpl. reflexivity.\n- simpl.\n  destruct bb.\n  + simpl. induction n0.\n    * simpl. reflexivity.\n    * rewrite equality. reflexivity.\n  + simpl eqb. rewrite equality. simpl. reflexivity.\nQed.\n\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  - (* l = nil *)\n    simpl length.\n    simpl.\n    reflexivity.\n  - (* l = cons n l' *)\n    simpl length.\n    simpl pred.\n    reflexivity.\nQed.\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n    (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\n\nProof.\n\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    simpl.\n    reflexivity.\n  - (* l1 = cons n l1' *)\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.\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\n\nTheorem rev_length_firsttry : 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\nintros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    simpl app.\n    simpl length.\n    simpl plus.\n    reflexivity.\n  - (* l1 = cons *)\n    simpl app.\n    simpl length.\n    rewrite -> IHl1'.\n    simpl plus.\n    reflexivity.\nQed.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length. simpl. rewrite -> plus_comm. simpl.\n    simpl. rewrite -> IHl'. reflexivity.\nQed.\n\n\n\nSearch rev.\n\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  induction l.\n  - simpl app. reflexivity.\n  - simpl app. rewrite -> IHl. reflexivity.\nQed.\n\nSearch app.\n\n\nTheorem rev_l : forall l: natlist, forall n: nat, rev (n :: l) = rev (l) ++ [n].\nProof. reflexivity. Qed.\n  \n\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  induction l1.\n  - simpl. destruct l2. reflexivity. simpl. rewrite  app_nil_r. reflexivity.  \n  - simpl. destruct l2 as [| n' l2'].\n    + simpl. rewrite app_nil_r. reflexivity.\n    + rewrite IHl1. simpl. rewrite app_assoc. reflexivity.\nQed.\n\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite rev_app_distr. rewrite IHl. simpl. reflexivity.\nQed.\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros l1 l2 l3 l4.\n  rewrite app_assoc.\n  rewrite app_assoc.\n  reflexivity.\nQed.\n\n\n\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  simpl.\n  induction l1.\n  - simpl. reflexivity.\n  - induction  n.\n    + simpl. induction l2.\n      * simpl. rewrite app_nil_r. rewrite app_nil_r. reflexivity.\n      * rewrite <- IHl1. reflexivity.\n    + simpl. induction l2.\n      * simpl. rewrite app_nil_r. rewrite app_nil_r. reflexivity.\n      * rewrite IHl1. reflexivity.\nQed.\n\n\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n  | nil, nil => true\n  | nil, _ => false\n  | _, nil => false\n  | h1 :: t1, h2 :: t2 => match (eqb h1 h2) with\n                       | true => (eqblist t1 t2)\n                       | false => false\n                       end\n  end.\n\nExample test_eqblist1 : (eqblist nil nil = true).\nProof. reflexivity. Qed.\n\nExample test_eqblist2 : eqblist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\nTheorem eqblist_refl : forall l:natlist,\n    true = eqblist l l.\n\nProof.\n  induction l.\n\n  - simpl. reflexivity.\n  - simpl. rewrite equality. rewrite IHl. reflexivity.\nQed.\n\nTheorem count_member_nonzero : forall (s : bag),\n  1 <=? (count 1 (1 :: s)) = true.\n\nProof.\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  - (* 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.\n\n  - simpl. reflexivity.\n  - simpl. destruct n.\n    + simpl. rewrite leb_n_Sn. reflexivity.\n    + simpl. rewrite IHs. reflexivity.\nQed.\n\n\nTheorem sum_zero : forall (s : bag), (sum s []) = s.\nProof.\n  induction s.\n  - reflexivity.\n  - simpl. rewrite IHs. reflexivity.\nQed.\n\n\nTheorem bag_count_sum : forall (s1 s2 : bag) (n: nat),\n    (count n s1) + (count n s2) = count n (sum s1 s2).\n\nProof.\n  induction s1 as [| n1 t1 IHs1].\n  - simpl. reflexivity.\n  - simpl. induction n.\n    + rewrite <- IHs1. destruct n1.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n    + rewrite <- IHs1. destruct n1.\n      * simpl. reflexivity.\n      * simpl. destruct (n =? n1). reflexivity. reflexivity. \nQed.\n\n\nTheorem injective_rev_rev : forall (l1 l2 : natlist), l1 = l2 -> rev l1 = rev l2.\nProof.\n  intros l1 l2 H1.\n  rewrite H1.\n  reflexivity.\nQed.\n\nTheorem injective_rev : forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2 H1.\n  apply injective_rev_rev in H1.\n  repeat rewrite rev_involutive in H1.\n  rewrite <- H1.\n  reflexivity.\nQed.\n\nInductive natoption : Type :=\n  | Some (n : nat)\n  | None.\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | 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 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. reflexivity. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  destruct l.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nEnd NatList.\n\n\nInductive id : Type :=\n  | Id (n : nat).\n\nDefinition eqb_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => n1 =? n2\n  end.\n\nTheorem eqb_id_refl : forall x, true = eqb_id x x.\nProof.\n  destruct x. simpl. rewrite NatList.equality. 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\n\n\nTheorem update_eq :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n  simpl. destruct x. 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 H1.\n  simpl.\n  rewrite H1.\n  reflexivity.\nQed.\n\nEnd PartialMap.\n\nInductive baz : Type :=\n  | Baz1 (x : baz)\n  | Baz2 (y : baz) (b : bool).\n\nSet Warnings \"-notation-overridden,-parsing\".\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.\n\nCheck boollist.\n\nCheck (nil nat).\n\nCheck (cons nat 3 (nil nat)).\n\nCheck nil.\n\nCheck cons.\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity. Qed.\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity. Qed.\n\nModule MumbleGrumble.\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\nCheck b a 5.\n\nCheck d bool (b a 5).\n\nCheck d mumble (b a 5).\nCheck d bool (b a 5).\nCheck e bool true.\nCheck e mumble (b c 0).\nCheck c.\n\n  \nEnd MumbleGrumble.\n\n\nFixpoint repeat' X x count :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\nCheck repeat'.\n\nCheck repeat.\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0 => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} _ _.\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 x count')\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 h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity. Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity. Qed.\n\nFail Definition mynil := nil.\n\nDefinition mynil : list nat := nil.\n\nCheck nil.\n\nCheck @nil.\n\nDefinition mynil' := @nil nat.\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\nDefinition list123''' := [1; 2; 3].\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. destruct m, n. all: rewrite IHl ; reflexivity. \nQed.\n\nLemma app_length : forall X (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  induction l1.\n  - simpl. reflexivity.\n  - simpl. destruct l2. all: 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  induction l1.\n  - simpl. destruct l2. all: rewrite app_nil_r; reflexivity.\n  - simpl. destruct l2. all: rewrite IHl1, app_assoc; reflexivity.\nQed.\n\n\nTheorem rev_app_distr_gen: forall X, forall l1 l2 : list X,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  induction l1.\n  - simpl. destruct l2. reflexivity. simpl. rewrite  app_nil_r. reflexivity.  \n  - simpl. destruct l2.\n    + simpl. rewrite app_nil_r. reflexivity.\n    + rewrite IHl1. simpl. rewrite app_assoc. reflexivity.\nQed.\n\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite rev_app_distr_gen. rewrite IHl. simpl. reflexivity.\nQed.\n\n\n\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\n\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.\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\nCheck @combine.\n\nCompute (combine [1;2] [false;false;true;true]).\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) :=\n  match l with\n  | [] => ([], [])\n  | (l, r) :: t => match (split t) with\n                 | (ll, rr) => (l :: ll, r :: rr)\n                 end\n  end.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. reflexivity. Qed.\n\nModule OptionPlayground.\n\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\n\nArguments Some {X} _.\n\nArguments None {X}.\n\nEnd OptionPlayground.\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if n =? O then Some a else nth_error l' (pred n)\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\n\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\n\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n  | [] => None\n  | h :: t => Some h\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\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.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | [] => []\n  | h :: t => if test h then h :: (filter test t)\n                        else filter test t\n  end.\n\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity. Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  (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).\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 => (length l) =? 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n => (evenb n) && (negb (n <=? 7))) l.\n    \nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity. Qed.\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\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\n\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n\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\nLemma destruct_map_list : forall X Y (f: X -> Y) (h: X) (t: list X),\n    map f (t ++ [h]) = map f t ++ [f h].\nProof.\n  simpl.\n  induction t.\n  - simpl. reflexivity.\n  - simpl. rewrite IHt. reflexivity.\nQed.\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  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHl. rewrite <- destruct_map_list. 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 :: t => (f h) ++ (flat_map f t)\n  end.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\nProof. reflexivity. Qed.\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : 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)\n                         : Y :=\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\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\nModule Exercises.\n\n  Definition fold_length {X : Type} (l : list X) : nat :=\n    fold (fun _ n => S n) l 0.\n\n  Example test_fold_length1 : fold_length [4;7;0] = 3.\n  Proof. reflexivity. Qed.\n\n  Theorem fold_length_correct : forall X (l : list X),\n      fold_length l = length l.\n  Proof.\n    induction l.\n    - simpl. unfold fold_length. simpl. reflexivity.\n    - simpl. rewrite <- IHl. unfold fold_length. simpl. reflexivity.\n  Qed.\n\n  Definition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y :=\n    fold (fun x l' => (f x) :: l') l [].\n\n  Theorem fold_map_correct: forall X Y (l: list X) (f: X -> Y),\n      fold_map f l = map f l.\n  Proof.\n    induction l.\n    - simpl. unfold fold_map. simpl. reflexivity.\n    - simpl. intros f. rewrite <- IHl. reflexivity.\n  Qed.\n\n  Definition prod_curry {X Y Z : Type}\n             (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n  Definition prod_uncurry {X Y Z : Type}\n             (f : X -> Y -> Z) (p : X * Y) : Z := f (fst p) (snd p).\n\n  Example test_map1': map (plus 3) [2;0;2] = [5;3;5].\n  Proof. reflexivity. Qed.\n\n  Check @prod_curry.\n  Check @prod_uncurry.\n\n  Theorem uncurry_curry : forall (X Y Z : Type)\n                            (f : X -> Y -> Z)\n                            x y,\n      prod_curry (prod_uncurry f) x y = f x y.\n  Proof.\n    intros X Y Z f x y.\n    unfold prod_curry.\n    unfold prod_uncurry.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Theorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n      prod_uncurry (prod_curry f) p = f p.\n  Proof.\n    intros X Y Z f p.\n    unfold prod_uncurry.\n    unfold prod_curry.\n    destruct p.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Theorem out_of_bound: forall X n l, length l = n -> @nth_error X l n = None.\n    intros X n l H.\n    destruct H.\n    induction l.\n    -  simpl. reflexivity.\n    - simpl. rewrite <- IHl. reflexivity.\n  Qed.\n\n  Module Church.\n    Definition cnat := forall X : Type, (X -> X) -> X -> X.\n\n    Definition one : cnat :=\n      fun (X : Type) (f : X -> X) (x : X) => f x.\n\n    Definition two : cnat :=\n      fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n    Definition zero : cnat :=\n      fun (X : Type) (f : X -> X) (x : X) => x.\n\n    Definition three : cnat := @doit3times.\n\n    Definition succ (n : cnat) : cnat :=\n      fun (X : Type) (f : X -> X) (x : X) => f (n X f x).\n\n    Example succ_1 : succ zero = one.\n    Proof. simpl. unfold succ. unfold one. unfold zero. reflexivity. Qed.\n\n    Example succ_2 : succ one = two.\n    Proof. simpl. unfold succ. unfold two. unfold one. reflexivity. Qed.\n\n    Example succ_3 : succ two = three.\n    Proof. simpl. unfold succ. unfold three. unfold two. reflexivity. Qed.\n\n\n\n    Definition plus (n m : cnat) : cnat :=\n      fun (X : Type) (f: X -> X) (x: X) => n X f (m X f x).\n\n    Example plus_1 : plus zero one = one.\n    Proof. reflexivity. Qed.\n\n    Example plus_2 : plus two three = plus three two.\n    Proof. reflexivity. Qed.\n\n    Example plus_3 :\n      plus (plus two two) three = plus one (plus three three).\n    Proof. reflexivity. Qed.\n\n    Definition mult (n m : cnat) : cnat :=\n      fun (X : Type) (f: X -> X) => n X (m X f).\n\n    Example mult_1 : mult one one = one.\n    Proof. reflexivity. Qed.\n\n    Example mult_2 : mult zero (plus three three) = zero.\n    Proof. reflexivity. Qed.\n\n    Example mult_3 : mult two three = plus three three.\n    Proof. reflexivity. Qed.\n\n    \n    Definition exp (n m : cnat) : cnat :=\n      fun (X : Type) (f: X -> X) => m (X -> X) ((n X)) f.\n    \n\n    Example exp_1 : exp two two = plus two two.\n    Proof. unfold exp. unfold plus. unfold mult. unfold two. unfold one. reflexivity. Qed.\n        \n    Example exp_2 : exp three zero = one.\n    Proof.  unfold exp. unfold mult. unfold zero. unfold one. reflexivity. Qed.\n\n    Example exp_3 : exp three two = plus (mult two (mult two two)) one.\n    Proof. reflexivity. Qed.\n\n  End Church.\nEnd Exercises.\n\n\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n  apply eq2.\nQed.\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.\nQed.\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m) ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.\nQed.\n\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     oddb 3 = true ->\n     evenb 4 = true.\nProof.\n  intros eq1 eq2.\n  apply eq2.\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  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.\n  rewrite H.\n  symmetry.\n  apply rev_involutive.\nQed.\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.\nQed.\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. 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]).\n  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  apply trans_eq with m. apply H0. apply H.\nQed.\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n 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\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.\n  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  y :: l = x :: j ->\n  x = y.\nProof.\n  intros.\n  injection H0 as H3 H4.\n  symmetry.\n  apply H3.\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  - (* n = 0 *)\n    intros H. reflexivity.\n  - simpl.\n    intros. discriminate H.\nQed.\n\nTheorem discriminate_ex1 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. discriminate contra. Qed.\n\nTheorem discriminate_ex2 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. discriminate contra. Qed.\n\nExample discriminate_ex3 :\n  forall (X : Type) (x y z : X) (l j : list X),\n    x :: y :: l = [] ->\n    x = z.\nProof.\n  intros.\n  simpl in H. discriminate H.\nQed.\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq. reflexivity. Qed.\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     (S n) =? (S m) = b ->\n     n =? m = b.\nProof.\n  intros n m b H. simpl in H. apply H.\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.\n  symmetry in H. apply eq in H. symmetry in H.\n  apply H.\nQed.\n\n\n\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  - intros m H. destruct m.  reflexivity. discriminate H.\n  - destruct m as [| m'].\n    + simpl. intros H. discriminate H.\n    + intros H.\n      apply f_equal.\n      apply IHn'.\n      repeat rewrite <- plus_n_Sm in H.\n      simpl in H.\n      repeat apply S_injective in H.\n      apply H.\nQed.\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     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 = S n' *) simpl. intros m eq. destruct m as [| m'] eqn:E.\n    + simpl. discriminate eq.\n    + apply f_equal.\n      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  intros n. induction n.\n  - intros m H. destruct m.\n    * reflexivity.\n    * discriminate H.\n  - intros m H. destruct m.\n    * discriminate H.\n    * apply f_equal. apply IHn. simpl in H. 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  - (* m = O *) simpl. intros eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) discriminate eq.\n  - (* m = S m' *) intros eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) discriminate eq.\n    + (* n = S n' *) apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n\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\nTheorem eqb_id_true : forall x y,\n  eqb_id x y = true -> x = y.\nProof.\n  intros [m] [n]. simpl. intros H.\n  assert (H' : m = n). { apply eqb_true. apply H. }\n  rewrite H'. reflexivity.\nQed.\n\nTheorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     nth_error l n = None.\nProof.\n  intros n X l.\n  generalize dependent n.\n  induction l.\n  - simpl. reflexivity.\n  - intros n H. rewrite <- H. simpl. apply IHl. reflexivity.\nQed.\n\n\nDefinition square n := n * n.\n\n\nTheorem mult_S: forall a b, S a * b = a * b + b.\n  simpl.\n  induction a.\n  - simpl. intros b. rewrite plus_comm. simpl. reflexivity.\n  - intros b. simpl. rewrite IHa. rewrite plus_comm. reflexivity.\nQed.\n\n\nTheorem plus_S_a_b: forall a b, S a + b = a + S b.\nProof.\n  simpl.\n  induction a.\n  - simpl. reflexivity.\n  - simpl. intros b. rewrite IHa. reflexivity.\nQed.\n\nTheorem mult_comm: forall a b, a * b = b * a.\nProof.\n  induction a.\n  - simpl. intros b. rewrite mult_0_r. reflexivity.\n  - simpl. intros b. rewrite IHa. induction b.\n    + simpl. reflexivity.\n    + rewrite mult_S. rewrite plus_comm. rewrite mult_S.\n      rewrite <- IHb. rewrite <- IHa. rewrite (plus_comm b).\n      rewrite (plus_comm _ (S b)).\n      rewrite (plus_comm _ b).\n      repeat rewrite plus_assoc.\n      rewrite (plus_comm _ (S a)).\n      rewrite (plus_comm _ a).\n      repeat rewrite plus_assoc.\n      rewrite plus_S_a_b.\n      reflexivity.\nQed.\n\nTheorem mult_distrib: forall a b c, a * (b + c) = a * b + a * c.\nProof.\n  induction a.\n  - simpl. reflexivity.\n  - intros b c. rewrite mult_S. rewrite mult_S. rewrite mult_S.\n    rewrite IHa.\n    repeat rewrite plus_assoc.\n    repeat rewrite (plus_comm _ b).\n    repeat rewrite plus_assoc.\n    reflexivity.\nQed.\n\nTheorem mult_1n : forall n, n = 1 * n.\nProof. simpl. intros n. rewrite <- plus_comm. simpl. reflexivity. Qed.\n\nTheorem mult_assoc: forall a b c, a * (b * c) = (a * b) * c.\nProof.\n  intros a b c.\n  induction a, b, c.\n  1, 2, 3, 4, 5, 6, 7: simpl.\n  5, 6: rewrite <- IHa. simpl.\n  1, 2, 3, 4, 5, 6: reflexivity.\n  - repeat rewrite mult_0_r. simpl. reflexivity.\n  - rewrite mult_S. rewrite IHa.\n    repeat rewrite (mult_comm _ (S c)).\n    rewrite <- mult_distrib.\n    rewrite <- mult_S.\n    reflexivity.\nQed.\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.\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\nFact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  destruct m eqn:E.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n\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\nDefinition sillyfun (n : nat) : bool :=\n  if n =? 3 then false\n  else if 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 (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.\nQed.\n\n\n\nLemma split_nil: forall (X: Type) (Y: Type), @split X Y [] = ([], []).\nProof. reflexivity. Qed.\n\nLemma xplit_nil_reason:  forall (X: Type) (Y: Type) (l: list (X * Y)) (xx: list Y),\n    @split X Y l = ([], xx) -> l = [].\nProof.\n  intros X Y l xx H.\n  induction l.\n  -  reflexivity.\n  - destruct x. simpl in H. rewrite IHl in H.\n    * simpl in H. discriminate.\n    * rewrite <- H. destruct (split l). discriminate H.\nQed.\n\n\nLemma xplit_nil_reason_2:  forall (X: Type) (Y: Type) (l: list (X * Y)) (xx: list X),\n    @split X Y l = (xx, []) -> l = [].\nProof.\n  intros X Y l xx H.\n  induction l.\n  -  reflexivity.\n  - destruct x. simpl in H. rewrite IHl in H.\n    * simpl in H. discriminate.\n    * rewrite <- H. destruct (split l). discriminate H.\nQed.\n  \n\nLemma tuples: forall X (x : X) (y: X), (x, x) = (y, y) -> x = y.\nProof. intros X x y H. injection H as H1 H2. apply H1. Qed.\n\n\nTheorem to_fst: forall X Y (x: X) (y: Y) (t: X * Y), (x, y) = t -> x = fst t.  \nProof. intros X Y x y t H. symmetry in H. rewrite H. simpl. reflexivity. Qed.\n\n\nTheorem to_snd: forall X Y (x: X) (y: Y) (t: X * Y), (x, y) = t -> y = snd t.  \nProof. intros X Y x y t H. symmetry in H. rewrite H. simpl. reflexivity. Qed.\n\n\nTheorem combine_tup: forall X Y (x: X) (y: Y) (l: list (X * Y)),\n    combine (fst (split ((x, y) :: l))) (snd (split ((x, y) :: l))) = (x, y) :: l.\nProof.\n  induction l.\n  - simpl. reflexivity.\n  - destruct x0. simpl in *. destruct (split l) in *. simpl in *.\n    destruct (combine x1 y1) in *.\n    * injection IHl as H1. symmetry in H1. rewrite H1. reflexivity.\n    * injection IHl as H1. symmetry in H1. rewrite H1. 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.\n\n  induction l.\n  - intros l1 l2 H. simpl in H. injection H as H1 H2. rewrite <- H1, <- H2. simpl. reflexivity.\n  - intros l1' l2' H. induction l1', l2'.\n    * apply xplit_nil_reason in H. discriminate H.\n    * apply xplit_nil_reason in H. discriminate H.\n    * apply xplit_nil_reason_2 in H. discriminate H.\n    * symmetry in H. apply to_fst in H as H1. apply to_snd in H as H2.\n      rewrite  H1. rewrite H2.\n      destruct x.\n      apply combine_tup.\nQed.\n      \nDefinition sillyfun1 (n : nat) : bool :=\n  if n =? 3 then true\n  else if n =? 5 then true\n       else false.\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3).\n  (* stuck... *)\nAbort.\n\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.\nQed.\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 b) eqn:Hf.\n  - destruct b.\n    * rewrite Hf. rewrite Hf. reflexivity.\n    * rewrite <- Hf. destruct (f false) eqn:Hff.\n      ** destruct (f true) eqn:Hfff.\n         *** rewrite Hfff. reflexivity.\n         *** rewrite Hff. reflexivity.\n      ** rewrite Hff. rewrite Hff. reflexivity.\n  - destruct b.\n    * destruct (f false) eqn:Hff.\n      ** rewrite Hf. reflexivity.\n      ** rewrite Hff. reflexivity.\n    * rewrite Hf. rewrite Hf. reflexivity.\nQed.\n\nTheorem eqb_sym : forall (n m : nat),\n  (n =? m) = (m =? n).\nProof.\n  induction n, m.\n  -  simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. apply IHn.\nQed.\n\n\nLemma idd: forall n, n =? n = true.\nProof.\n  induction n.\n  - reflexivity.\n  - simpl. rewrite IHn. reflexivity.\nQed.\n\n    \nTheorem eqb_trans : forall n m p,\n  n =? m = true ->\n  m =? p = true ->\n  n =? p = true.\nProof.\n  induction n, m, p.\n  1,2,3,4,5,6,7,8:simpl.\n  1,3: reflexivity.\n  intros H1 H2. discriminate H2.\n  1, 2, 3 : intros H; discriminate H.\n  - intros H1 H2. discriminate H2.\n  - intros H1 H2. apply eqb_true in H1. apply eqb_true in H2.\n    symmetry in H2. rewrite H1, H2. apply idd.\nQed.\n\nDefinition empty {X} (l: list X) :=\n  match l with\n  | [] => true\n  | _ => false\n  end.\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\n\n\nTheorem detuple : forall X Y (x : X) (y : Y) (t : X * Y),\n    x = fst t -> y = snd t -> (x, y) = t.\nProof.\n  intros X Y x y t H1 H2.\n  rewrite H1, H2.\n  destruct t.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem zero_length: forall X (l: list X), length l = 0 -> l = [].\nProof.\n  intros X l H.\n  destruct l.\n  - reflexivity.\n  - simpl in H. discriminate H.\nQed.\n\nTheorem tail_eq: forall X (x : X) (l1 : list X) (l2 : list X),\n    l1 = l2 -> x :: l1 = x :: l2.\nProof.\n  intros X x l1 l2 H.\n  rewrite <- H.\n  reflexivity.\nQed.\n\nTheorem split_combine : split_combine_statement.\nProof.\n  intros X Y.\n  induction l1.\n\n  - simpl. intros l2 H. symmetry in H. apply zero_length in H.\n    rewrite H. reflexivity.\n  - intros l2 H. simpl in *. destruct l2.\n    * simpl in H. discriminate H.\n    * simpl in *.\n      injection H as H.\n      symmetry. apply detuple.\n      ** simpl. destruct (split (combine l1 l2))  eqn:Hh. simpl.\n         symmetry in Hh. apply to_fst in Hh. rewrite Hh.\n         apply tail_eq.\n         rewrite IHl1.\n         *** simpl. reflexivity.\n         *** rewrite <- H. reflexivity.\n      ** simpl. destruct (split (combine l1 l2)) eqn:Hh. simpl.\n         symmetry in Hh. apply to_snd in Hh. rewrite Hh.\n         apply tail_eq.\n         rewrite IHl1.\n         *** simpl. reflexivity.\n         *** rewrite <- H. reflexivity.\nQed.\n\nTheorem filter_properly_defined: forall X (x: X) (l : list X) (test : X -> bool),\n    hd_error (filter test l) = Some x -> test x = true.\nProof.\n  intros X x l test H.\n  induction l.\n  - simpl in H. discriminate H.\n  - simpl in H. destruct (test x0) eqn: HH in H.\n    * simpl in H. injection H as H. rewrite <- H. apply HH.\n    * rewrite H in IHl. apply IHl. reflexivity.\nQed.\n\nTheorem convert: forall X (l: list X) (r: list X),\n    l = r -> hd_error l = hd_error r.\nProof. intros X l r H. rewrite H. reflexivity. Qed.\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 H.\n  apply convert in H. simpl in H. apply filter_properly_defined in H. apply H.\nQed.\n\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => true\n  | h :: t => match (test h) with\n            | true => forallb test t\n            | false => false\n            end\n  end.\n\nFixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => false\n  | h :: t => match (test h) with\n            | true => true\n            | false => existsb test t\n            end\n  end.\n\nDefinition existsb' {X : Type} (test : X -> bool) (l : list X) : bool :=\n  negb (forallb (fun x => negb (test x)) l).\n\nTheorem existsb_existsb' : forall (X : Type) (test : X -> bool) (l : list X),\n  existsb test l = existsb' test l.\nProof.\n  unfold existsb'.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. destruct (test x).\n    * simpl. reflexivity.\n    * simpl. rewrite <- IHl. reflexivity.\nQed.\n\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\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 is_three (n : nat) : Prop :=\n  n = 3.\nCheck is_three.\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\nLemma succ_inj : injective S.\nProof.\n  intros n m H. injection H as H1. apply H1.\nQed.\n\nCheck @eq.\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\nExample and_example : (3 + 4 = 7) /\\ (2 * 2 = 4).\n\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  - reflexivity.\n  - reflexivity.\nQed.\n\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m H.\n  apply and_intro.\n  - destruct m.\n    * rewrite plus_comm in H. simpl in H. apply H.\n    * rewrite plus_comm in H. discriminate H.\n  - destruct n.\n    * simpl in H. apply H.\n    * discriminate H.\nQed.\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example2' :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example2'' :\n  forall n m : nat, n = 0 -> m = 0 -> n + m = 0.\nProof.\n  intros n m Hn Hm.\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros n m H.\n  assert (H' : n = 0 /\\ m = 0).\n  { apply and_exercise. apply H. }\n  destruct H' as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP.\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.\n    * apply HP.\n    * apply HQ.\n  - apply HR.\nQed.\n\nCheck and.\n\nLemma or_example :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  (* This pattern implicitly does case analysis on\n     n = 0 \\/ m = 0 *)\n  intros n m [Hn | Hm].\n  - (* Here, n = 0 *)\n    rewrite Hn. reflexivity.\n  - (* Here, m = 0 *)\n    rewrite Hm. rewrite <- mult_n_O.\n    reflexivity.\nQed.\n\nLemma or_intro : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  (* WORKED IN CLASS *)\n  intros [|n].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\nModule MyNot.\nDefinition not (P:Prop) := P -> False.\nNotation \"~ x\" := (not x) : type_scope.\nCheck not.\n(* ===> Prop -> Prop *)\nEnd MyNot.\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  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 PProp NotP QProp P.\n  destruct NotP.\n  apply P.\nQed.\n\nNotation \"x <> y\" := (~(x = y)).\n\nTheorem zero_not_one : 0 <> 1.\nProof.\n  unfold not.\n  intros contra.\n  discriminate contra.\nQed.\n\nTheorem not_False :\n  ~False.\nProof.\n  unfold not. intros H. destruct H.\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].\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  (* WORKED IN CLASS *)\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 H1.\n  unfold not.\n  unfold not in H1.\n  intros H2.\n  apply H1 in H.\n  - destruct H.\n  - apply H2.\nQed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n  ~(P /\\ ~P).\nProof.\n  intros P.\n  unfold not.\n  intros H.\n  destruct H.\n  apply H0 in H.\n  destruct H.\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    exfalso.\n    unfold not in H.\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\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_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R.\n  split.\n  - intros [H1| H2].\n    * split.\n      ** left. apply H1.\n      ** left. apply H1.\n    * split.\n      ** right. apply H2.\n      ** right. apply H2.\n  - intros [H1  H2]. destruct H1, H2.\n    * left. apply H.\n    * left. apply H.\n    * left. apply H0.\n    * right. split.\n      ** apply H.\n      ** apply H0.\nQed.\n\nFrom Coq Require Import Setoids.Setoid.\n\n\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m. destruct n as [|n']. \n    + intros _. left. reflexivity.\n    + destruct m as [|m'].\n        - intros _. right. reflexivity.\n        - intros contra. discriminate contra.\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 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) ->\n  (exists o, n = 2 + o).\nProof.\n  intros n H. (* note implicit destruct here *)\n  destruct H as [m].\n  exists (2 + m).\n  apply H.\nQed.\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> not (exists x, not (P x)).\nProof.\n  intros X P.\n  unfold not.\n  intros H1 [x].\n  apply H.\n  apply 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 X P Q.\n  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\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x' = x \\/ In x l'\n  end.\n\nExample In_example_1 : In 4 [1; 2; 3; 4; 5].\nProof.\n  (* WORKED IN CLASS *)\n  simpl. right. right. right. left. reflexivity.\nQed.\n\nExample In_example_2 :\n  forall n, In n [2; 4] ->\n  exists n', n = 2 * n'.\nProof.\n  (* WORKED IN CLASS *)\n  simpl.\n  intros n [H | [H | L]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\n  - exfalso. apply L.\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 or_eq : forall X (x: X), (x = x) <-> True.\nProof.\n  intros X x.\n  split.\n  - intros H. apply I.\n  - intros H. reflexivity.\nQed.\n\nLemma or_true : forall P : Prop, (True \\/ P) <-> True.\nProof.\n  intros P.\n  split.\n  - intros H. apply I.\n  - intros H. left. apply I.\nQed.\n\nLemma and_true : forall P : Prop, (P /\\ True) <-> P.\nProof.\n  intros P.\n  split.\n  - intros H. destruct H. apply H.\n  - intros H. split.\n    * apply H.\n    * apply I.\nQed.\n\nLemma In_map_iff :\n  forall (A B : Type) (f : A -> B) (l : list A) (y : B),\n    In y (map f l) <->\n    exists x, f x = y /\\ In x l.\nProof.\n  intros A B f l y.\n  induction l.\n  - simpl. split.\n    * intros [].\n    * intros H. destruct H. destruct H. apply H0.\n  - simpl. split.\n    * intros [H | H].\n      ** exists x. split.\n         *** apply H.\n         *** left. reflexivity.\n      ** destruct IHl. apply H0 in H. destruct H.\n         exists x0. destruct H. split.\n         *** apply H.\n         *** right. apply H2.\n    * intros H. destruct H. destruct H. destruct H0.\n      ** left. rewrite <- H0 in H. apply H.\n      ** right. apply IHl. exists x0. split.\n         *** apply H.\n         *** apply H0.\nQed.\n\nLemma false_or : forall P : Prop, False \\/ P <-> P.\nProof.\n  intros P.\n  split.\n  - intros H. destruct H.\n    * exfalso. apply H.\n    * apply H.\n  -  intros H. right. apply H.\nQed.\n\nAxiom list_app_zero: forall X (l : list X), l ++ [] = l.\n\nLemma or_false : forall P : Prop, P \\/ False <-> P.\nProof.\n  intros P.\n  split.\n  - intros H. destruct H.\n    * apply H.\n    * exfalso. apply H.\n  -  intros H. left. apply H.\nQed.\n\nLemma In_app_iff : forall A l l' (a:A),\n  In a (l ++ l') <-> In a l \\/ In a l'.\nProof.\n  intros A l l' a.\n  induction l.\n  - simpl. rewrite false_or. reflexivity.\n  - simpl. rewrite <- or_assoc. split.\n    * intros H. induction l'.\n      ** simpl. rewrite or_false. rewrite list_app_zero in H. apply H.\n      ** simpl. rewrite IHl in H. simpl in H. apply H.\n    * intros H. induction l'.\n      ** simpl. rewrite list_app_zero in *. simpl in *. rewrite or_false in *. apply H.\n      ** simpl in *. rewrite <- IHl in H. apply H.\nQed.\n\nFixpoint All {T : Type} (P : T -> Prop) (l : list T) : Prop :=\n  match l with\n  | [] => True\n  | h :: t => (P h) /\\ (All P t)\n  end.\n\nLemma All_In :\n  forall T (P : T -> Prop) (l : list T),\n    (forall x, In x l -> P x) <->\n    All P l.\nProof.\n  intros T P l.\n  induction l.\n  - simpl. split.\n    * intros _. apply I.\n    * intros _ x H. exfalso. apply H.\n  - simpl in *. rewrite <- IHl. split.\n    * intros H. split.\n      ** apply H. left. reflexivity.\n      ** intros x0. intros H2. apply H. right. apply H2.\n    * intros H. intros x0. intros H1. destruct H. destruct H1.\n      ** rewrite <- H1. apply H.\n      ** apply H0. apply H1.\nQed.\n\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  (fun n => if (oddb n) then Podd n else Peven n).\n\nTheorem combine_odd_even_intro :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  intros Podd Peven n.\n  unfold combine_odd_even.\n  destruct (oddb n).\n  - intros H1 H2. apply H1. reflexivity.\n  - intros H1 H2. 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.\n  unfold combine_odd_even.\n  destruct (oddb n).\n  - intros H _. apply H.\n  - intros _ H. discriminate 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 Podd Peven n.\n  unfold combine_odd_even.\n  destruct (oddb n).\n  - intros _ H. discriminate H.\n  - intros H _. apply H.\nQed.\n\nCheck plus_comm.\n\nLemma plus_comm33 :\n  forall x y z, x + (y + z) = (z + y) + x.\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\nLemma plus_comm3_take2 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  assert (H : y + z = z + y).\n  { rewrite plus_comm. reflexivity. }\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma plus_comm3_take3 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  rewrite (plus_comm y z).\n  reflexivity.\nQed.\n\nLemma in_not_nil :\n  forall A (x : A) (l : list A), In x l -> l <> [].\nProof.\n  intros A x l H. unfold not. intro Hl. destruct l.\n  - simpl in H. destruct H.\n  - discriminate Hl.\nQed.\n\nLemma in_not_nil_42_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\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. simpl. reflexivity. Qed.\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n   (* Stuck *)\nAbort.\n\nAxiom functional_extensionality : forall {X Y: Type}\n                                    {f g : X -> Y},\n    (forall (x:X), f x = g x) -> f = g.\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n  apply functional_extensionality.\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.\nDefinition tr_rev {X} (l : list X) : list X :=\n  rev_append l [].\n\n\nTheorem delist: forall X (x : X) (l : list X), x :: l = [x] ++ l.\nProof. reflexivity. Qed.\n\nLemma rev_append_acc : forall X (a b: list X),\n    rev_append a b = rev_append a [] ++ b.\nProof.\n  intros X a.\n  induction a.\n  - simpl. reflexivity.\n  - simpl. intros b. rewrite IHa with (x :: b).\n    rewrite IHa with [x].\n    rewrite delist. rewrite app_assoc.\n    reflexivity.\nQed.\n      \nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n  intros X.\n  apply functional_extensionality.\n  unfold tr_rev.\n  intros l.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHl. rewrite rev_append_acc. 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. apply IHk'.\nQed.\n\n\nTheorem evenb_double_conv : forall n,\n  exists k, n = if evenb n then double k\n                else S (double k).\nProof.\n  intros n.\n  induction n.\n  - simpl. exists 0. reflexivity.\n  - rewrite evenb_S. destruct evenb.\n    * simpl. destruct IHn. exists x. apply eq_S. apply H.\n    * simpl. destruct IHn. rewrite H. exists (S x). simpl. reflexivity.\nQed.\n\nTheorem even_bool_prop : forall n,\n  evenb n = true <-> exists k, n = double k.\nProof.\n  intros n. split.\n  - intros H. destruct (evenb_double_conv n) as [k Hk].\n    rewrite Hk. rewrite H. exists k. reflexivity.\n  - intros [k Hk]. rewrite Hk. apply evenb_double.\nQed.\n\nTheorem eqb_eq : forall n1 n2 : nat,\n  n1 =? n2 = true <-> n1 = n2.\nProof.\n  intros n1 n2. split.\n  - apply eqb_true.\n  - intros H. rewrite H. destruct H. induction n1.\n    * simpl. reflexivity.\n    * simpl. apply IHn1.\nQed.\n\nFail Definition is_even_prime n :=\n  if n = 2 then true\n  else false.\n\nExample even_1000 : exists k, 1000 = double k.\nProof. exists 500. reflexivity. Qed.\n\nExample even_1000' : evenb 1000 = true.\nProof. reflexivity. Qed.\n\nExample even_1000'' : exists k, 1000 = double k.\nProof. apply even_bool_prop. reflexivity. Qed.\n\nExample not_even_1001 : evenb 1001 = false.\nProof.\n  (* WORKED IN CLASS *)\n  reflexivity.\nQed.\n\nExample not_even_1001' : ~(exists k, 1001 = double k).\nProof.\n  (* WORKED IN CLASS *)\n  rewrite <- even_bool_prop.\n  unfold not.\n  simpl.\n  intro H.\n  discriminate H.\nQed.\n\nLemma plus_eqb_example : forall n m p : nat,\n    n =? m = true -> n + p =? m + p = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros n m p H.\n    rewrite eqb_eq in H.\n  rewrite H.\n  rewrite eqb_eq.\n  reflexivity.\nQed.\n\nLemma andb_true_iff : forall b1 b2: bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros b1 b2.\n  split.\n  - intros H. split.\n    * destruct b1.\n      ** reflexivity.\n      ** simpl in H. discriminate H.\n    * destruct b2.\n      ** reflexivity.\n      ** rewrite andb_commutative in H. simpl in H. discriminate H.\n  - intros H. destruct b1, b2.\n    * simpl. reflexivity.\n    * destruct H. discriminate H0.\n    * destruct H. discriminate H.\n    * destruct H. discriminate H.\nQed.\n\nLemma or_b_commutative: forall (a b : bool), a || b = b || a.\nProof. intros a b. destruct a.\n       - simpl. destruct b. all: reflexivity.\n       - simpl. destruct b. all: reflexivity.\nQed.\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros b1 b2.\n  split.\n  - intros H. destruct b1.\n    * left. reflexivity.\n    * simpl in H. right. apply H.\n  - intros H. destruct H.\n    * rewrite H. simpl. reflexivity.\n    * rewrite H. rewrite or_b_commutative. simpl. reflexivity.\nQed.\n\nTheorem eq_x_x : forall x, x =? x = true.\nProof. intros x. induction x.\n       - simpl. reflexivity.\n       - simpl. apply IHx.\nQed.\n\nTheorem eqb_neq : forall x y : nat,\n  x =? y = false <-> x <> y.\nProof.\n  \n  split.\n  - intros H. unfold not. intros H1. rewrite H1 in H. rewrite eq_x_x in H. discriminate H.\n  - intros H. unfold not in H. rewrite <- eqb_eq in H. destruct eqb.\n    * exfalso. apply H. reflexivity.\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  | [], [] => true\n  | [], _ :: _ => false\n  | _ :: _, [] => false\n  | h1 :: t1, h2 :: t2 => eqb h1 h2 && eqb_list eqb t1 t2\n  end.\n\nLemma eqb_list_true_iff :\n  forall A (eqb : A -> A -> bool),\n    (forall a1 a2, eqb a1 a2 = true <-> a1 = a2) ->\n    forall l1 l2, eqb_list eqb l1 l2 = true <-> l1 = l2.\nProof.\n  intros A eqb H l1.\n  induction l1.\n  - intros l2. destruct l2.\n    * simpl. split. intros H1. reflexivity. intros H2. reflexivity.\n    * simpl. split. intros H1. discriminate H1. intros H2. discriminate H2.\n  - induction l2.\n    * simpl. split. intros H1. discriminate H1. intros H2. discriminate H2.\n    * simpl. rewrite andb_true_iff. split.\n      ** intros H1. destruct H1. rewrite H in H0.\n         rewrite H0. rewrite IHl1 in H1. rewrite H1.\n         reflexivity.\n      ** intros H2. injection H2 as HH1 HH2. split.\n         *** rewrite HH1. rewrite H. reflexivity.\n         *** rewrite IHl1. apply HH2.\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\nintros X test l.\ninduction l.\n- simpl. split. intros _. apply I. intros _. reflexivity.\n- simpl. split.\n  * destruct test.\n    ** intros H. split.\n       *** reflexivity.\n       *** apply IHl. apply H.\n    ** intros H. discriminate H.\n  * destruct test.\n    ** intros H. destruct H. apply IHl. apply H0.\n    ** intros H. destruct H. discriminate H.\nQed.\n\nDefinition excluded_middle := forall P : Prop,\n    P \\/ ~ P.\n\nTheorem restricted_excluded_middle : forall P b,\n  (P <-> b = true) -> P \\/ ~P.\nProof.\n  intros 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  intros P.\n  intros H. unfold not in H. apply H. right. intros H2. apply H. left. apply H2.\nQed.\n\nTheorem not_exists_dist :\n  excluded_middle ->\n  forall (X:Type) (P : X -> Prop),\n    not (exists x, not (P x)) -> (forall x, P x).\nProof.\n  intros EM.\n  intros X P.\n  intros H.\n  intros x.\n  destruct EM with (P x).\n  - apply H0.\n  - destruct H. exists x. apply H0.\nQed.\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\nDefinition double_negation_elimination := forall P:Prop,\n  ~~P -> P.\nDefinition de_morgan_not_and_not := forall P Q:Prop,\n  ~(~P /\\ ~Q) -> P\\/Q.\nDefinition implies_to_or := forall P Q:Prop,\n    (P->Q) -> (~P\\/Q).\n\nTheorem classic_to_peirce:\n  excluded_middle -> peirce.\nProof.\n  unfold excluded_middle.\n  unfold peirce.\n  intros H. intros P. destruct H with P.\n  * intros Q. intros H1. apply H0.\n  * intros Q. intros H1. unfold not in H0. apply H1.\n    intros H2. exfalso. apply H0. apply H2.\nQed.\n                     \nTheorem classic_to_dneg:\n  excluded_middle -> double_negation_elimination.\nProof.\n  unfold excluded_middle.\n  unfold double_negation_elimination.\n  intros H. intros P. destruct H with P.\n  - intros H1. apply H0.\n  - intros H1. apply H1 in H0. exfalso. apply H0.\nQed.\n\nTheorem classic_to_de_morgan:\n  excluded_middle -> de_morgan_not_and_not.\nProof.\n  unfold excluded_middle.\n  unfold de_morgan_not_and_not.\n  intros H. intros P Q. destruct H with P.\n  - intros H1. left. apply H0.\n  - destruct H with Q.\n    * intros H2. right. apply H1.\n    * intros H2. unfold not in *.  exfalso. apply H2. split.\n      ** apply H0.\n      ** apply H1.\nQed.\n\nTheorem classic_to_implies_to_or:\n  excluded_middle -> implies_to_or.\nProof.\n  unfold excluded_middle.\n  unfold implies_to_or.\n  intros H. intros P Q. destruct H with P.\n  - intros H1. right. apply H1. apply H0.\n  - intros H1. left. apply H0.\nQed.\n\nTheorem implies_to_or_to_classic:\n  implies_to_or -> excluded_middle.\nProof.\n  unfold excluded_middle.\n  unfold implies_to_or.\n  intros H. intros P.\n  destruct H with P P.\n  - intros H0. apply H0.\n  - right. apply H0.\n  - left. apply H0.\nQed.\n\nTheorem implies_classic_eqv:\n  implies_to_or <-> excluded_middle.\nProof. split. apply implies_to_or_to_classic. apply classic_to_implies_to_or. Qed.\n\nTheorem de_morgan_to_implies:\n  de_morgan_not_and_not -> implies_to_or.\nProof.\n  unfold de_morgan_not_and_not.\n  unfold implies_to_or.\n  intros H. intros P Q.\n  intros H0. apply H.\n  unfold not.\n  intros H1. destruct H1. destruct H1.\n  intros H3. apply H2. apply H0. apply H3.\nQed.\n\nTheorem demorgan_classic_eqv:\n  de_morgan_not_and_not <-> excluded_middle.\nProof.\n  split.\n  - rewrite <- implies_classic_eqv. apply de_morgan_to_implies.\n  - apply classic_to_de_morgan.\nQed.\n\nTheorem dneg_to_classic:\n  double_negation_elimination -> excluded_middle.\nProof.\n  unfold double_negation_elimination.\n  unfold excluded_middle.\n  intros H. intros P.\n  apply H.\n  apply excluded_middle_irrefutable.\nQed.\n\nTheorem dneg_classic_eqv:\n  double_negation_elimination <-> excluded_middle.\nProof. split. apply dneg_to_classic. apply classic_to_dneg. Qed.\n\nTheorem peirce_to_dneg:\n  peirce -> double_negation_elimination.\nProof.\n  unfold peirce.\n  unfold double_negation_elimination.\n  intros H P.\n  unfold not.\n  intros H0.\n  apply H with False.\n  intros H1.\n  exfalso.\n  apply H0.\n  apply H1.\nQed.\n\nTheorem peirce_classic_eqv:\n  peirce <-> excluded_middle.\n\nProof.\n  split.\n  - rewrite <- dneg_classic_eqv. apply peirce_to_dneg.\n  - apply classic_to_peirce.\nQed.\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. apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nTheorem ev_4' : even 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\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\nTheorem ev_double : forall n,\n  even (double n).\nProof.\n  intros n. induction n.\n  - simpl. apply ev_0.\n  - simpl. apply ev_SS. 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  - (* 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\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\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\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\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\nTheorem SSSSev__even : 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 even5_nonsense :\n  even 5 -> 2 + 2 = 9.\nProof.\n  intros H.\n  inversion H.\n  inversion H1.\n  inversion H3.\nQed.\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H.\n  inversion H.\n  reflexivity.\nQed.\n\nTheorem inversion_ex2 : 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 : forall n,\n  even n -> exists k, n = double k.\nProof.\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    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 *)\nAbort.\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\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\nTheorem ev_sum : forall n m, even n -> even m -> even (n + m).\nProof.\n  intros n m H1 H2.\n  induction H1, H2.\n  - simpl. apply ev_0.\n  - simpl. apply ev_SS. apply H2.\n  - rewrite plus_comm in *. simpl in *. apply ev_SS. apply H1.\n  - simpl. apply ev_SS. apply IHeven.\nQed.\n\nInductive even' : nat -> Prop :=\n| even'_0 : even' 0\n| even'_2 : even' 2\n| even'_sum n m (Hn : even' n) (Hm : even' m) : even' (n + m).\n\nTheorem even'_ev : forall n, even' n <-> even n.\nProof.\n  intros n.\n  split.\n  - intros H. induction H.\n    * apply ev_0.\n    * apply ev_SS. apply ev_0.\n    * apply ev_sum.\n      ** apply IHeven'1.\n      ** apply IHeven'2.\n  - intros H. induction H.\n    * apply even'_0.\n    * assert (H2 : forall n, S (S n) = n + 2).\n      { intros n0. rewrite plus_comm. simpl. reflexivity. }\n      rewrite H2. apply even'_sum.\n      ** apply IHeven.\n      ** apply even'_2.\nQed.\n\nTheorem ev_ev__ev : forall n m,\n  even (n+m) -> even n -> even m.\nProof.\n  intros n m H H1.\n  induction H1.\n  - simpl in *. apply H.\n  - apply IHeven. simpl in H. apply evSS_ev in H. apply H.\nQed.\n\nTheorem ev_plus_plus : forall n m p,\n  even (n+m) -> even (n+p) -> even (m+p).\nProof.\n  intros n m p H1 H2.\n  apply (ev_ev__ev (n + p)).\n  - rewrite (plus_comm _ p). rewrite (plus_comm _ p). rewrite plus_assoc.\n    rewrite (plus_comm _ p). rewrite plus_assoc. rewrite <- double_plus.\n    rewrite plus_comm. rewrite plus_assoc. rewrite plus_comm. rewrite plus_assoc.\n    apply ev_sum.\n    *  apply H1.\n    * apply ev_double.\n  - apply H2.\nQed.\n\nModule Playground.\n\n  Inductive 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\n  Notation \"m <= n\" := (le m n).\n\n\n  Theorem test_le1 : 3 <= 3.\n  Proof. apply (le_n 3). Qed.\n\n  Theorem test_le2 :\n    3 <= 6.\n  Proof.\n    apply (le_S 3 5).\n    apply (le_S 3 4).\n    apply (le_S 3 3).\n    apply (le_n 3).\n  Qed.\n\n  Theorem test_le3 :\n    (4 <= 2) -> 2 + 2 = 5.\n  Proof.\n    intros H.\n    inversion H.\n    inversion H2.\n    inversion H5.\n  Qed.\n\nEnd Playground.\n\nDefinition lt (n m:nat) := le (S n) m.\nNotation \"m < n\" := (lt m 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_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 := total n m : total_relation n m.\n\nDefinition empty_relation (n m : nat) := False.\n\nLemma tot : forall (n m : nat), total_relation n m.\nProof. intros n m. apply total. Qed.\n\nLemma empt : forall (n m : nat), not (empty_relation n m).\nProof. intros n m. unfold not. intros H. inversion H. Qed.\n\nTheorem n_le_m__Sn_le_Sm: forall n m, n <= m -> S n <= S m.\nProof.\n  intros n m H. induction H.\n    * apply le_n.\n    * apply le_S. apply IHle.\nQed.\n\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. apply le_n. inversion H1. \n  - inversion H.\n    * apply le_n.\n    * apply le_S. apply IHm. apply H1.\nQed.\n\nTheorem le_eqv: forall n m, n <= m <-> S n <= S m.\nProof.\n  split. apply n_le_m__Sn_le_Sm. apply Sn_le_Sm__n_le_m. Qed.\n        \nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o H1.\n  induction H1.\n  - intros H2. apply H2.\n  - intros H2. apply IHle. apply Sn_le_Sm__n_le_m. apply le_S. apply H2.\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. apply IHn.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  induction b.\n  - rewrite plus_comm. simpl. apply le_n.\n  - rewrite plus_comm. simpl. rewrite plus_comm. apply le_S. apply IHb.\nQed.\n\nTheorem not_le: forall n m : nat,  not (S n + m <= n).\nProof.\n  intros n m.\n  unfold not.\n  intros H.\n  induction n, m.\n  - simpl in *. inversion H.\n  - simpl in *. inversion H.\n  - simpl in *. rewrite plus_comm in *. simpl in *. apply Sn_le_Sm__n_le_m in H.\n    apply IHn. apply H.\n  - apply IHn. simpl in H. apply Sn_le_Sm__n_le_m in H. simpl. apply H.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n  unfold lt.\n  intros n1 n2 m H.\n  split.\n  - induction n1, n2.\n    * simpl in H. apply H.\n    * simpl in H. inversion H.\n      ** apply n_le_m__Sn_le_Sm. apply O_le_n.\n      ** apply n_le_m__Sn_le_Sm. apply O_le_n.\n    * simpl in *. rewrite plus_comm in *. simpl in *. apply H.\n    * destruct IHn1.\n      ** simpl in H. apply Sn_le_Sm__n_le_m. apply le_S. apply H.\n      ** apply Sn_le_Sm__n_le_m in H. apply not_le in H. exfalso. apply H.\n      ** apply n_le_m__Sn_le_Sm in l. apply l.\n  - rewrite plus_comm in H. induction n2, n1.\n    * simpl in H. apply H.\n    * simpl in H. inversion H.\n      ** apply n_le_m__Sn_le_Sm. apply O_le_n.\n      ** apply n_le_m__Sn_le_Sm. apply O_le_n.\n    * simpl in *. rewrite plus_comm in *. simpl in *. apply H.\n    * destruct IHn2.\n      ** simpl in H. apply Sn_le_Sm__n_le_m. apply le_S. apply H.\n      ** apply Sn_le_Sm__n_le_m in H. apply not_le in H. exfalso. apply H.\n      ** apply n_le_m__Sn_le_Sm in l. apply l.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  intros n m H. apply le_S. unfold lt in H. apply H.\nQed.\n\nTheorem leb_complete : forall n m,\n  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    * simpl in *. discriminate H.\n    * rewrite <- le_eqv.\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 H.\n  generalize dependent n.\n  induction m.\n  - intros n H. induction n.\n    * simpl. reflexivity.\n    * simpl in *. inversion H.\n  - intros n H. induction n.\n    * simpl. reflexivity.\n    * simpl in *. apply IHm.\n      rewrite le_eqv.\n      apply H.\nQed.\n\nTheorem leb_iff : forall n m,\n  n <=? m = true <-> n <= m.\nProof.\n  split. apply leb_complete. apply leb_correct.\nQed.\n\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  repeat rewrite leb_iff. apply le_trans.\nQed.\n\nModule R.\n\n  Inductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0\n   | c2 m n o (H : R m n o) : R (S m) n (S o)\n   | c3 m n o (H : R m n o) : R m (S n) (S o)\n   | c4 m n o (H : R (S m) (S n) (S (S o))) : R m n o\n   | c5 m n o (H : R m n o) : R n m o.\n\n  Lemma R1: R 1 1 2.\n  Proof. apply c2. apply c3. apply c1. Qed.\n  Lemma R2: R 2 2 6.\n  Proof. apply c2. apply c2. apply c3. apply c3. Abort.\n\n  Definition fR : nat -> nat -> nat := plus.\n\n  Theorem R_equiv_fR : forall m n o, R m n o <-> fR m n = o.\n  Proof.\n    unfold fR.\n    split.\n    - intros H. induction H.\n      * simpl. reflexivity.\n      * rewrite <- IHR. simpl. reflexivity.\n      * rewrite <- IHR. rewrite plus_comm. simpl. rewrite plus_comm. reflexivity.\n      * simpl in IHR. injection IHR as IHR2. rewrite plus_comm in IHR2.\n        simpl in IHR2. injection IHR2 as IHR3. rewrite plus_comm. apply IHR3.\n      * rewrite plus_comm. apply IHR.\n    - generalize dependent n. generalize dependent m. induction o.\n      * induction m.\n        ** intros n H. simpl in *. rewrite H. apply c1.\n        ** intros n H. discriminate H.\n      * induction m.\n        ** intros n H. simpl in *. rewrite H. apply c3. apply IHo. simpl. reflexivity.\n        ** intros n H. apply c2. apply IHo. simpl in H. injection H as H1. apply H1.\n  Qed.\n\nEnd R.\n\nInductive R : nat -> list nat -> Prop :=\n      | c1 : R 0 []\n      | c2 : forall n l, R n l -> R (S n) (n :: l)\n      | c3 : forall n l, R (S n) l -> R n l.\n\nExample r1: R 2 [1;0].\nProof.\n  apply c2.\n  apply c2.\n  apply c1.\nQed.\n\nExample r2: R 1 [1;2;1;0].\nProof.\n  apply c3.\n  apply c2.\n  apply c3.\n  apply c3.\n  apply c2.\n  apply c2.\n  apply c2.\n  apply c1.\nQed.\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\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\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.\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. inversion H.\nQed.\n\nFixpoint reg_exp_of_list {T} (l : list T) :=\n  match l with\n  | [] => EmptyStr\n  | x :: l' => App (Char x) (reg_exp_of_list l')\n  end.\n\nExample reg_exp_ex4 : [1; 2; 3] =~ reg_exp_of_list [1; 2; 3].\nProof.\n  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\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\nLemma empty_is_empty : forall T (s : list T),\n  ~(s =~ EmptySet).\nProof.\n  intros T s.\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.\n  - apply MUnionL. apply H.\n  - apply MUnionR. apply H.\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 T ss re H.\n  induction ss.\n  - simpl in *.  apply MStar0.\n  - simpl in *. apply MStarApp.\n    * apply H. left. reflexivity.\n    * apply IHss. intros s H1. apply H. right. apply H1.\nQed.\n\nTheorem list_h: forall T (x : T) (l1 l2 : list T), l1 = l2 -> x :: l1 = x :: l2.\nProof.\n  intros T x l1 l2 H. rewrite H. reflexivity.\nQed.\n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n  s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof.\n  intros T.\n  split.\n  - intros H. generalize dependent s1. induction s2.\n    * intros s1 H. inversion H. reflexivity.\n    * intros s1 H. inversion H. inversion H3. rewrite <- delist.\n      apply list_h. apply IHs2. apply H4.\n  - intros H. rewrite H. generalize dependent s1. induction s2.\n    * intros s1 H. simpl. apply MEmpty.\n    * intros s1 H. simpl. rewrite delist. apply MApp.\n      ** apply MChar.\n      ** apply IHs2 with s2. reflexivity.\nQed.\n\nFixpoint re_chars {T} (re : reg_exp) : list T :=\n  match re with\n  | EmptySet => []\n  | EmptyStr => []\n  | Char x => [x]\n  | App re1 re2 => re_chars re1 ++ re_chars re2\n  | Union re1 re2 => re_chars re1 ++ re_chars re2\n  | Star re => re_chars re\n  end.\n\nTheorem in_re_match : forall T (s : list T) (re : reg_exp) (x : T),\n  s =~ re ->\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  - (* MStarApp *)\n    simpl. rewrite In_app_iff in Hin.\n    destruct Hin as [Hin | Hin].\n    + (* In x s1 *)\n      apply (IH1 Hin).\n    + (* In x s2 *)\n      apply (IH2 Hin).\nQed.\n\nFixpoint re_not_empty {T : Type} (re : @reg_exp T) : bool :=\n  match re with\n  | EmptySet => false\n  | EmptyStr => true\n  | Char x => true\n  | App re1 re2 => re_not_empty re1 && re_not_empty re2\n  | Union re1 re2 => re_not_empty re1 || re_not_empty re2\n  | Star re => true\n  end.\n\nLemma re_not_empty_correct : forall T (re : @reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  intros T re.\n  split.\n  - intros H. induction H. induction H.\n    * simpl. reflexivity.\n    * simpl. reflexivity.\n    * simpl. rewrite andb_true_iff. split. apply IHexp_match1. apply IHexp_match2.\n    * simpl. rewrite orb_true_iff. left. apply IHexp_match.\n    * simpl. rewrite orb_true_iff. right. apply IHexp_match.\n    * simpl. reflexivity.\n    * simpl. reflexivity.\n  - induction re.\n    * intros H. simpl in *. discriminate H.\n    * intros H. simpl in *. exists []. apply MEmpty.\n    * intros H. exists [t]. apply MChar.\n    * simpl in *. intros H. rewrite andb_true_iff in H. destruct H. induction IHre1, IHre2.\n      ** apply H0.\n      ** exists (x ++ x0). apply MApp. apply H1. apply H2.\n      ** apply H0.\n      ** apply H.\n    * intros H. simpl in *. rewrite orb_true_iff in H. destruct H.\n      ** destruct IHre1.\n         *** apply H.\n         *** exists x. apply MUnionL. apply H0.\n      ** destruct IHre2.\n         *** apply H.\n         *** exists x. apply MUnionR. apply H0.\n    * intros H. exists []. apply MStar0.\nQed.\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  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 Heqre'.\n  - (* MApp *) discriminate.\n  - (* MUnionL *) discriminate.\n  - (* MUnionR *) discriminate.\n  - (* MStar0 *)\n    injection Heqre'. intros Heqre'' s H. simpl. apply H.\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\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\nintros T s r H.\n  remember (Star r) as r'.\n  induction H as [| | | | |r'|s s' r'' H _ H' IH'];\n  try (inversion Heqr' as [Heq]).\n  - exists [ ]. split.\n    + simpl. reflexivity.\n    + intros _ [].\n      \n  - subst. apply IH' in Heqr'. destruct Heqr' as [x Hx]. clear IH'.\n  destruct Hx as [Hfs' Hxr]. subst. clear H'.\n  exists (s :: x). split.\n    + simpl. trivial.\n    + intros s' H''. destruct H''.\n      * subst. trivial.\n      * apply Hxr. trivial.\nQed.\n\n\nModule Pumping.\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 T n m l.\n  induction n as [|n IHn].\n  - reflexivity.\n  - simpl. rewrite IHn, app_assoc. reflexivity.\nQed.\n\n\nRequire Import Coq.omega.Omega.\nRequire Export Logic.\n\nLemma sum_le: forall (n1 n2 n3 n4 : nat), n1 + n2 <= n3 + n4 -> n1 <= n3 \\/ n2 <= n4.\nProof.\n  intros n1 n2 n3 n4 H.\n  omega.\nQed.\n\nLemma sum_le2: forall (n1 n2 n3 : nat), n1 + n2 <= n3 -> n1 <= n3 /\\ n2 <= n3.\nProof.    \n  intros n1 n2 n3 H. split.\n  - omega.\n  - omega.\nQed.\n\nLemma length_le: forall T (s1 s2 : list T), 1 <= length (s1 ++ s2) -> 1 <= length s1 \\/ 1 <= length s2.\nProof.\n  intros T s1 s2 H.\n  rewrite app_length in H.\n  omega.\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\nProof.\n  intros T re s Hmatch.\n  induction Hmatch\n    as [ | x | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n       | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n       | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2 ].\n  - simpl. omega.\n  - simpl. omega.\n  - simpl. rewrite app_length. intro H.\n    apply sum_le in H. destruct H.\n    + apply IH1 in H.\n      destruct H as [x0 [x1 [x2]]].\n      destruct H as [Hs [Hx Happ]]. clear IH1. clear IH2.\n      exists x0, x1, (x2 ++ s2). split.\n      * rewrite Hs. repeat rewrite <- app_assoc. reflexivity.\n      * split.\n        ** trivial.\n        ** intros m. rewrite app_assoc. rewrite app_assoc. apply MApp.\n           *** rewrite <- app_assoc. apply Happ.\n           *** apply Hmatch2.\n    + apply IH2 in H.\n      destruct H as [x0 [x1 [x2]]].\n      destruct H as [Hs [Hx Happ]]. clear IH1. clear IH2.\n      exists (s1 ++ x0), x1, x2. split.\n      * rewrite Hs. repeat rewrite <- app_assoc. trivial.\n      * split.\n        ** apply Hx.\n        ** intros m. repeat rewrite <- app_assoc. apply MApp.\n           *** apply Hmatch1.\n           *** apply Happ.      \n  - simpl. intros H. apply sum_le2 in H. destruct H. apply IH in H. clear IH. clear H0.\n    destruct H as [x1 [x2 [x3]]].\n    destruct H as [H0 [H1 H2]].\n    exists x1, x2, x3. split.\n    + apply H0.\n    + split.\n      * apply H1.\n      * intros m. apply MUnionL. apply H2.\n  - simpl. intros H. rewrite plus_comm in H. apply sum_le2 in H.\n    destruct H. apply IH in H. clear IH. clear H0.\n    destruct H as [x1 [x2 [x3]]].\n    destruct H as [H0 [H1 H2]].\n    exists x1, x2, x3. split.\n    + apply H0.\n    + split.\n      * apply H1.\n      * intros m. apply MUnionR.\n        apply H2.\n  - simpl. omega.\n  - simpl in *. intros H. apply length_le in H.\n    destruct H.\n    * exists [], s1,s2. split.\n      ** simpl. trivial.\n      ** split.\n         *** induction s1.\n             **** inversion H.\n             **** unfold not. intros HH. inversion HH.\n         *** intros m. simpl. apply star_app.\n             **** induction m.\n                  ***** simpl. apply MStar0.\n                  ***** simpl. apply star_app. apply MStar1. apply Hmatch1. apply IHm.\n             **** apply Hmatch2.\n    * apply IH2 in H.\n      destruct H as [x1 [x2 [x3]]].\n      destruct H as [H0 [H1 H2]].\n      exists (s1 ++ x1), x2, x3.\n      split.\n      ** rewrite H0. repeat rewrite <- app_assoc. trivial.\n      ** split.\n        *** apply H1.\n        *** intros m. rewrite <- app_assoc.  apply MStarApp.\n          **** apply Hmatch1.\n          **** apply H2.\nQed.\n\nEnd Pumping.\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\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  (* 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\nTheorem reflect_iff : forall P b, reflect P b -> (P <-> b = true).\nProof.\n  intros P b H.\n  split.\n  - intros H0. destruct H.\n    * reflexivity.\n    * unfold not in *. apply H in H0. inversion H0.\n  - intros H0. destruct H.\n    * apply H.\n    * discriminate H0.\nQed.\n\nLemma eqbP : forall n m, reflect (n = m) (n =? m).\nProof.\n  intros n m. apply iff_reflect. rewrite eqb_eq. reflexivity.\nQed.\n\nTheorem filter_not_empty_In' : forall n l,\n  filter (fun x => n =? x) l <> [] ->\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.\n\nTheorem eqbP_practice : forall n l,\n  count n l = 0 -> ~(In n l).\nProof.\n  intros n l H.\n  induction l.\n  - simpl. unfold not. intros [].\n  - simpl. unfold not. intros H0. destruct H0.\n    * rewrite H0 in H. simpl in H. destruct (eqbP n n) in H.\n      ** inversion H.\n      ** unfold not in H1. apply H1. reflexivity.\n    * simpl in *. destruct (eqbP n x) in H.\n      ** inversion H.\n      ** simpl in *. apply IHl in H. clear IHl. clear H1. unfold not in *. apply H, H0.\nQed.\n\nInductive nostutter {X:Type} : list X -> Prop :=\n| nostutter_empty : nostutter []\n| nostutter_cons (hd: X) (tail: list X):\n    (hd_error tail) <> (Some hd) -> nostutter tail -> nostutter (hd :: tail).\n\nExample test_nostutter_1: nostutter [3;1;4;1;5;6].\nProof.\n  repeat constructor; simpl; unfold not; intros H; inversion H.\nQed.\n\nExample test_nostutter_2: nostutter (@nil nat).\nProof.\n  constructor.\nQed.\n\nExample test_nostutter_3: nostutter [5].\nProof.\n  constructor. simpl. unfold not. intros H. inversion H.\n  constructor.\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\n  contradiction H1. trivial.\nQed.\n\nDefinition tl {T} (l: list T) : list T :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nInductive merge {T : Type} : (list T) -> (list T) -> (list T) -> Prop :=\n| merge_empty_empty : merge [] [] []                            \n| merge_l (l1 l2 l : list T) :\n    l1 <> [] -> hd_error l1 = hd_error l -> merge (tl l1) l2 (tl l) -> merge l1 l2 l\n| merge_r (l1 l2 l : list T) :                                                                \n    l2 <> [] -> hd_error l2 = hd_error l -> merge l1 (tl l2) (tl l) -> merge l1 l2 l.\n\nExample merge_example: merge [1;6;3] [4;2] [1;4;6;2;3].\nProof.\n  simpl. constructor. unfold not. intros H. inversion H. simpl. trivial.\n  simpl. constructor 3. unfold not. intros H. inversion H. simpl. trivial.\n  simpl. constructor. unfold not. intros H. inversion H. simpl. trivial.\n  simpl. constructor 3. unfold not. intros H. inversion H. simpl. trivial.\n  simpl. constructor. unfold not. intros H. inversion H. simpl. trivial.\n  simpl. constructor.\nQed.\n\nTheorem hd_error_empty: forall X (l : list X), hd_error l = None -> l = [].\nProof.\n  intros X l H.\n  induction l.\n  - trivial.\n  - simpl in *. inversion H.\nQed.\n\nTheorem forallb_tail: forall X (l : list X) (test : X -> bool),\n    forallb test l = true -> forallb test (tl l) = true.\nProof.\n  intros X l test H.\n  induction l.\n  -  simpl. trivial.\n  - simpl in *. destruct (test x).\n    * apply H.\n    * inversion H.\nQed.\n\nTheorem forallb_false : forall X (l : list X) (test : X -> bool),\n    forallb test l = true -> (forall x, hd_error l = Some x -> test x = true).\nProof.\n  intros X  l test H0.\n  induction l.\n  - intros x H. simpl in *. inversion H.\n  - simpl in *. intros x0. destruct (test x) eqn:TT.\n    * intros H. injection H as H. subst. apply TT.\n    * discriminate H0.\nQed.\n    \n\nTheorem existsb_true : forall X (l : list X) (test : X -> bool),\n     existsb test l = false -> (forall x, hd_error l = Some x -> test x = false).\nProof.\n  intros X l test H0.\n  induction l.\n  - intros x H. simpl in *. inversion H.\n  - simpl in *. intros x0. destruct (test x) eqn:TT.\n    *  discriminate H0.\n    * intros H. injection H as H. subst. apply TT.\nQed.\n\n\nTheorem existsb_tail: forall X (l : list X) (test : X -> bool),\n    existsb test l = false -> existsb test (tl l) = false.\nProof.\n  intros X l test H.\n  induction l.\n  - simpl. trivial.\n  - simpl in *. destruct (test x).\n    * inversion H.\n    * apply H.\nQed.\n\nTheorem list_decom: forall X (x: X) (t l: list X),\n    hd_error l = Some x /\\ tl l = t -> x :: t = l.\nProof.\n  intros X x t l H.\n  destruct H.\n  rewrite <- H0.\n  induction l.\n  - simpl in *. discriminate H.\n  -  simpl in *. subst. injection H as HH. rewrite HH. trivial.\nQed.\n\nTheorem empty_merge: forall X (l : list X),\n    merge l [] [] -> l = [].\nProof.\n  intros X l H.\n  inversion H.\n  - trivial.\n  - subst. simpl in *. apply hd_error_empty in H1. apply H1.\n  - subst. unfold not in *. simpl in *. destruct H0. trivial.\nQed.\n\nTheorem fiter_filter : forall X (l l1 l2: list X) (test : X -> bool),\n    merge l1 l2 l ->\n    forallb test l1 = true ->\n    existsb test l2 = false ->\n    filter test l = l1.\nProof.\n  intros X.\n  induction l.\n  - intros l1 l2 test Hm Hl1 Hl2. simpl. inversion Hm.\n    * trivial.\n    * simpl in H. apply hd_error_empty in H0. subst. trivial.\n    * simpl in *. subst. apply hd_error_empty in H0. subst. simpl in *.\n      clear Hl2 Hl1. apply empty_merge in Hm. symmetry. trivial.\n  - simpl in *. intros l1 l2 test Hm Hl1 Hl2. inversion Hm.\n    * clear Hm. subst. simpl in *. apply IHl with (tl l1) l2 test in H1.\n      ** destruct test eqn:TT.\n         *** clear IHl. apply list_decom. split.\n             **** trivial.\n             **** symmetry. trivial.\n         *** apply forallb_false with X l1 test x in Hl1. subst.\n             rewrite Hl1 in TT. inversion TT. apply H0.\n      ** apply forallb_tail. apply Hl1.\n      ** apply Hl2.\n    * subst. simpl in *. apply IHl with l1 (tl l2) test in H1.\n      ** destruct (test x) eqn:TT.\n         *** apply existsb_true with X l2 test x in Hl2. subst.\n             rewrite Hl2 in TT. inversion TT. apply H0.\n         *** apply H1.\n      ** apply Hl1.\n      ** apply existsb_tail. apply Hl2.\nQed.\n\nRequire Import Coq.omega.Omega.\nRequire Export Logic.\n\n\n\nInductive subseq: list nat -> list nat -> Prop :=\n  subseq_nil : forall l, subseq [] l\n| subseq_inboth : forall x l1 l2, subseq l1 l2 -> subseq (x :: l1) (x :: l2)\n| subseq_in2nd  : forall x l1 l2, subseq l1 l2 -> subseq l1 (x :: l2).\n\nTheorem subseq_refl : forall (l : list nat), subseq l l.\nProof.\n  intros l.\n  induction l.\n  - apply subseq_nil.\n  - apply subseq_inboth. apply IHl.\nQed.\n\nTheorem subseq_app : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l1 (l2 ++ l3).\nProof.\n  intros l1 l2 l3 H.\n  induction H.\n  - apply subseq_nil.\n  - apply subseq_inboth. apply IHsubseq.\n  - apply subseq_in2nd. apply IHsubseq.\nQed.\n  \nTheorem subseq_trans : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l2 l3 ->\n  subseq l1 l3.\nProof.\n  intros l1 l2 l3 H1 H2.\n  generalize dependent H1.\n  generalize dependent l1.\n  induction H2.\n  - intros l1 H1. inversion H1. apply subseq_nil.\n  - intros l0 H1. inversion H1.\n    * apply subseq_nil.\n    * apply subseq_inboth. apply IHsubseq. apply H3.\n    * apply subseq_in2nd. rewrite <- H0. apply IHsubseq. rewrite <- H0 in H3. apply H3.\n  - intros l0 H1. apply subseq_in2nd. apply IHsubseq. apply H1.\nQed.\n\n\nLemma subseq_l_xl: forall x l1 l2, subseq l1 (x :: l2) -> subseq l1 l2 \\/ hd_error l1 = Some x.\nProof.\n  intros x l1 l2 H.\n  inversion H.\n  - subst. simpl in *. left. constructor.\n  - subst. right. simpl. trivial.\n  - subst. left. apply H2.\nQed.\n\nLemma subseq_xl_l: forall x l1 l2, subseq (x :: l1) l2 -> subseq l1 l2.\nProof.\n  intros x l1 l2 H.\n  apply subseq_trans with (x::l1).\n  - constructor. apply subseq_refl.\n  - apply H.\nQed.\n  \nLemma subseq_xl_xl: forall x1 x2 l1 l2, subseq (x1 :: l1) (x2 :: l2) -> subseq l1 l2.\nProof.\n  intros x1 x2 l1 l2 H.\n  apply subseq_l_xl in H as H0.\n  destruct H0.\n  - apply subseq_trans with (x1 :: l1).\n    * constructor. apply subseq_refl.\n    * apply H0.\n  - simpl in *. injection H0 as H1. subst. inversion H.\n    * subst. apply H1.\n    * subst. apply subseq_xl_l in H2. apply H2.\nQed.\n\nTheorem fiter_filter' : forall (l l': list nat) (test : nat -> bool),\n    subseq l' l ->\n    forallb test l' = true ->\n    length (filter test l) >= length (filter test l').\nProof.\n  induction l.\n  - intros l' test H0 H1. simpl. inversion H0. subst. simpl. omega.\n  - intros l' test H0 H1. simpl in *. destruct (test x) eqn:TT.\n    * simpl in *. induction l'.\n      ** simpl. omega.\n      ** simpl in *.  destruct (test x0) eqn:TTT.\n         *** simpl. assert (H: forall n m, n >= m -> S n >= S m).\n             **** intros n m H. omega.\n             **** apply H. apply IHl.\n                  ***** apply subseq_xl_xl in H0. apply H0.\n                  ***** apply H1.\n         *** discriminate H1.\n    * apply IHl.\n      ** clear IHl.\n         apply subseq_l_xl in H0. destruct H0.\n         *** apply H.\n         *** assert (Herror: hd_error l' = Some x -> exists t, l' = x :: t).\n             **** intros HH. exists (tl l'). induction l'.\n                  ***** simpl in *. discriminate HH.\n                  ***** simpl in *. injection HH as HH. rewrite HH. reflexivity.\n             **** apply Herror in H. destruct H as [t H]. subst. clear Herror.\n             simpl in H1. rewrite TT in H1. discriminate H1.\n      ** apply H1.\nQed.\n\n\n\n\nInductive pal: list nat -> Prop :=\n| empty_pal : pal []\n| single_pal : forall (x : nat), pal [x]\n| pal_extend: forall (l1 l2 : list nat), l1 = rev l1 -> pal (l2 ++ l1 ++ (rev l2)).                                           \n\nTheorem pal_app_rev:\n  forall l, pal (l ++ rev l).\nProof. intros l. apply (pal_extend [] l). simpl. trivial. Qed.\n\nTheorem pal_rev:\n  forall l, pal l -> l = rev l.\nProof.\n  intros l H.\n  induction H.\n  - constructor.\n  - constructor.\n  - rewrite rev_app_distr. rewrite rev_app_distr. rewrite rev_involutive.\n    rewrite <- app_assoc. rewrite H. rewrite rev_involutive. rewrite <- H. trivial.\nQed.\n\nTheorem tail_eq2: forall l1 l2 : list nat, l1 = l2 -> tl l1 = tl l2.\nProof.\n  intros l1 l2 H. rewrite H. trivial.\nQed.\n\nTheorem rev_pal:\n  forall l, l = rev l -> pal l.\nProof.\n  intros l H.\n  destruct l.\n  - constructor.\n  - simpl in H. rewrite delist in *.\n    apply tail_eq2 in H as H1. simpl in H1.\n    destruct (rev l) eqn: HHH.\n    * simpl in *. rewrite H1. constructor.\n    * simpl in H1.\n      subst.\n      rewrite rev_app_distr in HHH. simpl in HHH.\n      rewrite delist in HHH. injection HHH as H1.\n      constructor.\n      symmetry.\n      apply H0.\nQed.\n    \nDefinition disjoint (l1 l2 : list nat) : Prop :=\n  forall x, In x l1 -> not (In x l2).\n\nInductive NoDup: list nat -> Prop :=\n| nodup_empty : NoDup []\n| nodup_single : forall (x : nat), NoDup [x]\n| nodup_app : forall (l1: list nat) (l2 : list nat),\n    NoDup l1 -> NoDup l2 -> disjoint l1 l2 -> NoDup (l1 ++ l2).\n\nTheorem nodup_1:\n  forall l1 l2 l3, NoDup l1 -> NoDup l2 -> NoDup l3 ->\n              disjoint l1 l2 -> disjoint l2 l3 -> disjoint l1 l3 -> NoDup (l1 ++ l2 ++ l3).\nProof.\n  intros l1 l2 l3 H1 H2 H3 HH1 HH2 HH3.\n  constructor.\n  - apply H1.\n  - constructor.\n    * apply H2.\n    * apply H3.\n    * apply HH2.\n  - unfold disjoint in *.\n    intros x.\n    intros HHH.\n    unfold not in *.\n    intros HHH1.\n    apply In_app_iff in HHH1.\n    destruct HHH1.\n    * apply HH1 with x.\n      ** apply HHH.\n      ** apply H.\n    * apply HH3 with x.\n      ** apply HHH.\n      ** apply H.\nQed.\n\nTheorem nodup_2: forall l1 l2, NoDup l1 -> NoDup l2 -> disjoint l1 l2 -> NoDup (l2 ++ l1).\nProof.\n  intros l1 l2 H1 H2 H3.\n  constructor.\n  - apply H2.\n  - apply H1.\n  - unfold disjoint in *.\n    unfold not in *.\n    intros x HH1 HH2.\n    apply H3 with x.\n    * apply HH2.\n    * apply HH1.\nQed.\n\nLemma in_split : forall (X:Type) (x:X) (l:list X),\n  In x l ->\n  exists l1 l2, l = l1 ++ x :: l2.\nProof.\n  intros X x l H.\n  induction l.\n  - simpl. inversion H.\n  - rewrite delist in H. rewrite In_app_iff in H. simpl in H.\n    destruct H.\n    * destruct H.\n      ** subst. exists [], l. simpl. trivial.\n      ** inversion H.\n    * destruct IHl.\n      ** apply H.\n      ** destruct H0. exists (x0 :: x1), x2.\n         simpl. rewrite H0. trivial.\nQed.\n\nRequire Import Coq.Arith.Lt.\n\nInductive repeats {X:Type} : list X -> Prop :=\n| one_repeat : forall x, repeats [x; x]\n| with_repeat_left : forall l1 l2, repeats l1 -> repeats (l1 ++ l2)\n| with_repeat_right : forall l1 l2, repeats l1 -> repeats (l2 ++ l1)\n| repeats_el: forall x l, In x l -> repeats (x :: l).\n\n\nTheorem exclude_In: forall X (x1 x2 : X) (l1 l2 : list X),\n    In x1 (l1 ++ x2 :: l2) -> x1 <> x2 -> In x1 (l1 ++ l2).\nProof.\n  intros X x1 x2 l1 l2 H1 H2.\n  apply In_app_iff.\n  apply In_app_iff in H1. rewrite delist in H1.\n  destruct H1.\n  - left. apply H.\n  - apply In_app_iff in H. destruct H.\n    * exfalso. unfold not in *. apply H2. simpl in H. destruct H.\n      ** symmetry. apply H.\n      ** inversion H.\n    * right. apply H.\nQed.\n\nTheorem exclude_length: forall X (x : X) (l1 l2 : list X),\n    length (l1 ++ x :: l2) = S (length (l1 ++ l2)).\nProof.\n  intros X x l1 l2.\n  rewrite app_length. rewrite delist.\n  rewrite app_length. rewrite app_length.\n  simpl. rewrite <- plus_1_l.\n  rewrite <- (plus_1_l (length l1 + length l2)).\n  repeat rewrite plus_assoc. rewrite (plus_comm 1 (length l1)).\n  trivial.\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' IHl1'].\n  - intros l2 Hem H Hlength. simpl in *. inversion Hlength.\n  - intros l2 Hem H Hlength. simpl in *.\n    destruct (Hem (In x l1')).\n    * apply repeats_el. apply H0.\n    * unfold not in *. rewrite delist. constructor 3.\n      destruct (Hem (In x l2)).\n      ** apply in_split in H1.\n         inversion H1. inversion H2.\n         apply IHl1' with (x0 ++ x1).\n         *** apply Hem.\n         *** intros x2 HH. subst.\n             destruct (Hem (x2 = x)).\n             **** subst. contradiction.\n             **** clear IHl1' H1 H2 Hem. apply exclude_In with x.\n                  ***** apply H. right. apply HH.\n                  ***** apply H3.\n         *** subst. clear H H0 H1. rewrite exclude_length in Hlength.\n             apply lt_S_n. apply Hlength.\n      ** unfold not in *. exfalso. apply H1. apply H. left. trivial.\nQed.\n\nRequire Export Coq.Strings.Ascii.\nDefinition string := list ascii.\n\nLemma provable_equiv_true : forall (P : Prop), P -> (P <-> True).\nProof.\n  intros.\n  split.\n  - intros. constructor.\n  - intros _. apply H.\nQed.\n\nLemma not_equiv_false : forall (P : Prop), ~P -> (P <-> False).\nProof.\n  intros.\n  split.\n  - apply H.\n  - intros. destruct H0.\nQed.\n\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\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\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\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\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\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. subst. 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\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   assert (app_nil: forall X (s : list X), [] ++ s = s). intros. simpl. trivial.\n  split.\n  - intros. inversion H. subst. \n    destruct s1.\n    * simpl in *. left. split. apply H3. apply H4.\n    * simpl in *. injection H1 as H11 H22. subst. right.\n      exists s1, s2. split.\n      ** reflexivity.\n      ** split. apply H3. apply H4.  \n  -  intros. destruct H.\n     * destruct H.\n       rewrite <- app_nil with ascii (a::s).\n       apply MApp. apply H. apply H0.\n     * destruct H as [s0 [s1]]. destruct H. destruct H0.\n       rewrite H. rewrite delist. rewrite app_assoc. apply MApp.\n       ** simpl. apply H0.\n       ** simpl. apply H1.\nQed.\n\nLemma union_disj : forall (s : string) re0 re1,\n    s =~ Union re0 re1 <-> s =~ re0 \\/ s =~ re1.\nProof.\n  intros. split.\n  - intros. inversion H. subst.\n    + left. apply H2.\n    + right. apply H1.\n  - intros [ H | H ].\n    + apply MUnionL. apply H.\n    + apply MUnionR. apply H.\nQed.\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  - intros H.\n    remember (a :: s) as s'.\n    remember (Star re) as star'.\n    induction H.\n    * discriminate.\n    * discriminate.\n    * discriminate.\n    * discriminate.\n    * discriminate.\n    * discriminate.\n    * injection Heqstar' as HH. subst.\n      destruct s1.\n      ** simpl in *. apply IHexp_match2. apply Heqs'. reflexivity.\n      ** clear IHexp_match2. clear IHexp_match1.\n         simpl in Heqs'.\n         inversion Heqs'. subst. clear Heqs'.\n         exists s1, s2. split.\n         *** trivial.\n         *** split. apply H. apply H0.\n  - intros H. destruct H as [s0 [s1]]. destruct H. destruct H0. subst.\n    apply (MStarApp (a :: s0) s1). apply H0. apply H1.\nQed.\n\nDefinition refl_matches_eps m :=\n  forall re : @reg_exp ascii, reflect ([ ] =~ re) (m re).\n\nFixpoint match_eps (re: @reg_exp ascii) : bool :=\n  match re with\n  | EmptyStr => true\n  | App re1 re2 => andb (match_eps re1) (match_eps re2)\n  | Star _ => true\n  | Union re1 re2 => orb (match_eps re1) (match_eps re2)\n  | _ => false\n  end.\n\n\nTheorem empty_app : forall X (l1 l2 : list X), l1 ++ l2 = [] <-> l1 = [] /\\ l2 = [].\nProof.\n  intros X l1 l2.\n  split.\n  - intros H. split.\n    * destruct l1.\n      ** reflexivity.\n      ** inversion H.\n    * destruct l2.\n      ** reflexivity.\n      ** destruct l1.\n         *** simpl in H. inversion H.\n         *** simpl in H. inversion H.\n  - intros H. destruct H. subst. simpl. reflexivity.\nQed.\n\nLemma match_eps_refl : refl_matches_eps match_eps.\nProof.\n  unfold refl_matches_eps.\n  intros.\n  apply iff_reflect.\n  split.\n  - induction re.\n    * intros. inversion H.\n    * intros. simpl. trivial.\n    * intros. inversion H.\n    * intros. inversion H. subst. apply empty_app in H1.\n      destruct H1. subst. apply IHre1 in H3. apply IHre2 in H4.\n      simpl. apply andb_true_iff. split. apply H3. apply H4.\n    * intros. inversion H.\n      ** subst. apply IHre1 in H2. simpl.\n         apply orb_true_iff. left. apply H2.\n      ** subst. apply IHre2 in H1. simpl.\n         apply orb_true_iff. right. apply H1.\n    * intros. simpl. trivial.\n  - induction re.\n    * simpl. intros. inversion H.\n    * simpl. intros. apply MEmpty.\n    * simpl. intros. inversion H.\n    * simpl. intros. apply andb_true_iff in H. destruct H.\n      rewrite <- (app_nil_r _ []). apply MApp.\n      ** apply IHre1 in H. apply H.\n      ** apply IHre2 in H0. apply H0.\n    * simpl. intros. apply orb_true_iff in H. destruct H.\n      ** apply MUnionL. apply IHre1 in H. apply H.\n      ** apply MUnionR. apply IHre2 in H. apply H.\n    * simpl. intros. apply MStar0.\nQed.\n\nDefinition is_der re (a : ascii) re' :=\n  forall s, a :: s =~ re <-> s =~ re'.\n\nDefinition derives d := forall a re, is_der re a (d a re).\n\nFixpoint derive (a : ascii) (re : @reg_exp ascii) : @reg_exp ascii :=\n  match re with\n  | EmptySet => EmptySet\n  | EmptyStr => EmptySet\n  | Char a' => if (ascii_dec a a') then EmptyStr else EmptySet\n  | App re1 re2 => if (match_eps re1)\n                  then 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) (Star re)\n  end.\n\nExample c := ascii_of_nat 99.\nExample d := ascii_of_nat 100.\n\nExample test_der0 : match_eps (derive c (EmptySet)) = false.\nProof. simpl. trivial. Qed.\n\nExample test_der1 : match_eps (derive c (Char c)) = true.\nProof. simpl. trivial. Qed.\n\nExample test_der2 : match_eps (derive c (Char d)) = false.\nProof. simpl. trivial. Qed.\n\nExample test_der3 : match_eps (derive c (App (Char c) EmptyStr)) = true.\nProof. simpl. trivial. Qed.\n\nExample test_der4 : match_eps (derive c (App EmptyStr (Char c))) = true.\nProof. simpl. trivial. Qed.\n\nExample test_der5 : match_eps (derive c (Star (Char c))) = true.\nProof. simpl. trivial. Qed.\n\nExample test_der6 :\n  match_eps (derive d (derive c (App (Char c) (Char d)))) = true.\nProof. simpl. trivial. Qed.\n\nExample test_der7 :\n  match_eps (derive d (derive c (App (Char d) (Char c)))) = false.\nProof. simpl. trivial. Qed.\n\nTheorem app_nil_l : forall X (l : list X), l = [] ++ l.\nProof. simpl. trivial. Qed.\n\nLemma derive_corr : derives derive.\nProof.\n  split.\n  - intros H.\n    generalize dependent s.\n    induction re; intros s H.\n    * inversion H.\n    * inversion H.\n    * inversion H. subst.\n      simpl. destruct (ascii_dec t t).\n      apply MEmpty. unfold not in *. exfalso. apply n. trivial.\n    *  simpl in *. inversion H. subst.\n       apply app_ne in H. \n       destruct (match_eps_refl re1).\n       ** destruct s1.\n          *** simpl in *. subst. apply MUnionR. apply IHre2. apply H4.\n          *** simpl in *. apply MUnionL. inversion H1. subst.\n              apply MApp.\n              **** clear H1. apply IHre1. apply H3.\n              **** apply H4.\n       ** unfold not in *. destruct s1.\n          *** exfalso. apply H0, H3.\n          *** simpl in *. inversion H1. subst. clear H1 H0.\n              apply MApp.\n              **** apply IHre1, H3.\n              **** apply H4.\n    * simpl in *. inversion H.\n      ** subst. apply MUnionL. apply IHre1. apply H2.\n      ** subst. apply MUnionR. apply IHre2. apply H1.\n    * simpl. apply star_ne in H.\n      destruct H as [s0 [s1]]. destruct H. destruct H0.\n      subst. apply MApp.\n      ** apply IHre, H0.\n      ** apply H1.\n  - intros H.\n    generalize dependent s.\n    induction re; intros s H.\n    * inversion H.\n    * inversion H.\n    * simpl in *. destruct (ascii_dec a t).\n      ** inversion H. subst. apply MChar.\n      ** inversion H.\n    * simpl in *. destruct (match_eps_refl re1).\n      ** inversion H. subst.\n         *** inversion H3. subst. rewrite delist. rewrite app_assoc. apply MApp.\n             **** simpl in *. apply IHre1, H5.\n             **** apply H6.\n         *** subst. rewrite app_nil_l with ascii (a :: s).\n             apply MApp.\n             **** apply H0.\n             **** apply IHre2, H3.\n      ** inversion H. subst. rewrite delist. rewrite app_assoc. apply MApp.\n         *** simpl. apply IHre1. apply H4.\n         *** apply H5.\n    * simpl in *. inversion H; subst.\n      ** apply MUnionL, IHre1, H2.\n      ** apply MUnionR, IHre2, H1.\n    * simpl in *. inversion H. subst. rewrite delist. rewrite app_assoc. apply MStarApp.\n      ** simpl. apply IHre. apply H3.\n      ** apply H4.\nQed.\n\nDefinition matches_regex m : Prop :=\n  forall (s : string) re, reflect (s =~ re) (m s re).\n\nFixpoint regex_match (s : string) (re : @reg_exp ascii) : bool :=\n  match s with\n  | [] => match_eps re\n  | h :: t => regex_match t (derive h re)\n  end.\n\nTheorem regex_refl : matches_regex regex_match.\nProof.\n  unfold matches_regex.\n  intros s.\n  induction s as [| h t IH]; simpl; intros.\n  - apply (match_eps_refl re).\n  - destruct  (IH (derive h re)) as [refl_t | refl_f].\n    * apply ReflectT. apply derive_corr in refl_t. apply refl_t.\n    * apply ReflectF. unfold not in *. intros H. apply derive_corr in H.\n      apply refl_f in H. apply H.\nQed.\n", "meta": {"author": "dk14", "repo": "emacs-init", "sha": "2325f4587e32eae7e13cf63ebbd5ce4f9ffa2e9e", "save_path": "github-repos/coq/dk14-emacs-init", "path": "github-repos/coq/dk14-emacs-init/emacs-init-2325f4587e32eae7e13cf63ebbd5ce4f9ffa2e9e/test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.6904758805190565}}
{"text": "Require Import List.\nRequire Import QArith.\nRequire Import Qpower.\nRequire Import Orders.\nRequire Import Sorted.\nRequire Import hddivsteps_base.\nImport ListNotations.\n\nLemma Dadd_Q : forall x y, Dadd x y == x + y.\nProof.\nintros x y.\nunfold Dadd.\nassert (Hxy := Dalign_lr x y).\ndestruct (Dalign x y) as [[xm ym] e].\ndestruct Hxy as [<- <-].\nunfold inject_D; simpl.\nrewrite inject_Z_plus.\nring.\nQed.\n\nLemma Dsub_Q : forall x y, Dsub x y == x - y.\nProof.\nintros x y.\nunfold Dsub.\nassert (Hxy := Dalign_lr x y).\ndestruct (Dalign x y) as [[xm ym] e].\ndestruct Hxy as [<- <-].\nunfold inject_D, Z.sub; simpl.\nrewrite inject_Z_plus, inject_Z_opp.\nring.\nQed.\n\nLemma Dmult_Q : forall x y, Dmult x y == x * y.\nProof.\nintros x y.\nunfold Dmult, inject_D; simpl.\nrewrite inject_Z_mult, Qpower_plus by discriminate.\nring.\nQed.\n\nLemma Dhalf_Q : forall x, Dhalf x == x / 2.\nProof.\nintros x.\nunfold Dhalf, inject_D, Z.pred; simpl.\nrewrite Qpower_plus, Qmult_assoc by discriminate.\nreflexivity.\nQed.\n\nLemma Dltb_Q : forall x y, Dltb x y = true -> x < y.\nProof.\nintros a b.\nunfold Dltb, D_as_TTLT.leb, D_as_OrderedTypeAlt.compare.\nrewrite D_as_OrderedTypeAlt.compare_sym, Dcompare_Q, Qlt_alt.\ncase (a ?= b);try discriminate;reflexivity.\nQed.\n\nDefinition QQ : Set := Q * Q.\nDefinition Qsum := fold_right Qplus 0.\nDefinition Qcombine := \n  fold_right (fun (qp : Q * DD) a =>\n             (fst a + fst qp * fst (snd qp), snd a + fst qp * snd (snd qp)))\n             (0,0).\nDefinition QQplus p1 p2 := (fst p1 + fst p2, snd p1 + snd p2).\nDefinition QQscale c p := (c * fst p, c * snd p).\nDefinition QQavg c p1 p2 := QQplus (QQscale c p1) (QQscale (1-c) p2).\nDefinition QQeq (p q : QQ) := fst p == fst q /\\ snd p == snd q.\nDefinition inject_DD (p : DD) : QQ := (inject_D (fst p), inject_D (snd p)).\nCoercion inject_DD : DD >-> QQ.\n\nLemma QQeq_sym : forall p q, QQeq p q -> QQeq q p.\nProof.\nintros p q [H0 H1].\nunfold QQeq.\nauto with *.\nQed.\n\nHint Rewrite Dcompare_Q Dadd_Q Dmult_Q Dsub_Q : DQ.\n\nLemma Qsum_app : forall l1 l2, Qsum (l1 ++ l2) == Qsum l1 + Qsum l2.\nProof.\nintros l1 l2.\nunfold Qsum.\nrewrite fold_right_app.\ngeneralize (fold_right Qplus 0 l2); intros q.\ninduction l1;simpl;[ring|].\nrewrite IHl1.\nring.\nQed.\n\nLemma Qsum_pos : forall l, (forall x, In x l -> 0 <= x) ->\n 0 <= Qsum l.\nProof.\ninduction l;simpl;auto with *.\nintros H.\nchange 0 with (0 + 0).\nauto using Qplus_le_compat.\nQed.\n\nLemma Qsum_mult : forall c l, Qsum (map (Qmult c) l) == c * Qsum l.\nProof.\ninduction l;simpl;try rewrite IHl; ring.\nQed.\n\nLemma QQscale_1 : forall p, QQeq (QQscale 1 p) p.\nProof.\nintros p.\nsplit;simpl;ring.\nQed.\n\nLemma QQscale_mult : forall a b p,\n  QQeq (QQscale a (QQscale b p)) (QQscale (a*b) p).\nProof.\nintros a b p.\nsplit;simpl;ring.\nQed.\n\nLemma Qcombine_app : forall l1 l2,\n  QQeq (Qcombine (l1 ++ l2)) \n       (QQplus (Qcombine l1) (Qcombine l2)).\nProof.\nintros l1 l2.\nunfold Qcombine.\nrewrite fold_right_app.\nset (f := fun qp a => _).\ngeneralize (fold_right f (0,0) l2); intros q.\ninduction l1;simpl;[split;simpl;ring|].\nunfold QQeq; simpl.\ndestruct IHl1 as [-> ->]; simpl.\nsplit;ring.\nQed.\n\nLemma Qcombine_scale : forall c l,\n  QQeq (QQscale c (Qcombine l)) (Qcombine (map (fun x => (c * fst x, snd x)) l)).\nProof.\nintros c l.\nunfold QQeq; simpl.\ninduction l;[split;simpl;ring|].\nsimpl.\ndestruct IHl as [<- <-].\nsplit;ring.\nQed.\n\nDefinition Deq (a b : D) : Prop := Dcompare a b = Eq.\nDefinition DDeq (a b : DD) : Prop := \n  Deq (fst a) (fst b) /\\ Deq (snd a) (snd b).\n\nLemma Deq_Q : forall x y, Deq x y <-> x == y.\nProof.\nintros x y.\nunfold Deq.\nrewrite Dcompare_Q.\nsymmetry.\napply Qeq_alt.\nQed.\n\nLemma DDeq_Q : forall p q : DD, DDeq p q -> QQeq p q.\nProof.\nintros [x1 y1] [x2 y2] [H1 H2].\nrewrite Deq_Q in *.\nsplit; simpl in *; congruence.\nQed.\n\nModule DD_as_OTF <: OrderedTypeFull := OT_to_Full DDOrder.\n\n(*Opaque point*)\nDefinition null : DD.\nexact (0:D,0:D)%Z.\nQed.\n\nDefinition DDreverse x y := DDOrder.lt y x.\n\nDefinition Qdet (p1 p2 p3 : QQ) := \nlet (x1, y1) := p1 in\nlet (x2, y2) := p2 in\nlet (x3, y3) := p3 in\n (x1 * y2 - y1 * x2) +\n (x2 * y3 - y2 * x3) +\n (x3 * y1 - y3 * x1).\n\nLemma Qdet_opp : forall p q r, - Qdet p q r == Qdet p r q.\nProof.\nintros [x1 y1] [x2 y2] [x3 y3].\nsimpl.\nring.\nQed.\n\nLemma orientation_det : forall p1 p2 p3,\norientation p1 p2 p3 = (Qdet p1 p2 p3 ?= 0).\nProof.\nintros [x1 y1] [x2 y2] [x3 y3].\nsimpl.\nautorewrite with DQ.\ndestruct Qcompare_spec with\n  (x1 * y2 - y1 * x2 + (x2 * y3 - y2 * x3) + (x3 * y1 - y3 * x1)) 0.\n* apply Qeq_alt.\n  apply Qplus_inj_r with (-((y1 - y3) * (x2 - x3))).\n  rewrite Qplus_opp_r.\n  rewrite <- H; ring.\n* apply -> Qlt_alt.\n  apply Qplus_lt_l with (-((y1 - y3) * (x2 - x3))).\n  rewrite Qplus_opp_r.\n  eapply Qlt_compat;[|reflexivity|apply H].\n  ring.\n* apply -> Qgt_alt.\n  apply <- Qlt_minus_iff.\n  eapply Qlt_compat;[reflexivity| |apply H].\n  ring.\nQed.\n\nLemma orientation_dup : forall p q, orientation p q q = Eq.\nProof.\nintros [x1 y1] [x2 y2].\nrewrite orientation_det, <- Qeq_alt.\nsimpl.\nring.\nQed.\n\nLemma orientation_rot : forall p q r,\n orientation p q r = orientation r p q.\nProof.\nintros [x1 y1] [x2 y2] [x3 y3].\nrewrite !orientation_det.\nsimpl.\nset (a := _ + _).\nset (b := _ + _).\nsetoid_replace a with b; [reflexivity|].\nunfold a, b.\nring.\nQed.\n\nLemma orientation_opp : forall p q r, CompOpp (orientation p q r) = orientation p r q.\nProof.\nintros p q r.\nrewrite !orientation_det.\nrewrite <- Qdet_opp.\ngeneralize (Qdet p r q).\nclear p q r.\nintros x.\nrewrite Qcompare_antisym.\ndestruct (Qcompare_spec x 0).\n* apply Qeq_alt.\n  rewrite H.\n  ring.\n* apply -> Qlt_alt.\n  setoid_replace (-x) with (0 + - x) by ring.\n  apply -> Qlt_minus_iff.\n  assumption.\n* apply -> Qgt_alt.\n  apply Qlt_minus_iff.\n  ring_simplify.\n  assumption.\nQed.\n\nAdd Morphism orientation with signature DDOrder.eq ==> DDOrder.eq ==> DDOrder.eq ==> eq as orientation_morph.\nintros [x1 y1] [x2 y2] [H12a H12b].\nintros [x3 y3] [x4 y4] [H34a H34b].\nintros [x5 y5] [x6 y6] [H56a H56b].\nrewrite !orientation_det; simpl.\napply Deq_Q in H12a,H12b,H34a,H34b,H56a,H56b.\nrewrite H12a,H12b,H34a,H34b,H56a,H56b.\nreflexivity.\nQed.\n\nLemma In_DDSet_fromList : forall l (p : DD),\n DDSet.In p (DDSet_fromList l) <->\n exists q : DD, DDeq p q /\\ In q l.\nProof.\nintros l p.\nunfold DDSet_fromList.\nrewrite <- fold_left_rev_right.\ntransitivity (exists q :DD, DDeq p q /\\ In q (rev l));\n [|split; intros [q Hq];exists q; assert (H0 := in_rev l q);firstorder].\nchange DDSet.elt with DD.\ninduction (rev l);[|split].\n* simpl; split; [|intros [q [Hq []]]].\n  intros H.\n  apply DDSet.empty_spec in H.\n  elim H.\n* intros Hp.\n  apply DDSet.add_spec in Hp.\n  destruct Hp as [Hp|Hp].\n  exists a;auto with *.\n  apply IHl0 in Hp.\n  destruct Hp as [q [Hpq Hp]].\n  exists q;auto with *.\n* intros [q [Hpq Hp]].\n  apply DDSet.add_spec.\n  destruct Hp as [->|Hp];[left;assumption|right].\n  apply IHl0.\n  exists q;tauto.\nQed.\n\nDefinition make_upper l :=\n  fold_right addUpperPoint nil l.\nDefinition make_lower l :=\n  fold_right addLowerPoint nil l.\n\nDefinition convexHull_alt : forall s,\n convexHull s =\n DDSet_fromList (make_upper (rev (DDSet.elements s))\n              ++ make_lower (rev (DDSet.elements s))).\nProof.\nintros s.\nunfold convexHull.\napply f_equal.\nrewrite !DDSet.fold_spec.\nrewrite <- !fold_left_rev_right.\nreflexivity.\nQed.\n\nLemma hd_addUpperPoint : forall a l, \n addUpperPoint a l = a :: tl (addUpperPoint a l).\nProof.\nintros a l.\ninduction l.\n reflexivity.\nsimpl.\ndestruct l as [|b l].\n* case (DDOrder.compare _ _); reflexivity.\n* case (orientation _ _ _); try reflexivity; apply IHl.\nQed.\n\nLemma hd_make_upper : forall l, hd null (make_upper l) = hd null l.\nProof.\nintros [|a l]; try reflexivity.\nsimpl.\nrewrite hd_addUpperPoint.\nreflexivity.\nQed.\n\nLemma hd_addLowerPoint : forall a l, \n  addLowerPoint a l = a :: tl (addLowerPoint a l).\nProof.\nintros a l.\ninduction l.\n reflexivity.\nsimpl.\ndestruct l as [|b l].\n* case (DDOrder.compare _ _); reflexivity.\n* case (orientation _ _ _); try reflexivity; apply IHl.\nQed.\n\nLemma hd_make_lower : forall l, hd null (make_lower l) = hd null l.\nProof.\nintros [|a l]; try reflexivity.\nsimpl.\nrewrite hd_addLowerPoint.\nreflexivity.\nQed.\n\nFixpoint addUpperPoint_ris (p : DD) (l : list DD) : list DD :=\nmatch l with\n| [] => []\n| q :: l0 => match l0 with\n   | [] => match DDOrder.compare p q with\n           | Eq => [q]\n           | _ => []\n           end\n   | r :: _ => match orientation p q r with\n                 | Gt => []\n                 | _ => q :: addUpperPoint_ris p l0\n               end\n   end\nend.\n\nFixpoint addLowerPoint_ris (p : DD) (l : list DD) : list DD :=\nmatch l with\n| [] => []\n| q :: l0 => match l0 with\n   | [] => match DDOrder.compare p q with\n           | Eq => [q]\n           | _ => []\n           end\n   | r :: _ => match orientation p q r with\n                 | Lt => []\n                 | _ => q :: addLowerPoint_ris p l0\n                 end\n   end\nend.\n\nLemma tl_addUpperPoint : forall a l, \n l = addUpperPoint_ris a l ++ tl (addUpperPoint a l).\nProof.\nintros a.\ninduction l; auto.\nsimpl.\ndestruct l as [|b l].\n* case (DDOrder.compare _ _); reflexivity.\n* case (orientation _ _ _); auto; cbn [app]; congruence.\nQed.\n\nLemma tl_addLowerPoint : forall a l, \n l = addLowerPoint_ris a l ++ tl (addLowerPoint a l).\nProof.\nintros a.\ninduction l; auto.\nsimpl.\ndestruct l as [|b l].\n* case (DDOrder.compare _ _); reflexivity.\n* case (orientation _ _ _); auto; cbn [app]; congruence.\nQed.\n\nLemma SSorted_app : forall A R (l1 l2 : list A),\n StronglySorted R (l1 ++ l2) ->\n StronglySorted R l1 /\\ StronglySorted R l2.\nProof.\nintros A R l1 l2.\ninduction l1; simpl; intros H.\n* split;auto;constructor.\n* inversion_clear H.\n  destruct (IHl1 H0) as [Hl1 Hl2].\n  split;try constructor;auto.\n  apply Forall_app in H1.\n  tauto.\nQed.\n\nLemma Sorted_rev : forall A R (l : list A),\n Sorted R l -> Sorted (fun x y => R y x) (rev l).\nProof.\nintros A R.\nset (R' := fun x y => _).\nassert (H : forall l l' a,\n Sorted R l -> Sorted R' l' -> HdRel R a l -> HdRel R' a l' ->\n Sorted R' (rev l ++ [a] ++ l')).\n intros l.\n induction l; try constructor;auto.\n intros l' a0 Hl Hl' Hal Hal'.\n simpl.\n rewrite <- app_assoc.\n apply IHl.\n inversion_clear Hl; auto.\n constructor; auto.\n inversion_clear Hl; auto.\n constructor; inversion_clear Hal; auto.\nintros [|a l] Hl; try constructor.\nsimpl.\ninversion_clear Hl.\napply H; try constructor; auto.\nQed.\n\nLemma incl_make_upper : forall l,\n incl (make_upper l) l.\nProof.\nintros l.\ninduction l; intros x Hx; auto.\nsimpl in *.\nrewrite hd_addUpperPoint in Hx.\ndestruct Hx as [<-| Hx];auto.\nright.\napply IHl.\nrewrite (tl_addUpperPoint a (make_upper l)).\napply in_or_app.\ntauto.\nQed.\n\nLemma incl_make_lower : forall l,\n incl (make_lower l) l.\nProof.\nintros l.\ninduction l; intros x Hx; auto.\nsimpl in *.\nrewrite hd_addLowerPoint in Hx.\ndestruct Hx as [<-| Hx];auto.\nright.\napply IHl.\nrewrite (tl_addLowerPoint a (make_lower l)).\napply in_or_app.\ntauto.\nQed.\n\nLemma SSorted_make_upper : forall R l,\n StronglySorted R l ->\n StronglySorted R (make_upper l).\nProof.\nintros R l.\ninduction l; auto.\nintros H.\ninversion_clear H.\nspecialize (IHl H0).\nsimpl.\nrewrite hd_addUpperPoint.\nrewrite (tl_addUpperPoint a) in IHl.\napply SSorted_app in IHl.\nconstructor;try tauto.\neapply incl_Forall;[|apply H1].\neapply incl_tran;[|apply incl_make_upper].\nrewrite (tl_addUpperPoint a).\nauto with *.\nQed.\n\nLemma SSorted_make_lower : forall R l,\n StronglySorted R l ->\n StronglySorted R (make_lower l).\nProof.\nintros R l.\ninduction l; auto.\nintros H.\ninversion_clear H.\nspecialize (IHl H0).\nsimpl.\nrewrite hd_addLowerPoint.\nrewrite (tl_addLowerPoint a) in IHl.\napply SSorted_app in IHl.\nconstructor;try tauto.\neapply incl_Forall;[|apply H1].\neapply incl_tran;[|apply incl_make_lower].\nrewrite (tl_addLowerPoint a).\nauto with *.\nQed.\n\nDefinition in_between p a b := \n exists c, 0 <= c <= 1 /\\ QQeq p (QQavg c a b).\n\nDefinition in_convex_hull (x : QQ) (s : DDSet.t) : Prop :=\nexists l : list (Q * DD),\n (forall q p, In (q, p) l -> 0 <= q /\\ DDSet.In p s) /\\\n Qsum (map fst l) == 1 /\\\n QQeq (Qcombine l) x.\n\nLemma in_convex_hull_Empty : forall {x}, ~in_convex_hull x DDSet.empty.\nProof.\nintros s [[|[q d]] [H0 [H1 [H2 H3]]]];[discriminate|].\ndestruct (H0 q d); auto with *.\nauto using (@DDSet.empty_spec d).\nQed.\n\nLemma in_convex_hull_morph1 : forall p1 p2 s,\n QQeq p1 p2 ->\n in_convex_hull p1 s ->\n in_convex_hull p2 s.\nProof.\nintros p1 p2 s [Hp1 Hp2] [l Hl].\nexists l.\nsplit; try tauto.\nsplit; try tauto.\nunfold QQeq.\nrewrite <- Hp1, <- Hp2.\nfold (QQeq (Qcombine l) p1).\ntauto.\nQed.\n\nLemma in_convex_hull_morph2 : forall p s1 s2,\n DDSet.eq s1 s2 ->\n in_convex_hull p s1 ->\n in_convex_hull p s2.\nProof.\nintros p s1 s2 Hs [l Hl].\nexists l.\nsplit; try tauto.\nintros a b H.\ndestruct Hl as [Hl _].\ndestruct (Hl a b H).\nsplit; try tauto.\napply Hs.\nassumption.\nQed.\n\nLemma in_in_convex_hull : forall (p:DD) s,\n DDSet.In p s -> in_convex_hull p s.\nProof.\nintros p s Hp.\nexists ((1,p)::nil);split;[|split].\n* intros q0 p0 [Hqp|[]].\n  injection Hqp; intros <- <-; clear Hqp.\n  split; auto with *.\n* reflexivity.\n* unfold QQeq in *.\n  simpl;split;ring.\nQed.\n\nLemma in_convex_hull_subset : forall q s1 s2,\n DDSet.Subset s1 s2 -> in_convex_hull q s1 ->\n in_convex_hull q s2.\nProof.\nintros q s1 s2 Hs [l H].\nunfold DDSet.Subset in Hs.\nexists l;split;[|split]; firstorder.\nQed.\n\nLemma in_convex_hull_singleton : forall q (p:DD),\n in_convex_hull q (DDSet.add p DDSet.empty) ->\n QQeq q p.\nProof.\nintros q p [l [H0 [H1 H2]]].\nunfold QQeq.\ndestruct H2 as [<- <-].\nsetoid_replace (fst p:Q) with (1*(fst p)) by ring.\nsetoid_replace (snd p:Q) with (1*(snd p)) by ring.\nrewrite <- H1; clear H1.\ninduction l;simpl;[split;ring|].\ndestruct IHl as [-> ->]; auto with *.\nspecialize (H0 (fst a) (snd a) (or_introl (surjective_pairing a))).\ndestruct H0 as [_ H0].\napply DDSet.add_spec in H0.\ndestruct H0 as [[H0 H1]|H0];\n [apply Deq_Q in H0, H1; rewrite H0, H1; split; ring|].\napply DDSet.mem_spec in H0.\ndiscriminate.\nQed.\n\nLemma QQavg_in_convex_hull : forall c p1 p2 s,\n  0 <= c <= 1 ->\n  in_convex_hull p1 s ->\n  in_convex_hull p2 s ->\n  in_convex_hull (QQavg c p1 p2) s.\nProof.\nintros c p1 p2 s Hc [l1 Hp1] [l2 Hp2].\npose (f := fun c (x : Q * DD) => (c * fst x, snd x)).\npose (l1' := map (f c) l1).\npose (l2' := map (f (1-c)) l2).\nexists (l1' ++ l2').\nsplit;[|split].\nassert (Hc' : 0 <= 1 - c) by\n (apply -> Qle_minus_iff; tauto).\n* intros q p Hqp.\n  apply in_app_or in Hqp.\n  destruct Hp1 as [Hp1 _].\n  destruct Hp2 as [Hp2 _].\n  destruct Hqp as [Hqp|Hqp];split;\n    apply in_map_iff in Hqp;\n    destruct Hqp as [[x y] [Hx1 Hx2]];\n    injection Hx1; intros <- <-;\n    try apply Qmult_le_0_compat; firstorder.\n* destruct Hp1 as [_ [Hp1 _]].\n  destruct Hp2 as [_ [Hp2 _]].\n  rewrite map_app.\n  unfold l1', l2'.\n  rewrite !map_map.\n  change (fun x => fst (f c x)) with (fun x : Q * DD => c * fst x).\n  change (fun x => fst (f (1 - c) x)) with (fun x : Q * DD => (1 - c) * fst x).\n  rewrite <- (map_map _ (Qmult (1-c))), <- map_map.\n  rewrite Qsum_app, !Qsum_mult, Hp1, Hp2.\n  ring.\n* unfold QQeq; simpl.\n  destruct Hp1 as [_ [_ [<- <-]]].\n  destruct Hp2 as [_ [_ [<- <-]]].\n  destruct (Qcombine_app l1' l2') as [-> ->].\n  simpl.\n  destruct (Qcombine_scale c l1) as [-> ->].\n  destruct (Qcombine_scale (1-c) l2) as [-> ->].\n  fold (f c) (f (1-c)) l1' l2'.\n  split; ring.\nQed.\n\nInductive OnPath (p : QQ) : list DD -> Prop :=\n| OnPathTl : forall a l, OnPath p l -> OnPath p (a::l)\n| OnPathBetween : forall (a b : DD) l, in_between p (a:QQ) (b:QQ) -> OnPath p (a::b::l).\n\nLemma incl_DDSet_fromList : forall l1 l2,\n incl l1 l2 ->\n DDSet.Subset (DDSet_fromList l1) (DDSet_fromList l2).\nProof.\nintros p l1 l2 H Hq.\nrewrite In_DDSet_fromList in *.\ndestruct Hq as [r [Hqr Hr]].\nexists r;split;auto with *.\nQed.\n\nLemma OnPathConvex : forall p l,\n  OnPath p l -> in_convex_hull p (DDSet_fromList l).\nProof.\nintros p l H.\ninduction H.\n* eapply in_convex_hull_subset;[|apply IHOnPath].\n  apply incl_DDSet_fromList.\n  auto with *.\n* destruct H as [c [Hc Hp]].\n  exists [(c,a);((1-c),b)];split;[intros q r [Hqr|[Hqr|[]]];injection Hqr; intros <- <-; clear Hqr|split].\n  + split; try tauto.\n    rewrite In_DDSet_fromList.\n    exists a;repeat split;auto with *.\n  + split;[apply -> Qle_minus_iff;tauto|].\n    rewrite In_DDSet_fromList.\n    exists b;repeat split;auto with *.\n  + simpl;ring.\n  + unfold QQeq;destruct Hp as [-> ->].\n    simpl;split;ring.\nQed.\n\nDefinition under p l := exists q, OnPath q l /\\ fst p == fst q /\\ snd p <= snd q.\n\nLemma in_under : forall (p : DD) (l : list DD),\n In p l -> under (p:QQ) l \\/ l = [p].\nProof.\nintros p l.\ninduction l;try contradiction.\nintros [->|H].\n* destruct l;[right;reflexivity|].\n  left.\n  exists p; repeat split; auto with *.\n  apply OnPathBetween.\n  exists 1; repeat split;auto with *;simpl;ring.\n* left.\n  specialize (IHl H).\n  destruct IHl as [[q H0]| ->].\n   exists q;split;[apply OnPathTl|]; tauto.\n  exists p; repeat split; auto with *.\n  apply OnPathBetween.\n  exists 0; repeat split;auto with *;simpl;ring.\nQed.\n\nLemma DDorder_fst : forall a b, DDOrder.lt a b -> fst a <= fst b.\nProof.\nintros a b H.\nrewrite Qle_lteq.\ndestruct H as [H|[H _]];[left|right].\n* rewrite Qlt_alt, <- Dcompare_Q; auto.\n* rewrite Qeq_alt, <- Dcompare_Q; auto.\nQed.\n\nLemma DDorder_snd : forall a b, DDOrder.lt a b -> fst a == fst b -> snd a < snd b.\nProof.\nintros a b H H0.\ndestruct H as [H|[H H']].\n* change (Dcompare (fst a) (fst b) = Lt) in H.\n  rewrite Dcompare_Q, <- Qlt_alt in H.\n  apply Qlt_not_eq in H.\n  contradiction.\n* rewrite Qlt_alt, <- Dcompare_Q; auto.\nQed.\n\nLemma under_addUpperPoint : forall p a l,\n StronglySorted DDreverse (a :: l) ->\n under p (a::l) -> under p (addUpperPoint a l).\nProof.\nintros p a l.\ninduction l.\n* intros Hsort [q [HPath [Hpq1 Hpq2]]].\n  inversion_clear HPath;inversion H.\n* rename a0 into b.\n  intros Hsort H.\n  simpl.\n  destruct l as [|c l].\n   simpl.\n   destruct (DDOrder.compare_spec a b); auto.\n   inversion_clear Hsort.\n   inversion_clear H2.\n   change (DDOrder.lt b a) in H3.\n   rewrite H0 in H3.\n   destruct DDOrder.lt_strorder.\n   elim (StrictOrder_Irreflexive b H3).\n  compare (orientation a b c) Gt;[intros ->; auto|].\n   intros Horient.\n   cut (under p (addUpperPoint a (c :: l))).\n    intros;case (orientation a b c);try contradiction; auto.\n   apply IHl.\n    inversion_clear Hsort.\n    inversion_clear H0.\n    inversion_clear H1.\n    constructor; auto.\n   destruct H as [q [HPath [Hpq1 Hpq2]]].\n     cut (under q (a :: c :: l)).\n     intros [r [Hr [Heq1 Heq2]]].\n     exists r;repeat split;auto;eauto with *.\n    clear Hpq1 Hpq2 p IHl.\n    change DD in a,b,c.\n    assert (Hb : under (b:QQ) [a;c]).\n     inversion_clear Hsort.\n     inversion_clear H0.\n     inversion_clear H2.\n     clear H3.\n     inversion_clear H.\n     clear H2.\n     inversion_clear H3.\n     clear H2. \n     assert (Hac : fst c <= fst a).\n      apply DDorder_fst.\n      assumption.\n     rewrite Qle_lteq in Hac.\n     destruct Hac as [Hac|Hac].\n     + rewrite Qlt_minus_iff in Hac.\n       pose (d := ((fst b - fst c)/(fst a - fst c))).\n       assert (Hd0 : 0 <= d).\n        apply Qle_shift_div_l; auto.\n        ring_simplify (0 * (fst a - fst c)).\n        apply -> Qle_minus_iff.\n        auto using DDorder_fst.\n       assert (Hd1 : d <= 1).\n        apply Qle_shift_div_r; auto.\n        ring_simplify (1 * (fst a - fst c)).\n        apply Qle_minus_iff.\n        ring_simplify.\n        apply -> Qle_minus_iff.\n        auto using DDorder_fst.\n       exists (QQavg d (a:QQ) (c:QQ)).\n       simpl; repeat split.\n         apply OnPathBetween.\n         exists d;repeat split;auto.\n        unfold d;field;auto with *.\n       rewrite orientation_rot in Horient.\n       destruct a as [a1 a2]; destruct b as [b1 b2]; destruct c as [c1 c2].\n       unfold orientation in Horient.\n       autorewrite with DQ in Horient.\n       rewrite <- Qle_alt in Horient.\n       simpl in *.\n       setoid_replace (d * a2 + (1 - d) * c2) with (((b1 - c1)*a2 + (a1 - b1)*c2)/(a1 - c1)) \n         by (unfold d;field;auto with *).\n       apply Qle_shift_div_l; auto with *.\n       rewrite Qle_minus_iff in *.\n       eapply Qle_trans;[apply Horient|].\n       rewrite Qle_minus_iff.\n       ring_simplify.\n       auto with *.\n     + exists a.\n       split.\n        apply OnPathBetween.\n        exists 1;repeat split;simpl;auto with *; ring.\n       assert (Hab : fst b == fst a).\n        apply Qle_antisym.\n         apply DDorder_fst; auto.\n        rewrite <- Hac.\n        apply DDorder_fst; auto.\n       split;auto.\n       apply Qlt_le_weak.\n       apply DDorder_snd; auto.\n  + destruct Hb as [r [Hr [Hr1 Hr2]]].\n    inversion_clear Hr;[inversion_clear H; inversion_clear H0|].\n    inversion_clear HPath;[inversion_clear H0|].\n    - exists q;split;auto with *.\n      apply OnPathTl; assumption.\n    - destruct H as [x [Hx Hr]].\n      destruct H1 as [y [Hy Hq]].\n      exists (QQavg y (r:QQ) (c:QQ)); split;simpl.\n        apply OnPathBetween.\n        destruct Hx as [Hx0 Hx1].\n        destruct Hy as [Hy0 Hy1].\n        exists (x*y).\n        unfold QQeq; simpl.\n        destruct Hr as [-> ->]; simpl.\n        repeat split; try ring; auto using Qmult_le_0_compat.\n        rewrite Qle_lteq in Hx0.\n        destruct Hx0 as [Hx0|<-];[|ring_simplify;auto with *].\n        rewrite <- (Qmult_le_l _ _ x) in Hy1 by assumption.\n        ring_simplify in Hy1.\n        eauto with *.\n       destruct Hq as [-> ->]; simpl.\n       split;[rewrite Hr1;ring|].\n       rewrite Qle_minus_iff in Hr2|-*.\n       ring_simplify.\n       setoid_replace (y * snd r + -1 * y * snd b) with (y * (snd r + - snd b)) by ring.\n       destruct Hy;apply Qmult_le_0_compat; auto with *.\n    - destruct H as [x [Hx Hr]].\n      destruct H0 as [y [Hy Hq]].\n      exists (QQavg y (a:QQ) (r:QQ)); split;simpl.\n        apply OnPathBetween.\n        destruct Hx as [Hx0 Hx1].\n        destruct Hy as [Hy0 Hy1].\n        exists (x + y*(1 - x)).\n        unfold QQeq; simpl.\n        destruct Hr as [-> ->]; simpl.\n        repeat split; try ring.\n         change 0 with (0 + 0).\n         apply Qplus_le_compat; auto.\n         apply Qmult_le_0_compat; auto.\n         rewrite Qle_minus_iff in Hx1; auto.\n        rewrite Qle_minus_iff.\n        setoid_replace (1 + - (x + y * (1 - x))) with ((1 - x)*(1 - y)) by ring.\n        rewrite Qle_minus_iff in Hx1, Hy1.\n        apply Qmult_le_0_compat; auto.\n       destruct Hq as [-> ->]; simpl.\n       split;[rewrite Hr1;ring|].\n       rewrite Qle_minus_iff in Hr2|-*.\n       ring_simplify.\n       setoid_replace (-1 * y * snd r + y * snd b + snd r + -1 * snd b) with ((1-y) * (snd r + - snd b)) by ring.\n       destruct Hy as [Hy0 Hy1].\n       rewrite Qle_minus_iff in Hy1.\n       apply Qmult_le_0_compat; auto with *.\nQed.\n\nLemma under_make_upper : forall (p:DD) l,\n StronglySorted DDreverse l ->\n In p l ->\n under (p:QQ) (make_upper l) \\/ l = [p].\nProof.\nintros p.\ninduction l; try contradiction.\nintros Hsort H.\nsimpl.\ndestruct l as [|b l].\n destruct H as [->|[]].\n right;reflexivity.\nleft.\napply under_addUpperPoint.\n inversion_clear Hsort.\n constructor; auto using SSorted_make_upper.\n eapply incl_Forall;[|apply H1].\n apply incl_make_upper.\ndestruct l as [|c l].\n simpl.\n apply in_under in H.\n destruct H;auto;discriminate.\ndestruct H as [->|H].\n assert (H0 : In p (p :: make_upper (b :: c :: l))) by auto with *.\n apply in_under in H0.\n destruct H0 as [H0|H0];auto.\n simpl in H0.\n rewrite hd_addUpperPoint in H0.\n discriminate.\ninversion_clear Hsort.\nspecialize (IHl H0 H).\ndestruct IHl as [[q Hq]|IHl];try discriminate.\nexists q;split;[apply OnPathTl|]; tauto.\nQed.\n\nDefinition over p l := exists q, OnPath q l /\\ fst p == fst q /\\ snd q <= snd p.\n\nLemma in_over : forall (p : DD) (l : list DD),\n In p l -> over (p:QQ) l \\/ l = [p].\nProof.\nintros p l.\ninduction l;try contradiction.\nintros [->|H].\n* destruct l;[right;reflexivity|].\n  left.\n  exists p; repeat split; auto with *.\n  apply OnPathBetween.\n  exists 1; repeat split;auto with *;simpl;ring.\n* left.\n  specialize (IHl H).\n  destruct IHl as [[q H0]| ->].\n   exists q;split;[apply OnPathTl|]; tauto.\n  exists p; repeat split; auto with *.\n  apply OnPathBetween.\n  exists 0; repeat split;auto with *;simpl;ring.\nQed.\n\nLemma over_addLowerPoint : forall p a l,\n StronglySorted DDreverse (a :: l) ->\n over p (a::l) -> over p (addLowerPoint a l).\nProof.\nintros p a l.\ninduction l.\n* intros Hsort [q [HPath [Hpq1 Hpq2]]].\n  inversion_clear HPath;inversion H.\n* rename a0 into b.\n  intros Hsort H.\n  simpl.\n  destruct l as [|c l].\n   simpl.\n   destruct (DDOrder.compare_spec a b); auto.\n   inversion_clear Hsort.\n   inversion_clear H2.\n   change (DDOrder.lt b a) in H3.\n   rewrite H0 in H3.\n   destruct DDOrder.lt_strorder.\n   elim (StrictOrder_Irreflexive b H3).\n  compare (orientation a b c) Lt;[intros ->; auto|].\n   intros Horient.\n   cut (over p (addLowerPoint a (c :: l))).\n    intros;case (orientation a b c);try contradiction; auto.\n   apply IHl.\n    inversion_clear Hsort.\n    inversion_clear H0.\n    inversion_clear H1.\n    constructor; auto.\n   destruct H as [q [HPath [Hpq1 Hpq2]]].\n     cut (over q (a :: c :: l)).\n     intros [r [Hr [Heq1 Heq2]]].\n     exists r;repeat split;auto;eauto with *.\n    clear Hpq1 Hpq2 p IHl.\n    change DD in a,b,c.\n    assert (Hb : over (b:QQ) [a;c]).\n     inversion_clear Hsort.\n     inversion_clear H0.\n     inversion_clear H2.\n     clear H3.\n     inversion_clear H.\n     clear H2.\n     inversion_clear H3.\n     clear H2. \n     assert (Hac : fst c <= fst a).\n      apply DDorder_fst.\n      assumption.\n     rewrite Qle_lteq in Hac.\n     destruct Hac as [Hac|Hac].\n     + rewrite Qlt_minus_iff in Hac.\n       pose (d := ((fst b - fst c)/(fst a - fst c))).\n       assert (Hd0 : 0 <= d).\n        apply Qle_shift_div_l; auto.\n        ring_simplify (0 * (fst a - fst c)).\n        apply -> Qle_minus_iff.\n        auto using DDorder_fst.\n       assert (Hd1 : d <= 1).\n        apply Qle_shift_div_r; auto.\n        ring_simplify (1 * (fst a - fst c)).\n        apply Qle_minus_iff.\n        ring_simplify.\n        apply -> Qle_minus_iff.\n        auto using DDorder_fst.\n       exists (QQavg d (a:QQ) (c:QQ)).\n       simpl; repeat split.\n         apply OnPathBetween.\n         exists d;repeat split;auto.\n        unfold d;field;auto with *.\n       rewrite orientation_rot in Horient.\n       destruct a as [a1 a2]; destruct b as [b1 b2]; destruct c as [c1 c2].\n       unfold orientation in Horient.\n       autorewrite with DQ in Horient.\n       rewrite <- Qge_alt in Horient.\n       simpl in *.\n       setoid_replace (d * a2 + (1 - d) * c2) with (((b1 - c1)*a2 + (a1 - b1)*c2)/(a1 - c1)) \n         by (unfold d;field;auto with *).\n       apply Qle_shift_div_r; auto with *.\n       rewrite Qle_minus_iff in *.\n       eapply Qle_trans;[apply Horient|].\n       rewrite Qle_minus_iff.\n       ring_simplify.\n       auto with *.\n     + exists c.\n       split.\n        apply OnPathBetween.\n        exists 0;repeat split;simpl;auto with *; ring.\n       assert (Hab : fst c == fst b).\n        apply Qle_antisym.\n         apply DDorder_fst; auto.\n        rewrite Hac.\n        apply DDorder_fst; auto.\n       split;auto with *.\n       apply Qlt_le_weak.\n       apply DDorder_snd; auto.\n  + destruct Hb as [r [Hr [Hr1 Hr2]]].\n    inversion_clear Hr;[inversion_clear H; inversion_clear H0|].\n    inversion_clear HPath;[inversion_clear H0|].\n    - exists q;split;auto with *.\n      apply OnPathTl; assumption.\n    - destruct H as [x [Hx Hr]].\n      destruct H1 as [y [Hy Hq]].\n      exists (QQavg y (r:QQ) (c:QQ)); split;simpl.\n        apply OnPathBetween.\n        destruct Hx as [Hx0 Hx1].\n        destruct Hy as [Hy0 Hy1].\n        exists (x*y).\n        unfold QQeq; simpl.\n        destruct Hr as [-> ->]; simpl.\n        repeat split; try ring; auto using Qmult_le_0_compat.\n        rewrite Qle_lteq in Hx0.\n        destruct Hx0 as [Hx0|<-];[|ring_simplify;auto with *].\n        rewrite <- (Qmult_le_l _ _ x) in Hy1 by assumption.\n        ring_simplify in Hy1.\n        eauto with *.\n       destruct Hq as [-> ->]; simpl.\n       split;[rewrite Hr1;ring|].\n       rewrite Qle_minus_iff in Hr2|-*.\n       ring_simplify.\n       setoid_replace (y * snd b + -1 * y * snd r) with (y * (snd b + - snd r)) by ring.\n       destruct Hy;apply Qmult_le_0_compat; auto with *.\n    - destruct H as [x [Hx Hr]].\n      destruct H0 as [y [Hy Hq]].\n      exists (QQavg y (a:QQ) (r:QQ)); split;simpl.\n        apply OnPathBetween.\n        destruct Hx as [Hx0 Hx1].\n        destruct Hy as [Hy0 Hy1].\n        exists (x + y*(1 - x)).\n        unfold QQeq; simpl.\n        destruct Hr as [-> ->]; simpl.\n        repeat split; try ring.\n         change 0 with (0 + 0).\n         apply Qplus_le_compat; auto.\n         apply Qmult_le_0_compat; auto.\n         rewrite Qle_minus_iff in Hx1; auto.\n        rewrite Qle_minus_iff.\n        setoid_replace (1 + - (x + y * (1 - x))) with ((1 - x)*(1 - y)) by ring.\n        rewrite Qle_minus_iff in Hx1, Hy1.\n        apply Qmult_le_0_compat; auto.\n       destruct Hq as [-> ->]; simpl.\n       split;[rewrite Hr1;ring|].\n       rewrite Qle_minus_iff in Hr2|-*.\n       ring_simplify.\n       setoid_replace (-1 * y * snd b + y * snd r + snd b + -1 * snd r) with \n         ((1-y) * (snd b + - snd r)) by ring.\n       destruct Hy as [Hy0 Hy1].\n       rewrite Qle_minus_iff in Hy1.\n       apply Qmult_le_0_compat; auto with *.\nQed.\n\nLemma over_make_lower : forall (p:DD) l,\n StronglySorted DDreverse l ->\n In p l ->\n over (p:QQ) (make_lower l) \\/ l = [p].\nProof.\nintros p.\ninduction l; try contradiction.\nintros Hsort H.\nsimpl.\ndestruct l as [|b l].\n destruct H as [->|[]].\n right;reflexivity.\nleft.\napply over_addLowerPoint.\n inversion_clear Hsort.\n constructor; auto using SSorted_make_lower.\n eapply incl_Forall;[|apply H1].\n apply incl_make_lower.\ndestruct l as [|c l].\n simpl.\n apply in_over in H.\n destruct H;auto;discriminate.\ndestruct H as [->|H].\n assert (H0 : In p (p :: make_lower (b :: c :: l))) by auto with *.\n apply in_over in H0.\n destruct H0 as [H0|H0];auto.\n simpl in H0.\n rewrite hd_addLowerPoint in H0.\n discriminate.\ninversion_clear Hsort.\nspecialize (IHl H0 H).\ndestruct IHl as [[q Hq]|IHl];try discriminate.\nexists q;split;[apply OnPathTl|]; tauto.\nQed.\n\nLemma over_under : forall p l1 l2,\n under p l1 ->\n over p l2 ->\n in_convex_hull p (DDSet_fromList (l1 ++ l2)).\nProof.\nintros p l1 l2 [p1 [Hl1 [Hp11 Hp12]]] [p2 [Hl2 [Hp21 Hp22]]].\napply OnPathConvex in Hl1.\napply OnPathConvex in Hl2.\npose (c := (snd p - snd p2)/(snd p1 - snd p2)).\nassert (Hp0 := Qle_trans _ _ _ Hp22 Hp12).\napply Qle_lt_or_eq in Hp0.\nassert (Hp : QQeq (QQavg c p1 p2) p).\n unfold QQeq; simpl.\n rewrite <- Hp11, <- Hp21.\n split;[ring|].\n destruct Hp0 as [Hp0|Hp0].\n  rewrite Qlt_minus_iff in Hp0.\n  unfold c; field; auto with *.\n unfold c; simpl.\n rewrite Hp0; ring_simplify.\n apply Qle_antisym; auto.\n rewrite <- Hp0.\n auto.\neapply in_convex_hull_morph1;[apply Hp|].\napply QQavg_in_convex_hull.\n* destruct Hp0 as [Hp0|Hp0].\n   rewrite Qlt_minus_iff in Hp0.\n   unfold c;split.\n    apply Qle_shift_div_l; auto.\n    ring_simplify (0 * (snd p1 - snd p2)).\n    apply -> Qle_minus_iff; auto.\n   apply Qle_shift_div_r; auto.\n   rewrite Qle_minus_iff in * .\n   ring_simplify.\n   assumption.\n  unfold c.\n  rewrite Hp0.\n  setoid_replace (snd p1 - snd p1) with 0 by ring.\n  unfold Qdiv.\n  change (/0) with 0.\n  split;ring_simplify; auto with *.\n* eapply in_convex_hull_subset;[|apply Hl1].\n  apply incl_DDSet_fromList; auto with *.\n* eapply in_convex_hull_subset;[|apply Hl2].\n  apply incl_DDSet_fromList; auto with *.\nQed.\n\nLemma convexHull_sound : forall s (p : DD), DDSet.In p s ->\n  in_convex_hull p (convexHull s).\nProof.\nintros s p H.\napply DDSet.elements_spec1 in H.\napply SetoidList.InA_rev in H.\napply SetoidList.InA_alt in H.\ndestruct H as [p0 [Hp H]].\nsymmetry in Hp.\nchange DD in p0.\ndestruct Hp as [Hp0 Hp1].\napply Deq_Q in Hp0,Hp1.\napply in_convex_hull_morph1 with (p0:QQ);[split;auto|].\nclear -H.\nrename p0 into p.\nrewrite convexHull_alt.\nassert (HSorted0 := DDSet.elements_spec2 s).\nchange (Sorted (DDOrder.lt) (DDSet.elements s)) in HSorted0.\nassert (HSorted1 := Sorted_rev _ _ _ HSorted0).\nset (l := (rev _)) in *.\nset (l1 := make_upper _).\nset (l2 := make_lower _).\nchange (Sorted DDreverse l) in HSorted1.\nclear HSorted0.\ndestruct l as [|a [|b l]]; try contradiction.\n apply in_in_convex_hull.\n destruct H as [->|[]].\n simpl.\n apply In_DDSet_fromList.\n exists p;split;auto with *.\n change (DDOrder.eq p p).\n reflexivity.\nset (l0 := a :: b :: l) in *.\napply Sorted_StronglySorted in HSorted1;\n[|intros x y z Hx Hy;unfold DDreverse in *;simpl;transitivity y;auto].\nassert (Hunder := under_make_upper p l0 HSorted1 H).\nassert (Hover := over_make_lower p l0 HSorted1 H).\ndestruct Hunder as [Hunder|Hunder];try discriminate.\ndestruct Hover as [Hover|Hover];try discriminate.\napply over_under; auto.\nQed.\n", "meta": {"author": "sipa", "repo": "safegcd-bounds", "sha": "afab8eda5b7e526b0069c4b132609e9fd09404bf", "save_path": "github-repos/coq/sipa-safegcd-bounds", "path": "github-repos/coq/sipa-safegcd-bounds/safegcd-bounds-afab8eda5b7e526b0069c4b132609e9fd09404bf/coq/hddivsteps/hddivsteps_convexhull.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.6904758794508348}}
{"text": "(* --------------------------------------------------------------------\n * Copyright (c) - 2006--2012 - IMDEA Software Institute\n * Copyright (c) - 2006--2012 - Inria\n * Copyright (c) - 2006--2012 - Microsoft Coprporation\n *\n * Distributed under the terms of the CeCILL-B-V1 license\n * -------------------------------------------------------------------- *)\n\n\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(**********************************************************************\n    PGroup.v                        \n                                                                     \n    Build the group of pairs modulo needed for the theorem of\n      lucas lehmer\n                                                                 \n    Definition: PGroup              \n **********************************************************************)\nRequire Import ZArith.\nRequire Import ZAux.\nRequire Import Tactic.\nRequire Import Wf_nat.\nRequire Import ListAux.\nRequire Import UList.\nRequire Import FGroup.\nRequire Import EGroup.\nRequire Import IGroup.\n\nOpen Scope Z_scope.\n\nDefinition base := 3.\n\n\n(************************************** \n  Equality is decidable on pairs\n **************************************)\n\nDefinition P_dec: forall p q: Z * Z, {p = q} + {p <> q}.\nintros p1 q1; case p1; case q1; intros z t x y; case (Z_eq_dec x z); intros H1.\ncase (Z_eq_dec y t); intros H2.\nleft; eq_tac; auto.\nright; contradict H2; injection H2; auto.\nright; contradict H1; injection H1; auto.\nDefined.\n\n\n(************************************** \n  Addition of two pairs\n **************************************)\n\nDefinition pplus (p q: Z * Z) := let (x ,y) := p in let (z,t) := q in (x + z, y + t).\n\n(************************************** \n  Properties of addition\n **************************************)\n\nTheorem pplus_assoc: forall p q r, (pplus p (pplus q r)) = (pplus (pplus p q) r).\nintros p q r; case p; case q; case r; intros r1 r2 q1 q2 p1 p2; unfold pplus.\neq_tac; ring.\nQed.\n\nTheorem pplus_comm: forall p q, (pplus p q) = (pplus q p).\nintros p q; case p; case q; intros q1 q2 p1 p2; unfold pplus.\neq_tac; ring.\nQed.\n\n(************************************** \n  Multiplication of two pairs\n **************************************)\n\nDefinition pmult (p q: Z * Z) := let (x ,y) := p in let (z,t) := q in (x * z + base * y * t, x * t + y * z).\n\n(************************************** \n  Properties of multiplication\n **************************************)\n\nTheorem pmult_assoc: forall p q r, (pmult p (pmult q r)) = (pmult (pmult p q) r).\nintros p q r; case p; case q; case r; intros r1 r2 q1 q2 p1 p2; unfold pmult.\neq_tac; ring.\nQed.\n\nTheorem pmult_0_l: forall p, (pmult (0, 0) p) = (0, 0).\nintros p; case p; intros x y; unfold pmult; eq_tac; ring.\nQed.\n\nTheorem pmult_0_r: forall p, (pmult p (0, 0)) = (0, 0).\nintros p; case p; intros x y; unfold pmult; eq_tac; ring.\nQed.\n\nTheorem pmult_1_l: forall p, (pmult (1, 0) p) = p.\nintros p; case p; intros x y; unfold pmult; eq_tac; ring.\nQed.\n\nTheorem pmult_1_r: forall p, (pmult p (1, 0)) = p.\nintros p; case p; intros x y; unfold pmult; eq_tac; ring.\nQed.\n\nTheorem pmult_comm: forall p q, (pmult p q) = (pmult q p).\nintros p q; case p; case q; intros q1 q2 p1 p2; unfold pmult.\neq_tac; ring.\nQed.\n\nTheorem pplus_pmult_dist_l: forall p q r, (pmult p (pplus q r)) = (pplus (pmult p q) (pmult p r)).\nintros p q r; case p; case q; case r; intros r1 r2 q1 q2 p1 p2; unfold pplus, pmult.\neq_tac; ring.\nQed.\n\n\nTheorem pplus_pmult_dist_r: forall p q r, (pmult (pplus q r) p) = (pplus (pmult q p) (pmult r p)).\nintros p q r; case p; case q; case r; intros r1 r2 q1 q2 p1 p2; unfold pplus, pmult.\neq_tac; ring.\nQed.\n\n(************************************** \n  In this section we create the group PGroup of inversible elements {(p, q) | 0 <= p < m /\\ 0 <= q < m}\n **************************************)\nSection Mod.\n\nVariable m : Z.\n\nHypothesis m_pos: 1 < m.\n\n(************************************** \n  mkLine creates {(a, p) | 0 <= p < n}\n **************************************)\n\nFixpoint mkLine (a: Z) (n: nat) {struct n} : list (Z * Z) :=\n  (a, Z_of_nat n) :: match n with O => nil | (S n1) => mkLine a n1 end. \n\n(************************************** \n  Some properties of mkLine\n **************************************)\n\nTheorem mkLine_length: forall a n, length (mkLine a n) = (n + 1)%nat.\nintros a n; elim n; simpl; auto.\nQed.\n\nTheorem mkLine_in: forall a n p, 0 <= p <= Z_of_nat n -> (In (a, p) (mkLine a n)).\nintros a n; elim n.\nsimpl; auto with zarith.\nintros p (H1, H2); replace p with 0; auto with zarith.\nintros n1 Rec p (H1, H2).\ncase (Zle_lt_or_eq p  (Z_of_nat (S n1))); auto with zarith.\nrewrite inj_S in H2; auto with zarith.\nrewrite inj_S; auto with zarith.\nintros H3; right; apply Rec; auto with zarith.\nintros H3; subst; simpl; auto.\nQed.\n\nTheorem in_mkLine: forall a n p, In p (mkLine  a n) ->  exists  q, 0 <= q <= Z_of_nat n  /\\ p = (a, q).\nintros a n p; elim n; clear n.\nsimpl; intros [H1 | H1]; exists 0; auto with zarith; case H1.\nsimpl; intros n Rec [H1 | H1]; auto.\nexists (Z_of_nat (S n)); auto with zarith.\ncase Rec; auto; intros q ((H2, H3), H4); exists q; repeat split; auto with zarith.\nchange (q <= Z_of_nat (S n)).\nrewrite inj_S; auto with zarith.\nQed.\n\nTheorem mkLine_ulist: forall a n, ulist (mkLine a n).\nintros a n; elim n; simpl; auto.\nintros n1 H; apply ulist_cons; auto.\nchange (~ In (a, Z_of_nat (S n1)) (mkLine a n1)).\nrewrite inj_S; intros H1.\ncase in_mkLine with (1 := H1); auto with zarith.\nintros x ((H2, H3), H4); injection H4.\nintros H5; subst; auto with zarith.\nQed.\n\n(************************************** \n  mkRect creates the list  {(p, q) | 0 <= p < n /\\ 0 <= q < m}\n **************************************)\n\nFixpoint mkRect (n m: nat) {struct n} : list (Z * Z) :=\n  (mkLine (Z_of_nat n) m) ++ match n with O => nil | (S n1) => mkRect n1 m end. \n\n(************************************** \n  Some properties of mkRect\n **************************************)\n\nTheorem mkRect_length: forall n m, length (mkRect n m) = ((n + 1) * (m + 1))%nat.\nintros n; elim n; simpl; auto.\nintros n1; rewrite <- app_nil_end; rewrite mkLine_length; rewrite plus_0_r; auto.\nintros n1 Rec m1; rewrite length_app; rewrite Rec; rewrite mkLine_length; auto.\nQed.\n\nTheorem mkRect_in: forall n m p q, 0 <= p <= Z_of_nat n -> 0 <= q <= Z_of_nat m -> (In (p, q) (mkRect n m)).\nintros n m1; elim n; simpl.\nintros p  q  (H1, H2) (H3, H4); replace p with 0; auto with zarith.\nrewrite <- app_nil_end; apply mkLine_in; auto.\nintros n1 Rec p q (H1, H2) (H3, H4).\ncase (Zle_lt_or_eq p  (Z_of_nat (S n1))); auto with zarith; intros H5.\nrewrite inj_S in H5; apply in_or_app; auto with zarith.\napply in_or_app; left; subst; apply mkLine_in; auto with zarith.\nQed.\n\nTheorem in_mkRect: forall n m p, In p (mkRect n  m) ->  exists p1, exists  p2, 0 <= p1 <= Z_of_nat n  /\\ 0 <= p2 <= Z_of_nat m  /\\ p = (p1, p2).\nintros n m1 p; elim n; clear n; simpl.\nrewrite <- app_nil_end; intros H1.\ncase in_mkLine with (1 := H1).\nintros p2 (H2, H3); exists 0; exists p2; auto with zarith.\nintros n Rec H1.\ncase in_app_or with (1 := H1); intros H2.\ncase in_mkLine with (1 := H2).\nintros p2 (H3, H4); exists (Z_of_nat (S n)); exists p2; subst; simpl; auto with zarith.\ncase Rec with (1 := H2); auto.\nintros p1 (p2, (H3, (H4, H5))); exists p1; exists p2; repeat split; auto with zarith.\nchange (p1 <= Z_of_nat (S n)).\nrewrite inj_S; auto with zarith.\nQed.\n\nTheorem mkRect_ulist: forall n m, ulist (mkRect n m).\nintros n; elim n; simpl; auto.\nintros n1; rewrite <- app_nil_end; apply mkLine_ulist; auto.\nintros n1 Rec m1; apply ulist_app; auto.\napply mkLine_ulist.\nintros a H1 H2.\ncase in_mkLine with (1 := H1); intros p1 ((H3, H4), H5).\ncase in_mkRect with (1 := H2); intros p2 (p3, ((H6, H7), ((H8, H9), H10))).\nsubst; injection H10; clear H10; intros; subst.\ncontradict H7.\nchange (~ Z_of_nat (S n1) <= Z_of_nat  n1).\nrewrite inj_S; auto with zarith.\nQed.\n\n(************************************** \n  mL is the list  {(p, q) | 0 <= p < m-1 /\\ 0 <= q < m - 1}\n **************************************)\nDefinition mL := mkRect (Zabs_nat (m - 1)) (Zabs_nat (m -1)).\n\n(************************************** \n  Some properties of mL\n **************************************)\n\nTheorem mL_length : length mL = Zabs_nat (m * m).\nunfold mL; rewrite mkRect_length; simpl; apply inj_eq_inv.\nrepeat (rewrite inj_mult || rewrite inj_plus || rewrite Z_of_nat_Zabs_nat); simpl; auto with zarith.\neq_tac; auto with zarith.\nQed.\n\nTheorem mL_in: forall p q, 0 <= p < m -> 0 <= q <  m -> (In (p, q) mL).\nintros p q (H1, H2) (H3, H4); unfold mL; apply mkRect_in; rewrite Z_of_nat_Zabs_nat; auto with zarith.\nQed.\n\nTheorem in_mL: forall p, In p mL->  exists p1, exists  p2, 0 <= p1 < m  /\\ 0 <= p2 < m  /\\ p = (p1, p2).\nunfold mL; intros p H1; case in_mkRect with (1 := H1).\nrepeat rewrite Z_of_nat_Zabs_nat; auto with zarith.\nintros p1 (p2, ((H2, H3), ((H4, H5), H6))); exists p1; exists p2; repeat split; auto with zarith.\nQed.\n\nTheorem mL_ulist:  ulist mL.\nunfold mL; apply mkRect_ulist; auto.\nQed.\n\n(************************************** \n  We define zpmult the multiplication of pairs module m\n **************************************)\n\nDefinition zpmult (p q: Z * Z) := let (x ,y) := pmult p q in (Zmod x m, Zmod y m).\n\n(************************************** \n  Some properties of zpmult\n **************************************)\n\nTheorem zpmult_internal: forall p q, (In (zpmult p q) mL).\nintros p q; unfold zpmult; case (pmult p q); intros z y; apply mL_in; auto with zarith.\napply Z_mod_lt; auto with zarith.\napply Z_mod_lt; auto with zarith.\nQed.\n\nTheorem zpmult_assoc: forall p q r, (zpmult p (zpmult q r)) = (zpmult (zpmult p q) r).\nassert (U: 0 < m); auto with zarith.\nintros p q r; unfold zpmult.\ngeneralize (pmult_assoc p q r).\ncase (pmult p q); intros x1 x2.\ncase (pmult q r); intros y1 y2.\ncase p; case r; unfold pmult.\nintros z1 z2 t1 t2 H.\nmatch goal with\n  H: (?X, ?Y) = (?Z, ?T) |- _ =>\n   assert (H1: X = Z); assert (H2: Y = T); try (injection H; simpl; auto; fail); clear H\nend.\neq_tac.\ngeneralize (f_equal (fun x => x mod m) H1).\nrepeat rewrite <- Zmult_assoc.\nrepeat (rewrite (fun x  => Zmod_plus (t1 * x))); auto.\nrepeat (rewrite (fun x  => Zmod_plus (x1 * x))); auto.\nrepeat (rewrite (fun x  => Zmod_plus (x1 mod m * x))); auto.\nrepeat (rewrite (Zmod_mult t1)); auto.\nrepeat (rewrite (Zmod_mult x1)); auto.\nrepeat (rewrite (Zmod_mult base)); auto.\nrepeat (rewrite (Zmod_mult t2)); auto.\nrepeat (rewrite (Zmod_mult x2)); auto.\nrepeat (rewrite (Zmod_mult (t2 mod m))); auto.\nrepeat (rewrite (Zmod_mult (x1 mod m))); auto.\nrepeat (rewrite (Zmod_mult (x2 mod m))); auto.\nrepeat (rewrite Zmod_mod); auto.\ngeneralize (f_equal (fun x => x mod m) H2).\nrepeat (rewrite (fun x  => Zmod_plus (t1 * x))); auto.\nrepeat (rewrite (fun x  => Zmod_plus (x1 * x))); auto.\nrepeat (rewrite (fun x  => Zmod_plus (x1 mod m * x))); auto.\nrepeat (rewrite (Zmod_mult t1)); auto.\nrepeat (rewrite (Zmod_mult x1)); auto.\nrepeat (rewrite (Zmod_mult t2)); auto.\nrepeat (rewrite (Zmod_mult x2)); auto.\nrepeat (rewrite (Zmod_mult (t2 mod m))); auto.\nrepeat (rewrite (Zmod_mult (x1 mod m))); auto.\nrepeat (rewrite (Zmod_mult (x2 mod m))); auto.\nrepeat (rewrite Zmod_mod); auto.\nQed.\n\nTheorem zpmult_0_l: forall p, (zpmult (0, 0) p) = (0, 0).\nintros p; case p; intros x y; unfold zpmult, pmult; simpl.\nrewrite Zmod_def_small; auto with zarith.\nQed.\n\nTheorem zpmult_1_l: forall p, In p mL -> zpmult (1, 0) p = p.\nintros p H; case in_mL with (1 := H); clear H; intros p1 (p2, ((H1, H2), (H3, H4))); subst.\nunfold zpmult; rewrite pmult_1_l.\nrepeat rewrite Zmod_def_small; auto with zarith.\nQed.\n\nTheorem zpmult_1_r: forall p, In p mL -> zpmult p (1, 0) = p.\nintros p H; case in_mL with (1 := H); clear H; intros p1 (p2, ((H1, H2), (H3, H4))); subst.\nunfold zpmult; rewrite pmult_1_r.\nrepeat rewrite Zmod_def_small; auto with zarith.\nQed.\n\nTheorem zpmult_comm: forall p q, zpmult p q = zpmult q p.\nintros p q; unfold zpmult; rewrite pmult_comm; auto.\nQed.\n\n(************************************** \n   We are now ready to build our group \n **************************************)\n\nDefinition PGroup : (FGroup zpmult).\napply IGroup with (support := mL) (e:= (1, 0)).\nexact P_dec.\napply mL_ulist.\napply mL_in; auto with zarith.\nintros; apply zpmult_internal.\nintros; apply zpmult_assoc.\nexact zpmult_1_l.\nexact zpmult_1_r.\nDefined.\n\nEnd Mod.\n", "meta": {"author": "EasyCrypt", "repo": "certicrypt", "sha": "7b3cd2fe4a317aec38dfff9eec902b265c575587", "save_path": "github-repos/coq/EasyCrypt-certicrypt", "path": "github-repos/coq/EasyCrypt-certicrypt/certicrypt-7b3cd2fe4a317aec38dfff9eec902b265c575587/Examples/Indifferentiability/ECurve/PrimalityTest/PGroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6904758783903459}}
{"text": "(* \n  Author(s):\n    Dominique Larchey-Wendling (1)\n    Andrej Dudenhefner (2)\n  Affiliation(s):\n    (1) LORIA -- CNRS\n    (2) TU Dortmund University, Dortmund, Germany\n*)\n\n(* \n  Problem(s):\n    Two-counter Machine Halting (MM2_HALTING)\n    Two-counter Machine Halting starting from (0, 0) (MM2_ZERO_HALTING)\n    Two-counter Machine Halting ending in (0, 0) (MM2_HALTS_ON_ZERO)\n    Two-counter Machine Reversibility (MM2_REV)\n    Reversible Two-counter Machine Halting (MM2_REV_HALT)\n    Two-counter Machine Uniform Boundedness (MM2_UBOUNDED)\n    Two-counter Machine Uniform Mortality (MM2_UMORTAL)\n*)\n\n(* \n  Literature:\n  [1] Certified Undecidability of Intuitionistic Linear Logic via Binary Stack Machines and Minsky Machines.\n      Yannick Forster and Dominique Larchey-Wendling. CPP '19. http://uds-psl.github.io/ill-undecidability/ \n*)\n\nRequire Import List Relations.Relation_Operators.\n\n#[local] Set Implicit Arguments.\n\n(* Two counters Minsky machines. Counters are named A and B\n\n    For instructions: INC{A,B} | DEC{A,B} j \n\n    j is a conditional jump PC index which occurs\n    when the counter has non-zero value \n*)\n\nInductive mm2_instr : Set :=\n  | mm2_inc_a : mm2_instr\n  | mm2_inc_b : mm2_instr\n  | mm2_dec_a : nat -> mm2_instr\n  | mm2_dec_b : nat -> mm2_instr.\n\nReserved Notation \"i '//' r '⇢' s\" (at level 70, no associativity).\nReserved Notation \"P '//' r '→' s\" (at level 70, no associativity).\nReserved Notation \"P '//' r '↠' s\" (at level 70, no associativity).\nReserved Notation \"P '//' r ↓\" (at level 70, no associativity).\n\n#[local] Notation mm2_state := (nat*(nat*nat))%type.\n\n(* Instruction step semantics:\n\n    ρ // x ⇢ y : instruction ρ transforms state x into state y \n\n    Notice that the jump occurs on the non-zero case when DEC\n\n  *)\n\nInductive mm2_atom : mm2_instr -> mm2_state -> mm2_state -> Prop :=\n  | in_mm2s_inc_a  : forall i   a b, mm2_inc_a   // (i,(  a,  b)) ⇢ (1+i,(S a,  b))\n  | in_mm2s_inc_b  : forall i   a b, mm2_inc_b   // (i,(  a,  b)) ⇢ (1+i,(  a,S b))\n  | in_mm2s_dec_aS : forall i j a b, mm2_dec_a j // (i,(S a,  b)) ⇢ (  j,(  a,  b))\n  | in_mm2s_dec_bS : forall i j a b, mm2_dec_b j // (i,(  a,S b)) ⇢ (  j,(  a,  b))\n  | in_mm2s_dec_a0 : forall i j   b, mm2_dec_a j // (i,(  0,  b)) ⇢ (1+i,(  0,  b))\n  | in_mm2s_dec_b0 : forall i j a,   mm2_dec_b j // (i,(  a,  0)) ⇢ (1+i,(  a,  0))\nwhere \"ρ // x ⇢ y\" := (mm2_atom ρ x y).\n\n(* instruction ρ occurs at PC index i in the program (1,P) *)\n\nDefinition mm2_instr_at (ρ : mm2_instr) i P := exists l r, P = l++ρ::r /\\ 1+length l = i.\n\n(* Program step semantics:\n\n    program P with first instruction at PC index 1 transforms \n    state x into state y in one step, using instruction a PC index (fst x) *)\n\nDefinition mm2_step P x y := exists ρ, mm2_instr_at ρ (fst x) P /\\ ρ // x ⇢ y.\n#[local] Notation \"P // x → y\" := (mm2_step P x y).\n\n(* Halting condition: program P cannot progress from s *)\nDefinition mm2_stop P s := forall s', not (P // s → s').\n\n(* reflexive and transitive closure of program step semantics *)\n#[local] Notation \"P // x ↠ y\" := (clos_refl_trans _ (mm2_step P) x y).\n\nDefinition mm2_terminates P s := exists s', P // s ↠ s' /\\ mm2_stop P s'.\n#[local] Notation \"P // s ↓\" := (mm2_terminates P s).\n\nDefinition MM2_PROBLEM := (list mm2_instr * nat * nat)%type.\n\n(* Two-counter Machine Halting *)\nDefinition MM2_HALTING (P : MM2_PROBLEM) := \n  match P with (P,a,b) => P // (1,(a,b)) ↓ end.\n\n(* Two-counter Machine Halting starting from (0, 0) *)\nDefinition MM2_ZERO_HALTING : list mm2_instr -> Prop := \n  fun P => P // (1,(0,0)) ↓.\n\n(* Two-counter Machine Halting ending in (0, 0) *)\nDefinition MM2_HALTS_ON_ZERO (P : MM2_PROBLEM) := \n  match P with (P,a,b) => P // (1,(a,b)) ↠ (0,(0,0)) end.\n\n(* injectivity of the step relation *)\nDefinition mm2_reversible (P : list mm2_instr) : Prop := \n  forall x y z, mm2_step P x z -> mm2_step P y z -> x = y.\n\n(* k bounds the number of reachable configurations from x *)\nDefinition mm2_bounded (P : list mm2_instr) (k: nat) (x: mm2_state) : Prop := \n  exists (L: list mm2_state), (length L <= k) /\\\n    (forall (y: mm2_state), P // x ↠ y -> In y L).\n\n(* uniform bound for number of reachable configurations *)\nDefinition mm2_uniformly_bounded (P : list mm2_instr) : Prop :=\n  exists k, forall x, mm2_bounded P k x.\n\n(* configuration trace P // x → x1 → x2 → ... → xn *)\nFixpoint mm2_trace (P : list mm2_instr) (x : mm2_state) (xs : list mm2_state) : Prop :=\n  match xs with\n  | nil => True\n  | y::ys => P // x → y /\\ mm2_trace P y ys\n  end.\n\n(* k bounds the number of steps in any run from x *)\nDefinition mm2_mortal (P : list mm2_instr) (k: nat) (x: mm2_state) : Prop :=\n  forall (L: list mm2_state), mm2_trace P x L -> length L <= k.\n\n(* uniform bound for number of steps until termination *)\nDefinition mm2_uniformly_mortal (P : list mm2_instr) : Prop :=\n  exists k, forall x, mm2_mortal P k x.\n\n(* Two-counter Machine Reversibility:\n   Given a two-counter machine P,\n   is the step function of P injective? *)\nDefinition MM2_REV : list mm2_instr -> Prop :=\n  fun P => mm2_reversible P.\n\n(* Reversible Two-counter Machine Halting:\n   Given a reversible two-counter machine P and a configucation x,\n   does a run in M starting from x eventually halt? *)\nDefinition MM2_REV_HALT : { P: list mm2_instr | mm2_reversible P } * mm2_state -> Prop :=\n  fun '((exist _ P _), x) => P // x ↓.\n\n(* Two-counter Machine Uniform Boundedness:\n   Given a two-counter machine P,\n   is there a uniform bound n,\n   such that for any configuration x,\n   the number of reacheable configurations from x in P is bounded by n? *)\nDefinition MM2_UBOUNDED : list mm2_instr -> Prop :=\n  fun P => mm2_uniformly_bounded P.\n\n(* Two-counter Machine Uniform Mortality:\n   Given a two-counter machine P,\n   is there a uniform bound n,\n   such that for any configuration x,\n   a run in P starting from x halts after at most n steps? *)\nDefinition MM2_UMORTAL : list mm2_instr -> Prop :=\n  fun P => mm2_uniformly_mortal P.\n\nModule MM2Notations.\n  Notation mm2_state := (nat*(nat*nat))%type.\n  Notation index x := (@fst nat (nat*nat) x).\n  Notation value1 x := (fst (@snd nat (nat*nat) x)).\n  Notation value2 x := (snd (@snd nat (nat*nat) x)).\n  Notation \"ρ // x ⇢ y\" := (mm2_atom ρ x y).\n  Notation \"P // x → y\" := (mm2_step P x y).\n  Notation \"P // x ↠ y\" := (clos_refl_trans _ (mm2_step P) x y).\n  Notation \"P // s ↓\" := (mm2_terminates P s).\nEnd MM2Notations.\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/MM2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6904758746593026}}
{"text": "(**********************************************LISTS*********************************************************)\nRequire Import List.\nImport ListNotations.\n\nModule MyList.\n\nInductive list (A : Type) : Type :=\n| nil : list A\n| cons : A -> list A -> list A.\n\nEnd MyList.\n\nCheck list.\n\nDefinition is_empty (A : Type) (lst : list A) :=\n  match lst with\n  | nil => true\n  | cons _ _ => false\n  end.\n\nDefinition is_empty_sugar (A : Type) (lst : list A) :=\n  match lst with\n  | [] => true\n  | _::_ => false\n  end.\n\nCompute is_empty nat [1].\n\nCompute is_empty nat [].\n\nDefinition is_empty' {A : Type} (lst : list A) :=\n  match lst with\n  | [] => true\n  | _::_ => false\n  end.\n\nCompute is_empty' [1].\n\n\nCompute @is_empty' nat [1].\n\nModule MyLength.\n\nFixpoint length {A : Type} (lst : list A) :=\n  match lst with\n  | nil => 0\n  | _::t => 1 + length t\n  end.\n\nCompute length [1;2].\n\nEnd MyLength.\n\n(************************************************OPTIONS******************************************************)\n\nModule MyOption.\n\nInductive option (A:Type) : Type :=\n  | Some : A -> option A\n  | None : option A.\n\nEnd MyOption.\n\nDefinition hd_opt {A : Type} (lst : list A) : option A :=\n  match lst with\n  | nil => None \n  | x :: xs => Some x\n  end.\n\nCompute hd_opt [1].\n\nCompute @hd_opt nat [].\n\nTheorem length0_implies_hdopt_is_none :\n  forall A : Type, forall lst : list A,\n    length lst = 0 -> hd_opt lst = None.\nProof.\n  intros A lst length_lst_is_0.\n  destruct lst.\n    trivial.\n    discriminate.\nQed.\n\nTheorem length0_implies_hdopt_is_none' :\nforall A : Type, forall lst : list A,\n  length lst = 0 -> hd_opt lst = None.\nProof.\n  intros A lst length_lst_is_0.\n  destruct lst.\n    - trivial.\n    - discriminate.\nQed.", "meta": {"author": "sheeraSearch82", "repo": "Coq_assignments", "sha": "e93136c16ecebbbfe09cb356845f9b29f5850bfb", "save_path": "github-repos/coq/sheeraSearch82-Coq_assignments", "path": "github-repos/coq/sheeraSearch82-Coq_assignments/Coq_assignments-e93136c16ecebbbfe09cb356845f9b29f5850bfb/lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6904758735988138}}
{"text": "Require Import XR_R0.\nRequire Import XR_Rle_dec.\nRequire Import XR_Rnot_le_lt.\n\nLocal Open Scope R_scope.\n\nLemma Rcase_abs : forall r, {r < R0} + {R0 <= r}.\nProof.\n  intro x.\n  assert (h := Rle_dec).\n  specialize (h R0 x).\n  destruct h as [ hl | hr ].\n  {\n    right.\n    exact hl.\n  }\n  {\n    left.\n    apply Rnot_le_lt.\n    exact hr.\n  }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rcase_abs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6904758735988137}}
{"text": "Require Import Lia.\nRequire Import Nat.\nRequire Import List.\nRequire Import Classes.DecidableClass.\n\nFrom Cyclic_PA.Maths Require Import naturals.\nFrom Cyclic_PA.Logic Require Import definitions.\n\nRequire Import Coq.Arith.Wf_nat.\n\nOpen Scope bool_scope.\nOpen Scope list_scope.\n\nImport ListNotations.\n\nNotation nat_eq_dec := PeanoNat.Nat.eq_dec.\n\nLemma concat_map_remove_eq {A B : Type} {DEC : forall (a b : A), {a = b} + {a <> b}} :\nforall (f : A -> list B) (a : A) (L1 L2 : list A),\n    concat (map f L1) = concat (map f L2) ->\n        concat (map f (remove DEC a L1)) = concat (map f (remove DEC a L2)).\nintros f a L1.\ninduction L1 as [L1 IND1] using (induction_ltof1 _ (@length _));\nunfold ltof in IND1.\nintros L2 EQ;\ninduction L2 as [L2 IND2] using (induction_ltof1 _ (@length _));\nunfold ltof in IND2.\ndestruct L1 as [| hd1 L1];\ndestruct L2 as [| hd2 L2].\n- reflexivity.\n- unfold map, remove in *;\n  fold (map f) (remove DEC) in *.\n  symmetry in EQ.\n  apply app_eq_nil in EQ as [EQ1 EQ2].\n  fold (@concat B) in *.\n  case DEC as [EQ | NE];\n  unfold map;\n  fold (map f);\n  try rewrite EQ1;\n  try rewrite IND2;\n  try apply le_n;\n  symmetry;\n  try apply EQ2.\n- unfold flat_map, remove in *;\n  fold (flat_map f) (remove DEC) in *.\n  apply app_eq_nil in EQ as [EQ1 EQ2].\n  case DEC as [EQ | NE];\n  unfold flat_map;\n  fold (flat_map f);\n  try rewrite EQ1;\n  try rewrite app_nil_l;\n  refine (IND1 _ _ [] _);\n  try apply le_n;\n  apply EQ2.\n- unfold remove;\n  fold (remove DEC).\n  unfold flat_map in *;\n  fold (flat_map f) in *.\n  case DEC as [EQ' | NE].\n  + rewrite flat_map_concat_map.\nQed.\n*)\nLemma flat_map_remove_eq {A B : Type} {DEC : forall (a b : A), {a = b} + {a <> b}} :\n  forall (f : A -> list B) (a : A) (L1 L2 : list A),\n      flat_map f L1 = flat_map f L2 ->\n          flat_map f (remove DEC a L1) = flat_map f (remove DEC a L2).\nProof.\nintros f a L1 L2 EQ.\nrepeat rewrite flat_map_concat_map in *.\napply concat_map_remove_eq, EQ.\nQed.\n\n\nFixpoint list_eqb (l1 l2 : list nat) : bool :=\nmatch l1,l2 with\n| [],[] => true\n| m :: l1',[] => false\n| [], n :: l2' => false\n| m :: l1', n :: l2' => nat_eqb m n && list_eqb l1' l2'\nend.\n\nLemma list_eqb_eq :\n    forall (l1 l2 : list nat),\n        list_eqb l1 l2 = true ->\n            l1 = l2.\nProof.\ninduction l1;\nintros l2 EQ.\n- destruct l2.\n  + reflexivity. \n  + inversion EQ.\n- destruct l2.\n  + inversion EQ.\n  + unfold list_eqb in EQ; fold list_eqb in EQ.\n    destruct (and_bool_prop _ _ EQ) as [EQ1 EQ2].\n    rewrite (IHl1 l2 EQ2).\n    rewrite (nat_eqb_eq _ _ EQ1).\n    reflexivity.\nQed.\n\nLemma list_eqb_refl :\n    forall (l : list nat),\n        list_eqb l l = true.\nProof.\ninduction l.\n- reflexivity.\n- unfold list_eqb; fold list_eqb.\n  rewrite nat_eqb_refl.\n  apply IHl.\nQed.\n\nFixpoint member (n : nat) (l : list nat) : bool :=\nmatch l with\n| nil => false\n| m :: l' => \n  (match nat_eqb m n with\n  | true => true\n  | false => member n l'\n  end)\nend.\n\nLemma member_in (n : nat) (l : list nat) : member n l = true <-> In n l.\nProof.\ninduction l;\nsplit;\nintros IN.\n- inversion IN.\n- inversion IN.\n- unfold In; fold (@In nat).\n  unfold member in IN;\n  fold member in IN.\n  case (nat_eqb a n) eqn:EQB.\n  + apply nat_eqb_eq in EQB.\n    left.\n    apply EQB.\n  + right.\n    apply IHl, IN.\n- unfold member;\n  fold member.\n  destruct IN as [EQ | IN].\n  + destruct EQ.\n    rewrite nat_eqb_refl.\n    reflexivity.\n  + case (nat_eqb a n).\n    * reflexivity.\n    * apply IHl, IN.\nQed.\n\nLemma not_member_nin (n : nat) (l : list nat) : member n l = false <-> ~In n l.\nProof.\ndestruct (in_dec nat_eq_dec n l) as [IN | NIN];\nsplit;\nintros NIN'.\n- rewrite (proj2 (member_in _ _) IN) in NIN'.\n  inversion NIN'.\n- contradict (NIN' IN).\n- apply NIN.\n- case (member n l) eqn:IN.\n  + contradict (NIN (proj1 (member_in _ _) IN)).\n  + reflexivity.\nQed.\n\nLemma remove_dups_empty :\n    forall (l : list nat),\n        nodup nat_eq_dec l = [] -> l = [].\nProof.\nintros l lE.\ninduction l.\n- reflexivity.\n- unfold nodup in lE.\n  fold (nodup nat_eq_dec) in lE.\n  case (in_dec nat_eq_dec a l) as [IN | NIN].\n  + rewrite (IHl lE) in IN.\n    inversion IN.\n  + inversion lE.\nQed.\n\nLemma remove_dups_order :\n    forall (l : list nat) (n : nat),\n        remove nat_eq_dec n (nodup nat_eq_dec l) = nodup nat_eq_dec (remove nat_eq_dec n l).\nProof.\nintros l n.\ninduction l.\n- reflexivity.\n- unfold nodup; fold (nodup nat_eq_dec);\n  unfold remove; fold (remove nat_eq_dec).\n  case (nat_eq_dec a n) as [EQ | NE];\n  try destruct EQ;\n  destruct nat_eq_dec as [EQ | NE'];\n  unfold nodup; fold (nodup nat_eq_dec);\n  unfold remove; fold (remove nat_eq_dec).\n  + rewrite <- IHl.\n    case (in_dec nat_eq_dec a l) as [IN | NIN].\n    * reflexivity.\n    * apply remove_cons.\n  + contradict (NE' eq_refl).\n  + contradict NE.\n    destruct EQ.\n    reflexivity.\n  + rewrite <- IHl.\n    case (in_dec nat_eq_dec a l) as [IN | NIN];\n    case (in_dec nat_eq_dec a (remove nat_eq_dec n l)) as [IN' | NIN'].\n    * reflexivity.\n    * contradict (NIN' (in_in_remove nat_eq_dec _ NE IN)).\n    * contradict (NIN (proj1 (in_remove nat_eq_dec _ _ _ IN'))).\n    * unfold remove; fold (remove nat_eq_dec).\n      case nat_eq_dec as [EQ | _].\n      --  contradict (NE' EQ).\n      --  reflexivity.\nQed.\n\nLemma remove_n_dups_empty :\n    forall (l : list nat) (n : nat),\n        remove nat_eq_dec n (nodup nat_eq_dec l) = [] ->\n            nodup nat_eq_dec l = [n] \\/ nodup nat_eq_dec l = [].\nProof.\nintros l n RlE.\ninduction l.\n- right.\n  reflexivity.\n- unfold nodup; fold (nodup nat_eq_dec).\n  rewrite remove_dups_order in *.\n  unfold remove in *; fold (remove nat_eq_dec) in *.\n  case (nat_eq_dec n a) as [EQ | NE].\n  + destruct EQ.\n    destruct (IHl RlE) as [Ln | Le];\n    case (in_dec nat_eq_dec n l) as [IN | NIN].\n    * left.\n      apply Ln.\n    * contradict NIN.\n      refine ((proj1 (nodup_incl nat_eq_dec [n] _)) _ _ (in_eq _ _)).\n      rewrite Ln.\n      apply incl_refl.\n    * right.\n      apply Le.\n    * left.\n      rewrite Le.\n      reflexivity.\n  + unfold nodup in RlE; fold (nodup nat_eq_dec) in RlE.\n    case in_dec as [IN | NIN].\n    * rewrite <- nodup_In, RlE in IN.\n      inversion IN.\n    * inversion RlE.\nQed.\n\nLemma remove_dups_twice : forall (l : list nat),\n  nodup nat_eq_dec (nodup nat_eq_dec l) = nodup nat_eq_dec l.\nProof.\nintros l.\napply nodup_fixed_point, NoDup_nodup.\nQed.\n\nLemma member_remove' : forall (l : list nat) (m n : nat),\n  nat_eqb m n = false ->\n  member n l = true ->\n  member n (remove nat_eq_dec m l) = true.\nProof.\nintros l m n NE' IN.\ninduction l.\n- apply IN.\n- unfold member in IN.\n  fold member in IN.\n  unfold remove.\n  fold (remove nat_eq_dec).\n  case (nat_eq_dec m a) as [EQ | NE].\n  + destruct EQ.\n    case (nat_eqb m n) eqn:EQB.\n    * inversion NE'.\n    * apply IHl, IN.\n  + unfold member.\n    fold member.\n    case (nat_eqb a n) eqn:EQB.\n    * reflexivity.\n    * apply IHl, IN.\nQed.\n\nLemma member_remove : forall (l : list nat) (m n : nat),\n  nat_eqb m n = false ->\n  member n (remove nat_eq_dec m l) = false ->\n  member n l = false.\nProof.\nintros l m n NEB NMEM.\ncase (member n l) eqn:MEM.\n- rewrite (member_remove' _ _ _ NEB MEM) in NMEM. apply NMEM.\n- reflexivity.\nQed.\n\nLemma member_remove_dups : forall (l : list nat) (n : nat),\n  member n (nodup nat_eq_dec l) = false -> member n l = false.\nProof.\nintros. induction l; auto.\nsimpl. simpl in H.\ncase in_dec as [IN | NIN];\ndestruct (nat_eqb a n) eqn:EQB.\n- apply nat_eqb_eq in EQB.\n  destruct EQB.\n  apply not_member_nin in H.\n  contradict H.\n  apply nodup_In, IN.\n- apply IHl, H.\n- apply nat_eqb_eq in EQB.\n  destruct EQB.\n  unfold member in H.\n  rewrite nat_eqb_refl in H.\n  inversion H.\n- apply IHl.\n  unfold member in H.\n  rewrite EQB in H.\n  apply H.\nQed.\n\nLemma member_concat' : forall (l1 l2 : list nat) (n : nat),\n  member n (l1 ++ l2) = true ->\n  member n l1 = true \\/ member n l2 = true.\nProof.\nintros. induction l1.\n- right. apply H.\n- simpl in H. simpl. destruct (nat_eqb a n) eqn:Hx.\n  + left. auto.\n  + destruct (IHl1 H).\n    * left. apply H0.\n    * right. apply H0.\nQed.\n\nLemma member_concat : forall (l1 l2 : list nat) (n : nat),\n  member n (l1 ++ l2) = false ->\n  member n l1 = false /\\ member n l2 = false.\nProof.\nintros. induction l1; auto.\nsimpl. case_eq (nat_eqb a n); intros; simpl in H; rewrite H0 in H.\n- inversion H.\n- apply (IHl1 H).\nQed.\n\nLemma member_remove_dups_concat : forall (l1 l2 : list nat) (n : nat),\n  member n (nodup nat_eq_dec (l1 ++ l2)) = false ->\n  member n l1 = false /\\ member n l2 = false.\nProof.\nintros.\napply member_concat.\napply member_remove_dups.\napply H.\nQed.\n\nLemma concat_member : forall (l l' : list nat) (n : nat),\n  member n l = true -> member n (l ++ l') = true.\nProof.\nintros. destruct (member n (l ++ l')) eqn:Hn; auto.\ndestruct (member_concat _ _ _ Hn). rewrite H0 in H. inversion H.\nQed.\n\nLemma remove_dups_member : forall (l : list nat) (n : nat),\n  member n l = true -> member n (nodup nat_eq_dec l) = true.\nProof.\nintros. destruct (member n (nodup nat_eq_dec l)) eqn:Hn; auto.\napply member_remove_dups in Hn. rewrite Hn in H. inversion H.\nQed.\n\nFixpoint repeated_element_n (l : list nat) (n : nat) : bool :=\nmatch l with\n| [] => true\n| m :: l' => nat_eqb m n && repeated_element_n l' n\nend.\n\nLemma in_reapeated_is : forall (m n : nat) (L : list nat), repeated_element_n L n = true -> In m L -> m = n.\nProof.\ninduction L;\nintros RL IN.\n- inversion IN.\n- destruct IN as [EQ | IN].\n  + destruct EQ.\n    apply (nat_eqb_eq _ _ (proj1 (and_bool_prop _ _ RL))).\n  + apply (IHL (proj2 (and_bool_prop _ _ RL)) IN).\nQed.\n\nLemma remove_dups_repeated_element : forall (l : list nat) (n : nat),\n  repeated_element_n l n = true ->\n  sum (nodup nat_eq_dec l = [n]) (l = []).\nProof.\nintros.\ninduction l; auto.\nleft.\napply and_bool_prop in H as [X1 X2].\nfold repeated_element_n in X2.\ndestruct (IHl X2) as [H3 | H3].\n- simpl. rewrite H3. \n  apply nat_eqb_eq in X1.\n  destruct X1.\n  unfold repeated_element_n in X2.\n  destruct l.\n  + inversion H3.\n  + apply and_bool_prop in X2 as [X1 X2].\n    apply nat_eqb_eq in X1.\n    destruct X1.\n    case (in_dec nat_eq_dec n (n :: l)) as [_ | FAL].\n    * reflexivity.\n    * contradict FAL.\n      left.\n      reflexivity.\n- rewrite H3. rewrite (nat_eqb_eq _ _ X1). reflexivity.\nQed.\n\nLemma nodup_nil : forall l : list nat, nodup nat_eq_dec l = [] -> l = [].\nProof.\ninduction l;\nintros EQ.\n- reflexivity.\n- unfold nodup in EQ.\n  fold (nodup nat_eq_dec) in EQ.\n  case in_dec as [IN | NIN].\n  + rewrite (IHl EQ) in IN.\n    inversion IN.\n  + inversion EQ.\nQed.\n\nLemma remove_dups_repeated_element' : forall (l : list nat) (n : nat),\n  nodup nat_eq_dec l = [n] ->\n  repeated_element_n l n = true.\nProof.\nintros. induction l; auto.\nsimpl. inversion H.\ncase in_dec as [IN | NIN].\n- pose proof (IHl H1).\n  destruct (in_reapeated_is _ _ _ H0 IN).\n  rewrite nat_eqb_refl.\n  apply H0.\n- inversion H1.\n  destruct H2.\n  rewrite nat_eqb_refl.\n  rewrite (nodup_nil _ H3).\n  reflexivity.\nQed.\n\nLemma repeated_element_n_concat_aux : forall (l1 l2 : list nat) (m n : nat),\n  repeated_element_n (l1 ++ (m :: l2)) n = true ->\n  nat_eqb m n && repeated_element_n l2 n = true.\nProof.\nintros. induction l1; simpl in H.\n- apply H.\n- apply IHl1. destruct (and_bool_prop _ _ H). apply H1.\nQed.\n\nLemma repeated_element_n_concat : forall (l1 l2 : list nat) (n : nat),\n  repeated_element_n (l1 ++ l2) n = true ->\n  repeated_element_n l1 n = true /\\ repeated_element_n l2 n = true.\nProof.\nintros. split.\n- induction l1; auto.\n  simpl. simpl in H. destruct (and_bool_prop _ _ H).\n  rewrite H0, (IHl1 H1). auto.\n- induction l2; auto. simpl.\n  apply (repeated_element_n_concat_aux l1 l2 a n), H.\nQed.\n\nLemma remove_dup_single_right : forall l1 l2 m, nodup nat_eq_dec (l1 ++ l2) = [m] -> nodup nat_eq_dec l2 = [m] \\/ nodup nat_eq_dec l2 = [].\nProof.\nintros. pose proof (remove_dups_repeated_element' _ _ H). pose proof (repeated_element_n_concat _ _ _ H0). destruct H1. destruct (remove_dups_repeated_element _ _ H2); auto. rewrite e. auto.\nQed.\n\nLemma remove_dup_single_left : forall l1 l2 m, nodup nat_eq_dec (l1 ++ l2) = [m] -> nodup nat_eq_dec l1 = [m] \\/ nodup nat_eq_dec l1 = [].\nProof.\nintros. pose proof (remove_dups_repeated_element' _ _ H). pose proof (repeated_element_n_concat _ _ _ H0). destruct H1. destruct (remove_dups_repeated_element _ _ H1); auto. rewrite e. auto.\nQed.\n\nLemma remove_not_in : forall l n, list_eqb (remove nat_eq_dec n l) [n] = false.\nProof.\nintros. induction l. auto. simpl. case (nat_eq_dec n a) as [EQ | NE].\n- auto.\n- simpl.\n  case (nat_eqb a n) eqn:Y.\n  + contradict NE.\n    symmetry.\n    apply nat_eqb_eq, Y.\n  + reflexivity.\nQed. \n\nLemma remove_not_member : forall l n, member n (remove nat_eq_dec n l) = false.\nProof.\nintros. induction l. auto. simpl.  case (nat_eq_dec n a) as [EQ | NE].\n- auto.\n- simpl.\n  case (nat_eqb a n) eqn:Y.\n  + contradict NE.\n    symmetry.\n    apply nat_eqb_eq, Y.\n  + apply IHl.\nQed. \n\nLemma member_remove_true : forall l n m, member n (remove nat_eq_dec m l) = true -> member n l = true.\nProof.\nintros. induction l; inversion H. rewrite H1. simpl. case (nat_eqb a n) eqn:X; auto.\ncase (nat_eq_dec m a) as [EQ | NE]; auto.\n- simpl in H1. rewrite X in H1. auto.\nQed.\n\nLemma remove_member_false : forall l n m, member n l = false -> member n (remove nat_eq_dec m l) = false.\nProof.\nintros. case (nat_eqb n m) eqn:X.\n- apply nat_eqb_eq in X. destruct X. apply remove_not_member.\n- induction l. auto. simpl. inversion H. case (nat_eqb a n) eqn:X1; auto. inversion H1. rewrite H1. case (nat_eq_dec m a) as [EQ | NE]; auto. simpl. rewrite X1. auto.\nQed.\n\nLemma member_remove_dups_true : forall l n, member n (nodup nat_eq_dec l) = true -> member n l = true.\nProof.\n\nintros. induction l; inversion H. simpl. case (nat_eqb a n) eqn:X; auto.\ncase in_dec as [IN | NIN];\nrewrite H1; apply IHl.\n- apply H1.\n- unfold member in H1.\n  rewrite X in H1.\n  apply H1.\nQed.  \n\nLemma nodups_incl_app : forall L1 L2, (forall m, In m L1 -> In m L2) -> nodup nat_eq_dec (L1 ++ L2) = nodup nat_eq_dec L2. \nProof.\ninduction L1; intros.\n- rewrite app_nil_l. reflexivity.\n- rewrite <- app_comm_cons.\n  unfold nodup; fold (nodup nat_eq_dec).\n  case in_dec as [IN | NIN].\n  + apply IHL1.\n    apply (fun m HY => H m (or_intror HY)).\n  + contradict NIN.\n    apply in_or_app.\n    right.\n    apply H.\n    left.\n    reflexivity.\nQed.\n\nLemma remove_dups_concat_self : forall L, nodup nat_eq_dec (L ++ L) = nodup nat_eq_dec L.\nProof.\nintros.\napply nodups_incl_app.\nauto.\nQed.\n\nLemma remove_dups_double_cons_ne : forall n m l, nodup nat_eq_dec (n :: m :: l) = n :: m :: l -> nat_eqb m n = false.\nProof.\nintros.\ncase (nat_eqb m n) eqn:EQB.\n- apply nat_eqb_eq in EQB.\n  destruct EQB.\n  pose proof (NoDup_nodup nat_eq_dec (m :: m :: l)).\n  rewrite H in H0.\n  inversion H0.\n  contradict H3.\n  left.\n  reflexivity.\n- reflexivity.\nQed.\n\nLemma remove_idem_not_mem : forall l n, remove nat_eq_dec n l = l -> member n l = false.\nProof.\nintros. induction l. auto. simpl in *. case (nat_eqb a n) eqn:X.\n- apply nat_eqb_eq in X. destruct X. pose proof (remove_not_member l a). \n  case nat_eq_dec as [_ | FAL].\n  + rewrite H in H0. simpl in H0. rewrite nat_eqb_refl in H0. apply H0.\n  + contradict FAL.\n    reflexivity.\n- case nat_eq_dec as [FAL | _].\n+ destruct FAL.\n  rewrite nat_eqb_refl in X.\n  inversion X.\n+ inversion H.\n  rewrite H1.\n  apply IHl, H1.\nQed.\n\nLemma remove_not_mem_idem : forall l n, member n l = false -> remove nat_eq_dec n l = l.\nProof.\nintros. induction l. auto. simpl in *. case (nat_eqb a n) eqn:X. inversion H. rewrite IHl; auto.\ncase (nat_eq_dec n a) as [FAL | _].\n- destruct FAL.\n  rewrite nat_eqb_refl in X.\n  inversion X.\n- reflexivity.\nQed.\n\nLemma remove_dups_idem_remove_false : forall l n, nodup nat_eq_dec (n :: l) = n :: l -> member n l = false.\nProof.\nintros.\napply nodup_inv in H.\napply not_member_nin, H.\nQed.\n\nLemma not_mem_dupes : forall l n, member n l = false -> member n (nodup nat_eq_dec l) = false.\nProof.\nintros.\napply not_member_nin.\napply not_member_nin in H.\nintros FAL.\napply H.\napply nodup_In in FAL.\napply FAL.\nQed.\n\nLemma remove_dups_idem_remove_triv : forall l n, nodup nat_eq_dec (n :: l) = n :: l -> remove nat_eq_dec n (n :: l) = l.\nProof.\nintros.\npose proof (remove_dups_idem_remove_false _ _ H).\nunfold remove; fold (remove nat_eq_dec).\ncase nat_eq_dec as [_ | FAL].\n- apply notin_remove, not_member_nin, H0.\n- contradict FAL.\n  reflexivity.\nQed.\n\nLemma remove_idem_tail : forall l n, nodup nat_eq_dec (n :: l) = n :: l -> nodup nat_eq_dec l = l.\nProof.\nintros.\npose proof (remove_dups_idem_remove_false _ _ H).\nunfold nodup in H.\nfold (nodup nat_eq_dec) in H.\ncase in_dec as [FAL | _].\n- apply member_in in FAL.\n  rewrite H0 in FAL.\n  inversion FAL.\n- inversion H.\n  repeat rewrite H2.\n  reflexivity.\nQed.\n\nLemma member_split : forall l n, member n l = true -> exists l1 l2, l = l1 ++ (n :: l2).\nProof.\nintros. induction l. inversion H. simpl in H. case (nat_eqb a n) eqn:X.\n- apply nat_eqb_eq in X. destruct X. exists [], l. auto.\n- destruct (IHl H) as [l1 [l2 HL]]. exists (a :: l1), l2. rewrite HL. auto.\nQed.\n\nLemma member_split_first : forall l n, member n l = true -> exists l1 l2, l = l1 ++ (n :: l2) /\\ member n l1 = false.\nProof.\nintros. induction l. inversion H. simpl in H. case (nat_eqb a n) eqn:X.\n- apply nat_eqb_eq in X. destruct X. exists [], l. auto.\n- destruct (IHl H) as [l1 [l2 [HL1 Hl2]]]. exists (a :: l1), l2. split. rewrite HL1. auto. simpl. rewrite X. auto.\nQed.\n\nLemma split_member : forall l1 l2 n, member n (l1 ++ (n :: l2)) = true.\nProof.\nintros l1. induction l1. intros. simpl. rewrite nat_eqb_refl. auto. intros. simpl. case (nat_eqb a n); auto.\nQed.", "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/lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.6904758714701031}}
{"text": "Check refl_equal.\n(* ===>\neq_refl\n     : forall (A : Type) (x : A), x = x\n*)\n\nCheck eq_ind.\n(* ===>\neq_ind\n     : forall (A : Type) (x : A) (P : A -> Prop),\n       P x -> forall y : A, x = y -> P y\n*)\n\nDefinition eq_sym' (A:Type)(x y:A)(h : x=y) : y=x :=\n  eq_ind x (fun z => z=x) (refl_equal x) y h.\n\nDefinition eq_trans' (A:Type)(x y z:A)(h : x=y)(g : y=z) : x=z :=\n  eq_ind y (fun z => x=z) h z g.\n\nDefinition eq_subst' (A:Type)(B: A -> Prop)(x y:A)(h : x=y)(g : B x) : B y :=\n  eq_ind x (fun z => B z) g y h.\n\nDefinition eq_resp' (A:Type)(B: Prop)(x y:A)(h : x=y)(g: A -> B) : g x = g y :=\n  eq_ind x (fun z => g x = g z) (refl_equal (g x)) y h.\n\nInductive id' (A:Type) : A -> A -> Prop :=\n  refl': forall x, id' A x x.\n\nCheck id'_ind.\n(* ===>\nid'_ind\n     : forall (A : Type) (P : A -> A -> Prop),\n       (forall x : A, P x x) -> forall y y0 : A, id' A y y0 -> P y y0\n*)\n\nDefinition J (A:Type)(x y: A)(h: id' A x y)(P: A -> A -> Prop)(Q: forall x : A, P x x): P x y :=\n  id'_ind A P Q x y h.\n\nDefinition id'_sym (A:Type)(x y:A)(h : id' A x y) : id' A y x :=\n  J A x y h (fun u v => id' A v u) (fun z => refl' A z).\n\nDefinition id'_trans (A:Type)(x y z:A)(h : id' A x y)(g : id' A y z) : id' A x z :=\n  J A x y h (fun u v => id' A v z -> id' A u z) (fun z i => i) g.\n\nDefinition id'_subst (A:Type)(B: A -> Prop)(x y:A)(h : id' A x y)(g : B x) : B y :=\n  J A x y h (fun u v => B u -> B v) (fun z i => i) g.\n\nDefinition id'_resp' (A:Type)(B: Prop)(x y:A)(h : id' A x y)(g: A -> B) : id' B (g x) (g y) :=\n  J A x y h (fun u v => forall q, id' B (q u) (q v)) (fun z q => refl' B (q z)) g.\n", "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/eq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.6904758687995484}}
{"text": "(* 5_folding-left-and-right-over-peano-numbers.v *)\n(* FPP 2020 - YSC3236 2020-2011, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Liu Zhang <zhangliu@u.yale-nus.edu.sg>*)\n(* Version of 05 Sep 2020 *)\n\n(* ********** *)\n\n(* Paraphernalia: *)\n\nLtac fold_unfold_tactic name := intros; unfold name; fold name; reflexivity.\n\nRequire Import Arith Bool.\n\nNotation \"A =n= B\" :=\n  (beq_nat A B) (at level 70, right associativity).\n\n(* ********** *)\n\nDefinition specification_of_power (power : nat -> nat -> nat) :=\n  (forall x : nat,\n      power x 0 = 1)\n  /\\\n  (forall (x : nat)\n          (n' : nat),\n      power x (S n') = x * power x n').\n\n(* ***** *)\n\nProposition there_is_at_most_one_function_satisfying_the_specification_of_power :\n  forall power1 power2 : nat -> nat -> nat,\n    specification_of_power power1 ->\n    specification_of_power power2 ->\n    forall x n : nat,\n      power1 x n = power2 x n.\nProof.\n  intros power1 power2.\n  unfold specification_of_power.\n  intros [S1_O S1_S] [S2_O S2_S] x n.\n  induction n as [ | n' IHn'].\n  - rewrite -> (S2_O x).\n    exact (S1_O x).\n  - rewrite -> (S1_S x n').\n    rewrite -> (S2_S x n').\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\n(* ***** *)\n\nDefinition test_power (candidate : nat -> nat -> nat) : bool :=\n  (candidate 2 0 =? 1) &&\n  (candidate 10 2 =? 10 * 10) &&\n  (candidate 3 2 =? 3 * 3).\n\n(* ***** *)\n\nFixpoint power_v0_aux (x n : nat) : nat :=\n  match n with\n  | O =>\n    1\n  | S n' =>\n    x * power_v0_aux x n'\n  end.\n\nDefinition power_v0 (x n : nat) : nat :=\n  power_v0_aux x n.\n\nCompute (test_power power_v0).\n\nLemma fold_unfold_power_v0_aux_O :\n  forall x : nat,\n    power_v0_aux x 0 = 1.\nProof.\n  fold_unfold_tactic power_v0_aux.\nQed.\n\nLemma fold_unfold_power_v0_aux_S :\n  forall x n' : nat,\n    power_v0_aux x (S n') = x * power_v0_aux x n'.\nProof.\n  fold_unfold_tactic power_v0_aux.\nQed.\n\nProposition power_v0_safisfies_the_specification_of_power :\n  specification_of_power power_v0.\nProof.\n  unfold specification_of_power, power_v0.\n  split.\n  - exact fold_unfold_power_v0_aux_O.\n  - exact fold_unfold_power_v0_aux_S.\nQed.\n\n(* ***** *)\n\nFixpoint power_v1_aux (x n a : nat) : nat :=\n  match n with\n  | O =>\n    a\n  | S n' =>\n    power_v1_aux x n' (x * a)\n  end.\n\nDefinition power_v1 (x n : nat) : nat :=\n  power_v1_aux x n 1.\n\nCompute (test_power power_v1).\n\nLemma fold_unfold_power_v1_aux_O :\n  forall x a : nat,\n    power_v1_aux x 0 a =\n    a.\nProof.\n  fold_unfold_tactic power_v1_aux.\nQed.\n\nLemma fold_unfold_power_v1_aux_S :\n  forall x n' a : nat,\n    power_v1_aux x (S n') a =\n    power_v1_aux x n' (x * a).\nProof.\n  fold_unfold_tactic power_v1_aux.\nQed.\n\n(* ***** *)\n\n(* Eureka lemma: *)\n\nLemma about_power_v0_aux_and_power_v1_aux :\n  forall x n a : nat,\n    power_v0_aux x n * a = power_v1_aux x n a.\nProof.\n  intros x n.\n  induction n as [ | n' IHn'].\n  - intro a.\n    rewrite -> (fold_unfold_power_v0_aux_O x).\n    rewrite -> (fold_unfold_power_v1_aux_O x a).\n    exact (Nat.mul_1_l a).\n  - intro a.\n    rewrite -> (fold_unfold_power_v0_aux_S x n').\n    rewrite -> (fold_unfold_power_v1_aux_S x n' a).\n    Check (IHn' (x * a)).\n    rewrite <- (IHn' (x * a)).\n    rewrite -> (Nat.mul_comm x (power_v0_aux x n')).\n    Check (Nat.mul_assoc).\n    symmetry.\n    exact (Nat.mul_assoc (power_v0_aux x n') x a).\nQed.\n\nTheorem power_v0_and_power_v1_are_equivalent :\n  forall x n : nat,\n    power_v0 x n = power_v1 x n.\nProof.\n  intros x n.\n  unfold power_v0, power_v1.\n  Check (about_power_v0_aux_and_power_v1_aux x n 1).\n  rewrite <- (Nat.mul_1_r (power_v0_aux x n)).\n  exact (about_power_v0_aux_and_power_v1_aux x n 1).\nQed.\n\n(* ********** *)\n\nFixpoint nat_fold_right (V : Type) (z : V) (s : V -> V) (n : nat) : V :=\n  match n with\n  | O =>\n    z\n  | S n' =>\n    s (nat_fold_right V z s n')\n  end.\n\nLemma fold_unfold_nat_fold_right_O :\n  forall (V : Type)\n         (z : V)\n         (s : V -> V),\n    nat_fold_right V z s O =\n    z.\nProof.\n  fold_unfold_tactic nat_fold_right.\nQed.\n\nLemma fold_unfold_nat_fold_right_S :\n  forall (V : Type)\n         (z : V)\n         (s : V -> V)\n         (n' : nat),\n    nat_fold_right V z s (S n') =\n    s (nat_fold_right V z s n').\nProof.\n  fold_unfold_tactic nat_fold_right.\nQed.\n\n(* ***** *)\n\nFixpoint nat_fold_left (V : Type) (z : V) (s : V -> V) (n : nat) : V :=\n  match n with\n  | O =>\n    z\n  | S n' =>\n    nat_fold_left V (s z) s n'\n  end.\n\nLemma fold_unfold_nat_fold_left_O :\n  forall (V : Type)\n         (z : V)\n         (s : V -> V),\n    nat_fold_left V z s O =\n    z.\nProof.\n  fold_unfold_tactic nat_fold_left.\nQed.\n\nLemma fold_unfold_nat_fold_left_S :\n  forall (V : Type)\n         (z : V)\n         (s : V -> V)\n         (n' : nat),\n    nat_fold_left V z s (S n') =\n    nat_fold_left V (s z) s n'.\nProof.\n  fold_unfold_tactic nat_fold_left.\nQed.\n\n(* ********** *)\n\nDefinition power_v0_alt (x n : nat) : nat :=\n  nat_fold_right nat 1 (fun ih => x * ih) n.\n\nCompute (test_power power_v0_alt).\n\nProposition power_v0_alt_safisfies_the_specification_of_power :\n  specification_of_power power_v0_alt.\nProof.\n  unfold specification_of_power, power_v0_alt.\n  split.\n  - intro x.\n    rewrite -> (fold_unfold_nat_fold_right_O nat 1 (fun ih : nat => x * ih)).\n    reflexivity.\n  - intros x n'.\n    rewrite -> (fold_unfold_nat_fold_right_S nat 1 (fun ih : nat => x * ih) n').\n    reflexivity.\nQed.\n\nCorollary power_v0_and_power_v0_alt_are_equivalent :\n  forall x n : nat,\n    power_v0 x n = power_v0_alt x n.\nProof.\n  intros x n.\n  Check (there_is_at_most_one_function_satisfying_the_specification_of_power\n           power_v0\n           power_v0_alt\n           power_v0_safisfies_the_specification_of_power\n           power_v0_alt_safisfies_the_specification_of_power\n           x\n           n).\n  exact (there_is_at_most_one_function_satisfying_the_specification_of_power\n           power_v0\n           power_v0_alt\n           power_v0_safisfies_the_specification_of_power\n           power_v0_alt_safisfies_the_specification_of_power\n           x\n           n).\nQed.\n\n(* ***** *)\n\nDefinition power_v1_alt (x n : nat) : nat :=\n  nat_fold_left nat 1 (fun ih => x * ih) n.\n\nCompute (test_power power_v1_alt).\n\nLemma power_v1_and_power_v1_alt_are_equivalent_aux :\n  forall x n a : nat,\n    power_v1_aux x n a = nat_fold_left nat a (fun ih : nat => x * ih) n.\nProof.\n  intros x n.\n  induction n as [ | n' IHn'].\n  - intro a.\n    rewrite -> (fold_unfold_power_v1_aux_O x a).\n    rewrite -> (fold_unfold_nat_fold_left_O nat a (fun ih : nat => x * ih)).\n    reflexivity.\n  - intro a.\n    rewrite -> (fold_unfold_power_v1_aux_S x n' a).\n    rewrite -> (fold_unfold_nat_fold_left_S nat a (fun ih : nat => x * ih) n').\n    Check (IHn' (x * a)).\n    exact (IHn' (x * a)).\nQed.\n\n    \nProposition power_v1_and_power_v1_alt_are_equivalent :\n  forall x n : nat,\n    power_v1 x n = power_v1_alt x n.\nProof.\n  intros x n.\n  unfold power_v1, power_v1_alt.\n  exact (power_v1_and_power_v1_alt_are_equivalent_aux x n 1).\nQed.\n\n(* ********** *)\n\nLemma about_nat_fold_left :\n  forall (V : Type) (z : V) (s : V -> V) (n : nat),\n    nat_fold_left V (s z) s n = s (nat_fold_left V z s n).\nProof.\nAdmitted.\n\nLemma about_nat_fold_right :\n  forall (V : Type) (z : V) (s : V -> V) (n : nat),\n    nat_fold_right V (s z) s n = s (nat_fold_right V z s n).\nProof.\nAdmitted.\n\nTheorem folding_left_and_right :\n  forall (V : Type) (z : V) (s : V -> V) (n : nat),\n    nat_fold_left V z s n = nat_fold_right V z s n.\nProof.\n  intros V z s n.\n  revert z.\n  induction n as [ | n' IHn'].\n  - intro z.\n    rewrite -> (fold_unfold_nat_fold_left_O V z s).\n    rewrite -> (fold_unfold_nat_fold_right_O V z s).\n    reflexivity.\n  - intro z.\n    rewrite -> (fold_unfold_nat_fold_left_S V z s n').\n    rewrite -> (fold_unfold_nat_fold_right_S V z s n').\n(*\n    rewrite -> (about_nat_fold_left V z s n').\n    rewrite -> (IHn' z).\n    reflexivity.\n*)\n    rewrite <- (about_nat_fold_right V z s n').\n    Check (IHn' (s z)).\n    exact (IHn' (s z)).\nQed.\n    \n(* ********** *)\n\nCorollary power_v0_and_power_v1_are_equivalent_alt :\n  forall x n : nat,\n    power_v0 x n = power_v1 x n.\nProof.\n  intros x n.\n  rewrite -> (power_v0_and_power_v0_alt_are_equivalent x n).\n  rewrite -> (power_v1_and_power_v1_alt_are_equivalent x n).\n  unfold power_v0_alt, power_v1_alt.\n  symmetry.\n  exact (folding_left_and_right nat 1 (fun ih : nat => x * ih) n).\nQed.\n\n(* ********** *)\n\n(* Exercise 2a *)\n\nDefinition recursive_specification_of_multiplication (mul : nat -> nat -> nat) :=\n    ((forall j : nat,\n         mul O j = 0)\n     /\\\n     (forall i' j : nat,\n         mul (S i') j = j + (mul i' j))).\n\nProposition there_is_at_most_one_function_satisfying_the_recursive_specification_of_multiplication :\n  forall mul1 mul2 : nat -> nat -> nat,\n    recursive_specification_of_multiplication mul1 ->\n    recursive_specification_of_multiplication mul2 ->\n    forall i j : nat,\n      mul1 i j = mul2 i j.\nProof.\n  intros mul1 mul2.\n  unfold recursive_specification_of_multiplication.\n  intros [S1_O S1_S] [S2_O S2_S] i j.\n  induction i as [ | i' IHi'].\n  - rewrite -> (S2_O j).\n    exact (S1_O j).\n  - rewrite -> (S2_S i' j).\n    rewrite -> (S1_S i' j).\n    rewrite -> IHi'.\n    reflexivity.\nQed.\n    \nDefinition test_mul (candidate: nat -> nat -> nat) : bool :=\n  (candidate 0 0 =n= 0)\n  &&\n  (candidate 0 1 =n= 0)\n  &&\n  (candidate 1 0 =n= 0)\n  &&\n  (candidate 1 1 =n= 1)\n  &&\n  (candidate 1 2 =n= 2)\n  &&\n  (candidate 2 1 =n= 2)\n  &&\n  (candidate 2 2 =n= 4)\n  &&\n  (candidate 2 3 =n= 6)\n  &&\n  (candidate 3 2 =n= 6)\n  &&\n  (candidate 6 4 =n= 24)\n  &&\n  (candidate 4 6 =n= 24)\n  (* etc. *)\n  .\n\nFixpoint mul_v0_aux (i j : nat) : nat :=\n  match i with\n    | O => 0\n    | S i' => j + (mul_v0_aux i' j)\n  end.\n\nLemma fold_unfold_mul_v0_aux_O :\n  forall j : nat,\n    mul_v0_aux O j = 0.\nProof.\n  fold_unfold_tactic mul_v0_aux.\nQed.\n\nLemma fold_unfold_mul_v0_aux_S :\n  forall i' j : nat,\n    mul_v0_aux (S i') j = j + (mul_v0_aux i' j).\nProof.\n  fold_unfold_tactic mul_v0_aux.\nQed.\n\nDefinition mul_v0 (i j : nat) : nat :=\n  mul_v0_aux i j.\n\nProposition mul_v0_safisfies_the_specification_of_multiplication :\n  recursive_specification_of_multiplication mul_v0.\nProof.\n  unfold recursive_specification_of_multiplication, mul_v0.\n  split.\n  - exact fold_unfold_mul_v0_aux_O.\n  - exact fold_unfold_mul_v0_aux_S.\nQed.\n\nCompute (test_mul mul_v0).\n\nDefinition mul_v0_alt (i j : nat) : nat :=\n  nat_fold_right nat 0 (fun ih => j + ih) i.\n\nProposition mul_v0_alt_safisfies_the_specification_of_multiplication :\n  recursive_specification_of_multiplication mul_v0_alt.\nProof.\n  unfold recursive_specification_of_multiplication, mul_v0_alt.\n  split.\n  - intro j.\n    rewrite -> (fold_unfold_nat_fold_right_O nat 0 (fun ih : nat => j + ih)).\n    reflexivity.\n  - intros i' j.\n    rewrite -> (fold_unfold_nat_fold_right_S nat 0 (fun ih : nat => j + ih) i').\n    reflexivity.\nQed.\n\nCompute (test_mul mul_v0_alt).\n\nCorollary mul_v0_and_mul_v0_alt_are_equivalent :\n  forall i j : nat,\n    mul_v0 i j = mul_v0_alt i j.\nProof.\n  - intros i j.\n    Check (there_is_at_most_one_function_satisfying_the_recursive_specification_of_multiplication\n             mul_v0\n             mul_v0_alt\n             mul_v0_safisfies_the_specification_of_multiplication\n             mul_v0_alt_safisfies_the_specification_of_multiplication\n             i\n             j\n          ).\n    exact (there_is_at_most_one_function_satisfying_the_recursive_specification_of_multiplication\n             mul_v0\n             mul_v0_alt\n             mul_v0_safisfies_the_specification_of_multiplication\n             mul_v0_alt_safisfies_the_specification_of_multiplication\n             i\n             j\n          ).\nQed.\n\n(* Exercise 2b *)\n\nFixpoint mul_v1_aux (i j a : nat) : nat :=\n  match i with\n    | O => a\n    | S i' => mul_v1_aux i' j (j + a)\n  end.\n\nLemma fold_unfold_mul_v1_aux_O :\n  forall j a : nat,\n    mul_v1_aux O j a = a.\nProof.\n  fold_unfold_tactic mul_v1_aux.\nQed.\n\nLemma fold_unfold_mul_v1_aux_S :\n  forall i' j a : nat,\n    mul_v1_aux (S i') j a = mul_v1_aux i' j (j + a).\nProof.\n  fold_unfold_tactic mul_v1_aux.\nQed.\n\nDefinition mul_v1 (i j : nat) : nat :=\n  mul_v1_aux i j 0.\n\nCompute (test_mul mul_v1).\n\nDefinition mul_v1_alt (i j : nat) : nat :=\n  nat_fold_left nat 0 (fun ih => j + ih) i.\n\nCompute (test_mul mul_v1_alt).\n\nLemma mul_v1_and_mul_v1_alt_are_equivalent_aux :\n  forall i j a : nat,\n    mul_v1_aux i j a = nat_fold_left nat a (fun ih : nat => j + ih) i.\nProof.\n  intros i j.\n  induction i as [ | i' IHi'].\n  - intro a.\n    rewrite -> (fold_unfold_mul_v1_aux_O j a).\n    rewrite -> (fold_unfold_nat_fold_left_O nat a (fun ih : nat => j + ih)).\n    reflexivity.\n  - intro a.\n    rewrite -> (fold_unfold_mul_v1_aux_S i' j a).\n    rewrite -> (fold_unfold_nat_fold_left_S nat a (fun ih : nat => j + ih) i').\n    Check (IHi' (j + a)).\n    exact (IHi' (j + a)).\nQed.\n\nProposition mul_v1_and_mul_v1_alt_are_equivalent :\n  forall i j : nat,\n    mul_v1 i j = mul_v1_alt i j.\nProof.\n  intros i j.\n  unfold mul_v1, mul_v1_alt.\n  exact (mul_v1_and_mul_v1_alt_are_equivalent_aux i j 0).\nQed.\n\n(* Exercise 2c *)\n\nCorollary mul_v0_and_mul_v1_are_equivalent_alt :\n  forall i j : nat,\n    mul_v0 i j = mul_v1 i j.\nProof.\n  intros i j.\n  rewrite -> (mul_v0_and_mul_v0_alt_are_equivalent i j).\n  rewrite -> (mul_v1_and_mul_v1_alt_are_equivalent i j).\n  unfold mul_v0_alt, mul_v1_alt.\n  symmetry.\n  exact (folding_left_and_right nat 0 (fun ih : nat => j + ih) i).\nQed.\n\n\n(* ********** *)\n\n(* Exercise 3 *)\n\n(* The sumtorial function *)\n\nDefinition specification_of_sum_n (sum_n :  nat -> nat) :=\n  (sum_n 0 = 0)\n  /\\\n  (forall n' : nat,\n      sum_n (S n') = (S n') + sum_n n').\n\n(* ***** *)\n\n\nProposition there_is_at_most_one_function_satisfying_the_specification_of_sum_n :\n  forall sum_n1 sum_n2 :  nat -> nat,\n    specification_of_sum_n sum_n1 ->\n    specification_of_sum_n sum_n2 ->\n    forall n : nat,\n      sum_n1 n = sum_n2 n.\nProof.\n  intros sum_n1 sum_n2.\n  unfold specification_of_sum_n.\n  intros [S1_O S1_S] [S2_O S2_S] n.\n  induction n as [ | n' IHn']. \n  - rewrite -> (S2_O).\n    exact (S1_O).\n  - rewrite -> (S1_S n').\n    rewrite -> (S2_S n').\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n(* ***** *)\n\nDefinition test_sum_n (candidate : nat  -> nat) : bool :=\n  (candidate 1 =? 1) &&\n  (candidate 2 =? 3) &&\n  (candidate 3 =? 6) &&\n  (candidate 10 =? 55)\n.\n\n(* ***** *)\n\nFixpoint sum_n_v0_aux (n : nat) : nat :=\n  match n with\n  | O =>\n    0\n  | S n' =>\n    S n' + (sum_n_v0_aux n')\n  end.\n\nDefinition sum_n_v0 (n : nat) : nat :=\n  sum_n_v0_aux n.\n \nCompute (test_sum_n sum_n_v0). \n\nLemma fold_unfold_sum_n_v0_aux_O :\n   sum_n_v0_aux 0 = 0.\nProof.\n  fold_unfold_tactic sum_n_v0_aux.\nQed.\n\nLemma fold_unfold_sum_n_v0_aux_S :\n  forall n' : nat,\n    sum_n_v0_aux (S n') = (S n') + sum_n_v0_aux n'.\nProof.\n  fold_unfold_tactic sum_n_v0_aux.\nQed.\n\nProposition sum_n_v0_safisfies_the_specification_of_sum_n :\n  specification_of_sum_n sum_n_v0.\nProof.\n  unfold specification_of_sum_n, sum_n_v0.\n  split.\n  - exact fold_unfold_sum_n_v0_aux_O.\n  - exact fold_unfold_sum_n_v0_aux_S.\nQed.\n\n(* ***** *)\n\nFixpoint sum_n_v1_aux (n a : nat) : nat :=\n  match n with\n  | O =>\n    a\n  | S n' =>\n    sum_n_v1_aux n' ( (S n') + a)\n  end.\n\nDefinition sum_n_v1 (n : nat) : nat :=\n  sum_n_v1_aux n 0.\n \nCompute (test_sum_n sum_n_v1).\n\nLemma fold_unfold_sum_n_v1_aux_O :\n  forall a : nat,\n    sum_n_v1_aux 0 a =\n    a.\nProof.\n  fold_unfold_tactic sum_n_v1_aux.\nQed.\n\nLemma fold_unfold_sum_n_v1_aux_S :\n  forall n' a : nat,\n    sum_n_v1_aux (S n') a =\n    sum_n_v1_aux n' ((S n') + a).\nProof.\n  fold_unfold_tactic sum_n_v1_aux.\nQed.\n\n(* ***** *)\n\n(* Eureka lemma: *)\n\nLemma about_sum_n_v0_aux_and_sum_n_v1_aux :\n  forall n a : nat,\n    sum_n_v0_aux n + a = sum_n_v1_aux n a.\nProof.\n  intro n.\n  induction n as [ | n' IHn'].\n  - intro a.\n    rewrite -> (fold_unfold_sum_n_v0_aux_O).\n    rewrite -> (fold_unfold_sum_n_v1_aux_O a).\n    Search(0+_).\n    exact (Nat.add_0_l a).\n  - intro a.\n    rewrite -> (fold_unfold_sum_n_v0_aux_S n').\n    rewrite -> (fold_unfold_sum_n_v1_aux_S n' a).\n    Check (IHn' ((S n') + a)).\n    rewrite <- (IHn' ((S n') + a)).\n    rewrite -> (Nat.add_comm (S n') (sum_n_v0_aux n')).\n    Check (Nat.add_assoc).\n    symmetry.\n    exact (Nat.add_assoc (sum_n_v0_aux n') (S n') a).\nQed.\n\nTheorem sum_n_v0_and_sum_n_v1_are_equivalent :\n  forall n : nat,\n    sum_n_v0 n = sum_n_v1 n.\nProof.\n  intros n.\n  unfold sum_n_v0, sum_n_v1.\n  Check (about_sum_n_v0_aux_and_sum_n_v1_aux n 0).\n  rewrite <- (Nat.add_0_r (sum_n_v0_aux n)).\n  exact (about_sum_n_v0_aux_and_sum_n_v1_aux n 0).\nQed.\n\n(* ********** *)\n(* ********** *)\n\n(* Remark: partitially inspired by Section 2.4 of Prof Danvy's paper \"Folding left and right over Peano numbers\" *)\n\n(* <OD> *)\n\n(*\nDefinition sum_n_v0_alt_helper (n : nat) : nat * nat :=\n  nat_fold_right (nat * nat)\n                 (0,0)\n                 (fun c => let (ind, sum) := c in (ind + 1, sum + ind + 1))\n                 n.\n*)\n\nDefinition sum_n_v0_alt_helper (n : nat) : nat * nat :=\n  nat_fold_right (nat * nat)\n                 (0, 0)\n                 (fun c => let (ind, sum) := c in (S ind, S ind + sum))\n                 n.\n\nDefinition sum_n_v0_alt (n : nat) : nat :=\n   let (ind, sum) := sum_n_v0_alt_helper n in sum.\n     \nCompute (test_sum_n sum_n_v0_alt).\n\nLemma about_sum_n_v0_alt_helper :\n  forall n ind res: nat,\n    nat_fold_right (nat * nat)\n                   (0, 0)\n                   (fun c => let (ind, sum) := c in (S ind, S ind + sum))\n                   n = (ind, res) ->\n    n = ind.\nProof.\n  intro n.\n  induction n as [ | n' IHn'].\n  - intros ind res.\n    rewrite -> (fold_unfold_nat_fold_right_O (nat * nat) (0, 0) (fun c : nat * nat => let (ind, sum) := c in (S ind, S ind + sum))).\n    intros H_tmp.\n    injection H_tmp as H_ind H_res.\n    exact H_ind.\n  - intros ind res.\n    rewrite -> (fold_unfold_nat_fold_right_S (nat * nat) (0, 0) (fun c : nat * nat => let (ind, sum) := c in (S ind, S ind + sum)) n').\n    case (nat_fold_right (nat * nat) (0, 0) (fun c : nat * nat => let (ind0, sum) := c in (S ind0, S ind0 + sum)) n') as (x, y).\n    intro H_tmp.\n    injection H_tmp as H_ind H_res.\n    rewrite <- H_ind.\n    Check (IHn' x y).\n    Check (IHn' x y (eq_refl (x, y))).\n    rewrite <- (IHn' x y (eq_refl (x, y))).\n    reflexivity.\nQed.\n\n(* NO PROBLEM HERE *)\n\nProposition sum_n_v0_alt_safisfies_the_specification_of_sum_n :\n  specification_of_sum_n sum_n_v0_alt.\nProof.\n  unfold specification_of_sum_n, sum_n_v0_alt.\n  Check specification_of_sum_n.\n  split.     \n  - destruct (sum_n_v0_alt_helper 0) as (_, sum_n_O).\n    rewrite <- (sum_n_v0_alt 0).\n    Check sum_n_O.\n    Check (fold_unfold_nat_fold_right_O (nat * nat) (_,sum_n_O) (fun c => let (_, sum_n_O) := c in (_, sum_n_O +_+ 1))).\n=======\n  unfold specification_of_sum_n, sum_n_v0_alt, sum_n_v0_alt_helper.\n  split.     \n  - rewrite -> (fold_unfold_nat_fold_right_O (nat * nat) (0, 0) (fun c : nat * nat => let (ind, sum) := c in (S ind, S ind + sum))).\n    reflexivity.\n>>>>>>> 98035c6356c96242f70ffd7a101fd8d1c8d19331\n=======\n  unfold specification_of_sum_n, sum_n_v0_alt, sum_n_v0_alt_helper.\n  split.     \n  - rewrite -> (fold_unfold_nat_fold_right_O (nat * nat) (0, 0) (fun c : nat * nat => let (ind, sum) := c in (S ind, S ind + sum))).\n    reflexivity.\n>>>>>>> 98035c6356c96242f70ffd7a101fd8d1c8d19331\n  - intro n'.\n    rewrite -> (fold_unfold_nat_fold_right_S (nat * nat) (0, 0) (fun c : nat * nat => let (ind, sum) := c in (S ind, S ind + sum)) n').\n    destruct (nat_fold_right (nat * nat) (0, 0) (fun c : nat * nat => let (ind, sum) := c in (S ind, S ind + sum)) n') as (ind, res) eqn:H_witness.\n    Check (about_sum_n_v0_alt_helper n' ind res H_witness).\n    rewrite <- (about_sum_n_v0_alt_helper n' ind res H_witness).\n    reflexivity.\nQed.\n\nCorollary sum_n_v0_and_sum_n_v0_alt_are_equivalent :\n  forall n : nat,\n    sum_n_v0 n = sum_n_v0_alt n.\nProof.\n  intros n.\n  exact (there_is_at_most_one_function_satisfying_the_specification_of_sum_n\n           sum_n_v0\n           sum_n_v0_alt\n           sum_n_v0_safisfies_the_specification_of_sum_n\n           sum_n_v0_alt_safisfies_the_specification_of_sum_n\n           n).\nQed.\n(* ***** *)\n\n\nDefinition sum_n_v1_alt_helper (n : nat) : nat * nat :=\n  nat_fold_left (nat * nat)\n                 (0,0)\n                 (fun c => let (ind, sum) := c in (ind + 1, sum + ind + 1))\n                 n.\nDefinition sum_n_v1_alt (n : nat) : nat :=\n   let (ind,sum) := sum_n_v0_alt_helper n in sum.\n     \nCompute (test_sum_n sum_n_v1_alt).\n\nLemma sum_n_v1_and_sum_n_v1_alt_are_equivalent_aux :\n  forall n a : nat,\n    sum_n_v1_aux n a = sum_n_v1_alt n.\nProof.\nAdmitted.\n\nProposition sum_n_v1_and_sum_n_v1_alt_are_equivalent :\n  forall n : nat,\n    sum_n_v1 n = sum_n_v1_alt n.\nProof.\n  intro  n.\n  unfold sum_n_v1, sum_n_v1_alt.\n  exact (sum_n_v1_and_sum_n_v1_alt_are_equivalent_aux n 0).\nQed.\n\n(* ********** *)\n\nCorollary sum_n_v0_and_sum_n_v1_are_equivalent_alt :\n  forall n : nat,\n    sum_n_v0 n = sum_n_v1 n.\nProof.\n  intros n.\n  rewrite -> (sum_n_v0_and_sum_n_v0_alt_are_equivalent n).\n  rewrite -> (sum_n_v1_and_sum_n_v1_alt_are_equivalent n). \n  unfold sum_n_v0_alt, sum_n_v1_alt.\n  symmetry.\n  reflexivity.\nQed.\n\n\n(* end of week-05_folding-left-and-right-over-peano-numbers.v *)\n", "meta": {"author": "zhang-liu-official", "repo": "Coq-Code", "sha": "4f3dfe2aaa6d6515fdce280189fa0599447f7aff", "save_path": "github-repos/coq/zhang-liu-official-Coq-Code", "path": "github-repos/coq/zhang-liu-official-Coq-Code/Coq-Code-4f3dfe2aaa6d6515fdce280189fa0599447f7aff/5_folding-left-and-right-over-peano-numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738010682209, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.6904594035814827}}
{"text": "(* ***************************************************************** *)\n(*                                                                   *)\n(* Released: 2021/05/17.                                             *)\n(* Due: 2021/05/21, 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 (Assignment8.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 \"Assignment9.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.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\nRequire Import PL.RTClosure PL.Imp.\n\n(* ################################################################# *)\n(** * Task 1: Mix typed expressions *)\n\nModule Task1.\nLocal Open Scope Z.\n\n(** This is our definition of mix typed expressions. In this task, you need to\n    answer questions about their evaluation process and type checking results. *)\n\nDefinition var: Type := nat.\n\nDefinition state: Type := var -> Z.\n\nInductive mexp : Type :=\n  | MNum (n : Z)\n  | MId (X : var)\n  | MPlus (a1 a2 : mexp)\n  | MMinus (a1 a2 : mexp)\n  | MMult (a1 a2 : mexp)\n  | MTrue\n  | MFalse\n  | MEq (a1 a2 : mexp)\n  | MLe (a1 a2 : mexp)\n  | MNot (b : mexp)\n  | MAnd (b1 b2 : mexp)\n.\n\n(** Here is some coercion and notations for pretty printing. *)\n\nDeclare Scope mexp.\nDelimit Scope mexp with mexp.\nLocal Open Scope mexp.\n\nCoercion MNum : Z >-> mexp.\nCoercion MId : var >-> mexp.\nNotation \"x + y\" := (MPlus x y) (at level 50, left associativity) : mexp.\nNotation \"x - y\" := (MMinus x y) (at level 50, left associativity) : mexp.\nNotation \"x * y\" := (MMult x y) (at level 40, left associativity) : mexp.\nNotation \"x <= y\" := (MLe x y) (at level 70, no associativity) : mexp.\nNotation \"x == y\" := (MEq x y) (at level 70, no associativity) : mexp.\nNotation \"x && y\" := (MAnd x y) (at level 40, left associativity) : mexp.\nNotation \"'!' b\" := (MNot b) (at level 39, right associativity) : mexp.\nNotation \"[ x ; .. ; y ]\" := (@cons mexp x .. (@cons mexp y (@nil mexp)) ..).\n\nModule Task1_Examples.\n\nParameter X: var.\nParameter S: var.\n  \n(** Suppose [X] and [S] are program variables and [st: state] satisfies:\n\n    - [st X = 0]\n\n    - [st S = 0].\n\n    Please describe the evaluation process of\n\n    - [S + (X == 0)]\n\n    on [st] using a Coq list. Specifically, this Coq list must demonstrate the\n    result of every step (see lecture notes: run time error 2) from the\n    beginning to the end. The ending expression can be a evaluation result (an\n    integer constant or a boolean constant) or a stuck state (no step can be\n    taken since an error occurs).\n*)\n\nDefinition my_answer_1: list mexp :=\n  [ S + (X == 0);\n    0 + (X == 0);\n    0 + (0 == 0);\n    0 + MTrue;\n    0 + 1;\n    1 ]\n.\n\n(** Suppose [X] and [S] are program variables and [st: state] satisfies:\n\n    - [st X = 0]\n\n    - [st S = 0].\n\n    Please describe the evaluation process of\n\n    - [S && (X == 0)]\n\n    on [st] using a Coq list. Specifically, this Coq list must demonstrate the\n    result of every step (see lecture notes: run time error 2) from the\n    beginning to the end. The ending expression can be a evaluation result (an\n    integer constant or a boolean constant) or a stuck state (no step can be\n    taken since an error occurs).\n*)\n\nDefinition my_answer_2: list mexp :=\n  [ S && (X == 0);\n    0 && (X == 0) ]\n.\n\nEnd Task1_Examples.\n\n(** **** Exercise: 2 stars, standard *)\n\nParameter P: var.\nParameter X: var.\n\n(** Suppose [P] and [X] are program variables and [st: state] satisfies:\n\n    - [st P = 0]\n\n    - [st X = 1].\n\n    Please describe the evaluation process of\n\n    - [(P == 0) && (X && (X + 1))]\n\n    on [st] using a Coq list. Specifically, this Coq list must demonstrate the\n    result of every step (see lecture notes: run time error 2) from the\n    beginning to the end. The ending expression can be a evaluation result (an\n    integer constant or a boolean constant) or a stuck state (no step can be\n    taken since an error occurs).\n*)\n\nDefinition my_answer_1_1: list mexp := \n  [ (P == 0) && (X && (X + 1));\n    (0 == 0) && (X && (X + 1));\n    MTrue && (X && (X + 1));\n    X && (X + 1);\n    1 && (X + 1) ]\n.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard *)\n\n(** This time, consider a slightly different situation. Suppose [st: state]\n    satisfies:\n\n    - [st P = 1]\n\n    - [st X = 1].\n\n    Please describe the evaluation process of\n\n    - [(P == 0) && (X && (X + 1))]\n\n    on [st] using a Coq list. Specifically, this Coq list must demonstrate the\n    result of every step (see lecture notes: run time error 2) from the\n    beginning to the end. The ending expression can be a evaluation result (an\n    integer constant or a boolean constant) or a stuck state (no step can be\n    taken since an error occurs).\n*)\n\nDefinition my_answer_1_2: list mexp :=\n  [ (P == 0) && (X && (X + 1));\n    (1 == 0) && (X && (X + 1));\n    MFalse && (X && (X + 1));\n    MFalse ]\n.\n(** [] *)\n\n(** **** Exercise: 1 star, standard *)\n\n(** Does [(P == 0) && (X && (X + 1))] type check?\n    1. Yes. 2. No.\n*)\n\nDefinition my_answer_1_3: Z := 2.\n(** [] *)\n\n(** **** Exercise: 1 star, standard *)\n\n(** Does [(P == 0) && (P == 1) && (X && (X + 1))] type check?\n    1. Yes. 2. No.\n*)\n\nDefinition my_answer_1_4: Z := 2.\n(** [] *)\n\nImport ListNotations.\n\n(** **** Exercise: 1 star, standard *)\n\n(** Which of the following statements are correct about [mexp]'s small step\n    semantics and type checking function?\n\n    1. Its semantics is type safe since it has the progress property and\n       the preservation property.\n\n    2. Every legal expression (according the type checking function) can be\n       evaluated safely to the end on any program state and the evaluation\n       process will either end in an integer constant or a boolean constant.\n\n    3. If an expression [m: mexp] can be safely evaluated on a state [st],\n       then [m] must be a well-typed expression.\n\n    4. If an expression [m: mexp] can be safely evaluated on any state [st],\n       then [m] must be a well-typed expression.\n\n    This is a multiple-choice problem. You should use an ascending Coq list to\n    describe your answer, e.g. [1; 2; 3], [1; 3], [2]. *)\n\nDefinition my_answer_1_5: list Z := [1; 2].\n(** [] *)\n\nEnd Task1.\n\n(* ################################################################# *)\n(** * Task 2: Nondeterministic programs *)\n\nModule Task2.\n\n(** Consider the programming language with [CChoice] we discussed in class.\n    Please determine whether sample programs satisfy one of the following\n    properties or not. Here are the list of properties.\n\n    - 1. The program has deterministic behavior and will terminate.\n\n    - 2. The program has nondeterministic behavior but will always terminate.\n\n    - 3. The program has deterministic behavior and will not terminate.\n\n    - 4. It is possible for the program to terminate and also possible not to\n         terminate . *)\n\n(** **** Exercise: 1 star, standard *)\n\n(** The program [c] is:\n        [[\n            CChoice (X ::= 1) (X ::= 2)\n        ]]\n    The initial state [st] satisfies:\n        [[\n            st Y = 0\n        ]]\n    for any program variable [Y]. Which property listed in the beginning of this\n    task is true for executing [c] from [st] according to the denotational\n    semantics? *)\n\nDefinition my_answer_2_1: Z := 2.\n(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n(** [] *)\n\n(** **** Exercise: 1 star, standard *)\n\n(** The program [c] is:\n        [[\n            CChoice (X ::= 1) (X ::= X + 1)\n        ]]\n    The initial state [st] satisfies:\n        [[\n            st Y = 0\n        ]]\n    for any program variable [Y]. Which property listed in the beginning of this\n    task is true for executing [c] from [st] according to the small step\n    semantics? *)\n\nDefinition my_answer_2_2: Z := 2.\n(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n(** [] *)\n\n(** **** Exercise: 1 star, standard *)\n\n(** The program [c] is:\n        [[\n            X ::= 1000;;\n            While (! (X == 0)) Do\n               CChoice (X ::= X - 1) (Skip)\n            EndWhile\n        ]]\n    The initial state [st] satisfies:\n        [[\n            st Y = 0\n        ]]\n    for any program variable [Y]. Which property listed in the beginning of this\n    task is true for executing [c] from [st] according to the small step\n    semantics? *)\n\nDefinition my_answer_2_3: Z := 4.\n(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n(** [] *)\n\n(** **** Exercise: 1 star, standard *)\n\n(** The program [c] is:\n        [[\n            X ::= 1001;;\n            While (! (X == 0)) Do\n               CChoice (X ::= X - 2) (Skip)\n            EndWhile\n        ]]\n    The initial state [st] satisfies:\n        [[\n            st Y = 0\n        ]]\n    for any program variable [Y]. Which property listed in the beginning of this\n    task is true for executing [c] from [st] according to the denotational\n    semantics? *)\n\nDefinition my_answer_2_4: Z := 3.\n(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n(** [] *)\n\nEnd Task2.\n\n(* ################################################################# *)\n(** * Task 3: Pointers and addresses *)\n\nModule OptF.\n\nDefinition add {A: Type} (f g: A -> option Z): A -> option Z :=\n  fun st =>\n    match f st, g st with\n    | Some v1, Some v2 => Some (v1 + v2)\n    | _, _ => None\n    end.\n\nDefinition sub {A: Type} (f g: A -> option Z): A -> option Z :=\n  fun st =>\n    match f st, g st with\n    | Some v1, Some v2 => Some (v1 - v2)\n    | _, _ => None\n    end.\n\nDefinition mul {A: Type} (f g: A -> option Z): A -> option Z :=\n  fun st =>\n    match f st, g st with\n    | Some v1, Some v2 => Some (v1 * v2)\n    | _, _ => None\n    end.\n\nEnd OptF.\n\nModule Task3.\nLocal Open Scope Z.\n\n(** The following are the programming language we discussed in class. We paste\n    its integer expression, its denotational semantics and its small step\n    semantics. *)\n\nDefinition var: Type := nat.\n\nInductive aexp : Type :=\n  | ANum (n : Z)\n  | AId (X : var)\n  | APlus (a1 a2 : aexp)\n  | AMinus (a1 a2 : aexp)\n  | AMult (a1 a2 : aexp)\n  | ADeref (a1: aexp)\n  | AAddr (a1: aexp).\n\nDefinition var2addr (X: var): Z := Z.of_nat X + 1.\n\nDefinition state: Type := Z -> option Z.\n\nFixpoint aevalR (a: aexp): state -> option Z :=\n  match a with\n  | ANum n => fun _ => Some n\n  | AId X => fun st => st (var2addr X)\n  | APlus a1 a2 => OptF.add (aevalR a1) (aevalR a2)\n  | AMinus a1 a2  => OptF.sub (aevalR a1) (aevalR a2)\n  | AMult a1 a2 => OptF.mul (aevalR a1) (aevalR a2)\n  | ADeref a1 => fun st =>\n                   match aevalR a1 st with\n                   | Some n1 => st n1\n                   | None => None\n                   end\n  | AAddr a1 => aevalL a1\n  end\nwith aevalL (a: aexp): state -> option Z :=\n  match a with\n  | ANum n => fun _ => None\n  | AId X => fun st => Some (var2addr X)\n  | APlus a1 a2 => fun _ => None\n  | AMinus a1 a2  => fun _ => None\n  | AMult a1 a2 => fun _ => None\n  | ADeref a1 => aevalR a1\n  | AAddr a1 => fun _ => None\n  end.\n\nInductive aexp_halt: aexp -> Prop :=\n  | AH_num : forall n, aexp_halt (ANum n).\n\nInductive astepR : state -> aexp -> aexp -> Prop :=\n  | ASR_Id : forall st X n,\n      st (var2addr X) = Some n ->\n      astepR st\n        (AId X) (ANum n)\n\n  | ASR_Plus1 : forall st a1 a1' a2,\n      astepR st\n        a1 a1' ->\n      astepR st\n        (APlus a1 a2) (APlus a1' a2)\n  | ASR_Plus2 : forall st a1 a2 a2',\n      aexp_halt a1 ->\n      astepR st\n        a2 a2' ->\n      astepR st\n        (APlus a1 a2) (APlus a1 a2')\n  | ASR_Plus : forall st n1 n2,\n      astepR st\n        (APlus (ANum n1) (ANum n2)) (ANum (n1 + n2))\n\n  | ASR_Minus1 : forall st a1 a1' a2,\n      astepR st\n        a1 a1' ->\n      astepR st\n        (AMinus a1 a2) (AMinus a1' a2)\n  | ASR_Minus2 : forall st a1 a2 a2',\n      aexp_halt a1 ->\n      astepR st\n        a2 a2' ->\n      astepR st\n        (AMinus a1 a2) (AMinus a1 a2')\n  | ASR_Minus : forall st n1 n2,\n      astepR st\n        (AMinus (ANum n1) (ANum n2)) (ANum (n1 - n2))\n\n  | ASR_Mult1 : forall st a1 a1' a2,\n      astepR st\n        a1 a1' ->\n      astepR st\n        (AMult a1 a2) (AMult a1' a2)\n  | ASR_Mult2 : forall st a1 a2 a2',\n      aexp_halt a1 ->\n      astepR st\n        a2 a2' ->\n      astepR st\n        (AMult a1 a2) (AMult a1 a2')\n  | ASR_Mult : forall st n1 n2,\n      astepR st\n        (AMult (ANum n1) (ANum n2)) (ANum (n1 * n2))\n\n  | ASR_DerefStep : forall st a1 a1',\n      astepR st\n        a1 a1' ->\n      astepR st\n        (ADeref a1) (ADeref a1')\n  | ASR_Deref : forall st n n',\n      st n = Some n' ->\n      astepR st\n        (ADeref (ANum n)) (ANum n')\n\n  | ASR_AddrStep : forall st a1 a1',\n      astepL st\n        a1 a1' ->\n      astepR st\n        (AAddr a1) (AAddr a1')\n  | ASR_Addr : forall st n,\n      astepR st\n        (AAddr (ADeref (ANum n))) (ANum n)\nwith astepL : state -> aexp -> aexp -> Prop :=\n  | ASL_Id: forall st X,\n      astepL st\n        (AId X) (ADeref (ANum (var2addr X)))\n\n  | ASL_DerefStep: forall st a1 a1',\n      astepR st\n        a1 a1' ->\n      astepL st\n        (ADeref a1) (ADeref a1')\n.\n\n(** Then, we can define multi-step relations like we did before. *)\n\nDefinition multi_astepR st := clos_refl_trans (astepR st).\nDefinition multi_astepL st := clos_refl_trans (astepL st).\n\n(** The following tasks require you to show congruence properties of small step\n    relations for [AAddr]. Remember that you can use [induction_n1],\n    [induction_1n], [etransitivity_n1] and [etransitivity_1n] to automate your\n    proof. *)\n\n(** **** Exercise: 2 stars, standard (multi_congr_AAddr) *)\nLemma multi_congr_AAddr: forall st a a',\n  multi_astepL st a a' ->\n  multi_astepR st (AAddr a) (AAddr a').  \nProof.\n  intros.\n  induction_1n H.\n  + reflexivity.\n  + etransitivity_1n.\n    - constructor.\n      exact H.\n    - exact IHrt.\nQed.\n(** [] *)\n\n(** How to formally state the connection between the denotational semantics and\n    the small step semantics? One direction should be:\n        [[\n           forall st a n,\n             aevalR a st = Some n -> multi_astepR st a (ANum n)\n        ]]\n    and\n        [[\n           forall st a n,\n             aevalL a st = Some n -> multi_astepL st a (ADeref (ANum n)).\n        ]]\n    We can prove these properties by induction over [a]. The next task requires\n    you to prove the induction step for [AAddr]. *)\n\n(** **** Exercise: 2 stars, standard (semantic_equiv_aexp_AAddr) *)\nLemma semantic_equiv_aexp_AAddr: forall st a\n  (IH: forall n: Z, aevalL a st = Some n -> multi_astepL st a (ADeref (ANum n))),\n  (forall n: Z, aevalR (AAddr a) st = Some n -> multi_astepR st (AAddr a) (ANum n)).\nProof.\n  intros.\n  simpl in H.\n  specialize (IH n H).\n  apply multi_congr_AAddr in IH.\n  etransitivity_n1.\n  + exact IH.\n  + constructor.\nQed.\n(** [] *)\n\nEnd Task3.\n\n(* 2021-05-17 20:13 *)\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/Assignment8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.690459394318771}}
{"text": "Require Types.Iso.\nRequire Fin.\n\nSet Asymmetric Patterns.\n\n(** A type family which is isomorphic to Fin.t, but defined in\n    terms of simpler types by recursion, and is a little bit\n    easier to work with. *)\nFixpoint Fin (n : nat) : Set := match n with\n  | 0 => False\n  | S n' => (True + Fin n')%type\n  end.\n\n(** Fin and Fin.t are isomorphic for every size. *)\nTheorem finIso (n : nat) : Iso.T (Fin.t n) (Fin n).\nProof.\ninduction n.\n- eapply Iso.Build_T.\n  intros a. inversion a.\n  intros b. inversion b. \n- \nrefine (\n{| Iso.to := fun x => (match x in Fin.t n'\n  return (S n = n') -> Fin (S n) with\n   | Fin.F1 _ => fun _ => inl I\n   | Fin.FS n' x' => fun pf => inr (Iso.to IHn (eq_rect n' Fin.t x' _ (eq_sym (eq_add_S _ _ pf))))\n   end) eq_refl\n ; Iso.from := fun x => match x with\n   | inl I => Fin.F1\n   | inr x' => Fin.FS (Iso.from IHn x')\n   end\n|}).\nintros a.\nRequire Import Program.\ndependent destruction a; simpl.\nreflexivity. rewrite Iso.from_to. reflexivity.\nintros b. destruct b. destruct t. reflexivity.\n  simpl. rewrite Iso.to_from. reflexivity.\nGrab Existential Variables.\nintros bot. contradiction.\nintros f0. inversion f0.\nDefined.\n\nLemma botNull (A : Type) : Iso.T A (A + False).\nProof.\nrefine (\n{| Iso.to   := inl\n ; Iso.from := fun x => match x with\n    | inl x' => x'\n    | inr bot => False_rect A bot\n   end\n|}).\nreflexivity.\nintros b. destruct b. reflexivity. contradiction.\nDefined.\n\nFixpoint split (m : nat)\n  : forall (n : nat), Fin.t (m + n) -> (Fin.t m + Fin.t n).\nrefine (\n  match m return (forall (n : nat), Fin.t (m + n) -> (Fin.t m + Fin.t n)) with\n  | 0 => fun _ => inr\n  | S m' => fun n x => (match x as x0 in Fin.t k \n    return forall (pf : k = (S m' + n)), (Fin.t (S m') + Fin.t n) with\n    | Fin.F1 _ => fun pf => inl Fin.F1\n    | Fin.FS n' x' => fun pf => _\n    end) eq_refl\n  end).\nsimpl in pf.\napply eq_add_S in pf.\nrewrite pf in x'.\nrefine (match split m' n x' with\n  | inl a => inl (Fin.FS a)\n  | inr b => inr b\n  end).\nDefined.\n\nLemma splitL : forall {m n : nat} {x : Fin.t m},\n  split m n (Fin.L n x) = inl x.\nProof.\nintros m. induction m; intros n x.\n- inversion x.\n- dependent destruction x; simpl.\n  + reflexivity.\n  + rewrite (IHm n x). reflexivity.\nQed.\n\nLemma splitR : forall {m n : nat} {x : Fin.t n},\n  split m n (Fin.R m x) = inr x.\nProof.\nintros m. induction m; intros n x; simpl.\n- reflexivity.\n- rewrite (IHm n x). reflexivity.\nQed.\n\nLemma splitInj : forall {m n : nat} {x y : Fin.t (m + n)},\n  split m n x = split m n y -> x = y.\nProof.\nintros m; induction m; intros n x y Heq.\n- inversion Heq. reflexivity.\n- dependent destruction x; dependent destruction y.\n  + reflexivity.\n  + simpl in Heq. destruct (split m n y); inversion Heq.\n  + simpl in Heq. destruct (split m n x); inversion Heq.\n  + apply f_equal. simpl in Heq. apply IHm.\n    destruct (split m n x) eqn:sx;\n    destruct (split m n y) eqn:sy.\n    apply f_equal. \n    assert (forall (A B : Type) (x y : A), @inl A B x = @inl A B y -> x = y).\n    intros A B x0 y0 Heqn. inversion Heqn. reflexivity.\n    apply H in Heq. apply Fin.FS_inj in Heq. assumption.\n    inversion Heq. inversion Heq. apply f_equal. injection Heq. trivial.\nQed.\n\nFixpoint splitMult (m : nat)\n  : forall (n : nat), Fin.t (m * n) -> (Fin.t m * Fin.t n) \n  := match m return (forall (n : nat), Fin.t (m * n) -> (Fin.t m * Fin.t n)) with\n  | 0 => fun _ => Fin.case0 _\n  | S m' => fun n x => match split n (m' * n) x with\n    | inl a => (Fin.F1, a)\n    | inr b => match splitMult m' n b with\n      | (x, y) => (Fin.FS x, y)\n      end\n    end\n  end.\n\n\nLemma finPlus : forall {m n : nat},\n  Iso.T (Fin.t m + Fin.t n) (Fin.t (m + n)).\nProof.\nintros m n.\nrefine (\n{| Iso.to := fun x => match x with\n   | inl a => Fin.L n a\n   | inr b => Fin.R m b\n   end\n ; Iso.from := split m n\n|}).\nintros. destruct a; simpl. induction m; simpl.\n- inversion t.\nRequire Import Program.\n- dependent destruction t; simpl.\n  + reflexivity.\n  + rewrite IHm. reflexivity.\n- induction m; simpl. reflexivity. rewrite IHm. reflexivity.\n- induction m; intros; simpl.\n  + reflexivity.\n  + dependent destruction b; simpl. reflexivity.\n     pose proof (IHm b).\n     destruct (split m n b) eqn:seqn;\n     simpl; rewrite H; reflexivity.\nQed.\n\nLemma finMult : forall {m n : nat},\n  Iso.T (Fin.t m * Fin.t n) (Fin.t (m * n)).\nProof.\nintros m n.\nrefine (\n{| Iso.to := fun x => match x with (a, b) => Fin.depair a b end\n ; Iso.from := splitMult m n\n|}).\nintros p. destruct p.\ninduction m; simpl.\n- inversion t.\n- dependent destruction t; simpl.\n  + rewrite splitL. reflexivity.\n  + rewrite splitR. rewrite (IHm t). reflexivity.\n\n- induction m; intros b; simpl.\n  + inversion b.\n  + destruct (split n (m * n) b) eqn:seqn.\n    * simpl. rewrite <- splitL in seqn. \n      apply splitInj in seqn. symmetry. assumption.\n    * pose proof (IHm t). assert (b = Fin.R n t).\n      apply (@splitInj n (m * n)). \n      rewrite seqn. symmetry. apply splitR.\n      rewrite H0. simpl.\n      destruct (splitMult m n t) eqn:smeqn.\n      simpl. rewrite <- H. reflexivity.\nDefined.\n\nFixpoint pow (b e : nat) : nat := match e with\n  | 0 => 1\n  | S e' => b * pow b e'\n  end.\n\nTheorem finPow : forall {e b : nat},\n  Iso.T (Fin.t (pow b e)) (Fin.t e -> Fin.t b).\nProof.\nintros e. induction e; intros n; simpl.\n- eapply Iso.Trans. apply finIso. simpl. eapply Iso.Trans.\n  eapply Iso.Sym. apply botNull. eapply Iso.Trans. Focus 2.\n  eapply Iso.FuncCong. eapply Iso.Sym. apply finIso. apply Iso.Refl.\n  simpl. apply Iso.Sym. apply Iso.FFunc.\n- eapply Iso.Trans. eapply Iso.Sym. apply finMult.\n  eapply Iso.Trans. Focus 2. eapply Iso.FuncCong.\n  eapply Iso.Sym. apply finIso. apply Iso.Refl.\n  simpl. eapply Iso.Trans. Focus 2. eapply Iso.Sym. eapply Iso.PlusFunc.\n  apply Iso.TFunc. eapply Iso.Trans. eapply Iso.FuncCong.\n  eapply Iso.Sym. apply finIso. apply Iso.Refl. eapply Iso.Sym.\n  apply IHe. apply Iso.Refl.\nQed.\n\n(** A universe of codes for finite types. *)\nInductive U : Set :=\n  | U0    : U\n  | U1    : U\n  | UPlus : U -> U -> U\n  | UTimes : U -> U -> U\n  | UFunc : U -> U -> U\n  | UFint : nat -> U\n  | UFin : nat -> U.\n\n(** The types which the codes of U represent. *)\nFixpoint ty (t : U) : Set := match t with\n  | U0 => False\n  | U1 => True\n  | UPlus a b => (ty a + ty b)%type\n  | UTimes a b => (ty a * ty b)%type\n  | UFunc a b => ty a -> ty b\n  | UFint n => Fin.t n\n  | UFin n => Fin n\n  end.\n\n(** For every code for a finite type, we give its cardinality as\n    a natural number. *)\nFixpoint Ucard (t : U) : nat := match t with\n  | U0 => 0\n  | U1 => 1\n  | UPlus a b => Ucard a + Ucard b\n  | UTimes a b => Ucard a * Ucard b\n  | UFunc a b => pow (Ucard b) (Ucard a)\n  | UFint n => n\n  | UFin n => n\n  end.\n    \n(** Each type in the finite universe is isomorphic to the Fin.t\n    family whose size is determined by the cardinality function above. *)\nTheorem finChar (t : U) : Iso.T (ty t) (Fin.t (Ucard t)).\nProof.\ninduction t; simpl.\n- apply Iso.Sym. apply (finIso 0).\n- apply Iso.Sym. apply (@Iso.Trans _ (Fin 1)). apply (finIso 1).\n  apply Iso.Sym. apply botNull.\n- eapply Iso.Trans. eapply Iso.PlusCong. eassumption.\n  eassumption.\n  apply finPlus.\n- eapply Iso.Trans. eapply Iso.TimesCong; try eassumption.\n  apply finMult.\n- eapply Iso.Trans. eapply Iso.FuncCong; try eassumption.\n  apply Iso.Sym. apply finPow.\n- apply Iso.Refl.\n- apply Iso.Sym. apply finIso.\nQed.\n\n(** A type for evidence that a type is finite: a type is finite if\n    any of the following hold:\n    a) it is True\n    b) it is False\n    c) it is a sum of finite types\n    d) it is isomorphic to a finite type\n\n    This is not minimal. We could have replaced b) and c) with the condition\n    e) it is the sum of True with a finite type\n       (this is the analog of Successor)\n    But this definition is simple so I like it.\n*)\n\nInductive T : Type -> Type :=\n  | F0 : T False\n  | FS : forall {A}, T A -> T (True + A)\n  | FIso : forall {A B}, T A -> Iso.T A B -> T B\n.\n\nFixpoint card {A} (fin : T A) := match fin with\n  | F0 => 0\n  | FS _ n => S (card n)\n  | FIso _ _ x iso => card x\n  end.\n\nDefinition fin (n : nat) : T (Fin.t n).\nProof. eapply FIso. Focus 2. eapply Iso.Sym. eapply finIso.\ninduction n; simpl.\n- apply F0.\n- apply FS. assumption.\nQed.\n\nDefinition finU (A : U) : T (ty A).\nProof. \neapply FIso. Focus 2. eapply Iso.Sym. apply finChar.\napply fin.\nQed.\n\nDefinition iso {A : Type} (fin : T A) : Iso.T A (Fin.t (card fin)).\nProof.\ninduction fin.\n-  apply (finChar U0).\n- apply Iso.Sym. eapply Iso.Trans. \n  apply finIso. simpl. apply Iso.PlusCong. apply Iso.Refl.\n  eapply Iso.Trans. eapply Iso.Sym. apply finIso. apply Iso.Sym.\n  assumption.\n- eapply Iso.Trans. eapply Iso.Sym. eassumption.\n  assumption. \nQed.\n\nDefinition true : T True := finU U1.\n\nDefinition plus {A B : Type} (fa : T A) (fb : T B) : T (A + B).\nProof.\neapply (@FIso (Fin.t (card fa + card fb))). apply (finU (UFint _)).\neapply Iso.Trans. eapply Iso.Sym. apply finPlus.\neapply Iso.PlusCong; eapply Iso.Sym; apply iso.\nQed.\n\nLemma finiteSig {A : Type} (fa : T A)\n  : forall {B : A -> Type}, \n  (forall (x : A), T (B x))\n  -> sigT (fun S => (T S * Iso.T (sigT B) S)%type).\nProof.\ninduction fa; intros b fb.\n- exists False. split. constructor. apply Iso.FSig.\n- pose proof (IHfa (fun x => b (inr x)) (fun x => fb (inr x))).\n  destruct X. destruct p.\n  exists (b (inl I) + x)%type. constructor. apply plus. apply fb. \n  assumption.\n  apply Iso.PlusSig. apply (@Iso.TSig (fun x => b (inl x))). \n  assumption.\n- pose (Iso.Sym t).\n  pose proof (IHfa (fun x => b (Iso.from t0 x))\n                   (fun x => fb (Iso.from t0 x))).\n  destruct X. destruct p.\n  exists x. split. assumption.\n  eapply Iso.Trans. Focus 2. apply t2.\n  apply Iso.sigmaProp.\nDefined.\n\n(** Sigma types are closed under finiteness. *)\nTheorem Sig {A : Type} {B : A -> Type} \n  : T A \n  -> (forall (x : A), T (B x))\n  -> T (sigT B).\nProof.\nintros fA fB.\npose proof (finiteSig fA fB).\ndestruct X. destruct p.\neapply FIso. apply t.\napply Iso.Sym. assumption.\nDefined.\n\n(** Product types are closed under finiteness. *)\nTheorem times {A B : Type} : T A -> T B -> T (A * B).\nProof.\nintros fa fb.\neapply FIso. Focus 2. eapply Iso.Sym. eapply Iso.sigTimes.\napply Sig. assumption. apply (fun _ => fb).\nDefined.\n\nLemma finiteMapped {A : Type} (fa : T A)\n  : forall {B : Type}, T B -> sigT (fun S => (T S * Iso.T (A -> B) S)%type).\nProof.\ninduction fa.\n- intros. exists True. apply (true, Iso.FFunc).\n- intros B fb.\n  destruct (IHfa B fb).\n  exists (B * x)%type.\n  destruct p.\n  apply (times fb t , Iso.PlusFunc Iso.TFunc t0).\n- intros B1 fb.\n  destruct (IHfa B1 fb).\n  destruct p.\n  exists x.\n  split.\n  assumption.  \n  eapply Iso.Trans.\n  eapply Iso.Sym.\n  apply (Iso.FuncCong t (Iso.Refl B1)).\n  assumption.\nDefined.\n\n(** Functions are closed under finiteness. *)\nTheorem func {A B : Type} : T A -> T B -> T (A -> B).\nProof.\nintros FA FB.\npose proof (finiteMapped FA FB).\ndestruct X.\ndestruct p.\neapply FIso.\neassumption.\napply Iso.Sym.\nassumption.\nDefined.\n\n(** Any finite type has decidable equality. *)\nTheorem eq_dec {A : Type} : T A -> forall a b : A, {a = b} + {a <> b}.\nProof.\nintros finite.\ninduction finite; intros; try (decide equality).\n- destruct a, b. \n  + destruct t, t0. auto. \n  + destruct t. right. congruence.\n  + destruct t. right. congruence.\n  + pose proof (IHfinite a a0). destruct H; [left | right]; congruence.\n- eapply Iso.eq_dec; eassumption.\nQed.\n\nFixpoint elementsV {A} (fin : T A) : Vector.t A (card fin) := \n  match fin in T A' return Vector.t A' (card fin) with\n  | F0 => Vector.nil False\n  | FS _ n => Vector.cons _ (inl I) _ (Vector.map inr (elementsV n))\n  | FIso _ _ x iso => let xs := elementsV x in\n     Vector.map (Iso.to iso) xs\n  end.\n\n\nTheorem fin_dec_subset {A} (fin : T A) {P : A -> Prop}\n  : (forall a, {P a} + {~ P a}) -> T (sig P).\nProof.\ngeneralize dependent P. induction fin; intros P decP.\n- eapply FIso. apply F0.\n  eapply Iso.Trans. apply Iso.iso_true_subset. \n  apply Iso.subsetSelf; firstorder.\n- eapply FIso. 2: eapply Iso.Sym; apply Iso.subset_sum_distr.\n  destruct (decP (inl I)).\n  + eapply FIso. Focus 2.\n    eapply Iso.PlusCong. apply (Iso.subsetSelf (fun _ => True)); intros; auto.\n    destruct a. tauto. destruct p0, q. reflexivity.\n    apply proof_irrelevance. apply Iso.Refl.\n    eapply FIso. Focus 2. eapply Iso.PlusCong.\n    apply Iso.iso_true_subset. apply Iso.Refl.\n    apply FS. apply IHfin. intros. apply decP.  \n  + eapply FIso. Focus 2.\n    eapply Iso.PlusCong. apply (Iso.subsetSelf (fun _ => False)); intros; auto.\n    destruct a. tauto. contradiction. destruct b. congruence.\n    apply Iso.Refl. eapply FIso. Focus 2. eapply Iso.PlusCong.\n    apply Iso.iso_false_subset. apply Iso.Refl.\n    eapply FIso. Focus 2.\n    eapply Iso.Trans. Focus 2. apply Iso.PlusComm.\n    apply botNull. apply IHfin. intros; apply decP.\n- eapply FIso. apply (IHfin (fun a => P (Iso.to t a))). \n  intros. apply decP. apply Iso.subset with t; firstorder.\n  rewrite Iso.to_from. assumption. apply proof_irrelevance.\n  apply proof_irrelevance.\nDefined.", "meta": {"author": "bmsherman", "repo": "finite", "sha": "63706fa4898aa05296c4290be1dba646b2c512d1", "save_path": "github-repos/coq/bmsherman-finite", "path": "github-repos/coq/bmsherman-finite/finite-63706fa4898aa05296c4290be1dba646b2c512d1/Finite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6904593931746467}}
{"text": "Fixpoint Fin n : Type :=\n  match n with\n  | 0 => Empty_set\n  | S m => unit + Fin m\n  end.\n\nFixpoint nat_of_Fin {n} : Fin n -> nat :=\n  match n with\n  | 0 => fun e =>\n    match e with\n    end\n  | S m => fun i =>\n    match i with\n    | inl _ => 0\n    | inr j => S (nat_of_Fin j)\n    end\n  end.\n\n(* TODO: change option to have better names*)\nFixpoint avoid {n} : Fin (S n) -> Fin (S n) ->\n  option (Fin n) :=\n  match n with\n  | 0 => fun _ _ => None\n  | S m => fun i j  =>\n    match i with\n    | inl _ =>\n      match j with\n      | inl _ => None\n      | inr j' => Some j'\n      end\n    | inr i' =>\n      match j with\n      | inl _ => Some (inl tt)\n      | inr j' =>\n        match avoid i' j' with\n        | Some k => Some (inr k)\n        | None => None\n        end\n      end\n    end\n  end.\n\nLemma avoid_refl : forall n (i : Fin (S n)),\n  avoid i i = None.\nProof.\n  induction n; intro.\n  - reflexivity.\n  - destruct i.\n    + reflexivity.\n    + simpl.\n      rewrite IHn.\n      reflexivity.\nQed.\n\nFixpoint shift {n} : Fin (S n) -> Fin n -> Fin (S n) :=\n  match n with\n  | 0 => fun _ e =>\n    match e with\n    end\n  | S m => fun k i =>\n    match k with\n    | inl _ => inr i\n    | inr k' =>\n      match i with\n      | inl _ => inl tt\n      | inr i' => inr (shift k' i')\n      end\n    end\n  end.\n\nLemma avoid_shift {n} (i : Fin (S n))\n  (j : Fin n) : avoid i (shift i j) = Some j.\nProof.\n  induction n.\n  - destruct j.\n  - simpl.\n    destruct i.\n    + reflexivity.\n    + destruct j.\n      * destruct u; reflexivity.\n      * now rewrite IHn.\nQed.\n\nFixpoint Fin_of_nat {m} (n : nat) : Fin (n + S m) :=\n  match n with\n  | 0 => inl tt\n  | S k => inr (Fin_of_nat k)\n  end.\n", "meta": {"author": "emarzion", "repo": "lc-self-interpreter", "sha": "d3ec0e13c4e725f886d81d7d9e17dc06e4584e0f", "save_path": "github-repos/coq/emarzion-lc-self-interpreter", "path": "github-repos/coq/emarzion-lc-self-interpreter/lc-self-interpreter-d3ec0e13c4e725f886d81d7d9e17dc06e4584e0f/src/Util/Fin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.6904593926117265}}
{"text": "Require Import \"misc\".\n\nTheorem sig_extract_ok :\n  forall (A:Set) (P:A -> Prop) (y:sig P), P (sig_extract A P y).\n  intros.\n  destruct y.\n  auto.\nDefined.\n\nRequire Import ZArith.\nPrint lt_dec.\nOpen Scope Z_scope.\n\nParameter\n  div_pair :\n    forall a b:Z,\n      0 < b ->\n      {p : Z * Z | a = fst p * b + snd p  /\\ 0 <= snd p < b}.\n\nDefinition div : forall a b:Z,\n    0 < b -> Z * Z.\n  intros.\n  apply (div_pair a b).\n  auto.\nDefined.\n\nClose Scope Z_scope.\n\nDefinition sig_rec_simple (A:Set) (P: A -> Prop) (B : Set) :\n  (forall x, P x -> B) -> (sig P) -> B.\n  intros.\n  destruct H0.\n  eauto.\nDefined.\n\nDefinition eqdec (A : Set) := forall a b : A, {a = b} + {a <> b}.\n\nDefinition nat_eq_dec : eqdec nat.\n  unfold eqdec.\n  induction a,b;auto with arith.\nDefined.\n\nDefinition nat_3_rect :\n  forall P : nat -> Type,\n    P O ->\n      P 1 ->\n        P 2 ->\n          (forall n, P n -> P (S (S (S n)))) -> \n            forall n, P n.\n  intros.\n  assert(3 > 0).\n  omega.\n  apply (nat_n_rect (exist _ 3 H));simpl.\n  intros.\n  do 4(\n    destruct m;\n    omega||auto).\n  intros.\n  rewrite plus_comm.\n  simpl.\n  auto.\nDefined.\n\nDefinition nat_2_rect :\n  forall P : nat -> Type,\n    P O ->\n      P 1 ->\n        (forall n, P n -> P (S (S n))) -> \n          forall n, P n.\n  intros.\n  assert(2 > 0).\n  omega.\n  apply(nat_n_rect (exist _ 2 H));simpl.\n  intros.\n  do 3(\n    destruct m;\n    (omega||auto)).\n  intros.\n  rewrite plus_comm.\n  simpl.\n  auto.\nDefined.\n\nDefinition nat_4_rect :\n  forall P : nat -> Type,\n    P O ->\n      P 1 ->\n        P 2 ->\n          P 3 ->\n            (forall n, P n -> P (S(S (S (S n))))) -> \n              forall n, P n.\n  intros.\n  assert(4 > 0).\n  omega.\n  apply (nat_n_rect (exist _ 4 H));simpl.\n  intros.\n  do 5(\n    destruct m;\n    omega||auto).\n  intros.\n  rewrite plus_comm.\n  simpl.\n  auto.\nDefined.\n\nDefinition div3 (n : nat) : { r : nat | r * 3 <= n < r * 3 + 3 }.\n  induction n using nat_3_rect;\n  try(\n    econstructor;\n    instantiate( 1 := 0 );\n    omega).\n  destruct IHn.\n  econstructor.\n  instantiate( 1 := x + 1 ).\n  omega.\nDefined.\n\nFixpoint div2 (n:nat) : nat :=\n  match n with \n  | 0 => 0\n  | 1 => 0\n  | S (S p) => S (div2 p)\n  end.\n\nDefinition mod2 (n : nat) : { m : nat | n = (div2 n) + m }.\n  induction n using nat_2_rect.\n  repeat econstructor.\n  repeat econstructor.\n  destruct IHn.\n  simpl.\n  eapply (exist _).\n  instantiate( 1 := x + 1 ).\n  omega.\nQed.\n\nFixpoint fib(n : nat) : nat :=\n  match n with\n  | O => 1\n  | S n' =>\n      match n' with\n      | O => 1\n      | S n'' => (fib n') + (fib n'')\n      end\n  end.\n\nFixpoint fib_pair (n:nat) : nat * nat :=\n  match n with\n  | O => (1, 1)\n  | S p => match fib_pair p with\n           | (x, y) => (y, x + y)\n           end\n  end.\n\nDefinition linear_fib (n:nat) := fst (fib_pair n).\n\nLemma fib_pair_correct : forall n:nat, fib_pair n = (fib n, fib (S n)).\n  induction n.\n  auto.\n  simpl.\n  rewrite IHn.\n  f_equal.\n  destruct n.\n  auto.\n  rewrite <- plus_assoc.\n  f_equal.\n  simpl.\n  omega.\nQed.\n\nGoal forall n, fib n = linear_fib n.\n  unfold linear_fib.\n  intros.\n  rewrite fib_pair_correct.\n  auto.\nQed.\n\nGoal forall n, (sig_extract _ _ (div3 n)) <= n.\n  intros.\n  remember(div3 n).\n  destruct s.\n  simpl.\n  omega.\nQed.\n\nTheorem div3_3 : (sig_extract _ _ (div3 3)) = 1.\n  unfold sig_extract.\n  remember (div3 3).\n  destruct s.\n  repeat(omega||destruct x).\nQed.\n\nTheorem div3_S : forall n, (sig_extract _ _ (div3 (S (S (S n))))) = S (sig_extract _ _ (div3 n)).\n  intros.\n  remember(div3 (S (S (S n)))).\n  remember(div3 n).\n  destruct s.\n  destruct s0.\n  induction n using nat_3_rect;\n  simpl;\n  omega.\nQed.\n\nDefinition mod3 (n : nat) : { m : nat | n = (sig_extract _ _ (div3 n)) + m }.\n  induction n using nat_3_rect;\n  try destruct IHn;\n  repeat econstructor.\n  rewrite div3_S.\n  instantiate(1 := x + 2).\n  omega.\nDefined.\n\nDefinition div2_mod2 : \n  forall n:nat, {q:nat & {r:nat | n = 2*q + r /\\ r <= 1}}.\n  intros.\n  induction n using nat_2_rect.\n  econstructor.\n  econstructor.\n  instantiate( 1 := 0 ).\n  instantiate( 1 := 0 ).\n  omega.\n  econstructor.\n  econstructor.\n  instantiate( 1 := 1 ).\n  instantiate( 1 := 0 ).\n  omega.\n  destruct IHn.\n  destruct s.\n  destruct a.\n  econstructor.\n  econstructor.\n  instantiate( 1 := x0 ).\n  instantiate( 1 := x + 1 ).\n  omega.\nQed.\n\nFixpoint plus' (n m:nat){struct m} : nat :=\n  match m with \n  | O => n\n  | S p => S (plus' n p) \n  end.\n\nTheorem plus'_O_n : forall n, plus' 0 n = n.\n  intros.\n  induction n;\n  simpl;\n  auto.\nQed.\n\nHint Resolve plus'_O_n.\n\nTheorem plus'_assoc : forall n m p : nat, plus' n (plus' m p) = plus' (plus' n m) p.\n  assert(forall n m, plus' (S m) n = S (plus' m n)).\n  intros.\n  induction n;\n  simpl;\n  auto.\n  intros.\n  induction m;\n  simpl;\n  auto.\n  rewrite H.\n  simpl.\n  rewrite IHm.\n  auto.\nQed.\n\nFixpoint plus'' (n m:nat) {struct m} : nat :=\n  match m with 0 =>  n \n      | S p => plus'' (S n) p \n  end.\n\nTheorem plus''_Sn_m m : forall n, plus'' (S n) m = S (plus'' n m).\n  induction m.\n  simpl;\n  auto.\n  intros.\n  apply IHm.\nQed.\n\nHint Resolve plus''_Sn_m plus'_assoc.\n\nGoal forall n m p : nat, plus'' n (plus'' m p) = plus'' (plus'' n m) p.\n  assert(forall n m, plus'' n m = plus' n m).\n  intros.\n  induction m.\n  auto.\n  simpl.\n  rewrite <- IHm.\n  auto.\n  intros.\n  repeat rewrite H.\n  auto.\nQed.\n\n", "meta": {"author": "DKXXXL", "repo": "CoqArt", "sha": "ae8f577a618aeb7182c4478642a9d5ce4b289b46", "save_path": "github-repos/coq/DKXXXL-CoqArt", "path": "github-repos/coq/DKXXXL-CoqArt/CoqArt-ae8f577a618aeb7182c4478642a9d5ce4b289b46/Chapter9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.6904201557701295}}
{"text": "Require Import List Permutation Factorial Arith.\nRequire Import Lia Setoid.\nImport ListNotations.\n\n(* see also:\n  - https://github.com/clucas26e4/List_Permutation\n  - https://github.com/math-comp/math-comp/blob/master/mathcomp/ssreflect/seq.v#L4326\n*)\n\n(* TODO: remove when https://github.com/coq/coq/pull/17082 is released *)\nSection flat_map.\nLemma concat_length A l:\n  length (concat l) = list_sum (map (@length A) l).\nProof.\n  induction l; [reflexivity|].\n  simpl. rewrite app_length.\n  f_equal. assumption.\nQed.\n\nLemma flat_map_length A B (f: A -> list B) l:\n  length (flat_map f l) = list_sum (map (fun x => length (f x)) l).\nProof.\n  rewrite flat_map_concat_map, concat_length, map_map. reflexivity.\nQed.\n\nCorollary flat_map_constant_length A B c (f: A -> list B) l:\n  (forall x, In x l -> length (f x) = c) -> length (flat_map f l) = (length l) * c.\nProof.\n  intro H. rewrite flat_map_length.\n  induction l; [reflexivity|].\n  simpl. rewrite IHl, H.\n  - reflexivity.\n  - left. reflexivity.\n  - intros x Hx. apply H. right. assumption.\nQed.\n\nLemma notin_app {A} a (l1 l2 : list A):\n  ~ In a l1 -> ~ In a l2 -> ~ In a (l1 ++ l2).\nProof.\n  intros H1 H2. induction l1 as [|b l1 IHl1].\n  - exact H2.\n  - cbn. intros [].\n    + apply H1. subst a. apply in_eq.\n    + apply not_in_cons in H1 as [].\n      apply IHl1; assumption.\nQed.\n\nLemma NoDup_app [A] (l1 l2 : list A):\n  NoDup l1 -> NoDup l2 -> (forall a, In a l1 -> ~ In a l2) ->\n  NoDup (l1 ++ l2).\nProof.\n  intros H1 H2 H. induction l1 as [|a l1 IHl1]; [assumption|].\n  apply NoDup_cons_iff in H1 as [].\n  cbn. constructor.\n  - apply notin_app; [assumption|apply H, in_eq].\n  - apply IHl1; [assumption|].\n    intros. apply H. right. assumption.\nQed.\n\nEnd flat_map.\n\nLemma In_singleton [A : Type] (x y : A):\n  In x [y] <-> y = x.\nProof.\n  split; intro H.\n  - destruct H; [assumption | contradiction H].\n  - subst y. constructor. reflexivity.\nQed.\n\nSection factorials.\nFixpoint falling_fact n x :=\nmatch n, x with\n| 0, _ => 1\n| _, 0 => 0\n| S n', S x' => x * falling_fact n' x'\nend.\n\nFixpoint rising_fact n x :=\nmatch n with\n| 0 => 1\n| S n' => x * rising_fact n' (S x)\nend.\n\nLemma falling_fact_fact n: falling_fact n n = fact n.\nProof.\n  induction n; [reflexivity|simpl].\n  rewrite IHn. reflexivity.\nQed.\n\nLemma rising_fact_S n x:\n  rising_fact (S n) x = (x + n) * rising_fact n x.\nProof.\n  revert x. induction n; intros x.\n  - cbn. auto.\n  - remember (S n) as m. (* to avoid zealous cbn *)\n    cbn. rewrite IHn by auto.\n    subst m. cbn. lia. (* ??? *) \nQed.\n\nLemma falling_raising_fact n x:\n  n <= S x -> falling_fact n x = rising_fact n (S x-n).\nProof.\n  revert x. induction n.\n  - reflexivity.\n  - intros x H%le_S_n. rewrite rising_fact_S. destruct x.\n    + cbn. lia.\n    + cbn [falling_fact]. rewrite IHn by assumption.\n      replace (S (S x) - S n) with (S x - n) by lia.\n      rewrite Nat.sub_add by assumption. reflexivity.\nQed.\n\nLemma rising_fact_fact n: rising_fact n 1 = fact n.\nProof.\n  induction n; [ reflexivity | ].\n  rewrite rising_fact_S, IHn; constructor.\nQed.\nEnd factorials.\n\nSection permutations.\nVariable A : Type.\nImplicit Type l : list A.\n\nDefinition insert_at i x l :=\n  firstn i l ++ [x] ++ skipn i l.\n\nLemma Add_nil x l:\n  Add x [] l <-> l = [x].\nProof.\n  split; intro H.\n  - remember [] as l'. destruct H.\n    + reflexivity.\n    + discriminate Heql'.\n  - rewrite H. constructor.\nQed.\n\nLemma insert_at_length i x l:\n  length (insert_at i x l) = S (length l).\nProof.\n  unfold insert_at. autorewrite with list. cbn.\n  enough (length (firstn i l) + length (skipn i l) = length l) by lia.\n  rewrite <- app_length, firstn_skipn. reflexivity.\nQed.\n\nLemma insert_at_cons i x l a:\n  insert_at (S i) x (a :: l) = a :: insert_at i x l.\nProof. cbn. f_equal. Qed.\n\nLemma Add_insert_at x l:\n  forall l', Add x l l' <-> exists i, i <= length l /\\ l' = insert_at i x l.\nProof.\n  intro l'. split; intro H.\n  - induction H.\n    + exists 0. split; [apply Nat.le_0_l | reflexivity].\n    + destruct IHAdd as [i [Hi ->]]. exists (S i). split.\n      * cbn. apply le_n_S. assumption.\n      * cbn. f_equal.\n  - destruct H as [i [Hi H]].\n    revert Hi H. revert l l'. induction i; intros l l' Hi H.\n    + rewrite H. constructor.\n    + destruct l.\n      * exfalso. eapply Nat.nle_succ_0. exact Hi.\n      * rewrite H, insert_at_cons. constructor.\n        apply IHi; [ | reflexivity]. apply le_S_n. assumption.\nQed.\n\nDefinition additions x l :=\n  map (fun i => insert_at i x l) (seq 0 (S (length l))).\n\nLemma in_additions x l l':\n  In l' (additions x l) <-> exists i, i <= length l /\\ l' = insert_at i x l.\nProof. \n  split; intro H.\n  - apply in_map_iff in H as [i [H0 H1]]. exists i.\n    apply in_seq in H1 as [_ H1]. split.\n    + apply le_S_n. exact H1.\n    + symmetry. exact H0.\n  - apply in_map_iff. destruct H as [i [H1 H0]].\n    exists i. split.\n    + symmetry. exact H0.\n    + apply in_seq. split.\n      * apply Nat.le_0_l.\n      * apply le_n_S. exact H1.\nQed.\n\nCorollary additions_spec x:\n  forall (l l': list A), Add x l l' <-> In l' (additions x l).\nProof. intros l l'. rewrite Add_insert_at, in_additions. reflexivity. Qed.\n\nLemma seq_shift_n len start n:\n  map (Nat.add n) (seq start len) = seq (n + start) len.\nProof.\n  induction n.\n  - now rewrite map_id.\n  - cbn. now rewrite <- map_map, IHn, seq_shift.\nQed.\n\nLemma map_ext_seq {X} (f g: nat -> X) n start d:\n  (forall j, start <= j < start + n -> f (d + j) = g j) ->\n  map f (seq (start + d) n) = map g (seq start n).\nProof.\n  intro H. rewrite Nat.add_comm, <- seq_shift_n.\n  rewrite map_map. apply map_ext_in.\n  intros j ?%in_seq. apply H. assumption.\nQed.\n\nLemma additions_cons x a l:\n  additions x (a :: l) = (x::a::l)::map (cons a) (additions x l).\nProof.\n  cbn. f_equal. f_equal. rewrite map_map.\n  replace 2 with (1 + 1) by reflexivity.\n  apply map_ext_seq. reflexivity.\nQed.\n\nLemma additions_length x l:\n  length (additions x l) = S (length l).\nProof. unfold additions. now rewrite map_length, seq_length. Qed.\n\nFixpoint permutations l :=\nmatch l with\n| nil => [ nil ]\n| x::l' => flat_map (additions x) (permutations l')\nend.\n\nLemma permutations_refl l:\n  In l (permutations l).\nProof.\n  induction l; [now left|].\n  cbn. apply in_flat_map. exists l.\n  split; [assumption | now left].\nQed.\n\nLemma permutations_spec:\n  forall l l', Permutation l l' <-> In l' (permutations l).\nProof.\n  intros l l'. split; intro H.\n  - revert H. revert l'. induction l; intros l' H.\n    + apply Permutation_nil in H as ->. apply permutations_refl.\n    + cbn. apply in_flat_map. symmetry in H.\n      destruct (Permutation_vs_elt_inv nil _ _ H) as [l1 [l2 ->]].\n      exists (l1 ++ l2); split.\n      * apply IHl. apply Permutation_cons_app_inv with (a:=a).\n        symmetry. assumption.\n      * apply additions_spec, Add_app.\n  - revert H. revert l'. induction l; intros l' H.\n    + apply In_singleton in H as <-. constructor.\n    + cbn in H. apply in_flat_map in H as [l'' [Hl'' H%additions_spec]].\n      specialize (IHl _ Hl''). rewrite IHl. apply Permutation_Add. assumption.\nQed.\n\nTheorem permutations_fact l:\n  length (permutations l) = fact (length l).\nProof.\n  induction l.\n  - reflexivity.\n  - cbn. rewrite flat_map_constant_length with (c := S (length l)); [lia|].\n    intros x Hx%permutations_spec. rewrite additions_length.\n    f_equal. apply Permutation_length. symmetry. assumption.\nQed.\n\nTheorem permutations_NoDup l:\n  NoDup l -> NoDup (permutations l).\nProof.\n  intros H. induction H.\n  - constructor; [apply in_nil|constructor].\n  - cbn. rewrite flat_map_concat_map.\nAbort.\n\n\nEnd permutations.", "meta": {"author": "haansn08", "repo": "coq-basic-combinatorics", "sha": "391e280605c2127142bc2cec20c0b874034d936a", "save_path": "github-repos/coq/haansn08-coq-basic-combinatorics", "path": "github-repos/coq/haansn08-coq-basic-combinatorics/coq-basic-combinatorics-391e280605c2127142bc2cec20c0b874034d936a/theories/Permutations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.6904201423990128}}
{"text": "\nFrom mathcomp Require Import all_ssreflect.\n\n(* move/ の使用例 *)\n\n(* move *)\nGoal forall (P Q R : Prop),\n    (P -> Q) -> (Q -> R) -> (P -> R).\nProof.\n  move=> P Q R V1 V2.\n  move/V1/V2.\n  done.\nQed.\n\n(* move *)\nGoal forall (P Q R : Prop),\n    (P -> Q) -> (Q -> R) -> (P -> R).\nProof.\n  move=> P Q R V1 V2.\n  move/V1/V2.\n  done.\nQed.\n\nGoal forall (P Q R : Prop),\n    (P -> Q) -> (Q -> R) -> (P -> R).\nProof.\n  move=> P Q R V1 V2 HP.\n  move: (V1 HP).\n  done.\nQed.\n\nGoal forall (P Q R : Prop),\n    (P -> Q) -> (Q -> R) -> (P -> R).\nProof.\n  move=> P Q R V1 V2 HP.\n  move/V1/V2 in HP.\n  done.\nQed.\n\n(* vanilla Coq *)\nGoal forall (P Q R : Prop),\n    (P -> Q) -> (Q -> R) -> (P -> R).\nProof.\n  intros P Q R V1 V2 HP.\n  apply V1,V2 in HP.\n  exact HP.\nQed.", "meta": {"author": "morita-hm", "repo": "proofcafe", "sha": "b784a37638b6793ed0f44a5555e7738df20e1706", "save_path": "github-repos/coq/morita-hm-proofcafe", "path": "github-repos/coq/morita-hm-proofcafe/proofcafe-b784a37638b6793ed0f44a5555e7738df20e1706/syllogism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.6904201317840423}}
{"text": "Require Export P03.\n\n\n\n(** **** Exercise: 2 stars (hoare_asgn_example4)  *)\n(** Translate this \"decorated program\" into a formal proof:\n                   {{ True }} ->>\n                   {{ 1 = 1 }}\n    X ::= 1;;\n                   {{ X = 1 }} ->>\n                   {{ X = 1 /\\ 2 = 2 }}\n    Y ::= 2\n                   {{ X = 1 /\\ Y = 2 }}\n*)\n\nExample hoare_asgn_example4 :\n  {{fun st => True}} (X ::= (ANum 1);; Y ::= (ANum 2)) \n  {{fun st => st X = 1 /\\ st Y = 2}}.\nProof.\n  apply hoare_seq with (Q:= (fun st => st X = 1)); unfold hoare_triple; intros.\n  inversion H; subst. simpl. split.\n  rewrite<-H0. reflexivity.\n  reflexivity.\n  unfold hoare_triple; intros.\n  inversion H; subst. 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/10/P04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.6904201286668908}}
{"text": "From Nominal Require Export Prelude.\n\n(** *Group operations *)\nClass Neutral A := neutral: A.\n#[export] Hint Mode Neutral ! : typeclass_instances.\nNotation ɛ := neutral.\nNotation \"ɛ@{ A }\" := (@neutral A _) (only parsing): nominal_scope.\n\nClass Operator A := op: A → A → A.\n#[export] Hint Mode Operator ! : typeclass_instances.\n#[export] Instance: Params (@op) 2 := {}.\n\nInfix \"+\" := op: nominal_scope.\nNotation \"(+)\" := op (only parsing): nominal_scope.\nNotation \"(+ x )\" := (op x) (only parsing): nominal_scope.\nNotation \"( x +)\" := (λ y, op y x) (only parsing): nominal_scope.\n\nClass Inverse A := inv: A → A.\n#[export] Hint Mode Inverse ! : typeclass_instances.\n#[export] Instance: Params (@inv) 1 := {}.\n\nNotation \"- x\" := (inv x): nominal_scope.\nNotation \"(-)\" := inv (only parsing): nominal_scope.\nNotation \"x - y\" := (x + (-y))%nom: nominal_scope.\n\nClass Group (A : Type) `{Ntr: Neutral A, Opr: Operator A, Inv: Inverse A, Equiv A}: Prop := {\n  grp_setoid :> Equivalence(≡@{A});\n  grp_op_proper :> Proper ((≡@{A}) ⟹ (≡@{A}) ⟹ (≡@{A})) (+);\n  grp_inv_proper :> Proper ((≡@{A}) ⟹ (≡@{A})) (-);\n\n  grp_assoc : ∀ (x y z : A), x + (y + z) ≡@{A} (x + y) + z;\n\n  grp_left_id : ∀ (x : A), ɛ@{A} + x ≡@{A} x;\n  grp_right_id : ∀ (x : A), x + ɛ@{A} ≡@{A} x;\n\n  grp_left_inv : ∀ (x : A), (-x) + x ≡@{A} ɛ@{A};\n  grp_right_inv : ∀ (x : A), x - x ≡@{A} ɛ@{A};\n}.\n(* #[global] Hint Mode Group ! - - - -: typeclass_instances. *)\n\nArguments grp_assoc {_ _ _ _ _ Grp}: rename.\nArguments grp_left_id {_ _ _ _ _ Grp}: rename.\nArguments grp_right_id {_ _ _ _ _ Grp}: rename.\nArguments grp_left_inv {_ _ _ _ _ Grp}: rename.\nArguments grp_right_inv {_ _ _ _ _ Grp}: rename.\nArguments grp_op_proper {_ _ _ _ _ Grp}: rename.\nArguments grp_inv_proper {_ _ _ _ _ Grp}: rename.\n\nSection Properties.\nContext `{Group G}.\n\nLemma grp_inv_involutive (x: G): -(-x) ≡ x.\n    Proof with auto.\n      rewrite <-(grp_left_id x) at 2;\n       rewrite <-grp_left_inv, <-grp_assoc, grp_left_inv, grp_right_id...\n    Qed.\n\n    Corollary grp_inv_neutral: -ɛ ≡@{G} ɛ.\n    Proof with auto.\n      rewrite <-grp_left_inv at 1; rewrite grp_right_id, grp_inv_involutive...\n    Qed.\n\n    Corollary grp_inv_inj (x y: G): x ≡ y → (-x) ≡ (-y).\n    Proof. apply grp_inv_proper. Qed.\n\n    Corollary grp_inj1 (x y z: G): x ≡ y → z + x ≡ z + y.\n    Proof. intros HH; rewrite HH; auto. Qed.\n\n    Corollary grp_inj (x y z: G): x + y ≡ x + z → y ≡ z.\n    Proof. intros HH; apply grp_inj1 with (z := -x) in HH; \n      rewrite !grp_assoc,grp_left_inv,!grp_left_id in HH; assumption.\n    Qed.\n\n    Lemma perm_op_inv (x y: G): -(x + y) ≡ -y - x.\n    Proof.\n      assert (L1: (x + y) + (-(x + y)) ≡ ɛ).\n      { apply grp_right_inv. }\n      assert (L2: x + y + (- y - x) ≡ x + (y - y) - x). { rewrite !grp_assoc; reflexivity. }\n      assert (L3: (x + y) + (-y - x) ≡ ɛ).\n      { rewrite L2, grp_right_inv, grp_right_id; apply grp_right_inv. } clear L2.\n      apply grp_inj with (x := x + y); rewrite L1,L3; reflexivity.\n    Qed.    \nEnd Properties.", "meta": {"author": "fasapa", "repo": "nominal", "sha": "fa998a69041ca44315e7400c91ad59ae9556a63f", "save_path": "github-repos/coq/fasapa-nominal", "path": "github-repos/coq/fasapa-nominal/nominal-fa998a69041ca44315e7400c91ad59ae9556a63f/theories/Group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.690401500940818}}
{"text": "Require Export D.\n\n(* Subtask 1 *)\n\nTheorem double_negation_excluded_middle : 이중부정 -> 배중률.\nProof.\n  (* FILL IN HERE *)\n  intros NNPP P. apply NNPP. intros Hc.\n  eassert (~P) by (intros HP; destruct (Hc (@or_introl P (~P) HP))).\n  destruct (Hc (@or_intror P (~P) H)).\nQed.\n\n(* Natural Excluded Middle *)\nInductive nat_value :=\n| Add : nat_value -> nat_value -> nat_value\n| Mul : nat_value -> nat_value -> nat_value\n| Var : nat -> nat_value\n.\n\nInductive nat_prop :=\n| And : nat_prop -> nat_prop -> nat_prop\n| Or : nat_prop -> nat_prop -> nat_prop\n| Implies : nat_prop -> nat_prop -> nat_prop\n| Not : nat_prop -> nat_prop\n| Forall : nat -> nat -> nat_prop -> nat_prop\n| Exists : nat -> nat -> nat_prop -> nat_prop\n| Eq : nat_value -> nat_value -> nat_prop\n| Le : nat_value -> nat_value -> nat_prop\n.\n\nFixpoint nv_to_nat (nv : nat_value) (env : nat -> nat) : nat :=\n  match nv with\n  | Add nv1 nv2 => (nv_to_nat nv1 env) + (nv_to_nat nv2 env)\n  | Mul nv1 nv2 => (nv_to_nat nv1 env) * (nv_to_nat nv2 env)\n  | Var v => env v\n  end\n.\n\nFixpoint np_to_prop (np : nat_prop) (env : nat -> nat) : Prop :=\n  match np with\n  | And np1 np2 => (np_to_prop np1 env) /\\ (np_to_prop np2 env)\n  | Or np1 np2 => (np_to_prop np1 env) \\/ (np_to_prop np2 env)\n  | Implies np1 np2 => (np_to_prop np1 env) -> (np_to_prop np2 env)\n  | Not np' => ~(np_to_prop np' env)\n  | Forall x l np' =>\n    forall y, y < (env l) -> (np_to_prop np' (\n      fun n => if Nat.eqb n x then y else env n\n    ))\n  | Exists x l np' =>\n    exists y, y < (env l) /\\ (np_to_prop np' (\n      fun n => if Nat.eqb n x then y else env n\n    ))\n  | Eq nv1 nv2 => (nv_to_nat nv1 env) = (nv_to_nat nv2 env)\n  | Le nv1 nv2 => (nv_to_nat nv1 env) <= (nv_to_nat nv2 env)\n  end\n.\n\nLemma excluded_middle_np : forall (np : nat_prop) (env : nat -> nat),\n  (np_to_prop np env) \\/ ~(np_to_prop np env).\nProof.\n  induction np; intros.\n  + destruct (IHnp1 env); destruct (IHnp2 env); try (\n      right; simpl; intros [Hl Hr]; eauto; fail\n    ). left. simpl; split; eauto.\n  + destruct (IHnp1 env); destruct (IHnp2 env); try (\n      left; simpl; eauto; fail\n    ). right. simpl; intros [Hl | Hr]; eauto.\n  + destruct (IHnp2 env); try (left; simpl; intros; eauto; fail).\n    destruct (IHnp1 env).\n    - right; simpl. intro Hc. destruct (H (Hc H0)).\n    - left; simpl. intros. destruct (H0 H1).\n  + destruct (IHnp env); eauto.\n  + simpl. remember (env n0) as lim; clear Heqlim. induction lim.\n    - left; intros. inv H.\n    - specialize (IHnp (fun n0 => if Nat.eqb n0 n then lim else env n0)).\n      destruct IHlim; destruct IHnp.\n      * left; intros. inv H1; eauto.\n      * right; intros Hc. apply H0; apply Hc; eauto.\n      * right; intros Hc. apply H; intros. apply Hc; eauto.\n      * right; intros Hc. apply H; intros. apply Hc; eauto.\n  + simpl. remember (env n0) as lim; clear Heqlim. induction lim.\n    - right; intros [y [Hy _]]. inv Hy.\n    - specialize (IHnp (fun n0 => if Nat.eqb n0 n then lim else env n0)).\n      destruct IHlim; destruct IHnp.\n      * left. destruct H as [y [Hylt Heqy]]. exists y; split; eauto.\n      * left. destruct H as [y [Hylt Heqy]]. exists y; split; eauto.\n      * left. exists lim; eauto.\n      * right. intros [y [Hylt Heqy]]. inv Hylt; eauto.\n  + simpl.\n    remember (nv_to_nat n env) as x. remember (nv_to_nat n0 env) as y.\n    clear; destruct (Nat.eqb x y) eqn: EQ.\n    - left. apply eqb_refl; eauto.\n    - right. intros Hc. apply eqb_refl in Hc.\n      rewrite Hc in EQ. inv EQ.\n  + simpl.\n    remember (nv_to_nat n env) as x. remember (nv_to_nat n0 env) as y.\n    clear; destruct (Nat.leb x y) eqn: EQ.\n    - left. apply leb_refl; eauto.\n    - right. intros Hc. apply leb_refl in Hc.\n      rewrite Hc in EQ. inv EQ.\nQed.\n\n(* Subtask 2 *)\n\nTheorem excluded_middle_square : 제곱수 는 극단적이야! .\nProof.\n  (* FILL IN HERE *)\n  intros x. unfold 제곱수.\n  destruct (excluded_middle_np (\n    Exists 2 1 (Eq (Mul (Var 2) (Var 2)) (Var 0))\n  ) (fun n => match n with 0 => x | _ => S x end)); simpl in *;\n  try destruct H as [y [Hylt Heqy]]; eauto.\n  right. intros Hc. destruct Hc as [y Hy]. apply H; exists y; split; eauto.\n  clear H. apply le_prog. subst. destruct y; eauto.\n  replace (S y * S y) with (S y + y * S y) by simpl_arith.\n  remember (S y) as x; remember (y * x) as z; clear.\n  rewrite add_comm. induction z; simpl; eauto.\nQed.\n\n(* Subtask 3 *)\n\nTheorem excluded_middle_prime : 소수 는 극단적이야! .\nProof.\n  (* FILL IN HERE *)\n  intros x. unfold 소수. unfold divides.\n  destruct (excluded_middle_np (\n    And (Le (Var 2) (Var 0)) (Forall 1 0 (Implies (Le (Var 2) (Var 1)) (\n      Not (Exists 3 0 (Eq (Var 0) (Mul (Var 1) (Var 3))))\n    )))\n  ) (fun n => match n with 0 => x | _ => 2 end)); simpl in *.\n  + left. destruct H; split; eauto. intros x0 [Hx0gt Hx0lt].\n    intros [x1 Heqx1]. specialize (H0 x0 Hx0lt Hx0gt). apply H0.\n    exists x1; split; eauto. destruct x0; try destruct x0; try le_contra.\n    destruct x1; try (subst; simpl_arith; inv Hx0lt; fail).\n    subst. simpl_arith. repeat apply le_prog. clear.\n    replace (x1 + x1 + x0 + x0 * x1) with (\n      x1 + (x1 + x0 + x0 * x1)\n    ) by simpl_arith. remember (x1 + x0 + x0 * x1) as z. clear.\n    rewrite add_comm. induction z; simpl; eauto.\n  + right. intros [Hxgt Heqx]. apply H. split; eauto. intros.\n    specialize (Heqx y (conj H1 H0)). intros Hc. apply Heqx.\n    destruct Hc as [y0 [Hy01 Hy02]]. eexists; eauto.\nQed.\n", "meta": {"author": "ghudegy", "repo": "2020", "sha": "07637dd4640fec626a0c14e929cf147d30b05af4", "save_path": "github-repos/coq/ghudegy-2020", "path": "github-repos/coq/ghudegy-2020/2020-07637dd4640fec626a0c14e929cf147d30b05af4/files/excluded_middle/Method3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6903997117397895}}
{"text": "Require Import ct07.\n\nLemma inserted_sorted : forall (a0 a : nat) (l' x : list nat),\n  sorted (a0 :: l') -> sorted x -> permutation x (a :: l') -> a0 < a -> \n  sorted (a0 :: x).\nProof.\nintros; constructor; trivial.\n- apply Sorted_extends in H.\n  + assert (H3 : List.Forall (le a0) (a :: l')). \n    constructor. apply Nat.lt_le_incl; assumption. assumption.\n    assert (H4 : List.Forall (le a0) x).\n    eapply Permutation_Forall. apply Permutation_sym; exact H1. trivial.\n    destruct x; auto. constructor. apply Forall_inv in H4; auto.\n  + unfold Relations_1.Transitive; apply le_trans.\nDefined.", "meta": {"author": "jinxinglim", "repo": "coq-chain", "sha": "e237c6b5f797f2af43237b68ff599d6cc0a8d60e", "save_path": "github-repos/coq/jinxinglim-coq-chain", "path": "github-repos/coq/jinxinglim-coq-chain/coq-chain-e237c6b5f797f2af43237b68ff599d6cc0a8d60e/contributions/ct10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6903997096348177}}
{"text": "Set Implicit Arguments.\nSet Strict Implicit.\n\nSection PairWF.\n  Variables T U : Type.\n  Variable RT : T -> T -> Prop.\n  Variable RU : U -> U -> Prop.\n  \n  Inductive R_pair : T * U -> T * U -> Prop :=\n  | L : forall l l' r r',\n    RT l l' -> R_pair (l,r) (l',r')\n  | R : forall l r r',\n    RU r r' -> R_pair (l,r) (l,r').\n\n  Hypothesis wf_RT : well_founded RT.\n  Hypothesis wf_RU : well_founded RU.\n\n  Theorem wf_R_pair : well_founded R_pair.\n  Proof.\n    red. intro x.\n    destruct x. generalize dependent u.\n    apply (well_founded_ind wf_RT (fun t => forall u : U, Acc R_pair (t, u))) .\n    do 2 intro.\n\n    apply (well_founded_ind wf_RU (fun u => Acc R_pair (x,u))). intros.\n    constructor. destruct y.\n    remember (t0,u). remember (x,x0). inversion 1; subst;\n    inversion H4; inversion H3; clear H4 H3; subst; eauto.\n  Defined.\nEnd PairWF.\n\nInductive R_nat : nat -> nat -> Prop :=\n| R_S : forall n, R_nat n (S n).\n\nTheorem wf_R_nat : well_founded R_nat.\nProof.\n  red; induction a; constructor; intros.\n    inversion H.\n    inversion H; subst; auto.\nDefined.\n\nFixpoint guard A (R : A -> A -> Prop) (n : nat) (wfR : well_founded R)\n  {struct n}: well_founded R :=\n  match n with\n    | 0 => wfR\n    | S n => fun x => Acc_intro x (fun y _ => guard n (guard n wfR) y)\n  end.", "meta": {"author": "csgordon", "repo": "bedrock", "sha": "debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12", "save_path": "github-repos/coq/csgordon-bedrock", "path": "github-repos/coq/csgordon-bedrock/bedrock-debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12/src/GenRec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6903997027785528}}
{"text": "Require Import Recdef Lia ZArith.\n\nImport Pos.\n\n(** [Plus] to 1, [Minus] to -1, [ShiftPlus k] to 3k + 1, [ShiftMinus k] to 3k - 1,\n    a [ShiftZero k] to 3k. *)\nInductive Z3' : Type :=\n| Plus       : Z3'\n| Minus      : Z3'\n| ShiftPlus  : Z3' -> Z3'\n| ShiftMinus : Z3' -> Z3'\n| ShiftZero  : Z3' -> Z3'.\n\nInductive Z3 : Type :=\n| Zero    : Z3\n| Nonzero : Z3' -> Z3.\n\nCoercion Nonzero : Z3' >-> Z3.\n\nDefinition shiftMinus (n : Z3) : Z3 :=\nmatch n with\n| Zero => Minus\n| Nonzero n' => ShiftMinus n'\nend.\n\nDefinition shiftPlus (n : Z3) : Z3 :=\nmatch n with\n| Zero => Plus\n| Nonzero n' => ShiftPlus n'\nend.\n\nDefinition shiftZero (n : Z3) : Z3 :=\nmatch n with\n| Zero => Zero\n| Nonzero n' => ShiftZero n'\nend.\n\nFunction neg' (n : Z3') : Z3' :=\nmatch n with\n| Plus => Minus\n| Minus => Plus\n| ShiftPlus n' => ShiftMinus (neg' n')\n| ShiftMinus n' => ShiftPlus (neg' n')\n| ShiftZero n' => ShiftZero (neg' n')\nend.\n\nDefinition neg (n : Z3) : Z3 :=\nmatch n with\n| Zero => Zero\n| Nonzero n' => neg' n'\nend.\n\nFunction succ' (n : Z3') : Z3 :=\nmatch n with\n| Plus => ShiftMinus Plus\n| Minus => Zero\n| ShiftPlus n' =>\n  match succ' n' with\n  | Zero => Minus\n  | Nonzero n'' => ShiftMinus n''\n  end\n| ShiftMinus n' => ShiftZero n'\n| ShiftZero n' => ShiftPlus n'\nend.\n\nDefinition succ (n : Z3) : Z3 :=\nmatch n with\n| Zero => Plus\n| Nonzero n' => succ' n'\nend.\n\nDefinition pred' (n : Z3') : Z3 :=\n  neg (succ' (neg' n)).\n\nDefinition pred (n : Z3) : Z3 :=\n  neg (succ (neg n)).\n\nFunction add (n m : Z3') : Z3 :=\nmatch n with\n| Plus => succ m\n| Minus => pred m\n| ShiftPlus n' =>\n  match m with\n  | Plus => succ n\n  | Minus => pred n\n  | ShiftPlus m' => shiftMinus (succ (add n' m'))\n  | ShiftMinus m' => shiftZero (add n' m')\n  | ShiftZero m' => shiftPlus (add n' m')\n  end\n| ShiftMinus n' =>\n  match m with\n  | Plus => succ n\n  | Minus => pred n\n  | ShiftPlus m' => shiftZero (add n' m')\n  | ShiftMinus m' => shiftPlus (pred (add n' m'))\n  | ShiftZero m' => shiftMinus (add n' m')\n  end\n| ShiftZero n' =>\n  match m with\n  | Plus => shiftPlus n'\n  | Minus => shiftMinus n'\n  | ShiftPlus m' => shiftPlus (add n' m')\n  | ShiftMinus m' => shiftMinus (add n' m')\n  | ShiftZero m' => shiftZero (add n' m')\n  end\nend.\n\nFunction add' (n m : Z3) : Z3 :=\nmatch n, m with\n| Zero, _ => m\n| _, Zero => n\n| Nonzero n', Nonzero m' => add n' m'\nend.\n\nDefinition mul2 (n : Z3) : Z3 :=\n  add' n n.\n\nFunction fromPositive (p : positive) : Z3 :=\nmatch p with\n| xH => Plus\n| xI p' => succ (mul2 (fromPositive p'))\n| xO p' => mul2 (fromPositive p')\nend.\n\nFunction fromZ (n : Z) : Z3 :=\nmatch n with\n| Z0 => Zero\n| Zpos p => fromPositive p\n| Zneg p => neg (fromPositive p)\nend.\n\nFixpoint toZ' (n : Z3') : Z :=\nmatch n with\n| Plus => 1\n| Minus => -1\n| ShiftPlus n' => 1 + 3 * toZ' n'\n| ShiftMinus n' => -1 + 3 * toZ' n'\n| ShiftZero n' => 3 * toZ' n'\nend.\n\nDefinition toZ (n : Z3) : Z :=\nmatch n with\n| Zero => 0\n| Nonzero n' => toZ' n'\nend.\n\nFunction mul (n m : Z3') : Z3 :=\nmatch n with\n| Plus          => m\n| Minus         => neg' m\n| ShiftPlus n'  => add' m (shiftZero (mul n' m))\n| ShiftMinus n' => add' (neg' m) (shiftZero (mul n' m))\n| ShiftZero n'  => shiftZero (mul n' m)\nend.\n\nLemma neg'_neg' :\n  forall n : Z3', neg' (neg' n) = n.\nProof.\n  induction n as [| | n' | n' | n']; cbn; congruence.\nQed.\n\nLemma neg_neg :\n  forall n : Z3, neg (neg n) = n.\nProof.\n  destruct n; cbn.\n  - reflexivity.\n  - f_equal. apply neg'_neg'.\nQed.\n\nLemma toZ_succ' :\n  forall n : Z3', toZ (succ' n) = (1 + toZ' n)%Z.\nProof.\n  induction n as [| | n' | n' | n']; cbn [succ' toZ toZ']; try lia.\n  destruct (succ' n'); cbn [toZ toZ'] in *; lia.\nQed.\n\nLemma toZ_succ :\n  forall n : Z3, toZ (succ n) = (1 + toZ n)%Z.\nProof.\n  destruct n as [| n'].\n  - reflexivity.\n  - apply toZ_succ'.\nQed.\n\nLemma toZ_neg :\n  forall n : Z3, toZ (neg n) = (- toZ n)%Z.\nProof.\n  destruct n as [| n]; cbn.\n  - reflexivity.\n  - induction n as [| | n' | n' | n']; cbn [neg' toZ']; lia.\nQed.\n\nLemma toZ_pred :\n  forall n : Z3, toZ (pred n) = (-1 + toZ n)%Z.\nProof.\n  unfold pred.\n  intro n.\n  rewrite toZ_neg, toZ_succ, toZ_neg. lia.\nQed.\n\nLemma toZ_shiftMinus :\n  forall n : Z3, toZ (shiftMinus n) = (-1 + 3 * toZ n)%Z.\nProof.\n  destruct n as [| n']; reflexivity.\nQed.\n\nLemma toZ_shiftPlus :\n  forall n : Z3, toZ (shiftPlus n) = (1 + 3 * toZ n)%Z.\nProof.\n  destruct n as [| n']; reflexivity.\nQed.\n\nLemma toZ_shiftZero :\n  forall n : Z3, toZ (shiftZero n) = (3 * toZ n)%Z.\nProof.\n  destruct n as [| n']; reflexivity.\nQed.\n\nLemma toZ_add :\n  forall n m : Z3', toZ (add n m) = (toZ' n + toZ' m)%Z.\nProof.\n  intros.\n  functional induction add n m;\n  rewrite ?toZ_shiftMinus, ?toZ_shiftPlus, ?toZ_shiftZero, ?toZ_succ, ?toZ_pred\n  ; cbn [toZ' toZ]; lia.\nQed.\n\nLemma toZ_add' :\n  forall n m : Z3, toZ (add' n m) = (toZ n + toZ m)%Z.\nProof.\n  destruct n as [| n'], m as [| m']; cbn [toZ add'].\n  - reflexivity.\n  - reflexivity.\n  - lia.\n  - rewrite toZ_add. reflexivity.\nQed.\n\nLemma toZ_mul2 :\n  forall n : Z3, toZ (mul2 n) = (2 * toZ n)%Z.\nProof.\n  unfold mul2.\n  intros.\n  rewrite toZ_add'.\n  lia.\nQed.\n\nLemma toZ_fromPositive :\n  forall p : positive, toZ (fromPositive p) = Zpos p.\nProof.\n  induction p as [p' | p' |]; cbn.\n  - rewrite toZ_succ, toZ_mul2, IHp'. reflexivity.\n  - rewrite toZ_mul2, IHp'. reflexivity.\n  - reflexivity.\nQed.\n\nLemma toZ_fromZ :\n  forall n : Z, toZ (fromZ n) = n.\nProof.\n  induction n as [| n' | n']; cbn.\n  - reflexivity.\n  - apply toZ_fromPositive.\n  - rewrite toZ_neg, toZ_fromPositive. lia.\nQed.\n\nLemma toZ'_inv_Zero :\n  forall n : Z3', (toZ' n = 0)%Z -> False.\nProof.\n  induction n as [| | n' | n' | n']; cbn [toZ']; intros; try lia.\nQed.\n\nLemma toZ'_inv_Plus :\n  forall n : Z3', (toZ' n = 1)%Z -> n = Plus.\nProof.\n  induction n as [| | n' | n' | n']; cbn [toZ']; intros H; try lia.\n  - reflexivity.\n  - assert (toZ' n' = 0%Z) by lia. apply toZ'_inv_Zero in H0. contradiction.\nQed.\n\nLemma toZ'_inv_Minus:\n  forall n : Z3', (toZ' n = -1)%Z -> n = Minus.\nProof.\n  induction n as [| | n' | n' | n']; cbn [toZ']; intros; try lia.\n  - reflexivity.\n  - assert (toZ' n' = 0%Z) by lia. apply toZ'_inv_Zero in H0. contradiction.\nQed.\n\nLemma toZ_Zero :\n  forall n : Z3, (toZ n = 0)%Z -> n = Zero.\nProof.\n  destruct n as [| n]; cbn.\n  - reflexivity.\n  - intro H. apply toZ'_inv_Zero in H. contradiction.\nQed.\n\nLemma toZ'_inj :\n  forall n m : Z3', toZ' n = toZ' m -> n = m.\nProof.\n  induction n as [| | n' | n' | n']; cbn [toZ']; intros; try lia.\n  - symmetry in H. apply toZ'_inv_Plus in H. congruence.\n  - symmetry in H. apply toZ'_inv_Minus in H. congruence.\n  - destruct m; cbn [toZ'] in *; try lia.\n    + assert (toZ' n' = 0%Z) by lia. apply toZ'_inv_Zero in H0. contradiction.\n    + f_equal. apply IHn'. lia.\n  - destruct m; cbn [toZ'] in *; try lia.\n    + assert (toZ' n' = 0%Z) by lia. apply toZ'_inv_Zero in H0. contradiction.\n    + f_equal. apply IHn'. lia.\n  - destruct m; cbn [toZ'] in *; try lia.\n    f_equal. apply IHn'. lia.\nQed.\n\nLemma toZ_inj :\n  forall n m : Z3, toZ n = toZ m -> n = m.\nProof.\n  destruct n as [| n], m as [| m]; cbn; intros.\n  - reflexivity.\n  - symmetry in H. apply toZ'_inv_Zero in H. contradiction.\n  - apply toZ'_inv_Zero in H. contradiction.\n  - apply toZ'_inj in H. inversion H. reflexivity.\nQed.\n\nLemma fromZ_toZ :\n  forall n : Z3, fromZ (toZ n) = n.\nProof.\n  intros.\n  apply toZ_inj, toZ_fromZ.\nQed.\n\nLemma add_Plus_r :\n  forall k : Z3', add k Plus = succ k.\nProof.\n  destruct k; cbn; reflexivity.\nQed.\n\nLemma add_Minus_r :\n  forall k : Z3', add k Minus = pred k.\nProof.\n  destruct k; cbn; rewrite ?neg'_neg'; reflexivity.\nQed.\n\nLemma add_comm :\n  forall k1 k2 : Z3',\n    add k1 k2 = add k2 k1.\nProof.\n  intros k1 k2; functional induction add k1 k2\n  ; cbn; rewrite ?IHz; try reflexivity.\n  - rewrite add_Plus_r; reflexivity.\n  - rewrite add_Minus_r; reflexivity.\n  - rewrite neg'_neg'; reflexivity.\nRestart.\n  intros k1 k2.\n  rewrite <- fromZ_toZ, toZ_add, <- Z.add_comm, <- toZ_add, fromZ_toZ.\n  reflexivity.\nQed.\n\nLemma add'_comm :\n  forall k1 k2 : Z3,\n    add' k1 k2 = add' k2 k1.\nProof.\n  intros k1 k2.\n  rewrite <- fromZ_toZ, toZ_add', <- Z.add_comm, <- toZ_add', fromZ_toZ.\n  reflexivity.\nQed.\n\nLemma add_assoc :\n  forall k1 k2 k3 : Z3',\n    add' (add' k1 k2) k3 = add' k1 (add' k2 k3).\nProof.\n  intros k1 k2 k3.\n  rewrite <- fromZ_toZ, !toZ_add', <- Z.add_assoc, <- !toZ_add', fromZ_toZ at 1.\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/BalancedTernaryZ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.6902072404861798}}
{"text": "Require Import Undecidability.Shared.Libs.PSL.Base Lia.\n(* Nats smaller than n *)\n\nFixpoint natsLess n : list nat :=\n  match n with\n    0 => []\n  | S n => n :: natsLess n\n  end.\n\nLemma natsLess_in_iff n m:\n  n el natsLess m <-> n < m.\nProof.\n  induction m in n|-*;cbn. lia.\n  split.\n  -intuition. destruct n;intuition. apply IHm in H0. lia.\n  -intros. decide (m=n). intuition. right. apply IHm. lia.\nQed.\n\n\nLemma natsLess_S n :\n  natsLess (S n) = map S (natsLess n)++[0].\nProof.\n  induction n;cbn in *;congruence.\nQed.\n\n\n(* Sum *)\n\nFixpoint sumn (A:list nat) :=\n  match A with\n    [] => 0\n  | a::A => a + sumn A\n  end.\n\nLemma sumn_app A B : sumn (A++B) = sumn A + sumn B.\nProof.\n  induction A;cbn;lia.\nQed.\n\nHint Rewrite sumn_app : list. \n\nLemma length_concat X (A : list (list X)) :\n  length (concat A) = sumn (map (@length _) A).\n  induction A;cbn. reflexivity. autorewrite with list in *. lia.\nQed.\n\nLemma sumn_rev A :\n  sumn A = sumn (rev A).\nProof.\n  enough (H:forall B, sumn A + sumn B = sumn (rev A++B)).\n  {specialize (H []). cbn in H. autorewrite with list in H. cbn in H. lia. }\n  induction A as [|a A];intros B. reflexivity.\n  cbn in *. specialize (IHA (a::B)). autorewrite with list in *. cbn in *. lia.\nQed.\n\nLemma sumn_map_natsLess f n :\n  sumn (map f (natsLess n)) = sumn (map (fun i => f (n - (1 + i))) (natsLess n)).\nProof.\n  rewrite sumn_rev. f_equal.\n  rewrite <- map_rev.\n  rewrite <- map_map with (g:=f) (f:= fun i => (n - (1+i))).\n  f_equal.\n  induction n;intros;autorewrite with list in *. reflexivity.\n  rewrite natsLess_S at 2. cbn. rewrite map_app. cbn.\n  rewrite map_map. cbn in IHn.\n  rewrite IHn. rewrite <- minus_n_O. reflexivity.\nQed.\n\n\nLemma sumn_map_add X f g (l:list X) :\n  sumn (map (fun x => f x + g x) l) = sumn (map f l) + sumn (map g l).\nProof.\n  induction l;cbn;nia.\nQed.\nLemma sumn_map_mult_c_r X f c (l:list X) :\n  sumn (map (fun x => f x *c) l) = sumn (map f l)*c.\nProof.\n  induction l;cbn;nia.\nQed.\nLemma sumn_map_c X c (l:list X) :\n  sumn (map (fun _ => c) l) = length l * c.\nProof.\n  induction l;cbn;nia.\nQed.\n\nLemma sumn_le_in n xs: n el xs -> n <= sumn xs.\nProof.\n  induction xs. easy. intros [ | ]. now cbn;nia.\n  cbn;etransitivity. apply IHxs. easy. nia.\nQed.\n\nLemma sumn_concat xs: sumn (concat xs) = sumn (map sumn xs).\nProof.\n  induction xs;cbn. easy. etransitivity. apply sumn_app. nia.\nQed.\n\n\nLemma sumn_repeat c n: sumn (repeat c n) = c * n.\nProof.\n  induction n;cbn. all:nia.\nQed.\n\nDefinition maxl := fold_right max 0.\nLemma maxl_leq n l: n el l -> n <= maxl l.\nProof.\n  induction l;cbn.\n  -easy.\n  -intros [->|]. all:apply Nat.max_case_strong;try intuition Lia.lia.\nQed.\n\nLemma maxl_leq_l c l :\n  (forall n, n el l -> n <= c) -> maxl l <= c.\nProof.\n  induction l;cbn. Lia.lia. \n  intros H. eapply Nat.max_lub_iff;split. all:eauto.  \nQed.\n\nLemma maxl_app l l': maxl (l++l') = max (maxl l) (maxl l').\nProof.\n  induction l;cbn;Lia.lia.\nQed.\n\nLemma maxl_rev l: maxl (rev l) = maxl l.\nProof.\n  unfold maxl. rewrite fold_left_rev_right. rewrite fold_symmetric. 2,3:now intros;Lia.lia.\n  induction l;cbn;try Lia.lia.\nQed.\n", "meta": {"author": "uds-psl", "repo": "constructive-and-synthetic-reducibility-in-coq", "sha": "3bd7c2e7c311d17bb93a9edcd55e39fc1ad9aa9d", "save_path": "github-repos/coq/uds-psl-constructive-and-synthetic-reducibility-in-coq", "path": "github-repos/coq/uds-psl-constructive-and-synthetic-reducibility-in-coq/constructive-and-synthetic-reducibility-in-coq-3bd7c2e7c311d17bb93a9edcd55e39fc1ad9aa9d/L/Prelim/MoreList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.6902072395838943}}
{"text": "(* Ethereum instructions that deal with signed ints: SDIV SMOD SIGNEXTEND SLT SGT SAR *)\n\nFrom Coq Require Import NArith ZArith Lia.\n\nRequire Import UInt.\nRequire Import Arith2.\n\nLocal Open Scope Z_scope.\n\nDefinition sint (width: N) := bound_int (- 2 ^ (Z.of_N width - 1))\n                                         (  2 ^ (Z.of_N width - 1)).\n\nDefinition Z_of_sint {width: N} (z: sint width): Z := Z_of_bound_int z.\n\nLocal Lemma uint_of_sint_pos_spec {width : N}\n                             (a: sint width)\n                             (p: positive)\n                             (E: Z_of_sint a = Z.pos p):\n  (N.pos p < 2 ^ width)%N.\nProof.\nassert (B := bound_int_upper a).\nunfold Z_of_sint in E. rewrite E in B.\nclear E a.\napply N2Z.inj_lt.\nrewrite N2Z.inj_pow.\ncbn.\napply (Z.lt_trans _ _ _ B).\napply Z.pow_lt_mono_r. { now rewrite<- Z.ltb_lt. }\n{ apply N2Z.is_nonneg. }\napply Z.lt_pred_l.\nQed.\n\nLocal Lemma uint_of_sint_neg_spec {width : N}\n                            (a: sint width)\n                            (p: positive)\n                            (E: Z_of_sint a = Z.neg p):\n  (2 ^ width - N.pos p < 2 ^ width)%N.\nProof.\nassert (B := bound_int_lower a). unfold Z_of_sint in E.\nrewrite E in B. clear E a.\napply N.sub_lt. 2:{ now apply N_ne_0_gt_0. }\napply N2Z.inj_le.\nrewrite N2Z.inj_pow.\ncbn.\nrewrite Z.opp_le_mono in B.\ncbn in B. rewrite Z.opp_involutive in B.\napply (Z.le_trans _ _ _ B).\napply Z.pow_le_mono_r. { now rewrite<- Z.ltb_lt. }\napply Z.lt_le_incl.\napply Z.lt_pred_l.\nQed.\n\n(** Convert an uint to a sint in a usual way:\n    split the range of uints in half and \n    map the higher half into the negatives.\n *)\n\nDefinition uint_of_sint {width: N} (a: sint width)\n: uint width\n:= let z := Z_of_sint a in \n   match z as z' return z = z' -> _ with\n   | Z0 => fun _ => uint_0 width\n   | Zpos p => fun E => uint_of_N (Npos p) (uint_of_sint_pos_spec a p E)\n   | Zneg p => fun E => uint_of_N (2^width - Npos p)%N (uint_of_sint_neg_spec a p E)\n   end eq_refl.       (* I don't like this ^ subtraction in N but it's too late *)\n\n \nLemma Z_of_uint_of_sint {width: N} (a: sint width):\n  Z_of_uint (uint_of_sint a) =\n    let z := Z_of_sint a in\n    match z with\n    | Z0 | Zpos _ => z\n    | Zneg p => (z + 2^(Z.of_N width))%Z\n    end.\nProof.\nunfold Z_of_uint.\nunfold uint_of_sint.\nremember (fun p (E : Z_of_sint a = Z.pos p) => uint_of_N (N.pos p) (uint_of_sint_pos_spec a p E))\n  as branch_pos.\nremember (fun p (E : Z_of_sint a = Z.neg p) =>\n   uint_of_N (2 ^ width - N.pos p) (uint_of_sint_neg_spec a p E))\n  as branch_neg.\nassert(PosOk: forall p E, Z_of_bound_int (branch_pos p E) = Zpos p).\n{ intros. subst. trivial. }\nassert(NegOk: forall p E, Z_of_bound_int (branch_neg p E) = Zneg p + 2^(Z.of_N width)).\n{ \n  intros. subst. cbn. clear PosOk.\n  assert (P: 0 < 2 ^ Z.of_N width). { apply Z_0_lt_pow2. apply N2Z.is_nonneg. }\n  remember (2 ^ Z.of_N width) as m.\n  destruct m. { now apply Z.lt_irrefl in P. }\n  2:{ exfalso. rewrite<- Z.ltb_lt in P. cbn in P. discriminate. }\n  clear P.\n  unfold Z_of_sint in E.\n  rewrite<- Pos2Z.add_pos_neg.\n  rewrite Heqm. clear Heqm.\n  assert (U := bound_int_lower a).\n  assert (Q: (N.pos p <= 2 ^ width)%N).\n  {\n    rewrite E in U.\n    rewrite<- (Pos2Z.opp_pos p) in U.\n    rewrite<- Z.opp_le_mono in U.\n    rewrite N2Z.inj_le.\n    rewrite N2Z.inj_pow. cbn.\n    apply (Z.le_trans _ _ _ U).\n    apply Z.pow_le_mono_r. { now rewrite<- Z.ltb_lt. }\n    apply Z.le_pred_l.\n  }\n  rewrite N2Z.inj_sub; try assumption.\n  rewrite N2Z.inj_pow. cbn.\n  rewrite<- (Pos2Z.opp_pos p). rewrite Z.add_opp_r. trivial.\n}\nclear Heqbranch_pos Heqbranch_neg.\ndestruct (Z_of_sint a); easy.\nQed.\n\nLocal Lemma sint_of_uint_high {width: positive}\n                               (z: Z)\n                               (H : (Z.ones (Zpos width - 1) <? z) = true)\n                               (U: z < 2 ^ Zpos width):\n  - 2 ^ (Zpos width - 1) <= z - 2 ^ Zpos width < 2 ^ (Zpos width - 1).\nProof.\nrewrite Z.ones_equiv in H.\nrewrite Z.ltb_lt in H.\nrewrite Z.lt_pred_le in H.\nreplace (2 ^ Zpos width) with (2 ^ (Z.succ (Z.pred (Zpos width)))) in *.\n2:{ f_equal. now rewrite Z.succ_pred. }\nreplace (Z.pred (Zpos width)) with (Zpos width - 1)%Z in *. 2:{ trivial. }\nrewrite Z.pow_succ_r in *; lia.\nQed.\n\nLocal Lemma sint_of_uint_low {width: positive}\n                              (z: Z)\n                              (L: (Z.ones (Z.pos width - 1) <? z) = false)\n                              (NN: 0 <= z):\n  - 2 ^ (Z.pos width - 1) <= z < 2 ^ (Z.pos width - 1).\nProof.\nrewrite Z.ones_equiv in L.\nrewrite Z.ltb_ge in L.\nrewrite<- Z.lt_le_pred in L.\nsplit; try assumption.\nrefine (Z.le_trans _ _ _ _ NN).\nrewrite Z.opp_nonpos_nonneg.\napply Z.pow_nonneg.\nrewrite<- Z.leb_le. trivial.\nQed.\n\nDefinition sint_of_uint {width: positive} (a: uint (Npos width))\n: sint (Npos width)\n:= let z := Z_of_uint a in\n   (if (Z.ones (Zpos width - 1) <? z)%Z as b return _ = b -> _\n     then fun H => bound_int_of_Z_conj (z - 2^(Zpos width))\n                                        (sint_of_uint_high z H (bound_int_upper a))\n     else fun L => bound_int_of_Z_conj z \n                                        (sint_of_uint_low z L (bound_int_lower a))) \n       eq_refl.\n\n(* Same but without proofs: *)\nLemma Z_of_sint_of_uint {width: positive} (a: uint (Npos width)):\n  Z_of_sint (sint_of_uint a) =\n   let z := Z_of_uint a in\n   if (Z.ones (Zpos width - 1) <? z)%Z\n     then z - 2 ^ (Zpos width)\n     else z.\nProof.\nunfold sint_of_uint.\n(* TODO: write a tactic for this: *)\nremember (fun H : (Z.ones (Z.pos width - 1) <? Z_of_uint a) = true =>\n     bound_int_of_Z_conj (Z_of_uint a - 2 ^ Z.pos width)\n       (sint_of_uint_high (Z_of_uint a) H (bound_int_upper a))) \n  as high_branch.\nremember (fun L : (Z.ones (Z.pos width - 1) <? Z_of_uint a) = false =>\n     bound_int_of_Z_conj (Z_of_uint a) (sint_of_uint_low (Z_of_uint a) L (bound_int_lower a)))\n  as low_branch.\nassert(HighOk: forall H, Z_of_bound_int (high_branch H) = Z_of_uint a - 2 ^ Z.pos width).\n{ intro. subst. trivial. }\nassert(LowOk: forall L, Z_of_bound_int (low_branch L) = Z_of_uint a).\n{ intro. subst. trivial. }\nclear Heqhigh_branch Heqlow_branch.\ndestruct (Z.ones (Z.pos width - 1) <? Z_of_uint a).\n{ apply (HighOk eq_refl). }\n{ apply (LowOk eq_refl). }\nQed.\n\nExample sint_of_uint_example:\n  Z_of_sint (sint_of_uint (uint_not (uint_0 8))) = -1%Z.\nProof. trivial. Qed.\n\nLemma Z_pow2_pos_pred (p: positive):\n  2 ^ Z.pos p = 2 * 2 ^ (Z.pos p - 1).\nProof.\nreplace (2 ^ Z.pos p) with (2 ^ Z.succ (Z.pos p - 1)).\n{ apply Z.pow_succ_r. lia. }\nf_equal. lia.\nQed.\n\nLemma sint_of_uint_of_sint {width: positive} (s: sint (Npos width)):\n  sint_of_uint (uint_of_sint s) = s.\nProof.\napply bound_int_irrel.\nreplace (Z_of_bound_int (sint_of_uint (uint_of_sint s)))\n  with (Z_of_sint (sint_of_uint (uint_of_sint s))) by trivial.\nrewrite Z_of_sint_of_uint.\nrewrite Z_of_uint_of_sint.\nrewrite Z.ones_equiv.\nassert(LB := bound_int_lower s).\nassert(UB := bound_int_upper s).\nreplace (Z.of_N (N.pos width)) with (Z.pos width) in * by trivial.\nunfold Z_of_sint.\nremember (Z_of_bound_int s) as z. clear Heqz s. subst.\nassert (K: 0 <= Z.pred (2 ^ (Z.pos width - 1))).\n{\n  apply Zlt_0_le_0_pred.\n  apply Z_0_lt_pow2.\n  lia.\n}\ndestruct z. { rewrite<- Z.ltb_ge in K. now rewrite K. }\n{\n  assert (M: Z.pos p <= Z.pred (2 ^ (Z.pos width - 1))).\n  {\n    replace (Z.of_N (N.pos width)) with (Z.pos width) in UB by trivial.\n    lia.\n  }\n  rewrite<- Z.ltb_ge in M. rewrite M. trivial.\n}\nassert (M: Z.pred (2 ^ (Z.pos width - 1)) < Z.neg p + 2 ^ Z.of_N (N.pos width)).\n{\n  replace (Z.of_N (N.pos width)) with (Z.pos width) in * by trivial.\n  rewrite (Z_pow2_pos_pred width). lia.\n}\nrewrite<- Z.ltb_lt in M. rewrite M.\nreplace (Z.of_N (N.pos width)) with (Z.pos width) in * by trivial.\nlia.\nQed.\n\nLemma uint_of_sint_of_uint {width: positive} (u: uint (Npos width)):\n  uint_of_sint (sint_of_uint u) = u.\nProof.\napply bound_int_irrel.\nreplace (Z_of_bound_int (uint_of_sint (sint_of_uint u))) \n   with (Z_of_uint (uint_of_sint (sint_of_uint u))) by trivial.\nrewrite Z_of_uint_of_sint. rewrite Z_of_sint_of_uint.\nassert(LB := bound_int_lower u).\nassert(UB := bound_int_upper u).\nreplace (Z_of_uint u) with (Z_of_bound_int u) by trivial.\nremember (Z_of_bound_int u) as z. clear Heqz u.\nreplace (Z.of_N (N.pos width)) with (Z.pos width) in * by trivial.\nrewrite Z.ones_equiv. rewrite (Z_pow2_pos_pred width) in *.\nremember (2 ^ (Z.pos width - 1)) as m.\nassert(M: 0 < m). { subst. apply Z_0_lt_pow2. lia. }\ncbn. clear Heqm.\nremember (Z.pred m <? z) as f. symmetry in Heqf.\ndestruct m; try lia.\ndestruct f; remember (z - Z.pos p~0) as y; destruct y; try lia.\ndestruct z; lia.\nQed.\n\n(*************************************************************************)\n\nLemma sint_minus_1_lower (width: positive):\n  (- 2 ^ (Z.of_N (N.pos width) - 1)) <= -1.\nProof.\napply Zlt_succ_le.\napply Z.opp_neg_pos.\napply Z_0_lt_pow2.\nlia.\nQed.\n\nLemma sint_0_lower (width: positive):\n  (- 2 ^ (Z.of_N (N.pos width) - 1)) <= 0.\nProof.\napply (Z.le_trans _ _ _ (sint_minus_1_lower _)).\nrewrite<- Z.leb_le. trivial.\nQed.\n\nLemma sint_0_upper (width: positive):\n  0 < 2 ^ (Z.of_N (N.pos width) - 1).\nProof.\napply Z_0_lt_pow2.\nlia.\nQed.\n\nLemma sint_minus_1_upper (width: positive):\n  -1 < 2 ^ (Z.of_N (N.pos width) - 1).\nProof.\nrefine (Z.lt_trans _ _ _ _ (sint_0_upper _)).\nrewrite<- Z.ltb_lt. trivial.\nQed.\n\nDefinition sint_0 (width: positive)\n: sint (Npos width)\n:= bound_int_of_Z 0%Z (sint_0_lower width) (sint_0_upper width).\n\nDefinition sint_minus_1 (width: positive)\n: sint (Npos width)\n:= bound_int_of_Z (-1)%Z (sint_minus_1_lower width) (sint_minus_1_upper width).\n\nDefinition sint_lowest (width: positive)\n: sint (Npos width)\n:= bound_int_of_Z (- 2 ^ (Z.of_N (Npos width) - 1))\n                  (Z.le_refl _) \n                  (Z.le_lt_trans _ _ _ (sint_0_lower width) (sint_0_upper width)).\n\n(*************************************************************************)\n\nDefinition sdiv (a b: Z) := Z.sgn a * Z.sgn b * (Z.abs a / Z.abs b).\n\nLemma sdiv_0_r (a: Z):\n  sdiv a 0 = 0.\nProof.\nunfold sdiv. cbn. rewrite Z.mul_0_r. rewrite Z.mul_0_l. trivial.\nQed.\n\nLemma sdiv_1_r (a: Z):\n  sdiv a 1 = a.\nProof.\nunfold sdiv. cbn. rewrite Z.mul_1_r. rewrite Z.div_1_r.\nnow destruct a.\nQed.\n\nLemma abs_sdiv (a b: Z):\n  Z.abs (sdiv a b) = Z.abs a / Z.abs b.\nProof.\nunfold sdiv.\nrewrite<- Z.mul_assoc.\nrewrite Z_abs_sgn.\nrewrite Z_abs_sgn.\nremember (Z.abs a / Z.abs b) as q.\nassert(Q: 0 <= q). { subst. apply Z_div_nonneg; apply Z.abs_nonneg. }\ndestruct a, b; try easy; now apply Z.abs_eq.\nQed.\n\nLemma abs_sdiv_le (a b: Z):\n  Z.abs (sdiv a b) <= Z.abs a.\nProof.\nrewrite abs_sdiv.\napply Z2N.inj_le; try apply Z_div_nonneg; try rewrite Z2N.inj_div; try apply Z.abs_nonneg. \napply N_div_le.\nQed.\n\nLemma abs_sdiv_lt (a b: Z)\n                  (A: 0 < Z.abs a)\n                  (B: 1 < Z.abs b):\n  Z.abs (sdiv a b) < Z.abs a.\nProof.\nrewrite abs_sdiv. now apply Z.div_lt.\nQed.\n\nLemma sint_sdiv_bound {width: positive} (a b: sint (Npos width))\n      (E: ((Z_of_sint a =? Z_of_sint (sint_lowest width)) && (Z_of_sint b =? -1))%bool = false):\n  - 2 ^ (Z.of_N (N.pos width) - 1) <= sdiv (Z_of_sint a) (Z_of_sint b) < 2 ^ (Z.of_N (N.pos width) - 1).\nProof.\nassert(AL := bound_int_lower a).\nassert(AU := bound_int_upper a).\nassert(BL := bound_int_lower b).\nassert(BU := bound_int_upper b).\nunfold Z_of_sint in *.\nremember (Z_of_bound_int a) as n. clear Heqn.\nremember (Z_of_bound_int b) as m. clear Heqm.\napply Bool.andb_false_elim in E.\ndestruct E as [NotLowest | NotMinusOne].\n{\n  rewrite Z.eqb_neq in NotLowest.\n  replace (Z_of_bound_int (sint_lowest width)) \n    with (- 2 ^ (Z.of_N (N.pos width) - 1))\n    in NotLowest by trivial.\n  assert(NL: - 2 ^ (Z.of_N (N.pos width) - 1) < n) by lia. clear AL.\n  enough (- 2 ^ (Z.of_N (N.pos width) - 1) < sdiv n m < 2 ^ (Z.of_N (N.pos width) - 1)) by lia.\n  rewrite<- Z.abs_lt. rewrite abs_sdiv.\n  apply (Z.le_lt_trans _ _ _ (Z_abs_div_le _ _)).\n  lia.\n}\nrewrite Z.eqb_neq in NotMinusOne.\nassert(MZ: m = 0 \\/ 0 < Z.abs m). { lia. }\ncase MZ; intro; subst. { rewrite sdiv_0_r. apply (bound_int_both (sint_0 width)). }\nassert(NZ: n = 0 \\/ 0 < Z.abs n). { lia. }\ncase NZ; intro; subst. { apply (bound_int_both (sint_0 width)). }\nassert(M1: m = 1 \\/ 1 < Z.abs m). { lia. }\ncase M1; intro; subst. { rewrite sdiv_1_r. tauto. }\nenough (- 2 ^ (Z.of_N (N.pos width) - 1) < sdiv n m < 2 ^ (Z.of_N (N.pos width) - 1)) by lia.\nrewrite<- Z.abs_lt. rewrite abs_sdiv.\nrefine (Z.lt_le_trans _ _ _ (Z.div_lt _ _ _ _) _); try lia.\nQed.\n\nDefinition sint_sdiv {width: positive} (a b: sint (Npos width))\n: sint (Npos width)\n:= (if ((Z_of_sint a =? Z_of_sint (sint_lowest width)) && (Z_of_sint b =? -1))%bool \n      as over return _ = over -> _ \n      then fun _ => a\n      else fun E => bound_int_of_Z_conj (sdiv (Z_of_sint a) (Z_of_sint b)) \n                                         (sint_sdiv_bound a b E))\n      eq_refl.\n\n(*************************************************************************)\n\n(* This is Ethereum's smod: the sign of b is ignored. *)\nDefinition smod (a b: Z) := Z.sgn a * (Z.abs a mod Z.abs b).\nLemma smod_0_r (a: Z):\n  smod a 0 = 0.\nProof.\nunfold smod. cbn. rewrite Zmod_0_r. now rewrite Z.mul_0_r.\nQed. \n\nLemma sint_smod_bound {width: positive} (a b: sint (Npos width)):\n  - 2 ^ (Z.of_N (N.pos width) - 1) <= smod (Z_of_sint a) (Z_of_sint b) < 2 ^ (Z.of_N (N.pos width) - 1).\nProof.\nassert(AL := bound_int_lower a).\nassert(AU := bound_int_upper a).\nassert(BL := bound_int_lower b).\nassert(BU := bound_int_upper b).\nunfold Z_of_sint in *.\nremember (Z_of_bound_int a) as n. clear Heqn.\nremember (Z_of_bound_int b) as m. clear Heqm.\nassert(M: m = 0 \\/ 0 < Z.abs m) by lia.\ncase M; intro MZ. { subst. rewrite smod_0_r. apply (bound_int_both (sint_0 width)). }\nclear M.\nunfold smod.\nassert (B := Z.mod_pos_bound (Z.abs n) (Z.abs m) MZ).\nenough(- 2 ^ (Z.of_N (N.pos width) - 1) < Z.sgn n * (Z.abs n mod Z.abs m) < 2 ^ (Z.of_N (N.pos width) - 1)) by lia.\napply Z.abs_lt. rewrite Z_abs_sgn.\nenough (Z.abs (Z.abs n mod Z.abs m) < 2 ^ (Z.of_N (N.pos width) - 1)) by now destruct n.\nlia.\nQed.\n\nDefinition sint_smod {width: positive} (a b: sint (Npos width))\n: sint (Npos width)\n:= bound_int_of_Z_conj (smod (Z_of_sint a) (Z_of_sint b))\n                       (sint_smod_bound a b).", "meta": {"author": "formalize", "repo": "coq-evm", "sha": "790328bf9294e32fbca3d7e47be48576e330b9dd", "save_path": "github-repos/coq/formalize-coq-evm", "path": "github-repos/coq/formalize-coq-evm/coq-evm-790328bf9294e32fbca3d7e47be48576e330b9dd/Arith/SInt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.6900598925167482}}
{"text": "(* -*- mode: coq; mode: visual-line -*- *)\nRequire Import Basics Types.\nRequire Export Basics.Nat.\nRequire Export HoTT.DProp.\n\nLocal Unset Elimination Schemes.\n\nScheme nat_ind := Induction for nat Sort Type.\nScheme nat_rect := Induction for nat Sort Type.\nScheme nat_rec := Minimality for nat Sort Type.\n\n(** * Theorems about the natural numbers *)\n\n(** Many of these definitions and proofs have been ported from the coq stdlib. *)\n\n(** We want to close the trunc_scope so that notations from there don't conflict here. *)\nLocal Close Scope trunc_scope.\nLocal Open Scope nat_scope.\n\n(** ** Basic operations on naturals *)\n\n(** It is common to call [S] [succ] so we add it as a parsing only notation. *)\nNotation succ := S (only parsing).\n\n(** The predecessor of a natural number. *)\nDefinition pred n : nat :=\n  match n with\n  | 0 => n\n  | S n' => n'\n  end.\n\n(** Addition of natural numbers *)\nFixpoint add n m : nat :=\n  match n with\n  | 0 => m\n  | S n' => S (add n' m)\n  end.\n\nNotation \"n + m\" := (add n m) : nat_scope.\n\nDefinition double n : nat := n + n.\n\nFixpoint mul n m : nat :=\n  match n with\n  | 0 => 0\n  | S n' => m + (mul n' m)\n  end.\n\nNotation \"n * m\" := (mul n m) : nat_scope.\n\n(** Truncated subtraction: [n - m] is [0] if [n <= m] *)\nFixpoint sub n m : nat :=\n  match n, m with\n  | S n' , S m' => sub n' m'\n  | _ , _ => n\n  end.\n\nNotation \"n - m\" := (sub n m) : nat_scope.\n\n(** ** Minimum, maximum *)\n\nFixpoint max n m :=\n  match n, m with\n  | 0 , _ => m\n  | S n' , 0 => n'.+1\n  | S n' , S m' => (max n' m').+1\n  end.\n\nFixpoint min n m :=\n  match n, m with\n  | 0 , _ => 0\n  | S n' , 0 => 0\n  | S n' , S m' => S (min n' m')\n  end.\n\n(** ** Power *)\n\nFixpoint pow n m :=\n  match m with\n  | 0 => 1\n  | S m' => n * (pow n m')\n  end.\n\n(** ** Euclidean division *)\n\n(** This division is linear and tail-recursive. In [divmod], [y] is the predecessor of the actual divisor, and [u] is [y] sub the real remainder. *)\n\nFixpoint divmod x y q u : 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\nDefinition div x y : nat :=\n  match y with\n    | 0 => y\n    | S y' => fst (divmod x y' 0 y')\n  end.\n\nDefinition modulo x y : nat :=\n  match y with\n    | 0 => y\n    | S y' => y' - snd (divmod x y' 0 y')\n  end.\n\nInfix \"/\" := div : nat_scope.\nInfix \"mod\" := modulo : nat_scope.\n\n(** ** Greatest common divisor *)\n\n(** We use Euclid algorithm, which is normally not structural, but Coq is now clever enough to accept this (behind modulo there is a subtraction, which now preserves being a subterm) *)\n\nFixpoint gcd a b :=\n  match a with\n  | O => b\n  | S a' => gcd (b mod a'.+1) a'.+1\n  end.\n\n(** ** Square *)\n\nDefinition square n : nat := n * n.\n\n(** ** Square root *)\n\n(** The following square root function is linear (and tail-recursive).\n  With Peano representation, we can't do better. For faster algorithm,\n  see Psqrt/Zsqrt/Nsqrt...\n\n  We search the square root of n = k + p^2 + (q - r)\n  with q = 2p and 0<=r<=q. We start with p=q=r=0, hence\n  looking for the square root of n = k. Then we progressively\n  decrease k and r. When k = S k' and r=0, it means we can use (S p)\n  as new sqrt candidate, since (S k')+p^2+2p = k'+(S p)^2.\n  When k reaches 0, we have found the biggest p^2 square contained\n  in n, hence the square root of n is p.\n*)\n\nFixpoint sqrt_iter k p q r : nat :=\n  match k with\n  | O => p\n  | S k' =>\n    match r with\n    | O => sqrt_iter k' p.+1 q.+2 q.+2\n    | S r' => sqrt_iter k' p q r'\n    end\n  end.\n\nDefinition sqrt n : nat := sqrt_iter n 0 0 0.\n\n(** ** Log2 *)\n\n(** This base-2 logarithm is linear and tail-recursive.\n\n  In [log2_iter], we maintain the logarithm [p] of the counter [q],\n  while [r] is the distance between [q] and the next power of 2,\n  more precisely [q + S r = 2^(S p)] and [r<2^p]. At each\n  recursive call, [q] goes up while [r] goes down. When [r]\n  is 0, we know that [q] has almost reached a power of 2,\n  and we increase [p] at the next call, while resetting [r]\n  to [q].\n\n  Graphically (numbers are [q], stars are [r]) :\n\n<<\n                    10\n                  9\n                8\n              7   *\n            6       *\n          5           ...\n        4\n      3   *\n    2       *\n  1   *       *\n0   *   *       *\n>>\n\n  We stop when [k], the global downward counter reaches 0.\n  At that moment, [q] is the number we're considering (since\n  [k+q] is invariant), and [p] its logarithm.\n*)\n\nFixpoint log2_iter k p q r : nat :=\n  match k with\n  | O    => p\n  | S k' =>\n    match r with\n    | O => log2_iter k' (S p) (S q) q\n    | S r' => log2_iter k' p (S q) r'\n    end\n  end.\n\nDefinition log2 n : nat := log2_iter (pred n) 0 1 0.\n\n(** ** Iterator on natural numbers *)\n\nDefinition iter (n : nat) {A} (f : A -> A) (x : A) : A :=\n  nat_rec A x (fun _ => f) n.\n\nLocal Definition ap_S := @ap _ _ S.\nLocal Definition ap_nat := @ap nat.\n#[export] Hint Resolve ap_S : core.\n#[export] Hint Resolve ap_nat : core.\n\nTheorem pred_Sn : forall n:nat, n = pred (S n).\nProof.\n  auto.\nDefined.\n\n(** Injectivity of successor *)\n\nDefinition path_nat_S n m (H : S n = S m) : n = m := ap pred H.\n#[export] Hint Immediate path_nat_S : core.\n\nTheorem not_eq_S : forall n m:nat, n <> m -> S n <> S m.\nProof.\n  auto.\nDefined.\n#[export] Hint Resolve not_eq_S : core.\n\n(** TODO: keep or remove? *)\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\nTheorem not_eq_O_S : forall n:nat, 0 <> S n.\nProof.\n  discriminate.\nDefined.\n#[export] Hint Resolve not_eq_O_S : core.\n\nTheorem not_eq_n_Sn : forall n:nat, n <> S n.\nProof.\n  induction n; auto.\nDefined.\n#[export] Hint Resolve not_eq_n_Sn : core.\n\nLocal Definition ap011_add := @ap011 _ _ _ add.\nLocal Definition ap011_nat := @ap011 nat nat.\n#[export] Hint Resolve ap011_add : core.\n#[export] Hint Resolve ap011_nat : core.\n\nLemma add_n_O : forall (n : nat), n = n + 0.\nProof.\n  induction n; simpl; auto.\nDefined.\n#[export] Hint Resolve add_n_O : core.\n\nLemma add_O_n : forall (n : nat), 0 + n = n.\nProof.\n  auto.\nDefined.\n\nLemma add_n_Sm : forall n m:nat, S (n + m) = n + S m.\nProof.\n  intros n m; induction n; simpl; auto.\nDefined.\n#[export] Hint Resolve add_n_Sm: core.\n\nLemma add_Sn_m : forall n m:nat, S n + m = S (n + m).\nProof.\n  auto.\nDefined.\n\n(** Multiplication *)\n\nLocal Definition ap011_mul := @ap011 _ _ _  mul.\n#[export] Hint Resolve ap011_mul : core.\n\nLemma mul_n_O : forall n:nat, 0 = n * 0.\nProof.\n  induction n; simpl; auto.\nDefined.\n#[export] Hint Resolve mul_n_O : core.\n\nLemma mul_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 <- add_n_Sm; apply ap.\n  pattern m at 1 3; elim m; simpl; auto.\nDefined.\n#[export] Hint Resolve mul_n_Sm: core.\n\n(** Standard associated names *)\n\nNotation mul_0_r_reverse := mul_n_O (only parsing).\nNotation mul_succ_r_reverse := mul_n_Sm (only parsing).\n\n(** ** Equality of natural numbers *)\n\n(** *** Boolean equality and its properties *)\n\nFixpoint code_nat (m n : nat) {struct m} : DHProp :=\n  match m, n with\n  | 0, 0 => True\n  | m'.+1, n'.+1 => code_nat m' n'\n  | _, _ => False\n  end.\n\nInfix \"=n\" := code_nat : nat_scope.\n\nFixpoint idcode_nat {n} : (n =n n) :=\n  match n as n return (n =n n) with\n  | 0 => tt\n  | S n' => @idcode_nat n'\n  end.\n\nFixpoint path_nat {n m} : (n =n m) -> (n = m) :=\n  match m as m, n as n return (n =n m) -> (n = m) with\n  | 0, 0 => fun _ => idpath\n  | m'.+1, n'.+1 => fun H : (n' =n m') => ap S (path_nat H)\n  | _, _ => fun H => match H with end\n  end.\n\nGlobal Instance isequiv_path_nat {n m} : IsEquiv (@path_nat n m).\nProof.\n  refine (isequiv_adjointify\n            (@path_nat n m)\n            (fun H => transport (fun m' => (n =n m')) H idcode_nat)\n            _ _).\n  { intros []; simpl.\n    induction n; simpl; trivial.\n    by destruct (IHn^)%path. }\n  { intro. apply path_ishprop. }\nDefined.\n\nDefinition equiv_path_nat {n m} : (n =n m) <~> (n = m)\n  := Build_Equiv _ _ (@path_nat n m) _.\n\n(** Thus [nat] has decidable paths *)\nGlobal Instance decidable_paths_nat : DecidablePaths nat\n  := fun n m => decidable_equiv _ (@path_nat n m) _.\n\n(** And is therefore a HSet *)\nGlobal Instance hset_nat : IsHSet nat := _.\n\n(** ** Inequality of natural numbers *)\n\nInductive leq (n : nat) : nat -> Type :=\n| leq_n : leq n n\n| leq_S : forall m, leq n m -> leq n (S m).\n\nScheme leq_ind := Induction for leq Sort Type.\nScheme leq_rect := Induction for leq Sort Type.\nScheme leq_rec := Minimality for leq Sort Type.\n\nNotation \"n <= m\" := (leq n m) : nat_scope.\n#[export] Hint Constructors leq : core.\n\nExisting Class leq.\nGlobal Existing Instances leq_n leq_S.\n\nNotation leq_refl := leq_n (only parsing).\nGlobal Instance reflexive_leq : Reflexive leq := leq_n.\n\nLemma leq_trans {x y z} : x <= y -> y <= z -> x <= z.\nProof.\n  induction 2; auto.\nDefined.\n\nGlobal Instance transitive_leq : Transitive leq := @leq_trans.\n\nLemma leq_n_pred n m : leq n m -> leq (pred n) (pred m).\nProof.\n  induction 1; auto.\n  destruct m; simpl; auto.\nDefined.\n\nLemma leq_S_n : forall n m, n.+1 <= m.+1 -> n <= m.\nProof.\n  intros n m.\n  apply leq_n_pred.\nDefined.\n\nLemma leq_S_n' n m : n <= m -> n.+1 <= m.+1.\nProof.\n  induction 1; auto.\nDefined.\nGlobal Existing Instance leq_S_n' | 100.\n\nLemma not_leq_Sn_n n : ~ (n.+1 <= n).\nProof.\n  induction n.\n  { intro p.\n    inversion p. }\n  intros p.\n  by apply IHn, leq_S_n.\nDefined.\n\n(** A general form for injectivity of this constructor *)\nDefinition leq_n_inj_gen n k (p : n <= k) (r : n = k) : p = r # leq_n n.\nProof.\n  induction p.\n  + assert (c : idpath = r) by apply path_ishprop.\n    destruct c.\n    reflexivity.\n  + destruct r^.\n    contradiction (not_leq_Sn_n _ p).\nDefined.\n\n(** Which we specialise to this lemma *)\nDefinition leq_n_inj n (p : n <= n) : p = leq_n n\n  := leq_n_inj_gen n n p idpath.\n\nFixpoint leq_S_inj_gen n m k (p : n <= k) (q : n <= m) (r : m.+1 = k)\n  : p = r # leq_S n m q.\nProof.\n  revert m q r.\n  induction p.\n  + intros k p r.\n    destruct r.\n    contradiction (not_leq_Sn_n _ p).\n  + intros m' q r.\n    pose (r' := path_nat_S _ _ r).\n    destruct r'.\n    assert (t : idpath = r) by apply path_ishprop.\n    destruct t.\n    cbn. apply ap.\n    destruct q.\n    1:  apply leq_n_inj.\n    apply (leq_S_inj_gen n m _ p q idpath).\nDefined.\n\nDefinition leq_S_inj n m (p : n <= m.+1) (q : n <= m) : p = leq_S n m q\n  := leq_S_inj_gen n m m.+1 p q idpath.\n\nGlobal Instance ishprop_leq n m : IsHProp (n <= m).\nProof.\n  apply hprop_allpath.\n  intros p q; revert p.\n  induction q.\n  + intros y.\n    rapply leq_n_inj.\n  + intros y.\n    rapply leq_S_inj.\nDefined.\n\nGlobal Instance leq_0_n n : 0 <= n | 10.\nProof.\n  induction n; auto.\nDefined.\n\nLemma not_leq_Sn_0 n : ~ (n.+1 <= 0).\nProof.\n  intros p.\n  apply (fun x => leq_trans x (leq_0_n n)) in p.\n  contradiction (not_leq_Sn_n _ p).\nDefined.\n\nDefinition equiv_leq_S_n n m : n.+1 <= m.+1 <~> n <= m.\nProof.\n  srapply equiv_iff_hprop.\n  apply leq_S_n.\nDefined.\n\nGlobal Instance decidable_leq n m : Decidable (n <= m).\nProof.\n  revert n.\n  induction m; intros n.\n  - destruct n.\n    + left; exact _.\n    + right; apply not_leq_Sn_0.\n  - destruct n.\n    + left; exact _.\n    + rapply decidable_equiv'.\n      symmetry.\n      apply equiv_leq_S_n.\nDefined.\n\nFixpoint leq_add n m : n <= (m + n).\nProof.\n  destruct m.\n  1: apply leq_n.\n  apply leq_S, leq_add.\nDefined.\n\nLemma equiv_leq_add n m\n  : leq n m <~> exists k, k + n = m.\nProof.\n  srapply equiv_iff_hprop.\n  { apply hprop_allpath.\n    intros [x p] [y q].\n    apply path_sigma_hprop.\n    simpl.\n    revert m p q.\n    induction n.\n    { intros m p q.\n      rewrite <- add_n_O in p,q.\n      exact (p @ q^). }\n    intros m p q.\n    rewrite <- add_n_Sm in p,q.\n    destruct m.\n    { inversion p. }\n    apply path_nat_S in p, q.\n    by apply (IHn m). }\n  { intros p.\n    induction p.\n    + exists 0.\n      reflexivity.\n    + exists IHp.1.+1.\n      apply ap_S, IHp.2. }\n  intros [k p].\n  destruct p.\n  apply leq_add.\nDefined.\n\n(** We define the less-than relation [lt] in terms of [leq] *)\nDefinition lt n m : Type0 := leq (S n) m.\n             \n(** We declare it as an existing class so typeclass search is performed on its goals. *)\nExisting Class lt.\n#[export] Hint Unfold lt : core typeclass_instances.\nInfix \"<\" := lt : nat_scope.\n(** We add a typeclass instance for unfolding the definition so lemmas about [leq] can be used. *)\nGlobal Instance lt_is_leq n m : leq n.+1 m -> lt n m | 100 := idmap.\n\n(** We should also give them their various typeclass instances *)\nGlobal Instance transitive_lt : Transitive lt.\nProof.\n  hnf; unfold lt in *.\n  intros x y z p q.\n  rapply leq_trans.\nDefined.\n\nGlobal Instance decidable_lt n m : Decidable (lt n m) := _.\n\nDefinition ge n m := leq m n.\nExisting Class ge.\n#[export] Hint Unfold ge : core typeclass_instances.\nInfix \">=\" := ge : nat_scope.\nGlobal Instance ge_is_leq n m : leq m n -> ge n m | 100 := idmap.\n\nGlobal Instance reflexive_ge : Reflexive ge := leq_n.\nGlobal Instance transitive_ge : Transitive ge := fun x y z p q => leq_trans q p.\nGlobal Instance decidable_ge n m : Decidable (ge n m) := _.\n\nDefinition gt n m := lt m n.\nExisting Class gt.\n#[export] Hint Unfold gt : core typeclass_instances.\nInfix \">\" := gt : nat_scope.\nGlobal Instance gt_is_leq n m : leq m.+1 n -> gt n m | 100 := idmap.\n\nGlobal Instance transitive_gt : Transitive gt\n  := fun x y z p q => transitive_lt _ _ _ q p.\nGlobal Instance decidable_gt n m : Decidable (gt n m) := _.\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\n(** Principle of double induction *)\n\nTheorem nat_double_ind (R : nat -> nat -> Type)\n  (H1 : forall n, R 0 n) (H2 : forall n, R (S n) 0)\n  (H3 : forall n m, R n m -> R (S n) (S m))\n  : forall n m:nat, R n m.\nProof.\n  induction n; auto.\n  destruct m; auto.\nDefined.\n\n(** Maximum and minimum : definitions and specifications *)\n\nLemma max_n_n n : max n n = n.\nProof.\n  induction n; cbn; auto.\nDefined.\n#[export] Hint Resolve max_n_n : core.\n\nLemma max_Sn_n n : max (S n) n = S n.\nProof.\n  induction n; cbn; auto.\nDefined.\n#[export] Hint Resolve max_Sn_n : core.\n\nLemma max_comm n m : max n m = max m n.\nProof.\n  revert m; induction n; destruct m; cbn; auto.\nDefined.\n\nLemma max_0_n n : max 0 n = n.\nProof.\n  auto.\nDefined.\n#[export] Hint Resolve max_0_n : core.\n\nLemma max_n_0 n : max n 0 = n.\nProof.\n  by rewrite max_comm.\nDefined.\n#[export] Hint Resolve max_n_0 : core.\n\nTheorem max_l : forall n m, m <= n -> max n m = n.\nProof.\n  intros n m; revert n; induction m; auto.\n  intros [] p.\n  1: inversion p.\n  cbn; by apply ap_S, IHm, leq_S_n.\nDefined.\n\nTheorem max_r : forall n m : nat, n <= m -> max n m = m.\nProof.\n  intros; rewrite max_comm; by apply max_l.\nDefined.\n\nLemma min_comm : forall n m, min n m = min m n.\nProof.\n  induction n; destruct m; cbn; auto.\nDefined. \n\nTheorem min_l : forall n m : nat, n <= m -> min n m = n.\nProof.\n  intros n m; revert m; induction n; auto.\n  intros [] p.\n  1: inversion p.\n  cbn; by apply ap_S, IHn, leq_S_n.\nDefined.\n\nTheorem min_r : forall n m : nat, m <= n -> min n m = m.\nProof.\n  intros; rewrite min_comm; by apply min_l.\nDefined.\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.\nDefined.\n\nTheorem nat_iter_add :\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.\nDefined.\n\n(** Preservation of invariants : if [f : A -> A] preserves the invariant [Inv], then the iterates of [f] also preserve it. *)\n\nTheorem nat_iter_invariant (n : nat) {A} (f : A -> A) (P : A -> Type)\n  : (forall x, P x -> P (f x)) -> forall x, P x -> P (nat_iter n f x).\nProof.\n  revert n A f P.\n  induction n; simpl; trivial.\n  intros A f P Hf x Hx.\n  apply Hf, IHn; trivial.\nDefined.\n\n(** ** Arithmetic *)\n\nLemma nat_add_n_O : forall n:nat, n = n + 0.\nProof.\n  induction n.\n  - reflexivity.\n  - simpl; apply ap; assumption.\nDefined.\n\nLemma nat_add_n_Sm : forall n m:nat, (n + m).+1 = n + m.+1.\nProof.\n  intros n m; induction n; simpl.\n  - reflexivity.\n  - apply ap; assumption.\nDefined.\n\nDefinition nat_add_comm (n m : nat) : n + m = m + n.\nProof.\n  revert m; induction n as [|n IH]; intros m; simpl.\n  - refine (nat_add_n_O m).\n  - transitivity (m + n).+1.\n    + apply ap, IH.\n    + apply nat_add_n_Sm.\nDefined.\n\n(** ** Exponentiation *)\n\nFixpoint nat_exp (n m : nat) : nat\n  := match m with\n       | 0 => 1\n       | S m => nat_exp n m * n\n     end.\n\n(** ** Factorials *)\n\nFixpoint factorial (n : nat) : nat\n  := match n with\n       | 0 => 1\n       | S n => S n * factorial n\n     end.\n\n(** ** Natural number ordering *)\n\n(** ** Theorems about natural number ordering *)\n\nLemma leq_antisym {x y} : x <= y -> y <= x -> x = y.\nProof.\n  intros p q.\n  destruct p.\n  1: reflexivity.\n  destruct x; [inversion q|].\n  apply leq_S_n in q.\n  pose (r := leq_trans p q).\n  by apply not_leq_Sn_n in r.\nDefined.\n\nDefinition not_lt_n_n n : ~ (n < n) := not_leq_Sn_n n.\n\nDefinition leq_1_Sn {n} : 1 <= n.+1 := leq_S_n' 0 n (leq_0_n _).\n\nFixpoint leq_dichot {m} {n} : (m <= n) + (m > n).\nProof.\n  induction m, n.\n  - left; reflexivity.\n  - left; apply leq_0_n.\n  - right; unfold lt; apply leq_1_Sn.\n  - assert ((m <= n) + (n < m)) as X by apply leq_dichot.\n    induction X as [leqmn|ltnm].\n    + left; apply leq_S_n'; assumption.\n    + right; apply leq_S_n'; assumption.\nDefined.\n\nLemma not_lt_n_0 n : ~ (n < 0).\nProof.\n  apply not_leq_Sn_0.\nDefined.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Spaces/Nat/Core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6900598907099601}}
{"text": "(* FPP_8b_annotated.v *)\n(* was: *)\n(* FPP_8b.v *)\n(* YSC3236 2018-2019, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 11 October 2018 *)\n\n(* Paraphernalia: *)\n\nLtac fold_unfold_tactic name := intros; unfold name; fold name; reflexivity.\n\nRequire Import Arith Bool List.\n\n(* ********** *)\n\nNotation \"A =n= B\" :=\n  (beq_nat A B) (at level 70, right associativity).\n\nNotation \"A =b= B\" :=\n  (eqb A B) (at level 70, right associativity).\n\nDefinition test_even (candidate: nat -> bool) : 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    (* etc. *)\n.\n\n\nDefinition test_odd (candidate: nat -> bool) : bool :=\n  (candidate 0 =b= false)\n    &&\n    (candidate 1 =b= true)\n    &&\n    (candidate 2 =b= false)\n    &&\n    (candidate 3 =b= true)\n    (* etc. *)\n.\n\nFixpoint is_odd (n : nat) : bool :=\n  match n with\n  | 0 => false\n  | S n' => is_even n'\n  end\nwith is_even (n : nat) : bool :=\n  match n with\n  | 0 => true\n  | S n' => is_odd n'\n  end.\n\nCompute test_odd is_odd.\nCompute test_even is_even.\n\nLemma fold_unfold_is_even_O :\n  is_even 0 = true.\nProof.\n  fold_unfold_tactic is_even.\nQed.\n\nLemma fold_unfold_is_even_S :\n  forall (n : nat),\n    is_even (S n) = is_odd n.\nProof.\n  fold_unfold_tactic is_even\n  .\nQed.\n\nLemma fold_unfold_is_odd_O :\n  is_odd 0 = false.\nProof.\n  fold_unfold_tactic is_odd.\nQed.\n\nLemma fold_unfold_is_odd_S :\n  forall (n : nat),\n    is_odd (S n) = is_even n.\nProof.\n  fold_unfold_tactic is_odd.\nQed.\n\nProposition disjunction_is_commutative :\n  forall P Q : Prop,\n    P \\/ Q <-> Q \\/ P.\n(* O: is the bi-implication really necessary? *)\nProof.\n  intros P Q.\n  split.\n  \n  - intro H_P_or_Q.\n    destruct H_P_or_Q as [H_P | H_Q].\n    \n    right.\n    exact H_P.\n    left.\n    exact H_Q.\n    \n  - intro H_Q_or_P.\n    destruct H_Q_or_P as [H_Q | H_P].\n    \n    right.\n    exact H_Q.\n    left.\n    exact H_P.\n    Show Proof.\nQed.\n\n\nLemma n_is_either_even_or_odd :\n  forall (n : nat),\n    is_even n = true \\/ is_odd n = true.\nProof.\n  intro n.\n  induction n as [ | n' IHn'].\n\n  - rewrite -> fold_unfold_is_even_O.\n    left.\n    reflexivity.\n\n  - rewrite -> (fold_unfold_is_even_S (n')).\n    rewrite -> (fold_unfold_is_odd_S (n')).\n    Check disjunction_is_commutative.\n(* O: You are abusing Coq here: apply works for an implication, not a bi-implication.  Mindfully use destruct first. *)\n    apply (disjunction_is_commutative (is_odd n' = true) (is_even n' = true)).\n    exact IHn'.\nQed.\n\nLemma n_is_even_implies_successor_of_n_is_odd :\n  forall (n : nat),\n    is_even n = true ->\n    is_odd (S n) = true.\nProof.\n  intro n.\n  intro H_is_even.\n  rewrite -> (fold_unfold_is_odd_S n).\n  apply H_is_even.\n(* O: You might as well use exact here. *)\nQed.\n\nLemma n_is_odd_implies_successor_of_n_is_even :\n  forall (n : nat),\n    is_odd n = true ->\n    is_even (S n) = true.\nProof.\n  intro n.\n  intro H_is_odd.\n  rewrite -> (fold_unfold_is_even_S n).\n  apply H_is_odd.\nQed.\n\nLemma evenness_of_additions :\n  forall (n m : nat),\n    (is_odd n = true ->\n     is_odd m = true ->\n     is_even (n + m) = true)\n    /\\\n    (is_odd n = true ->\n     is_even m = true ->\n     is_odd (n + m) = true)\n    /\\\n    (is_even n  = true ->\n     is_odd m = true ->\n     is_odd (n + m) = true)\n    /\\\n    (is_even n = true ->\n     is_even m = true ->\n     is_even (n + m) = true).\nProof.\n  intro n.\n  induction n as [ | n' IHn'].\n\n  - intro m.\n    rewrite -> (fold_unfold_is_odd_O).\n    rewrite -> (fold_unfold_is_even_O).\n    rewrite -> (plus_O_n).\n    split.\n\n    * intro H_absurd.\n      discriminate H_absurd.\n\n    * split.\n\n    + intro H_absurd.\n      discriminate H_absurd.\n\n    + split.\n\n      ** intros H_1 H_2.\n         exact H_2.\n\n      ** intros H_1 H_2.\n         exact H_2.\n\n  - intro m.\n    rewrite -> (fold_unfold_is_even_S).\n    rewrite -> (fold_unfold_is_odd_S).\n    Search (S _ + _ = _).\n    rewrite -> plus_Sn_m.\n    rewrite -> (fold_unfold_is_odd_S).\n    rewrite -> (fold_unfold_is_even_S).\n    split.\n\n    * apply (IHn' m).\n\n    * split.\n\n      ** apply (IHn' m).\n\n      ** split.\n\n      ++ apply (IHn' m).\n\n      ++ apply IHn'.\nQed.\n\n(* O: Wouldn't be more natural to state:\n  forall n : nat,\n    is_even n = true ->\n    forall m : nat,\n      is_even (n * m) = true.\n   ?\n*)\n\nProposition product_of_even_and_any_number_is_even :\n  forall (n m : nat),\n    is_even n = true ->\n    is_even (n * m) = true.\nProof.\n  intro n.\n  induction m as [ | m' IHm'].\n\n  - intro H_is_even.\n    Search (_ * 0 = 0).\n    rewrite -> (Nat.mul_0_r).\n    rewrite -> (fold_unfold_is_even_O).\n    reflexivity.\n\n  - intro H_is_even.\n    Search (_ * S _ = _).\n    rewrite -> Nat.mul_succ_r.\n    rewrite -> Nat.add_comm.\n    Check evenness_of_additions.\n    apply (evenness_of_additions n (n * m')).\n(* O: Again, you are abusing Coq here.  Mindfully use destruct first. *)\n    apply H_is_even.\n(* O: How about:\n    Check (IHm' H_is_even).\n   ?\n*)\n    apply IHm'. (*Which tells us that if n is even, then n * m' is even. So we need the fact that n is even. *)\n    apply H_is_even.\nQed.\n\nCorollary product_of_any_number_and_even_is_even :\n  forall (n m : nat),\n    is_even m = true ->\n    is_even (n * m) = true.\nProof.\n  intros n m.\n  revert m. (* Will not fall for this again. *)\n  induction n as [ | n' IHn'].\n\n  - intro m.\n    intro H_is_even.\n    rewrite -> (Nat.mul_0_l).\n    rewrite -> (fold_unfold_is_even_O).\n    reflexivity.\n\n  - intro m.\n    intro H_is_even.\n    rewrite -> Nat.mul_succ_l.\n    rewrite -> Nat.add_comm.\n    Check evenness_of_additions.\n    apply (evenness_of_additions m (n' * m)).\n    apply H_is_even.\n    apply IHn'.\n    apply H_is_even.\nQed.\n(* O: Why is this a corollary?  You have a full-fledged proof.\n      A corollary would be to use Nat.nat_comm and then product_of_even_and_any_number_is_even.\n*)\n\nTheorem the_product_of_two_consecutive_nat_numbers_is_even :\n  forall (n : nat), is_even (mult n (S n)) = true.\nProof.\n  intro n.\n(* O: How about using n_is_either_even_or_odd here?\n  destruct (n_is_either_even_or_odd n) as [H_n | H_n].\n*)\n\n  case n as [ | n' IHn'].\n\n  - Search (0 * _ = 0).\n    rewrite -> (Nat.mul_0_l 1).\n    rewrite -> (fold_unfold_is_even_O).\n    reflexivity.\n\n  - Check Nat.mul_succ_l.\n    rewrite -> Nat.mul_succ_l.\n    rewrite -> Nat.add_succ_r.\n    rewrite -> Nat.add_succ_r.\n    rewrite -> fold_unfold_is_even_S.\n    rewrite -> fold_unfold_is_odd_S.\n    rewrite -> Nat.mul_comm.\n    Search (S _ * _ = _).\n    rewrite -> (Nat.mul_succ_l).\n    rewrite -> (Nat.mul_succ_l).\n    Abort.\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/jeremy-parser/test_data/sample_submissions/FPP_8b_annotated_and_anonymized.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985637, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.6900188839619591}}
{"text": "\nLemma plus_n_0 : forall n:nat, n = n + 0.\nintro n; elim n.\nsimpl.\nauto.\nsimpl; auto.\nQed.\nPrint plus_n_0.\nPrint eq_refl.\nHint Resolve plus_n_0.\n\nLemma plus_n_S : forall n m : nat, S (n + m) = n + S m.\nsimple induction n; simpl; auto.\nQed.\n\nLemma plus_com : forall n m : nat, n+m = m+n.\nsimple induction m; simpl; auto.\nintros m' E; rewrite <- E; auto.\nQed.\n\nPrint plus_com.\nPrint nat_ind.\n\nDefinition Is_S (n:nat) := match n with \n| 0 => False\n| S p => True\nend.\n\nLemma S_Is_S : forall n:nat, Is_S (S n).\nsimpl; trivial.\nQed.\n\nLemma no_confusion : forall n:nat, 0 <> S n.\nred; intros n H.\nchange (Is_S 0).\nrewrite H; trivial.\nsimpl; trivial.\nQed.\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 plus_0_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.\nintros n m.\nrewrite -> plus_0_n.\nreflexivity. Qed.\n\nTheorem mult_S_1 : forall n m : nat,\n  m = S n -> m * (1 + n) = m * m.\nProof.\nintros.\nrewrite -> H.\nreflexivity.\nQed.\n\n(*\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  beq_nat (n + 1) 0 = false.\n*)", "meta": {"author": "NickFromNormandy", "repo": "ProofsWithCoq", "sha": "5c6c356bce4087b342106a172807bf4ae3dad493", "save_path": "github-repos/coq/NickFromNormandy-ProofsWithCoq", "path": "github-repos/coq/NickFromNormandy-ProofsWithCoq/ProofsWithCoq-5c6c356bce4087b342106a172807bf4ae3dad493/simple_proof_byinduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808498, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.6900188829312652}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2015     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\n(** Decidability results about lists *)\n\nRequire Import List Decidable.\nSet Implicit Arguments.\n\nDefinition decidable_eq A := forall x y:A, decidable (x=y).\n\nSection Dec_in_Prop.\nVariables (A:Type)(dec:decidable_eq A).\n\nLemma In_decidable x (l:list A) : decidable (In x l).\nProof using A dec.\n induction l as [|a l IH].\n - now right.\n - destruct (dec a x).\n   + left. now left.\n   + destruct IH; simpl; [left|right]; tauto.\nQed.\n\nLemma incl_decidable (l l':list A) : decidable (incl l l').\nProof using A dec.\n induction l as [|a l IH].\n - left. inversion 1.\n - destruct (In_decidable a l') as [IN|IN].\n   + destruct IH as [IC|IC].\n     * left. destruct 1; subst; auto.\n     * right. contradict IC. intros x H. apply IC; now right.\n   + right. contradict IN. apply IN; now left.\nQed.\n\nLemma NoDup_decidable (l:list A) : decidable (NoDup l).\nProof using A dec.\n induction l as [|a l IH].\n - left; now constructor.\n - destruct (In_decidable a l).\n   + right. inversion_clear 1. tauto.\n   + destruct IH.\n     * left. now constructor.\n     * right. inversion_clear 1. tauto.\nQed.\n\nEnd Dec_in_Prop.\n\nSection Dec_in_Type.\nVariables (A:Type)(dec : forall x y:A, {x=y}+{x<>y}).\n\nDefinition In_dec := List.In_dec dec. (* Already in List.v *)\n\nLemma incl_dec (l l':list A) : {incl l l'}+{~incl l l'}.\nProof using A dec.\n induction l as [|a l IH].\n - left. inversion 1.\n - destruct (In_dec a l') as [IN|IN].\n   + destruct IH as [IC|IC].\n     * left. destruct 1; subst; auto.\n     * right. contradict IC. intros x H. apply IC; now right.\n   + right. contradict IN. apply IN; now left.\nQed.\n\nLemma NoDup_dec (l:list A) : {NoDup l}+{~NoDup l}.\nProof using A dec.\n induction l as [|a l IH].\n - left; now constructor.\n - destruct (In_dec a l).\n   + right. inversion_clear 1. tauto.\n   + destruct IH.\n     * left. now constructor.\n     * right. inversion_clear 1. tauto.\nQed.\n\nEnd Dec_in_Type.\n\n(** An extra result: thanks to decidability, a list can be purged\n    from redundancies. *)\n\nLemma uniquify_map A B (d:decidable_eq B)(f:A->B)(l:list A) :\n exists l', NoDup (map f l') /\\ incl (map f l) (map f l').\nProof.\n induction l.\n - exists nil. simpl. split; [now constructor | red; trivial].\n - destruct IHl as (l' & N & I).\n   destruct (In_decidable d (f a) (map f l')).\n   + exists l'; simpl; split; trivial.\n     intros x [Hx|Hx]. now subst. now apply I.\n   + exists (a::l'); simpl; split.\n     * now constructor.\n     * intros x [Hx|Hx]. subst; now left. right; now apply I.\nQed.\n\nLemma uniquify A (d:decidable_eq A)(l:list A) :\n exists l', NoDup l' /\\ incl l l'.\nProof.\n destruct (uniquify_map d id l) as (l',H).\n exists l'. now rewrite !map_id in H.\nQed.\n", "meta": {"author": "afetisov", "repo": "HottCat", "sha": "b22c6298fa0b97c868760199ca09a1a5eacd73c0", "save_path": "github-repos/coq/afetisov-HottCat", "path": "github-repos/coq/afetisov-HottCat/HottCat-b22c6298fa0b97c868760199ca09a1a5eacd73c0/Lists/ListDec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.6899470814292574}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Import PeanoNat.\n\nLocal Open Scope nat_scope.\n\n\n\nNotation le_refl := Nat.le_refl.\nNotation le_trans := Nat.le_trans.\nNotation le_antisym := Nat.le_antisymm.\n\nHint Resolve le_trans: arith.\nHint Immediate le_antisym: arith.\n\n\n\nNotation le_0_n := Nat.le_0_l.\nNotation le_Sn_0 := Nat.nle_succ_0.\n\nLemma le_n_0_eq n : n <= 0 -> 0 = n.\nProof. hammer_hook \"Le\" \"Le.le_n_0_eq\".\nintros. symmetry. now apply Nat.le_0_r.\nQed.\n\n\n\n\n\nTheorem le_n_S : forall n m, n <= m -> S n <= S m.\nProof. hammer_hook \"Le\" \"Le.le_n_S\".  exact (Peano.le_n_S). Qed.\n\nTheorem le_S_n : forall n m, S n <= S m -> n <= m.\nProof. hammer_hook \"Le\" \"Le.le_S_n\".  exact (Peano.le_S_n). Qed.\n\nNotation le_n_Sn := Nat.le_succ_diag_r.\nNotation le_Sn_n := Nat.nle_succ_diag_l.\n\nTheorem le_Sn_le : forall n m, S n <= m -> n <= m.\nProof. hammer_hook \"Le\" \"Le.le_Sn_le\".  exact (Nat.lt_le_incl). Qed.\n\nHint Resolve le_0_n le_Sn_0: arith.\nHint Resolve le_n_S le_n_Sn le_Sn_n : arith.\nHint Immediate le_n_0_eq le_Sn_le le_S_n : arith.\n\n\n\nNotation le_pred_n := Nat.le_pred_l.\nNotation le_pred := Nat.pred_le_mono.\n\nHint Resolve le_pred_n: arith.\n\n\n\nLemma le_elim_rel :\nforall P:nat -> nat -> Prop,\n(forall p, P 0 p) ->\n(forall p (q:nat), p <= q -> P p q -> P (S p) (S q)) ->\nforall n m, n <= m -> P n m.\nProof. hammer_hook \"Le\" \"Le.le_elim_rel\".\nintros P H0 HS.\ninduction n; trivial.\nintros m Le. elim Le; auto with arith.\nQed.\n\n\nNotation le_O_n := le_0_n (only parsing).\nNotation le_Sn_O := le_Sn_0 (only parsing).\nNotation le_n_O_eq := le_n_0_eq (only parsing).\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/quick/Le.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.6899470779675216}}
{"text": "(*\nInductive appears_in {X:Type} (a:X) : list X -> Prop :=\n| singleton: appears_in a (cons a nil)\n| left: forall l l1, appears_in a l -> appears_in a (l1++l)\n| right: forall l l1, appears_in a l -> appears_in a (l++l1).\n\nExample ex1: appears_in 3 [1;3;2;4].\nProof.\n  apply (left 3 [3;2;4] [1]).\n  apply (right 3 [3] [2;4]).\n  apply singleton.\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/sf_sol/Midterm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.689864019029242}}
{"text": "\nRequire Export Chap3.\n\n\n(* Ordered Series *)\n\n\nDefinition asymmetrical {X : Type} (R : relation X) : Prop :=\n  forall x y, R x y -> ~(R y x).\n\nDefinition transitive {X: Type} (R: relation X) : Prop :=\n  forall x y z, R x y -> R y z -> R x z.\n\nDefinition connected {X: Type} (R: relation X) : Prop :=\n  forall x y, x <> y -> (R x y) /\\ (R y x).\n\nDefinition aliorelative {X: Type} (R: relation X) : Prop :=\n  forall x, ~(R x x).\n\nInductive square {X: Type} (R: relation X) : relation X :=\n  | sq0 : forall x y z, R x y -> R y z -> square R x z.\n\nInductive diversity {X} : relation X :=\n  | dv0 : forall x y, x <> y -> diversity x y.\n\n\n\n\n(* page 33:\nIt will be seen that an asymmetrical relation is the same thing as\na relation whose square is an aliorelative. It often happens that a\nrelation is an aliorelative without being asymmetrical, though an\nasymmetrical relation is always an aliorelative. For example, “spouse”\nis an aliorelative, but is symmetrical, since if x is the spouse of y, y is\nthe spouse of x. But among transitive relations, all aliorelatives are\nasymmetrical as well as vice versa.\n *)\nTheorem asy_implies_aliosq :\n  forall {X: Type} (R: relation X), asymmetrical R -> aliorelative (square R).\nProof.\n  intros.\n  unfold aliorelative.\n  intros.\n  unfold asymmetrical in H.\n  intro.\n  inversion H0.\n  subst.\n  apply H in H1.\n  apply H1 in H2.\n  inversion H2.\nQed.\n\nTheorem aliosq_implies_asy :\n  forall {X: Type} (R: relation X), aliorelative (square R) -> asymmetrical R.\nProof.\n  intros.\n  unfold aliorelative in H.\n  unfold asymmetrical.\n  intros.\n  intro.\n  assert (H': square R x x).\n  apply sq0 with y; assumption.\n  apply H in H'.\n  inversion H'.\nQed.\n\nTheorem asy_eqv_aliosq :\n  forall {X: Type} (R: relation X), aliorelative (square R) <-> asymmetrical R.\nProof.\n  intros.\n  split.\n  apply aliosq_implies_asy.\n  apply asy_implies_aliosq.\nQed.\n\n(* One relation is said to contain or be implied by another if it\nholds whenever the other holds.\n*)\n\nDefinition contains {X} (R Q: relation X) :=\n  forall x y, R x y -> Q x y.\n\n\n(*\nFrom the definitions it will be seen that a transitive relation is one\nwhich is implied by its square, or, as we also say, “contains” its square.\n*)\n\n(*\nTheorem sqself_imp_trans :\n  forall {X: Type} (R: relation X), (R = square R) -> transitive R.\nProof.\n  intros.\n  unfold transitive.\n  intros.\n  rewrite H.\n  apply sq0 with y; assumption.\nQed.\n*)\n\n(* Rectified theorem, this is exactly what the statement is talking *)\nTheorem sqself_imp_trans :\n  forall {X} (R: relation X), (contains (square R) R) -> transitive R.\nProof.\n  intros.\n  unfold transitive.\n  intros.\n  apply H.\n  apply sq0 with y; assumption.\nQed.\n\n\nTheorem trans_imp_sqself :\n  forall {X} (R: relation X), transitive R -> (contains (square R) R).\nProof.\n  unfold contains.\n  intros.\n  induction H0.\n  unfold transitive in H.\n  apply H with y; assumption.\nQed.\n\n\n(*\nA transitive aliorelative is one which contains its square\nand is contained in diversity; or, what comes to the same thing, one\nwhose square implies both it and diversity\n*)\n\nLemma diversity_eqv_aliorelative :\n  forall {X} (R: relation X), (contains R diversity) <-> aliorelative R.\nProof.\n  intros.\n  unfold aliorelative.\n  unfold contains.\n  split.\n\n  intros. intro.\n  apply H in H0.\n  inversion H0.\n  apply H1. reflexivity.\n\n  intros. intuition.\n  apply dv0. intro.\n  apply H with y.\n  rewrite H1 in H0.\n  assumption.\nQed.\n\nDefinition transitive_aliorelative {X} (R : relation X) : Prop :=\n  contains R (square R) /\\ contains R diversity.\n\nDefinition transitive_aliorelative' {X} (R : relation X) : Prop :=\n  contains (square R) R /\\ contains (square R) diversity.\n\n(* continued from above.\n—because, when a relation is transitive, asymmetry is equivalent\nto being an aliorelative.\n*)\n\nTheorem trans_imp_asym_eqv_alio :\n  forall {X} (R : relation X), transitive R -> (asymmetrical R <-> aliorelative R).\nProof.\n  unfold transitive.\n  unfold asymmetrical.\n  unfold aliorelative.\n  intros.\n  split.\n\n  intros. intro.\n  apply H0 with x x; assumption.\n\n  intros. intro.\n  apply H0 with x.\n  apply H with y; assumption.\nQed.\n\n(* A relation is connected when, given any two different terms of its field,\nthe relation holds between the first and the second or between the second and\nthe first (not excluding the possibility that both may happen, though both\ncannot happen if the relation is asymmetrical).\n*)\n\n(* Defined in the beginning as definition of 'connected' *)\n\n\n(* A relation is serial when it is an aliorelative, transitive,\nand connected; or, what is equivalent, when it is asymmetrical,\ntransitive, and connected.\n*)\n\nDefinition serial {X} (R : relation X) : Prop :=\n  aliorelative R /\\ transitive R /\\ connected R.\nDefinition serial' {X} (R : relation X) : Prop :=\n  asymmetrical R /\\ transitive R /\\ connected R.\n\n\n(*Definition proper_posterity {X} (R : relation X) *)\n\n(* page 36:\nThe “proper posterity” of x with respect to R consists of\nall terms that possess every R-hereditary property possessed by\nevery term to which x has the relation R.\n*)\n\n(* method 1: defining Type\nDefinition proper_posterity {X} (R : relation X) (x : X) :=\n  { y | forall (p : X -> Prop), r_hereditary R p -> R y x }.\n*)\n(* method 2: defining Prop *)\n\nDefinition proper_posterity {X} (R : relation X) (x : X) : X -> Prop :=\n  fun y => forall p, r_hereditary R p -> (forall t, R x t -> p t) -> p y.\n\n(*\nDefinition proper_posterity {X} (R : relation X) (x : X) (y : X) : Prop :=\n  r_posterity R y x /\\ R y x.\n*)\n\n(* A term x is a “proper ancestor” of y with respect to R if y\nbelongs to the proper posterity of x with respect to R.\n*)\n\nDefinition proper_ancestor {X} (R : relation X) (x : X) (y : X) : Prop :=\n  proper_posterity R y x.\n\n\n(* It will always be transitive: no matter what sort of relation\n   R may be, “R-ancestor” and “proper R-ancestor” are always both transitive.\n*)\n\nTheorem r_anc_trans {X} :\n  forall R : relation X, transitive (r_ancestor R).\nProof.\n  intros.\n  unfold transitive. unfold r_ancestor.\n  intros.\n  apply H0. exact H1.\n  apply H. exact H1.\n  assumption.\nQed.\n\nTheorem prop_anc_trans {X} :\n  forall R : relation X, transitive (proper_ancestor R).\nProof.\n  intros.\n  unfold transitive. unfold proper_ancestor. unfold proper_posterity.\n  intros.\n\n  apply H.\n  exact H1.\n  intros.\n  unfold r_hereditary in H1.\n  apply H1 with y.\n\n  apply H0.\n  exact H1.\n  intros. apply H2. assumption.\n\n  assumption.\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/imp/Chap4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.689864016295557}}
{"text": "(*\n   Coq Record\n   2010_10_21\n*)\n\n\n(****************************************)\n(* Inductive を使うコンストラクタの定義 *)\n(****************************************)\n\n\nInductive zero : Set :=                     (* 0要素 *)\n| Zero : zero.\nCheck zero.                                 (* Set *)\nCheck zero_rec.\nDefinition zero0 : zero -> nat :=\n  zero_rec (fun z:zero => nat)\n  0.\nEval cbv in zero0 (Zero).                   (* 0 *)\n\n\nInductive one : Set :=                      (* 1要素 *)\n| One : nat -> one.\nCheck one.                                  (* Set *)\nCheck one_rec.\nDefinition one1 : one -> nat :=\n  one_rec (fun o:one => nat)\n  (fun n:nat => n).\nEval cbv in one1 (One 1).                   (* 1 *)\n\n\nInductive two : Set :=                      (* 2要素 *)\n| Two : nat -> nat -> two.\nCheck two.                                  (* Set *)\nCheck two_rec.\nDefinition two1 : two -> nat :=             (* 第一要素 *)\n  two_rec (fun t:two => nat)\n  (fun n m:nat => n).\nEval cbv in two1 (Two 1 2).                 (* 1 *)\nDefinition two2 : two -> nat :=             (* 第二要素 *)\n  two_rec (fun t:two => nat)\n  (fun n m:nat => m).\nEval cbv in two2 (Two 1 2).                 (* 2 *)\n\n\n\n\nInductive o12 : Set :=\n| Zero' : o12\n| One' : nat -> o12\n| Two' : nat -> nat -> o12.\n\n\nCheck o12.                                  (* Set *)\nCheck o12_rec.\n\n\nDefinition o12012 : o12 -> nat :=\n  o12_rec (fun o:o12 => nat)\n  0\n  (fun n:nat => n)\n  (fun n m:nat => m).                       (* 第二要素 *)\n\n\nEval cbv in o12012 (Zero').                 (* 0 *)\nEval cbv in o12012 (One' 1).                (* 1 *)\nEval cbv in o12012 (Two' 1 2).              (* 2 *)\n\n\nDefinition o12011 : o12 -> nat :=\n  o12_rec (fun o:o12 => nat)\n  0\n  (fun n:nat => n)\n  (fun n m:nat => n).                       (* 第一要素 *)\n\n\nEval cbv in o12011 (Zero').                 (* 0 *)\nEval cbv in o12011 (One' 1).                (* 1 *)\nEval cbv in o12011 (Two' 1 2).              (* 1 *)\n\n\n\n\n(*******************************)\n(* Record を使うコンストラクタ *)\n(*******************************)\n\n\nRecord pair : Set :=\n  mkpair {first : nat; second : bool}.\n\n\nCheck pair.                                 (* Set *)\nCheck mkpair.                               (* nat -> bool -> pair *)\nCheck mkpair 1 true.                        (* pair *)\n\n\n(* セレクタは要素名を使えばよい *)\nEval cbv in first (mkpair 1 true).          (* 1 *)\nEval cbv in second (mkpair 1 true).         (* true *)\n\n\nCheck pair_rec.\n\n\nDefinition fst : pair -> nat :=\n  pair_rec (fun p:pair => nat)\n  (fun n:nat => (fun b:bool => n)).\nDefinition snd : pair -> bool :=\n  pair_rec (fun p:pair => bool)\n  (fun n:nat => (fun b:bool => b)).\n\n\n(* 型の宣言は省略できる。 *)\nDefinition fst' : pair -> nat :=\n  pair_rec (fun p => nat)\n  (fun n b => n).\nDefinition snd' : pair -> bool :=\n  pair_rec (fun p => bool)\n  (fun n b => b).\n\n\nEval cbv in fst (mkpair 1 true).            (* 1 *)\nEval cbv in snd (mkpair 1 true).            (* true *)\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_record.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6898267692751937}}
{"text": "Require Import ZArith.\nFrom Bremen.theories.harmony Require Import Letter PitchClass.\n\nInductive pitch : Set :=\n  p : pitchClass -> nat -> pitch.\n\nNotation \"PC ' O\" := (p PC O) (at level 85, right associativity).\n\nExample C2 := (C # 0) ' 2.\nExample Cb4 := (C # - 1) ' 4.\n\nDefinition class (x : pitch) : pitchClass :=\n  match x with\n  | pc ' o => pc\n  end.\n\nDefinition octave (x : pitch) : nat :=\n  match x with\n  | pc ' o => o\n  end.\n\nDefinition sharpen (x : pitch) : pitch :=\n  sharpen (class x) ' (octave x).\n\nDefinition flatten (x : pitch) : pitch :=\n  flatten (class x) ' (octave x).\n\nDefinition distance_C0 (x : pitch) : Z :=\n Z.of_nat(PitchClass.upward_distance (C # 0) (class x)) + (Z.of_nat(octave x) * 12).\n\nDefinition distance (x y : pitch) : nat :=\n  N.to_nat(Z.to_N (Zminus (distance_C0 x) (distance_C0 y))).\n\nDefinition enharmonic_eq (x y : pitch) : Prop :=\n  distance_C0 x = distance_C0 y.\n\nNotation \"X ee= Y\" := (enharmonic_eq X Y) (at level 90, right associativity).\n\nDefinition halfstep_up (x : pitch) : pitch :=\n  match x with\n  | B # m ' o => halfstep_up (B # m) ' o + 1\n  | l # m ' o => halfstep_up (l # m) ' o\n  end.\n\nNotation \"> X\" := (halfstep_up X) (at level 90, right associativity).\n\nDefinition wholestep_up (x : pitch) : pitch :=\n  sharpen (> x).\n\nNotation \">> X\" := (wholestep_up X) (at level 90, right associativity).\n\n(* pitch-ek távolságára vonatkozó állítások *)\nLemma distance_enharmonic : forall (x y : pitch), distance x y = 0 -> enharmonic_eq x y. Proof. Admitted.\nLemma distance_to_from : forall (x y : pitch), distance x y + distance y x = 0. Proof. Admitted.\nLemma distance_triangle : forall (x y z : pitch), distance x z <= distance x y + distance y z. Proof. Admitted.\n\n(* pitch-ek enharmóniai összefüggései *)\nLemma enharmonic_xx : forall (x : pitch), enharmonic_eq x x. Proof. Admitted.\nLemma enharmonix_xy_yx : forall (x y : pitch), enharmonic_eq x y -> enharmonic_eq y x. Proof. Admitted.\nLemma enharmonic_transitivity : forall (x y z : pitch), (enharmonic_eq x y) /\\ (enharmonic_eq y z) -> enharmonic_eq x z.\nProof. Admitted.\nLemma enharmonic_halfstep_up : forall (x y : pitch), enharmonic_eq x y -> enharmonic_eq (halfstep_up x) (halfstep_up y).\nProof. Admitted.", "meta": {"author": "fajtaiandris", "repo": "bremen", "sha": "49d9324e5894d86966884f681c09d9db876a6d09", "save_path": "github-repos/coq/fajtaiandris-bremen", "path": "github-repos/coq/fajtaiandris-bremen/bremen-49d9324e5894d86966884f681c09d9db876a6d09/theories/harmony/Pitch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963206, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6897517605071147}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria.                       *)\n(* You may distribute this file under the terms of the CeCILL-B license *)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq path div choice.\nRequire Import fintype tuple finfun bigop prime ssralg poly ssrnum ssrint rat.\nRequire Import polydiv finalg perm zmodp matrix mxalgebra vector.\n\n(******************************************************************************)\n(* This file provides various results on divisibility of integers.            *)\n(* It defines, for m, n, d : int,                                             *)\n(*   (m %% d)%Z == the remainder of the Euclidean division of m by d; this is *)\n(*                 the least non-negative element of the coset m + dZ when    *)\n(*                 d != 0, and m if d = 0.                                    *)\n(*   (m %/ d)%Z == the quotient of the Euclidean division of m by d, such     *)\n(*                 that m = (m %/ d)%Z * d + (m %% d)%Z. Since for d != 0 the *)\n(*                 remainder is non-negative, (m %/ d)%Z is non-zero for      *)\n(*   (d %| m)%Z <=> m is divisible by d; dvdz d is the (collective) predicate *)\n(*                 for integers divisible by d, and (d %| m)%Z is actually    *)\n(*                 (transposing) notation for m \\in dvdz d.                   *)\n(* (m = n %[mod d])%Z, (m == n %[mod d])%Z, (m != n %[mod d])%Z               *)\n(*                 m and n are (resp. compare, don't compare) equal mod d.    *)\n(*     gcdz m n == the (non-negative) greatest common divisor of m and n,     *)\n(*                 with gcdz 0 0 = 0.                                         *)\n(* coprimez m n <=> m and n are coprime.                                      *)\n(*    egcdz m n == the Bezout coefficients of the gcd of m and n: a pair      *)\n(*                 (u, v) of coprime integers such that u*m + v*n = gcdz m n. *)\n(*                 Alternatively, a Bezoutz lemma states such u and v exist.  *)\n(* zchinese m1 m2 n1 n2 == for coprime m1 and m2, a solution to the Chinese   *)\n(*                 remainder problem for n1 and n2, i.e., and integer n such  *)\n(*                 that n = n1 %[mod m1] and n = n2 %[mod m2].                *)\n(*  zcontents p == the contents of p : {poly int}, that is, the gcd of the    *)\n(*                 coefficients of p, with the lead coefficient of p,         *)\n(* zprimitive p == the primitive part of p : {poly int}, i.e., p divided by   *)\n(*                 its contents.                                              *)\n(* inIntSpan X v <-> v is an integral linear combination of elements of       *)\n(*                 X : seq V, where V is a zmodType. We prove that this is a  *)\n(*                 decidable property for Q-vector spaces.                    *)\n(* int_Smith_normal_form :: a theorem asserting the existence of the Smith    *)\n(*                 normal form for integer matrices.                          *)\n(* Note that many of the concepts and results in this file could and perhaps  *)\n(* sould be generalized to the more general setting of integral, unique       *)\n(* factorization, principal ideal, or Euclidean domains.                      *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory Num.Theory.\nLocal Open Scope ring_scope.\n\nDefinition divz (m d : int) :=\n  let: (K, n) := match m with Posz n => (Posz, n) | Negz n => (Negz, n) end in\n  sgz d * K (n %/ `|d|)%N.\n\nDefinition modz (m d : int) : int := m - divz m d * d.\n\nDefinition dvdz d m := (`|d| %| `|m|)%N.\n\nDefinition gcdz m n := (gcdn `|m| `|n|)%:Z.\n\nDefinition egcdz m n : int * int :=\n  if m == 0 then (0, (-1) ^+ (n < 0)%R) else\n  let: (u, v) := egcdn `|m| `|n| in (sgz m * u, - (-1) ^+ (n < 0)%R * v%:Z).\n\nDefinition coprimez m n := (gcdz m n == 1).\n\nInfix \"%/\" := divz : int_scope.\nInfix \"%%\" := modz : int_scope.\nNotation \"d %| m\" := (m \\in dvdz d) : int_scope.\nNotation \"m = n %[mod d ]\" := (modz m d = modz n d) : int_scope.\nNotation \"m == n %[mod d ]\" := (modz m d == modz n d) : int_scope.\nNotation \"m <> n %[mod d ]\" := (modz m d <> modz n d) : int_scope.\nNotation \"m != n %[mod d ]\" := (modz m d != modz n d) : int_scope.\n\nLemma divz_nat (n d : nat) : (n %/ d)%Z = (n %/ d)%N.\nProof. by case: d => // d; rewrite /divz /= mul1r. Qed.\n\nLemma divzN m d : (m %/ - d)%Z = - (m %/ d)%Z.\nProof. by case: m => n; rewrite /divz /= sgzN abszN mulNr. Qed.\n\nLemma divz_abs m d : (m %/ `|d|)%Z = (-1) ^+ (d < 0)%R * (m %/ d)%Z.\nProof.\nby rewrite {3}[d]intEsign !mulr_sign; case: ifP => -> //; rewrite divzN opprK.\nQed.\n\nLemma div0z d : (0 %/ d)%Z = 0.\nProof.\nby rewrite -(canLR (signrMK _) (divz_abs _ _)) (divz_nat 0) div0n mulr0.\nQed.\n\nLemma divNz_nat m d : (d > 0)%N -> (Negz m %/ d)%Z = - (m %/ d).+1%:Z.\nProof. by case: d => // d _; apply: mul1r. Qed.\n\nLemma divz_eq m d : m = (m %/ d)%Z * d + (m %% d)%Z.\nProof. by rewrite addrC subrK. Qed.\n\nLemma modzN m d : (m %% - d)%Z = (m %% d)%Z.\nProof. by rewrite /modz divzN mulrNN. Qed.\n\nLemma modz_abs m d : (m %% `|d|%N)%Z = (m %% d)%Z.\nProof. by rewrite {2}[d]intEsign mulr_sign; case: ifP; rewrite ?modzN. Qed.\n\nLemma modz_nat (m d : nat) : (m %% d)%Z = (m %% d)%N.\nProof.\nby apply: (canLR (addrK _)); rewrite addrC divz_nat {1}(divn_eq m d).\nQed.\n\nLemma modNz_nat m d : (d > 0)%N -> (Negz m %% d)%Z = d%:Z - 1 - (m %% d)%:Z.\nProof.\nrewrite /modz => /divNz_nat->; apply: (canLR (addrK _)).\nrewrite -!addrA -!opprD -!PoszD -opprB mulnSr !addnA PoszD addrK.\nby rewrite addnAC -addnA mulnC -divn_eq.\nQed.\n\nLemma modz_ge0 m d : d != 0 -> 0 <= (m %% d)%Z.\nProof.\nrewrite -absz_gt0 -modz_abs => d_gt0.\ncase: m => n; rewrite ?modNz_nat ?modz_nat // -addrA -opprD subr_ge0.\nby rewrite lez_nat ltn_mod.\nQed.\n\nLemma divz0 m : (m %/ 0)%Z = 0. Proof. by case: m. Qed.\nLemma mod0z d : (0 %% d)%Z = 0. Proof. by rewrite /modz div0z mul0r subrr. Qed.\nLemma modz0 m : (m %% 0)%Z = m. Proof. by rewrite /modz mulr0 subr0. Qed.\n\nLemma divz_small m d : 0 <= m < `|d|%:Z -> (m %/ d)%Z = 0.\nProof.\nrewrite -(canLR (signrMK _) (divz_abs _ _)); case: m => // n /divn_small.\nby rewrite divz_nat => ->; rewrite mulr0.\nQed.\n\nLemma divzMDl q m d : d != 0 -> ((q * d + m) %/ d)%Z = q + (m %/ d)%Z.\nProof.\nrewrite neqr_lt -oppr_gt0 => nz_d.\nwlog{nz_d} d_gt0: q d / d > 0; last case: d => // d in d_gt0 *.\n  move=> IH; case/orP: nz_d => /IH// /(_  (- q)).\n  by rewrite mulrNN !divzN -opprD => /oppr_inj.\nwlog q_gt0: q m / q >= 0; last case: q q_gt0 => // q _.\n  move=> IH; case: q => n; first exact: IH; rewrite NegzE mulNr.\n  by apply: canRL (addKr _) _; rewrite -IH ?addNKr.\ncase: m => n; first by rewrite !divz_nat divnMDl.\nhave [le_qd_n | lt_qd_n] := leqP (q * d) n.\n  rewrite divNz_nat // NegzE -(subnKC le_qd_n) divnMDl //.\n  by rewrite -!addnS !PoszD !opprD !addNKr divNz_nat.\nrewrite divNz_nat // NegzE -PoszM subzn // divz_nat.\napply: canRL (addrK _) _; congr _%:Z; rewrite addnC -divnMDl // mulSnr.\nrewrite -{3}(subnKC (ltn_pmod n d_gt0)) addnA addnS -divn_eq addnAC.\nby rewrite subnKC // divnMDl // divn_small ?addn0 // subnSK ?ltn_mod ?leq_subr.\nQed.\n\nLemma mulzK m d : d != 0 -> (m * d %/ d)%Z = m.\nProof. by move=> d_nz; rewrite -[m * d]addr0 divzMDl // div0z addr0. Qed.\n\nLemma mulKz m d : d != 0 -> (d * m %/ d)%Z = m.\nProof. by move=> d_nz; rewrite mulrC mulzK. Qed.\n\nLemma expzB p m n : p != 0 -> (m >= n)%N -> p ^+ (m - n) = (p ^+ m %/ p ^+ n)%Z.\nProof. by move=> p_nz /subnK{2}<-; rewrite exprD mulzK // expf_neq0. Qed.\n\nLemma modz1 m : (m %% 1)%Z = 0.\nProof. by case: m => n; rewrite (modNz_nat, modz_nat) ?modn1. Qed.\n\nLemma divn1 m : (m %/ 1)%Z = m. Proof. by rewrite -{1}[m]mulr1 mulzK. Qed.\n\nLemma divzz d : (d %/ d)%Z = (d != 0).\nProof. by have [-> // | d_nz] := altP eqP; rewrite -{1}[d]mul1r mulzK. Qed.\n\nLemma ltz_pmod m d : d > 0 -> (m %% d)%Z < d.\nProof.\ncase: m d => n [] // d d_gt0; first by rewrite modz_nat ltz_nat ltn_pmod.\nby rewrite modNz_nat // -lez_addr1 addrAC subrK ger_addl oppr_le0.\nQed.\n\nLemma ltz_mod m d : d != 0 -> (m %% d)%Z < `|d|.\nProof. by rewrite -absz_gt0 -modz_abs => d_gt0; apply: ltz_pmod. Qed.\n\nLemma divzMpl p m d : p > 0 -> (p * m %/ (p * d) = m %/ d)%Z.\nProof.\ncase: p => // p p_gt0; wlog d_gt0: d / d > 0; last case: d => // d in d_gt0 *.\n  by move=> IH; case/intP: d => [|d|d]; rewrite ?mulr0 ?divz0 ?mulrN ?divzN ?IH.\nrewrite {1}(divz_eq m d) mulrDr mulrCA divzMDl ?mulf_neq0 ?gtr_eqF // addrC.\nrewrite divz_small ?add0r // PoszM pmulr_rge0 ?modz_ge0 ?gtr_eqF //=.\nby rewrite ltr_pmul2l ?ltz_pmod.\nQed.\nImplicit Arguments divzMpl [p m d].\n\nLemma divzMpr p m d : p > 0 -> (m * p %/ (d * p) = m %/ d)%Z.\nProof. by move=> p_gt0; rewrite -!(mulrC p) divzMpl. Qed.\nImplicit Arguments divzMpr [p m d].\n\nLemma lez_floor m d : d != 0 -> (m %/ d)%Z * d <= m.\nProof. by rewrite -subr_ge0; apply: modz_ge0. Qed.\n\n(* leq_mod does not extend to negative m. *)\nLemma lez_div m d : (`|(m %/ d)%Z| <= `|m|)%N.\nProof.\nwlog d_gt0: d / d > 0; last case: d d_gt0 => // d d_gt0.\n  by move=> IH; case/intP: d => [|n|n]; rewrite ?divz0 ?divzN ?abszN // IH.\ncase: m => n; first by rewrite divz_nat leq_div.\nby rewrite divNz_nat // NegzE !abszN ltnS leq_div.\nQed.\n \nLemma ltz_ceil m d : d > 0 -> m < ((m %/ d)%Z + 1) * d.\nProof.\nby case: d => // d d_gt0; rewrite mulrDl mul1r -ltr_subl_addl ltz_mod ?gtr_eqF.\nQed.\n\nLemma ltz_divLR m n d : d > 0 -> ((m %/ d)%Z < n) = (m < n * d).\nProof.\nmove=> d_gt0; apply/idP/idP.\n  by rewrite -lez_addr1 -(ler_pmul2r d_gt0); apply: ltr_le_trans (ltz_ceil _ _).\nrewrite -(ltr_pmul2r d_gt0 _ n) //; apply: ler_lt_trans (lez_floor _ _).\nby rewrite gtr_eqF.\nQed.\n\nLemma lez_divRL m n d : d > 0 -> (m <= (n %/ d)%Z) = (m * d <= n).\nProof. by move=> d_gt0; rewrite !lerNgt ltz_divLR. Qed.\n\nLemma divz_ge0 m d : d > 0 -> ((m %/ d)%Z >= 0) = (m >= 0).\nProof. by case: d m => // d [] n d_gt0; rewrite (divz_nat, divNz_nat). Qed.\n\nLemma divzMA_ge0 m n p : n >= 0 -> (m %/ (n * p) = (m %/ n)%Z %/ p)%Z. \nProof.\ncase: n => // [[|n]] _; first by rewrite mul0r !divz0 div0z.\nwlog p_gt0: p / p > 0; last case: p => // p in p_gt0 *.\n  by case/intP: p => [|p|p] IH; rewrite ?mulr0 ?divz0 ?mulrN ?divzN // IH.\nrewrite {2}(divz_eq m (n.+1%:Z * p)) mulrA mulrAC !divzMDl // ?gtr_eqF //.\nrewrite [rhs in _ + rhs]divz_small ?addr0 // ltz_divLR // divz_ge0 //.\nby rewrite mulrC ltz_pmod ?modz_ge0 ?gtr_eqF ?pmulr_lgt0.\nQed.\n\nLemma modz_small m d : 0 <= m < d -> (m %% d)%Z = m.\nProof. by case: m d => //= m [] // d; rewrite modz_nat => /modn_small->. Qed.\n\nLemma modz_mod m d : ((m %% d)%Z = m %[mod d])%Z.\nProof.\nrewrite -!(modz_abs _ d); case: {d}`|d|%N => [|d]; first by rewrite !modz0.\nby rewrite modz_small ?modz_ge0 ?ltz_mod.\nQed.\n\nLemma modzMDl p m d : (p * d + m = m %[mod d])%Z.\nProof.\nhave [-> | d_nz] := eqVneq d 0; first by rewrite mulr0 add0r.\nby rewrite /modz divzMDl // mulrDl opprD addrACA subrr add0r.\nQed.\n\nLemma mulz_modr {p m d} : 0 < p -> p * (m %% d)%Z = ((p * m) %% (p * d))%Z.\nProof.\ncase: p => // p p_gt0; rewrite mulrBr; apply: canLR (addrK _) _.\nby rewrite mulrCA -(divzMpl p_gt0) subrK.\nQed.\n\nLemma mulz_modl {p m d} : 0 < p -> (m %% d)%Z * p = ((m * p) %% (d * p))%Z.\nProof. by rewrite -!(mulrC p); apply: mulz_modr. Qed.\n\nLemma modzDl m d : (d + m = m %[mod d])%Z.\nProof. by rewrite -{1}[d]mul1r modzMDl. Qed.\n\nLemma modzDr m d : (m + d = m %[mod d])%Z.\nProof. by rewrite addrC modzDl. Qed.\n\nLemma modzz d : (d %% d)%Z = 0.\nProof. by rewrite -{1}[d]addr0 modzDl mod0z. Qed.\n\nLemma modzMl p d : (p * d %% d)%Z = 0.\nProof. by rewrite -[p * d]addr0 modzMDl mod0z. Qed.\n\nLemma modzMr p d : (d * p %% d)%Z = 0.\nProof. by rewrite mulrC modzMl. Qed.\n\nLemma modzDml m n d : ((m %% d)%Z + n = m + n %[mod d])%Z.\nProof. by rewrite {2}(divz_eq m d) -[_ * d + _ + n]addrA modzMDl. Qed.\n\nLemma modzDmr m n d : (m + (n %% d)%Z = m + n %[mod d])%Z.\nProof. by rewrite !(addrC m) modzDml. Qed.\n\nLemma modzDm m n d : ((m %% d)%Z + (n %% d)%Z = m + n %[mod d])%Z.\nProof. by rewrite modzDml modzDmr. Qed.\n\nLemma eqz_modDl p m n d : (p + m == p + n %[mod d])%Z = (m == n %[mod d])%Z.\nProof.\nhave [-> | d_nz] := eqVneq d 0; first by rewrite !modz0 (inj_eq (addrI p)).\napply/eqP/eqP=> eq_mn; last by rewrite -modzDmr eq_mn modzDmr.\nby rewrite -(addKr p m) -modzDmr eq_mn modzDmr addKr.\nQed.\n\nLemma eqz_modDr p m n d : (m + p == n + p %[mod d])%Z = (m == n %[mod d])%Z.\nProof. by rewrite -!(addrC p) eqz_modDl. Qed.\n\nLemma modzMml m n d : ((m %% d)%Z * n = m * n %[mod d])%Z.\nProof. by rewrite {2}(divz_eq m d) mulrDl mulrAC modzMDl. Qed.\n\nLemma modzMmr m n d : (m * (n %% d)%Z = m * n %[mod d])%Z.\nProof. by rewrite !(mulrC m) modzMml. Qed.\n\nLemma modzMm m n d : ((m %% d)%Z * (n %% d)%Z = m * n %[mod d])%Z.\nProof. by rewrite modzMml modzMmr. Qed.\n\nLemma modzXm k m d : ((m %% d)%Z ^+ k = m ^+ k %[mod d])%Z.\nProof. by elim: k => // k IHk; rewrite !exprS -modzMmr IHk modzMm. Qed.\n\nLemma modzNm m d : (- (m %% d)%Z = - m %[mod d])%Z.\nProof. by rewrite -mulN1r modzMmr mulN1r. Qed.\n\nLemma modz_absm m d : ((-1) ^+ (m < 0)%R * (m %% d)%Z = `|m|%:Z %[mod d])%Z.\nProof. by rewrite modzMmr -abszEsign. Qed.\n\n(** Divisibility **)\n\nFact dvdz_key d : pred_key (dvdz d). Proof. by []. Qed.\nCanonical dvdz_keyed d := KeyedPred (dvdz_key d).\n\nLemma dvdzE d m : (d %| m)%Z = (`|d| %| `|m|)%N. Proof. by []. Qed.\nLemma dvdz0 d : (d %| 0)%Z. Proof. exact: dvdn0. Qed.\nLemma dvd0z n : (0 %| n)%Z = (n == 0). Proof. by rewrite -absz_eq0 -dvd0n. Qed.\nLemma dvdz1 d : (d %| 1)%Z = (`|d|%N == 1%N). Proof. exact: dvdn1. Qed.\nLemma dvd1z m : (1 %| m)%Z. Proof. exact: dvd1n. Qed.\nLemma dvdzz m : (m %| m)%Z. Proof. exact: dvdnn. Qed.\n\nLemma dvdz_mull d m n : (d %| n)%Z -> (d %| m * n)%Z.\nProof. by rewrite !dvdzE abszM; apply: dvdn_mull. Qed.\n\nLemma dvdz_mulr d m n : (d %| m)%Z -> (d %| m * n)%Z.\nProof. by move=> d_m; rewrite mulrC dvdz_mull. Qed.\nHint Resolve dvdz0 dvd1z dvdzz dvdz_mull dvdz_mulr.\n\nLemma dvdz_mul d1 d2 m1 m2 : (d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2)%Z.\nProof. by rewrite !dvdzE !abszM; apply: dvdn_mul. Qed.\n\nLemma dvdz_trans n d m : (d %| n -> n %| m -> d %| m)%Z.\nProof. by rewrite !dvdzE; apply: dvdn_trans. Qed.\n\nLemma dvdzP d m : reflect (exists q, m = q * d) (d %| m)%Z.\nProof.\napply: (iffP dvdnP) => [] [q Dm]; last by exists `|q|%N; rewrite Dm abszM.\nexists ((-1) ^+ (m < 0)%R * q%:Z * (-1) ^+ (d < 0)%R).\nby rewrite -!mulrA -abszEsign -PoszM -Dm -intEsign.\nQed.\nImplicit Arguments dvdzP [d m].\n\nLemma dvdz_mod0P d m : reflect (m %% d = 0)%Z (d %| m)%Z.\nProof.\napply: (iffP dvdzP) => [[q ->] | md0]; first by rewrite modzMl.\nby rewrite (divz_eq m d) md0 addr0; exists (m %/ d)%Z.\nQed.\nImplicit Arguments dvdz_mod0P [d m].\n\nLemma dvdz_eq d m : (d %| m)%Z = ((m %/ d)%Z * d == m).\nProof. by rewrite (sameP dvdz_mod0P eqP) subr_eq0 eq_sym. Qed.\n\nLemma divzK d m : (d %| m)%Z -> (m %/ d)%Z * d = m.\nProof. by rewrite dvdz_eq => /eqP. Qed.\n\nLemma lez_divLR d m n : 0 < d -> (d %| m)%Z -> ((m %/ d)%Z <= n) = (m <= n * d).\nProof. by move=> /ler_pmul2r <- /divzK->. Qed.\n\nLemma ltz_divRL d m n : 0 < d -> (d %| m)%Z -> (n < m %/ d)%Z = (n * d < m).\nProof. by move=> /ltr_pmul2r <- /divzK->. Qed.\n\nLemma eqz_div d m n : d != 0 -> (d %| m)%Z -> (n == m %/ d)%Z = (n * d == m).\nProof. by move=> /mulIf/inj_eq <- /divzK->. Qed.\n\nLemma eqz_mul d m n : d != 0 -> (d %| m)%Z -> (m == n * d) = (m %/ d == n)%Z.\nProof. by move=> d_gt0 dv_d_m; rewrite eq_sym -eqz_div // eq_sym. Qed.\n\nLemma divz_mulAC d m n : (d %| m)%Z -> (m %/ d)%Z * n = (m * n %/ d)%Z.\nProof.\nhave [-> | d_nz] := eqVneq d 0; first by rewrite !divz0 mul0r.\nby move/divzK=> {2} <-; rewrite mulrAC mulzK.\nQed.\n\nLemma mulz_divA d m n : (d %| n)%Z -> m * (n %/ d)%Z = (m * n %/ d)%Z.\nProof. by move=> dv_d_m; rewrite !(mulrC m) divz_mulAC. Qed.\n\nLemma mulz_divCA d m n :\n  (d %| m)%Z -> (d %| n)%Z -> m * (n %/ d)%Z = n * (m %/ d)%Z.\nProof. by move=> dv_d_m dv_d_n; rewrite mulrC divz_mulAC ?mulz_divA. Qed.\n\nLemma divzA m n p : (p %| n -> n %| m * p -> m %/ (n %/ p)%Z = m * p %/ n)%Z.\nProof.\nmove/divzK=> p_dv_n; have [->|] := eqVneq n 0; first by rewrite div0z !divz0.\nrewrite -{1 2}p_dv_n mulf_eq0 => /norP[pn_nz p_nz] /divzK; rewrite mulrA p_dv_n.\nby move/mulIf=> {1} <- //; rewrite mulzK.\nQed.\n\nLemma divzMA m n p : (n * p %| m -> m %/ (n * p) = (m %/ n)%Z %/ p)%Z.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 !divz0.\nhave [-> | nz_n] := eqVneq n 0; first by rewrite mul0r !divz0 div0z.\nby move/divzK=> {2} <-; rewrite mulrA mulrAC !mulzK.\nQed.\n\nLemma divzAC m n p : (n * p %| m -> (m %/ n)%Z %/ p =  (m %/ p)%Z %/ n)%Z.\nProof. by move=> np_dv_mn; rewrite -!divzMA // mulrC. Qed.\n\nLemma divzMl p m d : p != 0 -> (d %| m -> p * m %/ (p * d) = m %/ d)%Z.\nProof.\nhave [-> | nz_d nz_p] := eqVneq d 0; first by rewrite mulr0 !divz0.\nby move/divzK=> {1}<-; rewrite mulrCA mulzK ?mulf_neq0.\nQed.\n\nLemma divzMr p m d : p != 0 -> (d %| m -> m * p %/ (d * p) = m %/ d)%Z.\nProof. by rewrite -!(mulrC p); apply: divzMl. Qed.\n\nLemma dvdz_mul2l p d m : p != 0 -> (p * d %| p * m)%Z = (d %| m)%Z.\nProof. by rewrite !dvdzE -absz_gt0 !abszM; apply: dvdn_pmul2l. Qed.\nImplicit Arguments dvdz_mul2l [p m d].\n\nLemma dvdz_mul2r p d m : p != 0 -> (d * p %| m * p)%Z = (d %| m)%Z.\nProof. by rewrite !dvdzE -absz_gt0 !abszM; apply: dvdn_pmul2r. Qed.\nImplicit Arguments dvdz_mul2r [p m d].\n\nLemma dvdz_exp2l p m n : (m <= n)%N -> (p ^+ m %| p ^+ n)%Z.\nProof. by rewrite dvdzE !abszX; apply: dvdn_exp2l. Qed.\n\nLemma dvdz_Pexp2l p m n : `|p| > 1 -> (p ^+ m %| p ^+ n)%Z = (m <= n)%N.\nProof. by rewrite dvdzE !abszX ltz_nat; apply: dvdn_Pexp2l. Qed.\n\nLemma dvdz_exp2r m n k : (m %| n -> m ^+ k %| n ^+ k)%Z.\nProof. by rewrite !dvdzE !abszX; apply: dvdn_exp2r. Qed.\n\nFact dvdz_zmod_closed d : zmod_closed (dvdz d).\nProof.\nsplit=> [|_ _ /dvdzP[p ->] /dvdzP[q ->]]; first exact: dvdz0.\nby rewrite -mulrBl dvdz_mull.\nQed.\nCanonical dvdz_addPred d := AddrPred (dvdz_zmod_closed d).\nCanonical dvdz_oppPred d := OpprPred (dvdz_zmod_closed d).\nCanonical dvdz_zmodPred d := ZmodPred (dvdz_zmod_closed d).\n  \nLemma dvdz_exp k d m : (0 < k)%N -> (d %| m -> d %| m ^+ k)%Z.\nProof. by case: k => // k _ d_dv_m; rewrite exprS dvdz_mulr. Qed.\n\nLemma eqz_mod_dvd d m n : (m == n %[mod d])%Z = (d %| m - n)%Z.\nProof.\napply/eqP/dvdz_mod0P=> eq_mn.\n  by rewrite -modzDml eq_mn modzDml subrr mod0z.\nby rewrite -(subrK n m) -modzDml eq_mn add0r.\nQed.\n\nLemma divzDl m n d :\n  (d %| m)%Z -> ((m + n) %/ d)%Z = (m %/ d)%Z + (n %/ d)%Z.\nProof.\nhave [-> | d_nz] := eqVneq d 0; first by rewrite !divz0.\nby move/divzK=> {1}<-; rewrite divzMDl.\nQed.\n\nLemma divzDr m n d :\n  (d %| n)%Z -> ((m + n) %/ d)%Z = (m %/ d)%Z + (n %/ d)%Z.\nProof. by move=> dv_n; rewrite addrC divzDl // addrC. Qed.\n\n(* Greatest common divisor *)\n\nLemma gcdzz m : gcdz m m = `|m|%:Z. Proof. by rewrite /gcdz gcdnn. Qed.\nLemma gcdzC : commutative gcdz. Proof. by move=> m n; rewrite /gcdz gcdnC. Qed.\nLemma gcd0z m : gcdz 0 m = `|m|%:Z. Proof. by rewrite /gcdz gcd0n. Qed.\nLemma gcdz0 m : gcdz m 0 = `|m|%:Z. Proof. by rewrite /gcdz gcdn0. Qed.\nLemma gcd1z : left_zero 1 gcdz. Proof. by move=> m; rewrite /gcdz gcd1n. Qed.\nLemma gcdz1 : right_zero 1 gcdz. Proof. by move=> m; rewrite /gcdz gcdn1. Qed.\nLemma dvdz_gcdr m n : (gcdz m n %| n)%Z. Proof. exact: dvdn_gcdr. Qed.\nLemma dvdz_gcdl m n : (gcdz m n %| m)%Z. Proof. exact: dvdn_gcdl. Qed.\nLemma gcdz_eq0 m n : (gcdz m n == 0) = (m == 0) && (n == 0).\nProof. by rewrite -absz_eq0 eqn0Ngt gcdn_gt0 !negb_or -!eqn0Ngt !absz_eq0. Qed.\nLemma gcdNz m n : gcdz (- m) n = gcdz m n. Proof. by rewrite /gcdz abszN. Qed.\nLemma gcdzN m n : gcdz m (- n) = gcdz m n. Proof. by rewrite /gcdz abszN. Qed.\n\nLemma gcdz_modr m n : gcdz m (n %% m)%Z = gcdz m n.\nProof.\nrewrite -modz_abs /gcdz; move/absz: m => m.\nhave [-> | m_gt0] := posnP m; first by rewrite modz0.\ncase: n => n; first by rewrite modz_nat gcdn_modr.\nrewrite modNz_nat // NegzE abszN {2}(divn_eq n m) -addnS gcdnMDl.\nrewrite -addrA -opprD -intS /=; set m1 := _.+1.\nhave le_m1m: (m1 <= m)%N by exact: ltn_pmod.\nby rewrite subzn // !(gcdnC m) -{2 3}(subnK le_m1m) gcdnDl gcdnDr gcdnC.\nQed.\n\nLemma gcdz_modl m n : gcdz (m %% n)%Z n = gcdz m n.\nProof. by rewrite -!(gcdzC n) gcdz_modr. Qed.\n\nLemma gcdzMDl q m n : gcdz m (q * m + n) = gcdz m n.\nProof. by rewrite -gcdz_modr modzMDl gcdz_modr. Qed.\n \nLemma gcdzDl m n : gcdz m (m + n) = gcdz m n.\nProof. by rewrite -{2}(mul1r m) gcdzMDl. Qed.\n\nLemma gcdzDr m n : gcdz m (n + m) = gcdz m n.\nProof. by rewrite addrC gcdzDl. Qed.\n\nLemma gcdzMl n m : gcdz n (m * n) = `|n|%:Z.\nProof. by rewrite -[m * n]addr0 gcdzMDl gcdz0. Qed.\n\nLemma gcdzMr n m : gcdz n (n * m) = `|n|%:Z.\nProof. by rewrite mulrC gcdzMl. Qed.\n\nLemma gcdz_idPl {m n} : reflect (gcdz m n = `|m|%:Z) (m %| n)%Z.\nProof. by apply: (iffP gcdn_idPl) => [<- | []]. Qed.\n\nLemma gcdz_idPr {m n} : reflect (gcdz m n = `|n|%:Z) (n %| m)%Z.\nProof. by rewrite gcdzC; apply: gcdz_idPl. Qed.\n\nLemma expz_min e m n : e >= 0 -> e ^+ minn m n = gcdz (e ^+ m) (e ^+ n).\nProof.\nby case: e => // e _; rewrite /gcdz !abszX -expn_min -natz -natrX !natz.\nQed.\n\nLemma dvdz_gcd p m n : (p %| gcdz m n)%Z = (p %| m)%Z && (p %| n)%Z.\nProof. exact: dvdn_gcd. Qed.\n\nLemma gcdzAC : right_commutative gcdz.\nProof. by move=> m n p; rewrite /gcdz gcdnAC. Qed.\n\nLemma gcdzA : associative gcdz.\nProof. by move=> m n p; rewrite /gcdz gcdnA. Qed.\n\nLemma gcdzCA : left_commutative gcdz.\nProof. by move=> m n p; rewrite /gcdz gcdnCA. Qed.\n\nLemma gcdzACA : interchange gcdz gcdz.\nProof. by move=> m n p q; rewrite /gcdz gcdnACA. Qed.\n\nLemma mulz_gcdr m n p : `|m|%:Z * gcdz n p = gcdz (m * n) (m * p).\nProof. by rewrite -PoszM muln_gcdr -!abszM. Qed.\n\nLemma mulz_gcdl m n p : gcdz m n * `|p|%:Z = gcdz (m * p) (n * p).\nProof. by rewrite -PoszM muln_gcdl -!abszM. Qed.\n\nLemma mulz_divCA_gcd n m : n * (m %/ gcdz n m)%Z  = m * (n %/ gcdz n m)%Z.\nProof. by rewrite mulz_divCA ?dvdz_gcdl ?dvdz_gcdr. Qed.\n\n(* Not including lcm theory, for now. *)\n\n(* Coprime factors *)\n\nLemma coprimezE m n : coprimez m n = coprime `|m| `|n|. Proof. by []. Qed.\n\nLemma coprimez_sym : symmetric coprimez.\nProof. by move=> m n; apply: coprime_sym. Qed.\n\nLemma coprimeNz m n : coprimez (- m) n = coprimez m n.\nProof. by rewrite coprimezE abszN. Qed.\n\nLemma coprimezN m n : coprimez m (- n) = coprimez m n.\nProof. by rewrite coprimezE abszN. Qed.\n\nCoInductive egcdz_spec m n : int * int -> Type :=\n  EgcdzSpec u v of u * m + v * n = gcdz m n & coprimez u v\n     : egcdz_spec m n (u, v).\n\nLemma egcdzP m n : egcdz_spec m n (egcdz m n).\nProof.\nrewrite /egcdz; have [-> | m_nz] := altP eqP.\n  by split; [rewrite -abszEsign gcd0z | rewrite coprimezE absz_sign].\nhave m_gt0 : (`|m| > 0)%N by rewrite absz_gt0.\ncase: egcdnP (coprime_egcdn `|n| m_gt0) => //= u v Duv _ co_uv; split.\n  rewrite !mulNr -!mulrA mulrCA -abszEsg mulrCA -abszEsign.\n  by rewrite -!PoszM Duv addnC PoszD addrK.\nby rewrite coprimezE abszM absz_sg m_nz mul1n mulNr abszN abszMsign.\nQed.\n\nLemma Bezoutz m n : {u : int & {v : int | u * m + v * n = gcdz m n}}.\nProof. by exists (egcdz m n).1, (egcdz m n).2; case: egcdzP. Qed.\n\nLemma coprimezP m n :\n  reflect (exists uv, uv.1 * m + uv.2 * n = 1) (coprimez m n).\nProof.\napply: (iffP eqP) => [<-| [[u v] /= Duv]].\n  by exists (egcdz m n); case: egcdzP.\ncongr _%:Z; apply: gcdn_def; rewrite ?dvd1n // => d dv_d_n dv_d_m.\nby rewrite -(dvdzE d 1) -Duv [m]intEsg [n]intEsg rpredD ?dvdz_mull.\nQed.\n\nLemma Gauss_dvdz m n p :\n  coprimez m n -> (m * n %| p)%Z = (m %| p)%Z && (n %| p)%Z.\nProof. by move/Gauss_dvd <-; rewrite -abszM. Qed.\n\nLemma Gauss_dvdzr m n p : coprimez m n -> (m %| n * p)%Z = (m %| p)%Z.\nProof. by rewrite dvdzE abszM => /Gauss_dvdr->. Qed.\n\nLemma Gauss_dvdzl m n p : coprimez m p -> (m %| n * p)%Z = (m %| n)%Z.\nProof. by rewrite mulrC; apply: Gauss_dvdzr. Qed.\n\nLemma Gauss_gcdzr p m n : coprimez p m -> gcdz p (m * n) = gcdz p n.\nProof. by rewrite /gcdz abszM => /Gauss_gcdr->. Qed.\n\nLemma Gauss_gcdzl p m n : coprimez p n -> gcdz p (m * n) = gcdz p m.\nProof. by move=> co_pn; rewrite mulrC Gauss_gcdzr. Qed.\n\nLemma coprimez_mulr p m n : coprimez p (m * n) = coprimez p m && coprimez p n.\nProof. by rewrite -coprime_mulr -abszM. Qed.\n\nLemma coprimez_mull p m n : coprimez (m * n) p = coprimez m p && coprimez n p.\nProof. by rewrite -coprime_mull -abszM. Qed.\n\nLemma coprimez_pexpl k m n : (0 < k)%N -> coprimez (m ^+ k) n = coprimez m n.\nProof. by rewrite /coprimez /gcdz abszX; apply: coprime_pexpl. Qed.\n\nLemma coprimez_pexpr k m n : (0 < k)%N -> coprimez m (n ^+ k) = coprimez m n.\nProof. by move=> k_gt0; rewrite !(coprimez_sym m) coprimez_pexpl. Qed.\n\nLemma coprimez_expl k m n : coprimez m n -> coprimez (m ^+ k) n.\nProof. by rewrite /coprimez /gcdz abszX; apply: coprime_expl. Qed.\n\nLemma coprimez_expr k m n : coprimez m n -> coprimez m (n ^+ k).\nProof. by rewrite !(coprimez_sym m); apply: coprimez_expl. Qed.\n\nLemma coprimez_dvdl m n p : (m %| n)%N -> coprimez n p -> coprimez m p.\nProof. exact: coprime_dvdl. Qed.\n\nLemma coprimez_dvdr m n p : (m %| n)%N -> coprimez p n -> coprimez p m.\nProof. exact: coprime_dvdr. Qed.\n\nLemma dvdz_pexp2r m n k : (k > 0)%N -> (m ^+ k %| n ^+ k)%Z = (m %| n)%Z.\nProof. by rewrite dvdzE !abszX; apply: dvdn_pexp2r. Qed.\n\nSection Chinese.\n\n(***********************************************************************)\n(*   The chinese remainder theorem                                     *)\n(***********************************************************************)\n\nVariables m1 m2 : int.\nHypothesis co_m12 : coprimez m1 m2.\n\nLemma zchinese_remainder x y :\n  (x == y %[mod m1 * m2])%Z = (x == y %[mod m1])%Z && (x == y %[mod m2])%Z.\nProof. by rewrite !eqz_mod_dvd Gauss_dvdz. Qed.\n\n(***********************************************************************)\n(*   A function that solves the chinese remainder problem              *)\n(***********************************************************************)\n\nDefinition zchinese r1 r2 :=\n  r1 * m2 * (egcdz m1 m2).2 + r2 * m1 * (egcdz m1 m2).1.\n\nLemma zchinese_modl r1 r2 : (zchinese r1 r2 = r1 %[mod m1])%Z.\nProof.\nrewrite /zchinese; have [u v /= Duv _] := egcdzP m1 m2.\nrewrite -{2}[r1]mulr1 -((gcdz _ _ =P 1) co_m12) -Duv.\nby rewrite mulrDr mulrAC addrC (mulrAC r2) !mulrA !modzMDl.\nQed.\n\nLemma zchinese_modr r1 r2 : (zchinese r1 r2 = r2 %[mod m2])%Z.\nProof.\nrewrite /zchinese; have [u v /= Duv _] := egcdzP m1 m2.\nrewrite -{2}[r2]mulr1 -((gcdz _ _ =P 1) co_m12) -Duv.\nby rewrite mulrAC modzMDl mulrAC addrC mulrDr !mulrA modzMDl.\nQed.\n\nLemma zchinese_mod x : (x = zchinese (x %% m1)%Z (x %% m2)%Z %[mod m1 * m2])%Z.\nProof.\napply/eqP; rewrite zchinese_remainder //.\nby rewrite zchinese_modl zchinese_modr !modz_mod !eqxx.\nQed.\n\nEnd Chinese.\n\nSection ZpolyScale.\n\nDefinition zcontents p :=\n  sgz (lead_coef p) * \\big[gcdn/0%N]_(i < size p) `|(p`_i)%R|%N.\n\nLemma sgz_contents p : sgz (zcontents p) = sgz (lead_coef p).\nProof.\nrewrite /zcontents mulrC sgzM sgz_id; set d := _%:Z.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite lead_coef0 mulr0.\nrewrite gtr0_sgz ?mul1r // ltz_nat polySpred ?big_ord_recr //= -lead_coefE.\nby rewrite gcdn_gt0 orbC absz_gt0 lead_coef_eq0 nz_p.\nQed.\n\nLemma zcontents_eq0 p : (zcontents p == 0) = (p == 0).\nProof. by rewrite -sgz_eq0 sgz_contents sgz_eq0 lead_coef_eq0. Qed.\n\nLemma zcontents0 : zcontents 0 = 0.\nProof. by apply/eqP; rewrite zcontents_eq0. Qed.\n\nLemma zcontentsZ a p : zcontents (a *: p) = a * zcontents p.\nProof.\nhave [-> | nz_a] := eqVneq a 0; first by rewrite scale0r mul0r zcontents0.\nrewrite {2}[a]intEsg mulrCA -mulrA -PoszM big_distrr /= mulrCA mulrA -sgzM.\nrewrite -lead_coefZ; congr (_ * _%:Z); rewrite size_scale //.\nby apply: eq_bigr => i _; rewrite coefZ abszM.\nQed.\n\nLemma zcontents_monic p : p \\is monic -> zcontents p = 1.\nProof.\nmove=> mon_p; rewrite /zcontents polySpred ?monic_neq0 //.\nby rewrite big_ord_recr /= -lead_coefE (monicP mon_p) gcdn1.\nQed.\n\nLemma dvdz_contents a p : (a %| zcontents p)%Z = (p \\is a polyOver (dvdz a)).\nProof.\nrewrite dvdzE abszM absz_sg lead_coef_eq0.\nhave [-> | nz_p] := altP eqP; first by rewrite mul0n dvdn0 rpred0.\nrewrite mul1n; apply/dvdn_biggcdP/(all_nthP 0)=> a_dv_p i ltip /=.\n  exact: (a_dv_p (Ordinal ltip)).\nexact: a_dv_p.\nQed.\n\nLemma map_poly_divzK a p :\n  p \\is a polyOver (dvdz a) -> a *: map_poly (divz^~ a) p = p.\nProof.\nmove/polyOverP=> a_dv_p; apply/polyP=> i.\nby rewrite coefZ coef_map_id0 ?div0z // mulrC divzK.\nQed.\n\nLemma polyOver_dvdzP a p :\n  reflect (exists q, p = a *: q) (p \\is a polyOver (dvdz a)).\nProof.\napply: (iffP idP) => [/map_poly_divzK | [q ->]].\n  by exists (map_poly (divz^~ a) p).\nby apply/polyOverP=> i; rewrite coefZ dvdz_mulr.\nQed.\n\nDefinition zprimitive p := map_poly (divz^~ (zcontents p)) p.\n\nLemma zpolyEprim p : p = zcontents p *: zprimitive p.\nProof. by rewrite map_poly_divzK // -dvdz_contents. Qed.\n\nLemma zprimitive0 : zprimitive 0 = 0.\nProof.\nby apply/polyP=> i; rewrite coef0 coef_map_id0 ?div0z // zcontents0 divz0.\nQed.\n\nLemma zprimitive_eq0 p : (zprimitive p == 0) = (p == 0).\nProof.\napply/idP/idP=> /eqP p0; first by rewrite [p]zpolyEprim p0 scaler0.\nby rewrite p0 zprimitive0.\nQed.\n\nLemma size_zprimitive p : size (zprimitive p) = size p.\nProof.\nhave [-> | ] := eqVneq p 0; first by rewrite zprimitive0.\nby rewrite {1 3}[p]zpolyEprim scale_poly_eq0 => /norP[/size_scale-> _].\nQed.\n\nLemma sgz_lead_primitive p : sgz (lead_coef (zprimitive p)) = (p != 0).\nProof.\nhave [-> | nz_p] := altP eqP; first by rewrite zprimitive0 lead_coef0.\napply: (@mulfI _ (sgz (zcontents p))); first by rewrite sgz_eq0 zcontents_eq0.\nby rewrite -sgzM mulr1 -lead_coefZ -zpolyEprim sgz_contents.\nQed.\n\nLemma zcontents_primitive p : zcontents (zprimitive p) = (p != 0).\nProof.\nhave [-> | nz_p] := altP eqP; first by rewrite zprimitive0 zcontents0.\napply: (@mulfI _ (zcontents p)); first by rewrite zcontents_eq0.\nby rewrite mulr1 -zcontentsZ -zpolyEprim.\nQed.\n\nLemma zprimitive_id p : zprimitive (zprimitive p) = zprimitive p.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite !zprimitive0.\nby rewrite {2}[zprimitive p]zpolyEprim zcontents_primitive nz_p scale1r.\nQed.\n\nLemma zprimitive_monic p : p \\in monic -> zprimitive p = p.\nProof. by move=> mon_p; rewrite {2}[p]zpolyEprim zcontents_monic ?scale1r. Qed.\n\nLemma zprimitiveZ a p : a != 0 -> zprimitive (a *: p) = zprimitive p.\nProof.\nhave [-> | nz_p nz_a] := eqVneq p 0; first by rewrite scaler0.\napply: (@mulfI _ (a * zcontents p)%:P).\n  by rewrite polyC_eq0 mulf_neq0 ?zcontents_eq0.\nby rewrite -{1}zcontentsZ !mul_polyC -zpolyEprim -scalerA -zpolyEprim.\nQed.\n\nLemma zprimitive_min p a q :\n    p != 0 -> p = a *: q ->\n  {b | sgz b = sgz (lead_coef q) & q = b *: zprimitive p}.\nProof.\nmove=> nz_p Dp; have /dvdzP/sig_eqW[b Db]: (a %| zcontents p)%Z.\n  by rewrite dvdz_contents; apply/polyOver_dvdzP; exists q.\nsuffices ->: q = b *: zprimitive p.\n  by rewrite lead_coefZ sgzM sgz_lead_primitive nz_p mulr1; exists b.\napply: (@mulfI _ a%:P).\n  by apply: contraNneq nz_p; rewrite Dp -mul_polyC => ->; rewrite mul0r.\nby rewrite !mul_polyC -Dp scalerA mulrC -Db -zpolyEprim.\nQed.\n\nLemma zprimitive_irr p a q :\n  p != 0 -> zprimitive p = a *: q -> a = sgz (lead_coef q).\nProof.\nmove=> nz_p Dp; have: p = (a * zcontents p) *: q.\n  by rewrite mulrC -scalerA -Dp -zpolyEprim.\ncase/zprimitive_min=> // b <- /eqP.\nrewrite Dp -{1}[q]scale1r scalerA -subr_eq0 -scalerBl scale_poly_eq0 subr_eq0.\nhave{Dp} /negPf->: q != 0.\n  by apply: contraNneq nz_p; rewrite -zprimitive_eq0 Dp => ->; rewrite scaler0.\nby case: b a => [[|[|b]] | [|b]] [[|[|a]] | [|a]] //; rewrite mulr0.\nQed.\n\nLemma zcontentsM p q : zcontents (p * q) = zcontents p * zcontents q.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite !(mul0r, zcontents0).\nhave [-> | nz_q] := eqVneq q 0; first by rewrite !(mulr0, zcontents0).\nrewrite -[zcontents q]mulr1 {1}[p]zpolyEprim {1}[q]zpolyEprim.\nrewrite -scalerAl -scalerAr !zcontentsZ; congr (_ * (_ * _)).\nrewrite [zcontents _]intEsg sgz_contents lead_coefM sgzM !sgz_lead_primitive.\napply/eqP; rewrite nz_p nz_q !mul1r [_ == _]eqn_leq absz_gt0 zcontents_eq0.\nrewrite mulf_neq0 ?zprimitive_eq0 // andbT leqNgt.\napply/negP=> /pdivP[r r_pr r_dv_d]; pose to_r : int -> 'F_r := intr.\nhave nz_prim_r q1: q1 != 0 -> map_poly to_r (zprimitive q1) != 0.\n  move=> nz_q1; apply: contraTneq (prime_gt1 r_pr) => r_dv_q1.\n  rewrite -leqNgt dvdn_leq // -(dvdzE r true) -nz_q1 -zcontents_primitive.\n  rewrite dvdz_contents; apply/polyOverP=> i /=; rewrite dvdzE /=.\n  have /polyP/(_ i)/eqP := r_dv_q1; rewrite coef_map coef0 /=.\n  rewrite {1}[_`_i]intEsign rmorphM rmorph_sign /= mulf_eq0 signr_eq0 /=.\n  by rewrite -val_eqE /= val_Fp_nat.\nsuffices{nz_prim_r} /idPn[]: map_poly to_r (zprimitive p * zprimitive q) == 0.\n  by rewrite rmorphM mulf_neq0 ?nz_prim_r.\nrewrite [_ * _]zpolyEprim [zcontents _]intEsign mulrC -scalerA map_polyZ /=.\nby rewrite scale_poly_eq0 -val_eqE /= val_Fp_nat ?(eqnP r_dv_d).\nQed.\n\n\nLemma zprimitiveM p q : zprimitive (p * q) = zprimitive p * zprimitive q.\nProof.\nhave [pq_0|] := eqVneq (p * q) 0.\n  rewrite pq_0; move/eqP: pq_0; rewrite mulf_eq0.\n  by case/pred2P=> ->; rewrite !zprimitive0 (mul0r, mulr0).\nrewrite -zcontents_eq0 -polyC_eq0 => /mulfI; apply; rewrite !mul_polyC.\nby rewrite -zpolyEprim zcontentsM -scalerA scalerAr scalerAl -!zpolyEprim.\nQed.\n\nLemma dvdpP_int p q : p %| q -> {r | q = zprimitive p * r}.\nProof.\ncase/Pdiv.Idomain.dvdpP/sig2_eqW=> [[c r] /= nz_c Dpr].\nexists (zcontents q *: zprimitive r); rewrite -scalerAr.\nby rewrite -zprimitiveM mulrC -Dpr zprimitiveZ // -zpolyEprim.\nQed.\n\nLocal Notation pZtoQ := (map_poly (intr : int -> rat)).\n\nLemma size_rat_int_poly p : size (pZtoQ p) = size p.\nProof. by apply: size_map_inj_poly; first exact: intr_inj. Qed.\n\nLemma rat_poly_scale (p : {poly rat}) :\n  {q : {poly int} & {a | a != 0 & p = a%:~R^-1 *: pZtoQ q}}.\nProof.\npose a := \\prod_(i < size p) denq p`_i.\nhave nz_a: a != 0 by apply/prodf_neq0=> i _; exact: denq_neq0.\nexists (map_poly numq (a%:~R *: p)), a => //.\napply: canRL (scalerK _) _; rewrite ?intr_eq0 //.\napply/polyP=> i; rewrite !(coefZ, coef_map_id0) // numqK // Qint_def mulrC.\nhave [ltip | /(nth_default 0)->] := ltnP i (size p); last by rewrite mul0r.\nby rewrite [a](bigD1 (Ordinal ltip)) // rmorphM mulrA -numqE -rmorphM denq_int.\nQed.\n\nLemma dvdp_rat_int p q : (pZtoQ p %| pZtoQ q) = (p %| q).\nProof.\napply/dvdpP/Pdiv.Idomain.dvdpP=> [[/= r1 Dq] | [[/= a r] nz_a Dq]]; last first.\n  exists (a%:~R^-1 *: pZtoQ r); rewrite -scalerAl -rmorphM -Dq.\n  by rewrite -{2}[a]intz scaler_int rmorphMz -scaler_int scalerK ?intr_eq0.\nhave [r [a nz_a Dr1]] := rat_poly_scale r1; exists (a, r) => //=.\napply: (map_inj_poly _ _ : injective pZtoQ) => //; first exact: intr_inj.\nrewrite -[a]intz scaler_int rmorphMz -scaler_int /= Dq Dr1.\nby rewrite -scalerAl -rmorphM scalerKV ?intr_eq0.\nQed.\n\nLemma dvdpP_rat_int p q :\n    p %| pZtoQ q ->\n  {p1 : {poly int} & {a | a != 0 & p = a *: pZtoQ p1} & {r | q = p1 * r}}.\nProof.\nhave{p} [p [a nz_a ->]] := rat_poly_scale p.\nrewrite dvdp_scalel ?invr_eq0 ?intr_eq0 // dvdp_rat_int => dv_p_q.\nexists (zprimitive p); last exact: dvdpP_int.\nhave [-> | nz_p] := eqVneq p 0.\n  by exists 1; rewrite ?oner_eq0 // zprimitive0 map_poly0 !scaler0.\nexists ((zcontents p)%:~R / a%:~R).\n  by rewrite mulf_neq0 ?invr_eq0 ?intr_eq0 ?zcontents_eq0.\nby rewrite mulrC -scalerA -map_polyZ -zpolyEprim.\nQed.\n\nEnd ZpolyScale.\n\n(* Integral spans. *)\n\nLemma int_Smith_normal_form m n (M : 'M[int]_(m, n)) :\n  {L : 'M[int]_m & L \\in unitmx &\n  {R : 'M[int]_n & R \\in unitmx &\n  {d : seq int | sorted dvdz d &\n   M = L *m (\\matrix_(i, j) (d`_i *+ (i == j :> nat))) *m R}}}.\nProof.\nmove: {2}_.+1 (ltnSn (m + n)) => mn.\nelim: mn => // mn IHmn in m n M *; rewrite ltnS => le_mn.\nhave [[i j] nzMij | no_ij] := pickP (fun k => M k.1 k.2 != 0%N); last first.\n  do 2![exists 1%:M; first exact: unitmx1]; exists nil => //=.\n  apply/matrixP=> i j; apply/eqP; rewrite mulmx1 mul1mx mxE nth_nil mul0rn.\n  exact: negbFE (no_ij (i, j)).\ndo [case: m i => [[]//|m] i; case: n j => [[]//|n] j /=] in M nzMij le_mn *.\nwlog Dj: j M nzMij / j = 0; last rewrite {j}Dj in nzMij.\n  case/(_ 0 (xcol j 0 M)); rewrite ?mxE ?tpermR // => L uL [R uR [d dvD dM]].\n  exists L => //; exists (xcol j 0 R); last exists d => //=.\n     by rewrite xcolE unitmx_mul uR unitmx_perm.\n  by rewrite xcolE !mulmxA -dM xcolE -mulmxA -perm_mxM tperm2 perm_mx1 mulmx1.\nmove Da: (M i 0) nzMij => a nz_a.\nelim: {a}_.+1 {-2}a (ltnSn `|a|) => // A IHa a leA in m n M i Da nz_a le_mn *.\nwlog [j a'Mij]: m n M i Da le_mn / {j | ~~ (a %| M i j)%Z}; last first.\n  have nz_j: j != 0 by apply: contraNneq a'Mij => ->; rewrite Da.\n  case: n => [[[]//]|n] in j le_mn nz_j M a'Mij Da *.\n  wlog{nz_j} Dj: j M a'Mij Da / j = 1; last rewrite {j}Dj in a'Mij.\n    case/(_ 1 (xcol j 1 M)); rewrite ?mxE ?tpermR ?tpermD //.\n    move=> L uL [R uR [d dvD dM]]; exists L => //.\n    exists (xcol j 1 R); first by rewrite xcolE unitmx_mul uR unitmx_perm.\n    exists d; rewrite //= xcolE !mulmxA -dM xcolE -mulmxA -perm_mxM tperm2.\n    by rewrite perm_mx1 mulmx1.\n  have [u [v]] := Bezoutz a (M i 1); set b := gcdz _ _ => Db.\n  have{leA} ltA: (`|b| < A)%N.\n    rewrite -ltnS (leq_trans _ leA) // ltnS ltn_neqAle andbC.\n    rewrite dvdn_leq ?absz_gt0 ? dvdn_gcdl //=.\n    by rewrite (contraNneq _ a'Mij) ?dvdzE // => <-; exact: dvdn_gcdr.\n  pose t2 := [fun j : 'I_2 => [tuple _; _]`_j : int]; pose a1 := M i 1.\n  pose Uul := \\matrix_(k, j) t2 (t2 u (- (a1 %/ b)%Z) j) (t2 v (a %/ b)%Z j) k.\n  pose U : 'M_(2 + n) := block_mx Uul 0 0 1%:M; pose M1 := M *m U.\n  have{nz_a} nz_b: b != 0 by rewrite gcdz_eq0 (negPf nz_a).\n  have uU: U \\in unitmx.\n    rewrite unitmxE det_ublock det1 (expand_det_col _ 0) big_ord_recl big_ord1.\n    do 2!rewrite /cofactor [row' _ _]mx11_scalar !mxE det_scalar1 /=.\n    rewrite mulr1 mul1r mulN1r opprK -[_ + _](mulzK _ nz_b) mulrDl. \n    by rewrite -!mulrA !divzK ?dvdz_gcdl ?dvdz_gcdr // Db divzz nz_b unitr1.\n  have{Db} Db: M1 i 0 = b.\n    rewrite /M1 -(lshift0 n 1) [U]block_mxEh mul_mx_row row_mxEl.\n    rewrite -[M](@hsubmxK _ _ 2) (@mul_row_col _ _ 2) mulmx0 addr0 !mxE /=.\n    rewrite big_ord_recl big_ord1 !mxE /= [lshift _ _]((_ =P 0) _) // Da.\n    by rewrite [lshift _ _]((_ =P 1) _) // mulrC -(mulrC v).\n  have [L uL [R uR [d dvD dM1]]] := IHa b ltA _ _ M1 i Db nz_b le_mn.\n  exists L => //; exists (R *m invmx U); last exists d => //.\n    by rewrite unitmx_mul uR unitmx_inv.\n  by rewrite mulmxA -dM1 mulmxK.\nmove=> {A leA IHa} IHa; wlog Di: i M Da / i = 0; last rewrite {i}Di in Da.\n  case/(_ 0 (xrow i 0 M)); rewrite ?mxE ?tpermR // => L uL [R uR [d dvD dM]].\n  exists (xrow i 0 L); first by rewrite xrowE unitmx_mul unitmx_perm.\n  exists R => //; exists d; rewrite //= xrowE -!mulmxA (mulmxA L) -dM xrowE.\n  by rewrite mulmxA -perm_mxM tperm2 perm_mx1 mul1mx.\nwithout loss /forallP a_dvM0: / [forall j, a %| M 0 j]%Z.\n  have [_|] := altP forallP; first exact; rewrite negb_forall => /existsP/sigW.\n  by move/IHa=> IH _; apply: IH. \nwithout loss{Da a_dvM0} Da: M / forall j, M 0 j = a.\n  pose Uur := col' 0 (\\row_j (1 - (M 0 j %/ a)%Z)). \n  pose U : 'M_(1 + n) := block_mx 1 Uur 0 1%:M; pose M1 := M *m U.\n  have uU: U \\in unitmx by rewrite unitmxE det_ublock !det1 mulr1.\n  case/(_ (M *m U)) => [j | L uL [R uR [d dvD dM]]].\n    rewrite -(lshift0 m 0) -[M](@submxK _ 1 _ 1) (@mulmx_block _ 1 m 1).\n    rewrite (@col_mxEu _ 1) !mulmx1 mulmx0 addr0 [ulsubmx _]mx11_scalar.\n    rewrite mul_scalar_mx !mxE !lshift0 Da.\n    case: splitP => [j0 _ | j1 Dj]; rewrite ?ord1 !mxE // lshift0 rshift1.\n    by rewrite mulrBr mulr1 mulrC divzK ?subrK.\n  exists L => //; exists (R * U^-1); first by rewrite unitmx_mul uR unitmx_inv.\n  by exists d; rewrite //= mulmxA -dM mulmxK.\nwithout loss{IHa} /forallP/(_ (_, _))/= a_dvM: / [forall k, a %| M k.1 k.2]%Z.\n  have [_|] := altP forallP; first exact; rewrite negb_forall => /existsP/sigW.\n  case=> [[i j] /= a'Mij] _.\n  have [|||L uL [R uR [d dvD dM]]] := IHa _ _ M^T j; rewrite ?mxE 1?addnC //.\n    by exists i; rewrite mxE.\n  exists R^T; last exists L^T; rewrite ?unitmx_tr //; exists d => //.\n  rewrite -[M]trmxK dM !trmx_mul mulmxA; congr (_ *m _ *m _).\n  by apply/matrixP=> i1 j1; rewrite !mxE eq_sym; case: eqP => // ->.\nwithout loss{nz_a a_dvM} a1: M a Da / a = 1.\n  pose M1 := map_mx (divz^~ a) M; case/(_ M1 1)=> // [k|L uL [R uR [d dvD dM]]].\n    by rewrite !mxE Da divzz nz_a.\n  exists L => //; exists R => //; exists [seq a * x | x <- d].\n    case: d dvD {dM} => //= x d; elim: d x => //= y d IHd x /andP[dv_xy /IHd].\n    by rewrite [dvdz _ _]dvdz_mul2l ?[_ \\in _]dv_xy.\n  have ->: M = a *: M1 by apply/matrixP=> i j; rewrite !mxE mulrC divzK ?a_dvM.\n  rewrite dM scalemxAl scalemxAr; congr (_ *m _ *m _).\n  apply/matrixP=> i j; rewrite !mxE mulrnAr; congr (_ *+ _).\n  have [lt_i_d | le_d_i] := ltnP i (size d); first by rewrite (nth_map 0).\n  by rewrite !nth_default ?size_map ?mulr0.\nrewrite {a}a1 -[m.+1]/(1 + m)%N -[n.+1]/(1 + n)%N in M Da *.\npose Mu := ursubmx M; pose Ml := dlsubmx M.\nhave{Da} Da: ulsubmx M = 1 by rewrite [_ M]mx11_scalar !mxE !lshift0 Da.\npose M1 := - (Ml *m Mu) + drsubmx M.\nhave [|L uL [R uR [d dvD dM1]]] := IHmn m n M1; first by rewrite -addnS ltnW.\nexists (block_mx 1 0 Ml L).\n  by rewrite unitmxE det_lblock det_scalar1 mul1r.\nexists (block_mx 1 Mu 0 R).\n  by rewrite unitmxE det_ublock det_scalar1 mul1r.\nexists (1 :: d); set D1 := \\matrix_(i, j) _ in dM1.\n  by rewrite /= path_min_sorted // => g _; exact: dvd1n.\nrewrite [D in _ *m D *m _](_ : _ = block_mx 1 0 0 D1); last first.\n  by apply/matrixP=> i j; do 3?[rewrite ?mxE ?ord1 //=; case: splitP => ? ->].\nrewrite !mulmx_block !(mul0mx, mulmx0, addr0) !mulmx1 add0r mul1mx -Da -dM1.\nby rewrite addNKr submxK.\nQed.\n\nDefinition inIntSpan (V : zmodType) m (s : m.-tuple V) v :=\n  exists a : int ^ m, v = \\sum_(i < m) s`_i *~ a i.\n\nLemma dec_Qint_span (vT : vectType rat) m (s : m.-tuple vT) v :\n  decidable (inIntSpan s v).\nProof.\nhave s_s (i : 'I_m): s`_i \\in <<s>>%VS by rewrite memv_span ?memt_nth.\nhave s_Zs a: \\sum_(i < m) s`_i *~ a i \\in <<s>>%VS.\n  by rewrite memv_suml // => i _; rewrite -scaler_int memvZ.\ncase s_v: (v \\in <<s>>%VS); last by right=> [[a Dv]]; rewrite Dv s_Zs in s_v.\npose S := \\matrix_(i < m, j < _) coord (vbasis <<s>>) j s`_i.\npose r := \\rank S; pose k := (m - r)%N; pose Em := erefl m; pose Ek := erefl k.\nhave Dm: (m = k + r)%N by rewrite subnK ?rank_leq_row.\nhave [K kerK]: {K : 'M_(k, m) | map_mx intr K == kermx S}%MS.\n  pose B := row_base (kermx S); pose d := \\prod_ij denq (B ij.1 ij.2).\n  exists (castmx (mxrank_ker S, Em) (map_mx numq (intr d *: B))).\n  rewrite /k; case: _ / (mxrank_ker S); set B1 := map_mx _ _.\n  have ->: B1 = (intr d *: B).\n    apply/matrixP=> i j; rewrite 3!mxE mulrC [d](bigD1 (i, j)) // rmorphM mulrA.\n    by rewrite -numqE -rmorphM numq_int.\n  suffices nz_d: d%:Q != 0 by rewrite !eqmx_scale // !eq_row_base andbb.\n  by rewrite intr_eq0; apply/prodf_neq0 => i _; exact: denq_neq0.\nhave [L _ [G uG [D _ defK]]] := int_Smith_normal_form K.\npose Gud := castmx (Dm, Em) G; pose G'lr := castmx (Em, Dm) (invmx G).\nhave{K L D defK kerK} kerGu: map_mx intr (usubmx Gud) *m S = 0.\n  pose Kl : 'M[rat]_k:= map_mx intr (lsubmx (castmx (Ek, Dm) (K *m invmx G))).\n  have{defK} defK: map_mx intr K = row_mx Kl 0 *m map_mx intr Gud.\n    rewrite -[K](mulmxKV uG) -{2}[G](castmxK Dm Em) -/Gud.\n    rewrite -[K *m _](castmxK Ek Dm) map_mxM map_castmx.\n    rewrite -(hsubmxK (castmx _ _)) map_row_mx -/Kl map_castmx /Em.\n    set Kr := map_mx _ _; case: _ / (esym Dm) (map_mx _ _) => /= GudQ.\n    congr (row_mx _ _ *m _); apply/matrixP=> i j; rewrite !mxE defK mulmxK //=.\n    rewrite castmxE mxE big1 //= => j1 _; rewrite mxE /= eqn_leq andbC.\n    by rewrite leqNgt (leq_trans (valP j1)) ?mulr0 ?leq_addr.\n  have /row_full_inj: row_full Kl; last apply.\n    rewrite /row_full eqn_leq rank_leq_row /= -{1}[k](mxrank_ker S).\n    rewrite -(eqmxP kerK) defK map_castmx mxrankMfree; last first.\n      case: _ / (Dm); apply/row_freeP; exists (map_mx intr (invmx G)).\n      by rewrite -map_mxM mulmxV ?map_mx1.\n    by rewrite -mxrank_tr tr_row_mx trmx0 -addsmxE addsmx0 mxrank_tr.\n  rewrite mulmx0 mulmxA (sub_kermxP _) // -(eqmxP kerK) defK.\n  by rewrite -{2}[Gud]vsubmxK map_col_mx mul_row_col mul0mx addr0.\npose T := map_mx intr (dsubmx Gud) *m S.\nhave{kerGu} defS: map_mx intr (rsubmx G'lr) *m T = S.\n  have: G'lr *m Gud = 1%:M by rewrite /G'lr /Gud; case: _ / (Dm); exact: mulVmx.\n  rewrite -{1}[G'lr]hsubmxK -[Gud]vsubmxK mulmxA mul_row_col -map_mxM.\n  move/(canRL (addKr _))->; rewrite -mulNmx raddfD /= map_mx1 map_mxM /=.\n  by rewrite mulmxDl -mulmxA kerGu mulmx0 add0r mul1mx.\npose vv := \\row_j coord (vbasis <<s>>) j v.\nhave uS: row_full S.\n  apply/row_fullP; exists (\\matrix_(i, j) coord s j (vbasis <<s>>)`_i).\n  apply/matrixP=> j1 j2; rewrite !mxE.\n  rewrite -(coord_free _ _ (basis_free (vbasisP _))).\n  rewrite -!tnth_nth (coord_span (vbasis_mem (mem_tnth j1 _))) linear_sum.\n  by apply: eq_bigr => i _; rewrite !mxE (tnth_nth 0) !linearZ.\nhave eqST: (S :=: T)%MS by apply/eqmxP; rewrite -{1}defS !submxMl.\ncase Zv: (map_mx denq (vv *m pinvmx T) == const_mx 1).\n  pose a := map_mx numq (vv *m pinvmx T) *m dsubmx Gud.\n  left; exists [ffun j => a 0 j].\n  transitivity (\\sum_j (map_mx intr a *m S) 0 j *: (vbasis <<s>>)`_j).\n    rewrite {1}(coord_vbasis s_v); apply: eq_bigr => j _; congr (_ *: _).\n    have ->: map_mx intr a = vv *m pinvmx T *m map_mx intr (dsubmx Gud).\n      rewrite map_mxM /=; congr (_ *m _); apply/rowP=> i; rewrite 2!mxE numqE.\n      by have /eqP/rowP/(_ i) := Zv; rewrite !mxE => ->; rewrite mulr1.\n    by rewrite -(mulmxA _ _ S) mulmxKpV ?mxE // -eqST submx_full.\n  rewrite (coord_vbasis (s_Zs _)); apply: eq_bigr => j _; congr (_ *: _).\n  rewrite linear_sum mxE; apply: eq_bigr => i _.\n  by rewrite -scaler_int linearZ [a]lock !mxE ffunE.\nright=> [[a Dv]]; case/eqP: Zv; apply/rowP.\nhave ->: vv = map_mx intr (\\row_i a i) *m S.\n  apply/rowP=> j; rewrite !mxE Dv linear_sum.\n  by apply: eq_bigr => i _; rewrite -scaler_int linearZ !mxE.\nrewrite -defS -2!mulmxA; have ->: T *m pinvmx T = 1%:M.\n  have uT: row_free T by rewrite /row_free -eqST.\n  by apply: (row_free_inj uT); rewrite mul1mx mulmxKpV.\nby move=> i; rewrite mulmx1 -map_mxM 2!mxE denq_int mxE.\nQed.\n\n", "meta": {"author": "beta-ziliani", "repo": "ssreflect-1.4", "sha": "2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571", "save_path": "github-repos/coq/beta-ziliani-ssreflect-1.4", "path": "github-repos/coq/beta-ziliani-ssreflect-1.4/ssreflect-1.4-2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571/theories/intdiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6897517602340912}}
{"text": "Require Export Lattice.PartialOrder.\nRequire Import Coq.Sets.Ensembles.\n\nLocal Open Scope order_scope.\n\n(** An M-lattice (measure lattice) is partial order relation that has all joins (LUBs) and\na top element. We require the user to provide the bottom element also explicitly. In any\npartial order relation with arbitrary joins always has a unique bottom element – namely,\nthe join of the empty set. *)\nRecord MLattice : Type :=\n  {\n    ML_PO :> PartialOrder;\n    ML_meets : ∀ (X : Type) (f : X → ML_PO), ⊔ᵍ f;\n    ML_top : ML_PO;\n    ML_top_top : ∀ (x : ML_PO), x ⊑ ML_top;\n    ML_bot : ML_PO;\n    ML_bot_bottom : ∀ (x : ML_PO), ML_bot ⊑ x;\n(*    (** This is a usual property of real numbers used in the context of metric spaces in\ne.g., proof of uniqueness of limits. We require it to be proven for an M-lattice as we\ncan't prove it constructively in general. Note that its contrapositive is easily provable for\nany partial order relation with a bottom element! *)\n    ML_strict_bot : ∀ x, (∀ y, ML_bot ⊏ y → x ⊏ y) → x = ML_bot; *)\n    (** The subset of distances for which we have to provide constructive approximatons\nfor limits and such. *)\n    ML_appr_cond : ML_PO → Type;\n    (** The top element must be in the approximation subset. *)\n    ML_appr_top : ML_appr_cond ML_top;\n    (** The approximation subset must be all positive. *)\n    ML_appr_pos : ∀ x, ML_appr_cond x → ML_bot ⊏ x;\n    (** The approximation subset dominate all positive values. *)\n    ML_appr_dominate_pos : (∀ x, (∀ y, ML_appr_cond y → x ⊏ y) → x = ML_bot);\n    (** This is a dichotomy about the bottom element of a lattice. It states that the \nbottom element is either not reachable from a non-bottom element (there is always an\nelement strictly between them) or there is an element (not necessarily unique) in the\nlattice that sits immediately (and strictly) above the bottom element.\n\nWe require this as part of the definition of an M-lattice as we can't distinguish\nthese two cases and we need this distinction to keep proofs (e.g., uniqueness of limits)\nconstructive. *)\n    ML_bottom_dichotomy :\n      (∀ x, ML_appr_cond x → {y : ML_PO & ML_appr_cond y & ML_bot ⊏ y ∧ y ⊏ x})\n      +\n      {ab : ML_PO & ML_appr_cond ab & (∀ x, x ⊏ ab → x = ML_bot)};\n    (** All elements are approximatable. This is off course not always constructively\nprovable, e.g., in bisected spaces. Therefore, we try to avoid it as much as possible.*)\n    ML_all_approximatable :\n      ∀ x, ML_bot ⊏ x → {b : ML_PO & b ⊑ x & ML_appr_cond b}\n  }.\n\nArguments ML_PO _ : assert.\nArguments ML_meets {_ _} _, _ {_} _.\nArguments ML_top {_}.\nArguments ML_bot {_}.\n\nDefinition ApprType (M : MLattice) := {x : M & ML_appr_cond M x}.\n\nNotation \"⊤\" := ML_top : lattice_scope.\nNotation \"⊥\" := ML_bot : lattice_scope.\n\nDefinition Lat_LUB {Lat : MLattice} {X : Type} (f : X → Lat) : ⊔ᵍ f :=\n  (ML_meets Lat f).\n\nDefinition Lat_LUB_Pair {Lat : MLattice} (x y : Lat) : x ⊔ y :=\n  (ML_meets Lat (fun u : bool => if u then x else y)).\n\nNotation \"⊔ᵍ Q\" := (Lat_LUB Q) : lattice_scope.\n\nNotation \"x ⊔ y\" := (Lat_LUB_Pair x y) : lattice_scope.\n\nHint Resolve ML_bot_bottom.\n\nHint Resolve ML_top_top.\n\nLocal Open Scope lattice_scope.\n\nTheorem Top_Unique {Lat : MLattice} (t : Lat) : (∀ x, x ⊑ t) → t = ⊤.\nProof.\n  intros H.\n  apply PO_ASym; auto.\nQed.\n\nTheorem Bottom_Unique {Lat : MLattice} (b : Lat) : (∀ x, b ⊑ x) → b = ⊥.\nProof.\n  intros H.\n  apply PO_ASym; auto.\nQed.\n\nTheorem LE_Bottom_Bottom {Lat : MLattice} (b : Lat) : b ⊑ ⊥ → b = ⊥.\nProof.\n  intros H.\n  apply PO_ASym; auto.\nQed.\n\nTheorem lub_sym {L : MLattice} (a b : L) : (a ⊔ b) = (b ⊔ a) :> L.\nProof.\n  apply PO_ASym; apply lub_lst; intros [|];\n  apply (lub_ub (fun u : bool => if u then _ else _) _ false) +\n  apply (lub_ub (fun u : bool => if u then _ else _) _ true).\nQed.\n\nTheorem lub_bot {L : MLattice} (b : L) : (b ⊔ ⊥) = b :> L.\nProof.\n  apply PO_ASym.\n  apply lub_lst; intros [|]; trivial.\n  apply (lub_ub (fun u : bool => if u then _ else _) _ true).\nQed.\n", "meta": {"author": "amintimany", "repo": "CTDT", "sha": "91e390152e09c554126b13fd953c905d16bfed5f", "save_path": "github-repos/coq/amintimany-CTDT", "path": "github-repos/coq/amintimany-CTDT/CTDT-91e390152e09c554126b13fd953c905d16bfed5f/Lattice/MLattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6896504536822919}}
{"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 double (double_arg0 : natural) : natural\n           := match double_arg0 with\n              | Zero => Zero\n              | Succ n => Succ (Succ (double n))\n              end.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint len (len_arg0 : lst) : natural\n           := match len_arg0 with\n              | Nil => Zero\n              | Cons x y => Succ (len y)\n              end.\n\nLemma lem : forall l1 l2 n, Succ (len (append l1 l2)) = len (append l1 (Cons n l2)).\nProof.\n   induction l1.\n   - intros. simpl. f_equal. apply IHl1.\n   - intros. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : lst), eq (len (append x x)) (double (len x)).\nProof.\ninduction x.\n   - simpl. rewrite <- IHx. f_equal. rewrite (lem x x n). reflexivity.\n   - reflexivity.\nQed.\n              \n", "meta": {"author": "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/goal4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.6896504536822917}}
{"text": "Extraction Language Haskell.\n\nSection Ejercicio1.\n\n(* 1.1 *)\nLemma predspec : forall n: nat,\n  { m: nat | n = 0 /\\ m = 0 \\/ n = S m }.\nProof.\n  intro.\n  destruct n;\n  [ exists 0; left; split\n  | exists n; right\n  ]; reflexivity.\nQed.\n\nEnd Ejercicio1.\n\n(* 1.2 *)\nExtraction \"predecesor\" predspec.\n\nSection Ejercicio2.\n\nInductive bintree (X: Set) :=\n  Empty : bintree X\n  | Branch : X -> bintree X -> bintree X -> bintree X.\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\n(* 2.1 *)\nLemma MirrorC: forall (A: Set) (t: bintree A),\n  { t': bintree A | (mirror A t t') }.\nProof.\n  intros.\n  induction t.\n    exists (Empty A).\n    constructor.\n\n    destruct IHt1.\n    destruct IHt2.\n    exists (Branch A x x1 x0).\n    constructor; trivial.\nQed.\n\n(* 2.2 *)\nFunction inverse (X: Set) (b: bintree X) {struct b}: 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\nHint Constructors mirror.\n\nLemma MirrorC2: forall (A: Set) (t: bintree A),\n{ t' : bintree A | (mirror A t t') }.\nProof.\n  intros.\n  exists (inverse A t).\n  functional induction (inverse A t);\n    constructor; trivial.\nQed.\n\nEnd Ejercicio2.\n\n(* 2.3 *)\nExtraction \"mirror_function\" MirrorC2.\n\nSection Ejercicio3.\n\n(* 3.1 *)\nDefinition Value := bool.\n\nInductive BoolExpr: Set :=\n  | bbool: bool -> BoolExpr\n  | or: BoolExpr -> BoolExpr -> BoolExpr\n  | bnot: BoolExpr -> BoolExpr.\n\nInductive BEval: BoolExpr -> Value -> Prop :=\n  | ebool: forall b: bool, BEval (bbool b) (b: Value)\n  | eorl: forall e1 e2: BoolExpr,\n    BEval e1 true -> BEval (or e1 e2) true\n  | eorr: forall e1 e2: BoolExpr,\n    BEval e2 true -> BEval (or e1 e2) true\n  | eorrl: forall e1 e2: BoolExpr,\n    BEval e1 false -> BEval e2 false -> BEval (or e1 e2) false\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\nFunction beval (e : BoolExpr): Value :=\n  match e with\n    | bbool b => b\n    | or e1 e2 =>\n    match beval e1, beval e2 with\n      | false, false => false\n      | _, _ => true\n    end\n    | bnot e1 => if beval e1 then false else true\n  end.\n\nFunction sbeval (e : BoolExpr): Value :=\n  match e with\n    | bbool b => b\n    | or e1 e2 =>\n    match sbeval e1 with\n      | true => true\n      | _ => sbeval e2\n    end\n    | bnot e1 => if sbeval e1 then false else true\n  end.\n\nLemma bevalC: forall e: BoolExpr,\n  { b:Value | (BEval e b) }.\nProof.\n  intro.\n  exists (beval e).\n  induction e; simpl.\n    constructor.\n\n    case_eq (beval e1); intro.\n      constructor.\n      rewrite <- H.\n      assumption.\n\n      case_eq (beval e2); intro.\n      apply eorr.\n      rewrite <- H0.\n      assumption.\n\n      constructor.\n      rewrite <- H.\n      assumption.\n\n      rewrite <- H0.\n      assumption.\n\n  case_eq (beval e); intro.\n    constructor.\n    rewrite <- H.\n    assumption.\n\n    constructor.\n    rewrite <- H.\n    assumption.\nQed.\n\nLemma sbevalC: forall e: BoolExpr,\n  { b:Value | (BEval e b) }.\nProof.\n  intro.\n  exists (sbeval e).\n  induction e; simpl.\n    constructor.\n\n    case_eq (sbeval e1); intro.\n      constructor.\n      rewrite <- H.\n      assumption.\n\n      case_eq (sbeval e2); intro.\n        apply eorr.\n        rewrite <- H0.\n        assumption.\n\n      constructor.\n      rewrite <- H.\n      assumption.\n      \n      rewrite <- H0.\n      assumption.\n\n  case_eq (sbeval e); intro.\n    constructor.\n    rewrite <- H.\n    assumption.\n\n    constructor.\n    rewrite <- H.\n    assumption.\nQed.\n\n(* 3.2 *)\nHint Constructors BEval.\n\nLemma bevalC2: forall e: BoolExpr,\n  { b:Value | (BEval e b) }.\nProof.\n  intro.\n  exists (beval e).\n  induction e.\n    constructor.\n\n    simpl.\n    case_eq (beval e1); intro.\n      constructor.\n      rewrite <- H.\n      trivial.\n\n      case_eq (beval e2); intro.\n        apply eorr.\n        rewrite <- H0.\n        trivial.\n\n      constructor.\n        rewrite <- H.\n        assumption.\n\n        rewrite <- H0.\n        assumption.\n\n    simpl.\n    case_eq (beval e); intro.\n      constructor.\n      rewrite <- H.\n      assumption.\n\n      constructor.\n      rewrite <- H.\n      assumption.\nQed.\n\nLemma sbevalC2: forall e: BoolExpr,\n  { b:Value | (BEval e b) }.\nProof.\n  intro.\n  exists (sbeval e).\n  induction e.\n    constructor.\n\n    simpl.\n    case_eq (sbeval e1); intro.\n      constructor.\n      rewrite <- H.\n      trivial.\n\n      case_eq (sbeval e2); intro.\n        apply eorr.\n        rewrite <- H0.\n        trivial.\n\n      constructor.\n        rewrite <- H.\n        assumption.\n\n        rewrite <- H0.\n        assumption.\n\n    simpl.\n    case_eq (sbeval e); intro.\n      constructor.\n      rewrite <- H.\n      assumption.\n\n      constructor.\n      rewrite <- H.\n      assumption.\nQed.\n\nEnd Ejercicio3.\n\n(* 3.3 *)\nExtract Inductive bool => \"Prelude.Bool\" [ \"Prelude.True\" \"Prelude.False\" ].\nExtraction \"BEval\" bevalC sbevalC.\n\nSection Ejercicio4.\n\nVariable A: Set.\n\nInductive list: Set :=\n  | nil: list\n  | cons: A -> list -> list.\n\nFixpoint append (l1 l2 : list) {struct l1}: list :=\n  match l1 with\n    | nil => l2\n    | cons a l => cons a (append l l2)\n  end.\n\nInductive perm: list -> list -> Prop :=\n  | perm_refl: forall l, perm l l\n  | perm_cons: forall a l0 l1,\n    perm l0 l1-> perm (cons a l0)(cons a l1)\n  | perm_app: forall a l,\n    perm (cons a l) (append l (cons a nil))\n  | perm_trans: forall l1 l2 l3,\n    perm l1 l2 -> perm l2 l3 -> perm l1 l3.\n\nHint Constructors perm.\n\n(* 4.1 *)\nFunction reverse (l: list) {struct l}: list :=\n  match l with\n    | nil => nil\n    | cons x xs => append (reverse xs) (cons x nil)\n  end.\n\n(* 4.2 *)\nLemma Ej6_4: forall l: list, { l2: list | perm l l2 }.\nProof.\n  intro.\n  functional induction (reverse l);\n  [ exists nil\n  | destruct IHl0;\n    exists (append (cons x nil) x0);\n    constructor\n  ]; trivial.\nQed.\n\n(* exists reverse l *)\n(* perm_trans *)\n\nLemma Ej6_4': forall l: list, { l2: list | perm l l2 }.\nProof.\n  induction l.\n    exists nil.\n    constructor.\n\n    destruct IHl.\n    exists (cons a x).\n    constructor.\n    trivial.\nQed.\n\nEnd Ejercicio4.\n\nSection Ejercicio5.\n\nInductive Le: nat -> nat -> Prop :=\n  LeZero: forall m: nat, Le 0 m\n  | LeS: forall n m: nat, Le n m -> Le (S n) (S m).\n\nInductive Le': nat -> nat -> Prop :=\n  LeZero': forall n: nat, Le' n n\n  | LeS': forall n m: nat, Le' n m -> Le' n (S m).\n\nInductive Gt: nat -> nat -> Prop :=\n  GtZero: forall m: nat, Gt (S m) 0\n  | GtS: forall n m: nat, Gt n m -> Gt (S n) (S m).\n\nInductive Gt': nat -> nat -> Prop :=\n  GtZero': forall n: nat, Gt' n n\n  | GtS': forall n m: nat, Gt' n m -> Gt' (S n) m.\n\nFunction leBool (n m: nat) {struct n}: 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\n(**\nFunction leBool : nat -> nat -> bool :=\n  fun x y =>\n    match Le x y with\n      | True => true\n      | _ => false\n    end.\n**)\n\nLemma Le_Gt_dec: forall n m: nat,\n  { (Le n m) } + { (Gt n m) }.\nProof.\n  intros.\n  functional induction (leBool n m).\n    left.\n    apply LeZero.\n\n    right.\n    apply GtZero.\n\n    elim IHb; intro.\n      left.\n      apply LeS.\n      assumption.\n\n      right.\n      apply GtS.\n      assumption.\nQed.\n\nRequire Import Omega.\n\nLemma le_gt_dec: forall n m: nat,\n  { (le n m) } + { (gt n m) }.\nProof.\n  intros.\n  functional induction (leBool n m).\n    left.\n    omega.\n\n    right.\n    omega.\n\n    destruct IHb.\n      left.\n      omega.\n\n      right.\n      omega.\nQed.\n\nEnd Ejercicio5.\n\nSection Ejercicio6.\n\nRequire Import Omega.\nRequire Import DecBool.\nRequire Import Compare_dec.\nRequire Import Plus.\nRequire Import Mult.\nRequire Import NPeano.\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 ltb n m := leb (S n) m.\n\nLemma nat_div_mod :\n  forall a b: nat, not (b = 0)\n    -> { qr: nat*nat | spec_res_nat_div_mod a b qr }.\nProof.\n  intros.\n  induction a.\n    exists (0, 0).\n    split.\n      rewrite mult_0_r.\n      rewrite plus_0_r.\n      reflexivity.\n\n      elim (zerop b); [ contradiction | trivial ].\n\n    case_eq b; intros.\n      contradiction.\n\n      destruct IHa.\n      destruct x.\n      simpl in s.\n      destruct s.\n      rewrite H1.\n      case_eq (ltb n1 n); intro.\n        exists (n0, S n1).\n        simpl.\n        split.\n          rewrite H0.\n          simpl.\n          trivial.\n\n          unfold ltb in H3.\n          apply leb_complete in H3.\n          apply le_lt_n_Sm.\n          trivial.\n\n        exists (S n0, 0).\n        simpl.\n        split.\n          rewrite H0.\n          simpl.\n          unfold ltb in H3.\n          apply leb_iff_conv in H3.\n          rewrite H0 in H2.\n          apply lt_le_S in H2.\n          apply lt_le_S in H3.\n          apply le_S_n in H2.\n          apply le_S_n in H3.\n          assert (n = n1) by (apply (le_antisym n n1); trivial).\n          rewrite H4.\n          rewrite mult_succ_r.\n          rewrite plus_0_r.\n          rewrite plus_assoc.\n          trivial.\n\n          apply lt_0_Sn.\nQed.\n\nEnd Ejercicio6.\n\nExtraction \"nat_div_mod\" nat_div_mod.\n\nSection Ejercicio7.\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),\n    tree_sub A t (node A x t t')\n  | tree_sub2: forall (t': tree A) (x: A),\n    tree_sub A t (node A x t' t).\n\nTheorem well_founded_tree_sub: forall A: Set,\n  well_founded (tree_sub A).\nProof.\n  unfold well_founded.\n  intros.\n  induction a;\n  constructor;\n  intros;\n  inversion H;\n  trivial.\nQed.\n\nEnd Ejercicio7.\n\nSection Ejercicio8.\n\nRequire Import Inverse_Image.\nRequire Import Wf_nat.\n\n(**\nInductive BoolExpr : Set :=\n  | bbool : bool -> BoolExpr\n  | or : BoolExpr -> BoolExpr -> BoolExpr\n  | bnot : BoolExpr -> BoolExpr.\n**)\n\n(* 8.1 *)\nFunction size (e: BoolExpr): nat :=\n  match e with\n    | bbool b => 1\n    | or e1 e2 => 1 + size e1 + size e2\n    | bnot e => 1 + size e\n  end.\n\nDefinition elt (e1 e2: BoolExpr) := size e1 < size e2.\n\n(* 8.2 *)\nTheorem well_founded_elt: forall A: Set,\n  well_founded elt.\nProof.\n  unfold well_founded.\n  intros.\n  induction a;\n  constructor;\n  intros;\n  inversion H;\n  apply Acc_inverse_image;\n  apply lt_wf.\nQed.\n\nEnd Ejercicio8.", "meta": {"author": "nicodelpiano", "repo": "coq", "sha": "06344cda6995cdd9c5d44c52880b49a7ec280ebd", "save_path": "github-repos/coq/nicodelpiano-coq", "path": "github-repos/coq/nicodelpiano-coq/coq-06344cda6995cdd9c5d44c52880b49a7ec280ebd/TP6/practica6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.6896397552127975}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export IndProp.\n\n\n\n\n\n\nDefinition relation (X: Type) := X -> X -> Prop.\n\n\n\n\n\nPrint le.\n\nCheck le : nat -> nat -> Prop.\nCheck le : relation nat.\n\n\n\n\n\n\n\n\n\n\n\n\nDefinition partial_function {X: Type} (R: relation X) :=\nforall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.\n\n\n\nPrint next_nat.\n\nCheck next_nat : relation nat.\n\nTheorem next_nat_partial_function :\npartial_function next_nat.\nProof. hammer_hook \"Rel\" \"Rel.next_nat_partial_function\".\nunfold partial_function.\nintros x y1 y2 H1 H2.\ninversion H1. inversion H2.\nreflexivity.  Qed.\n\n\n\nTheorem le_not_a_partial_function :\n~ (partial_function le).\nProof. hammer_hook \"Rel\" \"Rel.le_not_a_partial_function\".\nunfold not. unfold partial_function. intros Hc.\nassert (0 = 1) as Nonsense. {\napply Hc with (x := 0).\n- apply le_n.\n- apply le_S. apply le_n. }\ndiscriminate Nonsense.   Qed.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nDefinition reflexive {X: Type} (R: relation X) :=\nforall a : X, R a a.\n\nTheorem le_reflexive :\nreflexive le.\nProof. hammer_hook \"Rel\" \"Rel.le_reflexive\".\nunfold reflexive. intros n. apply le_n.  Qed.\n\n\n\n\n\n\nDefinition transitive {X: Type} (R: relation X) :=\nforall a b c : X, (R a b) -> (R b c) -> (R a c).\n\nTheorem le_trans :\ntransitive le.\nProof. hammer_hook \"Rel\" \"Rel.le_trans\".\nintros n m o Hnm Hmo.\ninduction Hmo.\n-  apply Hnm.\n-  apply le_S. apply IHHmo.  Qed.\n\nTheorem lt_trans:\ntransitive lt.\nProof. hammer_hook \"Rel\" \"Rel.lt_trans\".\nunfold lt. unfold transitive.\nintros n m o Hnm Hmo.\napply le_S in Hnm.\napply le_trans with (a := (S n)) (b := (S m)) (c := o).\napply Hnm.\napply Hmo. Qed.\n\n\n\nTheorem lt_trans' :\ntransitive lt.\nProof. hammer_hook \"Rel\" \"Rel.lt_trans'\".\n\nunfold lt. unfold transitive.\nintros n m o Hnm Hmo.\ninduction Hmo as [| m' Hm'o].\nAdmitted.\n\n\n\n\nTheorem lt_trans'' :\ntransitive lt.\nProof. hammer_hook \"Rel\" \"Rel.lt_trans''\".\nunfold lt. unfold transitive.\nintros n m o Hnm Hmo.\ninduction o as [| o'].\nAdmitted.\n\n\n\n\nTheorem le_Sn_le : forall n m, S n <= m -> n <= m.\nProof. hammer_hook \"Rel\" \"Rel.le_Sn_le\".\nintros n m H. apply le_trans with (S n).\n- apply le_S. apply le_n.\n- apply H.\nQed.\n\n\nTheorem le_S_n : forall n m,\n(S n <= S m) -> (n <= m).\nProof. hammer_hook \"Rel\" \"Rel.le_S_n\".\nAdmitted.\n\n\n\n\n\n\nTheorem le_Sn_n : forall n,\n~ (S n <= n).\nProof. hammer_hook \"Rel\" \"Rel.le_Sn_n\".\nAdmitted.\n\n\n\n\n\n\n\n\n\nDefinition symmetric {X: Type} (R: relation X) :=\nforall a b : X, (R a b) -> (R b a).\n\n\nTheorem le_not_symmetric :\n~ (symmetric le).\nProof. hammer_hook \"Rel\" \"Rel.le_not_symmetric\".\nAdmitted.\n\n\n\n\nDefinition antisymmetric {X: Type} (R: relation X) :=\nforall a b : X, (R a b) -> (R b a) -> a = b.\n\n\nTheorem le_antisymmetric :\nantisymmetric le.\nProof. hammer_hook \"Rel\" \"Rel.le_antisymmetric\".\nAdmitted.\n\n\n\nTheorem le_step : forall n m p,\nn < m ->\nm <= S p ->\nn <= p.\nProof. hammer_hook \"Rel\" \"Rel.le_step\".\nAdmitted.\n\n\n\n\n\n\n\nDefinition equivalence {X:Type} (R: relation X) :=\n(reflexive R) /\\ (symmetric R) /\\ (transitive R).\n\n\n\n\n\n\nDefinition order {X:Type} (R: relation X) :=\n(reflexive R) /\\ (antisymmetric R) /\\ (transitive R).\n\n\n\nDefinition preorder {X:Type} (R: relation X) :=\n(reflexive R) /\\ (transitive R).\n\nTheorem le_order :\norder le.\nProof. hammer_hook \"Rel\" \"Rel.le_order\".\nunfold order. split.\n-  apply le_reflexive.\n- split.\n+  apply le_antisymmetric.\n+  apply le_trans.  Qed.\n\n\n\n\n\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) :\nclos_refl_trans R x z.\n\n\n\nTheorem next_nat_closure_is_le : forall n m,\n(n <= m) <-> ((clos_refl_trans next_nat) n m).\nProof. hammer_hook \"Rel\" \"Rel.next_nat_closure_is_le\".\nintros n m. split.\n-\nintro H. induction H.\n+  apply rt_refl.\n+\napply rt_trans with m. apply IHle. apply rt_step.\napply nn.\n-\nintro H. induction H.\n+  inversion H. apply le_S. apply le_n.\n+  apply le_n.\n+\napply le_trans with y.\napply IHclos_refl_trans1.\napply IHclos_refl_trans2. Qed.\n\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) :\nclos_refl_trans_1n R x z.\n\n\n\nLemma rsc_R : forall (X:Type) (R:relation X) (x y : X),\nR x y -> clos_refl_trans_1n R x y.\nProof. hammer_hook \"Rel\" \"Rel.rsc_R\".\nintros X R x y H.\napply rt1n_trans with y. apply H. apply rt1n_refl.   Qed.\n\n\nLemma rsc_trans :\nforall (X:Type) (R: relation X) (x y z : X),\nclos_refl_trans_1n R x y  ->\nclos_refl_trans_1n R y z ->\nclos_refl_trans_1n R x z.\nProof. hammer_hook \"Rel\" \"Rel.rsc_trans\".\nAdmitted.\n\n\n\n\n\nTheorem rtc_rsc_coincide :\nforall (X:Type) (R: relation X) (x y : X),\nclos_refl_trans R x y <-> clos_refl_trans_1n R x y.\nProof. hammer_hook \"Rel\" \"Rel.rtc_rsc_coincide\".\nAdmitted.\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/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245617, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.6896397501529409}}
{"text": "\n\n(* Reflexive_Transitive_Closure stuff, using Type rather than Prop *)\n\nSet Implicit Arguments.\nRequire Import List.\nImport ListNotations.\n\nRequire Import gen genT.\n\n(* compare \n  https://coq.inria.fr/stdlib/Coq.Relations.Relation_Definitions.html\n  https://coq.inria.fr/stdlib/Coq.Relations.Relation_Operators.html\n  https://coq.inria.fr/stdlib/Coq.Relations.Operators_Properties.html\n  Require Import Coq.Relations.Relation_Definitions.\n  Require Import Coq.Relations.Relation_Operators.\n  Require Import Coq.Relations.Operators_Properties.  \n  *)\n(* this in genT.v in ../lnt/tense-logic-in-Coq \nDefinition relationT (A : Type) := A -> A -> Type.\n*)\n\nDefinition transitiveT W (R : relationT W) :=\n  forall (x y z : W), R x y -> R y z -> R x z.\nCheck transitiveT.\n\n(* see https://coq.inria.fr/stdlib/Coq.Relations.Relation_Operators.html *)\nSection Reflexive_ClosureT.\n  Variable A : Type.\n  Variable R : relationT A.\n\nInductive clos_reflT (x: A) : A -> Type :=\n  | rT_step (y:A) : R x y -> clos_reflT x y\n  | rT_refl : clos_reflT x x.\n\nEnd Reflexive_ClosureT.\n\nSection Reflexive_Transitive_ClosureT.\n  Variable A : Type.\n  Variable R : relationT A.\n\nInductive clos_refl_transT (x:A) : A -> Type :=\n  | rtT_step (y:A) : R x y -> clos_refl_transT x y\n  | rtT_refl : clos_refl_transT x x\n  | rtT_trans (y z:A) :\n\tclos_refl_transT x y -> clos_refl_transT y z -> clos_refl_transT x z.\n\n(* Alternative definition by transitive extension on the left/right *)\n\nInductive clos_refl_transT_1n (x: A) : A -> Type :=\n  | rt1nT_refl : clos_refl_transT_1n x x\n  | rt1nT_trans (y z:A) :\n       R x y -> clos_refl_transT_1n y z -> clos_refl_transT_1n x z.\n\nInductive clos_refl_transT_n1 (x: A) : A -> Type :=\n  | rtn1T_refl : clos_refl_transT_n1 x x\n  | rtn1T_trans (y z:A) :\n      R y z -> clos_refl_transT_n1 x y -> clos_refl_transT_n1 x z.\n\nEnd Reflexive_Transitive_ClosureT.\n\n(* equivalences between above, need to reprove for ...T *)\nLemma clos_rt1n_rtT : forall A R (x y : A),\n  clos_refl_transT_1n R x y -> clos_refl_transT R x y.\nProof. intros. induction X. apply rtT_refl.\neapply rtT_trans. apply rtT_step. eassumption. eassumption. Qed.\n\nLemma clos_rt_rt1nT : forall A R (x y : A),\n  clos_refl_transT R x y -> clos_refl_transT_1n R x y.\nProof. intros. induction X. \neapply rt1nT_trans. eassumption. apply rt1nT_refl.\napply rt1nT_refl. \nclear X1 X2.  induction IHX1. assumption.\napply IHIHX1 in IHX2. eapply rt1nT_trans ; eassumption. Qed.\n\nLemma clos_rtn1_rtT : forall A R (x y : A),\n  clos_refl_transT_n1 R x y -> clos_refl_transT R x y.\nProof. intros. induction X.  apply rtT_refl.\neapply rtT_trans. eassumption. apply rtT_step. eassumption.  Qed.\n\nLemma clos_rt_rtn1T : forall A R (x y : A),\n  clos_refl_transT R x y -> clos_refl_transT_n1 R x y.\nProof. intros. induction X. \neapply rtn1T_trans. eassumption. apply rtn1T_refl.\napply rtn1T_refl. \nclear X1 X2.  induction IHX2. assumption.\neapply rtn1T_trans ; eassumption. Qed.\n\n(*\nLemma clos_rt_rt1n_iffT : forall A R (x y : A),\n  clos_refl_transT R x y <-> clos_refl_transT_1n R x y.\n\nLemma clos_rt_rtn1_iffT : forall A R (x y : A),\n  clos_refl_transT R x y <-> clos_refl_transT_n1 R x y.\n*)\n\n", "meta": {"author": "ianshil", "repo": "CE_GLS", "sha": "3dd86195e5dfb3e9c8e1db450512840ab407b688", "save_path": "github-repos/coq/ianshil-CE_GLS", "path": "github-repos/coq/ianshil-CE_GLS/CE_GLS-3dd86195e5dfb3e9c8e1db450512840ab407b688/general/rtcT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.8459424353665382, "lm_q1q2_score": 0.6896397498373523}}
{"text": "(*** Barrett Reduction *)\n(** This file implements a slightly-generalized version of Barrett\n    Reduction on [Z].  This version follows the Handbook of Applied\n    Cryptography (Algorithm 14.42) rather closely; the only deviations\n    are that we generalize from [k ± 1] to [k ± offset] for an\n    arbitrary offset, and we weaken the conditions on the base [b] in\n    [bᵏ] slightly.  Contrasted with some other versions, this version\n    does reduction modulo [b^(k+offset)] early (ensuring that we don't\n    have to carry around extra precision), but requires more stringint\n    conditions on the base ([b]), exponent ([k]), and the [offset]. *)\nRequire Import Coq.ZArith.ZArith Coq.micromega.Psatz.\nRequire Import Crypto.Util.ZUtil Crypto.Util.Tactics.BreakMatch.\n\nLocal Open Scope Z_scope.\n\nSection barrett.\n  (** Quoting the Handbook of Applied Cryptography <http://cacr.uwaterloo.ca/hac/about/chap14.pdf>: *)\n  (** Barrett reduction (Algorithm 14.42) computes [r = x mod m] given\n      [x] and [m]. The algorithm requires the precomputation of the\n      quantity [µ = ⌊b²ᵏ/m⌋]; it is advantageous if many reductions\n      are performed with a single modulus. For example, each RSA\n      encryption for one entity requires reduction modulo that\n      entity’s public key modulus. The precomputation takes a fixed\n      amount of work, which is negligible in comparison to modular\n      exponentiation cost.  Typically, the radix [b] is chosen to be\n      close to the word-size of the processor. Hence, assume [b > 3] in\n      Algorithm 14.42 (see Note 14.44 (ii)). *)\n\n  (** * Barrett modular reduction *)\n  Section barrett_modular_reduction.\n    Context (m b x k μ offset : Z)\n            (m_pos : 0 < m)\n            (base_pos : 0 < b)\n            (k_good : m < b^k)\n            (μ_good : μ = b^(2*k) / m) (* [/] is [Z.div], which is truncated *)\n            (x_nonneg : 0 <= x)\n            (offset_nonneg : 0 <= offset)\n            (k_big_enough : offset <= k)\n            (x_small : x < b^(2*k))\n            (m_small : 3 * m <= b^(k+offset))\n            (** We also need that [m] is large enough; [m] larger than\n                [bᵏ⁻¹] works, but we ask for something more precise. *)\n            (m_large : x mod b^(k-offset) <= m).\n\n    Let q1 := x / b^(k-offset). Let q2 := q1 * μ. Let q3 := q2 / b^(k+offset).\n    Let r1 := x mod b^(k+offset). Let r2 := (q3 * m) mod b^(k+offset).\n    (** At this point, the HAC says \"If [r < 0] then [r ← r + bᵏ⁺¹]\".\n        This is equivalent to reduction modulo [b^(k+offset)], as we\n        prove below.  The version involving modular reduction has the\n        benefit of being cheaper to implement, and making the proofs\n        simpler, so we primarily use that version. *)\n    Let r_mod_3m      := (r1 - r2) mod b^(k+offset).\n    Let r_mod_3m_orig := let r := r1 - r2 in\n                         if r <? 0 then r + b^(k+offset) else r.\n\n    Lemma r_mod_3m_eq_orig : r_mod_3m = r_mod_3m_orig.\n    Proof using base_pos k_big_enough m_pos m_small offset_nonneg r1 r2.\n      assert (0 <= r1 < b^(k+offset)) by (subst r1; auto with zarith).\n      assert (0 <= r2 < b^(k+offset)) by (subst r2; auto with zarith).\n      subst r_mod_3m r_mod_3m_orig; cbv zeta.\n      break_match; Z.ltb_to_lt.\n      { symmetry; apply (Zmod_unique (r1 - r2) _ (-1)); lia. }\n      { symmetry; apply (Zmod_unique (r1 - r2) _ 0); lia. }\n    Qed.\n\n    (** 14.43 Fact By the division algorithm (Definition 2.82), there\n        exist integers [Q] and [R] such that [x = Qm + R] and [0 ≤ R <\n        m]. In step 1 of Algorithm 14.42 (Barrett modular reduction),\n        the following inequality is satisfied: [Q - 2 ≤ q₃ ≤ Q]. *)\n    (** We prove this by providing a more useful form for [q₃]. *)\n    Let Q := x / m.\n    Let R := x mod m.\n    Lemma q3_nice : { b : bool * bool | q3 = Q + (if fst b then -1 else 0) + (if snd b then -1 else 0) }.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg x_nonneg x_small μ_good.\n      assert (0 < b^(k+offset)) by zero_bounds.\n      assert (0 < b^(k-offset)) by zero_bounds.\n      assert (x / b^(k-offset) <= b^(2*k) / b^(k-offset)) by auto with zarith lia.\n      assert (x / b^(k-offset) <= b^(k+offset)) by (autorewrite with pull_Zpow zsimplify in *; assumption).\n      subst q1 q2 q3 Q r_mod_3m r_mod_3m_orig r1 r2 R μ.\n      rewrite (Z.div_mul_diff_exact' (b^(2*k)) m (x/b^(k-offset))) by auto with lia zero_bounds.\n      rewrite (Z_div_mod_eq (_ * b^(2*k) / m) (b^(k+offset))) by lia.\n      autorewrite with push_Zmul push_Zopp zsimplify zstrip_div zdiv_to_mod.\n      rewrite Z.div_sub_mod_cond, !Z.div_sub_small; auto with zero_bounds zarith.\n      eexists (_, _); reflexivity.\n    Qed.\n\n    Fact q3_in_range : Q - 2 <= q3 <= Q.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg q2 x_nonneg x_small μ_good.\n      rewrite (proj2_sig q3_nice).\n      break_match; lia.\n    Qed.\n\n    (** 14.44 Note (partial justification of correctness of Barrett reduction) *)\n    (** (i) Algorithm 14.42 is based on the observation that [⌊x/m⌋]\n            can be written as [Q =\n            ⌊(x/bᵏ⁻¹)(b²ᵏ/m)(1/bᵏ⁺¹)⌋]. Moreover, [Q] can be\n            approximated by the quantity [q₃ = ⌊⌊x/bᵏ⁻¹⌋µ/bᵏ⁺¹⌋].\n            Fact 14.43 guarantees that [q₃] is never larger than the\n            true quotient [Q], and is at most 2 smaller. *)\n    Lemma x_minus_q3_m_in_range : 0 <= x - q3 * m < 3 * m.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg q2 x_nonneg x_small μ_good.\n      pose proof q3_in_range.\n      assert (0 <= R < m) by (subst R; auto with zarith).\n      assert (0 <= (Q - q3) * m + R < 3 * m) by nia.\n      subst Q R; autorewrite with push_Zmul zdiv_to_mod in *; lia.\n    Qed.\n\n    Lemma r_mod_3m_eq_alt : r_mod_3m = x - q3 * m.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg q2 x_nonneg x_small μ_good.\n      pose proof x_minus_q3_m_in_range.\n      subst r_mod_3m r_mod_3m_orig r1 r2.\n      autorewrite with pull_Zmod zsimplify; reflexivity.\n    Qed.\n\n    (** This version uses reduction modulo [b^(k+offset)]. *)\n    Theorem barrett_reduction_equivalent\n      : r_mod_3m mod m = x mod m.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg r1 r2 x_nonneg x_small μ_good.\n      rewrite r_mod_3m_eq_alt.\n      autorewrite with zsimplify push_Zmod; reflexivity.\n    Qed.\n\n    (** This version, which matches the original in the HAC, uses\n        conditional addition of [b^(k+offset)]. *)\n    Theorem barrett_reduction_orig_equivalent\n      : r_mod_3m_orig mod m = x mod m.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg r_mod_3m x_nonneg x_small μ_good. rewrite <- r_mod_3m_eq_orig; apply barrett_reduction_equivalent. Qed.\n\n    Lemma r_small : 0 <= r_mod_3m < 3 * m.\n    Proof using Q R base_pos k_big_enough m_large m_pos m_small offset_nonneg q3 x_nonneg x_small μ_good.\n      pose proof x_minus_q3_m_in_range.\n      subst Q R r_mod_3m r_mod_3m_orig r1 r2.\n      autorewrite with pull_Zmod zsimplify; lia.\n    Qed.\n\n\n    (** This version uses reduction modulo [b^(k+offset)]. *)\n    Theorem barrett_reduction_small (r := r_mod_3m)\n      : x mod m = let r := if r <? m then r else r-m in\n                  let r := if r <? m then r else r-m in\n                  r.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg r1 r2 x_nonneg x_small μ_good.\n      pose proof r_small. cbv zeta.\n      destruct (r <? m) eqn:Hr, (r-m <? m) eqn:?; subst r; rewrite !r_mod_3m_eq_alt, ?Hr in *; Z.ltb_to_lt; try lia.\n      { symmetry; eapply (Zmod_unique x m q3); lia. }\n      { symmetry; eapply (Zmod_unique x m (q3 + 1)); lia. }\n      { symmetry; eapply (Zmod_unique x m (q3 + 2)); lia. }\n    Qed.\n\n    (** This version, which matches the original in the HAC, uses\n        conditional addition of [b^(k+offset)]. *)\n    Theorem barrett_reduction_small_orig (r := r_mod_3m_orig)\n      : x mod m = let r := if r <? m then r else r-m in\n                  let r := if r <? m then r else r-m in\n                  r.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg r_mod_3m x_nonneg x_small μ_good. subst r; rewrite <- r_mod_3m_eq_orig; apply barrett_reduction_small. Qed.\n  End barrett_modular_reduction.\nEnd barrett.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Arithmetic/BarrettReduction/HAC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.6896170571761507}}
{"text": "Require Export XR_R.\nRequire Export XR_Rlt.\nRequire Export XR_Rle.\nRequire Export XR_Rlt_asym.\nRequire Export XR_Rlt_irrefl.\n\nImplicit Type r : R.\nLocal Open Scope R_scope.\n\nLemma Rle_not_lt : forall r1 r2, r2 <= r1 -> ~ r1 < r2.\nProof.\n  intros x y.\n  unfold \"<=\".\n  intros h.\n  unfold \"~\".\n  intro hxy.\n  destruct h as [ hyx | heq ].\n  {\n    assert (asym := Rlt_asym x y).\n    unfold \"~\" in asym.\n    apply asym.\n    { exact hxy. }\n    { exact hyx. }\n  }\n  {\n    subst y.\n    generalize dependent hxy.\n    apply Rlt_irrefl.\n  }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rle_not_lt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.6896170499790608}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) : natural := plus (Succ Zero) x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_91_mult_succ/goal33conj66_coqofml_z9ptHH.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.6896071146955083}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.Logic.ProofIrrelevance.\nRequire Import Coq.Relations.Relations.\nRequire Import Coq.Lists.List.\nRequire Import Bag.TotalOrder.\nRequire Import Bag.OrderedLists.\n\nImport ListNotations.\nLocal Open Scope list_scope.\n\nRecord bag {A : Type} (R : relation A) : Type := Bag {\n  to_list : list A;\n  order : Ordered R to_list\n}.\n\nArguments Bag {A R} to_list order.\n\n\nSection Definitions.\n\n  Variable A : Type.\n  Variable R : relation A.\n  Variable Order : TotalOrder R.\n\n  Lemma singleton_ordered : forall (x : A), Ordered R [x].\n  Proof. \n    intros. \n    apply Ordered_cons. \n    intros. \n    simpl in H.\n    inversion H. \n    apply Ordered_nil.\n  Qed.\n\n  Definition singleton (x : A) := Bag [x] (singleton_ordered x).\n\n  Definition union (b1 b2 : bag R) :=\n    Bag (union (to_list b1) (to_list b2)) \n        (union_order_pres Order (order b1) (order b2)).\n\n  Definition from_list (lst : list A) :=\n    Bag (from_list lst) (from_list_order Order lst).\n\n  Lemma unions_order_pres : forall (bags : list (bag R)),\n    Ordered R (unions (map (@to_list A R) bags)).\n  Proof with auto.\n    intros.\n    apply unions_order_pres.\n    intros.\n    rewrite -> in_map_iff in H.\n    destruct H as [bag [Heq HIn]].\n    destruct bag.\n    simpl in Heq.\n    subst...\n  Qed.\n\n  Definition unions (bags : list (bag R)) :=\n    Bag (unions (map (@to_list A R) bags)) (unions_order_pres bags).\n\n  Definition empty := Bag [] (Ordered_nil R).\n\nEnd Definitions.\n\n(* When writing singleton sets in isolation, R will not be inferrable. But,\n   this is convenient when singletons appear in a context that determines \n   R. *)\nArguments singleton [A R] x.\nArguments union [A R Order] b1 b2.\nArguments from_list [A R Order] lst.\nArguments empty [A R].\nArguments unions [A R Order] bags.\n", "meta": {"author": "frenetic-lang", "repo": "featherweight-openflow", "sha": "4470518794e3ed867919d30500be2d0128b1de1c", "save_path": "github-repos/coq/frenetic-lang-featherweight-openflow", "path": "github-repos/coq/frenetic-lang-featherweight-openflow/featherweight-openflow-4470518794e3ed867919d30500be2d0128b1de1c/coq/Bag/Bag2Defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6895443723499479}}
{"text": "(** by Evelyne Contejean, LRI *)\n\n\nFrom Coq Require Import List Relations Wellfounded Arith  Wf_nat Lia.\nFrom hydras Require Import more_list list_permut dickson term.\n\n\n(** A non-dependent version of lexicographic extension. \n*)\n\nDefinition lex (A B : Set) \n  (eq_A_dec : forall a1 a2, {a1=a2}+{a1<>a2}) \n  (o1 : relation A) (o2 : relation B) (s t : _ * _) :=\n  match s, t  with (s1,s2), (t1,t2) =>\n   if eq_A_dec s1 t1 then o2 s2 t2 else o1 s1 t1\n  end. \n \n(** Transitivity of  lexicographic extension. \n*)\n\nLemma lex_trans :\n forall (A B : Set) eq_A_dec o1 o2, \n antisymmetric A o1 -> transitive A o1 -> transitive B o2 ->\n transitive _ (lex _ _ eq_A_dec o1 o2).\nProof.\n  unfold transitive, lex; \n    intros A B eq_A_dec o1 o2 A1 T1 T2 p1 p2 p3; \n    destruct p1 as [a1 b1]; destruct p2 as [a2 b2]; \n    destruct p3 as [a3 b3];\n    elim (eq_A_dec a1 a2); intro eq1.\n  subst a2; elim (eq_A_dec a1 a3); intro eq2; trivial; apply T2.\n  intro lt1; elim (eq_A_dec a1 a3); intro eq3.\n  subst a3; elim (eq_A_dec a2 a1); intro eq2.\n  subst a2; absurd (a1=a1); trivial.\n  intro lt2; generalize (A1 _ _ lt1 lt2); contradiction.\n  elim (eq_A_dec a2 a3); intro eq4.\n  subst a3; trivial.\n  intro lt2; apply T1 with a2; trivial.\nQed.\n\n(** Well-foundedness of  lexicographic extension. \n*)\n\nLemma wf_lex :\n  forall A B eq_A_dec o1 o2, well_founded o1 -> well_founded o2 ->\n                             well_founded (lex A B eq_A_dec o1 o2).\nProof.\n  intros A B eq_A_dec o1 o2 W1 W2; unfold well_founded in *; \n    destruct a.\n  generalize b; clear b; pattern a; \n    refine (well_founded_ind W1 _ _ a);\n    clear a; intros a IH1 b; pattern b; \n    refine (well_founded_ind W2 _ _ b).\n  clear b; intros b IH2; apply Acc_intro.\n  destruct y; simpl; elim (eq_A_dec a0 a); intro a0_eq_a.\n  subst a0; apply IH2.\n  intro; apply IH1; trivial.\nQed.\n\n(** ** Module Type Precedence, \n** Definition of a precedence. \n*)\n\nModule Type Precedence.\nParameter A : Set.\nParameter prec : relation A.\n\nInductive status_type : Set :=\n  | Lex : status_type\n  | Mul : status_type.\n\nParameter status : A -> status_type.\n\nAxiom prec_dec : forall a1 a2 : A, {prec a1 a2} + {~ prec a1 a2}.\nAxiom prec_antisym : forall s, prec s s -> False.\nAxiom prec_transitive : transitive A prec.\n\nEnd Precedence.\n\n(** ** Module Type RPO, \n** Definition of RPO from a precedence on symbols. \n*)\n\nModule Type RPO.\n\nDeclare Module T : term.Term.\nDeclare Module P : Precedence with Definition A:= T.symbol.\n\nImport T.\nImport P.\nDeclare Module LP : list_permut.Permut with Definition DS.A:=term.\nImport LP.\n\n(** ** Definition of rpo.\n\n*)\nInductive rpo : term -> term -> Prop :=\n  | Subterm : forall f l t s, In s l -> rpo_eq t s -> rpo t (Term f l)\n  | Top_gt : \n       forall f g l l', prec g f -> \n       (forall s', In s' l' -> rpo s' (Term f l)) -> \n       rpo (Term g l') (Term f l)\n  | Top_eq_lex : \n        forall f l l', status f = Lex -> rpo_lex l' l -> \n        (forall s', In s' l' -> rpo s' (Term f l)) ->\n        rpo (Term f l') (Term f l)\n\n  | Top_eq_mul : \n        forall f l l', status f = Mul -> rpo_mul l' l -> \n        rpo (Term f l') (Term f l)\n\nwith rpo_eq : term -> term -> Prop :=\n  | Eq : forall t, rpo_eq t t\n  | Lt : forall s t, rpo s t -> rpo_eq s t\n\nwith rpo_lex : list term -> list term -> Prop :=\n  | List_gt : \n      forall s t l l', rpo s t -> length l = length l' -> \n      rpo_lex (s :: l) (t :: l')\n  | List_eq : forall s l l', rpo_lex l l' -> \n                             rpo_lex (s :: l) (s :: l')\n\nwith rpo_mul : list term -> list term -> Prop :=\n  | List_mul : \n       forall a lg ls lc l l', \n       list_permut l' (ls ++ lc) ->\n       list_permut l (a :: lg ++ lc) ->\n       (forall b, In b ls -> exists a', In a' (a :: lg) /\\ rpo b a') ->\n       rpo_mul l' l.\n\n(** ** rpo is a preorder, and its reflexive closure is an ordering. \n*)\n\nAxiom rpo_closure :\n  forall s t u, \n  (rpo t s -> rpo u t -> rpo u s) /\\\n  (rpo s t -> rpo t s -> False) /\\\n  (rpo s s -> False) /\\\n  (rpo_eq s t -> rpo_eq t s -> s = t).\n\nAxiom rpo_trans : forall s t u, rpo t s -> rpo u t -> rpo u s.\n\n(** ** Main theorem: when the precedence is well-founded, so is the rpo. \n\n*)\nAxiom wf_rpo : well_founded prec -> well_founded rpo.\n\n(** ** RPO is compatible with the instanciation by a substitution. \n*)\n\nAxiom rpo_subst :\n  forall t s, rpo s t -> \n  forall sigma, rpo (apply_subst sigma s) (apply_subst sigma t).\n\n(** ** RPO is compatible with adding context. \n*)\n\nAxiom rpo_add_context :\n forall p ctx s t, rpo s t -> is_a_pos ctx p = true -> \n  rpo (replace_at_pos ctx s p) (replace_at_pos ctx t p).\n\nEnd RPO.\n\nModule Make (T1: term.Term) \n                    (P1 : Precedence with Definition A := T1.symbol)\n<: RPO. (* with Module T := T1 with Module P:=P1. *)\n\nModule T := T1.\nModule P := P1.\n\nImport T.\nImport P.\n\nModule LP := list_permut.Make (Term_eq_dec).\nImport LP.\n\n(** ** Definition of size-based well-founded orderings for induction.\n*)\n\nDefinition o_size s t := size s < size t.\n\nLemma wf_size :  well_founded o_size.\nProof.\ngeneralize (well_founded_ltof _ size); unfold ltof; trivial.\nQed.\n\nDefinition size2 s := match s with (s1,s2) => (size s1, size s2) end.\nDefinition o_size2 s t := lex _ _ eq_nat_dec lt lt (size2 s) (size2 t).\nLemma wf_size2 : well_founded o_size2.\nProof.\nrefine (wf_inverse_image _ _ (lex _ _ eq_nat_dec lt lt) size2 _);\napply wf_lex; apply lt_wf.\nQed.\n\nDefinition size3 s := match s with (s1,s2) => (size s1, size2 s2) end.\nDefinition o_size3 s t := \n  lex _ _ eq_nat_dec lt (lex _ _ eq_nat_dec lt lt) (size3 s) (size3 t).\nLemma wf_size3 : well_founded o_size3.\nProof.\nrefine (wf_inverse_image _ _ \n  (lex _ _ eq_nat_dec lt (lex _ _ eq_nat_dec lt lt)) size3 _);\napply wf_lex; [ idtac | apply wf_lex ]; apply lt_wf.\nQed.\n\nLemma lex1 : \n forall s f l t1 u1 t2 u2, In s l -> o_size3 (s,(t1,u1)) (Term f l,(t2,u2)).\nProof.\nintros s f l t1 u1 t2 u2 In_s; unfold o_size3, size3, size2, lex;\nelim (eq_nat_dec (size s) (size (Term f l))).\nintro eq1; absurd (size (Term f l) < size (Term f l)); auto with arith;\ngeneralize (size_direct_subterm s (Term f l) In_s); rewrite eq1; trivial.\nintros; apply (size_direct_subterm s (Term f l) In_s).\nQed.\n\nLemma lex1_bis : \n forall a f l t1 u1 t2 u2, o_size3 (Term f l,(t1,u1)) (Term f (a::l),(t2,u2)).\nProof.\nintros a f l t1 u1 t2 u2; unfold o_size3, size3, size2, lex;\nelim (eq_nat_dec (size (Term f l)) (size (Term f (a :: l)))); intro eq1.\ndo 2 rewrite size_unfold in eq1; injection eq1; clear eq1; intro eq1;\nabsurd (list_size size l < list_size size l); auto with arith.\nassert (Ha: 1 <= size a) by apply size_ge_one.\nexfalso; lia.\ndo 2 rewrite size_unfold;\nsimpl; rewrite <- Nat.succ_lt_mono; \napply Nat.lt_le_trans with (1 + list_size size l);\nauto with arith; \napply Nat.add_le_mono_r; apply size_ge_one.\nQed.\n\nLemma lex2 :\n  forall t f l s u1 u2, In t l -> o_size3 (s,(t,u1)) (s,(Term f l, u2)).\nProof.\nintros t f l s u1 u2 In_t;\nunfold o_size3, size3, size2, lex;\nelim (eq_nat_dec (size s) (size s)); intro eq1.\nelim (eq_nat_dec (size t) (size (Term f l))); intro eq2.\nabsurd (size (Term f l) < size (Term f l)); auto with arith;\ngeneralize (size_direct_subterm t (Term f l) In_t); rewrite eq2; trivial.\napply (size_direct_subterm t (Term f l) In_t).\nabsurd (size s = size s); trivial.\nQed.\n\nLemma lex3 :\n  forall u f l s t, In u l -> o_size3 (s,(t,u)) (s,(t,Term f l)).\nProof.\nintros u f l s t In_u;\nunfold o_size3, size3, size2, lex;\nelim (eq_nat_dec (size s) (size s)); intro eq1.\nelim (eq_nat_dec (size t) (size t)); intro eq2.\napply (size_direct_subterm u (Term f l) In_u).\nabsurd (size t = size t); trivial.\nabsurd (size s = size s); trivial.\nQed.\n\nLemma o_size3_trans : transitive _ o_size3.\nProof.\ngeneralize (lex_trans _ _ eq_nat_dec lt (lex _ _ eq_nat_dec lt lt));\nunfold transitive, o_size3, size3, o_size2; intros H x y z lt1 lt2;\ndestruct x; destruct p; rename t into x1; rename t0 into x2; rename t1 into x3;\ndestruct y; destruct p; rename t into y1; rename t0 into y2; rename t1 into y3;\ndestruct z; destruct p; rename t into z1; rename t0 into z2; rename z1 into z3.\napply H with (size y1, size2 (y2,y3)); trivial.\nunfold antisymmetric; \nintros n m lt' lt''; generalize (Nat.lt_asymm n m lt' lt''); contradiction.\napply Nat.lt_trans.\nfold transitive; apply lex_trans.\nunfold antisymmetric; \nintros n m lt' lt''; generalize (Nat.lt_asymm n m lt' lt''); contradiction.\nunfold transitive; apply Nat.lt_trans.\nunfold transitive; apply Nat.lt_trans.\nQed.\n\n(** ** Definition of rpo.\n*)\n\nInductive rpo : term -> term -> Prop :=\n  | Subterm : forall f l t s, In s l -> rpo_eq t s -> rpo t (Term f l)\n  | Top_gt : \n       forall f g l l', prec g f -> \n       (forall s', In s' l' -> rpo s' (Term f l)) -> \n       rpo (Term g l') (Term f l)\n  | Top_eq_lex : \n        forall f l l', status f = Lex -> rpo_lex l' l -> \n        (forall s', In s' l' -> rpo s' (Term f l)) ->\n        rpo (Term f l') (Term f l)\n\n  | Top_eq_mul : \n        forall f l l', status f = Mul -> rpo_mul l' l -> \n        rpo (Term f l') (Term f l)\n\nwith rpo_eq : term -> term -> Prop :=\n  | Eq : forall t, rpo_eq t t\n  | Lt : forall s t, rpo s t -> rpo_eq s t\n\nwith rpo_lex : list term -> list term -> Prop :=\n  | List_gt : \n      forall s t l l', rpo s t -> length l = length l' -> \n      rpo_lex (s :: l) (t :: l')\n  | List_eq : forall s l l', rpo_lex l l' -> rpo_lex (s :: l) (s :: l')\n\nwith rpo_mul : list term -> list term -> Prop :=\n  | List_mul : \n       forall a lg ls lc l l', \n       list_permut l' (ls ++ lc) ->\n       list_permut l (a :: lg ++ lc) ->\n       (forall b, In b ls -> exists a', In a' (a :: lg) /\\ rpo b a') ->\n       rpo_mul l' l.\n\nLemma rpo_lex_same_length :\n  forall l l', rpo_lex l l' -> length l = length l'.\nProof.\ninduction l; intros l' rpo_lex_l; inversion rpo_lex_l.\nsimpl; rewrite H3; trivial.\nsimpl; rewrite (IHl l'0); trivial.\nQed.\n\nLemma rpo_subterm :\n forall s t, rpo t s -> forall tj, direct_subterm tj t -> rpo tj s.\nProof.\nintros s t;\ncut (forall p : term * term,\n       match p with\n       | (s,t) => rpo t s -> forall tj, direct_subterm tj t -> rpo tj s\n       end).\nintros H; apply (H (s,t)).\nclear s t; intro p; pattern p; refine (well_founded_ind wf_size2 _ _ _); \nclear p; intro p; destruct p; rename t into s; rename t0 into t;\nintros IH H tj In_tj; inversion H; clear H.\nsubst s t0; inversion H1; clear H1.\nsubst s0 t0; apply (Subterm f l tj t); trivial;\napply Lt; destruct t; try contradiction;\napply (Subterm s l0 tj tj); trivial; apply Eq; trivial.\nsubst t t0; apply (Subterm f l tj s0); trivial;\napply Lt; refine (IH (s0, s) _ _ tj _); trivial.\nunfold o_size2, size2, lex; \nelim (eq_nat_dec (size s0) (size (Term f l))); intro eq1.\nabsurd (size (Term f l) < size (Term f l)); auto with arith;\ngeneralize (size_direct_subterm s0 (Term f l) H0); rewrite eq1; trivial.\napply size_direct_subterm; trivial.\n\nsubst t s; apply H1; trivial.\n\nsubst t s; apply H2; trivial.\n\nsubst t s; inversion H1; clear H1.\nsubst l'0 l0; simpl in In_tj;\nelim (in_app_or _ _ _ (in_permut_in tj In_tj H)); clear In_tj; intro In_tj.\nelim (H3 tj In_tj); intros a' H4; elim H4; clear H4; intros H4 H5.\napply (Subterm f l tj a');\n[ refine (in_permut_in a' _ (list_permut_sym H2));\nrewrite app_comm_cons; apply in_or_app;  left\n| apply Lt; apply H5 ]; trivial.\napply (Subterm f l tj tj);\n[ refine (in_permut_in tj _ (list_permut_sym H2)); right; \napply in_or_app; right\n| apply Eq ]; trivial.\nQed.\n\n(** ** rpo is a preorder, and its reflexive closure is an ordering. \n*)\n\nLemma rpo_closure :\n  forall s t u, \n  (rpo t s -> rpo u t -> rpo u s) /\\\n  (rpo s t -> rpo t s -> False) /\\\n  (rpo s s -> False) /\\\n  (rpo_eq s t -> rpo_eq t s -> s = t).\nProof.\nintros s t u;\ncut (forall triple : term * (term * term),\n       match triple with\n       | (s,(t,u)) =>\n         (rpo t s -> rpo u t -> rpo u s) /\\\n         (rpo s t -> rpo t s -> False) /\\\n         (rpo s s -> False) /\\\n         (rpo_eq s t -> rpo_eq t s -> s = t)\n       end).\nintros H; apply (H (s,(t,u))).\nclear s t u; intro triple; pattern triple; \nrefine (well_founded_ind wf_size3 _ _ triple); clear triple.\nintros x IH; destruct x; rename t into s; destruct p; rename t0 into u;\ndestruct s.\nintuition.\ninversion H.\ninversion H0.\ninversion H.\ninversion_clear H0; trivial; inversion H1.\n\nrename s into f; cut (rpo (Term f l)  (Term f l) -> False).\nintro Anti0; cut (rpo (Term f l) t -> rpo t (Term f l) -> False).\nintro Anti; intuition.\n\ninversion H.\nsubst t0 f0 l0; inversion H5; clear H5.\nsubst t t0; apply (Subterm f l u s); trivial; apply Lt; trivial.\nsubst s0 t0; apply (Subterm f l u s); trivial; elim (IH (s,(t,u))); intuition.\napply Lt; trivial.\napply lex1; trivial.\n\nsubst t f0 l0; inversion H0.\nsubst u f0 l0; inversion H7; clear H7.\nsubst t t0; apply (rpo_subterm _ _ H); trivial.\nsubst s0 t0; elim (IH (Term f l,(s,t))); intuition; apply lex2; trivial.\n\nsubst u f0 l0; rename g0 into h; rename l'0 into l''; apply Top_gt.\napply prec_transitive with g; trivial.\nintros; elim (IH (Term f l,(Term g l',s'))); intuition;  apply lex3; trivial.\n\nsubst f0 l0 u; rename l'0 into l''; apply Top_gt; trivial.\nintros; elim (IH (Term f l, (Term g l',s'))); intuition; apply lex3; trivial.\nsubst u f0 l0; rename l'0 into l''; apply Top_gt; trivial.\ninversion H7; subst l0 l'0.\nintros s' In_s'; generalize (in_permut_in s' In_s' H1); clear In_s'; \nintro In_s'; elim (in_app_or _ _ _ In_s'); clear In_s'; \nintro In_s'.\nelim (IH (Term f l, (Term g l', s'))); intuition.\napply H11; elim (H3 s' In_s'); intros tj H'; elim H'; clear H'; \nintros In_tj H'; apply (Subterm g l' s' tj);\n[ refine (in_permut_in tj _ (list_permut_sym H2));\n  rewrite app_comm_cons; apply in_or_app; left\n| apply Lt ]; trivial.\napply lex3; refine (in_permut_in s' _ (list_permut_sym H1)); \napply in_or_app; left; trivial.\napply (rpo_subterm _ _ H); \nrefine (in_permut_in s' _ (list_permut_sym H2)); \nrewrite app_comm_cons; apply in_or_app; right; trivial.\n\nsubst f0 l0 t; inversion H0.\nsubst t f0 l0; inversion H8; clear H8.\nsubst s t; apply H6; trivial.\nsubst s s0; elim (IH (Term f l, (t,u))); intuition; apply lex2; trivial.\nsubst u f0 l0; rename l'0 into l''; apply Top_gt; trivial;\nintros; elim (IH (Term f l, (Term f l', s'))); intuition; apply lex3; trivial.\nsubst f0 l0 u; rename l'0 into l''; apply Top_eq_lex; trivial.\ngeneralize l' l'' H5 H8 IH; clear l' l'' H3 H5 H6 Anti Anti0 H H4 H8 H9 IH H0; \ninduction l; intros l' l'' H4 H6 IH; inversion H4.\nsubst l' t l'0; inversion H6.\nsubst l'' t l0; apply List_gt; elim (IH (a,(s,s0))); intuition.\napply lex1; trivial; left; trivial.\nrewrite H7; trivial.\napply lex1; trivial; left; trivial.\napply List_gt; trivial.\nsubst l'' s0 l'; rewrite (rpo_lex_same_length _ _ H1); trivial.\nsubst l' l'0 s; inversion H6.\napply List_gt; trivial; rewrite H5; apply rpo_lex_same_length; trivial.\nsubst l'' s l'; apply List_eq; apply IHl with l0; trivial;\nintros; apply IH; \napply o_size3_trans with (Term f l, (Term f l0, Term f l1)); trivial;\napply lex1_bis.\nintros; elim (IH (Term f l,(Term f l', s'))); intuition; apply lex3; trivial.\n\nabsurd (Lex = Mul); [ discriminate | rewrite <- H3; rewrite <- H7; trivial ].\n\nsubst t f0 l0; inversion H0.\nsubst t f0 l0; inversion H7; clear H7.\nsubst s t; apply (rpo_subterm _ _ H); trivial.\nsubst s0 t; elim (IH (Term f l, (s, u))); intuition;\n[ apply H2; trivial; apply (rpo_subterm _ _ H) | apply lex2 ]; trivial.\napply Top_gt; trivial;\nsubst u l0 f0; intros s' In_s'; \nelim (IH (Term f l, (Term f l', s'))); intuition; apply lex3; trivial.\nabsurd (Lex = Mul); [ discriminate | rewrite <- H3; rewrite <- H4; trivial ].\nsubst u f0 l0; apply Top_eq_mul; trivial;\ninversion H5; subst l'1 l0; inversion H7; subst l'1 l0; rename l'0 into l'';\nrewrite app_comm_cons in H9;\nelim (ac_syntactic _ _ _ _ (list_permut_trans (list_permut_sym H1) H9));\nintros lcc H'; elim H'; clear H';\nintros lcg H'; elim H'; clear H';\nintros lsc H'; elim H'; clear H';\nintros lsg H'; elim H'; clear H';\nintros P1 H'; elim H'; clear H';\nintros P2 H'; elim H'; clear H';\nintros P3 P4; apply (List_mul a (lg ++ lcg) (ls0 ++ lsc) lcc).\nrewrite <- ass_app; apply list_permut_trans with (ls0 ++ lc0); trivial;\napply context_list_permut_app1; trivial.\napply list_permut_trans with (lcc ++ lsc); trivial; apply list_permut_app_app.\napply list_permut_trans with (a :: lg ++ lc); trivial;\napply context_list_permut_cons; rewrite <- ass_app; \napply context_list_permut_app1;\napply list_permut_trans with (lcc ++ lcg); trivial; apply list_permut_app_app.\nintros b In_b; elim (in_app_or _ _ _ In_b); clear In_b; intro In_b.\nelim (H10 b In_b); intros a' H'; elim H'; clear H'; \nintros In_a' H'; elim (in_app_or _ _ _ (in_permut_in a' In_a' P4)); clear In_a'; \nintro In_a'.\nexists a'; split; trivial; rewrite app_comm_cons; apply in_or_app; right; trivial.\nassert (In a' ls).\nrefine (in_permut_in a' _ (list_permut_sym P2)); apply in_or_app; right; trivial.\nelim (H3 a' H11); intros a'' H''; elim H''; intros; exists a''; \nassert (In a'' (a :: lg ++ lcg)).\nrewrite app_comm_cons; apply in_or_app; left; trivial.\nsplit; trivial; \nelim (IH (a'',(a',b))); intuition; apply lex1;\nrefine (in_permut_in a'' _ (list_permut_sym H2)); trivial;\nrewrite app_comm_cons; apply in_or_app; left; trivial.\nassert (In b ls).\nrefine (in_permut_in b _ (list_permut_sym P2));\napply in_or_app; left; trivial.\nelim (H3 b H11); intros a'' H''; elim H''; intros; exists a''; split; trivial.\nrewrite app_comm_cons; apply in_or_app; left; trivial.\n\ninversion_clear H; trivial;\ninversion_clear H0; trivial;\ngeneralize (Anti H1 H); contradiction.\n\nintros lt_s_t lt_t_s; inversion lt_t_s; clear lt_t_s.\nsubst t0 f0 l0; inversion H3; clear H3.\nsubst t t0; elim (IH (s, (Term f l, u))); intuition;\n[ apply H1; trivial; apply (Subterm f l s s); trivial; apply Eq\n| apply lex1 ]; trivial.\nsubst s0 t0; elim (IH (s,(t,(Term f l)))); intuition.\napply Anti0; apply (Subterm f l (Term f l) s); trivial; apply Lt; trivial.\napply lex1; trivial.\nsubst t f0 l0; inversion lt_s_t; clear lt_s_t.\nsubst t f0 l0; inversion H5; clear H5.\nsubst t s; apply Anti0; apply H3; trivial.\nsubst s s0; elim (IH (Term f l, (t,u))); intuition; apply lex2; trivial.\nsubst g0 l'0 f0 l0; apply prec_antisym with f; trivial;\napply prec_transitive with g; trivial.\nsubst f0 l'0 g l0; apply prec_antisym with f; trivial.\nsubst f0 l'0 g l0; apply prec_antisym with f; trivial.\nsubst t f0 l0; inversion lt_s_t; clear lt_s_t.\nsubst t f0 l0; inversion H6; clear H6.\nsubst s t; apply Anti0; trivial; apply H4; trivial.\nsubst s s0; elim (IH (Term f l, (t,u))); intuition; apply lex2; trivial.\napply prec_antisym with f; trivial.\ngeneralize l' IH H3 H6; subst f0 l'0 l0; clear Anti0 H1 H3 H4 IH H5 H6 H7;\ninduction l; intros; inversion H3; clear H3.\nsubst t l'0 l'1; inversion H6; clear H6.\nsubst s0 l1 t l0; elim (IH (a,(s,u))); intuition; apply lex1; left; trivial.\nsubst s; elim (IH (a, (Term f (a::l0),u))); intuition; apply lex1; left; trivial.\nsubst s l'0 l'1; inversion H6; clear H6.\nelim (IH (a, (Term f (a::l0),u))); intuition; apply lex1; left; trivial.\nsubst l'0 s l1; apply IHl with l0; trivial;\nintros; apply IH;\napply o_size3_trans with (Term f l, (Term f l0, u)); trivial; apply lex1_bis.\n\nabsurd (Lex = Mul); [ discriminate | rewrite <- H1; rewrite <- H5; trivial ].\n\nsubst t f0 l0; inversion lt_s_t.\nsubst t f0 l0; inversion H3; subst l0 l'0.\nelim (in_app_or _ _ _ (in_permut_in s H4 H)); intro In_s.\nelim (H1 s In_s); intros a' H'; elim H'; clear H'; \nintros In_a' H'; apply Anti0; apply (Subterm f l (Term f l) a').\nrefine (in_permut_in a' _ (list_permut_sym H0)); \n rewrite app_comm_cons; apply in_or_app; left; trivial.\ninversion H5; subst s; apply Lt; trivial;\nelim (IH (a',(t,(Term f l)))); intuition; apply lex1;\nrefine (in_permut_in a' _ (list_permut_sym H0));\nrewrite app_comm_cons; apply in_or_app; left; trivial.\napply Anti0; apply (Subterm f l (Term f l) s); trivial;\nrefine (in_permut_in s _ (list_permut_sym H0)); \n rewrite app_comm_cons; apply in_or_app; right; trivial.\napply prec_antisym with f; trivial.\nabsurd (Lex = Mul); [ discriminate | rewrite <- H2; rewrite <- H4; trivial ].\n\nsubst f0 l'0 l0; apply Anti0; apply Top_eq_mul; trivial;\ninversion H3; subst l'0 l0; inversion H5; subst l'0 l0.\nrewrite app_comm_cons in H7;\nelim (ac_syntactic _ _ _ _ (list_permut_trans (list_permut_sym H) H7));\nintros lcc H'; elim H'; clear H';\nintros lcg H'; elim H'; clear H';\nintros lsc H'; elim H'; clear H';\nintros lsg H'; elim H'; clear H';\nintros P1 H'; elim H'; clear H';\nintros P2 H'; elim H'; clear H';\nintros P3 P4; apply (List_mul a (lg ++ lcg) (ls0 ++ lsc) lcc).\nrewrite <- ass_app; apply list_permut_trans with (ls0 ++ lc0); trivial;\napply context_list_permut_app1; trivial;\napply list_permut_trans with (lcc ++ lsc); trivial; apply list_permut_app_app.\napply list_permut_trans with (a :: lg ++ lc); trivial;\napply context_list_permut_cons; rewrite <- ass_app; \napply context_list_permut_app1;\napply list_permut_trans with (lcc ++ lcg); trivial; apply list_permut_app_app.\nintros b In_b; elim (in_app_or _ _ _ In_b); clear In_b; intro In_b.\nelim (H8 b In_b); intros a' H'; elim H'; clear H'; \nintros In_a' H'; elim (in_app_or _ _ _ (in_permut_in a' In_a' P4)); clear In_a'; \nintro In_a'.\nexists a'; split; trivial; rewrite app_comm_cons; apply in_or_app; right; trivial.\nassert (In a' ls).\nrefine (in_permut_in a' _ (list_permut_sym P2)); apply in_or_app; right; trivial.\nelim (H1 a' H9); intros a'' H''; elim H''; intros; exists a''; \nassert (In a'' (a :: lg ++ lcg)).\nrewrite app_comm_cons; apply in_or_app; left; trivial.\nsplit; trivial; \nelim (IH (a'',(a',b))); intuition; apply lex1;\nrefine (in_permut_in a'' _ (list_permut_sym H0)); trivial;\nrewrite app_comm_cons; apply in_or_app; left; trivial.\nassert (In b ls).\nrefine (in_permut_in b _ (list_permut_sym P2));\napply in_or_app; left; trivial.\nelim (H1 b H9); intros a'' H''; elim H''; intros; exists a''; split; trivial.\nrewrite app_comm_cons; apply in_or_app; left; trivial.\n\nintro lt_s_s; inversion lt_s_s; clear lt_s_s.\ninversion H3; clear H3.\nsubst t0 f0 l0 t1 s;\nabsurd (size (Term f l) < size (Term f l)); auto with arith;\napply (size_direct_subterm (Term f l) (Term f l) H2).\nsubst t0 f0 l0 s0 t1.\nelim (IH (s,(Term f l, s))); intuition.\napply H1; trivial; apply (Subterm f l s s); trivial; apply Eq; trivial.\napply lex1; trivial.\napply prec_antisym with f; trivial.\nsubst f0 l' l0; clear H4; induction l; inversion H3.\nelim (IH (a,(t,u))); intuition; apply lex1; left; trivial.\nsubst s l0 l'; apply IHl; trivial; intros; apply IH;\napply o_size3_trans with (Term f l, (t, u)); trivial; apply lex1_bis.\n\nsubst f0 l0 l'; inversion H3.\nsubst l' l0; assert (list_permut ls (a :: lg)).\napply remove_context_list_permut_app2 with lc; rewrite <- app_comm_cons; \napply list_permut_trans with l; trivial;\napply list_permut_sym; trivial.\nassert (forall b, In b ls -> (exists a', In a' ls /\\ rpo b a')).\nintros b In_b; elim (H1 b In_b); intros a' H'; exists a'; intuition;\nrefine (in_permut_in _ _ (list_permut_sym H4)); trivial.\nassert (forall v, In v ls -> In v l).\nintros; refine (in_permut_in _ _ (list_permut_sym H));\napply in_or_app; left; trivial.\nassert (1 <= length ls). \nrewrite (list_permut_length H4); simpl; auto with arith.\ngeneralize H5 H6; clear a lg H4 H5 H6 H2 H3 H0 H1 H;\ninduction ls; intros.\nabsurd (1 <= 0); auto with arith.\ndestruct ls.\nelim (H5 a (or_introl _ (refl_equal _))); intros a' H'; \nelim H'; clear H'; intros In_a' lt_a_a'; elim In_a'; clear In_a'; intro In_a'.\nsubst a'; elim (IH (a,(t,u))); intuition; apply lex1; apply H6; left; trivial.\ncontradiction.\napply IHls.\nsimpl; auto with arith.\nintros b In_b; elim (H5 b).\nintros a' H'; elim H'; clear H'; \nintros In_a' lt_b_a'; elim In_a'; clear In_a';\nintro In_a'.\nsubst a'; elim (H5 a (or_introl _ (refl_equal _))); \nintros a'' H''; elim H''; clear H''; \nintros In_a'' lt_a_a''; elim In_a''; clear In_a'';\nintros In_a''.\nsubst a''; elim (IH (a,(t,u))); intuition; apply lex1; apply H6; left; trivial.\nexists a''; split; trivial.\nelim (IH (a'',(a,b))); intuition; apply lex1; apply H6; right; trivial.\nexists a'; split; trivial.\nright; trivial.\nintros; apply H6; right; trivial.\nQed.\n\nLemma rpo_trans : forall s t u, rpo t s -> rpo u t -> rpo u s.\nProof.\nintros s t u lt_t_s lt_u_t; elim (rpo_closure s t u); intuition.\nQed.\n\nRecord SN_term : Set := \n  mk_sn \n  {\n    tt : term; \n    sn : Acc rpo tt\n    }.\n\n(** ** Well-foundedness of rpo. \nHow to build a built a list of pairs (terms, proof of accessibility) from\na global of accessibility on the list. \n*)\n\nDefinition build_list_of_SN_terms :\n forall l (proof : forall t, In t l -> Acc rpo t), list SN_term.  \nProof.\nintro l; induction l.\nintros _; exact nil.\nintro Acc_subterm; assert (Acc rpo a).\napply Acc_subterm; left; trivial.\nassert (forall t, In t l -> Acc rpo t).\nintros; apply Acc_subterm; right; trivial.\nexact ((mk_sn a H) :: (IHl H0)).\nDefined.\n\n(** Projection on the first element of the pairs after building the\npairs as above is the identity. \n*)\n\nLemma projection_list_of_SN_terms :\n  forall l proof, map tt (build_list_of_SN_terms l proof) = l.\nProof.\nintro l; induction l; simpl; trivial.\nintros proof; apply (f_equal (fun l => a :: l)); apply IHl.\nQed.\n\nLemma in_sn_sn : \n forall l s, In s (map tt l) -> Acc rpo s.\nProof.\nintro l; induction l.\ncontradiction.\nintros s In_s; elim In_s; clear In_s; intro In_s.\nsubst s; destruct a; trivial.\napply IHl; trivial.\nQed.\n\n(** Definition of rpo on accessible terms. \n*)\n\nDefinition rpo_rest := fun s t => rpo (tt s) (tt t).\n\n(** Extension of [rpo_lex] to the accessible terms. \n*)\n\nInductive rpo_lex_rest : list SN_term -> list SN_term -> Prop :=\n  | List_gt_rest : \n       forall s t l l', rpo_rest s t -> length l = length l' -> \n       rpo_lex_rest (s :: l) (t :: l')\n  | List_eq_rest : forall s t l l', tt s = tt t -> rpo_lex_rest l l' -> \n        rpo_lex_rest (s :: l) (t :: l').\n\n(** A triviality: rpo on accessible terms is well-founded.\n\n *)\nLemma wf_on_rest : well_founded rpo_rest.\nProof.\nunfold well_founded, rpo_rest; intro s;\napply (Acc_inverse_image SN_term term rpo tt).\ndestruct s; simpl; trivial.\nQed.\n\nLemma rpo_lex_rest_same_length :\n  forall l l', rpo_lex_rest l l' -> length l = length l'.\nProof.\ninduction l; intros l' rpo_lex_l; inversion rpo_lex_l.\nsimpl; rewrite H3; trivial.\nsimpl; rewrite (IHl l'0); trivial.\nQed.\n\n(** Proof of accessibility does not actually matter, provided at \n  least one exists. \n*)\n\nLemma acc_lex_drop_proof :\n  forall s t l, tt s = tt t -> Acc rpo_lex_rest (s::l) -> Acc rpo_lex_rest (t::l).\nProof.\nintros s t l s_eq_t Acc_s.\napply Acc_intro; intros l' lt_l'_l;\napply Acc_inv with (s :: l); trivial; inversion lt_l'_l.\n\nsubst l' t0 l'0; apply List_gt_rest; trivial;\nunfold rpo_rest in *; rewrite s_eq_t; trivial.\n\nsubst l' t0 l'0; apply List_eq_rest; trivial;\nrewrite s_eq_t; trivial.\nQed.\n\n(** Lexicographic extension of rpo on accessible terms lists is well-founded. \n*)\n\nLemma wf_on_lex_rest : well_founded rpo_lex_rest.\nProof.\nunfold well_founded; intro a; pattern a; apply list_rec2; clear a; \ninduction n;\nintros l L; destruct l.\napply Acc_intro; intros l' lt_l'_l; inversion lt_l'_l.\nsimpl in L; absurd (S(length l) <= 0); auto with arith.\napply Acc_intro; intros l' lt_l'_l; inversion lt_l'_l.\nsimpl in L; generalize (le_S_n _ _ L); clear L; intro L.\ngeneralize l L; clear l L; pattern s;\napply (well_founded_induction_type wf_on_rest);\nclear s; intros s IH l L.\ngeneralize (IHn l L); intro Acc_l; induction Acc_l; rename x into l.\napply Acc_intro; intros l' lt_l'_l; inversion lt_l'_l.\nsubst l' t l'0; apply IH; trivial; rewrite H5; trivial.\nsubst l' t l'0; apply acc_lex_drop_proof with s.\napply sym_eq; trivial.\napply H0; trivial; rewrite (rpo_lex_rest_same_length _ _ H5); trivial.\nQed.\n\n(** Extension of [rpo_mul] to the accessible terms. \n*)\n\nInductive rpo_mul_rest : list SN_term -> list SN_term -> Prop :=\n  | List_mul_rest : \n       forall a lg ls lc l l', \n       list_permut (map tt l') (map tt (ls ++ lc)) ->\n       list_permut (map tt l) (map tt (a :: lg ++ lc)) ->\n       (forall b, In b ls -> exists a', In a' (a :: lg) /\\ rpo_rest b a') ->\n       rpo_mul_rest l' l.\n\n(** Definition of a finer grain for multiset extension. \n*)\n\nInductive rpo_mul_rest_step : list SN_term -> list SN_term -> Prop :=\n  | List_mul_rest_step : \n       forall a ls lc l l', \n       list_permut (map tt l') (map tt (ls ++ lc)) ->\n       list_permut (map tt l) (map tt (a :: lc)) ->\n       (forall b, In b ls -> rpo_rest b a) ->\n       rpo_mul_rest_step l' l.\n\n(** The plain multiset extension is in the transitive closure of\nthe finer grain extension. \n*)\n\nLemma rpo_mul_trans_clos :\n  inclusion _ rpo_mul_rest (clos_trans _ rpo_mul_rest_step).\nProof.\nunfold inclusion; intros l' l H; inversion H; clear H; subst l0 l'0;\ngeneralize l' l a ls lc H0 H1 H2; clear l' l a ls lc H0 H1 H2;\ninduction lg.\nintros l' l a ls lc H0 H1 H2;\napply t_step; apply (List_mul_rest_step a ls lc); trivial;\nintros b In_b; elim (H2 b In_b); \nintros a' H'; elim H'; clear H';\nintros In_a' lt_b; elim In_a'; clear In_a'; \nintro In_a'; [subst a'; trivial | contradiction ].\nintros l' l a0 ls lc H0 H1 H2.\nassert (exists ls1, exists ls2, \n list_permut (map tt ls) (map tt (ls1 ++ ls2)) /\\\n (forall b, In b ls1 -> rpo_rest b a0) /\\\n (forall b, In b ls2 -> exists a', In a' ( a:: lg) /\\ rpo_rest b a')).\nclear H0; induction ls.\nexists (nil : list SN_term); exists (nil : list SN_term); intuition.\ncontradiction.\ncontradiction.\nelim IHls.\nintros ls1 H; elim H; clear H;\nintros ls2 H; elim (H2 a1 (or_introl _ (refl_equal _)));\nintros a' H'; elim H'; clear H';\nintros In_a' H'; elim In_a'; clear In_a'; \nintro In_a'.\nsubst a'; exists (a1 :: ls1); exists ls2; intuition.\nrewrite <- app_comm_cons; simpl; apply context_list_permut_cons; trivial.\nelim H3; clear H3; intro H3.\nsubst b; trivial.\napply H; trivial.\nexists ls1; exists (a1 :: ls2); intuition.\nrewrite map_app; simpl; apply (list_permut_add_cons_inside);\nrewrite <- map_app; trivial.\nelim H3; clear H3; intro H3.\nsubst b; exists a'; intuition.\napply H4; trivial.\nintros; apply H2; trivial; right; trivial.\nelim H; clear H;\nintros ls1 H; elim H; clear H; \nintros ls2 H; apply t_trans with (a0 :: ls2 ++ lc). \napply t_step; apply (List_mul_rest_step a0 ls1 (ls2 ++ lc)).\napply list_permut_trans with (map tt (ls ++ lc)); trivial.\nrewrite <- app_ass; do 2 rewrite map_app; apply context_list_permut_app2; intuition.\napply list_permut_refl.\nintuition.\napply (IHlg (a0 :: ls2 ++ lc) l a ls2 (a0 :: lc)).\nrewrite map_app; simpl; apply list_permut_add_cons_inside;\nrewrite map_app; apply list_permut_refl.\napply list_permut_trans with (map tt (a0 :: (a :: lg) ++ lc)); trivial.\ndo 2 rewrite app_comm_cons; generalize (a :: lg); intro l0.\ndo 2 rewrite map_app; simpl; apply list_permut_add_cons_inside;\napply list_permut_refl.\nintuition.\nQed.\n\n(** Splitting in two disjoint cases. \n*)\n\nLemma two_cases_rpo :\n forall a m n, \n rpo_mul_rest_step n (a :: m) ->\n (exists n', list_permut (map tt n) (map tt (a :: n')) /\\ \n             rpo_mul_rest_step n' m) \\/\n (exists k, (forall b, In b k -> rpo_rest b a) /\\ \n            list_permut (map tt n) (map tt (k ++ m))).\nProof.\nintros a m n M; inversion_clear M;\ndestruct a; destruct a0; elim (eq_term_dec tt0 tt1).\nintro; subst tt1; right; exists ls; intuition;\napply list_permut_trans with (map tt (ls ++ lc)); trivial;\ndo 2 rewrite map_app; apply context_list_permut_app1;\napply remove_context_list_permut_cons with tt0; \napply list_permut_sym; trivial.\nintro a_diff_a0; left;\nelim (In_dec eq_term_dec tt1 (map tt m)); intro In_a0.\ngeneralize (split_list_app_cons eq_term_dec _ _ In_a0); clear In_a0;\ndestruct (split_list eq_term_dec (map tt m) tt1).\nintro; assert (forall s, In s l -> Acc rpo s).\nintros s In_s; apply in_sn_sn with m; rewrite H2; apply in_or_app; left; trivial.\nassert (forall s, In s l0 -> Acc rpo s).\nintros s In_s; apply in_sn_sn with m; rewrite H2; apply in_or_app; do 2 right; trivial.\nexists ((build_list_of_SN_terms l H3) ++ ls ++ (build_list_of_SN_terms l0 H4)); \nintuition.\napply list_permut_trans with (map tt (ls ++ lc)) ; trivial;\napply remove_context_list_permut_cons with tt1;\napply list_permut_trans with ((map tt ls) ++ tt1 :: (map tt lc)).\napply list_permut_add_cons_inside; rewrite map_app; apply list_permut_refl.\napply list_permut_trans with (map tt ls ++ (tt0 :: l ++ tt1 :: l0)).\napply context_list_permut_app1; apply list_permut_sym; rewrite <- H2; trivial.\nrewrite app_comm_cons; rewrite <- app_ass; apply list_permut_sym;\napply list_permut_add_cons_inside;\nrewrite app_ass; rewrite <- app_comm_cons; simpl;\napply list_permut_add_cons_inside;\ndo 2 rewrite map_app; do 2 rewrite projection_list_of_SN_terms;\ndo 2 rewrite <- app_ass; apply context_list_permut_app2;\napply list_permut_app_app.\napply (List_mul_rest_step (mk_sn tt1 sn1) ls \n(build_list_of_SN_terms l H3 ++ build_list_of_SN_terms l0 H4)); intuition.\ndo 2 rewrite ass_app; do 4 rewrite map_app; \napply context_list_permut_app2; apply list_permut_app_app.\nrewrite H2; simpl; rewrite map_app; do 2 rewrite projection_list_of_SN_terms;\napply list_permut_sym; apply list_permut_add_cons_inside; \napply list_permut_refl.\nabsurd (In tt1 (map tt (mk_sn tt0 sn0 :: m))).\nunfold not; intro H2; elim H2; clear H2; intro H2.\napply a_diff_a0; trivial.\napply In_a0; trivial.\nrefine (in_permut_in tt1 _ (list_permut_sym H0)); left; trivial.\nQed.\n\nLemma list_permut_map_acc :\n forall l l', list_permut (map tt l) (map tt l') ->\n Acc rpo_mul_rest_step l ->  Acc rpo_mul_rest_step l'.\nProof.\nintros l l' P A1; apply Acc_intro; \nintros l'' M2.\ninversion A1; apply H; inversion M2.\nsubst l'0 l0; apply (List_mul_rest_step a ls lc); trivial.\napply list_permut_trans with (map tt l'); trivial.\nQed.\n\n(** Multiset extension of rpo on accessible terms lists is well-founded. \n*)\n\nLemma wf_on_mul_rest : well_founded rpo_mul_rest.\nProof.\napply wf_incl with (clos_trans _ rpo_mul_rest_step).\napply rpo_mul_trans_clos.\napply wf_clos_trans.\nunfold well_founded; intro a; induction a.\napply Acc_intro; intros m H; inversion_clear H.\ngeneralize (list_permut_length H1); intro Abs; simpl in Abs;\nabsurd (0 = S (length (map tt (a :: lc)))); trivial; discriminate.\ngeneralize a0 IHa; clear a0 IHa; pattern a;\nrefine (well_founded_ind wf_on_rest _ _ a); clear a.\nintros;\napply (Acc_iter  (R:= rpo_rest)\n(fun a => Acc rpo_rest a -> forall m, Acc rpo_mul_rest_step m -> \nAcc rpo_mul_rest_step (a :: m))); trivial.\ndestruct x; rename tt0 into s; rename sn0 into Acc_s; \nclear a0 IHa; intros b IH Acc_b m Acc_m.\napply (Acc_iter  (R:= rpo_mul_rest_step) \n        (fun m => Acc rpo_mul_rest_step m -> Acc rpo_mul_rest_step (b :: m))); trivial.\nclear m Acc_m; intros m IHm Acc_m; apply Acc_intro.\nintros y lt_y; elim (two_cases_rpo _ _ _ lt_y); clear lt_y; intro lt_y.\nelim lt_y; clear lt_y;\nintros n' H'; elim H'; clear H';\nintros P M; apply list_permut_map_acc with (b :: n').\napply list_permut_sym; trivial.\napply IHm; trivial; apply Acc_inv with m; trivial.\nelim lt_y; clear lt_y;\nintros k H'; elim H'; clear H';\nintros M P; apply list_permut_map_acc with (k ++ m).\napply list_permut_sym; trivial.\nclear P; induction k; trivial.\nsimpl; apply IH.\napply M; left; trivial.\napply Acc_inv with b; trivial; apply M; left; trivial.\napply IHk;\nintros; apply M; right; trivial.\napply wf_on_rest.\napply wf_on_rest.\nQed.\n\n(** Another definition of rpo, only on scheme of accessible terms. \n*)\n\nDefinition rpo_term : relation (symbol * list SN_term) :=\n fun f_l g_l' => \n  match f_l with\n  | (f,l) =>\n  match g_l' with\n  | (g,l') =>\n    if F.eq_symbol_dec f g\n    then\n      match status f with\n      | Lex => rpo_lex_rest l l'\n      | Mul => rpo_mul_rest l l'\n      end\n    else prec f g\n  end\n  end.\n\nLemma  wf_rpo_term : well_founded prec -> well_founded rpo_term.\nProof.\nintro wf_prec; unfold well_founded in *; destruct a; rename s into f;\ngeneralize l; clear l; pattern f; refine (well_founded_ind wf_prec _ _ f);\nclear f; intros f IHf l; pattern l;\nassert (forall g, f=g -> status g = status f).\nintros; subst f; trivial.\ndestruct (status f); generalize (H f (refl_equal _)); clear H; intro H.\npattern l; refine (well_founded_ind wf_on_lex_rest _ _ l); clear l; \nintros l IHl; apply Acc_intro; intros y; destruct y; simpl;\nelim (F.eq_symbol_dec s f); intro eq1.\nsubst s; rewrite H; intros; apply IHl; trivial.\nintros; apply IHf; trivial.\npattern l; refine (well_founded_ind wf_on_mul_rest _ _ l); clear l; \nintros l IHl; apply Acc_intro; intros y; destruct y; simpl;\nelim (F.eq_symbol_dec s f); intro eq1.\nsubst s; rewrite H; intros; apply IHl; trivial.\nintros; apply IHf; trivial.\nQed.\n\nLemma acc_build :\n  well_founded prec -> forall f l, \n  Acc rpo (Term f (map (fun sn_tt => tt sn_tt) l)).\nProof.\nintros wf_prec f l;\nrefine (well_founded_induction_type (wf_rpo_term wf_prec)\n(fun f_l =>  \n  match f_l with\n  | (f,l) => Acc rpo (Term f (map (fun sn_tt : SN_term => tt sn_tt) l))\n  end) _ (f,l)).\nclear f l; intros x IH; destruct x; rename s into f.\napply Acc_intro; intros t; pattern t; apply term_rec3; clear t.\nintros v _; apply Acc_intro; intros u lt_u_t; inversion lt_u_t.\nintros g l' IH' lt_t_s; inversion lt_t_s.\n\nsubst t f0 l0; assert (Acc rpo s).\napply (in_sn_sn _ _ H2).\ninversion H3; subst s; trivial; apply Acc_inv with t; trivial.\n\nsubst g0 l'0 f0 l0; assert (forall s', In s' l' -> Acc rpo s').\nintros s' In_s'; apply IH'; trivial; apply H4; trivial.\nrewrite <- (projection_list_of_SN_terms l' H); \napply (IH (g,(build_list_of_SN_terms l' H)));\nsimpl; elim (F.eq_symbol_dec g f); intro eq1; trivial;\nsubst g; generalize (prec_antisym _ H2); contradiction.\n\nsubst f0 l'0 g l0; assert (forall s', In s' l' -> Acc rpo s').\nintros s' In_s'; apply IH'; trivial; apply H5; trivial.\n\nrewrite <- (projection_list_of_SN_terms l' H); \napply (IH (f,(build_list_of_SN_terms l' H)));\nsimpl; elim (F.eq_symbol_dec f f); intro eq1.\nrewrite H3; generalize l' H H4; clear l' H H4 H5 IH IH' lt_t_s eq1; \ninduction l; intros l' H H4; inversion H4; clear H4.\nsubst l' t l'0; simpl; apply List_gt_rest.\nunfold rpo_rest; trivial.\nrewrite <- (projection_list_of_SN_terms l0 \n              (fun (t : term) (H0 : In t l0) => H t (or_intror (s = t) H0))) in H6;\ndo 2 rewrite length_map in H6; trivial.\n\nsubst l' s l'0; simpl; apply List_eq_rest; trivial;\napply IHl; trivial.\n\nabsurd (f=f); trivial.\n\nsubst f0 l'0 g l0; assert (forall s', In s' l' -> Acc rpo s').\nintros s' In_s'; apply IH'; trivial; apply (rpo_subterm _ _ lt_t_s); simpl; trivial.\n\nrewrite <- (projection_list_of_SN_terms l' H); \napply (IH (f,(build_list_of_SN_terms l' H)));\nsimpl; elim (F.eq_symbol_dec f f); intro eq1.\nrewrite H2; inversion H4; subst l'0 l0; assert (Acc rpo a).\napply in_sn_sn with l; refine (in_permut_in a _ (list_permut_sym H1)); \nleft; trivial.\nassert (forall t, In t lg -> Acc rpo t).\nintros; apply in_sn_sn with l; refine (in_permut_in _ _ (list_permut_sym H1));\nright; apply in_or_app; left; trivial.\nassert (forall t, In t ls -> Acc rpo t).\nintros; apply H; refine (in_permut_in _ _ (list_permut_sym H0));\napply in_or_app; left; trivial.\nassert (forall t, In t lc -> Acc rpo t).\nintros; apply H; refine (in_permut_in _ _ (list_permut_sym H0));\napply in_or_app; right; trivial.\napply (List_mul_rest (mk_sn a H5) (build_list_of_SN_terms lg H6)\n(build_list_of_SN_terms ls H7) (build_list_of_SN_terms lc H8)).\nrewrite map_app; do 3 rewrite projection_list_of_SN_terms; trivial.\nsimpl; rewrite map_app; do 2 rewrite projection_list_of_SN_terms; trivial.\nintros b In_b; destruct b; elim (H3 tt0).\nintros x H'; elim H'; clear H'; intros In_x H'; \nelim In_x; clear In_x; intro In_x.\nsubst x; exists (mk_sn a H5); intuition.\nassert (exists a', In a' (build_list_of_SN_terms lg H6) /\\ tt a' = x).\ngeneralize lg H6 In_x; clear lg H1 H3 H6 In_x; induction lg.\ncontradiction.\nintros H6 In_x; elim In_x; clear In_x; intro In_x; simpl.\nsubst a0; econstructor; intuition.\nelim (IHlg (fun (t : term) (H1 : In t lg) => H6 t (or_intror (a0 = t) H1)) In_x);\nintros a' H''; elim H''; clear H''; intros In_a' H''.\nexists a'; split; trivial; right; trivial.\nelim H9; clear H9; \nintros a' H9; elim H9; clear H9; \nintros In_a' H9; exists a'; split;\n[ right | unfold rpo_rest; simpl; rewrite H9 ]; trivial.\nclear H0 H3; induction ls.\ncontradiction.\nelim In_b; clear In_b; intro In_b;\n[ left; injection In_b; trivial | right; refine (IHls _ In_b)].\n\nabsurd (f=f); trivial.\nQed.\n\n(** ** Main theorem: when the precedence is well-founded, so is the rpo. \n*)\n\nLemma wf_rpo : well_founded prec -> well_founded rpo.\nProof.\nintro wf_prec;\nunfold well_founded; intro t; pattern t; apply term_rec3; clear t.\nintro v; apply Acc_intro; intros t lt_t_s; inversion lt_t_s.\nintros f l Acc_subterm;\nrewrite <- (projection_list_of_SN_terms l Acc_subterm). \napply acc_build; trivial.\nQed.\n\n(** ** RPO is compatible with the instanciation by a substitution. \n*)\n\nLemma rpo_subst :\n  forall t s, rpo s t -> \n  forall sigma, rpo (apply_subst sigma s) (apply_subst sigma t).\nProof.\nintro t; pattern t; apply term_rec3; clear t.\nintros v s H; inversion H.\nintros f l IHl s; simpl; pattern s; apply term_rec3; clear s.\n(* case s = Var v; rpo by Subterm *)\nintros v R; inversion R as [ f' l' s' t In_t_l R' H1 H2 | | | ]; subst; \nintro sigma; simpl; apply Subterm with (apply_subst sigma t).\napply in_in_map; trivial.\ninversion R' as [ s' R'' | s' t' R'' ]; subst; simpl;\n[ apply Eq| apply Lt; refine (IHl _ In_t_l _ R'' sigma) ].\n(* case s = Term f l *)\nintros g k IHl' R sigma; \ninversion R as [ f' l' s' t In_t_l R' H1 H2 \n                       | f' g' l' l'' R' R'' H1 H2\n                       | g' l' k' f_lex Rlex R' H2 H3\n                       | g' l' k' f_mul Rmul R' H2 ]; subst.\n(* case Subterm *)\napply Subterm with (apply_subst sigma t).\napply in_in_map; trivial.\ninversion R' as [ s' R'' | s' t' R'' ]; subst; \n[ apply Eq | apply Lt; apply IHl; trivial ].\n(* case Top_gt *)\nsimpl; apply Top_gt; trivial.\nintros s' In_s'; elim (in_map_in _ s' _ In_s'); intros s [H1 H2]; subst.\napply IHl'; trivial; apply R''; trivial.\n(* case Top_eq_lex *)\nsimpl; apply Top_eq_lex; trivial.\ngeneralize l Rlex IHl; clear l R Rlex R' IHl IHl';\ninduction k as [ | s' k ]; intros l Rlex IHl; inversion Rlex; subst; simpl.\napply List_gt; [ apply IHl; trivial; left | do 2 (rewrite length_map) ]; trivial.\napply List_eq; apply IHk; trivial;\nintros; apply IHl; trivial; right; trivial.\nintros s' In_s'; elim (in_map_in _ s' _ In_s'); \nintros s [In_s H1]; subst; apply IHl'; trivial;\napply rpo_trans with (Term f k); trivial;\napply Subterm with s; trivial; apply Eq.\n(* case Top_eq_mul *)\nsimpl; apply Top_eq_mul; trivial.\ninversion Rmul as [ a lg ls lc l0 k0 Pk Pl H]; subst.\napply (List_mul (apply_subst sigma a) (map (apply_subst sigma) lg)\n(map (apply_subst sigma) ls) (map (apply_subst sigma) lc)).\nrewrite <- map_app; apply list_permut_map; trivial.\nrewrite <- map_app;\ngeneralize (list_permut_map (apply_subst sigma) Pl); simpl; trivial.\nintros b' In_b'; elim (in_map_in _ b' _ In_b'); \nintros b [In_b H1]; subst; elim (H b In_b); intros a' [ In_a' H1 ];\nexists (apply_subst sigma a'); split.\ngeneralize (in_in_map (apply_subst sigma) _ _ In_a'); simpl; trivial.\napply IHl; trivial;\napply in_permut_in with (a :: lg ++ lc).\nelim In_a'; clear In_a'; intro In_a'; subst.\nleft; trivial.\nright; apply in_or_app; left; trivial.\napply list_permut_sym; trivial.\nQed.\n\n(** ** RPO is compatible with adding context. \n*)\n\nLemma rpo_add_context :\n forall p ctx s t, rpo s t -> is_a_pos ctx p = true -> \n  rpo (replace_at_pos ctx s p) (replace_at_pos ctx t p).\nProof.\nintro p; induction p as [ | i p ]; intros ctx s t R H; trivial;\ndestruct ctx as [ v | f l ].\ndiscriminate.\nassert (Status : forall g, g = f -> status g = status f).\nintros; subst; trivial.\ndo 2 (rewrite replace_at_pos_unfold);\ndestruct (status f); generalize (Status f (refl_equal _)); clear Status; \nintro Status.\napply Top_eq_lex; trivial.\ngeneralize l i H; clear l i H; induction l as [ | u1 l ]; intros i H.\ndestruct i; discriminate.\ndestruct i; simpl in H; simpl.\napply List_gt; trivial; apply IHp; trivial.\napply List_eq; apply IHl; trivial.\nintros s' In_s'; \nassert (H' : exists t', In t' (replace_at_pos_list l t i p) /\\ rpo_eq s' t').\ngeneralize l i H In_s'; clear l i H In_s'; \ninduction l as [ | u1 l ]; intros i H In_s'.\ndestruct i; discriminate.\ndestruct i; elim In_s'; clear In_s'; intro In_s'; subst.\nexists (replace_at_pos u1 t p); split; [ left | apply Lt; apply IHp ]; trivial.\nexists s'; split; [ right; trivial | apply Eq ].\nexists s'; split; [ left; trivial | apply Eq ].\nelim (IHl i H In_s'); intros t' [H1 H2]; exists t'; split; [ right | idtac ]; trivial.\nelim H'; clear H'; intros t' [H1 H2]; apply Subterm with t'; trivial.\n\napply Top_eq_mul; trivial.\nassert (H' : exists l1, exists ui, exists l2, l = l1 ++ ui :: l2 /\\ length l1 = i).\ngeneralize i H; clear i H; induction l as [ | u1 l ]; intros i H.\ndestruct i; discriminate.\ndestruct i as [ | i ].\nexists (nil (A:= term)); exists u1; exists l; split; trivial.\nelim (IHl i H); intros l1 [ ui [ l2 [ H1 H2]]].\nexists (u1 :: l1); exists ui; exists l2; split; subst; trivial.\nelim H'; clear H';  intros l1 [ ui [ l2 [ H1 H' ]]]; subst l.\ndo 2 (rewrite replace_at_pos_list_replace_at_pos_in_subterm; trivial).\napply (List_mul (replace_at_pos ui t p) nil (replace_at_pos ui s p :: nil) \n          (l1 ++ l2)).\nsimpl; apply list_permut_sym; \napply list_permut_add_cons_inside; apply list_permut_refl.\nsimpl; apply list_permut_sym; \napply list_permut_add_cons_inside; apply list_permut_refl.\nintros b In_b; elim In_b; clear In_b; intro In_b; subst.\nexists (replace_at_pos ui t p); split; [ left | apply IHp ]; trivial.\ninduction l1 as [ | u1 l1 ]; trivial; apply IHl1; trivial.\ncontradiction.\nQed.\n\nEnd Make.\n\n\n\n\n\n\n\n\n", "meta": {"author": "coq-community", "repo": "hydra-battles", "sha": "2d211e0b5030d5f77aaaf6366b01fc64ed998c61", "save_path": "github-repos/coq/coq-community-hydra-battles", "path": "github-repos/coq/coq-community-hydra-battles/hydra-battles-2d211e0b5030d5f77aaaf6366b01fc64ed998c61/theories/ordinals/rpo/rpo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.884039278690883, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6895443609246504}}
{"text": "Require Import init.\n\nRequire Import set_base.\nRequire Import set_type.\nRequire Export relation.\n\n#[universes(template)]\nRecord set_function_type (U V : Type) := make_set_function {\n    domain : U → Prop;\n    set_function : set_type domain → V;\n}.\n\nArguments make_set_function {U} {V}.\nArguments domain {U} {V}.\nArguments set_function {U} {V}.\n\nNotation \"f ⟨ x ⟩\" := (set_function f x) (at level 69).\n\n(* begin hide *)\nSection FunctionOrder.\n\nLocal Open Scope set_scope.\n(* end hide *)\nContext {U V : Type}.\nDefinition func_le (f g : set_function_type U V) :=\n    domain f ⊆ domain g ⋏ λ sub,\n        ∀ x : set_type (domain f),\n            f⟨x⟩ = g⟨[[x|]|sub [x|] [|x]]⟩.\n\nGlobal Instance func_le_refl : Reflexive func_le.\nProof.\n    split.\n    intros f.\n    split with (refl _).\n    intros [x x_in]; cbn.\n    apply f_equal.\n    rewrite set_type_eq2.\n    reflexivity.\nQed.\n\nGlobal Instance func_le_antisym : Antisymmetric func_le.\nProof.\n    split.\n    intros f g [f_sub_g fg] [g_sub_f gf]; cbn in *.\n    pose proof (antisym f_sub_g g_sub_f) as set_eq.\n    destruct f as [f_dom f], g as [g_dom g]; cbn in *.\n    subst g_dom.\n    apply f_equal.\n    apply functional_ext.\n    intros x.\n    rewrite fg.\n    apply f_equal.\n    apply set_type_simpl.\nQed.\n\nGlobal Instance func_le_trans : Transitive func_le.\nProof.\n    split.\n    intros f g h [f_sub_g fg] [g_sub_h gh]; cbn in *.\n    split with (trans f_sub_g g_sub_h); cbn.\n    intros x.\n    rewrite fg.\n    rewrite gh; cbn.\n    apply f_equal.\n    rewrite set_type_eq2.\n    reflexivity.\nQed.\n(* begin hide *)\n\nEnd FunctionOrder.\n(* end hide *)\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Set/zorn_unary_function.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6895443564034994}}
{"text": "Require Import MyTactics.\nRequire Export PreLattice.\nRequire Export Ordinals.\n\n(** * Ascending transfinite chains. *)\nModule Ascending.\n\n(** (Countably) Transfinite iteration of a function. *)\nFixpoint trans_iter {T leq} `{JoinCompletePreLattice T leq}\n         (f: T -> T) (o: Ord) (zero : T) : T :=\n  match o with\n    | O_Ord => zero\n    | S_Ord o' => f (trans_iter f o' zero)\n    | lim_Ord os =>\n      let (sup, _) :=\n          (join_complete (fun t : T => exists n, t = trans_iter f (os n) zero))\n      in sup\n  end.\n\nLemma trans_iter_monotone_zero {T leq} `{JoinCompletePreLattice T leq}\n      (f: T -> T) (o: Ord):\n  monotone f ->\n  monotone (trans_iter f o).\nProof.\nintros Hf x y Hxy. induction o.\n* assumption.\n* simpl. apply Hf. assumption.\n* simpl.\n  destruct\n    (join_complete\n       (fun t : T => exists n : nat, t = trans_iter f (o n) x))\n    as [xsup [HxUB HxLUB]].\n  destruct\n    (join_complete\n       (fun t : T => exists n : nat, t = trans_iter f (o n) y))\n    as [ysup [HyUB HyLUB]].\n  apply HxLUB.\n  intros t [n Heq]. subst t.\n  transitivity (trans_iter f (o n) y); trivial.\n  apply HyUB. eauto.\nQed.\n\nDefinition trans_iteration_chain {T leq} `{JoinCompletePreLattice T leq}\n           (zero: T) (f: T -> T) :=\n  fun x => exists o, equiv x (trans_iter f o zero).\n\nLemma trans_iter_ascending_S {T leq} `{JoinCompletePreLattice T leq} :\n  forall zero (f: T -> T),\n    monotone f ->\n    leq zero (f zero) ->\n    forall o,\n      leq (trans_iter f o zero) (trans_iter f (S_Ord o) zero).\nProof.\nintros zero f Hf Hzero o. induction o; simpl; auto.\n* destruct\n    (join_complete\n       (fun t : T => exists n : nat, t = trans_iter f (o n) zero))\n    as [sup [HUB HLUB]].\n  apply HLUB. intros t [n Heq]; subst t.\n  transitivity (trans_iter f (S_Ord (o n)) zero); trivial.\n  simpl. apply Hf. apply HUB. eauto.\nQed.\n\nLemma trans_iter_lower_bound {T leq} `{JoinCompletePreLattice T leq}:\n  forall zero (f: T -> T) (o: Ord),\n    leq zero (f zero) ->\n    monotone f ->\n    leq zero (trans_iter f o zero).\nProof.\nintros zero f o Hzero Hf. induction o; simpl in *.\n* reflexivity.\n* transitivity (trans_iter f o zero); trivial.\n  apply trans_iter_ascending_S; auto.\n* destruct\n    (join_complete\n       (fun t : T => exists n : nat, t = trans_iter f (o n) zero))\n    as [sup [HUB HLUB]].\n  transitivity (trans_iter f (o 0) zero); trivial.\n  apply HUB. eauto.\nQed.\n\nLemma trans_iter_S_pred {T leq} `{JoinCompletePreLattice T leq} :\n  forall zero (f : T -> T),\n    leq zero (f zero) ->\n    monotone f ->\n    forall o t,\n      leq (trans_iter f (S_Ord (ord_pred o t)) zero) (trans_iter f o zero).\nProof.\ninduction o; simpl in *.\n- destruct t.\n- destruct t as [t | t]. reflexivity.\n  transitivity (trans_iter f o zero). trivial.\n  apply trans_iter_ascending_S; auto.\n- destruct t as [n Hn].\n  destruct\n    (join_complete\n       (fun t0 : T => exists n : nat, t0 = trans_iter f (o n) zero))\n    as [sup [HUB HLUB]].\n  transitivity (trans_iter f (o n) zero); trivial.\n  apply HUB. eauto.\nQed.\n\nLemma trans_iter_monotone {T leq} `{JoinCompletePreLattice T leq}:\n  forall zero (f: T -> T),\n    leq zero (f zero) ->\n    monotone f ->\n    monotone (fun o => trans_iter f o zero).\nProof.\nintros zero f Hzero Hf o1. induction o1; intros o2 Hord; simpl in *.\n* apply trans_iter_lower_bound; auto.\n* destruct Hord as [t Hord].\n  transitivity (trans_iter f (S_Ord (ord_pred o2 t)) zero).\n  + simpl. apply Hf. auto.\n  + apply trans_iter_S_pred; auto.\n* destruct\n    (join_complete\n       (fun t0 : T => exists n : nat, t0 = trans_iter f (o n) zero))\n    as [sup [HUB HLUB]].\n  apply HLUB. intros t [n Heq]; subst t. auto.\nQed.\n\nLemma trans_iter_upper_bound_f {T leq} `{JoinCompletePreLattice T leq} :\n  forall zero (f: T -> T),\n    leq zero (f zero) ->\n    monotone f ->\n    forall b,\n      leq zero (f b) ->\n      (forall o, leq (trans_iter f o zero) b) ->\n      forall o, leq (trans_iter f o zero) (f b).\nProof.\nintros zero f Hzero Hf b Hb Hleq o. induction o.\n* assumption.\n* simpl. auto.\n* simpl.\n  destruct\n    (join_complete\n       (fun t : T => exists n : nat, t = trans_iter f (o n) zero))\n    as [sup [HUB HLUB]].\n  apply HLUB. intros t [n Heq]; subst t. auto.\nQed.\n\nLemma trans_iteration_chain_upper_bound_f {T leq}\n      `{JoinCompletePreLattice T leq} :\n  forall zero (f: T -> T),\n    leq zero (f zero) ->\n    monotone f ->\n  forall b,\n    leq zero b ->\n    is_upper_bound (trans_iteration_chain zero f) b ->\n    is_upper_bound (trans_iteration_chain zero f) (f b).\nProof.\nintros zero f Hzero Hf b Hb HUB x [o Hx]. rewrite Hx.\napply trans_iter_upper_bound_f; trivial.\n* transitivity (f zero); trivial. apply Hf. trivial.\n* intro o'. apply HUB. exists o'. reflexivity.\nQed.\n\nLemma trans_iteration_chain_upper_bound_im_f {T leq}\n      `{JoinCompletePreLattice T leq} :\n  forall zero (f: T -> T),\n    monotone f ->\n    forall b,\n      is_upper_bound (trans_iteration_chain zero f) b ->\n      is_upper_bound (im f (trans_iteration_chain zero f)) b.\nProof.\nintros zero f Hf b HUB. intros y [x [[o Hx] Heq]]. rewrite Heq.\napply HUB. exists (S_Ord o).\ntransitivity (f (trans_iter f o zero)).\napply monotone_equiv_compat; auto.\nreflexivity.\nQed.\n\nLemma fixed_point_is_upper_bound_chain {T leq} `{JoinCompletePreLattice T leq} :\n  forall zero (f: T -> T),\n    monotone f ->\n    forall x,\n      leq zero x ->\n      is_fixed_point f x ->\n      is_upper_bound (trans_iteration_chain zero f) x.\nProof.\nintros zero f Hf x Hzerox Hx y [o Hy].\ngeneralize dependent y. induction o; intros y Hy.\n* rewrite Hy. assumption.\n* rewrite Hy. simpl.\n  unfold is_fixed_point in Hx. rewrite <- Hx.\n  apply Hf. apply IHo. reflexivity.\n* rewrite Hy. simpl.\n  destruct\n    (join_complete\n       (fun t : T => exists n : nat, t = trans_iter f (o n) zero))\n    as [sup [HUB HLUB]].\n  apply HLUB. intros t [n Heq]; subst t.\n  apply (H1 n). reflexivity.\nQed.\n\nLemma fixed_point_above_trans_iter {T leq} `{JoinCompletePreLattice T leq} :\n  forall zero (f: T -> T),\n    monotone f ->\n    forall x,\n      leq zero x ->\n      is_fixed_point f x ->\n      forall o,\n      leq (trans_iter f o zero) x.\nProof.\nintros zero f Hf x Hzerox Hx o.\napply (fixed_point_is_upper_bound_chain zero f Hf x Hzerox Hx).\nexists o. reflexivity.\nQed.\n\nEnd Ascending.\n\n(** * Descending transfinite chains. *)\nModule Descending.\n\n(** (Countably) Transfinite iteration of a function. *)\nFixpoint trans_iter {T leq} `{MeetCompletePreLattice T leq}\n         (f: T -> T) (o: Ord) (zero : T) : T :=\n  match o with\n    | O_Ord => zero\n    | S_Ord o' => f (trans_iter f o' zero)\n    | lim_Ord os =>\n      let (inf, _) :=\n          (meet_complete (fun t : T => exists n, t = trans_iter f (os n) zero))\n      in inf\n  end.\n\nLemma trans_iter_monotone_zero {T leq} `{MeetCompletePreLattice T leq}\n      (f: T -> T) (o: Ord):\n  monotone f ->\n  monotone (trans_iter f o).\nProof.\nintros Hf x y Hxy. induction o.\n* assumption.\n* simpl. apply Hf. assumption.\n* simpl.\n  destruct\n    (meet_complete\n       (fun t : T => exists n : nat, t = trans_iter f (o n) x))\n    as [xinf [HxLB HxGLB]].\n  destruct\n    (meet_complete\n       (fun t : T => exists n : nat, t = trans_iter f (o n) y))\n    as [yinf [HyLB HyGLB]].\n  apply HyGLB.\n  intros t [n Heq]. subst t.\n  transitivity (trans_iter f (o n) x); trivial.\n  apply HxLB. eauto.\nQed.\n\nDefinition trans_iteration_chain {T leq} `{MeetCompletePreLattice T leq}\n           (zero: T) (f: T -> T) :=\n  fun x => exists o, equiv x (trans_iter f o zero).\n\nLemma trans_iter_descending_S {T leq} `{MeetCompletePreLattice T leq} :\n  forall zero (f: T -> T),\n    monotone f ->\n    leq (f zero) zero ->\n    forall o,\n      leq (trans_iter f (S_Ord o) zero) (trans_iter f o zero).\nProof.\nintros zero f Hf Hzero o. induction o; simpl; auto.\n* destruct\n    (meet_complete\n       (fun t : T => exists n : nat, t = trans_iter f (o n) zero))\n    as [inf [HLB HGLB]].\n  apply HGLB. intros t [n Heq]; subst t.\n  transitivity (trans_iter f (S_Ord (o n)) zero); trivial.\n  simpl. apply Hf. apply HLB. eauto.\nQed.\n\nLemma trans_iter_upper_bound {T leq} `{MeetCompletePreLattice T leq}:\n  forall zero (f: T -> T) (o: Ord),\n    leq (f zero) zero ->\n    monotone f ->\n    leq (trans_iter f o zero) zero.\nProof.\nintros zero f o Hzero Hf. induction o; simpl in *.\n* reflexivity.\n* transitivity (trans_iter f o zero); trivial.\n  apply trans_iter_descending_S; auto.\n* destruct\n    (meet_complete\n       (fun t : T => exists n : nat, t = trans_iter f (o n) zero))\n    as [inf [HLB HGLB]].\n  transitivity (trans_iter f (o 0) zero); trivial.\n  apply HLB. eauto.\nQed.\n\nLemma trans_iter_S_pred {T leq} `{MeetCompletePreLattice T leq} :\n  forall zero (f : T -> T),\n    leq (f zero) zero ->\n    monotone f ->\n    forall o t,\n      leq (trans_iter f o zero) (trans_iter f (S_Ord (ord_pred o t)) zero).\nProof.\ninduction o; simpl in *.\n- destruct t.\n- destruct t as [t | t]. reflexivity.\n  transitivity (trans_iter f o zero); trivial.\n  apply trans_iter_descending_S; auto.\n- destruct t as [n Hn].\n  destruct\n    (meet_complete\n       (fun t0 : T => exists n : nat, t0 = trans_iter f (o n) zero))\n    as [inf [HLB HGLB]].\n  transitivity (trans_iter f (o n) zero); trivial.\n  apply HLB. eauto.\nQed.\n\nLemma trans_iter_anti_monotone {T leq} `{MeetCompletePreLattice T leq}:\n  forall zero (f: T -> T),\n    leq (f zero) zero ->\n    monotone f ->\n    anti_monotone (fun o => trans_iter f o zero).\nProof.\nintros zero f Hzero Hf o1 o2.\ngeneralize dependent o1.\ninduction o2; intros o1 Hord; simpl in *.\n* apply trans_iter_upper_bound; auto.\n* destruct Hord as [t Hord].\n  transitivity (trans_iter f (S_Ord (ord_pred o1 t)) zero).\n  + apply trans_iter_S_pred; auto.\n  + simpl. apply Hf. auto.\n* destruct\n    (meet_complete\n       (fun t0 : T => exists n : nat, t0 = trans_iter f (o n) zero))\n    as [inf [HLB HGLB]].\n  apply HGLB. intros t [n Heq]; subst t. unfold flip in *. auto.\nQed.\n\nLemma trans_iter_lower_bound_f {T leq} `{MeetCompletePreLattice T leq} :\n  forall zero (f: T -> T),\n    leq (f zero) zero ->\n    monotone f ->\n    forall b,\n      leq (f b) zero ->\n      (forall o, leq b (trans_iter f o zero)) ->\n      forall o, leq (f b) (trans_iter f o zero).\nProof.\nintros zero f Hzero Hf b Hb Hleq o. induction o.\n* assumption.\n* simpl. auto.\n* simpl.\n  destruct\n    (meet_complete\n       (fun t : T => exists n : nat, t = trans_iter f (o n) zero))\n    as [inf [HLB HGLB]].\n  apply HGLB. intros t [n Heq]; subst t. auto.\nQed.\n\nLemma trans_iteration_chain_lower_bound_f {T leq}\n      `{MeetCompletePreLattice T leq} :\n  forall zero (f: T -> T),\n    leq (f zero) zero ->\n    monotone f ->\n  forall b,\n    leq b zero ->\n    is_lower_bound (trans_iteration_chain zero f) b ->\n    is_lower_bound (trans_iteration_chain zero f) (f b).\nProof.\nintros zero f Hzero Hf b Hb HUB x [o Hx]. rewrite Hx.\napply trans_iter_lower_bound_f; trivial.\n* transitivity (f zero); trivial. apply Hf. trivial.\n* intro o'. apply HUB. exists o'. reflexivity.\nQed.\n\nLemma trans_iteration_chain_lower_bound_im_f {T leq}\n      `{MeetCompletePreLattice T leq} :\n  forall zero (f: T -> T),\n    monotone f ->\n    forall b,\n      is_lower_bound (trans_iteration_chain zero f) b ->\n      is_lower_bound (im f (trans_iteration_chain zero f)) b.\nProof.\nintros zero f Hf b HLB. intros y [x [[o Hx] Heq]]. rewrite Heq.\napply HLB. exists (S_Ord o).\ntransitivity (f (trans_iter f o zero)).\napply monotone_equiv_compat; auto.\nreflexivity.\nQed.\n\nLemma fixed_point_is_lower_bound_chain {T leq} `{MeetCompletePreLattice T leq} :\n  forall zero (f: T -> T),\n    monotone f ->\n    forall x,\n      leq x zero ->\n      is_fixed_point f x ->\n      is_lower_bound (trans_iteration_chain zero f) x.\nProof.\nintros zero f Hf x Hzerox Hx y [o Hy].\ngeneralize dependent y. induction o; intros y Hy.\n* rewrite Hy. assumption.\n* rewrite Hy. simpl.\n  unfold is_fixed_point in Hx. rewrite <- Hx.\n  apply Hf. apply IHo. reflexivity.\n* rewrite Hy. simpl.\n  destruct\n    (meet_complete\n       (fun t : T => exists n : nat, t = trans_iter f (o n) zero))\n    as [inf [HLB HGLB]].\n  apply HGLB. intros t [n Heq]; subst t.\n  apply (H1 n). reflexivity.\nQed.\n\nLemma fixed_point_below_trans_iter {T leq} `{MeetCompletePreLattice T leq} :\n  forall zero (f: T -> T),\n    monotone f ->\n    forall x,\n      leq x zero ->\n      is_fixed_point f x ->\n      forall o,\n      leq x (trans_iter f o zero).\nProof.\nintros zero f Hf x Hzerox Hx o.\napply (fixed_point_is_lower_bound_chain zero f Hf x Hzerox Hx).\nexists o. reflexivity.\nQed.\n\nEnd Descending.\n", "meta": {"author": "esope", "repo": "robustness_coq", "sha": "149b3b60f5f018237ad5371212cdb1e9e4603fdf", "save_path": "github-repos/coq/esope-robustness_coq", "path": "github-repos/coq/esope-robustness_coq/robustness_coq-149b3b60f5f018237ad5371212cdb1e9e4603fdf/TransfiniteChains.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6895382490756111}}
{"text": "Require Import Arith Nat FunctionalExtensionality Omega.\nRequire Import Tactics.Tactics.\n\n(** Simple formalization of an array. *)\nSection Array.\n  Definition array : Set := nat -> nat.\n\n  Definition aempty : array := fun _ => 0.\n\n  Definition getv (a : array) (k : nat) := a k.\n\n  Definition setv (a : array) (k : nat) (v : nat) : array :=\n    fun k' => if k' =? k then v else a k'.\n\n  Definition swap (a : array) (i j : nat) : array :=\n    let (x, y) := (getv a i, getv a j)\n    in setv (setv a i y) j x.\n\n  Hint Unfold getv setv swap.\n\n  Lemma getv_eq :\n    forall a i v, getv (setv a i v) i = v.\n  Proof.\n    intros. unfold getv. unfold setv.\n    rewrite <- beq_nat_refl. auto.\n  Qed.\n\n  Lemma getv_ne :\n    forall a i j v, j <> i -> getv (setv a i v) j = getv a j.\n  Proof.\n    intros. unfold getv. unfold setv.\n    rewrite <- Nat.eqb_neq in H.\n    rewrite H. reflexivity.\n  Qed.\n\n  Lemma swap_eq :\n    forall a i, swap a i i = a.\n  Proof.\n    intros.\n    apply functional_extensionality.\n    intros.\n    destruct (x =? i) eqn:H.\n    - unfold swap. unfold setv. unfold getv. rewrite H.\n      apply beq_nat_true in H. auto.\n    - unfold swap. unfold setv. unfold getv. rewrite H. auto.\n  Qed.\n\n  Lemma swap_get1 :\n    forall a i j, getv (swap a i j) i = getv a j.\n  Proof.\n    intros. unfold swap. unfold getv. unfold setv.\n    rewrite <- beq_nat_refl.\n    destruct (i =? j) eqn:H.\n    apply beq_nat_true in H. subst. auto. auto.\n  Qed.\n\n  Lemma swap_get2 :\n    forall a i j, getv (swap a i j) j = getv a i.\n  Proof.\n    intros. unfold swap. unfold getv. unfold setv.\n    rewrite <- beq_nat_refl.\n    auto.\n  Qed.\n\n  Lemma swap_get3 :\n    forall a i j k, k <> i -> k <> j -> getv (swap a i j) k = getv a k.\n  Proof.\n    intros. unfold swap. unfold getv. unfold setv.\n    rewrite <- Nat.eqb_neq in H. rewrite <- Nat.eqb_neq in H0.\n    rewrite H. rewrite H0. reflexivity.\n  Qed.\nEnd Array.\n\n(* Some useful lemmas about log2 and division. *)\n\nLemma log2_div2 :\n  forall (k n : nat),\n    k > 0 -> log2 k = S n -> log2 (k/2) = n.\nProof.\n  intros.\n  assert (2 ^ (S n) <= k < 2 ^ (S (S n))).\n  { rewrite <- H0. apply Nat.log2_spec. auto. }\n  destruct H1.\n  apply Nat.log2_unique. omega.\n  split.\n  rewrite <- Nat.add_1_r with n in H1.\n  rewrite Nat.pow_add_r in H1. simpl in H1.\n  apply (Nat.div_le_mono _ _ 2) in H1.\n  rewrite Nat.div_mul in H1. auto. auto. auto.\n  rewrite <- Nat.add_1_r with (S n) in H2.\n  rewrite Nat.pow_add_r in H2. simpl in H2.\n  apply Nat.div_lt_upper_bound. omega.\n  simpl. omega.\nQed.\n\nLemma div2_ge_1 :\n  forall (n : nat), 2 <= n -> 1 <= n/2.\nProof.\n  intros.\n  assert (2/2 <= n/2). { apply Nat.div_le_mono. omega. auto. }\n  simpl in *. auto.\nQed.\n\nLemma div2_ge_2 :\n  forall (n : nat), 4 <= n -> 2 <= n/2.\nProof.\n  intros.\n  assert (4/2 <= n/2). { apply Nat.div_le_mono. omega. auto. }\n  simpl in *. auto.\nQed.\n\nLemma div2_le_n :\n  forall (n : nat), n/2 <= n.\nProof.\n  intros.\n  assert (n/2 <= n/1). { apply Nat.div_le_compat_l. omega. }\n  rewrite Nat.div_1_r in H.\n  auto.\nQed.\n\nLemma div2_lt_n :\n  forall (n : nat), n > 0 -> n/2 < n.\nProof.\n  intros.\n  assert (n/2 <= n/1). { apply Nat.div_le_compat_l. omega. }\n  rewrite Nat.div_1_r in H0.\n  apply le_lt_or_eq in H0. destruct H0.\n  - apply H0.\n  - assert (2*(n/2) <= n). { apply Nat.mul_div_le. omega. }\n    rewrite H0 in H1. omega.\nQed.\n\nLemma div2_eq_n :\n  forall (n : nat), n/2 = n -> n = 0.\nProof.\n  intros.\n  assert (2*(n/2) <= n). { apply Nat.mul_div_le. omega. }\n  rewrite H in H0. omega.\nQed.\n\nLemma div2_mul2_vals :\n  forall (n : nat), n = 2*(n/2) \\/ n = 2*(n/2)+1.\nProof.\n  intros. remember (n/2) as k.\n  assert (2*k <= n). { rewrite Heqk. apply Nat.mul_div_le. omega. }\n  assert (n mod 2 = n - 2*(n/2)). { apply Nat.mod_eq. omega. }\n  rewrite <- Heqk in H0.\n  assert (n mod 2 < 2). { apply Nat.mod_upper_bound. omega. }\n  rewrite H0 in H1.\n  assert (n - 2*k = 0 \\/ n - 2*k = 1). { omega. }\n  destruct H2; omega.\nQed.\n\nLemma div2_neq_n :\n  forall (n k : nat), k <> 2*n -> k <> 2*n+1 -> k/2 <> n.\nProof.\n  intros. intro contra.\n  assert (k = 2 * (k / 2) \\/ k = 2 * (k / 2) + 1). { apply div2_mul2_vals. }\n  destruct H1; rewrite contra in H1; auto.\nQed.\n\nLemma div2_mul2_le :\n  forall (n : nat), 2*(n/2) <= n.\nProof.\n  intros.\n  apply Nat.mul_div_le. omega.\nQed.\n\nLemma mul2_div2 :\n  forall (n : nat), 2*n/2 = n.\nProof.\n  intros.\n  rewrite Nat.mul_comm, Nat.div_mul; auto.\nQed.\n\nLemma mul2_S_div2 :\n  forall (n : nat), (2*n+1)/2 = n.\nProof.\n  intros. symmetry.\n  eapply Nat.div_unique. auto. reflexivity.\nQed.\n\nHint Resolve div2_ge_1 div2_ge_2.\nHint Resolve div2_lt_n.\nHint Resolve div2_le_n.\nHint Resolve div2_eq_n.\nHint Resolve div2_neq_n.\nHint Resolve div2_mul2_le.\nHint Resolve mul2_div2.\nHint Resolve mul2_S_div2.\nHint Resolve gt_le_S.\nHint Resolve Nat.le_trans.\nHint Resolve Nat.lt_le_incl.\n\n(** Heap *)\n\n(** Definition of heap. *)\nDefinition heap : Set := array * nat.\n\nDefinition heap_array (h : heap) : array :=\n  match h with\n  | (a, n) => a\n  end.\n\nDefinition heap_n (h : heap) : nat :=\n  match h with\n  | (a, n) => n\n  end.\n\nDefinition extend_heap (h : heap) (v : nat) : heap :=\n  (setv (heap_array h) (S (heap_n h)) v, S (heap_n h)).\n\nDefinition shrink_heap (h : heap) : heap :=\n  match h with\n  | (a, 0) => (a, 0)\n  | (a, S n) => (setv (swap a 1 (S n)) (S n) 0, n)\n  end.\n\nDefinition Heap (h : heap) : Prop :=\n     (forall (i : nat), 2 <= i ->\n       getv (heap_array h) i <= getv (heap_array h) (i/2))\n  /\\ (forall (i : nat), i > heap_n h -> getv (heap_array h) i = 0).\n\nFixpoint heap_upify (h : heap) (k height : nat) : heap :=\n  match height with\n  | 0 => h\n  | S height' =>\n      if getv (heap_array h) (k/2) <? getv (heap_array h) (k)\n        then heap_upify (swap (heap_array h) k (k/2), heap_n h) (k/2) height'\n        else h\n  end.\n\nFixpoint heap_downify (h : heap) (k height : nat) : heap :=\n  match height with\n  | 0 => h\n  | S height' =>\n      let\n        ind := if getv (heap_array h) (2*k) <? getv (heap_array h) (2*k+1)\n                 then 2*k+1\n                 else 2*k\n      in\n        if getv (heap_array h) k <? getv (heap_array h) ind\n          then heap_downify (swap (heap_array h) k ind, heap_n h) ind height'\n          else h\n  end.\n\nDefinition heap_push (h : heap) (v : nat) : heap :=\n  heap_upify (extend_heap h v) (S (heap_n h)) (log2 (S (heap_n h))).\n\nDefinition heap_pop (h : heap) : (heap * option nat) :=\n  match (heap_n h) with\n  | 0 => (h, None)\n  | S n => (heap_downify (shrink_heap h) 1 (log2 n), Some (heap_array h 1))\n  end.\n\n(* Here comes the proof of verifying heap is correct. *)\n\n(* extending heap will add one element. *)\nLemma extend_heap_n :\n  forall (h : heap) (v : nat),\n    heap_n (extend_heap h v) = S (heap_n h).\nProof.\n  intros. auto.\nQed.\n\n(* shrinking heap will delete one element. *)\nLemma shrink_heap_n :\n  forall (h : heap),\n    heap_n (shrink_heap h) = pred (heap_n h).\nProof.\n  intros. unfold shrink_heap. unfold heap_n.\n  destruct h. destruct n; auto.\nQed.\n\n(* querying element but not last one of extended is same as unextended. *)\nLemma extend_heap_unaffected :\n  forall (i v : nat) (h : heap),\n    i <> S (heap_n h) ->\n    getv (heap_array (extend_heap h v)) i = getv (heap_array h) i.\nProof.\n  intros.\n  simpl.\n  unfold setv. unfold getv.\n  bdestruct (i =? S (heap_n h)); omega.\nQed.\n\n(* h[1] is the maximum element of a heap. *)\nLemma heap_1_maximum_by_height :\n  forall (h : heap) (height : nat),\n    Heap h ->\n      (forall (i : nat), i > 0 -> log2 i = height -> \n         getv (heap_array h) i <= getv (heap_array h) 1).\nProof.\n  intros h height.\n  induction height; intros.\n  - rewrite Nat.log2_null in H1.\n    assert (i = 1). { omega. } subst. auto.\n  - assert (i >= 2). { apply Nat.log2_lt_cancel. rewrite Nat.log2_1. omega. }\n    assert (getv (heap_array h) (i/2) <= getv (heap_array h) 1).\n    { apply IHheight.\n      - auto.\n      - auto.\n      - apply log2_div2. auto. auto. }\n    unfold Heap in H. destruct H. eauto.\nQed.\n\nLemma heap_1_maximum :\n  forall (h : heap),\n    Heap h -> (forall (i : nat), i > 0 -> getv (heap_array h) i <= getv (heap_array h) 1).\nProof.\n  intros.\n  apply heap_1_maximum_by_height with (height := log2 i); auto.\nQed.\n\n(* Now verify heap_push and heap_pop is correct.\n   We need some auxiliary lemmas of heap_upify and heap_downify.\n\n   The main 3 results are:\n     1). The property of heap keeps after heap_push.\n     2). The property of heap keeps after heap_pop.\n     3). heap_pop extracts the maximum element of heap.\n*)\n\nLemma heap_upify_correct :\n  forall (h : heap) (k height : nat),\n    log2 k = height ->\n    k > 0 /\\ k <= heap_n h ->\n    (forall (i : nat),\n       2 <= i /\\ k <> i -> getv (heap_array h) i <= getv (heap_array h) (i/2)) ->\n    (forall (i : nat),\n       4 <= i /\\ i/2 = k -> getv (heap_array h) i <= getv (heap_array h) (k/2)) ->\n    (forall (i : nat),\n       i > heap_n h -> getv (heap_array h) i = 0) ->\n    Heap (heap_upify h k height).\nProof.\n  intros h k height.\n  generalize dependent h.\n  generalize dependent k.\n  induction height.\n  - intros.\n    rewrite Nat.log2_null in H.\n    assert (k = 1). { omega. } clear H H0. subst. simpl.\n    unfold Heap. split. intros. apply H1. omega. apply H3.\n  - intros. unfold heap_upify. fold heap_upify.\n    assert (k > 1 /\\ k <= heap_n h).\n    { split. apply Nat.log2_lt_cancel. rewrite Nat.log2_1. rewrite H. omega.\n      destruct H0. auto. }\n    clear H0. rename H4 into H0.\n    bdestruct (getv (heap_array h) (k/2) <? getv (heap_array h) k).\n    + apply IHheight; clear IHheight.\n      * apply log2_div2; auto. destruct H0. auto.\n      * assert (1 <= k/2). { assert (2 <= k). { omega. } auto. }\n        split; auto.\n        assert (k/2 <= k). { auto. }\n        destruct H0. simpl. eauto.\n      * intros. destruct H5.\n        unfold heap_array. unfold heap_array in H4.\n        { bdestruct (k =? i).\n          - rewrite swap_get1. rewrite swap_get2. auto.\n          - bdestruct (k/2 =? i/2).\n            + rewrite <- H8.\n              rewrite swap_get2. rewrite swap_get3; try omega.\n              apply Nat.lt_le_incl in H4.\n              eapply Nat.le_trans; try apply H4.\n              rewrite H8. auto.\n            + unfold heap_array. rewrite swap_get3; try omega.\n              bdestruct (k =? i/2).\n              * rewrite swap_get1.\n                apply H2. split; auto.\n                assert (2*(i/2) <= i). { auto. } omega.\n              * rewrite swap_get3; eauto. }\n      * intros. destruct H5.\n        unfold heap_array.\n        { bdestruct (k =? i).\n          - assert (2 <= i/2). { auto. }\n            assert (i/2 < i). { apply div2_lt_n. omega. }\n            assert (i/2/2 < i/2). { apply div2_lt_n. omega. }\n            rewrite swap_get1.\n            rewrite swap_get3.\n            apply H1. omega. omega. omega.\n          - assert (2 <= i/2). { auto. }\n            assert (i/2 < i). { apply div2_lt_n. omega. }\n            assert (i <> k/2). { intros contra. subst. apply div2_eq_n in H6. omega. }\n            assert (2*(k/2) <= k). { auto. }\n            assert (4 <= k). { rewrite <- H6 in H11. omega. }\n            assert (2 <= k/2). { rewrite <- H6 in H11. omega. }\n            assert (k/2 < k). { apply div2_lt_n. omega. }\n            assert (k/2/2 < k/2). { apply div2_lt_n. omega. }\n            rewrite swap_get3. rewrite swap_get3.\n            eapply Nat.le_trans. apply H1. omega.\n            rewrite H6. apply H1. split. rewrite <- H6.\n            omega. omega. omega. omega. omega. omega. }\n      * intros. destruct H0. simpl in H5. unfold heap_array.\n        rewrite swap_get3. apply H3. auto. omega.\n        assert (k/2 <= k). { auto. } omega.\n    + unfold Heap. split.\n      * intros.\n        bdestruct (k =? i); auto.\n      * auto.\nQed.\n\nTheorem heap_push_correct :\n  forall (h : heap) (v : nat),\n    Heap h -> Heap (heap_push h v).\nProof.\n  intros.\n  unfold heap_push.\n  apply heap_upify_correct; auto.\n  - split. omega. rewrite extend_heap_n. omega.\n  - intros. destruct H0. unfold Heap in H.\n    assert (getv (heap_array (extend_heap h v)) i = getv (heap_array h) i).\n    { apply extend_heap_unaffected. auto. }\n    rewrite H2.\n    destruct H.\n    bdestruct (i/2 =? S (heap_n h)).\n    + assert (i/2 <= i). { auto. } rewrite H4 in H5.\n      assert (getv (heap_array h) i = 0). { apply H3. auto. }\n      rewrite H6. omega.\n    + assert (getv (heap_array (extend_heap h v)) (i/2) = getv (heap_array h) (i/2)).\n      { apply extend_heap_unaffected.\n        destruct H2. apply H4. }\n    rewrite H5. auto.\n  - intros. destruct H0. unfold Heap in H.\n    assert (i/2 < i). { apply div2_lt_n. omega. } rewrite H1 in H2.\n    destruct H.\n    assert (getv (heap_array (extend_heap h v)) i = getv (heap_array h) i).\n    { apply extend_heap_unaffected. omega. }\n    assert (getv (heap_array h) i = 0).\n    { apply H3. auto. }\n    rewrite H4, H5. omega.\n  - intros. unfold Heap in H. destruct H.\n    rewrite extend_heap_n in H0.\n    assert (getv (heap_array (extend_heap h v)) i = getv (heap_array h) i).\n    { apply extend_heap_unaffected. omega. }\n    rewrite H2. auto.\nQed.\n\nTheorem heap_pop_maximum :\n  forall (h : heap) (v : nat),\n    Heap h -> snd (heap_pop h) = Some v ->\n      (forall (i : nat), i > 0 -> getv (heap_array h) i <= v).\nProof.\n  intros.\n  unfold heap_pop in H0.\n  destruct (heap_n h).\n  - inversion H0.\n  - simpl in H0. inversion H0.\n    apply heap_1_maximum; auto.\nQed.\n\nLemma heap_downify_correct :\n  forall (h : heap) (k height : nat),\n    log2 k + height = log2 (heap_n h) ->\n    k > 0 ->\n    (forall (i : nat),\n       2 <= i /\\ k <> i/2 -> getv (heap_array h) i <= getv (heap_array h) (i/2)) ->\n    (forall (i : nat),\n       4 <= i /\\ i/2 = k -> getv (heap_array h) i <= getv (heap_array h) (k/2)) ->\n    (forall (i : nat),\n       i > heap_n h -> getv (heap_array h) i = 0) ->\n    Heap (heap_downify h k height).\nProof.\n  intros h k height.\n  generalize dependent h.\n  generalize dependent k.\n  induction height.\n  - intros. rewrite <- plus_n_O in H.\n    assert (heap_n h < 2*k).\n    { apply Nat.log2_lt_cancel. rewrite Nat.log2_double. omega. omega. }\n    unfold Heap. split; unfold heap_downify.\n    + intros.\n      bdestruct (k =? (i/2)).\n      * assert (heap_n h < i). { assert (2*(i/2) <= i). { auto. } omega. }\n        rewrite H3; omega.\n      * apply H1. auto.\n    + auto.\n  - intros. unfold heap_downify. fold heap_downify.\n    bdestruct (getv (heap_array h) (2*k) <? getv (heap_array h) (2*k+1)).\n    + bdestruct (getv (heap_array h) k <? getv (heap_array h) (2*k+1)).\n      * { apply IHheight; clear IHheight.\n          - rewrite Nat.log2_succ_double. simpl. omega. auto.\n          - omega.\n          - intros. destruct H6. unfold heap_array.\n            bdestruct (i =? k).\n            + assert (k/2 < k). { auto. }\n              rewrite swap_get1. rewrite swap_get3; try omega.\n              apply H2. split. omega. auto.\n            + bdestruct (i =? 2*k).\n              * rewrite swap_get3; try omega.\n                assert (2*k/2 = k). { auto. }\n                rewrite H9. rewrite swap_get1. auto.\n              * { bdestruct (i =? 2*k+1).\n                  - rewrite swap_get2.\n                    assert ((2*k+1)/2 = k). { auto. }\n                    rewrite H10. rewrite swap_get1. auto.\n                  - assert (i/2 <> k). { auto. }\n                    rewrite swap_get3; auto.\n                    rewrite swap_get3; auto. }\n          - intros. destruct H6.\n            assert ((2*k+1)/2 = k). { auto. }\n            assert (i/2 < i). { apply div2_lt_n. omega. }\n            rewrite -> H8.\n            unfold heap_array. rewrite swap_get3. rewrite swap_get1.\n            rewrite <- H7. apply H1. omega. omega. omega.\n          - unfold heap_n, heap_array in *. intros. destruct h.\n            assert (k < n). { apply Nat.log2_lt_cancel. omega. }\n            bdestruct (i =? 2*k+1).\n            + assert (getv a (2*k+1) = 0). { apply H3. omega. }\n              omega.\n            + rewrite swap_get3. apply H3.\n              omega. omega. omega. }\n      * { unfold Heap. split.\n          - intros.\n            bdestruct (k =? i/2).\n            + assert (i = 2 * (i / 2) \\/ i = 2 * (i / 2) + 1). { apply div2_mul2_vals. }\n              destruct H7; rewrite <- H7 in *; eauto.\n            + apply H1. auto.\n          - auto. }\n    + (* almost duplicate proof as last bullet. *)\n      bdestruct (getv (heap_array h) k <? getv (heap_array h) (2 * k)).\n      * { apply IHheight; clear IHheight.\n          - rewrite Nat.log2_double. simpl. omega. auto.\n          - omega.\n          - intros. destruct H6. unfold heap_array.\n            bdestruct (i =? k).\n            + assert (k/2 < k). { auto. }\n              rewrite swap_get1. rewrite swap_get3; try omega.\n              apply H2. split. omega. auto.\n            + bdestruct (i =? 2*k+1).\n              * rewrite swap_get3; try omega.\n                assert ((2*k+1)/2 = k). { auto. }\n                rewrite H9. rewrite swap_get1. auto.\n              * { bdestruct (i =? 2*k).\n                  - rewrite swap_get2.\n                    assert (2*k/2 = k). { auto. }\n                    rewrite H10. rewrite swap_get1. auto.\n                  - assert (i/2 <> k). { auto. }\n                    rewrite swap_get3; auto.\n                    rewrite swap_get3; auto. }\n          - intros. destruct H6.\n            assert (2*k/2 = k). { auto. }\n            assert (i/2 < i). { apply div2_lt_n. omega. }\n            rewrite -> H8.\n            unfold heap_array. rewrite swap_get3. rewrite swap_get1.\n            rewrite <- H7. apply H1. omega. omega. omega.\n          - unfold heap_n, heap_array in *. intros. destruct h.\n            assert (k < n). { apply Nat.log2_lt_cancel. omega. }\n            bdestruct (i =? 2*k).\n            + assert (getv a (2*k) = 0). { apply H3. omega. }\n              omega.\n            + rewrite swap_get3. apply H3.\n              omega. omega. omega. }\n      * { unfold Heap. split.\n          - intros.\n            bdestruct (k =? i/2).\n            + assert (i = 2*(i/2) \\/ i = 2*(i/2)+1). { apply div2_mul2_vals. }\n              destruct H7; rewrite <- H7 in *; eauto.\n            + apply H1. auto.\n          - auto. }\nQed.\n\nTheorem heap_pop_correct :\n  forall (h : heap),\n    Heap h -> Heap (fst (heap_pop h)).\nProof.\n  intros.\n  unfold heap_pop.\n  destruct (heap_n h) eqn:H1.\n  - auto.\n  - simpl.\n    destruct n.\n    + simpl. unfold shrink_heap.\n      destruct h. simpl in H1. subst.\n      unfold Heap in *. destruct H. unfold heap_array in *.\n      rewrite swap_eq.\n      split.\n      * intros. simpl in H0. rewrite getv_ne. rewrite H0.\n        omega. omega. omega.\n      * intros. simpl in H0.\n        bdestruct (i =? 1); auto.\n        rewrite getv_ne. rewrite H0. auto. omega. omega.\n    + apply heap_downify_correct; try omega.\n      * rewrite Nat.log2_1. rewrite shrink_heap_n. rewrite H1.\n        auto.\n      * intros. destruct H0. unfold Heap in H. destruct H.\n        unfold shrink_heap. unfold heap_array, heap_n in *. destruct h. subst.\n        bdestruct (i/2 =? S (S n)).\n        { - rewrite -> H1.\n            assert (S (S n) < i). { assert (i/2 < i). { auto. } omega. }\n            rewrite getv_ne. rewrite getv_eq.\n            rewrite swap_get3. rewrite H3.\n            omega. omega. omega. omega. omega. }\n        { - bdestruct (i =? S (S n)).\n            + rewrite getv_eq. omega.\n            + rewrite getv_ne. rewrite getv_ne.\n              rewrite swap_get3. rewrite swap_get3. apply H.\n              omega. omega. omega. omega. omega. omega. omega. }\n      * intros. destruct H0.\n        assert (2 <= i/2). { auto. } omega.\n      * intros. rewrite shrink_heap_n in H0. rewrite H1 in H0. simpl in H0.\n        unfold Heap in H. destruct H. rewrite H1 in H2.\n        unfold shrink_heap, heap_array, heap_n in *. destruct h. subst.\n        bdestruct (i =? S (S n)).\n        { rewrite getv_eq. auto. }\n        { rewrite getv_ne, swap_get3.\n          apply H2. omega. omega. omega. omega. }\nQed.\n", "meta": {"author": "foreverbell", "repo": "verified", "sha": "44bba8f17b8070de304e14bc6fe1580e6890cd43", "save_path": "github-repos/coq/foreverbell-verified", "path": "github-repos/coq/foreverbell-verified/verified-44bba8f17b8070de304e14bc6fe1580e6890cd43/binary-heap/Heap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.6895012458535953}}
{"text": "Require Import List.\n\nTheorem app_assoc : forall A (l m n:list A), l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros.\n  induction l.\n    simpl.\n    reflexivity.\n\n    simpl.\n    rewrite IHl.\n    reflexivity.\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/list/AppAssoc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.6895012389643711}}
{"text": "(* Copyright (c) 2008-2012, 2015, Adam Chlipala\n * \n * This work is licensed under a\n * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0\n * Unported License.\n * The license text is available at:\n *   http://creativecommons.org/licenses/by-nc-nd/3.0/\n *)\n\n(* begin hide *)\nRequire Import List.\n\nRequire Import Cpdt.CpdtTactics.\n(* end hide *)\n\n(** These exercises were originally included inline in the text, but my latest feeling is that I don't have the time to maintain the exercises at a sufficient quality level to match the level I'm targetting for the rest of the book.  I'm including them in this file for now. *)\n\n(** * From InductiveTypes *)\n\n(** %\\begin{enumerate}%#<ol>#\n\n%\\item%#<li># Define an inductive type [truth] with three constructors, [Yes], [No], and [Maybe].  [Yes] stands for certain truth, [No] for certain falsehood, and [Maybe] for an unknown situation.  Define %``%#\"#not,#\"#%''% %``%#\"#and,#\"#%''% and %``%#\"#or#\"#%''% for this replacement boolean algebra.  Prove that your implementation of %``%#\"#and#\"#%''% is commutative and distributes over your implementation of %``%#\"#or.#\"#%''%#</li>#\n *)\n\nModule ex1.\nInductive truth : Type := Yes | No | Maybe.\n\nDefinition not (a : truth) : truth :=\n  match a with\n  | Yes => No\n  | No => Yes\n  | Maybe => Maybe\n  end.\n\nCheck not Yes.\n\nDefinition and (a b : truth) : truth :=\nmatch a with\n| Yes => b\n| No => match b with\n       | Maybe => Maybe\n       | _ => No\n       end\n| Maybe => Maybe\nend.\n\nDefinition or (a b : truth) : truth :=\n  match a with\n  | Yes => match b with\n          | Maybe => Maybe\n          | _ => Yes\n          end\n  | No => b\n  | Maybe => Maybe\n  end.\n\nLemma and_comm : forall (a b : truth), and a b = and b a.\n  intros; destruct a, b; auto. Qed.\nLemma or_comm : forall (a b : truth), or a b = or b a.\n  intros; destruct a, b; auto. Qed.\nLemma or_distr : forall (a b c : truth), or (and a b) c = and (or a c) (or b c).\n  intros; destruct a, b, c; auto. Qed.\n\nEnd ex1.\n(**\n%\\item%#<li># Define an inductive type [slist] that implements lists with support for constant-time concatenation.  This type should be polymorphic in a choice of type for data values in lists.  The type [slist] should have three constructors, for empty lists, singleton lists, and concatenation.  Define a function [flatten] that converts [slist]s to [list]s.  (You will want to run [Require Import] %\\coqdocconstructor{%#<tt>#List#</tt>#%}%[.] to bring list definitions into scope.)  Finally, prove that [flatten] distributes over concatenation, where the two sides of your quantified equality will use the [slist] and [list] versions of concatenation, as appropriate.  Recall from Chapter 2 that the infix operator [++] is syntactic sugar for the [list] concatenation function [app].#</li>#\n *)\n\nModule ex2.\nRequire Import List.\nSet Implicit Arguments.\nInductive slist (X : Type) : Type:=\n| s_nil : slist X\n| s_singleton : X -> slist X\n| s_cons : slist X -> slist X -> slist X.\n\nFixpoint flattern (X : Type) (sl : slist X) : list X :=\n  match sl with\n  | @s_nil _ => nil\n  | s_singleton a => a::nil\n  | s_cons sl1 sl2 => (flattern sl1) ++ (flattern sl2)\n  end.\nFixpoint s_app (X : Type) (s1 s2 : slist X) : slist X:=\n  match s1 with\n  | @s_nil _=> s2\n  | s_singleton a' as a => s_cons a s2\n  | s_cons a s1' => s_cons a (s_app s1' s2)\n  end.\nLemma flattern_distr : forall (X : Type) (a b : slist X), flattern (s_app a b) = (flattern a) ++ (flattern b).\n  induction a; intuition.\n  - simpl. rewrite <- app_assoc. rewrite <- (IHa2 b). reflexivity. Qed.\nEnd ex2.\n\n(**\n%\\item%#<li># Modify the first example language of Chapter 2 to include variables, where variables are represented with [nat].  Extend the syntax and semantics of expressions to accommodate the change.  Your new [expDenote] function should take as a new extra first argument a value of type [var -> nat], where [var] is a synonym for naturals-as-variables, and the function assigns a value to each variable.  Define a constant folding function which does a bottom-up pass over an expression, at each stage replacing every binary operation on constants with an equivalent constant.  Prove that constant folding preserves the meanings of expressions.#</li>#\n *)\n\nModule ex3.\nInductive binop : Set := Plus | Times.\nInductive var := vvar : nat-> var.\nInductive exp : Set :=\n| Const : nat -> exp\n| Binop : binop -> exp -> exp -> exp\n| Var : var -> exp.\n\nDefinition binopDenote (b : binop) :=\nmatch b with\n| Plus => plus\n| Times => mult\nend.\n\nFixpoint expDenote (ass : var-> nat) (e : exp) : nat :=\n  match e with\n  | Const n => n\n  | Binop b e1 e2 => (binopDenote b) (expDenote ass e1) (expDenote ass e2)\n  | Var v => ass v\n  end.\n\nFixpoint const_fold (e : exp) : exp:=\n  match e with\n  | Const n => e\n  | Var v => e\n  | Binop b e1 e2 => match e1, e2 with\n                    | Const n1, Const n2 => Const ((binopDenote b) n1 n2)\n                    | _, _ => Binop b (const_fold e1) (const_fold e2)\n                    end\n  end.\n\nLemma const_fold_correct : forall (e : exp) (ass : var -> nat), expDenote ass e = expDenote ass (const_fold e).\n  induction e; intuition; destruct b; induction e1, e2;\n    auto; simpl; f_equal; simpl in *; auto. Qed.\nEnd ex3.\n\n(**\n%\\item%#<li># Reimplement the second example language of Chapter 2 to use mutually inductive types instead of dependent types.  That is, define two separate (non-dependent) inductive types [nat_exp] and [bool_exp] for expressions of the two different types, rather than a single indexed type.  To keep things simple, you may consider only the binary operators that take naturals as operands.  Add natural number variables to the language, as in the last exercise, and add an %``%#\"#if#\"#%''% expression form taking as arguments one boolean expression and two natural number expressions.  Define semantics and constant-folding functions for this new language.  Your constant folding should simplify not just binary operations (returning naturals or booleans) with known arguments, but also %``%#\"#if#\"#%''% expressions with known values for their test expressions but possibly undetermined %``%#\"#then#\"#%''% and %``%#\"#else#\"#%''% cases.  Prove that constant-folding a natural number expression preserves its meaning.#</li>#\n *)\n\nModule ex4.\n  Require Import Arith.\n  Inductive nbinop : Set := NPlus | NTimes.\n  Inductive bbinop : Set := TEq | TLt.\n\n  Inductive var : Set := vvar : nat -> var.\n  Inductive bool_exp : Set:=\n  | BEq : nat -> nat -> bool_exp\n  | BLt : nat -> nat -> bool_exp\n  | BConst : bool -> bool_exp.\n  \n  Inductive nat_exp : Set :=\n  | NConst : nat -> nat_exp\n  | NBinop : nbinop -> nat_exp -> nat_exp -> nat_exp\n  | NVar : var -> nat_exp\n  | NIf : bool_exp -> nat_exp -> nat_exp -> nat_exp.\n\n  Definition bbinopDenote bb :=\n  match bb with\n  | TEq => beq_nat\n  | TLt => Nat.leb\n  end.\n\n  Definition nbinopDenote nb :=\n  match nb with\n  | NPlus => plus\n  | NTimes => mult\n  end.\n\n  Fixpoint bexpDenote (e : bool_exp) : bool :=\n    match e with\n    | BEq n1 n2 => beq_nat n1 n2\n    | BLt n1 n2 => Nat.leb n1 n2\n    | BConst b => b\n    end.\n\n  Fixpoint nexpDenote (ass : var -> nat) (e : nat_exp) : nat :=\n    match e with\n    | NConst n1 => n1\n    | NBinop b e1 e2 => (nbinopDenote b) (nexpDenote ass e1) (nexpDenote ass e2)\n    | NVar v => ass v\n    | NIf b e1 e2 => if (bexpDenote b) then (nexpDenote ass e1) else (nexpDenote ass e2)\n    end.\n\n  Fixpoint fold_const (e : nat_exp) : nat_exp :=\n    match e with\n    | NBinop b e1 e2 => match e1, e2 with\n                       | NConst n1, NConst n2 => NConst ((nbinopDenote b) n1 n2)\n                       | _, _ => NBinop b (fold_const e1) (fold_const e2)\n                       end\n    | NIf b e1 e2 => if (bexpDenote b) then (fold_const e1) else (fold_const e2)\n    | _ => e\n    end.\n\n  Lemma fold_const_correct : forall (e : nat_exp) (ass : var-> nat),\n      nexpDenote ass e = nexpDenote ass (fold_const e).\n    induction e; intuition.\n    - destruct n; induction e1, e2; auto; simpl; f_equal; simpl in *; auto.\n    - destruct b; try destruct b; auto; simpl; intuition; destruct (n <=? n0);\n        destruct (n =? n0); auto. Qed.\nEnd ex4.\n\n(**\n%\\item%#<li># Define mutually inductive types of even and odd natural numbers, such that any natural number is isomorphic to a value of one of the two types.  (This problem does not ask you to prove that correspondence, though some interpretations of the task may be interesting exercises.)  Write a function that computes the sum of two even numbers, such that the function type guarantees that the output is even as well.  Prove that this function is commutative.#</li>#\n *)\n\nModule ex5.\n  Inductive even : Set :=\n  | O : even\n  | SSe : even -> even.\n  Inductive odd : Set :=\n  | S : even -> odd.\n  Fixpoint add (n m:even) : even :=\n    match n with\n    | O => m\n    | SSe n' => SSe (add n' m)\n    end.\n  Lemma add_r_O : forall n, n = add n O.\n    induction n; simpl; try rewrite <- IHn; auto. Qed.\n\n  Hint Rewrite add_r_O.\n\n  Lemma add_n_SSem : forall n m, add n (SSe m) = SSe (add n m).\n    induction n; intros; simpl; try rewrite IHn; auto. Qed.\n\n  Hint Rewrite add_n_SSem.\n  \n  Lemma add_comm : forall (n m : even), add n m = add m n.\n    induction n; intros; simpl; auto.\n    - rewrite <- add_r_O with m. reflexivity.\n    - rewrite (add_n_SSem m n). rewrite IHn with m. reflexivity. Qed.\n  \nEnd ex5.\n\n(**\n%\\item%#<li># Using a reflexive inductive definition, define a type [nat_tree] of infinitary trees, with natural numbers at their leaves and a countable infinity of new trees branching out of each internal node.  Define a function [increment] that increments the number in every leaf of a [nat_tree].  Define a function [leapfrog] over a natural [i] and a tree [nt].  [leapfrog] should recurse into the [i]th child of [nt], the [i+1]st child of that node, the [i+2]nd child of the next node, and so on, until reaching a leaf, in which case [leapfrog] should return the number at that leaf.  Prove that the result of any call to [leapfrog] is incremented by one by calling [increment] on the tree.#</li>#\n *)\n\nModule ex6.\n(**\nevery nat_tree has two constructors:\n1. Only a leaf, which take a natural;\n2. A function that map naturals to nat_trees.\n *)\n  \n  Inductive nat_tree : Type :=\n  | Leaf : nat -> nat_tree\n  | Branch : (nat -> nat_tree) -> nat_tree.\n\n(** \n1. return type must be coinductive type;\n2. Guard constraint: all recursive call must be in the constructors. \n *)\n  \n  Fixpoint increment (t : nat_tree) : nat_tree :=\n    match t with\n    | Leaf n => Leaf (n+1)\n    | Branch f => Branch (fun n => increment (f n))\n    end.\n  \n  Fixpoint leapfrog (i : nat) (t : nat_tree) : nat :=\n    match t with\n    | Leaf n => n\n    | Branch f => leapfrog (i+1) (f i)\n    end.\n\n  Lemma leapfrog_increment : forall (t : nat_tree) (i : nat),\n      leapfrog i (increment t) = leapfrog i t + 1.\n    induction t; simpl; auto. Qed.\nEnd ex6.\n\n(**\n%\\item%#<li># Define a type of trees of trees of trees of (repeat to infinity).  That is, define an inductive type [trexp], whose members are either base cases containing natural numbers or binary trees of [trexp]s.  Base your definition on a parameterized binary tree type [btree] that you will also define, so that [trexp] is defined as a nested inductive type.  Define a function [total] that sums all of the naturals at the leaves of a [trexp].  Define a function [increment] that increments every leaf of a [trexp] by one.  Prove that, for all [tr], [total (increment tr) >= total tr].  On the way to finishing this proof, you will probably want to prove a lemma and add it as a hint using the syntax [Hint Resolve name_of_lemma.].#</li>#\n *)\n\nModule ex7.\n\n  Require Import Arith Bool.\n  Inductive trexp : Type :=\n  | Leaf : nat -> trexp\n  | Bin : trexp -> trexp -> trexp.\n\n  Fixpoint total (t : trexp) : nat :=\n    match t with\n    | Leaf n => n\n    | Bin t1 t2 => (total t1) + (total t2)\n    end.\n\n  Fixpoint increment (t : trexp) : trexp :=\n    match t with\n    | Leaf n => Leaf (n+1)\n    | Bin t1 t2 => Bin (increment t1) (increment t2)\n    end.\n\n  Lemma le_n_1_n : forall (n : nat), n + 1 = S n.\n    induction n; simpl; auto. Qed.\n  \n  Hint Resolve le_n_1_n.\n    \n  Lemma total_increment_add : forall (t : trexp), total (increment t) >= total t.\n    induction t; simpl; auto. rewrite (le_n_1_n n). auto.\n    apply plus_le_compat; assumption. Qed.\n\n(**\n%\\item%#<li># Prove discrimination and injectivity theorems for the [nat_btree] type defined earlier in this chapter.  In particular, without using the tactics [discriminate], [injection], or [congruence], prove that no leaf equals any node, and prove that two equal nodes carry the same natural number.#</li>#\n *)\n\n    Lemma inj_leaf_node : forall (n : nat) (t1 t2 : trexp), Leaf n <> Bin t1 t2.\n    intros; unfold not; intros; inversion H. Qed.\n\n  Fixpoint nat_in_tree (n : nat) (t : trexp) : bool :=\n    match t with\n    | Leaf n' => beq_nat n n'\n    | Bin t1 t2 => orb (nat_in_tree n t1) (nat_in_tree n t2)\n    end.\n  Lemma node_equal : forall (t1 t2 : trexp), t1 = t2 -> (forall n : nat, nat_in_tree n t1 = nat_in_tree n t2).\n    induction t1, t2; intros; inversion H; simpl; auto. Qed.\nEnd ex7.\n\n(**\n#</ol>#%\\end{enumerate}% *)\n\n\n\n(** * From Predicates *)\n\n(** %\\begin{enumerate}%#<ol>#\n\n%\\item%#<li># Prove these tautologies of propositional logic, using only the tactics [apply], [assumption], %\\coqdockw{%#<tt>#constructor#</tt>#%}%, [destruct], [intro], [intros], %\\coqdockw{%#<tt>#left#</tt>#%}%, %\\coqdockw{%#<tt>#right#</tt>#%}%, [split], and [unfold].\n  %\\begin{enumerate}%#<ol>#\n    %\\item%#<li># [(][True \\/ False) /\\ (][False \\/ True)]#</li>#\n    %\\item%#<li># [P -> ~ ~ P]#</li>#\n    %\\item%#<li># [P /\\ (][Q \\/ R) -> (][P /\\ Q) \\/ (][P /\\ R)]#</li>#\n  #</ol> </li>#%\\end{enumerate}%\n *)\n\nModule ex8.\n  Lemma ex1 : (True \\/ False ) /\\ ( False \\/ True ).\n    split; [ left | right ]; constructor. Qed.\n\n  Lemma ex2 : forall P : Prop, P -> ~ ~ P.\n    unfold not; intros;\n      match goal with\n      | [ H: _ |- False ] => apply H\n      end; assumption. Qed.\n\n  Lemma ex3 : forall (P Q R : Prop), P /\\ (Q \\/ R) -> (P /\\ Q) \\/ (P /\\ R).\n    intros P Q R H; destruct H;\n      match goal with\n      | [ H : ?H1 \\/ ?H2 |- _ ] => destruct H\n      end; [left | right]; split; repeat assumption. Qed.\nEnd ex8.\n\n(**\n  %\\item%#<li># Prove the following tautology of first-order logic, using only the tactics [apply], [assert], [assumption], [destruct], [eapply], %\\coqdockw{%#<tt>#eassumption#</tt>#%}%, and %\\coqdockw{%#<tt>#exists#</tt>#%}%.  You will probably find the [assert] tactic useful for stating and proving an intermediate lemma, enabling a kind of %``%#\"#forward reasoning,#\"#%''% in contrast to the %``%#\"#backward reasoning#\"#%''% that is the default for Coq tactics.  The tactic %\\coqdockw{%#<tt>#eassumption#</tt>#%}% is a version of [assumption] that will do matching of unification variables.  Let some variable [T] of type [Set] be the set of individuals.  [x] is a constant symbol, [p] is a unary predicate symbol, [q] is a binary predicate symbol, and [f] is a unary function symbol.\n%\\begin{enumerate}%#<ol>#\n    %\\item%#<li># [p x -> (][forall x, p x -> exists y, q x y) -> (][forall x y, q x y -> q y (f y)) -> exists z, q z (f z)]#</li>#\n  #</ol> </li>#%\\end{enumerate}%\n *)\n\nModule ex9.\n  Lemma ex1 : forall (T : Type) p q f (x y z : T),\n    p x -> (forall x, p x -> exists y, q x y) ->\n    (forall x y, q x y -> q y (f y)) ->\n    exists z, q z (f z).\n    intros. destruct (H x). assumption.\n    exists x0. eapply H0. eassumption. Qed.\nEnd ex9.\n\n(**\n%\\item%#<li># Define an inductive predicate capturing when a natural number is an integer multiple of either 6 or 10.  Prove that 13 does not satisfy your predicate, and prove that any number satisfying the predicate is not odd.  It is probably easiest to prove the second theorem by indicating %``%#\"#odd-ness#\"#%''% as equality to [2 * n + 1] for some [n].#</li>#\n *)\n\nModule ex10.\n  Inductive six : nat -> Prop :=\n  | six_O : six O\n  | sixS : forall n, six n -> six (S (S (S (S (S (S n)))))).\n  Inductive ten : nat -> Prop :=\n  | ten_O : ten O\n  | tenS : forall n, ten n -> ten (S (S (S (S (S (S (S (S (S (S n)))))))))).\n  \n  Inductive six_ten : nat -> Prop :=\n  | Six : forall n, six n -> six_ten n\n  | Ten : forall n, ten n -> six_ten n.\n\n  Ltac finisher :=\n    unfold not; intros H; inversion H; subst;\n    repeat match goal with\n           | [ H: six _ |- _ ] => inversion H; subst\n           | [ H: ten _ |- _ ] => inversion H; subst\n           end.\n  Lemma not_13_six_tem : ~ ( six_ten 13).\n    finisher. Qed.\n\n  Require Import Arith Plus Nat.\n\n  Lemma six_ten_not_odd : forall n, six_ten n -> (odd n = false).\n    assert (H1 : forall n, six n -> (odd n = false)).\n    { intros n H; induction H; auto. }\n    assert (H2 : forall n, ten n -> (odd n = false)).\n    { intros n H; induction H; auto. }\n    intros n H; destruct H; auto. Qed.\nEnd ex10.\n\n(**\n%\\item%#<li># Define a simple programming language, its semantics, and its typing rules, and then prove that well-typed programs cannot go wrong.  Specifically:\n  %\\begin{enumerate}%#<ol>#\n    %\\item%#<li># Define [var] as a synonym for the natural numbers.#</li>#\n    %\\item%#<li># Define an inductive type [exp] of expressions, containing natural number constants, natural number addition, pairing of two other expressions, extraction of the first component of a pair, extraction of the second component of a pair, and variables (based on the [var] type you defined).#</li>#\n    %\\item%#<li># Define an inductive type [cmd] of commands, containing expressions and variable assignments.  A variable assignment node should contain the variable being assigned, the expression being assigned to it, and the command to run afterward.#</li>#\n    %\\item%#<li># Define an inductive type [val] of values, containing natural number constants and pairings of values.#</li>#\n    %\\item%#<li># Define a type of variable assignments, which assign a value to each variable.#</li>#\n    %\\item%#<li># Define a big-step evaluation relation [eval], capturing what it means for an expression to evaluate to a value under a particular variable assignment.  %``%#\"#Big step#\"#%''% means that the evaluation of every expression should be proved with a single instance of the inductive predicate you will define.  For instance, %``%#\"#[1 + 1] evaluates to [2] under assignment [va]#\"#%''% should be derivable for any assignment [va].#</li>#\n    %\\item%#<li># Define a big-step evaluation relation [run], capturing what it means for a command to run to a value under a particular variable assignment.  The value of a command is the result of evaluating its final expression.#</li>#\n    %\\item%#<li># Define a type of variable typings, which are like variable assignments, but map variables to types instead of values.  You might use polymorphism to share some code with your variable assignments.#</li>#\n    %\\item%#<li># Define typing judgments for expressions, values, and commands.  The expression and command cases will be in terms of a typing assignment.#</li>#\n    %\\item%#<li># Define a predicate [varsType] to express when a variable assignment and a variable typing agree on the types of variables.#</li>#\n    %\\item%#<li># Prove that any expression that has type [t] under variable typing [vt] evaluates under variable assignment [va] to some value that also has type [t] in [vt], as long as [va] and [vt] agree.#</li>#\n    %\\item%#<li># Prove that any command that has type [t] under variable typing [vt] evaluates under variable assignment [va] to some value that also has type [t] in [vt], as long as [va] and [vt] agree.#</li>#\n  #</ol> </li>#%\\end{enumerate}%\n  A few hints that may be helpful:\n  %\\begin{enumerate}%#<ol>#\n    %\\item%#<li># One easy way of defining variable assignments and typings is to define both as instances of a polymorphic map type.  The map type at parameter [T] can be defined to be the type of arbitrary functions from variables to [T].  A helpful function for implementing insertion into such a functional map is [eq_nat_dec], which you can make available with [Require Import Arith.].  [eq_nat_dec] has a dependent type that tells you that it makes accurate decisions on whether two natural numbers are equal, but you can use it as if it returned a boolean, e.g., [if eq_nat_dec n m then E1 else E2].#</li>#\n    %\\item%#<li># If you follow the last hint, you may find yourself writing a proof that involves an expression with [eq_nat_dec] that you would like to simplify.  Running [destruct] on the particular call to [eq_nat_dec] should do the trick.  You can automate this advice with a piece of Ltac: [[\nmatch goal with\n  | [ |- context[eq_nat_dec ?X ?Y] ] => destruct (eq_nat_dec X Y)\nend\n]]\n    #</li>#\n    %\\item%#<li># You probably do not want to use an inductive definition for compatibility of variable assignments and typings.#</li>#\n    %\\item%#<li># The [CpdtTactics] module from this book contains a variant [crush'] of [crush].  [crush'] takes two arguments.  The first argument is a list of lemmas and other functions to be tried automatically in %``%#\"#forward reasoning#\"#%''% style, where we add new facts without being sure yet that they link into a proof of the conclusion.  The second argument is a list of predicates on which inversion should be attempted automatically.  For instance, running [crush' (lemma1, lemma2) pred] will search for chances to apply [lemma1] and [lemma2] to hypotheses that are already available, adding the new concluded fact if suitable hypotheses can be found.  Inversion will be attempted on any hypothesis using [pred], but only those inversions that narrow the field of possibilities to one possible rule will be kept.  The format of the list arguments to [crush'] is that you can pass an empty list as [tt], a singleton list as the unadorned single element, and a multiple-element list as a tuple of the elements.#</li>#\n    %\\item%#<li># If you want [crush'] to apply polymorphic lemmas, you may have to do a little extra work, if the type parameter is not a free variable of your proof context (so that [crush'] does not know to try it).  For instance, if you define a polymorphic map insert function [assign] of some type [forall T : Set, ...], and you want particular applications of [assign] added automatically with type parameter [U], you would need to include [assign] in the lemma list as [assign U] (if you have implicit arguments off) or [assign (T := U)] or [@assign U] (if you have implicit arguments on).#</li>#\n  #</ol> </li>#%\\end{enumerate}%\n\n#</li>#\n\n#</ol>#%\\end{enumerate}% *)\n\nModule ex11.\n  Definition var := nat.\n\n  Inductive exp : Type :=\n  | Const : nat -> exp\n  | Plus : nat -> nat -> exp\n  | Pair : exp -> exp -> exp\n  | Fst : exp -> exp\n  | Snd : exp -> exp\n  | Var : var -> exp.\n\n  Inductive cmd : Type :=\n  | Cmd : var -> exp -> cmd.\n\n  Inductive val : Type :=\n  | NumVal : nat -> val\n  | PairVar : val -> val -> val.\n\n  Inductive ass : Type :=\n  | Ass : var -> exp -> ass.\n\nEnd ex11.\n\n\n(** * From Coinductive *)\n\n(** %\\begin{enumerate}%#<ol>#\n\n%\\item%#<li># %\\begin{enumerate}%#<ol>#\n  %\\item%#<li># Define a co-inductive type of infinite trees carrying data of a fixed parameter type.  Each node should contain a data value and two child trees.#</li>#\n  %\\item%#<li># Define a function [everywhere] for building a tree with the same data value at every node.#</li>#\n  %\\item%#<li># Define a function [map] for building an output tree out of two input trees by traversing them in parallel and applying a two-argument function to their corresponding data values.#</li>#\n  %\\item%#<li># Define a tree [falses] where every node has the value [false].#</li>#\n  %\\item%#<li># Define a tree [true_false] where the root node has value [true], its children have value [false], all nodes at the next have the value [true], and so on, alternating boolean values from level to level.#</li>#\n  %\\item%#<li># Prove that [true_false] is equal to the result of mapping the boolean %``%#\"#or#\"#%''% function [orb] over [true_false] and [falses].  You can make [orb] available with [Require Import Bool.].  You may find the lemma [orb_false_r] from the same module helpful.  Your proof here should not be about the standard equality [=], but rather about some new equality relation that you define.#</li>#\n#</ol>#%\\end{enumerate}% #</li>#\n\n#</ol>#%\\end{enumerate}% *)\n\nModule ex12.\n  CoInductive cotree (X : Type) : Type :=\n  | Node : X -> cotree X -> cotree X -> cotree X.\n\n\n  CoFixpoint everywhere (X : Type) (a : X) : cotree X :=\n    Node X a (everywhere X a) (everywhere X a).\n\n  CoFixpoint map (X : Type) (Y : Type) (f : X -> X -> Y) (t1 t2 : cotree X) : cotree Y :=\n    match t1, t2 with\n    | Node _ a1 t11 t12, Node _ a2 t21 t22 =>\n      Node Y (f a1 a2) (map X Y f t11 t21) (map X Y f t12 t22)\n    end.\n\n  Definition falses := everywhere _ false.\n\n  CoFixpoint true_false :=\n    Node _ true false_true false_true\n  with false_true :=\n         Node _ false true_false true_false.\n\n  CoInductive co_equal (X : Type)  : cotree X -> cotree X -> Prop:=\n  | Eq : forall l1 l2 r1 r2 e1 e2,\n      co_equal X l1 l2 ->\n      co_equal X r1 r2 -> e1 = e2 ->\n      co_equal X (Node _ e1 l1 r1) (Node _ e2 l2 r2).\n  Lemma orb_false_r : forall x, orb x false = x.\n    intros; destruct x; auto. Qed.\n  Hint Resolve orb_false_r.\n\n  Definition frob (X : Type) (t : cotree X) :=\n  match t with\n  | Node _ a t1 t2 => Node _ a t1 t2\n  end.\n\n  Lemma frob_eq : forall (X : Type) (t : cotree X), t = frob _ t.\n    destruct t; auto. Qed. \n\n  Hint Resolve frob_eq.\n\n(**\nThe next Lemma if very important, a little difficult. \n *)\n    \n  Lemma f : co_equal _ true_false (map _ _ orb true_false falses).\n    cofix. rewrite (frob_eq _ (map bool bool orb true_false falses)),\n           (frob_eq _ true_false). simpl. constructor; try reflexivity.\n    rewrite (frob_eq _ (map bool bool orb false_true (everywhere bool false))),\n    (frob_eq _ false_true); simpl; constructor; fold falses; auto.\n    rewrite (frob_eq _ (map bool bool orb false_true (everywhere bool false))),\n    (frob_eq _ false_true); simpl; constructor; auto. Qed.\nEnd ex12.\n\n(** * From Subset *)\n\n(** All of the notations defined in this chapter, plus some extras, are available for import from the module [MoreSpecif] of the book source.\n\n%\\begin{enumerate}%#<ol>#\n%\\item%#<li># Write 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.#</li>#\n *)\nModule ex13.\n  Require Import Specif.\n  Require Import Arith.\n  Require Import Peano.\n\n  Notation \"'LE'\" := (left _ _ ).\n  Notation \"'GT'\" := (right _ _).\n  Notation \"'Reduce' x\" := (if x then LE else GT) (at level 50).\n  \n  Definition le_nat : 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, _ => LE\n           | S _, O => GT\n           | S n', S m' => Reduce (f n' m')\n           end);\n      [ apply le_0_n |\n        apply gt_Sn_O|\n        apply le_n_S; assumption |\n        apply gt_n_S; assumption ].\n  Defined.\n\n  Eval compute in le_nat 99 100.\n      \nEnd ex13.\n\n\n(**\n%\\item%#<li># %\\begin{enumerate}%#<ol>#\n  %\\item%#<li># Define [var], a type of propositional variables, as a synonym for [nat].#</li>#\n  %\\item%#<li># Define an inductive type [prop] of propositional logic formulas, consisting of variables, negation, and binary conjunction and disjunction.#</li>#\n  %\\item%#<li># 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].#</li>#\n  %\\item%#<li># 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}]. #</li>#\n  %\\item%#<li># 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.#</li>#\n  %\\item%#<li># 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.#</li>#\n#</ol>#%\\end{enumerate}% #</li>#\n *)\n\nModule ex14.\n  Inductive var : Type :=\n  | Var : nat -> var.\n  Inductive prop : Type :=\n  | PVar : var -> prop\n  | PNot : prop -> prop\n  | PConj : prop -> prop -> prop\n  | PDisj : prop -> prop -> prop.\n  \n  Fixpoint propDenote (f : var -> bool) (p : prop) : Prop :=\n    match p with\n    | PVar v => if (f v) then True else False\n    | PNot p => ~ (propDenote f p)\n    | PConj p1 p2 => (propDenote f p1) /\\ (propDenote f p2)\n    | PDisj p1 p2 => (propDenote f p1) \\/ (propDenote f p2)\n    end.\n\n  Definition bool_true_dec := forall b, { b = true } + { ~ ( b = true) }.\n\n  Definition decide := forall ( truth : var -> bool) (p : prop), { propDenote truth p} + { ~ propDenote truth p}.\n\n  Definition negate := forall p : prop, { p' : prop | forall truth, propDenote truth p <-> ~ propDenote truth p' }.\n  \nEnd ex14.\n\n(**\n%\\item%#<li># Implement the DPLL satisfiability decision procedure for boolean formulas in conjunctive normal form, with a dependent type that guarantees its correctness.  An example of a reasonable type for this function would be [forall f : formula, {truth : tvals | formulaTrue truth f} + {][forall truth, ~ formulaTrue truth f}].  Implement at least %``%#\"#the basic backtracking algorithm#\"#%''% as defined here:\n  %\\begin{center}\\url{http://en.wikipedia.org/wiki/DPLL_algorithm}\\end{center}%\n  #<blockquote><a href=\"http://en.wikipedia.org/wiki/DPLL_algorithm\">http://en.wikipedia.org/wiki/DPLL_algorithm</a></blockquote>#\nIt might also be instructive to implement the unit propagation and pure literal elimination optimizations described there or some other optimizations that have been used in modern SAT solvers.#</li>#\n   \n#</ol>#%\\end{enumerate}% *)\n\n\n(** * From MoreDep *)\n\n(** %\\begin{enumerate}%#<ol>#\n\n%\\item%#<li># Define a kind of dependently typed lists, where a list's type index gives a lower bound on how many of its elements satisfy a particular predicate.  In particular, for an arbitrary set [A] and a predicate [P] over it:\n%\\begin{enumerate}%#<ol>#\n  %\\item%#<li># Define a type [plist : nat -> Set].  Each [plist n] should be a list of [A]s, where it is guaranteed that at least [n] distinct elements satisfy [P].  There is wide latitude in choosing how to encode this.  You should try to avoid using subset types or any other mechanism based on annotating non-dependent types with propositions after-the-fact.#</li>#\n  %\\item%#<li># Define a version of list concatenation that works on [plist]s.  The type of this new function should express as much information as possible about the output [plist].#</li>#\n  %\\item%#<li># Define a function [plistOut] for translating [plist]s to normal [list]s.#</li>#\n  %\\item%#<li># Define a function [plistIn] for translating [list]s to [plist]s.  The type of [plistIn] should make it clear that the best bound on [P]-matching elements is chosen.  You may assume that you are given a dependently typed function for deciding instances of [P].#</li>#\n  %\\item%#<li># Prove that, for any list [ls], [plistOut (plistIn ls) = ls].  This should be the only part of the exercise where you use tactic-based proving.#</li>#\n  %\\item%#<li># Define a function [grab : forall n (ls : plist (][S n)), sig P].  That is, when given a [plist] guaranteed to contain at least one element satisfying [P], [grab] produces such an element.  The type family [sig] is the one we met earlier for sigma types (i.e., dependent pairs of programs and proofs), and [sig P] is extensionally equivalent to [{][x : A | P x}], though the latter form uses an eta-expansion of [P] instead of [P] itself as the predicate.#</li>#\n#</ol>#%\\end{enumerate}% #</li>#\n   \n#</ol>#%\\end{enumerate}% *)\n\n\n(** * From DataStruct *)\n\n(** remove printing * *)\n\n(** Some of the type family definitions and associated functions from this chapter are duplicated in the [DepList] module of the book source.  Some of their names have been changed to be more sensible in a general context.\n\n%\\begin{enumerate}%#<ol>#\n\n%\\item%#<li># Define a tree analogue of [hlist].  That is, define a parameterized type of binary trees with data at their leaves, and define a type family [htree] indexed by trees.  The structure of an [htree] mirrors its index tree, with the type of each data element (which only occur at leaves) determined by applying a type function to the corresponding element of the index tree.  Define a type standing for all possible paths from the root of a tree to leaves and use it to implement a function [tget] for extracting an element of an [htree] by path.  Define a function [htmap2] for %``%#\"#mapping over two trees in parallel.#\"#%''%  That is, [htmap2] takes in two [htree]s with the same index tree, and it forms a new [htree] with the same index by applying a binary function pointwise.\n\n  Repeat this process so that you implement each definition for each of the three definition styles covered in this chapter: inductive, recursive, and index function.#</li>#\n\n%\\item%#<li># Write a dependently typed interpreter for a simple programming language with ML-style pattern-matching, using one of the encodings of heterogeneous lists to represent the different branches of a [case] expression.  (There are other ways to represent the same thing, but the point of this exercise is to practice using those heterogeneous list types.)  The object language is defined informally by this grammar:\n  [[\nt ::= bool | t + t\np ::= x | b | inl p | inr p\ne ::= x | b | inl e | inr e | case e of [p => e]* | _ => e\n]]\n\n  The non-terminal [x] stands for a variable, and [b] stands for a boolean constant.  The production for [case] expressions means that a pattern-match includes zero or more pairs of patterns and expressions, along with a default case.\n\n  Your interpreter should be implemented in the style demonstrated in this chapter.  That is, your definition of expressions should use dependent types and de Bruijn indices to combine syntax and typing rules, such that the type of an expression tells the types of variables that are in scope.  You should implement a simple recursive function translating types [t] to [Set], and your interpreter should produce values in the image of this translation.#</li>#\n\n#</ol>#%\\end{enumerate}% *)\n\n\n(** * From Equality *)\n\n(** %\\begin{enumerate}%#<ol>#\n\n%\\item%#<li># Implement and prove correct a substitution function for simply typed lambda calculus.  In particular:\n%\\begin{enumerate}%#<ol>#\n  %\\item%#<li># Define a datatype [type] of lambda types, including just booleans and function types.#</li>#\n  %\\item%#<li># Define a type family [exp : list type -> type -> Type] of lambda expressions, including boolean constants, variables, and function application and abstraction.#</li>#\n  %\\item%#<li># Implement a definitional interpreter for [exp]s, by way of a recursive function over expressions and substitutions for free variables, like in the related example from the last chapter.#</li>#\n  %\\item%#<li># Implement a function [subst : forall t' ts t, exp (t' :: ts) t -> exp ts t' -> exp ts t].  The type of the first expression indicates that its most recently bound free variable has type [t'].  The second expression also has type [t'], and the job of [subst] is to substitute the second expression for every occurrence of the %``%#\"#first#\"#%''% variable of the first expression.#</li>#\n  %\\item%#<li># Prove that [subst] preserves program meanings.  That is, prove\n  [[\nforall t' ts t (e : exp (t' :: ts) t) (e' : exp ts t') (s : hlist typeDenote ts),\n  expDenote (subst e e') s = expDenote e (expDenote e' s ::: s)\n  ]]\n  where [:::] is an infix operator for heterogeneous %``%#\"#cons#\"#%''% that is defined in the book's [DepList] module.#</li>#\n#</ol>#%\\end{enumerate}%\n  The material presented up to this point should be sufficient to enable a good solution of this exercise, with enough ingenuity.  If you get stuck, it may be helpful to use the following structure.  None of these elements need to appear in your solution, but we can at least guarantee that there is a reasonable solution based on them.\n%\\begin{enumerate}%#<ol>#\n  %\\item%#<li># The [DepList] module will be useful.  You can get the standard dependent list definitions there, instead of copying-and-pasting from the last chapter.  It is worth reading the source for that module over, since it defines some new helpful functions and notations that we did not use last chapter.#</li>#\n  %\\item%#<li># Define a recursive function [liftVar : forall ts1 ts2 t t', member t (ts1 ++ ts2) -> member t (ts1 ++ t' :: ts2)].  This function should %``%#\"#lift#\"#%''% a de Bruijn variable so that its type refers to a new variable inserted somewhere in the index list.#</li>#\n  %\\item%#<li># Define a recursive function [lift' : forall ts t (e : exp ts t) ts1 ts2 t', ts = ts1 ++ ts2 -> exp (ts1 ++ t' :: ts2) t] which performs a similar lifting on an [exp].  The convoluted type is to get around restrictions on [match] annotations.  We delay %``%#\"#realizing#\"#%''% that the first index of [e] is built with list concatenation until after a dependent [match], and the new explicit proof argument must be used to cast some terms that come up in the [match] body.#</li>#\n  %\\item%#<li># Define a function [lift : forall ts t t', exp ts t -> exp (t' :: ts) t], which handles simpler top-level lifts.  This should be an easy one-liner based on [lift'].#</li>#\n  %\\item%#<li># Define a recursive function [substVar : forall ts1 ts2 t t', member t (ts1 ++ t' :: ts2) -> (t' = t) + member t (ts1 ++ ts2)].  This function is the workhorse behind substitution applied to a variable.  It returns [inl] to indicate that the variable we pass to it is the variable that we are substituting for, and it returns [inr] to indicate that the variable we are examining is _not_ the one we are substituting for.  In the first case, we get a proof that the necessary typing relationship holds, and, in the second case, we get the original variable modified to reflect the removal of the substitutee from the typing context.#</li>#\n  %\\item%#<li># Define a recursive function [subst' : forall ts t (e : exp ts t) ts1 t' ts2, ts = ts1 ++ t' :: ts2 -> exp (ts1 ++ ts2) t' -> exp (ts1 ++ ts2) t].  This is the workhorse of substitution in expressions, employing the same proof-passing trick as for [lift'].  You will probably want to use [lift] somewhere in the definition of [subst'].#</li>#\n  %\\item%#<li># Now [subst] should be a one-liner, defined in terms of [subst'].#</li>#\n  %\\item%#<li># Prove a correctness theorem for each auxiliary function, leading up to the proof of [subst] correctness.#</li>#\n  %\\item%#<li># All of the reasoning about equality proofs in these theorems follows a regular pattern.  If you have an equality proof that you want to replace with [eq_refl] somehow, run [generalize] on that proof variable.  Your goal is to get to the point where you can [rewrite] with the original proof to change the type of the generalized version.  To avoid type errors (the infamous %``%#\"#second-order unification#\"#%''% failure messages), it will be helpful to run [generalize] on other pieces of the proof context that mention the equality's lefthand side.  You might also want to use [generalize dependent], which generalizes not just one variable but also all variables whose types depend on it.  [generalize dependent] has the sometimes-helpful property of removing from the context all variables that it generalizes.  Once you do manage the mind-bending trick of using the equality proof to rewrite its own type, you will be able to rewrite with [UIP_refl].#</li>#\n  %\\item%#<li># The [ext_eq] axiom from the end of this chapter is available in the Coq standard library as [functional_extensionality] in module [FunctionalExtensionality], and you will probably want to use it in the [lift'] and [subst'] correctness proofs.#</li>#\n  %\\item%#<li># The [change] tactic should come in handy in the proofs about [lift] and [subst], where you want to introduce %``%#\"#extraneous#\"#%''% list concatenations with [nil] to match the forms of earlier theorems.#</li>#\n  %\\item%#<li># Be careful about [destruct]ing a term %``%#\"#too early.#\"#%''%  You can use [generalize] on proof terms to bring into the proof context any important propositions about the term.  Then, when you [destruct] the term, it is updated in the extra propositions, too.  The [case_eq] tactic is another alternative to this approach, based on saving an equality between the original term and its new form.#</li>#\n#</ol>#%\\end{enumerate}%\n#</li>#\n   \n#</ol>#%\\end{enumerate}% *)\n\n\n(** * From LogicProg *)\n\n(** printing * $\\cdot$ *)\n\n(** %\\begin{enumerate}%#<ol>#\n\n%\\item%#<li># I did a Google search for group theory and found #<a href=\"http://dogschool.tripod.com/housekeeping.html\">#a page that proves some standard theorems#</a>#%\\footnote{\\url{http://dogschool.tripod.com/housekeeping.html}}%.  This exercise is about proving all of the theorems on that page automatically.\n\n  For the purposes of this exercise, a group is a set [G], a binary function [f] over [G], an identity element [e] of [G], and a unary inverse function [i] for [G].  The following laws define correct choices of these parameters.  We follow standard practice in algebra, where all variables that we mention are quantified universally implicitly at the start of a fact.  We write infix [*] for [f], and you can set up the same sort of notation in your code with a command like [Infix \"*\" := f.].\n\n  %\\begin{itemize}%#<ul>#\n    %\\item%#<li># %\\textbf{%#<b>#Associativity#</b>#%}%: [(a * b) * c = a * (b * c)]#</li>#\n    %\\item%#<li># %\\textbf{%#<b>#Right Identity#</b>#%}%: [a * e = a]#</li>#\n    %\\item%#<li># %\\textbf{%#<b>#Right Inverse#</b>#%}%: [a * i a = e]#</li>#\n  #</ul> </li>#%\\end{itemize}%\n\n  The task in this exercise is to prove each of the following theorems for all groups, where we define a group exactly as above.  There is a wrinkle: every theorem or lemma must be proved by either a single call to [crush] or a single call to [eauto]!  It is allowed to pass numeric arguments to [eauto], where appropriate.  Recall that a numeric argument sets the depth of proof search, where 5 is the default.  Lower values can speed up execution when a proof exists within the bound.  Higher values may be necessary to find more involved proofs.\n\n  %\\begin{itemize}%#<ul>#\n    %\\item%#<li># %\\textbf{%#<b>#Characterizing Identity#</b>#%}%: [a * a = a -> a = e]#</li>#\n    %\\item%#<li># %\\textbf{%#<b>#Left Inverse#</b>#%}%: [i a * a = e]#</li>#\n    %\\item%#<li># %\\textbf{%#<b>#Left Identity#</b>#%}%: [e * a = a]#</li>#\n    %\\item%#<li># %\\textbf{%#<b>#Uniqueness of Left Identity#</b>#%}%: [p * a = a -> p = e]#</li>#\n    %\\item%#<li># %\\textbf{%#<b>#Uniqueness of Right Inverse#</b>#%}%: [a * b = e -> b = i a]#</li>#\n    %\\item%#<li># %\\textbf{%#<b>#Uniqueness of Left Inverse#</b>#%}%: [a * b = e -> a = i b]#</li>#\n    %\\item%#<li># %\\textbf{%#<b>#Right Cancellation#</b>#%}%: [a * x = b * x -> a = b]#</li>#\n    %\\item%#<li># %\\textbf{%#<b>#Left Cancellation#</b>#%}%: [x * a = x * b -> a = b]#</li>#\n    %\\item%#<li># %\\textbf{%#<b>#Distributivity of Inverse#</b>#%}%: [i (a * b) = i b * i a]#</li>#\n    %\\item%#<li># %\\textbf{%#<b>#Double Inverse#</b>#%}%: [i (][i a) = a]#</li>#\n    %\\item%#<li># %\\textbf{%#<b>#Identity Inverse#</b>#%}%: [i e = e]#</li>#\n  #</ul> </li>#%\\end{itemize}%\n\n  One more use of tactics is allowed in this problem.  The following lemma captures one common pattern of reasoning in algebra proofs: *)\n\n(* begin hide *)\nVariable G : Set.\nVariable f : G -> G -> G.\nInfix \"*\" := f.\n(* end hide *)\n\nLemma mult_both : forall a b c d1 d2,\n  a * c = d1\n  -> b * c = d2\n  -> a = b\n  -> d1 = d2.\n  crush.\nQed.\n\n(** That is, we know some equality [a = b], which is the third hypothesis above.  We derive a further equality by multiplying both sides by [c], to yield [a * c = b * c].  Next, we do algebraic simplification on both sides of this new equality, represented by the first two hypotheses above.  The final result is a new theorem of algebra.\n\n   The next chapter introduces more details of programming in Ltac, but here is a quick teaser that will be useful in this problem.  Include the following hint command before you start proving the main theorems of this exercise: *)\n\nHint Extern 100 (_ = _) =>\n  match goal with\n    | [ _ : True |- _ ] => fail 1\n    | _ => assert True by constructor; eapply mult_both\n  end.\n\n(** This hint has the effect of applying [mult_both] _at most once_ during a proof.  After the next chapter, it should be clear why the hint has that effect, but for now treat it as a useful black box.  Simply using [Hint Resolve mult_both] would increase proof search time unacceptably, because there are just too many ways to use [mult_both] repeatedly within a proof.\n\n   The order of the theorems above is itself a meta-level hint, since I found that order to work well for allowing the use of earlier theorems as hints in the proofs of later theorems.\n\n   The key to this problem is coming up with further lemmas like [mult_both] that formalize common patterns of reasoning in algebraic proofs.  These lemmas need to be more than sound: they must also fit well with the way that [eauto] does proof search.  For instance, if we had given [mult_both] a traditional statement, we probably would have avoided %``%#\"#pointless#\"#%''% equalities like [a = b], which could be avoided simply by replacing all occurrences of [b] with [a].  However, the resulting theorem would not work as well with automated proof search!  Every additional hint you come up with should be registered with [Hint Resolve], so that the lemma statement needs to be in a form that [eauto] understands %``%#\"#natively.#\"#%''%\n\n   I recommend testing a few simple rules corresponding to common steps in algebraic proofs.  You can apply them manually with any tactics you like (e.g., [apply] or [eapply]) to figure out what approaches work, and then switch to [eauto] once you have the full set of hints.\n\n   I also proved a few hint lemmas tailored to particular theorems, but which do not give common algebraic simplification rules.  You will probably want to use some, too, in cases where [eauto] does not find a proof within a reasonable amount of time.  In total, beside the main theorems to be proved, my sample solution includes 6 lemmas, with a mix of the two kinds of lemmas.  You may use more in your solution, but I suggest trying to minimize the number.\n\n#</ol>#%\\end{enumerate}% *)\n\n\n(** * From Match *)\n\n(** %\\begin{enumerate}%#<ol>#\n\n   %\\item%#<li># An anonymous Coq fan from the Internet was excited to come up with this tactic definition shortly after getting started learning Ltac: *)\n\nLtac deSome :=\n  match goal with\n    | [ H : Some _ = Some _ |- _ ] => injection H; clear H; intros; subst; deSome\n    | _ => reflexivity\n  end.\n\n(** Without lifting a finger, exciting theorems can be proved: *)\n\nTheorem test : forall (a b c d e f g : nat),\n  Some a = Some b\n  -> Some b = Some c\n  -> Some e = Some c\n  -> Some f = Some g\n  -> c = a.\n  intros; deSome.\nQed.\n\n(** Unfortunately, this tactic exhibits some degenerate behavior.  Consider the following example: *)\n\nTheorem test2 : forall (a x1 y1 x2 y2 x3 y3 x4 y4 x5 y5 x6 y6 : nat),\n  Some x1 = Some y1\n  -> Some x2 = Some y2\n  -> Some x3 = Some y3\n  -> Some x4 = Some y4\n  -> Some x5 = Some y5\n  -> Some x6 = Some y6\n  -> Some a = Some a\n  -> x1 = x2.\n  intros.\n  Time try deSome.\nAbort.\n\n(* begin hide *)\nReset test.\n(* end hide *)\n\n(** This (failed) proof already takes about one second on my workstation.  I hope a pattern in the theorem statement is clear; this is a representative of a class of theorems, where we may add more matched pairs of [x] and [y] variables, with equality hypotheses between them.  The running time of [deSome] is exponential in the number of such hypotheses.\n\n   The task in this exercise is twofold.  First, figure out why [deSome] exhibits exponential behavior for this class of examples and record your explanation in a comment.  Second, write an improved version of [deSome] that runs in polynomial time.#</li>#\n\n   %\\item%#<li># Sometimes it can be convenient to know that a proof attempt is doomed because the theorem is false.  For instance, here are three non-theorems about lists: *)\n\nTheorem test1 : forall A (ls1 ls2 : list A), ls1 ++ ls2 = ls2 ++ ls1.\n(* begin hide *)\nAbort.\n(* end hide *)\n\nTheorem test2 : forall A (ls1 ls2 : list A), length (ls1 ++ ls2) = length ls1 - length ls2.\n(* begin hide *)\nAbort.\n(* end hide *)\n\nTheorem test3 : forall A (ls : list A), length (rev ls) - 3 = 0.\n(* begin hide *)\nAbort.\n(* end hide *)\n\n(** The task in this exercise is to write a tactic that disproves these and many other related %``%#\"#theorems#\"#%''% about lists.  Your tactic should follow a simple brute-force enumeration strategy, considering all [list bool] values with length up to some bound given by the user, as a [nat] argument to the tactic.  A successful invocation should add a new hypothesis of the negation of the theorem (guaranteeing that the tactic has made a sound decision about falsehood).\n\n   A few hints: A good starting point is to pattern-match the conclusion formula and use the [assert] tactic on its negation.  An [assert] invocation may include a [by] clause to specify a tactic to use to prove the assertion.\n\n   The idea in this exercise is to disprove a quantified formula by finding instantiations for the quantifiers that make it manifestly false.  Recall the [specialize] tactic for specializing a hypothesis to particular quantifier instantiations.  When you have instantiated quantifiers fully, [discriminate] is a good choice to derive a contradiction.  (It at least works for the three examples above and is smart enough for this exercise's purposes.)  The [type of] Ltac construct may be useful to analyze the type of a hypothesis to choose how to instantiate its quantifiers.\n\n   To enumerate all boolean lists up to a certain length, it will be helpful to write a recursive tactic in continuation-passing style, where the continuation is meant to be called on each candidate list.\n\n   Remember that arguments to Ltac functions may not be type-checked in contexts large enough to allow usual implicit argument inference, so instead of [nil] it will be useful to write [@][nil bool], which specifies the usually implicit argument explicitly.\n\n   %\\item%#<li># Some theorems involving existential quantifiers are easy to prove with [eauto]. *)\n\nTheorem test1 : exists x, x = 0.\n  eauto.\nQed.\n\n(** Others are harder.  The problem with the next theorem is that the existentially quantified variable does not appear in the rest of the theorem, so [eauto] has no way to deduce its value.  However, we know that we had might as well instantiate that variable to [tt], the only value of type [unit]. *)\n\nTheorem test2 : exists x : unit, 0 = 0.\n(* begin hide *)\n  eauto.\nAbort.\n(* end hide *)\n\n(** We also run into trouble in the next theorem, because [eauto] does not understand the [fst] and [snd] projection functions for pairs. *)\n\nTheorem test3 : exists x : nat * nat, fst x = 7 /\\ snd x = 2 + fst x.\n(* begin hide *)\n  eauto.\nAbort.\n(* end hide *)\n\n(** Both problems show up in this monster example. *)\n\nTheorem test4 : exists x : (unit * nat) * (nat * bool),\n  snd (fst x) = 7 /\\ fst (snd x) = 2 + snd (fst x) /\\ snd (snd x) = true.\n(* begin hide *)\n  eauto.\nAbort.\n(* end hide *)\n\n(** The task in this problem is to write a tactic that preprocesses such goals so that [eauto] can finish them.  Your tactic should serve as a complete proof of each of the above examples, along with the wide class of similar examples.  The key smarts that your tactic will bring are: first, it introduces separate unification variables for all the %``%#\"#leaf types#\"#%''% of compound types built out of pairs; and second, leaf unification variables of type [unit] are simply replaced by [tt].\n\n   A few hints: The following tactic is more convenient than direct use of the built-in tactic [evar], for generation of new unification variables: *)\n\nLtac makeEvar T k := let x := fresh in\n  evar (x : T); let y := eval unfold x in x in clear x; k y.\n\n(** remove printing exists *)\n\n(** This is a continuation-passing style tactic.  For instance, when the goal begins with existential quantification over a type [T], the following tactic invocation will create a new unification variable to use as the quantifier instantiation:\n\n[makeEvar T ltac:(][fun x => exists x)] *)\n\n(** printing exists $\\exists$ *)\n\n(** Recall that [exists] formulas are desugared to uses of the [ex] inductive family.  In particular, a pattern like the following can be used to extract the domain of an [exists] quantifier into variable [T]:\n\n[| ]#[#%[%[ |- ex (][A := ?][T) _ ]#]#%]%[ => ...]\n\n    The [equate] tactic used as an example in this chapter will probably be useful, to unify two terms, for instance if the first is a unification variable whose value you want to set.\n[[\nLtac equate E1 E2 := let H := fresh in\n  assert (H : E1 = E2) by reflexivity; clear H.\n]]\n\n    Finally, there are some minor complications surrounding overloading of the [*] operator for both numeric multiplication and Cartesian product for sets (i.e., pair types).  To ensure that an Ltac pattern is using the type version, write it like this:\n\n[| (?T1 * ?T2)%][type => ...]#</li>#\n\n%\\item%#<li># An exercise in the last chapter dealt with automating proofs about rings using [eauto], where we must prove some odd-looking theorems to push proof search in a direction where unification does all the work.  Algebraic proofs consist mostly of rewriting in equations, so we might hope that the [autorewrite] tactic would yield more natural automated proofs.  Indeed, consider this example within the same formulation of ring theory that we dealt with last chapter, where each of the three axioms has been added to the rewrite hint database [cpdt] using [Hint Rewrite]:\n[[\nTheorem test1 : forall a b, a * b * i b = a.\n  intros; autorewrite with cpdt; reflexivity.\nQed.\n]]\n\nSo far so good.  However, consider this further example:\n[[\nTheorem test2 : forall a, a * e * i a * i e = e.\n  intros; autorewrite with cpdt.\n]]\n\nThe goal is merely reduced to [a * (][i a * i e) = e], which of course [reflexivity] cannot prove.  The essential problem is that [autorewrite] does not do backtracking search.  Instead, it follows a %``%#\"#greedy#\"#%''% approach, at each stage choosing a rewrite to perform and then never allowing that rewrite to be undone.  An early mistake can doom the whole process.\n\nThe task in this problem is to use Ltac to implement a backtracking version of [autorewrite] that works much like [eauto], in that its inputs are a database of hint lemmas and a bound on search depth.  Here our search trees will have uses of [rewrite] at their nodes, rather than uses of [eapply] as in the case of [eauto], and proofs must be finished by [reflexivity].\n\nAn invocation to the tactic to prove [test2] might look like this:\n[[\n  rewriter (right_identity, (right_inverse, tt)) 3.\n]]\n\nThe first argument gives the set of lemmas to consider, as a kind of list encoded with pair types.  Such a format cannot be analyzed directly by Gallina programs, but Ltac allows us much more freedom to deconstruct syntax.  For example, to case analyze such a list found in a variable [x], we need only write:\n[[\n  match x with\n    | (?lemma, ?more) => ...\n  end\n]]\n\nIn the body of the case analysis, [lemma] will be bound to the first lemma, and [more] will be bound to the remaining lemmas.  There is no need to consider a case for [tt], our stand-in for [nil].  This is because lack of any matching pattern will trigger failure, which is exactly the outcome we would like upon reaching the end of the lemma list without finding one that applies.  The tactic will fail, triggering backtracking to some previous [match].\n\nThere are different kinds of backtracking, corresponding to different sorts of decisions to be made.  The examples considered above can be handled with backtracking that only reconsiders decisions about the order in which to apply rewriting lemmas.  A full-credit solution need only handle that kind of backtracking, considering all rewriting sequences up to the length bound passed to your tactic.  A good test of this level of applicability is to prove both [test1] and [test2] above.  However, some theorems could only be proved using a smarter tactic that considers not only order of rewriting lemma uses, but also choice of arguments to the lemmas.  That is, at some points in a proof, the same lemma may apply at multiple places within the goal formula, and some choices may lead to stuck proof states while others lead to success.  For an extra challenge (without any impact on the grade for the problem), you might try beefing up your tactic to do backtracking on argument choice, too.#</li>#\n\n#</ol>#%\\end{enumerate}% *)\n\n\n(** * Exercises *)\n\n(** remove printing * *)\n\n(** %\\begin{enumerate}%#<ol>#\n\n%\\item%#<li># Implement a reflective procedure for normalizing systems of linear equations over rational numbers.  In particular, the tactic should identify all hypotheses that are linear equations over rationals where the equation righthand sides are constants.  It should normalize each hypothesis to have a lefthand side that is a sum of products of constants and variables, with no variable appearing multiple times.  Then, your tactic should add together all of these equations to form a single new equation, possibly clearing the original equations.  Some coefficients may cancel in the addition, reducing the number of variables that appear.\n\nTo work with rational numbers, import module [QArith] and use [Local Open Scope Q_scope].  All of the usual arithmetic operator notations will then work with rationals, and there are shorthands for constants 0 and 1.  Other rationals must be written as [num # den] for numerator [num] and denominator [den].  Use the infix operator [==] in place of [=], to deal with different ways of expressing the same number as a fraction.  For instance, a theorem and proof like this one should work with your tactic:\n[[\n  Theorem t2 : forall x y z, (2 # 1) * (x - (3 # 2) * y) == 15 # 1\n    -> z + (8 # 1) * x == 20 # 1\n    -> (-6 # 2) * y + (10 # 1) * x + z == 35 # 1.\n    intros; reifyContext; assumption.\n  Qed.\n]]\n\n  Your solution can work in any way that involves reifying syntax and doing most calculation with a Gallina function.  These hints outline a particular possible solution.  Throughout, the [ring] tactic will be helpful for proving many simple facts about rationals, and tactics like [rewrite] are correctly overloaded to work with rational equality [==].\n\n%\\begin{enumerate}%#<ol>#\n  %\\item%#<li># Define an inductive type [exp] of expressions over rationals (which inhabit the Coq type [Q]).  Include variables (represented as natural numbers), constants, addition, subtraction, and multiplication.#</li>#\n  %\\item%#<li># Define a function [lookup] for reading an element out of a list of rationals, by its position in the list.#</li>#\n  %\\item%#<li># Define a function [expDenote] that translates [exp]s, along with lists of rationals representing variable values, to [Q].#</li>#\n  %\\item%#<li># Define a recursive function [eqsDenote] over [list (exp * Q)], characterizing when all of the equations are true.#</li>#\n  %\\item%#<li># Fix a representation [lhs] of flattened expressions.  Where [len] is the number of variables, represent a flattened equation as [ilist Q len].  Each position of the list gives the coefficient of the corresponding variable.#</li>#\n  %\\item%#<li># Write a recursive function [linearize] that takes a constant [k] and an expression [e] and optionally returns an [lhs] equivalent to [k * e].  This function returns [None] when it discovers that the input expression is not linear.  The parameter [len] of [lhs] should be a parameter of [linearize], too.  The functions [singleton], [everywhere], and [map2] from [DepList] will probably be helpful.  It is also helpful to know that [Qplus] is the identifier for rational addition.#</li>#\n  %\\item%#<li># Write a recursive function [linearizeEqs : list (exp * Q) -> option (lhs * Q)].  This function linearizes all of the equations in the list in turn, building up the sum of the equations.  It returns [None] if the linearization of any constituent equation fails.#</li>#\n  %\\item%#<li># Define a denotation function for [lhs].#</li>#\n  %\\item%#<li># Prove that, when [exp] linearization succeeds on constant [k] and expression [e], the linearized version has the same meaning as [k * e].#</li>#\n  %\\item%#<li># Prove that, when [linearizeEqs] succeeds on an equation list [eqs], then the final summed-up equation is true whenever the original equation list is true.#</li>#\n  %\\item%#<li># Write a tactic [findVarsHyps] to search through all equalities on rationals in the context, recursing through addition, subtraction, and multiplication to find the list of expressions that should be treated as variables.  This list should be suitable as an argument to [expDenote] and [eqsDenote], associating a [Q] value to each natural number that stands for a variable.#</li>#\n  %\\item%#<li># Write a tactic [reify] to reify a [Q] expression into [exp], with respect to a given list of variable values.#</li>#\n  %\\item%#<li># Write a tactic [reifyEqs] to reify a formula that begins with a sequence of implications from linear equalities whose lefthand sides are expressed with [expDenote].  This tactic should build a [list (exp * Q)] representing the equations.  Remember to give an explicit type annotation when returning a nil list, as in [constr:(][@][nil (exp * Q))].#</li>#\n  %\\item%#<li># Now this final tactic should do the job:\n[[\n  Ltac reifyContext :=\n    let ls := findVarsHyps in\n      repeat match goal with\n               | [ H : ?e == ?num # ?den |- _ ] =>\n                 let r := reify ls e in\n                   change (expDenote ls r == num # den) in H;\n                   generalize H\n             end;\n      match goal with\n        | [ |- ?g ] => let re := reifyEqs g in\n            intros;\n              let H := fresh \"H\" in\n              assert (H : eqsDenote ls re); [ simpl in *; tauto\n                | repeat match goal with\n                           | [ H : expDenote _ _ == _ |- _ ] => clear H\n                         end;\n                generalize (linearizeEqsCorrect ls re H); clear H; simpl;\n                  match goal with\n                    | [ |- ?X == ?Y -> _ ] =>\n                      ring_simplify X Y; intro\n                  end ]\n      end.\n]]\n\n#</ol>#%\\end{enumerate}%\n#</li>#\n   \n#</ol>#%\\end{enumerate}% *)\n", "meta": {"author": "shij-hsu", "repo": "coq", "sha": "335711e36628d93d5723d8617b250e90be578d83", "save_path": "github-repos/coq/shij-hsu-coq", "path": "github-repos/coq/shij-hsu-coq/coq-335711e36628d93d5723d8617b250e90be578d83/cpdt/ex/ex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.689501236518262}}
{"text": "From Equations Require Import Equations.\nFrom Coq Require Import ssreflect ssrbool ssrfun.\nFrom mathcomp Require Import ssrnat eqtype seq path order bigop.\nFrom favssr Require Import prelude.\n\nImport Order.POrderTheory.\nImport Order.TotalTheory.\nOpen Scope order_scope.\n\nSection InsertionSort.\nContext {disp : unit} {T : orderType disp}.\n\n(* Definition *)\n\nFixpoint insort (x : T) xs :=\n  if xs is y :: xs' then\n    if x <= y then x :: y :: xs' else y :: insort x xs'\n    else [:: x].\n\nFixpoint isort xs :=\n  if xs is x :: xs' then insort x (isort xs') else [::].\n\n(* Functional Correctness *)\n\nLemma perm_insort x xs : perm_eq (insort x xs) (x :: xs).\nProof.\nelim: xs=>//= y xs IH; case: (_ <= _)=>//.\nrewrite -(perm_cons y) in IH.\napply: perm_trans; first by exact: IH.\nby apply/permP=>/=?; rewrite addnCA.\nQed.\n\nLemma perm_isort xs : perm_eq (isort xs) xs.\nProof.\nelim: xs=>//= x xs IH.\napply: perm_trans; first by apply: perm_insort.\nby rewrite perm_cons.\nQed.\n\nLemma sorted_insort a xs : sorted <=%O (insort a xs) = sorted <=%O xs.\nProof.\nelim: xs=>//= x xs IH.\ncase H: (_ <= _)=>/=; first by rewrite H.\nrewrite !path_sortedE; try by exact: le_trans.\nrewrite (perm_all _ (perm_insort _ _)) /= IH.\nsuff: x <= a by move=>->.\nby rewrite leNgt lt_neqAle H andbF.\nQed.\n\nLemma sorted_isort xs : sorted <=%O (isort xs).\nProof. by elim: xs=>//= x xs; rewrite sorted_insort. Qed.\n\n(* Time complexity *)\n\nFixpoint T_insort (x : T) (xs : seq T) : nat :=\n  if xs is y :: xs' then\n    (if x <= y then 0 else T_insort x xs').+1\n    else 1.\n\nFixpoint T_isort xs : nat :=\n  if xs is x :: xs' then (T_isort xs' + T_insort x (isort xs')).+1 else 1.\n\nLemma T_insort_size x xs : T_insort x xs <= (size xs).+1.\nProof.\nelim: xs=>//=y xs IH.\nby case: (x <= y).\nQed.\n\n(* This seems to be unused *)\nLemma size_insort x xs: size (insort x xs) = (size xs).+1.\nProof. by move/perm_size: (perm_insort x xs). Qed.\n\nLemma size_isort xs : size (isort xs) = size xs.\nProof. by move/perm_size: (perm_isort xs). Qed.\n\nLemma T_isort_size xs : T_isort xs <= (size xs).+1 ^ 2.\nProof.\nelim: xs=>// x xs IH.\nrewrite -addn1 sqrnD /= -addn1 -!addnA.\napply: leq_add=>//; rewrite exp1n muln1 addnC leq_add2l.\napply: leq_trans; first by exact: T_insort_size.\nby rewrite size_isort; apply: leq_pmull.\nQed.\n\n(* Exercise 2.1 *)\n\nLemma isort_beh (f : seq T -> seq T) xs :\n  perm_eq (f xs) xs -> sorted <=%O (f xs) -> f xs = isort xs.\nProof.\nAdmitted.\n\n(* Exercise 2.2.1 *)\n\nLemma T_isort_optimal xs : sorted <=%O xs -> T_isort xs = (2 * size xs).+1.\nProof.\nAdmitted.\n\nEnd InsertionSort.\n\nSection InsertionSortNat.\n\n(* uphalf_addn from prelude might come in handy here *)\n(* Exercise 2.2.2 *)\nLemma T_isort_worst n : T_isort (rev (iota 0 n)) = uphalf ((n.+1)*(n.+2)).\nProof.\nAdmitted.\n\nEnd InsertionSortNat.\n\nSection QuickSort.\nContext {disp : unit} {T : orderType disp}.\n\n(* Definition *)\n\nEquations? quicksort (xs : seq T) : seq T by wf (size xs) lt :=\nquicksort [::]    => [::];\nquicksort (x::xs) => quicksort (filter (< x) xs) ++ [:: x] ++\n                     quicksort (filter (>= x) xs).\nProof.\n- by rewrite size_filter /=; apply/ssrnat.ltP/count_size.\nby rewrite size_filter /=; apply/ssrnat.ltP/count_size.\nQed.\n\n(* Functional Correctness *)\n\nLemma perm_quicksort xs : perm_eq (quicksort xs) xs.\nProof.\napply_funelim (quicksort xs)=>//=x {}xs Hl Hg.\nrewrite perm_catC cat_cons perm_cons perm_sym -(perm_filterC (>= x)) perm_sym.\napply: perm_cat=>//.\nrewrite (eq_in_filter (a2 := < x)) //= =>y _.\nby rewrite ltNge.\nQed.\n\nLemma sorted_quicksort xs : sorted <=%O (quicksort xs).\nProof.\napply_funelim (quicksort xs)=>//= x {}xs Hl Hg.\nhave Hx : sorted <=%O [:: x] by [].\nmove: (merge_sorted le_total Hx Hg)=>{Hx}/=.\nrewrite allrel_merge; last first.\n- by rewrite allrel1l (perm_all _ (perm_quicksort _)) filter_all.\nmove/(merge_sorted le_total Hl); rewrite allrel_merge //=.\napply/allrelP=>y z.\nrewrite (perm_mem (perm_quicksort _) y) inE\n  (perm_mem (perm_quicksort _) z) !mem_filter /=.\ncase/andP=>Hy _; case/orP=>[/eqP ->|/andP [Hz _]];\nrewrite le_eqVlt; apply/orP; right=>//.\nby apply/lt_le_trans/Hz.\nQed.\n\n(* Exercise 2.3 *)\n\nEquations? quicksort2 (xs ys : seq T) : seq T by wf (size xs) lt :=\nquicksort2 xs ys => ys. (* FIXME *)\nProof.\nQed.\n\nLemma quick2_quick xs ys : quicksort2 xs ys = quicksort xs ++ ys.\nProof.\nAdmitted.\n\n(* Exercise 2.4 *)\n\nDefinition partition3 (x : T) (xs : seq T) : seq T * seq T * seq T :=\n  (filter (< x) xs, filter (pred1 x) xs, filter (> x) xs).\n\nEquations? quicksort3 (xs : seq T) : seq T by wf (size xs) lt :=\nquicksort3 [::]    => [::];\nquicksort3 (x::xs) with inspect (partition3 x xs) => {\n  | (ls, es, gs) eqn: eq => quicksort3 ls ++ x :: es ++ quicksort3 gs\n}.\nProof.\n- by apply/ssrnat.ltP; rewrite size_filter; apply: count_size.\nby apply/ssrnat.ltP; rewrite size_filter; apply: count_size.\nQed.\n\n(* this is the main part *)\nLemma quick_filter_ge x xs :\n  quicksort (filter (>= x) xs) = filter (pred1 x) xs ++ quicksort (filter (> x) xs).\nProof.\nAdmitted.\n\nLemma quick3_quick xs : quicksort3 xs = quicksort xs.\nProof.\nAdmitted.\n\n(* Exercise 2.5.1 *)\n\nFixpoint T_filter {A} (ta : A -> nat) (s : seq A) : nat :=\n  if s is x :: s' then ta x + T_filter ta s' + 1 else 1.\n\nLemma T_filter_size {A} (xs : seq A) ta :\n  T_filter ta xs = \\sum_(x<-xs) (ta x) + size xs + 1.\nProof.\nelim: xs=>/=; first by rewrite big_nil.\nby move=>x xs ->; rewrite big_cons -(addn1 (size _)) !addnA.\nQed.\n\nEquations? T_quicksort (xs : seq T) : nat by wf (size xs) lt :=\nT_quicksort [::]    => 1;\nT_quicksort (x::xs) => T_quicksort (filter (< x) xs) +\n                       T_quicksort (filter (>= x) xs) +\n                       2 * T_filter (fun => 1%N) xs + 1.\nProof.\n- by apply/ssrnat.ltP; rewrite size_filter; apply: count_size.\nby apply/ssrnat.ltP; rewrite size_filter; apply: count_size.\nQed.\n\n(* FIXME replace these with concrete numbers *)\nParameters (a b c : nat).\n\nLemma quicksort_quadratic xs : sorted <=%O xs -> T_quicksort xs = a * size xs ^ 2 + b * size xs + c.\nProof.\nAdmitted.\n\n(* Exercise 2.5.2 *)\n\nLemma quicksort_worst xs : T_quicksort xs <= a * size xs ^ 2 + b * size xs + c.\nProof.\nAdmitted.\n\nEnd QuickSort.\n\nSection TopDownMergeSort.\nContext {disp : unit} {T : orderType disp}.\n\n(* reusing `merge` from mathcomp.path *)\n\nEquations? msort (xs : seq T) : seq T by wf (size xs) lt :=\nmsort [::]  => [::];\nmsort [::x] => [::x];\nmsort xs    => let n := size xs in\n               merge <=%O (msort (take n./2 xs))\n                          (msort (drop n./2 xs)).\nProof.\n- by apply/ssrnat.ltP; rewrite size_take /= !ltnS !half_le.\nby apply/ssrnat.ltP; rewrite size_drop /= /leq subSS subnAC subnn.\nQed.\n\n(* Functional Correctness *)\n\nLemma perm_msort xs : perm_eq (msort xs) xs.\nProof.\nfunelim (msort xs)=>//=.\nrewrite perm_merge -{3}(cat_take_drop (size l)./2 (s0::l)) -cat_cons.\nby apply: perm_cat.\nQed.\n\nLemma sorted_msort xs : sorted <=%O (msort xs).\nProof. by funelim (msort xs)=>//=; apply: merge_sorted. Qed.\n\n(* Running Time Analysis *)\n\nFixpoint C_merge (s1 : seq T) :=\n  if s1 is x1 :: s1' then\n    let fix C_merge_s1 (s2 : seq T) :=\n      if s2 is x2 :: s2' then\n        (if x1 <= x2 then C_merge s1' s2 else C_merge_s1 s2').+1\n      else 0 in\n    C_merge_s1\n  else fun => 0.\n\nEquations? C_msort (xs : seq T) : nat by wf (size xs) lt :=\nC_msort [::]  => 0;\nC_msort [::x] => 0;\nC_msort xs    => let n := (size xs) in\n                 let ys := take n./2 xs in\n                 let zs := drop n./2 xs in\n                 C_msort ys + C_msort zs + C_merge (msort ys) (msort zs).\nProof.\n- by apply/ssrnat.ltP; rewrite size_take /= !ltnS !half_le.\nby apply/ssrnat.ltP; rewrite size_drop /= /leq subSS subnAC subnn.\nQed.\n\nLemma C_merge_leq xs ys : (C_merge xs ys <= size xs + size ys)%N.\nProof.\nelim: xs ys=>//= x xs IH1; elim=>//= y ys IH2.\ncase: ifP=>_.\n- rewrite -addn1 -!(addn1 (size _)) addnA leq_add2r addnAC.\n  apply: leq_trans; first by apply: IH1.\n  by rewrite addn1 addnS.\nby rewrite addnS ltnS; apply: IH2.\nQed.\n\nLemma C_msort_leq xs k: size xs = 2^k -> (C_msort xs <= k * 2^k)%N.\nProof.\nelim: k xs=>/=.\n- by move=>xs; rewrite expn0 =>/size1 [x] ->; simp C_msort.\nmove=>k IH xs H.\nhave Hs1 : (size xs > 1)%N by rewrite H -{1}(expn0 2); apply: ltn_exp2l.\ncase: (size2 _ Hs1)=> x[y][ys] He; rewrite He /= in H *; simp C_msort=>/=.\nhave Hp : (size ys)./2.+1 = ((size ys).+2)./2 by rewrite -addn2 halfD andbF /= addn1.\nhave Ht : size (x :: take (size ys)./2 (y :: ys)) = 2^k.\n- by rewrite /= size_take /= ltnS half_le Hp H expnS mul2n half_double.\nhave Hd : size (drop (size ys)./2 (y :: ys)) = 2^k.\n- rewrite size_drop /= subSn; last by apply: half_le.\n  by rewrite half_subn uphalf_half -addnS Hp H expnS mul2n half_double odd2 H oddX.\napply: leq_trans;\n  first by exact: (leq_add (leq_add (IH _ Ht) (IH _ Hd)) (C_merge_leq _ _)).\nrewrite !(perm_size (perm_msort _)) Ht Hd.\nby rewrite !addnn -!muln2 -mulnA -!expnSr -{3}(addn1 k) mulnDl mul1n.\nQed.\n\n(* Exercise 2.6 *)\n\nFixpoint halve {A: Type} (xs ys zs : seq A) : seq A * seq A :=\n  ([::],[::]). (* FIXME *)\n\nEquations? msort2 (xs : seq T) : seq T by wf (size xs) lt :=\nmsort2 [::]  => [::];\nmsort2 [::x] => [::x];\nmsort2 xs with inspect (halve xs [::] [::]) := {\n  | (ys1, ys2) eqn: eq => merge <=%O (msort2 ys1) (msort2 ys2)\n}.\nProof.\n(* FIXME *)\n- by apply/ssrnat.ltP.\nby apply/ssrnat.ltP.\nQed.\n\nLemma perm_msort2 xs : perm_eq (msort2 xs) xs.\nProof.\nAdmitted.\n\nLemma sorted_msort2 xs : sorted <=%O (msort2 xs).\nProof.\nAdmitted.\n\nEnd TopDownMergeSort.\n\nSection BottomUpMergeSort.\nContext {disp : unit} {T : orderType disp}.\n\nEquations merge_adj : seq (seq T) -> seq (seq T) :=\nmerge_adj [::]          => [::];\nmerge_adj [::xs]        => [::xs];\nmerge_adj (xs::ys::zss) => merge <=%O xs ys :: merge_adj zss.\n\nLemma size_merge_adj xss : size (merge_adj xss) = uphalf (size xss).\nProof. by funelim (merge_adj xss)=>//=; congr S. Qed.\n\nEquations? merge_all (xss : seq (seq T)) : seq T by wf (size xss) lt :=\nmerge_all [::]   => [::];\nmerge_all [::xs] => xs;\nmerge_all xss    => merge_all (merge_adj xss).\nProof.\nby apply/ssrnat.ltP; rewrite size_merge_adj /= !ltnS; apply: uphalf_le.\nQed.\n\nDefinition msort_bu (xs : seq T) : seq T :=\n  merge_all (map (fun x => [::x]) xs).\n\n(* Functional Correctness *)\n\nLemma perm_merge_adj xss : perm_eq (flatten (merge_adj xss)) (flatten xss).\nProof.\nfunelim (merge_adj xss)=>//=.\nrewrite catA; apply: perm_cat=>//.\nby rewrite perm_merge.\nQed.\n\nLemma perm_merge_all xss : perm_eq (merge_all xss) (flatten xss).\nProof.\nfunelim (merge_all xss)=>//=; first by rewrite cats0.\nby apply/(perm_trans H)/perm_merge_adj.\nQed.\n\nLemma perm_msort_bu xs : perm_eq (msort_bu xs) xs.\nProof.\nrewrite /msort_bu; apply: (perm_trans (perm_merge_all _)).\nby rewrite flatten_map1 map_id.\nQed.\n\nLemma sorted_merge_adj xss :\n  all (sorted <=%O) xss -> all (sorted <=%O) (merge_adj xss).\nProof.\nfunelim (merge_adj xss)=>//= /and3P [Hs1 Hs2] /H ->; rewrite andbT.\nby apply: merge_sorted.\nQed.\n\nLemma sorted_merge_all xss :\n  all (sorted <=%O) xss -> sorted <=%O (merge_all xss).\nProof.\nfunelim (merge_all xss)=>//=; first by rewrite andbT.\nmove: H; simp merge_adj=>/= H.\ncase/and3P=>Hs1 Hs2 Hs; apply/H/andP.\nby split; [apply: merge_sorted | apply: sorted_merge_adj].\nQed.\n\nLemma sorted_msort_bu xs : sorted <=%O (msort_bu xs).\nProof.\nrewrite /msort_bu; apply: sorted_merge_all; rewrite all_map.\nby elim: xs.\nQed.\n\n(* Running Time Analysis *)\n\nEquations C_merge_adj : seq (seq T) -> nat :=\nC_merge_adj [::]          => 0;\nC_merge_adj [::xs]        => 0;\nC_merge_adj (xs::ys::zss) => C_merge xs ys + C_merge_adj zss.\n\nEquations? C_merge_all (xss : seq (seq T)) : nat by wf (size xss) lt :=\nC_merge_all [::]   => 0;\nC_merge_all [::xs] => 0;\nC_merge_all xss    => C_merge_adj xss + C_merge_all (merge_adj xss).\nProof.\nby apply/ssrnat.ltP; rewrite size_merge_adj /= !ltnS; apply: uphalf_le.\nQed.\n\nDefinition C_msort_bu (xs : seq T) : nat :=\n  C_merge_all (map (fun x => [::x]) xs).\n\nLemma merge_adj_sizes xss m :\n  ~~ odd (size xss) -> all (fun xs => size xs == m) xss ->\n  all (fun xs => size xs == m.*2) (merge_adj xss).\nProof.\nfunelim (merge_adj xss)=>//=; rewrite negbK=>Ho /and3P [/eqP Hx /eqP Hy Ha]; apply/andP.\nsplit; last by rewrite (H _ Ho Ha).\nby rewrite size_merge size_cat Hx Hy addnn.\nQed.\n\nLemma C_merge_adj_leq xss m :\n  all (fun xs => size xs == m) xss -> C_merge_adj xss <= m * size xss.\nProof.\nfunelim (C_merge_adj xss)=>//= /and3P [/eqP Hx /eqP Hy Ha].\nrewrite -add2n mulnDr muln2 -addnn; apply/leq_add/H=>//.\nby rewrite -{1}Hx -Hy; apply: C_merge_leq.\nQed.\n\nLemma C_merge_all_leq xss m k :\n  all (fun xs => size xs == m) xss -> size xss = 2 ^ k ->\n  C_merge_all xss <= m * k * 2^k.\nProof.\nfunelim (C_merge_all xss)=>//= /and3P [/eqP Hx /eqP Hy Ha] Hs.\nmove: H; simp merge_adj C_merge_adj=>/= H. (* slow for some reason *)\nhave [k0 Hk] : { k0 | k = k0.+1 } by move: Hs; case: k=>//=k0 _; exists k0.\nhave He : ~~ odd (size l1) by rewrite odd2 Hs oddX Hk.\nrewrite Hk expnS mulnS mulnDl in Hs *; apply: leq_add.\n- rewrite -Hs -addn2 mulnDr addnC.\n  apply: leq_add; first by apply: C_merge_adj_leq.\n  by rewrite muln2 -addnn -{1}Hx -Hy; apply: C_merge_leq.\nrewrite mulnCA !mulnA mul2n; apply: H.\n- apply/andP; split; last by apply: merge_adj_sizes.\n  by rewrite size_merge size_cat Hx Hy addnn.\napply/eqP; rewrite size_merge_adj -addn1 -(eqn_pmul2r (m:=2)) // mulnDl muln2.\nhave -> : (uphalf (size l1)).*2 = size l1\n  by rewrite -[in RHS](odd_double_half (size l1)) uphalf_half (negbTE He).\nby rewrite addn2 mulnC Hs.\nQed.\n\nLemma C_msort_bu_leq xs k : size xs = 2^k -> C_msort_bu xs <= k * 2^k.\nProof.\nmove=>H; rewrite -(mul1n (_ * _)) mulnA; apply: C_merge_all_leq.\n- by rewrite all_map; elim: {H}xs.\nby rewrite size_map.\nQed.\n\nEnd BottomUpMergeSort.\n\nSection NaturalMergeSort.\nContext {disp : unit} {T : orderType disp}.\n\nFixpoint runs_fix (a : T) (xs : seq T) : seq (seq T) :=\n  if xs is b::bs\n    then if b < a then desc b [:: a] bs else asc b (cons a) bs\n    else [::[::a]]\nwith asc (x : T) (xs : seq T -> seq T) (ys : seq T) : seq (seq T) :=\n  if ys is y::ys'\n    then if x <= y then asc y (xs \\o cons x) ys' else xs [::x] :: runs_fix y ys'\n    else [:: xs [::x]]\nwith desc (x : T) (xs : seq T) (ys : seq T) : seq (seq T) :=\n  if ys is y::ys'\n     then if y < x then desc y (x :: xs) ys' else (x :: xs) :: runs_fix y ys'\n     else [:: (x :: xs)].\n\nDefinition runs (xs : seq T) : seq (seq T) :=\n  if xs is x::xs' then runs_fix x xs' else [::].\n\nDefinition nmsort xs := merge_all (runs xs).\n\n(* Functional Correctness *)\n\nDefinition is_dlist (f : seq T -> seq T) := forall ps qs, f (ps ++ qs) = f ps ++ qs.\n\nLemma perm_runs_asc_desc x xs ys f :\n     perm_eq (flatten (runs_fix x ys)) (x :: ys)\n  /\\ perm_eq (flatten (desc x xs ys)) (x::xs ++ ys)\n  /\\ (is_dlist f ->\n       perm_eq (flatten (asc x f ys)) (x :: f [::] ++ ys)).\nProof.\nelim: ys x xs f=>/=.\n- move=>x xs f; do!split=>//.\n  by move=>H; move: (H [::] [::x])=>/=; rewrite !cats0=>->; rewrite perm_catC.\nmove=>b bs IH x xs f; do!split.\n- case: ifP=>_.\n  - apply: perm_trans; first by case: (IH b [::x] f)=>_ [+ _]; apply.\n    by move: (perm_catCA [::b] [::x] bs)=>/=->.\n  apply: perm_trans; first by case: (IH b [::x] (cons x))=>_ [_] /=; apply.\n  by move: (perm_catCA [::b] [::x] bs)=>/=->.\n- case: ifP=>_.\n  - apply: perm_trans; first by case: (IH b (x::xs) f)=>_ [+ _]; apply.\n    by move: (perm_catCA [::b] (x::xs) bs)=>/=->.\n  rewrite /= -!cat_cons perm_cat2l.\n  by case: (IH b xs f)=>+ _; apply.\nmove=>H; case: ifP=>_.\n- apply: perm_trans.\n  - case: (IH b xs (f \\o cons x))=>_ [_] /=; apply=>ps qs.\n    by rewrite /= -cat_cons; apply: H.\n  move: (H [::] [::x])=>/=->; move: (perm_catCA [::b] (f [::] ++ [::x]) bs)=>/=->.\n  by rewrite -cat_cons perm_cat2r perm_catC.\nmove: (H [::] [::x])=>/=->; rewrite -cat_cons.\napply: perm_cat; first by rewrite perm_catC.\nby case: (IH b xs f)=>+ _; apply.\nQed.\n\nLemma perm_runs xs : perm_eq (flatten (runs xs)) xs.\nProof.\ncase: xs=>//=x xs.\nby case: (perm_runs_asc_desc x [::] xs id).\nQed.\n\nLemma perm_nmsort xs : perm_eq (nmsort xs) xs.\nProof.\nrewrite /nmsort; apply/perm_trans/perm_runs.\nby apply: perm_merge_all.\nQed.\n\nLemma sorted_runs_asc_desc x xs ys f :\n     all (sorted <=%O) (runs_fix x ys)\n  /\\ (sorted <=%O xs -> all (>= x) xs -> all (sorted <=%O) (desc x xs ys))\n  /\\ (is_dlist f -> sorted <=%O (f [::]) -> all (<= x) (f [::]) ->\n      all (sorted <=%O) (asc x f ys)).\nProof.\nelim: ys x xs f=>/=.\n- move=>x xs f; do!split.\n  - by move=>Hs Ha; rewrite andbT (path_sortedE le_trans); apply/andP.\n  move=>Hd Hs Ha; rewrite andbT; move: (Hd [::] [::x])=>/=->.\n  by rewrite cats1; apply: sorted_rcons=>//; exact: le_trans.\nmove=>b ys IH x xs f; do!split.\n- case: ifP=>Ho.\n  - case: (IH b [::x] id)=>_ [+ _]; apply=>//.\n    by rewrite all_seq1 le_eqVlt Ho orbT.\n  case: (IH b xs (cons x))=>_ [_]; apply=>//.\n  by rewrite all_seq1 /= leNgt; apply/negbT.\n- move=>Hs Ha; case: ifP=>Ho /=.\n  - case: (IH b (x::xs) id)=>_ [+ _]; apply=>/=.\n    - by rewrite (path_sortedE le_trans); apply/andP.\n    rewrite le_eqVlt Ho orbT /=; apply/sub_all/Ha=>z.\n    by apply/le_trans; rewrite le_eqVlt Ho orbT.\n  apply/andP; split; first by rewrite (path_sortedE le_trans); apply/andP.\n  by case: (IH b xs f)=>+ _; apply.\nmove=>Hd Hs Ha; case: ifP=>Ho /=.\n- case: (IH b xs (f \\o cons x))=>_ [_] /=; apply.\n  - by move=>ps qs /=; rewrite -cat_cons; apply: Hd.\n  - move: (Hd [::] [::x])=>/=->.\n    by rewrite cats1; apply: sorted_rcons=>//; exact: le_trans.\n  move: (Hd [::] [::x])=>/=->.\n  rewrite cats1 all_rcons /= Ho /=.\n  by apply/sub_all/Ha=>z /= Hx; apply/le_trans/Ho.\napply/andP; split.\n- move: (Hd [::] [::x])=>/=->.\n  by rewrite cats1; apply: sorted_rcons=>//; exact: le_trans.\nby case: (IH b xs id)=>+ _; apply.\nQed.\n\nLemma sorted_runs xs : all (sorted <=%O) (runs xs).\nProof. by case: xs=>//=x xs; case: (sorted_runs_asc_desc x [::] xs id). Qed.\n\nLemma sorted_nmsort xs : sorted <=%O (nmsort xs).\nProof. by rewrite /nmsort; apply/sorted_merge_all/sorted_runs. Qed.\n\n(* Running Time Analysis *)\n\nFixpoint C_runs_fix a xs : nat :=\n  if xs is b::bs\n    then (if b < a then C_desc b bs else C_asc b bs).+1\n    else 0\nwith C_asc (a : T) (xs : seq T) : nat :=\n  if xs is b::bs\n    then (if a <= b then C_asc b bs else C_runs_fix b bs).+1\n    else 0\nwith C_desc (a : T) (xs : seq T) : nat :=\n  if xs is b::bs\n     then (if b < a then C_desc b bs else C_runs_fix b bs).+1\n     else 0.\n\nDefinition C_runs (xs : seq T) : nat :=\n  if xs is x::xs' then C_runs_fix x xs' else 0.\n\nDefinition C_nmsort (xs : seq T) : nat :=\n  C_runs xs + C_merge_all (runs xs).\n\nLemma C_merge_adj_flat (xss : seq (seq T)) : C_merge_adj xss <= size (flatten xss).\nProof.\nfunelim (C_merge_adj xss)=>//=; rewrite catA !size_cat.\nby apply: leq_add=>//; apply: C_merge_leq.\nQed.\n\nLemma merge_adj_flat (xss : seq (seq T)) :\n  size (flatten (merge_adj xss)) = size (flatten xss).\nProof.\nfunelim (merge_adj xss)=>//=.\nby rewrite catA !size_cat H size_merge size_cat.\nQed.\n\nLemma C_merge_adj_log2 (xss : seq (seq T)) : C_merge_all xss <= size (flatten xss) * log2n (size xss).\nProof.\nfunelim (C_merge_all xss)=>//=; move: H; simp C_merge_adj merge_adj.\nrewrite /= !size_cat merge_adj_flat size_merge_adj size_merge size_cat =>IH.\nrewrite log2n_half //= mulnS !addnA; apply: leq_add=>//.\nby apply/leq_add/C_merge_adj_flat/C_merge_leq.\nQed.\n\nLemma size_runs_asc_desc x xs ys f :\n      size (flatten (runs_fix x ys)) = (size ys).+1\n  /\\  size (flatten (desc x xs ys)) = (size xs + size ys).+1\n  /\\ (is_dlist f ->\n      size (flatten (asc x f ys)) = (size (f [::]) + size ys).+1).\nProof.\nelim: ys x xs f=>/=.\n- move=>x xs f; do!split; first by rewrite cats0 addn0.\n  by move=>H; move: (H [::] [::x])=>/=; rewrite !cats0=>->; rewrite size_cat addn0 /= addn1.\nmove=>b bs IH x xs f; do!split.\n- case: ifP=>_.\n  - by case: (IH b [::x] id)=>_ [+ _]; rewrite /= addnC addn1.\n  case: (IH b [::x] (cons x))=>_ [_] /=; rewrite /= addnC addn1; apply.\n  by move=>??; rewrite cat_cons.\n- case: ifP=>_ /=.\n  - by case: (IH b (x::xs) id)=>_ [+ _]; rewrite /= addSnnS.\n  by case: (IH b xs f)=>+ _; rewrite size_cat=>->.\nmove=>H; case: ifP=>_ /=.\n- case: (IH b xs (f \\o cons x))=>_ [_] /=.\n  move: (H [::] [::x])=>/=->; rewrite size_cat /= addnAC -addnA addn1; apply.\n  by move=>?? /=; rewrite -cat_cons; apply: H.\nmove: (H [::] [::x])=>/=->; rewrite !size_cat /=.\nby case: (IH b xs f)=>+ _; rewrite addnAC addn1=>->.\nQed.\n\nLemma size_runs xs : size (flatten (runs xs)) = size xs.\nProof. by case: xs=>//=x xs; case: (size_runs_asc_desc x [::] xs id). Qed.\n\nLemma size_runs_asc_desc_leq x xs ys f :\n      (size (runs_fix x ys) <= (size ys).+1)%N\n  /\\  (size (desc x xs ys) <= (size ys).+1)%N\n  /\\ (is_dlist f ->\n      (size (asc x f ys) <= (size ys).+1)%N).\nProof.\nelim: ys x xs f=>//= b bs IH x xs f; do!split.\n- case: ifP=>_.\n  - by apply: leqW; case: (IH b [::x] id)=>_ [+ _].\n  apply: leqW; case: (IH b [::x] (cons x))=>_ [_]; apply.\n  by move=>??; rewrite cat_cons.\n- case: ifP=>_ /=.\n  - by apply: leqW; case: (IH b (x::xs) id)=>_ [+ _].\n  by rewrite ltnS; case: (IH b xs f)=>+ _ /=.\nmove=>H; case: ifP=>_ /=.\n- apply: leqW; case: (IH b xs (f \\o cons x))=>_ [_] /=; apply.\n  by move=>?? /=; rewrite -cat_cons; apply: H.\nby rewrite ltnS; case: (IH b xs f)=>+ _.\nQed.\n\nLemma size_runs_leq xs : (size (runs xs) <= size xs)%N.\nProof. by case: xs=>//=x xs; case: (size_runs_asc_desc_leq x [::] xs id). Qed.\n\nLemma C_size_runs_asc_desc_leq x ys :\n     (C_runs_fix x ys <= size ys)%N\n  /\\ (C_desc x ys <= size ys)%N\n  /\\ (C_asc x ys <= size ys)%N.\nProof.\nelim: ys x=>//=b bs IH x.\nby do!split; case: ifP=>_; rewrite ltnS; case: (IH b)=>+ [].\nQed.\n\nLemma C_size_runs_leq xs : (C_runs xs <= (size xs).-1)%N.\nProof. by case: xs=>//=x xs; case: (C_size_runs_asc_desc_leq x xs). Qed.\n\nLemma C_merge_runs_leq xs n : size xs = n -> (C_merge_all (runs xs) <= n * log2n n)%N.\nProof.\nmove=>H; apply: leq_trans; first by apply: C_merge_adj_log2.\nrewrite size_runs H leq_mul2l; apply/orP.\ncase: n H=>[H|n H]; first by left.\nright; apply: leq_log2n; rewrite -H.\nby apply: size_runs_leq.\nQed.\n\nLemma C_nmsort_leq xs n : size xs = n -> (C_nmsort xs <= n + n * log2n n)%N.\nProof.\nmove=>H; rewrite /C_nmsort; apply/leq_add/C_merge_runs_leq=>//.\napply: leq_trans; first by apply: C_size_runs_leq.\nby rewrite H; exact: leq_pred.\nQed.\n\nEnd NaturalMergeSort.\n\nSection Stability.\nContext {disp : unit} {A : eqType} {K : orderType disp}.\n\n(* Definition *)\n\nFixpoint insort_key (f : A -> K) (x : A) xs : seq A :=\n  if xs is y :: xs' then\n    if f x <= f y then x :: y :: xs' else y :: insort_key f x xs'\n    else [:: x].\n\nFixpoint isort_key f xs :=\n  if xs is x :: xs' then insort_key f x (isort_key f xs') else [::].\n\nLemma perm_insort_key f x xs : perm_eq (insort_key f x xs) (x :: xs).\nProof.\nelim: xs=>//= y xs IH; case: (_ <= _)=>//.\nrewrite -(perm_cons y) in IH.\napply: perm_trans; first by exact: IH.\nby apply/permP=>/=?; rewrite addnCA.\nQed.\n\nLemma perm_isort_key f xs : perm_eq (isort_key f xs) xs.\nProof.\nelim: xs=>//= x xs IH.\napply: perm_trans; first by apply: perm_insort_key.\nby rewrite perm_cons.\nQed.\n\nLemma sorted_insort_key f a xs :\n  sorted <=%O (map f (insort_key f a xs)) = sorted <=%O (map f xs).\nProof.\nelim: xs=>//= x xs IH.\ncase H: (_ <= _)=>/=; first by rewrite H.\nrewrite !path_sortedE; try by exact: le_trans.\nrewrite !all_map (perm_all _ (perm_insort_key _ _ _)) /= IH.\nsuff: f x <= f a by move=>->.\nby rewrite leNgt lt_neqAle H andbF.\nQed.\n\nLemma sorted_isort_key f xs : sorted <=%O (map f (isort_key f xs)).\nProof. by elim: xs=>//=x xs; rewrite sorted_insort_key. Qed.\n\nLemma insort_key_cons f a xs :\n  all (fun x => f a <= f x) xs -> insort_key f a xs = a :: xs.\nProof. by case: xs=>//=x xs /andP [-> _]. Qed.\n\nLemma filter_not_insort_key (p : pred A) f x xs :\n  ~~ p x -> filter p (insort_key f x xs) = filter p xs.\nProof.\nmove/negbTE=>Hp; elim: xs=>/=; first by rewrite Hp.\nmove=>y xs IH; case: ifP=>_ /=; first by rewrite Hp.\nby rewrite IH.\nQed.\n\nLemma filter_insort_key (p : pred A) f x xs :\n  sorted <=%O (map f xs) -> p x ->\n  filter p (insort_key f x xs) = insort_key f x (filter p xs).\nProof.\nmove/[swap]=>Hp; elim: xs=>/=; first by rewrite Hp.\nmove=>y xs IH; rewrite (path_sortedE le_trans)=>/andP [Ha Hs].\ncase: ifP=>Hf /=.\n- rewrite Hp; case: ifP=>/=; first by rewrite Hf.\n  rewrite insort_key_cons //.\n  rewrite all_map in Ha; rewrite all_filter; apply/sub_all/Ha.\n  by move=>z /= Hf2; apply/implyP=>_; apply/le_trans/Hf2.\ncase: ifP=>/=; rewrite (IH Hs) //.\nby rewrite Hf.\nQed.\n\nLemma isort_key_stable f k xs :\n  filter (fun y => f y == k) (isort_key f xs) = filter (fun y => f y == k) xs.\nProof.\nelim: xs=>//=x xs IH; case: ifP; last first.\n- by move/negbT=>Hk; rewrite filter_not_insort_key.\nmove=>Hk; rewrite filter_insort_key //; last by apply: sorted_isort_key.\nrewrite IH insort_key_cons // all_filter (eq_in_all (a2:=predT)) ?all_predT //.\nby move=>z _ /=; apply/implyP; move/eqP: Hk=>->/eqP->.\nQed.\n\nEnd Stability.\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/func_algo_verif/src/sorting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.6895012338715553}}
{"text": "Require Export GeoCoq.Tarski_dev.Ch03_bet.\n\nSection T3.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma l4_2 : forall A B C D A' B' C' D', IFSC A B C D A' B' C' D' -> Cong B D B' D'.\nProof.\nunfold IFSC.\nintros.\nspliter.\n\ninduction (eq_dec_points A C).\n\ntreat_equalities;assumption.\n\nassert (exists E, Bet A C E /\\ C <> E)\n by apply point_construction_different.\nex_and H6 E.\nprolong A' C' E' C E.\n\nassert  (Cong E D E' D')\n by (\n  apply (five_segment_with_def A C E D A' C' E' D');[\n  unfold OFSC;  repeat split;Cong|\n  assumption]).\n\napply (five_segment_with_def E C B D E' C' B' D').\nunfold OFSC.\nrepeat split; try solve [eBetween| Cong ].\nauto.\nQed.\n\nLemma l4_3 : forall A B C A' B' C',\n  Bet A B C -> Bet A' B' C' -> Cong A C A' C' -> Cong B C B' C' -> Cong A B A' B'.\nProof.\nintros.\napply cong_commutativity.\napply (l4_2 A B C A A' B' C' A').\nunfold IFSC.\nrepeat split;Cong.\nQed.\n\nLemma l4_3_1 : forall A B C A' B' C',\n Bet A B C -> Bet A' B' C' -> Cong A B A' B' -> Cong A C A' C' -> Cong B C B' C'.\nProof.\n    intros.\n    apply cong_commutativity.\n    eapply l4_3;eBetween;Cong.\nQed.\n\nLemma l4_5 : forall A B C A' C',\n  Bet A B C -> Cong A C A' C' ->\n  exists B', Bet A' B' C' /\\ Cong_3 A B C A' B' C'.\nProof.\nintros.\nunfold Cong_3.\n\nassert (exists D', Bet C' A' D' /\\ A' <> D')\n by (apply point_construction_different).\nex_and H1 x'.\nprolong x' A' B' A B.\nprolong x' B' C'' B C.\n\nassert (Bet A' B' C'') by eBetween.\n\nassert (C'' = C').\neapply (construction_uniqueness x' A' ).\n\nauto.\neBetween.\n\napply (l2_11 A' B' C'' A B C);Between.\n\neBetween.\nCong.\n\nsubst C''.\nexists B'.\nrepeat split;Cong.\nQed.\n\nLemma l4_6 : forall A B C A' B' C', Bet A B C -> Cong_3 A B C A' B' C' -> Bet A' B' C'.\nProof.\nunfold Cong_3.\nintros.\nassert (exists B'', Bet A' B'' C' /\\ Cong_3 A B C A' B'' C')\n  by (eapply l4_5;intuition).\nex_and H1 x.\nunfold Cong_3 in *;spliter.\n\nassert (Cong_3 A' x C' A' B' C').\n  unfold Cong_3;repeat split; Cong.\n  apply cong_transitivity with A B; Cong.\n  apply cong_transitivity with B C; Cong.\nunfold Cong_3 in H7;spliter.\n\nassert (IFSC A' x C' x  A' x C' B')\n by (unfold IFSC;repeat split;Cong).\nassert (Cong x x x B')\n by (eapply l4_2;apply H10).\nBetween.\nQed.\n\nLemma cong3_bet_eq : forall  A B C X,\n Bet A B C -> Cong_3 A B C A X C -> X = B.\nProof.\nunfold Cong_3.\nintros.\nspliter.\nassert (IFSC A B C B A B C X)\n by (unfold IFSC;intuition).\nassert (Cong B B B X)\n by (apply (l4_2 _ _ _ _ _ _ _ _ H3)).\nBetween.\nQed.\n\nEnd T3.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/GeoCoq/Tarski_dev/Ch04_cong_bet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.6895012329733512}}
{"text": "\nRequire Export ZArith.\nRequire Export List.\nRequire Export Arith.\nRequire Export ZArithRing.\nRequire Arith.\n\nParameters (prime_divisor : nat->nat)\n           (prime : nat->Prop)\n           (divides : nat->nat->Prop).\n\n(** Tests:\n\nCheck prime (prime_divisor 220).\n\nCheck divides (prime_divisor 220) 220.\n\nCheck divides 3.\n\n*)\n\nParameter binary_word : nat->Set.\n\nDefinition short : Set := binary_word 32.\nDefinition long : Set := binary_word 64.\n\n(** Tests :\n\nCheck ~ divides 3 81.\n\nCheck (let d := prime_divisor 220 in prime d /\\ divides d 220).\n\n*)\n\n\nParameters (decomp : nat -> list nat)\n           (decomp2 : nat->nat*nat).\n\n(** Tests :\n\nCheck decomp 220.\n\nCheck decomp2 284.\n\nCheck forall n:nat, 2<=n ->\n       prime (prime_divisor n) /\\\n       divides (prime_divisor n) n.\n*)\n\nParameter\n  prime_divisor_correct :\n     forall n:nat, 2 <= n -> \n       let d := prime_divisor n in prime d /\\ divides d n.\n\nParameter\n  binary_word_concat :\n     forall n p:nat,\n       binary_word n -> binary_word p -> binary_word (n+p).\n\n(* Tests :\n\nCheck (forall A B :Set, A->B->A*B).\n\n*)\n\nDefinition le_36_37 := le_S 36 36 (le_n 36).\n\nDefinition le_36_38 : 36 <= 38 := le_S 36 37 le_36_37.\n\n(** Tests :\n\nCheck (le_S _ _ (le_S _ _ (le_n 36))).\n\nCheck prime_divisor_correct 220.\n\n*)\n\n\nFixpoint iterate (A:Type)(f:A->A)(n:nat)(x:A) : A :=\n  match n with\n  | O => x\n  | S p => f (iterate A f p x)\n  end.\n\n(** Tests : \nCheck iterate nat.\n\nCheck iterate  _ (mult 2).\n\nCheck (iterate _ (mult 2) 10).\n\nCompute iterate _ (mult 2) 10 1.\n\n\nCheck binary_word_concat 32.\n\nCheck binary_word_concat 32 32.\n*)\n\nArguments iterate {A} _ _ _.\nArguments binary_word_concat {n p} _ _.\nArguments le_S {n m} _.\n\nDefinition binary_word_duplicate (n:nat)(w:binary_word n) \n : binary_word (n+n) :=\n  binary_word_concat  w w.\n\nDefinition short_concat : short -> short -> long \n                        := @binary_word_concat 32 32.\nPrint short_concat.\n\nTheorem le_i_SSi : forall i:nat, i <= S (S i).\nProof (fun i:nat => le_S  (le_S  (le_n i))).\n\n\nDefinition compose {A B C : Type} :  (A->B)->(B->C)->A->C\n   := fun f g x => g (f x).\n\n(** Tests :\n\nCheck fun (A:Type)(f:Z->A) => compose  Z_of_nat f.\n\nCheck compose  Zabs_nat (plus 78) 45%Z.\n\nCheck le_i_SSi 1515.\n\nCheck le_S  (le_i_SSi 1515).\n\nCheck compose (C := Z) S.\n\nCheck @le_S 45.\n\n*)\n\nDefinition thrice {A:Type} (f:A->A) := compose f (compose f f).\n\n\nLemma thrice_as_iter_3 {A:Type} (f: A -> A): thrice f = iterate f 3.\nProof. reflexivity. Qed.\n\nLemma thrice_thrice {A:Type} (f: A -> A): thrice (thrice f) = iterate f 9.\nProof. reflexivity. Qed.\n\nDefinition my_plus : nat->nat->nat := iterate  S.\n\nDefinition my_mult (n p:nat) : nat := iterate  (my_plus n) p 0.\n\nDefinition my_expt (x n:nat) : nat := iterate (my_mult x) n 1.\n\nDefinition ackermann (n:nat) : nat->nat :=\n  iterate (fun (f:nat->nat)(p:nat) => iterate  f (S p) 1) \n          n\n          S.\n\nPrint ackermann.\nParameter f : nat->nat.\nParameter p : nat.\nCheck (f (S p)).\nCompute (f (S p)).\nCheck iterate.\nCheck (iterate f ).\nCheck iterate.\nCheck (fun (f:nat->nat)(p:nat) => iterate  f (S p) 1).\n\n(** Tests :\nCompute my_plus 9 7.\n\nCompute my_expt 2 5.\n\n*)\n\n\n(** Tests :\n\n\nCheck forall P:Prop, P->P.\n\nCheck fun (P:Prop)(p:P) => p.\n\nCheck @refl_equal.\n*)\n\nTheorem ThirtySix : 9*4=6*6.\nProof (refl_equal 36).\n\nDefinition eq_sym  {A:Type}{x y:A}(h : x=y) : y=x :=\n eq_ind  x (fun z => z=x) (refl_equal x) y h.\n\n(** Tests :\n Check eq_sym  ThirtySix. \n\nCheck conj.\n\nCheck or_introl.\n\nCheck or_intror.\n\nCheck and_ind.\n*)\n\nTheorem conj3 : forall P Q R:Prop, P->Q->R->P/\\Q/\\R.\nProof fun P Q R p q r => conj p (conj q r).\n\nTheorem disj4_3 : forall P Q R S:Prop, R -> P\\/Q\\/R\\/S.\nProof \n fun P Q R S r => or_intror _ (or_intror _ (or_introl _ r)).\n\nDefinition proj1' :  forall A B:Prop, A/\\B->A :=\n fun (A B:Prop)(H:A/\\B) => and_ind (fun (H0:A)(_:B) => H0) H.\n\n(** Tests :\n\nCheck ex (fun z:Z => (z*z <= 37 /\\ 37 < (z+1)*(z+1))%Z).\n\nCheck ex_intro.\n\nCheck ex_ind.\n\nCheck and.\n\n*)\n\nCheck ex_ind.\nCheck ex_intro.\n\nTheorem mhy : forall (P : nat -> Prop) (x : nat) , exists x, P x.\nProof.\n  eapply ex_ind. Abort.\n\nTheorem trivialProof : exists n, n = 3.\nProof\n(* @ex_intro nat (fun n => n = 3) 3 eq_refl. *)\nex_intro (fun n => n = 3) 3 eq_refl.\n\nCheck eq_refl.\n\nCheck nil.\n\nFail Check (cons 655 (cons (-273)%Z nil)).\n\n(*The same term with all the implicit arguments given would have had the following form*)\nFail Check (cons (A:=nat) 655 (cons (A:=Z) (-273)%Z (nil (A:=Z)))).", "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/ch4_dependent_product/SRC/chap4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.6895012300112742}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\n(******************************************************************************)\n(* This file deals with divisibility for natural numbers.                     *)\n(* It contains the definitions of:                                            *)\n(*      edivn m d   == the pair composed of the quotient and remainder        *)\n(*                     of the Euclidean division of m by d.                   *)\n(*          m %/ d  == quotient of m by d.                                    *)\n(*          m %% d  == remainder of m by d.                                   *)\n(*  m = n %[mod d]  <-> m equals n modulo d.                                  *)\n(*  m == n %[mod d] <=> m equals n modulo d (boolean version).                *)\n(*  m <> n %[mod d] <-> m differs from n modulo d.                            *)\n(*  m != n %[mod d] <=> m differs from n modulo d (boolean version).          *)\n(*           d %| m <=> d divides m.                                          *)\n(*         gcdn m n == the GCD of m and n.                                    *)\n(*        egcdn m n == the extended GCD of m and n.                           *)\n(*         lcmn m n == the LCM of m and n.                                    *)\n(*      coprime m n <=> m and n are coprime (:= gcdn m n == 1).               *)\n(*  chinese m n r s == witness of the chinese remainder theorem.              *)\n(* We adjoin an m to operator suffixes to indicate a nested %% (modn), as in  *)\n(*   modnDml : m %% d + n = m + n %[mod d].                                   *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** Euclidean division *)\n\nDefinition edivn_rec d :=\n  fix loop m q := if m - d is m'.+1 then loop m' q.+1 else (q, m).\n\nDefinition edivn m d := if d > 0 then edivn_rec d.-1 m 0 else (0, m).\n\nCoInductive edivn_spec m d : nat * nat -> Type :=\n  EdivnSpec q r of m = q * d + r & (d > 0) ==> (r < d) : edivn_spec m d (q, r).\n\nLemma edivnP m d : edivn_spec m d (edivn m d).\nProof.\nrewrite -{1}[m]/(0 * d + m) /edivn; case: d => //= d.\nelim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //= le_mn.\nhave le_m'n: m - d <= n by rewrite (leq_trans (leq_subr d m)).\nrewrite subn_if_gt; case: ltnP => [// | le_dm].\nby rewrite -{1}(subnKC le_dm) -addSn addnA -mulSnr; exact: IHn.\nQed.\n\nLemma edivn_eq d q r : r < d -> edivn (q * d + r) d = (q, r).\nProof.\nmove=> lt_rd; have d_gt0: 0 < d by exact: leq_trans lt_rd.\ncase: edivnP lt_rd => q' r'; rewrite d_gt0 /=.\nwlog: q q' r r' / q <= q' by case/orP: (leq_total q q'); last symmetry; eauto.\nrewrite leq_eqVlt; case/predU1P => [-> /addnI-> |] //=.\nrewrite -(leq_pmul2r d_gt0) => /leq_add lt_qr eq_qr _ /lt_qr {lt_qr}.\nby rewrite addnS ltnNge mulSn -addnA eq_qr addnCA addnA leq_addr.\nQed.\n\nDefinition divn m d := (edivn m d).1.\n\nNotation \"m %/ d\" := (divn m d) : nat_scope.\n\n(* We redefine modn so that it is structurally decreasing. *)\n\nDefinition modn_rec d := fix loop m := if m - d is m'.+1 then loop m' else m.\n\nDefinition modn m d := if d > 0 then modn_rec d.-1 m else m.\n\nNotation \"m %% d\" := (modn m d) : nat_scope.\nNotation \"m = n %[mod d ]\" := (m %% d = n %% d) : nat_scope.\nNotation \"m == n %[mod d ]\" := (m %% d == n %% d) : nat_scope.\nNotation \"m <> n %[mod d ]\" := (m %% d <> n %% d) : nat_scope.\nNotation \"m != n %[mod d ]\" := (m %% d != n %% d) : nat_scope.\n\nLemma modn_def m d : m %% d = (edivn m d).2.\nProof.\ncase: d => //= d; rewrite /modn /edivn /=.\nelim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //=.\nrewrite ltnS !subn_if_gt; case: (d <= m) => // le_mn.\nby apply: IHn; apply: leq_trans le_mn; exact: leq_subr.\nQed.\n\nLemma edivn_def m d : edivn m d = (m %/ d, m %% d).\nProof. by rewrite /divn modn_def; case: (edivn m d). Qed.\n\nLemma divn_eq m d : m = m %/ d * d + m %% d.\nProof. by rewrite /divn modn_def; case: edivnP. Qed.\n\nLemma div0n d : 0 %/ d = 0. Proof. by case: d. Qed.\nLemma divn0 m : m %/ 0 = 0. Proof. by []. Qed.\nLemma mod0n d : 0 %% d = 0. Proof. by case: d. Qed.\nLemma modn0 m : m %% 0 = m. Proof. by []. Qed.\n\nLemma divn_small m d : m < d -> m %/ d = 0.\nProof. by move=> lt_md; rewrite /divn (edivn_eq 0). Qed.\n\nLemma divnMDl q m d : 0 < d -> (q * d + m) %/ d = q + m %/ d.\nProof.\nmove=> d_gt0; rewrite {1}(divn_eq m d) addnA -mulnDl.\nby rewrite /divn edivn_eq // modn_def; case: edivnP; rewrite d_gt0.\nQed.\n\nLemma mulnK m d : 0 < d -> m * d %/ d = m.\nProof. by move=> d_gt0; rewrite -[m * d]addn0 divnMDl // div0n addn0. Qed.\n\nLemma mulKn m d : 0 < d -> d * m %/ d = m.\nProof. by move=> d_gt0; rewrite mulnC mulnK. Qed.\n\nLemma expnB p m n : p > 0 -> m >= n -> p ^ (m - n) = p ^ m %/ p ^ n.\nProof.\nby move=> p_gt0 /subnK{2}<-; rewrite expnD mulnK // expn_gt0 p_gt0.\nQed.\n\nLemma modn1 m : m %% 1 = 0.\nProof. by rewrite modn_def; case: edivnP => ? []. Qed.\n\nLemma divn1 m : m %/ 1 = m.\nProof. by rewrite {2}(@divn_eq m 1) // modn1 addn0 muln1. Qed.\n\nLemma divnn d : d %/ d = (0 < d).\nProof. by case: d => // d; rewrite -{1}[d.+1]muln1 mulKn. Qed.\n\nLemma divnMl p m d : p > 0 -> p * m %/ (p * d) = m %/ d.\nProof.\nmove=> p_gt0; case: (posnP d) => [-> | d_gt0]; first by rewrite muln0.\nrewrite {2}/divn; case: edivnP; rewrite d_gt0 /= => q r ->{m} lt_rd.\nrewrite mulnDr mulnCA divnMDl; last by rewrite muln_gt0 p_gt0.\nby rewrite addnC divn_small // ltn_pmul2l.\nQed.\nImplicit Arguments divnMl [p m d].\n\nLemma divnMr p m d : p > 0 -> m * p %/ (d * p) = m %/ d.\nProof. by move=> p_gt0; rewrite -!(mulnC p) divnMl. Qed.\nImplicit Arguments divnMr [p m d].\n\nLemma ltn_mod m d : (m %% d < d) = (0 < d).\nProof. by case: d => // d; rewrite modn_def; case: edivnP. Qed.\n\nLemma ltn_pmod m d : 0 < d -> m %% d < d.\nProof. by rewrite ltn_mod. Qed.\n\nLemma leq_trunc_div m d : m %/ d * d <= m.\nProof. by rewrite {2}(divn_eq m d) leq_addr. Qed.\n\nLemma leq_mod m d : m %% d  <= m.\nProof. by rewrite {2}(divn_eq m d) leq_addl. Qed.\n\nLemma leq_div m d : m %/ d <= m.\nProof.\nby case: d => // d; apply: leq_trans (leq_pmulr _ _) (leq_trunc_div _ _).\nQed.\n\nLemma ltn_ceil m d : 0 < d -> m < (m %/ d).+1 * d.\nProof.\nby move=> d_gt0; rewrite {1}(divn_eq m d) -addnS mulSnr leq_add2l ltn_mod.\nQed.\n\nLemma ltn_divLR m n d : d > 0 -> (m %/ d < n) = (m < n * d).\nProof.\nmove=> d_gt0; apply/idP/idP.\n  by rewrite -(leq_pmul2r d_gt0); apply: leq_trans (ltn_ceil _ _).\nrewrite !ltnNge -(@leq_pmul2r d n) //; apply: contra => le_nd_floor.\nexact: leq_trans le_nd_floor (leq_trunc_div _ _).\nQed.\n\nLemma leq_divRL m n d : d > 0 -> (m <= n %/ d) = (m * d <= n).\nProof. by move=> d_gt0; rewrite leqNgt ltn_divLR // -leqNgt. Qed.\n\nLemma ltn_Pdiv m d : 1 < d -> 0 < m -> m %/ d < m.\nProof. by move=> d_gt1 m_gt0; rewrite ltn_divLR ?ltn_Pmulr // ltnW. Qed.\n\nLemma divn_gt0 d m : 0 < d -> (0 < m %/ d) = (d <= m).\nProof. by move=> d_gt0; rewrite leq_divRL ?mul1n. Qed.\n\nLemma leq_div2r d m n : m <= n -> m %/ d <= n %/ d.\nProof.\nhave [-> //| d_gt0 le_mn] := posnP d.\nby rewrite leq_divRL // (leq_trans _ le_mn) -?leq_divRL.\nQed.\n\nLemma leq_div2l m d e : 0 < d -> d <= e -> m %/ e <= m %/ d.\nProof.\nmove/leq_divRL=> -> le_de.\nby apply: leq_trans (leq_trunc_div m e); apply: leq_mul.\nQed.\n\nLemma leq_divDl p m n : (m + n) %/ p <= m %/ p + n %/ p + 1.\nProof.\nhave [-> //| p_gt0] := posnP p; rewrite -ltnS -addnS ltn_divLR // ltnW //.\nrewrite {1}(divn_eq n p) {1}(divn_eq m p) addnACA !mulnDl -3!addnS leq_add2l.\nby rewrite mul2n -addnn -addSn leq_add // ltn_mod.\nQed.\n\nLemma geq_divBl k m p : k %/ p - m %/ p <= (k - m) %/ p + 1.\nProof.\nrewrite leq_subLR addnA; apply: leq_trans (leq_divDl _ _ _).\nby rewrite -maxnE leq_div2r ?leq_maxr.\nQed.\n\nLemma divnMA m n p : m %/ (n * p) = m %/ n %/ p. \nProof.\ncase: n p => [|n] [|p]; rewrite ?muln0 ?div0n //.\nrewrite {2}(divn_eq m (n.+1 * p.+1)) mulnA mulnAC !divnMDl //.\nby rewrite [_ %/ p.+1]divn_small ?addn0 // ltn_divLR // mulnC ltn_mod.\nQed.\n\nLemma divnAC m n p : m %/ n %/ p =  m %/ p %/ n.\nProof. by rewrite -!divnMA mulnC. Qed.\n\nLemma modn_small m d : m < d -> m %% d = m.\nProof. by move=> lt_md; rewrite {2}(divn_eq m d) divn_small. Qed.\n\nLemma modn_mod m d : m %% d = m %[mod d].\nProof. by case: d => // d; apply: modn_small; rewrite ltn_mod. Qed.\n\nLemma modnMDl p m d : p * d + m = m %[mod d].\nProof.\ncase: (posnP d) => [-> | d_gt0]; first by rewrite muln0.\nby rewrite {1}(divn_eq m d) addnA -mulnDl modn_def edivn_eq // ltn_mod.\nQed.\n\nLemma muln_modr {p m d} : 0 < p -> p * (m %% d) = (p * m) %% (p * d).\nProof.\nmove=> p_gt0; apply: (@addnI (p * (m %/ d * d))).\nby rewrite -mulnDr -divn_eq mulnCA -(divnMl p_gt0) -divn_eq.\nQed.\n\nLemma muln_modl {p m d} : 0 < p -> (m %% d) * p = (m * p) %% (d * p).\nProof. by rewrite -!(mulnC p); apply: muln_modr. Qed.\n\nLemma modnDl m d : d + m = m %[mod d].\nProof. by rewrite -{1}[d]mul1n modnMDl. Qed.\n\nLemma modnDr m d : m + d = m %[mod d].\nProof. by rewrite addnC modnDl. Qed.\n\nLemma modnn d : d %% d = 0.\nProof. by rewrite -{1}[d]addn0 modnDl mod0n. Qed.\n\nLemma modnMl p d : p * d %% d = 0.\nProof. by rewrite -[p * d]addn0 modnMDl mod0n. Qed.\n\nLemma modnMr p d : d * p %% d = 0.\nProof. by rewrite mulnC modnMl. Qed.\n\nLemma modnDml m n d : m %% d + n = m + n %[mod d].\nProof. by rewrite {2}(divn_eq m d) -addnA modnMDl. Qed.\n\nLemma modnDmr m n d : m + n %% d = m + n %[mod d].\nProof. by rewrite !(addnC m) modnDml. Qed.\n\nLemma modnDm m n d : m %% d  + n %% d = m + n %[mod d].\nProof. by rewrite modnDml modnDmr. Qed.\n\nLemma eqn_modDl p m n d : (p + m == p + n %[mod d]) = (m == n %[mod d]).\nProof.\ncase: d => [|d]; first by rewrite !modn0 eqn_add2l.\napply/eqP/eqP=> eq_mn; last by rewrite -modnDmr eq_mn modnDmr.\nrewrite -(modnMDl p m) -(modnMDl p n) !mulnSr -!addnA.\nby rewrite -modnDmr eq_mn modnDmr.\nQed.\n\nLemma eqn_modDr p m n d : (m + p == n + p %[mod d]) = (m == n %[mod d]).\nProof. by rewrite -!(addnC p) eqn_modDl. Qed.\n\nLemma modnMml m n d : m %% d * n = m * n %[mod d].\nProof. by rewrite {2}(divn_eq m d) mulnDl mulnAC modnMDl. Qed.\n\nLemma modnMmr m n d : m * (n %% d) = m * n %[mod d].\nProof. by rewrite !(mulnC m) modnMml. Qed.\n\nLemma modnMm m n d : m %% d * (n %% d) = m * n %[mod d].\nProof. by rewrite modnMml modnMmr. Qed.\n\nLemma modn2 m : m %% 2 = odd m.\nProof. by elim: m => //= m IHm; rewrite -addn1 -modnDml IHm; case odd. Qed.\n\nLemma divn2 m : m %/ 2 = m./2.\nProof. by rewrite {2}(divn_eq m 2) modn2 muln2 addnC half_bit_double. Qed.\n\nLemma odd_mod m d : odd d = false -> odd (m %% d) = odd m.\nProof.\nby move=> d_even; rewrite {2}(divn_eq m d) odd_add odd_mul d_even andbF.\nQed.\n\nLemma modnXm m n a : (a %% n) ^ m = a ^ m %[mod n].\nProof.\nby elim: m => // m IHm; rewrite !expnS -modnMmr IHm modnMml modnMmr.\nQed.\n\n(** Divisibility **)\n\nDefinition dvdn d m := m %% d == 0.\n\nNotation \"m %| d\" := (dvdn m d) : nat_scope.\n\nLemma dvdnP d m : reflect (exists k, m = k * d) (d %| m).\nProof.\napply: (iffP eqP) => [md0 | [k ->]]; last by rewrite modnMl.\nby exists (m %/ d); rewrite {1}(divn_eq m d) md0 addn0.\nQed.\nImplicit Arguments dvdnP [d m].\nPrenex Implicits dvdnP.\n\nLemma dvdn0 d : d %| 0.\nProof. by case: d. Qed.\n\nLemma dvd0n n : (0 %| n) = (n == 0).\nProof. by case: n. Qed.\n\nLemma dvdn1 d : (d %| 1) = (d == 1).\nProof. by case: d => [|[|d]] //; rewrite /dvdn modn_small. Qed.\n\nLemma dvd1n m : 1 %| m.\nProof. by rewrite /dvdn modn1. Qed.\n\nLemma dvdn_gt0 d m : m > 0 -> d %| m -> d > 0.\nProof. by case: d => // /prednK <-. Qed.\n\nLemma dvdnn m : m %| m.\nProof. by rewrite /dvdn modnn. Qed.\n\nLemma dvdn_mull d m n : d %| n -> d %| m * n.\nProof. by case/dvdnP=> n' ->; rewrite /dvdn mulnA modnMl. Qed.\n\nLemma dvdn_mulr d m n : d %| m -> d %| m * n.\nProof. by move=> d_m; rewrite mulnC dvdn_mull. Qed.\nHint Resolve dvdn0 dvd1n dvdnn dvdn_mull dvdn_mulr.\n\nLemma dvdn_mul d1 d2 m1 m2 : d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2.\nProof.\nby move=> /dvdnP[q1 ->] /dvdnP[q2 ->]; rewrite mulnCA -mulnA 2?dvdn_mull.\nQed.\n\nLemma dvdn_trans n d m : d %| n -> n %| m -> d %| m.\nProof. by move=> d_dv_n /dvdnP[n1 ->]; exact: dvdn_mull. Qed.\n\nLemma dvdn_eq d m : (d %| m) = (m %/ d * d == m).\nProof.\napply/eqP/eqP=> [modm0 | <-]; last exact: modnMl.\nby rewrite {2}(divn_eq m d) modm0 addn0.\nQed.\n\nLemma dvdn2 n : (2 %| n) = ~~ odd n.\nProof. by rewrite /dvdn modn2; case (odd n). Qed.\n\nLemma dvdn_odd m n : m %| n -> odd n -> odd m.\nProof.\nby move=> m_dv_n; apply: contraTT; rewrite -!dvdn2 => /dvdn_trans->.\nQed.\n\nLemma divnK d m : d %| m -> m %/ d * d = m.\nProof. by rewrite dvdn_eq; move/eqP. Qed.\n\nLemma leq_divLR d m n : d %| m -> (m %/ d <= n) = (m <= n * d).\nProof. by case: d m => [|d] [|m] ///divnK=> {2}<-; rewrite leq_pmul2r. Qed.\n\nLemma ltn_divRL d m n : d %| m -> (n < m %/ d) = (n * d < m).\nProof. by move=> dv_d_m; rewrite !ltnNge leq_divLR. Qed.\n\nLemma eqn_div d m n : d > 0 -> d %| m -> (n == m %/ d) = (n * d == m).\nProof. by move=> d_gt0 dv_d_m; rewrite -(eqn_pmul2r d_gt0) divnK. Qed.\n\nLemma eqn_mul d m n : d > 0 -> d %| m -> (m == n * d) = (m %/ d == n).\nProof. by move=> d_gt0 dv_d_m; rewrite eq_sym -eqn_div // eq_sym. Qed.\n\nLemma divn_mulAC d m n : d %| m -> m %/ d * n = m * n %/ d.\nProof.\ncase: d m => [[] //| d m] dv_d_m; apply/eqP.\nby rewrite eqn_div ?dvdn_mulr // mulnAC divnK.\nQed.\n\nLemma muln_divA d m n : d %| n -> m * (n %/ d) = m * n %/ d.\nProof. by move=> dv_d_m; rewrite !(mulnC m) divn_mulAC. Qed.\n\nLemma muln_divCA d m n : d %| m -> d %| n -> m * (n %/ d) = n * (m %/ d).\nProof. by move=> dv_d_m dv_d_n; rewrite mulnC divn_mulAC ?muln_divA. Qed.\n\nLemma divnA m n p : p %| n -> m %/ (n %/ p) = m * p %/ n.\nProof. by case: p => [|p] dv_n; rewrite -{2}(divnK dv_n) // divnMr. Qed.\n\nLemma modn_dvdm m n d : d %| m -> n %% m = n %[mod d].\nProof.\nby case/dvdnP=> q def_m; rewrite {2}(divn_eq n m) {3}def_m mulnA modnMDl.\nQed.\n\nLemma dvdn_leq d m : 0 < m -> d %| m -> d <= m.\nProof. by move=> m_gt0 /dvdnP[[|k] Dm]; rewrite Dm // leq_addr in m_gt0 *. Qed.\n\nLemma gtnNdvd n d : 0 < n -> n < d -> (d %| n) = false.\nProof. by move=> n_gt0 lt_nd; rewrite /dvdn eqn0Ngt modn_small ?n_gt0. Qed.\n\nLemma eqn_dvd m n : (m == n) = (m %| n) && (n %| m).\nProof.\ncase: m n => [|m] [|n] //; apply/idP/andP; first by move/eqP->; auto.\nrewrite eqn_leq => [[Hmn Hnm]]; apply/andP; have:= dvdn_leq; auto.\nQed.\n\nLemma dvdn_pmul2l p d m : 0 < p -> (p * d %| p * m) = (d %| m).\nProof. by case: p => // p _; rewrite /dvdn -muln_modr // muln_eq0. Qed.\nImplicit Arguments dvdn_pmul2l [p m d].\n\nLemma dvdn_pmul2r p d m : 0 < p -> (d * p %| m * p) = (d %| m).\nProof. by move=> p_gt0; rewrite -!(mulnC p) dvdn_pmul2l. Qed.\nImplicit Arguments dvdn_pmul2r [p m d].\n\nLemma dvdn_divLR p d m : 0 < p -> p %| d -> (d %/ p %| m) = (d %| m * p).\nProof. by move=> /(@dvdn_pmul2r p _ m) <- /divnK->. Qed.\n\nLemma dvdn_divRL p d m : p %| m -> (d %| m %/ p) = (d * p %| m).\nProof.\nhave [-> | /(@dvdn_pmul2r p d) <- /divnK-> //] := posnP p.\nby rewrite divn0 muln0 dvdn0.\nQed.\n\nLemma dvdn_div d m : d %| m -> m %/ d %| m.\nProof. by move/divnK=> {2}<-; apply: dvdn_mulr. Qed.\n\nLemma dvdn_exp2l p m n : m <= n -> p ^ m %| p ^ n.\nProof. by move/subnK <-; rewrite expnD dvdn_mull. Qed.\n\nLemma dvdn_Pexp2l p m n : p > 1 -> (p ^ m %| p ^ n) = (m <= n).\nProof.\nmove=> p_gt1; case: leqP => [|gt_n_m]; first exact: dvdn_exp2l.\nby rewrite gtnNdvd ?ltn_exp2l ?expn_gt0 // ltnW.\nQed.\n\nLemma dvdn_exp2r m n k : m %| n -> m ^ k %| n ^ k.\nProof. by case/dvdnP=> q ->; rewrite expnMn dvdn_mull. Qed.\n\nLemma dvdn_addr m d n : d %| m -> (d %| m + n) = (d %| n).\nProof. by case/dvdnP=> q ->; rewrite /dvdn modnMDl. Qed.\n\nLemma dvdn_addl n d m : d %| n -> (d %| m + n) = (d %| m).\nProof. by rewrite addnC; exact: dvdn_addr. Qed.\n\nLemma dvdn_add d m n : d %| m -> d %| n -> d %| m + n.\nProof. by move/dvdn_addr->. Qed.\n\nLemma dvdn_add_eq d m n : d %| m + n -> (d %| m) = (d %| n).\nProof. by move=> dv_d_mn; apply/idP/idP => [/dvdn_addr | /dvdn_addl] <-. Qed.\n\nLemma dvdn_subr d m n : n <= m -> d %| m -> (d %| m - n) = (d %| n).\nProof. by move=> le_n_m dv_d_m; apply: dvdn_add_eq; rewrite subnK. Qed.\n\nLemma dvdn_subl d m n : n <= m -> d %| n -> (d %| m - n) = (d %| m).\nProof. by move=> le_n_m dv_d_m; rewrite -(dvdn_addl _ dv_d_m) subnK. Qed.\n\nLemma dvdn_sub d m n : d %| m -> d %| n -> d %| m - n.\nProof.\nby case: (leqP n m) => [le_nm /dvdn_subr <- // | /ltnW/eqnP ->]; rewrite dvdn0.\nQed.\n\nLemma dvdn_exp k d m : 0 < k -> d %| m -> d %| (m ^ k).\nProof. by case: k => // k _ d_dv_m; rewrite expnS dvdn_mulr. Qed.\n\nHint Resolve dvdn_add dvdn_sub dvdn_exp.\n\nLemma eqn_mod_dvd d m n : n <= m -> (m == n %[mod d]) = (d %| m - n).\nProof.\nby move=> le_mn; rewrite -{1}[n]add0n -{1}(subnK le_mn) eqn_modDr mod0n.\nQed.\n\nLemma divnDl m n d : d %| m -> (m + n) %/ d = m %/ d + n %/ d.\nProof. by case: d => // d /divnK{1}<-; rewrite divnMDl. Qed.\n\nLemma divnDr m n d : d %| n -> (m + n) %/ d = m %/ d + n %/ d.\nProof. by move=> dv_n; rewrite addnC divnDl // addnC. Qed.\n\n(***********************************************************************)\n(*   A function that computes the gcd of 2 numbers                     *)\n(***********************************************************************)\n\nFixpoint gcdn_rec m n :=\n  let n' := n %% m in if n' is 0 then m else\n  if m - n'.-1 is m'.+1 then gcdn_rec (m' %% n') n' else n'.\n\nDefinition gcdn := nosimpl gcdn_rec.\n\nLemma gcdnE m n : gcdn m n = if m == 0 then n else gcdn (n %% m) m.\nProof.\nrewrite /gcdn; elim: m {-2}m (leqnn m) n => [|s IHs] [|m] le_ms [|n] //=.\ncase def_n': (_ %% _) => // [n'].\nhave{def_n'} lt_n'm: n' < m by rewrite -def_n' -ltnS ltn_pmod.\nrewrite {}IHs ?(leq_trans lt_n'm) // subn_if_gt ltnW //=; congr gcdn_rec.\nby rewrite -{2}(subnK (ltnW lt_n'm)) -addnS modnDr.\nQed.\n\nLemma gcdnn : idempotent gcdn.\nProof. by case=> // n; rewrite gcdnE modnn. Qed.\n\nLemma gcdnC : commutative gcdn.\nProof.\nmove=> m n; wlog lt_nm: m n / n < m.\n  by case: (ltngtP n m) => [||-> //]; last symmetry; auto.\nby rewrite gcdnE -{1}(ltn_predK lt_nm) modn_small.\nQed.\n\nLemma gcd0n : left_id 0 gcdn. Proof. by case. Qed.\nLemma gcdn0 : right_id 0 gcdn. Proof. by case. Qed.\n\nLemma gcd1n : left_zero 1 gcdn.\nProof. by move=> n; rewrite gcdnE modn1. Qed.\n\nLemma gcdn1 : right_zero 1 gcdn.\nProof. by move=> n; rewrite gcdnC gcd1n. Qed.\n\nLemma dvdn_gcdr m n : gcdn m n %| n.\nProof.\nelim: m {-2}m (leqnn m) n => [|s IHs] [|m] le_ms [|n] //.\nrewrite gcdnE; case def_n': (_ %% _) => [|n']; first by rewrite /dvdn def_n'.\nhave lt_n's: n' < s by rewrite -ltnS (leq_trans _ le_ms) // -def_n' ltn_pmod.\nrewrite /= (divn_eq n.+1 m.+1) def_n' dvdn_addr ?dvdn_mull //; last exact: IHs.\nby rewrite gcdnE /= IHs // (leq_trans _ lt_n's) // ltnW // ltn_pmod.\nQed.\n\nLemma dvdn_gcdl m n : gcdn m n %| m.\nProof. by rewrite gcdnC dvdn_gcdr. Qed.\n\nLemma gcdn_gt0 m n : (0 < gcdn m n) = (0 < m) || (0 < n).\nProof.\nby case: m n => [|m] [|n] //; apply: (@dvdn_gt0 _ m.+1) => //; exact: dvdn_gcdl.\nQed.\n\nLemma gcdnMDl k m n : gcdn m (k * m + n) = gcdn m n.\nProof. by rewrite !(gcdnE m) modnMDl mulnC; case: m. Qed.\n\nLemma gcdnDl m n : gcdn m (m + n) = gcdn m n.\nProof. by rewrite -{2}(mul1n m) gcdnMDl. Qed.\n\nLemma gcdnDr m n : gcdn m (n + m) = gcdn m n.\nProof. by rewrite addnC gcdnDl. Qed.\n\nLemma gcdnMl n m : gcdn n (m * n) = n.\nProof. by case: n => [|n]; rewrite gcdnE modnMl gcd0n. Qed.\n\nLemma gcdnMr n m : gcdn n (n * m) = n.\nProof. by rewrite mulnC gcdnMl. Qed.\n\nLemma gcdn_idPl {m n} : reflect (gcdn m n = m) (m %| n).\nProof.\nby apply: (iffP idP) => [/dvdnP[q ->] | <-]; rewrite (gcdnMl, dvdn_gcdr).\nQed.\n\nLemma gcdn_idPr {m n} : reflect (gcdn m n = n) (n %| m).\nProof. by rewrite gcdnC; apply: gcdn_idPl. Qed.\n\nLemma expn_min e m n : e ^ minn m n = gcdn (e ^ m) (e ^ n).\nProof.\nrewrite /minn; case: leqP; [rewrite gcdnC | move/ltnW];\n  by move/(dvdn_exp2l e)/gcdn_idPl.\nQed.\n\nLemma gcdn_modr m n : gcdn m (n %% m) = gcdn m n.\nProof. by rewrite {2}(divn_eq n m) gcdnMDl. Qed.\n\nLemma gcdn_modl m n : gcdn (m %% n) n = gcdn m n.\nProof. by rewrite !(gcdnC _ n) gcdn_modr. Qed.\n\n(* Extended gcd, which computes Bezout coefficients. *)\n\nFixpoint Bezout_rec km kn qs :=\n  if qs is q :: qs' then Bezout_rec kn (NatTrec.add_mul q kn km) qs'\n  else (km, kn).\n\nFixpoint egcdn_rec m n s qs :=\n  if s is s'.+1 then\n    let: (q, r) := edivn m n in\n    if r > 0 then egcdn_rec n r s' (q :: qs) else\n    if odd (size qs) then qs else q.-1 :: qs\n  else [::0].\n\nDefinition egcdn m n := Bezout_rec 0 1 (egcdn_rec m n n [::]).\n\nCoInductive egcdn_spec m n : nat * nat -> Type :=\n  EgcdnSpec km kn of km * m = kn * n + gcdn m n & kn * gcdn m n < m :\n    egcdn_spec m n (km, kn).\n\nLemma egcd0n n : egcdn 0 n = (1, 0).\nProof. by case: n. Qed.\n\nLemma egcdnP m n : m > 0 -> egcdn_spec m n (egcdn m n).\nProof.\nrewrite /egcdn; have: (n, m) = Bezout_rec n m [::] by [].\ncase: (posnP n) => [-> /=|]; first by split; rewrite // mul1n gcdn0.\nmove: {2 6}n {4 6}n {1 4}m [::] (ltnSn n) => s n0 m0.\nelim: s n m => [[]//|s IHs] n m qs /= le_ns n_gt0 def_mn0 m_gt0.\ncase: edivnP => q r def_m; rewrite n_gt0 /= => lt_rn.\ncase: posnP => [r0 {s le_ns IHs lt_rn}|r_gt0]; last first.\n  by apply: IHs => //=; [rewrite (leq_trans lt_rn) | rewrite natTrecE -def_m].\nrewrite {r}r0 addn0 in def_m; set b := odd _; pose d := gcdn m n.\npose km := ~~ b : nat; pose kn := if b then 1 else q.-1.\nrewrite (_ : Bezout_rec _ _ _ = Bezout_rec km kn qs); last first.\n  by rewrite /kn /km; case: (b) => //=; rewrite natTrecE addn0 muln1.\nhave def_d: d = n by rewrite /d def_m gcdnC gcdnE modnMl gcd0n -[n]prednK.\nhave: km * m + 2 * b * d = kn * n + d.\n  rewrite {}/kn {}/km def_m def_d -mulSnr; case: b; rewrite //= addn0 mul1n.\n  by rewrite prednK //; apply: dvdn_gt0 m_gt0 _; rewrite def_m dvdn_mulr.\nhave{def_m}: kn * d <= m.\n  have q_gt0 : 0 < q by rewrite def_m muln_gt0 n_gt0 ?andbT in m_gt0.\n  by rewrite /kn; case b; rewrite def_d def_m leq_pmul2r // leq_pred.\nhave{def_d}: km * d <= n by rewrite -[n]mul1n def_d leq_pmul2r // leq_b1.\nmove: km {q}kn m_gt0 n_gt0 def_mn0; rewrite {}/d {}/b.\nelim: qs m n => [|q qs IHq] n r kn kr n_gt0 r_gt0 /=.\n  case=> -> -> {m0 n0}; rewrite !addn0 => le_kn_r _ def_d; split=> //.\n  have d_gt0: 0 < gcdn n r by rewrite gcdn_gt0 n_gt0.\n  have: 0 < kn * n by rewrite def_d addn_gt0 d_gt0 orbT.\n  rewrite muln_gt0 n_gt0 andbT; move/ltn_pmul2l <-.\n  by rewrite def_d -addn1 leq_add // mulnCA leq_mul2l le_kn_r orbT.\nrewrite !natTrecE; set m:= _ + r; set km := _ * _ + kn; pose d := gcdn m n.\nhave ->: gcdn n r = d by rewrite [d]gcdnC gcdnMDl.\nhave m_gt0: 0 < m by rewrite addn_gt0 r_gt0 orbT.\nhave d_gt0: 0 < d by rewrite gcdn_gt0 m_gt0.\nmove/IHq=> {IHq} IHq le_kn_r le_kr_n def_d; apply: IHq => //; rewrite -/d.\n  by rewrite mulnDl leq_add // -mulnA leq_mul2l le_kr_n orbT.\napply: (@addIn d); rewrite -!addnA addnn addnCA mulnDr -addnA addnCA.\nrewrite /km mulnDl mulnCA mulnA -addnA; congr (_ + _).\nby rewrite -def_d addnC -addnA -mulnDl -mulnDr addn_negb -mul2n.\nQed.\n\nLemma Bezoutl m n : m > 0 -> {a | a < m & m %| gcdn m n + a * n}.\nProof.\nmove=> m_gt0; case: (egcdnP n m_gt0) => km kn def_d lt_kn_m.\nexists kn; last by rewrite addnC -def_d dvdn_mull.\napply: leq_ltn_trans lt_kn_m.\nby rewrite -{1}[kn]muln1 leq_mul2l gcdn_gt0 m_gt0 orbT.\nQed.\n\nLemma Bezoutr m n : n > 0 -> {a | a < n & n %| gcdn m n + a * m}.\nProof. by rewrite gcdnC; exact: Bezoutl. Qed.\n\n(* Back to the gcd. *)\n\nLemma dvdn_gcd p m n : p %| gcdn m n = (p %| m) && (p %| n).\nProof.\napply/idP/andP=> [dv_pmn | [dv_pm dv_pn]].\n  by rewrite !(dvdn_trans dv_pmn) ?dvdn_gcdl ?dvdn_gcdr.\ncase (posnP n) => [->|n_gt0]; first by rewrite gcdn0.\ncase: (Bezoutr m n_gt0) => // km _ /(dvdn_trans dv_pn).\nby rewrite dvdn_addl // dvdn_mull.\nQed.\n\nLemma gcdnAC : right_commutative gcdn.\nProof.\nsuffices dvd m n p: gcdn (gcdn m n) p %| gcdn (gcdn m p) n.\n  by move=> m n p; apply/eqP; rewrite eqn_dvd !dvd.\nrewrite !dvdn_gcd dvdn_gcdr.\nby rewrite !(dvdn_trans (dvdn_gcdl _ p)) ?dvdn_gcdl ?dvdn_gcdr.\nQed.\n\nLemma gcdnA : associative gcdn.\nProof. by move=> m n p; rewrite !(gcdnC m) gcdnAC. Qed.\n\nLemma gcdnCA : left_commutative gcdn.\nProof. by move=> m n p; rewrite !gcdnA (gcdnC m). Qed.\n\nLemma gcdnACA : interchange gcdn gcdn.\nProof. by move=> m n p q; rewrite -!gcdnA (gcdnCA n). Qed.\n\nLemma muln_gcdr : right_distributive muln gcdn.\nProof.\nmove=> p m n; case: (posnP p) => [-> //| p_gt0].\nelim: {m}m.+1 {-2}m n (ltnSn m) => // s IHs m n; rewrite ltnS => le_ms.\nrewrite gcdnE [rhs in _ = rhs]gcdnE muln_eq0 (gtn_eqF p_gt0) -muln_modr //=.\nby case: posnP => // m_gt0; apply: IHs; apply: leq_trans le_ms; apply: ltn_pmod.\nQed.\n\nLemma muln_gcdl : left_distributive muln gcdn.\nProof. by move=> m n p; rewrite -!(mulnC p) muln_gcdr. Qed.\n\nLemma gcdn_def d m n :\n    d %| m -> d %| n -> (forall d', d' %| m -> d' %| n -> d' %| d) ->\n  gcdn m n = d.\nProof.\nmove=> dv_dm dv_dn gdv_d; apply/eqP.\nby rewrite eqn_dvd dvdn_gcd dv_dm dv_dn gdv_d ?dvdn_gcdl ?dvdn_gcdr.\nQed.\n\nLemma muln_divCA_gcd n m : n * (m %/ gcdn n m)  = m * (n %/ gcdn n m).\nProof. by rewrite muln_divCA ?dvdn_gcdl ?dvdn_gcdr. Qed.\n\n(* We derive the lcm directly. *)\n\nDefinition lcmn m n := m * n %/ gcdn m n.\n\nLemma lcmnC : commutative lcmn.\nProof. by move=> m n; rewrite /lcmn mulnC gcdnC. Qed.\n\nLemma lcm0n : left_zero 0 lcmn.  Proof. by move=> n; exact: div0n. Qed.\nLemma lcmn0 : right_zero 0 lcmn. Proof. by move=> n; rewrite lcmnC lcm0n. Qed.\n\nLemma lcm1n : left_id 1 lcmn.\nProof. by move=> n; rewrite /lcmn gcd1n mul1n divn1. Qed.\n\nLemma lcmn1 : right_id 1 lcmn.\nProof. by move=> n; rewrite lcmnC lcm1n. Qed.\n\nLemma muln_lcm_gcd m n : lcmn m n * gcdn m n = m * n.\nProof. by apply/eqP; rewrite divnK ?dvdn_mull ?dvdn_gcdr. Qed.\n\nLemma lcmn_gt0 m n : (0 < lcmn m n) = (0 < m) && (0 < n).\nProof. by rewrite -muln_gt0 ltn_divRL ?dvdn_mull ?dvdn_gcdr. Qed.\n\nLemma muln_lcmr : right_distributive muln lcmn.\nProof.\ncase=> // m n p; rewrite /lcmn -muln_gcdr -!mulnA divnMl // mulnCA.\nby rewrite muln_divA ?dvdn_mull ?dvdn_gcdr.\nQed.\n\nLemma muln_lcml : left_distributive muln lcmn.\nProof. by move=> m n p; rewrite -!(mulnC p) muln_lcmr. Qed.\n\nLemma lcmnA : associative lcmn.\nProof.\nmove=> m n p; rewrite {1 3}/lcmn mulnC !divn_mulAC ?dvdn_mull ?dvdn_gcdr //.\nrewrite -!divnMA ?dvdn_mulr ?dvdn_gcdl // mulnC mulnA !muln_gcdr.\nby rewrite ![_ * lcmn _ _]mulnC !muln_lcm_gcd !muln_gcdl -!(mulnC m) gcdnA.\nQed.\n\nLemma lcmnCA : left_commutative lcmn.\nProof. by move=> m n p; rewrite !lcmnA (lcmnC m). Qed.\n\nLemma lcmnAC : right_commutative lcmn.\nProof. by move=> m n p; rewrite -!lcmnA (lcmnC n). Qed.\n\nLemma lcmnACA : interchange lcmn lcmn.\nProof. by move=> m n p q; rewrite -!lcmnA (lcmnCA n). Qed.\n\nLemma dvdn_lcml d1 d2 : d1 %| lcmn d1 d2.\nProof. by rewrite /lcmn -muln_divA ?dvdn_gcdr ?dvdn_mulr. Qed.\n\nLemma dvdn_lcmr d1 d2 : d2 %| lcmn d1 d2.\nProof. by rewrite lcmnC dvdn_lcml. Qed.\n\nLemma dvdn_lcm d1 d2 m : lcmn d1 d2 %| m = (d1 %| m) && (d2 %| m).\nProof.\ncase: d1 d2 => [|d1] [|d2]; try by case: m => [|m]; rewrite ?lcmn0 ?andbF.\nrewrite -(@dvdn_pmul2r (gcdn d1.+1 d2.+1)) ?gcdn_gt0 // muln_lcm_gcd.\nby rewrite muln_gcdr dvdn_gcd {1}mulnC andbC !dvdn_pmul2r.\nQed.\n\nLemma lcmnMl m n : lcmn m (m * n) = m * n.\nProof. by case: m => // m; rewrite /lcmn gcdnMr mulKn. Qed.\n\nLemma lcmnMr m n : lcmn n (m * n) = m * n.\nProof. by rewrite mulnC lcmnMl. Qed.\n\nLemma lcmn_idPr {m n} : reflect (lcmn m n = n) (m %| n).\nProof.\nby apply: (iffP idP) => [/dvdnP[q ->] | <-]; rewrite (lcmnMr, dvdn_lcml).\nQed.\n\nLemma lcmn_idPl {m n} : reflect (lcmn m n = m) (n %| m).\nProof. by rewrite lcmnC; apply: lcmn_idPr. Qed.\n\nLemma expn_max e m n : e ^ maxn m n = lcmn (e ^ m) (e ^ n).\nProof.\nrewrite /maxn; case: leqP; [rewrite lcmnC | move/ltnW];\n by move/(dvdn_exp2l e)/lcmn_idPr.\nQed.\n\n(* Coprime factors *)\n\nDefinition coprime m n := gcdn m n == 1.\n\nLemma coprime1n n : coprime 1 n.\nProof. by rewrite /coprime gcd1n. Qed.\n\nLemma coprimen1 n : coprime n 1.\nProof. by rewrite /coprime gcdn1. Qed.\n\nLemma coprime_sym m n : coprime m n = coprime n m.\nProof. by rewrite /coprime gcdnC. Qed.\n\nLemma coprime_modl m n : coprime (m %% n) n = coprime m n.\nProof. by rewrite /coprime gcdn_modl. Qed.\n\nLemma coprime_modr m n : coprime m (n %% m) = coprime m n.\nProof. by rewrite /coprime gcdn_modr. Qed.\n\nLemma coprime2n n : coprime 2 n = odd n.\nProof. by rewrite -coprime_modr modn2; case: (odd n). Qed.\n\nLemma coprimen2 n : coprime n 2 = odd n.\nProof. by rewrite coprime_sym coprime2n. Qed.\n\nLemma coprimeSn n : coprime n.+1 n.\nProof. by rewrite -coprime_modl (modnDr 1) coprime_modl coprime1n. Qed.\n\nLemma coprimenS n : coprime n n.+1.\nProof. by rewrite coprime_sym coprimeSn. Qed.\n\nLemma coprimePn n : n > 0 -> coprime n.-1 n.\nProof. by case: n => // n _; rewrite coprimenS. Qed.\n\nLemma coprimenP n : n > 0 -> coprime n n.-1.\nProof. by case: n => // n _; rewrite coprimeSn. Qed.\n\nLemma coprimeP n m :\n  n > 0 -> reflect (exists u, u.1 * n - u.2 * m = 1) (coprime n m).\nProof.\nmove=> n_gt0; apply: (iffP eqP) => [<-| [[kn km] /= kn_km_1]].\n  by have [kn km kg _] := egcdnP m n_gt0; exists (kn, km); rewrite kg addKn.\napply gcdn_def; rewrite ?dvd1n // => d dv_d_n dv_d_m.\nby rewrite -kn_km_1 dvdn_subr ?dvdn_mull // ltnW // -subn_gt0 kn_km_1.\nQed.\n\nLemma modn_coprime k n : 0 < k -> (exists u, (k * u) %% n = 1) -> coprime k n.\nProof.\nmove=> k_gt0 [u Hu]; apply/coprimeP=> //.\nby exists (u, k * u %/ n); rewrite /= mulnC {1}(divn_eq (k * u) n) addKn.\nQed.\n\nLemma Gauss_dvd m n p : coprime m n -> (m * n %| p) = (m %| p) && (n %| p).\nProof. by move=> co_mn; rewrite -muln_lcm_gcd (eqnP co_mn) muln1 dvdn_lcm. Qed.\n\nLemma Gauss_dvdr m n p : coprime m n -> (m %| n * p) = (m %| p).\nProof.\ncase: n => [|n] co_mn; first by case: m co_mn => [|[]] // _; rewrite !dvd1n.\nby symmetry; rewrite mulnC -(@dvdn_pmul2r n.+1) ?Gauss_dvd // andbC dvdn_mull.\nQed.\n\nLemma Gauss_dvdl m n p : coprime m p -> (m %| n * p) = (m %| n).\nProof. by rewrite mulnC; apply: Gauss_dvdr. Qed.\n\nLemma Gauss_gcdr p m n : coprime p m -> gcdn p (m * n) = gcdn p n.\nProof.\nmove=> co_pm; apply/eqP; rewrite eqn_dvd !dvdn_gcd !dvdn_gcdl /=.\nrewrite andbC dvdn_mull ?dvdn_gcdr //= -(@Gauss_dvdr _ m) ?dvdn_gcdr //.\nby rewrite /coprime gcdnAC (eqnP co_pm) gcd1n.\nQed.\n\nLemma Gauss_gcdl p m n : coprime p n -> gcdn p (m * n) = gcdn p m.\nProof. by move=> co_pn; rewrite mulnC Gauss_gcdr. Qed.\n\nLemma coprime_mulr p m n : coprime p (m * n) = coprime p m && coprime p n.\nProof.\ncase co_pm: (coprime p m) => /=; first by rewrite /coprime Gauss_gcdr.\napply/eqP=> co_p_mn; case/eqnP: co_pm; apply gcdn_def => // d dv_dp dv_dm.\nby rewrite -co_p_mn dvdn_gcd dv_dp dvdn_mulr.\nQed.\n\nLemma coprime_mull p m n : coprime (m * n) p = coprime m p && coprime n p.\nProof. by rewrite -!(coprime_sym p) coprime_mulr. Qed.\n\nLemma coprime_pexpl k m n : 0 < k -> coprime (m ^ k) n = coprime m n.\nProof.\ncase: k => // k _; elim: k => [|k IHk]; first by rewrite expn1.\nby rewrite expnS coprime_mull -IHk; case coprime.\nQed.\n\nLemma coprime_pexpr k m n : 0 < k -> coprime m (n ^ k) = coprime m n.\nProof. by move=> k_gt0; rewrite !(coprime_sym m) coprime_pexpl. Qed.\n\nLemma coprime_expl k m n : coprime m n -> coprime (m ^ k) n.\nProof. by case: k => [|k] co_pm; rewrite ?coprime1n // coprime_pexpl. Qed.\n\nLemma coprime_expr k m n : coprime m n -> coprime m (n ^ k).\nProof. by rewrite !(coprime_sym m); exact: coprime_expl. Qed.\n\nLemma coprime_dvdl m n p : m %| n -> coprime n p -> coprime m p.\nProof. by case/dvdnP=> d ->; rewrite coprime_mull => /andP[]. Qed.\n\nLemma coprime_dvdr m n p : m %| n -> coprime p n -> coprime p m.\nProof. by rewrite !(coprime_sym p); exact: coprime_dvdl. Qed.\n\nLemma coprime_egcdn n m : n > 0 -> coprime (egcdn n m).1 (egcdn n m).2.\nProof.\nmove=> n_gt0; case: (egcdnP m n_gt0) => kn km /= /eqP.\nhave [/dvdnP[u defn] /dvdnP[v defm]] := (dvdn_gcdl n m, dvdn_gcdr n m).\nrewrite -[gcdn n m]mul1n {1}defm {1}defn !mulnA -mulnDl addnC.\nrewrite eqn_pmul2r ?gcdn_gt0 ?n_gt0 //; case: kn => // kn /eqP def_knu _.\nby apply/coprimeP=> //; exists (u, v); rewrite mulnC def_knu mulnC addnK.\nQed.\n\nLemma dvdn_pexp2r m n k : k > 0 -> (m ^ k %| n ^ k) = (m %| n).\nProof.\nmove=> k_gt0; apply/idP/idP=> [dv_mn_k|]; last exact: dvdn_exp2r.\ncase: (posnP n) => [-> | n_gt0]; first by rewrite dvdn0.\nhave [n' def_n] := dvdnP (dvdn_gcdr m n); set d := gcdn m n in def_n.\nhave [m' def_m] := dvdnP (dvdn_gcdl m n); rewrite -/d in def_m.\nhave d_gt0: d > 0 by rewrite gcdn_gt0 n_gt0 orbT.\nrewrite def_m def_n !expnMn dvdn_pmul2r ?expn_gt0 ?d_gt0 // in dv_mn_k.\nhave: coprime (m' ^ k) (n' ^ k).\n  rewrite coprime_pexpl // coprime_pexpr // /coprime -(eqn_pmul2r d_gt0) mul1n.\n  by rewrite muln_gcdl -def_m -def_n.\nrewrite /coprime -gcdn_modr (eqnP dv_mn_k) gcdn0 -(exp1n k).\nby rewrite (inj_eq (expIn k_gt0)) def_m; move/eqP->; rewrite mul1n dvdn_gcdr.\nQed.\n\nSection Chinese.\n\n(***********************************************************************)\n(*   The chinese remainder theorem                                     *)\n(***********************************************************************)\n\nVariables m1 m2 : nat.\nHypothesis co_m12 : coprime m1 m2.\n\nLemma chinese_remainder x y :\n  (x == y %[mod m1 * m2]) = (x == y %[mod m1]) && (x == y %[mod m2]).\nProof.\nwlog le_yx : x y / y <= x; last by rewrite !eqn_mod_dvd // Gauss_dvd.\nby case/orP: (leq_total y x); last rewrite !(eq_sym (x %% _)); auto.\nQed.\n\n(***********************************************************************)\n(*   A function that solves the chinese remainder problem              *)\n(***********************************************************************)\n\nDefinition chinese r1 r2 :=\n  r1 * m2 * (egcdn m2 m1).1 + r2 * m1 * (egcdn m1 m2).1.\n\nLemma chinese_modl r1 r2 : chinese r1 r2 = r1 %[mod m1].\nProof.\nrewrite /chinese; case: (posnP m2) co_m12 => [-> /eqnP | m2_gt0 _].\n  by rewrite gcdn0 => ->; rewrite !modn1.\ncase: egcdnP => // k2 k1 def_m1 _.\nrewrite mulnAC -mulnA def_m1 gcdnC (eqnP co_m12) mulnDr mulnA muln1.\nby rewrite addnAC (mulnAC _ m1) -mulnDl modnMDl.\nQed.\n\nLemma chinese_modr r1 r2 : chinese r1 r2 = r2 %[mod m2].\nProof.\nrewrite /chinese; case: (posnP m1) co_m12 => [-> /eqnP | m1_gt0 _].\n  by rewrite gcd0n => ->; rewrite !modn1.\ncase: (egcdnP m2) => // k1 k2 def_m2 _.\nrewrite addnC mulnAC -mulnA def_m2 (eqnP co_m12) mulnDr mulnA muln1.\nby rewrite addnAC (mulnAC _ m2) -mulnDl modnMDl.\nQed.\n\nLemma chinese_mod x : x = chinese (x %% m1) (x %% m2) %[mod m1 * m2].\nProof.\napply/eqP; rewrite chinese_remainder //.\nby rewrite chinese_modl chinese_modr !modn_mod !eqxx.\nQed.\n\nEnd Chinese.\n", "meta": {"author": "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/div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.6895012289793381}}
{"text": "Require Import Reals Sums Lra Lia.\n(* Require Import Coquelicot.Hierarchy Coquelicot.Series Coquelicot.Lim_seq Coquelicot.Rbar.*)\nRequire Import Coquelicot.Coquelicot.\nRequire Import LibUtils.\nRequire Import sumtest.\nRequire Import RealAdd.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nSection fold_iter.\n\nLemma fold_right_mult_acc (acc : R) (l : list R) :\n  List.fold_right Rmult acc l =\n  List.fold_right Rmult 1 l * acc.\nProof.\n  revert acc.\n  induction l; simpl; intros acc.\n  - lra.\n  - rewrite IHl.\n    lra.\nQed.\n\nLemma iota_is_an_annoying_seq m n : seq.iota m n = List.seq m n.\nProof.\n  revert m.\n  induction n; simpl; trivial.\nQed.\n\nLemma fold_right_mult_pos {A} (a: A -> posreal) (l:list A) :\n  0 < List.fold_right (fun (a1 : A) (b : R) => a a1 * b) 1 l.\nProof.\n  induction l; simpl.\n  - lra.\n  - apply Rmult_lt_0_compat.\n    + apply cond_pos.\n    + trivial.\nQed.\n\nLemma fold_right_max_upper_list  acc l x :\n  List.In x l -> x <= List.fold_right Rmax acc l.\nProof.\n  induction l; simpl; intros inn; [intuition | ].\n  destruct inn.\n  - subst.    \n    apply Rmax_l.\n  - specialize (IHl H).\n    eapply Rle_trans.\n    + eapply IHl.\n    + apply Rmax_r.\nQed.\n\nLemma fold_right_max_upper_acc acc l :\n  acc <= List.fold_right Rmax acc l.\nProof.\n  induction l; simpl.\n  - lra.\n  - eapply Rle_trans.\n    + eapply IHl.\n    + apply Rmax_r.\nQed.\n\nLemma fold_right_max_in acc l :\n  (List.fold_right Rmax acc l) = acc \\/\n  List.In (List.fold_right Rmax acc l) l.\nProof.\n  induction l; simpl.\n  - intuition.\n  - destruct IHl.\n    + rewrite H.\n      apply Rmax_case; eauto.\n    + apply Rmax_case; eauto.\nQed.\n\nLemma fold_right_max_acc (acc1 acc2 : R) (l : list R) :\n  Rmax acc2 (List.fold_right Rmax acc1 l) =\n  Rmax acc1 (List.fold_right Rmax acc2 l).\nProof.\n  revert acc1 acc2.\n  induction l; simpl; intros acc1 acc2.\n  - apply Rmax_comm.\n  - rewrite Rmax_comm, <- Rmax_assoc.\n    rewrite (Rmax_comm _ acc2).\n    rewrite IHl.\n    rewrite Rmax_assoc.\n    rewrite (Rmax_comm a _).\n    now rewrite <- Rmax_assoc.\nQed.\n\nLemma fold_right_plus_acc {G: AbelianGroup} (f : nat -> G) (acc : G) (l : list nat) :\n  List.fold_right (fun (i : nat) (acc : G) => plus (f i) acc) acc l =\n  plus (List.fold_right (fun (i : nat) (acc : G) => plus (f i) acc) zero l) acc.\nProof.\n  revert acc.\n  induction l; simpl; intros acc.\n  - now rewrite plus_zero_l.\n  - rewrite IHl.\n    now rewrite plus_assoc.\nQed.\n\nLemma fold_right_rmax_const acc l c:\n  0 <= c ->\n  List.fold_right Rmax acc l * c = List.fold_right Rmax (acc*c) (List.map (fun x => x * c) l).\nProof.\n  induction l; simpl; trivial; intros.\n  rewrite <- IHl by trivial.\n  repeat rewrite (Rmult_comm _ c).\n  now rewrite RmaxRmult by trivial.\nQed.\n\n\nLemma iter_plus_times_const {A} F (l:list A)  c :\n        Iter.iter Rplus 0 l (fun k  => F k * c) =\n        Iter.iter Rplus 0 l (fun k => F k) * c.\nProof.\n  induction l; simpl; intros.\n  - lra.\n  - rewrite IHl.\n    lra.\nQed.\n\nLemma list_seq_init_map init len :\n  List.seq init len = List.map (fun x => (init + x)%nat) (List.seq 0 len).\nProof.\n  induction init; simpl.\n  - now rewrite List.map_id.\n  - simpl.\n    rewrite <- List.seq_shift.\n    rewrite IHinit.\n    now rewrite List.map_map.\nQed.    \n\nEnd fold_iter.\n\n\nSection products.\n\nDefinition part_prod_n (a : nat -> posreal) (n m : nat) :R  :=\n  List.fold_right Rmult 1 (List.map (fun x => (a x).(pos)) (List.seq n (S m - n)%nat)).\n\nDefinition part_prod (a : nat -> posreal) (n : nat) : R :=\n  part_prod_n a 0 n.\n\nLemma pos_part_prod_n  (a : nat -> posreal) (m n : nat) :\n  0 < part_prod_n a m n.\nProof.\n  unfold part_prod_n.\n  generalize (S n - m)%nat; intros.\n  revert m.\n  induction n0; simpl; intros m.\n  - lra.\n  - apply Rmult_lt_0_compat; [|trivial].\n    apply cond_pos.\nQed.\n\nLemma pos_part_prod (a : nat -> posreal) (n : nat) :\n  0 < part_prod a n.\nProof.\n  apply pos_part_prod_n.\nQed.\n\nDefinition part_prod_n_pos (a : nat -> posreal) (m n : nat) : posreal :=\n  mkposreal (part_prod_n a m n) (pos_part_prod_n a m n).\n\nDefinition part_prod_pos (a : nat -> posreal) (n : nat) : posreal :=\n  mkposreal (part_prod a n) (pos_part_prod a n).\n\nLemma part_prod_n_S a m n :\n  (m <= S n)%nat ->\n  (part_prod_n a m (S n)) = part_prod_n a m n * a (S n).\nProof.\n  intros mle.\n  unfold part_prod_n.\n  replace (S (S n) - m)%nat with ((S n - m) + 1)%nat by lia.\n  rewrite seq_plus, List.map_app, List.fold_right_app, fold_right_mult_acc.\n  f_equal.\n  simpl.\n  destruct m; simpl.\n  - lra.\n  - field_simplify.\n    simpl.\n    do 3 f_equal.\n    lia.\nQed.\n\nLemma part_prod_n_k_k a k :\n  part_prod_n a k k = a k.\nProof.\n  unfold part_prod_n.\n  replace (S k - k)%nat with (1%nat) by lia.\n  simpl; lra.\nQed.\n\nLemma part_prod_n_1 a m n :\n  (m > n)%nat ->\n  (part_prod_n a m n) = 1.\nProof.\n  intros.\n  unfold part_prod_n.\n  replace (S n - m)%nat with (0%nat) by lia.\n  now simpl.\nQed.  \n\n\nTheorem ln_part_prod (a : nat -> posreal) (n : nat) :\n  ln (part_prod_pos a n) = sum_n (fun n1 => ln (a n1)) n.\nProof.\n  unfold part_prod_pos, part_prod; simpl.\n  unfold sum_n, sum_n_m.\n  unfold Iter.iter_nat.\n  rewrite Iter.iter_iter'.\n  rewrite iota_is_an_annoying_seq.\n  unfold Iter.iter', part_prod_n.\n  generalize (List.seq 0 (S n - 0)); intros l; simpl.\n  rewrite ListAdd.fold_right_map.\n  induction l; simpl.\n  - apply ln_1.\n  - rewrite ln_mult.\n    + now rewrite IHl.\n    + apply cond_pos.\n    + apply fold_right_mult_pos.\nQed.\n\nLemma initial_seg_prod (a : nat -> posreal) (m k:nat):\n  part_prod a (m + S k)%nat = (part_prod a m) * (part_prod_n a (S m) (m + S k)%nat).\nProof.\n  induction k; simpl.\n  - unfold part_prod.\n    replace (m+1)%nat with (S m) by lia.\n    rewrite part_prod_n_S; [|lia].\n    rewrite part_prod_n_k_k; lra.\n  - replace (m + S (S k))%nat with (S (m + S k)%nat) by lia; simpl.\n    unfold part_prod in *.\n    rewrite part_prod_n_S; [|lia].\n    rewrite IHk; simpl.\n    rewrite part_prod_n_S; [|lia]; lra.\nQed.\n\nLemma initial_seg_prod_n (a : nat -> posreal) (k m n:nat):\n  (k <= m)%nat -> \n  part_prod_n a k (S m + n)%nat = (part_prod_n a k m) * (part_prod_n a (S m) (S m + n)%nat).\nProof.\n  intros.\n  induction n; simpl.\n  - replace (m+0)%nat with (m) by lia.\n    rewrite part_prod_n_S.\n    now rewrite part_prod_n_k_k.\n    lia.\n  - rewrite part_prod_n_S; [|lia].\n    rewrite part_prod_n_S; [|lia].\n    replace (m + S n)%nat with (S m + n)%nat by lia.\n    rewrite IHn; lra.\nQed.\n\nLemma part_prod_n_shift (F : nat -> posreal) (m n:nat) :\n  part_prod_n (fun k : nat => F (m + k)%nat) 0 n = part_prod_n F m (n +  m).\nProof.\n  unfold part_prod_n.\n  f_equal.\n  replace (S n - 0)%nat with (S n) by lia.\n  replace (S (n + m) - m)%nat with (S n) by lia.\n  induction n.\n  - simpl.\n    now replace (m + 0)%nat with (m) by lia.\n  - replace (S (S n)) with (S n+1)%nat by lia.\n    rewrite seq_plus, seq_plus, List.map_app.\n    rewrite IHn.\n    replace (S n) with (n+1)%nat by lia.\n    rewrite List.map_app.\n    now simpl.\nQed.    \n\nLemma initial_seg_prod2 (a : nat -> posreal) (m k:nat):\n  part_prod a (k + S m)%nat =\n  (part_prod a m) * (part_prod (fun k0 : nat => a (S m + k0)%nat) k).\nProof.\n  generalize (initial_seg_prod a m k).\n  unfold part_prod.\n  intros.\n  replace (k + S m)%nat with (m + S k)%nat by lia.\n  rewrite H, part_prod_n_shift.\n  now replace (m + S k)%nat with (k + S m)%nat by lia.\nQed.\n\nProgram Definition pos_sq (c : posreal) : posreal :=\n  mkposreal (c * c) _.\nNext Obligation.\n  apply Rmult_lt_0_compat; apply (cond_pos c).\nQed.\n\nDefinition pos_sq_fun (a : nat -> posreal) : (nat -> posreal) :=\n  fun n => pos_sq (a n).\n\nLemma part_prod_pos_sq_pos (a : nat -> posreal) (n:nat) :\n  (part_prod_pos (pos_sq_fun a) n).(pos) = (pos_sq_fun (part_prod_pos a) n).(pos).\nProof.\n  unfold pos_sq_fun, pos_sq, part_prod_pos; simpl.\n  induction n; simpl; trivial.\n  - unfold part_prod, part_prod_n.\n    simpl; lra.\n  - unfold part_prod in *.\n    rewrite part_prod_n_S; [|lia].\n    rewrite IHn; simpl.\n    rewrite part_prod_n_S; [|lia]; lra.\nQed.\n\nLemma inf_prod_sq_0 (a : nat -> posreal) :\n  is_lim_seq (part_prod_pos a) 0 ->\n  is_lim_seq (part_prod_pos (pos_sq_fun a)) 0.\nProof.\n  intros.\n  apply (is_lim_seq_ext (fun n => pos_sq_fun (part_prod_pos a) n)).\n  intros; now rewrite (part_prod_pos_sq_pos a n).\n  simpl; replace (0) with (0 * 0) by lra.\n  now apply is_lim_seq_mult with (l1 := 0) (l2 := 0).\nQed.\n\n\nLemma inf_prod_m_0 (a : nat -> posreal):\n  is_lim_seq (part_prod_pos a) 0 ->\n  forall (m:nat), is_lim_seq (part_prod_pos (fun n => a (m + n)%nat)) 0.\nProof.\n  intros.\n  destruct m.\n  - apply (is_lim_seq_ext (part_prod a)); trivial.\n  - generalize (is_lim_seq_incr_n (part_prod_pos a) (S m) 0).\n    intros.\n    destruct H0.\n    specialize (H0 H).\n    apply (is_lim_seq_ext (fun k => (/ (part_prod a m)) *\n                                  (part_prod a (k + S m)))).\n    + intros.\n      rewrite initial_seg_prod2.\n      rewrite <- Rmult_assoc.\n      rewrite Rmult_comm with (r2 := part_prod a m).\n      rewrite  Rinv_r_simpl_r; trivial.\n      apply Rgt_not_eq.\n      apply Rlt_gt.\n      apply pos_part_prod.\n    + apply is_lim_seq_mult with (l1 := / (part_prod_pos a m)) (l2 := 0).\n      * apply is_lim_seq_const.\n      * apply H0.\n      * unfold is_Rbar_mult; simpl.\n        now rewrite Rmult_0_r.\nQed.\n\nLemma inf_prod_n_m_0 (a : nat -> posreal):\n  is_lim_seq (part_prod_pos a) 0 ->\n  forall (m:nat), is_lim_seq (part_prod_n_pos a m) 0.\nProof.\n  intros.\n  unfold part_prod_n_pos.\n  apply is_lim_seq_incr_n with (N := m).\n  apply (is_lim_seq_ext (fun n : nat => part_prod_pos (fun k : nat => a (m + k)%nat) n)).\n  intros; simpl.\n  unfold part_prod.\n  now rewrite part_prod_n_shift.  \n  now apply inf_prod_m_0.\nQed.  \n\nEnd products.\n\nSection series_sequences.\n\nLemma series_seq (a : nat -> R) (l:R) :\n  is_series a l <-> is_lim_seq (sum_n a) l.\nProof.\n  now unfold is_series, is_lim_seq.\nQed.\n\nLemma log_product_iff_sum_logs (a : nat -> posreal) (l:R): \n  is_lim_seq (fun n => (ln (part_prod_pos a n))) l <-> is_series (fun n => ln (a n)) l .\nProof.\n  rewrite series_seq.\n  split.\n  - apply is_lim_seq_ext; intros.\n    apply ln_part_prod.\n  - apply is_lim_seq_ext; intros.\n    now rewrite <- ln_part_prod.  \nQed.\n\nLemma derivable_pt_ln (x:R) :\n  0 < x -> derivable_pt ln x.\nProof.\n  intros.\n  unfold derivable_pt, derivable_pt_abs.\n  exists (/ x).\n  now apply derivable_pt_lim_ln.\nDefined.\n\nLemma log_product_iff_product (a : nat -> posreal) (l:posreal): \n  is_lim_seq (fun n => (ln (part_prod_pos a n))) (ln l) <-> is_lim_seq (part_prod_pos a) l .\nProof.\n  assert (0 < l) by (apply (cond_pos l)).\n  split; intros.\n  - apply (is_lim_seq_ext (fun n =>  exp (ln (part_prod_pos a n)))).\n    + intros.\n      rewrite exp_ln; f_equal.\n      apply pos_part_prod.\n    + replace (pos l) with (exp (ln (pos l))) by (rewrite exp_ln; trivial).\n      apply is_lim_seq_continuous; [|trivial].\n      apply derivable_continuous_pt; apply derivable_pt_exp.\n  - apply is_lim_seq_continuous; [|trivial].\n    apply derivable_continuous_pt; now apply derivable_pt_ln.\nQed.\n\nLemma is_product_iff_is_log_sum (a : nat -> posreal) (l:posreal) :\n  is_lim_seq (part_prod_pos a) l <-> is_series (fun n => ln (a n)) (ln l).\nProof.\n  rewrite <- log_product_iff_sum_logs.\n  now rewrite log_product_iff_product.\nQed.\n\nLemma is_lim_seq_pos (a : nat -> posreal) (l:R) (lb:posreal):\n  (forall n, lb <= a n) -> is_lim_seq a l -> 0 < l.\nProof.\n  generalize (is_lim_seq_const lb); intros.\n  generalize (is_lim_seq_le (fun _ => lb) a lb l H0 H H1).\n  destruct lb; simpl.\n  lra.\nQed.    \n\nLemma ex_product_iff_ex_log_sum (a : nat -> posreal) (lb:posreal):\n  (forall n, lb <= part_prod_pos a n) -> \n  ex_finite_lim_seq (part_prod_pos a) <-> ex_series (fun n => ln (a n)).\nProof.\n  unfold ex_finite_lim_seq, ex_series.\n  split; intros; destruct H0.\n  - generalize (is_lim_seq_pos (part_prod_pos a) x lb H H0); intros.\n    exists (ln x).\n    now apply is_product_iff_is_log_sum with (l := mkposreal x H1).\n  - exists (exp x).\n    replace (x) with (ln (exp x)) in H0 by apply ln_exp.\n    assert (0 < exp x) by apply exp_pos.\n    now apply is_product_iff_is_log_sum with (l := mkposreal (exp x) H1).\nQed.\n\nLemma sum_split {G : AbelianGroup} (f : nat -> G) (n1 n2 m : nat) :\n  (n1 <= m)%nat -> (m < n2)%nat -> \n  sum_n_m f n1 n2 = plus (sum_n_m f n1 m) (sum_n_m f (S m) n2).\nProof.\n  intros.\n  unfold sum_n_m.\n  unfold Iter.iter_nat.\n  repeat rewrite Iter.iter_iter'.\n  unfold Iter.iter'.\n  rewrite iota_is_an_annoying_seq.\n  rewrite (iota_is_an_annoying_seq n1  (S m - n1)).\n  rewrite (iota_is_an_annoying_seq (S m) (S n2 - S m)).  \n  replace (S n2 - n1)%nat with ((S m - n1) + (S n2 - S m))%nat by lia.\n  rewrite seq_plus.\n  rewrite List.fold_right_app.\n  rewrite fold_right_plus_acc.\n  now replace (n1 + (S m - n1))%nat with (S m) by lia.\nQed.\n\nLemma sum_split_plus {G : AbelianGroup} (f : nat -> G) (n1 n2 k : nat) :\n  (n1 <= n2)%nat -> (0 < k)%nat ->\n  sum_n_m f n1 (n2 + k) = plus (sum_n_m f n1 n2) (sum_n_m f (S n2) (n2 + k)).\nProof.\n  intros.\n  apply sum_split; lia.\nQed.\n\n\n    Lemma seq_sum_shift (α : nat -> R) (nk:nat):\n      is_lim_seq (sum_n α) p_infty ->\n      is_lim_seq (sum_n (fun n0 => α (n0 + nk)%nat)) p_infty.\n    Proof.\n      intros.\n      destruct (Nat.eq_dec nk 0).\n      - subst.\n        eapply (is_lim_seq_ext _ _ _ _ H).\n        Unshelve.\n        intros.\n        apply sum_n_ext.\n        intros.\n        f_equal; lia.\n     -  apply is_lim_seq_incr_n with (N := nk) in H.\n        assert (0 < nk)%nat by lia.\n        apply is_lim_seq_ext \n              with (v := (fun n => ((sum_n α (nk-1)%nat) + \n                                    (sum_n (fun n1 : nat => α (n1 + nk)%nat) n))%R ))\n                   in H.\n        + eapply is_lim_seq_minus with (v := fun _ => sum_n α (nk-1)) in H.\n          * eapply is_lim_seq_ext in H.\n            -- apply H.\n            -- intros; lra.\n          * apply is_lim_seq_const.\n          * unfold is_Rbar_minus, is_Rbar_plus.\n            now simpl.\n        + intros.\n          unfold sum_n.\n          rewrite sum_split with (m := (nk-1)%nat); try lia.\n          apply Rplus_eq_compat_l.\n          replace (S (nk - 1)) with (nk) by lia.\n          apply sum_n_m_shift.\n    Qed.\n\n\n  Lemma ex_seq_sum_shift (α : nat -> R) (nk:nat):\n      ex_lim_seq (sum_n α) ->\n      ex_lim_seq (sum_n (fun n0 => α (n0 + nk)%nat)).\n  Proof.\n    destruct nk.\n    {\n      apply ex_lim_seq_ext; intros.\n      apply sum_n_ext; intros.\n      f_equal; lia.\n    }\n    intros.\n    eapply ex_lim_seq_ext.\n    - intros.\n      apply (sum_n_m_shift α (S nk) n).\n    - unfold sum_n in H.\n      apply (ex_lim_seq_incr_n _ (S nk)) in H.\n      simpl in H.\n\n      cut (ex_lim_seq (fun n : nat => sum_n_m α 0 (nk + S n) - sum_n_m α 0 nk)).\n      {\n        apply ex_lim_seq_ext; intros.\n        rewrite (sum_split_plus α 0 nk (S n)); try lia.\n        unfold plus; simpl.\n        field_simplify.\n        f_equal.\n        lia.\n      }\n      apply ex_lim_seq_minus.\n      + revert H.\n        apply ex_lim_seq_ext; intros.\n        f_equal; lia.\n      + apply ex_lim_seq_const.\n      + rewrite Lim_seq_const.\n        unfold ex_Rbar_minus.\n        apply CoquelicotAdd.ex_Rbar_plus_Finite_r.\n  Qed.\n\n\nLemma nneg_sum_n_m_sq  (a : nat -> R) (n m : nat) :\n  0 <= sum_n_m (fun k => Rsqr (a k)) n m.\nProof.\n  replace (0) with (INR (S m - n) * 0) by lra.\n  rewrite <- sum_n_m_const.\n  apply sum_n_m_le.\n  intros.\n  apply Rle_0_sqr.\nQed.\n\nLemma nneg_series (a : nat -> R) :\n  (forall n, 0 <= a n) ->\n  ex_series a ->\n  0 <= Series a.\nProof.\n  intros.\n  assert (Series (fun _ => 0) = 0).\n  {\n    unfold Series.\n    rewrite <- (Lim_seq_ext (fun _ => 0)).\n    now rewrite Lim_seq_const.\n    intros.\n    rewrite sum_n_const; lra.\n  }\n  rewrite <- H1.\n  apply Series_le; trivial.\n  intros.\n  split; try lra; trivial.\nQed.\n\nLemma nneg_series_sq (a : nat -> R) :\n  ex_series (fun n => Rsqr (a n)) ->\n  0 <= Series (fun n => Rsqr (a n)).\nProof.\n  intros.\n  apply nneg_series; trivial.\n  intros.\n  apply Rle_0_sqr.\nQed.\n\nLemma sub_sum_limit_nneg (a : nat -> R) (n: nat) :\n  (forall n, 0 <= a n) ->\n  ex_series a ->\n  sum_n a n <= Series a.\nProof.\n  intros.\n  assert (0 < S n)%nat by lia.\n  generalize (Series_incr_n a (S n) H1 H0).\n  intros.\n  rewrite H2.\n  rewrite <- sum_n_Reals.\n  replace (Init.Nat.pred (S n)) with (n) by lia.\n  replace (sum_n a n) with (sum_n a n + 0) at 1 by lra.\n  apply Rplus_le_compat_l.\n  apply nneg_series; trivial.\n  rewrite <- (ex_series_incr_n a (S n)); trivial.\nQed.\n\nLemma sub_sum_limit_sq (a : nat -> R) (n: nat) :\n  let fnsq := (fun n => Rsqr (a n)) in      \n  ex_series fnsq ->\n  sum_n fnsq n <= Series fnsq.\nProof.\n  apply sub_sum_limit_nneg.\n  intros.\n  apply Rle_0_sqr.\nQed.\n\nLemma lim_sq_0 (a : nat -> R) :\n  is_series (fun k => Rsqr (a k)) 0 ->\n  forall n, 0 = a n.\nProof.\n  intros.\n  assert (H' := H).\n  apply is_series_unique in H.\n  assert (ex_series (fun k : nat => (a k)²)).\n  unfold ex_series.\n  exists 0; trivial.\n  generalize (sub_sum_limit_sq a n H0); intros.\n  rewrite H in H1.\n  generalize (nneg_sum_n_m_sq  a 0%nat n); intros.\n  unfold sum_n in H1.\n  generalize  (Rle_antisym _ _ H2 H1); intros.\n  induction n.\n  - rewrite sum_n_n in H3; trivial.\n    now rewrite Rsqr_eq_0.\n  - rewrite sum_n_Sm in H3; unfold plus in H3; simpl in H3; [|lia].\n    generalize (Rle_0_sqr (a (S n))); intros.\n    generalize (nneg_sum_n_m_sq  a 0%nat n); intros.    \n    generalize (Rplus_eq_R0 _ _ H4 H5).\n    intros.\n    destruct H6; [lra|].\n    now apply Rsqr_eq_0 in H6.\nQed.\n\nEnd series_sequences.\n\nSection max_prod.\n\nDefinition max_prod_fun (a : nat -> posreal) (m n : nat) : R :=\n  List.fold_right Rmax 0 (List.map (fun k => part_prod_n a k n) (List.seq 0 (S m)%nat)).\n\n\nLemma max_prod_le (F : nat -> posreal) (k m n:nat) :\n  (k <= m)%nat ->\n  (m <= n)%nat ->  \n  part_prod_n F k n <= max_prod_fun F m n.\nProof.\n  intros.\n  unfold max_prod_fun.\n  apply fold_right_max_upper_list.\n  apply List.in_map_iff.\n  exists k.\n  split; trivial.\n  apply List.in_seq; lia.\nQed.\n    \nLemma max_bounded1_pre_le (F : nat -> posreal) (m n:nat) :\n  (forall (n:nat), F n <= 1) ->\n  (S m <= n)%nat ->\n  part_prod_n F m n <= part_prod_n F (S m) n.\nProof.\n  intros.\n  unfold part_prod_n.\n  replace (S n - S m)%nat with (n - m)%nat by lia.\n  replace (S n - m)%nat with (1 + (n - m))%nat by lia.\n  rewrite seq_plus, List.map_app; simpl.\n  replace (m + 1)%nat with (S m) by lia.\n  specialize (H m).\n  rewrite <- Rmult_1_l.\n  apply Rmult_le_compat_r; trivial.\n  rewrite ListAdd.fold_right_map.\n  left; apply fold_right_mult_pos.\nQed.\n\nLemma max_bounded1 (F : nat -> posreal) (m n:nat) :\n  (forall (n:nat), F n <= 1) ->\n  (m <= n)%nat -> max_prod_fun F m n = part_prod_n F m n.\nProof.\n  intros.\n  unfold max_prod_fun.\n  induction m.\n  - apply Rmax_left.\n    left.\n    apply pos_part_prod_n.\n  - replace (S (S m)) with (S m + 1)%nat by lia.\n    rewrite seq_plus, List.map_app, List.fold_right_app.\n    replace (List.fold_right Rmax\n    (List.fold_right Rmax 0 (List.map (fun k : nat => part_prod_n F k n) (List.seq (0 + S m) 1)))\n    (List.map (fun k : nat => part_prod_n F k n) (List.seq 0 (S m))))\n      with\n        (Rmax 0 (List.fold_right Rmax\n    (List.fold_right Rmax 0 (List.map (fun k : nat => part_prod_n F k n) (List.seq (0 + S m) 1)))\n    (List.map (fun k : nat => part_prod_n F k n) (List.seq 0 (S m))))).\n    + rewrite fold_right_max_acc.\n      rewrite IHm by lia.\n      simpl.\n      rewrite (Rmax_left _ 0).\n      * apply Rmax_left.\n        now apply max_bounded1_pre_le.\n      * left; apply pos_part_prod_n.\n    + apply Rmax_right; simpl.\n      apply Rle_trans with (r2 := part_prod_n F 0 n); trivial.\n      left; apply pos_part_prod_n.\n      apply Rmax_l.\nQed.\n\nLemma lim_max_bounded1 (F : nat -> posreal) (m:nat) :\n  (forall (n:nat), F n <= 1) ->\n  is_lim_seq (part_prod F) 0 -> is_lim_seq (fun n => max_prod_fun F m (n+m)%nat) 0.\nProof.\n  intros.\n  apply (is_lim_seq_ext (part_prod (fun k : nat => F (m + k)%nat))).\n  - intros.\n    rewrite max_bounded1; [|trivial|lia].\n    unfold part_prod.\n    apply part_prod_n_shift.\n  - now apply inf_prod_m_0.\nQed.\n\nLemma pos_sq_bounded1 (F : nat -> posreal) (n : nat) :\n  F n <= 1 -> (pos_sq_fun F) n <= 1.\nProof.\n  intros.\n  unfold pos_sq_fun, pos_sq; simpl.\n  replace (1) with (1 * 1) by lra.\n  assert (0 <= F n) by (destruct (F n); simpl; lra).\n  apply Rmult_le_compat; trivial.\nQed.\n\nLemma lim_max_bounded1_sq (F : nat -> posreal) (m:nat) :\n  (forall (n:nat), F n <= 1) ->\n  is_lim_seq (part_prod F) 0 -> is_lim_seq (fun n => max_prod_fun (pos_sq_fun F) m (n+m)%nat) 0.\nProof.\n  intros.\n  apply lim_max_bounded1; intros.\n  now apply pos_sq_bounded1.\n  apply inf_prod_sq_0.\n  apply H0.\nQed.\n\nLemma max_prod_index_n (F : nat -> posreal) (m : nat) (n:nat) (mle:(m <= n)%nat) :\n  exists k : nat,\n    (k <= m)%nat /\\\n     part_prod_n F k n = max_prod_fun F m n.\nProof.\n  unfold max_prod_fun.\n  destruct (fold_right_max_in 0 (List.map (fun k : nat => part_prod_n F k n) (List.seq 0 (S m)))).\n  - generalize (pos_part_prod_n F); intros.\n    simpl in H.\n    generalize (Rmax_l  (part_prod_n F 0 n) (List.fold_right Rmax 0 (List.map (fun k : nat => part_prod_n F k n) (List.seq 1 m)))); intros ineq1.\n    rewrite H in ineq1.\n    specialize (H0 0%nat n); lra.\n  - rewrite List.in_map_iff in H.\n    destruct H as [k [keqq ink]].\n    apply List.in_seq in ink.\n    exists k.\n    split; trivial; lia.\nQed.\n\nLemma max_prod_n_S (a: nat -> posreal) (m n : nat) :\n  (m <= n)%nat ->\n  (max_prod_fun a m (S n)) = max_prod_fun a m n * a (S n).\nProof.\n  intros mle.\n  unfold max_prod_fun.\n  rewrite fold_right_rmax_const.\n  - rewrite List.map_map.\n    f_equal.\n    + lra.\n    + apply List.map_ext_in; intros.\n      apply List.in_seq in H.\n      apply part_prod_n_S.\n      lia.\n  - left. apply cond_pos. \nQed.  \n\nLemma initial_max_prod_n (a : nat -> posreal) (k m n:nat):\n  (k <= m)%nat -> \n  max_prod_fun a k (S m + n)%nat = (max_prod_fun a k m) * (part_prod_n a (S m) (S m + n)%nat).\nProof.\n  intros.\n  induction n; simpl.\n  - replace (m+0)%nat with (m) by lia.\n    rewrite part_prod_n_k_k, max_prod_n_S; trivial.\n  - rewrite part_prod_n_S; [|lia].\n    rewrite max_prod_n_S; [|lia].\n    replace (m + S n)%nat with (S m + n)%nat by lia.\n    rewrite IHn; lra.\nQed.\n\nLemma max_prod_index (F : nat -> posreal) (m:nat) :\n  exists (k:nat), (k<=m)%nat /\\\n                  forall (n:nat), (m <= n)%nat ->\n                  part_prod_n F k n = max_prod_fun F m n.\nProof.\n  intros.\n  assert (m <= m)%nat by lia.\n  generalize (max_prod_index_n F m m H); intros.\n  destruct H0 as [k H0]; destruct H0.\n  exists k.\n  split; trivial; intros.\n  destruct (lt_dec m n).\n  + remember (n - S m)%nat as nm.\n    replace (n) with (S m + nm)%nat; [|lia].\n    rewrite initial_seg_prod_n; trivial.\n    rewrite initial_max_prod_n; trivial.\n    now rewrite H1.\n  + replace (n) with (m) by lia.\n    now rewrite H1.\nQed.\n\nLemma lim_max_prod_m_0 (a : nat -> posreal):\n  is_lim_seq (part_prod_pos a) 0 -> \n  forall (m:nat), is_lim_seq (max_prod_fun a m) 0.\nProof.\n  intros.\n  generalize (max_prod_index a m); intros.\n  destruct H0 as [k H0]; destruct H0.\n  apply is_lim_seq_incr_n with (N:=m).\n  apply (is_lim_seq_ext (fun n => part_prod_n a k (n+m)%nat)).\n  intros; apply H1; lia.\n  generalize (inf_prod_n_m_0 a H k); intros.\n  apply is_lim_seq_incr_n.\n  now unfold part_prod_n_pos in H2; simpl in H2.\nQed.\n\nEnd max_prod.\n\nLemma prod_sq_bounded_1 (F : nat -> posreal) (r s :nat) :\n  (forall (n:nat), F n <= 1) -> part_prod_n (pos_sq_fun F) r s <= 1.\nProof.\n  intros.\n  generalize (pos_sq_bounded1 F); intros.\n  unfold part_prod_n.\n  induction (S s-r)%nat.\n  - simpl.\n    lra.\n  - replace (S n) with (n+1)%nat by lia.\n    rewrite seq_plus, List.map_app, List.fold_right_app; simpl.\n    replace (1) with (1*1) at 2 by lra.\n    rewrite fold_right_mult_acc.\n    apply Rmult_le_compat; trivial.\n    + rewrite ListAdd.fold_right_map; left.\n      apply (fold_right_mult_pos (pos_sq_fun F)).\n    + left; apply Rmult_lt_0_compat; [|lra].\n      apply Rmult_lt_0_compat; apply cond_pos.\n    + rewrite Rmult_1_r, <- Rmult_1_r.\n      apply Rmult_le_compat; trivial.\n      left; apply cond_pos.\n      left; apply cond_pos.      \nQed.\n\nLemma part_prod_le (F : nat -> posreal) (m k n:nat) :\n  (forall (n:nat), F n <= 1) ->\n  (m + k <= n)%nat ->\n  part_prod_n (pos_sq_fun F) m n <= part_prod_n (pos_sq_fun F) (m + k)%nat n.\nProof.\n  intros.\n  induction k.\n  - replace (m + 0)%nat with (m) by lia; lra.\n  - assert (m + k <= n)%nat by lia.\n    specialize (IHk H1).\n    apply Rle_trans with (r2 := part_prod_n (pos_sq_fun F) (m + k) n); trivial.\n    replace (m + S k)%nat with (S (m+k)%nat) by lia.\n    destruct (le_gt_dec (S (m+k)) n).\n    + apply max_bounded1_pre_le; trivial.\n      intros; apply pos_sq_bounded1; trivial.\n    + rewrite (part_prod_n_1 (pos_sq_fun F) (S (m + k)%nat)) ; [|lia].\n      apply prod_sq_bounded_1; trivial.\nQed.      \n\nSection Dvoretsky.\n\nTheorem Dvoretzky4_0 (F: nat -> posreal) (sigma V : nat -> R) :\n  (forall (n:nat), V (S n) <= (F n) * (V n) + (sigma n)) ->\n  (forall (n:nat), \n      V (S n) <= sum_n (fun k => (sigma k)*(part_prod_n F (S k) n)) n + \n                 (V 0%nat)*(part_prod_n F 0 n)).\nProof.\n  intros.\n  induction n.\n  - unfold sum_n, part_prod_n; simpl.\n    unfold sum_n_m, Iter.iter_nat; simpl.\n    specialize (H 0%nat).\n    unfold plus, zero; simpl; lra.\n  - rewrite sum_Sn.\n    unfold sum_n in *.\n    unfold sum_n_m, Iter.iter_nat in *; simpl.\n    unfold plus, zero in *; simpl in *.\n    rewrite (Iter.iter_ext _ _ _ (fun k : nat => sigma k * part_prod_n F (S k) (S n))\n                           (fun k : nat => (sigma k * part_prod_n F (S k) n) * F (S n))).\n    + rewrite iter_plus_times_const.\n      specialize (H (S n)).\n      rewrite part_prod_n_S; [|lia].\n      rewrite (part_prod_n_1 _ (S (S n)) (S n)); [|lia].\n      rewrite part_prod_n_S; [|lia].\n      apply Rle_trans with (r2 := F (S n) * V (S n) + sigma (S n)); trivial.\n      apply Rmult_le_compat_l with (r:=F (S n)) in IHn.\n      apply Rplus_le_compat_r with (r:=sigma (S n))  in IHn.\n      lra.\n      left; apply cond_pos.\n    + intros.\n      rewrite part_prod_n_S.\n      * lra.\n      * generalize (Iter.In_iota 1 x n); intros HH.\n        replace (S n - 1)%nat with n in HH by lia.\n        apply HH in H0; lia.\nQed.\n\nLemma sum_bound_prod_A (F : nat -> posreal) (sigma : nat -> R) (A : R) (n m:nat) :\n  (forall r s, part_prod_n (pos_sq_fun F) r s <= A) ->\n  sum_n_m (fun k => (Rsqr (sigma k))*(part_prod_n (pos_sq_fun F) (S k) n)) (S m) n <=\n  (sum_n_m (fun k => Rsqr (sigma k)) (S m) n) * A.\nProof.\n  intros.\n  rewrite <- sum_n_m_mult_r with (a := A).\n  apply sum_n_m_le; intros.\n  specialize (H (S k) n).\n  apply Rmult_le_compat; trivial.\n  apply Rle_0_sqr.\n  left; apply pos_part_prod_n.\n  lra.\nQed.\n\nLemma sum_bound3_max (F : nat -> posreal) (sigma : nat -> R) (n m:nat) :\n  (S m <= n)%nat ->\n  sum_n (fun k => (Rsqr (sigma k))*(part_prod_n (pos_sq_fun F) (S k) n)) m <=\n  (sum_n (fun k => (Rsqr (sigma k))) m) * (max_prod_fun (pos_sq_fun F) (S m) n).\nProof.  \n  intros.\n  rewrite <- sum_n_mult_r with (a := (max_prod_fun (pos_sq_fun F) (S m) n)).\n  apply sum_n_le_loc; intros.\n  apply Rmult_le_compat_l.\n  apply Rle_0_sqr.\n  apply max_prod_le; lia.\nQed.\n    \nTheorem Dvoretzky4_8_5 (F : nat -> posreal) (sigma V: nat -> R) (n m:nat) (A:R):\n  (forall r s, part_prod_n (pos_sq_fun F) r s <= A) ->\n  (forall (n:nat), Rsqr (V (S n)) <= (pos_sq_fun F) n * Rsqr (V n) + Rsqr (sigma n)) ->\n  (m<n)%nat ->\n   Rsqr (V (S n)) <= \n     ( sum_n_m (fun k => Rsqr (sigma k)) (S m) n) * A +\n     (Rsqr (V 0%nat) + sum_n (fun k => (Rsqr (sigma k))) m) *\n             (max_prod_fun (pos_sq_fun F) (S m) n).\nProof.\n  intros F1 Vsqle mn.\n  generalize (Dvoretzky4_0 (pos_sq_fun F) (fun k => Rsqr(sigma k)) (fun k => Rsqr (V k))).\n  intros.\n  specialize (H Vsqle n).\n  unfold sum_n in H.\n  rewrite (sum_split _ _ _ m) in H; trivial; [|lia].\n  generalize (sum_bound_prod_A F sigma A n m F1); intros.\n  generalize (max_prod_le (pos_sq_fun F) 0 (S m) n); intros.\n  generalize (sum_bound3_max F sigma n m); intros.\n  apply Rmult_le_compat_l with (r := Rsqr (V 0%nat)) in H1; try lia; [|apply Rle_0_sqr].\n  unfold sum_n in *.\n  assert (S m <= n)%nat by lia.\n  specialize (H2 H3).\n  generalize (Rplus_le_compat _ _ _ _ H0 H1); intros.\n  generalize (Rplus_le_compat _ _ _ _ H2 H4); intros.\n  unfold plus, zero in *.\n  simpl in *.\n  lra.\nQed.\n\nLemma sum_bound_prod_A_sigma1 \n      (F : nat -> posreal) (sigma : nat -> R) (A : R) (n m:nat) :\n  (forall r s, part_prod_n (pos_sq_fun F) r s <= A) ->\n  (forall n, 0 <= sigma n) ->\n  sum_n_m (fun k => (sigma k)*(part_prod_n (pos_sq_fun F) (S k) n)) (S m) n <=\n  (sum_n_m sigma (S m) n) * A.\nProof.\n  intros.\n  rewrite <- sum_n_m_mult_r with (a := A).\n  apply sum_n_m_le; intros.\n  specialize (H (S k) n).\n  apply Rmult_le_compat; trivial; try lra.\n  left; apply pos_part_prod_n.\nQed.\n\nLemma sum_bound3_max_sigma1 (F : nat -> posreal) (sigma : nat -> R) (n m:nat) :\n  (S m <= n)%nat ->\n  (forall n, 0 <= sigma n) ->\n  sum_n (fun k => (sigma k)*(part_prod_n (pos_sq_fun F) (S k) n)) m <=\n  (sum_n sigma m) * (max_prod_fun (pos_sq_fun F) (S m) n).\nProof.  \n  intros.\n  rewrite <- sum_n_mult_r with (a := (max_prod_fun (pos_sq_fun F) (S m) n)).\n  apply sum_n_le_loc; intros.\n  apply Rmult_le_compat_l.\n  - apply H0.\n  - apply max_prod_le; lia.\nQed.\n\n\n\nTheorem Dvoretzky4_8_5_V1 (F : nat -> posreal) (sigma V: nat -> R) (n m:nat) (A:R):\n  (forall r s, part_prod_n (pos_sq_fun F) r s <= A) ->\n  (forall (n:nat), (V (S n)) <= (pos_sq_fun F) n * (V n) + (sigma n)) ->\n  (forall (n:nat), 0 <= V n) ->\n  (forall (n:nat), 0 <= sigma n) ->\n  (m<n)%nat ->\n  V (S n) <= \n  (sum_n_m sigma (S m) n) * A +\n  (V 0%nat + sum_n sigma m) *\n             (max_prod_fun (pos_sq_fun F) (S m) n).\nProof.\n  intros F1 Vle Vpos sigma_pos mn.\n  generalize (Dvoretzky4_0 (pos_sq_fun F) sigma V).\n  intros.\n  specialize (H Vle n).\n  unfold sum_n in H.\n  rewrite (sum_split _ _ _ m) in H; trivial; [|lia].\n  generalize (sum_bound_prod_A_sigma1 F sigma A n m F1); intros.\n  generalize (max_prod_le (pos_sq_fun F) 0 (S m) n); intros.\n  generalize (sum_bound3_max_sigma1 F sigma n m); intros.\n  apply Rmult_le_compat_l with (r := (V 0%nat)) in H1; try lia; try apply Vpos.\n  unfold sum_n in *.\n  assert (S m <= n)%nat by lia.\n  specialize (H2 H3 sigma_pos).\n  specialize (H0 sigma_pos).\n  generalize (Rplus_le_compat _ _ _ _ H0 H1); intros.\n  generalize (Rplus_le_compat _ _ _ _ H2 H4); intros.\n  unfold plus, zero in *.\n  simpl in *.\n  lra.\nQed.\n\nTheorem Dvoretzky4_8_5_1 (F : nat -> posreal) (sigma V: nat -> R) (n m:nat) (A sigmasum:R) :\n  (forall r s, part_prod_n (pos_sq_fun F) r s <= A) ->\n  (forall (n:nat), Rsqr (V (S n)) <= (pos_sq_fun F) n * Rsqr (V n) + Rsqr (sigma n)) ->\n  is_series (fun n => Rsqr (sigma n)) sigmasum ->   \n  (m<n)%nat ->\n   Rsqr (V (S n)) <= \n      (sum_n_m (fun k => Rsqr (sigma k)) (S m) n) * A +\n     (Rsqr (V 0%nat) + sigmasum) * (max_prod_fun (pos_sq_fun F) (S m) n).      \nProof.\n  intros.\n  generalize (Dvoretzky4_8_5 F sigma V n m A H H0 H2); intros.\n  assert (sum_n (fun k : nat => (sigma k)²) m <= sigmasum).\n  - assert (H1' := H1).\n    apply is_series_unique in H1.\n    assert (ex_series (fun k : nat => (sigma k)²)).\n    + unfold ex_series.\n      exists sigmasum; trivial.\n    + rewrite <- H1.\n      apply sub_sum_limit_sq; trivial.\n  - apply Rplus_le_compat_l with (r := Rsqr (V 0%nat)) in H4.\n    apply Rmult_le_compat_r with \n      (r := max_prod_fun (pos_sq_fun F) (S m) n) in H4; try lra.\n    assert (part_prod_n (pos_sq_fun F) (S m) n <=  max_prod_fun (pos_sq_fun F) (S m) n).\n    + apply max_prod_le; lia.\n    + assert (0 <= part_prod_n (pos_sq_fun F) (S m) n).\n      * left; apply pos_part_prod_n.\n      * apply (Rle_trans  _ _ _ H6 H5).\nQed.\n\nTheorem Dvoretzky4_8_5_1_V1 (F : nat -> posreal) (sigma V: nat -> R) (n m:nat) (A sigmasum:R) :\n  (forall r s, part_prod_n (pos_sq_fun F) r s <= A) ->\n  (forall (n:nat), V (S n) <= (pos_sq_fun F) n * (V n) + (sigma n)) ->\n  (forall n, 0 <= sigma n) ->\n  (forall n, 0 <= V n) ->\n  is_series sigma sigmasum ->   \n  (m<n)%nat ->\n   V (S n) <= \n      (sum_n_m sigma (S m) n) * A +\n      (V 0%nat + sigmasum) * (max_prod_fun (pos_sq_fun F) (S m) n).      \nProof.\n  intros.\n  generalize (Dvoretzky4_8_5_V1 F sigma V n m A H H0 H2 H1 H4); intros.\n  assert (sum_n sigma m <= sigmasum).\n  - assert (H3' := H3).\n    apply is_series_unique in H3.\n    assert (ex_series sigma).\n    + unfold ex_series.\n      exists sigmasum; trivial.\n    + rewrite <- H3.\n      apply sub_sum_limit_nneg; trivial.\n  - apply Rplus_le_compat_l with (r := (V 0%nat)) in H6.\n    apply Rmult_le_compat_r with \n        (r := max_prod_fun (pos_sq_fun F) (S m) n) in H6; try lra.\n    assert (part_prod_n (pos_sq_fun F) (S m) n <=  max_prod_fun (pos_sq_fun F) (S m) n).\n    + apply max_prod_le; lia.\n    + assert (0 <= part_prod_n (pos_sq_fun F) (S m) n).\n      * left; apply pos_part_prod_n.\n      * apply (Rle_trans  _ _ _ H8 H7).\nQed.\n\nLemma Dvoretzky4_sigma_v0_2_0 (F : nat -> posreal) (sigma V: nat -> R) :\n  (forall (n:nat), Rsqr (V (S n)) <= (pos_sq_fun F) n * Rsqr (V n) + Rsqr (sigma n)) ->\n  ex_series (fun n => Rsqr (sigma n)) ->\n  Series (fun n => Rsqr (sigma n)) + Rsqr (V 0%nat) = 0 ->\n  forall n, V n = 0.\nProof.\n  intros.\n  remember (Series (fun n => Rsqr (sigma n))) as sigma_sum.\n  generalize (nneg_series_sq sigma H0); simpl; intros.\n  generalize (Rle_0_sqr (V 0%nat)); intros.\n  rewrite <- Heqsigma_sum in H2.\n  generalize (Rplus_eq_R0 sigma_sum (Rsqr (V 0%nat)) H2 H3 H1); intros.\n  destruct H4.\n  generalize (lim_sq_0 sigma).\n  rewrite Heqsigma_sum in H4; intros.\n  generalize (Series_correct _ H0); intros.\n  rewrite H4 in H7.\n  specialize (H6 H7).\n  induction n.\n  - now apply Rsqr_eq_0 in H5.\n  - specialize (H n).\n    rewrite IHn, <- H6 in H.\n    rewrite Rsqr_0, Rplus_0_r, Rmult_0_r in H.\n    generalize (Rle_0_sqr (V (S n))); intros.\n    generalize (Rle_antisym _ _ H H8).\n    apply Rsqr_eq_0.\nQed.\n  \nLemma Dvoretzky4_sigma_v0_2_0_V_pos (F : nat -> posreal) (sigma V: nat -> R) :\n  (forall n, 0 <= sigma n) ->\n  (forall n, 0 <= V n) ->\n  (forall (n:nat), (V (S n)) <= (pos_sq_fun F) n * (V n) + (sigma n)) ->\n  ex_series sigma ->\n  Series sigma + (V 0%nat) = 0 ->\n  forall n, V n = 0.\nProof.\n  intros.\n  remember (Series sigma) as sigma_sum.\n  generalize (nneg_series sigma H H2); simpl; intros.\n  rewrite <- Heqsigma_sum in H4.\n  generalize (Rplus_eq_R0 sigma_sum (V 0%nat) H4 (H0 0%nat) H3); intros.\n  destruct H5.\n  generalize (lim_0_nneg sigma).\n  rewrite Heqsigma_sum in H5; intros.\n  generalize (Series_correct _ H2); intros.\n  rewrite H5 in H8.\n  specialize (H7 H8).\n  induction n.\n  - trivial.\n  - specialize (H1 n).\n    cut_to H7; trivial.\n    specialize (H7 n).\n    rewrite IHn, H7 in H1.\n    rewrite Rplus_0_r, Rmult_0_r in H1.\n    now apply Rle_antisym.\nQed.\n\nTheorem Dvoretzky4_A (F : nat -> posreal) (sigma V: nat -> R) (A:posreal) :\n  (forall r s, part_prod_n (pos_sq_fun F) r s <= A) ->\n  (forall (n:nat), Rsqr (V (S n)) <= (pos_sq_fun F) n * Rsqr (V n) + Rsqr (sigma n)) ->\n  is_lim_seq (part_prod F) 0 ->\n  ex_series (fun n => Rsqr (sigma n)) ->   \n  is_lim_seq (fun n => Rsqr (V n)) 0.\nProof.\n  intros.\n  generalize (Cauchy_ex_series (fun n : nat => (sigma n)²) H2); intros.\n  unfold Cauchy_series in H3.\n  generalize (inf_prod_sq_0 F H1); intros lim_prod_sq.\n  generalize (lim_max_prod_m_0 (pos_sq_fun F) lim_prod_sq); intros.\n  rewrite is_lim_seq_Reals; unfold Un_cv; intros.\n  assert (0 < eps/(2*A)).\n  apply Rdiv_lt_0_compat; trivial.\n  apply Rmult_lt_0_compat; [lra|apply cond_pos].\n  remember (mkposreal (eps/(2*A)) H6) as half_eps_div_A.\n  specialize (H3 half_eps_div_A).\n  destruct H3 as [Nsigma H3].\n  unfold norm in H3; simpl in H3.\n  unfold abs in H3; simpl in H3.\n  assert (H2' := H2).\n  unfold ex_series in H2.\n  destruct H2 as [sigma_sum H2].\n  remember (sigma_sum + Rsqr (V 0%nat)) as sigma_V0_2.\n  destruct (Req_dec sigma_V0_2 0).\n  - exists (0%nat); intros.\n    rewrite Heqsigma_V0_2 in H7.\n    apply is_series_unique in H2.\n    rewrite <- H2 in H7.\n    rewrite (Dvoretzky4_sigma_v0_2_0 F sigma); trivial.\n    unfold R_dist.\n    now rewrite Rsqr_0, Rminus_0_r, Rabs_R0.\n  - assert (0 <= sigma_V0_2).\n    rewrite Heqsigma_V0_2.\n    apply Rplus_le_le_0_compat.\n    assert (H2'' := H2).\n    apply is_series_unique in H2''.\n    rewrite <- H2''.\n    apply nneg_series_sq; trivial.\n    apply Rle_0_sqr.\n    destruct H8; [|congruence].\n    remember ((eps / 2) / sigma_V0_2) as part_prod_eps.\n    specialize (H4 (S Nsigma)).\n    rewrite is_lim_seq_Reals in H4; unfold Un_cv in H4.\n    specialize (H4 part_prod_eps).\n    assert (part_prod_eps > 0).\n    rewrite Heqpart_prod_eps.\n    apply  Rdiv_lt_0_compat; trivial; lra.\n    specialize (H4 H9). \n    destruct H4 as [NH4 H4].\n    remember ( NH4 + S Nsigma)%nat as NV.\n    exists (S NV).\n    unfold R_dist in *; intros.\n    rewrite Rminus_0_r, Rabs_pos_eq; [| apply Rle_0_sqr].\n    generalize (Dvoretzky4_8_5_1 F sigma V (n-1)%nat Nsigma A sigma_sum H H0 H2).\n    replace (S (n-1)%nat) with n by lia; intros.\n    cut_to H11; [|lia].\n    specialize (H3 (S Nsigma) (n-1)%nat).\n    cut_to H3; try lia.\n    rewrite Rabs_pos_eq in H3; [|apply nneg_sum_n_m_sq ].\n    specialize (H4 (n - 1)%nat).\n    rewrite Rminus_0_r in H4.\n    assert (0 < max_prod_fun (pos_sq_fun F) (S Nsigma) (n - 1)).\n\n    + generalize (max_prod_index_n (pos_sq_fun F) (S Nsigma) (n-1)%nat); intros.\n      destruct H12 as [k H12]; [lia|]; destruct H12.\n      rewrite <- H13.\n      apply pos_part_prod_n.\n    + rewrite Rabs_pos_eq in H4; [|left; apply H12].\n      apply Rmult_lt_compat_l with (r := sigma_V0_2) in H4; trivial; try lia.\n      rewrite Heqpart_prod_eps in H4.\n      replace (sigma_V0_2 * (eps / 2 / sigma_V0_2)) with (eps/2) in H4; [|now field_simplify].\n      rewrite Rplus_comm in Heqsigma_V0_2.\n      rewrite <- Heqsigma_V0_2 in H11.\n      unfold part_prod_pos, pos in H4.\n      rewrite Heqhalf_eps_div_A in H3; simpl in H3.\n      apply Rmult_lt_compat_r with (r := A) in H3; [|apply cond_pos].\n      replace (eps / ( 2 * A) * A) with (eps / 2) in H3; \n        [|field_simplify;trivial; apply Rgt_not_eq; apply cond_pos].\n      generalize (Rplus_lt_compat _ _ _ _ H3 H4); intros.\n      replace (eps/2 + eps/2) with (eps) in H13 by lra.\n      apply (Rle_lt_trans  _ _ _ H11 H13).\nQed.\n\nTheorem Dvoretzky4_A_Vpos (F : nat -> posreal) (sigma V: nat -> R) (A:posreal) :\n  (forall r s, part_prod_n (pos_sq_fun F) r s <= A) ->\n  (forall (n:nat), V (S n) <= (pos_sq_fun F) n * (V n) + (sigma n)) ->\n  (forall (n:nat), 0 <= V n) ->\n  (forall (n:nat), 0 <= sigma n) ->\n  is_lim_seq (part_prod F) 0 ->\n  ex_series sigma ->   \n  is_lim_seq V 0.\nProof.\n  intros.\n  generalize (Cauchy_ex_series sigma H4); intros.\n  unfold Cauchy_series in H5.\n  generalize (inf_prod_sq_0 F H3); intros lim_prod_sq.\n  generalize (lim_max_prod_m_0 (pos_sq_fun F) lim_prod_sq); intros.\n  rewrite is_lim_seq_Reals; unfold Un_cv; intros.\n  assert (0 < eps/(2*A)).\n  apply Rdiv_lt_0_compat; trivial.\n  apply Rmult_lt_0_compat; [lra|apply cond_pos].\n  remember (mkposreal (eps/(2*A)) H8) as half_eps_div_A.\n  specialize (H5 half_eps_div_A).\n  destruct H5 as [Nsigma H5].\n  unfold norm in H5; simpl in H5.\n  unfold abs in H5; simpl in H5.\n  assert (H4' := H4).\n  unfold ex_series in H4.\n  destruct H4 as [sigma_sum H4].\n  remember (sigma_sum + (V 0%nat)) as sigma_V0.\n  destruct (Req_dec sigma_V0 0).\n  - exists (0%nat); intros.\n    rewrite Heqsigma_V0 in H9.\n    apply is_series_unique in H4.\n    rewrite <- H4 in H9.\n    rewrite (Dvoretzky4_sigma_v0_2_0_V_pos F sigma); trivial.\n    unfold R_dist.\n    now rewrite Rminus_0_r, Rabs_R0.\n  - assert (0 <= sigma_V0).\n    rewrite Heqsigma_V0.\n    apply Rplus_le_le_0_compat; trivial.\n    assert (H4'' := H4).\n    apply is_series_unique in H4''.\n    rewrite <- H4''.\n    apply nneg_series; trivial.\n    destruct H10; [|congruence].\n    remember ((eps / 2) / sigma_V0) as part_prod_eps.\n    specialize (H6 (S Nsigma)).\n    rewrite is_lim_seq_Reals in H6; unfold Un_cv in H6.\n    specialize (H6 part_prod_eps).\n    assert (part_prod_eps > 0).\n    rewrite Heqpart_prod_eps.\n    apply  Rdiv_lt_0_compat; trivial; lra.\n    specialize (H6 H11). \n    destruct H6 as [NH6 H6].\n    remember ( NH6 + S Nsigma)%nat as NV.\n    exists (S NV).\n    unfold R_dist in *; intros.\n    rewrite Rminus_0_r, Rabs_pos_eq; trivial.\n    generalize (Dvoretzky4_8_5_1_V1 F sigma V (n-1)%nat Nsigma A sigma_sum H H0 H2 H1 H4).\n    replace (S (n-1)%nat) with n by lia; intros.\n    cut_to H13; [|lia].\n    specialize (H5 (S Nsigma) (n-1)%nat).\n    cut_to H5; try lia.\n    rewrite Rabs_pos_eq in H5; [|apply sum_n_m_pos; intros; apply H2; try lia].\n    specialize (H6 (n - 1)%nat).\n    rewrite Rminus_0_r in H6.\n    assert (0 < max_prod_fun (pos_sq_fun F) (S Nsigma) (n - 1)).\n\n    + generalize (max_prod_index_n (pos_sq_fun F) (S Nsigma) (n-1)%nat); intros.\n      destruct H14 as [k H14]; [lia|]; destruct H14.\n      rewrite <- H15.\n      apply pos_part_prod_n.\n    + rewrite Rabs_pos_eq in H6; [|left; apply H14].\n      apply Rmult_lt_compat_l with (r := sigma_V0) in H6; trivial; try lia.\n      rewrite Heqpart_prod_eps in H6.\n      replace (sigma_V0 * (eps / 2 / sigma_V0)) with (eps/2) in H6; [|now field_simplify].\n      rewrite Rplus_comm in Heqsigma_V0.\n      rewrite <- Heqsigma_V0 in H13.\n      unfold part_prod_pos, pos in H6.\n      rewrite Heqhalf_eps_div_A in H5; simpl in H5.\n      apply Rmult_lt_compat_r with (r := A) in H5; [|apply cond_pos].\n      replace (eps / ( 2 * A) * A) with (eps / 2) in H5; \n        [|field_simplify;trivial; apply Rgt_not_eq; apply cond_pos].\n      generalize (Rplus_lt_compat _ _ _ _ H5 H6); intros.\n      replace (eps/2 + eps/2) with (eps) in H15 by lra.\n      apply (Rle_lt_trans  _ _ _ H13 H15).\nQed.\n\nTheorem Dvoretzky4B (F : nat -> posreal) (sigma V: nat -> R) :\n  (forall n, F n <= 1) ->\n  (forall (n:nat), Rsqr (V (S n)) <= (pos_sq_fun F) n * Rsqr (V n) + Rsqr (sigma n)) ->\n  is_lim_seq (part_prod F) 0 ->\n  ex_series (fun n => Rsqr (sigma n)) ->   \n  is_lim_seq (fun n => Rsqr (V n)) 0.\nProof.\n  intros.\n  apply Dvoretzky4_A with (F := F) (sigma := sigma) (A := mkposreal _ Rlt_0_1); trivial.\n  intros; apply prod_sq_bounded_1; trivial.\nQed.  \n\nTheorem Dvoretzky4B_Vpos (F : nat -> posreal) (sigma V: nat -> R) :\n  (forall n, F n <= 1) ->\n  (forall n, 0 <= V n) ->\n  (forall n, 0 <= sigma n) ->\n  (forall (n:nat), V (S n) <= (pos_sq_fun F) n * (V n) + (sigma n)) ->\n  is_lim_seq (part_prod F) 0 ->\n  ex_series sigma ->\n  is_lim_seq V 0.\nProof.\n  intros.\n  apply Dvoretzky4_A_Vpos with (F := F) (sigma := sigma) (A := mkposreal _ Rlt_0_1); trivial.\n  intros; apply prod_sq_bounded_1; trivial.\nQed.  \n\nSection Generalized_Harmonic_Series.\n\nLemma inv_bound_gt (a b : posreal) :\n  / a  > / (a + b).\nProof.\n  apply Rinv_lt_contravar.\n  - apply Rmult_lt_0_compat.\n    + apply cond_pos.\n    + apply Rplus_lt_0_compat; apply cond_pos.\n  - replace (pos a) with (a + 0) at 1 by lra.\n    apply Rplus_lt_compat_l.\n    apply cond_pos.\nQed.\n\nLemma inv_bound_sq_gt (a b : posreal) :\n  Rsqr (/ a)  > Rsqr (/ (a + b)).\nProof.\n  apply Rsqr_incrst_1.\n  + apply inv_bound_gt.\n  + left.\n    apply Rinv_0_lt_compat.\n    apply Rplus_lt_0_compat; apply cond_pos.    \n  + left.\n    apply Rinv_0_lt_compat; apply cond_pos.\nQed.\n\nLemma inv_bound_exists_lt  (a b : posreal) :\n  exists (j : nat), forall (n:nat), / (a * (INR ((S n) + j))) < / (a * INR (S n) + b).\nProof.\n  exists (Z.to_nat (up (b/a))).\n  intros.\n  generalize  (RealAdd.up_pos (b/a)); intros.\n  cut_to H.\n  apply Z.gt_lt in H.\n  apply Rinv_lt_contravar.\n  - apply Rmult_lt_0_compat.\n    + apply Rplus_lt_0_compat; [| apply cond_pos].\n      apply Rmult_lt_0_compat; [apply cond_pos | ].\n      apply lt_0_INR; lia.\n    + apply Rmult_lt_0_compat; [apply cond_pos | ].\n      apply lt_0_INR; lia.\n  - rewrite plus_INR.\n    rewrite Rmult_plus_distr_l.\n    apply Rplus_lt_compat_l.\n    assert (b/a < IZR (up (b/a))) by apply archimed.\n    rewrite INR_IZR_INZ.\n    rewrite Z2Nat.id; trivial; [|lia].\n    apply Rmult_lt_compat_l with (r:=a) in H0; [|apply cond_pos].\n    replace (a * (b / a)) with (pos b) in H0.\n    generalize (cond_pos a); intros.\n    lra.\n    field.\n    apply  Rgt_not_eq, cond_pos.\n  - unfold Rdiv.\n    apply Rmult_gt_0_compat; [apply cond_pos|].\n    apply Rinv_0_lt_compat; apply cond_pos.    \nQed.\n\nLemma genharmonic_series_sq (b c : posreal) :\n  ex_series (fun n => Rsqr (/ (b + c * INR (S n)))).\nProof.\n  apply (@ex_series_le R_AbsRing) with (b := fun n => Rsqr ( / (c * INR (S n)))).\n  - intros.\n    assert (0 < c * INR (S n)).    \n    + apply Rmult_lt_0_compat; [apply cond_pos | ].\n      apply lt_0_INR; lia.\n    + rewrite Rabs_right.\n      * left; apply Rgt_lt.\n        rewrite Rplus_comm.\n        generalize (inv_bound_sq_gt (mkposreal _ H) b); intros.\n        apply H0.\n      * apply Rle_ge.\n        apply Rle_0_sqr.\n  - generalize sum_inv_sqr_bounded; intros.\n    unfold ex_finite_lim_seq in H.\n    destruct H.\n    apply (ex_series_ext (fun n => Rsqr (/ c) * Rsqr (/ INR (S n)))).\n    + intros.\n      rewrite Rinv_mult_distr.\n      * now rewrite Rsqr_mult.\n      * apply Rgt_not_eq; apply cond_pos.\n      * apply Rgt_not_eq.\n        apply RealAdd.INR_zero_lt; lia.\n    + apply (@ex_series_scal R_AbsRing).\n      unfold ex_series.\n      exists x.\n      apply is_series_Reals.\n      apply infinite_sum_is_lim_seq.\n      apply (is_lim_seq_ext (fun n : nat => sum_f_R0 (fun i : nat => 1 / (INR i + 1)²) n)); trivial; intros.\n      apply sum_f_R0_ext; intros.\n      unfold Rdiv.\n      rewrite  Rmult_1_l.\n      rewrite Rsqr_inv.\n      * now rewrite S_INR.\n      * apply not_0_INR; lia.\nQed.\n\nLemma genharmonic_sq_lim (b c : posreal) :\n  is_lim_seq (fun n => Rsqr (/ (b + c * INR (S n)))) 0.\nProof.  \n  apply ex_series_lim_0.\n  apply genharmonic_series_sq.\nQed.\n\nLemma harmonic_increasing :\n  let f := fun i => sum_f_R0' (fun n => 1 / INR (S n)) i in\n  forall n m : nat, (n <= m)%nat -> f n <= f m.\nProof.\n  intros.\n  subst f.\n  simpl.\n  replace (m) with (n + (m-n))%nat by lia.\n  rewrite sum_f_R0'_plus_n.\n  rewrite <- Rplus_0_r at 1.\n  apply Rplus_le_compat_l.\n  induction (m-n)%nat.\n  - simpl; lra.\n  - simpl.\n    apply Rplus_le_le_0_compat; trivial.\n    unfold Rdiv.\n    rewrite Rmult_1_l.\n    left.\n    apply Rinv_0_lt_compat.\n    destruct (n + n0)%nat.\n    + lra.\n    + rewrite <- S_INR.\n      apply lt_0_INR; lia.\nQed.\n  \nLemma harmonic_series :\n  is_lim_seq (fun i => sum_f_R0' (fun n => 1 / INR (S n)) i) p_infty.\nProof.\n  apply is_lim_seq_spec.\n  intro.\n  unfold eventually.\n  generalize (sum_f_R0'_bound2 (Z.to_nat (up (2 * (Rabs M))))); intros.\n  exists (2 ^ Z.to_nat (up (2 * (Rabs M))))%nat.\n  intros.\n  assert (IZR (up (2 * Rabs M)) > 2*Rabs M) by apply archimed.\n  assert (1 + INR (Z.to_nat (up (2 * (Rabs M)))) / 2 > Rabs M).\n  rewrite RealAdd.INR_up_pos.\n  lra.\n  assert (0 <= Rabs M) by apply Rabs_pos; lra.\n  generalize (harmonic_increasing (2 ^ Z.to_nat (up (2 * Rabs M))) n H0).\n  intros.\n  generalize (Rle_abs M); intros.\n  lra.\nQed.\n\nLemma harmonic_series2 (c:posreal) :\n  is_lim_seq (fun i => sum_f_R0' (fun n =>  1 / (c * INR (S n))) i) p_infty.\nProof.\n  generalize (cond_pos c); intros cpos.\n  generalize harmonic_series; intros.\n  apply is_lim_seq_scal_l with (a := /c) in H.\n  replace (Rbar_mult (/c) p_infty) with p_infty in H.\n  - apply (is_lim_seq_ext (fun n : nat => /c * sum_f_R0' (fun n0 : nat => 1 / INR (S n0)) n)); intros; trivial.\n    rewrite <- sum_f_R0'_mult_const.\n    apply sum_f_R0'_ext.\n    intros.\n    unfold Rdiv.\n    do 2 rewrite Rmult_1_l.\n    rewrite Rinv_mult_distr; trivial.\n    lra.\n    apply not_0_INR; lia.\n  - rewrite Rbar_mult_comm; symmetry.\n    apply is_Rbar_mult_unique.\n    apply is_Rbar_mult_p_infty_pos.\n    apply Rinv_0_lt_compat; apply cond_pos.\nQed.\n\nLemma harmonic_series3 (j:nat) (f : nat -> R) :\n  is_lim_seq (fun i => sum_f_R0' f i) p_infty ->\n  is_lim_seq (fun i => sum_f_R0' (fun n => f (n + j)%nat) i) p_infty.\nProof.\n  intros.\n  apply (is_lim_seq_incr_n _ j) in H.\n  apply is_lim_seq_minus with (v := fun _ => sum_f_R0' f j) (l2 := sum_f_R0' f j) (l1 := p_infty) (l := p_infty) in H.\n  - apply (is_lim_seq_ext  (fun n : nat => sum_f_R0' f (n + j) - sum_f_R0' f j)); trivial.\n    intros.\n    rewrite sum_f_R0'_split with (m := j); [|lia].\n    replace (n+j-j)%nat with n by lia.\n    lra.\n  - apply is_lim_seq_const.\n  - unfold is_Rbar_minus, is_Rbar_plus.\n    now simpl.\nQed.\n\nLemma genharmon (a b : posreal) :\n  forall (n:nat), / ((a+b)*(INR (S n))) <= /(a*(INR (S n)) + b) < /(a * (INR (S n))).\nProof.\n  intros.\n  split.\n  - apply Rinv_le_contravar.\n    + apply Rplus_lt_0_compat; [ | apply cond_pos].\n      apply Rmult_lt_0_compat; [apply cond_pos | ].\n      apply lt_0_INR; lia.\n    + rewrite Rmult_plus_distr_r.\n      apply Rplus_le_compat_l.\n      replace (pos b) with (b * 1) at 1 by lra.\n      apply Rmult_le_compat_l; [left;apply cond_pos | ].\n      rewrite S_O_plus_INR.\n      replace 1 with (1 + 0) by lra.\n      apply Rplus_le_compat_l.\n      apply pos_INR.\n  - assert (0 < a * INR (S n)).\n    + apply Rmult_lt_0_compat; [apply cond_pos | ].\n      apply lt_0_INR; lia.\n    + apply Rinv_lt_contravar.\n      * apply Rmult_lt_0_compat; trivial.\n        apply Rplus_lt_0_compat; [trivial | apply cond_pos].\n      * replace (a * INR (S n)) with (a * INR (S n) + 0) at 1 by lra.\n        apply Rplus_lt_compat_l; apply cond_pos.\nQed.\n\nLemma genharmon_sq (a b : posreal) :\n  forall (n:nat), \n    Rsqr (/ ((a+b)*(INR (S n)))) <= Rsqr (/ (a*(INR (S n)) + b)) < Rsqr (/ (a * (INR (S n)))).\nProof.\n  intros.\n  generalize (genharmon a b n); intros.\n  destruct H.\n  assert (0 < INR (S n)) by (apply lt_0_INR; lia).\n  assert (0 < (a + b) * INR (S n)).\n  - apply Rmult_lt_0_compat; trivial.\n    apply Rplus_lt_0_compat; apply cond_pos.\n  - assert (0 < a * INR (S n) + b).\n    + apply Rplus_lt_0_compat; [ | apply cond_pos].\n      apply Rmult_lt_0_compat; [apply cond_pos| trivial].\n    + split.\n      * apply Rsqr_incr_1; trivial.\n        -- left; apply Rinv_0_lt_compat; trivial.\n        -- left; apply Rinv_0_lt_compat; trivial.        \n      * apply Rsqr_incrst_1; trivial.\n        -- left; apply Rinv_0_lt_compat; trivial.\n        -- left; apply Rinv_0_lt_compat.\n           apply Rmult_lt_0_compat; [apply cond_pos | trivial].\nQed.\n\nLemma genharmonic_series (b c : posreal) :\n  is_lim_seq (fun i => sum_f_R0' (fun n => 1 / (b + c * INR (S n))) i) p_infty.\nProof.\n  generalize (cond_pos c); intros cpos.\n  generalize (inv_bound_exists_lt c b); intros.\n  destruct H as [j H].\n  unfold is_lim_seq.\n  apply filterlim_ge_p_infty with (f := fun n : nat => sum_f_R0' (fun n0 : nat => 1 / (c *INR (S (n0) + j))) n).\n  unfold eventually;  exists (0%nat); intros.\n  apply sum_f_R0'_le_f.\n  intros.\n  unfold Rdiv; do 2 rewrite Rmult_1_l.\n  rewrite Rplus_comm; left; apply H.\n  generalize (harmonic_series2 c); intros.\n  generalize (harmonic_series3 j (fun n => 1 / (c * INR (S n))) H0); trivial.\nQed.\n  \nLemma genharmonic_series2 (b c : posreal) :\n  is_lim_seq (fun i => sum_f_R0' (fun n => 1 / (b + c * INR (S n))) i) p_infty.\nProof.\n  generalize (genharmon c b); intros.\n  assert (0 < c + b).\n  apply Rplus_lt_0_compat; apply cond_pos.\n  generalize (harmonic_series2 (mkposreal _ H0)); intros.\n  unfold is_lim_seq in *.\n  apply filterlim_ge_p_infty\n    with (f := (fun i : nat =>\n          sum_f_R0' (fun n : nat => 1 / ({| pos := c + b; cond_pos := H0 |} * INR (S n))) i)); trivial.\n  unfold eventually;  exists (0%nat); intros.\n  apply sum_f_R0'_le_f.\n  intros.\n  specialize (H i); destruct H.\n  unfold Rdiv.\n  do 2 rewrite Rmult_1_l.\n  replace (b + c * INR (S i)) with (c * INR (S i) + b) by lra.\n  apply H.\nQed.  \n\nEnd Generalized_Harmonic_Series.\n\nLemma Robbins_Monro_0 (u : R) (a : nat -> posreal) (g : R -> R) (A B : posreal) :\n  (forall (u:R), u <> 0 -> A <= g u <= B) ->\n  forall (n:nat), \n    (u <> 0) ->\n    Rabs (1 - a n * g u) <= Rmax (1-A*(a n)) (B*(a n) - 1).\nProof.\n  intros.\n  specialize (H u H0).\n  destruct H.\n  replace (B*(a n) - 1) with (- (1 - B*a n)) by lra.\n  apply Rcomplements.Rabs_le_between_Rmax; unfold Rminus.\n  split; apply Rplus_le_compat_l, Ropp_le_contravar; rewrite Rmult_comm.\n  - apply Rmult_le_compat_r; trivial.    \n    left; apply cond_pos.\n  - apply Rmult_le_compat_l; trivial.\n    left; apply cond_pos.\nQed.\n\nLemma Robbins_Monro_1 (r : nat -> R) (a : nat -> posreal) (f : R -> R) (A B : posreal) :\n  (forall (u:R), u <> 0 -> A <= f(u)/u <= B) ->\n  forall (n:nat), r n <> 0 -> Rabs (r n - a n * f (r n)) <= Rabs (r n) * Rmax (1-A*(a n)) (B*(a n) - 1).\nProof.\n  intros.\n  replace (r n - a n * f (r n)) with ((r n)*(1 - a n * (f(r n)/(r n)))).\n  - rewrite Rabs_mult.\n    apply Rmult_le_compat_l; [apply Rabs_pos | ].\n    apply Robbins_Monro_0 with (g := fun u => f u / u); trivial.\n  - now field.    \nQed.    \n\nLemma Robbins_Monro_1b (a A B : posreal) :\n  a < 2/(A + B) -> Rmax (1-A*a) (B*a-1) = 1-A*a.\nProof.\n  intros.\n  assert (0 < A + B).\n  apply Rplus_lt_0_compat; apply cond_pos.\n  apply Rmax_left; left.\n  unfold Rdiv in H.\n  replace (pos a) with (a * (A + B) * / (A + B)) in H.\n  - apply Rmult_lt_reg_r in H; [lra | ].\n    now apply Rinv_0_lt_compat.\n  - field.\n    now apply Rgt_not_eq.\nQed.\n\nLemma is_derive_Rsqr (f : R -> R) (x df : R) :\n  is_derive f x df -> is_derive (fun x0 => Rsqr (f x0)) x (2 * (f x) * df).\nProof.\n  intros.\n  apply (is_derive_ext (fun x0 => (f x0) * (f x0))); [now unfold Rsqr |].\n  replace (2 * f x * df) with ((df * f x) + (f x * df)) by lra.\n  apply (@is_derive_mult R_AbsRing); trivial.\n  apply Rmult_comm.\nQed.\n\nLemma Robbins_Monro_2a (A sigma : posreal) (a0 V : R) :\n  let f := fun a => (Rsqr (1-A*a) * (Rsqr V)) + (Rsqr a * (Rsqr sigma)) in\n  is_derive f a0 ((2 * (1-A*a0) * (-A) * (Rsqr V)) + (2 * a0 * (Rsqr sigma))).\nProof.\n  intros.\n  apply (@is_derive_plus R_AbsRing).\n  - apply (@is_derive_scal_l R_AbsRing).\n    apply (is_derive_Rsqr (fun x => (1 - A * x))).\n    replace (-A) with (0 - A) by lra.\n    apply (@is_derive_minus R_AbsRing).\n    + apply (@is_derive_const R_AbsRing).\n    + replace (pos A) with (A*1) at 2 by lra.\n      apply is_derive_scal.\n      apply (@is_derive_id R_AbsRing).\n  - apply (@is_derive_scal_l R_AbsRing).\n    replace (2 * a0) with (2 * a0 * 1) by lra.\n    apply is_derive_Rsqr.\n    apply (@is_derive_id R_AbsRing).\nQed.\n    \nLemma Robbins_Monro_2b (A sigma : posreal) (V : R) :\n  let a0 := (A * V^2) / (sigma^2 + A^2 * V^2) in\n  (2 * (1-A*a0) * (-A) * (Rsqr V)) + (2 * a0 * (Rsqr sigma)) = 0.\nProof.\n  intros.\n  subst a0; unfold Rsqr.\n  field.\n  apply Rgt_not_eq.\n  apply Rlt_gt.\n  generalize (cond_pos sigma); intros.\n  apply Rplus_lt_le_0_compat.\n  - apply Rmult_lt_0_compat; [apply cond_pos | ].\n    rewrite Rmult_1_r; apply cond_pos.\n  - replace ((A * V)^2) with (Rsqr (A*V)) by (unfold Rsqr; lra).\n    apply Rle_0_sqr.\nQed.\n\nLemma Robbins_Monro_2c (A sigma : posreal) (V x : R) :\n  let f := fun a => (Rsqr (1-A*a) * (Rsqr V)) + (Rsqr a * (Rsqr sigma)) in\n  let a0 := (A * V^2) / (sigma^2 + A^2 * V^2) in\n  is_derive f a0 0.\nProof.\n  intros.\n  subst f.\n  generalize (Robbins_Monro_2a A sigma a0 V); intros.\n  simpl in H; subst a0.\n  now rewrite (Robbins_Monro_2b A sigma V) in H.\nQed.\n\nLemma Robbins_Monro_2d (A sigma : posreal) (V x : R) :\n  let f := fun a => (Rsqr (1-A*a) * (Rsqr V)) + (Rsqr a * (Rsqr sigma)) in\n  let a0 := (A * V^2) / (sigma^2 + A^2 * V^2) in\n  f a0 = sigma^2 * V^2 / (sigma^2 + (A*V)^2).\nProof.\n  intros.\n  subst f; subst a0; simpl.\n  unfold Rsqr.\n  field.\n  apply Rgt_not_eq.\n  apply Rlt_gt.\n  apply Rplus_lt_le_0_compat.\n  - apply Rmult_lt_0_compat; apply cond_pos.\n  - replace (A * V * (A * V)) with (Rsqr (A * V)) by (unfold Rsqr; lra).\n    apply Rle_0_sqr.\nQed.  \n  \n\nEnd Dvoretsky.\n", "meta": {"author": "IBM", "repo": "FormalML", "sha": "e399d096f1ad572420dbd1c638d593eee2129cbe", "save_path": "github-repos/coq/IBM-FormalML", "path": "github-repos/coq/IBM-FormalML/FormalML-e399d096f1ad572420dbd1c638d593eee2129cbe/coq/QLearn/infprod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511359371249, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6895012220901133}}
{"text": "Require Import Omega.\nRequire Import Wf_nat.\n\nDefinition f1_aux :\n  forall x, (forall z, z < x ->{y:nat | z=0 \\/ y < z})->{y:nat | x=0\\/ y< x}.\n intros x; case x.\n(* value for 0 *)\n intros rec; exists 0; auto.\n intros x'; case x'.\n(* value for 1 *)\n intros rec; exists 0; auto.  \n(* value for x > 1 *)\n refine\n    (fun x'' rec => \n      match rec (S x'') _ with\n      | (exist _ v H) =>\n        match rec (S v) _ with\n        | (exist _ v' H') => (exist _ (S v') _)\n        end\n      end); omega.\nDefined.\n\nDefinition f1' : forall x, {y:nat | x=0 \\/ y<x} :=\n (well_founded_induction lt_wf\n   (fun x:nat => {y:nat | x=0\\/ y<x})\n   f1_aux).\n\nDefinition f1 (x:nat): nat :=\n match f1' x with (exist _ v _) => v end.\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch15_general_recursion/SRC/exo_15_14.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6894983132005129}}
{"text": "From DEZ.Has Require Export\n  EquivalenceRelation OrderRelation.\nFrom DEZ.Is Require Export\n  Proper Antisymmetric Transitive Connex.\nFrom DEZ.ShouldHave Require Import\n  OrderNotations.\n\nClass IsTotalOrder {A : Type} {has_eqv : HasEqv A}\n  (has_ord : HasOrd A) : Prop := {\n  ord_is_proper :> IsProper (eqv ==> eqv ==> flip impl) ord;\n  ord_is_antisymmetric :> IsAntisymmetric ord;\n  ord_is_transitive :> IsTransitive ord;\n  ord_is_connex :> IsConnex ord;\n}.\n\nSection Context.\n\nContext {A : Type} `{is_total_order : IsTotalOrder A}.\n\nTheorem ord_reflexive : forall x : A, x <= x.\nProof.\n  intros x. destruct (connex x x) as [H | H].\n  - specialize (H : x <= x). apply H.\n  - specialize (H : x <= x). apply H. Qed.\n\nGlobal Instance ord_is_reflexive : IsReflexive ord := {}.\nProof. apply ord_reflexive. Qed.\n\nEnd Context.\n", "meta": {"author": "Tuplanolla", "repo": "dez", "sha": "c2eadc2e032094c3504ec3803c000dba4feb547e", "save_path": "github-repos/coq/Tuplanolla-dez", "path": "github-repos/coq/Tuplanolla-dez/dez-c2eadc2e032094c3504ec3803c000dba4feb547e/garbage/prototype/Is/TotalOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6894446572949281}}
{"text": "Require Import JMeq.\n\nLemma plus_assoc_JM : forall n p q:nat,\n                       JMeq (n+(p+q)) (n+p+q).\nProof.\n induction n; simpl.\n -  split.\n -  intros p q; pattern (n+p+q). \n    eapply JMeq_ind.\n    +  apply JMeq_refl.\n    +  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/ch8_inductive_predicates/SRC/JM_assoc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6892892132997644}}
{"text": "(* =========== Basic tactics :\n-> intro - introduction rule for Pi;\n-> apply - elimination rule for Pi;\n-> assumption, exact - match conclusion with an hypothesis. \n*)\n\n(* =========== Tactics for first-order reasoning:\n-> intro - introduction rule for negation, implication and universal quantification\n-> split - introduction rule for conjunction\n-> left, right - introduction rule for disjuntion\n-> exists x - introduction rule for existencial quantification\n-> apply H -  elimination rule for negation, implication and universal quantification\n-> elim H - elimination rule for conjunction, disjuntion and existencial quantification\n-> destruct H as ... - elimination rule for: [H1 H2] conjunction, [H1 | H2] disjuntion, [x H] exists\n*)\n\n(* =========== Tactics for EQUALITY and REWRITING :\n-> rewrite - rewrites an equality;\n-> rewrite <- - reverse rewrite of an equality;\n-> reflexivity - reflexivity property for equality;\n-> symmetry - symmetry property for equality;\n-> transitivity - transitivity property for equality.\n*)\n\n(* =========== Tactics for EVALUATION and CONVERTIBILITY :\n-> simpl, red, cbv, lazy - performs evaluation;\n-> pattern - performs a beta-expansion on the goal;\n-> change - replaces the goal by a convertible one.\n*)\n\n(* =========== Tactics for INDUCTION :\n-> elim - to apply the corresponding induction principle;\n-> induction - performs induction on an identifier;\n-> destruct - case analysis;\n-> discriminate - discriminates objects built from different constructors;\n-> injection - constructors of inductive types are injections; \n-> inversion - given an inductive type instance, find all the necessary condition \n               that must hold on the arguments of its constructors.\n*)\n\n(* =========== LIBRARIES \nA large base of definitions and facts found in the Coq Standard Library.\nOften used libraries: \n-> Arith - unary integers;\n-> ZArith - binary integers;\n-> List - polymorphic lists;\n\nUseful commands for finding theorems acting on a given identifier:\n-> Search\n-> SearchAbout\n-> SearchPattern\n*)\n\n(* =========== AUTOMATISATION\nFor some specific domains, Coq is able to support some degree of automatisation:\n-> auto - automatically applies theorems from a database;\n-> tauto, intuition - decision procedures for specific classes of goals (e.g. propositional logic);\n-> firstorder - useful to prove facts that are tautologies in intuitionistic FOL;\n-> omega, ring - specialized tactics for numerical properties.\n*)\n\n(* =========== USEFUL tactics and commands...\nTactics:\n-> clear - removes an hypothesis from the environment;\n-> generalize - re-introduce an hypothesis into the goal;\n-> cut, assert - proves the goal through an intermediate result;\n-> pattern - performs eta-expansion on the goal.\n\nCommands:\n-> Admitted - aborts the current proof (property is assumed);\n-> Set Implicit Arguments - makes possible to omit some arguments (when inferable by the system);\n-> Open Scope - opens a syntax notation scope (constants, operators, etc.)\n\nSee the Reference Manual...\n *)\n\n\n(* ================================================================== *)\n\nRequire Import Arith.\n\nSet Implicit Arguments.\n\nSection Parte1.\n(* ****** Prove os lemas desta secção SEM usar táticas automáticas ****** *)\n\nVariables A B : Prop.\nVariable X : Set.\nVariables P Q R W : X -> Prop.\n\n\nLemma questao1 : (A->B) -> ((A/\\B) -> A) /\\ (A -> (A/\\B)).\nProof.\nintro H1.\nsplit.\nintro H2.\ndestruct H2 as [H3 H4].\nexact H3.\nintro H2.\nsplit.\nexact H2.\napply H1.\nexact H2.\nQed.\n\n\nLemma questao2 : ~A \\/ ~B -> ~(A /\\ B).\nProof.\nintro H.\nintro H2.\ndestruct H2 as [H3 H4].\ndestruct H as [H5 | H6].\napply H5.\nexact H3.\napply H6.\nexact H4.\nQed.\n\nLemma questao3 : (forall x y:X, (R y) -> (P x)) -> (exists y:X, (R y)) -> (forall x:X, (P x)).\nProof.\nintros H1 H2.\nintro x.\ndestruct H2 as [y H3].\napply H1 with (y := y).\nexact H3.\nQed.\n\n\nLemma questao4 : (forall z:X, (P z)->(W z)) -> (exists x:X, (P x)/\\(Q x)) -> (exists y:X, (W y)/\\(Q y)).\nProof.\nintros H1 H2.\ndestruct H2 as [x H3].\ndestruct H3 as [H4 H5].\nexists x.\nsplit.\napply H1.\nexact H4.\nexact H5.\nQed.\n\nLemma questao5 : forall (x y:nat), x+2=y -> y>x.\nProof.\nintros.\ninduction H.\nrewrite plus_n_O.\nSearchPattern (_ + _ > _).\napply plus_gt_compat_l.\nSearchPattern (_ > 0).\napply gt_Sn_O.\nQed.\n\nEnd Parte1.\n\n(* ================================================================== *)\n\nSection Parte2.\n\nRequire Import List.\nRequire Import ZArith.\n\nOpen Scope Z_scope.\n\n\nFixpoint Elem (A:Type) (a : A) (l : list A) {struct l} : Prop :=\n  match l with\n  | nil => False\n  | b :: m => b = a \\/ Elem a m\n  end.\n\nFixpoint count (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 (count z l')\n      | right _ => count z l'\n      end\n  end.\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\nInductive Sorted : list Z -> Prop := \n  | sorted0 : Sorted nil \n  | sorted1 : forall z:Z, Sorted (z :: nil) \n  | sorted2 : forall (z1 z2:Z) (l:list Z), \n        z1 <= z2 -> Sorted (z2 :: l) -> Sorted (z1 :: z2 :: l). \n\n\n\nLemma questao6 :  forall (x:Z) (l: list Z), Sorted (x::l) -> Sorted l.\nProof.\nintros x l H.\ninduction l.\n(* base *)\napply sorted0.\n(* ind1 *)\ninversion H.\nexact H4.\nQed.\n\nLemma questao7 : forall (x y:Z) (l: list Z), ~(Elem x (y::l)) -> ~(Elem x l).\nProof.\nintros x y l.\nintro H.\nintro H1.\napply H.\nsimpl.\nright; assumption.\nQed.\n\n                                                                  \nClose Scope Z_scope.\n\nLemma questao8 : forall (x:Z) (l: list Z), (count x l) > O -> Elem x l.\nProof.\ninduction l.\n(* base *)\nsimpl.\nintro H.\ninversion H.\n(* ind *)\nintro H.\nsimpl.\nsimpl in H.\ndestruct Z.eq_dec.\nleft.\nsymmetry; assumption.\nright.\napply IHl; assumption.\nQed.\n\n\nLemma questao9 : forall (A:Type) (x:A) (l1 l2: list A), (Elem x l1) -> SubList l1 l2 -> Elem x l2.\nProof.\nintros.\ninduction H0.\ninduction l.\nexact H.\nsimpl.\nright; assumption.\nsimpl.\nsimpl in H.\ndestruct H as [H1 | H2].\nleft; assumption.\nright.\napply IHSubList; assumption.\nsimpl.\nright.\napply IHSubList; assumption.\nQed.\n\nEnd Parte2.\n\n\n\n\n\n", "meta": {"author": "vitorenesduarte", "repo": "the_coq_proof_assistant", "sha": "6aca5e1b0bba923a6b118838b1442f0876af5009", "save_path": "github-repos/coq/vitorenesduarte-the_coq_proof_assistant", "path": "github-repos/coq/vitorenesduarte-the_coq_proof_assistant/the_coq_proof_assistant-6aca5e1b0bba923a6b118838b1442f0876af5009/test1415_solutions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.6892852782058249}}
{"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\n\nLemma Zabs_Zle_1 : forall z : Z, {Z.abs z = 0%Z} + {(0 < Z.abs z)%Z}.\n\nProof.\nintros.\ndestruct z.\nauto with arith.\nright.\nsimpl in |- *.\napply Z.gt_lt.\napply Zorder.Zgt_pos_0.\nright.\nsimpl in |- *.\napply Z.gt_lt.\napply Zorder.Zgt_pos_0.\nQed.\n\nHint Resolve Zabs_Zle_1: real.\n\n\n\nLemma Zabs_Zle_2 :\n forall z z1 : Z, {z = 0%Z /\\ z1 = 0%Z} + {(0 < Z.abs z)%Z \\/ (0 < Z.abs z1)%Z}.\n\nProof.\nintros.\ndestruct z.\ndestruct z1.\nleft.\nauto with arith.\nright; right.\nsimpl in |- *.\napply Z.gt_lt.\napply Zorder.Zgt_pos_0.\ndo 2 right.\nsimpl in |- *.\napply Z.gt_lt.\napply Zorder.Zgt_pos_0.\nright.\nleft.\nsimpl in |- *.\napply Z.gt_lt.\napply Zorder.Zgt_pos_0.\nright.\nleft.\nsimpl in |- *.\napply Z.gt_lt.\napply Zorder.Zgt_pos_0.\n\nQed.\n\nHint Resolve Zabs_Zle_2: real.\n\n\nLemma Zlt_le_ind : forall z z1 : Z, (z1 <= z)%Z \\/ (z <= z1)%Z.\n\nProof.\nintros.\ncut ({(z1 <= z)%Z} + {(z1 > z)%Z}); [ intro | apply Z_le_gt_dec ].\nelim H.\nintro.\nleft; auto.\nintro; right; apply Zlt_le_weak; apply Z.gt_lt; auto.\nQed.\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/Zdec_complements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.6891477712372769}}
{"text": "(* Copyright 2012-2015 by Adam Petcher.\t\t\t\t*\n * Use of this source code is governed by the license described\t*\n * in the LICENSE file at the root of the source tree.\t\t*)\n\n(* An operation that returns a (uniformly distributed) random element from a list *)\n\nSet Implicit Arguments.\n\nRequire Import fcf.FCF.\n\nSection RndListElem.\n\n  Variable A : Set.\n  Hypothesis eqd : EqDec A.\n\n  Local Open Scope list_scope.\n\n  Definition rndListElem(ls : list A) : Comp (option A) :=\n    match (length ls) with\n      | O => ret None\n      | S _ =>\n        i <-$ [0 .. (length ls));\n          ret (nth_option ls i)\n    end.\n\n  Theorem rndListElem_wf :\n    forall (ls : list A),\n      well_formed_comp (rndListElem ls).\n       \n    intuition.\n    unfold rndListElem.\n    case_eq (length ls); intuition; wftac.\n  Qed.\n\nEnd RndListElem.\n\nLocal Open Scope list_scope.\n\nLemma rndListElem_support: \n      forall (A : Set)(eqd : EqDec A)(ls : list A) a,\n        In a ls <-> \n        In (Some a) (getSupport (rndListElem eqd ls)).\n\n      intuition.\n      unfold rndListElem.\n      case_eq (length ls); intuition.\n      exfalso.\n      destruct ls; simpl in *; intuition.\n      \n      eapply getSupport_In_Seq.\n\n      eapply in_getSupport_RndNat.\n\n      Fixpoint firstIndexOf(A : Set)(eqd : eq_dec A)(ls : list A)(a : A)(def : nat) :=\n        match ls with\n            | nil => def\n            | a' :: ls' =>\n              if (eqd a a') then O else (S (firstIndexOf eqd ls' a def))\n        end.\n\n      Theorem firstIndexOf_in_lt : \n        forall (A : Set)(eqd : eq_dec A)(ls : list A)(a : A)(def : nat),\n          In a ls ->\n          firstIndexOf eqd ls a def < length ls.\n\n        induction ls; intuition; simpl in *;\n        intuition.\n        \n        subst.\n        destruct (eqd a0 a0); subst.\n        omega.\n        intuition.\n\n        destruct (eqd a0 a); subst.\n        omega.\n\n        eapply lt_n_S.\n        eauto.\n\n      Qed.\n      \n      Theorem nth_firstIndexOf : \n        forall (A : Set)(eqd : eq_dec A)(ls : list A)(a : A)(def : nat),\n          In a ls ->\n          nth_option ls (firstIndexOf eqd ls a def) = Some a.\n\n        induction ls; intuition; simpl in *.\n        intuition.\n\n        intuition.\n        subst.\n        destruct (eqd a0 a0); subst; intuition.\n        \n        destruct (eqd a0 a); subst; intuition.\n\n      Qed.\n\n      rewrite <- H0.\n      eapply firstIndexOf_in_lt; eauto.\n      simpl.\n      left.\n\n      eapply nth_firstIndexOf; trivial.\n      \n      unfold rndListElem in *.\n      repeat simp_in_support.\n      discriminate.\n      \n      Theorem nth_option_In : \n        forall (A : Set)(ls : list A)(a : A) i,\n          nth_option ls i = Some a ->\n          In a ls.\n\n        induction ls; intuition; simpl in *.\n        discriminate.\n\n        destruct i.\n        inversion H; clear H; subst.\n        intuition.\n        right.\n        eapply IHls.\n        eauto.\n\n      Qed.\n\n      eapply nth_option_In; eauto.\n\n      Grab Existential Variables.\n      apply O.\n      unfold eq_dec.\n      eapply (EqDec_dec eqd).\n    Qed.\n\n Theorem rndListElem_uniform : \n   forall (A : Set)(eqd : EqDec A)(ls : list A)(a1 a2 : option A),\n     NoDup ls ->\n     In a1 (getSupport (rndListElem _ ls)) ->\n     In a2 (getSupport (rndListElem _ ls)) ->\n     evalDist (rndListElem _ ls) a1 ==\n     evalDist (rndListElem _ ls) a2.\n   \n   intuition.\n   \n   destruct a1.\n   destruct a2.\n   \n   rewrite <- rndListElem_support in *.\n\n   unfold rndListElem.\n   case_eq (length ls); intuition.\n   destruct ls; simpl in *. intuition. omega.\n   \n   eapply comp_spec_impl_eq.\n   \n   eapply comp_spec_seq.\n   apply (Some a).\n   apply (Some a).\n   eapply eq_impl_comp_spec.\n   eapply well_formed_RndNat.\n   omega.\n   eapply well_formed_RndNat.\n   omega.\n   eapply RndNat_uniform.\n   Focus 3.\n   intros.\n   simpl in H5.\n\n   eapply comp_spec_ret.\n   assert (a1 = (firstIndexOf (EqDec_dec _) ls a 0) <->\n     b = (firstIndexOf (EqDec_dec _) ls a0 0)).\n   eapply H5.\n   clear H5.\n   intuition; subst.\n   \n   rewrite H5.\n   eapply nth_firstIndexOf; trivial.\n\n   Theorem nth_firstIndexOf_if : \n     forall (A : Set)(eqd : eq_dec A)(ls : list A) n a,\n       nth_option ls n = Some a ->\n       NoDup ls ->\n       firstIndexOf eqd ls a 0 = n.\n\n     induction ls; intuition; simpl in *.\n     discriminate.\n     inversion H0; clear H0; subst.\n     destruct n.\n     inversion H; clear H; subst.\n     destruct (eqd a0 a0); subst; intuition.\n\n     destruct (eqd a0 a); subst; intuition.\n     exfalso.\n     eapply H3.\n     \n     eapply nth_option_In.\n     eauto.\n\n   Qed.\n\n   symmetry.\n   eapply nth_firstIndexOf_if; intuition.\n\n   rewrite H7.\n   eapply nth_firstIndexOf; trivial.\n   symmetry.\n   eapply nth_firstIndexOf_if; intuition.\n   \n   rewrite <- H2.\n   apply firstIndexOf_in_lt; trivial.\n\n   rewrite <- H2.\n   apply firstIndexOf_in_lt; trivial.\n\n   apply rndListElem_support in H0.\n\n   Theorem nth_option_some : \n     forall (A : Set)(ls : list A) n,\n       n < length ls ->\n       exists a, nth_option ls n = Some a.\n     \n     induction ls; intuition; simpl in *.\n     omega.\n     \n     destruct n.\n     econstructor; eauto.\n     \n     destruct (IHls n).\n     omega.\n     \n     econstructor; eauto.\n     \n   Qed.\n   \n   Theorem rndListElem_support_None : \n     forall (A : Set) eqd (ls : list A),\n       In None (getSupport (rndListElem eqd ls)) <->\n       ls = nil.\n\n     intuition.\n     unfold rndListElem in *.\n     case_eq (length ls); intuition.\n     destruct ls; simpl in *; trivial; discriminate.\n\n     rewrite H0 in H.\n     repeat simp_in_support.\n     apply RndNat_support_lt in H1.\n     \n     edestruct (nth_option_some ls); eauto.\n     rewrite H0.\n     eauto.\n     congruence.\n\n     subst.\n     simpl.\n     intuition.\n\n   Qed.\n\n   Show.\n   \n   apply rndListElem_support_None in H1.\n   subst.\n   simpl in *.\n   intuition.\n\n   \n   destruct a2.\n   apply rndListElem_support in H1.\n   apply rndListElem_support_None in H0.\n   subst.\n   simpl in *.\n   intuition.\n\n   intuition.\n\nQed.\n\n      Theorem nth_firstIndexOf_None : \n        forall (A : Set)(eqd : eq_dec A)(ls : list A),\n          NoDup ls ->\n          forall (a a' : A) i,\n          In a ls ->\n          i <> firstIndexOf eqd ls a O ->\n          nth_option ls i = Some a' ->\n          a <> a'.\n\n        induction 1; intuition; simpl in *.\n        intuition; subst.\n        destruct (eqd a' a'); subst; intuition.\n       \n        destruct i; intuition.\n\n        Lemma not_in_nth_option : \n          forall (A : Set)(ls : list A)(a : A)(i : nat),\n            (~In a ls) ->\n            nth_option ls i = Some a -> \n            False.\n\n          induction ls; intuition; simpl in *.\n          discriminate.\n\n          destruct i.\n          inversion H0; clear H0; subst.\n          intuition.\n          \n          eapply IHls; eauto.\n\n        Qed.\n\n        eapply not_in_nth_option; eauto.\n\n        destruct i; intuition.\n        inversion H3; clear H3; subst.\n        destruct (eqd a' a'); subst; intuition.\n\n        destruct (eqd a' x); subst; intuition.\n        eapply IHNoDup; eauto.\n      Qed.\n\n        Lemma nth_option_not_None : \n          forall (A : Set)(ls : list A)(i : nat),\n            i < length ls ->\n            nth_option ls i = None ->\n            False.\n\n          induction ls; intuition; simpl in *.\n          omega.\n\n          destruct i.\n          discriminate.\n          assert (i < length ls).\n          omega.\n          eauto.\n\n        Qed.\n\n\n    Theorem rndListElem_uniform_gen : \n      forall (A B : Set)(eqda : EqDec A)(eqdb : EqDec B)(ls1 : list A)(ls2 : list B)(a1 :  A)(a2 : B),\n        NoDup ls1 ->\n        NoDup ls2 ->\n        length ls1 = length ls2 ->\n        In a1 ls1 ->\n        In a2 ls2 ->\n        comp_spec \n          (fun x y => x = Some a1 <-> y = Some a2)\n          (rndListElem _ ls1) (rndListElem _ ls2).\n\n      intuition.\n\n      unfold rndListElem.\n      case_eq (length ls1); intuition.\n      rewrite <- H1.\n      rewrite H4.\n\n      eapply comp_spec_ret; intuition.\n      discriminate.\n      discriminate.\n      \n      rewrite <- H1.\n      rewrite H4.\n\n      eapply comp_spec_seq; try eapply None.\n      eapply eq_impl_comp_spec.\n      eapply well_formed_RndNat; omega.\n      eapply well_formed_RndNat; omega.\n      eapply (@RndNat_uniform  (firstIndexOf (EqDec_dec _) ls1 a1 O) (firstIndexOf (EqDec_dec _) ls2 a2 O)).\n \n      rewrite <- H4.\n      apply firstIndexOf_in_lt; trivial.\n      rewrite <- H4.\n      rewrite H1.\n      apply firstIndexOf_in_lt; trivial.\n\n      intuition.\n      eapply comp_spec_ret.\n      intuition.\n      \n      destruct (eq_nat_dec a (firstIndexOf (EqDec_dec _) ls1 a1 O)).\n      subst.\n      assert (b = firstIndexOf (EqDec_dec _) ls2 a2 0); intuition.\n      subst.\n      repeat rewrite nth_firstIndexOf; intuition.\n\n      assert (b <> firstIndexOf (EqDec_dec _) ls2 a2 0).\n      intuition.\n\n      exfalso.\n      eapply nth_firstIndexOf_None.\n      eapply H.\n      eapply H2.\n      eapply n0.\n      eauto.\n      intuition.\n\n      destruct (eq_nat_dec a (firstIndexOf (EqDec_dec _) ls1 a1 O)).\n      subst.\n      assert (b = firstIndexOf (EqDec_dec _) ls2 a2 0); intuition.\n      subst.\n      repeat rewrite nth_firstIndexOf; intuition.\n\n      assert (b <> firstIndexOf (EqDec_dec _) ls2 a2 0).\n      intuition.\n\n      exfalso.\n      eapply nth_firstIndexOf_None.\n      eapply H0.\n      eapply H3.\n      eapply H10.\n      eauto.\n      intuition.\n    Qed.\n\n     Theorem rndListElem_support_exists : \n      forall (A : Set)(eqd : EqDec A)(ls : list A),\n        exists x,\n          In x (getSupport (rndListElem eqd ls)).\n\n      destruct ls; intuition.\n      econstructor.\n      left.\n      eauto.\n\n      unfold rndListElem.\n      unfold length.\n      econstructor.\n      eapply getSupport_In_Seq.\n\n      eapply (@in_getSupport_RndNat O).\n      omega.\n      simpl.\n      intuition.\n    Qed.\n\n    (*\n\n    Theorem rndListElem_uniform_remove_eq : \n      forall (A : Set)(eqd : EqDec A)(ls : list A)(a1 a2 : A),\n        NoDup ls ->\n        evalDist (rndListElem _ (removeFirst (EqDec_dec _) ls a1)) (Some a1) == 0.\n\n      intuition.\n      eapply getSupport_not_In_evalDist.\n      intuition.\n      rewrite <- rndListElem_support in H0.\n      eapply removeFirst_NoDup_not_in; eauto.\n    Qed.\n\n    Notation \"$ c1 \" := (rndListElem _ c1%comp)\n                          (right associativity, at level 89, c1 at next level) : comp_scope.\n\n Theorem rndListElem_support_exists : \n      forall (A : Set)(eqd : EqDec A)(ls : list A),\n        exists x,\n          In x (getSupport (rndListElem eqd ls)).\n\n      destruct ls; intuition.\n      econstructor.\n      left.\n      eauto.\n\n      unfold rndListElem.\n      unfold length.\n      econstructor.\n      eapply getSupport_In_Seq.\n\n      eapply (@in_getSupport_RndNat O).\n      omega.\n      simpl.\n      intuition.\n    Qed.\n\n*)", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/fcf/RndListElem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.6891477594085732}}
{"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 ev_4 : ev 4.\nProof. apply (ev_SS 2 ev_2). Qed.\n\nTheorem ev_8 : ev 8.\nProof. apply (ev_SS 6 (ev_SS 4 ev_4)). Qed.\n\n\n\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.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6891417490702206}}
{"text": "(** Calculation of an abstract machine for arithmetic expressions +\nexceptions + global state . *)\n\nRequire Import List.\nRequire Import ListIndex.\nRequire Import Tactics.\n\n(** * Syntax *)\n\nInductive Expr : Set := \n| Val : nat -> Expr \n| Add : Expr -> Expr -> Expr\n| Throw : Expr\n| Catch : Expr -> Expr -> Expr\n| Get : Expr\n| Put : Expr -> Expr -> Expr.\n\n(** * Semantics *)\n\nDefinition State := nat.\n\nFixpoint eval (x: Expr) (q : State) : (option nat * State) :=\n  match x with\n    | Val n => (Some n , q)\n    | Add x1 x2 => match eval x1 q with\n                   | (Some n, q') => match eval x2 q' with\n                                       | (Some m, q'') => (Some (n + m), q'')\n                                       | (None, q'') => (None, q'')\n                                     end\n                   | (None, q') => (None, q')\n                   end\n    | Throw => (None, q)\n    | Catch x1 x2 => match eval x1 q with\n                     | (Some n, q') => (Some n, q')\n                     | (None, q') => eval x2 q'\n                     end\n    | Get => (Some q,q)\n    | Put x1 x2 => match eval x1 q with\n                   | (Some n, q') => eval x2 n\n                   | (None, q') => (None, q')\n                   end\n  end.\n\n(** * Abstract machine *)\n\nInductive CONT : Set :=\n| NEXT : Expr -> CONT -> CONT\n| ADD : nat -> CONT -> CONT\n| HAND : Expr -> CONT -> CONT\n| PUT : Expr -> CONT -> CONT\n| HALT : CONT\n.\n\nInductive Conf : Set := \n| eval'' : Expr -> State -> CONT -> Conf\n| exec : CONT -> State -> nat -> Conf\n| fail : CONT -> State -> Conf.\n\nNotation \"⟨ x , q , c ⟩\" := (eval'' x q c).\nNotation \"⟪ c , q , v ⟫\" := (exec c q v).\nNotation \"⟨| c , q |⟩\" := (fail c q).\n\n\n\nReserved Notation \"x ==> y\" (at level 80, no associativity).\nInductive AM : Conf -> Conf -> Prop :=\n| am_val n q c : ⟨Val n, q, c⟩ ==> ⟪c, q, n⟫\n| am_add x y c q : ⟨Add x y, q, c⟩ ==> ⟨x, q, NEXT y c⟩\n| am_throw  c q : ⟨Throw, q, c ⟩ ==> ⟨|c, q |⟩\n| am_catch x1 x2 c q : ⟨Catch x1 x2, q,  c ⟩ ==> ⟨x1, q, HAND x2 c⟩\n| am_get q c : ⟨Get, q, c ⟩ ==> ⟪c, q, q ⟫\n| am_put x1 x2 q c : ⟨Put x1 x2, q, c⟩ ==> ⟨x1, q, PUT x2 c⟩\n| am_NEXT y c n q : ⟪NEXT y c, q, n⟫ ==> ⟨y, q, ADD n c⟩\n| am_NEXT_fail y c q : ⟨|NEXT y c, q|⟩ ==> ⟨|c, q|⟩\n| am_ADD c n m q : ⟪ADD n c, q, m⟫ ==> ⟪c, q, n+m⟫\n| am_ADD_fail c n q : ⟨|ADD n c, q|⟩ ==> ⟨|c, q|⟩\n| am_HAND_fail x2 c q : ⟨|HAND x2 c, q|⟩ ==> ⟨x2, q, c⟩\n| am_HAND x2 c n q : ⟪HAND x2 c, q, n⟫ ==> ⟪c, q, n⟫\n| am_PUT x2 c q' n : ⟪PUT x2 c, q', n⟫ ==> ⟨x2, n, c⟩\n| am_PUT_fail x2 c q' : ⟨|PUT x2 c, q'|⟩ ==> ⟨|c, q'|⟩\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 q c : ⟨x, q, c⟩ =>> match eval x q with\n                                 | (Some n, q') => ⟪c, q', n⟫\n                                 | (None, q')     => ⟨|c, q'|⟩\n                                 end.\n(** Setup the induction proof *)\n\nProof.\n  intros.\n  generalize dependent c.\n  generalize dependent q.\n  induction x;intros.\n\n(** Calculation of the abstract machine *)\n\n  begin\n  ⟪c, q, n⟫.\n  <== { apply am_val }\n  ⟨Val n, q, c⟩.\n  [].\n\n  begin\n    match eval x1 q with\n    | (Some n, q') => match eval x2 q' with\n                      | (Some m, q'') => ⟪c, q'', n+m⟫\n                      | (None, q'') => ⟨|c, q''|⟩\n                      end\n    | (None, q') => ⟨|c, q'|⟩\n    end.\n  <<= { apply am_ADD }\n    match eval x1 q with\n    | (Some n, q') => match eval x2 q' with\n                      | (Some m, q'') => ⟪ADD n c, q'', m⟫\n                      | (None, q'') => ⟨|c, q''|⟩\n                      end\n    | (None, q') => ⟨|c, q'|⟩\n    end.\n  <<= { apply am_ADD_fail }\n    match eval x1 q with\n    | (Some n, q') => match eval x2 q' with\n                      | (Some m, q'') => ⟪ADD n c, q'', m⟫\n                      | (None, q'') => ⟨|ADD n c, q''|⟩\n                      end\n    | (None, q') => ⟨|c, q'|⟩\n    end.\n  <<= { apply IHx2 }\n    match eval x1 q with\n    | (Some n, q') => ⟨x2, q', ADD n c⟩\n    | (None, q') => ⟨|c, q'|⟩\n    end.\n  <<= { apply am_NEXT }\n    match eval x1 q with\n    | (Some n, q') => ⟪NEXT x2 c, q', n⟫\n    | (None, q') => ⟨|c, q'|⟩\n    end.\n  <<= { apply am_NEXT_fail }\n    match eval x1 q with\n    | (Some n, q') => ⟪NEXT x2 c, q', n⟫\n    | (None, q') => ⟨|NEXT x2 c, q'|⟩\n    end.\n  <<= { apply IHx1 }\n      ⟨x1, q, NEXT x2 c⟩.\n  <== {apply am_add}\n      ⟨Add x1 x2, q, c⟩.\n  [].\n\n\n  begin\n    ⟨|c, q|⟩.\n  <== {apply am_throw}\n    ⟨Throw, q, c ⟩. \n  [].\n\n  begin\n      match eval x1 q with\n      | (Some n, q') => ⟪c, q', n⟫\n      | (None, q')   => match eval x2 q' with\n                        | (Some m, q'') => ⟪c, q'', m⟫\n                        | (None, q'')   => ⟨|c, q''|⟩\n                        end\n      end.\n  <<= {apply IHx2}\n      match eval x1 q with\n      | (Some n, q') => ⟪c, q', n⟫\n      | (None, q')   => ⟨x2, q', c⟩\n      end.\n  <<= {apply am_HAND_fail}\n      match eval x1 q with\n      | (Some n, q') => ⟪c, q', n⟫\n      | (None, q')   => ⟨|HAND x2 c, q'|⟩\n      end.\n  <<= {apply am_HAND}\n      match eval x1 q with\n      | (Some n, q') => ⟪HAND x2 c, q', n⟫\n      | (None, q')   => ⟨|HAND x2 c, q'|⟩\n      end.\n  <<= {apply IHx1}\n      ⟨x1, q, HAND x2 c⟩.\n  <== {apply am_catch}\n      ⟨Catch x1 x2, q, c⟩.\n  [].\n\n  begin\n    ⟪c, q, q ⟫.\n  <== {apply am_get}\n    ⟨Get, q, c ⟩.\n  [].\n\n\n  begin\n    match eval x1 q with\n    | (Some n, q') => match eval x2 n with\n                      | (Some m, q'') => ⟪c, q'', m⟫\n                      | (None, q'')   => ⟨|c, q''|⟩\n                      end\n    | (None, q')   => ⟨|c, q'|⟩\n    end.\n  <<= {apply IHx2}\n    match eval x1 q with\n    | (Some n, q') => ⟨x2, n, c⟩\n    | (None, q')   => ⟨|c, q'|⟩\n    end.\n  <<= {apply am_PUT}\n    match eval x1 q with\n    | (Some n, q') => ⟪PUT x2 c, q', n⟫\n    | (None, q')   => ⟨|c, q'|⟩\n    end.\n  <<= {apply am_PUT_fail}\n    match eval x1 q with\n    | (Some n, q') => ⟪PUT x2 c, q', n⟫\n    | (None, q')   => ⟨|PUT x2 c, q'|⟩\n    end.\n  <<= {apply IHx1}\n    ⟨x1, q, PUT x2 c⟩.\n  <== {apply am_put}\n    ⟨Put x1 x2, q, c⟩.\n  [].\nQed.\n  \n", "meta": {"author": "pa-ba", "repo": "cps-defun", "sha": "2f2c9d3e45f4a7fb12dadbff41579d0fa5a085bf", "save_path": "github-repos/coq/pa-ba-cps-defun", "path": "github-repos/coq/pa-ba-cps-defun/cps-defun-2f2c9d3e45f4a7fb12dadbff41579d0fa5a085bf/StateGlobal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.7853085733507947, "lm_q1q2_score": 0.6890900516743905}}
{"text": "Require Import ZArith Lia Znumtheory.\n\n(** * Contains some useful lemmas not in stdlib and a tactic *)\n\n\n(** A convenient and simple tactic to prove 0<x or 0<>x *)\n\nLemma Zmult_neq_0_compat : forall a b, 0 <> a -> 0 <> b -> 0 <> a * b.\nProof.\n  intros [] [] P Q I; simpl in *;\n    inversion I; tauto.\nQed.\n\nLemma Zmult_le_1_compat : forall a b, 1 <= a -> 1 <= b -> 1 <= a * b.\nProof.\n  intros a b.\n  replace a with (1 + (a - 1)) by lia.\n  replace b with (1 + (b - 1)) by lia.\n  generalize (a - 1).\n  generalize (b - 1).\n  intros c d.\n  intros.\n  assert (0 <= c) by lia.\n  assert (0 <= d) by lia.\n  ring_simplify.\n  assert (0 <= d * c) by auto with *.\n  lia.\nQed.\n\nLemma Zsquare_pos : forall x, 0 <> x -> 0 < x * x.\nProof.\n  intros [] E; simpl; reflexivity || tauto.\nQed.\n\nLtac notzero :=\n  lazymatch goal with\n  | |- ?a <> 0 => apply not_eq_sym; notzero\n  | |- ?a > 0 => cut (0 < a); [ apply Zcompare_Gt_Lt_antisym | ]; notzero\n  | |- 0 < ?a * ?a => apply Zsquare_pos; notzero\n  | |- 0 < ?a ^ 2 => replace (a ^ 2) with (a * a) by ring; notzero\n  | |- 0 <  ?a * ?b => apply Zmult_lt_0_compat; notzero\n  | |- 0 <> ?a * ?b => apply Zmult_neq_0_compat; notzero\n  | |- 0 < Zpos _ => reflexivity\n  | |- 0 > Zneg _ => reflexivity\n  | |- 0 <> Zpos _ => let I := fresh \"I\" in intros I; inversion I\n  | |- 0 <> Zneg _ => let I := fresh \"I\" in intros I; inversion I\n  | Pp : prime ?p |- 0 < ?p => pose proof prime_ge_2 p Pp; lia\n  | Pp : prime ?p |- 0 <> ?p => pose proof prime_ge_2 p Pp; lia\n  | Pp : prime ?p |- 1 <> ?p => pose proof prime_ge_2 p Pp; lia\n  | Pp : prime ?p |- ?p <> 0 => pose proof prime_ge_2 p Pp; lia\n  | Pp : prime ?p |- ?p <> 1 => pose proof prime_ge_2 p Pp; lia\n  | Pp : prime ?p |- ?p > 0 => pose proof prime_ge_2 p Pp; lia\n  | |- 0 < _  => auto with *; try lia\n  | |- 0 <> _ => auto with *; try lia\n  | |- _ => idtac\n  end.\n\n\n(** Subsumed by tactic [notzero] but also useful, since it shows up in\nSearch *)\n\nLemma prime_not_0 p : prime p -> p <> 0.\nProof.\n  intro; notzero.\nQed.\n\nLemma prime_not_1 p : prime p -> p <> 1.\nProof.\n  intro; notzero.\nQed.\n\n\n(** Extraction from the Zdivide predicate *)\n\nLemma Zdivide_inf : forall a b, (a | b) -> { q | b = q * a }.\nProof.\n  intros a b D.\n  exists (b / a).\n  rewrite Zmult_comm.\n  destruct (Z.eq_dec a 0).\n    subst; destruct D; lia.\n    \n    apply Z_div_exact_full_2; auto with *.\n    apply Zdivide_mod; auto.\nDefined.\n\n\n(** About Zmod or Zdiv *)\n\nLemma Z_mult_div_mod : forall a b, b <> 0 -> b * (a / b) = a - a mod b.\nProof.\n  intros a b N.\n  pose proof Z_div_mod_eq_full a b; lia.\nQed.\n\nLemma Zdivide_square : forall a b, (a | b) -> (a * a | b * b).\nProof.\n  intros a b (k, Ek).\n  exists (k * k); subst; ring.\nQed.\n\nLemma Zmult_divide_compat_rev_l: forall a b c : Z, c <> 0 -> (c * a | c * b) -> (a | b).\nProof.\n  intros a b c Nc (k, Hk).\n  exists k.\n  eapply Zmult_reg_l; eauto.\n  rewrite Hk; ring.\nQed.\n\nLemma Z_mult_div_bounds : forall a b, 0 < b -> a - b < b * (a / b) <= a.\nProof.\n  intros a b N; split.\n    pose proof Z_mod_lt a b.\n    rewrite Z_mult_div_mod; lia.\n    \n    apply Z_mult_div_ge; lia.\nQed.\n\n\n(** About square *)\n\nLemma Zle_0_square : forall a, 0 <= a * a.\nProof.\n  intros []; intuition; try (simpl; intro H; inversion H).\nQed.\n\nLemma Zeq_0_square : forall a, a * a = 0 -> a = 0.\nProof.\n  intros [] H; intuition simpl; inversion H.\nQed.\n\nLemma rewrite_power_2 : forall x, x ^ 2 = x * x.\nProof.\n  (* TODO virer ça .. ? *)\n  intros; ring.\nQed.\n\nLemma sqrt_eq_compat : forall a b, 0 <= a -> 0 <= b ->\n  a * a = b * b -> a = b.\nProof.\n  intros a b Pa Pb E.\n  destruct (Z.eq_dec 0 (a + b)) as [F|F].\n    lia.\n    \n    cut (a - b = 0); [ lia | ].\n    apply (Zmult_reg_l _ _ (a + b)); notzero.\n    ring_simplify.\n    rewrite rewrite_power_2, E.\n    ring.\nQed.\n\nLemma sqrt_eq_compat_abs : forall a b, a * a = b * b -> Z.abs a = Z.abs b.\nProof.\n  intros a b E.\n  destruct (Z.eq_dec 0 (Z.abs a + Z.abs b)) as [F|F].\n    lia.\n    \n    cut (Z.abs a - Z.abs b = 0); [ lia | ].\n    apply (Zmult_reg_l _ _ (Z.abs a + Z.abs b)); notzero.\n    ring_simplify.\n    rewrite <- Z.abs_square, <- (Z.abs_square b) in E.\n    rewrite rewrite_power_2, E.\n    ring.\nQed.\n\nLemma sqrt_le_compat : forall a b, 0 <= a -> 0 <= b ->\n  a * a <= b * b -> a <= b.\nProof.\n  intros a b Pa Pb E.\n  destruct (Z.eq_dec 0 (a + b)) as [F|F].\n    lia.\n    \n    cut (0 <= b - a); [ lia | ].\n    apply Zmult_le_reg_r with (a + b); notzero.\n    ring_simplify.\n    do 2 rewrite rewrite_power_2; lia.\nQed.\n\n\n(** About Z.abs *)\n\nLemma Zabs_nat_inj : forall a b, 0 <= a -> 0 <= b -> Z.abs_nat a = Z.abs_nat b -> a = b.\nProof.\n  intros a b Pa Pb E.\n  rewrite <- (Z.abs_eq a), <- (Z.abs_eq b); eauto.\n  do 2 rewrite <- inj_Zabs_nat.\n  auto.\nQed.\n\n\n(* TODO (prouver et déplacer) ou virer *)\nLemma Zdivide_square_rev : forall a b, (a * a | b * b) -> (a | b).\nProof.\n  intros a b D.\n  destruct (Z.eq_dec a 0).\n    subst; simpl in D.\n    destruct D as (q, Hq); ring_simplify (q * 0) in Hq.\n    destruct b; inversion Hq.\n    exists 0; ring.\n    \n    exists (b / a).\n    rewrite Zmult_comm, Z_mult_div_mod; auto.\n\n    (* TODO déplacer et prouver : inutilisé mais intéressant.\n    un peu intéressant, c'est dur environ comme sqrt(n)∈Q => sqrt(n)∈N *)\nAbort.\n\nLemma Zpow_mod (a b m : Z) : (a ^ b) mod m = ((a mod m) ^ b) mod m.\nProof.\n  assert (b < 0 \\/ 0 <= b) as [bz | bz] by lia.\n  - rewrite 2 Z.pow_neg_r; auto.\n  - rewrite <-(Z2Nat.id b); auto.\n    rewrite <-2Zpower_nat_Z.\n    generalize (Z.to_nat b); intros n. clear b bz.\n    destruct (Z.eq_dec m 0).\n    + subst. now rewrite !Zmod_0_r.\n    + induction n. easy. simpl.\n      rewrite Z.mul_mod, IHn, Z.mul_mod_idemp_r; auto.\nQed.\n\n(* When we already have a proof [pr] of [P] and the goal is [Q], it is\n   enough to prove [P = Q] *)\n\nLtac exact_eq pr :=\n  generalize pr;\n  let A := fresh in\n  assert (A : forall P Q : Prop, P = Q -> P -> Q) by congruence;\n  apply A; clear A.\n\n(* If [H] is a hypothesis of the form [P -> Q], assert a proof of [P]\n   and remove the [P ->] from [H] *)\n\nTactic Notation \"spec\" hyp(H) :=\n  match type of H with\n  | ?P -> _ =>\n    let h := fresh in\n    assert (h : P); [ | specialize (H h); clear h ]\n  end.\n\nTactic Notation \"spec\" hyp(H) \"by\" tactic(t) :=\n  match type of H with\n  | ?P -> _ =>\n    let h := fresh in\n    assert (h : P) by t;\n    specialize (H h); clear h\n  end.\n", "meta": {"author": "coq-community", "repo": "coqtail-math", "sha": "be26e1a6a52f2e13e0779c68aba685ddfb4f0535", "save_path": "github-repos/coq/coq-community-coqtail-math", "path": "github-repos/coq/coq-community-coqtail-math/coqtail-math-be26e1a6a52f2e13e0779c68aba685ddfb4f0535/Arith/Ztools.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6890900488465023}}
{"text": "Require Import Bool Nat Arith.\n\nInductive lst : Type := Nil : lst | Cons : nat -> lst -> lst.\n\nScheme Equality for lst.\n\nInductive queue : Type := Queue : lst -> lst -> queue.\n\nFixpoint len (len_arg0 : lst) : nat\n           := match len_arg0 with\n              | Nil => 0\n              | Cons x y => plus 1 (len y)\n              end.\n\nDefinition qlen (qlen_arg0 : queue) : nat\n           := let 'Queue x y := qlen_arg0 in\n              plus (len x) (len y).\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint butlast (butlast_arg0 : lst) : lst\n           := match butlast_arg0 with\n              | Nil => Nil\n              | Cons n x => if lst_beq x Nil then Nil else Cons n (butlast x)\n              end.\n\nDefinition qpopback (qpopback_arg0 : queue) : queue\n           := match qpopback_arg0 with\n              | Queue x (Cons n y) => Queue x y\n              | Queue x Nil => Queue (butlast x) Nil\n              end.\n\nDefinition isAmortized (isAmortized_arg0 : queue) : bool\n           := let 'Queue x y := isAmortized_arg0 in\n              leb (len y) (len x).\n\nDefinition isEmpty (isEmpty_arg0 : queue) : bool\n           := let 'Queue x y := isEmpty_arg0 in\n              andb (lst_beq x Nil) (lst_beq y Nil).\n\nLemma len_butlast : forall (l : lst) (n : nat), S (len (butlast (Cons n l))) = len (Cons n l).\nProof.\n  intros.\n  generalize dependent n.\n  induction l.\n  - reflexivity.\n  - intros. simpl. simpl in IHl. rewrite IHl. reflexivity.\nQed.\n\nTheorem theorem0 : forall (q : queue) (n : nat), isAmortized q && negb (isEmpty q) = true -> eq (plus 1 (qlen (qpopback q))) (qlen q).\nProof.\n  intros.\n  destruct q.\n  destruct l0.\n  - simpl. rewrite <- plus_n_O. destruct l.\n    + simpl in H. discriminate.\n    + rewrite len_butlast. apply plus_n_O.\n  - simpl. apply plus_n_Sm.\nQed.\n", "meta": {"author": "ana-brendel", "repo": "coq-benchmarks", "sha": "78b9ca2993b0fb579d814ed17e63c6859e79681c", "save_path": "github-repos/coq/ana-brendel-coq-benchmarks", "path": "github-repos/coq/ana-brendel-coq-benchmarks/coq-benchmarks-78b9ca2993b0fb579d814ed17e63c6859e79681c/testing_results_initial/old_script_testing/HasSummary/lia/queue_popback/queue_popback.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.7853085834000791, "lm_q1q2_score": 0.6890900453952284}}
{"text": "Require Import List.\nRequire Import Nat.\nRequire Import Bool.\nRequire Export Coq.Arith.Compare_dec.\nRequire Import Coq.Arith.Lt.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Lia.\nImport ListNotations.\n\nLemma eqb_reflect : forall x y, reflect (x = y) (x =? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.eqb_eq.\nQed.\n\nLemma ltb_reflect : forall x y, reflect (x < y) (x <? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.ltb_lt.\nQed.\n\nLemma leb_reflect : forall x y, reflect (x <= y) (x <=? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.leb_le.\nQed.\n\nLtac bdestruct X :=\n  let H := fresh in let e := fresh \"e\" in\n   evar (e: Prop);\n   assert (H: reflect e X); subst e;\n    [eauto with bdestruct\n    | destruct H as [H|H];\n       [ | try first [apply not_lt in H | apply not_le in H]]].\n#[export]\nHint Resolve ltb_reflect leb_reflect eqb_reflect : bdestruct.\n\nLemma eq_list {A} : forall (a : A) (l1 l2 : list A),\n  a :: l1 = a :: l2 -> l1 = l2.\nProof.\n  intros.\n  inversion H. reflexivity.\nQed.\n\n(** * Insertion\n\nInserting a number into a list will guarantee the number appears exactly once.\n*)\nFixpoint insert (i : nat) (l : list nat) :=\n  match l with\n  | [] => [i]\n  | h :: t => if i <? h then i :: h :: t  \n              else if i =? h then l\n              else h :: insert i t\n  end.\n\nLemma insert_lt : forall (n h : nat) (t : list nat),\n  n < h -> insert n (h :: t) = n :: h :: t.\nProof.\n  intros.\n  apply Nat.ltb_lt in H as H1.\n  unfold insert. rewrite H1. reflexivity.\nQed.\n\nLemma insert_eq : forall (n h : nat) (t : list nat),\n  n = h -> insert n (h :: t) = h :: t.\nProof.\n  intros.\n  apply Nat.eqb_eq in H as H1. \n  unfold insert.\n  destruct (ltb_reflect n h). \n  contradict l. Nat.order.\n  rewrite H1. reflexivity.\nQed.\n\nLemma insert_gt : forall (n h : nat) (t : list nat),\n  n > h -> insert n (h :: t) = h :: (insert n t).\nProof.\n  intros.\n  apply Nat.ltb_lt in H as H1.\n  unfold insert.\n  destruct (ltb_reflect n h). \n  contradict l. apply le_not_lt. lia.\n  destruct (eqb_reflect n h). \n  contradict e. lia. reflexivity.\nQed.\n\nTheorem insert_inv : forall (n : nat) (l : list nat),\n  In n (insert n l).\nProof.\n  intros.\n  induction l.\n  - (* Base case: l = [] *)\n    unfold insert; unfold In. auto.\n  - (* Inductive case: l = a::l *)\n    assert (n = a \\/ n > a \\/ n < a). lia.\n    inversion H.\n  -- (* Subcase: n = a *) \n    rewrite <- H0. apply Nat.eqb_eq in H0 as H1. unfold insert.\n    destruct (ltb_reflect n n). apply (in_eq n (n :: l)).\n    rewrite <- H0 in H1. rewrite H1. apply (in_eq n l).\n  -- inversion H0.\n  --- (* Subcase: n > a *)\n      apply (insert_gt n a l) in H1 as H2. rewrite H2.\n      apply (in_cons a n (insert n l)). assumption.\n  --- (* Subcase: n < a *)\n      apply (insert_lt n a l) in H1 as H2. rewrite H2.\n      apply (in_eq n (a :: l)).\nQed.\n\nTheorem insert_preserves_elts : forall (e n : nat) (l : list nat),\n  In e l -> In e (insert n l).\nProof.\n  intros. induction l.\n  - contradict H.\n  - (* Inductive case: l = a :: l *) \n    assert (e = a \\/ e <> a). lia. inversion H0.\n    + (* Case: e = a *) \n      assert (n = a \\/ n < a \\/ n > a). lia. inversion H2.\n      ++ apply (insert_eq n a l) in H3. rewrite H3. assumption.\n      ++ inversion H3.\n      +++ (* Subcase: n = a *)\n          apply (insert_lt n a l) in H4 as H5. rewrite H5. rewrite <- H1.\n          unfold In. auto.\n      +++ (* Subcase n < a *)\n          apply (insert_gt n a l) in H4 as H5. rewrite H5. rewrite <- H1.\n          apply (in_eq e (insert n l)).\n    + (* Case: e <> a *)\n      assert (n = a \\/ n < a \\/ n > a). lia. inversion H2.\n    ++ (* Subcase: a = n *)\n       apply (insert_eq n a l) in H3 as H4. rewrite H4. assumption.\n    ++ inversion H3.\n    +++ (* Subcase: n < a *)\n        apply (insert_lt n a l) in H4 as H5. rewrite H5.\n        assert (e = n \\/ e <> n). lia. inversion H6.\n        rewrite H7. apply (in_eq n (a::l)).\n        unfold In. simpl; auto.\n    +++ (* Subcase: n > a *)\n        apply (insert_gt n a l) in H4 as H5. rewrite H5.\n        assert (e = n \\/ e <> n). lia. inversion H6.\n        rewrite H7. apply (in_cons a n (insert n l)). apply (insert_inv n l).\n        apply (in_cons a e (insert n l)).\n        inversion H. apply eq_sym in H8. contradict H8. assumption.\n         apply IHl. assumption.\nQed.\n\nTheorem insert_nonempty : forall (n : nat) (l : list nat),\n  [] <> (insert n l).\nProof. intros. induction l.\n  - unfold insert. apply nil_cons.\n  - assert (n < a \\/ n = a \\/ n > a). lia. inversion H.\n  + apply (insert_lt n a l) in H0 as H1. rewrite H1. discriminate.\n  + inversion H0.\n  ++ apply (insert_eq n a l) in H1 as H2. rewrite H2. discriminate.\n  ++ apply (insert_gt n a l) in H1 as H2. rewrite H2. discriminate.\nQed.\n\n\n(** Now we have an inductive way to specify if our set of [nat]\nis sorted or not. *)\nInductive sorted : list nat -> Prop :=\n| sorted_nil :\n    sorted []\n| sorted_1 : forall x,\n    sorted [x]\n| sorted_cons : forall x y l,\n    x < y -> sorted (y :: l) -> sorted (x :: y :: l).\n\nTheorem sorted_tl : forall (n : nat) (l : list nat),\n  sorted (n :: l) -> sorted l.\nProof.\n  intros. induction l.\n  - apply sorted_nil.\n  - inversion H. assumption.\nQed.\n\nLemma sorted_head : forall (n a : nat) (l : list nat),\n  sorted (a :: l) -> Some a = hd_error (insert n (a :: l)) \\/ Some n = hd_error (insert n (a :: l)).\nProof.\n  intros.\n  assert (a < n \\/ n = a \\/ a > n). lia. inversion H0.\n  - (* Case 1: a < n *)\n    apply (insert_gt n a l) in H1. left. rewrite H1. unfold hd_error. reflexivity.\n  - inversion H1.\n  + (* Case 2: a = n *)\n    apply (insert_eq n a l) in H2. left. rewrite H2. unfold hd_error. reflexivity.\n  + (* Case 3: a > n *)\n    apply (insert_lt n a l) in H2. right. rewrite H2. unfold hd_error. reflexivity.\nQed.\n\nLemma sorted_head_ge : forall (n a : nat) (l : list nat),\n  sorted (a :: l) -> n >= a -> Some a = hd_error (insert n (a :: l)).\nProof.\n  intros. assert (n = a \\/ n > a). lia. inversion H1.\n  - (* Case: a = n *)\n    apply (insert_eq n a l) in H2. rewrite H2. unfold hd_error; reflexivity.\n  - (* Case: n > a *)\n    apply (insert_gt n a l) in H2. rewrite H2. unfold hd_error; reflexivity.\nQed.\n\n(*\nLemma sorted_tail : forall (n : nat) (l l0 : list nat),\n  sorted l -> n :: l0 = insert n l -> (~(In n l) -> l0 = l).\nProof.\n  intros. inversion H.\n  destruct l as [|a tl]. \n  - (* Case: l = [] *)\n  unfold insert in H0; injection H0; auto.\n  - (* Case: l = a::tl *)\n  (* Goal: l0 = a :: tl *)\n  inversion H as [|b|b tl']. (* sorted (a :: tl) can be considerd in two \n  subcases: tl=[] and sorted_cons : a < b -> sorted (b::tl') -> sorted(a::b::tl').\n  The sorted_nil case isn't possible. *)\n  + (* Subcase: l = a::[] *)\n  rewrite <- H3 in H; rewrite <- H3 in H0; rewrite <- H3 in H1.\n  \n  - (* Subcase: l = a::b::tl' *)\n  apply sorted_tl in H as IH. \n  apply IHtl in IH.\n  inversion H.\n  + (* Subcase: tl = []; goal becomes l0 = [a] *)\n  rewrite <- H4 in H0.\n  \n  inversion H0.\n  assert (sorted []) as IH. apply sorted_nil.\n  apply IHtl in IH.\n  \n  apply IHtl in H1.\n  assert(In n (insert n tl)).\n\n  assert (a < n \\/ n = a \\/ a > n). lia.\n  inversion H1.\n  - apply (insert_gt n a l) in H2 as H3.\n    assert (n :: l0 = a :: insert n l). { rewrite <- H3; rewrite <- H0; reflexivity. }\nAdmitted.\n\nLemma sorted_insert_sorted_tl : forall (n : nat) (l : list nat),\n  sorted (insert n l) -> sorted l.\nProof.\n  intros. induction l.\n  - apply sorted_nil.\n  - (* Inductive case: l = a :: l *)\n    assert (n < a \\/ n = a \\/ n > a). lia. inversion H0.\n  + (* Subcase: n < a *)\n    apply (insert_lt n a l) in H1 as H2. rewrite H2 in H.\n    apply (sorted_cons n a l) in H1. apply sorted_tl in H1 as H3. assumption.\n    apply sorted_tl in H. assumption.\n  + inversion H1.\n  ++ (* Subcase: n = a *)\n     apply (insert_eq n a l) in H2 as H3. rewrite H3 in H. assumption.\n  ++ (* Subcase: n > a *)\n     apply (insert_gt n a l) in H2 as H3. rewrite H3 in H.\n     apply sorted_tl in H as IH. apply IHl in IH.\n     inversion IH. apply sorted_1. rewrite <- H4 in H.\n     assert (x < n \\/ x = n \\/ x > n). lia. inversion H5.\n     (* Sub-subcases [sorted [a; x]]. *)\n     * (* Sub-subcase: x < n *)\n       apply (insert_gt n x []) in H6 as H7. rewrite H7 in H. unfold insert in H.\n       inversion H. apply (sorted_cons a x []) in H10 as H13. assumption.\n       apply sorted_1.\n     * inversion H6.\n     ** (* Sub-subcase: x = n *) apply eq_sym in H7.\n        apply (insert_eq n x []) in H7 as H8. rewrite H8 in H. assumption.\n     ** (* Sub-subcase: x > n *)\n        assert (a < x). lia.\n        apply (sorted_cons a x []) in H8. assumption. apply sorted_1.\n     (* Subcases to prove [sorted (a :: x :: y :: l0)] *)\n     * apply (sorted_cons x y l0) in H4 as H4a. inversion H. contradict H9.\n       apply (insert_nonempty n l).\n       assert (Some y0 = hd_error (insert n l)). { rewrite <- H8. unfold hd_error; reflexivity. }\n       assert (x = y0 \\/ n = y0). { apply (sorted_head n x (y :: l0)) in H4a as H4b.\n       rewrite H6 in H4b. rewrite <- H11 in H4b. inversion H4b.\n       left. injection H12. auto.\n       right. injection H12. auto. }\n       inversion H12.\n     ** (* insert n l = x :: (stuff) *) \n       rewrite <- H13 in H8; rewrite <- H13 in H10; rewrite <- H13 in H9.\n       apply (sorted_cons a x (y :: l0)) in H9. apply H9. apply H4a.\n     ** (* insert n l = n :: l *)\n       rewrite <- H13 in H8; rewrite <- H13 in H10; rewrite <- H13 in H9.\n       inversion H8. unfold insert in H15. rewrite <- H6 in H15. \n       apply (sorted_cons a n (y :: l0)) in H9. apply H9.\n        sorted (a :: n :: y :: l0)\n       rewrite H6 in H4b. \n        apply (insert_lt n x []) in H7 as H8. rewrite H8 in H.\n     unfold insert in H. \n     \n     induction l. apply sorted_1.\n     inversion IH. rewrite <- H6 in IH.\nAdmitted.\n*)\n\nLemma sorted_split : forall (l1 l2 : list nat),\n  sorted (l1 ++ l2) -> sorted l1 /\\ sorted l2.\nProof. intros. induction l1.\n  - rewrite (app_nil_l l2) in H; split. apply sorted_nil. apply H.\n  - rewrite <- (app_comm_cons l1 l2 a) in H. apply sorted_tl in H as H1.\n    apply IHl1 in H1. split. destruct l1.\n  -- apply sorted_1.\n  -- inversion H. assert (sorted (n :: l1)). apply H1. apply sorted_tl in H6 as H7.\n     apply (sorted_cons a n l1). assumption. assumption.\n  -- apply H1.\nQed.\n\nLemma sorted_head_min : forall (n k : nat) (l : list nat),\n  sorted (n :: l) -> In k l -> n < k.\nProof.\n  intros. induction l.\n  - contradict H0.\n  - apply (sorted_tl n (a::l)) in H as IH. destruct l.\n  -- unfold In in H0. inversion H. destruct H0. apply eq_sym in H0. rewrite H0. assumption.\n     contradict H0.\n  -- inversion H. inversion H5. clear H6 H7 H9 H1 H2 H4.\n     assert (n < n0). { rewrite <- H8. assumption. }\n     inversion H0. apply eq_sym in H2. rewrite H2. assumption.\n     apply (sorted_cons n n0 l) in H1. apply IHl in H1 as IH1. assumption. assumption.\n     assumption.\nQed.\n\n(*\nLemma sorted_split_ends : forall (l1 l2 : list nat),\n  sorted (l1 ++ l2) ->\n  (forall (a b : nat), In a l1 /\\ In b l2 -> a < b).\nAdmitted.\nProof. intros. induction l1.\n  - apply proj1 in H0. contradict H0.\n  - apply proj1 in H0 as H1; apply proj2 in H0 as H2.\n    destruct l1.\n -- (* Subcase: l1 = [] *) apply sorted_tl in H as IH. \n    unfold app in IHl1; unfold app in H. assert (a0 = a). { unfold In in H1. intuition. }\n    rewrite H3 in H; rewrite H3 in H1; rewrite H3 in H0.\n    apply (sorted_head b a l2) in H. apply IHl1 in IH. assumption. assumption.\n -- (* Subcase: l1 = n :: l1 *) \n    rewrite <- (app_comm_cons (n :: l1) l2 a0) in H.\n    apply sorted_tl in H as IH. \n    assert (a = a0 \\/ a <> a0). { lia. }\n    inversion H3.\n  + (* a = a0 *) rewrite <- H4 in H; rewrite <- H4 in H1.\n    apply (sorted_head a b ((n :: l1) ++ l2)) in H.\n    assumption. apply (in_or_app (n :: l1) l2 b). auto.\n  + (* a <> a0 *)\n    assert (In a (n :: l1)). { inversion H1. apply eq_sym in H5. \n      contradict H5. assumption. assumption.\n    }\n    apply IHl1 in IH. assumption. split. assumption. assumption.\nQed.\n\nLemma insert_split : forall (n : nat) (l1 l2 : list nat),\n  sorted (l1 ++ n::l2) -> (l1 ++ n::l2) = insert n (l1 ++ n::l2).\nAdmitted.\n*)\n\n(*\n\nTheorem insert_existing_sorted : forall (n : nat) (l : list nat),\n  sorted l -> In n l -> l = insert n l.\nProof.\n  intros.\n  apply in_split in H0 as H1. destruct H1. destruct H1.\n  rewrite H1 in H.\n  apply insert_split in H.\n  rewrite <- H1 in H. apply H.\nQed.\n*)\n\nLemma sorted_in_inv : forall (n h : nat) (tl : list nat),\n  sorted(h :: tl) -> In n (h::tl) -> h=n \\/ (In n tl).\nProof.\n  intros. apply in_inv in H0. trivial.\nQed.\n\nLemma sorted_surgery : forall ( a b : nat) (tl : list nat),\n  sorted (a :: b :: tl) -> sorted (a :: tl).\nProof.\n  intros. inversion H. apply sorted_tl in H4 as H5.\n  destruct tl.\n  - apply sorted_1.\n  - inversion H4.\n    assert (a < n). { Nat.order. }\n    apply (sorted_cons a n tl) in H11. assumption. assumption.\nQed.\n\n\nLemma sorted_in_tl : forall (n h : nat) (tl : list nat),\n  sorted (h :: tl) -> In n tl -> h < n.\nProof.\n  intros. induction tl.\n  - (* Base case: tl = [] *)\n    contradict H0.\n  - (* Inductive case: tl = a::tl *)\n    inversion H.\n(*\n  -- (* Case: sorted_1 *)\n    contradict H0. rewrite <- H3. apply in_nil.\n*)\n  -- (* Case: sorted_cons where [h < y] and [tl = y::l] *)\n    rewrite <- H2 in H0. apply in_inv in H0 as H6.\n    case H6.\n  + (* Subcase: [n = y] *)\n    intro. rewrite H7 in H2. rewrite <- H2 in H3. assumption.\n  + (* Subcase: [In n l] *)\n    intro. apply sorted_surgery in H as IH. apply IHtl in IH.\n    apply IH. assumption.\nQed.\n\nTheorem insert_existing_sorted : forall (n : nat) (l : list nat),\n  sorted l -> In n l -> l = insert n l.\nProof.\n  intros. \n  induction l as [|h tl].\n  - contradict H0. \n  - inversion H.\n  + rewrite <- H3 in H0; rewrite <- H3 in H.\n    assert (h = n). { unfold In in H0. intuition. }\n    rewrite H1; rewrite H1 in H0; rewrite H1 in H.\n    assert (n = n). reflexivity.\n    apply (insert_eq n n []) in H4. symmetry. assumption.\n  + (* Subcase sorted_cons : tl=y::l, h < y, sorted(y :: l) *)\n    apply in_inv in H0. case H0. \n  ++ (* Case of [In h n::tl] when [h = n] *)\n    intro. rewrite H5. rewrite (insert_eq n n (y::l)). reflexivity. reflexivity.\n  ++ (* Case of [In h n::tl] when [In h tl] *)\n    intro. (* apply sorted_tl in H as IH. apply IHtl in IH. *)\n    rewrite <- H2 in H5. apply in_inv in H5. case H5.\n    (* Since [tl = y::l], we do this again! *)\n  +++ intro.  rewrite H6; rewrite H6 in H5; rewrite H6 in H2; rewrite H6 in H3; rewrite H6 in H4.\n    rewrite (insert_gt n h (n :: l)).\n    rewrite (insert_eq n n l). reflexivity. reflexivity. assumption.\n  +++ (* Last case: In n l -> h :: y :: l = insert n (h :: y :: l) *)\n    intro. (* INDUCTION SAVES US, AT LONG LAST! *)\n    apply sorted_tl in H as IH. apply IHtl in IH.\n    rewrite H2. apply (sorted_in_tl n h tl) in H as IH1.\n    apply (insert_gt n h tl) in IH1. rewrite <- IH in IH1. auto.\n    rewrite <- H2. simpl; auto.\n    rewrite <- H2. simpl; auto.\nQed.\n\nLemma eq_lists_eq_len {A} : forall (l1 l2 : list A),\n  l1 = l2 -> length l1 = length l2.\nProof.\n  intros.\n  rewrite H. reflexivity.\nQed.\n\n(*\nTheorem insert_nondecreasing : forall (n : nat) (l : list nat),\n  sorted l -> length l <= length (insert n l).\nProof.\n  intros.\n  assert (In n l \\/ ~In n l).\n  2: { inversion H0.\n  - apply (insert_existing_sorted n l) in H as H2. \n    apply eq_lists_eq_len in H2 as H3. Nat.order. assumption.\n  - \n  assumption.\n  \nAdmitted.\n\n*)\n\n\n\n\n\n\n\n\n\nLemma in_singleton_eq : forall {A} (a x : A),\n  In a [x] -> a = x.\nProof. intros. unfold In in H. intuition. Qed.\n\n\nTheorem insert_singleton_invert : forall (n x : nat) (l : list nat),\n  [x] = (insert n l) -> l = [] \\/ l = [n].\nProof.\n  intros. \n  assert (sorted [x]). apply sorted_1.\n  rewrite H in H0. \n  assert (In n [x]). { rewrite H. apply (insert_inv n l). }\n  apply  (in_singleton_eq n x) in H1. rewrite <- H1 in H.\n  clear H1.\n  induction l as [|n0 l0].\n  - (* Case: l = [] *) left; reflexivity.\n  - (* Case: l = n0::l0 *) \n    assert (n < n0 \\/ n = n0 \\/ n > n0). lia. \n  -- destruct H1.\n  + (* Subcase: n < n0 *)\n    apply (insert_lt n n0 l0) in H1. rewrite H1 in H; rewrite H1 in H0.\n    inversion H0; right; discriminate.\n  + destruct H1.\n  ++ (* Subcase: n = n0 *)\n    apply (insert_eq n n0 l0) in H1. rewrite H1 in H; rewrite H1 in H0.\n    right; symmetry. apply H.\n  ++ (* Subcase: n > n0 *)\n    apply  (insert_gt n n0 l0) in H1 as H2. rewrite H2 in H; rewrite H2 in H0.\n    inversion H0.\n  +++ (* Sub-subcase (sorted_1) : l0 = [] *)\n    right. rewrite <- H5 in H.\n    contradict H5. apply (insert_nonempty n l0).\n  +++ (* Sub-subcase (sorted_cons) [sorted (insert n (n0 :: l0))] becomes : \n         n0 < y -> sorted( y :: l) -> sorted(n0 :: y :: l)*)\n      rewrite <- H4 in H; rewrite <- H4 in H2. left. discriminate.\nQed.\n\nRequire Import Coq.Classes.RelationClasses.\n\nTheorem nat_comparison : forall (a b : nat),\n  a < b \\/ a = b \\/ a > b.\nProof.\n  intros. lia.\nQed.\n\nLemma gt_to_not_ltb : forall (n a : nat),\n  n > a -> Nat.ltb n a = false.\nProof. intros.\n  bdestruct (n <? a); simpl.\n  contradict H0. lia. reflexivity.\nQed.\n\nLemma gt_to_not_eqb : forall (n a : nat),\n  n > a -> Nat.eqb n a = false.\nProof. intros.\n  bdestruct (n =? a); simpl.\n  contradict H0. lia. reflexivity.\nQed.\n\n\nLemma invert_insert_sorted : forall (n a n0 : nat) (l l0 : list nat),\n  sorted (a :: l) -> insert n (a :: l) = a :: n0 :: l0 ->\n  a < n0.\nProof.\n  intros.\n  assert (a > n \\/ a = n \\/ a < n). lia.\n  generalize dependent l0.\n  induction l.\n  - intros. destruct H1.\n  -- (* Subcase: a > n *)\n    apply (insert_lt n a []) in H1 as H2. rewrite H2 in H0.\n    contradict H0. injection. intros. lia.\n  -- destruct H1.\n  --- (* Subcase: a = n *) apply eq_sym in H1.\n    apply (insert_eq n a []) in H1 as H2. rewrite H2 in H0.\n    contradict H0. injection. discriminate.\n  --- (* Subcase: a < n *)\n    apply (insert_gt n a []) in H1 as H2. rewrite H2 in H0.\n    unfold insert in H0. injection H0. intros. rewrite H4 in H1. assumption.\n - (* Inductive case: l = a0::l *)\n  destruct H1.\n  -- intros. apply Nat.ltb_lt in H0 as H2. unfold insert in H1.\n    rewrite H2 in H1. contradict H1. injection.\n    intros. rewrite <- H3 in H1. injection H1. intro. lia.\n  -- destruct H0.\n  + (* Subcase: a = n *) intros. apply eq_sym in H0.\n    apply (insert_eq n a (a0::l)) in H0 as H3.\n    rewrite H3 in H1. injection H1. intros.\n    rewrite H4 in H. inversion H. assumption.\n  + (* Subase: a < n *) intros.\n    apply (sorted_surgery a a0 l) in H as IH.\n    apply (insert_gt n a (a0 :: l)) in H0 as H2.\n    assert (a0 < n \\/ a0 = n \\/ a0 > n). lia.\n    destruct H3.\n  ++ (* a0 < n *)\n    apply (insert_gt n a0 l) in H3 as H4.\n    apply (insert_gt n a (a0 :: l)) in H0 as H5.\n    rewrite H4 in H2. rewrite H2 in H1. injection H1.\n    intros. rewrite H7 in H. inversion H. assumption.\n  ++ destruct H3.\n  * (* Case a0 = n *) apply eq_sym in H3.\n    apply (insert_eq n a0 l) in H3 as H4.\n    rewrite H4 in H2. rewrite H2 in H1. injection H1. intros.\n    inversion H. rewrite H6 in H9. assumption.\n  * (* Case a0 > n *)\n    apply (insert_lt n a0 l) in H3 as H4. \n    assert (insert n (a :: a0 :: l) = a :: insert n (a0 :: l)). assumption.\n    rewrite H4 in H2.\n    rewrite H4 in H5. rewrite H1 in H5. injection H5. intros. rewrite H7. assumption.\nQed. \n\nTheorem insert_preserves_sorted : forall (n : nat) (l : list nat),\n  sorted l -> sorted (insert n l).\nProof.\n  intros.\n  induction l.\n  - unfold insert. apply sorted_1.\n  - apply sorted_tl in H as H1. apply IHl in H1.\n    assert (n < a \\/ n = a \\/ n > a). lia.\n    inversion H0.\n  -- (*  Case: n < a *)\n     apply (insert_lt n a l) in H2 as H3. rewrite H3.\n     apply sorted_cons. assumption. assumption.\n  -- (* Case: n = a *)\n     inversion H2. apply (insert_eq n a l) in H3 as H4. rewrite H4.\n     assumption.\n     (* Case: n > a *)\n     apply (insert_gt n a l) in H3 as H4. rewrite H4. destruct (insert n l).\n  + apply sorted_1.\n  + clear H0; clear H2.\n    apply sorted_tl in H1 as H5.\n    assert (n < n0 \\/ n = n0 \\/ n > n0). lia. inversion H0.\n    (* case: n < n0 *)\n  ++ apply sorted_cons. rewrite <- H2. assumption. assumption.\n  ++ (* case: n = n0 *)\n     inversion H2. apply sorted_cons. rewrite <- H6. assumption. assumption.\n     (* case: n > n0 *)\n     clear H2 H0.\n     inversion H4. apply gt_to_not_ltb in H3 as H8.\n     rewrite H8. rewrite H8 in H2. clear H8; apply gt_to_not_eqb in H3 as H8.\n     rewrite H8; rewrite H8 in H2.\n     apply (invert_insert_sorted n a n0 l l0) in H4 as H7.\n     apply eq_list in H2. rewrite H2. apply sorted_cons. assumption.\n     assumption. assumption.\nQed.\n\n(*\nTheorem insert_preserves_sorted2 : forall (n : nat) (l : list nat),\n  sorted l -> sorted (insert n l).\nProof.\n  intros.\n  induction l.\n  - unfold insert. apply sorted_1.\n  - apply sorted_tl in H as H1. apply IHl in H1.\n    assert (n < a \\/ n = a \\/ n > a). lia.\n    inversion H0.\n  -- apply (insert_lt n a l) in H2 as H3. rewrite H3.\n     apply sorted_cons. assumption. assumption.\n  -- inversion H2.\n  --- apply (insert_eq n a l) in H3 as H4. rewrite H4. assumption.\n  --- apply (insert_gt n a l) in H3 as H4. rewrite H4.\n      destruct (insert n l). apply sorted_1.\n      set (ln := insert n l). inversion H4. auto; simpl.\n  + apply sorted_1.\n  + assert (n = n0 \\/ n <> n0). lia. inversion H5.\n  ++ apply sorted_cons. rewrite <- H6. assumption. rewrite <- H6.\n  +  unfold insert in ln. unfold ln. apply sorted_cons.\n    assumption. apply sorted_1.\n  + \n\n      destruct l.\n  + unfold insert. apply sorted_cons. assumption. apply sorted_1.\n  + \n      set (ln := insert n l). destruct l. auto.\n      apply (sorted_cons a n l) in H3.\n      apply (sorted_tl a (insert n l)) in H1 as H5.\n      apply sorted_tl with (n := a) (l := insert n l) in H1 as H5.\n      apply (sorted_cons a n l) in H3.\nAdmitted.\n*)\n\n\n\n(*\nTheorem insert_preserves_sorted : forall (n : nat) (l : list nat),\n  sorted l -> sorted (insert n l).\nProof.\n  intros.\n  induction l.\n  - unfold insert. apply sorted_1.\n  - apply sorted_tl in H as H1. apply IHl in H1.\n    assert (n < a \\/ n = a \\/ n > a). lia.\n    inversion H0.\n  -- apply (insert_lt n a l) in H2 as H3. rewrite H3.\n     apply sorted_cons. assumption. assumption.\n  -- inversion H2.\n  --- apply (insert_eq n a l) in H3 as H4. rewrite H4. assumption.\n  --- apply (insert_gt n a l) in H3 as H4. rewrite H4.\n      apply (sorted_cons a n l) in H3.\n\n  -- contradict H2. apply insert_nonempty.\n  -- apply (insert_singleton_invert n x l) in H2. rewrite H2.\n     assert (n < a \\/ n = a \\/ n > a). lia.\n     inversion H0.\n  --- apply (insert_lt n a []) in H3 as H4. rewrite H4.\n      apply sorted_cons. assumption. apply sorted_1.\n  --- inversion H3. apply (insert_eq n a []) in H4 as H5. rewrite H5.\n      apply sorted_1.\n      apply (insert_gt n a []) in H4 as H5. rewrite H5. unfold insert.\n      apply sorted_cons. assumption. apply sorted_1.\n  -- auto.\n  --- auto.\n*)\n\nLemma insert_different : forall (a n : nat) (l : list nat),\n  sorted (a :: l) -> a <> n ->\n  (n < a -> sorted (n :: a :: l)) /\\ (a < n -> sorted (a :: insert n l)).\n  (*\nProof.\n  intros. split.\n  - intro H1. apply sorted_cons. assumption. assumption.\n  - intro H1. apply (insert_gt n a l) in H1 as H2. rewrite <- H2.\n\n apply sorted_tl in H as H2. destruct l.\n  -- unfold insert. apply sorted_cons. assumption. apply sorted_1.\n  -- apply (sorted_cons a n (n0 :: l)) in H1. inversion H1.\n     unfold insert.\n  assert (a < n \\/ n > a).\n  2: { split. }\n*)\nAdmitted.\n\n(*\nTheorem insert_if_present :\n  forall (n : nat) (l : list nat),\n  sorted l -> In n l -> insert n l = l.\nProof.\n  intros. induction l.\n  - unfold In in H. contradiction.\n  - bdestruct (n =? a).\n  -- unfold insert. \n     assert (~ n < a). { lia. } (* intuition. *)\n     assert (Nat.ltb n a = false). { apply Nat.nlt_ge in H2 as H3.\n      unfold Nat.ltb. apply leb_correct_conv. intuition.\n     }\n     rewrite H3. apply (Nat.eqb_eq n a) in H1. rewrite H1. reflexivity.\n  -- apply List.in_inv in H0 as H2.\n     assert (List.In n l).  {  firstorder. contradict H0. auto. }\n     apply sorted_tl in H as H4.\n     apply IHl in H3 as IHl2. discriminate. intuition.\n  --- symmetry in H5. contradict H5. auto.\n  --- auto.\n     assert (a < n).\n     2: { intuition. apply Nat.ltb_lt in H5 as H6. unfold insert. apply H6.\n  --- unfold insert. apply Nat.eqb_eq in H5.\n simpl. auto.\n apply (ltb_reflect n a) in H1. auto.\n rewrite H0. rewrite <- H0.\nLemma insert_different : forall (a n : nat) (l : list nat),\n  sorted (a :: l) -> a <> n ->\n  sorted (n :: a :: l) \\/ sorted (a :: insert n l).\n\n*)\n\nFixpoint insert_merge (l1 l2 : list nat) :=\nmatch l1 with\n| [] => l2\n| a::tl => insert_merge tl (insert a l2)\nend.\n\nTheorem insert_merge_sorted : forall (l1 l2 : list nat),\n  sorted l1 -> sorted l2 -> sorted (insert_merge l1 l2).\nProof.\n  intros. generalize dependent l2.\n  induction l1.\n  - (* Base case: l1 = nil *)\n    intros. unfold insert_merge; auto.\n  - (* Inductive case: l1 = a::l1 *)\n    intros.\n    assert (forall l2 : list nat, sorted l2 -> sorted (insert_merge l1 l2)). {\n      apply IHl1. apply sorted_tl in H. assumption.\n    }\n    assert (sorted (insert a l2)). {\n    apply insert_preserves_sorted. assumption.\n    }\n    assert (insert_merge (a :: l1) l2 = insert_merge l1 (insert a l2)). {\n      unfold insert. simpl; auto.\n    }\n    rewrite H3.\n    apply H1 in H2. assumption.\nQed.\n\nTheorem insert_merge_sorted2 : forall (l1 l2 : list nat),\n  sorted l2 -> sorted (insert_merge l1 l2).\nProof.\n  intros. generalize dependent l2.\n  induction l1.\n  - (* Base case: l1 = nil *)\n    intros. unfold insert_merge; auto.\n  - (* Inductive case: l1 = a::l1 *)\n    intros.\n    assert (forall l2 : list nat, sorted l2 -> sorted (insert_merge l1 l2)). {\n      apply IHl1.\n    }\n    assert (sorted (insert a l2)). {\n    apply insert_preserves_sorted. assumption.\n    }\n    assert (insert_merge (a :: l1) l2 = insert_merge l1 (insert a l2)). {\n      unfold insert. simpl; auto.\n    }\n    rewrite H2. apply H0.\n    apply insert_preserves_sorted. assumption.\nQed.\n\nTheorem insert_merge_idempotent : forall (l1 l2 : list nat),\n  sorted l2 -> incl l1 l2 -> l2 = insert_merge l1 l2.\nProof.\n  intros.\n  induction l1.\n  - simpl; auto.\n  - apply incl_cons_inv in H0 as H1. destruct H1.\n    assert (insert_merge (a :: l1) l2 = insert_merge l1 (insert a l2)). {\n      simpl; auto.\n    }\n    assert(l2 = insert a l2). { apply insert_existing_sorted. assumption. assumption. }\n    rewrite H3. rewrite <- H4.\n    apply IHl1.\n    assumption.\nQed.\n\nLemma insert_merge_idem_right : forall l,\n  insert_merge l [] = l.\nAdmitted.\n\n(** * Fresh Number\n\nThe other important function we want to implement concerns,\ngiven a list [l : list nat], find the first natural number\n*not* in the list.\n*)\n\nFixpoint first_new (n : nat) (l : list nat) : nat :=\nmatch l with\n| (h::tl)%list => if Nat.eqb h n then first_new (S n) tl else first_new n tl\n| []%list => n\nend.\n\nLemma first_new_eq {l n} :\n  first_new n (n::l) = first_new (S n) l.\nProof.\n  intros.\n  assert (Nat.eqb n n = true). apply Nat.eqb_eq; reflexivity.\n  unfold first_new; rewrite H. reflexivity.\nQed.\n\nRequire Import Coq.Arith.EqNat.\n\nLemma neq_is_neqb {a b} :\n  a <> b -> Nat.eqb a b = false.\nAdmitted.\n\nLemma first_new_not_eq {l a n} :\n  a <> n -> first_new n (a::l) = first_new n l.\nProof.\n  intros.\n  assert (Nat.eqb a n = false). apply neq_is_neqb; assumption.\n  unfold first_new. rewrite H0. simpl; auto.\nQed. \n\nRequire Import Coq.Lists.ListDec.\n\nTheorem first_new_nondecreasing {l n} :\n  n <= first_new n l.\nProof.\n  generalize dependent n. induction l.\n  - simpl; auto.\n  - intros.\n    assert({a = n} + {a <> n}). decide equality.\n    destruct H.\n    + (* Case: a = n *) rewrite e.\n      assert (first_new n (n::l) = first_new (S n) l). apply first_new_eq.\n      rewrite H.\n      assert (n < S n). lia.\n      assert (S n <= first_new (S n) l). apply IHl.\n      lia.\n    + (* Case: a <> n *)\n      apply (@first_new_not_eq l a n) in n0. rewrite n0.\n      apply IHl.\nQed. \n\nTheorem first_new_lt {l x n} :\n  sorted (x :: l) -> n < x -> first_new n (x::l) = n.\nProof. intros.\n  induction l.\n  - assert (x <> n). lia.\n    apply (@first_new_not_eq [] x n) in H1.\n    rewrite H1. unfold first_new. reflexivity.\n  - assert (sorted (x :: l)). { apply sorted_surgery in H. assumption. }\n    apply IHl in H1 as H2.\n    assert (x <> n). lia.\n    apply (@first_new_not_eq l x n) in H3 as H4.\n    inversion H. clear H5 H8 H6.\n    assert (a <> n). lia.\n    apply (@first_new_not_eq l a n) in H5 as H6.\n    assert (first_new n (x :: a :: l) = first_new n (a :: l)). {\n      apply (@first_new_not_eq (a::l) x n). assumption.\n    }\n    rewrite H8. rewrite H6. rewrite <- H4. assumption.\nQed.\n\nLemma first_new_not_in_lt {l l0 a n} :\n  l = a::l0 -> sorted (l) -> n < a -> ~In (first_new n l) l.\nProof. intros.\n  assert (first_new n (a::l0) = n). {\n    apply (@first_new_lt l0 a n). rewrite <- H. assumption. assumption.\n  }\n  rewrite H. rewrite H2. rewrite <- H. generalize dependent a.\n  generalize dependent l0.\n  induction H0.\n  - intros; apply in_nil.\n  - intros; apply not_in_cons. split. inversion H. lia. apply in_nil.\n  - intros.\n    assert (sorted (x :: y :: l)). { apply (sorted_cons x y l). assumption.\n      assumption.\n    }\n    apply not_in_cons. split.\n    + inversion H1. lia.\n    + apply (IHsorted l y). \n      reflexivity. inversion H1. lia.\n      apply first_new_lt. assumption. inversion H1. lia.\nQed.\n\nLemma first_new_not_in_gt {l x y n} : \n  forall (IHsorted : forall n : nat, ~ In (first_new n (y :: l)) (y :: l)),\n  sorted (y :: l) -> x < n -> x < y -> ~ In (first_new n (x :: y :: l)) (x :: y :: l).\nProof.\n  intros.\n  apply not_in_cons. split.\n  - assert(n <= first_new n (x :: y :: l)). { apply first_new_nondecreasing. }\n    lia.\n  - assert(x <> n). lia.\n    apply (@first_new_not_eq (y::l) x n) in H2.\n    rewrite H2. apply IHsorted.\nQed.\n   \nTheorem first_new_not_in {l n} :\n  sorted l -> ~ In (first_new n l) l.\nProof.\n  intros. generalize dependent n.\n  induction H.\n  - (* Base case: sorted_nil. *) simpl; auto.\n  - (* Base case: sorted_1. *) intros. assert ({x = n} + {x <> n}). decide equality. destruct H.\n   + (* If x = n *) rewrite e.\n     assert (first_new n [n] = first_new (S n) []). apply first_new_eq.\n     rewrite H. unfold first_new. \n     apply not_in_cons. simpl; auto.\n   + (* If x <> n *)\n     apply (@first_new_not_eq [] x n) in n0 as H.\n     rewrite H. unfold first_new.\n     apply not_in_cons. simpl; auto.\n  - (* Inductive case (sorted_cons): x < y && sorted (y::l0) && l = x::y::l0 *)\n    intros.\n    assert ({x < n} + {x = n} + {n < x}). apply lt_eq_lt_dec. destruct H1. destruct s.\n -- (* x < n *)\n    apply (@first_new_not_in_gt l x y n IHsorted). assumption.\n    assert (x <> n). lia. assumption. assumption.\n -- (* x = n *) rewrite e.\n     assert (first_new n (n :: y :: l) = first_new (S n) (y :: l)). apply first_new_eq.\n     rewrite H1.\n     apply not_in_cons.\n     assert (S n <> n). lia.\n     assert (S n <= first_new (S n) (y :: l)). apply first_new_nondecreasing.\n     split. lia. apply IHsorted.\n -- (* x > n *)\n    apply (@first_new_not_in_lt (x :: y :: l) (y :: l) x n).\n    reflexivity. apply sorted_cons. assumption. assumption. assumption.\nQed.\n\nTheorem insert_merge_list_fold_sorted : forall (A : Type) (f : A -> list nat) (l : list A) (init : list nat),\n  sorted init -> sorted (List.fold_left (fun l' => fun (a : A) => insert_merge (f a) l') l init%list).\nProof.\n  intros. generalize dependent init.\n  induction l.\n  - simpl; auto.\n  - intros.\n    assert((fold_left (fun (l' : list nat) (a0 : A) => insert_merge (f a0) l') (a :: l) init)\n          = (fold_left (fun (l' : list nat) (a0 : A) => insert_merge (f a0) l') l (insert_merge (f a) init))). {\n      simpl; auto.\n    } rewrite H0.\n    assert (sorted (insert_merge (f a) init)). {\n      apply insert_merge_sorted2. assumption.\n    }\n    apply IHl in H1 as IH. apply IH.\nQed.\n\nTheorem insert_merge_list_fold_sorted2 : forall (A : Type) (f : A -> list nat -> list nat) (l : list A) (init : list nat),\n  sorted init -> sorted (List.fold_left (fun l' => fun (a : A) => insert_merge (f a l') l') l init%list).\nProof.\n  intros. generalize dependent init.\n  induction l.\n  - simpl; auto.\n  - intros.\n    assert((fold_left (fun (l' : list nat) (a0 : A) => insert_merge (f a0 l') l') (a :: l) init)\n          = (fold_left (fun (l' : list nat) (a0 : A) => insert_merge (f a0 l') l') l (insert_merge (f a init) init))). {\n      simpl; auto.\n    } rewrite H0.\n    assert (sorted (insert_merge (f a init) init)). {\n      apply insert_merge_sorted2. assumption.\n    }\n    apply IHl in H1 as IH. apply IH.\nQed.\n\nRequire Export Coq.Vectors.VectorSpec.\n\nTheorem insert_merge_vector_fold_sorted {n} : forall (A : Type) (f : A -> list nat) (v : Vector.t A n) (init : list nat),\n  sorted init -> sorted (Vector.fold_left (fun l' => fun (a : A) => insert_merge (f a) l') init v).\nProof.\n  intros.\n  assert(Vector.fold_left (fun l' => fun (a : A) => insert_merge (f a) l') init v\n          = List.fold_left (fun l' => fun (a : A) => insert_merge (f a) l') (Vector.to_list v) init).\n  { apply to_list_fold_left. }\n  rewrite H0.\n  apply insert_merge_list_fold_sorted.\n  assumption.\nQed.\n\nTheorem insert_merge_vector_fold_sorted2 {n} : forall (A : Type) (f : A -> list nat -> list nat) (v : Vector.t A n) (init : list nat),\n  sorted init -> sorted (Vector.fold_left (fun l' => fun (a : A) => insert_merge (f a l') l') init v).\nProof.\n  intros.\n  assert(Vector.fold_left (fun l' => fun (a : A) => insert_merge (f a l') l') init v\n          = List.fold_left (fun l' => fun (a : A) => insert_merge (f a l') l') (Vector.to_list v) init).\n  { apply to_list_fold_left. }\n  rewrite H0.\n  apply insert_merge_list_fold_sorted2.\n  assumption.\nQed.\n  \n\nRequire Import Nat.\nRequire Import Coq.Arith.PeanoNat.\n\nLemma first_new_cons {l n} :\n  first_new n (n :: l) = first_new (S n) l.\nProof.\n  assert(n = n). reflexivity.\n  apply Nat.eqb_eq in H as H1.\n  simpl; auto. rewrite H1. reflexivity.\nQed.\n\nLemma neq_neqb : forall (n k : nat),\n  n <> k <-> Nat.eqb n k = false.\nProof. intros. revert n.\n  induction k as [|k IHk]; intro n; destruct n; simpl; rewrite ?IHk; split; try easy.\n  - intros. assert (n <> k). red; auto. apply IHk in H0. assumption.\n  - intros. apply IHk in H. red; auto.\nQed.\n\nLemma first_new_distinct {l a n} :\n  a <> n -> first_new n (a :: l) = first_new n l.\nProof. \n  intros. \n  apply neq_neqb in H as H1.\n  simpl; auto. rewrite H1. \n  reflexivity.\nQed.\n\nLemma fresh_new_step {l n k} :\n  first_new n l = first_new n (k::l) \\/ first_new (S n) l = first_new n (k::l).\nProof.\n  assert({k = n} + {k <> n}). decide equality. destruct H.\n  - right. rewrite e. symmetry. apply first_new_cons.\n  - left. apply (@first_new_distinct l k n) in n0. symmetry; assumption.\nQed.\n\n(*\nLemma first_new_nondecreasing {l n} :\n  n <= first_new n l.\nProof. generalize dependent n.\n  induction l. \n  - simpl; auto.\n  - intros. assert ({a = n} + {a <> n}). decide equality.\n    destruct H.\n  -- rewrite e. \n     assert (first_new n (n :: l) = first_new (S n) l).\n     apply first_new_cons. rewrite H.\n     assert (S n <= first_new (S n) l). apply (@IHl (S n)).\n     intuition.\n  -- assert(first_new n l = first_new n (a :: l)). symmetry. apply (@first_new_distinct l a n).\n     assumption. rewrite <- H.\n     apply IHl.\nQed.  \n*)\n\nLemma fresh_succ_nonzero {l n} :\n  0 < first_new (S n) l.\nProof.\n  intros. generalize dependent n. induction l.\n  - simpl; auto. apply Nat.lt_0_succ.\n  - intros. destruct (@fresh_new_step l (S n) a).\n  + rewrite <- H. apply IHl.\n  + rewrite <- H. apply (IHl (S n)).\nQed.\n\n(*\nLemma first_new_cons_inv {l n a} :\n  a = n <-> first_new n (a :: l) = first_new (S n) l.\nProof.\n  assert ({a = n} + {a <> n}). decide equality. destruct H.\n  - split.\n  -- rewrite e. intros. apply first_new_cons.\n  -- intros; assumption.\n  - split. contradiction. intros. inversion H.\n    assert (Nat.eqb a n  = false). { apply neq_neqb. assumption. }\n    rewrite H0 in H1.\n  split. \n  - intros. rewrite H. apply first_new_cons.\n  - intros. inversion H.\n  assert(n = n). reflexivity.\n  apply Nat.eqb_eq in H as H1.\n  simpl; auto. rewrite H1. reflexivity.\nQed.\n*)\nRequire Import Coq.Arith.Compare.\n\nLemma first_new_on_different_args {l m n} :\n  m <= n -> first_new m l <= first_new n l.\nProof.\n  intros. generalize dependent m. generalize dependent n.\n  induction l.\n  - simpl; auto.\n  - intros.\n    assert ({n = a} + {n <> a}). decide equality. destruct H0.\n  + assert (first_new n (n :: l) = first_new (S n) l). apply first_new_cons.\n    assert ({m = a} + {m <> a}). decide equality. destruct H1.\n  ++ rewrite e0; rewrite <- e. reflexivity.\n  ++ (* m <> a && n = a *)\n    assert (first_new m (a :: l) = first_new m l). {\n    apply (@first_new_distinct l a m); intuition.\n    }\n    rewrite H1. \n    assert (n <= first_new n (a :: l)). { apply first_new_nondecreasing. }\n    rewrite <- e; rewrite H0. apply IHl. intuition.\n  + (* n <> a *)\n    assert (first_new n (a :: l) = first_new n l). { apply (@first_new_distinct l a n); intuition. }\n    assert ({m = a} + {m <> a}). decide equality. destruct H1.\n  ++ (* n <> a && m = a *)\n     assert (first_new m (a :: l) = first_new (S m) l). {\n       rewrite <- e; apply first_new_cons.\n     }\n     assert (S m <= n \\/ m = n). { apply le_le_S_eq in H. assumption. }\n     destruct H2.\n +++ (* S m <= n *)\n     rewrite H0. rewrite H1. apply IHl. intuition.\n +++ rewrite H2. reflexivity.\n ++ assert (first_new m (a :: l) = first_new m l). { apply (@first_new_distinct l a m); intuition. }\n    rewrite H1; rewrite H0. apply IHl. assumption.\nQed.\n\n\n(** * Segments -- range of integers \nAt present, it seems like I will need to use a consecutive,\nfinite sequence of natural numbers. I defined it as a \nfixpoint, then proved a number of useful theorems about it.\n*)\nFixpoint nat_range_list (n : nat) : list nat :=\nmatch n with\n| 0 => []%list\n| S n' => ((nat_range_list n') ++ [n'])%list\nend.\n\nLemma test_works2 :\n  [0;1;2]%list = nat_range_list 3.\nProof. unfold nat_range_list.\n  simpl; auto.\nQed.\n\nLemma nat_range_list_ind :\n  forall (n : nat), \n  nat_range_list (S n) = ((nat_range_list n) ++ [n])%list.\nProof.\n  intros. induction n.\n  - unfold nat_range_list; simpl; auto.\n  - unfold nat_range_list; simpl; auto.\nQed.\n\nRequire Import Lia.\n\nTheorem nat_range_list_length :\n  forall (n : nat), length (nat_range_list n) = n.\nProof.\n  intros. induction n.\n  - unfold nat_range_list; simpl; auto.\n  - assert (nat_range_list (S n) = ((nat_range_list n) ++ [n])%list). {\n      apply nat_range_list_ind.\n    }\n    rewrite H. \n    assert (length (nat_range_list n ++ [n]) = (length (nat_range_list n)) + (length [n]%list)). {\n      apply List.app_length.\n    } \n    rewrite H0. rewrite IHn. unfold length. lia.\nQed.\n\nLemma nth_cons :\n  forall {A} (n : nat) (l : list A) (a default : A),\n  nth (S n) (a::l) default = nth n l default.\nProof. intros.\n  induction l.\n  - unfold nth; simpl; auto.\n  - unfold nth; simpl; auto.\nQed.\n\nLemma last_nth :\n  forall {A} (n n' : nat) (l : list A) (default : A),\n  S n' = n -> n = length l -> List.nth n' l default = List.last l default.\nProof.\n  intros. generalize dependent n'. generalize dependent n. induction l.\n  - intros. unfold length in H0. rewrite H0 in H. contradict H. unfold length; simpl; auto.\n  - intros. destruct l.\n  + unfold length in H0. rewrite H0 in H.\n    assert (n' = 0). lia.\n    rewrite H1. unfold nth; unfold last; simpl; auto.\n  + set (n'' := length l).\n    assert (S n'' = length (a0 :: l)). { unfold length; simpl; auto; lia. }\n    assert (S (S n'') = length (a :: a0 :: l)). { unfold length; simpl; auto; lia. }\n    \n    assert (S (S n'') = n). { lia. }\n    assert (S n'' = n'). { lia. }\n    assert (n' = length (a0 :: l)). lia.\n    rewrite <- H4.\n    assert(last (a :: a0 :: l) default = last (a0 :: l) default). {\n      simpl; auto. \n    }\n    rewrite H6.\n    assert (nth (S n'') (a :: a0 :: l) default = nth n'' (a0 :: l) default). {\n      simpl; auto.\n    }\n    rewrite H7.\n    apply (IHl n'). assumption. assumption.\nQed.\n\nLemma nat_range_list_incl_end :\n  forall (n : nat),\n  List.incl (nat_range_list n) (nat_range_list (S n)).\nProof.\n  intros.\n  induction n.\n  - unfold nat_range_list; simpl; auto. unfold incl; simpl; auto.\n  - set (m := S n).\n    assert (nat_range_list m = (nat_range_list n ++ [n])%list). {\n      unfold nat_range_list; unfold m; simpl; auto.\n    }\n    assert (nat_range_list (S m) = (nat_range_list m ++ [m])%list). {\n      unfold nat_range_list; unfold m; simpl; auto.\n    }\n    assert (nat_range_list (S m) = (nat_range_list n ++ [n; m])%list). {\n      rewrite H0.\n      rewrite H. symmetry. apply (List.app_assoc (nat_range_list n) ([n]%list) ([m]%list)).\n    }\n    rewrite H1. rewrite H.\n    assert (incl [n]%list [n; m]%list). { unfold incl; simpl; auto.\n      intros. destruct H2. left; simpl; auto. simpl; auto.\n    }\n    apply List.incl_app_app; simpl; auto.\n    apply List.incl_refl.\nQed.\n\nTheorem nat_range_list_incl :\n  forall (m n : nat),\n  m < n -> List.incl (nat_range_list m) (nat_range_list n).\nProof.\n  intros. generalize dependent m.\n  induction n.\n  - intros. contradict H; lia.\n  - intros. \n    assert (incl (nat_range_list n) (nat_range_list (S n))). {\n      apply nat_range_list_incl_end.\n    }\n    assert ({m = n} + {m <> n}). decide equality.\n    destruct H1.\n  + rewrite e. assumption.\n  + assert (m < n). { lia. }\n    assert (incl (nat_range_list m) (nat_range_list n)). {\n      apply IHn. assumption.\n    }\n    apply (@incl_tran nat (nat_range_list m) (nat_range_list n) (nat_range_list (S n))).\n    assumption.\n    assumption.\nQed.\n\nTheorem nat_range_list_firstn :\n  forall (m n : nat),\n  m < n -> List.firstn m (nat_range_list n) = nat_range_list m.\nProof.\n  intros. generalize dependent m.\n  induction n.\n  - intros. contradict H; lia.\n  - intros. \n    assert({m = n} + {m <> n}). decide equality.\n    assert(nat_range_list (S n) = (nat_range_list n ++ [n])%list). {\n      unfold nat_range_list; simpl; auto.\n    }\n    destruct H0.\n  + rewrite e. rewrite H1.\n    set (l := nat_range_list n).\n    assert (n = length l). { symmetry. apply nat_range_list_length. }\n    assert (firstn (length l + 0) (l ++ [n])%list = l). {\n      assert (firstn 0 [n]%list = List.nil). { simpl; auto. }\n      assert (l = (l ++ (firstn 0 [n]%list))%list). { simpl; auto. symmetry. apply app_nil_r. }\n      set (l2 := firstn (length l + 0) (l ++ [n])%list).\n      rewrite H3. unfold l2.\n      apply (@firstn_app_2 nat 0 l ([n])%list).\n    }\n    assert (length l + 0 = length l). { simpl; auto. }\n    rewrite H3 in H2. rewrite <- H0 in H2. assumption.\n  + assert (m < n) as IH. lia.\n    apply IHn in IH.\n    destruct m as [| m'].\n ++ (* m = 0 *)\n    apply firstn_O.\n ++ (* m = S m' *)\n    set (l := skipn (S m') (nat_range_list n)).\n    assert (nat_range_list n = (nat_range_list (S m') ++ l)%list). {\n      symmetry. rewrite <- IH. unfold l.\n      apply (@firstn_skipn nat (S m') (nat_range_list n)).\n    }\n    assert (nat_range_list (S n) = ((nat_range_list (S m') ++ l) ++ [n])%list). {\n      rewrite <- H0. rewrite H1. reflexivity.\n    }\n    rewrite H2.\n    assert (((nat_range_list (S m') ++ l) ++ [n])%list \n            = (nat_range_list (S m') ++ (l ++ [n]))%list). {\n      symmetry. apply app_assoc.\n    }\n    rewrite H3.\n    set (l' := (l ++ [n])%list).\n    assert (length (nat_range_list (S m')) = S m'). {\n      apply nat_range_list_length.\n    }\n    assert (firstn (length (nat_range_list (S m')) + 0) (nat_range_list (S m') ++ l')%list =\n            ((nat_range_list (S m')) ++ firstn 0 l')%list). {\n      apply (@firstn_app_2 nat 0).\n    }\n    rewrite H4 in H5.\n    assert ((nat_range_list (S m') ++ firstn 0 l')%list = nat_range_list (S m')). {\n      assert (firstn 0 l' = []%list). simpl; auto.\n      rewrite H6.\n      apply app_nil_r.\n    } rewrite H6 in H5.\n    assert (firstn (S m' + 0)\n       (nat_range_list (S m') ++ l') = firstn (S m')\n       (nat_range_list (S m') ++ l')). { assert(S m' + 0 = S m').\n       simpl; auto. rewrite H7. reflexivity.\n    }\n    rewrite H7 in H5. assumption.\nQed.\n\nTheorem nat_range_list_entry :\n  forall (k n : nat),\n  k < n -> nth k (nat_range_list n) (S n) = k.\nProof.\n  intros. generalize dependent k.\n  induction n as [|n'].\n  - intros. contradict H. lia.\n  - intros. set (n := S n').\n    assert (nat_range_list n = (nat_range_list n' ++ [n'])%list). {\n      simpl; auto.\n    }\n    assert ({k = n'} + {k <> n'}). decide equality.\n    destruct H1.\n  + (* Case: k = n' *)\n    assert (nth k (nat_range_list (S k)) (S (S k)) = last (nat_range_list (S k)) (S (S k))). {\n      apply (@last_nth nat n k). lia.\n      rewrite e. unfold n. symmetry.\n      apply nat_range_list_length.\n    } unfold n. rewrite <- e.\n    rewrite H1.\n    unfold n in H0.\n    rewrite <- e in H0.\n    rewrite H0.\n    apply last_last.\n  + assert (k < n'). lia.\n    assert (length (nat_range_list n') = n'). {\n      apply nat_range_list_length.\n    }\n    apply IHn' in H1 as IH.\n    rewrite H0.\n    assert (nth k (nat_range_list n' ++ [n'])%list (S n') = nth k (nat_range_list n') (S n')). {\n      apply app_nth1 with (d := (S n')). rewrite H2. assumption.\n    }\n    assert (nth k (nat_range_list n' ++ [n']) (S n) = nth k (nat_range_list n' ++ [n']) (S n')). {\n      apply nth_indep.\n      assert (length (nat_range_list n') + 1 = length (nat_range_list n' ++ [n'])). {\n        symmetry. apply app_length.\n      }\n      lia.\n    } rewrite H4.\n    rewrite H3. rewrite IH. reflexivity.\nQed.\n\nDefinition rev_nat_range_list (n : nat) : list nat :=\n  List.rev (nat_range_list n).\n\nExample ex_rev_nat_range_list_4 :\n  rev_nat_range_list 4 = [3;2;1;0]%list.\nProof.\n  simpl; auto.\nQed.\n\nTheorem rev_nat_range_list_length : forall (n : nat),\n  length (rev_nat_range_list n) = n.\nProof.\n  intros.\n  unfold rev_nat_range_list.\n  assert (length (rev (nat_range_list n)) = length (nat_range_list n)). {\n    apply (rev_length (nat_range_list n)).\n  }\n  rewrite H.\n  apply nat_range_list_length.\nQed.\n(* \n  Lemma rev_nth : forall l d n, n < length l ->\n    nth n (rev l) d = nth (length l - S n) l d.\nnat_range_list_entry\n     : forall k n : nat,\n       k < n -> nth k (nat_range_list n) (S n) = k\nnth k (rev_nat_range_list n) d\n= nth (n - k) (nat_range_list n) d\n= (n - k)\n*)\n\nTheorem rev_nat_range_list_entry :\n  forall (k n : nat),\n  k < n -> nth k (rev_nat_range_list n) (S n) = (n - S k).\nProof.\n  intros. unfold rev_nat_range_list.\n  assert (length (nat_range_list n) = n). { apply nat_range_list_length. }\n  assert (nth k (rev (nat_range_list n)) (S n)\n          = nth (length (nat_range_list n) - S k) (nat_range_list n) (S n)). {\n    apply (@rev_nth nat (nat_range_list n) (S n) k).\n    rewrite H0. assumption.\n  } rewrite H0 in H1.\n  assert (nth (n - S k) (nat_range_list n) (S n) = (n - S k)). {\n    apply nat_range_list_entry. lia.\n  } rewrite H1. rewrite H2.\n  reflexivity.\nQed.\n\n(* Coq thinks [Vector.of_list (rev_nat_range_list n)] is a [Vector]\nof size [length (rev_nat_range_list n)]. So we have to explicitly\nspell it out for Coq. *)\n\n\nRequire Fin List.\nRequire Import VectorDef PeanoNat Eqdep_dec.\nImport VectorNotations EqNotations.\nFixpoint rev_nat_range_vector (n : nat) : Vector.t nat n :=\nmatch n with\n| 0 => []\n| S n' => (n') :: (rev_nat_range_vector n')\nend.\n\nLemma rev_nat_range_vector_last :\n  forall (n' : nat),\n  Vector.last (rev_nat_range_vector (S n')) = 0.\nProof.\n  intros. induction n'.\n  - unfold rev_nat_range_vector. simpl; auto.\n  - assert((rev_nat_range_vector (S (S n')))\n            = Vector.cons nat (S n') (S n') (rev_nat_range_vector (S n'))). {\n      simpl; auto.\n    }\n    rewrite H.\n    assert (Vector.last (Vector.cons nat (S n') (S n') (rev_nat_range_vector (S n')))\n            = Vector.last (rev_nat_range_vector (S n'))). {\n      simpl; auto.\n    }\n    rewrite H0. apply IHn'.\nQed.\n\nExample rev_nat_range_vector_0 :\n  rev_nat_range_vector 0 = [].\nProof. simpl; auto. Qed.\n\nExample rev_nat_range_vector_1 :\n  rev_nat_range_vector 1 = [0].\nProof. simpl; auto. Qed.\n\nExample rev_nat_range_vector_2 :\n  rev_nat_range_vector 2 = [1;0].\nProof. simpl; auto. Qed.\n\n\nLemma rev_nat_range_vector_hd :\n  forall (n' : nat),\n  Vector.hd (rev_nat_range_vector (S n')) = n'.\nProof.\n  intros. unfold rev_nat_range_vector. simpl; auto.\nQed.\n\nLemma rev_nat_range_vector_tl :\n  forall (n' : nat),\n  Vector.tl (rev_nat_range_vector (S (S n'))) = rev_nat_range_vector (S n').\nProof.\n  intros. unfold rev_nat_range_vector. simpl; auto.\nQed.\n\n(* These next two lemmas are true, but I am too stupid to understand\nCoq's inner workings to prove them. *)\nLemma rev_nat_range_vector_entry_base_case :\n  forall (k : nat) (H : k < 1),\n  nth_order (rev_nat_range_vector 1) H = 1 - S k.\nAdmitted.\n\nLemma rev_nat_range_vector_entry_inductive_case_subtlety :\n  forall (k n : nat) (H : k < S (S n)) (e : k = S n) (H0 : S n < S (S n)),\n  nth_order (rev_nat_range_vector (S (S n))) H \n  = nth_order (rev_nat_range_vector (S (S n))) H0.\nAdmitted.\n\nTheorem rev_nat_range_vector_entry :\n  forall (k n : nat) (H : k < S n),\n  nth_order (rev_nat_range_vector (S n)) H = (S n - S k).\nProof.\n  intros.\n  generalize dependent k. induction n.\n  - intros. apply rev_nat_range_vector_entry_base_case.\n  - intros. assert({k = S n} + {k <> S n}). decide equality. destruct H0.\n    + assert (S n < S (S n)) as H0. lia.\n      assert (nth_order (rev_nat_range_vector (S (S n))) H \n              = nth_order (rev_nat_range_vector (S (S n))) H0). {\n        apply rev_nat_range_vector_entry_inductive_case_subtlety. assumption.\n      }\n      rewrite H1. rewrite e.\n      assert (last (rev_nat_range_vector (S (S n))) = 0). {\n        apply rev_nat_range_vector_last.\n      }\n      assert (nth_order (rev_nat_range_vector (S (S n))) H0 = last (rev_nat_range_vector (S (S n)))). {\n        apply (@nth_order_last nat (S n) (rev_nat_range_vector (S (S n)))).\n      }\n      rewrite H3; rewrite H2; lia.\n    + destruct k as [|k'].\n  ++ (* k = 0 *)\n     apply nth_order_hd.\n  ++ (* k = S k' *)\n     set (k := S k'). assert (k' < S n). lia.\n     assert (nth_order (rev_nat_range_vector (S n)) H0 = S n - S k') as IH. {\n        apply (IHn k' H0).\n     }\n     assert (S (S n) - S k = S n - S k'). lia. rewrite H1.\n     rewrite <- IH. symmetry.\n     assert (Vector.tl (rev_nat_range_vector (S (S n))) = rev_nat_range_vector (S n)). {\n       apply rev_nat_range_vector_tl.\n     }\n     rewrite <- H2.\n     apply (@nth_order_tl nat (S n) k' (rev_nat_range_vector (S (S n)))).\nQed.\n", "meta": {"author": "pqnelson", "repo": "soft-type", "sha": "4a46a11ea98b89425d571fcb1ba0c73a30cd91c4", "save_path": "github-repos/coq/pqnelson-soft-type", "path": "github-repos/coq/pqnelson-soft-type/soft-type-4a46a11ea98b89425d571fcb1ba0c73a30cd91c4/ST/EVarsScratchwork.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.6890900343727113}}
{"text": "(** Definition of the ordered setoid of ordinal numbers, together with\n    proofs that it is indeed an ordered setoid under the given relations.\n    That is:\n    - Ord.eq (==) is an equivalence relation;\n    - Ord.lt (<) is an ==-compatible strict ordering relation;\n    - Ord.le (≤) is a partial ordering relation w.r.t. ==;\n    - < is a subrelation of ≤.\n\n    Some desirable properties (such as totality) require excluded middle,\n    and are deferred to the OrdClassical module.\n\n    Implementation note:\n    A rather more elegant mutually recursive definition of < and ≤ is\n    possible, and was originally to be used here:\n    - ssup f ≤ y when, for all a:A, f(a) < y; \n    - x < ssup g when, for some b:B, x ≤ g(b). \n      However, Coq does not accept these as fixpoint definitions since\n    they descend on different parameters. It does accept them as\n    inductive definitions, but this would require them to be redefined\n    inside the Ord module, which causes annoying notational issues.\n    We have instead included proofs of the above properties for our\n    definitions, as lemmata le_lt and lt_le respectively.\n*)\n\nFrom Ordinal Require Import CommonHeader WellOrderClass Notations.\n\nRequire Arith_base.\n\nGeneralizable All Variables.\n\nOpen Scope Ord_scope.\n\n\n(** An ordinal is represented by the image of a (possibly empty) function\n    with codomain the ordinals. Conceptually it 'is' the least ordinal\n    greater than every element of the function's range. *)\n\nInductive Ord := Ord_ssup `(x: A → Ord).\n\nModule Ord <: EqLtLe' <: StrOrder.\n\n  Definition t := Ord.\n  Notation ssup := Ord_ssup.\n\n  Definition src (o: Ord) := let (A, _) := o in A.\n  \n  Definition src_map (o: Ord) : src o → Ord :=\n    match o with ssup f => f end.\n\n  Fixpoint le o o': Prop :=\n    ∀ a: src o, ∃ a': src o',le (src_map o a) (src_map o' a').\n\n  Fixpoint lt o o': Prop :=\n    ∃ a': src o', ∀ a: src o, lt (src_map o a) (src_map o' a').\n\n  Definition ge := flip le.\n  Definition gt := flip lt.\n  Definition eq := relation_conjunction le ge.\n\n  #[export] Hint Unfold ge gt relation_conjunction flip: core.\n\n  Include EqLtLeNotation.\n  Infix \"≤\" := le.\n  Infix \"≥\" := ge.\n  Notation \"x =/= y\" := (x ~= y).\n  \n  Section Reduction_Lemmata.\n\n    Lemma le_le `(x: A → Ord) `(y: B → Ord):\n      (∀ a, ∃ b, x a ≤ y b) ↔ ssup x ≤ ssup y.\n    Proof. reflexivity. Qed.\n\n    Lemma lt_lt `(x: A → Ord) `(y: B → Ord):\n      (∃ b, ∀ a, x a < y b) ↔ ssup x < ssup y.\n    Proof. reflexivity. Qed.\n\n    Fixpoint le_lt (o: Ord): ∀ [A] (x: A → Ord), (∀ a, x a < o) ↔ ssup x ≤ o.\n    Proof.\n      destruct o as [A' x'].\n      split.\n      intros hyp a; specialize (hyp a).\n      simpl in a, hyp |- *. destruct (x a).\n      destruct hyp as [a' hyp]. exists a'.\n      apply le_lt. auto.\n    Qed.\n\n    Fixpoint lt_le (o: Ord): ∀ [A] (x: A → Ord), (∃ a, o ≤ x a) ↔ o < ssup x.\n    Proof.\n      destruct o as [A' x'].\n      split.\n      intros [a hyp]. exists a.\n      simpl in hyp |- *. destruct (x a).\n      intro. apply lt_le, hyp.\n    Qed.\n\n    Lemma eq_le `(x: A → Ord) `(y: B → Ord):\n      (∀ a, ∃ b, x a ≤ y b) → (∀ b, ∃ a, y b ≤ x a) → (ssup x == ssup y)%Ω.\n    Proof @conj _ _.\n\n    Lemma eq_eq `(x: A → Ord) `(y: B → Ord):\n      (∀ a, ∃ b, x a == y b) → (∀ b, ∃ a, y b == x a) → (ssup x == ssup y)%Ω.\n    Proof. firstorder. Qed.\n\n  End Reduction_Lemmata.\n\n\n  Section Order_Properties.\n\n    Open Scope equiv_scope.\n\n    #[export] Instance lt_sub_le: subrelation lt le.\n    Proof.\n      unfold subrelation; fix Fix 1.\n      destruct x, y, 1; eexists; eauto.\n    Qed.\n\n    #[export] Instance eq_sub_le: subrelation eq le.\n    Proof λ x y H, proj1 H.\n\n    #[export] Instance le_preorder: PreOrder le.\n    Proof.\n      split; autounfold.\n      fix Fix 1.\n      - destruct x; intro a; now exists a.\n      - destruct x, y, z; intros H1 H2 a.\n        edestruct H1, H2. eauto.\n    Qed.\n\n    #[export] Instance ge_preorder: PreOrder ge | 2 :=\n      flip_PreOrder _.\n\n    #[export] Instance lt_strorder: StrictOrder lt.\n    Proof.\n      split; autounfold.\n      fix Fix 1.\n      - destruct x, 1; firstorder.\n      - destruct x, y, z, 1, 1.\n        eexists; eauto.\n    Qed.\n\n    #[export] Instance gt_strorder: StrictOrder gt | 2 :=\n      flip_StrictOrder _.\n\n    #[export] Instance eq_equiv: Equivalence eq.\n    Proof.\n      firstorder using le_preorder.\n    Qed.\n\n    #[export] Instance le_partial_order: PartialOrder eq le.\n    Proof.\n      now_show (eq === relation_conjunction le (flip le)).\n      reflexivity.\n    Qed.\n\n    #[export] Instance ge_partial_order: PartialOrder eq ge | 2 :=\n      PartialOrder_inverse _.\n\n    #[export] Instance lt_le_compat: Proper (le --> le ++> impl) lt.\n    Proof.\n      autounfold. fix Fix 1.\n      intros [A x] [B y] Le [A' x'] [B' y'] Le'.\n      unfold flip; simpl in *.\n      intros (a', Lt). specialize (Le' a') as (b', Le').\n      exists b'. intro b. specialize (Le b) as (a, Le).\n      specialize (Lt a).\n      eapply Fix; eassumption.\n    Qed.\n    \n    #[export] Instance lt_compat: Proper (eq ==> eq ==> iff) lt.\n    Proof.\n      apply (proper_sym_impl_iff_2 _ _).\n      firstorder using lt_le_compat.\n    Qed.\n\n    #[export] Instance lt_wf: well_founded lt.\n    Proof.\n      intro x. enough (∀ (y: Ord) (H: y ≤ x), Acc lt y).\n      { apply H; reflexivity. }\n      induction x as [A f IH], y as [B g].\n      intro; constructor; intros z H'.\n      apply lt_le in H'. destruct H' as [b H'].\n      specialize (H b) as [a H].\n      apply (IH a). etransitivity; eassumption.\n    Qed.\n\n    #[export] Instance lt_ext: Extensional eq lt.\n    Proof.\n      enough (WeaklyExtensional eq lt) by exact _.\n      intros x y H; split.\n      induction x as [A f IH], y as [B g]. simpl.\n      intro x. apply lt_le, H, le_lt; reflexivity.\n    Qed.\n\n    #[export] Instance lt_wo: WellOrder eq lt := { }.\n\n    #[export] Instance pointwise_eq_sub_le [A]:\n    subrelation (pointwise_relation A eq) (pointwise_relation A le) := _.\n\n    #[export] Instance pointwise_lt_sub_le [A]:\n    subrelation (pointwise_relation A lt) (pointwise_relation A le) := _.\n    \n    #[export] Instance unary_covariant_is_proper (op: Ord → Ord):\n      Proper (le ==> le) op → Proper (eq ==> eq) op.\n    Proof. firstorder. Qed.\n\n    #[export] Instance binop_covariant_proper (op: Ord → Ord → Ord):\n      Proper (le ==> le ==> le) op → Proper (eq ==> eq ==> eq) op.\n    Proof. firstorder. Qed.\n\n    #[export] Instance pointwise_covariant_is_proper [A] (op: (A → Ord) → Ord):\n      Proper (pointwise_relation A le ==> le) op →\n      Proper (pointwise_relation A eq ==> eq) op.\n    Proof.\n      intros covariant x y E. pose proof (E' := symmetry E).\n      apply pointwise_eq_sub_le in E, E'.\n      split; auto.\n    Qed.\n\n  End Order_Properties.\n    \n\n  Section Strict_Supremum.\n\n    Variable A: Type.\n\n    #[export]\n    Instance ssup_covariance: Proper (pointwise_relation A le ++> le) ssup.\n    Proof. firstorder. Qed.\n\n    #[export]\n    Instance ssup_compat: Proper (pointwise_relation A eq ==> eq) ssup := _.\n\n    Property ssup_gt (x: A → Ord): ∀ a, x a < ssup x.\n    Proof.\n      apply le_lt; reflexivity.\n    Qed.\n  \n    Property ssup_minimality (x: A → Ord): ∀ s, (∀ a: A, x a < s) ↔ ssup x ≤ s.\n    Proof.\n      intro; apply le_lt.\n    Qed.\n\n    Property ssup_ge (x: A → Ord): ∀ a, x a ≤ ssup x.\n    Proof.\n      intro; apply lt_sub_le, ssup_gt.\n    Qed.\n    \n    Lemma compose_le `(x: B → Ord) (f: A → B): ssup (x ∘ f) ≤ ssup x.\n    Proof.\n      intro a; exists (f a). reflexivity.\n    Qed.\n\n  End Strict_Supremum.\n\n\n  Section Propriety.\n\n    Variable Q: ∀ A, (A → Ord) → Prop.\n    Let P (o: Ord) := Q (src_map o).\n\n    Hypothesis proper: Proper (eq ==> iff) P.\n\n    #[export]\n    Instance proper_is_pointwise_proper A:\n      Proper (pointwise_relation A eq ==> iff) (@Q A).\n    Proof.\n      intros x y H.\n      now apply ssup_compat, proper in H.\n    Qed.\n\n    Theorem source_irrelevance (o: Ord):\n      ∀ A (f: A → Ord), ssup f == o → Q f → P o.\n    Proof.\n      intros A f Eq. now rewrite <- Eq.\n    Qed.\n\n    Theorem source_irrelevance_inv (o: Ord):\n      P o → ∀ A (f: A → Ord), ssup f == o → Q f.\n    Proof.\n      intros H A f Eq. now rewrite <- Eq in H.\n    Qed.\n\n  End Propriety.\n\n\n  Section Zero.\n\n    Definition zero: Ord := ssup (Empty_set_rect _).\n\n    Property zero_le: ∀ x: Ord, zero ≤ x.\n    Proof λ x, Empty_set_ind _.\n\n    Definition zero_unique z: (∀ x, z ≤ x) -> z == zero.\n    Proof λ h, conj (h zero) (zero_le z).\n  \n    Property le_zero_is_zero x: x ≤ zero -> x == zero.\n    Proof λ h, conj h (zero_le x).\n  \n    Property nlt_zero: ∀ w, ¬(w  < zero).\n    Proof.\n      intros [] []; contradiction.\n    Qed.\n\n    Definition lt_zero_exfalso {P: Ord -> Type} w: w < zero → P w :=\n      λ h, False_rect (P w) (nlt_zero w h).\n\n    Property ssup_empty_is_zero w: ¬inhabited (src w) ↔ w == zero.\n    Proof.\n      destruct w as (A, x); simpl. split.\n      - intro N. apply le_zero_is_zero, le_lt.\n        intro a; now contradict N.\n      - intros [H _] [a]. now destruct (H a).\n    Qed.\n\n    Property ssup_inhabited_is_positive w: inhabited (src w) ↔ w > zero.\n    Proof.\n      split; intros [a].\n      - exists a; intros [].\n      - auto.\n    Qed.\n\n    Property ssup_nonempty_is_nonzero w: ¬¬inhabited (src w) ↔ w ~= zero.\n    Proof.\n      split. intros H H'.\n      apply (ssup_empty_is_zero w) in H'.\n      contradiction.\n    Qed.\n\n  End Zero.\n\n  #[export] Hint Resolve zero_le: ord.\n  #[export] Hint Resolve zero_unique: ord.\n  #[export] Hint Resolve le_zero_is_zero: ord.\n  #[export] Hint Resolve nlt_zero: ord.\n  #[export] Hint Resolve <- ssup_empty_is_zero: ord.\n  #[export] Hint Resolve <- ssup_inhabited_is_positive: ord.\n  #[export] Hint Resolve <- ssup_nonempty_is_nonzero: ord.\n\n\n  Section Successor.\n    (** The successor operation and its basic properties. *)\n\n    Definition succ (o: Ord): Ord := ssup (λ _:unit, o).\n\n    #[export]\n    Instance succ_strict_covariance: Proper (lt ++> lt) succ.\n    Proof.\n      repeat intro; simpl; repeat elim_quantifiers.\n      assumption.\n    Qed.\n\n    #[export]\n    Instance succ_covariance: Proper (le ==> le) succ.\n    Proof.\n      unfold succ; solve_proper.\n    Qed.\n\n    #[export]\n    Instance succ_compat: Proper (eq ==> eq) succ := _.\n\n    Property succ_gt o: o < succ o.\n    Proof.\n      apply -> lt_le. exists tt; reflexivity.\n    Qed.\n\n    Property succ_minimality o: ∀ s, o < s ↔ succ o ≤ s.\n    Proof.\n      split; intros.\n      - apply -> le_lt; auto.\n      - apply <- le_lt in H; auto using tt.\n    Qed.\n\n    Property succ_ge o: o ≤ succ o.\n    Proof.\n      apply lt_sub_le, succ_gt.\n    Qed.\n\n    Property le_iff_lt_succ x y: x ≤ y ↔ x < succ y.\n    Proof.\n      intros; split; intro H.\n      - apply -> lt_le; repeat constructor; assumption.\n      - apply <- lt_le in H; destruct H; assumption.\n    Qed.\n\n    Property succ_lt_inv x y: succ x < succ y → x < y.\n    Proof.\n      intros; now apply succ_minimality, le_iff_lt_succ.\n    Qed.\n\n    Property succ_le_inv: ∀ x y, succ x ≤ succ y → x ≤ y.\n    Proof.\n      intros; now apply le_iff_lt_succ, succ_minimality.\n    Qed.\n\n    Property succ_inj: ∀ x y, succ x == succ y → x == y.\n    Proof.\n      destruct 1; split; now apply succ_le_inv.\n    Qed.\n  \n  End Successor.\n\n  #[export] Hint Resolve -> succ_minimality: ord.\n  #[export] Hint Rewrite <- succ_gt: ord.\n  #[export] Hint Rewrite <- succ_minimality: ord.\n\n\n  Section Limit_and_Successor_Ordinals.\n    \n    Definition Is_successor (o: Ord) := ∃ p, succ p == o.\n\n    Definition Is_limit (o: Ord) := ∀ p, p < o → succ p < o.\n\n    #[export]\n    Instance: Proper (eq ==> iff) Is_successor.\n    Proof.\n      unfold Is_successor; solve_proper.\n    Qed.\n\n    #[export]\n    Instance: Proper (eq ==> iff) Is_limit.\n    Proof.\n      unfold Is_limit; solve_proper.\n    Qed.\n\n    (** Constructively we cannot prove every ordinal is either a\n     successor or a limit ordinal, but we can prove the following. *)\n\n    Fact limit_nand_successor (o: Ord): ¬(Is_limit o ∧ Is_successor o).\n    Proof.\n      intros [H [p H']]. rewrite <- H' in H. clear dependent o.\n      pose proof (H'' := succ_gt p).\n      specialize (H p H''). contradict H. apply irreflexivity.\n    Qed.\n\n    Fact not_successor_is_limit (o: Ord) : ¬Is_successor o → Is_limit o.\n    Proof.\n      intros H p L.\n      assert (Hp: succ p =/= o) by firstorder.\n      give_up.\n    Abort.\n    (* Is this even true constructively? *)\n      \n\n    (** An ordinal is a successor iff every map into the ordinals\n    specifying it has a maximal element, iff any map does so. *)\n\n    Lemma successor_max (o: Ord):\n      Is_successor o →\n      ∀ `(x: A → Ord), ssup x == o → ∃ μ: A, ∀ a: A, x μ ≥ x a.\n    Proof.\n      intros [o' s] I x Eq.\n      rewrite <- Eq in s; clear dependent o.\n      specialize (proj1 s tt) as [i s1];\n      specialize (proj2 s i) as [[] s2];\n      pose proof (Eq' := conj s1 s2: o' == x i); clear s1 s2.\n      rewrite -> Eq' in s.\n      exists i. firstorder.\n    Qed.\n\n    Lemma max_successor (o: Ord) `(x: A → Ord) (Eq: ssup x == o):\n      (∃ μ: A, ∀ a: A, x μ ≥ x a) → Is_successor o.\n    Proof.\n      intros [μ M]. exists (x μ).\n      rewrite <- Eq; clear dependent o.\n      split.\n      - intros []; exists μ; reflexivity.\n      - intro a; exists tt; apply M.\n    Qed.\n  \n  End Limit_and_Successor_Ordinals.\n\n\n  Section From_WF.\n    (** Mapping of other sets with well-founded relations into the ordinals *)\n    \n    Context `{Rwf: well_founded A R}.\n    Local Infix \"≺\" := R (at level 70).\n\n    Let fwf (a: A) (ih: ∀ x: A, x ≺ a → Ord): Ord :=\n        @ssup {y | y ≺ a} (sig_apply ih).\n\n    Definition from_wf := Fix _ fwf : A → Ord.\n\n    Local Lemma fwf_ext (a: A) (f g: ∀ y, y ≺ a → Ord) :\n      (∀ (y:A) (p: y ≺ a), f y p == g y p) -> fwf f == fwf g.\n    Proof.\n      intro H. apply eq_eq.\n      intro y; exists y. destruct y.\n      2: symmetry.\n      apply H.\n    Qed.\n\n    Local Lemma fwf_inv (x: A):\n      ∀ (r s: Acc R x), Fix_F _ fwf r == Fix_F _ fwf s.\n    Proof.\n      induction (Rwf x); intros.\n      rewrite <-! Fix_F_eq.\n      apply fwf_ext.\n      auto.\n    Qed.\n    \n    Property from_wf_eq a:\n      from_wf a == ssup (λ y: {y | y ≺ a}, from_wf (proj1_sig y)).\n    Proof.\n      change (ssup _) with (fwf (λ y (_: y ≺ a), from_wf y)).\n      unfold from_wf, Fix. rewrite <- Fix_F_eq.\n      apply fwf_ext. intros. apply fwf_inv.\n    Qed.\n\n    Global Instance from_wf_strict_covariance: Proper (R ==> lt) from_wf.\n    Proof.\n      intros x y p. rewrite -> (from_wf_eq y).\n      exact (ssup_gt _ (exist _ x p)).\n    Qed.\n\n    Context `{equivA: Equivalence A eqA}.\n    Context {R_compat: Proper (eqA ==> eqA ==> iff) R}.\n    Local Infix \"≃\" := eqA (at level 70).\n\n    Global Instance from_wf_compat: Proper (eqA ==> eq) from_wf.\n    Proof.\n      intros x y e. rewrite ->! from_wf_eq.\n      apply eq_eq.\n      intros [z r].\n      pose (r' := r).\n      apply (R_compat (reflexivity z) e) in r'.\n      exists (exist _ z r'). reflexivity.\n    Qed.\n\n    Context {Rtrans: Transitive R}.\n\n    Local Coercion sig_of_sig2 : sig2 >-> sig.\n\n    Property lt_from_wf (x: Ord) (a: A): x < from_wf a → ∃ a': A, x == from_wf a'.\n    Proof.\n    Abort.\n\n\n    Context {Rwext: WeaklyExtensional eqA R}.\n\n    Property from_wf_inj: ∀ x y, from_wf x == from_wf y → x ≃ y.\n    Proof.\n      induction y as [y IH] using well_founded_ind. intro Eq.\n      apply weak_extensionality. intro t; split.\n    Abort.\n      \n  End From_WF.\n\n\n  Section From_Nat.\n    (** Mapping of the natural numbers into the finite ordinals. We could\n    just use from_wf, but we instead define a simpler function and then\n    show that it is equivalent. *)\n\n    Fixpoint from_nat (n: nat): Ord :=\n      match n with\n      | 0 => zero\n      | S n' => succ (from_nat n')\n      end.\n\n    Local Lemma from_wf_nat_covariance:\n      Proper (Peano.le ==> le) (from_wf (R := Peano.lt)).\n    Proof.\n      intros m n h.\n      apply Arith.Compare_dec.le_lt_eq_dec in h; destruct h.\n      - apply lt_sub_le, from_wf_strict_covariance. assumption.\n      - destruct e. reflexivity.\n    Qed.\n\n    Proposition from_wf_is_from_nat:\n      pointwise_relation _ eq (from_wf (R := Peano.lt)) from_nat.\n    Proof.\n      intro n; induction n.\n      cbn [from_nat]. rewrite -> from_wf_eq.\n      - apply ssup_empty_is_zero. firstorder with arith.\n      - rewrite <- IHn; clear IHn. split.\n        + simpl. intros [m l]; exists tt.\n          apply from_wf_nat_covariance; auto with arith.\n        + intro. assert (l: (n < S n)%nat) by auto.\n          now exists (exist _ n l).\n    Qed.\n    (*\n    Lemma from_nat_src (n: nat): (0 < n)%nat → unit = src (from_nat n) :> Type.\n    Proof.\n      intro H. rewrite <- (Arith.PeanoNat.Nat.succ_pred_pos _ H). reflexivity.\n    Qed.\n\n    Lemma from_nat_src_0 (n: nat): ∅ = src (from_nat 0) :> Type.\n    Proof.\n      reflexivity.\n    Qed.*)\n\n    #[export]\n    Instance from_nat_compat: Proper (Logic.eq ==> eq) from_nat := _.\n\n    #[export]\n    Instance from_nat_strict_covariace: Proper (Peano.lt ==> lt) from_nat.\n    Proof.\n      repeat intro.\n      rewrite <- from_wf_is_from_nat.\n      apply from_wf_strict_covariance, H.\n    Qed.\n\n    #[export]\n    Instance from_nat_covariance: Proper (Peano.le ==> le) from_nat.\n    Proof.\n      intros m n m_le_n.\n      induction m, n as [n | m | m n IH] using nat_double_ind.\n      - (* 0, n *) apply zero_le.\n      - (* S m, 0 *) exfalso. inversion m_le_n.\n      - (* S m, S n *)\n        simpl; repeat elim_quantifiers.\n        apply IH. auto with arith.\n    Qed.\n    \n    Property from_nat_le_inv m n: from_nat m ≤ from_nat n → (m <= n)%nat.\n    Proof.\n      induction m, n as [n | m | m n IH] using nat_double_ind.\n      simpl; intro H; repeat elim_quantifiers.\n      auto with arith.\n    Qed.\n    \n    Property from_nat_inj m n: from_nat m == from_nat n → m = n.\n      intros [H₁ H₂].\n      apply from_nat_le_inv in H₁, H₂.\n      auto with arith. \n    Qed.\n\n  End From_Nat.\n  \n\n  Section Supremum.\n    (** The supremum, or join, of an indexed family of ordinals.\n        Conceptually we join all their sources into a sigma-type and\n        take the strict supremum of the corresponding join of their\n        source maps.\n        *)\n\n    Open Scope equiv_scope.\n\n    Section Def.\n\n      Context `(x: A → Ord).\n\n      Let J: Type := { a: A & src (x a) }.\n\n      Let Jmap: J → Ord := λ j, let (a, b) := j in src_map (x a) b.\n\n      Definition sup: Ord := ssup Jmap.\n\n      Property sup_ge: ∀ a: A, x a ≤ sup.\n      Proof.\n        intro a. destruct (x a) as [B y] eqn: E.\n        intro b.\n        exists (existT _ a (eq_rect _ _ b _ (symmetry E))).\n        unfold sup; simpl. rewrite -> E. reflexivity.\n      Qed.\n\n      Property sup_minimality: ∀ s, (forall a, x a ≤ s) → sup ≤ s.\n      Proof.\n        intros s H. destruct s eqn: E.\n        apply le_lt.\n        intros [a b]. rewrite <- (H a).\n        simpl. destruct (x a). apply ssup_gt.\n      Qed.\n\n      Property sup_uniqueness:\n      ∀ s, (∀ a, x a ≤ s) → (∀ s', (∀ a, x a ≤ s') → s ≤ s') → sup == s.\n      Proof.\n        split.\n        - apply sup_minimality; auto.\n        - apply H0, sup_ge.\n      Qed.\n\n      Property sup_maximum: ∀ a:A, (∀ b:A, x b ≤ x a) → x a == sup.\n      Proof.\n        intros. split.\n        - apply sup_ge.\n        - apply sup_minimality; assumption.\n      Qed.\n\n    End Def.\n\n    #[export]\n    Instance sup_covariance {A}: Proper (pointwise_relation A le ==> le) sup.\n    Proof λ x y H,\n          sup_minimality x (sup y) (transitivity H (sup_ge y)).\n\n    #[export]\n    Instance sup_compat {A}: Proper (pointwise_relation A eq ==> eq) sup := _.\n\n    Property sup_le_ssup [A]: pointwise_relation _ le (@sup A) (@ssup A).\n    Proof.\n      intro x. apply sup_minimality, ssup_ge.\n    Qed.\n\n    Proposition ssup_is_sup_succ [A] (x: A → Ord): ssup x == sup (succ ∘ x).\n    Proof.\n      split; simpl.\n      - intro a; exists (existT _ a tt). reflexivity.\n      - intros [a []]; exists a. reflexivity.\n    Qed.\n\n    Proposition succ_sup [A] (x: A → Ord): sup x < ssup x ↔ succ (sup x) == ssup x.\n    Proof.\n      split.\n      + split.\n        - apply le_lt; trivial.\n        - cbn. intro a; exists tt; apply sup_ge.\n      + intro H; rewrite <- H; apply succ_gt.\n    Qed.\n\n    Proposition sup_empty_is_zero [A] (x: A → Ord): ¬inhabited A → sup x == zero.\n    Proof.\n      intro N; apply le_zero_is_zero.\n      intros [a]; now contradict N.\n    Qed.\n\n    Remark sup_const_le x [A]: sup (const x : A → Ord) ≤ x.\n    Proof.\n      apply sup_minimality; reflexivity.\n    Qed.\n\n    Remark sup_const_eq x [A]: inhabited A → sup (const x : A → Ord) == x.\n    Proof.\n      split. 1: apply sup_const_le.\n      destruct H as [a].\n      change x with (const x a) at 2. apply sup_ge.\n    Qed.\n\n  End Supremum.\n\n\n  Section Pairwise_Maximum.\n\n    Definition max (x y: Ord): Ord := ssup (sum_rect _ (src_map x) (src_map y)).\n    Local Notation \"[ f , g ]\" := (sum_rect _ f g).\n\n    Property max_ge x y: x ≤ max x y ∧ y ≤ max x y.\n    Proof.\n      destruct x, y. split. intro a.\n      1: exists (inl a). 2: exists (inr a).\n      reflexivity.\n    Qed.\n\n    Definition max_ge_L x y := proj1 (max_ge x y): x ≤ max x y.\n    Definition max_ge_R x y := proj2 (max_ge x y): y ≤ max x y.\n\n    Property max_minimality x y: ∀ z, x ≤ z → y ≤ z → max x y ≤ z.\n    Proof.\n      destruct x, y, z; simpl.\n      intros H1 H2 p. destruct p as [a | a].\n      1: destruct (H1 a). 2: destruct (H2 a).\n      eexists; eassumption.\n    Qed.\n\n    Corollary max_uniqueness x y: ∀ m,\n      x ≤ m → y ≤ m → (∀ z, x ≤ z → y ≤ z → m ≤ z) → max x y == m.\n    Proof.\n      split.\n      - apply max_minimality; assumption.\n      - apply H1; apply max_ge.\n    Qed.\n\n    Proposition max_is_sup x y: max x y == sup (λ b:bool, if b then x else y).\n    Proof.\n      split.\n      - apply max_minimality. \n        + exact (sup_ge _ true).\n        + exact (sup_ge _ false).\n      - apply sup_minimality.\n        intro b; case b. apply max_ge.\n    Qed.\n  \n    #[export]\n    Instance max_covariance: Proper (le ++> le ++> le) max.\n    Proof.\n      intros [A f] [B g] Le [A' f'] [B' g'] Le'.\n      intro x; destruct x as [a | a].\n      - destruct (Le a) as [x]; now exists (inl x).\n      - destruct (Le' a) as [x]; now exists (inr x).\n    Qed.\n\n    #[export]\n    Instance max_compat: Proper (eq ==> eq ==> eq) max := _.\n\n    Property max_idempotence x: max x x == x.\n    Proof.\n      destruct x as [A f]; apply eq_eq.\n      - intros [a | a]; now exists a.\n      - intro a; now exists (inl a).\n    Qed.\n\n    Property max_sym x y: max x y == max y x.\n    Proof.\n      apply eq_eq. intros [a | a].\n      1, 3: exists (inr a). 3, 4: exists (inl a).\n      reflexivity.\n    Qed.\n\n    Property max_eq_L x y: x ≥ y ↔ max x y == x.\n    Proof.\n      split.\n      - split.\n        + rewrite <- H; apply max_idempotence.\n        + apply max_ge.\n      - intro H; rewrite <- H; apply max_ge.\n    Qed.\n\n    Property max_eq_R x y: x ≤ y ↔ max x y == y.\n    Proof.\n      rewrite max_sym. apply max_eq_L.\n    Qed.\n  \n  End Pairwise_Maximum.\n\n\n  Section Pairwise_Minimum.\n    \n    Fixpoint min (x y: Ord): Ord :=\n      ssup (λ p: src x × src y, min (src_map x (fst p)) (src_map y (snd p))).\n\n    Fixpoint min_le (x y: Ord): min x y ≤ x ∧ min x y ≤ y.\n    Proof.\n      destruct x, y; split; intros [a b].\n      1: exists a. 2: exists b.\n      apply min_le.\n    Qed.\n\n    Definition min_le_L x y := proj1 (min_le x y) : min x y ≤ x.\n    Definition min_le_R x y := proj2 (min_le x y) : min x y ≤ y.\n\n    Fixpoint min_maximality x y: ∀ z, z ≤ x → z ≤ y → z ≤ min x y.\n    Proof.\n      destruct x as [A x], y as [B y], z as [C z]. cbn.\n      intros H1 H2 c.\n      specialize (H1 c) as [a H1]; specialize (H2 c) as [b H2].\n      exists (a, b). now_show (z c ≤ min (x a) (y b)).\n      now apply min_maximality.\n    Qed.\n\n    Corollary min_uniqueness x y: ∀ m,\n      m ≤ x → m ≤ y → (∀ z, z ≤ x → z ≤ y → z ≤ m) → min x y == m.\n    Proof.\n      split.\n      - apply H1; apply min_le.\n      - apply min_maximality; assumption.\n    Qed.\n  \n    #[export]\n    Instance min_covariance: Proper (le ++> le ++> le) min.\n    Proof.\n      intros [A f] [B g] Le [A' f'] [B' g'] Le'. simpl.\n      intros (a, a').\n      specialize (Le a) as (b, Le); fold le in Le.\n      specialize (Le' a') as (b', Le'); fold le in Le'.\n      exists (b, b'); cbn in *.\n      apply min_maximality.\n      1: rewrite <- Le. 2: rewrite <- Le'.\n      apply min_le.\n    Qed.\n\n    #[export]\n    Instance min_compat: Proper (eq ==> eq ==> eq) min := _.\n  \n  End Pairwise_Minimum.\n\nEnd Ord.\n\n#[global] Bind Scope Ord_scope with Ord Ord.t.\n\n#[global] Infix \"≤\" := Ord.le: Ord_scope.\n#[global] Infix \"≥\" := Ord.ge: Ord_scope.\n#[global] Infix \"<\" := Ord.lt: Ord_scope.\n#[global] Infix \">\" := Ord.gt: Ord_scope.\n#[global] Infix \"==\" := Ord.eq: Ord_scope.\n#[global] Notation \"x =/= y\" := (not (Ord.eq x y)): Ord_scope.\n\n#[global] Notation \"x == y == z\" := (and (Ord.eq x y) (Ord.eq y z)): Ord_scope.\n#[global] Notation \"x < y < z\" := (and (Ord.lt x y) (Ord.lt y z)): Ord_scope.\n#[global] Notation \"x ≤ y ≤ z\" := (and (Ord.le x y) (Ord.le y z)): Ord_scope.\n#[global] Notation \"x ≤ y < z\" := (and (Ord.le x y) (Ord.lt y z)): Ord_scope.\n#[global] Notation \"x < y ≤ z\" := (and (Ord.lt x y) (Ord.le y z)): Ord_scope.\n#[global] Notation \"x < y == z\" := (and (Ord.lt x y) (Ord.eq y z)): Ord_scope.\n#[global] Notation \"x == y < z\" := (and (Ord.eq x y) (Ord.lt y z)): Ord_scope.\n#[global] Notation \"x ≤ y == z\" := (and (Ord.le x y) (Ord.eq y z)): Ord_scope.\n#[global] Notation \"x == y ≤ z\" := (and (Ord.eq x y) (Ord.le y z)): Ord_scope.\n\n#[export] Instance Ord_eq_rewrite: RewriteRelation Ord.eq | 0 := {}.\n#[export] Instance Ord_lt_rewrite: RewriteRelation Ord.lt | 1 := {}.\n#[export] Instance Ord_le_rewrite: RewriteRelation Ord.le | 1 := {}.\n#[export] Instance Ord_gt_rewrite: RewriteRelation Ord.lt | 2 := {}.\n#[export] Instance Ord_ge_rewrite: RewriteRelation Ord.ge | 2 := {}.\n", "meta": {"author": "imaxw", "repo": "Ordinal", "sha": "bec054b035c759fbe4330d3ffdfb345b2e81ab99", "save_path": "github-repos/coq/imaxw-Ordinal", "path": "github-repos/coq/imaxw-Ordinal/Ordinal-bec054b035c759fbe4330d3ffdfb345b2e81ab99/theories/Base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346598, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6890716958495202}}
{"text": "(* Source : https://erikmd.github.io/tryjscoq/tapfa/tad.v *)\n\nRequire Import List. Import ListNotations.\nSet Implicit Arguments.\n\nModule Type Monoide.\n  Parameter T : Type.           (* une sorte *)\n  Parameter un : T.             (* une constante *)\n  Parameter prod : T -> T -> T. (* une opération *)\n\n  Axiom assoc : forall x y z:T, prod x (prod y z) = prod (prod x y) z.\n  Axiom neutre_g : forall x, prod un x = x.\n  Axiom neutre_d : forall x, prod x un = x.\nEnd Monoide.\n\nModule MonoList <: Monoide. (* vérification sans masquage *)\n  Definition T := list nat.\n  Definition un : T := [].\n  Definition prod (x y : T) := x ++ y.\n  Lemma assoc : forall x y z:T, prod x (prod y z) = prod (prod x y) z.\n  Proof. apply app_assoc. Qed.\n  Lemma neutre_g : forall x, prod un x = x.\n  Proof. reflexivity. Qed.\n  Lemma neutre_d : forall x, prod x un = x.\n  Proof. induction x; auto. simpl. rewrite IHx. reflexivity. Qed.\nEnd MonoList.\n\nModule Use (M : Monoide).\n  Theorem unicite : forall u : M.T, (forall x, M.prod x u = x) -> u = M.un.\n  Proof.\n  intros u Hu.\n  rewrite <-(Hu M.un).\n  rewrite M.neutre_g.\n  reflexivity.\n  Qed.\nEnd Use.\n\nModule Inst := Use(MonoList).\nCheck Inst.unicite.\n(* : forall u : MonoList.T, (forall x : MonoList.T, MonoList.prod x u = x) -> u = MonoList.un *)\n\nPrint MonoList.un.\n(* MonoList.un = [] : MonoList.T *)\nPrint MonoList.T.\n(* MonoList.T = list nat : Set *)\n\nModule Type Pile.\n  Parameter Elem: Type.\n  Parameter P: Type.\n\n  Parameter vide: P.\n  Parameter push: Elem -> P -> P.\n  Parameter estVide: P -> bool.\n  Parameter pop: P -> P.\n  Parameter top: P -> option Elem.\n\n  Axiom estVide_vide: estVide vide = true.\n  Axiom estVide_push: forall p e, estVide (push e p) = false.\n  Axiom top_vide: top vide = None.\n  Axiom top_push: forall p e, top (push e p) = Some e.\n  Axiom pop_vide: pop vide = vide.\n  Axiom pop_push: forall p e, pop (push e p) = p.\nEnd Pile.\n\nModule Pile_Liste <: Pile.\n  Definition Elem := nat.\n  Definition P := list nat.\n  Definition vide : P := [].\n  Definition push (e: Elem) (p: P) := e :: p.\n  Definition estVide (p: P) :=\n    match p with [] => true | _ => false end.\n  Definition top (p: P) :=\n    match p with [] => None | x :: _ => Some x end.\n  Definition pop (p: P) :=\n    match p with [] => [] | _ :: l => l end.\n\n  Lemma estVide_vide: estVide vide = true.\n  Proof.\n  Admitted.\n\n  Lemma estVide_push: forall p e, estVide (push e p) = false.\n  Proof.\n  Admitted.\n\n  Lemma top_vide: top vide = None.\n  Proof.\n  Admitted.\n\n  Lemma top_push: forall p e, top (push e p) = Some e.\n  Proof.\n  Admitted.\n\n  Lemma pop_vide: pop vide = vide.\n  Proof.\n  Admitted.\n\n  Lemma pop_push: forall p e, pop (push e p) = p.\n  Proof.\n  Admitted.\nEnd Pile_Liste.\n\n\nModule Pile_QListe <: Pile.\n  Definition Elem := nat.\n  Definition P := list nat.\n  Definition vide : P := [].\n  Definition push (e: Elem) (p: P) := p ++ [e].\n  Definition estVide (p: P) :=\n    match p with [] => true | _ => false end.\n  Fixpoint top (p: P) :=\n    match p with\n    | [] => None\n    | [e] => Some e\n    | x :: l => top l\n    end.\n  Fixpoint pop (p: P) :=\n    match p with\n    | [] => []\n    | [e] => []\n    | x :: l => x :: pop l\n    end.\n\n  Lemma estVide_vide: estVide vide = true.\n  Proof.\n  Admitted.\n\n  Lemma estVide_push: forall p e, estVide (push e p) = false.\n  Proof.\n  Admitted.\n\n  Lemma top_vide: top vide = None.\n  Proof.\n  Admitted.\n\n  Lemma top_push: forall p e, top (push e p) = Some e.\n  Proof.\n  Admitted.\n\n  Lemma pop_vide: pop vide = vide.\n  Proof.\n  Admitted.\n\n  Lemma pop_push: forall p e, pop (push e p) = p.\n  Proof.\n  Admitted.\n\nEnd Pile_QListe.\n", "meta": {"author": "erikmd", "repo": "tryjscoq", "sha": "b5636d1b7bc6616fe7f136678e30bc4030484f22", "save_path": "github-repos/coq/erikmd-tryjscoq", "path": "github-repos/coq/erikmd-tryjscoq/tryjscoq-b5636d1b7bc6616fe7f136678e30bc4030484f22/tapfa/tad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6890716931557552}}
{"text": "Require Import Lia.\n\nInductive tree : Type :=\n| o : tree\n| T : tree -> tree -> tree.\n\n\nFixpoint branches (t : tree) :=\nmatch t with\n| o => 0\n| T t1 t2 => 1 + (branches t1) + (branches t2)\nend.\n\n\nFixpoint normal (T : tree) : Prop :=\nmatch T with\n| o => True\n| T o t => normal t\n| _ => False\nend.\n\n\nInductive Eq : tree -> tree -> Prop :=\n| EqRef : forall t, Eq t t\n| EqSym : forall s t, Eq s t -> Eq t s\n| EqTran : forall x y z, Eq x y -> Eq y z -> Eq x z\n| EqAsso : forall t1 t2 t3, Eq ( T (T t1 t2) t3 ) (T t1 (T t2 t3) )\n| EqT : forall t1 t2 s1 s2, Eq t1 s1 -> Eq t2 s2 -> Eq (T t1 t2) (T s1 s2).\n\n\nRequire Import Setoid Morphisms.\n\nInstance : Equivalence Eq.\nProof.\n  split.\n  intros t. exact (EqRef t).\n  intros s t H. apply EqSym; auto.\n  intros x y z H1 H2. exact (EqTran x y z H1 H2).\nDefined.\n\n\nInstance T_congruent :\n  Proper (Eq ==> Eq ==> Eq) T.\nProof.\n  intros t s Eq t' s' Eq'. apply EqT; auto.\nQed.\n\n\nInstance branch_congruent :\n  Proper (Eq ==> (@eq nat)) branches.\nProof.\n  intros t s H. induction H; cbn; lia.\nQed.\n  \n\nLemma free_leaf t : \n  t <> o -> (exists t', Eq t (T o t') ).\nProof.\n  intros noLeaf. induction t. now exists o.\n  destruct t1.\n  - now exists t2.\n  - assert (T t1_1 t1_2 <> o) as H by discriminate.\n    destruct (IHt1 H) as [t' H']. exists (T t' t2).\n    now rewrite H', EqAsso.\nQed.\n\n\nLemma ex_iff {X} (P Q : X -> Prop) :\n  (forall x, P x <-> Q x) -> (exists x, P x) <-> (exists x, Q x).\nProof.\n  firstorder.\nQed.\n\nTheorem pre_normalization : forall (n: nat)(t : tree), \n  branches t < n -> exists t', normal t'  /\\ Eq t t'.\nProof.\n  induction n. destruct t; cbn; lia.\n  destruct t; intro Bran. exists o; cbn; split. auto. apply EqRef.\n  cbn in Bran. destruct t1.\n  - assert (branches t2 < n) as H by lia. \n    destruct (IHn _ H) as [s [? E]].\n    exists (T o s). split; cbn; try tauto.\n    rewrite E; apply EqRef.\n  - assert (T t1_1 t1_2 <> o) as  Triv by discriminate.\n    destruct ( free_leaf (T t1_1 t1_2) Triv ) as [t1 N1].\n    eapply (ex_iff (fun x => normal x /\\ Eq (T (T o t1) t2) x)).\n    { intros x. now rewrite N1. }\n    assert (branches t2 < S n) as H by lia.\n    rewrite N1 in Bran; cbn in Bran.\n    assert (S (branches t1 + branches t2) < n) as H' by lia.\n    change (branches (T t1 t2) < n) in H'.\n    destruct (IHn _ H') as [s [? E]].\n    exists (T o s). split; cbn; try tauto.\n    now rewrite EqAsso, E. \nQed.\n\n\nCorollary normalization : forall t, exists t', normal t' /\\ Eq t t'.\nProof.\n  intros t. apply (pre_normalization ( S(branches t)) ). lia.\nQed.\n", "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/tree_normalizing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.7931059438487662, "lm_q1q2_score": 0.6890716911845255}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_collinearright.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_rightreverse.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_altitudebisectsbase.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_droppedperpendicularunique : \n   forall A J M P, \n   Per A M P -> Per A J P -> Col A M J ->\n   eq M J.\nProof.\nintros.\nassert (~ neq M J).\n {\n intro.\n assert (neq J M) by (conclude lemma_inequalitysymmetric).\n let Tf:=fresh in\n assert (Tf:exists E, (BetS M J E /\\ Cong J E M J)) by (conclude lemma_extension);destruct Tf as [E];spliter.\n assert (neq M E) by (forward_using lemma_betweennotequal).\n let Tf:=fresh in\n assert (Tf:exists F, (BetS J M F /\\ Cong M F M E)) by (conclude lemma_extension);destruct Tf as [F];spliter.\n assert (BetS E J M) by (conclude axiom_betweennesssymmetry).\n assert (BetS E J F) by (conclude lemma_3_7b).\n assert (BetS F J E) by (conclude axiom_betweennesssymmetry).\n assert (BetS E M F) by (conclude lemma_3_7a).\n assert (neq J F) by (forward_using lemma_betweennotequal).\n assert (neq F J) by (conclude lemma_inequalitysymmetric).\n assert (Col J M F) by (conclude_def Col ).\n assert (Col M J F) by (forward_using lemma_collinearorder).\n assert (Col M J A) by (forward_using lemma_collinearorder).\n assert (neq J M) by (forward_using lemma_betweennotequal).\n assert (neq M J) by (conclude lemma_inequalitysymmetric).\n assert (Col J F A) by (conclude lemma_collinear4).\n assert (Col A J F) by (forward_using lemma_collinearorder).\n assert (Per F J P) by (conclude lemma_collinearright).\n assert (Col J M F) by (conclude_def Col ).\n assert (Col J M A) by (forward_using lemma_collinearorder).\n assert (Col M F A) by (conclude lemma_collinear4).\n assert (Col A M F) by (forward_using lemma_collinearorder).\n assert (neq M F) by (forward_using lemma_betweennotequal).\n assert (neq F M) by (conclude lemma_inequalitysymmetric).\n assert (Per F M P) by (conclude lemma_collinearright).\n assert (Cong F M M E) by (forward_using lemma_congruenceflip).\n assert (Per F M P) by (conclude lemma_collinearright).\n assert (BetS F M E) by (conclude axiom_betweennesssymmetry).\n assert (Cong F P E P) by (conclude lemma_rightreverse).\n assert (Midpoint F J E) by (conclude lemma_altitudebisectsbase).\n assert (BetS F M E) by (conclude axiom_betweennesssymmetry).\n assert (Cong F M M E) by (forward_using lemma_congruenceflip).\n assert (Midpoint F M E) by (conclude_def Midpoint ).\n assert (eq J M) by (conclude lemma_midpointunique).\n contradict.\n }\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_droppedperpendicularunique.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6890716879213775}}
{"text": "(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire int.Int.\n\n(* Why3 comment *)\n(* abs is replaced with (ZArith.BinInt.Z.abs x) by the coq driver *)\n\n(* Why3 goal *)\nLemma abs_def : forall (x:Z), ((0%Z <= x)%Z ->\n  ((ZArith.BinInt.Z.abs x) = x)) /\\ ((~ (0%Z <= x)%Z) ->\n  ((ZArith.BinInt.Z.abs x) = (-x)%Z)).\nintros x.\nsplit ; intros H.\nnow apply Zabs_eq.\napply Zabs_non_eq.\napply Znot_gt_le.\ncontradict H.\napply Zlt_le_weak.\nnow apply Zgt_lt.\nQed.\n\n(* Why3 goal *)\nLemma Abs_le : forall (x:Z) (y:Z), ((ZArith.BinInt.Z.abs x) <= y)%Z <->\n  (((-y)%Z <= x)%Z /\\ (x <= y)%Z).\nintros x y.\nzify.\nomega.\nQed.\n\n(* Why3 goal *)\nLemma Abs_pos : forall (x:Z), (0%Z <= (ZArith.BinInt.Z.abs x))%Z.\nexact Zabs_pos.\nQed.\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/lib/coq/int/Abs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.6890716782850844}}
{"text": "(** Calculation of an abstract machine for the call-by-name lambda\ncalculus. The resulting abstract machine (almost) coincides with the\nKrivine machine. The relation to the Krivine machine is explained\nbelow. *)\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\n(** We start with the evaluator for this language, which is taken from\nAger et al. \"A functional correspondence between evaluators and\nabstract machines\" (we use Haskell syntax to describe the evaluator):\n<<\ntype Env   = [Thunk]\ndata Thunk = Thunk (() -> Value)\ndata Value = Clo (Thunk -> Value)\n\n\neval :: Expr -> Env -> Value\neval (Var i)   e = case e !! i of\n                     Thunk t -> t ()\neval (Abs x)   e = Clo (\\t -> eval x (t : e))\neval (App x y) e = case eval x e of\n                     Clo f -> f (Thunk (\\_ -> eval y e))\n>>\nAfter defunctionalisation and translation into relational form we\nobtain the semantics below.  *)\n\nInductive Thunk : Set  :=\n  | thunk : Expr -> list Thunk -> Thunk.\n\nDefinition Env : Set := list Thunk.\n\nInductive Value : Set :=\n| Clo : Expr -> Env -> Value.\n\nReserved Notation \"x ⇓[ e ] y\" (at level 80, no associativity).\n\nInductive eval : Expr -> Env -> Value -> Prop :=\n| eval_var e e' x i v : nth e i = Some (thunk x e') -> x ⇓[e'] v -> Var i ⇓[e] v\n| eval_abs e x : Abs x ⇓[e] Clo x e\n| eval_app e e' x x' v y  : x ⇓[e] Clo x' e' -> x' ⇓[thunk y e :: e'] v -> App x y ⇓[e] v\nwhere \"x ⇓[ e ] y\" := (eval x e y).\n\n(** * Abstract machine *)\n\nInductive CONT : Set :=\n| APP : 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 x e' : nth e i = Some (thunk x e') -> ⟨Var i, e, c⟩ ==> ⟨x, e', c⟩\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, APP y e c⟩\n| am_APP y e c x' e' : ⟪APP y e c, Clo x' e'⟫ ==> ⟨x', thunk y e::e', c⟩\nwhere \"x ==> y\" := (AM x y).\n\n(** The only difference between the above machine and the Krivine\nmachine is that the former produces via the rule [am_abs] a state of\nthe form [⟪...⟫], which is then immediately consumed by the rule\n[am_APP]. These two rules [am_abs] and [am_APP] can therefore be fused\ninto a single rule. The resulting machine is exactly coincides with\nthe Krivine machine. *)\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(** - [Var i ⇓[e] v] *)\n\n  begin\n    ⟪c, v ⟫.\n  <<= {apply IHeval}\n    ⟨x, e', c ⟩.\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, v⟫.\n  <<= { apply IHeval2 }\n    ⟨x', (thunk y e::e'), c⟩.\n  <== { apply am_APP }\n    ⟪APP y e c, Clo x' e'⟫.\n  <<= {apply IHeval1}\n    ⟨x, e, APP 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/LambdaCBName.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541611, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.6889368684203023}}
{"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 Orders Rbase Rbasic_fun ROrderedType GenericMinMax.\n\n(** * Maximum and Minimum of two real numbers *)\n\nLocal Open Scope R_scope.\n\n(** The functions [Rmax] and [Rmin] implement indeed\n    a maximum and a minimum *)\n\nLemma Rmax_l : forall x y, y<=x -> Rmax x y = x.\nProof.\n unfold Rmax. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nLemma Rmax_r : forall x y, x<=y -> Rmax x y = y.\nProof.\n unfold Rmax. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nLemma Rmin_l : forall x y, x<=y -> Rmin x y = x.\nProof.\n unfold Rmin. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nLemma Rmin_r : forall x y, y<=x -> Rmin x y = y.\nProof.\n unfold Rmin. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nModule RHasMinMax <: HasMinMax R_as_OT.\n Definition max := Rmax.\n Definition min := Rmin.\n Definition max_l := Rmax_l.\n Definition max_r := Rmax_r.\n Definition min_l := Rmin_l.\n Definition min_r := Rmin_r.\nEnd RHasMinMax.\n\nModule R.\n\n(** We obtain hence all the generic properties of max and min. *)\n\nInclude UsualMinMaxProperties R_as_OT RHasMinMax.\n\n(** * Properties specific to the [R] domain *)\n\n(** Compatibilities (consequences of monotonicity) *)\n\nLemma plus_max_distr_l : forall n m p, Rmax (p + n) (p + m) = p + Rmax n m.\nProof.\n intros. apply max_monotone.\n intros x y. apply Rplus_le_compat_l.\nQed.\n\nLemma plus_max_distr_r : forall n m p, Rmax (n + p) (m + p) = Rmax n m + p.\nProof.\n intros. rewrite (Rplus_comm n p), (Rplus_comm m p), (Rplus_comm _ p).\n apply plus_max_distr_l.\nQed.\n\nLemma plus_min_distr_l : forall n m p, Rmin (p + n) (p + m) = p + Rmin n m.\nProof.\n intros. apply min_monotone.\n intros x y. apply Rplus_le_compat_l.\nQed.\n\nLemma plus_min_distr_r : forall n m p, Rmin (n + p) (m + p) = Rmin n m + p.\nProof.\n intros. rewrite (Rplus_comm n p), (Rplus_comm m p), (Rplus_comm _ p).\n apply plus_min_distr_l.\nQed.\n\n(** Anti-monotonicity swaps the role of [min] and [max] *)\n\nLemma opp_max_distr : forall n m : R, -(Rmax n m) = Rmin (- n) (- m).\nProof.\n intros. symmetry. apply min_max_antimonotone.\n do 3 red. intros; apply Rge_le. apply Ropp_le_ge_contravar; auto.\nQed.\n\nLemma opp_min_distr : forall n m : R, - (Rmin n m) = Rmax (- n) (- m).\nProof.\n intros. symmetry. apply max_min_antimonotone.\n do 3 red. intros; apply Rge_le. apply Ropp_le_ge_contravar; auto.\nQed.\n\nLemma minus_max_distr_l : forall n m p, Rmax (p - n) (p - m) = p - Rmin n m.\nProof.\n unfold Rminus. intros. rewrite opp_min_distr. apply plus_max_distr_l.\nQed.\n\nLemma minus_max_distr_r : forall n m p, Rmax (n - p) (m - p) = Rmax n m - p.\nProof.\n unfold Rminus. intros. apply plus_max_distr_r.\nQed.\n\nLemma minus_min_distr_l : forall n m p, Rmin (p - n) (p - m) = p - Rmax n m.\nProof.\n unfold Rminus. intros. rewrite opp_max_distr. apply plus_min_distr_l.\nQed.\n\nLemma minus_min_distr_r : forall n m p, Rmin (n - p) (m - p) = Rmin n m - p.\nProof.\n unfold Rminus. intros. apply plus_min_distr_r.\nQed.\n\nEnd R.\n", "meta": {"author": "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/Reals/Rminmax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768094082276, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.6889368605591049}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (lf2 : natural) (y : natural) (lf1 : natural)\n  : natural := plus (Succ y) Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj206_coqofml_JBMFai.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6889259381026861}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Crypto.Util.Decidable.\nRequire Import Crypto.Util.ZUtil.Notations.\nRequire Import Crypto.Util.LetIn.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Definition pow2_mod n i := (n &' (Z.ones i)).\n\n  Definition zselect (cond zero_case nonzero_case : Z) :=\n    if cond =? 0 then zero_case else nonzero_case.\n\n  Definition add_modulo x y modulus :=\n    if (modulus <=? x + y) then (x + y) - modulus else (x + y).\n\n  Definition get_carry (bitwidth : Z) (v : Z) : Z * Z\n    := (v mod 2^bitwidth, v / 2^bitwidth).\n  Definition add_with_carry (c : Z) (x y : Z) : Z\n    := c + x + y.\n  Definition add_with_get_carry (bitwidth : Z) (c : Z) (x y : Z) : Z * Z\n    := get_carry bitwidth (add_with_carry c x y).\n  Definition add_get_carry (bitwidth : Z) (x y : Z) : Z * Z\n    := add_with_get_carry bitwidth 0 x y.\n\n  Definition get_borrow (bitwidth : Z) (v : Z) : Z * Z\n    := let '(v, c) := get_carry bitwidth v in\n       (v, -c).\n  Definition sub_with_borrow (c : Z) (x y : Z) : Z\n    := add_with_carry (-c) x (-y).\n  Definition sub_with_get_borrow (bitwidth : Z) (c : Z) (x y : Z) : Z * Z\n    := get_borrow bitwidth (sub_with_borrow c x y).\n  Definition sub_get_borrow (bitwidth : Z) (x y : Z) : Z * Z\n    := sub_with_get_borrow bitwidth 0 x y.\n\n  (* splits at [bound], not [2^bitwidth]; wrapper to make add_getcarry\n  work if input is not known to be a power of 2 *)\n  Definition add_get_carry_full (bound : Z) (x y : Z) : Z * Z\n    := if 2 ^ (Z.log2 bound) =? bound\n       then add_get_carry (Z.log2 bound) x y\n       else ((x + y) mod bound, (x + y) / bound).\n  Definition add_with_get_carry_full (bound : Z) (c x y : Z) : Z * Z\n    := if 2 ^ (Z.log2 bound) =? bound\n       then add_with_get_carry (Z.log2 bound) c x y\n       else ((c + x + y) mod bound, (c + x + y) / bound).\n  Definition sub_get_borrow_full (bound : Z) (x y : Z) : Z * Z\n    := if 2 ^ (Z.log2 bound) =? bound\n       then sub_get_borrow (Z.log2 bound) x y\n       else ((x - y) mod bound, -((x - y) / bound)).\n  Definition sub_with_get_borrow_full (bound : Z) (c x y : Z) : Z * Z\n    := if 2 ^ (Z.log2 bound) =? bound\n       then sub_with_get_borrow (Z.log2 bound) c x y\n       else ((x - y - c) mod bound, -((x - y - c) / bound)).\n\n  Definition mul_split_at_bitwidth (bitwidth : Z) (x y : Z) : Z * Z\n    := dlet xy := x * y in\n        (match bitwidth with\n         | Z.pos _ | Z0 => xy &' Z.ones bitwidth\n         | Z.neg _ => xy mod 2^bitwidth\n         end,\n         match bitwidth with\n         | Z.pos _ | Z0 => xy >> bitwidth\n         | Z.neg _ => xy / 2^bitwidth\n         end).\n  Definition mul_split (s x y : Z) : Z * Z\n    := if s =? 2^Z.log2 s\n       then mul_split_at_bitwidth (Z.log2 s) x y\n       else ((x * y) mod s, (x * y) / s).\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/Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6889259364559157}}
{"text": "(** * The very classical example of GCD computation in Hoare logic.\n\n This file is part of the \"Tutorial on Hoare Logic\". \n For an introduction to this Coq library, \n see README #or <a href=index.html>index.html</a>#.\n\n This file illustrates how to use the Hoare logic described in file\n #<a href=\"hoarelogicsemantics.html\">#[hoarelogicsemantics]#</a>#\n\n\n I use here the very classical example of \"great common divisor\"\n computations through successive subtractions.\n*)\n\nSet Implicit Arguments.\n\nRequire Import ZArith.\nRequire Import Znumtheory.\nRequire Import Bool.\nRequire Import hoarelogic.\nRequire Import Zwf.\nRequire Import Wellfounded.\n\n(** * Implementation of the expression language *)\nModule Example <: ExprLang.\n\n(** Here, I use only two global variables [VX] and [VY] of type [Z]\n(binary integers). *)\nInductive ExVar: Type -> Type := \n  VX: (ExVar Z) | \n  VY: (ExVar Z). \n\nDefinition Var:=ExVar.\n\n(** An environment is just a pair of integers. First component\nrepresents [VX] and second component represents [VY].  This is\nexpressed in [upd] and [get] below. *)\nDefinition Env:= (Z*Z)%type.\n\nDefinition upd (A:Type): (ExVar A) -> A -> Env -> Env :=\n fun x => \n   match x in (ExVar A) return A -> Env -> Env with\n   | VX => fun vx e => (vx,snd e)\n   | VY => fun vy e => (fst e,vy)\n   end.\n\nDefinition get (A:Type): (ExVar A) -> Env -> A :=\n fun x => \n   match x in (ExVar A) return Env -> A with\n   | VX => fun e => fst e\n   | VY => fun e => snd e\n   end.\n\n(** I consider only two binary operators [PLUS] and [MINUS]. Their\nmeaning is given by [eval_binOP] below *)\nInductive binOP: Type := PLUS | MINUS.\n \nDefinition eval_binOP: binOP -> Z -> Z -> Z :=\n fun op => match op with\n  | PLUS => Zplus\n  | MINUS => Zminus\n end.\n\n(** I consider only three comparison operators [EQ], [NEQ] and\n[LE]. Their meaning is given by [eval_relOP] below *)\nInductive relOP: Type := EQ | NEQ | LE.\n\nDefinition eval_relOP: relOP -> Z -> Z -> bool :=\n fun op => match op with\n  | EQ => Zeq_bool\n  | NEQ => Zneq_bool\n  | LE => Zle_bool\n end. \n\n(** Here is the abstract syntax of expressions. The semantics is given\nby [eval] below *)\nInductive ExExpr: Type -> Type :=\n | const: forall (A:Type), A -> (ExExpr A)\n | binop: binOP -> (ExExpr Z) -> (ExExpr Z) -> (ExExpr Z)\n | relop: relOP -> (ExExpr Z) -> (ExExpr Z) -> (ExExpr bool)\n | getvar: forall (A:Type), (ExVar A) -> (ExExpr A). \n\nDefinition Expr:= ExExpr.\n\nFixpoint eval (A:Type) (expr:Expr A) (e:Env) { struct expr } : A :=\n match expr in ExExpr A return A with\n | const A v => v\n | binop op e1 e2 => eval_binOP op (eval e1 e) (eval e2 e)\n | relop op e1 e2 => eval_relOP op (eval e1 e) (eval e2 e)\n | getvar A x => (get x e)\nend.\n\nEnd Example.\n\n(** * Instantiation of the Hoare logic on this langage. *)\nModule HL :=  HoareLogic(Example).\nImport HL.\nImport Example.\n\n(** These coercions makes the abstract syntax more user-friendly *)\nCoercion getvar: ExVar >-> ExExpr.\nCoercion binop: binOP >-> Funclass.\nCoercion relop: relOP >-> Funclass.\n\n(** A last coercion useful for assertions *)\nCoercion get: ExVar >-> Funclass.\n\n(** ** A [gcd] computation in this language *)\nDefinition gcd := \n  (Iwhile (NEQ VX VY)\n          (Iif (LE VX VY)\n               (Iset VY (MINUS VY VX))\n               (Iset VX (MINUS VX VY)))).\n\n(** A small technical lemma on the mathematical notion of gcd (called\n[Zis_gcd]) *)\nLemma Zgcd_minus: forall a b d:Z, Zis_gcd a (b - a) d -> Zis_gcd a b d.\nProof.\n  intros a b d H; case H; constructor; intuition (auto with zarith).\n  replace b with (b-a+a)%Z.\n  auto with zarith.\n  omega.\nQed.\n\nHint Resolve Zgcd_minus: zarith.\n\n(** Two other lemmas relating [Zneq_bool] function with inequality\nrelation *)\nLemma Zneq_bool_false: forall x y, Zneq_bool x y=false -> x=y.\nProof.\n intros x y H0; apply Zcompare_Eq_eq; generalize H0; clear H0; unfold Zneq_bool. case (x ?= y)%Z; auto; \n try (intros; discriminate); auto. \nQed.\n\nLemma Zneq_bool_true: forall x y, Zneq_bool x y=true -> x<>y.\nProof.\n intros x y; unfold Zneq_bool.\n intros H H0; subst.\n rewrite Zcompare_refl in H.\n discriminate.\nQed.\n\nHint Resolve Zneq_bool_true Zneq_bool_false Zle_bool_imp_le Zis_gcd_intro: zarith.\n\n(** ** Partial correctness proof of [gcd] *)\nLemma gcd_partial_proof: \n forall x0 y0, (fun e => (VX e)=x0 /\\ (VY e)=y0) \n   |= gcd  {= fun e => (Zis_gcd x0 y0 (VX e)) =}.\nProof.\n intros x0 y0. \n apply PHL.soundness.\n simpl.\n intros e; intuition subst.\n (** after PO generation, I provide the invariant and simplify the goal *) \n constructor 1 with (x:=fun e'=> \n  forall d, (Zis_gcd (VX e') (VY e') d)\n              ->(Zis_gcd (VX e) (VY e) d)); simpl.\n intuition auto with zarith.\n (** - invariant => postcondition *)\n cutrewrite <- ((fst e')=(snd e')) in H; auto with zarith.\nQed.\n\n\n(** ** Total correctness proof of [gcd] *)\n\nLemma gcd_total_proof: \n forall x0 y0, (fun e => (VX e)=x0 /\\ (VY e)=y0 /\\ x0 > 0 /\\ y0 > 0)\n  |= gcd  [= fun e => (Zis_gcd x0 y0 (VX e)) =].\nProof.\n intros x0 y0. \n apply THL.soundness.\n simpl.\n intros e; intuition subst.\n (** after simplification, I provide the invariant and then the variant *) \n constructor 1 with (x:=fun e' => (VX e') > 0 /\\ (VY e') > 0 /\\\n  forall d, (Zis_gcd (VX e') (VY e') d)\n              ->(Zis_gcd (VX e) (VY e) d)); simpl.\n constructor 1 with (x:=fun e1 e0 => Zwf 0 ((VX e1)+(VY e1)) ((VX e0)+(VY e0))).\n (** - proof that my variant is a well_founded relation *) \n constructor 1.\n apply wf_inverse_image with (f:=fun e=>(VX e)+(VY e)).\n auto with datatypes.\n (** - other goals *)\n  unfold Zwf; simpl; (intuition auto with zarith).\n (** -- invariant => postcondition \n      --- gcd part like in partial correctness proof \n *)\n  cutrewrite <- ((fst e')=(snd e')) in H5; auto with zarith.\n  (** --- new VY in branch \"then\" is positive *)\n  cut ((fst e')<=(snd e')); auto with zarith.\n  cut ((fst e')<>(snd e')); auto with zarith.\n  (** --- new VX in branch \"else\" is positive *)\n  cut (~(fst e')<=(snd e')); auto with zarith.\n  intros X; rewrite (Zle_imp_le_bool _ _ X) in H4.\n  discriminate.\nQed.\n\n(** ** Another example: infinite loops in partial correctness.\n\nBasic Hoare logic is not well-suited for reasoning about non-terminating programs.\nIn total correctness, postconditions of non-terminating programs are not provable.\nIn partial correctness, a non-terminating program satisfies any (unsatisfiable) postcondition.\n\nFor example, in an informal \"meaning\", the program below enumerates all multiples of 3. But this meaning \ncan not be expressed here (even in partial correctness).\n*)\n\nDefinition enum_3N := \n  (Iseq (Iset VX (const 0))\n        (Iwhile (const true)\n                (Iset VX (PLUS VX (const 3))))).\n\nLemma enum_3N_stupid: \n (fun e => True) |= enum_3N  {= fun e => False =}.\nProof.\n apply PHL.soundness.\n simpl.\n constructor 1 with (x:=fun _:Env => True).\n intuition (discriminate || auto).\nQed.\n\n\n(** \"Tutorial on Hoare Logic\" Library. Copyright 2007 Sylvain Boulme.\n\nThis file is distributed under the terms of the \n \"GNU LESSER GENERAL PUBLIC LICENSE\" version 3.  \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/hoare-tut/exgcd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245994514084, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.6889192764346234}}
{"text": "(*\n(C) Copyright 2010, COQTAIL team\n\nProject Info: http://sourceforge.net/projects/coqtail/\n\nThis library is free software; you can redistribute it and/or modify it\nunder the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation; either version 2.1 of the License, or\n(at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\nor FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\nLicense for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,\nUSA.\n*)\n\n(** Common definitions of real functions sequences. *)\nRequire Import Cbase.\nRequire Import Cfunctions.\nRequire Import Csequence.\nRequire Import Canalysis_def.\n\nDelimit Scope CFseq_scope with Cseq_scope.\n\nOpen Local Scope C_scope.\nOpen Local Scope CFseq_scope.\n\nImplicit Type n : nat.\nImplicit Type fn gn : nat -> C -> C.\nImplicit Type f g : C -> C.\n\n(** * Morphism of functions on R -> R to sequences. *)\n\nDefinition CFseq_plus fn gn n := (fn n + gn n)%F.\nDefinition CFseq_mult fn gn n := (fn n * gn n)%F.\nDefinition CFseq_opp fn n := (fun x => Copp (fn n x))%F.\nDefinition CFseq_inv fn n := (fun x => Cinv (fn n x))%F.\n\nInfix \"+\" := CFseq_plus : CFseq_scope.\nInfix \"*\" := CFseq_mult : CFseq_scope.\nNotation \"- u\" := (CFseq_opp u) : CFseq_scope.\nNotation \"/ u\" := (CFseq_inv u) : CFseq_scope.\n\nDefinition CFseq_minus fn gn n := (fn n - gn n)%F.\nDefinition CFseq_div fn gn n := (fn n / gn n)%F.\n\nInfix \"-\" := CFseq_minus : CFseq_scope.\nInfix \"/\" := CFseq_div : CFseq_scope.\n\n(** * Convergence of functions sequences. *)\n\nDefinition CFseq_cv fn f := forall x, Cseq_cv (fun n => fn n x) (f x).\nDefinition CFseq_cv_boule fn f (c : C) (r : posreal) := forall x,  Boule c r x -> Cseq_cv (fun n => fn n x) (f x).\n\nDefinition CFseq_cvu fn f (x : C) (r : posreal) := forall eps : R, 0 < eps ->\n        exists N : nat, forall n (y : C), (N <= n)%nat -> Boule x r y ->\n        C_dist (fn n y) (f y) < eps.\n\nDefinition CFpartial_sum (fn : nat -> C) N := sum_f_C0 fn 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/Complex/CFsequence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.6889192658968478}}
{"text": "(** \n  ** The ring ([ring]) structure and variants such as integral domains ([idom]) and fields ([field]).\n*)\n\nRequire Import ssr.\nRequire Import lib.\n\nSet Implicit Arguments. \nUnset Strict Implicit. \nImport Prenex Implicits.\n\n(** Rings *)\n\nSection RingAxioms.\n\nVariable R : eqType.\nVariable add : R -> R -> R.\nVariable mul : R -> R -> R.\nVariable opp : R -> R.\nVariable zero : R.\nVariable one : R.\n\nNotation \"x1 + x2\" := (add x1 x2).\nNotation \"x1 * x2\" := (mul x1 x2).\nNotation \"- x\" := (opp x). \nNotation \"0\" := zero. \nNotation \"x - y\" := (x + opp y).\n\nStructure ring_axioms : Prop := Ring_axioms {\n  addC': forall x1 x2 : R, x1 + x2 = x2 + x1;\n  addA': forall x1 x2 x3 : R, x1 + (x2 + x3) = (x1 + x2) + x3;\n  add0r' : forall x : R, x + 0 = x;\n  oppL' : forall x : R, - x + x = 0;\n  mulA' : forall x1 x2 x3 : R, x1 * (x2 * x3) = x1 * x2 * x3;\n  distPM' : forall x1 x2 x3 : R, (x1 + x2) * x3 = x1 * x3 + x2 * x3;\n  distMP' : forall x1 x2 x3 : R, x1 * (x2 + x3) = x1 * x2 + x1 * x3;\n  mul1r' : forall x : R, one * x = x;\n  mulr1' : forall x : R, x * one = x;\n  mulC' : forall x1 x2 : R, x1 * x2 = x2 * x1\n}.\n\nEnd RingAxioms.\n\n\nModule Ring.\n\nStructure ring : Type := Ring {\n  rbase :> eqType;\n  add : rbase -> rbase -> rbase;\n  mul : rbase -> rbase -> rbase;\n  opp : rbase -> rbase;\n  zero : rbase;\n  one : rbase;\n  axioms : ring_axioms add mul opp zero one\n}.\n\nEnd Ring.\n\n\nDelimit Scope ring_scope with R.\nBind Scope ring_scope with Ring.rbase.\n\nArguments Scope Ring.add [_ ring_scope ring_scope].\nArguments Scope Ring.mul [_ ring_scope ring_scope].\nArguments Scope Ring.opp [_ ring_scope].\n\nDefinition addr := nosimpl Ring.add.\nDefinition oppr := nosimpl Ring.opp.\nDefinition mulr := nosimpl Ring.mul.\nDefinition zeror := nosimpl Ring.zero.\nDefinition oner := nosimpl Ring.one.\n\nImplicit Arguments Ring.zero [].\nImplicit Arguments Ring.one [].\n\nOpen Scope ring_scope.\nNotation ring := Ring.ring (only parsing).\nNotation \"x1 + x2\" := (addr x1 x2) : ring_scope.\nNotation \"x1 * x2\" := (mulr x1 x2) : ring_scope.\nNotation \"- x\" := (oppr x) : ring_scope.\nNotation \"0\" := (zeror _) : ring_scope.\nNotation \"1\" := (oner _) : ring_scope.\nNotation \"x - y\" := (x + oppr y) : ring_scope.\nNotation addrr := (fun x y => y + x).\nNotation mulrr := (fun x y => y * x).\n\n(** Identities and Basic Lemmas *)\n\nSection Rings.\n\nVariable R : ring.\n\nNotation axioms := Ring.axioms.\n\nLemma oppL : forall x : R, -x + x = 0.\nProof. exact: oppL' (axioms _). Qed. \n\nLemma addr0 : forall x: R, x + 0 = x.\nProof. exact: add0r' (axioms _). Qed.\n\nLemma mulA : forall x y z : R, x * (y * z) = x * y * z. \nProof. exact: mulA' (axioms _). Qed.\n\nLemma distPM : forall x1 x2 x3 : R, (x1 + x2) * x3 = (x1 * x3) + (x2 * x3).\nProof.  exact: distPM' (axioms _). Qed.\n\nLemma distMP : forall x1 x2 x3 : R, x1 * (x2 + x3) = (x1 * x2) + (x1 * x3).\nProof. exact: distMP' (axioms _). Qed.\n\nLemma addC : forall x y : R, x + y = y + x.\nProof. exact: addC' (axioms _). Qed.\n\nLemma addA : forall x y z : R, x + (y + z) = (x + y) + z. \nProof. exact: addA' (axioms _). Qed.\n\nLemma add0r : forall x : R, 0 + x = x.\nProof. move=> x; rewrite addC; exact: addr0. Qed.\n\nLemma oppR : forall x : R, x + -x = 0.\nProof. move=> x. rewrite addC. exact: oppL. Qed.\n\nLemma addr_injl : forall x : R, injective (addr x).\nProof. by move=> x y z; move/(congr1 (addr (-x))); rewrite !addA !oppL !add0r. Qed.\n\nLemma addr_injr : forall x : R, injective (addrr x).\nProof. by move=> x y z /=; rewrite addC [z + _]addC; exact: addr_injl. Qed.\n\nLemma addKr : forall x : R, cancel (addr x) (addr (- x)).\nProof. by move=> x y; rewrite addA oppL add0r. Qed.\n\nLemma addKrV : forall x : R, cancel (addr (- x)) (addr x).\nProof. by move=> x y; rewrite addA oppR add0r. Qed.\n\nLemma addrK : forall x : R, cancel (addrr x) (addrr (- x)).\nProof. by move=> x y; rewrite -addA oppR addr0. Qed.\n\nLemma addrKV : forall x : R, cancel (addrr (- x)) (addrr x).\nProof. by move=> x y; rewrite -addA oppL addr0. Qed.\n\nLemma opp_opp : forall x : R, -(-x) = x.\nProof. by move=> x; apply: (@addr_injr (- x)); rewrite oppL oppR. Qed.\n\nLemma opp_uniq : forall x y y' : R, x + y = 0 -> x + y' = 0 -> y = y'.\nProof. by move=> x y y' H H'; apply (@addr_injl x); rewrite H H'. Qed.\n\nLemma opp_def : forall x y : R, x + y = 0 -> y = - x.\nProof. move=> x y H; apply (@opp_uniq x);auto; by rewrite oppR. Qed.\n\n(** # <a href=http://code.google.com/p/coq-galois-theory/wiki/TheoremTimeline> ROTMAN: Theorem 1(i) </a> # *)\nLemma mul0r : forall x : R, 0 * x = 0.\nProof. by move=> x; apply (@addr_injr (0 * x)); rewrite -distPM !add0r. Qed.\n\nLemma mulr0 : forall x : R, x * 0 = 0.\nProof. by move=> x; apply (@addr_injr (x * 0)); rewrite -distMP !add0r. Qed.\n\nLemma mul_oppL : forall x y : R, - x * y = - (x * y).\nProof. by move=> x y; apply (@opp_uniq (x * y));rewrite -?distPM oppR ?mul0r. Qed. \n  \nLemma mul_oppR : forall x y : R, x * - y = - (x * y).\nProof. by move=> x y; apply (@opp_uniq (x * y)); rewrite -?distMP oppR ?mulr0. Qed.\n\nLemma mul_opp_opp : forall x y : R, - x * - y = x * y.\nProof. by move=> x y; rewrite mul_oppR mul_oppL opp_opp. Qed.\n\nLemma opp_sym : forall x y : R, - x = y -> x = - y.\nProof. by move=> x y H; rewrite -H; symmetry; exact: opp_opp. Qed.\n\nLemma addrCA : forall m n p : R, m + (n + p) = n + (m + p).\nProof. by move=> m n p; rewrite addA [m + _]addC addA. Qed.\n\nLemma opp0 : - 0 = 0 :> R.\nProof. by apply (@addr_injr 0); rewrite oppL !addr0. Qed.\n\nLemma oppr0 : forall x : R, (-x == 0) = (x == 0).\nProof. \n (* {{{ *)\n\nmove=> x. \napply/eqP.\ncase H : (_ == _) => [|H']; first by rewrite (eqP H) opp0.\nmove: (congr1 (@oppr _) H).\nrewrite opp_opp opp0 => H0.\nby rewrite H0 eq_refl in H'.\n\n (* }}} *)\nQed.\n\nLemma mul1r : forall x : R, 1 * x = x. \nProof. exact: mul1r' (axioms _). Qed.\n\nLemma mulr1 : forall x : R, x * 1 = x.\nProof. exact: mulr1' (axioms _). Qed.\n\n(** # <a href=http://code.google.com/p/coq-galois-theory/wiki/TheoremTimeline> ROTMAN: Theorem 1(ii) </a> # *)\nLemma mul_opp1r : forall x : R, -(1) * x = - x.\nProof. by move=> x; apply (@addr_injl x); rewrite oppR mul_oppL mul1r oppR. Qed.\n\n(** # <a href=http://code.google.com/p/coq-galois-theory/wiki/TheoremTimeline> ROTMAN: Theorem 1(iii) </a> # *)\nLemma mul_opp1_opp : forall x : R, -(1) * - x = x.\nProof. by move=> x; rewrite mul_opp1r opp_opp. Qed.\n\nLemma mul_opp1_opp1 : -(1) * -(1) = 1 :> R.\nProof.  exact: mul_opp1_opp. Qed.\n\nLemma opp_add : forall x y : R, -(x + y) = - x - y.\nProof. by move=> x y; rewrite -mul_opp1r distMP !mul_opp1r. Qed.\n\nLemma zero_ring : (1:R) = 0 -> forall x : R, x = 0.\nProof. by move=> H x; rewrite -[x]mul1r H mul0r. Qed.\n\nLemma subr0 : forall x : R, x - 0 = x.\nProof. by rewrite opp0; exact: addr0. Qed.\n\nLemma sub0r : forall x : R, 0 - x = - x.\nProof. by move=> x; rewrite add0r. Qed.\n\nLemma mulC : forall x y : R, x * y = y * x.\nProof. exact: mulC' (axioms _). Qed.\n\nLemma mulrCA : forall m n p : R, m * (n * p) = n * (m * p).\nProof. by move=> m n p; rewrite mulA [m * _]mulC mulA. Qed.\n\nDefinition rdivides a b := exists a' : R, a * a' = b.\n\nNotation \"x |` y\" := (rdivides x y) (at level 55).\n\nLemma div0 : forall c : R, c |` 0.\nProof. exists (0:R); exact: mulr0. Qed.\n\nLemma div1 : forall c : R, 1 |` c.\nProof. by move=> c; exists c; rewrite mul1r. Qed.\n\nLemma div_refl : forall c : R, c |` c.\nProof. by move=> x; exists (1 : R); rewrite mulr1. Qed.\n\nLemma div_add : forall a b c : R, c |` a -> c |` b -> c |` a + b.\nProof. \n (* {{{ *)\n\nmove=> a b c [a' <-] [b' <-].\nrewrite -distMP.\nby exists (a' + b').\n\n (* }}} *)\nQed.\n\nLemma div_mulL : forall a b c : R, c |` a -> c |` a * b.\nProof. by move=> a b c [a' <-]; exists (a' * b); rewrite mulA. Qed.\n\nLemma div_trans : forall a b c : R, a |` b -> b |` c -> a |` c.\nProof. by move=> a b c [a' <-] [b' <-]; rewrite -mulA; exists (a' * b'). Qed.\n\nLemma div_mulR : forall a b c : R, c |` b -> c |` a * b.\nProof. by move=> a b c [b' <-]; exists (a * b'); rewrite mulC -mulA [b' * _]mulC. Qed.\n\nLemma div_addP : forall a b c : R, c |` a + b -> c |` a -> c |` b.\nProof.\n (* {{{ *)\n\nmove=> a b c [d Hd] [a' Ha'].\nrewrite -Ha' in Hd.\nmove: (canLR Hd (addKr (c * a'))).\nrewrite -mul_oppR -distMP.\nby exists (- a' + d).\n\n (* }}} *)\nQed.\n\n(** Definitions *)\n\nCoInductive gcd (f g d : R) : Type :=\n  Gcd : (d |` f) -> (d |` g) -> \n       (forall d', (d' |` f) -> (d' |` g) -> (d' |` d)) -> gcd f g d.\n\nDefinition unit (x : R) := exists x', (x * x' = 1).\n\nLemma unit_nz : (1:R) <> 0 -> forall u, unit u -> u <> (0:R).\nProof. by move=> H u [u' Hu'] H'; rewrite H' mul0r in Hu'; move/esym: Hu'. Qed.\n\nDefinition associates x y := exists u : R, unit u /\\ x = u * y.  \n\nDefinition irreducible (p : R) := forall x y, x * y = p -> (unit x \\/ unit y).\n\nDefinition prime (p : R) := ~ (unit p) /\\ irreducible p.\n\nDefinition rel_prime x y := forall d : R, gcd x y d -> unit d.\n\nFixpoint pow (x : R) (n : nat) {struct n} : R := \n  if n is S n' then x * pow x n' else 1.\n\nFixpoint cmul (n : nat) (a : R) {struct n} : R := \n  if n is S n' then a + cmul n' a else 1.\n\nFixpoint dot (s1 s2 : seq R) {struct s1} : R := \n  match s1,s2 with \n    | seq0, seq0 => 1%R\n    | Adds h1 t1, Adds h2 t2 => h1 * h2 + dot t1 t2\n    | _, _ => 0\n  end.\n\nDefinition domainP := forall x1 x2 : R, x1 * x2 = 0 -> x1 = 0 \\/ x2 = 0.\n\n(** # <a href=http://code.google.com/p/coq-galois-theory/wiki/TheoremTimeline> ROTMAN: Theorem 2</a> # *)\nLemma domain_cancel : (forall r a b : R, r != 0 -> r * a = r * b -> a = b) <-> domainP.\nProof.\n (* {{{ *)\nsplit.\n  move=> H x1 x2 H1.\n  case H2 : (x1 == 0).\n  left; by apply/eqP.\n  right.\n  move/negbT: H2.\n  move/(H x1 x2 0).\n  apply.\n  by rewrite mulr0.\nmove=> H r a b H1 H2.\nhave: r * (a - b) = 0 by rewrite distMP mul_oppR H2 oppR.\nmove/(H _ _) => [].\n  by move/eqP: H1.\nmove=> H3.\napply(@addr_injr (-b)).\nby rewrite H3 oppR.\n (* }}} *)\nQed.\n\n(** # <a href=http://code.google.com/p/coq-galois-theory/wiki/TheoremTimeline> ROTMAN: Exercise 4</a> # *)\nLemma domain_unit : domainP -> forall f g u v : R, f <> 0 -> f = u * g -> g = v * f -> u * v = 1.\nProof.\n (* {{{ *)\nmove=> H f g u v Hf Hfg Hgf.\nmove: Hfg.\nrewrite {}Hgf mulA -{1}(@mul1r f) => Hfg.\nmove: {Hfg}(comb (addrr (- (1 * f))) Hfg).\nrewrite oppR -mul_oppL -distPM.\nmove=> Hg.\nmove: {Hg}(sym_eq Hg).\nmove/H.\nmove=> [] //.\nmove/(comb (addrr 1)).\nby rewrite -addA oppL addr0 add0r.\n (* }}} *)\nQed.\n\nEnd Rings.\n\nNotation \"x |` y\" := (rdivides x y) (at level 55) : ring_scope.\nNotation \"x ^ n\" := (pow x n) : ring_scope.\n\nPrenex Implicits unit.\n\n(* -------------------------------------------------------------------------- *)\n(*  Integral domains                                                          *)\n(* -------------------------------------------------------------------------- *)\n\n(** Integral domains *)\nStructure domain : Type := Idom {\n  ibase :> ring;\n  integ : domainP ibase\n}.\n\nSection Domain.\n\nVariable R : domain.\n\nLemma mulr_injl : forall x : R, x <> 0 -> injective (mulr x).\nProof.\n (* {{{ *)\nmove=> x Hx y z Hxy.\nrewrite -(add0r (x * z)) in Hxy.\nmove/(fun H => canLR H (addrK _)) : Hxy.\nrewrite -mul_oppR -distMP.\nmove/integ => [|] //.\nmove/(fun H => canRL H (addrKV _)).\nby rewrite add0r.\n (* }}} *)\nQed.\n\nLemma mulr_injr : forall z x y : R, z <> 0 -> (x * z = y * z) -> (x = y).\nProof. by move=> z x y H0 H; apply: (mulr_injl H0); rewrite mulC H mulC. Qed.\nOpen Scope ring_scope.\n\nLemma div_sym : forall a b : R, a |` b -> b |` a -> associates a b.\nProof.\n (* {{{ *)\nmove=> a b [a' Ha'] [b' Hb'].\ncase Ha : (a == 0); move/eqP: Ha => Ha.\n  have Hb : (b = 0) by symmetry; rewrite Ha mul0r in Ha'.\n  exists (1:R); split; first by exists (1:R); rewrite mulr1.\n  by rewrite Ha Hb mulr0.\nexists b'.\nsplit.\n  exists a'.\n  rewrite -Ha' in Hb'.\n  rewrite mulC.\n  apply: (mulr_injl Ha).\n  by rewrite mulA mulr1.\nby rewrite -Hb' mulC.\n (* }}} *)\nQed.  \n\nEnd Domain. \n\n(** Fields *)\n\nModule Field.\n\nStructure field : Type := Field {\n  fbase :> domain;\n  inv : fbase -> fbase;  \n  unitPL : forall x : fbase, x <> 0 -> inv x * x = 1;\n  nzP : 1 <> 0 :> fbase;\n  inv0 : inv 0 = 0\n}.\n\nEnd Field.\n\nNotation field := Field.field (only parsing).\nArguments Scope Field.inv [_ ring_scope].\n\nDefinition invf := nosimpl Field.inv.\n\nNotation \"x '^-1'\" := (invf x) (at level 9, format \"x '^-1'\") : ring_scope.\n\n(** Euclidean rings *)\n\nOpen Scope nati_scope.\nOpen Scope ring_scope.\n\nInductive div_res (R : ring) (deg : R -> nati) (a b : R) : Prop :=\n  Div_res q r : a = q * b + r -> deg r < deg b -> div_res deg a b.\n\nStructure euclid_ring : Type := Ering {\n  ebase :> domain;\n  deg : ebase -> nati;\n  deg0 : forall x, deg x = -oo -> x = 0;\n  deg0' : forall x, x = 0 -> deg x = -oo;\n  deg_lt : forall a b, b <> 0 -> deg a <= deg (a * b);\n  degP : forall a b, b <> 0 -> div_res deg a b\n}.\n\nSection Fields.\n\nVariable F : field.\n\nLemma inv0 : 0^-1 = 0 :> F.\nProof. exact: Field.inv0. Qed.\n\nLemma invL : forall x : F, x <> 0 -> x^-1 * x = 1.\nProof. exact: Field.unitPL. Qed.\n\nLemma mulKr : forall x : F, x <> 0 -> cancel (mulr x) (mulr x^-1).\nProof. by move=> x Hx y; rewrite mulA (invL Hx) mul1r. Qed.\n\nLemma invR : forall x : F, x <> 0 -> x * x^-1 = 1.\nProof. move=> x; rewrite mulC; exact: invL. Qed.\n\nLemma mulrK : forall x : F, x <> 0 -> cancel (mulrr x) (mulrr x^-1).\nProof. by move=> x Hx y; rewrite -mulA (invR Hx) mulr1. Qed.\n\nLemma mulKrV : forall x : F, x <> 0 -> cancel (mulr x^-1) (mulr x).\nProof. by move=> x Hx y; rewrite mulA (invR Hx) mul1r. Qed.\n\nLemma mulrKV : forall x : F, x <> 0 -> cancel (mulrr x^-1) (mulrr x).\nProof. by move=> x Hx y; rewrite -mulA (invL Hx) mulr1. Qed.\n\nLemma inv_injR : forall x y : F, x <> 0 -> x * y = 1 -> y = x^-1.\nProof.\n (* {{{ *)\nmove=> x y Hx.\nmove/(congr1 (fun k => x^-1 * k)).\nby rewrite mulA invL // mul1r mulr1.\n (* }}} *)\nQed.\n\nLemma inv_injL : forall x y : F, x <> 0 -> y * x = 1 -> y = x^-1.\nProof.  move=> x y; rewrite mulC; exact: inv_injR. Qed.\n\nLemma nzP : 1 <> 0 :> F.\nProof. exact: Field.nzP. Qed.\n\nLemma opp1nz : -(1) != 0 :> F.\nProof. \n (* {{{ *)\napply/eqP.\nmove/(congr1 (fun x => x * -(1))).\nrewrite mul_opp1_opp1 mul0r.\nexact: nzP.\n (* }}} *)\nQed.\n\nLemma inv1 : 1^-1 = 1 :> F.\nProof. symmetry; apply: inv_injL; first exact: nzP; by rewrite mulr1. Qed.\n\nLemma opp_inv : forall x : F, x <> 0 -> (- x)^-1 = -(x ^-1).\nProof.\n (* {{{ *)\nmove=> x Hx.\nsymmetry.\napply: inv_injR.\n  move=> H.\n  by rewrite -(opp_opp x) H opp0 in Hx.\nby rewrite mul_opp_opp invR.\n (* }}} *)\nQed.\n\nLemma add_inv0 : forall x y : F, x <> 0 -> y <> 0 -> x + y = 0 -> x ^-1 + y ^-1 = 0.\nProof.\n (* {{{ *)\nmove=> x y Hx Hy Hxy.\nmove/(congr1 (fun k => - x + k)): Hxy.\nrewrite addA oppL addr0 add0r => ->.\nrewrite opp_inv => //.\nby rewrite oppR.\n (* }}} *)\nQed.\n\nEnd Fields.\n\n\n(** Subrings *)\nSection Sub_ring.\n\nVariable R : ring.\n\nStructure subring : Type := Subring {\n  srbase :> set R;\n  zeroP : srbase 0;\n  oneP : srbase 1;\n  addP : forall x y : R, srbase x -> srbase y -> srbase (x + y);\n  mulP : forall x y : R, srbase x -> srbase y -> srbase (x * y);\n  oppP : forall x : R, srbase x -> srbase (- x)\n}.\n\nLemma Subring_ext : forall H K : subring, srbase H = srbase K -> H = K.\nProof.\n (* {{{ *)\nmove=> [H1 H2 H3 H4 H5 H6] [K1 K2 K3 K4 K5 K6].\nrewrite /= => H.\nrewrite H in H2 H3 H4 H5 H6 *.\ncongr Subring;  by apply: proof_irrelevance.\n (* }}} *)\nQed.\n\nDefinition ring_to_subring : subring.\nexists (fun (x:R) => true) => //. \nDefined.\n\nVariable S : subring.\n\nNotation Sty := (sub_eqType S).\n\nDefinition sadd : Sty -> Sty -> Sty.\n (* {{{ *)\nmove=> x y.\nexists (val x + val y).\nabstract(apply: addP; exact: valP).\n (* }}} *)\nDefined.\n\nDefinition smul : Sty -> Sty -> Sty.\n (* {{{ *)\nmove=> x y.\nexists (val x * val y).\nabstract(apply: mulP; exact: valP).\n (* }}} *)\nDefined.\n\nDefinition sopp : Sty -> Sty.\n (* {{{ *)\nmove=> x.\nexists (- val x).\nabstract(apply: oppP; exact: valP).\n (* }}} *)\nDefined.\n\nDefinition szero := EqSig _ 0 (@zeroP S).\n\nDefinition sone := EqSig _ 1 (@oneP S).\n\nLemma subring_axioms : ring_axioms sadd smul sopp szero sone.\nProof.\n (* {{{ *)\n\nsplit; move=> H *; apply: val_inj => /=;\n[exact: addC |\n exact: addA |\n exact: addr0 |\n exact: oppL |\n exact: mulA |\n exact: distPM |\n exact: distMP |\n exact: mul1r |\n exact: mulr1 |\n exact: mulC].\n\n (* }}} *)\nQed.\n\nDefinition subring_to_ring := Ring.Ring subring_axioms.\n\nLemma subring_addl : forall x y, S x -> S (x + y) -> S y.\nProof.\n (* {{{ *)\nmove=> x y Hx Hxy.\nmove: (oppP Hx) => Hx'.\nmove: (addP Hx' Hxy).\nby rewrite addA oppL add0r.\n (* }}} *)\nQed.\n\nLemma subring_addr : forall x y, S y -> S (x + y) -> S x.\nProof. by move=> x y Hy; rewrite addC; apply: subring_addl. Qed.\n\nLemma subr_m1 : S (- (1:R)).\nProof. apply: oppP. exact: oneP. Qed.\n\nEnd Sub_ring.\n\nCoercion ring_to_subring : ring >-> subring.\n\n(** Subdomain *)\nSection SubDomain.\n\nVariable R : domain.\nVariable S : subring R.\n\nDefinition subring_to_domain : domain.\n (* {{{ *)\n\nexists (subring_to_ring S).\nabstract(\n  move=> x1 x2 [H];\n  (case: {H}(integ H) => H; first by (left; apply: val_inj));\n  by right;apply: val_inj).\n\n (* }}} *)\nDefined.\n\nEnd SubDomain.\n\n(** Subfields *)\n\nSection Sub_field.\n\nVariable F : field.\n\nStructure subfield : Type := Subfield {\n  sfbase :> subring F;\n  invP : forall x : F, sfbase x -> sfbase (invf x)\n}.\n\nLemma Subfield_ext : forall H K : subfield, srbase H = srbase K -> H = K.\nProof.\n (* {{{ *)\nmove=> [[H1 H2 H3 H4 H5] H6 H7] [[K1 K2 K3 K4 K5] K6 K7] /= H.\nrewrite {H1} H in H2 H3 H4 H5 H6 H7 *.\nhave -> : H2 = K2 by apply: proof_irrelevance.\nhave -> : H3 = K3 by apply: proof_irrelevance.\nhave -> : H4 = K4 by apply: proof_irrelevance.\nhave -> : H5 = K5 by apply: proof_irrelevance.\nhave -> : H6 = K6 by apply: proof_irrelevance.\ncongr Subfield.\nby apply: proof_irrelevance.\n (* }}} *)\nQed.\n\nDefinition field_to_subfield : subfield.\nexists (ring_to_subring F) => //.\nDefined.\n\nVariable S : subfield.\n\nNotation Fty := (sub_eqType S).\n\nDefinition sinv : Fty -> Fty.\n (* {{{ *)\nmove=> x.\nexists ((val x)^-1).\nabstract(apply: invP; exact: valP).\n (* }}} *)\nDefined.\n\nDefinition subfield_to_field : field.\n (* {{{ *)\nexists (subring_to_domain S) sinv.\n  abstract(\n  move=> [x Hx] H;\n  apply: val_inj => /=;\n  apply: invL => H0;\n  rewrite H0 in Hx H;\n  (suffices: (EqSig S 0 Hx = (@szero _ _)) by done);\n  by apply: val_inj).\nabstract(move=> [H]; by move/nzP: H).\nabstract(\nrewrite /sinv;\napply: val_inj => /=;\nexact: inv0).\n (* }}} *)\nDefined.\n\nEnd Sub_field.\n\nCoercion field_to_subfield : field >-> subfield.\n\n(** Ideals *)\n\nSection Ideal.\n\nVariable U : ring.\nVariable R : subring U.\n\nStructure ideal : Type := Ideal {\n  idbase :> set U;\n  id_ss : sub_set idbase R;\n  id0 : idbase 0;\n  id_add : forall x y : U, idbase x -> idbase y -> idbase (x + y);\n  idPL : forall x y : U, idbase x -> R y -> idbase (x * y);\n  idPR : forall x y : U, R x -> idbase y -> idbase (x * y)\n}.\n\nLemma id_opp : forall (I:ideal) x, I x -> I (- x).\nProof.  by move=> I x Hx; rewrite -mul_opp1r idPR // subr_m1. Qed.\n\nDefinition ring_to_ideal : ideal.\n (* {{{ *)\nexists R => //.\n- exact: zeroP.\n- exact: addP.\n- exact: mulP.\n- exact: mulP.\n (* }}} *)\nDefined.\n\nEnd Ideal.\n\nCoercion ring_to_ideal : subring >-> ideal.\n\nSection Ideal0.\n\nVariable U : ring.\nVariable R : subring U.\n\nLemma ideq : forall (I J : ideal R), (forall x, I x = J x) -> I = J.\nProof.\n (* {{{ *)\n\nmove=> [I a1 a2 a3 a4 a5] [J b1 b2 b3 b4 b5] /= H.\nrewrite (weak_ext H) in a1 a2 a3 a4 a5 *.\ncongr Ideal; by apply: proof_irrelevance.\n\n (* }}} *)\nQed.\n\nLemma idbase_inj : forall I J : ideal R, (idbase I = idbase J) -> I = J.\nProof.\n (* {{{ *)\n\nmove=> I J H.\napply: ideq.\nby rewrite H.\n\n (* }}} *)\nQed.\n\nDefinition zero_ideal : ideal R.\n (* {{{ *)\nexists (fun x => x == 0 :> U).\n- abstract(\n  move=> x;\n  move/eqP => ->;\n  exact: zeroP).\n- abstract(exact: eq_refl).\n- abstract(by move=> x y;do 2 move/eqP => ->; rewrite addr0).\n- abstract(by move=> x y; move/eqP => ->; rewrite mul0r).\nabstract(\nmove=> x y Hx;\nmove/eqP => ->; \nby rewrite mulr0).\n (* }}} *)\nDefined.\n\nDefinition maximal_ideal (I : ideal R) := \n  I <> R /\\  \n  forall J : ideal R, sub_set I J -> J = I \\/ J = R.\n\nInductive not_maximal_ideal (I : ideal R) : Prop :=  \n  | Not_maximal0 : I = R -> not_maximal_ideal I\n  | Not_maximal1 (J : ideal R) : \n    sub_set I J -> J <> I -> J <> R -> not_maximal_ideal I.\n\nLemma not_maximalP : forall I, ~ (maximal_ideal I) -> not_maximal_ideal I.\nProof.\n (* {{{ *)\nmove=> I.\nmove/not_and_or => [|].\n  left; by apply: NNPP.\nmove/(not_all_ex_not _ (fun x => _)) => [K HK].\nmove: (imply_to_and _ _ HK) => [H1 H2].\nmove/not_or_and: H2 => [H2 H3].\nby apply: (@Not_maximal1 I K).\n (* }}} *)\nQed.\n\nEnd Ideal0.\n\nNotation \"0\" := (zero_ideal _) : ideal_scope.\nDelimit Scope ideal_scope with Id.\n\nSection Ideal1.\n\nOpen Scope ring_scope.\nOpen Scope ideal_scope.\n\nVariable U : ring.\nVariable R : subring U.\n\nHint Resolve id0 id_add idPL idPR mulP oneP zeroP addP.\n\nDefinition ideal_of_elem (a : U) : ideal R.\n (* {{{ *)\nmove/(insub R)=> [[a Ha]|]; last exact: 0.\nexists (fun x => Pb (exists x', R x' /\\ x = x' * a )).\n- abstract(\n  move=> x /=;\n  move/PbP => [y [Hy ->]];\n  auto).\n- abstract(by apply/PbP; exists (0:U)%R; rewrite mul0r; auto).\n- abstract(move=> x y;move/PbP => [x' [Hx' ->]]; move/PbP => [y' [Hy' ->]];\n  rewrite -distPM; apply/PbP; exists (x' + y'); auto).\n- abstract(move=> x y; move/PbP => [x' [Hx' ->]] Hy; apply/PbP; exists (x' * y);\n  rewrite -mulA [a * _]mulC mulA; auto).\nabstract(move=> x y Hx; move/PbP => [x' [Hx' ->]]; apply/PbP; exists (x * x');\nrewrite mulA; auto).\n  (* }}} *)\nDefined.\n\nDefinition srunit u := exists u', R u' /\\ u * u' = 1. \n\nLemma ideal_unit : forall a, R a -> srunit a -> ideal_of_elem a = R.\nProof.\n (* {{{ *)\nmove=> a Ha [u' [Hu Hu']].\napply: ideq => x /=.\nrewrite /ideal_of_elem /=.\ncase: insubP => [[_ _] /= _ ->|]; last by rewrite Ha.\napply/idP/idP.\n  by move/PbP => [y [Hy ->]]; auto.\nmove=> H.\napply/PbP.\nexists (u' * x).\nsplit; auto.\nrewrite -mulA mulrCA.\nrewrite mulC in Hu'.\nby rewrite Hu' mulr1.\n (* }}} *)\nQed.\n\nLemma unit_ideal : forall u, R u -> ideal_of_elem u = R -> srunit u.\nProof.\n (* {{{ *)\n\nmove=> u Hu.\nmove/(congr1 (fun x => idbase x (1:U))).\nrewrite /ideal_of_elem /ring_to_ideal /=.\ncase: insubP => [[_ _] /= _ ->|].\n  move/PbP.\n  rewrite oneP => [[x' [Hx' Hx0]]].\n  exists x'.\n  by rewrite mulC; split.\nby move/negP.\n\n (* }}} *)\nQed.\n\nEnd Ideal1.\n\nPrenex Implicits ideal_of_elem.\n\n(** Homomorphisms *)\n\nSection Homo.\n\nVariable R S : ring.\nVariable R' : subring R.\nVariable S' : subring S.\n\nStructure homo (h : R -> S) : Prop := Homo {\n  homoP : forall x, R' x -> S' (h x);\n  homoAddP : forall x y, R' x -> R' y -> h (x + y) = h x + h y;\n  homoMulP : forall x y, R' x -> R' y -> h (x * y) = h x * h y;\n  homoJunk : forall x, ~ (R' x) -> h x = 0\n}.\n\nStructure iso (h : R -> S) : Prop := Iso {\n  isobase :> homo h;\n  imonoP : forall x y, R' x -> R' y -> h x = h y -> x = y;\n  iontoP : surj R' S' h\n}.\n\nDefinition isomorphic := exists h, iso h.\n\nEnd Homo.\n  \nDefinition endo R R' := @homo R R R' R'.\nDefinition auto R R' := @iso R R R' R'.\n\nPrenex Implicits auto.\n\nSection Homo0.\n\nVariable R S : ring.\nVariable R' : subring R.\nVariable S' : subring S.\nVariable s : R -> S.\n\nLemma homo0 : homo R' S' s -> s 0 = 0.\nProof.\n (* {{{ *)\n\nmove=> Hs.\napply: (@addr_injl _ (s 0)).\nrewrite addr0 -(homoAddP Hs); try exact: zeroP.\nby rewrite addr0.\n\n (* }}} *)\nQed.\n\nLemma homoOpp : homo R' S' s -> forall x, R' x -> s (- x) = - (s x).\nProof.\n (* {{{ *)\nmove=> Hs x Hx.\napply: (@addr_injl _ (s x)).\nrewrite oppR -(homoAddP Hs) //.\n  by rewrite oppR homo0.\nexact: oppP.\n (* }}} *)\nQed.\n\nDefinition kernel := fun x => R' x && (s x == 0).\n\nDefinition ker_ideal : homo R' S' s -> ideal R'.\n (* {{{ *)\n\nmove=> Hs.\nexists kernel.\n- abstract(by move=> x; move/andP; firstorder).\n- by rewrite /kernel homo0 // eq_refl andbT zeroP.\n- abstract(\n  move: (Hs) => [H1 H2 H3 H4];\n  move=> x y;\n  move/andP => [H5 H6];\n  move/eqP: H6 => H6;\n  move/andP => [H7 H8];\n  move/eqP: H8 => H8;\n  by rewrite /kernel H2 //= H6 H8 addr0 addP /=).\n- abstract(\n  move: (Hs) => [H1 H2 H3 H4];\n  move=> x y;\n  move/andP => [H5 H6];\n  move/eqP: H6 => H6;\n  move=> H7;\n  by rewrite /kernel H3 //= H6 mulP //= mul0r).\n- move: (Hs) => [H1 H2 H3 H4].\n  move=> x y Hx. \n  move/andP => [H5 H6].\n  move/eqP: H6 => H6.\n  rewrite /kernel.\n  by rewrite mulP //= H3 //= H6 mulr0.\n\n (* }}} *)\nDefined.\n\nEnd Homo0.\n\nPrenex Implicits kernel.\n\n(** Isomorphisms *)\n\nSection Iso.\n\nVariable R S : ring.\nVariable R' : subring R.\nVariable S' : subring S.\nVariable i : R -> S.\nHypothesis Hi : iso R' S' i.\n\n(* -------------------------------  inverse  -------------------------------- *)\n\nStructure iso_inv_spec (i' : S -> R) : Prop := IIS {\n  ii_closed : forall x, S' x -> R' (i' x);\n  ii_inv1 : forall x, R' x -> i' (i x) = x;\n  ii_inv2 : forall y, S' y -> i (i' y) = y;\n  ii_junk : forall y, ~ (S' y) -> i' y = 0\n}.\n\nDefinition iso_inv y := if S' y then epsilon (inhabits 0) (fun x : R => R' x /\\ i x = y) else 0.\n\nLemma iso_invP : iso_inv_spec iso_inv.\nProof.\n (* {{{ *)\nsplit.\n- move=> x Hx; rewrite /iso_inv.\n  case H : (S' x).\n    move: (@epsilon_spec _ (inhabits 0) (fun y => R' y /\\ i y = x)).\n    apply: antsE. \n      move: (iontoP Hi Hx) => [y [Hy Hy']].\n      by exists y; split.\n    by move => [H1 H2].\n  exact: zeroP.\n- move=> x Hx; rewrite /iso_inv.\n  have ->: (S' (i x)) by apply: (homoP Hi) ;eauto.\n  move: (@epsilon_spec _ (inhabits 0) (fun y => R' y /\\ i y = i x)).\n  apply: antsE; first by exists x;split.\n  move => [H1 H2].\n  by move: (imonoP Hi H1 Hx H2) => ->.\n- move=> y Hy; rewrite /iso_inv Hy.\n  move: (@epsilon_spec _ (inhabits 0) (fun x => R' x /\\ i x = y)).\n  apply: antsE. \n    move: (iontoP Hi Hy) => [y1 [Hy1 Hy1']].\n    by exists y1; split.\n  by move => [H1 H2].\nby rewrite /iso_inv; move=> y Hy; move/eqP: Hy; rewrite neq_true; move/eqP => ->.\n (* }}} *)\nQed.\n\nHint Resolve oneP addP mulP oppP homoP homoAddP homoMulP ii_closed.\n\nLemma iso_inv_homo : homo S' R' iso_inv.\nProof.\n (* {{{ *)\nmove: iso_invP => [H1 H2 H3 H4].\nsplit; auto.\n- move=> x y Hx Hy.\n  apply: (imonoP Hi); auto.\n  rewrite H3;auto.\n  rewrite (homoAddP Hi);auto.\n  by rewrite !H3; auto.\n- move=> x y Hx Hy.\n  apply: (imonoP Hi); auto.\n  rewrite H3;auto.\n  rewrite (homoMulP Hi);auto.\n  by rewrite !H3; auto.\n (* }}} *)\nQed.\n\nLemma iso_inv_iso : iso S' R' iso_inv.\nProof.\n (* {{{ *)\nmove: iso_invP => [H1 H2 H3 H4].\nsplit; first by exact: iso_inv_homo.\n  move=> x y Hx Hy.\n  move/(congr1 i).\n  by rewrite !H3;auto.\nmove=> y Hy.\nexists (i y).\nsplit.\n  by apply: (homoP Hi).\nby symmetry; auto.\n (* }}} *)\nQed.\n\nLemma iso1 : i 1 = 1.\nProof.\n (* {{{ *)\nrewrite -(mul1r (i 1)).\nrewrite -{1}(@ii_inv2 _ iso_invP 1);auto.\nrewrite -(homoMulP Hi); auto.\n  by rewrite mulr1 (ii_inv2 iso_invP); auto.\nby apply: (ii_closed iso_invP); auto.\n (* }}} *)\nQed.\n\nEnd Iso.\n\nSection Iso0.\n\nVariable F K : field.\nVariable F' : subfield F.\nVariable K' : subfield K.\nVariable i : F -> K.\nHypothesis Hi : iso F' K' i.\n\nLemma inv_iso : forall x, F' x -> x <> 0 -> i (x^-1) = (i x)^-1.\nProof.\n (* {{{ *)\nmove=> x Hx H0.\nhave H0' : i x <> 0.\n  move/(congr1 (iso_inv F' K' i)).\n  rewrite (ii_inv1 (iso_invP Hi)); auto.\n  by rewrite (homo0 (iso_inv_homo Hi)).\napply: (@mulr_injl _ (i x)) => //.\nrewrite invR; auto.\nrewrite -(homoMulP Hi); auto.\n  rewrite invR;auto.\n  exact: (iso1 Hi).\nby apply: invP.\n (* }}} *)\nQed.\n\nEnd Iso0.\n\nSection Iso1.\n\nVariable R S : ring.\nVariable R' : subring R.\nVariable S' : subring S.\nVariable phi : R -> S.\nHypothesis phiP : homo R' S' phi.\nHypothesis ontoP : surj R' S' phi.\nHypothesis phiP' : kernel R' phi = set1 0.\n\nHint Resolve oppP addP.\n\nLemma homo_iso : iso R' S' phi.\nProof.\n (* {{{ *)\n\nsplit => //.\nmove=> x y Hx Hy.\nmove/(congr1 (addrr (- phi y))).\nrewrite oppR -(homoOpp phiP Hy) -(homoAddP phiP); auto.\nmove=> H.\nmove/(congr1 (fun f => f (x - y))): phiP'.\nrewrite /kernel.\nmove/andP.\ncase H' : (_ == _).\n  move=> _.\n  move/eqP: H'.\n  move/(congr1 (addrr y)).\n  rewrite -addA oppL addr0 add0r.\n  by move=> ->.\nrewrite H.\nmove/not_and_or => [|].\n  case; auto.\nby rewrite eq_refl; move/negP.\n\n (* }}} *)\nQed.\n\nEnd Iso1.\n\n\n\n\n\n\n", "meta": {"author": "kallol26", "repo": "coq-galois-theory", "sha": "4fff4d1b919d79f4dc4ba5afa126aa995e577489", "save_path": "github-repos/coq/kallol26-coq-galois-theory", "path": "github-repos/coq/kallol26-coq-galois-theory/coq-galois-theory-4fff4d1b919d79f4dc4ba5afa126aa995e577489/src/ring.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587668, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.6888837161976764}}
{"text": "Require Import Coq.Bool.Bool.\n\nLtac reduce_orb_step :=\n  match goal with\n  | [ |- context [?X || ?Y || (?Z || ?Y)]] =>\n    rewrite orb_comm with Z Y\n  | [ |- context [?X || ?Y || (?Y || ?Z)]] =>\n    rewrite orb_assoc with (X||Y) Y Z\n  | [ |- context [?X || ?Y || ?Y]] =>\n    rewrite <- orb_assoc with X Y Y\n  | [ |- context [?Y || ?Y]] =>\n    rewrite orb_diag\n  | [|- context [?X || ?Y || ?Z = ?X || ?Z || ?Y]] =>\n    rewrite <- orb_assoc with X Z Y;\n    rewrite orb_comm with Z Y;\n    rewrite orb_assoc with X Y Z\n  end.\n\nLtac reduce_orb := repeat (try reduce_orb_step).\n\nExample example_reduce_orb_step: forall (a b c: bool),\n  a || b || (c || b) = a || b || c.\nProof.\nintros.\nreduce_orb_step.\nreduce_orb_step.\nreduce_orb_step.\nreduce_orb_step.\nreflexivity.\nQed.\n\nExample example_reduce_orb: forall (a b c: bool),\n  a || b || (c || b) = a || b || c.\nProof.\nintros.\nreduce_orb.\nreflexivity.\nQed.\n\n(* TODO: Good First Issue\n   Add more examples of using reduce_orb_step, \n   by creating theorems that are proved using reduce_orb_step\n   The theorem names should start with example_\n*)", "meta": {"author": "awalterschulze", "repo": "regex-reexamined-coq", "sha": "71e4a82790f269814fc3eb33e9e9cd1b49b559c5", "save_path": "github-repos/coq/awalterschulze-regex-reexamined-coq", "path": "github-repos/coq/awalterschulze-regex-reexamined-coq/regex-reexamined-coq-71e4a82790f269814fc3eb33e9e9cd1b49b559c5/src/CoqStock/reduce_orb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891261650247, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.6886820223786365}}
{"text": "(* infotheo (c) AIST. R. Affeldt, M. Hagiwara, J. Senizergues. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq div.\nFrom mathcomp Require Import choice fintype finfun bigop prime binomial ssralg.\nFrom mathcomp Require Import finset fingroup finalg matrix.\nRequire Import Reals Fourier.\nRequire Import Reals_ext ssrR logb Rbigop proba channel.\n\n(** * Definition of a channel code *)\n\nReserved Notation \"e( W , c )\" (at level 50).\nReserved Notation \"echa( W , c )\" (at level 50).\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope proba_scope.\nLocal Open Scope channel_scope.\n\nSection code_definition.\n\n(** A code is an index set\n   (or set of codewords) M with an encoding and a decoding function. *)\n\nVariables A B M : finType.\nVariable n : nat.\n\nLocal Open Scope ring_scope.\n\nDefinition encT := {ffun M -> 'rV[A]_n}.\nDefinition decT := {ffun 'rV[B]_n -> option M}.\n\nRecord code := mkCode { enc : encT ; dec : decT }.\n\nDefinition CodeRate (c : code) := (log (INR #| M |) / INR n)%R.\n\n(** Probability of error given that the codeword m was sent: *)\n\nDefinition preimC (phi : decT) m := ~: (phi @^-1: xpred1 (Some m)).\n\nDefinition ErrRateCond (W : `Ch_1(A, B)) c m :=\n  Pr (W ``(| enc c m)) (preimC (dec c) m).\n\nLocal Notation \"e( W , c )\" := (ErrRateCond W c) (at level 50).\n\n(** Average probability of error: *)\n\nDefinition CodeErrRate (W : `Ch_1(A, B)) c :=\n  (1 / INR #| M | * \\rsum_(m in M) e(W, c) m)%R.\n\nLocal Notation \"echa( W , c )\" := (CodeErrRate W c) (at level 50).\n\nLemma echa_ge0 (HM : (0 < #| M |)%nat) W (c : code) : 0 <= echa(W , c).\nProof.\napply mulR_ge0.\n- apply divR_ge0; by [fourier | exact/ltR0n].\n- apply: rsumr_ge0 => ? _; apply: rsumr_ge0 => ? _; exact: DMC_ge0.\nQed.\n\nLemma echa1 (HM : (0 < #| M |)%nat) W (c : code) : echa(W , c) <= 1.\nProof.\nrewrite /CodeErrRate div1R.\napply (@leR_pmul2l (INR #|M|)); first exact/ltR0n.\nrewrite mulRA mulRV ?INR_eq0' -?lt0n // mul1R -iter_addR -big_const.\napply: ler_rsum => m _; exact: Pr_1.\nQed.\n\nEnd code_definition.\n\nNotation \"e( W , c )\" := (ErrRateCond W c) : channel_code_scope.\nNotation \"echa( W , c )\" := (CodeErrRate W c) : channel_code_scope.\n\n(** Definition of the set of (code) rates (unit: bits per transmission): *)\n\nRecord CodeRateType := mkCodeRateType {\n  rate :> R ;\n  _ : exists n d, (0 < n)%nat /\\ (0 < d)%nat /\\ rate = log (INR n) / INR d }.\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/channel_code.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.6886820175378795}}
{"text": "Require Import Classical.\n\nInductive Ordinal : Type :=\n  | ordS : Ordinal -> Ordinal\n  | ord_sup: forall {I:Type}, (I->Ordinal) -> Ordinal.\n\n(*\nFixpoint ord_le (alpha beta:Ordinal) : Prop :=\n  match alpha with\n  | ordS alpha => \n                  (fix gt_alpha (beta:Ordinal) : Prop :=\n                  match beta with\n                  | ordS beta => ord_le alpha beta\n                  | ord_sup J beta => exists j:J,\n                    gt_alpha (beta j)\n                  end) beta\n  | ord_sup I0 alpha => forall i:I0, ord_le (alpha i) beta\n  end.\n*)\n\nInductive ord_le : Ordinal -> Ordinal -> Prop :=\n  | ord_le_respects_succ: forall alpha beta:Ordinal,\n    ord_le alpha beta -> ord_le (ordS alpha) (ordS beta)\n  | ord_le_S_sup: forall (alpha:Ordinal) (J:Type)\n    (beta:J->Ordinal) (j:J), ord_le (ordS alpha) (beta j) ->\n    ord_le (ordS alpha) (ord_sup beta)\n  | ord_sup_minimal: forall (I:Type) (alpha:I->Ordinal)\n    (beta:Ordinal), (forall i:I, ord_le (alpha i) beta) ->\n                    ord_le (ord_sup alpha) beta.\n\nDefinition ord_lt (alpha beta:Ordinal) :=\n  ord_le (ordS alpha) beta.\nDefinition ord_eq (alpha beta:Ordinal) :=\n  ord_le alpha beta /\\ ord_le beta alpha.\nDefinition ord_ge (alpha beta:Ordinal) :=\n  ord_le beta alpha.\nDefinition ord_gt (alpha beta:Ordinal) :=\n  ord_lt beta alpha.\n\nDelimit Scope ordinal_scope with Ordinal.\nOpen Scope ordinal_scope.\nNotation \"alpha < beta\" := (ord_lt alpha beta) : ordinal_scope.\nNotation \"alpha <= beta\" := (ord_le alpha beta) : ordinal_scope.\nNotation \"alpha == beta\" := (ord_eq alpha beta)\n  (at level 70) : ordinal_scope.\nNotation \"alpha > beta\" := (ord_gt alpha beta) : ordinal_scope.\nNotation \"alpha >= beta\" := (ord_ge alpha beta) : ordinal_scope.\n\nLemma ord_le_respects_succ_converse: forall alpha beta:Ordinal,\n  ordS alpha <= ordS beta -> alpha <= beta.\nProof.\nintros.\ninversion_clear H.\nassumption.\nQed.\n\nLemma ord_le_S_sup_converse: forall (alpha:Ordinal)\n  (J:Type) (beta:J->Ordinal), ordS alpha <= ord_sup beta ->\n  exists j:J, ordS alpha <= beta j.\nProof.\nintros.\ninversion H.\nexists j.\nassumption.\nQed.\n\nLemma ord_sup_minimal_converse: forall (I:Type)\n  (alpha:I->Ordinal) (beta:Ordinal),\n  ord_sup alpha <= beta -> forall i:I, alpha i <= beta.\nProof.\nintros.\ninversion H.\nRequire Import Eqdep.\napply inj_pair2 in H2.\ndestruct H2.\napply H3.\nQed.\n\nLemma ord_le_trans: forall alpha beta gamma:Ordinal,\n  alpha <= beta -> beta <= gamma -> alpha <= gamma.\nProof.\ninduction alpha.\ninduction beta.\ninduction gamma.\nintros.\napply ord_le_respects_succ.\napply IHalpha with beta.\napply ord_le_respects_succ_converse; trivial.\napply ord_le_respects_succ_converse; trivial.\nintros.\napply ord_le_S_sup_converse in H1.\ndestruct H1 as [i].\napply ord_le_S_sup with i.\napply H; trivial.\nintros.\npose proof (ord_sup_minimal_converse _ _ _ H1).\napply ord_le_S_sup_converse in H0.\ndestruct H0 as [i].\napply H with i; trivial.\nintros.\npose proof (ord_sup_minimal_converse _ _ _ H0).\nconstructor.\nintro.\napply H with beta; trivial.\nQed.\n\nLemma ord_le_sup: forall (I:Type) (alpha:I->Ordinal) (i:I),\n  alpha i <= ord_sup alpha.\nProof.\nassert (forall beta:Ordinal, beta <= beta /\\\n  forall (I:Type) (alpha:I->Ordinal) (i:I),\n  beta <= alpha i -> beta <= ord_sup alpha).\ninduction beta.\ndestruct IHbeta.\nsplit.\napply ord_le_respects_succ; trivial.\nintros.\napply ord_le_S_sup with i.\ntrivial.\nsplit.\napply ord_sup_minimal.\nintro.\ndestruct (H i).\napply H1 with i; trivial.\nintros J alpha j ?.\napply ord_sup_minimal.\nintro.\ndestruct (H i).\napply H2 with j.\napply ord_le_trans with (ord_sup o).\napply H2 with i; trivial.\ntrivial.\n\nintros.\ndestruct (H (alpha i)).\napply H1 with i; trivial.\nQed.\n\nLemma ord_le_refl: forall alpha:Ordinal, alpha <= alpha.\nProof.\ninduction alpha.\napply ord_le_respects_succ; trivial.\napply ord_sup_minimal.\napply ord_le_sup.\nQed.\n\nLemma ord_le_S: forall alpha:Ordinal, alpha <= ordS alpha.\nProof.\ninduction alpha.\napply ord_le_respects_succ; trivial.\napply ord_sup_minimal.\nintro.\napply ord_le_trans with (ordS (o i)).\napply H.\napply ord_le_respects_succ.\napply ord_le_sup.\nQed.\n\nLemma ord_lt_le: forall alpha beta:Ordinal,\n  alpha < beta -> alpha <= beta.\nProof.\nintros.\napply ord_le_trans with (ordS alpha); trivial.\napply ord_le_S.\nQed.\n\nLemma ord_lt_le_trans: forall alpha beta gamma:Ordinal,\n  alpha < beta -> beta <= gamma -> alpha < gamma.\nProof.\nintros.\napply ord_le_trans with beta; trivial.\nQed.\n\nLemma ord_le_lt_trans: forall alpha beta gamma:Ordinal,\n  alpha <= beta -> beta < gamma -> alpha < gamma.\nProof.\nintros.\napply ord_le_trans with (ordS beta); trivial.\napply ord_le_respects_succ; trivial.\nQed.\n\nLemma ord_lt_trans: forall alpha beta gamma:Ordinal,\n  alpha < beta -> beta < gamma -> alpha < gamma.\nProof.\nintros.\napply ord_lt_le_trans with beta; trivial;\n apply ord_lt_le; trivial.\nQed.\n\nLemma ord_lt_respects_succ: forall alpha beta:Ordinal,\n  alpha < beta -> ordS alpha < ordS beta.\nProof.\nintros.\napply ord_le_respects_succ; trivial.\nQed.\n\nLemma ord_total_order: forall alpha beta:Ordinal,\n  alpha < beta \\/ alpha == beta \\/ alpha > beta.\nProof.\ninduction alpha.\ninduction beta.\ndestruct (IHalpha beta) as [|[|]].\nleft; apply ord_lt_respects_succ; trivial.\nright; left.\nsplit.\napply ord_le_respects_succ; apply H.\napply ord_le_respects_succ; apply H.\nright; right.\napply ord_lt_respects_succ; trivial.\n\ndestruct (classic (exists i:I, ordS alpha < o i)).\ndestruct H0 as [i].\nleft.\napply ord_lt_le_trans with (o i); trivial.\napply ord_le_sup.\ndestruct (classic (exists i:I, ordS alpha == o i)).\ndestruct H1 as [i].\nright; left.\nsplit.\napply ord_le_trans with (o i).\napply H1.\napply ord_le_sup.\napply ord_sup_minimal.\nintro.\ndestruct (H i0) as [|[|]].\ncontradiction H0; exists i0; trivial.\napply H2.\napply ord_lt_le; trivial.\nassert (forall i:I, ordS alpha > o i).\nintros.\ndestruct (H i) as [|[|]].\ncontradiction H0; exists i; trivial.\ncontradiction H1; exists i; trivial.\ntrivial.\nright; right.\napply ord_le_lt_trans with alpha.\napply ord_sup_minimal.\nintro.\napply ord_le_respects_succ_converse.\napply H2.\napply ord_le_refl.\n\ninduction beta.\ncase (classic (exists i:I, o i > ordS beta)); intro.\ndestruct H0 as [i].\nright; right.\napply ord_lt_le_trans with (o i); trivial.\napply ord_le_sup.\ncase (classic (exists i:I, o i == ordS beta)); intro.\nright; left.\ndestruct H1 as [i].\nsplit.\napply ord_sup_minimal.\nintro j.\ndestruct (H j (ordS beta)) as [|[|]].\napply ord_lt_le; trivial.\napply H2.\ncontradiction H0; exists j; trivial.\napply ord_le_trans with (o i).\napply H1.\napply ord_le_sup.\nleft.\napply ord_le_respects_succ.\napply ord_sup_minimal.\nintro.\ndestruct (H i (ordS beta)) as [|[|]].\napply ord_le_respects_succ_converse; trivial.\ncontradiction H1; exists i; trivial.\ncontradiction H0; exists i; trivial.\n\ncase (classic (exists j:I0, ord_sup o < o0 j)); intro.\nleft.\ndestruct H1 as [j].\napply ord_lt_le_trans with (o0 j); trivial.\napply ord_le_sup.\ncase (classic (exists i:I, o i > ord_sup o0)); intro.\ndestruct H2 as [i].\nright; right.\napply ord_lt_le_trans with (o i); trivial.\napply ord_le_sup.\n\nright; left.\nsplit.\napply ord_sup_minimal; intro.\ndestruct (H i (ord_sup o0)) as [|[|]].\napply ord_lt_le; trivial.\napply H3.\ncontradiction H2; exists i; trivial.\napply ord_sup_minimal; intro j.\ndestruct (H0 j) as [|[|]].\ncontradiction H1; exists j; trivial.\napply H3.\napply ord_lt_le; trivial.\nQed.\n\nLemma ordinals_well_founded: well_founded ord_lt.\nProof.\nred; intro alpha.\ninduction alpha.\nconstructor.\nintros beta ?.\napply ord_le_respects_succ_converse in H.\nconstructor; intros gamma ?.\ndestruct IHalpha.\napply H1.\napply ord_lt_le_trans with beta; trivial.\n\nconstructor; intros alpha ?.\napply ord_le_S_sup_converse in H0.\ndestruct H0 as [j].\n\ndestruct (H j).\napply H1; trivial.\nQed.\n\nLemma ord_lt_irrefl: forall alpha:Ordinal, ~(alpha < alpha).\nProof.\nintro; red; intro.\nassert (forall beta:Ordinal, beta <> alpha).\nintro.\npose proof (ordinals_well_founded beta).\ninduction H0.\nred; intro.\nsymmetry in H2; destruct H2.\ncontradiction (H1 alpha H); trivial.\ncontradiction (H0 alpha); trivial.\nQed.\n\nInductive successor_ordinal : Ordinal->Prop :=\n  | intro_succ_ord: forall alpha:Ordinal,\n    successor_ordinal (ordS alpha)\n  | succ_ord_wd: forall alpha beta:Ordinal,\n    successor_ordinal alpha -> alpha == beta ->\n    successor_ordinal beta.\nInductive limit_ordinal : Ordinal->Prop :=\n  | intro_limit_ord: forall {I:Type} (alpha:I->Ordinal),\n    (forall i:I, exists j:I, alpha i < alpha j) ->\n    limit_ordinal (ord_sup alpha)\n  | limit_ord_wd: forall alpha beta:Ordinal,\n    limit_ordinal alpha -> alpha == beta ->\n    limit_ordinal beta.\n\nLemma ord_successor_or_limit: forall alpha:Ordinal,\n  successor_ordinal alpha \\/ limit_ordinal alpha.\nProof.\ninduction alpha.\nleft; constructor.\ndestruct (classic (forall i:I, exists j:I, o i < o j)).\nright; constructor; trivial.\ndestruct (not_all_ex_not _ _ H0) as [i].\nassert (forall j:I, o j <= o i).\nintro.\ndestruct (ord_total_order (o i) (o j)) as [|[|]].\ncontradiction H1; exists j; trivial.\napply H2.\napply ord_lt_le; trivial.\n\nassert (ord_sup o == o i).\nsplit.\napply ord_sup_minimal; trivial.\napply ord_le_sup.\ncase (H i); intro.\nleft; apply succ_ord_wd with (o i); trivial.\nsplit; apply H3.\nright.\napply limit_ord_wd with (o i); trivial.\nsplit; apply H3.\nQed.\n\nLemma successor_ordinal_not_limit: forall alpha:Ordinal,\n  successor_ordinal alpha -> ~ limit_ordinal alpha.\nProof.\nintros; red; intro.\ninduction H.\ninversion_clear H0.\ninduction H as [I beta|].\nassert (ord_sup beta <= alpha).\napply ord_sup_minimal.\nintro.\napply ord_le_respects_succ_converse.\ndestruct (H i) as [j].\napply ord_le_trans with (beta j); trivial.\napply ord_le_trans with (ord_sup beta).\napply ord_le_sup.\napply H1.\n\ncontradiction (ord_lt_irrefl alpha).\napply ord_le_trans with (ord_sup beta); trivial.\napply H1.\n\napply IHlimit_ordinal.\nsplit; apply ord_le_trans with beta;\n  (apply H0 || apply H1).\n\ncontradiction IHsuccessor_ordinal.\napply limit_ord_wd with beta; trivial.\nsplit; apply H1.\nQed.\n", "meta": {"author": "dschepler", "repo": "coq-zorns-lemma", "sha": "4ad354c50f73758c094f43da5fc0f2c6dd8e3da2", "save_path": "github-repos/coq/dschepler-coq-zorns-lemma", "path": "github-repos/coq/dschepler-coq-zorns-lemma/coq-zorns-lemma-4ad354c50f73758c094f43da5fc0f2c6dd8e3da2/Ordinals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.6886017836648817}}
{"text": "(*************************************************************************)\n(* Copyright (C) 2013 - 2015                                             *)\n(* Author C. Cohen                                                       *)\n(* DRAFT - PLEASE USE WITH CAUTION                                       *)\n(* License CeCILL-B                                                      *)\n(*************************************************************************)\n\nFrom mathcomp Require Import ssreflect ssrbool ssrnat eqtype ssrfun seq.\nFrom mathcomp Require Import choice  path finset finfun fintype bigop.\n\n(*****************************************************************************)\n(* This file provides a representation of finitely supported maps where      *)\n(* the keys K lie in an ordType and the values V in an arbitrary type.       *)\n(*                                                                           *)\n(*         {fset K} == finite sets of elements of K                          *)\n(*    {fmap K -> V} == finitely supported maps from K to V.                  *)\n(*                                                                           *)\n(* In the remainder, A and B are of type {fset K}.                           *)\n(* because of the coercion for {fset K} to Type, writing a : A makes sense   *)\n(*                                                                           *)\n(* The following notations are in the %fset scope                            *)\n(*            fset0 == the empty finite set                                  *)\n(*         [fset k] == the singleton finite set {k}                          *)\n(*          A `&` B == the intersection of A and B                           *)\n(*          A `|` B == the union of A and B                                  *)\n(*           a |` B == the union of singleton a and B                        *)\n(*          A `\\` B == the complement of B in A                              *)\n(*           A `\\ b == A without b                                           *)\n(* [disjoint A & B] := A `&` B == 0                                          *)\n(*     A `<=` B == A is a subset of B                                        *)\n(*     A `<` B == A is a proper subset of B                                  *)\n(*            #|`A| == cardinal of A                                         *)\n(*    fincl AsubB a == turns a : A  into an element of B                     *)\n(*                     using a proof AsubB of A \\fsubset B                   *)\n(*         fsub B A == turns A : {fset K} into a {set B}                     *)\n(*           f @` A == the image set of the collective predicate A by f.     *)\n(*      f @2`(A, B) == the image set of A x B by the binary function f.      *)\n(*                                                                           *)\n(*    [fset x : X | P] == the set of all x in X such that P is true          *)\n(*                        where P is a predicate on X                        *)\n(*  [fset x : X | P & Q] := [set x : X | P && Q].                            *)\n(* [fset x : K in A | P] == the set containing the x in A such that P is true*)\n(*                      this type P is a predicate on K                      *)\n(* [fset x : K in A | P & Q ] :=  [set x : K in A | P && Q].                 *)\n(* [fset x in A | P]     :=   [set x : _ in A | P].                          *)\n(* [fset x in A | P & Q ] :=  [set x : _ in A | P & Q].                      *)\n(*      fpowerset A == the powerset of A, has type {fset {fset K}}           *)\n(*                                                                           *)\n(*                                                                           *)\n(* [fset E | x in A] == the set of all the values of the expression E, for x *)\n(*                     drawn from the collective predicate A.                *)\n(* [fset E | x in A & P] == the set of values of E for x drawn from A, such  *)\n(*                     that P is true.                                       *)\n(* [fset E | x in A, y in B] == the set of values of E for x drawn from A and*)\n(*                     and y drawn from B; B may depend on x.                *)\n(* [fset E | x : T] == the set of all values of E, with x in type T.         *)\n(* [fset E | x : T & P] == the set of values of E for x : T s.t. P is true.  *)\n(* [fset E | x : T, y : U in B], [fset E | x : T, y : U in B & P],           *)\n(* [fset E | x : T, y : U], [fset E | x : T, y : U & P]                      *)\n(*            == type-ranging versions of the binary comprehensions.         *)\n(*  [fset E | x : T in A], [fset E | x in A, y], [fset E | x, y & P], etc.   *)\n(*            == typed and untyped variants of the comprehensions above.     *)\n(*               The types may be required as type inference processes E     *)\n(*               before considering A or B. Note that type casts in the      *)\n(*               binary comprehension must either be both present or absent  *)\n(*               and that there are no untyped variants for single-type      *)\n(*               comprehension as Coq parsing confuses [x | P] and [E | x].  *)\n(*                                                                           *)\n(* Operations on finmaps                                                     *)\n(* The following notations are in the %fmap scope                            *)\n(*                                                                           *)\n(*            domf f == finite set (of type {fset K}) of keys of f           *)\n(*          codomf f == finite set (of type {fset V}) of values of f         *)\n(*           k \\in f == k is a key of f                                      *)\n(*            [fmap] == the empty finite map                                 *)\n(* [fmap x : S => E] == the finmap defined by E on the support S             *)\n(*        f.[k <- v] == f extended with the mapping k -> v                   *)\n(*           f.[& A] == f restricted to A (intersected with domf f)          *)\n(*           f.[\\ A] == f.[& domf `\\` A]                                     *)\n(*                   := f where all the keys in A have been removed          *)\n(*           f.[~ k] := f.[\\ [fset k]                                        *)\n(*             f.[p] == returns v if p has type k \\in f, and k maps to v     *)\n(*           f.[? k] == returns Some v if k maps to v, otherwise None        *)\n(*             f + g == concatenation of f and g,                            *)\n(*                      the keys of g override the keys of f                 *)\n(*                                                                           *)\n(*****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nReserved Notation \"{fset K }\" (at level 0, format \"{fset  K }\").\nReserved Notation \"A `&` B\"  (at level 48, left associativity).\nReserved Notation \"A `|` B\" (at level 52, left associativity).\nReserved Notation \"a |` A\" (at level 52, left associativity).\nReserved Notation \"A `\\` B\" (at level 50, left associativity).\nReserved Notation \"A `\\ b\" (at level 50, left associativity).\n\nReserved Notation \"{fmap T }\" (at level 0, format \"{fmap  T }\").\nReserved Notation \"x .[ k <- v ]\"\n  (at level 2, k at level 200, v at level 200, format \"x .[ k  <-  v ]\").\nReserved Notation \"x .[~ k ]\" (at level 2, k at level 200, format \"x .[~  k ]\").\nReserved Notation \"x .[& k ]\" (at level 2, k at level 200, format \"x .[&  k ]\").\nReserved Notation \"x .[\\ k ]\" (at level 2, k at level 200, format \"x .[\\  k ]\").\nReserved Notation \"x .[? k ]\" (at level 2, k at level 200, format \"x .[?  k ]\").\nReserved Infix \"`~`\" (at level 52).\nReserved Notation \"[ 'fset' k ]\" (at level 0, k at level 99, format \"[ 'fset'  k ]\").\n\nReserved Notation \"[ 'fmap' E | k , kf , v <- f ]\"\n  (at level 0, E at level 99, k ident, kf ident, v ident,\n   format \"[ '[hv' 'fmap'  E '/ '  |  k ,  kf ,  v  <-  f ] ']'\").\nReserved Notation \"[ 'fmap' E | k , v <- f ]\"\n  (at level 0, E at level 99, k ident, v ident,\n   format \"[ '[hv' 'fmap'  E '/ '  |  k ,  v  <-  f ] ']'\").\nReserved Notation \"[ 'fmap' E | v <- f ]\"\n  (at level 0, E at level 99, v ident,\n   format \"[ '[hv' 'fmap'  E '/ '  |  v  <-  f ] ']'\").\n\nReserved Notation \"[ 'fmap' k kf 'in' A => E ]\"\n   (at level 0, E at level 99, k ident, kf ident,\n   format \"[ '[hv' 'fmap'  k  kf  'in'  A  =>  '/' E ] ']'\").\nReserved Notation \"[ 'fmap' k 'in' A => E ]\"\n   (at level 0, E at level 99, k ident,\n   format \"[ '[hv' 'fmap'  k  'in'  A  =>  '/' E ] ']'\").\n\nSection extra.\n\nLemma mem_remF (T : eqType) (s : seq T) x : uniq s -> x \\in rem x s = false.\nProof. by move=> us; rewrite mem_rem_uniq // inE eqxx. Qed.\n\nDefinition ffun0 (T : finType) (X : Type) : #|T| = 0 -> {ffun T -> X}.\nProof. by move=> /card0_eq T0; apply: finfun => t; move: (T0 t). Defined.\n\nDefinition oextract (T : Type) (o : option T) : o -> T :=\n  if o is Some t return o -> T then fun=> t else False_rect T \\o notF.\n\nLemma oextractE (T : Type) (x : T) (xP : Some x) : oextract xP = x.\nProof. by []. Qed.\n\nLemma Some_oextract T (x : option T) (x_ex : x) : Some (oextract x_ex) = x.\nProof. by case: x x_ex. Qed.\n\nDefinition ojoin T (x : option (option T)) :=\n  if x is Some y then y else None.\n\nLemma Some_ojoin T (x : option (option T)) : x -> Some (ojoin x) = x.\nProof. by case : x. Qed.\n\nLemma ojoinT T (x : option (option T)) : ojoin x -> x.\nProof. by case: x. Qed.\n\nEnd extra.\n\nSection ChoiceKeys.\n\nVariable (K : choiceType).\nImplicit Types (k : K) (ks : seq K).\n\nDefinition sort_keys (s : seq K) : seq K :=\n   choose [pred t : seq K | perm_eq (undup s) t] (undup s).\n\nFact sort_keys_uniq s : uniq (sort_keys s).\nProof.\nrewrite /sort_keys; set P := (X in choose X).\nhave : P (choose P (undup s)) by exact/chooseP/perm_eq_refl.\nby move=> /perm_eq_uniq <-; rewrite undup_uniq.\nQed.\n\nFact sort_keysE (s : seq K) : sort_keys s =i s.\nProof.\nrewrite /sort_keys; set P := (X in choose X) => x.\nhave : P (choose P (undup s)) by exact/chooseP/perm_eq_refl.\nby move=> /perm_eq_mem <-; rewrite mem_undup.\nQed.\nHint Resolve sort_keysE.\n\nLemma eq_sort_keys (s s' : seq K) :\n  s =i s' <-> sort_keys s = sort_keys s'.\nProof.\nsplit=> [eq_ss'|eq_ss' k]; last by rewrite -sort_keysE eq_ss' sort_keysE.\nrewrite /sort_keys; have peq_ss' : perm_eq (undup s) (undup s').\n  by apply: uniq_perm_eq; rewrite ?undup_uniq // => x; rewrite !mem_undup.\nrewrite (@choose_id _ _ _ (undup s')) //=; apply: eq_choose => x /=.\nby apply: sym_left_transitive; [exact: perm_eq_sym|exact: perm_eq_trans|].\nQed.\n\nLemma mem_sort_keys ks k : k \\in ks -> k \\in sort_keys ks.\nProof. by rewrite sort_keysE. Qed.\n\nLemma mem_sort_keys_intro ks k : k \\in sort_keys ks -> k \\in ks.\nProof. by rewrite sort_keysE. Qed.\n\nLemma sort_keys_nil : sort_keys [::] = [::].\nProof.\nhave := sort_keysE [::].\nby case: sort_keys => //= a l /(_ a); rewrite mem_head.\nQed.\n\nLemma sort_keys_id ks : sort_keys (sort_keys ks) = sort_keys ks.\nProof. by have /eq_sort_keys := sort_keysE ks. Qed.\n\nDefinition canonical_keys ks := sort_keys ks == ks.\n\nLemma canonical_uniq ks : canonical_keys ks -> uniq ks.\nProof. by move=> /eqP <-; exact: sort_keys_uniq. Qed.\n\nLemma canonical_sort_keys ks : canonical_keys (sort_keys ks).\nProof. by rewrite /canonical_keys sort_keys_id. Qed.\n\nLemma canonical_eq_keys ks ks' :\n  canonical_keys ks -> canonical_keys ks' ->\n  ks =i ks' -> ks = ks'.\nProof.\nmove=> /eqP; case: _ /; move=> /eqP; case: _ / => eq_ks_ks'.\nby apply/eq_sort_keys => x; rewrite -sort_keysE eq_ks_ks' sort_keysE.\nQed.\n\nLemma size_sort_keys ks : size (sort_keys ks) = size (undup ks).\nProof.\nrewrite -(iffLR (@eq_sort_keys _ _) (mem_undup _)); symmetry.\nby apply/eqP; rewrite -uniq_size_uniq ?sort_keys_uniq ?undup_uniq.\nQed.\n\nEnd ChoiceKeys.\n\nArguments eq_sort_keys {K s s'}.\n\nSection Def.\nVariables (K : choiceType).\n\nStructure finSet : Type := mkFinSet {\n  fset_keys : seq K;\n  _ : canonical_keys fset_keys\n}.\n\nDefinition finset_of (_ : phant K) := finSet.\n\nEnd Def.\n\nIdentity Coercion type_of_finset : finset_of >-> finSet.\n\nFact finset_key : unit. Proof. exact: tt. Qed.\nDefinition pred_of_finset (K : choiceType)\n  (f : finSet K) : pred K := fun k => k \\in locked_with finset_key (fset_keys f).\nCanonical finSetPredType (K : choiceType) :=\n  Eval hnf in mkPredType (@pred_of_finset K).\n\nLemma pred_of_finsetE (K : choiceType) (f : finSet K) k :\n  (k \\in f) = (k \\in fset_keys f).\nProof. by rewrite /pred_of_finset -topredE /= /pred_of_finset locked_withE. Qed.\n\nNotation \"{fset T }\" := (@finset_of _ (Phant T)) : type_scope.\n\nSection FinSetCanonicals.\n\nVariable (K : choiceType).\n\nCanonical fsetType := Eval hnf in [subType for (@fset_keys K)].\nDefinition fset_eqMixin := Eval hnf in [eqMixin of {fset K} by <:].\nCanonical fset_eqType := Eval hnf in EqType {fset K} fset_eqMixin.\nDefinition fset_choiceMixin := Eval hnf in [choiceMixin of {fset K} by <:].\nCanonical fset_choiceType := Eval hnf in ChoiceType {fset K} fset_choiceMixin.\n\nEnd FinSetCanonicals.\n\nSection FinTypeSet.\n\nVariables (K : choiceType) (A : finSet K).\n\nRecord fset_sub : Type :=\n  FSetSub {fsval : K; fsvalP : in_mem fsval (@mem K _ A)}.\n\nCanonical fset_sub_subType := Eval hnf in [subType for fsval].\nDefinition fset_sub_eqMixin := Eval hnf in [eqMixin of fset_sub by <:].\nCanonical fset_sub_eqType := Eval hnf in EqType fset_sub fset_sub_eqMixin.\nDefinition fset_sub_choiceMixin := Eval hnf in [choiceMixin of fset_sub by <:].\nCanonical fset_sub_choiceType := Eval hnf in ChoiceType fset_sub fset_sub_choiceMixin.\n\nDefinition fset_sub_enum : seq fset_sub :=\n  undup (pmap insub (fset_keys A)).\n\nLemma mem_fset_sub_enum x : x \\in fset_sub_enum.\nProof.\nby rewrite mem_undup mem_pmap -valK map_f // -pred_of_finsetE fsvalP.\nQed.\n\nLemma val_fset_sub_enum : uniq (fset_keys A) ->\n  map val fset_sub_enum = fset_keys A.\nProof.\nmove=> Us; rewrite /fset_sub_enum undup_id ?pmap_sub_uniq //.\nrewrite (pmap_filter (@insubK _ _ _)); apply/all_filterP.\nby apply/allP => x; rewrite isSome_insub pred_of_finsetE.\nQed.\n\nDefinition fset_sub_pickle x := index x fset_sub_enum.\nDefinition fset_sub_unpickle n := nth None (map some fset_sub_enum) n.\nLemma fset_sub_pickleK : pcancel fset_sub_pickle fset_sub_unpickle.\nProof.\nrewrite /fset_sub_unpickle => x.\nby rewrite (nth_map x) ?nth_index ?index_mem ?mem_fset_sub_enum.\nQed.\n\nDefinition fset_sub_countMixin := CountMixin fset_sub_pickleK.\nCanonical fset_sub_countType := Eval hnf in CountType fset_sub fset_sub_countMixin.\n\nDefinition fset_sub_finMixin :=\n  Eval hnf in UniqFinMixin (undup_uniq _) mem_fset_sub_enum.\nCanonical fset_sub_finType := Eval hnf in FinType fset_sub fset_sub_finMixin.\n\nLemma card_fset_sub : #|{: fset_sub}| = size (fset_keys A).\nProof.\nrewrite cardE enumT -(size_map val) unlock val_fset_sub_enum //.\nby rewrite canonical_uniq //; case: A.\nQed.\n\nEnd FinTypeSet.\n\nCoercion fset_sub : finSet >-> Sortclass.\nHint Resolve fsvalP.\n\nDefinition fset_predT {T : choiceType} {A : finSet T} := @predT {: A}.\nNotation \"#|` A |\" := #|@fset_predT _ A|\n  (at level 0, A at level 99, format \"#|` A |\") : nat_scope.\n\nSection Basics.\nVariables (K : choiceType).\n\nLemma keys_canonical (f : {fset K}) : canonical_keys (fset_keys f).\nProof. by case: f. Qed.\n\nDefinition seq_fset s : {fset K} := mkFinSet (canonical_sort_keys s).\n\nEnd Basics.\n\nArguments pred_of_finset : simpl never.\n\nHint Resolve keys_canonical.\nHint Resolve sort_keys_uniq.\n\nCanonical  finSetSubType K := [subType for (@fset_keys K)].\nDefinition finSetEqMixin (K : choiceType) := [eqMixin of {fset K} by <:].\nCanonical  finSetEqType  (K : choiceType) := EqType {fset K} (finSetEqMixin K).\n\n(* Definition mem_pred_of_finset (K : choiceType) (A : {fset K}) := mem [finType of A]. *)\n\nNotation Local imfset_def :=\n  (fun (K : choiceType) (T : finType) (f : T -> K) (P : mem_pred T) =>\n  seq_fset [seq f x | x <- enum P]).\nNotation Local imfset2_def :=\n  (fun (K : choiceType) (T1 T2 : finType) (f : T1 -> T2 -> K)\n      (P1 : mem_pred T1) (P2 : T1 -> mem_pred T2) =>\n  seq_fset (flatten [seq [seq f x y | y <- enum (P2 x)]| x <- enum P1])).\n\n\nModule Type ImfsetSig.\nParameter imfset : forall (K : choiceType) (T : finType),\n                   (T -> K) -> mem_pred T -> {fset K}.\nParameter imfset2 : forall (K : choiceType) (T1 T2 : finType),\n                   (T1 -> T2 -> K) -> mem_pred T1 -> (T1 -> mem_pred T2) ->\n                   {fset K}.\nAxiom imfsetE : imfset = imfset_def.\nAxiom imfset2E : imfset2 = imfset2_def.\nEnd ImfsetSig.\n\nModule Imfset : ImfsetSig.\nDefinition imfset := imfset_def.\nDefinition imfset2 := imfset2_def.\nLemma imfsetE : imfset = imfset_def. Proof. by []. Qed.\nLemma imfset2E : imfset2 = imfset2_def. Proof. by []. Qed.\nEnd Imfset.\n\nNotation imfset := Imfset.imfset.\nNotation imfset2 := Imfset.imfset2.\nCanonical imfset_unlock := Unlockable Imfset.imfsetE.\nCanonical imfset2_unlock := Unlockable Imfset.imfset2E.\n\nDelimit Scope fset_scope with fset.\nLocal Open Scope fset_scope.\n\nNotation \"A `=` B\" := (A = B :> {fset _})\n  (at level 70, no associativity, only parsing) : fset_scope.\nNotation \"A `<>` B\" := (A <> B :> {fset _})\n  (at level 70, no associativity, only parsing) : fset_scope.\nNotation \"A `==` B\" := (A == B :> {fset _})\n  (at level 70, no associativity, only parsing) : fset_scope.\nNotation \"A `!=` B\" := (A != B :> {fset _})\n  (at level 70, no associativity, only parsing) : fset_scope.\nNotation \"A `=P` B\" := (A =P B :> {fset _})\n  (at level 70, no associativity, only parsing) : fset_scope.\n\nNotation \"f @` A\" := (imfset f (mem A)) (at level 24) : fset_scope.\nNotation \"f @2` ( A , B )\" := (imfset2 f (mem A) (fun _ => mem B))\n  (at level 24, format \"f  @2`  ( A ,  B )\") : fset_scope.\n\nNotation \"[ 'fset' E | x 'in' A ]\" := ((fun x => E) @` A)\n  (at level 0, E, x at level 99,\n   format \"[ '[hv' 'fset'  E '/ '  |  x  'in'  A ] ']'\") : fset_scope.\n(* Typed variants. *)\nNotation \"[ 'fset' E | x : T 'in' A ]\" := ((fun x : T => E) @` A)\n  (at level 0, E, x at level 99, only parsing) : fset_scope.\n\nNotation \"[ 'fset' x : T | P ]\" := [fset val t | t : T in [pred x | P]]\n  (at level 0, x at level 99, format \"[ 'fset'  x  :  T  |  P ]\") : fset_scope.\n\nNotation \"[ 'fset' x : T | P & Q ]\" := [fset x : T | P && Q]\n  (at level 0, x at level 99, format \"[ 'fset'  x  :  T  |  P  &  Q ]\") : fset_scope.\nNotation \"[ 'fset'  x  :  T  'in'  A  |  P ]\" :=\n  [fset @val T _ _ (x : A) | x in [pred a | (fun x => P) (val a)]]\n  (at level 0, x at level 99, only parsing) : fset_scope.\nNotation \"[ 'fset' x 'in' A | P ]\" := [fset x : _ in A | P]\n  (at level 0, x at level 99, format \"[ 'fset'  x  'in'  A  |  P ]\") : fset_scope.\nNotation \"[ 'fset'  x  :  T  'in' A  |  P  &  Q ]\" := [fset x : T in A | P && Q]\n  (at level 0, x at level 99, only parsing) : fset_scope.\nNotation \"[ 'fset' x 'in' A | P & Q ]\" := [fset x in A | P && Q]\n  (at level 0, x at level 99,\n   format \"[ 'fset'  x  'in'  A  |  P  &  Q ]\") : fset_scope.\n\nSection Ops.\n\nContext {K : choiceType}.\nImplicit Types (a b c : K) (A B C D : {fset K}) (s : seq K).\n\n(* Definition FinSet V (kvs : K * V) : *)\n(*   canonical_keys (keys []). *)\n\nDefinition fset0 : {fset K} :=\n  @mkFinSet K [::] (introT eqP (@sort_keys_nil K)).\n\nDefinition fset1U a A : {fset K} := seq_fset (a :: fset_keys A).\n\nDefinition fset1 a : {fset K} := seq_fset [:: a].\n\nDefinition fsetU A B := seq_fset (fset_keys A ++ fset_keys B).\n\nDefinition fsetI A B := [fset x in A | x \\in B].\n\nDefinition fsetD A B := [fset x in A | x \\notin B].\n\nDefinition fsubset A B := fsetI A B == A.\n\nDefinition fproper A B := fsubset A B && ~~ fsubset B A.\n\nDefinition fdisjoint A B := (fsetI A B == fset0).\n\nEnd Ops.\n\nNotation \"[ 'fset' a ]\" := (fset1 a)\n  (at level 0, a at level 99, format \"[ 'fset'  a ]\") : fset_scope.\nNotation \"[ 'fset' a : T ]\" := [fset (a : T)]\n  (at level 0, a at level 99, format \"[ 'fset'  a   :  T ]\") : fset_scope.\nNotation \"A `|` B\" := (fsetU A B) : fset_scope.\nNotation \"a |` A\" := ([fset a] `|` A) : fset_scope.\n\n(* This is left-associative due to historical limitations of the .. Notation. *)\nNotation \"[ 'fset' a1 ; a2 ; .. ; an ]\" := (fsetU .. (a1 |` [fset a2]) .. [fset an])\n  (at level 0, a1 at level 99,\n   format \"[ 'fset'  a1 ;  a2 ;  .. ;  an ]\") : fset_scope.\nNotation \"A `&` B\" := (fsetI A B) : fset_scope.\nNotation \"A `\\` B\" := (fsetD A B) : fset_scope.\nNotation \"A `\\ a\" := (A `\\` [fset a]) : fset_scope.\n\nNotation \"A `<=` B\" := (fsubset A B)\n  (at level 70, no associativity) : bool_scope.\n\nNotation \"A `<` B\" := (fproper A B)\n  (at level 70, no associativity) : bool_scope.\n\nNotation \"[ 'disjoint' A & B ]\" := (fdisjoint A B) : fset_scope.\n\n\n(* Comprehensions *)\nNotation \"[ 'fset' E | x 'in' A & P ]\" := [fset E | x in [fset x in A | P]]\n  (at level 0, E, x at level 99,\n   format \"[ '[hv' 'fset'  E '/ '  |  x  'in'  A '/ '  &  P ] ']'\") : fset_scope.\nNotation \"[ 'fset' E | x 'in' A , y 'in' B ]\" :=\n  (imfset2 (fun x y => E) (mem A) (fun x => (mem B)))\n  (at level 0, E, x, y at level 99, format\n   \"[ '[hv' 'fset'  E '/ '  |  x  'in'  A , '/   '  y  'in'  B ] ']'\"\n  ) : fset_scope.\nNotation \"[ 'fset' E | x 'in' A , y 'in' B & P ]\" :=\n  [fset E | x in A, y in [fset y in B | P]]\n  (at level 0, E, x, y at level 99, format\n   \"[ '[hv' 'fset'  E '/ '  |  x  'in'  A , '/   '  y  'in'  B '/ '  &  P ] ']'\"\n  ) : fset_scope.\n\n(* Typed variants. *)\nNotation \"[ 'fset' E | x : T 'in' A & P ]\" :=\n  [fset E | x : T in [set x : T in A | P]]\n  (at level 0, E, x at level 99, only parsing) : fset_scope.\nNotation \"[ 'fset' E | x : T 'in' A , y : U 'in' B ]\" :=\n  (imset2 (fun (x : T) (y : U) => E) (mem A) (fun (x : T) => (mem B)))\n  (at level 0, E, x, y at level 99, only parsing) : fset_scope.\nNotation \"[ 'fset' E | x : T 'in' A , y : U 'in' B & P ]\" :=\n  [fset E | x : T in A, y : U in [set y : U in B | P]]\n  (at level 0, E, x, y at level 99, only parsing) : fset_scope.\n\n(* Comprehensions over a type. *)\nLocal Notation predOfType T := (sort_of_simpl_pred (@pred_of_argType T)).\nNotation \"[ 'fset' E | x : T ]\" := [fset E | x : T in predOfType T]\n  (at level 0, E, x at level 99,\n   format \"[ '[hv' 'fset'  E '/ '  |  x  :  T ] ']'\") : fset_scope.\nNotation \"[ 'fset' E | x : T & P ]\" := [fset E | x : T in [set x : T | P]]\n  (at level 0, E, x at level 99,\n   format \"[ '[hv' 'fset'  E '/ '  |  x  :  T '/ '  &  P ] ']'\") : fset_scope.\nNotation \"[ 'fset' E | x : T , y : U 'in' B ]\" :=\n  [fset E | x : T in predOfType T, y : U in B]\n  (at level 0, E, x, y at level 99, format\n   \"[ '[hv' 'fset'  E '/ '  |  x  :  T , '/   '  y  :  U  'in'  B ] ']'\")\n   : fset_scope.\nNotation \"[ 'fset' E | x : T , y : U 'in' B & P ]\" :=\n  [fset E | x : T, y : U in [fset y in B | P]]\n  (at level 0, E, x, y at level 99, format\n \"[ '[hv ' 'fset'  E '/'  |  x  :  T , '/  '  y  :  U  'in'  B '/'  &  P ] ']'\"\n  ) : fset_scope.\nNotation \"[ 'fset' E | x : T 'in' A , y : U ]\" :=\n  [fset E | x : T in A, y : U in predOfType U]\n  (at level 0, E, x, y at level 99, format\n   \"[ '[hv' 'fset'  E '/ '  |  x  :  T  'in'  A , '/   '  y  :  U ] ']'\")\n   : fset_scope.\nNotation \"[ 'fset' E | x : T 'in' A , y : U & P ]\" :=\n  [fset E | x : T in A, y : U in [set y in P]]\n  (at level 0, E, x, y at level 99, format\n   \"[ '[hv' 'fset'  E '/ '  |  x  :  T  'in'  A , '/   '  y  :  U  &  P ] ']'\")\n   : fset_scope.\nNotation \"[ 'fset' E | x : T , y : U ]\" :=\n  [fset E | x : T, y : U in predOfType U]\n  (at level 0, E, x, y at level 99, format\n   \"[ '[hv' 'fset'  E '/ '  |  x  :  T , '/   '  y  :  U ] ']'\")\n   : fset_scope.\nNotation \"[ 'fset' E | x : T , y : U & P ]\" :=\n  [fset E | x : T, y : U in [set y in P]]\n  (at level 0, E, x, y at level 99, format\n   \"[ '[hv' 'fset'  E '/ '  |  x  :  T , '/   '  y  :  U  &  P ] ']'\")\n   : fset_scope.\n\n(* Untyped variants. *)\nNotation \"[ 'fset' E | x , y 'in' B ]\" := [fset E | x : _, y : _ in B]\n  (at level 0, E, x, y at level 99, only parsing) : fset_scope.\nNotation \"[ 'fset' E | x , y 'in' B & P ]\" := [fset E | x : _, y : _ in B & P]\n  (at level 0, E, x, y at level 99, only parsing) : fset_scope.\nNotation \"[ 'fset' E | x 'in' A , y ]\" := [fset E | x : _ in A, y : _]\n  (at level 0, E, x, y at level 99, only parsing) : fset_scope.\nNotation \"[ 'fset' E | x 'in' A , y & P ]\" := [fset E | x : _ in A, y : _ & P]\n  (at level 0, E, x, y at level 99, only parsing) : fset_scope.\nNotation \"[ 'fset' E | x , y ]\" := [fset E | x : _, y : _]\n  (at level 0, E, x, y at level 99, only parsing) : fset_scope.\nNotation \"[ 'fset' E | x , y & P ]\" := [fset E | x : _, y : _ & P ]\n  (at level 0, E, x, y at level 99, only parsing) : fset_scope.\n\n(* Print-only variants to work around the Coq pretty-printer K-term kink. *)\nNotation \"[ 'fse' 't' E | x 'in' A , y 'in' B ]\" :=\n  (imset2 (fun x y => E) (mem A) (fun _ => mem B))\n  (at level 0, E, x, y at level 99, format\n   \"[ '[hv' 'fse' 't'  E '/ '  |  x  'in'  A , '/   '  y  'in'  B ] ']'\")\n   : fset_scope.\nNotation \"[ 'fse' 't' E | x 'in' A , y 'in' B & P ]\" :=\n  [se t E | x in A, y in [fset y in B | P]]\n  (at level 0, E, x, y at level 99, format\n \"[ '[hv ' 'fse' 't'  E '/'  |  x  'in'  A , '/  '  y  'in'  B '/'  &  P ] ']'\"\n  ) : fset_scope.\nNotation \"[ 'fse' 't' E | x : T , y : U 'in' B ]\" :=\n  (imset2 (fun x (y : U) => E) (mem (predOfType T)) (fun _ => mem B))\n  (at level 0, E, x, y at level 99, format\n   \"[ '[hv ' 'fse' 't'  E '/'  |  x  :  T , '/  '  y  :  U  'in'  B ] ']'\")\n   : fset_scope.\nNotation \"[ 'fse' 't' E | x : T , y : U 'in' B & P ]\" :=\n  [se t E | x : T, y : U in [fset y in B | P]]\n  (at level 0, E, x, y at level 99, format\n\"[ '[hv ' 'fse' 't'  E '/'  |  x  :  T , '/  '  y  :  U  'in'  B '/'  &  P ] ']'\"\n  ) : fset_scope.\nNotation \"[ 'fse' 't' E | x : T 'in' A , y : U ]\" :=\n  (imset2 (fun x y => E) (mem A) (fun _ : T => mem (predOfType U)))\n  (at level 0, E, x, y at level 99, format\n   \"[ '[hv' 'fse' 't'  E '/ '  |  x  :  T  'in'  A , '/   '  y  :  U ] ']'\")\n   : fset_scope.\nNotation \"[ 'fse' 't' E | x : T 'in' A , y : U & P ]\" :=\n  (imset2 (fun x (y : U) => E) (mem A) (fun _ : T => mem [fset y \\in P]))\n  (at level 0, E, x, y at level 99, format\n\"[ '[hv ' 'fse' 't'  E '/'  |  x  :  T  'in'  A , '/  '  y  :  U '/'  &  P ] ']'\"\n  ) : fset_scope.\nNotation \"[ 'fse' 't' E | x : T , y : U ]\" :=\n  [se t E | x : T, y : U in predOfType U]\n  (at level 0, E, x, y at level 99, format\n   \"[ '[hv' 'fse' 't'  E '/ '  |  x  :  T , '/   '  y  :  U ] ']'\")\n   : fset_scope.\nNotation \"[ 'fse' 't' E | x : T , y : U & P ]\" :=\n  [se t E | x : T, y : U in [set y in P]]\n  (at level 0, E, x, y at level 99, format\n   \"[ '[hv' 'fse' 't'  E '/'  |  x  :  T , '/   '  y  :  U '/'  &  P ] ']'\")\n   : fset_scope.\n\nSection imfset.\n\nVariable (K : choiceType).\nImplicit Types (A B : {fset K}).\n\nLemma imfsetP (T : finType) (f : T -> K) (D : mem_pred T) (k : K) :\n  reflect (exists2 x : T, in_mem x D & k = f x) (k \\in imfset f D).\nProof. rewrite unlock pred_of_finsetE sort_keysE; exact: imageP. Qed.\n\nLemma in_imfset (T : finType) (f : T -> K) (D : pred T) (x : T) :\n   x \\in D -> f x \\in [fset f x | x in D].\nProof. by move=> xD; apply/imfsetP; exists x. Qed.\n\nLemma mem_imfset (T : finType) (f : T -> K) (D : pred T): injective f ->\n  forall (k : T), (f k \\in [fset f x | x in D]) = (k \\in D).\nProof.\nby move=> f_inj k; rewrite unlock pred_of_finsetE /= sort_keysE mem_image.\nQed.\n\nLemma imfset2P (T1 T2 : finType) (f : T1 -> T2 -> K)\n      (D1 : mem_pred T1) (D2 : T1 -> mem_pred T2) (k : K) :\n  reflect (exists2 x : T1, in_mem x D1\n         & exists2 y : T2, in_mem y (D2 x) & k = f x y)\n          (k \\in imfset2 f D1 D2).\nProof.\nrewrite unlock !pred_of_finsetE !sort_keysE.\napply: (iffP flatten_mapP) => [[x xD1 /mapP [y yD2]]|[x xD1 [y yD2]]] ->.\n  by rewrite !mem_enum in xD1 yD2; exists x => //; exists y.\nby exists x; rewrite ?mem_enum //; apply/mapP; exists y; rewrite ?mem_enum.\nQed.\n\nLemma in_imfset2 (T1 T2 : finType) (f : T1 -> T2 -> K)\n      (D1 : mem_pred T1) (D2 : T1 -> mem_pred T2) (k : K) (x : T1) (y : T2) :\n   x \\in D1 -> y \\in D2 x -> f x y \\in [fset f x y | x in D1, y in D2 x].\nProof. by move=> xD1 yD2; apply/imfset2P; exists x => //; exists y. Qed.\n\nLemma val_in_FSet A (X : pred A) (k : A) :\n  (val k \\in [fset k : A | k \\in X]) = (k \\in X).\nProof. by rewrite mem_imfset //; apply: val_inj. Qed.\n\nLemma in_FSet A (X : pred A) (k : K) (kA : k \\in A) :\n  (k \\in [fset k : A | k \\in X]) = (FSetSub kA \\in X).\nProof. by rewrite -val_in_FSet. Qed.\n\nLemma FSetP A (X : pred A) (k : K) :\n  reflect {kA : k \\in A & FSetSub kA \\in X} (k \\in [fset k : A | k \\in X]).\nProof.\napply: (iffP idP) => [|[kA kA_X]]; last by rewrite in_FSet.\nrewrite unlock pred_of_finsetE /= sort_keysE => /mapP [/= x x_in_X ->].\nexists (valP x); rewrite mem_enum in x_in_X.\nby set y := (y in y \\in X); suff <- : x = y by []; apply: val_inj.\nQed.\n\nLemma notin_FSet A (X : pred A) (k : K) : k \\notin A ->\n  (k \\in [fset k : A | k \\in X]) = false.\nProof. by apply: contraNF => /FSetP []. Qed.\n\nEnd imfset.\n\nSection Theory.\n\nVariables (K : choiceType).\nImplicit Types (a b x : K) (A B C D : {fset K}) (pA pB pC : pred K) (s : seq K).\n\nLemma in_seq_fsetE s : seq_fset s =i s.\nProof. by move=> a; rewrite pred_of_finsetE sort_keysE. Qed.\n\nLemma in_seq_fset x s : x \\in seq_fset s -> x \\in s.\nProof. by rewrite in_seq_fsetE. Qed.\n\nLemma in_fsetT x s : x \\in s -> x \\in seq_fset s.\nProof. by rewrite in_seq_fsetE. Qed.\n\nLemma fsetP {A B} : A =i B <-> A = B.\nProof.\nsplit=> [eqAB|-> //]; apply/val_inj/canonical_eq_keys => //= a.\nby rewrite -!pred_of_finsetE.\nQed.\n\nLemma fset_eqP {A B} : reflect (A =i B) (A == B).\nProof. exact: (equivP eqP (iff_sym fsetP)). Qed.\n\nLemma in_fset0 x : x \\in fset0 = false.\nProof. by rewrite pred_of_finsetE. Qed.\n\nLemma in_fset1U a' A a : (a \\in a' |` A) = (a == a') || (a \\in A).\nProof. by rewrite !(pred_of_finsetE, sort_keysE, in_cons, mem_cat, orbF). Qed.\n\nLemma in_fset1 a' a : a \\in [fset a'] = (a == a').\nProof. by rewrite !(pred_of_finsetE, sort_keysE, in_cons, mem_cat, orbF). Qed.\n\nLemma in_fsetU A B a : (a \\in A `|` B) = (a \\in A) || (a \\in B).\nProof. by rewrite !(pred_of_finsetE, sort_keysE, mem_cat). Qed.\n\nLemma in_fset A pA a : (a \\in [fset x in A | pA x]) = (a \\in A) && (pA a).\nProof.\napply/FSetP/idP => [[/= aA]|/andP [aA pAa]]; last by exists aA.\nby rewrite -[in X in X -> _]topredE /= aA.\nQed.\n\nLemma val_in_fset A (P : pred A) (k : A) :\n  (val k \\in [fset k : A | P k]) = P k.\nProof. by have Pk := valP k; rewrite in_FSet; congr P; apply: val_inj. Qed.\n\nLemma in_fsetI A B a : (a \\in A `&` B) = (a \\in A) && (a \\in B).\nProof. by rewrite in_fset. Qed.\n\nLemma in_fsetD A B a : (a \\in A `\\` B) = (a \\notin B) && (a \\in A).\nProof. by rewrite in_fset andbC. Qed.\n\nLemma in_fsetD1 A b a : (a \\in A `\\ b) = (a != b) && (a \\in A).\nProof. by rewrite in_fsetD in_fset1. Qed.\n\nDefinition in_fsetE :=\n  (in_fset, in_fset0, in_fset1, in_fsetU, in_fset1U, in_fsetI, in_fsetD, in_fsetD1).\n\nLemma fsetIC (A B : {fset K}) : A `&` B = B `&` A.\nProof. by apply/fsetP => a; rewrite !in_fsetI andbC. Qed.\n\nLemma fsetUC (A B : {fset K}) : A `|` B = B `|` A.\nProof. by apply/fsetP => a; rewrite !in_fsetU orbC. Qed.\n\nLemma fset0I A : fset0 `&` A = fset0.\nProof. by apply/fsetP => x; rewrite !in_fsetE andFb. Qed.\n\nLemma fsetI0 A : A `&` fset0 = fset0.\nProof. by rewrite fsetIC fset0I. Qed.\n\nLemma fsetIA A B C : A `&` (B `&` C) = A `&` B `&` C.\nProof. by apply/fsetP=> x; rewrite !in_fsetI andbA. Qed.\n\nLemma fsetICA A B C : A `&` (B `&` C) = B `&` (A `&` C).\nProof. by rewrite !fsetIA (fsetIC A). Qed.\n\nLemma fsetIAC A B C : A `&` B `&` C = A `&` C `&` B.\nProof. by rewrite -!fsetIA (fsetIC B). Qed.\n\nLemma fsetIACA A B C D : (A `&` B) `&` (C `&` D) = (A `&` C) `&` (B `&` D).\nProof. by rewrite -!fsetIA (fsetICA B). Qed.\n\nLemma fsetIid A : A `&` A = A.\nProof. by apply/fsetP=> x; rewrite in_fsetI andbb. Qed.\n\nLemma fsetIIl A B C : A `&` B `&` C = (A `&` C) `&` (B `&` C).\nProof. by rewrite fsetIA !(fsetIAC _ C) -(fsetIA _ C) fsetIid. Qed.\n\nLemma fsetIIr A B C : A `&` (B `&` C) = (A `&` B) `&` (A `&` C).\nProof. by rewrite !(fsetIC A) fsetIIl. Qed.\n\n(* distribute /cancel *)\n\nLemma fsetIUr A B C : A `&` (B `|` C) = (A `&` B) `|` (A `&` C).\nProof. by apply/fsetP=> x; rewrite !in_fsetE andb_orr. Qed.\n\nLemma fsetIUl A B C : (A `|` B) `&` C = (A `&` C) `|` (B `&` C).\nProof. by apply/fsetP=> x; rewrite !in_fsetE andb_orl. Qed.\n\nLemma fsetUIr A B C : A `|` (B `&` C) = (A `|` B) `&` (A `|` C).\nProof. by apply/fsetP=> x; rewrite !in_fsetE orb_andr. Qed.\n\nLemma fsetUIl A B C : (A `&` B) `|` C = (A `|` C) `&` (B `|` C).\nProof. by apply/fsetP=> x; rewrite !in_fsetE orb_andl. Qed.\n\nLemma fsetUK A B : (A `|` B) `&` A = A.\nProof. by apply/fsetP=> x; rewrite !in_fsetE orbK. Qed.\n\nLemma fsetKU A B : A `&` (B `|` A) = A.\nProof. by apply/fsetP=> x; rewrite !in_fsetE orKb. Qed.\n\nLemma fsetIK A B : (A `&` B) `|` A = A.\nProof. by apply/fsetP=> x; rewrite !in_fsetE andbK. Qed.\n\nLemma fsetKI A B : A `|` (B `&` A) = A.\nProof. by apply/fsetP=> x; rewrite !in_fsetE andKb. Qed.\n\n(* subset *)\n\nLemma fsubsetP {A B} : reflect {subset A <= B} (A `<=` B).\nProof.\napply: (iffP fset_eqP) => AsubB a; first by rewrite -AsubB in_fsetI => /andP[].\nby rewrite in_fsetI; have [/AsubB|] := boolP (a \\in A).\nQed.\n\nLemma FSet_sub A (P : pred A) : [fset x : A | P x] `<=` A.\nProof. by apply/fsubsetP => k /FSetP []. Qed.\n\nLemma fsetD_eq0 (A B : {fset K}) : (A `\\` B == fset0) = (A `<=` B).\nProof.\napply/fset_eqP/fsubsetP => sAB a.\n  by move=> aA; have := sAB a; rewrite !in_fsetE aA andbT => /negPn.\nby rewrite in_fsetD in_fset0 andbC; apply/negP => /andP [/sAB ->].\nQed.\n\nLemma fsubset_refl A : A `<=` A. Proof. exact/fsubsetP. Qed.\nHint Resolve fsubset_refl.\n\nDefinition fincl A B (AsubB : A `<=` B) (a : A) : B :=\n  FSetSub ((fsubsetP AsubB) _ (valP a)).\n\nDefinition fsub B A : {set B} := [set x : B | val x \\in A].\n\nLemma fsubE A B (AsubB : A `<=` B) :\n  fsub B A = [set fincl AsubB x | x in {: A}].\nProof.\napply/setP => x; rewrite in_set; apply/idP/imsetP => [|[[a aA] aA' ->]] //.\nby move=> xA; exists (FSetSub xA)=> //; apply: val_inj.\nQed.\n\nLemma fincl_fsub A B (AsubB : A `<=` B) (a : A) :\n  fincl AsubB a \\in fsub B A.\nProof. by rewrite inE /= (valP a). Qed.\n\nLemma in_fsub B A (b : B) : (b \\in fsub B A) = (val b \\in A).\nProof. by rewrite inE. Qed.\n\nLemma subset_fsubE C A B : A `<=` C -> B `<=` C ->\n   (fsub C A \\subset fsub C B) = (A `<=` B).\nProof.\nmove=> sAC sBC; apply/subsetP/fsubsetP => sAB a; last first.\n  by rewrite !in_fsub => /sAB.\nby move=> aA; have := sAB _ (fincl_fsub sAC (FSetSub aA)); rewrite in_fsub.\nQed.\n\nLemma fsubset_trans : transitive (@fsubset K).\nProof. by move=>??? s t ; apply/fsubsetP => a /(fsubsetP s) /(fsubsetP t). Qed.\n\nLemma subset_fsub A B C : A `<=` B -> B `<=` C ->\n  fsub C A \\subset fsub C B.\nProof. by move=> sAB sBC; rewrite subset_fsubE // (fsubset_trans sAB). Qed.\n\nLemma fsetIidPl {A B} : reflect (A `&` B = A) (A `<=` B).\nProof. exact: eqP. Qed.\n\nLemma fsetIidPr {A B} : reflect (A `&` B = B) (B `<=` A).\nProof. by rewrite fsetIC; apply: fsetIidPl. Qed.\n\nLemma fsubsetIidl A B : (A `<=` A `&` B) = (A `<=` B).\nProof.\nby apply/fsubsetP/fsubsetP=> sAB a aA; have := sAB _ aA; rewrite !in_fsetI ?aA.\nQed.\n\nLemma fsubsetIidr A B : (B `<=` A `&` B) = (B `<=` A).\nProof. by rewrite fsetIC fsubsetIidl. Qed.\n\nLemma fsetUidPr A B : reflect (A `|` B = B) (A `<=` B).\nProof.\napply: (iffP fsubsetP) => sAB; last by move=> a aA; rewrite -sAB in_fsetU aA.\nby apply/fsetP => b; rewrite in_fsetU; have [/sAB|//] := boolP (_ \\in _).\nQed.\n\nLemma fsetUidPl A B : reflect (A `|` B = A) (B `<=` A).\nProof. by rewrite fsetUC; apply/fsetUidPr. Qed.\n\nLemma fsubsetUl A B : A `<=` A `|` B.\nProof. by apply/fsubsetP => a; rewrite in_fsetU => ->. Qed.\nHint Resolve fsubsetUl.\n\nLemma fsubsetUr A B : B `<=` A `|` B.\nProof. by rewrite fsetUC. Qed.\nHint Resolve fsubsetUr.\n\nLemma fsubsetU1 x A : A `<=` x |` A.\nProof. by rewrite fsubsetUr. Qed.\nHint Resolve fsubsetU1.\n\nLemma fsubsetU A B C : (A `<=` B) || (A `<=` C) -> A `<=` B `|` C.\nProof. by move=> /orP [] /fsubset_trans ->. Qed.\n\nLemma fincl_inj A B (AsubB : A `<=` B) : injective (fincl AsubB).\nProof. by move=> a b [eq_ab]; apply: val_inj. Qed.\nHint Resolve fincl_inj.\n\nLemma fsub_inj B : {in [pred A | A `<=` B] &, injective (fsub B)}.\nProof.\nmove=> A A'; rewrite -!topredE /= => sAB sA'B /setP eqAA'; apply/fsetP => a.\napply/idP/idP => mem_a.\n  have := eqAA' (fincl sAB (FSetSub mem_a)).\n  by rewrite !in_fsub // => <-.\nhave := eqAA' (fincl sA'B (FSetSub mem_a)).\nby rewrite !in_fsub // => ->.\nQed.\nHint Resolve fsub_inj.\n\nLemma eqEfsubset A B : (A == B) = (A `<=` B) && (B `<=` A).\nProof.\napply/eqP/andP => [-> //|[/fsubsetP AB /fsubsetP BA]].\nby apply/fsetP=> x; apply/idP/idP=> [/AB|/BA].\nQed.\n\nLemma subEfproper A B : A `<=` B = (A == B) || (A `<` B).\nProof. by rewrite eqEfsubset -andb_orr orbN andbT. Qed.\n\nLemma fproper_sub A B : A `<` B -> A `<=` B.\nProof. by rewrite subEfproper orbC => ->. Qed.\n\nLemma eqVfproper A B : A `<=` B -> A = B \\/ A `<` B.\nProof. by rewrite subEfproper => /predU1P. Qed.\n\nLemma fproperEneq A B : A `<` B = (A != B) && (A `<=` B).\nProof. by rewrite andbC eqEfsubset negb_and andb_orr andbN. Qed.\n\nLemma fproper_neq A B : A `<` B -> A != B.\nProof. by rewrite fproperEneq; case/andP. Qed.\n\nLemma eqEfproper A B : (A == B) = (A `<=` B) && ~~ (A `<` B).\nProof. by rewrite negb_and negbK andb_orr andbN eqEfsubset. Qed.\n\nLemma card_fsub B A : A `<=` B -> #|fsub B A| = #|` A|.\nProof. by move=> sAB; rewrite fsubE card_imset //; apply: fincl_inj. Qed.\n\nLemma eqEfcard A B : (A == B) = (A `<=` B) &&\n  (#|` B| <= #|` A|)%N.\nProof.\nrewrite -(inj_in_eq (@fsub_inj (A `|` B))) -?topredE //=.\nby rewrite eqEcard !(@subset_fsubE (A `|` B)) ?(@card_fsub (A `|` B)).\nQed.\n\nLemma fproperEcard A B :\n  (A `<` B) = (A `<=` B) && (#|` A| < #|` B|)%N.\nProof. by rewrite fproperEneq ltnNge andbC eqEfcard; case: (A `<=` B). Qed.\n\nLemma fsubset_leqif_cards A B : A `<=` B -> (#|` A| <= #|` B| ?= iff (A == B))%N.\nProof.\nrewrite -!(@card_fsub (A `|` B)) // -(@subset_fsubE (A `|` B)) //.\nby move=> /subset_leqif_cards; rewrite (inj_in_eq (@fsub_inj _)) -?topredE /=.\nQed.\n\nLemma fsub0set A : fset0 `<=` A.\nProof. by apply/fsubsetP=> x; rewrite in_fsetE. Qed.\nHint Resolve fsub0set.\n\nLemma fsubset0 A : (A `<=` fset0) = (A == fset0).\nProof. by rewrite eqEfsubset fsub0set andbT. Qed.\n\nLemma fproper0 A : (fset0 `<` A) = (A != fset0).\nProof. by rewrite /fproper fsub0set fsubset0. Qed.\n\nLemma fproperE A B : (A `<` B) = (A `<=` B) && ~~ (B `<=` A).\nProof. by []. Qed.\n\nLemma fsubEproper A B : (A `<=` B) = (A == B) || (A `<` B).\nProof. by rewrite fproperEneq; case: eqP => //= ->; apply: fsubset_refl. Qed.\n\nLemma fsubset_leq_card A B : A `<=` B -> (#|` A| <= #|` B|)%N.\nProof. by move=> /fsubset_leqif_cards ->. Qed.\n\nLemma fproper_ltn_card A B : A `<` B -> (#|` A| < #|` B|)%N.\nProof. by rewrite fproperEcard => /andP []. Qed.\n\nLemma fsubset_cardP A B : #|` A| = #|` B| ->\n  reflect (A =i B) (A `<=` B).\nProof.\nmove=> eq_cardAB; apply: (iffP idP) => [/eqVfproper [->//|]|/fsetP -> //].\nby rewrite fproperEcard eq_cardAB ltnn andbF.\nQed.\n\nLemma fproper_sub_trans B A C : A `<` B -> B `<=` C -> A `<` C.\nProof.\nrewrite !fproperEcard => /andP [sAB lt_AB] sBC.\nby rewrite (fsubset_trans sAB) //= (leq_trans lt_AB) // fsubset_leq_card.\nQed.\n\nLemma fsub_proper_trans B A C :\n  A `<=` B -> B `<` C -> A `<` C.\nProof.\nrewrite !fproperEcard => sAB /andP [sBC lt_BC].\nby rewrite (fsubset_trans sAB) //= (leq_ltn_trans _ lt_BC) // fsubset_leq_card.\nQed.\n\nLemma fsubset_neq0 A B : A `<=` B -> A != fset0 -> B != fset0.\nProof. by rewrite -!fproper0 => sAB /fproper_sub_trans->. Qed.\n\n(* fsub is a morphism *)\n\nLemma fsub0 A : fsub A fset0 = set0 :> {set A}.\nProof. by apply/setP => x; rewrite in_fsub in_fsetE inE. Qed.\n\nLemma fsubT A : fsub A A = [set : A].\nProof. by apply/setP => x; rewrite in_fsub inE (valP x). Qed.\n\nLemma fsub1 A a (aA : a \\in A) : fsub A [fset a] = [set FSetSub aA] :> {set A}.\nProof. by apply/setP=> x; rewrite in_fsub in_set1 in_fset1; congr eq_op. Qed.\n\nLemma fsubU C A B : fsub C (A `|` B) = fsub C A :|: fsub C B.\nProof. by apply/setP => x; rewrite !(in_fsub, in_setU, in_fsetU). Qed.\n\nLemma fsubI C A B : fsub C (A `&` B) = fsub C A :&: fsub C B.\nProof. by apply/setP => x; rewrite !(in_fsub, in_setI, in_fsetI). Qed.\n\nLemma fsubD C A B : fsub C (A `\\` B) = fsub C A :\\: fsub C B.\nProof. by apply/setP => x; rewrite !(in_fsub, in_setD, in_fsetD) andbC. Qed.\n\nLemma fsubD1 C A b (bC : b \\in C) : fsub C (A `\\ b) = fsub C A :\\ FSetSub bC.\nProof. by rewrite fsubD fsub1. Qed.\n\nLemma fsub_eq0 A B : A `<=` B -> (fsub B A == set0) = (A == fset0).\nProof.\nby move=> sAB; rewrite -fsub0 (inj_in_eq (@fsub_inj _)) -?topredE /=.\nQed.\n\nLemma fset_0Vmem A : (A = fset0) + {x : K | x \\in A}.\nProof.\nhave [|[x mem_x]] := set_0Vmem (fsub A A); last first.\n  by right; exists (val x); rewrite in_fsub // in mem_x.\nby move=> /eqP; rewrite fsub_eq0 // => /eqP; left.\nQed.\n\nLemma fset1P x a : reflect (x = a) (x \\in [fset a]).\nProof. by rewrite in_fset1; exact: eqP. Qed.\n\nLemma fset11 x : x \\in [fset x].\nProof. by rewrite in_fset1. Qed.\n\nLemma fset1_inj : injective (@fset1 K).\nProof. by move=> a b eqsab; apply/fset1P; rewrite -eqsab fset11. Qed.\n\nLemma fset1UP x a B : reflect (x = a \\/ x \\in B) (x \\in a |` B).\nProof. by rewrite !in_fset1U; exact: predU1P. Qed.\n\nLemma fset_cons a s : seq_fset (a :: s) = a |` (seq_fset s).\nProof. by apply/fsetP=> x; rewrite in_fset1U !in_seq_fsetE. Qed.\n\nLemma fset1U1 x B : x \\in x |` B.\nProof. by rewrite in_fset1U eqxx. Qed.\n\nLemma fset1Ur x a B : x \\in B -> x \\in a |` B.\nProof. by move=> Bx; rewrite in_fset1U predU1r. Qed.\n\n(* We need separate lemmas for the explicit enumerations since they *)\n(* associate on the left.                                           *)\nLemma fsetU1l x A b : x \\in A -> x \\in A `|` [fset b].\nProof. by move=> Ax; rewrite !in_fsetU Ax. Qed.\n\nLemma fsetU1r A b : b \\in A `|` [fset b].\nProof. by rewrite in_fsetU in_fset1 eqxx orbT. Qed.\n\nLemma fsetD1P x A b : reflect (x != b /\\ x \\in A) (x \\in A `\\ b).\nProof. by rewrite in_fsetD1; exact: andP. Qed.\n\nLemma fsetD11 b A : (b \\in A `\\ b) = false.\nProof. by rewrite in_fsetD1 eqxx. Qed.\n\nLemma fsetD1K a A : a \\in A -> a |` (A `\\ a) = A.\nProof.\nby move=> Aa; apply/fsetP=> x; rewrite !in_fsetE; case: eqP => // ->.\nQed.\n\nLemma fsetU1K a B : a \\notin B -> (a |` B) `\\ a = B.\nProof.\nby move/negPf=> nBa; apply/fsetP=> x; rewrite !in_fsetE; case: eqP => // ->.\nQed.\n\nLemma fset2P x a b : reflect (x = a \\/ x = b) (x \\in [fset a; b]).\nProof. by rewrite !in_fsetE; apply: (iffP orP) => [] [] /eqP; intuition. Qed.\n\nLemma in_fset2 x a b : (x \\in [fset a; b]) = (x == a) || (x == b).\nProof. by rewrite !in_fsetU !in_fset1. Qed.\n\nLemma set21 a b : a \\in [fset a; b]. Proof. by rewrite fset1U1. Qed.\n\nLemma set22 a b : b \\in [fset a; b]. Proof. by rewrite in_fset2 eqxx orbT. Qed.\n\nLemma fsetUP x A B : reflect (x \\in A \\/ x \\in B) (x \\in A `|` B).\nProof. by rewrite !in_fsetU; exact: orP. Qed.\n\nLemma fsetULVR x A B : x \\in A `|` B -> (x \\in A) + (x \\in B).\nProof. by rewrite in_fsetU; case: (x \\in A); [left|right]. Qed.\n\nLemma fsetUS A B C : A `<=` B -> C `|` A `<=` C `|` B.\nProof.\nmove=> sAB; apply/fsubsetP=> x; rewrite !in_fsetU.\nby case: (x \\in C) => //; exact: (fsubsetP sAB).\nQed.\n\nLemma fsetSU A B C : A `<=` B -> A `|` C `<=` B `|` C.\nProof. by move=> sAB; rewrite -!(fsetUC C) fsetUS. Qed.\n\nLemma fsetUSS A B C D : A `<=` C -> B `<=` D -> A `|` B `<=` C `|` D.\nProof. by move=> /(fsetSU B) /fsubset_trans sAC /(fsetUS C)/sAC. Qed.\n\nLemma fset0U A : fset0 `|` A = A.\nProof. by apply/fsetP => x; rewrite !in_fsetE orFb. Qed.\n\nLemma fsetU0 A : A `|` fset0 = A.\nProof. by rewrite fsetUC fset0U. Qed.\n\nLemma fsetUA A B C : A `|` (B `|` C) = A `|` B `|` C.\nProof. by apply/fsetP => x; rewrite !in_fsetU orbA. Qed.\n\nLemma fsetUCA A B C : A `|` (B `|` C) = B `|` (A `|` C).\nProof. by rewrite !fsetUA (fsetUC B). Qed.\n\nLemma fsetUAC A B C : A `|` B `|` C = A `|` C `|` B.\nProof. by rewrite -!fsetUA (fsetUC B). Qed.\n\nLemma fsetUACA A B C D : (A `|` B) `|` (C `|` D) = (A `|` C) `|` (B `|` D).\nProof. by rewrite -!fsetUA (fsetUCA B). Qed.\n\nLemma fsetUid A : A `|` A = A.\nProof. by apply/fsetP=> x; rewrite in_fsetU orbb. Qed.\n\nLemma fsetUUl A B C : A `|` B `|` C = (A `|` C) `|` (B `|` C).\nProof. by rewrite fsetUA !(fsetUAC _ C) -(fsetUA _ C) fsetUid. Qed.\n\nLemma setUUr A B C : A `|` (B `|` C) = (A `|` B) `|` (A `|` C).\nProof. by rewrite !(fsetUC A) fsetUUl. Qed.\n\n(* intersection *)\n\nLemma fsetIP x A B : reflect (x \\in A /\\ x \\in B) (x \\in A `&` B).\nProof. by rewrite in_fsetI; apply: andP. Qed.\n\nLemma fsetIS A B C : A `<=` B -> C `&` A `<=` C `&` B.\nProof.\nmove=> sAB; apply/fsubsetP=> x; rewrite !in_fsetI.\nby case: (x \\in C) => //; exact: (fsubsetP sAB).\nQed.\n\nLemma fsetSI A B C : A `<=` B -> A `&` C `<=` B `&` C.\nProof. by move=> sAB; rewrite -!(fsetIC C) fsetIS. Qed.\n\nLemma fsetISS A B C D : A `<=` C -> B `<=` D -> A `&` B `<=` C `&` D.\nProof. by move=> /(fsetSI B) /fsubset_trans sAC /(fsetIS C) /sAC. Qed.\n\n(* difference *)\n\nLemma fsetDP A B x : reflect (x \\in A /\\ x \\notin B) (x \\in A `\\` B).\nProof. by rewrite in_fsetD andbC; apply: andP. Qed.\n\nLemma fsetSD A B C : A `<=` B -> A `\\` C `<=` B `\\` C.\nProof.\nmove=> sAB; apply/fsubsetP=> x; rewrite !in_fsetD.\nby case: (x \\in C) => //; exact: (fsubsetP sAB).\nQed.\n\nLemma fsetDS A B C : A `<=` B -> C `\\` B `<=` C `\\` A.\nProof.\nmove=> sAB; apply/fsubsetP=> x; rewrite !in_fsetD ![_ && (_ \\in _)]andbC.\nby case: (x \\in C) => //; apply: contra; exact: (fsubsetP sAB).\nQed.\n\nLemma fsetDSS A B C D : A `<=` C -> D `<=` B -> A `\\` B `<=` C `\\` D.\nProof. by move=> /(fsetSD B) /fsubset_trans sAC /(fsetDS C) /sAC. Qed.\n\nLemma fsetD0 A : A `\\` fset0 = A.\nProof. by apply/fsetP=> x; rewrite !in_fsetE. Qed.\n\nLemma fset0D A : fset0 `\\` A = fset0.\nProof. by apply/fsetP=> x; rewrite !in_fsetE andbF. Qed.\n\nLemma fsetDv A : A `\\` A = fset0.\nProof. by apply/fsetP=> x; rewrite !in_fsetE andNb. Qed.\n\nLemma fsetID A B : A `&` B `|` A `\\` B = A.\nProof. by apply/fsetP=> x; rewrite !in_fsetE; do ?case: (_ \\in _). Qed.\n\nLemma fsetDUl A B C : (A `|` B) `\\` C = (A `\\` C) `|` (B `\\` C).\nProof. by apply/fsetP=> x; rewrite !in_fsetE; do ?case: (_ \\in _). Qed.\n\nLemma fsetDUr A B C : A `\\` (B `|` C) = (A `\\` B) `&` (A `\\` C).\nProof. by apply/fsetP=> x; rewrite !in_fsetE; do ?case: (_ \\in _). Qed.\n\nLemma fsetDIl A B C : (A `&` B) `\\` C = (A `\\` C) `&` (B `\\` C).\nProof. by apply/fsetP=> x; rewrite !in_fsetE; do ?case: (_ \\in _). Qed.\n\nLemma fsetIDA A B C : A `&` (B `\\` C) = (A `&` B) `\\` C.\nProof. by apply/fsetP=> x; rewrite !in_fsetE; do ?case: (_ \\in _). Qed.\n\nLemma fsetIDAC A B C : (A `\\` B) `&` C = (A `&` C) `\\` B.\nProof. by apply/fsetP=> x; rewrite !in_fsetE; do ?case: (_ \\in _). Qed.\n\nLemma fsetDIr A B C : A `\\` (B `&` C) = (A `\\` B) `|` (A `\\` C).\nProof. by apply/fsetP=> x; rewrite !in_fsetE; do ?case: (_ \\in _). Qed.\n\nLemma fsetDDl A B C : (A `\\` B) `\\` C = A `\\` (B `|` C).\nProof. by apply/fsetP=> x; rewrite !in_fsetE; do ?case: (_ \\in _). Qed.\n\nLemma fsetDDr A B C : A `\\` (B `\\` C) = (A `\\` B) `|` (A `&` C).\nProof. by apply/fsetP=> x; rewrite !in_fsetE; do ?case: (_ \\in _). Qed.\n\nLemma fsetUDl (A B C : {fset K}) : A `|` (B `\\` C) = (A `|` B) `\\` (C `\\` A).\nProof. by apply/fsetP=> x; rewrite !in_fsetE; do ?case: (_ \\in _). Qed.\n\nLemma fsetUDr (A B C : {fset K}) : (A `\\` B) `|` C = (A `|` C) `\\` (B `\\` C).\nProof. by apply/fsetP=> x; rewrite !in_fsetE; do ?case: (_ \\in _). Qed.\n\n(* other inclusions *)\n\nLemma fsubsetIl A B : A `&` B `<=` A.\nProof. by apply/fsubsetP=> x; rewrite in_fsetE => /andP []. Qed.\n\nLemma fsubsetIr A B : A `&` B `<=` B.\nProof. by apply/fsubsetP=> x; rewrite in_fsetE => /andP []. Qed.\n\nLemma fsubsetDl A B : A `\\` B `<=` A.\nProof. by apply/fsubsetP=> x; rewrite in_fsetE => /andP []. Qed.\n\nLemma fsubD1set A x : A `\\ x `<=` A.\nProof. by rewrite fsubsetDl. Qed.\n\nHint Resolve fsubsetIl fsubsetIr fsubsetDl fsubD1set.\n\n(* cardinal lemmas for fsets *)\n\nLemma cardfs0 : #|` @fset0 K| = 0.\nProof. by rewrite -(@card_fsub fset0) // fsub0 cards0. Qed.\n\nLemma cardfs_eq0 A : (#|` A| == 0) = (A == fset0).\nProof. by rewrite -(@card_fsub A) // cards_eq0 fsub_eq0. Qed.\n\nLemma cardfs0_eq A : #|` A| = 0 -> A = fset0.\nProof. by move=> /eqP; rewrite cardfs_eq0 => /eqP. Qed.\n\nLemma fset0Pn A : reflect (exists x, x \\in A) (A != fset0).\nProof.\nrewrite -cardfs_eq0; apply: (equivP existsP).\nby split=> [] [a aP]; [exists (val a); apply: valP|exists (FSetSub aP)].\nQed.\n\nLemma cardfs_gt0 A : (0 < #|` A|)%N = (A != fset0).\nProof. by rewrite lt0n cardfs_eq0. Qed.\n\nLemma cardfsE s : #|` seq_fset s| = size (undup s).\nProof.\nrewrite cardT enumT unlock /= undup_id ?pmap_sub_uniq ?sort_keys_uniq //.\nrewrite size_pmap_sub (@eq_in_count _ _ predT) ?count_predT ?size_sort_keys //.\nby move=> k ? /=; rewrite pred_of_finsetE.\nQed.\n\nLemma cardfs1 x : #|` [fset x]| = 1.\nProof. by rewrite cardfsE undup_id. Qed.\n\nLemma cardfsUI A B : #|` A `|` B| + #|` A `&` B| = #|` A| + #|` B|.\nProof.\nrewrite -!(@card_fsub (A `|` B)) ?(fsubset_trans (fsubsetIl _ _)) //.\nby rewrite fsubU fsubI cardsUI.\nQed.\n\nLemma cardfsU A B : #|` A `|` B| = (#|` A| + #|` B| - #|` A `&` B|)%N.\nProof. by rewrite -cardfsUI addnK. Qed.\n\nLemma cardfsI A B : #|` A `&` B| = (#|` A| + #|` B| - #|` A `|` B|)%N.\nProof. by rewrite  -cardfsUI addKn. Qed.\n\nLemma cardfsID B A : #|` A `&` B| + #|` A `\\` B| = #|` A|.\nProof. by rewrite -!(@card_fsub A) // fsubI fsubD cardsID. Qed.\n\nLemma cardfsD A B : #|` A `\\` B| = (#|` A| - #|` A `&` B|)%N.\nProof. by rewrite -(cardfsID B A) addKn. Qed.\n\nLemma mem_fset1U a A : a \\in A -> a |` A = A.\nProof.\nmove=> aA; apply/fsetP => x; rewrite !in_fsetE orbC.\nby have [//|/=] := boolP (_ \\in A); apply: contraNF => /eqP ->.\nQed.\n\nLemma mem_fsetD1 a A : a \\notin A -> A `\\ a = A.\nProof.\nmove=> aA; apply/fsetP => x; rewrite !in_fsetE andbC.\nby have [/= xA|//] := boolP (_ \\in A); apply: contraNneq aA => <-.\nQed.\n\nLemma fsetI1 a A : A `&` [fset a] = if a \\in A then [fset a] else fset0.\nProof.\napply/fsetP => x; rewrite (fun_if (fun X => _ \\in X)) !in_fsetE.\nby have [[->|?] []] := (altP (x =P a), boolP (a \\in A)); rewrite ?andbF.\nQed.\n\nLemma cardfsU1 a A : #|` a |` A| = (a \\notin A) + #|` A|.\nProof.\nhave [aA|aNA] := boolP (a \\in A); first by rewrite mem_fset1U.\nrewrite cardfsU -addnBA ?fsubset_leq_card // fsetIC -cardfsD.\nby rewrite mem_fsetD1 // cardfs1.\nQed.\n\nLemma cardfs2 a b : #|` [fset a; b]| = (a != b).+1.\nProof. by rewrite !cardfsU1 cardfs1 addn1 in_seq_fsetE in_cons orbF. Qed.\n\nLemma cardfsD1 a A : #|` A| = (a \\in A) + #|` A `\\ a|.\nProof.\nrewrite -(cardfsID [fset a]) fsetI1 (fun_if (fun A => #|` A|)).\nby rewrite cardfs0 cardfs1; case: (_ \\in _).\nQed.\n\n(* other inclusions *)\n\nLemma fsub1set A x : ([fset x] `<=` A) = (x \\in A).\nProof.\nrewrite -(@subset_fsubE (x |` A)) // fsub1 ?fset1U1 // => xxA.\nby rewrite sub1set in_fsub.\nQed.\n\nLemma cardfs1P A : reflect (exists x, A = [fset x]) (#|` A| == 1).\nProof.\napply: (iffP idP) => [|[x ->]]; last by rewrite cardfs1.\nrewrite eq_sym eqn_leq cardfs_gt0=> /andP[/fset0Pn[x Ax] leA1].\nby exists x; apply/eqP; rewrite eq_sym eqEfcard fsub1set cardfs1 leA1 Ax.\nQed.\n\nLemma fsubset1 A x : (A `<=` [fset x]) = (A == [fset x]) || (A == fset0).\nProof.\nrewrite eqEfcard cardfs1 -cardfs_eq0 orbC andbC.\nby case: posnP => // A0; rewrite (cardfs0_eq A0) fsub0set.\nQed.\n\nImplicit Arguments fsetIidPl [A B].\n\nLemma cardfsDS A B : B `<=` A -> #|` A `\\` B| = (#|` A| - #|` B|)%N.\nProof. by rewrite cardfsD => /fsetIidPr->. Qed.\n\nLemma fsubIset A B C : (B `<=` A) || (C `<=` A) -> (B `&` C `<=` A).\nProof. by case/orP; apply: fsubset_trans; rewrite (fsubsetIl, fsubsetIr). Qed.\n\nLemma fsubsetI A B C : (A `<=` B `&` C) = (A `<=` B) && (A `<=` C).\nProof.\nrewrite !(sameP fsetIidPl eqP) fsetIA; have [-> //| ] := altP (A `&` B =P A).\nby apply: contraNF => /eqP <-; rewrite -fsetIA -fsetIIl fsetIAC.\nQed.\n\nLemma fsubsetIP A B C : reflect (A `<=` B /\\ A `<=` C) (A `<=` B `&` C).\nProof. by rewrite fsubsetI; exact: andP. Qed.\n\nLemma fsubUset A B C : (B `|` C `<=` A) = (B `<=` A) && (C `<=` A).\nProof.\napply/idP/idP => [subA|/andP [AB CA]]; last by rewrite -[A]fsetUid fsetUSS.\nby rewrite !(fsubset_trans _ subA).\nQed.\n\nLemma fsubUsetP A B C : reflect (A `<=` C /\\ B `<=` C) (A `|` B `<=` C).\nProof. by rewrite fsubUset; exact: andP. Qed.\n\nLemma fsubDset A B C : (A `\\` B `<=` C) = (A `<=` B `|` C).\nProof.\napply/fsubsetP/fsubsetP=> sABC x; rewrite !in_fsetE.\n  by case Bx: (x \\in B) => // Ax; rewrite sABC ?in_fsetD ?Bx.\nby case Bx: (x \\in B) => //; move/sABC; rewrite in_fsetE Bx.\nQed.\n\nLemma fsetU_eq0 A B : (A `|` B == fset0) = (A == fset0) && (B == fset0).\nProof. by rewrite -!fsubset0 fsubUset. Qed.\n\nLemma setD_eq0 A B : (A `\\` B == fset0) = (A `<=` B).\nProof. by rewrite -fsubset0 fsubDset fsetU0. Qed.\n\nLemma fsubsetD1 A B x : (A `<=` B `\\ x) = (A `<=` B) && (x \\notin A).\nProof.\ndo !rewrite -(@subset_fsubE (x |` A `|` B)) ?fsubDset ?fsetUA // 1?fsetUAC //.\nrewrite fsubD1 => [|mem_x]; first by rewrite -fsetUA fset1U1.\nby rewrite subsetD1 // in_fsub.\nQed.\n\nLemma fsubsetD1P A B x : reflect (A `<=` B /\\ x \\notin A) (A `<=` B `\\ x).\nProof. by rewrite fsubsetD1; exact: andP. Qed.\n\nLemma fsubsetPn A B : reflect (exists2 x, x \\in A & x \\notin B) (~~ (A `<=` B)).\nProof.\n rewrite -fsetD_eq0; apply: (iffP (fset0Pn _)) => [[x]|[x xA xNB]].\n  by rewrite in_fsetE => /andP[]; exists x.\nby exists x; rewrite in_fsetE xA xNB.\nQed.\n\nLemma fproperD1 A x : x \\in A -> A `\\ x `<` A.\nProof.\nmove=> Ax; rewrite fproperE fsubsetDl; apply/fsubsetPn; exists x=> //.\nby rewrite in_fsetD1 Ax eqxx.\nQed.\n\nLemma fproperIr A B : ~~ (B `<=` A) -> A `&` B `<` B.\nProof. by move=> nsAB; rewrite fproperE fsubsetIr fsubsetI negb_and nsAB. Qed.\n\nLemma fproperIl A B : ~~ (A `<=` B) -> A `&` B `<` A.\nProof. by move=> nsBA; rewrite fproperE fsubsetIl fsubsetI negb_and nsBA orbT. Qed.\n\nLemma fproperUr A B : ~~ (A `<=` B) ->  B `<` A `|` B.\nProof. by rewrite fproperE fsubsetUr fsubUset fsubset_refl /= andbT. Qed.\n\nLemma fproperUl A B : ~~ (B `<=` A) ->  A `<` A `|` B.\nProof. by move=> not_sBA; rewrite fsetUC fproperUr. Qed.\n\nLemma fproper1set A x : ([fset x] `<` A) -> (x \\in A).\nProof. by move/fproper_sub; rewrite fsub1set. Qed.\n\nLemma fproperIset A B C : (B `<` A) || (C `<` A) -> (B `&` C `<` A).\nProof. by case/orP; apply: fsub_proper_trans; rewrite (fsubsetIl, fsubsetIr). Qed.\n\nLemma fproperI A B C : (A `<` B `&` C) -> (A `<` B) && (A `<` C).\nProof.\nmove=> pAI; apply/andP.\nby split; apply: (fproper_sub_trans pAI); rewrite (fsubsetIl, fsubsetIr).\nQed.\n\nLemma fproperU A B C : (B `|` C `<` A) -> (B `<` A) && (C `<` A).\nProof.\nmove=> pUA; apply/andP.\nby split; apply: fsub_proper_trans pUA; rewrite (fsubsetUr, fsubsetUl).\nQed.\n\nLemma fsetI_eq0 A B : (A `&` B == fset0) = [disjoint A & B].\nProof. by []. Qed.\n\nLemma fdisjoint_sub {A B} : [disjoint A & B]%fset ->\n  forall C : {fset K}, [disjoint fsub C A & fsub C B]%bool.\nProof.\nmove=> disjointAB C; apply/pred0P => a /=; rewrite !in_fsub.\nby have /eqP /fsetP /(_ (val a)) := disjointAB; rewrite !in_fsetE.\nQed.\n\nLemma disjoint_fsub C A B : A `|` B `<=` C ->\n  [disjoint fsub C A & fsub C B]%bool = [disjoint A & B].\nProof.\nmove=> ABsubC.\napply/idP/idP=> [/pred0P DAB|/fdisjoint_sub->//]; apply/eqP/fsetP=> a.\nrewrite !in_fsetE; have [aC|] := boolP (a \\in A `|` B); last first.\n  by rewrite !in_fsetE => /norP [/negPf-> /negPf->].\nby have /= := DAB (FSetSub (fsubsetP ABsubC _ aC)); rewrite !(@in_fsub C).\nQed.\n\nLemma fdisjointP {A B} :\n  reflect (forall a, a \\in A -> a \\notin B) [disjoint A & B]%fset.\nProof.\napply: (iffP eqP) => [AIB_eq0 a aA|neq_ab].\n  by have /fsetP /(_ a) := AIB_eq0; rewrite !in_fsetE aA /= => ->.\napply/fsetP => a; rewrite !in_fsetE.\nby case: (boolP (a \\in A)) => // /neq_ab /negPf ->.\nQed.\n\nLemma fsetDidPl A B : reflect (A `\\` B = A) [disjoint A & B]%fset.\nProof.\napply: (iffP fdisjointP)=> [NB|<- a]; last by rewrite in_fsetE => /andP[].\napply/fsetP => a; rewrite !in_fsetE andbC.\nby case: (boolP (a \\in A)) => //= /NB ->.\nQed.\n\nLemma disjoint_fsetI0 A B : [disjoint A & B] -> A `&` B = fset0.\nProof. by rewrite -fsetI_eq0; move/eqP. Qed.\n\nLemma fsubsetD A B C :\n  (A `<=` (B `\\` C)) = (A `<=` B) && [disjoint A & C]%fset.\nProof.\npose D := A `|` B `|` C.\nhave AD : A `<=` D by rewrite /D -fsetUA fsubsetUl.\nhave BD : B `<=` D by rewrite /D fsetUAC fsubsetUr.\nrewrite -(@subset_fsubE D) //; last first.\n  by rewrite fsubDset (fsubset_trans BD) // fsubsetUr.\nrewrite fsubD subsetD !subset_fsubE // disjoint_fsub //.\nby rewrite /D fsetUAC fsubsetUl.\nQed.\n\nLemma fsubsetDP A B C :\n   reflect (A `<=` B /\\ [disjoint A & C]%fset) (A `<=` (B `\\` C)).\nProof. by rewrite fsubsetD; apply: andP. Qed.\n\nLemma fdisjoint_sym A B : [disjoint A & B] = [disjoint B & A].\nProof. by rewrite -!fsetI_eq0 fsetIC. Qed.\n\nLemma fdisjointP_sym {A B} :\n  reflect (forall a, a \\in A -> a \\notin B) [disjoint B & A]%fset.\nProof. by rewrite fdisjoint_sym; apply: fdisjointP. Qed.\n\nLemma fdisjoint_trans A B C :\n   A `<=` B -> [disjoint B & C] -> [disjoint A & C].\nProof.\nmove=> AsubB; rewrite -!(@disjoint_fsub (B `|` C)) ?fsetSU //.\nby apply: disjoint_trans; rewrite subset_fsub.\nQed.\n\nLemma fdisjoint0X A : [disjoint fset0 & A].\nProof. by rewrite -fsetI_eq0 fset0I. Qed.\n\nLemma fdisjointX0 A : [disjoint A & fset0].\nProof. by rewrite -fsetI_eq0 fsetI0. Qed.\n\nLemma fdisjoint1X x A : [disjoint [fset x] & A] = (x \\notin A).\nProof.\nrewrite -(@disjoint_fsub (x |` A)) //;\nrewrite (@eq_disjoint1 _ (FSetSub (fset1U1 _ _))) ?(@in_fsub (x |` A)) //=.\nby move=> b; rewrite (@in_fsub (x |` _)) [in RHS]inE in_fsetE.\nQed.\n\nLemma fdisjointX1 x A : [disjoint A & [fset x]] = (x \\notin A).\nProof. by rewrite fdisjoint_sym fdisjoint1X. Qed.\n\nLemma fdisjointUX A B C :\n   [disjoint A `|` B & C] = [disjoint A & C]%fset && [disjoint B & C]%fset.\nProof. by rewrite -!fsetI_eq0 fsetIUl fsetU_eq0. Qed.\n\nLemma fdisjointXU A B C :\n   [disjoint A & B `|` C] = [disjoint A & B]%fset && [disjoint A & C]%fset.\nProof. by rewrite -!fsetI_eq0 fsetIUr fsetU_eq0. Qed.\n\nLemma fdisjointU1X x A B :\n   [disjoint x |` A & B]%fset = (x \\notin B) && [disjoint A & B]%fset.\nProof. by rewrite fdisjointUX fdisjoint1X. Qed.\n\nLemma Ffset_sub A (X : {set A}) : [fset k : A | k \\in X] `<=` A.\nProof. by apply/fsubsetP => k /FSetP []. Qed.\n\nLemma fsubK A B : A `<=` B -> [fset k : B | k \\in (fsub B A)] = A.\nProof.\nmove=> AsubB; apply/fsetP => k /=; symmetry.\nhave [kB|kNB] := (boolP (k \\in B)); first by rewrite in_FSet in_fsub.\nrewrite (contraNF (fsubsetP (Ffset_sub _) _)) //.\nby apply: contraNF kNB; apply: fsubsetP.\nQed.\n\nLemma FSetK A (X : {set A}) : fsub A [fset k : A | k \\in X] = X.\nProof. by apply/setP => x; rewrite in_fsub val_in_FSet. Qed.\n\nEnd Theory.\n\nLemma card_in_imfset (T : finType) (K : choiceType) (f : T -> K) (D : pred T) :\n   {in D &, injective f} -> #|` [fset f x | x in D]| = #|D|.\nProof.\nmove=> f_inj; rewrite [imfset]unlock cardfsE undup_id.\n  by rewrite size_map -cardE.\nrewrite map_inj_in_uniq ?enum_uniq // => x y.\nby rewrite !mem_enum => ? ? /f_inj; apply.\nQed.\n\nLemma card_imfset (T : finType) (K : choiceType) (f : T -> K) (D : pred T) :\n    injective f -> #|` [fset f x | x in D]| = #|D|.\nProof. by move=> f_inj; rewrite card_in_imfset // => x y ? ?; apply: f_inj. Qed.\n\nSection PowerSetTheory.\n\nVariable (K : choiceType).\n\nDefinition fpowerset (A : {fset K}) : {fset {fset K}} :=\n  [fset [fset val y | y : A in Y : {set A}] | Y in powerset [set: A]].\n\nLemma fpowersetE A B : (B \\in fpowerset A) = (B `<=` A).\nProof.\napply/imfsetP/fsubsetP => /= [[Z _ -> y /FSetP [] //]|/fsubsetP subYX].\nexists (fsub _ B); last by rewrite fsubK.\nby rewrite powersetE /= -fsubT subset_fsub ?fsubset_refl.\nQed.\n\nLemma fpowersetCE (X A B : {fset K}) :\n (A \\in fpowerset (X `\\` B)) = (A `<=` X) && [disjoint A & B]%fset.\nProof. by rewrite fpowersetE fsubsetD. Qed.\n\nLemma fpowersetS A B : (fpowerset A `<=` fpowerset B) = (A `<=` B).\nProof.\napply/fsubsetP/fsubsetP => [sub_pA_pB a|subAB X].\n  by have := sub_pA_pB [fset a]; rewrite !fpowersetE !fsub1set.\nby rewrite !fpowersetE => /fsubsetP XA; apply/fsubsetP => x /XA /subAB.\nQed.\n\nLemma fpowerset0 : fpowerset fset0 = [fset fset0].\nProof. by apply/fsetP=> X; rewrite in_fsetE fpowersetE fsubset0. Qed.\n\nLemma fpowerset1 (x : K) : fpowerset [fset x] = [fset fset0; [fset x]].\nProof. by apply/fsetP => X; rewrite !in_fsetE fpowersetE fsubset1 orbC. Qed.\n\nLemma fpowersetI A B : fpowerset (A `&` B) = fpowerset A `&` fpowerset B.\nProof. by apply/fsetP=> X; rewrite in_fsetE !fpowersetE fsubsetI. Qed.\n\nLemma card_fpowerset (A : {fset K}) : #|` fpowerset A| = 2 ^ #|` A|.\nProof.\nrewrite card_imfset //=; first by rewrite card_powerset cardsE.\nmove=> X Y /fsetP eqXY; apply/setP => x;\nby have := eqXY (val x); rewrite !val_in_FSet.\nQed.\n\nEnd PowerSetTheory.\n\nSection DefMap.\nVariables (K : choiceType) (V : Type).\n\nRecord finMap : Type := FinMap {\n  domf : {fset K};\n  ffun_of_fmap :> {ffun domf -> V}\n}.\n\nDefinition finmap_of (_ : phant (K -> V)) := finMap.\n\nLet T_ (domf : {fset K}) :=  {ffun domf -> V}.\nLocal Notation finMap' := {domf : _ & T_ domf}.\n\nEnd DefMap.\n\nNotation \"{fmap T }\" := (@finmap_of _ _ (Phant T)) : type_scope.\n\nDefinition pred_of_finmap (K : choiceType) (V : Type)\n  (f : {fmap K -> V}) : pred K := mem (domf f).\nCanonical finMapPredType (K : choiceType) (V : Type) :=\n  Eval hnf in mkPredType (@pred_of_finmap K V).\n\nDelimit Scope fmap_scope with fmap.\nLocal Open Scope fmap_scope.\nNotation \"f .[ kf ]\" := (f (FSetSub kf)) : fmap_scope.\nArguments ffun_of_fmap : simpl never.\n\nNotation \"[ 'fmap' x : aT => F ]\" := (FinMap [ffun x : aT => F])\n  (at level 0, x ident, only parsing) : fun_scope.\n\nNotation \"[ 'fmap' : aT => F ]\" := (FinMap [ffun : aT => F])\n  (at level 0, only parsing) : fun_scope.\n\nNotation \"[ 'fmap' x => F ]\" := [fmap x : _ => F]\n  (at level 0, x ident, format \"[ 'fmap'  x  =>  F ]\") : fun_scope.\n\nNotation \"[ 'fmap' => F ]\" := [fmap: _ => F]\n  (at level 0, format \"[ 'fmap' =>  F ]\") : fun_scope.\n\n\nCanonical finmap_of_finfun (K : choiceType) V (A : {fset K}) (f : {ffun A -> V}) := FinMap f.\nArguments finmap_of_finfun /.\nArguments ffun_of_fmap : simpl nomatch.\n\nSection OpsMap.\n\nVariables (K : choiceType).\n\nDefinition fmap0 V : {fmap K -> V} := FinMap (ffun0 _ (cardfs0 K)).\n\nDefinition fnd V (A : {fset K}) (f : {ffun A -> V}) (k : K) :=\n  omap f (insub k).\n\nInductive fnd_spec V (A : {fset K}) (f : {ffun A -> V}) k :\n  bool -> option A -> option V -> Type :=\n| FndIn  (kf : k \\in A) : fnd_spec f k true (some (FSetSub kf)) (some (f.[kf]))\n| FndOut (kNf : k \\notin A) : fnd_spec f k false None None.\n\nDefinition setf V (f : {fmap K -> V}) (k0 : K) (v0 : V) : {fmap K -> V} :=\n  [fmap k : k0 |` domf f => if val k == k0 then v0\n                            else odflt v0 (fnd f (val k))].\n\nEnd OpsMap.\n\nPrenex Implicits fnd setf.\nArguments fmap0 {K V}.\nArguments setf : simpl never.\nArguments fnd : simpl never.\n\nNotation \"[fmap]\" := fmap0 : fmap_scope.\nNotation \"x .[ k <- v ]\" := (setf x k v) : fmap_scope.\nNotation \"f .[? k ]\" := (fnd f k) : fmap_scope.\n\nSection FinMapCanonicals.\nVariable K : choiceType.\n\nLet finMap_on (V : Type) (d : {fset K}) := {ffun d -> V}.\nLocal Notation finMap_ V := {d : _ & finMap_on V d}.\n\nDefinition finMap_encode V (f : {fmap K -> V}) := Tagged (finMap_on V) (ffun_of_fmap f).\nDefinition finMap_decode V (f : finMap_ V) := FinMap (tagged f).\nLemma finMap_codeK V : cancel (@finMap_encode V) (@finMap_decode V).\nProof. by case. Qed.\n\nSection FinMapEqType.\nVariable V : eqType.\n\nDefinition finMap_eqMixin := CanEqMixin (@finMap_codeK V).\nCanonical finMap_eqType := EqType {fmap K -> V} finMap_eqMixin.\n\nEnd FinMapEqType.\n\nSection FinMapChoiceType.\nVariable V : choiceType.\n\nDefinition finMap_choiceMixin := CanChoiceMixin (@finMap_codeK V).\nCanonical finMap_choiceType := ChoiceType {fmap K -> V} finMap_choiceMixin.\n\nEnd FinMapChoiceType.\n\nEnd FinMapCanonicals.\n\nSection FinMapTheory.\n\nVariables (K : choiceType).\n\nLemma fndP V (f : {fmap K -> V}) k :\n  fnd_spec f k (k \\in domf f) (insub k) (f.[? k]).\nProof.\nrewrite /fnd; case: insubP=> [[k' k'f] _ {k} <- /=|kNf].\n  by rewrite k'f; constructor.\nby rewrite (negPf kNf); constructor.\nQed.\n\nLemma fndSome V (f : {fmap K -> V}) (k : K) :\n  f.[? k] = (k \\in f) :> bool.\nProof. by case: fndP. Qed.\n\nLemma not_fnd V (f : {fmap K -> V}) (k : K) :\n  k \\notin domf f -> f.[? k] = None.\nProof. by case: fndP. Qed.\n\nLemma getfE V (f : {fmap K -> V}) (k : domf f)\n      (kf : val k \\in domf f) : f.[kf] = f k :> V.\nProof. by congr (_ _); apply: val_inj. Qed.\n\nLemma eq_getf V (f : {fmap K -> V}) k (kf kf' : k \\in domf f) :\n  f.[kf] = f.[kf'] :> V.\nProof. by rewrite (@getfE _ _ (FSetSub kf')). Qed.\n\nLemma Some_fnd V (f : {fmap K -> V}) (k : domf f) :\n  Some (f k) = f.[? val k].\nProof. by case: fndP (valP k) => // ? _; rewrite getfE. Qed.\n\nLemma in_fnd V (f : {fmap K -> V}) (k : K)\n      (kf : k \\in domf f) : f.[? k] = Some f.[kf].\nProof. by rewrite Some_fnd. Qed.\n\nLemma fnd_if V (cond : bool) (f g : {fmap K -> V}) (k : K) :\n  ((if cond then f else g) : finMap _ _).[? k] =\n  if cond then f.[? k] else g.[? k].\nProof. by case: cond. Qed.\n\nLemma getfP V (f g : {fmap K -> V}) : domf f = domf g ->\n  (forall k (kMf : k \\in f) (kMg : k \\in g), f.[kMf] = g.[kMg]) -> f = g.\nProof.\nmove: f g => [kf f] [kg g] /= eq_kfg; case: _ / eq_kfg in g * => {kg}.\nmove=> eq_fg; congr FinMap; apply/ffunP => /= x.\nby do [rewrite -!getfE; do ?exact: valP] => *.\nQed.\n\nLemma fmapP V (f g : {fmap K -> V}) :\n      (forall k, f.[? k] = g.[? k]) <-> f = g.\nProof.\nsplit=> [fnd_fg|-> //]; apply: getfP => [|k kMf kMg].\n  by apply/fsetP => x; rewrite -!fndSome fnd_fg.\nby apply: Some_inj; rewrite !Some_fnd.\nQed.\n\nLemma mem_setf V (f : {fmap K -> V}) (k0 : K) (v0 : V) :\n  f.[k0 <- v0] =i predU1 k0 (mem (domf f)).\nProof. by move=> k; rewrite !in_fsetE !inE. Qed.\n\nLemma dom_setf V (f : {fmap K -> V}) (k0 : K) (v0 : V) :\n  domf (f.[k0 <- v0]) = k0 |` domf f.\nProof. by apply/fsetP=> k; rewrite mem_setf. Qed.\n\nLemma fnd_set_in V (f : {fmap K -> V}) k0 v0 (x : domf f.[k0 <- v0]) :\n  val x != k0 -> val x \\in f.\nProof. by have := valP x; rewrite mem_setf inE; case: eqP. Qed.\n\nLemma setfK V (f : {fmap K -> V}) k0 v0 (x : domf f.[k0 <- v0]):\n   f.[k0 <- v0] x = if eqVneq (val x) k0 is right xNk0\n                    then f.[fnd_set_in xNk0] else v0.\nProof.\ncase: eqVneq => [|xNk0]; rewrite ?ffunE /=; first by move->; rewrite eqxx.\nby rewrite (negPf xNk0) in_fnd ?fnd_set_in //= => xf; apply: eq_getf.\nQed.\n\nLemma fnd_set V (f : {fmap K -> V}) k0 v0 k :\n   f.[k0 <- v0].[? k] = if k == k0 then Some v0 else f.[? k].\nProof.\ncase: fndP => [ksf|]; last first.\n  by rewrite mem_setf inE negb_or => /andP [/negPf ->]; case: fndP.\nrewrite setfK; case: eqVneq => //= [->|kNk0]; first by rewrite eqxx.\nby rewrite Some_fnd (negPf kNk0).\nQed.\n\nLemma fmap_nil V (f : {fmap K -> V}) : domf f = fset0 -> f = [fmap].\nProof.\nby move=> kf0; apply: getfP => //= k ? kMg; have := kMg; rewrite in_fsetE.\nQed.\n\nLemma getf_set V (f : {fmap K -> V}) (k : K) (v : V) (kf' : k \\in _) :\n   f.[k <- v].[kf'] = v.\nProof. by apply: Some_inj; rewrite Some_fnd fnd_set eqxx. Qed.\n\nLemma setf_get V (f : {fmap K -> V}) (k : domf f) :\n  f.[val k <- f k] = f.\nProof. by apply/fmapP=> k'; rewrite fnd_set Some_fnd; case: eqP => [->|]. Qed.\n\nLemma setfNK V (f : {fmap K -> V}) (k k' : K) (v : V)\n      (k'f : k' \\in _) (k'f' : k' \\in _):\n   f.[k <- v].[k'f'] = if k' == k then v else f.[k'f].\nProof. by apply: Some_inj; rewrite Some_fnd !fnd_set in_fnd; case: ifP. Qed.\n\nEnd FinMapTheory.\n\nSection ReduceOp.\n\nVariable (K : choiceType) (V : Type).\nImplicit Types (f : {fmap K -> option V}).\n\nLemma reducef_subproof f (x : [fset x : domf f | f x]) :\n  f (fincl (FSet_sub _) x).\nProof.\nset y := (y in f y); suff : val y \\in [fset x : domf f | f x].\n  by rewrite val_in_fset.\nby suff -> : val y = val x by exact: valP.\nQed.\n\nDefinition reducef f : {fmap K -> V} :=\n  [fmap x => oextract (@reducef_subproof f x)].\n\nLemma domf_reduce f : domf (reducef f) = [fset k : domf f | f k].\nProof. by []. Qed.\n\nLemma mem_reducef f k : k \\in reducef f = ojoin f.[? k].\nProof.\nrewrite inE; case: fndP => [kf|] /=; first by rewrite in_FSet.\nby apply: contraNF; apply: (fsubsetP (FSet_sub _)).\nQed.\n\nLemma fnd_reducef f k : (reducef f).[? k] = ojoin f.[? k].\nProof.\ncase: fndP => /= [kf|]; last by rewrite mem_reducef; case: ojoin.\nrewrite ffunE /= Some_oextract; apply: Some_inj; rewrite Some_fnd.\nby rewrite Some_ojoin // ojoinT // -mem_reducef.\nQed.\n\nLemma get_reducef f k (krf : k \\in reducef f) (kf : k \\in f):\n  Some (reducef f).[krf] = f.[kf].\nProof. by rewrite Some_fnd fnd_reducef in_fnd. Qed.\n\nEnd ReduceOp.\n\nArguments reducef : simpl never.\n\nSection RestrictionOps.\n\nVariable (K : choiceType) (V : Type).\nImplicit Types (f g : {fmap K -> V}).\n\nDefinition filterf f (P : pred K) : {fmap K -> V} :=\n   [fmap x : [fset x in domf f | P x] => f (fincl (FSet_sub _) x)].\n\nDefinition restrictf f (A : {fset K}) : {fmap K -> V} :=\n  filterf f (mem A).\n\nNotation \"x .[& A ]\" := (restrictf x A) : fmap_scope.\nNotation \"x .[\\ A ]\" := (x.[& domf x `\\` A]) : fmap_scope.\nNotation \"x .[~ k ]\" := (x.[\\ [fset k]]) : fmap_scope.\n\nLemma domf_filterf f (P : pred K) :\n domf (filterf f P) = [fset k in domf f | P k].\nProof. by []. Qed.\n\nLemma mem_filterf f (P : pred K) (k : K) :\n  (k \\in domf (filterf f P)) = (k \\in f) && (P k) :> bool.\nProof. by rewrite in_fset. Qed.\n\nLemma mem_restrictf f (A : {fset K}) (k : K) :\n   k \\in f.[& A] = (k \\in A) && (k \\in f) :> bool.\nProof. by rewrite mem_filterf andbC. Qed.\n\nLemma mem_remf f (A : {fset K}) (k : K) :\n   k \\in f.[\\ A] = (k \\notin A) && (k \\in f) :> bool.\nProof. by rewrite mem_restrictf in_fsetE -andbA andbb. Qed.\n\nLemma mem_remf1 f (k' k : K) :\n   k \\in f.[~ k'] = (k != k') && (k \\in f) :> bool.\nProof. by rewrite mem_remf in_fsetE. Qed.\n\nLemma domf_restrict f A : domf f.[& A] = A `&` domf f.\nProof. by apply/fsetP=> k'; rewrite mem_restrictf !in_fsetE. Qed.\n\nLemma domf_rem f A : domf f.[\\ A] = domf f `\\` A.\nProof. by rewrite domf_restrict fsetIDAC fsetIid. Qed.\n\nLemma mem_remfF f (k : K) : k \\in f.[~ k] = false.\nProof. by rewrite mem_remf1 eqxx. Qed.\n\nLemma fnd_filterf f P k : (filterf f P).[? k] = if P k then f.[? k] else None.\nProof.\ncase: fndP => [kff|]; last first.\n  by rewrite in_fset => /nandP [/not_fnd->|/negPf-> //]; rewrite if_same.\nby have := kff; rewrite in_fset => /andP [kf ->]; rewrite ffunE Some_fnd.\nQed.\n\nLemma get_filterf f P k (kff : k \\in filterf f P) (kf : k \\in f) :\n  (filterf f P).[kff] = f.[kf].\nProof.\napply: Some_inj; rewrite !Some_fnd /= fnd_filterf.\nby move: kff; rewrite in_fset => /andP [? ->].\nQed.\n\nLemma fnd_restrict f A (k : K) :\n   f.[& A].[? k] = if k \\in A then f.[? k] else None.\nProof. by rewrite fnd_filterf. Qed.\n\nLemma fnd_rem f A (k : K) : f.[\\ A].[? k] = if k \\in A then None else f.[? k].\nProof.\nrewrite fnd_restrict in_fsetE.\nby case: fndP => ?; rewrite ?(andbT, andbF) //=; case: (_ \\in _).\nQed.\n\nLemma restrictf_comp f A B : f.[& A].[& B] = f.[& A `&` B].\nProof.\nby apply/fmapP=> k; rewrite !fnd_restrict !in_fsetE; do !case: (_ \\in _).\nQed.\n\nLemma remf_comp f A B : f.[\\ A].[\\ B] = f.[\\ A `|` B].\nProof. by apply/fmapP=> k; rewrite !fnd_rem in_fsetE; do !case: (_ \\in _). Qed.\n\nLemma restrictfT f : f.[& domf f] = f.\nProof. by apply/fmapP=> k; rewrite fnd_restrict; case: fndP. Qed.\n\nLemma restrictf0 f : f.[& fset0] = [fmap].\nProof. by apply/fmapP => k; rewrite fnd_restrict !(in_fsetE, not_fnd). Qed.\n\nLemma remf0 f : f.[\\ fset0] = f. Proof. by rewrite fsetD0 restrictfT. Qed.\n\nLemma fnd_rem1 f (k k' : K) :\n  f.[~ k].[? k'] = if k' != k then f.[? k'] else None.\nProof. by rewrite fnd_rem in_fsetE; case: eqP. Qed.\n\nLemma getf_restrict f A (k : K) (kf : k \\in f) (kfA : k \\in f.[& A]) :\n      f.[& A].[kfA] = f.[kf].\nProof. by rewrite get_filterf. Qed.\n\nLemma setf_restrict f A (k : K) (v : V) :\n  f.[& A].[k <- v] = f.[k <- v].[& k |` A].\nProof.\nby apply/fmapP=> k'; rewrite !(fnd_set, fnd_restrict, in_fsetE); case: eqP.\nQed.\n\nLemma setf_rem f A (k : K) (v : V) :\n  f.[\\ A].[k <- v] = f.[k <- v].[\\ (A `\\ k)].\nProof. by rewrite setf_restrict fsetUDl. Qed.\n\nLemma setf_rem1 f (k : K) (v : V) : f.[~ k].[k <- v] = f.[k <- v].\nProof. by rewrite setf_rem fsetDv remf0. Qed.\n\nLemma setfC f k1 k2 v1 v2 : f.[k1 <- v1].[k2 <- v2] =\n   if k2 == k1 then f.[k2 <- v2] else f.[k2 <- v2].[k1 <- v1].\nProof.\napply/fmapP => k. rewrite fnd_if !fnd_set.\nhave [[->|kNk2] [// <-|k2Nk1]] // := (altP (k =P k2), altP (k2 =P k1)).\nby rewrite (negPf kNk2).\nQed.\n\nLemma restrictf_mkdom f A : f.[& A] = f.[& domf f `&` A].\nProof.\napply/fmapP=> k; rewrite !fnd_restrict in_fsetE.\nby case: fndP => ?; rewrite ?(andbT, andbF) //=; case: (_ \\in _).\nQed.\n\nLemma restrictf_id f A : [disjoint domf f & A] -> f.[& A] = [fmap].\nProof. by move=> dAf; rewrite restrictf_mkdom (eqP dAf) restrictf0. Qed.\n\nLemma remf_id f A : [disjoint domf f & A] -> f.[\\ A] = f.\nProof. by move=> /fsetDidPl ->; rewrite restrictfT. Qed.\n\nLemma remf1_id f k : k \\notin f -> f.[~ k] = f.\nProof. by move=> kNf; rewrite remf_id //= fdisjointX1. Qed.\n\nLemma restrictf_set f A (k : K) (v : V) :\n  f.[k <- v].[& A] = if k \\in A then f.[& A].[k <- v] else f.[& A].\nProof.\napply/fmapP => k' /=; rewrite !(fnd_if, fnd_set, fnd_restrict).\nby case: eqP => [->|]; do !case: ifP.\nQed.\n\nLemma remf_set f A (k : K) (v : V) :\n  f.[k <- v].[\\ A] = if k \\in A then f.[\\ A] else f.[\\ A].[k <- v].\nProof.\napply/fmapP => k' /=; rewrite !(fnd_if, fnd_rem, fnd_set, in_fsetE).\nby case: eqP => [->|]; do !case: (_ \\in _).\nQed.\n\nLemma remf1_set f (k k' : K) (v : V) :\n  f.[k' <- v].[~ k] = if k == k' then f.[~ k] else f.[~ k].[k' <- v].\nProof. by rewrite remf_set in_fsetE eq_sym. Qed.\n\nLemma setf_inj f f' k v : k \\notin f -> k \\notin f' ->\n                          f.[k <- v] = f'.[k <- v]-> f = f'.\nProof.\nmove=> kf kf' eq_fkv; apply/fmapP => k'.\nhave := congr1 (fun g => g.[? k']) eq_fkv.\nby rewrite !fnd_set; case: eqP => // ->; rewrite !not_fnd.\nQed.\n\nEnd RestrictionOps.\n\nArguments filterf : simpl never.\nArguments restrictf : simpl never.\nNotation \"x .[& A ]\" := (restrictf x A) : fmap_scope.\nNotation \"x .[\\ A ]\" := (x.[& domf x `\\` A]) : fmap_scope.\nNotation \"x .[~ k ]\" := (x.[\\ [fset k]]) : fmap_scope.\n\nSection Cat.\nVariables (K : choiceType) (V : Type).\nImplicit Types (f g : {fmap K -> V}).\n\nDefinition catf (f g : {fmap K -> V}) :=\n  [fmap k : (domf f `\\` domf g) `|` domf g=>\n          match fsetULVR (valP k) with\n            | inl kfDg => f.[fsubsetP (fsubsetDl _ _) _ kfDg]\n            | inr kg => g.[kg]\n          end].\n\nLocal Notation \"f + g\" := (catf f g) : fset_scope.\n\nLemma domf_cat f g : domf (f + g) = domf f `|` domf g.\nProof.\nby apply/fsetP=> x; rewrite !in_fsetE; case: (boolP (_ \\in _)); rewrite ?orbT.\nQed.\n\nLemma mem_catf f g k : k \\in domf (f + g) = (k \\in f) || (k \\in g).\nProof. by rewrite domf_cat in_fsetE. Qed.\n\nLemma fnd_cat f g k :\n  (f + g).[? k] = if k \\in domf g then g.[? k] else f.[? k].\nProof.\ncase: fndP => //= [kfg|]; rewrite /catf /=.\n  rewrite ffunE /=; case: fsetULVR => [kf|kg]; last by rewrite Some_fnd kg.\n  by rewrite -in_fnd; move: kf; rewrite in_fsetE => /andP[/negPf ->].\nby rewrite mem_catf => /norP [kNf kNg]; rewrite !not_fnd // if_same.\nQed.\n\nLemma catfE f g : f + g = f.[\\ domf g] + g.\nProof. by apply/fmapP=> k; rewrite !(fnd_cat, fnd_rem); case: ifP. Qed.\n\nLemma getf_catl f g k (kfg : k \\in domf (f + g))\n      (kf : k \\in domf f) : k \\notin domf g -> (f + g).[kfg] = f.[kf].\nProof.\nby move=> kNg; apply: Some_inj; rewrite Some_fnd fnd_cat (negPf kNg) in_fnd.\nQed.\n\nLemma getf_catr f g k (kfg : k \\in domf (f + g))\n      (kg : k \\in domf g) : (f + g).[kfg] = g.[kg].\nProof. by apply: Some_inj; rewrite Some_fnd fnd_cat kg in_fnd. Qed.\n\nLemma catf0 f : f + [fmap] = f.\nProof. by apply/fmapP => k; rewrite fnd_cat in_fset0. Qed.\n\nLemma cat0f f : [fmap] + f = f.\nProof.\napply/fmapP => k; rewrite fnd_cat; case: ifPn => //= kf.\nby rewrite !not_fnd ?in_fsetE.\nQed.\n\nLemma catf_setl f g k (v : V) :\n  f.[k <- v] + g = if k \\in g then f + g else (f + g).[k <- v].\nProof.\napply/fmapP=> k'; rewrite !(fnd_if, fnd_cat, fnd_set).\nby have [->|Nkk'] := altP eqP; do !case: (_ \\in _).\nQed.\n\nLemma catf_setr f g k (v : V) : f + g.[k <- v] = (f + g).[k <- v].\nProof.\napply/fmapP=> k'; rewrite !(fnd_cat, fnd_set, mem_setf, inE).\nby have [->|Nkk'] := altP eqP; do !case: (_ \\in _).\nQed.\n\nLemma restrictf_cat f g A : (f + g).[& A] = f.[& A] + g.[& A].\nProof.\napply/fmapP => k'; rewrite !(fnd_cat, fnd_restrict) mem_restrictf.\nby case: (_ \\in _).\nQed.\n\nLemma restrictf_cat_domr f g : (f + g).[& domf g] = g.\nProof.\nrewrite catfE restrictf_cat restrictf_comp.\nby rewrite fsetIDAC fsetDIl fsetDv fsetI0 restrictf0 restrictfT cat0f.\nQed.\n\nLemma remf_cat f g A : (f + g).[\\ A] = f.[\\ A] + g.[\\ A].\nProof.\nby apply/fmapP => k'; rewrite !(fnd_cat, fnd_rem) mem_remf; case: (_ \\in _).\nQed.\n\nLemma catf_restrictl A f g : f.[& A] + g = (f + g).[& A `|` domf g].\nProof.\napply/fmapP=> k; rewrite !(fnd_cat, fnd_restrict) !in_fsetE.\nby do !case: (_ \\in _).\nQed.\n\nLemma catf_reml A f g : f.[\\ A] + g = (f + g).[\\ A `\\` domf g].\nProof.\nby apply/fmapP=> k; rewrite !(fnd_cat, fnd_rem) in_fsetE; case: (_ \\in _).\nQed.\n\nLemma catf_rem1l k f g :\n  f.[~ k] + g = if k \\in g then f + g else (f + g).[~ k].\nProof.\napply/fmapP => k'; rewrite !(fnd_if, fnd_cat, fnd_rem1).\nby have [->|?] := altP eqP; do !case: (_ \\in _).\nQed.\n\nLemma setf_catr f g k (v : V) : (f + g).[k <- v] = f + g.[k <- v].\nProof. by rewrite catf_setr. Qed.\n\nLemma setf_catl f g k (v : V) : (f + g).[k <- v] = f.[k <- v] + g.[~ k].\nProof. by rewrite catf_setl mem_remf1 eqxx /= !setf_catr setf_rem1. Qed.\n\nLemma catfA f g h : f + (g + h) = f + g + h.\nProof.\nby apply/fmapP => k; rewrite !fnd_cat !mem_catf; do !case: (_ \\in _).\nQed.\n\nLemma catfC f g : f + g = g + f.[\\ domf g].\nProof.\napply/fmapP=> k; rewrite !fnd_cat fnd_rem domf_rem in_fsetE.\nby have [|kNg] //= := boolP (_ \\in domf g); rewrite (not_fnd kNg); case: fndP.\nQed.\n\nLemma disjoint_catfC f g : [disjoint domf f & domf g] -> f + g = g + f.\nProof. by move=> dfg; rewrite catfC remf_id. Qed.\n\nLemma catfAC f g h : f + g + h = f + h + g.[\\ domf h].\nProof. by rewrite -!catfA [X in _ + X]catfC. Qed.\n\nLemma disjoint_catfAC f g h : [disjoint domf g & domf h]%fmap ->\n     f + g + h = f + h + g.\nProof. by move=> dgh; rewrite catfAC remf_id. Qed.\n\nLemma catfCA f g h : f + (g + h) = g + (f.[\\ domf g] + h).\nProof. by rewrite !catfA [X in X + _]catfC. Qed.\n\nLemma disjoint_catfCA f g h : [disjoint domf f & domf g]%fmap ->\n     f + (g + h) = g + (f + h).\nProof. by move=> dfg; rewrite catfCA remf_id. Qed.\n\nLemma catfIs f g h : f + h = g + h -> f.[\\ domf h] = g.[\\ domf h].\nProof.\nmove=> /fmapP eq_fg_fh; apply/fmapP => k; have := eq_fg_fh k.\nby rewrite !fnd_cat !fnd_rem; case: ifP.\nQed.\n\nLemma disjoint_catfIs h f g :\n  [disjoint domf f & domf h] -> [disjoint domf g & domf h] ->\n  f + h = g + h -> f = g.\nProof. by move=> dfg dgh /catfIs; rewrite !remf_id. Qed.\n\nLemma restrict_catfsI f g h : f + g = f + h -> g.[& domf h] = h.[& domf g].\nProof.\nmove=> /fmapP eq_fg_fh; apply/fmapP => k; have := eq_fg_fh k.\nrewrite !fnd_cat !fnd_restrict.\nby do ![case: (boolP (_ \\in _)) => ? //=] => _; rewrite not_fnd.\nQed.\n\nLemma disjoint_catfsI h f g :\n  [disjoint domf f & domf h] -> [disjoint domf g & domf h] ->\n  h + f = h + g -> f = g.\nProof.\nmove=> dfg dgh; rewrite -disjoint_catfC // -[RHS]disjoint_catfC //.\nby apply: disjoint_catfIs.\nQed.\n\nEnd Cat.\n\nArguments catf : simpl never.\nNotation \"f + g\" := (catf f g) : fset_scope.\n\nSection FinMapKeyType.\n\nVariables (K V : choiceType).\nImplicit Types (f g : {fmap K -> V}).\n\nDefinition codomf f : {fset V} := [fset f k | k : domf f].\n\nLemma mem_codomf f v : (v \\in codomf f) = [exists x : domf f, f x == v].\nProof.\napply: sameP existsP.\nby apply: (iffP (imfsetP _ _ _)) => /= [[x _ ->]|[x /eqP <-]]; exists x.\nQed.\n\nLemma codomfP f v : reflect (exists x, f.[? x] = Some v) (v \\in codomf f).\nProof.\napply: (iffP (imfsetP _ _ _)) => /= [[x _ ->]|[k]].\n  by exists (val x); rewrite Some_fnd.\nby case: fndP => //= kf [<-]; exists (FSetSub kf).\nQed.\n\nLemma codomfPn f v : reflect (forall x, f.[? x] != Some v) (v \\notin codomf f).\nProof.\nrewrite mem_codomf negb_exists; apply: (iffP forallP) => f_eq_v x /=.\n  by case: fndP => //= kf; rewrite f_eq_v.\nby apply: contraNneq (f_eq_v (val x)) => <-; rewrite Some_fnd.\nQed.\n\nLemma codomf0 : codomf [fmap] = fset0.\nProof.\napply/fsetP=> k; rewrite in_fsetE; apply/negP => /codomfP [k'].\nby rewrite not_fnd //= in_fsetE.\nQed.\n\nLemma in_codomf f (k : domf f) : f k \\in codomf f.\nProof. by rewrite in_imfset. Qed.\n\nLemma fndSomeP f (k : K) (v : V):\n  (f.[? k] = Some v) <-> {kf : k \\in f & f.[kf] = v}.\nProof.\nsplit => [fk|[kf fk]]; last by rewrite in_fnd fk.\nhave kf : k \\in f by rewrite -fndSome fk.\nby exists kf; apply: Some_inj; rewrite Some_fnd.\nQed.\n\nLemma codomf_restrict f (A : {fset K})  :\n  codomf f.[& A] = [fset v : codomf f\n                   | [exists k : domf f, (val k \\in A) && (f k == val v)]].\nProof.\napply/fsetP => v; apply/imfsetP/imfsetP => [[k _ ->]|[v' v'_in ->]].\n  have k_in_res := valP k.\n  have [k_in_dom k_inA] : val k \\in domf f /\\ val k \\in A.\n    by move: k_in_res; rewrite in_fsetE => /andP.\n  exists (FSetSub ((@in_codomf _).[k_in_dom])); rewrite ?inE /=.\n    by apply/existsP; exists (FSetSub k_in_dom); rewrite ?k_inA /=.\n  by rewrite ffunE /=; rewrite -getfE.\nmove: v'_in; rewrite inE => /existsP [k /andP [kA /eqP <-]].\nhave kfA : val k \\in domf f.[& A] by rewrite in_fsetE /= (valP k).\nexists (FSetSub kfA); rewrite ?inE //= ?ffunE //=.\nby apply: Some_inj; rewrite !Some_fnd.\nQed.\n\nLemma codomf_restrictE f (A : {fset K})  :\n  codomf f.[& A] = [fset f (fincl (fsubsetIr _ _) k) | k : A `&` domf f].\nProof.\napply/fsetP => v; apply/imfsetP/imfsetP => [] [k _ ->].\n  have k_in_res := valP k.\n  have k_inI : val k \\in A `&` domf f by rewrite in_fsetE -mem_restrictf.\n  have k_inA : val k \\in A by move: k_inI; rewrite in_fsetI => /andP[].\n  exists (FSetSub k_inI); rewrite ?inE //.\n  by apply: Some_inj; rewrite -getfE -!in_fnd fnd_restrict k_inA.\nhave k_inI := valP k.\nhave k_in_res : val k \\in domf f.[& A].\n  by rewrite mem_restrictf -in_fsetE.\nhave k_inA : val k \\in A by move: k_inI; rewrite in_fsetI => /andP[].\nexists (FSetSub k_in_res); rewrite ?inE //; apply: Some_inj.\nrewrite -getfE; first by move: k_inI; rewrite in_fsetE => /andP[].\nby move=> k_in_dom; rewrite -!in_fnd fnd_restrict k_inA.\nQed.\n\nLemma codomf_rem f (A : {fset K})  :\n  codomf f.[\\ A] = codomf f `\\` [fset v : codomf f\n                   | [forall k : domf f,\n                      (val k \\in A) || (f k != val v)]].\nProof.\nrewrite codomf_restrict; apply/fsetP => v; rewrite !in_fsetE.\nhave [vf|vNf] := boolP (v \\in codomf f); rewrite (andbF, andbT); last first.\n  by rewrite notin_FSet.\nrewrite !in_FSet /= -!topredE /= -[RHS]lt0n.\napply/existsP/card_gt0P => [[x]|[x]]; rewrite !(in_fsetE, inE).\n  rewrite -andbA => /and3P [xf xNA /eqP <-].\n  by exists x; rewrite inE eqxx orbF.\nrewrite negb_or negbK => /andP [xNA /eqP <-].\nby exists x; rewrite !in_fsetE xNA (valP x) eqxx.\nQed.\n\nLemma codomf_remE f (A : {fset K})  :\n  codomf f.[\\ A] = [fset f (fincl (fsubsetDl _ _) k) | k : domf f `\\` A].\nProof.\nrewrite codomf_restrictE; apply/fsetP => k.\napply/imfsetP/imfsetP => [] [k' _ ->].\n  have k'D: val k' \\in domf f `\\` A.\n    by have := valP k'; rewrite in_fsetE => /andP [].\n  by exists (FSetSub k'D); rewrite ?inE //; apply: eq_getf.\nhave k'D : val k' \\in (domf f `\\` A) `&` domf f.\n  by have := valP k'; rewrite !in_fsetE -andbA; case: (_ \\in domf _).\nby exists (FSetSub k'D); rewrite ?inE //=; apply: eq_getf.\nQed.\n\nLemma in_codomf_rem1 f (k : K) (kf : k \\in domf f)  :\n  codomf f.[~ k] =\n  if [exists k' : domf f, (val k' != k) && (f k' == f.[kf])] then codomf f\n  else codomf f `\\ f.[kf].\nProof.\ntransitivity\n  (codomf f `\\` if [exists k' : domf f, (val k' != k) && (f k' == f.[kf])]\n                then fset0 else [fset f.[kf]]); last first.\n  by case: ifP => //=; rewrite fsetD0.\nrewrite codomf_rem; apply/fsetP => v; rewrite !in_fsetE.\nhave [vf|vNf] := boolP (v \\in codomf f); rewrite ?andbF //; last first.\nrewrite !andbT; congr (~~ _); rewrite (fun_if (fun X => _ \\in X)) !in_fsetE.\nhave [->|neq_vfk] := altP eqP; last first.\n  rewrite if_same; apply: negbTE; rewrite in_FSet /= -topredE /= -lt0n.\n  case: vf => /imfsetP [k' _ ->] in neq_vfk *.\n  apply/card_gt0P; exists k'; rewrite -topredE /= in_fsetE eqxx orbF.\n  apply: contra neq_vfk => /eqP eq_kk'; apply/eqP/Some_inj.\n  by rewrite !Some_fnd /= eq_kk'.\napply: negb_inj; rewrite -/(negb _) negbK.\nrewrite in_FSet ?in_codomf // => ?; rewrite -topredE /= -lt0n.\napply/card_gt0P/existsP => [] [x fx]; exists x;\nby  move: fx; rewrite !inE negb_or in_fsetE negbK.\nQed.\n\nLemma codomf_set f (k : K) (v : V) (kf : k \\in domf f) :\n  codomf f.[k <- v] = v |` codomf f.[~ k].\nProof.\nrewrite -setf_rem1; apply/fsetP=> v'; rewrite !in_fsetE.\nhave [->|neq_v'v] /= := altP eqP.\n  by apply/codomfP; exists k; rewrite fnd_set eqxx.\napply/codomfP/codomfP => [] [k' fk'_eq]; exists k';\nmove: fk'_eq; rewrite fnd_set.\n  by have [_ [eq_vv']|//] := altP eqP; rewrite eq_vv' eqxx in neq_v'v *.\nby have [->|//] := altP eqP; rewrite fnd_rem in_fsetE eqxx.\nQed.\n\nEnd FinMapKeyType.\n", "meta": {"author": "ejgallego", "repo": "coq-alternate-reals", "sha": "8e1ad799ae9ae80d3c1d97d0a5f5b6d772eb6e01", "save_path": "github-repos/coq/ejgallego-coq-alternate-reals", "path": "github-repos/coq/ejgallego-coq-alternate-reals/coq-alternate-reals-8e1ad799ae9ae80d3c1d97d0a5f5b6d772eb6e01/finmap/finmap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6885455366555887}}
{"text": "\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n\nFixpoint half (half_arg0 : natural) : natural\n           := match half_arg0 with\n              | Zero => Zero\n              | Succ Zero => Zero\n              | Succ (Succ n) => Succ (half n)\n              end.\n\nTheorem plus_comm: forall (n m: natural), plus n m = plus m n.\nProof.\n   induction n; induction m.\n   { simpl. rewrite IHn. rewrite <- IHm. simpl. rewrite IHn. reflexivity. }\n   { simpl. rewrite IHn. simpl. reflexivity. }\n   { simpl. rewrite <- IHm. simpl. reflexivity. }\n   { reflexivity. }\nQed.\n\nTheorem theorem0 : forall (x : natural) (y : natural), eq (half (plus x y)) (half (plus y x)).\nProof.\n   intros.\n   rewrite plus_comm.\n   reflexivity.\nQed.\n\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal26.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6885455329052205}}
{"text": "Require Import Coq.ZArith.ZArith.\nLocal Open Scope Z_scope.\n\nModule Z.\n\n  Ltac push_mod_step :=\n    match goal with\n    | |- context [ (?op ?a ?b) mod ?m ] =>\n      lazymatch a with\n      | _ mod m =>\n        lazymatch b with\n        | _ mod m => fail\n        | _ => idtac\n        end\n      | _ => idtac\n      end;\n      match op with\n      | Z.add => rewrite (Zplus_mod a b m)\n      | Z.sub => rewrite (Zminus_mod a b m)\n      | Z.mul => rewrite (Zmult_mod a b m)\n      end\n    end.\n\n  Ltac push_mod := repeat push_mod_step.\n\n  Ltac mod_free t :=\n    lazymatch t with\n    | Z.modulo ?a ?b => fail \"contains\" a \"mod\" b\n    | Z.add ?a ?b => mod_free a; mod_free b\n    | Z.sub ?a ?b => mod_free a; mod_free b\n    | Z.mul ?a ?b => mod_free a; mod_free b\n    | _ => idtac\n    end.\n\n  Ltac pull_mod_step :=\n    match goal with\n    | |- context [ (?op (?a mod ?m) (?b mod ?m)) mod ?m ] =>\n      mod_free a;\n      mod_free b;\n      match op with\n      | Z.add => rewrite <- (Zplus_mod a b m)\n      | Z.sub => rewrite <- (Zminus_mod a b m)\n      | Z.mul => rewrite <- (Zmult_mod a b m)\n      end\n    end.\n\n  Ltac pull_mod := repeat pull_mod_step.\n\n  Ltac unary_to_binary_minus :=\n    repeat match goal with\n           | |- context [(- ?x)] => rewrite <- (Z.sub_0_l x)\n           end.\n\n  Ltac push_pull_mod :=\n    unary_to_binary_minus;\n    push_mod;\n    rewrite? Zmod_mod;\n    pull_mod.\n\n  Ltac mod_equality :=\n    push_pull_mod;\n    solve [repeat (ring || f_equal)].\n\nEnd Z.\n\n(* Useful for debugging parenthesis around mod:\nNotation \"[ a ]_ m\" := (a mod m) (at level 20, format \"[ a ]_ m\").\n*)\n\nGoal forall v B M lo, (v + B) mod M =\n  ((((v + B) mod M - B - lo + B) mod M - B + B) mod M - B + ((lo + B) mod M - B) + B) mod M.\nProof.\n  intros.\n  Z.mod_equality.\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/PushPullMod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6885455298102832}}
{"text": "Require Import Arith.\n\nGoal forall x y, x < y -> x + 10 < y + 10.\nProof.\nintros.\napply plus_lt_compat_r.\napply H.\nQed.", "meta": {"author": "ashiato45", "repo": "CoqEx2014", "sha": "83750632bf6a78db93ed493a739b4aeae8505df1", "save_path": "github-repos/coq/ashiato45-CoqEx2014", "path": "github-repos/coq/ashiato45-CoqEx2014/CoqEx2014-83750632bf6a78db93ed493a739b4aeae8505df1/2/6_plus_lt_compat_r.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6885200997631336}}
{"text": "(*|\n###################################\nGeneralising a set of proofs in Coq\n###################################\n\n:Link: https://stackoverflow.com/q/53204593\n|*)\n\n(*|\nQuestion\n********\n\nI am trying to complete the first part lab of the 6.826 MIT course,\nbut I am unsure about a comment above one of the exercises that says I\ncan solve a bunch of examples using the same proof. here is what i\nmean:\n|*)\n\nRequire Import FunInd. (* .none *)\n(* A `nattree` is a tree of natural numbers, where every internal node\n   has an associated number and leaves are empty. There are two\n   constructors, L (empty leaf) and I (internal node). I's arguments\n   are: left-subtree, number, right-subtree. *)\nInductive nattree : Set :=\n| L : nattree                               (* Leaf *)\n| I : nattree -> nat -> nattree -> nattree. (* Internal nodes *)\n\n(* Some example nattrees. *)\nDefinition empty_nattree := L.\nDefinition singleton_nattree := I L 0 L.\nDefinition right_nattree := I L 0 (I L 1 (I L 2 (I L 3 L))).\nDefinition left_nattree := I (I (I (I L 0 L) 1 L) 2 L) 3 L.\nDefinition balanced_nattree := I (I L 0 (I L 1 L)) 2 (I L 3 L).\nDefinition unsorted_nattree := I (I L 3 (I L 1 L)) 0 (I L 2 L).\n\n(* EXERCISE: Complete this proposition, which should be `True` iff `x`\n   is located somewhere in `t` (even if `t` is unsorted, i.e., not a\n   valid binary search tree). *)\nFunction btree_in (x : nat) (t : nattree) : Prop :=\n  match t with\n  | L => False\n  | I l n r => n = x \\/ btree_in x l \\/ btree_in x r\n  end.\n\n(* EXERCISE: Complete these examples, which show `btree_in` works.\n   Hint: The same proof will work for every example. End each example\n   with `Qed.`. *)\nExample btree_in_ex1 : ~ btree_in 0 empty_nattree.\nProof.\n  simpl. auto.\nQed.\nExample btree_in_ex2 : btree_in 0 singleton_nattree.\nProof.\n  simpl. auto.\nQed.\nExample btree_in_ex3 : btree_in 2 right_nattree.\nProof.\n  simpl. right. auto.\nQed.\nExample btree_in_ex4 : btree_in 2 left_nattree.\nProof.\n  simpl. right. auto.\nQed.\nExample btree_in_ex5 : btree_in 2 balanced_nattree.\nProof.\n  simpl. auto.\nQed.\nExample btree_in_ex6 : btree_in 2 unsorted_nattree.\nProof.\n  simpl. auto.\nQed.\nExample btree_in_ex7 : ~ btree_in 10 balanced_nattree.\nProof.\n  simpl. intros G. destruct G. inversion H. destruct H. destruct H. inversion H.\n  destruct H. inversion H. destruct H. inversion H. destruct H. inversion H.\n  destruct H. destruct H. inversion H. destruct H. inversion H. destruct H.\nQed.\nExample btree_in_ex8 : btree_in 3 unsorted_nattree.\nProof.\n  simpl. auto.\nQed.\n\n(*|\nThe code under the comments ``EXERCISE`` have been completed as an\nexercise (though ``ex7`` required some googling...), the hint for the\nsecond exercise says 'Hint: The same proof will work for every\nexample.' but i'm unsure how to write a proof for each one that isn't\nspecific to that case.\n\nThe course material in question can be found here:\nhttp://6826.csail.mit.edu/2017/lab/lab0.html\n\nAs a beginner with Coq I'd appreciate being steered in the right\ndirection as opposed to just being given a solution. If there is a\nparticular tactic that would be useful here that I am perhaps missing\nit would be good to be pointed towards that...\n|*)\n\n(*|\nAnswer\n******\n\nI think you're just missing the ``intuition`` tactic, which ``intro``\\\ns hypotheses when it sees ``A -> B``, unfolds ``~ P`` to ``P ->\nFalse`` and ``intro``'s that, splits ``/\\``\\ s and ``\\/``\\ s in the\nhypotheses, breaks ``/\\``\\ s in the goal into multiple subgoals, and\nuses ``auto`` to search both branches of ``\\/``\\ s in the goal. That\nmay seem like a lot but note that these are all basic strategies from\nlogic (other than the call to ``auto``).\n\nAfter you run simpl on each of these exercises you'll see it fits this\nform and then ``intuition`` will work.\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/generalising-a-set-of-proofs-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.6884922930700225}}
{"text": "From LF Require Export Induction.\nFrom LF Require Export Basics.\n\n\nModule NatList.\n\n\n(* ## Pairs of Numbers *)\n\nInductive natprod : Type :=\n| pair (n1 n2 : nat).\n\nDefinition fst (p : natprod) : nat :=\nmatch p with\n| pair x y => x\nend.\n\nDefinition snd (p : natprod) : nat :=\nmatch p with\n| pair x y => y\nend.\n\nDefinition swap_pair (p : natprod) : natprod :=\nmatch p with\n| pair x y => pair y x\nend.\n\nNotation \"( x , y )\" := (pair x y).\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\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.\n  destruct p as [x y].\n  simpl.\n  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 [x y].\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 [x y].\n  simpl.\n  reflexivity.\nQed.\n\n(* # Lists of Numbers *)\n\nInductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\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                     (right associativity, at level 60).\n\nDefinition hd (default:nat) (l:natlist) : nat :=\nmatch l with\n| nil => default\n| h :: t => h\nend.\n\nDefinition tl (l:natlist) : natlist :=\nmatch l with\n| nil => nil\n| h :: t => t\nend.\n\nFixpoint nonzeros (l:natlist) : natlist :=\nmatch l with\n| nil => nil\n| cons O t => (nonzeros t)\n| cons x t => x :: (nonzeros t)\nend.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n  simpl. reflexivity.\nQed.\n\n\nFixpoint oddmembers (l:natlist) : natlist :=\nmatch l with\n| nil => nil\n| h :: t => if(oddb h) then h :: oddmembers t else oddmembers t\nend.\n\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\n  simpl.\n  reflexivity.\nQed.\n\nDefinition countoddmembers (l:natlist) : nat := length (oddmembers l).\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\n  simpl.\n  reflexivity.\nQed.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\nmatch l1, l2 with\n| nil, nil => nil\n| nil, _ => l2\n| _, nil => l1\n| h :: t, h' :: t' => h :: h' :: (alternate t t')\nend.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof.\nreflexivity.\nQed.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof.\nreflexivity.\nQed.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof.\nreflexivity.\nQed.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof.\nreflexivity.\nQed.\n\nDefinition bag := natlist.\n\nFixpoint filter (v:nat) (s:bag) : bag :=\nmatch s with\n| nil => nil\n| h :: t => if eqb h v then h :: filter v t else filter v t\nend.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => O\n  | h :: t => if(eqb h v) then 1 + (count v t) else count v t \nend.\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof.\n reflexivity.\nQed.\n\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof.\n  reflexivity.\nQed.\n\nDefinition sum : bag -> bag -> bag :=\n  fun l1 l2 => l1 ++ l2.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\n simpl. reflexivity.\nQed.\n\nDefinition add (v:nat) (s:bag) : bag :=\n  (v :: nil) ++ s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\n  reflexivity.\nQed.\n\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\n  simpl. reflexivity.\nQed.\n\nDefinition member (v:nat) (s:bag) : bool :=\nmatch (count v s) with\n| O => false\n| S n => true\nend.\n\nExample test_member1: member 1 [1;4;1] = true.\nreflexivity.\nQed.\n\nExample test_member2: member 2 [1;4;1] = false.\nreflexivity.\nQed.\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\nmatch s with\n| nil => nil\n| h :: t => if(eqb v h) then t else h :: remove_one v t\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\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\nmatch s with\n| nil => nil\n| h :: t => if(eqb v h) then remove_all v t else h :: remove_all v t\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 exist (v:nat) (s:bag) : bool :=\n  match s with\n  | nil => false\n  | h :: t => if (eqb v h) then true else exist v t\nend.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n  | nil => true\n  | h :: t => if exist h s2 then subset t (remove_one h s2) else false\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,\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  - (* l = nil *)\n    reflexivity.\n  - (* l = cons n l' *)\n  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.\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.\nintros l1 l2.\ninduction l1 as [| n l1' IHl1'].\n- (* l1 = nil *)\n  reflexivity.\n- (* l1 = cons *)\n  simpl. rewrite -> IHl1'. 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\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.\n  rewrite -> IHl'.\n  reflexivity.\nQed.\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\nintros l.\ninduction l as [| n l' IHl'].\n- simpl. reflexivity.\n- simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros l1 l2.\n  induction l1 as [| n l1' IHl1'].\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IHl1'. apply app_assoc.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l.\n  induction l as [| n l' IHl].\n  - reflexivity.\n  - simpl.\n    rewrite -> rev_app_distr.\n    rewrite -> IHl.\n    reflexivity.\nQed.\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\nintros l1 l2 l3 l4.\nrewrite -> app_assoc.\nrewrite -> app_assoc.\nreflexivity.\nQed.\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\nintros l1 l2. induction l1 as [| n1 l1'].\n\n- reflexivity.\n- simpl.\n  rewrite -> IHl1'.\n  destruct n1 as [| n1'].\n  + reflexivity.\n  + reflexivity.\nQed.\n\n\nFixpoint eqblist (l1 l2 : natlist) : bool :=\nmatch l1, l2 with\n| nil, nil => true\n| nil, _ => false\n| _, nil => false\n| h :: t, h' :: t' => if eqb h h' then eqblist t t' else false\nend.\n\nExample test_beq_natlist1 :\n  (eqblist nil nil = true).\nProof. reflexivity. Qed.\n\nExample test_beq_natlist2 :\n  eqblist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\nExample test_beq_natlist3 :\n  eqblist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem eqblist_refl : forall l:natlist,\n  true = eqblist l l.\nProof.\n  intros l.\n  induction l as [| n l'].\n  - reflexivity.\n  - { induction n.\n    - simpl. rewrite <- IHl'. reflexivity.\n    - rewrite -> IHn. simpl. reflexivity. }\nQed.\n\nTheorem count_member_nonzero : forall (s : bag),\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\nintros s. 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    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  intros s. induction s.\n  - simpl. reflexivity.\n  - simpl. { induction n.\n             - simpl. rewrite leb_n_Sn. reflexivity.\n             - simpl. rewrite IHs. reflexivity. \n           }\nQed.\n\n\n(* Options *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\nmatch 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\nend.\n\nInductive natoption : Type :=\n| Some (n : nat)\n| None.\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\nmatch l with\n| nil => None\n| a :: l' => if n =? O then Some a\n             else nth_error l' (pred n)\nend.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nsimpl. reflexivity.\nQed.\n\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nsimpl. reflexivity.\nQed.\n\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nsimpl. reflexivity.\nQed.\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 :=\n  match l with\n  | nil => None\n  | a :: l => Some a\nend.\n\nExample test_hd_error1 : hd_error [] = None.\nreflexivity.\nQed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nreflexivity.\nQed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nreflexivity.\nQed.\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n intros l def. induction l as [| n l' IHl].\n  - reflexivity.\n  - reflexivity.\nQed.\n\n\n\n\n\n(* Partial Maps *)\n\nInductive id : Type :=\n  | Id (n : nat).\n\nDefinition eqb_id (x1 x2 : id) :=\nmatch x1, x2 with\n| Id n1, Id n2 => n1 =? n2\nend.\n\nTheorem eqb_id_refl : forall x, true = eqb_id x x.\nProof.\nintros x.\ndestruct x.\nsimpl.\nSearch \"nat_refl\".\napply eqb_nat_refl.\nQed.\n\nModule PartialMap.\n\nInductive partial_map : Type :=\n  | empty\n  | record (i : id) (v : nat) (m : partial_map).\n\nDefinition update (d : partial_map)\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\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 k 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 k v o H.\n  simpl.\n  rewrite H.\n  reflexivity.\nQed.\n\n\nEnd PartialMap.\n\nInductive baz : Type :=\n  | Baz1 (x : baz)\n  | Baz2 (y : baz) (b : bool).\n\nEnd NatList.", "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/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.8397339676722394, "lm_q1q2_score": 0.6884922840347019}}
{"text": "Require Import Overture.\nSet Universe Polymorphism.\n\nSet Implicit Arguments.\nGeneralizable All Variables.\n\n\nDelimit Scope morphism_scope with morphism.\nDelimit Scope category_scope with category.\nDelimit Scope object_scope with object.\n\nLocal Open Scope morphism_scope.\n\nReserved Notation \"f ∘ g\" (at level 40, left associativity).\n\nRecord Category : Type :=\n  Build_Category' {\n      object :> Type;\n      morphism : object -> object -> Type;\n\n      identity : forall x, morphism x x;\n      compose : forall s d d',\n          morphism d d'\n          -> morphism s d\n          -> morphism s d'\n      where \"f ∘ g\" := (compose f g);\n\n      associativity : forall x1 x2 x3 x4\n                             (m1 : morphism x1 x2)\n                             (m2 : morphism x2 x3)\n                             (m3 : morphism x3 x4),\n          (m3 ∘ m2) ∘ m1 ≡ m3 ∘ (m2 ∘ m1);\n\n      associativity_sym : forall x1 x2 x3 x4\n                                 (m1 : morphism x1 x2)\n                                 (m2 : morphism x2 x3)\n                                 (m3 : morphism x3 x4),\n          m3 ∘ (m2 ∘ m1) ≡ (m3 ∘ m2) ∘ m1;\n\n      left_identity : forall a b (f : morphism a b), identity b ∘ f ≡ f;\n      right_identity : forall a b (f : morphism a b), f ∘ identity a ≡ f;\n\n      identity_identity : forall x, identity x ∘ identity x ≡ identity x\n    }.\n\nBind Scope category_scope with Category.\nBind Scope object_scope with object.\nBind Scope morphism_scope with morphism.\n\nArguments object !C%category / : rename.\nArguments morphism !C%category / s d : rename.\nArguments identity {!C%category} / x%object : rename.\nArguments compose {!C%category} / {s d d'}%object (m1 m2)%morphism : rename.\n\nGlobal Infix \"∘\" := compose : morphism_scope.\nGlobal Notation \"x --> y\" := (morphism _ x y) (at level 99, right associativity, y at level 200) : type_scope.\nGlobal Notation \"1\" := (identity _) : morphism_scope.\n\nDefinition Build_Category\n           object morphism compose identity\n           associativity left_identity right_identity\n  := @Build_Category'\n       object\n       morphism\n       compose\n       identity\n       associativity\n       (fun _ _ _ _ _ _ _ => Einverse (associativity _ _ _ _ _ _ _))\n       left_identity\n       right_identity\n       (fun _ => left_identity _ _ _).\n\n\nDefinition TYPE : Category.\nProof.\n  rapply Build_Category.\n  - exact Type.\n  - exact (λ A B, A -> B).\n  - exact (λ A, idmap).\n  - exact (λ A B C g f, g o f).\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nDefined.\n\n(* Lifting property between f and g *)\nDefinition LP {C: Category} {x y: C} (f: x --> y) {x' y': C} (g: x' --> y')\n  := ∀ (F: x --> x') (G: y --> y'), g ∘ F ≡ G ∘ f -> ∃ (Ɣ: y --> x'), (Ɣ ∘ f ≡ F) × (g ∘ Ɣ ≡ G).\n\nDefinition LLP {C: Category} (R: ∀ {x y: C}, (x --> y) -> Type) {x y: C} (f: x --> y)\n  := ∀ x' y' (g: x' --> y'), R g -> LP f g.\n\nDefinition RLP {C: Category} (L: ∀ {x y: C}, (x --> y) -> Type) {x' y': C} (g: x' --> y')\n  := ∀ x y (f: x --> y), L f -> LP f g.\n\nDefinition LLP_functor {C: Category} (R R': ∀ {x y: C}, (x --> y) -> Type)\n           (RR': ∀ x y (f: x --> y), R f -> R' f)\n           {x y: C} (f: x --> y)\n  : LLP (@R') f -> LLP (@R) f.\nProof.\n  intros H x' y' g Hg. apply H. apply RR'; assumption.\nDefined.\n\nDefinition RLP_functor {C: Category} (L L': ∀ {x y: C}, (x --> y) -> Type)\n           (LL': ∀ x y (f: x --> y), L f -> L' f)\n           {x y: C} (f: x --> y)\n  : RLP (@L') f -> RLP (@L) f.\nProof.\n  intros H x' y' g Hg. apply H. apply LL'; assumption.\nDefined.\n\nRecord weak_factorization_system {C: Category} (L R: ∀ {x y: C}, (x --> y) -> Type) :=\n  { facto: ∀ (x z: C) (f: x --> z),\n      ∃ y (g: x --> y) (h: y --> z), (h ∘ g ≡ f) × L g × R h;\n    LLP_R: ∀ (x y: C) (f: x --> y), L f <-> LLP (@R) f;\n    RLP_L: ∀ (x y: C) (f: x --> y), R f <-> RLP (@L) f\n  }.\n\nDefinition wfs_iff_R {C: Category} (L R R': ∀ {x y: C}, (x --> y) -> Type)\n           (H: ∀ x y (f: x --> y), R f <-> R' f)\n           (W: weak_factorization_system (@L) (@R))\n  : weak_factorization_system (@L) (@R').\nProof.\n  destruct W. use Build_weak_factorization_system.\n  - intros x z f. destruct (facto0 x z f) as [y [g [h [H1 [H2 H3]]]]].\n    ref (y; (g; h; (H1, (H2, _)))). now apply H.\n  - intros x y f; split; intro H1.\n    + eapply LLP_functor. apply H.\n      apply LLP_R0. assumption.\n    + apply LLP_R0. eapply LLP_functor.\n      apply H. assumption.\n  - intros x y f; split; intro H1.\n    + apply RLP_L0. apply H. assumption.\n    + apply H. eapply RLP_L0. assumption.\nDefined.      \n  \n\nDefinition wfs_iff_L {C: Category} (L L' R: ∀ {x y: C}, (x --> y) -> Type)\n           (H: ∀ x y (f: x --> y), L f <-> L' f)\n           (W: weak_factorization_system (@L) (@R))\n  : weak_factorization_system (@L') (@R).\nProof.\n  destruct W. use Build_weak_factorization_system.\n  - intros x z f. destruct (facto0 x z f) as [y [g [h [H1 [H2 H3]]]]].\n    ref (y; (g; h; (H1, (_, H3)))). now apply H.\n  - intros x y f; split; intro H1.\n    + apply LLP_R0. apply H. assumption.\n    + apply H. eapply LLP_R0. assumption.\n  - intros x y f; split; intro H1.\n    + eapply RLP_functor. apply H.\n      apply RLP_L0. assumption.\n    + apply RLP_L0. eapply RLP_functor.\n      apply H. assumption.\nDefined.      \n\n\nDefinition two_out_of_three {C: Category} (W: ∀ {x y: C}, (x --> y) -> Type)\n  := ∀ (x y z: C) (f: x --> y) (g: y --> z),\n    (W f -> W g -> W (g ∘ f)) × (W g -> W (g ∘ f) -> W f) × (W (g ∘ f) -> W f -> W g).\n\nRecord model_structure (C: Category) :=\n  { W: ∀ {x y: C}, (x --> y) -> Type;\n    F: ∀ {x y: C}, (x --> y) -> Type;\n    C: ∀ {x y: C}, (x --> y) -> Type;\n    tot: two_out_of_three (@W);\n    C_AF: weak_factorization_system (@C) (λ x y f, W f × F f);\n    AC_F: weak_factorization_system (λ x y f, W f × C f) (@F)\n  }.", "meta": {"author": "SimonBoulier", "repo": "ModelStructure-HTS", "sha": "824474431577e3f998c2c293d5d32c1762d75680", "save_path": "github-repos/coq/SimonBoulier-ModelStructure-HTS", "path": "github-repos/coq/SimonBoulier-ModelStructure-HTS/ModelStructure-HTS-824474431577e3f998c2c293d5d32c1762d75680/Category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6884225670213033}}
{"text": "\n(** * Typy hybrydowe *)\n\n(** Ostatnim z typów istotnych z punktu widzenia silnych specyfikacji\n    jest typ o wdzięcznej nazwie [sumor]. *)\n\nModule sumor.\n\nInductive sumor (A : Type) (B : Prop) : Type :=\n| inleft : A -> sumor A B\n| inright : B -> sumor A B.\n\n(** Jak sama nazwa wskazuje, [sumor] jest hybrydą sumy rozłącznej [sum]\n    oraz dysjunkcji [or]. Możemy go interpretować jako typ, którego\n    elementami są elementy [A] albo wymówki w stylu \"nie mam elementu [A],\n    ponieważ zachodzi zdanie [B]\". [B] nie zależy od [A], a więc jest to\n    zwykła suma (a nie suma zależna, czyli uogólnienie produktu). [sumor]\n    żyje w [Type], a więc jest to specyfikacja i liczy się konkretna\n    postać jego termów, a nie jedynie fakt ich istnienia. *)\n\n(** **** Ćwiczenie ([pred']) *)\n\n(** Zdefiniuj funkcję [pred'], która przypisuje liczbie naturalnej jej\n    poprzednik. Poprzednikiem [0] nie powinno być [0]. Mogą przydać ci\n    się typ [sumor] oraz sposób definiowania za pomocą taktyk, omówiony\n    w podrozdziale dotyczącym sum zależnych. *)\n\n(* begin hide *)\nDefinition pred' (n : nat) : sumor nat (n = 0) :=\nmatch n with\n| 0 => inright _ _ eq_refl\n| S n' => inleft _ _ n'\nend.\n(* end hide *)\n\nEnd sumor.", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/code/IndRec/Hybrydy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6884225504304495}}
{"text": "Require Import Basics.\nRequire Import Types.\nRequire Import Pointed.Core.\n\nLocal Open Scope pointed_scope.\n\n(* pointed homotopy is a reflexive relation *)\nGlobal Instance phomotopy_reflexive {A B} : Reflexive (@pHomotopy A B).\nProof.\n  intro.\n  serapply Build_pHomotopy.\n  + intro. reflexivity.\n  + apply concat_1p.\nDefined.\n\n(** ** Whiskering of pointed homotopies by pointed functions *)\n\nDefinition pmap_postwhisker {A B C : pType} {f g : A ->* B}\n  (h : B ->* C) (p : f ==* g) : h o* f ==* h o* g.\nProof.\n  pointed_reduce.\n  simple refine (Build_pHomotopy _ _); cbn.\n  - intros a; apply ap, p.\n  - reflexivity.\nQed.\n\nDefinition pmap_prewhisker {A B C : pType} (f : A ->* B)\n  {g h : B ->* C} (p : g ==* h) : g o* f ==* h o* f.\nProof.\n  pointed_reduce.\n  simple refine (Build_pHomotopy _ _); cbn.\n  - intros a; apply p.\n  - refine (concat_p1 _ @ (concat_1p _)^).\nQed.\n\n(** ** Composition of pointed homotopies *)\n\nDefinition phomotopy_compose {A B : pType} {f g h : A ->* B}\n  (p : f ==* g) (q : g ==* h) : f ==* h.\nProof.\n  pointed_reduce.\n  simple refine (Build_pHomotopy _ _); cbn.\n  - intros x; exact (p x @ q x).\n  - apply concat_p1.\nQed.\n\nInfix \"@*\" := phomotopy_compose : pointed_scope.\n\n(* pointed homotopy is a transitive relation *)\nGlobal Instance phomotopy_transitive {A B} : Transitive (@pHomotopy A B)\n  := @phomotopy_compose A B.\n\nDefinition phomotopy_inverse {A B : pType} {f g : A ->* B}\n: (f ==* g) -> (g ==* f).\nProof.\n  intros p; pointed_reduce.\n  simple refine (Build_pHomotopy _ _); cbn.\n  - intros x; exact ((p x)^).\n  - apply concat_Vp.\nQed.\n\n(* pointed homotopy is a symmetric relation *)\nGlobal Instance phomotopy_symmetric {A B} : Symmetric (@pHomotopy A B)\n  := @phomotopy_inverse A B.\n\n\nNotation \"p ^*\" := (phomotopy_inverse p) : pointed_scope.\n\nDefinition issig_phomotopy {A B : pType} (f g : A ->* B)\n: { p : f == g & p (point A) @ point_eq g = point_eq f } <~> (f ==* g).\nProof.\n  issig.\nDefined.\n\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/theories/Pointed/pHomotopy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6884225344191668}}
{"text": "(******************************************************************************)\n(* Chapter 1.6.1: Product Categories                                          *)\n(******************************************************************************)\n\n(*\n(0)\n同じディレクトリにある Categories.v と Functor.v を使う。\n\n(1) ベースライン\nhttp://www.megacz.com/berkeley/coq-categories/\nこれをもとに改変。Instance ... Proper を使うようにした。\n *)\n\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import finset fintype.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import Notations.                   (* coq standard libs. *)\nRequire Import Categories.                  (* same dir. *)\nRequire Import Functors.                    (* same dir. *)\nRequire Import Isomorphisms.                (* same dir. *)\n\n(* 積圏 *)\nSection ProductCategories.\n\n  Locate \"_ ~~{ _ }~~> _\".                  (* Categories.v *)\n  \n(*\n  Context `(C1 : Category Obj1 Hom1).\n  Context `(C2 : Category Obj2 Hom2).\n*)  \n  Context `(C1 : Category).                 (* Obj Hom *)\n  Context `(C2 : Category).                 (* Obj0 Hom0 *)\n  \n  (* trying to use the standard \"prod\" here causes a universe\n  inconsistency once we get to coqBinoidal; moreover, using a\n  general fully-polymorphic pair type seems to trigger some serious\n  memory leaks in Coq *)\n  \n  Inductive  prod_obj : Type :=\n  | pair_obj : C1 -> C2 -> prod_obj.\n  \n  Definition fst_obj (x : prod_obj) : C1 :=\n    match x with\n      | pair_obj a _ => a\n    end.\n  \n  Definition snd_obj (x : prod_obj) : C2 :=\n    match x with\n      | pair_obj _ b => b\n    end.\n\n  Inductive prod_mor (a b : prod_obj) : Type :=\n    pair_mor :\n      ((fst_obj a) ~~{C1}~~> (fst_obj b)) -> (* f1 *)\n      ((snd_obj a) ~~{C2}~~> (snd_obj b)) -> (* f2 *)\n      prod_mor a b.                          (* f *)\n  Check prod_mor : prod_obj → prod_obj → Type.\n  \n  Definition prod_eqv (a b : prod_obj)\n             (f : prod_mor a b) (g : prod_mor a b) : Prop :=\n    match f with\n      | pair_mor f1 f2 =>\n        match g with\n          | pair_mor g1 g2 =>\n            f1 === g1 /\\ f2 === g2\n        end\n    end.\n  \n  Program Instance prod_Equiv (a b : prod_obj) : Equivalence (@prod_eqv a b).\n  Obligation 1.                             (* Reflexive *)\n  Proof.\n    rewrite /prod_eqv /Reflexive /=.\n    case=> f1 f2.\n    split.\n    - reflexivity.\n    - reflexivity.\n  Qed.\n  Obligation 2.                             (* Symmetric *)\n  Proof.\n    rewrite /prod_eqv /Symmetric /=.\n    case=> f1 f2.\n    case=> g1 g2.\n    case=> H1 H2.\n    split.\n    - rewrite H1.\n      reflexivity.\n    - rewrite H2.\n      reflexivity.\n  Qed.\n  Obligation 3.                             (* Transitive *)\n  Proof.\n    rewrite /prod_eqv /Transitive /=.\n    case=> f1 f2.\n    case=> g1 g2.\n    case=> h1 h2.\n    case=> Hfg1 Hfg2.\n    case=> Hgh1 Hgh2.\n    split.\n    - rewrite Hfg1 Hgh1.\n      reflexivity.\n    - rewrite Hfg2 Hgh2.\n      reflexivity.\n  Qed.\n  \n  (* 射はSetoidでないといけない。 *)\n  Instance PC_mor (a b : prod_obj) : Setoid :=\n    {\n      carrier := prod_mor a b;\n      eqv := @prod_eqv a b\n    }.\n  Check PC_mor : prod_obj → prod_obj → Setoid.\n  Print PC_mor.\n  \n  Definition fst_mor {a b : prod_obj} (f : prod_mor a b) :=\n    match f with\n      | pair_mor a _ => a\n    end.\n  \n  Definition snd_mor {a b : prod_obj} (f : prod_mor a b) :=\n    match f with\n      | pair_mor _ b => b\n    end.\n  \n  Check @Category.\n  Check prod_obj : Type.\n  Check prod_mor : prod_obj → prod_obj → Type.\n  Check PC_mor   : prod_obj → prod_obj → Setoid.\n  Check @Category prod_obj PC_mor.\n  \n  Program Instance ProductCategory : @Category prod_obj PC_mor.\n  Obligation 1.                             (* id *)\n  Proof.\n    apply pair_mor.\n    - apply id.\n    - apply id.\n  Defined.\n  Obligation 2.                             (* comp *)\n  Proof.\n    apply pair_mor.\n    Check (fun (f1 : fst_obj a ~~{ C1 }~~> fst_obj b)\n               (g1 : fst_obj b ~~{ C1 }~~> fst_obj c) => (g1 \\\\o f1)).\n    - apply (fun (f1 : fst_obj a ~~{ C1 }~~> fst_obj b)\n                 (g1 : fst_obj b ~~{ C1 }~~> fst_obj c) => (g1 \\\\o f1));\n        by [apply X | apply X0].\n    - apply (fun (f2 : snd_obj a ~~{ C2 }~~> snd_obj b)\n                 (g2 : snd_obj b ~~{ C2 }~~> snd_obj c) => (g2 \\\\o f2));\n        by [apply X | apply X0].\n  Defined.\n  Obligation 3.                             (* comp_respects *)\n  Proof.\n    rewrite /ProductCategory_obligation_2.\n    move=> g1 g2 Hg.\n    move=> f1 f2 Hf.\n    move: Hg Hf.\n    rewrite /prod_eqv.\n    case g1 => gf1 gs1.\n    case f1 => ff1 fs1.\n    case g2 => gf2 gs2.\n    case f2 => ff2 fs2.\n    case=> Hgf Hgs.\n    case=> Hff Hfs.\n    split.\n    - rewrite Hgf Hff.\n      reflexivity.\n    - rewrite Hgs Hfs.\n      reflexivity.\n  Defined.\n  Obligation 4.                             (* id \\\\o f === f  *)\n  Proof.\n    case: f => ff fs.\n    split.\n    - rewrite left_identity.\n      reflexivity.\n    - rewrite left_identity.\n      reflexivity.\n  Defined.\n  Obligation 5.                             (* f \\\\o id === f  *)\n  Proof.\n    case: f => ff fs.\n    split.\n    - rewrite right_identity.\n      reflexivity.\n    - rewrite right_identity.\n      reflexivity.\n  Defined.\n  Obligation 6.                             (* f \\\\o g \\\\o h === f \\\\o (g \\\\o h) *)\n  Proof.\n    case: f => ff fs.\n    split.\n    - case: g => gf gs.\n      case: h => hf hs.\n      rewrite associativity.\n      reflexivity.\n    - case: g => gf gs.\n      case: h => hf hs.\n      rewrite associativity.\n      reflexivity.\n  Defined.\nEnd ProductCategories.\n\nNotation \"C ×× D\" := (ProductCategory C D).\n\n(*\nImplicit Arguments pair_obj [ Ob1 Hom1 Ob2 Hom2 C1 C2 ].\nImplicit Arguments pair_mor [ Ob1 Hom1 Ob2 Hom2 C1 C2 ].\n *)\n\nCheck @pair_obj : ∀Obj Hom C1 Obj Hom C2 a b, prod_obj C1 C2.\nCheck @pair_mor : ∀Obj Hom C1 Obj Hom C2 a b f g, prod_mor a b.\nCheck @fst_obj.\nCheck @fst_mor.\nArguments pair_obj {Obj1 Hom1 C1 Obj2 Hom2 C2} a b : rename.\nArguments pair_mor {Obj1 Hom1 C1 Obj2 Hom2 C2 a b} f g : rename.\nArguments fst_obj  {Obj1 Hom1 C1 Obj2 Hom2 C2} D : rename.\nArguments snd_obj  {Obj1 Hom1 C1 Obj2 Hom2 C2} D : rename.\nArguments fst_mor  {Obj1 Hom1 C1 Obj2 Hom2 C2 a b} i : rename.\nArguments snd_mor  {Obj1 Hom1 C1 Obj2 Hom2 C2 a b} i : rename.\nCheck pair_obj : _ -> _ -> prod_obj _ _.    (* 圏の指定は要らない。 *)\nCheck pair_mor : _ ~> _ ->  _ ~> _ -> prod_mor _ _.\nCheck fst_obj  : prod_obj _ _ -> _.\nCheck snd_obj  : prod_obj _ _ -> _.\nCheck fst_mor  : prod_mor _ _ -> _ ~> _.\n\nCheck @PC_mor : ∀Obj Hom C1 Obj0 Hom0 C2 _ _, Setoid.\nArguments PC_mor {Obj1 Hom1 C1 Obj2 Hom2 C2} f g : rename.\nCheck PC_mor : prod_obj _ _ → prod_obj _ _ → Setoid.\n\nCheck @Functor : ∀Obj Hom C1 Obj0 Hom0 C2 _, Type.\nArguments Functor {Obj Hom} C1 {Obj0 Hom0} C2 i : rename.\n\nSection ProductCategoryFunctors.\n\n  Context `{C : Category}.                  (* Obj Hom C *)\n  Context `{D:Category}.                    (* Obj0 Hom0 D *)\n\n  Check @Functor.\n  Check @Functor _ _ (C ×× D) Obj Hom C (fun c => fst_obj c).\n  Check Functor (C ×× D) C (fun c => fst_obj c).\n\n  Check @prod_obj Obj Hom C Obj0 Hom0 D.\n  Check prod_obj C D.\n\n  Check @PC_mor Obj Hom C Obj0 Hom0 D.\n  Check PC_mor.\n  \n  Check @fst_obj Obj Hom C Obj0 Hom0 D : prod_obj C D → C.\n  Check fst_obj : prod_obj C D → C.\n  \n  Check fun (c : prod_obj C D) => @fst_obj Obj Hom C Obj0 Hom0 D c.\n  Check fun (c : prod_obj C D) => fst_obj c.\n  \n  Check @Functor (prod_obj C D) (@PC_mor Obj Hom C Obj0 Hom0 D) (C ×× D)\n        Obj Hom C (fun c => fst_obj _ _ c).\n  Check Functor (C ×× D) C (fun (c : prod_obj C D) => @fst_obj Obj Hom C Obj0 Hom0 D c).\n  \n  (* 積圏からもとの圏をとりだす関手 *)\n  Program Instance func_pi1 : Functor (C ×× D) C\n                                      (fun (c : prod_obj C D) => fst_obj c).\n  Obligation 1.\n  (* fst_obj a ~~{ C }~~> fst_obj b *)\n  Proof.\n    by apply fst_mor.\n  Defined.\n  Obligation 2.\n  (* fst_mor f === fst_mor f' *)\n  Proof.\n    rewrite /func_pi1_obligation_1.\n    case: f H => ff fs.\n    case: f' => f'f f's H /=.\n    by case: H.\n  Defined.\n  Obligation 3.\n  (* id === id *)\n  Proof.\n    reflexivity.\n  Defined.\n  Obligation 4.\n  Proof.\n    rewrite /func_pi1_obligation_1.\n    case: f => ff fs.\n    case: g => gf gs.\n    reflexivity.\n  Defined.\n  \n  Program Instance func_pi2 : Functor (C ×× D) D\n                                      (fun (c : prod_obj C D) => snd_obj c).\n  Obligation 1.\n  (* snd_obj a ~~{ D }~~> snd_obj b *)\n  Proof.\n    by apply snd_mor.\n  Defined.\n  Obligation 2.\n  (* snd_mor f === snd_mor f' *)\n  Proof.\n    rewrite /func_pi2_obligation_1.\n    case: f H => ff fs.\n    case: f' => f'f f's H /=.\n    by case: H.\n  Defined.\n  Obligation 3.\n  (* id === id *)\n  Proof.\n    reflexivity.\n  Defined.\n  Obligation 4.\n  Proof.\n    rewrite /func_pi2_obligation_1.\n    case: f => ff fs.\n    case: g => gf gs.\n    reflexivity.\n  Defined.  \n  \n  (* 積圏の左が恒等射である場合 *)\n  Definition llecnac_fmor (I : C) (a b : D) (g : a ~~{D}~~> b) :\n    (pair_obj I a) ~~{C××D}~~> (pair_obj I b).\n  Proof.\n    apply: pair_mor => /=.\n    - by apply: id.\n    - by apply: g.\n  Defined.\n  \n  (* 圏から左が恒等射である積圏への関手 *)\n  Program Instance func_llecnac (I : C) : Functor D (C ×× D) (pair_obj I).\n  Obligation 1.\n  (* prod_mor (pair_obj I a) (pair_obj I b) *)\n   Proof.\n    apply: pair_mor;\n      by apply llecnac_fmor.\n  Defined.\n  Obligation 2.\n  Proof.\n    split; [reflexivity | done].\n  Defined.\n  Obligation 3.\n    split; [reflexivity | reflexivity].\n  Defined.\n  Obligation 4.\n  Proof.\n    split.\n    - rewrite left_identity.\n      reflexivity.\n    - reflexivity.\n  Defined.\n  \n  (* 積圏の右が恒等射である場合 *)\n  Definition rlecnac_fmor (I : D) (a b : C) (f : a ~~{C}~~> b) :\n    (pair_obj a I) ~~{C××D}~~> (pair_obj b I).\n  Proof.\n    apply: pair_mor => /=.\n    - by apply: f.\n    - by apply: id.\n  Defined.\n  \n  (* 圏から右が恒等射である積圏への関手 *)\n  Program Instance func_rlecnac (I : D) : Functor C (C ×× D) (fun c => (pair_obj c I)).\n  Obligation 1.\n  (* prod_mor (pair_obj a I) (pair_obj b I) *)\n  Proof.\n    apply: pair_mor;\n      by apply rlecnac_fmor.\n  Defined.\n  Obligation 2.\n  Proof.\n    split; [done | reflexivity].\n  Defined.\n  Obligation 3.\n    split; [reflexivity | reflexivity].\n  Defined.\n  Obligation 4.\n  Proof.\n    split.\n    - reflexivity.\n    - rewrite right_identity.\n      reflexivity.\n  Defined.\n  \n  Context `{E : Category}.\n  \n  (* 積圏の結合律 *)\n  Definition cossa : ((C ×× D) ×× E) -> (C ×× (D ×× E)).\n  Proof.\n    move=> [[HC HD] HE].\n    by [].\n  Defined.\n  \n  (* 次の定理のための補題 *)\n  Definition cossa_fmor (a : ((C ×× D) ×× E)) (b : ((C ×× D) ×× E))\n             (f : a ~~{(C ×× D) ×× E}~~> b) :\n    (cossa a) ~~{C ×× (D ×× E)}~~> (cossa b).\n  Proof.\n    case: a f => HCxD HE.\n    case: b => GCxD GE.\n    case: HCxD.\n    case: GCxD.\n    move=> HC HD GC GD.\n    case=> fCD fE.\n    case: fCD => fC fD.\n    done.\n  Defined.\n\n  (* cossa は、関手である。 *)\n  Program Instance func_cossa : Functor ((C ×× D) ×× E) (C ×× (D ×× E)) cossa :=\n    {|\n      fmor := fun a b f => cossa_fmor f\n    |}.\n  Obligation 1.\n  Proof.\n    move: a b f f' H.\n    (* ∀a b f f' _, cossa_fmor f === cossa_fmor f' *)\n    move=> [[a11 a12] a2].                  (* case a *)\n    move=> [[b11 b12] b2].                  (* case b *)\n    move=> [[f11 f12] f2].                  (* case f *)\n    move=> [[g11 g12] g2].                  (* case f' *)\n    case; case.\n    split; [exact | split; exact].\n  Defined.\n  Obligation 2.\n  Proof.\n    (* ∀ a : (C ×× D) ×× E, cossa_fmor id === id *)\n    case: a => HCxD HE.\n    case: HCxD => HC HD.\n    split; [reflexivity | split; reflexivity].\n  Defined.\n  Obligation 3.\n  Proof.\n    move: a b c f g.\n    (* ∀a b c f g, cossa_fmor g \\\\o cossa_fmor f === cossa_fmor (g \\\\o f) *)\n    move=> [[a11 a12] a2].                  (* case a *)\n    move=> [[b11 b12] b2].                  (* case b *)\n    move=> [[c11 c12] c2].                  (* case c *)\n    move=> [[f11 f12] f2].                  (* case f *)\n    move=> [[g11 g12] g2].                  (* case g *)\n    rewrite /=; split; [reflexivity | split; reflexivity].\n  Defined.\n  \n  (* 同じ圏の積 C^2 *)\n  Program Instance func_diagonal : Functor C (C ×× C) (fun c => (pair_obj c c)).\n  Obligation 1.\n  (* prod_mor (pair_obj a a) (pair_obj b b) *)\n  Proof.\n    by apply: pair_mor.\n  Defined.\n  Obligation 3.\n  (* id === id ∧ id === id *)\n  Proof.\n    split; reflexivity.\n  Defined.\n  Obligation 4.\n  (* g \\\\o f === g \\\\o f ∧ g \\\\o f === g \\\\o f *)\n  Proof.\n    split; reflexivity.\n  Defined.\nEnd ProductCategoryFunctors.\n\nSection func_prod.\n  \n  Context `{C1 : Category} `{C2 : Category} `{C3 : Category} `{C4 : Category}.\n  Variables (Fobj1 : C1 -> C2) (Fobj2 : C3 -> C4).\n  Variables (F1 : Functor C1 C2 Fobj1) (F2 : Functor C3 C4 Fobj2).\n\n  Definition functor_product_fobj (a : prod_obj C1 C3) :=\n    pair_obj (Fobj1 (fst_obj a)) (Fobj2 (snd_obj a)).  \n  Check functor_product_fobj.\n  Check functor_product_fobj : prod_obj C1 C3 → prod_obj C2 C4.\n\n  Definition functor_product_fmor (a b : (C1 ×× C3)) (f : a ~~{C1 ×× C3}~~> b) :\n    (functor_product_fobj a) ~~{C2 ×× C4}~~> (functor_product_fobj b).\n  Proof.\n    case: a f => HC1 HC3 H.\n    apply: pair_mor => /=.\n    - apply (fmor F1); by case H.\n    - apply (fmor F2); by case H.\n  Defined.\n  \n  Hint Unfold fst_obj.\n\n  Program Instance func_prod : Functor (C1 ×× C3) (C2 ×× C4) functor_product_fobj :=\n    {|\n      fmor := fun a b (f:a~~{C1 ×× C3}~~>b) => functor_product_fmor f\n    |}.\n  Obligation 1.\n  Proof.\n    move: a b f f' H.\n    (* ∀a b f f' _, functor_product_fmor f === functor_product_fmor f' *)\n    move=> [a1 a2].                         (* case a *)\n    move=> [b1 b2].                         (* case b *)\n    move=> [f1 f2].                         (* case f *)\n    move=> [g1 g2].                         (* case g *)\n    case=> H1 H2.                           (* case H *)\n    split; [rewrite H1 | rewrite H2]; reflexivity.\n  Defined.\n  Obligation 2.\n  Proof.\n  (* ∀ a : C1 ×× C3, functor_product_fmor id === id *)\n    case: a => [a1 a2] /=.\n      by split; apply fmor_preserves_id.\n  Defined.\n  Obligation 3.\n  Proof.\n    move: a b c f g.\n  (* ∀a b c f g,\n   functor_product_fmor g \\\\o functor_product_fmor f ===\n   functor_product_fmor (g \\\\o *)\n    move=> [a1 a2].                         (* case a *)\n    move=> [b1 b2].                         (* case b *)\n    move=> [c1 c2].                         (* case c *)\n    case=> f1 f3.                           (* case f *)\n    case=> g1 g3.                           (* csae g *)\n    by move=> /=; split; apply fmor_preserves_comp.\n  Defined.\nEnd func_prod.\n\nNotation \"f **** g\" := (func_prod f g).\n\nProgram Instance iso_prod `{C : Category} `{D : Category} {a b : C} {c d : D}\n         (ic : a ≅ b) (id : @Isomorphic _ _ D c d) :\n  @Isomorphic _ _ (C ×× D) (pair_obj a c) (pair_obj b d).\nObligation 1.                               (* prod_mor (pair_obj a c) (pair_obj b d) *)\nProof.\n  apply: pair_mor => /=.\n  - by case: ic.\n  - by case: id.\nDefined.\nObligation 2.                               (* prod_mor (pair_obj b d) (pair_obj a c) *)\nProof.\n  apply: pair_mor => /=.\n  - by case: ic.\n  - by case: id.\nDefined.\nObligation 3.\nProof.\n   by split; apply iso_comp1.\nDefined.\nObligation 4.\nProof.\n   by split; apply iso_comp2.\nDefined.\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/monad/ProductCategories_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6884178055014929}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (lf2 : natural) : natural := plus z lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj126_coqofml_37bgAJ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6884178030988193}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) : natural := plus y lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj2010_coqofml_clhxbR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6884177984740706}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) : natural := plus y lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj134_coqofml_RlK3Tf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6884177894653714}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := plus (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_plus_commut_64_plus_succ/goal33conj83_coqofml_0pnbQ1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927012, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.688401226467426}}
{"text": "From Babel Require Import FQP.premises.\nFrom Babel Require Import TerminalDogma.Sequence.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\nRequire ComplexTheories.\nRequire VectorSpaceTheories.\n\n\n\nModule HilbertSpaceTheory.\n\nExport ComplexTheories.ComplexTheory.\nExport VectorSpaceTheories.VectorSpaceTheory.\n\n(** Definition 2.1.2 (complex inner product space) *)\nRecord CIP_space := build_ipspace {\n    Vs :> vspace ℂ_field;\n    Vsdot : Vs -> Vs -> ℂ;\n\n    (** dot non-negative *)\n    Vsdot_realc : forall u : Vs, realc (Vsdot u u);\n    Vsdot_pos_def : forall u : Vs, Vsdot_realc u >= 0; \n    Vsdot_pos_0 : forall u : Vs, ((Vsdot_realc u) = 0%R :> R) <-> u = 𝟎;\n\n    (** dot conjugate *)\n    Vsdot_conj : forall u v : Vs, (Vsdot u v)^* = Vsdot v u;\n\n    (** dot linearity *)\n    Vsdot_linear : forall (c1 c2 : ℂ) (u v1 v2 : Vs), \n        Vsdot u (Vadd (@Vscal _ Vs c1 v1) (@Vscal _ Vs c2 v2)) = \n        (c1 * (Vsdot u v1) + c2 * (Vsdot u v2))%ℂ;\n}.\n\n(** Note : The level for a ∗ b is 30, and we want\n        a ∗ u ∙ v to\n    to mean\n        a ∗ (u ∙ v), \n    so level 35 is appropriate. *)\nNotation \" u '∙' v \" := (Vsdot u v) (at level 35) : Vspace_scope.\n\n(** Dirac Notation *)\nNotation \" <[ u | v ]> \" := (Vsdot u v) : Vspace_scope.\n\n(** orthogonal *)\nDefinition orthogonal (CIPs : CIP_space) (u v : CIPs) := <[ u | v ]> = 0.\nNotation \" u '⊥' v \" := (orthogonal u v) (at level 20) : Vspace_scope.\n(** [] *)\n\nDefinition f_norm (CIPs : CIP_space) (u : CIPs) := √ (Vsdot_realc u).\nNotation \" |[ u ]| \" := (f_norm u) : Vspace_scope.\n\nDefinition unit_vector (CIPs : CIP_space) (u : CIPs) : Prop := |[ u ]| = 1%R.\n\n\n(** Definition 2.1.3 *)\n\nRecord v_Cauchy_seq (H : CIP_space) := mk_v_Cauchy_seq {\n    f_v_seq :> infSeq H;\n    seq_conv_proof : \n        forall e : { r : R | r > 0 },\n        exists N : nat, forall m n : { n : nat | (n > N)%nat }, \n        |[ (f_v_seq (proj1_sig m)) + (- (f_v_seq (proj1_sig n))) ]| < proj1_sig e;\n}.\n\nDefinition seq_lim (H : CIP_space) (f : infSeq H) (psi : H) :=\n    forall e : { r : R | r > 0 },\n    exists N : nat, forall n : { n : nat | (n > N)%nat }, \n    |[ (f (proj1_sig n)) + (- psi) ]| < proj1_sig e.\n\n(** Definition 2.1.4 *)\nRecord Hilbert_space := build_Hspace {\n    H :> CIP_space;\n    H_complete : forall s : v_Cauchy_seq H, exists psi, seq_lim s psi;\n}.\n\n(** Definition 2.1.5 *)\n\nDefinition is_ortho_basis (H : Hilbert_space) (s : Seque H) : Prop :=\n    forall i j : index s, s i ⊥ s j.\n\nRecord ortho_basis (H : Hilbert_space) := build_ortho_basis {\n    ortho_basis_obj :> Seque H;\n    ortho_basis_proof : is_ortho_basis ortho_basis_obj;\n}.\n\nDefinition in_linear_comb (H : Hilbert_space) (s : Seque H) (psi : H) :=\n    exists \n\n\n\nEnd HilbertSpaceTheory.", "meta": {"author": "LucianoXu", "repo": "Project-Babel", "sha": "92a749468a5ab3f3acb5e0bcbf29800df90be651", "save_path": "github-repos/coq/LucianoXu-Project-Babel", "path": "github-repos/coq/LucianoXu-Project-Babel/Project-Babel-92a749468a5ab3f3acb5e0bcbf29800df90be651/history/FQP/HilbertSpaceTheories.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927012, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.688401226467426}}
{"text": "\nRequire Export Iron.Language.SystemF2Cap.Type.\nRequire Export Iron.Language.SystemF2Cap.Value.\nRequire Export Iron.Language.SystemF2Cap.Store.Bind.\n\n\n(********************************************************************)\n(* Small Step Evaluation (pure rules)\n   These are pure transitions that don't depend on the store. *)\nInductive StepP : exp  -> exp -> Prop :=\n\n (* Value application. *)\n | SpAppSubst\n   :  forall t11 x12 v2\n   ,  StepP (XApp (VLam t11 x12) v2)\n            (substVX 0 v2 x12)\n\n (* Type application. *)\n | SpAPPSubst\n   :  forall k11 x12 t2      \n   ,  StepP (XAPP (VLAM k11 x12) t2)\n            (substTX 0 t2 x12)\n\n (* Take the successor of a natural. *)\n | SpSucc\n   :  forall n\n   ,  StepP (XOp1 OSucc (VConst (CNat n)))\n            (XVal (VConst (CNat (S n))))\n\n (* Test a natural for zero. *)\n | SpIsZero\n   :  forall n\n   ,  StepP (XOp1 OIsZero (VConst (CNat n)))\n            (XVal (VConst (CBool (beq_nat n 0)))).\n\nHint Constructors StepP.\n\n\n(********************************************************************)\n(* Preservation for pure single step rules. *)\nLemma stepp_preservation\n :  forall se sp x x' t e\n ,  StepP  x x'\n -> Forall ClosedT se\n -> TypeX  nil nil se sp x  t e\n -> TypeX  nil nil se sp x' t e.\nProof.\n intros se sp x x' t e HS HC HT. gen t e.\n induction HS; intros; inverts_type; rip.\n\n - Case \"SpAppSubst\".\n   eapply subst_val_exp; eauto.\n\n - Case \"SpAPPSubst\".\n   rrwrite (TBot KEffect = substTT 0 t2 (TBot KEffect)).\n   have HTE: (nil = substTE 0 t2 nil).\n   have HSE: (se  = substTE 0 t2 se) by (symmetry; auto).\n   rewrite HTE. rewrite HSE.\n\n   lets D: subst_type_exp H4 H8.\n   rrwrite (liftTE 0 se = se).\n   simpl in D. simpl. auto.\n\n - Case \"SpSucc\".\n   snorm. inverts H5. auto.\n\n - Case \"SpIsZero\".\n   snorm. inverts H5. auto.\nQed.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/devel/Iron/Language/SystemF2Cap/Step/Pure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436727, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6884012168342015}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\nRequire Import Nat Arith.\n\nInductive lst : Type := Nil : lst | Cons : nat -> lst -> lst.\n\nInductive queue : Type := Queue : lst -> lst -> queue.\n\nFixpoint len (len_arg0 : lst) : nat\n           := match len_arg0 with\n              | Nil => 0\n              | Cons x y => plus 1 (len y)\n              end.\n\nDefinition qlen (qlen_arg0 : queue) : nat\n           := let 'Queue x y := qlen_arg0 in\n              plus (len x) (len y).\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nDefinition amortizeQueue (amortizeQueue_arg0 : lst) (amortizeQueue_arg1 : lst) : queue\n           := match amortizeQueue_arg0, amortizeQueue_arg1 with\n              | x, y => if leb (len y) (len x) then Queue x y else Queue (append x (rev y)) Nil\n              end.\n\nDefinition qpush (qpush_arg0 : queue) (qpush_arg1 : nat) : queue\n           := match qpush_arg0, qpush_arg1 with\n              | Queue x y, n => amortizeQueue x (Cons n y)\n              end.\n\nDefinition queue_to_lst (queue_to_lst_arg0 : queue) : lst\n           := let 'Queue x y := queue_to_lst_arg0 in\n              append x (rev y).\n\nLemma append_nil : forall (l : lst), append l Nil = l.\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem theorem0 : forall (q : queue) (n : nat), eq (append (queue_to_lst q) (Cons n Nil)) (queue_to_lst (qpush q n)).\nProof.\n  intros.\n  destruct q.\n  induction l.\n  - simpl. rewrite append_nil. reflexivity.\n  - simpl. simpl in IHl. rewrite IHl. unfold amortizeQueue. simpl. destruct (len l) eqn:?.\n    + simpl. destruct (len l0 <=? 0) eqn:?.\n      * simpl. rewrite append_nil. reflexivity.\n      * simpl. reflexivity.\n    + destruct (len l0 <=? n1) eqn:?.\n      * simpl. apply Nat.leb_le in Heqb. apply le_S in Heqb. rewrite <- Nat.leb_le in Heqb. rewrite Heqb. simpl. reflexivity.\n      * destruct (len l0 <=? S n1) eqn:?.\n        -- simpl. lfind. Admitted.\n", "meta": {"author": "ana-brendel", "repo": "coq-benchmarks", "sha": "78b9ca2993b0fb579d814ed17e63c6859e79681c", "save_path": "github-repos/coq/ana-brendel-coq-benchmarks", "path": "github-repos/coq/ana-brendel-coq-benchmarks/coq-benchmarks-78b9ca2993b0fb579d814ed17e63c6859e79681c/testing_results_initial/old_script_testing/HasSummary/lia/queue_push_to_list/queue_push_to_list_lfind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6884012148593814}}
{"text": "Require Import QArith ZArith Zwf Omega.\nRequire Import ssreflect eqtype ssrbool ssrnat div fintype seq ssrfun.\nRequire Import bigop fingroup choice.\nRequire Export ssralg orderedalg infra pol.\n\nImport GroupScope .\nImport GRing.Theory.\nImport OrderedRing.Theory.\nOpen Local Scope ring_scope .\n\n\nSet Printing Width 50.\n\n(* We want to prove a simple and contructive approximation of the\n middle value theorem: if a polynomial is negative in a and positive in b,\n and a < b, then for any positive epsilon, there exists c and d, so that \n a <= c < d <= b, the polynomial is negative in c and positive and d,\n and the variation between c and d is less than epsilon.  To prove this,\n we use a second polynomial, obtained by taking the the absolute value\n of each coefficient.\n*)\n\n(* Theorem binding the slope between two points inside an interval. *)\nLemma cm2 :\n  forall l b, { c |\n  forall x, 0 <= x -> x <= b -> \n    `|(eval_pol l x - eval_pol l 0)| <= c * x}.\nProof.\nmove=> l b; case: l =>[| a l].\n- by exists 0; move=> /= x; rewrite mul0r oppr0 addr0 absr0 lerr.\n- exists (eval_pol (abs_pol l) b) => x px xb /=; rewrite mul0r addr0.\n  rewrite addrC addKr absf_mul ger0_abs // mulrC lter_mulp //=.\n  rewrite (ler_trans (ler_absr_eval_pol _ _)) //.\n  by rewrite eval_pol_abs_pol_increase // ger0_abs.\nQed.\n\n\n\n(* Cannot be abstracted since not every ordered ring has a floor ring *)\nLemma QZ_bound : forall x:Q, (0 <= x)%Q -> {n : Z | x <= n#1}%Q.\nintros [n d]; exists(Zdiv n (Zpos d)+1)%Z.\nassert (dpos : (('d) > 0)%Z) by apply (refl_equal Gt).\nunfold Qle; simpl; rewrite Zmult_1_r; rewrite Zmult_plus_distr_l.\nrewrite Zmult_1_l {1}(Z_div_mod_eq n ('d)) //.\nrewrite (Zmult_comm ('d)); apply Zplus_le_compat; auto with zarith.\ndestruct (Z_mod_lt n ('d)) as [_ H2]; auto.\nby apply Zlt_le_weak.\nDefined.\n\n(* We will look at n points regularly placed between a and b,  a satisfies\n  a property P and b does not, we want to find the first point among the\n  n points that satisfies P and has a neighbour that does not. *)\nDefinition find_pair : forall A:eqType, forall P:A->bool, forall Q:A->A->Prop,\n    forall l:seq A, forall a b:A, P a -> ~P b ->\n    (forall l1 l2 x y, a::l ++ b::nil= l1 ++ x :: y :: l2 -> Q x y) ->\n    {c :A & { d | Q c d /\\ P c /\\ ~P d}}.\nProof.\nmove => A P Q l; elim: l => [ | a l IHl] a' b' Pa Pb connect. \n  by exists a'; exists b'; split => //; apply: (connect [::] [::]).\ncase Pa1: (P a).\n  have tmp :\n     forall l1 l2 x y,  a :: l ++ [:: b' ]= l1 ++ [::x, y & l2] -> Q x y.\n    by move => l1 l2 x y q; apply: (connect (a'::l1) l2); rewrite /= q.\n  by move: (IHl a b' Pa1 Pb tmp) => [c [d [cd Pc]]]; exists c; exists d.\nexists a'; exists a; split; first by apply (connect nil (l++b'::nil)).\nby rewrite Pa1. \nQed.\n\nFixpoint nat_ns (p : Z)(n : nat) :=\n  match n with\n    |0 => [:: p]\n    |m.+1 => (p - (Z_of_nat m.+1)) :: nat_ns p m\n  end.\n\nDefinition ns p n :=\n  match n with\n    |Zpos q => nat_ns p (nat_of_P q)\n    |_ => [:: p]\n  end.\n\nLemma ltb_Zneg0 : forall x, (Zneg x) < 0.\nProof. move=> x; by []. Qed.\n\nLemma leb_Zneg0N : forall x, 0 <= (Zneg x) = false.\nProof. by move=> x. Qed.\n\nLemma nat_ns_head : forall (p : Z) n, \n  exists l, nat_ns p n = (p - (Z_of_nat n)) :: l.\nProof.\nmove=> p; elim=>[|n [l Ih]] /=.\n  by rewrite oppr0 addr0; exists [::].\nby rewrite Ih; exists [:: p - Z_of_nat n & l].\nQed.\n\nLemma ns_head :  forall p n :Z, (0 <= n) -> exists l, ns p n = (p - n) :: l.\nProof.\nmove=> p [|n|n] /=; last 1 first.\n- by rewrite leb_Zneg0N.\n- by exists [::]; rewrite oppr0 addr0.\n- move=> _; set m := nat_of_P n; case: (nat_ns_head p m)=> l' ->; exists l'.\n  by rewrite /m Zpos_eq_Z_of_nat_o_nat_of_P.\nQed.\n\nLemma nat_ns_step : forall p n, forall l1 l2 x y,\n  nat_ns p n = l1 ++ [:: x, y & l2] -> y = x + 1.\nProof.\nmove=> p; elim=> [|n Ihn] l1 l2 x y /=.\n  by move/(congr1 size)=> /=; rewrite size_cat /= !addnS; move/eqP; rewrite eqSS.\ncase: l1 => [|u l3] /=; last by case=> _; move/Ihn.\ncase=> <-; case: (nat_ns_head p n)=> [l' ->]; case=> <- _.\nrewrite Zpos_P_of_succ_nat /Zsucc /= -[(_ + 1)%Z]/((Z_of_nat n) + 1) oppr_add addrA.\nby rewrite addrK.\nQed.\n\nLemma ns_step : forall p n, forall l1 l2 x y, 0 <= n ->\n  ns p n = l1 ++ [:: x, y & l2] -> y = x + 1.\nProof.\nmove=> p [|n|n] /=; last 1 first.\n- by rewrite leb_Zneg0N.\n- move=> ? ? ? ? ?.\n  by move/(congr1 size)=> /=; rewrite size_cat /= !addnS; move/eqP; rewrite eqSS.\n- move=> l1 l2 x y _; exact: nat_ns_step.\nQed.\n\nLemma nat_ns_tail : forall p n, exists l, nat_ns p n = l ++ [:: p].\nProof.\nmove=> p; elim=> [|n [l' Ihn]] /=.\n- by exists [::]; rewrite cat0s.\n- by rewrite Ihn; exists [:: (p - (' P_of_succ_nat n)%Z) & l']; rewrite cat_cons.\nQed.\n  \nLemma ns_tail : forall p n, exists l, ns p n = l ++ p ::nil.\nProof.\nmove=> p [|n|n] /=. \n- by exists [::]; rewrite cat0s.\n- by case: (nat_ns_tail p (nat_of_P n))=> l' ->; exists l'.\n- by exists [::]; rewrite cat0s.\nQed.\n\n(* Lemmas about minus are missing in xssralg .. .*)\nLemma nat_ns_bounds : forall p n x l1 l2, nat_ns p n = l1 ++ [:: x & l2] -> \n        (p - Z_of_nat n <= x) && (x <= p).\nProof.\nmove=> p; elim=> [|n Ihn] x l1 l2 /= h.\n- rewrite oppr0 addr0. \n  suff exp : p = x by rewrite exp lerr.\n  case: l1 h => /=; first by case.\n  move=> z s.\n  by move/(congr1 size)=> /=; rewrite size_cat /= !addnS; move/eqP;\n      rewrite eqSS.\n- case: l1 h => [| u l1] /=.\n  + by set sn := (' _)%Z; case=> h _; rewrite -h lerr lter_addlr /= oppr_lte0.\n  + case=> _; move/Ihn; case/andP=> h1 h2; rewrite h2 andbT; apply: ler_trans h1.\n    rewrite lter_add2r /= -lter_opp2 /= Zpos_P_of_succ_nat /Zsucc.\n    by rewrite -[Zplus _ _]/(Z_of_nat n + 1) lter_addrr /= ler01.\nQed.\n\nLemma ns_bounds : forall p n x l1 l2, 0 <= n -> ns p n = l1 ++ x::l2 -> \n        (p - n <= x) && ( x <= p).\nProof.\nmove=> p [| n | n] x l1 l2 /=.\n- move=> _ h; rewrite oppr0 addr0.\n  suff exp : p = x by rewrite exp lerr.\n  case: l1 h => /=; first by case.\n  move=> z s.\n  by move/(congr1 size)=> /=; rewrite size_cat /= !addnS; move/eqP; rewrite eqSS.\n- by move=> _; move/nat_ns_bounds; rewrite Zpos_eq_Z_of_nat_o_nat_of_P.\n- by rewrite leb_Zneg0N.\nQed. \n\nLemma map_contiguous :\nforall (A B : Type)(f : A -> B) l l1 l2 a b,\n  map f l = l1 ++ [:: a, b & l2] ->\n  {l'1 : seq A & \n    {l'2 : seq A & \n      {x : A & \n        {y : A | [/\\ l1 = map f l'1, l2= map f l'2, a = f x,\n          b = f y & l = l'1 ++ [:: x, y & l'2]]}}}}.\nProof.\nintros A B f; elim=> [|x l Ihl] /= l1 l2 a b h; first by case: l1 h.\ncase: l Ihl h => [|a' l'] /= h.\n- by move/(congr1 size)=> /=; rewrite size_cat /= !addnS; move/eqP; rewrite eqSS.\n- case: l1 h => [|a1 l1] /= h.\n    by case=> <- <- <-; exists [::]; exists l'; exists x; exists a' => /=.\n  case=> e1; move/h => [l1' [l2' [x' [y' [h1 h2 h3 h4 h5]]]]].\n  exists [:: x & l1']; rewrite /= -h1 h2 e1; exists l2'; exists x'; exists y'.\n  by split=> //; rewrite h5.\nQed.\n\n(*This is map_cat.\nLemma map_app :\n  forall A B:Type, forall f : A -> B, forall l1 l2, map f (l1++l2) = map f l1 ++ map f l2.\nintros A B f l1; induction l1; simpl; auto.\nintros l2; rewrite IHl1; auto.\nQed.\n*)\n\n\nLemma non_empty_tail : \n  forall (A : Type) (a : A) l, exists l', exists b, [:: a & l] = l' ++ [::b].\nProof.\nmove=> A a l; elim: l a => [| x l  Ihl] a.\n- by exists [::]; exists a.\n- case: (Ihl x)=> s [b Ihb]; rewrite Ihb; exists [:: a & s]; exists b.\n  by rewrite cat_cons.\nQed.\n\n(* wait and see ...\nLemma Qfrac_add_Z_l : forall a b c,\n  (a # 1) + (b # c)%Q = ( a * ' c + b # c)%Q :> Qcb.\nintros;unfold Qeq; simpl; ring.\nQed.\n*)\n\nLemma leb_Z : forall x y:Z, x <= y -> Qcb_make x <= Qcb_make y.\nProof. \nmove => x y xy; apply/QcblebP; rewrite /qcb_val /Qcb_make /Qle /Qnum /Qden.\nby rewrite 2!Zmult_1_r; apply/Zle_is_le_bool.\nQed.\n\nLemma leb_0_Z : forall y, 0%Z <= y -> 0 <= Qcb_make y.\nProof. by move => y yp; apply: leb_Z. Qed.\n\nLemma ltb_Z : forall x y:Z, x < y -> Qcb_make x < Qcb_make y.\nProof. \n  move => x y xy. apply/QcblebP; rewrite /qcb_val /Qcb_make /Qle /Qnum /Qden.\nrewrite 2!Zmult_1_r; move/Zle_is_le_bool; rewrite -[Zle_bool y x]/(y <= x).\nby rewrite ler_nlt xy.\nQed.\n\nLemma ltb_0_Z : forall y, 0%Z < y -> 0 < Qcb_make y.\nProof. by move => y yp; apply: ltb_Z. Qed.\n\nLemma Qcb_make_add :\n  forall x y, Qcb_make (x + y) == Qcb_make x + Qcb_make y.\nmove => x y; apply/Qcb_QeqP.\nby rewrite  -[(Qcb_make _ + _)%R]/(Q2Qcb(Qplus (qcb_val (Qcb_make x))\n                                  (qcb_val (Qcb_make y)))) /Qcb_make\n   ?qcb_valE /Qplus /Qnum /Qden !Zmult_1_r Pmult_1_r /Q2Qcb ?qcb_valE\n   (eqP (Qcb_Z _)).\nQed.\n\nLemma half_lt : forall a b :Qcb, 0 < a -> 0 <  b ->\n   a / ((Qcb_make 2) * b) < a / b.\nmove => a b Ha Hb; rewrite ltef_mulpl // invr_mul //=; last first.\n  by rewrite unitfE eq_sym ltrWN.\nby rewrite ltef_divp //= -{1}[_^-1]mulr1 ltef_mulp //= invf_cp0.\nQed.\n\nLemma cut_epsilon : forall eps:Qcb, 0 < eps ->\n  exists eps1, exists eps2, 0 < eps1 /\\ 0 < eps2 /\\ eps1 + eps2 <= eps /\\\n      eps1 < eps /\\ eps2 < eps.\nmove => eps p; exists (eps/Qcb_make 2); exists (eps/Qcb_make 2).\nhave p1 : 0 < eps/Qcb_make 2 by rewrite ltef_divp.\nsplit; first done; split; first done; split.\n  rewrite -mulr_addr.\n  have q2 : (Qcb_make 2)^-1 + (Qcb_make 2)^-1 == 1 by [].\n  by rewrite (eqP q2) mulr1 lerr.\nsuff cmp : eps/Qcb_make 2 < eps by [].\nby rewrite ltef_divp //= -{1}[eps]mulr1 ltef_mulp.\nQed.\n\n\nLemma constructive_ivt :\n  forall l x y, x < y -> eval_pol l x < 0%R -> 0%R <= eval_pol l y  ->\n       forall epsilon, 0 < epsilon ->\n       exists x', exists y',  - epsilon <= eval_pol l x' /\\\n         eval_pol l x' < 0 /\\ 0 <= eval_pol l y' /\\\n         eval_pol l y' <= epsilon /\\ x <= x' /\\ x' < y' /\\ y' <= y.\nProof.\nmove=> l a b ab nla plb.\nhave ba' : 0 < b - a by rewrite -(addrN a) lter_add2l.\n(*have mpolapos : 0 < - eval_pol l a by rewrite gtr0_ltNr0 opprK.*)\nhave evalba : 0 < eval_pol l b - eval_pol l a. \n  rewrite -(lter_add2l (eval_pol l a)) add0r -addrA addNr addr0. \n  exact: lter_le_trans plb.\ncase: (translate_pol l a) => l' q.\ncase: (@cm3 (b - a) ba' l') => /= c pc.\nhave cpos : 0 < c.\n  rewrite -(ltef_mulp _ _ _ ba') /= mul0r -[b -a]addr0.\n  apply: lter_le_trans (pc 0 (b - a) _ _ _); rewrite ?lerr // ?(ltrW ba') //.\n  by rewrite -{2}(addrN a) -!q ger0_abs // ltrW. \nmove=> eps pe.\nhave pdiv : (0 < (b - a) * c / eps).\n  by rewrite ltef_divp // mul0r mulf_gte0 /= ba' cpos.\nmove: (pdiv); move/ltrW; move/QcblebP; case/QZ_bound => n qn.\n(* assia : canonical structures are missing here for Z -> Qcb *)\nhave qn' : (((b - a) * c / eps) <= (Qcb_make n)).\n    by apply/QcblebP; rewrite /Qcb_make qcb_valE.\nhave fact1 : 0 < n.\n  have tmp : 0 < Qcb_make n.\n    by apply: lter_le_trans pdiv qn'.\n  move: tmp; move/QcblebP. rewrite /Qcb_make /=.\n  by move/Qle_bool_iff; rewrite /Qle_bool /= Zmult_1_r; move/negP.\nhave mkl: \n  exists l, forall l1 l2 x y, \n    [:: a & l] ++ [:: b] = l1 ++ [:: x, y & l2] ->\n    y - x = (b - a) / (Qcb_make n) /\\ \n    exists k : Z, \n      x = a + (b - a)* (Qcb_make k)/ (Qcb_make n) /\\ \n      (0<= k) /\\ (k <= n - 1).\n  case en : (n == 1).\n  - rewrite (eqP en); exists [::] => l1 l2 x y /=; case: l1 => [| t1 ql1] /=.\n      case=> e1 e2 e3; rewrite e1 e2 Qcb_make1 invr1 mulr1; split=> //.\n      by exists 0; rewrite addrN lerr Qcb_make0 mulr0 mul0r addr0; split.\n    by move/(congr1 size)=> /=; rewrite size_cat /= !addnS; move/eqP; rewrite eqSS.\n- exists (map  (fun x => a + (b-a)*((Qcb_make x)/(Qcb_make n))) (ns (n-1) (n-2))).\n  have fact8 : 0 <= n - 2%Z.\n    move/eqP: en; move: fact1; rewrite -[1]/1%Z -[0]/0%Z.\n    clear. rewrite /is_true. rewrite -Zle_is_le_bool-[(n-2%Z)%R]/(n - 2)%Z.\n    rewrite -[0%Z < n]/(~~(Zle_bool n 0)); move/negP.\n    rewrite /is_true -Zle_is_le_bool; omega.\n  have fact2 : 0 <= n - 1.\n    by rewrite  ler_eqVlt (ler_lte_trans fact8) ?orbT // lter_add2r.\n  move=> l1 l2 x y; case: l1 => [|t1 ql1] /=.\n    case: (ns_head (n - 1) (n - 2) fact8) => a1 qa1.\n    rewrite qa1 /= (_ : (n - 1) - (n - 2)%Z = 1) ?Qcb_make1; last first.\n      by rewrite addrAC [-(n - 2%Z)]oppr_add addrA opprK addrN add0r. \n    case => -> <- /=; split.\n      by rewrite addrAC addrN add0r mulrA mulr1.\n    exists 0; rewrite Qcb_make0 mulr0 mul0r addr0 lerr; split=> //; split=> //.\n  case=> ->; case: l2 => [|d l2] /=.\n    rewrite -[[:: x, y & [::]]]/([::x]++[:: y]) catA.\n    rewrite !cats1 -!rot1_cons; move/rot_inj; case=> <-.\n    case: (ns_tail (n - 1) (n - 2))=> l3 ->; rewrite map_cat /=.\n    rewrite cats1 -rot1_cons; move/rot_inj; case=> <- h2.\n    have fact3 : (Qcb_make (n - 1) / Qcb_make n) = 1 - (Qcb_make n)^-1.\n      have nn0 : ~~ (Qcb_make n == 0).\n         by apply/negP => nis0; move/Qcb_QeqP: nis0; \n         rewrite /Qeq /= Zmult_1_r => nis0; move: fact1;\n         rewrite nis0 ltrr.\n      by apply/eqP; rewrite /= (eqP (Qcb_make_add _ _)) mulr_addl mulrV /= //.\n    rewrite fact3 mulr_addr mulr1 oppr_add !addrA oppr_add addrA addrN add0r.\n    rewrite -mulrN opprK; split=> //.\n    exists (n - 1); split; last by rewrite lerr.\n    by rewrite  -mulrA fact3 mulr_addr mulr1 !addrA.\n  case: (non_empty_tail  _ d l2) => l3 [e qe]; rewrite qe.\n  rewrite -[ql1 ++ [:: x, y & l3 ++ [:: e]]]/(ql1 ++ [:: x, y & l3] ++ [:: e]).\n  rewrite [_ ++ _ ++ [:: e]]catA !cats1 -!rot1_cons; move/rot_inj; case=> -> q''.\n  case: (map_contiguous _ _ (fun x => t1+(e-t1)*((Qcb_make x)/(Qcb_make n)))\n             _ _ _ _ _ q'') =>  [l'1 [l'2 [n1 [n2 [_ [_ [qx [qy st]]]]]]]].\n  rewrite qx qy.\n  have n21 : n2 = n1 + 1 by apply: ns_step st.\n  split.\n    rewrite n21 [t1 + _]addrC -addrA oppr_add [t1 + _]addrA addrN add0r -mulrN\n       -mulr_addr -mulNr -[_ * _^-1 + _]mulr_addl.\n    have fact5: Qcb_make (n1 + 1) - Qcb_make n1 = 1.\n      by rewrite -[_ - _]/(Q2Qcb (Qcb_make _ + Qcbopp(Qcb_make _)))\n          /Qcbopp /Qcb_make ?qcb_valE /Qopp /Qden /Qnum /Q2Qcb ?qcb_valE\n          (eqP (Qcb_Z _)) /Qplus /Qden /Qnum /Pmult 2!Zmult_1_r -Zplus_assoc\n          [Zplus _ (Zopp _)]Zplus_comm Zplus_assoc Zplus_opp_r Zplus_0_l.\n    by rewrite fact5 mul1r.\n  exists n1; split; first by rewrite mulrA.\n  have bds : (1 <= n1) && (n1 <= (n-1)).\n    have fact9 : (n - 1) - (n - 2%Z) = 1\n        by rewrite oppr_add opprK addrA [ _ - n]addrC addKr.\n    by rewrite -{1}fact9; apply: ns_bounds _ _ _ _ _ fact8 st.\n  move/andP: bds => [bds1 bds2];split; last by [].\n  have fact6: 0 <= n1 by apply: ler_trans bds1; apply: ltrW; apply ltr01.\n  by [].\ncase: mkl => [sl qsl].\nhave fact7 : ~ eval_pol l b < 0.\n  by apply/negP; rewrite ltrNge.\ncase: (find_pair _ (fun x => (eval_pol l x) < 0)\n             (fun x y => y - x = (b-a)/Qcb_make n /\\\n                (exists k, x = a + (b-a)*Qcb_make k / Qcb_make n /\\\n                        0 <= k /\\ k <= (n-1))) sl a b nla fact7 qsl) =>\n             [a' [b' [[A1 [k [A4 A5]]] [A2 A3]]]] {qsl sl}.\nexists a'; exists b'.\nhave aa' : a <= a'.\n  rewrite -(addr0 a) A4; apply: lter_add=> /=; first by apply lerr.\n  rewrite mulr_ge0pp //; first apply: mulr_ge0pp; rewrite ?(ltrW ba') //.\n    by apply: leb_0_Z; case: A5.\n  by rewrite invf_gte0 /=; apply: leb_0_Z; apply: ltrW.\nhave bb' :  b' <= b.\n  have bdec : b = a + (b - a) * (Qcb_make n) / (Qcb_make n).\n    have nn0 : Qcb_unit (Qcb_make n).\n      apply/negP => nq0; move/Qcb_QeqP: nq0.\n      rewrite /Qeq Zmult_1_r /Qcb_make qcb_valE /Qnum Zmult_0_l => nq0.\n      by move: fact1; rewrite nq0 ltrr.\n    by rewrite mulrK // addrA [a + _]addrC addrK.\n  have b'a: b' = a' + (b' - a') by rewrite addrA [ a' + _]addrC addrK /=.\n  rewrite b'a A1 A4 -addrA {3}bdec -mulr_addl; apply: lter_add; rewrite /= ?lerr //=.\n  rewrite lter_mulpr //=; first by rewrite invf_gte0; apply: leb_0_Z; apply: ltrW.\n  rewrite -{2}[b - a]mulr1 -mulr_addr lter_mulpl //= ?(ltrW ba') //.\n  rewrite -Qcb_make1  -(eqP (Qcb_make_add _ _)) /=; apply: leb_Z.\n  by case: A5=> _; rewrite -(lter_add2l 1) addrNK.\nhave ab' :  a' < b'.\n  by rewrite -(lter_add2l (- a')) addrN A1 /=  mulf_gte0 /= invf_cp0 /= ltb_0_Z // ba'.\nhave epsban: (b-a)*c/Qcb_make n <= eps.\n  by rewrite ltef_divpl ?ltb_0_Z // [eps * _]mulrC -ltef_divpl.\nhave main: eval_pol l b' - eval_pol l a' <= eps.\n  rewrite !q -(@ger0_abs _ (_ - _)).\n    have b'a': c * (b' - a') <= eps by rewrite A1 mulrA (mulrC c).\n    apply: ler_trans b'a'; rewrite -{2}(addr0 b') -(addNr a) addrA\n        -(addrA (b' - a)) -(opprK (a - a')) oppr_add opprK (addrC (-a)).\n    apply: pc.\n    - by rewrite subr_gte0.\n    - by rewrite lter_add2l /= ltrW.\n    - by rewrite lter_add2l.\n  rewrite -!q lter_addpl //=; first by rewrite oppr_gte0 /= ltrW.\n  by rewrite -ltrNge; apply/negP.\nsplit; last (split; first exact A2).\n  rewrite lter_oppl /=; apply: ler_trans main.\n  by rewrite lter_addrl /= -ltrNge; apply/negP.\nsplit; first by rewrite -ltrNge; move/negP: A3.\nsplit; last by auto.\napply: ler_trans main; rewrite -{1}(addr0 (eval_pol l b')); apply: lter_add; rewrite /= ?lerr //.\nby rewrite /= oppr_gte0 /= ltrW.\nQed.\n", "meta": {"author": "math-comp", "repo": "trajectories", "sha": "cc6e1298208a93592230f5b4ee3228a024aa03e7", "save_path": "github-repos/coq/math-comp-trajectories", "path": "github-repos/coq/math-comp-trajectories/trajectories-cc6e1298208a93592230f5b4ee3228a024aa03e7/attic/CAD_COQ/ssr_descartes/cmvt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6884012146116754}}
{"text": "Require Export ZArith.\nRequire Export ZArithRing.\n\nOpen Scope Z_scope.\n\n(* The following tactic looks for all the instances of\n   \"Zpos (xO p)\" and \"Zpos (xI p)\" and replaces them with\n   polynomial expressions in p, but avoids doing it for the numbers\n   2 and 3 which are \"Zpos (xO xH)\" and \"Zpos (xI xH)\". *)\n\nLtac Zpos_x_tac :=\n match goal with\n   |- context [Zpos (xO ?P)] =>\n       match P with\n        | xH => fail 1\n        | ?X2 => rewrite (Zpos_xO X2); Zpos_x_tac\n       end\n | |- context [Zpos (xI ?P)] =>\n       match P with\n        | xH => fail 1\n        | ?X2 => rewrite (Zpos_xI X2); Zpos_x_tac\n       end\n | |- _ => idtac\n end.\n\n(* Here is an example using this tactic. *)\n\nTheorem ex1 :\n  forall p, Zpos (xO (xI p))=4*(Zpos p)+2.\nProof.\n intros p.\n Zpos_x_tac.\n(* the goal becomes:\n  p : positive\n  ============================\n   2 * (2 * Zpos p + 1) = 2 * 2 * Zpos p + 2 (in Coq CVS Nov 2004)\n *)\n rewrite Zmult_plus_distr_r; simpl (2*1).\n rewrite Zmult_assoc.\n reflexivity.\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/autotac/SRC/Zpos_x_tac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6884012031274835}}
{"text": "Definition lem := forall p, p \\/ ~p.\nPrint lem.\n\nDefinition f := 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_f : lem -> f.\n\nProof.\n  unfold f, lem.\n  firstorder.\n  assert (G := H q).\n  destruct (H q); firstorder.\n\n  (* firstorder logic\n  left.\n  assumption.\n  right.\n  intro.\n  destruct (H0 x).\n  elim H1.\n  assumption.\n  assumption.\n   *)\nQed.\n\nPrint lem_to_f.\n", "meta": {"author": "glsscnnn", "repo": "sumbullshit", "sha": "326e545889303b4bb34e1ff9e52881c29185c2c3", "save_path": "github-repos/coq/glsscnnn-sumbullshit", "path": "github-repos/coq/glsscnnn-sumbullshit/sumbullshit-326e545889303b4bb34e1ff9e52881c29185c2c3/classical.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6883385611611289}}
{"text": "Load Preamble.\n\n\nDefinition eq X := fun p : X*X => match p with (x,y) =>  x = y end. \nDefinition ap X := fun p : X*X => match p with (x,y) =>  ~~ x = y end. \n\nGoal forall X, Sdec (eq X) -> Dec (eq X).\nProof.\n  intros X [f H]. intros [x y].\n  assert (exists n, f n (x, x) = true) as Hn.\n  { now apply H. }\n  apply WO_nat in Hn. \n  destruct Hn as [n Hn].\n  2 : { intros. decide equality. }\n  destruct (f n (x,y)) eqn:Hfn.\n  - left. apply H. now exists n.\n  - right. intros ->. congruence.\nQed. \n\n\nGoal forall X, enum (eq X) -> Dec (eq X).\nProof.\n  intros X [f H]. intros [x y].\n  assert (exists n, f n = Some (x, x)) as Hn.\n  { now apply H. }\n  apply WO_nat in Hn. \n  destruct Hn as [n Hn].\n  2 : { intros. decide equality. }\n  destruct (f n) eqn:Hfn.\n  - left. apply H. exists n. admit.\n  - right. intros ->. congruence.\nAdmitted. \n\n\n\nSection FixF.\n\n  Variable F : Type.\n  Notation \"¬ A\" := (A -> F) (at level 10).\n\n\n  Goal forall A B : Prop, (¬A -> ~B) -> ¬ ¬(B -> A).\n  Proof.\n    intros A B H1 H2.\n    apply H2. intros b. exfalso.\n    apply H1. intros a. all: tauto.\n  Qed.\n\nEnd FixF.", "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/Temp1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6883385569639605}}
{"text": "Set Implicit Arguments.\n\nRequire Import\n        Discrete.DiscreteType\n        Finite.FinType\n        Finite.Constructions.Vector\n        Finite.Constructions.Cardinality\n        Tactics.Tactics.\n\nImport ListNotations.\n\nSection Fixedpoints.\n  Variable A : Type.\n  Variable f : A -> A.\n\n  Definition fp x := f x = x.\n\n  Lemma fp_trans x : fp x -> fp (f x).\n  Proof.\n    congruence.\n  Qed.\n  \n  Lemma fInduction\n        (p : A -> Prop)\n        (x : A)\n        (px : p x)\n        (IHf : forall y, p y -> p (f y)) n\n    : p (Nat.iter n f x).\n  Proof.\n    induction n ; crush.\n  Qed.\n\n  Lemma fp_iter_trans x n\n    : fp (Nat.iter n f x) -> forall m, m >= n -> fp (Nat.iter m f x).\n  Proof.\n    intros F m H. induction m.\n    -\n      destruct n ; crush.\n    -\n      decide (S m = n).\n      +\n        now rewrite e.\n      +\n        assert (m >= n) as G by omega.\n        specialize (IHm G).\n        simpl.\n        now apply fp_trans.\n  Qed.\nEnd Fixedpoints.\n\nDefinition admissible (A : discType) f\n  := forall xs : list A,  fp f xs \\/ card (f xs) > card xs.\n\nLemma fp_card_admissible\n      (A : discType) f n\n  : admissible f ->\n    forall xs : list A, fp f (Nat.iter n f xs) \\/ card (Nat.iter n f xs) >= n.\n Proof.\n   intros M xs. induction n.\n     - cbn in *. right. omega.\n     - simpl in *. destruct IHn as [IHn | IHn] .\n       + left.  now apply fp_trans.\n       + destruct (M ((Nat.iter n f xs))) as [M' | M'].\n         * left.  now apply fp_trans.\n         * right. omega. \n Qed.\n\n Lemma fp_admissible (A : finType) (f : list A -> list A)\n   : admissible f -> forall (xs : list A), fp f (Nat.iter (Cardinality A) f xs).\n Proof.\n   intros F xs.\n   destruct (fp_card_admissible (Cardinality A) F xs) as [H | H].\n   -\n     exact H.\n   -\n     specialize (F (Nat.iter (Cardinality A) f xs)).  destruct F as [F |F] ; crush.\n     +\n       pose proof (card_upper_bound (f (Nat.iter (Cardinality A) f xs))) ; crush.\nQed. \n\nSection FiniteIteration.\n  Variable A : finType.\n  Variable step : list A -> A -> Prop.\n  Variable step_dec: forall xs x, dec (step xs x).\n\n  Lemma pick xs : {x | step xs x /\\ ~ (x el xs)} + forall x, step xs x -> x el xs.\n  Proof.\n    decide (forall x : A, step xs x -> x el xs).\n    - tauto.\n    - left. destruct (DM_notAll _ (p:= fun x => step xs x -> x el xs)) as [H _].\n      destruct (finType_cc _ (H n)) as [x H']. firstorder.\n  Defined.\n\n  Definition finite_iter_step xs :=\n    match (pick xs) with\n    | inl L => match L with\n                exist _ x _ => x :: xs end\n    | inr _ => xs\n    end.\n\n  Definition finite_iter := Nat.iter (Cardinality A) finite_iter_step.\n\n  Lemma finite_iter_step_admissible: admissible finite_iter_step.\n  Proof.\n    intro xs.\n    unfold fp.\n    unfold finite_iter_step.\n    destruct (pick xs) as [[y [S ne]] | S] ; repeat (crush ; dec).\n  Qed.\n\n  Lemma finite_iter_fp xs : fp finite_iter_step (finite_iter xs).\n  Proof.\n    unfold finite_iter.\n    apply fp_admissible.\n    exact finite_iter_step_admissible.\n  Qed.        \n\n  (* inclp A p means every x in A satisfies p *)\n\n  Lemma finite_iter_ind (p : A -> Prop) xs\n    :  inclp xs p -> (forall xs x , (inclp xs p) -> (step xs x -> p x)) ->\n       inclp (finite_iter xs) p.\n  Proof.\n    intros incl H. unfold finite_iter. apply fInduction.\n    -\n      assumption.\n    -\n      intros B H1 x E.\n      unfold finite_iter_step in E.\n      destruct (pick B) as [[y [S nE]] | S].\n      +\n        destruct E as [E|E] ; try subst x ; eauto.\n      +\n        auto.\n  Qed. \n\n  Lemma list_cycle (B : Type) (xs : list B) x\n    : x :: xs <> xs.\n  Proof.\n    intros D.\n    assert (C : |x :: xs| <> |xs|) by (simpl; omega).\n    apply C. now rewrite D.\n  Qed.\n  \n  Lemma closure x xs : fp finite_iter_step xs -> step xs x -> x el xs.\n  Proof.\n    intros F.\n    unfold fp in F.\n    unfold finite_iter_step in F.\n    destruct (pick xs) as [[y _] | S].\n    -\n      contradiction (list_cycle F).\n    - exact (S x).\n  Qed.\n\n  Lemma closure_finite_iter x xs\n    : step (finite_iter xs) x -> x el (finite_iter xs).\n  Proof.\n    apply closure.\n    apply finite_iter_fp.\n  Qed.\n\n  Lemma preservation_step xs : xs <<= finite_iter_step xs.\n  Proof.\n    intro H.\n    unfold finite_iter_step.\n    destruct (pick xs) as [[y [S ne]] | S]; cbn; tauto.\n  Qed.\n\n  Lemma preservation_iter xs n\n    : xs <<= Nat.iter n finite_iter_step xs.\n  Proof.\n    intros x E. induction n.\n    -\n      assumption.\n    -\n      simpl. now apply preservation_step.\n  Qed.\n\n  Lemma preservation_finite_iter xs : xs <<= finite_iter xs. \n  Proof.\n    apply preservation_iter.\n  Qed.\n\n  Definition least_fp_containing f (ys xs : list A) :=\n    fp f ys /\\ xs <<= ys /\\ forall ys', fp f ys' /\\ xs <<= ys' -> ys <<= ys'.\n\n  Definition step_consistent :=\n    forall xs x, step xs x -> forall xs', xs <<= xs' -> step xs' x.\n\n  Lemma step_iter_consistent\n    : step_consistent -> forall xs x n, step xs x -> step (Nat.iter n finite_iter_step xs) x.\n  Proof.\n    intros H xs x n S. eapply H.\n    -\n      exact S.\n    -\n      apply preservation_iter.\n  Qed.\n\n  Lemma step_trans_fp_incl\n    : step_consistent ->\n      forall xs ys, fp finite_iter_step ys -> xs <<= ys ->\n               forall n, Nat.iter n finite_iter_step xs <<= ys.\n  Proof.\n    intros ST xs ys F H n. apply fInduction.\n    -\n      exact H.\n    -\n      intros ys' H'.\n      unfold finite_iter_step at 1.\n      destruct (pick ys') as [[y [S _]] | _].\n      +\n        specialize (ST  _ _ S _ H').\n        intros x [E |E].\n        *\n          subst x.\n          now apply closure.\n        *\n          auto.\n      +\n        exact H'.\n  Qed.\n\n  Lemma step_consistent_least_fp\n    : step_consistent -> forall xs, least_fp_containing finite_iter_step (finite_iter xs) xs.\n  Proof.\n    intros ST xs.\n    repeat split.\n    -\n      apply finite_iter_fp.\n    -\n      apply preservation_finite_iter.\n    -\n      intros B [H H'].\n      now apply step_trans_fp_incl.\n  Qed.\n\n  Lemma dup_free_finite_iter_step xs\n    : dup_free xs -> dup_free (finite_iter_step xs).\n  Proof.\n    intro DA.\n    unfold finite_iter_step.\n    destruct (pick xs) as [[y [S ne]] | S] ; auto. \n  Qed.\n\n  Lemma dup_free_iter_step n xs\n    : dup_free xs -> dup_free (Nat.iter n finite_iter_step xs).\n  Proof.\n    induction n.\n    -\n      now cbn.\n    -\n      intro H.\n      simpl. apply dup_free_finite_iter_step ; tauto.\n  Qed.\n\n  Lemma dup_free_finite_iter xs\n    : dup_free xs -> dup_free (finite_iter xs).\n  Proof.\n    apply dup_free_iter_step.\n  Qed.\nEnd FiniteIteration.\n\nArguments finite_iter {A} step {step_dec} x.\nArguments finite_iter_step {A} step {step_dec} xs.\nArguments pick {A} {step} {step_dec} xs.\n\n\n", "meta": {"author": "rodrigogribeiro", "repo": "finite_types", "sha": "27582ce97686654d741bca49a0f091a68a3dc89d", "save_path": "github-repos/coq/rodrigogribeiro-finite_types", "path": "github-repos/coq/rodrigogribeiro-finite_types/finite_types-27582ce97686654d741bca49a0f091a68a3dc89d/Finite/Constructions/FiniteIteration.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6883385540196812}}
{"text": "From Coq Require Import Strings.String. (* for manual grading *)\nFrom Coq Require Import ZArith.\nFrom Coq Require Import PArith.\nFrom VFA Require Import Perm.\nFrom VFA Require Import Maps.\nImport FunctionalExtensionality.\n\n\nModule Integers.\n\nInductive positive : Set :=\n  | (* 1 + 2n *) xI : positive -> positive\n  | (* 2n     *) xO : positive -> positive\n  | (* 1      *) xH : positive.\n\n\nDefinition ten := xO (xI (xO xH)).\n\nFixpoint positive2nat (p: positive) : nat :=\n  match p with\n  | xI q => 1 + 2 * positive2nat q\n  | xO q => 0 + 2 * positive2nat q\n  | xH   => 1\n end.\n\nEval compute in positive2nat ten.\n\nFixpoint print_in_binary (p: positive) : list nat :=\n  match p with\n  | xI q => print_in_binary q ++ [1]\n  | xO q => print_in_binary q ++ [0]\n  | xH   =>  [1]\n end.\nEval compute in print_in_binary ten.\n\n\nNotation \"p ~ 1\" := (xI p) (at level 7, left associativity, format \"p '~' '1'\").\nNotation \"p ~ 0\" := (xO p) (at level 7, left associativity, format \"p '~' '0'\").\nPrint ten.\n\nFixpoint succ x :=\n  match x with\n    | p~1 => (succ p)~0\n    | p~0 => p~1\n    | xH  => xH~0\n  end.\n\nFixpoint addc (carry: bool) (x y: positive) {struct x} : positive :=\n  match carry, x, y with\n    | false, p~1, q~1 => (addc true p q)~0\n    | false, p~1, q~0 => (addc false p q)~1\n    | false, p~1, xH  => (succ p)~0\n    | false, p~0, q~1 => (addc false p q)~1\n    | false, p~0, q~0 => (addc false p q)~0\n    | false, p~0, xH  => p~1\n    | false, xH,  q~1 => (succ q)~0\n    | false, xH,  q~0 => q~1\n    | false, xH,  xH  => xH~0\n    | true,  p~1, q~1 => (addc true p q)~1\n    | true,  p~1, q~0 => (addc true p q)~0\n    | true,  p~1, xH  => (succ p)~1\n    | true,  p~0, q~1 => (addc true p q)~0\n    | true,  p~0, q~0 => (addc false p q)~1\n    | true,  p~0, xH  => (succ p)~0\n    | true,  xH,  q~1 => (succ q)~1\n    | true,  xH,  q~0 => (succ q)~0\n    | true,  xH,  xH  => xH~1\n  end.\nDefinition add (x y: positive) : positive := addc false x y.\n\n\n\nLemma succ_correct: forall p,\n   positive2nat (succ p) = S (positive2nat p).\nProof.\n  intros. induction p; simpl.\n  - rewrite IHp. lia.\n  - lia.\n  - reflexivity.\nQed.\n\nLemma addc_correct: forall (c: bool) (p q: positive),\n   positive2nat (addc c p q) =\n        (if c then 1 else 0) + positive2nat p + positive2nat q.\nProof.\n  intros c p.\n  generalize dependent c.\n  induction p; simpl; intros.\n  - destruct c.\n    + destruct q.\n      * simpl. rewrite IHp. simpl.\n        remember (positive2nat p) as p'.\n        remember (positive2nat q) as q'.\n        lia.\n      * simpl. rewrite IHp. simpl.\n        remember (positive2nat p) as p'.\n        remember (positive2nat q) as q'.\n        lia.\n      * simpl. rewrite succ_correct. simpl.\n        remember (positive2nat p) as p'.\n        lia.\n    + destruct q.\n      * simpl. rewrite IHp. simpl.\n        remember (positive2nat p) as p'.\n        remember (positive2nat q) as q'.\n        lia.\n      * simpl. rewrite IHp. simpl.\n        remember (positive2nat p) as p'.\n        remember (positive2nat q) as q'.\n        lia.\n      * simpl. rewrite succ_correct. simpl.\n        remember (positive2nat p) as p'.\n        lia.\n  - destruct c.\n    + destruct q.\n      * simpl. rewrite IHp. simpl.\n        remember (positive2nat p) as p'.\n        remember (positive2nat q) as q'.\n        lia.\n      * simpl. rewrite IHp. simpl.\n        remember (positive2nat p) as p'.\n        remember (positive2nat q) as q'.\n        lia.\n      * simpl. rewrite succ_correct. simpl.\n        remember (positive2nat p) as p'.\n        lia.\n    + destruct q.\n      * simpl. rewrite IHp. simpl.\n        remember (positive2nat p) as p'.\n        remember (positive2nat q) as q'.\n        lia.\n      * simpl. rewrite IHp. simpl.\n        remember (positive2nat p) as p'.\n        remember (positive2nat q) as q'.\n        lia.\n      * simpl.\n        remember (positive2nat p) as p'.\n        lia.\n  - destruct c.\n    + destruct q.\n      * simpl. rewrite succ_correct. simpl.\n        remember (positive2nat q) as q'.\n        lia.\n      * simpl. rewrite succ_correct. simpl.\n        remember (positive2nat q) as q'.\n        lia.\n      * simpl. reflexivity.\n    + destruct q.\n      * simpl. rewrite succ_correct. simpl.\n        remember (positive2nat q) as q'.\n        lia.\n      * simpl.\n        remember (positive2nat q) as q'.\n        lia.\n      * simpl. reflexivity.\nQed.\n\nTheorem add_correct: forall (p q: positive),\n   positive2nat (add p q) = positive2nat p + positive2nat q.\nProof.\n  intros.\n  unfold add.\n  apply addc_correct.\nQed.\n\nInductive comparison : Set :=\n    Eq : comparison | Lt : comparison | Gt : comparison.\n\n\nFixpoint compare x y {struct x}:=\n  match x, y with\n    | p~1, q~1 => compare p q\n    | p~1, q~0 => match compare p q with \n                  | Lt => Lt \n                  | _  => Gt end\n    | p~1, xH  => Gt\n    | p~0, q~1 => match compare p q with \n                  | Gt => Gt \n                  | _  => Lt end\n    | p~0, q~0 => compare p q\n    | p~0, xH  => Gt\n    | xH, q~1  => Lt\n    | xH, q~0  => Lt\n    | xH, xH   => Eq\n  end.\n\nLemma positive2nat_pos:\n forall p, positive2nat p > 0.\nProof.\n  intros.\n  induction p; simpl; lia.\nQed.\n\nLemma positive_not_less_1: forall x, positive2nat x < 1 -> False.\nProof.\n  intro x. induction x; simpl; intro HContra.\n  - simpl in *. apply IHx. lia.\n  - simpl in *. apply IHx. lia.\n  - simpl in *. inversion HContra. lia.\nQed.\n\nLemma positive_geq_1: forall x, positive2nat x >= 1.\nProof.\n  intro x. induction x; simpl.\n  - lia.\n  - lia.\n  - lia.\nQed.\n\nTheorem compare_correct:\n forall x y,\n  match compare x y with\n  | Lt => positive2nat x < positive2nat y\n  | Eq => positive2nat x = positive2nat y\n  | Gt => positive2nat x > positive2nat y\n end.\nProof.\n  induction x; destruct y; simpl.\n  - repeat (rewrite Nat.add_0_r).\n    specialize (IHx y).\n    destruct (compare x y).\n    + rewrite Nat.succ_inj_wd. rewrite IHx. reflexivity.\n    + rewrite <- Nat.succ_lt_mono. lia.\n    + apply gt_n_S. lia.\n  - repeat (rewrite Nat.add_0_r).\n    specialize (IHx y).\n    destruct (compare x y).\n    + rewrite IHx. constructor.\n    + lia.\n    + lia.\n  - repeat (rewrite Nat.add_0_r).\n    specialize (IHx xH).\n    destruct (compare x xH); simpl in *.\n    + rewrite IHx. lia.\n    + exfalso. apply (positive_not_less_1 x IHx).\n    + lia.\n  - repeat (rewrite Nat.add_0_r).\n    specialize (IHx y).\n    destruct (compare x y); lia.\n  - repeat (rewrite Nat.add_0_r).\n    specialize (IHx y).\n    destruct (compare x y); lia.\n  - repeat (rewrite Nat.add_0_r).\n    assert (G:= positive_geq_1 x).\n    lia.\n  - assert (G:= positive_geq_1 y).\n    lia.\n  - assert (G:= positive_geq_1 y).\n    lia.\n  - reflexivity.\nQed.\n\nInductive Z : Set :=\n  | Z0 : Z\n  | Zpos : positive -> Z\n  | Zneg : positive -> Z.\n\nEnd Integers.\n\n\n(* Trie *)\n\nInductive trie (A : Type) :=\n    | Leaf : trie A\n    | Node : trie A -> A -> trie A -> trie A.\nArguments Leaf {A}.\nArguments Node {A} _ _ _.\n\nDefinition trie_table (A: Type) : Type := (A * trie A)%type.\nDefinition empty {A: Type} (default: A) : trie_table A :=\n      (default, Leaf).\n\nFixpoint look {A: Type} (default: A) (i: positive) (m: trie A): A :=\n    match m with\n    | Leaf       => default\n    | Node l x r =>\n        match i with\n        | xH    => x\n        | xO i' => look default i' l\n        | xI i' => look default i' r\n        end\n    end.\n\nDefinition lookup {A: Type} (i: positive) (t: trie_table A) : A :=\n   look (fst t) i (snd t).\n\n\nFixpoint ins {A: Type} default (i: positive) (a: A) (m: trie A): trie A :=\n    match m with\n    | Leaf =>\n        match i with\n        | xH    => Node Leaf a Leaf\n        | xO i' => Node (ins default i' a Leaf) default Leaf\n        | xI i' => Node Leaf default (ins default i' a Leaf)\n        end\n    | Node l o r =>\n        match i with\n        | xH => Node l a r\n        | xO i' => Node (ins default i' a l) o r\n        | xI i' => Node l o (ins default i' a r)\n        end\n    end.\nDefinition insert {A: Type} (i: positive) (a: A) (t: trie_table A)\n                 : trie_table A :=\n  (fst t, ins (fst t) i a (snd t)).\n\n\nDefinition three_ten : trie_table bool :=\n insert 3 true (insert 10 true (empty false)).\nEval compute in three_ten.\nEval compute in map (fun i => lookup i three_ten) [3;1;4;1;5]%positive.\n\n(* Trie correctness TODO *)\n\nLemma look_leaf: forall A (a:A) j, \n  look a j Leaf = a.\nProof.\n  intros.\n  induction j.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nLemma look_ins_same: forall {A} a k (v:A) t, \n  look a k (ins a k v t) = v.\nProof.\n  intros A a k.\n  induction k; simpl; intros.\n  - destruct t.\n    + apply IHk.\n    + apply IHk.\n  - destruct t.\n    + apply IHk.\n    + apply IHk.\n  - destruct t.\n    + reflexivity.\n    + reflexivity.\nQed.\n\nLemma look_ins_other: forall {A} a j k (v:A) t,\n   j <> k -> look a j (ins a k v t) = look a j t.\nProof.\n  intros A a j.\n  induction j; simpl; intros.\n  - destruct k.\n    + simpl.\n      destruct t.\n      * rewrite IHj.\n        apply look_leaf.\n        lia.\n      * apply IHj.\n        lia.\n    + simpl.\n      destruct t.\n      * apply look_leaf.\n      * reflexivity.\n    + simpl.\n      destruct t.\n      * apply look_leaf.\n      * reflexivity.\n  - destruct k.\n    + simpl.\n      destruct t.\n      * apply look_leaf.\n      * reflexivity.\n    + simpl.\n      destruct t.\n      * rewrite IHj.\n        apply look_leaf.\n        lia.\n      * apply IHj.\n        lia.\n    + simpl.\n      destruct t.\n      * apply look_leaf.\n      * reflexivity.\n  - destruct k.\n    + simpl.\n      destruct t.\n      * reflexivity.\n      * reflexivity.\n    + simpl.\n      destruct t.\n      * reflexivity.\n      * reflexivity.\n    + simpl.\n      destruct t.\n      * exfalso. apply H. lia.\n      * exfalso. apply H. lia.\nQed.\n\n\nDefinition nat2pos (n: nat) : positive := Pos.of_succ_nat n.\nDefinition pos2nat (n: positive) : nat := pred (Pos.to_nat n).\n\nLemma pos2nat2pos: forall p, nat2pos (pos2nat p) = p.\nProof.\n  intro. unfold nat2pos, pos2nat.\n  rewrite <- (Pos2Nat.id p) at 2.\n  destruct (Pos.to_nat p) eqn:?.\n  pose proof (Pos2Nat.is_pos p). lia.\n  rewrite <- Pos.of_nat_succ.\n  reflexivity.\nQed.\n\nLemma nat2pos2nat: forall i, pos2nat (nat2pos i) = i.\nProof.\n  intro. unfold nat2pos, pos2nat.\n  rewrite SuccNat2Pos.id_succ.\n  reflexivity.\nQed.\n\nLemma pos2nat_injective: forall p q, pos2nat p = pos2nat q -> p = q.\nProof.\n  intros.\n  rewrite <- pos2nat2pos.\n  rewrite <- H.\n  symmetry.\n  apply pos2nat2pos.\nQed.\n\nLemma nat2pos_injective: forall i j, nat2pos i = nat2pos j -> i = j.\nProof.\n  intros.\n  rewrite <- nat2pos2nat.\n  rewrite <- H.\n  symmetry.\n  apply nat2pos2nat.\nQed.\n\n\nDefinition is_trie {A: Type} (t: trie_table A) : Prop := True.\n\nDefinition abstract {A: Type} (t: trie_table A) (n: nat) : A :=\n  lookup (nat2pos n) t.\n\nDefinition Abs {A: Type} (t: trie_table A) (m: total_map A) :=\n  abstract t = m.\n\n\nTheorem empty_is_trie: forall {A} (default: A), is_trie (empty default).\nProof.\nAdmitted.\n\nTheorem insert_is_trie: forall {A} i x (t: trie_table A),\n   is_trie t -> is_trie (insert i x t).\nProof.\nAdmitted.\n\n\nTheorem empty_relate: forall {A} (default: A),\n    Abs (empty default) (t_empty default).\nProof.\n  intros.\n  unfold Abs, abstract, t_empty.\n  extensionality o.\n  unfold lookup.\n  simpl.\n  apply look_leaf.\nQed.\n\nTheorem lookup_relate: forall {A} i (t: trie_table A) m,\n    is_trie t -> Abs t m -> lookup i t = m (pos2nat i).\nProof.\n  intros.\n  unfold Abs, abstract, t_empty in *.\n  rewrite <- H0.\n  rewrite pos2nat2pos.\n  reflexivity.\nQed.\n\nTheorem insert_relate: forall {A} k (v: A) t cts,\n    is_trie t ->\n    Abs t cts ->\n    Abs (insert k v t) (t_update cts (pos2nat k) v).\nProof.\n  intros.\n  unfold Abs, abstract, t_empty, t_update in *.\n  extensionality o.\n  unfold lookup. destruct t. simpl.\n  bdestruct (pos2nat k =? o).\n  - rewrite <- H1.\n    rewrite pos2nat2pos.\n    apply look_ins_same.\n  - rewrite <- H0.\n    unfold lookup. simpl.\n    apply look_ins_other.\n    intros Hcontra.\n    apply H1.\n    rewrite <- pos2nat2pos in Hcontra.\n    apply nat2pos_injective in Hcontra.\n    symmetry.\n    assumption.\nQed. \n\nExample Abs_three_ten:\n    Abs\n       (insert 3 true (insert 10 true (empty false)))\n       (t_update (t_update (t_empty false) (pos2nat 10) true) (pos2nat 3) true).\nProof.\n  try (apply insert_relate; [hnf; auto | ]).\n  try (apply insert_relate; [hnf; auto | ]).\n  try (apply empty_relate).\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/Trie.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.6883259071731901}}
{"text": "Require Export NatList.\nRequire Export Nat.\nRequire Import Induction.\n\n(* /////////////////// POLYMOPHIC LISTS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ *)\n(* Let's introduce generic types, and the 'Type' → Type ≡ * , ∋ , ∀ t , t : * ≡ Type *)\nInductive list (X : Type) : Type :=\n  | nil : list X                  (* nil : ∀ X : Type, list X *)\n  | cons : X -> list X -> list X.   (* cons : ∀ X : Type, X → list X → list X *)\n\n(* Implementation of Polymorphic functions for Lists *)\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(* We can _substantially_ simplify snytax by leaving out input type annotations, as Coq will use Type Inference *)\n(* Type Inference - repeat'' *)\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\n(* For both cases, Coq will Type Inference `repeat''` as :\n  ∀ X : Type, X → nat → list X *)\n\n(* We can avoid '_' by asserting the implicit arguments that Coq must always determine by Type Inference *)\n(* Imnplicitness must be associated in one-to-one correspondence with some Function *)\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat' {X} x count.\n\n(* We can also make function arguments implicit by surrounding them with : {} *)\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(* We can extend the idea of implicitness to writing Inductive Types *)\nInductive list' {X : Type} : Type :=\n  | nil' : list'\n  | cons' : X -> list' -> list'.\n(* NOTE : THE ABOVE IS NOT USED, BECAUSE, list' nat ≡ list' bool IN type-signature *)\n\n(* Implicit + Polymorphic re-implementation of standard List Functions *)\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 h t => S (length t)\n  end.\n\n(* Some convenient notation again *)\n(* The implicitness allows the constructors to be written as before *)\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(* ////////// PROOFS 1 \\\\\\\\\\\\\\\\\\\\\\\\\\ *)\nTheorem app_nil_r : forall X : Type, forall l : list X,\n  l ++ [ ]  = l.\nProof.\n  intros X l.\n  induction l as [| n1 l1 IHl1].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHl1. reflexivity.\nQed.\n\nTheorem app_assoc : forall A : Type, forall l1 l2 l3 : list A,\n  l1 ++ l2 ++ l3 = (l1 ++ l2) ++ l3.\nProof.\n  intros A l1 l2 l3.\n  induction l1 as [| n1 l1' IHl1'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHl1'. reflexivity.\nQed.\n\nTheorem app_length : forall X : Type, forall l1 l2 : list X,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros X l1 l2.\n  induction l1 as [| n' l1' IHl1'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHl1'. simpl. reflexivity.\nQed.\n\nTheorem rev_app_distr : forall X : Type, forall l1 l2 : list X,\n  rev (app l1 l2) = app (rev l2) (rev l1).\nProof.\n  intros X l1 l2.\n  induction l1 as [| n l1' IHl1'].\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IHl1'. rewrite <- app_assoc. reflexivity.\nQed.\n  \nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros X l.\n  induction l as [| n l' IHl'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> rev_app_distr. rewrite -> IHl'. simpl. reflexivity.\nQed.\n\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(* \"type_scope\" : Tells Coq to only use (X * Y) when parsing types, thereby, avoiding a clash with the multliplication symbol *)\n\n(* Projection Functions *)\nDefinition fst {X Y : Type} (p : X * Y) :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) :=\n  match p with\n  | (x, y) => y\n  end.\n\n(* Zip ≡ Combine *)\nFixpoint combine {X Y : Type} (l1 : list X) (l2 : list Y): list (X * Y) :=\n  match l1, l2 with\n  | nil, _ => [ ]\n  | _, nil => [ ]\n  | x1 :: t1, x2 :: t2 => (x1, x2) :: (combine t1 t2)\n  end.\n\n(* Split ≡ ¬ Combine *)\nFixpoint split {X Y : Type} (l : list (X * Y)) : ((list X) * (list Y)) :=\n  match l with\n  | [ ] => ([ ], [ ])\n  | (x1, y1) :: t => pair (x1 :: (fst (split t))) (y1 :: (snd (split t))) \n  end.\n\n(* //////////// POLYMORPHIC OPTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ *)\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) : option X :=\n  match l with\n  | [ ] => None\n  | h :: t => match n with\n             | O => Some h\n             | _ => nth_error t (pred n)\n             end          \n  end.\n\nDefinition hd_error {X : Type} (l : list X): option X :=\n  match l with\n  | [ ] => None\n  | h :: t => Some h\n  end.\n\n(* /////////////// HIGHER-ORDER FUNCTIONS + ANONYMOUS FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ *)\n\n(* Coq allows Functions to be passed around → Higher-Order Functions *)\n(* {Map,Filter,Fold} *)\n\nFixpoint filter {X : Type} (f : X -> bool) (l : list X) : list X :=\n  match l with\n  | [ ] => [ ]\n  | h :: t => match f h with\n             | true => h :: (filter f t)\n             | false => filter f t\n             end\n  end.\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 fold {X Y : Type} (f : X -> Y -> Y) (l : list X) (acc : Y) : Y :=\n  match l with\n  | [ ] => acc\n  | h :: t => f h (fold f t acc)\n  end.\n\n(* The \"fun\" keyword allows for the definition of anonymous functions. 'fun' ≡ λ *)\n\n(* A Helper Bool Function *)\nDefinition and_bool (b1 b2 : bool) : bool :=\n  match b1, b2 with\n  | true, true => true\n  | _, _ => false\n  end.\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n => (and_bool (even_nat n) (negate_bool (leq_nat n (S (S (S (S (S (S O)))))))))) l.\n\nDefinition failure_test {X : Type} (x : X) (y : list X * list X) (z : X -> bool) : list X * list X :=\n  match z x with\n  | true => pair (x :: (fst y)) (snd y)\n  | false => pair (fst y) (x :: (snd y))\n  end.\n\nDefinition partition {X : Type} (test : X -> bool) (l : list X) : list X * list X :=\n  fold (fun x y => (failure_test x y test)) l (pair [ ] [ ]).\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)\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(* Higher-Order Function Constructors *)\nDefinition constfun {X : Type} (x : X) : nat -> X :=\n  fun (k : nat) => x.\n  \n(* /////////////// PROOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ *)\n \nTheorem map_rev : forall X Y : Type, forall f : X -> Y, forall l : list X,\n  map f (rev l) = rev (map f l).\n(* Proof.\n  intros X Y f l.\n  induction l as [| n l' IHl'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHl'. reflexivity.\nQed. *)\nAdmitted.\n\n(* ////////////// EXERCISES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ *)\n\n(* Fold Length *)\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l O.\n\n(* Proof that : fold_length ≡ length *)\nTheorem fold_length_correct : forall X : Type, forall l : list X,\n  fold_length l = length l.\nProof.\n  intros X l.\n  induction l as [| n l' IHl'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHl'. reflexivity.\nQed.\n\n(* Fold Map *)\nDefinition fold_map {X Y : Type} (f : X -> Y) (l : list X) : list Y :=\n  fold (fun x y => (f x) :: y) l [ ].\n\n(* Proof that fold_map ≡ map *)  \nTheorem fold_map_correct : forall X Y : Type, forall f : X -> Y, forall l : list X,\n  fold_map f l = map f l.\nProof.\n  intros X Y f l.\n  induction l as [| n l' IHl'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHl'. reflexivity.\nQed.\n\n(* Currying *)\n(* f : A → B → C ≡ f : A → (B → C) [Right-Associative Typing, in keeping with the λ-calculus [Typed]] *)\n(* So, f a, for some a ∈ A is - f a : B → C --> This is the standard Currying format *)\n(* Uncurrying --> Given some f : A → B → C ≡ (A * B) → C ≡ ∏α:(A * B) → C, where `*` denotes the Product-Type *)\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\n(* Proof that : prod_curry = (prod_curry)^(-1) *)\nTheorem uncurry_curry : forall X Y Z : Type, forall f : X -> Y -> Z, forall x : X, forall y : Y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  intros X Y Z f x y.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem curry_uncurry : forall X Y Z : Type, forall f : (X * Y) -> Z, forall p : (X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros X Y Z f p.\n  destruct p as [x y].\n  reflexivity.\nQed.\n\n(* N⁽ᵗʰ⁾-error function proof *)\n(* Informal Proof \nTheorem curried_nth_error : forall X : Type, forall n : nat, forall l : list X,\n  length l = n -> @nth_error X l n = None.\nProof. `\n  intros X n l H.\n  induction l as [ | m l' IHl'].\n  - simpl. reflexivity.\n  - (rewrite ← curr_H). rewrite <- H. simpl. rewrite <- IHl'. simpl. reflexivity.\nQed. *)\n  \n(* Church Numerals *)\nDefinition nat_number := forall X : Type, (X -> X) -> X -> X.\n\nDefinition zero : nat_number := fun (X : Type) (f : X -> X) (x : X) => x.\n\nDefinition one : nat_number := fun (X : Type) (f : X -> X) (x : X) => (f x).\n\n(* Let use define :\n1) The Successor Function\n2) Addition ≡ Plus\n3) Multiplication ≡ Repeated Addition\n4) Exponentitation ≡ Repeated Multiplication *)\nDefinition succ_nat (n : nat_number) : nat_number :=\n  fun (X : Type) (f : X -> X) (x : X) => f (n X f x).\n\nDefinition plus_nat (n m : nat_number) : nat_number :=\n  fun (X : Type) (f : X -> X) (x : X) => m X f (n X f x).\n\nDefinition mult_nat (n m : nat_number) : nat_number :=\n  fun (X : Type) (f : X -> X) (x : X) => m X (n X f) x.\n\nDefinition exp_nat (n m : nat_number): nat_number :=\n  m mult_nat (mult_nat n) one. (* FIX THIS! *)", "meta": {"author": "jssandh2", "repo": "coq-types", "sha": "bc844def91356335816a0c97b556d98a202165f6", "save_path": "github-repos/coq/jssandh2-coq-types", "path": "github-repos/coq/jssandh2-coq-types/coq-types-bc844def91356335816a0c97b556d98a202165f6/src/Proofs/Polymorphism/Polymorphism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.6883258977021951}}
{"text": "From Undecidability.Shared.Libs.PSL Require Import FinTypes.\n\n(* * Definition of prod as finType *)\n\nLemma ProdCount (T1 T2: eqType) (A: list T1) (B: list T2) (a:T1) (b:T2)  :\n  count (prodLists A B) (a,b) =  count A a * count B b .\nProof.\n  induction A.\n  - reflexivity.\n  - cbn. rewrite <- countSplit. decide (a = a0) as [E | E].\n    + cbn. f_equal. subst a0. apply countMap. eauto.\n    + rewrite <- plus_O_n. f_equal. now apply countMapZero. eauto.\nQed.\n\nLemma prod_enum_ok (T1 T2: finType) (x: T1 * T2):\n  count (prodLists (elem T1) (elem T2)) x = 1.\nProof.\n  destruct x as [x y]. rewrite ProdCount. unfold elem.\n  now repeat rewrite enum_ok.\nQed.\n\n#[global]\nInstance finTypeC_Prod (F1 F2: finType) : finTypeC (EqType (F1 * F2)).\nProof.\n  econstructor.  apply prod_enum_ok.\nDefined.\n\n(* * Definition of option as finType *)\n\n(* Wrapping elements in \"Some\" does not change the number of occurences in a list *)\nLemma SomeElement (X: eqType) (A: list X) x:\n  count (toOptionList A) (Some x) = count A x .\nProof.\n  unfold toOptionList. simpl. dec; try congruence.\n  induction A.\n  + tauto.  \n  + simpl. dec; congruence.\nQed.\n\n(* A list produced by toOptionList contains None exactly once *)\nLemma NoneElement (X: eqType) (A: list X) :\n  count (toOptionList A) None = 1.\nProof.\n  unfold toOptionList. simpl. dec; try congruence. f_equal.\n  induction A.\n  - reflexivity.\n  - simpl; dec; congruence.    \nQed.\n\nLemma option_enum_ok (T: finType) x :\n  count (toOptionList (elem T)) x = 1.\nProof.\n  destruct x.\n  + rewrite SomeElement. apply enum_ok.\n  + apply NoneElement.\nQed.\n\n#[global]\nInstance  finTypeC_Option(F: finType): finTypeC (EqType (option F)).\nProof.\n  eapply FinTypeC.  apply option_enum_ok.\nDefined.\n\n(* * Definition of sum as finType *)\n\n(* The sum of two nats can only be 1 if one of them is 1 and the other one is 0 *)\nLemma proveOne m n: m = 1 /\\ n = 0 \\/ n = 1 /\\ m = 0 -> m + n = 1.\nProof.\n  lia.\nQed.\n\nLemma sum_enum_ok (X: finType) (Y: finType) x :\n  count (toSumList1 Y (elem X) ++ toSumList2 X (elem Y)) x = 1.\nProof.\n  rewrite <- countSplit. apply proveOne. destruct x.\n  - left. split; cbn.\n    + rewrite toSumList1_count. apply enum_ok.\n    + apply toSumList2_missing.\n  - right. split; cbn.\n    + rewrite toSumList2_count. apply enum_ok.\n    + apply toSumList1_missing.\nQed.\n\n(* Instance declaration for sum types for  the type class *)\n#[global]\nInstance finTypeC_sum (X Y: finType) : finTypeC (EqType ( X + Y)).\nProof.\n  eapply FinTypeC. apply sum_enum_ok.\nDefined.\n\n(* Some hints to make the typeclass inference work *)\n\n#[export] Hint Extern 4 (finTypeC (EqType (_ * _))) => eapply finTypeC_Prod : typeclass_instances.\n#[export] Hint Extern 4 (finTypeC (EqType (_ + _))) => eapply finTypeC_sum : typeclass_instances.\n#[export] Hint Extern 4 (finTypeC (EqType (option _))) => eapply finTypeC_Option : typeclass_instances.\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/PSL/FiniteTypes/CompoundFinTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6883258952827364}}
{"text": "(* -*- mode: coq; mode: visual-line -*- *)\n(** * Theorems about the natural numbers, depending on TruncType *)\n\nRequire Export Coq.Init.Peano.\nRequire Import HoTT.Basics.\nRequire Import HoTT.Types.Bool.\nRequire Import HoTT.TruncType HoTT.DProp.\n\n(** We reopen these scopes so they take precedence over nat_scope; otherwise, now that we have [Coq.Init.Peano], we'd get [* : nat -> nat -> nat] rather than [* : Type -> Type -> Type]. *)\nGlobal Open Scope type_scope.\nGlobal Open Scope core_scope.\n\n(** But in this file, we want to be able to use the usual symbols for natural number arithmetic. *)\nLocal Open Scope nat_scope.\n\nScheme nat_ind := Induction for nat Sort Type.\nScheme nat_rec := Minimality for nat Sort Type.\n\n(** ** Arithmetic *)\n\nLemma nat_plus_n_O : forall n:nat, n = n + 0.\nProof.\n  induction n.\n  - reflexivity.\n  - simpl; apply ap; assumption.\nQed.\n\nLemma nat_plus_n_Sm : forall n m:nat, (n + m).+1 = n + m.+1.\nProof.\n  intros n m; induction n; simpl.\n  - reflexivity.\n  - apply ap; assumption.\nQed.\n\nDefinition nat_plus_comm (n m : nat) : n + m = m + n.\nProof.\n  revert m; induction n as [|n IH]; intros m; simpl.\n  - refine (nat_plus_n_O m).\n  - transitivity (m + n).+1.\n    + apply ap, IH.\n    + apply nat_plus_n_Sm.\nQed.\n\n(** ** Exponentiation *)\n\nFixpoint nat_exp (n m : nat) : nat\n  := match m with\n       | 0 => 1\n       | S m => nat_exp n m * n\n     end.\n\n(** ** Factorials *)\n\nFixpoint factorial (n : nat) : nat\n  := match n with\n       | 0 => 1\n       | S n => S n * factorial n\n     end.\n\n(* here ends the old Types/Nat.v and starts Spaces.v *)\n\n(** Much of the layout of this file is adapted from ssreflect *)\n\n(** ** Equality *)\n(** *** Boolean equality and its properties *)\n\nFixpoint code_nat (m n : nat) {struct m} : DHProp :=\n  match m, n with\n    | 0, 0 => True\n    | m'.+1, n'.+1 => code_nat m' n'\n    | _, _ => False\n  end.\n\nInfix \"=n\" := code_nat : nat_scope.\n\nFixpoint idcode_nat {n} : (n =n n) :=\n  match n as n return (n =n n) with\n    | 0 => tt\n    | S n' => @idcode_nat n'\n  end.\n\nFixpoint path_nat {n m} : (n =n m) -> (n = m) :=\n  match m as m, n as n return (n =n m) -> (n = m) with\n    | 0, 0 => fun _ => idpath\n    | m'.+1, n'.+1 => fun H : (n' =n m') => ap S (path_nat H)\n    | _, _ => fun H => match H with end\n  end.\n\nGlobal Instance isequiv_path_nat {n m} : IsEquiv (@path_nat n m).\nProof.\n  refine (isequiv_adjointify\n            (@path_nat n m)\n            (fun H => transport (fun m' => (n =n m')) H idcode_nat)\n            _ _).\n  { intros []; simpl.\n    induction n; simpl; trivial.\n    by destruct (IHn^)%path. }\n  { intro. apply path_ishprop. }\nDefined.\n\nDefinition equiv_path_nat {n m} : (n =n m) <~> (n = m)\n  := Build_Equiv _ _ (@path_nat n m) _.\n\nGlobal Instance decidable_paths_nat : DecidablePaths nat\n  := fun n m => decidable_equiv _ (@path_nat n m) _.\n\nCorollary hset_nat : IsHSet nat.\nProof.\n  exact _.\nDefined.\n\n(** ** Natural number ordering *)\n\nDefinition leq m n := ((m - n) =n 0).\nDefinition lt m n := leq (m.+1) n.\n\nNotation \"m <= n\" := (leq m n) : nat_scope.\nNotation \"m < n\" := (lt m n) : nat_scope.\nNotation \"m >= n\" := (n <= m) (only parsing) : nat_scope.\nNotation \"m > n\" := (n < m) (only parsing) : nat_scope.\n\n(** ** Theorems about natural number ordering *)\n\nFixpoint leq0n {n} : 0 <= n :=\n  match n as n return 0 <= n with\n    | 0 => tt\n    | n'.+1 => @leq0n n'\n  end.\n\nFixpoint subnn {n} : n - n =n 0 :=\n  match n as n return n - n =n 0 with\n    | 0 => tt\n    | n'.+1 => @subnn n'\n  end.\n\nGlobal Instance leq_refl : Reflexive leq\n  := @subnn.\n\nFixpoint leqnSn {n} : n <= S n :=\n  match n as n return n <= S n with\n  | 0 => tt\n  | n'.+1 => @leqnSn n'\n  end.\n\nFixpoint leq_transd {x y z} : (x <= y -> y <= z -> x <= z)%dprop :=\n  match x as x, y as y, z as z return (x <= y -> y <= z -> x <= z)%dprop with\n    | 0, 0, 0 => dprop_istrue\n    | x'.+1, 0, 0 => dprop_istrue\n    | 0, y'.+1, 0 => dprop_istrue\n    | 0, 0, z'.+1 => dprop_istrue\n    | x'.+1, y'.+1, 0 => dprop_istrue\n    | x'.+1, 0, z'.+1 => dprop_istrue\n    | 0, y'.+1, z'.+1 => @leq_transd 0 y' z'\n    | x'.+1, y'.+1, z'.+1 => @leq_transd x' y' z'\n  end.\n\nGlobal Instance leq_trans : Transitive (fun n m => leq n m)\n  := @leq_transd.\n\nFixpoint leq_antisymd {x y} : (x <= y -> y <= x -> x =n y)%dprop :=\n  match x as x, y as y return (x <= y -> y <= x -> x =n y)%dprop with\n    | 0, 0 => dprop_istrue\n    | x'.+1, y'.+1 => @leq_antisymd x' y'\n    | _, _ => dprop_istrue\n  end.\n\nLemma leq_antisym : forall {x y}, x <= y -> y <= x -> x = y.\nProof.\n  intros x y p q.\n  apply path_nat.\n  apply leq_antisymd; assumption.\nDefined.\n\nDefinition not_nltn n : ~ (n < n).\nProof.\n  induction n as [|n IH]; simpl.\n  - auto.\n  - apply IH.\nDefined.\n\nDefinition leq1Sn {n} : 1 <= n.+1 := tt.\n\nFixpoint leqdichot {m} {n} : ((m <= n) + (m > n))%type.\nProof.\n  induction m, n.\n  - left; reflexivity.\n  - left; apply leq0n.\n  - right; unfold lt; apply leq1Sn.\n  - assert ((m <= n) + (n < m)) as X by apply leqdichot.\n    induction X as [leqmn|ltnm].\n    + left; assumption.\n    + right; assumption.\nDefined.\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/theories/Spaces/Nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.68832589119419}}
{"text": "Add LoadPath \"D:\\sfsol\".\nRequire Export Stlc.\n\nModule STLCExtended.\n\nInductive ty : Type :=\n  | TArrow : ty -> ty -> ty\n  | TNat : ty\n  | TUnit : ty\n  | TProd : ty -> ty -> ty\n  | TSum : ty -> ty -> ty\n  | TList : ty -> ty.\n\nTactic Notation \"T_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"TArrow\" | Case_aux c \"TNat\"\n  | Case_aux c \"TProd\" | Case_aux c \"TUnit\"\n  | Case_aux c \"TSum\" | Case_aux c \"TList\" ].\n\nInductive tm : Type :=\n  | tvar : id -> tm\n  | tapp : tm -> tm -> tm\n  | tabs : id -> ty -> tm -> tm\n  | tnat : nat -> tm\n  | tsucc : tm -> tm\n  | tpred : tm -> tm\n  | tmult : tm -> tm -> tm\n  | tif0 : tm -> tm -> tm -> tm\n  | tpair : tm -> tm -> tm\n  | tfst : tm -> tm\n  | tsnd : tm -> tm\n  | tunit : tm\n  | tlet : id -> tm -> tm -> tm\n  | tinl : ty -> tm -> tm\n  | tinr : ty -> tm -> tm\n  | tcase : tm -> id -> tm -> id -> tm -> tm\n  | tnil : ty -> tm\n  | tcons : tm -> tm -> tm\n  | tlcase : tm -> tm -> id -> id -> tm -> tm\n  | tfix : tm -> tm.\n\nTactic Notation \"t_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"tvar\" | Case_aux c \"tapp\" | Case_aux c \"tabs\"\n  | Case_aux c \"tnat\" | Case_aux c \"tsucc\" | Case_aux c \"tpred\"\n  | Case_aux c \"tmult\" | Case_aux c \"tif0\"\n  | Case_aux c \"tpair\" | Case_aux c \"tfst\" | Case_aux c \"tsnd\"\n  | Case_aux c \"tunit\" | Case_aux c \"tlet\"\n  | Case_aux c \"tinl\" | Case_aux c \"tinr\" | Case_aux c \"tcase\"\n  | Case_aux c \"tnil\" | Case_aux c \"tcons\" | Case_aux c \"tlcase\"\n  | Case_aux c \"tfix\" ].\n\nFixpoint subst (x:id) (s:tm) (t:tm) : tm :=\n  match t with\n  | tvar y =>\n      if eq_id_dec x y then s else t\n  | tabs y T t1 =>\n      tabs y T (if eq_id_dec x y then t1 else (subst x s t1))\n  | tapp t1 t2 =>\n      tapp (subst x s t1) (subst x s t2)\n  | tnat x => tnat x\n  | tsucc t => tsucc (subst x s t)\n  | tpred t => tpred (subst x s t)\n  | tmult t1 t2 => tmult (subst x s t1) (subst x s t2)\n  | tif0 t1 t2 t3 => tif0 (subst x s t1) (subst x s t2)(subst x s t3)\n  | tpair t1 t2 => tpair (subst x s t1) (subst x s t2)\n  | tfst t1 => tfst (subst x s t1)\n  | tsnd t1 => tsnd (subst x s t1)\n  | tunit => tunit\n  | tlet y t1 t2 => if eq_id_dec x y then \n      tlet y (subst x s t1) t2 else\n      tlet y (subst x s t1) (subst x s t2)\n  | tinl T t => tinl T (subst x s t)\n  | tinr T t => tinr T (subst x s t)\n  | tcase t x1 t1 x2 t2 => if eq_id_dec x x1 then\n      if eq_id_dec x x2 then\n        tcase (subst x s t) x1 t1 x2 t2 else\n        tcase (subst x s t) x1 t1 x2 (subst x s t2)\n      else if eq_id_dec x x2 then\n        tcase (subst x s t) x1 (subst x s t1) x2 t2 else\n        tcase (subst x s t) x1 (subst x s t1) x2 (subst x s t2)\n  | tnil T => tnil T\n  | tcons t1 t2 => tcons (subst x s t1) (subst x s t2)\n  | tlcase t1 t2 x1 x2 t3 => if eq_id_dec x x1 then\n      tlcase (subst x s t1) (subst x s t2) x1 x2 t3\n      else if eq_id_dec x x2 then\n      tlcase (subst x s t1) (subst x s t2) x1 x2 t3\n      else tlcase (subst x s t1) (subst x s t2) x1 x2 (subst x s t3)\n  | tfix t => tfix (subst x s t)\n  end.\n\nNotation \"'[' x ':=' s ']' t\" := (subst x s t) (at level 20).\n\nInductive value : tm -> Prop :=\n  | v_abs : forall x T11 t12,\n      value (tabs x T11 t12)\n  | v_nat : forall x,\n      value (tnat x)\n  | v_unit : value tunit\n  | v_pair : forall t1 t2,\n      value t1 ->\n      value t2 ->\n      value (tpair t1 t2)\n  | v_inl : forall T t,\n      value t ->\n      value (tinl T t)\n  | v_inr : forall T t,\n      value t ->\n      value (tinr T t)\n  | v_nil : forall T,\n      value (tnil T)\n  | v_cons : forall t1 t2,\n      value t1 ->\n      value t2 ->\n      value (tcons t1 t2).\n\nHint Constructors value.\n\nReserved Notation \"t1 '==>' t2\" (at level 40).\n\nInductive step : tm -> tm -> Prop :=\n  | ST_AppAbs : forall x T11 t12 v2,\n         value v2 ->\n         (tapp (tabs x T11 t12) v2) ==> [x:=v2]t12\n  | ST_App1 : forall t1 t1' t2,\n         t1 ==> t1' ->\n         (tapp t1 t2) ==> (tapp t1' t2)\n  | ST_App2 : forall v1 t2 t2',\n         value v1 ->\n         t2 ==> t2' ->\n         (tapp v1 t2) ==> (tapp v1 t2')\n  | ST_Succ : forall t t',\n         t ==> t' ->\n         tsucc t ==> tsucc t'\n  | ST_SuccNat : forall x,\n         tsucc (tnat x) ==> tnat (S x)\n  | ST_Pred : forall t t',\n         t ==> t' ->\n         tpred t ==> tpred t'\n  | ST_PredNat : forall x,\n         tpred (tnat x) ==> tnat (pred x)\n  | ST_Mult1 : forall t1 t1' t2,\n         t1 ==> t1' ->\n         tmult t1 t2 ==> tmult t1' t2\n  | ST_Mult2 : forall v1 t2 t2',\n         value v1 ->\n         t2 ==> t2' ->\n         tmult v1 t2 ==> tmult v1 t2'\n  | ST_MultNat : forall x1 x2,\n         tmult (tnat x1) (tnat x2) ==> tnat (mult x1 x2)\n  | ST_IF0_Cond : forall t1 t1' t2 t3,\n         t1 ==> t1' ->\n         tif0 t1 t2 t3 ==> tif0 t1' t2 t3\n  | ST_If0_If : forall t1 t2,\n         tif0 (tnat 0) t1 t2 ==> t1\n  | ST_If0_Else : forall x t1 t2,\n         x <> 0 ->\n         tif0 (tnat x) t1 t2 ==> t2\n  | ST_Pair1 : forall t1 t1' t2,\n         t1 ==> t1' ->\n         tpair t1 t2 ==> tpair t1' t2\n  | ST_Pair2 : forall v1 t2 t2',\n         value v1 ->\n         t2 ==> t2' ->\n         tpair v1 t2 ==> tpair v1 t2'\n  | ST_First_Pair : forall t1 t2,\n         tfst (tpair t1 t2) ==> t1\n  | ST_Second_Pair : forall t1 t2,\n         tsnd (tpair t1 t2) ==> t2\n  | ST_First : forall t t',\n         t ==> t' ->\n         tfst t ==> tfst t'\n  | ST_Second : forall t t',\n         t ==> t' ->\n         tsnd t ==> tsnd t'\n  | ST_Let1 : forall x t1 t1' t2,\n         t1 ==> t1' ->\n         tlet x t1 t2 ==> tlet x t1' t2\n  | ST_LetValue : forall x v1 t2,\n         value v1 ->\n         tlet x v1 t2 ==> [x:=v1]t2\n  | ST_Inl : forall T t t',\n         t ==> t' ->\n         tinl T t ==> tinl T t'\n  | ST_Inr : forall T t t',\n         t ==> t' ->\n         tinr T t ==> tinr T t'\n  | ST_Case : forall t t' x1 t1 x2 t2,\n         t ==> t' ->\n         tcase t x1 t1 x2 t2 ==> tcase t' x1 t1 x2 t2\n  | ST_CaseInl : forall T t x1 t1 x2 t2,\n         tcase (tinl T t) x1 t1 x2 t2 ==> [x1:=t]t1\n  | ST_CaseInr : forall T t x1 t1 x2 t2,\n         tcase (tinr T t) x1 t1 x2 t2 ==> [x2:=t]t2\n  | ST_Cons : forall t t' t2,\n         t ==> t' ->\n         tcons t t2 ==> tcons t' t2\n  | ST_ConsValue : forall v1 t t',\n         value v1 ->\n         t ==> t' ->\n         tcons v1 t ==> tcons v1 t'\n  | ST_LCase1 : forall t1 t1' t2 x1 x2 t3,\n         t1 ==> t1' ->\n         tlcase t1 t2 x1 x2 t3 ==> tlcase t1' t2 x1 x2 t3\n  | ST_LCaseNil : forall T t2 x1 x2 t3,\n         tlcase (tnil T) t2 x1 x2 t3 ==> t2\n  | ST_LCaseCons : forall t2 x1 x2 t3 v1 v2,\n         value v1 ->\n         value v2 ->\n         tlcase (tcons v1 v2) t2 x1 x2 t3 ==>\n         [x1:=v1]([x2:=v2]t3)\n  | ST_Fix1 : forall t1 t1',\n         t1 ==> t1' ->\n         tfix t1 ==> tfix t1'\n  | ST_FixAbs : forall x T t,\n         tfix (tabs x T t) ==> [x:=tfix (tabs x T t)]t\n\nwhere \"t1 '==>' t2\" := (step t1 t2).\n\nTactic Notation \"step_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"ST_AppAbs\" | Case_aux c \"ST_App1\" | Case_aux c \"ST_App2\"\n    | Case_aux c \"ST_Succ\" | Case_aux c \"ST_Pred\"\n    | Case_aux c \"ST_Mult1\" | Case_aux c \"ST_Mult2\"\n    | Case_aux c \"ST_IF0_Cond\" | Case_aux c \"ST_IF0_If\"\n    | Case_aux c \"ST_IF0_Else\" | Case_aux c \"ST_Pair1\"\n    | Case_aux c \"ST_Pair2\" | Case_aux c \"ST_FirstPair\"\n    | Case_aux c \"ST_SecondPair\" | Case_aux c \"ST_First\"\n    | Case_aux c \"ST_Second\" | Case_aux c \"ST_Let1\"\n    | Case_aux c \"ST_LetValue\" | Case_aux c \"ST_Inl\"\n    | Case_aux c \"ST_Inr\" | Case_aux c \"ST_Case\"\n    | Case_aux c \"ST_CaseInl\" | Case_aux c \"ST_CaseInr\"\n    | Case_aux c \"ST_Cons\" | Case_aux c \"ST_ConsValue\"\n    | Case_aux c \"ST_LCase1\" | Case_aux c \"ST_LCaseNil\"\n    | Case_aux c \"ST_LCaseCons\" | Case_aux c \"ST_Fix1\"\n    | Case_aux c \"ST_FixAbs\"\n  ].\n\nNotation multistep := (multi step).\nNotation \"t1 '==>*' t2\" := (multistep t1 t2) (at level 40).\n\nHint Constructors step.\n\nDefinition context := partial_map ty.\n\nReserved Notation \"Gamma '|-' t '\\in' T\" (at level 40).\n\nInductive has_type : context -> tm -> ty -> Prop :=\n  | T_Var : forall Gamma x T,\n      Gamma x = Some T ->\n      Gamma |- (tvar x) \\in T\n  | T_Abs : forall Gamma x T11 T12 t12,\n      (extend Gamma x T11) |- t12 \\in T12 ->\n      Gamma |- (tabs x T11 t12) \\in (TArrow T11 T12)\n  | T_App : forall T1 T2 Gamma t1 t2,\n      Gamma |- t1 \\in (TArrow T1 T2) ->\n      Gamma |- t2 \\in T1 ->\n      Gamma |- (tapp t1 t2) \\in T2\n  | T_Nat : forall Gamma x,\n      Gamma |- tnat x \\in TNat\n  | T_Succ : forall Gamma t,\n      Gamma |- t \\in TNat ->\n      Gamma |- tsucc t \\in TNat\n  | T_Pred : forall Gamma t,\n      Gamma |- t \\in TNat ->\n      Gamma |- tpred t \\in TNat\n  | T_Mult : forall Gamma t1 t2,\n      Gamma |- t1 \\in TNat ->\n      Gamma |- t2 \\in TNat ->\n      Gamma |- tmult t1 t2 \\in TNat\n  | T_If : forall Gamma t1 t2 t3 T,\n      Gamma |- t1 \\in TNat ->\n      Gamma |- t2 \\in T ->\n      Gamma |- t3 \\in T ->\n      Gamma |- tif0 t1 t2 t3 \\in T\n  | T_Pair : forall Gamma t1 t2 T1 T2,\n      Gamma |- t1 \\in T1 ->\n      Gamma |- t2 \\in T2 ->\n      Gamma |- (tpair t1 t2) \\in (TProd T1 T2)\n  | T_First : forall Gamma t T1 T2,\n      Gamma |- t \\in (TProd T1 T2) ->\n      Gamma |- tfst t \\in T1\n  | T_Second : forall Gamma t T1 T2,\n      Gamma |- t \\in (TProd T1 T2) ->\n      Gamma |- tsnd t \\in T2\n  | T_Unit : forall Gamma,\n      Gamma |- tunit \\in TUnit\n  | T_Let : forall Gamma x t1 T1 t2 T2,\n      Gamma |- t1 \\in T1 ->\n      extend Gamma x T1 |- t2 \\in T2 ->\n      Gamma |- tlet x t1 t2 \\in T2\n  | T_Inl : forall Gamma t T1 T2,\n      Gamma |- t \\in T1 ->\n      Gamma |- tinl T2 t \\in TSum T1 T2\n  | T_Inr : forall Gamma t T1 T2,\n      Gamma |- t \\in T2 ->\n      Gamma |- tinr T1 t \\in TSum T1 T2\n  | T_Case : forall Gamma t0 T1 T2 x1 x2 t1 t2 T,\n      Gamma |- t0 \\in TSum T1 T2 ->\n      extend Gamma x1 T1 |- t1 \\in T ->\n      extend Gamma x2 T2 |- t2 \\in T ->\n      Gamma |- tcase t0 x1 t1 x2 t2 \\in T\n  | T_Nil : forall Gamma T,\n      Gamma |- tnil T \\in TList T\n  | T_Cons : forall Gamma t1 t2 T,\n      Gamma |- t1 \\in T ->\n      Gamma |- t2 \\in TList T ->\n      Gamma |- tcons t1 t2 \\in TList T\n  | T_LCase : forall Gamma h t t1 t2 t3 T1 T,\n      Gamma |- t1 \\in TList T1 ->\n      Gamma |- t2 \\in T ->\n      extend (extend Gamma h T1) t (TList T1) |- t3 \\in T ->\n      Gamma |- tlcase t1 t2 h t t3 \\in T\n  | T_Fix : forall Gamma t1 T1,\n      Gamma |- t1 \\in TArrow T1 T1 ->\n      Gamma |- tfix t1 \\in T1\n\nwhere \"Gamma '|-' t '\\in' T\" := (has_type Gamma t T).\n\nHint Constructors has_type.\n\nTactic Notation \"has_type_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"T_Var\" | Case_aux c \"T_Abs\" | Case_aux c \"T_App\"\n    | Case_aux c \"T_Nat\" | Case_aux c \"T_Succ\" | Case_aux c \"T_Pred\"\n    | Case_aux c \"T_Mult\" | Case_aux c \"T_If\" | Case_aux c \"T_Pair\"\n    | Case_aux c \"T_First\" | Case_aux c \"T_Second\" | Case_aux c \"T_Unit\"\n    | Case_aux c \"T_Let\" | Case_aux c \"T_Inl\" | Case_aux c \"T_Inr\"\n    | Case_aux c \"T_Case\" | Case_aux c \"T_Nil\" | Case_aux c \"T_Cons\"\n    | Case_aux c \"T_LCase\" | Case_aux c \"T_Fix\"\n].\n\nModule Examples.\n\nNotation a := (Id 0).\nNotation f := (Id 1).\nNotation g := (Id 2).\nNotation l := (Id 3).\nNotation k := (Id 6).\nNotation i1 := (Id 7).\nNotation i2 := (Id 8).\nNotation x := (Id 9).\nNotation y := (Id 10).\nNotation processSum := (Id 11).\nNotation n := (Id 12).\nNotation eq := (Id 13).\nNotation m := (Id 14).\nNotation evenodd := (Id 15).\nNotation even := (Id 16).\nNotation odd := (Id 17).\nNotation eo := (Id 18).\n\nHint Extern 2 (has_type _ (tapp _ _) _) =>\n  eapply T_App; auto.\n\nHint Extern 2 (has_type _ (tlcase _ _ _ _ _) _) => \n  eapply T_LCase; auto.\n\nHint Extern 2 (_ = _) => compute; reflexivity.\n\nModule Numtest.\n\nDefinition test :=\n  tif0\n    (tpred\n      (tsucc\n        (tpred\n          (tmult\n            (tnat 2)\n            (tnat 0)))))\n    (tnat 5)\n    (tnat 6).\n\nExample typechecks :\n  (@empty ty) |- test \\in TNat.\nProof.\n  unfold test.\n  auto 10. \nQed.\n\nExample numtest_reduces :\n  test ==>* tnat 5.\nProof.\n  unfold test. normalize.\nQed.\n\nEnd Numtest.\n\nModule Prodtest.\n\nDefinition test :=\n  tsnd\n    (tfst\n      (tpair\n        (tpair\n          (tnat 5)\n          (tnat 6))\n        (tnat 7))).\n\nExample typechecks :\n  (@empty ty) |- test \\in TNat.\nProof. unfold test. eauto 15. Qed.\n\nExample reduces :\n  test ==>* tnat 6.\nProof. unfold test. normalize. Qed.\n\nEnd Prodtest.\n\nModule LetTest.\n\nDefinition test :=\n  tlet\n    x\n    (tpred (tnat 6))\n    (tsucc (tvar x)).\n\nExample typechecks :\n  (@empty ty) |- test \\in TNat.\nProof. unfold test. eauto 15. Qed.\n\nExample reduces :\n  test ==>* tnat 6.\nProof. unfold test. normalize. Qed.\n\nEnd LetTest.\n\nModule Sumtest1.\n\nDefinition test :=\n  tcase (tinl TNat (tnat 5))\n    x (tvar x)\n    y (tvar y).\n\nExample typechecks :\n  (@empty ty) |- test \\in TNat.\nProof. unfold test. eauto 15. Qed.\n\nExample reduces :\n  test ==>* (tnat 5).\nProof. unfold test. normalize. Qed.\n\nEnd Sumtest1.\n\nModule Sumtest2.\n\nDefinition test :=\n  tlet\n    processSum\n    (tabs x (TSum TNat TNat)\n      (tcase (tvar x)\n         n (tvar n)\n         n (tif0 (tvar n) (tnat 1) (tnat 0))))\n    (tpair\n      (tapp (tvar processSum) (tinl TNat (tnat 5)))\n      (tapp (tvar processSum) (tinr TNat (tnat 5)))).\n\nExample typechecks :\n  (@empty ty) |- test \\in (TProd TNat TNat).\nProof. unfold test. eauto 15. Qed.\n\nExample reduces :\n  test ==>* (tpair (tnat 5) (tnat 0)).\nProof. unfold test. normalize. Qed.\n\nEnd Sumtest2.\n\nModule ListTest.\n\nDefinition test :=\n  tlet l\n    (tcons (tnat 5) (tcons (tnat 6) (tnil TNat)))\n    (tlcase (tvar l)\n       (tnat 0)\n       x y (tmult (tvar x) (tvar x))).\n\nExample typechecks :\n  (@empty ty) |- test \\in TNat.\nProof. unfold test. eauto 20. Qed.\n\nExample reduces :\n  test ==>* (tnat 25).\nProof. unfold test. normalize. Qed.\n\nEnd ListTest.\n\nModule FixTest1.\n\nDefinition fact :=\n  tfix\n    (tabs f (TArrow TNat TNat)\n      (tabs a TNat\n        (tif0\n           (tvar a)\n           (tnat 1)\n           (tmult\n              (tvar a)\n              (tapp (tvar f) (tpred (tvar a))))))).\n\nExample fact_typechecks :\n  (@empty ty) |- fact \\in (TArrow TNat TNat).\nProof. unfold fact. auto 10. \nQed.\n\nExample fact_example: \n  (tapp fact (tnat 4)) ==>* (tnat 24).\nProof. unfold fact. normalize. Qed.\n\nEnd FixTest1.\n\nModule FixTest2.\n\nDefinition map :=\n  tabs g (TArrow TNat TNat)\n    (tfix\n      (tabs f (TArrow (TList TNat) (TList TNat))\n        (tabs l (TList TNat)\n          (tlcase (tvar l)\n            (tnil TNat)\n            a l (tcons (tapp (tvar g) (tvar a))\n                         (tapp (tvar f) (tvar l))))))).\n\nExample map_typechecks :\n  empty |- map \\in \n    (TArrow (TArrow TNat TNat)\n      (TArrow (TList TNat) \n        (TList TNat))).\nProof. unfold map. auto 10. Qed.\n\nExample map_example :\n  tapp (tapp map (tabs a TNat (tsucc (tvar a))))\n         (tcons (tnat 1) (tcons (tnat 2) (tnil TNat)))\n  ==>* (tcons (tnat 2) (tcons (tnat 3) (tnil TNat))).\nProof. unfold map. normalize. Qed.\n\nEnd FixTest2.\n\nModule FixTest3.\n\nDefinition equal :=\n  tfix\n    (tabs eq (TArrow TNat (TArrow TNat TNat))\n      (tabs m TNat\n        (tabs n TNat\n          (tif0 (tvar m)\n            (tif0 (tvar n) (tnat 1) (tnat 0))\n            (tif0 (tvar n)\n              (tnat 0)\n              (tapp (tapp (tvar eq)\n                              (tpred (tvar m)))\n                      (tpred (tvar n)))))))).\n\nExample equal_typechecks :\n  (@empty ty) |- equal \\in (TArrow TNat (TArrow TNat TNat)).\nProof. unfold equal. auto 10. \nQed.\n\nExample equal_example1: \n  (tapp (tapp equal (tnat 4)) (tnat 4)) ==>* (tnat 1).\nProof. unfold equal. normalize. Qed.\n\nExample equal_example2: \n  (tapp (tapp equal (tnat 4)) (tnat 5)) ==>* (tnat 0).\nProof. unfold equal. normalize. Qed.\n\nEnd FixTest3.\n\nModule FixTest4.\n\nDefinition eotest :=\n  tlet evenodd\n    (tfix\n      (tabs eo (TProd (TArrow TNat TNat) (TArrow TNat TNat))\n        (tpair\n          (tabs n TNat\n            (tif0 (tvar n)\n              (tnat 1)\n              (tapp (tsnd (tvar eo)) (tpred (tvar n)))))\n          (tabs n TNat\n            (tif0 (tvar n)\n              (tnat 0)\n              (tapp (tfst (tvar eo)) (tpred (tvar n))))))))\n  (tlet even (tfst (tvar evenodd))\n  (tlet odd (tsnd (tvar evenodd))\n  (tpair\n    (tapp (tvar even) (tnat 3))\n    (tapp (tvar even) (tnat 4))))).\n\nExample eotest_typechecks :\n  (@empty ty) |- eotest \\in (TProd TNat TNat).\nProof. unfold eotest. eauto 30. \nQed.\n\nExample eotest_example1: \n  eotest ==>* (tpair (tnat 0) (tnat 1)).\nProof. unfold eotest. normalize. Qed.\n\nEnd FixTest4.\n\nEnd Examples.\n\nTheorem progress : forall t T,\n     empty |- t \\in T ->\n     value t \\/ exists t', t ==> t'.\nProof with eauto.\n  intros t T Ht.\n  remember (@empty ty) as Gamma.\n  generalize dependent HeqGamma.\n  has_type_cases (induction Ht) Case; intros HeqGamma; subst...\n  Case \"T_Var\".\n    inversion H.\n  Case \"T_App\".\n    right.\n    destruct IHHt1; subst...\n      destruct IHHt2; subst...\n        inversion H; subst; try (solve by inversion)...\n      inversion H0; subst...\n      inversion H;subst...\n  Case \"T_Succ\".\n    right.\n    destruct IHHt; subst...\n      inversion H; subst; try (solve by inversion)...\n      inversion H...\n  Case \"T_Pred\".\n    right.\n    destruct IHHt; subst...\n      inversion H; subst; try (solve by inversion)...\n      inversion H...\n  Case \"T_Mult\".\n    right.\n    destruct IHHt1; subst...\n      inversion H; subst; try (solve by inversion)...\n      destruct IHHt2; subst...\n        inversion H0; subst; try (solve by inversion)...\n        inversion H0...\n      inversion H...\n  Case \"T_If\".\n    right.\n    destruct IHHt1; subst...\n      inversion H; subst; try (solve by inversion).\n      destruct x...\n      inversion H...\n  Case \"T_Pair\".\n    destruct IHHt1; subst...\n      destruct IHHt2; subst...\n        inversion H0...\n      inversion H...\n  Case \"T_First\".\n    right.\n      destruct IHHt; subst...\n        inversion H; subst; try (solve by inversion)...\n        inversion H...\n  Case \"T_Second\".\n    right.\n      destruct IHHt; subst...\n        inversion H; subst; try (solve by inversion)...\n        inversion H...\n  Case \"T_Let\".\n    right.\n      destruct IHHt1; subst...\n        inversion H...\n  Case \"T_Inl\".\n    destruct IHHt; subst...\n      inversion H; subst; try (solve by inversion)...\n  Case \"T_Inr\".\n    destruct IHHt; subst...\n      inversion H; subst; try (solve by inversion)...\n  Case \"T_Case\".\n    right.\n      destruct IHHt1; subst...\n        inversion H; subst; try (solve by inversion).\n        inversion Ht1...\n        inversion Ht1...\n        inversion H...\n  Case \"T_Cons\".\n    destruct IHHt1; subst...\n      destruct IHHt2; subst...\n      inversion H0...\n      inversion H...\n  Case \"T_LCase\".\n    right.\n    destruct IHHt1; subst...\n      inversion H; subst; try (solve by inversion)...\n      inversion H...\n  Case \"T_Fix\".\n    right.\n      destruct IHHt; subst...\n      inversion H; subst; try (solve by inversion)...\n      inversion H...\n  Qed.\n\nInductive appears_free_in : id -> tm -> Prop :=\n  | afi_var : forall x,\n      appears_free_in x (tvar x)\n  | afi_app1 : forall x t1 t2,\n      appears_free_in x t1 -> appears_free_in x (tapp t1 t2)\n  | afi_app2 : forall x t1 t2,\n      appears_free_in x t2 -> appears_free_in x (tapp t1 t2)\n  | afi_abs : forall x y T11 t12,\n        y <> x ->\n        appears_free_in x t12 ->\n        appears_free_in x (tabs y T11 t12)\n  | afi_succ : forall x t,\n        appears_free_in x t ->\n        appears_free_in x (tsucc t)\n  | afi_pred : forall x t,\n        appears_free_in x t ->\n        appears_free_in x (tpred t)\n  | afi_mult1 : forall x t1 t2,\n        appears_free_in x t1 -> appears_free_in x (tmult t1 t2)\n  | afi_mult2 : forall x t1 t2,\n        appears_free_in x t2 -> appears_free_in x (tmult t1 t2)\n  | afi_if0_0 : forall x t1 t2 t3,\n        appears_free_in x t1 -> appears_free_in x (tif0 t1 t2 t3)\n  | afi_if0_1 : forall x t1 t2 t3,\n        appears_free_in x t2 -> appears_free_in x (tif0 t1 t2 t3)\n  | afi_if0_2 : forall x t1 t2 t3,\n        appears_free_in x t3 -> appears_free_in x (tif0 t1 t2 t3)\n  | afi_pair1 : forall x t1 t2,\n        appears_free_in x t1 -> appears_free_in x (tpair t1 t2)\n  | afi_pair2 : forall x t1 t2,\n        appears_free_in x t2 -> appears_free_in x (tpair t1 t2)\n  | afi_first : forall x t,\n        appears_free_in x t -> appears_free_in x (tfst t)\n  | afi_second : forall x t,\n        appears_free_in x t -> appears_free_in x (tsnd t)\n  | afi_Let1 : forall x y t1 t2,\n        appears_free_in x t1 -> appears_free_in x (tlet y t1 t2)\n  | afi_Let2 : forall x y t1 t2,\n        x<>y ->\n        appears_free_in x t2 ->\n        appears_free_in x (tlet y t1 t2)\n  | afi_inl : forall x T t,\n        appears_free_in x t -> appears_free_in x (tinl T t)\n  | afi_inr : forall x T t,\n        appears_free_in x t -> appears_free_in x (tinr T t)\n  | afi_case1 : forall x1 x2 x3 t1 t2 t3,\n        appears_free_in x1 t1 ->\n        appears_free_in x1 (tcase t1 x2 t2 x3 t3)\n  | afi_case2 : forall x1 x2 x3 t1 t2 t3,\n        x1<>x2 ->\n        appears_free_in x1 t2 ->\n        appears_free_in x1 (tcase t1 x2 t2 x3 t3)\n  | afi_case3 : forall x1 x2 x3 t1 t2 t3,\n        x1<>x3 ->\n        appears_free_in x1 t3 ->\n        appears_free_in x1 (tcase t1 x2 t2 x3 t3)\n  | afi_cons1 : forall x t1 t2,\n        appears_free_in x t1 ->\n        appears_free_in x (tcons t1 t2)\n  | afi_cons2 : forall x t1 t2,\n        appears_free_in x t2 ->\n        appears_free_in x (tcons t1 t2)\n  | afi_tlcase1 : forall x1 x2 x3 t1 t2 t3,\n        appears_free_in x1 t1 ->\n        appears_free_in x1 (tlcase t1 t2 x2 x3 t3)\n  | afi_tlcase2 : forall x1 x2 x3 t1 t2 t3,\n        appears_free_in x1 t2 ->\n        appears_free_in x1 (tlcase t1 t2 x2 x3 t3)\n  | afi_tlcase3 : forall x1 x2 x3 t1 t2 t3,\n        x1<>x2 -> \n        x1<>x3 -> \n        appears_free_in x1 t3 ->\n        appears_free_in x1 (tlcase t1 t2 x2 x3 t3)\n  | afi_fix : forall x t,\n        appears_free_in x t ->\n        appears_free_in x (tfix t).\n\nHint Constructors appears_free_in.\n\nLemma context_invariance : forall Gamma Gamma' t S,\n     Gamma |- t \\in S ->\n     (forall x, appears_free_in x t -> Gamma x = Gamma' x) ->\n     Gamma' |- t \\in S.\nProof with eauto.\n  intros. generalize dependent Gamma'.\n  has_type_cases (induction H) Case;\n    intros Gamma' Heqv...\n  Case \"T_Var\".\n    apply T_Var... rewrite <- Heqv...\n  Case \"T_Abs\".\n    apply T_Abs... apply IHhas_type. intros y Hafi.\n    unfold extend.\n    destruct (eq_id_dec x y)...\n  Case \"T_Mult\".\n    apply T_Mult...\n  Case \"T_If\".\n    apply T_If...\n  Case \"T_Pair\".\n    apply T_Pair...\n  Case \"T_Let\".\n    eapply T_Let...\n    apply IHhas_type2. intros. unfold extend.\n    destruct (eq_id_dec x x0)...\n  Case \"T_Case\".\n    eapply T_Case...\n    apply IHhas_type2. intros. unfold extend.\n    destruct (eq_id_dec x1 x)...\n    apply IHhas_type3. intros. unfold extend.\n    destruct (eq_id_dec x2 x)...\n  Case \"T_Cons\".\n    apply T_Cons...\n  Case \"T_LCase\".\n    eapply T_LCase...\n    apply IHhas_type3. intros. unfold extend.\n    destruct (eq_id_dec t x)...\n    destruct (eq_id_dec h x)...\nQed.\n\nLemma free_in_context : forall x t T Gamma,\n   appears_free_in x t ->\n   Gamma |- t \\in T ->\n   exists T', Gamma x = Some T'.\nProof with eauto.\n  intros x t T Gamma Hafi Htyp.\n  has_type_cases (induction Htyp) Case; inversion Hafi; subst...\n  Case \"T_Abs\".\n    destruct IHHtyp as [T' Hctx]... exists T'.\n    unfold extend in Hctx.\n    rewrite neq_id in Hctx...\n  Case \"T_Let\".\n    apply IHHtyp2 in H4. inversion H4; subst.\n    unfold extend in H. rewrite neq_id in H...\n  Case \"T_Case\".\n    apply IHHtyp2 in H6. inversion H6; subst.\n    unfold extend in H6. rewrite neq_id in H6...\n    apply IHHtyp3 in H6. inversion H6; subst.\n    unfold extend in H6. rewrite neq_id in H6...\n  Case \"T_LCase\".\n    apply IHHtyp3 in H7. inversion H7; subst.\n    unfold extend in H. rewrite neq_id in H...\n    rewrite neq_id in H...\n  Qed.\n\nLemma substitution_preserves_typing : forall Gamma x U v t S,\n     (extend Gamma x U) |- t \\in S ->\n     empty |- v \\in U ->\n     Gamma |- ([x:=v]t) \\in S.\nProof with eauto.\n  intros Gamma x U v t S Htypt Htypv.\n  generalize dependent Gamma. generalize dependent S.\n  t_cases (induction t) Case;\n    intros S Gamma Htypt; simpl; inversion Htypt; subst...\n  Case \"tvar\".\n    simpl.\n    destruct (eq_id_dec x i).\n      subst. unfold extend in H1. rewrite eq_id in H1.\n      inversion H1; subst. clear H1.\n      eapply context_invariance...\n      intros x Hcontra.\n      destruct (free_in_context _ _ S empty Hcontra) as [T' HT']...\n      inversion HT'.\n      apply T_Var... unfold extend in H1. rewrite neq_id in H1...\n  Case \"tabs\".\n    apply T_Abs...\n    destruct (eq_id_dec x i).\n      eapply context_invariance...\n      subst. intros x Hafi. unfold extend.\n      destruct (eq_id_dec i x)...\n      apply IHt. eapply context_invariance...\n      intros z Hafi. unfold extend.\n      destruct (eq_id_dec i z)...\n      subst. rewrite neq_id...\n  Case \"tlet\".\n    destruct (eq_id_dec x i);\n    eapply T_Let; eauto; eapply context_invariance...\n    intros. unfold extend. subst. destruct (eq_id_dec i x0)...\n    apply IHt2. eapply context_invariance...\n    intros. unfold extend. destruct (eq_id_dec i x0); eauto.\n    subst. rewrite neq_id...\n  Case \"tcase\".\n    destruct (eq_id_dec x i); subst...\n      destruct (eq_id_dec i i0); subst; eauto;\n        eapply T_Case; eauto; eapply context_invariance; eauto;\n        intros; unfold extend.\n        destruct (eq_id_dec i0 x)...\n        destruct (eq_id_dec i0 x)...\n        destruct (eq_id_dec i x)...\n      apply IHt3... eapply context_invariance...\n      intros. unfold extend. destruct (eq_id_dec i0 x); subst...\n      rewrite neq_id...\n    destruct (eq_id_dec x i0); subst; eauto;\n      eapply T_Case; eauto; eapply context_invariance...\n      apply IHt2. eapply context_invariance...\n      intros. unfold extend. destruct (eq_id_dec i x); subst...\n      rewrite neq_id...\n      intros. unfold extend. destruct (eq_id_dec i0 x); subst...\n      apply IHt2. eapply context_invariance...\n      intros. unfold extend. destruct (eq_id_dec i x0); subst...\n      rewrite neq_id...\n      apply IHt3. eapply context_invariance...\n      intros. unfold extend. destruct (eq_id_dec i0 x0); subst...\n      rewrite neq_id...\n  Case \"tlcase\".\n    destruct (eq_id_dec x i); subst...\n      eapply T_LCase... eapply context_invariance...\n      intros. unfold extend. destruct (eq_id_dec i0 x); subst...\n      destruct (eq_id_dec i x)...\n      destruct (eq_id_dec x i0); subst...\n      eapply T_LCase... eapply context_invariance...\n      intros; unfold extend. destruct (eq_id_dec i0 x); subst...\n      eapply T_LCase... apply IHt3.\n      eapply context_invariance... intros.\n      unfold extend. destruct(eq_id_dec i0 x0); subst...\n      rewrite neq_id...\n      destruct (eq_id_dec i x0); subst...\n      rewrite neq_id...\n  Qed.\n\nTheorem preservation : forall t t' T,\n     empty |- t \\in T ->\n     t ==> t' ->\n     empty |- t' \\in T.\nProof with eauto.\n  intros t t' T HT.\n  remember (@empty ty) as Gamma. generalize dependent HeqGamma.\n  generalize dependent t'.\n  has_type_cases (induction HT) Case;\n  intros t' HeqGamma HE; subst; inversion HE; subst...\n  Case \"T_App\".\n    inversion HE; subst...\n    apply substitution_preserves_typing with T1...\n    inversion HT1...\n  Case \"T_First\".\n    inversion HT...\n  Case \"T_Second\".\n    inversion HT...\n  Case \"T_Let\".\n    eapply substitution_preserves_typing...\n  Case \"T_Case\".\n    eapply substitution_preserves_typing...\n    inversion HT1...\n    eapply substitution_preserves_typing...\n    inversion HT1...\n  Case \"T_LCase\".\n    eapply substitution_preserves_typing...\n    eapply substitution_preserves_typing...\n    inversion HT1...\n    inversion HT1...\n  Case \"T_Fix\".\n    eapply substitution_preserves_typing...\n    inversion HT...\n  Qed.\n\nEnd STLCExtended.", "meta": {"author": "mmalone", "repo": "sfsol", "sha": "5888f4532a1ec1ababa21bef39e25eb26279f0e4", "save_path": "github-repos/coq/mmalone-sfsol", "path": "github-repos/coq/mmalone-sfsol/sfsol-5888f4532a1ec1ababa21bef39e25eb26279f0e4/MoreStlc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6883258780098332}}
{"text": "From mathcomp Require Import all_ssreflect.\nRequire Import ZArith.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nCheck Equality.axiom.\nCheck Zeq_bool.\nCheck rel.\n\nLemma Zeq_boolP : Equality.axiom Zeq_bool.\nProof.\n    move => x y.\n    by apply: (iffP idP); rewrite Zeq_is_eq_bool.\nQed.\n\nRestart.\nShow.\nUndo.\n\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/nat_ring.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6882874801572042}}
{"text": "Theorem all_perm :\n  forall (A : Type) (P : A -> A -> Prop),\n    (forall x y : A, P x y) -> forall x y : A, P y x.\nProof. intros A P H x y; apply H. Qed.\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 A P Q R S H H' c H0 H1.\n  apply H.\n  apply H'; assumption.\n  assumption.\n  Qed.\n  \n  \n", "meta": {"author": "Ablach", "repo": "CoqArt_exercises", "sha": "a2c38b095b6972e57a3c152ec22f3100475b6186", "save_path": "github-repos/coq/Ablach-CoqArt_exercises", "path": "github-repos/coq/Ablach-CoqArt_exercises/CoqArt_exercises-a2c38b095b6972e57a3c152ec22f3100475b6186/ch4/ch4-5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6882874801572042}}
{"text": "Require Import Reals.\nRequire Import Waterproof.AllTactics.\nRequire Import Waterproof.notations.notations.\nRequire Import Reals.ROrderedType.\nRequire Import Waterproof.theory.analysis.reals. (* Req_true is in here *)\nRequire Import Waterproof.load.\nImport databases_RealsAndIntegers.\nRequire Import micromega.Lra.\nOpen Scope R_scope.\n\nSection Definitions.\nContext (X : Metric_Space).\n\n(* Definition metric_to_base := Base. *)\n\nCoercion Base : Metric_Space >-> Sortclass.\n\nDefinition dist_positive :\n  ∀ x y : X, dist X x y ≥ 0\n  := dist_pos X.\n\nDefinition dist_non_degenerate :\n  ∀ x y : X, (dist X x y = 0) ⇒ (x = y). \n  Take x, y : X.\n  By (proj1(_,_,(dist_refl X x y))) we conclude that (dist X x y = 0 ⇨ x = y).\nDefined.\n\nDefinition dist_symmetric :\n  ∀ x y : X, dist X x y = dist X y x\n  := dist_sym X.\n\nDefinition dist_triangle_inequality :\n  ∀ x y z : X, dist X x z ≤ dist X x y + dist X y z.\n  Take x, y, z : X. \n  By (dist_tri X) we conclude that (dist X x z ≤ dist X x y + dist X y z).\nQed.\n\nDefinition dist_reflexive : ∀ x : X, dist X x x = 0.\n  Take x : X.\n  By (proj2(_,_,(dist_refl X x x))) we conclude that (dist X x x = 0).\nDefined.\n\nEnd Definitions.\n\n\n\n(** ** Expample : a discrete metric on the real line *)\n\nDefinition d_discrete_R : \n  ℝ → ℝ → ℝ := fun (x y : ℝ) => if Reqb x y then 0 else 3.\n\nLemma d'_eq_0 : forall x y : ℝ,\n  d_discrete_R x y = 0 -> (Reqb x y) = true.\nProof.\nTake x, y : ℝ.\nAssume that (d_discrete_R x y = 0) (i).\nEither (x = y) or (x ≠ y).\n+ Case (x = y).\n  By Req_true we conclude that (Reqb x y = true).\n\n+ Case (x ≠ y).\n  Expand the definition of d_discrete_R in (i).\n  That is, write (i) as ( (if Reqb x y then 0 else 3) = 0).\n  rewrite (Req_false x y n) in i.\n  It holds that (3 ≠ 0).\n  Contradiction.\nQed.\n\nLemma d'_eq_3 : forall x y : ℝ, d_discrete_R x y = 3 -> (Reqb x y) = false.\nProof.\nTake x, y : ℝ. \nAssume that (d_discrete_R x y = 3) (i).\nExpand the definition of d_discrete_R in (i).\nThat is, write (i) as ( (if Reqb x y then 0 else 3) = 3).\nEither (x = y) or (x ≠ y).\n+ Case (x = y).\n  rewrite (Req_true x y e) in i.\n  It holds that (0 ≠ 3).\n  Contradiction.\n+ Case (x ≠ y).\n  By Req_false we conclude that (Reqb x y = false).\nQed.\n\n#[export] Hint Resolve d'_eq_0 : reals.\n#[export] Hint Resolve d'_eq_3 : reals.\n#[export] Hint Extern 0 => unfold d_discrete_R; rewrite Req_true; lra : reals.\n#[export] Hint Extern 0 => unfold d_discrete_R; rewrite Req_false; lra : reals.", "meta": {"author": "impermeable", "repo": "coq-waterproof", "sha": "a32bad4e44fedb4038065d2b55660cd967c2d1fd", "save_path": "github-repos/coq/impermeable-coq-waterproof", "path": "github-repos/coq/impermeable-coq-waterproof/coq-waterproof-a32bad4e44fedb4038065d2b55660cd967c2d1fd/waterproof/theory/analysis/metric_spaces.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6882874777454983}}
{"text": "Set Implicit Arguments.\n\nRequire Import List.\n\nSection TopSection.\n\n  Fixpoint app_all A (ls : list (list A)) :=\n    match ls with\n      | nil => nil\n      | x :: xs => x ++ app_all xs\n    end.\n\n  Definition Disjoint A (ls1 ls2 : list A) := forall e : A, ~ (In e ls1 /\\ In e ls2).\n\n  Definition IsInjection A B (f : A -> B) := forall x y, x <> y -> f x <> f y.\n\n  Variable t : Type.\n  Variable B : Type.\n\n  Implicit Types ls : list t.\n  Implicit Types f : t -> B.\n  Implicit Types x y e a : t.\n\n  Lemma map_app_all : forall f lsls, map f (app_all lsls) = app_all (map (fun ls => map f ls) lsls).\n    induction lsls; simpl; intros; eauto.\n    rewrite map_app; f_equal; eauto.\n  Qed.\n\n  Require Import Sumbool.\n  Require Import GeneralTactics.\n\n  Lemma find_spec : forall (f : t -> bool) ls a, find f ls = Some a -> f a = true /\\ In a ls.\n    induction ls; simpl; intuition; try discriminate;\n    (destruct (sumbool_of_bool (f a)); \n     [rewrite e in H; injection H; intros; subst; eauto | \n      rewrite e in H; eapply IHls in H; openhyp; eauto]).\n  Qed.\n\n  Lemma find_spec_None : forall (f : t -> bool) ls, List.find f ls = None -> ~ exists a, List.In a ls /\\ f a = true.\n    induction ls; simpl; intuition.\n    openhyp; intuition.\n    openhyp.\n    subst.\n    rewrite H1 in H.\n    intuition.\n    eapply IHls.\n    discriminate.\n    discriminate.\n    destruct (f a); intuition.\n    discriminate.\n    eapply H2.\n    eexists; split; eauto.\n  Qed.\n\n  Lemma In_app_all_intro : forall lsls ls e, In e ls -> In ls lsls -> In e (app_all lsls).\n    induction lsls; simpl; intros.\n    eauto.\n    openhyp.\n    subst.\n    eapply in_or_app.\n    eauto.\n    eapply in_or_app.\n    right.\n    eauto.\n  Qed.\n\n  Lemma In_app_all_elim : forall lsls x, In x (app_all lsls) -> exists ls, In x ls /\\ In ls lsls.\n    induction lsls; simpl; intros.\n    intuition.\n    eapply in_app_or in H.\n    openhyp.\n    eexists.\n    eauto.\n    eapply IHlsls in H.\n    openhyp.\n    eexists; eauto.\n  Qed.\n\n  Lemma Disjoint_symm : forall ls1 ls2, Disjoint ls1 ls2 -> Disjoint ls2 ls1.\n    unfold Disjoint; intros; firstorder.\n  Qed.\n\n  Lemma Disjoint_incl : forall ls1 ls2 ls1' ls2', Disjoint ls1 ls2 -> incl ls1' ls1 -> incl ls2' ls2 -> Disjoint ls1' ls2'.\n    unfold Disjoint, incl; intros; firstorder.\n  Qed.\n\n  Lemma incl_map : forall f ls1 ls2, incl ls1 ls2 -> incl (map f ls1) (map f ls2).\n    unfold incl.\n    intros.\n    eapply in_map_iff in H0.\n    openhyp.\n    subst.\n    eapply H in H1.\n    eapply in_map_iff.\n    eexists.\n    eauto.\n  Qed.\n\n  Lemma Disjoint_map : forall f ls1 ls2, Disjoint (map f ls1) (map f ls2) -> Disjoint ls1 ls2.\n    unfold Disjoint; intros.\n    intuition.\n    eapply H.\n    split; eapply in_map; eauto.\n  Qed.\n\n  Lemma Injection_NoDup : forall f ls, IsInjection f -> NoDup ls -> NoDup (map f ls).\n    unfold IsInjection.\n    induction ls; simpl; intros.\n    econstructor.\n    inversion H0; subst.\n    econstructor.\n    intuition.\n    contradict H3. \n    eapply in_map_iff in H1.\n    openhyp.\n    eapply H in H1.\n    intuition.\n    intros.\n    subst.\n    inversion H0; subst.\n    contradiction.\n    eapply IHls.\n    eauto.\n    eauto.\n  Qed.\n\n  Lemma NoDup_app : forall ls1 ls2, NoDup ls1 -> NoDup ls2 -> Disjoint ls1 ls2 -> NoDup (ls1 ++ ls2).\n    unfold Disjoint.\n    induction ls1; simpl; intros.\n    eauto.\n    econstructor.\n    intuition.\n    eapply in_app_or in H2.\n    openhyp.\n    inversion H; subst.\n    contradiction.\n    eapply H1.\n    eauto.\n    eapply IHls1.\n    inversion H; subst.\n    eauto.\n    eauto.\n    intros.\n    firstorder.\n  Qed.\n\nEnd TopSection.", "meta": {"author": "mmcco", "repo": "Verified-BPF", "sha": "f103ec2b08344c72e6d4fc6d08b8844f01748676", "save_path": "github-repos/coq/mmcco-Verified-BPF", "path": "github-repos/coq/mmcco-Verified-BPF/Verified-BPF-f103ec2b08344c72e6d4fc6d08b8844f01748676/bedrock/platform/cito/ListFacts1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6882874732325883}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra all_field.\nRequire Import extra_mathcomp posnum hanson_elem_arith.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport Order.TTheory GRing.Theory Num.Theory.\n\nLocal Open Scope ring_scope.\n\nNotation \"r '%:C'\" := (ratr r : algC) (at level 8). (* random level *)\n\n(* Section presenting the theory of exp_quo, which corresponds to\ntaking a rational exponent of a complex algebraic number *)\nSection RationalPower.\n\nDefinition exp_quo r p q := q.-root r%:C ^+ p.\n\nArguments exp_quo r p%nat q%nat : simpl never.\n\nLemma exp_quo_0 p q : exp_quo 0 p q = (p == 0%N)%:R.\nProof. by rewrite /exp_quo /ratr mul0r rootC0 expr0n. Qed.\n\nLemma exp_quo_1 p q : (0 < q)%N -> exp_quo 1 p q = 1.\nProof. by move => Hq; rewrite /exp_quo rmorph1 rootC1 // expr1n. Qed.\n\nLemma exp_quoMl r1 r2 p1 q1 (Hr1 : 0 <= r1) :\n  exp_quo (r1 * r2) p1 q1 = exp_quo r1 p1 q1 * exp_quo r2 p1 q1.\nProof. by rewrite /exp_quo rmorphM /= rootCMl ?exprMn ?ler0q. Qed.\n\nLemma exp_quoMr r1 r2 p1 q1 (Hr2 : 0 <= r2) :\n  exp_quo (r1 * r2) p1 q1 = exp_quo r1 p1 q1 * exp_quo r2 p1 q1.\nProof. by rewrite mulrC exp_quoMl // mulrC. Qed.\n\nLemma exp_quoV r p q : 0 <= r -> exp_quo r^-1 p q = (exp_quo r p q)^-1.\nProof.\nrewrite /exp_quo fmorphV /=; case: q => [|q] r_ge_0.\n  by rewrite !root0C expr0n; case: eqP; rewrite (invr0, invr1).\nby rewrite rootCV ?ler0q // exprVn.\nQed.\n\nLemma exp_quo_lessE r1 r2 p1 q1 p2 q2 :\n    0 <= r1 -> 0 <= r2 -> (0 < q1)%N -> (0 < q2)%N ->\n    (exp_quo r1 p1 q1 <= exp_quo r2 p2 q2) =\n    (r1%:C ^+ (p1 * q2) <= r2%:C ^+ (p2 * q1)).\nProof.\nmove=> Hr1 Hr2 Hq1 Hq2; rewrite /exp_quo -!rootCX ?ler0q //.\nrewrite root_le_x // ?rootC_ge0 ?exprn_ge0 ?ler0q //.\nby rewrite -rootCX ?root_x_le ?exprn_ge0 ?ler0q // -!exprM.\nQed.\n\nLemma exp_quo_less r1 r2 p q :\n  (0 < q)%N -> 0 <= r1 -> 0 <= r2 -> r1 <= r2 ->\n  exp_quo r1 p q <= exp_quo r2 p q.\nProof.\nmove => Hq H1 H2 Hleq.\nby rewrite exp_quo_lessE // ler_expn2r ?ler_rat // nnegrE ler0q.\nQed.\n\nLemma exp_quo_lessn r1 (p1 q1 p2 q2 : nat) :\n  (0 < q1)%N -> (0 < q2)%N -> 1 <= r1 -> (p1 * q2 <= p2 * q1)%N ->\n  exp_quo r1 p1 q1 <= exp_quo r1 p2 q2.\nProof.\nmove => Hq1 Hq2 H1r Hle.\nhave H0r : 0 <= r1 by apply/le_trans/H1r/ler01.\nby rewrite exp_quo_lessE // exp_incr_expp ?ler1q.\nQed.\n\nLemma exp_quo_r_nat r i : (r ^+ i)%:C = exp_quo r i 1.\nProof. by rewrite /exp_quo root1C CratrE /=. Qed.\n\nLemma exp_quo_nat_nat i j : (i ^ j)%:R%:C = exp_quo i%:Q j 1.\nProof. by rewrite natrX exp_quo_r_nat. Qed.\n\nLemma exp_quo_plus r1 p1 q1 p2 q2 :\n  (0 < q1)%N -> (0 < q2)%N -> 0 <= r1 ->\n  exp_quo r1 (p1 * q2 + p2 * q1) (q1 * q2) =\n  exp_quo r1 p1 q1 * exp_quo r1 p2 q2.\nProof.\nmove => Hq1pos Hq2pos Hr1pos.\nrewrite [LHS]exprD [in l in l * _ = _]mulnC !prod_root ?ler0q //.\nby rewrite mulnC exprM mulnC exprM !rootCK.\nQed.\n\nLemma exp_quo_equiv r1 p1 q1 p2 q2 :\n  (0 < q1)%N -> (0 < q2)%N -> 0 <= r1 -> (p1 * q2 = p2 * q1)%N ->\n  exp_quo r1 p1 q1 = exp_quo r1 p2 q2.\nProof.\nmove => Hq1pos Hq2pos Hr1pos Heq.\nhave Hprodpos : (0 < q1 * q2)%N by rewrite muln_gt0 Hq1pos Hq2pos.\nsuff : q1.-root r1%:C ^+ p1 ^+ (q1 * q2) = q2.-root r1%:C ^+ p2 ^+ (q1 * q2).\n  by apply: pexpIrn; rewrite // nnegrE exprn_ge0 ?rootC_ge0 ?ler0q.\nrewrite !exprM ![_ ^+ _ ^+ q1]exprAC -exprM ![_ ^+ _ ^+ q2]exprAC !rootCK //.\nby rewrite -exprM Heq mulnC.\nQed.\n\nLemma exp_quo_ge0 r p q : (0 < q)%N -> 0 <= r -> 0 <= exp_quo r p q.\nProof. by move=> Hq Hr; rewrite exprn_gte0 ?rootC_ge0 ?ler0q. Qed.\n\nLemma exp_quo_gt0 r p q : (0 < q)%N -> (0 < r) ->  0 < exp_quo r p q.\nProof. by move => Hq Hr; rewrite exprn_gte0 ?rootC_gt0 ?ltr0q. Qed.\n\nLemma exp_quo_ge1 r p q : (0 < q)%N -> (1 <= r) -> 1 <= exp_quo r p q.\nProof. by move => Hq Hr; rewrite exprn_ege1 ?rootC_ge1 ?ler1q. Qed.\n\nLemma exp_quo_gt1 r p q : (0 < p)%N -> (0 < q)%N -> 1 < r -> 1 < exp_quo r p q.\nProof. by move => Hp Hq Hr; rewrite exprn_egt1 ?rootC_gt1 ?ltr1q -?lt0n. Qed.\n\nLemma sqrtC_exp_quo (r : rat) : sqrtC r%:C = exp_quo r 1%N 2%N.\nProof. by rewrite /exp_quo expr1. Qed.\n\nLemma exp_quo_self_grows (p1 q1 p2 q2 : nat) r1 r2 :\n  (0 < q1)%N ->\n  (0 < q2)%N ->\n  r1 = p1%:Q / q1%:Q ->\n  r2 = p2%:Q / q2%:Q ->\n  0 < r1 ->\n  1 <= r2 ->\n  r1 <= r2 ->\n  exp_quo r1 p1 q1 <= exp_quo r2 p2 q2.\nProof.\nmove => Hq1 Hq2 Hr1 Hr2 Hr1gt0 Hle1r2 Hle12.\nhave Hr1pos : 0 <= r1 by apply: ltW.\nhave Hr2pos : 0 <= r2 by rewrite Hr2 divr_ge0 // ?ler0z.\nhave: r1%:C ^+ (p1 * q2) <= r2%:C ^+ (p1 * q2).\n  by rewrite ler_expn2r ?ler_rat // nnegrE ler0q.\nrewrite exp_quo_lessE // => /le_trans -> //; rewrite exp_incr_expp ?ler1q //.\nmove: Hle12; rewrite Hr1 Hr2 ler_pdivr_mulr ?ltr0n //.\nby rewrite mulrAC ler_pdivl_mulr ?ltr0n // -!natrM ler_nat.\nQed.\n\nEnd RationalPower.\n\n(* This Section contains a collection of four facts used in the proof\nof Hanson's lemma: a comparison of factorial to a geometric sequence,\nthe formula for summing a geometric sequence, and a bound on (1 + 1 /\nx) ^ x *)\nSection FourFacts.\n\n(* A lemma comparing factorial to a geometric sequence *)\nLemma fact_greater_geom i : i.+1`!%:R >= (3%:Q / 2%:Q) ^+ i.\nProof.\nelim: i => // i IHi; rewrite exprS factS natrM; apply: ler_pmul IHi => //.\nby rewrite ler_pdivr_mulr ?ltr0n // mulr_natr -mulrnA ler_nat.\nQed.\n\n(* Formula for a geometric sum in a field *)\nLemma geometric_sum (R : numFieldType) n (r : R) (Hr : r != 1) :\n  \\sum_(i < n) r ^+ i = (1 - r ^+ n) / (1 - r).\nProof.\nelim: n => [|n Hn]; first by rewrite big_ord0 expr0 subrr mul0r.\nhave den_neq0 : 1 - r != 0 by rewrite subr_eq0 eq_sym.\nrewrite big_ord_recr /= Hn; apply: canRL (mulfK den_neq0) _.\nby rewrite [LHS]mulrDl divfK // mulrBr mulr1 addrA subrK exprSr.\nQed.\n\n(* A bound on (1 + 1 / (n+1)) ^ (n+2) *)\nLemma one_plus_invn_expn (n : nat) : (1 + n%:Q^-1) ^+ n.+1 <= 8%:Q.\nProof.\ncase: n => // n.\nhave step: (1 + n.+1%:Q^-1) ^+ n.+1 <= \\sum_(i < n.+2) i`!%:Q^-1.\n  rewrite exprDn; apply: ler_sum => i _; rewrite expr1n mul1r -mulr_natr exprVn.\n  rewrite ler_pdivr_mull ?ler_pdivl_mulr ?ltr0n ?expn_gt0 ?fact_gt0 //.\n  by rewrite -natrM bin_ffact -natrX ler_nat ffact_le_expn.\nhave {step}: (1 + n.+1%:Q^-1) ^+ n.+2 <= 2%:Q * \\sum_(i < n.+2) i`!%:Q^-1.\n  rewrite exprS; apply: ler_pmul => //.\n  by rewrite -[2%:Q]/(1 + 1) ler_add2l invf_le1 // ler1z.\nmove/le_trans; apply; rewrite -[8%:Q]/(2%:Q * 4%:Q) ler_pmul2l //.\nhave: 1 + \\sum_(i < n.+1) (2%:Q / 3%:Q) ^+ i <= 4%:Q.\n  rewrite geometric_sum // -[4%:Q]/(1 + 3%:Q) ler_add2l.\n  have -> : 1 - 2%:Q / 3%:Q = 3%:Q^-1 by [].\n  by rewrite invrK ler_pimull // ler_subl_addr ler_addl.\napply: le_trans; rewrite big_ord_recl ler_add2l; apply: ler_sum => i _ /=.\nby rewrite -invf_div exprVn lef_pinv ?posrE ?ltr0n ?fact_gt0 ?fact_greater_geom.\nQed.\n\n(* TODO : clean up, use more ^-1 *)\n(* this proof is very long in big part because of exp_quo *)\nLemma one_plus_invx_expx (p q : nat) :\n  0 < p%:Q / q%:Q -> exp_quo (1 + q%:Q / p%:Q) p q <= ratr 9%:Q.\nProof.\nmove=> /ltr_neq.\nrewrite eq_sym mulf_eq0 invr_eq0 negb_or !intr_eq0 -!lt0n => /andP[Hp Hq].\nhave [leqp|ltpq] := leqP q p.\n\n(* First part : q <= p *)\npose f := (p %/ q)%N.\napply: (@le_trans _ _ (ratr 8%:Q)); last by rewrite ler_rat.\nsuff: exp_quo (1 + q%:~R / p%:~R) p q <= exp_quo (1 + f%:Q^-1) f.+1 1.\n  by move=> /le_trans -> //; rewrite -exp_quo_r_nat ler_rat one_plus_invn_expn.\nrewrite exp_quo_lessE ?addr_ge0 ?mulr_ge0 ?invr_ge0 ?ler0n // muln1.\nhave: (1 + f%:~R^-1)%:C ^+ p <= (1 + f%:~R^-1)%:C ^+ (f.+1 * q).\n  by rewrite exp_incr_expp ?ler1q ?ler_addl ?invr_ge0 ?ler0n 1?ltnW ?ltn_ceil.\napply: le_trans.\nrewrite ler_expn2r ?nnegrE ?ler0q ?addr_ge0 ?mulr_ge0 ?invr_ge0 ?ler0n //.\nrewrite ler_rat ler_add2l ler_pdivr_mulr ?ltr0n // mulrC.\nrewrite ler_pdivl_mulr ?ltr0n ?divn_gt0 //.\nby rewrite -intrM ler_nat mulnC leq_trunc_div.\n\n(* Second part : p < q *)\npose f := (q %/ p)%N.\nhave Helper0 : (0 < f)%N.\n  by rewrite divn_gt0 // ltnW.\nhave Helper1 : 0 <= 1 + q%:Q / p%:Q.\n  by rewrite addr_ge0 ?divr_ge0 ?ler0n.\nhave Helper2 : 1 + q%:Q / p%:Q <= 1 + (1 + f%:~R).\n  rewrite ler_add2l -mulrS ler_pdivr_mulr ?ltr0n // -natrM ler_nat.\n  by rewrite ltnW ?ltn_ceil.\nhave Helper3 : (p * f <= q)%N.\n  by rewrite mulnC leq_trunc_div.\napply: (@le_trans _ _ (exp_quo (1 + (1 + f%:Q)) p q)).\n  by apply: exp_quo_less; rewrite // !addr_ge0 ?ler0n.\napply: (@le_trans _ _ (exp_quo (1 + (1 + f%:Q)) 1 f)).\n  by apply: exp_quo_lessn; rewrite //= ?ler_addl ?addr_ge0 ?ler0n // mul1n.\napply: (@le_trans _ _ (exp_quo ((3 ^ f.+1)%N%:Q) 1 f)).\n  rewrite exp_quo_less // ?addr_ge0 ?ler0n //.\n  by rewrite -rat1 -!natrD ler_nat !add1n replace_exponential.\nrewrite /exp_quo expr1 !CratrE expnS natrM rootCMr ?ler0n //.\nhave -> : 9%:R = 3%:R * 3%:R :> algC by rewrite -natrM.\nby rewrite ler_pmul ?root_le_x ?rootC_ge0 ?ler0n ?natrX // ler_eexpr ?ler1n.\nQed.\n\nEnd FourFacts.\n", "meta": {"author": "coq-community", "repo": "apery", "sha": "305046d98025d75ca426cc44283302963389f1dc", "save_path": "github-repos/coq/coq-community-apery", "path": "github-repos/coq/coq-community-apery/apery-305046d98025d75ca426cc44283302963389f1dc/theories/hanson_elem_analysis.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6882874680986737}}
{"text": "Require Import CSet Var.\n\nDefinition vars_up_to (n:var) :=\n  Pos.peano_rect (fun _ => set var)\n                 {}\n                 (fun x X => {x; X})\n                 n.\n\nLemma inj_lt x y\n  : (x < y)%positive\n    <-> Pos.to_nat x < Pos.to_nat y.\nProof.\n  rewrite <- (Pos2Nat.id y) at 1.\n  rewrite <- (Pos2Nat.id x) at 1.\n  unfold Pos.lt.\n  rewrite <- Nat2Pos.inj_compare; eauto.\n  - rewrite Nat.compare_lt_iff. reflexivity.\n  - exploit (Pos2Nat.is_pos x). simpl in *. omega.\n  - exploit (Pos2Nat.is_pos y). simpl in *. omega.\nQed.\n\nLemma inj_le x y\n  : (x <= y)%positive\n    <-> Pos.to_nat x <= Pos.to_nat y.\nProof.\n  rewrite <- (Pos2Nat.id y) at 1.\n  rewrite <- (Pos2Nat.id x) at 1.\n  unfold Pos.le.\n  rewrite <- Nat2Pos.inj_compare; eauto.\n  - rewrite Nat.compare_le_iff. reflexivity.\n  - exploit (Pos2Nat.is_pos x). simpl in *. omega.\n  - exploit (Pos2Nat.is_pos y). simpl in *. omega.\nQed.\n\nLemma vars_up_to_in (x i:var)\n  : (x < i)%positive <-> x ∈ vars_up_to i.\nProof.\n  unfold vars_up_to.\n  revert x.\n  induction i using Pos.peano_ind; intros.\n  - rewrite Pos.peano_rect_base.\n    split; intros.\n    + exfalso.\n      eapply inj_lt in H.\n      rewrite Pos2Nat.inj_1 in H.\n      exploit (Pos2Nat.is_pos x). simpl in *. omega.\n    + cset_tac.\n  - rewrite Pos.peano_rect_succ.\n    cset_tac'.\n    + eapply IHi.\n      eapply inj_lt.\n      eapply inj_lt in H.\n      rewrite Pos2Nat.inj_succ in *.\n      decide (Pos.to_nat i = Pos.to_nat x).\n      * simpl in *. exfalso. eapply n. hnf.\n        eapply Pos2Nat.inj in e. eauto.\n      * omega.\n    + eapply inj_lt.\n      rewrite Pos2Nat.inj_succ. omega.\n    + eapply IHi in H0.\n      eapply inj_lt in H0.\n      eapply inj_lt.\n      rewrite Pos2Nat.inj_succ. omega.\nQed.\n\nLemma in_vars_up_to (n m:var)\n: (n < m)%positive -> n ∈ vars_up_to m.\nProof.\n  intros. eapply vars_up_to_in. eauto.\nQed.\n\nLemma in_vars_up_to' n m\n: (n <= m)%positive -> n ∈ vars_up_to (m + 1)%positive.\nProof.\n  intros. eapply vars_up_to_in.\n  eapply inj_lt. eapply inj_le in H.\n  rewrite Pos.add_1_r. rewrite Pos2Nat.inj_succ. omega.\nQed.\n\nLemma vars_up_to_incl n m\n: (n <= m)%positive -> vars_up_to n ⊆ vars_up_to m.\nProof.\n  intros H x IN. eapply vars_up_to_in; eapply vars_up_to_in in IN.\n  eapply inj_lt; eapply inj_lt in IN. eapply inj_le in H. omega.\nQed.\n\nLemma vars_up_to_max n m\n: vars_up_to (Pos.max n m) [=] vars_up_to n ∪ vars_up_to m.\nProof.\n  hnf. intros.\n  rewrite <- !vars_up_to_in.\n  cset_tac'.\n  - rewrite <- !vars_up_to_in in *.\n    rewrite inj_lt in *.\n    rewrite Pos2Nat.inj_max in *.\n    decide ((Pos.to_nat n) <= (Pos.to_nat m)).\n    + rewrite Max.max_r in H; eauto.\n    + rewrite Max.max_l in H; omega.\n  - rewrite <- !vars_up_to_in in *.\n    rewrite inj_lt in *.\n    rewrite Pos2Nat.inj_max in *.\n    decide ((Pos.to_nat n) <= (Pos.to_nat m)).\n    + rewrite Max.max_r; omega.\n    + rewrite Max.max_l; omega.\n  - rewrite <- !vars_up_to_in in *.\n    rewrite inj_lt in *.\n    rewrite Pos2Nat.inj_max in *.\n    decide ((Pos.to_nat n) <= (Pos.to_nat m)).\n    + rewrite Max.max_r; omega.\n    + rewrite Max.max_l; omega.\nQed.\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Infra/VarsUpTo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6882874656869674}}
{"text": "Require Import List.\nSet Implicit Arguments.\n\nInductive lfactor (A:Set) : list A -> list A -> Prop :=\n  | lf1 : forall u:list A, lfactor nil u\n  | lf2 : forall (a:A) (u v:list A), lfactor u v ->\n                                     lfactor (a :: u) (a :: v).\n\nDefinition lfactor_suffix :\n  forall (A:Set) (u v:list A), lfactor u v -> {w : list A | v = u ++ w}.\n intros A u; elim u.\n intros v; exists v; auto.\n intros a u' Hrec v; case v.\n intros Hf; cut False.\n contradiction.\n inversion Hf.\n intros b v' Hf.\n elim (Hrec v').\n intros r Heq; exists r.\n inversion Hf.\n simpl in |- *; rewrite <- Heq.\n trivial.\n inversion Hf; assumption.\nDefined.\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/induc-fond/SRC/factor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6882874614845601}}
{"text": "Require Import Specif.\nRequire Import Orders.\nRequire Import OrdersEx.\nRequire Import MSets.\nRequire Import Arith.\nRequire Import Omega.\n\nModule NatSet := Make Nat_as_OT.\nModule NatSetFacts := Facts NatSet.\n\nSection MSet_set.\n\n  Import NatSet.\n\n  Definition has_upper_bound n\n    := For_all (gt n).\n\n  Definition MFinNatSet (n:nat) : Type\n    := {s: t | has_upper_bound n s}.\n\n  Definition MsingleS (n:nat) (i:nat): MFinNatSet n.\n  Proof.\n    unfold MFinNatSet.\n    case (lt_dec i n); intros H.\n    -\n      exists (singleton i).\n      unfold has_upper_bound, For_all.\n      intros x I.\n      apply singleton_spec in I.\n      omega.\n    -\n      exists empty.\n      unfold has_upper_bound, For_all.\n      intros x I.\n      apply empty_spec in I.\n      contradiction.\n  Defined.\n\n  Example MFoo: Empty (inter\n                         (proj1_sig (MsingleS 5 2))\n                         (proj1_sig (MsingleS 5 1))).\n  Proof.\n    simpl.\n    unfold Empty.\n    intros a H.\n    apply inter_spec in H.\n    destruct H as [H1 H2].\n    apply singleton_spec in H1.\n    apply singleton_spec in H2.\n    congruence.\n  Qed.\n\n\n  (* Unbounded version *)\n  Fixpoint NatSet_indexf (n:nat) (f: nat -> bool): NatSet.t :=\n    match n with\n    | O => empty\n    | S j => union\n              (if f j then singleton j else empty)\n              (NatSet_indexf j f)\n    end.\n\n\n  Lemma empty_upper_bound:\n    has_upper_bound 0 empty.\n  Proof.\n    unfold has_upper_bound.\n    unfold For_all.\n    intros x H.\n    apply empty_spec in H.\n    contradiction.\n  Qed.\n\n  Lemma lt_gt:\n    forall m n, m < n <-> n > m.\n  Proof.\n    intros m n.\n    split; intros;omega.\n  Qed.\n\n\n  Lemma max_lb_l: forall n m p : nat, n > p -> max n m > p.\n  Proof.\n    intros n m p H.\n    assert (D: n < m /\\ Nat.max n m = m \\/ m <= n /\\ Nat.max n m = n) by apply Max.max_spec.\n    destruct D; omega.\n  Qed.\n\n  Lemma max_lb_r: forall n m p : nat, m > p -> max n m > p.\n  Proof.\n    intros n m p H.\n    assert (D: n < m /\\ Nat.max n m = m \\/ m <= n /\\ Nat.max n m = n) by apply Max.max_spec.\n    destruct D; omega.\n  Qed.\n\n  Lemma union_upper_bound\n        (ba bb:nat)\n        (a b: t):\n    has_upper_bound ba a -> has_upper_bound bb b ->\n    has_upper_bound (max ba bb) (union a b).\n  Proof.\n    intros A B.\n    unfold has_upper_bound, For_all in *.\n    intros x I.\n    specialize (A x).\n    specialize (B x).\n    rewrite union_spec in *.\n    destruct I as [IA | IB].\n    -\n      apply A in IA.\n      apply max_lb_l, IA.\n    -\n      apply B in IB.\n      apply max_lb_r, IB.\n  Qed.\n\n  Lemma singleton_upper_bound:\n    forall n, has_upper_bound (S n) (singleton n).\n  Proof.\n    intros n.\n    unfold has_upper_bound, For_all.\n    intros x H.\n    apply singleton_spec in H.\n    omega.\n  Qed.\n\n  Lemma weaken_upper_bound:\n    forall s n m, m>=n -> has_upper_bound n s -> has_upper_bound m s.\n  Proof.\n    intros s n m D U.\n    unfold has_upper_bound, For_all in *.\n    intros x H.\n    specialize (U x H).\n    omega.\n  Qed.\n\n  Lemma max_sn_n:\n    forall n : nat, Init.Nat.max (S n) n = S n.\n  Proof.\n    intros n.\n    induction n.\n    reflexivity.\n    rewrite <- IHn at 3.\n    rewrite Max.succ_max_distr.\n    reflexivity.\n  Qed.\n\n  Definition build_FinNatSet (n:nat) (f: nat -> bool): MFinNatSet n.\n  Proof.\n    exists (NatSet_indexf n f).\n    induction n.\n    -\n      apply empty_upper_bound.\n    -\n      simpl.\n      replace (S n) with (max (S n) n).\n      apply union_upper_bound.\n      case (f n).\n      + apply singleton_upper_bound.\n      + assert (E: has_upper_bound 0 empty) by apply empty_upper_bound.\n        apply weaken_upper_bound with (m:=S n) in E.\n        apply E.\n        omega.\n      + apply IHn.\n      + apply max_sn_n.\n  Defined.\n\n  Definition full_set (n:nat) (m b:nat): MFinNatSet n :=\n    build_FinNatSet n (fun _ => true).\n\n\nEnd MSet_set.\n", "meta": {"author": "vzaliva", "repo": "helix", "sha": "5d0a71df99722d2011c36156f12b04875df7e1cb", "save_path": "github-repos/coq/vzaliva-helix", "path": "github-repos/coq/vzaliva-helix/helix-5d0a71df99722d2011c36156f12b04875df7e1cb/experiments/MFinNatSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6882874614845601}}
{"text": "Require Import Classes.RelationClasses.\nRequire Import Permutation.\n\nFrom CoqAlgs Require Export Base.\nFrom CoqAlgs Require Export Ord.\nFrom CoqAlgs Require Export Data.ListLemmas.\n\n(*Set Universe Polymorphism.*)\n\nFixpoint count {A : Type} (p : A -> bool) (l : list A) : nat :=\nmatch l with\n    | [] => 0\n    | h :: t => (if p h then 1 else 0) + count p t\nend.\n\nDefinition perm {A : Type} (l1 l2 : list A) : Prop :=\n  forall p : A -> bool, count p l1 = count p l2.\n\n(* Lemmas about [count]. *)\n\nLemma count_app :\n  forall (A : Type) (p : A -> bool) (l1 l2 : list A),\n    count p (l1 ++ l2) = count p l1 + count p l2.\nProof.\n  induction l1; cbn; intros.\n    reflexivity.\n    rewrite IHl1. destruct (p a); cbn; reflexivity.\nQed.\n\nLemma count_app_comm :\n  forall (A : Type) (p : A -> bool) (l1 l2 : list A),\n    count p (l1 ++ l2) = count p (l2 ++ l1).\nProof.\n  induction l1 as [| h1 t1]; cbn; intros.\n    rewrite app_nil_r. reflexivity.\n    rewrite !count_app. cbn. destruct (p h1); lia.\nQed.\n\nLemma count_last :\n  forall (A : Type) (p : A -> bool) (l : list A) (x : A),\n    count p (l ++ [x]) = count p l + count p [x].\nProof.\n  intros. rewrite count_app. reflexivity.\nQed.\n\nLemma count_reverse :\n  forall (A : Type) (p : A -> bool) (l : list A),\n    count p (rev l) = count p l.\nProof.\n  induction l as [| h t]; cbn; intros.\n    reflexivity.\n    rewrite count_app, IHt. cbn. destruct (p h); lia.\nQed.\n\nLemma count_cons :\n  forall (A : Type) (p : A -> bool) (h : A) (t : list A),\n    p h = true -> count p (h :: t) = 1 + count p t.\nProof.\n  intros. cbn. rewrite H. reflexivity.\nQed.\n\nLemma count_filter :\n  forall (A : Type) (p1 p2 : A -> bool) (t : list A),\n    count p1 t = count p1 (filter p2 t) +\n                 count p1 (filter (fun x : A => negb (p2 x)) t).\nProof.\n  induction t as [| h' t']; cbn.\n    reflexivity.\n    destruct (p1 h') eqn: H, (p2 h'); cbn; rewrite ?H, ?IHt'; try\n      lia.\nQed.\n\nLemma count_In :\n  forall (A : Type) (p : A -> bool) (l : list A),\n    Exists (fun x => p x = true) l <-> count p l <> 0.\nProof.\n  split.\n    induction 1; cbn.\n      rewrite H. inv 1.\n      destruct (p x).\n        inv 1.\n        assumption.\n    induction l as [| h t]; cbn; intros.\n      contradiction.\n      destruct (p h) eqn: Hph.\n        left. assumption.\n        right. apply IHt, H.\nQed.\n\nLemma count_0_nil :\n  forall (A : Type) (l : list A),\n    (forall p : A -> bool, count p l = 0) -> l = [].\nProof.\n  induction l as [| h t]; cbn; intros.\n    reflexivity.\n    specialize (H (fun _ => true)). cbn in H. congruence.\nQed.\n\n(* Lemmas about [perm]. *)\nLemma perm_refl :\n  forall (A : Type) (l : list A), perm l l.\nProof. unfold perm; auto. Defined.\n\nLemma perm_symm :\n  forall (A : Type) (l1 l2 : list A),\n    perm l1 l2 -> perm l2 l1.\nProof. unfold perm; auto. Defined.\n\nLemma perm_trans :\n  forall (A : Type) (l1 l2 l3 : list A),\n    perm l1 l2 -> perm l2 l3 -> perm l1 l3.\nProof.\n  unfold perm; intros. eapply eq_trans; auto.\nDefined.\n\nLemma perm_cons :\n  forall (A : Type) (x : A) (l1 l2 : list A),\n    perm l1 l2 -> perm (x :: l1) (x :: l2).\nProof.\n  unfold perm. intros. simpl. rewrite H. reflexivity.\nDefined.\n\nLemma perm_nil_cons :\n  forall (A : Type) (h : A) (t : list A),\n    ~ perm (h :: t) [].\nProof.\n  unfold not; intros.\n  red in H. specialize (H (fun _ => true)).\n  cbn in H. inversion H.\nQed.\n\nLemma perm_swap :\n  forall (A : Type) (x y : A) (l1 l2 : list A),\n    perm l1 l2 -> perm (x :: y :: l1) (y :: x :: l2).\nProof.\n  unfold perm; cbn; intros.\n  destruct (p x), (p y); rewrite ?H; reflexivity.\nDefined.\n\nTheorem perm_front :\n  forall (A : Type) (x : A) (l1 l2 : list A),\n    perm (l1 ++ x :: l2) (x :: l1 ++ l2).\nProof.\n  induction l1 as [| h1 t1]; simpl; intros.\n    apply perm_refl.\n    eapply perm_trans with (h1 :: x :: t1 ++ l2).\n      apply perm_cons. apply IHt1.\n      apply perm_swap. apply perm_refl.\nQed.\n\n#[global] Hint Resolve perm_refl perm_symm perm_cons perm_swap perm_front : core.\n\nLemma perm_app_comm :\n  forall (A : Type) (l1 l2 : list A),\n    perm (l1 ++ l2) (l2 ++ l1).\nProof.\n  unfold perm. intros. apply count_app_comm.\nQed.\n\nLemma perm_app :\n  forall (A : Type) (l1 l1' l2 l2' : list A),\n    perm l1 l1' -> perm l2 l2' -> perm (l1 ++ l2) (l1' ++ l2').\nProof.\n  unfold perm; intros. rewrite 2 count_app, H, H0. auto.\nQed.\n\nLemma Exists_dec :\n  forall (A : Ord) (x : A) (l : list A),\n    Exists (fun y => y = x) l <->\n    Exists (fun y => y =? x = true) l.\nProof.\n  split; induction 1; subst; auto.\n    left. trich.\n    trich.\nQed.\n\nLemma perm_In :\n  forall (A : Ord) (x : A) (l l' : list A),\n    In x l -> perm l l' -> In x l'.\nProof.\n  intros. rewrite In_Exists, Exists_dec in *.\n  rewrite count_In. red in H0. rewrite <- H0, <- count_In.\n  assumption.\nQed.\n\n#[export]\nInstance Equiv_perm (A : Type) : Equivalence (@perm A).\nProof.\n  split; red; intros; eauto. eapply perm_trans; eauto.\nDefined.\n\nLemma perm_singl :\n  forall (A : Ord) (x : A) (l : list A),\n    perm [x] l -> l = [x].\nProof.\n  unfold perm; destruct l as [| h1 [| h2 t]]; cbn; intros.\n    specialize (H (fun _ => true)). cbn in H. inv H.\n    specialize (H (fun y => y =? h1)). cbn in H. trich.\n    {\n      assert (H1 := H (fun y => y =? h1)).\n      assert (H2 := H (fun y => y =? h2)).\n      cbn in *. trich.\n    }\nQed.\n\nLemma perm_cons_inv :\n  forall (A : Type) (h : A) (t1 t2 : list A),\n    perm (h :: t1) (h :: t2) -> perm t1 t2.\nProof.\n  unfold perm; intros.\n  specialize (H p). cbn in H.\n  destruct (p h).\n    inv H.\n    assumption.\nQed.\n\nLemma removeFirst_In_perm :\n  forall (A : Ord) (p : A -> bool) (x : A) (l : list A),\n    In x l -> p x = true ->\n      perm l (x :: removeFirst (fun y => y =? x) l).\nProof.\n  induction l as [| h t]; cbn; inv 1; trich.\n  intro. rewrite perm_swap.\n    apply perm_cons, IHt; assumption.\n    reflexivity.\nQed.\n\nFunction removeFirst' {A : Type} (p : A -> bool) (l : list A) : option (A * list A) :=\nmatch l with\n    | [] => None\n    | h :: t =>\n        if p h\n        then Some (h, t)\n        else\n          match removeFirst' p t with\n              | None => None\n              | Some (x, l') => Some (x, h :: l')\n          end\nend.\n\nLemma removeFirst'_perm :\n  forall {A : Type} {p : A -> bool} {l l' : list A} {x : A},\n    removeFirst' p l = Some (x, l') ->\n      perm l (x :: l').\nProof.\n  intros until l.\n  functional induction removeFirst' p l;\n  inv 1.\n  rewrite perm_swap.\n    apply perm_cons, IHo. eassumption.\n    reflexivity.\nQed.\n\nLemma perm_In' :\n  forall (A : Ord) (h : A) (t l : list A),\n    perm (h :: t) l -> In h l.\nProof.\n  intros. rewrite In_Exists, Exists_dec, count_In, <- H. cbn. trich.\nQed.\n\nLemma count_removeFirst_neq :\n  forall (A : Ord) (x y : A) (l : list A),\n    x <> y -> count (fun z => z =? x) (removeFirst (fun z => z =? y) l) =\n              count (fun z => z =? x) l.\nProof.\n  induction l as [| h t]; cbn; intros; trich; trich.\nQed.\n\nLemma count_removeFirst_In :\n  forall (A : Type) (p : A -> bool) (l : list A),\n    Exists (fun x => p x = true) l ->\n      count p (removeFirst p l) = count p l - 1.\nProof.\n  induction l as [| h t]; cbn; intros.\n    reflexivity.\n    destruct (p h) eqn: Hph; cbn.\n      lia.\n      rewrite Hph. inv H.\nQed.\n\nFixpoint removeFirst'' {A : Type} (p : A -> bool) (l : list A) : option (list A * A * list A) :=\nmatch l with\n    | [] => None\n    | h :: t =>\n        if p h\n        then Some ([], h, t)\n        else\n          match removeFirst'' p t with\n              | None => None\n              | Some (start, x, rest) => Some (h :: start, x, rest)\n          end\nend.\n\nFunctional Scheme removeFirst''_ind := Induction for removeFirst'' Sort Prop.\n\nLemma perm_removeFirst'' :\n  forall {A : Type} {p : A -> bool} {l s e : list A} {x : A},\n    removeFirst'' p l = Some (s, x, e) ->\n      perm l (s ++ x :: e).\nProof.\n  intros until l.\n  functional induction removeFirst'' p l;\n  inv 1.\n    cbn. apply perm_cons, IHo. assumption.\nQed.\n\nLemma removeFirst''_Exists_Some :\n  forall {A : Type} {p : A -> bool} {l : list A},\n    Exists (fun x : A => p x = true) l ->\n      exists (s e : list A) (x : A),\n        removeFirst'' p l = Some (s, x, e).\nProof.\n  intros until l.\n  functional induction removeFirst'' p l;\n  inv 1.\n    do 3 eexists. reflexivity.\n    do 3 eexists. reflexivity.\n    do 3 eexists. reflexivity.\n    destruct (IHo H1) as (s & e & x & IH). congruence.\nQed.\n\nLemma removeFirst''_spec :\n  forall {A : Type} {p : A -> bool} {l s e : list A} {x : A},\n    removeFirst'' p l = Some (s, x, e) ->\n      l = s ++ x :: e.\nProof.\n  intros until l.\n  functional induction removeFirst'' p l;\n  inv 1.\n    rewrite (IHo _ _ _ e1). reflexivity.\nQed.\n\nLemma removeFirst''_spec' :\n  forall {A : Type} {p : A -> bool} {l s e : list A} {x : A},\n    removeFirst'' p l = Some (s, x, e) ->\n      p x = true.\nProof.\n  intros until l.\n  functional induction removeFirst'' p l;\n  inv 1.\n    eapply IHo. eassumption.\nQed.\n\nLemma removeFirst''_spec'' :\n  forall {A : Type} {p : A -> bool} {l : list A},\n    removeFirst'' p l = None ->\n      Forall (fun x : A => p x = false) l.\nProof.\n  intros until l.\n  functional induction removeFirst'' p l;\n  inv 1.\nQed.\n\nLemma count_removeFirst''_None :\n  forall {A : Type} {p : A -> bool} {l : list A},\n    removeFirst'' p l = None ->\n      count p l = 0.\nProof.\n  intros until l.\n  functional induction removeFirst'' p l;\n  inv 1.\n  cbn. destruct (p h).\n    congruence.\n    auto.\nQed.\n\nLemma perm_front_ex' :\n  forall (A : Ord) (h : A) (t l : list A),\n    perm (h :: t) l -> exists l1 l2 : list A,\n      l = l1 ++ h :: l2 /\\ perm (l1 ++ l2) t.\nProof.\n  intros.\n  destruct (removeFirst'' (fun x : A => x =? h) l) eqn: Hrf.\n    destruct p as [[s x] e]. rewrite (removeFirst''_spec Hrf).\n      exists s, e. split.\n        do 2 f_equal. apply removeFirst''_spec' in Hrf. cbn in Hrf. trich.\n        apply (perm_cons_inv _ h). rewrite H, (perm_removeFirst'' Hrf), perm_front.\n          apply removeFirst''_spec' in Hrf. cbn in Hrf. trich.\n    apply count_removeFirst''_None in Hrf. specialize (H (fun x : A => x =? h)).\n      cbn in H. trich.\nQed.\n\nTheorem Permutation_perm :\n  forall (A : Type) (l1 l2 : list A),\n    Permutation l1 l2 -> perm l1 l2.\nProof.\n  induction 1; cbn; intros; auto.\n    eapply perm_trans; eauto.\nQed.\n\nTheorem perm_Permutation :\n  forall (A : Ord) (l1 l2 : list A),\n    perm l1 l2 -> Permutation l1 l2.\nProof.\n  induction l1 as [| h1 t1]; cbn; intros.\n    destruct l2; cbn; auto. red in H. cbn in H.\n      specialize (H (fun _ => true)). inv H.\n    apply perm_front_ex' in H. destruct H as (l1 & l3 & H1 & H3). subst.\n      rewrite <- Permutation_cons_app.\n        reflexivity.\n        apply IHt1. symmetry. assumption.\nQed.\n\n(** Moved from ListLemmas to avoid circularity. *)\n\nLemma perm_min_front :\n  forall (A : Ord) (h : A) (t : list A),\n    let m := min_dflt A h t in\n      perm (m :: removeFirst (fun x => x =? m) (h :: t)) (h :: t).\nProof.\n  intros. destruct (min_split A h t) as [l1 [l2 [H H']]].\n  fold m in H, H'. rewrite H, <- H' in *. apply perm_symm, perm_front.\nQed.\n\nTheorem trifilter_spec' :\n  forall (A : Ord) (pivot : A) (l lo eq hi : list A),\n    trifilter pivot l = (lo, eq, hi) ->\n      perm (lo ++ eq) (filter (fun x : A => x ≤? pivot) l)\n        /\\\n      hi = filter (fun x : A => pivot <? x) l.\nProof.\n  intros. rewrite trifilter_spec in H.\n  inv H. split.\n    induction l as [| h t]; cbn.\n      reflexivity.\n      trich.\n        cbn. apply perm_cons. assumption.\n        rewrite perm_front. apply perm_cons. assumption.\n    reflexivity.\nQed.", "meta": {"author": "wkolowski", "repo": "coq-algs", "sha": "ee6c656314e3d93e3029dd5f845cfb5352c1b089", "save_path": "github-repos/coq/wkolowski-coq-algs", "path": "github-repos/coq/wkolowski-coq-algs/coq-algs-ee6c656314e3d93e3029dd5f845cfb5352c1b089/Sorting/Perm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.8705972751232808, "lm_q1q2_score": 0.6882335413361577}}
{"text": "Require Import Coq.Lists.List Program. Import ListNotations.\nRequire Import SyDPaCC.Core.Bmf SyDPaCC.Support.List.\nSet Implicit Arguments.\nGeneralizable All Variables.\n\n(*---------------------------------------------------------*)\n\n(** * The Diffusion Theorem for Accumulative Computations  *)\n\nTheorem diffusion:\n  forall A B C (h: B -> list A -> C) (g:B->C) (p:A*B->C) (q:A->B)\n    (oplus:C->C->C) (otimes:B->B->B) \n    `(Monoid _ oplus e_oplus) \n    `(Monoid _ otimes e_otimes),\n    (forall c, h c [] = g c) ->\n    (forall c x xs,  h c (x::xs) = oplus (p (x,c)) (h (otimes c (q x)) xs)) ->\n    forall xs c,\n      let bs := map (otimes c) (scan otimes (map q xs)) in \n      let ys := List.combine xs (removelast bs) in \n      h c xs = oplus ( reduce oplus (map p ys) ) (g (last bs)).\nProof.\n  intros A B C h g p q oplus otimes e_oplus Hopluq e_otimes Hotimes H1 H2.\n  induction xs as [ | x xs IH]; intros c bs ys.\n  - rewrite H1; unfold bs; compute. \n    now rewrite left_neutral, right_neutral.\n  - assert(bs = c :: map (otimes (otimes c (q x))) (scan otimes (map q xs))) as Hbs.\n    {\n      clear; unfold bs; simpl; clear bs.\n      rewrite right_neutral. f_equal.\n      autounfold with sydpacc; repeat rewrite <- scanl_map.\n      f_equal.\n      symmetry; rewrite right_neutral.\n      f_equal; now rewrite left_neutral.\n    }\n    assert(last bs = last (map(otimes(otimes c (q x)))(scan otimes (map q xs)))) as Hlast.\n    {\n      assert(last bs = last (c::map(otimes(otimes c (q x)))(scan otimes (map q xs)))) as H'\n          by now apply last_pi.\n      rewrite H'.\n      apply last_cons_non_empty.\n    }\n    set(bs' := map (otimes (otimes c (q x))) (scan otimes (map q xs))) in *.\n    set(ys' := combine xs (removelast bs')).\n    assert(ys = (x,c)::ys') as Hys.\n    {\n      unfold ys, ys'.\n      rewrite Hbs.\n      replace (c :: bs') with ([c] ++ bs') by trivial.\n      now rewrite removelast_app by (apply non_emptiness; typeclasses eauto).\n    }\n    rewrite Hys.\n    replace (g(last bs)) with (g(last bs'))\n      by (f_equal; now rewrite <- Hlast).\n    simpl. rewrite reduce_eq.\n    rewrite H2.\n    rewrite IH.\n    now rewrite associative.\nQed.\n\nTheorem diffusion_scanl_last:\n  forall A B C (h: B -> list A -> C) (g:B->C) (p:A*B->C) (q:A->B)\n    (oplus:C->C->C) (otimes:B->B->B) \n    `(Monoid _ oplus e_oplus) \n    `(Monoid _ otimes e_otimes),\n    (forall c, h c [] = g c) ->\n    (forall c x xs,  h c (x::xs) = oplus (p (x,c)) (h (otimes c (q x)) xs)) ->\n    forall xs c,\n      let bsb := scanl_last otimes e_otimes (map q xs) in\n      let (bs,b) := (map (otimes c) (fst bsb), otimes c (snd bsb)) in \n      let ys := List.combine xs bs in \n      h c xs = oplus ( reduce oplus (map p ys) ) (g b).\nProof.\n  intros A B C h g p q oplus otimes e_oplus Moplus e_otimes Motimes Heq1 Heq2 xs c bsb.\n  set(Diff := diffusion h g p q Moplus Motimes Heq1 Heq2).\n  rewrite Diff; simpl; unfold bsb; do 2 f_equal.\n  - unfold scan; rewrite scanl_scanl_last; simpl.\n    rewrite removelast_map, removelast_app by\n      (intros; discriminate); simpl.\n    now rewrite app_nil_r.\n  - rewrite last_map; f_equal.\n    unfold scan; erewrite last_pi with (l':=scanl otimes e_otimes (map q xs)) by auto.\n    apply last_scanl.\nQed.\n\n(** * The Sequential [accumulate] Function *)\n\nFixpoint accumulate A B C (g:B->C) (p:A*B->C) (q:A->B)(oplus:C->C->C) (otimes:B->B->B) \n         c l : C :=\n  match l with\n  | [ ] => g c\n  | x::xs => oplus (p (x,c)) (accumulate g p q oplus otimes (otimes c (q x)) xs)\n  end.\n\nOpen Scope sydpacc_scope.\n\n(** * Diffusion for [accumulate] *)\n\n#[export] Instance diffusion_accumulate\n         `(g:B->C) `(p:A*B->C) (q:A->B)\n         `{Hp:Monoid C oplus e_oplus} `{Ht:Monoid B otimes e_otimes}\n         (c:B) :\n  Opt (accumulate g p q oplus otimes c)\n      ( (prod_curry oplus)\n          ∘ ( ((prod_curry (fold_left2 (fun (u:C) (vw:A*B)=>oplus u (p vw)) e_oplus)) × g )\n                ∘ ( ( (id × fst) △ (snd ∘ snd) )\n                      ∘ ( id △ (scanl_last (fun s t=>otimes s (q t)) c) ) ) ) ).\nProof.\n  constructor; intro xs; autounfold with sydpacc; simpl.\n  set(Diff := diffusion_scanl_last (accumulate g p q oplus otimes) g p q Hp Ht); simpl in Diff.\n  rewrite Diff by auto; unfold reduce.\n  rewrite fold_left2_prop2.\n  repeat rewrite scanl_last_fst_scanl.\n  rewrite <- removelast_map. \n  rewrite <- @scanl_map with (op:=otimes)(x:=c) by typeclasses eauto.\n  repeat rewrite scanl_last_snd. \n  erewrite map_scanl by typeclasses eauto.\n  rewrite fold_left_map_r with (g:=q).\n  rewrite <- fold_left_prop by typeclasses eauto.\n  now repeat rewrite @right_neutral with (op:=otimes) by typeclasses eauto.\nQed.\n\nClose Scope sydpacc_scope.\n", "meta": {"author": "SyDPaCC", "repo": "sydpacc", "sha": "640f0f74f21524ee203b192255ecfa9e456fb7d1", "save_path": "github-repos/coq/SyDPaCC-sydpacc", "path": "github-repos/coq/SyDPaCC-sydpacc/sydpacc-640f0f74f21524ee203b192255ecfa9e456fb7d1/Core/Diffusion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6882335317313861}}
{"text": "(************************************************************************)\n(* Copyright 2006 Milad Niqui                                           *)\n(* This file is distributed under the terms of the                      *)\n(* GNU Lesser General Public License Version 2.1                        *)\n(* A copy of the license can be found at                                *)\n(*                  <http://www.gnu.org/licenses/lgpl-2.1.html>         *)\n(************************************************************************)\n\nFrom QArithSternBrocot Require Export Qsyntax.\nFrom QArithSternBrocot Require Export Field_Theory_Q.\nFrom QArithSternBrocot Require Export Q_ordered_field_properties.\n\nDefinition Qmax p q := if Q_le_lt_dec p q then q else p.\n\nDefinition Qmin p q := if Q_le_lt_dec p q then p else q.\n\nLemma Qle_max_l: forall p q, p <= Qmax p q.\nProof.\n intros p q; unfold Qmax; destruct (Q_le_lt_dec p q); simpl; trivial.\nQed.\n\nLemma Qle_max_r: forall p q, q <= Qmax p q.\nProof.\n intros p q; unfold Qmax; destruct (Q_le_lt_dec p q); auto. \nQed.\n\nLemma Qmax_lub: forall q1 q2 p, q1 <= p -> q2 <= p -> Qmax q1 q2 <= p.\nProof.\n intros q1 q2 p H1 H2; unfold Qmax; destruct (Q_le_lt_dec q1 q2); trivial.\nQed.\n\nLemma Qmax_Qlt_upper_bound:forall p q1 q2, p<q1 -> p<q2 ->p < Qmax q1 q2.\nProof.\n intros p q1 q2 H1 H2; unfold Qmax; destruct (Q_le_lt_dec q1 q2); trivial.\nQed.\n\nLemma Qmax_nondecreasing: forall q1 q2 p1 p2, q1 <= p1 -> q2 <= p2 -> Qmax q1 q2 <= Qmax p1 p2.\nProof.\n intros q1 q2 p1 p2 H1 H2; unfold Qmax; destruct (Q_le_lt_dec q1 q2); destruct (Q_le_lt_dec p1 p2); trivial; \n [apply Qlt_le_weak; apply Qle_lt_trans with p2 | apply Qle_trans with p1]; trivial.\nQed.\n\nLemma Qmin_Qmax_Qle:forall q1 q2, Qmin q1 q2 <= Qmax q1 q2.\nProof.\n intros q1 q2; unfold Qmax, Qmin; destruct (Q_le_lt_dec q1 q2); trivial; apply Qlt_le_weak; assumption.\nQed.\n\nLemma Qmin_nondecreasing: forall q1 q2 p1 p2, q1 <= p1 -> q2 <= p2 -> Qmin q1 q2 <= Qmin p1 p2.\nProof.\n intros q1 q2 p1 p2 H1 H2; unfold Qmin; destruct (Q_le_lt_dec q1 q2); destruct (Q_le_lt_dec p1 p2); trivial;\n [apply Qle_trans with q2| apply Qlt_le_weak; apply Qlt_le_trans with q1]; trivial.\nQed.\n\nLemma Qmin_glb: forall q1 q2 p, p<=q1 -> p<=q2 -> p<=Qmin q1 q2.\nProof.\n intros q1 q2 p H1 H2; unfold Qmin; destruct (Q_le_lt_dec q1 q2); trivial.\nQed.\n\nLemma Qmin_Qlt_upper_bound:forall p q1 q2, p<q1 -> p<q2 ->p < Qmin q1 q2.\nProof.\n intros p q1 q2 H1 H2; unfold Qmin; destruct (Q_le_lt_dec q1 q2); trivial.\nQed.\n\nLemma Qle_min_l: forall p q : Q, Qmin p q <= p.\nProof.\n intros p q; unfold Qmin; destruct (Q_le_lt_dec p q); trivial ; apply Qlt_le_weak; assumption.\nQed.\n\nLemma Qle_min_r: forall p q : Q, Qmin p q <= q.\nProof.\n intros p q; unfold Qmin; destruct (Q_le_lt_dec p q); trivial ; apply Qlt_le_weak; assumption.\nQed.\n\nLemma Qmax_or_informative:forall p q, {Qmax p q = p} + {Qmax p q = q}.\nProof.\n intros p q; unfold Qmax; destruct (Q_le_lt_dec p q); auto.\nQed.\n\nLemma Qmin_or_informative:forall p q, {Qmin p q = p} + {Qmin p q = q}.\nProof.\n intros p q; unfold Qmin; destruct (Q_le_lt_dec p q); auto.\nQed.\n\nDefinition Qmax4 q1 q2 q3 q4 := Qmax (Qmax q1 q2) (Qmax q3 q4).\nDefinition Qmin4 q1 q2 q3 q4 := Qmin (Qmin q1 q2) (Qmin q3 q4).\n\nLemma Qmax4_informative:forall q1 q2 q3 q4, {Qmax4 q1 q2 q3 q4=q1} + {Qmax4 q1 q2 q3 q4=q2} + {Qmax4 q1 q2 q3 q4=q3} + {Qmax4 q1 q2 q3 q4=q4}.\nProof.\n intros q1 q2 q3 q4; unfold Qmax4; \n destruct (Qmax_or_informative (Qmax q1 q2) (Qmax q3 q4)) as [H|H]; rewrite H;\n  [ left; left; exact (Qmax_or_informative q1 q2)\n  | destruct (Qmax_or_informative q3 q4) as [H'|H']; rewrite H'; auto]. \nQed. \n\nLemma Qmin4_informative:forall q1 q2 q3 q4, {Qmin4 q1 q2 q3 q4=q1} + {Qmin4 q1 q2 q3 q4=q2} + {Qmin4 q1 q2 q3 q4=q3} + {Qmin4 q1 q2 q3 q4=q4}.\nProof.\n intros q1 q2 q3 q4; unfold Qmin4; \n destruct (Qmin_or_informative (Qmin q1 q2) (Qmin q3 q4)) as [H|H]; rewrite H;\n  [ left; left; exact (Qmin_or_informative q1 q2)\n  | destruct (Qmin_or_informative q3 q4) as [H'|H']; rewrite H'; auto]. \nQed. \n\nLemma Qmin4_Qmax4_Qle:forall q1 q2 q3 q4, Qmin4 q1 q2 q3 q4<= Qmax4 q1 q2 q3 q4.\nProof.\n intros q1 q2 q3 q4; unfold Qmax4, Qmin4;\n apply Qle_trans with (Qmin (Qmax q1 q2) (Qmax q3 q4)); [apply Qmin_nondecreasing|]; apply Qmin_Qmax_Qle.\nQed.\n\nLemma Qle_Qmax4_1:forall q1 q2 q3 q4, q1<=Qmax4 q1 q2 q3 q4.\nProof.\n intros q1 q2 q3 q4; apply Qle_trans with (Qmax q1 q2); unfold Qmax4; apply Qle_max_l.\nQed.\n\nLemma Qle_Qmax4_2:forall q1 q2 q3 q4, q2<=Qmax4 q1 q2 q3 q4.\nProof.\n intros q1 q2 q3 q4; apply Qle_trans with (Qmax q1 q2); unfold Qmax4; apply Qle_max_l || apply Qle_max_r.\nQed.\n\nLemma Qle_Qmax4_3:forall q1 q2 q3 q4, q3<=Qmax4 q1 q2 q3 q4.\nProof.\n intros q1 q2 q3 q4; apply Qle_trans with (Qmax q3 q4); unfold Qmax4; apply Qle_max_l || apply Qle_max_r.\nQed.\n\nLemma Qle_Qmax4_4:forall q1 q2 q3 q4, q4<=Qmax4 q1 q2 q3 q4.\nProof.\n intros q1 q2 q3 q4; apply Qle_trans with (Qmax q3 q4); unfold Qmax4; apply Qle_max_r.\nQed.\n\nLemma Qle_Qmin4_1:forall q1 q2 q3 q4, Qmin4 q1 q2 q3 q4<= q1.\nProof.\n intros q1 q2 q3 q4; apply Qle_trans with (Qmin q1 q2); unfold Qmin4; apply Qle_min_l.\nQed.\n\nLemma Qle_Qmin4_2:forall q1 q2 q3 q4, Qmin4 q1 q2 q3 q4<= q2.\nProof.\n intros q1 q2 q3 q4; apply Qle_trans with (Qmin q1 q2); unfold Qmin4; apply Qle_min_l || apply Qle_min_r.\nQed.\n\nLemma Qle_Qmin4_3:forall q1 q2 q3 q4, Qmin4 q1 q2 q3 q4<= q3.\nProof.\n intros q1 q2 q3 q4; apply Qle_trans with (Qmin q3 q4); unfold Qmin4; apply Qle_min_l || apply Qle_min_r.\nQed.\n\nLemma Qle_Qmin4_4:forall q1 q2 q3 q4, Qmin4 q1 q2 q3 q4<= q4.\nProof.\n intros q1 q2 q3 q4; apply Qle_trans with (Qmin q3 q4); unfold Qmin4; apply Qle_min_r.\nQed.\n\nLemma Qmax4_Qlt_upper_bound:forall p q1 q2 q3 q4, p<q1 -> p<q2 -> p<q3 -> p<q4 -> p < Qmax4 q1 q2 q3 q4.\nProof.\n intros p q1 q2 q3 q4 H1 H2 H3 H4; unfold Qmax4; repeat apply Qmax_Qlt_upper_bound; assumption.\nQed.\n\nLemma Qlt_Qmin_upper_bound: forall p q1 q2 : Q, p < Qmin q1 q2 -> p < q1 /\\ p < q2.\nProof.\n intros p q1 q2; split; apply Qlt_le_trans with (Qmin q1 q2); trivial; [apply Qle_min_l|apply Qle_min_r].\nQed.\n\nDefinition Qlt_Qmin_upper_bound_l p q1 q2 (hyp:p < Qmin q1 q2) : p < q1 :=proj1 (Qlt_Qmin_upper_bound p q1 q2 hyp).\nDefinition Qlt_Qmin_upper_bound_r p q1 q2 (hyp:p < Qmin q1 q2) : p < q2 :=proj2 (Qlt_Qmin_upper_bound p q1 q2 hyp).\n\nLemma Qmax_Qlt_lower_bound: forall p q1 q2 : Q, q1 < p  -> q2 < p -> Qmax q1 q2 < p.\nProof.\n intros p q1 q2 H1 H2; unfold Qmax; destruct (Q_le_lt_dec q1 q2); trivial.\nQed.\n\nLemma Qlt_Qmax_lower_bound: forall p q1 q2 : Q, Qmax q1 q2 < p -> q1 < p /\\ q2 < p.\nProof.\n intros p q1 q2; split; apply Qle_lt_trans with (Qmax q1 q2); trivial; [apply Qle_max_l|apply Qle_max_r].\nQed.\n\nDefinition Qlt_Qmax_lower_bound_l p q1 q2 (hyp:Qmax q1 q2 < p) := proj1 (Qlt_Qmax_lower_bound p q1 q2 hyp).\nDefinition Qlt_Qmax_lower_bound_r p q1 q2 (hyp:Qmax q1 q2 < p) := proj2 (Qlt_Qmax_lower_bound p q1 q2 hyp).\n\nLemma Qmin_involutive : forall q, Qmin q q = q.\nProof.\n intros q; destruct (Qmin_or_informative q q); trivial.\nQed.\n\nLemma Qmax_involutive : forall q, Qmax q q = q.\nProof.\n intros q; destruct (Qmax_or_informative q q); trivial.\nQed.\n\nDefinition Qmean (x y:Q):Q := (x+y) / (Qone + Qone).\n\nLemma Qmean_property:forall (x y:Q), x < y -> x < Qmean x y /\\ Qmean x y < y.\nProof.\n intros x y H; split; unfold Qmean.\n  apply Qmult_pos_Qlt_Qdiv; auto; stepl (x+x); auto; ring.  \n  apply Qmult_pos_Qdiv_Qlt; auto; stepr (y+y); auto; ring.\nQed.\n\nDefinition Qmean_property_l x y (hyp:x<y) := proj1 (Qmean_property x y hyp).\nDefinition Qmean_property_r x y (hyp:x<y) := proj2 (Qmean_property x y hyp).\n\nLemma Qmean_incr: forall x1 x2 y1 y2, x1< x2 -> y1 < y2 ->  Qmean x1 y1 < Qmean x2 y2.\nProof.\n intros x1 x2 y1 y2 Hx Hy; unfold Qmean;\n apply Qmult_Qdiv_pos; auto;\n (stepl (x1 + x1 + y1 + y1) by ring); stepr (x2 + x2 + y2 + y2) ; auto; ring. \nQed.\n\nTheorem Q_is_dense:forall x y, x<y -> {z:Q | x<z /\\ z<y}.\nProof.\n intros x y Hxy; exists (Qmean x y); apply Qmean_property; trivial.\nQed.\n", "meta": {"author": "coq-community", "repo": "qarith-stern-brocot", "sha": "a36a01526e76f4ef92bc87445da33dfb025e2db4", "save_path": "github-repos/coq/coq-community-qarith-stern-brocot", "path": "github-repos/coq/coq-community-qarith-stern-brocot/qarith-stern-brocot-a36a01526e76f4ef92bc87445da33dfb025e2db4/theories/Qmax_min.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.6882335221266143}}
{"text": "Set Implicit Arguments.\n\nRequire Import kat normalisation rewriting kat_tac.\nRequire Import rel comparisons.\n\nRequire Import Packet.\n\nLocal Open Scope bool_scope.\n\nInductive pred : Type :=\n| pr_true\n| pr_false\n| pr_and : pred -> pred -> pred\n| pr_or : pred -> pred -> pred\n| pr_not : pred -> pred\n| pr_test : hdr -> val -> pred.\n\nInductive pol : Type :=\n| po_id : pol\n| po_drop : pol\n| po_sum : pol -> pol -> pol\n| po_seq : pol -> pol -> pol\n| po_star : pol -> pol\n| po_pred : pred -> pol\n| po_upd : hdr -> val -> pol\n| po_upd_obs : hdr -> val -> pol.\n\nDefinition test0 h v : dset trace :=\n  fun tr => test h v (head tr).\n\nFixpoint eval_pred (pr : pred) : dset trace  := \n  match pr with\n    | pr_and pr1 pr2 => eval_pred pr1 \\cap eval_pred pr2\n    | pr_or pr1 pr2 => eval_pred pr1 \\cup eval_pred pr2\n    | pr_true => top\n    | pr_false => bot\n    | pr_not pr' => ! (eval_pred pr')\n    | pr_test h v => test0 h v\n  end.\n\nDefinition upd0 h v : rel trace trace :=\n  fun t1 t2 => replace_head (upd h v (head t1)) t1 = t2.\n\nDefinition obs0 h v : rel trace trace :=\n  fun t1 t2 => tr_cons (upd h v (head t1)) t1 = t2.\n\nFixpoint eval_pol (po : pol) : rel trace trace :=\n  match po with\n    | po_id => 1\n    | po_drop => 0\n    | po_sum e1 e2 => eval_pol e1 + eval_pol e2\n    | po_seq e1 e2 => eval_pol e1 * eval_pol e2\n    | po_star e' => (eval_pol e')^*\n    | po_pred pr => [eval_pred pr]\n    | po_upd h v => upd0 h v\n    | po_upd_obs h v => obs0 h v\n  end.\n  \nCoercion po_pred : pred >-> pol.\n\nReserved Notation \"h ~:= n\" (at level 48, no associativity).\nReserved Notation \"h ^:= n\" (at level 48, no associativity).\nReserved Notation \"h =? n\" (at level 48, no associativity).\nReserved Notation \"x ; y\" (at level 50, left associativity).\n\nModule KatNotation.\n\n  Notation \"h =? n\" := (pr_test h n) : kat_scope.\n  Notation \"h ~:= n\" := (po_upd h n) : kat_scope.\n  Notation \"h ^:= n\" := (po_upd_obs h n) : kat_scope.\n  Notation \"x + y\" := (po_sum x y) : kat_scope.\n  Notation \"x ; y\" := (po_seq x y) : kat_scope.\n  Notation \"x ^*\" := (po_star x) : kat_scope.\n  Notation \"#t\" := pr_true : kat_scope.\n  Notation \"#f\" := pr_false : kat_scope.\n  Notation \"x && y\" := (pr_and x y) : kat_scope.\n  Notation \"x || y\" := (pr_or x y) : kat_scope.\n  Notation \"p ~ q\" := (eval_pol p == eval_pol q) (at level 80) : kat_scope.\n  Notation \"~ p\" := (pr_not p).\n\nEnd KatNotation.\n\nModule Notation.\n\n  Notation \"h =? n\" := (test0 h n) : netcore_scope.\n  Notation \"h ~:= n\" := (upd0 h n) : netcore_scope.\n  Notation \"h ^:= n\" := (obs0 h n) : netcore_scope.\n  Notation \"x + y\" := (x + y) : netcore_scope.\n  Notation \"x ; y\" := (x * y) : netcore_scope.\n  Notation \"p ~ q\" := \n    (eval_pol p == eval_pol q) (at level 80) : netcore_scope.\n  Notation \"~ p\" := (pr_not p).\n\nEnd Notation.\n\nSection DomainEquations.\n\n  Variable h h1 h2 : hdr.\n  Variable m n : val.\n\n  Import Notation.\n  Local Open Scope netcore_scope.\n\n  Hint Unfold rel_dot rel_inj test0 obs0 upd0.\n  Lemma upd_compress : (h~:=m) * (h~:=n) == (h~:=n).\n  Proof with auto.\n    simpl. intros. autounfold. split; intros.\n    + destruct H.\n      destruct (head a) as [[[sw pt] src] dst].\n      subst.\n      autorewrite with pkt using simpl...\n      rewrite -> upd_upd_compress...\n    + destruct (head a) as [[[sw pt] src] dst].\n      subst. eexists. reflexivity.\n      autorewrite with pkt using simpl...\n      rewrite -> upd_upd_compress...\n  Qed.\n\n  Lemma upd_comm : h1 <> h2 -> h1~:=m; h2~:=n == h2~:=n; h1~:=m.\n  Proof with auto.\n    simpl. intros. autounfold. split; intros.\n    + destruct H0.\n      subst.\n      destruct (head a) as [[[sw pt] src] dst].\n      unfold not in H.\n      destruct h1; destruct h2;\n      try solve [contradiction H; trivial |\n                 destruct a; eexists; simpl; eauto].\n    + intros.\n      destruct H0.\n      subst.\n      destruct (head a) as [[[sw pt] src] dst].\n      unfold not in H.\n      destruct h1; destruct h2; \n      try solve [contradiction H; trivial |\n                 destruct a; eexists; simpl; eauto].\n  Qed.\n\n  Lemma upd_test_compress : h~:=n; [h=?n] == h~:=n.\n  Proof with eauto.\n    simpl. intros. autounfold. split; intros.\n    + destruct H. destruct H0. subst.\n      trivial.\n    + subst. eexists. reflexivity.\n      unfold rel_inj.\n      split...\n      autorewrite with pkt using simpl.\n      rewrite -> test_upd_true...\n  Qed.\n\n  Lemma upd_test_comm : h1 <> h2 -> h1~:=m; [h2=?n] == [h2=?n]; h1~:=m.\n  Proof with eauto.\n    simpl. intros. autounfold. split; intros.\n    + destruct H0. destruct H1. subst.\n      autorewrite with pkt in H2 using (simpl in H2). subst.\n      rewrite -> test_upd_ignore in H2...\n    + destruct H0. destruct H0. subst.\n      eexists. reflexivity.\n      split...\n      autorewrite with pkt using simpl.\n      rewrite -> test_upd_ignore...\n  Qed.\n\n  Lemma test_test_zero : m <> n -> [h=?m]; [h=?n] == bot.\n  Proof with eauto.\n    simpl. intros. autounfold. split; intros.\n    + destruct H0 as [a1 [H0 H1] [H2 H3]].\n      subst.\n      assert (m = n). \n      { eapply test_true_diff... }\n      subst...\n    + inversion H0.\n  Qed.\n\n  Lemma upd_test_zero : m <> n -> h~:=n; [h=?m] == bot.\n  Proof with eauto.\n    simpl. intros. autounfold. split; intros.\n    destruct H0.\n    + destruct H1. subst.\n      remember (test h m (head a)) as b.\n      destruct b.\n      - subst.\n        autorewrite with pkt in H2 using (simpl in H2)...\n        rewrite -> test_upd_0 in H2...\n        inversion H2.\n      - subst.\n        autorewrite with pkt in H2 using (simpl in H2)...\n        rewrite -> test_upd_0 in H2...\n        inversion H2.\n    + inversion H0.\n  Qed.\n\n  Lemma obs_test_compress : h^:=n; [h=?n] == h^:=n.\n  Proof with eauto.\n    simpl. intros. autounfold. split; intros.\n    + destruct H as [a1 H [H0 H1]]. subst.\n      simpl in H1.\n      rewrite -> test_upd_true in H1...\n    + subst. eexists. reflexivity.\n      split...\n      simpl.\n      rewrite -> test_upd_true...\n  Qed.\n\n  Lemma obs_test_comm : h1 <> h2 -> h1^:=m; [h2=?n] == [h2=?n]; h1^:=m.\n  Proof with eauto.\n    simpl. intros. autounfold. split; intros.\n    + destruct H0 as [tr J [J0 J1]]. subst.\n      simpl in J1.\n      rewrite -> test_upd_ignore in J1...\n    + destruct H0 as [tr [J0 J1] J]. subst.\n      eexists...\n      split...\n      simpl.\n      rewrite -> test_upd_ignore...\n  Qed.\n\n  Lemma obs_test_zero : m <> n -> h^:=m; [h=?n] == bot.\n  Proof with eauto.\n    simpl. intros. autounfold. split; intros.\n    + destruct H0 as [tr J [J0 J1]]. subst.\n      simpl in J1.\n      rewrite -> test_upd_0 in J1...\n      inversion J1.\n    + inversion H0.\n  Qed.\n\n  Lemma obs_upd_compress : h^:=m; h~:=n == h^:=n.\n  Proof with eauto.\n    simpl. intros. autounfold. split; intros.\n    + destruct H. subst. simpl.\n      rewrite -> upd_upd_compress...\n    + subst.\n      eexists. reflexivity.\n      simpl.\n      rewrite -> upd_upd_compress...\n  Qed.\n\nEnd DomainEquations.\n\nLtac kat_simpl := \n  unfold eval_pol; unfold eval_pred; fold eval_pred; fold eval_pol.\n", "meta": {"author": "frenetic-lang", "repo": "featherweight-openflow", "sha": "4470518794e3ed867919d30500be2d0128b1de1c", "save_path": "github-repos/coq/frenetic-lang-featherweight-openflow", "path": "github-repos/coq/frenetic-lang-featherweight-openflow/featherweight-openflow-4470518794e3ed867919d30500be2d0128b1de1c/coq/Netkat/netcore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6881648947185336}}
{"text": "Module FormulaTheory.\nRequire Export form name decidability feature_model.\nImport Name Form Decidability FeatureModel.\nRequire Import Coq.Lists.ListSet Coq.Lists.List.\n\n(*yields names for a formula*)\nFixpoint names_ (f : Formula) : set Name :=\n  match f with\n    | TRUE_FORMULA    => empty_set Name\n    | FALSE_FORMULA   => empty_set Name\n    | NAME_FORMULA n1 => set_add name_dec n1 nil\n    | NOT_FORMULA f1  => names_ f1\n    | AND_FORMULA f1 f2     => set_union name_dec  (names_ f1) \n                                  (set_diff name_dec  (names_ f2) (names_ f1))  \n    | IMPLIES_FORMULA f1 f2 => set_union name_dec  (names_ f1) \n                                  (set_diff name_dec  (names_ f2) (names_ f1)) \n  end.  \n\n\n(* indicates whether a formula is well-typed*)\nFixpoint wt (fm : FM) (f : Formula) : Prop :=\n  match f with\n    | TRUE_FORMULA    => True\n    | FALSE_FORMULA   => True\n    | NAME_FORMULA n1 => set_In n1 (fst fm)\n    | NOT_FORMULA f1  => wt fm f1\n    | AND_FORMULA f1 f2     => (wt fm f1) /\\ (wt fm f2)  \n    | IMPLIES_FORMULA f1 f2 => (wt fm f1) /\\ (wt fm f2)\n   end.\n\n(*indicates whether a feature model has all of its formulae well-typed*)\nDefinition wfFormulae (fm: FM) : Prop :=\n  forall (f: Formula), set_In f (formulas fm) -> wt fm f.\n\n(*indicates when a configuration satisfies a formula*)\nFixpoint satisfies (f: Formula) ( c : Configuration) : Prop :=\n  match f with\n    | TRUE_FORMULA   => True\n    | FALSE_FORMULA  => False\n    | NAME_FORMULA n => set_In n c\n    | NOT_FORMULA f1 => not (satisfies f1 c)\n    | AND_FORMULA f1 f2     => and(satisfies f1 c) (satisfies f2 c)  \n    | IMPLIES_FORMULA f1 f2 => (satisfies f1 c) -> (satisfies f2 c)\n   end.\n\n(*a well-typed formula only contains names from the feature model*)\nLemma formNames : forall (fm : FM) (f : Formula),  \n (wt fm f) -> ( forall (n : Name), set_In n (names_ f) -> set_In n (fst fm)).\nProof.\ninduction f.\n   + simpl. intuition.\n   + simpl. intuition.\n   + simpl. intuition. rewrite H1 in H. apply H.\n   + intuition.\n   + simpl. intros H ; destruct H. intros. apply set_union_elim in H1. inversion H1.\n      - apply IHf1. apply H. apply H2.\n      - apply set_diff_elim1 in H2. apply IHf2. apply H0. apply H2.\n    + simpl. intros H. destruct H. intros. apply set_union_elim in H1. inversion H1.\n      - apply IHf1. apply H. apply H2. \n      - apply set_diff_elim1 in H2. apply IHf2. apply H0. apply H2.\nQed.\n\nLemma formNames2 : forall (fm : FM) (f : Formula) (n: Name) , and (wt fm f) \n  (not(set_In n (fst fm))) -> (not(set_In n (names_ f))).\nProof.\ninduction f.\n   + intuition.\n   + intuition.\n   + simpl. intuition. rewrite H in H1. apply H2. apply H1.\n   + intuition.\n   + simpl. intros. destruct H; destruct H.  intuition. apply set_union_elim in H2. inversion H2.\n      - apply (IHf1 n). intuition. apply H3.\n      - apply set_diff_elim1 in H3. apply (IHf2 n). intuition. apply H3. \n   + simpl. intros. destruct H. destruct H. intuition. apply set_union_elim in H2. inversion H2.\n      - apply (IHf1 n). intuition. apply H3.\n      - apply set_diff_elim1 in H3. apply (IHf2 n). intuition. apply H3.\nQed. \n\n\nTheorem not_compat : forall A B : Prop,\n  (A = B) -> ((~ A) = (~B)).\nProof.\n  intros.\n  rewrite H.\n  reflexivity.\nQed.\n\n\nLemma set_union_elim_not :\n   forall (a:Name) (x y:set Name),\n     ~(set_In a (set_union name_dec x y)) -> ~(set_In a x) /\\ ~(set_In a y).\nProof.\n  intros. split.\n    + intuition. apply H. apply set_union_intro1. apply H0.\n    + intuition. apply H. apply set_union_intro2. apply H0.\nQed.\n\nLemma set_union_elim_not2 :\n   forall (a:Name) (x y:set Name),\n     ~(set_In a x) /\\ ~(set_In a y) ->  ~(set_In a (set_union name_dec x y)).\nProof.  \n  intros. destruct H.\n  intuition. apply H. \n  apply set_union_elim in H1.\n  generalize H1. tauto.\nQed.\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q H.\n  tauto. Qed. \n\n\nLemma set_diff_elim_not:\n    forall (n : Name) (f1 f2 : Formula),\n    (not (set_In n (set_diff name_dec (names_ f1) (names_ f2)))) -> or (not (set_In n (names_ f1))) (set_In n (names_ f2)).\nProof.\n  intros. left.\n  intuition. apply H.\n  apply set_diff_intro.\n  + apply H0.\n  + unfold not. intro.\n  apply H. apply set_diff_intro.\n  apply H0.\nAdmitted.\n\n(* satisfies's result is equal if we add a feature to the configuration that is not in the formula *)\nLemma satisfies1 : forall (f: Formula) (c : Configuration) (n : Name),\n  not(set_In n (names_ f)) -> satisfies f c = satisfies f (set_add name_dec n c).\nProof.\ninduction f. \n  + intuition.\n  + intuition.\n  + simpl. intuition. exfalso. apply H0. rewrite n. rewrite n0. reflexivity.\n  + simpl. intros. apply not_compat. apply (IHf c). apply H.\n  + simpl. intros. apply set_union_elim_not in H. destruct H as [H1 H2]. \n    specialize (IHf1 c n). specialize (IHf2 c n).\n    apply set_diff_elim_not in H2. inversion H2.\n    -  apply IHf1 in H1. apply IHf2 in H. rewrite H1.\n      rewrite H. reflexivity.\n    - contradiction.\n + simpl. intros. apply set_union_elim_not in H. destruct H as [H1 H2]. \n    specialize (IHf1 c n). specialize (IHf2 c n).\n    apply set_diff_elim_not in H2. inversion H2.\n    -  apply IHf1 in H1. apply IHf2 in H. rewrite H1.\n      rewrite H. reflexivity.\n    - contradiction.\nQed.\n\n(*satisfies's result is equal if we remove a feature from the configuration that is not in the formula*)\nLemma satisfies2 : forall (f: Formula) (c : Configuration) (n : Name),\n  not(set_In n (names_ f)) -> satisfies f c = satisfies f (set_remove name_dec n c).\nProof.\ninduction f. \n  + intuition.\n  + intuition.\n  + simpl. intuition. exfalso. apply H0. rewrite n. rewrite n0. reflexivity.\n  + simpl. intros. apply not_compat. apply (IHf c). apply H.\n  + simpl. intros. apply set_union_elim_not in H. destruct H as [H1 H2]. \n    specialize (IHf1 c n). specialize (IHf2 c n).\n    apply set_diff_elim_not in H2. inversion H2.\n    -  apply IHf1 in H1. apply IHf2 in H. rewrite H1.\n      rewrite H. reflexivity.\n    - contradiction.\n + simpl. intros. apply set_union_elim_not in H. destruct H as [H1 H2]. \n    specialize (IHf1 c n). specialize (IHf2 c n).\n    apply set_diff_elim_not in H2. inversion H2.\n    -  apply IHf1 in H1. apply IHf2 in H. rewrite H1.\n      rewrite H. reflexivity.\n    - contradiction.\nQed.\n\n(* well-typed formulae from a FM continue well-typed in another FM with the same features *)\nLemma wtFormSameFeature : forall (abs : FM) (con : FM), (fst abs = fst con\n  /\\ (wfTree abs) /\\ (wfTree con) -> ( forall (f : Formula), (wt abs f) ->  (wt con f))).\nProof.\n  intros.\n  destruct H as [equals_abs_con wf_abs_con].\n  destruct wf_abs_con as [wf_abs wf_con].\n  induction f.\n    + auto. \n    + auto. \n    + simpl. simpl in H0. rewrite equals_abs_con in H0. apply H0. \n    + auto. \n    + induction abs, con. simpl. destruct H0. intuition. \n    + induction abs, con. simpl. destruct H0. intuition. \nQed.\n\nEnd FormulaTheory.\n\n\n\n", "meta": {"author": "spgroup", "repo": "theory-pl-refinement-coq", "sha": "9587dddac0d6f4792db18629fa1ea3bd3d933abe", "save_path": "github-repos/coq/spgroup-theory-pl-refinement-coq", "path": "github-repos/coq/spgroup-theory-pl-refinement-coq/theory-pl-refinement-coq-9587dddac0d6f4792db18629fa1ea3bd3d933abe/formula_theory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6881230170162492}}
{"text": "Require Export TopologicalSpaces.\nRequire Import WeakTopology.\n\nSection Subspace.\n\nVariable X:TopologicalSpace.\nVariable A:Ensemble (point_set X).\n\nDefinition SubspaceTopology : TopologicalSpace :=\n  WeakTopology1 (proj1_sig (P:=fun x:point_set X => In A x)).\n\nDefinition subspace_inc : point_set SubspaceTopology ->\n  point_set X :=\n  proj1_sig (P:=fun x:point_set X => In A x).\n\nLemma subspace_topology_topology: forall U:Ensemble {x:point_set X | In A x},\n  @open SubspaceTopology U -> exists V:Ensemble (point_set X),\n  open V /\\ U = inverse_image subspace_inc V.\nProof.\napply weak_topology1_topology.\nQed.\n\nLemma subspace_inc_continuous:\n  continuous subspace_inc.\nProof.\napply weak_topology1_makes_continuous_func.\nQed.\n\nEnd Subspace.\n\nArguments SubspaceTopology {X}.\nArguments subspace_inc {X}.\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/SubspaceTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6881230072392749}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_lessthantransitive.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_TTtransitive : \n   forall A B C D E F G H P Q R S, \n   TT A B C D E F G H -> TT E F G H P Q R S ->\n   TT A B C D P Q R S.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists K, (BetS E F K /\\ Cong F K G H /\\ TG A B C D E K)) by (conclude_def TT );destruct Tf as [K];spliter.\nlet Tf:=fresh in\nassert (Tf:exists J, (BetS A B J /\\ Cong B J C D /\\ Lt E K A J)) by (conclude_def TG );destruct Tf as [J];spliter.\nlet Tf:=fresh in\nassert (Tf:exists L, (BetS P Q L /\\ Cong Q L R S /\\ TG E F G H P L)) by (conclude_def TT );destruct Tf as [L];spliter.\nlet Tf:=fresh in\nassert (Tf:exists M, (BetS E F M /\\ Cong F M G H /\\ Lt P L E M)) by (conclude_def TG );destruct Tf as [M];spliter.\nassert (eq K K) by (conclude cn_equalityreflexive).\nassert (neq F K) by (forward_using lemma_betweennotequal).\nassert (neq F M) by (forward_using lemma_betweennotequal).\nassert (Out F K M) by (conclude_def Out ).\nassert (Out F K K) by (conclude lemma_ray4).\nassert (Cong G H F M) by (conclude lemma_congruencesymmetric).\nassert (Cong F K F M) by (conclude lemma_congruencetransitive).\nassert (eq K M) by (conclude lemma_layoffunique).\nassert (Lt P L E K) by (conclude cn_equalitysub).\nassert (Lt P L A J) by (conclude lemma_lessthantransitive).\nassert (TG A B C D P L) by (conclude_def TG ).\nassert (TT A B C D P Q R S) by (conclude_def TT ).\nclose.\nQed.\n\nEnd Euclid.", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_TTtransitive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6880751938786752}}
{"text": "Load \"Tactics4_Constructions.v\".\n\nSection INCIDENCE.\n\n(* On verifie que les axiomes d'incidence du systeme de Hilbert sont des theoremes dans notre systeme d'axiomes. *)\n\n(* I1 : For any two points A, B, there exists a line L containing A, B. If A and B are distincts points, L is a unique line.*)\n\nLemma I1 : forall A B : Point, exists d : Line, OnLine d A /\\ OnLine d B.\nProof.\n\tintros; byApartCases Oo Uu ipattern:A.\n\t by3Cases Oo A B.\n\t  setLine A B ipattern:d.\n\t    answerIs d.\n\t  setLine A B ipattern:d.\n\t    answerIs d.\n\t  setLine Oo A ipattern:d.\n\t    answerIs d.\n\t by3Cases Uu A B.\n\t  setLine A B ipattern:d.\n\t    answerIs d.\n\t  setLine A B ipattern:d.\n\t    answerIs d.\n\t  setLine Uu A ipattern:d.\n\t    answerIs d.\nQed.\n\nLemma I1' : forall A B : Point, forall d1 d2 : Line, \n\tA <> B -> OnLine d1 A -> OnLine d1 B -> OnLine d2 A -> OnLine d2 B ->\n\tEqLine d1 d2.\nProof.\n\tintros.\n\tstep H.\nQed.\n\n(* I2 : Every line contains at least two points. *)\n\nLemma I2 : forall d : Line, exists A : Point, exists B : Point, A <> B /\\ OnLine d A /\\ OnLine d B.\nProof.\n\tintros; destruct d.\n\tanswerIs A; answerIs B.\nQed.\n\n(* I3 : There exist three noncollinear points (that is, three points not all contained in a single line). *)\n\nLemma I3 : exists A : Point, exists B : Point, exists C : Point, forall d : Line, \n\t~(OnLine d A /\\ OnLine d B /\\ OnLine d C).\nProof.\n\tanswerIs Oo; answerIs Uu; answerIs Vv; intros.\n\tsince (~ Collinear Oo Uu Vv).\n\tcontrapose H.\n\tstep d; canonize.\nQed.\n\nEnd INCIDENCE.\n\n", "meta": {"author": "coq-contribs", "repo": "euclidean-geometry", "sha": "06838851a5924918d98e5a9c07ffa84021e13af7", "save_path": "github-repos/coq/coq-contribs-euclidean-geometry", "path": "github-repos/coq/coq-contribs-euclidean-geometry/euclidean-geometry-06838851a5924918d98e5a9c07ffa84021e13af7/Hilbert1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6880751933789604}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (x : natural) (y : natural) (lf2 : natural)\n  : natural := plus (Succ y) Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_commut/goal33conj187_coqofml_JI4TmD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6880218028244882}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (z : natural) (lf2 : natural) (lf1 : natural)\n  : natural := mult (Succ Zero) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj54_coqofml_7XW7Tz.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6880217943365421}}
{"text": "(**\n   型付インタープリタ\n   \n   https://www.math.nagoya-u.ac.jp/~garrigue/lecture/2011_AW/coq7.pdf\n *)\n\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nInductive exp : Type -> Type :=\n| Nat : nat -> exp nat\n| Pair : forall t1 t2, exp t1 -> exp t2 -> exp (t1 * t2)\n| App : forall t1 t2, exp (t1 -> t2) -> exp t1 -> exp t2\n| Plus : exp (nat -> nat -> nat).\n\nFixpoint eval (t : Type) (e : exp t) : t :=\n  match e with\n  | Nat n => n\n  | Pair t1 t2 a b => (eval a, eval b) (* (@eval t1 a, @eval t2 b) *)\n  | App t1 t2 f g => (eval f) (eval g) (* (@eval (t1 -> t2) f) (@eval t1 g) *)\n  | Plus => addn\n  end.\n\nCompute eval (App (App Plus (Nat 1)) (Nat 2)). (* 3 *)\n\nInductive evaluate : forall {t : Type}, exp t -> t -> Prop :=\n| e_nat n : evaluate (Nat n) n\n| e_pair t1 t2 (a : exp t1) (b : exp t2) (a' : t1) (b' : t2) :\n    evaluate a a' -> evaluate b b' -> evaluate (Pair a b) (a' , b')\n| e_app t1 t2 (f : exp (t1 -> t2)) (g : exp t1) (f' : t1 -> t2) (g' : t1) :\n    evaluate f f' -> evaluate g g' -> evaluate (App f g) (f' g')\n| e_plus : evaluate Plus plus.\nHint Constructors evaluate.\n\nGoal evaluate (App (App Plus (Nat 1)) (Nat 2)) (plus 1 2).\nProof.\n  apply: e_app.\n  - by apply: e_app.\n  - done.\nQed.\n\nLemma eval_eval (t : Type) (e : exp t) (v : t) : evaluate e v <-> eval e = v.\nProof.\n  split.\n  - elim=> //=.\n    + move=> t1 t2 a b a' b' H1 H2 H3 H4.\n        by subst.\n    + move=> t1 t2 a b a' b' H1 H2 H3 H4.\n        by subst.\n  - elim: e v => [n v H | t1 t2 e1 H1 e2 H2 v IH | t1 t2 f Hf g Hg v IH | v H];\n                   subst => //=.\n    + apply: e_pair.\n      * by apply: H1.\n      * by apply: H2.\n    + apply: e_app.\n      * by apply: Hf.\n      * by apply: Hg.\nQed.\n\nRequire Import Program.\nProgram Fixpoint eval' (t : Type) (e : exp t) : {v | evaluate e v} :=\n  match e with\n  | Nat n => n\n  | Pair t1 t2 a b => (eval' a, eval' b)\n  | App t1 t2 f g => (eval' f) (eval' g)\n  | Plus => addn\n  end.\n(* 証明責務はなし。 *)\n\nCompute (eval (App (App Plus (Nat 1)) (Nat 2))).\nCompute (eval' (App (App Plus (Nat 1)) (Nat 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/prog/ssr_typed_interpreter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764119, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.6879706956055863}}
{"text": "Require Export GeoCoq.Tarski_dev.Annexes.circles.\nRequire Export GeoCoq.Tarski_dev.Annexes.half_angles.\nRequire Export GeoCoq.Tarski_dev.Ch12_parallel_inter_dec.\n\nImport circles.\n\nSection Inscribed_angle.\n\nContext `{TE:Tarski_euclidean}.\n\n(** The sum of the angles of a triangle is the flat angle. *)\n\nLemma trisuma__bet : forall A B C D E F, TriSumA A B C D E F -> Bet D E F.\nProof.\n  apply alternate_interior__triangle.\n  unfold alternate_interior_angles_postulate.\n  apply l12_21_a.\nQed.\n\nLemma bet__trisuma : forall A B C D E F, Bet D E F -> A <> B -> B <> C -> A <> C -> D <> E -> E <> F ->\n  TriSumA A B C D E F.\nProof.\n  intros A B C D E F HBet; intros.\n  destruct (ex_trisuma A B C) as [P [Q [R HTri]]]; auto.\n  apply conga_trisuma__trisuma with P Q R; trivial.\n  assert (Hd := HTri).\n  apply trisuma_distincts in Hd; spliter.\n  apply conga_line; auto.\n  apply (trisuma__bet A B C); trivial.\nQed.\n\nLemma right_saccheris : forall A B C D, Saccheri A B C D -> Per A B C.\nProof.\n  apply postulates_in_euclidean_context; simpl; repeat (try (left; reflexivity); right).\nQed.\n\nLemma not_obtuse_saccheris : ~ hypothesis_of_obtuse_saccheri_quadrilaterals.\nProof.\n  apply not_oah; right.\n  unfold hypothesis_of_right_saccheri_quadrilaterals; apply right_saccheris.\nQed.\n\nLemma suma123231__sams : forall A B C D E F, SumA A B C B C A D E F -> SAMS D E F C A B.\nProof. exact (t22_20 not_obtuse_saccheris). Qed.\n\nLemma bet_suma__suma : forall A B C D E F G H I, G <> H -> H <> I ->\n  Bet G H I -> SumA A B C B C A D E F -> SumA D E F C A B G H I.\nProof.\n  intros A B C D E F G H I HGH HHI HBet HSuma.\n  suma.assert_diffs.\n  destruct (bet__trisuma A B C G H I) as [D' [E' [F' []]]]; auto.\n  apply (conga3_suma__suma D' E' F' C A B G H I); try apply conga_refl; auto.\n  apply (suma2__conga A B C B C A); assumption.\nQed.\n\nLemma suma__suppa : forall A B C D E F, SumA A B C B C A D E F -> SuppA D E F C A B.\nProof.\n  intros A B C D E F HSuma.\n  suma.assert_diffs.\n  destruct (point_construction_different A B) as [A' []].\n  apply bet_suma__suppa with A B A'; trivial.\n  apply bet_suma__suma; auto.\nQed.\n\nLemma high_school_exterior_angle_theorem : forall A B C B', A <> B -> B <> C -> A <> C -> A <> B' ->\n  Bet B A B' -> SumA A B C B C A C A B'.\nProof.\n  intros A B C B'; intros.\n  destruct (ex_suma A B C B C A) as [D [E [F HSuma]]]; auto.\n  apply (conga3_suma__suma A B C B C A D E F); try apply conga_refl; auto.\n  apply suppa2__conga123 with C A B.\n    apply suma__suppa; assumption.\n    apply suppa_sym, suppa_left_comm, bet__suppa; auto.\nQed.\n\n(** If A, B and C are points on a circle where the line AB is a diameter of the circle,\n    then the angle ACB is a right angle. *)\n\nLemma thales_theorem : forall A B C M,\n  Midpoint M A B -> Cong M A M C -> Per A C B.\nProof.\n  apply rah__thales_postulate.\n  unfold postulate_of_right_saccheri_quadrilaterals; apply right_saccheris.\nQed.\n\n(** In a right triangle, the midpoint of the hypotenuse is the circumcenter. *)\n\nLemma thales_converse_theorem : forall A B C M,\n  Midpoint M A B -> Per A C B -> Cong M A M C.\nProof.\n  apply thales_postulate__thales_converse_postulate.\n  unfold thales_postulate; apply thales_theorem.\nQed.\n\nLemma thales_converse_theorem_1 : forall A B C O, A <> C -> B <> C ->\n  Per A C B -> Cong O A O B -> Cong O A O C -> Coplanar A B C O -> Midpoint O A B.\nProof.\n  intros A B C O HAC HBC HPer HCong1 HCong2 HCop.\n  destruct (midpoint_existence A B) as [M HM].\n  assert (M = O); [|subst; apply HM].\n  suma.assert_diffs.\n  apply (cong4_cop2__eq A C B); Cong; [|Cop..].\n  apply cong_commutativity, thales_converse_theorem with B; assumption.\nQed.\n\nLemma bet_cong__ghalfa : forall A B C B', A <> B -> B <> C -> A <> B' ->\n  Bet B A B' -> Cong A B A C -> gHalfA A B C C A B'.\nProof.\n  intros A B C B' HAB HBC HAB' HBet HCong.\n  apply ghalfa_chara; split.\n    apply cong__acute; auto.\n  suma.assert_diffs.\n  apply (conga3_suma__suma A B C B C A C A B'); try apply conga_refl; auto.\n    apply high_school_exterior_angle_theorem; auto.\n  apply conga_left_comm, l11_44_1_a; Cong.\nQed.\n\n(** If the angle ACB is inscribed in a circle of center O and\n    C, O lie on the same side of AB, then this angle is acute. *)\n\nLemma onc3_os__acute : forall O P A B C,\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> OS A B O C ->\n  Acute A C B.\nProof.\n  intros O P A B C HA HB HC HOS.\n  destruct (midpoint_existence A B) as [M HM].\n  assert (HNCol : ~ Col A B C) by (eapply one_side_not_col124, HOS).\n  assert (HLt : Lt M A M C).\n  { assert (HNCol1 : ~ Col A B O) by (eapply one_side_not_col123, HOS).\n    assert (M <> O) by (intro; treat_equalities; apply HNCol1; Col).\n    assert (O <> C) by (intro; treat_equalities; auto).\n    suma.assert_diffs.\n    assert (Cong O A O C) by (apply (onc2__cong O P); assumption).\n    destruct (angle_partition M O C); auto.\n    - assert (HMO := H).\n      clear H.\n      destruct (l8_18_existence M O C) as [H []].\n      { intro.\n        destruct (acute_col__out M O C) as [_ [_ [HBet|HBet]]]; auto.\n        - apply l9_9_bis in HOS.\n          apply HOS.\n          repeat split; Col.\n          exists M; split; Col.\n        - apply (le__nlt O C O M); Le.\n          apply (cong2_lt__lt O M O P); Cong.\n          apply bet_inc2__incs with A B; Circle; Between.\n      }\n      assert (Perp O M A B) by (apply mid_onc2__perp with P; auto).\n      assert (HOS1 : OS A B C H).\n      { apply l12_6, par_not_col_strict with C; Col.\n        apply l12_9 with O M; Perp; [|Cop| |Cop].\n          apply coplanar_perm_5, col_cop__cop with B; Col; Cop.\n          apply coplanar_perm_5, col_cop__cop with A; Col; Cop.\n      }\n      assert (M <> H) by (intro; subst; apply one_side_not_col124 in HOS1; apply HOS1; Col).\n      assert (Per M H C) by (apply perp_per_1, perp_left_comm, perp_col with O; Col).\n      apply lt_transitivity with H C; [|suma.assert_diffs; apply l11_46; auto].\n      apply cong_lt_per2__lt_1 with O O; Cong.\n        apply l8_2, per_col with M; Col; Perp.\n        apply perp_per_1, perp_left_comm, perp_col1 with B; Col.\n      apply bet__lt1213; auto; apply out2__bet.\n        apply (acute_col_perp__out C); [apply acute_sym|..]; Col; Perp.\n        apply (l9_19 A B); Col; apply one_side_transitivity with C; assumption.\n    - apply lt_transitivity with O C; [|apply l11_46; auto].\n      apply (cong2_lt__lt M A O A); Cong.\n      apply l11_46; auto.\n      left.\n      apply mid_onc2__per with P B; auto.\n  }\n  destruct HLt as [[C' [HBet HCong]] HNCong].\n  exists A, C', B; split.\n    apply thales_theorem with M; trivial.\n  suma.assert_diffs.\n  assert (C <> C') by (intro; subst; apply HNCong, HCong).\n  apply os3__lta.\n  - apply one_side_transitivity with M.\n      apply invert_one_side, out_one_side; [Col|apply l6_6, bet_out; Between].\n      apply out_one_side; [left; intro; apply HNCol; ColR|apply l6_6, bet_out; Between].\n  - apply out_one_side_1 with M; Col; apply l6_6, bet_out; auto.\n  - apply one_side_transitivity with M.\n      apply invert_one_side, out_one_side; [Col|apply l6_6, bet_out; Between].\n      apply out_one_side; [left; intro; apply HNCol; ColR|apply l6_6, bet_out; Between].\nQed.\n\nLemma inscribed_angle_aux : forall O P A B C,\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P ->\n  OS A B O C -> TS O C A B ->\n  gHalfA A C B A O B.\nProof.\n  intros O P A B C HA HB HC HOS HTS.\n  destruct (segment_construction C O O P) as [C' []].\n  suma.assert_diffs.\n  assert (O <> C') by (intro; treat_equalities; auto).\n  assert (HCong := (onc2__cong O P)).\n  apply suma_preserves_ghalfa with A C C' C' C B A O C' C' O B.\n    apply (onc3_os__acute O P); assumption.\n    apply ts__suma, invert_two_sides, col_two_sides with O; Side; Col.\n    apply ts__suma, invert_two_sides, col_two_sides with C; Col.\n    apply ghalfa_out4__ghalfa with A O A C'; try apply out_trivial; auto;\n      [apply l6_6, bet_out|apply ghalfa_left_comm, bet_cong__ghalfa]; auto.\n    apply ghalfa_out4__ghalfa with O B C' B; try apply out_trivial; auto;\n      [apply l6_6, bet_out|apply ghalfa_right_comm, bet_cong__ghalfa]; auto.\nQed.\n\nLemma inscribed_angle_aux1 : forall O P A B C,\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P ->\n  OS A B O C -> OS O C A B ->\n  gHalfA A C B A O B.\nProof.\n  assert (Haux : forall O P A B C, OnCircle A O P -> OnCircle B O P -> OnCircle C O P ->\n  OS A B O C -> OS O C A B -> OS O B A C -> gHalfA A C B A O B).\n  { intros O P A B C HA HB HC HOS1 HOS2 HOS3.\n    destruct (chord_completion O P C O) as [C' [HC' HBet ]]; Circle.\n    suma.assert_diffs.\n    assert (C' <> O) by (intro; treat_equalities; auto).\n    assert (TS O B A C').\n    { apply l9_8_2 with C; [|Side].\n      apply one_side_not_col124 in HOS3.\n      repeat split.\n        Col.\n        intro; apply HOS3; ColR.\n      exists O; split; Col.\n    }\n    assert (HCong := (onc2__cong O P)).\n    apply acute_ghalfa2_sams_suma2__ghalfa123 with B C O A C O B O C' A O C'.\n    - repeat split; auto.\n        right; intro; assert_cols; assert_ncols; Col.\n      exists C'.\n      split; CongA.\n      repeat split; [Side| |Cop].\n      apply l9_9_bis, invert_one_side, one_side_symmetry, os_ts1324__os; [|Side].\n      apply col_one_side with C; Col; Side.\n    - apply (onc3_os__acute O P); assumption.\n    - exists O.\n      repeat (split; CongA); [|Cop].\n      apply l9_9, invert_two_sides, l9_31; Side.\n    - exists C'.\n      repeat (split; CongA); [Side|Cop].\n    - apply ghalfa_left_comm, bet_cong__ghalfa; auto.\n    - apply ghalfa_left_comm, bet_cong__ghalfa; auto.\n  }\n  intros O P A B C HA HB HC HOS1 HOS2.\n  assert_ncols.\n  destruct (cop__one_or_two_sides O B A C) as [HTS|]; Col; Cop.\n    apply ghalfa_comm, Haux with P; auto; [..|apply one_side_symmetry, os_ts1324__os]; Side.\n    apply Haux with P; assumption.\nQed.\n\n(** Euclid Book III Prop 20:\n    In a circle the angle at the centre is double of the angle at the circumference,\n    when the angles have the same circumference as base. *)\n\nLemma inscribed_angle : forall O P A B C,\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> OS A B O C ->\n  gHalfA A C B A O B.\nProof.\n  intros O P A B C HA HB HC HOS.\n  assert (HCong := (onc2__cong O P)).\n  destruct (col_dec A O C).\n  { suma.assert_diffs.\n    assert (Bet C O A) by (apply col_inc_onc2__bet with O P; Col; Circle).\n    assert (O <> C) by (intro; treat_equalities; auto).\n    apply ghalfa_right_comm, ghalfa_out4__ghalfa with O B B A; try apply out_trivial; auto.\n      apply l6_6, bet_out; auto.\n    apply bet_cong__ghalfa; auto.\n  }\n  destruct (col_dec B O C).\n  { suma.assert_diffs.\n    assert (Bet C O B) by (apply col_inc_onc2__bet with O P; Col; Circle).\n    assert (O <> C) by (intro; treat_equalities; auto).\n    apply ghalfa_left_comm, ghalfa_out4__ghalfa with O A A B; try apply out_trivial; auto.\n      apply l6_6, bet_out; auto.\n    apply bet_cong__ghalfa; auto.\n  }\n  destruct (cop__one_or_two_sides O C A B); Cop.\n    apply inscribed_angle_aux with P; assumption.\n    apply inscribed_angle_aux1 with P; assumption.\nQed.\n\nLemma diam_onc2_ts__suppa : forall O P A B C C',\n  OnCircle A O P -> OnCircle B O P -> Diam C C' O P -> TS A B C C' ->\n  SuppA A C B A C' B.\nProof.\n  intros O P A B C C' HA HB [HBet [HC HC']] HTS.\n  suma.assert_diffs.\n  assert (HCong := onc2__cong O P).\n  assert (HMid : Midpoint O C C') by (split; Cong).\n  assert (C <> C') by (intro; treat_equalities; auto).\n  assert (HNColA : ~ Col C C' A) by (apply (onc3__ncol O P); auto).\n  assert (HNColB : ~ Col C C' B) by (apply (onc3__ncol O P); auto).\n  assert (HSumaA : SumA A C C' C C' A C A C') by (apply cong_mid__suma with O; auto).\n  assert (HSumaB : SumA B C C' C C' B C B C') by (apply cong_mid__suma with O; auto).\n  assert (Per C A C') by (apply thales_theorem with O; auto).\n  assert (Per C B C') by (apply thales_theorem with O; auto).\n  assert (HSuma : SumA C A C' C B C' C O C') by (suma.assert_diffs; apply bet_per2__suma; auto).\n  apply bet_suma__suppa with C O C'; trivial.\n  destruct (ex_suma C A C' C' C B) as [D [E [F HSuma1]]]; auto.\n  assert (HTS2 : TS C C' A B) by (apply (chord_intersection O P); assumption).\n  assert (HTS3 : TS C' C A B) by (apply invert_two_sides, HTS2).\n  assert (Acute C' C A).\n  { suma.assert_diffs; apply acute_out2__acute with O A.\n      apply l6_6, bet_out; auto.\n      apply out_trivial; auto.\n      apply cong__acute; auto.\n  }\n  assert (Acute C' C B).\n  { suma.assert_diffs; apply acute_out2__acute with O B.\n      apply l6_6, bet_out; auto.\n      apply out_trivial; auto.\n      apply cong__acute; auto.\n  }\n  assert (Acute C C' A).\n  { suma.assert_diffs; apply acute_out2__acute with O A.\n      apply l6_6, bet_out; Between.\n      apply out_trivial; auto.\n      apply cong__acute; auto.\n  }\n  assert (Acute C C' B).\n  { suma.assert_diffs; apply acute_out2__acute with O B.\n      apply l6_6, bet_out; Between.\n      apply out_trivial; auto.\n      apply cong__acute; auto.\n  }\n  assert (HSuma2 : SumA A C B A C' C D E F).\n    apply suma_sym, suma_assoc_1 with A C C' C' C B C A C'; SumA.\n  assert (HSAMS : SAMS A C B A C' C).\n    apply sams_sym, sams_assoc_1 with A C C' C' C B C A C'; SumA.\n  apply suma_assoc_1 with A C' C C C' B D E F; [SumA..|].\n  apply suma_assoc_2 with C A C' B C C' C B C'; SumA.\nQed.\n\n(** In a circle the angle at the centre is double of the angle at the circumference. *)\n\nLemma inscribed_angle_1 : forall O P A B C, A <> B -> B <> C -> A <> C ->\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> Coplanar A B C O ->\n  SumA A C B A C B A O B.\nProof.\n  intros O P A B C HAB HBC HAC HA HB HC HCop.\n  assert (~ Col A B C) by (apply (onc3__ncol O P); auto).\n  destruct (col_dec A B O).\n  { assert (Midpoint O A B) by (apply col_onc2__mid with P; auto).\n    assert (Per A C B) by (apply thales_theorem with O; auto; apply cong_transitivity with O P; Cong).\n    suma.assert_diffs; apply bet_per2__suma; Between.\n  }\n  destruct (cop__one_or_two_sides A B O C); Col; Cop.\n  - destruct (chord_completion O P C O) as [C' []]; Circle.\n    assert (TS A B C' C) by (apply l9_2, bet_ts__ts with O; Side).\n    assert (SuppA A C' B A C B).\n      apply (diam_onc2_ts__suppa O P); [..|repeat split|]; Between.\n    apply (suma_suppa2__suma A C' B A C' B); trivial.\n    apply ghalfa__suma, inscribed_angle with P; trivial.\n    exists C; split; trivial.\n  - apply ghalfa__suma, inscribed_angle with P; trivial.\nQed.\n\n(** If two angles ACB and ADB are inscribed in the same circle,\n    then they are either congruent or supplementary. *)\n\nLemma cop2_onc4__or_conga_suppa : forall O P A B C C',\n  A <> B -> B <> C -> A <> C -> B <> C' -> A <> C' ->\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> OnCircle C' O P ->\n  Coplanar A B C O -> Coplanar A B C' O ->\n  CongA A C B A C' B \\/ SuppA A C B A C' B.\nProof.\n  intros O P A B C C'; intros.\n  apply suma2__or_conga_suppa with A O B; trivial; apply inscribed_angle_1 with P; assumption.\nQed.\n\n(** If the angle ACB is inscribed in a circle of center O and\n    C, O lie on opposite sides of AB, then this angle is obtuse. *)\n\nLemma onc3_ts__obtuse : forall O P A B C,\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> TS A B O C ->\n  Obtuse A C B.\nProof.\n  intros O P A B C HA HB HC HTS.\n  destruct (chord_completion O P C O) as [C' []]; Circle.\n  assert (TS A B C C') by (apply bet_ts__ts with O; Side).\n  apply (acute_suppa__obtuse A C' B).\n    apply (onc3_os__acute O P); trivial; exists C; split; Side.\n  apply (diam_onc2_ts__suppa O P); Side.\n  repeat split; Between.\nQed.\n\n(** Euclid Book III Prop 21:\n    In a circle the angles in the same segment are equal to one another. *)\n\nLemma cop_onc4_os__conga : forall O P A B C C',\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> OnCircle C' O P ->\n  OS A B C C' -> Coplanar A B C O ->\n  CongA A C B A C' B.\nProof.\n  intros O P A B C C' HA HB HC HC' HOS HCop.\n  assert_ncols.\n  destruct (col_dec A B O).\n  { suma.assert_diffs.\n    assert (Midpoint O A B) by (apply col_onc2__mid with P; auto).\n    apply l11_16; auto; apply thales_theorem with O; Col; apply cong_transitivity with O P; Cong.\n  }\n  destruct (cop__one_or_two_sides A B O C); Col; Cop.\n  - suma.assert_diffs; destruct (cop2_onc4__or_conga_suppa O P A B C C') as [|Habs]; auto.\n      apply coplanar_trans_1 with C; Col; Cop.\n    exfalso.\n    apply (nlta A C' B), acute_obtuse__lta.\n      apply (obtuse_suppa__acute A C B); [apply (onc3_ts__obtuse O P)|]; trivial.\n      apply (onc3_ts__obtuse O P); trivial; apply l9_2, l9_8_2 with C; Side.\n  - apply ghalfa2__conga_2 with A O B; apply inscribed_angle with P; trivial.\n    apply one_side_transitivity with C; Side.\nQed.\n\n(** Euclid Book III Prop 22:\n    The opposite angles of quadrilaterals in circles are equal to two right angles. *)\n\nLemma cop_onc4_ts__suppa : forall O P A B C C',\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> OnCircle C' O P ->\n  TS A B C C' -> Coplanar A B C O ->\n  SuppA A C B A C' B.\nProof.\n  intros O P A B C C' HA HB.\n  revert C C'.\n  assert (Haux : forall C C', OnCircle C O P -> OnCircle C' O P -> TS A B C C' -> OS A B O C ->\n    SuppA A C B A C' B).\n  { intros C C' HC HC' HTS HOS.\n    suma.assert_diffs.\n    assert (~ Col C A B) by (destruct HTS; assumption).\n    assert (Coplanar A B C' O) by (apply coplanar_trans_1 with C; Cop).\n    destruct (cop2_onc4__or_conga_suppa O P A B C C') as [Habs|]; Cop.\n    exfalso.\n    assert (HLta : LtA A C B A C' B); [|destruct HLta as [_ HN]; apply HN, Habs].\n    apply acute_obtuse__lta.\n      apply (onc3_os__acute O P); assumption.\n    apply (onc3_ts__obtuse O P); trivial.\n    apply l9_8_2 with C; Side.\n  }\n  intros C C' HC HC' HTS HCop.\n  assert (~ Col C A B) by (destruct HTS; assumption).\n  destruct (col_dec A B O).\n  { suma.assert_diffs.\n    assert (Midpoint O A B) by (apply col_onc2__mid with P; auto).\n    destruct HTS as [_ []].\n    apply per2__suppa; auto; apply thales_theorem with O; trivial; apply onc2__cong with P; assumption.\n  }\n  destruct (cop__one_or_two_sides A B O C); Col; Cop.\n  apply suppa_sym, Haux; [..|exists C; split]; Side.\nQed.\n\n(** If the angle ACB is acute and inscribed in a circle of center O,\n    then C and O lie on the same side of AB. *)\n\nLemma acute_cop_onc3__os : forall O P A B C, A <> B ->\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> Coplanar A B C O -> Acute A C B ->\n  OS A B O C.\nProof.\n  intros O P A B C HAB HA HB HC HCop HAcute.\n  suma.assert_diffs.\n  assert (~ Col A B C) by (apply (onc3__ncol O P); auto).\n  apply coplanar_perm_1 in HCop.\n  apply cop_nts__os; Col; intro Habs; apply (nlta A C B).\n  - apply acute_per__lta; auto.\n    apply thales_theorem with O; trivial.\n      apply col_onc2__mid with P; Col.\n      apply (onc2__cong O P); assumption.\n  - apply acute_obtuse__lta; trivial.\n    apply (onc3_ts__obtuse O P); assumption.\nQed.\n\n(** If the angle ACB is obtuse and inscribed in a circle of center O,\n    then C and O lie on opposite sides of AB. *)\n\nLemma cop_obtuse_onc3__ts : forall O P A B C,\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> Coplanar A B C O -> Obtuse A C B ->\n  TS A B O C.\nProof.\n  intros O P A B C HA HB HC HCop HObtuse.\n  suma.assert_diffs.\n  assert (~ Col A B C) by (apply (onc3__ncol O P); auto).\n  apply coplanar_perm_1 in HCop.\n  apply cop_nos__ts; Col; intro Habs; apply (nlta A C B).\n  - apply obtuse_per__lta; auto.\n    apply thales_theorem with O; trivial.\n      apply col_onc2__mid with P; Col.\n      apply (onc2__cong O P); assumption.\n  - apply acute_obtuse__lta; trivial.\n    apply (onc3_os__acute O P); assumption.\nQed.\n\n(** If the angles ACB and ADB are congruent and inscribed in the same circle,\n    then C and D lie on the same side of AB. *)\n\nLemma conga_cop2_onc4__os : forall O P A B C D, ~ Col A B O ->\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> OnCircle D O P ->\n  Coplanar A B O C -> Coplanar A B O D -> CongA A C B A D B ->\n  OS A B C D.\nProof.\n  intros O P A B C D HNCol HA HB HC HD HCopC HCopD HConga.\n  suma.assert_diffs.\n  destruct (angle_partition A C B) as [HAcute|[HPer|HObtuse]]; auto.\n  - apply one_side_transitivity with O; [apply one_side_symmetry|];\n      apply acute_cop_onc3__os with P; Cop.\n    apply (acute_conga__acute A C B); assumption.\n  - exfalso.\n    apply HNCol, col_permutation_1, midpoint_col.\n    assert (HCong := onc2__cong O P).\n    apply thales_converse_theorem_1 with C; Cop.\n  - exists O; split; apply l9_2; apply cop_obtuse_onc3__ts with P; Cop.\n    apply (conga_obtuse__obtuse A C B); assumption.\nQed.\n\n(** If the angles ACB and ADB are supplementary and inscribed in the same circle,\n    then C and D lie on opposite sides of AB. *)\n\nLemma cop2_onc4_suppa__ts : forall O P A B C D, ~ Col A B O ->\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> OnCircle D O P ->\n  Coplanar A B O C -> Coplanar A B O D -> SuppA A C B A D B ->\n  TS A B C D.\nProof.\n  intros O P A B C D HNCol HA HB HC HD HCopC HCopD HSuppa.\n  suma.assert_diffs.\n  destruct (angle_partition A C B) as [HAcute|[HPer|HObtuse]]; auto.\n  - apply l9_8_2 with O.\n      apply cop_obtuse_onc3__ts with P; Cop; apply (acute_suppa__obtuse A C B); assumption.\n      apply acute_cop_onc3__os with P; Cop.\n  - exfalso.\n    apply HNCol, col_permutation_1, midpoint_col.\n    assert (HCong := onc2__cong O P).\n    apply thales_converse_theorem_1 with C; Cop.\n  - apply l9_2, l9_8_2 with O.\n      apply cop_obtuse_onc3__ts with P; Cop.\n    apply acute_cop_onc3__os with P; Cop; apply (obtuse_suppa__acute A C B); assumption.\nQed.\n\n(** Non degenerated triangles can be circumscribed. *)\n\nLemma triangle_circumscription : forall A B C, ~ Col A B C ->\n  exists CC : Tpoint, Cong A CC B CC /\\ Cong A CC C CC /\\ Coplanar A B C CC.\nProof.\n  apply postulates_in_euclidean_context; simpl; repeat (try (left; reflexivity); right).\nQed.\n\n(** Euclid Book III Prop 23:\n    On the same straight line there cannot be constructed\n    two similar and unequal segments of circles on the same side. *)\n\nLemma conga_cop_onc6_os__eqc : forall A B C D O P O' P',\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P -> Coplanar A B C O ->\n  OnCircle A O' P' -> OnCircle B O' P' -> OnCircle D O' P' -> Coplanar A B D O' ->\n  OS A B C D -> CongA A C B A D B ->\n  EqC O P O' P'.\nProof.\n  intros A B C D O P O' P' HA HB HC HCop HA' HB' HD' HCop' HOS HConga.\n  apply eqc_chara.\n  assert (O = O'); [|split; trivial; subst O'; apply cong_transitivity with O A; Cong].\n  assert (HNCol : ~ Col A B C) by (apply one_side_not_col123 with D, HOS).\n  assert (HCong := onc2__cong O P).\n  assert (HCong' := onc2__cong O' P').\n  destruct (col_dec A B O) as [|HNCol1].\n  { suma.assert_diffs.\n    assert (Midpoint O A B) by (apply col_onc2__mid with P; assumption).\n    apply (l7_17 A B); trivial.\n    apply thales_converse_theorem_1 with D; auto.\n    apply (l11_17 A C B); trivial.\n    apply thales_theorem with O; auto.\n  }\n  assert (HNCol' : ~ Col A B D) by (apply one_side_not_col124 with C, HOS).\n  destruct (midpoint_existence A B) as [M HM].\n  assert (HOS1 : OS A B O O').\n  { suma.assert_diffs; destruct (angle_partition A C B) as [HAcute|[HPer|HObtuse]]; auto.\n    - apply one_side_transitivity with C;\n        [|apply one_side_transitivity with D; trivial; apply one_side_symmetry].\n        apply acute_cop_onc3__os with P; auto.\n      apply acute_cop_onc3__os with P'; auto.\n      apply (acute_conga__acute A C B); assumption.\n    - exfalso.\n      apply HNCol1, col_permutation_1, midpoint_col.\n      apply thales_converse_theorem_1 with C; auto.\n    - exists C; split; [|apply l9_2, l9_8_2 with D; [apply l9_2|Side]].\n        apply cop_obtuse_onc3__ts with P; auto.\n      apply cop_obtuse_onc3__ts with P'; auto.\n      apply (conga_obtuse__obtuse A C B); assumption.\n  }\n  assert (HNCol1' : ~ Col A B O') by (apply one_side_not_col124 with O, HOS1).\n  destruct (bet_cop_onc2__ex_onc_os_out O P A B C M) as [C1]; Between; Col; [suma.assert_diffs; auto..|].\n  destruct (bet_cop_onc2__ex_onc_os_out O' P' A B D M) as [D1]; Between; Col; [suma.assert_diffs; auto..|].\n  spliter.\n  assert (HNCol2 : ~ Col A B C1) by (apply one_side_not_col124 with C; assumption).\n  assert (HOut : Out M C1 D1).\n  { apply (l9_19 A B); [Col| |\n      apply one_side_transitivity with C; [|apply one_side_transitivity with D]; Side].\n    assert (O <> M) by (intro; subst; apply HNCol1; Col).\n    assert (O' <> M) by (intro; subst; apply HNCol1'; Col).\n    assert (Col O O' M); [|ColR].\n    suma.assert_diffs; apply (cop_per2__col A); auto;\n      [|apply mid_onc2__per with P B; auto|apply mid_onc2__per with P' B; auto].\n    apply coplanar_trans_1 with B; Col; [|Cop].\n    apply coplanar_trans_1 with C; Col; [Cop|].\n    apply coplanar_perm_12, coplanar_trans_1 with D; Col; Cop.\n  }\n  destruct (eq_dec_points C1 D1).\n  { subst D1.\n    suma.assert_diffs.\n    apply (cong4_cop2__eq A B C1); Cong; exists M; left; split; Col.\n  }\n  assert (HNCol2' : ~ Col A B D1) by (apply one_side_not_col124 with D; assumption).\n  assert (CongA A C1 B A C B) by (apply (cop_onc4_os__conga O P); Side; exists M; left; split; Col).\n  assert (CongA A D1 B A D B) by (apply (cop_onc4_os__conga O' P'); Side; exists M; left; split; Col).\n  assert (Out A B M) by (suma.assert_diffs; apply l6_6, bet_out; Between).\n  assert (Out B A M) by (suma.assert_diffs; apply l6_6, bet_out; Between).\n  assert (HH := HOut).\n  destruct HH as [HMC1 [HMD1 [HBet|HBet]]]; exfalso.\n  - apply (lta_not_conga A D B A C B); CongA.\n    apply (conga_preserves_lta A D1 B A C1 B); trivial.\n    assert (Out D1 M C1) by (apply l6_6, bet_out; Between).\n    apply os3__lta; [|apply one_side_symmetry, l9_19 with M; Col|];\n      apply one_side_transitivity with M.\n      apply invert_one_side, out_one_side; Col.\n      apply out_one_side; trivial; left; intro; apply HNCol2'; ColR.\n      apply invert_one_side, out_one_side; Col.\n      apply out_one_side; trivial; left; intro; apply HNCol2'; ColR.\n  - apply (lta_not_conga A C B A D B); trivial.\n    apply (conga_preserves_lta A C1 B A D1 B); trivial.\n    assert (Out C1 M D1) by (apply l6_6, bet_out; Between).\n    apply os3__lta; [|apply l9_19 with M; Col|];\n      apply one_side_transitivity with M.\n      apply invert_one_side, out_one_side; Col.\n      apply out_one_side; trivial; left; intro; apply HNCol2; ColR.\n      apply invert_one_side, out_one_side; Col.\n      apply out_one_side; trivial; left; intro; apply HNCol2; ColR.\nQed.\n\nLemma conga_cop_onc3_os__onc : forall A B C D O P,\n  OnCircle A O P -> OnCircle B O P -> OnCircle C O P ->\n  Coplanar A B C O -> OS A B C D -> CongA A C B A D B ->\n  OnCircle D O P.\nProof.\n  intros A B C D O P HA HB HC HCop HOS HConga.\n  destruct (triangle_circumscription A B D) as [O'].\n    apply one_side_not_col124 in HOS; Col.\n  spliter.\n  assert (OnCircle A O' A /\\ OnCircle B O' A /\\ OnCircle D O' A).\n    unfold OnCircle; repeat split; Cong.\n  spliter.\n  apply (conga_cop_onc6_os__eqc A B C D O P O' A); trivial.\nQed.\n\n(** If the angles ACB and ADB are congruent and C, D lie on the same side of AB,\n    then A, B, C and D are concyclic. *)\n\nLemma conga_os__concyclic : forall A B C D,\n  OS A B C D -> CongA A C B A D B -> Concyclic A B C D.\nProof.\n  intros A B C D HOS HConga.\n  split.\n    apply os__coplanar, HOS.\n  destruct (triangle_circumscription A B C) as [O]; spliter.\n    apply one_side_not_col123 with D, HOS.\n  assert (OnCircle A O A /\\ OnCircle B O A /\\ OnCircle C O A).\n    unfold OnCircle; repeat split; Cong.\n  spliter.\n  exists O, A; repeat split; trivial.\n  apply (conga_cop_onc3_os__onc A B C); assumption.\nQed.\n\n(** If the angles ACB and ADB are supplementary and C, D lie on opposite sides of AB,\n    then A, B, C and D are concyclic. *)\n\nLemma suppa_ts__concyclic : forall A B C D,\n  TS A B C D -> SuppA A C B A D B -> Concyclic A B C D.\nProof.\n  intros A B.\n  assert (Haux : forall C D, TS A B C D -> Obtuse A C B -> SuppA A C B A D B -> Concyclic A B C D).\n  { intros C D HTS HObtuse HSuppa.\n    split.\n      apply ts__coplanar, HTS.\n    assert (HNCol : ~ Col A B C) by (destruct HTS; Col).\n    destruct (triangle_circumscription A B C HNCol) as [O]; spliter.\n    assert (OnCircle A O A /\\ OnCircle B O A /\\ OnCircle C O A).\n      unfold OnCircle; repeat split; Cong.\n    spliter.\n    exists O, A; repeat split; trivial.\n    destruct (chord_completion O A C O) as [C'[HC' HBet]]; Circle.\n    assert (TS A B C C').\n      apply bet_ts__ts with O; [apply l9_2, cop_obtuse_onc3__ts with A|]; assumption.\n    apply (conga_cop_onc3_os__onc A B C'); trivial.\n      apply coplanar_trans_1 with C; Col; Cop.\n      exists C; split; Side.\n      apply (suppa2__conga456 A C B); [apply (cop_onc4_ts__suppa O A)|]; assumption.\n  }\n  intros C D HTS HSuppa.\n  assert (HCop : Coplanar A B C D) by (apply ts__coplanar, HTS).\n  suma.assert_diffs; destruct (angle_partition A C B) as [|[|]]; auto; split; trivial.\n  { destruct (Haux D C) as [_ [O [P]]].\n      Side.\n      apply (acute_suppa__obtuse A C B); trivial.\n      apply suppa_sym, HSuppa.\n    exists O, P.\n    spliter; repeat split; trivial.\n  }\n  destruct (midpoint_existence A B) as [M].\n  exists M, A.\n  destruct HTS as [HNCol1 [HNCol2 _]].\n  unfold OnCircle; repeat split; [Cong..| |];\n    apply cong_symmetry, thales_converse_theorem with B; auto.\n  apply (per_suppa__per A C B); assumption.\nQed.\n\n(** In a convex quadrilateral, if two opposite angles are supplementary\n    then the two other angles are also supplementary. *)\n\nLemma suppa_ts2__suppa : forall A B C D,\n  TS A C B D -> TS B D A C -> SuppA A B C A D C -> SuppA B A D B C D.\nProof.\n  intros A B C D HTS1 HTS2 HSuppa.\n  assert (HCon : Concyclic A C B D) by (apply suppa_ts__concyclic; trivial).\n  apply concyclic_aux in HCon.\n  destruct HCon as [O [P]]; spliter.\n  apply (cop_onc4_ts__suppa O P); trivial.\n  apply coplanar_perm_2, coplanar_trans_1 with C; [destruct HTS1; Col|Cop..].\nQed.\n\nEnd Inscribed_angle.\n\nSection Inscribed_angle_2.\n\nContext `{T2D:Tarski_2D}.\nContext `{TE:@Tarski_euclidean Tn TnEQD}.\n\nLemma chord_par_diam : forall O P A B C C' A' U,\n O <> P -> ~Col A B C' -> Diam C C' O P -> Midpoint A' A C' -> OnCircle A O P -> OnCircle B O P ->\n Col A B U -> Perp O U A B -> Par A C' O U -> B = C.\nProof.\nintros.\nsuma.assert_diffs.\nassert(Midpoint U A B).\n{\n  apply(col_onc2_perp__mid O P A B U); Col.\n}\nassert(O <> A').\nintro.\ntreat_equalities.\ninduction H7.\napply H7.\nexists O.\nsplit; Col.\nspliter.\nassert(Perp A U  O U).\n{\n  apply perp_sym in H6.\n  apply (perp_col A B O U U); Col.\n  intro.\n  treat_equalities.\n  apply perp_distinct in H6.\n  tauto.\n}\napply perp_left_comm in H18.\napply perp_not_col in H18.\napply H18; Col.\nunfold Diam in H1.\nspliter.\nassert(HH:=mid_onc2__perp O P A C' A' H15 H13 H3 H17 H2).\nassert(Perp O U O A').\n{\n  apply(par_perp__perp A C' O U O A' H7); Perp.\n}\n\nassert(Par O A' A B).\n{\n  apply (l12_9_2D _ _ _ _ O U); Perp.\n}\nassert(HM:=midpoint_existence B C').\nex_and HM O'.\nassert(HP:= triangle_mid_par A B C' O' A' H0 H20 H2).\napply par_strict_par in HP.\nassert(Par O A' A' O').\n{\n  apply (par_trans _ _ A B); Par.\n}\nassert(Col O O' A').\n{\n  induction H21.\n  apply False_ind.\n  apply H21.\n  exists A'.\n  split; Col.\n  spliter.\n  Col.\n}\n\ninduction(eq_dec_points O O').\ntreat_equalities.\napply(symmetric_point_uniqueness C' O); Midpoint.\nsplit; [Between|CongR].\n\nassert(HQ:= mid_onc2__perp O P B C' O' H23  H10 H4 H17 H20).\napply(perp_col O A' A C' O') in HH; Col.\nassert(Par A C' B C').\n{\n  apply(l12_9_2D A C' B C' O O'); Perp.\n}\napply False_ind.\ninduction H24.\napply H24.\nexists C'.\nsplit;Col.\nspliter.\napply H0.\nCol.\nQed.\n\nEnd Inscribed_angle_2.\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Tarski_dev/Annexes/inscribed_angle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.6879396033546011}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (z : natural) (lf2 : natural) (lf1 : natural)\n  : natural := plus Zero (plus Zero lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj33_coqofml_C3fnU4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.687863211972591}}
{"text": "\nTheorem Ex037 (A B C : Prop) :  A \\/ B -> ~A \\/ ~C -> C -> B.\nProof.\n  intros.\n  destruct H.\n  + destruct H0. \n    - contradiction.\n    - contradiction.\n  + exact H.\nQed.\n\n\n", "meta": {"author": "SvenWille", "repo": "CoqLogicExercises", "sha": "b4c1aea30abb95dc7ba81fa42ccb914d534d65e5", "save_path": "github-repos/coq/SvenWille-CoqLogicExercises", "path": "github-repos/coq/SvenWille-CoqLogicExercises/CoqLogicExercises-b4c1aea30abb95dc7ba81fa42ccb914d534d65e5/src/propLogic/Ex037.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6878632083309729}}
{"text": "Require Import CT.Category.\nRequire Import CT.Functor.\nRequire Import CT.NaturalTransformation.\nRequire Import CT.Instance.Functor.ComposeFunctor.\n\n(** * Horizontal Composition of Natural Transformations\n\nFrom wikipedia:\n\nNatural transformations also have a \"horizontal composition\". If η : F → G is a\nnatural transformation between functors F,G : C → D and ε : J → K is a natural\ntransformation between functors J,K : D → E, then the composition of functors\nallows a composition of natural transformations εη : JF → KG. This operation is\nalso associative with identity, and the identity coincides with that for\nvertical composition.\n*)\nSection HCNaturalTransformation.\n  Context {C D E : Category} {F G : Functor C D} {J K : Functor D E}.\n  Variable mu : NaturalTransformation F G.\n  Variable epsilon : NaturalTransformation J K.\n  Let JF := ComposeFunctor F J.\n  Let KG := ComposeFunctor G K.\n\n  Program Definition HCNaturalTransformation : NaturalTransformation JF KG :=\n    {| nt_components :=\n         fun X => comp (nt_components J K epsilon (F_ob F X)) (F_mor K (nt_components F G mu X))\n    |}.\n  Next Obligation.\n  Proof.\n    rewrite assoc.\n    rewrite nt_commutes.\n    rewrite assoc_sym.\n    rewrite <- F_comp_law.\n    rewrite nt_commutes.\n    rewrite F_comp_law.\n    rewrite assoc.\n    reflexivity.\n  Qed.\n  Next Obligation.\n  Proof.\n    symmetry.\n    apply HCNaturalTransformation_obligation_1.\n  Qed.\nEnd HCNaturalTransformation.", "meta": {"author": "relrod", "repo": "ct", "sha": "abd8b0067e219ee4867f7136bdf1b35885224cb4", "save_path": "github-repos/coq/relrod-ct", "path": "github-repos/coq/relrod-ct/ct-abd8b0067e219ee4867f7136bdf1b35885224cb4/CT/Instance/NaturalTransformation/HCNaturalTransformation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.7853085733507947, "lm_q1q2_score": 0.6877630406081912}}
{"text": "Require Import Setoid Field Min List Aux.\n\nStructure eparams: Type := {\n E:> Set;                      (* the vector type *)\n stype:> fparams;              (* the scalar field *)\n E0: E;                        (* 0 *)\n eqE: E -> E -> bool;          (* = as a boolean function *)\n addE : E -> E -> E;          (* + *)\n scalE : (K stype) -> E -> E   (* scalar *)\n}.\n\nDelimit Scope vector_scope with v.\n\nNotation \"x ?= y\" := (eqE _ x y) (at level 70): vector_scope.\nNotation \"0\" := (E0 _): vector_scope.\nNotation \"x + y\" := (addE _ x y): vector_scope.\nNotation \"x .* y\" := (scalE _ x%f y) (at level 31, no associativity): vector_scope.\n\nArguments scalE _ _%field_scope _%vector_scope.\n\nSection VectorSpace.\n\n\n(* This is our scalar space *)\nVariable p : eparams.\n\nOpen Scope vector_scope.\n\nImplicit Type v x y z: p.\nImplicit Type k: stype p.\n\n(* Multiple product for characterizing linear combinations *)\nDefinition  mprod ks vs :=\n   fold2 (fun k v r => k .* v + r) ks vs 0.\n\nNotation \" x *X* y \" := (mprod x y) (at level 40, no associativity): vector_scope.\n\n\n(* What it means for a sub vector space (i.e a list of vectors)\n   to be free *)\nDefinition free vs := \n  forall ks, length ks = length vs -> ks *X* vs = 0 -> \n    (forall k, In k ks -> k = 0%f).\n\n \n(* What it is to be a linear combination *)\nInductive cbl (l: list (E p)): (E p) -> Prop :=\n  cbl0: cbl l 0\n| cbl_in: forall v, In v l -> cbl l v\n| cbl_add: forall x y, cbl l x -> cbl l y -> cbl l (x + y)\n| cbl_scal: forall k x, cbl l x -> cbl l (k .* x).\n\nLemma cbl_trans l1 l2 x: \n  (forall i, In i l2 -> cbl l1 i) -> cbl l2 x -> cbl l1 x.\nProof.\nintros H1 H2; elim H2; auto.\napply cbl0.\nintros; apply cbl_add; auto.\nintros; apply cbl_scal; auto.\nQed.\n \nDefinition is_base vs := free vs /\\ forall e, cbl vs e.\n\nStructure vparamsProp: Type := {\n sProp : fparamsProp p;\n eqE_dec: forall x y, if x ?= y then x = y else x <> y;        \n          (* Boolean equality *)\n addE_assoc: forall x y z, (x + y) + z = x + (y + z);\n          (* Associativity for + *)\n addE_com: forall x y, x + y = y + x;\n          (* Commutativity for + *)\n addE0l: forall x, 0 + x = x;\n          (* Left neutral  for + *)\n scalE0l: forall x, 0 .* x = 0;\n          (* scalar 0 *)\n scalE1: forall x, 1 .* x = x;\n          (* scalar 1 *)\n scal_addEl: forall k1 k2 x, (k1 + k2) .* x = (k1.* x) + (k2 .* x);\n          (* scalar distributivity left *)\n scal_addEr: forall k x y, k .* (x + y) = k .* x + k .* y;\n          (* scalar distributivity right *)\n scal_multE: forall k1 k2 x, (k1 * k2) .* x = k1.* (k2 .* x)\n          (* scalar distributivity left *)\n}.\n\nVariable Hp: vparamsProp.\n\nLemma eqE_refl x: (x ?= x) = true.\nProof.\ngeneralize (eqE_dec Hp x x); case eqE; auto.\nQed.\n\nLemma addE0r: forall x, x + 0 = x.\nProof.\nintros x; rewrite addE_com; auto; rewrite addE0l; auto.\nQed.\n\nLet sfP := sProp Hp.\n\nLemma addE_cancell x y z : z + x = z + y -> x = y.\nProof.\nintros H.\nrewrite <-addE0l; auto.\nrewrite <-(fun xx => scalE0l xx z); auto.\nrewrite <-(oppKl _ sfP 1%f); auto.\nrewrite scal_addEl; auto.\nrewrite scalE1; auto.\nrewrite addE_assoc; auto.\nrewrite <-H; rewrite <-addE_assoc; auto.\npattern z at 2; rewrite <-(fun xx => scalE1 xx z); auto.\nrewrite <-scal_addEl; auto.\nrewrite oppKl; auto.\nrewrite scalE0l; auto.\nrewrite addE0l; auto.\nQed.\n\nLemma addE_cancelr x y z : x + z = y + z -> x = y.\nProof.\nintros H; apply addE_cancell with z.\nrepeat rewrite (fun xx => addE_com xx z); auto.\nQed.\n\nLemma scalE0r k : k .* 0 = 0.\nProof.\napply addE_cancell with (k .* 0).\nrewrite addE0r.\nrewrite <-scal_addEr; auto.\nrewrite addE0l; auto.\nQed.\n\n(* Opposite for  + *)\nLemma scal_addE0 x : x + (- (1)) .* x = 0.\nProof.\ngeneralize (scal_addEl Hp (1)%f (- (1))%f x).\nrewrite oppKr; auto; rewrite scalE1, scalE0l; auto.\nQed.\n\n\nLemma addE_eq_opp x y : x + (-(1)) .* y = 0 -> x = y.\nProof.\nintros H; apply addE_cancell with ((-(1)) .* y).\nrewrite addE_com, H, addE_com, scal_addE0; auto.\nQed.\n\n(* Recursive equation for multiple product *)\nLemma mprod_S k ks v vs : (k :: ks) *X* (v :: vs) = k .* v + ks *X* vs.\nProof.\nassert (Hf: forall ks vs v,\n   fold2 (fun k v r => k .* v + r) ks vs v = v + ks *X* vs).\nintros ks1; induction ks1 as [| k1 ks1 IH]; simpl.\n  intros vs1 v1; unfold mprod; simpl; rewrite addE0r; auto.\nintros [| v' vs1] v1; unfold mprod; simpl.\n  rewrite addE0r; auto.\nrewrite IH; rewrite IH; rewrite addE0r;\n  rewrite (fun xx => addE_com xx v1); auto; repeat rewrite addE_assoc; auto;\n  rewrite (fun xx => addE_com xx v1); auto.\nunfold mprod; simpl.\nrewrite Hf; rewrite Hf; rewrite addE0r; rewrite addE0l; auto.\nQed.\n\nLemma mprod0l vs : nil *X* vs = 0.\nProof. auto. Qed.\n\nLemma mprod0r ks : ks *X* nil = 0.\nProof. destruct ks as [| k ks]; auto. Qed.\n\nLemma mprod0 vs1 vs2 : map (fun _ : E p => 0%f) vs1 *X* vs2 = 0.\nProof.\ngeneralize vs2; clear vs2.\ninduction vs1 as [| a vs1]; intros [| b vs2]; simpl map; \n  try rewrite mprod0r; auto.\nrewrite mprod_S; rewrite scalE0l; auto; rewrite addE0l; auto.\nQed.\n\n(* Concation for multiple product *)\nLemma mprod_app ks1 ks2 vs1 vs2 :\n   length ks1 = length vs1 -> \n      (ks1 ++ ks2) *X* (vs1 ++ vs2) = ks1 *X* vs1 + ks2 *X* vs2.\nProof.\ngeneralize ks2 vs1 vs2; clear ks2 vs1 vs2.\ninduction ks1 as [| k ks1 IH]; intros ks2 [| v vs1] vs2 H;\n  try discriminate H.\nsimpl mprod; unfold mprod; simpl; rewrite addE0l; auto.\nsimpl app; rewrite mprod_S; rewrite mprod_S; rewrite IH; auto; \n  rewrite addE_assoc; auto.\nQed.\n\nLemma eqE_spec x y : eq_Spec x y (x ?= y).\nProof.\ngeneralize (eqE_dec Hp x y); case eqE; constructor; auto.\nQed.\n\n(* Lemmas for free *)\n\nLemma free_nil : free nil.\nProof.\nintros [| k ks]; auto.\nintros H1 H2 l Hk; case Hk.\nintros HH; discriminate HH.\nQed.\n\nLemma free_cons v vs : free (v::vs) -> free vs.\nProof.\nintros Hvs ks Hlks Hpks k Hk.\napply (Hvs (0%f::ks)); simpl; auto.\nrewrite mprod_S; rewrite Hpks; rewrite scalE0l; auto; rewrite addE0l; auto.\nQed.\n\nLemma free_perm vs1 vs2 : perm vs1 vs2 -> free vs2 -> free vs1.\nProof.\nintros HH Hvs1.\nassert (Hf: forall (k1: list _), length k1 = length vs1 ->\n  exists (k2:list _), perm k1 k2 /\\ k1 *X* vs1 = k2 *X* vs2).\nelim HH; clear vs1 vs2 HH Hvs1; auto.\nintros l k1 Hk1; exists k1; split; auto.\napply perm_id.\nintros a b vs1 [|k1 [| k2 ks1]] Hl; try discriminate Hl.\nexists (k2::k1::ks1); split; auto.\napply Aux.perm_swap.\nrepeat rewrite mprod_S; repeat rewrite <-addE_assoc; auto.\nrewrite (addE_com Hp (k1 .* a)); auto.\nintros a vs1 vs2 Hperm IH [| k1 ks1]; intros HH; try discriminate.\ncase (IH ks1); auto.\nintros ks2 (H1ks2, H2ks2); exists (k1::ks2); split; simpl; auto.\napply Aux.perm_skip; auto.\nrepeat rewrite mprod_S; rewrite H2ks2; auto.\nintros vs1 vs2 vs3 Hp1 IH1 Hp2 IH2 k1 Hk1.\ncase (IH1 _ Hk1); intros k2 (H1k2, H2k2).\nassert (Hk2: length k2 = length vs2).\n  rewrite <-(perm_length _ _ _ Hp1);\n  rewrite <-(perm_length _ _ _ H1k2); auto.\ncase (IH2 _ Hk2); intros k3 (H1k3, H2k3).\nexists k3; split.\napply Aux.perm_trans with (1 := H1k2); auto.\nrewrite H2k2; auto.\nintros ks Hlks Hpks k Hk.\ncase (Hf ks); auto.\nintros ks1 (H1ks1, H2ks1).\napply (Hvs1 ks1); auto.\nrewrite <-(perm_length _ _ _ HH);\n  rewrite <-(perm_length _ _ _ H1ks1); auto.\nrewrite <-H2ks1; auto.\napply perm_in with ks; auto.\nQed.\n\nLemma uniq_free vs : free vs -> uniq vs.\nProof.\ninduction vs as [| a vs IH]; intros Hf.\napply uniq_nil.\napply uniq_cons; auto.\nintros HH; case (perm_in_inv _ _ _ HH).\nintros vs1 Hp1.\nassert (H1: free (a::a::vs1)).\napply free_perm with (a::vs); auto.\napply Aux.perm_skip; auto.\napply perm_sym; auto.\ncase (one_diff_zero _ sfP).\napply (H1 (1%f::(-(1))%f::(map (fun _ => 0%f) vs1))); simpl; auto.\nrewrite map_length; auto.\nrepeat rewrite mprod_S; rewrite mprod0.\nrewrite addE0r.\nrewrite <-scal_addEl; auto.\nrewrite  oppKr; auto.\nrewrite scalE0l; auto.\napply IH; apply free_cons with a; auto.\nQed.\n\nLemma free_incl vs1 vs2 : incl vs1 vs2 -> uniq vs1 -> free vs2 -> free vs1.\nProof.\nintros Hi Hu Hf.\ncase (perm_incl_inv _ vs1 vs2); auto.\napply uniq_free; auto.\nintros vs3 H3 ks Hlks Hpks x Hx.\nassert (H1: free (vs1 ++ vs3)).\napply free_perm with (1 := perm_sym _ _ _ H3); auto.\napply (H1 (ks ++ map (fun _ => 0%f) vs3)%list); auto with datatypes.\nrepeat rewrite app_length; rewrite map_length; auto.\nrewrite mprod_app; auto.\nrewrite Hpks; rewrite addE0l; auto.\nrewrite mprod0; auto.\nQed.\n\n(* Lemmas for cbl *)\n\n(* Linear combination  behaves well with inclusion *)\nLemma cbl_incl l1 l2 v : incl l1 l2 -> cbl l1 v -> cbl l2 v.\nProof.\nintros H1 H2.\ngeneralize H1; elim H2; clear H1 H2.\nintros; apply cbl0.\nintros; apply cbl_in; auto with datatypes.\nintros; apply cbl_add; auto.\nintros; apply cbl_scal; auto.\nQed.\n\nLemma cbl0_inv x : cbl nil x -> x = 0.\nProof. \nintros HH; elim HH; simpl; auto.\nintros v [].\nintros x1 y1 _ H1 _ H2; rewrite H1, H2; rewrite addE0l; auto.\nintros k x1 _ H1; rewrite H1, scalE0r; auto.\nQed.\n\n(* Multiple products are linear combinations *)\nLemma mprod_cbl l ks : cbl l (ks *X* l).\nProof.\ngeneralize ks; clear ks.\ninduction l as [| x l1 IH].\n  intros [| k ks]; unfold mprod; simpl; apply cbl0.\nintros [| k ks].\n  unfold mprod; simpl; apply cbl0.\nrewrite mprod_S; apply cbl_add.\napply cbl_scal; apply cbl_in; auto with datatypes.\napply cbl_incl with (2 := IH ks); auto with datatypes.\nQed.\n\n(* Multiple product of a sum *)\nLemma addE_mprod ks1 ks2 vs : length ks1 = length ks2 ->\n  map2 (fun k1 k2 => (k1 + k2)%f) ks1 ks2 *X* vs = ks1 *X* vs + ks2 *X* vs.\nProof.\ngeneralize ks2 vs; clear ks2 vs.\ninduction ks1 as [| k1 ks1 IH]; intros [| k2 ks2].\nintros; unfold mprod; simpl; rewrite addE0l; auto.\nintros vs H; discriminate H.\nintros vs H; discriminate H.\nsimpl length; intros [| v vs] Hl.\nunfold mprod; simpl; rewrite addE0l; auto.\nsimpl map2; repeat rewrite mprod_S.\nrewrite scal_addEl; auto; rewrite IH; auto.\nrepeat rewrite addE_assoc; auto.\n apply f_equal2 with (f := addE p); auto.\nrewrite addE_com; auto; repeat rewrite addE_assoc; auto; \n  apply f_equal2 with (f := addE p); auto.\nrewrite addE_com; auto.\nQed.\n\n(* Multiple production of a scalar product *)\nLemma scalE_mprod k ks vs : \n map (fun k1 => (k * k1)%f) ks *X* vs = k .* (ks *X* vs).\nProof.\ngeneralize vs; clear vs.\ninduction ks as [| k1 ks IH].\nintros; unfold mprod; simpl; rewrite scalE0r; auto.\nintros [| v vs].\nunfold mprod; simpl; rewrite scalE0r; auto.\nsimpl map; repeat rewrite mprod_S.\nrewrite scal_multE; auto; rewrite IH; auto.\nrewrite scal_addEr; auto.\nQed.\n\nLemma mprod_perm l1 l2 lk1: perm l1 l2 -> length lk1 = length l1 ->\n  exists lk2, perm lk1 lk2 /\\ lk1 *X* l1 = lk2 *X* l2.\nProof.\nintros HH; generalize lk1; elim HH; auto; clear l1 l2 lk1 HH.\nintros l1 lk1 _; exists lk1; split; auto; apply perm_id.\nintros a b l1 [| a1 [| b1 lk]] HH; try discriminate HH.\nexists (b1::a1::lk); split; auto.\napply perm_swap.\nrewrite !mprod_S, <-!addE_assoc, (addE_com Hp (a1 .* a)); auto.\nintros a l1 l2 Hp1 IH [|a1 lk1] Hlk1; try discriminate Hlk1.\ncase (IH lk1); auto.\nintros lk2 (H1lk2, H2lk2).\nexists (a1 :: lk2); repeat split; auto.\napply perm_skip; auto.\nrewrite !mprod_S, H2lk2; auto.\nintros l1 l2 l3 Hp1 IH1 Hp2 IH2 lk1 Hlk1.\ncase (IH1 _ Hlk1); intros lk2 (H1lk2, H2lk2).\ncase (IH2 lk2); auto.\nrewrite <-(perm_length _ _  _ H1lk2), Hlk1.\napply perm_length; auto.\nintros lk3 (H1lk3, H2lk3); exists lk3; split; auto.\napply perm_trans with (1 := H1lk2); auto.\nrewrite H2lk2; auto.\nQed.\n\n(* How to generate the multiple product for a constant *)\nFixpoint lgenk (n: nat) (k: K p) {struct n} : list (K p) :=\n  match n  with\n    O => nil\n  | 1 => k :: nil\n  | S n1 => k::lgenk n1 k\n  end.\n\n(* The length is ok *)\nLemma lgenk_length n k : length (lgenk n k) = n.\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; simpl; auto.\nintros k; generalize IH; case n; clear n IH; auto.\nintros n IH; pattern (S n) at 2; rewrite <- (IH k); auto.\nQed.\n\n(* 0 as a multiple product *)\nLemma genk0_mprod vs :  0 = lgenk (length vs) 0%f *X* vs.\nProof.\ninduction vs as [| v [| v' vs] IH]; auto;\n  simpl lgenk; rewrite mprod_S; rewrite IH; rewrite scalE0l; auto;\n  rewrite addE0l; auto.\nQed.\n\n(* A linear combination is a multiple product *)\nLemma cbl_mprod vs v : cbl vs v -> \n  exists ks, length ks = length vs /\\ v = ks *X* vs.\nProof.\nintros H; elim H.\nexists (lgenk (length vs) 0%f); rewrite lgenk_length; split; auto.\napply genk0_mprod.\nintros v2; clear H; induction vs as [| v' vs IH]; auto.\nintros HH; absurd (In v2 nil); auto with datatypes.\nsimpl In; intros [H1 | H1].\n  exists (1%f::lgenk (length vs) 0%f); split.\n  simpl; rewrite lgenk_length; auto.\n  rewrite mprod_S; rewrite scalE1; auto; rewrite <- genk0_mprod; \n  rewrite addE0r; auto.\n  case IH; auto; intros ks (Hks, Hks1); exists (0%f::ks); split.\n  simpl; auto.\n  rewrite mprod_S; rewrite scalE0l; auto; rewrite addE0l; auto.\nintros x y Hcx (ks1, (Hlks1, Hks1)) Hcy (ks2, (Hlks2, Hks2)).\nexists (map2 (fun k1 k2 => (k1 + k2)%f) ks1 ks2); split.\nrewrite map2_length; rewrite min_l; auto.\nrewrite Hlks1; rewrite Hlks2; auto with arith.\nrewrite addE_mprod; try rewrite Hks1; try rewrite Hks2; auto.\nrewrite Hlks1; auto.\nintros k x Hcx (ks, (Hlks, Hks)).\nexists (map (fun k1 => (k * k1)%f) ks); split.\n  rewrite map_length; auto.\nrewrite scalE_mprod; rewrite Hks; auto.\nQed.\n\nLemma scalE_add0 x : x + (- (1)) .* x = 0.\nProof.\npattern x at 1; rewrite <- (fun xx => scalE1 xx x); auto.\nrewrite <-scal_addEl; auto.\nrewrite oppKr; auto.\nrewrite scalE0l; auto.\nQed.\n\nLemma scalE_integral k x : k .* x = 0 -> {k = 0%f} + {x = 0}.\nProof.\nintros Hk.\ngeneralize (eqK_dec _ sfP k 0%f); case eqK; auto; intros Hk1.\nright.\nrewrite <-(scalE1 Hp x).\nsimpl; rewrite <-(invKr _ sfP _ Hk1).\nrewrite scal_multE; auto.\nrewrite Hk; rewrite scalE0r; auto.\nDefined.\n\nLemma scalE_opp k1 k2 x : k1 .* ((- (k2)) .* x) = (-k1).* (k2 .* x).\nProof.\nrewrite <- scal_multE,  <- opp_multKr, opp_multKl, scal_multE; auto.\nQed.\n\nLemma scalE_swap k1 k2 x : k1 .* (k2 .* x) = k2 .* (k1 .* x).\nProof.\nrepeat rewrite <- scal_multE; auto.\nrewrite multK_com; auto.\nQed.\n\nLemma addE_swap x1 x2 x3 : x1 + (x2 + x3) = x2 + (x1 + x3).\nProof.\nrewrite addE_com; auto; repeat rewrite addE_assoc; auto.\napply f_equal2 with (f := addE _); auto; rewrite addE_com; auto.\nQed.\n\nLemma cblnil x : cbl nil x -> x = 0.\nProof. \nintros H; elim H; auto; clear x H.\nintros v [].\nintros x y _ Hx _ Hy; rewrite Hx, Hy; rewrite addE0l; auto.\nintros k x _ Hx; rewrite Hx; rewrite scalE0r; auto.\nQed.\n\nLemma cbl1 x y : cbl (x::nil) y -> exists k, y = k .* x.\nProof.\nintros H; elim H; auto; clear y H.\nexists 0%f; rewrite scalE0l; auto.\nsimpl; intros v [[]|[]]; exists 1%f; rewrite scalE1; auto.\nintros x1 y _ (k1,Hk1) _ (k2,Hk2).\nexists (k1 + k2)%f; subst; rewrite scal_addEl; auto.\nintros k x1 _ (k1,Hk1); exists (k * k1)%f; rewrite Hk1, scal_multE; auto.\nQed.\n\nEnd VectorSpace.\n\nNotation \" x *X* y \" := (mprod _ x y) (at level 40, no associativity): vector_scope.\n\n\nSection Trans.\n\nVariable p p1 : eparams.\nHypothesis Hp: vparamsProp p.\nHypothesis Hp1: vparamsProp p1.\nVariable (f: p -> p1).\nVariable (g : stype p -> stype p1).\nVariable (g1 : stype p1 -> stype p).\nHypothesis Hf0: f 0%v = 0%v.\nHypothesis Hf1: forall x y : p, (f (x + y) = f x + f y)%v.\nHypothesis Hf2: forall (k: stype p) (x : p), (f (k .* x) = g k .* f x)%v.\nHypothesis Hg: forall k, g (g1 k) = k. \n\nLemma cbl_map l v : cbl _ l v -> cbl _ (map f l) (f v).\nProof.\nintros Hcb; elim Hcb; auto.\nrewrite Hf0; constructor.\nintros v1 Hv1; constructor; apply in_map; auto.\nintros; rewrite Hf1; apply cbl_add; auto.\nintros; rewrite Hf2; apply cbl_scal; auto.\nQed.\n\nLemma cbl_map_inv l v :\n cbl _ (map f l) v -> exists v1, cbl _ l v1 /\\ v = f v1.\nProof.\nassert (exists l1, l1 = map f l).\nexists (map f l); auto.\ncase H; intros l1 Hl1; rewrite <-Hl1; intros HH.\ngeneralize Hl1; elim HH; auto; clear HH Hl1.\nintros H1; exists 0%v; split; auto; constructor.\nintros v1 Hv1 H1; subst.\nrewrite in_map_iff in Hv1; case Hv1; intros v2 (H1v2, H2v2); subst.\nexists v2; split; auto; constructor; auto.\nintros c y H1 H2 H3 H4 H5.\ncase (H2 H5); intros v1 (H1v1, H2v1).\ncase (H4 H5); intros v2 (H1v2, H2v2); subst.\nexists (v1 + v2)%v; split; auto.\napply cbl_add; auto.\nintros k x H1 H2 H3.\ncase (H2 H3); intros v1 (H1v1, H2v1).\nexists ((g1 k).* v1)%v; split; subst; auto.\napply cbl_scal; auto.\nrewrite Hf2, Hg; auto.\nQed.\n\nEnd Trans.\n\nStructure params: Type := {\n dim:> nat;           (* the dimension of the space *)\n K:> fparams          (* the scalar type *)\n}.\n\nLtac Vrm0 := Krm0;\n  repeat (rewrite addE0l ||rewrite addE0r || rewrite scalE0l|| rewrite scalE0r); auto.\n\n\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/GeometricAlgebra/VectorSpace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6877630388795517}}
{"text": "Require Import Coq.Strings.Ascii.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Arith.PeanoNat.\n\nRequire Coq.Classes.RelationClasses.\nRequire Coq.Setoids.Setoid.\nRequire Coq.Relations.Relations.\n\n\nRequire Import Coq.micromega.Lia.\nImport ListNotations.\nRequire Import Turing.Lang.\nRequire Import Turing.Regex.\nRequire Import Turing.Util.\n\nSection Defs.\n  Inductive Regular: language -> Prop :=\n  | regular_def:\n    forall r l,\n    Equiv (Accept r) l ->\n    Regular l.\nEnd Defs.\n\nSection Props.\n  Lemma union_regular:\n    forall L1 L2,\n    Regular L1 ->\n    Regular L2 ->\n    Regular (Lang.Union L1 L2).\n  Proof.\n    intros.\n    inversion H; subst; clear H.\n    inversion H0; subst; clear H0.\n    apply regular_def with (r:=r_union r r0).\n    split; intros.\n    - inversion H0; subst; clear H0.\n      + apply union_in_l.\n        apply H1.\n        assumption.\n      + apply union_in_r.\n        apply H.\n        assumption.\n    - destruct H0.\n      + apply H1 in H0.\n        apply accept_union_l.\n        assumption.\n      + apply H in H0.\n        apply accept_union_r.\n        assumption.\n  Qed.\nEnd Props.\n\nSection Pumping.\n\n  Inductive Pump (L:language) (p:nat) (w:word) : Prop :=\n  | pump_def:\n    forall x y z,\n    w = x ++ y ++ z ->\n    y <> [] ->\n    length (x ++ y) <= p ->\n    (forall i, In (x ++ pow y i ++ z) L) ->\n    Pump L p w.\n\n  Lemma rex_pump_to_pump:\n    forall L r w,\n    Equiv (Accept r) L ->\n    RexPump r w ->\n    In w (Pump L (pumping_constant r)).\n  Proof.\n    intros.\n    inversion H0; subst; clear H0.\n    apply pump_def with (x:=x) (y:=y) (z:=z); auto.\n    intros.\n    apply H.\n    apply H4.\n  Qed.\n\n  Theorem pumping:\n    forall L,\n    Regular L ->\n    exists p, p >= 1 /\\\n    forall w, In w L ->\n    length w >= p ->\n    In w (Pump L p).\n  Proof.\n    intros.\n    inversion H; subst; clear H.\n    exists (pumping_constant r).\n    split. {\n      apply pumping_constant_ge_1.\n    }\n    intros.\n    assert (RexPump r w). {\n      apply rex_pumping.\n      + apply H0.\n        assumption.\n      + lia.\n    }\n    apply rex_pump_to_pump; auto.\n  Qed.\n\n  (** We say that a word [w] and size [p] clogs a language [L] when\n      no matter how we divide [w] into three parts, there is at least one pumped\n      string not in the language. *)\n  Definition Clogs (L:language) p w := \n    forall (x y z:word),\n      w = x ++ y ++ z ->\n      y <> [] ->\n      length (x ++ y) <= p ->\n      exists i,\n      ~ In (x ++ (pow y i) ++ z) L.\n\n  Lemma in_clogs:\n    forall w p L,\n    (forall x y z,\n    w = x ++ y ++ z ->\n    y <> [] ->\n    length (x ++ y) <= p ->\n    exists i, ~ In (x ++ (pow y i) ++ z) L) ->\n    In w (Clogs L p).\n  Proof.\n    intros.\n    unfold Clogs.\n    intros; auto.\n  Qed.\n\n  (**\n\n  A language is clogged if we can find one word in language [L] that clogs [L].\n\n   w \\in L    |w| >= p    w \\in Clogs L p\n   -----------------------------------\n            L clogged with p\n  *)\n  Inductive Clogged (L:language) p : Prop :=\n  | clogged_def:\n    forall w,\n    In w L ->\n    length w >= p ->\n    In w (Clogs L p) ->\n    Clogged L p.\n\n  (** Clogged languages are not regular.\n      We show that a language is not regular by clogging it for all p >= 1. *)\n  Lemma not_regular:\n    forall (L:language),\n    (forall p, p >= 1 -> Clogged L p) ->\n    ~ Regular L.\n  Proof.\n    (* H: For any p >= 1, L is clogged starting with p *)\n    intros.\n    (* Assume N: (L is regular) to reach a contradiction. *)\n    intros N.\n    (* Since L is regular, then we can apply the pumping lemma. *)\n    apply pumping in N.\n    destruct N as (p, (Hle, Hw)). (* there is a p which we can pump *)\n    (* We have that p >= 1, so L is clogged on p *)\n    assert (H := H _ Hle).\n    (* We cannot use Hw, so we are only left with H:Clogged L p,\n       let us open it. *)\n    (* We now know that there is a string `w` in `L` that clogs `L`. *)\n    inversion H as (w, Hin, Hlen, Hc); subst; clear H.\n    (* Let us use string `w` in the pumping of L *)\n    assert (Hw := Hw w Hin Hlen).\n    (* If w is in the pumping of L, then we can pump it for any i *)\n    inversion Hw as (x, y, z, ?, ?, ?, Ha); subst; clear Hw.\n    (* But we recall that w is clogged (H2), so there is some i that is not in L *)\n    assert (Hi: exists i, ~ In (x ++ (pow y i) ++ z) L). {\n      apply Hc.\n      - reflexivity.\n      - assumption.\n      - assumption.\n    }\n    destruct Hi as (i, Hi).\n    contradict Hi.\n    apply Ha.\n  Qed.\n\n  Lemma not_regular_ex:\n    forall (L:language),\n    (forall p, p >= 1 ->\n      exists w,\n      (\n        In w L /\\\n        length w >= p /\\ (\n          forall x y z,\n          (w = x ++ y ++ z ->\n           y <> [] ->\n           length (x ++ y) <= p ->\n           exists i,  ~ In (x ++ pow y i ++ z) L\n           )))) ->\n    ~ Regular L.\n  Proof.\n    intros.\n    apply not_regular.\n    intros.\n    destruct (H _ H0) as (w, (Ha, (Hb, Hc))); clear H.\n    apply clogged_def with (w:=w); auto.\n  Qed.\n\n  Lemma equiv_clogs_impl:\n    forall n L1 L2,\n    Equiv L1 L2 ->\n    Equiv (Clogs L1 n) (Clogs L2 n).\n  Proof.\n    intros.\n    unfold Clogs; split; unfold In; intros; subst.\n    - assert (H0 := H0 x y z eq_refl H2 H3).\n      destruct H0 as (i, Hx).\n      exists i.\n      intros N.\n      contradict Hx.\n      apply H.\n      assumption.\n    - assert (H0 := H0 x y z eq_refl H2 H3).\n      destruct H0 as (i, Hx).\n      exists i.\n      intros N.\n      contradict Hx.\n      apply H.\n      assumption.\n  Qed.\n\n  Lemma equiv_clogged:\n    forall L1 L2 p,\n    Equiv L1 L2 ->\n    Clogged L1 p ->\n    Clogged L2 p.\n  Proof.\n    intros.\n    inversion H0; subst; clear H0.\n    apply clogged_def with (w:=w).\n    - apply H.\n      assumption.\n    - assumption.\n    - apply equiv_clogs_impl with (n:=p) in H.\n      rewrite <- H.\n      assumption.\n  Qed.\n\n  Import Morphisms.\n  Global Instance rw_equiv_proper: Proper (Equiv ==> eq ==> iff) Clogged.\n  Proof.\n    unfold Proper.\n    unfold respectful.\n    intros.\n    subst.\n    split; intros.\n    - eapply equiv_clogged; eauto.\n    - eapply equiv_clogged; eauto.\n      symmetry.\n      assumption.\n  Qed.\n\nEnd Pumping.\n\nModule Examples.\n  Import RegexNotations.\n  Import LangNotations.\n  Import Lang.\n  Import Setoid.\n\n  Open Scope lang_scope.\n\n  (** Ends with \"a\" *)\n\n  Lemma l1_is_reg:\n    Regular Examples.L1.\n  Proof.\n    apply regular_def with (r:= r_star r_any ;; \"a\").\n    unfold Examples.L1.\n    rewrite r_app_rw.\n    rewrite r_char_rw.\n    rewrite r_star_rw.\n    rewrite r_any_rw.\n    rewrite star_any_rw.\n    reflexivity.\n    (* Direct proof: *)\n    (*\n    apply app_spec.\n    unfold Equiv; split; unfold Examples.L1; intros.\n    - inversion H; subst; clear H.\n      exists s1.\n      inversion H3; subst; clear H3.\n      reflexivity.\n    - destruct H as (w, Hs).\n      subst.\n      apply accept_app with (s1:=w) (s2:=[\"a\"]); auto.\n      + apply accept_any_star.\n      + auto using accept_char.\n      *)\n  Qed.\n\n  (** Any string of length 2 *)\n\n  Lemma l2_is_reg:\n    Regular Examples.L2.\n  Proof.\n    apply regular_def with (r:= r_any ;; r_any).\n    unfold Equiv, Examples.L2; split; intros.\n    - inversion H; subst.\n      apply accept_any_inv in H2.\n      apply accept_any_inv in H3.\n      destruct H2 as (c1, ?).\n      destruct H3 as (c2, ?).\n      subst.\n      reflexivity.\n    - destruct w. {\n        inversion H.\n      }\n      inversion H; subst; clear H.\n      destruct w. {\n        inversion H1.\n      }\n      inversion H1; subst; clear H1.\n      destruct w. {\n        simpl.\n        apply accept_any_cons.\n        apply accept_any.\n      }\n      inversion H0.\n  Qed.\n\n  (** Any string that starts with \"a\" and ends with \"b\". *)\n  Lemma l3_is_reg:\n    Regular Examples.L3.\n  Proof.\n    unfold Examples.L3.\n    apply regular_def with (r:=\"a\" ;; r_star r_any ;; \"b\").\n    repeat rewrite r_app_rw.\n    rewrite r_star_rw.\n    rewrite r_any_rw.\n    repeat rewrite r_char_rw.\n    rewrite star_any_rw.\n    reflexivity.\n  Qed.\n\n  Lemma l1_l3:\n    Regular (Lang.Union Examples.L1 Examples.L3).\n  Proof.\n    apply union_regular.\n    - apply l1_is_reg.\n    - apply l3_is_reg.\n  Qed.\n\n  (** Irregular language *)\n\n  Lemma xyz_rw:\n    forall (a:ascii) b p x y z,\n    (\n      length (x ++ y) <= p ->\n      pow1 a p ++ pow1 b p = x ++ y ++ z ->\n      exists n,\n      (length (x ++ y) + n) % nat = p /\\\n      pow1 a (length x + (length y + n)) ++ pow1 b (length x + length y + n) = x ++ y ++ z\n    ) % list.\n  Proof.\n    intros.\n    apply le_to_plus in H.\n    destruct H as (n, Hlen).\n    exists n.\n    split; auto.\n    rewrite <- Hlen in H0.\n    rewrite app_length in H0.\n    rewrite Nat.add_assoc.\n    assumption.\n  Qed.\n\n  Lemma pow1_plus_xy:\n    forall (a:ascii) z x n y,\n    pow1 a (length x + n) ++ z = x ++ y ->\n    x = pow1 a (length x) /\\ y = pow1 a n ++ z.\n  Proof.\n    induction x; intros.\n    - simpl in *.\n      rewrite H.\n      auto.\n    - simpl in *.\n      inversion H; subst; clear H.\n      apply IHx in H2.\n      destruct H2.\n      split; auto.\n      rewrite <- H.\n      reflexivity.\n  Qed.\n\n  Lemma l4_not_regular:\n    ~ Regular Turing.Lang.Examples.L4.\n  Proof.\n    apply not_regular.\n    (* Adversary picks `p` *)\n    intros.\n    rewrite Turing.Lang.Examples.l4_spec.\n    (* We pick our word: *)\n    apply clogged_def with (w:=(pow1 \"a\" p ++ pow1 \"b\" p) % list).\n    - unfold In.\n      exists p.\n      reflexivity.\n    - Search (length (_ ++ _)).\n      rewrite app_length.\n      Search (length (pow1 _ _)).\n      rewrite pow1_length.\n      lia.\n    - (* Finally, we show that our string clogs the language *)\n      Search (In _ (Clogs _ _)).\n      apply in_clogs.\n      (* Adversary gives x y z *)\n      intros x y z Ha Hneq Hlen.\n      (* We pick the number of pumps that breaks: *)\n      exists 2.\n      (* Open up the definition of In *)\n      unfold In.\n      (* We have that there is a word in L4 and we will reach a contradiction *)\n      intros N.\n      (* Break down some n *)\n      destruct N as (n, N).\n      (* We don't want pow in N, so we compute function pow with simpl: *)\n      simpl in N.\n      (* We remove the ++ [] *)\n      Search (_ ++ []).\n      rewrite app_nil_r in N.\n      (* We start working on our assumption H0, this is the first step of the slides:\n         There is some b such that lenght (x ++ y) + b = p *)\n      apply xyz_rw in Ha; auto.\n      destruct Ha as (b, (_, Hb)).\n      (* We now separate x, y, and z in Hb *)\n      apply pow1_plus_xy in Hb.\n      destruct Hb as (Hx, Hyz).\n      symmetry in Hyz.\n      apply pow1_plus_xy in Hyz.\n      destruct Hyz as (Hy, Hz).\n      (* We now know what x, y, and z are.\n         We are ready to rewrite them in N. *) \n      rewrite Hy in N.\n      rewrite Hx in N.\n      rewrite Hz in N.\n      (* Next, we want to simplify all of our powers of a into a single base at the\n         RHS of the equality in N, so that we get a^x b^y = a^v b^w *)\n      (* First we normalize ++ *) \n      repeat rewrite app_assoc in *.\n      (* Then, we eagerly join the terms with the same base *) \n      repeat rewrite pow1_plus in N.\n      assert (\"a\" <> \"b\") by (intros M; inversion M).\n      apply pow1_a_b_inv_eq in N; auto.\n      destruct N as (L, R).\n      subst.\n      repeat rewrite <- Nat.add_assoc in *.\n      apply plus_inv_eq_r in R.\n      apply plus_inv_eq_r in R.\n      (* We now have to show that |y| + b = b *)\n      apply plus_inv_zero_l in R.\n      (* But we know that |y| >= 1, so we reach a contradiction *)\n      destruct y. {\n        contradiction.\n      }\n      inversion R.\n  Qed.\n\n  Lemma xyz_rw_ex:\n    forall (a:ascii) p x y z w,\n    length (x ++ y) <= p ->\n    pow1 a p ++ w = x ++ y ++ z ->\n    exists n,\n    p = length (x ++ y) + n /\\\n    length w + n = length z /\\\n    x = pow1 a (length x) /\\\n    y = pow1 a (length y) /\\\n    z = pow1 a n ++ w.\n  Proof.\n    intros.\n    apply le_to_plus in H.\n    destruct H as (n, Hlen).\n    exists n.\n    split; auto.\n    rewrite <- Hlen in H0.\n    rewrite app_length in H0.\n    rewrite <- Nat.add_assoc in *.\n    apply pow1_plus_xy in H0.\n    destruct H0 as (Ha, Hb).\n    symmetry in Hb.\n    apply pow1_plus_xy in Hb.\n    destruct Hb as (Hb, Hc).\n    repeat split; auto.\n    subst.\n    rewrite app_length.\n    rewrite pow1_length.\n    auto with *.\n  Qed.\n\n  Lemma l4_not_regular_v2:\n    ~ Regular Turing.Lang.Examples.L4.\n  Proof.\n    apply not_regular_ex.\n    (* Adversary: picks p >= 1 *)\n    intros p Hge.\n    (* We pick a string *)\n    exists (pow1 \"a\" p ++ pow1 \"b\" p) % list.\n    repeat split.\n    - unfold Examples.L4, In.\n      exists p.\n      apply app_in_eq.\n      + apply pow_char_in.\n      + apply pow_char_in.\n    - Search (length (_ ++ _)).\n      rewrite app_length.\n      Search (length (pow1 _ _)).\n      rewrite pow1_length.\n      lia.\n    - (* Adversary picks x y z *)\n      intros x y z Ha Hneq Hlen.\n      (* We pick 2 *)\n      exists 2.\n      intros N.\n      (* Break down some n *)\n      destruct N as (n, N).\n      (* We don't want pow in N, so we compute function pow with simpl: *)\n      simpl in N.\n      (* We remove the ++ [] *)\n      Search (_ ++ []).\n      rewrite app_nil_r in N.\n      (* We start working on our assumption H0, this is the first step of the slides:\n         There is some b such that lenght (x ++ y) + b = p *)\n      apply xyz_rw_ex in Ha; auto.\n      destruct Ha as (b, (Hz, (_,(Hb,(Hc,Hd))))).\n\n      (* We note that we can simplify away p *)\n      rewrite Hz in Hd; clear Hz.\n\n      (* Similarly, we simplify x, y, and z in N. *) \n      rewrite Hb in N; clear Hb.\n      rewrite Hc in N; clear Hc.\n      rewrite Hd in N; clear Hd.\n\n      (* Next, we want to simplify all of our powers of a into a single base at the\n         RHS of the equality in N, so that we get a^x b^y = a^v b^w *)\n      (* Normalize app (++) *) \n      repeat rewrite app_assoc in *.\n      (* Then, we eagerly join the terms with the same base *) \n      repeat rewrite pow1_plus in N.\n      assert (\"a\" <> \"b\") by (intros M; inversion M).\n      Search (In _ (_ >> _)).\n      apply pow_pow_in_inv in N.\n      apply pow1_a_b_inv_eq in N; auto.\n      destruct N as (L, R).\n      subst.\n      rewrite app_length in *.\n      (* Normalize addition, like we did with app *)\n      repeat rewrite <- Nat.add_assoc in *.\n      (* We now have to show that |y| + b = b *)\n      apply plus_inv_eq_r in R.\n      apply plus_inv_eq_r in R.\n      (* Thus, |y| = 0 *)\n      assert (X: length y = 0). { lia. }\n      (* However, from y <> [], we have that |y| > 0*)\n      destruct y. { contradiction. }\n      inversion X.\n  Qed.\n\n  Lemma l4_not_regular_v3:\n    ~ Regular Turing.Lang.Examples.L4.\n  Proof.\n    apply not_regular.\n    intros.\n    rewrite Turing.Lang.Examples.l4_spec.\n    (* We pick our word: *)\n    apply clogged_def with (w:=(pow1 \"a\" p ++ pow1 \"b\" p) % list).\n    - unfold In.\n      exists p.\n      reflexivity.\n    - Search (length (_ ++ _)).\n      rewrite app_length.\n      Search (length (pow1 _ _)).\n      rewrite pow1_length.\n      lia.\n    - unfold In.\n      unfold Clogs.\n      intros.\n      (* Goal 3: *)\n      exists 2.\n      (* Open up the definition of In *)\n      unfold In.\n      (* We have that there is a word in L4 and we will reach a contradiction *)\n      intros N.\n      (* Break down some n *)\n      destruct N as (n, N).\n      (* We don't want pow in N, so we compute function pow with simpl: *)\n      simpl in N.\n      (* We remove the ++ [] *)\n      Search (_ ++ []).\n      rewrite app_nil_r in N.\n      (* We start working on our assumption H0, this is the first step of the slides:\n         There is some b such that lenght (x ++ y) + b = p *)\n      apply xyz_rw_ex in H0; auto.\n      destruct H0 as (b, (Hz, (_,(Hb,(Hc,Hd))))).\n      (* We already used H2 for xyz_rw, we can safely remove it. *)\n      clear H2.\n\n      (* We note that we can simplify away p *)\n      rewrite Hz in Hd; clear Hz.\n\n      (* Similarly, we simplify x, y, and z in N. *) \n      rewrite Hb in N; clear Hb.\n      rewrite Hc in N; clear Hc.\n      rewrite Hd in N; clear Hd.\n\n      (* Next, we want to simplify all of our powers of a into a single base at the\n         RHS of the equality in N, so that we get a^x b^y = a^v b^w *)\n      (* Normalize app (++) *) \n      repeat rewrite app_assoc in *.\n      (* Then, we eagerly join the terms with the same base *) \n      repeat rewrite pow1_plus in N.\n      assert (\"a\" <> \"b\") by (intros M; inversion M).\n      apply pow1_a_b_inv_eq in N; auto.\n      destruct N as (L, R).\n      subst.\n      rewrite app_length in *.\n      (* Normalize addition, like we did with app *)\n      repeat rewrite <- Nat.add_assoc in *.\n      (* We now have to show that |y| + b = b *)\n      apply plus_inv_eq_r in R.\n      apply plus_inv_eq_r in R.\n      apply plus_inv_zero_l in R.\n      (* But we know that |y| >= 1, so we reach a contradiction *)\n      destruct y. {\n        contradiction.\n      }\n      inversion R.\n  Qed.\nEnd Examples.\n", "meta": {"author": "yforster", "repo": "cs420-library", "sha": "6e7725535c50efd4da4c253de5933cc6e8974390", "save_path": "github-repos/coq/yforster-cs420-library", "path": "github-repos/coq/yforster-cs420-library/cs420-library-6e7725535c50efd4da4c253de5933cc6e8974390/src/Regular.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.6877630333159611}}
{"text": "Require Export P06.\n\n(* Write a relation [bevalR] in the same style as\n   [aevalR], and prove that it is equivalent to [beval]. *)\n\n(* Don't use aeval and beval when define bevalR (only use aevalR). *)\n\nInductive bevalR: bexp -> bool -> Prop :=\n  (* FILL_IN_HERE *)\n.\n\n(** If your definition can't proof these examples using \"do 20 try econstructor\", **)\n(** comment out and write your proofs in following area. **)\n\n(*\nExample my_bevalR1: bevalR (BNot BTrue) false.\nProof. do 20 try econstructor. Qed.\nExample my_bevalR2: bevalR (BEq (APlus (ANum 2) (ANum 1)) (ANum 3)) true.\nProof. do 20 try econstructor. Qed.\nExample my_bevalR3: bevalR (BAnd (BLe (AMult (ANum 3) (ANum 1))\n                                        (AMinus (ANum 1) (ANum 3)))\n                                   BTrue) false.\nProof. do 20 try econstructor. Qed.\n*)\n\n\nCheck aeval_iff_aevalR.\n\nLemma beval_iff_bevalR : forall b bv,\n  bevalR b bv <-> beval b = bv.\nProof.\n  exact FILL_IN_HERE.\nQed.\n", "meta": {"author": "snu-sf-class", "repo": "sf202002", "sha": "dcc8ab303e7bcccebff51ef00929c91a26e45c4f", "save_path": "github-repos/coq/snu-sf-class-sf202002", "path": "github-repos/coq/snu-sf-class-sf202002/sf202002-dcc8ab303e7bcccebff51ef00929c91a26e45c4f/3-IndProp_Imp/P07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.6876684169761141}}
{"text": "(* Produce canonical lists using merge sort and deduplication. *)\n\nRequire Import Permutation.\nFrom larith Require Import A_setup B1_utils.\n\nNotation Sorted leb := (RTC (λ x y, leb x y = true)).\nNotation Increasing leb := (RTC (λ x y, leb y x = false)).\n\n(*\nThe primary goal of this file is to supply an efficient algorithm to normalize\nlists of states in the powerset automaton construction. For the correctness of\nthe depth-first search, a list containing all states must exist. To realize this\nwe will represent states as strictly increasing lists.\n*)\nSection Canonical_lists.\n\nVariable X : Type.\nVariable leb : X -> X -> bool.\n\nNotation Sorted := (Sorted leb).\nNotation Increasing := (Increasing leb).\n\nNotation \"x <= y\" := (leb x y = true) (at level 70).\nNotation \"x > y\" := (leb x y = false) (at level 70).\n\n(* Proving `Sorted (mergesort l)` only requires totality. *)\nHypothesis leb_total : ∀x y, x <= y \\/ y <= x.\n\n(* Proving `Increasing (dedup l)` only requires anti-symmetry. *)\nHypothesis leb_asym : ∀x y, x <= y /\\ y <= x <-> x = y.\n\n(* Proving uniqueness of increasing lists uses the above + transitivity. *)\nHypothesis leb_trans : ∀x y z, x <= y -> y <= z -> x <= z.\n\n(* These three hypotheses represent a linear order. *)\nDefinition Linear_order :=\n  (∀x y, x <= y /\\ y <= x <-> x = y) /\\\n  (∀x y z, x <= y -> y <= z -> x <= z) /\\\n  (∀x y, x <= y \\/ y <= x).\n\nLocal Lemma gt_leb x y :\n  x > y -> y <= x.\nProof.\ndestruct (leb_total y x); [easy|congruence].\nQed.\n\nLocal Lemma leb_refl x :\n  x <= x.\nProof.\napply leb_asym; easy.\nQed.\n\n(******************************************************************************)\n(* I. A merge sort algorithm.                                                 *)\n(******************************************************************************)\n(* Initial author: Hugo Herbelin, Oct 2009                                    *)\n(* This section only relies on the leb_total hypothesis.                      *)\n(******************************************************************************)\nSection Mergesort.\n\nNotation Sorted_stack stack := (Forall Sorted (strip stack)).\nNotation flatten stack := (concat (strip stack)).\n\nFixpoint merge l1 l2 :=\n  let fix merge_aux l2 :=\n  match l1, l2 with\n  | [], _ => l2\n  | _, [] => l1\n  | x1 :: l1', x2 :: l2' =>\n    if leb x1 x2\n    then x1 :: merge l1' l2\n    else x2 :: merge_aux l2'\n  end\n  in merge_aux l2.\n\nFixpoint merge_push stack l :=\n  match stack with\n  | [] => [Some l]\n  | None :: stack' => Some l :: stack'\n  | Some l' :: stack' => None :: merge_push stack' (merge l' l)\n  end.\n\nFixpoint merge_all stack :=\n  match stack with\n  | [] => []\n  | None :: stack' => merge_all stack'\n  | Some l :: stack' => merge l (merge_all stack')\n  end.\n\nFixpoint merge_iter stack l :=\n  match l with\n  | [] => merge_all stack\n  | x :: l' => merge_iter (merge_push stack [x]) l'\n  end.\n\nDefinition mergesort := merge_iter [].\n\nSection Sorted.\n\nTheorem Sorted_merge l1 l2 :\n  Sorted l1 -> Sorted l2 -> Sorted (merge l1 l2).\nProof.\nrevert l2; induction l1; induction l2; intros; simpl; auto.\ndestruct (leb a a0) eqn:Heq1.\n- inv H. simpl; apply RTC_cons; easy.\n  assert(IH := IHl1 _ H3 H0); simpl; simpl in IH.\n  destruct (leb y a0); apply RTC_cons; easy.\n- apply gt_leb in Heq1.\n  inv H0. apply RTC_cons; easy.\n  assert(IH := IHl2 H H3); simpl; simpl in IH.\n  destruct (leb a y); apply RTC_cons; easy.\nQed.\n\nTheorem Sorted_stack_merge_push stack l :\n  Sorted_stack stack -> Sorted l -> Sorted_stack (merge_push stack l).\nProof.\nrevert l; induction stack as [|[|]]; intros; simpl.\n1,3: constructor; easy. inv H. apply IHstack. easy.\napply Sorted_merge; easy.\nQed.\n\nTheorem Sorted_stack_merge_all stack :\n  Sorted_stack stack -> Sorted (merge_all stack).\nProof.\ninduction stack as [|[|]]; simpl; intros. constructor.\ninv H; apply Sorted_merge. all: auto.\nQed.\n\nTheorem Sorted_merge_iter stack l :\n  Sorted_stack stack -> Sorted (merge_iter stack l).\nProof.\nrevert stack; induction l; simpl; intros.\napply Sorted_stack_merge_all, H.\napply IHl, Sorted_stack_merge_push. easy. constructor.\nQed.\n\nTheorem Sorted_mergesort l :\n  Sorted (mergesort l).\nProof.\napply Sorted_merge_iter; constructor.\nQed.\n\nEnd Sorted.\n\nSection Permutation.\n\nTheorem Permutation_merge l1 l2 :\n  Permutation (l1 ++ l2) (merge l1 l2).\nProof.\nrevert l2; induction l1; simpl merge; intros.\n- destruct l2; apply Permutation_refl.\n- induction l2. rewrite app_nil_r; apply Permutation_refl.\n  destruct (leb a a0). apply perm_skip, IHl1.\n  apply Permutation_sym, Permutation_cons_app, Permutation_sym, IHl2.\nQed.\n\nTheorem Permutation_merge_push stack l :\n  Permutation (l ++ flatten stack) (flatten (merge_push stack l)).\nProof.\nrevert l; induction stack as [|[]]; simpl; intros.\n- reflexivity.\n- rewrite app_assoc; etransitivity.\n  apply Permutation_app_tail; etransitivity.\n  apply Permutation_app_comm. apply Permutation_merge. apply IHstack.\n- reflexivity.\nQed.\n\nTheorem Permutation_merge_all stack :\n  Permutation (flatten stack) (merge_all stack).\nProof.\ninduction stack as [|[]]; simpl. easy.\ntransitivity (l ++ merge_all stack).\napply Permutation_app_head, IHstack.\napply Permutation_merge. apply IHstack.\nQed.\n\nTheorem Permutation_merge_iter l stack :\n  Permutation (flatten stack ++ l) (merge_iter stack l).\nProof.\nrevert stack; induction l; simpl; intros.\nrewrite app_nil_r; apply Permutation_merge_all.\nrewrite cons_app, app_assoc; etransitivity.\napply Permutation_app_tail; etransitivity.\napply Permutation_app_comm.\napply Permutation_merge_push.\napply IHl.\nQed.\n\nTheorem Permutation_mergesort l :\n  Permutation l (mergesort l).\nProof.\napply (Permutation_merge_iter l []).\nQed.\n\nEnd Permutation.\n\nEnd Mergesort.\n\n(******************************************************************************)\n(* II. Deduplication of sorted lists.                                         *)\n(******************************************************************************)\n(* This section only relies on the leb_asym hypothesis.                       *)\n(******************************************************************************)\nSection Deduplication.\n\nFixpoint dedup l :=\n  match l with\n  | [] => []\n  | x :: l' =>\n    match l' with\n    | []     => [x]\n    | y :: _ => if leb y x then dedup l' else x :: dedup l'\n    end\n  end.\n\nTheorem dedup_eqv l x :\n  Sorted l -> In x (dedup l) <-> In x l.\nProof.\nintros; induction l; simpl.\neasy. destruct l. easy. inv H.\napply IHl in H2; destruct (leb x0 a) eqn:Ha.\n- assert(a = x0) by (apply leb_asym; easy); subst.\n  etransitivity. apply H2. simpl; intuition.\n- symmetry; transitivity (a = x \\/ In x (dedup (x0 :: l))).\n  rewrite H2; reflexivity. easy.\nQed.\n\nLemma Increasing_cons_dedup x y l :\n  Sorted (y :: l) -> y > x -> Increasing (x :: dedup (y :: l)).\nProof.\nrevert x y; induction l; intros. repeat constructor; easy.\nreplace (dedup _) with (if leb a y then dedup (a::l) else y :: dedup (a::l))\nby easy; inv H; destruct (leb a y) eqn:Ha.\n- apply IHl. easy. assert(a = y) by (now apply leb_asym); subst; easy.\n- constructor. apply IHl. all: easy.\nQed.\n\nTheorem Increasing_dedup l :\n  Sorted l -> Increasing (dedup l).\nProof.\ninduction l; simpl; intros. constructor.\ninv H. constructor. destruct (leb y a) eqn:Hy.\nauto. apply Increasing_cons_dedup; easy.\nQed.\n\nTheorem length_dedup l :\n  (length (dedup l) <= length l)%nat.\nProof.\ninduction l. easy. destruct l. easy.\nreplace (dedup _) with (if leb x a then dedup (x::l) else a :: dedup (x::l))\nby easy; destruct (leb _). apply le_S, IHl. apply le_n_S, IHl.\nQed.\n\nEnd Deduplication.\n\n(******************************************************************************)\n(* III. Uniqueness of increasing lists.                                       *)\n(******************************************************************************)\nSection Uniqueness.\n\nLemma Increasing_le x y l :\n  Increasing (y :: l) -> x <= y -> ¬In x l.\nProof.\nrevert y; induction l; simpl; intros. easy.\ninv H; intros []. subst; congruence.\napply IHl with (y:=a); try easy.\napply leb_trans with (y:=y). easy. apply gt_leb, H5.\nQed.\n\nCorollary Increasing_tl x l :\n  Increasing (x :: l) -> ¬In x l.\nProof.\nintros; apply Increasing_le with (y:=x).\napply H. apply leb_refl.\nQed.\n\nCorollary Increasing_lt x y l :\n  Increasing (y :: l) -> y > x -> ¬In x (y :: l).\nProof.\nintros Hy Hx [F|F].\nsubst; rewrite leb_refl in Hx; easy.\napply Increasing_le with (y:=y) in F.\neasy. easy. apply gt_leb, Hx.\nQed.\n\nTheorem Increasing_unique l1 l2 :\n  (∀x, In x l1 <-> In x l2) ->\n  Increasing l1 -> Increasing l2 ->\n  l1 = l2.\nProof.\nrevert l2; induction l1; destruct l2; intros. easy.\n1,2: exfalso; eapply in_nil, H, in_eq. assert(a = x). \n- apply leb_asym; split.\n  + destruct (leb a x) eqn:F; [easy|exfalso].\n    eapply Increasing_lt; [apply H0|apply F|apply H, in_eq].\n  + destruct (leb x a) eqn:F; [easy|exfalso].\n    eapply Increasing_lt; [apply H1|apply F|apply H, in_eq].  \n- subst; apply wd, IHl1. apply Increasing_tl in H0, H1.\n  intros y; split; intros Y; eapply in_cons in Y as Z; apply H in Z; inv Z.\n  all: eapply RTC_weaken. apply H0. apply H1.\nQed.\n\nEnd Uniqueness.\n\n(******************************************************************************)\n(* IV. The normalization function.                                            *)\n(******************************************************************************)\nSection Normalization.\n\nDefinition normalize l := dedup (mergesort l).\n\nTheorem Increasing_normalize l :\n  Increasing (normalize l).\nProof.\napply Increasing_dedup, Sorted_mergesort.\nQed.\n\nTheorem normalize_eqv l x :\n  In x (normalize l) <-> In x l.\nProof.\netransitivity. apply dedup_eqv, Sorted_mergesort.\nsplit; apply Permutation_in. apply Permutation_sym.\nall: apply Permutation_mergesort.\nQed.\n\nTheorem normalize_fixed_point l :\n  Increasing l -> normalize l = l.\nProof.\nintros; apply Increasing_unique. apply normalize_eqv.\napply Increasing_normalize. apply H.\nQed.\n\nEnd Normalization.\n\n(******************************************************************************)\n(* V. Exhausting all increasing sequences over a finite domain.               *)\n(******************************************************************************)\nSection Powerset.\n\nNotation Below x := (Forall (λ y, leb y x = false)).\n\nFixpoint powerset (dom : list X) :=\n  match dom with\n  | [] => [[]]\n  | a :: dom' => let p := powerset dom' in p ++ map (cons a) p\n  end.\n\nTheorem Increasing_Below x l :\n  Increasing (x :: l) -> Below x l.\nProof.\nintros; apply Forall_forall; intros.\ndestruct (leb x0 x) eqn:Hx; [|easy].\napply Increasing_le with (l:=l) in Hx; easy.\nQed.\n\nTheorem Below_Increasing x l :\n  Increasing l -> Below x l -> Increasing (x :: l).\nProof.\ndestruct l; intros; constructor.\neasy. inv H0.\nQed.\n\nLocal Lemma X_dec (x y : X) :\n  {x = y} + {x ≠ y}.\nProof.\ndestruct (leb x y) eqn:Hx, (leb y x) eqn:Hy. left; apply leb_asym; easy.\nall: right; intros F; apply leb_asym in F; rewrite Hx, Hy in F; easy.\nQed.\n\nLocal Lemma Increasing_remove x l :\n  Increasing l -> Increasing (remove X_dec x l).\nProof.\ninduction l; simpl; intros. constructor.\napply RTC_weaken in H as Hl; apply IHl in Hl.\ndestruct (X_dec x a); [easy|].\napply Below_Increasing; [easy|].\napply Forall_incl with (l':=l); intros.\napply in_remove in H0; easy. apply Increasing_Below, H.\nQed.\n\nTheorem Increasing_In_powerset dom l :\n  (∀x, In x l -> In x dom) ->\n  Increasing dom -> Increasing l ->\n  In l (powerset dom).\nProof.\nrevert l; induction dom as [|e dom']; simpl; intros.\ndestruct l; [now left|right]; eapply H, in_eq.\nassert(He := Increasing_remove e _ H1).\nassert(In (remove X_dec e l) (powerset dom')). {\n  apply IHdom'. intros x Hx; apply in_remove in Hx as [].\n  apply H in H2 as []; [congruence|easy].\n  eapply RTC_weaken, H0. easy. }\napply in_app_iff; destruct (in_dec X_dec e l).\n2: left; rewrite notin_remove in H2; easy. right.\napply in_map_iff; exists (remove X_dec e l); split; [|easy].\napply Increasing_unique; try easy.\n- split. intros []. subst; easy. apply in_remove in H3; easy.\n  intros; destruct (X_dec x e). subst; apply in_eq.\n  apply in_cons, in_in_remove; easy.\n- apply Below_Increasing.\n  apply Increasing_remove, H1.\n  apply Forall_incl with (l':=dom'); intros.\n  apply in_remove in H3 as [].\n  apply H in H3 as []; [congruence|easy].\n  apply Increasing_Below, H0.\nQed.\n\nEnd Powerset.\n\nEnd Canonical_lists.\n\nArguments Linear_order {_}.\nArguments mergesort {_}.\nArguments dedup {_}.\nArguments normalize {_}.\nArguments powerset {_}.\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/C1_norm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.6876684142589566}}
{"text": "Require Export List.\nRequire Export Induction.\n\nInductive list (X: Type): Type :=\n| nil: list X\n| cons: X -> list X -> list X.\n\nCheck nil.\nCheck cons.\n\n\n\nCheck nil.\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\nFixpoint repeat (X: Type) (x: X) (count: nat): list X :=\n    match count with\n    | 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  Inductive mumble: Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\n\n  Inductive grumble (X: Type) : Type :=\n  | d : mumble -> grumble X\n  | e : X -> grumble X.\n\n  Compute (d mumble (b a 5)).\n  Compute d bool (b a 5).\n  Compute d nat (b a 5).\n\nEnd MumbleGrumble.\n\nFixpoint repeat' X x count: list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\nCheck 1.\n\nTheorem repeat_same: forall (X: Type) (x: X) (count: nat),\n    repeat X x count = repeat X x count.\nProof.\n  intros X x count.\n  reflexivity.\nQed.\n\nFixpoint repeat'' X x count: list X :=\n  match count with\n  | 0 => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\nDefinition p_zl: forall (n: nat), 0 + n = n.\nProof.\n  intros n.\n  reflexivity.\nQed.\n\nDefinition p_zr: forall (n: nat), n + 0 = n.\nProof.\n  intros n.\n  induction n as [|k IH].\n  - reflexivity.\n  - simpl.\n    rewrite -> IH.\n    reflexivity.\nQed.\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\nFixpoint repeat''' {X: Type} (x: X) (count: nat) : list X :=\n  match count with\n  | 0 => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\nInductive list' {X: Type} : Type :=\n| nil' : list'\n| cons' : X -> list' -> list'.\n\nFixpoint app {X: Type} (l1 l2: list X) : (list X) :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X: Type} (l: list X) : (list X) :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X: Type} (l: list X) : nat :=\n  match l with\n  | nil => 0\n  | cons h t => (length t) + 1\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity. Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity. Qed.\n\nFail Definition mynil := nil.\n\nDefinition mynil: list nat := nil.\n\nCheck @nil.\n\nDefinition mynil' := @nil nat.\n\nNotation \"x :: y\" := (cons x y)\n                       (at level 60, right associativity).\n\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y) (at level 60, right associativity).\n\nDefinition list123'''' := [1;2;3].\n\nTheorem app_nil_r: forall (X: Type), forall (l: list X), l ++ [] = l.\nProof.\n  intros X l.\n  induction 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  intros A l m n.\n  induction l.\n  - reflexivity.\n  - simpl.\n    rewrite -> IHl.\n    reflexivity.\nQed.\n\nTheorem app_length: forall (X: Type) (l1 l2: list X),\n    length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros X l1 l2.\n  induction l1.\n  - reflexivity.\n  - simpl.\n    rewrite -> IHl1.\n    rewrite <- plus_assoc.\n    replace (length l2 + 1) with (1 + length l2).\n    rewrite -> plus_assoc.\n    + reflexivity.\n    + rewrite -> plus_comm.\n      reflexivity.\nQed.\n\nTheorem rev_app_distr: forall X (l1 l2: list X),\n    rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros X l1 l2.\n  induction l1.\n  - simpl.\n    rewrite -> app_nil_r.\n    reflexivity.\n  - simpl.\n    rewrite -> IHl1.\n    rewrite -> app_assoc.\n    reflexivity.\nQed.\n\nTheorem rev_involutive: forall (X: Type) (l: list X),\n    rev (rev l) = l.\nProof.\n  intros X l.\n  induction l.\n  - reflexivity.\n  - simpl.\n    rewrite -> rev_app_distr.\n    rewrite -> IHl.\n    reflexivity.\nQed.\n\nInductive prod (X Y: Type) :Type :=\n| pair: X -> Y -> prod X Y.\n\nArguments pair {X} {Y} _ _.\n\nNotation \"( x , y )\" := (pair x y).\n\n(* Notation \"X * Y\" := (prod X Y) : type_scope. *)\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | pair 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] [true;false;true]).\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))\n  end.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof.\n  reflexivity.\nQed.\n\nInductive option (X: Type): Type :=\n| Some : X -> option X\n| None : option X.\n\nArguments Some {X} _.\nArguments None {X}.\n\nFixpoint nth_error {X: Type} (l: list X) (n: nat) : option X :=\n  match l with\n    | [] => None\n    | h :: t => if beq_nat n 0 then Some h else nth_error t (n -1)\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 [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\n\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  nth_error l 0.\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\nDefinition doit3times {X: Type} {f: X -> X} (n: X): X :=\n  f (f (f n)).\nArguments doit3times {X} _ _.\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity. Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\n\nFixpoint filter {X: Type} (test: X -> bool) (l: list X) :(list X) :=\n  match l with\n  | [] => []\n  | h :: t => if test h then h :: (filter test t) else (filter test t)\n  end.\n\nExample test_filter1: filter 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.\n  reflexivity.\nQed.\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\nRequire Export Basics.\n\nDefinition filter_even_gt7 (l: list nat) : list nat :=\n  filter (blt_nat 7) (filter evenb l).\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof.\n  reflexivity.\nQed.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\n\nDefinition partition {X: Type} (f: X -> bool) (l: list X) : list X * list X :=\n  pair (filter f l) (filter (fun n => negb (f n)) l).\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\n\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n\nFixpoint map {X Y: Type} (f: X -> Y) (l: list X) : (list Y) :=\n  match l with\n  | [] => []\n  | h :: t => f h :: map f t\n  end.\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\nExample test_map2:\n  map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity. Qed.\n\nExample test_map3:\n    map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity. Qed.\n\nLemma map_rev_assoc: forall (X Y: Type) (f: X -> Y) (l1 l2: list X),\n    map f (l1 ++ l2) = map f l1 ++ map f l2.\nProof.\n  intros X Y f l1 l2.\n  induction l1.\n  - reflexivity.\n  - simpl.\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  intros X Y f l.\n  induction l.\n  - reflexivity.\n  - simpl.\n    rewrite <- IHl.\n    rewrite -> map_rev_assoc.\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  | h :: t => f h ++ flat_map f t\n  end.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\nProof. reflexivity. Qed.\n\nDefinition option_map {X Y: Type} (f: X ->Y) (xo: option X) : option Y :=\n  match xo with\n  | None => None\n  | Some x => Some (f x)\n  end.\n\nFixpoint fold {X Y: Type} (f: X -> Y -> Y) (l: list X) (b: Y) : Y :=\n  match l with\n  | [] => b\n  | h :: t => f h (fold f t b)\n  end.\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\nDefinition constfun {X: Type} (x: X): nat -> X :=\n  fun (k: nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 : plus3 4 = 7.\nProof. reflexivity. Qed.\nExample test_plus3' : doit3times plus3 0 = 9.\nProof. reflexivity. Qed.\nExample test_plus3'' : doit3times (plus 3) 0 = 9.\nProof. reflexivity. Qed.\n\nModule Exercises.\n  Definition fold_length {X: Type} (l: list X) : nat :=\n    fold (fun _ n => S n) l 0.\n\n  Example test_fold_length1 : fold_length [4;7;0] = 3.\n  Proof. reflexivity. Qed.\n\n  Lemma eq_remove_s: forall n m,\n      n = m -> S n = S m.\n  Proof.\n    intros n m H.\n    rewrite -> H.\n    reflexivity.\n  Qed.\n\n  Theorem fold_length_correct: forall X (l: list X),\n      fold_length l = length l.\n  Proof.\n    intros X l.\n    induction l.\n    - reflexivity.\n    - unfold fold_length.\n      unfold fold_length in IHl.\n      simpl.\n      simpl in IHl.\n  Admitted.\n\n  Definition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y :=\n    fold (fun x p => f x :: p) l [].\n\n  Theorem fold_map_correct: forall X Y (l: list X) (f: X -> Y),\n      fold_map f l = map f l.\n  Proof.\n    intros X Y l f.\n    induction l.\n    - reflexivity.\n    - unfold fold_map.\n      unfold fold_map in IHl.\n      simpl.\n      rewrite -> IHl.\n      reflexivity.\n  Qed.\n\n  Definition prod_curry {X Y Z: Type} (f: X * Y -> Z) (x: X) (y: Y) : Z := f (x, y).\n\n  Definition prod_uncurry {X Y Z: Type} (f: X -> Y -> Z) (p: X * Y) : Z :=\n    match p with\n    | (x, y) => f x y\n    end.\n\n  Example test_map2: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\n  Proof. reflexivity. Qed.\n\n  Theorem uncurry_curry: forall (X Y Z: Type) (f: X -> Y ->Z) x y,\n      prod_curry (prod_uncurry f) x y = f x y.\n  Proof.\n    intros X Y Z f x y.\n    unfold prod_curry.\n    unfold prod_uncurry.\n    reflexivity.\n  Qed.\n\n  Fixpoint nth_error {X: Type} (l: list X) (n: nat) : option X :=\n    match l with\n    | [] => None\n    | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\n    end.\n\n  Theorem p1n0: forall (n: nat),\n      beq_nat (n + 1) 0 = false.\n  Proof.\n    intro n.\n    induction n.\n    + reflexivity.\n    + reflexivity.\n  Qed.\n\n  Theorem pred_length: forall X (x: X) (l: list X) (n: nat),\n      length (x :: l) = n -> length l = pred n.\n  Proof.\n    intros X x l n H.\n    simpl in H. induction l.\n    - simpl in H.\n      rewrite <- H.\n      reflexivity.\n    - Admitted.\n    \n  \n  Theorem nth_index_error: forall X (l: list X) (n: nat),\n      length l = n -> @nth_error X l n = None.\n  Proof.\n    intros X l n H.\n    generalize dependent n.\n    induction l.\n    - reflexivity.\n    - intros.\n      apply pred_length in H.\n      apply IHl in H.\n  Admitted.\n  \n      \n\n      \n\n  Module Church.\n    Definition nat := forall {X: Type},\n      (X -> X) -> X -> X.\n\n    Definition zero: nat :=\n      fun {X: Type} (f: X -> X) (x: X) => x.\n\n    Definition one: nat :=\n      fun {X: Type} (f: X -> X) (x: X) => f x.\n\n    Definition two: nat :=\n      fun {X: Type} (f: X -> X) (x: X) => f (f x).\n\n    Definition three: nat := @doit3times.\n\n    Definition succ (n: nat): nat :=\n      fun {X: Type} (f: X -> X) (x: X) => f (n X f x).\n\n    Example succ_1: succ zero = one.\n    Proof. reflexivity. Qed.\n\n    Example succ_2: succ one = two.\n    Proof. reflexivity. Qed.\n\n    Example succ_3: succ two = three.\n    Proof. reflexivity. Qed.\n\n    Definition plus(n m: nat): nat :=\n      fun (X: Type) (f: X -> X) (x: X) => (n X f (m X f x)).\n\n    Example plus_1 : plus zero one = one.\n    Proof. reflexivity. Qed.\n\n    Example plus_2 : plus two three = plus three two.\n    Proof. reflexivity. Qed.\n\n    Example plus_3 : plus (plus two two) three = plus one (plus three three).\n    Proof. reflexivity. Qed.\n\n    Definition mult(n m: nat): nat :=\n      fun (X: Type) (f: X -> X) (x: X) => (m X (n X f) x).\n\n    Example mult_1 : mult one one = one.\n    Proof. reflexivity. Qed.\n\n    Example mult_2 : mult zero (plus three three) = zero.\n    Proof. reflexivity. Qed.\n\n    Example mult_3 : mult two three = plus three three.\n    Proof. reflexivity. Qed.\n\n    Compute (mult two two).\n\n  End Church.  \nEnd Exercises.\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/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867729389246, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.6876684031493377}}
{"text": "(** * Lists: Products, Lists and Options *)\n\n(* $Date: 2011-06-22 10:06:32 -0400 (Wed, 22 Jun 2011) $ *)\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    Here are some simple function definitions illustrating pattern\n    matching on two-argument 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\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,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\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 telling it what variables to\n    bind. *)\n\n\nTheorem surjective_pairing_2 : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  destruct p. reflexivity.  Qed.\n\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  destruct p as (a, b).\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  destruct p as (a, b).\n  reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n    describe the type of _lists_ of numbers like this: \"A list is\n    either the empty list or else a pair of a number and another\n    list.\" *)\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition l_123 := 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 l_123'   := 1 :: (2 :: (3 :: nil)).\nDefinition l_123''  := 1 :: 2 :: 3 :: nil.\nDefinition l_123''' := [1,2,3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n    expressions that involve both [::] and some other infix operator.\n    For example, since we defined [+] as infix notation for the [plus]\n    function at level 50,\n[[\nNotation \"x + y\" := (plus x y)  \n                    (at level 50, left associativity).\n]]\n   The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n   will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n   + (2 :: [3])].\n\n   (By the way, it's worth noting in passing that expressions like \"[1\n   + 2 :: [3]]\" can be a little confusing when you read them in a .v\n   file.  The inner brackets, around 3, indicate a list, but the outer\n   brackets are there to instruct the \"coqdoc\" tool that the bracketed\n   part should be displayed as Coq code rather than running text.\n   These brackets don't appear in the generated HTML.)\n\n   The second and third [Notation] declarations above introduce the\n   standard square-bracket notation for lists; the right-hand side of\n   the third one illustrates Coq's syntax for declaring n-ary\n   notations and translating them to nested sequences of binary\n   constructors. *)\n\n(** A number of functions are useful for manipulating lists.\n    For example, the [repeat] function takes a number [n] and a\n    [count] and returns a list of length [count] where every element\n    is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist := \n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat := \n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist := \n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(** Actually, [app] will be used a lot in some parts of what\n    follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y) \n                     (right associativity, at level 60).\n\nExample test_app1:             [1,2,3] ++ [4,5] = [1,2,3,4,5].\nProof. reflexivity.  Qed.\nExample test_app2:             nil ++ [4,5] = [4,5].\nProof. reflexivity.  Qed.\nExample test_app3:             [1,2,3] ++ nil = [1,2,3].\nProof. reflexivity.  Qed.\n\n(** Here are two more small 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    | 0 :: t => nonzeros t\n    | h :: t => h :: nonzeros t\n  end.\n\nExample test_nonzeros:            nonzeros [0,1,0,2,3,0,0] = [1,2,3].\nProof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with\n    | nil => nil\n    | h :: t =>\n      let newTail := oddmembers t in\n      if oddb h then h :: newTail else newTail\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.\n\nExample test_countoddmembers2:    countoddmembers [0,2,4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers3:    countoddmembers nil = 0.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n    into one, alternating between elements taken from the first list\n    and elements from the second.  See the tests below for more\n    specific examples.\n\n    Note: one natural way of writing [alternate] will fail to satisfy\n    Coq's requirement that all [Fixpoint] definitions be \"obviously\n    terminating.\"  If you find yourself in this rut, look for a\n    slightly more verbose solution that considers elements of both\n    lists at the same time. *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1 with\n    | nil => l2\n    | h1 :: t1 =>\n      match l2 with\n        | nil => l1\n        | h2 :: t2 => h1 :: h2 :: alternate t1 t2\n      end\n  end.\n\nExample test_alternate1:        alternate [1,2,3] [4,5,6] = [1,4,2,5,3,6].\nProof. reflexivity. Qed.\nExample test_alternate2:        alternate [1] [4,5,6] = [1,4,5,6].\nProof. reflexivity. Qed.\nExample test_alternate3:        alternate [1,2,3] [4] = [1,4,2,3].\nProof. reflexivity. Qed.\nExample test_alternate4:        alternate [] [20,30] = [20,30].\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n    multiple times instead of just once.  One reasonable\n    implementation of bags is to represent a bag of numbers as a\n    list. *)\n\nDefinition bag := natlist.  \n\n(** **** Exercise: 3 stars (bag_functions) *)\n(** Complete the following definitions for the functions\n    [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat := \n  match s with\n    | nil => 0\n    | h :: t =>\n      (if beq_nat v h then 1 else 0) + 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 := 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\nDefinition add2 : nat -> bag -> bag := cons.\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 := blt_nat 0 (count v s).\n\nExample test_member1:             member 1 [1,4,1] = true.\nProof. reflexivity. Qed.\nExample test_member2:             member 2 [1,4,1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  (* When remove_one is applied to a bag without the number to remove,\n     it should return the same bag unchanged. *)\n  match s with\n    | nil => nil\n    | h :: t =>\n      if (beq_nat v h) then\n        t\n      else\n        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 =>\n      let rest := remove_all v t in\n      if (beq_nat v h) then rest else h :: rest\n  end.\n\nExample test_remove_all1:          count 5 (remove_all 5 [2,1,5,4,1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all2:          count 5 (remove_all 5 [2,1,4,1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all3:          count 4 (remove_all 5 [2,1,4,5,1,4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_all4:          count 5 (remove_all 5 [2,1,5,4,5,1,4,5,1,4]) = 0.\nProof. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n    | nil => true\n    | h :: t =>\n      if (blt_nat 0 (count h s2)) then\n        subset t (remove_one h s2)\n      else\n        false\n  end.\n\nExample test_subset1:              subset [1,2] [2,1,4,1] = true.\nProof. reflexivity. Qed.\nExample test_subset2:              subset [1,2,2] [2,1,4,1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (bag_theorem) *)\n(** Write down an interesting theorem about bags involving the\n    functions [count] and [add], and prove it.  Note that, since this\n    problem is somewhat open-ended, it's possible that you may come up\n    with a theorem which is true, but whose proof requires techniques\n    you haven't learned yet.  Feel free to ask for help if you get\n    stuck! *)\n\nTheorem add_correct_1: forall (v : nat) (s : bag), count v (add v s) = S (count v s).\nProof.\n  destruct s; simpl; rewrite <- beq_nat_refl; reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n    functions can sometimes be proved entirely by simplification. For\n    example, the simplification performed by [reflexivity] is enough\n    for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof.\n   reflexivity.  Qed.\n\n(** ... because the [[]] is substituted into the match position\n    in the definition of [app], allowing the match itself to be\n    simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n    analysis on the possible shapes (empty or non-empty) of an unknown\n    list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tail l).\nProof.\n  intros l. destruct l as [| n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons n l'\". \n    reflexivity.  Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n    [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n    tactic here introduces two names, [n] and [l'], corresponding to\n    the fact that the [cons] constructor for lists takes two\n    arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n    induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proofs will not get you very far!  It is\n    very important to work through the details of each one, using Coq\n    and thinking about what each step of the proof achieves.\n    Otherwise it is more or less guaranteed that the exercises will\n    make no sense. *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n    perhaps a little less familiar than standard natural number\n    induction, but the basic idea is equally simple.  Each [Inductive]\n    declaration defines a set of data values that can be built up from\n    the declared constructors: a boolean can be either [true] or\n    [false]; a number can be either [O] or [S] applied to a number; a\n    list can be either [nil] or [cons] applied to a number and a list.\n\n    Moreover, applications of the declared constructors to one another\n    are the _only_ possible shapes that elements of an inductively\n    defined set can have, and this fact directly gives rise to a way\n    of reasoning about inductively defined sets: a number is either\n    [O] or else it is [S] applied to some _smaller_ number; a list is\n    either [nil] or else it is [cons] applied to some number and some\n    _smaller_ list; etc. So, if we have in mind some proposition [P]\n    that mentions a list [l] and we want to argue that [P] holds for\n    _all_ lists, we can reason as follows:\n\n      - First, show that [P] is true of [l] when [l] is [nil].\n\n      - Then show that [P] is true of [l] when [l] is [cons n l'] for\n        some number [n] and some smaller list [l'], asssuming that [P]\n        is true for [l'].\n\n    Since larger lists can only be built up from smaller ones,\n    eventually reaching [nil], these two things together establish the\n    truth of [P] for all lists [l].  Here's a concrete example: *)\n\nTheorem app_ass : forall l1 l2 l3 : natlist, \n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).   \nProof.\n  intros l1 l2 l3. induction l1 as [| n l1'].\n  Case \"l1 = nil\".\n    reflexivity.\n  Case \"l1 = cons n l1'\".\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n    static written document -- it is easy to see what's going on if\n    you are reading the proof in an interactive Coq session and you\n    can see the current goal and context at each point, but this state\n    is not visible in the written-down parts of the Coq proof.  So a\n    natural-language proof -- one written for human readers -- will\n    need to include more explicit signposts; in particular, it will\n    help the reader stay oriented if we remind them exactly what the\n    induction hypothesis is in the second case.  *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3], \n   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _Proof_: By induction on [l1].\n\n   - First, suppose [l1 = []].  We must show\n[[\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n]]\n     which follows directly from the definition of [++].\n\n   - Next, suppose [l1 = n::l1'], with\n[[\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n]]\n     (the induction hypothesis). We must show\n[[\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]]  \n     By the definition of [++], this follows from\n[[\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n]]\n     which is immediate from the induction hypothesis.  []\n\n  Here is an exercise to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1'].\n  Case \"l1 = nil\".\n    reflexivity.\n  Case \"l1 = cons\".\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** For a slightly more involved example of an inductive proof\n    over lists, suppose we define a \"cons on the right\" function\n    [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist := \n  match l with\n  | nil    => [v]\n  | h :: t => h :: (snoc t v)\n  end.\n\n(** ... and use it to define a list-reversing function [rev]\n    like this: *)\n\nFixpoint rev (l:natlist) : natlist := \n  match l with\n  | nil    => nil\n  | h :: t => snoc (rev t) h\n  end.\n\nExample test_rev1:            rev [1,2,3] = [3,2,1].\nProof. reflexivity.  Qed.\nExample test_rev2:            rev nil = nil.\nProof. reflexivity.  Qed.\n\n(** Now let's prove some more list theorems using our newly\n    defined [snoc] and [rev].  For something a little more challenging\n    than the inductive proofs we've seen so far, let's prove that\n    reversing a list does not change its length.  Our first attempt at\n    this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    simpl. (* Here we are 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]! *)\nAdmitted.\n\n(** So let's take the equation about [snoc] that would have\n    enabled us to make progress and prove it as a separate lemma. *)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n  length (snoc l n) = S (length l).\nProof.\n  intros n l. induction l as [| n' l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons n' l'\".\n    simpl. rewrite -> IHl'. reflexivity.  Qed. \n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons\".\n    simpl. rewrite -> length_snoc. \n    rewrite -> IHl'. reflexivity.  Qed.\n\n(** For comparison, here are _informal_ proofs of these two theorems: \n\n    _Theorem_: For all numbers [n] and lists [l],\n       [length (snoc l n) = S (length l)].\n \n    _Proof_: By induction on [l].\n\n    - First, suppose [l = []].  We must show\n[[\n        length (snoc [] n) = S (length []),\n]]\n      which follows directly from the definitions of\n      [length] and [snoc].\n\n    - Next, suppose [l = n'::l'], with\n[[\n        length (snoc l' n) = S (length l').\n]]\n      We must show\n[[\n        length (snoc (n' :: l') n) = S (length (n' :: l')).\n]]\n      By the definitions of [length] and [snoc], this\n      follows from\n[[\n        S (length (snoc l' n)) = S (S (length l')),\n]] \n      which is immediate from the induction hypothesis. [] *)\n                        \n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n    \n    _Proof_: By induction on [l].  \n\n      - First, suppose [l = []].  We must show\n[[\n          length (rev []) = length [],\n]]\n        which follows directly from the definitions of [length] \n        and [rev].\n    \n      - Next, suppose [l = n::l'], with\n[[\n          length (rev l') = length l'.\n]]\n        We must show\n[[\n          length (rev (n :: l')) = length (n :: l').\n]]\n        By the definition of [rev], this follows from\n[[\n          length (snoc (rev l') n) = S (length l')\n]]\n        which, by the previous lemma, is the same as\n[[\n          S (length (rev l')) = S (length l').\n]]\n        This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n    and pedantic.  After the first few, we might find it easier to\n    follow proofs that give a little less detail overall (since we can\n    easily work them out in our own minds or on scratch paper if\n    necessary) and just highlight the non-obvious steps.  In this more\n    compressed style, the above proof might look more like this: *)\n\n(** _Theorem_:\n     For all lists [l], [length (rev l) = length l].\n\n    _Proof_: First, observe that\n[[\n       length (snoc l n) = S (length l)\n]]\n     for any [l].  This follows by a straightforward induction on [l].\n     The main property now follows by another straightforward\n     induction on [l], using the observation together with the\n     induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n    the sophistication of the expected audience and on how similar the\n    proof at hand is to ones that the audience will already be\n    familiar with.  The more pedantic style is a good default for\n    present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n    already proved, using [rewrite], and later we will see other ways\n    of reusing previous theorems.  But in order to refer to a theorem,\n    we need to know its name, and remembering the names of all the\n    theorems we might ever want to use can become quite difficult!  It\n    is often hard even to remember what theorems have been proven,\n    much less what they are named.\n\n    Coq's [SearchAbout] command is quite helpful with this.  Typing\n    [SearchAbout foo] will cause Coq to display a list of all theorems\n    involving [foo].  For example, try uncommenting the following to\n    see a list of theorems that we have proved about [rev]: *)\n\n(* SearchAbout rev. *)\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n    throughout the rest of the course; it can save you a lot of time! *)\n    \n(** Also, if you are using ProofGeneral, you can run [SearchAbout]\n    with [C-c C-f]. Pasting its response into your buffer can be\n    accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars, recommended (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist, \n  l ++ [] = l.   \nProof.\n  induction l as [| n l']; simpl; try reflexivity.\n  rewrite IHl'. reflexivity.\nQed.\n\nLemma snoc_rev : forall (l : natlist) (n : nat), rev (snoc l n) = n :: rev l.\nProof.\n  intros.\n  induction l as [| n' l']; simpl; try reflexivity.\n  rewrite IHl'.\n  reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  induction l as [| n l']; simpl; try reflexivity.\n  rewrite snoc_rev.\n  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 as [| n l1']; simpl.\n\n  Case \"nil\".\n  rewrite app_nil_end.\n  reflexivity.\n\n  Case \"n ++ l1'\".\n  rewrite IHl1'. clear IHl1'.\n  set (l3 := rev l2). induction l3 as [| n3 l3']; simpl; try reflexivity.\n  rewrite IHl3'.\n  reflexivity.\nQed.\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. repeat (rewrite app_ass). reflexivity.\nQed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n  snoc l n = l ++ [n].\nProof.\n  intros.\n  induction l as [| n' l']; simpl; try reflexivity.\n  rewrite IHl'.\n  reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_length : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros. induction l1 as [ | n1 l1']; simpl; try reflexivity.\n  rewrite IHl1'.\n  destruct n1; reflexivity.\nQed.\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\nTheorem append_snoc :\n  forall (l1 l2 : natlist) (n : nat), snoc l1 n ++ l2 = l1 ++ (n :: l2).\nProof.\n  intros l1 l2 n.\n  induction l1 as [ | n' l1']; simpl; try reflexivity.\n  congruence.\nQed.\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  reflexivity.\nQed.\n\n(** The following lemma about [ble_nat] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n  ble_nat n (S n) = true.\nProof.\n  intros n. induction n as [| n'].\n  Case \"0\".  \n    simpl.  reflexivity.\n  Case \"S n'\".\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n  ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  induction s as [ | h' s' ]; try reflexivity.\n  Case \"s = cons h' s'\".\n  destruct h' as [ | h''].\n  SCase \"h' = 0\".\n  apply ble_n_Sn.\n  SCase \"h' = S h''\".\n  assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *)  \n(** Write down an interesting theorem about bags involving the\n    functions [count] and [sum], and prove it. *)\n\nTheorem count_distr_sum : forall (n: nat) (bag1 bag2 : bag), count n (sum bag1 bag2) = count n bag1 + count n bag2.\nProof.\n  intros n bag1 bag2.\n  induction bag1; simpl; try reflexivity.\n  rewrite IHbag1.\n  rewrite plus_assoc.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n[[\n    forall X (l1 l2 : list X), rev l1 = rev l2 -> l1 = l2.\n]]\n\nThere is a hard way and an easy way to solve this exercise.\n*)\n\nTheorem rev_injective : forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros.\n  SearchAbout rev.\n(* rev_involutive: forall l : natlist, rev (rev l) = l *)\n  rewrite <- rev_involutive.\n  rewrite <- rev_involutive at 1.\n  congruence.\nQed.\n\nLemma rev_empty : forall l : natlist, rev l = [] -> l = [].\n  induction l; simpl; try reflexivity.\n  destruct (rev l); simpl; intros; discriminate.\nQed.\n\nLemma snoc_nonempty: forall (l : natlist) (n : nat), snoc l n = [] -> False.\nProof.\n  intros.\n  destruct l; revert H; simpl; discriminate.\nQed.\n\nTheorem rev_injective_2 : forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros.\n  destruct l1 as [ | n l1'].\n\n  Case \"l1 = []\".\n  revert H. simpl. intros.\n\n  symmetry.\n  apply (rev_empty l2).\n  symmetry.\n  assumption.\n\n  Case \"l1 = n :: l1'\".\n  destruct l2 as [ | m l2'].\n  SCase \"l2 = []\".\n  \n  revert H.\n  simpl.  \n  intros.\n  exfalso.\n  apply (snoc_nonempty (rev l1') n H).\n\n  SCase \"l2 = m :: l2'\".\n  revert H.\n  simpl.\nAbort.\nTheorem foo2: forall (l1 l2: natlist) (n1 n2: nat), snoc l1 n1 = snoc l2 n2 -> l1 = l2 /\\ n1 = n2.\n\n  intros l1 l2 n1 n2.\n  destruct l1.\n  destruct l2.\n  simpl.\n  split; try reflexivity.\n  congruence.\n  simpl.\n  destruct l2.\n  simpl.\n  discriminate.\n  simpl.\n  discriminate.\n\n  simpl.\n  destruct l1.\n  simpl.\n  intros.\n  destruct l2.\n  discriminate.\n  split.\n  inversion H.\n  revert H.\n  rewrite H1.\n  simpl.\n  intros.\n  clear H1 n.\n  simpl.\n  SearchAbout snoc.\n  revert H2.\n  rewrite snoc_append.\n  simpl.\n  intros.\n  Restart.\n\n  intros.\n  induction l1 as [| n1' l1'].\n  destruct l2.\n  inversion H; split; reflexivity.\n  inversion H.\n  exfalso.\n  apply (snoc_nonempty l2 n2).\n  congruence.\n\n  induction l2 as [| n2' l2'].\n  inversion H.\n  exfalso.\n  apply (snoc_nonempty l1' n1 H2).\n\n\n\n  inversion H.\n  revert H.\n  repeat (rewrite snoc_append).\n  intros.\n  inversion H. clear H.\n  clear IHl1' IHl2'.\n  clear H1 H3 n1'.\nAbort.\nTheorem rev_injective_2 : forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\nProof.\n  induction l1.\n  simpl.\n  intros.\n  induction l2; try reflexivity.\n  revert H.\n  simpl.\n  destruct (rev l2) eqn:e; simpl; intros; discriminate.\n  Restart.\n  intros.\n  destruct (rev l2) eqn:e; simpl; intros.\n  destruct l1; try reflexivity.\n  destruct l2; try reflexivity.\n  Restart.\n\n  induction l1.\n  simpl.\n  intros.\n  induction l2; try reflexivity.\n  revert H.\n  simpl.\n  destruct (rev l2) eqn:e; simpl; intros; discriminate.\n  simpl.\n  intros.\n  induction l2.\n  destruct (rev l1) eqn:e; simpl; intros; discriminate.\n  revert H.\n  simpl.\n  intros.\n  destruct (rev l1) eqn:e1; simpl; intros.\n  revert e1.\n  revert H.\n  rewrite (rev_empty l1).\n  intros.\n\n  destruct (rev l2) eqn:e2; simpl; intros.\n  revert e2.\n  rewrite (rev_empty l2).\n  intros.\n  revert H.\n  simpl.\n  tauto.\n  clear e1.\n  clear IHl1.\n  clear IHl2.\nAbort.\n(*  Abort.\nTheorem rev_injective_2 : forall (l1 l2 : natlist), l1 <> l2 -> rev l1 <> rev l2.\n  intros.\n  induction l1.\n  simpl.\n  Abort.*)\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 (o : natoption) (d : nat) : 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 :: l => 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: 2 stars, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim (hd_opt l) default.\nProof.\n  destruct l; try reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n    lists of numbers for equality.  Prove that [beq_natlist l l]\n    yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1 with\n    | nil =>\n      match l2 with\n        | nil => true\n        | _ => false\n      end\n    | h1 :: t1 =>\n      match l2 with\n        | nil => false\n        | h2 :: t2 => andb (beq_nat h1 h2) (beq_natlist t1 t2)\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\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  induction l; simpl; try reflexivity.\n  rewrite <- beq_nat_refl.\n  simpl.\n  apply IHl.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    exactly the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n,o] = [n,p] ->\n     [n,o] = [m,p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n  (* At this point, we could finish with \n     \"[rewrite -> eq2. reflexivity.]\"\n     as we have done several times above.  \n     But we can achieve the same effect in \n     a single step by using the [apply] tactic \n     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.\n\n  Restart.\n\n  intros n m o p eq1 eq2. \n  rewrite (eq2 n m).\n  reflexivity.\n  rewrite eq1.\n  reflexivity.\nQed.\n\n(** You may find it instructive to experiment with this proof\n    and see if there is a way to complete it using just [rewrite]\n    instead of [apply]. *)\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] binding some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex) *)\n(** Complete the following proof without using [simpl]. *)\n\nTheorem silly_ex : \n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 3 = true ->\n     oddb 4 = true.\nProof.\n  intros H H0.\n  apply (H 3 H0).\n  \n  Restart.\n  intros H H0.\n  apply H.\n  apply H0.\nQed.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal _exactly_ -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  simpl.\n  (* here we cannot use [apply] directly *)\nAdmitted.\n\n(** In this case we can use the [symmetry] tactic, which\n    switches the left and right sides of an equality in the goal. *)\n\nTheorem silly3 : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  symmetry.\n  simpl. (* Actually, this [simpl] is unnecessary, since \n            [apply] will do a [simpl] step first. *)  \n  apply H.  Qed.         \n\n\n(** **** Exercise: 3 stars, recommended (apply_exercise1) *)\nTheorem rev_exercise1 : forall (l l' : natlist),\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(** **** Exercise: 1 star (apply_rewrite) *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  Are there situations where both can usefully be\n    applied?\n\n  (* FILL IN HERE *)\n*)\n(** [] *)\n\n(* ###################################################### *)\n(** * Varying the Induction Hypothesis *)\n\n(** One subtlety in these inductive proofs is worth noticing here.\n    For example, look back at the proof of the [app_ass] theorem.  The\n    induction hypothesis (in the second subgoal generated by the\n    [induction] tactic) is\n\n      [ (l1' ++ l2) ++ l3 = l1' ++ l2 ++ l3 ].\n\n    (Note that, because we've defined [++] to be right associative,\n    the expression on the right of the [=] is the same as writing [l1'\n    ++ (l2 ++ l3)].)\n\n    This hypothesis makes a statement about [l1'] together with the\n    _particular_ lists [l2] and [l3].  The lists [l2] and [l3], which\n    were introduced into the context by the [intros] at the top of the\n    proof, are \"held constant\" in the induction hypothesis.  If we set\n    up the proof slightly differently by introducing just [n] into the\n    context at the top, then we get an induction hypothesis that makes\n    a stronger claim:\n\n     [ forall l2 l3,  (l1' ++ l2) ++ l3 = l1' ++ l2 ++ l3 ]\n\n    Use Coq to see the difference for yourself.\n\n    In the present case, the difference between the two proofs is\n    minor, since the definition of the [++] function just examines its\n    first argument and doesn't do anything interesting with its second\n    argument.  But we'll soon come to situations where setting up the\n    induction hypothesis one way or the other can make the difference\n    between a proof working and failing. *)\n\n(** **** Exercise: 2 stars, optional (app_ass') *)\n(** Give an alternate proof of the associativity of [++] with a more\n    general induction hypothesis.  Complete the following (leaving the\n    first line unchanged). *)\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  Case \"l1 = []\".\n  reflexivity.\n  Case \"l1 = n :: l1'\".\n  simpl.\n  intros.\n  rewrite IHl1'.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (apply_exercise2) *)\n(** Notice that we don't introduce [m] before performing induction.\n    This leaves it general, so that the IH doesn't specify a\n    particular [m], but lets us pick. *)\n\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = 0\".\n  destruct m; reflexivity.\n  Case \"n = S n'\".\n  intros.\n  destruct m; simpl; try reflexivity.\n\n  (* destruct m. reflexivity. simpl. *)\n  apply IHn'.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (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: By induction on [n].\n\n- First, suppose that [n = 0]. We must show\n[[\n   forall m : nat, beq_nat 0 m = beq_nat m 0,\n]]\n  To do so, we perform case analysis on m.\n  - If m = 0, the thesis becomes the obvious:\n[[\n   beq_nat 0 0 = beq_nat 0 0,\n]]\n  - If m = S m', the thesis becomes the obvious:\n[[\n   forall m' : nat, beq_nat 0 (S m') = beq_nat (S m') 0,\n]]\n  which follows from the definition of beq_nat (which tells us that\n  both sides are false).\n- Next, suppose that n = S n', with\n[[\n  forall m : nat, beq_nat n' m = beq_nat m n'.\n]]\n  We must show \n[[\n  forall m : nat, beq_nat (S n') m = beq_nat m (S n').\n]]\n  We proceed again by case analysis on [m]. The case [m = 0] follows\n  directly from the definition. For the case [m = S m'], we need to\n  prove:\n[[\n  beq_nat (S n') (S m') = beq_nat (S m') (S n').\n]]\n  By the definition of [beq_nat], this follows from the induction\n  hypothesis applied for the case [m = m']. [] *)\n\nEnd NatList.\n\n(* ###################################################### *)\n(** * Exercise: Dictionaries *)\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(** Below 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) : 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(** **** Exercise: 1 star (dictionary_invariant1) *)\n(* Complete the following proof. *)\nTheorem dictionary_invariant1 : forall (d : dictionary) (k v: nat),\n  (find k (insert k v d)) = Some v.\nProof.\n  intros d k v.\n  simpl.\n  rewrite <- beq_nat_refl.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(* Complete the following proof. *)\nTheorem dictionary_invariant2 : forall (d : dictionary) (m n o: nat),\n  (beq_nat m n) = false -> (find m d) = (find m (insert n o d)).\nProof.\n intros d m n o H.\n simpl.\n rewrite H.\n reflexivity.\nQed.\n(** [] *)\n\nEnd Dictionary.\n\n(** The following declaration puts [beq_nat_sym] into the\n    top-level namespace, so that we can use it later without having to\n    write [NatList.beq_nat_sym]. *)\n\nDefinition beq_nat_sym := NatList.beq_nat_sym.\n\n", "meta": {"author": "Blaisorblade", "repo": "Software-Foundations", "sha": "aeb1b49fd922a346b774b330694fe6c16caf9626", "save_path": "github-repos/coq/Blaisorblade-Software-Foundations", "path": "github-repos/coq/Blaisorblade-Software-Foundations/Software-Foundations-aeb1b49fd922a346b774b330694fe6c16caf9626/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673223709251, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.6876389670520446}}
{"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(** ** Sparse ciphers *)\n\nRequire Import Arith Nat Omega List Bool Setoid.\nRequire Import utils_tac gcd sums rel_iter bool_nat power_decomp.\n\nSet Implicit Arguments.\n\nLocal Notation power := (mscal mult 1).\nLocal Notation \"∑\" := (msum plus 0).\nLocal Infix \"≲\" := binary_le (at level 70, no associativity).\nLocal Infix \"⇣\" := nat_meet (at level 40, left associativity).\nLocal Infix \"⇡\" := nat_join (at level 50, left associativity).\n\nHint Resolve power2_gt_0.\n\nSection stability_of_power.\n\n  Fact mult_lt_power_2 u v k : u < power k 2 -> v < power k 2 -> u*v < power (2*k) 2.\n  Proof.\n    intros H1 H2.\n    replace (2*k) with (k+k) by omega.\n    rewrite power_plus.\n    apply lt_le_trans with ((S u)*S v).\n    simpl; rewrite (mult_comm _ (S _)); simpl; rewrite mult_comm; omega.\n    apply mult_le_compat; auto.\n  Qed.\n\n  Fact mult_lt_power_2_4 u v k : u < power k 2 -> v < power k 2 -> u*v < power (4*k) 2.\n  Proof.\n    intros H1 H2.\n    apply lt_le_trans with (1 := mult_lt_power_2 _ H1 H2).\n    apply power_mono_l; omega.\n  Qed.\n\n  Fact mult_lt_power_2_4' u1 v1 u2 v2 k : \n               u1 < power k 2 \n            -> v1 < power k 2\n            -> u2 < power k 2\n            -> v2 < power k 2\n            -> u1*v1+v2*u2 < power (4*k) 2.\n  Proof.\n    intros H1 H2 H3 H4.\n    destruct (eq_nat_dec k 0) as [ ? | Hk ].\n    - subst k; simpl.\n      rewrite power_0 in *.\n      destruct u1; destruct v1; destruct u2; destruct v2; subst; omega.\n    - apply lt_le_trans with (power (S (2*k)) 2). \n      + rewrite power_S, <- mult_2_eq_plus.\n        apply plus_lt_compat; apply mult_lt_power_2; auto.\n      + apply power_mono_l; omega.\n  Qed.\n\nEnd stability_of_power.\n\nSection power_decomp.\n\n  Variable (p : nat) (Hp : 2 <= p).\n\n  Let power_nzero x : power x p <> 0.\n  Proof. generalize (@power_ge_1 x p); omega. Qed.\n\n  Fact power_decomp_lt n f a q :  \n           (forall i j, i < j < n -> f i < f j)\n        -> (forall i, i < n -> f i < q)\n        -> (forall i, i < n -> a i < p)\n        -> ∑ n (fun i => a i * power (f i) p) < power q p.\n  Proof.\n    revert q; induction n as [ | n IHn ]; intros q Hf1 Hf2 Ha.\n    + rewrite msum_0; apply power_ge_1; omega.\n    + rewrite msum_plus1; auto.\n      apply lt_le_trans with (1*power (f n) p + a n * power (f n) p).\n      * apply plus_lt_le_compat; auto.\n        rewrite Nat.mul_1_l.\n        apply IHn.\n        - intros; apply Hf1; omega.\n        - intros; apply Hf1; omega.\n        - intros; apply Ha; omega.\n      * rewrite <- Nat.mul_add_distr_r.\n        replace q with (S (q-1)).\n        - rewrite power_S; apply mult_le_compat; auto.\n          ++ apply Ha; auto.\n          ++ apply power_mono_l; try omega.\n             generalize (Hf2 n); intros; omega.\n        - generalize (Hf2 0); intros; omega.\n  Qed.\n\n  Lemma power_decomp_is_digit n a f : \n           (forall i j, i < j < n -> f i < f j)\n        -> (forall i, i < n -> a i < p)\n        ->  forall i, i < n -> is_digit (∑ n (fun i => a i * power (f i) p)) p (f i) (a i).\n  Proof.\n    intros Hf Ha.\n    induction n as [ | n IHn ]; intros i Hi.\n    + omega.\n    + split; auto.\n      exists (∑ (n-i) (fun j => a (S i + j) * power (f (S i+j) - f i - 1) p)), \n             (∑ i (fun j => a j * power (f j) p)); split.\n      - replace (S n) with (S i + (n-i)) by omega.\n        rewrite msum_plus, msum_plus1; auto.\n        rewrite <- plus_assoc, plus_comm; f_equal.\n        rewrite Nat.mul_add_distr_r, plus_comm; f_equal.\n        rewrite <- mult_assoc, mult_comm, <- sum_0n_scal_l.\n        apply msum_ext.\n        intros j Hj.\n        rewrite (mult_comm (_ * _));\n        repeat rewrite <- mult_assoc; f_equal.\n        rewrite <- power_S, <- power_plus; f_equal.\n        generalize (Hf i (S i+j)); intros; omega.\n      - apply power_decomp_lt; auto.\n        * intros; apply Hf; omega.\n        * intros; apply Ha; omega.\n  Qed.\n\n  Theorem power_decomp_unique n f a b :\n            (forall i j, i < j < n -> f i < f j)\n         -> (forall i, i < n -> a i < p)\n         -> (forall i, i < n -> b i < p)\n         -> ∑ n (fun i => a i * power (f i) p)\n          = ∑ n (fun i => b i * power (f i) p)\n         -> forall i, i < n -> a i = b i.\n  Proof.\n    intros Hf Ha Hb E i Hi.\n    generalize (power_decomp_is_digit _ _ Hf Ha Hi)\n               (power_decomp_is_digit _ _ Hf Hb Hi).\n    rewrite E; apply is_digit_fun.\n  Qed.\n\nEnd power_decomp.\n\nSection power_decomp_uniq.\n\n  Variable (p : nat) (Hp : 2 <= p).\n\n  Theorem power_decomp_factor n f a : \n           (forall i, 0 < i < S n -> f 0 < f i)\n        -> ∑ (S n) (fun i => a i * power (f i) p) \n         = ∑ n (fun i => a (S i) * power (f (S i) - f 0 - 1) p) * power (S (f 0)) p\n         + a 0 * power (f 0) p.\n  Proof.\n    intros Hf.\n    rewrite msum_S, plus_comm; f_equal.\n    rewrite <- sum_0n_scal_r.\n    apply msum_ext.\n    intros i Hi.\n    rewrite <- mult_assoc; f_equal.\n    rewrite <- power_plus; f_equal.\n    generalize (Hf (S i)); intros; omega.\n  Qed.\n\n  Let power_nzero x : power x p <> 0.\n  Proof.\n    generalize (@power_ge_1 x p); omega.\n  Qed.\n\n  Let lt_minus_cancel a b c : a < b < c -> b - a - 1 < c - a - 1.\n  Proof. intros; omega. Qed. \n\n  (* Another proof of the above statement *)\n\n  Theorem power_decomp_unique' n f a b :\n            (forall i j, i < j < n -> f i < f j)\n         -> (forall i, i < n -> a i < p)\n         -> (forall i, i < n -> b i < p)\n         -> ∑ n (fun i => a i * power (f i) p)\n          = ∑ n (fun i => b i * power (f i) p)\n         -> forall i, i < n -> a i = b i.\n  Proof.\n    revert f a b.\n    induction n as [ | n IHn ]; intros f a b Hf Ha Hb.\n    + intros; omega.\n    + assert (forall i, 0 < i < S n -> f 0 < f i)\n        by (intros; apply Hf; omega). \n      do 2 (rewrite power_decomp_factor; auto).\n      intros E.\n      apply div_rem_uniq in E; auto.\n      * destruct E as (E1 & E2).\n        intros [ | i ] Hi.\n        - revert E2; rewrite Nat.mul_cancel_r; auto.\n        - apply IHn with (4 := E1); try omega.\n          ++ intros u j Hu; apply lt_minus_cancel; split; apply Hf; omega. \n          ++ intros; apply Ha; omega.\n          ++ intros; apply Hb; omega.\n      * rewrite power_S.\n        apply Nat.mul_lt_mono_pos_r.\n        - apply power_ge_1; omega.\n        - apply Ha; omega.\n      * rewrite power_S.\n        apply Nat.mul_lt_mono_pos_r.\n        - apply power_ge_1; omega.\n        - apply Hb; omega.\n  Qed.\n\nEnd power_decomp_uniq.\n\nFact mult_2_eq_plus x : x + x = 2 *x.\nProof. ring. Qed.\n\nSection power_injective.\n\n  Let power_2_inj_1 i j n : j < i -> 2* power n 2 <> power i 2 + power j 2.\n  Proof.\n    rewrite <- power_S; intros H4 E.\n     generalize (@power_ge_1 j 2); intro C.\n     destruct (lt_eq_lt_dec i (S n)) as [ [ H5 | H5 ] | H5 ].\n     + apply power_mono_l with (x := 2) in H5; auto.\n       rewrite power_S in H5.\n       apply power_mono_l with (x := 2) in H4; auto.\n       rewrite power_S in H4; omega.\n     + subst i; omega.\n     + apply power_mono_l with (x := 2) in H5; auto.\n      rewrite power_S in H5; omega.\n  Qed.\n\n  Fact power_2_n_ij_neq i j n : i <> j -> power (S n) 2 <> power i 2 + power j 2.\n  Proof.\n    intros H.\n    destruct (lt_eq_lt_dec i j) as [ [] | ]; try tauto.\n    + rewrite plus_comm; apply power_2_inj_1; auto.\n    + apply power_2_inj_1; auto.\n  Qed.\n\n  Fact power_2_inj i j : power i 2 = power j 2 -> i = j.\n  Proof.\n    intros H.\n    destruct (lt_eq_lt_dec i j) as [ [ C | C ] | C ]; auto;\n      apply power_smono_l with (x := 2) in C; omega.\n  Qed.\n\n  Let power_plus_lt a b c : a < b < c -> power a 2 + power b 2 < power c 2.\n  Proof.\n    intros [ H1 H2 ].\n    apply power_mono_l with (x := 2) in H2; auto.\n    apply power_smono_l with (x := 2) in H1; auto.\n    rewrite power_S in H2; omega.\n  Qed.\n\n  Let power_inj_2 i1 j1 i2 j2 : \n             j1 < i1 \n          -> j2 < i2 \n          -> power i1 2 + power j1 2 = power i2 2 + power j2 2\n          -> i1 = i2 /\\ j1 = j2.\n  Proof.\n    intros H1 H2 H3.\n    destruct (lt_eq_lt_dec i1 i2) as [ [ C | C ] | C ].\n    + generalize (@power_plus_lt j1 i1 i2); intros; omega.\n    + split; auto; apply power_2_inj; subst; omega.\n    + generalize (@power_plus_lt j2 i2 i1); intros; omega.\n  Qed.\n\n  Theorem sum_2_power_2_injective i1 j1 i2 j2 :\n              j1 <= i1 \n           -> j2 <= i2 \n           -> power i1 2 + power j1 2 = power i2 2 + power j2 2 \n           -> i1 = i2 /\\ j1 = j2.\n  Proof.\n    intros H1 H2 E.\n    destruct (eq_nat_dec i1 j1) as [ H3 | H3 ];\n    destruct (eq_nat_dec i2 j2) as [ H4 | H4 ].\n    + subst j1 j2.\n      assert (i1 = i2); auto.\n      do 2 rewrite mult_2_eq_plus, <- power_S in E.\n      apply power_2_inj in E; omega.\n    + subst j1; rewrite mult_2_eq_plus in E.\n      apply power_2_inj_1 in E; omega.\n    + subst j2; symmetry in E.\n      rewrite mult_2_eq_plus in E.\n      apply power_2_inj_1 in E; omega.\n    + revert E; apply power_inj_2; omega.\n  Qed. \n \nEnd power_injective.\n\nFact divides_power p a b : a <= b -> divides (power a p) (power b p).\nProof.\n  (* split. *)\n  * induction 1 as [ | b H IH ].\n    + apply divides_refl.\n    + apply divides_trans with (1 := IH).\n      rewrite power_S; apply divides_mult, divides_refl.\n(*  * intros H.\n    apply divides_le in H. *)\nQed.\n\nFact divides_msum k n f : (forall i, i < n -> divides k (f i)) -> divides k (∑ n f).\nProof.\n  revert f; induction n as [ | n IHn ]; intros f Hf.\n  + rewrite msum_0; apply divides_0.\n  + rewrite msum_S; apply divides_plus.\n    * apply Hf; omega.\n    * apply IHn; intros; apply Hf; omega.\nQed.\n\nFact inc_seq_split_lt n f k : \n         (forall i j, i < j < n -> f i < f j) \n      -> { p | p <= n /\\ (forall i, i < p -> f i < k) /\\ forall i, p <= i < n -> k <= f i }.\nProof.\n  revert f; induction n as [ | n IHn ]; intros f Hf.\n  + exists 0; split; auto; split; intros; omega.\n  + destruct (le_lt_dec k (f 0)) as [ H | H ].\n    - exists 0; split; try omega.\n      split; intros i Hi; try omega.\n      destruct i as [ | i ]; auto.\n      apply le_trans with (1 := H), lt_le_weak, Hf; omega.\n    - destruct (IHn (fun i => f (S i))) as (p & H1 & H2 & H3).\n      * intros; apply Hf; omega.\n      * exists (S p); split; try omega; split.\n        ++ intros [ | i ] Hi; auto; apply H2; omega.\n        ++ intros [ | i ] Hi; try omega; apply H3; omega.\nQed.\n\nFact inc_seq_split_le n f h : (forall i j, i < j < n -> f i < f j) \n                   -> { q | q <= n \n                         /\\ (forall i, i < q      -> f i <= h)\n                         /\\ (forall i, q <= i < n -> h < f i) }.\nProof.\n  intros Hf.\n  destruct inc_seq_split_lt with (1 := Hf) (k := S h)\n    as (q & H1 & H2 & H3); exists q; split; auto; split.\n  + intros i Hi; specialize (H2 _ Hi); omega.\n  + intros i Hi; specialize (H3 _ Hi); omega.\nQed.\n\nFact divides_lt p q : q < p -> divides p q -> q = 0.\nProof.\n  intros H1 ([ | k] & H2); auto.\n  revert H2; simpl; generalize (k *p); intros; omega.\nQed.\n\nFact sum_powers_inc_lt_last n f r : \n        2 <= r\n     -> (forall i j, i < j <= n -> f i < f j)\n     -> ∑ (S n) (fun i => power (f i) r) < power (S (f n)) r.\nProof.\n  intros Hr.\n  revert f.\n  induction n as [ | n IHn ]; intros f Hf.\n  + rewrite msum_1; auto; apply power_smono_l; auto.\n  + rewrite msum_plus1; auto.\n    rewrite power_S.\n    apply lt_le_trans with (power (S (f n)) r + power (f (S n)) r).\n    * apply plus_lt_compat_r; auto.\n      apply IHn; intros; apply Hf; omega.\n    * assert (power (S (f n)) r <= power (f (S n)) r) as H.\n      { apply power_mono_l; try omega; apply Hf; omega. }\n      apply le_trans with (2 * power (f (S n)) r); try omega.\n      apply mult_le_compat; auto.\nQed.\n\nFact sum_powers_inc_lt n f p r : \n        2 <= r\n     -> (forall i, i < n -> f i < p)\n     -> (forall i j, i < j < n -> f i < f j)\n     -> ∑ n (fun i => power (f i) r) < power p r.\nProof.\n  destruct n as [ | n ].\n  + intros H _ _; rewrite msum_0; apply power_ge_1; omega.\n  + intros H1 H2 H3.\n    apply lt_le_trans with (power (S (f n)) r).\n    * apply sum_powers_inc_lt_last; auto.\n      intros; apply H3; omega.\n    * apply power_mono_l; try omega.\n      apply H2; auto.\nQed.\n\n(* the value r^f1 + ... + f^fn uniquely determines n and f1 < ... < fn  *)\n\nFact sum_powers_injective r n f m g :\n       2 <= r\n    -> (forall i j, i < j < n -> f i < f j)\n    -> (forall i j, i < j < m -> g i < g j)\n    -> ∑ n (fun i => power (f i) r) = ∑ m (fun i => power (g i) r)\n    -> n = m /\\ forall i, i < n -> f i = g i.\nProof.\n  intros Hr; revert m f g.\n  induction n as [ | n IHn ]; intros m f g Hf Hg.\n  + rewrite msum_0.\n    destruct m as [ | m ].\n    * rewrite msum_0; split; auto; intros; omega.\n    * rewrite msum_S.\n      generalize (@power_ge_1 (g 0) r); intros; exfalso; omega.\n  + destruct m as [ | m ].\n    * rewrite msum_0, msum_S; intros; exfalso.\n       generalize (@power_ge_1 (f 0) r); intros; exfalso; omega.\n    * destruct (lt_eq_lt_dec (f n) (g m)) as [ [E|E]| E].\n      - rewrite msum_plus1 with (n := m); auto. \n        intros; exfalso.\n        assert (∑ (S n) (fun i => power (f i) r) < power (g m) r) as C; try omega.\n        apply sum_powers_inc_lt; auto.\n        intros i Hi.\n        destruct (eq_nat_dec i n); subst; auto.\n        apply lt_trans with (2 := E), Hf; omega.\n      - do 2 (rewrite msum_plus1; auto); intros C.\n        destruct (IHn m f g) as (H1 & H2).\n        ++ intros; apply Hf; omega.\n        ++ intros; apply Hg; omega.\n        ++ rewrite E in C; omega.\n        ++ split; subst; auto.\n           intros i Hi.\n           destruct (eq_nat_dec i m); subst; auto.\n           apply H2; omega.\n      - rewrite msum_plus1 with (n := n); auto. \n        intros; exfalso.\n        assert (∑ (S m) (fun i => power (g i) r) < power (f n) r) as C; try omega.\n        apply sum_powers_inc_lt; auto.\n        intros i Hi.\n        destruct (eq_nat_dec i m); subst; auto.\n        apply lt_trans with (2 := E), Hg; omega.\nQed.\n\nFact power_divides_sum_power r p n f :\n         2 <= r \n      -> 0 < n\n      -> (forall i j, i < j < n -> f i < f j) \n      -> divides (power p r) (∑ n (fun i => power (f i) r)) <-> p <= f 0.\nProof.\n  intros Hr Hn Hf.\n  split.\n  + destruct inc_seq_split_lt with (k := p) (1 := Hf) as (k & H1 & H2 & H3).\n    replace n with (k+(n-k)) by omega.\n    rewrite msum_plus; auto.\n    rewrite plus_comm; intros H.\n    apply divides_plus_inv in H.\n    2: apply divides_msum; intros; apply divides_power, H3; omega.\n    destruct k as [ | k ].\n    * apply H3; omega.\n    * apply divides_lt in H.\n      - rewrite msum_S in H.\n        generalize (@power_ge_1 (f 0) r); intros; omega.\n      - apply sum_powers_inc_lt; auto.\n        intros; apply Hf; omega.\n  + intros H.\n    apply divides_msum.\n    intros i Hi; apply divides_power.\n    apply le_trans with (1 := H).\n    destruct i; auto. \n    generalize (Hf 0 (S i)); intros; omega.\nQed.\n\nFact smono_upto_injective n f :\n       (forall i j, i < j < n -> f i < f j)\n    -> (forall i j, i < n -> j < n -> f i = f j -> i = j).\nProof.\n  intros Hf i j Hi Hj E.\n  destruct (lt_eq_lt_dec i j) as [ [H|] | H ]; auto.\n  + generalize (@Hf i j); intros; omega.\n  + generalize (@Hf j i); intros; omega.\nQed.\n\nFact product_sums n f g : (∑ n f)*(∑ n g) \n                         = ∑ n (fun i => f i*g i) \n                         + ∑ n (fun i => ∑ i (fun j => f i*g j + f j*g i)).\nProof.\n  induction n as [ | n IHn ].\n  + repeat rewrite msum_0; auto.\n  + repeat rewrite msum_plus1; auto.\n    repeat rewrite Nat.mul_add_distr_l.\n    repeat rewrite Nat.mul_add_distr_r.\n    rewrite IHn, msum_sum; auto.\n    * rewrite sum_0n_scal_l, sum_0n_scal_r; ring.\n    * intros; ring.\nQed.\n\nSection sums.\n\n  Fact square_sum n f : (∑ n f)*(∑ n f) = ∑ n (fun i => f i*f i) + 2*∑ n (fun i => ∑ i (fun j => f i*f j)).\n  Proof.\n    rewrite product_sums, <- sum_0n_scal_l; f_equal.\n    apply msum_ext; intros; rewrite <- sum_0n_scal_l.\n    apply msum_ext; intros; ring.\n  Qed. \n\n  Fact sum_regroup r k n f :\n          (forall i, i < n -> f i < k) \n       -> (forall i j, i < j < n -> f i < f j)\n       -> { g | ∑ n (fun i => power (f i) r) \n              = ∑ k (fun i => g i * power i r) \n             /\\ (forall i, i < k  -> g i <= 1) \n             /\\ (forall i, k <= i -> g i = 0) }.\n  Proof.\n    revert k f; induction n as [ | n IHn ]; intros k f Hf1 Hf2.\n    + exists (fun _ => 0); split; auto.\n      rewrite msum_0, msum_of_unit; auto.\n    + destruct (IHn (f n) f) as (g & H1 & H2 & H3).\n      * intros; apply Hf2; omega.\n      * intros; apply Hf2; omega.\n      * exists (fun i => if eq_nat_dec i (f n) then 1 else g i).\n        split; [ | split ].\n        - rewrite msum_plus1, H1; auto.\n          replace k with (f n + S (k - f n -1)).\n          2: generalize (Hf1 n); intros; omega.\n          rewrite msum_plus; auto; f_equal.\n          ++ apply msum_ext.\n             intros i He.\n             destruct (eq_nat_dec i (f n)); try ring; omega.\n          ++ rewrite msum_S, msum_of_unit; auto.\n             ** repeat (rewrite plus_comm; simpl). \n                destruct (eq_nat_dec (f n) (f n)); try ring; omega.\n             ** intros i Hi.\n                destruct (eq_nat_dec (f n+S i) (f n)); try omega.\n                rewrite H3; omega.\n        - intros i Hi.\n          destruct (eq_nat_dec i (f n)); auto.\n          destruct (le_lt_dec (f n) i).\n          ++ rewrite H3; omega.\n          ++ apply H2; omega.\n        - intros i Hi.\n          generalize (Hf1 n); intros.\n          destruct (eq_nat_dec i (f n)); try omega.\n          apply H3; omega.\n  Qed.\n \n  Section sum_sum_regroup.\n\n    Variable (r n k : nat) (f : nat -> nat)\n             (Hf1 : forall i, i < n -> f i <= k) \n             (Hf2 : forall i j, i < j < n -> f i < f j).\n\n    Theorem sum_sum_regroup : { g | ∑ n (fun i => ∑ i (fun j => power (f i + f j) r))\n                                  = ∑ (2*k) (fun i => g i * power i r) \n                                  /\\ forall i, g i <= n }.\n    Proof.\n      revert n f Hf1 Hf2. \n      induction n as [ | p IHp ]; intros f Hf1 Hf2.\n      + exists (fun _ => 0); split; auto.\n        rewrite msum_0.\n        simpl; rewrite msum_of_unit; auto.\n      + destruct (IHp f) as (g & H1 & H2).\n        * intros; apply Hf1; omega.\n        * intros; apply Hf2; omega.\n        * destruct sum_regroup with (r := r) (n := p) (f := fun j => f p + f j) (k := 2*k)\n            as (g1 & G1 & G2 & G3).\n          - intros i Hi; generalize (@Hf1 p) (@Hf2 i p); intros; omega.\n          - intros i j H; generalize (@Hf2 i j); intros; omega.\n          - assert (forall i, g1 i <= 1) as G4.\n            { intro i; destruct (le_lt_dec (2*k) i); auto; rewrite G3; omega. }\n            exists (fun i => g i + g1 i); split.\n            ++ rewrite msum_plus1; auto.\n               rewrite H1, G1, <- msum_sum; auto.\n               2: intros; ring.\n               apply msum_ext; intros; ring.\n            ++ intros i.\n               generalize (H2 i) (G4 i); intros; omega.\n    Qed.\n\n  End sum_sum_regroup.\n\n  Section all_ones.\n\n    Let equation_inj x y a b : 1 <= x -> 1+x*a = y -> 1+x*b = y -> a = b.\n    Proof.\n      intros H1 H2 H3.\n      rewrite <- H3 in H2; clear y H3.\n      rewrite <- (@Nat.mul_cancel_l _ _ x); omega.\n    Qed.\n\n    Variables (r : nat) (Hr : 2 <= r).\n\n    Fact all_ones_equation l : 1+(r-1)*∑ l (fun i => power i r) = power l r.\n    Proof.\n      induction l as [ | l IHl ].\n      * rewrite msum_0, Nat.mul_0_r, power_0; auto.\n      * rewrite msum_plus1; auto.\n        rewrite Nat.mul_add_distr_l, power_S.\n        replace r with (1+(r-1)) at 4 by omega.\n        rewrite Nat.mul_add_distr_r.\n        rewrite <- IHl at 2; ring.\n    Qed.\n\n    Fact all_ones_dio l w : w = ∑ l (fun i => power i r) <-> 1+(r-1)*w = power l r.\n    Proof.\n      split.\n      + intros; subst; apply all_ones_equation.\n      + intros H.\n        apply equation_inj with (2 := H).\n        * omega.\n        * apply all_ones_equation.\n    Qed.\n\n  End all_ones.\n\n  Section const_1.\n\n    Variable (l q : nat) (Hl : 0 < l) (Hlq : l+1 < q).\n\n    Let Hq : 1 <= q.     Proof. omega. Qed. \n    Let Hq' : 0 < 4*q.   Proof. omega. Qed.\n    \n    Let r := (power (4*q) 2).\n\n    Let Hr' : 4 <= r.    Proof. apply (@power_mono_l 2 (4*q) 2); omega. Qed.\n    Let Hr :  2 <= r.    Proof. omega. Qed.\n\n    Section all_ones.\n\n      Variable (n w : nat) (Hw : w = ∑ n (fun i => power i r)).\n\n      Let Hw_0 : w = ∑ n (fun i => 1*power i r).\n      Proof. rewrite Hw; apply msum_ext; intros; ring. Qed.\n\n      Fact all_ones_joins : w = msum nat_join 0 n (fun i => 1*power i r).\n      Proof. \n        rewrite Hw_0.\n        apply sum_powers_ortho with (q := 4*q); auto; try omega.\n      Qed.\n\n      Let Hw_1 : 2*w = ∑ n (fun i => 2*power i r).\n      Proof. \n        rewrite Hw_0, <- sum_0n_scal_l.\n        apply msum_ext; intros; ring.\n      Qed.\n\n      Fact all_ones_2_joins : 2*w = msum nat_join 0 n (fun i => 2*power i r).\n      Proof.\n        rewrite Hw_1.\n        apply sum_powers_ortho with (q := 4*q); auto; try omega.\n        intros; omega.\n      Qed.\n\n    End all_ones.\n\n    Section increase.\n   \n      Variable (m k k' u w : nat) (f : nat -> nat) \n               (Hm : 2*m < r) \n               (Hf1 : forall i, i < m -> f i <= k)\n               (Hf2 : forall i j, i < j < m  -> f i < f j)\n               (Hw : w = ∑ k' (fun i => power i r))\n               (Hu : u = ∑ m (fun i => power (f i) r)).\n\n      Let Hf4 : forall i j, i < m -> j < m -> f i = f j -> i = j.\n      Proof. apply smono_upto_injective; auto. Qed.\n\n      Let u1 := ∑ m (fun i => power (2*f i) r).\n      Let u2 := ∑ m (fun i => ∑ i (fun j => 2*power (f i + f j) r)).\n\n      Fact const_u_square : u * u = u1 + u2.\n      Proof.\n        unfold u1, u2.\n        rewrite Hu, square_sum; f_equal.\n        + apply msum_ext; intros; rewrite <- power_plus; f_equal; omega.\n        + rewrite <- sum_0n_scal_l; apply msum_ext; intros i Hi.\n          rewrite <- sum_0n_scal_l; apply msum_ext; intros j Hj.\n          rewrite power_plus; ring.\n      Qed.\n\n      Let Hu1_0 : u1 = ∑ m (fun i => 1*power (2*f i) r).\n      Proof. apply msum_ext; intros; ring. Qed.\n\n      Let Hseq_u a : a <= m -> ∑ a (fun i => 1*power (2*f i) r) = msum nat_join 0 a (fun i => 1*power (2*f i) r).\n      Proof.\n        intros Ha.\n        apply sum_powers_ortho with (q := 4*q); auto; try omega.\n        intros i j Hi Hj ?; apply Hf4; omega.\n      Qed.\n\n      Let Hu1 : u1 = msum nat_join 0 m (fun i => 1*power (2*f i) r).\n      Proof. \n        rewrite Hu1_0; apply Hseq_u; auto.\n      Qed.\n\n      Let Hu2_0 : u2 = 2 * ∑ m (fun i => ∑ i (fun j => power (f i + f j) r)).\n      Proof.\n        unfold u2; rewrite <- sum_0n_scal_l; apply msum_ext.\n        intros; rewrite <- sum_0n_scal_l; apply msum_ext; auto.\n      Qed.\n\n      (* MAJOR change in the argumentation ... one cannot show\n         in generalize that the powers r^(f i + f j) are distincts\n         powers for the values j < i < n, hence it is not correct\n         than the sum reduces to a join ... it works when \n         f i = 2^i but not for an arbitrary (increasing function) f \n\n         So we rewrite ∑ {j < i < n} r^(f i + f j) as\n            ∑ {i < k} (g i)*r^i for some small g i <= n\n         supposing n is low compared to r *) \n         \n\n      Let g_full : { g | ∑ m (fun i => ∑ i (fun j => power (f i + f j) r))\n                      = ∑ (2*k) (fun i : nat => g i * power i r) \n                      /\\ forall i : nat, g i <= m }.\n      Proof. apply sum_sum_regroup; auto. Qed.\n \n      Let g := proj1_sig g_full.\n      Let Hg1 : u2 = ∑ (2*k) (fun i => (2*g i) * power i r).\n      Proof. \n        rewrite Hu2_0, (proj1 (proj2_sig g_full)), <- sum_0n_scal_l.\n        apply msum_ext; unfold g; intros; ring.\n      Qed.\n\n      Let Hg2 i : 2*g i <= 2*m.\n      Proof. apply mult_le_compat; auto; apply (proj2_sig g_full). Qed.\n\n      Let Hg3 i : 2*g i < r.\n      Proof. apply le_lt_trans with (1 := Hg2 _); auto. Qed.\n\n      Let Hu2 : u2 = msum nat_join 0 (2*k) (fun i => (2*g i) * power i r).  \n      Proof.\n        rewrite Hg1.\n        apply sum_powers_ortho with (q := 4*q); auto; omega.\n      Qed.\n  \n      Let Hu1_u2_1 : u1 ⇣ u2 = 0.\n      Proof.\n        rewrite Hu1, Hu2.\n        apply nat_ortho_joins.\n        intros i j Hi Hj.\n        destruct (eq_nat_dec j (2*f i)) as [ H | H ].\n        + unfold r; do 2 rewrite <- power_mult.\n          rewrite <- H.\n          rewrite nat_meet_mult_power2.\n          rewrite nat_meet_12n; auto.\n        + rewrite nat_meet_powers_neq with (q := 4*q); auto; omega.\n      Qed.\n\n      Let Hu1_u2 : u*u = u1 ⇡ u2.\n      Proof.\n        rewrite const_u_square.\n        apply nat_ortho_plus_join; auto.\n      Qed.\n   \n      Let Hw_1 : w = msum nat_join 0 k' (fun i => 1*power i r).\n      Proof. rewrite Hw; apply all_ones_joins; auto. Qed.\n\n      Let H2w_1 : 2*w = msum nat_join 0 k' (fun i => 2*power i r).\n      Proof. rewrite Hw; apply all_ones_2_joins; auto. Qed.\n\n      Let Hu2_w : u2 ⇣ w = 0.\n      Proof.\n        rewrite Hu2, Hw_1.\n        destruct (le_lt_dec k' (2*k)) as [ Hk | Hk ].\n        2: { apply nat_ortho_joins.\n             intros i j Hi Hj.\n             rewrite nat_meet_comm.\n             destruct (eq_nat_dec i j) as [ H | H ].\n             + subst j; rewrite nat_meet_powers_eq with (q := 4*q); auto.\n               rewrite nat_meet_12n; auto.\n             + apply nat_meet_powers_neq with (q := 4*q); auto; try omega. }\n        replace (2*k) with (k'+(2*k-k')) by omega.\n        rewrite msum_plus, nat_meet_comm, nat_meet_join_distr_l, nat_join_comm; auto.\n        rewrite (proj2 (nat_ortho_joins k' (2*k-k') _ _)), nat_join_0n.\n        2: { intros i j H1 H2.\n             apply nat_meet_powers_neq with (q := 4*q); auto; try omega. }\n        apply nat_ortho_joins.\n        intros i j Hi Hj.\n        destruct (eq_nat_dec i j) as [ H | H ].\n        + subst j; rewrite nat_meet_powers_eq with (q := 4*q); auto.\n          rewrite nat_meet_12n; auto.\n        + apply nat_meet_powers_neq with (q := 4*q); auto; try omega.\n      Qed.\n\n      Fact const_u1_prefix : { q | q <= m /\\ u*u ⇣ w = ∑ q (fun i => 1*power (2*f i) r) }.\n      Proof.\n        destruct inc_seq_split_lt with (n := m) (f := fun i => 2*f i) (k := k') as (a & H1 & H2 & H3).\n        + intros i j Hij; apply Hf2 in Hij; omega.\n        + exists a; split; auto.\n          rewrite Hu1_u2, nat_meet_comm, nat_meet_join_distr_l.\n          do 2 rewrite (nat_meet_comm w).\n          rewrite Hu2_w, nat_join_n0.\n          rewrite Hu1, Hw_1.\n          replace m with (a+(m-a)) by omega.\n          rewrite msum_plus, nat_meet_comm, nat_meet_join_distr_l.\n          rewrite nat_join_comm.\n          rewrite (proj2 (nat_ortho_joins k' (m-a) _ _)), nat_join_0n; auto.\n          3: apply nat_join_monoid.\n          * rewrite Hseq_u; auto.\n            rewrite nat_meet_comm.\n            apply binary_le_nat_meet.\n            apply nat_joins_binary_le.\n            intros i Hi.\n            exists (2*f i); split; auto.\n          * intros; apply  nat_meet_powers_neq with (q := 4*q); auto; try omega.\n            generalize (H3 (a + j)); intros; omega.\n      Qed. \n         \n      Hypothesis (Hk : 2*k < k').\n\n      Let Hu1_w : u1 ⇣ w = u1.\n      Proof.\n        apply binary_le_nat_meet.\n        rewrite Hu1, Hw_1.\n        apply nat_joins_binary_le.\n        intros i Hi.\n        exists (2*f i); split; auto.\n        apply le_lt_trans with (2 := Hk), mult_le_compat; auto.\n      Qed.\n\n      Let Hu1_2w : u1 ⇣ (2*w) = 0.\n      Proof.\n        rewrite H2w_1, Hu1, nat_ortho_joins.\n        intros i j Hi Hj.\n        destruct (eq_nat_dec j (2 * f i)) as [ H | H ].\n        + rewrite <- H, nat_meet_powers_eq with (q := 4*q); auto; try omega.\n          rewrite nat_meet_12; auto.\n        + apply nat_meet_powers_neq with (q := 4*q); auto; try omega.\n      Qed.\n\n      Fact const_u1_meet p : p = (u*u) ⇣ w <-> p = u1.\n      Proof.\n        rewrite Hu1_u2, nat_meet_comm, nat_meet_join_distr_l.\n        do 2 rewrite (nat_meet_comm w).\n        rewrite Hu1_w, Hu2_w, nat_join_n0; tauto.\n      Qed.\n\n      Fact const_u1_eq : (u*u) ⇣ w = u1.\n      Proof. apply const_u1_meet; auto. Qed.\n\n      Hypothesis Hf : forall i, i < m -> f i = power (S i) 2.\n\n      Let Hu2_1 : u2 = msum nat_join 0 m (fun i => msum nat_join 0 i (fun j => 2*power (f i + f j) r)).\n      Proof.\n        unfold u2.\n        apply double_sum_powers_ortho with (q := 4*q); auto; try omega.\n        + intros; omega.\n        + intros ? ? ? ? ? ?; repeat rewrite Hf; try omega.\n          intros E.\n          apply sum_2_power_2_injective in E; omega.\n      Qed.\n\n      (* This cannot be proved anymore without stronger hypothesis on f *) \n\n      Let Hu2_2w : u2 ⇣ (2*w) = u2.\n      Proof.\n        apply binary_le_nat_meet.\n        rewrite H2w_1, Hu2_1.\n        apply nat_double_joins_binary_le.\n        intros i j Hij.\n        exists (f i + f j); split; auto.\n        apply le_lt_trans with (2*f i); auto.\n        + apply Hf2 in Hij; omega.\n        + apply le_lt_trans with (2 := Hk), mult_le_compat; auto.\n          apply Hf1; omega.\n      Qed. \n\n      Fact const_u2_meet p : p = (u*u) ⇣ (2*w) <-> p = u2.\n      Proof.\n        rewrite Hu1_u2, nat_meet_comm, nat_meet_join_distr_l.\n        do 2 rewrite (nat_meet_comm (2*w)).\n        rewrite Hu1_2w, Hu2_2w, nat_join_0n; tauto.\n      Qed.\n\n    End increase.\n\n    Let Hl'' : 2*l < r.\n    Proof.\n      unfold r.\n      rewrite (mult_comm _ q), power_mult.\n      change (power 4 2) with 16.\n      apply power_smono_l with (x := 16) in Hlq; try omega.\n      apply le_lt_trans with (2 := Hlq).\n      rewrite plus_comm; simpl plus; rewrite power_S.\n      apply mult_le_compat; try omega.\n      apply power_ge_n; omega.\n    Qed.\n\n    Section const_1_cn.\n\n      (* Perhaps you should encode the predicate that \n          \n           w = ∑ {i=0..2^{l+1}} r^i\n           u = ∑ {1..l} r^{2^i} and u1 = u*u ⇣ w\n\n         as diophantine and use that predicate because\n         it is used for Const1 and the product and CodeNat *)\n\n      Variable (u u1 : nat) (Hu  : u = ∑ l (fun i => power (power (S i) 2) r))\n                            (Hu1 : u1 = ∑ l (fun i => power (power (S (S i)) 2) r)).\n \n      Let w  := ∑ (S (power (S l) 2)) (fun i => power i r).\n (*     Let u1 := ∑ l (fun i => power (power (S (S i)) 2) r). *)\n      Let u2 := ∑ l (fun i => ∑ i (fun j => 2*power (power (S i) 2 + power (S j) 2) r)).\n \n      Let H18 : 1+(r-1)*w = power (S (power (S l) 2)) r.\n      Proof. rewrite <- all_ones_dio; auto. Qed.\n\n      Let H19 : u*u = u1 + u2.\n      Proof.\n        rewrite Hu1. \n        apply const_u_square with (w := w) (2 := eq_refl); auto.\n      Qed.\n\n      Let k := S (power (S l) 2).\n      Let f i := power (S i) 2.\n\n      Let Hf1 i : i < l -> 2*f i < k.\n      Proof.\n        unfold k, f.\n        intros; rewrite <- power_S; apply le_n_S, power_mono_l; omega.\n      Qed.\n\n      Let Hf2 i j : i < j < l -> f i < f j.\n      Proof. intros; apply power_smono_l; omega. Qed.\n\n      Let Hf3 i1 j1 i2 j2 : j1 <= i1 < l -> j2 <= i2 < l -> f i1 + f j1 = f i2 + f j2 -> i1 = i2 /\\ j1 = j2.\n      Proof.\n        unfold f; intros H1 H2 E.\n        apply sum_2_power_2_injective in E; omega.\n      Qed.\n\n      Let H20 : u1 = (u*u) ⇣ w.\n      Proof. \n        rewrite const_u1_meet with (k := power l 2) (m := l) (f := f); auto.\n        * intros i Hi; specialize (Hf1 Hi).\n          revert Hf1; unfold k; rewrite power_S; intros; omega.\n        * rewrite <- power_S; auto.\n      Qed. \n\n      Let H21 : u2 = (u*u) ⇣ (2*w).\n      Proof. \n        rewrite const_u2_meet with (k := power l 2) (m := l) (f := f); auto.\n        * intros i Hi; specialize (Hf1 Hi).\n          revert Hf1; unfold k; rewrite power_S; intros; omega.\n        * rewrite <- power_S; auto.\n     Qed. \n \n      Let H22 : power 2 r + u1 = u + power (power (S l) 2) r.\n      Proof.\n        rewrite Hu, Hu1.\n        destruct l.\n        + do 2 rewrite msum_0.\n          rewrite power_1; auto.\n        + rewrite msum_plus1, msum_S; auto.\n          rewrite power_1; ring.\n      Qed.\n  \n      Let H23 : divides (power 4 r) u1.\n      Proof.\n        rewrite Hu1.\n        apply divides_msum.\n        intros i _.\n        apply divides_power.\n        apply (@power_mono_l 2 _ 2); omega.\n      Qed.\n\n      Lemma const1_cn : exists w u2,    1+(r-1)*w = power (S (power (S l) 2)) r\n                                     /\\ u*u = u1 + u2\n                                     /\\ u1 = (u*u) ⇣ w\n                                     /\\ u2 = (u*u) ⇣ (2*w)\n                                     /\\ power 2 r + u1 = u + power (power (S l) 2) r\n                                     /\\ divides (power 4 r) u1.\n      Proof.\n        exists w, u2; repeat (split; auto).\n      Qed.\n\n    End const_1_cn.\n\n    Section const_1_cs.\n\n      Variable (w u u1 u2 : nat).\n\n      Hypothesis (H18 : 1+(r-1)*w = power (S (power (S l) 2)) r)\n                 (H19 : u*u = u1 + u2)\n                 (H20 : u1 = (u*u) ⇣ w)\n                 (H21 : u2 = (u*u) ⇣ (2*w))\n                 (H22 : power 2 r + u1 = u + power (power (S l) 2) r)\n                 (H23 : divides (power 4 r) u1).\n\n      Let Hw_0 : w = ∑ (S (power (S l) 2)) (fun i => power i r).\n      Proof. apply all_ones_dio; auto. Qed.\n\n      Let Hw_1 : w = ∑ (S (power (S l) 2)) (fun i => 1*power i r).\n      Proof. rewrite Hw_0; apply msum_ext; intros; ring. Qed.\n\n      Let Hw : w = msum nat_join 0 (S (power (S l) 2)) (fun i => 1*power i r).\n      Proof. apply all_ones_joins; auto. Qed.\n\n      Let H2w : 2*w = msum nat_join 0 (S (power (S l) 2)) (fun i => 2*power i r).\n      Proof. apply all_ones_2_joins; auto. Qed.\n    \n      Let Hu1_0 : u1 ≲ ∑ (S (power (S l) 2)) (fun i => 1*power i r).\n      Proof. rewrite H20, <- Hw_1; auto. Qed.\n\n      Let mk_full : { m : nat & { k | u1 = ∑ (S m) (fun i => power (k i) r) \n                                /\\ m <= power (S l) 2\n                                /\\ (forall i, i < S m -> k i <= power (S l) 2) \n                                /\\ forall i j, i < j < S m -> k i < k j } }.\n      Proof.\n        assert ({ k : nat &\n                 { g : nat -> nat & \n                 { h | u1 = ∑ k (fun i => g i * power (h i) r)\n                     /\\ k <= S (power (S l) 2)\n                     /\\ (forall i, i < k -> g i <> 0 /\\ g i ≲ 1)\n                     /\\ (forall i, i < k -> h i < S (power (S l) 2))\n                     /\\ (forall i j, i < j < k -> h i < h j) } } }) as H.\n        { apply (@sum_powers_binary_le_inv _ Hq' r eq_refl _ (fun _ => _) (fun i => i)); auto.\n          intros; omega. }\n        destruct H as (m' & g & h & H1 & H2 & H3 & H4 & H5).\n        assert (H6 : forall i, i < m' -> g i = 1).\n        { intros i Hi; generalize (H3 _ Hi).\n          intros (? & G2); apply binary_le_le in G2; omega. }\n        assert (H7 : u1 = ∑ m' (fun i => 1 * power (h i) r)).\n        { rewrite H1; apply msum_ext; intros; rewrite H6; try ring; omega. }\n        assert (H8 : u1 = ∑ m' (fun i => power (h i) r)).\n        { rewrite H7; apply msum_ext; intros; ring. }\n        assert (H9 : m' <> 0).\n        { intros E; rewrite E, msum_0 in H1.\n          assert (power 2 r < power (power (S l) 2) r) as C.\n          { apply power_smono_l; auto.\n            apply (@power_smono_l 1 _ 2); omega. }\n          omega. }\n        destruct m' as [ | m ]; try omega.\n        exists m, h; repeat (split; auto).\n        + omega.\n        + intros i; generalize (H4 i); intros; omega.\n      Qed.\n\n      Let m := projT1 mk_full.\n      Let k := proj1_sig (projT2 mk_full).\n\n      Let Hu1 : u1 = ∑ (S m) (fun i => power (k i) r).        Proof. apply (proj2_sig (projT2 mk_full)). Qed.\n      Let Hm : m <= (power (S l) 2).                          Proof. apply (proj2_sig (projT2 mk_full)). Qed.\n      Let Hk1 : forall i, i < S m -> k i <= power (S l) 2.    Proof. apply (proj2_sig (projT2 mk_full)). Qed.\n      Let Hk2 : forall i j, i < j < S m -> k i < k j.         Proof. apply (proj2_sig (projT2 mk_full)). Qed.\n\n      Let Hh_0 : 4 <= k 0.\n      Proof.\n        rewrite Hu1 in H23.\n        apply power_divides_sum_power in H23; auto; try omega.\n      Qed.\n\n      Let f1 i := match i with 0 => 2 | S i => k i end.\n      Let f2 i := if le_lt_dec i m then power (S l) 2 else k i.\n\n      Let Hf1_0 : forall i, i <= S m -> f1 i < S (power (S l) 2).\n      Proof.\n        intros [ | i ] Hi; simpl; apply le_n_S.\n        + rewrite power_S.\n          change 2 with (2*1) at 1.\n          apply mult_le_compat; auto.\n          apply power_ge_1; omega.\n        + apply Hk1; auto.\n      Qed.\n\n      Let Hf1_1 : forall i j, i < j <= S m -> f1 i < f1 j.\n      Proof.\n        intros [ | i ] [ | j ] Hij; simpl; try omega.\n        * apply lt_le_trans with (k 0); try omega.\n          destruct j; auto; apply lt_le_weak, Hk2; omega.\n        * apply Hk2; omega.\n      Qed.\n\n      Let Hf1_2 : ∑ (S (S m)) (fun i => power (f1 i) r) = u + power (power (S l) 2) r.\n      Proof.\n        rewrite msum_S; unfold f1.\n        rewrite <- Hu1; auto.\n      Qed.\n\n      Let Hh_1 : k m = power (S l) 2.\n      Proof.\n        destruct (le_lt_dec (power (S l) 2) (k m)) as [ H | H ].\n        + apply le_antisym; auto.\n        + assert (∑ (S (S m)) (fun i => power (f1 i) r) < power (power (S l) 2) r); try omega.\n          apply sum_powers_inc_lt; auto.\n          - intros [ | i ] Hi; simpl.\n            * apply (@power_smono_l 1 _ 2); omega.\n            * apply le_lt_trans with (2 := H).\n              destruct (eq_nat_dec i m); subst; auto.\n              apply lt_le_weak, Hk2; omega.\n          - intros; apply Hf1_1; omega.\n      Qed.\n \n      Let Hu : u = ∑ (S m) (fun i => power (f1 i) r).\n      Proof.\n        rewrite msum_plus1 in Hf1_2; auto.\n        simpl f1 at 2 in Hf1_2.\n        rewrite Hh_1 in Hf1_2.\n        omega.\n      Qed.\n        \n      Let Huu : u*u = ∑ (S m) (fun i => power (2*f1 i) r)\n                    + ∑ (S m) (fun i => ∑ i (fun j => 2*power (f1 i + f1 j) r)).\n      Proof.\n        rewrite Hu, square_sum; f_equal.\n        + apply msum_ext; intros; rewrite <- power_plus; f_equal; omega.\n        + rewrite <- sum_0n_scal_l; apply msum_ext; intros i Hi.\n          rewrite <- sum_0n_scal_l; apply msum_ext; intros j Hj.\n          rewrite power_plus; ring.\n      Qed.\n\n      (* This one should not be that hard given S l < q but to check *)\n\n      Let HSl_q : 2 * S (power (S l) 2) < power (2 * q) 2.\n      Proof.\n        rewrite <- (mult_2_eq_plus q), power_plus.\n        apply le_lt_trans with (2*power q 2).\n        + apply mult_le_compat; auto.\n          apply power_smono_l; omega.\n        + assert (power 1 2 < power q 2) as H.\n          { apply power_smono_l; omega. }\n          rewrite power_1 in H.\n          apply Nat.mul_lt_mono_pos_r; omega.\n      Qed.\n  \n      Let Hu1_1 : { d | d <= S m /\\ u1 = ∑ d (fun i => power (2*f1 i) r) }.\n      Proof.\n        destruct const_u1_prefix with (m := S m) (k := power (S l) 2) (k' := S (power (S l) 2))\n           (u := u) (w := w) (f := fun i => f1 i)\n           as (d & H1 & H2); auto.\n        + unfold r.\n          apply le_lt_trans with (2*S (power (S l) 2)); try omega.\n          apply le_lt_trans with (power (S (S (S l))) 2).\n          do 4 rewrite power_S.\n          * generalize (@power_ge_1 l 2); intros; omega.\n          * apply power_smono_l; omega.\n        + intros i Hi; generalize (@Hf1_0 i); intros; omega.\n        + intros; apply Hf1_1; omega.\n        + exists d; split; auto.\n          rewrite H20, H2.\n          apply msum_ext; intros; ring.\n      Qed.\n\n      Let Hk_final : k 0 = 4 /\\ forall i, i < m -> k (S i) = 2*k i.\n      Proof.\n        destruct Hu1_1 as (d & Hd1 & E).\n        rewrite Hu1 in E.\n        apply sum_powers_injective in E; auto.\n        + destruct E as (? & E); subst d; split.\n          * rewrite E; try omega; auto.\n          * intros; rewrite E; auto; omega.\n        + intros i j H; specialize (@Hf1_1 i j); intros; omega.\n      Qed.\n\n      Let Hk_is_power i : i <= m -> k i = power (S (S i)) 2.\n      Proof.\n         induction i as [ | i IHi ]; intros Hi.\n         + rewrite (proj1 Hk_final); auto.\n         + rewrite (proj2 Hk_final), IHi, <- power_S; auto; omega.\n      Qed.\n\n      Let Hm_is_l : S m = l.\n      Proof.\n        rewrite Hk_is_power in Hh_1; auto.\n        apply power_2_inj in Hh_1; omega.\n      Qed.\n        \n      Fact obtain_u_u1_value :  u  = ∑ l (fun i => power (power (S i) 2) r)\n                             /\\ u1 = ∑ l (fun i => power (power (S (S i)) 2) r).\n      Proof.\n        split.\n        + rewrite <- Hm_is_l, Hu.\n          apply msum_ext.\n          intros [ | i ]; simpl; auto.\n          intros; rewrite Hk_is_power; auto; omega.\n        + rewrite <- Hm_is_l, Hu1.\n          apply msum_ext.\n          intros [ | i ]; simpl; auto.\n          * rewrite Hk_is_power; auto; omega.\n          * intros; rewrite Hk_is_power; auto; omega.\n      Qed.\n\n    End const_1_cs.\n\n  End const_1.\n\n  Variable (l q : nat).\n\n  Notation r := (power (4*q) 2).\n\n  Definition seqs_of_ones u u1 :=\n                   l+1 < q \n                /\\ u  = ∑ l (fun i => power (power (S i) 2) r)\n                /\\ u1 = ∑ l (fun i => power (power (S (S i)) 2) r).\n\n  (* This lemma shows that seqs_of_ones can be encoded by a diophantine expression *)\n\n  Lemma seqs_of_ones_dio u u1 :\n            seqs_of_ones u u1 \n        <-> l = 0 /\\ u = 0 /\\ u1 = 0 /\\ 2 <= q\n         \\/ 0 < l /\\ l+1 < q\n         /\\ exists u2 w r0 r1 p1 p2,\n                r0 = r \n             /\\ r1+1 = r0\n             /\\ p1 = power (1+l) 2\n             /\\ p2 = power p1 r0\n             /\\ 1+r1*w = r0*p2\n             /\\ u*u = u1 + u2\n             /\\ u1 = (u*u) ⇣ w\n             /\\ u2 = (u*u) ⇣ (2*w)\n             /\\ r0*r0 + u1 = u + p2\n             /\\ divides (r0*r0*r0*r0) u1. \n  Proof.\n    split.\n    + intros (H2 & H3 & H4).\n      destruct (le_lt_dec l 0) as [ H1 | H1 ].\n      - assert (l=0) by omega; subst l.\n        rewrite msum_0 in H3, H4; subst; left; omega.\n      - right; split; auto; split; auto.\n        destruct (const1_cn H1 H2 H3 H4) as (w & u2 & E1 & E2 & E3 & E4 & E5 & E6).\n        exists u2, w, r, (r-1), (power (S l) 2), (power (power (S l) 2) r); repeat (split; auto).\n        * generalize (@power_ge_1 (4*q) 2); intros; omega.\n        * revert E5; rewrite power_S, power_1; auto.\n        * revert E6; do 3 rewrite power_S; rewrite power_1.\n          repeat rewrite mult_assoc; auto.\n    + intros [ (H1 & H2 & H3 & H4)\n             | (H1 & H2 & u2 & w & r0 & r1 & p1 & p2 & ? & H0 & ? & ? & E1 & E2 & E3 & E4 & E5 & E6) ].\n      - red; subst; do 2 rewrite msum_0; omega.\n      - assert (r1 = r0-1) by omega; clear H0.\n        subst r0 r1 p1 p2; split; auto.\n        apply obtain_u_u1_value with w u2; auto.\n        * rewrite power_S, power_1; auto.\n        * do 3 rewrite power_S; rewrite power_1.\n          repeat rewrite mult_assoc; auto.\n  Qed.\n\n  Definition is_cipher_of f a :=\n                 l+1 < q\n              /\\ (forall i, i < l -> f i < power q 2)\n              /\\ a = ∑ l (fun i => f i * power (power (S i) 2) r).\n\n  Fact is_cipher_of_0 f a : l = 0 -> is_cipher_of f a <-> 1 < q /\\ a = 0.\n  Proof.\n    intros ?; unfold is_cipher_of; subst l.\n    rewrite msum_0; simpl.\n    repeat (split; try tauto).\n    intros; omega.\n  Qed.\n\n  Fact is_cipher_of_inj f1 f2 a : is_cipher_of f1 a -> is_cipher_of f2 a -> forall i, i < l -> f1 i = f2 i.\n  Proof.\n    intros (H1 & H2 & H3) (_ & H4 & H5).\n    rewrite H3 in H5.\n    revert H5; apply power_decomp_unique.\n    + apply (@power_mono_l 1 _ 2); omega.\n    + intros; apply power_smono_l; omega.\n    + intros i Hi; apply lt_le_trans with (1 := H2 _ Hi), power_mono_l; omega.\n    + intros i Hi; apply lt_le_trans with (1 := H4 _ Hi), power_mono_l; omega.\n  Qed.\n\n  Fact is_cipher_of_fun f1 f2 a b : \n          (forall i, i < l -> f1 i = f2 i)\n        -> is_cipher_of f1 a \n        -> is_cipher_of f2 b\n        -> a = b.\n  Proof.\n    intros H1 (_ & _ & H2) (_ & _ & H3); subst a b.\n    apply msum_ext; intros; f_equal; auto.\n  Qed.\n\n  Lemma is_cipher_of_equiv f1 f2 a b : \n           is_cipher_of f1 a \n        -> is_cipher_of f2 b\n        -> a = b <-> forall i, i < l -> f1 i = f2 i.\n  Proof.\n    intros Ha Hb; split.\n    + intro; subst; revert Ha Hb; apply is_cipher_of_inj.\n    + intro; revert Ha Hb; apply is_cipher_of_fun; auto.\n  Qed.\n\n  Lemma is_cipher_of_const_1 u : 0 < l -> is_cipher_of (fun _ => 1) u\n                                     <-> l+1 < q /\\ exists u1, seqs_of_ones u u1.\n  Proof.\n    intros Hl.\n    split.\n    + intros (H1 & H2 & H3); split; auto.\n      exists (∑ l (fun i => power (power (S (S i)) 2) r)).\n      rewrite H3; split; auto; split; auto.\n      apply msum_ext; intros; ring.\n    + intros (H1 & u1 & _ & H2).\n      apply proj1 in H2.\n      repeat (split; auto).\n      * intros; apply (@power_smono_l 0); omega.\n      * rewrite H2; apply msum_ext; intros; ring.\n  Qed.\n\n  Fact is_cipher_of_u : l+1 < q -> is_cipher_of (fun _ => 1) (∑ l (fun i => power (power (S i) 2) r)).\n  Proof.\n    intros H; split; auto; split.\n    + intros; apply (@power_mono_l 1 _ 2); omega.\n    + apply msum_ext; intros; omega.\n  Qed.\n (*\n  Fact is_cipher_of_u1 : l+1 < q -> is_cipher_of (fun _ => 1) (∑ l (fun i => power (power (S (S i)) 2) r)).\n  Proof.\n    intros H; split; auto; split.\n    + intros; apply (@power_mono_l 1 _ 2); omega.\n    + apply msum_ext; intros; omega.\n  Qed.\n *)\n\n  Definition the_cipher f : l+1 < q -> (forall i, i < l -> f i < power q 2) -> { c | is_cipher_of f c }.\n  Proof.\n    intros H1 H2.\n    exists (∑ l (fun i => f i * power (power (S i) 2) r)); split; auto.\n  Qed.\n\n  Definition Code a := exists f, is_cipher_of f a.\n\n  Lemma Code_dio a : Code a <-> l = 0 /\\ 1 < q /\\ a = 0\n                             \\/ 0 < l /\\ l+1 < q /\\ exists p u u1, p+1 = power q 2 /\\ seqs_of_ones u u1 /\\ a ≲ p*u.\n  Proof.\n    split.\n    + intros (f & H1 & H2 & H3).\n      destruct (eq_nat_dec l 0) as [ Hl | Hl ].\n      * left; subst l; rewrite msum_0 in H3; omega.\n      * right; split; try omega; split; auto.\n        exists (power q 2-1), (∑ l (fun i => power (power (S i) 2) r)), (∑ l (fun i => power (power (S (S i)) 2) r)).\n        repeat (split; auto).\n        - generalize (@power_ge_1 q 2); intros; omega.\n        - rewrite H3.\n          apply sum_power_binary_lt with (q := 4*q); auto; try omega.\n          intros; apply power_smono_l; omega.\n    + intros [ (H1 & H2 & H3) | (H1 & H2 & p & u1 & u2 & ? & H3 & H4) ].\n      * exists (fun _ => 0); subst a; apply is_cipher_of_0; auto.\n      * destruct H3 as (_ & H3 & _).\n        assert (p = power q 2 -1) by omega; subst p.\n        rewrite H3 in H4. \n        apply sum_power_binary_lt_inv with (q := 4*q) (e := fun i => power (S i) 2) in H4; auto; try omega.\n        2,3: intros; apply power_smono_l; omega.\n        destruct H4 as (f & H4 & H5).\n        exists f; split; auto.\n  Qed.\n\n  Definition Const c v := exists f, is_cipher_of f v /\\ forall i, i < l -> f i = c.\n\n  Lemma Const_dio c v : Const c v <-> l = 0 /\\ 1 < q /\\ v = 0\n                                   \\/ 0 < l /\\ l+1 < q /\\\n                                      exists p u u1, p = power q 2 /\\ c < p /\\ seqs_of_ones u u1 /\\ v = c*u.\n  Proof.\n    split.\n    + intros (f & (H1 & H2 & H3) & H4).\n      destruct (eq_nat_dec l 0) as [ Hl | Hl ].\n      * left; subst l; rewrite msum_0 in H3; omega.\n      * right; split; try omega; split; auto.\n        exists (power q 2), (∑ l (fun i => power (power (S i) 2) r)), (∑ l (fun i => power (power (S (S i)) 2) r)).\n        repeat (split; auto).\n        - rewrite <- (H4 0); try omega; apply H2; omega.\n        - rewrite H3, <- sum_0n_scal_l; apply msum_ext.\n          intros; f_equal; auto.\n    + intros [ (H1 & H2 & H3) | (H1 & H2 & p & u1 & u2 & ? & H3 & H4 & H5) ].\n      * exists (fun _ => 0); subst v; split.\n        - apply is_cipher_of_0; auto.\n        - subst l; intros; omega.\n      * destruct H4 as (_ & H4 & _).\n        rewrite H4, <- sum_0n_scal_l in H5.\n        exists (fun _ => c); split; auto.\n        split; auto; split; auto.\n        intros; omega.\n  Qed.\n\n  Let Hr : 1 < q -> 4 <= r. \n  Proof.\n    intros H.\n    replace (4*q) with (2*q+2*q) by omega.\n    rewrite power_plus.\n    change 4 with ((power 1 2)*(power 1 2)); apply mult_le_compat;\n    apply power_mono_l; try omega.\n  Qed.\n\n  Section plus.\n\n    Variable (a b c : nat-> nat) (ca cb cc : nat) \n             (Ha : is_cipher_of a ca)\n             (Hb : is_cipher_of b cb) \n             (Hc : is_cipher_of c cc).\n\n    Definition Code_plus := ca = cb + cc.\n \n    Lemma Code_plus_spec : Code_plus <-> forall i, i < l -> a i = b i + c i.\n    Proof.\n      symmetry; unfold Code_plus.\n      destruct Ha as (H & Ha1 & Ha2).\n      destruct Hb as (_ & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      destruct (eq_nat_dec l 0) as [ | Hl ].\n      + subst l; rewrite msum_0 in *; split; intros; omega.\n      + rewrite Hc2, Ha2, Hb2, <- sum_0n_distr_in_out.\n        split.\n        * intros; apply msum_ext; intros; f_equal; auto.\n        * intros E i Hi. \n          apply power_decomp_unique with (i := i) in E; auto; try omega; clear i Hi.\n          - intros; apply power_smono_l; omega.\n          - intros i Hi; apply lt_le_trans with (1 := Ha1 _ Hi), power_mono_l; omega.\n          - intros i Hi.\n            apply lt_le_trans with (power (S q) 2).\n            ++ rewrite power_S, <- mult_2_eq_plus.\n               generalize (Hb1 _ Hi) (Hc1 _ Hi); omega.\n            ++ apply power_mono_l; omega.\n    Qed.\n\n  End plus.\n\n  Notation u := (∑ l (fun i => power (power (S i) 2) r)).\n  Notation u1 := (∑ l (fun i => power (power (S (S i)) 2) r)).\n\n  Section mult_utils.\n \n    Variable (b c : nat-> nat) (cb cc : nat) \n             (Hb : is_cipher_of b cb) \n             (Hc : is_cipher_of c cc).\n\n    Let eq1 :    cb*cc = ∑ l (fun i => (b i*c i)*power (power (S (S i)) 2) r)\n                       + ∑ l (fun i => ∑ i (fun j => (b i*c j + b j*c i)*power (power (S i) 2 + power (S j) 2) r)).\n    Proof.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      rewrite Hb2, Hc2, product_sums; f_equal.\n      * apply msum_ext; intros; rewrite (power_S (S _)).\n        rewrite <- (mult_2_eq_plus (power _ _)), power_plus; ring.\n      * apply msum_ext; intros i Hi.\n        apply msum_ext; intros j Hj.\n        rewrite power_plus; ring.\n    Qed.\n\n    Let Hbc_1 i : i < l -> b i * c i < r.\n    Proof.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      intro; apply mult_lt_power_2_4; auto.\n    Qed.\n  \n    Let Hbc_2 i j : i < l -> j < l -> b i * c j + b j * c i < r.\n    Proof.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      intros; apply mult_lt_power_2_4'; auto.\n    Qed.\n\n    Let Hbc_3 : ∑ l (fun i => (b i*c i)*power (power (S (S i)) 2) r) \n              = msum nat_join 0 l (fun i => (b i*c i)*power (power (S (S i)) 2) r).\n    Proof.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      apply sum_powers_ortho with (q := 4*q); try omega; auto.\n      intros ? ? ? ? E; apply power_2_inj in E; omega.\n    Qed.\n\n    Let Hbc_4 : ∑ l (fun i => ∑ i (fun j => (b i*c j + b j*c i)*power (power (S i) 2 + power (S j) 2) r))\n              = msum nat_join 0 l (fun i => \n                           msum nat_join 0 i (fun j => (b i*c j + b j*c i)*power (power (S i) 2 + power (S j) 2) r)).\n    Proof.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      rewrite double_sum_powers_ortho with (q := 4*q); auto; try omega.\n      + intros; apply Hbc_2; omega.\n      + intros ? ? ? ? ? ? E; apply sum_2_power_2_injective in E; omega.\n    Qed.\n    \n    Let eq2 :   cb*cc = msum nat_join 0 l (fun i => (b i*c i)*power (power (S (S i)) 2) r)\n                      ⇡ msum nat_join 0 l (fun i => \n                           msum nat_join 0 i (fun j => (b i*c j + b j*c i)*power (power (S i) 2 + power (S j) 2) r)).\n    Proof.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      rewrite eq1, Hbc_3, Hbc_4.\n      apply nat_ortho_plus_join.\n      apply nat_ortho_joins.\n      intros i j Hi Hj; apply nat_ortho_joins_left.\n      intros k Hk.\n      apply nat_meet_powers_neq with (q := 4*q); auto; try omega.\n      * apply power_2_n_ij_neq; omega.\n      * apply Hbc_2; omega.\n    Qed.\n\n    Let Hr_1 : (r-1)*u1 = ∑ l (fun i => (r-1)*power (power (S (S i)) 2) r).\n    Proof. rewrite sum_0n_scal_l; auto. Qed.\n\n    Let Hr_2 : (r-1)*u1 = msum nat_join 0 l (fun i => (r-1)*power (power (S (S i)) 2) r).\n    Proof.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      rewrite Hr_1.\n      apply sum_powers_ortho with (q := 4*q); auto; try omega.\n      + intros; omega.\n      + intros ? ? ? ? E; apply power_2_inj in E; omega.\n    Qed.\n   \n    Fact cipher_mult_eq : (cb*cc)⇣((r-1)*u1) = ∑ l (fun i => (b i*c i)*power (power (S (S i)) 2) r).\n    Proof.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      rewrite eq2, Hbc_3, Hr_2.\n      rewrite nat_meet_comm, nat_meet_join_distr_l.\n      rewrite <- Hr_2 at 1; rewrite Hr_1, <- Hbc_3.\n      rewrite meet_sum_powers with (q := 4*q); auto; try (intros; omega).\n      2: intros; apply power_smono_l; omega.\n      rewrite (proj2 (nat_ortho_joins _ _ _ _)), nat_join_n0.\n      * apply msum_ext; intros i Hi; f_equal.\n        rewrite nat_meet_comm; apply binary_le_nat_meet, power_2_minus_1_gt; auto.\n      * intros i j Hi Hj.\n        apply nat_ortho_joins_left.\n        intros k Hk; apply nat_meet_powers_neq with (q := 4*q); auto; try omega.\n        + apply power_2_n_ij_neq; omega.\n        + apply Hbc_2; omega.\n    Qed.\n\n  End mult_utils.\n  \n  Section mult.\n\n    Variable (a b c : nat-> nat) (ca cb cc : nat) \n             (Ha : is_cipher_of a ca)\n             (Hb : is_cipher_of b cb) \n             (Hc : is_cipher_of c cc).\n\n    Definition Code_mult := \n                l = 0 \n             \\/ l <> 0 \n             /\\ exists v v1 r' r'' p, \n                        r'' = r \n                     /\\ r'' = r'+1 \n                     /\\ seqs_of_ones v v1 \n                     /\\ p = (ca*v)⇣(r'*v1) \n                     /\\ p = (cb*cc)⇣(r'*v1).\n\n    Lemma Code_mult_spec : Code_mult <-> forall i, i < l -> a i = b i * c i. \n    Proof.\n      unfold Code_mult; symmetry.\n      destruct Ha as (Hlq & Ha1 & Ha2).\n      destruct Hb as (_ & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      destruct (eq_nat_dec l 0) as [ | Hl ].\n      + subst l; split; intros; auto; omega.\n      + split.\n        * intros H; right; split; try omega.\n          exists u, u1, (r-1), r, (ca * u ⇣ ((r-1) * u1)).\n          split; auto; split; try omega.\n          repeat (split; auto).\n          generalize (is_cipher_of_u Hlq); intros H2.\n          rewrite cipher_mult_eq with (1 := Ha) (2 := H2).\n          rewrite cipher_mult_eq with (1 := Hb) (2 := Hc).\n          apply msum_ext; intros; rewrite H; try ring; omega.\n        * intros [ | (_ & v & v1 & r' & r'' & p & H0 & H1 & H2 & H3 & H4) ]; try (destruct Hl; auto; fail).\n          destruct H2 as (_ & ? & ?); subst v v1.\n          rewrite H3 in H4.\n          revert H4.\n          generalize (is_cipher_of_u Hlq); intros H2.\n          replace r' with (r-1) by omega.\n          rewrite cipher_mult_eq with (1 := Ha) (2 := H2).\n          rewrite cipher_mult_eq with (1 := Hb) (2 := Hc).\n          intros E.\n          intros i Hi. \n          rewrite <- power_decomp_unique with (5 := E); auto; try omega.\n          - intros; apply power_smono_l; omega.\n          - intros j Hj; rewrite Nat.mul_1_r.\n            apply lt_le_trans with (1 := Ha1 _ Hj), power_mono_l; omega.\n          - intros; apply mult_lt_power_2_4; auto.\n    Qed.\n\n  End mult.\n\n  Section inc_seq.\n\n    Definition CodeNat c := is_cipher_of (fun i => i) c.\n\n    Let IncSeq_dio_priv y : CodeNat y <-> l = 0 /\\ 1 < q /\\ y = 0 \n                                  \\/ 0 < l \n                                  /\\ exists z v v1, \n                                        seqs_of_ones v v1 \n                                     /\\ Code y\n                                     /\\ Code z\n                                     /\\ y + l*(power (power (S l) 2) r) = (z*v)⇣((r-1) * v1)\n                                     /\\ y+v1+power (power 1 2) r = z + power (power (S l) 2) r.\n    Proof.\n      split.\n      + intros (H1 & H2 & H3).\n        destruct (le_lt_dec l 0) as [ | Hl ].\n        - assert (l = 0) by omega; subst l.\n          rewrite msum_0 in H3; left; omega.\n        - right; split; auto.\n          exists (∑ l (fun i => (S i) * power (power (S i) 2) r)), u, u1; split; auto.\n          { split; auto. }\n          split.\n          { rewrite H3; exists (fun i => i); split; auto. }\n          split.\n          { exists S; repeat (split; auto).\n            intros; apply lt_le_trans with q; try omega.\n            apply power_ge_n; auto. }\n          split.\n          { rewrite cipher_mult_eq with (b := S) (c := fun _ => 1).\n            * rewrite H3.\n              rewrite <- msum_plus1 with (f := fun i => i*power (power (S i) 2) r); auto.\n              rewrite msum_S, Nat.mul_0_l, Nat.add_0_l.\n              apply msum_ext; intros; ring.\n            * repeat split; auto; intros.\n              apply lt_le_trans with q; try omega.\n              apply power_ge_n; auto.\n            * apply is_cipher_of_u; auto. }\n          { rewrite H3.\n            destruct l as [ | l' ]; try omega.\n            rewrite msum_S, Nat.mul_0_l, Nat.add_0_l.\n            rewrite msum_plus1; auto.\n            rewrite plus_assoc.\n            rewrite msum_S.\n            rewrite <- msum_sum; auto.\n            2: intros; ring.\n            rewrite Nat.mul_1_l, plus_comm.\n            repeat rewrite <- plus_assoc; do 2 f_equal.\n            apply msum_ext; intros; ring. }\n      + intros [ (H1 & H2 & H3) | (Hl & z & v & v1 & H1 & H2 & H3 & H4 & H5) ].\n        - split; subst; auto; split; intros; try omega.\n          rewrite msum_0; auto.\n        - destruct H1 as (Hq & ? & ?); subst v v1.\n          split; auto; split.\n          { intros i Hi; apply lt_le_trans with q; try omega.\n            apply power_ge_n; auto. }\n          destruct H2 as (f & Hf).\n          destruct H3 as (g & Hg).\n          generalize (is_cipher_of_u Hq); intros Hu.\n          rewrite cipher_mult_eq with (1 := Hg) (2 := Hu) in H4.\n          destruct Hf as (_ & Hf & Hy).\n          destruct Hg as (_ & Hg & Hz).\n          set (h i := if le_lt_dec l i then l else f i).\n          assert (y+l*power (power (S l) 2) r = ∑ (S l) (fun i => h i * power (power (S i) 2) r)) as H6.\n          { rewrite msum_plus1; auto; f_equal.\n            * rewrite Hy; apply msum_ext.\n              intros i Hi; unfold h.\n              destruct (le_lt_dec l i); try omega.\n            * unfold h.\n              destruct (le_lt_dec l l); try omega. }\n          rewrite H4 in H6.\n          set (g' i := match i with 0 => 0 | S i => g i end).\n          assert ( ∑ (S l) (fun i => g' i * power (power (S i) 2) r)\n                 = ∑ l (fun i : nat => g i * 1 * power (power (S (S i)) 2) r)) as H7.\n          { unfold g'; rewrite msum_S; apply msum_ext; intros; ring. }\n          rewrite <- H7 in H6.\n          assert (forall i, i < S l -> g' i = h i) as H8.\n          { apply power_decomp_unique with (5 := H6); try omega. \n            * intros; apply power_smono_l; omega. \n            * unfold g'; intros [ | i ] Hi; try omega.\n              apply lt_S_n in Hi.\n              apply lt_le_trans with (1 := Hg _ Hi), power_mono_l; omega.\n            * intros i Hi; unfold h.\n              destruct (le_lt_dec l i) as [ | Hi' ].\n              + apply lt_le_trans with (4*q); try omega.\n                apply power_ge_n; auto.\n              + apply lt_le_trans with (1 := Hf _ Hi'), power_mono_l; omega.  }\n          assert (h 0 = 0) as E0.\n          { rewrite <- H8; simpl; omega. }\n          assert (forall i, i < l -> h (S i) = g i) as E1.\n          { intros i Hi; rewrite <- H8; simpl; omega. }\n          assert (f 0 = 0) as E3.\n          { unfold h in E0; destruct (le_lt_dec l 0); auto; omega. }\n          assert (forall i, S i < l -> f (S i) = g i) as E4.\n          { intros i Hi; specialize (E1 i); unfold h in E1.\n            destruct (le_lt_dec l (S i)); omega. }\n          assert (g (l-1) = l) as E5.\n          { specialize (E1 (l-1)); unfold h in E1.\n            destruct (le_lt_dec l (S (l-1))); omega. }  \n          clear H6 H7 g' H8 E0 E1 h H4.\n          assert (y + u1 + power (power 1 2) r = \n                  ∑ l (fun i => (1+f i) * power (power (S i) 2) r)\n                + power (power (S l) 2) r) as E1.\n          { rewrite sum_0n_distr_in_out.\n            rewrite <- Hy, sum_0n_scal_l, Nat.mul_1_l.\n            destruct l as [ | l' ]; try omega.\n            rewrite msum_plus1; auto.\n            rewrite msum_S; ring. }\n          assert (forall i, i < l -> 1+f i = g i) as E2.\n          { apply power_decomp_unique with (f := fun i => power (S i) 2) (p := r); try omega.\n            + intros; apply power_smono_l; omega.\n            + intros i Hi; apply le_lt_trans with (power q 2); auto.\n              * apply Hf; auto.\n              * apply power_smono_l; omega. \n            + intros i Hi; apply lt_le_trans with (1 := Hg _ Hi), power_mono_l; omega. } \n          rewrite Hy; apply msum_ext.\n          clear Hy Hf Hg Hz H5 E5 E1 Hu.\n          intros i Hi; f_equal; revert i Hi.\n          induction i as [ | i IHi ]; intros Hi; auto.\n          rewrite E4, <- E2; try omega.\n          rewrite IHi; omega.\n    Qed.\n\n    Lemma CodeNat_dio y : CodeNat y <-> l = 0 /\\ 1 < q /\\ y = 0 \n                                  \\/ 0 < l \n                                  /\\ exists z v v1 p0 p1 p2 r1,\n                                        p0 = r\n                                     /\\ r1+1 = p0 \n                                     /\\ p1 = power (1+l) 2\n                                     /\\ p2 = power p1 p0 \n                                     /\\ seqs_of_ones v v1 \n                                     /\\ Code y\n                                     /\\ Code z\n                                     /\\ y + l*p2 = (z*v) ⇣ (r1 * v1)\n                                     /\\ y + v1 + p0*p0 = z + p2.\n    Proof.\n      rewrite IncSeq_dio_priv; split; (intros [ H | H ]; [ left | right ]); auto; revert H;\n        intros (H1 & H); split; auto; clear H1; revert H.\n      + intros (z & v & v1 & H1 & H2 & H3 & H4 & H5).\n        exists z, v, v1, r, (power (S l) 2), (power (power (S l) 2) r), (r-1); repeat (split; auto).\n        * destruct H1; omega.\n        * rewrite <- H5; f_equal.\n          rewrite power_1, power_S, power_1; auto.\n      + intros (z & v & v1 & p0 & p1 & p2 & r1 & H1 & H2 & H3 & H4 & H5 & H6 & H7 & H8 & H9).\n        assert (r1 = r - 1) by omega; clear H2; subst.\n        exists z, v, v1; repeat (split; auto).\n        simpl in H9 |- *; rewrite <- H9; f_equal.\n        rewrite power_1, power_S, power_1; auto.\n    Qed.\n      \n  End inc_seq.\n\nEnd sums.  \n\nCheck Code_plus_spec.\nCheck Code_mult_spec.\nCheck CodeNat_dio.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/coq-library-undecidability/H10/Matija/cipher.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6875561000335028}}
{"text": "(* ******************************************************************************* *)\n(** Associativity laws are inverses\n ********************************************************************************* *)\n\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.PrecategoryBinProduct.\nRequire Import UniMath.Bicategories.Core.Bicat. Import Bicat.Notations.\nRequire Import UniMath.Bicategories.Core.Invertible_2cells.\nRequire Import UniMath.Bicategories.Core.BicategoryLaws.\nRequire Import UniMath.Bicategories.Core.Unitors.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Base.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Map1Cells.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Map2Cells.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Identitor.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Compositor.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.PseudoFunctorBicat.\nRequire Import UniMath.Bicategories.PseudoFunctors.PseudoFunctor.\nImport PseudoFunctor.Notations.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Identity.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Composition.\nRequire Import UniMath.Bicategories.Transformations.PseudoTransformation.\nRequire Import UniMath.Bicategories.Transformations.Examples.Associativity.\nRequire Import UniMath.Bicategories.Modifications.Modification.\n\nLocal Open Scope cat.\n\nSection Associativity.\n  Context {B₁ B₂ B₃ B₄: bicat}.\n  Variable (F₁ : psfunctor B₁ B₂)\n           (F₂ : psfunctor B₂ B₃)\n           (F₃ : psfunctor B₃ B₄).\n\n  Definition lassociator_rassociator_pstrans_data\n    : invertible_modification_data\n        (comp_pstrans\n           (lassociator_pstrans F₁ F₂ F₃)\n           (rassociator_pstrans F₁ F₂ F₃))\n        (id_pstrans _).\n  Proof.\n    intros X.\n    use make_invertible_2cell.\n    - exact (lunitor _).\n    - is_iso.\n  Defined.\n\n  Definition lassociator_rassociator_pstrans_modification\n    : is_modification lassociator_rassociator_pstrans_data.\n  Proof.\n    intros X Y f ; cbn.\n    rewrite <- lwhisker_vcomp.\n    rewrite !vassocr.\n    rewrite lunitor_lwhisker.\n    rewrite <- rwhisker_vcomp.\n    rewrite !vassocl.\n    etrans.\n    {\n      do 2 apply maponpaths.\n      rewrite !vassocr.\n      rewrite lunitor_triangle.\n      apply maponpaths_2.\n      rewrite !vassocl.\n      rewrite rwhisker_hcomp.\n      rewrite <- triangle_r_inv.\n      rewrite <- lwhisker_hcomp.\n      apply idpath.\n    }\n    rewrite !vassocl.\n    rewrite lwhisker_vcomp.\n    rewrite linvunitor_lunitor, lwhisker_id2, id2_right.\n    rewrite vcomp_lunitor.\n    rewrite runitor_lunitor_identity.\n    apply idpath.\n  Qed.\n\n  Definition lassociator_rassociator_pstrans\n    : invertible_modification\n        (comp_pstrans\n           (lassociator_pstrans F₁ F₂ F₃)\n           (rassociator_pstrans F₁ F₂ F₃))\n        (id_pstrans _).\n  Proof.\n    use make_invertible_modification.\n    - exact lassociator_rassociator_pstrans_data.\n    - exact lassociator_rassociator_pstrans_modification.\n  Defined.\n\n  Definition rassociator_lassociator_pstrans_data\n    : invertible_modification_data\n        (comp_pstrans\n           (rassociator_pstrans F₁ F₂ F₃)\n           (lassociator_pstrans F₁ F₂ F₃))\n        (id_pstrans _).\n  Proof.\n    intros X.\n    use make_invertible_2cell.\n    - exact (lunitor _).\n    - is_iso.\n  Defined.\n\n  Definition rassociator_lassociator_pstrans_is_modification\n    : is_modification rassociator_lassociator_pstrans_data.\n  Proof.\n    intros X Y f ; cbn.\n    rewrite <- lwhisker_vcomp.\n    rewrite !vassocr.\n    rewrite lunitor_lwhisker.\n    rewrite <- rwhisker_vcomp.\n    rewrite !vassocl.\n    etrans.\n    {\n      do 2 apply maponpaths.\n      rewrite !vassocr.\n      rewrite lunitor_triangle.\n      apply maponpaths_2.\n      rewrite !vassocl.\n      rewrite rwhisker_hcomp.\n      rewrite <- triangle_r_inv.\n      rewrite <- lwhisker_hcomp.\n      apply idpath.\n    }\n    rewrite !vassocl.\n    rewrite lwhisker_vcomp.\n    rewrite linvunitor_lunitor, lwhisker_id2, id2_right.\n    rewrite vcomp_lunitor.\n    rewrite runitor_lunitor_identity.\n    apply idpath.\n  Qed.\n\n  Definition rassociator_lassociator_pstrans\n    : invertible_modification\n        (comp_pstrans\n           (rassociator_pstrans F₁ F₂ F₃)\n           (lassociator_pstrans F₁ F₂ F₃))\n        (id_pstrans _).\n  Proof.\n    use make_invertible_modification.\n    - exact rassociator_lassociator_pstrans_data.\n    - exact rassociator_lassociator_pstrans_is_modification.\n  Defined.\nEnd Associativity.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/Bicategories/Modifications/Examples/Associativity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6875560836750605}}
{"text": "Require Import Classical.\nRequire Import  Wf_nat.\n\nSection Wf_inf.\n  Variable A : Type.\n  Variable ltA : A -> A -> Prop.\n  Hypothesis wf_ltA : well_founded ltA.\n\n  Definition sat (P:A-> Prop) := exists b, P b.\n  Definition inf(a:A)(P:A-> Prop) := P a /\\ forall b,  P b -> ~ ltA b a.\n\n  Lemma nonempty_inf : forall P, sat P -> exists a, inf a P.\n  Proof.\n    unfold sat, inf.\n    intros.\n    destruct H as [b Hex].\n    unfold well_founded in *.\n    specialize (wf_ltA b).\n    induction wf_ltA.\n    destruct (classic (exists y, ltA y x /\\ P y)).\n    * destruct H1 as [y [Hlt HP]]. \n      apply H0 with y ; auto.\n    * exists x ; split ; intuition.\n      apply H1.\n      exists b; intuition.\n  Qed.\nEnd Wf_inf.\n\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/second_method/WfInf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178928, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6875398702980308}}
{"text": "Require Import  Eqdep_dec Image Peano_dec Arith.\n\n(** Inductive Finite Types *)\n\nSet Implicit Arguments.\n\n Inductive Fin : nat -> Set :=\n | fz : forall n, Fin (S n)\n | fs : forall n, Fin n -> Fin (S n).\n\n Derive Inversion FinO_rect with (Fin 0) Sort Type.\n\n (* fs /fz View *)\n Inductive FinSN (n : nat) : Fin (S n) -> Set :=\n  | isfz : FinSN  (fz n)\n  | isfs : forall i, FinSN  (fs i).\n\n\n Definition finSN (n : nat) (i : Fin (S n)) : FinSN i :=\n   match i in (Fin k) return match k return Fin k -> Set with\n                             | O => fun _ => unit\n                             | S n' => @FinSN _\n                             end i with \n   | fz _ => isfz _\n   | fs _ j => isfs  j\n   end.\n\n Definition FinSn_rect :  forall n,  forall (P:Fin (S n)->Type), \n                   (forall y:Fin n, P (fs y)) ->  P (fz n)  -> forall x, P x :=\n fun n P H0 H1 x => match (finSN x) in (FinSN  e) return (P e) with\n                    | isfz => H1\n                    | isfs i => (H0 i)\n                    end.\n\n Lemma fsInject : forall n, forall x y:Fin n, (fs x)=(fs y) -> x=y.\n Proof.\n  induction x; intro y. destruct (finSN y); trivial.\n  intro H; try discriminate H.\n   destruct (finSN y).\n  intro H; try discriminate H.\n  intro H; injection H.\n   intro H0; \n    rewrite (inj_pair2_eq_dec _  eq_nat_dec (fun n : nat => Fin n) n x i H0);\n    trivial.\nQed.\n\nHint Resolve fsInject : fin_scope.\n\nLemma FinDecideEquality : forall n, forall (x y:Fin n), {x=y}+{x<>y}.\nProof.\n  induction x. intro y ; destruct (finSN y) ; auto.\n  try (right;  discriminate).\n  intro y; destruct (finSN y).\n  right; discriminate.\n  destruct (IHx i); subst.\n  left ; trivial.\n  right; intuition. \nDefined.\n\nLemma FinForallOrExist : forall n (P Q:Fin n->Prop), \n                  (forall x, {P x}+{Q x}) -> {x:Fin n | P x}+{forall x, Q x}.\nProof.\ninduction n. intros; right; inversion x.\nintros P Q H. destruct (H ( fz n)).\nleft; exists (fz n); auto.\ndestruct (IHn (fun x=>(P (fs x))) (fun x=>(Q (fs x))) (fun x=> (H (fs x)))).\ndestruct s. left; exists (fs x); auto.\nright. intros x; destruct x using FinSn_rect; auto.\nDefined.\n \n (* boolean equality for finite sets*)\n  Fixpoint eqFin (n :nat) (i : Fin n)  {struct i}: 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                    | isfs _ => false\n                   end\n     | fs _ k => fun j => match (finSN j) with\n                      | isfz => false \n                      | isfs k' => eqFin k k'\n                     end\n    end.\n\n Lemma eqFin_ok : forall n (i j : Fin n), eqFin i j = true -> i = j.\n Proof.\n   induction i; simpl. intros j; destruct (finSN j);\n   try (intro h; discriminate h); trivial. \n    intro j; destruct (finSN j); try (intro h; discriminate h).\n    intro h; rewrite (IHi i0 h); trivial.\n Qed.  \n\n\n(* boolean less or equal for finite sets *)\nFixpoint lefin (n : nat) (i  : Fin n) {struct i}: Fin n -> bool :=\n match i as e in (Fin n) return (Fin n -> bool) with\n | fz _  => fun _ => true\n | fs _ i' => fun x => \n      match (finSN x) with\n      | isfs z  =>  lefin i' z\n      |  _   => false  \n      end\n end.\n\n (* inductive less or equal *)\n Inductive Lefin : forall n, Fin n -> Fin n -> Set :=\n   | leq  : forall n, Lefin (fz n) (fz n)\n   | lefz : forall n ( i : Fin n) , Lefin (fz n) (fs i)\n   | lefs : forall n (i j : Fin n), Lefin i j -> Lefin (fs i) (fs j).\n (*Infix \" x =<= y \" := Lefin (at level 30) : fin.*)\n\n Lemma Le_refl : forall n (i : Fin n), Lefin i i.\n Proof.\n   induction i; try apply leq.\n   exact (lefs IHi).\n Qed.\n\n Lemma Le_fs_inj : forall n (i j : Fin n), Lefin (fs i) (fs j) -> Lefin i j.\n Proof.\n   intros n i j H; try inversion H.\n  rewrite <- (inj_pair2_eq_dec  _ eq_nat_dec  (fun n : nat => Fin n) n i0 i  H1);\n  rewrite <- (inj_pair2_eq_dec  _ eq_nat_dec  (fun n : nat => Fin n) n j0 j  H2);\n  trivial.\n Qed.\n  \n Lemma Le_trans : \n   forall n (i j k: Fin n), Lefin i j -> Lefin j k -> Lefin i k.\n Proof.\n   induction i. destruct j using FinSn_rect.\n   destruct k using FinSn_rect. intros.\n   apply lefz. intros. inversion H0.\n   destruct k using FinSn_rect.\n   intros. apply lefz.\n   intros. apply leq. destruct j using FinSn_rect;\n   destruct k using FinSn_rect.\n   intros H H1. exact (lefs (IHi _ _ (Le_fs_inj H) (Le_fs_inj H1)) ).\n   intros. inversion H0.\n   intros. inversion H.\n   intros. inversion H.\n Qed.\n\n (* inductive Le correspond to the boolean le*)\n Lemma Le_ind_bool : forall n (i j : Fin n), Lefin i j -> lefin i j = true.\n Proof.\n   induction i. destruct j using FinSn_rect; simpl; auto.\n   destruct j using FinSn_rect; simpl; auto.\n   intros. exact (IHi _ (Le_fs_inj H)).\n   intros. inversion H.\n  Qed.\n   \n\n(* Fin 0 is empty *)\n Lemma fin_0_empty: (Fin 0) -> False.\n Proof.\n  intro i; inversion i.\n Qed.\n\n (* the natural number represented by Fin n*)\n Fixpoint foo  n (i : Fin n)  :=\n     match i with\n     | fz _ => 0\n     | fs _ i => S (foo i)\n    end.\n\n Fixpoint nat_finite (n:nat) k : k<n -> Fin n :=\n match n return ( k<n -> Fin n) with\n  O => fun (h:k<O)  =>\n         match (lt_n_O k h) return (Fin 0) with end\n | (S n') =>   match k return (k<(S n') -> Fin (S n')) with\n                O => fun _ => (fz n')\n              | (S k') => fun h:S k' < S n' =>\n                            fs (nat_finite (lt_S_n _ _ h))\n              end\n end.\n\nImplicit Arguments nat_finite [n].\n\n\nLemma nat_finite_id:\n  forall (n k:nat)(h:k<n), (foo (nat_finite k h)) = k.\nProof.\n induction n.\n intros k h; destruct (lt_n_O k h).\n induction k;  auto.\n exact (fun h => f_equal S (IHn k (lt_S_n k n h))).\nQed.\n\n Fixpoint finite_lt_n (n : nat) (i : Fin n) : (foo i) < n :=\n   match i as e in Fin m return (foo e) < m with\n   | fz x => lt_O_Sn x\n   | fs _ j => lt_n_S (foo j) _ (finite_lt_n j)\n   end.\n\n Definition finite_le_n (n : nat) (i : Fin n) :=\n    lt_le_weak _ _ (finite_lt_n i). \n   \n\nLemma finite_nat_id_general:\n  forall (n:nat)(i:Fin n)(h:(foo i)<n),  (nat_finite (foo i) h) = i.\nProof.\n induction i; auto;\n try (intro h; simpl; rewrite IHi; auto).\nQed.\n\nLemma finite_nat_id:\n  forall (n:nat)(i:Fin n), (nat_finite (foo i) (finite_lt_n i)) = i.\nProof.\n intros; apply finite_nat_id_general; auto.\nQed.\n\n(* similarity *)\n\n (* turn (forall n, Fin n -> Fin n) to  N x N -> N *)\n Definition FinFn (H : forall n, Fin n -> Fin n) := \n     fun n m => match le_lt_dec n m  with\n                | left _ => 0\n                | right l => foo (H _ (nat_finite m l))\n                end.\n\n\n Definition FinFn1 (f : nat -> nat) (H : forall n, Fin (f n) -> Fin n) := \n     fun n m => match le_lt_dec (f n) m  with\n                | left _ => 0\n                | right l => foo (H _ (nat_finite m l))\n                end.\n\n Definition FinFnEx \n   (f : nat -> nat) (H : forall n, Fin (f n) -> Fin n) :\n      forall n, {k | k < f n} -> Fin n :=\n   fun n ex => let (_, l) := ex in  H n (nat_finite _ l).\n\n Definition FinFn_inv (H : nat -> nat -> nat) : forall n, Fin n -> Fin n :=\n   fun n i =>   match le_lt_dec n (H n (foo i)) with\n                | left _ => i\n                | right l => nat_finite (H n (foo i)) l\n                end .\n\n\n (* correctness *)\n Lemma foo_not_le : forall n (i : Fin n), ~ n <= foo i.\n   induction i; simpl; auto with arith.\n Qed.\n\n  Lemma FinFn_l (H : forall n, Fin n -> Fin n) :\n              forall n (i : Fin n),   FinFn_inv (FinFn H)  i =  H n i .\n  Proof.\n   unfold FinFn_inv; unfold FinFn; simpl; intros.\n   destruct (le_lt_dec n (foo i)); simpl.\n   case (foo_not_le i l).\n   rewrite (finite_nat_id_general i l).\n   destruct (le_lt_dec n (foo (H n i)) ).\n   case (foo_not_le (H n i) l0 ).  \n   apply (finite_nat_id_general (H n i) l0 ).\n Qed.\n\n Lemma FinFn_l1 (H : nat -> nat -> nat) :\n       forall n m, m < n -> H n m < n ->  FinFn (FinFn_inv H) n m   =  H n m .\n Proof.\n   unfold FinFn; unfold FinFn_inv; intros.\n   destruct (le_lt_dec n m) as [ l | r ].\n   case (le_not_lt _ _ l H0).\n   rewrite (nat_finite_id r).\n   destruct (le_lt_dec n (H n m ));\n   [case (le_not_lt _ _ l H1) | apply (nat_finite_id l)].\n  Qed.\n\n (* the conversions preserves equality *)\n Lemma FinFn_eq_ok : forall (h h1 : forall n, Fin n -> Fin n), h  = h1 -> \n   FinFn h = FinFn h1.\n  Proof.\n    intros h h1 H; destruct H; trivial.\n  Qed.\n\n Lemma FinFn_inv_eq_ok : forall (h h1 : nat -> nat -> nat), h = h1 ->\n    FinFn_inv h  = FinFn_inv h1.\n  Proof.\n   intros h h1 H; destruct H; trivial.\n Qed.\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/InductiveFiniteSets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570318, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6875398695280917}}
{"text": "Require Export Arith.\nRequire Export ArithRing.\nRequire Export Omega.\nRequire Export Wf_nat.\n \nFixpoint div2 (n : nat) : nat :=\n match n with S (S p) => S (div2 p) | _ => 0 end.\n \nTheorem div2_ind:\n forall (P : nat ->  Prop),\n P 0 -> P 1 -> (forall n, P n ->  P (S (S n))) -> forall n,  P n.\nProof.\nintros P H0 H1 Hstep n.\nassert (P n /\\ P (S n)).\nelim n; intuition.\nintuition.\nQed.\n \nTheorem div2_lt: forall n,  (div2 (S n) < S n).\nProof.\nintros; elim n  using div2_ind; simpl; intros; omega.\nQed.\n \nDefinition log2_it_F (log2 : nat ->  nat) (n : nat) : nat :=\n   match n with\n     0 => 0\n    | 1 => 0\n    | S (S p) => S (log2 (div2 (S (S p))))\n   end.\n \nFixpoint iter (A : Set) (f : A ->  A) (k : nat) (a : A) {struct k} : A :=\n match k with   0%nat => a\n               | S p => f (iter A f p a) end.\nImplicit Arguments iter.\n \nLtac caseEq f := generalize (refl_equal f); pattern f at -1; case f.\n \nDefinition log2_terminates:\n forall (n : nat),\n  ({v : nat | exists p : nat , forall k g, p < k ->  iter log2_it_F k g n = v }).\nintros n; elim n  using (well_founded_induction lt_wf); clear n.\nintros n; case n.\nintros; exists 0; exists 0.\nintros k; case k.\nintros; omega.\nintros k' g _; simpl; auto.\nintros n'; case n'.\nintros; exists 0; exists 0; intros k; case k.\nintros; omega.\nintros k' g_; simpl; auto.\nintros p f; assert (Hlt: div2 (S (S p)) < S (S p)).\napply div2_lt.\ndestruct (f (div2 (S (S p))) Hlt) as [v Hex].\nexists (S v).\ndestruct Hex as [p' Heq].\nexists (S p').\nintros k g; case k.\nintros; omega.\nintros k' Hltk.\nrewrite <- (Heq k' g).\nauto.\nomega.\nQed.\n \nDefinition log2 (n : nat) : nat :=\n   match log2_terminates n with exist v _ => v end.\n \nTheorem log2_fix_eqn:\n forall n,  log2 n = match n with\n                       0 => 0\n                      | 1 => 0\n                      | S (S p) => S (log2 (div2 (S (S p))))\n                     end.\nintros n; unfold log2; case (log2_terminates n); case n.\nintros v [p Heq].\nrewrite <- (Heq (S p) log2); auto.\nintros n'; case n'.\nintros v [p Heq].\nrewrite <- (Heq (S p) log2); auto.\nintros n'' v [p Heq].\ncase (log2_terminates (div2 (S (S n'')))).\nintros v' [p' Heq'].\nrewrite <- (Heq (S (S (p + p'))) log2).\nrewrite <- (Heq' (S (p + p')) log2); auto.\nomega.\nomega.\nQed.\n \nTheorem div2_eq: forall n,  2 * div2 n = n \\/ 2 * div2 n + 1 = n.\nProof.\nintros n; elim n  using div2_ind; simpl; (try omega).\nintros n' [Heq|Heq]; omega.\nQed.\n \nFixpoint two_power (n : nat) : nat :=\n match n with 0 => 1 | S p => 2 * two_power p end.\n \nTheorem log2_power:\n forall n, 0 < n ->  ( two_power (log2 n) <= n < 2 * two_power (log2 n) ).\nintros n; elim n  using (well_founded_ind lt_wf).\nintros x; case x.\nsimpl; intros; omega.\nintros x'; case x'.\nrewrite (log2_fix_eqn 1).\nsimpl; auto with arith.\nintros p Hrec; elim (Hrec (div2 (S (S p)))).\nintros Hle Hlt _; rewrite (log2_fix_eqn (S (S p))).\ncbv zeta iota beta delta [two_power]; fold two_power.\nsplit.\napply le_trans with (2 * div2 (S (S p))).\nauto with arith.\nelim (div2_eq (S (S p))).\nomega.\nomega.\napply le_lt_trans with (2 * div2 (S (S p)) + 1).\nelim (div2_eq (S (S p))).\nomega.\nomega.\nomega.\napply div2_lt.\nsimpl; auto with arith.\nQed.\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/gen-rec/SRC/log2_it.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6875398572990534}}
{"text": "(**\n*  CS386L Programming Languages\n* Final project\n* Tian Zhang (tz3272)\n* Brief Introduction:\n*     This file contains proof for program equivalence, a starting point\n*     For my final project\n*     All the proof is based on the language in Imp.v \n*     Some example and proof are followed content from equiv.v\n*)\n\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 Coq.Logic.FunctionalExtensionality.\nImport ListNotations.\nRequire Import Maps.\nRequire Import Imp.\n\n\n(** Two aexp or bexp are behaviorally equivalent if they\n    evaluate to the same result in every state *)\n\nDefinition aequiv (a1 a2 : aexp) : Prop :=\n  forall (st:state),\n    aeval st a1 = aeval st a2.\n\nDefinition bequiv (b1 b2 : bexp) : Prop :=\n  forall (st:state),\n    beval st b1 = beval st b2.\n\n(** Two commands are behaviorally equivalent\n    if, for any given starting state, they either both diverge or both\n    terminate in the same final state.*)\n\nDefinition cequiv (c1 c2 : com) : Prop :=\n  forall (st st' : state),\n    (c1 / st \\\\ st') <-> (c2 / st \\\\ st').\n\n\n(** Here is some command equivalent example*)\n\n(** SKIP , skip in command left and skip in command right*)\n\nTheorem skip_left: forall c,\n  cequiv \n     (SKIP;; c) \n     c.\nProof. \n  intros c st st'.\n  split; intros H.\n  - (* -> *) \n    inversion H. subst. \n    inversion H2. subst. \n    assumption.\n  - (* <- *) \n    apply E_Seq with st.\n    apply E_Skip. \n    assumption.  \nQed.\n\n\nTheorem skip_right: forall c,\n  cequiv \n    (c;; SKIP) \n    c.\nProof.\n  intros.\n  split; intros.\n  - (* -> *)\n    inversion H.\n    simpl. subst. inversion H5.\n    subst.\n    assumption.\n  - (* <- *)\n  apply E_Seq with st'.\n  assumption.\n  apply E_Skip.\nQed.\n\n(** IFB, (IFB b THEN c1 ELSE c2 FI), if clause evaluate to true , \n    then goto c1\n    If evaluate to false, then goto c2\n*)\n\n\nTheorem IFB_true: forall b c1 c2,\n     bequiv b BTrue  ->\n     cequiv\n       (IFB b THEN c1 ELSE c2 FI)\n       c1.\nProof.\n  intros b c1 c2 Hb.\n  split; intros H.\n  - (* -> *)\n    inversion H; subst.\n    + (* b == true *)\n      assumption.\n    + (* b == false *)\n      unfold bequiv in Hb. simpl in Hb.\n      rewrite Hb in H5.\n      inversion H5.\n  - (* <- *)\n    apply E_IfTrue; try assumption.\n    unfold bequiv in Hb. simpl in Hb.\n    rewrite Hb. reflexivity.  Qed.\n\n\nTheorem IFB_false: forall b c1 c2,\n  bequiv b BFalse  ->\n  cequiv\n    (IFB b THEN c1 ELSE c2 FI)\n    c2.\nProof.\n  intros b c1 c2 Hb.\n  split; intros H.\n  - (* -> *)\n    inversion H; subst.\n    + (* b => true *)\n    unfold bequiv in Hb.\n    rewrite Hb in H5. inversion H5.\n    + (* b => false *)\n    assumption.\n  - (* <- *)\n    apply E_IfFalse.\n    unfold bequiv in Hb.\n    simpl in Hb. apply Hb.\n    assumption.\nQed.\n\n\n(** swap_if_branches,\n    swap the if else cases by negating the if clause\n  *)\n\nLemma beval_neg : forall st b b',\n                    beval st (BNot b) = b' -> beval st b = negb b'.\nProof.\n  intros.\n  destruct b'; simpl in H; symmetry in H; apply negb_sym in H; assumption.\nQed. \n\nTheorem swap_if_branches: forall b e1 e2,\n  cequiv\n    (IFB b THEN e1 ELSE e2 FI)\n    (IFB BNot b THEN e2 ELSE e1 FI).\nProof.\n  intros.\n  split; intros.\n  - (* -> *)\n  inversion H; subst.\n  apply E_IfFalse. simpl. rewrite H5. reflexivity.\n  assumption.\n  apply E_IfTrue. simpl. rewrite H5. reflexivity.\n  assumption.\n  - (* <- *)\n  inversion H; subst.\n    + (* False *)\n    apply E_IfFalse.\n    apply beval_neg in H5; simpl in H5; assumption.\n    assumption.\n    + (*True *)\n    apply E_IfTrue.\n    apply beval_neg in H5; simpl in H5; assumption.\n    assumption.\nQed.\n\n\n(** WHILE loops, if while clause evaluate to false, then it is similar\n  to skip\n *)\n\nTheorem WHILE_false : forall b c,\n     bequiv b BFalse ->\n     cequiv\n       (WHILE b DO c END)\n       SKIP.\nProof.\n  intros b c Hb. split; intros H.\n  - (* -> *)\n    inversion H; subst.\n    + (* E_WhileEnd *)\n      apply E_Skip.\n    + (* E_WhileLoop *)\n      rewrite Hb in H2. inversion H2.\n  - (* <- *)\n    inversion H; subst.\n    apply E_WhileEnd.\n    rewrite Hb.\n    reflexivity.  Qed.\n\n\n\n(** When while clause evaluate to true, it will never terminate,\n    Here is the lemma,\n\n    If b is equivalent to [BTrue], then it cannot be the\n    case that [(WHILE b DO c END) / st \\\\ st'].\n*)\n\nLemma WHILE_true_nonterm : forall b c st st',\n     bequiv b BTrue ->\n     ~( (WHILE b DO c END) / st \\\\ st' ).\nProof.\n\n  intros b c st st' Hb.\n  intros H.\n  remember (WHILE b DO c END) as cw eqn:Heqcw.\n  induction H;\n    (*by inversion *)\n    inversion Heqcw; subst; clear Heqcw.\n  - (* E_WhileEnd *) (* contradictory -- b is always true! *)\n    unfold bequiv in Hb.\n    (* [rewrite] is able to instantiate the quantifier in [st] *)\n    rewrite Hb in H. inversion H.\n  - (* E_WhileLoop *) (* immediate from the IH *)\n    apply IHceval2. reflexivity.  Qed.\n\n\n(** now we have lemma, we can evaluate while true *)\n\nLemma ex_falso_quodlibet : forall (P:Prop), False -> P.\nProof.\n  intros. inversion H.\nQed.\n\nLemma skip_state : forall st st',\n                     SKIP / st \\\\ st' -> st = st'.\nProof.\n  intros.\n  inversion H. subst.\n  reflexivity.\nQed.\n\n\nTheorem WHILE_true: forall b c,\n     bequiv b BTrue  ->\n     cequiv\n       (WHILE b DO c END)\n       (WHILE BTrue DO SKIP END).\nProof.\n  intros.\n  intros st st'. split.\n  - (* -> *) \n    intros.\n    apply WHILE_true_nonterm with (c:=c) (st:=st) (st':=st') in H.\n    apply ex_falso_quodlibet.\n    apply H in H0. assumption.\n  - (* <- *)\n  intros.\n  remember (WHILE BTrue DO SKIP END).\n  induction H0; inversion Heqc0. \n    + (* E_WhileEnd *)\n  subst. simpl in H0. inversion H0.\n    + (* E_WhileLoop *)\n  subst.\n  clear IHceval1.\n  rename H0_ into Hst.\n  apply skip_state in Hst.\n  rewrite Hst.\n  apply IHceval2.\n  assumption.\nQed.\n\n\n(** another key concept in loop is loop unrolling , programms are\n    behaviorally equivalent if we perform the loop unrolling\n*)\n\nTheorem loop_unrolling: forall b c,\n  cequiv\n    (WHILE b DO c END)\n    (IFB b THEN (c;; WHILE b DO c END) ELSE SKIP FI).\nProof.\n  intros b c st st'.\n  split; intros Hce.\n  - (* -> *)\n    inversion Hce; subst.\n    + (* loop doesn't run *)\n      apply E_IfFalse. assumption. apply E_Skip.\n    + (* loop runs *)\n      apply E_IfTrue. assumption.\n      apply E_Seq with (st' := st'0). assumption. assumption.\n  - (* <- *)\n    inversion Hce; subst.\n    + (* loop runs *)\n      inversion H5; subst.\n      apply E_WhileLoop with (st' := st'0).\n      assumption. assumption. assumption.\n    + (* loop doesn't run *)\n      inversion H5; subst. apply E_WhileEnd. assumption.  Qed.\n\n\n(** change the associativity of command *)\n\n\nTheorem seq_assoc : forall c1 c2 c3,\n  cequiv ((c1;;c2);;c3) (c1;;(c2;;c3)).\nProof.\n intros.\n  split; intros.\n  - (* -> *)\n  inversion H; subst.\n  inversion H2; subst.\n  apply E_Seq with (st':=st'1).\n  assumption.\n  apply E_Seq with (st':=st'0).\n  assumption.\n  assumption.\n  - (* <- *)\n  inversion H; subst.\n  inversion H5; subst.\n  apply E_Seq with (st':=st'1).\n  apply E_Seq with (st':=st'0).\n  assumption.\n  assumption.\n  assumption.\nQed.\n\n\n(** Assignment , simple example is like indentity assignment *)\n\nTheorem identity_assignment : forall (X:id),\n  cequiv\n    (X ::= AId X)\n    SKIP.\nProof.\n   intros. split; intro H.\n     - (* -> *)\n       inversion H; subst. simpl.\n       replace (t_update st X (st X)) with st.\n       + constructor.\n       + apply functional_extensionality. intro.\n         rewrite t_update_same; reflexivity.\n     - (* <- *)\n       replace st' with (t_update st' X (aeval st' (AId X))).\n       + inversion H. subst. apply E_Ass. reflexivity.\n       + apply functional_extensionality. intro.\n         rewrite t_update_same. reflexivity.\nQed.\n\n(** Another theorem about assignment simple, no need to assign twices\nif X already evaluate to e*)\n\n\nTheorem assign_aequiv : forall X e,\n  aequiv (AId X) e ->\n  cequiv SKIP (X ::= e).\nProof.\nintros.\n  split; intro He.\n  - (* -> *)\n  apply skip_state in He.\n  unfold aequiv in H.\n  assert (st' = (t_update st' X (st' X))).\n    apply functional_extensionality. intro.\n    rewrite t_update_same; reflexivity.\n  rewrite H0.\n  rewrite He.\n  apply E_Ass.\n  rewrite <- H.\n  simpl. reflexivity.\n  - (* <- *)\n  inversion He.\n  subst.\n  assert (st = t_update st X (st X)).\n    apply functional_extensionality. intros.\n    rewrite t_update_same; reflexivity.\n  rewrite H0 in He at 1.\n  inversion He.\n  rewrite <- H0 in H4.\n  unfold aequiv in H.\n  rewrite <- H in H5.\n  simpl in H5.\n  rewrite H5.\n  rewrite <- H0.\n  apply E_Skip.\nQed.\n\n\n\n\n\n(** Now we show the detail of program equivalence, and the next step\nis show the  Properties of Behavioral Equivalence , in order to help further\nproof about constant folding and partial evaluation\n*)\n\n(** First, we verify that the equivalences on aexps, bexps, and\n    coms are eflexive,\n    symmetric, and transitive. *)\n\nLemma refl_aequiv : forall (a : aexp), aequiv a a.\nProof.\n  intros a st. reflexivity.  Qed.\n\nLemma sym_aequiv : forall (a1 a2 : aexp),\n  aequiv a1 a2 -> aequiv a2 a1.\nProof.\n  intros a1 a2 H. intros st. symmetry. apply H.  Qed.\n\nLemma trans_aequiv : forall (a1 a2 a3 : aexp),\n  aequiv a1 a2 -> aequiv a2 a3 -> aequiv a1 a3.\nProof.\n  unfold aequiv. intros a1 a2 a3 H12 H23 st.\n  rewrite (H12 st). rewrite (H23 st). reflexivity.  Qed.\n\nLemma refl_bequiv : forall (b : bexp), bequiv b b.\nProof.\n  unfold bequiv. intros b st. reflexivity.  Qed.\n\nLemma sym_bequiv : forall (b1 b2 : bexp),\n  bequiv b1 b2 -> bequiv b2 b1.\nProof.\n  unfold bequiv. intros b1 b2 H. intros st. symmetry. apply H.  Qed.\n\nLemma trans_bequiv : forall (b1 b2 b3 : bexp),\n  bequiv b1 b2 -> bequiv b2 b3 -> bequiv b1 b3.\nProof.\n  unfold bequiv. intros b1 b2 b3 H12 H23 st.\n  rewrite (H12 st). rewrite (H23 st). reflexivity.  Qed.\n\nLemma refl_cequiv : forall (c : com), cequiv c c.\nProof.\n  unfold cequiv. intros c st st'. apply iff_refl.  Qed.\n\nLemma sym_cequiv : forall (c1 c2 : com),\n  cequiv c1 c2 -> cequiv c2 c1.\nProof.\n  unfold cequiv. intros c1 c2 H st st'.\n  assert (c1 / st \\\\ st' <-> c2 / st \\\\ st') as H'.\n  { (* Proof of assertion *) apply H. }\n  apply iff_sym. assumption.\nQed.\n\nLemma iff_trans : forall (P1 P2 P3 : Prop),\n  (P1 <-> P2) -> (P2 <-> P3) -> (P1 <-> P3).\nProof.\n  intros P1 P2 P3 H12 H23.\n  inversion H12. inversion H23.\n  split; intros A.\n    apply H1. apply H. apply A.\n    apply H0. apply H2. apply A.  Qed.\n\nLemma trans_cequiv : forall (c1 c2 c3 : com),\n  cequiv c1 c2 -> cequiv c2 c3 -> cequiv c1 c3.\nProof.\n  unfold cequiv. intros c1 c2 c3 H12 H23 st st'.\n  apply iff_trans with (c2 / st \\\\ st'). apply H12. apply H23.  Qed.\n\n\n(** The next step is to prove Behavioral Equivalence is a Congruence \n    That is, the equivalence of two subprograms implies the\n    equivalence of the larger programs in which they are embedded:\n\n\n              cequiv c1 c1'\n              cequiv c2 c2'\n         ------------------------\n         cequiv (c1;;c2) (c1';;c2')\n*)\n\n\n(** First, aquiv cases, which is simple,\n              aequiv a1 a1'\n      -----------------------------\n      cequiv (i ::= a1) (i ::= a1')\n*)\n\nTheorem CAss_congruence : forall i a1 a1',\n  aequiv a1 a1' ->\n  cequiv (CAss i a1) (CAss i a1').\nProof.\n  intros i a1 a2 Heqv st st'.\n  split; intros Hceval.\n  - (* -> *)\n    inversion Hceval. subst. apply E_Ass.\n    rewrite Heqv. reflexivity.\n  - (* <- *)\n    inversion Hceval. subst. apply E_Ass.\n    rewrite Heqv. reflexivity.  Qed.\n    \n(** Next case is while loop,\n                    bequiv b1 b1'\n      --------------------------------------------------\n      cequiv (WHILE b1 DO c1 END) (WHILE b1' DO c1' END).\n*)\nTheorem CWhile_congruence : forall b1 b1' c1 c1',\n  bequiv b1 b1' -> cequiv c1 c1' ->\n  cequiv (WHILE b1 DO c1 END) (WHILE b1' DO c1' END).\nProof.\n  unfold bequiv,cequiv.\n  intros b1 b1' c1 c1' Hb1e Hc1e st st'.\n  split; intros Hce.\n  - (* -> *)\n    remember (WHILE b1 DO c1 END) as cwhile\n      eqn:Heqcwhile.\n    induction Hce; inversion Heqcwhile; subst.\n    + (* E_WhileEnd *)\n      apply E_WhileEnd. rewrite <- Hb1e. apply H.\n    + (* E_WhileLoop *)\n      apply E_WhileLoop with (st' := st').\n      * (* show loop runs *) rewrite <- Hb1e. apply H.\n      * (* body execution *)\n        apply (Hc1e st st').  apply Hce1.\n      * (* subsequent loop execution *)\n        apply IHHce2. reflexivity.\n  - (* <- *)\n    remember (WHILE b1' DO c1' END) as c'while\n      eqn:Heqc'while.\n    induction Hce; inversion Heqc'while; subst.\n    + (* E_WhileEnd *)\n      apply E_WhileEnd. rewrite -> Hb1e. apply H.\n    + (* E_WhileLoop *)\n      apply E_WhileLoop with (st' := st').\n      * (* show loop runs *) rewrite -> Hb1e. apply H.\n      * (* body execution *)\n        apply (Hc1e st st').  apply Hce1.\n      * (* subsequent loop execution *)\n        apply IHHce2. reflexivity.  Qed.\n\n(** the next case is about command sequence\n                    cequiv c1 c1' \n                    cequiv c2 c2'\n           -----------------------------\n           cequiv (c1;;c2) (c1';;c2').\n*)\nTheorem CSeq_congruence : forall c1 c1' c2 c2',\n  cequiv c1 c1' -> cequiv c2 c2' ->\n  cequiv (c1;;c2) (c1';;c2').\nProof.\n  intros. unfold cequiv. split; intros He.\n  - (* <- *)\n  unfold cequiv in *. inversion He. subst.\n  apply H with (st':=st'0) in H3.\n  apply H0 with (st:=st'0) in H6.\n  apply E_Seq with (st':=st'0). assumption.\n  assumption.\n  - (* -> *)\n  unfold cequiv in *.\n  inversion He. subst.\n  apply H with (st':=st'0) in H3.\n  apply H0 with (st:=st'0) in H6.\n  apply E_Seq with (st':=st'0).\n  assumption.\n  assumption.\nQed.\n\n(** The final case is about if\n                    bequiv b b'\n                    cequiv c1 c1' \n                    cequiv c2 c2'\n         ----------------------------------------------------\n   cequiv (IFB b THEN c1 ELSE c2 FI) (IFB b' THEN c1' ELSE c2' FI).\n\n*)\nTheorem CIf_congruence : forall b b' c1 c1' c2 c2',\n  bequiv b b' -> cequiv c1 c1' -> cequiv c2 c2' ->\n  cequiv (IFB b THEN c1 ELSE c2 FI)\n         (IFB b' THEN c1' ELSE c2' FI).\nProof.\n  intros.\n  unfold cequiv.\n  split; intro He.\n  - (* -> *)\n  unfold cequiv in *.\n  unfold bequiv in H.\n  inversion He; subst.\n    + (* b => true *)\n    apply E_IfTrue. rewrite H in H7. assumption.\n    rewrite H0 in H8. assumption.\n    + (* b => false *)\n    apply E_IfFalse. rewrite H in H7. assumption.\n    rewrite H1 in H8. assumption.\n  - (* <- *)\n  unfold cequiv in *.\n  unfold bequiv in H.\n  symmetry in H.\n  inversion He; subst.\n     + (* b => true *)\n  apply E_IfTrue. rewrite H in H7. assumption.\n  rewrite <- H0 in H8. assumption.\n     + (* b => false *)\n  apply E_IfFalse. rewrite H in H7. assumption.\n  rewrite <- H1 in H8. assumption.\nQed.\n\n(** Now we finish the definition and proof about behaviorally equivalence\n    the next step is to use those definition and proof in constant propagation\n    and partial evaluation\n*)\n", "meta": {"author": "HugoTian", "repo": "CS386L_PL_coq", "sha": "34dea8b5badf8164dd1b10e49b32d17233e6e71d", "save_path": "github-repos/coq/HugoTian-CS386L_PL_coq", "path": "github-repos/coq/HugoTian-CS386L_PL_coq/CS386L_PL_coq-34dea8b5badf8164dd1b10e49b32d17233e6e71d/final project/ProgramEquivalence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6873972196530282}}
{"text": "Require Import \"F01_Defs\".\n(** * III. Affaiblissement par déclaration d'une sorte\nDans cette partie, nous étudions essentiellement l'affaiblissement de l'environnement par ajout d'une déclaration d'une variable de type. Nous utilisons pour cela un prédicat inductif caractérisant de tels affaiblissements d'un environnement. *)\n\n(** [insert_kind] est le prédicat inductif tel que [insert_kind X e e'] est prouvable ssi [e'] est une extension de [e] par une déclaration de sorte à l'indice [X] (et donc [e'] est l'affaiblissement de [e]). *)\nInductive insert_kind : var -> env -> env -> Prop :=\n| Top : forall e K, insert_kind 0 e (ConsK K e)\n| BelowK : forall e e' X K, insert_kind X e e' ->\n      insert_kind (S X) (ConsK K e) (ConsK K e')\n| BelowT : forall e e' X T, insert_kind X e e' ->\n      insert_kind (S X) (ConsT T e) (ConsT (tshift X T) e').\n(** *)\n\n\n(** ** Préservation du typage *)\n\n(** On montre ici deux lemmes intermédiaires puis on montre que l'affaiblissement par déclaration de sorte préserve les trois formes de typage. *)\n\n(** Le lemme suivant montre que l'ajout d'une sorte dans un environnement n'empêche pas d'accéder à ses anciens éléments, tant que l'on tient compte de l'éventuel shifting provoqué par l'insertion. *)\nLemma insert_kind_get_kind : forall X e e', insert_kind X e e' ->\n                forall Y, get_kind Y e = (get_kind (if leb X Y then S Y else Y) e').\n(** *)\nProof.\n  intros X e e' H. induction H; intros.\n  + easy.\n  + destruct Y; simpl.\n    reflexivity.\n    rewrite IHinsert_kind.\n    destruct (leb X Y) eqn:?.\n    reflexivity. reflexivity.\n  + destruct Y; simpl.\n    reflexivity.\n    rewrite IHinsert_kind.\n    destruct (leb X Y) eqn:?.\n    reflexivity. reflexivity.\nQed.\n(** *)\n\n\n(** De même, on montre que les types accessibles avant insertion d'une sorte le sont toujours après. *)\nLemma insert_kind_get_type : forall X e e', insert_kind X e e' -> forall x, \n            get_type x e' = match nat_compare X x with\n                              | Lt => option_map (tshift X) (get_type (x-1) e)\n                              | Eq => None\n                              | Gt => option_map (tshift (X)) (get_type x e) end.\n(** *)\nProof.\n  intros X e e' H. induction H; intros.\n  + destruct x; simpl. reflexivity. now rewrite <- minus_n_O.\n  + destruct x; simpl. reflexivity.\n    rewrite IHinsert_kind.\n    destruct (nat_compare X x) eqn:?; try reflexivity.\n    * apply nat_compare_Lt_lt in Heqc. destruct x. inv Heqc. rewrite <- minus_n_O. replace (S x - 1) with x. simpl.  destruct (get_type x e); [|reflexivity]. simpl. apply f_equal. specialize (tshift_tshift t 0 X). rewrite plus_O_n. easy. omega.\n    * apply nat_compare_Gt_gt in Heqc. destruct (get_type x e) as [T|]; [|reflexivity]. simpl. apply f_equal.      specialize (tshift_tshift T 0 X). rewrite plus_O_n. easy.\n  + destruct x; simpl. apply f_equal.  specialize (tshift_tshift T 0 X). rewrite plus_O_n. easy. \n    rewrite IHinsert_kind.\n    destruct (nat_compare X x) eqn:?; try reflexivity.\n    * apply nat_compare_Lt_lt in Heqc. destruct x. inv Heqc. rewrite <- minus_n_O. replace (S x - 1) with x.\n      simpl.  destruct (get_type x e); [|reflexivity]. simpl. apply f_equal. specialize (tshift_tshift t 0 X). rewrite plus_O_n. easy. omega.\n    * apply nat_compare_Gt_gt in Heqc. destruct (get_type x e); [|reflexivity]. simpl. apply f_equal.\n      specialize (tshift_tshift t 0 X). rewrite plus_O_n. easy.\nQed.\n(** *)\n\n\n(** On montre ici, que l'affaiblissement préserve les jugements de typage [wf] et [kinding].\nLa preuve se fait par induction mutuelle sur le jugement de typage, c'est pour cela que nous montrons les deux propriétés en même temps. *)\nLemma insert_kind_wf_kinding :\n  (forall e, wf e -> forall X e', insert_kind X e e' -> wf e')\n      /\\\n        (forall e T K, kinding e T K -> forall X e', insert_kind X e e' -> kinding e' (tshift X T) K).\n(** *)\nProof.\n  apply wf_kinding_ind_mut.\n  + intros X e' Hins. inv Hins. apply WfConsK. apply WfNil.\n  + intros K e w IHHwf X e' Hins. inv Hins. apply WfConsK. now apply WfConsK.\n    apply WfConsK. eapply IHHwf. eassumption.\n  + intros T e K k IHHwf w IHHwf0 X e' Hins. inv Hins. apply WfConsK. eapply WfConsT; eassumption. eapply WfConsT. apply IHHwf. \nassumption. eapply IHHwf0. eassumption.\n  + intros e Y p q w IHHwf H H' X e' Hins. specialize (insert_kind_get_kind _ _ _ Hins Y). intros. simpl. destruct (leb X Y); eapply KVar; eauto. congruence.\n    congruence.\n  + intros e T1 T2 p q k IHHwf Hk IHHwf0 X e' Hins. apply KArrow; auto.\n  + intros e T p q k IHHwf X e' Hins. apply KFAll. apply IHHwf. now apply BelowK.\nQed.\n(** *)\n\n\n(** Et on montre ici la préservation du troisième jugement de typage : [typing]. *)\nLemma insert_kind_typing : forall e t T, typing e t T ->\n       forall X e', insert_kind X e e' -> typing e' (shift X t) (tshift X T).\n(** *)\nProof.\n  intros e t T Ht. induction Ht; intros X e' Hins.\n  + simpl. destruct (leb X x) eqn:?.\n    * econstructor. eapply insert_kind_wf_kinding; eassumption.\n      rewrite (insert_kind_get_type _ _ _ Hins (S x)).\n      replace (nat_compare X (S x)) with Lt. simpl.\n      rewrite <- minus_n_O. now rewrite H0. symmetry. \n      apply nat_compare_lt. apply leb_complete in Heqb. omega.\n    * constructor. eapply insert_kind_wf_kinding; eassumption.\n      rewrite (insert_kind_get_type _ _ _ Hins (x)).\n      replace (nat_compare X (x)) with Gt. now rewrite H0. symmetry. \n      apply nat_compare_gt. apply leb_complete_conv in Heqb. omega.\n  + simpl. constructor. specialize (IHHt (S X) (ConsT (tshift X T1) e')). specialize (tshift_tshift T2 0 X). intro Htt.\n    rewrite plus_O_n in Htt. rewrite Htt. apply IHHt.\n    now constructor.\n  + econstructor. now apply IHHt1.\n    now apply IHHt2.\n  + constructor. apply IHHt. now constructor.\n  + replace (tshift X (tsubst 0 T2 T1)) with (tsubst 0 (tshift X T2) (tshift (S X) T1)).\n    apply (TAppT _ _ K). replace (FAll K (tshift (S X) T1)) with (tshift X (FAll K T1)).\n    now apply IHHt. reflexivity.\n    eapply insert_kind_wf_kinding; eassumption.\n    specialize  (tsubst_tshift T1 0 X T2).\n    now rewrite plus_O_n.\nQed.\n(** *)\n\n(** ** Préservation de [kinding] par substitution  *)\n\n(** Ici, nous profitons de [insert_kind] pour exprimer le fait que la substitution préserve [kinding]. *)\n\n(**  *)\nLemma kinding_wf : forall e T K, kinding e T K -> wf e.\n(** *)\nProof.\nintros e T K H. induction H; auto.\nnow inv IHkinding.\nQed.\n(** *)\n\n\n(**  *)\nLemma tsubst_kinding : forall T e' K, kinding e' T K ->\n                                      forall X e L U, insert_kind X e e' -> get_kind X e' = Some L -> kinding e U L -> kinding e (tsubst X U T) K.\n(** *)\nProof.\n  induction T as [Y|T1 IHT1 T2 IHT2|k T]; intros e' K HkT X e L U Hik Hgk HkU.\n  - destruct (nat_compare X Y) eqn:H.\n    + simpl. rewrite H. destruct (le_lt_dec K L) as [H1|H1].\n      inversion HkT. comp.\n      replace L with p in HkU.\n      now apply (cumulativity U e p K).\n      rewrite <- H in H3. rewrite H3 in Hgk. now injection Hgk.\n      apply (cumulativity U e L K). omega. assumption.\n    + simpl. rewrite H. inversion HkT. comp. apply KVar with p.\n      apply (kinding_wf e U L HkU).\n      rewrite (insert_kind_get_kind X e e'). replace (leb X (Y-1)) with true. \n      replace (S (Y-1)) with Y. assumption.\n      destruct Y; [omega|]. now mysimpl.\n      symmetry. comp. omega.\n      assumption. assumption.\n      (* comme les 2e et 3e + se ressemblent, \n         comment on les traite de la meme façon ? *)\n    + simpl. rewrite H. inversion HkT. apply KVar with p.\n      apply (kinding_wf e U L HkU).\n      rewrite (insert_kind_get_kind X e e'). replace (leb X Y) with false. assumption.\n      symmetry. comp. omega.\n      assumption. assumption.\n  - simpl. inversion HkT. apply KArrow.\n    + now apply IHT1 with e' L.\n    + now apply IHT2 with e' L.\n  - simpl. inversion HkT. apply KFAll.\n    apply IHT with (ConsK k e') L. assumption.\n    now constructor.\n    assumption.\n    apply (proj2 (insert_kind_wf_kinding)) with e. assumption.\n    constructor.\nQed.\n\n\n\n(** #<script src=\"jquery.min.js\"></script>#\n    #<script src=\"coqjs.js\"></script># *)", "meta": {"author": "lewer", "repo": "systemF-coq", "sha": "feffde3745ebaaf5784a31e19464772ab1414cd1", "save_path": "github-repos/coq/lewer-systemF-coq", "path": "github-repos/coq/lewer-systemF-coq/systemF-coq-feffde3745ebaaf5784a31e19464772ab1414cd1/F03_Insert_kind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511359371249, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6873972039508931}}
{"text": "(* P. Casteran *)\n\nRequire Import Arith.\n\nFixpoint mult2 (n:nat) : nat :=\n  match n with\n  | O => 0\n  | S p => S (S (mult2 p))\n  end.\n\n\nLemma mult2_double : forall n:nat, mult2 n = n + n.\nProof.\n intro n; elim n; simpl; auto.\n intros n0 H; rewrite H.\n rewrite <- plus_n_Sm; trivial.\nQed.\n\n\n\n\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/structinduct/SRC/mult2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.6873497269220248}}
{"text": "Require Import prosa.classic.util.all.\nRequire Import prosa.classic.analysis.global.parallel.bertogna_fp_theory.\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq fintype bigop div path.\n\nModule ResponseTimeIterationFP.\n\n  Import ResponseTimeAnalysisFP.\n\n  (* In this section, we define the algorithm of Bertogna and Cirinei's\n     response-time analysis for FP scheduling with parallel jobs. *)\n  Section Analysis.\n    \n    Context {sporadic_task: eqType}.\n    Variable task_cost: sporadic_task -> time.\n    Variable task_period: sporadic_task -> time.\n    Variable task_deadline: sporadic_task -> time.\n\n    (* During the iterations of the algorithm, we pass around pairs\n       of tasks and computed response-time bounds. *)\n    Let task_with_response_time := (sporadic_task * time)%type.\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 -> sporadic_task.\n\n    (* Consider a platform with num_cpus processors, ... *)\n    Variable num_cpus: nat.\n\n    (* ..., and priorities based on an FP policy. *)\n    Variable higher_priority: FP_policy sporadic_task.\n\n    (* Next we define the fixed-point iteration for computing\n       Bertogna's response-time bound of a task set. *)\n    \n    (* First, given a sequence of pairs R_prev = <..., (tsk_hp, R_hp)> of\n       response-time bounds for the higher-priority tasks, we define an\n       iteration that computes the response-time bound of the current task:\n\n           R_tsk (0) = task_cost tsk\n           R_tsk (step + 1) =  f (R step),\n\n       where f is the response-time recurrence, step is the number of iterations,\n       and R_tsk (0) is the initial state. *)\n    Definition per_task_rta (tsk: sporadic_task)\n                            (R_prev: seq task_with_response_time) (step: nat) :=\n      iter step\n        (fun t => task_cost tsk +\n                  div_floor\n                    (total_interference_bound_fp task_cost task_period R_prev t)\n                    num_cpus)\n        (task_cost tsk).\n\n    (* To ensure that the iteration converges, we will apply per_task_rta\n       a \"sufficient\" number of times: task_deadline tsk - task_cost tsk + 1.\n       This corresponds to the time complexity of the iteration. *)\n    Definition max_steps (tsk: sporadic_task) := task_deadline tsk - task_cost tsk + 1.\n    \n    (* Next we compute the response-time bounds for the entire task set.\n       Since high-priority tasks may not be schedulable, we allow the\n       computation to fail.\n       Thus, given the response-time bound of previous tasks, we either\n       (a) append the computed response-time bound (tsk, R) of the current task\n           to the list of pairs, or,\n       (b) return None if the response-time analysis failed. *)\n    Definition fp_bound_of_task hp_pairs tsk :=\n      if hp_pairs is Some rt_bounds then\n        let R := per_task_rta tsk rt_bounds (max_steps tsk) in\n          if R <= task_deadline tsk then\n            Some (rcons rt_bounds (tsk, R))\n          else None\n      else None.\n\n    (* The response-time analysis for a given task set is defined\n       as a left-fold (reduce) based on the function above.\n       This either returns a list of task and response-time bounds, or None. *)\n    Definition fp_claimed_bounds (ts: seq sporadic_task) :=\n      foldl fp_bound_of_task (Some [::]) ts.\n\n    (* The schedulability test simply checks if we got a list of\n       response-time bounds (i.e., if the computation did not fail). *)\n    Definition fp_schedulable (ts: seq sporadic_task) :=\n      fp_claimed_bounds ts != None.\n    \n    (* In the following section, we prove several helper lemmas about the\n       list of response-time bounds. The results seem trivial, but must be proven\n       nonetheless since the list of response-time bounds is computed with\n       a specific algorithm and there are no lemmas in the library for that. *)\n    Section SimpleLemmas.\n\n      (* First, we show that the first component of the computed list is the set of tasks. *)\n      Lemma fp_claimed_bounds_unzip :\n        forall ts hp_bounds, \n          fp_claimed_bounds ts = Some hp_bounds ->\n          unzip1 hp_bounds = ts.\n      Proof.\n        unfold fp_claimed_bounds in *; intros ts.\n        induction ts using last_ind; first by destruct hp_bounds.\n        {\n          intros hp_bounds SOME.\n          destruct (lastP hp_bounds) as [| hp_bounds'].\n          {\n            rewrite -cats1 foldl_cat /= in SOME.\n            unfold fp_bound_of_task at 1 in SOME; simpl in *; desf.\n            by destruct l.\n          }\n          rewrite -cats1 foldl_cat /= in SOME.\n          unfold fp_bound_of_task at 1 in SOME; simpl in *; desf.\n          move: H0 => /eqP EQSEQ.\n          rewrite eqseq_rcons in EQSEQ.\n          move: EQSEQ => /andP [/eqP SUBST /eqP EQSEQ]; subst.\n          unfold unzip1; rewrite map_rcons; f_equal.\n          by apply IHts.\n        }\n      Qed.\n      \n      (* Next, we show that some properties of the analysis are preserved for the\n         prefixes of the list: (a) the tasks do not change, (b) R <= deadline,\n         (c) R is computed using the response-time equation, ... *) \n      Lemma fp_claimed_bounds_rcons :\n        forall ts' hp_bounds tsk1 tsk2 R,\n          (fp_claimed_bounds (rcons ts' tsk1) = Some (rcons hp_bounds (tsk2, R)) ->\n           (fp_claimed_bounds ts' = Some hp_bounds /\\\n            tsk1 = tsk2 /\\\n            R = per_task_rta tsk1 hp_bounds (max_steps tsk1) /\\\n            R <= task_deadline tsk1)).\n      Proof.\n        intros ts hp_bounds tsk tsk' R.\n        rewrite -cats1.\n        unfold fp_claimed_bounds in *.\n        rewrite foldl_cat /=.\n        unfold fp_bound_of_task at 1; simpl; desf.\n        intros EQ; inversion EQ; move: EQ H0 => _ /eqP EQ.\n        rewrite eqseq_rcons in EQ.\n        move: EQ => /andP [/eqP EQ /eqP RESP].\n        by inversion RESP; repeat split; subst.\n      Qed.\n\n      (* ..., which implies that any prefix of the computation is the computation\n         of the prefix. *)\n      Lemma fp_claimed_bounds_take :\n        forall ts hp_bounds i,\n          fp_claimed_bounds ts = Some hp_bounds ->\n          i <= size hp_bounds ->\n          fp_claimed_bounds (take i ts) = Some (take i hp_bounds).\n      Proof.                                                        \n        intros ts hp_bounds i SOME LTi.\n        have UNZIP := fp_claimed_bounds_unzip ts hp_bounds SOME.\n        rewrite <- UNZIP in *.\n        rewrite -[hp_bounds]take_size /unzip1 map_take in SOME.\n        fold (unzip1 hp_bounds) in *; clear UNZIP.\n        rewrite leq_eqVlt in LTi.\n        move: LTi => /orP [/eqP EQ | LTi]; first by subst.\n        remember (size hp_bounds) as len; apply eq_leq in Heqlen.\n        induction len; first by rewrite ltn0 in LTi.\n        {\n          assert (TAKElen: fp_claimed_bounds (take len (unzip1 (hp_bounds))) =\n                             Some (take len (hp_bounds))).\n          {\n            assert (exists p, p \\in hp_bounds).\n            {\n              destruct hp_bounds; first by rewrite ltn0 in Heqlen.\n              by exists t; rewrite in_cons eq_refl orTb.\n            } destruct H as [[tsk R] _].\n             rewrite (take_nth tsk) in SOME; last by rewrite size_map.\n            rewrite (take_nth (tsk,R)) in SOME; last by done.\n            destruct (nth (tsk, R) hp_bounds len) as [tsk_len R_len].\n            by apply fp_claimed_bounds_rcons in SOME; des.\n          }\n          rewrite ltnS leq_eqVlt in LTi.\n          move: LTi => /orP [/eqP EQ | LESS]; first by subst.\n          apply ltnW in Heqlen.\n          by specialize (IHlen Heqlen TAKElen LESS).\n        }\n      Qed.\n      \n      (* If the analysis suceeds, the computed response-time bounds are no larger\n         than the deadline... *)\n      Lemma fp_claimed_bounds_le_deadline :\n        forall ts' rt_bounds tsk R,\n          fp_claimed_bounds ts' = Some rt_bounds ->\n          (tsk, R) \\in rt_bounds ->\n          R <= task_deadline tsk.\n      Proof.\n        intros ts; induction ts as [| ts' tsk_lst] using last_ind.\n        {\n          intros rt_bounds tsk R SOME IN.\n          by inversion SOME; subst; rewrite in_nil in IN.\n        }\n        {\n          intros rt_bounds tsk_i R SOME IN.\n          destruct (lastP rt_bounds) as [|rt_bounds (tsk_lst', R_lst)];\n            first by rewrite in_nil in IN.\n          rewrite mem_rcons in_cons in IN; move: IN => /orP IN.\n          destruct IN as [LAST | FRONT].\n          {\n            move: LAST => /eqP LAST.\n            rewrite -cats1 in SOME.\n            unfold fp_claimed_bounds in *.\n            rewrite foldl_cat /= in SOME.\n            unfold fp_bound_of_task in SOME.\n            desf; rename H0 into EQ.\n            move: EQ => /eqP EQ.\n            rewrite eqseq_rcons in EQ.\n            move: EQ => /andP [_ /eqP EQ].\n            inversion EQ; subst.\n            by apply Heq0.\n          }\n          {\n            apply IHts with (rt_bounds := rt_bounds); last by ins.\n            by apply fp_claimed_bounds_rcons in SOME; des.\n          }\n        }\n      Qed.\n      \n      (* ... and the computed response-time bounds are no smaller than\n         the task costs. *)\n      Lemma fp_claimed_bounds_ge_cost :\n        forall ts' rt_bounds tsk R,\n          fp_claimed_bounds ts' = Some rt_bounds ->\n          (tsk, R) \\in rt_bounds ->\n          R >= task_cost tsk.\n      Proof.\n        intros ts; induction ts as [| ts' tsk_lst] using last_ind.\n        {\n          intros rt_bounds tsk R SOME IN.\n          by inversion SOME; subst; rewrite in_nil in IN.\n        }\n        {\n          intros rt_bounds tsk_i R SOME IN.\n          destruct (lastP rt_bounds) as [|rt_bounds (tsk_lst', R_lst)];\n            first by rewrite in_nil in IN.\n          rewrite mem_rcons in_cons in IN; move: IN => /orP IN.\n          destruct IN as [LAST | FRONT].\n          {\n            move: LAST => /eqP LAST.\n            rewrite -cats1 in SOME.\n            unfold fp_claimed_bounds in *.\n            rewrite foldl_cat /= in SOME.\n            unfold fp_bound_of_task in SOME.\n            desf; rename H0 into EQ.\n            move: EQ => /eqP EQ.\n            rewrite eqseq_rcons in EQ.\n            move: EQ => /andP [_ /eqP EQ].\n            inversion EQ; subst.\n            by destruct (max_steps tsk_lst');\n              [by apply leqnn | by apply leq_addr].\n          }\n          {\n            apply IHts with (rt_bounds := rt_bounds); last by ins.\n            by apply fp_claimed_bounds_rcons in SOME; des.\n          }\n        }\n      Qed.\n\n      (* Short lemma about unfolding the iteration one step. *)\n      Lemma per_task_rta_fold :\n        forall tsk rt_bounds,\n          task_cost tsk +\n           div_floor (total_interference_bound_fp task_cost task_period rt_bounds\n                     (per_task_rta tsk rt_bounds (max_steps tsk))) num_cpus\n          = per_task_rta tsk rt_bounds (max_steps tsk).+1.\n      Proof.\n          by done.\n      Qed.\n\n    End SimpleLemmas.\n\n    (* In this section, we prove that if the task set is sorted by priority,\n       the tasks in fp_claimed_bounds are interfering tasks.  *)\n    Section HighPriorityTasks.\n\n      (* Consider a list of previous tasks and a task tsk to be analyzed. *)\n      Variable ts: taskset_of sporadic_task.\n\n      (* Assume that the task set is sorted by unique priorities, ... *)\n      Hypothesis H_task_set_is_sorted: sorted higher_priority ts.\n      Hypothesis H_task_set_has_unique_priorities:\n        FP_is_antisymmetric_over_task_set higher_priority ts.\n\n      (* ...the priority order is transitive, ...*)\n      Hypothesis H_priority_transitive: FP_is_transitive higher_priority.\n      \n      (* ... and that the response-time analysis succeeds. *)\n      Variable hp_bounds: seq task_with_response_time.\n      Variable R: time.\n      Hypothesis H_analysis_succeeds: fp_claimed_bounds ts = Some hp_bounds.\n\n      (* Let's refer to tasks by index. *)\n      Variable elem: sporadic_task.\n      Let TASK := nth elem ts.\n                    \n      (* We prove that higher-priority tasks have smaller index. *)\n      Lemma fp_claimed_bounds_hp_tasks_have_smaller_index :\n        forall hp_idx idx,\n          hp_idx < size ts ->\n          idx < size ts ->\n          hp_idx != idx ->\n          higher_priority (TASK hp_idx) (TASK idx) ->\n          hp_idx < idx.\n      Proof.\n        unfold TASK; clear TASK.\n        rename ts into ts'; destruct ts' as [ts UNIQ]; simpl in *.\n        intros hp_idx idx LThp LT NEQ HP.\n        rewrite ltn_neqAle; apply/andP; split; first by done.\n        by apply sorted_rel_implies_le_idx with (leT := higher_priority) (xs := ts) (default := elem).\n      Qed.\n      \n    End HighPriorityTasks.\n\n    (* In this section, we show that the fixed-point iteration converges. *)\n    Section Convergence.\n\n      (* Consider any set of higher-priority tasks. *)\n      Variable ts_hp: seq sporadic_task.\n\n      (* Assume that the response-time analysis succeeds for the higher-priority tasks. *)\n      Variable rt_bounds: seq task_with_response_time.\n      Hypothesis H_test_succeeds: fp_claimed_bounds ts_hp = Some rt_bounds.\n\n      (* Consider any task tsk to be analyzed, ... *)\n      Variable tsk: sporadic_task.\n\n      (* ... and assume all tasks have valid parameters. *)\n      Hypothesis H_valid_task_parameters:\n        valid_sporadic_taskset task_cost task_period task_deadline (rcons ts_hp tsk).\n\n      (* To simplify, let f denote the fixed-point iteration. *)\n      Let f := per_task_rta tsk rt_bounds.\n\n      (* Assume that f (max_steps tsk) is no larger than the deadline. *)\n      Hypothesis H_no_larger_than_deadline: f (max_steps tsk) <= task_deadline tsk.\n\n      (* First, we show that f is monotonically increasing. *)\n      Lemma bertogna_fp_comp_f_monotonic :\n        forall x1 x2, x1 <= x2 -> f x1 <= f x2.\n      Proof.\n        unfold valid_sporadic_taskset, is_valid_sporadic_task in *.\n        rename H_test_succeeds into SOME,\n               H_valid_task_parameters into VALID.\n        intros x1 x2 LEx; unfold f, per_task_rta.\n        apply fun_mon_iter_mon; [by ins | by ins; apply leq_addr |].\n        clear LEx x1 x2; intros x1 x2 LEx.\n        rewrite leq_add2l leq_div2r //.\n        unfold total_interference_bound_fp.\n        rewrite big_seq_cond.\n        rewrite [\\sum_(_ <- _ | true) _]big_seq_cond.\n        apply leq_sum; move => i /andP [IN _].\n        destruct i as [i R].\n        have GE_COST := fp_claimed_bounds_ge_cost ts_hp rt_bounds i R SOME IN.\n        have UNZIP := fp_claimed_bounds_unzip ts_hp rt_bounds SOME.\n        unfold interference_bound_generic; simpl.\n        apply W_monotonic; try (by done).\n        have INts: i \\in ts_hp by rewrite -UNZIP; apply/mapP; exists (i, R).\n        by exploit (VALID i);\n          [by rewrite mem_rcons in_cons INts orbT | by ins; des].\n      Qed.\n\n      (* If the iteration converged at an earlier step, then it remains stable. *)\n      Lemma bertogna_fp_comp_f_converges_early :\n        (exists k, k <= max_steps tsk /\\ f k = f k.+1) ->\n        f (max_steps tsk) = f (max_steps tsk).+1.\n      Proof.\n        by intros EX; des; apply fixedpoint.iter_fix with (k := k).\n      Qed.\n\n      (* Else, we derive a contradiction. *)\n      Section DerivingContradiction.\n\n        (* Assume instead that the iteration continued to diverge. *)\n        Hypothesis H_keeps_diverging:\n          forall k,\n            k <= max_steps tsk -> f k != f k.+1.\n\n        (* By monotonicity, it follows that the value always increases. *)\n        Lemma bertogna_fp_comp_f_increases :\n          forall k,\n            k <= max_steps tsk ->\n            f k < f k.+1.\n        Proof.\n          intros k LT.\n          rewrite ltn_neqAle; apply/andP; split.\n            by apply H_keeps_diverging.\n            by apply bertogna_fp_comp_f_monotonic, leqnSn.\n        Qed.\n\n        (* In the end, the response-time bound must exceed the deadline. Contradiction! *)\n        Lemma bertogna_fp_comp_rt_grows_too_much :\n          forall k,\n            k <= max_steps tsk ->\n            f k > k + task_cost tsk - 1.\n        Proof.\n          have INC := bertogna_fp_comp_f_increases.\n          rename H_valid_task_parameters into TASK_PARAMS.\n          unfold valid_sporadic_taskset, is_valid_sporadic_task in *; des.\n          exploit (TASK_PARAMS tsk);\n            [by rewrite mem_rcons in_cons eq_refl orTb | intro PARAMS; des].\n          induction k.\n          {\n            intros _; rewrite add0n -addn1 subh1;\n              first by rewrite -addnBA // subnn addn0 /= leqnn.\n            by apply PARAMS.\n          }\n          {\n            intros LT.\n            specialize (IHk (ltnW LT)).\n            apply leq_ltn_trans with (n := f k); last by apply INC, ltnW.\n            rewrite -addn1 -addnA [1 + _]addnC addnA -addnBA // subnn addn0.\n            rewrite -(ltn_add2r 1) in IHk.\n            rewrite subh1 in IHk;\n              last by apply leq_trans with (n := task_cost tsk);\n                [by apply PARAMS | by apply leq_addl].\n            by rewrite -addnBA // subnn addn0 addn1 ltnS in IHk.\n          }  \n        Qed.\n\n      End DerivingContradiction.\n      \n      (* Using the lemmas above, we prove the convergence of the iteration after max_steps. *)\n      Lemma per_task_rta_converges:\n        f (max_steps tsk) = f (max_steps tsk).+1.\n      Proof.\n        have TOOMUCH := bertogna_fp_comp_rt_grows_too_much.\n        have INC := bertogna_fp_comp_f_increases.\n        rename H_no_larger_than_deadline into LE,\n               H_valid_task_parameters into TASK_PARAMS.\n        unfold valid_sporadic_taskset, is_valid_sporadic_task in *; des.\n       \n        (* Either f converges by the deadline or not. *)\n        destruct ([exists k in 'I_(max_steps tsk).+1, f k == f k.+1]) eqn:EX.\n        {\n          move: EX => /exists_inP EX; destruct EX as [k _ ITERk].\n          apply bertogna_fp_comp_f_converges_early.\n          by exists k; split; [by rewrite -ltnS; apply ltn_ord | by apply/eqP].\n        }\n\n        (* If not, then we reach a contradiction *)\n        apply negbT in EX; rewrite negb_exists_in in EX.\n        move: EX => /forall_inP EX.\n        rewrite leqNgt in LE; move: LE => /negP LE.\n        exfalso; apply LE.\n\n        assert (DIFF: forall k : nat, k <= max_steps tsk -> f k != f k.+1).\n        {\n          intros k LEk; rewrite -ltnS in LEk.\n          by exploit (EX (Ordinal LEk)); [by done | intro DIFF; apply DIFF].\n        }          \n        exploit TOOMUCH; [by apply DIFF | by apply leq_addr |].\n        exploit (TASK_PARAMS tsk);\n          [by rewrite mem_rcons in_cons eq_refl orTb | intro PARAMS; des].\n        rewrite subh1; last by apply PARAMS2.\n        rewrite -addnBA // subnn addn0 subn1 prednK //.\n        intros LT; apply (leq_ltn_trans LT).\n        by rewrite /max_steps [_ - _ + 1]addn1; apply INC, leq_addr.\n      Qed.\n      \n    End Convergence.\n    \n    Section MainProof.\n\n      (* Consider a task set ts. *)\n      Variable ts: taskset_of sporadic_task.\n      \n      (* Assume that all tasks have valid parameters, ... *)\n      Hypothesis H_valid_task_parameters:\n        valid_sporadic_taskset task_cost task_period task_deadline ts.\n\n      (* ...and constrained deadlines.*)\n      Hypothesis H_constrained_deadlines:\n        forall tsk, tsk \\in ts -> task_deadline tsk <= task_period tsk.\n\n       (* Assume that the task set is totally ordered by unique priorities,\n          and that the priority order is transitive. *)\n      Hypothesis H_task_set_is_sorted: sorted higher_priority ts.\n      Hypothesis H_task_set_has_unique_priorities:\n        FP_is_antisymmetric_over_task_set higher_priority ts.\n      Hypothesis H_priority_is_total:\n        FP_is_total_over_task_set higher_priority ts.\n      Hypothesis H_priority_transitive: FP_is_transitive higher_priority.\n\n      (* Next, consider any arrival sequence such that...*)\n      Variable arr_seq: arrival_sequence Job.\n\n     (* ...all jobs come from task set ts, ...*)\n      Hypothesis H_all_jobs_from_taskset:\n        forall j, arrives_in arr_seq j -> job_task j \\in ts.\n      \n      (* ...they 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      (* ... and satisfy the sporadic task model.*)\n      Hypothesis H_sporadic_tasks:\n        sporadic_task_model task_period job_arrival job_task arr_seq.\n      \n      (* Then, consider any schedule of this arrival sequence such that... *)\n      Variable sched: schedule Job num_cpus.\n      Hypothesis H_at_least_one_cpu: num_cpus > 0.\n      Hypothesis H_jobs_come_from_arrival_sequence:\n        jobs_come_from_arrival_sequence sched arr_seq.\n      \n      (* ...jobs only execute after they arrived and no longer\n         than their execution costs,... *)\n      Hypothesis H_jobs_must_arrive_to_execute:\n        jobs_must_arrive_to_execute job_arrival sched.\n      Hypothesis H_completed_jobs_dont_execute:\n        completed_jobs_dont_execute job_cost sched.\n\n      (* Assume that the scheduler is work-conserving and respects the FP policy. *)\n      Hypothesis H_work_conserving: work_conserving job_arrival job_cost arr_seq sched.\n      Hypothesis H_respects_FP_policy:\n        respects_FP_policy job_arrival job_cost job_task arr_seq sched higher_priority.\n\n      Let no_deadline_missed_by_task (tsk: sporadic_task) :=\n        task_misses_no_deadline job_arrival job_cost job_deadline job_task arr_seq sched tsk.\n      Let no_deadline_missed_by_job :=\n        job_misses_no_deadline job_arrival job_cost job_deadline sched.\n      Let response_time_bounded_by (tsk: sporadic_task) :=\n        is_response_time_bound_of_task job_arrival job_cost job_task arr_seq sched tsk.\n          \n      (* In the following theorem, we prove that any response-time bound contained\n         in fp_claimed_bounds is safe. The proof follows by induction on the task set:\n\n           Induction hypothesis: all higher-priority tasks have safe response-time bounds.\n           Inductive step: We prove that the response-time bound of the current task is safe.\n\n         Note that the inductive step is a direct application of the main Theorem from\n         bertogna_fp_theory.v. *)\n      Theorem fp_analysis_yields_response_time_bounds :\n        forall tsk R,\n          (tsk, R) \\In fp_claimed_bounds ts ->\n          response_time_bounded_by tsk R.\n      Proof.\n        rename H_valid_job_parameters into JOBPARAMS, H_valid_task_parameters into TASKPARAMS.\n        unfold valid_sporadic_taskset in *.\n        intros tsk R MATCH.\n        assert (SOME: exists hp_bounds, fp_claimed_bounds ts = Some hp_bounds /\\\n                                        (tsk, R) \\in hp_bounds).\n        {\n          destruct (fp_claimed_bounds ts); last by done.\n          by exists l; split.\n        } clear MATCH; des; rename SOME0 into IN.\n\n        have UNZIP := fp_claimed_bounds_unzip ts hp_bounds SOME.\n        \n        set elem := (tsk,R).\n        move: IN => /(nthP elem) [idx LTidx EQ].\n        set NTH := fun k => nth elem hp_bounds k.\n        set TASK := fun k => (NTH k).1.\n        set RESP := fun k => (NTH k).2.\n        cut (response_time_bounded_by (TASK idx) (RESP idx));\n          first by unfold TASK, RESP, NTH; rewrite EQ.\n        clear EQ.\n\n        assert (PAIR: forall idx, (TASK idx, RESP idx) = NTH idx).\n          by intros i; unfold TASK, RESP; destruct (NTH i).\n\n        assert (SUBST: forall i, i < size hp_bounds -> TASK i = nth tsk ts i).\n          by intros i LTi; rewrite /TASK /NTH -UNZIP (nth_map elem) //.\n\n        assert (SIZE: size hp_bounds = size ts).\n          by rewrite -UNZIP size_map.\n\n        induction idx as [idx IH'] using strong_ind.\n\n        assert (IH: forall tsk_hp R_hp, (tsk_hp, R_hp) \\in take idx hp_bounds -> response_time_bounded_by tsk_hp R_hp).\n        {\n          intros tsk_hp R_hp INhp.\n          move: INhp => /(nthP elem) [k LTk EQ].\n          rewrite size_take LTidx in LTk.\n          rewrite nth_take in EQ; last by done.\n          cut (response_time_bounded_by (TASK k) (RESP k));\n            first by unfold TASK, RESP, NTH; rewrite EQ.\n          by apply IH'; try (by done); apply (ltn_trans LTk).\n        } clear IH'.\n\n        unfold response_time_bounded_by in *.\n\n        exploit (fp_claimed_bounds_rcons (take idx ts) (take idx hp_bounds) (TASK idx) (TASK idx) (RESP idx)).\n        {\n          by rewrite PAIR SUBST // -2?take_nth -?SIZE // (fp_claimed_bounds_take _ hp_bounds).\n        }\n        intros [_ [_ [REC DL]]].\n\n        apply bertogna_cirinei_response_time_bound_fp with\n              (task_cost0 := task_cost) (task_period0 := task_period)\n              (task_deadline0 := task_deadline) (job_deadline0 := job_deadline) (tsk0 := (TASK idx))\n              (job_task0 := job_task) (ts0 := ts) (hp_bounds0 := take idx hp_bounds)\n              (higher_eq_priority := higher_priority); try (by done).\n        {\n          cut (NTH idx \\in hp_bounds = true);\n            [intros IN | by apply mem_nth].\n          by rewrite set_mem -UNZIP; apply/mapP; exists (TASK idx, RESP idx); rewrite PAIR.\n        }\n        {\n          intros hp_tsk IN INTERF.\n          exists (RESP (index hp_tsk ts)).\n          move: (IN) => INDEX; apply nth_index with (x0 := tsk) in INDEX.\n          rewrite -{1}[hp_tsk]INDEX -SUBST; last by rewrite SIZE index_mem.\n          assert (UNIQ: uniq hp_bounds).\n          {\n            apply map_uniq with (f := fst); unfold unzip1 in *; rewrite UNZIP.\n            by destruct ts.\n          }\n          rewrite -filter_idx_lt_take //.\n          {\n            rewrite PAIR mem_filter; apply/andP; split;\n              last by apply mem_nth; rewrite SIZE index_mem.\n            {\n              rewrite /NTH index_uniq; [| by rewrite SIZE index_mem | by done ].\n              {\n                move: INTERF => /andP [HP NEQ].\n                apply fp_claimed_bounds_hp_tasks_have_smaller_index with\n                  (ts := ts) (elem := tsk) (hp_bounds := hp_bounds);\n                  try (by done);\n                  [by rewrite index_mem | by rewrite -SIZE | | by rewrite INDEX -SUBST].\n                apply/eqP; intro BUG; subst idx.\n                rewrite SUBST -{1}INDEX in NEQ;\n                  first by rewrite eq_refl in NEQ.\n                by rewrite SIZE index_mem INDEX.\n              }\n            }\n          }\n        }\n        {\n          rewrite REC per_task_rta_fold.\n          apply per_task_rta_converges with (ts_hp := take idx ts);\n            [by apply fp_claimed_bounds_take; try (by apply ltnW) | | by rewrite -REC ].\n          rewrite SUBST // -take_nth -?SIZE //.\n          by intros i IN; eapply TASKPARAMS, mem_take, IN.\n        }\n      Qed.\n      \n      (* Therefore, if the schedulability test suceeds, ...*)\n      Hypothesis H_test_succeeds: fp_schedulable ts.\n      \n      (*..., no task misses its deadline. *)\n      Theorem taskset_schedulable_by_fp_rta :\n        forall tsk, tsk \\in ts -> no_deadline_missed_by_task tsk.\n      Proof.\n        have RLIST := (fp_analysis_yields_response_time_bounds).\n        have UNZIP := (fp_claimed_bounds_unzip ts).\n        have DL := (fp_claimed_bounds_le_deadline ts).\n        unfold no_deadline_missed_by_task, task_misses_no_deadline,\n               job_misses_no_deadline, completed,\n               fp_schedulable, valid_sporadic_job in *.\n        rename H_valid_job_parameters into JOBPARAMS.\n        move => tsk INtsk j ARRj JOBtsk.\n        \n        destruct (fp_claimed_bounds ts) as [rt_bounds |]; last by ins.\n        feed (UNZIP rt_bounds); first by done.\n        assert (EX: exists R, (tsk, R) \\in rt_bounds).\n        {\n          rewrite set_mem -UNZIP in INtsk; move: INtsk => /mapP EX.\n          by destruct EX as [p]; destruct p as [tsk' R]; simpl in *; subst tsk'; exists R.\n        } des.\n        exploit (RLIST tsk R); eauto 1; intro COMPLETED.\n        exploit (DL rt_bounds tsk R); [by ins | by ins | clear DL; intro DL].\n        apply leq_trans with (n := service sched j (job_arrival j + R)); last first.\n        {\n          unfold valid_sporadic_taskset, is_valid_sporadic_task in *.\n          apply extend_sum; rewrite // leq_add2l.\n          specialize (JOBPARAMS j ARRj); des; rewrite JOBPARAMS1.\n          by rewrite JOBtsk.\n        }\n        by done.\n      Qed.\n\n      (* For completeness, since all jobs of the arrival sequence\n         are spawned by the task set, we also conclude that no job in\n         the schedule misses its deadline. *)\n      Theorem jobs_schedulable_by_fp_rta :\n        forall j, arrives_in arr_seq j -> no_deadline_missed_by_job j.\n      Proof.\n        intros j ARRj.\n        have SCHED := taskset_schedulable_by_fp_rta.\n        unfold no_deadline_missed_by_task, task_misses_no_deadline in *.\n        apply SCHED with (tsk := job_task j); try (by done).\n        by apply H_all_jobs_from_taskset.\n      Qed.\n      \n    End MainProof.\n\n  End Analysis.\n\nEnd ResponseTimeIterationFP.\n", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/classic/analysis/global/parallel/bertogna_fp_comp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.6873497099461416}}
{"text": "Require\n  MathClasses.theory.naturals.\nRequire Import\n  Coq.setoid_ring.Ring MathClasses.interfaces.abstract_algebra MathClasses.interfaces.naturals MathClasses.interfaces.orders MathClasses.interfaces.additional_operations.\n\n(* * Properties of Nat Pow *)\nSection nat_pow_properties.\nContext `{SemiRing A} `{Naturals B} `{!NatPowSpec A B pw}.\n\nAdd Ring A: (rings.stdlib_semiring_theory A).\nAdd Ring B: (rings.stdlib_semiring_theory B).\n\nGlobal Instance: Proper ((=) ==> (=) ==> (=)) (^) | 0.\nProof nat_pow_proper.\n\nGlobal Instance nat_pow_mor_1: ∀ x : A, Setoid_Morphism (x^) | 0.\nProof. split; try apply _. Qed.\n\nGlobal Instance nat_pow_mor_2: ∀ n : B, Setoid_Morphism (^n) | 0.\nProof. split; try apply _. solve_proper. Qed.\n\nLemma nat_pow_base_0 (n : B) : n ≠ 0 → 0 ^ n = 0.\nProof.\n  pattern n. apply naturals.induction; clear n.\n    solve_proper.\n   intros E. now destruct E.\n  intros. rewrite nat_pow_S. ring.\nQed.\n\nGlobal Instance nat_pow_1: RightIdentity (^) (1:B).\nProof.\n  intro. assert ((1:B) = 1 + 0) as E by ring. rewrite E.\n  rewrite nat_pow_S, nat_pow_0. ring.\nQed.\n\nLemma nat_pow_2 x : x ^ (2:B) = x * x.\nProof. now rewrite nat_pow_S, nat_pow_1. Qed.\n\nLemma nat_pow_3 x : x ^ (3:B) = x * (x * x).\nProof. now rewrite nat_pow_S, nat_pow_2. Qed.\n\nLemma nat_pow_4 x : x ^ (4:B) = x * (x * (x * x)).\nProof. now rewrite nat_pow_S, nat_pow_3. Qed.\n\nGlobal Instance nat_pow_base_1: LeftAbsorb (^) 1.\nProof.\n  intro.\n  pattern y. apply naturals.induction; clear y.\n    solve_proper.\n   apply nat_pow_0.\n  intros n E. rewrite nat_pow_S. rewrite E. ring.\nQed.\n\nLemma nat_pow_exp_plus (x : A) (n m : B) :\n  x ^ (n + m) = x ^ n * x ^ m.\nProof.\n  pattern n. apply naturals.induction; clear n.\n    solve_proper.\n   rewrite nat_pow_0, left_identity. ring.\n  intros n E.\n  rewrite <-associativity.\n  rewrite 2!nat_pow_S.\n  rewrite E. ring.\nQed.\n\nLemma nat_pow_base_mult (x y : A) (n : B) :\n  (x * y) ^ n = x ^ n * y ^ n.\nProof.\n  pattern n. apply naturals.induction; clear n.\n    solve_proper.\n   rewrite ?nat_pow_0. ring.\n  intros n E.\n  rewrite ?nat_pow_S.\n  rewrite E. ring.\nQed.\n\nLemma nat_pow_exp_mult (x : A) (n m : B) :\n  x ^ (n * m) = (x ^ n) ^ m.\nProof.\n  pattern m. apply naturals.induction; clear m.\n    solve_proper.\n   rewrite right_absorb. now rewrite ?nat_pow_0.\n  intros m E.\n  rewrite nat_pow_S, <-E.\n  rewrite distribute_l, right_identity.\n  now rewrite nat_pow_exp_plus.\nQed.\n\nInstance nat_pow_ne_0 `{!NoZeroDivisors A} `{!PropHolds ((1:A) ≠ 0)} (x : A) (n : B) :\n  PropHolds (x ≠ 0) → PropHolds (x ^ n ≠ 0).\nProof.\n  pattern n. apply naturals.induction; clear n.\n    solve_proper.\n    intros. rewrite nat_pow_0. now apply (rings.is_ne_0 1).\n  intros n E F G. rewrite nat_pow_S in G.\n  unfold PropHolds in *.\n  apply (no_zero_divisors x); split; eauto.\nQed.\n\nContext `{Apart A} `{!FullPseudoSemiRingOrder (A:=A) Ale Alt} `{PropHolds (1 ≶ 0)}.\n\nInstance: StrongSetoid A := pseudo_order_setoid.\n\nInstance nat_pow_apart_0 (x : A) (n : B) : PropHolds (x ≶ 0) → PropHolds (x ^ n ≶ 0).\nProof.\n  pattern n. apply naturals.induction; clear n.\n    solve_proper.\n   intros. now rewrite nat_pow_0.\n  intros n E F. rewrite nat_pow_S.\n  rewrite <-(rings.mult_0_r x).\n  apply (strong_left_cancellation (.*.) x). now apply E.\nQed.\n\nInstance nat_pow_nonneg (x : A) (n : B) : PropHolds (0 ≤ x) → PropHolds (0 ≤ x ^ n).\nProof.\n  intros. pattern n. apply naturals.induction; clear n.\n    solve_proper.\n   rewrite nat_pow_0. apply _.\n  intros. rewrite nat_pow_S. apply _.\nQed.\n\nInstance nat_pow_pos (x : A) (n : B) : PropHolds (0 < x) → PropHolds (0 < x ^ n).\nProof.\n  rewrite !lt_iff_le_apart.\n  intros [? ?]. split.\n   now apply nat_pow_nonneg.\n  symmetry. apply nat_pow_apart_0.\n  red. now symmetry.\nQed.\n\nLemma nat_pow_ge_1 (x : A) (n : B) : 1 ≤ x → 1 ≤ x ^ n.\nProof.\n  intros. pattern n. apply naturals.induction.\n    solve_proper.\n   now rewrite nat_pow_0.\n  intros. rewrite nat_pow_S.\n  now apply semirings.ge_1_mult_compat.\nQed.\nEnd nat_pow_properties.\n\n(* Due to bug #2528 *)\n#[global]\nHint Extern 18 (PropHolds (_ ^ _ ≠ 0)) => eapply @nat_pow_ne_0 : typeclass_instances.\n#[global]\nHint Extern 18 (PropHolds (_ ^ _ ≶ 0)) => eapply @nat_pow_apart_0 : typeclass_instances.\n#[global]\nHint Extern 18 (PropHolds (0 ≤ _ ^ _)) => eapply @nat_pow_nonneg : typeclass_instances.\n#[global]\nHint Extern 18 (PropHolds (0 < _ ^ _)) => eapply @nat_pow_pos : typeclass_instances.\n\nSection preservation.\n  Context `{Naturals B} `{SemiRing A1} `{!NatPowSpec A1 B pw1} `{SemiRing A2} `{!NatPowSpec A2 B pw2}\n    {f : A1 → A2} `{!SemiRing_Morphism f}.\n\n  Add Ring B2 : (rings.stdlib_semiring_theory B).\n\n  Lemma preserves_nat_pow x (n : B) : f (x ^ n) = (f x) ^ n.\n  Proof.\n    revert n. apply naturals.induction.\n      solve_proper.\n     rewrite nat_pow_0, nat_pow_0. now apply rings.preserves_1.\n    intros n E.\n    rewrite nat_pow_S, rings.preserves_mult, E.\n    now rewrite nat_pow_S.\n  Qed.\nEnd preservation.\n\nSection exp_preservation.\n  Context `{SemiRing A} `{Naturals B1} `{Naturals B2} `{!NatPowSpec A B1 pw1} `{!NatPowSpec A B2 pw2}\n    {f : B1 → B2} `{!SemiRing_Morphism f}.\n\n  Lemma preserves_nat_pow_exp x (n : B1) : x ^ (f n) = x ^ n.\n  Proof.\n    revert n. apply naturals.induction.\n      solve_proper.\n     rewrite rings.preserves_0.\n     now rewrite 2!nat_pow_0.\n    intros n E.\n    rewrite rings.preserves_plus, rings.preserves_1.\n    rewrite 2!nat_pow_S.\n    now rewrite E.\n  Qed.\nEnd exp_preservation.\n\n(* Very slow default implementation by translation into Peano *)\nSection nat_pow_default.\n  Context `{SemiRing A}.\n\n  Global Instance nat_pow_peano: Pow A nat :=\n    fix nat_pow_rec (x: A) (n : nat) : A := match n with\n    | 0 => 1\n    | S n => x * @pow _ _ nat_pow_rec x n\n    end.\n\n  Instance: Proper ((=) ==> (=) ==> (=)) nat_pow_peano.\n  Proof.\n    intros ? ? E a ? [].\n    induction a; try easy.\n    simpl. now rewrite IHa, E.\n  Qed.\n\n  Global Instance: NatPowSpec A nat nat_pow_peano.\n  Proof. split; try apply _; easy. Qed.\n\n  Context `{Naturals B}.\n\n  Global Instance default_nat_pow: Pow A B | 10 := λ x n, x ^ naturals_to_semiring B nat n.\n  Global Instance: NatPowSpec A B default_nat_pow.\n  Proof.\n    split; unfold pow, default_nat_pow.\n      solve_proper.\n     intros x. now rewrite rings.preserves_0.\n    intros x n. now rewrite rings.preserves_plus, rings.preserves_1.\n  Qed.\nEnd nat_pow_default.\n\nSet Warnings \"-unsupported-attributes\". (* FIXME: remove when minimal Coq version is enough *)\n\n#[global]\nTypeclasses Opaque default_nat_pow.\n", "meta": {"author": "coq-community", "repo": "math-classes", "sha": "c11eb05a1e58a7293ef9a9a046ca02a9fd5b44bc", "save_path": "github-repos/coq/coq-community-math-classes", "path": "github-repos/coq/coq-community-math-classes/math-classes-c11eb05a1e58a7293ef9a9a046ca02a9fd5b44bc/theory/nat_pow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.6872599939124624}}
{"text": "Require Export GeoCoq.Tarski_dev.Ch06_out_lines.\n\nSection Sums.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\n(** Existence of the sum *)\n\nLemma ex_sums : forall A B C D, exists E F, SumS A B C D E F.\nProof.\n  intros A B C D.\n  destruct (segment_construction A B C D) as [R [HR1 HR2]].\n  exists A, R, A, B, R.\n  repeat split; Cong.\nQed.\n\n(** Commutativity of the sum. *)\n\nLemma sums_sym : forall A B C D E F, SumS A B C D E F -> SumS C D A B E F.\nProof.\n  intros A B C D E F HSumS.\n  destruct HSumS as [P [Q [R [HBet [HCong1 [HCong2 HCong3]]]]]].\n  exists R, Q, P.\n  repeat split; Between; Cong.\nQed.\n\n(** Unicity of the sum. *)\n\nLemma sums2__cong56 : forall A B C D E F E' F', SumS A B C D E F -> SumS A B C D E' F' ->\n  Cong E F E' F'.\nProof.\n  intros A B C D E F E' F' HSumS HSumS'.\n  destruct HSumS as [P [Q [R [HBet [HCong1 [HCong2 HCong3]]]]]].\n  destruct HSumS' as [P' [Q' [R' [HBet' [HCong1' [HCong2' HCong3']]]]]].\n  apply cong_transitivity with P R; Cong.\n  apply cong_transitivity with P' R'; trivial.\n  apply l2_11 with Q Q'; trivial.\n  apply cong_transitivity with A B; Cong.\n  apply cong_transitivity with C D; Cong.\nQed.\n\n(** Unicity of the difference of segments. *)\n\nLemma sums2__cong12 : forall A B C D E F A' B', SumS A B C D E F -> SumS A' B' C D E F ->\n  Cong A B A' B'.\nProof.\n  intros A B C D E F A' B' HSumS HSumS'.\n  destruct HSumS as [P [Q [R [HBet [HCong1 [HCong2 HCong3]]]]]].\n  destruct HSumS' as [P' [Q' [R' [HBet' [HCong1' [HCong2' HCong3']]]]]].\n  apply cong_transitivity with P Q; Cong.\n  apply cong_transitivity with P' Q'; trivial.\n  apply l4_3 with R R'; trivial.\n  apply cong_transitivity with E F; Cong.\n  apply cong_transitivity with C D; Cong.\nQed.\n\n(** Unicity of the difference of segments on the right. *)\n\nLemma sums2__cong34 : forall A B C D E F C' D', SumS A B C D E F -> SumS A B C' D' E F ->\n  Cong C D C' D'.\nProof.\n  intros A B C D E F C' D' HSumS HSumS'.\n  apply sums2__cong12 with A B E F; apply sums_sym; trivial.\nQed.\n\n(** Cong preserves SumS *)\n\nLemma cong3_sums__sums : forall A B C D E F A' B' C' D' E' F',\n  Cong A B A' B' -> Cong C D C' D' -> Cong E F E' F' -> SumS A B C D E F ->\n  SumS A' B' C' D' E' F'.\nProof.\n  intros A B C D E F A' B' C' D' E' F' HCong1 HCong2 HCong3 HSumS.\n  destruct HSumS as [P [Q [R [HBet [HCong4 [HCong5 HCong6]]]]]].\n  exists P, Q, R; repeat split; trivial; eapply cong_transitivity; eauto.\nQed.\n\n(** The degenerate segments represent the additive identity *)\n\nLemma sums123312 : forall A B C, SumS A B C C A B.\nProof.\n  intros A B C.\n  exists A, B, B.\n  repeat split; Between; Cong.\nQed.\n\nLemma sums__cong1245 : forall A B C D E, SumS A B C C D E -> Cong A B D E.\nProof.\n  intros A B C D E HSum.\n  apply (sums2__cong56 A B C C); trivial.\n  apply sums123312.\nQed.\n\nLemma sums__eq34 : forall A B C D, SumS A B C D A B -> C = D.\nProof.\n  intros A B C D HSum.\n  apply cong_identity with C.\n  apply sums2__cong34 with A B A B; trivial.\n  apply sums123312.\nQed.\n\nLemma sums112323 : forall A B C, SumS A A B C B C.\nProof.\n  intros; apply sums_sym, sums123312.\nQed.\n\nLemma sums__cong2345 : forall A B C D E, SumS A A B C D E -> Cong B C D E.\nProof.\n  intros A B C D E HSum.\n  apply (sums2__cong56 A A B C); trivial.\n  apply sums112323.\nQed.\n\nLemma sums__eq12 : forall A B C D, SumS A B C D C D -> A = B.\nProof.\n  intros A B C D HSum.\n  apply cong_identity with A.\n  apply sums2__cong12 with C D C D; trivial.\n  apply sums112323.\nQed.\n\n(** Some permutation properties *)\n\nLemma sums_left_comm : forall A B C D E F, SumS A B C D E F -> SumS B A C D E F.\nProof.\n  intros A B C D E F HSumS.\n  apply (cong3_sums__sums A B C D E F); Cong.\nQed.\n\nLemma sums_middle_comm : forall A B C D E F, SumS A B C D E F -> SumS A B D C E F.\nProof.\n  intros; apply sums_sym, sums_left_comm, sums_sym; trivial.\nQed.\n\nLemma sums_right_comm : forall A B C D E F, SumS A B C D E F -> SumS A B C D F E.\nProof.\n  intros A B C D E F HSumS.\n  apply (cong3_sums__sums A B C D E F); Cong.\nQed.\n\nLemma sums_comm : forall A B C D E F, SumS A B C D E F -> SumS B A D C F E.\nProof.\n  intros; apply sums_left_comm, sums_middle_comm, sums_right_comm; trivial.\nQed.\n\n(** Basic case of sum *)\n\nLemma bet__sums : forall A B C, Bet A B C -> SumS A B B C A C.\nProof.\n  intros A B C HBet.\n  exists A, B, C; repeat split; Cong.\nQed.\n\n\nLemma sums_assoc_1 : forall A B C D E F G H I J K L,\n  SumS A B C D G H -> SumS C D E F I J -> SumS G H E F K L ->\n  SumS A B I J K L.\nProof.\n  intros A B C D E F G H I J K L HSumS1 HSumS2 HSumS3.\n  destruct HSumS1 as [P [Q [R [HBet [HCong1 [HCong2 HCong3]]]]]].\n  destruct (segment_construction P R E F) as [S [HS1 HS2]].\n  exists P, Q, S; repeat split; trivial.\n  - apply between_exchange4 with R; trivial.\n  - apply (sums2__cong56 C D E F); trivial.\n    exists Q, R, S; repeat split; Cong.\n    apply between_exchange3 with P; trivial.\n  - apply (sums2__cong56 G H E F); trivial.\n    exists P, R, S; repeat split; Cong.\nQed.\n\nLemma sums_assoc_2 : forall A B C D E F G H I J K L,\n  SumS A B C D G H -> SumS C D E F I J -> SumS A B I J K L ->\n  SumS G H E F K L.\nProof.\n  intros A B C D E F G H I J K L HSumS1 HSumS2 HSumS3.\n  apply sums_sym, sums_assoc_1 with C D A B I J; apply sums_sym; trivial.\nQed.\n\n(** Associativity of the sum. *)\n\nLemma sums_assoc : forall A B C D E F G H I J K L,\n  SumS A B C D G H -> SumS C D E F I J ->\n  (SumS G H E F K L <-> SumS A B I J K L).\nProof.\n  intros A B C D E F G H I J K L HSumS1 HSumS2.\n  split; intro HSumS3.\n  - apply sums_assoc_1 with C D E F G H; trivial.\n  - apply sums_assoc_2 with A B C D I J; trivial.\nQed.\n\n(** AB <= AB + CD *)\n\nLemma sums__le1256 : forall A B C D E F, SumS A B C D E F -> Le A B E F.\nProof.\n  intros A B C D E F HSumS.\n  destruct HSumS as [P [Q [R [HBet [HCong1 [HCong2 HCong3]]]]]].\n  apply (l5_6 P Q P R); trivial.\n  exists Q; Cong.\nQed.\n\n(** CD <= AB + CD *)\n\nLemma sums__le3456 : forall A B C D E F, SumS A B C D E F -> Le C D E F.\nProof.\n  intros A B C D E F HSumS.\n  apply sums__le1256 with A B, sums_sym; trivial.\nQed.\n\n(** If the sum of two segments is degenerate, then the segments are degenerate *)\n\nLemma eq_sums__eq : forall A B C D E, SumS A B C D E E -> A = B /\\ C = D.\nProof.\n  intros A B C D E HSumS.\n  split; apply le_zero with E; [apply sums__le1256 with C D|apply (sums__le3456 A B)]; assumption.\nQed.\n\nLemma sums_diff_1 : forall A B C D E F, A <> B -> SumS A B C D E F -> E <> F.\nProof.\n  intros A B C D E F Hdiff HSumS Heq.\n  subst F.\n  apply Hdiff.\n  destruct (eq_sums__eq A B C D E HSumS); assumption.\nQed.\n\nLemma sums_diff_2 : forall A B C D E F, C <> D -> SumS A B C D E F -> E <> F.\nProof.\n  intros A B C D E F Hdiff HSumS Heq.\n  subst F.\n  apply Hdiff.\n  destruct (eq_sums__eq A B C D E HSumS); assumption.\nQed.\n\n(** SumS preserves Le *)\n\nLemma le2_sums2__le : forall A B C D E F A' B' C' D' E' F',\n  Le A B A' B' -> Le C D C' D' -> SumS A B C D E F -> SumS A' B' C' D' E' F' ->\n  Le E F E' F'.\nProof.\n  intros A B C D E F A' B' C' D' E' F' HLe1 HLe2 HSumS HSumS'.\n  destruct HSumS as [P [Q [R [HBet [HCong1 [HCong2 HCong3]]]]]].\n  destruct HSumS' as [P' [Q' [R' [HBet' [HCong1' [HCong2' HCong3']]]]]].\n  apply (l5_6 P R P' R'); trivial.\n  apply bet2_le2__le1346 with Q Q'; trivial.\n  apply (l5_6 A B A' B'); Cong.\n  apply (l5_6 C D C' D'); Cong.\nQed.\n\n(** If AB <= A'B', CD <= C'D' and AB + CD = A'B' + C'D', then AB = A'B' and CD = C'D' *)\n\nLemma le2_sums2__cong12 : forall A B C D E F A' B' C' D',\n  Le A B A' B' -> Le C D C' D' -> SumS A B C D E F -> SumS A' B' C' D' E F ->\n  Cong A B A' B'.\nProof.\n  intros A B C D E F A' B' C' D' HLe1 HLe2 HSum HSum'.\n  apply sums2__cong12 with C D E F; trivial.\n  destruct (ex_sums A' B' C D) as [E' [F' HSum1]].\n  apply (cong3_sums__sums A' B' C D E' F'); Cong.\n  apply le_anti_symmetry.\n    apply le2_sums2__le with A' B' C D A' B' C' D'; Le.\n    apply le2_sums2__le with A B C D A' B' C D; Le.\nQed.\n\nLemma le2_sums2__cong34 : forall A B C D E F A' B' C' D',\n  Le A B A' B' -> Le C D C' D' -> SumS A B C D E F -> SumS A' B' C' D' E F ->\n  Cong C D C' D'.\nProof.\n  intros A B C D E F A' B' C' D' HLe1 HLe2 HSum HSum'.\n  apply le2_sums2__cong12 with A B E F A' B'; try (apply sums_sym); trivial.\nQed.\n\n(** If AB < A'B' and CD <= C'D', then AB + CD < A'B' + C'D' *)\n\nLemma le_lt12_sums2__lt : forall A B C D E F A' B' C' D' E' F',\n  Lt A B A' B' -> Le C D C' D' -> SumS A B C D E F -> SumS A' B' C' D' E' F' ->\n  Lt E F E' F'.\nProof.\n  intros A B C D E F A' B' C' D' E' F' HLt HLe HSum HSum'.\n  split.\n    apply le2_sums2__le with A B C D A' B' C' D'; Le.\n  intro HCong.\n  destruct HLt as [HLe1 HNCong].\n  apply HNCong.\n  apply le2_sums2__cong12 with C D E F C' D'; trivial.\n  apply (cong3_sums__sums A' B' C' D' E' F'); Cong.\nQed.\n\nLemma le_lt34_sums2__lt : forall A B C D E F A' B' C' D' E' F',\n  Le A B A' B' -> Lt C D C' D' -> SumS A B C D E F -> SumS A' B' C' D' E' F' ->\n  Lt E F E' F'.\nProof.\n  intros A B C D E F A' B' C' D' E' F' HLe HLt HSum HSum'.\n  apply le_lt12_sums2__lt with C D A B C' D' A' B'; try (apply sums_sym); trivial.\nQed.\n\nLemma lt2_sums2__lt : forall A B C D E F A' B' C' D' E' F',\n  Lt A B A' B' -> Lt C D C' D' -> SumS A B C D E F -> SumS A' B' C' D' E' F' ->\n  Lt E F E' F'.\nProof.\n  intros A B C D E F A' B' C' D' E' F' HLt1 HLt2 HSum HSum'.\n  apply le_lt12_sums2__lt with A B C D A' B' C' D'; Le.\nQed.\n\n(** If CD >= C'D' and AB + CD <= A'B' + C'D', then AB <= A'B' *)\n\nLemma le2_sums2__le12 : forall A B C D E F A' B' C' D' E' F',\n  Le C' D' C D -> Le E F E' F' -> SumS A B C D E F -> SumS A' B' C' D' E' F' ->\n  Le A B A' B'.\nProof.\n  intros A B C D E F A' B' C' D' E' F' HLe1 HLe2 HSum HSum'.\n  apply nlt__le; intro HLt.\n  apply le__nlt in HLe2; apply HLe2.\n  apply le_lt12_sums2__lt with A' B' C' D' A B C D; trivial.\nQed.\n\nLemma le2_sums2__le34 : forall A B C D E F A' B' C' D' E' F',\n  Le A' B' A B -> Le E F E' F' -> SumS A B C D E F -> SumS A' B' C' D' E' F' ->\n  Le C D C' D'.\nProof.\n  intros A B C D E F A' B' C' D' E' F' HLe1 HLe2 HSum HSum'.\n  apply le2_sums2__le12 with A B E F A' B' E' F'; try (apply sums_sym); trivial.\nQed.\n\n(** If CD > C'D' and AB + CD <= A'B' + C'D', then AB < A'B' *)\n\nLemma le_lt34_sums2__lt12 : forall A B C D E F A' B' C' D' E' F',\n  Lt C' D' C D -> Le E F E' F' -> SumS A B C D E F -> SumS A' B' C' D' E' F' ->\n  Lt A B A' B'.\nProof.\n  intros A B C D E F A' B' C' D' E' F' HLt HLe HSum HSum'.\n  apply nle__lt; intro HLe1.\n  apply le__nlt in HLe; apply HLe.\n  apply le_lt34_sums2__lt with A' B' C' D' A B C D; trivial.\nQed.\n\nLemma le_lt12_sums2__lt34 : forall A B C D E F A' B' C' D' E' F',\n  Lt A' B' A B -> Le E F E' F' -> SumS A B C D E F -> SumS A' B' C' D' E' F' ->\n  Lt C D C' D'.\nProof.\n  intros A B C D E F A' B' C' D' E' F' HLe1 HLe2 HSum HSum'.\n  apply le_lt34_sums2__lt12 with A B E F A' B' E' F'; try (apply sums_sym); trivial.\nQed.\n\n(** If CD >= C'D' and AB + CD < A'B' + C'D', then AB < A'B' *)\n\nLemma le_lt56_sums2__lt12 : forall A B C D E F A' B' C' D' E' F',\n  Le C' D' C D -> Lt E F E' F' -> SumS A B C D E F -> SumS A' B' C' D' E' F' ->\n  Lt A B A' B'.\nProof.\n  intros A B C D E F A' B' C' D' E' F' HLe HLt HSum HSum'.\n  apply nle__lt; intro HLe1.\n  apply lt__nle in HLt; apply HLt.\n  apply le2_sums2__le with A' B' C' D' A B C D; trivial.\nQed.\n\nLemma le_lt56_sums2__lt34 : forall A B C D E F A' B' C' D' E' F',\n  Le A' B' A B -> Lt E F E' F' -> SumS A B C D E F -> SumS A' B' C' D' E' F' ->\n  Lt C D C' D'.\nProof.\n  intros A B C D E F A' B' C' D' E' F' HLe HLt HSum HSum'.\n  apply le_lt56_sums2__lt12 with A B E F A' B' E' F'; try (apply sums_sym); trivial.\nQed.\n\nLemma lt2_sums2__lt12 : forall A B C D E F A' B' C' D' E' F',\n  Lt C' D' C D -> Lt E F E' F' -> SumS A B C D E F -> SumS A' B' C' D' E' F' ->\n  Lt A B A' B'.\nProof.\n  intros A B C D E F A' B' C' D' E' F' HLt1 HLt2 HSum HSum'.\n  apply le_lt56_sums2__lt12 with C D E F C' D' E' F'; Le.\nQed.\n\nLemma lt2_sums2__lt34 : forall A B C D E F A' B' C' D' E' F',\n  Lt A' B' A B -> Lt E F E' F' -> SumS A B C D E F -> SumS A' B' C' D' E' F' ->\n  Lt C D C' D'.\nProof.\n  intros A B C D E F A' B' C' D' E' F' HLe HLt HSum HSum'.\n  apply le_lt56_sums2__lt34 with A B E F A' B' E' F'; Le.\nQed.\n\nEnd Sums.\n\n#[global]\nHint Resolve sums_sym sums_left_comm sums_middle_comm sums_right_comm\n             sums_comm sums112323 sums123312 bet__sums : sums.\n\nLtac Sums := auto 4 with sums.\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Tarski_dev/Annexes/sums.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357569, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.6872599783428839}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (x : natural) : natural := mult z 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/goal33conj2810_coqofml_IOLKaQ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544446, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6871678210084791}}
{"text": "Require Import SyDPaCC.Core.Bmf.\nRequire Import Program Lia Bool NArith (*Classical_Pred_Type*).\n\nSet Implicit Arguments.\n\nOpen Scope sydpacc_scope.\nOpen Scope N.\n\n(* * Binary Trees: Type and Properties *)\n\n(* ** Binary Trees: Definition *)\n\nInductive t (A B: Type) :=\n| Leaf : A -> t A B\n| Node : B -> t A B -> t A B -> t A B.\n\nArguments Leaf [A B].\n\n(* ** Binary Trees: Same Form Property *)\n\nInductive same_form {A B C D:Type} : t A B -> t C D ->  Prop :=\n| sfi_leaf :\n    forall a1 a2,\n      same_form (Leaf a1) (Leaf a2)\n| sfi_node :\n    forall a1 a2 l1 r1 l2 r2,\n      same_form l1 l2\n      -> same_form r1 r2\n      -> same_form (Node a1 l1 r1) (Node a2 l2 r2).\n\n\nLemma same_form_trans :\n  forall A B C D E F (t1:t A B) (t2:t C D) (t3:t E F),\n    same_form t1 t2 -> same_form t2 t3 -> same_form t1 t3.\nProof.\n  intros A B C D E F tree1;\n    induction tree1; intros tree2 tree3;\n    destruct tree2, tree3; intros H1 H2;\n    try solve [ constructor ];\n    try solve [ inversion H1 ] ;\n    try solve [ inversion H2 ].\n  inversion H1; inversion H2; subst; constructor;\n    eauto using IHtree1_1, IHtree1_2.\nQed.\n\nArguments same_form_trans [A B C D E F].\n\nClass Same_Form {A B C D} (t1: t A B) (t2: t C D) :=\n  MkSF\n    {\n      c_same_form : same_form t1 t2\n    }.\n\n\nClass Same_Form_RT {A B C D} (t1: t A B) (t2:t C D) {H: Same_Form t1 t2}.\n\nGeneralizable All Variables.\n\n#[export] Instance Same_Form_Trans {A B C D E F} (t1:t A B) (t2:t C D) (t3:t E F)\n         {H1:Same_Form t1 t2} `{H2: @Same_Form_RT _ _ _ _ t2 t3 H}:\n  @Same_Form_RT _ _ _ _ t1 t3\n                (MkSF (same_form_trans t1 t2 t3\n                                       (c_same_form (Same_Form := H1))\n                                       (@c_same_form _ _ _ _ _ _ H))).\nDefined.\n\n#[export] Instance sameform_node_left {A B C D:Type} (a1:B) (l1 r1:t A B) (a2:D) (l2 r2:t C D) t1 t2:\n  t1 = Node a1 l1 r1 ->\n  t2 = Node a2 l2 r2 ->\n  Same_Form t1 t2 -> Same_Form l1 l2.\nProof.\n  intros H1 H2 Hsf; subst. inversion Hsf; inversion c_same_form0.\n  constructor; assumption.\nQed.\n\n#[export] Instance sameform_node_right {A B C D:Type} (a1:B) (l1 r1:t A B) (a2:D) (l2 r2:t C D) t1 t2:\n  t1 = Node a1 l1 r1 ->\n  t2 = Node a2 l2 r2 ->\n  Same_Form t1 t2 -> Same_Form r1 r2.\nProof.\n  intros H1 H2 Hsf; subst. inversion Hsf; inversion c_same_form0.\n  constructor; assumption.\nQed.\n\n#[export] Instance sameform_node_left'\n         {A B C D:Type} (a1:B) (l1 r1:t A B) (a2:D) (l2 r2:t C D)\n         {H: Same_Form (Node a1 l1 r1) (Node a2 l2 r2)}\n  : Same_Form l1 l2.\nProof.\n  eapply sameform_node_left; eauto.\nQed.\n\n#[export] Instance sameform_node_right'\n         {A B C D:Type} (a1:B) (l1 r1:t A B) (a2:D) (l2 r2:t C D)\n         { H:Same_Form (Node a1 l1 r1) (Node a2 l2 r2)}\n  : Same_Form r1 r2.\nProof.\n  eapply sameform_node_right; eauto.\nQed.\n\nLemma not_same_form_tn:\n  forall (A B C D: Type) (a:A) (d:D) (r l:t C D) (t1:t A B) (t2:t C D),\n    t1 = Leaf a ->\n    t2 = Node d r l ->\n    not(Same_Form t1 t2).\nProof.\n  intros; subst; intro HH; inversion HH as [ H' ]; inversion H'.\nQed.\n\nLemma not_same_form_nt:\n  forall (A B C D: Type) (a:A) (d:D) (r l:t C D) t1 (t2:t A B),\n    t2 = Leaf a ->\n    t1 = Node d r l ->\n    not(Same_Form t1 t2).\nProof.\n  intros; subst; intro HH; inversion HH as [ H' ]; inversion H'.\nQed.\n\n(** * Functions on Binary Trees *)\n\n(** ** Specifications *)\n\nModule Spec.\n  \n  Fixpoint size `(tree: t A B) : N :=\n    match tree with\n    | Leaf _ => 1\n    | Node _ l r => 1 + (size l) + (size r)\n    end.\n  \n  Fixpoint map (A B C D :Type) (kL:A -> C)(kN:B -> D)(tree: t A B): t C D :=\n    match tree with\n    | Leaf n => Leaf (kL n)\n    | Node n l r => Node (kN n) (map kL kN l) (map kL kN r)\n    end.\n  \n  Fixpoint mapt (A B C D:Type) (kL: A -> C)\n           (kN: B -> t A B -> t A B -> D) (tree:t A B) : t C D :=\n    match tree with\n    | Leaf n =>  Leaf (kL n)\n    | Node n l r => Node (kN n l r) (mapt kL kN l) (mapt kL kN r)\n    end.\n\n  (* TODO: change the type of k to A -> B -> A -> A *)\n  Fixpoint reduce (A B:Type) (k: A * B * A -> A)(tree: t A B): A :=\n    match tree with\n    | Leaf n => n\n    | Node n l r => k (reduce k l, n, reduce k r)\n    end.\n\n    (* TODO: change the type of k to A -> B -> A -> A *)\n  Fixpoint uAcc (A B : Type) (k: A * B * A -> A)(tree: t A B): t A A :=\n    match tree with\n    | Leaf n => Leaf n\n    | Node n l r => let n' := reduce k tree in\n                   Node n' (uAcc k l) (uAcc k r)\n    end.\n\n    (* TODO: change the type of gl, gr to C -> B -> C *)\n  Fixpoint dAcc (A B C:Type) (gl gr:C * B -> C) (c:C) (tree: t A B): t C C :=\n    match tree with\n    | Leaf n => Leaf c\n    | Node n l r =>\n      let l' := dAcc gl gr (gl (c,n)) l in\n      let r' := dAcc gl gr (gr (c,n)) r in\n      Node c l' r'\n    end.\n  \n  Program Fixpoint zip (A B C D:Type) (tree1 : t A B) (tree2 : t C D) (H: Same_Form tree1 tree2)\n    : t (A*C) (B*D) :=\n    match (tree1,tree2) with\n    | (Leaf a, Leaf c) => Leaf (a,c)\n    | (Node b l1 r1, Node d l2 r2) =>\n      let l := (zip (@sameform_node_left _ _ _ _ b l1 r1 d l2 r2 _ _ _ _  H)) in\n      let r := (zip (@sameform_node_right _ _ _ _ b l1 r1 d l2 r2 _ _ _ _ H)) in\n      Node (b,d) l r\n    | _ => _\n    end.\n  Next Obligation.\n    inversion H.\n    destruct tree1, tree2.\n    + contradiction H1 with (a0:=a) (c0:=c). reflexivity.\n    + contradict H; intro H; inversion H; inversion c_same_form0.\n    + contradict H; intro H; inversion H; inversion c_same_form0.\n    + contradiction H0 with (b0:=b) (l1:=tree1_1) (r1:=tree1_2)\n                            (d0:=d) (l2:=tree2_1) (r2:=tree2_2); reflexivity.\n  Defined.\n  Next Obligation.\n    split; intros; discriminate.\n  Defined.\n  Next Obligation.\n    inversion H; split; intros; discriminate.\n  Defined.\n\n  Arguments zip [A B C D] tree1 tree2 {H}.\n  \nEnd Spec.\n\n(** ** Tail-Recursive Definitions *)\n\nDefinition root {A:Type} (tree : t A A) : A :=\n  match tree with\n  | Leaf a => a\n  | Node b _ _ => b\n  end.\n\n(* ====================================== *)\n(* TODO: externalize all the internal fix *)\n(* ====================================== *)\n\nFixpoint size_aux (A B: Type) (tree:t A B)(k: N -> N) :=\n  match tree with\n  | Leaf _ => k 1\n  | Node _ l r =>\n    size_aux l (fun lm => size_aux r (fun rm =>k (1 + lm + rm)))\n  end.\n      \nDefinition size (A B:Type) (tree: t A B) : N :=\n  size_aux tree (fun x => x).\n\nFixpoint map_aux (A B C D:Type) (kL : A -> C) (kN : B -> D) (tree: t A B) (k: t C D -> t C D) : t C D :=\n  match tree with\n  | Leaf a => k (Leaf (kL a))\n  | Node b l r => \n    map_aux kL kN l (fun lm => map_aux kL kN r (fun rm => k(Node (kN b) lm rm)))\n  end.\n  \nDefinition map (A B C D:Type) (kL : A -> C) (kN : B -> D) (tree: t A B) : t C D :=\n  map_aux kL kN tree (fun x => x).\n\nFixpoint mapt_aux (A B C D:Type) (kL: A -> C) (kN: B -> t A B -> t A B -> D) (tree:t A B) (k: t C D -> t C D) :=\n  match tree with\n  | Leaf a => k (Leaf (kL a))\n  | Node b l r =>\n    mapt_aux kL kN l (fun lm => mapt_aux kL kN r (fun rm => k(Node (kN b l r) lm rm)))\n  end.\n\nDefinition mapt (A B C D:Type) (kL: A -> C) (kN: B -> t A B -> t A B -> D) (tree:t A B) : t C D :=\n  mapt_aux kL kN tree (fun x => x).\n\nFixpoint reduce_aux (A B: Type)(kr: A * B * A -> A)(tree: t A B) (k:A->A) : A :=\n  match tree with\n  | Leaf a => k a\n  | Node b l r =>\n    reduce_aux kr l (fun lm => reduce_aux kr r (fun rm => k( kr (lm,b,rm))))\n  end.\n\nDefinition reduce (A B: Type)(kr: A * B * A -> A)(tree: t A B): A :=\n  reduce_aux kr tree (fun x => x).\n\nFixpoint uAcc_aux (A B : Type) (ka: A * B * A -> A) (tree:t A B) (k: t A A -> t A A) :=\n  match tree with\n  | Leaf a => k (Leaf a)\n  | Node b l r =>\n    uAcc_aux ka l (fun lm => uAcc_aux ka r (fun rm => k(Node (ka ((root lm),b,(root rm))) lm rm )))\n  end.\n\nDefinition uAcc (A B : Type) (ka: A * B * A -> A)(tree: t A B): t A A :=\n  uAcc_aux ka tree (fun x => x).\n\nFixpoint dAcc_aux (A B C: Type) (gl gr:C * B -> C) (c:C) (tree: t A B) (k: t C C -> t C C) :=\n  match tree with\n  | Leaf n => k (Leaf c)\n  | Node n l r =>\n    dAcc_aux gl gr (gl (c,n)) l (fun lm => dAcc_aux gl gr (gr (c,n)) r (fun rm => k(Node c lm rm)))\n  end.\n\nDefinition dAcc (A B C: Type) (gl gr:C * B -> C) (c:C) (tree: t A B) : t C C :=\n  dAcc_aux gl gr c tree (fun x => x).\n\nFixpoint zip_aux (A B C D:Type) (tree1 : t A B) (tree2 : t C D) {HH: Same_Form tree1 tree2}\n         (k:  t (A*C) (B*D) ->  t (A*C) (B*D)) :=\n  (match (tree1,tree2) as pair return tree1 = (fst pair) -> tree2 = (snd pair) -> t (A*C) (B*D) with\n   | (Leaf a, Leaf c) => fun _ _ => k (Leaf (a,c))\n   | (Node b l1 r1, Node d l2 r2) =>\n     fun H1 H2 =>\n       zip_aux (HH := @sameform_node_left _ _ _ _ b l1 r1 d l2 r2 _ _ H1 H2 HH)\n               (fun lm => zip_aux (HH := @sameform_node_right _ _ _ _ b l1 r1 d l2 r2 _ _ H1 H2 HH)\n                               (fun rm => k(Node (b,d) lm rm)))\n   | (Leaf a, Node d l r) =>\n     fun H1 H2 =>  False_rect _ (not_same_form_tn H1 H2 HH)\n   | (Node d l r, Leaf a) => fun H1 H2 => False_rect _ (not_same_form_nt H2 H1 HH)\n   end) eq_refl eq_refl.\n\nArguments zip_aux [A B C D] tree1 tree2 {HH} k.\n\nDefinition zip (A B C D:Type) (tree1 : t A B) (tree2 : t C D) {H: Same_Form tree1 tree2}\n  : t (A*C) (B*D) :=\n  zip_aux tree1 tree2 (fun x => x) (HH:=H).\n\nArguments zip [A B C D] tree1 tree2 {H}.\n\n(** ** Correctness of Tail-Recursive Definitions  *)\n\nSection EqSpec.\n\n  (* ================================================================ *)\n  (* TODO: Auxiliary lemmas about the auxiliary recursive definitions *)\n  (* ================================================================ *)\n\n  Lemma size_aux_prop:\n    forall `(tree:t A B) f,\n      size_aux tree f = f(Spec.size tree).\n  Proof.\n    intros A B tree. induction tree as [ a | a l IHl r IHr ]; intro f; simpl.\n    - trivial.\n    - rewrite IHl, IHr; trivial.\n  Qed.\n  \n  Lemma size_spec_size :\n    forall `(tree:t A B),\n      size tree = Spec.size tree.\n  Proof.\n    unfold size. intros A B tree.\n    now rewrite size_aux_prop.\n  Qed.\n  \n  Lemma map_aux_prop:\n    forall A B C D (kL:A->C) (kN:B->D) (tree:t A B) (k:t C D->t C D),\n      map_aux kL kN tree k = k(Spec.map kL kN tree).\n  Proof.\n    intros A B C D kL kN tree.\n    induction tree as [ a | a l IHl r IHr ]; intro k; simpl.\n    - trivial.\n    - rewrite IHl, IHr; trivial.\n  Qed.\n  \n  Lemma map_spec_map :\n    forall `(kL : A -> C) `(kN : B -> D) (tree: t A B),\n      map kL kN tree = Spec.map kL kN tree.\n  Proof.\n    unfold map; intros; now rewrite map_aux_prop.\n  Qed.\n\n  Lemma mapt_aux_prop:\n    forall `(kL: A -> C) `(kN: B -> t A B -> t A B -> D) (tree:t A B) k,\n      mapt_aux kL kN tree k = k(Spec.mapt kL kN tree).\n  Proof.\n    intros A C kL B D kN tree; \n      induction tree as [ a | a l IHl r IHr ]; intro k; simpl.\n    - trivial.\n    - rewrite IHl, IHr; trivial.\n  Qed.\n  \n  Lemma mapt_spec_mapt: forall `(kL: A -> C) `(kN: B -> t A B -> t A B -> D) (tree:t A B),\n      mapt kL kN tree = Spec.mapt kL kN tree.\n  Proof.\n    unfold mapt; intros; now rewrite mapt_aux_prop.\n  Qed.\n\n  Lemma reduce_aux_prop:\n    forall `(kr: A * B * A -> A)(tree: t A B) k,\n      reduce_aux kr tree k = k (Spec.reduce kr tree).\n  Proof.\n    intros A B kr tree; \n      induction tree as [ a | a l IHl r IHr ]; intro k; simpl.\n    - trivial.\n    - rewrite IHl, IHr; trivial.\n  Qed.\n  \n  Lemma reduce_spec_reduce: forall (A B: Type)(kr: A * B * A -> A)(tree: t A B),\n      reduce kr tree = Spec.reduce kr tree.\n  Proof.\n    unfold reduce; intros; now rewrite reduce_aux_prop.\n  Qed.\n\n  Lemma uAcc_aux_prop:\n    forall (A B : Type) (ka: A * B * A -> A)(tree: t A B) k,\n      uAcc_aux ka tree k = k(Spec.uAcc ka tree).\n  Proof.\n    intros A B ka tree; \n    induction tree as [ a | a l IHl r IHr ]; intro k; simpl.\n    - trivial.\n    - rewrite IHl, IHr; simpl; repeat f_equal;\n      match goal with\n      | [ |- _ = Spec.reduce _ ?tree] => destruct tree; auto\n      end.\n  Qed.\n  \n  Lemma uAcc_spec_uAcc: forall (A B : Type) (ka: A * B * A -> A)(tree: t A B),\n      uAcc ka tree = Spec.uAcc ka tree.\n  Proof.\n    unfold uAcc; intros; now rewrite uAcc_aux_prop.\n  Qed.\n\n  Lemma dAcc_aux_prop:\n    forall (A B C: Type) (gl gr:C * B -> C) (tree: t A B) c k,\n      dAcc_aux gl gr c tree k = k(Spec.dAcc gl gr c tree).\n  Proof.\n    intros A B C gl gr tree.\n    induction tree as [ a | a l IHl r IHr ]; intros c k; simpl.\n    - trivial.\n    - rewrite IHl, IHr; trivial.\n  Qed.\n  \n  Lemma dAcc_spec_dAcc: forall (A B C: Type) (gl gr:C * B -> C) (c:C) (tree: t A B),\n      dAcc gl gr c tree = Spec.dAcc gl gr c tree.\n  Proof.\n    unfold dAcc; intros; now rewrite dAcc_aux_prop.\n  Qed.\n\n\n  Lemma zip_aux_prop:\n    forall (A B C D:Type) (t1: t A B) (t2: t C D) {H:Same_Form t1 t2} k,\n      zip_aux t1 t2 k (HH:=H) = k(Spec.zip t1 t2 (H:=H)).\n  Proof.\n    intros A B C D t1; induction t1 as [ a1 | a1 l1 IHl1 r1 IHr1]; intros [ a2 | a2 l2 r2 ] H k.\n    - trivial.\n    - contradict H. eapply not_same_form_tn; eauto.\n    - contradict H. eapply not_same_form_nt; eauto.\n    - simpl; now rewrite IHl1, IHr1.\n  Qed.\n\n\n  Lemma zip_spec_zip: forall (A B C D:Type) (t1: t A B) (t2: t C D) {H:Same_Form t1 t2},\n      zip t1 t2 (H:=H) = Spec.zip t1 t2 (H:=H).\n  Proof.\n    unfold zip; intros; now rewrite zip_aux_prop.\n  Qed.\n  \nEnd EqSpec.\n\n(** ** Preservation of the Same Form Property *)\n\n#[export] Instance same_form_map {A B C D} (kL : A -> C) (kN : B -> D) (tree:t A B) :\n  Same_Form tree (map kL kN tree).\nProof.    \n  induction tree as [| x tl Hl tr Hr].\n  + simpl. constructor; apply sfi_leaf.\n  + simpl. constructor.\n    rewrite map_spec_map.\n    rewrite map_spec_map in Hr, Hl.\n    apply sfi_node.\n    ++ inversion Hl; assumption.\n    ++ inversion Hr; assumption. \nQed.\n\n#[export] Instance same_form_mapt {A B C D} (kL : A -> C)  (kN: B -> t A B -> t A B -> D) (tree:t A B) :\n  Same_Form tree (mapt kL kN tree).\nProof.    \n  induction tree as [| x tl Hl tr Hr].\n  + simpl. constructor; apply sfi_leaf.\n  + simpl. constructor.\n    rewrite mapt_spec_mapt. rewrite mapt_spec_mapt in Hl, Hr.\n    apply sfi_node.\n    ++ inversion Hl; assumption.\n    ++ inversion Hr; assumption.\nQed.\n\n#[export] Instance same_form_uAcc {A B} (k: A * B * A -> A)(tree: t A B) :\n  Same_Form tree (uAcc k tree).\nProof.\n  induction tree as [| x tl Hl tr Hr].\n  + simpl. constructor; apply sfi_leaf.\n  + simpl; constructor.\n    rewrite uAcc_spec_uAcc; rewrite uAcc_spec_uAcc in Hr, Hl.\n    apply sfi_node.\n    ++ inversion Hl; assumption.\n    ++ inversion Hr; assumption.\nQed.  \n\n#[export] Instance same_form_dAcc {A B C} (gl gr:C * B -> C) (c:C) (tree: t A B) :\n  Same_Form tree (dAcc gl gr c tree).\nProof.\n  generalize dependent c. induction tree as [| a l IHl r IHr].\n  - simpl. constructor; apply sfi_leaf.\n  - intro c. rewrite dAcc_spec_dAcc. \n    simpl. repeat rewrite <- dAcc_spec_dAcc. \n    constructor; apply sfi_node.\n    + apply IHl.\n    + apply IHr. \nQed.\n\n#[export] Instance same_form_comp {A B C D E F} (tree1: t A B)\n         (f: t A B -> t C D) (g: t C D -> t E F)\n         {Hf_sf: forall x, Same_Form x (f x)} {Hg_sf: forall x, Same_Form x (g x)} :\n  Same_Form tree1 ((g ∘ f) tree1).\nProof.\n  autounfold. constructor.\n  apply same_form_trans with (t2:=f tree1).\n  apply c_same_form. apply Hg_sf.\nQed.\n\nClose Scope N.\nClose Scope sydpacc_scope.\n", "meta": {"author": "SyDPaCC", "repo": "sydpacc", "sha": "640f0f74f21524ee203b192255ecfa9e456fb7d1", "save_path": "github-repos/coq/SyDPaCC-sydpacc", "path": "github-repos/coq/SyDPaCC-sydpacc/sydpacc-640f0f74f21524ee203b192255ecfa9e456fb7d1/Tree/BTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.687167818761793}}
{"text": "(** A _strategy_ is any function $\\gamma$ of type [positive -> positive] \nsuch that, if $n>3$, then $1<\\gamma(n)<n$.\n\n \n*)\n    \n\nRequire Import Arith NArith Pow Compatibility More_on_positive.\nOpen Scope positive_scope.\n\nOpen Scope positive_scope.\n(* begin snippet StrategyDef *)\nClass Strategy (gamma : positive -> positive):=\n  {\n  gamma_lt :forall p:positive, 3 < p -> gamma  p < p;\n  gamma_gt : forall p:positive, 3 < p -> 1 < gamma  p\n  }.\n(* end snippet StrategyDef *)\n\nLtac gamma_bounds gamma i H1 H2 :=\n  assert (H1 : 1 < gamma i) by (apply gamma_gt;auto with chains);\n  assert (H2 : gamma i < i) by (apply gamma_lt; auto with chains).\n\nLemma div_gamma_pos {gamma}{Hgamma : Strategy gamma}\n: forall (p:positive) q r, \n    N.pos_div_eucl p (N.pos (gamma p)) = (q, r) ->\n    3 < p ->\n    (0 < q)%N.\nProof.\n  destruct q; [ | reflexivity].\n  intros r H H0;assert (H1  : p = N2pos r) by \n                   (apply (N_pos_div_eucl_q0 _ _ _ H);auto).\n  destruct (Pos.lt_irrefl p).\n  transitivity (gamma  p).  \n  -   rewrite H1 at 1.\n      generalize  (N.pos_div_eucl_remainder  p\n                                             (N.pos (gamma p)));\n        rewrite H; cbn.  \n      intros H2; destruct r.\n      +  apply gamma_gt; auto. \n      +  rewrite  <- pos2N_inj_lt in H2;  cbn; auto with chains.\n  -  apply gamma_lt;auto with chains. \nQed.\n\n\n\n", "meta": {"author": "coq-community", "repo": "hydra-battles", "sha": "2d211e0b5030d5f77aaaf6366b01fc64ed998c61", "save_path": "github-repos/coq/coq-community-hydra-battles", "path": "github-repos/coq/coq-community-hydra-battles/hydra-battles-2d211e0b5030d5f77aaaf6366b01fc64ed998c61/theories/additions/Strategies.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6871678071701833}}
{"text": "(* Definition of high-level semantics *)\n\nRequire Import Program Arith.\n\n(* Model *)\n\nRecord HLocalState := HHonest {hhl_input : bool; hhl_decision : option bool}.\n\nRecord HGlobalState := HGS {hg_n : nat; h_localstates : nat -> option HLocalState}.\n\n(* Semantics *)\n\nDefinition Hstep_decide_loc (ls : HLocalState) (b : bool) : HLocalState :=\n  HHonest (hhl_input ls) (Some b).\n\nDefinition Hstep_decide (gs : HGlobalState) (i : nat) (b : bool) : HGlobalState :=\n  let n := hg_n gs in\n  let ls := h_localstates gs in\n  HGS n \n    (fun j => \n    if j =? i then \n      match ls i with\n      | Some ls => Some (Hstep_decide_loc ls b)\n      | None => None\n      end\n    else\n      ls j).\n\nDefinition Hextract_loc (ls : option HLocalState) : option bool :=\n  match ls with\n  | Some (HHonest _ d) => d\n  | _ => None\n  end.\n\nDefinition mergeb (l : option bool) (r : option bool) : option bool :=\n  match l with\n  | Some b => Some b\n  | None => r\n  end.\n\nDefinition Hextract (gs : HGlobalState) (i : nat) : option bool :=\n  match gs with\n  | HGS n ls => if i <? n then Hextract_loc (ls i) else None\n  end.\n\n(* TODO Hide behind a monad, so it can be written as a fun *)\nInductive HStep : HGlobalState -> HGlobalState -> Prop :=\n  | NOTHING : forall gs, HStep gs gs\n  | DECIDE : forall gs i b gs', ((forall j, Hextract gs j = None) /\\ (gs' = Hstep_decide gs i b)) -> HStep gs gs'\n  | AGREE : forall gs i b gs', ((exists j, Hextract gs j = Some b) /\\ (gs' = Hstep_decide gs i b)) -> HStep gs gs'.\n\nInductive HSteps : HGlobalState -> HGlobalState -> Prop :=\n  | HONE : forall gs gs', HStep gs gs' -> HSteps gs gs'\n  | HMANY : forall gs gs' gs'', HSteps gs gs' -> HStep gs' gs'' -> HSteps gs gs''.\n", "meta": {"author": "FTRobbin", "repo": "Ironwood", "sha": "615b886297446571f7cd65c1b7475e7f4717cf6a", "save_path": "github-repos/coq/FTRobbin-Ironwood", "path": "github-repos/coq/FTRobbin-Ironwood/Ironwood-615b886297446571f7cd65c1b7475e7f4717cf6a/High_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6871678006092142}}
{"text": "Require Import PeanoNat.\nRequire Import Reals.\n\nRequire Import Coquelicot.Continuity.\nRequire Import Coquelicot.Hierarchy.\nRequire Import Coquelicot.Rcomplements.\n\nRequire Import Lia.\nRequire Import Lra.\n\nSection Lim_seq_US_def.\nContext {U : UniformSpace}.\n  \n(** * Limit of sequences *)\n(** ** Definition *)\nDefinition is_lim_seq (u : nat -> U) (l : U) :=\n  filterlim u eventually (locally l).\n\nDefinition ex_lim_seq (u : nat -> U) :=\n  exists l, is_lim_seq u l.\n\nDefinition ex_lim_seq_inf (u : nat -> U) :=\n  {l & is_lim_seq u l}.\n\n(** Extensionality *)\n\nLemma is_lim_seq_ext_loc (u v : nat -> U) (l : U) :\n  eventually (fun n => u n = v n) ->\n  is_lim_seq u l -> is_lim_seq v l.\nProof.\n  intros H1 H2.\n  intros P Hl.\n  specialize (H2 P Hl).\n  unfold filtermap.\n  destruct H1 as [N1 H1].\n  destruct H2 as [N2 H2].\n  split with (Nat.max N1 N2).\n  intros n H.\n  rewrite <- H1; try lia.\n  apply H2; lia.\nQed.  \n  \nLemma ex_lim_seq_ext_loc (u v : nat -> U) :\n  eventually (fun n => u n = v n) ->\n  ex_lim_seq u -> ex_lim_seq v.\nProof.\n  intros H1 [l H2].\n  split with l.\n  apply is_lim_seq_ext_loc with u; assumption.\nQed.\n  \nLemma is_lim_seq_ext (u v : nat -> U) (l : U) :\n  (forall n, u n = v n) -> is_lim_seq u l -> is_lim_seq v l.\nProof.\n  intros H1 H2.\n  intros P Hl.\n  specialize (H2 P Hl).\n  destruct H2 as [N H2].\n  split with N.\n  intros n H.\n  rewrite <- H1.\n  apply H2; assumption.\nQed.\n  \nLemma ex_lim_seq_ext (u v : nat -> U) :\n  (forall n, u n = v n) -> ex_lim_seq u -> ex_lim_seq v.\nProof.\n  intros H1 [l H2].\n  split with l; apply is_lim_seq_ext with u; assumption.\nQed.\n\n(** ** Arithmetic operations and order *)\n\n(** Constants *)\nLemma is_lim_seq_const (a : U) :\n  is_lim_seq (fun n => a) a.\nProof.\n  intros P Hl.\n  destruct Hl as [e Hl].\n  split with 0%nat.\n  intros n _.\n  apply Hl.\n  apply ball_center.\nQed.\n  \nLemma ex_lim_seq_const (a : U) :\n  ex_lim_seq (fun n => a).\nProof.\n  split with a.\n  apply is_lim_seq_const.\nQed.\n\n(** Increasing natural functions *)\nDefinition subseq_support phi := forall n, (phi n < phi (S n))%nat.\n\nLemma subseq_support_implies_incr : forall phi,\n    subseq_support phi ->\n    forall a b, (a < b)%nat -> (phi a < phi b)%nat.\nProof.\n  intros phi Hsup a b.\n  revert a; induction b; intros a Hlt; try now inversion Hlt.\n  inversion Hlt.\n  { apply Hsup. }\n  transitivity (phi b).\n  - apply IHb.\n    apply H0.\n  - apply Hsup.\nQed.\n\nLemma subseq_support_ge_id : forall phi,\n    subseq_support phi ->\n    forall n, (n <= phi n)%nat.\nProof.\n  intros phi Hsup n.\n  induction n; try lia.\n  transitivity (S (phi n)); try lia.\n  apply Hsup.\nQed.\n\nLemma eventually_subseq_loc_gt_id :\n  forall phi N k, (forall n, (N <= n)%nat -> (phi n < phi (S n))%nat) ->\n                  (k <= phi (N + k))%nat.\nProof.\n  intros phi N k H.\n  induction k; try lia.\n  rewrite Nat.add_succ_r.\n  transitivity (S (phi (N + k)))%nat; try lia.\n  apply H.\n  lia.\nQed.\n\nLemma eventually_subseq_loc_incr :\n  forall phi N n k, (forall n, (N <= n)%nat -> (phi n < phi (S n))%nat) ->\n                    (N <= n)%nat -> (n <= k)%nat ->\n                    (phi n <= phi k)%nat.\nProof.\n  intros phi N n k H; revert n; induction k; intros n Hln Hlk.\n  - inversion Hlk; inversion Hln; subst; lia.\n  - inversion Hlk; try lia; subst.\n    etransitivity; [ apply IHk; try lia | ].\n    apply Nat.lt_le_incl.\n    apply H; lia.\nQed.\n  \nLemma eventually_subseq_loc :\n  forall phi,  eventually (fun n => (phi n < phi (S n))%nat) ->\n               filterlim phi eventually eventually.\nProof.\n  intros phi [N H].\n  intros P [N' H'].\n  split with (N + N')%nat.\n  intros n Hle.\n  apply H'.\n  etransitivity; [ apply eventually_subseq_loc_gt_id; apply H | ].\n  apply eventually_subseq_loc_incr with N; try lia.\n  apply H.\nQed.  \n  \nLemma eventually_subseq :\n  forall phi,\n    subseq_support phi ->\n    filterlim phi eventually eventually.\nProof.\n  intros phi H.\n  apply eventually_subseq_loc.\n  split with 0%nat.\n  intros n _; apply H.\nQed.\n\n\n(** Subsequences *)\n\nDefinition is_subseq {A} (v u : nat -> A) := { phi & prod (subseq_support phi) (forall n, v n = u (phi n))}.\n  \nLemma is_lim_seq_subseq_eventually (u : nat -> U) (l : U) (phi : nat -> nat) :\n  filterlim phi eventually eventually ->\n  is_lim_seq u l ->\n  is_lim_seq (fun n => u (phi n)) l.\nProof.\n  intros Hes H.\n  intros P Hloc.\n  specialize (H P Hloc) as [N H].\n  specialize (Hes (fun x => N <= x)%nat).\n  assert (eventually (fun x : nat => (N <= x)%nat)).\n  { split with N.\n    intros; lia. }\n  specialize (Hes H0); clear H0.\n  destruct Hes as [N' Hes].\n  split with N'.\n  intros n Hle'.\n  apply H.\n  apply Hes.\n  apply Hle'.\nQed.\n\nLemma is_lim_seq_subseq (u v : nat -> U) (l : U) :\n  is_subseq v u ->\n  is_lim_seq u l ->\n  is_lim_seq v l.\nProof.\n  intros [phi [sub_support Heqn]] Hlim.\n  apply is_lim_seq_ext with (fun n => u (phi n)); [intros n; rewrite Heqn; reflexivity | ].\n  apply is_lim_seq_subseq_eventually; try assumption.\n  apply eventually_subseq.\n  apply sub_support.\nQed.\n  \nLemma ex_lim_seq_subseq (u v : nat -> U) :\n  is_subseq v u ->\n  ex_lim_seq u ->\n  ex_lim_seq v.\nProof.\n  intros Hsubseq [l Hlim].\n  split with l.\n  apply is_lim_seq_subseq with u; assumption.\nQed.\n\nLemma is_lim_seq_incr_1 (u : nat -> U) (l : U) :\n  is_lim_seq u l <-> is_lim_seq (fun n => u (S n)) l.\nProof.\n  split.\n  - apply is_lim_seq_subseq.\n    split with S.\n    split; try auto.\n    intro n.\n    lia.\n  - intros Hlim P H.\n    specialize (Hlim P H) as [N Hlim].\n    split with (S N).\n    intros n Hle.\n    destruct n; try now inversion Hle.\n    apply Hlim; lia.\nQed.    \n\nLemma ex_lim_seq_incr_1 (u : nat -> U) :\n  ex_lim_seq u <-> ex_lim_seq (fun n => u (S n)).\nProof.\n  split; intros [l Hlim]; split with l.\n  - apply ->is_lim_seq_incr_1; assumption.\n  - apply is_lim_seq_incr_1; assumption.\nQed.\n\nLemma is_lim_seq_incr_n (u : nat -> U) (N : nat) (l : U) :\n  is_lim_seq u l <-> is_lim_seq (fun n => u (n + N)%nat) l.\nProof.\n  induction N.\n  - split; intros Hlim; eapply is_lim_seq_ext; try apply Hlim; intros; simpl; rewrite Nat.add_0_r; reflexivity.\n  - eapply iff_trans; [ apply IHN | ].\n    eapply iff_trans; [ apply is_lim_seq_incr_1 | ].\n    split; intros Hlim; eapply is_lim_seq_ext; try apply Hlim; intros; simpl; rewrite Nat.add_succ_r; reflexivity.\nQed.\n\nLemma ex_lim_seq_incr_n (u : nat -> U) (N : nat) :\n  ex_lim_seq u <-> ex_lim_seq (fun n => u (n + N)%nat).\nProof.\n  split; intros [l Hlim]; split with l.\n  - apply ->is_lim_seq_incr_n; assumption.\n  - apply <-is_lim_seq_incr_n; eassumption.\nQed.\n\nEnd Lim_seq_US_def.\n\nSection Lim_US_CT.\n(** ** Image by a continuous function *)\nContext {U V : UniformSpace}.\nLemma is_lim_seq_continuous (f : U -> V) (u : nat -> U) (l : U) :\n  continuous f l -> is_lim_seq u l ->\n  is_lim_seq (fun n => f (u n)) (f l).\nProof.\n  intros Hc Hlim.\n  intros P Hloc.\n  specialize (Hlim (fun x => P (f x))).\n  assert (locally l (fun x => P (f x))) as Hlocf.\n  { apply Hc.\n    apply Hloc. }\n  specialize (Hlim Hlocf).\n  destruct Hlim as [N Hlim].\n  split with N.\n  apply Hlim.\nQed.\nEnd Lim_US_CT.\n\n(** Unicity *)\nSection Lim_US_Unicity.\n  \nContext {U : UniformSpace}.\nHypothesis all_ball_eq : forall (x y : U), (forall (eps : posreal), ball x eps y) -> x = y.\n\nLemma is_lim_seq_unique (u : nat -> U) (l1 l2 : U) :\n  is_lim_seq u l1 -> is_lim_seq u l2 ->\n  l1 = l2.\nProof.\n  intros Hlim1 Hlim2.\n  apply all_ball_eq.\n  intros eps.\n  specialize (Hlim1 (fun x => ball l1 (pos_div_2 eps) x)).\n  assert (locally l1 (fun x => ball l1 (pos_div_2 eps) x)).\n  { split with (pos_div_2 eps); auto. }\n  specialize (Hlim1 H); clear H.\n  destruct Hlim1 as [N Hlim1].\n  specialize (Hlim2 (fun x => ball l2 (pos_div_2 eps) x)).\n  assert (locally l2 (fun x => ball l2 (pos_div_2 eps) x)).\n  { split with (pos_div_2 eps); auto. }\n  specialize (Hlim2 H); clear H.\n  destruct Hlim2 as [N2 Hlim2].\n  destruct eps; simpl in *.\n  replace pos with (pos / 2 + pos / 2) by lra.\n  apply ball_triangle with (u (Nat.max N N2)).\n  - apply Hlim1; lia.\n  - apply ball_sym; apply Hlim2; lia.\nQed.\nEnd Lim_US_Unicity.\n", "meta": {"author": "clucas26e4", "repo": "ramics_archimedean", "sha": "27074ea90fcb3c1b7e857b8f789f223a10f3c4dd", "save_path": "github-repos/coq/clucas26e4-ramics_archimedean", "path": "github-repos/coq/clucas26e4-ramics_archimedean/ramics_archimedean-27074ea90fcb3c1b7e857b8f789f223a10f3c4dd/Utilities/Lim_seq_US.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6871636295946203}}
{"text": "\nRequire Export Iron.Language.SystemF2Data.Type.Exp.\n\n\n(********************************************************************)\n(* Well formed types are closed under the given kind environment. *)\nInductive wfT (kn: nat) : ty -> Prop :=\n | WfT_TVar\n   :  forall ki\n   ,  ki < kn\n   -> wfT kn (TVar ki)\n\n | WfT_TCon\n   :  forall n\n   ,  wfT kn (TCon n)\n\n | WfT_TForall\n   :  forall t\n   ,  wfT (S kn) t\n   -> wfT kn (TForall t)\n\n | WfT_TApp\n   :  forall t1 t2\n   ,  wfT kn t1 -> wfT kn t2\n   -> wfT kn (TApp t1 t2).\nHint Constructors wfT.\n\n\n(* Closed types are well formed under an empty environment. *)\nDefinition closedT : ty -> Prop\n := wfT O.\nHint Unfold closedT.\n\n\n(********************************************************************)\nLemma wfT_succ\n :  forall tn t1\n ,  wfT tn     t1\n -> wfT (S tn) t1.\nProof.\n intros. gen tn.\n induction t1; intros; inverts H; eauto.\nQed.\nHint Resolve wfT_succ.\n\n\nLemma wfT_more\n :  forall tn1 tn2 tt\n ,  tn1 <= tn2\n -> wfT tn1 tt\n -> wfT tn2 tt.\nProof.\n intros. gen tn1 tn2.\n induction tt; intros; inverts H0; eauto.\nQed.\nHint Resolve wfT_more.\n\n\nLemma wfT_max\n :  forall tn1 tn2 tt\n ,  wfT tn1 tt\n -> wfT (max tn1 tn2) tt.\nProof.\n intros.\n assert (  ((tn1 <  tn2) /\\ max tn1 tn2 = tn2)\n        \\/ ((tn2 <= tn1) /\\ max tn1 tn2 = tn1)).\n  eapply Max.max_spec.\n\n inverts H0.\n - rip. rewritess.\n   eapply wfT_more; eauto.\n\n - inverts H1.\n   rip. rewritess. auto.\nQed.\nHint Resolve wfT_max.\n\n\nLemma wfT_exists\n :  forall t1\n ,  (exists tn, wfT tn t1).\nProof.\n intros.\n induction t1.\n - Case \"TCon\".\n   exists 0. auto.\n\n - Case \"TVar\".\n   exists (S n). eauto.\n\n - Case \"TForall\".\n   shift tn.\n   eapply WfT_TForall; eauto.\n\n - Case \"TApp\".\n   destruct IHt1_1 as [tn1].\n   destruct IHt1_2 as [tn2].\n   exists (max tn1 tn2).\n   eapply WfT_TApp.\n    eauto.\n    rewrite Max.max_comm. eauto.\nQed.\nHint Resolve wfT_exists.\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/SystemF2Data/Type/Relation/WfT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6871636204732362}}
{"text": "Require Export SfLib.\n\n(**  Motivative example:\n     Z ::= X;\n     Y ::= 1;\n     WHILE not (Z = 0) DO\n       Y ::= Y * Z;\n       Z ::= Z - 1\n     END\n*)\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 (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  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 =>\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  Theorem optimize_0plus_sound : forall e,\n    aeval (optimize_0plus e) = aeval e.\n  Proof.\n    intros e.\n    induction e.\n\n    (* ANum *)\n    reflexivity.\n    (* APlus *)\n    destruct e1.\n      destruct n.\n        simpl. 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    (* AMinus *)\n    simpl. rewrite IHe1. rewrite IHe2. reflexivity.\n    simpl. rewrite IHe1. rewrite IHe2. 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      try reflexivity.\n\n  (* APlus *)\n    destruct e1;\n      try (simpl; simpl in IHe1; rewrite IHe1; rewrite IHe2; reflexivity).\n    destruct n;\n      simpl; rewrite IHe2; reflexivity.\n  Qed.\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  Example silly_presburger_example :\n    forall m n o p,\n      m + n <= n + o /\\ o + 3 = p + 3 ->\n      m <= p.\n  Proof.\n    intros. omega.\n  Qed.\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\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\"\n      | Case_aux c \"E_AMinus\" | Case_aux c \"E_AMult\" ].\n\n  Theorem aeval_iff_aevalR :\n    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;\n      intros; subst; simpl; constructor;\n\n      try apply IHa1;\n        try apply IHa2;\n        reflexivity.\n  Qed.\n\n  Inductive bevalR : bexp -> bool -> Prop :=\n    | E_BTrue : bevalR BTrue true\n    | E_BFalse : bevalR BFalse false\n    | E_BEq : forall (e1 e2 : aexp) (n1 n2 : nat),\n                (e1 || n1) -> (e2 || n2) -> (bevalR (BEq e1 e2) (beq_nat n1 n2))\n    | E_BLe : forall (e1 e2 : aexp) (n1 n2 : nat),\n                (e1 || n1) -> (e2 || n2) -> (bevalR (BLe e1 e2) (ble_nat n1 n2))\n    | E_BNot : forall (e : bexp) (b : bool),\n                 (bevalR e b) -> (bevalR (BNot e) (negb b))\n    | E_BAnd : forall (e1 e2 : bexp) (b1 b2 : bool),\n                 (bevalR e1 b1) -> (bevalR e2 b2) -> (bevalR (BAnd e1 e2) (b1 && b2)).\n\n  Theorem beval_iff_bevalR :\n    forall e b,\n      bevalR e b <-> beval e = b.\n  Proof.\n    split.\n    Case \"->\".\n    intros H.\n    induction H.\n    reflexivity.\n\n    reflexivity.\n\n    simpl.\n    apply aeval_iff_aevalR in H.\n    apply aeval_iff_aevalR in H0.\n    rewrite H. rewrite H0.\n    reflexivity.\n\n    simpl.\n    apply aeval_iff_aevalR in H.\n    apply aeval_iff_aevalR in H0.\n    rewrite H. rewrite H0.\n    reflexivity.\n\n    simpl.\n    rewrite IHbevalR.\n    reflexivity.\n\n    simpl.\n    rewrite IHbevalR1.\n    rewrite IHbevalR2.\n    reflexivity.\n\n    Case \"<-\".\n    generalize dependent b.\n    induction e;\n      intros;\n      simpl in H;\n      rewrite <- H;\n      constructor.\n\n    apply aeval_iff_aevalR.\n    reflexivity.\n    apply aeval_iff_aevalR.\n    reflexivity.\n\n    apply aeval_iff_aevalR.\n    reflexivity.\n    apply aeval_iff_aevalR.\n    reflexivity.\n\n    apply IHe.\n    reflexivity.\n\n    apply IHe1.\n    reflexivity.\n    apply IHe2.\n    reflexivity.\n  Qed.\n\nEnd AExp.\n\nModule Id.\n\n  Inductive id : Type :=\n    Id : nat -> id.\n\n  Definition beq_id X1 X2 :=\n    match (X1, X2) with\n        (Id n1, Id n2) => beq_nat n1 n2\n    end.\n\n  Theorem beq_id_refl :\n    forall X,\n      true = beq_id X X.\n  Proof.\n    intros. destruct X.\n    apply beq_nat_refl.  Qed.\n\n  Theorem beq_id_eq :\n    forall i1 i2,\n      true = beq_id i1 i2 -> i1 = i2.\n  Proof.\n  Admitted.\n\n  Theorem beq_id_false_not_eq :\n    forall i1 i2,\n      beq_id i1 i2 = false -> i1 <> i2.\n  Proof.\n  Admitted.\n\n  Theorem not_eq_beq_id_false :\n    forall i1 i2,\n      i1 <> i2 -> beq_id i1 i2 = false.\n  Proof.\n  Admitted.\n\n  Theorem beq_id_sym:\n    forall i1 i2,\n      beq_id i1 i2 = beq_id i2 i1.\n  Proof.\n  Admitted.\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  Admitted.\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  Admitted.\n\nTheorem update_example : forall (n:nat),\n  (update empty_state (Id 2) n) (Id 3) = 0.\nProof.\n  Admitted.\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  Admitted.\n\nTheorem update_same : forall x1 k1 k2 (f : state),\n  f k1 = x1 ->\n  (update f k1 x1) k2 = f k2.\nProof.\n  Admitted.\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  Admitted.\n\nDefinition X : id := Id 0.\nDefinition Y : id := Id 1.\nDefinition Z : id := Id 2.\n\nInductive aexp : Type :=\n| ANum : nat -> aexp\n| AId : id -> aexp                (* <----- NEW *)\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\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\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 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\n\n(* from ImpCEvalFun *)\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      (* This definition of while needs special tecnique *)\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  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\n(* Relational definition *)\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 X,\n      aeval st a1 = n ->\n      (X ::= a1) / 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' 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\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_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  repeat eapply E_Seq; eapply E_Ass; simpl; exists.\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\n  ceval_cases (induction E1) case;\n    intros; inversion E2; subst.\n  reflexivity.\n\n  reflexivity.\n\n  apply IHE1_1 in H1.\n  rewrite <- H1 in H4.\n  apply IHE1_2.\n  assumption.\n\n  apply IHE1.\n  assumption.\n\n  rewrite H in H5.\n  inversion H5.\n\n  rewrite H in H5.\n  inversion H5.\n\n  apply IHE1.\n  assumption.\n\n  reflexivity.\n\n  rewrite H in H2.\n  inversion H2.\n\n  rewrite H in H4.\n  inversion H4.\n\n  apply IHE1_2.\n  assert (st' = st'0) as EQ1.\n  apply IHE1_1.\n  assumption.\n  rewrite EQ1.\n  assumption.\nQed.\n\nDefinition XtimesYinZ : com :=\n  Z ::= (AMult (AId X) (AId Y)).\n\nTheorem XtimesYinZ_spec :\n  forall st n m st',\n    st X = n -> st Y = m -> XtimesYinZ / st || st' -> st' Z = n * m.\nProof.\n  intros.\n  inversion H1.\n  subst.\n  apply update_eq.\nQed.\n\nDefinition loop : com :=\n  WHILE BTrue DO\n    SKIP\n  END.\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  ceval_cases (induction contra) Case; inversion Heqloopdef.\n  subst. inversion H.\n  subst. apply IHcontra2. assumption.\nQed.\n(* Reference: https://github.com/sfja/sfja/blob/master/ImpList_J.v *)\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\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\nRequire Export Arith.Minus.\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.\n  subst.\n  inversion H1.\n  inversion H4.\n  subst.\n\n  unfold update. simpl.\n  destruct (st Z) as [| z'].\n  apply ex_falso_quodlibet.  apply HZnz. reflexivity.\n\n  rewrite <- Hm.\n  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  assumption.\n  simpl in H0.\n  apply beq_nat_false.\n  apply negb_true_iff.\n  assumption.\n  assumption.\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.  Qed.\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  apply guard_false_after_loop in H5. simpl in H5.\n  assert (st'' Z = 0).\n    apply beq_nat_true_iff. rewrite <- negb_false_iff. assumption.\n  unfold fact_invariant in H0.\n  rewrite H1 in H0.\n  simpl in H0.\n  omega.\nQed.\n\n(* stack machine *)\nInductive sinstr : Type :=\n| SPush : nat -> sinstr\n| SLoad : id -> sinstr\n| SPlus : sinstr\n| SMinus : sinstr\n| SMult : sinstr.\n\nDefinition s_eval (st : state) (stack : list nat) (inst : sinstr) : list nat :=\n  match inst with\n    | SPush x => x :: stack\n    | SLoad v => st v :: stack\n    | SPlus   => match stack with\n                   | a :: b :: rest => b + a :: rest\n                   | _ => []\n                 end\n    | SMinus  => match stack with\n                   | a :: b :: rest => b - a :: rest\n                   | _ => []\n                 end\n    | SMult   => match stack with\n                   | a :: b :: rest => b * a :: rest\n                   | _ => []\n                 end\n  end.\n\nFixpoint s_execute (st : state) (stack : list nat)\n                   (prog : list sinstr)\n                 : list nat :=\n  match prog with\n    | [] => stack\n    | inst :: insts =>\n      s_execute st (s_eval st stack inst) insts\n  end.\n\nExample s_execute1 :\n     s_execute empty_state []\n       [SPush 5, SPush 3, SPush 1, SMinus]\n   = [2, 5].\nProof. reflexivity. Qed.\n\nExample s_execute2 :\n     s_execute (update empty_state X 3) [3,4]\n       [SPush 4, SLoad X, SMult, SPlus]\n   = [15, 4].\nProof. reflexivity. Qed.\n\nFixpoint s_compile (e : aexp) : list sinstr :=\n  match e with\n    | ANum n       => [SPush n]\n    | AId X        => [SLoad X]\n    | APlus a1 a2  => s_compile a1 ++ s_compile a2 ++ [SPlus]\n    | AMinus a1 a2 => s_compile a1 ++ s_compile a2 ++ [SMinus]\n    | AMult a1 a2  => s_compile a1 ++ s_compile a2 ++ [SMult]\n  end.\n\n(* not used *)\nTheorem s_execute_step :\n  forall (st : state) (inst : sinstr) (prog : list sinstr) (l l' l'': list nat),\n    s_eval st l inst = l' ->\n    s_execute st l' prog = l'' ->\n    s_execute st l (inst :: prog) = l''.\nProof.\n  intros st inst.\n  destruct inst;\n    simpl;\n    intros;\n    try rewrite H; assumption;\n    try destruct l;\n      try rewrite H; assumption;\n      try destruct l; rewrite H; assumption.\nQed.\n\n(* not used *)\nTheorem s_execute_step_last :\n  forall (st : state) (inst : sinstr) (prog : list sinstr) (l l' l'': list nat),\n    s_execute st l prog = l' ->\n    s_eval st l' inst = l'' ->\n    s_execute st l (prog ++ [inst]) = l''.\nProof.\n  intros st inst.\n  induction prog.\n  destruct inst;\n    simpl;\n    intros;\n    rewrite H;\n    assumption.\n\n  intros.\n  rewrite <- app_comm_cons.\n  eapply s_execute_step.\n  exists.\n  eapply IHprog.\n  exists.\n  simpl in H.\n  rewrite H.\n  assumption.\nQed.\n\nTheorem s_execute_concat_program :\n  forall (st : state) (prog1 prog2 : list sinstr) (l : list nat),\n    s_execute st l (prog1 ++ prog2) = s_execute st (s_execute st l prog1) prog2.\nProof.\n  intros st.\n  induction prog1 as [| inst insts].\n  Case \"prog1 = []\".\n    simpl. reflexivity.\n  Case \"prog1 = inst :: insts\".\n    simpl.\n    intros.\n    destruct (s_eval st l inst);\n      apply IHinsts.\nQed.\n\nTheorem s_compile_correct : forall (st : state) (e : aexp) (l : list nat),\n  s_execute st l (s_compile e) = aeval st e :: l.\nProof.\n  intros st.\n\n  aexp_cases (induction e) Case;\n    intros;\n    simpl;\n    try trivial;\n    try\n      (repeat (rewrite s_execute_concat_program);\n       rewrite IHe2;\n       rewrite IHe1;\n       reflexivity).\nQed.\n", "meta": {"author": "egejjespersen", "repo": "software_foundation_exercise", "sha": "e2f788ff88b4b6a6cefc3f413e646c8a733232b2", "save_path": "github-repos/coq/egejjespersen-software_foundation_exercise", "path": "github-repos/coq/egejjespersen-software_foundation_exercise/software_foundation_exercise-e2f788ff88b4b6a6cefc3f413e646c8a733232b2/Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388040954684, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.6871395374321735}}
{"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\nend.\n\nCompute (next_weekday friday).\nCompute (next_weekday(next_weekday friday)).\n\nExample test_next_weekday: (next_weekday (next_weekday saturday)) = tuesday.\n\nProof. simpl. reflexivity. Qed.\n\nFrom Coq Require Export String.\n\nInductive bool: Type :=\n  | true\n  | false.\n\nDefinition negb (b: bool) : bool :=\n  match b with\n  | true => false\n  | false => true\nend.\n\nDefinition andb (b₁: bool) (b₂ : bool) : bool := \n  match b₁ with\n  | true => b₂\n  | false => false\nend.\n\nDefinition orb (b₁: bool) (b₂ : bool) : bool := \n  match b₁ with\n  | true => true\n  | false => b₂\nend.\n\n\nExample test_orb1: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb2: (orb false false) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb3: (orb false true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb4: (orb true true) = true.\nProof. simpl. reflexivity. Qed.\n\n\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\nDefinition negb' (b: bool) : bool :=\n  if b then false\n  else true.\n\nDefinition andb' (b₁: bool) (b₂: bool) : bool :=\n  if b₁ then b₂\n  else false.\n\nDefinition orb' (b₁: bool) (b₂: bool) : bool :=\n  if b₁ then true\n  else b₂.\n\n\nDefinition nandb (b₁:bool) (b₂:bool) : bool := \n  if b₁ then (negb b₂)\n  else true.\n\n\nExample test_nand1: (nandb false true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_nand2: (nandb true false) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_nand3: (nandb false false) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_nand4: (nandb true true) = false.\nProof. simpl. reflexivity. Qed.\n\n\n\nDefinition andb3 (b₁:bool) (b₂:bool) (b₃:bool) : bool :=\n  if (andb (andb b₁ b₂) b₃) then true\n  else false.\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 :=\n  | red\n  | green\n  | blue.\n\nInductive color : Type :=\n  | black\n  | white\n  | primary (p : rgb).\n\nDefinition monochrome (c: color) : bool :=\n  match c with\n  | black => true\n  | white => true\n  | primary p => false\n  end.\n\nDefinition isred (c: color) : bool :=\n  match c with\n  | black => false\n  | white => false\n  | primary red => true\n  | primary _ => false\n  end.\n\nModule Playground.\n  Definition b : rgb := blue.\nEnd Playground.\n\nDefinition b : bool := true.\n\nCheck Playground.b : rgb.\nCheck b : bool.\n\nModule TuplePlayground.\n  Inductive bit : Type :=\n    | B₀\n    | B₁.\n\n  Inductive nybble : Type :=\n    | bits (b₀ b₁ b₂ b₃ : bit).\n\n  Check (bits B₁ B₀ B₁ B₀) : nybble.\n\n  Definition all_zero (nb : nybble) : bool :=\n    match nb with\n    | (bits B₀ B₀ B₀ B₀) => true\n    | (bits _ _ _ _) => false\n    end.\n\n  Compute (all_zero (bits B₁ B₀ B₁ B₀)).\n  Compute (all_zero (bits B₀ B₀ B₀ B₀)).\nEnd TuplePlayground.\n\n\nModule NatPlayground.\n  Inductive nat : Type :=\n    | O\n    | S (n : nat).\n\n  Inductive nat' : Type :=\n    | stop\n    | tick (foo : nat').\n    \n  Definition pred (n : nat) : nat :=\n    match n with\n    | O => O\n    | S n' => n'\n    end.\nEnd NatPlayground.\n\n\nCheck (S (S (S (S O)))).\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\nCompute (minustwo 4).\n\n\nCheck S : nat -> nat.\nCheck pred : nat -> nat.\nCheck minustwo : nat -> nat.\n\nFixpoint even (n : nat) : bool :=\n  match n with\n  | 0 => true\n  | S 0 => false\n  | S (S n') => even n'\n  end.\n\nDefinition odd (n : nat) : bool :=\n  negb (even n).\n\nExample test_odd1: odd 1 = true.\nProof. simpl. reflexivity. Qed.\nExample test_odd2: odd 4 = false.\nProof. simpl. reflexivity. Qed.\n\nModule NatPlayground2.\n\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 3 2).\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  | S _, 0 => 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  | 0 => S 0\n  | S p => mult base (exp base p)\n  end.\n  \n  Fixpoint factorial (n:nat) : nat :=\n    match n with\n    | 0 => 1\n    | S n' => (NatPlayground2.mult (S n') (factorial n'))\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  \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 eqb (n m : nat) : bool :=\n  match n with\n  | 0 => match m with\n      | 0 => true\n      | S m' => false\n      end\n  | S n' => match m with\n      | 0 => false\n      | S m' => eqb n' m'\n      end\n  end.\n\nFixpoint leb (n m : nat) : bool :=\n  match n with\n  | 0 => true\n  | S n' => match m with\n    | 0 => false\n    | S m' => leb n' m'\n    end\n  end.\n\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\n\nDefinition ltb (n m : nat) : bool :=\n  andb (leb n m) (negb (eqb n m)).\n\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\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_0_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem plus_0_n' : forall n : nat, 0 + n = n.\nProof.\n  intros n. reflexivity. Qed.\n\nTheorem plus_0_n'' : forall n : nat,\n  0 + n = n.\nProof.\n  intros m. reflexivity. Qed.\n\nTheorem plus_1_l : forall n : nat, 1 + n = S n.\nProof. intros n. reflexivity. Qed.\n\nTheorem mult_0_l : forall n : nat, 0 * n = 0.\nProof. intros n. reflexivity. Qed.\n\nTheorem plus_id_example : forall n m : nat,\n  n = m -> n + n = m + m.\n\nProof.\n  intros n m.\n  intros H.\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.\n  intros H1 H2.\n  rewrite -> H1.\n  rewrite -> H2.\n  reflexivity. Qed.\n  \nCheck mult_n_O.\n\nCheck mult_n_Sm.\n\nTheorem mult_n_0_m_0 : forall p q : nat,\n  (p * 0) + (q * 0) = 0.\nProof.\n  intros p q.\n  rewrite <- mult_n_O.\n  rewrite <- mult_n_O.\n  reflexivity. Qed.\n  \nTheorem mult_n_1 : forall p : nat,\n  p * 1 = p.\nProof.\n  intros p.\n  rewrite <- mult_n_Sm.\n  rewrite <- mult_n_O.\n  reflexivity. Qed.\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  (n +1) =? 0 = false.\n\nProof.\n  intros 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.\nQed.\n\nTheorem andb_commutative : 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\nTheorem andb3_exchange : forall b c d,\n  andb (andb b c) d = andb (andb b d) c.\nProof.\n  intros b c d. destruct b eqn:Eb.\n  - destruct c eqn:Ec.\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\n  - destruct c eqn:Ec.\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\nQed.\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c H.\n  destruct c eqn:Ec.\n    - reflexivity.\n    - rewrite <- H.\n      destruct b.\n      reflexivity. reflexivity.\nQed.\n\nTheorem plus_1_neq_0' : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_commutative'' : forall b c,\n  andb b c = andb c b.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n  \nTheorem zero_nbeq_plus_1 : forall n : nat,\n  0 =? (n + 1) = false.\nProof.\n  intros [].\n  - reflexivity.\n  - reflexivity.\nQed.\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "puneetgill05", "repo": "Coq-Software-Foundations", "sha": "4a7dd2b6b6f4ed67f2ba6bcda331019400a8fab8", "save_path": "github-repos/coq/puneetgill05-Coq-Software-Foundations", "path": "github-repos/coq/puneetgill05-Coq-Software-Foundations/Coq-Software-Foundations-4a7dd2b6b6f4ed67f2ba6bcda331019400a8fab8/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.6871157690502817}}
{"text": "Require Import List Cpdt.CpdtTactics.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nSection stream.\n  Variable A : Type.\n\n  CoInductive stream : Type :=\n  | Cons : A -> stream -> stream.\nEnd stream.\n\nCoFixpoint zeroes : stream nat := Cons 0 zeroes.\n\nCoFixpoint trues_falses : stream bool := Cons true falses_trues\nwith falses_trues : stream bool := Cons false trues_falses.\n\nFixpoint approx A (s : stream A) (n : nat) : list A :=\n  match n with\n  | O => nil\n  | S n' =>\n    match s with\n    | Cons h t => h :: approx t n'\n    end\n  end.\n\nEval simpl in approx zeroes 10.\nCompute (approx zeroes 10).\n\nEval simpl in approx trues_falses 10.\n\nSection map.\n  Variables A B : Type.\n  Variable f : A -> B.\n\n  CoFixpoint map (s : stream A) : stream B :=\n    match s with\n    | Cons h t => Cons (f h) (map t)\n    end.\nEnd map.\n\nSection interleave.\n  Variable A : Type.\n\n  CoFixpoint interleave (s1 s2 : stream A) : stream A :=\n    match s1, s2 with\n    | Cons h1 t1, Cons h2 t2 => Cons h1 (Cons h2 (interleave t1 t2))\n    end.\nEnd interleave.\n\nSection map'.\n  Variables A B : Type.\n  Variable f : A -> B.\n\n  (* CoFixpoint map' (s : stream A) : stream B :=\n    match s with\n    | Cons h t => interleave (Cons (f h) (map' t)) (Cons (f h) (map' t))\n    end. *)\nEnd map'.\n\nDefinition tl A (s : stream A) : stream A :=\n  match s with\n  | Cons _ s' => s'\n  end.\n\nCoFixpoint ones : stream nat := Cons 1 ones.\nDefinition ones' := map S zeroes.\n\nTheorem ones_eq : ones = ones'.\nAbort.\n\nSection stream_eq.\n  Variable A : Type.\n\n  CoInductive stream_eq : stream A -> stream A -> Prop :=\n  | Stream_eq : forall h t1 t2,\n      stream_eq t1 t2 -> stream_eq (Cons h t1) (Cons h t2).\n  \nEnd stream_eq.\n\nTheorem ones_eq : stream_eq ones ones'.\n  cofix.\n  assumption.\n  Undo.\n  simpl.\nAbort.\n\nDefinition frob A (s : stream A) : stream A :=\n  match s with\n  | Cons h t => Cons h t\n  end.\n\nTheorem frob_eq : forall A (s : stream A), s = frob s.\n  destruct s; reflexivity.\nQed.\n\nTheorem ones_eq : stream_eq ones ones'.\n  cofix.\n  rewrite (frob_eq ones).\n  rewrite (frob_eq ones').\n  simpl.\n  constructor.\n  assumption.\nQed.\n\nDefinition hd A (s : stream A) : A :=\n  match s with\n  | Cons x _ => x\n  end.\n\nSection stream_eq_coind.\n  Variable A : Type.\n  Variable R : stream A -> stream A -> Prop.\n\n  Hypothesis Cons_case_hd : forall s1 s2, R s1 s2 -> hd s1 = hd s2.\n  Hypothesis Cons_case_tl : forall s1 s2, R s1 s2 -> R (tl s1) (tl s2).\n\n  Theorem stream_eq_coind : forall s1 s2, R s1 s2 -> stream_eq s1 s2.\n    cofix. destruct s1. destruct s2. intro.\n    generalize (Cons_case_hd H). simpl. intro Heq. rewrite Heq.\n    constructor.\n    apply stream_eq_coind.\n    apply (Cons_case_tl H).\n  Qed.\nEnd stream_eq_coind.\n\nPrint stream_eq_coind.\n\nTheorem ones_eq'' : stream_eq ones ones'.\n  apply (stream_eq_coind (fun s1 s2 => s1 = ones /\\ s2 = ones')); crush.\nQed.\n\nSection stream_eq_loop.\n  Variable A : Type.\n  Variables s1 s2 : stream A.\n\n  Hypothesis Cons_case_hd : hd s1 = hd s2.\n  Hypothesis loop1 : tl s1 = s1.\n  Hypothesis loop2 : tl s2 = s2.\n\n  Theorem stream_eq_loop : stream_eq s1 s2.\n    apply (stream_eq_coind (fun s1' s2' => s1' = s1 /\\ s2' = s2)); crush.\n  Qed.\nEnd stream_eq_loop.\n\nTheorem ones_eq''' : stream_eq ones ones'.\n  apply stream_eq_loop; crush.\nQed.\n\nRequire Import Arith.\n\nPrint fact.\n\nCoFixpoint fact_slow' (n : nat) := Cons (fact n) (fact_slow' (S n)).\nDefinition fact_slow := fact_slow' 1.\n\nCoFixpoint fact_iter' (cur acc : nat) := Cons acc (fact_iter' (S cur) (acc * cur)).\nDefinition fact_iter := fact_iter' 2 1.\n\nEval simpl in approx fact_iter 5.\nEval simpl in approx fact_slow 5.\n\nLemma fact_def : forall x n,\n    fact_iter' x (fact n * S n) = fact_iter' x (fact (S n)).\n  simpl. intros. f_equal. ring.\nQed.\n\nHint Resolve fact_def.\n\nLemma fact_eq' : forall n, stream_eq (fact_iter' (S n) (fact n)) (fact_slow' n).\n  intro;\n  apply (stream_eq_coind (fun s1 s2 => exists n, s1 = fact_iter' (S n) (fact n)\n                                                 /\\ s2 = fact_slow' n));\n    crush;\n    eauto.\nQed.\n\nTheorem fact_eq : stream_eq fact_iter fact_slow.\n  apply fact_eq'.\nQed.\n\nSection stream_eq_onequant.\n  Variables A B : Type.\n  Variables f g : A -> stream B.\n\n  Hypothesis Cons_case_hd : forall x, hd (f x) = hd (g x).\n  Hypothesis Cons_case_tl : forall x, exists y,\n        tl (f x) = f y /\\ tl (g x) = g y.\n\n  Theorem stream_eq_onequant : forall x, stream_eq (f x) (g x).\n    intro.\n    apply (stream_eq_coind (fun s1 s2 => exists x,\n                                s1 = f x /\\ s2 = g x));\n      crush; eauto.\n  Qed.\nEnd stream_eq_onequant.\n\nLemma fact_eq'' : forall n, stream_eq (fact_iter' (S n) (fact n)) (fact_slow' n).\n  apply stream_eq_onequant; crush; eauto.\nQed.\n\nDefinition var := nat.\nDefinition vars := var -> nat.\nDefinition set (vs : vars) (v : var) (n : nat) : vars :=\n  fun v' => if beq_nat v v' then n else vs v'.\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Var : var -> exp\n| Plus : exp -> exp -> exp.\n\nFixpoint evalExp (vs : vars) (e : exp) : nat :=\n  match e with\n  | Const n => n\n  | Var v => vs v\n  | Plus e1 e2 => evalExp vs e1 + evalExp vs e2\n  end.\n\nInductive cmd : Set :=\n| Assign : var -> exp -> cmd\n| Seq : cmd -> cmd -> cmd\n| If : exp -> cmd -> cmd                        \n| While : exp -> cmd -> cmd.\n\nCoInductive evalCmd : vars -> cmd -> vars -> Prop :=\n| EvalAssign : forall vs v e, evalCmd vs (Assign v e) (set vs v (evalExp vs e))\n| EvalSeq : forall vs1 vs2 vs3 c1 c2,\n    evalCmd vs1 c1 vs2 ->\n    evalCmd vs2 c2 vs3 ->\n    evalCmd vs1 (Seq c1 c2) vs3\n| EvalIfFalse : forall vs e c,\n    evalExp vs e = 0 ->\n    evalCmd vs (If e c) vs\n| EvalIfTrue : forall vs1 vs2 e c,\n    evalExp vs1 e <> 0 ->\n    evalCmd vs1 c vs2 ->\n    evalCmd vs1 (If e c) vs2\n| EvalWhileFalse : forall vs e c,\n    evalExp vs e = 0 ->\n    evalCmd vs (While e c) vs\n| EvalWhileTrue : forall vs1 vs2 vs3 e c,\n    evalExp vs1 e <> 0 ->\n    evalCmd vs1 c vs2 ->\n    evalCmd vs2 (While e c) vs3 ->\n    evalCmd vs1 (While e c) vs3.\n\nSection evalCmd_coind.\n  Variable R : vars -> cmd -> vars -> Prop.\n\n  Hypothesis AssignCase : forall vs1 vs2 v e, R vs1 (Assign v e) vs2\n                                              -> vs2 = set vs1 v (evalExp vs1 e).\n  Hypothesis SeqCase : forall vs1 vs3 c1 c2, R vs1 (Seq c1 c2) vs3\n                                             -> exists vs2, R vs1 c1 vs2 /\\ R vs2 c2 vs3.\n  Hypothesis IfCase : forall vs1 vs2 e c, R vs1 (If e c) vs2\n                      -> (evalExp vs1 e = 0 /\\ vs1 = vs2)\n                           \\/ (evalExp vs1 e <> 0 /\\ R vs1 c vs2).\n  Hypothesis WhileCase : forall vs1 vs3 e c, R vs1 (While e c) vs3\n                                             -> (evalExp vs1 e = 0 /\\ vs3 = vs1)\n                                                \\/ exists vs2, evalExp vs1 e <> 0 /\\ R vs1 c vs2 /\\ R vs2 (While e c) vs3.\n\n  Theorem evalCmd_coind : forall vs1 c vs2, R vs1 c vs2 -> evalCmd vs1 c vs2.\n    cofix; intros; destruct c.\n    rewrite (AssignCase H); constructor.\n    destruct (SeqCase H) as [? [? ?]]. econstructor; eauto.\n    destruct (IfCase H) as [[? ?] | [? ?]]; subst; constructor; auto.\n    destruct (WhileCase H) as [[? ?] | [? [? [? ?]]]]; subst; econstructor; eauto.\n  Qed.\nEnd evalCmd_coind.\n\nFixpoint optExp (e : exp) : exp :=\n  match e with\n  | Plus (Const 0) e => optExp e\n  | Plus e1 e2 => Plus (optExp e1) (optExp e2)\n  | _ => e\n  end.\n\nFixpoint optCmd (c : cmd) : cmd :=\n  match c with\n  | Assign v e => Assign v (optExp e)\n  | Seq c1 c2 => Seq (optCmd c1) (optCmd c2)\n  | If e c => If (optExp e) (optCmd c)\n  | While e c => While (optExp e) (optCmd c)\n  end.\n\nLemma optExp_correct : forall vs e, evalExp vs (optExp e) = evalExp vs e.\n  induction e; crush;\n  repeat (match goal with\n          | [ |- context [match ?E with Const _ => _ | _ => _ end]] => destruct E\n          | [ |- context [match ?E with O => _ | S _ => _ end]] => destruct E\n          end; crush).\nQed.\n\nHint Rewrite optExp_correct.\n\nLtac finisher := match goal with\n                 | [H : evalCmd _ _ _ |- _ ] => ((inversion H; [])\n                                                 || (inversion H; [|])); subst\n                 end; crush; eauto 10.\n\nLemma optCmd_correct1 : forall vs1 c vs2, evalCmd vs1 c vs2\n                                          -> evalCmd vs1 (optCmd c) vs2.\n  intros; apply (evalCmd_coind (fun vs1 c' vs2 => exists c, evalCmd vs1 c vs2\n                                                            /\\ c' = optCmd c));\n  eauto; crush;\n    match goal with\n    | [H : _ = optCmd ?E |- _ ] => destruct E; simpl in *; discriminate\n                                                           || injection H; intros; subst\n    end; finisher.\nQed.\n\nLemma optCmd_correct2 : forall vs1 c vs2, evalCmd vs1 (optCmd c) vs2\n                                          -> evalCmd vs1 c vs2.\n  intros; apply (evalCmd_coind (fun vs1 c vs2 => evalCmd vs1 (optCmd c) vs2));\n    crush; finisher.\nQed.\n\nTheorem optCmd_correct : forall vs1 c vs2, evalCmd vs1 (optCmd c) vs2\n                                           <-> evalCmd vs1 c vs2.\n  intuition;\n    apply optCmd_correct1 || apply optCmd_correct2; assumption.\nQed.\n\n\n\n                      \n                                                       \n\n\n  \n\n  \n\n\n", "meta": {"author": "mattjquinn", "repo": "distsyscoq", "sha": "815906ff12881c26010dd8312a3bcb94fc45fe9a", "save_path": "github-repos/coq/mattjquinn-distsyscoq", "path": "github-repos/coq/mattjquinn-distsyscoq/distsyscoq-815906ff12881c26010dd8312a3bcb94fc45fe9a/cpdt/src/MQuinnCoinductive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.6871157566757822}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (z : natural) (lf2 : natural) (lf1 : natural)\n  : natural := plus Zero (plus Zero lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj54_coqofml_KhHPNI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6870962306458596}}
{"text": "Require Import Le.\n\nRequire Import Logic.Axiom.Wec.\nRequire Import Logic.Axiom.Dec.\nRequire Import Logic.Axiom.Witness.\n\nRequire Import Logic.Class.Ord.\n\nRequire Import Logic.Nat.Ord.\nRequire Import Logic.Nat.Leq.\nRequire Import Logic.Nat.Wec.\nRequire Import Logic.Nat.Dec.\n\nDeclare Scope Nat_Subset_scope.\n\n(* Subset of N defined as predicate over N                                      *)\nDefinition Subset : Type := nat -> Prop.\n\n(* n is an element of subset A.                                                 *)\nDefinition Elem (n:nat) (A:Subset) : Prop := A n.\n\nNotation \"n :: A\" := (Elem n A) : Nat_Subset_scope.\n\nOpen Scope Nat_Subset_scope.\n\n(* n is the smallest element of A.                                              *)\nDefinition SmallestOf (A:Subset) (n:nat) : Prop :=\n    (n :: A) /\\ forall (m:nat), m :: A -> n <= m.\n\n(* A is a finite subset of N.                                                   *)\nDefinition Finite (A:Subset) : Prop :=\n    exists (n:nat), forall (m:nat), m :: A -> m <= n.\n\n(* A /\\ [0,n]                                                                   *)\nDefinition restrict (n:nat) (A:Subset) : Subset :=\n    fun (m:nat)  => m :: A /\\ m <= n.\n\nLemma restrictWec : forall (A:Subset) (n:nat), pWec A -> pWec (restrict n A).\nProof.\n    intros A n H1 k. apply andWec.\n    - apply H1.\n    - apply DecWec, leqDec.\nDefined.\n\n(* All restricted subsets are finite.                                           *)\nLemma restrictFinite : forall (A:Subset) (n:nat), Finite (restrict n A).\nProof.\n    intros A n. exists n. intros m [H1 H2]. assumption.\nDefined.\n\n\n(* If A /\\ [0,n] is non-empty, being the smallest element of A is the same as   *)\n(* being the smallest element of A /\\ [0, n].                                   *)\nLemma restrictSmallest : forall (A:Subset) (n m:nat), \n    (exists (k:nat), k :: restrict n A) ->\n    SmallestOf A m <-> SmallestOf (restrict n A) m.\nProof.\n    intros A n m [k [H1 H2]]. split.\n    - intros [H3 H4]. split.\n        + split; try assumption. apply le_trans with k; try assumption.\n          apply H4. assumption.\n        + intros p [H5 H6]. apply H4. assumption.\n    - intros [[H3 H4] H5]. split; try assumption. intros p H6.\n      destruct (leqTotal p n) as [H7|H7].\n        + apply H5. split; assumption.\n        + apply le_trans with n; assumption.\nDefined.\n\nLemma nonEmptyFiniteHasSmallest : forall (A:Subset),\n    pWec A                   ->     (* A is weakly decidable *)\n    (exists (k:nat), k :: A) -> \n    Finite A                 -> \n    (exists (k:nat), SmallestOf A k).\n\nProof.\n    intros A W H2 [n H1]. revert n A W H1 H2.\n    induction n as [|n IH]; intros A W H1 [m H2].\n    - assert (m = 0) as H3. { apply le_0, H1. assumption. }\n      subst. exists 0. split; try assumption. intros m H3. apply le_0_n.\n    - destruct (boundedWec A W n) as [H3|H3]. \n        + destruct H3 as [m' [H3 H4]].\n          assert (exists (k:nat), SmallestOf (restrict n A) k) as H5. \n            {apply IH.\n                { apply  restrictWec. assumption. }\n                { intros k [H5 H6]. assumption. }\n                { exists m'. split; assumption. }}\n          destruct H5 as [k H5]. exists k. rewrite (restrictSmallest A n k);\n          try assumption. exists k. destruct H5 as [H5 H6]. assumption.\n        + exists m. split; try assumption. intros k H4.\n          assert (k = S n) as H5. \n            { apply le_antisym.\n                { apply H1. assumption. }\n                { destruct (leqDec k n) as [H5|H5].\n                    { exfalso. apply H3. exists k. split; assumption. }\n                    { apply not_le_ge. assumption. }}}\n          rewrite H5. apply H1. assumption. \nDefined.\n\nTheorem nonEmptyHasSmallest : forall (A:Subset),\n    pWec A                   ->\n    (exists (k:nat), k :: A) ->\n    (exists (k:nat), SmallestOf A k).\nProof.\n    intros A W [k H1]. \n    assert (exists (m:nat), SmallestOf (restrict k A) m) as H2.\n    { apply nonEmptyFiniteHasSmallest.\n        { apply restrictWec. assumption. }\n        { exists k. split; try assumption. apply le_n. }\n        { apply restrictFinite. }}\n    destruct H2 as [m H2]. exists m. \n    apply restrictSmallest in H2; try assumption. exists k. \n    split; try assumption. apply le_n.\nDefined.\n\n\n(* If a subset is computationally decidable, then so is the predicate which     *)\n(* expresses the fact that a natural number is its smallest element.            *)\nLemma DecSmallest : forall (A:Subset), pDec A -> pDec (SmallestOf A).\nProof.\n    intros A H1 n. destruct n as [|n]. \n    - destruct (H1 0) as [H2|H2]. \n        + left. split; try assumption. intros m H3. apply le_0_n.\n        + right. intros [H3 H4]. apply H2. assumption.\n    - remember (boundedDec A H1 n) as H2 eqn:E. clear E. destruct H2 as [H2|H2].\n        + right. intros [H3 H4]. destruct H2 as [m [H2 H5]].\n          apply not_le_Sn_n with n. apply le_trans with m; try assumption.\n          apply H4. assumption.\n        + destruct (H1 (S n)) as [H3|H3].\n            { left. split; try assumption. intros m H4.\n              destruct (leqDec m n) as [H5|H5].\n                { exfalso. apply H2. exists m. split; assumption. }\n                { apply not_le_ge. assumption. }}\n            { right. intros [H4 H5]. apply H3 in H4. contradiction. }\nDefined.\n\n(* Function which given a subset, a proof of it computational decidability,     *)\n(* a proof of its non-emptiness, returns its smallest element.                  *)\nDefinition smallestOf (A:Subset) (p:pDec A) (q:exists (k:nat), k :: A) : nat :=\n    proj1_sig \n        (witness \n            (SmallestOf A) \n            (DecSmallest A p) \n            (nonEmptyHasSmallest A (pDecWec nat A p) q)).\n\n\nLemma smallestOfSound : \n    forall (A:Subset) (p:pDec A) (q:exists (k:nat), k :: A),\n        SmallestOf A (smallestOf A p q).\nProof.\n    intros A p q. exact (\n        proj2_sig \n            (witness \n                (SmallestOf A) \n                (DecSmallest A p) \n                (nonEmptyHasSmallest A (pDecWec nat A p) q))).\nDefined.\n\n(*\nDefinition ex1 : Subset := fun n => n * n = 144.\n\nLemma ex1Dec : pDec ex1.\nProof.\n    unfold ex1. intros n. exact (eqDec (n*n) 144).\nDefined.\n\nLemma ex1NonEmpty : exists (k:nat), k :: ex1.\nProof.\n    exists 12. reflexivity.\nDefined.\n\nCompute smallestOf ex1 ex1Dec ex1NonEmpty.\n*)\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/Logic/Nat/Subset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6870962235752541}}
{"text": "From Tealeaves Require Export\n  Classes.Decorated.Functor\n  Classes.Decorated.Monad\n  Classes.Listable.Functor\n  Classes.Listable.Monad.\n\nImport Monoid.Notations.\nImport List.ListNotations.\n\n#[local] Generalizable Variables W F A.\n\n(** * Decorated listable functors *)\n(******************************************************************************)\n\n(** ** Derived operation [tolistd] *)\n(******************************************************************************)\nDefinition tolistd F `{Decorate W F} `{Tolist F} {A} : F A -> list (W * A)\n  := tolist F ∘ dec F.\n\n(** ** General properties *)\n(******************************************************************************)\nSection ListableFunctor_decorated_theory.\n\n  Context\n    `{Monoid W}\n    `{Fmap F} `{Decorate W F} `{Tolist F}\n    `{! DecoratedFunctor W F}\n    `{! ListableFunctor F}.\n\n  (** ** Interaction between [tolistd] and [dec] *)\n  (******************************************************************************)\n  Theorem tolistd_dec {A} :\n      tolistd F ∘ dec F (A:=A) = fmap list (cojoin (prod W)) ∘ tolistd F.\n  Proof.\n    intros. unfold tolistd.\n    reassociate ->.\n    rewrite (dfun_dec_dec W F).\n    reassociate <-.\n    rewrite <- natural.\n    reflexivity.\n  Qed.\n\n  (** ** Corollaries: [tolist] and [dec] *)\n  (******************************************************************************)\n  Theorem tolist_dec {A} :\n      tolist F ∘ dec F (A:=A) = tolistd F.\n  Proof.\n    reflexivity.\n  Qed.\n\n  (** ** Corollaries: [tolistd] and [fmap] *)\n  (******************************************************************************)\n  Theorem tolistd_fmap {A B} : forall (f : A -> B),\n      tolistd F ∘ fmap F f = fmap list (fmap (prod W) f) ∘ tolistd F.\n  Proof.\n    intros. unfold tolistd.\n    reassociate <-.\n    rewrite natural.\n    reassociate -> on right.\n    change (fmap F (fmap (prod W) ?f)) with (fmap (F ∘ prod W) f).\n    rewrite (natural (ϕ := @dec W F _)).\n    reflexivity.\n  Qed.\n\nEnd ListableFunctor_decorated_theory.\n\n(*\n\nBelow needs Kleisli-style presentation of decorated functors\n\n(** ** General properties *)\n(******************************************************************************)\nSection ListableFunctor_decorated_theory.\n\n  Context\n    `{Monoid W}\n    `{Fmap F} `{Decorate W F} `{Tolist F}\n    `{! DecoratedFunctor W F}\n    `{! ListableFunctor F}.\n\n  #[local] Set Keyed Unification.\n\n  (** ** Interaction between [tolistd] and [fmapd] *)\n  (******************************************************************************)\n  Theorem tolistd_fmapd {A B} : forall (f : W * A -> B),\n      tolistd F ∘ fmapd F f = fmap list (cobind (prod W) f) ∘ tolistd F.\n  Proof.\n    intros. unfold fmapd, tolistd.\n    reassociate <- on left; reassociate <- on right.\n    change_left (tolist F ∘ (dec F ∘ fmap F f ∘ dec F)).\n    rewrite <- (natural (G := F ∘ prod W)).\n    reassociate <- on left. unfold_ops @Fmap_compose.\n    reassociate <- on left. rewrite <- (natural (F := F)).\n    reassociate -> on left. rewrite (dfun_dec_dec W F).\n    change_left (fmap list (fmap (prod W) f) ∘ (tolist F ∘ fmap F (cojoin (prod W))) ∘ dec F).\n    rewrite <- natural.\n    reassociate <- on left. rewrite (fun_fmap_fmap list).\n    reflexivity.\n  Qed.\n\n  (** ** Corollaries: [tolist] and [fmapd] *)\n  (******************************************************************************)\n  Theorem tolist_fmapd {A B} : forall (f : W * A -> B),\n      tolist F ∘ fmapd F f = fmap list f ∘ tolistd F.\n  Proof.\n    intros. unfold fmapd, tolistd.\n    reassociate <- on left; reassociate <- on right.\n    now rewrite <- natural.\n  Qed.\n\n  (** ** Corollaries: [tolistd] and [fmap] *)\n  (******************************************************************************)\n  Theorem tolistd_fmap {A B} : forall (f : W * A -> B),\n      tolistd F ∘ fmap F f = fmap list (fmap (prod W) f) ∘ tolistd F.\n  Proof.\n    intros. unfold fmapd, tolistd.\n    reassociate -> on left. rewrite <- (natural (G := F ∘ prod W)).\n    reassociate <- on left. unfold_ops @Fmap_compose.\n    now rewrite <- (natural (F := F) (G := list)).\n  Qed.\n\n  #[local] Unset Keyed Unification.\n\nEnd ListableFunctor_decorated_theory.\n*)\n\n(** * Decorated listable monads *)\n(******************************************************************************)\n\n(** ** Interaction between [tolistd], [join], and [ret] *)\n(******************************************************************************)\nSection ListableMonad_tolistd.\n\n  Context\n    (T : Type -> Type)\n    `{Monoid W}\n    `{Fmap T} `{Decorate W T} `{Tolist T}\n    `{Return T} `{Join T}\n    `{! DecoratedMonad W T}\n    `{! ListableMonad T}\n    {A B : Type}.\n\n  Implicit Types (w : W) (a : A) (b : B) (t : T A).\n\n  Theorem tolistd_ret : forall a,\n      tolistd T (ret T a) = [ (Ƶ, a) ].\n  Proof.\n    introv. unfold tolistd, compose.\n    compose near a on left. rewrite (dmon_ret W T).\n    unfold compose. compose near (Ƶ, a) on left.\n    now rewrite (lmon_ret T).\n  Qed.\n\n  Lemma tolistd_join1 :\n    tolist T ∘ fmap T (tolist T ∘ shift T (A := A)) =\n    fmap list (shift list) ∘ tolist T ∘ fmap T (fmap (prod W) (tolist T)).\n  Proof.\n    unfold shift. reassociate <-.\n    rewrite <- (fun_fmap_fmap list).\n    reassociate -> near (tolist T).\n    rewrite (natural (ϕ := @tolist T _)).\n    reassociate <-. reassociate -> near (fmap T (fmap (prod W) (tolist T))).\n    rewrite (fun_fmap_fmap T).\n    replace (strength list ∘ fmap (prod W) (tolist T))\n      with (tolist T ∘ strength T (A := W) (B := W * A)).\n    rewrite <- (fun_fmap_fmap T).\n    rewrite <- (fun_fmap_fmap T _ _ _ (strength T)).\n    do 2 reassociate <-. fequal.\n    rewrite (natural (ϕ := @tolist T _)).\n    reassociate -> on right; rewrite (fun_fmap_fmap T). fequal.\n    fequal. now rewrite (natural (ϕ := @tolist T _)).\n    ext [w t]; unfold compose; cbn. compose near t.\n    now rewrite (natural (ϕ := @tolist T _)).\n  Qed.\n\n  Theorem tolistd_join : forall (t : T (T A)),\n      tolistd T (join T t) = join list (fmap list (shift list) (tolistd T (fmap T (tolistd T) t))).\n  Proof.\n    introv. unfold tolistd, compose.\n    compose near t on left. rewrite (dmon_join W T).\n    unfold compose. compose near (fmap T (shift T) (dec T (fmap T (dec T) t))) on left.\n    rewrite (lmon_join T). unfold compose.\n    compose near (dec T (fmap T (tolist T ○ dec T) t)) on right.\n    change (tolist T ○ dec T) with (tolist T ∘ dec T (A:=A)).\n    rewrite <- (fun_fmap_fmap T). unfold compose.\n    compose near (fmap T (dec T) t) on right.\n    rewrite <- (natural (ϕ := @dec W T _)). unfold compose.\n    unfold_ops @Fmap_compose. fequal. compose near (dec T (fmap T (dec T) t)).\n    rewrite (fun_fmap_fmap T).\n    compose near (dec T (fmap T (dec T) t)).\n    now rewrite tolistd_join1.\n  Qed.\n\nEnd ListableMonad_tolistd.\n", "meta": {"author": "dunnl", "repo": "tealeaves", "sha": "8dd6ba8acdd097f6e474ae2a1a9b10f5cc9ca65b", "save_path": "github-repos/coq/dunnl-tealeaves", "path": "github-repos/coq/dunnl-tealeaves/tealeaves-8dd6ba8acdd097f6e474ae2a1a9b10f5cc9ca65b/Tealeaves/Classes/Decorated/Listable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6870962218076027}}
{"text": "(** Complements on lists\n\n   Pierre Castéran, Univ. Bordeaux and LaBRI *)\n\n\nFrom Coq  Require Export List Arith Relations Lia.\nRequire Import Sorting.Sorted  Compare_dec  Sorting.Sorted.\n\n(** *  Sets of natural numbers as lists *)\n\n\n(** ** Definitions *)\n\n\n(** numbers from i to i+n-1  *)\n\nFixpoint iota_from i n :=\n  match n with 0 => nil\n            | S p =>  i :: iota_from (S i) p\n  end.\n\nDefinition interval i j := iota_from i (S j - i).\n\nDefinition bounded_by (n:nat)(s: list nat) :=\n  List.Forall (fun i => i<=n)%nat s.\n\n(*  shift and unshift lists of nats *)\n\nDefinition shift (l: list nat) := List.map S l.\n\nFixpoint unshift (l : list nat) : list nat :=\n  match l with\n      nil => nil\n    | 0 :: l' => unshift l'\n    | S i :: l' => i :: unshift l'\n  end.\n\n (** sorted list of elements greater or equal than n *)\n\nInductive sorted_ge (n: nat) : list nat -> Prop :=\n| sorted_ge_nil : sorted_ge n nil\n| sorted_ge_one : forall p, n<=p -> sorted_ge n (p::nil)\n| sorted_ge_cons: forall p q s,\n    n <= p -> p < q -> sorted_ge p (q::s) ->\n    sorted_ge n (p::q::s).\n\n\n(** simpler than StdLib's last *)\n\nFixpoint simple_last {A} (x:A) s :=\n  match s with\n      nil => x\n    | i::s' => simple_last  i s'\n  end.\n\n(** the list (x::s) without its last item *)\n\nFixpoint but_last {A:Type}(x:A) (s : list A) :=\n  match s with\n  | nil => nil\n  | y::s' => x :: but_last  y s' \n  end.\n\n\n\nLemma but_last_iota_from : forall l i,\n      but_last i (iota_from (S i) (S l)) = i::iota_from (S i) l.\ninduction l; simpl. \nreflexivity. \nintros.\nrepeat f_equal.\nsimpl.\nspecialize (IHl (S i)).\nsimpl in IHl.\ninjection IHl. intros. rewrite H. auto.\nQed.\n\n\nLemma interval_length i j : length (interval i j) = S j - i.\nProof.\n  unfold interval.\n generalize (S j - i). intro.   revert i.\n induction n; simpl; auto.\nQed.\n\nLemma but_last_interval i j:\n  i < j ->\n  but_last i (interval (S i) (S j)) = i:: interval (S i) j.        \nProof.\n  intros.\n  unfold interval.    \n  specialize (but_last_iota_from (S j - S i) i).\n intro.\n  replace (S (S j) - S i) with (S (S j - S i)).\n  replace (S j) with (i + S (S j - S i)) at 3.\n 2: lia.\n\n  2:lia.\n auto.\nQed.\n\n\nLemma but_last_shift'   s : forall x,\n     but_last (S x) (shift  s) = shift (but_last x s).\nProof.\n  induction s; cbn.\n  - auto.\n  - intros;f_equal.  rewrite IHs.  cbn;  reflexivity.\nQed.\n\n\nLemma unshift_but_last   s : forall x,\n    ~ In 0 (x::s) ->\n    unshift (but_last  x s) = but_last (Nat.pred x) (unshift s).\nProof.\n  induction s; cbn.\n  - auto.\n  - intros;f_equal. destruct x.\n    destruct H; auto.\n    simpl.\n    specialize (IHs  a).  simpl in IHs.\n     destruct a.\n      destruct H; auto.\n     simpl.\n     simpl in IHs.\n      f_equal.\n    apply IHs.\n    tauto.\nQed.\n\nLemma unshift_app : forall s t,  unshift (s ++ t) = unshift s ++ unshift t.\nProof.\n  induction s; cbn.\n  - reflexivity.\n  - intro; destruct a; auto.\n    now rewrite (IHs t).\nQed.\n\n\nLemma unshift_not_nil : forall s, ~ In 0 s -> s <> nil -> unshift s <> nil.\nProof.\n  destruct  s.  \n  - destruct 2; auto.\n  - cbn. destruct n.\n     + destruct 1; now left.\n     +  discriminate.\n Qed.\n\n\nLemma but_last_app {A} : forall s (x:A),\n  but_last x s ++  simple_last x s :: nil = x::s.\nProof.\n  induction s; simpl; auto.\n  intros; simpl; now rewrite IHs.\nQed.\n\n(* useful ??? *)\nLemma but_last_iota_from' j : forall i, but_last i (iota_from (S i) (S j)) =\n                                       iota_from i (S j). \n intros; rewrite but_last_iota_from.\n reflexivity.\nQed.\n\n\nDefinition ptwise_le: list nat -> list nat -> Prop := Forall2 le.\n\n(** ** Lemmas *)\n\nLemma empty_interval i j : (j < i)%nat -> interval i j = nil.\nProof.\n unfold interval.\n  intro H; replace (S j - i)%nat with 0.\n  reflexivity.\n  abstract lia.\nQed.\n\nLemma shift_iota_from : forall i l,  shift (iota_from i l) = iota_from (S i) l.\nProof.\n  intros i l; revert i;induction l.\n  - trivial.\n  - cbn; intro; now rewrite IHl.\nQed.\n\nLemma shift_interval (i j: nat): shift (interval i j) = interval (S i) (S j).\nProof.\n  unfold interval; rewrite shift_iota_from; f_equal.\nQed.\n\nLemma unshift_iota_from : forall i l,  unshift (iota_from (S i) l) =\n                                       iota_from i l.\nProof.\n  intros i l; revert i;induction l.\n  - trivial.\n  - cbn. intro; now rewrite IHl.\nQed.\n\nLemma unshift_interval (i j: nat): unshift (interval (S i) (S j)) =\n                                   interval  i  j.\nProof.\n unfold interval;rewrite unshift_iota_from;f_equal.\nQed.\n\nLemma unshift_interval_pred (i j:nat) : 0 < j ->\n  unshift (interval (S i) j) = interval i (Nat.pred j).\n  Proof.\n    destruct j.\n   inversion 1.\n   intro; simpl.\n   now   rewrite unshift_interval.\n  Qed.\n  \nLemma shift_no_zero l : ~ In 0 (shift l).\nProof.\n  induction l; destruct 1; [discriminate | auto].\nQed.\n\n\n\nLemma shift_unshift l : unshift (shift l) = l.\nProof.\n  induction l; simpl in *; [trivial | now rewrite IHl].\nQed.\n\nLemma unshift_shift l (H: ~ In 0 l): shift (unshift l) = l.\nProof.\n  induction l.\n- reflexivity.\n- simpl. destruct a.\n contradiction H; now left.\n  simpl;  rewrite IHl; auto.\n  intro; apply H; now right.\nQed.\n\nLemma unshift_pred : forall (s: list nat),  ~ In 0 s ->\n                                            unshift s = List.map Nat.pred s.\nProof.\ninduction s.\n -  trivial.\n -  destruct a.\n   +   destruct 1; now  left.\n   +  simpl;  intro;  rewrite IHs; auto.\n Qed.\n\n \nLemma sorted_ge_Forall (n:nat) : forall l, sorted_ge n l ->\n                                           Forall (fun x =>  n <= x) l.\nProof.\n  induction 1.\n  - left.\n  - now right.\n  - right.\n   + assumption.\n   +  eapply Forall_impl  with (P := (fun x: nat => p <= x)); [|trivial].\n     intros; abstract lia.\nQed.\n\n\nLemma sorted_ge_trans n p l : n <= p -> sorted_ge p l -> sorted_ge n l.\ninduction 2.  \n- constructor 1.\n- constructor 2; eauto with arith.\n- constructor 3; [eauto with arith |assumption | assumption].\nQed.\n\n\nLemma sorted_ge_not_In (n:nat) : forall l, sorted_ge (S n) l ->\n                                           ~ In n l.\nProof.\n intros l H; generalize (sorted_ge_Forall _ _ H); intros H0 H1.\n rewrite Forall_forall in H0. generalize (H0 n).\n intro H2; generalize (H2 H1). \n abstract lia.\nQed.\n\n\n\n#[global] Hint Constructors sorted_ge : lists.\n\n\nLemma sorted_inv_gt : forall n p s, sorted_ge n (p::s) ->\n                                    (p < n)%nat -> False.\nProof.\n inversion_clear 1 ; intro;abstract lia.\nQed.\n\nLemma iota_from_app n p :\n  iota_from n (S p) = iota_from n p ++ (n+p::nil)%nat.\nProof.\n  revert n; induction p; simpl.\n  -  intros; f_equal; abstract lia.\n  -  intros;  f_equal; replace (n + S p)%nat with (S n + p)%nat.\n     +  rewrite  <- IHp; auto.\n     +  abstract lia.\nQed.\n\nLemma iota_from_plus : forall k i j, iota_from i (k+j) =\n                                     iota_from i k ++ iota_from (k+i) j.\nProof.\n  induction k; simpl.\n  - trivial.    \n  - intros; rewrite IHk; repeat  f_equal; abstract lia.\nQed.\n\nLemma interval_not_empty : forall i j, i <= j -> interval i j <> nil.\nProof.\n  induction 1.\n  - unfold interval.\n    case_eq (S i -  i).\n    + intro; abstract lia.\n    + simpl. destruct i; discriminate.\n  -  cbn.\n     destruct i.\n     cbn; discriminate.\n     destruct i; cbn.\n     discriminate.\n     case_eq (m - i).\n     intro; abstract lia.\n     cbn; discriminate.\nQed.\n\nLemma interval_not_empty_iff (n p : nat) :\n  interval n p <> nil <-> (n <= p)%nat.\nProof.\n  split.\n  - intro H; destruct (le_lt_dec n p); [trivial| ].\n\n   apply empty_interval in l.\n   contradiction.\n    - apply interval_not_empty.\nQed.\n\nLemma interval_singleton (i:nat) : interval i i = i::nil.\nProof.\n  unfold interval; replace (S i - i) with 1;  [reflexivity | lia].\nQed.\n\nLemma interval_app (i j k:nat):\n  (i <= j)%nat -> (j <= k)%nat ->\n  interval i k = interval i j ++ interval (S j) k.\nProof.\n  unfold interval;intros.\n  replace (S k - i)%nat with ((S j - i) + (S k - S j))%nat.\n  - rewrite iota_from_plus;repeat f_equal; lia.\n  - abstract lia.\nQed.\n\nLemma iota_from_unroll i l : iota_from i (S l) = i :: iota_from (S i) l.\nProof. reflexivity. Qed.\n\nLemma interval_unroll : forall i j:nat , (i < j)%nat ->\n                                       interval i j = i :: interval (S i) j.\nProof.\n  intros.\n  change (interval i j = (i :: nil) ++ interval (S i) j).\n  replace (i::nil) with (interval i i).\n  rewrite  interval_app with i i j.\n  reflexivity.\n  auto with arith.\n  auto with arith.\n  unfold interval.\n  replace (S i - i)%nat with 1.\n  reflexivity.\n  abstract lia.\nQed.\n\n\nLemma iota_from_sorted_ge : forall p n q : nat,\n    (q <= n)%nat  ->\n    sorted_ge q (iota_from n p).\nProof.\n  induction p.  \n  - constructor.\n  - simpl; destruct p.\n     + constructor 2 ; auto.\n     +  simpl; simpl in IHp;  constructor 3; auto.\nQed.\n\nLemma interval_sorted_ge: forall p n q : nat,  (q <= n)%nat ->\n                                                sorted_ge q (interval n p).\n unfold interval; intros; now apply iota_from_sorted_ge.\nQed.\n\nLemma iota_from_lt_not_In i j l : i < j -> ~ In i (iota_from j l).\nProof.\n   intros; generalize (iota_from_sorted_ge l j (S i) H ).\n   intros; now apply sorted_ge_not_In.\nQed.\n\nLemma interval_lt_not_In :\n  forall i j k,  i < j -> ~ In i (interval j k).\nProof.\n  intros; unfold interval; now apply iota_from_lt_not_In.\nQed.\n\n\nSection Forall2_right_induction.\n\nInductive Forall2R {A B: Type} (R: A -> B -> Prop) : list A -> list B -> Prop :=\n  Forall2R_nil : Forall2R R nil nil\n| Forall2R_last : forall l l' x y l1 l'1, Forall2R R l l' ->\n                                          R x y ->\n                                          l1 = l++(x::nil) ->\n                                          l'1 = l' ++ (y::nil) ->\n                                          Forall2R R l1 l'1.\n\nRemark Forall2R_cons {A B: Type} (R: A -> B -> Prop):\n  forall l l',  Forall2R R l l' -> forall x y, R x y -> Forall2R R (x::l) (y:: l').\n  induction 1.\n  - intros.\n    eright with nil nil x y ; auto.\n    left.          \n  -  intros; subst;  right with (x0::l) (y0::l') x y; auto.\nQed. \n\n     \nRemark Forall2_R  {A B: Type} (R: A -> B -> Prop) :\n  forall l l', Forall2 R l l' -> Forall2R R l l'.\n  induction 1.\n  - constructor. \n  - inversion IHForall2.\n     + eright with nil nil x y;auto.\n       now left.     \n     + subst; apply Forall2R_cons; auto.\nQed.\n\n\nRemark Forall2_RR  {A B: Type} (R: A -> B -> Prop) :\n  forall l l', Forall2R R l l' -> Forall2 R l l'.\nProof.\n  induction 1.\n  - constructor. \n  - subst; apply Forall2_app; auto.\nQed.\n\nLemma Forall2R_iff {A B: Type} (R: A -> B -> Prop) :\n  forall l l', Forall2R R l l' <-> Forall2 R l l'.\nProof. \n  split.\n  - intro;now  apply Forall2_RR .\n  - intro;now  apply Forall2_R .\nQed. \n\n\nLemma Forall2_indR {A B : Type} (R : A -> B -> Prop) (P : list A -> list B -> Prop):\nP nil nil ->\n(forall (l : list A) (l' : list B) (x : A) (y : B) \n   (l1 : list A) (l'1 : list B),\n Forall2 R l l' -> P l l' ->\n R x y -> l1 = l ++ x :: nil -> l'1 = l' ++ y :: nil -> P l1 l'1) ->\n  forall (l : list A) (l0 : list B), Forall2 R l l0 -> P l l0.\nProof. \n  intros; rewrite  <- Forall2R_iff in  H1.\n  eapply Forall2R_ind; eauto.\n  intros; subst.\n  eapply H0 with l1 l' x y; auto.  \n  now  rewrite  <- Forall2R_iff .\nQed.    \n\nEnd  Forall2_right_induction.\n\n\n\n\n\n\nLemma sorted_le : forall i j X, i <= j ->\n                                sorted_ge j X ->\n                                sorted_ge i X.\nProof.\n  induction 2; eauto with arith lists. \nQed.\n\n\n\n  \nLemma sorted_tail : forall i j X, sorted_ge i (j::X) ->\n                                  sorted_ge i X.\nProof.   \n  inversion 1.\n  -   constructor.\n  -   destruct s; auto. \n      all:  inversion H4;eauto with arith lists.\nQed.\n\nLemma sorted_tail' : forall i j X, sorted_ge i (j::X) ->\n                                   sorted_ge j X.\nProof.\n  inversion_clear  1; auto with lists.\nQed. \n\nLemma sorted_head : forall n m s, sorted_ge n (m::s)\n                                  -> n<=m.\nProof.\n  induction s. \n  - inversion 1; auto. \n  - inversion_clear 1.\n    apply IHs.\n  inversion_clear H2.   \n  +   constructor; auto with arith.\n  +  constructor; eauto with arith.\n     eapply sorted_le;eauto.\nQed.\n\n\n\nLemma Sorted_mono {A:Type}(R S : relation A)\n      (Hincl : forall x y, R x y -> S x y):\n  forall l, Sorted R l -> Sorted S l.\nProof.   \n  induction 1; auto. \n  constructor; auto. \n  destruct H0;auto. \nQed.\n\n\n\nLemma sorted_ge_iff0 : forall l n, sorted_ge n l <->\n                                    LocallySorted Peano.lt l /\\\n                                    List.Forall (fun i => n <= i) l.\nProof.\n  induction l.\n  - split; auto with lists.\n    split; auto with lists; constructor.\n  - destruct l.    \n    + split.\n      * split; auto with lists.\n        constructor.\n        constructor.        \n        eapply  sorted_head; eauto.\n        constructor.    \n      *   destruct 1;  constructor;  inversion H0;auto.\n    +  repeat  split.\n      *  inversion_clear H; auto.     \n         rewrite IHl in H2.\n         constructor;tauto.\n      *   inversion_clear H.\n          rewrite IHl in H2.\n          constructor; auto.\n          destruct H2.\n          eapply Forall_impl.\n          2:eapply H2.\n          intros;   transitivity a.\n          auto. \n          apply H3.\n      *  destruct 1.\n         constructor.\n           inversion_clear H0; auto. \n           inversion_clear H; auto.\n           inversion_clear H.\n           rewrite IHl.\n           split; auto.\n           constructor;  auto with arith.\n           apply Sorted_extends.\n           intros x y z Hxy Hyz.\n           eauto with arith.\n           apply Sorted_mono with Peano.lt.\n           eauto with arith. \n           rewrite <- Sorted_LocallySorted_iff in H1.\n           inversion_clear H1.\n           constructor;auto.\n           induction H3.\n           constructor.\n           constructor. \n           eauto with arith. \nQed. \n\nLemma sorted_ge_iff : forall l n, sorted_ge n l <->\n                                    Sorted lt l /\\\n                                    List.Forall (fun i => n <= i) l.\nProof.  \n intros.\n rewrite Sorted_LocallySorted_iff.\n apply sorted_ge_iff0.\nQed.\n\n\nLemma sorted_ge_prefix :\n  forall  l1 n l2, sorted_ge n (l1 ++ l2) -> sorted_ge n l1.\n  induction l1.\n  - constructor.\n  - \n    destruct l1.\n    constructor.\n    cbn in H.\n    eapply sorted_head; eauto.\n    constructor.\n    cbn in H.\n    eapply sorted_head; eauto.\n    inversion_clear H.\n    auto. \n    eapply IHl1.\n    inversion_clear H.\n    eauto. \nQed. \n\n\nLemma sorted_In : forall i X, Sorted lt (i::X) -> forall j, In j X -> i < j.\nProof.\n  intros.\n  apply Sorted_StronglySorted in H.\n  apply StronglySorted_inv in H.\n  destruct H.\n  rewrite Forall_forall in H1.\n  auto.\n  red. \n  intros; abstract lia.\nQed.\n\nLemma sorted_not_in_tail : forall  i j X, Sorted lt (i::X)   -> j<=i ->\n                                           ~ (In j X).\nProof.\n intros. \n red; intro. \n specialize (sorted_In _ _ H j H1).\n intro; abstract lia.\nQed.\n\nRemark simple_last_correct {A}: forall s (x:A), simple_last x s = last s x.\n  induction s. \n  - now cbn.\n  -  cbn.   \n     destruct s.\n     now cbn.\n     auto.\nQed.\n\nLemma In_sorted_ge_inv : forall x y s,\n                             In x (y::s) ->\n                             sorted_ge y s ->\n                             y < x /\\ In x s \\/ y = x.\nProof.\n  intros x y s H H0;  destruct H.\n  -    subst; auto. \n  -  destruct (lt_eq_lt_dec x y) as [[H1 | H2] | H3].\n   +  rewrite   sorted_ge_iff in H0;  destruct H0.\n     rewrite Forall_forall in H2;  specialize (H2 x H). \n    cut False; [contradiction | abstract lia ]. \n   +  subst; auto. \n   +  auto. \nQed. \n\n\nLemma incl_inv : forall x y l1 l2,  Sorted lt (x::l1) ->\n                                    Sorted lt (y::l2)  ->\n                                    incl (x::l1)(y::l2) ->\n                                    y <= x /\\ incl l1 l2.\nProof. \n  intros.\n  red in H1.\n  assert (y <= x).\n  {\n    specialize (H1 x (in_eq x  l1)).   \n    destruct H1.\n    subst; auto with arith.   \n\n    specialize (sorted_In _ _ H0 _ H1).\n    auto with arith.\n  }   \n  split;auto.\n  intros z Hz.\n  assert (x < z). {\n\n    specialize (sorted_In _ _ H _ Hz).\n    auto.\n  }\n  assert (y < z).\n  eauto with arith. \n\n  specialize (H1 z).\n  destruct H1.\n  right;auto.\n  subst.\n  assert (F: False) by abstract lia; elim F. \n  auto.\nQed.\n\n\nLemma incl_decomp : forall l1 l2,  Sorted lt l1 ->\n                                   Sorted lt l2  ->\n                                   incl l1 l2 ->\n                                   exists l3 l4,  l2 = l3 ++ l4 /\\\n                                                  ptwise_le l3 l1.\n  induction l1.\n  intros; exists nil, l2.\n  split.\n  reflexivity.\n  constructor.\n  destruct l2.\n  intros.\n  red in H1.\n  destruct (H1 a) ;auto.\n  now left.\n  intros.   \n  destruct (incl_inv a n l1 l2);auto.\n  destruct (IHl1 l2).\n  now inversion_clear H.\n  now inversion_clear H0.\n  auto. \n  destruct H4 as [l4 [H5 H6]].\n  subst.\n  exists (n::x), l4.\n  split;auto. \n  constructor.\n  auto.\n  \n  auto.\nQed.\n\n\n  Lemma simple_last_app {A}: forall l l1 (x y:A), simple_last x (l++(y::l1))  =\n                                     simple_last y l1 .\n  induction l; cbn.\n  - reflexivity.     \n  - intros; now rewrite IHl.\nQed.\n\n\nLemma simple_last_app1 {A}: forall l (x y:A), simple_last x (l++(y::nil))  = y.\nProof.\n  intros; now rewrite simple_last_app. \nQed.\n\n\nLemma sorted_max_1 : forall s n, sorted_ge n s ->\n                                 (n <= simple_last n s)%nat.\n  induction s; cbn.\n  - auto with arith. \n  -  intros; destruct s.\n    + now inversion_clear H.\n    + inversion_clear H; transitivity a; auto.  \nQed.\n\n\nLemma sorted_cut :forall l1 n x l2, sorted_ge n (l1++(x::l2)) ->\n                                    simple_last n l1 <= x.\n  induction l1.\n  - cbn;  eapply sorted_head; eauto. \n  - cbn; intros; eapply IHl1 with l2.\n    cbn in H;    inversion_clear H; auto with lists.\nQed.\n\nLemma sorted_max_2 : forall s n, sorted_ge n s ->\n                                 Forall (fun i =>\n                                           (i <= simple_last n s)%nat)\n                                        s.\nProof.\n  induction s; cbn.\n  - intros; simpl; constructor.\n  -     constructor.\n       +  apply sorted_max_1; inversion H;auto with lists. \n       + apply IHs; eapply sorted_tail'; eauto with lists.\nQed. \n\n\nLemma sorted_ge_suffix :\n  forall  l1 n l2, sorted_ge n (l1 ++ l2) -> sorted_ge (simple_last n l1) l2.\n  induction l1.\n  -  intros; cbn. assumption. \n  -  destruct l1.\n    + cbn; inversion_clear 1; auto with lists.\n    + inversion_clear 1; cbn in *; eauto with lists.\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/MoreLists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.6870443990786084}}
{"text": "Require Import Znumtheory .\nRequire Import Zdiv .\nRequire Import ZArith .\nImport Z .\n\nSection SimpleChineseRemainder .\n\nOpen Scope Z_scope .\n\nDefinition modulo (a b n : Z) : Prop := (n | (a - b)) .\nNotation \"( a == b [ n ])\" := (modulo a b n) .\n\nLemma modulo_tran : forall a b c n : Z, \n    (a == b [ n ]) -> (b == c [ n ]) -> (a == c [ n ]) .\nProof.\n  intros a b c n Hab Hbc .\n  red in Hab, Hbc |- * .\n  cut (a - c = a - b + (b - c)) .\n  - intros H .\n    rewrite H .\n    apply Zdivide_plus_r .\n    + trivial .\n    + trivial .\n  - auto with * .\nQed.\n\nLemma modulo_plus_subst : forall a b c n : Z,\n    (a == b [ n ]) -> (a + c == b + c [ n ]) .\nProof.\n  (* to be done *)\n  intros a b c n Hab.\n  red in Hab |- *.\n  cut (a + c - (b + c) = a - b).\n  - intros H.\n    rewrite H.\n    trivial.\n  - auto with *.\nQed.\n\nLemma modulo_mult_subst : forall a b c n : Z,\n    (a == b [ n ]) -> (a * c == b * c [ n ]) .\nProof.\n  (* to be done *)\n  intros a b c n Hab.\n  red in Hab |- *.\n  cut (a * c - b * c = (a - b) * c).\n  - intros H.\n    rewrite H.\n    apply Zdivide_mult_l.\n    trivial.\n  - auto with *.\nQed.\n\nLemma modulo_plus_multiple_of_n : forall a b c m n : Z,\n    (a * m + b * n == c[ n ]) <-> (a * m == c [ n ]).\nProof.\n  intros a b c m n.\n  unfold iff.\n  split.\n  (* (a * m + b * n == c[ n ]) -> (a * m == c [ n ]) *)\n  - intros Hambnc.\n    red in Hambnc |- *.\n    apply divide_add_cancel_r with (m := b * n).\n    + apply Zdivide_factor_l.\n    + cut (b * n + (a * m - c) = a * m + b * n - c).\n    * intros H.\n      rewrite H.\n      trivial.\n    * auto with *.\n  (* (a * m == c [ n ]) -> (a * m + b * n == c[ n ]) *)\n  - intros Hamc.\n    red in Hamc |- *.\n    cut (a * m + b * n - c = a * m - c + b * n).\n    + intros H.\n      rewrite H.\n      apply Zdivide_plus_r.\n      * trivial.\n      * apply Zdivide_factor_l.\n    + auto with *.\nQed.\n\nHypothesis m n : Z .\nHypothesis co_prime : rel_prime m n .\n\nTheorem modulo_inv : forall m n : Z, rel_prime m n ->\n                       exists x : Z, (m * x == 1 [ n ]) .\nProof.\n  (* to be done *)\n  intros m0 n0 Hrel_prime.\n  elim (Zis_gcd_bezout m0 n0 1).\n  - intros u v Hbezout_identity.\n    exists u.\n    rewrite mul_comm.\n    apply modulo_plus_multiple_of_n with (b := v).\n    rewrite Hbezout_identity.\n    red.\n    rewrite sub_diag.\n    apply Zdivide_0.\n  - trivial.\nQed.\n\nTheorem SimpleChineseRemainder : forall a b : Z,\n  exists x : Z, (x == a [ m ]) /\\ (x == b [ n ]) .\nProof.\n  (* to be done *)\n  intros a b.\n  destruct (rel_prime_bezout _ _ co_prime) as [u v Hbezout_identity].\n  exists (a * v * n + b * u * m).\n  split.\n  (* (a * v * n + b * u * m == a [ m ]) *)\n  - apply add_move_l in Hbezout_identity.\n    rewrite <- mul_assoc.\n    rewrite Hbezout_identity.\n    cut (a * (1 - u * m) + b * u * m = a * 1 + (b * u - a * u) * m).\n    + intros H.\n      rewrite H.\n      apply modulo_plus_multiple_of_n.\n      rewrite mul_1_r.\n      red.\n      rewrite sub_diag.\n      apply Zdivide_0.\n    + auto with *.\n  (* (a * v * n + b * u * m == b [ n ]) *)\n  - apply add_move_r in Hbezout_identity.\n    rewrite add_comm.\n    rewrite <- mul_assoc.\n    rewrite Hbezout_identity.\n    cut (b * (1 - v * n) + a * v * n = b * 1 + (a * v - b * v) * n).\n    + intros H.\n      rewrite H.\n      apply modulo_plus_multiple_of_n.\n      rewrite mul_1_r.\n      red.\n      rewrite sub_diag.\n      apply Zdivide_0.\n    + auto with *.\nQed.\n\nEnd SimpleChineseRemainder .\n\nCheck SimpleChineseRemainder .", "meta": {"author": "microuzi9797", "repo": "IntroCL2020", "sha": "2b0f48a9c3a080492cc2166a46708d655c18f09b", "save_path": "github-repos/coq/microuzi9797-IntroCL2020", "path": "github-repos/coq/microuzi9797-IntroCL2020/IntroCL2020-2b0f48a9c3a080492cc2166a46708d655c18f09b/Homework4/hw2-2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6870370952018753}}
{"text": "Require Import Arith.\n\nInductive TVar : Type :=\n| tvar : nat -> TVar\n.\n\nInductive FType : Type :=\n| VarType : TVar -> FType\n| FunType : FType -> FType -> FType\n| UniType : TVar -> FType -> FType\n.\n\nDefinition tvarEqual (X Y:TVar) : bool :=\n    match X, Y with\n    | (tvar x), (tvar y)    => if (beq_nat x y) then true else false\n    end.\n\nFixpoint FTypeEqual (T T':FType) : bool :=\n    match T with\n    | VarType X     => match T' with \n                       | VarType Y     => tvarEqual X Y\n                       | _             => false\n                       end\n    | FunType T1 T2 => match T' with\n                       | FunType S1 S2 => andb (FTypeEqual T1 S1)(FTypeEqual T2 S2)\n                       | _             => false\n                       end\n    | UniType X T1  => match T' with (* equality stricter than alpha equivalence *)\n                       | UniType Y S1  => andb (tvarEqual X Y)(FTypeEqual T1 S1)\n                       | _             => false\n                       end\n    end.\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/systemF/type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6870370887144543}}
{"text": "(* Exercise 10 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_010 : (exists x : D, P x -> Q x) -> (forall x : D, P x) -> (exists x : D, Q x).\nProof.\nimp_i a1.\nimp_i a2.\nexi_e (exists x:D, P x -> Q x) a a3.\nhyp a1.\nexi_i a.\nimp_e (P a).\nhyp a3.\nall_e (forall x:D, P x) a.\nhyp a2.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred010.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896671963207, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6870370750749832}}
{"text": "Require Import PolTac.\nRequire Import NAux.\n\nOpen Scope N_scope.\n\nTheorem pols_test1: forall x y: N,  x < y ->  (x + x < y + x).\nintros.\npols.\nauto.\nQed.\n\nTheorem pols_test2: forall x y, y < 0 ->  (x + y < x).\nintros.\npols.\nauto.\nQed.\n \nTheorem pols_test4:\n forall x y,\n x * x  < y * y ->  ((x + y) * (x + y) < 2 * (x * y + y * y)).\nintros.\npols.\nauto.\nQed.\n \nTheorem pols_test5:\n forall x y z, x + y * (y + z) = 2 * z ->  2 * x + y * (y + z) = (x + z) + z.\nintros.\npols.\nauto.\nQed.\n\n\nTheorem polf_test1: forall x y, (1 <= y -> x  <= x  * y).\nintros.\npolf.\nQed.\n\nTheorem polf_test2: forall x y, 0 < x -> x  <= x  * y -> 1 <= y.\nintros.\nhyp_polf H0.\nauto.\nQed.\n\n\n\nTheorem polr_test1: forall x y z, (x + z) < y -> x + y + z < 2*y.\nintros x y z H.\npolr H.\npols.\nauto.\npols.\nauto.\nQed.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/PolTac/Nex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.7461389817407017, "lm_q1q2_score": 0.6870370711666433}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(**********************************************************************\n    EGroup.v                                \n                                                                     \n    Given an element a, create the group {e, a, a^2, ..., a^n}\n **********************************************************************)\nRequire Import ZArith.\nRequire Import Tactic.\nRequire Import List.\nRequire Import ZCAux.\nRequire Import ZArith Znumtheory.\nRequire Import Wf_nat.\nRequire Import UList.\nRequire Import FGroup.\nRequire Import Lagrange.\n\nOpen Scope Z_scope.\n\nSection EGroup.\n\nVariable A: Set.\n\nVariable A_dec: forall a b: A, {a = b} + {~ a = b}.\n\nVariable op: A -> A -> A.\n\nVariable a: A.\n\nVariable G: FGroup op.\n\nHypothesis a_in_G: In a G.(s).\n\n\n(************************************** \n  The power function for the group\n **************************************)\n \nSet Implicit Arguments.\nDefinition gpow n := match n with  Zpos p => iter_pos _ (op a) G.(e) p | _ => G.(e) end.\nUnset Implicit Arguments.\n\nTheorem gpow_0: gpow 0 = G.(e).\nsimpl; sauto.\nQed.\n\nTheorem gpow_1 : gpow 1 = a.\nsimpl; sauto.\nQed.\n\n(************************************** \n  Some properties of the power function\n **************************************)\n \nTheorem gpow_in: forall n, In (gpow n) G.(s).\nintros n; case n; simpl; auto.\nintros p; apply iter_pos_invariant with (Inv := fun x => In x G.(s)); auto.\nQed.\n\nTheorem gpow_op: forall b p, In b G.(s) -> iter_pos _ (op a) b p = op (iter_pos _ (op a) G.(e) p) b.\nintros b p; generalize b; elim p; simpl; auto; clear  b p.\nintros p Rec b Hb.\nassert (H: In (gpow (Zpos p)) G.(s)).\napply gpow_in.\nrewrite (Rec b); try rewrite (fun x y => Rec (op x y)); try rewrite (fun x y => Rec (iter_pos A x y p)); auto.\nrepeat rewrite G.(assoc); auto.\nintros p Rec b Hb.\nassert (H: In (gpow (Zpos p)) G.(s)).\napply gpow_in.\nrewrite (Rec b); try rewrite (fun x y => Rec (op x y)); try rewrite (fun x y => Rec (iter_pos A x y p)); auto.\nrepeat rewrite G.(assoc); auto.\nintros b H; rewrite e_is_zero_r; auto.\nQed.\n\nTheorem gpow_add: forall n m, 0 <= n -> 0 <= m -> gpow (n + m) = op (gpow n) (gpow m).\nintros n; case n.\nintros m _ _; simpl; apply sym_equal; apply e_is_zero_l; apply gpow_in.\n2: intros p m H; contradict H; auto with zarith.\nintros p1 m; case m.\nintros _ _; simpl; apply sym_equal; apply e_is_zero_r.\nexact (gpow_in (Zpos p1)).\n2: intros p2 _ H; contradict H; auto with zarith.\nintros p2 _ _; simpl.\nrewrite iter_pos_plus; rewrite (fun x y => gpow_op (iter_pos A x y p2)); auto.\nexact (gpow_in (Zpos p2)).\nQed.\n\nTheorem gpow_1_more: \n  forall n, 0 < n -> gpow n = G.(e) -> forall m, 0 <= m -> exists p, 0 <= p < n /\\ gpow m = gpow p.\nintros n H1 H2 m Hm;  generalize Hm; pattern m; apply Z_lt_induction; auto with zarith; clear m Hm.\nintros m Rec Hm.\ncase (Zle_or_lt n m); intros H3.\ncase (Rec (m - n)); auto with zarith.\nintros p (H4,H5); exists p; split; auto.\nreplace m with (n + (m - n)); auto with zarith.\nrewrite gpow_add; try rewrite H2; try rewrite H5; sauto; auto with zarith.\ngeneralize gpow_in; sauto.\nexists m; auto.\nQed.\n\nTheorem gpow_i: forall n m, 0 <= n -> 0 <= m -> gpow n = gpow (n + m) -> gpow m = G.(e).\nintros n m H1 H2 H3; generalize gpow_in; intro PI.\napply g_cancel_l with (g:= G) (a := gpow n); sauto.\nrewrite <- gpow_add; try rewrite <- H3; sauto.\nQed.\n\n(************************************** \n  We build the support by iterating the power function\n **************************************)\n\nSet Implicit Arguments.\n\nFixpoint support_aux (b: A) (n: nat) {struct n}: list A :=\nb::let c := op a b in\n    match n with \n       O => nil | \n      (S n1) =>if A_dec c G.(e) then nil else  support_aux c n1 \n    end.\n\nDefinition support := support_aux G.(e) (Zabs_nat (g_order G)).\n\nUnset Implicit Arguments.\n\n(************************************** \n  Some properties of the support that helps to prove that we have a group\n **************************************)\n\nTheorem support_aux_gpow: \n  forall n m b, 0 <=  m -> In b (support_aux (gpow m) n) -> \n        exists p, (0 <= p < length (support_aux (gpow m) n))%nat  /\\ b = gpow (m + Z_of_nat p).\nintros n; elim n; simpl.\nintros n1 b Hm [H1 | H1]; exists 0%nat; simpl; rewrite Zplus_0_r; auto; case H1.\nintros n1 Rec m b Hm [H1 | H1].\nexists 0%nat; simpl; rewrite Zplus_0_r; auto; auto with arith.\ngeneralize H1; case (A_dec (op a (gpow m)) G.(e)); clear H1; simpl; intros H1 H2.\ncase H2.\ncase (Rec (1 + m) b); auto with zarith.\nrewrite gpow_add; auto with zarith.\nrewrite gpow_1; auto.\nintros p (Hp1, Hp2); exists (S p); split; auto with zarith. \nrewrite <- gpow_1.\nrewrite <- gpow_add; auto with zarith.\nrewrite inj_S; rewrite Hp2; eq_tac; auto with zarith.\nQed.\n\nTheorem gpow_support_aux_not_e: \n  forall n m p, 0 <= m -> m < p < m + Z_of_nat (length (support_aux (gpow m) n)) -> gpow p <> G.(e).\nintros n; elim n; simpl.\nintros m p Hm (H1, H2); contradict H2; auto with zarith.\nintros n1 Rec m p Hm; case (A_dec (op a (gpow m)) G.(e)); simpl.\nintros _ (H1, H2); contradict H2; auto with zarith.\nassert (tmp: forall p, Zpos (P_of_succ_nat p) = 1 + Z_of_nat p).\nintros p1; apply trans_equal with (Z_of_nat (S p1)); auto; rewrite inj_S; auto with zarith.\nrewrite tmp.\nintros H1 (H2, H3); case (Zle_lt_or_eq (1 + m) p); auto with zarith; intros H4; subst.\napply (Rec (1 + m)); try split; auto with zarith.\nrewrite gpow_add; auto with zarith.\nrewrite gpow_1; auto with zarith.\nrewrite gpow_add; try rewrite gpow_1; auto with zarith.\nQed.\n\nTheorem support_aux_not_e: forall n m b, 0 <= m -> In b (tail (support_aux (gpow m) n)) -> ~ b = G.(e).\nintros n; elim n; simpl.\nintros m b Hm H; case H.\nintros n1 Rec m b Hm; case (A_dec (op a (gpow m)) G.(e)); intros H1 H2; simpl; auto.\nassert (Hm1: 0 <= 1 + m); auto with zarith.\ngeneralize( Rec (1 + m) b Hm1) H2; case n1; auto; clear Hm1.\nintros _ [H3 | H3]; auto.\ncontradict H1; subst; auto.\nrewrite gpow_add; simpl; try rewrite e_is_zero_r; auto with zarith.\nintros n2; case (A_dec (op a (op a (gpow m))) G.(e)); intros H3.\nintros _ [H4 | H4].\ncontradict H1; subst; auto.\ncase H4.\nintros H4 [H5 | H5]; subst; auto.\nQed.\n\nTheorem support_aux_length_le: forall n a, (length (support_aux a n) <= n + 1)%nat.\nintros n; elim n; simpl; auto.\nintros n1 Rec a1; case (A_dec (op a a1) G.(e)); simpl; auto with arith.\nQed.\n\nTheorem support_aux_length_le_is_e: \n   forall n m, 0 <= m ->  (length (support_aux (gpow m) n) <= n)%nat -> \n      gpow (m + Z_of_nat (length (support_aux (gpow m) n))) = G.(e) .\nintros n; elim n; simpl; auto.\nintros m _ H1; contradict H1; auto with arith.\nintros n1 Rec m Hm; case (A_dec (op a (gpow m)) G.(e)); simpl;  intros H1.\nintros H2; rewrite Zplus_comm; rewrite gpow_add; simpl; try rewrite e_is_zero_r; auto with zarith.\nassert (tmp: forall p, Zpos (P_of_succ_nat p) = 1 + Z_of_nat p).\nintros p1; apply trans_equal with (Z_of_nat (S p1)); auto; rewrite inj_S; auto with zarith.\nrewrite tmp; clear tmp.\nrewrite <- gpow_1.\nrewrite <- gpow_add; auto with zarith.\nrewrite  Zplus_assoc; rewrite (Zplus_comm 1); intros H2; apply Rec; auto with zarith.\nQed.\n\nTheorem support_aux_in: \n  forall n m p, 0 <= m ->  (p < length (support_aux (gpow m) n))% nat ->  \n            (In (gpow (m + Z_of_nat p)) (support_aux (gpow m) n)).\nintros n; elim n; simpl; auto; clear n.\nintros m p Hm H1; replace p with 0%nat.\nleft; eq_tac; auto with zarith.\ngeneralize H1; case p; simpl; auto with arith.\nintros n H2; contradict H2; apply le_not_lt; auto with arith.\nintros n1 Rec m p Hm; case (A_dec (op a (gpow m)) G.(e)); simpl; intros H1 H2; auto.\nreplace p with 0%nat.\nleft; eq_tac; auto with zarith.\ngeneralize H2; case p; simpl; auto with arith.\nintros n H3; contradict H3; apply le_not_lt; auto with arith.\ngeneralize H2; case p; simpl; clear H2.\nrewrite Zplus_0_r; auto.\nintros n.\nassert (tmp: forall p, Zpos (P_of_succ_nat p) = 1 + Z_of_nat p).\nintros p1; apply trans_equal with (Z_of_nat (S p1)); auto; rewrite inj_S; auto with zarith.\nrewrite tmp; clear tmp.\nrewrite <- gpow_1; rewrite <- gpow_add; auto with zarith.\nrewrite  Zplus_assoc; rewrite (Zplus_comm 1); intros H2; right; apply Rec; auto with zarith.\nQed.\n\nTheorem support_aux_ulist: \n  forall n m, 0 <= m -> (forall p, 0 <= p < m -> gpow (1 + p) <> G.(e)) -> ulist (support_aux (gpow m) n).\nintros n; elim n; auto; clear n.\nintros m _ _; auto.\nsimpl; apply ulist_cons; auto.\nintros n1 Rec m Hm H.\nsimpl; case (A_dec (op a (gpow m)) G.(e)); auto.\nintros He; apply ulist_cons; auto.\nintros H1; case  (support_aux_gpow n1 (1 + m) (gpow m)); auto with zarith.\nrewrite gpow_add; try rewrite gpow_1; auto with zarith.\nintros p (Hp1, Hp2).\nassert (H2: gpow (1 + Z_of_nat p) = G.(e)).\napply gpow_i with m; auto with zarith.\nrewrite Hp2; eq_tac; auto with zarith.\ncase (Zle_or_lt m  (Z_of_nat p)); intros H3; auto.\n2: case (H (Z_of_nat p)); auto with zarith.\ncase (support_aux_not_e (S n1) m (gpow (1 + Z_of_nat p))); auto.\nrewrite gpow_add; auto with zarith; simpl; rewrite e_is_zero_r; auto.\ncase (A_dec (op a (gpow m)) G.(e)); auto.\nintros _; rewrite <- gpow_1; repeat rewrite <- gpow_add; auto with zarith.\nreplace (1 + Z_of_nat p) with ((1 + m) + (Z_of_nat (p - Zabs_nat m))); auto with zarith.\napply support_aux_in; auto with zarith.\nrewrite inj_minus1; auto with zarith.\nrewrite inj_Zabs_nat; auto with zarith.\nrewrite Zabs_eq; auto with zarith.\napply inj_le_rev.\nrewrite inj_Zabs_nat; auto with zarith.\nrewrite Zabs_eq; auto with zarith.\nrewrite <- gpow_1; repeat rewrite <- gpow_add; auto with zarith.\napply (Rec (1 + m)); auto with zarith.\nintros p H1; case (Zle_lt_or_eq p m); intros; subst; auto with zarith.\nrewrite  gpow_add; auto with zarith.\nrewrite gpow_1; auto.\nQed.\n\nTheorem support_gpow: forall b, (In b support) -> exists p, 0 <= p < Z_of_nat (length support) /\\ b = gpow p.\nintros b H; case (support_aux_gpow  (Zabs_nat (g_order G)) 0 b); auto with zarith.\nintros p ((H1, H2), H3); exists (Z_of_nat p); repeat split; auto with zarith.\napply inj_lt; auto.\nQed.\n\nTheorem support_incl_G: incl support G.(s).\nintros a1 H; case (support_gpow a1); auto; intros p (H1, H2); subst; apply gpow_in.\nQed.\n\nTheorem gpow_support_not_e: forall p, 0 < p < Z_of_nat (length support) -> gpow p <> G.(e).\nintros p (H1, H2); apply gpow_support_aux_not_e with (m := 0) (n := length G.(s)); simpl;\n  try split; auto with zarith.\nrewrite  <- (Zabs_nat_Z_of_nat (length G.(s))); auto.\nQed.\n\nTheorem support_not_e: forall b, In b (tail support) -> ~ b = G.(e).\nintros b H; apply (support_aux_not_e (Zabs_nat (g_order G)) 0); auto with zarith.\nQed.\n\nTheorem support_ulist:  ulist support.\napply (support_aux_ulist (Zabs_nat (g_order G)) 0); auto with zarith.\nQed.\n\nTheorem support_in_e:  In G.(e) support.\nunfold support; case (Zabs_nat (g_order G)); simpl; auto with zarith.\nQed.\n\nTheorem gpow_length_support_is_e: gpow (Z_of_nat (length support)) = G.(e).\napply (support_aux_length_le_is_e (Zabs_nat (g_order G)) 0); simpl; auto with zarith.\nunfold g_order; rewrite Zabs_nat_Z_of_nat; apply ulist_incl_length.\nrewrite  <- (Zabs_nat_Z_of_nat (length G.(s))); auto.\nexact support_ulist.\nrewrite  <- (Zabs_nat_Z_of_nat (length G.(s))); auto.\nexact support_incl_G.\nQed.\n\nTheorem support_in:  forall p, 0 <= p < Z_of_nat (length support) ->  In (gpow p) support.\nintros p (H, H1); unfold support.\nrewrite <-  (Zabs_eq p); auto with zarith.\nrewrite <-  (inj_Zabs_nat p); auto.\ngeneralize (support_aux_in (Zabs_nat (g_order G)) 0); simpl; intros H2; apply H2; auto with zarith.\nrewrite <-  (fun x => Zabs_nat_Z_of_nat (@length A x)); auto.\napply Zabs_nat_lt; split; auto.\nQed.\n\nTheorem support_internal: forall a b, In a support -> In b support -> In (op a b) support.\nintros a1 b1 H1 H2.\ncase support_gpow with (1 := H1); auto; intros p1 ((H3, H4), H5); subst.\ncase support_gpow with (1 := H2); auto; intros p2 ((H5, H6), H7); subst.\nrewrite <- gpow_add; auto with zarith.\ncase gpow_1_more with (m:= p1 + p2)   (2 := gpow_length_support_is_e); auto with zarith.\nintros p3 ((H8, H9), H10); rewrite H10; apply support_in; auto with zarith.\nQed.\n\nTheorem support_i_internal: forall a, In a support -> In (G.(i) a) support.\ngeneralize gpow_in; intros Hp.\nintros a1 H1.\ncase support_gpow with (1 := H1); auto.\nintros p1 ((H2, H3), H4); case Zle_lt_or_eq with (1 := H2); clear H2; intros H2; subst.\n2: rewrite gpow_0; rewrite i_e; apply support_in_e.\nreplace (G.(i) (gpow p1)) with (gpow (Z_of_nat (length support - Zabs_nat p1))).\napply support_in; auto with zarith.\nrewrite inj_minus1.\nrewrite inj_Zabs_nat; auto with zarith.\nrewrite Zabs_eq; auto with zarith.\napply inj_le_rev; rewrite inj_Zabs_nat; auto with zarith.\nrewrite Zabs_eq; auto with zarith.\napply g_cancel_l with (g:= G) (a := gpow p1); sauto.\nrewrite <- gpow_add; auto with zarith.\nreplace (p1 + Z_of_nat (length support - Zabs_nat p1)) with (Z_of_nat (length support)).\nrewrite gpow_length_support_is_e; sauto.\nrewrite inj_minus1; auto with zarith.\nrewrite inj_Zabs_nat; auto with zarith.\nrewrite Zabs_eq; auto with zarith.\napply inj_le_rev; rewrite inj_Zabs_nat; auto with zarith.\nrewrite Zabs_eq; auto with zarith.\nQed.\n\n(************************************** \n  We are now ready to build the group\n **************************************)\n\nDefinition Gsupport: (FGroup op).\ngeneralize support_incl_G; unfold incl; intros Ho.\napply mkGroup with support G.(e) G.(i); sauto. \napply support_ulist.\napply support_internal.\nintros a1 b1 c1 H1 H2 H3; apply G.(assoc); sauto.\napply support_in_e.\napply support_i_internal.\nDefined.\n\n(************************************** \n  Definition of the order of an element\n **************************************)\nSet Implicit Arguments.\n\nDefinition e_order := Z_of_nat (length support).\n\nUnset Implicit Arguments.\n\n(************************************** \n Some properties of the order of an element\n **************************************)\n\nTheorem gpow_e_order_is_e: gpow e_order = G.(e).\napply (support_aux_length_le_is_e (Zabs_nat (g_order G)) 0); simpl; auto with zarith.\nunfold g_order; rewrite Zabs_nat_Z_of_nat; apply ulist_incl_length.\nrewrite  <- (Zabs_nat_Z_of_nat (length G.(s))); auto.\nexact support_ulist.\nrewrite  <- (Zabs_nat_Z_of_nat (length G.(s))); auto.\nexact support_incl_G.\nQed.\n\nTheorem gpow_e_order_lt_is_not_e: forall n, 1 <= n < e_order -> gpow n <> G.(e).\nintros n (H1, H2); apply gpow_support_not_e; auto with zarith.\nQed.\n\nTheorem e_order_divide_g_order:  (e_order | g_order G).\nchange ((g_order Gsupport) | g_order G).\napply lagrange; auto.\nexact support_incl_G.\nQed.\n\nTheorem e_order_pos: 0 < e_order.\nunfold e_order, support; case (Zabs_nat (g_order G)); simpl; auto with zarith.\nQed.\n\nTheorem e_order_divide_gpow: forall n, 0 <= n -> gpow n = G.(e) -> (e_order | n).\ngeneralize gpow_in; intros Hp.\ngeneralize e_order_pos; intros Hp1.\nintros n Hn; generalize Hn; pattern n; apply Z_lt_induction; auto; clear n Hn.\nintros n Rec Hn H.\ncase (Zle_or_lt  e_order n); intros H1.\ncase (Rec (n - e_order)); auto with zarith.\napply g_cancel_l with (g:= G) (a := gpow e_order); sauto.\nrewrite G.(e_is_zero_r); auto with zarith.\nrewrite <- gpow_add; try (rewrite gpow_e_order_is_e; rewrite <- H; eq_tac); auto with zarith.\nintros k Hk; exists (1 + k).\nrewrite Zmult_plus_distr_l; rewrite <- Hk; auto with zarith.\ncase (Zle_lt_or_eq 0 n); auto with arith; intros H2; subst.\ncontradict H; apply support_not_e.\ngeneralize H1; unfold e_order, support.\ncase (Zabs_nat (g_order G)); simpl; auto.\nintros H3; contradict H3; auto with zarith.\nintros n1; case (A_dec (op a G.(e)) G.(e)); simpl; intros _ H3.\ncontradict H3; auto with zarith.\ngeneralize H3; clear H3.\nassert (tmp: forall p, Zpos (P_of_succ_nat p) = 1 + Z_of_nat p).\nintros p1; apply trans_equal with (Z_of_nat (S p1)); auto; rewrite inj_S; auto with zarith.\nrewrite tmp; clear tmp; intros H3.\nchange (In (gpow n) (support_aux (gpow 1) n1)).\nreplace n with (1 + Z_of_nat (Zabs_nat n - 1)).\napply support_aux_in; auto with zarith.\nrewrite <- (fun x => Zabs_nat_Z_of_nat (@length A x)).\nreplace (Zabs_nat n - 1)%nat  with (Zabs_nat (n - 1)).\napply Zabs_nat_lt; split; auto with zarith.\nrewrite G.(e_is_zero_r) in H3; try rewrite gpow_1; auto with zarith.\napply inj_eq_rev; rewrite inj_Zabs_nat; auto with zarith.\nrewrite Zabs_eq; auto with zarith.\nrewrite inj_minus1; auto with zarith.\nrewrite inj_Zabs_nat; auto with zarith.\nrewrite Zabs_eq; auto with zarith.\napply inj_le_rev; rewrite inj_Zabs_nat; simpl; auto with zarith.\nrewrite Zabs_eq; auto with zarith.\nrewrite inj_minus1; auto with zarith.\nrewrite inj_Zabs_nat; auto with zarith.\nrewrite Zabs_eq; auto with zarith.\nrewrite Zplus_comm; simpl; auto with zarith.\napply inj_le_rev; rewrite inj_Zabs_nat; simpl; auto with zarith.\nrewrite Zabs_eq; auto with zarith.\nexists 0; auto with arith.\nQed.\n\nEnd EGroup.\n\nTheorem gpow_gpow: forall (A : Set) (op : A -> A -> A) (a : A) (G : FGroup op),\n       In a (s G) -> forall n m, 0 <= n -> 0 <= m -> gpow a G (n * m ) = gpow (gpow a G n) G m.\nintros A op a G H n m; case n.\nsimpl; intros _ H1; generalize H1.\npattern m; apply natlike_ind; simpl; auto.\nintros x H2 Rec _; unfold Zsucc; rewrite gpow_add; simpl; auto with zarith.\nrepeat rewrite G.(e_is_zero_r); auto with zarith.\napply gpow_in; sauto.\nintros p1 _; case m; simpl; auto.\nassert(H1: In (iter_pos A (op a) (e G) p1) (s G)).\nrefine (gpow_in _ _ _ _ _ (Zpos p1)); auto.\nintros p2 _;  pattern p2; apply Pind; simpl; auto.\nrewrite Pmult_1_r; rewrite G.(e_is_zero_r); try rewrite G.(e_is_zero_r); auto.\nintros p3 Rec; rewrite Pplus_one_succ_r; rewrite Pmult_plus_distr_l.\nrewrite Pmult_1_r.\nsimpl; repeat rewrite iter_pos_plus; simpl.\nrewrite G.(e_is_zero_r); auto.\nrewrite gpow_op with (G:= G); try rewrite Rec; auto.\napply sym_equal; apply gpow_op; auto.\nintros p Hp; contradict Hp; auto with zarith.\nQed.\n\nTheorem gpow_e: forall (A : Set) (op : A -> A -> A) (G : FGroup op) n, 0 <= n -> gpow G.(e) G n = G.(e).\nintros A op G n; case n; simpl; auto with zarith.\nintros p _; elim p; simpl; auto; intros p1 Rec; repeat rewrite Rec; auto.\nQed.\n\nTheorem gpow_pow: forall (A : Set) (op : A -> A -> A) (a : A) (G : FGroup op),\n       In a (s G) -> forall n, 0 <= n -> gpow a G (2 ^ n) = G.(e) -> forall m, n <= m -> gpow a G (2 ^ m) = G.(e).\nintros A op a G H n H1 H2 m Hm.\nreplace m with (n + (m - n)); auto with zarith.\nrewrite Zpower_exp; auto with zarith.\nrewrite gpow_gpow; auto with zarith.\nrewrite H2; apply gpow_e.\napply Zpower_ge_0; auto with zarith.\nQed.\n\nTheorem gpow_mult: forall (A : Set) (op : A -> A -> A) (a b: A) (G : FGroup op)\n       (comm: forall a b,  In a (s G) -> In b (s G) -> op a b = op b a), \n       In a (s G) -> In b (s G) -> forall n, 0 <= n -> gpow (op a b) G n = op (gpow a G n) (gpow b G n).\nintros A op a  b G comm Ha Hb n; case n; simpl; auto.\nintros _; rewrite G.(e_is_zero_r); auto.\n2: intros p Hp; contradict Hp; auto with zarith.\nintros p _; pattern p; apply Pind; simpl; auto.\nrepeat rewrite G.(e_is_zero_r); auto.\nintros p3 Rec; rewrite Pplus_one_succ_r.\nrepeat rewrite iter_pos_plus; simpl.\nrepeat rewrite (fun x y H z => gpow_op A  op x G H (op y z)) ; auto.\nrewrite Rec.\nrepeat rewrite G.(e_is_zero_r); auto.\nassert(H1: In (iter_pos A (op a) (e G) p3) (s G)).\nrefine (gpow_in _ _ _ _ _ (Zpos p3)); auto.\nassert(H2: In (iter_pos A (op b) (e G) p3) (s G)).\nrefine (gpow_in _ _ _ _ _ (Zpos p3)); auto.\nrepeat rewrite <- G.(assoc); try eq_tac; auto.\nrewrite (fun x y => comm (iter_pos A x y p3) b); auto.\nrewrite (G.(assoc) a); try apply comm; auto.\nQed.\n\nTheorem Zdivide_mult_rel_prime:  forall a b c : Z, (a | c) -> (b | c) -> rel_prime a b -> (a * b | c).\nintros a b c (q1, H1) (q2, H2) H3.\nassert (H4: (a | q2)).\napply Gauss with (2 := H3).\nexists q1; rewrite <- H1; rewrite H2; auto with zarith.\ncase H4; intros q3 H5; exists q3; rewrite H2; rewrite H5; auto with zarith.\nQed.\n\nTheorem order_mult: forall (A : Set) (op : A -> A -> A) (A_dec: forall a b: A, {a = b} + {~ a = b}) (G : FGroup op)\n       (comm: forall a b,  In a (s G) -> In b (s G) -> op a b = op b a) (a b: A), \n       In a (s G) -> In b (s G) -> rel_prime (e_order A_dec a G) (e_order A_dec b G) -> \n        e_order A_dec (op a b) G = e_order A_dec a G * e_order A_dec b G.\nintros A op A_dec G comm a b Ha Hb Hab.\nassert (Hoat: 0 < e_order A_dec a G); try apply e_order_pos.\nassert (Hobt: 0 < e_order A_dec b G); try apply e_order_pos.\nassert (Hoabt: 0 < e_order A_dec (op a b) G); try apply e_order_pos.\nassert (Hoa: 0 <= e_order A_dec a G); auto with zarith.\nassert (Hob: 0 <= e_order A_dec b G); auto with zarith.\napply Zle_antisym; apply Zdivide_le; auto with zarith.\napply Zmult_lt_O_compat; auto.\napply e_order_divide_gpow; sauto; auto with zarith.\nrewrite gpow_mult; auto with zarith.\nrewrite gpow_gpow; auto with zarith.\nrewrite gpow_e_order_is_e; auto with zarith.\nrewrite gpow_e; auto.\nrewrite Zmult_comm.\nrewrite gpow_gpow; auto with zarith.\nrewrite gpow_e_order_is_e; auto with zarith.\nrewrite gpow_e; auto.\napply Zdivide_mult_rel_prime; auto.\napply Gauss with (2 := Hab).\napply e_order_divide_gpow; auto with zarith.\nrewrite <- (gpow_e _ _ G (e_order A_dec b G)); auto.\nrewrite <- (gpow_e_order_is_e _ A_dec  _ (op a b) G); auto with zarith.\nrewrite <- gpow_gpow; auto with zarith.\nrewrite (Zmult_comm (e_order A_dec (op a b) G)).\nrewrite gpow_mult; auto with zarith.\nrewrite gpow_gpow with (a := b); auto with zarith.\nrewrite gpow_e_order_is_e; auto with zarith.\nrewrite gpow_e; auto with zarith.\nrewrite G.(e_is_zero_r); auto with zarith.\napply gpow_in; auto.\napply Gauss with (2 := rel_prime_sym _ _ Hab).\napply e_order_divide_gpow; auto with zarith.\nrewrite <- (gpow_e _ _ G (e_order A_dec a G)); auto.\nrewrite <- (gpow_e_order_is_e _ A_dec  _ (op a b) G); auto with zarith.\nrewrite <- gpow_gpow; auto with zarith.\nrewrite (Zmult_comm (e_order A_dec (op a b) G)).\nrewrite gpow_mult; auto with zarith.\nrewrite gpow_gpow with (a := a); auto with zarith.\nrewrite gpow_e_order_is_e; auto with zarith.\nrewrite gpow_e; auto with zarith.\nrewrite G.(e_is_zero_l); auto with zarith.\napply gpow_in; auto.\nQed.\n\nTheorem fermat_gen: forall (A : Set) (A_dec: forall (a b: A), {a = b} + {a <>b}) (op : A -> A -> A) (a: A) (G : FGroup op),\n       In a G.(s) ->  gpow a G (g_order G) = G.(e).\nintros A A_dec op a G H.\nassert (H1: (e_order A_dec a G | g_order G)).\napply e_order_divide_g_order; auto.\ncase H1; intros q; intros Hq; rewrite Hq.\nassert (Hq1: 0 <= q).\napply Zmult_le_reg_r with (e_order A_dec a G); auto with zarith.\napply Zlt_gt; apply e_order_pos.\nrewrite Zmult_0_l; rewrite <- Hq; apply Zlt_le_weak; apply g_order_pos.\nrewrite Zmult_comm; rewrite gpow_gpow; auto with zarith.\nrewrite gpow_e_order_is_e; auto with zarith.\napply gpow_e; auto.\napply Zlt_le_weak; apply e_order_pos.\nQed.\n\nTheorem order_div: forall (A : Set) (A_dec: forall (a b: A), {a = b} + {a <>b}) (op : A -> A -> A) (a: A) (G : FGroup op) m,\n 0 < m -> (forall p, prime p -> (p | m) -> gpow a G (m / p) <> G.(e)) ->\n In a G.(s) -> gpow a G m = G.(e) -> e_order A_dec a G = m.\nintros A Adec op a G m Hm H H1 H2.\nassert (F1: 0 <= m); auto with zarith.\ncase (e_order_divide_gpow A Adec op a G H1 m F1 H2); intros q Hq.\nassert (F2: 1 <= q).\n  case (Zle_or_lt 0 q); intros HH.\n    case (Zle_lt_or_eq _ _ HH); auto with zarith.\n    intros HH1; generalize Hm; rewrite Hq; rewrite <- HH1; \n      auto with zarith.\n  assert (F2: 0 <= (- q) * e_order Adec a G); auto with zarith.\n    apply Zmult_le_0_compat; auto with zarith. \n    apply Zlt_le_weak; apply e_order_pos.\n  generalize F2; rewrite Zopp_mult_distr_l_reverse;\n      rewrite <- Hq; auto with zarith.\ncase (Zle_lt_or_eq _ _ F2); intros H3; subst; auto with zarith.\ncase (prime_dec q); intros Hq.\n  case (H q); auto with zarith.\n    rewrite Zmult_comm; rewrite Z_div_mult; auto with zarith.\n  apply gpow_e_order_is_e; auto.\ncase (Zdivide_div_prime_le_square _ H3 Hq); intros r (Hr1, (Hr2, Hr3)).\ncase (H _ Hr1); auto.\n  apply Zdivide_trans with (1 := Hr2).\n  apply Zdivide_factor_r.\ncase Hr2; intros q1 Hq1; subst.\nassert (F3: 0 < r).\n  generalize (prime_ge_2 _ Hr1); auto with zarith.\nrewrite <- Zmult_assoc; rewrite Zmult_comm; rewrite <- Zmult_assoc;\n  rewrite Zmult_comm; rewrite Z_div_mult; auto with zarith.\nrewrite gpow_gpow; auto with zarith.\n  rewrite gpow_e_order_is_e; try rewrite gpow_e; auto.\n  apply Zmult_le_reg_r with r; auto with zarith.\n  apply Zlt_le_weak; apply e_order_pos.\napply Zmult_le_reg_r with r; auto with zarith.\nQed.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_crypto_defined/coqprime/Coqprime/EGroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.687026610144892}}
{"text": "(* Adapt nat paths in the TLC style. *)\n\nSet Implicit Arguments.\nRequire Import TLC.LibTactics TLC.LibReflect TLC.LibBool TLC.LibOperation TLC.LibRelation TLC.LibOrder  TLC.LibNat.\n\n\n(* ********************************************************************** *)\n(** * Inhabited and comparable *)\n\n\nInductive IPE: Set :=\n | zero_pe    \n | one_pe.\n\nInductive PE : Set := \n | i_pe      : IPE -> PE\n | u_pe      : PE.\n\nDefinition Path : Set := list PE.\nDefinition pdot : Path := nil.\n\nInstance path_inhab : Inhab Path.\nProof using. intros. apply (prove_Inhab (cons u_pe nil)). Qed.\n\nFixpoint path_compare (x y : Path) :=\n  match x, y with\n    | nil, nil => true\n    | (cons _ _), nil => false\n    | nil, (cons _ _) => false\n    | (cons a x'), (cons b y') =>\n      If a = b (* The trick is to USE equality at each step! *)\n      then path_compare x' y'\n      else false\n  end.\n\n(* And this proves equality is valid in classical logic! *)\nInstance path_comparable : Comparable Path.\nProof using.\n  applys (comparable_beq path_compare).\n  induction x; destruct y; simpl; autos*; auto_false.\n  destruct (classicT (a = p));  split; intros; try solve[inversion H].\n  apply IHx in H.\n  subst.\n  reflexivity.\n  inversion H; subst.\n  apply IHx.\n  reflexivity.\n  inversion H.\n  contradiction.\nQed.\n\n", "meta": {"author": "briangmilnes", "repo": "CycloneCoqSemantics", "sha": "190c0fc57d5aebfde244efb06a119f108de7a150", "save_path": "github-repos/coq/briangmilnes-CycloneCoqSemantics", "path": "github-repos/coq/briangmilnes-CycloneCoqSemantics/CycloneCoqSemantics-190c0fc57d5aebfde244efb06a119f108de7a150/4.4/LibPath.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.68702660978579}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_8_3.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_8_2.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_equaltorightisright : \n   forall A B C a b c, \n   Per A B C -> CongA a b c A B C ->\n   Per a b c.\nProof.\nintros.\nassert (CongA A B C a b c) by (conclude lemma_equalanglessymmetric).\nlet Tf:=fresh in\nassert (Tf:exists E F e f, (Out B A E /\\ Out B C F /\\ Out b a e /\\ Out b c f /\\ Cong B E b e /\\ Cong B F b f /\\ Cong E F e f /\\ nCol A B C)) by (conclude_def CongA );destruct Tf as [E[F[e[f]]]];spliter.\nassert (Per A B F) by (conclude lemma_8_3).\nassert (Per F B A) by (conclude lemma_8_2).\nassert (Per F B E) by (conclude lemma_8_3).\nassert (Per E B F) by (conclude lemma_8_2).\nassert (neq B E) by (conclude lemma_raystrict).\nassert (neq E B) by (conclude lemma_inequalitysymmetric).\nlet Tf:=fresh in\nassert (Tf:exists W, (BetS E B W /\\ Cong E B W B /\\ Cong E F W F /\\ neq B F)) by (conclude_def Per );destruct Tf as [W];spliter.\nassert (neq b e) by (conclude axiom_nocollapse).\nassert (neq e b) by (conclude lemma_inequalitysymmetric).\nlet Tf:=fresh in\nassert (Tf:exists w, (BetS e b w /\\ Cong b w e b)) by (conclude lemma_extension);destruct Tf as [w];spliter.\nassert (Cong e b E B) by (forward_using lemma_doublereverse).\nassert (Cong b w E B) by (conclude lemma_congruencetransitive).\nassert (Cong E B B W) by (forward_using lemma_congruenceflip).\nassert (Cong b w B W) by (conclude lemma_congruencetransitive).\nassert (Cong b f B F) by (conclude lemma_congruencesymmetric).\nassert (Cong e f E F) by (conclude lemma_congruencesymmetric).\nassert (Cong e w E W) by (conclude cn_sumofparts).\nassert (Cong f w F W) by (conclude (axiom_5_line e b w f E B W F)).\nassert (Cong e b B W) by (conclude lemma_congruencetransitive).\nassert (Cong B W b w) by (conclude lemma_congruencesymmetric).\nassert (Cong e b b w) by (conclude lemma_congruencetransitive).\nassert (Cong e b w b) by (forward_using lemma_congruenceflip).\nassert (Cong e f W F) by (conclude lemma_congruencetransitive).\nassert (Cong W F w f) by (forward_using lemma_doublereverse).\nassert (Cong e f w f) by (conclude lemma_congruencetransitive).\nassert (neq b f) by (conclude lemma_raystrict).\nassert (Per e b f) by (conclude_def Per ).\nassert (Out b f c) by (conclude lemma_ray5).\nassert (Per e b c) by (conclude lemma_8_3).\nassert (Per c b e) by (conclude lemma_8_2).\nassert (Out b e a) by (conclude lemma_ray5).\nassert (Per c b a) by (conclude lemma_8_3).\nassert (Per a b c) by (conclude lemma_8_2).\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_equaltorightisright.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6870266094266877}}
{"text": "(* generated by Ott 0.31, locally-nameless lngen from: ../ott/rules.ott *)\nRequire Import Bool.\nRequire Import Metalib.Metatheory.\nRequire Import List.\n(** syntax *)\n\nInductive nexp : Set :=  (*r expressions *)\n | ne_var_b (_:nat) (*r variables *)\n | ne_var_f (x:var) (*r variables *)\n | ne_lit (i:nat): nexp (*r lit *)\n | ne_abs (e:nexp) (*r abstractions *)\n | ne_app (e1:nexp) (e2:nexp) (*r applications *).\n\n(* EXPERIMENTAL *)\n(** auxiliary functions on the new list types *)\n(** library functions *)\n(** subrules *)\n(** arities *)\n(** opening up abstractions *)\nFixpoint open_nexp_wrt_nexp_rec (k:nat) (e_5:nexp) (e__6:nexp) {struct e__6}: nexp :=\n  match e__6 with\n  | (ne_var_b nat) => \n      match lt_eq_lt_dec nat k with\n        | inleft (left _) => ne_var_b nat\n        | inleft (right _) => e_5\n        | inright _ => ne_var_b (nat - 1)\n      end\n  | (ne_var_f x) => ne_var_f x\n  | ne_lit i => ne_lit i \n  | (ne_abs e) => ne_abs (open_nexp_wrt_nexp_rec (S k) e_5 e)\n  | (ne_app e1 e2) => ne_app (open_nexp_wrt_nexp_rec k e_5 e1) (open_nexp_wrt_nexp_rec k e_5 e2)\nend.\n\nDefinition open_nexp_wrt_nexp e_5 e__6 := open_nexp_wrt_nexp_rec 0 e__6 e_5.\n\n(** terms are locally-closed pre-terms *)\n(** definitions *)\n\n(* defns LC_nexp *)\nInductive lc_nexp : nexp -> Prop :=    (* defn lc_nexp *)\n | lc_ne_var_f : forall (x:var),\n     (lc_nexp (ne_var_f x))\n | lc_ne_lit : forall i, \n     (lc_nexp (ne_lit i))\n | lc_ne_abs : forall (e:nexp),\n      ( forall x , lc_nexp  ( open_nexp_wrt_nexp e (ne_var_f x) )  )  ->\n     (lc_nexp (ne_abs e))\n | lc_ne_app : forall (e1 e2:nexp),\n     (lc_nexp e1) ->\n     (lc_nexp e2) ->\n     (lc_nexp (ne_app e1 e2)).\n(** free variables *)\nFixpoint fv_nexp (e_5:nexp) : vars :=\n  match e_5 with\n  | (ne_var_b nat) => {}\n  | (ne_var_f x) => {{x}}\n  | ne_lit i => {}\n  | (ne_abs e) => (fv_nexp e)\n  | (ne_app e1 e2) => (fv_nexp e1) \\u (fv_nexp e2)\nend.\n\n(** substitutions *)\nFixpoint subst_nexp (e_5:nexp) (x5:var) (e__6:nexp) {struct e__6} : nexp :=\n  match e__6 with\n  | (ne_var_b nat) => ne_var_b nat\n  | (ne_var_f x) => (if eq_var x x5 then e_5 else (ne_var_f x))\n  | ne_lit i => ne_lit i \n  | (ne_abs e) => ne_abs (subst_nexp e_5 x5 e)\n  | (ne_app e1 e2) => ne_app (subst_nexp e_5 x5 e1) (subst_nexp e_5 x5 e2)\nend.\n\n\n(** definitions *)\n\n\n(** infrastructure *)\nHint Constructors lc_nexp : core.\n\n\n", "meta": {"author": "YeWenjia", "repo": "TypedDirectedGradualTypingWithBlame", "sha": "99210b5208555d4ea729738ea4a959c59b0646d0", "save_path": "github-repos/coq/YeWenjia-TypedDirectedGradualTypingWithBlame", "path": "github-repos/coq/YeWenjia-TypedDirectedGradualTypingWithBlame/TypedDirectedGradualTypingWithBlame-99210b5208555d4ea729738ea4a959c59b0646d0/JFP-Artifact/\\Bg/coq/syntaxn_ott.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6870266028732218}}
{"text": "(* NEXT: ===> Core                                                              *) \n\nRequire Import Le.\nRequire Import List.\n\nRequire Import Logic.Nat.Max.\n\nRequire Import Logic.Set.Set.\n\n\n(* Now that we have a type to represent our universe of sets, we shall need     *)\n(* to define various notions in relation to it. For example we shall need to    *) \n(* define what it means for a set x to belong to a set y (denoted x :: y), or   *)\n(* what it means for a set x to be a subset of y (denoted x <== y), or what it  *)\n(* means for a set x to be equal to y (denoted x == y). These relations can be  *)\n(* defined in coq in any way we like. However, if we want our model of set      *)\n(* theory to be interesting, we shall need to use definitions which are more    *)\n(* complex than simple recursive definitions. In particular, we shall need to   *)\n(* reason on the 'complexity' of the arguments, as measured by the 'order'.     *)\nFixpoint order (xs:set) : nat :=\n    match xs with\n    | Nil       =>  0\n    | Cons x xs =>  S (max (order x) (order xs))\n    end.\n\n(* This lemma will be used on many occasions. If a set x is one of the elements *)\n(* of the list of sets associated with a set y, then the 'complexity' of x      *)\n(* cannot be greater to that of y. In fact a stronger result with a strict      *)\n(* inequality can be obtained, but this has not been needed so far.             *)\nLemma orderToList : forall (x y:set),\n    In x (toList y) -> order x <= order y.\nProof.\n    intros x. induction y as [|y _ ys IH]; intros H.\n    - inversion H.\n    - destruct H as [H|H].\n        + rewrite <- H. simpl. apply le_S. apply n_le_max.\n        + simpl. apply le_S. apply le_trans with (order ys).\n            { apply IH. assumption. }\n            { apply m_le_max. }\nQed.\n\n(* The only set with order 0 is Nil.                                            *)\nLemma order_0 : forall (xs:set), order xs = 0 -> xs = Nil.\nProof.\n    intros [|x xs].\n    - intros _. reflexivity.\n    - intros H. inversion H.\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/Set/Order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797081106935, "lm_q2_score": 0.7799929002541067, "lm_q1q2_score": 0.6870154698279499}}
{"text": "Require Import Reals.\nRequire Import Lra.\nRequire Import Psatz.\n(*Require Import SeqSeries.*)\nLocal Open Scope R_scope.\n\nDefinition harmonic_squrd (n : nat) := 1 / (((INR n) + 1) ^ 2).\n\n(*decreasing*)\nLemma harmonic_squrd_decreasing : Un_decreasing harmonic_squrd.\nProof.\n  unfold Un_decreasing, harmonic_squrd.\n  intros n.\n  induction n as [| n' IHn'].\n  - field_simplify; simpl; lra.\n  - field_simplify.\n\nAdmitted.\n\n\nLemma harmonic_squrd_convergent : Un_cv harmonic_squrd 0.\n  unfold Un_cv, harmonic_squrd.\n  intros eps H.\n  remember (sqrt eps) as sqrt_eps.\n  (*exists nat.ceil (1 / sqrt_eps)*)\nAdmitted.\n\nLtac abs_lra :=\n  unfold R_dist, Rabs; destruct Rcase_abs; try lra.\n\nLemma Rdist_ident :\n  forall x, x >= 0 -> R_dist x 0 = x.\nProof.\n  intros x H.\n  unfold R_dist, Rabs.\n  destruct Rcase_abs; try lra.\nQed.\n\nLemma sqrt_preserves_convergence_to0 : forall (Xn : nat -> R),\n    (*exericse 2.3.1 in Stephen Abbott Understanding Analysis*)\n    Un_cv Xn 0 -> forall k, Xn k >= 0 -> Un_cv (fun n => sqrt (Xn n)) 0.\nProof.\n  intros Xn H k H'.\n  unfold Un_cv in *.\n  intros eps H__eps.\n  assert (0<eps*eps). apply Rmult_lt_compat_r with (r:=eps) in H__eps;\n                        try (rewrite Rmult_comm in H__eps;\n                             rewrite Rmult_0_r in H__eps);\n                        apply H__eps.\n  specialize (H (eps*eps) H0).\n  destruct H as [N H].\n  exists N.\n  intros n0 H2.\n  specialize (H n0 H2).\n  unfold sqrt.\n  destruct Rcase_abs as [G | G].\n  - abs_lra.\n  - unfold Rsqrt; simpl.\n    destruct Rsqrt_exists as [x0 [F1 F2]].\n    abs_lra.\n    inversion F1 as [F1' | F1']; try lra.\n    rewrite Rminus_0_r in *.\n    apply Rsqr_incrst_0; unfold Rsqr; try lra.\n    unfold Rsqr in F2.\n    rewrite <- F2.\n    rewrite Rdist_ident in H; try lra.\nQed.\n", "meta": {"author": "quinn-dougherty", "repo": "rca", "sha": "e5d5344e2880e80a3ac395772db7fc193566a63c", "save_path": "github-repos/coq/quinn-dougherty-rca", "path": "github-repos/coq/quinn-dougherty-rca/rca-e5d5344e2880e80a3ac395772db7fc193566a63c/with-standard-library/sequences_scratch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.687015469451242}}
{"text": "Require Import List.\nImport ListNotations.\n\nFixpoint penU {X : Type} (ls: list X): option X := \nmatch ls with \n| [] => None\n| [x;y] => Some x\n| x::xs => penU xs\nend.\n\nTheorem penUNone {X : Type} : forall (ls : list X), \n  length ls < 2 -> penU ls = None.\nProof.\n  destruct ls.\n  auto.\n  destruct ls.\n  auto.\n  intro.\n  inversion H.\n  inversion H1.\n  inversion H3.\nQed.\n\nTheorem penUCorrect {X : Type} : forall (ls : list X) x y, penU (ls ++ [x;y]) = Some x.\nProof.\n  intros.\n  induction ls.\n  + reflexivity.\n  + destruct ls.\n    - auto.\n    - destruct ls.\n      * auto.\n      * assert (penU ((a :: x0 :: x1 :: ls) ++ [x; y]) =  penU ((x0 :: x1 :: ls) ++ [x; y])).\n        { reflexivity. }\n        rewrite H.\n        exact IHls.\nQed.", "meta": {"author": "SvenWille", "repo": "Coq99Problems", "sha": "47002c12016120e3ab43c2591de25875b7067a99", "save_path": "github-repos/coq/SvenWille-Coq99Problems", "path": "github-repos/coq/SvenWille-Coq99Problems/Coq99Problems-47002c12016120e3ab43c2591de25875b7067a99/coqSrc/P2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6870154681407264}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div seq path order.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(* Axiom replace_with_your_solution_here : forall {A : Type}, A. *)\n\nSection InsertionSort.\n\nVariable T : eqType.\nVariable leT : rel T.\nImplicit Types x y z : T.\n\n(** Insert an element [e] into a sorted list [s] *)\nFixpoint insert e s : seq T :=\n  if s is x :: s' then\n    if leT e x then e :: s\n    else x :: (insert e s')\n  else [:: e].\n\n(** Sort input list [s] *)\nFixpoint sort s : seq T :=\n  if s is x :: s' then insert x (sort s')\n  else [::].\n\nHypothesis leT_total : total leT.\nHypothesis leT_tr : transitive leT.\n\n(* from lection *)\nLemma insert_path z e s :\n    leT z e ->\n    path leT z s ->\n    path leT z (insert e s).\nProof.\nelim: s z=> [/= | x1 s IHs] z; first by move=> ->.\nmove=> z_le_e /=.\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(* from lection *)\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(* from lection *)\nLemma sort_sorted s :\n  sorted leT (sort s).\nProof.\nelim: s=> //= x s IHs.\nby rewrite insert_sorted.\nQed.\n\nLemma all_expands s e x :\n    leT x e ->\n    all (leT e) s ->\n    all (leT x) s.\nProof.\nmove=> x_le_e.\nelim: s=> // y s IHs /=.\ncase/andP.\nmove=> e_le_y all_es.\napply/andP.\nsplit.\nexact: (leT_tr x_le_e e_le_y).\nby apply: IHs.\nQed.\n\n\nLemma where_are_all_lemmas_about_all e y s :\n    all (leT e) (y :: s) -> leT e y.\nProof.\nelim: s => //=.\nby case/andP.\nmove=> x s IHs.\nby case/andP.\nQed.\n\n\nLemma insert_with_all s e :\n    sorted leT s ->\n    all (leT e) s ->\n    e :: s = insert e s.\nProof.\nelim: s=> // y s IHs sorted_ys all_ys /=.\ncase: ifP => //.\nmove=> e_le_y_false.\nmove: (where_are_all_lemmas_about_all all_ys).\nrewrite e_le_y_false //.\nQed.\n\n\nLemma filter_doesnt_break_all (p all_p : pred T) s :\n    all all_p s -> all all_p (filter p s).\nProof.\nelim: s=> // x s IHs /=.\ncase/andP=> all_px all_ps.\ncase: ifP=> px_info.\nmove=> /=.\napply/andP ; split ; first done.\nby rewrite IHs.\nby rewrite IHs.\nQed.\n\nLemma take_insert_from_filter (p : pred T) s x :\n    p x ->\n    sorted leT s ->\n    filter p (insert x s) = insert x (filter p s).\nProof.\nmove=> px.\nelim: s=> //=.\nmove=> _.\ncase: ifP => //.\nrewrite px //.\nmove=> e s IHs path_e_s.\ncase: ifP.\ncase: ifP.\nmove=> pe x_le_e /=.\ncase: ifP => //.\ncase: ifP => //.\ncase: ifP => //.\nrewrite x_le_e //.\nrewrite pe //.\nrewrite px //.\nmove=> pe_false x_le_e /=.\ncase: ifP.\ncase: ifP.\nrewrite pe_false //.\nmove: (order_path_min leT_tr path_e_s).\nmove=> all_le_e_s _ _ /=.\nSearch all transitive.\nmove: (all_expands x_le_e all_le_e_s).\nmove=> all_le_x_s.\nrewrite insert_with_all //.\nrewrite sorted_filter //.\nrewrite (path_sorted path_e_s) //.\nby rewrite filter_doesnt_break_all.\nrewrite px //.\nmove=> x_le_e_false.\ncase: ifP=> pe_info /=.\ncase: ifP.\ncase: ifP.\nrewrite x_le_e_false //.\nmove=> _ _.\nrewrite IHs //.\nrewrite (path_sorted path_e_s) //.\nrewrite pe_info //.\ncase: ifP.\nrewrite pe_info //.\nmove=> _.\nrewrite IHs //.\nrewrite (path_sorted path_e_s) //.\nQed.\n\nLemma absurd_insert_filter (p : pred T) s x :\n    p x = false ->\n    filter p (insert x s) = filter p s.\nProof.\nelim: s=> //=.\ncase: ifP=> //.\nmove=> e s IHs.\ncase: ifP=> //.\nmove=> le_x_e px_false.\ncase: ifP=> //=.\ncase: ifP.\nrewrite px_false //.\nmove=> _ pe.\ncase: ifP => //.\nrewrite pe //.\nmove=> pe_false.\ncase: ifP => //.\nrewrite px_false //.\nmove=> _.\ncase: ifP => //.\nrewrite pe_false //.\nmove=> le_x_e_false px_false.\ncase: ifP => // pe.\nrewrite -IHs //=.\ncase: ifP => //.\nrewrite pe //.\nrewrite -IHs //=.\ncase: ifP => //.\nrewrite pe //.\nQed.\n\n(** * Exercise *)\nLemma filter_sort (p : pred T) s :\n  filter p (sort s) = sort (filter p s).\nProof.\nelim: s=> //= x s IHs.\ncase: ifP=> px /=.\nrewrite take_insert_from_filter.\nrewrite IHs.\nmove=> //.\ndone.\nexact: sort_sorted.\nby rewrite absurd_insert_filter.\nQed.\n\n(** Hint: you will probably need to introduce a number of helper lemmas *)\n\nEnd InsertionSort.\n\n\n\nSection AccPredicate.\n\n(* To help you understand the meaning of the `Acc` predicate, here is how\n it can be used to write recursive functions without explicitly using recursion: *)\n\n\n(** * Exercise:  understand how `addn_f` works *)\nSection AdditionViaFix_F.\n\n(* First, let's redefine the addition on natural numbers\n   using the `Fix_F` combinator: *)\nAbout Fix_F.\nPrint Fix_F.\n\n(* Fix_F =  \n     fun (A : Type) (R : A -> A -> Prop) (P : A -> Type) \n         (F : forall x : A, (forall y : A, R y x -> P y) -> P x) => \n fix Fix_F (x : A) (a : Acc R x) {struct a} : P x := \n   F x (fun (y : A) (h : R y x) => Fix_F y (Acc_inv a h)) \n\t  : forall (A : Type) (R : A -> A -> Prop) (P : A -> Type), \n        (forall x : A, (forall y : A, R y x -> P y) -> P x) -> \n        forall x : A, Acc R x -> P x *)\n\n(* notice we do recursion on the `a : Acc R x` argument *)\nPrint Acc_inv.\n(* To define addition, we first need to choose the relation `R`\n   which \"connects\" successive value.\n   In the case of addition `R x y` can simply mean `y = x.+1` *)\n\nDefinition R m n := n = m.+1.\nPrint R.\n\n(* This definition has to be transparent, otherwise\n   evaluation will get stuck *)\nDefinition esucc_inj : injective succn. by move=> n m []. Defined.\n\n(* Every natural number is accessible w.r.t. R defined above *)\nFixpoint acc (n : nat) : Acc R n :=\n  if n is n'.+1 then\n      Acc_intro n'.+1 (fun y (pf : n'.+1 = y.+1) =>\n                         eq_ind n' _ (acc n') y (esucc_inj pf))\n  else Acc_intro 0 (fun y contra => False_ind _ (O_S y contra)).\n\nCheck acc.\n(*\nBy the way, `forall n : nat, Acc R n` means that `R` is a well-founded\nrelation: https://en.wikipedia.org/wiki/Well-founded_relation.\n*)\nPrint well_founded.\nPrint acc.\n(* Addition via `Fix_F` *)\nDefinition addn_f : nat -> nat -> nat :=\n  fun m =>\n    @Fix_F (nat : Type)\n           (R : nat -> nat -> Prop)\n           ((fun=> nat -> nat) : (nat -> Type))\n           (fun (m : nat) (rec : (forall y : nat, R y m -> (fun=> nat -> nat) y)) =>\n              match m return (_ = m -> nat -> nat) with\n              | m'.+1 => fun (eq : m = m'.+1) => succn \\o rec m' eq\n              | 0 => fun=> id\n              end erefl)\n           (m : nat)\n           ((acc m) : Acc R m).\n\n(* This would get stuck if esucc *)\nCheck erefl : addn_f 2 4 = 6.\n\nLemma addn_equiv_addn_f :\n  addn =2 addn_f.\nProof. by elim=> // m IHm n; rewrite addSn IHm. Qed.\n\n\nEnd AdditionViaFix_F.\n\n\n\n(** Exercise: implement multiplication on natural numbers using `Fix_F`:\n    no explicit recursion, Program Fixpoint or things like that! *)\nSection MultiplicationViaFix_F.\n\nDefinition eaddn_inj n : injective (addn n).\nProof.\nelim: n=> // n IHn x y.\nrewrite !addSnnS.\nrewrite /injective in IHn.\nmove=> eqxy.\nmove: (IHn x.+1 y.+1 eqxy).\napply: esucc_inj.\nDefined.\n\nDefinition muln_f : nat -> nat -> nat :=\n  fun m =>\n    @Fix_F (nat : Type)\n           (R : nat -> nat -> Prop)\n           ((fun=> nat -> nat) : (nat -> Type))\n           (fun (m : nat) (rec : (forall y : nat, R y m -> (fun=> nat -> nat) y)) =>\n              match m return (_ = m -> nat -> nat) with\n              | 0 => fun=> (fun x => 0) \n              | m'.+1 => fun (eq : m = m'.+1) => (fun x => x + (rec m' eq) x)\n              end erefl)\n           (m : nat)\n           ((acc m) : Acc R m).\n\n\n\n(* this should not fail *)\nCompute muln_f 2 33.\nCompute muln_f 1 33.\nCompute muln_f 0 33.\nCompute muln_f 0 0.\nCompute muln_f 123 0.\nCheck erefl : muln_f 21 2 = 42.\n\nLemma muln_equiv_muln_f :\n  muln =2 muln_f.\nProof. by elim=> // y IHy x ; rewrite mulSn IHy. Qed.\n\n\nEnd MultiplicationViaFix_F.\n\n\n\nEnd AccPredicate.", "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/hw09.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7799928951399099, "lm_q1q2_score": 0.6870154677640191}}
{"text": "(*|\n#################################################################\nCoq: destruct (co)inductive hypothesis without losing information\n#################################################################\n\n:Link: https://stackoverflow.com/q/45151308\n|*)\n\n(*|\nQuestion\n********\n\nConsider the following development:\n|*)\n\nRequire Import Relation_Definitions RelationClasses.\n\nSet Implicit Arguments.\n\nCoInductive stream (A : Type) : Type :=\n| scons : A -> stream A -> stream A.\n\nCoInductive stream_le (A : Type) {eqA R : relation A}\n            `{PO : PartialOrder A eqA R} :\n  stream A -> stream A -> Prop :=\n| le_step : forall h1 h2 t1 t2, R h1 h2 ->\n                                (eqA h1 h2 -> stream_le t1 t2) ->\n                                stream_le (scons h1 t1) (scons h2 t2).\n\n(*|\nIf I have a hypothesis ``stream_le (scons h1 t1) (scons h2 t2)``, it\nwould be reasonable for the ``destruct`` tactic to turn it into a pair\nof hypotheses ``R h1 h2`` and ``eqA h1 h2 -> stream_le t1 t2``. But\nthat's not what happens, because ``destruct`` loses information\nwhenever doing anything non-trivial. Instead, new terms ``h0``,\n``h3``, ``t0``, ``t3`` are introduced into the context, with no recall\nthat they are respectively equal to ``h1``, ``h2``, ``t1``, ``t2``.\n\n\nI would like to know if there is a quick and easy way to do this kind\nof \"smart ``destruct``\". Here is what i have right now:\n|*)\n\nTheorem stream_le_destruct :\n  forall (A : Type) eqA R\n         `{PO : PartialOrder A eqA R} (h1 h2 : A) (t1 t2 : stream A),\n    stream_le (scons h1 t1) (scons h2 t2) ->\n    R h1 h2 /\\ (eqA h1 h2 -> stream_le t1 t2).\nProof.\n  intros.\n  destruct H eqn:Heq. Undo.\n  remember (scons h1 t1) as s1 eqn:Heqs1.\n  remember (scons h2 t2) as s2 eqn:Heqs2.\n  destruct H.\n  inversion Heqs1. inversion Heqs2. subst.\n  split; assumption.\nQed.\n\n(*|\nAnswer (Arthur Azevedo De Amorim)\n*********************************\n\nCalling ``destruct`` will not directly give you what you want. You\nneed to use ``inversion`` instead.\n|*)\n\nReset stream_le_destruct. (* .none *)\nTheorem stream_le_destruct :\n  forall (A : Type) eqA R\n         `{PO : PartialOrder A eqA R} (h1 h2 : A) (t1 t2 : stream A),\n    stream_le (scons h1 t1) (scons h2 t2) ->\n    R h1 h2 /\\ (eqA h1 h2 -> stream_le t1 t2).\nProof.\n  intros.\n  inversion H. subst.\n  split; assumption.\nQed.\n\n(*|\nUnfortunately, the ``inversion`` tactic is quite ill behaved, as it\ntends to generate a lot of spurious equality hypotheses, making it\nhard to name them consistently. One (somewhat heavyweight, admittedly)\nalternative is to use ``inversion`` only to prove a lemma like the one\nyou did, and apply this lemma in proofs instead of calling\n``inversion``.\n|*)\n\n(*|\nAnswer (ejgallego)\n******************\n\nIndeed, ``inversion`` basically does what you want, however as Arthur\npointed out it is a bit unstable, mainly due to the different\ncongruence steps.\n\nUnder the hood, ``inversion`` just calls a version of ``destruct``,\nbut remembering some equalities first. As you have well discovered,\npattern matching in Coq will \"forget\" arguments of constructors,\nexcept if these are variables, then, all the variables *under the\nscope* of the destruct will be instantiated.\n\nWhat does that mean? It means that in order to properly destruct an\ninductive ``I : Idx -> Prop``, you want to get your goal of the form:\n``I x -> Q x``, so that destructing the ``I x`` will also refine the\n``x`` in ``Q``. Thus, a standard transformation for an inductive ``I\nterm`` and goal ``Q (f term)`` is to rewrite it to ``I x -> x = term\n-> Q (f x)``. Then, destructing ``I x`` will get you ``x``\ninstantiated to the proper index.\n\nWith that in mind, it may be a good exercise to implement inversion\nmanually using the ``case:`` tactic of Coq 8.7;\n|*)\n\nReset stream_le_destruct. (* .none *)\nFrom Coq Require Import ssreflect.\n\nTheorem stream_le_destruct A eqA R\n        `{PO : PartialOrder A eqA R} (h1 h2 : A) (t1 t2 : stream A) :\n  stream_le (scons h1 t1) (scons h2 t2) ->\n  R h1 h2 /\\ (eqA h1 h2 -> stream_le t1 t2).\nProof.\n  move E1: (scons h1 t1) => sc1. move E2: (scons h2 t2) => sc2 H.\n  by case: sc1 sc2 / H E1 E2 => h1' h2' t1' t2' hr ih [? ?] [? ?]; subst.\nQed.\n\n(*|\nYou can read the manual for more details, but basically with the first\nline, we create the equalities we need; then, in the second we can\ndestruct the term and get the proper instantiations solving the goal.\nA good effect of the ``case:`` tactic is that, contrary to destruct,\nit will try to prevent us from destructing a term without first\nbringing its dependencies into scope.\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-destruct-coinductive-hypothesis-without-losing-information.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581049086031, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.6869645321857261}}
{"text": "\nRequire Import Lib BinPosDef BinNatDef BinIntDef.\n\n(** Instead of list of digits as in [Deci.v], we try here\n    an ad-hoc specialized list-like datatype. Moreover, the conversion\n    to digits are done via Horner-style computations in base 10 instead\n    of division+modulo in the other base.\n*)\n\nInductive dec :=\n | Stop\n | D0 : dec -> dec\n | D1 : dec -> dec\n | D2 : dec -> dec\n | D3 : dec -> dec\n | D4 : dec -> dec\n | D5 : dec -> dec\n | D6 : dec -> dec\n | D7 : dec -> dec\n | D8 : dec -> dec\n | D9 : dec -> dec.\n\nDefinition ten := D1 (D0 Stop). (** For example... *)\n\n(** This representation favors simplicity over canonicity :\n    we might need later to normalize by removing the leading zeros *)\n\nFixpoint norm l :=\n  match l with\n  | D0 l => norm l\n  | _ => l\n  end.\n\n(** A few easy operations. For more advanced computations, use the conversions\n    with other Coq numeral datatypes (e.g. Z) and the operations on them. *)\n\n(** For conversions with binary numbers, it is easier to operate\n    on little-endian numbers. *)\n\nFixpoint rev (l l' : dec) :=\n  match l with\n  | Stop => l'\n  | D0 l => rev l (D0 l')\n  | D1 l => rev l (D1 l')\n  | D2 l => rev l (D2 l')\n  | D3 l => rev l (D3 l')\n  | D4 l => rev l (D4 l')\n  | D5 l => rev l (D5 l')\n  | D6 l => rev l (D6 l')\n  | D7 l => rev l (D7 l')\n  | D8 l => rev l (D8 l')\n  | D9 l => rev l (D9 l')\n  end.\n\nModule Little.\n\n(** Successor of little-endian numbers *)\n\nFixpoint succ d :=\n  match d with\n  | Stop => D1 Stop\n  | D0 l => D1 l\n  | D1 l => D2 l\n  | D2 l => D3 l\n  | D3 l => D4 l\n  | D4 l => D5 l\n  | D5 l => D6 l\n  | D6 l => D7 l\n  | D7 l => D8 l\n  | D8 l => D9 l\n  | D9 l => D0 (succ l)\n  end.\n\n(** Doubling little-endian numbers *)\n\nFixpoint double d :=\n  match d with\n  | Stop => Stop\n  | D0 l => D0 (double l)\n  | D1 l => D2 (double l)\n  | D2 l => D4 (double l)\n  | D3 l => D6 (double l)\n  | D4 l => D8 (double l)\n  | D5 l => D0 (succ_double l)\n  | D6 l => D2 (succ_double l)\n  | D7 l => D4 (succ_double l)\n  | D8 l => D6 (succ_double l)\n  | D9 l => D8 (succ_double l)\n  end\n\nwith succ_double d :=\n  match d with\n  | Stop => D1 Stop\n  | D0 l => D1 (double l)\n  | D1 l => D3 (double l)\n  | D2 l => D5 (double l)\n  | D3 l => D7 (double l)\n  | D4 l => D9 (double l)\n  | D5 l => D1 (succ_double l)\n  | D6 l => D3 (succ_double l)\n  | D7 l => D5 (succ_double l)\n  | D8 l => D7 (succ_double l)\n  | D9 l => D9 (succ_double l)\n  end.\n\nEnd Little.\n\n\n(** Conversion between decimal and Peano nat representations *)\n\nModule DecNat.\n\nLocal Notation ten := (S (S (S (S (S (S (S (S (S (S O)))))))))).\nLocal Notation tenfold := (TailNat.mul ten).\n\nFixpoint of_dec_acc (d:dec)(acc:nat) :=\n  match d with\n  | Stop => acc\n  | D0 d => of_dec_acc d (tenfold acc)\n  | D1 d => of_dec_acc d (S (tenfold acc))\n  | D2 d => of_dec_acc d (S (S (tenfold acc)))\n  | D3 d => of_dec_acc d (S (S (S (tenfold acc))))\n  | D4 d => of_dec_acc d (S (S (S (S (tenfold acc)))))\n  | D5 d => of_dec_acc d (S (S (S (S (S (tenfold acc))))))\n  | D6 d => of_dec_acc d (S (S (S (S (S (S (tenfold acc)))))))\n  | D7 d => of_dec_acc d (S (S (S (S (S (S (S (tenfold acc))))))))\n  | D8 d => of_dec_acc d (S (S (S (S (S (S (S (S (tenfold acc)))))))))\n  | D9 d => of_dec_acc d (S (S (S (S (S (S (S (S (S (tenfold acc))))))))))\n  end.\n\nDefinition of_dec (d:dec) := of_dec_acc d O.\n\nFixpoint to_little_dec n acc :=\n  match n with\n  | O => acc\n  | S n => to_little_dec n (Little.succ acc)\n  end.\n\nDefinition to_dec n :=\n  rev (to_little_dec n Stop) Stop.\n\nEnd DecNat.\n\n\n(** Same for decimal and binary N numbers *)\n\nModule DecPos.\n\nLocal Open Scope positive.\n\nFixpoint to_dec_rev p :=\n  match p with\n  | 1 => D1 Stop\n  | p~1 => Little.succ_double (to_dec_rev p)\n  | p~0 => Little.double (to_dec_rev p)\n  end.\n\nDefinition to_dec p := rev (to_dec_rev p) Stop.\n\nLocal Notation ten := 1~0~1~0.\nLocal Notation tenfold := (Pos.mul ten).\n\nFixpoint of_dec_acc (d:dec)(acc:positive) :=\n  match d with\n  | Stop => acc\n  | D0 l => of_dec_acc l (tenfold acc)\n  | D1 l => of_dec_acc l (Pos.add 1 (tenfold acc))\n  | D2 l => of_dec_acc l (Pos.add 2 (tenfold acc))\n  | D3 l => of_dec_acc l (Pos.add 3 (tenfold acc))\n  | D4 l => of_dec_acc l (Pos.add 4 (tenfold acc))\n  | D5 l => of_dec_acc l (Pos.add 5 (tenfold acc))\n  | D6 l => of_dec_acc l (Pos.add 6 (tenfold acc))\n  | D7 l => of_dec_acc l (Pos.add 7 (tenfold acc))\n  | D8 l => of_dec_acc l (Pos.add 8 (tenfold acc))\n  | D9 l => of_dec_acc l (Pos.add 9 (tenfold acc))\n  end.\n\nFixpoint of_dec (d:dec) : N :=\n  match d with\n  | Stop => N0\n  | D0 l => of_dec l\n  | D1 l => Npos (of_dec_acc l 1)\n  | D2 l => Npos (of_dec_acc l 1~0)\n  | D3 l => Npos (of_dec_acc l 1~1)\n  | D4 l => Npos (of_dec_acc l 1~0~0)\n  | D5 l => Npos (of_dec_acc l 1~0~1)\n  | D6 l => Npos (of_dec_acc l 1~1~0)\n  | D7 l => Npos (of_dec_acc l 1~1~1)\n  | D8 l => Npos (of_dec_acc l 1~0~0~0)\n  | D9 l => Npos (of_dec_acc l 1~0~0~1)\n  end.\n\nEnd DecPos.\n\n\nModule DecN.\n\nLocal Open Scope N.\n\nDefinition of_dec := DecPos.of_dec.\n\nDefinition to_dec (n:N) :=\n  match n with\n  | N0 => Stop\n  | Npos p => DecPos.to_dec p\n  end.\n\nEnd DecN.\n\nModule DecZ.\n\nDefinition dec2z d :=\n match DecN.of_dec d with\n | N0 => Z0\n | Npos p => Zpos p\n end.\n\nDefinition z2dec z :=\n match z with\n | Zpos p => DecPos.to_dec p\n | _ => Stop (* TODO : for now, we discard negative numbers *)\n end.\n\nEnd DecZ.\n\n\n(** A successor on decimal. Not really mandatory, just to state\n    that our conversions preserve the order of numbers *)\n\nDefinition succ d := rev (Little.succ (rev d Stop)) Stop.\n\n(** The strict order on decimal numbers is the transitive\n    closure of the successor *)\n\nInductive lt : dec -> dec -> Prop :=\n | Succ x : lt x (succ x)\n | Trans x y z : lt x y -> lt y z -> lt x z.\n", "meta": {"author": "letouzey", "repo": "baseconv", "sha": "9acc385745c1ea27a2d7891726d190b6e50d3325", "save_path": "github-repos/coq/letouzey-baseconv", "path": "github-repos/coq/letouzey-baseconv/baseconv-9acc385745c1ea27a2d7891726d190b6e50d3325/DeciTer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.6869645245237285}}
{"text": "Add LoadPath \".\" as OPAT.\nRequire Import OPAT.aula3 OPAT.aula4 OPAT.aula5 OPAT.aula6 OPAT.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 :=\n  match l with\n  | nil => nil\n  | 0 :: t => nonzeros t\n  | n :: t => n :: nonzeros t\n  end.\n\n(** **** Exercise: 1 star  *)\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. simpl. reflexivity. Qed.\n\n(* GRADE_THEOREM 0.5: NatList.test_nonzeros *)\n\n(** **** Exercise: 2 star  *)\nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | n :: t => match oddb n with\n              | true => n :: oddmembers t\n              | false => oddmembers t\n              end\n  end.\n\n(** **** Exercise: 1 star  *)\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\n(** **** Exercise: 2 star  *)\nDefinition countoddmembers (l:natlist) : nat :=\n  length (oddmembers l).\n\n(** **** Exercise: 1 star  *)\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star  *)\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star  *)\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate)  *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n    into one, alternating between elements taken from the first list\n    and elements from the second.  See the tests below for more\n    specific examples.\n\n    Note: one natural and elegant way of writing [alternate] will fail\n    to satisfy Coq's requirement that all [Fixpoint] definitions be\n    \"obviously terminating.\"  If you find yourself in this rut, look\n    for a slightly more verbose solution that considers elements of\n    both lists at the same time.  (One possible solution requires\n    defining a new kind of pairs, but this is not the only way.)  *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | n1 :: t1 => match l2 with\n                | nil => n1 :: t1\n                | n2 :: t2 => n1 :: n2 :: alternate t1 t2\n                end\n  end.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. 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", "meta": {"author": "bugarela", "repo": "Coq", "sha": "9f4973fec5b34ed836aa2239a009385e0549c024", "save_path": "github-repos/coq/bugarela-Coq", "path": "github-repos/coq/bugarela-Coq/Coq-9f4973fec5b34ed836aa2239a009385e0549c024/OPAT exercises/doit5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.6869645238070023}}
{"text": "(* Do not edit this file, it was generated automatically *)\n(* This file tests:\n    forward_for_simple_bound on 64-bit long integers,\n    forward load with 64-bit integer array subscript, and\n    forward store with 64-bit integer array subscript.\n*)\n\nRequire Import VST.floyd.proofauto.\nRequire Import VST.progs64.min64.\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs.  mk_varspecs prog. Defined.\n\nRequire Import ZArith.\nRequire Import List.\nImport ListNotations.\nOpen Scope Z.\n\n\nTheorem fold_min_general:\n  forall (al: list Z)(i: Z),\n  In i (al) ->\n  forall x, List.fold_right Z.min x al <= i.\nProof.\ninduction al; intros.\ninversion H.\ndestruct H.\nsubst a.\nsimpl.\napply Z.le_min_l.\nsimpl. rewrite Z.le_min_r.\napply IHal.\napply H.\nQed.\n\nTheorem fold_min:\n  forall (al: list Z)(i: Z),\n  In i (al) ->\n  List.fold_right Z.min (hd 0 al) al <= i.\nProof.\nintros.\napply fold_min_general.\napply H.\nQed.\n\nLemma Forall_fold_min:\n  forall (f: Z -> Prop) (x: Z) (al: list Z),\n    f x -> Forall f al -> f (fold_right Z.min x al).\nProof.\n intros.\n induction H0.\n simpl. auto.\n simpl.\n unfold Z.min at 1.\n destruct (Z.compare x0 (fold_right Z.min x l)) eqn:?; auto.\nQed.\n\nLemma fold_min_another:\n  forall x al y,\n    fold_right Z.min x (al ++ [y]) = Z.min (fold_right Z.min x al) y.\nProof.\n intros.\n revert x; induction al; simpl; intros.\n apply Z.min_comm.\n rewrite <- Z.min_assoc. f_equal.\n apply IHal.\nQed.\n\nLemma is_int_I32_Znth_map_Vint:\n forall i s al,\n  0 <= i < Zlength al ->\n  is_int I32 s (Znth i (map Vint al)).\nProof.\nintros. rewrite Znth_map; auto.\nQed.\n#[export] Hint Extern 3 (is_int I32 _ (Znth _ (map Vint _))) =>\n  (apply  is_int_I32_Znth_map_Vint; rewrite ?Zlength_map; lia) : core.\n\nDefinition minimum_spec :=\n DECLARE _minimum\n  WITH a: val, n: Z, al: list Z\n  PRE [ tptr tint , tlong ]\n    PROP  (1 <= n <= Int64.max_signed; Forall repable_signed al)\n    PARAMS (a; Vlong (Int64.repr n))\n    SEP   (data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a)\n  POST [ tint ]\n    PROP ()\n    RETURN (Vint (Int.repr (fold_right Z.min (hd 0 al) al)))\n    SEP   (data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a).\n\nDefinition Gprog : funspecs :=\n      ltac:(with_library prog [minimum_spec]).\n\n(* First approach from \"Modular Verification for Computer Security\",\n  proved using forward_for_simple_bound *)\n\nLemma body_min: semax_body Vprog Gprog f_minimum minimum_spec.\nProof.\nstart_function.\nassert_PROP (Zlength al = n) by (entailer!; list_solve).\nforward.  (* min = a[0]; *)\nforward_for_simple_bound n\n  (EX i:Z,\n    PROP()\n    LOCAL(temp _min (Vint (Int.repr (fold_right Z.min (Znth 0 al) (sublist 0 i al))));\n          temp _a a;\n          temp _n (Vlong (Int64.repr n)))\n    SEP(data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a)).\n* (* Prove that the precondition implies the loop invariant *)\n  entailer!!.\n* (* Prove that the loop body preserves the loop invariant *)\n forward. (* j = a[i]; *)\n forward. (* a[i] = j; *)\n assert (repable_signed (Znth i al))\n     by (apply Forall_Znth; auto; lia).\n assert (repable_signed (fold_right Z.min (Znth 0 al) (sublist 0 i al)))\n   by (apply Forall_fold_min;\n          [apply Forall_Znth; auto; lia\n          |apply Forall_sublist; auto]).\n autorewrite with sublist.\n subst POSTCONDITION; unfold abbreviate.\n rewrite (sublist_split 0 i (i+1)) by lia.\n rewrite (sublist_one i (i+1) al) by lia.\n rewrite fold_min_another.\n replace  (upd_Znth i (map Vint (map Int.repr al)) (Vint (Int.repr (Znth i al))))\n  with (map Vint (map Int.repr al))\n  by list_solve.\n forward_if.\n +\n forward. (* min = j; *)\n entailer!.\n rewrite Z.min_r; auto; lia.\n +\n forward. (* skip; *)\n entailer!.\n rewrite Z.min_l; auto; lia.\n* (* After the loop *)\n forward. (* return *)\n entailer!!.\n autorewrite with sublist.\n destruct al; simpl; auto.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs64/verif_min64.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.6869645140415611}}
{"text": "Require Import Nat_utils.\nRequire Import Validity.\nRequire Import ZArith. \nRequire Import Coeff_utils.\nRequire Import Coeff.\nRequire Import Values.\nRequire Import Arith.\n\nFixpoint minus_base (p : poly) {struct p} : poly :=\n  match p with\n  |Cst (Z0) => Cst (Z0)\n  |Cst (Z.pos z) => Cst (Z.neg z)\n  |Cst (Z.neg z) => Cst (Z.pos z)\n  |Poly p1 i p2 => Poly (minus_base p1) i (minus_base p2)\nend.\n\nLemma minus_isnull (p : poly) :\n  is_null p = is_null (minus_base p).\nProof.\n  induction p.\n  - induction z.\n    + simpl minus_base.\n      reflexivity.\n    + simpl is_null.\n      reflexivity.\n    + simpl is_null.\n      reflexivity.\n  - simpl is_null.\n    reflexivity.\nQed.\n\nLemma minus_valid_i (p : poly) :\n  forall i : nat, valid_bool_i p i = true -> valid_bool_i (minus_base p) i = true.\nProof.\n  induction p.\n  induction z; simpl valid_bool_i; trivial.\n\n  intros.\n  simpl valid_bool_i in H.\n  apply Bool.andb_true_iff in H.\n  destruct H.\n  apply Bool.andb_true_iff in H0.\n  destruct H0.\n  apply Bool.andb_true_iff in H1.\n  destruct H1.\n\n  simpl valid_bool_i.\n  apply Bool.andb_true_iff.\n  split.\n  assumption.\n\n  apply Bool.andb_true_iff.\n  split.\n  rewrite <- minus_isnull.\n  assumption.\n\n  apply Bool.andb_true_iff.\n  split.\n  apply IHp1.\n  assumption.\n\n  apply IHp2.\n  assumption.\n\nQed.\n\nLemma minus_valid (p : poly) :\n  valid_bool p = true -> valid_bool (minus_base p) = true.\nProof.\n  unfold valid_bool.\n  apply minus_valid_i with (i := 0).\n  \nQed.\n\nDefinition minus_poly (p : valid_poly) : valid_poly :=\n{| VP_value := minus_base (VP_value p) ;\n   VP_prop := minus_valid (VP_value p) (VP_prop p) |}.\n\nTheorem eval_minus (p : valid_poly) (f : nat -> Z) :\n  eval (minus_poly p) f = Z.opp (eval p f).\nProof.\n  destruct p as [p p'].\n  unfold eval.\n  simpl VP_value.\n  induction p.\n\n  - simpl.\n    induction z;reflexivity.\n  - unfold valid_bool in p'.\n    simpl valid_bool_i in p'.\n    apply Bool.andb_true_iff in p'.\n    destruct p' as [p' p1'].\n    apply Bool.andb_true_iff in p1'.\n    destruct p1' as [p1' p2'].\n\n    simpl eval_base.\n    rewrite IHp1.\n    rewrite IHp2.\n    Lia.lia.\n\n    unfold valid_bool; apply valid_leb with (n := n); trivial;assumption.\n    unfold valid_bool; apply valid_leb with (n := S n); trivial;assumption.\nQed.\n\n\n\n\n", "meta": {"author": "TabetSalwa", "repo": "2.7.2-polynomials", "sha": "78bcea3ccdf0b614223266cf867b6954dc704dbf", "save_path": "github-repos/coq/TabetSalwa-2.7.2-polynomials", "path": "github-repos/coq/TabetSalwa-2.7.2-polynomials/2.7.2-polynomials-78bcea3ccdf0b614223266cf867b6954dc704dbf/Reflection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6869645126314758}}
{"text": "(** Author: Floris van Doorn, december 2017 *)\nRequire Import UniMath.Combinatorics.Lists.\nRequire Import UniMath.MoreFoundations.Subtypes.\n\n(** Graphs.\n\nContents:\n- paths in a graph (called gpaths to disambiguate from the identity type)\n- operations on paths\n*)\n\n\n(** In this file we consider graphs with a type of vertices and a type of edges between any pair of\n   vertices. We could restrict to sets, but there is no reason to do that here. *)\n\nDefinition issymmetric {V : UU} (E : V → V → UU) : UU :=\n  ∏u v, E u v ≃ E v u.\n\nDefinition gpaths_of_length {V : UU} (E : V → V → UU) (v w : V) (n : nat) : UU.\nProof.\n  revert v. induction n as [|n IH].\n  - intro v. exact (v = w).\n  - intro v. exact (∑u, E v u × IH u).\nDefined.\n\nDefinition gpaths {V : UU} (E : V → V → UU) (v w : V) : UU :=\n  ∑n, gpaths_of_length E v w n.\n\nDefinition nil {V : UU} {E : V → V → UU} (v : V) : gpaths E v v :=\n  (0,, idpath v).\n\nDefinition cons {V : UU} {E : V → V → UU} {w u v : V} (e : E u v) (p : gpaths E v w) : gpaths E u w :=\n  (S (pr1 p),, (v,, (e,, pr2 p))).\n\nLocal Notation \"[]\" := (nil _) (at level 0, format \"[]\").\nLocal Infix \"::\" := cons.\n\nLemma gpaths_ind {V : UU} {E : V → V → UU} {w : V} (P : ∏{u}, gpaths E u w → UU)\n      (H1 : P []) (H2 : ∏{u v} (e : E u v) (p : gpaths E v w), P p → P (e :: p))\n      {u : V} (p : gpaths E u w) : P p.\nProof.\n  induction p as [n p]. revert u p. induction n as [|n IH].\n  - induction p. exact H1.\n  - induction p as [v x]. induction x as [e p]. apply (H2 _ _ _ (n,, p)).\n    apply IH.\nDefined.\n\nDefinition foldr {V : UU} {E : V → V → UU} {w : V} {B : V → UU} (f : ∏{u v}, E u v → B v → B u)\n           (b : B w) : ∏{u : V}, gpaths E u w → B u.\nProof. apply gpaths_ind. exact b. exact (λ u v e _ b, f u v e b). Defined.\n\nDefinition concat {V : UU} {E : V → V → UU} {u v w : V} (p : gpaths E u v) (q : gpaths E v w) :\n  gpaths E u w :=\n  foldr (λ _ _ , cons) q p.\n\nLocal Infix \"++\" := concat.\n\nDefinition append {V : UU} {E : V → V → UU} {u v w : V} (p : gpaths E u v) (e : E v w) :\n  gpaths E u w :=\n  p ++ e::[].\n\nDefinition reverse {V : UU} {E : V → V → UU} (H : issymmetric E) {u v : V} (p : gpaths E u v) :\n  gpaths E v u.\nProof.\n  revert u p. apply gpaths_ind.\n  - exact [].\n  - intros u u' e p q. exact (append q (invmap (H u' u) e)).\nDefined.\n\nDefinition symmetric_closure {V : UU} (E : V → V → UU) (u v : V) : UU :=\nE u v ⨿ E v u.\n\nDefinition issymmetric_symmetric_closure {V : UU} (E : V → V → UU) :\n  issymmetric (symmetric_closure E) :=\n  λ u v, weqcoprodcomm (E u v) (E v u).\n\nDefinition reverse_in_closure {V : UU} {E : V → V → UU} {u v : V}\n           (p : gpaths (symmetric_closure E) u v) : gpaths (symmetric_closure E) v u :=\n  reverse (issymmetric_symmetric_closure E) p.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/Combinatorics/GraphPaths.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891435927269, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.6869254938568969}}
{"text": "(* Copyright (C) 2005-2008 Sebastien Briais *)\n(* http://lamp.epfl.ch/~sbriais/ *)\n\n(* This library is free software; you can redistribute it and/or modify *)\n(* it under the terms of the GNU Lesser General Public License as *)\n(* published by the Free Software Foundation; either version 2.1 of the *)\n(* License, or (at your option) any later version. *)\n\n(* This library is distributed in the hope that it will be useful, but *)\n(* WITHOUT ANY WARRANTY; without even the implied warranty of *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU *)\n(* Lesser General Public License for more details. *)\n\n(* You should have received a copy of the GNU Lesser General Public *)\n(* License along with this library; if not, write to the Free Software *)\n(* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA *)\n\nRequire Import missing.\nRequire Import division.\nRequire Import Wf_nat.\n\nUnset Standard Proposition Elimination Names.\n\n(** lemmae about divisibility *)\nLemma divides_le : forall (a b:nat),(a<>O)->(divides a b)->(b<=a).\n  intros.\n  elim H0;intro q;intro.\n  replace b with (b*1);try ring.\n  rewrite H1.\n  apply mult_le_compat;try omega.\n  destruct q;omega.\nQed.\n\n(** Euclide theorem (existence) *)\nTheorem euclide : forall (a b:nat),(b<>O)->{q:nat & { r:nat | (a=b*q+r) /\\ (r < b)}}.\n  intros.\n  apply (lt_wf_rec a (fun a:nat =>{q : nat &  {r : nat | a = b * q + r /\\ r < b}})).\n  intros.\n  case (le_lt_dec b n);intro.\n  elim (H0 (n-b)).\n  intro q;intro.\n  elim p;intro r;intro.\n  exists (q+1);exists r.\n  split;try tauto.\n  rewrite (le_plus_minus b n);trivial.\n  elim p0;intros.\n  rewrite H1;ring.\n  omega.\n  exists 0;exists n.\n  split;try tauto.\n  ring.\nQed.\n\nDefinition quotient_euclide (a b:nat)(H:(b<>O)) := let (q,_) := (euclide a b H) in q.\n\nDefinition remainder_euclide (a b:nat)(H:(b<>O)) := let (_,e0) := (euclide a b H) in let (r,_) := e0 in r.\n\n(** a div b where b<>0 *)\nLemma quo_rem_euclide : forall (a b:nat)(H:(b<>O)),a=b*(quotient_euclide a b H)+(remainder_euclide a b H).\n  unfold quotient_euclide;unfold remainder_euclide;intros.\n  generalize (euclide a b H);intros.\n  elim s;intro q;intro.\n  elim p;intro r;intro.\n  tauto.\nQed.\n\n(** a mod b where b<>0 *)\nLemma rem_euclide : forall (a b:nat)(H:(b<>O)),(remainder_euclide a b H)<b.\n  unfold remainder_euclide;intros.\n  generalize (euclide a b H);intros.\n  elim s;intro q;intro.\n  elim p;intro r;intro.\n  tauto.\nQed.\n\n(** Euclide division is unique *)\nLemma euclide_unique : forall (a b q r q' r':nat),(b<>O)->a=b*q+r->a=b*q'+r'->r<b->r'<b->(q=q')/\\(r=r').\n  intros.\n  rewrite H1 in H0.\n  case (lt_eq_lt_dec q q');intro.\n  case s;intro.\n  rewrite (le_plus_minus q q') in H0;try (auto with arith).\n  rewrite mult_plus_distr_l in H0.\n  assert (b*(q'-q)+r' = r).\n  apply plus_reg_l with (b*q).\n  rewrite plus_assoc;trivial.\n  assert (0<(q'-q));try omega.\n  assert (b<=b*(q'-q));try omega.\n  case (mult_O_le b (q'-q));intro;try omega.\n  rewrite mult_comm;trivial.\n  split;try tauto.\n  rewrite <- e in H0.\n  symmetry;apply plus_reg_l with (b*q);trivial.\n  rewrite (le_plus_minus q' q) in H0;try (auto with arith).\n  rewrite mult_plus_distr_l in H0.\n  assert (r'=(b*(q-q')+r)).\n  apply plus_reg_l with (b*q').\n  rewrite plus_assoc;trivial.\n  assert (0<(q-q'));try omega.\n  assert (b<=b*(q-q'));try omega.\n  case (mult_O_le b (q-q'));intro;try omega.\n  rewrite mult_comm;trivial.\nQed.\n\n(** if b<>0, then b | a iff a mod b = 0 *) \nLemma divides_euclide : forall (a b:nat)(H:(b<>O)),((divides a b)<->((remainder_euclide a b H)=O)).\n  intros.\n  red.\n  split;intro.\n  generalize (quo_rem_euclide a b H);intro.\n  generalize (rem_euclide a b H);intro.\n  elim H0;intro q;intro.\n  assert (a=b*q+0).\n  rewrite plus_comm;simpl;trivial.\n  assert (0<b);try omega.\n  generalize (euclide_unique a b (quotient_euclide a b H) (remainder_euclide a b H) q 0 H H1 H4 H2 H5).\n  intros;tauto.\n  generalize (quo_rem_euclide a b H).\n  rewrite H0;rewrite plus_comm;simpl.\n  intro;exists (quotient_euclide a b H);trivial.\nQed.\n\n(** divisibility is decidable *)\nLemma divides_dec : forall (a b:nat),{divides a b}+{~(divides a b)}.\n  intros.\n  case (eq_nat_dec b 0).\n  case (eq_nat_dec a 0);intros.\n  rewrite e;left;apply zero_max_div.\n  right;rewrite e;intro.\n  elim H;intro q;intro.\n  simpl in H0;apply n;trivial.\n  intro.\n  case (eq_nat_dec (remainder_euclide a b n) 0);[left | right];intros;elim (divides_euclide a b n);auto.\nQed.\n\n(** if a property about integer is decidable then it is decidable if there is an integer less than n that satisfies this property *)\nLemma dec_impl_lt_dec : forall (P:nat->Prop),(forall (n:nat),{(P n)}+{~(P n)})->(forall (m:nat),{n:nat | (n<m)/\\(P(n))}+{(forall (n:nat),(n<m)->~(P n))}).\n  intros.\n  induction m.\n  right;intros;inversion H0.\n  case (H m);intro.\n  left;exists m;split;try (auto with arith).\n  case IHm;intro.\n  elim s;intro n0;intro.\n  left;exists n0;split;[omega | tauto].\n  right;intros.\n  inversion H0;trivial.\n  apply n0;omega.\nQed.\n\n(** forall n, either forall p, p<>1 /\\ p<>n -> not(p | n) or there is p such that p<>1 and p<>n and p | n *) \nLemma divides_nat : forall (n:nat),{p:nat | (p<>1)/\\(p<>n)/\\(divides n p)}+{forall (p:nat),(p<>1)->(p<>n)->~(divides n p)}.\n  intros.\n  case (dec_impl_lt_dec (fun p => (p<>1)/\\(divides n p))) with n;intros.\n  case (divides_dec n n0);intro.\n  case (eq_nat_dec n0 1);intros.\n  right;intro;tauto.\n  left;tauto.\n  right;tauto.\n  elim s;intros.\n  left;exists x.\n  split;try tauto.\n  split;try tauto.\n  omega.\n  case (eq_nat_dec n 0);intro.\n  rewrite e;left;exists 2.\n  split;try (intro;discriminate).\n  split;try (intro;discriminate).\n  apply zero_max_div.\n  right;intros.\n  case (lt_eq_lt_dec p n);intro.\n  case s;intro;[red in n0;intro;apply n0 with p;tauto | auto].\n  intro;generalize (divides_le n p n1 H1);omega.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "fundamental-arithmetics", "sha": "8976d4ba6a5c53b7eb25d08921e592d200189431", "save_path": "github-repos/coq/coq-contribs-fundamental-arithmetics", "path": "github-repos/coq/coq-contribs-fundamental-arithmetics/fundamental-arithmetics-8976d4ba6a5c53b7eb25d08921e592d200189431/euclide.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.6869254846204667}}
{"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: Relation_Definitions.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\nSection Relation_Definition.\n\n  Variable A : Type.\n\n  Definition relation := A -> A -> Prop.\n\n  Variable R : relation.\n\n\n  Section General_Properties_of_Relations.\n\n    Definition reflexive : Prop := forall x:A, R x x.\n    Definition transitive : Prop := forall x y z:A, R x y -> R y z -> R x z.\n    Definition symmetric : Prop := forall x y:A, R x y -> R y x.\n    Definition antisymmetric : Prop := forall x y:A, R x y -> R y x -> x = y.\n\n    (* for compatibility with Equivalence in  ../PROGRAMS/ALG/  *)\n    Definition equiv := reflexive /\\ transitive /\\ symmetric.\n\n  End General_Properties_of_Relations.\n\n\n\n  Section Sets_of_Relations.\n\n    Record preorder : Prop :=\n      { preord_refl : reflexive; preord_trans : transitive}.\n\n    Record order : Prop :=\n      { ord_refl : reflexive;\n\tord_trans : transitive;\n\tord_antisym : antisymmetric}.\n\n    Record equivalence : Prop :=\n      { equiv_refl : reflexive;\n\tequiv_trans : transitive;\n\tequiv_sym : symmetric}.\n\n    Record PER : Prop :=  {per_sym : symmetric; per_trans : transitive}.\n\n  End Sets_of_Relations.\n\n\n  Section Relations_of_Relations.\n\n    Definition inclusion (R1 R2:relation) : Prop :=\n      forall x y:A, R1 x y -> R2 x y.\n\n    Definition same_relation (R1 R2:relation) : Prop :=\n      inclusion R1 R2 /\\ inclusion R2 R1.\n\n    Definition commut (R1 R2:relation) : Prop :=\n      forall x y:A,\n\tR1 y x -> forall z:A, R2 z y ->  exists2 y' : A, R2 y' x & R1 z y'.\n\n  End Relations_of_Relations.\n\n\nEnd Relation_Definition.\n\nHint Unfold reflexive transitive antisymmetric symmetric: sets v62.\n\nHint Resolve Build_preorder Build_order Build_equivalence Build_PER\n  preord_refl preord_trans ord_refl ord_trans ord_antisym equiv_refl\n  equiv_trans equiv_sym per_sym per_trans: sets v62.\n\nHint Unfold inclusion same_relation commut: sets 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/Relations/Relation_Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.6869254762005246}}
{"text": "Set Implicit Arguments.\n\nRequire Import Arith.\nRequire Import Div2.\nRequire Import Recdef.\n\nFunction ceil_log2_S (n: nat) {wf lt n}: nat :=\n  match n with\n  | 0 => 0\n  | S _ => S (ceil_log2_S (div2 n))\n  end.\nProof.\n  intros.\n  apply lt_div2; auto with arith.\n  apply lt_wf.\nDefined.\n\nLemma ceil_log2_S_def n: ceil_log2_S n =\n  match n with\n  | 0 => 0\n  | S _ => S (ceil_log2_S (div2 n))\n  end.\nProof. functional induction (ceil_log2_S n); auto. Qed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq-serapi/tests/genarg/functional_induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6869024323410897}}
{"text": "Require Export lecture2.\nRequire Import EqNat.\n\n(* # Contents *)\n(*\nIn the next lecture, we will be defining a program logic in the form of a\nseparation logic for our ML-like language. The crucial feature of separation\nlogic is that it allows one to talk about _disjointness_ of memories. In this\npart of the lecture, we will prepare for the next lecture by defining the\nfollowing operations on maps, and proving properties about them:\n\n  munion : map A -> map A -> map A\n  mdisjoint : map A -> map A -> Prop\n\nA crucial thing that you will learn now is reuse existing lemmas on finite maps\nto prove derived properties.\n*)\n\n(* # The union operation on finite maps *)\n(*\nIn order to model separation logic in Coq, we need to have an operation that\ntakes the union of two finite maps:\n\n  munion : map A -> map A -> map A\n\nThat satisfies\n\n  mlookup (munion m1 m2) i =\n    option_union (mlookup m1 i) (mlookup m2 i)\n\nWhere `option_union` is the (left-biased) union operation on the `option` type,\nwhich is defined as follows:\n*)\nDefinition option_union {A} (mx my : option A) : option A :=\n  match mx with\n  | Some x => Some x\n  | None => my\n  end.\n\n(*\nAs is usual, we define the union operation in several stages: 1.) we define it\non raw maps, 2.) we prove that it preserves well-formedness of maps, 3.) lift\nthe operation to maps (which are bundled with a proof of well-formedness) 4.) we\nprove the lookup property on raw maps, and finally 5.) lift that property from\nraw maps to maps.\n*)\nFixpoint munion_raw {A} (m1 m2 : map_raw A) : map_raw A :=\n  match m1, m2 with\n  | mx :: m1, my :: m2 => option_union mx my :: munion_raw m1 m2\n  | [], m2 => m2\n  | m1, [] => m1\n  end.\n\nLemma munion_raw_wf {A} b c (m1 m2 : map_raw A) :\n  map_wf b m1 -> map_wf c m2 -> map_wf (b || c)%bool (munion_raw m1 m2).\nProof.\nrevert b c m2.\ninduction m1; destruct m2; trivial.\ndestruct b; trivial.\nsimpl.\nreplace (is_Some (option_union a o)) with (is_Some a || is_Some o)%bool.\napply IHm1.\ndestruct a, o; trivial.\nQed.\n\nLemma option_union_r {A} (a : option A) : a = option_union a None.\nProof.\ndestruct a; trivial.\nQed.\n\nLemma munion_lookup_raw {A} (m1 m2 : map_raw A) (i : nat) :\n  mlookup_raw (munion_raw m1 m2) i =\n    option_union (mlookup_raw m1 i) (mlookup_raw m2 i).\nProof.\nrevert i m2.\ninduction m1; destruct m2, i; simpl; trivial.\napply option_union_r.\napply option_union_r.\nQed.\n\nDefinition munion {A} (m1 m2 : map A) : map A :=\n  let (m1,Hm1) := m1 in\n  let (m2,Hm2) := m2 in\n  make_map (munion_raw m1 m2) (munion_raw_wf _ _ m1 m2 Hm1 Hm2).\n\nLemma munion_lookup {A} (m1 m2 : map A) (i : nat) :\n  mlookup (munion m1 m2) i =\n    option_union (mlookup m1 i) (mlookup m2 i).\nProof.\ndestruct m1, m2.\napply munion_lookup_raw.\nQed.\n\n(* ## Properties of the union operation *)\n(*\nNow that we have defined the operation `munion` and have proven the lemma\n`munion_lookup`, we prove some properties. The crucial thing to notice is that\nthe lemma `munion_lookup` fully specifies the behavior of the union operation,\nafter we have proven that, we never have to unfold the definition again. Let us\ntake a look at an example.\n*)\nLemma munion_empty_l {A} (m : map A) : munion mempty m = m.\nProof.\n  (* Note that apply also works with bi-implications, like `map_eq`:\n\n    m1 = m2 <-> (forall i : nat, mlookup m1 i = mlookup m2 i)\n\n  *)\n  apply map_eq. intros i.\n  rewrite munion_lookup.\n  rewrite mempty_lookup.\n  simpl.\n  reflexivity.\nQed.\n\nLemma munion_insert_l {A} (m : map A) i x :\n  minsert i x m = munion (msingleton i x) m.\nProof.\n  apply map_eq. intros j. rewrite munion_lookup.\n  (* In order to proceed, we need to make a case distinction between whether\n  the natural numbers `i` and `j` are equal or not. For this we use the lemma:\n\n    Nat.eq_dec: forall n m : nat, {n = m} + {n <> m}\n\n  The lemma says that for any two natural numbers, we have either a proof\n  of `x = y` that they are equal, or a proof of `n <> m` that they are unequal.\n  The result of the lemma is a `sumbool`:\n\n    Inductive sumbool (A B : Prop) : Set :=\n      left : A -> {A} + {B} | right : B -> {A} + {B}\n\n  On which we will perform a case analysis using the `destruct` tactic.\n  *)\n  destruct (Nat.eq_dec i j) as [Heq|Hneq].\n  - subst i.\n    rewrite minsert_lookup. rewrite msingleton_lookup.\n    simpl. reflexivity.\n  - (* In this case, we will use the lemma `insert_lookup_ne`:\n\n        i <> j -> mlookup (minsert i y m) j = mlookup m j\n\n    Note that contrary to most lemmas we have used for rewriting so far, this\n    lemma has a premise `i <> j`. As a result, when we say:\n\n      rewrite minsert_lookup_ne\n\n    We will get an additional goal for proving the premise `i <> j`. In this\n    case, however, it is trivial to prove the premise `i <> j`, after all, we\n    already have a hypothesis `Hneq : i <> j`. As such, we can make use of the\n    `by` argument of the `rewrite` tactic as follows:\n    *)\n    rewrite minsert_lookup_ne by assumption.\n    (*\n    This causes the `assumption` tactic to be used for proving the premise of\n    the lemma that we wish to rewrite with.\n    *)\n    rewrite msingleton_lookup_ne by assumption. \n    (*\n    Note that `msingleton_lookup_ne` has a similar premise.\n    *)\n    simpl. reflexivity.\nQed.\n\n(* ### Exercise *)\n(*\nProve the following properties. In order to prove the properties about maps, you\nshould make use of the lemma `map_eq`, and the lookup lemmas for the various\noperations involved.\n*)\nLemma munion_empty_r {A} (m : map A) : munion mempty m = m.\nProof.\napply map_eq.\ndestruct m.\ntrivial.\nQed.\n\nLemma option_union_assoc {A} (mx my mz : option A) :\n  option_union mx (option_union my mz) = option_union (option_union mx my) mz.\nProof.\ndestruct mx, my, mz; trivial.\nQed.\n\nLtac kongresen := intros; subst; repeat ( rewrite minsert_lookup\n                        || rewrite minsert_lookup_ne\n                        || rewrite munion_lookup\n                        || rewrite mdelete_lookup\n                        || rewrite mdelete_lookup_ne\n                        || rewrite msingleton_lookup\n                        || rewrite msingleton_lookup_ne); intuition eauto.\n\nLemma munion_assoc {A} (m1 m2 m3 : map A) :\n  munion m1 (munion m2 m3) = munion (munion m1 m2) m3.\nProof.\napply map_eq.\nintro i.\nkongresen.\napply option_union_assoc.\nQed.\n\nLemma minsert_union {A} (m1 m2 : map A) i x :\n  minsert i x (munion m1 m2) = munion (minsert i x m1) m2.\nProof.\napply map_eq.\nintro j.\ncompare i j; intro H.\n- rewrite H. kongresen.\n- kongresen.\nQed.\n\nLemma mdelete_union {A} (m1 m2 : map A) i :\n  mdelete i (munion m1 m2) = munion (mdelete i m1) (mdelete i m2).\nProof.\napply map_eq.\nintro j.\ncompare i j; intro H.\n- rewrite H. kongresen.\n- kongresen.\nQed.\n\n(* ## Disjointness of finite maps *)\n(*\nSo far, we have proved associativity of the union operation on finite maps, but\nnot yet commutativity. Unfortunately, this property does not hold\nunconditionally. In case `m1` and `m2` both contain the key `i`, but with\ndifferent values, we do not have `munion m1 m2 = munion m2 m1`. To deal with\nthis issue, we define a relation:\n\n  mdisjoint : map  A -> map A -> Prop\n\nWhich states that two maps are _disjoint_, i.e. they do not have any keys in\ncommon. We can then state commutativity as:\n\n  mdisjoint m1 m2 -> munion m1 m2 = munion m2 m1.\n*)\nDefinition mdisjoint {A} (m1 m2 : map A) : Prop :=\n  forall i, mlookup m1 i = None \\/ mlookup m2 i = None.\n\nLemma option_union_None_r {A} (mx : option A) : option_union mx None = mx.\nProof. destruct mx; simpl; reflexivity. Qed.\n\nLemma munion_comm {A} (m1 m2 : map A) :\n  mdisjoint m1 m2 -> munion m1 m2 = munion m2 m1.\nProof.\n  intros Hdisj. apply map_eq; intros i.\n  rewrite !munion_lookup. (* Using the modifier `!` of the rewrite tactic, we\n  can rewrite using a lemma as many times as possible. *)\n  destruct (Hdisj i) as [Hi | Hi].\n  - rewrite Hi. simpl. rewrite option_union_None_r. reflexivity.\n  - rewrite Hi. simpl. rewrite option_union_None_r. reflexivity.\nQed.\n\n(*\nLet us prove some more properties about disjointness of finite maps.\n*)\nLemma mdisjoint_empty_l {A} (m : map A) : mdisjoint mempty m.\nProof.\n  intros i. left.\n  rewrite mempty_lookup. reflexivity.\nQed.\n\nLemma mdisjoint_sym {A} (m1 m2 : map A) : mdisjoint m1 m2 -> mdisjoint m2 m1.\nProof.\n  intros Hm i.\n  unfold mdisjoint in Hm.\n  (* As we see now, we have a hypothesis\n\n    Hm : forall i : nat, mlookup m1 i = None \\/ mlookup m2 i = None\n\n  Which contains a disjunction below a universal quantifier. As we have seen\n  before, we can use the `destruct` tactic to eliminate disjunctions. But how\n  can we deal with disjunctions below a universal quantifier?\n\n  Well, the answer is simple: we first have to instantiate the universal\n  quantifier. But how do we do that? By the Curry-Howard correspondence, we\n  know that `forall` quantifiers are in fact dependent functions, which means\n  that when we have `H : forall x : A, P x`, we just write `H a` to obtain\n  something of type `P a`.\n\n  So, in this case, we have:\n\n    Hm i : mlookup m1 i = None \\/ mlookup m2 i = None\n\n  On which we can then do a case analysis.\n  *)\n  destruct (Hm i) as [Hm1|Hm2].\n  - right. assumption.\n  - left. assumption.\nQed.\n\n(* ### Exercise *)\n(* Prove the properties below. Do not forget that you can use\n\n  destruct (Nat.eq_dec i j) as [Heq|Hneq].\n  \nTo make a case analysis between whether `i` and `j` are equal or not.\n*)\nLemma mdisjoint_singleton {A} (m : map A) i x :\n  mlookup m i = None -> mdisjoint (msingleton i x) m.\nProof.\nintros H j.\ncompare i j.\n- right. replace j with i. trivial.\n- left. rewrite (msingleton_lookup_ne i j x). trivial. trivial.\nQed.\n\nLemma mdisjoint_singleton_inv {A} (m : map A) i x :\n  mdisjoint (msingleton i x) m -> mlookup m i = None.\nProof.\nintro H.\nspecialize (H i) as []; trivial.\ncontradict H. rewrite msingleton_lookup. discriminate.\nQed.\n\nLemma mdisjoint_union_l {A} (m1 m2 m3 : map A) :\n  mdisjoint m1 m3 ->\n  mdisjoint m2 m3 ->\n  mdisjoint (munion m1 m2) m3.\nProof.\nintros m1m3 m2m3 i.\nrewrite munion_lookup.\nspecialize (m1m3 i) as [-> | ->]; intuition.\nspecialize (m2m3 i) as [-> | ->]; intuition.\nQed.\n\nLemma mdisjoint_union_inv_ll {A} (m1 m2 m3 : map A) :\n  mdisjoint (munion m1 m2) m3 ->\n  mdisjoint m1 m3.\nProof.\nintros H i.\nspecialize (H i) as []; intuition.\nrewrite munion_lookup in H.\ndestruct (mlookup m1 i); intuition.\nQed.\n\nLemma mdisjoint_union_inv_lr {A} (m1 m2 m3 : map A) :\n  mdisjoint (munion m1 m2) m3 ->\n  mdisjoint m2 m3.\nProof.\nintros H i.\nspecialize (H i) as []; intuition.\nrewrite munion_lookup in H.\ndestruct (mlookup m1 i), (mlookup m2 i); intuition.\ndiscriminate.\nQed.\n\n(*\nNote that the properties below can be derived from the properties you have just\nproven. You should not unfold the definition `mdisjoint`.\n*)\nLemma mdisjoint_union_r {A} (m1 m2 m3 : map A) :\n  mdisjoint m3 m1 ->\n  mdisjoint m3 m2 ->\n  mdisjoint m3 (munion m1 m2).\nProof.\nintros.\napply mdisjoint_sym.\napply mdisjoint_union_l; apply mdisjoint_sym; assumption.\nQed.\n\nLemma mdisjoint_union_inv_rl {A} (m1 m2 m3 : map A) :\n  mdisjoint m3 (munion m1 m2) ->\n  mdisjoint m3 m1.\nProof.\nintro H.\neapply mdisjoint_sym, mdisjoint_union_inv_ll, mdisjoint_sym.\neassumption.\nQed.\n\nLemma mdisjoint_union_inv_rr {A} (m1 m2 m3 : map A) :\n  mdisjoint m3 (munion m1 m2) ->\n  mdisjoint m3 m2.\nProof.\nintro H.\neapply mdisjoint_sym, mdisjoint_union_inv_lr, mdisjoint_sym.\neassumption.\nQed.\n\n(* ### Exercise *)\n(*\nAnd finally, some more properties about finite maps that will need later.\n*)\nLemma minsert_singleton {A} i (x y : A) :\n  minsert i x (msingleton i y) = msingleton i x.\nProof.\napply map_eq.\nintro j.\ncompare i j; kongresen.\nQed.\n\nLemma mdelete_singleton {A} i (x : A) :\n  mdelete i (msingleton i x) = mempty.\nProof.\napply map_eq.\nintro j.\ncompare i j; kongresen.\nQed.\n\nLemma mdelete_None {A} (m : map A) i :\n  mlookup m i = None -> mdelete i m = m.\nProof.\nintros.\napply map_eq.\nintro j.\ncompare i j; kongresen.\nQed.\n", "meta": {"author": "carlostome", "repo": "Ohrid-coq", "sha": "128c85ac771f89b8b5f162b4a52bb9fc45fc71ab", "save_path": "github-repos/coq/carlostome-Ohrid-coq", "path": "github-repos/coq/carlostome-Ohrid-coq/Ohrid-coq-128c85ac771f89b8b5f162b4a52bb9fc45fc71ab/lecture3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.8688267898240861, "lm_q1q2_score": 0.6868339190283853}}
{"text": "\n\n(* --------------------------   Description ---------------------------------------------------  \n\n      In this file we formally define the  relation between graphs G and G', where the graph G'\n      is obtained by repeating vertex a of G  to a'. \n\n      Following definition captures this relationship:\n\n      Definition Rep_in (G:UG) (a a':A) (G': UG):=\n       In a G /\\ ~ In a' G /\\ (nodes G') = (add a' G) /\\ edg G' a a' /\\\n       (forall x y, In x G -> In y G-> edg G x y = edg G' x y) /\\ \n       (forall x, x<>a-> edg G x a = edg G' x a').\n\n       Definition Rep G G':= exists a a', Rep_in G a a' G'.\n\n      For a the given graphs G and G' related to each other by above relation we prove \n      many useful properties relating their edges.\n\n      We also establish an isomorphism between the graph G and G'_a using the following \n      function f: \n\n       Let f:= ( fun x:A => match (x == a), (x == a') with\n                            | true, true => x\n                            | true, false => a'\n                            | false, true => a\n                            | false, false => x\n                     end).\n\n      Lemma G_iso_G'_a : iso_usg f G (ind_at N'_a G').\n\n   ------------------------------------------------------------------------------------------*)\n\nRequire Export MoreUG GenIso.\n\nSet Implicit Arguments.\n\nSection Repeat_node.\n\n  Context { A: ordType }.\n\n  (*------ Definition and properties of the relation (Repeat G G' a a') and (Rep G G' -------*)\n\n  Definition Rep_in (G:UG) (a a':A) (G': UG):=\n    In a G /\\ ~ In a' G /\\ (nodes G') = (add a' G) /\\ edg G' a a' /\\\n    (forall x y, In x G -> In y G-> edg G x y = edg G' x y) /\\ (forall x, x<>a-> edg G x a = edg G' x a').\n\n  Definition Rep G G':= exists a a', Rep_in G a a' G'.\n\n  \n  Variable G G': @UG A.\n  Variable a a': A.\n  \n  Hypothesis Hrep: Rep_in G a a' G'.\n  \n  Lemma a_in_G: In a G.\n  Proof. apply Hrep. Qed.\n\n  Lemma a'_not_in_G: ~ In a' G.\n  Proof. apply Hrep. Qed.\n\n  Lemma a'_in_G': In a' G'.\n  Proof. replace (nodes G') with (add a' G). auto. symmetry;apply Hrep. Qed.\n\n  Lemma nodes_GG': (nodes G') = (add a' G).\n  Proof. apply Hrep. Qed.\n\n  Lemma a_not_a': a <> a'.\n  Proof. intro h1; subst a; unfold Rep_in in Hrep; absurd (In a' G); apply Hrep.  Qed.\n\n  Hint Resolve a_in_G a'_not_in_G a'_in_G'  nodes_GG' a_not_a': core.\n  \n\n  Lemma E'_aa': (edg G') a a'.\n  Proof.  { unfold Rep_in in Hrep.\n            destruct Hrep as [hr1 hr]; destruct hr as [hr2 hr]; destruct hr as [hr3 hr].\n            destruct hr as [hr4 hr];destruct hr as [hr5 hr]. auto. } Qed.\n\n  Lemma Exa_E'xa' (x: A):(edg G) x a-> (edg G') x a'.\n  Proof. { unfold Rep_in in Hrep.\n           destruct (x==a) eqn: Hxa.\n           move /eqP in Hxa. subst x;intros;apply Hrep. move /eqP in Hxa.\n           replace (edg G' x a') with (edg G x a). auto. apply Hrep. auto. } Qed.\n\n  Lemma Eay_E'a'y (y: A): (edg G) a y -> (edg G') a' y.\n  Proof. { intros h. apply sym_edg. apply sym_edg in h.  apply Exa_E'xa'; auto. } Qed.\n  \n  Hint Resolve E'_aa' Exa_E'xa' Eay_E'a'y : core. \n\n \n \n  (* --- following three results true only for x y both in G  --- *)\n\n  Lemma In_Exy_eq_E'xy (x y:A): In x G-> In y G-> edg G x y=edg G' x y.\n  Proof. { unfold Rep_in in Hrep. apply Hrep. } Qed.\n  \n  Lemma In_E'xy_Exy (x y:A): In x G -> In y G -> ~ edg G x y  -> ~ edg G' x y.\n  Proof.  { intros h1 h2. replace (edg G' x y) with (edg G x y). auto.\n            apply In_Exy_eq_E'xy;auto. } Qed.\n      \n  Lemma In_E'xy_Exy1 (x y:A): In x G -> In y G  -> edg G' x y -> edg G x y.\n  Proof.  { intros h1 h2. replace (edg G' x y) with (edg G x y). auto.\n            apply In_Exy_eq_E'xy;auto. } Qed.\n\n\nHint Immediate In_E'xy_Exy In_E'xy_Exy1 In_Exy_eq_E'xy: core.\n\n  Lemma Exy_E'xy (x y:A): edg G x y -> edg G' x y.\n  Proof. { intro h1.\n           assert (h2: In x G). eauto.\n           assert (h3: In y G). eauto.\n           replace (edg G' x y) with (edg G x y); auto. } Qed.\n  \n  Hint Immediate Exy_E'xy: core.\n\n\n  (* ---- if niether x nor y is a' then E' x y = E x y --------*)\n\n  Lemma Exy_eq_E'xy (x y:A): x <> a'-> y<> a'->  edg G x y = edg G' x y.\n  Proof. { intros H1 H2.\n           assert (hx: In x G \\/ ~ In x G). eauto.\n           assert (hy: In y G \\/ ~ In y G). eauto.\n           destruct hx as [hx | hx].\n           { (*--  In x G  -*)\n             destruct hy as [hy | hy].\n             { (*-- In y G---*)\n               auto. }\n             { (*---  ~ In y G --*)\n               assert (hyG': ~ In y G' ).\n               { intros h1. replace (nodes G') with (add a' G) in h1.\n                 cut (y = a' \\/ In y G). intro h2.\n                 destruct h2; contradiction. auto. symmetry; apply Hrep.  }\n               replace (edg G x y) with false.\n               replace (edg G' x y) with false.\n               auto. all: symmetry; switch; intros h3.\n               absurd (In y G');eauto. absurd (In y G);eauto. } } \n           { (*--  ~ In x G  -*)\n             assert (hyG': ~ In x G' ).\n              { intros h1. replace (nodes G') with (add a' G) in h1.\n                cut (x = a' \\/ In x G). intro h2.\n                destruct h2; contradiction. auto. symmetry; apply Hrep.  }\n             replace (edg G x y) with false.\n             replace (edg G' x y) with false.\n             auto. all: symmetry; switch; intros h3.\n             absurd (In x G');eauto. absurd (In x G);eauto. }  } Qed.\n\n  \n    Hint Immediate Exy_eq_E'xy: core.\n\n    Lemma E'xy_Exy (x y:A): x<>a'-> y<>a'-> edg G' x y -> edg G x y.\n    Proof. intros h1 h2; replace (edg G' x y) with (edg G x y); auto. Qed.\n           \n    Lemma Exy_E'xy1 (x y:A): x<>a'-> y<>a'-> edg G x y -> edg G' x y.\n    Proof. intros h1 h2; replace (edg G' x y) with (edg G x y); auto. Qed.\n    \n    Hint Immediate E'xy_Exy Exy_E'xy1: core.\n\n   (*------------- other special cases of interest------------*)\n\n    Lemma E'xa_Exa (x:A):  x<> a'->  edg G' x a -> edg G x a.\n    Proof. intros. apply E'xy_Exy; auto.  Qed.\n\n   Lemma Exa_eq_E'xa'(x:A): x <> a ->  edg G x a = edg G' x a'.\n   Proof. apply Hrep. Qed.\n            \n  Lemma Eay_eq_E'a'y (y:A): y<>a  -> edg G a y = edg G' a' y.\n  Proof. { replace (edg G a y) with (edg G y a);\n           replace (edg G' a' y) with (edg G' y a');\n           (eapply Exa_eq_E'xa' || eapply edg_sym); auto. } Qed.\n\n   \n    Lemma E'xa'_Exa (x:A): x <> a->  edg G' x a' -> edg G x a.\n    Proof. { intro h1. replace (edg G' x a') with (edg G x a). auto.\n              auto using Exa_eq_E'xa'. } Qed.\n\n  \n  Hint Immediate E'xa_Exa E'xa'_Exa Exa_eq_E'xa' Eay_eq_E'a'y: core.\n\n  \n\n  (*------------------------- edge properties only in G'--------------*)\n  Lemma E'xa_E'xa' (x:A):  x <> a' -> edg G' x a -> edg G' x a'.\n    Proof.  auto.  Qed.\n\n  Lemma E'xa'_E'xa (x:A): x <> a->  edg G' x a' -> edg G' x a.\n  Proof. intros H1 H2.  specialize ( E'xa'_Exa H1 H2) as H3;  auto. Qed.\n\n  Hint Immediate E'xa_E'xa' E'xa'_E'xa: core.\n    \n  Lemma E'xa_eq_E'xa' (x:A): x <> a-> x<> a'->  edg G' x a = edg G' x a'.\n   Proof. auto. Qed.\n\n   Lemma E'ay_eq_E'a'y (y:A): y<>a -> y<> a'-> edg G' a y = edg G' a' y.\n   Proof. { intros H1 H2.\n           replace (edg G' a y) with (edg G' y a);\n             replace (edg G' a' y) with (edg G' y a').\n           auto using E'xa_eq_E'xa'. all: apply edg_sym. } Qed.\n\n   Hint Immediate E'xa_eq_E'xa' E'ay_eq_E'a'y: core.\n\n   (*------------------- G is Induced subgraph of G'-----------------------*)\n\n   Lemma Ind_sub_GG': Ind_subgraph G G'.\n   Proof.  { split. replace (nodes G') with (add a' G). intros x h1; auto.\n             symmetry. auto.  apply Hrep. } Qed.\n\n   Hint Resolve Ind_sub_GG': core.\n\n   \n\n   (* The term G'_a is used to represent the induced subgraph of G' at G' \\ {a} *)\n   \n   (*-------------------- G'_a is isomorphic to G  -----------------------*)\n\n   Let N'_a:= (rmv a G').\n   Let G'_a:= (ind_at (rmv a G') G').\n\n\n   Lemma NG'_a: N'_a = nodes (ind_at N'_a G').\n   Proof.  apply set_equal;auto. unfold N'_a. auto. \n          cut ((rmv a G') [<=] G'). simpl. auto. auto.  Qed.\n\n\n   Lemma G'_a_is_ind_subgraph: Ind_subgraph (ind_at N'_a G') G'.\n   Proof. split.\n          { simpl. auto. }\n          { intros x y H1 H2. simpl. symmetry;auto. } Qed.\n\n   \n   (*---- Following function is used to establish isomorphism between G and G'_a----*)\n   \n   Let f:= ( fun x:A => match (x == a), (x == a') with\n                            | true, true => x\n                            | true, false => a'\n                            | false, true => a\n                            | false, false => x\n                     end).\n\n   (* -----------  some properties of f to become an isomorphism-------------- *)\n   Lemma fa_is_a':  (f a) = a'.\n   Proof. { unfold f. replace (a==a) with true. replace (a==a') with false.\n            auto. all: symmetry; apply /eqP; auto. } Qed.\n   \n   Lemma fa'_is_a :  (f a') = a.\n   Proof. { unfold f. replace (a'==a') with true. replace (a'==a) with false.\n            auto. all: symmetry; apply /eqP; auto.  } Qed.\n   \n   Lemma fx_is_x (x:A): In x G-> x<>a-> (f x) = x.\n   Proof.  { intros H H1. unfold f. replace (x==a) with false. replace (x==a') with false.\n             auto. all: symmetry; apply /eqP; auto. intro. subst x.\n             absurd (In a' G). apply Hrep. auto.  } Qed.\n   \n   Lemma fx_is_x2 (x:A): x<>a'-> x<>a-> (f x) = x.\n   Proof.  { intros H H1. unfold f. replace (x==a) with false. replace (x==a') with false.\n             auto. all: symmetry; apply /eqP; auto.  } Qed.\n   \n   (* -----   fact: f (f x) = x     ------------ *)\n   Lemma f_is_invertible: forall x : A, f (f x) = x.\n   Proof. { assert (H0: a <> a'). auto.\n            intro x. unfold f.  destruct (x==a) eqn: Hxa;destruct (x==a') eqn: Hxa'.\n            {  absurd (a=a'). auto. move /eqP in Hxa; move /eqP in Hxa'.\n               rewrite <- Hxa; auto.  }\n            { replace (a'== a) with false.\n              { replace (a'==a') with true. symmetry;auto. symmetry;auto. }\n              { symmetry. switch.  move /eqP. intro H1;apply H0;auto. } }\n            { replace (a==a) with true. replace (a==a') with false. all: symmetry;auto.  }\n            { rewrite Hxa. rewrite Hxa'. auto. } } Qed.\n\n   (* -----   fact:   G'_a = (img f G) -------- *)\n   Lemma G'_a_is_imgG: nodes (ind_at N'_a G') = (img f G).\n   Proof. { assert (H0: a <> a'). auto.\n            assert (HGG': nodes G' = add a' G). apply Hrep.\n          assert (H1: Equal (ind_at N'_a G') (img f G)).\n          { split; unfold Subset.\n            { (* -- x in G_a' implies x in img f G --*)\n              intros x H1.\n              assert (H1a: x <> a). rewrite <- NG'_a in H1. \n              { eapply set_rmv_elim2 with (l:= (add a' G)). auto.\n                unfold N'_a in H1. rewrite <- HGG'. auto.  }\n              assert (case_xa': x=a' \\/ x<>a'). eauto.\n              destruct case_xa'.\n              { subst x. replace a' with (f a).  auto. auto using fa_is_a'. }\n              { assert (H2: In x G).\n                { simpl in H1.  cut (In x (add a' G)). eauto.\n                  unfold N'_a in H1. rewrite <- HGG'. eauto. }\n                replace x with (f x). auto. auto using fx_is_x.  } }\n            { (*--- x in img f G implie x in G_a' ---*)\n              intros y H1.\n              assert (H1a: exists x, In x G /\\ y= f x ). auto.\n              destruct H1a as [x H1a]. destruct H1a as [H1a H1b].\n              assert (Hxa: x=a \\/ x<>a). eauto.\n              destruct Hxa.\n              { subst y. replace (f x) with a'. simpl.\n                cut (In a' (add a' G)). cut (In a' N'_a).\n                auto. unfold N'_a. cut(a'<>a). cut (In a' G').  auto.\n                simpl. all: auto.  subst x; symmetry. auto using fa_is_a'. }\n              { subst y. replace (f x) with x. rewrite <- NG'_a.\n                unfold N'_a. cut (In x G').  auto. rewrite HGG'. auto.\n                symmetry; auto using fx_is_x. } } }\n              auto. } Qed. \n   \n   (* -----   fact: f preserves edg relation ----- *)\n   Lemma f_preserves_edg(x y:A):In x G -> In y G -> edg G x y = edg (ind_at N'_a G') (f x) (f y).\n   Proof. { intros hx hy.  assert (H0: a <> a'). auto.\n          assert (H0a: a == a' = false). switch. move /eqP. auto.\n          assert (H0b: (rmv a G') [<=] G'). auto.\n          \n          assert (H0d: In a' G'). simpl;  auto. \n         \n          destruct (x==y) eqn: Hxy.\n          { (* when x =y : easy case*)\n            assert (H1: x=y). auto. subst y.\n            replace (edg G x x) with false.  all: symmetry; switch; auto. }\n          { (* when x <> y : involved case*)\n            assert (H1: x <> y).\n            { move /eqP. switch_in Hxy. auto. }\n            unfold f.\n            destruct (x==a) eqn: Hxa.\n            { (* when x=a*)\n              assert (x=a); auto. subst x. rewrite H0a.\n              assert (y == a =false).\n              { switch. move /eqP. intro H2. subst y. auto. }\n              rewrite H.\n              destruct (y == a') eqn: Hya'.\n              { (*when y=a'*)\n                assert (y=a'). auto. subst y. absurd (In a' G).\n                apply Hrep. auto.  }\n              { (*when y <> a'*)\n                assert (y<>a'). move /eqP. switch. auto. \n                replace (edg G a y) with (edg G' a' y). \n                Focus 2. symmetry. apply Eay_eq_E'a'y;auto.\n                assert (H3: In a' (rmv a G')).  auto.\n                assert (H3a: memb a' G' = memb a' (rmv a G')). symmetry; auto.\n                assert (H4: memb y G' = memb y (rmv a G')). auto. auto. } }\n            { (*when x<>a*)\n              assert (x<> a). move /eqP. switch; auto.\n              destruct (x==a') eqn: Hxa'.\n              { (* when x =a'*)\n                assert (x=a'). auto. subst x. absurd (In a' G).\n                apply Hrep. auto. }\n              { (* when x <> a'*)\n                assert (x<> a'). switch_in Hxa'. intro H2; apply Hxa'; auto.\n                destruct (y==a) eqn: Hya; destruct (y== a') eqn: Hya'.\n                { move /eqP in Hya. move /eqP in Hya'. subst y. contradiction. }\n                { move /eqP in Hya. subst y.\n                  replace (edg G x a) with (edg G' x a').\n                  Focus 2. auto.\n                  assert (memb x G' = memb x (rmv a G')). auto.\n                  assert (memb a' G' = memb a' (rmv a G')). auto.\n                  auto. }\n                { move /eqP in Hya'. subst y.  absurd (In a' G).\n                  apply Hrep. auto.  } \n                { assert (y<>a). move /eqP; switch; auto.\n                  assert (y<>a'). move /eqP; switch; auto.\n                  replace (edg G x y) with (edg G' x y).\n                  Focus 2. auto.\n                  assert (memb x G' = memb x (rmv a G')). auto.\n                  assert (memb y G' = memb y (rmv a G')). auto.\n                  auto. } } } }  } Qed.\n                  \n   Lemma G_iso_G'_a : iso_usg f G (ind_at N'_a G').\n   Proof. { assert (H0: a <> a'). auto.\n          split.\n          { (* ------------------ Proof of the fact that f (f x) = x -----------------*)\n             intros x hx. apply f_is_invertible;auto. }\n          split.\n          { (*----------------- Proof of the fact that G'_a = img f G -------------- *)\n            apply G'_a_is_imgG;auto. }\n          { (*---------------  Proof that isomorphism preserves the edg relation-------*)\n            intros x y. intros hx hy. apply f_preserves_edg;auto.  } } Qed.\n\n   Lemma G_isomorphic_G'_a: exists f, iso_usg f G (ind_at N'_a G').\n     Proof.  exists f. apply G_iso_G'_a;auto. Qed.\n    \nEnd Repeat_node.\n\n\nHint Resolve a_in_G a'_not_in_G a'_in_G' nodes_GG' a_not_a': core.\nHint Resolve E'_aa' Exa_E'xa' Eay_E'a'y : core.\n\n Hint Immediate In_E'xy_Exy In_E'xy_Exy1 In_Exy_eq_E'xy: core.\n Hint Immediate Exy_E'xy Exy_E'xy1 Exy_eq_E'xy: core.\n\n Hint Immediate E'xy_Exy : core.\n\n Hint Immediate E'xa_Exa E'xa'_Exa Exa_eq_E'xa' Eay_eq_E'a'y: core.\n\n Hint Immediate E'xa_E'xa' E'xa'_E'xa: core.\n Hint Immediate E'xa_eq_E'xa' E'ay_eq_E'a'y: core.\n\n Hint Resolve Ind_sub_GG': core.\n \n Hint Resolve G_isomorphic_G'_a: core.\n\n Hint Resolve no_edg1 no_edg2: core.\n Hint Resolve G_iso_G'_a: core.", "meta": {"author": "Abhishek-TIFR", "repo": "wpgt", "sha": "48c612063cbfbe51d6eed41d244c044e43bf8d67", "save_path": "github-repos/coq/Abhishek-TIFR-wpgt", "path": "github-repos/coq/Abhishek-TIFR-wpgt/wpgt-48c612063cbfbe51d6eed41d244c044e43bf8d67/Repeat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6868339179460381}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\nRequire Export ZArith_base.\nRequire Export Rdefinitions.\nLocal Open Scope R_scope.\n\n\n\n\n\n\n\n\n\n\nAxiom Rplus_comm : forall r1 r2:R, r1 + r2 = r2 + r1.\nHint Resolve Rplus_comm: real.\n\n\nAxiom Rplus_assoc : forall r1 r2 r3:R, r1 + r2 + r3 = r1 + (r2 + r3).\nHint Resolve Rplus_assoc: real.\n\n\nAxiom Rplus_opp_r : forall r:R, r + - r = 0.\nHint Resolve Rplus_opp_r: real.\n\n\nAxiom Rplus_0_l : forall r:R, 0 + r = r.\nHint Resolve Rplus_0_l: real.\n\n\n\n\n\n\nAxiom Rmult_comm : forall r1 r2:R, r1 * r2 = r2 * r1.\nHint Resolve Rmult_comm: real.\n\n\nAxiom Rmult_assoc : forall r1 r2 r3:R, r1 * r2 * r3 = r1 * (r2 * r3).\nHint Resolve Rmult_assoc: real.\n\n\nAxiom Rinv_l : forall r:R, r <> 0 -> / r * r = 1.\nHint Resolve Rinv_l: real.\n\n\nAxiom Rmult_1_l : forall r:R, 1 * r = r.\nHint Resolve Rmult_1_l: real.\n\n\nAxiom R1_neq_R0 : 1 <> 0.\nHint Resolve R1_neq_R0: real.\n\n\n\n\n\n\nAxiom\nRmult_plus_distr_l : forall r1 r2 r3:R, r1 * (r2 + r3) = r1 * r2 + r1 * r3.\nHint Resolve Rmult_plus_distr_l: real.\n\n\n\n\n\n\n\n\n\nAxiom total_order_T : forall r1 r2:R, {r1 < r2} + {r1 = r2} + {r1 > r2}.\n\n\n\n\n\n\nAxiom Rlt_asym : forall r1 r2:R, r1 < r2 -> ~ r2 < r1.\n\n\nAxiom Rlt_trans : forall r1 r2 r3:R, r1 < r2 -> r2 < r3 -> r1 < r3.\n\n\nAxiom Rplus_lt_compat_l : forall r r1 r2:R, r1 < r2 -> r + r1 < r + r2.\n\n\nAxiom\nRmult_lt_compat_l : forall r r1 r2:R, 0 < r -> r1 < r2 -> r * r1 < r * r2.\n\nHint Resolve Rlt_asym Rplus_lt_compat_l Rmult_lt_compat_l: real.\n\n\n\n\n\n\nFixpoint INR (n:nat) : R :=\nmatch n with\n| O => 0\n| S O => 1\n| S n => INR n + 1\nend.\nArguments INR n%nat.\n\n\n\n\n\n\n\nAxiom archimed : forall r:R, IZR (up r) > r /\\ IZR (up r) - r <= 1.\n\n\n\n\n\n\nDefinition is_upper_bound (E:R -> Prop) (m:R) := forall x:R, E x -> x <= m.\n\n\nDefinition bound (E:R -> Prop) :=  exists m : R, is_upper_bound E m.\n\n\nDefinition is_lub (E:R -> Prop) (m:R) :=\nis_upper_bound E m /\\ (forall b:R, is_upper_bound E b -> m <= b).\n\n\nAxiom\ncompleteness :\nforall E:R -> Prop,\nbound E -> (exists x : R, E x) -> { m:R | is_lub E m }.\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/Raxioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.6868339066647965}}
{"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 ZArith_base.\nRequire Import ZArithRing.\nRequire Import Zcomplements.\nRequire Import Zdiv.\nRequire Import Wf_nat.\n\n(** For compatibility reasons, this Open Scope isn't local as it should *)\n\nOpen Scope Z_scope.\n\n(** This file contains some notions of number theory upon Z numbers:\n     - a divisibility predicate [Z.divide]\n     - a gcd predicate [gcd]\n     - Euclid algorithm [euclid]\n     - a relatively prime predicate [rel_prime]\n     - a prime predicate [prime]\n     - properties of the efficient [Z.gcd] function\n*)\n\nNotation Zgcd := Z.gcd (compat \"8.6\").\nNotation Zggcd := Z.ggcd (compat \"8.6\").\nNotation Zggcd_gcd := Z.ggcd_gcd (compat \"8.6\").\nNotation Zggcd_correct_divisors := Z.ggcd_correct_divisors (compat \"8.6\").\nNotation Zgcd_divide_l := Z.gcd_divide_l (compat \"8.6\").\nNotation Zgcd_divide_r := Z.gcd_divide_r (compat \"8.6\").\nNotation Zgcd_greatest := Z.gcd_greatest (compat \"8.6\").\nNotation Zgcd_nonneg := Z.gcd_nonneg (compat \"8.6\").\nNotation Zggcd_opp := Z.ggcd_opp (compat \"8.6\").\n\n(** The former specialized inductive predicate [Z.divide] is now\n    a generic existential predicate. *)\n\nNotation Zdivide := Z.divide (compat \"8.6\").\n\n(** Its former constructor is now a pseudo-constructor. *)\n\nDefinition Zdivide_intro a b q (H:b=q*a) : Z.divide a b := ex_intro _ q H.\n\n(** Results concerning divisibility*)\n\nNotation Zdivide_refl := Z.divide_refl (compat \"8.6\").\nNotation Zone_divide := Z.divide_1_l (only parsing).\nNotation Zdivide_0 := Z.divide_0_r (only parsing).\nNotation Zmult_divide_compat_l := Z.mul_divide_mono_l (only parsing).\nNotation Zmult_divide_compat_r := Z.mul_divide_mono_r (only parsing).\nNotation Zdivide_plus_r := Z.divide_add_r (only parsing).\nNotation Zdivide_minus_l := Z.divide_sub_r (only parsing).\nNotation Zdivide_mult_l := Z.divide_mul_l (only parsing).\nNotation Zdivide_mult_r := Z.divide_mul_r (only parsing).\nNotation Zdivide_factor_r := Z.divide_factor_l (only parsing).\nNotation Zdivide_factor_l := Z.divide_factor_r (only parsing).\n\nLemma Zdivide_opp_r a b : (a | b) -> (a | - b).\nProof. apply Z.divide_opp_r. Qed.\n\nLemma Zdivide_opp_r_rev a b : (a | - b) -> (a | b).\nProof. apply Z.divide_opp_r. Qed.\n\nLemma Zdivide_opp_l a b : (a | b) -> (- a | b).\nProof. apply Z.divide_opp_l. Qed.\n\nLemma Zdivide_opp_l_rev a b : (- a | b) -> (a | b).\nProof. apply Z.divide_opp_l. Qed.\n\nTheorem Zdivide_Zabs_l a b : (Z.abs a | b) -> (a | b).\nProof. apply Z.divide_abs_l. Qed.\n\nTheorem Zdivide_Zabs_inv_l a b : (a | b) -> (Z.abs a | b).\nProof. apply Z.divide_abs_l. Qed.\n\nHint Resolve Z.divide_refl Z.divide_1_l Z.divide_0_r: zarith.\nHint Resolve Z.mul_divide_mono_l Z.mul_divide_mono_r: zarith.\nHint Resolve Z.divide_add_r Zdivide_opp_r Zdivide_opp_r_rev Zdivide_opp_l\n  Zdivide_opp_l_rev Z.divide_sub_r Z.divide_mul_l Z.divide_mul_r\n  Z.divide_factor_l Z.divide_factor_r: zarith.\n\n(** Auxiliary result. *)\n\nLemma Zmult_one x y : x >= 0 -> x * y = 1 -> x = 1.\nProof.\n Z.swap_greater. apply Z.eq_mul_1_nonneg.\nQed.\n\n(** Only [1] and [-1] divide [1]. *)\n\nNotation Zdivide_1 := Z.divide_1_r (only parsing).\n\n(** If [a] divides [b] and [b] divides [a] then [a] is [b] or [-b]. *)\n\nNotation Zdivide_antisym := Z.divide_antisym (compat \"8.6\").\nNotation Zdivide_trans := Z.divide_trans (compat \"8.6\").\n\n(** If [a] divides [b] and [b<>0] then [|a| <= |b|]. *)\n\nLemma Zdivide_bounds a b : (a | b) -> b <> 0 -> Z.abs a <= Z.abs b.\nProof.\n intros H Hb.\n rewrite <- Z.divide_abs_l, <- Z.divide_abs_r in H.\n apply Z.abs_pos in Hb.\n now apply Z.divide_pos_le.\nQed.\n\n(** [Z.divide] can be expressed using [Z.modulo]. *)\n\nLemma Zmod_divide : forall a b, b<>0 -> a mod b = 0 -> (b | a).\nProof.\n apply Z.mod_divide.\nQed.\n\nLemma Zdivide_mod : forall a b, (b | a) -> a mod b = 0.\nProof.\n intros a b (c,->); apply Z_mod_mult.\nQed.\n\n(** [Z.divide] is hence decidable *)\n\nLemma Zdivide_dec a b : {(a | b)} + {~ (a | b)}.\nProof.\n destruct (Z.eq_dec a 0) as [Ha|Ha].\n  destruct (Z.eq_dec b 0) as [Hb|Hb].\n   left; subst; apply Z.divide_0_r.\n   right. subst. contradict Hb. now apply Z.divide_0_l.\n  destruct (Z.eq_dec (b mod a) 0).\n   left. now apply Z.mod_divide.\n   right. now rewrite <- Z.mod_divide.\nDefined.\n\nTheorem Zdivide_Zdiv_eq a b : 0 < a -> (a | b) ->  b = a * (b / a).\nProof.\n intros Ha H.\n rewrite (Z.div_mod b a) at 1; auto with zarith.\n rewrite Zdivide_mod; auto with zarith.\nQed.\n\nTheorem Zdivide_Zdiv_eq_2 a b c :\n 0 < a -> (a | b) -> (c * b) / a = c * (b / a).\nProof.\n intros. apply Z.divide_div_mul_exact; auto with zarith.\nQed.\n\nTheorem Zdivide_le: forall a b : Z,\n 0 <= a -> 0 < b -> (a | b) ->  a <= b.\nProof.\n intros. now apply Z.divide_pos_le.\nQed.\n\nTheorem Zdivide_Zdiv_lt_pos a b :\n 1 < a -> 0 < b -> (a | b) ->  0 < b / a < b .\nProof.\n  intros H1 H2 H3; split.\n  apply Z.mul_pos_cancel_l with a; auto with zarith.\n  rewrite <- Zdivide_Zdiv_eq; auto with zarith.\n  now apply Z.div_lt.\nQed.\n\nLemma Zmod_div_mod n m a:\n 0 < n -> 0 < m -> (n | m) -> a mod n = (a mod m) mod n.\nProof.\n  intros H1 H2 (p,Hp).\n  rewrite (Z.div_mod a m) at 1; auto with zarith.\n  rewrite Hp at 1.\n  rewrite Z.mul_shuffle0, Z.add_comm, Z.mod_add; auto with zarith.\nQed.\n\nLemma Zmod_divide_minus a b c:\n 0 < b -> a mod b = c -> (b | a - c).\nProof.\n  intros H H1. apply Z.mod_divide; auto with zarith.\n  rewrite Zminus_mod; auto with zarith.\n  rewrite H1. rewrite <- (Z.mod_small c b) at 1.\n  rewrite Z.sub_diag, Z.mod_0_l; auto with zarith.\n  subst. now apply Z.mod_pos_bound.\nQed.\n\nLemma Zdivide_mod_minus a b c:\n 0 <= c < b -> (b | a - c) -> a mod b = c.\nProof.\n  intros (H1, H2) H3.\n  assert (0 < b) by Z.order.\n  replace a with ((a - c) + c); auto with zarith.\n  rewrite Z.add_mod; auto with zarith.\n  rewrite (Zdivide_mod (a-c) b); try rewrite Z.add_0_l; auto with zarith.\n  rewrite Z.mod_mod; try apply Zmod_small; auto with zarith.\nQed.\n\n(** * Greatest common divisor (gcd). *)\n\n(** There is no unicity of the gcd; hence we define the predicate\n    [Zis_gcd a b g] expressing that [g] is a gcd of [a] and [b].\n    (We show later that the [gcd] is actually unique if we discard its sign.) *)\n\nInductive Zis_gcd (a b g:Z) : Prop :=\n Zis_gcd_intro :\n  (g | a) ->\n  (g | b) ->\n  (forall x, (x | a) -> (x | b) -> (x | g)) ->\n  Zis_gcd a b g.\n\n(** Trivial properties of [gcd] *)\n\nLemma Zis_gcd_sym : forall a b d, Zis_gcd a b d -> Zis_gcd b a d.\nProof.\n  induction 1; constructor; intuition.\nQed.\n\nLemma Zis_gcd_0 : forall a, Zis_gcd a 0 a.\nProof.\n  constructor; auto with zarith.\nQed.\n\nLemma Zis_gcd_1 : forall a, Zis_gcd a 1 1.\nProof.\n  constructor; auto with zarith.\nQed.\n\nLemma Zis_gcd_refl : forall a, Zis_gcd a a a.\nProof.\n  constructor; auto with zarith.\nQed.\n\nLemma Zis_gcd_minus : forall a b d, Zis_gcd a (- b) d -> Zis_gcd b a d.\nProof.\n  induction 1; constructor; intuition.\nQed.\n\nLemma Zis_gcd_opp : forall a b d, Zis_gcd a b d -> Zis_gcd b a (- d).\nProof.\n  induction 1; constructor; intuition.\nQed.\n\nLemma Zis_gcd_0_abs a : Zis_gcd 0 a (Z.abs a).\nProof.\n  apply Zabs_ind.\n  intros; apply Zis_gcd_sym; apply Zis_gcd_0; auto.\n  intros; apply Zis_gcd_opp; apply Zis_gcd_0; auto.\nQed.\n\nHint Resolve Zis_gcd_sym Zis_gcd_0 Zis_gcd_minus Zis_gcd_opp: zarith.\n\nTheorem Zis_gcd_unique: forall a b c d : Z,\n Zis_gcd a b c -> Zis_gcd a b d ->  c = d \\/ c = (- d).\nProof.\nintros a b c d [Hc1 Hc2 Hc3] [Hd1 Hd2 Hd3].\nassert (c|d) by auto.\nassert (d|c) by auto.\napply Z.divide_antisym; auto.\nQed.\n\n\n(** * Extended Euclid algorithm. *)\n\n(** Euclid's algorithm to compute the [gcd] mainly relies on\n    the following property. *)\n\nLemma Zis_gcd_for_euclid :\n  forall a b d q:Z, Zis_gcd b (a - q * b) d -> Zis_gcd a b d.\nProof.\n  simple induction 1; constructor; intuition.\n  replace a with (a - q * b + q * b). auto with zarith. ring.\nQed.\n\nLemma Zis_gcd_for_euclid2 :\n  forall b d q r:Z, Zis_gcd r b d -> Zis_gcd b (b * q + r) d.\nProof.\n  simple induction 1; constructor; intuition.\n  apply H2; auto.\n  replace r with (b * q + r - b * q). auto with zarith. ring.\nQed.\n\n(** We implement the extended version of Euclid's algorithm,\n    i.e. the one computing Bezout's coefficients as it computes\n    the [gcd]. We follow the algorithm given in Knuth's\n    \"Art of Computer Programming\", vol 2, page 325. *)\n\nSection extended_euclid_algorithm.\n\n  Variables a b : Z.\n\n  (** The specification of Euclid's algorithm is the existence of\n      [u], [v] and [d] such that [ua+vb=d] and [(gcd a b d)]. *)\n\n  Inductive Euclid : Set :=\n    Euclid_intro :\n    forall u v d:Z, u * a + v * b = d -> Zis_gcd a b d -> Euclid.\n\n  (** The recursive part of Euclid's algorithm uses well-founded\n      recursion of non-negative integers. It maintains 6 integers\n      [u1,u2,u3,v1,v2,v3] such that the following invariant holds:\n      [u1*a+u2*b=u3] and [v1*a+v2*b=v3] and [gcd(u3,v3)=gcd(a,b)].\n      *)\n\n  Lemma euclid_rec :\n    forall v3:Z,\n      0 <= v3 ->\n      forall u1 u2 u3 v1 v2:Z,\n\tu1 * a + u2 * b = u3 ->\n\tv1 * a + v2 * b = v3 ->\n\t(forall d:Z, Zis_gcd u3 v3 d -> Zis_gcd a b d) -> Euclid.\n  Proof.\n    intros v3 Hv3; generalize Hv3; pattern v3.\n    apply Zlt_0_rec.\n    clear v3 Hv3; intros.\n    destruct (Z_zerop x) as [Heq|Hneq].\n    apply Euclid_intro with (u := u1) (v := u2) (d := u3).\n    assumption.\n    apply H3.\n    rewrite Heq; auto with zarith.\n    set (q := u3 / x) in *.\n    assert (Hq : 0 <= u3 - q * x < x).\n    replace (u3 - q * x) with (u3 mod x).\n    apply Z_mod_lt; omega.\n    assert (xpos : x > 0). omega.\n    generalize (Z_div_mod_eq u3 x xpos).\n    unfold q.\n    intro eq; pattern u3 at 2; rewrite eq; ring.\n    apply (H (u3 - q * x) Hq (proj1 Hq) v1 v2 x (u1 - q * v1) (u2 - q * v2)).\n    tauto.\n    replace ((u1 - q * v1) * a + (u2 - q * v2) * b) with\n      (u1 * a + u2 * b - q * (v1 * a + v2 * b)).\n    rewrite H1; rewrite H2; trivial.\n    ring.\n    intros; apply H3.\n    apply Zis_gcd_for_euclid with q; assumption.\n    assumption.\n  Qed.\n\n  (** We get Euclid's algorithm by applying [euclid_rec] on\n      [1,0,a,0,1,b] when [b>=0] and [1,0,a,0,-1,-b] when [b<0]. *)\n\n  Lemma euclid : Euclid.\n  Proof.\n    case (Z_le_gt_dec 0 b); intro.\n    intros;\n      apply euclid_rec with\n\t(u1 := 1) (u2 := 0) (u3 := a) (v1 := 0) (v2 := 1) (v3 := b);\n\tauto with zarith; ring.\n    intros;\n      apply euclid_rec with\n\t(u1 := 1) (u2 := 0) (u3 := a) (v1 := 0) (v2 := -1) (v3 := - b);\n\tauto with zarith; try ring.\n  Qed.\n\nEnd extended_euclid_algorithm.\n\nTheorem Zis_gcd_uniqueness_apart_sign :\n  forall a b d d':Z, Zis_gcd a b d -> Zis_gcd a b d' -> d = d' \\/ d = - d'.\nProof.\n  simple induction 1.\n  intros H1 H2 H3; simple induction 1; intros.\n  generalize (H3 d' H4 H5); intro Hd'd.\n  generalize (H6 d H1 H2); intro Hdd'.\n  exact (Z.divide_antisym d d' Hdd' Hd'd).\nQed.\n\n(** * Bezout's coefficients *)\n\nInductive Bezout (a b d:Z) : Prop :=\n  Bezout_intro : forall u v:Z, u * a + v * b = d -> Bezout a b d.\n\n(** Existence of Bezout's coefficients for the [gcd] of [a] and [b] *)\n\nLemma Zis_gcd_bezout : forall a b d:Z, Zis_gcd a b d -> Bezout a b d.\nProof.\n  intros a b d Hgcd.\n  elim (euclid a b); intros u v d0 e g.\n  generalize (Zis_gcd_uniqueness_apart_sign a b d d0 Hgcd g).\n  intro H; elim H; clear H; intros.\n  apply Bezout_intro with u v.\n  rewrite H; assumption.\n  apply Bezout_intro with (- u) (- v).\n  rewrite H; rewrite <- e; ring.\nQed.\n\n(** gcd of [ca] and [cb] is [c gcd(a,b)]. *)\n\nLemma Zis_gcd_mult :\n  forall a b c d:Z, Zis_gcd a b d -> Zis_gcd (c * a) (c * b) (c * d).\nProof.\n  intros a b c d; simple induction 1. constructor; auto with zarith.\n  intros x Ha Hb.\n  elim (Zis_gcd_bezout a b d H). intros u v Huv.\n  elim Ha; intros a' Ha'.\n  elim Hb; intros b' Hb'.\n  apply Zdivide_intro with (u * a' + v * b').\n  rewrite <- Huv.\n  replace (c * (u * a + v * b)) with (u * (c * a) + v * (c * b)).\n  rewrite Ha'; rewrite Hb'; ring.\n  ring.\nQed.\n\n\n(** * Relative primality *)\n\nDefinition rel_prime (a b:Z) : Prop := Zis_gcd a b 1.\n\n(** Bezout's theorem: [a] and [b] are relatively prime if and\n    only if there exist [u] and [v] such that [ua+vb = 1]. *)\n\nLemma rel_prime_bezout : forall a b:Z, rel_prime a b -> Bezout a b 1.\nProof.\n  intros a b; exact (Zis_gcd_bezout a b 1).\nQed.\n\nLemma bezout_rel_prime : forall a b:Z, Bezout a b 1 -> rel_prime a b.\nProof.\n  simple induction 1; constructor; auto with zarith.\n  intros. rewrite <- H0; auto with zarith.\nQed.\n\n(** Gauss's theorem: if [a] divides [bc] and if [a] and [b] are\n    relatively prime, then [a] divides [c]. *)\n\nTheorem Gauss : forall a b c:Z, (a | b * c) -> rel_prime a b -> (a | c).\nProof.\n  intros. elim (rel_prime_bezout a b H0); intros.\n  replace c with (c * 1); [ idtac | ring ].\n  rewrite <- H1.\n  replace (c * (u * a + v * b)) with (c * u * a + v * (b * c));\n    [ eauto with zarith | ring ].\nQed.\n\n(** If [a] is relatively prime to [b] and [c], then it is to [bc] *)\n\nLemma rel_prime_mult :\n  forall a b c:Z, rel_prime a b -> rel_prime a c -> rel_prime a (b * c).\nProof.\n  intros a b c Hb Hc.\n  elim (rel_prime_bezout a b Hb); intros.\n  elim (rel_prime_bezout a c Hc); intros.\n  apply bezout_rel_prime.\n  apply Bezout_intro with\n    (u := u * u0 * a + v0 * c * u + u0 * v * b) (v := v * v0).\n  rewrite <- H.\n  replace (u * a + v * b) with ((u * a + v * b) * 1); [ idtac | ring ].\n  rewrite <- H0.\n  ring.\nQed.\n\nLemma rel_prime_cross_prod :\n  forall a b c d:Z,\n    rel_prime a b ->\n    rel_prime c d -> b > 0 -> d > 0 -> a * d = b * c -> a = c /\\ b = d.\nProof.\n  intros a b c d; intros.\n  elim (Z.divide_antisym b d).\n  split; auto with zarith.\n  rewrite H4 in H3.\n  rewrite Z.mul_comm in H3.\n  apply Z.mul_reg_l with d; auto with zarith.\n  intros; omega.\n  apply Gauss with a.\n  rewrite H3.\n  auto with zarith.\n  red; auto with zarith.\n  apply Gauss with c.\n  rewrite Z.mul_comm.\n  rewrite <- H3.\n  auto with zarith.\n  red; auto with zarith.\nQed.\n\n(** After factorization by a gcd, the original numbers are relatively prime. *)\n\nLemma Zis_gcd_rel_prime :\n  forall a b g:Z,\n    b > 0 -> g >= 0 -> Zis_gcd a b g -> rel_prime (a / g) (b / g).\nProof.\n  intros a b g; intros.\n  assert (g <> 0).\n  intro.\n  elim H1; intros.\n  elim H4; intros.\n  rewrite H2 in H6; subst b; omega.\n  unfold rel_prime.\n  destruct H1.\n  destruct H1 as (a',H1).\n  destruct H3 as (b',H3).\n  replace (a/g) with a';\n    [|rewrite H1; rewrite Z_div_mult; auto with zarith].\n  replace (b/g) with b';\n    [|rewrite H3; rewrite Z_div_mult; auto with zarith].\n  constructor.\n  exists a'; auto with zarith.\n  exists b'; auto with zarith.\n  intros x (xa,H5) (xb,H6).\n  destruct (H4 (x*g)) as (x',Hx').\n  exists xa; rewrite Z.mul_assoc; rewrite <- H5; auto.\n  exists xb; rewrite Z.mul_assoc; rewrite <- H6; auto.\n  replace g with (1*g) in Hx'; auto with zarith.\n  do 2 rewrite Z.mul_assoc in Hx'.\n  apply Z.mul_reg_r in Hx'; trivial.\n  rewrite Z.mul_1_r in Hx'.\n  exists x'; auto with zarith.\nQed.\n\nTheorem rel_prime_sym: forall a b, rel_prime a b -> rel_prime b a.\nProof.\n  intros a b H; auto with zarith.\n  red; apply Zis_gcd_sym; auto with zarith.\nQed.\n\nTheorem rel_prime_div: forall p q r,\n rel_prime p q -> (r | p) -> rel_prime r q.\nProof.\n  intros p q r H (u, H1); subst.\n  inversion_clear H as [H1 H2 H3].\n  red; apply Zis_gcd_intro; try apply Z.divide_1_l.\n  intros x H4 H5; apply H3; auto.\n  apply Z.divide_mul_r; auto.\nQed.\n\nTheorem rel_prime_1: forall n, rel_prime 1 n.\nProof.\n  intros n; red; apply Zis_gcd_intro; auto.\n  exists 1; auto with zarith.\n  exists n; auto with zarith.\nQed.\n\nTheorem not_rel_prime_0: forall n, 1 < n -> ~ rel_prime 0 n.\nProof.\n  intros n H H1; absurd (n = 1 \\/ n = -1).\n  intros [H2 | H2]; subst; contradict H; auto with zarith.\n  case (Zis_gcd_unique  0 n n 1); auto.\n  apply Zis_gcd_intro; auto.\n  exists 0; auto with zarith.\n  exists 1; auto with zarith.\nQed.\n\nTheorem rel_prime_mod: forall p q, 0 < q ->\n rel_prime p q -> rel_prime (p mod q) q.\nProof.\n  intros p q H H0.\n  assert (H1: Bezout p q 1).\n  apply rel_prime_bezout; auto.\n  inversion_clear H1 as [q1 r1 H2].\n  apply bezout_rel_prime.\n  apply Bezout_intro with q1  (r1 + q1 * (p / q)).\n  rewrite <- H2.\n  pattern p at 3; rewrite (Z_div_mod_eq p q); try ring; auto with zarith.\nQed.\n\nTheorem rel_prime_mod_rev: forall p q, 0 < q ->\n rel_prime (p mod q) q -> rel_prime p q.\nProof.\n  intros p q H H0.\n  rewrite (Z_div_mod_eq p q); auto with zarith; red.\n  apply Zis_gcd_sym; apply Zis_gcd_for_euclid2; auto with zarith.\nQed.\n\nTheorem Zrel_prime_neq_mod_0: forall a b, 1 < b -> rel_prime a b -> a mod b <> 0.\nProof.\n  intros a b H H1 H2.\n  case (not_rel_prime_0 _ H).\n  rewrite <- H2.\n  apply rel_prime_mod; auto with zarith.\nQed.\n\n(** * Primality *)\n\nInductive prime (p:Z) : Prop :=\n  prime_intro :\n    1 < p -> (forall n:Z, 1 <= n < p -> rel_prime n p) -> prime p.\n\n(** The sole divisors of a prime number [p] are [-1], [1], [p] and [-p]. *)\n\nLemma prime_divisors :\n  forall p:Z,\n    prime p -> forall a:Z, (a | p) -> a = -1 \\/ a = 1 \\/ a = p \\/ a = - p.\nProof.\n  destruct 1; intros.\n  assert\n    (a = - p \\/ - p < a < -1 \\/ a = -1 \\/ a = 0 \\/ a = 1 \\/ 1 < a < p \\/ a = p).\n  { assert (Z.abs a <= Z.abs p) as H2.\n      apply Zdivide_bounds; [ assumption | omega ].\n    revert H2.\n    pattern (Z.abs a); apply Zabs_ind; pattern (Z.abs p); apply Zabs_ind;\n    intros; omega. }\n  intuition idtac.\n  (* -p < a < -1 *)\n  - absurd (rel_prime (- a) p); intuition.\n    inversion H2.\n    assert (- a | - a) by auto with zarith.\n    assert (- a | p) by auto with zarith.\n    apply H7, Z.divide_1_r in H8; intuition.\n  (* a = 0 *)\n  - inversion H1. subst a; omega.\n  (* 1 < a < p *)\n  - absurd (rel_prime a p); intuition.\n    inversion H2.\n    assert (a | a) by auto with zarith.\n    assert (a | p) by auto with zarith.\n    apply H7, Z.divide_1_r in H8; intuition.\nQed.\n\n(** A prime number is relatively prime with any number it does not divide *)\n\nLemma prime_rel_prime :\n  forall p:Z, prime p -> forall a:Z, ~ (p | a) -> rel_prime p a.\nProof.\n  intros; constructor; intros; auto with zarith.\n  apply prime_divisors in H1; intuition; subst; auto with zarith.\n  - absurd (p | a); auto with zarith.\n  - absurd (p | a); intuition.\nQed.\n\nHint Resolve prime_rel_prime: zarith.\n\n(** As a consequence, a prime number is relatively prime with smaller numbers *)\n\nTheorem rel_prime_le_prime:\n forall a p, prime p -> 1 <=  a < p -> rel_prime a p.\nProof.\n  intros a p Hp [H1 H2].\n  apply rel_prime_sym; apply prime_rel_prime; auto.\n  intros [q Hq]; subst a.\n  case (Z.le_gt_cases q 0); intros Hl.\n  absurd (q * p <= 0 * p); auto with zarith.\n  absurd (1 * p <= q * p); auto with zarith.\nQed.\n\n\n(** If a prime [p] divides [ab] then it divides either [a] or [b] *)\n\nLemma prime_mult :\n  forall p:Z, prime p -> forall a b:Z, (p | a * b) -> (p | a) \\/ (p | b).\nProof.\n  intro p; simple induction 1; intros.\n  case (Zdivide_dec p a); intuition.\n  right; apply Gauss with a; auto with zarith.\nQed.\n\nLemma not_prime_0: ~ prime 0.\nProof.\n  intros H1; case (prime_divisors _ H1 2); auto with zarith.\nQed.\n\nLemma not_prime_1: ~ prime 1.\nProof.\n  intros H1; absurd (1 < 1); auto with zarith.\n  inversion H1; auto.\nQed.\n\nLemma prime_2: prime 2.\nProof.\n  apply prime_intro; auto with zarith.\n  intros n (H,H'); Z.le_elim H; auto with zarith.\n  - contradict H'; auto with zarith.\n  - subst n. constructor; auto with zarith.\nQed.\n\nTheorem prime_3: prime 3.\nProof.\n  apply prime_intro; auto with zarith.\n  intros n (H,H'); Z.le_elim H; auto with zarith.\n  - replace n with 2 by omega.\n    constructor; auto with zarith.\n    intros x (q,Hq) (q',Hq').\n    exists (q' - q). ring_simplify. now rewrite <- Hq, <- Hq'.\n  - replace n with 1 by trivial.\n    constructor; auto with zarith.\nQed.\n\nTheorem prime_ge_2 p : prime p ->  2 <= p.\nProof.\n  intros (Hp,_); auto with zarith.\nQed.\n\nDefinition prime' p := 1<p /\\ (forall n, 1<n<p -> ~ (n|p)).\n\nLemma Z_0_1_more x : 0<=x -> x=0 \\/ x=1 \\/ 1<x.\nProof.\n intros H. Z.le_elim H; auto.\n apply Z.le_succ_l in H. change (1 <= x) in H. Z.le_elim H; auto.\nQed.\n\nTheorem prime_alt p : prime' p <-> prime p.\nProof.\n  split; intros (Hp,H).\n  - (* prime -> prime' *)\n    constructor; trivial; intros n Hn.\n    constructor; auto with zarith; intros x Hxn Hxp.\n    rewrite <- Z.divide_abs_l in Hxn, Hxp |- *.\n    assert (Hx := Z.abs_nonneg x).\n    set (y:=Z.abs x) in *; clearbody y; clear x; rename y into x.\n    destruct (Z_0_1_more x Hx) as [->|[->|Hx']].\n    + exfalso. apply Z.divide_0_l in Hxn. omega.\n    + now exists 1.\n    + elim (H x); auto.\n      split; trivial.\n      apply Z.le_lt_trans with n; auto with zarith.\n      apply Z.divide_pos_le; auto with zarith.\n  - (* prime' -> prime *)\n    constructor; trivial. intros n Hn Hnp.\n    case (Zis_gcd_unique n p n 1); auto with zarith.\n    constructor; auto with zarith.\n    apply H; auto with zarith.\nQed.\n\nTheorem square_not_prime: forall a, ~ prime (a * a).\nProof.\n  intros a Ha.\n  rewrite <- (Z.abs_square a) in Ha.\n  assert (H:=Z.abs_nonneg a).\n  set (b:=Z.abs a) in *; clearbody b; clear a; rename b into a.\n  rewrite <- prime_alt in Ha; destruct Ha as (Ha,Ha').\n  assert (H' : 1 < a) by now apply (Z.square_lt_simpl_nonneg 1).\n  apply (Ha' a).\n  + split; trivial.\n    rewrite <- (Z.mul_1_l a) at 1. apply Z.mul_lt_mono_pos_r; omega.\n  + exists a; auto.\nQed.\n\nTheorem prime_div_prime: forall p q,\n prime p -> prime q -> (p | q) -> p = q.\nProof.\n  intros p q H H1 H2;\n  assert (Hp: 0 < p); try apply Z.lt_le_trans with 2; try apply prime_ge_2; auto with zarith.\n  assert (Hq: 0 < q); try apply Z.lt_le_trans with 2; try apply prime_ge_2; auto with zarith.\n  case prime_divisors with (2 := H2); auto.\n  intros H4; contradict Hp; subst; auto with zarith.\n  intros [H4| [H4 | H4]]; subst; auto.\n  contradict H; auto; apply not_prime_1.\n  contradict Hp; auto with zarith.\nQed.\n\n(** we now prove that [Z.gcd] is indeed a gcd in\n   the sense of [Zis_gcd]. *)\n\nNotation Zgcd_is_pos := Z.gcd_nonneg (only parsing).\n\nLemma Zgcd_is_gcd : forall a b, Zis_gcd a b (Z.gcd a b).\nProof.\n constructor.\n apply Z.gcd_divide_l.\n apply Z.gcd_divide_r.\n apply Z.gcd_greatest.\nQed.\n\nTheorem Zgcd_spec : forall x y : Z, {z : Z | Zis_gcd x y z /\\ 0 <= z}.\nProof.\n  intros x y; exists (Z.gcd x y).\n  split; [apply Zgcd_is_gcd  | apply Z.gcd_nonneg].\nQed.\n\nTheorem Zdivide_Zgcd: forall p q r : Z,\n (p | q) -> (p | r) -> (p | Z.gcd q r).\nProof.\n intros. now apply Z.gcd_greatest.\nQed.\n\nTheorem Zis_gcd_gcd: forall a b c : Z,\n 0 <= c ->  Zis_gcd a b c -> Z.gcd a b = c.\nProof.\n  intros a b c H1 H2.\n  case (Zis_gcd_uniqueness_apart_sign a b c (Z.gcd a b)); auto.\n  apply Zgcd_is_gcd; auto.\n  Z.le_elim H1.\n  - generalize (Z.gcd_nonneg a b); auto with zarith.\n  - subst. now case (Z.gcd a b).\nQed.\n\nNotation Zgcd_inv_0_l := Z.gcd_eq_0_l (only parsing).\nNotation Zgcd_inv_0_r := Z.gcd_eq_0_r (only parsing).\n\nTheorem Zgcd_div_swap0 : forall a b : Z,\n 0 < Z.gcd a b ->\n 0 < b ->\n (a / Z.gcd a b) * b = a * (b/Z.gcd a b).\nProof.\n  intros a b Hg Hb.\n  assert (F := Zgcd_is_gcd a b); inversion F as [F1 F2 F3].\n  pattern b at 2; rewrite (Zdivide_Zdiv_eq (Z.gcd a b) b); auto.\n  repeat rewrite Z.mul_assoc; f_equal.\n  rewrite Z.mul_comm.\n  rewrite <- Zdivide_Zdiv_eq; auto.\nQed.\n\nTheorem Zgcd_div_swap : forall a b c : Z,\n 0 < Z.gcd a b ->\n 0 < b ->\n (c * a) / Z.gcd a b * b = c * a * (b/Z.gcd a b).\nProof.\n  intros a b c Hg Hb.\n  assert (F := Zgcd_is_gcd a b); inversion F as [F1 F2 F3].\n  pattern b at 2; rewrite (Zdivide_Zdiv_eq (Z.gcd a b) b); auto.\n  repeat rewrite Z.mul_assoc; f_equal.\n  rewrite Zdivide_Zdiv_eq_2; auto.\n  repeat rewrite <- Z.mul_assoc; f_equal.\n  rewrite Z.mul_comm.\n  rewrite <- Zdivide_Zdiv_eq; auto.\nQed.\n\nNotation Zgcd_comm := Z.gcd_comm (compat \"8.6\").\n\nLemma Zgcd_ass a b c : Z.gcd (Z.gcd a b) c = Z.gcd a (Z.gcd b c).\nProof.\n symmetry. apply Z.gcd_assoc.\nQed.\n\nNotation Zgcd_Zabs := Z.gcd_abs_l (only parsing).\nNotation Zgcd_0 := Z.gcd_0_r (only parsing).\nNotation Zgcd_1 := Z.gcd_1_r (only parsing).\n\nHint Resolve Z.gcd_0_r Z.gcd_1_r : zarith.\n\nTheorem Zgcd_1_rel_prime : forall a b,\n Z.gcd a b = 1 <-> rel_prime a b.\nProof.\n  unfold rel_prime; split; intro H.\n  rewrite <- H; apply Zgcd_is_gcd.\n  case (Zis_gcd_unique a b (Z.gcd a b) 1); auto.\n  apply Zgcd_is_gcd.\n  intros H2; absurd (0 <= Z.gcd a b); auto with zarith.\n  generalize (Z.gcd_nonneg a b); auto with zarith.\nQed.\n\nDefinition rel_prime_dec: forall a b,\n { rel_prime a b }+{ ~ rel_prime a b }.\nProof.\n  intros a b; case (Z.eq_dec (Z.gcd a b) 1); intros H1.\n  left; apply -> Zgcd_1_rel_prime; auto.\n  right; contradict H1; apply <- Zgcd_1_rel_prime; auto.\nDefined.\n\nDefinition prime_dec_aux:\n forall p m,\n  { forall n, 1 < n < m -> rel_prime n p } +\n  { exists n, 1 < n < m  /\\ ~ rel_prime n p }.\nProof.\n  intros p m.\n  case (Z_lt_dec 1 m); intros H1;\n   [ | left; intros; exfalso; omega ].\n  pattern m; apply natlike_rec; auto with zarith.\n  left; intros; exfalso; omega.\n  intros x Hx IH; destruct IH as [F|E].\n  destruct (rel_prime_dec x p) as [Y|N].\n  left; intros n [HH1 HH2].\n  rewrite Z.lt_succ_r in HH2.\n  Z.le_elim HH2; subst; auto with zarith.\n  - case (Z_lt_dec 1 x); intros HH1.\n    * right; exists x; split; auto with zarith.\n    * left; intros n [HHH1 HHH2]; contradict HHH1; auto with zarith.\n  - right; destruct E as (n,((H0,H2),H3)); exists n; auto with zarith.\nDefined.\n\nDefinition prime_dec: forall p, { prime p }+{ ~ prime p }.\nProof.\n  intros p; case (Z_lt_dec 1 p); intros H1.\n  + case (prime_dec_aux p p); intros H2.\n    * left; apply prime_intro; auto.\n      intros n (Hn1,Hn2). Z.le_elim Hn1; auto; subst n.\n      constructor; auto with zarith.\n    * right; intros H3; inversion_clear H3 as [Hp1 Hp2].\n      case H2; intros n [Hn1 Hn2]; case Hn2; auto with zarith.\n  + right; intros H3; inversion_clear H3 as [Hp1 Hp2]; case H1; auto.\nDefined.\n\nTheorem not_prime_divide:\n forall p, 1 < p -> ~ prime p -> exists n, 1 < n < p  /\\ (n | p).\nProof.\n  intros p Hp Hp1.\n  case (prime_dec_aux p p); intros H1.\n  - elim Hp1; constructor; auto.\n    intros n (Hn1,Hn2).\n    Z.le_elim Hn1; auto with zarith.\n    subst n; constructor; auto with zarith.\n  - case H1; intros n (Hn1,Hn2).\n    destruct (Z_0_1_more _ (Z.gcd_nonneg n p)) as [H|[H|H]].\n    + exfalso. apply Z.gcd_eq_0_l in H. omega.\n    + elim Hn2. red. rewrite <- H. apply Zgcd_is_gcd.\n    + exists (Z.gcd n p); split; [ split; auto | apply Z.gcd_divide_r ].\n      apply Z.le_lt_trans with n; auto with zarith.\n      apply Z.divide_pos_le; auto with zarith.\n      apply Z.gcd_divide_l.\nQed.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/ZArith/Znumtheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6868339013156147}}
{"text": "Require Import Category4.\nRequire Import Category2.\n\n(* given a Category4, we define the data necessary to create a Category2 *)\n\nDefinition dom_ (c:Category4) (f:Mor4 c) : Obj4 c := dom4 c f.\nDefinition cod_ (c:Category4) (f:Mor4 c) : Obj4 c := cod4 c f.\nDefinition compose2_ (c:Category4) (f g:Mor4 c) : option (Mor4 c) := compose4 c f g.\nDefinition id_ (c:Category4) (a:Obj4 c) : Mor4 c := id4 c a.\n\nDefinition proof_sid_ (c:Category4) : forall (a:Obj4 c), dom_ c (id_ c a) = a.\nProof. apply (proof_sid4 c). Qed.\n\nDefinition proof_tid_ (c:Category4) : forall (a:Obj4 c), cod_ c (id_ c a) = a.\nProof. apply (proof_tid4 c). Qed.\n\n\nDefinition proof_dom2_ (c:Category4) : forall (f g:Mor4 c),\n    cod_ c f = dom_ c g <-> compose2_ c f g <> None.\nProof. apply (proof_dom4 c). Qed.\n\n\nDefinition proof_src2_ (c:Category4) : forall (f g h:Mor4 c),\n    compose2_ c f g = Some h -> dom_ c h = dom_ c f.\nProof. apply (proof_src4 c). Qed.\n\nDefinition proof_tgt2_ (c:Category4) : forall (f g h:Mor4 c),\n    compose2_ c f g = Some h -> cod_ c h = cod_ c g.\nProof. apply (proof_tgt4 c). Qed.\n\nDefinition proof_idl2_ (c:Category4) : forall (a:Obj4 c) (f:Mor4 c), \n    a = dom_ c f -> compose2_ c (id_ c a) f = Some f.\nProof. apply (proof_idl4 c). Qed.\n\nDefinition proof_idr2_ (c:Category4) : forall (a:Obj4 c) (f:Mor4 c), \n    a = cod_ c f -> compose2_ c f (id_ c a) = Some f.\nProof. apply (proof_idr4 c). Qed.\n\nDefinition proof_asc2_ (c:Category4) : forall (f g h fg gh:Mor4 c), \n    compose2_ c f g  = Some fg ->\n    compose2_ c g h  = Some gh ->\n    compose2_ c f gh = compose2_ c fg h.\nProof. apply (proof_asc4 c). Qed.\n\n\nDefinition toCategory2 (c:Category4):Category2 (Obj4 c) (Mor4 c) := category2\n    (dom_               c)\n    (cod_               c)\n    (compose2_          c)\n    (id_                c)\n    (proof_sid_         c)\n    (proof_tid_         c)\n    (proof_dom2_        c)\n    (proof_src2_        c)\n    (proof_tgt2_        c)\n    (proof_idl2_        c)\n    (proof_idr2_        c)\n    (proof_asc2_        c) . \n\n\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/cat/Category4AsCategory2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.6868338980894237}}
{"text": "(** * Iterators\n\n    Throughout this discussion we'll work with an [Iterator] interface\n    and various concrete classes which implement [Iterator].\n\n    ** Iterator Interface\n\n    We'll start with a Java code example that consumes the [Iterator]\n    interface:\n\n[[\nIterator<int> it = getIteratorSomehow();\nit.forth();\n\nwhile (!it.after()) {\n\n  doSomethingWithAnInt(it.item());\n  it.forth();\n}\n]]\n\n    N.B. This is not Java's standard [Iterator<E>] interface [[1]].\n\n    An [Iterator] has three states:\n\n    - _Start_: [Iterator] has not retrieved the first item.\n    - _Intermediate_: [Iterator] has retrieved an item and is ready to\n      retrieve the next item.\n    - _Stop_: [Iterator] ran out of items.\n\n\n    These three states are encoded by two boolean functions:\n\n    - [off]: [false] if [Iterator] has a current item.\n    - [after]: [true] if [Iterator] ran out of items.\n\n\n    The states are encoded by [off] and [after] as follows:\n\n    - _Start_: [off = true /\\ after = false].\n    - _Intermediate_: [off = false /\\ after = false].\n    - _Stop_: [off = true /\\ after = true].\n\n\n    N.B. [off = false /\\ after = true] represents an invalid state.\n\n    The [Iterator] moves to the next state or the next item when we call\n    [forth]. If we consider the [Iterator] as a transition system [[2]]\n    the set of state transition labelled by [forth] is:\n\n    - (_Start_, _Intermediate_).\n    - (_Start_, _Stop_).\n    - (_Intermediate_, _Intermediate_).\n    - (_Intermediate_, _Stop_).\n\n\n    We call [item] to retrieve the [Iterator]'s current item.\n\n    In summary, the [Iterator] interface contains the following\n    functions:\n\n    - [off]: [false] if [Iterator] has a current item.\n    - [after]: [true] if [Iterator] ran out of items.\n    - [forth]: move to next state or next item.\n    - [item]: retrieve current item.\n\n    ** NatRangeIterator Class\n\n    A [NatRangeIterator] is an [Iterator] whose items are a range of\n    [nat]'s. It is defined by two [nat]'s:\n\n    - [first]: the first [nat] returned.\n    - [count]: the number of [nat]'s returned before entering _Stop_\n    state.\n\n    ** NatMultiplierIterator Class\n\n    A [NatMultiplierIterator] is an [Iterator] whose items are the items\n    of another [Iterator] multiplied by a [nat]. It is defined by a\n    [nat] [Iterator] and a [nat] multiplier:\n\n    - [inner_iterator]: the source [nat] [Iterator].\n    - [multiplier]: the [nat] which multiplies each item of the\n      [inner_iterator].\n\n    * Outcomes\n\n    The outcomes of this discussion are:\n\n    - An [Iterator] specification (in the form of a Coq function) which\n      tests if an implementation specification (either a concrete class or\n      a sub-interface) conforms to [Iterator].\n    - A [NatRangeIterator] specification describing the behavior with\n      respect to [first] and [count].\n    - Proof that the [NatRangeIterator] specification conforms to the\n      [Iterator] specifiation.\n    - A [NatMultiplierIterator] specification describing the behavior\n      with respect to [inner_iterator] and [multiplier].\n    - Proof that the [NatMultiplierIterator] specification conforms to\n      the [Iterator] specification.\n    - A [Main] function which is a closed term that composes a\n      [NatRangeIterator] with a [NatMultiplierIterator] to produce some\n      output.\n    - Proof that [Main] produces the expected output.\n\n    * Naming Conventions\n\n    This project uses function names from Eiffel's base library wherever\n    possible. For example [off], [after], [forth], and [item] were\n    inspired by Eiffel's [LINEAR] class [[3]].\n\n    * References\n\n    - [[1]]: https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html\n    - [[2]]: https://en.wikipedia.org/wiki/Transition_system\n    - [[3]]: https://www.eiffel.org/files/doc/static/trunk/libraries/base/linear_chart.html *)\n", "meta": {"author": "jlapolla", "repo": "coq-oo", "sha": "510e5e471d06c1fa805528cff305e6a287e74686", "save_path": "github-repos/coq/jlapolla-coq-oo", "path": "github-repos/coq/jlapolla-coq-oo/coq-oo-510e5e471d06c1fa805528cff305e6a287e74686/Software/Doc/Introduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749422, "lm_q2_score": 0.8499711832583696, "lm_q1q2_score": 0.6868338495844547}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Basic_Cons.CCC.\nRequire Import Coq_Cats.Type_Cat.Type_Cat.\n\nProgram Instance unit_Type_term : (𝟙_ Type_Cat)%object :=\n{\n  terminal := unit;\n  t_morph := fun _ _=> tt\n}.\n\nNext Obligation. (* t_morph_unique *)\nProof.\n  extensionality x.\n  destruct (f x); destruct (g x); reflexivity.\nQed.\n\n\nLocal Notation \"A × B\" := (@Product Type_Cat A B) : object_scope.\n\n(** The cartesian product of types is the categorical notion of products in\n    category of types. *)\nProgram Definition prod_Product (A B : Type) : (A × B)%object :=\n{|\n  product := (A * B)%type;\n  Pi_1 := fst;\n  Pi_2 := snd;\n  Prod_morph_ex := fun p x y z => (x z, y z)\n|}.\n\nNext Obligation. (* Prod_morph_unique *)\nProof.\n  extensionality x.\n  repeat\n    match goal with\n      [H : _ = _ |- _] =>\n      apply (fun p => equal_f p x) in H\n    end.\n  basic_simpl.  \n  destruct (f x); destruct (g x); cbn in *; subst; trivial.\nQed.\n\nProgram Instance Type_Cat_Has_Products : Has_Products Type_Cat := prod_Product.\n\n(** The function type in coq is the categorical exponential in the category of\n    types. *)\nProgram Definition fun_exp (A B : Type_Cat) : (A ⇑ B)%object :=\n{|\n  exponential := A -> B;\n  eval := fun x => (fst x) (snd x);\n  Exp_morph_ex := fun h z u v=>  z (u, v)\n|}.\n\nNext Obligation. (* Exp_morph_unique *)\nProof.\n  extensionality a; extensionality x.\n  repeat\n    match goal with\n      [H : _ = _ |- _] =>\n      apply (fun p => equal_f p (a, x)) in H\n    end.\n  transitivity (f (a, x)); auto.\nQed.\n\n(* fun_exp defined *)\n\nProgram Instance Type_Cat_Has_Exponentials : Has_Exponentials Type_Cat := fun_exp.\n\n(* Category of Types is cartesian closed *)\n\nProgram Instance Type_Cat_CCC : CCC Type_Cat.", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/Categories/Coq_Cats/Type_Cat/CCC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571775, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.6868338285853682}}
{"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 NArith NPeano Ascii String.\n\nSet Implicit Arguments.\n\nLocal Open Scope string_scope.\n\nLocal Definition natToDigit (n : nat) : string :=\n  match n with\n    | 0 => \"0\"\n    | 1 => \"1\"\n    | 2 => \"2\"\n    | 3 => \"3\"\n    | 4 => \"4\"\n    | 5 => \"5\"\n    | 6 => \"6\"\n    | 7 => \"7\"\n    | 8 => \"8\"\n    | _ => \"9\"\n  end.\n\nLocal Definition NToDigit (n : N) := natToDigit (N.to_nat n).\n\nLocal Fixpoint writeNatAux (time n : nat) (acc : string) : string :=\n  let acc' := natToDigit (n mod 10) ++ acc in\n  match time with\n    | 0 => acc'\n    | S time' =>\n      match n / 10 with\n        | 0 => acc'\n        | n' => writeNatAux time' n' acc'\n      end\n  end.\n\nLocal Fixpoint writeNAux (time : nat) (n : N) (acc : string) : string :=\n  let acc' := NToDigit (n mod 10)%N ++ acc in\n  match time with\n    | 0 => acc'\n    | S time' =>\n      match (n / 10)%N with\n        | N0 => acc'\n        | n' => writeNAux time' n' acc'\n      end\n  end.\n\nSection N_to_string.\n  \n  Let loop := fix loop l n s :=\n    let (d,r) := N.div_eucl n 10 in\n    let s'    := String (ascii_of_N (48+r)) s\n    in match d, l with\n         | N0, _   => s'\n         | _ , 0   => s'\n         | _ , S l => loop l d s'\n    end.\n  \n  (* We limit the display of N to 10^12 *)\n \n  Definition string_of_N n := \n    match n with \n      | N0 => \"0\"\n      | _  => loop 12 n EmptyString\n    end.\n  \nEnd N_to_string.\n\nDefinition string_of_nat n := writeNatAux n n \"\".\n\n(*\nEval compute in string_of_N 123456789012309271072.\n*)", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/Shared/Libs/DLW/Utils/utils_string.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338727, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6868080770431892}}
{"text": "From mathcomp Require Export fintype ssrbool seq choice ssreflect finset.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\nNotation \"∅\" := set0.\nNotation \"x ∈ X\" := (x \\in X)(at level 60). \nNotation \"A ∩ B\" := (setI A B)(at level 40).\nNotation \"A ∪ B\" := (setU A B)(at level 40).\nNotation \"A ⊂ B\" := (A \\subset B)(at level 30).\nNotation \"A // B\" := (setD A B)(at level 40).\nNotation \"¬ A\" := (setC A)(at level 40).\nNotation \"pow[ A ]\" := (powerset A).\nNotation \"∅\" := set0.\n\nLemma extension {T : finType} (A B : {set T}) :\n    A ⊂ B -> B ⊂ A -> A = B.\nProof.\n    move => AB BA; apply /setP /subset_eqP /andP => //.\nQed.\n\n\nLemma set_enum {T : finType} (A : {set T}) :\n    [set x | x \\in enum A] = A.\nProof.\n    by apply/setP => x; rewrite inE mem_enum .\nQed.    \n\nAxiom bigcup : forall {T : finType}, {set {set T}} -> {set T}.\nAxiom bigcupP : forall {T : finType} (XX : {set {set T}}) (X : T),\n    reflect (exists (Y : {set T}), X ∈ Y /\\ Y ∈ XX) (X ∈ bigcup XX).\n\nAxiom bigcap : forall {T : finType}, {set {set T}} -> {set T}.\nAxiom bigcapP : forall {T : finType} (XX : {set {set T}}) (X : T),\n    reflect (forall (Y : {set T}), Y ∈ XX -> X ∈ Y) (X ∈ bigcup XX).\n\n    ", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "compiler", "sha": "0ba27418104bb0abc38ca2f9ccdcd7e539629dd2", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-compiler", "path": "github-repos/coq/gaxiiiiiiiiiiii-compiler/compiler-0ba27418104bb0abc38ca2f9ccdcd7e539629dd2/Base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463334, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.6868080435542022}}
{"text": "(** * Abstract theory of coinduction \n\n  See\n  Coinduction All the Way Up. Damien Pous. In Proc. LICS, 2016.\n  http://dx.doi.org/10.1145/2933575.2934564\n  https://hal.archives-ouvertes.fr/hal-01259622/document\n\n*)\n\nRequire Export lattice.\nRequire Classical.              (* only for distributivity of the companion *)\nSet Implicit Arguments.\n\n(** * Knaster-Tarski and compatibility  *)\n\nSection s1.\n Context {X} {L: CompleteLattice X}.\n \n Variable b: mon X.\n\n (** ** compatible functions *)\n Notation compat f := (f ° b <= b ° f) (only parsing).\n \n (** compositionality properties of compatibility *)\n Lemma compat_id: compat id.\n Proof. reflexivity. Qed.\n \n Lemma compat_comp f g: compat f -> compat g -> compat (f ° g).\n Proof.\n   intros Hf Hg.\n   rewrite <-compA, Hg.\n   rewrite compA, Hf.\n   now rewrite compA. \n Qed.\n\n Lemma compat_b: compat b.\n Proof. reflexivity. Qed.\n\n Lemma compat_const y: y <= b y -> compat (const y).\n Proof. now intros ??. Qed. \n \n Lemma compat_sup (P: mon X -> Prop):\n   (forall f, P f -> compat f) -> compat (sup P).\n Proof.\n   intros H x. simpl. apply sup_spec. intros f Pf. \n   rewrite (H _ Pf x). apply b. eapply eleq_xsup; eauto.\n Qed.\n\n (** ** companion *)\n\n (** the companion is the largest compatible function *)\n Definition t := sup (fun f => compat f).\n\n Lemma compat_t: compat t.\n Proof. now apply compat_sup. Qed.\n\n (** ** Knaster Tarski *)\n\n (** we will show that [t bot] is the greatest fixpoint of [b] (Theorem 3.3), \n     whence the following definition *)\n Definition gfp := t bot. \n\n (** [gfp] is a post-fixpoint *)\n Proposition gfp_pfp: gfp <= b gfp.\n Proof.\n   transitivity (t (b bot)).\n   now apply t. \n   apply compat_t.\n Qed.\n (** and actually the greatest one *)\n Proposition leq_gfp y: y <= b y -> y <= gfp.\n Proof.\n   intro H.\n   assert (H': const y <= t) by now apply leq_xsup, compat_const.\n   apply (H' bot).\n Qed.\n\n (** thus a fixpoint, as in Knaster-Tarski's proof *)\n Theorem gfp_fp: gfp == b gfp.\n Proof.\n   apply antisym. apply gfp_pfp.\n   apply leq_gfp. apply b, gfp_pfp.\n Qed.\n\n (** more properties about [t] (Lemma 3.2) *)\n Lemma leq_t f: compat f -> f <= t.\n Proof. intro; now apply leq_xsup. Qed.\n \n Lemma id_t: id <= t.\n Proof. apply leq_t, compat_id. Qed.\n\n Lemma b_t: b <= t.\n Proof. apply leq_t, compat_b. Qed.\n \n Lemma tt_t: t ° t <= t.\n Proof. apply leq_t, compat_comp; apply compat_t. Qed.\n \n Lemma ft_t f: f <= t -> f ° t <= t.\n Proof. intro H. rewrite H. apply tt_t. Qed.\n\n Lemma t_idem: t ° t == t.\n Proof. apply antisym. apply tt_t. now rewrite <-id_t at 2. Qed.\n\n (** 'guarded companion', convenient later for expressing the [coinduction] and [accumulate] rules *)\n Definition bt := b ° t.\n\n Lemma bt_t: bt <= t.\n Proof. apply ft_t, b_t. Qed.\n\n Lemma fbt_bt {f}: f <= t -> f°bt <= bt.\n Proof. intro H. unfold bt. rewrite H. now rewrite compA, compat_t, <-compA, tt_t. Qed.\n   \n (** to sum up: [gfp = t bot = t gfp <= t x] *)\n (** Corollary 3.4 *)\n Corollary t_gfp: t gfp == gfp.\n Proof. apply t_idem. Qed.\n\n Corollary gfp_t x: gfp <= t x.\n Proof. now apply t. Qed.\n\n Corollary gfp_bt x: gfp <= bt x.\n Proof. now rewrite gfp_pfp, (gfp_t x) . Qed.\n\n Lemma leq_f_ft f: f <= f ° t.\n Proof. now rewrite <-id_t. Qed.\n Lemma leq_f_tf f: f <= t ° f.\n Proof. now rewrite <-id_t. Qed.\n \nEnd s1.\nNotation compat b f := (f ° b <= b ° f) (only parsing).\n#[export] Typeclasses Opaque t.\nGlobal Opaque t.\n\nSection s2.\n Context {X} {L: CompleteLattice X}.\n\n (** [gfp] is monotone, as a function from [mon X] to [X] \n     (be careful: [t] is not monotone from [mon X] to [mon X]) *)\n Instance gfp_leq: Proper (leq ==> leq) gfp.\n Proof. intros b b' Hb. apply leq_gfp. rewrite gfp_fp at 1. apply Hb. Qed.\n Instance gfp_weq: Proper (weq ==> weq) gfp := op_leq_weq_1.\n \n Variable b: mon X.\n\n (** [t] is intended to be used as an up-to technique, to play with \n     [b' = b ° t] rather than just [b].\n    The following proposition (Equation 11) shows that we would not get\n    anything new by iterating this idea. *)\n Notation bt := (bt b).\n Notation t' := (t bt).\n Notation t := (t b).\n Proposition stagnate_t: t == t'.\n Proof.\n   unfold bt.\n   apply antisym'. apply leq_t. now rewrite compA, compat_t.\n   intro E. apply leq_t.\n   rewrite (leq_f_ft b b) at 3.\n   rewrite compat_t.\n   rewrite <-compA. rewrite E at 1.\n   now rewrite tt_t.\n Qed.\n\n (** as a corollary, [b'] is a valid enhancement of [b] (Theorem 3.6) *)\n Corollary enhanced_gfp: gfp b == gfp bt.\n Proof. apply stagnate_t. Qed.\n\n (** and we get a unique enhanced coinduction principle *)\n Corollary coinduction x: x <= bt x -> x <= gfp b.\n Proof. intro. rewrite enhanced_gfp. now apply leq_gfp. Qed.  \n\nEnd s2.\n \n(** * Compatibility up-to: second order reasoning *)\n\nSection s3.\n Context {X} {L: CompleteLattice X}.\n Variable b: mon X.\n \n (** a function whose post-fixpoints are the compatible functions (Definition 6.1) *)\n Program Definition B: mon (mon X) :=\n   {| body g := sup (fun f => f ° b <= b ° g) |}.\n Next Obligation.\n   intros g g' Hg x. apply sup_leq; trivial. \n   intros f Hf z. now rewrite <-(Hg z).\n Qed.\n\n (** Lemma 6.2 *)\n Lemma B_spec f g: f <= B g <-> f ° b <= b ° g.\n Proof.\n   split; intro H. rewrite H. intro. apply sup_spec. \n   intros h Hh. apply Hh.\n   now apply leq_xsup.\n Qed.\n Lemma Bfb f: B f ° b <= b ° f.\n Proof. now apply B_spec. Qed.\n\n (** the companion of [b] is the greatest fixpoint of [B] *)\n Theorem companion_gfp: t b == gfp B.\n Proof.\n  apply antisym.\n   apply leq_gfp. rewrite B_spec. apply compat_t.\n   apply leq_t. rewrite <-B_spec. apply gfp_pfp.\n Qed.\n\n (** [T] is the companion of [B] *)\n Definition T := t B.\n Definition bT f := comp b (T f).\n Notation t := (t b).\n Notation bt := (bt b).\n\n (** corresponding second-order coinduction principle *)\n Corollary Coinduction f: f ° b <= bT f -> f <= t.\n Proof. unfold bT. rewrite <-B_spec, companion_gfp. apply coinduction. Qed.     \n\n \n (** ** properties of the second order companion (Proposition 6.4) *)\n \n (** the squaring function is compatible for [B] (Lemma 6.3) *)\n Program Definition csquare: mon (mon X) := {| body f := f ° f |}.\n Next Obligation. intros ? ? ?. now apply comp_leq. Qed.\n Lemma compat_csquare: compat B csquare. \n Proof.\n   intro f. apply B_spec. change (B f ° B f ° b <= b ° f ° f).\n   rewrite <-compA, Bfb. \n   now rewrite compA, Bfb.    \n Qed.\n\n (** so is the constant-to-identity function *)\n Lemma compat_constid: const id ° B <= B ° const id.\n Proof. intro f. now apply B_spec. Qed.\n \n (** thus [T f] is always an idempotent function  *)\n Proposition TT_T f: T f ° T f <= T f.\n Proof. apply (ft_t (leq_t compat_csquare)). Qed.\n Proposition id_T f: id <= T f.\n Proof. apply (ft_t (leq_t compat_constid)). Qed.\n Corollary T_idem f: T f ° T f == T f.\n Proof. apply antisym. apply TT_T. now rewrite <-id_T at 2. Qed.\n\n (** [T f] always contains [f], [t], [b], and [gfp b] *)\n Lemma f_Tf f: f <= T f.\n Proof. apply id_t. Qed.\n Lemma t_T f: t <= T f.\n Proof. rewrite companion_gfp. apply gfp_t. Qed.\n Lemma bt_bT f: bt <= bT f.\n Proof. unfold bt, bT. now rewrite t_T. Qed.\n Lemma b_T f: b <= T f.\n Proof. rewrite b_t. apply t_T. Qed.\n Lemma bT_T f: bT f <= T f.\n Proof. unfold bT. rewrite (b_T f). apply TT_T. Qed.\n Lemma bt_T f: bt <= T f.\n Proof. rewrite bt_t. apply t_T. Qed.\n \n Lemma gfp_bT f x: gfp b <= bT f x.\n Proof. rewrite <-bt_bT. apply gfp_bt. Qed.\n Lemma gfp_T f x: gfp b <= T f x.\n Proof. rewrite <-t_T. apply gfp_t. Qed.\n\n (** helpers, to extract components out of [T]  *)\n Lemma fT_T_ f g: f <= T g -> f ° T g <= T g.\n Proof. intro H. rewrite H. apply TT_T. Qed.\n Lemma fTf_Tf f: f ° T f <= T f.\n Proof. apply fT_T_, f_Tf. Qed.\n Lemma fT_T f: f <= t -> forall g, f ° T g <= T g.\n Proof. intros H g. apply fT_T_. rewrite H. apply t_T. Qed.\n Lemma Tf_T f g: f <= T g -> T g ° f <= T g.\n Proof. intro H. rewrite H. apply TT_T. Qed.\n Lemma Cancel f g x y: f <= T g -> x <= T g y -> f x <= T g y.\n Proof. intros Hf Hx. rewrite Hx. now apply fT_T_. Qed.\n\n Lemma fbT_bT {f}: f <= t -> forall g, f°bT g <= bT g.\n Proof. intros H g. unfold bT. rewrite H. now rewrite compA, compat_t, <-compA, fT_T. Qed.\n\n (** [T f R] is always of the shape [t _] *)\n Lemma T_tT f: T f == t ° T f.\n Proof.\n   apply antisym.\n   - intro. apply id_t.\n   - rewrite t_T. apply TT_T. \n Qed.\n (** [bt R] is always of the shape [t _] *)\n Lemma bt_tbt: bt == t ° bt.\n Proof.\n   apply antisym.\n   - intro. apply id_t.\n   - now apply fbt_bt.\n Qed.\n\n (** we can thus transfer universal properties of [t] to [bt], [T], and [bT] \n     (not used yet)\n  *)\n Lemma Pt_PTf (P: X -> Prop) (H: forall R, P (t R)) (H': Proper (weq ==> leq) P): forall f R, P (T f R).\n Proof. intros f R. rewrite T_tT. apply H. Qed.\n Lemma Pt_Pbt (P: X -> Prop) (H: forall R, P (t R)) (H': Proper (weq ==> leq) P): forall R, P (bt R).\n Proof. intros R. rewrite bt_tbt. apply H. Qed.\n Lemma Pt_PbTf (P: X -> Prop) (H: forall R, P (t R)) (H': Proper (weq ==> leq) P): forall f R, P (bT f R).\n Proof. intros f R. unfold bT. rewrite T_tT. apply (Pt_Pbt H H' _). Qed.\n (* TOTHINK: \n    in fact, universal properties of [t] are universal properties of elements of [chain.S] below\n  *)\n\n (** * Parametric coinduction: the accumulation rule  *)\n \n Program Definition xaccumulate y x: mon X :=\n   {| body z := sup' (fun _:unit => x <= z) (fun _:unit => y) |}.\n Next Obligation.\n   intros z z' Hz. apply sup_leq; trivial.\n   intros _ H. now rewrite H.\n Qed.\n\n (** Theorem 10.2 *)\n Theorem accumulate y x: y <= bt (cup x y) -> y <= t x.\n Proof.\n   intro H. set (f:=xaccumulate y x).\n   assert (E: y <= f x) by now eapply eleq_xsup; eauto.\n   cut (f <= t). intro F. now rewrite E.\n   apply Coinduction. intro z. apply sup_spec. intros _ Hxz.\n   rewrite H. apply b. apply Cancel. apply t_T.\n   apply cup_spec. split.\n   rewrite Hxz. apply b_T. \n   rewrite E, Hxz. apply Cancel. apply f_Tf. apply b_T.\n Qed.\n \nEnd s3. \n#[export] Typeclasses Opaque B T.\nGlobal Opaque B.\n\n(** * Symmetry arguments *)\n\nSection symmetry.\n (** we use a class to record the involution: this makes it possible to\n     find the appropriate involution automativally in concrete examples  *)\n Context {X} {L: CompleteLattice X} {i: mon X}.\n Class Involution := invol: i ° i == id.\n Context {I: Involution}.\n \n Lemma invol' x: i (i x) == x.\n Proof. apply invol. Qed.\n \n Lemma switch x y: i x <= y <-> x <= i y.\n Proof. split; (intro H; apply i in H; now rewrite invol' in H). Qed.\n\n Lemma Switch f g: i ° f <= g <-> f <= i ° g.\n Proof. split; (intros H x; apply switch, H). Qed.\n\n Lemma compat_if_fi f: compat i f -> compat f i.\n Proof. intro H; apply Switch. now rewrite compA, <-H, <-compA, invol. Qed.\n  \n (** [b] is assumed to be of the shape [s /\\ i s i]  \n     we use a class to record such a fact, so that the end-user may use syntactically different definitions and yet be able to declare a function as being of this shape.\n  *)\n\n Context {b s: mon X}.\n Class Sym_from := sym_from: b == (cap s (i ° s ° i)).\n Context {H: Sym_from}.\n Notation B := (B b).\n Notation T := (T b).\n Notation t := (t b).\n Notation bt := (bt b).\n Notation bT := (bT b).\n\n (** [i] is compatible  *)\n Lemma compat_invol: compat b i.\n Proof.\n   rewrite sym_from. \n   rewrite o_mcap, 2compA, invol.\n   rewrite mcap_o, <-2compA, invol.\n   now rewrite capC. \n Qed.\n\n (** thus below [t]  *)\n Lemma invol_t: i <= t.\n Proof. apply leq_t, compat_invol. Qed.\n\n (** reasoning by symmetry on plain post-fixpoints *)\n Proposition symmetric_pfp x: i x <= x -> x <= s x -> x <= b x.\n Proof.\n   intros ix sx. rewrite sym_from. apply cap_spec. split. assumption.\n   apply switch. rewrite ix at 1. apply switch in ix. now rewrite <-ix. \n Qed. \n\n (** reasoning by symmetry at the first level *)\n Proposition by_symmetry x y: i x <= x -> x <= s (t y) -> x <= bt y.\n Proof.\n   assert(it: i ° t == t). apply antisym'. apply ft_t, invol_t. apply Switch.\n   intros Hx Hxy. rewrite (sym_from (t y)). apply cap_spec. split. assumption.\n   apply switch. rewrite Hx, Hxy. now rewrite (it y).\n Qed. \n\n (** reasoning by symmetry at the second level *)\n Proposition by_Symmetry f g: compat i f -> f ° b <= s ° (T g) -> f ° b <= bT g.\n Proof.\n   intros Hf Hfg. apply compat_if_fi in Hf.\n   unfold bT. rewrite sym_from at 2.\n   rewrite mcap_o. apply cap_spec. split. assumption.\n   change (f ° b <= i ° (s ° i ° T g)). apply Switch.\n   rewrite compA, Hf.\n   rewrite <-compA, compat_invol. \n   rewrite compA, Hfg, <-2(compA s).\n   apply comp_leq. reflexivity.\n   assert (iT: i <= T g). rewrite invol_t at 1. apply t_T.\n   rewrite iT at 1. setoid_rewrite TT_T.\n   apply Switch. apply fT_T_, iT. \n Qed.\n\nEnd symmetry.\nArguments Involution {_ _} _.\nArguments Sym_from {_ _} _ _ _.\n\n(** obvious instance of [Sym_from] (default) *)\n#[export] Instance sym_from_def {X} {L: CompleteLattice X} {i s: mon X}: Sym_from i (cap s (i ° s ° i)) s.\nProof. now cbn. Qed.\n\n\n(** * Proof system *)\n\nSection proof_system.\n Context {X} {L: CompleteLattice X}.\n \n Variable b: mon X.\n Notation B := (B b).\n Notation T := (T b).\n Notation t := (t b).\n Notation bt := (bt b).\n\n Lemma rule_init y: y <= t bot -> y <= gfp b.\n Proof. now intro. Qed.\n\n Lemma rule_done y x: y <= x -> y <= t x.\n Proof. now rewrite <-id_t. Qed.\n \n Lemma rule_upto f y x: f <= t -> y <= f (t x) -> y <= t x.\n Proof. intros Hf Hy. now rewrite <- (ft_t Hf). Qed.\n \n Lemma rule_coind y x: y <= bt (cup x y) -> y <= t x.\n Proof. apply accumulate. Qed.\n\nEnd proof_system.\n\n\n(** * Coincidence of the greatest respectful and the greatest compatible *)\n\nModule respectful.\nSection s.\n Context {X} {L: CompleteLattice X}.\n\n Variable b: mon X. \n Notation b' := (cap b id).\n Notation t' := (t b').\n Notation B' := (B b').\n Notation T' := (T b').\n Notation B := (B b).\n Notation T := (T b).\n Notation t := (t b).\n \n Lemma b_b't: b <= b' ° t.\n Proof. \n   rewrite mcap_o. apply cap_spec. split.\n    now rewrite <-id_t. \n    apply b_t.  \n Qed.\n\n (** Proposition 9.1  *)\n Proposition t_t': t == t'.\n Proof.\n   apply antisym'. \n    apply leq_t. rewrite cap_l at 1. \n    rewrite compat_t. rewrite b_b't at 1. now rewrite <-compA, tt_t.\n   intro E. apply leq_t. rewrite b_b't at 2. \n   rewrite compA, compat_t.\n   rewrite E. rewrite <-compA, tt_t. \n   now rewrite cap_l at 1. \n Qed.\n \n Proposition bt_b't: b ° t == b' ° t.\n Proof.\n   apply antisym.\n    rewrite b_b't at 1. now rewrite <-compA, tt_t.\n    now rewrite cap_l.\n Qed.\n\n Lemma B'S_BS: forall S, S=T \\/ S=T' -> B' ° S == B ° S.\n Proof.\n   intros S HS g.\n   assert (tS: t ° S g <= S g). destruct HS as [->| ->].\n    now apply fT_T.\n    rewrite t_t'. now apply fT_T. \n   assert (St: S g ° t <= S g). destruct HS as [->| ->].\n    apply Tf_T, t_T. \n    rewrite t_t'. apply Tf_T, t_T. \n   apply from_below. intro f.\n   change (f <= B' (S g) <-> f <= B (S g)). rewrite 2B_spec.\n   split; intro H.\n   rewrite b_b't at 1. rewrite compA, H. rewrite <-compA, St.\n   now rewrite cap_l. \n   rewrite cap_l at 1. rewrite H. rewrite b_b't at 1.\n   now rewrite <-tS at 2. \n Qed.\n                                          \n (** Proposition 9.2  *)\n Proposition T'_T: T' == T.\n Proof.\n   apply antisym; apply leq_t.\n   transitivity (T' ° B ° T'). now setoid_rewrite <-id_t at 3.\n   rewrite <-compA. rewrite <-B'S_BS by tauto.\n   rewrite compA. setoid_rewrite compat_t. \n   now rewrite <-compA, tt_t. \n   transitivity (T ° B' ° T). now setoid_rewrite <-id_t at 3.\n   rewrite <-compA. rewrite B'S_BS by tauto.\n   rewrite compA. setoid_rewrite compat_t. \n   now rewrite <-compA, tt_t. \n Qed.\n\n Proposition B'T'_BT: B' ° T' == B ° T.\n Proof. rewrite T'_T. apply B'S_BS. tauto. Qed.\n \n (* note that B≠B' in general *)\n\nEnd s.\nEnd respectful.\n\nGlobal Opaque T.\n\n\n\n(** * Characterisation of Hur et al.' function G using the companion *)\n\nModule paco.\nSection s.\n\n Context {X} {L: CompleteLattice X}. \n\n Program Definition g (b: mon X) x: mon X := {| body y := b (cup x y) |}.\n Next Obligation. intros y z H. now rewrite H. Qed.\n\n Program Definition G b: mon X := {| body x := gfp (g b x) |}.\n Next Obligation.\n   intros ? ? ?. apply gfp_leq.\n   intro. simpl. now rewrite H.\n Qed.\n\n Variable b: mon X.\n Notation t := (t b).\n Notation bt := (bt b).\n Notation G' := (G bt).\n \n (** Theorem 10.1 *)\n Theorem G_bt: G' == bt.\n Proof.\n   apply antisym.\n    assert (E: G' <= t).\n     intro x. apply rule_coind. simpl. now rewrite gfp_fp at 1. \n    intro x. simpl. rewrite gfp_fp. simpl. apply b.\n    rewrite (E x). rewrite <-(tt_t b x) at 2. apply t. apply cup_spec. split.\n    apply id_t. reflexivity. \n   intro. simpl. apply leq_gfp. simpl. apply b, t, cup_l.\n Qed. \n\n Proposition G_upto: G' == t ° G'. (* i.e., bt = tbt *)\n Proof.\n   rewrite G_bt. apply antisym. intro. apply id_t.\n   unfold bt. now rewrite compA, compat_t, <-compA, tt_t.\n Qed.\n \n (* note: tb < bt = tbt < t *)\nEnd s.\nEnd paco.\n\n\n(** * alternative definition of the companion, using Kleene iteration *)\nModule chain.\nSection s.\n Context {X} {L: CompleteLattice X}. \n Variable b: mon X.\n Notation t := (t b).\n Inductive S: X -> Prop :=\n | Sb: forall x, S x -> S (b x)\n | Sinf: forall T, T <= S -> S (inf T).\n Lemma gfpS: gfp b == inf S.\n Proof.\n   apply antisym. apply inf_spec. simpl. intros u U. induction U.\n   rewrite gfp_pfp. now apply b. now apply inf_spec.\n   apply leq_gfp. apply leq_infx. now apply Sb, Sinf.\n Qed.\n Lemma tS: forall s, S s -> t s == s.\n Proof.\n   intros s H. apply antisym. 2: apply id_t.\n   induction H as [s Hs IH|T HT IH].\n   rewrite (compat_t b s). now apply b.\n   apply inf_spec. intros s Hs. rewrite <-(IH _ Hs). apply t. now apply leq_infx.\n Qed.               \n Definition S_ x s := S s /\\ x <= s.\n Definition t'_ x := inf (S_ x).\n Lemma t'_mon: Proper (leq ==> leq) t'_.\n Proof.\n   intros x y H. apply inf_spec; intros s [Ss E]. apply leq_infx.\n   split. assumption. now rewrite H. \n Qed.\n Definition t' := Build_mon t'_mon. \n Lemma id_t' x: x <= t' x.\n Proof. apply inf_spec. now intros s [_ ?]. Qed.\n Lemma St' x: S (t' x).\n Proof. apply Sinf. now intros ? [? ?]. Qed.\n Lemma compat_t': t' ° b <= b ° t'.\n Proof.\n   intro x. simpl. apply leq_infx. split.\n   apply Sb. apply St'. apply b. apply id_t'. \n Qed.\n \n Theorem tt': t == t'.\n Proof.\n   apply antisym.\n   intro x. rewrite (id_t' x) at 1. now rewrite tS by apply St'.\n   apply leq_t, compat_t'.\n Qed.\n \n Corollary leq_t' f: f <= t <-> forall s, S s -> f s <= s.\n Proof.\n   split.\n   intros E s H. now rewrite (E s), tS.\n   intros H. apply Coinduction. intro x. simpl.\n   rewrite (id_t' x) at 1. rewrite H by apply Sb, St'.\n   apply b. rewrite <-tt'. apply t_T.\n Qed.\n \n Lemma St x: S (t x).\n Abort.\n Lemma St x: exists tx, S tx /\\ tx == t x.\n Proof. exists (t' x). split. apply St'. now rewrite tt'. Qed.\n\n Lemma Sflat s: S s -> exists T, T<=S /\\ s == inf' T b.\n Proof.\n   induction 1 as [s Hs IH|T HT IH].\n   exists (eq s). split. now intros ? <-.\n   apply antisym. apply inf_spec. now intros ? <-.\n   eapply eleq_infx; eauto.\n   (* exists (fun t => exists a (A: T a), match IH a A return Prop with ex_intro _ U _ => U t end). *)\n Abort.\n \n Lemma Sflat s: S s -> s == inf' (fun t => S t /\\ s <= b t) b.\n Proof.\n   intro E. apply antisym. now apply inf_spec; intros t [_ T].\n   induction E as [s Hs IH|T HT IH].\n   eapply eleq_infx; eauto.\n   apply inf_spec. intros s Hs.\n   rewrite <- (IH s Hs). apply inf_leq; trivial. \n   intros t [St sbt]. split. assumption.\n   rewrite <-sbt. now apply leq_infx.\n Qed.\n\n (** * additivity of the companion (assuming classical logic) *)\n \n Import Classical. \n Lemma choose (P A B: X -> Prop): (forall x, P x -> A x \\/ B x) -> (exists x, P x /\\ B x) \\/ (forall x, P x -> A x).\n Proof.\n   intro H. classical_right. intros x Px.\n   destruct (H _ Px). assumption. exfalso; eauto. \n Qed.\n\n Lemma S_linear x y: S x -> S y -> x <= y \\/ y <= x.\n Proof.\n   intro Sx. revert y. induction Sx as [x Hx IH|T HT IH]; intros y Sy.\n   - pose proof (Sflat Sy) as E.\n     set (T t := S t /\\ y <= b t) in E. \n     assert (IH': forall y, T y -> x <= y \\/ y <= x). intros t Tt. apply IH, Tt. \n     destruct (choose _ _ _ IH') as [[s [Ss sx]]|F].\n     right. rewrite E, <-sx. eapply eleq_infx; eauto.\n     left. rewrite E. apply inf_spec; intros s Ts. now apply b, F.\n   - assert (IH': forall a, T a -> y <= a \\/ a <= y). intros a A. specialize (IH _ A _ Sy). tauto. \n     destruct (choose _ _ _ IH') as [[s [Ss sx]]|F].\n     left. rewrite <-sx. now apply leq_infx.\n     right. apply inf_spec; intros t Tt. now apply F. \n Qed.\n\n Lemma tcup x y: t (cup x y) == cup (t x) (t y).\n Proof.\n   apply antisym.\n   transitivity (t (cup (t' x) (t' y))).\n   apply t. apply cup_leq; apply id_t'. \n   destruct (S_linear (St' x) (St' y)) as [xy|yx].\n   transitivity (t (t' y)). apply t. apply cup_spec. now split.\n   rewrite <-tt', (tt_t b y). apply cup_r. \n   transitivity (t (t' x)). apply t. apply cup_spec. now split.\n   rewrite <-tt', (tt_t b x). apply cup_l.\n   apply cup_spec. split; apply t. apply cup_l. apply cup_r. \n Qed.\n\nEnd s.\nEnd chain.\n", "meta": {"author": "damien-pous", "repo": "coinduction", "sha": "035e5c8608d068d890bed4893c463f0e6fd2f0f8", "save_path": "github-repos/coq/damien-pous-coinduction", "path": "github-repos/coq/damien-pous-coinduction/coinduction-035e5c8608d068d890bed4893c463f0e6fd2f0f8/theories/companion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513786759492, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6867917340864071}}
{"text": "Require Import prosa.classic.util.all.\nRequire Import prosa.classic.model.arrival.basic.task prosa.classic.model.arrival.basic.job prosa.classic.model.arrival.basic.task_arrival.\nRequire Import prosa.classic.model.schedule.uni.schedule.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.\n\nModule ResponseTime.\n\n  Import UniprocessorSchedule SporadicTaskset TaskArrival.\n\n  (* In this section, we define the notion of response-time bound. *)\n  Section ResponseTimeBound.\n\n    Context {sporadic_task: eqType}.\n    Context {Job: eqType}.\n    Variable job_arrival: Job -> time.\n    Variable job_cost: Job -> time.\n    Variable job_task: Job -> sporadic_task.\n\n    (* Consider any job arrival sequence... *)\n    Variable arr_seq: arrival_sequence Job.\n\n    (* ...and any uniprocessor schedule of these jobs. *)\n    Variable sched: schedule Job.\n\n    (* For simplicity, let's define some local names. *)\n    Let job_has_completed_by := completed_by job_cost sched.\n\n    Section Job.\n      \n      (* Given any job j, ... *)\n      Variable j: Job.\n    \n      (* ...we say that R is a response-time bound of j in this schedule ... *)\n      Variable R: time.\n\n      (* ... iff j completes by (job_arrival j + R). *)\n      Definition is_response_time_bound_of_job := job_has_completed_by j (job_arrival j + R).\n\n    End Job.\n\n    Section Task.\n\n      (* Let tsk be any task that is to be analyzed. *)\n      Variable tsk: sporadic_task.\n\n      (* Then, we say that R is a response-time bound of tsk in this schedule ... *)\n      Variable R: time.\n\n      (* ... iff any job j of tsk in this arrival sequence has\n         completed by (job_arrival j + R). *)\n      Definition is_response_time_bound_of_task :=\n        forall j,\n          arrives_in arr_seq j ->\n          job_task j = tsk ->\n          is_response_time_bound_of_job j R.\n      \n      End Task.\n    \n  End ResponseTimeBound.\n\n  (* In this section, we prove some basic lemmas about response-time bounds. *)\n  Section BasicLemmas.\n\n    Context {sporadic_task: eqType}.\n    Context {Job: eqType}.\n    Variable job_arrival: Job -> time.\n    Variable job_cost: Job -> time.\n    Variable job_task: Job -> sporadic_task.\n    \n    (* Consider any job arrival sequence... *)\n    Variable arr_seq: arrival_sequence Job.\n\n    (* ...and any uniprocessor schedule of these jobs. *)\n    Variable sched: schedule Job.\n\n    (* Assume that jobs don't execute after completion. *)\n    Hypothesis H_completed_jobs_dont_execute:\n      completed_jobs_dont_execute job_cost sched.\n\n    (* For simplicity, let's define some local names. *)\n    Let response_time_bounded_by := is_response_time_bound_of_job job_arrival job_cost sched.\n\n    (* We begin by proving lemmas about job response-time bounds. *)\n    Section SpecificJob.\n\n      (* Let j be any job... *)\n      Variable j: Job.\n      \n      (* ...with response-time bound R. *)\n      Variable R: time.\n      Hypothesis response_time_bound: response_time_bounded_by j R.\n\n      (* Then, the service received by j at any time t' after its response time is 0. *)\n      Lemma service_after_job_rt_zero :\n        forall t',\n          t' >= job_arrival j + R ->\n          service_at sched j t' = 0.\n      Proof.\n        rename response_time_bound into RT,\n               H_completed_jobs_dont_execute into EXEC; ins.\n        unfold is_response_time_bound_of_task, completed_by,\n               completed_jobs_dont_execute in *.\n        apply/eqP; rewrite eqb0; apply/negP; intros CONTR.\n        unfold response_time_bounded_by,is_response_time_bound_of_job in *.\n        eapply completion_monotonic in RT; eauto 2.\n        apply completed_implies_not_scheduled in RT; eauto 2.\n          by move: RT => /negP RT; apply:RT.\n      Qed.\n\n      (* The same applies for the cumulative service of job j. *)\n      Lemma cumulative_service_after_job_rt_zero :\n        forall t' t'',\n          t' >= job_arrival j + R ->\n          \\sum_(t' <= t < t'') service_at sched j t = 0.\n      Proof.\n        ins; apply/eqP; rewrite -leqn0.\n        rewrite big_nat_cond; rewrite -> eq_bigr with (F2 := fun i => 0);\n          first by rewrite big_const_seq iter_addn mul0n addn0 leqnn.\n        intro i; rewrite andbT; move => /andP [LE _].\n        by rewrite service_after_job_rt_zero;\n          [by ins | by apply leq_trans with (n := t')].\n      Qed.\n      \n    End SpecificJob.\n\n    (* Next, we prove properties about task response-time bounds. *)\n    Section AllJobs.\n\n      (* Consider any task tsk ...*)\n      Variable tsk: sporadic_task.\n\n      (* ... for which a response-time bound R is known. *)\n      Variable R: time.\n      Hypothesis response_time_bound:\n        is_response_time_bound_of_task job_arrival job_cost job_task arr_seq sched tsk R.\n\n      (* Then, for any job j of this task, ...*)\n      Variable j: Job.\n      Hypothesis H_from_arrival_sequence: arrives_in arr_seq j.\n      Hypothesis H_job_of_task: job_task j = tsk.\n\n      (* ...the service received by job j at any time t' after the response time is 0. *)\n      Lemma service_after_task_rt_zero :\n        forall t',\n          t' >= job_arrival j + R ->\n          service_at sched j t' = 0.\n      Proof.\n        intros t' LE.\n        apply service_after_job_rt_zero with (R := R); last by done.\n        by apply response_time_bound.\n      Qed.\n\n      (* The same applies for the cumulative service of job j. *)\n      Lemma cumulative_service_after_task_rt_zero :\n        forall t' t'',\n          t' >= job_arrival j + R ->\n          \\sum_(t' <= t < t'') service_at sched j t = 0.\n      Proof.\n        by ins; apply cumulative_service_after_job_rt_zero with (R := R);\n          first by apply response_time_bound. \n      Qed.\n      \n    End AllJobs.\n\n  End BasicLemmas.\n    \nEnd ResponseTime.", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/classic/model/schedule/uni/response_time.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6867681546393534}}
{"text": "Require Import A1_Plan.\n\nSection CLOCKWISE.\n\n(* Il existe une relation sur les triplets de points d'orientation dans le sens des aiguilles d'une montre. *)\n\nParameter Clockwise : Point -> Point -> Point -> Prop.\n\nDefinition HalfPlane (A B : Point) : Figure := Clockwise A B.\n\nDefinition EquiOriented (A B C D: Point) : Prop  := \n\tforall M : Point, Clockwise A B M -> Clockwise C D M.\n\nDefinition EquiDirected := fun A B C D : Point =>\n\tEquiOriented A B C D \\/ EquiOriented A B D C \\/\n\tEquiOriented B A C D \\/ EquiOriented B A D C \\/\n\tEquiOriented C D A B \\/ EquiOriented C D B A \\/\n\tEquiOriented D C A B \\/ EquiOriented D C B A.\n\nDefinition OpenRay (A B : Point) : Figure  := EquiOriented A B A.\n\nDefinition ClosedRay (A B : Point) : Figure  := \n\tfun M : Point => EquiOriented A M A B.\n\nDefinition Collinear (A B C : Point) := ~Clockwise A B C /\\ ~Clockwise B A C.\n\nDefinition Between (A B C : Point) :=\n\tA <> B /\\ EquiOriented A B B C.\n\nDefinition Segment (A B : Point) :=\n\tfun M : Point => ClosedRay A B M /\\ ClosedRay B A M.\n\n(* Trois points ne peuvent avoir deux orientations a la fois. *)\n\nAxiom ClockwiseAntisym : forall A B C, ~Clockwise A B C \\/ ~Clockwise B A C.\n\n(* La relation d'orientation est stable par permutation circulaire. *)\n\nAxiom ClockwisePerm : forall A B C, Clockwise A B C -> Clockwise B C A.\n\n(* Trois points sont necessairement orientes ou alignes. *)\n\nAxiom FourCases : forall A B C,\n\tClockwise A B C \\/ Clockwise B A C \\/ OpenRay A B C \\/ OpenRay B A C.\n \n(* Etant donne un triangle non degenere, tout point est dans le meme demi plan qu'un sommet par rapport au cote oppose. *)\n\nAxiom FourthPoint : forall A B C D,\n\tClockwise A B C ->\n\tClockwise A B D \\/ Clockwise A D C \\/ Clockwise D B C.\n\n(* Trois points colineaires partagent le plan en 2. *)\n\nAxiom ChangeSense : forall A B C D,\n\tEquiOriented A B C D ->\n\tCollinear A B C ->\n\tEquiOriented B A D C.\n\n(* Deux droites paralleles partagent le plan en 3. *)\n\nAxiom ChangeSide : forall A B C D,\n\tEquiOriented A B C D ->\n\tA <> B ->\n\tEquiOriented D C B A.\n\nEnd CLOCKWISE.\n", "meta": {"author": "coq-contribs", "repo": "euclidean-geometry", "sha": "06838851a5924918d98e5a9c07ffa84021e13af7", "save_path": "github-repos/coq/coq-contribs-euclidean-geometry", "path": "github-repos/coq/coq-contribs-euclidean-geometry/euclidean-geometry-06838851a5924918d98e5a9c07ffa84021e13af7/A2_Orientation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6867681532658882}}
{"text": "Require Export TopologicalSpaces.\nRequire Export Continuity.\nRequire Export SubspaceTopology.\n\nSection continuous_factorization.\n\nVariable X Y:TopologicalSpace.\nVariable f:point_set X -> point_set Y.\nVariable S:Ensemble (point_set Y).\nHypothesis f_cont: continuous f.\nHypothesis f_img: forall x:point_set X, In S (f x).\n\nDefinition continuous_factorization :\n  point_set X -> point_set (SubspaceTopology S) :=\n  fun x:point_set X => exist _ (f x) (f_img x).\n\nLemma factorization_is_continuous:\n  continuous continuous_factorization.\nProof.\nred; intros.\ndestruct (subspace_topology_topology _ _ V H) as [V' []].\nrewrite H1.\nrewrite <- inverse_image_composition.\nsimpl.\nassert (inverse_image (fun x:point_set X => f x) V' =\n        inverse_image f V').\napply Extensionality_Ensembles; split; red; intros.\ndestruct H2; constructor; trivial.\ndestruct H2; constructor; trivial.\nrewrite H2.\napply f_cont; trivial.\nQed.\n\nEnd continuous_factorization.\n\nImplicit Arguments continuous_factorization [[X] [Y]].\n\nSection continuous_surj_factorization.\n\nVariable X Y:TopologicalSpace.\nVariable f:point_set X -> point_set Y.\nHypothesis f_cont: continuous f.\n\nDefinition continuous_surj_factorization :\n  point_set X -> point_set (SubspaceTopology (Im Full_set f)).\napply continuous_factorization with f.\nintros.\nexists x.\nconstructor.\ntrivial.\nDefined.\n\nLemma continuous_surj_factorization_is_surjective:\n  surjective continuous_surj_factorization.\nProof.\nred; intros.\ndestruct y.\ndestruct i.\nexists x.\nunfold continuous_surj_factorization.\nunfold continuous_factorization.\npose proof (e).\nsymmetry in H.\ndestruct H.\nf_equal.\nf_equal.\napply proof_irrelevance.\napply proof_irrelevance.\nQed.\n\nLemma continuous_surj_factorization_is_continuous:\n  continuous continuous_surj_factorization.\nProof.\napply factorization_is_continuous.\nexact f_cont.\nQed.\n\nEnd continuous_surj_factorization.\n\nImplicit Arguments continuous_surj_factorization [[X] [Y]].\n", "meta": {"author": "dschepler", "repo": "coq-topology", "sha": "462b0777da71e8b860fcd67879278e919b295266", "save_path": "github-repos/coq/dschepler-coq-topology", "path": "github-repos/coq/dschepler-coq-topology/coq-topology-462b0777da71e8b860fcd67879278e919b295266/ContinuousFactorization.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654974, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6867681521316354}}
{"text": "(** * Natural numbers and their properties. Vladimir Voevodsky . Apr. - Sep. 2011  \n\nThis file contains the formulations and proofs of general properties of natural numbers from the univalent perspecive. *)\n\n\n\n\n\n\n(** ** Preambule *)\n\n(** Settings *)\n\nUnset Automatic Introduction. (* This line has to be removed for the file to compile with Coq8.2 *)\n\n\n\n(** Imports. *)\n\nAdd LoadPath \"../..\" .\n\nRequire Export Foundations.hlevel2.algebra1d . \n\n(** To up-stream files  *)\n\n\n\n(** ** Equality on [ nat ] *)\n\n\n(** *** Basic properties of [ paths ] on [ nat ] and the proofs of [ isdeceq ] and [ isaset ] for [ nat ] .  *) \n   \n\nLemma negpaths0sx ( x : nat ) : neg ( paths O (S x) ) .\nProof. intro. set (f:= fun n : nat => match n with O => true | S m => false end ) . apply ( negf ( @maponpaths _ _ f 0 ( S x ) ) nopathstruetofalse ) . Defined. \n\nLemma negpathssx0 ( x : nat ) : neg ( paths (S x) O ) .\nProof. intros x X. apply (negpaths0sx x (pathsinv0  X)). Defined. \n\nLemma invmaponpathsS ( n m : nat ) : paths ( S n ) ( S m ) -> paths n m .\nProof. intros n m e . set ( f := fun n : nat => match n with O => O | S m => m end ) .   apply ( @maponpaths _ _ f ( S n ) ( S m ) e ) .  Defined.  \n\nLemma noeqinjS ( x x' : nat ) : neg ( paths x x' ) -> neg ( paths (S x) (S x') ) .\nProof. intros x x'. apply ( negf ( invmaponpathsS x x' ) ) .  Defined. \n \nDefinition isdeceqnat: isdeceq nat.\nProof. unfold isdeceq.  intro x . induction x as [ | x IHx ] . intro x' .  destruct x'. apply ( ii1  ( idpath O ) ) . apply ( ii2  ( negpaths0sx x' ) ) . intro x' .  destruct x'.  apply ( ii2  (negpathssx0 x ) ) . destruct ( IHx x' ) as [ p | e ].   apply ( ii1 ( maponpaths S  p ) ) .  apply ( ii2 ( noeqinjS  _ _ e ) ) . Defined . \n\nDefinition isisolatedn ( n : nat ) : isisolated _ n .\nProof. intro. unfold isisolated . intro x' . apply isdeceqnat . Defined. \n\nTheorem isasetnat: isaset nat.\nProof.  apply (isasetifdeceq _ isdeceqnat). Defined. \n\nDefinition natset : hSet := hSetpair _ isasetnat . \n(* Canonical Structure natset . *) \n\nDefinition nateq ( x y : nat ) : hProp := hProppair ( paths x y ) ( isasetnat _ _  )  .\nDefinition isdecrelnateq : isdecrel nateq  := fun a b => isdeceqnat a b .\nDefinition natdeceq : decrel nat := decrelpair isdecrelnateq . \n(* Canonical Structure natdeceq. *)\n\nDefinition natbooleq := decreltobrel natdeceq .  \n\nDefinition natneq ( x y : nat ) : hProp := hProppair ( neg ( paths x y ) ) ( isapropneg _  )  .\nDefinition isdecrelnatneq : isdecrel natneq  := isdecnegrel _ isdecrelnateq . \nDefinition natdecneq : decrel nat := decrelpair isdecrelnatneq . \n\n(* Canonical Structure natdecneq. *) \n\nDefinition natboolneq := decreltobrel natdecneq .  \n\n(** *** [ S : nat -> nat ] is a decidable inclusion . *)\n\nTheorem isinclS : isincl S .\nProof. apply ( isinclbetweensets S isasetnat isasetnat invmaponpathsS ) .  Defined .\n\nTheorem isdecinclS : isdecincl S .\nProof. intro n . apply isdecpropif . apply ( isinclS n ) .  destruct n as [ | n ] .  assert ( nh : neg ( hfiber S 0 ) ) .  intro hf .  destruct hf as [ m e ] .  apply ( negpathssx0 _ e ) .  apply ( ii2 nh ) .  apply ( ii1 ( hfiberpair _ n ( idpath _ ) ) ) .  Defined . \n\n\n(** ** Inequalities on [ nat ] . *)\n\n\n(** *** Boolean \"less or equal\" and \"greater or equal\" on [ nat ] . *)\n\nFixpoint natgtb (n m : nat) : bool :=\nmatch n , m with\n | S n , S m => natgtb n m\n | O, _ => false\n | _, _ => true\nend.\n\n\n\n(** *** Semi-boolean \"greater\" on [ nat ] or [ natgth ]  \n\n1. Note that due to its definition [ natgth ] automatically has the property that [ natgth n m <-> natgth ( S n ) ( S m ) ] and the same applies to all other inequalities defined in this section.\n2. We choose \"greater\" as the root relation from which we define all other relations on [ nat ] because it is more natural to extend \"greater\" to integers and then to rationals than it is to extend \"less\".   *) \n\n\nDefinition natgth ( n m : nat ) := hProppair ( paths ( natgtb n m ) true ) ( isasetbool _ _ ) . \n\nLemma negnatgth0n ( n : nat ) : neg ( natgth 0 n ) .\nProof. intro n . simpl . intro np . apply ( nopathsfalsetotrue np ) .  Defined . \n\nLemma natgthsnn ( n : nat ) : natgth ( S n ) n .\nProof . intro . induction n as [ | n IHn ] . simpl . apply idpath .   apply IHn . Defined .\n\nLemma natgthsn0 ( n : nat ) : natgth ( S n ) 0 .\nProof . intro . simpl . apply idpath .  Defined . \n\nLemma negnatgth0tois0 ( n : nat ) ( ng : neg ( natgth n 0 ) ) : paths n 0 .\nProof . intro. destruct n as [ | n ] . intro.   apply idpath.  intro ng .  destruct ( ng ( natgthsn0 _ ) ) . Defined . \n\nLemma natneq0togth0 ( n : nat ) ( ne : neg ( paths n 0 ) ) : natgth n 0 .\nProof . intros . destruct n as [ | n ] . destruct ( ne ( idpath _ ) ) .  apply natgthsn0 .  Defined . \n\nLemma nat1gthtois0 ( n : nat ) ( g : natgth 1 n ) : paths n 0 .\nProof . intro . destruct n as [ | n ] . intro . apply idpath . intro x .  destruct ( negnatgth0n n x ) .  Defined .\n\nLemma istransnatgth ( n m k : nat ) : natgth n m -> natgth m k -> natgth n k .\nProof. intro. induction n as [ | n IHn ] . intros m k g . destruct ( negnatgth0n _ g ) .  intro m . destruct m as [ | m ] . intros k g g' . destruct ( negnatgth0n _ g' ) . intro k . destruct k as [ | k ] . intros . apply natgthsn0 . apply ( IHn m k ) .  Defined. \n\nLemma isirreflnatgth ( n : nat ) : neg ( natgth n n ) .\nProof. intro . induction n as [ | n IHn ] . apply ( negnatgth0n 0 ) .  apply IHn .  Defined . \n\nNotation negnatlthnn := isirreflnatgth . \n\nLemma natgthtoneq ( n m : nat ) ( g : natgth n m ) : neg ( paths n m ) .\nProof . intros . intro e . rewrite e in g . apply ( isirreflnatgth _ g ) . Defined .  \n\nLemma isasymmnatgth ( n m : nat ) : natgth n m -> natgth m n -> empty .\nProof. intros n m is is' . apply ( isirreflnatgth n ( istransnatgth _ _ _ is is' ) ) . Defined .  \n\nLemma isantisymmnegnatgth ( n m : nat ) : neg ( natgth n m ) -> neg ( natgth m n ) -> paths n m .\nProof . intro n . induction n as [ | n IHn ] . intros m ng0m ngm0  .  apply ( pathsinv0 ( negnatgth0tois0 _ ngm0 ) ) . intro m . destruct m as [ | m ] . intros ngsn0 ng0sn . destruct ( ngsn0 ( natgthsn0 _ ) ) .  intros ng1 ng2 .   apply ( maponpaths S ( IHn m ng1 ng2 ) ) .  Defined .     \n\nLemma isdecrelnatgth : isdecrel natgth .\nProof. intros n m . apply ( isdeceqbool ( natgtb n m ) true ) .  Defined .\n\nDefinition natgthdec := decrelpair isdecrelnatgth .\n\n(* Canonical Structure natgthdec . *)\n\nLemma isnegrelnatgth : isnegrel natgth .\nProof . apply isdecreltoisnegrel . apply isdecrelnatgth . Defined . \n\nLemma iscoantisymmnatgth ( n m : nat ) : neg ( natgth n m ) -> coprod ( natgth m n ) ( paths n m ) .\nProof . apply isantisymmnegtoiscoantisymm . apply isdecrelnatgth .  intros n m . apply isantisymmnegnatgth . Defined .  \n\nLemma iscotransnatgth ( n m k : nat ) : natgth n k -> hdisj ( natgth n m ) ( natgth m k ) .\nProof . intros x y z gxz .  destruct ( isdecrelnatgth x y ) as [ gxy | ngxy ] . apply ( hinhpr _ ( ii1 gxy ) ) . apply hinhpr .   apply ii2 .  destruct ( isdecrelnatgth y x ) as [ gyx | ngyx ] . apply ( istransnatgth _ _ _ gyx gxz ) .  set ( e := isantisymmnegnatgth _ _ ngxy ngyx ) . rewrite e in gxz .  apply gxz .  Defined .   \n\n\n\n\n(** *** Semi-boolean \"less\" on [ nat ] or [ natlth ] *)\n\nDefinition natlth ( n m : nat ) := natgth m n .\n\nDefinition negnatlthn0 ( n : nat ) : neg ( natlth n 0 ) := negnatgth0n n .\n\nDefinition natlthnsn ( n : nat ) : natlth n ( S n ) := natgthsnn n . \n\nDefinition negnat0lthtois0 ( n : nat ) ( nl : neg ( natlth 0 n ) ) : paths n 0 := negnatgth0tois0 n nl .\n\nDefinition natneq0to0lth ( n : nat ) ( ne : neg ( paths n 0 ) ) : natlth 0 n := natneq0togth0 n ne .\n\nDefinition natlth1tois0 ( n : nat ) ( l : natlth n 1 ) : paths n 0 := nat1gthtois0 _ l . \n\nDefinition istransnatlth ( n m k  : nat ) : natlth n m -> natlth m k -> natlth n k := fun lnm lmk => istransnatgth _ _ _ lmk lnm . \n\nDefinition isirreflnatlth ( n : nat ) : neg ( natlth n n ) := isirreflnatgth n . \n\nNotation negnatgthnn := isirreflnatlth . \n\nLemma natlthtoneq ( n m : nat ) ( g : natlth n m ) : neg ( paths n m ) .\nProof . intros . intro e . rewrite e in g . apply ( isirreflnatlth _ g ) . Defined .   \n\nDefinition isasymmnatlth ( n m : nat ) : natlth n m -> natlth m n -> empty := fun lnm lmn => isasymmnatgth _ _ lmn lnm .\n\nDefinition isantisymmnegnattth  ( n m : nat ) : neg ( natlth n m ) -> neg ( natlth m n ) -> paths n m := fun nlnm nlmn => isantisymmnegnatgth _ _ nlmn nlnm .\n\nDefinition isdecrelnatlth  : isdecrel natlth  := fun n m => isdecrelnatgth m n . \n\nDefinition natlthdec := decrelpair isdecrelnatlth .\n\n(* Canonical Structure natlthdec . *)\n\nDefinition isnegrelnatlth : isnegrel natlth := fun n m => isnegrelnatgth m n .\n\nDefinition iscoantisymmnatlth ( n m : nat ) : neg ( natlth n m ) -> coprod ( natlth m n ) ( paths n m ) .\nProof . intros n m nlnm . destruct ( iscoantisymmnatgth m n nlnm ) as [ l | e ] . apply ( ii1 l ) . apply ( ii2 ( pathsinv0 e ) ) . Defined . \n\nDefinition iscotransnatlth ( n m k : nat ) : natlth n k -> hdisj ( natlth n m ) ( natlth m k ) . \nProof . intros n m k lnk . apply ( ( pr1 islogeqcommhdisj ) ( iscotransnatgth _ _ _ lnk ) )  .  Defined .      \n\n\n\n(** *** Semi-boolean \"less or equal \" on [ nat ] or [ natleh ] *)\n\nDefinition natleh ( n m : nat ) := hProppair ( neg ( natgth n m ) ) ( isapropneg _ )  .\n\nDefinition natleh0tois0 ( n : nat ) ( l : natleh n 0 ) : paths n 0 := negnatgth0tois0 _ l .\n\nDefinition natleh0n ( n : nat ) : natleh 0 n := negnatgth0n _ .\n\nDefinition negnatlehsn0 ( n : nat ) : neg ( natleh ( S n ) 0 ) := todneg _ ( natgthsn0 n ) . \n\nDefinition negnatlehsnn ( n : nat ) : neg ( natleh ( S n ) n ) := todneg _ ( natgthsnn _ ) . \n\nDefinition  istransnatleh ( n m k : nat ) : natleh n m -> natleh m k -> natleh n k .\nProof. apply istransnegrel . unfold iscotrans. apply iscotransnatgth .  Defined.   \n\nDefinition isreflnatleh ( n : nat ) : natleh n n := isirreflnatgth n .  \n\nDefinition isantisymmnatleh ( n m : nat ) : natleh n m -> natleh m n -> paths n m := isantisymmnegnatgth n m .   \n\nDefinition isdecrelnatleh : isdecrel natleh := isdecnegrel _ isdecrelnatgth . \n\nDefinition natlehdec := decrelpair isdecrelnatleh .\n\n(* Canonical Structure natlehdec . *)\n\nDefinition isnegrelnatleh : isnegrel natleh .\nProof . apply isdecreltoisnegrel . apply isdecrelnatleh . Defined . \n\nDefinition iscoasymmnatleh ( n m : nat ) ( nl : neg ( natleh n m ) ) : natleh m n := negf ( isasymmnatgth _ _ ) nl . \n\nDefinition istotalnatleh : istotal natleh . \nProof . intros x y . destruct ( isdecrelnatleh x y ) as [ lxy | lyx ] . apply ( hinhpr _ ( ii1 lxy ) ) . apply hinhpr .   apply ii2 . apply ( iscoasymmnatleh _ _ lyx ) .   Defined . \n\n\n\n(** *** Semi-boolean \"greater or equal\" on [ nat ] or [ natgeh ] . *)\n\n\nDefinition natgeh ( n m : nat ) : hProp := hProppair ( neg ( natgth m n ) ) ( isapropneg _ ) .  \n\nDefinition nat0gehtois0 ( n : nat ) ( g : natgeh 0 n ) : paths n 0 := natleh0tois0 _ g . \n\nDefinition natgehn0 ( n : nat ) : natgeh n 0 := natleh0n n .  \n\nDefinition negnatgeh0sn ( n : nat ) : neg ( natgeh 0 ( S n ) ) := negnatlehsn0 n . \n\nDefinition negnatgehnsn ( n : nat ) : neg ( natgeh n ( S n ) ) := negnatlehsnn n . \n\nDefinition istransnatgeh ( n m k : nat ) : natgeh n m -> natgeh m k -> natgeh n k := fun gnm gmk => istransnatleh _ _ _ gmk gnm . \n\nDefinition isreflnatgeh ( n : nat ) : natgeh n n := isreflnatleh _ . \n\nDefinition isantisymmnatgeh ( n m : nat ) : natgeh n m -> natgeh m n -> paths n m := fun gnm gmn => isantisymmnatleh _ _ gmn gnm . \n\nDefinition isdecrelnatgeh : isdecrel natgeh := fun n m => isdecrelnatleh m n .\n\nDefinition natgehdec := decrelpair isdecrelnatgeh .\n\n(* Canonical Structure natgehdec . *)\n\nDefinition isnegrelnatgeh : isnegrel natgeh := fun n m => isnegrelnatleh m n . \n\nDefinition iscoasymmnatgeh ( n m : nat ) ( nl : neg ( natgeh n m ) ) : natgeh m n := iscoasymmnatleh _ _ nl . \n\nDefinition istotalnatgeh : istotal natgeh := fun n m => istotalnatleh m n .\n\n\n\n\n(** *** Simple implications between comparisons *)\n\nDefinition natgthtogeh ( n m : nat ) : natgth n m -> natgeh n m .\nProof. intros n m g . apply iscoasymmnatgeh . apply ( todneg _ g ) . Defined .\n\nDefinition natlthtoleh ( n m : nat ) : natlth n m -> natleh n m := natgthtogeh _ _ . \n\nDefinition natlehtonegnatgth ( n m : nat ) : natleh n m -> neg ( natgth n m )  .\nProof. intros n m is is' . apply ( is is' ) .  Defined . \n\nDefinition  natgthtonegnatleh ( n m : nat ) : natgth n m -> neg ( natleh n m ) := fun g l  => natlehtonegnatgth _ _ l g .   \n\nDefinition natgehtonegnatlth ( n m : nat ) : natgeh n m -> neg ( natlth n m ) := fun gnm lnm => natlehtonegnatgth _ _ gnm lnm . \n\nDefinition natlthtonegnatgeh ( n m : nat ) : natlth n m -> neg ( natgeh n m ) := fun gnm lnm => natlehtonegnatgth _ _ lnm gnm .  \n\nDefinition negnatlehtogth ( n m : nat ) : neg ( natleh n m ) -> natgth n m := isnegrelnatgth n m .   \n\nDefinition negnatgehtolth ( n m : nat ) : neg ( natgeh n m ) -> natlth n m := isnegrelnatlth n m .\n\nDefinition negnatgthtoleh ( n m : nat ) : neg ( natgth n m ) -> natleh n m .\nProof . intros n m ng . destruct ( isdecrelnatleh n m ) as [ l | nl ] . apply l . destruct ( nl ng ) .  Defined . \n\nDefinition negnatlthtogeh ( n m : nat ) : neg ( natlth n m ) -> natgeh n m := fun nl => negnatgthtoleh _ _ nl . \n\n\n(* *** Simple corollaries of implications *** *)\n\nDefinition natlehnsn ( n : nat ) : natleh n ( S n ) := natlthtoleh _ _ ( natgthsnn n ) .  \n\nDefinition natgehsnn ( n : nat ) : natgeh ( S n ) n := natlehnsn n  .\n\n\n(** *** Comparison alternatives *)\n\n\nDefinition natgthorleh ( n m : nat ) : coprod ( natgth n m ) ( natleh n m ) .\nProof . intros . apply ( isdecrelnatgth n m ) .  Defined . \n\nDefinition natlthorgeh ( n m : nat ) : coprod ( natlth n m ) ( natgeh n m ) := natgthorleh _ _ .\n\nDefinition natneqchoice ( n m : nat ) ( ne : neg ( paths n m ) ) : coprod ( natgth n m ) ( natlth n m ) .\nProof . intros . destruct ( natgthorleh n m ) as [ l | g ]  .   apply ( ii1 l ) .  destruct ( natlthorgeh n m ) as [ l' | g' ] . apply ( ii2 l' ) .  destruct ( ne ( isantisymmnatleh _ _ g g' ) ) . Defined . \n\nDefinition natlehchoice ( n m : nat ) ( l : natleh n m ) : coprod ( natlth n m ) ( paths n m ) .\nProof .  intros . destruct ( natlthorgeh n m ) as [ l' | g ] .  apply ( ii1 l' ) . apply ( ii2 ( isantisymmnatleh _ _ l g ) ) . Defined . \n\nDefinition natgehchoice ( n m : nat ) ( g : natgeh n m ) : coprod ( natgth n m ) ( paths n m ) .\nProof .  intros . destruct ( natgthorleh n m ) as [ g' | l ] .  apply ( ii1 g' ) . apply ( ii2 ( isantisymmnatleh _ _ l g ) ) .  Defined . \n\n\n\n\n(** *** Mixed transitivities *)\n\n\n\nLemma natgthgehtrans ( n m k : nat ) : natgth n m -> natgeh m k -> natgth n k .\nProof. intros n m k gnm gmk . destruct ( natgehchoice m k gmk ) as [ g' | e ] . apply ( istransnatgth _ _ _ gnm g' ) .  rewrite e in gnm  .  apply gnm . Defined. \n\nLemma natgehgthtrans ( n m k : nat ) : natgeh n m -> natgth m k -> natgth n k .\nProof. intros n m k gnm gmk . destruct ( natgehchoice n m gnm ) as [ g' | e ] . apply ( istransnatgth _ _ _ g' gmk ) .  rewrite e .  apply gmk . Defined. \n\nLemma natlthlehtrans ( n m k : nat ) : natlth n m -> natleh m k -> natlth n k .\nProof . intros n m k l1 l2 . apply ( natgehgthtrans k m n l2 l1 ) . Defined . \n\nLemma natlehlthtrans ( n m k : nat ) : natleh n m -> natlth m k -> natlth n k .\nProof . intros n m k l1 l2 . apply ( natgthgehtrans k m n l2 l1 ) . Defined . \n\n\n\n(** *** Two comparisons and [ S ] *)\n\nLemma natgthtogehsn ( n m : nat ) : natgth n m -> natgeh n ( S m ) .\nProof. intro n . induction n as [ | n IHn ] .  intros m X .  destruct ( negnatgth0n _ X ) . intros m X . destruct m as [ | m ] .  apply ( natgehn0 n ) .  apply ( IHn m X ) .  Defined . \n\nLemma natgthsntogeh ( n m : nat ) : natgth ( S n ) m -> natgeh n m .\nProof. intros n m a . apply ( natgthtogehsn ( S n ) m a ) . Defined. (* PeWa *) \n\nLemma natgehtogthsn ( n m : nat ) : natgeh n m -> natgth ( S n ) m .\nProof . intros n m X . apply ( natgthgehtrans _ n _ ) .  apply natgthsnn . apply X . Defined.  (* New *)\n\nLemma natgehsntogth ( n m : nat ) : natgeh n ( S m ) -> natgth n m .\nProof. intros n m X . apply ( natgehgthtrans _ ( S m ) _ X ) .  apply natgthsnn . Defined .  (* New *)\n\nLemma natlthtolehsn ( n m : nat ) : natlth n m -> natleh ( S n ) m .\nProof. intros n m X . apply ( natgthtogehsn m n X ) . Defined .\n\nLemma natlehsntolth ( n m : nat ) : natleh ( S n ) m -> natlth n m .\nProof.  intros n m X . apply ( natgehsntogth m n X ) .   Defined . \n\nLemma natlehtolthsn ( n m : nat ) : natleh n m -> natlth n ( S m ) . \nProof. intros n m X . apply ( natgehtogthsn m n X ) .  Defined.\n\nLemma natlthsntoleh ( n m : nat ) : natlth n ( S m ) -> natleh n m .\nProof. intros n m a . apply ( natlthtolehsn n ( S m ) a ) . Defined. (* PeWa *) \n\n\n\n(** *** Comparsion alternatives and [ S ] *)\n\n\nLemma natlehchoice2 ( n m : nat ) : natleh n m -> coprod ( natleh ( S n ) m ) ( paths n m ) .\nProof . intros n m l . destruct ( natlehchoice n m l ) as [ l' | e ] .   apply ( ii1 ( natlthtolehsn _ _ l' ) ) . apply ( ii2 e ) .  Defined . \n\n\nLemma natgehchoice2 ( n m : nat ) : natgeh n m -> coprod ( natgeh n ( S m ) ) ( paths n m ) .\nProof . intros n m g . destruct ( natgehchoice n m g ) as [ g' | e ] .   apply ( ii1 ( natgthtogehsn _ _ g' ) ) . apply ( ii2 e ) . Defined . \n\n\nLemma natgthchoice2 ( n m : nat ) : natgth n m -> coprod ( natgth n ( S m ) ) ( paths n ( S m ) ) .\nProof.  intros n m g . destruct ( natgehchoice _ _ ( natgthtogehsn _ _ g ) ) as [ g' | e ] . apply ( ii1 g' ) .  apply ( ii2 e ) .  Defined . \n\n\nLemma natlthchoice2 ( n m : nat ) : natlth n m -> coprod ( natlth ( S n ) m ) ( paths ( S n ) m ) .\nProof.  intros n m l . destruct ( natlehchoice _ _ ( natlthtolehsn _ _ l ) ) as [ l' | e ] . apply ( ii1 l' ) .  apply ( ii2 e ) .   Defined . \n   \n\n\n\n\n\n(** ** Some properties of [ plus ] on [ nat ] *)\n\n(* Addition is defined in Init/Peano.v by the following code \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*)\n\n\n(** *** The structure of the additive ablelian monoid on [ nat ] *) \n\n\nLemma natplusl0 ( n : nat ) : paths ( 0 + n ) n .\nProof . intros . apply idpath . Defined .  \n\nLemma natplusr0 ( n : nat ) : paths ( n + 0 ) n .\nProof . intro . induction n as [ | n IH n ] . apply idpath .  simpl . apply ( maponpaths S IH ) . Defined .\nHint Resolve natplusr0: natarith .\n\nLemma natplusnsm ( n m : nat ) : paths ( n + S m ) ( S n + m ) .\nProof. intro . simpl . induction n as [ | n IHn ] .  auto with natarith . simpl . intro . apply ( maponpaths S ( IHn m ) ) .  Defined . \nHint Resolve natplusnsm : natarith .\n\nLemma natpluscomm ( n m : nat ) : paths ( n + m ) ( m + n ) .\nProof. intro. induction n as [ | n IHn ] . intro . auto with natarith .  intro .  set ( int := IHn ( S m ) ) . set ( int2 := pathsinv0 ( natplusnsm n m ) ) . set ( int3 := pathsinv0 ( natplusnsm m n ) ) .  set ( int4 := pathscomp0 int2 int  ) .  apply ( pathscomp0 int4 int3 ) . Defined . \nHint Resolve natpluscomm : natarith . \n\nLemma natplusassoc ( n m k : nat ) : paths ( ( n + m ) + k ) ( n + ( m + k ) ) .\nProof . intro . induction n as [ | n IHn ] . auto with natarith . intros . simpl .  apply ( maponpaths S ( IHn m k ) ) . Defined. \nHint Resolve natplusassoc : natarith .\n\nDefinition nataddabmonoid : abmonoid := abmonoidpair ( setwithbinoppair natset ( fun n m : nat => n + m ) ) ( dirprodpair ( dirprodpair natplusassoc ( @isunitalpair natset _ 0 ( dirprodpair natplusl0 natplusr0 ) ) ) natpluscomm ) .    \n\n\n\n\n(** *** Addition and comparisons  *)\n\n\n\n(** [ natgth ] *)\n\n\n\nDefinition natgthtogths ( n m : nat ) : natgth n m -> natgth ( S n ) m  .\nProof. intros n m is . apply ( istransnatgth _ _ _ ( natgthsnn n ) is ) . Defined .\n\nDefinition negnatgthmplusnm ( n m : nat ) : neg ( natgth m ( n + m ) ) .\nProof. intros . induction n as [ | n IHn ] .  apply isirreflnatgth . apply ( istransnatleh _ _ _ IHn ( ( natlthtoleh _ _ ( natlthnsn _ ) ) ) ) .  Defined . \n\nDefinition negnatgthnplusnm ( n m : nat ) : neg ( natgth n ( n + m ) ) .\nProof. intros . rewrite ( natpluscomm n m ) .  apply ( negnatgthmplusnm m n ) .  Defined . \n\nDefinition natgthandplusl ( n m k : nat ) : natgth n m -> natgth ( k + n ) ( k + m ) .\nProof. intros n m k l . induction k as [ | k IHk ] . assumption .  assumption .  Defined . \n\nDefinition natgthandplusr ( n m k : nat ) : natgth n m -> natgth ( n + k ) ( m + k ) .\nProof. intros . rewrite ( natpluscomm n k ) . rewrite ( natpluscomm m k ) . apply natgthandplusl . assumption . Defined . \n\nDefinition natgthandpluslinv  ( n m k : nat ) : natgth ( k + n ) ( k + m ) -> natgth n m  .\nProof. intros n m k l . induction k as [ | k IHk ] . assumption .  apply ( IHk l ) . Defined .\n\nDefinition natgthandplusrinv ( n m k : nat ) :  natgth ( n + k ) ( m + k ) -> natgth n m  . \nProof. intros n m k l . rewrite ( natpluscomm n k ) in l . rewrite ( natpluscomm m k ) in l . apply ( natgthandpluslinv _ _ _ l )  . Defined . \n \n\n(** [ natlth ] *)\n\n\nDefinition natlthtolths ( n m : nat ) : natlth n m -> natlth n ( S m ) := natgthtogths _ _ . \n\nDefinition negnatlthplusnmm ( n m : nat ) : neg ( natlth ( n + m ) m )  := negnatgthmplusnm _ _ .\n\nDefinition negnatlthplusnmn ( n m : nat ) : neg ( natlth ( n + m ) n )  := negnatgthnplusnm _ _ .\n\nDefinition natlthandplusl ( n m k : nat ) : natlth n m -> natlth ( k + n ) ( k + m )  := natgthandplusl _ _ _ . \n\nDefinition natlthandplusr ( n m k : nat ) : natlth n m -> natlth ( n + k ) ( m + k ) := natgthandplusr _ _ _ .\n\nDefinition natlthandpluslinv  ( n m k : nat ) : natlth ( k + n ) ( k + m ) -> natlth n m := natgthandpluslinv _ _ _ .\n\nDefinition natlthandplusrinv ( n m k : nat ) :  natlth ( n + k ) ( m + k ) -> natlth n m := natgthandplusrinv _ _ _ . \n\n\n\n(** [ natleh ] *)\n\n\nDefinition natlehtolehs ( n m : nat ) : natleh n m -> natleh n ( S m ) .  \nProof . intros n m is . apply ( istransnatleh _ _ _ is ( natlthtoleh _ _ ( natlthnsn _ ) ) ) . Defined .\n\nDefinition natlehmplusnm ( n m : nat ) : natleh m ( n + m )  := negnatlthplusnmm _ _  .\n\nDefinition natlehnplusnm ( n m : nat ) : natleh n ( n + m ) := negnatlthplusnmn _ _  .\n\nDefinition natlehandplusl ( n m k : nat ) : natleh n m -> natleh ( k + n ) ( k + m ) := negf ( natgthandpluslinv n m k )  . \n\nDefinition natlehandplusr ( n m k : nat ) : natleh n m -> natleh ( n + k ) ( m + k ) := negf ( natgthandplusrinv n m k )  . \n\nDefinition natlehandpluslinv  ( n m k : nat ) : natleh ( k + n ) ( k + m ) -> natleh n m := negf ( natgthandplusl n m k )  .  \n\nDefinition natlehandplusrinv ( n m k : nat ) :  natleh ( n + k ) ( m + k ) -> natleh n m :=  negf ( natgthandplusr n m k ) . \n\n\n\n\n(** [ natgeh ] *)\n\n\nDefinition natgehtogehs ( n m : nat ) : natgeh n m -> natgeh ( S n ) m := natlehtolehs _ _  .\n \nDefinition natgehplusnmm ( n m : nat ) : natgeh ( n + m ) m := negnatgthmplusnm _ _ .\n\nDefinition natgehplusnmn ( n m : nat ) : natgeh ( n + m ) n := negnatgthnplusnm _ _  . \n\nDefinition natgehandplusl ( n m k : nat ) : natgeh n m -> natgeh ( k + n ) ( k + m ) := negf ( natgthandpluslinv m n k ) .  \n\nDefinition natgehandplusr ( n m k : nat ) : natgeh n m -> natgeh ( n + k ) ( m + k ) := negf ( natgthandplusrinv m n k )  . \n\nDefinition natgehandpluslinv  ( n m k : nat ) : natgeh ( k + n ) ( k + m ) -> natgeh n m := negf ( natgthandplusl m n k )  . \n\nDefinition natgehandplusrinv ( n m k : nat ) :  natgeh ( n + k ) ( m + k ) -> natgeh n m :=  negf ( natgthandplusr m n k ) . \n\n\n\n(* The following are included mainly for direct compatibility with the library hz.v *)\n\n\n\n(** *** Comparisons and [ n -> n + 1 ] *)\n\nDefinition natgthtogthp1 ( n m : nat ) : natgth n m -> natgth ( n + 1 ) m  .\nProof. intros n m is . destruct (natpluscomm 1 n) . apply (natgthtogths n m is). Defined. \n \nDefinition natlthtolthp1 ( n m : nat ) : natlth n m -> natlth n ( m + 1 ) := natgthtogthp1 _ _ . \n\nDefinition natlehtolehp1 ( n m : nat ) : natleh n m -> natleh n ( m + 1 ) .  \nProof . intros n m is . destruct (natpluscomm 1 m) . apply (natlehtolehs n m is). Defined. \n\nDefinition natgehtogehp1 ( n m : nat ) : natgeh n m -> natgeh ( n + 1 ) m := natlehtolehp1 _ _  .\n \n\n\n(** *** Two comparisons and [ n -> n + 1 ] *)\n\nLemma natgthtogehp1 ( n m : nat ) : natgth n m -> natgeh n ( m + 1 ) .\nProof. intros n m is . destruct (natpluscomm 1 m) . apply (natgthtogehsn n m is). Defined . \n\n\nLemma natgthp1togeh ( n m : nat ) : natgth ( n + 1 ) m -> natgeh n m .\nProof.   intros n m is . destruct (natpluscomm 1 n) . apply ( natgthsntogeh n m is). Defined. (* PeWa *) \n\nLemma natlehp1tolth ( n m : nat ) : natleh ( n + 1 )  m -> natlth n m .\nProof.  intros n m is . destruct (natpluscomm 1 n) . apply (natlehsntolth n m is).  Defined . \n\nLemma natlthtolehp1 ( n m : nat ) : natlth n m -> natleh ( n + 1 )  m .\nProof. intros n m is . destruct (natpluscomm 1 n) . apply (natlthtolehsn n m is). Defined .\n\nLemma natlthp1toleh ( n m : nat ) : natlth n ( m + 1 ) -> natleh n m .\nProof. intros n m is . destruct (natpluscomm 1 m) . apply (natlthsntoleh n m is). Defined. (* PeWa *) \n\nLemma natgehp1togth ( n m : nat ) : natgeh n ( m + 1 ) -> natgth n m .\nProof. intros n m is . destruct (natpluscomm 1 m) . apply (natgehsntogth n m is). Defined .  \n\n\n(** *** Comparsion alternatives and [ n -> n + 1 ] *)\n\n\nLemma natlehchoice3 ( n m : nat ) : natleh n m -> coprod ( natleh ( n + 1 )  m ) ( paths n m ) .\nProof . intros n m l . destruct ( natlehchoice n m l ) as [ l' | e ] .   apply ( ii1 ( natlthtolehp1 _ _ l' ) ) . apply ( ii2 e ) .  Defined . \n\n\nLemma natgehchoice3 ( n m : nat ) : natgeh n m -> coprod ( natgeh n ( m + 1 ) ) ( paths n m ) .\nProof . intros n m g . destruct ( natgehchoice n m g ) as [ g' | e ] .   apply ( ii1 ( natgthtogehp1 _ _ g' ) ) . apply ( ii2 e ) . Defined . \n\n\nLemma natgthchoice3 ( n m : nat ) : natgth n m -> coprod ( natgth n ( m + 1 ) ) ( paths n ( m + 1 ) ) .\nProof.  intros n m g . destruct ( natgehchoice _ _ ( natgthtogehp1 _ _ g ) ) as [ g' | e ] . apply ( ii1 g' ) .  apply ( ii2 e ) .  Defined . \n\n\nLemma natlthchoice3 ( n m : nat ) : natlth n m -> coprod ( natlth ( n + 1 )  m ) ( paths ( n + 1 )  m ) .\nProof.  intros n m l . destruct ( natlehchoice _ _ ( natlthtolehp1 _ _ l ) ) as [ l' | e ] . apply ( ii1 l' ) .  apply ( ii2 e ) .   Defined . \n   \n\n\n\n\n\n\n\n(** *** Cancellation properties of [ plus ] on [ nat ] *)\n\nLemma pathsitertoplus ( n m : nat ) : paths ( iteration S n m ) ( n + m ) .\nProof. intros .  induction n as [ | n IHn ] . apply idpath . simpl .  apply ( maponpaths S IHn ) .  Defined .\n\nLemma isinclnatplusr ( n : nat ) : isincl ( fun m : nat => m + n ) .\nProof. intro . induction n as [ | n IHn ] . apply ( isofhlevelfhomot 1 _ _ ( fun m : nat => pathsinv0 ( natplusr0 m ) ) ) . apply ( isofhlevelfweq 1 ( idweq nat ) ) .  apply ( isofhlevelfhomot 1 _ _ ( fun m : nat => pathsinv0 ( natplusnsm m n ) ) ) . simpl .   apply ( isofhlevelfgf 1 _ _ isinclS IHn ) .  Defined. \n\nLemma isinclnatplusl ( n : nat ) : isincl ( fun m : nat => n + m ) .\nProof. intro .  apply ( isofhlevelfhomot 1 _ _ ( fun m : nat => natpluscomm m n ) ( isinclnatplusr n ) ) . Defined . \n\nLemma natplusrcan ( a b c : nat ) ( is : paths ( a + c ) ( b + c ) ) : paths a b .\nProof . intros . apply ( invmaponpathsincl _ ( isinclnatplusr c ) a b ) . apply is . Defined .  \n\nLemma natpluslcan ( a b c : nat ) ( is : paths ( c + a ) ( c + b ) ) : paths a b .\nProof . intros . rewrite ( natpluscomm _ _ ) in is . rewrite ( natpluscomm c b ) in is . apply ( natplusrcan a b c  is ) .  Defined .   \n\n\nLemma iscontrhfibernatplusr ( n m : nat ) ( is : natgeh m n ) : iscontr ( hfiber ( fun i : nat => i + n ) m ) .\nProof. intros . apply iscontraprop1 .    apply isinclnatplusr . induction m as [ | m IHm ] . set ( e := natleh0tois0 _ is ) .   split with 0 . apply e .  destruct ( natlehchoice2 _ _ is ) as [ l | e ] .  set ( j := IHm l ) .  destruct j as [ j e' ] . split with ( S j ) .  simpl . apply ( maponpaths S e' ) .  split with 0 . simpl .  assumption .  Defined . \n\nLemma neghfibernatplusr ( n m : nat ) ( is : natlth m n ) : neg ( hfiber  ( fun i : nat => i + n ) m ) .\nProof. intros. intro h . destruct h as [ i e ] . rewrite ( pathsinv0 e )  in is . destruct ( natlehtonegnatgth _ _ ( natlehmplusnm i n ) is ) .  Defined .    \n\nLemma isdecinclnatplusr ( n : nat ) : isdecincl ( fun i : nat => i + n ) .\nProof. intros . intro m . apply isdecpropif . apply ( isinclnatplusr _ m ) . destruct ( natlthorgeh m n ) as [ ni | i ] .  apply ( ii2 ( neghfibernatplusr n m ni ) ) . apply ( ii1 ( pr1 ( iscontrhfibernatplusr n m i ) ) ) . Defined .  \n\n\n\n\n(** *** Some properties of [ minus ] on [ nat ] \n\nNote : minus is defined in Init/Peano.v by the following code:\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*)\n\n\nDefinition minuseq0 ( n m : nat ) ( is : natleh n m ) : paths ( n - m )%nat  0 .\nProof. intros n m . generalize n . clear n . induction m .  intros n is . rewrite ( natleh0tois0 n is ) . simpl . apply idpath. intro n . destruct n . intro . apply idpath .  apply (IHm n ) . Defined. \n\nDefinition minusgeh0 ( n m : nat ) ( is : natgeh n m ) : natgeh ( n - m ) 0%nat.\nProof. intro . induction n as [ | n IHn ] . intros.  apply isreflnatgeh. intros .  apply natgehn0 . Defined. \n\nDefinition minusgth0 ( n m : nat ) ( is : natgth n m ) : natgth ( n - m ) 0%nat .\nProof . intro n . induction n as [ | n IHn ] .  intros .  destruct (negnatgth0n _ is ) . intro m . destruct m as [ | m ] . intro . apply natgthsn0 .  intro is .  apply ( IHn m is ) .  Defined. \n\nDefinition minusgth0inv ( n m : nat ) ( is : natgth ( n - m ) 0%nat ) : natgth n m .\nProof . intro . induction n as [ | n IHn ] . intros .  destruct ( negnatgth0n _ is ) . intro . destruct m as [ | m ]. intros . apply natgthsn0.  intro . apply ( IHn m is ) . Defined. \n\n\n\nDefinition natminuseqn ( n : nat ) : paths ( n - 0 )%nat n .\nProof . intro. destruct n . apply idpath . apply idpath. Defined. \n\nDefinition natminuslehn ( n m : nat ) : natleh ( n - m ) n .\nProof . intro n. induction n as [ | n IHn ] . intro. apply isreflnatleh .  intro . destruct m as [ | m ]. apply isreflnatleh . simpl .  apply ( istransnatleh _ _ _ (IHn m) ( natlehnsn n ) ) .  Defined. \n\nDefinition natminuslthn ( n m : nat ) ( is : natgth n 0 ) ( is' : natgth m 0 ) : natlth ( n - m ) n .\nProof . intro . induction n as [ | n IHn ] . intros . destruct ( negnatgth0n _ is ) . intro m . induction m . intros . destruct ( negnatgth0n _ is' ) . intros . apply ( natlehlthtrans _ n _ ) .  apply ( natminuslehn n m )  .  apply natlthnsn . Defined. \n\nDefinition natminuslthninv (n m : nat ) ( is : natlth ( n - m ) n ) : natgth m 0 .\nProof. intro .   induction n as [ | n IHn ] . intros .  destruct ( negnatlthn0 _ is ) . intro m . destruct m as [ | m ] . intro . destruct ( negnatlthnn _ is ) .  intro .  apply ( natgthsn0 m ) . Defined. \n\n\n\nDefinition minusplusnmm ( n m : nat ) ( is : natgeh n m ) : paths ( ( n - m ) + m ) n .\nProof . intro n . induction n as [ | n IHn] . intro m . intro is . simpl . apply ( natleh0tois0 _ is ) . intro m . destruct m as [ | m ] . intro .   simpl . rewrite ( natplusr0 n ) .  apply idpath .  simpl . intro is .  rewrite ( natplusnsm ( n - m ) m ) . apply ( maponpaths S ( IHn m is ) ) .  Defined . \n\nDefinition minusplusnmmineq ( n m : nat ) : natgeh ( ( n - m ) + m ) n .\nProof. intros. destruct ( natlthorgeh n m ) as [ lt | ge ] .  rewrite ( minuseq0 _ _ ( natlthtoleh _ _ lt ) ). apply ( natgthtogeh _ _ lt ) . rewrite ( minusplusnmm _ _ ge ) . apply isreflnatgeh . Defined. \n\nDefinition plusminusnmm ( n m : nat ) : paths ( ( n + m ) - m )%nat n .\nProof. intros . set ( int1 := natgehplusnmm n m ) . apply ( natplusrcan _ _ m ) .  rewrite ( minusplusnmm _ _ int1 ) .  apply idpath. Defined. \n\n\n(* *** Two-sided minus and comparisons *)\n\nDefinition natgehandminusr ( n m k : nat ) ( is : natgeh  n m ) : natgeh ( n - k ) ( m - k ) .\nProof. intro n. induction n as [ | n IHn ] . intros .  rewrite ( nat0gehtois0 _ is ) . apply isreflnatleh .  intro m . induction m . intros . destruct k .  apply natgehn0.  apply natgehn0 .  intro k . induction k . intro is .  apply is .  intro is .  apply ( IHn m k is ) . Defined. \n\nDefinition natgehandminusl ( n m k : nat ) ( is : natgeh n m ) : natgeh ( n - k ) ( m - k ) .\nProof .  intro n. induction n as [ | n IHn ] . intros . rewrite ( nat0gehtois0 _ is ) . apply isreflnatleh .  intro m . induction m . intros . destruct k .  apply natgehn0 . apply natgehn0 .  intro k . induction k . intro is .  apply is . intro is .  apply ( IHn m k is ) .  Defined. \n\nDefinition natgehandminusrinv ( n m k : nat ) ( is' : natgeh n k ) ( is : natgeh  ( n - k ) ( m - k ) ) : natgeh n m  .\nProof. intro n. induction n as [ | n IHn ] . intros . rewrite ( nat0gehtois0 _ is' ) in is . rewrite ( natminuseqn m )  in is . rewrite ( nat0gehtois0 _ is ) . apply isreflnatleh .  intro m . induction m . intros . apply natgehn0 . intros . destruct k .  rewrite natminuseqn in is . rewrite natminuseqn in is .  apply is . apply ( IHn m k is' is ) .  Defined. \n\n(*\n\nDefinition natgehandminuslinv ( n m k : nat ) ( is' : natgeh k n ) ( is : natleh  ( k - n ) ( k - m ) ) : natgeh n m  .\nProof. intros. set ( int := natgehgthtrans _ ( k - n ) _ is ( minusgeh0 _ _ is' ) ) . set ( int' := minusgeh0inv _ _ int ) . set ( int'' := natlehandplusr _ _ n is ) . rewrite ( minusplusnmm _ _ ( natgthtogeh _ _ is' ) ) in int''.  set ( int''' := natlehandplusr _ _ m int'' ) .  rewrite ( natplusassoc _ n _ ) in int'''.   rewrite ( natpluscomm n m ) in int''' . destruct ( natplusassoc ( k - m ) m n ) in int'''. rewrite ( minusplusnmm _ _ ( natgthtogeh _ _ int' ) ) in int'''.  apply ( natgehandpluslinv _ _ k ) . apply int'''.  Defined. \n\n\n\n\n\ninduction n as [ | n IHn ] . intros . rewrite ( nat0gehtois0 _ is' ) in is . rewrite ( natminuseqn m )  in is . rewrite ( nat0gehtois0 _ is ) . apply isreflnatleh .  intro m . induction m . intros . apply natgehn0 . intros . destruct k .  rewrite natminuseqn in is . rewrite natminuseqn in is .  apply is . apply ( IHn m k is is' ) .  Defined. \n\n\n\nDefinition natgthandminusinvr ( n m k : nat ) ( is : natgth n m ) ( is' : natgth n k ) : natgth ( n - k ) ( m - k ) .\nProof . intro n. induction n as [ | n IHn ] . intros . destruct ( negnatgth0n _ is ) .  intro m . induction m . intros . destruct k .  apply natgthsn0.  apply ( IHapply natgehn0 .  intro k . induction k . intro is .  apply is .  intro is .  apply ( IHn m k is ) . Defined. \n\n\n\nDefinition natlehandminusl ( n m k : nat ) ( is : natgeh n m ) : natleh ( k - n ) ( k - m ) .\nProof. intro n. induction n as [ | n IHn ] . intros .  rewrite ( nat0gehtois0 _ is ) . apply isreflnatleh .  intro m . induction m . intros . destruct k .  apply natminuslehn . apply natminuslehn .  intro k . induction k . intro is .  apply isreflnatleh . intro is .  apply ( IHn m k ) . apply is .  Defined. \n\nDefinition natlehandminusr \n\nDefinition natlthandminusl ( n m k : nat ) ( is : natgth n m ) ( is' : natgeh k n ) : natlth ( k - n ) ( k - m ) .\nProof. intro n. induction n as [ | n IHn ] . intros .  destruct ( negnatgth0n _ is ) . intro m . induction m . intros . destruct k .  destruct ( negnatgeh0sn _ is' ) . apply ( natlehlthtrans _ k _ )  .  apply ( natminuslehn k n ) . apply natlthnsn .  intro k . induction k . intros is is'.  destruct ( negnatgeh0sn _ is' ) . intros is is' .  apply ( IHn m k is is' ) .  Defined. \n\nDefinition natlehandminusl ( n m k : nat ) ( is : natgeh n m ) : natleh ( k - n ) ( k - m ) .\nProof. intro n. induction n as [ | n IHn ] . intros .  rewrite ( nat0gehtois0 _ is ) . apply isreflnatleh .  intro m . induction m . intros . destruct k .  apply natminuslehn . apply natminuslehn .  intro k . induction k . intro is .  apply isreflnatleh . intro is .  apply ( IHn m k ) . apply is .  Defined. \n\n\nDefinition natlehandminusl ( n m k : nat ) : ( natleh n m ) -> natgeh ( k - n ) ( k - m ) := natlehandminusl m n k . \n\nDefinition natlehandminusr ( n m k : nat ) : ( natleh n m ) -> natleh ( n - k ) ( m - k ) := natgehandminusr m n k .\n\n\n \n\n(* *** One sided minus and comparisons *)\n\n\n(* *** Greater or equal and minus *)\n\n\nDefinition natgehrightminus ( n m k : nat ) ( is : natgeh ( n + m ) k ) : natgeh n ( k - m ) .\nProof. intros . \n\nDefinition natgehrightplus ( n m k : nat ) ( is : natgeh ( n - m ) k ) : natgeh n ( k + m ) .\n\nDefinition natgehleftminus ( n m k : nat ) ( is : natgeh n ( m + k ) ) : natgeh ( n - k ) m .\n\nDefinition natgehleftplus ( n m k : nat ) ( is : natgeh n ( m - k ) ) : natgeh ( n + k ) m .\n\n\n(* **** Greater and minus *)\n\n\nDefinition natgthrightminus ( n m k : nat ) ( is : natgth ( n + m ) k ) : natgth n ( k - m ) .\nProof . intros. \n\nDefinition natgthrightplus ( n m k : nat ) ( is : natgth ( n - m ) k ) : natgth n ( k + m ) .\n\nDefinition natgthleftminus ( n m k : nat ) ( is : natgth n ( m + k ) ) : natgth ( n - k ) m .\n\nDefinition natgthleftplus ( n m k : nat ) ( is : natgth n ( m - k ) ) : natgth ( n + k ) m .\\\n\n\n(* **** Less and minus *)\n\n\nDefinition natlthrightminus ( n m k : nat ) ( is : natlth ( n + m ) k ) : natlth n ( k - m ) .\n\nDefinition natlthrightplus ( n m k : nat ) ( is : natlth ( n - m ) k ) : natlth n ( k + m ) .\n\nDefinition natlthleftminus ( n m k : nat ) ( is : natlth n ( m + k ) ) : natlth ( n - k ) m .\n\nDefinition natlthleftplus ( n m k : nat ) ( is : natlth n ( m - k ) ) : natlth ( n + k ) m .\n\n\n(* **** Less or equal and minus *)\n\n\nDefinition natlehrightminus ( n m k : nat ) ( is : natleh ( n + m ) k ) : natleh n ( k - m ) .\n\nDefinition natlehrightplus ( n m k : nat ) ( is : natleh ( n - m ) k ) : natleh n ( k + m ) .\n\nDefinition natlehleftminus ( n m k : nat ) ( is : natleh n ( m + k ) ) : natleh ( n - k ) m .\n\nDefinition natlehleftplus ( n m k : nat ) ( is : natleh n ( m - k ) ) : natleh ( n + k ) m .\n\n\n\n\n\n\n\n\n\n\n(* *** Mixed plus/minus associativities. \n\nThere are four possible plus/minus associativities which are labelled by pp, pm, mp and mm depending on where in the side with the left parenthesis one has minuses and where one has pluses. Two of those - pp and mm, are unconditional. Two others require a condition to hold as equality and also provide an unconditional inequality. Alltogether we have six statements including a repeat of the usual pp associativity which we give here another name in accrdance with the general naming scheme for these statements. *)\n\nNotation natassocppeq := natplusassoc .\n\nDefinition natassocpmeq ( n m k : nat ) ( is : natgeh m k ) : paths (( n + m ) - k )%nat (n + ( m - k )).\nProof. intros.  apply ( natplusrcan _ _ k ) . rewrite ( natplusassoc n _ k ) .  rewrite ( minusplusnmm _ k is ) .  set ( is' := istransnatgeh _ _ _ ( natgehplusnmm n m ) is ) . rewrite ( minusplusnmm _ k is' ) . apply idpath. Defined. \n\nDefinition natassocpmineq ( n m k : nat ) : natleh (( n + m ) - k ) ( n + ( m - k )) .\nProof. intros n m k . destruct (natgthorleh k m) as [g | le]. \n\nset ( e := minuseq0 m k ( natgthtogeh _ _ g ) ) .   rewrite e . rewrite (natplusr0 n ).  destruct (boolchoice ( natgtb k (n+m) ) ) as [ g' | le']. set ( e' := minuseq0 (n+m) k ( natgthtogeh _ _ g' ) ) .  rewrite e' . apply natleh0n . apply ( natlehandplusrinv _ _ k ) . rewrite ( minusplusnmm _ k ) . apply natlehandplusl . apply ( natlthtoleh _ _ g ) . set ( int := falsetonegtrue _ le' ) . assumption .\n\nrewrite ( natassocpmeq _ _ _ le ) .  apply isreflnatleh . Defined.\n\n\nDefinition natassocmpeq ( n m k : nat ) ( isnm : natgeh n m ) ( ismk : natgeh m k ) : paths (( n - m ) + k )%nat (n - ( m - k ))%nat.\nProof. intros.  apply ( natplusrcan _ _ ( m - k ) ) . \n\nassert ( is' : natleh ( m - k ) n ) . apply ( istransnatleh _ _ _ (natminuslehn _ _ ) isnm ) . rewrite ( minusplusnmm _ _ is' ) . rewrite (natplusassoc _ k _ ) .  rewrite ( natpluscomm k _ ) . rewrite ( minusplusnmm _ _ ismk ) . rewrite ( minusplusnmm _ _ isnm ) . apply idpath. Defined. \n\n\nDefinition natassocmpineq ( n m k : nat ) : natgeh (( n - m ) + k ) ( n - ( m - k )) .\nProof. intros n m k . destruct (natgthorleh k m) as [g | le]. \n\nset ( e := minuseq0 m k ( natgthtogeh _ _ g ) ) .   rewrite e . rewrite ( natminuseqn n ) . apply ( natgehandplusrinv _ _ m ) . rewrite ( natplusassoc _ _ m ) .  rewrite ( natpluscomm _ m ) . destruct ( natplusassoc ( n - m ) m k ) . assert ( int1 : natgeh (n - m + m + k ) ( n + k ) ) .  apply ( natgehandplusr _ _ k ) .  apply minusplusnmmineq . assert ( int2 : natgeh (n + k ) (n + m ) ) . apply ( natgehandplusl _ _ n ) . apply ( natgthtogeh _ _ g ) .  apply ( istransnatgeh _ _ _ int1 int2 ) .  \n\ndestruct ( natgthorleh m n ) as [g' | le']. rewrite ( minuseq0 _ _ ( natgthtogeh _ _ g' ) ) . change ( 0 + k ) with k .   apply ( natgehandplusrinv _ _ (m - k ) ) .  rewrite ( natpluscomm k _ ) . rewrite ( minusplusnmm _ _ le ) .  \n\ndestruct ( natgthorleh ( m - k ) n ) as [ g'' | le'' ] . rewrite ( minuseq0 n ( m - k ) ( natgthtogeh _ _ g'' ) ) .   apply ( natminuslehn  m k ) . rewrite ( minusplusnmm _ _ le'' ) .  apply ( natgthtogeh _ _ g' ) .  \n\nrewrite ( natassocmpeq _ _ _ le' le ) . apply isreflnatgeh .  Defined. \n\n\nDefinition natassocmmeq ( n m k : nat ) : paths (( n  - m ) - k )%nat (n - ( m + k ))%nat.\nProof. intros.  destruct ( natgthorleh ( m + k ) n ) as [ g | le ] . \n\nrewrite ( minuseq0 _ _ ( natgthtogeh _ _ g ) ) .  assert ( int1 : natleh ( n - m ) k ) . rewrite natpluscomm in g . set ( int2 := natgehandminusr _ _ m ( natgthtogeh _ _ g ) ) .  rewrite plusminusnmm in int2 .  apply int2 .  apply ( minuseq0 _ _ int1 ) . apply ( natplusrcan _ _ ( m + k ) ) .   rewrite ( minusplusnmm _ ( m + k )%nat ) . rewrite ( natpluscomm m k ) . destruct ( natplusassoc ( n - m - k ) k m ) .   rewrite \n\n\n\n\n\n\n\n\napply ( natplusrcan _ _ k ) . rewrite ( natplusassoc n _ k ) .  rewrite ( minusplusnmm _ k is ) .  set ( is' := istransnatgeh _ _ _ ( natgehplusnmm n m ) is ) . rewrite ( minusplusnmm _ k is' ) .apply idpath. Defined. \n\nDefinition natassocpmineq ( n m k : nat ) : natleh (( n + m ) - k ) ( n + ( m - k )) .\nProof. intros n m k . destruct (natgthorleh k m) as [g | le]. \n\nset ( e := minuseq0 m k ( natgthtogeh _ _ g ) ) .   rewrite e . rewrite (natplusr0 n ).  destruct (boolchoice ( natgtb k (n+m) ) ) as [ g' | le']. set ( e' := minuseq0 (n+m) k ( natgthtogeh _ _ g' ) ) .  rewrite e' . apply natleh0n . apply ( natlehandplusrinv _ _ k ) . rewrite ( minusplusnmm _ k ) . apply natlehandplusl . apply ( natlthtoleh _ _ g ) . set ( int := falsetonegtrue _ le' ) . assumption .\n\nrewrite ( natassocpmeq _ _ _ le ) .  apply isreflnatleh . Defined.\n\n \n\n\n\n*)\n\n\n\n\n\n\n(** ** Some properties of [ mult ] on [ nat ] \n\nNote : multiplication is defined in Init/Peano.v by the following code:\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\n*)\n\n(** *** Basic algebraic properties of [ mult ] on [ nat ] *)\n\nLemma natmult0n ( n : nat ) : paths ( 0 * n ) 0 .\nProof. intro n . apply idpath . Defined . \nHint Resolve natmult0n : natarith .\n\nLemma natmultn0 ( n : nat ) : paths ( n * 0 ) 0 .\nProof. intro n . induction n as [ | n IHn ] . apply idpath . simpl .   assumption .  Defined . \nHint Resolve natmultn0 : natarith .\n\nLemma multsnm ( n m : nat ) : paths ( ( S n ) * m ) ( m + n * m ) .\nProof. intros . apply idpath . Defined .\nHint Resolve multsnm : natarith .\n\nLemma multnsm ( n m : nat ) : paths ( n * ( S m ) ) ( n + n * m ) .\nProof. intro n . induction n as [ | n IHn ] . intro .  simpl .  apply idpath .  intro m .  simpl . apply ( maponpaths S ) .  rewrite ( pathsinv0 ( natplusassoc n m ( n * m ) ) ) .  rewrite ( natpluscomm n m ) .  rewrite ( natplusassoc m n ( n * m ) ) .  apply ( maponpaths ( fun x : nat => m + x ) ( IHn m ) ) .  Defined . \nHint Resolve multnsm : natarith .\n\nLemma natmultcomm ( n m : nat ) : paths ( n * m ) ( m * n ) .\nProof. intro . induction n as [ | n IHn ] . intro .  auto with natarith . intro m .  rewrite ( multsnm n m ) .  rewrite ( multnsm m n ) .  apply ( maponpaths ( fun x : _ => m + x ) ( IHn m ) ) .   Defined .\n\nLemma natrdistr ( n m k : nat ) : paths ( ( n + m ) * k ) ( n * k + m * k ) .\nProof . intros . induction n as [ | n IHn ] . auto with natarith .   simpl . rewrite ( natplusassoc k ( n * k ) ( m * k ) ) .   apply ( maponpaths ( fun x : _ => k + x ) ( IHn ) ) .  Defined . \n  \nLemma natldistr ( m k n : nat ) : paths ( n * ( m + k ) ) ( n * m + n * k ) .\nProof . intros m k n . induction m as [ | m IHm ] . simpl . rewrite ( natmultn0 n ) . auto with natarith .  simpl . rewrite ( multnsm n ( m + k ) ) . rewrite ( multnsm n m ) .  rewrite ( natplusassoc _ _ _ ) .  apply ( maponpaths ( fun x : _ => n + x ) ( IHm ) ) . Defined .\n\nLemma natmultassoc ( n m k : nat ) : paths ( ( n * m ) * k ) ( n * ( m * k ) ) .\nProof. intro . induction n as [ | n IHn ] . auto with natarith . intros . simpl . rewrite ( natrdistr m ( n * m ) k ) .  apply ( maponpaths ( fun x : _ => m * k + x ) ( IHn m k ) ) .   Defined . \n\nLemma natmultl1 ( n : nat ) : paths ( 1 * n ) n .\nProof. simpl .  auto with natarith . Defined . \nHint Resolve natmultl1 : natarith .\n\nLemma natmultr1 ( n : nat ) : paths ( n * 1 ) n .\nProof. intro n . rewrite ( natmultcomm n 1 ) . auto with natarith . Defined . \nHint Resolve natmultr1 : natarith .\n\nDefinition natmultabmonoid : abmonoid :=  abmonoidpair ( setwithbinoppair natset ( fun n m : nat => n * m ) ) ( dirprodpair ( dirprodpair natmultassoc ( @isunitalpair natset _ 1 ( dirprodpair natmultl1 natmultr1 ) ) ) natmultcomm ) . \n\n    \n\n\n(** *** [ nat ] as a commutative rig *)\n\nDefinition natcommrig : commrig .\nProof . split with ( setwith2binoppair natset ( dirprodpair  ( fun n m : nat => n + m ) ( fun n m : nat => n * m ) ) ) .  split . split . split with ( dirprodpair ( dirprodpair ( dirprodpair natplusassoc ( @isunitalpair natset _ 0 ( dirprodpair natplusl0 natplusr0 ) ) ) natpluscomm ) ( dirprodpair natmultassoc ( @isunitalpair natset _ 1 ( dirprodpair natmultl1 natmultr1 ) ) ) ) . apply ( dirprodpair natmult0n natmultn0 ) . apply ( dirprodpair natldistr natrdistr ) . unfold iscomm . apply natmultcomm . Defined .\n\n\n(** *** Cancellation properties of [ mult ] on [ nat ] *)\n\nDefinition natneq0andmult ( n m : nat ) ( isn : natneq n 0 ) ( ism : natneq m 0 ) : natneq ( n * m ) 0 .\nProof . intros . destruct n as [ | n ] . destruct ( isn ( idpath _ ) ) .  destruct m as [ | m ] .  destruct ( ism ( idpath _ ) ) . simpl . apply ( negpathssx0 ) .  Defined . \n\nDefinition natneq0andmultlinv ( n m : nat ) ( isnm : natneq ( n * m ) 0 ) : natneq n 0 := rigneq0andmultlinv natcommrig n m isnm . \n\nDefinition natneq0andmultrinv ( n m : nat ) ( isnm : natneq ( n * m ) 0 ) : natneq m 0 := rigneq0andmultrinv natcommrig n m isnm .\n\n\n\n(** *** Multiplication and comparisons  *)\n\n\n(** [ natgth ] *)\n\n\nDefinition natgthandmultl ( n m k : nat ) ( is : natneq k 0 ) : natgth n m -> natgth ( k * n ) ( k * m ) .\nProof. intro n . induction n as [ | n IHn ] .  intros m k g g' . destruct ( negnatgth0n _ g' ) .  intro m . destruct m as [ | m ] . intros k g g' . rewrite ( natmultn0 k ) .  rewrite ( multnsm k n ) .  apply ( natgehgthtrans _ _ _ ( natgehplusnmn k ( k* n ) ) ( natneq0togth0 _ g ) ) .  intros k g g' . rewrite ( multnsm k n ) . rewrite ( multnsm k m ) . apply ( natgthandplusl _ _ _ ) . apply ( IHn m k g g' ) . Defined .  \n\nDefinition natgthandmultr ( n m k : nat ) ( is : natneq k 0 ) : natgth n m -> natgth ( n * k ) ( m * k )  .\nProof . intros n m k l . rewrite ( natmultcomm n k ) . rewrite ( natmultcomm m k ) . apply ( natgthandmultl n m k l ) . Defined .\n\nDefinition natgthandmultlinv ( n m k : nat ) : natgth ( k * n ) ( k * m ) -> natgth n m .\nProof . intro n . induction n as [ | n IHn ] . intros m k g . rewrite ( natmultn0 k ) in g . destruct ( negnatgth0n _ g ) .  intro m . destruct m as [ | m ] .  intros . apply ( natgthsn0 _ ) . intros k g . rewrite ( multnsm k n ) in g .  rewrite ( multnsm k m ) in g . apply ( IHn m k ( natgthandpluslinv _ _ k g ) ) .  Defined . \n\nDefinition natgthandmultrinv ( n m k : nat ) : natgth ( n * k ) ( m * k ) -> natgth n m .\nProof.  intros n m k g . rewrite ( natmultcomm n k ) in g . rewrite ( natmultcomm m k ) in g . apply ( natgthandmultlinv n m k g ) . Defined .\n\n\n\n(** [ natlth ] *)\n\n\nDefinition natlthandmultl ( n m k : nat ) ( is : natneq k 0 ) : natlth n m -> natlth ( k * n ) ( k * m )  := natgthandmultl _ _ _ is .\n\nDefinition natlthandmultr ( n m k : nat ) ( is : natneq k 0 ) : natlth n m -> natlth ( n * k ) ( m * k ) := natgthandmultr _ _ _ is .\n\nDefinition natlthandmultlinv ( n m k : nat ) : natlth ( k * n ) ( k * m ) -> natlth n m := natgthandmultlinv _ _ _  .\n\nDefinition natlthandmultrinv ( n m k : nat ) : natlth ( n * k ) ( m * k ) -> natlth n m := natgthandmultrinv _ _ _ .\n\n\n(** [ natleh ] *)\n\n\nDefinition natlehandmultl ( n m k : nat ) : natleh n m -> natleh ( k * n ) ( k * m ) := negf ( natgthandmultlinv _ _ _ ) .\n\nDefinition natlehandmultr ( n m k : nat ) : natleh n m -> natleh ( n * k ) ( m * k ) := negf ( natgthandmultrinv _ _ _ ) .\n\nDefinition natlehandmultlinv ( n m k : nat ) ( is : natneq k 0 ) : natleh ( k * n ) ( k * m ) -> natleh n m := negf ( natgthandmultl _ _ _ is )  .\n\nDefinition natlehandmultrinv ( n m k : nat ) ( is : natneq k 0 ) : natleh ( n * k ) ( m * k ) -> natleh n m := negf ( natgthandmultr _ _ _ is ) .\n\n\n(** [ natgeh ] *)\n\n\nDefinition natgehandmultl ( n m k : nat ) : natgeh n m -> natgeh ( k * n ) ( k * m ) := negf ( natgthandmultlinv _ _ _ ) .\n\nDefinition natgehandmultr ( n m k : nat ) : natgeh n m -> natgeh ( n * k ) ( m * k )  := negf ( natgthandmultrinv _ _ _ ) .\n\nDefinition natgehandmultlinv ( n m k : nat ) ( is : natneq k 0 ) : natgeh ( k * n ) ( k * m ) -> natgeh n m := negf ( natgthandmultl _ _ _ is )   .\n\nDefinition natgehandmultrinv ( n m k : nat ) ( is : natneq k 0 ) : natgeh ( n * k ) ( m * k ) -> natgeh n m := negf ( natgthandmultr _ _ _ is )  .\n\n\n\n\n\n\n(** *** Properties of comparisons in the terminology of  algebra1.v *)\n\nOpen Scope rig_scope.\n\n(** [ natgth ] *)\n\nLemma isplushrelnatgth : @isbinophrel nataddabmonoid natgth . \nProof . split . apply  natgthandplusl .  apply natgthandplusr .  Defined . \n\nLemma isinvplushrelnatgth : @isinvbinophrel nataddabmonoid natgth . \nProof . split . apply  natgthandpluslinv .  apply natgthandplusrinv .  Defined . \n\nLemma isinvmulthrelnatgth : @isinvbinophrel natmultabmonoid natgth . \nProof . split .  intros a b c r . apply ( natlthandmultlinv _ _ _ r ) .   intros a b c r .  apply ( natlthandmultrinv _ _ _ r ) .  Defined . \n\nLemma isrigmultgtnatgth : isrigmultgt natcommrig natgth .\nProof . change ( forall a b c d : nat , natgth a b -> natgth c d -> natgth ( a * c + b * d ) ( a * d + b * c ) ) .  intro a . induction a as [ | a IHa ] . intros b c d rab rcd . destruct ( negnatgth0n _ rab ) . \n\nintro b . induction b as [ | b IHb ] . intros c d rab rcd . rewrite ( natmult0n d ) .  rewrite ( natplusr0 _ ) .  rewrite ( natmult0n _ ) .        rewrite ( natplusr0 _ ) . apply ( natlthandmultl _ _ _ ( natgthtoneq _ _ rab ) rcd ) . intros c d rab rcd . simpl . set ( rer := ( abmonoidrer nataddabmonoid ) ) . simpl in rer .  rewrite ( rer _ _ d _ ) . rewrite ( rer _ _ c _ ) .  rewrite ( natpluscomm c d ) .  apply ( natlthandplusl (a * d + b * c)  (a * c + b * d) ( d + c ) ) . apply ( IHa _ _ _ rab rcd ) .  Defined . \n\nLemma isinvrigmultgtnatgth : isinvrigmultgt natcommrig natgth .\nProof . set ( rer := abmonoidrer nataddabmonoid  ) .  simpl in rer .  apply isinvrigmultgtif . intros a b c d . generalize a b c . clear a b c .  induction d as [ | d IHd ] .  \n\nintros a b c g gab . change ( pr1 ( natgth ( a * c + b * 0 ) ( a * 0 + b * c ) ) ) in g .   destruct c as [ | c ] .  rewrite ( natmultn0 _ ) in g .  destruct ( isirreflnatgth _ g ) .  apply natgthsn0 .   \n\nintros a b c g gab .  destruct c as [ | c ] . change ( pr1 ( natgth ( a * 0 + b * S d ) ( a * S d + b * 0 ) ) ) in g . rewrite ( natmultn0 _ ) in g .  rewrite ( natmultn0 _ ) in g .  rewrite ( natplusl0 _ ) in g . rewrite ( natplusr0 _ ) in g .  set ( g' := natgthandmultrinv _ _ _ g ) .  destruct ( isasymmnatgth _ _ gab g' ) .  change ( pr1 ( natgth ( a * S c + b * S d ) ( a * S d + b * S c ) ) ) in g .  rewrite ( multnsm _ _ ) in g .   rewrite ( multnsm _ _ ) in g .  rewrite ( multnsm _ _ ) in g .  rewrite ( multnsm _ _ ) in g . rewrite ( rer _ ( a * c ) _ _ ) in g . rewrite ( rer _ ( a * d ) _ _ ) in g . set ( g' := natgthandpluslinv _ _ ( a + b ) g ) .  apply ( IHd a b c g' gab ) . Defined .  \n\n\n\n\n\n(** [ natlth ] *)\n\nLemma isplushrelnatlth : @isbinophrel nataddabmonoid natlth . \nProof . split . intros a b c . apply  ( natgthandplusl b a c ) . intros a b c . apply ( natgthandplusr b a c )  .  Defined . \n\nLemma isinvplushrelnatlth : @isinvbinophrel nataddabmonoid natlth . \nProof . split . intros a b c . apply  ( natgthandpluslinv b a c ) .  intros a b c . apply ( natgthandplusrinv b a c ) .  Defined . \n\nLemma isinvmulthrelnatlth : @isinvbinophrel natmultabmonoid natlth . \nProof . split . intros a b c r .  apply ( natlthandmultlinv  _ _ _ r ) .   intros a b c r .  apply ( natlthandmultrinv _ _ _ r ) .  Defined . \n\n(** [ natleh ] *)\n\nLemma isplushrelnatleh : @isbinophrel nataddabmonoid natleh . \nProof . split . apply natlehandplusl .  apply natlehandplusr . Defined . \n\nLemma isinvplushrelnatleh : @isinvbinophrel nataddabmonoid natleh . \nProof . split . apply natlehandpluslinv .  apply natlehandplusrinv . Defined . \n\nLemma ispartinvmulthrelnatleh : @ispartinvbinophrel natmultabmonoid ( fun x => natneq x 0 ) natleh . \nProof . split . intros a b c s r . apply ( natlehandmultlinv _ _ _ s r ) .   intros a b c s r .  apply ( natlehandmultrinv _ _ _ s r ) .  Defined . \n\n\n(** [ natgeh ] *)\n\nLemma isplushrelnatgeh : @isbinophrel nataddabmonoid natgeh . \nProof . split . intros a b c . apply ( natlehandplusl b a c ) .   intros a b c . apply ( natlehandplusr b a c ) . Defined . \n\nLemma isinvplushrelnatgeh : @isinvbinophrel nataddabmonoid natgeh . \nProof . split . intros a b c . apply ( natlehandpluslinv b a c ) .   intros a b c . apply ( natlehandplusrinv b a c ) . Defined . \n\nLemma ispartinvmulthrelnatgeh : @ispartinvbinophrel natmultabmonoid ( fun x => natneq x 0 ) natgeh . \nProof . split .  intros a b c s r . apply ( natlehandmultlinv _ _ _ s r ) .   intros a b c s r .  apply ( natlehandmultrinv _ _ _ s r ) .  Defined . \n\n\nClose Scope rig_scope . \n\n\n\n(** *** Submonoid of non-zero elements in [ nat ] *)\n\nDefinition natnonzero : @subabmonoids natmultabmonoid . \nProof . split with ( fun a => natneq a 0 ) .  unfold issubmonoid .  split .  unfold issubsetwithbinop . intros a a' .  apply ( natneq0andmult _ _ ( pr2 a ) ( pr2 a' ) ) . apply ( ct ( natneq , isdecrelnatneq, 1 , 0 ) ) . Defined . \n\nLemma natnonzerocomm ( a b : natnonzero ) : paths ( @op natnonzero a b ) ( @op natnonzero b a ) . \nProof . intros . apply ( invmaponpathsincl _ ( isinclpr1carrier _ ) ( @op natnonzero a b ) ( @op natnonzero b a ) ) .  simpl . apply natmultcomm . Defined . \n\n\n\n(** *** Division with a remainder on [ nat ] \n\nFor technical reasons it is more convenient to introduce divison with remainder for all pairs (n,m) including pairs of the form (n,0). *)\n\n\nDefinition natdivrem ( n m : nat ) : dirprod nat nat .\nProof. intros . induction n as [ | n IHn ] . intros . apply ( dirprodpair 0 0 ) . destruct ( natlthorgeh ( S ( pr2 IHn ) ) m )  . apply ( dirprodpair ( pr1 IHn ) ( S ( pr2 IHn ) ) ) .  apply ( dirprodpair ( S ( pr1 IHn ) ) 0 ) .   Defined . \n\nDefinition natdiv ( n m : nat )  := pr1 ( natdivrem n m ) .\nDefinition natrem ( n m : nat )  := pr2 ( natdivrem n m ) .\n\nLemma lthnatrem ( n m : nat ) ( is : natneq m 0 ) : natlth ( natrem n m ) m .\nProof. intro . destruct n as [ | n ] . unfold natrem . simpl . intros.  apply ( natneq0togth0 _ is ) .  unfold natrem . intros m is . simpl .   destruct ( natlthorgeh (S (pr2 (natdivrem n m))) m )  as [ nt | t ] . simpl . apply nt . simpl .  apply ( natneq0togth0 _ is ) .   Defined . \n\n\nTheorem natdivremrule ( n m : nat ) ( is : natneq m 0 ) : paths n ( ( natrem n m ) + ( natdiv n m ) * m ) .\nProof. intro . induction n as [ | n IHn ] . simpl .  intros . apply idpath . intros m is .  unfold natrem . unfold natdiv . simpl .  destruct ( natlthorgeh ( S ( pr2 ( natdivrem n m  ) ) ) m )  as [ nt | t ] . \n\nsimpl .  apply ( maponpaths S ( IHn m is ) ) .\n\nsimpl . set ( is' := lthnatrem n m is ) .  destruct ( natgthchoice2 _ _ is' ) as [ h | e ] .    destruct ( natlehtonegnatgth _ _ t h ) .  fold ( natdiv n m ) . set ( e'' := maponpaths S ( IHn m is ) ) .  change (S (natrem n m + natdiv n m * m) ) with (  S ( natrem n m ) + natdiv n m * m ) in  e'' . rewrite ( pathsinv0 e ) in e'' . apply e'' . \nDefined . \n\nOpaque natdivremrule . \n\n\nLemma natlehmultnatdiv ( n m : nat ) ( is : natneq m 0 ) :  natleh ( mult ( natdiv n m ) m ) n .\nProof . intros . set ( e := natdivremrule n m ) . set ( int := ( natdiv n m ) * m ) . rewrite e . unfold int  .   apply ( natlehmplusnm _ _ ) .  apply is . Defined . \n\n\nTheorem natdivremunique ( m i j i' j' : nat ) ( lj : natlth j m ) ( lj' : natlth j' m ) ( e : paths ( j + i * m ) ( j' + i' * m ) ) : dirprod ( paths i i' ) ( paths j j' ) .\nProof. intros m i . induction i as [ | i IHi ] .\n\nintros j i' j' lj lj' .  intro e .  simpl in e . rewrite ( natplusr0 j ) in e .  rewrite e in lj .  destruct i' . simpl in e .  rewrite ( natplusr0 j' ) in e .  apply ( dirprodpair ( idpath _ ) e ) .  simpl in lj . rewrite ( natpluscomm m ( i' * m ) ) in lj . rewrite ( pathsinv0 ( natplusassoc _ _ _ ) ) in lj .  destruct ( negnatgthmplusnm _ _ lj ) .\n\nintros j i' j' lj lj' e . destruct i' as [ | i' ] .  simpl in e .  rewrite ( natplusr0 j' ) in e . rewrite ( pathsinv0 e ) in lj' .   rewrite ( natpluscomm m ( i * m ) ) in lj' .  rewrite ( pathsinv0 ( natplusassoc _ _ _ ) ) in lj' .  destruct ( negnatgthmplusnm _ _ lj' ) .  \n\nsimpl in e .  rewrite ( natpluscomm m ( i * m ) ) in e .  rewrite ( natpluscomm m ( i' * m ) ) in e .  rewrite ( pathsinv0 ( natplusassoc j _ _ ) ) in e .  rewrite ( pathsinv0 ( natplusassoc j' _ _ ) ) in e . set ( e' := invmaponpathsincl _ ( isinclnatplusr m ) _ _ e ) .  set ( ee := IHi j i' j' lj lj' e' ) .  apply ( dirprodpair ( maponpaths S ( pr1 ee ) ) ( pr2 ee )  ) .  Defined . \n\nOpaque natdivremunique .\n\nLemma natdivremandmultl ( n m k : nat ) ( ism : natneq m 0 ) ( iskm : natneq ( k * m ) 0 ) : dirprod ( paths ( natdiv ( k * n ) ( k * m ) ) ( natdiv n m ) ) ( paths ( natrem ( k * n ) ( k * m ) ) ( k * ( natrem n m ) ) ) . \nProof . intros . set ( ak := natdiv ( k * n ) ( k * m ) ) . set ( bk := natrem ( k * n ) ( k * m ) ) . set ( a :=  natdiv n m ) . set ( b :=  natrem n m ) . assert ( e1 : paths ( bk + ak * ( k * m )  ) ( ( b * k ) + a * ( k * m ) ) ) . unfold ak. unfold bk .   rewrite ( pathsinv0 ( natdivremrule  ( k * n ) ( k * m ) iskm ) ) . rewrite ( natmultcomm k m ) .   rewrite ( pathsinv0 ( natmultassoc _ _ _ ) ) . rewrite ( pathsinv0 ( natrdistr _ _ _ ) ) .  unfold a . unfold b .  rewrite ( pathsinv0 ( natdivremrule  n m ism ) ) . apply ( natmultcomm k n ) . assert ( l1 := lthnatrem  n m ism ) . assert ( l1' := ( natlthandmultr _ _ _ ( natneq0andmultlinv _ _ iskm ) l1 ) )  .   rewrite ( natmultcomm m k ) in l1' . set ( int := natdivremunique _ _ _ _ _ ( lthnatrem ( k * n ) ( k * m ) iskm ) l1' e1 ) . \n\nsplit with ( pr1 int ) . \n\nrewrite ( natmultcomm k b ) . apply ( pr2 int ) .  Defined . \n\nOpaque natdivremandmultl .\n\n\nDefinition natdivandmultl ( n m k : nat ) ( ism : natneq m 0 ) ( iskm : natneq ( k * m ) 0 ) : paths ( natdiv ( k * n ) ( k * m ) ) ( natdiv n m ) := pr1 ( natdivremandmultl _ _ _ ism iskm ) .\n\n  \nDefinition natremandmultl ( n m k : nat ) ( ism : natneq m 0 ) ( iskm : natneq ( k * m ) 0 ) : paths ( natrem ( k * n ) ( k * m ) ) ( k * ( natrem n m ) ) := pr2 ( natdivremandmultl _ _ _ ism iskm ) .\n\n\nLemma natdivremandmultr ( n m k : nat ) ( ism : natneq m 0 ) ( ismk : natneq ( m * k ) 0 ) : dirprod ( paths ( natdiv ( n * k ) ( m * k ) ) ( natdiv n m ) ) ( paths ( natrem ( n * k ) ( m * k) ) ( ( natrem n m ) * k  ) ) . \nProof . intros . rewrite ( natmultcomm m k ) .   rewrite ( natmultcomm m k ) in ismk .  rewrite ( natmultcomm n k ) . rewrite ( natmultcomm ( natrem _ _ ) k ) .  apply ( natdivremandmultl _ _ _ ism ismk ) . Defined . \n\n\nOpaque natdivremandmultr .\n\n\nDefinition natdivandmultr ( n m k : nat ) ( ism : natneq m 0 ) ( ismk : natneq ( m * k ) 0 ) : paths ( natdiv ( n * k ) ( m * k ) ) ( natdiv n m ) := pr1 ( natdivremandmultr _ _ _ ism ismk ) .\n \n\nDefinition natremandmultr ( n m k : nat ) ( ism : natneq m 0 ) ( ismk : natneq ( m * k ) 0 ) : paths ( natrem ( n * k ) ( m * k ) ) ( ( natrem n m ) * k ) := pr2 ( natdivremandmultr _ _ _ ism ismk ) .\n\n\n\n\n\n(** *** Exponentiation [ natpower n m ] ( \" n to the power m \" ) on [ nat ] *)\n\nFixpoint natpower ( n m : nat ) := match m with\nO => 1 |\nS m' => n * ( natpower n m' ) end .\n\n\n(** *** Factorial on [ nat ] *)\n\nFixpoint factorial ( n : nat ) := match n with\n0 => 1 |\nS n' => ( S n' ) * ( factorial n' ) end .  \n\n\n\n\n\n(** ** The order-preserving functions [ di i : nat -> nat ] whose image is the complement to one element [ i ] . *)\n\n\n\n\nDefinition di ( i : nat ) ( x : nat ) : nat :=\nmatch natlthorgeh x i with \nii1 _ => x |\nii2 _ => S x \nend .\n\n\nLemma natlehdinsn ( i n : nat ) : natleh ( di i n ) ( S n ) .\nProof . intros . unfold di . destruct ( natlthorgeh n i ) . apply natlthtoleh . apply natlthnsn . apply isreflnatleh .  Defined . \n\nLemma natgehdinn ( i n : nat ) : natgeh ( di i n ) n .\nProof. intros . unfold di . destruct ( natlthorgeh n i ) .  apply isreflnatleh .  apply natlthtoleh . apply natlthnsn .   Defined . \n\n\nLemma isincldi ( i : nat ) : isincl ( di i ) .\nProof. intro .   apply ( isinclbetweensets ( di i ) isasetnat isasetnat ) . intros x x' . unfold di . intro e. destruct  ( natlthorgeh x i )  as [ l | nel ] .  destruct  ( natlthorgeh x' i )   as [ l' | nel' ] . apply e .  rewrite e in l .  set ( e' := natgthtogths _ _  l ) . destruct ( nel' e' ) .   destruct  ( natlthorgeh x' i )  as [ l' | nel' ] .  destruct e.  set ( e' := natgthtogths _ _ l' ) . destruct ( nel e' ) .  apply ( invmaponpathsS _ _ e ) . Defined . \n\n\nLemma neghfiberdi ( i : nat ) : neg ( hfiber ( di i ) i ) .\nProof. intros i hf . unfold di in hf . destruct hf as [ j e ] .  destruct ( natlthorgeh j i ) as [ l | g ] . destruct e . apply ( isirreflnatlth _ l) .  destruct e in g .  apply ( negnatgehnsn _ g ) .   Defined. \n\nLemma iscontrhfiberdi ( i j : nat ) ( ne : neg ( paths i j ) ) : iscontr ( hfiber ( di i ) j ) .\nProof. intros . apply iscontraprop1 .   apply ( isincldi i j ) . destruct ( natlthorgeh j i ) as [ l | nel ]  .  split with j .  unfold di .   destruct ( natlthorgeh j i ) as [ l' | nel' ]  .  apply idpath .  destruct ( nel' l ) .   destruct ( natgehchoice2 _ _ nel ) as [ g | e ] . destruct j as [ | j ] . destruct ( negnatgeh0sn _ g ) .   split with j . unfold di .  destruct ( natlthorgeh j i ) as [ l' | g' ] .  destruct ( g l' ) .  apply idpath .  destruct ( ne ( pathsinv0 e ) ) . Defined . \n \n\nLemma isdecincldi ( i : nat ) : isdecincl ( di i ) .\nProof. intro i . intro j . apply isdecpropif .   apply ( isincldi i j ) .  destruct ( isdeceqnat i j )  as [ eq | neq ] .    destruct eq .  apply ( ii2 ( neghfiberdi i ) ) . apply ( ii1 ( pr1 ( iscontrhfiberdi i j neq ) ) ) .   Defined .\n\n\n\n\n\n\n(** ** Inductive types [ le ] with values in [ Type ] . \n\nThis part is included for illustration purposes only . In practice it is easier to work with [ natleh ] than with [ le ] . \n\n*)\n\n(** *** A generalization of [ le ] and its properties . *)\n\nInductive leF { T : Type } ( F : T -> T ) ( t : T ) : T -> Type := leF_O : leF F t t | leF_S : forall t' : T , leF F t t' -> leF F t ( F t' ) .\n\nLemma leFiter { T : UU } ( F : T -> T ) ( t : T ) ( n : nat ) : leF F t ( iteration F n t ) .\nProof. intros .   induction n as [ | n IHn ] . apply leF_O . simpl . unfold funcomp . apply leF_S .  assumption .  Defined . \n\nLemma leFtototal2withnat { T : UU } ( F : T -> T ) ( t t' : T ) ( a : leF F t t' ) : total2 ( fun n : nat => paths ( iteration F n t ) t' ) .\nProof. intros. induction a as [ | b H0 IH0 ] . split with O . apply idpath .  split with  ( S ( pr1 IH0 ) ) . simpl . apply ( @maponpaths _ _ F ( iteration F ( pr1 IH0 ) t ) b ) . apply ( pr2 IH0 ) .  Defined. \nLemma total2withnattoleF { T : UU } ( F : T -> T ) ( t t' : T ) ( a : total2 ( fun n : nat => paths ( iteration F n t ) t' ) ) : leF F t t' .\nProof. intros .  destruct a as [ n e ] .  destruct e .  apply leFiter.  Defined . \n\n\nLemma leFtototal2withnat_l0 { T : UU } ( F : T -> T ) ( t : T ) ( n : nat ) : paths ( leFtototal2withnat F t _ (leFiter F t n)) ( tpair _  n ( idpath (iteration F n t) ) ) . \nProof . intros . induction n as [ | n IHn ] .   apply idpath . simpl .  \nset ( h := fun ne :  total2 ( fun n0 : nat => paths ( iteration F n0 t ) ( iteration F n t ) ) => tpair  ( fun n0 : nat => paths ( iteration F n0 t ) ( iteration F ( S n ) t ) ) ( S ( pr1 ne ) ) ( maponpaths F ( pr2 ne ) ) ) . apply ( @maponpaths _ _ h  _ _ IHn ) . Defined. \n\n\nLemma isweqleFtototal2withnat { T : UU } ( F : T -> T ) ( t t' : T ) : isweq ( leFtototal2withnat F t t' ) .\nProof . intros .  set ( f := leFtototal2withnat F t t' ) . set ( g :=  total2withnattoleF  F t t' ) . \nassert ( egf : forall x : _ , paths ( g ( f x ) ) x ) . intro x .  induction x as [ | y H0 IHH0 ] . apply idpath . simpl . simpl in IHH0 .  destruct (leFtototal2withnat F t y H0 ) as [ m e ] .   destruct e .  simpl .   simpl in IHH0.  apply (  @maponpaths _ _ ( leF_S F t (iteration F m t) ) _ _ IHH0 ) .\nassert ( efg : forall x : _ , paths ( f ( g x ) ) x ) . intro x .  destruct x as [ n e ] .  destruct e . simpl .  apply  leFtototal2withnat_l0 . \napply ( gradth _ _ egf efg ) . Defined.\n\nDefinition weqleFtototalwithnat { T : UU } ( F : T -> T ) ( t t' : T ) : weq ( leF F t t' ) (  total2 ( fun n : nat => paths ( iteration F n t ) t' ) ) := weqpair _ ( isweqleFtototal2withnat F t t' ) .\n\n\n(** *** Inductive types [ le ] with values in [ Type ] are in [ hProp ] *)\n\nDefinition le ( n : nat ) : nat -> Type := leF S n .\nDefinition le_n := leF_O S .\nDefinition le_S := leF_S S . \n\n\n\nTheorem isaprople ( n m : nat ) : isaprop ( le n m ) .\nProof. intros .  apply ( isofhlevelweqb 1 ( weqleFtototalwithnat S n m ) ) . apply invproofirrelevance .  intros x x' .  set ( i := @pr1 _ (fun n0 : nat => paths (iteration S n0 n) m) ) . assert ( is : isincl i ) . apply ( isinclpr1 _ ( fun n0 : nat => isasetnat (iteration S n0 n) m ) ) . apply ( invmaponpathsincl _  is ) .  destruct x as [ n1 e1 ] . destruct x' as [ n2 e2 ] . simpl .   set ( int1 := pathsinv0 ( pathsitertoplus n1 n ) ) . set ( int2 := pathsinv0 (pathsitertoplus n2 n ) ) . set ( ee1 := pathscomp0 int1 e1 ) . set ( ee2 := pathscomp0 int2 e2 ) . set ( e := pathscomp0 ee1 ( pathsinv0 ee2 ) ) .   apply ( invmaponpathsincl _ ( isinclnatplusr n ) n1 n2 e ) .    Defined . \n\n(** *** Comparison between [ le ] with values in [ Type ] and [ natleh ] . *)\n\n\nLemma letoleh ( n m : nat ) : le n m -> natleh n m .\nProof .  intros n m H . induction H as [ | m H0 IHH0 ] . apply isreflnatleh .  apply natlehtolehs .  assumption .  Defined . \n\nLemma natlehtole ( n m : nat ) : natleh n m ->  le n m .\nProof. intros n m H .  induction m .  assert ( int := natleh0tois0 n H ) .   clear H . destruct int . apply le_n . \n set ( int2 := natlehchoice2 n ( S m ) H ) .  destruct int2 as [ isnatleh | iseq ] . apply ( le_S n m ( IHm isnatleh ) ) . destruct iseq .   apply le_n . Defined .\n\nLemma isweqletoleh ( n m : nat ) : isweq ( letoleh n m ) .\nProof. intros . set ( is1 := isaprople n m ) . set ( is2 := pr2 ( natleh n m )  ) . apply ( isweqimplimpl ( letoleh n m ) ( natlehtole n m ) is1 is2 ) .  Defined . \n\nDefinition weqletoleh ( n m : nat ) := weqpair _ ( isweqletoleh n m ) .\n\n\n\n\n(* End of the file hnat.v *)\n", "meta": {"author": "UniMath", "repo": "Foundations", "sha": "df19211f602ab71ee44f0ae4de2a19170c5b9e4d", "save_path": "github-repos/coq/UniMath-Foundations", "path": "github-repos/coq/UniMath-Foundations/Foundations-df19211f602ab71ee44f0ae4de2a19170c5b9e4d/hlevel2/hnat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6867681507581707}}
{"text": "\n(************************************************************************)\n(* Copyright (c) 2020, Gergei Bana, Qianli Zhang                        *)\n(*                                                                      *)\n(* This work is licensed under the MIT license. The license is          *)\n(* described in the file \"LICENSE\" available at the root of the source  *)\n(* or at https://opensource.org/licenses/MIT                            *)\n(************************************************************************)\n\n\n\n\nRequire Export F_Axioms.\n\n\nProposition ModusTollens :\n      (* \"meta-level quantification\" *) forall P Q : Prop,\n      (* \"premise1:\" *)     (P -> Q) ->\n      (* \"premise2:\" *)     (not Q) ->\n      (* \"conclusion:\" *)   (not P).\nProof. intros P Q. intros. unfold not. intros. apply H in H1.\ncontradiction.  Qed.\n\n\n\n\nProposition PBC (*Proof By Contradiction*) :\n      (* \"meta-level quantification\" *) forall P : Prop,\n      (* \"premise:\" *)     ((not P) -> False) ->\n      (* \"conclusion:\" *)    P.\nProof. intros. apply doubleneg_elim. unfold not.\nassumption. Qed.\n\nProposition LEM  (*Law of Excluded Middle*):\n      (* \"meta-level quantification\" *) forall P : Prop,\n      (* \"conclusion:\" *)    P \\/ (not P).\nProof. intros P.  apply PBC.\nintros. assert (P \\/ (not P)). apply or_intror. unfold not.\nintros. apply H.\napply or_introl. assumption.\napply H. assumption.  Qed.\n\n\n\n\n(**)\nLemma MT: forall p q: Prop,\n    (p -> q) -> not q -> not p.\nProof.\n  auto.\nQed.\n\n\n\n(**************************************************************************************)\n(*********************************** Axioms for Equality ******************************)\n(**************************************************************************************)\n\n\n(* Just for convenient naming  *)\n\nProposition  ceq_ref :\n    forall {x  : ppt} , x  = x .\nProof.\n  reflexivity.\nQed.\n\n\nProposition  ceq_symm :\n    forall {x y : ppt} , (x = y) -> (y = x).\nProof.\n  intros.\n  rewrite H.\n  reflexivity.\nQed.\n\nProposition  ceq_trans :\n    forall {x y z : ppt}, (x = y) -> (y = z) -> (x = z).\nProof.\n  intros.\n  rewrite H.\n  assumption.\nDefined.\n\n\nProposition  ceq_transymm :\n    forall {x y z : ppt }, (y = x) -> (y = z) -> (x = z).\nProof.\n  intros.\n  rewrite <- H.\n  assumption. \nDefined.\n\n\n\n\n\nProposition  ceq_cind :\nforall {x y : ppt}, x = y ->  [x] ~ [y].\nProof.\n  intros.\n  rewrite H.\n  apply cind_ref.\nDefined.\n\n\nProposition  ceq_funcapp :\n  forall {lt :  ppt -> ppt} ,\n  forall {x y : ppt},\n    x = y ->  ((lt x) = (lt y)).\nProof.\n  intros.\n  rewrite H.\n  reflexivity. \nQed.\n\n\nProposition ceq1 :\n  forall {x y} , x = y -> [EQ [x ; y]] ~ [TRue].\nProof.\n  intros.\n  apply ceq.\n  assumption.\nQed.\n\nProposition ceq2 :\n  forall {x y} , [EQ [x ; y]] ~ [TRue] -> x = y.\nProof.\n  intros.\n  apply ceq.\n  assumption.\nQed.\n\nProposition  ceql_ref :\n    forall {x  : list ppt} , x  = x .\nProof.\n  reflexivity.\nQed.\n\n\nProposition  ceql_symm :\n    forall {x y : list ppt} , (x = y) -> (y = x).\nProof.\n  intros.\n  rewrite H.\n  reflexivity.\nQed.\n\nProposition  ceql_trans :\n    forall {x y z : list ppt}, (x = y) -> (y = z) -> (x = z).\nProof.\n  intros.\n  rewrite H.\n  assumption.\nDefined.\n\nProposition  ceq_subeq :\n    (*\"<<<\"*) forall {lt1 :  ppt ->  ppt} {lt2 : ppt -> ppt}, (*\">>>\"*)\n    forall {x y : ppt},\n     x = y -> ((lt1 x) = (lt2 x)) -> ((lt1 y) = (lt2 y)).\nProof.\n  intros.\n  rewrite <- H.\n  assumption. \nQed.\n\n\n(*******************************************************************************)\n(*******************************************************************************)\n(********************* Properties of our PPT functions *************************)\n(*******************************************************************************)\n(*******************************************************************************)\n\n\nProposition Func0Const :\n  forall (hag : ComputationType) (c :  Symbols hag (narg 0)) (lx : list ppt),\n    ConstInt hag c = FuncInt hag (narg 0) c lx.\nProof.\n  intros.\n  rewrite <- (Const0Func hag c).\n  reflexivity.\nQed.\n\n\nProposition ConstHAG :\n  forall hag hag' c ,\n    PPT hag (FuncInt hag' (narg 0) c)\n    -> PPT hag (fun _ : list ppt => ConstInt hag' c).\nProof.\n  intros.\n  rewrite  (Const0Func hag' c).\n  assumption.\nQed.\n\n\nProposition nonceHonest :\n  forall n ,\n    (PPT Honest) (fun lx : list ppt => nonce n).\nProof.\n  intros.\n  simpl (nonce n).\n  rewrite Const0Func.\n  apply FunHAG.\nQed.\n\n\nProposition advAdversarial :\n  forall n ,\n    (PPT Adversarial) (adv n).\nProof.\n  intros.\n  simpl (adv n).\n  apply FunHAG.\nQed.\n\n\n\n\n\n\n\n(**************************************************************************************)\n(**************************************************************************************)\n(******************************** CORE  AXIOM IMPLICATIONS ****************************)\n(**************************************************************************************)\n(**************************************************************************************)\n\n\n\n\n\n\n\n(**************************************************************************************)\n(***************************** Properties of Indistinguishability ************************)\n(**************************************************************************************)\n\n\nProposition FuncApp :\n  forall {f : list ppt -> list ppt},\n  forall {lx ly} ,\n    (Context Adversarial List f )\n    ->  lx ~ ly\n    -> lx++f(lx) ~ ly++f(ly).\nProof.\n  intros.\n  assert (forall (f : list ppt -> list ppt) ,\n             (Context Adversarial List f )\n           -> (Context Adversarial List  (fun lx': list ppt => lx' ++ (f lx')))).\n  intros.\n  ProveContext.\n  assert (lx ++(f lx) ~ ly ++(f ly)).\n  apply (@cind_funcapp (fun lx' => lx' ++ (f lx')) lx ly).\n  apply H1.\n  assumption.\n  assumption.\n  assumption.\nQed.\n\n\n\n(* If f is constant, and lx, ly are lists, then we can apply cind_funcapp for the constant function:*)\nProposition cind_funcapp0 :\n  forall x0 :  ppt,\n    PPT Adversarial (fun lx => x0)\n    -> forall lx ly ,\n      lx ~ ly\n      -> lx ++ [x0] ~ ly ++ [x0].\nProof.\n  intros.\n  assert  (Context Adversarial List (fun lx => [x0])).\n  ProveContext.\n  apply (FuncApp H1).\n  assumption.\nQed.\n\n\n\nProposition cind_restr :\n  forall {l1 l2 t1 t2},\n    ((t1 :: l1) ~ (t2 :: l2))\n    -> (l1 ~ l2).\nProof.\n  intros.\n  assert (TL (t1 :: l1) ~ TL (t2 :: l2)).\n  apply (@cind_funcapp TL). ProveContext.\n  assumption.\n    simpl in H0.\nassumption. \nQed.\n\nProposition cind_len_rev :\n  forall {lt1 lt2 : list ppt},\n    lt1 ~ lt2\n    -> length lt1 = length lt2.\nProof.\n  intros.\n  apply doubleneg_elim.\n  unfold not at 1.\n  intros.\n  apply cind_len in H0.\n  contradiction.\nQed.\n\n\n\n\n\n(**************************************************************************************)\n(*************************************** Parametric Relations  ************************************)\n(**************************************************************************************)\n\n\n\n\n\n\nAdd Parametric Relation : (list ppt) cind\n  reflexivity proved by @cind_ref\n  symmetry proved by @cind_sym\n  transitivity proved by @cind_trans\n  as cind_rel.\n\n\n\n\n\n\n\n\n\n\n(**************************************************************************************)\n(******************************** Lemmas for If_Then_Else_ ****************************)\n(**************************************************************************************)\n\nProposition If_same :\n  forall {b x} , (If b Then x Else x) = x.\nProof.\n  intros.\n  assert (x = If TRue Then x Else (If b Then x Else x)).\n  rewrite If_true. reflexivity.\nrewrite (@If_morph (fun t => If TRue Then x Else t)) in H. \nrewrite If_true in H. rewrite <- H. reflexivity.\nProveContext. \nQed. \n\n\n\n(* TRue, FAlse are bools, EQ outputs bool, ITE outputs bool if its second and third inputs are bool *)\nProposition TRuebool : bppt TRue.\nProof.\n  unfold bppt.\n  rewrite If_true.\n  reflexivity.\nQed.\n\nProposition FAlsebool : bppt FAlse.\nProof.\n  unfold bppt.\n  rewrite If_false.\n  reflexivity.\nQed.\n\n\n\n\n\n(*****************\n **    If_tf    **\n *****************)\n\n(*  This his here just to match the papers. *)\n\nLemma If_tf :\n  forall b , bppt b ->\n    b = (If b Then TRue Else FAlse).\nProof.\n  intros.\n  unfold bppt in H. \n  assumption.\nQed.\n\n(*****************\n **  If_on_tf   **\n *****************)\n\nLemma If_on_tf :\n  forall b x y,\n    If b Then x Else y = If (If b Then TRue Else FAlse) Then x Else y.\nProof.\n  intros.\n  rewrite (@If_morph (fun t => If t Then x Else y)).\n  rewrite If_true.\n  rewrite If_false.\n  reflexivity.\n  ProveContext.\nQed. \n\n\n\n\n(*****************\n **  If_eval   **\n *****************)\n\n  \n  \nLemma If_eval :\n    (*\"<<<\"*) forall {tc1 tc2 : ppt -> ppt} ,  (*\">>>\"*)\nforall {b} ,\n(*\"<<<\"*) (ContextTerm General Term  tc1) ->  (ContextTerm General Term tc2) -> bppt b -> (*\">>>\"*)\n     ( If b Then (tc1 b) Else (tc2 b) ) = ( If b Then (tc1 TRue) Else (tc2 FAlse) ).\nProof.\n  intros.\n  rewrite (If_tf b) at 2 3.\n  rewrite (@If_morph (fun t => If b Then tc1 t Else tc2 t)).\n  rewrite (@If_idemp b).\n  reflexivity. \n  ProveContext.\n  assumption.\nQed.\n\n\n\n\n\n\n\n\n\n  \nProposition ITEbool :\n  forall b x y,\n    bppt x ->\n    bppt y ->\n    bppt (If b Then x Else y).\nProof.\n  unfold bppt.\n  intros.\n  rewrite (@If_morph (fun x => If x Then TRue Else FAlse)). simpl. \n  rewrite <- H. rewrite <- H0.\n  reflexivity.\n  ProveContext.\nQed.   \n  \n\n  \nLtac Provebool :=\n  repeat ( intros;\n           match goal with\n           |H : ?prop |- ?prop => apply H\n           |    |- bppt ((FuncInt ?hag ?arg ?f) ?lx)  => unfold f; apply bool1001\n           |    |- bppt (ConstInt ?hag ?f)  => unfold f; apply bool1001                                                                                            |    |- bppt (If ?b Then ?x Else ?y)  => apply ITEbool\n           end).\n\n\nGoal bppt FAlse.\n  Provebool. \nQed.\n\nGoal forall x y , bppt y -> bppt (EQ [x ; y]).\n  intros.  Provebool. \nQed.\n\n\nGoal forall x y z , bppt z -> bppt (If TRue\n             Then (EQ [x ; y])\n             Else (If FAlse\n                     Then z\n                     Else (EQ [FAlse ; default])  ) ).\nProof.\nProvebool.   \nQed. \n\n\n\n\n\n\nLtac ProveboolandContext :=\n  try (Provebool ; ProveContext).\n\nProposition  ceq_eq :\n    forall {x y : ppt} , x = y -> EQ [x ; y] = TRue.\nProof.\n  intros. \n  apply ceq in H.\n  apply (@FuncApp (fun lx => [TRue])) in H.  simpl in H.\n  apply (@cind_funcapp (fun lx => [EQ lx])) in H; simpl in H.\n  assert (H1 := (@ceq_ref TRue)).\n  apply ceq in H1.\n  apply ceq. \n  apply (cind_trans H H1). ProveContext. ProveContext.\nQed.\n\n\n\n\nProposition  ceqeq :\n    forall {x : ppt} , EQ [x ; x] = TRue.\nProof.\n  intros. \n  apply ceq_eq.\n  reflexivity.\nQed.\n\n\nProposition FreshNEqeq :\n      (*\"<<<\"*) forall nc x, FreshTerm nc x -> (*\"<<<\"*)\n                EQ [nc ; x] = FAlse.\nProof.\n  intros.\n  apply  (FreshNEq nc x) in H.\n  apply (@FuncApp (fun lx => [FAlse])) in H.  simpl in H.\n  apply (@cind_funcapp (fun lx => [EQ lx])) in H; simpl in H.\n  assert (H1 := (@ceq_ref FAlse)).\n  apply ceq in H1.\n  apply ceq. \n  apply (cind_trans H H1). ProveContext. ProveContext.\nQed.\n\n\n\n\n\n\n\n\n\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/G_AxiomImplications.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6867681457427351}}
{"text": "Require Export P05.\n\n\n\n(** **** Exercise: 2 stars (slow_assignment)  *)\n(** A roundabout way of assigning a number currently stored in [X] to\n    the variable [Y] is to start [Y] at [0], then decrement [X] until\n    it hits [0], incrementing [Y] at each step. Here is a program that\n    implements this idea:\n      {{ X = m }}\n    Y ::= 0;;\n    WHILE X <> 0 DO\n      X ::= X - 1;;\n      Y ::= Y + 1\n    END\n      {{ Y = m }} \n    Write an informal decorated program showing that this is correct. *)\n\nTheorem slow_assignment : forall m,\n    {{ fun st => st X = m }}\n    Y ::= ANum 0;;\n    WHILE BNot (BEq (AId X) (ANum 0)) DO\n      X ::= AMinus (AId X) (ANum 1);;\n      Y ::= APlus (AId Y) (ANum 1)\n    END\n    {{ fun st => st Y = m }}.\nProof. intros.\n  (* {{P}} c;;while {{R}} *)\n  eapply hoare_seq with (Q:= (fun st => st X + st Y= m)). (* Q = P /\\ Y=0 *)\n  Case \"{{Q}} while {{R}} \". eapply hoare_consequence_post. \n    SCase \"{{Q}} while {{R'}}\". apply hoare_while. (* R' = Q/\\~b *)\n    (* now need to show that {{Q/\\b}} c1;;c2 {{Q}} *)\n    simpl. eapply hoare_seq.\n      SSCase \"{{Q'}} c2 {{R'}}\".\n        apply hoare_asgn.\n      SSCase \"{{Q/\\b}} c1 {{Q'}}\".\n        eapply hoare_consequence_pre. \n        (* {{Q''}} c1 {{Q'}} *) apply hoare_asgn.\n        (* Q/\\b ->> Q'' *) unfold assert_implies, assn_sub. intros; simpl.\n        unfold update. simpl. destruct H. rewrite<-H. \n        apply negb_true_iff in H0. apply beq_nat_false_iff in H0.\n        (* We need the condition that xt X > 0 to use omega here *) omega.\n    SCase \"R' ->> R\".\n  unfold hoare_triple, assert_implies. intros.\n  destruct H. simpl in H0. apply negb_false in H0. apply beq_nat_true_iff in H0. omega.\n\n  Case \"{{P}} c {{Q}}\".\n    unfold hoare_triple. intros. inversion H; subst. simpl.\n    unfold update. simpl. omega.\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/10/P06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.6867590383227469}}
{"text": "(******************************************************************************)\n(** Various list-related lemmas **)\n(******************************************************************************)\n\nRequire Import List.\nFrom hahn Require Import Hahn.\nRequire Import Omega.\nRequire Import Utils.\nFrom PromisingLib Require Import Basic Loc.\nSet Implicit Arguments.\n\n\nSection ListHelpersTemp.\n  (******************************************************************************)\n  (** The following lemmas are proved in Coq 8.10 **)\n  (** Proofs have been (partially) copied from it **)\n  (******************************************************************************)\n  \n  Variable A : Type.\n\n  Lemma skipn_firstn_comm : forall m n (l: list A),\n      skipn m (firstn n l) = firstn (n - m) (skipn m l).\n  Proof.\n    now induction m; intros [] []; simpl; rewrite ?firstn_nil.\n  Qed.\n\n\n  Lemma firstn_skipn_comm : forall m n (l: list A),\n      firstn m (skipn n l) = skipn n (firstn (n + m) l).\n  Proof.\n    now intros m; induction n; intros []; simpl; destruct m.\n  Qed.\n\n  Lemma skipn_app n : forall {A: Type} (l1 l2: list A),\n      skipn n (l1 ++ l2) = (skipn n l1) ++ (skipn (n - length l1) l2).\n  Proof.\n    induction n; auto; intros.\n    destruct l1; auto.\n    rewrite <- app_comm_cons. simpl.\n    auto.\n  Qed.\n\n  Lemma skipn_all2 n: forall (l: list A), length l <= n -> skipn n l = nil.\n  Proof.\n    intros l L%PeanoNat.Nat.sub_0_le; rewrite <- (firstn_all l).\n    now rewrite skipn_firstn_comm, L.\n  Qed.\n\nEnd ListHelpersTemp.\n\n\nSection ListHelpers.\n  Variable A: Type. \n\n  Lemma first_end (l: list A) n x (NTH: Some x = List.nth_error l n):\n    firstn (n + 1) l = firstn n l ++ cons x nil.\n  Proof.\n    ins. \n    symmetry in NTH. apply nth_error_split in NTH as [l1 [l2 [CAT H]]].\n    rewrite <- H. pose proof (@firstn_app_2 A 1 l1 (x :: l2)).\n    rewrite CAT. simpl in H0. rewrite H0.\n    pose proof (@firstn_app_2 A 0 l1). simpl in H1. rewrite app_nil_r, NPeano.Nat.add_0_r in H1.\n    rewrite H1. auto. \n  Qed.      \n  \n  Lemma firstn_ge_incl (l: list A) i j (LE: i <= j):\n    firstn j l = firstn i l ++ skipn i (firstn j l).\n  Proof. \n    destruct (lt_dec j (length l)) as [LTj | GEj]. \n    2: { rewrite firstn_all2 with (n := j); [| omega].\n         symmetry. eapply firstn_skipn. }\n    rewrite <- firstn_skipn with (n := i) at 1.\n    rewrite firstn_firstn.\n    rewrite (NPeano.Nat.min_l _ _ LE). \n    eauto.\n  Qed. \n  \n  Lemma skipn_firstn_nil (l: list A) i:\n    skipn i (firstn i l) = nil.\n  Proof.\n    generalize dependent l. induction i; vauto. ins. destruct l; auto.\n  Qed.     \nEnd ListHelpers. \n\n\nSection ListListHelpers.\n  Variable A: Type. \n\n  Definition same_struct (ll1 ll2: list (list A)) :=\n    Forall2 (fun l1 l2 => length l1 = length l2) ll1 ll2.\n  \n  Lemma SAME_STRUCT_PREF (ll1 ll2: list (list A)) (SS: same_struct ll1 ll2) i: \n    length (flatten (firstn i ll1)) = length (flatten (firstn i ll2)).\n  Proof.\n    generalize dependent ll2. generalize dependent i.\n    induction ll1.\n    { ins. inversion SS. subst. auto. }\n    ins. inversion SS. subst.\n    destruct i.\n    { simpl. auto. }\n    simpl. do 2 rewrite length_app. f_equal; auto.  \n  Qed. \n    \n  Lemma same_struct_refl (ll: list (list A)): same_struct ll ll.\n  Proof.\n    induction ll.\n    { vauto. }\n    econstructor; vauto.\n  Qed.\n  \n  Lemma NONEMPTY_PREF (ll: list (list A)) (NE: Forall (fun l => l <> nil) ll)\n        i j (SAME_LEN: length (flatten (firstn i ll)) =\n                       length (flatten (firstn j ll)))\n        (INDEXI: i <= length ll) (INDEXJ: j <= length ll ): \n    i = j.\n  Proof.\n    generalize dependent i. generalize dependent j.\n    induction ll.\n    { ins. omega. }\n    ins. destruct i, j; [auto | | |]. \n    { simpl in SAME_LEN. rewrite length_app in SAME_LEN.\n      inversion NE. subst. destruct a; vauto. }\n    { simpl in SAME_LEN. rewrite length_app in SAME_LEN.\n      inversion NE. subst. destruct a; vauto. }\n    f_equal.\n    apply IHll.\n    { inversion NE. auto. }\n    { apply le_S_n. auto. }\n    2: { apply le_S_n. auto. }\n    simpl in SAME_LEN. do 2 rewrite length_app in SAME_LEN.\n    omega.\n  Qed. \n  \n  Lemma flatten_split (ll: list (list A)) bi (INDEX: bi < length ll):\n    flatten ll = flatten (firstn bi ll) ++ flatten (skipn bi ll).\n  Proof. ins. rewrite <- flatten_app. rewrite firstn_skipn. auto. Qed.\n   \n  Lemma ll_index_shift (ll: list (list A)) i j block\n        (ITH: Some block = nth_error ll i) (NE: Forall (fun l => l <> nil) ll)\n        (J_BOUND: j <= length ll):\n    length (flatten (firstn j ll)) = length (flatten (firstn i ll)) + length block\n    <-> j = i + 1.\n  Proof.\n    split. \n    2: { ins; subst. erewrite first_end; eauto.\n         rewrite flatten_app, length_app. simpl. rewrite app_nil_r. auto. }\n    intros FLT_SHIFT. \n    destruct (dec_le j i) as [LE | GT].\n     { rewrite (firstn_ge_incl ll LE) in FLT_SHIFT.  \n       rewrite flatten_app, length_app in FLT_SHIFT.\n       cut (length block > 0); [ins; omega |]. \n       apply (proj1 (Forall_forall (fun l => l <> nil) ll)) with (x := block) in NE. \n       { destruct block; vauto. simpl. omega. } \n       eapply nth_error_In. eauto. }\n     apply not_le in GT.\n     rewrite (@firstn_ge_incl _ ll i j) in FLT_SHIFT; [| omega].\n     assert (exists d, j = i + S d). \n     { ins. destruct (j - i) eqn:DIFF. \n       { exists 0. omega. }\n       exists n. omega. }\n     desc. subst.\n     cut (d = 0); [ins; omega|].\n     destruct d; auto.\n     exfalso. \n     rewrite flatten_app, length_app in FLT_SHIFT.\n     apply plus_reg_l in FLT_SHIFT.\n     replace (i + S (S d)) with ((i + 1 + d) + 1) in FLT_SHIFT by omega.\n     assert (exists block', Some block' = nth_error ll (i + 1 + d)) as [block' BLOCK'].\n     { apply OPT_VAL, nth_error_Some. omega. }\n     erewrite first_end in FLT_SHIFT; eauto.\n     rewrite skipn_app in FLT_SHIFT.\n     replace (i - length (firstn (i + 1 + d) ll)) with 0 in FLT_SHIFT.\n     2: { rewrite firstn_length_le; omega. }\n     rewrite <- firstn_skipn with (l := ll) (n := i + 1) in FLT_SHIFT.\n     erewrite first_end in FLT_SHIFT; eauto.\n     rewrite <- app_assoc in FLT_SHIFT.\n     replace i with (length (firstn i ll)) in FLT_SHIFT at 2.\n     2: { apply firstn_length_le. omega. }\n     rewrite <- plus_assoc in FLT_SHIFT. \n     rewrite firstn_app_2 in FLT_SHIFT.\n     simpl in FLT_SHIFT.\n     rewrite skipn_app in FLT_SHIFT.\n     replace (length (firstn i ll)) with i in FLT_SHIFT. \n     2: { symmetry. apply firstn_length_le. omega. }\n     rewrite skipn_firstn_nil in FLT_SHIFT. \n     rewrite Nat.sub_diag in FLT_SHIFT. simpl in FLT_SHIFT.\n     rewrite !flatten_app, !length_app in FLT_SHIFT. simpl in FLT_SHIFT.\n     rewrite app_nil_r in FLT_SHIFT.\n     cut (length block' <> 0); [ins; omega| ]. \n     pose proof (Forall_forall (fun l : list A => l <> nil) ll).\n     cut (block' <> nil).\n     { ins. destruct block'; vauto. }\n     apply H; auto.  \n     eapply nth_error_In. eauto.\n  Qed.\n     \nEnd ListListHelpers. \n\n\nSection Forall2Helpers.\n  Variable A B: Type.\n  \n  Lemma Forall2_index (l1: list A) (l2: list B) P\n        (FORALL2: Forall2 P l1 l2)\n        x y i (XI: Some x = nth_error l1 i) (YI: Some y = nth_error l2 i):\n    P x y.\n  Proof.\n    generalize dependent l2. generalize dependent l1.\n    set (T := fun i => forall l1 : list A,\n                  Some x = nth_error l1 i ->\n                  forall l2 : list B, Forall2 P l1 l2 -> Some y = nth_error l2 i -> P x y).\n    eapply (strong_induction T).\n    ins. red. ins. unfold T in IH.\n    destruct l1; [destruct n; vauto |]. destruct l2; [destruct n; vauto |]. \n    destruct n eqn:N.\n    { subst. simpl in *. inversion H. inversion H1. subst.\n      inversion H0. auto. }\n    subst. simpl in *. eapply IH; eauto.\n    inversion H0. auto.\n  Qed.\n\n  Lemma Forall2_length (l1: list A) (l2: list B) P\n        (FORALL2: Forall2 P l1 l2):\n    length l1 = length l2.\n  Proof.\n    generalize dependent l2. induction l1.\n    { ins. inversion FORALL2. auto. }\n    ins. inversion FORALL2. subst. simpl. f_equal.\n    apply IHl1. auto.\n  Qed. \n      \nEnd Forall2Helpers.\n\n\nSection ForallHelpers.\n  Variable A: Type. \n  \n  Lemma Forall_index (l: list A) P:\n    Forall P l <-> forall x i (XI: Some x = nth_error l i), P x.\n  Proof.\n    split.\n    { intros FORALL x i XI.\n      forward eapply (@Forall2_index _ _ l l (fun x _ => P x)); eauto. \n      clear XI. generalize dependent l. intros l. induction l.\n      { ins. }\n      ins. inversion FORALL. subst. apply Forall2_cons; auto. }\n    ins. induction l; auto.    \n    apply Forall_cons. split.\n    { apply H with (i := 0). auto. }\n    apply IHl. ins.\n    apply H with (i := S i). simpl. auto. \n  Qed.\n\nEnd ForallHelpers.   \n\n\nSection Sublist.\n  Variable A: Type.\n  \n  Definition sublist (l: list A) (start len: nat) := firstn len (skipn start l).\n\n  Lemma sublist_items (whole: list A) start size result\n        (SL: result = sublist whole start size)\n        (FULL: length result = size):\n    forall i (INDEX: i < size), nth_error result i = nth_error whole (start + i). \n  Proof.\n    intros.\n    unfold sublist in SL.\n    assert (forall {A: Type} (pref res suf: list A) i (INDEX: i < length res), nth_error res i = nth_error (pref ++ res ++ suf) (length pref + i)).\n    { intros. induction pref.\n      - simpl. symmetry. apply nth_error_app1. auto.\n      - simpl. apply IHpref. }\n    forward eapply (@H _ (firstn start whole) result (skipn size (skipn start whole))) as H'. \n    { rewrite FULL. eauto. }\n    assert (STRUCT: whole = firstn start whole ++ result ++ skipn size (skipn start whole)).\n    { rewrite <- (firstn_skipn start whole) at 1.\n      cut (result ++ skipn size (skipn start whole) = skipn start whole).\n      { intros. congruence. }\n      rewrite SL. apply firstn_skipn. }\n    rewrite H'. rewrite STRUCT at 4.\n    cut (length (firstn start whole) = start); auto.\n    apply firstn_length_le.\n    destruct (le_lt_dec start (length whole)); auto.\n    rewrite skipn_all2 in SL; [| omega]. rewrite firstn_nil in SL.\n    rewrite SL in FULL. simpl in FULL. omega. \n  Qed.  \n\nEnd Sublist. ", "meta": {"author": "fresheed", "repo": "omm-imm", "sha": "59a4c709e31d3aaf2b34ebd5a8e7d3efe104f3c2", "save_path": "github-repos/coq/fresheed-omm-imm", "path": "github-repos/coq/fresheed-omm-imm/omm-imm-59a4c709e31d3aaf2b34ebd5a8e7d3efe104f3c2/src/ocamlmm/ListHelpers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.6867590086223093}}
{"text": "Require Import List Nat PeanoNat Bool.\n\nDefinition mapfold k {A} (f: A->nat) l := fold_right k 0 (map f l).\n\nClass Work (A: Type) :=\n  {\n    est      : A -> nat; (* earliest start time *)\n    lct      : A -> nat; (* latest completion time *)\n    energy   : A -> nat; (* resource units times time units *)\n  }.\n\nStructure Activity : Type := mkActivity\n  {\n    a_est : nat;\n    a_lct : nat;\n    a_c : nat;\n    a_p : nat\n    (*;a_ok : (a_lct-a_est >= a_p)*)\n  }.\n\nInstance : Work Activity :=\n  {\n    est := a_est;\n    lct := a_lct;\n    energy w := (a_c w) * (a_p w)\n  }.\n\nInstance : Work (list Activity) :=\n  {\n    est    := mapfold min est;\n    lct    := mapfold max lct;\n    energy := mapfold add energy\n  }.\n\nInstance : Work (list (Activity*nat)) :=\n  {\n    est    l := est (map fst l);\n    lct    l := lct (map fst l);\n    energy l := energy (map fst l)\n  }.\n\nDefinition envelope_unit (C: nat) (activity: Activity) : nat :=\n  C * est activity + energy activity.\n\nDefinition a_valid (a: Activity) (start: nat) : Prop :=\n  start >= (a_est a) /\\ start + (a_p a) <= (a_lct a).\n\nDefinition a_use (a: Activity) (start: nat) (sample: nat) :=\n  if (start <=? sample) && (sample <? start + (a_p a))\n    then a_c a\n    else 0.\n\nDefinition aa_valid (assignment: list (Activity * nat)) :=\n  fold_right and True (map\n    (fun x => a_valid (fst x) (snd x))\n    assignment).\n\nDefinition aa_use (assignment: list (Activity * nat)) (sample: nat) :=\n  mapfold add (fun x => a_use (fst x) (snd x) sample) assignment.\n\nDefinition aa_fit (C: nat) (assignment: list (Activity * nat)) :=\n  forall (sample: nat), aa_use assignment sample <= C.\n", "meta": {"author": "rrika", "repo": "cumulative", "sha": "b9ab2af27a691249ec656bd482264324a7c8b9ab", "save_path": "github-repos/coq/rrika-cumulative", "path": "github-repos/coq/rrika-cumulative/cumulative-b9ab2af27a691249ec656bd482264324a7c8b9ab/src/definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6865539852100044}}
{"text": "\nRequire Import Relations Relation_Operators.\nRequire Import Wf_nat.\n\n\nSection Bad_hypothesis.\n\n(** Let's assume the union of any pair of well-founded relations is \n    well founded too ... *)\n\nHypothesis union_wf : forall {A:Type}(R S: relation A),\n                      well_founded R -> \n                      well_founded S ->\n                      well_founded (union A R S).\n\n(** Les us build a counter-example ... *)\nDefinition  R0  : relation nat := fun x y : nat => x = 2 /\\ y = 1.\n\n\nLemma R0_wf : well_founded  R0.\nProof.\n intros x; split.\n intros y Hy; destruct Hy; subst x y.\n - split.\n  + destruct  1; discriminate.\nQed.\n\n(** By our hypothesis, the union of Peano's lt and R0 would be well-founded *)\nDefinition R1 := union _ lt R0.\n\nRemark  R1_wf : well_founded R1.\nProof.\n unfold R1; apply union_wf.\n - apply lt_wf.\n - apply R0_wf.\nQed.\n\nLemma Acc_neg {A:Type}(R:relation A) : \n          forall x, Acc R x -> forall y, R y x ->  ~ R x y.\ninduction 1.\nintros y Hy H1; generalize (H0 y Hy x H1); intro; contradiction.\nQed.\n\n\nLemma F : False.\nProof. \n specialize  (Acc_neg  R1 1); intro H; apply H with 2.  \n - apply R1_wf.\n - right; now constructor.\n - left;auto with arith.\nQed.\n\n\n\n\nEnd Bad_hypothesis.\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/new_exercises/SRC/union_not_wf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6864645840402773}}
{"text": "Require Import List.\nImport ListNotations.\n\nFrom mathcomp Require Import fintype.\nRequire Import Basics.\nRequire Import Lia.\n\nSection Tclose.\n  Context {T : Type}.\n  Context (R : T -> T -> Prop).\n  Inductive TransitiveClosure : T -> T -> Prop :=\n  | ClosureBase : forall t1 t2 : T, R t1 t2 -> TransitiveClosure t1 t2\n  | ClosureRec : forall t1 t2 t3, TransitiveClosure t1 t2 -> R t2 t3 -> TransitiveClosure t1 t3.\n\n  Lemma CloseCompose : forall t1 t2 t3, TransitiveClosure t1 t2 -> TransitiveClosure t2 t3 -> TransitiveClosure t1 t3.\n    intros t1 t2 t3 r1 r2.\n    revert r1. generalize dependent t1.\n    induction r2.\n    {\n      intros t0 r.\n      eauto using TransitiveClosure.\n    }\n    {\n      intros t0 r.\n      assert (TransitiveClosure t0 t2) by eauto.\n      eauto using TransitiveClosure.\n    }\n  Qed.\n\n  Inductive TransitiveReflexiveClosure : T -> T -> Prop :=\n  | ReflexiveBase1 : forall t, TransitiveReflexiveClosure t t\n  | ReflexiveBase2 : forall t1 t2, R t1 t2 -> TransitiveReflexiveClosure t1 t2\n  | ReflexiveRec : forall t1 t2 t3, TransitiveReflexiveClosure t1 t2 ->\n                              TransitiveReflexiveClosure t2 t3 ->\n                              TransitiveReflexiveClosure t1 t3.\n\n  Lemma TR_in_TRC : forall t1 t2, TransitiveClosure t1 t2 -> TransitiveReflexiveClosure t1 t2.\n    intros t1 t2 H.\n    induction H; try eauto using TransitiveReflexiveClosure.\n  Qed.\n\n  Inductive TransitiveReflexiveClosure' : T -> T -> Prop :=\n  | ReflexiveBase' : forall t, TransitiveReflexiveClosure' t t\n  | ReflexiveRec' : forall t1 t2, TransitiveClosure t1 t2 -> TransitiveReflexiveClosure' t1 t2.\n\n  Lemma TRCCompose : forall t1 t2 t3, TransitiveReflexiveClosure t1 t2 -> TransitiveReflexiveClosure t2 t3 -> TransitiveReflexiveClosure t1 t3.\n    intros t1 t2 t3 r1.\n    induction r1; try eauto.\n    intros r2. induction r2; try eauto using TransitiveReflexiveClosure.\n  Qed.\n\n  Lemma TRCCompose' : forall t1 t2 t3, TransitiveReflexiveClosure' t1 t2 -> TransitiveReflexiveClosure' t2 t3 -> TransitiveReflexiveClosure' t1 t3.\n    intros t1 t2 t3 r1 r2.\n    inversion r1; try auto. subst.\n    inversion r2; try (subst; auto).\n    eauto using CloseCompose, TransitiveReflexiveClosure'.\n  Qed.\n\n  Lemma TRCConv : forall t1 t2, TransitiveReflexiveClosure t1 t2 ->\n                           TransitiveReflexiveClosure' t1 t2.\n    intros t1 t2 HTrc.\n    induction HTrc; try eauto using TransitiveReflexiveClosure', TransitiveClosure, CloseCompose.\n    inversion IHHTrc1; try (subst; easy).\n    inversion IHHTrc2; try (subst; easy).\n    subst.\n    eauto using CloseCompose, TransitiveReflexiveClosure'.\n  Qed.\n\n  Lemma TRCConv' : forall t1 t2, TransitiveReflexiveClosure' t1 t2 ->\n                           TransitiveReflexiveClosure t1 t2.\n    intros t1 t2 HTrc.\n    inversion HTrc; try (subst; eauto using TransitiveReflexiveClosure, TR_in_TRC).\n  Qed.\nEnd Tclose.\n\n\nAxiom lem : forall P : Prop, P \\/ ~P.\n\nLemma dn : forall P, ~ ~ P -> P.\n  intros P H.\n  unfold not in H.\n  assert (P \\/ ~P) by apply lem.\n  inversion H0. { assumption. } { exfalso. apply H. apply H1. } Qed.\n\n\nSection PegReg.\n  Context (Σ : finType).\n  Context (eq_dec : Σ -> Σ -> bool).\n  Context (eq_dec_correct : forall σ1 σ2, (eq_dec σ1 σ2 = true <-> σ1 = σ2) /\\ (eq_dec σ1 σ2 = false <-> σ1 <> σ2)).\n\n  Inductive PEG : Type :=\n  | Char (c : Σ)\n  | Concat (p1 : PEG) (p2 : PEG)\n  | PossesiveStar (p1 : PEG)\n  | OrderedChoice (p1 : PEG) (p2 : PEG).\n\n  Inductive SyntacticOrder : PEG -> PEG -> Prop :=\n  | ConcatL : forall p1 p2 : PEG, SyntacticOrder p1 (Concat p1 p2)\n  | ConcatR : forall p1 p2 : PEG, SyntacticOrder p2 (Concat p1 p2)\n  | PossesiveStarLt : forall p1 : PEG, SyntacticOrder p1 (PossesiveStar p1)\n  | OrderedChoiceL : forall p1 p2 : PEG, SyntacticOrder p1 (OrderedChoice p1 p2)\n  | OrderedChoiceR : forall p1 p2 : PEG, SyntacticOrder p2 (OrderedChoice p1 p2).\n\n  Lemma char_smallest : forall c, forall p, SyntacticOrder p (Char c) -> False.\n    intros c p H.\n    remember (Char c).\n    remember p.\n    induction H; discriminate.\n  Qed.\n\n  Lemma wf_syntactic_order : well_founded SyntacticOrder.\n    unfold well_founded.\n    intros a.\n    induction a.\n    {\n      constructor.\n      intros y H.\n      exfalso.\n      eapply char_smallest.\n      exact H.\n    }\n    {\n      constructor.\n      intros y.\n      intros H.\n      inversion H; subst; assumption.\n    }\n    {\n      constructor.\n      intros y H.\n      inversion H.\n      subst.\n      assumption.\n    }\n    {\n      constructor.\n      intros y H.\n      inversion H; subst; assumption.\n    }\n  Qed.\n\n  Inductive RecursiveSyntacticOrder : PEG -> PEG -> Prop :=\n  | SyntacticOrderLt : forall p1 p2, SyntacticOrder p1 p2 -> RecursiveSyntacticOrder p1 p2\n  | Trans : forall p1 p2 p3, RecursiveSyntacticOrder p1 p2 -> RecursiveSyntacticOrder p2 p3 -> RecursiveSyntacticOrder p1 p3.\n\n\n  Lemma char_smallest_rec : forall c, forall p, RecursiveSyntacticOrder p (Char c) -> False.\n    intros c p H.\n    remember (Char c).\n    induction H.\n    {\n      subst.\n      apply char_smallest in H.\n      assumption.\n    }\n    {\n      subst.\n      eauto.\n    }\n  Qed.\n\n  Check (well_founded_ind (wf_syntactic_order) (fun o =>\n                                                  forall e, RecursiveSyntacticOrder o e ->\n                                                  Acc RecursiveSyntacticOrder o)).\n  Lemma wf_recursive_syntactic_order : well_founded RecursiveSyntacticOrder.\n    constructor.\n    induction a.\n    {\n      intros y H.\n      now apply char_smallest_rec in H.\n    }\n    {\n      intros y H.\n      remember (Concat a1 a2).\n      induction H.\n      {\n        subst.\n        inversion H; subst; constructor; intros y HSmaller. { now apply IHa1. } { now apply IHa2. }\n      }\n      {\n        subst.\n        assert (Acc RecursiveSyntacticOrder p2) by eauto.\n        inversion H1.\n        now apply H2.\n      }\n    }\n    {\n      intros y H.\n      remember (PossesiveStar a).\n      induction H.\n      {\n        subst.\n        inversion H.\n        subst.\n        constructor.\n        intros y HSmaller.\n        now apply IHa.\n      }\n      {\n        subst.\n        assert (Acc RecursiveSyntacticOrder p2) by eauto.\n        inversion H1.\n        now apply H2.\n      }\n    }\n    {\n      intros y H.\n      remember (OrderedChoice a1 a2).\n      induction H.\n      {\n        subst.\n        inversion H; subst; constructor; intros y HSmaller. { now apply IHa1. } { now apply IHa2. }\n      }\n      {\n        subst.\n        assert (Acc RecursiveSyntacticOrder p2) by eauto.\n        inversion H1.\n        now apply H2.\n      }\n    }\n    Qed.\n\n  Inductive PegMatch : PEG -> list Σ -> option (list Σ * list Σ) -> Prop :=\n  | CharS : forall c : Σ, forall t : list Σ, PegMatch (Char c) (c :: t) (Some ([c], t))\n  | CharFail : forall c1 c2 : Σ, forall t : list Σ, (eq_dec c1 c2) = false -> PegMatch (Char c1) (c2 :: t) None\n  | CatS : forall p1 p2 : PEG, forall l0 l1 l2 l3 l4 : list Σ, PegMatch p1 l0 (Some (l1, l2)) ->\n                                                     PegMatch p2 l2 (Some (l3,  l4)) ->\n                                                     PegMatch (Concat p1 p2) l0 (Some ((l1 ++ l3), l4))\n  | CatFail1 : forall p1 p2 : PEG, forall l : list Σ, PegMatch p1 l None -> PegMatch (Concat p1 p2) l None\n  | CatFail2 : forall p1 p2 : PEG, forall l0 l1 l2 : list Σ, PegMatch p1 l0 (Some (l1, l2)) -> PegMatch p2 l2 None -> PegMatch (Concat p1 p2) l0 None\n  | ChoiceL : forall p1 p2 : PEG, forall l0 l1 l2 : list Σ, PegMatch p1 l0 (Some (l1, l2)) ->\n                                                  PegMatch (OrderedChoice p1 p2) l0 (Some (l1, l2))\n  | ChoiceR : forall p1 p2 : PEG, forall l0 l1 l2 : list Σ, PegMatch p1 l0 None -> PegMatch p2 l0 (Some (l1, l2)) -> PegMatch (OrderedChoice p1 p2) l0 (Some (l1, l2))\n  | ChoiceFail : forall p1 p2 : PEG, forall l0 : list Σ, PegMatch p1 l0 None -> PegMatch p2 l0 None -> PegMatch (OrderedChoice p1 p2) l0 None\n  | StarEnd : forall p1 : PEG, forall l : list Σ, PegMatch p1 l None -> PegMatch (PossesiveStar p1) l (Some ([], l))\n  | StarRec : forall p1 : PEG, forall l0 l1 l2 l3 l4 : list Σ, PegMatch p1 l0 (Some (l1, l2)) -> PegMatch (PossesiveStar p1) l2 (Some (l3, l4)) -> PegMatch (PossesiveStar p1) l0 (Some (l1 ++ l3, l4)).\n\n  Lemma app_nil : forall T, forall l1 l2 : list T, l1 ++ l2 = [] -> (l1 = [] /\\ l2 = []).\n    intros T l1.\n    induction l1.\n    {\n      eauto.\n    }\n    {\n      intros l2 H.\n      inversion H.\n    }\n  Qed.\n\n  Lemma some_eq : forall T, forall t1 t2 : T, t1 = t2 -> Some t1 = Some t2.\n    - intros T t1 t2 H.\n      rewrite H.\n      reflexivity.\n  Qed.\n\n  Lemma list_split : forall p : PEG, forall l1 l2 l3 : list Σ, PegMatch p l1 (Some (l2, l3)) -> l1 = l2 ++ l3.\n    intros P l1 l2 l3 m.\n    remember (Some (l2, l3)) as output.\n    generalize dependent l3.\n    generalize dependent l2.\n    remember l1 as input.\n    generalize dependent l1.\n    induction m; try discriminate; try eauto.\n    {\n      intros l1 H1 l2 l3 H2.\n      inversion H2.\n      reflexivity.\n    }\n    {\n      intros l5 H1 l6 l7 H2.\n      inversion H2.\n      subst l7.\n      subst l6.\n      clear H2.\n      subst l5.\n      rename l0 into input.\n      rename l2 into remainder.\n      assert (remainder = l3 ++ l4).\n      {\n        eauto.\n      }\n      rewrite <- app_assoc.\n      subst remainder.\n      eauto.\n    }\n    {\n      intros l1 H1 l2 l3 H2.\n      inversion H2. subst l3. subst l2.\n      reflexivity.\n    }\n    {\n      intros l6 H1 l7 l8 H2.\n      subst l6.\n      inversion H2.\n      subst l8.\n      subst l7.\n      clear H2.\n      assert (l2 = l3 ++ l4).\n      {\n        eauto.\n      }\n      rewrite <- app_assoc.\n      subst l2.\n      eauto.\n    }\n  Qed.\n\n  Lemma ConcatDistrEquivalentMatch : forall P1 P2 P3, forall l1 l2 l3,\n      PegMatch (Concat (Concat P1 P2) P3) l1 (Some (l2, l3)) <->\n      PegMatch (Concat P1 (Concat P2 P3)) l1 (Some (l2, l3)).\n    intros P1 P2 P3 l1 l2 l3.\n    split.\n    {\n      intros H.\n      inversion H.\n      subst.\n      inversion H4.\n      subst.\n      rewrite <- app_assoc.\n      eapply CatS.\n      {\n        exact H5.\n      }\n      {\n        eapply CatS. { exact H8. } { exact H6. }\n      }\n    }\n    {\n      intros H.\n      inversion H.\n      subst.\n      inversion H6.\n      subst.\n      rewrite app_assoc.\n      eapply CatS.\n      {\n        eapply CatS.\n        {\n          exact H4.\n        }\n        {\n          exact H5.\n        }\n      }\n      {\n        exact H8.\n      }\n    }\n  Qed.\n\n  Lemma ConcatDistrEquivalentFail : forall P1 P2 P3, forall l,\n      PegMatch (Concat (Concat P1 P2) P3) l None <->\n        PegMatch (Concat P1 (Concat P2 P3)) l None.\n    intros P1 P2 P3 l.\n    split.\n    {\n      intros H.\n      inversion H.\n      {\n        subst.\n        inversion H3.\n        {\n          now eapply CatFail1.\n        }\n        {\n          subst.\n          eapply CatFail2; try exact H2.\n          now eapply CatFail1.\n        }\n      }\n      {\n        subst.\n        inversion H2.\n        subst.\n        eapply CatFail2.\n        {\n          exact H6.\n        }\n        {\n          eapply CatFail2.\n          {\n            exact H8.\n          }\n          {\n            exact H4.\n          }\n        }\n      }\n    }\n    {\n      intros H.\n      inversion H.\n      {\n        subst.\n        eapply CatFail1.\n        now eapply CatFail1.\n      }\n      {\n        subst.\n        inversion H4.\n        subst.\n        {\n          eapply CatFail1.\n          now eapply CatFail2; try exact H2.\n        }\n        {\n          subst.\n          eapply CatFail2.\n          {\n            eapply CatS. { exact H2. } { exact H3. }\n          }\n          {\n            exact H6.\n          }\n        }\n      }\n    }\n  Qed.\n\n  Lemma PStarWeakerPPStar : forall P l1 l2 l3, PegMatch (PossesiveStar P) l1 (Some (l2, l3)) ->\n                                          l2 = [] \\/ PegMatch (Concat P (PossesiveStar P)) l1 (Some (l2, l3)).\n    intros P l1 l2 l3 H.\n    inversion H.\n    {\n      left.\n      reflexivity.\n    }\n    {\n      right.\n      subst.\n      eapply CatS.\n      {\n        exact H4.\n      }\n      {\n        exact H5.\n      }\n    }\n  Qed.\n\n  Lemma StarImpliesRemainderFailStrong : forall p, forall l1 o,\n      PegMatch p l1 o ->\n      forall P l2 l3,\n      p = PossesiveStar P ->\n      o = Some (l2, l3) ->\n      PegMatch P l3 None.\n    intros P l1 o H.\n    induction H; try discriminate.\n    {\n      intros P l1 l2 HPeq HOeq.\n      inversion HPeq.\n      inversion HOeq.\n      subst.\n      assumption.\n    }\n    {\n      intros P l6 l7 HPeq HOeq.\n      inversion HPeq.\n      inversion HOeq.\n      subst.\n      now eapply IHPegMatch2.\n    }\n    Qed.\n\n    Lemma StarImpliesRemainderFail :\n      forall P l1 l2 l3, PegMatch (PossesiveStar P) l1 (Some (l2, l3)) ->\n                    PegMatch P l3 None.\n      intros P l1 l2 l3 H.\n      eauto using StarImpliesRemainderFailStrong.\n      Qed.\n\n    Definition WeakenMatch (P : PEG) (l1 l2 l3 : list Σ) :=\n      PegMatch P (l1 ++ l2) (Some (l1, l2)) ->\n      PegMatch P (l1 ++ l2 ++ l3) (Some (l1, l2 ++ l3)).\n\n    Definition WeakenFail (P : PEG) (l1 l2 : list Σ) :=\n      PegMatch P l1 None -> PegMatch P (l1 ++ l2) None.\n\n    Definition StarWillFailPrefixes (p : PEG) := forall l o, PegMatch (PossesiveStar p) l o ->\n                                                        forall l1 l2, o = Some (l1, l2) -> forall l3 l4, l3 ++ l4 = l2 -> (l3 = [] \\/ PegMatch p l3 None).\n\n    Definition BlameConcatenee (P : PEG) (l1 l2 l3: list Σ) :=\n      forall P', PegMatch P l1 (Some (l2, l3)) -> PegMatch (Concat P P') l1 None ->\n            PegMatch P' l3 None.\n\n    Definition WeakenStar (P : PEG) (l1 l2 l3 : list Σ) :=\n      PegMatch (PossesiveStar P) (l1 ++ l2) (Some (l1, l2)) ->\n        PegMatch (PossesiveStar P) (l1 ++ l2 ++ l3) (Some (l1, l2 ++ l3)).\n\n    Lemma catnil : forall T, forall l1 l2 : list T, [] = l1 ++ l2 -> l1 = [].\n      intros T l1.\n      induction l1; try eauto.\n      intros l2 H.\n      inversion H.\n    Qed.\n\n\n    Fixpoint foldl {T O} (l : list T) (f : T -> O -> O) (z : O) : O :=\n      match l with\n      | [] => z\n      | h :: t => f h (foldl t f z)\n      end.\n\n\n    Lemma StarWeakenBaseStrong1 : forall p l o,\n        PegMatch p l o ->\n        forall l1 l2 l3 c,\n          p = (PossesiveStar (Char c)) -> l = l1 ++ l2 -> o = (Some (l1, l2)) ->\n          PegMatch p (l1 ++ l2 ++ l3) (Some (l1, l2 ++ l3)).\n      intros p l o m.\n      induction m; try discriminate.\n      {\n        intros l1 l2 l3 c Heq1 Heq2 H.\n        inversion H. inversion Heq2. inversion Heq1. subst.\n        constructor.\n        simpl in m.\n        inversion m.\n        subst.\n        now constructor.\n      }\n      {\n        intros l6 l7 l8 c Heq1 Heq2 H.\n        inversion H.\n        inversion Heq1.\n        inversion Heq2.\n        subst.\n        rewrite <- app_assoc.\n        rewrite <- app_assoc in m1.\n        inversion m1.\n        subst.\n        eapply StarRec.\n        {\n          constructor.\n        }\n        {\n          eapply IHm2.\n          reflexivity.\n          apply list_split in m2.\n          assumption.\n          reflexivity.\n        }\n      }\n    Qed.\n\n    Lemma StarWeakenBase1 : forall l1 l2 l3 c,\n        PegMatch (PossesiveStar (Char c)) (l1 ++ l2) (Some (l1, l2)) ->\n        PegMatch (PossesiveStar (Char c)) (l1 ++ l2 ++ l3) (Some (l1, l2 ++ l3)).\n      eauto using StarWeakenBaseStrong1.\n    Qed.\n\n    Lemma taileq : forall {T}, forall l1 l2 l3 : list T, l1 ++ l2 = l1 ++ l3 -> l2 = l3.\n      intros T l1.\n      induction l1; try eauto.\n      intros l2 l3 H.\n      simpl in H.\n      inversion H.\n      now apply IHl1.\n    Qed.\n\n    Lemma StarWeakenConcatStrong :\n      forall p l o, PegMatch p l o ->\n               forall P1 P2 l1 l2 l3 l4, p = (PossesiveStar (Concat P1 P2)) -> l = l1 -> o = (Some (l2, l3)) ->\n                                    (forall l4 l5 l6, WeakenMatch (Concat P1 P2) l4 l5 l6 /\\ WeakenFail (Concat P1 P2) l4 l5) -> PegMatch p (l1 ++ l4) (Some (l2, l3 ++ l4)).\n      intros p l o m.\n      induction m; try discriminate.\n      {\n        intros P1 P2 l1 l2 l3 l4 Heq1 Heq2 Heq3 HWeaken.\n        inversion Heq1.\n        inversion Heq2.\n        inversion Heq3.\n        subst.\n        apply StarEnd.\n        assert (WeakenFail (Concat P1 P2) l3 l4) by (apply HWeaken; exact []).\n        unfold WeakenFail in H0.\n        now apply H0.\n      }\n      {\n        intros P1 P2 l6 l7 l8 l9 Heq1 Heq2 Heq3 HWeaken.\n        inversion Heq1.\n        inversion Heq2.\n        inversion Heq3.\n        subst.\n        apply list_split in m1 as HLS.\n        subst l6.\n        assert (PegMatch (Concat P1 P2) (l1 ++ l2 ++ l9) (Some (l1, l2 ++ l9))).\n        {\n          assert (WeakenMatch (Concat P1 P2) l1 l2 l9) by (apply HWeaken; exact []).\n          unfold WeakenMatch in H0.\n          now apply H0.\n        }\n        assert (PegMatch (PossesiveStar (Concat P1 P2)) (l2 ++ l9) (Some (l3, l8 ++ l9))) by (eapply IHm2; eauto).\n        rewrite <- app_assoc.\n        econstructor. { exact H0. } { exact H1.}\n      }\n    Qed.\n\n    Lemma StarWeakenOrderedChoiceStrong :\n      forall p l o, PegMatch p l o ->\n               forall P1 P2 l1 l2 l3 l4, p = (PossesiveStar (OrderedChoice P1 P2)) -> l = l1 -> o = (Some (l2, l3)) ->\n                                    (forall l4 l5 l6, WeakenMatch (OrderedChoice P1 P2) l4 l5 l6 /\\ WeakenFail (OrderedChoice P1 P2) l4 l5) -> PegMatch p (l1 ++ l4) (Some (l2, l3 ++ l4)).\n      intros p l o m.\n      induction m; try discriminate.\n      {\n        intros P1 P2 l1 l2 l3 l4 Heq1 Heq2 Heq3 HWeaken.\n        inversion Heq1.\n        inversion Heq2.\n        inversion Heq3.\n        subst.\n        apply StarEnd.\n        assert (WeakenFail (OrderedChoice P1 P2) l3 l4) by (apply HWeaken; exact []).\n        unfold WeakenFail in H0.\n        now apply H0.\n      }\n      {\n        intros P1 P2 l5 l6 l7 l8 Heq1 Heq2 Heq3 HWeaken.\n        inversion Heq1.\n        inversion Heq2.\n        inversion Heq3.\n        subst.\n        apply list_split in m1 as HLS.\n        subst l5.\n        assert (PegMatch (OrderedChoice P1 P2) (l1 ++ l2 ++ l8) (Some (l1, l2 ++ l8))).\n        {\n          assert (WeakenMatch (OrderedChoice P1 P2) l1 l2 l8) by (apply HWeaken; exact []).\n          unfold WeakenMatch in H0.\n          now apply H0.\n        }\n        assert (PegMatch (PossesiveStar (OrderedChoice P1 P2)) (l2 ++ l8) (Some (l3, l7 ++ l8))) by (eapply IHm2; eauto).\n        rewrite <- app_assoc.\n        econstructor. { exact H0. } { exact H1.}\n      }\n    Qed.\n\n    Lemma StarWeakenOrderedChoice : forall P1 P2 l1 l2 l3, (forall l4 l5 l6, WeakenMatch (OrderedChoice P1 P2) l4 l5 l6 /\\ WeakenFail (OrderedChoice P1 P2) l4 l5) -> WeakenStar (OrderedChoice P1 P2) l1 l2 l3.\n      intros P1 P2 l1 l2 l3 H1 H2.\n      remember (PossesiveStar (OrderedChoice P1 P2)).\n      remember (l1 ++ l2).\n      rewrite app_assoc.\n      remember (Some (l1, l2)).\n      eapply StarWeakenOrderedChoiceStrong; eauto.\n    Qed.\n\n    Lemma StarWeakenConcat : forall P1 P2 l1 l2 l3, (forall l4 l5 l6, WeakenMatch (Concat P1 P2) l4 l5 l6 /\\ WeakenFail (Concat P1 P2) l4 l5) -> WeakenStar (Concat P1 P2) l1 l2 l3.\n      intros P1 P2 l1 l2 l3 H1 H2.\n      remember (PossesiveStar (Concat P1 P2)).\n      remember (l1 ++ l2).\n      rewrite app_assoc.\n      remember (Some (l1, l2)).\n      eapply StarWeakenConcatStrong; eauto.\n    Qed.\n\n    Lemma MatchDeterministic :\n      forall p l o, PegMatch p l o -> forall o', PegMatch p l o' -> o' = o.\n      intros p l o m.\n      induction m.\n      {\n        intros o' H.\n        inversion H.\n        {\n          subst.\n          reflexivity.\n        }\n        {\n          subst.\n          now apply eq_dec_correct in H4.\n        }\n      }\n      {\n        intros o' H'.\n        inversion H'.\n        {\n          subst.\n          apply eq_dec_correct in H.\n          contradiction.\n        }\n        {\n          reflexivity.\n        }\n      }\n      {\n        intros o' H2.\n        inversion H2.\n        {\n          subst.\n          assert (Some (l6, l7) = Some (l1, l2)).\n          {\n            now apply IHm1.\n          }\n          assert (Some (l8, l9) = Some (l3, l4)).\n          {\n            apply IHm2.\n            inversion H.\n            subst.\n            assumption.\n          }\n          inversion H.\n          inversion H0.\n          subst.\n          reflexivity.\n        }\n        {\n          subst.\n          assert (None = Some (l1, l2)).\n          {\n            now apply IHm1.\n          }\n          inversion H.\n        }\n        {\n          subst.\n          assert (Some (l6, l7) = Some (l1, l2)); eauto.\n          inversion H.\n          subst.\n          assert (None = (Some (l3, l4))); eauto using IHm2.\n          inversion H0.\n        }\n      }\n      {\n        intros o H1.\n        inversion H1; try eauto.\n        subst.\n        assert (Some (l1, l2) = None); eauto.\n        inversion H.\n      }\n      {\n        intros o H1.\n        inversion H1; try eauto.\n        subst.\n        assert (Some (l4, l5) = Some (l1, l2)); eauto.\n        inversion H.\n        subst.\n        assert (Some (l6, l7) = None); eauto.\n        inversion H0.\n      }\n      {\n        intros o H1.\n        inversion H1.\n        {\n          subst.\n          eapply IHm.\n          exact H4.\n        }\n        {\n          subst.\n          assert (None = (Some (l1, l2))) by (apply IHm; assumption).\n          inversion H.\n        }\n        {\n          subst.\n          assert (None = (Some (l1, l2))) by (apply IHm; assumption).\n          inversion H.\n        }\n      }\n      {\n        intros o H1.\n        inversion H1; try eauto.\n        subst.\n        assert (Some (l4, l5) = None); eauto.\n        inversion H.\n      }\n      {\n        intros o H1.\n        inversion H1.\n        {\n          subst.\n          now eapply IHm1.\n        }\n        {\n          subst.\n          now eapply IHm2.\n        }\n        {\n          reflexivity.\n        }\n      }\n      {\n        intros o' H.\n        inversion H.\n        {\n          subst.\n          reflexivity.\n        }\n        {\n          subst.\n          assert (Some (l1, l2) = None) by eauto.\n          inversion H0.\n        }\n      }\n      {\n        intros o H.\n        inversion H; subst.\n        {\n          now assert (None = Some (l1, l2)) by eauto.\n        }\n        {\n          assert (Some (l6, l7) = Some (l1, l2)) by eauto.\n          inversion H0.\n          subst.\n          assert (Some (l8, l9) = Some (l3, l4)) by eauto.\n          now inversion H3.\n        }\n      }\n    Qed.\n\n    Lemma StarStarNeverStrong : forall p l o, PegMatch p l o -> forall p', p = (PossesiveStar (PossesiveStar p')) -> False.\n      intros P l o H.\n      induction H; try discriminate.\n      {\n        intros p' Heq.\n        inversion Heq.\n        subst.\n        inversion H.\n      }\n      {\n        intros p' Heq.\n        inversion Heq.\n        subst.\n        eapply IHPegMatch2.\n        reflexivity.\n      }\n    Qed.\n\n    Lemma StarStarNever : forall p l o, PegMatch (PossesiveStar (PossesiveStar p)) l o -> False.\n      eauto using StarStarNeverStrong.\n      Qed.\n\n    Lemma MatchWeakenStrong : forall P l1 l2 l3, WeakenMatch P l1 l2 l3 /\\ WeakenFail P l1 l2 /\\ BlameConcatenee P l1 l2 l3 /\\ ((forall l4 l5 l6, WeakenMatch P l4 l5 l6 /\\ WeakenFail P l4 l5) -> WeakenStar P l1 l2 l3).\n      intros P.\n      induction P.\n      {\n        intros l1 l2 l3.\n        repeat split.\n        (* { *)\n        (*   intros H. *)\n        (*   inversion H. *)\n        (*   subst. *)\n        (*   constructor. *)\n        (* } *)\n        {\n          intros H.\n          inversion H.\n          subst.\n          apply CharS.\n        }\n        {\n          intros H.\n          inversion H.\n          {\n            subst.\n            now constructor.\n          }\n        }\n        {\n          unfold BlameConcatenee.\n          intros P' H1 H2.\n          inversion H1.\n          subst.\n          inversion H2.\n          {\n            subst.\n            inversion H4.\n            subst.\n            apply eq_dec_correct in H3.\n            contradiction.\n          }\n          {\n            subst.\n            inversion H3.\n            now subst.\n          }\n        }\n        {\n          intros H.\n          unfold WeakenStar.\n          apply StarWeakenBase1.\n        }\n      }\n      {\n        intros l1 l2 l3.\n        repeat split.\n        (* { *)\n        (*   intros H. *)\n        (*   inversion H. *)\n        (*   subst. *)\n        (*   eapply CatS. *)\n        (*   { *)\n        (*     rewrite <- app_assoc. *)\n        (*     apply IHP1 with (l3 := l3). *)\n        (*     replace (l4 ++ (l6 ++ l2) ++ l3) with ((l4 ++ l6) ++ l2 ++ l3). *)\n        (*     2: { *)\n        (*       rewrite <- app_assoc. *)\n        (*       symmetry. *)\n        (*       now rewrite <- app_assoc. *)\n        (*     } *)\n        (*     assert (l5 = (l6 ++ l2) ++ l3) by (apply list_split in H6; rewrite <- app_assoc; assumption). *)\n        (*     rewrite H0 in H4. *)\n        (*     assumption. *)\n        (*   } *)\n        (*   { *)\n        (*     apply IHP2 with (l3 := l3). *)\n        (*     apply list_split in H6 as HLS. *)\n        (*     now rewrite HLS in H6. *)\n        (*   } *)\n        (* } *)\n        {\n          intros H.\n          inversion H.\n          subst.\n          apply list_split in H6 as HLS.\n          rewrite HLS in H6.\n          assert (WeakenMatch P2 l6 l2 l3) by apply IHP2.\n          unfold WeakenMatch in H0.\n          apply H0 in H6.\n          rewrite <- app_assoc in H4.\n          rewrite app_assoc in H4.\n          apply list_split in H4 as HLS1.\n          rewrite HLS1 in H4.\n          assert (WeakenMatch P1 l4 l5 l3) by apply IHP1.\n          unfold WeakenMatch in H1.\n          apply H1 in H4.\n          rewrite HLS in H4.\n          rewrite <- app_assoc in H4.\n          rewrite <- app_assoc.\n          eapply CatS.\n          exact H4.\n          exact H6.\n        }\n        {\n          unfold WeakenFail.\n          intros H.\n          inversion H.\n          {\n            subst.\n            assert (WeakenFail P1 l1 l2) by (apply IHP1; exact []).\n            unfold WeakenFail in H0.\n            eapply CatFail1.\n            now apply H0.\n          }\n          {\n            subst.\n            assert (BlameConcatenee P1 l1 l4 l5) by (apply IHP1).\n            unfold BlameConcatenee in H0.\n            apply list_split in H2 as HLS. subst l1.\n            assert (WeakenMatch P1 l4 l5 l2) by apply IHP1.\n            unfold WeakenMatch in H1.\n            apply H1 in H2.\n            assert (WeakenFail P2 l5 l2) by (apply IHP2; exact []).\n            unfold WeakenFail in H3.\n            assert (PegMatch P2 (l5 ++ l2) None) by auto.\n            eapply CatFail2.\n            rewrite <- app_assoc.\n            exact H2.\n            exact H5.\n          }\n        }\n        {\n          unfold BlameConcatenee.\n          intros P' H1 H2.\n          inversion H1.\n          subst.\n          apply ConcatDistrEquivalentFail in H2 as HFail.\n          apply list_split in H1 as HLS.\n          assert (BlameConcatenee P1 l1 l4 l5) by apply IHP1.\n          unfold BlameConcatenee in H.\n          assert (PegMatch (Concat P2 P') l5 None) by eauto.\n          assert (BlameConcatenee P2 l5 l6 l3) by apply IHP2.\n          unfold BlameConcatenee in H3.\n          now apply H3.\n        }\n        {\n          apply StarWeakenConcat.\n        }\n      }\n      {\n        intros l1 l2 l3.\n        repeat split.\n        {\n          unfold WeakenMatch.\n          intros H.\n          assert (WeakenStar P l1 l2 l3).\n          {\n            apply IHP.\n            split.\n            apply IHP.\n            apply IHP.\n            exact [].\n          }\n          eauto.\n        }\n        {\n          intros H.\n          inversion H.\n        }\n        {\n          unfold BlameConcatenee.\n          intros P' H1 H2.\n          inversion H2.\n          {\n            subst.\n            assert (Some (l2, l3) = None); eauto using MatchDeterministic.\n            discriminate.\n          }\n          {\n            subst.\n            assert (Some (l2, l3) = Some (l4, l5)); eauto using MatchDeterministic.\n            inversion H.\n            assumption.\n          }\n        }\n        {\n          intros H1 H2.\n          apply StarStarNever in H2.\n          contradiction.\n        }\n      }\n      {\n        intros l1 l2 l3.\n        repeat split.\n        {\n          intros H.\n          inversion H.\n          {\n            subst.\n            assert (WeakenMatch P1 l1 l2 l3) by apply IHP1.\n            eauto using PegMatch.\n          }\n          {\n            subst.\n            assert (WeakenMatch P2 l1 l2 l3) by apply IHP2.\n            assert (WeakenFail P1 (l1 ++ l2) l3) by (apply IHP1; exact []).\n            unfold WeakenMatch in H0.\n            unfold WeakenFail in H1.\n            assert (PegMatch P1 ((l1 ++ l2) ++ l3) None) by eauto.\n            rewrite <- app_assoc in H2.\n            eapply ChoiceR; eauto.\n          }\n        }\n        {\n          intros H.\n          inversion H.\n          {\n            subst.\n            assert (WeakenFail P1 l1 l2) by (apply IHP1; exact []).\n            assert (WeakenFail P2 l1 l2) by (apply IHP2; exact []).\n            unfold WeakenFail in H0.\n            unfold WeakenFail in H1.\n            constructor. { now apply H0. } { now apply H1. }\n          }\n        }\n        {\n          intros P H1 H2.\n          inversion H2.\n          {\n            subst.\n            assert (None = (Some (l2, l3))); eauto using MatchDeterministic.\n            discriminate.\n          }\n          {\n            subst.\n            assert (Some (l2, l3) = Some (l4, l5)); eauto using MatchDeterministic.\n            now inversion H.\n          }\n        }\n        {\n          intros H1 H2.\n          apply StarWeakenOrderedChoice.\n          {\n            intros l4 l5 l6. split. apply H1. apply H1. exact [].\n          }\n          {\n            exact H2.\n          }\n        }\n      }\n    Qed.\n\n    Lemma MatchWeaken' : forall P l1 l2 l3, WeakenMatch P l1 l2 l3 /\\ WeakenFail P l1 l2 /\\ BlameConcatenee P l1 l2 l3.\n      intros P l1 l2 l3.\n      repeat split.\n      {\n        eapply MatchWeakenStrong.\n      }\n      {\n        eapply MatchWeakenStrong. exact [].\n      }\n      {\n        eapply MatchWeakenStrong.\n      }\n    Qed.\n\n    Lemma MatchWeaken : forall P l1 l2 l3, WeakenMatch P l1 l2 l3 /\\ WeakenFail P l1 l2.\n      intros P l1 l2 l3.\n      repeat split; try eapply MatchWeaken'.\n      exact [].\n      Qed.\n\n    Definition DoesNotMatch (P : PEG) (l : list Σ) := (forall l1 l2, PegMatch P l (Some (l1, l2)) -> False).\n\n    Definition PPartial (p : PEG) := forall l o, PegMatch p l o -> forall o', PegMatch p l o' -> o = o'.\n\n    Lemma PPartialStar : forall p l o, PegMatch p l o -> forall p', p = PossesiveStar p' -> PPartial p' -> forall o', PegMatch p l o' -> o = o'.\n      intros p l o m.\n      induction m; try discriminate.\n      {\n        intros p' Heq HPartial o' m'.\n        inversion Heq. subst p'.\n        destruct o' eqn:eqo.\n        {\n          inversion m'. { reflexivity. } { subst. assert (Some (l1, l2) = None) by eauto. discriminate. }\n        }\n        {\n          inversion m'.\n        }\n      }\n      {\n        intros p' Heqp Hpartial o' m'.\n        inversion Heqp.\n        subst p'.\n        destruct o' eqn:eqo.\n        {\n          inversion m'.\n          {\n            subst.\n            assert (None = Some (l1, l2)) by eauto.\n            discriminate.\n          }\n          {\n            subst.\n            assert (Some (l6, l7) = Some (l1, l2)) by eauto.\n            inversion H.\n            subst.\n            assert (Some (l3, l4) = Some (l8, l9)). { eapply IHm2. exact Heqp. exact Hpartial. exact H3. }\n            now inversion H0.\n          }\n        }\n        {\n          inversion m'.\n        }\n      }\n    Qed.\n\n    Lemma PegPartialFunctionStrong: forall p, PPartial p.\n      intros p.\n      induction p.\n      {\n        intros l o m1 o' m2.\n        destruct o; destruct o'; try reflexivity.\n        {\n          inversion m1. inversion m2.\n          subst.\n          now inversion H2.\n        }\n        {\n          inversion m1. inversion m2.\n          subst. inversion H4. subst. now apply eq_dec_correct in H3.\n        }\n        {\n          inversion m1. inversion m2.\n          subst. inversion H2. subst. now apply eq_dec_correct in H0.\n        }\n      }\n      {\n        intros l o m1 o' m2.\n        destruct o; destruct o'; try reflexivity.\n        {\n          inversion m1. inversion m2.\n          subst.\n          assert (Some (l1, l2) = Some (l6, l7)) by eauto.\n          inversion H.\n          subst l7. subst l6.\n          assert (Some (l3, l4) = Some (l8, l9)) by eauto.\n          inversion H0. subst l9. subst l8.\n          reflexivity.\n        }\n        {\n          inversion m2.\n          { inversion m1. subst. assert (Some (l2, l3) = None) by eauto. discriminate. }\n          { inversion m1. subst. assert (Some (l1, l2) = Some (l4, l5)) by eauto. inversion H. subst. assert (Some (l6, l7) = None) by eauto. discriminate. }\n        }\n        {\n          inversion m1.\n          { inversion m2. subst. assert (Some (l2, l3) = None) by eauto. discriminate. }\n          { inversion m2. subst. assert (Some (l1, l2) = Some (l4, l5)) by eauto. inversion H. subst. assert (Some (l6, l7) = None) by eauto. discriminate. }\n        }\n      }\n      {\n        intros l o m1 o' m2.\n        eauto using PPartialStar.\n      }\n      {\n        intros l o m1 o' m2.\n        destruct o; destruct o'; try reflexivity.\n        {\n          inversion m1.\n          {\n            inversion m2.\n            {\n              eauto.\n            }\n            {\n              assert (Some (l1, l2) = None) by eauto.\n              discriminate.\n            }\n          }\n          {\n            inversion m2.\n            {\n              assert (None = Some (l4, l5)) by eauto.\n              discriminate.\n            }\n            {\n              eauto.\n            }\n          }\n        }\n        {\n          inversion m2.\n          subst.\n          inversion m1; subst; assert (Some (l1, l2) = None) by eauto; discriminate.\n        }\n        {\n          inversion m1.\n          subst.\n          inversion m2; subst; assert (Some (l1, l2) = None) by eauto; discriminate.\n        }\n      }\n    Qed.\n\n\n    Theorem PegPartial : forall p l o, PegMatch p l o -> forall o', PegMatch p l o' -> o = o'.\n      intros p.\n      assert (PPartial p) by eauto using PegPartialFunctionStrong.\n      eauto using PegPartialFunctionStrong.\n    Qed.\n\n    Definition StrengthenFail (P : PEG) (l1 l2 : list Σ) :=  DoesNotMatch P (l1 ++ l2) -> DoesNotMatch P l1.\n\n    Lemma splitcases : forall T, forall (l1 l2 l3 l4 : list T), l1 ++ l2 = l3 ++ l4 ->\n                                                      ((exists restl3, (l1 ++ restl3) = l3 /\\ restl3 ++ l4 = l2) \\/ (exists begl4, l3 ++ begl4 = l1 /\\ begl4 ++ l2 = l4)).\n      intros T l1.\n      induction l1.\n      {\n        intros l2 l3 l4 H.\n        simpl in H.\n        simpl.\n        left.\n        exists l3; split; symmetry; auto.\n      }\n      {\n        intros l2 l3 l4 H.\n        destruct l3.\n        {\n          destruct l4. { simpl in H. inversion H. }\n          simpl in H.\n          inversion H.\n          assert (l1 ++ l2 = [] ++ l4) by auto.\n          assert ((exists restl3 : list T, l1 ++ restl3 = [] /\\ restl3 ++ l4 = l2) \\/ (exists begl4 : list T, [] ++ begl4 = l1 /\\ begl4 ++ l2 = l4)) by auto.\n          inversion H3.\n          {\n            inversion H4.\n            inversion H5.\n            subst.\n            right.\n            exists (t :: l1). split. { reflexivity. } { simpl. reflexivity. }\n          }\n          {\n            inversion H4.\n            inversion H5.\n            right.\n            subst.\n            simpl.\n            exists (t :: x); auto.\n          }\n        }\n        {\n          simpl in H.\n          inversion H.\n          subst.\n          assert ((exists restl3 : list T, l1 ++ restl3 = l3 /\\ restl3 ++ l4 = l2) \\/ (exists begl4 : list T, l3 ++ begl4 = l1 /\\ begl4 ++ l2 = l4)) by auto.\n          inversion H0.\n          {\n            inversion H1.\n            inversion H3.\n            subst.\n            left.\n            exists x; auto.\n          }\n          {\n            inversion H1.\n            inversion H3.\n            subst.\n            right.\n            exists x; auto.\n          }\n        }\n      }\n    Qed.\n\n    Theorem MatchStrengthen : forall P l1 l2, StrengthenFail P l1 l2.\n      intros p l1 l2.\n      hnf. intros H'.\n      hnf. hnf in H'.\n      assert (forall o, PegMatch p l1 o \\/ ~ (PegMatch p l1 o)).\n      {\n        intros o.\n        eapply lem.\n      }\n      assert (PegMatch p l1 None \\/ ~ PegMatch p l1 None) by eauto.\n      inversion H0.\n      {\n        intros l0 l3 H''.\n        assert (Some (l0, l3) = None) by eauto using PegPartial.\n        discriminate.\n      }\n      {\n        intros l1' l2' H''.\n        apply H' with (l1 := l1') (l2 := l2' ++ l2).\n        eapply list_split in H'' as HLS1.\n        assert (PegMatch p (l1' ++ l2') (Some (l1', l2'))) by (rewrite <- HLS1; assumption).\n        assert (WeakenMatch p l1' l2' l2). { eapply MatchWeaken. }\n        hnf in H3.\n        rewrite app_assoc in H3.\n        repeat rewrite <- HLS1 in H3.\n        now eapply H3.\n      }\n    Qed.\n\n  Lemma allmatch_eq : forall p : PEG, forall l1 l2 : list Σ, PegMatch p l1 (Some (l2, [])) -> l1 = l2.\n    - intros p l1 l2 m.\n      apply list_split in m.\n      now rewrite <- app_nil_r.\n      Qed.\n\n  Inductive REG : Type :=\n  | REmp\n  | RChar (c : Σ)\n  | RConcat (r1 : REG) (r2 : REG)\n  | RUnion (r1 : REG) (r2 : REG)\n  | RStar (r : REG)\n  | RIntersection (r1 : REG) (r2 : REG)\n  | RNeg (r1 : REG).\n\n  Inductive RegMatch : REG -> list Σ -> bool -> Prop :=\n  | REmpS : RegMatch REmp [] true\n  | REmpF : forall c, forall t : list Σ, RegMatch REmp (c :: t) false\n  | RCharS : forall c : Σ, RegMatch (RChar c) [c] true\n  | RCharFEmp : forall c : Σ, RegMatch (RChar c) [] false\n  | RCharF1 : forall c1 c2 : Σ, forall t, (eq_dec c1 c2) = false -> RegMatch (RChar c1) (c2 :: t) false\n  | RCharF2 : forall c c1 c2, forall t, RegMatch (RChar c) (c1 :: c2 :: t) false\n  | RConcatS : forall l1 l2 : list Σ, forall r1 r2 : REG, RegMatch r1 l1 true -> RegMatch r2 l2 true -> RegMatch (RConcat r1 r2) (l1 ++ l2) true\n  | RConcatF r1 r2 : forall l : list Σ,\n      (forall l1' l1'', l1' ++ l1'' = l -> (RegMatch r1 l1' false) \\/ (RegMatch r1 l1' true /\\ RegMatch r2 l1'' false)) ->\n                                            RegMatch (RConcat r1 r2) l false\n  | RUnionSL : forall l1 : list Σ, forall r1 r2 : REG, RegMatch r1 l1 true -> RegMatch (RUnion r1 r2) l1 true\n  | RUnionSR : forall l1 : list Σ, forall r1 r2 : REG, RegMatch r2 l1 true -> RegMatch (RUnion r1 r2) l1 true\n  | RUnionF r1 r2 : forall l1 : list Σ, RegMatch r1 l1 false -> RegMatch r2 l1 false -> RegMatch (RUnion r1 r2) l1 false\n  | RStarS r1 : forall l, (exists l', List.concat l' = l /\\ Forall (fun l => RegMatch r1 l true) l') -> RegMatch (RStar r1) l true\n  | RStarF r1 : forall l, (forall l', List.concat l' = l -> (exists e, In e l' /\\ RegMatch r1 e false)) -> RegMatch (RStar r1) l false\n  | RIntersectionS : forall l : list Σ, forall r1 r2 : REG, RegMatch r1 l true -> RegMatch r2 l true -> RegMatch (RIntersection r1 r2) l true\n  | RIntersectionFL r1 r2 : forall l : list Σ, RegMatch r1 l false -> RegMatch (RIntersection r1 r2) l false\n  | RIntersectionFR r1 r2 : forall l : list Σ, RegMatch r2 l false -> RegMatch (RIntersection r1 r2) l false\n  | RNegS : forall l : list Σ, forall r : REG, RegMatch r l true -> RegMatch (RNeg r) l false\n  | RNegF : forall l : list Σ, forall r : REG, RegMatch r l false -> RegMatch (RNeg r) l true.\n\n  Definition RDeterministic (r : REG) := forall l b, RegMatch r l b -> forall b', RegMatch r l b' -> b = b'.\n\n  Definition RStarDeterministic (r : REG) := forall l b, RegMatch (RStar r) l b -> forall b', RegMatch (RStar r) l b' -> b = b'.\n\n  Lemma ConcatFactor : forall {T}, forall l (l1 : list T) a, concat (a :: l) = l1 -> l1 = a ++ (concat l).\n    intros T l.\n    induction l.\n    {\n      intros l1 a H.\n      inversion H.\n      simpl.\n      reflexivity.\n    }\n    {\n      intros l1 a1 H.\n      simpl in H.\n      simpl.\n      now symmetry.\n    }\n  Qed.\n\n  Lemma InImpliesAll : forall T, forall l : list T, forall x (P : T -> Prop), In x l -> Forall P l -> P x.\n    intros T l.\n    induction l.\n    {\n      intros x P H1 H2.\n      inversion H1.\n    }\n    {\n      intros x P H1 H2.\n      inversion H1.\n      {\n        subst x.\n        now inversion H2.\n      }\n      {\n        inversion H2.\n        subst.\n        eapply IHl; eauto.\n      }\n    }\n    Qed.\n\n  Lemma REmpStarImpossibleCaseStrong : RDeterministic REmp ->\n                                       forall l, ((exists l', concat l' = l /\\ Forall (fun l : list Σ => RegMatch REmp l true) l') /\\ (forall l', concat l' = l -> exists e : list Σ, In e l' /\\ RegMatch REmp e false)) -> False.\n    intros RDet l.\n    destruct l.\n    {\n      intros HImp.\n      inversion HImp.\n      assert (exists e : list Σ, In e [] /\\ RegMatch REmp e false) by eauto.\n      inversion H1.\n      inversion H2.\n      inversion H3.\n    }\n    {\n      intros HImp.\n      inversion HImp.\n      inversion H.\n      inversion H1.\n      assert (exists e : list Σ, In e x /\\ RegMatch REmp e false) by eauto.\n      inversion H4.\n      inversion H5.\n      inversion H7.\n      subst x0.\n      inversion H5.\n      assert (RegMatch REmp (c :: t) true). { eapply InImpliesAll with (x := (c :: t)). exact H8. exact H3. }\n      eauto.\n    }\n    Qed.\n\n  Lemma RCharStarImpossibleCaseStrong : forall c, RDeterministic (RChar c) ->\n                                       forall l, ((exists l', concat l' = l /\\ Forall (fun l : list Σ => RegMatch (RChar c) l true) l') /\\ (forall l', concat l' = l -> exists e : list Σ, In e l' /\\ RegMatch (RChar c) e false)) -> False.\n    intros c RDet l.\n    destruct l.\n    {\n      intros HImp.\n      inversion HImp.\n      assert (exists e : list Σ, In e [] /\\ RegMatch (RChar c) e false) by eauto.\n      inversion H1.\n      inversion H2.\n      inversion H3.\n    }\n    {\n      intros HImp.\n      inversion HImp.\n      inversion H.\n      inversion H1.\n      assert (exists e, In e x /\\ RegMatch (RChar c) e false); eauto.\n      inversion H4.\n      inversion H5.\n      assert (RegMatch (RChar c) x0 true). { eapply InImpliesAll with (x := x0). exact H6. exact H3. }\n      eauto.\n    }\n    Qed.\n\n  Lemma RConcatImpossibleCaseStrong : forall r1 r2, RDeterministic (RConcat r1 r2) ->\n                                               forall l, ((exists l', concat l' = l /\\ Forall (fun l : list Σ => RegMatch (RConcat r1 r2) l true) l') /\\ (forall l', concat l' = l -> exists e : list Σ, In e l' /\\ RegMatch (RConcat r1 r2) e false)) -> False.\n    intros r1 r2 RDet l.\n    destruct l.\n    {\n      intros HImp.\n      inversion HImp.\n      assert (exists e : list Σ, In e [] /\\ RegMatch (RConcat r1 r2) e false) by eauto.\n      inversion H1.\n      inversion H2.\n      inversion H3.\n    }\n    {\n      intros HImp.\n      inversion HImp.\n      inversion H.\n      inversion H1.\n      assert (exists e, In e x /\\ RegMatch (RConcat r1 r2) e false); eauto.\n      inversion H4.\n      inversion H5.\n      assert (RegMatch (RConcat r1 r2) x0 true). { eapply InImpliesAll with (x := x0). exact H6. exact H3. }\n      eauto.\n    }\n    Qed.\n\n  Lemma RUnionImpossibleCaseStrong : forall r1 r2, RDeterministic (RUnion r1 r2) ->\n                                               forall l, ((exists l', concat l' = l /\\ Forall (fun l : list Σ => RegMatch (RUnion r1 r2) l true) l') /\\ (forall l', concat l' = l -> exists e : list Σ, In e l' /\\ RegMatch (RUnion r1 r2) e false)) -> False.\n    intros r1 r2 RDet l.\n    destruct l.\n    {\n      intros HImp.\n      inversion HImp.\n      assert (exists e : list Σ, In e [] /\\ RegMatch (RUnion r1 r2) e false) by eauto.\n      inversion H1.\n      inversion H2.\n      inversion H3.\n    }\n    {\n      intros HImp.\n      inversion HImp.\n      inversion H.\n      inversion H1.\n      assert (exists e, In e x /\\ RegMatch (RUnion r1 r2) e false); eauto.\n      inversion H4.\n      inversion H5.\n      assert (RegMatch (RUnion r1 r2) x0 true). { eapply InImpliesAll with (x := x0). exact H6. exact H3. }\n      eauto.\n    }\n    Qed.\n\n  Lemma RIntersectionImpossibleCaseStrong : forall r1 r2, RDeterministic (RIntersection r1 r2) ->\n                                               forall l, ((exists l', concat l' = l /\\ Forall (fun l : list Σ => RegMatch (RIntersection r1 r2) l true) l') /\\ (forall l', concat l' = l -> exists e : list Σ, In e l' /\\ RegMatch (RIntersection r1 r2) e false)) -> False.\n    intros r1 r2 RDet l.\n    destruct l.\n    {\n      intros HImp.\n      inversion HImp.\n      assert (exists e : list Σ, In e [] /\\ RegMatch (RIntersection r1 r2) e false) by eauto.\n      inversion H1.\n      inversion H2.\n      inversion H3.\n    }\n    {\n      intros HImp.\n      inversion HImp.\n      inversion H.\n      inversion H1.\n      assert (exists e, In e x /\\ RegMatch (RIntersection r1 r2) e false); eauto.\n      inversion H4.\n      inversion H5.\n      assert (RegMatch (RIntersection r1 r2) x0 true). { eapply InImpliesAll with (x := x0). exact H6. exact H3. }\n      eauto.\n    }\n    Qed.\n\n  Lemma RStarImpossibleCaseStrong : forall r1, RDeterministic (RStar r1) ->\n                                               forall l, ((exists l', concat l' = l /\\ Forall (fun l : list Σ => RegMatch (RStar r1) l true) l') /\\ (forall l', concat l' = l -> exists e : list Σ, In e l' /\\ RegMatch (RStar r1) e false)) -> False.\n    intros r1 RDet l.\n    destruct l.\n    {\n      intros HImp.\n      inversion HImp.\n      assert (exists e : list Σ, In e [] /\\ RegMatch (RStar r1) e false) by eauto.\n      inversion H1.\n      inversion H2.\n      inversion H3.\n    }\n    {\n      intros HImp.\n      inversion HImp.\n      inversion H.\n      inversion H1.\n      assert (exists e, In e x /\\ RegMatch (RStar r1) e false); eauto.\n      inversion H4.\n      inversion H5.\n      assert (RegMatch (RStar r1) x0 true). { eapply InImpliesAll with (x := x0). exact H6. exact H3. }\n      eauto.\n    }\n    Qed.\n\n  Lemma RNegImpossibleCaseStrong : forall r1, RDeterministic (RNeg r1) ->\n                                               forall l, ((exists l', concat l' = l /\\ Forall (fun l : list Σ => RegMatch (RNeg r1) l true) l') /\\ (forall l', concat l' = l -> exists e : list Σ, In e l' /\\ RegMatch (RNeg r1) e false)) -> False.\n    intros r1 RDet l.\n    destruct l.\n    {\n      intros HImp.\n      inversion HImp.\n      assert (exists e : list Σ, In e [] /\\ RegMatch (RNeg r1) e false) by eauto.\n      inversion H1.\n      inversion H2.\n      inversion H3.\n    }\n    {\n      intros HImp.\n      inversion HImp.\n      inversion H.\n      inversion H1.\n      assert (exists e, In e x /\\ RegMatch (RNeg r1) e false); eauto.\n      inversion H4.\n      inversion H5.\n      assert (RegMatch (RNeg r1) x0 true). { eapply InImpliesAll with (x := x0). exact H6. exact H3. }\n      eauto.\n    }\n    Qed.\n\n  Lemma RNegImpossibleCase : forall r1, RDeterministic (RNeg r1) -> forall l, RegMatch (RStar (RNeg r1)) l true -> RegMatch (RStar (RNeg r1)) l false -> False.\n    intros r1 HDet l HTrue HFalse.\n    eapply RNegImpossibleCaseStrong.\n    {\n      exact HDet.\n    }\n    {\n      inversion HTrue.\n      inversion HFalse.\n      repeat split; eauto.\n    }\n    Qed.\n\n  Lemma RStarStarImpossibleCase : forall r1, RDeterministic (RStar r1) -> forall l, RegMatch (RStar (RStar r1)) l true -> RegMatch (RStar (RStar r1)) l false -> False.\n    intros r1 HDet l HTrue HFalse.\n    eapply RStarImpossibleCaseStrong.\n    {\n      exact HDet.\n    }\n    {\n      inversion HTrue.\n      inversion HFalse.\n      repeat split; eauto.\n    }\n    Qed.\n\n  Lemma RConcatStarImpossibleCase : forall r1 r2, RDeterministic (RConcat r1 r2) -> forall l, RegMatch (RStar (RConcat r1 r2)) l true -> RegMatch (RStar (RConcat r1 r2)) l false -> False.\n    intros r1 r2 HDet l HTrue HFalse.\n    eapply RConcatImpossibleCaseStrong.\n    {\n      exact HDet.\n    }\n    {\n      inversion HTrue.\n      inversion HFalse.\n      repeat split; eauto.\n    }\n    Qed.\n\n  Lemma RIntersectionStarImpossibleCase : forall r1 r2, RDeterministic (RIntersection r1 r2) -> forall l, RegMatch (RStar (RIntersection r1 r2)) l true -> RegMatch (RStar (RIntersection r1 r2)) l false -> False.\n    intros r1 r2 HDet l HTrue HFalse.\n    eapply RIntersectionImpossibleCaseStrong.\n    {\n      exact HDet.\n    }\n    {\n      inversion HTrue.\n      inversion HFalse.\n      repeat split; eauto.\n    }\n    Qed.\n\n  Lemma RUnionStarImpossibleCase : forall r1 r2, RDeterministic (RUnion r1 r2) -> forall l, RegMatch (RStar (RUnion r1 r2)) l true -> RegMatch (RStar (RUnion r1 r2)) l false -> False.\n    intros r1 r2 HDet l HTrue HFalse.\n    eapply RUnionImpossibleCaseStrong.\n    {\n      exact HDet.\n    }\n    {\n      inversion HTrue.\n      inversion HFalse.\n      repeat split; eauto.\n    }\n    Qed.\n\n  Lemma RCharStarImpossibleCase : forall c, RDeterministic (RChar c) -> forall l, RegMatch (RStar (RChar c)) l true -> RegMatch (RStar (RChar c)) l false -> False.\n    intros c HDet l HTrue HFalse.\n    eapply RCharStarImpossibleCaseStrong.\n    {\n      exact HDet.\n    }\n    {\n      inversion HTrue.\n      inversion HFalse.\n      repeat split; eauto.\n    }\n    Qed.\n\n  (* By an online source *)\n  Lemma length_nil: forall A:Type, forall l:list A,\n      l = nil <-> length l = 0.\n  Proof.\n    split; intros H.\n    rewrite H; simpl; auto.\n    destruct l. auto.\n    contradict H; simpl.\n    apply sym_not_eq; apply O_S.\n  Qed.\n\n  Lemma LOrder : forall {T}, forall l1 l2 l3 : list T, l1 ++ l2 = l3 -> length l1 <= length l3.\n    intros T l1.\n    induction l1.\n    {\n      intros l2 l3 H.\n      simpl.\n      lia.\n    }\n    {\n      intros l2 l3 H.\n      simpl in H.\n      destruct l3.\n      {\n        inversion H.\n      }\n      {\n        inversion H.\n        simpl.\n        apply le_n_S.\n        rewrite H2.\n        eapply IHl1.\n        exact H2.\n      }\n    }\n    Qed.\n\n  Lemma Reg_Det : forall r, RDeterministic r /\\ (RDeterministic r -> RStarDeterministic r).\n    intros r.\n    induction r.\n    {\n      repeat split.\n      {\n        intros l b H b' H'.\n        inversion H. { inversion H'. { reflexivity. } { subst. inversion H3. }} { subst. inversion H'. reflexivity.  }\n      }\n      {\n        intros Hdet.\n        intros l b Hs b' H'.\n        destruct b; destruct b'; try reflexivity.\n        {\n          inversion Hs.\n          subst.\n          inversion H'.\n          subst.\n          exfalso.\n          eapply REmpStarImpossibleCaseStrong; repeat split; eauto.\n        }\n        {\n          inversion Hs. inversion H'. subst. exfalso. eapply REmpStarImpossibleCaseStrong; repeat split; eauto.\n        }\n      }\n    }\n    {\n      repeat split.\n      {\n        intros l b H b' H'.\n        inversion H.\n        { inversion H'. { reflexivity. } { subst. inversion H3. } { subst. inversion H5. subst. apply eq_dec_correct in H4. contradiction.  } { subst. inversion H3. } }\n        { subst. inversion H'. { reflexivity. } }\n        { subst. inversion H'. { subst. apply eq_dec_correct in H1. contradiction. } { reflexivity. } { reflexivity. } }\n        { subst. inversion H'. { reflexivity. } { reflexivity. } }\n      }\n      {\n        intros HDet l b Hs1 b' Hs2.\n        destruct b; destruct b'; try reflexivity; try (exfalso; eapply RCharStarImpossibleCase; eauto).\n      }\n    }\n    {\n      repeat split.\n      {\n        intros l b H b' H'.\n        inversion IHr1.\n        inversion IHr2.\n        destruct b; destruct b'; try reflexivity; inversion H; inversion H'; subst; assert (RegMatch r1 l1 false \\/ RegMatch r1 l1 true /\\ RegMatch r2 l2 false) by eauto; inversion H4; try eauto; inversion H5; eauto.\n      }\n      {\n        intros H.\n        intros l b HMatch1 b' HMatch2.\n        inversion IHr1.\n        inversion IHr2.\n        destruct b; destruct b'; try reflexivity; exfalso; eauto using RConcatStarImpossibleCase.\n      }\n    }\n    {\n      repeat split.\n      {\n        intros l b H b' H'.\n        inversion IHr1.\n        inversion IHr2.\n        destruct b; destruct b'; try reflexivity; inversion H; inversion H'; eauto.\n      }\n      {\n        intros RUnion.\n        inversion IHr1. inversion IHr2.\n        intros l b HMatch b' HMatch'.\n        destruct b; destruct b'; try reflexivity; exfalso; eauto using RUnionStarImpossibleCase.\n      }\n    }\n    {\n      repeat split.\n      {\n        intros l b H b' H'.\n        inversion IHr.\n        assert (RStarDeterministic r) by eauto.\n        eauto.\n      }\n      {\n        intros H.\n        inversion IHr.\n        intros l b HMatch1 b' HMatch2.\n        destruct b; destruct b'; try reflexivity; exfalso; eauto using RStarStarImpossibleCase.\n      }\n    }\n    {\n      repeat split.\n      {\n        intros l b H b' H'.\n        inversion IHr1.\n        inversion IHr2.\n        destruct b; destruct b'; try reflexivity; inversion H; inversion H'; subst; assert (true = false) by eauto; discriminate.\n      }\n      {\n        intros H.\n        inversion IHr1.\n        inversion IHr2.\n        intros l b HMatch1 b' HMatch2.\n        destruct b; destruct b'; try reflexivity; exfalso; eauto using RIntersectionStarImpossibleCase.\n      }\n    }\n    {\n      repeat split.\n      {\n        intros l b H b' H'.\n        inversion IHr.\n        destruct b; destruct b'; try reflexivity; inversion H; inversion H'; subst; assert (true = false) by eauto; discriminate.\n      }\n      {\n        intros H.\n        inversion IHr.\n        intros l b HMatch1 b' HMatch2.\n        destruct b; destruct b'; try reflexivity; exfalso; eauto using RNegImpossibleCase.\n      }\n    }\n  Qed.\n\n  Theorem reg_det : forall r, RDeterministic r.\n    intros r.\n    assert (forall r0, RDeterministic r0 /\\ (RDeterministic r0 -> RStarDeterministic r0)) by eapply Reg_Det.\n    assert (RDeterministic r /\\ (RDeterministic r -> RStarDeterministic r)) by eauto.\n    now inversion H0.\n  Qed.\n\n  Definition RTotal (r : REG) := forall l, RegMatch r l true \\/ RegMatch r l false.\n\n  Lemma SplitEmpty : forall {T}, forall l1 l2 : list T, l1 ++ l2 = [] -> l1 = [] /\\ l2 = [].\n    intros T l1.\n    induction l1.\n    {\n      intros l2 H.\n      simpl in H.\n      rewrite H.\n      split; reflexivity.\n    }\n    {\n      intros l2 H.\n      simpl in H.\n      inversion H.\n    }\n  Qed.\n\n  Lemma RegCatEquivalence : forall r1 r2 r3 l b, RTotal r1 -> RTotal r2 -> RTotal (RConcat r1 r2) -> RTotal r3 -> RegMatch (RConcat r1 (RConcat r2 r3)) l b -> RegMatch (RConcat (RConcat r1 r2) r3) l b.\n    intros r1 r2 r3 l b HT1 HTCat HT2 HT3 H.\n    destruct b eqn:Eqb.\n    {\n      inversion H.\n      subst.\n      inversion H4.\n      subst.\n      replace (l1 ++ l0 ++ l3) with ((l1 ++ l0) ++ l3) by eauto using app_assoc.\n      constructor. { constructor; assumption. } assumption.\n    }\n    {\n      constructor.\n      intros left1 right1 Heql1.\n      assert (RegMatch (RConcat r1 r2) left1 true \\/ RegMatch (RConcat r1 r2) left1 false) by eauto.\n      inversion H0; try (left; assumption).\n      inversion H1.\n      subst.\n      rename l1 into left2. rename l2 into right2.\n      rewrite <- app_assoc in H.\n      inversion H.\n      subst.\n      assert (RegMatch r1 left2 false \\/ RegMatch r1 left2 true /\\ RegMatch (RConcat r2 r3) (right2 ++ right1) false) by eauto.\n      inversion H2.\n      {\n        assert (RDeterministic r1) by eauto using reg_det.\n        assert (false = true) by eauto.\n        discriminate.\n      }\n      {\n        inversion H3.\n        right. split; try assumption.\n        inversion H8.\n        subst.\n        assert (RegMatch r2 right2 false \\/ RegMatch r2 right2 true /\\ RegMatch r3 right1 false) by eauto.\n        inversion H9; try (inversion H10; assumption).\n        assert (RDeterministic r2) by eauto using reg_det.\n        assert (false = true) by eauto.\n        discriminate.\n      }\n    }\n  Qed.\n\n  Lemma UnionConcatEquivalence : forall r1 r2 , RTotal r1 -> RTotal r2 -> RTotal (RUnion r1 r2) -> forall r0, RTotal r0 -> forall l b, RegMatch (RUnion (RConcat r1 r0) (RConcat r2 r0)) l b -> RegMatch (RConcat (RUnion r1 r2) r0) l b.\n    intros r1 r2 HRT1 HRT2 HRT3 r0 HRT0 l b H.\n    destruct b.\n    {\n      inversion H.\n      {\n        subst.\n        inversion H3.\n        subst.\n        constructor. { eapply RUnionSL. assumption. } { assumption. }\n      }\n      {\n        subst.\n        inversion H3.\n        subst.\n        constructor. { eapply RUnionSR. assumption. } { assumption. }\n      }\n    }\n    {\n      inversion H.\n      subst.\n      inversion H2.\n      subst.\n      inversion H4.\n      subst.\n      constructor.\n      intros left1 right1 Hlr1.\n      assert (RegMatch (RUnion r1 r2) left1 true \\/ RegMatch (RUnion r1 r2) left1 false) by eauto.\n      inversion H0; try (left; assumption).\n      right.\n      split; try assumption.\n      subst l.\n      inversion H1.\n      {\n        subst.\n        assert (RegMatch r1 left1 false \\/ RegMatch r1 left1 true /\\ RegMatch r0 right1 false) by eauto.\n        inversion H3; try (inversion H7; assumption).\n        assert (RDeterministic r1) by eauto using reg_det.\n        assert (false = true) by eauto.\n        discriminate.\n      }\n      {\n        subst.\n        assert (RegMatch r2 left1 false \\/ RegMatch r2 left1 true /\\ RegMatch r0 right1 false) by eauto.\n        inversion H3; try (inversion H7; assumption).\n        assert (RDeterministic r2) by eauto using reg_det.\n        assert (false = true) by eauto.\n        discriminate.\n      }\n    }\n    Qed.\n\n  Lemma RegStarBase : RTotal REmp -> forall l' l, List.concat l' = l -> (l = [] \\/ exists x, In x l' /\\ RegMatch REmp x false).\n    intros HRT l'.\n    induction l'.\n    {\n      intros l H.\n      simpl in H.\n      rewrite <- H.\n      left. reflexivity.\n    }\n    {\n      intros l H1.\n      assert ((concat l') = [] \\/ exists x : list Σ, In x l' /\\ RegMatch REmp x false) by eauto.\n      destruct a.\n      {\n        inversion H.\n        {\n          left.\n          subst.\n          simpl.\n          assumption.\n        }\n        {\n          right.\n          inversion H0.\n          inversion H2.\n          exists x.\n          split. { simpl. now right. } { assumption. }\n        }\n      }\n      {\n        right.\n        exists (s :: a).\n        split. { simpl. left. reflexivity. } { constructor. }\n      }\n    }\n  Qed.\n\n  Lemma RegCharStarBase1 : forall c, RTotal (RChar c) -> forall l' l c2 , eq_dec c c2 = false -> List.concat l' = (c2 :: l) -> (l = [] \\/ exists x, In x l' /\\ RegMatch (RChar c) x false).\n    intros c HRT l'.\n    induction l'.\n    {\n      intros l c2 H1 H2.\n      simpl in H2.\n      inversion H2.\n    }\n    {\n      intros l c2 H1 H2.\n      destruct a.\n      {\n        simpl in H2.\n        simpl.\n        right.\n        exists []. split. {left. reflexivity.} { constructor. }\n      }\n      {\n        destruct a.\n        2: { right. exists (s :: s0 :: a). split. { simpl. left. reflexivity. } { eapply RCharF2. } }\n        simpl in H2.\n        inversion H2.\n        right.\n        exists [c2]. split. { simpl. left. reflexivity. } { constructor. assumption. }\n      }\n    }\n  Qed.\n\n  Lemma RegCharStarBase2 : forall c, RTotal (RChar c) -> forall l' l, RegMatch (RStar (RChar c)) l false -> List.concat l' = (c :: l) -> (exists x, In x l' /\\ RegMatch (RChar c) x false).\n    intros c HRT l'.\n    induction l'.\n    {\n      intros l' l H.\n      inversion H.\n    }\n    {\n      intros l H H0.\n      inversion H.\n      subst.\n      destruct a.\n      {\n        simpl in H0.\n        exists []; repeat split; eauto using RegMatch. simpl. left. reflexivity.\n      }\n      {\n        destruct a.\n        2: { exists (s :: s0 :: a). split. { simpl. left. reflexivity. } { eapply RCharF2. } }\n        simpl in H0.\n        inversion H0.\n        subst.\n        assert (exists e : list Σ, In e l' /\\ RegMatch (RChar c) e false) by eauto.\n        inversion H1.\n        inversion H3.\n        exists x. split. { now right. } { assumption. }\n      }\n    }\n  Qed.\n\n\n  Lemma RRStarWeakRStar : forall r l b, RegMatch (RConcat (RUnion r REmp) (RStar r)) l b -> RegMatch (RStar r) l b.\n    intros r l b.\n    destruct b.\n    {\n      intros H.\n      inversion H.\n      subst.\n      inversion H4.\n      subst.\n      constructor.\n      inversion H1.\n      inversion H0.\n      inversion H2.\n      {\n        subst.\n        exists (l1 :: x).\n        split. { simpl. reflexivity. } { now constructor. }\n      }\n      {\n        subst.\n        inversion H9.\n        subst l1.\n        simpl.\n        exists x. split; eauto.\n      }\n    }\n    {\n      intros H.\n      inversion H.\n      subst.\n      constructor.\n      intros ls Hconcat.\n      destruct ls.\n      {\n        simpl in Hconcat.\n        subst l.\n        assert (RegMatch (RUnion r REmp) [] false \\/ RegMatch (RUnion r REmp) [] true /\\ RegMatch (RStar r) [] false) by eauto.\n        inversion H0.\n        {\n          assert (RegMatch (RUnion r REmp) [] true) by eauto using RegMatch.\n          assert (RDeterministic (RUnion r REmp)) by eauto using reg_det.\n          assert (false = true) by eauto.\n          discriminate.\n        }\n        {\n          inversion H1.\n          assert (RegMatch (RStar r) [] true) by (constructor; exists []; eauto).\n          assert (RDeterministic (RStar r)) by eauto using reg_det.\n          assert (false = true) by eauto.\n          discriminate.\n        }\n      }\n      simpl in Hconcat.\n      assert (RegMatch (RUnion r REmp) l0 false \\/ RegMatch (RUnion r REmp) l0 true /\\ RegMatch (RStar r) (concat ls) false) by eauto.\n      inversion H0.\n      {\n        inversion H1.\n        subst.\n        exists l0; split; try eauto; try (constructor; reflexivity).\n      }\n      {\n        inversion H1.\n        inversion H4.\n        subst.\n        assert (exists e : list Σ, In e ls /\\ RegMatch r e false) by eauto.\n        inversion H5.\n        inversion H7.\n        exists x. split. { simpl. now right. } { assumption. }\n      }\n    }\n  Qed.\n\n\n  (* H' : concat l' = [a] *)\n  (* ============================ *)\n  (* exists e : list Σ, In e l' /\\ RegMatch (RChar c) e false *)\n  Lemma LMembMakesFalse : forall l' c t, RegMatch (RStar (RChar c)) t true -> forall a, eq_dec c a = false -> concat l' = (a :: t) ->\n        exists e : list Σ, In e l' /\\ RegMatch (RChar c) e false.\n    intros l'.\n    induction l'.\n    {\n      intros a t HMatch a0 Heq Hconcat.\n      simpl in Hconcat.\n      inversion Hconcat.\n    }\n    {\n      intros c t HMatch a0 Heq Hconcat.\n      simpl in Hconcat.\n      destruct a.\n      {\n        exists []; split. { left. reflexivity. } { constructor. }\n      }\n      {\n        destruct a.\n        2: { exists (s :: s0 :: a). split. { left. reflexivity. } { eapply RCharF2. } }\n        inversion Hconcat.\n        exists [a0].\n        split. { left. reflexivity. } { now constructor. }\n      }\n    }\n  Qed.\n\n  Inductive Splits {T} : list T -> list T -> Type :=\n  | SplitsBase l1 : Splits [] l1\n  | SplitsRec l1 : forall h t, Splits l1 (h :: t) -> Splits (l1 ++ [h]) t.\n\n  Fixpoint ListOfSplits {T} {l1 l2} (s : Splits l1 l2) : list T :=\n    match s with\n     | SplitsBase l1 => l1\n     | SplitsRec l1 _ _ m => l1 ++ ListOfSplits m\n    end.\n\n  (*\n  IHr1 : RTotal r1 /\\ (RTotal r1 -> forall r2 : REG, RTotal r2 -> RTotal (RConcat r1 r2)) /\\ (RTotal r1 -> forall r3 : REG, RTotal r3 -> RTotal (RUnion r1 r3)) /\\ (RTotal r1 -> RTotal (RStar r1))\n  IHr2 : RTotal r2 /\\ (RTotal r2 -> forall r3 : REG, RTotal r3 -> RTotal (RConcat r2 r3)) /\\ (RTotal r2 -> forall r3 : REG, RTotal r3 -> RTotal (RUnion r2 r3)) /\\ (RTotal r2 -> RTotal (RStar r2))\n  ============================\n  RTotal (RConcat r1 r2) -> RTotal (RStar (RConcat r1 r2))\n   *)\n\n  (* Lemma RegTotalStrong : forall r, RTotal r /\\ (RTotal r -> forall r2, RTotal r2 -> RTotal (RConcat r r2)) /\\ (RTotal r -> forall r3, RTotal r3 -> RTotal (RUnion r r3)) /\\ (RTotal r -> RTotal (RStar r)). *)\n  (*   intros r. *)\n  (*   induction r. *)\n  (*   { *)\n  (*     repeat split. *)\n  (*     { *)\n  (*       intros l. *)\n  (*       destruct l. *)\n  (*       { *)\n  (*         left. *)\n  (*         constructor. *)\n  (*       } *)\n  (*       { *)\n  (*         right. *)\n  (*         constructor. *)\n  (*       } *)\n  (*     } *)\n  (*     { *)\n  (*       intros HTotalEmp r2 HTotalr2 l. *)\n  (*       unfold RTotal in HTotalr2. *)\n  (*       assert (RegMatch r2 l true \\/ RegMatch r2 l false) by eauto. *)\n  (*       inversion H. *)\n  (*       { *)\n  (*         left. *)\n  (*         replace l with ([] ++ l) by reflexivity. *)\n  (*         constructor; try constructor; try assumption. *)\n  (*       } *)\n  (*       { *)\n  (*         right. *)\n  (*         apply RConcatF. *)\n  (*         intros l1 l1'' Heq. *)\n  (*         destruct l1. *)\n  (*         { *)\n  (*           right; repeat split. *)\n  (*           { *)\n  (*             constructor. *)\n  (*           } *)\n  (*           { *)\n  (*             simpl in Heq. *)\n  (*             now subst l1''. *)\n  (*           } *)\n  (*         } *)\n  (*         { *)\n  (*           left. *)\n  (*           constructor. *)\n  (*         } *)\n  (*       } *)\n  (*     } *)\n  (*     { *)\n  (*       intros HRT1 r0 HRT0 l. *)\n  (*       destruct l. *)\n  (*       { *)\n  (*         left. *)\n  (*         eapply RUnionSL. *)\n  (*         constructor. *)\n  (*       } *)\n  (*       { *)\n  (*         assert (RegMatch r0 (s :: l) true \\/ RegMatch r0 (s :: l) false) by eauto. *)\n  (*         inversion H. *)\n  (*         { *)\n  (*           left. *)\n  (*           now eapply RUnionSR. *)\n  (*         } *)\n  (*         { *)\n  (*           right. *)\n  (*           apply RUnionF; try assumption; try constructor. *)\n  (*         } *)\n  (*       } *)\n  (*     } *)\n  (*     { *)\n  (*       intros HRT l. *)\n  (*       destruct l eqn:Eql. *)\n  (*       { *)\n  (*         left. constructor. *)\n  (*         exists []. repeat split; eauto. *)\n  (*       } *)\n  (*       { *)\n  (*         right. *)\n  (*         constructor. *)\n  (*         intros l' H. *)\n  (*         assert ((s :: l0) = [] \\/ (exists x : list Σ, In x l' /\\ RegMatch REmp x false)) by eauto using RegStarBase. *)\n  (*         inversion H0. { inversion H1. } { assumption. } *)\n  (*       } *)\n  (*     } *)\n  (*   } *)\n  (*   { *)\n  (*     repeat split. *)\n  (*     { *)\n  (*       intros l. *)\n  (*       destruct l. *)\n  (*       { *)\n  (*         right. now constructor. *)\n  (*       } *)\n  (*       { *)\n  (*         destruct l. *)\n  (*         { *)\n  (*           destruct (eq_dec c s) eqn:Eqd. *)\n  (*           { *)\n  (*             apply eq_dec_correct in Eqd. *)\n  (*             rewrite Eqd. *)\n  (*             left. *)\n  (*             constructor. *)\n  (*           } *)\n  (*           { *)\n  (*             right. *)\n  (*             now constructor. *)\n  (*           } *)\n  (*         } *)\n  (*         { *)\n  (*           right. *)\n  (*           eapply RCharF2. *)\n  (*         } *)\n  (*       } *)\n  (*     } *)\n  (*     { *)\n  (*       intros HTotal1 r2 HTotal2 l. *)\n  (*       destruct l. *)\n  (*       { *)\n  (*         right. *)\n  (*         constructor. *)\n  (*         intros l1' l1'' Hsplit. *)\n  (*         eapply SplitEmpty in Hsplit. *)\n  (*         inversion Hsplit. *)\n  (*         subst. *)\n  (*         left. *)\n  (*         constructor. *)\n  (*       } *)\n  (*       { *)\n  (*         destruct (eq_dec c s) eqn:Eqd. *)\n  (*         { *)\n  (*           apply eq_dec_correct in Eqd. *)\n  (*           subst s. *)\n  (*           unfold RTotal in HTotal2. *)\n  (*           assert (RegMatch r2 l true \\/ RegMatch r2 l false) by eauto. *)\n  (*           inversion H. *)\n  (*           { *)\n  (*             left. *)\n  (*             replace (c :: l) with ([c] ++ l) by eauto. *)\n  (*             eapply RConcatS; try constructor; try assumption. *)\n  (*           } *)\n  (*           { *)\n  (*             right. *)\n  (*             constructor. *)\n  (*             intros l1' l1'' Hsplit. *)\n  (*             destruct l1'. { left. constructor. } *)\n  (*             destruct l1'. { right. inversion Hsplit. subst. split; try constructor; try assumption. } *)\n  (*             left. eapply RCharF2. *)\n  (*           } *)\n  (*         } *)\n  (*         { *)\n  (*           right. *)\n  (*           constructor. *)\n  (*           intros l1' l1'' H. *)\n  (*           destruct l1'. { left. constructor. } *)\n  (*           destruct l1'. { left. constructor. now inversion H. } *)\n  (*           left. eapply RCharF2. *)\n  (*         } *)\n  (*       } *)\n  (*     } *)\n  (*     { *)\n  (*       intros HT1 r3 HT0 l. *)\n  (*       assert (RegMatch r3 l true \\/ RegMatch r3 l false) by eauto. *)\n  (*       inversion H; try (left; eapply RUnionSR; assumption). *)\n  (*       destruct l; try destruct l; eauto using RegMatch. *)\n  (*       destruct (eq_dec c s) eqn:Eqd. *)\n  (*       { apply eq_dec_correct in Eqd. rewrite Eqd. left. eapply RUnionSL. constructor. } *)\n  (*       { right. constructor. constructor. assumption. assumption. } *)\n  (*     } *)\n  (*     { *)\n  (*       intros HRT l. *)\n  (*       induction l. *)\n  (*       { *)\n  (*         left. *)\n  (*         constructor. *)\n  (*         exists []. split; eauto. *)\n  (*       } *)\n  (*       { *)\n  (*         destruct (eq_dec c a) eqn:Eqd. *)\n  (*         { *)\n  (*           apply eq_dec_correct in Eqd. *)\n  (*           subst a. *)\n  (*           inversion IHl. *)\n  (*           { *)\n  (*             inversion H. *)\n  (*             subst. *)\n  (*             inversion H1. *)\n  (*             inversion H0. *)\n  (*             subst l. *)\n  (*             left. *)\n  (*             constructor. *)\n  (*             exists ([c] :: x); split. *)\n  (*             { simpl. reflexivity. } { constructor; eauto using RegMatch. } *)\n  (*           } *)\n  (*           { *)\n  (*             inversion H. *)\n  (*             subst l0. *)\n  (*             right. *)\n  (*             constructor. *)\n  (*             intros l' H'. *)\n  (*             eauto using RegCharStarBase2. *)\n  (*           } *)\n  (*         } *)\n  (*         { *)\n  (*           inversion IHl. *)\n  (*           { *)\n  (*             right. *)\n  (*             constructor. *)\n  (*             intros l' H'. *)\n  (*             eauto using LMembMakesFalse. *)\n  (*           } *)\n  (*           { *)\n  (*             right. *)\n  (*             constructor. *)\n  (*             intros l' H'. *)\n  (*             destruct l'. *)\n  (*             { *)\n  (*               simpl in H'. *)\n  (*               inversion H'. *)\n  (*             } *)\n  (*             { *)\n  (*               destruct l0. *)\n  (*               { *)\n  (*                 exists []. split. left. reflexivity. constructor. *)\n  (*               } *)\n  (*               { *)\n  (*                 destruct l0. *)\n  (*                 { *)\n  (*                   simpl in H'. *)\n  (*                   inversion H'. *)\n  (*                   exists [a]. split. left. reflexivity. constructor. assumption. *)\n  (*                 } *)\n  (*                 { *)\n  (*                   exists (s :: s0 :: l0). split. left. reflexivity. eapply RCharF2. *)\n  (*                 } *)\n  (*               } *)\n  (*             } *)\n  (*           } *)\n  (*         } *)\n  (*       } *)\n  (*     } *)\n  (*   } *)\n  (*   { *)\n  (*     repeat split. *)\n  (*     { *)\n  (*       inversion IHr1. *)\n  (*       inversion IHr2. *)\n  (*       inversion H0. *)\n  (*       inversion H2. *)\n  (*       eauto. *)\n  (*     } *)\n  (*     { *)\n  (*       intros HTotal1 r0 HTotal0 l. *)\n  (*       inversion IHr1. inversion IHr2. *)\n  (*       assert (RegMatch (RConcat r1 (RConcat r2 r0)) l true \\/ RegMatch (RConcat r1 (RConcat r2 r0)) l false). *)\n  (*       { *)\n  (*         eapply H0; try assumption. *)\n  (*         eapply H2; try assumption. *)\n  (*       } *)\n  (*       inversion H3. *)\n  (*       { *)\n  (*         apply RegCatEquivalence in H4; try assumption. *)\n  (*         left; assumption. *)\n  (*       } *)\n  (*       { *)\n  (*         apply RegCatEquivalence in H4; try assumption. *)\n  (*         right; assumption. *)\n  (*       } *)\n  (*     } *)\n  (*     { *)\n  (*       intros H r3 H0 l. *)\n  (*       assert (RegMatch (RConcat r1 r2) l true \\/ RegMatch (RConcat r1 r2) l false) by eauto. *)\n  (*       assert (RegMatch r3 l true \\/ RegMatch r3 l false) by eauto. *)\n  (*       inversion H1; inversion H2. *)\n  (*       { left. eapply RUnionSL. assumption. } *)\n  (*       { left. eapply RUnionSL. assumption. } *)\n  (*       { left. eapply RUnionSR. assumption. } *)\n  (*       { right. eapply RUnionF. assumption. assumption. } *)\n  (*     } *)\n  (*     { *)\n\n  (*       intros H. *)\n  (*     } *)\n  (*   } *)\n  (*   { *)\n  (*     inversion IHr1. *)\n  (*     inversion IHr2. *)\n  (*     repeat split. *)\n  (*     { *)\n  (*       intros l. *)\n  (*       unfold RTotal in H. *)\n  (*       unfold RTotal in H1. *)\n  (*       assert (RegMatch r1 l true \\/ RegMatch r1 l false) by eauto. *)\n  (*       assert (RegMatch r2 l true \\/ RegMatch r2 l false) by eauto. *)\n  (*       inversion H3; inversion H4. *)\n  (*       1: left. 2: left. 3: left. 4: { right; constructor; assumption. } all: constructor; assumption. *)\n  (*     } *)\n  (*     { *)\n  (*       intros HT1 r0 HT0 l. *)\n  (*       inversion IHr1. *)\n  (*       inversion H4. *)\n  (*       inversion IHr2. *)\n  (*       inversion H8. *)\n  (*       assert (RegMatch (RUnion (RConcat r1 r0) (RConcat r2 r0)) l true \\/ RegMatch (RUnion (RConcat r1 r0) (RConcat r2 r0)) l false). *)\n  (*       { *)\n  (*         assert (RegMatch (RConcat r1 r0) l true \\/ RegMatch (RConcat r1 r0) l false). *)\n  (*         { *)\n  (*           now eapply H5. *)\n  (*         } *)\n  (*         assert (RegMatch (RConcat r2 r0) l true \\/ RegMatch (RConcat r2 r0) l false). *)\n  (*         { *)\n  (*           now apply H9. *)\n  (*         } *)\n  (*         inversion H11. { left. now eapply RUnionSL. } { inversion H12. { left. now eapply RUnionSR. } { right. now constructor. }} *)\n  (*       } *)\n  (*       inversion H11. *)\n  (*       { *)\n  (*         left. *)\n  (*         eapply UnionConcatEquivalence in H12; eauto. *)\n  (*       } *)\n  (*       { *)\n  (*         right. *)\n  (*         eapply UnionConcatEquivalence in H12; eauto. *)\n  (*       } *)\n  (*     } *)\n  (*     { *)\n  (*       intros HT1 r3 HT3 l. *)\n  (*       assert (RegMatch (RUnion r1 r2) l true \\/ RegMatch (RUnion r1 r2) l false) by eauto. *)\n  (*       inversion H3. { left. now apply RUnionSL. } *)\n  (*       inversion H4. *)\n  (*       subst. *)\n  (*       assert (RegMatch r3 l true \\/ RegMatch r3 l false) by eauto. *)\n  (*       inversion H5. { left. now apply RUnionSR. } *)\n  (*       right. *)\n  (*       constructor; try constructor; assumption. *)\n  (*     } *)\n  (*   } *)\n  (*   { *)\n  (*     repeat split. *)\n  (*     { *)\n  (*       intros l. *)\n  (*       inversion IHr. *)\n  (*       inversion H0. *)\n        \n  (*     } *)\n  (*   } *)\n\n  (* Context (tot : forall r, RTotal r). *)\n\n  Definition RSetMinus (r1 : REG) (r2 : REG) := RIntersection r1 (RNeg r2).\n\n  (* First version, of which I am more confident of the semantics. *)\n  Fixpoint PEGREG__old (p : PEG) (r : REG) : REG :=\n    match p with\n    | Char c => RConcat (RChar c) r\n    | Concat p1 p2 => PEGREG__old p1 (PEGREG__old p2 r)\n    | OrderedChoice p1 p2 => let p1r := PEGREG__old p1 r in\n                            let p2r := PEGREG__old p2 r in\n                            RUnion p1r (RSetMinus p2r (RIntersection p1r p2r))\n    | PossesiveStar p1 => let p1r := RStar (PEGREG__old p1 REmp) in\n                         RConcat p1r (RSetMinus r (RIntersection p1r r))\n    end.\n\n  (* Second version, more inductive. *)\n\n  (* Remove the parts of r corresponding to ordered/possesive choices of p,\n     then concatenate p with r. *)\n  Fixpoint PEGREG (p : PEG) (r : REG) : REG :=\n    match p with\n    | Char c => RConcat (RChar c) r\n    | Concat p1 p2 => PEGREG p1 (PEGREG p2 r)\n    | OrderedChoice p1 p2 =>\n        let p1r := PEGREG p1 r in\n        let p2r := PEGREG p2 r in\n        let p2r' := RSetMinus p2r (RIntersection p1r p2r) in\n        RUnion p1r p2r\n    | PossesiveStar p1 =>\n        let p1r := RStar (PEGREG p1 REmp) in\n        let p2r := (RUnion (RSetMinus r (RIntersection p1r r)) (RIntersection r REmp)) in\n        RConcat p1r p2r\n    end.\n\n  Lemma concat_char_nomatch_emp : forall c1, forall r, RegMatch (RConcat (RChar c1) r) [] false.\n    intros c1 r.\n    constructor.\n    intros l1' l1'' H.\n    destruct l1'.\n    {\n      left. constructor.\n    }\n    {\n      destruct l1''.\n      {\n        simpl in H.\n        inversion H.\n      }\n      {\n        simpl in H.\n        inversion H.\n      }\n    }\n  Qed.\n\n  Lemma two_one_length_one_one_length_impossible : forall T, forall l1 l2 : list T, forall c1 c2 c3 : T,\n      (c1 :: l1) ++ (c2 :: l2) = [c3] -> False.\n    intros T l1.\n    induction l1.\n    {\n      intros l2 c1 c2 c3 H.\n      simpl in H.\n      inversion H.\n    }\n    {\n      intros l2 c1 c2 c3 H.\n      inversion H.\n    }\n  Qed.\n\n  Lemma two_char_nomatch_one : forall c1 c2 c3, forall r, RegMatch (RConcat (RChar c1) (RConcat (RChar c2) r)) [c3] false.\n    intros c1 c2 c3 r.\n    destruct (eq_dec c1 c3) eqn:Heq_dec; apply eq_dec_correct in Heq_dec.\n    {\n      subst c3.\n      constructor.\n      intros l1' l1'' H.\n      destruct l1'.\n      {\n        left.\n        constructor.\n      }\n      {\n        destruct l1''.\n        {\n          inversion H.\n          rewrite app_nil_r in H2.\n          rewrite H2.\n          right.\n          split.\n          {\n            constructor.\n          }\n          {\n            apply concat_char_nomatch_emp.\n          }\n        }\n        {\n          simpl in H.\n          inversion H.\n          subst.\n          simpl in H2.\n          destruct l1'; discriminate.\n        }\n      }\n    }\n    {\n      constructor.\n      intros l1' l1'' H.\n      destruct l1'.\n      {\n        simpl in H.\n        subst.\n        left.\n        constructor.\n      }\n      {\n        destruct l1''.\n        {\n          simpl in H.\n          inversion H.\n          subst.\n          left.\n          eapply RCharF1. { eapply eq_dec_correct. exact Heq_dec. }\n        }\n        {\n          apply two_one_length_one_one_length_impossible in H.\n          contradiction.\n        }\n      }\n    }\n  Qed.\n\n  Lemma lop : forall t r c,\n      RegMatch r t false -> RegMatch (RConcat (RChar c) r) (c :: t) false.\n    intros t.\n    induction t.\n    {\n      intros r c H.\n      constructor.\n      intros l1' l1'' H'.\n      destruct l1'.\n      {\n        simpl in H'.\n        rewrite H'.\n        left.\n        constructor.\n      }\n      {\n        destruct l1''.\n        {\n          simpl in H'.\n          inversion H'.\n          rewrite app_nil_r in H2.\n          subst.\n          right; split; simpl; eauto using RegMatch.\n        }\n        {\n          now apply two_one_length_one_one_length_impossible in H'.\n        }\n      }\n    }\n    {\n      intros r c H.\n      constructor.\n      intros l1' l1'' H'.\n      destruct l1'.\n      {\n        left.\n        constructor.\n      }\n      {\n        destruct l1''.\n        {\n          simpl in H'.\n          inversion H'.\n          rewrite app_nil_r in H2.\n          subst.\n          left.\n          eapply RCharF2.\n        }\n        {\n          destruct l1'.\n          {\n            inversion H'.\n            subst.\n            right; split; eauto using RegMatch.\n          }\n          {\n            left.\n            eapply RCharF2.\n          }\n        }\n      }\n    }\n  Qed.\n\n  Definition splits_imply_concat_inclusion : forall {T}, forall (P : list T -> Prop), forall l, (forall l1 l2 : list T, l1 ++ l2 = l -> P l1) -> (l = [] \\/ forall l3, concat l3 = l -> exists l1', In l1' l3 /\\ P l1').\n    intros T P l H.\n    destruct l eqn:eql.\n    {\n      left.\n      reflexivity.\n    }\n    {\n      right.\n      intros l3.\n      rewrite <- eql in * |- *.\n      intros HConc.\n      destruct l3.\n      {\n        simpl in HConc.\n        subst.\n        discriminate.\n      }\n      {\n        simpl in HConc.\n        assert (P l1) by eauto.\n        exists l1. split; eauto. left. reflexivity.\n      }\n    }\n  Qed.\n\n  Definition some_implies_match (P : PEG) (r__remainder : REG) (r__out : REG) :=\n    forall l1 l2 l3 prf suf, PegMatch P l1 (Some (l2, l3)) -> prf ++ suf = l3 -> RegMatch r__remainder prf true -> RegMatch r__out (l2 ++ prf) true.\n\n  Definition blame_remainder (P : PEG) (r__remainder : REG) (r__out : REG) :=\n    forall l1 l2 l3 prf suf, PegMatch P l1 (Some (l2, l3)) -> prf ++ suf = l3 ->\n                        RegMatch r__remainder prf false -> RegMatch r__out (l2 ++ prf) false.\n\n  (*\n   * some_implies_match and blame_remainder together characterize the\n   * \"action/influence\" of rremainder on rout\n   *)\n\n  Definition none_implies_nomatch (P : PEG) (r__remainder : REG) (r__out : REG) :=\n    forall l1, DoesNotMatch P l1 -> RegMatch r__out l1 false.\n\n  (* An by earlier lemma, therefore none -> nomatch any of the prefixes. *)\n\n\n  Definition LR (P : PEG) (r__remainder : REG) (r__out : REG) : Prop :=\n    some_implies_match P r__remainder r__out /\\ none_implies_nomatch P r__remainder r__out /\\ \n      blame_remainder P r__remainder r__out.\n\n  Lemma NoPegEmp' : forall p l o, PegMatch p l o -> l <> [].\n    intros p l o m.\n    induction m; try discriminate; try assumption.\n  Qed.\n\n  Lemma NoPegEmp : forall p o, PegMatch p [] o -> False.\n    intros p o m.\n    assert ([] <> []) by eauto using NoPegEmp'.\n    contradiction.\n  Qed.\n\n  Lemma PegMatchChunkFormStrong : forall p l o, PegMatch p l o -> forall l1 l2, o = Some (l1, l2) -> forall p', p = PossesiveStar p' ->\n                                                                                         exists ls, (concat ls = l1 /\\ forall prf a suf, prf ++ (a :: suf) = ls -> PegMatch p' ((concat (a :: suf)) ++ l2) (Some (a, (concat suf) ++ l2))).\n    intros p l o m.\n    induction m; try discriminate.\n    {\n      intros l1 l2 Heqo p' Heqp'.\n      inversion Heqo. inversion Heqp'. simpl.\n      exists [].\n      split.\n      { simpl. reflexivity. }\n      {\n        intros prf a suf HConc.\n        symmetry in HConc.\n        eapply catnil in HConc as HNil.\n        subst prf. simpl in HConc.\n        discriminate.\n      }\n    }\n    {\n      intros l5 l6 Heqo p' Heqp'.\n      inversion Heqo. inversion Heqp'. simpl.\n      subst.\n      assert (exists ls : list (list Σ),\n           concat ls = l3 /\\\n           (forall prf a suf,\n               prf ++ (a :: suf) = ls -> PegMatch p' ((concat (a :: suf)) ++ l6) (Some (a, concat (suf) ++ l6)))).\n      {\n        eapply IHm2; reflexivity.\n      }\n      inversion H.\n      inversion H0.\n      eapply list_split in m1 as HLS1.\n      eapply list_split in m2 as HLS2.\n      subst l2.\n      symmetry in H1.\n      subst.\n      exists (l1 :: x); split.\n      {\n        simpl. reflexivity.\n      }\n      {\n        intros prf a suf HConc.\n        destruct prf eqn:heqprf.\n        {\n          simpl in HConc.\n          inversion HConc.\n          subst.\n          rewrite <- app_assoc.\n          eauto.\n        }\n        {\n          simpl in HConc.\n          inversion HConc.\n          subst.\n          inversion H0.\n          replace (a ++ concat suf) with (concat (a :: suf)) by reflexivity.\n          eapply H3 with (prf := l0).\n          reflexivity.\n        }\n      }\n    }\n  Qed.\n\n  Lemma PegMatchChunkForm : forall p l1 l2 l3, PegMatch (PossesiveStar p) l1 (Some (l2, l3)) ->\n                                          exists ls, (concat ls = l2 /\\ forall prf a suf, prf ++ (a :: suf) = ls -> PegMatch p ((concat (a :: suf)) ++ l3) (Some (a, (concat suf) ++ l3))).\n    eauto using PegMatchChunkFormStrong.\n  Qed.\n\n  Lemma PegMatchInversion : forall ls p l3,\n      (forall prf a suf, prf ++ (a :: suf) = ls -> PegMatch p ((concat (a :: suf)) ++ l3) (Some (a, (concat suf) ++ l3))) -> PegMatch p l3 None -> PegMatch (PossesiveStar p) ((concat ls) ++ l3) (Some ((concat ls), l3)).\n    intros ls.\n    induction ls; try eauto using PegMatch.\n    intros p l3 HSuf HTail.\n    assert (\n        (forall (prf : list (list Σ)) (a : list Σ) (suf : list (list Σ)),\n          prf ++ a :: suf = ls -> PegMatch p (concat (a :: suf) ++ l3) (Some (a, concat suf ++ l3)))\n      ).\n    {\n      intros prf a0 suf HApp.\n      apply HSuf with (prf := a :: prf). rewrite <- HApp. reflexivity.\n    }\n    assert (PegMatch (PossesiveStar p) (concat ls ++ l3) (Some (concat ls, l3))) by (eapply IHls; assumption).\n    simpl. rewrite <- app_assoc. econstructor.\n    {\n      simpl in HSuf.\n      rewrite app_assoc.\n      eapply HSuf with (prf := []). simpl. reflexivity.\n    }\n    exact H0.\n  Qed.\n\n  Lemma SomeImpliesMatchStarChunkForm :\n    forall ls p l3,\n      (forall prf a suf, prf ++ (a :: suf) = ls -> PegMatch p ((concat (a :: suf)) ++ l3) (Some (a, (concat suf) ++ l3))) ->\n      forall l1, PegMatch (PossesiveStar p) l1 (Some (concat ls, l3)) ->\n               (forall r__remainder, LR p r__remainder (PEGREG p r__remainder)) ->\n                    (Forall (fun l => RegMatch (PEGREG p REmp) l true) ls).\n    intros ls.\n    induction ls. { constructor. }\n    {\n      intros.\n      assert\n         (forall (prf : list (list Σ)) (a : list Σ) (suf : list (list Σ)),\n             prf ++ a :: suf = ls -> PegMatch p (concat (a :: suf) ++ l3) (Some (a, concat suf ++ l3))).\n      {\n        intros prf a0 suf HSuf.\n        eapply H with (prf := a :: prf). now rewrite <- HSuf.\n      }\n      constructor.\n      {\n        assert (PegMatch p (concat (a :: ls) ++ l3) (Some (a, (concat ls) ++ l3))).\n        { eapply H with (prf := []). simpl. reflexivity. }\n        assert (some_implies_match p REmp (PEGREG p REmp)) by eapply H1.\n        replace a with (a ++ []) by eauto using app_nil_r.\n        unfold some_implies_match in H4.\n        apply H4 with (l1 := (concat (a :: ls) ++ l3)) (l2 := a) (l3 := concat ls ++ l3)\n                      (prf := []) (suf := concat ls ++ l3); eauto using RegMatch.\n      }\n      {\n        apply IHls with (l3 := l3) (l1 := (concat ls) ++ l3); try assumption.\n        {\n          apply StarImpliesRemainderFail in H0 as HRemainderFail.\n          eapply PegMatchInversion; try assumption.\n        }\n      }\n    }\n    Qed.\n\n\n  Lemma dnm_none : forall p l, PegMatch p l None -> DoesNotMatch p l.\n    intros p l H ? ? H'.\n    assert (None = Some (_, _)) by eauto using PegPartial.\n    discriminate.\n  Qed.\n\n\n  Lemma SomeImpliesMatchStarStrong :\n    forall p l o, PegMatch p l o ->\n             forall p', p = PossesiveStar p' ->\n             (forall r__remainder, LR p' r__remainder (PEGREG p' r__remainder)) ->\n             forall l2 prf suf : list Σ, o = (Some (l2, prf ++ suf)) -> forall r, RegMatch r prf true ->\n                                                               RegMatch (PEGREG p r) (l2 ++ prf) true.\n    intros p l o m p' Heqp HLR l2 prf suf Heqo r HMatch.\n    inversion Heqp. inversion Heqo. subst.\n    simpl.\n    apply list_split in m as HLS. subst l.\n    apply PegMatchChunkForm in m as HChunkform.\n    constructor.\n    {\n      constructor.\n      inversion HChunkform.\n      inversion H1.\n      eapply SomeImpliesMatchStarChunkForm in H3.\n      2: { rewrite H2. exact m. }\n      2: { exact HLR. }\n      exists x; split; eauto.\n    }\n    {\n      destruct prf eqn:Heqprf.\n      {\n        eapply RUnionSR.\n        constructor. { assumption. } { constructor. }\n      }\n      rewrite <- Heqprf in * |- *.\n      eapply RUnionSL.\n      constructor. try assumption.\n      constructor.\n      constructor.\n      constructor.\n      intros l' HConcat.\n      apply StarImpliesRemainderFail in m as HFail.\n      assert (StrengthenFail p' prf suf) by eapply MatchStrengthen.\n      assert (DoesNotMatch p' prf) by (eapply H1; eapply dnm_none; assumption).\n      assert (forall l' l'', l' ++ l'' = prf -> DoesNotMatch p' l').\n      {\n        intros l'0 l'' HApp.\n        assert (StrengthenFail p' l'0 l'') by eapply MatchStrengthen.\n        eapply H3. now rewrite HApp.\n      }\n      assert (forall l' l'', l' ++ l'' = prf -> RegMatch (PEGREG p' REmp) l' false).\n      {\n        intros l'0 l'' HApp.\n        assert (DoesNotMatch p' l'0) by eauto.\n        assert (none_implies_nomatch p' REmp (PEGREG p' REmp)) by apply HLR.\n        now apply H5.\n      }\n      assert (prf = [] \\/ (forall ell, concat ell = prf -> exists e : list Σ, In e ell /\\ RegMatch (PEGREG p' REmp) e false)) by (eapply splits_imply_concat_inclusion; auto).\n      inversion H5; try (subst prf; discriminate).\n      eapply H6; assumption.\n    }\n  Qed.\n\n  Lemma dnmchar : forall l c s, DoesNotMatch (Char c) (s :: l) ->\n                           eq_dec c s = false.\n    intros l c s.\n    destruct (eq_dec c s) eqn:Heqdc.\n    {\n      intros H.\n      apply eq_dec_correct in Heqdc as Heqs.\n      subst s.\n      {\n        exfalso.\n        apply H with (l1 := [c]) (l2 := l).\n        constructor.\n      }\n    }\n    {\n      intros H.\n      reflexivity.\n    }\n  Qed.\n\n  Lemma dnm_catassoc : forall p1 p2 p3 l, DoesNotMatch (Concat (Concat p1 p2) p3) l ->\n                                     DoesNotMatch (Concat p1 (Concat p2 p3)) l.\n    intros p1 p2 p3 l.\n    {\n      intros Hdnm.\n      intros l1 l2 m'.\n      apply Hdnm with (l1 := l1) (l2 := l2).\n      inversion m'.\n      subst.\n      inversion H5.\n      subst.\n      rewrite app_assoc.\n      eapply CatS. { eapply CatS; eauto. } eauto.\n    }\n  Qed.\n\n  Lemma impossible_listcons : forall {T}, forall l : list T, forall h, l = (h :: l) -> False.\n    intros T l.\n    induction l.\n    {\n      intros h H. inversion H.\n    }\n    {\n      intros h H.\n      inversion H.\n      eapply IHl. exact H2.\n    }\n    Qed.\n\n  Lemma impossible_listapp : forall {T}, forall l1 l2 : list T, forall h,\n      l1 = (h :: l2) ++ l1 -> False.\n    intros T l1.\n    induction l1.\n    {\n      intros l2 h H. simpl in H. inversion H.\n    }\n    {\n      intros l2 h H. inversion H.\n      destruct l2. { simpl in H2. eapply impossible_listcons. exact H2. }\n      replace ((t :: l2) ++ h :: l1) with (((t :: l2) ++ [h]) ++ l1) in H2 by (rewrite <- app_assoc; auto).\n      eapply IHl1.\n      exact H2.\n    }\n  Qed.\n\n  Lemma headeq : forall {T}, forall l2 l3 l1 : list T, l2 ++ l1 = l3 ++ l1 -> l2 = l3.\n    intros T l2.\n    induction l2.\n    { intros l3 l1 H. simpl in H. destruct l3. reflexivity. exfalso. eapply impossible_listapp. exact H.  }\n    { intros l3 l1 H. destruct l3. { simpl in H. symmetry in H. eapply impossible_listapp in H. contradiction. } { inversion H. simpl. assert (l2 = l3) by eauto. rewrite <- H0. reflexivity. } }.\n    Qed.\n\n  Lemma dnmcat' : forall l1 l2 P1 P2, DoesNotMatch (Concat P1 P2) (l1 ++ l2) ->\n                                 DoesNotMatch P1 l1 \\/ (exists l3 l4, PegMatch P1 (l1 ++ l2) (Some (l3, l4)) /\\ DoesNotMatch P2 l4).\n    intros l1 l2 P1 P2 H.\n    assert (DoesNotMatch P1 l1 \\/ ~ (DoesNotMatch P1 l1)) by apply lem.\n    inversion H0; try (left; assumption).\n    right. unfold DoesNotMatch in H1.\n    assert ((exists l3 l4 : list Σ, PegMatch P1 l1 (Some (l3, l4))) \\/ ~(exists l3 l4 : list Σ, PegMatch P1 l1 (Some (l3, l4)))) by apply lem.\n    inversion H2.\n    2: {\n      exfalso.\n      eapply H1.\n      intros l2' l3' H'.\n      eapply H3.\n      exists l2'. exists l3'. exact H'.\n    }\n    inversion H3.\n    inversion H4.\n    apply list_split in H5 as HLS1. subst l1.\n    assert (WeakenMatch P1 x x0 l2) by eapply MatchWeaken.\n    assert (PegMatch P1 (x ++ x0 ++ l2) (Some (x, x0 ++ l2))) by eauto.\n    assert ((exists l2' l3', PegMatch P2 (x0 ++ l2) (Some (l2', l3'))) \\/ ~(exists l2' l3', PegMatch P2 (x0 ++ l2) (Some (l2', l3')))) by apply lem.\n    inversion H8.\n    {\n      inversion H9. inversion H10.\n      rewrite <- app_assoc in H.\n      assert (PegMatch (Concat P1 P2) (x ++ x0 ++ l2) (Some (x ++ x1, x2))) by eauto using PegMatch.\n      exfalso.\n      eapply H; eauto.\n    }\n    {\n      assert (forall l2' l3', ~ PegMatch P2 (x0 ++ l2) (Some (l2', l3'))).\n      {\n        intros l2' l3' H'.\n        apply H9. exists l2'. exists l3'. exact H'.\n      }\n      unfold not in H10.\n      assert (DoesNotMatch P2 (x0 ++ l2)). { hnf. eapply H10. }\n      exists x. exists (x0 ++ l2). split. rewrite <- app_assoc. all: assumption.\n    }\n  Qed.\n\n  Context (reg_total : forall r l, RegMatch r l true \\/ RegMatch r l false).\n\n\n  Inductive PegI :=\n  | IChar (c : Σ)\n  | IConcat (p1 p2 : PegI)\n  | IConcatR (p2 : PegI)\n  | IChoose (p1 p2 : PegI)\n  | IChooseR (p2 : PegI)\n  | IStar (p1 : PegI)\n  | IReturn.\n\n  Inductive ReturnFreePegI : PegI -> Prop :=\n  | Rfic : forall c, ReturnFreePegI (IChar c)\n  | RfConcat : forall p1 p2, ReturnFreePegI p1 -> ReturnFreePegI p2 -> ReturnFreePegI (IConcat p1 p2)\n  | RfConcatR : forall p2, ReturnFreePegI p2 -> ReturnFreePegI (IConcatR p2)\n  | RfChoose : forall p1 p2, ReturnFreePegI p1 -> ReturnFreePegI p2 -> ReturnFreePegI (IChoose p1 p2)\n  | RfChooseR : forall p2, ReturnFreePegI p2 -> ReturnFreePegI (IChooseR p2)\n  | RfStar : forall p1, ReturnFreePegI p1 -> ReturnFreePegI (IStar p1).\n\n  Inductive WellFormedPegI : PegI -> Prop :=\n  | WellFormedRF : forall p, ReturnFreePegI p -> WellFormedPegI p\n  | WellFormedReturn : WellFormedPegI IReturn.\n\n  Fixpoint PegTranslate (p : PEG) :=\n    match p with\n    | Char c => IChar c\n    | Concat p1 p2 => IConcat (PegTranslate p1) (PegTranslate p2)\n    | OrderedChoice p1 p2 => IChoose (PegTranslate p1) (PegTranslate p2)\n    | PossesiveStar p1 => IStar (PegTranslate p1)\n    end.\n\n  (* Add PegMatch', intending to be plotkin style frame semantics *)\n  Inductive PegMatch' : list (PegI * option (list Σ * list Σ)) ->\n                        list (PegI * option (list Σ * list Σ)) -> Prop :=\n  | PopCharS : forall c l1 l2 t, PegMatch'\n                              ((IChar c, Some (l1, c :: l2)) :: t)\n                              ((IReturn, Some (l1 ++ [c], l2)) :: t)\n  | PopCharF : forall c1 c2 l1 l2 t, eq_dec c1 c2 = false ->\n                                PegMatch'\n                                  ((IChar c1, Some (l1, c2 :: l2)) :: t)\n                                  ((IReturn, None) :: t)\n  | CallCatL : forall p1 p2 l1 l2 t, PegMatch'\n                                  ((IConcat p1 p2, Some (l1, l2)) :: t)\n                                  ((p1, Some (l1, l2)) :: (IConcatR p2, None) :: t)\n  | RetFailCatL : forall p2 t, PegMatch'\n                              ((IReturn, None) :: (IConcatR p2, None) :: t)\n                              ((IReturn, None) :: t)\n  | CallCatR : forall p2 l1 l2 t, PegMatch'\n                                 ((IReturn, Some (l1, l2)) :: (IConcatR p2, None) :: t)\n                                 ((p2, Some (l1, l2)) :: t)\n  | CallChoiceL : forall p1 p2 l1 l2 t, PegMatch'\n                                     ((IChoose p1 p2, Some (l1, l2)) :: t)\n                                     ((p1, Some (l1, l2)) :: (IChooseR p2, Some (l1, l2)) :: t)\n  | RetChoiceLF : forall p2 o t, PegMatch'\n                                       ((IReturn, None) :: (IChooseR p2, o) :: t)\n                                       ((p2, o) :: t)\n  | RetChoiceLS : forall p2 l1 l2 o t, PegMatch'\n                                       ((IReturn, Some (l1, l2)) :: (IChooseR p2, o) :: t)\n                                       ((IReturn, Some (l1, l2)) :: t)\n  | CallStarSubterm : forall p1 l1 l2 t, PegMatch'\n                                      ((IStar p1, (Some (l1, l2))) :: t)\n                                      ((p1, (Some (l1, l2))) :: (IStar p1, (Some (l1, l2))) :: t)\n  | RetStarSubtermS : forall p1 l1 l2 o t, PegMatch'\n                                        ((IReturn, (Some (l1, l2))) :: (IStar p1, o) :: t)\n                                       ((IStar p1, (Some (l1, l2))) :: t)\n  | RetStarSubtermF : forall p1 o t, PegMatch'\n                                  ((IReturn, None) :: (IStar p1, o) :: t)\n                                  ((IReturn, o) :: t).\n\n  Notation WFState s := (Forall (fun x => WellFormedPegI (fst x)) s).\n\n  Lemma PegMatch'PreservesWF : forall s1 s2, WFState s1 ->\n                                        PegMatch' s1 s2 ->\n                                        WFState s2.\n    intros s1 s2 HAll m.\n    destruct s1 eqn:Heqs1. try (exfalso; inversion m).\n    inversion HAll.\n    subst.\n    inversion m; try eauto using Forall, WellFormedPegI.\n    {\n      subst. simpl in H1. inversion H1. subst. inversion H. subst.\n      constructor; eauto using WellFormedPegI.\n      constructor; eauto using WellFormedPegI.\n      simpl. constructor. now constructor.\n    }\n    {\n      constructor. { simpl. eauto using WellFormedPegI. } { subst. inversion H2. subst. eassumption. }\n    }\n    {\n      subst. inversion H2. subst. simpl in H3. inversion H3. subst. inversion H. subst.\n      constructor. { simpl. eauto using WellFormedPegI. } { eassumption. }\n    }\n    {\n      subst. inversion H1. subst. inversion H. subst.\n      constructor. { simpl. eauto using WellFormedPegI. } { constructor; simpl; try eauto using WellFormedPegI, ReturnFreePegI.  }\n    }\n    {\n      subst. inversion H2. subst. simpl in H3. inversion H3. subst. inversion H. subst.\n      constructor; simpl; eauto using WellFormedPegI, ReturnFreePegI.\n    }\n    {\n      subst. inversion H2. subst.\n      constructor; simpl; eauto using WellFormedPegI.\n    }\n    {\n      subst. inversion H1. subst. simpl in H. inversion H. subst.\n      constructor; eauto using WellFormedPegI, ReturnFreePegI.\n    }\n    {\n      subst. inversion H2. subst. simpl in H3. inversion H3. subst.\n      constructor; eauto using WellFormedPegI, ReturnFreePegI.\n    }\n    {\n      subst. inversion H2. subst. simpl in H3. inversion H3. subst.\n      constructor; eauto using WellFormedPegI, ReturnFreePegI.\n    }\n  Qed.\n\n  Lemma TCPegMatch'PreservesWF : forall s1 s2, (TransitiveClosure PegMatch') s1 s2 ->\n                                          Forall (fun x => WellFormedPegI (fst x)) s1 ->\n                                          Forall (fun x => WellFormedPegI (fst x)) s2.\n    intros s1 s2 m.\n    induction m.\n    {\n      eauto using PegMatch'PreservesWF.\n    }\n    {\n      intros s1.\n      assert (\n        Forall\n          (fun x : PegI * option (list Σ * list Σ) =>\n             WellFormedPegI (fst x)) t2) by eauto.\n      eauto using PegMatch'PreservesWF.\n    }\n  Qed.\n\n  Lemma TRCPegMatch'PreservesWF : forall s1 s2, (TransitiveReflexiveClosure PegMatch') s1 s2 ->\n                                          WFState s1 ->\n                                          WFState s2.\n    intros s1 s2 m.\n    apply TRCConv in m.\n    inversion m; try easy. subst.\n    eauto using TCPegMatch'PreservesWF.\n  Qed.\n\n  Lemma PegTranslateWellFormed : forall p, ReturnFreePegI (PegTranslate p).\n    intros p.\n    induction p; eauto using ReturnFreePegI.\n  Qed.\n\n  Definition finally_eq (p : PEG) (i : PegI) :=\n    (forall t l1 l2 l3, PegMatch p l1 (Some (l2, l3)) -> forall l',\n          (TransitiveClosure PegMatch') ((i, Some (l', l1)) :: t) ((IReturn, (Some (l' ++ l2, l3))) :: t)) /\\\n    (forall t l, PegMatch p l None -> forall l',\n          (TransitiveClosure PegMatch') ((i, Some (l', l)) :: t) ((IReturn, None) :: t)).\n\n  (*\n   * I guess we can characterize all of the terminating as follows:\n   * 1) Matches the stuff of the peg, if any\n   * 2) Returns, calling p again\n   * 3) Eventually reaches none\n   * 4) Finishes\n   *)\n\n  (* Tomorrow write that out as a nice definition. *)\n  Lemma finally_eq_peg : forall p l o, PegMatch p l o ->\n                                  forall p', p = PossesiveStar p' ->\n                                        forall l2 l3, o = Some (l2, l3) ->\n                                                 finally_eq p' (PegTranslate p') ->\n                                                 forall l' t,\n                                                   (TransitiveClosure PegMatch')\n                                                     (((PegTranslate p), Some (l', l)) :: t)\n                                                     ((IReturn, Some (l' ++ l2, l3)) :: t).\n    intros p l o m.\n    induction m; try discriminate.\n    {\n      intros p' Heqp' l1 l2 Heqo HFinally l' t.\n      inversion Heqo. inversion Heqp'. subst. rewrite app_nil_r. simpl.\n      assert (PegMatch'\n                ((IStar (PegTranslate p'), Some (l', l2)) :: t)\n                (((PegTranslate p'), Some (l', l2)) :: (IStar (PegTranslate p'), Some (l', l2)) :: t)\n             ) by eauto using PegMatch'.\n      eapply ClosureBase in H.\n      assert ((TransitiveClosure PegMatch')\n                (((PegTranslate p'), Some (l', l2)) :: (IStar (PegTranslate p'), Some (l', l2)) :: t)\n                ((IReturn, None) :: (IStar (PegTranslate p'), Some (l', l2)) :: t)\n             ) by (eapply HFinally; eassumption).\n      assert (PegMatch'\n                ((IReturn, None) :: (IStar (PegTranslate p'), Some (l', l2)) :: t)\n                ((IReturn, Some (l', l2)) :: t)\n             ) by eauto using PegMatch'.\n      eapply ClosureBase in H1.\n      eauto using CloseCompose.\n    }\n    {\n      intros p' Heqp' l5 l6 Heqo HFinally l' t.\n      inversion Heqo. inversion Heqp'. subst. simpl in * |- *.\n      assert (\n         TransitiveClosure PegMatch'\n           ((IStar (PegTranslate p'), Some ((l' ++ l1), l2)) :: t)\n           ((IReturn, Some ((l' ++ l1) ++ l3, l6)) :: t)\n        ) by eauto.\n      rewrite <- app_assoc in H.\n      eapply CloseCompose. 2: exact H.\n      assert (PegMatch'\n                ((IStar (PegTranslate p'), Some (l', l0)) :: t)\n                ((PegTranslate p', Some (l', l0)) :: (IStar (PegTranslate p'), Some (l', l0)) :: t)\n             ) by eauto using PegMatch'.\n      eapply ClosureBase in H0.\n      assert ((TransitiveClosure PegMatch')\n                ((PegTranslate p', Some (l', l0)) :: (IStar (PegTranslate p'), Some (l', l0)) :: t)\n                ((IReturn, Some (l' ++ l1, l2)) :: (IStar (PegTranslate p'), Some (l', l0)) :: t)\n             ) by (eapply HFinally; eassumption).\n      assert (PegMatch'\n                ((IReturn, Some (l' ++ l1, l2)) :: (IStar (PegTranslate p'), Some (l', l0)) :: t)\n                ((IStar (PegTranslate p'), Some (l' ++ l1, l2)) :: t)\n             ) by eauto using PegMatch'.\n      eapply ClosureBase in H2.\n      eauto using CloseCompose.\n    }\n  Qed.\n\n  Lemma SmallstepSimulBigstep : forall p, finally_eq p (PegTranslate p).\n    intros p.\n    induction p.\n    {\n      split.\n      {\n        intros t l1 l2 l3 m l4.\n        inversion m. subst. eauto using ClosureBase, PopCharS.\n      }\n      {\n        intros t l m l'.\n        destruct l eqn:eqnl.\n        { exfalso. eapply NoPegEmp; eassumption. }\n        inversion m. subst.\n        eauto using ClosureBase, PopCharF.\n      }\n    }\n    {\n      simpl.\n      split.\n      {\n        intros t l1 l2 l3 m l4.\n        inversion m. subst.\n        assert (PegMatch'\n                  ((IConcat (PegTranslate p1) (PegTranslate p2), (Some (l4, l1))) :: t)\n                  (((PegTranslate p1), Some (l4, l1)) :: (IConcatR (PegTranslate p2), None) :: t)\n               ) by eapply CallCatL.\n        apply ClosureBase in H.\n        assert (TransitiveClosure PegMatch'\n                  (((PegTranslate p1), Some (l4, l1)) :: (IConcatR (PegTranslate p2), None) :: t)\n                 ((IReturn, Some (l4 ++ l5, l6)) :: (IConcatR (PegTranslate p2), None) :: t)\n               ) by (eapply IHp1; eassumption).\n        assert (PegMatch'\n                  ((IReturn, Some (l4 ++ l5, l6)) :: (IConcatR (PegTranslate p2), None) :: t)\n                  ((PegTranslate p2, (Some (l4 ++ l5, l6))) :: t)\n               ) by eauto using PegMatch'.\n        assert ((TransitiveClosure PegMatch')\n                  (((PegTranslate p2), Some (l4 ++ l5, l6)) :: t)\n                  ((IReturn, Some ((l4 ++ l5) ++ l7, l3)) :: t)\n               ) by (eapply IHp2; eassumption).\n        rewrite <- app_assoc in H2.\n        apply ClosureBase in H1.\n        eauto using CloseCompose.\n      }\n      {\n        intros t l m l'.\n        inversion m.\n        {\n          subst.\n          assert (PegMatch'\n                    ((IConcat (PegTranslate p1) (PegTranslate p2), (Some (l', l))) :: t)\n                    (((PegTranslate p1), Some (l', l)) :: (IConcatR (PegTranslate p2), None) :: t)\n                 ) by eapply CallCatL.\n          apply ClosureBase in H.\n          assert ((TransitiveClosure PegMatch')\n                    ((PegTranslate p1, Some (l', l)) :: (IConcatR (PegTranslate p2), None) :: t)\n                    ((IReturn, None) :: (IConcatR (PegTranslate p2), None) :: t)\n                 ) by (eapply IHp1; eassumption).\n          assert (PegMatch'\n                    (((IReturn, None) :: (IConcatR (PegTranslate p2), None) :: t))\n                    (((IReturn, None) :: t))\n                 ) by eapply RetFailCatL.\n          apply ClosureBase in H1.\n          eauto using CloseCompose.\n        }\n        {\n          subst.\n          assert (PegMatch'\n                    ((IConcat (PegTranslate p1) (PegTranslate p2), (Some (l', l))) :: t)\n                    (((PegTranslate p1), Some (l', l)) :: (IConcatR (PegTranslate p2), None) :: t)\n                 ) by eapply CallCatL.\n          apply ClosureBase in H.\n          assert (TransitiveClosure PegMatch'\n                    (((PegTranslate p1), Some (l', l)) :: (IConcatR (PegTranslate p2), None) :: t)\n                    ((IReturn, Some (l' ++ l1, l2)) :: (IConcatR (PegTranslate p2), None) :: t)\n                 ) by (eapply IHp1; eassumption).\n        assert (PegMatch'\n                  ((IReturn, Some (l' ++ l1, l2)) :: (IConcatR (PegTranslate p2), None) :: t)\n                  ((PegTranslate p2, (Some (l' ++ l1, l2))) :: t)\n               ) by eauto using PegMatch'.\n        apply ClosureBase in H2.\n        assert ((TransitiveClosure PegMatch')\n                  ((PegTranslate p2, (Some (l' ++ l1, l2))) :: t)\n                  ((IReturn, None) :: t)\n               ) by (eapply IHp2; eassumption).\n        eauto using CloseCompose.\n        }\n      }\n    }\n    {\n      split.\n      {\n        eauto using finally_eq_peg.\n      }\n      {\n        intros t l m l'.\n        inversion m.\n      }\n    }\n    {\n      split.\n      {\n        intros t l1 l2 l3 m l4.\n        simpl.\n        inversion m.\n        {\n          subst.\n          Print PegMatch'.\n          assert (PegMatch'\n                    ((IChoose (PegTranslate p1) (PegTranslate p2),\n                       Some (l4, l1)) :: t)\n                    (((PegTranslate p1),\n                       Some (l4, l1)) ::\n                      (IChooseR (PegTranslate p2),\n                        Some (l4, l1)) :: t)) by eauto using PegMatch'.\n          eapply ClosureBase in H.\n          assert ((TransitiveClosure PegMatch')\n                    (((PegTranslate p1),\n                       Some (l4, l1)) ::\n                      (IChooseR (PegTranslate p2),\n                        Some (l4, l1)) :: t)\n                    ((IReturn,\n                       Some (l4 ++ l2, l3)) ::\n                      (IChooseR (PegTranslate p2),\n                        Some (l4, l1)) :: t)) by (eapply IHp1; eassumption).\n          assert (PegMatch'\n                    ((IReturn,\n                       Some (l4 ++ l2, l3)) ::\n                       (IChooseR (PegTranslate p2),\n                         Some (l4, l1)) :: t)\n                    ((IReturn,\n                       Some (l4 ++ l2, l3)) :: t)) by eauto using PegMatch'.\n          eapply ClosureBase in H1.\n          eauto using CloseCompose.\n        }\n        {\n          subst.\n          assert (PegMatch'\n                    ((IChoose (PegTranslate p1) (PegTranslate p2),\n                       Some (l4, l1)) :: t)\n                    (((PegTranslate p1),\n                       Some (l4, l1)) ::\n                      (IChooseR (PegTranslate p2),\n                        Some (l4, l1)) :: t)) by eauto using PegMatch'.\n          eapply ClosureBase in H.\n          assert ((TransitiveClosure PegMatch')\n                    (((PegTranslate p1),\n                       Some (l4, l1)) ::\n                      (IChooseR (PegTranslate p2),\n                        Some (l4, l1)) :: t)\n                    ((IReturn,\n                       None) ::\n                      (IChooseR (PegTranslate p2),\n                        Some (l4, l1)) :: t)) by (eapply IHp1; eassumption).\n          assert (PegMatch'\n                    ((IReturn, None) ::\n                       (IChooseR (PegTranslate p2),\n                         Some (l4, l1)) :: t)\n                    (((PegTranslate p2),\n                       Some (l4, l1)) :: t)) by eauto using PegMatch'.\n          eapply ClosureBase in H1.\n          assert ((TransitiveClosure PegMatch')\n                    (((PegTranslate p2),\n                       Some (l4, l1)) :: t)\n                    ((IReturn, (Some (l4 ++ l2, l3))) :: t)\n                 ) by (eapply IHp2; eassumption).\n          eauto using CloseCompose.\n        }\n      }\n      {\n        intros t l m l'.\n        inversion m.\n        subst.\n        assert (PegMatch'\n                  ((IChoose (PegTranslate p1) (PegTranslate p2),\n                     Some (l', l)) :: t)\n                  (((PegTranslate p1),\n                     Some (l', l)) ::\n                     (IChooseR (PegTranslate p2),\n                       Some (l', l)) :: t)) by eauto using PegMatch'.\n        eapply ClosureBase in H.\n        assert ((TransitiveClosure PegMatch')\n                  (((PegTranslate p1),\n                     Some (l', l)) ::\n                     (IChooseR (PegTranslate p2),\n                       Some (l', l)) :: t)\n                  ((IReturn,\n                     None) ::\n                     (IChooseR (PegTranslate p2),\n                       Some (l', l)) :: t)) by (eapply IHp1; eassumption).\n        assert (PegMatch'\n                  ((IReturn, None) ::\n                     (IChooseR (PegTranslate p2),\n                       Some (l', l)) :: t)\n                  (((PegTranslate p2),\n                     Some (l', l)) :: t)) by eauto using PegMatch'.\n        eapply ClosureBase in H2.\n        assert ((TransitiveClosure PegMatch')\n                  (((PegTranslate p2),\n                     Some (l', l)) :: t)\n                  ((IReturn, None) :: t)\n               ) by (eapply IHp2; eassumption).\n        eauto using CloseCompose.\n      }\n    }\n  Qed.\n\n  Lemma impossible_listapp2 : forall {T}, forall l1 l2 : list T, forall h, l1 = l2 ++ h :: l1 -> False.\n    intros T l1 l2 h H.\n    assert (length (l1) = (length (l2 ++ h :: l1))). { now rewrite H at 1. }\n    rewrite app_length in H0. simpl in H0.\n    lia.\n  Qed.\n\n  Definition frame_invariant (R : (list (PegI * option (list Σ * list Σ))) -> (list (PegI * option (list Σ * list Σ))) -> Prop) := forall s1 s2,\n      R s1 s2 ->\n      forall h prf1 prf2 suf, s1 = (h :: prf1) ++ suf -> s2 = prf2 ++ suf ->\n                         WFState s1 -> (Forall (fun x => ReturnFreePegI (fst x)) prf1) ->\n                         forall suf', WFState suf' -> R ((h :: prf1) ++ suf') (prf2 ++ suf').\n\n  Lemma impossible_listapp3 : forall {T}, forall l1 l2 : list T, forall h, l1 = (h :: l2) ++ l1 -> False.\n    intros T l1.\n    induction l1; try discriminate; try eauto using impossible_listapp.\n  Qed.\n\n  (* just for automation *)\n  Lemma impossible_listapp4 : forall {T}, forall l1 l2 : list T, forall h1 h2, l1 = h1 :: h2 :: l2 ++ l1 -> False.\n    intros. eapply impossible_listapp3 with (l2 := h2 :: l2). simpl. exact H.\n  Qed.\n\n  (* (IConcatR p2, None) :: t = (p :: l0) ++ (IConcat p1 p2, Some (l1, l2)) :: t *)\n\n  Lemma impossible_listapp5 : forall {T}, forall l1 l2 : list T, forall h1 h2 h3, (h1 :: l1) = (h2 :: l2) ++ (h3 :: l1) -> False.\n    intros T l1.\n    induction l1.\n    { intros. inversion H. destruct l2; discriminate. }\n    { intros. inversion H. eapply impossible_listapp2. exact H2. }\n  Qed.\n\n  Lemma Impossible_circularity : forall p, IChooseR p = p -> False.\n    intros p.\n    induction p; try discriminate.\n    intros H. inversion H. eapply IHp; eassumption.\n  Qed.\n\n  Lemma app_cons_distr : forall {T}, forall l1 t : list T, forall h1 h2, (l1 ++ [h1]) ++ (h2 :: t) =\n                                                            l1 ++ (h1 :: h2 :: t).\n    intros T l1.\n    induction l1; try eauto.\n    intros. simpl. rewrite IHl1. reflexivity.\n  Qed.\n\n  (* t = p :: l0 ++ (IReturn, None) :: (IConcatR p2, None) :: t *)\n  Lemma impossible_listapp6 : forall {T}, forall l1 l2 : list T, forall h1 h2 h3,\n      l1 = h1 :: l2 ++ (h2 :: h3 :: l1) -> False.\n    intros.\n    eapply impossible_listapp2 with (l2 := h1 :: l2 ++ [h2]).\n    simpl. rewrite app_cons_distr. eassumption.\n  Qed.\n\n  Lemma impossible_listcons2 : forall {T}, forall l1 : list T, forall h1 h2, l1 = (h1 :: h2 :: l1) -> False.\n    intros T l1.\n    induction l1; try discriminate.\n    intros. inversion H. eapply IHl1; eauto.\n  Qed.\n\n  (*\n   * I don't think I'll be able to prove frame invariance; in fact, with this strict definition,\n   * it's not even true.\n   * So here are some other possibilities:\n   * - [ ] Add a terminating character.\n   * - [ ] Add a recursive characterization with all prefixes and show it implies the forall prf ++ suf\n   * definition.\n   * Rework the definitions to have the (r - (prefixes excluding [] of p)emp) (for choice)\n   * and (r - p*(prefixes excluding [] of p)emp) (for star)\n   * & rework the logical relation for this.\n   * - [ ] Show that, in the case of peg stall, the remainder matcher will not match\n   * (basically, show that pegstalls correspond to prefix-emps.\n   *  So we go from Some x, None to Some x, None, pegstall corresponding to prefixemp)\n   *)\n\n  Lemma PegMatch'FrameInvariant : frame_invariant PegMatch'.\n    unfold frame_invariant.\n    {\n      intros.\n      destruct prf2 eqn:eqprf2.\n      {\n        destruct prf1; subst; simpl in * |- *.\n        {\n          simpl in H. inversion H; subst; simpl in * |- *; try (exfalso; eapply impossible_listcons; solve [eauto]); try (exfalso; eapply impossible_listcons2; solve [eauto]); try (exfalso; eapply Impossible_circularity; solve [eauto]).\n          \n        }\n        {\n          subst. simpl in H. inversion H; try (exfalso; try eapply impossible_listapp3; solve [eauto]); try (exfalso; try eapply impossible_listapp4; solve [eauto]); try (exfalso; try eapply impossible_listcons; solve [eauto]).\n          {\n            destruct l eqn:Heql.\n            { subst. simpl in * |- *. inversion H5. }\n            { subst. simpl in * |- *. inversion H5. subst. exfalso. eapply impossible_listapp2. eauto. }\n          }\n          {\n            subst. simpl in * |- *.\n            destruct l eqn:Heql.\n            { subst. simpl in * |- *. inversion H5. }\n            { subst. simpl in * |- *. inversion H5. subst. simpl in * |- *. exfalso. eapply impossible_listapp2. eauto. }\n          }\n          {\n            subst. simpl.\n            destruct l eqn:Heql.\n            { subst. simpl in * |- *. inversion H5. exfalso; eauto using Impossible_circularity. }\n            { subst. simpl in * |- *. inversion H5. simpl in * |- *. exfalso. eapply impossible_listapp2. eauto. }\n          }\n          {\n            subst. simpl.\n            destruct l eqn:Heql.\n            { inversion H5. }\n            { inversion H5. exfalso; eapply impossible_listapp2; eauto. }\n          }\n          {\n            subst. simpl. inversion H3. subst. simpl in * |- *. inversion H6.\n          }\n          {\n            simpl in * |- *. subst. inversion H3. simpl in * |- *. inversion H6.\n          }\n        }\n      }\n      {\n        subst.\n        destruct l eqn:eql.\n        {\n          subst.\n          destruct prf1 eqn:eqprf1.\n          simpl in * |- *. inversion H; simpl in * |- *; try (exfalso; eapply impossible_listcons; solve [eauto]); try (exfalso; eapply impossible_listcons2; solve [eauto]). { subst. }\n        }\n        destruct prf1 eqn:eqprf1.\n        {\n          simpl in * |- *. inversion H; subst; simpl in * |- *; try (exfalso; try eapply impossible_listapp2; solve [eauto]);\n            try (exfalso; try eapply impossible_listapp3; solve [eauto]); try (exfalso; try eapply impossible_listapp4; solve [eauto]); try (exfalso; try eapply impossible_listcons; solve [eauto]); destruct l eqn:eql; simpl in * |- *; try discriminate; try (exfalso; try eapply impossible_listapp5; solve [eauto]); try (exfalso; try eapply impossible_listcons2; solve [eauto]); try (exfalso; eapply impossible_listapp6; solve [eauto]).\n\n        }\n      }\n    }\n\n  Lemma cycle_free : forall i,\n    ReturnFreePegI i -> forall l1 l2 t o,\n        forall m1 m2 : (TransitiveReflexiveClosure PegMatch')\n                 ((i, Some (l1, l2)) :: t)\n                 ((IReturn, o) :: t),\n          m1 = m2.\n  intros i RF.\n \n  (*\n   * The stack machine Refines the PEG spec if:\n   * you observe the initial instruction, along with the tail of the stack, as In\n   * you observe the _FIRST_ return from this initial instruction, along with the tail of the stack, as Out\n   * You relate that to the PegMatch instr.\n   *)\n  (*\n   * It may be that this first criteria is already met right?\n   * If you do a choice, e.g. \"c\"/\"c\", that changes the tail for the second call.\n   * If you do a star, it also changes the tail for the second call\n   * So s2 is already unique\n   *)\n  Definition finally_eq_inv (p : PEG) (i : PegI) :=\n    ReturnFreePegI i -> forall p, PegTranslate p = i ->\n                            forall l1 l2 t o,\n                              (TransitiveClosure PegMatch')\n                                ((i, Some (l1, l2)) :: t)\n                                ((IReturn, o) :: t) -> PegMatch p l2 o.\n\n  (*\n   * The strongest property that \"probably\" holds looks something like an injection:\n   * for any PegMatch' starting from a state s and ending at a state s',\n   * there is exactly 1 state s_pred, s transitions to s_pred and s_pred transitions to s'.\n   * In other words, no duplicate states in the machine.\n   *)\n\n  Lemma also_impossible_listcons : forall {T}, forall l : list T, forall h1 h2,\n      l = h1 :: h2 :: l -> False.\n    intros T l.\n    induction l; try discriminate.\n    intros h1 h2 HBoth.\n    inversion HBoth.\n    eapply IHl; eassumption.\n  Qed.\n\n  Lemma also_also_impossible_listcons : forall {T}, forall l : list T, forall h1 h2 h3,\n      l = h1 :: h2 :: h3 :: l -> False.\n    intros T l.\n    induction l; try discriminate.\n    intros h1 h2 h3 Hthree.\n    inversion Hthree.\n    eapply IHl; eassumption.\n  Qed.\n\n  (* Lemma dup_impossible_case : forall s1 s2, *)\n  (*     (TransitiveClosure PegMatch') s1 s2 -> *)\n  (*     WFState s1 -> WFState s2 -> *)\n  (*     forall o c l1 l2 t p2, s1 = ((IChar c, Some (l1, c :: l2)) :: t) -> *)\n  (*                       s2 = ((IReturn, Some (l1 ++ [c], l2)) :: (IChooseR p2, o) :: t) -> False. *)\n  (*   intros. subst. *)\n\n  Lemma nostutter : forall s, PegMatch' s s -> False.\n    intros s.\n    destruct s eqn:eqs.\n    {\n      intros H. inversion H.\n    }\n    {\n      intros H.\n      inversion H; try eauto using impossible_listcons.\n    }\n  Qed.\n\n  (* Lemma PegMatch'_nodup : *)\n  (*   forall s s', (TransitiveClosure PegMatch') s s' -> WFState s -> *)\n  (*           exists s__pred, (((TransitiveReflexiveClosure PegMatch') s s__pred) /\\ *)\n  (*                       ((TransitiveClosure PegMatch') s__pred s')) /\\ *)\n  (*   (forall s__pred', (((TransitiveReflexiveClosure PegMatch') s s__pred') /\\ *)\n  (*                       ((TransitiveClosure PegMatch') s__pred' s')) -> s__pred' = s__pred). *)\n  (*   intros s s' m. *)\n  (*   induction m. *)\n  (*   { *)\n  (*     intros HWF. *)\n  (*     exists t1. repeat split; try eauto using ReflexiveBase1, ClosureBase. *)\n  (*     intros s__pred'. *)\n  (*     intros H'. inversion H'. *)\n  (*   } *)\n  (*   { *)\n  (*     destruct H. *)\n  (*     { *)\n  (*       exists ((IChar c, Some (l1, c :: l2)) :: t). split; try (left; reflexivity); split; try eauto using PegMatch'. *)\n  (*       intros s__pred'. intros H'. *)\n  (*       inversion H'. { intros H''. symmetry; assumption. } *)\n  (*       intros Hother. *)\n  (*       inversion Hother. *)\n  (*       { *)\n  (*         subst. apply app_inj_tail in H4. inversion H4. subst. reflexivity. *)\n  (*       } *)\n  (*       { *)\n  (*         subst. inversion H'. { inversion H2. } *)\n  (*         { *)\n  (*           assert (WFState *)\n  (*                     ((IConcat IReturn p2, Some (l1 ++ [c], l2)) *)\n  (*                        :: t0)) by eauto using TCPegMatch'PreservesWF. *)\n  (*           inversion H3. subst. simpl in H6. inversion H6. *)\n  (*           subst. inversion H4. subst. inversion H9. *)\n  (*         } *)\n  (*       } *)\n  (*       { *)\n  (*         subst. *)\n  (*         inversion H'. { inversion H2. } *)\n  (*         { *)\n  (*           assert (WFState *)\n  (*                     ((IReturn, Some (l1 ++ [c], l2)) :: (IConcatR IReturn, None) :: t) *)\n  (*                        ) by eauto using TCPegMatch'PreservesWF. *)\n  (*           inversion H3. subst. simpl in H7. inversion H7. *)\n  (*           subst. simpl in H8. inversion H8. inversion H4. inversion H11. *)\n  (*         } *)\n  (*       } *)\n  (*       { *)\n  (*         subst. *)\n  (*         inversion H'. { inversion H2. } *)\n  (*         assert ( *)\n  (*             WFState ((IChoose IReturn p2, Some (l1 ++ [c], l2)) :: t0) *)\n  (*           ) by eauto using TCPegMatch'PreservesWF. *)\n  (*         inversion H3. subst. simpl in H6. inversion H6. subst. inversion H4. subst. inversion H9. *)\n  (*       } *)\n  (*       { *)\n  (*         subst. *)\n  (*         inversion H'. { inversion H2. } *)\n  (*         assert ( *)\n  (*             WFState ((IReturn, None) :: (IChooseR IReturn, Some (l1 ++ [c], l2)) :: t) *)\n  (*           ) by eauto using TCPegMatch'PreservesWF. *)\n  (*         inversion H3. subst. inversion H7. subst. simpl in H8. inversion H8. inversion H4. inversion H11. *)\n  (*       } *)\n  (*       { *)\n  (*         subst. *)\n  (*         inversion H'. { inversion H2. } *)\n  (*         inversion H2. *)\n  (*         { subst. inversion H3. subst. eapply impossible_listcons in H10. contradiction. } *)\n  (*         { *)\n  (*           inversion Hother. subst. *)\n  (*           subst. *)\n  (*           inversion H4. *)\n  (*           { *)\n  (*             subst. apply app_inj_tail in H7. inversion H7. subst. *)\n  (*           } *)\n  (*         } *)\n  (*       } *)\n  (*     } *)\n  (*   } *)\n\n  Lemma BigStepSimulSmalStep : forall p, finally_eq_inv p (PegTranslate p).\n    intros p.\n    induction p.\n    {\n      split.\n      {\n        Check (PopCharS c _ _ _).\n        intros s1 s2 m.\n        intros t l1 l2 l3 l' Heqt1 Heqt2. subst.\n        assert (m = ClosureBase PegMatch' _ _ (PopCharS c _ _ _)).\n        subst.\n        \n        induction m.\n        {\n          intros t l1 l2 l3 l' Heqt1 Heqt2.\n          subst. inversion H. subst. apply taileq in H5 as Hl2eq. subst.\n          constructor.\n        }\n        {\n          intros t l1 l2 l3 l' Heqt1 Heqt2.\n          subst.\n          eapply IHm with (t := t). { reflexivity. } { }\n        }\n      }\n    }\n  (*\n    Now of course we want to prove the following lemma:\n    PegMatch p l1 (Some (l2, l3)) -> PegMatch'* [(PegTranslate p, l1)] [(IReturn, Some (l2, l3))]\n    PegMatch p l1 None -> PegMatch'* [(PegTranslate p, l1)] [(IReturn, None)]\n    Otherwise, & when ** and match all chars is prohibited: witness of partial match! such that for all r, (pegreg p r) otherwise does not match.\n   *)\n\n  Function PegMatch' (p : PEG) (prf : list Σ) (suf : list Σ) :=\n    (\n      match p with\n      | Char c => (match (prf ++ suf) with | h :: t => if eq_dec c h then Matches (h, t) else Fails | [] => Indeterminate)\n      | Concat p1 p2 => (match PegMatch' p1 prf suf with\n                        | Matches (l1, l2) =>\n                            (match PegMatch' p2 [] l2 with\n                             | Matches (l3, l4) => (l1 ++ l2, l4)\n                             | Fails => Fails\n                             | Indeterminate => Indeterminate)\n                        | Fails => Fails\n                        | Indeterminate => Indeterminate)\n      | OrderedChoice p1 p2 =>\n          (match PegMatch' p1 prf suf with\n           | Matches (l1, l2) => Matches (l1, l2)\n           | Fails => PegMatch' p2 prf suf\n           | Indeterminate => Indeterminate)\n      | PossesiveStar p1 =>\n          (match PegMatch' p1 prf suf with\n           | Matches (l1, l2) => PegMatch p \n          )\n\n\n  Theorem pegreg_correct : forall P r, LR P r (PEGREG P r). intros P.\n    induction P.\n    {\n      intros r.\n      unfold LR.\n      repeat split.\n      {\n        unfold some_implies_match.\n        intros l1 l2 l3 prf suf m Heql3 mr.\n        inversion m.\n        subst.\n        simpl.\n        replace (c :: prf) with ([c] ++ prf) by reflexivity.\n        eapply RConcatS; eauto using RegMatch.\n      }\n      {\n        unfold none_implies_nomatch.\n        intros l1 HNoMatch.\n        destruct l1 eqn:Hl1.\n        {\n          simpl. constructor. intros l1' l1'' HSplit.\n          symmetry in HSplit.\n          apply catnil in HSplit as HNil.\n          subst l1'.\n          simpl in HSplit.\n          subst l1''.\n          left.\n          constructor.\n        }\n        apply dnmchar in HNoMatch as Hdnmchar.\n        simpl.\n        constructor.\n        intros l1' l1'' HApp.\n        destruct l1'; left; eauto using RegMatch; inversion HApp; eauto using RegMatch.\n      }\n      {\n        unfold blame_remainder.\n        intros l1 l2 l3 prf suf m Heql3 mr.\n        inversion m.\n        subst.\n        simpl.\n        now apply lop.\n      }\n    }\n    {\n      intros r.\n      simpl.\n      repeat split.\n      {\n        intros l1 l2 l3 prf suf m Heql3 mr.\n        inversion m.\n        apply list_split in H5 as HLS2. apply list_split in H3 as HLS1.\n        subst.\n        assert (LR P1 (PEGREG P2 r) (PEGREG P1 (PEGREG P2 r))) by eauto.\n        assert (LR P2 r (PEGREG P2 r)) by eauto.\n        assert (some_implies_match P2 r (PEGREG P2 r)) by apply H0.\n        assert (some_implies_match P1 (PEGREG P2 r) (PEGREG P1 (PEGREG P2 r))) by apply H.\n        assert (RegMatch (PEGREG P2 r) (l6 ++ prf) true) by eauto.\n        rewrite <- app_assoc.\n        eapply H2. { exact H3. } { rewrite <- app_assoc. reflexivity. } { exact H4. }\n      }\n      {\n        intros l HDnm.\n        (* Either p1 does not match all prefixes of l, or it matches a prefix of l, by lem. or maybe we could induct over l\n         *)\n        assert (none_implies_nomatch P1 (PEGREG P2 r) (PEGREG P1 (PEGREG P2 r))) by eapply IHP1.\n        replace l with (l ++ []) in HDnm by eauto using app_nil_r.\n        assert ((DoesNotMatch P1 (l)) \\/ (exists l1 l2, PegMatch P1 (l ++ []) (Some (l1, l2)) /\\ DoesNotMatch P2 l2)). { eapply dnmcat'. exact HDnm. }\n        inversion H0.\n        {\n          now apply H.\n        }\n        {\n          rewrite app_nil_r in H1.\n          inversion H1. inversion H2. inversion H3.\n          assert (none_implies_nomatch P2 r (PEGREG P2 r)) by eapply IHP2.\n          assert (RegMatch (PEGREG P2 r) x0 false) by eauto.\n          assert (blame_remainder P1 (PEGREG P2 r) (PEGREG P1 (PEGREG P2 r))). { eapply IHP1. }\n          unfold blame_remainder in H8.\n          apply list_split in H4 as HLS. rewrite HLS.\n          apply H8 with (l1 := l) (l2 := x) (l3 := x0) (prf := x0) (suf := []); eauto using app_nil_r.\n        }\n      }\n      {\n        intros l1 l2 l3 prf suf m Heql3 mr.\n        inversion m.\n        subst.\n        assert (blame_remainder P2 r (PEGREG P2 r)) as HBlameRemainder by eapply IHP2.\n        assert (blame_remainder P1 (PEGREG P2 r) (PEGREG P1 (PEGREG P2 r))) as HBlameRemainder0 by eapply IHP1.\n        rewrite <- app_assoc.\n        eapply list_split in H3 as HLS1. eapply list_split in H5 as HLS2. subst.\n        eapply HBlameRemainder0.\n        { exact H3. }\n        { rewrite <- app_assoc. reflexivity. }\n        {\n          eapply HBlameRemainder. { exact H5. } { reflexivity. } { exact mr. }\n        }\n      }\n    }\n    {\n      assert (forall r, some_implies_match (PossesiveStar P) r (PEGREG (PossesiveStar P) r)) as HSM.\n      {\n        intros r'.\n        unfold some_implies_match.\n        intros l1 l2 l3 prf suf m Heql3 mr.\n        apply StarImpliesRemainderFail in m as HCF.\n        eapply SomeImpliesMatchStarStrong; try eauto.\n        rewrite <- Heql3. reflexivity.\n      }\n      assert (forall r, blame_remainder (PossesiveStar P) r (PEGREG (PossesiveStar P) r)) as HBM.\n      {\n        intros r l1 l2 l3 prf suf HMatch.\n        admit.\n      }\n      intros r.\n      repeat split.\n      eapply HSM.\n      {\n        intros l1 Hdnm.\n        destruct l1 eqn:Heql1.\n        {\n          simpl.\n          assert (RegMatch r [] true \\/ RegMatch r [] false) by eauto using reg_total.\n          constructor.\n          intros prf suf HApp.\n          symmetry in HApp. eapply catnil in HApp as HNil. subst prf. simpl in HApp.subst suf.\n          inversion H.\n          {\n            right. split. { constructor. exists []. split; eauto. }\n            constructor.\n            { unfold RSetMinus. eapply RIntersectionFR. constructor. constructor. { constructor. exists []. split; eauto. } assumption. }\n            {\n              \n            }\n          }\n          constructor.\n          intros l1' l1'' H'.\n          symmetry in H'.\n          eapply catnil in H' as Hcnl.\n          subst l1'. simpl in H'. subst l1''.\n          right. split.\n          { constructor. exists []; split; eauto. }\n          { constructor. }\n        }\n        unfold DoesNotMatch in Hdnm.\n      }\n      eapply HBM.\n      assert (blame_remainder (PossesiveStar P) r (PEGREG (PossesiveStar P) r)) as HBL.\n      {\n        unfold none_implies_nomatch.\n        intros l1 H.\n        simpl.\n        unfold DoesNotMatch in H.\n      }\n    }\n  (* Fixpoint LR (P : PEG) (r__cont) : Prop := *)\n  (*   forall l1 l2 l3, (some_implies_match P r__cont) /\\ (none_implies_nomatch P r__cont) /\\ *)\n  (*                 (match P with *)\n  (*                  | Char c => True *)\n  (*                  | Concat p1 p2 => forall r, LR p2 r -> LR P (PEGREG p1 r) *)\n  (*                  | PossesiveStar p1 => forall r, LR ) *)\n\n  Lemma unmatchable_remainder : forall p1, forall l1 l2 l3, forall r,\n      PegMatch p1 l1 (Some (l2, l3)) -> RegMatch r l3 false ->\n      RegMatch (PEGREG p1 r) l1 false.\n    intros p1 l1 l2 l3 r.\n    generalize dependent l3.\n    generalize dependent l2.\n    generalize dependent l1.\n    generalize dependent r.\n    induction p1.\n    {\n      intros r l1 l2 l3 H1 H2.\n      simpl.\n      inversion H1.\n      subst.\n      now eapply lop.\n    }\n    {\n      intros r l1 l2 l3 H1 H2.\n      simpl.\n      inversion H1.\n      subst.\n      assert (RegMatch (PEGREG p1_2 r) l5 false); eauto.\n    }\n    {\n      intros r l1 l2 l3 H1 H2.\n      inversion H1.\n      {\n        simpl.\n        subst.\n        constructor.\n        {\n          clear IHp1.\n          clear H1.\n          induction p1.\n          {\n            simpl.\n            replace l3 with ([] ++ l3); try easy.\n            eapply RStarF.\n            {\n              inversion H4.\n              subst.\n              now constructor.\n            }\n            {\n              constructor.\n            }\n          }\n          {\n            simpl.\n          }\n        }\n      }\n    }\n    intros r; induction r.\n    {\n      intros l1 l2 l3 H1 H2.\n      simpl.\n      inversion H1.\n      subst.\n      constructor.\n      intros l1' l1'' H.\n      destruct l1'.\n      {\n        left.\n        constructor.\n      }\n      {\n        destruct l1'.\n        2: left; eapply RCharF2.\n        inversion H.\n        subst.\n        right.\n        split; eauto using RegMatch.\n      }\n    }\n    {\n      intros l1 l2 l3 H1 H2.\n      inversion H1.\n      subst.\n      eapply lop.\n      exact H2.\n    }\n    {\n      intros l1 l2 l3 H1 H2.\n      simpl.\n      \n    }\n\n  Lemma unmatchable_p1 : forall p1, forall l,\n      PegMatch p1 l None -> forall r, RegMatch (PEGREG p1 r) l false.\n    intros p1.\n    induction p1.\n    {\n      intros l H r.\n      simpl.\n      inversion H.\n      subst.\n      constructor.\n      intros l1' l1'' H2.\n      destruct l1'.\n      {\n        simpl in H2.\n        subst.\n        left.\n        constructor.\n      }\n      {\n        simpl in H2.\n        inversion H2.\n        subst.\n        left.\n        eapply RCharF1; eauto.\n      }\n    }\n    {\n      intros l H r.\n      inversion H.\n      {\n        subst.\n        simpl.\n        now eapply IHp1_1.\n      }\n      {\n        subst.\n        simpl.\n        assert (RegMatch (PEGREG p1_2 r) l2 false) by eauto.\n        \n      }\n    }\n\n  Lemma unmatchable_p2 : forall p2 p1, forall l1 l2,\n      PegMatch p1 l1 (Some (l1, l2)) -> PegMatch p2 l2 None ->\n      forall r, RegMatch (PEGREG p1 (PEGREG p2 r)) l1 false.\n    intros p2.\n    induction p2.\n    {\n      intros p1.\n      induction p1.\n      {\n        intros l2 l0 H1 H2 r.\n        simpl.\n        inversion H1.\n        subst.\n        replace [c0] with ([c0] ++ []) by eauto.\n        eapply RConcatF.\n        intros l1'.\n        destruct l1'; try eauto using RegMatch.\n        intros l1''.\n        destruct l1''.\n        {\n          intros H.\n          right.\n          split.\n          {\n            simpl in H.\n            inversion H.\n            subst.\n            rewrite app_nil_r in H4.\n            rewrite H4.\n            constructor.\n          }\n          {\n            eapply concat_char_nomatch_emp.\n          }\n        }\n        {\n          intros H.\n          replace ([c0] ++ []) with [c0] in H. 2: rewrite app_nil_r; reflexivity.\n          apply two_one_length_one_one_length_impossible in H.\n          contradiction.\n        }\n      }\n      {\n        intros l1 l2 H1 H2 r.\n        simpl.\n        \n        eapply IHp1_1.\n      }\n    }\n\n  Theorem PEGREG_implies_reg : PEGREG_implies_reg_statement.\n    unfold PEGREG_implies_reg_statement.\n    intros p.\n    induction p.\n    {\n      intros r1 r2 l1 l2 l3 H1.\n      repeat split.\n      {\n        intros H2 H3.\n        simpl in H1.\n        subst r2.\n        apply list_split in H2 as Hl1eq.\n        inversion H2.\n        subst.\n        replace (c :: l3) with ([c] ++ l3) by auto.\n        constructor; eauto using RegMatch.\n      }\n      {\n        intros H.\n        simpl in H1.\n        inversion H.\n        subst.\n        eauto using RegMatch.\n      }\n      {\n        intros H.\n        unfold PEGREG__init.\n        inversion H.\n        constructor.\n      }\n    }\n    {\n      intros r1 r2 l1 l2 l3 H1.\n      repeat split.\n      {\n        intros H2 H3.\n        apply list_split in H2 as HLS.\n        simpl in H1.\n        inversion H2.\n        subst l7. subst l2. subst l1. subst l0. subst p3. subst p1.\n        remember (PEGREG p2 r1).\n        assert (RegMatch r l5 true).\n        {\n          symmetry in Heqr.\n          eapply IHp2. exact Heqr. exact H8. exact H3.\n        }\n        rewrite <- app_assoc.\n        apply list_split in H8 as HLS.\n        rewrite <- HLS.\n        rewrite <- app_assoc in H6.\n        rewrite <- HLS in H6.\n        eapply IHp1; eassumption.\n      }\n      {\n        intros H.\n        inversion H.\n        {\n          subst.\n          simpl PEGREG.\n          remember (PEGREG p1 (PEGREG p2 r1)).\n          symmetry in Heqr.\n          eapply IHp1; eauto.\n        }\n        {\n          subst.\n          simpl PEGREG.\n          assert ((PEGREG p2 r1) )\n        }\n      }\n    }\n    {\n      intros r1 r2 l1 l2 l3 H1 H2 H3.\n      apply list_split in H2 as HLS.\n      simpl in H1.\n      inversion H2.\n      subst l3. subst l2. subst l1. subst p1. clear HLS.\n      {\n\n      }\n    }\n", "meta": {"author": "jsalzbergedu", "repo": "pegreg", "sha": "46a7e75b5fa288d3050f18290fa73b19176222d9", "save_path": "github-repos/coq/jsalzbergedu-pegreg", "path": "github-repos/coq/jsalzbergedu-pegreg/pegreg-46a7e75b5fa288d3050f18290fa73b19176222d9/fixpoint_semantics/rework.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6864645661076707}}
{"text": "Lemma id_P : forall P:Prop, P -> P.\n  intros.\n  exact H.\nQed.\n\nLemma id_PP : forall P:Prop, (P -> P) -> P -> P.\n  intros.\n  assumption.\nQed.\n\nLemma imp_trans : forall P Q R :Prop, (P -> Q) -> (Q -> R) -> P -> R.\n  intros.\n  apply H0.\n  apply H.\n  apply H1.\nQed.\n\nLemma imp_perm :  forall P Q R :Prop, (P -> Q -> R) -> Q -> P -> R.\n  intros.\n  apply H;assumption.\nQed.\n\nLemma ignore_Q : forall P Q R :Prop, (P -> R) -> P -> Q -> R.\n  intros.\n  apply H.\n  assumption.\nQed.\n\nLemma delta_imp :  forall P Q :Prop,(P -> P -> Q) -> P -> Q.\n  intros.\n  apply H;assumption.\nQed.\n  \nLemma delta_impR :forall P Q :Prop, (P -> Q) -> P -> P -> Q.\n  intros.\n  apply H.\n  apply H0.\nQed.\n\nLemma diamond : forall P Q R T:Prop, (P -> Q) -> \n                                  (P -> R) -> \n                                  (Q -> R -> T) -> \n                                  P -> T.\n  intros.\n  apply H1;[apply H|apply H0];assumption.\nQed.\n\nLemma weak_peirce : forall P Q:Prop, ((((P -> Q) -> P) -> P) -> Q) -> Q.\n  intros.\n  apply H.\n  intros.\n  apply H0.\n  intros.\n  apply H.\n  intros.\n  apply H1.\nQed.  \n\nSection A_declared.\n  Variables \n    (A : Set )\n    (P Q : A->Prop)\n    (R : A->A->Prop).\n  Goal (forall a b:A, R a b) -> forall a b:A, R b a.\n    intros.\n    apply H.\n  Qed.\n  Goal (forall a:A, P a -> Q a) -> (forall a:A, P a) -> forall a:A, Q a.\n    intros.\n    apply H.\n    apply H0.\n  Qed.\n  Goal (forall a b:A, R a b) -> forall a:A, R a a.\n    intros.\n    apply H.\n  Qed.\nEnd A_declared.\n\nGoal forall P:Prop, ~ ~ ~ P -> ~ P.\n  intros.\n  unfold not.\n  intros.\n  apply H.\n  unfold not.\n  intros.\n  apply H1.\n  assumption.\nQed.\n\nGoal forall P Q:Prop, ~ ~ ~ P -> P -> Q.\n  unfold not.\n  intros.\n  elim H.\n  intros.\n  apply H1.\n  assumption.\nQed.\n\nGoal forall P Q:Prop, (P -> Q) -> ~ Q -> ~ P.\n  unfold not.\n  intros.\n  apply H0.\n  apply H.\n  apply H1.\nQed.\n\nGoal forall P Q R:Prop, (P -> Q) -> (P -> ~ Q) -> P -> R.\n  unfold not.\n  intros.\n  elim H0;[|apply H];assumption.\nQed.\n\nDefinition dyslexic_imp := forall P Q:Prop, (P->Q)->Q->P.\n\nDefinition dyslexic_contrap :=forall P Q:Prop,(P->Q)->~P->~Q.\n\nGoal dyslexic_imp -> False.\n  unfold dyslexic_imp.\n  intros.\n  apply (H False True);trivial.\nQed.\n\nGoal dyslexic_contrap -> False.\n  unfold dyslexic_contrap.\n  intros.\n  apply (H False True);unfold not;trivial.\nQed.\n\nTheorem abcd_c : forall (A:Set)(a b c d:A), a=c \\/ b= c \\/ c=c \\/ d=c.\n  intros.\n  right.\n  right.\n  left.\n  reflexivity.\nQed.\n\nLemma and_assoc : forall A B C:Prop, A /\\ (B /\\ C) -> (A /\\ B) /\\ C.\n  intros.\n  apply and_assoc.\n  assumption.\nQed.\n\nLemma and_imp_dist : forall A B C D:Prop,\n                     (A -> B) /\\ (C -> D) -> A /\\ C -> B /\\ D.\n  intros.\n  destruct H.\n  destruct H0.\n  split;[apply H|apply H1];assumption.\nQed.\n\nLemma not_contrad : forall A : Prop, ~(A /\\ ~A).\n  unfold not.\n  intros.\n  destruct H.\n  apply H0.\n  apply H.\nQed.\n\nLemma or_and_not : forall A B : Prop, (A\\/B)/\\~A -> B.\n  unfold not.\n  intros.\n  destruct H.\n  destruct H;[elim H0|];apply H.\nQed.\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\nLtac first_step := \n       try unfold peirce;\n       try unfold classic;\n       try unfold excluded_middle;\n       try unfold de_morgan_not_and_not;\n       try unfold implies_to_or;\n       try unfold not;\n       split;\n       intros.\n\nGoal peirce <-> classic.\n  first_step.\n  apply(H P False);intros;elim H0;assumption.\n  apply H.\n  intros.\n  apply H1.\n  apply H0.\n  intros.\n  apply H.\n  intros.\n  apply H1.\n  assumption.\nQed.\n\nGoal classic <-> excluded_middle.\n  first_step;\n  [\n    apply H;\n    apply H;\n    intros;\n    apply H0;\n    intros;\n    apply H1;\n    right;\n    intros;\n    apply H1;\n    left;\n    unfold not|\n\n    assert(P \\/ (P -> False));\n    [\n      apply H|\n    \n      destruct H1;\n      [|elim H0]\n    ]\n  ];assumption.\nQed.\n\nGoal excluded_middle <-> de_morgan_not_and_not.\n  first_step;\n  [\n    destruct (H P);\n    [\n      left|\n      \n      right;\n      destruct (H Q);\n      [|\n        elim H0;\n        split\n      ] \n    ]|\n    \n    apply H;\n    intros;\n    destruct H0;\n    apply H1\n  ];assumption.\nQed.\n\nGoal de_morgan_not_and_not <-> implies_to_or.\n  first_step;\n  [\n    apply H;\n    intros;\n    destruct H1;\n    apply H1;\n    intros;\n    apply H2;\n    apply H0|\n\n    assert(~~P \\/ ~~Q);\n    [\n      unfold not;\n      apply H;\n      intros;\n      destruct H0;\n      split|\n\n      assert((~P\\/P)/\\(~Q\\/Q));\n      [\n        split;\n        apply H;\n        intros|\n        \n        destruct H1;\n        [left|right];\n        destruct H2;\n        [destruct H2|destruct H3];\n        try assumption;\n        elim H1\n      ]\n    ]\n  ];\n  assumption.\nQed.\n\nSection on_ex. \n  Variables \n    (A:Type)\n    (P Q:A -> Prop).\n  Lemma ex_or : (exists x:A, P x \\/ Q x) -> ex P \\/ ex Q.\n    intros;\n    destruct H;\n    destruct H;\n    [left|right];\n    exists x;\n    assumption.\n  Qed.\n  \n  Lemma ex_or_R : ex P \\/ ex Q -> (exists x:A, P x \\/ Q x).\n    intros;\n    destruct H;\n    destruct H;\n    exists x;\n    [left|right];\n    assumption.\n  Qed.\n  \n  Lemma two_is_three : (exists x:A, forall R : A->Prop, R x) -> 2 = 3.\n    intros;\n    destruct H;\n    apply( H (fun _ => _ = 3) ).\n  Qed.\n\n  Lemma forall_no_ex : (forall x:A, P x) -> ~(exists y:A, ~ P y).\n    intros;\n    unfold not;\n    intros;\n    destruct H0;\n    apply H0;\n    apply H.\n  Qed.\nEnd on_ex.\n\nRequire Import Arith.\n\nTheorem plus_permute2 :\n  forall n m p:nat, n + m + p = n + p + m.\n  intros.\n  rewrite plus_assoc_reverse.\n  rewrite plus_assoc_reverse.\n  rewrite plus_comm.\n  rewrite (plus_comm n).\n  rewrite (plus_comm p).\n  reflexivity.\nQed.\n\nGoal forall (A:Set) (a b c:A), a = b -> b = c -> a = c.\n  intros.\n  rewrite <- H0.\n  assumption.\nQed.\n\nDefinition my_False : Prop := forall P:Prop, P.\n\nDefinition my_not (P:Prop) : Prop := P -> my_False.\n\nNotation \"! x\"  := (my_not x)(at level 1, no associativity).\n\nGoal forall P:Prop, ! ! ! P -> ! P.\n  unfold my_not.\n  intros.\n  apply H.\n  intros.\n  apply H0.\n  assumption.\nQed.\n\nGoal forall P Q:Prop, ! ! ! P -> P -> Q.\n  unfold my_not.\n  intros.\n  apply H.\n  intros.\n  apply H0.\n  assumption.\nQed.\n\nGoal forall P Q:Prop, (P -> Q) -> ! Q -> ! P.\n  unfold my_not.\n  intros.\n  apply H0.\n  apply H.\n  assumption.\nQed.\n\nGoal forall P Q R:Prop, (P -> Q) -> (P -> ! Q) -> P -> R.\n  unfold my_not.\n  intros.\n  apply H0;\n  try apply H;\n  assumption.\nQed.\n\nRequire Import Relations.\n\nSection impredicative_eq.\n  Variable A : Set.\n  Set Implicit Arguments.\n  Definition impredicative_eq (a b:A) : Prop := forall P:A -> Prop, P a -> P b.\n  Ltac first_step := \n    unfold\n      symmetric,\n      reflexive,\n      transitive,\n      equiv,\n      inclusion,\n      impredicative_eq.\n  Theorem impredicative_eq_sym : symmetric A impredicative_eq.\n    first_step.\n    intros a b H Q.\n    apply H.\n    trivial.\n  Qed.\n\n  Theorem impredicative_eq_refl : reflexive A impredicative_eq.\n    first_step.\n    intros.\n    assumption.\n  Qed.\n\n  Theorem impredicative_eq_trans :  transitive A impredicative_eq.\n    first_step.\n    intros.\n    apply H0.\n    apply H.\n    assumption.\n  Qed.\n\n  Theorem impredicative_eq_equiv : equiv A impredicative_eq.\n    unfold equiv.\n    repeat split.\n    apply impredicative_eq_refl.\n    apply impredicative_eq_trans.\n    apply impredicative_eq_sym.\n  Qed.\n\n  Theorem impredicative_eq_least :\n    forall R:relation A, reflexive A R -> inclusion A impredicative_eq R.\n    first_step.\n    intros.\n    apply H0.\n    apply H.\n  Qed.\n\n  Theorem impredicative_eq_eq : forall a b:A, impredicative_eq a b -> a = b.\n    first_step.\n    intros.\n    apply H.\n    reflexivity.\n  Qed.\n\n  Theorem eq_impredicative_eq : forall a b:A, a = b -> impredicative_eq a b.\n    first_step.\n    intros.\n    rewrite <- H.\n    assumption.\n  Qed.\n  \n  Theorem impredicative_eq_ind :\n    forall (x:A) (P:A -> Prop), P x -> forall y:A, impredicative_eq x y -> P y.\n    first_step.\n    intros.\n    apply H0.\n    assumption.\n  Qed.\nEnd impredicative_eq.\n\nDefinition my_and (P Q:Prop) : Prop := forall R:Prop, (P -> Q -> R) -> R.\n\nDefinition my_or (P Q:Prop) : Prop :=\n  forall R:Prop, (P -> R) -> (Q -> R) -> R.\n\nDefinition my_ex (A:Set) (P:A -> Prop) : Prop :=\n  forall R:Prop, (forall x:A, P x -> R) -> R.\n\nTheorem my_and_left : forall P Q:Prop, my_and P Q -> P.\n  unfold my_and.\n  intros.\n  apply H.\n  intros.\n  assumption.\nQed.\n\nTheorem my_and_right : forall P Q:Prop, my_and P Q -> Q.\n  unfold my_and.\n  intros.\n  apply H.\n  intros.\n  assumption.\nQed.\n\nTheorem my_and_ind : forall P Q R:Prop, (P -> Q -> R) -> my_and P Q -> R.\n  unfold my_and.\n  intros.\n  apply H0.\n  assumption.\nQed.\n\nTheorem my_or_introl : forall P Q:Prop, P -> my_or P Q.\n  unfold my_or.\n  intros.\n  apply H0.\n  assumption.\nQed.\n\nTheorem my_or_intror : forall P Q:Prop, Q -> my_or P Q.\n  unfold my_or.\n  intros.\n  apply H1.\n  assumption.\nQed.\n\nTheorem my_or_ind : forall P Q R:Prop, (P -> R) -> (Q -> R) -> my_or P Q -> R.\n  unfold my_or.\n  intros.\n  apply H1;\n  assumption.\nQed.\n\nTheorem my_or_False : forall P:Prop, my_or P my_False -> P.\n  unfold my_or, my_False.\n  intros.\n  apply H.\n  trivial.\n  intros.\n  apply H0.\nQed.\n\nTheorem my_or_comm : forall P Q:Prop, my_or P Q -> my_or Q P.\n  unfold my_or.\n  intros.\n  apply H;\n  assumption.\nQed.\n\nTheorem my_ex_intro : forall (A:Set) (P:A -> Prop) (a:A), P a -> my_ex P.\n  unfold my_ex.\n  intros.\n  apply(H0 a).\n  assumption.\nQed.\n\nTheorem my_not_ex_all :\n  forall (A:Set) (P:A -> Prop), my_not (my_ex P) -> forall a:A, my_not (P a).\n  unfold my_ex, my_not.\n  intros.\n  apply H.\n  intros.\n  apply(H1 a).\n  assumption.\nQed.\n\nTheorem my_ex_ex : forall (A:Set) (P:A -> Prop), my_ex P -> ex P.\n  unfold my_ex.\n  intros.\n  apply H.\n  intros.\n  exists x.\n  assumption.\nQed.\n\nDefinition my_le (n p:nat) :=\n  forall P : nat -> Prop,\n    P n ->\n      (forall q : nat, P q -> P (S q)) ->\n        P p.\n\nTheorem my_le_n : forall n:nat, my_le n n.\n  unfold my_le.\n  intros.\n  assumption.\n\nTheorem my_le_S : forall n p:nat,\n                   my_le n p -> my_le n (S p).\n  unfold my_le.\n  intros.\n  apply H1.\n  apply H;\n  assumption.\nQed.\n\nTheorem my_le_le : forall n p:nat,\n                    my_le n p -> n <= p.\n  unfold my_le.\n  intros.\n  apply H.\n  constructor.\n  intros.\n  constructor.\n  assumption.\nQed.", "meta": {"author": "DKXXXL", "repo": "CoqArt", "sha": "ae8f577a618aeb7182c4478642a9d5ce4b289b46", "save_path": "github-repos/coq/DKXXXL-CoqArt", "path": "github-repos/coq/DKXXXL-CoqArt/CoqArt-ae8f577a618aeb7182c4478642a9d5ce4b289b46/Chapter5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.6864203582856014}}
{"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\nSection Exponentiation.\n\n(* Why3 goal *)\nVariable t : Type.\nHypothesis t_WhyType : WhyType t.\nExisting Instance t_WhyType.\n\n(* Why3 goal *)\nVariable one: t.\n\n(* Why3 goal *)\nVariable infix_as: t -> t -> t.\n\n(* Why3 goal *)\nHypothesis Assoc : forall (x:t) (y:t) (z:t), ((infix_as (infix_as x y)\n  z) = (infix_as x (infix_as y z))).\n\n(* Why3 goal *)\nHypothesis Unit_def_l : forall (x:t), ((infix_as one x) = x).\n\n(* Why3 goal *)\nHypothesis Unit_def_r : forall (x:t), ((infix_as x one) = x).\n\n(* Why3 goal *)\nHypothesis Comm : forall (x:t) (y:t), ((infix_as x y) = (infix_as y x)).\n\n(* Why3 goal *)\nDefinition power: t -> Z -> t.\nintros x n.\nexact (iter_nat (Zabs_nat n) t (fun acc => infix_as x acc) one).\nDefined.\n\n(* Why3 goal *)\nLemma Power_0 : forall (x:t), ((power x 0%Z) = one).\nProof.\neasy.\nQed.\n\n(* Why3 goal *)\nLemma Power_s : forall (x:t) (n:Z), (0%Z <= n)%Z -> ((power x\n  (n + 1%Z)%Z) = (infix_as x (power x n))).\nProof.\nintros x n h1.\nunfold power.\nfold (Zsucc n).\nnow rewrite Zabs_nat_Zsucc.\nQed.\n\n(* Why3 goal *)\nLemma Power_s_alt : forall (x:t) (n:Z), (0%Z < n)%Z -> ((power x\n  n) = (infix_as x (power x (n - 1%Z)%Z))).\nintros x n h1.\nrewrite <- Power_s; auto with zarith.\nf_equal; omega.\nQed.\n\n(* Why3 goal *)\nLemma Power_1 : forall (x:t), ((power x 1%Z) = x).\nProof.\nexact Unit_def_r.\nQed.\n\n(* Why3 goal *)\nLemma Power_sum : forall (x:t) (n:Z) (m:Z), (0%Z <= n)%Z -> ((0%Z <= m)%Z ->\n  ((power x (n + m)%Z) = (infix_as (power x n) (power x m)))).\nProof.\nintros x n m Hn Hm.\nrevert n Hn.\napply natlike_ind.\napply sym_eq, Unit_def_l.\nintros n Hn IHn.\nreplace (Zsucc n + m)%Z with ((n + m) + 1)%Z by ring.\nrewrite Power_s by auto with zarith.\nrewrite IHn.\nnow rewrite <- Assoc, <- Power_s.\nQed.\n\n(* Why3 goal *)\nLemma Power_mult : forall (x:t) (n:Z) (m:Z), (0%Z <= n)%Z -> ((0%Z <= m)%Z ->\n  ((power x (n * m)%Z) = (power (power x n) m))).\nProof.\nintros x n m Hn Hm.\nrevert m Hm.\napply natlike_ind.\nnow rewrite Zmult_0_r, 2!Power_0.\nintros m Hm IHm.\nreplace (n * Zsucc m)%Z with (n * m + n)%Z by ring.\nrewrite Power_sum by auto with zarith.\nrewrite IHm.\nnow rewrite Comm, <- Power_s.\nQed.\n\n(* Why3 goal *)\nLemma Power_mult2 : forall (x:t) (y:t) (n:Z), (0%Z <= n)%Z ->\n  ((power (infix_as x y) n) = (infix_as (power x n) (power y n))).\nProof.\nintros x y.\napply natlike_ind.\napply sym_eq.\nrewrite 3!Power_0.\napply Unit_def_r.\nintros n Hn IHn.\nunfold Zsucc.\nrewrite 3!(Power_s _ _ Hn).\nrewrite IHn.\nnow rewrite Assoc, <- (Assoc y), (Comm y), 2!Assoc.\nQed.\n\nEnd Exponentiation.\n", "meta": {"author": "ssaavedra", "repo": "why3", "sha": "e28f4cda05925849c1c203f56b9f9b49e4bfe5b4", "save_path": "github-repos/coq/ssaavedra-why3", "path": "github-repos/coq/ssaavedra-why3/why3-e28f4cda05925849c1c203f56b9f9b49e4bfe5b4/lib/coq/int/Exponentiation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.7853085859124003, "lm_q1q2_score": 0.6864203472215743}}
{"text": "(*This file contains the proof that a clique generated from the clique \n**inductive type is colorable assuming each vertex is uniquely colored\n**as specified by the setVertices relation*)\nRequire Export ThreeSatReduction.  \n\n(*connecting x_i to each x_j when i <> j preserves colorability*)\nTheorem connectXColorable : forall Gamma Delta G C eta eta' u, \n                              ~In u Delta -> setVertices Gamma C 0 eta' eta -> In (u,3*u,3*u+1,3*u+2) Gamma ->\n                              connectX Gamma Delta (3*u+2) G -> coloring eta' G C. \nProof.\n  intros. genDeps {{ eta; C; eta'}}. remember (3*u+2). induction H2; intros. \n  {constructor. } \n  {subst. destruct(eq_nat_dec u u0). \n   {subst. exfalso. apply H. simpl. auto. }\n   {copy H3. eapply XMapsToU in H0; eauto. copy H1. eapply XMapsToU in H1; eauto.\n    invertHyp. econstructor; eauto. omega. omega. eapply IHconnectX; eauto. intros c. \n    apply H. simpl. auto. }\n  }\nQed. \n\nTheorem cliqueColorable : forall Gamma eta Delta C G eta' U, \n                            setVertices Gamma C 0 eta' eta -> \n                            unique U Delta -> \n                            clique Gamma Delta G -> coloring eta' G C. \nProof.\n  intros. genDeps {{ eta; C; U }}. induction H1; intros; auto. \n  {constructor. eapply IHclique; eauto. inv H0. constructor. inv H2. eauto. \n   eapply connectXColorable; eauto. inv H2. eapply uniqueNotIn; eauto. \n   apply Union_intror. constructor. }\nQed. \n", "meta": {"author": "lexxx320", "repo": "TheoryThinkTank", "sha": "e55c332cecaebf0c7556ca5a7ff74768254db389", "save_path": "github-repos/coq/lexxx320-TheoryThinkTank", "path": "github-repos/coq/lexxx320-TheoryThinkTank/TheoryThinkTank-e55c332cecaebf0c7556ca5a7ff74768254db389/three_sat_to_kcolor_reduction/cliqueColorable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.6864203443497666}}
{"text": "(* Implementation of [FSet A] using lists *)\nRequire Import HoTT HitTactics.\nRequire Import FSets set_interface kuratowski.length prelude dec_fset.\n\nSection Operations.\n  Context `{Univalence}.\n\n  Global Instance list_empty A : hasEmpty (list A) := nil.\n\n  Global Instance list_single A: hasSingleton (list A) A := fun a => cons a nil.\n\n  Global Instance list_union A : hasUnion (list A).\n  Proof.\n    intros l1 l2.\n    induction l1.\n    * apply l2.\n    * apply (cons a IHl1).\n  Defined.\n\n  Global Instance list_membership A : hasMembership (list A) A.\n  Proof.\n    intros a l.\n    induction l as [ | b l IHl].\n    - apply False_hp.\n    - apply (hor (a = b) IHl).\n  Defined.\n\n  Global Instance list_comprehension A: hasComprehension (list A) A.\n  Proof.\n    intros ϕ l.\n    induction l as [ | b l IHl].\n    - apply nil.\n    - apply (if ϕ b then cons b IHl else IHl).\n  Defined.\n\n  Fixpoint list_to_set A (l : list A) :  FSet A :=\n    match l with\n    | nil => ∅\n    | cons a l => {|a|} ∪ (list_to_set A l)\n    end.\n\nEnd Operations.\n\nSection ListToSet.\n  Variable A : Type.\n  Context `{Univalence}.\n\n  Lemma member_isIn (a : A) (l : list A)  :\n    member a l = a ∈ (list_to_set A l).\n  Proof.\n    induction l ; unfold member in * ; simpl in *.\n    - reflexivity.\n    - rewrite IHl.\n      unfold hor, merely, lor.\n      apply path_iff_hprop ; intros z ; strip_truncations ; destruct z as [z1 | z2].\n      * apply (tr (inl (tr z1))).\n      * apply (tr (inr z2)).\n      * strip_truncations ; apply (tr (inl z1)).\n      * apply (tr (inr z2)).\n  Defined.\n\n  Definition empty_empty : list_to_set A ∅ = ∅ := idpath.\n\n  Lemma filter_comprehension (ϕ : A -> Bool) (l : list A)  :\n    list_to_set A (filter ϕ l) =  {| list_to_set A l & ϕ |}.\n  Proof.\n    induction l ; cbn in *.\n    - reflexivity.\n    - destruct (ϕ a) ; cbn in * ; unfold list_to_set in IHl.\n      * refine (ap (fun y => {|a|} ∪ y) _).\n        apply IHl.\n      * rewrite nl.\n        apply IHl.\n  Defined.\n\n  Definition singleton_single (a : A) : list_to_set A (singleton a) = {|a|} :=\n    nr {|a|}.\n\n  Lemma append_union (l1 l2 : list A) :\n    list_to_set A (list_union _ l1 l2) = (list_to_set A l1) ∪ (list_to_set A l2).\n  Proof.\n    induction l1 ; simpl.\n    - apply (nl _)^.\n    - rewrite IHl1, assoc.\n      reflexivity.\n  Defined.\n\n  Fixpoint reverse (l : list A) : list A :=\n    match l with\n    | nil => nil\n    | cons a l => {|a|} ∪ (reverse l) ∪ {|a|}\n    end.\n\n  Lemma reverse_set (l : list A) :\n    list_to_set A l = list_to_set A (reverse l).\n  Proof.\n    induction l ; simpl.\n    - reflexivity.\n    - rewrite IHl, append_union.\n      simpl.\n      symmetry.\n      rewrite nr, comm, <- assoc, idem.\n      apply comm.\n  Defined.\n    \nEnd ListToSet.\n\nSection lists_are_sets.\n  Context `{Univalence}.\n\n  Global Instance lists_sets : sets list list_to_set.\n  Proof.\n    split ; intros.\n    - apply empty_empty.\n    - apply singleton_single.\n    - apply append_union.\n    - apply filter_comprehension.\n    - apply member_isIn.\n  Defined.\nEnd lists_are_sets.\n\nSection refinement_examples.\n  Context `{Univalence}.\n  Context {A : Type}.\n\n  Definition list_all (ϕ : A -> hProp) : list A -> hProp\n    := refinement list list_to_set (all ϕ).\n\n  Lemma list_all_set (ϕ : A -> hProp) (X : list A)\n    : list_all ϕ X = all ϕ (list_to_set A X).\n  Proof.\n    induction X ; try reflexivity.\n  Defined.\n\n  Lemma list_all_intro (X : list A) (ϕ : A -> hProp)\n    : forall (HX : forall a, a ∈ X -> ϕ a), list_all ϕ X.\n  Proof.\n    rewrite list_all_set.\n    intros H1.\n    assert (forall (a : A), a ∈ (list_to_set A X) -> ϕ a) as H2.\n    {\n      intros a H3.\n      rewrite <- (member_isIn A a X) in H3.\n      apply (H1 a H3).\n    }\n    apply (all_intro _ _ H2).\n  Defined.\n\n  Lemma list_all_elim (X : list A) (ϕ : A -> hProp) a\n    : list_all ϕ X -> (a ∈ X) -> ϕ a.\n  Proof.\n    rewrite list_all_set, (member_isIn A a X).\n    apply all_elim.\n  Defined.\n\n  Definition list_exist (ϕ : A -> hProp) : list A -> hProp\n    := refinement list list_to_set (exist ϕ).\n  \n  Lemma list_exist_set (ϕ : A -> hProp) (X : list A)\n    : list_exist ϕ X = exist ϕ (list_to_set A X).\n  Proof.\n    induction X ; try reflexivity.\n  Defined.\n\n  Lemma listexist_intro (X : list A) (ϕ : A -> hProp) a\n    : a ∈ X -> ϕ a -> list_exist ϕ X.\n  Proof.\n    rewrite list_exist_set, (member_isIn A a X).\n    apply exist_intro.\n  Defined.\n\n  Lemma exist_elim (X : list A) (ϕ : A -> hProp)\n    : list_exist ϕ X -> hexists (fun a => a ∈ X * ϕ a).\n  Proof.\n    rewrite list_exist_set.\n    assert (hexists (fun a : A => a ∈ (list_to_set A X) * ϕ a)\n            -> hexists (fun a : A => a ∈ X * ϕ a))\n      as H2.\n    {\n      intros H1.\n      strip_truncations.\n      destruct H1 as [a H1].\n      rewrite <- (member_isIn A a X) in H1.\n      refine (tr(a;H1)).\n    }\n    intros H1.\n    apply (H2 (exist_elim _ _ H1)).\n  Defined.\n\n  Context `{MerelyDecidablePaths A}.\n\n  Global Instance dec_memb a (l : list A) : Decidable (a ∈ l).\n  Proof.\n    induction l as [ | a0 l] ; simpl.\n    - apply _.\n    - unfold Decidable.\n      destruct IHl as [t | p].\n      * apply (inl(tr(inr t))).\n      * destruct (H0 a a0) as [t | p'].\n        ** left.\n           strip_truncations.\n           apply (tr(inl t)).\n        ** refine (inr(fun n => _)).\n           strip_truncations.\n           destruct n as [n1 | n2].\n           *** apply (p' (tr n1)).\n           *** apply (p n2).\n  Defined.\n  \n  Global Instance dec_memb_list : hasMembership_decidable (list A) A.\n  Proof.\n    intros a l.\n    destruct (dec (a ∈ l)).\n    - apply true.\n    - apply false.\n  Defined.\n\n  Lemma fset_list_memb a (l : list A) : a ∈_d (list_to_set A l) = a ∈_d l.\n  Proof.\n    unfold member_dec, dec_memb_list, fset_member_bool.\n    destruct (dec a ∈ (list_to_set A l)), (dec a ∈ l) ; try reflexivity.\n    - contradiction n.\n      rewrite <- (f_member _ list_to_set) in t.\n      apply t.\n    - contradiction n.\n      rewrite (f_member _ list_to_set) in t.\n      apply t.\n  Defined.\n        \n  Definition set_length : list A -> nat\n    := refinement list list_to_set length.\n\n  Definition set_length_nil : set_length nil = 0 := idpath.\n\n  Definition set_length_cons a l\n    : set_length (cons a l) = if (a ∈_d l) then set_length l else S(set_length l).\n  Proof.\n    unfold set_length, refinement.\n    simpl.\n    rewrite length_compute, fset_list_memb.\n    reflexivity.\n  Defined.\nEnd refinement_examples.", "meta": {"author": "nmvdw", "repo": "HITs-Examples", "sha": "c6f756a856768e1217a1f12f7a385948f9bacc9b", "save_path": "github-repos/coq/nmvdw-HITs-Examples", "path": "github-repos/coq/nmvdw-HITs-Examples/HITs-Examples-c6f756a856768e1217a1f12f7a385948f9bacc9b/FiniteSets/implementations/lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.7853085758631158, "lm_q1q2_score": 0.6864203435897078}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Logic.ClassicalChoice.\n\nModule Type NAT_CHOICE.\n\nFixpoint fisrtn_list_from_fun {A: Type} (f: nat -> A) (n: nat) : list A :=\n  match n with\n  | 0 => nil\n  | S m => fisrtn_list_from_fun f m ++ f m :: nil\n  end.\n\nAxiom nat_stepwise_choice: forall {A: Type} (P: list A -> Prop),\n  P nil ->\n  (forall l, P l -> exists a, P (l ++ a :: nil)) ->\n  exists f, forall n, P (fisrtn_list_from_fun f n).\n\nEnd NAT_CHOICE.\n\nModule NatChoice: NAT_CHOICE.\n\nSection NatChoice.\n\nFixpoint fisrtn_list_from_fun {A: Type} (f: nat -> A) (n: nat) : list A :=\n  match n with\n  | 0 => nil\n  | S m => fisrtn_list_from_fun f m ++ f m :: nil\n  end.\n\nContext {A: Type} (P: list A -> Prop).\n\nDefinition State: Type := {l: list A | P l}.\n\nHypothesis H_init: P nil.\n\nDefinition state_nil: State := exist _ nil H_init.\n\nSection step.\n\nVariable F: State -> A.\nHypothesis HF: forall l: State, P (proj1_sig l ++ F l :: nil).\n\nFixpoint step (n: nat): State := \n  match n with\n  | 0 => state_nil\n  | S m => exist _ _ (HF (step m))\n  end.\n\nLemma fisrtn_list_step: forall n, fisrtn_list_from_fun (fun n0 : nat => F (step n0)) n = proj1_sig (step n).\nProof.\n  intros.\n  induction n.\n  + simpl.\n    reflexivity.\n  + simpl.\n    f_equal; auto.\nQed.\n\nEnd step.\n\nLemma nat_stepwise_choice:\n  (forall l, P l -> exists a, P (l ++ a :: nil)) ->\n  exists f, forall n, P (fisrtn_list_from_fun f n).\nProof.\n  intros.\n  assert (forall (l: list A | P l), exists a : A, P (proj1_sig l ++ a :: nil)) as HH; [| clear H].\n  Focus 1. {\n    intros [l ?H].\n    apply H; auto.\n  } Unfocus.\n\n  apply choice in HH.\n  destruct HH as [f ?].\n\n  exists (fun n => f (step f H n)).\n  intros.\n  rewrite fisrtn_list_step.\n\n  apply (proj2_sig (step f H n)).\nQed.\n\nEnd NatChoice.\n\nEnd NatChoice.\n\nExport NatChoice.\n\nLemma nat_coinduction {A: Type}: forall (P: A -> Prop) (R: A -> A -> Prop) a0,\n  P a0 ->\n  (forall a, P a -> exists b, R a b /\\ P b) ->\n  exists l: nat -> A, l 0 = a0 /\\ (forall k, R (l k) (l (S k))).\nProof.\n  intros.\n  pose (Rs := \n            fix Rs (a: A) (l: list A): Prop :=\n              match l with\n              | nil => True\n              | a0 :: l0 => P a0 /\\ R a a0 /\\ Rs a0 l0\n              end).\n  destruct (nat_stepwise_choice (Rs a0)) as [l ?].\n  + simpl; auto.\n  + intro l.\n    revert a0 H.\n    induction l.\n    - simpl; intros.\n      destruct (H0 a0 H) as [a1 [? ?]].\n      exists a1; auto.\n    - simpl; intros ? ? [? [? ?]].\n      specialize (IHl _ H1 H3).\n      destruct IHl as [a1 ?].\n      exists a1; auto.\n  + exists (fun n => match n with 0 => a0 | S n => l n end).\n    split; auto.\n    intros.\n    specialize (H1 (S k)).\n    destruct k; [simpl in H1; tauto |].\n    simpl in H1.\n    rewrite <- app_assoc in H1; simpl in H1.\n    clear H H0.\n    revert a0 H1; induction (fisrtn_list_from_fun l k); intros.\n    - simpl in H1.\n      tauto.\n    - apply (IHl0 a); clear IHl0.\n      simpl in H1.\n      simpl; tauto.\nQed.\n\nLemma nat_coinduction' {A: Type}: forall (P: A -> Prop) (R: A -> A -> Prop) a0,\n  P a0 ->\n  (forall a, P a -> exists b, R a b /\\ P b) ->\n  exists l: nat -> A, l 0 = a0 /\\ (forall k, R (l k) (l (S k))) /\\ (forall k, P (l k)).\nProof.\n  intros.\n  pose (R' := fun (a b: A) => R a b /\\ P b).\n  \n  destruct (nat_coinduction P R' a0 H) as [l [? ?]].\n  + simpl; unfold R'; firstorder.\n  + exists l.\n    split; auto.\n    split; [subst R'; firstorder |].\n    intros.\n    destruct k; [subst; auto |].\n    specialize (H2 k).\n    destruct H2; auto.\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/UnifySL/lib/NatChoice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.6864203417737745}}
{"text": "(** Zainspirowane przez podręcznik\n    #<a class='link' href='https://www.ps.uni-saarland.de/~smolka/drafts/icl2021.pdf'>\n    Modeling and Proving in Computational Type Theory Using the Coq Proof Assistant</a>#\n    (rozdział 14). *)\n\nClass Provability : Type :=\n{\n  Provable : Prop -> Prop;\n  PMP : forall P Q : Prop, Provable (P -> Q) -> Provable P -> Provable Q;\n  PI  : forall P : Prop, Provable (P -> P);\n  PK  : forall P Q : Prop, Provable Q -> Provable (P -> Q);\n  PC  : forall P Q Z : Prop, Provable (P -> Q) -> Provable ((Q -> Z) -> P -> Z)\n}.\n\nSection AbstractProvability.\n\nContext\n  (Prv : Provability).\n\nDefinition Unprovable (P : Prop) : Prop :=\n  ~ Provable P.\n\nDefinition Disprovable (P : Prop) : Prop :=\n  Provable (~ P).\n\nDefinition Consistent (P : Prop) : Prop :=\n  ~ Provable (~ P).\n\nDefinition Independent (P : Prop) : Prop :=\n  ~ Provable P /\\ ~ Provable (~ P).\n\nLemma Independent2Consistent :\n  forall {P : Prop},\n    Independent P -> Consistent P.\nProof.\n  intros P [_ HC]; assumption.\nQed.\n\nLemma Consistent2Unprovable :\n  forall {P : Prop},\n    Consistent P -> Unprovable (~ P).\nProof.\n  compute.\n  intros P C U.\n  apply C. assumption.\nQed.\n\nLemma Provable_contraposition :\n  forall P Q : Prop,\n    Provable (P -> Q) -> ~ Provable Q -> ~ Provable P.\n(* begin hide *)\nProof.\n  intros P Q pq nq p.\n  apply nq. eapply PMP; eassumption.\nQed.\n(* end hide *)\n\nLemma Provable_contraposition' :\n  forall P Q : Prop,\n    Provable (P -> Q) -> Unprovable Q -> Unprovable P.\n(* begin hide *)\nProof.\n  intros P Q pq nq p.\n  apply nq. eapply PMP; eassumption.\nQed.\n(* end hide *)\n\nLemma Provable_Consistent :\n  forall P Q : Prop,\n    Provable (P -> Q) -> Consistent P -> Consistent Q.\n(* begin hide *)\nProof.\n  intros P Q ppq cp dq.\n  apply cp.\n  eapply PMP; cycle 1.\n  - exact dq.\n  - apply PC. assumption.\nQed.\n(* end hide *)\n\nLemma sandwich :\n  forall P Q Z : Prop,\n    Consistent P -> Unprovable Q -> Provable (P -> Z) -> Provable (Z -> Q) -> Independent Z.\n(* begin hide *)\nProof.\n  intros P Q Z cp uq p2z z2q.\n  split.\n  - intros pz. apply uq. eapply PMP; eauto.\n  - eapply Provable_Consistent; eauto.\nQed.\n(* end hide *)\n\nLemma PropExt_PI_Provable : \n  (forall P Q : Prop, (P <-> Q) -> P = Q) ->\n  forall P : Prop,\n    P -> Provable P.\n(* begin hide *)\nProof.\n  intros PropExt P p.\n  assert (H : P <-> (P <-> P)) by tauto.\n  assert (H' : P = (P -> P)) by firstorder.\n  rewrite H'.\n  apply PI.\nQed.\n(* end hide *)\n\nLemma ex_14_1_4 :\n  forall P Q : Prop,\n    Provable (P -> Q) -> Consistent P -> Unprovable Q ->\n      Independent P /\\ Independent Q.\n(* begin hide *)\nProof.\n  intros P Q ppq cp uq. split.\n  - eapply sandwich; eauto. apply PI.\n  - eapply sandwich; eauto. apply PI.\nQed.\n(* end hide *)\n\nLemma PE_Provable_False :\n  (forall P : Prop, Provable False -> Provable P) ->\n  Provable False <-> forall P : Prop, Provable P.\n(* begin hide *)\nProof.\n  intros PE. split.\n  - intros pf P. apply PE. assumption.\n  - intros PPP. apply PPP.\nQed.\n(* end hide *)\n\nLemma Unprovable_False__Consistent_NotFalse :\n  Unprovable False -> Consistent (~ False).\n(* begin hide *)\nProof.\n  unfold Unprovable, Consistent.\n  intros f g.\n  eapply (PMP (~ False) False) in g.\n  - contradiction.\n  - apply PI.\nQed.\n(* end hide *)\n\nLemma Consistent_NotFalse__Consistent_Any :\n  Consistent (~ False) -> exists P : Prop, Consistent P.\n(* begin hide *)\nProof.\n  intros cnf. exists (~ False). assumption.\nQed.\n(* end hide *)\n\nLemma Consistent_Any__Provable_Consistent :\n  (exists P : Prop, Consistent P) ->\n    forall P : Prop, Provable P -> Consistent P.\n(* begin hide *)\nProof.\n(*   unfold Unprovable, Consistent. *)\n  intros [X cx] P p.\n  apply Provable_Consistent with X.\n  - apply PK. assumption.\n  - assumption.\nQed.\n(* end hide *)\n\nLemma Provable_Consistent__Disprovable_Unprovable :\n  (forall P : Prop, Provable P -> Consistent P) ->\n  forall P : Prop, Disprovable P -> Unprovable P.\n(* begin hide *)\nProof.\n  unfold Consistent, Disprovable, Unprovable.\n  intros H P dp np.\n  eapply H; eassumption.\nQed.\n(* end hide *)\n\nLemma Disprovable_Unprovable__Unprovable_False :\n  (forall P : Prop, Disprovable P -> Unprovable P) ->\n    Unprovable False.\n(* begin hide *)\nProof.\n  unfold Disprovable, Unprovable.\n  intros H.\n  apply H.\n  apply PI.\nQed.\n(* end hide *)\n\nEnd AbstractProvability.\n\n#[refine]\n#[export]\nInstance Provability_id : Provability :=\n{|\n  Provable P := P;\n|}.\n(* begin hide *)\nProof.\n  all: tauto.\nDefined.\n(* end hide *)\n\n#[refine]\n#[export]\nInstance Provability_True : Provability :=\n{|\n  Provable _ := True;\n|}.\n(* begin hide *)\nProof.\n  all: tauto.\nDefined.\n(* end hide *)", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/code/Logika/ProvabilityTypeclass.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.6863606088030064}}
{"text": "From Coq Require Import Bool.\n\nTheorem bool_fn_applied_thrice : forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  intros f b. destruct b eqn:B.\n  - destruct (f true) eqn:Q.\n    * rewrite Q. apply Q.\n    * destruct (f false) eqn:R.\n      + apply Q.\n      + apply R.\n  - destruct (f false) eqn:Q.\n    * destruct (f true) eqn:R.\n      + apply R.\n      + apply Q.\n    * rewrite Q. apply Q.\nQed. \n\nTheorem andb_eq_orb : forall (b c : bool),\n  b && c = b || c -> b = c.\nProof.\n  intros b. case b.\n  - simpl. intros c H. rewrite H. reflexivity.\n  - simpl. intros c H. rewrite H. reflexivity.\nQed.\n\n\nLemma lemma_2:\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. simpl. reflexivity.\n  - rewrite Hb. rewrite <- mult_n_O. reflexivity.\nQed.\n\nLemma lemma_1 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q H.\n  destruct H as (HA & HB).\n  apply HB.\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/Destruct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.6863605978230389}}
{"text": "Require Export \"Ascii\". \nRequire Export \"Prop\".\nOpen Scope char_scope.\n\nInductive function : Type:=\n  |fInsert: nat -> ascii->function \n  |fDelete: nat -> function \n  |fId: function.\n\nDefinition beq_ascii n m : bool :=\n  if ascii_dec n m then true else false\n  .\n\nDefinition function_eq (a b:function) : bool :=\n  match a, b with \n  |fDelete n1,fDelete n2 => beq_nat n1 n2\n  |fInsert n1 x1, fInsert n2 x2 => andb (beq_nat n1 n2) (beq_ascii x1 x2)\n  |_,_ =>false\n  end.\n\n\nExample test_function_eq0: function_eq (fDelete 0) (fDelete 0)= true.\nProof. simpl; reflexivity. Qed.\nExample test_function_eq1: function_eq (fDelete 0) (fDelete 3)= false.\nProof. simpl; reflexivity. Qed.\nExample test_function_eq2: function_eq (fInsert 0 \"a\") (fInsert 0 \"a\")= true.\nProof. simpl; reflexivity. Qed.\nExample test_function_eq3: function_eq (fInsert 0 \"a\") (fInsert 0 \"c\")= false.\nProof. simpl; reflexivity. Qed.\n\n\nFixpoint insert1 n x (l:list ascii):list ascii:=\n  match n with \n  |0 => x::l\n  |S n' =>match l with\n    |[] => []\n    |h::l' => h::(insert1 n' x l')\n    end\n  end.\n\nDefinition insert n x (l:list ascii): option (list ascii):=\nif ble_nat (S(length l)) n then None else Some(insert1 n x l).\nExample test_insert0: insert 0 \"a\" [\"0\",\"1\",\"2\",\"3\"] = Some [\"a\",\"0\",\"1\",\"2\",\"3\"].\nProof. simpl; reflexivity. Qed.\nExample test_insert1: insert 2 \"a\" [\"0\",\"1\",\"2\",\"3\"] = Some [\"0\",\"1\",\"a\",\"2\",\"3\"].\nProof. simpl; reflexivity. Qed.\nExample test_insert2: insert 7 \"a\" [\"0\",\"1\",\"2\",\"3\"] = None.\nProof. simpl; reflexivity. Qed.\nExample test_insert3: insert 4 \"a\" [\"0\",\"1\",\"2\",\"3\"] = Some [\"0\",\"1\",\"2\",\"3\",\"a\"].\nProof. simpl; reflexivity. Qed.\nExample test_insert4: insert 5 \"a\" [\"0\",\"1\",\"2\",\"3\"] = None.\nProof. simpl; reflexivity. Qed.\n\nFixpoint delete1 n (l:list ascii):list ascii:=\n  match l with\n   |[] => []\n   |h::l' =>\n    match n with \n     |0 => l'\n     |S n' =>h::(delete1 n' l')\n    end \n  end.\n\nDefinition delete n (l:list ascii): option (list ascii):=\nif ble_nat (length l) n then None else Some(delete1 n l).\n\nExample test_delete0: delete 0 [\"0\",\"1\",\"2\",\"3\"] = Some [\"1\",\"2\",\"3\"].\nProof. simpl; reflexivity. Qed.\nExample test_delete1: delete 2 [\"0\",\"1\",\"2\",\"3\"] = Some [\"0\",\"1\",\"3\"].\nProof. simpl; reflexivity. Qed.\nExample test_delete2: delete 8 [\"0\",\"1\",\"2\",\"3\"] = None.\nProof. simpl; reflexivity. Qed.\nExample test_delete3: delete 3 [\"0\",\"1\",\"2\",\"3\"] = Some [\"0\",\"1\",\"2\"].\nProof. simpl; reflexivity. Qed.\nExample test_delete4: delete 4 [\"0\",\"1\",\"2\",\"3\"] = None.\nProof. simpl. reflexivity. Qed.\n\nDefinition apply (f:function) (l:list ascii): option (list ascii):=\n  match f with \n  |fInsert n x => insert n x l\n  |fDelete n => delete n l\n  |fId => Some l\n  end.\n(*f1 - applied function, f2 - function that we must apply*)\nDefinition OT (f1 f2:function) (server:bool):function:=\n  if function_eq f1 f2 then fId else\n  match f1, f2 with\n   |fId, _ => f2 \n   |_, fId => fId\n   |fInsert n1 x1, fInsert n2 x2 => (*\n    if beq_nat n1 n2 \n     then (\n      if server \n       then fInsert (S n2) x2\n       else f2)\n     else (\n      if ble_nat n1 n2\n       then fInsert (S n2) x2\n       else f2)*)\n    if orb (andb server (beq_nat n1 n2)) (negb(ble_nat n2 n1)) (*server or n1<n2*)\n     then fInsert (S n2) x2\n     else f2\n   |fDelete n1, fInsert n2 x2 => \n    if negb (ble_nat n2 n1) (*n1<n2*)\n     then fInsert (pred n2) x2\n     else f2\n   |fInsert n1 x1, fDelete n2 =>\n    if ble_nat n1 n2 (*n1<=n2*)\n     then fDelete (S n2)\n     else f2\n   |fDelete n1, fDelete n2 => \n    if negb (ble_nat n2 n1) (*n1<n2*)\n     then fDelete (pred n2) \n     else f2\n   end.\nOpen Scope string_scope.\n\nDefinition xor_boolToProp (b1 b2: bool):Prop:=\n  (b1 =false /\\ b2=true)\\/(b2 =false /\\ b1=true).\nDefinition excluded_middle := forall P:Prop, \n  P \\/ ~P.\n\nTheorem ble_nat_neg : forall (n0 n1 : nat),false=ble_nat n0 n1->true=ble_nat n1 n0.\nProof.\n  intros n0. induction n0.\n  Case \"n0=0\".\n   intros. inversion H.\n  Case \"n0=S n0\".\n   intros. destruct n1. \n    reflexivity.\n    simpl. apply IHn0. inversion H. reflexivity.\nQed.\n\nTheorem ble_nat_trans : forall (n0 n1 n2 : nat),true=ble_nat n0 n1->\ntrue = ble_nat n1 n2-> true=ble_nat n0 n2.\nProof.\n  intros n0. induction n0.\n  Case \"n0=0\".\n   intros. reflexivity.\n  Case \"n0=S n0\".\n   intros. destruct n2,n1; try inversion H.\n    inversion H0.\n    apply IHn0 with (n1:=n1).\n     inversion H. reflexivity.\n     inversion H0. reflexivity.\nQed.\n \nTheorem ble_nat_negtrans : forall (n0 n1 n2 : nat),false=ble_nat n0 n1->\nfalse = ble_nat n1 n2-> false=ble_nat n0 n2.\nProof.\n  intros n0. induction n0.\n  Case \"n0=0\".\n   intros. inversion H.\n  Case \"n0=S n0\".\n   intros. destruct n2, n1;try inversion H0.\n    reflexivity.\n    apply IHn0 with (n1:=n1).\n     inversion H. reflexivity.\n     inversion H0. reflexivity.\nQed.\n\nTheorem ble_nat_negtrans1 : forall (n0 n1 n2 : nat),true = ble_nat n0 n1->\nfalse = ble_nat n2 n1-> false=ble_nat n2 n0.\nProof.\n  intros n0. induction n0.\n  Case \"n0=0\".\n   intros. destruct n2,n1;try inversion H0;try inversion H;try reflexivity.\n  Case \"n0=S n0\".\n   intros. destruct n2, n1;try inversion H0.\n    inversion H.\n    apply IHn0 with (n1:=n1).\n     inversion H. reflexivity.\n     inversion H0. reflexivity.\nQed.\n\nTheorem beq_ascii_sym : forall (n1 n2 : ascii),beq_ascii n1 n2=beq_ascii n2 n1.\nProof.\nAdmitted.\n\nTheorem beq_ascii_eq : forall (n1 n2 : ascii),true = beq_ascii n1 n2 -> n1=n2.\nProof.\nAdmitted.\n\nTheorem ble_nat_neg0 : forall n n0 ,  false = beq_nat  n n0 ->true = ble_nat n0 n ->false=ble_nat n n0. \nProof.\n  intros n. induction n.\n   intros. destruct n0. \n    inversion H.\n    inversion H0.\n   intros. destruct n0.\n    reflexivity.\n    simpl. apply IHn.\n     simpl in H,H0. apply H.\n     simpl in H0. apply H0.\nQed.\n  \nTheorem ble_nat_neg1 : forall n n0 ,  false = beq_nat  n n0 ->false = ble_nat n0 n ->true=ble_nat n n0. \nProof.\n  intros n. induction n.\n   intros. reflexivity.\n   intros. destruct n0.\n    inversion H0.\n    simpl. apply IHn.\n     simpl in H,H0. apply H.\n     simpl in H0. apply H0.\nQed.\n\nTheorem ble_nat_neg2 : forall n n0 ,  \ntrue = ble_nat (S n) (n0) -> false = ble_nat n0 n. \nProof.\n  intros n. induction n.\n  intros. destruct n0.\n   inversion H.\n   reflexivity.\n  intros. destruct n0.\n   inversion H.\n   simpl. apply IHn. simpl in H. apply H.\nQed.\n\nTheorem ble_nat_beq : forall n n0 ,  \ntrue = ble_nat n0 (S n) -> false = ble_nat n0 n->true = beq_nat n0 (S n). \nProof.\n  intros n. induction n.\n   intros. destruct n0. inversion H0. destruct n0. reflexivity. inversion H. \n   intros. destruct n0. inversion H0.\n    apply IHn with (n0:=n0).\n     simpl in H. apply H.\n     simpl in H0. apply H0.\nQed.\n\n\nTheorem bleSF : forall n1 n2 , false = ble_nat n1 (S n2)->false = ble_nat n1 (n2).\nProof.\n  intros n1. induction n1.\n   simpl. intros. inversion H.\n   intros. destruct n2.\n    reflexivity.\n    simpl. apply IHn1. simpl in H. apply H.\nQed.\n\n\nTheorem bleST : forall n1 n2 , true = ble_nat (S n1) n2 ->true = ble_nat n1 n2.\nProof.\n  intros n1. induction n1.\n   simpl. intros. destruct n2.\n    inversion H.\n    reflexivity.\n   intros. destruct n2.\n    inversion H.\n    simpl. simpl in H. apply IHn1. apply H.\nQed.\n\n\nTheorem bleSF1 : forall n1 n2 , false = ble_nat n1 n2 ->false = ble_nat (S n1) n2.\nProof.\n  intros n1. induction n1.\n   simpl. intros. inversion H.\n   intros. destruct n2.\n    reflexivity.\n    simpl. apply IHn1. simpl in H. apply H.\nQed.\n\nTheorem ble_nat_neg3 : forall n n0 ,  false = beq_nat (n) (n0)->\nfalse = ble_nat (S n) (n0) -> false = ble_nat n n0. \nProof.\n  intros n. induction n.\n   intros. destruct n0.\n    inversion H.\n    inversion H0.\n   intros. destruct n0.\n    reflexivity.\n    simpl. apply IHn.\n     apply H.\n     simpl in H0. apply H0.\nQed.\n\n\nTheorem insert_len : forall n a l l1,apply (fInsert n a) l = Some l1->S (length l)=length l1.\nProof.\n  intros n a l. generalize n. \n   induction l.\n   Case \"l=[]\".\n    simpl. intros.\n     destruct l1; destruct n0; try inversion H; try reflexivity.\n   Case \"l=x::l\".\n    intros. simpl. destruct l1.\n     destruct n0;simpl in H; unfold insert in H.\n      simpl in H. inversion H.\n      destruct (ble_nat (S (length (x :: l))) (S n0)) in H;inversion H.\n     simpl in H. \n      destruct n0;simpl in H; unfold insert in H.\n       simpl in H. inversion H. simpl. reflexivity.\n       remember (ble_nat (S (length (x :: l))) (S n0)) as ble.\n        destruct ble;inversion H.\n        simpl. apply eq_remove_S. apply IHl with (n:=n0). simpl. unfold insert. \n        simpl in Heqble. simpl. rewrite <- Heqble. reflexivity.\nQed.\n \nTheorem delete_len : forall n l l1,apply (fDelete n) l = Some l1->(length l)=S(length l1).\nProof.\n intros n l. generalize n.\n  induction l.\n  Case \"l=[]\".\n   simpl. intros.\n   destruct l1; destruct n0; inversion H.\n  Case \"l=x::l\".\n   simpl. intros. destruct l1.\n    destruct n0.\n     simpl in H.\n     inversion H.\n     reflexivity. unfold delete in H.  destruct (ble_nat (length (x :: l)) (S n0)); inversion H.\n    simpl. intros. apply eq_remove_S. \n     destruct n0.\n      simpl in H. inversion H.  reflexivity.\n      apply IHl with (n:=n0). simpl. unfold delete in H.  simpl in H. unfold delete. \n       destruct (ble_nat (length l) n0); inversion H. reflexivity.\nQed. \n  \nTheorem OT2 : forall n0 a a0 l,insert1 n0 a0 (insert1 n0 a l) =insert1 (S n0) a (insert1 n0 a0 l).\nProof.\n  intros. generalize n0.\n  induction l.\n   intros. destruct n1; reflexivity.\n   intros.\n    destruct n1; simpl;try rewrite IHl; reflexivity.\nQed.\n  \nTheorem OT3 : forall n n0 a a0 l,true=ble_nat n0 n->\n insert1 n0 a0 (insert1 n a l) = insert1 (S n) a (insert1 n0 a0 l).\nProof.\n intros. generalize dependent n0. generalize dependent n.\n  induction l.\n   intros. destruct n0. reflexivity. destruct n. inversion H. reflexivity.\n   destruct n0. reflexivity. intros. destruct n. inversion H. simpl. \n    rewrite IHl.\n     reflexivity. \n     simpl in H. apply H.\nQed.\n\nTheorem OT5 : forall n n0 a l,true = ble_nat n n0 -> delete1 (S n0) (insert1 n a l) =\ninsert1 n a (delete1 n0 l).\nProof.\n  intros. generalize dependent n0. generalize dependent n.\n   induction l.\n    intros. destruct n0,n;reflexivity.\n    intros.\n     destruct n0,n;try reflexivity.\n      inversion H.\n      simpl. \n       rewrite <-IHl. reflexivity.\n       simpl in H. apply H.\nQed.\n\nTheorem OT6 : forall n n0 a l a4,false = ble_nat (S (length l)) n -> false = ble_nat (S n) n0->\ndelete1 n0 (a4 :: insert1 n a l) =insert1 n a (delete1 n0 (a4 :: l)).\nProof.\n  intros. generalize dependent n0. generalize dependent n. generalize dependent a4.\n   induction l.\n    intros. destruct n0,n; try reflexivity.\n     inversion H0.\n     inversion H.\n    intros. destruct n0,n; try reflexivity.\n     inversion H0.\n     simpl. rewrite <-IHl.\n      reflexivity.\n      simpl in H. apply H.\n      simpl in H0. apply H0.  \nQed.\n\nTheorem OT7 : forall n n0 a l,true = ble_nat n0 n->insert1 n0 a (delete1 n l) =\nmatch insert1 n0 a l with\n         | [] => []\n         | h :: l' => h :: delete1 n l'\n         end.\nProof.\n  intros. generalize dependent n0. generalize dependent n.\n  induction l.\n   intros. destruct n0,n; reflexivity.\n   intros. destruct n0,n; try reflexivity;try inversion H.\n    simpl in IHl. simpl. rewrite IHl.\n     reflexivity.\n     simpl in H. apply H.  \nQed.\n\nTheorem OT8 : forall n n0 a l a0,false = ble_nat (S(length l)) n -> false = ble_nat (S n0) n->\ninsert1 n0 a (delete1 n (a0 :: l)) = delete1 n (a0 :: insert1 n0 a l).\nProof.\n  intros. generalize dependent n0. generalize dependent n. generalize dependent a0.\n   induction l.\n    intros. destruct n. reflexivity. inversion H.\n  intros. destruct n0,n; try reflexivity.\n   inversion H0.\n   simpl. rewrite <-IHl. \n    reflexivity.\n    simpl in H. apply H.\n    simpl in H0. apply H0.  \nQed.\n\nTheorem OT9 : forall n n0 l a,false = ble_nat (length l) n ->false = ble_nat (S n) n0->\ndelete1 n0 (a :: delete1 n l) = delete1 n (delete1 n0 (a :: l)).\nProof.\n  intros. generalize dependent n0. generalize dependent n. generalize dependent a. induction l.\n   intros. destruct n0,n; inversion H.\n   intros. destruct n0,n;try reflexivity.\n    inversion H0.\n    simpl. rewrite <-IHl. \n     reflexivity.\n     simpl in H. apply H.\n     simpl in H0. apply H0.  \nQed.\nTheorem OT11 : forall n0 n l a,false = ble_nat (S n) n0 ->length l = S n->\ndelete1 n0 (a :: delete1 n l) =delete1 n (delete1 n0 (a :: l)).\nProof.\n  intros. generalize dependent n0. generalize dependent n. generalize dependent a. induction l.\n   intros. inversion H0. \n   intros. destruct n0,n;try reflexivity.\n    inversion H.\n    simpl. rewrite <-IHl. \n     reflexivity.\n     inversion H0.  reflexivity.\n     simpl in H. apply H.  \nQed.\n\nTheorem OT10 : forall n n0 l a,false = ble_nat (length l) n -> false = ble_nat (S n0) n->\n      delete1 n0 (delete1 n (a :: l)) = delete1 n (a :: delete1 n0 l).\nProof.\n  intros. generalize dependent n0. generalize dependent n. generalize dependent a. induction l. \n   intros. destruct n0,n; inversion H.\n   intros. destruct n0,n; try reflexivity.\n   inversion H0.\n   simpl. rewrite <-IHl. \n     reflexivity.\n     simpl in H. apply H.\n     simpl in H0. apply H0.  \nQed.\n\nTheorem OT_correctness : forall (f1 f2:function) (b1 b2: bool) (l l1 l2:list ascii),((apply f1 l)=Some l1 \n /\\ (apply f2 l) =Some l2)-> (apply (OT f1 f2 false) l1 =apply (OT f2 f1 true) l2/\\exists l3,apply (OT f2 f1 true) l2=Some l3).\nProof.\n  intros. destruct f1,f2.\n  Case \"f1=inv, f2=inv\".\n   inversion H. inversion H. apply insert_len in H3. apply insert_len in H2. simpl in H0,H1.\n    unfold insert in H0,H1. unfold OT. unfold function_eq. \n    remember (beq_nat n n0) as beq. destruct beq.\n    SCase \"n=n0\".\n     rewrite beq_nat_sym. rewrite <- Heqbeq. simpl.\n      remember (beq_ascii a a0) as beqa. destruct beqa.\n      SSCase \"a=a0\".\n       rewrite beq_ascii_sym. rewrite <- Heqbeqa. apply beq_nat_eq in Heqbeq.\n        rewrite Heqbeq in H0. apply beq_ascii_eq in Heqbeqa. rewrite Heqbeqa in H0.\n        rewrite H0 in H1. inversion H1. split. reflexivity. exists l2. reflexivity.\n      SSCase \"a!=a0\".\n       rewrite beq_ascii_sym.  rewrite <- Heqbeqa. apply beq_nat_eq in Heqbeq.  rewrite Heqbeq.\n        rewrite <- ble_nat_refl. simpl. unfold insert. rewrite <-H2,<-H3. rewrite Heqbeq in H0.\n        replace (ble_nat (S (S (length l))) (S n0)) with (ble_nat (S (length l)) n0) by reflexivity.\n        remember (ble_nat (S(length l)) n0) as ble. destruct ble; inversion H0. inversion H1.\n        apply bleSF1 in Heqble. rewrite <-Heqble. rewrite OT2. \n        split;try exists (insert1 (S n0) a (insert1 n0 a0 l));reflexivity.\n    SCase \"n!=n0\".\n     rewrite beq_nat_sym. rewrite <-Heqbeq. simpl. remember (ble_nat n0 n) as ble. destruct ble.\n     SSCase \"n0<=n\".\n      inversion Heqble.  apply ble_nat_neg0 in H5;try apply Heqbeq. rewrite <-H5.\n       simpl. unfold insert. rewrite <- H2,<-H3. \n       replace (ble_nat (S (S (length l))) (S n)) with (ble_nat (S (length l)) n) by reflexivity.\n       destruct (ble_nat (S (length l)) n); inversion H0.\n       remember (ble_nat (S (length l)) n0) as ble. destruct ble; inversion H1. apply bleSF1 in Heqble0.\n       rewrite <-Heqble0. rewrite OT3; try apply Heqble.\n       split;try exists (insert1 (S n) a (insert1 n0 a0 l));reflexivity.\n     SSCase \"n0>n\".\n      inversion Heqble.  apply ble_nat_neg in H5. rewrite <-H5. simpl. unfold insert.\n       rewrite <- H2,<-H3. \n       replace (ble_nat (S (S (length l))) (S n0)) with (ble_nat (S (length l)) n0) by reflexivity.\n       destruct (ble_nat (S (length l)) n0); inversion H1.\n       remember (ble_nat (S (length l)) n) as ble. destruct ble; inversion H0. apply bleSF1 in Heqble0.\n       rewrite <-Heqble0. rewrite <-OT3; try apply H5.\n       split;try exists (insert1 n a (insert1 n0 a0 l));reflexivity.\n  Case \"f1=ins, f2=del\".\n   inversion H. inversion H. apply insert_len in H2. apply delete_len in H3.\n    unfold OT. simpl. simpl in H0,H1. unfold insert,delete in H0,H1. \n    remember (ble_nat n n0) as ble. destruct ble.\n    SCase \"n<=n0\".\n     simpl. unfold delete,insert. rewrite <- H2,<-H3.\n      replace (ble_nat ((S (length l))) (S n0)) with (ble_nat ((length l)) n0) by reflexivity.\n      remember (ble_nat (length l) n0) as ble. destruct ble;inversion H1. \n      inversion Heqble0. apply ble_nat_negtrans1 with (n0:=n) in H6; try apply Heqble.\n      rewrite <- H6. destruct (ble_nat (S (length l)) n); inversion H0.\n      rewrite OT5;try apply Heqble. split;try exists (insert1 n a (delete1 n0 l));reflexivity.\n    SCase \"n>n0\". \n     simpl. unfold delete,insert. rewrite <- H2,<-H3.\n      destruct n. inversion Heqble. unfold pred. simpl in H0. \n       remember (ble_nat (length l) n) as ble. destruct ble;inversion H0. \n       remember (ble_nat (length l) n0) as ble. destruct ble; inversion H1. apply bleSF1 in Heqble1.\n       rewrite<- Heqble1. destruct l. inversion H3. simpl in Heqble,Heqble0.\n       rewrite OT6;try simpl;try apply Heqble; try apply Heqble0.\n       split;try exists (insert1 n a (delete1 n0 (a0 :: l)));reflexivity.\n  Case \"ins,id\".\n   simpl. inversion H. inversion H. inversion H1. apply insert_len in H2.\n    simpl in H0. unfold insert. unfold insert in H0. rewrite <- H5.\n    destruct (ble_nat (S (length l)) n);inversion H0.\n    split;try exists (insert1 n a l);reflexivity.\n  Case \"delete,ins\".\n   inversion H. inversion H. apply insert_len in H3. apply delete_len in H2.\n    unfold OT. simpl. simpl in H0,H1. unfold insert,delete in H0,H1. \n    remember (ble_nat n0 n) as ble. destruct ble.\n    SCase \"n0<=n\".\n     simpl. unfold insert,delete. rewrite <-H2,<-H3. simpl. \n      remember (ble_nat (length l) n) as ble. destruct ble;inversion H0.\n      inversion Heqble0. apply ble_nat_negtrans1 with (n0:=n0) in H6;try apply Heqble.\n      rewrite <- H6. apply bleSF1 in H6. rewrite <- H6 in H1. inversion H1. rewrite OT7;try apply Heqble.\n      split;try exists (match insert1 n0 a l with | [] => [] | h :: l' => h :: delete1 n l' end);reflexivity.\n    SCase \"n0>n\".\n     simpl. unfold insert,delete. rewrite <-H2,<-H3. destruct n0. inversion Heqble. unfold pred.\n      remember (ble_nat (length l) n) as ble. destruct ble;inversion H0. inversion Heqble0.\n      apply bleSF1 in H6. rewrite <- H6. simpl in H1. destruct (ble_nat (length l) n0);\n      inversion H1. destruct l. inversion H2. simpl in Heqble, Heqble0. \n      rewrite OT8;simpl;try apply Heqble;try apply Heqble0. \n      split;try exists (delete1 n (a0 :: insert1 n0 a l));reflexivity.\n  Case \"del,del\".\n   inversion H. inversion H. apply delete_len in H3. apply delete_len in H2.\n   unfold OT. simpl. simpl in H0,H1. unfold delete in H0,H1. \n   remember (beq_nat n n0) as beq. destruct beq.\n    SCase \"n=n0\".\n     apply beq_nat_eq in Heqbeq. rewrite <-Heqbeq. rewrite <- Heqbeq in H1.\n     rewrite <- beq_nat_refl. simpl. destruct (ble_nat (length l) n); inversion H0.\n     inversion H1. split;try exists (delete1 n l);reflexivity.\n    SCase \"n!=n0\".\n     remember (ble_nat n0 n) as ble. destruct ble.\n      SSCase \"n0<=n\".\n       inversion Heqble. apply ble_nat_neg0 in H5;try apply Heqbeq. rewrite <- H5.\n       rewrite beq_nat_sym in Heqbeq. rewrite<-Heqbeq. simpl. unfold delete.\n       destruct n. inversion H5. destruct l;inversion H2;inversion H3.\n       unfold pred. simpl in H0,H1. remember (ble_nat (length l) n) as ble.\n       destruct ble;inversion H0. inversion H5.\n       remember (beq_nat (length l) (S n)) as beq. destruct beq.\n        apply beq_nat_eq in Heqbeq0. rewrite Heqbeq0. rewrite <- H5.   \n        rewrite Heqbeq0 in H1. \n        remember (match n0 with | 0 => false | S m' => ble_nat (S n) m' end) as mat.\n        destruct mat; inversion H1.  rewrite OT11; try apply H5; try apply Heqbeq0.\n        split;try exists (delete1 n (delete1 n0 (a :: l)));reflexivity.\n       inversion Heqble0. \n        replace (ble_nat (length l) n) with  (ble_nat (S (length l)) (S n)) in H10 by reflexivity.\n        apply ble_nat_neg3 in H10; try apply Heqbeq0.\n        replace (match n0 with| 0 => false | S m' => ble_nat n m' end) with (ble_nat (S n) n0) in H9 by reflexivity.\n        apply ble_nat_negtrans with (n0:=length l) in H9; try apply H10.\n        rewrite <- H9. destruct (match n0 with | 0 => false| S m' => ble_nat (length l) m' end);inversion H1.\n        rewrite OT9; try apply H5; try apply Heqble0. \n        split;try exists (delete1 n (delete1 n0 (a :: l)));reflexivity.\n      SSCase \"n0>n\".\n       rewrite beq_nat_sym in Heqbeq. rewrite <- Heqbeq.\n       inversion Heqble. apply ble_nat_neg in H5. rewrite <- H5. simpl.\n       destruct n0. inversion Heqble. unfold pred. unfold delete.\n       destruct l; inversion H2; inversion H3. simpl in H1.\n       remember (ble_nat (length l) n0) as ble. destruct ble; inversion H1.\n       replace (ble_nat (length (a :: l)) n) with (ble_nat (S (length l)) n) in H0 by reflexivity.\n       remember (ble_nat (S (length l)) n) as ble. destruct ble; inversion H0.\n       remember (beq_nat (length l) n) as beq. destruct beq.\n        apply beq_nat_eq in Heqbeq0. rewrite Heqbeq0 in Heqble1, Heqble0.\n         apply ble_nat_beq in Heqble0; try apply H5. rewrite beq_nat_sym in Heqble0.\n         rewrite <-Heqble0 in Heqbeq. inversion Heqbeq.\n        apply ble_nat_neg3 in Heqble1; try apply Heqbeq0. rewrite <-Heqble1.\n         rewrite OT10; try apply Heqble1; try apply Heqble.\n         split;try exists (delete1 n (a :: delete1 n0 l));reflexivity.\n  Case \"del,id\".\n   inversion H. inversion H. apply delete_len in H2. simpl. unfold delete. simpl in H0,H1.\n    unfold delete in H0. inversion H1. rewrite<- H5. destruct (ble_nat (length l) n); inversion H0.\n    split;try exists (delete1 n l);reflexivity.\n  Case \"id,ins\".\n   simpl. inversion H. inversion H. apply insert_len in H3. unfold insert. simpl in H0,H1.\n    unfold insert in H1. inversion H0. rewrite<- H5. destruct (ble_nat (S(length l)) n); inversion H1.\n    split;try exists (insert1 n a l);reflexivity.\n  Case \"id,del\".\n   inversion H. inversion H. apply delete_len in H3. simpl. unfold delete. simpl in H0,H1.\n    unfold delete in H1. inversion H0. rewrite<- H5. destruct (ble_nat (length l) n); inversion H1.\n    split;try exists (delete1 n l);reflexivity.\n  Case \"ins,ins\".\n   simpl. inversion H. inversion H0. inversion H1. rewrite <- H3,<-H4.\n     split. reflexivity. exists (l). reflexivity.\nQed.", "meta": {"author": "AntonMilenin", "repo": "CoqBook", "sha": "2f8fc7f5da81079fbbb2a2fa86437d02adf7638f", "save_path": "github-repos/coq/AntonMilenin-CoqBook", "path": "github-repos/coq/AntonMilenin-CoqBook/CoqBook-2f8fc7f5da81079fbbb2a2fa86437d02adf7638f/OT - remake.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.6863605946088698}}
{"text": "(* Injective Library *)\n(* v0   Olivier Laurent *)\n\n\n(** * Some properties of injective functions *)\n\nRequire Import Relations.\nRequire Import RelationClasses.\nRequire Import List_more.\n\n(** Same definition as in standard library [Coq.Sets.Image] *)\nDefinition injective {A B} (f : A -> B) := forall x y, f x = f y -> x = y.\n\nDefinition injective2 {A B C} (f : A -> B -> C) :=\n  forall x y x' y', f x y = f x' y' -> x = x' /\\ y = y'.\n\n(** * Basic properties of injective functions *)\n\nLemma comp_inj {A B C} : forall (f : B -> C) (g : A -> B),\n  injective f -> injective g -> injective (fun x => f (g x)).\nProof.\nintros f g Hf Hg x y Hc.\napply Hg.\napply Hf.\nassumption.\nQed.\n\nLemma section_inj {A B} : forall (f : A -> B) g,\n  (forall x, g (f x) = x) -> injective f.\nProof.\nintros f g Hsec x y Hf.\nrewrite <- Hsec.\nrewrite <- Hf.\nrewrite Hsec.\nreflexivity.\nQed.\n\nLemma map_inj {A B} : forall f : A -> B, injective f -> injective (map f).\nProof.\nintros f Hf l1.\ninduction l1 ; intros l2 Hmap.\n- destruct l2.\n  + reflexivity.\n  + inversion Hmap.\n- destruct l2.\n  + inversion Hmap.\n  + simpl in Hmap.\n    injection Hmap ; intros Htl Hhd.\n    apply Hf in Hhd.\n    apply IHl1 in Htl.\n    subst.\n    reflexivity.\nQed.\n\nLemma map_inj_local {A B} : forall f : A -> B, forall l1 l2,\n  (forall x y, In x l1 -> In y l2 -> f x = f y -> x = y) ->\n    map f l1 = map f l2 -> l1 = l2.\nProof with try assumption ; try reflexivity.\ninduction l1 ; intros l2 Hi Hmap.\n- destruct l2...\n  inversion Hmap.\n- destruct l2.\n  + inversion Hmap.\n  + simpl in Hmap.\n    injection Hmap ; intros Htl Hhd.\n    apply Hi in Hhd ; try (apply in_eq ; fail).\n    apply IHl1 in Htl ; subst...\n    intros.\n    apply Hi...\n    * apply in_cons...\n    * apply in_cons...\nQed.\n\n\n(** * Inverse image of a relation by an injective function *)\n\nSection Relation_inj.\n\nVariable A B : Type.\nVariable f : A -> B.\nHypothesis f_inj : injective f.\n\nVariable R : relation B.\n\nDefinition f_R := fun x y => R (f x) (f y).\n\nLemma PreOrder_inj : PreOrder R -> PreOrder f_R.\nProof.\nintros Hp.\ndestruct Hp.\nsplit ; unfold f_R.\n- intros x.\n  apply PreOrder_Reflexive.\n- intros x y z H1 H2.\n  eapply PreOrder_Transitive ; eassumption.\nQed.\n\nLemma Equivalence_inj : Equivalence R -> Equivalence f_R.\nProof.\nintros He.\ndestruct He.\nsplit ; unfold f_R.\n- intros x.\n  apply Equivalence_Reflexive.\n- intros x y H.\n  apply Equivalence_Symmetric ; assumption.\n- intros x y z H1 H2.\n  eapply Equivalence_Transitive ; eassumption.\nQed.\n\nLemma PartialOrder_inj : forall Ro,\n  @PartialOrder _ eq _ _ Ro -> @PartialOrder _ eq _ _ (PreOrder_inj Ro).\nProof.\nintros Ro Rp x y ; split ; intros H.\n- subst ; split.\n  + clear Rp ; apply PreOrder_inj in Ro.\n    reflexivity.\n  + clear Rp ; apply PreOrder_inj in Ro.\n    reflexivity.\n- destruct H as [Hr Hs].\n  destruct Rp with (f x) (f y) as [_ Hf].\n  apply f_inj.\n  apply Hf.\n  split.\n  + apply Hr.\n  + apply Hs.\nQed.\n\nEnd Relation_inj.\n\n\n\n\n", "meta": {"author": "olaure01", "repo": "yalla", "sha": "9c6a66fa3a3d68b5a21ce7fa695402a0f2dda4d7", "save_path": "github-repos/coq/olaure01-yalla", "path": "github-repos/coq/olaure01-yalla/yalla-9c6a66fa3a3d68b5a21ce7fa695402a0f2dda4d7/ollibs/Injective.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.6862836217882761}}
{"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 drop (drop_arg0 : natural) (drop_arg1 : lst) : lst\n           := match drop_arg0, drop_arg1 with\n              | x, Nil => Nil\n              | Zero, x => x\n              | Succ x, Cons y z => drop x z\n              end.\n\nTheorem drop_Nil: forall (x: natural), drop x Nil = Nil.\nProof.\n  induction x ; simpl; reflexivity.\nQed.\n\nTheorem drop_Cons: forall (x n: natural) (l: lst), drop (Succ x) (Cons n l) = drop x l.\n  induction l; induction x; simpl; reflexivity.\nQed.\n\nTheorem drop_Cons_assoc: forall (x1 x2 x3: natural) (l: lst),\n    drop x1 (drop x2 (Cons x3 l)) = drop x2 (drop x1 (Cons x3 l)).\nProof.\n  induction x1; induction x2; try (simpl; reflexivity).\n  + induction l.\n    * rewrite 2 drop_Cons. rewrite <- IHx1.\n      rewrite IHx2. rewrite 2 drop_Cons.\n      induction l.\n      - rewrite IHx1. reflexivity. \n      - rewrite 3 drop_Nil. reflexivity. \n    * simpl. rewrite 2 drop_Nil. reflexivity. \n  + intros. simpl. destruct (drop x1 l); reflexivity. \n  + intros. simpl. destruct (drop x2 l); reflexivity. \nQed.\n\nTheorem drop_assoc : forall (x : natural) (y : natural) (z : lst), eq (drop x (drop y z)) (drop y (drop x z)).\nProof.\n  induction z.\n  + rewrite 2 drop_Cons_assoc. reflexivity. \n  + rewrite 3 drop_Nil. reflexivity. \nQed.\n\nTheorem theorem0 : forall (x : natural) (y : natural) (w : natural) (z : lst), eq (drop w (drop x (drop y z))) (drop y (drop x (drop w z))).\nProof.\n  intros.\n  rewrite (drop_assoc w x).\n  rewrite (drop_assoc w y).\n  rewrite (drop_assoc x y).\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/goal9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.6862836096495126}}
{"text": "Definition relation (a : Type) := a -> a -> Prop.\n\nRecord poset := mk_poset {\n  carrier :> Type;\n  ord : relation carrier;\n  ord_refl {x} : ord x x;\n  ord_trans {x y z} : ord x y -> ord y z -> ord x z;\n  ord_antisym {x y} : ord x y -> ord y x -> x = y\n}.\n\nRecord monotone (a b : poset) := mk_monotone {\n  base_f :> carrier a -> carrier b;\n  base_f_mono x y : ord a x y -> ord b (base_f x) (base_f y)\n}.\nArguments mk_monotone {a b}.\nArguments base_f {a b}.\nArguments base_f_mono {a b}.", "meta": {"author": "eashanhatti", "repo": "prog_logic", "sha": "fd93f214e015ac0cb0b699026914a1faae5d63ac", "save_path": "github-repos/coq/eashanhatti-prog_logic", "path": "github-repos/coq/eashanhatti-prog_logic/prog_logic-fd93f214e015ac0cb0b699026914a1faae5d63ac/theories/Poset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109622750986, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6862460093457196}}
{"text": "Theorem 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.", "meta": {"author": "cristianlepore", "repo": "Coq_exercises", "sha": "109d34794edee6bd2b255ed4f7fc3c91edb8c8f5", "save_path": "github-repos/coq/cristianlepore-Coq_exercises", "path": "github-repos/coq/cristianlepore-Coq_exercises/Coq_exercises-109d34794edee6bd2b255ed4f7fc3c91edb8c8f5/Software_foundation/Chapter5/eqb_trans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.686214375346384}}
{"text": "Require Import Arith.\nRequire Import NArith.\nRequire Import List.\nRequire Import Sorting.\nRequire Import Coq.Program.Equality.\n\nLemma minus_n_0 : forall n, n-0 = n.\nProof.\ninduction n; trivial.\nDefined.\n\nLemma plus_0_n : forall n, 0+n = n.\nProof.\ninduction n; trivial.\nDefined.\n\nLemma plus_n_0 : forall n, n+0 = n.\nProof.\ninduction n; trivial.\nsimpl; rewrite IHn; reflexivity.\nDefined.\n\nLemma plus_n_1 : forall n, n+1 = S n.\nProof.\ninduction n; trivial.\nsimpl; rewrite IHn; reflexivity.\nDefined.\n\nLemma minus_n1_n2_0 : forall n1 n2, n1+n2-0 = n1+n2.\nProof.\ninduction n1; induction n2; trivial.\nDefined.\n\nFixpoint arity (T:Type) (n:nat) :=\n match n with\n | 0 => Prop\n | S p => T -> arity T p\n end.\n\n(** Warning: cartesianPower T 0 represents T but it is never used *)\n\nFixpoint cartesianPowerAux (T:Type) (n:nat) :=\n match n with\n | 0 => T\n | S p => (T * cartesianPowerAux T p)%type\n end.\n\nDefinition cartesianPower T n := cartesianPowerAux T (n-1).\n\nDefinition headCP {T:Type} {n:nat} (cp : cartesianPower T (S n)) : T.\nProof.\ninduction n.\nexact cp.\nexact (fst cp).\nDefined.\n\nDefinition headCPbis {T:Type} {n:nat} (cp : cartesianPower T (S n)) : cartesianPower T 1.\nProof.\ninduction n.\nexact cp.\nexact (fst cp).\nDefined.\n\nDefinition tailCP {T:Type} {n:nat} (cp : cartesianPower T (S (S n))) : (cartesianPower T (S n)).\nProof.\ninduction n.\nexact (snd cp).\nexact (snd cp).\nDefined.\n\nDefinition tailDefaultCP {T:Type} {n:nat} (cp : cartesianPower T (S n)) (Default : cartesianPower T n) : (cartesianPower T n).\nProof.\ninduction n.\nexact Default.\nexact (tailCP cp).\nDefined.\n\nDefinition allButLastCP {T:Type} {n:nat} (cp : cartesianPower T (S (S n))) : (cartesianPower T (S n)).\nProof.\ninduction n.\nexact (headCP cp).\nsplit.\nexact (headCP cp).\nunfold cartesianPower in IHn.\nsimpl in *.\nrewrite minus_n_0 in IHn.\napply IHn.\nexact (tailCP cp).\nDefined.\n\nLemma allButLastCPTl {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S (S (S n)))),\n  allButLastCP (tailCP cp) = tailCP (allButLastCP cp).\nProof.\nintro cp; induction n; simpl; reflexivity.\nQed.\n\nDefinition lastCP {T:Type} {n:nat} (cp : cartesianPower T (S n)) : T.\nProof.\ninduction n.\nexact cp.\napply IHn.\nexact (tailCP cp).\nDefined.\n\nLemma lastCPTl {T:Type} {n:nat} : forall (cp : cartesianPower T (S (S n))), lastCP cp = lastCP (tailCP cp).\nProof.\nintro cp; induction n; simpl; reflexivity.\nQed.\n\nLemma CP_ind {T:Type} {n : nat} : forall (cp cp' : cartesianPower T (S (S n))),\n  headCP cp = headCP cp' -> tailCP cp = tailCP cp' -> cp = cp'.\nProof.\nintros.\ninduction n; simpl in *;\napply injective_projections; assumption.\nQed.\n\nLemma CPPair {T : Type} :\n  forall (cp : cartesianPower T 2),\n  cp = (fst cp, snd cp).\nProof.\nintro cp.\napply CP_ind; simpl; reflexivity.\nQed.\n\nDefinition tailCPbis {T:Type} {n:nat} m1 m2 (cp : cartesianPower T m1) :\n  (S (S n)) = m1 -> (S n) = m2 -> (cartesianPower T m2).\nProof.\nintros Hm1 Hm2.\nsubst.\nexact (tailCP cp).\nDefined.\n\nDefinition consHeadCP {T:Type} {n:nat} (t : T) (cp : cartesianPower T n) : (cartesianPower T (S n)).\nProof.\ninduction n.\nexact t.\nclear IHn.\nsplit.\nexact t.\nunfold cartesianPower in cp.\nsimpl in cp.\nrewrite minus_n_0 in cp.\nexact cp.\nDefined.\n\nLemma consHeadCPHd {T:Type} {n:nat} :\n  forall (cp : cartesianPower T n) t,\n  headCP (consHeadCP t cp) = t.\nProof.\nintro cp; induction n; simpl; reflexivity.\nQed.\n\nLemma consHeadCPTl {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S n)) t,\n  tailCP (consHeadCP t cp) = cp.\nProof.\nintro cp; induction n; simpl; reflexivity.\nQed.\n\nLemma consHeadCPOK {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S (S n))),\n  cp = consHeadCP (headCP cp) (tailCP cp).\nProof.\nintro cp.\ninduction n.\nsimpl.\napply CPPair.\napply CP_ind.\nsimpl; reflexivity.\nrewrite consHeadCPTl; reflexivity.\nQed.\n\nDefinition consTailCP {T:Type} {n:nat} (cp : cartesianPower T n) (t : T) : (cartesianPower T (S n)).\nProof.\ninduction n.\nexact t.\ninduction n.\nexact (cp, t).\nclear IHn0.\nsplit.\nexact (headCP cp).\nexact (IHn (tailCP cp)).\nDefined.\n\nLemma consTailCPTl {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S (S n))) t,\n  tailCP (consTailCP cp t) = consTailCP (tailCP cp) t.\nProof.\nintro cp; induction n; simpl; reflexivity.\nQed.\n\nLemma consTailCPOK {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S (S n))),\n  cp = consTailCP (allButLastCP cp) (lastCP cp).\nProof.\nintro cp.\ninduction n.\nsimpl.\napply CPPair.\napply CP_ind.\nsimpl; reflexivity.\nassert (H := IHn (tailCP cp)).\nrewrite <- lastCPTl in H.\nrewrite allButLastCPTl in H.\nrewrite <- consTailCPTl in H.\nassumption.\nQed.\n\nLemma consTailCPAbl {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S n)) t,\n  allButLastCP (consTailCP cp t) = cp.\nProof.\nintros cp t; induction n; try (simpl; reflexivity).\napply CP_ind.\nsimpl; reflexivity.\nrewrite <- IHn.\nrewrite <- consTailCPTl.\nrewrite allButLastCPTl.\nreflexivity.\nQed.\n\nLemma consTailCPTlD {T:Type} {n:nat} :\n  forall (cp : cartesianPower T n) t,\n  tailDefaultCP (consHeadCP t cp) cp = cp.\nProof.\nintros cp t; induction n; try (simpl; reflexivity).\ninduction n; simpl; reflexivity.\nQed.\n\nLemma consHdTlTlHd {T:Type} {n:nat} :\n  forall (F L : T) (X : cartesianPower T n),\n  consHeadCP F (consTailCP X L) = consTailCP (consHeadCP F X) L.\nProof.\ninduction n.\nintros F L X.\nunfold consHeadCP; unfold consTailCP; simpl; reflexivity.\nclear IHn.\ninduction n.\nintros F L X.\nunfold consHeadCP; unfold consTailCP; simpl; reflexivity.\nintros F L X.\napply CP_ind.\nsimpl; reflexivity.\nassert (H := consHeadCPOK X); rewrite H; clear H.\nrewrite consHeadCPTl.\nrewrite consTailCPTl.\nrewrite consHeadCPTl.\nreflexivity.\nQed.\n\nLemma consTlHdHdTl {T:Type} {n:nat} :\n  forall (A B C : T) (X : cartesianPower T n),\n  consHeadCP A (consHeadCP B (consTailCP X C)) = consTailCP (consHeadCP A (consHeadCP B X)) C.\nProof.\ninduction n.\nintros A B C X.\nunfold consHeadCP; unfold consTailCP; simpl; reflexivity.\nclear IHn.\ninduction n.\nintros A B C X.\nunfold consHeadCP; unfold consTailCP; simpl; reflexivity.\nintros A B C X.\napply CP_ind.\nsimpl; reflexivity.\nassert (H := consHeadCPOK X); rewrite H; clear H.\nrewrite consHeadCPTl.\nrewrite consTailCPTl.\nrewrite consHeadCPTl.\nrewrite <- IHn.\napply CP_ind.\nsimpl; reflexivity.\ndo 2 (rewrite consHeadCPTl).\napply CP_ind.\nsimpl; reflexivity.\nrewrite consHeadCPTl.\nrewrite consTailCPTl.\ninduction n.\nsimpl; reflexivity.\nrewrite consHeadCPTl; reflexivity.\nQed.\n\nDefinition CPToList {T:Type} {n:nat} (cp : cartesianPower T n) : list T.\nProof.\ninduction n.\nexact nil.\nclear IHn.\ninduction n.\nexact (cons cp nil).\napply cons.\nexact (headCP cp).\napply IHn.\nexact (tailCP cp).\nDefined.\n\nDefinition InCP {T:Type} {n:nat} p (cp : cartesianPower T n) := In p (CPToList cp).\n\nLemma InCPOK {T:Type} {n:nat} : forall p (cp : cartesianPower T (S (S n))),\n  InCP p cp <-> ((p = headCP cp) \\/ InCP p (tailCP cp)).\nProof.\nintros p cp; unfold InCP; induction n; simpl.\n\n  split; intro H.\n\n    elim H; clear H; intro H.\n\n      left; subst; reflexivity.\n\n      right; assumption.\n\n    elim H; clear H; intro H.\n\n      left; subst; reflexivity.\n\n      right; assumption.\n\n  split; intro H.\n\n    elim H; clear H; intro H.\n\n      left; subst; reflexivity.\n\n      right; assumption.\n\n    elim H; clear H; intro H.\n\n      left; subst; reflexivity.\n\n      right; assumption.\nQed.\n\nLemma lastCPIn {T:Type} {n:nat} : forall (cp : cartesianPower T (S n)), InCP (lastCP cp) cp.\nProof.\nunfold InCP.\nintro cp; induction n.\nsimpl; intuition.\nsimpl.\nassert (H := IHn (tailCP cp)).\nintuition.\nQed.\n\nDefinition nthCP {T:Type} {m:nat} (n : nat) (cp : cartesianPower T m) (Default : T) := nth (n-1) (CPToList cp) Default.\n\nLemma CPToListOK {T:Type} {n:nat} : forall (cp : cartesianPower T (S (S n))), CPToList cp = cons (headCP cp) (CPToList (tailCP cp)).\nProof.\nreflexivity.\nQed.\n\nLemma CPLHdTlOK {T:Type} {n:nat} : forall (cp : cartesianPower T (S (S n))),\n  CPToList cp = ((headCP cp) :: nil) ++ CPToList (tailCP cp).\nProof.\ninduction n; intro cp; simpl; reflexivity.\nQed.\n\nLemma consTailOK {T:Type} {n:nat} : forall (cp : cartesianPower T (S n)) t,\n  CPToList (consTailCP cp t) = CPToList cp ++ t :: nil.\nProof.\ninduction n; intros cp t.\nsimpl; reflexivity.\nrewrite CPToListOK.\nassert (H : headCP (consTailCP cp t) = headCP cp) by (simpl; reflexivity); rewrite H; clear H.\nassert (H : tailCP (consTailCP cp t) = (consTailCP (tailCP cp) t)) by (simpl; reflexivity);\nrewrite H; clear H.\nrewrite IHn.\nsimpl; reflexivity.\nQed.\n\nLemma InNth {T:Type} {n:nat} :\n  forall (cp : cartesianPower T n) (t Default : T),\n  InCP t cp -> (exists id, id >= 1 /\\ id <= n /\\ t = nthCP id cp Default).\nProof.\ninduction n; intros cp t Default HIn.\nunfold InCP in HIn.\nsimpl in HIn.\nintuition.\ninduction n.\nexists 1; try intuition.\nunfold nthCP; simpl.\nunfold InCP in HIn; simpl in HIn.\nintuition.\nclear IHn0.\napply InCPOK in HIn.\nelim HIn; clear HIn; intro HIn.\nexists 1; unfold nthCP; simpl; intuition.\nassert (H := IHn (tailCP cp) t Default).\napply H in HIn; clear H.\ndestruct HIn as [id [Hge [Hle HEq]]].\nunfold nthCP in *.\nexists (S id); try intuition.\nassert (H := app_nth2 ((headCP cp) :: nil) (CPToList (tailCP cp)) Default Hge).\nrewrite CPToListOK.\nassert (H' : (headCP cp :: nil) ++ CPToList (tailCP cp) = (headCP cp :: CPToList (tailCP cp)))\n  by (simpl; reflexivity); rewrite <- H'; clear H'.\nassert (H' : (S id - 1) = id) by (simpl; rewrite minus_n_0; reflexivity); rewrite H'; clear H'.\nrewrite H.\napply HEq.\nQed.\n\nLemma nthFirst {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S n)) (t Default : T),\n  t = nthCP 1 cp Default -> t = headCP cp.\nProof.\ninduction n; intros cp t Default Hnth.\nunfold nthCP in Hnth.\nsimpl in Hnth.\nassumption.\nunfold nthCP in Hnth.\nsimpl in Hnth.\nassumption.\nQed.\n\nLemma lengthOfCPToList {T:Type} {n:nat} : forall (cp : cartesianPower T n), n = length (CPToList cp).\nProof.\nintros.\ninduction n.\nsimpl.\nreflexivity.\nclear IHn.\ninduction n.\nsimpl.\nreflexivity.\napply eq_S.\napply IHn.\nDefined.\n\nLemma lastTailOK {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S (S n))),\n  lastCP cp = lastCP (tailCP cp).\nProof.\ninduction n; intro cp; simpl; reflexivity.\nQed.\n\nLemma consTailCPLast {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S n)) t,\n  lastCP (consTailCP cp t) = t.\nProof.\nintros cp t; induction n; try (simpl; reflexivity).\nrewrite lastTailOK.\napply IHn.\nQed.\n\nLemma nthLast {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S n)) (Default : T),\n  lastCP cp = nthCP (S n) cp Default.\nProof.\nunfold nthCP; induction n; intros cp Default.\nsimpl; reflexivity.\nrewrite lastTailOK.\nassert (H := IHn (tailCP cp) Default); rewrite H; clear H; clear IHn.\nsimpl.\nrewrite minus_n_0.\nreflexivity.\nQed.\n\nLemma nthCircPerm1 {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S (S n))) (t Default : T),\n  t = nthCP 1 cp Default -> t = nthCP (S (S n)) (consTailCP (tailCP cp) (headCP cp)) Default.\nProof.\nintros cp t Default Hnth.\napply nthFirst in Hnth.\nrewrite <- Hnth.\nclear Hnth.\nunfold nthCP.\nrewrite consTailOK.\nrewrite app_nth2.\nrewrite <- lengthOfCPToList.\nsimpl.\nrewrite <- Minus.minus_diag_reverse.\nreflexivity.\nrewrite <- lengthOfCPToList.\nsimpl.\nintuition.\nQed.\n\nLemma nthCircPerm1Eq {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S (S n))) (Default : T),\n  nthCP 1 cp Default = nthCP (S (S n)) (consTailCP (tailCP cp) (headCP cp)) Default.\nProof.\nintros cp Default.\napply nthCircPerm1.\nreflexivity.\nQed.\n\nLemma nthCircPerm2 {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S (S n))) (t Default : T) id,\n  t = nthCP (S (S id)) cp Default -> id <= n ->\n  t = nthCP (S id) (consTailCP (tailCP cp) (headCP cp)) Default.\nProof.\ninduction n; intros cp t Default id Hnth HIn.\nsimpl in *.\ninduction id.\nunfold nthCP in *.\nsimpl in Hnth.\nrewrite <- Hnth.\nsimpl; reflexivity.\nassert (H := Le.le_Sn_0 id); intuition.\nunfold nthCP in *.\nrewrite consTailOK.\nrewrite CPLHdTlOK in Hnth.\nrewrite app_nth2 in Hnth.\nassert (H : S (S id) - 1 - length (headCP cp :: nil)  = S id - 1) by (simpl; reflexivity);\nrewrite H in Hnth; clear H.\nrewrite app_nth1; try assumption.\nrewrite <- lengthOfCPToList.\nsimpl.\nrewrite minus_n_0.\napply Lt.le_lt_n_Sm; assumption.\nsimpl.\nintuition.\nQed.\n\nLemma nthCircPerm2Eq {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S (S n))) (Default : T) id,\n  id <= n -> nthCP (S (S id)) cp Default = nthCP (S id) (consTailCP (tailCP cp) (headCP cp)) Default.\nProof.\nintros cp Default id Hle.\napply nthCircPerm2.\nreflexivity.\nassumption.\nQed.\n\nLemma nthCPTlOK {T:Type} {m:nat} :\n  forall (cp : cartesianPower T (S (S m))) (Default : T) n,\n  nthCP (S n) (tailCP cp) Default = nthCP (S (S n)) cp Default.\nProof.\ninduction m; intros cp Default n.\ninduction n; unfold nthCP; simpl; reflexivity.\nassert (H := nthCircPerm2 cp (nthCP (S (S n)) cp Default) Default n).\nassert (Hnm := le_lt_dec n (S m)).\nelim Hnm; clear Hnm; intro Hnm.\nassert (H' : nthCP (S (S n)) cp Default = nthCP (S (S n)) cp Default) by reflexivity; apply H in H'; try assumption;\nclear H; rewrite H'; clear H'.\nunfold nthCP.\nrewrite consTailOK.\nrewrite app_nth1; try reflexivity.\nrewrite <- lengthOfCPToList.\nsimpl.\nrewrite minus_n_0.\napply Lt.le_lt_n_Sm; assumption.\nunfold nthCP.\nrewrite nth_overflow.\nrewrite nth_overflow; try reflexivity.\nrewrite <- lengthOfCPToList; simpl; intuition.\nrewrite <- lengthOfCPToList; simpl; rewrite minus_n_0; intuition.\nQed.\n\nLemma nthEqOK {T:Type} {m:nat} :\n  forall (cp1 cp2 : cartesianPower T (S m)) (Default : T),\n  (forall n, nthCP n cp1 Default = nthCP n cp2 Default) -> cp1 = cp2.\nProof.\ninduction m; intros cp1 cp2 Default Hnth.\nassert (H := Hnth 1).\nunfold nthCP in H.\nsimpl in H.\nassumption.\napply CP_ind.\nassert (H := Hnth 1).\nunfold nthCP in H.\nsimpl in H.\nassumption.\napply IHm with Default.\nintro n; induction n.\nassert (H := Hnth 2).\nunfold nthCP.\nunfold nthCP in H.\ndo 2 (rewrite CPLHdTlOK in H).\nsimpl; assumption.\ndo 2 (rewrite nthCPTlOK).\napply Hnth.\nQed.\n\nLemma consTailPerm  {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S (S n))),\n  Permutation.Permutation (CPToList cp) (CPToList (consTailCP (tailCP cp) (headCP cp))).\nProof.\nintro cp.\nrewrite CPLHdTlOK.\nrewrite consTailOK.\napply Permutation.Permutation_app_comm.\nQed.\n\nDefinition ListToCP {T : Type} (l : list T) (Default : T) : cartesianPower T (length l).\nProof.\ninduction l.\nexact Default.\ninduction l.\nexact a.\nclear IHl0.\nsplit.\nexact a.\nunfold cartesianPower in IHl.\nsimpl in IHl.\nrewrite minus_n_0 in IHl.\nexact IHl.\nDefined.\n\nFixpoint circPermNCP {T:Type} {m:nat} (n : nat) (cp : cartesianPower T (S (S m))) :=\n  match n with\n  | 0 => cp\n  | S p => circPermNCP p (consTailCP (tailCP cp) (headCP cp))\n  end.\n\nLemma circPermNCP0 {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S (S n))),\n  cp = circPermNCP 0 cp.\nProof.\nsimpl; reflexivity.\nQed.\n\nLemma circPermNCPOK {T:Type} {m:nat} :\n  forall (n : nat) (cp : cartesianPower T (S (S m))),\n  circPermNCP (S n) cp = circPermNCP n (consTailCP (tailCP cp) (headCP cp)).\nProof.\nunfold circPermNCP; reflexivity.\nQed.\n\nLemma nthCircPermNAny {T:Type} {m:nat} :\n  forall (cp : cartesianPower T (S (S m))) (Default : T) id n,\n  id + n <= S m -> nthCP (S id + n) cp Default = nthCP (S id) (circPermNCP n cp) Default.\nProof.\nintros cp Default id n Hle; revert cp; induction n; intro cp.\nrewrite plus_n_0; simpl; reflexivity.\nrewrite circPermNCPOK.\nassert (H : id + n <= S m) by (apply le_Sn_le; rewrite plus_n_Sm; assumption).\nassert (H' : id + n <= m) by (apply le_S_n; transitivity (id + S n); intuition).\nrewrite <- IHn; try assumption.\nrewrite <- plus_n_Sm.\napply nthCircPerm2Eq; assumption.\nQed.\n\nLemma circPermNIdFirst {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S (S n))) (Default : T),\n  nthCP 1 cp Default = nthCP 1 (circPermNCP (S (S n)) cp) Default.\nProof.\nintros cp Default.\nrewrite nthCircPerm1Eq.\nassert (H : 0 + S n <= S n) by intuition.\nassert (H' := nthCircPermNAny (consTailCP (tailCP cp) (headCP cp)) Default 0 (S n) H); clear H.\nassert (H : 1 + S n = S (S n)) by intuition; rewrite H in H'; clear H; rewrite H'.\napply eq_sym.\nrewrite circPermNCPOK.\nreflexivity.\nQed.\n\nLemma circPermNConsTlOK {T:Type} {m:nat} :\n  forall (n : nat) (cp : cartesianPower T (S (S m))),\n  consTailCP (tailCP (circPermNCP n cp)) (headCP (circPermNCP n cp)) = circPermNCP n (consTailCP (tailCP cp) (headCP cp)).\nProof.\nintros n; induction n; intro cp.\nsimpl; reflexivity.\napply eq_sym.\nrewrite circPermNCPOK.\nrewrite <- IHn.\nrewrite <- circPermNCPOK.\nreflexivity.\nQed.\n\nLemma circPermPerm {T:Type} {m:nat} :\n  forall (n : nat) (cp : cartesianPower T (S (S m))),\n  circPermNCP (S (S (S n))) cp = circPermNCP 1 (circPermNCP (S (S n)) cp).\nProof.\nintros n cp.\nrewrite circPermNCPOK.\napply eq_sym.\nrewrite circPermNCPOK.\nrewrite <- circPermNCP0.\napply circPermNConsTlOK.\nQed.\n\nLemma nthCP01 {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S n)) Default,\n  nthCP 0 cp Default = nthCP 1 cp Default.\nProof.\nunfold nthCP.\nassert (H : 0 - 1 = 0) by (simpl; reflexivity); rewrite H; clear H.\nassert (H : 1 - 1 = 0) by (simpl; reflexivity); rewrite H; clear H.\nreflexivity.\nQed.\n\nLemma circPermNIdAux {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S (S n))) (Default : T),\n  cp = circPermNCP (S (S n)) cp.\nProof.\nintros cp Default.\napply nthEqOK with Default.\nintro m.\nassert (Hmn := le_lt_dec m (S (S n))).\nelim Hmn; clear Hmn; intro Hmn.\nrevert cp; induction m; intro cp.\ndo 2 (rewrite nthCP01).\napply circPermNIdFirst.\nclear IHm.\nrevert cp; induction m; intro cp.\napply circPermNIdFirst.\nassert (H : m <= n) by (do 2 (apply le_S_n); assumption).\nrewrite nthCircPerm2Eq; try assumption; clear H.\nassert (H : S m <= S (S n)) by intuition.\nrewrite IHm; try assumption; clear H; clear IHm.\nrewrite <- circPermNCPOK.\nrewrite circPermPerm.\nassert (H : m + 1 <= S n) by (rewrite plus_n_1; intuition).\nrewrite <- nthCircPermNAny; try assumption; clear H.\nrewrite plus_n_1; reflexivity.\ninduction m.\nassert (H := lt_n_0 (S (S n))); intuition.\nclear IHm.\nunfold nthCP.\nrewrite nth_overflow.\nrewrite nth_overflow; try reflexivity.\nrewrite <- lengthOfCPToList.\nsimpl.\nrewrite minus_n_0.\napply gt_S_le.\nassumption.\nrewrite <- lengthOfCPToList.\nsimpl.\nrewrite minus_n_0.\napply gt_S_le.\nassumption.\nQed.\n\nLemma circPermNId {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S (S n))),\n  cp = circPermNCP (S (S n)) cp.\nProof.\nintro cp.\napply circPermNIdAux.\nexact (headCP cp).\nQed.\n\nLemma circPermNConsOK {T:Type} {n:nat} :\n  forall (cp : cartesianPower T (S n)) (t1 t2 : T),\n  circPermNCP (S n) (consTailCP (consTailCP cp t1) t2) = consHeadCP t1 (consHeadCP t2 cp).\nProof.\ninduction n; intros cp t1 t2.\nsimpl; reflexivity.\nclear IHn.\nassert (H := circPermNId (consHeadCP t1 (consHeadCP t2 cp))); rewrite H; clear H.\napply eq_sym.\nrewrite circPermNCPOK.\nassert (H : headCP (consHeadCP t1 (consHeadCP t2 cp)) = t1) by (simpl; reflexivity); rewrite H; clear H.\nassert (H : tailCP (consHeadCP t1 (consHeadCP t2 cp)) = consHeadCP t2 cp)\n  by (simpl; reflexivity); rewrite H; clear H.\nrewrite circPermNCPOK.\nassert (H : headCP (consTailCP (consHeadCP t2 cp) t1) = t2) by (simpl; reflexivity); rewrite H; clear H.\nassert (H : tailCP (consTailCP (consHeadCP t2 cp) t1) = consTailCP cp t1)\n  by (simpl; reflexivity); rewrite H; clear H.\nreflexivity.\nQed.\n\nLemma listInd {T : Type} : forall n (l l' : list T) Default,\n  length l = (S n) ->\n  length l' = (S n) ->\n  hd Default l = hd Default l' ->\n  tl l = tl l' ->\n  l = l'.\nProof.\nintros n l.\ninduction l.\nintros l' Default Hl.\nsimpl in Hl; discriminate.\nintros l' Default Hl Hl' Hhd Htl.\ninduction l'.\nsimpl in Hl'; discriminate.\nsimpl in Hhd.\nsimpl in Htl.\nsubst.\nreflexivity.\nQed.\n\nLemma CPLHd {T : Type} :\n  forall (a : T) l Default,\n  hd Default (CPToList (ListToCP (a :: l) Default)) = a.\nProof.\nintros a l Default.\ninduction l.\nsimpl; reflexivity.\nsimpl; reflexivity.\nQed.\n\nLemma ListToCPTl {T : Type} :\n  forall (a a0 : T) l (Ha0l : (S (length l)) = length (a0  :: l)) Haa0l Default,\n  tailCPbis (length (a :: a0 :: l)) (length (a :: l)) (ListToCP (a :: a0 :: l) Default) Haa0l Ha0l =\n  ListToCP (a0 :: l) Default.\nProof.\nintros a a0 l Ha0l Haa0l Default.\nsimpl in *.\nunfold tailCPbis.\nunfold tailCP.\nrepeat (elim_eq_rect; simpl).\ninduction l; simpl; reflexivity.\nQed.\n\nLemma CPToListTl1 {T : Type} :\n  forall (a a0 : T) l (cp : cartesianPower T (length (a :: a0 :: l))), tl (CPToList cp) = CPToList (tailCP cp).\nProof.\nsimpl; reflexivity.\nQed.\n\nLemma CPToListTl2 {T : Type} {n : nat} :\n  forall (cp : cartesianPower T (S (S n))), tl (CPToList cp) = CPToList (tailCP cp).\nProof.\nintro cp.\ninduction n.\nsimpl; reflexivity.\napply listInd with (S n) (fst cp).\napply eq_add_S.\nassert (H := lengthOfCPToList cp); rewrite H.\nsimpl; reflexivity.\nassert (H := lengthOfCPToList (tailCP cp)); rewrite H.\nreflexivity.\nsimpl; reflexivity.\nsimpl; reflexivity.\nQed.\n\nLemma CPCPL {T : Type} :\n  forall (a : T) l (cp1 : cartesianPower T (length (a :: l)))\n  (cp2 : cartesianPower T (S(length l))),\n  cp1 = cp2 -> CPToList cp1 = CPToList cp2.\nProof.\nintros; subst; reflexivity.\nQed.\n\nLemma CPLCP {T : Type} {n : nat} :\n  forall (cp1 cp2 : cartesianPower T (S n)),\n  CPToList cp1 = CPToList cp2 -> cp1 = cp2.\nProof.\ninduction n; intros cp1 cp2 HCPL.\n\n  simpl in *.\n  injection HCPL.\n  auto.\n\n  do 2 (rewrite CPToListOK in HCPL).\n  apply CP_ind.\n\n    injection HCPL; auto.\n\n    apply IHn.\n    injection HCPL; auto.\nQed.\n\nLemma CPLRec {T : Type} :\n  forall (a : T) l Default,\n  (a :: (CPToList (ListToCP l Default))) = CPToList (ListToCP (a :: l) Default).\nProof.\nintros a l Default.\nassert (HlAux := lengthOfCPToList (ListToCP l Default)).\nassert (Hl : S (length l) = length (a :: CPToList (ListToCP l Default))) by (simpl; apply eq_S; assumption);\nclear HlAux; apply eq_sym in Hl.\nassert (Hal := lengthOfCPToList (ListToCP (a :: l) Default)); apply eq_sym in Hal.\napply listInd with (length l) Default; try assumption.\nrewrite CPLHd; simpl; reflexivity.\nassert (H : tl (a :: CPToList (ListToCP l Default)) = CPToList (ListToCP l Default)) by (simpl; reflexivity);\nrewrite H; clear H.\ninduction l.\nsimpl; reflexivity.\nclear IHl.\nassert (H := CPToListTl1 a a0 l (ListToCP (a :: a0 :: l) Default)); rewrite H; clear H.\nassert (H := CPCPL a0 l (ListToCP (a0 :: l) Default) (tailCP (ListToCP (a :: a0 :: l) Default)));\napply H; clear H.\nassert (Ha0l : (S (length l)) = length (a0  :: l)) by (simpl; reflexivity).\nassert (Haa0l : (S (S (length l))) = length (a :: a0  :: l)) by (simpl; reflexivity).\nassert (H := ListToCPTl a a0 l Ha0l Haa0l Default); rewrite <- H; clear H.\nunfold tailCPbis.\nrepeat (elim_eq_rect; simpl); reflexivity.\nQed.\n\nLemma CPLOK {T : Type} : forall (l : list T) Default,\n  CPToList (ListToCP l Default) = l.\nProof.\nintros l Default.\ninduction l.\nsimpl; reflexivity.\nrewrite <- CPLRec.\nrewrite IHl.\nreflexivity.\nQed.\n\nDefinition fixLastCP {T:Type} {n:nat} (appPred : cartesianPower T (S (S n)) -> Prop) (t : T) : cartesianPower T (S n) -> Prop.\nProof.\nintro cp.\napply appPred.\nexact (consTailCP cp t).\nDefined.\n\nLemma fixLastCPOK {T:Type} {n:nat} :\n  forall (appPred : cartesianPower T (S (S n)) -> Prop) (cp : cartesianPower T (S n)) (t : T),\n  appPred (consTailCP  cp t) = (fixLastCP appPred t) cp.\nProof.\nintros appPred cp; unfold fixLastCP; reflexivity.\nQed.\n\nDefinition app {T:Type} {n:nat} (pred : arity T n) (cp : cartesianPower T n) : Prop.\nProof.\ninduction n; [apply pred|clear IHn].\ninduction n; [exact (pred cp)|exact (IHn (pred (headCP cp)) (tailCP cp))].\nDefined.\n\nDefinition app_n_1 {T:Type} {n:nat} (pred : arity T (S n)) (cp : cartesianPower T n) (x : T) : Prop.\nProof.\ninduction n; [exact (pred x)|clear IHn].\ninduction n; [exact (pred cp x)|exact (IHn (pred (headCP cp)) (tailCP cp))].\nDefined.\n\nLemma app_n_1_app {T:Type} {n:nat} :\n  forall (pred : arity T (S (S n))) (x : T)\n         (cpp : cartesianPower T (S n)) (cpt : cartesianPower T (S (S n))),\n    app_n_1 pred cpp x -> allButLastCP cpt = cpp -> lastCP cpt = x ->\n    app pred cpt.\nProof.\nintros.\ninduction n.\n\n  simpl in *.\n  rewrite H0; rewrite H1.\n  apply H.\n\n  apply IHn with (tailCP cpp); clear IHn.\n\n    unfold app_n_1 in *.\n    assert (H3 : (fst cpt) = fst (cpp)) by (rewrite <- H0; simpl; reflexivity).\n    simpl in *.\n    rewrite H3.\n    apply H.\n\n    rewrite <- H0.\n    induction n.\n\n      simpl; reflexivity.\n\n      apply CP_ind.\n\n        simpl; reflexivity.\n\n        simpl in *; reflexivity.\n\n    rewrite <- H1.\n    induction n.\n\n      simpl; reflexivity.\n\n      simpl; reflexivity.\nQed.\n\nLemma app_app_n_1 {T:Type} {n:nat} :\n  forall (pred : arity T (S (S n))) (x : T) (cpp : cartesianPower T (S n)) (cpt : cartesianPower T (S (S n))),\n  app pred cpt -> allButLastCP cpt = cpp -> lastCP cpt = x ->\n  app_n_1 pred cpp x.\nProof.\nintros.\ninduction n.\n\n  simpl in *.\n  rewrite <- H0; rewrite <- H1.\n  apply H.\n\n  apply IHn with (tailCP cpt); clear IHn.\n\n    unfold app in *.\n    assert (H3 : (fst cpt) = fst (cpp)) by (rewrite <- H0; simpl; reflexivity).\n    simpl in *.\n    rewrite <- H3.\n    apply H.\n\n    rewrite <- H0.\n    induction n.\n\n      simpl; reflexivity.\n\n      apply CP_ind.\n\n        simpl; reflexivity.\n\n        simpl in *; reflexivity.\n\n    rewrite <- H1.\n    induction n.\n\n      simpl; reflexivity.\n\n      simpl; reflexivity.\nQed.\n\nLemma app_n_1_app_eq {T:Type} {n:nat} :\n  forall (pred : arity T (S (S n))) (x : T) (cpp : cartesianPower T (S n)) (cpt : cartesianPower T (S (S n))),\n  allButLastCP cpt = cpp -> lastCP cpt = x ->\n  (app pred cpt <-> app_n_1 pred cpp x).\nProof.\nintros.\nsplit.\n\n  intro H1.\n  apply (app_app_n_1 pred x cpp cpt H1 H H0).\n\n  intro H1.\n  apply (app_n_1_app pred x cpp cpt H1 H H0).\nQed.\n\nDefinition app_1_n {T:Type} {n:nat} (pred : arity T (S n)) (x : T) (cp : cartesianPower T n) : Prop.\nProof.\ninduction n; [exact (pred x)|clear IHn].\ninduction n; [exact (pred x cp)|clear IHn].\nassert (newPred : arity T (S n)) by (exact (pred x (headCP cp))).\nexact (app newPred (tailCP cp)).\nDefined.\n\nLemma app_1_n_app {T:Type} {n:nat} :\n  forall (pred : arity T (S (S n))) (x : T) (cpp : cartesianPower T (S n)) (cpt : cartesianPower T (S (S n))),\n  app_1_n pred x cpp -> headCP cpt = x -> tailCP cpt = cpp ->\n  app pred cpt.\nProof.\nintros.\ninduction n.\n\n  simpl in *.\n  rewrite H0; rewrite H1.\n  apply H.\n\n  clear IHn.\n  simpl in *.\n  rewrite H0; rewrite H1.\n  apply H.\nQed.\n\nLemma app_app_1_n {T:Type} {n:nat} :\n  forall (pred : arity T (S (S n))) (x : T) (cpp : cartesianPower T (S n)) (cpt : cartesianPower T (S (S n))),\n  app pred cpt -> headCP cpt = x -> tailCP cpt = cpp ->\n  app_1_n pred x cpp.\nProof.\nintros.\ninduction n.\n\n  simpl in *.\n  rewrite <- H0; rewrite <- H1.\n  apply H.\n\n  clear IHn.\n  simpl in *.\n  rewrite <- H0; rewrite <- H1.\n  apply H.\nQed.\n\nLemma app_1_n_app_eq {T:Type} {n:nat} :\n  forall (pred : arity T (S (S n))) (x : T) (cpp : cartesianPower T (S n)) (cpt : cartesianPower T (S (S n))),\n  headCP cpt = x -> tailCP cpt = cpp ->\n  (app pred cpt <-> app_1_n pred x cpp).\nProof.\nintros.\nsplit.\n\n  intro H1.\n  apply (app_app_1_n pred x cpp cpt H1 H H0).\n\n  intro H1.\n  apply (app_1_n_app pred x cpp cpt H1 H H0).\nQed.\n\nDefinition app_2_n {T:Type} {n:nat} (pred : arity T (S (S n))) (x1 x2 : T) (cp : cartesianPower T n) : Prop.\nProof. exact (app (pred x1 x2) cp). Defined.\n\nLemma app_2_n_app {T:Type} {n:nat} :\n  forall (pred : arity T (S (S (S n)))) (x1 x2 : T)\n  (cpp : cartesianPower T (S n)) (cpt : cartesianPower T (S (S (S n)))),\n  app_2_n pred x1 x2 cpp -> headCP cpt = x1 -> headCP (tailCP cpt) = x2 -> tailCP (tailCP cpt) = cpp ->\n  app pred cpt.\nProof.\nintros.\ninduction n.\n\n  simpl in *.\n  rewrite H0; rewrite H1; rewrite H2.\n  apply H.\n\n  clear IHn.\n  simpl in *.\n  rewrite H0; rewrite H1; rewrite H2.\n  apply H.\nQed.\n\nLemma app_2_n_app_default {T:Type} {n:nat} :\n  forall (pred : arity T (S (S n))) (x1 x2 : T)\n  (cpp Default : cartesianPower T n) (cpt : cartesianPower T (S (S n))),\n  app_2_n pred x1 x2 cpp -> headCP cpt = x1 ->\n  headCP (tailCP cpt) = x2 ->\n  tailDefaultCP (tailCP cpt) Default = cpp ->\n  app pred cpt.\nProof.\nintros.\ninduction n.\n\n  simpl in *.\n  rewrite H0; rewrite H1.\n  apply H.\n\n  simpl in *.\n  rewrite H0; rewrite H1; rewrite H2.\n  apply H.\nQed.\n\nLemma app_app_2_n {T:Type} {n:nat} :\n  forall (pred : arity T (S (S (S n)))) (x1 x2 : T)\n  (cpp : cartesianPower T (S n)) (cpt : cartesianPower T (S (S (S n)))),\n  app pred cpt -> headCP cpt = x1 -> headCP (tailCP cpt) = x2 -> tailCP (tailCP cpt) = cpp ->\n  app_2_n pred x1 x2 cpp.\nProof.\nintros.\ninduction n.\n\n  simpl in *.\n  rewrite <- H0; rewrite <- H1; rewrite <- H2.\n  apply H.\n\n  clear IHn.\n  simpl in *.\n  rewrite <- H0; rewrite <- H1; rewrite <- H2.\n  apply H.\nQed.\n\nLemma app_app_2_n_default {T:Type} {n:nat} :\n  forall (pred : arity T (S (S n))) (x1 x2 : T)\n  (cpp Default : cartesianPower T n) (cpt : cartesianPower T (S (S n))),\n  app pred cpt -> headCP cpt = x1 -> headCP (tailCP cpt) = x2 -> tailDefaultCP (tailCP cpt) Default = cpp ->\n  app_2_n pred x1 x2 cpp.\nProof.\nintros.\ninduction n.\n\n  simpl in *.\n  rewrite <- H0; rewrite <- H1; rewrite <- H2.\n  apply H.\n\n  clear IHn.\n  simpl in *.\n  rewrite <- H0; rewrite <- H1; rewrite <- H2.\n  apply H.\nQed.\n\nLemma app_2_n_app_eq {T:Type} {n:nat} :\n  forall (pred : arity T (S (S (S n)))) (x1 x2 : T)\n  (cpp : cartesianPower T (S n)) (cpt : cartesianPower T (S (S (S n)))),\n  headCP cpt = x1 -> headCP (tailCP cpt) = x2 -> tailCP (tailCP cpt) = cpp ->\n  (app pred cpt <-> app_2_n pred x1 x2 cpp).\nProof.\nintros.\nsplit.\n\n  intro H2.\n  apply (app_app_2_n pred x1 x2 cpp cpt H2 H H0 H1).\n\n  intro H2.\n  apply (app_2_n_app pred x1 x2 cpp cpt H2 H H0 H1).\nQed.\n\nLemma PermOKAux {T : Type} {m : nat} :\n  forall (appPred : (cartesianPower T (S (S m))) -> Prop) n,\n  (forall (A : T) (X : cartesianPower T (S m)), appPred (consHeadCP A X) -> appPred (consTailCP X A)) ->\n  forall (X : cartesianPower T (S (S m))),\n          appPred X -> appPred (circPermNCP n X).\nProof.\nintros appPred n HPerm.\ninduction n.\nsimpl; auto.\nintros X HappPred.\nassert (H : appPred (circPermNCP n X)) by (apply IHn; assumption); clear IHn; clear HappPred.\nrewrite consHeadCPOK in H.\napply HPerm in H.\nrewrite circPermNCPOK.\nrewrite <- circPermNConsTlOK.\nassumption.\nQed.\n\nLemma PermOK {T : Type} {n : nat} :\n  forall (cp1 cp2 : cartesianPower T (S (S n))) (appPred : (cartesianPower T (S (S n))) -> Prop),\n  (forall (A : T) (X : cartesianPower T (S n)),\n    appPred (consHeadCP A X) -> appPred (consTailCP X A)) ->\n  (forall (A B : T) (X : cartesianPower T n),\n    appPred (consHeadCP A (consHeadCP B X)) -> appPred (consHeadCP B (consHeadCP A X))) ->\n  appPred cp1 ->\n  Permutation.Permutation (CPToList cp1) (CPToList cp2) ->\n  appPred cp2.\nProof.\ninduction n; intros cp1 cp2 appPred pred_perm_1 pred_perm_2 Hpred HPerm.\n\n  assert (Hcp1 := CPPair cp1); rewrite Hcp1 in *; clear Hcp1.\n  assert (Hcp2 := CPPair cp2); rewrite Hcp2 in *; clear Hcp2.\n  simpl in *.\n  apply Permutation.Permutation_length_2 in HPerm.\n  elim HPerm; clear HPerm; intro HPerm; destruct HPerm as [HEq1 HEq2]; rewrite <- HEq1; rewrite <- HEq2.\n\n    assumption.\n\n    apply pred_perm_1; assumption.\n\n  rewrite consTailCPOK.\n  assert (H' := lastCPIn cp2).\n  assert (H : InCP (lastCP cp2) cp1)\n    by (unfold InCP;apply Permutation.Permutation_in with (CPToList cp2);\n        try apply Permutation.Permutation_sym; assumption); clear H'.\n  assert (H' := InNth cp1 (lastCP cp2) (headCP cp2) H); clear H.\n  destruct H' as [id [Hge [Hle Hnth]]].\n  assert (H : exists cp, appPred cp /\\ Permutation.Permutation (CPToList cp2) (CPToList cp) /\\\n                                       lastCP cp = lastCP cp2).\n\n    induction id; try (unfold ge in Hge; assert (H := Le.le_Sn_0 0); contradiction); clear IHid.\n    revert Hnth; revert HPerm; revert Hpred; revert cp1; induction id; intros.\n\n      exists (consTailCP (tailCP cp1) (headCP cp1)).\n      split.\n\n        apply pred_perm_1.\n        rewrite <- consHeadCPOK.\n        assumption.\n\n        split.\n\n          apply Permutation.perm_trans with (CPToList cp1); try (apply consTailPerm).\n          apply Permutation.Permutation_sym; assumption.\n\n          apply nthCircPerm1 in Hnth.\n          rewrite Hnth.\n          assert (H := nthLast (consTailCP (tailCP cp1) (headCP cp1)) (headCP cp2)); rewrite H; reflexivity.\n\n      assert (H := Hle).\n      do 2 (apply Le.le_S_n in H).\n      apply nthCircPerm2 in Hnth; try assumption; clear H.\n      apply Le.le_Sn_le in Hle.\n      assert (H : S id >= 1) by intuition; clear Hge; rename H into Hge.\n      assert (H : appPred (consTailCP (tailCP cp1) (headCP cp1)))\n        by (apply pred_perm_1; rewrite <- consHeadCPOK; assumption) ; clear Hpred; rename H into Hpred.\n      assert (H := consTailPerm cp1); apply Permutation.Permutation_sym in H.\n      assert (H' : Permutation.Permutation (CPToList (consTailCP (tailCP cp1) (headCP cp1))) (CPToList cp2))\n        by (apply Permutation.perm_trans with (CPToList cp1); assumption); clear HPerm; rename H' into HPerm.\n      assert (H' := IHid Hge Hle (consTailCP (tailCP cp1) (headCP cp1)) Hpred HPerm Hnth).\n      destruct H' as [cp [Hpredcp [HPermcp Hlastcp]]]; exists cp.\n      do 2 (split; try assumption).\n\n  clear Hnth; clear Hle; clear Hge; clear id; clear HPerm; clear Hpred; clear cp1.\n  destruct H as [cp [Hpred [HPerm Hlast]]]; rewrite <- Hlast.\n  assert (H := consTailCPOK cp); rewrite H in HPerm; clear H.\n  assert (H := consTailCPOK cp2); rewrite H in HPerm; clear H.\n  do 2 (rewrite consTailOK in HPerm).\n  rewrite Hlast in HPerm.\n  apply Permutation.Permutation_app_inv_r in HPerm.\n  assert (ablcp := allButLastCP cp).\n  assert (ablcp2 := allButLastCP cp2).\n  assert (pred_perm_3 := PermOKAux appPred (S n) pred_perm_1).\n  assert (HPerm1 : (forall (A : T) (X : cartesianPower T (S n)),\n                   (fixLastCP appPred (lastCP cp)) (consHeadCP A X) ->\n                   (fixLastCP appPred (lastCP cp)) (consTailCP X A))).\n\n    unfold fixLastCP; intros A X HappPred.\n    induction n.\n\n      simpl in HappPred.\n      apply pred_perm_2.\n      simpl.\n      assumption.\n\n      clear IHn0.\n      induction n.\n\n        simpl.\n        simpl in HappPred.\n        simpl in pred_perm_1.\n        simpl in pred_perm_2.\n        apply pred_perm_2 in HappPred.\n        apply pred_perm_1 in HappPred; simpl in HappPred.\n        apply pred_perm_2 in HappPred.\n        apply pred_perm_1 in HappPred; simpl in HappPred.\n        apply pred_perm_3 in HappPred; simpl in HappPred.\n        assumption.\n\n        clear IHn0.\n        induction n.\n\n          simpl.\n          simpl in HappPred.\n          simpl in pred_perm_1.\n          simpl in pred_perm_2.\n          apply pred_perm_2 in HappPred.\n          apply pred_perm_1 in HappPred; simpl in HappPred.\n          apply pred_perm_2 in HappPred.\n          apply pred_perm_1 in HappPred; simpl in HappPred.\n          apply pred_perm_2 in HappPred.\n          apply pred_perm_1 in HappPred; simpl in HappPred.\n          apply pred_perm_1 in HappPred; simpl in HappPred.\n          apply pred_perm_1 in HappPred; simpl in HappPred.\n          assumption.\n\n          clear IHn0.\n          assert (H := consHeadCPOK X); rewrite H in *; clear H.\n          assert (H := consTailCPOK (tailCP X)); rewrite H in *; clear H.\n          set (B := headCP X) in *.\n          set (CP := allButLastCP (allButLastCP (tailCP X))) in *.\n          set (C := tailCP (allButLastCP (tailCP X))) in *.\n          set (D := lastCP (tailCP X)) in *.\n          set (E := lastCP cp) in *.\n          apply pred_perm_3 in HappPred; rewrite consTlHdHdTl in HappPred; rewrite circPermNConsOK in HappPred.\n          apply pred_perm_1 in HappPred; do 2 (rewrite <- consHdTlTlHd in HappPred).\n          apply pred_perm_2 in HappPred.\n          apply pred_perm_1; rewrite <- consHdTlTlHd; rewrite <- circPermNConsOK.\n          apply pred_perm_3.\n          do 2 (apply pred_perm_1; rewrite consHdTlTlHd); rewrite consHdTlTlHd.\n          apply pred_perm_1.\n          assumption.\n  assert (HPerm2 : (forall (A B : T) (X : cartesianPower T n),\n                   (fixLastCP appPred (lastCP cp)) (consHeadCP A (consHeadCP B X)) ->\n                   (fixLastCP appPred (lastCP cp)) (consHeadCP B (consHeadCP A X))))\n    by (unfold fixLastCP; intros A B X HappPred; rewrite <- consTlHdHdTl;\n        apply pred_perm_2; rewrite consTlHdHdTl; assumption).\n  apply Permutation.Permutation_sym in HPerm.\n  assert (H := IHn (allButLastCP cp) (allButLastCP cp2) (fixLastCP appPred (lastCP cp)) HPerm1 HPerm2).\n  apply H; try assumption.\n  rewrite <- fixLastCPOK.\n  rewrite <- consTailCPOK.\n  assumption.\nQed.\n\nLemma lengthNilOK {A : Type} : forall (l : list A),\n  length l = 0 -> l = nil.\nProof.\nintros l Hlength; induction l.\n\n  reflexivity.\n\n  simpl in Hlength.\n  discriminate.\nQed.\n\nLemma NoDupOK {A : Type} : forall (l l' : list A),\n  incl l l' ->\n  length l = length l' ->\n  NoDup l ->\n  Permutation.Permutation l l'.\nProof.\nintro l; induction l; intros l' Hincl Hlength HNoDup.\n\n  simpl in Hlength.\n  apply eq_sym in Hlength.\n  apply lengthNilOK in Hlength.\n  subst.\n  apply Permutation.perm_nil.\n\n  induction l'.\n\n    simpl in Hlength.\n    discriminate.\n\n    clear IHl'.\n    rename a0 into a'.\n    assert (HIn := in_eq a l).\n    assert (H := Hincl).\n    unfold incl in H.\n    apply H in HIn.\n    clear H.\n    apply in_split in HIn.\n    destruct HIn as [l1 [l2 Hl']].\n    rewrite Hl' in *.\n    apply Permutation.Permutation_cons_app.\n    apply IHl.\n\n      unfold incl.\n      intros e HIn.\n      unfold incl in Hincl.\n      assert (H := Hincl e).\n      clear Hincl.\n      assert (HIn' := in_cons a e l HIn).\n      apply H in HIn'.\n      clear H.\n      apply in_app_or in HIn'.\n      elim HIn'; clear HIn'; intro HIn'.\n\n        apply in_or_app.\n        auto.\n\n        apply in_inv in HIn'.\n        elim HIn'; clear HIn'; intro HIn'.\n\n          subst.\n          assert (H := NoDup_remove_2 nil l e).\n          simpl in H.\n          apply H in HNoDup.\n          contradiction.\n\n          apply in_or_app.\n          auto.\n\n      rewrite app_length.\n      rewrite app_length in Hlength.\n      simpl in Hlength.\n      rewrite <- plus_n_Sm in Hlength.\n      apply eq_add_S in Hlength.\n      assumption.\n\n      assert (H := NoDup_remove_1 nil l a).\n      simpl in H.\n      apply H.\n      assumption.\nQed.\n\nLemma NoDup_dec {A : Type} : forall (l : list A),\n  (forall x y : A, {x = y} + {x <> y}) ->\n  NoDup l \\/ ~ NoDup l.\nProof.\nintros l HDec.\ninduction l.\n\n  left.\n  apply NoDup_nil.\n\n  elim IHl; clear IHl; intro H.\n\n    assert (HIn := in_dec HDec a l).\n    elim HIn; clear HIn; intro HIn.\n\n      right.\n      clear H.\n      intro H.\n      assert (H' := NoDup_remove_2 nil l a).\n      simpl in H'.\n      apply H' in H.\n      contradiction.\n\n      left.\n      apply NoDup_cons; assumption.\n\n    right.\n    intro H'.\n    apply H.\n    clear H.\n    assert (H := NoDup_remove_1 nil l a).\n    simpl in H.\n    auto.\nQed.\n\nLemma NotNoDupDup {A : Type} : forall (l : list A),\n  (forall x y : A, {x = y} + {x <> y}) ->\n  ~ NoDup l->\n  exists e l1 l2, l = l1 ++ e :: l2 /\\ In e (l1 ++ l2).\nProof.\nintros l HDec.\ninduction l; intro HDup.\n\n  assert (H := NoDup_nil A).\n  contradiction.\n\n  assert (HIn := in_dec HDec a l).\n  elim HIn; clear HIn; intro HIn.\n\n    exists a; exists nil; exists l.\n    simpl.\n    auto.\n\n    assert (HDup' := NoDup_dec l HDec).\n    elim HDup'; clear HDup'; intro HDup'.\n\n      exfalso.\n      apply HDup.\n      apply NoDup_cons; assumption.\n\n      apply IHl in HDup'.\n      clear HDec; clear HDup; clear HIn.\n      destruct HDup' as [e [l1 [l2 [HEq HIn]]]]; clear IHl.\n      exists e; exists (a :: l1); exists l2.\n      simpl.\n      split.\n\n        rewrite HEq; reflexivity.\n\n        right; assumption.\nQed.\n\nDefinition pred_conj_aux {T:Type} {n:nat} (pred : arity T (S n)) (m : nat) (cp : cartesianPower T (S m)) (cpwd : cartesianPower T n) : Prop.\nProof.\ninduction m.\nexact (app_1_n pred cp cpwd).\nexact ((app_1_n pred (headCP cp) cpwd) /\\ IHm (tailCP cp)).\nDefined.\n\nLemma pcaHdTl {T:Type} {n:nat} : forall (pred : arity T (S n)) m cp cpwd,\n  pred_conj_aux pred (S m) cp cpwd = (app_1_n pred (headCP cp) cpwd /\\ pred_conj_aux pred m (tailCP cp) cpwd).\nProof.\nunfold pred_conj_aux; unfold nat_rect; reflexivity.\nQed.\n\nDefinition pred_conj {T:Type} {n:nat} (pred : arity T (S n)) (cp : cartesianPower T (S n)) (cpwd : cartesianPower T n) : Prop.\nProof.\nexact (pred_conj_aux pred n cp cpwd).\nDefined.\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Utils/arity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6862143626529489}}
{"text": "Require Import A_4.\n\n(*微积分系统的基本定理*)\n\n(* 定理4.1: 设F(x)在[a,b]上一致可导，其导数为f(x).\n   若在[a,b]上恒有f(x)>=0, 则F(x)单调增；\n   若在[a,b]上恒有f(x)<=0, 则F(x)单调减；\n   不等式中等号不成立时，则F(x)严格单调增或严格单调减 *)\n\nTheorem Theorem5_1 : forall F f a b, derivative F f a b -> \n  ((forall x, x ∈ [a,b] -> f(x)>=0) -> mon_increasing F [a,b]) /\\\n  ((forall x, x ∈ [a,b] -> f(x)<=0) -> mon_decreasing F [a,b]) /\\\n  ((forall x, x ∈ [a,b] -> f(x)>0) -> strict_mon_increasing F [a,b]) /\\\n  ((forall x, x ∈ [a,b] -> f(x)<0) -> strict_mon_decreasing F [a,b]).\nProof.\n  intros.\n  apply Theorem4_4 in H. destruct H.\n  unfold diff_quo_median in H.\n  assert(forall x0 x y a b, x0 ∈ [x, y] ->\n         x ∈ [a, b] -> y ∈ [a, b] -> x0 ∈ [a, b]) as Domain_x0.\n   { intros.\n     destruct H1, H2, H3. split; auto. split.\n     apply Rle_trans with (r2:=x); tauto.\n     apply Rle_trans with (r2:=y); tauto. }\n  repeat split; intros.\n  - unfold mon_increasing; intros.\n    generalize H2 as H3; intro.\n    apply H in H2.\n    destruct H3, H4, H2, H2, H2, H6, H7.\n    apply Domain_x0 with (x0:=x0)(x:=x) in H4; auto.\n    apply H1 in H4.\n    apply Rle_trans with (r1:=0) in H7.\n    apply Rmult_le_compat_r with (r:= y-x) in H7.\n    rewrite Rmult_0_l in H7.\n    unfold Rdiv in H7; rewrite Rinv_mult_rgt0 in H7; auto.\n    apply Rplus_le_reg_r with (r:=-F x). rewrite Rplus_opp_r; auto.\n    apply Rlt_le; auto. apply Rge_le; auto.\n  - unfold mon_decreasing; intros.\n    generalize H2 as H3; intro. apply H in H2.\n    destruct H3, H4, H2, H2, H2, H6, H7.\n    apply Domain_x0 with (x0:=x1)(x:=x) in H4; auto.\n    apply H1 in H4.\n    apply Rle_trans with (r3:=0) in H8; auto.\n    apply Rmult_le_compat_r with (r:= y-x) in H8.\n    rewrite Rmult_0_l in H8.\n    unfold Rdiv in H8; rewrite Rinv_mult_rgt0 in H8; auto.\n    apply Rle_ge; apply Rplus_le_reg_r with (r:=-F x).\n    rewrite Rplus_opp_r; auto. apply Rlt_le; auto.\n  - unfold strict_mon_increasing; intros.\n    generalize H2 as H3; intro. apply H in H2.\n    destruct H3, H4, H2, H2, H2, H6, H7.\n    apply Domain_x0 with (x0:=x0)(x:=x) in H4; auto.\n    apply H1 in H4.\n    apply Rlt_le_trans with (r1:=0) in H7; auto.\n    apply Rmult_lt_compat_r with (r:= y-x) in H7; auto.\n    rewrite Rmult_0_l in H7.\n    unfold Rdiv in H7; rewrite Rinv_mult_rgt0 in H7; auto.\n    apply Rplus_lt_reg_r with (r:=-F x).\n    rewrite Rplus_opp_r; auto.\n  - unfold strict_mon_decreasing; intros.\n    generalize H2 as H3; intro. apply H in H2.\n    destruct H3, H4, H2, H2, H2, H6, H7.\n    apply Domain_x0 with (x0:=x1)(x:=x) in H4; auto.\n    apply H1 in H4.\n    apply Rle_lt_trans with (r3:=0) in H8; auto.\n    apply Rmult_lt_compat_r with (r:= y-x) in H8; auto.\n    rewrite Rmult_0_l in H8.\n    unfold Rdiv in H8; rewrite Rinv_mult_rgt0 in H8; auto.\n    apply Rplus_lt_reg_r with (r:=-F x).\n    rewrite Rplus_opp_r; auto.\nQed.\n\n\nTheorem Theorem5_2 : forall F f a b , derivative F f a b ->\n  (fun u v=>F v-F u) ∫ f (x)dx a b.\nProof.\n  intros.\n  apply Theorem4_4 in H.\n  destruct H.\n  apply Theorem4_2 in H; auto.\n  destruct H; auto.\nQed.\n\n\nTheorem Theorem5_3 : forall G f a b, uniform_continuous f a b ->\n  (exists (S: R->R->R), integ_sys' S f a b /\\\n  forall x, x ∈ [a,b] -> G(x) = S a x) ->\n  derivative G f a b.\nProof.\n  intros.\n  destruct H0, H0. rename x into S.\n  assert(diff_quo_median G f a b).\n   { unfold diff_quo_median. intros.\n     unfold integ_sys' in H0. destruct H0.\n     unfold additivity' in H0. unfold median in H3.\n     assert(a ∈ [a, b] /\\ u ∈ [a, b] /\\ v ∈ [a, b]).\n      { split; try tauto. destruct H2, H2.\n        split; auto. split.\n        apply Req_le; reflexivity.\n        apply Rlt_le; auto. }\n     apply H0 in H4.\n     generalize (H1 u); intro.\n     generalize (H1 v); intro.\n     rewrite H5; try tauto. clear H5.\n     rewrite H6; try tauto. clear H6.\n     assert(v - u > 0) as gt_v_u . { tauto. }\n     apply H3 in H2. destruct H2, H2, H2, H5.\n     exists x,x0. split; auto. split; auto.\n     apply Rmult_le_r with(r:=v-u); auto.\n     rewrite Rplus_comm in H4; rewrite <- H4.\n     unfold Rminus. rewrite Rplus_assoc.\n     rewrite Rplus_opp_r; rewrite Rplus_0_r.\n     unfold Rdiv. rewrite Rinv_mult_rgt0; auto. }\n  apply Theorem4_4. split; auto.\nQed.\n\n(*阶乘*)\nFixpoint  factorial (n:nat) : nat :=\n  match n with\n  | 0 => 1\n  | S p => S p * (factorial p)\n  end.\n\n(*实数x的n次幂*)\nFixpoint  power (n:nat) x : R :=\n  match n with\n  | 0 => 1\n  | S p => x * power p x\n  end.\n\n\nFixpoint accumulation x1 x2 (n i:nat) : R :=\n  match i with\n  | 0 => power n x1\n  | S p => (power (n - S p) x1)*(power (S p) x2) + accumulation x1 x2 n p\n  end.\n\n\nLemma fix_property : forall x y (n i:nat), (i<=n)%nat ->\n  accumulation x y (n+1) i = x*accumulation x y n i.\nProof.\n  intros.\n  assert(forall x (n:nat), x * power n x = power (n + 1) x).\n     { intros.\n       induction n0; simpl; auto.\n       rewrite IHn0; auto. }\n  induction i.\n  - simpl.\n    rewrite H0; auto.\n  - simpl.\n    generalize H; intro.\n    apply le_Sn_le in H.\n    rewrite (IHi H); rewrite Rmult_plus_distr_l.\n    apply Rplus_eq_compat_r.\n    rewrite <- (Rmult_assoc x); rewrite (H0 x).\n    rewrite Nat.add_sub_swap; auto.\nQed.\n\n\n(* x^(n+1) - y^(n+1) = (x-y)*∑(x^(n-i)*y^i) *)\nLemma  decompose_th : forall x y (n:nat),\n  power (n+1) x - power (n+1) y = (x-y)*accumulation x y n n.\nProof.\n  intros.\n  induction n.\n  - simpl.\n    repeat rewrite Rmult_1_r; auto.\n  - simpl.\n    rewrite <- (Nat.add_1_r n).\n    rewrite (fix_property x y n n); auto.\n    rewrite Nat.sub_diag.\n    simpl. rewrite Rmult_1_l.\n    rewrite (Rmult_plus_distr_l (x-y) (y * power n y) (x * accumulation x y n n)).\n    rewrite Rmult_comm with (r2:=(x * accumulation x y n n)).\n    rewrite Rmult_assoc with (r1:=x).\n    rewrite Rmult_comm with (r1:=accumulation x y n n).\n    rewrite <- IHn.\n    rewrite Rplus_comm.\n    unfold Rminus. rewrite Rmult_plus_distr_r.\n    rewrite Rmult_plus_distr_l.\n    rewrite Rplus_assoc; apply Rplus_eq_compat_l.\n    rewrite <- Rplus_assoc.\n    assert(forall x (n:nat), x * power n x = power (n + 1) x).\n     { intros.\n       induction n0; simpl; auto.\n       rewrite IHn0; auto. }\n    assert(x * - power (n + 1) y + x * (y * power n y) = 0).\n     { rewrite <- Rmult_plus_distr_l.\n       rewrite H; ring. }\n    rewrite H0; rewrite Rplus_0_l.\n    rewrite (H y n). ring.\nQed.\n\n\nLemma exist_Rgt_lt : forall r1 r2,r1<r2 -> exists r, r1<r<r2.\nProof.\n  intros.\n  exists ((r1+r2)/2).\n  split.\n  - apply Rlt_mult. apply Rlt_0_2.\n    rewrite Rmult_comm; rewrite double.\n    apply Rplus_lt_compat_l with (r:=r1); auto.\n  - apply Rgt_lt; apply Rgt_mult. apply Rlt_0_2.\n    rewrite Rmult_comm; rewrite double.\n    apply Rplus_gt_compat_r with (r:=r2); auto.\nQed.\n\n\nLemma  accumul_th : forall a b n,\n  a>=0 -> b>=0 -> a>b -> accumulation a b n n <= INR(n+1)* power n a /\\\n  accumulation a b n n >= INR(n+1)%nat* power n b.\nProof.\n  intros.\n  induction n. simpl.\n  rewrite Rmult_1_r.\n  split. apply Rle_refl. apply Rge_refl.\n  destruct IHn.\n  assert(accumulation a b (S n) (S n)=\n         a*accumulation a b n n + power(S n) b).\n   { simpl.\n     rewrite <- Nat.add_1_r.\n     rewrite fix_property; try apply Nat.le_refl.\n     rewrite Nat.sub_diag. simpl.\n     rewrite Rmult_1_l. ring. }\n  assert(forall n a, power (n+1) a = (power n a) * a).\n   { intros. induction n0.\n     simpl.\n     rewrite Rmult_1_l; rewrite Rmult_1_r; auto.\n     simpl. rewrite IHn0; rewrite Rmult_assoc; auto. }\n  assert(forall a n, a>=0 -> 0<=power n a).\n   { intros.\n     induction n0.\n     simpl. apply Rlt_le; apply Rlt_0_1.\n     simpl. apply Rmult_le_pos; auto. apply Rge_le; auto. }\n  split; rewrite H4; rewrite plus_INR.\n  - rewrite Rmult_plus_distr_r.\n    rewrite Rmult_1_l.\n    apply Rplus_le_compat.\n    rewrite <- Nat.add_1_r.\n    rewrite H5.\n    rewrite Rmult_comm with (r2:=a).\n    rewrite Rmult_comm with (r1:=INR (n + 1)).\n    rewrite Rmult_assoc.\n    apply Rmult_le_compat_l. apply Rge_le; auto.\n    rewrite Rmult_comm; auto.\n    clear H2 H3 H4 H5.\n    induction n.\n    simpl. repeat rewrite Rmult_1_r.\n    apply Rlt_le; auto.\n    simpl in IHn. simpl.\n    apply Rle_trans with (r2:=a * (b * power n b)).\n    apply Rmult_le_compat_r.\n    apply Rmult_le_pos. apply Rge_le; auto.\n    apply H6; auto. apply Rlt_le; auto.\n    apply Rmult_le_compat_l; auto.\n    apply Rge_le; auto.\n  - rewrite Rmult_plus_distr_r.\n    rewrite Rmult_1_l.\n    apply Rplus_ge_compat; try apply Rge_refl.\n    rewrite <- Nat.add_1_r.\n    rewrite H5.\n    rewrite Rmult_comm with (r2:=b).\n    rewrite Rmult_comm with (r1:=INR (n + 1)).\n    rewrite Rmult_assoc. rewrite Rmult_comm with (r1:=power n b).\n    apply Rle_ge. apply Rge_le in H3.\n    apply Rmult_le_compat; auto. apply Rge_le; auto.\n    apply Rmult_le_pos; auto. apply Rlt_le; apply lt_0_INR.\n    rewrite Nat.add_1_r; apply gt_Sn_O.\n    apply Rlt_le; auto.\nQed.\n\n\nLemma  accumul_th' : forall a b n,\n  a>=0 -> b>=0 -> a<b -> accumulation a b n n <= INR(n+1)* power n b /\\\n  accumulation a b n n >= INR(n+1)%nat* power n a.\nProof.\n  intros.\n  induction n. simpl.\n  rewrite Rmult_1_r.\n  split. apply Rle_refl. apply Rge_refl.\n  destruct IHn.\n  assert(accumulation a b (S n) (S n)=\n         a*accumulation a b n n + power(S n) b).\n   { simpl.\n     rewrite <- Nat.add_1_r.\n     rewrite fix_property; try apply Nat.le_refl.\n     rewrite Nat.sub_diag. simpl.\n     rewrite Rmult_1_l. ring. }\n  assert(forall n a, power (n+1) a = (power n a) * a).\n   { intros. induction n0.\n     simpl.\n     rewrite Rmult_1_l; rewrite Rmult_1_r; auto.\n     simpl. rewrite IHn0; rewrite Rmult_assoc; auto. }\n  assert(forall a n, a>=0 -> 0<=power n a).\n   { intros.\n     induction n0.\n     simpl. apply Rlt_le; apply Rlt_0_1.\n     simpl. apply Rmult_le_pos; auto. apply Rge_le; auto. }\n  split; rewrite H4; rewrite plus_INR.\n  - rewrite Rmult_plus_distr_r.\n    rewrite Rmult_1_l.\n    apply Rplus_le_compat.\n    rewrite <- Nat.add_1_r.\n    rewrite H5.\n    rewrite Rmult_comm with (r2:=b).\n    rewrite Rmult_comm with (r1:=INR (n + 1)).\n    rewrite Rmult_assoc. apply Rmult_le_compat.\n    apply Rge_le; auto. clear H2 H3 H4.\n    assert(forall k, 0 <= accumulation a b n k).\n     { intro. induction k.\n       simpl. apply H6; auto.\n       simpl. apply Rplus_le_le_0_compat; auto.\n       apply Rmult_le_pos. apply H6; auto.\n       apply Rmult_le_pos; auto. apply Rge_le; auto. }\n    apply H2. apply Rlt_le; auto.\n    rewrite Rmult_comm; auto. apply Rle_refl.\n  - rewrite Rmult_plus_distr_r.\n    rewrite Rmult_1_l.\n    apply Rplus_ge_compat; try apply Rge_refl.\n    rewrite <- Nat.add_1_r.\n    rewrite H5.\n    rewrite Rmult_comm with (r2:=a).\n    rewrite Rmult_comm with (r1:=INR (n + 1)).\n    rewrite Rmult_assoc. rewrite Rmult_comm with (r1:=power n a).\n    apply Rle_ge. apply Rge_le in H3.\n    apply Rmult_le_compat; auto. apply Rge_le; auto.\n    apply Rmult_le_pos; auto. apply Rlt_le; apply lt_0_INR.\n    rewrite Nat.add_1_r; apply gt_Sn_O. apply Rle_refl.\n    assert(forall a b n, a>=0 -> b>=0 -> a<=b -> power n a <= power n b).\n    { intros. induction n0.\n      simpl; apply Rle_refl.\n      simpl. apply Rmult_le_compat; auto.\n      apply Rge_le; auto. } apply Rle_ge; apply H7; auto.\n    apply Rlt_le; auto.\nQed.\n\nLemma factorial_Sn : forall n, factorial (S n) = ((S n)*factorial n)%nat.\nProof.\n  intro.\n  induction n.\n  simpl; auto.\n  simpl. ring.\nQed.\n\nLemma factorial_pos : forall n, 0 < INR(factorial n).\nProof.\n  intro.\n  induction n.\n  simpl. apply Rlt_0_1.\n  simpl. rewrite plus_INR.\n  apply Rplus_lt_le_0_compat; auto.\n  rewrite mult_INR. apply Rmult_le_pos.\n  apply pos_INR. apply Rlt_le; auto.\nQed.\n\n\nLemma accumul_abc_bigger : forall a b c n, a>=0 -> b>=0 -> c>=0 -> a<=b ->\n  b<=c -> accumulation b a n n <= INR(n+1)%nat* power n c.\nProof.\n  intros.\n  assert(forall a b n, a>=0 -> b>=0 -> a<=b -> power n a <= power n b).\n   { intros. induction n0.\n     simpl; apply Rle_refl.\n     simpl. apply Rmult_le_compat; auto.\n     apply Rge_le; auto. clear IHn0.\n     induction n0. simpl. apply Rle_0_1.\n     simpl. apply Rmult_le_pos; auto.\n     apply Rge_le; auto. }\n  destruct H2.\n  generalize( accumul_th b a n H0 H H2); intro.\n  destruct H5. apply Rle_trans with (r2:=INR (n + 1) * power n b); auto.\n  apply Rmult_le_compat_l. apply pos_INR.\n  apply H4; auto.\n  rewrite H2.\n  assert(forall a n, accumulation a a n n = INR (n + 1) * power n a).\n   { intros. induction n0.\n     simpl. ring.\n     assert(accumulation a0 a0 (S n0) (S n0)=\n         a0*accumulation a0 a0 n0 n0 + power(S n0) a0).\n      { simpl.\n        rewrite <- Nat.add_1_r.\n        rewrite fix_property; try apply Nat.le_refl.\n        rewrite Nat.sub_diag. simpl.\n        rewrite Rmult_1_l. ring. }\n     rewrite H5. rewrite IHn0. rewrite Rmult_comm.\n     rewrite Rmult_assoc.\n     assert(power n0 a0 * a0 = power (S n0) a0).\n      { simpl. ring. } rewrite H6.\n     rewrite <- Rmult_1_l with (r:=power (S n0) a0) at 2.\n     rewrite <- Rmult_plus_distr_r. apply Rmult_eq_compat_r.\n     rewrite Nat.add_comm with (n:= S n0).\n     rewrite  S_O_plus_INR. rewrite Nat.add_1_r.\n     rewrite Rplus_comm. apply Rplus_eq_compat_r; auto. }\n  rewrite H5. apply Rmult_le_compat_l. apply pos_INR.\n  apply H4; auto.\nQed.\n\n\nLemma accumul_abc_bigger' : forall a b c n, a>=0 -> b>=0 -> c>=0 -> a>=b ->\n  a<=c -> accumulation b a n n <= INR(n+1)%nat* power n c.\nProof.\n  intros.\n  assert(forall a b n, a>=0 -> b>=0 -> a<=b -> power n a <= power n b).\n   { intros. induction n0.\n     simpl; apply Rle_refl.\n     simpl. apply Rmult_le_compat; auto.\n     apply Rge_le; auto. clear IHn0.\n     induction n0. simpl. apply Rle_0_1.\n     simpl. apply Rmult_le_pos; auto.\n     apply Rge_le; auto. }\n  destruct H2.\n  generalize( accumul_th' b a n H0 H H2); intro.\n  destruct H5. apply Rle_trans with (r2:=INR (n + 1) * power n a); auto.\n  apply Rmult_le_compat_l. apply pos_INR.\n  apply H4; auto.\n  rewrite H2.\n  assert(forall a n, accumulation a a n n = INR (n + 1) * power n a).\n   { intros. induction n0.\n     simpl. ring.\n     assert(accumulation a0 a0 (S n0) (S n0)=\n         a0*accumulation a0 a0 n0 n0 + power(S n0) a0).\n      { simpl.\n        rewrite <- Nat.add_1_r.\n        rewrite fix_property; try apply Nat.le_refl.\n        rewrite Nat.sub_diag. simpl.\n        rewrite Rmult_1_l. ring. }\n     rewrite H5. rewrite IHn0. rewrite Rmult_comm.\n     rewrite Rmult_assoc.\n     assert(power n0 a0 * a0 = power (S n0) a0).\n      { simpl. ring. } rewrite H6.\n     rewrite <- Rmult_1_l with (r:=power (S n0) a0) at 2.\n     rewrite <- Rmult_plus_distr_r. apply Rmult_eq_compat_r.\n     rewrite Nat.add_comm with (n:= S n0).\n     rewrite  S_O_plus_INR. rewrite Nat.add_1_r.\n     rewrite Rplus_comm. apply Rplus_eq_compat_r; auto. }\n  rewrite H5. apply Rmult_le_compat_l. apply pos_INR.\n  apply H4; auto. rewrite H2 in H3; auto.\nQed.\n\n\nLemma power_inv_fac_der : forall (m a b:R)(n:nat), a < b ->\n  str_derivative (fun x => m*power(S n)(x-a)/INR(factorial(S n)))\n  (fun x => m*power n (x-a)/INR(factorial n)) a b.\nProof.\n  intros. apply Theorem4_3. split.\n- unfold diff_quo_median. intros.\n  assert(u ∈ [u, v] /\\ v ∈ [u, v]) as vu_domain.\n   { split. unfold In; unfold cc.\n     split. apply Rminus_gt; tauto.\n     split. apply Rle_refl.\n     apply Rlt_le; apply Rminus_gt; tauto.\n     unfold In; unfold cc.\n     split. apply Rminus_gt; tauto.\n     split. apply Rlt_le; apply Rminus_gt; tauto.\n     apply Rle_refl. }\n     generalize (total_order_T m 0) as order_m; intro.\n     assert(v-a>=0 /\\ u-a>=0 /\\ v-a>u-a) as uv_a_order.\n     { destruct H0, H1, H0, H3, H1, H5.\n       repeat split.\n       apply Rle_ge. apply Rplus_le_reg_r with (r:=a).\n       rewrite Rminus_plus_r; rewrite Rplus_0_l; auto.\n       apply Rle_ge. apply Rplus_le_reg_r with (r:=a).\n       rewrite Rminus_plus_r; rewrite Rplus_0_l; auto.\n       apply Rlt_gt. apply Rplus_lt_reg_r with (r:=a).\n       repeat rewrite Rminus_plus_r.\n       apply Rminus_gt; auto.  }\n       destruct order_m. destruct s.\n       + exists v, u. split; try tauto. split; try tauto.\n         rewrite <- Rdiv_minus_distr.\n         rewrite <- Rmult_minus_distr_l.\n         rewrite <- Nat.add_1_r.\n         rewrite decompose_th.\n         assert(v - a - (u - a)=v-u). { ring. }\n         rewrite H1. clear H1.\n         split; unfold Rdiv; repeat rewrite Rmult_assoc;\n         apply Rmult_le_compat_neg_l with (r:=m).\n         apply Rlt_le; auto. rewrite Rmult_comm;\n         repeat rewrite <- Rmult_assoc;\n         rewrite Rmult_assoc with (r2:=/(v-u));\n         rewrite Rinv_l; try apply Rgt_not_eq; try tauto;\n         rewrite Nat.add_1_r; rewrite Rmult_1_r.\n         rewrite factorial_Sn. rewrite mult_INR.\n         rewrite Rinv_mult_distr.\n         rewrite <- Rmult_assoc. apply Rmult_le_compat_r.\n         apply Rlt_le; apply Rinv_0_lt_compat; apply factorial_pos.\n         apply Rmult_le_reg_r with (r:=INR (S n)).\n         rewrite <- Nat.add_1_r; rewrite plus_INR.\n         apply Rplus_le_lt_0_compat. apply pos_INR. apply Rlt_0_1.\n         rewrite Rinv_mult_rgt0. rewrite Rmult_comm.\n         destruct uv_a_order, H2.\n         apply accumul_th with (n:=n)in H3; auto.\n         destruct H3.\n         rewrite Nat.add_1_r in H3; auto.\n         apply lt_0_INR; apply Nat.lt_0_succ.\n         apply Rgt_not_eq.\n         apply lt_0_INR; apply Nat.lt_0_succ.\n         apply Rgt_not_eq; apply factorial_pos.\n         apply Rlt_le; auto.\n         rewrite Rmult_comm with (r1:=v-u).\n         repeat rewrite <- Rmult_assoc;\n         rewrite Rmult_assoc with (r2:=/(v-u));\n         rewrite Rinv_l; try apply Rgt_not_eq; try tauto;\n         rewrite Nat.add_1_r; rewrite Rmult_1_r.\n         rewrite factorial_Sn with (n:=n). rewrite mult_INR.\n         rewrite Rinv_mult_distr.\n         rewrite <- Rmult_assoc. apply Rmult_le_compat_r.\n         apply Rlt_le; apply Rinv_0_lt_compat; apply factorial_pos.\n         apply Rmult_le_reg_r with (r:=INR (S n)).\n         rewrite <- Nat.add_1_r; rewrite plus_INR.\n         apply Rplus_le_lt_0_compat. apply pos_INR. apply Rlt_0_1.\n         rewrite Rinv_mult_rgt0. rewrite Rmult_comm.\n         destruct uv_a_order, H2.\n         apply accumul_th with (n:=n)in H3; auto.\n         destruct H3.\n         rewrite Nat.add_1_r in H4; auto.\n         apply Rge_le; auto.\n         apply lt_0_INR; apply Nat.lt_0_succ.\n         apply Rgt_not_eq.\n         apply lt_0_INR; apply Nat.lt_0_succ.\n         apply Rgt_not_eq; apply factorial_pos.\n       + exists u, v. split; try tauto.\n         split; try tauto.\n         repeat rewrite e.\n         unfold Rdiv.\n         repeat rewrite Rmult_0_l.\n         rewrite Rminus_diag_eq; auto.\n         rewrite Rmult_0_l.\n         split; apply Rle_refl.\n       + exists u, v. split; try tauto. split; try tauto.\n         rewrite <- Rdiv_minus_distr.\n         rewrite <- Rmult_minus_distr_l.\n         rewrite <- Nat.add_1_r with (n:=n).\n         rewrite decompose_th.\n         assert(v - a - (u - a)=v-u). { ring. }\n         rewrite H1. clear H1.\n         split; unfold Rdiv; repeat rewrite Rmult_assoc.\n         apply Rmult_le_compat_l with (r:=m).\n         apply Rlt_le; auto.\n         rewrite Rmult_comm with (r1:=v-u);\n         repeat rewrite <- Rmult_assoc;\n         rewrite Rmult_assoc with (r2:=/(v-u));\n         rewrite Rinv_l; try apply Rgt_not_eq; try tauto;\n         rewrite Nat.add_1_r; rewrite Rmult_1_r.\n         rewrite factorial_Sn with (n:=n). rewrite mult_INR.\n         rewrite Rinv_mult_distr.\n         rewrite <- Rmult_assoc. apply Rmult_le_compat_r.\n         apply Rlt_le; apply Rinv_0_lt_compat; apply factorial_pos.\n         apply Rmult_le_reg_r with (r:=INR (S n)).\n         rewrite <- Nat.add_1_r; rewrite plus_INR.\n         apply Rplus_le_lt_0_compat. apply pos_INR. apply Rlt_0_1.\n         rewrite Rinv_mult_rgt0. rewrite Rmult_comm.\n         destruct uv_a_order, H2.\n         apply accumul_th with (n:=n)in H3; auto.\n         destruct H3.\n         rewrite Nat.add_1_r in H4; auto.\n         apply Rge_le; auto.\n         apply lt_0_INR; apply Nat.lt_0_succ.\n         apply Rgt_not_eq.\n         apply lt_0_INR; apply Nat.lt_0_succ.\n         apply Rgt_not_eq; apply factorial_pos.\n         apply Rmult_le_compat_l with (r:=m).\n         apply Rlt_le; auto.\n         rewrite Rmult_comm;\n         repeat rewrite <- Rmult_assoc;\n         rewrite Rmult_assoc with (r2:=/(v-u));\n         rewrite Rinv_l; try apply Rgt_not_eq; try tauto;\n         rewrite Nat.add_1_r; rewrite Rmult_1_r.\n         rewrite factorial_Sn. rewrite mult_INR.\n         rewrite Rinv_mult_distr.\n         rewrite <- Rmult_assoc. apply Rmult_le_compat_r.\n         apply Rlt_le; apply Rinv_0_lt_compat; apply factorial_pos.\n         apply Rmult_le_reg_r with (r:=INR (S n)).\n         rewrite <- Nat.add_1_r; rewrite plus_INR.\n         apply Rplus_le_lt_0_compat. apply pos_INR. apply Rlt_0_1.\n         rewrite Rinv_mult_rgt0. rewrite Rmult_comm.\n         destruct uv_a_order, H2.\n         apply accumul_th with (n:=n)in H3; auto.\n         destruct H3.\n         rewrite Nat.add_1_r in H3; auto.\n         apply lt_0_INR; apply Nat.lt_0_succ.\n         apply Rgt_not_eq.\n         apply lt_0_INR; apply Nat.lt_0_succ.\n         apply Rgt_not_eq; apply factorial_pos.\n     - generalize(total_eq_or_neq m 0); intro.\n       destruct H0.\n       + exists 1.\n         split. apply Rlt_0_1.\n         intros.\n         repeat rewrite H0.\n         unfold Rdiv; repeat rewrite Rmult_0_l.\n         rewrite Rminus_diag_eq; auto.\n         rewrite Rmult_1_l. rewrite Rabs_R0. apply Rabs_pos.\n       + generalize(Nat.eq_0_gt_0_cases n); intro.\n         destruct H1.\n         { exists 1. split. apply Rlt_0_1. rewrite H1.\n           intros. simpl. unfold Rdiv. rewrite Rinv_r_simpl_l.\n           rewrite Rminus_diag_eq; auto. rewrite Rmult_1_l.\n           rewrite Rabs_R0; apply Rabs_pos.\n           apply Rgt_not_eq; apply Rlt_0_1. }\n         { exists (Rabs(m*(power (n-1) (b-a))/INR(factorial (n-1)))).\n           split. intros.\n           assert(forall (a b: R)(n:nat), a<b -> (0 < n)%nat ->\n             Rabs (m * power (n - 1) (b - a) / INR (factorial (n - 1))) > 0 ).\n           { intros. apply Rabs_pos_lt.\n             apply Rmult_integral_contrapositive_currified.\n             apply Rmult_integral_contrapositive_currified; auto.\n             induction (n0-1)%nat. simpl. apply Rgt_not_eq. apply Rlt_0_1.\n             simpl. apply Rmult_integral_contrapositive_currified; auto.\n             apply Rgt_not_eq; auto. apply Rgt_minus; auto.\n             apply Rinv_neq_0_compat. apply Rgt_not_eq. apply factorial_pos. }\n           apply H2; auto.\n           intros. unfold Rdiv; repeat rewrite Rmult_assoc.\n           rewrite <- Rmult_minus_distr_l.\n           rewrite Rabs_mult. rewrite Rabs_mult.\n           rewrite Rmult_assoc; apply Rmult_le_compat_l. apply Rabs_pos.\n           rewrite Rmult_comm. \n           assert(n=S(n-1)).\n            { rewrite <- Nat.add_1_r.\n              rewrite Nat.sub_add; auto. }\n           rewrite H3. rewrite <- Nat.add_1_r.\n           rewrite Rmult_comm with (r1:=power (n - 1 + 1) (x - a)).\n           rewrite <- Rmult_minus_distr_l.\n           rewrite decompose_th.\n           assert(x + h - a - (x - a)=h). { ring. }\n           rewrite H4. clear H4.\n           rewrite Rmult_comm; rewrite Rmult_assoc.\n           rewrite Rabs_mult with (x:=h). \n           rewrite Rmult_comm with (r2:=Rabs h).\n           apply Rmult_le_compat_l. apply Rabs_pos.\n           assert(n-1+1-1 = n-1)%nat. { rewrite Nat.add_sub; auto. }\n           rewrite H4. rewrite Nat.sub_add; try apply lt_le_S; auto.\n           clear H3 H4.\n           destruct H2, H2, H4, H3, H6.\n           generalize(total_le_gt (x+h) x); intro.\n           assert(x + h - a >= 0 /\\ x - a >= 0) as gt_0_x0h.\n            { split. apply Rge_minus. apply Rle_ge; auto.\n              apply Rge_minus; apply Rle_ge; auto. }\n           destruct H8.\n           assert(x-a>=x+h-a). { unfold Rminus. apply Rle_ge. apply Rplus_le_compat_r; auto. }\n           apply accumul_abc_bigger' with (c:=b - a)(n:=(n-1)%nat) in H8; try tauto.\n           repeat rewrite Rabs_right.\n           apply Rmult_le_reg_r with (r:=INR (factorial (n - 1))).\n           apply factorial_pos. rewrite Rinv_mult_rgt0; try apply factorial_pos.\n           assert(forall k, INR (factorial (S k)) = INR(S k) * INR(factorial k)). \n            { intros. induction k. simpl. ring.\n              rewrite IHk.\n              simpl. destruct k. simpl. ring.\n              assert(factorial(S k)+S k*factorial(S k) = (S k+1)*factorial(S k))%nat.\n               { ring. } rewrite H9.\n              assert((S k+1)*factorial(S k)+((S k+1)*factorial(S k)+S k*((S k+1)*factorial(S k))) = \n                (S k+1+1)*(S k+1)*factorial(S k))%nat.\n                { ring. } rewrite H10. repeat rewrite mult_INR.\n              assert((INR(S k)+1+1) = INR(S k+1+1)). { repeat rewrite plus_INR; auto. }\n              assert((INR(S k)+1) = INR(S k+1)). { rewrite plus_INR; auto. }\n              rewrite H11. rewrite H12; auto. rewrite <- Rmult_assoc; auto. }\n              assert(accumulation (x + h - a) (x - a) (n - 1) (n - 1) * / INR (factorial n) *\n INR (factorial (n - 1)) = accumulation (x + h - a) (x - a) (n - 1) (n - 1) * /INR n).\n               { assert(S(n-1) = n).\n                   { rewrite <- Nat.sub_add with (n:=1%nat).\n                     rewrite Nat.add_1_r; auto. apply lt_le_S; auto. }\n                 rewrite <- H10 at 3. rewrite H9. rewrite Rinv_mult_distr.\n                 rewrite <- Rmult_assoc. rewrite Rinv_mult_rgt0. rewrite H10; auto.\n                 apply factorial_pos. rewrite H10. apply Rgt_not_eq; apply lt_0_INR; auto.\n                 apply Rgt_not_eq; apply factorial_pos. }\n               rewrite H10. rewrite Nat.sub_add in H8.\n               apply Rmult_le_reg_r with (r:=INR n). apply lt_0_INR; auto.\n               rewrite Rinv_mult_rgt0. rewrite Rmult_comm; auto. apply lt_0_INR; auto.\n               apply lt_le_S; auto.\n               apply Rle_ge; apply Rmult_le_pos.\n               clear H8. induction(n-1)%nat. simpl. apply Rle_0_1.\n               simpl. apply Rmult_le_pos; auto.\n               apply Rlt_le; apply Rlt_Rminus; auto.\n               apply Rlt_le; apply Rinv_0_lt_compat; apply factorial_pos.\n               apply Rle_ge; apply Rmult_le_pos.\n               assert(forall a n, a>=0 -> 0<=power n a).\n                { intros. induction n0.\n                  simpl. apply Rlt_le; apply Rlt_0_1.\n                  simpl. apply Rmult_le_pos; auto. apply Rge_le; auto. }\n               assert(forall a b n k, a>=0 -> b>=0 -> 0 <= accumulation a b n k).\n                { intros. induction k.\n                  simpl. apply H9; auto.\n                  simpl. apply Rplus_le_le_0_compat; auto.\n                  apply Rmult_le_pos. apply H9; auto.\n                  apply Rmult_le_pos; auto. apply Rge_le; auto. }\n               apply H10; try tauto. apply Rlt_le; apply Rinv_0_lt_compat.\n               apply factorial_pos. apply Rge_minus.\n               apply Rgt_ge; apply Rlt_gt; auto.\n               unfold Rminus. apply Rplus_le_compat_r; auto.\n               assert(x-a<=x+h-a). { unfold Rminus. apply Rlt_le; apply Rplus_lt_compat_r; auto. }\n               apply accumul_abc_bigger with (c:=b - a)(n:=(n-1)%nat) in H8; try tauto.\n               repeat rewrite Rabs_right.\n           apply Rmult_le_reg_r with (r:=INR (factorial (n - 1))).\n           apply factorial_pos. rewrite Rinv_mult_rgt0; try apply factorial_pos.\n           assert(forall k, INR (factorial (S k)) = INR(S k) * INR(factorial k)). \n            { intros. induction k. simpl. ring.\n              rewrite IHk.\n              simpl. destruct k. simpl. ring.\n              assert(factorial(S k)+S k*factorial(S k) = (S k+1)*factorial(S k))%nat.\n               { ring. } rewrite H9.\n              assert((S k+1)*factorial(S k)+((S k+1)*factorial(S k)+S k*((S k+1)*factorial(S k))) = \n                (S k+1+1)*(S k+1)*factorial(S k))%nat.\n                { ring. } rewrite H10. repeat rewrite mult_INR.\n              assert((INR(S k)+1+1) = INR(S k+1+1)). { repeat rewrite plus_INR; auto. }\n              assert((INR(S k)+1) = INR(S k+1)). { rewrite plus_INR; auto. }\n              rewrite H11. rewrite H12; auto. rewrite <- Rmult_assoc; auto. }\n              assert(accumulation (x + h - a) (x - a) (n - 1) (n - 1) * / INR (factorial n) *\n INR (factorial (n - 1)) = accumulation (x + h - a) (x - a) (n - 1) (n - 1) * /INR n).\n               { assert(S(n-1) = n).\n                   { rewrite <- Nat.sub_add with (n:=1%nat).\n                     rewrite Nat.add_1_r; auto. apply lt_le_S; auto. }\n                 rewrite <- H10 at 3. rewrite H9. rewrite Rinv_mult_distr.\n                 rewrite <- Rmult_assoc. rewrite Rinv_mult_rgt0. rewrite H10; auto.\n                 apply factorial_pos. rewrite H10. apply Rgt_not_eq; apply lt_0_INR; auto.\n                 apply Rgt_not_eq; apply factorial_pos. }\n               rewrite H10. rewrite Nat.sub_add in H8.\n               apply Rmult_le_reg_r with (r:=INR n). apply lt_0_INR; auto.\n               rewrite Rinv_mult_rgt0. rewrite Rmult_comm; auto. apply lt_0_INR; auto.\n               apply lt_le_S; auto.\n               apply Rle_ge; apply Rmult_le_pos.\n               clear H8. induction(n-1)%nat. simpl. apply Rle_0_1.\n               simpl. apply Rmult_le_pos; auto.\n               apply Rlt_le; apply Rlt_Rminus; auto.\n               apply Rlt_le; apply Rinv_0_lt_compat; apply factorial_pos.\n               apply Rle_ge; apply Rmult_le_pos.\n               assert(forall a n, a>=0 -> 0<=power n a).\n                { intros. induction n0.\n                  simpl. apply Rlt_le; apply Rlt_0_1.\n                  simpl. apply Rmult_le_pos; auto. apply Rge_le; auto. }\n               assert(forall a b n k, a>=0 -> b>=0 -> 0 <= accumulation a b n k).\n                { intros. induction k.\n                  simpl. apply H9; auto.\n                  simpl. apply Rplus_le_le_0_compat; auto.\n                  apply Rmult_le_pos. apply H9; auto.\n                  apply Rmult_le_pos; auto. apply Rge_le; auto. }\n               apply H10; try tauto. apply Rlt_le; apply Rinv_0_lt_compat.\n               apply factorial_pos. apply Rge_minus.\n               apply Rgt_ge; apply Rlt_gt; auto.\n               unfold Rminus. apply Rplus_le_compat_r; auto. }\nQed.\n\nLemma Rabs_le_reg : forall a b : R,  Rabs a <= b -> - b <= a <= b.\nProof.\n  intros.\n  assert(0<=b).\n   { apply Rle_trans with (r1:=0) in H; auto.\n     apply Rabs_pos. }\n  rewrite <- Rabs_pos_eq in H; auto.\n  apply Rsqr_le_abs_1 in H.\n  generalize(H) as H1; intro.\n  apply Rsqr_neg_pos_le_0 in H; auto.\n  apply Rsqr_incr_0_var in H1; auto.\nQed.\n\n\nLemma Domain_x_c : forall a b x c,\n  c ∈ [a, b] -> x ∈ [a, b]-> x ∈ [c, b]\\/x ∈ [a, c].\nProof.\n  intros.\n  generalize(total_eq_or_neq a c); intro.\n  generalize(total_eq_or_neq b c); intro.\n  destruct H1.\n  - rewrite <- H1. left; auto.\n  - destruct H2.\n    + rewrite <- H2. right; auto.\n    + generalize(Rle_or_lt x c); intro.\n      destruct H, H0, H4, H5. destruct H3.\n      * right. unfold In; unfold cc.\n        destruct H4; auto.\n        contradiction.\n      * left. unfold In; unfold cc.\n        apply Rlt_le in H3.\n        destruct H6; auto.\n        apply eq_sym in H6.\n        contradiction.\nQed.\n\nLemma power_x_pos : forall x n, 0<=x -> 0 <= power n x.\nProof.\n  intros.\n  induction n.\n  - simpl. apply Rle_0_1.\n  - simpl. apply Rmult_le_pos; auto.\nQed.\n\nLemma Rabs_power : forall a b n,\n Rabs (power n (-a-b))=Rabs(power n (a+b)).\nProof.\n  intros.\n  induction n.\n  - simpl; auto.\n  - simpl. repeat rewrite Rabs_mult.\n    rewrite IHn. apply Rmult_eq_compat_r.\n    unfold Rminus. rewrite <- Ropp_plus_distr.\n    rewrite Rabs_Ropp; auto.\nQed.\n\nLemma Rabs_power_opp : forall n, Rabs (power n (-1)) = 1.\nProof.\n  intro.\n  induction n. simpl. apply Rabs_R1.\n  simpl. rewrite Rabs_mult. rewrite IHn.\n  rewrite Rmult_1_r. rewrite <- Rabs_Ropp.\n  assert(- -1 = 1). { ring. } rewrite H.\n  rewrite Rabs_R1; auto.\nQed.\n\n\nLemma pow_mult_ab : forall n a b, power n (a*b) = power n a * power n b.\nProof.\n  intros.\n  induction n. simpl. rewrite Rmult_1_l; auto.\n  simpl. rewrite IHn. ring.\nQed.\n\n\n(* Taylor公式的预备定理 *)\n(*n阶可导，且n阶导数为f*)\nFixpoint N_str_derivative F f a b (n:nat) : Prop :=\n  match n with\n  | 0 => F = f\n  | S p => exists f1, str_derivative F f1 a b /\\ N_str_derivative f1 f a b p\n  end.\n\n(*n阶可导*)\nFixpoint N_str_derivability F a b (n:nat) : Prop :=\n  match n with\n  | 0 => N_str_derivative F F a b 0\n  | S p => exists f, str_derivative F f a b /\\ N_str_derivability f a b p\n  end.\n\n\nCorollary N_derivative_existence : forall a b n, forall F,\n  N_str_derivability F a b n -> exists f, N_str_derivative F f a b n.\nProof.\n  induction n; intros.\n   - simpl in H. exists F; simpl; auto.\n   - destruct H, H. apply IHn in H0. destruct H0.\n     exists x0. exists x. split; auto.\nQed.\n\nCorollary N0_derivative : forall F f a b,\n  N_str_derivative F f a b 0 -> F = f.\nProof.\n  simpl; auto.\nQed.\n\nAxiom ex_trans :\n  forall {A : Type} {P : A->Prop},\n    (exists x, P x) -> { x : A | P x }.\n\nLemma der_F : forall {F a b}, str_derivability F a b -> \n  exists f, exists M, 0<M /\\ forall x h:R, x ∈ [a,b] /\\ (x+h) ∈ [a,b] ->\n  Rabs (F(x+h) - F(x) - f(x)*h) <= M*(h^2).\nProof.\n  intros; red in H; eauto.\nQed.\n\n\nDefinition Con_der {F a b} (l:str_derivability F a b) :=\n  ex_trans (der_F l).\n\n\nDefinition Der {F a b}(l:str_derivability F a b) :=\n  proj1_sig(Con_der l).\n\n\nDefinition Con_N_der {F a b n} (l:N_str_derivability F a b n) :=\n  ex_trans (N_derivative_existence a b n F l).\n\n\nDefinition N_der {F a b n}(l:N_str_derivability F a b n) :=\n  proj1_sig(Con_N_der l).\n\n\nDefinition N_der_pro {F a b n}(l:N_str_derivability F a b n) :=\n  proj2_sig(Con_N_der l).\n\n\nCorollary N0_der_eq: forall F a b (l:N_str_derivability F a b 0),\n  N_der l = F.\nProof.\n  intros; unfold N_der.\n  destruct (Con_N_der l), n.\n  simpl; auto.\nQed.\n\n\nSection Taylor.\n\nLemma Nder_by_Snder : forall {F a b n}, N_str_derivability F a b (S n) ->\n  N_str_derivability F a b n.\nProof.\n  intros; generalize dependent  F; induction n; intros.\n  - constructor.\n  - destruct H, H. apply IHn in H0. exists x; auto.\nQed.\n\nLemma N_derivative_pro :forall F a b n, N_str_derivability F a b n ->\n  forall k, (k<=n)%nat -> N_str_derivability F a b k.\nProof.\n  intros; induction n.\n  - assert (k = O). { apply Nat.le_0_r; auto. }\n    rewrite H1. auto.\n  - apply le_lt_or_eq in H0; destruct H0.\n    apply  IHn. apply Nder_by_Snder; auto.\n    apply lt_n_Sm_le; auto.\n    rewrite <- H0 in H; auto.\nQed.\n\n\nLemma der_unique : forall {F f1 f2 a b}, str_derivative F f1 a b ->\n  str_derivative F f2 a b -> f1 = f2.\nAdmitted.\n\n\nLemma Nder_unique : forall F f1 f2 a b n, N_str_derivative F f1 a b n ->\n  N_str_derivative F f2 a b n -> f1 = f2.\nProof.\n  intros; generalize dependent F; induction n; intros.\n  - destruct H, H0; auto.\n  - destruct H, H, H0, H0.\n    pose proof (der_unique H H0); subst x.\n    apply IHn with x0; auto.\nQed.\n\nLemma N_derivative_eq : forall F a b m n (p:N_str_derivability F a b m)\n  (q:N_str_derivability F a b n), m = n -> N_der p = N_der q.\nProof.\n  intros. subst m.\n  unfold N_der; destruct (Con_N_der p), (Con_N_der q); simpl.\n  eapply Nder_unique; eauto.\nQed.\n\nLemma N_sub_derivative : forall F a b m n (p:N_str_derivability F a b m)\n  (q:N_str_derivability F a b n), S m = n ->\n  str_derivative (N_der p) (N_der q) a b.\nProof.\n  intros. subst n.\n  unfold N_der; destruct (Con_N_der p), (Con_N_der q); simpl.\n  clear p q. generalize dependent F.\n  induction m; intros.\n  - simpl in n, n0. destruct n0, H. subst F x1; auto.\n  - destruct n, n0, H, H0.\n    pose proof (der_unique H H0); subst x1.\n    apply IHm with x2; auto.\nQed.\n\n\nTheorem Taylor_Lemma H a b n (l: N_str_derivability H a b n) :\n  (forall k (p:N_str_derivability H a b k), (k<n)%nat-> N_der p a = 0) ->\n  forall m M, (forall x, x ∈ [a,b] -> m <= N_der l x <= M) -> \n  forall k , (k<=n)%nat -> forall x, x ∈ [a,b] ->\n  forall q:N_str_derivability H a b (n-k),\n  m*power k (x-a)/INR (factorial k) <= N_der q x <=\n  M*power k (x-a)/ INR(factorial k).\nProof.\n  intros H0 m M H1 k H2.\n  induction k.\n  - intros. unfold Rdiv.\n    repeat rewrite Rinv_r_simpl_l; try apply R1_neq_R0.\n    apply H1 in H3. rewrite N_derivative_eq with(n:=n)(q:=l); auto.\n    rewrite Nat.sub_0_r; auto.\n  - assert((k<=n)%nat) as le_k_n.\n     { apply Nat.le_trans with (m:= S k); auto. }\n    generalize(IHk le_k_n) as IHk_x; intros. clear IHk.\n    assert(a<b) as lt_a_b. { destruct H3; auto. }\n    generalize(power_inv_fac_der m a b k lt_a_b); intro.\n    generalize(power_inv_fac_der M a b k lt_a_b); intro.\n    assert(N_str_derivability H a b (n-k)) as p.\n     { generalize(N_derivative_pro H a b n l (n-k)); intro.\n       apply H6. apply Nat.le_sub_l. }\n    assert(str_derivative (N_der q)(N_der p) a b).\n     { assert((n-S k=n-k-1 /\\ n-k=S(n-k-1))%nat).\n        { split. auto.\n          rewrite <- Nat.sub_add_distr. rewrite Nat.add_1_r; auto.\n          rewrite <- Nat.add_1_r.\n          rewrite Nat.sub_add; auto.\n          apply plus_le_reg_l with (p:=k).\n          rewrite Nat.add_comm with (m:=(n-k)%nat).\n          rewrite Nat.sub_add. rewrite Nat.add_1_r; auto.\n          apply Nat.le_trans with (m:=S k); auto. }\n    apply N_sub_derivative. destruct H6.\n    apply eq_S in H6. rewrite <- H7 in H6; auto. }\n    assert(a<=x) as le_a_x.\n     { unfold In in H3. unfold cc in H3. tauto. }\n    split.\n    + destruct le_a_x.\n      * apply Theorem3_1_1' with (c:=-1) in H4.\n        apply (Theorem3_1_2' _ _ _ _ _ _ H6) in H4.\n        apply Theorem4_3 in H4. destruct H4. clear H8.\n        unfold diff_quo_median in H4.\n        assert(a ∈ [a, b] /\\ x ∈ [a, b] /\\ x - a > 0).\n          { destruct H3, H8. repeat split; auto.\n            apply Rle_refl. apply Rlt_le; auto.\n            apply Rgt_minus; auto. }\n        apply H4 in H8.\n        destruct H8, H8, H8, H9, H10. clear H4 H11.\n        unfold plus_Fu in H10; unfold mult_real_f in H10.\n        assert(n-S k<n)%nat.\n         { apply Nat.sub_lt; auto. apply Nat.lt_0_succ. }\n        rewrite H0 in H10; auto.\n        rewrite Rminus_diag_eq with(r1:=a) in H10; auto.\n        rewrite Rplus_0_l in H10.\n        assert(power (S k) 0 = 0).\n         { simpl. rewrite Rmult_0_l; auto. }\n        rewrite H11 in H10. rewrite Rmult_0_r in H10.\n        unfold Rdiv in H10; rewrite Rmult_0_l in H10.\n        rewrite Rmult_0_r in H10.\n        assert(x0 ∈ [a, b]).\n         { destruct H3, H12, H8, H14.\n           split; auto. split; auto.\n           apply Rle_trans with (r2:=x); auto. }\n        apply IHk_x with(q:=p) in H12.\n        apply Rplus_le_reg_r with \n          (r:=-(m*power(S k)(x-a)/INR(factorial(S k)))).\n        rewrite Rplus_opp_r. destruct H12. clear H13.\n        apply Rplus_le_compat_r with\n          (r:=-(m*power k (x0-a)/INR(factorial k))) in H12.\n        rewrite Rplus_opp_r in H12. unfold Rdiv in H12.\n        repeat rewrite Ropp_mult_distr_l_reverse with (r1:=1)in H10.\n        repeat rewrite Rmult_1_l in H10.\n        apply Rle_trans with (r1:=0)in H10; auto.\n        unfold Rdiv. rewrite Rminus_0_r in H10.\n        apply Rmult_le_reg_r with (r:= / (x - a)).\n        apply Rinv_0_lt_compat; apply Rlt_Rminus; auto.\n        rewrite Rmult_0_l; auto.\n      * rewrite <- H7. rewrite Rminus_diag_eq; auto.\n        simpl. rewrite Rmult_0_l. rewrite Rmult_0_r.\n        unfold Rdiv; rewrite Rmult_0_l.\n        rewrite H0. apply Req_le; auto.\n        apply Nat.sub_lt; auto.\n        apply Nat.lt_0_succ.\n    + destruct le_a_x.\n      * apply Theorem3_1_1' with (c:=-1) in H5.\n        apply (Theorem3_1_2' _ _ _ _ _ _ H6) in H5.\n        apply Theorem4_3 in H5. destruct H5. clear H8.\n        unfold diff_quo_median in H4.\n        assert(a ∈ [a, b] /\\ x ∈ [a, b] /\\ x - a > 0).\n          { destruct H3, H8. repeat split; auto.\n            apply Rle_refl. apply Rlt_le; auto.\n            apply Rgt_minus; auto. }\n        apply H5 in H8.\n        destruct H8, H8, H8, H9, H10. clear H5 H10.\n        unfold plus_Fu in H11; unfold mult_real_f in H11.\n        assert(n-S k<n)%nat.\n         { apply Nat.sub_lt; auto. apply Nat.lt_0_succ. }\n        rewrite H0 in H11; auto.\n        rewrite Rminus_diag_eq with(r1:=a) in H11; auto.\n        rewrite Rplus_0_l in H11.\n        assert(power (S k) 0 = 0).\n         { simpl. rewrite Rmult_0_l; auto. }\n        rewrite H10 in H11. rewrite Rmult_0_r in H11.\n        unfold Rdiv in H11; rewrite Rmult_0_l in H11.\n        rewrite Rmult_0_r in H11.\n        assert(x1 ∈ [a, b]).\n         { destruct H3, H12, H9, H14.\n           split; auto. split; auto.\n           apply Rle_trans with (r2:=x); auto. }\n        apply IHk_x with(q:=p) in H12.\n        apply Rplus_le_reg_r with \n          (r:=-(M*power(S k)(x-a)/INR(factorial(S k)))).\n        rewrite Rplus_opp_r. destruct H12. clear H12.\n        apply Rplus_le_compat_r with \n          (r:=-(M*power k (x1-a)/INR(factorial k))) in H13.\n        rewrite Rplus_opp_r in H13. unfold Rdiv in H13.\n        repeat rewrite Ropp_mult_distr_l_reverse with (r1:=1)in H11.\n        repeat rewrite Rmult_1_l in H11.\n        apply Rle_trans with (r3:=0)in H11; auto.\n        unfold Rdiv. rewrite Rminus_0_r in H11.\n        apply Rmult_le_reg_r with (r:= / (x - a)).\n        apply Rinv_0_lt_compat; apply Rlt_Rminus; auto.\n        rewrite Rmult_0_l; auto.\n      * rewrite <- H7. rewrite Rminus_diag_eq; auto.\n        simpl. rewrite Rmult_0_l. rewrite Rmult_0_r.\n        unfold Rdiv; rewrite Rmult_0_l.\n        rewrite H0. apply Req_le; auto.\n        apply Nat.sub_lt; auto.\n        apply Nat.lt_0_succ.\nQed.\n\n\nVariable Nder_H: forall {H a b n}, N_str_derivability H a b n.\n\nLemma Nder_H' : forall H a b n, N_str_derivative H (N_der(Nder_H H a b n)) a b n.\nProof.\n  intros. unfold N_der. destruct Con_N_der.\n  simpl. auto.\nQed.\n\nLemma N_der_eq : forall {H f1 f2 a b n}, N_str_derivative H f1 a b n ->\n  N_str_derivative H f2 a b n -> f1 = f2.\nProof.\n  intros. generalize dependent H.\n  induction n.\n  - intros. simpl in H0, H1. \n    rewrite <- H0, H1; auto.\n  - intros. simpl in H0, H1.\n    destruct H0, H0, H1, H1.\n    generalize(der_unique H0 H1); intro.\n    rewrite <- H4 in H3.\n    apply IHn with (H:=x); auto.\nQed.\n\nFixpoint Taylor_Formula H a b n (x c:R)  :=\n  match n with\n  | 0 => 0\n  | S p => ((N_der (Nder_H H a b p)) c)*(power p (x-c))/INR(factorial p)+\n           Taylor_Formula H a b p x c\n  end.\n\nLemma lt_ge_dec : forall n m : nat, {(n < m)%nat} + {(n >= m)%nat}.\nProof.\n  intros. generalize (le_gt_dec m n); intro.\n  destruct H; auto.\nQed.\n\nFixpoint Taylor_FormulaDer H a b n x c k  := \n  match n with \n  | 0 => 0\n  | S p => match lt_ge_dec k n with\n           |left _ => ((N_der (Nder_H H a b p)) c)*(power (p-k) (x-c))/INR(factorial (p-k)) +\n                      (Taylor_FormulaDer H a b p x c k)\n           |right _ => 0\n                 end\n  end.\n\nVariable fun_eq : forall (f1 f2:R->R), (forall a, f1 a = f2 a) <-> f1 = f2.\n\nLemma Str_Plus_FG : forall F G (a b:R),\n  str_derivability F a b -> str_derivability G a b ->\n  str_derivability (plus_Fu F G) a b.\nProof.\n  intros.\n  destruct H, H, H. rename x0 into M1. rename x into f.\n  destruct H0, H0, H0. rename x0 into M2. rename x into g.\n  exists (plus_Fu f g), (M1+M2). split.\n  apply Rplus_lt_0_compat; auto. intros.\n  generalize H3; intro.\n  apply H2 in H3; apply H1 in H4. unfold plus_Fu. \n  rewrite Rmult_plus_distr_r with (r1:=(f x))(r2:=(g x))(r3:=h).\n    rewrite plus_ab_minus_cd with (a:=F(x+h))(b:=G(x+h))(c:=F x)\n                                  (d:=G x)(e:=f x*h)(f:=g x*h).\n    assert (Rabs(F(x+h) - F x - f x*h)+Rabs(G(x+h) - G x - g x*h)\n            <= (M1+M2) * h ^ 2).\n     { rewrite Rmult_plus_distr_r. \n       apply Rplus_le_compat; auto. }\n    apply Rle_abcd with (a:=Rabs(F(x+h)-F x-f x*h+(G(x+h)-G x-g x*h)))\n                        (b:=Rabs(F(x+h)-F x-f x*h)+Rabs(G(x+h)-G x-g x*h))\n                        (c:=M1*h^2+M2*h^2)\n                        (d:=(M1+M2)*h^2).\n    + apply Rabs_triang.\n    + rewrite Rmult_plus_distr_r.\n      apply Rle_refl.\n    + rewrite <-Rmult_plus_distr_r; auto.\nQed.\n\n\nLemma plus_FG_Nder n : forall F G a b, N_str_derivability F a b n ->\n  N_str_derivability G a b n ->\n  N_str_derivability (plus_Fu F G) a b n.\nProof.\n  induction n.\n  - intros. simpl; auto. \n  - intros. simpl. simpl in H; simpl in H0.\n    destruct H, H, H0, H0. rename x into f. rename x0 into g.\n    exists(plus_Fu f g).\n    split.\n    + apply Theorem3_1_2'; auto.\n    + apply IHn with (G:=g) in H1; auto.\nQed.\n\n\nLemma plus_FG_Nder' n : forall F f G g a b, N_str_derivative F f a b n ->\n  N_str_derivative G g a b n ->\n  N_str_derivative (plus_Fu F G) (plus_Fu f g) a b n.\nProof.\n  induction n.\n  - intros. simpl; auto. simpl in H; simpl in H0.\n    rewrite H; rewrite H0; auto.\n  - intros. simpl. simpl in H; simpl in H0.\n    destruct H, H, H0, H0. rename x into f1. rename x0 into g1.\n    exists(plus_Fu f1 g1).\n    split.\n    + apply Theorem3_1_2'; auto.\n    + apply (IHn f1 f g1 g a b) in H1; auto.\nQed.\n\n\nLemma Sn_der : forall H f1 f2 a b n, N_str_derivative H f1 a b n ->\n  str_derivative f1 f2 a b -> N_str_derivative H f2 a b (S n).\nProof.\n  intros. generalize dependent H; induction n; intros.\n  - simpl in H0. subst H. simpl. exists f2; auto.\n  - simpl in H0. destruct H0 as [h1 [H0]].\n    apply IHn in H2. exists h1; auto.\nQed.\n\n\nLemma Strder_fun0 : forall a b, str_derivative (fun _ => 0) (fun _ => 0) a b.\nProof.\n  intros; red.\n  exists 1.\n  split. apply Rlt_0_1.\n  intros.\n  rewrite Rmult_0_l. repeat rewrite Rminus_0_r.\n  rewrite Rmult_1_l. rewrite Rabs_R0.\n  apply pow2_ge_0.\nQed.\n\nLemma Str_Snder : forall H f1 f2 a b n, N_str_derivative H f1 a b n -> \n  N_str_derivative H f2 a b (S n) -> str_derivative f1 f2 a b .\nProof.\n  intros. generalize dependent H; induction n; intros.\n  - simpl in H0, H1. destruct H0, H1, H0. subst x; auto.\n  - destruct H0, H1, H0, H1.\n    pose proof (der_unique H0 H1); subst x.\n    apply IHn with x0; auto.\nQed.\n\nLemma Domain_Strder : forall f f1 a b c, c ∈ [a, b] -> str_derivative f f1 a b -> str_derivative f f1 c b.\nProof.\n  intros. red in H0|-*.\n  destruct H0 as [M [H0]].\n  exists M. split; auto. intros.\n  apply H1. destruct H2, H2, H3, H, H6, H4, H5.\n  repeat split; auto; try apply Rle_trans with(r2:=c); auto.\nQed.\n\n\nLemma Domain_Nder F a b c n : c ∈ [a, b] -> N_str_derivability F a b n ->\n  N_str_derivability F c b n.\nProof.\n  intros. generalize dependent F; induction n; auto.\nQed.\n\n\nLemma Domain_Nder' F f a b c n : c ∈ [a, b] -> N_str_derivative F f a b n ->\n  N_str_derivative F f c b n.\nProof.\n  intros. generalize dependent F; induction n; auto.\n  intros. simpl in H0|-*.\n  destruct H0 as [f1 [H0]].\n  exists f1; split; auto.\n  eapply Domain_Strder; eauto.\nQed.\n\n\nLemma Domain_Nder_eq : forall {f a b c n}, c ∈ [a, b] -> (N_der (Nder_H f a b n)) = (N_der (Nder_H f c b n)).\nProof.\n  intros. unfold N_der. \n   destruct (Con_N_der (Nder_H f a b n)), (Con_N_der (Nder_H f c b n)); simpl.\n  generalize dependent f; induction n; intros.\n  - simpl in n0, n1. subst f; auto.\n  - destruct n0, n1, H0, H1.\n    pose proof (Domain_Strder _ _ _ _ _ H H0).\n    pose proof (der_unique H1 H4). subst x2.\n    apply IHn with x1; auto.\nQed.\n\nLemma Domain_Taylor_eq : forall f a b c n d, c ∈ [a, b] ->\n  (fun x => Taylor_Formula f a b n x d) = (fun x => Taylor_Formula f c b n x d).\nProof.\n  intros. apply fun_eq; intros.\n  induction n; auto.\n  - simpl. rewrite IHn. erewrite Domain_Nder_eq; eauto.\nQed.\n\nLemma Domain_Taylor_Nder_eq : forall f a b c n d k, c ∈ [a, b] -> \n  (fun x => Taylor_FormulaDer f a b n x d k) = (fun x => Taylor_FormulaDer f c b n x d k).\nProof.\n  intros. apply fun_eq; intros.\n  induction n; auto.\n  - simpl. rewrite IHn. erewrite Domain_Nder_eq; eauto.\nQed.\n\n\nLemma Nder_power_inv_fac : forall a b p n k,  (k <= n)%nat -> a<b ->\n  N_str_derivative (fun x : R => p * power n (x - a) / INR (factorial n))\n  (fun x : R => p * power (n - k) (x - a) / INR (factorial (n - k))) a b k.\nProof.\n  intros. induction k. \n  - simpl. rewrite <- minus_n_O; auto.\n  - assert (str_derivative  (fun x : R => p * power (n - k) (x - a) / INR (factorial (n - k)))\n      (fun x : R => p * power (n - S k) (x - a) / INR (factorial (n - S k))) a b).\n    { assert (n-k = S (n - (S k)))%nat.\n      { rewrite Nat.sub_succ_r, Nat.succ_pred_pos; auto.\n         apply lt_minus_O_lt; apply  le_S_gt; auto. }\n      rewrite H1. eapply power_inv_fac_der with (a:=a)(b:=b); auto. }\n    apply le_Sn_le in H. eapply Sn_der; eauto.\nQed.\n\n\nLemma Rminus_refl : forall n, n - n =0.\nProof.\n  intros. apply Rminus_diag_eq; auto.\nQed.\n\nLemma Nder_Taylor_eq0 : forall H a b n, a<b -> N_str_derivative (fun x : R => Taylor_Formula H a b n x a)\n (fun x : R => 0) a b n.\nProof.\n  intros. induction n.\n  - simpl; auto.\n  - simpl Taylor_Formula.\n    assert((fun _ => 0) = plus_Fu (fun _ => 0) (fun _ => 0)) as pp.\n    { unfold plus_Fu. rewrite Rplus_0_r; auto. } rewrite pp.\n    apply plus_FG_Nder'.\n    * pose proof (Nat.le_refl n).\n    pose proof (Nder_power_inv_fac a b (N_der (Nder_H H a b n) a) n n H1).\n    rewrite Nat.sub_diag in H2; simpl in H2.\n    unfold Rdiv in H2; rewrite Rmult_1_r, RMicromega.Rinv_1 in H2.\n    assert (str_derivative  (fun _ : R => N_der (Nder_H H a b n) a) (fun _ : R => 0) a b).\n     { exists 1.\n       split. apply Rlt_0_1.\n       intros. rewrite Rmult_0_l. rewrite Rminus_0_r.\n       rewrite Rminus_refl. rewrite Rabs_R0. rewrite Rmult_1_l.\n       apply pow2_ge_0. }\n    eapply Sn_der; eauto.\n    * pose proof (Strder_fun0 a b). eapply Sn_der; eauto.\nQed.\n\n\nLemma Taylor_onC_eq0 : forall H a b c n x,  Taylor_FormulaDer H a b n x c n = 0.\nProof.\n  intros. induction n. simpl; auto.\n  simpl. destruct (lt_ge_dec (S n) (S n)); auto.\n  apply Nat.lt_irrefl in l. destruct l.\nQed.\n\nLemma Taylor_Nder': forall H a b n k, (k < n)%nat -> a<b ->\n  N_str_derivative (fun x => Taylor_Formula H a b n x a)\n  (fun x => (Taylor_FormulaDer H a b n x a k)) a b k.\nProof.\n  intros. generalize dependent k;\n  induction n; simpl;intros. induction k. simpl. auto.\n  exists  (fun _ : R => 0). split;\n  apply Nat.nlt_0_r in H0; contradiction.\n  induction k. simpl. simpl in IHn. destruct (lt_ge_dec 0 (S n)).\n  rewrite Nat.sub_0_r.\n  assert(forall f1 f2, (fun x => (f1 x + f2 x)) = plus_Fu (fun x => f1 x) (fun x => f2 x)) as pp. { auto. }\n  repeat rewrite pp. f_equal.\n  specialize IHn with O.\n  assert (n=O \\/ n > O)%nat. \n  { apply lt_n_Sm_le in l. destruct l.\n    left; auto.\n    right. apply le_lt_n_Sm; auto. }\n  destruct H2.\n  subst n; simpl; auto.  simpl in IHn; auto.\n  apply lt_not_le in H0. contradiction.\n  destruct (lt_ge_dec (S k) (S n)).\n  destruct (lt_ge_dec k (S n)).\n  apply IHk in l0. clear IHk. apply lt_S_n in H0.\n  repeat rewrite pp. apply plus_FG_Nder'; auto.\n  apply Nder_power_inv_fac; auto.\n  assert (S k=n \\/ S k < n)%nat.\n   { apply lt_n_Sm_le in l. destruct l.\n     left; auto.\n     right; apply le_lt_n_Sm; auto. }\n  { destruct H2.\n    - rewrite H2.\n    assert ((fun x : R => Taylor_FormulaDer H a b n x a n)  = (fun x : R => 0)). \n     { apply fun_eq; intros; rewrite Taylor_onC_eq0; auto. }\n    rewrite H3. apply Nder_Taylor_eq0; auto.\n    - apply IHn; auto. }\n  apply le_S_gt in g. apply gt_n_S in g.\n  apply gt_asym in g. contradiction.\n  apply lt_not_le in H0. contradiction.\nQed.\n\n\nLemma Taylor_FormulaDer_onC H a b n c: forall k, (k<n)%nat ->\n  Taylor_FormulaDer H a b n c c k = N_der (Nder_H H a b k) c.\nProof.\n  intros.\n  revert H0.\n  induction n; intros.\n  - apply Nat.nlt_0_r in H0; contradiction.\n  - assert (k=n \\/ (k < n)%nat). \n     { apply lt_n_Sm_le in H0. destruct H0.\n       left; auto. \n       right; apply le_lt_n_Sm; auto. } destruct H1.\n    subst k. simpl Taylor_FormulaDer.\n    rewrite <- minus_diag_reverse.\n    destruct (lt_ge_dec n (S n)).\n    rewrite Rminus_diag_eq; auto. simpl.\n    rewrite Rmult_1_r. unfold Rdiv. rewrite Rinv_1, Rmult_1_r.\n    rewrite Taylor_onC_eq0. apply Rplus_0_r.\n    apply lt_not_le in H0; contradiction.\n    simpl. destruct (lt_ge_dec k (S n)); auto.\n    rewrite Rminus_diag_eq; auto.\n    assert(forall n:nat, (0<n)%nat -> power n 0 = 0) as power_0.\n     { intros. induction n0. apply Nat.lt_irrefl in H2. contradiction. \n       simpl. rewrite Rmult_0_l; auto. }\n    assert(forall (n m:nat),  (n<=m) -> n<m\\/n=m)%nat as or_lt_eq .\n     { intros. destruct H2.\n       right; auto.\n       left. apply le_lt_n_Sm; auto. }\n    rewrite power_0. rewrite Rmult_0_r. unfold Rdiv.\n    rewrite Rmult_0_l. rewrite Rplus_0_l. apply IHn. auto.\n    apply lt_minus_O_lt; auto.\n    apply lt_not_le in H0; contradiction.\nQed.\n\nLemma Nder_opp : forall f a b n, N_str_derivability f a b n ->\n  N_str_derivability (fun x => - (f x)) a b n.\nProof.\n  intros; generalize dependent f; induction n; intros.\n  - simpl; auto.\n  - simpl. destruct H, H. apply IHn in H0.\n    exists (fun x0 : R => - x x0); split; auto.\n    destruct H, H; red.\n    exists x0; split; intros; auto.\n    apply H1 in H2. \n    rewrite <- Rabs_Ropp in H2.\n    unfold Rminus in H2. repeat rewrite Ropp_plus_distr, Ropp_involutive in H2.\n    unfold Rminus; rewrite Ropp_involutive, Ropp_mult_distr_l, Ropp_involutive; auto.\nQed.\n\nLemma Nder_opp' : forall F f a b n, N_str_derivative F f a b n ->\n  N_str_derivative (fun x => - (F x)) (fun x => - (f x)) a b n.\nProof.\n  intros; generalize dependent F; induction n; intros.\n  - simpl in H. simpl; rewrite H; auto.\n  - simpl. destruct H, H. apply IHn in H0.\n    exists (fun x0 : R => - x x0); split; auto.\n    destruct H, H; red.\n    exists x0; split; intros; auto.\n    apply H1 in H2. \n    rewrite <- Rabs_Ropp in H2.\n    unfold Rminus in H2. repeat rewrite Ropp_plus_distr, Ropp_involutive in H2.\n    unfold Rminus; rewrite Ropp_involutive, Ropp_mult_distr_l, Ropp_involutive; auto.\nQed.\n\n\nLemma Taylor_Nder: forall H a b n, a<b ->\n  N_str_derivability (fun x => Taylor_Formula H a b n x a) a b n.\nProof.\n  intros.\n  generalize(Nder_Taylor_eq0 H a b n); intro.\n  induction n.\n  - simpl; auto.\n  - simpl. apply H1 in H0. simpl in H0.\n    destruct H0, H0. exists x.\n    split; auto.\nQed.\n\n\nLemma Taylor_on_cb : forall H a b n (l: N_str_derivability H a b n) M, \n  (forall x, x ∈ [a, b] -> Rabs(N_der l x)<=M) ->\n  forall c x, c ∈ [a, b] -> x ∈ [c, b] -> \n  Rabs(H(x)-(Taylor_Formula H a b n x c))<=\n  M*Rabs(power n (x-c))/INR(factorial n).\nProof.\n  intros.\n  assert (x ∈ [a, b]) as Domain_x. \n   { destruct H1, H3, H2, H5.\n     repeat split; auto.\n     apply Rle_trans with (r2:=c); auto. }\n  generalize H1 as Domain_c; intro.\n  assert(forall k, (k<n)%nat -> N_str_derivative\n    (fun x : R => H x - Taylor_Formula H a b n x c)\n    (fun x : R => N_der (Nder_H H a b k) x - (Taylor_FormulaDer H a b n x c k)) c b k) as N_der_Taylor.\n   { intros. unfold Rminus.\n     apply plus_FG_Nder'. apply Domain_Nder' with (a:=a)(b:=b).\n     apply Domain_c. apply Nder_H'.\n     apply Nder_opp'.\n     rewrite Domain_Taylor_eq with (c:=c); auto.\n     rewrite Domain_Taylor_Nder_eq with (c:=c); auto. apply Taylor_Nder'; auto.\n     destruct H2; auto. }\n  assert(N_str_derivative (fun x : R => H x - Taylor_Formula H a b n x c)\n    (fun x : R => N_der (Nder_H H a b n) x - 0) c b n) as N_der_Taylor_onN.\n   { intros. unfold Rminus.\n     apply plus_FG_Nder'. apply Domain_Nder' with (a:=a)(b:=b).\n     apply Domain_c. apply Nder_H'.\n     apply Domain_Nder' with (a:=c)(b:=b).\n     destruct H2. repeat split; auto. apply Rle_refl. apply Rlt_le; auto.\n     apply Nder_opp'. rewrite Domain_Taylor_eq with (c:=c); auto. apply Nder_Taylor_eq0; auto.\n     destruct H2; auto. }\n    apply Rabs_le.\n    rewrite Rabs_pos_eq; try apply power_x_pos.\n    assert(-(M*power n (x-c)/INR(factorial n))=\n            -M*power n (x-c)/INR(factorial n)).\n     { unfold Rdiv. repeat rewrite Rmult_assoc.\n       rewrite Ropp_mult_distr_l; auto. }\n    rewrite H3. clear H3.\n    assert(N_str_derivability (fun x => H x-Taylor_Formula H a b n x c) c b 0).\n     { simpl. auto. }\n    assert(forall (f g:R->R) x, f = g -> f x = g x).\n     { intros. rewrite H4; auto. }\n    assert(N_der H3 x = H x-Taylor_Formula H a b n x c).\n     { unfold N_der. unfold Con_N_der. \n       generalize(ex_trans (N_derivative_existence c b 0\n        (fun x0 : R => H x0 - Taylor_Formula H a b n x0 c) H3)); intro.\n       generalize(proj2_sig s); intro. simpl in H5.\n       apply H4 with (g:=(fun x0 : R => H x0 - Taylor_Formula H a b n x0 c)); auto. }\n    assert(n-n=0)%nat. { apply Nat.sub_diag. }\n    generalize H3; auto; intro. rewrite <- H6 in H7.\n    generalize (N_derivative_eq _ _ _ 0 (n-n) H3 H7); intro.\n    rewrite <- H5. rewrite H4 with(f:=N_der H3)(g:=N_der H7); auto.\n    assert(N_str_derivability (fun x =>H x - Taylor_Formula H a b n x c) c b n).\n     { unfold Rminus.\n       apply plus_FG_Nder. apply Domain_Nder with (a:=a)(b:=b).\n       apply Domain_c. apply l.\n       apply Domain_Nder with (a:=c)(b:=b).\n       destruct H2. repeat split; auto.\n       apply Rle_refl. apply Rlt_le; auto.\n       apply Nder_opp. rewrite Domain_Taylor_eq with (c:=c); auto. }\n    apply Taylor_Lemma with(l:=H9)(H:=(fun x : R => H x - Taylor_Formula H a b n x c))\n      (a:=c)(b:=b)(m:=-M)(q:=H7)(x:=x)(n:=n)(k:=n)(M:=M); auto.\n    + intros.\n      unfold N_der. destruct (Con_N_der p). simpl.\n      generalize(N_der_eq n0 (N_der_Taylor k H10)); intro.\n      rewrite H11.\n      rewrite Taylor_FormulaDer_onC; auto.\n      apply Rminus_diag_eq; auto.\n    + intros.\n      assert(x0 ∈ [a, b]) as Domain_c_x0.\n       { destruct Domain_c. destruct H10, H12, H13.\n         repeat split; auto.\n         apply Rle_trans with (r2:=c); auto. }\n      generalize(N_der_Taylor_onN); intro.\n      generalize(Nder_H' (fun x : R => H x - Taylor_Formula H a b n x c) c b n); intro.\n      generalize(N_der_eq N_der_Taylor_onN0 H11); intro.\n      assert((fun x : R => N_der (Nder_H H a b n) x - 0) = (fun x : R => N_der (Nder_H H a b n) x)).\n        { apply fun_eq. intro.\n          rewrite Rminus_0_r; auto. }\n      rewrite H13 in H12.\n      generalize(N_derivative_eq (fun x : R => H x - Taylor_Formula H a b n x c) c b n n\n      H9 (Nder_H (fun x : R => H x - Taylor_Formula H a b n x c) c b n)); intro.\n      rewrite H14; auto. rewrite <- H12.\n      apply Rabs_le_reg.\n      generalize( N_derivative_eq H a b n n l (Nder_H H a b n)); intro.\n      rewrite <- H15; auto.\n    + destruct H1, H3. apply Rge_le; apply Rge_minus.\n      apply Rle_ge; auto.\n      destruct H2, H5; auto.\nQed.\n\n\nLemma Nder_leN_exist : forall H f1 a b n, N_str_derivative H f1 a b (S n) ->forall k, (k<=n)%nat->\n exists f2, N_str_derivative H f2 a b k.\nProof.\n  intros; apply N_derivative_existence; eapply N_derivative_pro; eauto.\nQed.\n\n\nLemma Taylor_opp_on_cb : forall {H f1 f2 a b n}, N_str_derivative H f1 a b n -> N_str_derivative (fun x => H (- x)) f2 (-b) (-a) n\n  -> f2 = (fun x => (power n (-1)) * (f1 (- x))).\nProof.\n  intros. generalize dependent f1; generalize dependent f2; induction n; intros.\n  - simpl. simpl in H0, H1. rewrite <- H1, H0.\n    apply fun_eq; intros. rewrite Rmult_1_l; auto.\n  - assert (exists f11, N_str_derivative H f11 a b n).\n     { apply Nder_leN_exist with (k:=n) in H0; auto. }\n    assert (exists f22, N_str_derivative (fun x : R => H (- x)) f22 (-b) (-a) n).\n     { apply Nder_leN_exist with (k:=n) in H1; auto. }\n    destruct H2 as [f11 H2]. destruct H3 as [f22 H3].\n    pose proof (IHn _ H3 _ H2).\n    assert (str_derivative f11 f1 a b).\n    { apply Str_Snder with (H:=H)(n:=n); auto. }\n    assert (str_derivative f22 f2 (-b) (-a)).\n     { apply Str_Snder with (H:=fun x : R => H (- x))(n:=n); auto. }\n    assert (str_derivative (fun x => f11 (-x)) (fun x => - (f1 (-x))) (-b) (-a)).\n    { clear H6. destruct H5, H5. rename x into M.\n      exists M. split; auto.\n      intros.\n      assert( (-x) ∈ [a, b] /\\ (-x + -h) ∈ [a, b]).\n       { split. destruct H7.\n         - destruct H7, H9.\n           repeat split. apply Ropp_lt_cancel; auto.\n           rewrite <- Ropp_involutive with (r:=x) in H10.\n           apply Ropp_le_cancel in H10; auto.\n           rewrite <- Ropp_involutive with (r:=x) in H9.\n           apply Ropp_le_cancel in H9; auto.\n         - destruct H7, H8, H9.\n           repeat split. apply Ropp_lt_cancel; auto.\n           rewrite <- Ropp_plus_distr.\n           rewrite <- Ropp_involutive with (r:=x+h) in H10.\n           apply Ropp_le_cancel in H10; auto.\n           rewrite <- Ropp_plus_distr.\n           rewrite <- Ropp_involutive with (r:=x+h) in H9.\n           apply Ropp_le_cancel in H9; auto.  }\n      apply H6 in H8.  rewrite <- Ropp_plus_distr in H8.\n        unfold Rminus. unfold Rminus in H8.\n        rewrite Ropp_mult_distr_l_reverse.\n        rewrite Rmult_comm in H8. rewrite Ropp_mult_distr_l_reverse in H8.\n        rewrite Rmult_comm; auto.\n        rewrite <- Rsqr_pow2. rewrite <- Rsqr_pow2 in H8.\n        rewrite Rsqr_neg; auto. }\n    assert(str_derivative (fun x : R => power n (-1) * f11 (- x))\n      (fun x => power n (-1) * (- (f1 (-x)))) (-b) (-a)).\n     { apply Theorem3_1_1'; auto. }\n    rewrite H4 in H6.\n    pose proof (der_unique H6 H8).\n    rewrite H9. simpl.\n    apply fun_eq. intro. ring.\nQed.\n\n\nTheorem Taylor_Theorem H a b n (l: N_str_derivability H a b n):\n  forall M, (forall x, x ∈ [a, b] -> Rabs(N_der l x)<=M) ->\n  forall c x, c ∈ [a, b] -> x ∈ [a, b] -> \n  Rabs(H(x)-(Taylor_Formula H a b n x c))<=\n  M*Rabs(power n (x-c))/INR(factorial n).\nProof.\n  intros.\n  generalize H2 as Domain_x; intro.\n  generalize H1 as Domain_c; intro.\n  apply Domain_x_c with (x:=x) in H1; auto.\n  destruct H1.\n  - eapply Taylor_on_cb; eauto.\n  - set (u:=-x).\n    assert(x = -u). { unfold u. ring. }\n    rewrite H3.\n    set (G := fun u => H (- u) ).\n    assert (Rabs(G(u)-(Taylor_Formula G (-b) (-a) n u (-c)))<= M*Rabs(power n (u-(-c)))/INR(factorial n)).\n    { assert (N_str_derivability G (-b) (-a) n).\n      { unfold G. clear H0. generalize dependent H. induction n; intros. simpl; auto.\n        simpl. simpl in l. destruct l as [f [H0]].\n        exists (fun x => - (f (-x))); split.\n        destruct H0 as [M1 [H0]].\n        exists M1; split ;auto. intros.\n        assert ((-x0) ∈ [a, b] /\\ ((-x0) + (-h)) ∈ [a, b]). \n         { split. destruct H6.\n           - destruct H6, H8.\n             repeat split. apply Ropp_lt_cancel; auto.\n             rewrite <- Ropp_involutive with (r:=x0) in H9.\n             apply Ropp_le_cancel in H9; auto.\n             rewrite <- Ropp_involutive with (r:=x0) in H8.\n             apply Ropp_le_cancel in H8; auto.\n           - destruct H6, H7, H8.\n             repeat split. apply Ropp_lt_cancel; auto.\n             rewrite <- Ropp_plus_distr.\n             rewrite <- Ropp_involutive with (r:=x0+h) in H9.\n             apply Ropp_le_cancel in H9; auto.\n             rewrite <- Ropp_plus_distr.\n             rewrite <- Ropp_involutive with (r:=x0+h) in H8.\n             apply Ropp_le_cancel in H8; auto. }\n        apply H5 in H7.\n        rewrite <- Ropp_plus_distr in H7.\n        unfold Rminus. unfold Rminus in H7.\n        rewrite Ropp_mult_distr_l_reverse.\n        rewrite Rmult_comm in H7. rewrite Ropp_mult_distr_l_reverse in H7.\n        rewrite Rmult_comm; auto.\n        rewrite <- Rsqr_pow2. rewrite <- Rsqr_pow2 in H7.\n        rewrite Rsqr_neg; auto.\n        apply IHn in H4; auto. }\n       apply (Taylor_on_cb G (-b) (-a) n H4).\n       intros.\n       assert ((-x0) ∈ [a, b]). \n        { destruct H5, H6.\n          repeat split. apply Ropp_lt_cancel; auto.\n          rewrite <- Ropp_involutive with (r:=x0) in H7.\n          apply Ropp_le_cancel in H7; auto.\n          rewrite <- Ropp_involutive with (r:=x0) in H6.\n          apply Ropp_le_cancel in H6; auto.  }\n       apply H0 in H6.\n       assert (Rabs (N_der l (- x0)) = Rabs (N_der H4 x0)).\n       { unfold N_der. destruct (Con_N_der l), (Con_N_der H4); simpl.\n          rename x1 into f1. rename x2 into f2.\n          pose proof (Taylor_opp_on_cb n0 n1). rewrite H7.\n          rewrite Rabs_mult. rewrite Rabs_power_opp.\n          rewrite Rmult_1_l; auto. }\n    rewrite <- H7; auto.\n    destruct Domain_c, H6. repeat split.\n    try apply Ropp_lt_contravar; auto.\n    apply Ropp_le_contravar; auto.\n    apply Ropp_le_contravar; auto.\n    apply Ropp_eq_compat in H3. rewrite Ropp_involutive in H3.\n    rewrite <- H3. destruct H1, H5.\n    repeat split.\n    try apply Ropp_lt_contravar; auto.\n    apply Ropp_le_contravar; auto.\n    apply Ropp_le_contravar; auto. }\n    assert (Taylor_Formula G (- b) (- a) n u (- c) = Taylor_Formula H a b n (- u) c).\n    { unfold G. clear H0 l H4.  induction n. simpl. auto. \n      simpl. rewrite IHn. f_equal. f_equal.\n      assert (N_str_derivative H (N_der (Nder_H H a b n)) a b n).\n      { unfold N_der; destruct ((Con_N_der (Nder_H H a b n))); simpl; auto. }\n      assert (N_str_derivative (fun u0 => H (- u0)) (N_der (Nder_H (fun u0 => H (- u0)) (- b) (- a) n)) (-b) (-a) n).\n      { unfold N_der; destruct ((Con_N_der (Nder_H (fun u0 => H (- u0)) (- b) (- a) n))); simpl; auto. }\n      pose proof (Taylor_opp_on_cb H0 H4).\n      rewrite H5. unfold Rminus; rewrite Ropp_involutive.\n      assert(-u + -c = -1*(u+c)). { ring. }\n      rewrite H6. rewrite pow_mult_ab.\n      rewrite Rmult_comm with (r1:=N_der (Nder_H H a b n) c).\n      rewrite Rmult_assoc. rewrite Rmult_comm with (r1:=N_der (Nder_H H a b n) c).\n      rewrite <- Rmult_assoc; auto. }\n    rewrite <- H5. unfold Rminus in H4. rewrite Ropp_involutive in H4.\n    unfold Rminus.\n    assert(Rabs (power n (- u + - c)) = Rabs (power n (u + c))).\n     { assert(-u + -c = -1*(u+c)). { ring. }\n       rewrite H6. rewrite pow_mult_ab. rewrite Rabs_mult.\n       rewrite Rabs_power_opp. rewrite Rmult_1_l; auto.  }\n    rewrite H6; auto.\nQed.", "meta": {"author": "LittleGavin", "repo": "calculus_3rd", "sha": "6d0fd26bcf9f00252a2fffaee85b299c589d844c", "save_path": "github-repos/coq/LittleGavin-calculus_3rd", "path": "github-repos/coq/LittleGavin-calculus_3rd/calculus_3rd-6d0fd26bcf9f00252a2fffaee85b299c589d844c/Calculus_3rd/A_5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240721511739, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.686214358615275}}
{"text": "(**\n* Induction in Coq\n\n  From: https://www.cs.cornell.edu/courses/cs3110/2018sp/l/22-coq-induction/notes.v\n-----\n#<i>#\nTopics:\n\n- recursive functions\n- induction on lists\n- induction on natural numbers\n- rings and fields\n- induction principles\n- extraction\n\n#</i>#\n\n-----\n\nWe'll need the list library for these notes.\n*)\n\nRequire Import List.\nImport ListNotations.\n\n(**\n\n(**********************************************************************)\n\n** Recursive functions\n\nThe [List] library defines the list append operator, which in Coq is written as\ninfix operator [++], or as prefix function [app].  In OCaml, the same operator\nis written [@].  In OCaml's standard library, you'll recall that append\nis defined as follows:\n\n<<\nlet rec append lst1 lst2 =\n  match lst1 with\n  | [] -> lst2\n  | h::t -> h :: (append t lst2)\n>>\n\nThe Coq equivalent of that would be: *)\n\nFixpoint append {A : Type} (lst1 : list A) (lst2 : list A) :=\n  match lst1 with\n  | nil => lst2\n  | h::t => h :: (append t lst2)\n  end.\n\n(** The [Fixpoint] keyword is similar to a [let rec] definition in OCaml. The\nbraces around [A : Type] in that definition make the [A] argument implicit,\nhence we don't have to provide it at the recursive call to [append] in the\nsecond branch of the pattern match.  Without the braces, we'd have to write the\nfunction as follows: *)\n\nFixpoint append' (A : Type) (lst1 : list A) (lst2 : list A) :=\nmatch lst1 with\n| nil => lst2\n| h::t => h :: (append' A t lst2)\nend.\n\n(** The actual definition of [++] in the Coq standard library is a little more\ncomplicated, but it's essentially the same idea.  Here's that definition:\n\n<<\nDefinition app (A : Type) : list A -> list A -> list A :=\n  fix app' lst1 lst2 :=\n    match lst1 with\n    | nil => lst2\n    | h :: t => h :: app' t lst2\n    end.\n>>\n\nThe Coq [fix] keyword is similar to a [let rec] expression in OCaml, but where\nthe body of the expression is implicit:  Coq [fix f x1 .. xn := e] is like OCaml\n[let rec f x1 .. xn = e in f].  So in OCaml we could rephrase the above\ndefinition as follows:\n\n<<\nlet app : 'a list -> 'a list -> 'a list =\n  let rec app' lst1 lst2 =\n    match lst1 with\n    | [] -> lst2\n    | h :: t -> h :: app' t lst2\n  in\n  app'\n>>\n\nNow that we know how Coq defines [++], let's prove a theorem about it.\n*)\n\nTheorem nil_app : forall (A:Type) (lst : list A),\n  [] ++ lst = lst.\n\n(** Intuition:  appending the empty list to [lst] immediately returns\n    [lst], by the definition of [++]. *)\n\nProof.\n  intros A lst.\n  simpl.\n  trivial.\nQed.\n\n(** The second step in that proof simplifies [[] ++ lst] to [lst].  That's\nbecause of how [++] is defined:  it pattern matches against its first argument,\nwhich here is [[]], hence simply returns its second argument.\n\nNext, let's prove that appending nil on the right-hand side also results in\n[lst]: *)\n\nTheorem app_nil : forall (A:Type) (lst : list A),\n  lst ++ [] = lst.\n\n(* Intuition (incomplete):  by case analysis on [lst].\n   - if [lst] is [[]], then trivially [[] ++ []] is [[]].\n   - if [lst] is [h::t], then ...? *)\n\nProof.\n  intros A lst. destruct lst as [ | h t].\n  - trivial.\n  - simpl.  (* can't proceed *)\nAbort.\n\n(** When we get to the end of that proof, we are trying to show that [h :: (t ++\n[]) = h :: t].  There's no way to make progress on that, because we can't\nsimplify [t ++ []] to just [t].  Of course as humans we know that holds.  But to\nCoq, that's a fact that hasn't yet been proved.  Indeed, it is an instance of\nthe theorem we're currently trying to prove!\n\nWhat's going wrong here is that case analysis is not a sufficiently powerful\nproof technique for this theorem.  We need to be able to _recursively_ apply the\ntheorem we're trying to prove to smaller lists.  That's where _induction_ comes\ninto play.\n\n(**********************************************************************)\n\n** Induction on lists\n\n_Induction_ is a proof technique that you will have encountered in math\nclasses before---including CS 2800.  It is useful when you want to prove\nthat some property holds of all the members of an infinite set, such as\nthe natural numbers, as well as lists, trees, and other data types.\n\nOne classic metaphor for induction is _falling dominos_:  if you arrange some\ndominos such that each domino, when it falls, will knock over the next domino,\nand if you knock over the first domino, then all the dominos will fall. Another\nclassic metaphor for induction is a _ladder_:  if you can reach the first rung,\nand if for any given rung the next rung can be reached, then you can reach any\nrung you wish.  (As long as you're not afraid of heights.)\n\nWhat both of those metaphors have in common is\n\n- a _base case_, in which something is done first.  For the dominos, it's\n  knocking over the first domino; for the ladder, it's climbing the first rung.\n  And,\n\n- an _inductive case_, in which a step is taken from one thing to the\n  the next.  For the dominos, it's one domino knocking over the next; for the\n  ladder, it's literally taking the step from one rung to the next.  In both\n  cases, it must actually be possible for the action to occur:  if the dominos\n  or the rungs were spaced too far apart, then progress would stop.\n\nA proof by induction likewise has a base case and an inductive case.\nHere's the structure of a proof by induction on a list:\n\n<<\nTheorem.  For all lists lst, P(lst).\n\nProof.  By induction on lst.\n\nCase:  lst = nil\nShow:  P(nil)\n\nCase:  lst = h::t\nIH:    P(t)\nShow:  P(h::t)\n\nQED.\n>>\n\nThe _base case_ of a proof by induction on lists is for when the list is empty.\nThe _inductive case_ is when the list is non-empty, hence is the cons of a head\nto a tail.  In the inductive case, we get to assume an _inductive hypothesis_,\nwhich is that the property [P] holds of the tail.\n\nIn the metaphors above, the inductive hypothesis is the assumption that we've\nalready reached some particular domino or rung.  From there, the metaphorical\nwork we do in the inductive case of the proof is to show that from that domino\nor rung, we can reach the next one.\n\nAn inductive hypothesis is exactly the kind of assumption we needed to get our\nproof about appending nil to go through.\n\nHere's how that proof could be written:\n\n<<\nTheorem:  for all lists lst, lst ++ nil = lst.\n\nProof:  by induction on lst.\nP(lst) = lst ++ nil = lst.\n\nCase:  lst = nil\nShow:\n  P(nil)\n= nil ++ nil = nil\n= nil = nil\n\nCase:  lst = h::t\nIH: P(t) = (t ++ nil = t)\nShow\n  P(h::t)\n= (h::t) ++ nil = h::t\n= h::(t ++ nil) = h::t     // by definition of ++\n= h::t = h::t              // by IH\n\nQED\n>>\n\nIn Coq, we could prove that theorem as follows:\n*)\n\nTheorem app_nil : forall (A:Type) (lst : list A),\n  lst ++ nil = lst.\nProof.\nintros A lst. induction lst as [ | h t IH].\n- simpl. trivial.\n- simpl. rewrite -> IH. trivial.\nQed.\n\n\n\n(** The tactics used in that proof correspond exactly to the non-Coq proof\nabove.\n\nThe [induction] tactic is new to us.  It initiates a proof by induction on its\nargument, in this case [lst], and provides names for the variables to be used in\nthe cases.  There aren't any new variables in the base case, but the inductive\ncase has variables for the head of the list, the tail, and the inductive\nhypothesis.  You could leave out those variables and simply write [induction\nlst.], but that leads to a less human-readable proof.\n\nIn the inductive case, we use the [rewrite ->] tactic to rewrite [t ++\nnil] to [t].  The [IH] says those terms are equal.  That tactic replaces the\nleft-hand side of the equality with the right-hand side, wherever the left-hand\nside appears in the subgoal. It's also possible to rewrite from right to left\nwith the [rewrite <-] tactic.  If you leave out the arrow, Coq assumes that\nyou mean [->].\n\nHere's another theorem we can prove in exactly the same manner. This\ntheorem shows that append is _associative_.\n\n<<\nTheorem:  forall lists l1 l2 l3, l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\n\nProof: by induction on l1.\nP(l1) = l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3\n\nCase:  l1 = nil\nShow:\n  P(nil)\n= nil ++ (l2 ++ l3) = (nil ++ l2) ++ l3\n= l2 ++ l3 = l2 ++ l3   // simplifying ++, twice\n\nCase:  l1 = h::t\nIH:  P(t) = t ++ (l2 ++ l3) = (t ++ l2) ++ l3\nShow:\n  P(h::t)\n= h::t ++ (l2 ++ l3) = (h::t ++ l2) ++ l3\n= h::(t ++ (l2 ++ l3)) = h::((t ++ l2) ++ l3)  // simplifying ++, thrice\n= h::((t ++ l2) ++ l3) = h::((t ++ l2) ++ l3)  // by IH\n\nQED\n>>\n\nIn Coq, that proof looks more or less identical to our previous Coq proof\nabout append and nil:\n*)\n\nTheorem app_assoc : forall (A:Type) (l1 l2 l3 : list A),\n  l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\n(* Intuition: above *)\nProof.\n  intros A l1 l2 l3.\n  induction l1 as [ | h t IH].\n  - simpl. trivial.\n  - simpl. rewrite -> IH. trivial.\nQed.\n\n(**\n(**********************************************************************)\n\n** Induction on natural numbers\n\nOne of the classic theorems proved by induction is that [0 + 1 + ... + n] is\nequal to [n * (n+1) / 2].  It uses proof by induction on the natural numbers,\nwhich are the non-negative integers.  The structure of a proof by induction on\nthe naturals is as follows:\n\n<<\nTheorem.  For all natural numbers n, P(n).\n\nProof.  By induction on n.\n\nCase:  n = 0\nShow:  P(0)\n\nCase:  n = k+1\nIH:    P(k)\nShow:  P(k+1)\n\nQED.\n>>\n\nThe base case is for zero, the smallest natural number.  The inductive case\nassumes that P holds of k, then shows that P holds of k+1.\n\nThe [induction] tactic in Coq works for inductive types---that is, types defined\nwith the [Inductive] keyword.  You might, therefore, suspect that if we're going\nto do induction over [nat]s, the type [nat] must be inductively defined.  Indeed\nit is.  There is a famous inductive definition of the natural numbers that is\ncredited to Giuseppe Peano (1858-1932).  In OCaml, that definition would be:\n\n<<\ntype nat = O | S of nat\n>>\n\nThe [O] constructor (that's the letter capital O) represents zero.\nThe [S] constructor represents the successor function---that is, the\nfunction that adds one to its argument.  So:\n\n- 0 is [O]\n- 1 is [S O]\n- 2 is [S (S O)]\n- 3 is [S (S (S O))]\n- etc.\n\nThis is a kind of _unary_ representation of the naturals, in which we repeat\nthe symbol [S] a total of [n] times to represent the natural number [n].\n\nThe Coq definition of [nat] is much the same:\n*)\n\nPrint nat.\n\n(**\nCoq responds with output that is equivalent to the following:\n<<\nInductive nat : Set :=\n  | O : nat\n  | S : nat -> nat\n>>\n\nThat is, [nat] has two constructors, [O] and [S], which are just like the OCaml\nconstructors we examined above.  And [nat] has type [Set], meaning that [nat] is\na specification for program computations.  (Or, a little more loosely, that\n[nat] is a type representing program values.)\n\nAnywhere we write something that looks like an integer literal in Coq, Coq\nactually understand that as its expansion in the Peano representation defined\nabove.  For example, [2] is understood by Coq as just syntactic sugar for [S (S\nO)].  We can even write computations using those constructors:\n*)\n\nCompute S (S O).\n\n(**\nCoq responds, though, by reintroducing the syntactic sugar:\n<<\n= 2 : nat\n>>\n\nThe Coq standard library defines many functions over [nat] using those\nconstructors and pattern matching, including addition, subtraction,\nand multiplication.  For example, addition is defined like this:\n*)\n\nFixpoint my_add (a b : nat) : nat :=\n  match a with\n  | 0 => b\n  | S c => S (my_add c b)\n  end.\n\n(**\nNote that we're allowed to use either [0] or [O] as a pattern, because\nthe former is just syntactic sugar for the latter.  The second branch\nof the pattern match is effectively calling [my_add] recursively with\n[a-1] as its first argument, since [a = S c], meaning that [a] is the\nsuccessor of [c].\n\nNow that we know how [nat] is defined inductively, let's try\nto prove the classic theorem mentioned above about summation.\nMoreover, let's prove that a program that computes the sum [0 + 1 + ... + n]\ndoes in fact compute [n * (n+1) / 2].  First, we need to write\nthat program.  In OCaml, we could write the program quite easily:\n<<\nlet rec sum_to n =\n  if n=0 then 0\n  else n + sum_to (n-1)\n>>\n\nIn Coq, it will turn out to be surprisingly tricky...\n\n(**********************************************************************)\n\n** Recursive functions, revisited\n\nHere's a first attempt at defining [sum_to], which is just a direct translation\nof the OCaml code into Coq.  The [Fail] keyword before it tells Coq to expect\nthe definition to fail to compile. *)\n\nFail Fixpoint sum_to (n:nat) : nat :=\n  if n = 0 then 0 else n + sum_to (n-1).\n\n(**\nCoq responds:\n<<\nThe command has indeed failed with message:\nThe term \"n = 0\" has type \"Prop\"\nwhich is not a (co-)inductive type.\n>>\nThe problem is the the equality operator [=] returns a proposition (i.e.,\nsomething we could try to prove), whereas the [if] expression expects a Boolean\n(i.e., [true] or [false]) as its guard. (Actually [if] is willing to accept any\nvalue of an inductive type with exactly two constructors as its guard, and\n[bool] is an example of such a type.)\n\nTo fix this problem, we need to use an equality operator that returns a [bool],\nrather than a [Prop], when applied to two [nat]s.  Such an operator is defined\nin the [Arith] library for us: *)\n\nRequire Import Arith.\n\nLocate \"=?\".\nCheck Nat.eqb.\n\n(** Coq responds:\n<<\nNat.eqb : nat -> nat -> bool\n>>\n\nWe can now try to use that operator.  Unfortunately, we discover a new problem:\n*)\n\nFail Fixpoint sum_to (n:nat) : nat :=\n  if n =? 0 then 0 else n + sum_to (n-1).\n\n(** Coq responds with output that contains the following lines:\n<<\nRecursive definition of sum_to is ill-formed.\n...\nRecursive call to sum_to has principal argument equal to\n\"n - 1\" instead of a subterm of \"n\".\n...\n>>\nAlthough the error message might be cryptic, you can see that Coq is complaining\nabout the recursive call in the [else] branch.  For some reason, Coq is unhappy\nabout the argument [n-1] provided at that call.  Coq wants that argument to be a\n\"subterm\" of [n].  The words _term_ and _expression_ are synonymous here, so Coq\nis saying that it wants the argument to be a subexpression of [n].  Of course\n[n] doesn't have any subexpressions. So why is Coq giving us this error?\n\nBefore we can answer that question, let's look at a different recursive\nfunction---one that implements an infinite loop: *)\n\nFail Fixpoint inf (x:nat) : nat := inf x.\n\n(**\nCoq responds very similarly to how it did with [sum_to]:\n<<\nRecursive definition of inf is ill-formed.\n...\nRecursive call to inf has principal argument equal to\n\"x\" instead of a subterm of \"x\".\n>>\n\nThe reason Coq rejects [inf] is that #<b>Coq does not permit any infinite\nloops</b>#. That might seem strange, but there's an excellent reason for it.\nConsider how [inf] would be defined in OCaml:\n<<\n# let rec inf x = inf x\nval inf : 'a -> 'b = <fun>\n>>\nLet's look at the type of that function, using what we learned about\npropositions-as-types in the previous lecture.  The type ['a -> 'b]\ncorresponds to the proposition [A -> B], where [A] and [B] could\nbe any propositions.  In particular, [A] could be [True] and [B]\ncould be [False], leading to the proposition [True -> False].  That's\na proposition that should never be provable:  truth does not imply\nfalsehood.  And yet, since [inf] is a program of that type, [inf]\ncorresponds to a proof of that proposition.  So using [inf] we could\nactually prove [False]:\n<<\ntype void = {nope : 'a . 'a};;\nlet rec inf x = inf x;;\nlet ff : void = inf ();;\n>>\nThe [void] type is how we represented [False] in the previous lecture.\nThe value [ff] above corresponds to a proof of [False].\nSo infinite loops are able to prove [False].\n\nIn OCaml we don't mind that phenomenon, because OCaml's purpose is not to be a\nproof assistant.  But in Coq it would be deadly:  we should never allow the\nproof assistant to prove false propositions.  Coq therefore wants to prohibit\nall infinite loops.  But that's easier said than done!  Recall from CS 2800 that\nthe _halting problem_ is undecidable:  we can't write a program that precisely\ndetermines whether another program will terminate.  Well, the Coq compiler is a\nprogram, and it wants to detect which programs terminate and which programs do\nnot---which is exactly what the halting problem says is impossible.\n\nSo instead of trying to do something impossible, Coq settles for doing something\npossible but imprecise, specifically, something that prohibits all\nnon-terminating programs as well as prohibiting some terminating programs. Coq\nenforces a syntactic restriction on recursive functions: there must always be an\nargument that is _syntactically smaller_ at every recursive function\napplication.  An expression [e1] is syntactically smaller than [e2] if [e1] is a\nsubexpression of [e2].  For example, [1] is syntactically smaller than [1-x],\nbut [n-1] is not syntactically smaller than [n].  It turns out this restriction\nis sufficient to guarantee that programs must terminate:  eventually, if every\ncall results in something smaller, you must reach something that is small enough\nthat you cannot make a recursive call on it, hence evaluation must terminate.  A\nsynonym for \"syntactically smaller\" is _structurally decreasing_.\n\nBut that does rule out some programs that we as humans know will terminate yet\ndo not meet the syntactic restriction.  And [sum_to] is one of them. Here is the\ndefinition we previously tried: *)\n\nFail Fixpoint sum_to (n:nat) : nat :=\n  if n =? 0 then 0 else n + sum_to (n-1).\n\n(** The recursive call to [sum_to] has as its argument [n-1], which\nsyntactically is actually bigger than the original argument of [n].  So Coq\nrejects the program.\n\nTo finally succeed in definining [sum_to], we can make use of what we know about\nhow [nat] is defined:  since it's an inductive type, we can pattern match on it:\n*)\n\nFixpoint sum_to (n:nat) : nat :=\n  match n with\n  | 0 => 0\n  | S k => n + sum_to k\n  end.\n\n(** The second branch of the pattern match recurses on an argument that is both\nsyntactically and arithmetically smaller, just as our definition of [my_add]\ndid, above.  So Coq's syntactic restriction on recursion is satisfied, and the\ndefinition is accepted as a program that definitely terminates.\n\n\n<<--------CS6225 STOPPED HERE-------->>\n\n\n(**********************************************************************)\n\n** Inductive proof of the summation formula\n\nNow that we've finally succeeded in defining [sum_to], we can prove\nthe classic theorem about summation.\n\nHere's how we would write the proof mathematically:\n\n<<\nTheorem:  for all natural numbers n, sum_to n = n * (n+1) / 2.\n\nProof:  by induction on n.\nP(n) = sum_to n = n * (n+1) / 2\n\nCase:  n=0\nShow:\n  P(0)\n= sum_to 0 = 0 * (0+1) / 2\n= 0 = 0 * (0+1) / 2         // simplifying sum_to 0\n= 0 = 0                     // 0 * x = 0\n\nCase:  n=k+1\nIH:  P(k) = sum_to k = k * (k+1) / 2\nShow:\n  P(k+1)\n= sum_to (k+1) = (k+1) * (k+1+1) / 2\n= k + 1 + sum_to k = (k+1) * (k+1+1) / 2          // simplifying sum_to (k+1)\n= k + 1 + k * (k+1) / 2 = (k+1) * (k+1+1) / 2     // using IH\n= 2 + 3k + k*k = 2 + 3k + k*k                     // simplifying terms on each side\n\nQED\n>>\n\nNow let's do the proof in Coq. *)\n\nTheorem sum_sq : forall n : nat,\n  sum_to n = n * (n+1) / 2.\nProof.\n  intros n.\n  induction n as [ | k IH].\n  - trivial.\n  - simpl. rewrite -> IH.\nAbort.\n\n\n(** The proof is working fine so far, but now we have a complicated algebraic\nequation we need to prove:\n<<\nS (k + k * (k + 1) / 2) = fst (Nat.divmod (k + 1 + k * S (k + 1)) 1 0 0)\n>>\n([divmod] is part of how [/] is implemented in Coq.)\n\nAlthough we could try to prove that manually using the definitions of all the\noperators, it would be much nicer to get Coq to find the proof for us.  It turns\nout that Coq does have great support for finding proofs that involve _rings_:\nalgebraic structures that support addition and multiplication operations.\n(We'll discuss rings in detail after we finish the current proof.)  But we can't\nuse that automation here, because the equation we want to prove also involves\ndivision, and rings do not support division operations.\n\nTo avoid having to reason about division, we could rewrite the theorem we want\nto prove:  by multiplying both sides by 2, the division goes away: *)\n\nTheorem sum_sq_no_div : forall n : nat,\n  2 * sum_to n = n * (n+1).\nProof.\n  intros n.\n  induction n as [ | k IH].\n  - trivial.\n  - simpl.\nAbort.\n\n(** Now, after the call to [simpl], we don't have any division, but we also\ndon't have any expressions that look exactly like the left-hand side of the\ninductive hypothesis.  The problem is that [simpl] was too agressive in\nsimplifying all the expressions. All we really want is to transform the\nleft-hand side of the subgoal, [2 * sum_to (S k)], into an expression that\ncontains the left-hand side of the inductive hypothesis, [2 * sum_to k].\nThinking about the definition of [sum_to], we ought to be able to transform \n\n[2 * sum_to (S k)] \n\ninto \n\n[2 * (S k + sum_to k)]\n\n, which equals \n\n[2 * (S k) + 2 * sum_to k].  \n\nThat final expression does have the left-hand side of the inductive\nhypothesis in it, as desired.  Let's factor out that reasoning as a separate\n\"helper\" theorem.  In math, helper theorems are usually called _lemmas_.  The\nCoq keyword [Lemma] is synonymous with [Theorem]. *)\n\nLemma sum_helper : forall n : nat,\n  2 * sum_to (S n) = 2 * (S n) + 2 * sum_to n.\nProof.\n  intros n. simpl. ring.\nQed.\n\n(** The proof above simplifies the application of [sum_to (S n)], then invokes a\nnew tactic called [ring].  That tactic is able to automatically search for\nproofs of equations involving addition and multiplication of natural numbers.\n\nNow that we have our helper lemma, we can use it to prove the theorem: *)\n\nTheorem sum_sq_no_div : forall n : nat,\n  2 * sum_to n = n * (n+1).\nProof.\n  intros n.\n  induction n as [ | k IH].\n  - trivial.\n  - rewrite -> sum_helper.\n    rewrite -> IH.\n    ring.\nQed.\n\n(** Once more, after doing the rewriting with the lemma and the inductive\nhypothesis, we're left with algebraic equations that can be proved simply by\ninvoking the [ring] tactic.\n\nFinally, we can use [sum_sq_no_div] to prove the original theorem involving\ndivision.  To do that, we need to first prove another lemma that shows we can\ntransform a multiplication into a division: *)\n\nLemma div_helper : forall a b c : nat,\n  c <> 0 -> c * a = b -> a = b / c.\nProof.\n  intros a b c neq eq.\n  rewrite <- eq.\n  rewrite Nat.mul_comm.\n  rewrite Nat.div_mul.\n  trivial.\n  assumption.\nQed.\n\nCheck Nat.mul_comm.\n\n(**\nThat lemma involves two library theorems, [mult_comm] and [Nat.div_mul]. How\ndid we know to use these?  Coq can help us search for useful theorems. Right\nafter we [rewrite <- eq] in the above proof, our subgoal is [a = c * a / c]. It\nlooks like we ought to be able to cancel the [c] term on the right-hand side.\nSo we can search for a theorem that would help us do that.  The [Search] command\ntakes wildcards and reports all theorems that match the pattern we supply, for\nexample:\n*)\n\nSearch (_ * _ / _).\n\n(** This reveals a useful theorem:\n<<\nNat.div_mul: forall a b : nat, b <> 0 -> a * b / b = a\n>>\nThat would let us cancel a term from the numerator and denominator, but it\nrequires the left-hand side of the equality to be of the form [a * b / b],\nwhereas we have [c * a / c].  The problem is that the two sides of the\nmultiplication are reversed.  No worries; multiplication is commutative, and\nthere is a library theorem that proves it. Again, we could find that theorem: *)\n\nSearch (_ * _ = _ * _).\n\n(** One of the results is:\n<<\nNat.mul_comm: forall n m : nat, n * m = m * n\n>>\n\nPutting those two library theorems to use, we're able to prove the lemma as\nabove.\n\nFinally, we can use that lemma to prove our classic theorem about summation. *)\n\nTheorem sum_sq : forall n : nat,\n  sum_to n = n * (n+1) / 2.\nProof.\n  intros n.\n  apply div_helper.\n  - discriminate.\n  - rewrite sum_sq_no_div. trivial.\nQed.\n\n(** When we use [apply div_helper] in that proof, Coq generates two new\nsubgoals---one for each of the propositions [c <> 0] and [c * a = b] in the type\nof [div_helper].\n\n_Summary_:  wow, that was a lot of work to prove that seemingly simple classic\ntheorem!  We had to figure out how to code [sum_to], and we had to deal with a\nlot of complications involving algebra.  This situation is not uncommon:  the\ntheorems that we think of as easy with pencil-and-paper (like arithmetic) turn\nout to be hard to convince Coq of, whereas the theorems that we think of as\nchallenging with pencil-and-paper (like induction) turn out to be easy.\n\n(**********************************************************************)\n\n** Rings and fields\n\nIn the proof we just did above about summation, we used a tactic called [ring]\nthat we said searches for proofs about algebraic equations involving\nmultiplication and addition.  Let's look more closely at that tactic.\n\nWhen we studied OCaml modules, we looked at _rings_ as an example of a\nmathematical abstraction of addition, multiplication, and negation.  Here is an\nOCaml signature for a ring:\n\n<<\nmodule type Ring = sig\n  type t\n  val zero : t\n  val one  : t\n  val add  : t -> t -> t\n  val mult : t -> t -> t\n  val neg  : t -> t\nend\n>>\n\nWe could implement that signature with a representation type [t] that is [int],\nor [float], or even [bool].\n\nThe names given in [Ring] are suggestive of the operations they represent, but\nto really specify how those operations should behave, we need to write some\nequations that relate them.  Below are the equations that (it turns out) fully\nspecify [zero], [one], [add], and [mult].  Rather than use those identifiers, we\nuse the more familiar notation of [0], [1], [+], and [*].\n\n<<\n0 + x = x\nx + y = y + x\nx + (y + z) = (x + y) + z\n\n0 * x = 0\n1 * x = 1\nx * y = y * x\nx * (y * z) = (x * y) * z\n\n(x + y) * z = (x * z) + (y * z)\n>>\n\nTechnically these equations specify what is known as a _commutative semi-ring_.\nIt's a _semi_-ring because we don't have equations specifying negation yet.\nIt's a _commutative_ semi-ring because the [*] operation commutes. (The [+]\noperation commutes too, but that's always required of a semi-ring.)\n\nThe first group of equations specifies how [+] behaves on its own. The second\ngroup specifies how [*] behaves on its own. The final equation specifies how [+]\nand [*] interact.\n\nIf we extend the equations above with the following two, we get a specification\nfor a _ring_:\n\n<<\nx - y = x + (-y)\nx + (-x) = 0\n>>\n\nIt's a remarkable fact from the study of _abstract algebra_ that those equations\ncompletely specify a ring.  Any theorem you want to prove about addition,\nmultiplication, and negation follows from those equations.  We call the\nequations the _axioms_ that specify a ring.\n\nRings don't have a division operation.  Let's introduce a new operator called\n[inv] (short for \"inverse\"), and let's write [1/x] as syntactic sugar for [inv\nx].  If we take all the the ring axioms and add the following axiom for [inv],\nwe get what is called a _field_:\n\n<<\nx * 1/x = 1     if x<>0\n>>\n\nA field is an abstraction of addition, multiplication, negation, and division.\nNote that OCaml [int]s do not satisfy the [inv] axiom above.  For example, [2 *\n(1/2)] equals [0] in OCaml, not [1].  OCaml [float]s mostly do satisfy the field\naxioms, up to the limits of floating-point arithmetic.  And in mathematics, the\nrational numbers and the real numbers are fields.\n\nCoq provides two tactics, [ring] and [field], that automatically search for\nproofs using the ring and field axioms. The [ring] tactic was already loaded for\nus when we wrote [Require Import Arith] earlier in this file. We can use the\n[ring] tactic to easily prove equalities that follow from the ring axioms.  Here\nare two examples. *)\n\nTheorem plus_comm : forall a b,\n  a + b = b + a.\nProof.\n  intros a b. ring.\nQed.\n\nTheorem foil : forall a b c d,\n  (a + b) * (c + d) = a*c + b*c + a*d + b*d.\nProof.\n  intros a b c d. ring.\nQed.\n\n(** Coq infers the types of the variables above to be [nat], because the [+] and\n[*] operators are defined on [nat].\n\nThe proofs that the [ring] tactic finds can be quite complicated.  For example,\ntry looking at the output of the following command.  It's so long that we won't\nput that output in this file! *)\n\nPrint foil.\n\n(** Of course, [ring] won't find proofs of equations that don't actually hold.\nFor example, if we had a typo in our statement of [foil], then [ring] would\nfail. *)\n\nTheorem broken_foil:  forall a b c d,\n  (a + b) * (c + d) = a*c + b*c + c*d + b*d.\nProof.\n  intros a b c d. try ring.\nAbort.\n\n(** Here's a theorem that [ring], perhaps surprisingly, cannot prove. *)\n\nTheorem sub_add_1 : forall a : nat, a - 1 + 1 = a.\nProof.\n  intros a.\n  try ring.\nAbort.\n\n(** What's going wrong here is that [nat] is really only a semi-ring, not a\nring. That is, [nat] doesn't satisfy the axioms about negation.  Why?  Remember\nthat the natural numbers stop at [0]; we don't get any negative numbers. So if\n[a] is [0] in the above theorem, [a-1] actually evaluates to [0] rather than\n[-1]. *)\n\nCompute 0-1.  (* 0 : nat *)\n\n(** If we want to reason about the integers instead of the natural numbers, we\ncan use a library called [ZArith] for that.  The name comes from the fact that\n[Z] is used in mathematics to denote the integers. *)\n\nRequire Import ZArith.\nOpen Scope Z_scope.\n\n(** The [Open Scope] command causes the [ZArith] library's scope to be used to\nresolve names, hence [+] becomes the operator on [Z] instead of on [nat], as\ndoes [-], etc. *)\n\nCompute 0-1.  (* -1 : Z *)\n\n(** Now we can prove the theorem from before. *)\n\nTheorem sub_add_1 : forall a : Z, a - 1 + 1 = a.\nProof.\n  intros a. ring.\nQed.\n\n(** Before going on, let's close the [Z] scope so that the operators go back to\nworking on [nat], as usual. *)\n\nClose Scope Z_scope.\n\nCompute 0-1.  (* 0 : nat *)\n\n(** Coq also provides implementations of the rational numbers as a field, as\nwell as the real numbers as a field.  To get the [field] tactic, we first need\nto load the [Field] library. *)\n\nRequire Import Field.\n\n(** The rational numbers are provided in a couple different Coq libraries; the\none we'll use here is [Qcanon].  In mathematics, [Q] denotes the rational\nnumbers, and [canon] indicates that the numbers are stored in a _canonical\nform_---that is, as simplified fractions. For example, [Qcanon] would represent\n[2/4] as [1/2], eliminating the common factor of [2] from the numerator and the\ndenominator.  (The [QArith] library provides rational numbers that are not in\ncanonical form.) *)\n\n\n\nRequire Import Qcanon.\nOpen Scope Qc_scope.\n\nTheorem frac_qc: forall x y z : Qc, z <> 0 -> (x + y) / z = x / z + y /z.\nProof.\n  intros x y z z_not_0.\n  field. assumption.\nQed.\n\nClose Scope Qc_scope.\n\n(** The real numbers are provided in the [Reals] library.  Here's that same\ntheorem again. *)\n\nModule RealExample.\n\n(** This code is in its own module for an annoying reason: [Reals] redefines its\nown [nil], which will interefere with the examples want to give further below in\nthis file with lists. *)\n\nRequire Import Reals.\nOpen Scope R_scope.\n\nTheorem frac_r : forall x y z, z <> 0 -> (x + y) / z = x / z + y /z.\nProof.\n  intros x y z z_not_0.\n  field. assumption.\nQed.\n\n(** The assumption that [z <> 0] was needed in the above theorems to avoid\ndivision by zero.  If we omitted that assumption, the [field] tactic would leave\nus with an unprovable subgoal, as in the proof below. *)\n\nTheorem frac_r_broken : forall x y z, (x + y) / z = x / z + y /z.\nProof.\n  intros x y z.\n  field.\nAbort.\n\nClose Scope R_scope.\nEnd RealExample.\n\n(**\n\n(**********************************************************************)\n\n** Induction principles\n\nWhen we studied the Curry-Howard correspondence, we learned that proofs\ncorrespond to programs.  That correspondence applies to inductive proofs\nas well, and as it turns out, inductive proofs correspond to recursive\nprograms.  Intuitively, that's because an inductive proof involves\nan inductive hypothesis---which is an instance of the theorem that\nis being proved, but applied to a smaller value.  Likewise, recursive\nprograms involve recursive calls---which are like another instance\nof the function that is already being evaluated, but on a smaller value.\n\nTo get a more concrete idea of what this means, let's look at the proof\nvalue (i.e., program) that Coq produces for our original inductive\nproof in these notes:\n*)\n\nCheck app_nil.\n\nPrint app_nil.\n\n(**\nCoq responds:\n<<\napp_nil =\nfun (A : Type) (lst : list A) =>\nlist_ind (fun lst0 : list A => lst0 ++ nil = lst0) eq_refl\n  (fun (h : A) (t : list A) (IH : t ++ nil = t) =>\n   eq_ind_r (fun l : list A => h :: l = h :: t) eq_refl IH) lst\n     : forall (A : Type) (lst : list A), lst ++ nil = lst\n>>\n\nThat's dense, but let's start picking it apart.  First, we see that [app_nil] is\na function that takes in two arguments: [A] and [lst].  Then it immediately\napplies another function named [list_ind].  That function was defined for us in\nthe standard library, and it's what \"implements\" induction on lists.  Let's\ncheck it out: *)\n\nCheck list_ind.\n\n(**\nCoq responds:\n<<\nlist_ind\n     : 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>>\n\nWe call [list_ind] the _induction principle_ for lists.  It is a proposition\nthat says, intuitively, that induction is a valid reasoning principle for lists.\nIn more detail, it takes these arguments:\n\n- [A], which is the type of the list elements.\n\n- [P], which is the property to be proved by induction.  For example,\n  the property being proved in [app_nil] is\n  [fun (lst: list A) => lst ++ nil = lst].\n\n- [P nil], which is a proof that [P] holds of the empty list.  In other words,\n  a proof of the base case.\n\n- A final argument of type [forall (a : A) (l : list A), P l -> P (a :: l)].\n  This is the proof of the inductive case.  It takes an argument [a],\n  which is the head of a list, [l], which is the tail of a list, and\n  a proof [P l] that [P] holds of [l].  So, [P l] is the inductive\n  hypothesis.  The output is of type [P (a :: l)], which is a proof\n  that [P] holds of [a::l].\n\nFinally, [list_ind] returns a value of type [forall l : list A, P l],\nwhich is a proof that [P] holds of all lists.\n\nOk, so that's the type of [list_ind]: a proposition asserting that\nif you have a proof of the base case, and a proof of the inductive\ncase, you can assemble those to prove that a property holds of a list.\nNext, what's the _value_ of [list_ind]?  In other words, what's the\nproof that [list_ind] itself is actually a true proposition?\n*)\n\nPrint list_ind.\n\n\n\n(**\nCoq responds:\n<<\nlist_ind = \nfun (A : Type) (P : list A -> Prop) (f : P [])\n  (f0 : forall (a : A) (l : list A), P l -> P (a :: l)) =>\nfix F (l : list A) : P l :=\n  match l as l0 return (P l0) with\n  | [] => f\n  | y :: l0 => f0 y l0 (F l0)\n  end\n     : forall (A : Type) (P : list A -> Prop),\n       P [] ->\n       (forall (a : A) (l : list A), P l -> P (a :: l)) ->\n       forall l : list A, P l\n...\n>>\n\nBefore we look at [list_ind]'s actual implementation, let's look at our own\nequivalent implementation that is easier to read: *)\n\nFixpoint my_list_ind\n  (A : Type)\n  (P : list A -> Prop)\n  (baseCase : P nil)\n  (inductiveCase : forall (h : A) (t : list A), P t -> P (h::t))\n  (lst : list A)\n  : P lst\n:=\n  match lst with\n  | nil => baseCase\n  | h::t => inductiveCase h t\n              (my_list_ind A P baseCase inductiveCase t)\n  end.\n\n(** The arguments to [my_list_ind] are the same as the arguments to [list_ind]:\nan element type, a property to be proved, a proof of the base case, and a proof\nof the inductive case.  Then [my_list_ind] takes an argument [lst], which is\nthe list for which we want to prove that [P] holds.  Finally, [my_list_ind]\nreturns that proof specifically for [lst].\n\nThe body of [my_list_ind] constructs the proof that [P] holds of [lst].\nIt does so by matching against [lst]:\n\n- If [lst] is empty, then [my_list_ind] returns the proof of the base case.\n\n- If [lst] is [h::t], then [my_list_ind] returns the proof of the inductive\n  case.  To construct that proof, it applies [inductiveCase] to [h] and [t] as\n  the head and tail.  But [inductiveCase] also requires a final argument, which\n  is the proof that [P] holds of [t].  To construct that proof, [my_list_ind]\n  calls itself recursively on [t].\n\nThat recursive call is exactly why we said that inductive proofs are recursive\nprograms.  The inductive proof needs evidence that the inductive hypothesis\nholds of the smaller list, and recursing on that smaller list produces the\nevidence.\n\nIt's not immediately obvious, but [my_list_ind] is almost just [fold_right].\nHere's how we could implement [fold_right] in Coq, with a slightly different\nargument order than the same function in OCaml: *)\n\nFixpoint my_fold_right\n  {A B : Type}\n  (init : B)\n  (f : A -> B -> B)\n  (lst : list A)\n:=\n  match lst with\n  | nil => init\n  | h::t => f h (my_fold_right init f t)\n  end.\n\n(** Now compare the body of [my_fold_right] with [my_list_rect]:\n\n<<\nmy_fold_right's body:\n\n  match lst with\n  | nil => init\n  | h::t => f h (my_fold_right init f t)\n  end.\n\nmy_list_ind's body:\n\n  match lst with\n  | nil => baseCase\n  | h::t => inductiveCase h t (my_list_ind A P baseCase inductiveCase t)\n  end.\n>>\n\nBoth match against [lst].  If [lst] is empty, both return an initial/base-case\nvalue.  If [lst] is non-empty, both recurse on the tail, then pass the result of\nthe recursive call to a function ([f] or [inductiveCase]) that combines that\nresult with the head.  The only essential difference is that [f] does not take\n[t] directly as an input, whereas [inductiveCase] does.\n\nSo there you have it:  induction over a list is really just folding over the\nlist, eventually reaching the empty list and returning the proof of the base\ncase for it, then working the way back up the call stack, assembling an\never-larger proof for each element of the list.  #<b>#An inductive proof is a\nrecursive program.#</b>#\n\nGoing back to the actual definition of [list_ind], here it is: *)\n\nPrint list_ind.\n\n(** Coq responds:\n<<\nlist_rect =\nfun (A : Type) (P : list A -> Type) (f : P nil)\n  (f0 : forall (a : A) (l : list A), P l -> P (a :: l)) =>\nfix F (l : list A) : P l :=\n  match l as l0 return (P l0) with\n  | nil => f\n  | y :: l0 => f0 y l0 (F l0)\n  end\n     : forall (A : Type) (P : list A -> Type),\n       P nil ->\n       (forall (a : A) (l : list A), P l -> P (a :: l)) ->\n       forall l : list A, P l\n>>\n\nThat uses different syntax, but it ends up defining the same function as\n[my_list_ind].\n\nWhenever you define an inductive type, Coq automatically generates the induction\nprinciple and recursive function that implements it for you. For example, we\ncould define our own lists: *)\n\nInductive mylist (A:Type) : Type :=\n| mynil : mylist A\n| mycons : A -> mylist A -> mylist A.\n\n(** Coq automatically generates [mylist_ind] for us: *)\n\nPrint mylist_ind.\n\n(**\n\n(**********************************************************************)\n\n** Extraction\n\nCoq makes it possible to _extract_ OCaml code (or Haskell or Scheme) from\nCoq code.  That makes it possible for us to\n\n- write Coq code,\n- prove the Coq code is correct, and\n- extract OCaml code that can be compiled and run more efficiently\n  than the original Coq code.\n\nLet's first prove that a tail recursive factorial is equivalent to the non-tail-recursive one, and then extract the code for the tail recursive factorial.\n\n*)\n\nFixpoint fact (n:nat) : nat :=\n  match n with\n  | 0 => 1\n  | S k => n * fact k\n  end.\n\nFixpoint fact_tail_rec' (n : nat) (acc: nat) : nat :=\n  match n with\n  | 0 => acc\n  | S k => fact_tail_rec' k (acc * n)\n  end.\n\nDefinition fact_tail_rec (n : nat) := fact_tail_rec' n 1.\n\n(**\n\nWe need to prove an intermediate lemma about [fact_tail_rec'] for the proof of our main theorem to go through.\n\n*)\n\nLemma fact_tail_rec_lem : forall n acc,\n  fact_tail_rec' n acc = acc * fact_tail_rec' n 1.\nProof.\n  intros n.\n  induction n.\n  - intro acc. simpl. ring.\n  - intro acc. simpl (fact_tail_rec' (S n) 1). rewrite IHn. \n    simpl. rewrite IHn. ring.\nQed.\n\n(**\n\nIn the above proof, the [simpl] tactic is applied with a specific pattern only on which simplification occurs. This is done so that the subsequent [rewrite] tactic does not pick the wrong term to rewrite. Try changing [simpl (fact_tail_rec' (S n) 1)] to [simpl] and make the proof go through.\n\n\nNow we are ready to prove our main theorem. The proof involves induction on the input and an application of the lemma [fact_tail_rec_lem] that we had proved.\n\n*)\n\nTheorem fact_tail_rec_ok : forall n, fact n = fact_tail_rec n.\nProof.\n  unfold fact_tail_rec.\n  induction n.\n  - simpl. trivial.\n  - simpl. rewrite fact_tail_rec_lem. rewrite <- IHn. ring.\nQed.\n\n(**\n\nLet's extract [fact_tail_rec] as an example.\n\n*)\n\nRequire Import Extraction.\nExtraction Language OCaml.\nExtraction \"/tmp/fact.ml\" fact_tail_rec.\n\n(**\n\nThat produces the following file:\n\n<<\n\ntype nat =\n| O\n| S of nat\n\n(** val add : nat -> nat -> nat **)\n\nlet rec add n m =\n  match n with\n  | O -> m\n  | S p -> S (add p m)\n\n(** val mul : nat -> nat -> nat **)\n\nlet rec mul n m =\n  match n with\n  | O -> O\n  | S p -> add m (mul p m)\n\n(** val fact_tail_rec' : nat -> nat -> nat **)\n\nlet rec fact_tail_rec' n acc =\n  match n with\n  | O -> acc\n  | S k -> fact_tail_rec' k (mul acc n)\n\n(** val fact_tail_rec : nat -> nat **)\n\nlet fact_tail_rec n =\n  fact_tail_rec' n (S O)\n\n>>\n\nAs you can see, Coq has preserved the [nat] type in this extracted\ncode.  Unforunately, computation on natural numbers is not efficient.\n(Addition requires linear time; multiplication, quadratic!)\n\nWe can direct Coq to extract its own [nat] type to OCaml's [int]\ntype as follows:\n\n*)\n\nExtract Inductive nat =>\n  int [ \"0\" \"succ\" ] \"(fun fO fS n -> if n=0 then fO () else fS (n-1))\".\nExtract Inlined Constant Init.Nat.mul => \"( * )\".\n\n(**\nThe first command says to\n\n- use [int] instead of [nat] in the extract code,\n- use [0] instead of [O] and [succ] instead of [S]\n  (the [succ] function is in [Pervasives] and is [fun x -> x + 1]), and\n- use the provided function to emulate pattern matching over the type.\n\nThe second command says to use OCaml's integer [( * )] operator instead of\nCoq's natural-number multiplication operator.\n\nAfter issuing those commands, the extraction looks cleaner:\n\n*)\n\nExtraction \"/tmp/fact.ml\" fact_tail_rec.\n\n(**\n<<\n\n(** val fact_tail_rec' : int -> int -> int **)\n\nlet rec fact_tail_rec' n acc =\n  (fun fO fS n -> if n=0 then fO () else fS (n-1))\n    (fun _ -> acc)\n    (fun k -> fact_tail_rec' k (( * ) acc n))\n    n\n\n(** val fact_tail_rec : int -> int **)\n\nlet fact_tail_rec n =\n  fact_tail_rec' n (succ 0)\n\n>>\n\nThere is, however, a tradeoff.  The original version we extracted worked\n(albeit inefficiently) for arbitrarily large numbers without any error.\nBut the second version is subject to integer overflow errors.  So the\nproofs of correctness that we did for [fact_tail_rec] are no longer completely\napplicable:  they hold only up to the limits of the types we subsituted\nduring extraction.\n\nDo we truly care about the limits of machine arithmetic?  Maybe, maybe not.\nFor sake of this little example, we might not.  If we were verifying\nsoftware to control the flight dynamics of a space shuttle, maybe we\nwould.  The Coq standard library does contain a module 31-bit\nintegers and operators on them, which we could use if we wanted to\nprecisely model what would happen on a particular architecture.\n\n*)\n\n(**\n\n(**********************************************************************)\n\n** Summary\n\nCoq excels as a proof assistant when it comes to proof by induction.  Whenever\nwe define an inductive type, Coq generates an induction principle for us\nautomatically.  That principle is really a recursive program that knows how to\nassemble evidence for a proposition, given the constructors of the inductive\ntype.  The [induction] tactic manages the proof for us, automatically figuring\nout what the base case and the inductive case, and automatically generating the\ninductive hypothesis.\n\n** Terms and concepts\n\n- append\n- base case\n- field\n- [fix]\n- [Fixpoint]\n- induction\n- induction principle\n- inductive case\n- inductive hypothesis\n- lemma\n- Peano natural numbers\n- [Prop] vs [bool]\n- ring\n- searching for library theorems\n- semi-ring\n- syntactically smaller restriction on recursive calls\n\n** Tactics\n\n- [field]\n- [induction]\n- [rewrite]\n- [ring]\n- tacticals: [try]\n\n** Further reading\n\n- _Software Foundations, Volume 1: Logical Foundations_.\n  #<a href=\"https://softwarefoundations.cis.upenn.edu/lf-current/toc.html\">\n  Chapter 2 through 4: Induction, Lists, Poly</a>#.\n\n- _Interactive Theorem Proving and Program Development_.\n  Chapters 6 through 10. Available\n  #<a href=\"https://newcatalog.library.cornell.edu/catalog/10131206\">\n  online from the Cornell library</a>#.\n\n*)", "meta": {"author": "kayceesrk", "repo": "cs6225_s20_iitm", "sha": "1cb2ad5a92ed9fadd0bc23218c159a762301ae0f", "save_path": "github-repos/coq/kayceesrk-cs6225_s20_iitm", "path": "github-repos/coq/kayceesrk-cs6225_s20_iitm/cs6225_s20_iitm-1cb2ad5a92ed9fadd0bc23218c159a762301ae0f/lectures/Induction_lecture.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.9196425234694067, "lm_q1q2_score": 0.686181146409722}}
{"text": "\nDefinition admit {T: Type} : T.  Admitted.\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\nCompute (next_weekday monday).\nCompute (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n    Proof. simpl. reflexivity. Qed.\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\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\nInfix \"&&\" := andb.\nInfix \"||\" := orb.\n\nExample test_orb: false || false || true = true.\n  Proof.\n    simpl.\n    reflexivity.\n  Qed.\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  negb (andb b1 b2).\n\nExample test_nandb1: (nandb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb2: (nandb false false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb3: (nandb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb4: (nandb true true) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  andb (andb b1 b2) b3.\n\nExample test_andb31:                 (andb3 true true true) = true.\n  Proof. simpl. reflexivity.  Qed. (* FILL IN HERE *) \nExample test_andb32:                 (andb3 false true true) = false.\n  Proof. simpl. reflexivity. Qed.    (* FILL IN HERE *) \nExample test_andb33:                 (andb3 true false true) = false.\n  Proof. simpl. reflexivity. Qed.      (* FILL IN HERE *) \nExample test_andb34:                 (andb3 true true false) = false.\n  Proof. simpl. reflexivity. Qed.   (* FILL IN HERE *) \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    | O => O\n    | S O => O\n    | S (S n') => n'\n  end.\n\nCompute (minustwo 4).\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\nModule Playground2.\n\nFixpoint plus (n:nat) (m:nat) : nat :=\n  match n with\n    | O => m\n    | S k => S (plus k 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\nFixpoint minus (n m : nat) : nat :=\n  match n,m with\n    | O, _ => O\n    | S _, O => S 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 => 1\n    | S k => mult base (exp base k)\n  end.\n\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.\n\nCheck ((0 + 1) + 1).\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n,m with\n    | O, O => true\n    | S n', O => false\n    | O, S m' => false\n    | S n', S m' => beq_nat 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\nDefinition blt_nat (n m :nat) : bool :=\n  leb n m && negb (beq_nat n m).\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\n  Proof. simpl. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\n  Proof. simpl. reflexivity. Qed.\n\nTheorem plus_O_N : forall n : nat, O + n = n.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. reflexivity. Qed.\n\nTheorem mult_0_l : forall n:nat, 0 * n = 0.\nProof.\n  intros n. reflexivity. Qed.\n\nTheorem mult_0_r : forall n:nat, n * 0 = 0.\nProof.\n  intros. induction n.\n  - reflexivity.\n  - simpl. rewrite IHn. reflexivity.\nQed.\n\n\nTheorem plus_n_O : forall n, n = n + 0.\nProof.\n  intros n. simpl. Abort.\n\nTheorem plus_id_example : forall n m:nat,\n  n = m -> n + m = 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_0_plus : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity. Qed.\n\nTheorem mult_S_1 : forall n m : nat,\n  m = S n -> m * (1 + n) = m * m.\nProof.\n  intros n m.\n  intros H1.\n  rewrite -> plus_1_l.\n  rewrite <- H1.\n  reflexivity.\nQed.\n\nTheorem plus_1_neq0 : forall n : nat,\n    beq_nat (n + 1) 0 = false.\nProof.\n  intros n. destruct n as [| n'].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem negb_involutive : forall b : bool,\n    negb (negb b) = b.\nProof.\n  intros b. destruct b.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_commutative : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\nQed.\n\nTheorem andb3_exchange :\n  forall b c d, andb (andb b c) d = andb (andb b d) c.\nProof.\n  intros b c d. destruct b.\n  - destruct c.\n    { destruct d.\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 andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros [] [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n    beq_nat 0 (n + 1) = false.\nProof.\n  intros [].\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.\n  Proof.\n    intros. rewrite -> H. rewrite -> H. reflexivity.\n  Qed.\n\nTheorem andb_eq_orb :\n  forall(b c : bool),\n    (andb b c = orb b c) ->\n    b = c.\nProof.\n  intros [] [].\n  - simpl. intros. reflexivity.\n  - simpl. intros. rewrite -> H. reflexivity.\n  - simpl. intros. rewrite -> H. reflexivity.\n  - simpl. intros. reflexivity.\nQed.\n\n\nInductive bin : Type :=\n| Z : bin\n| T : bin -> bin\n| I : bin -> bin.\n\nFixpoint incr (b:bin) : bin :=\n  match b with\n  | Z => I Z\n  | T b' => I b'\n  | I b' => T (incr b')\n  end.\n\nFixpoint bin_to_nat (b:bin) : nat :=\n  match b with\n  | Z => O\n  | T b' => 2 * bin_to_nat b'\n  | I b' => S (2 * bin_to_nat b')\n  end.\n\nExample test_bin_incr1 : bin_to_nat (incr Z) = S O.\nProof. reflexivity. Qed.\n\nExample test_bin_incr2 : bin_to_nat (incr (incr Z)) = S (S O).\nProof. reflexivity. Qed.\n\nExample test_bin_incr3 : bin_to_nat (incr (incr (incr Z))) = 3.\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr4 : bin_to_nat (incr (incr (incr (incr Z)))) = 4.\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr5 : bin_to_nat (incr (incr (incr (incr (incr Z))))) = 5.\nProof. reflexivity. Qed.\n\n\n\n\n\n\n\n\n\n\n ", "meta": {"author": "adamschoenemann", "repo": "pls_sf_exercises", "sha": "feefd3857e4a5d3fe4001a78262c3d805267a993", "save_path": "github-repos/coq/adamschoenemann-pls_sf_exercises", "path": "github-repos/coq/adamschoenemann-pls_sf_exercises/pls_sf_exercises-feefd3857e4a5d3fe4001a78262c3d805267a993/assignment_03/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.6861722368955756}}
{"text": "Require Import Coq.Init.Datatypes.\n\nDefinition isTrue (b:bool) := andb b true.\n\n(*\nThe assertion we've just made can be\nproved by observing that both sides\nof the equality evaluate to the same\nthing, after some simplification.*)\n\nExample testIsTrue: (\n   (isTrue true) = true\n). Proof. reflexivity. Qed.\n\nEval compute in (isTrue true).\nEval compute in (isTrue false).\nEval compute in (isTrue (negb false)).\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n    match (andb b1 b2) with\n    | true => false\n    | false => true\n    end.\n\nExample nanddb_tt: (\nnandb true true = false\n). Proof. reflexivity. Qed.\nExample nanddb_ff: (\nnandb false false = true\n). Proof. reflexivity. Qed.\nExample nanddb_ft: (\nnandb false true = true\n). Proof. reflexivity. Qed.\nExample nanddb_tf: (\nnandb true false = true\n). Proof. reflexivity. Qed.\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\nandb (andb b1 b2) b3.\n\nExample andb3_ttt: (andb3 true true true) = true.\nProof. reflexivity. Qed.\n", "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/booleans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6861722290924636}}
{"text": "Require Import Arith.\nRequire Import Omega.\n\n\nModule RecRel.\n\n(*\nWe model super general (univariate, single function) reccurence relations for now.\nWe'll make them more restrictive if the general definition turns out to be a hassle.\n\n*)\nInductive Expr :=\n| Var : Expr\n| T   : Expr -> Expr\n| Const : nat -> Expr\n| Sum : Expr -> Expr -> Expr\n| Mul : Expr -> Expr -> Expr\n| Div : Expr -> Expr -> Expr\n| Fun : (nat -> nat) -> Expr -> Expr                          \n.\n\nRecord Rel := { lhs : Expr; rhs : Expr }.\n\nPrint Rel.\n\nCoercion Const : nat >-> Expr.\n\nNotation \"e1 <+> e2\" := (Sum e1 e2)(at level 20).\nNotation \"e1 <*> e2\" := (Mul e1 e2)(at level 20).\nNotation \"e1 </> e2\" := (Div e1 e2)(at level 20).\nNotation \"f <@> e\"   := (Fun f e)(at level 19).\nNotation \"<n>\"       := Var.\n\nCheck (_/_).\nSearch (_/_).\n\nPrint Nat.div.\nPrint Nat.divmod.\nSearch Nat.divmod.\n\nFixpoint Interp (e : Expr) (f : nat -> nat) (n : nat) : nat :=\n  match e with\n      | <n> => n\n      | T e' => f (Interp e' f n)\n      | Const m => m\n      | e1 <+> e2 => (Interp e1 f n) + (Interp e2 f n)\n      | e1 <*> e2 => (Interp e1 f n) * (Interp e2 f n)\n      | e1 </> e2 => (Interp e1 f n) / (Interp e2 f n)\n      | g <@> e  => g (Interp e f n)\n  end.\n\nNotation \"[[ e ]]\" := (Interp e).\n\nDefinition ValRel (r : Rel) (f : nat -> nat) : Prop :=\n  forall n, [[ lhs r ]] f n = [[ rhs r ]] f n.\n\n\nNotation \"l :== r\" := (Build_Rel l r)(at level 30).\n\nOpaque Nat.div.\n\nLemma test_lemma : forall f, ValRel (T <n> :== T ((<n> <*> 2) </> 2)) f.\nProof.\n  unfold ValRel; intros; simpl Interp.\n  \n  assert (H := Nat.div_mul n 2).\n\n  rewrite H; auto.\nQed.\n\n\nLemma test2 : ValRel (T <n> :== 2 <*> (T (<n> </> 2))) (fun n => n).\nProof.\n  unfold ValRel; intros; simpl Interp.\nAbort.\n\n\n(*\nWe use the most straightforward definition here,\nwe'll amend it later if needed.\n*)\nDefinition O (f : nat -> nat) (g : nat -> nat) : Prop :=\n  exists n, exists C, forall M, n <= M -> g M <= C * (f M).\n\n(*This notation is the worst *)\nNotation \"g ∈O a\":= (O a g)(at level 10).\n\nLtac trivial_bounds := exists 0; exists 1.\n\nLtac o_of_n_bounds n C := exists n; exists C.\n\nLtac idk_bounds := eexists; eexists.\n\nLemma mul_le_r : forall n m k, k > 0 -> n <= m -> n <= m * k.\nProof.\n  intros n m.\n  induction k.\n  - omega.\n  -  rewrite Nat.mul_comm in *.\n     simpl.\n     intros.\n     auto with arith.\nQed.\n\nLemma mul_le_l : forall n m k, k > 0 -> n <= m -> n <= k * m.\nProof.\n  intros n m.\n  induction k.\n  - omega.\n  -  simpl.\n     intros.\n     auto with arith.\nQed.\n\nLtac fast_progress_le_goal := match goal with\n                         | [|- _ * _ <= _ * _] => apply mult_le_compat_l\n                         | [|- _ * _ <= _ * _] => apply mult_le_compat_r\n                         | [|- _ + _ <= _ + _] => apply plus_le_compat_l\n                         | [|- _ + _ <= _ + _] => apply plus_le_compat_r\n                         | [|- S _ <= S _]     => apply le_n_S\n                         | [|- ?X / _ < ?X]    => apply Nat.div_lt\n                         | [|- _ / ?X <= _ / ?X] => apply Nat.div_le_mono\n                         | [|- ?X * (?Y / ?X) <= ?Y] => apply Nat.mul_div_le\n                         | [|- _ ^ ?X <= _ ^ ?X] => apply Nat.pow_le_mono_l\n                         | [|- ?X ^ _ <= ?X ^ _] => apply Nat.pow_le_mono_r\n                         | [|- _ <= _ * _]     => apply mul_le_r; now auto with arith\n                         | [|- _ <= _ * _]     => apply mul_le_l; now auto with arith\n                         end; auto with arith.\n\n\nLtac progress_le_goal := try\n                           (match goal with\n                            | [_ : ((Nat.max ?X _) <= _) |- ?X <= _ ] => eapply Nat.max_lub_l; eauto with arith\n                            | [_ : ((Nat.max _ ?X) <= _) |- ?X <= _ ] => eapply Nat.max_lub_r; eauto with arith\n                            end); fast_progress_le_goal.\n\n\nLemma n_O_of_n_squared : (fun n => n) ∈O (fun n => n * n).\nProof.\n  trivial_bounds.\n  intros M l.\n  simpl.\n  replace (M * M + 0) with (M*M) by auto.\n  induction M; auto.\n  simpl.\n  now progress_le_goal.\nQed.\n\n\nTheorem O_refl : forall f, f ∈O f.\nProof.\n  trivial_bounds.\n  intros; simpl; auto with arith.\nQed.\n\nTheorem O_trans : forall f g h, f ∈O g -> g ∈O h -> f ∈O h.\nProof.\n  intros f g h (M1, (C1, H1)) (M2, (C2, H2)).\n  o_of_n_bounds (Nat.max M1 M2) (C1 * C2).\n  intros M lt.\n  assert (f M <= C1 * g M).\n  - apply H1.\n    now progress_le_goal.\n\n  - assert (g M <= C2 * h M).\n    apply H2.\n    now progress_le_goal.\n    assert (C1 * g M <= C1 * (C2 * h M)) by auto with arith.\n    eapply le_trans.\n    * exact H.\n    * Search (_*_*_).\n      rewrite <- mult_assoc; now auto with arith.\nQed.\n\nTheorem O_add_idempot : forall f g h, f ∈O (fun n => g n + h n) -> h ∈O g -> f ∈O g.\nProof.\n  intros f g h (M1, (C1, H1)) (M2, (C2, H2)).\n  o_of_n_bounds (Nat.max M1 M2) (C1 + C1*C2).\n  intros M max_rel.\n  SearchAbout ((_ + _)*_).\n  rewrite Nat.mul_add_distr_r.\n  Check mult_assoc_reverse.\n  rewrite <- mult_assoc.\n  apply (Nat.le_trans _ (C1 * g M + C1 * h M)).\n  - rewrite <- Nat.mul_add_distr_l.\n    apply H1.\n    now progress_le_goal.\n  - repeat fast_progress_le_goal.\n    apply H2.\n    progress_le_goal.\nQed.\n\n\nDefinition monotone f := forall n m, n <= m -> f n <= f m.\n\nDefinition non_zero f := exists k:nat, f k > 0.\n\nTheorem O_mul_hyp : forall f g C, f ∈O (fun k => C * g k) -> f ∈O g.\nProof.\n  intros f g C (M, (C', H)).\n  o_of_n_bounds M (C' * C).\n  intros M0 leq.\n  rewrite <- Nat.mul_assoc.\n  apply H; auto.\nQed.\n\nTheorem O_mul_conc : forall f g C, C > 0 -> f ∈O g -> f ∈O (fun k => C * g k).\nProof.\n  intros f g C nz (M, (C', H)).\n  o_of_n_bounds M C'.\n  intros; apply (Nat.le_trans _ (C' * g M0)); auto.\n  repeat fast_progress_le_goal.\nQed.\n\nTheorem O_mul_src : forall f g C, f ∈O g -> (fun k => C * f k) ∈O g.\nProof.\n  intros f g C (M, (C', H)).\n  o_of_n_bounds M (C * C').\n  intros M0 leq.\n  rewrite <- Nat.mul_assoc.\n  fast_progress_le_goal.\nQed.\n\n\nTheorem O_const_plus : forall f g h C, h ∈O g -> f ∈O (fun k => g k + C * h k) -> f ∈O g.\nProof.\n  intros f g h C o_h_g o_f_sum.\n  eapply O_add_idempot.\n  apply o_f_sum.\n  apply O_mul_src; auto.\nQed.\n\nTheorem O_const : forall f n, monotone f -> non_zero f -> (fun _ => n) ∈O f.\nProof.\n  intros f n mon non_zero.\n  destruct non_zero as (k, k_n_z).\n  o_of_n_bounds k (n * f k).\n  intros M le_k.\n  apply (Nat.le_trans _ (n * f k * f k)).\n  repeat (apply mul_le_r; auto).\n  fast_progress_le_goal.\nQed.\n\nTheorem O_const_add_r : forall f g n, f ∈O g -> f ∈O (fun k => g k + n).\nProof.\n  intros f g n (M, (C, H)).\n  o_of_n_bounds M C.\n  intros M0 leq.\n  rewrite Nat.mul_add_distr_l.\n  auto with arith.\nQed.\n  \n(* Untrue!! *)\nTheorem O_const_add_l : forall f g n, f ∈O (fun k => g k + n) -> f ∈O g.\nAbort.\n\n\nTheorem O_const_add_l : forall f g n, monotone g -> non_zero g -> f ∈O (fun k => g k + n) -> f ∈O g.\nProof.\n  intros f g n mon non_zero o_g_const.\n  eapply O_add_idempot.\n  apply o_g_const.\n  apply O_const; auto.\nQed.\n\n\nSearchAbout (_ * (_ / _) <= _).\n\n\nTheorem O_id : forall f, ValRel (T <n> :== 2 <*> (T (<n> </> 2))) f ->\n                         f ∈O (fun n => n).\nProof.\n  Opaque Nat.mul.\n  unfold ValRel; simpl.\n  intros f eqn.\n  o_of_n_bounds 1 (f 1).\n  intros M geq; simpl.\n  (* we need strong induction here *)\n  induction M as (M,IH) using lt_wf_ind.\n  case_eq M.\n  - omega.\n  - intros n eqM.\n    case_eq n.\n    * intros; omega.\n    * intros m eq_m; assert (H1 := eqn M); clear eqn.\n      assert (H2 : 1 < M).\n      + subst n; rewrite eqM; auto with arith.\n      + subst n; rewrite <- eqM.\n        assert (H3: f (M / 2) <= f 1 * (M / 2)).\n        apply IH.\n        fast_progress_le_goal.\n        apply (Nat.le_trans _ (2/2)); auto with arith.\n        fast_progress_le_goal.\n\n        rewrite H1.\n        apply (Nat.le_trans _ (2 * (f 1 * (M/2)))).\n        now auto with arith.\n\n        replace (2 * (f 1 * (M / 2))) with (f 1 * (2 * (M/2))) by ring.\n        repeat fast_progress_le_goal.\nQed.\n\n\nTheorem O_pow : forall n m, n <= m -> (fun k => k^n) ∈O (fun k => k^m).\nProof.\n  intros n m leq.\n  o_of_n_bounds 1 1.\n  intros M M_bound.\n  replace (1 * M ^ m) with (M ^ m) by auto with arith.\n  fast_progress_le_goal.\n  omega.\nQed.\n\nPrint Nat.log2.\nPrint Nat.log2_iter.\n\nSearchAbout (_^_).\nSearchAbout Nat.log2_up.\nPrint Nat.log2_up.\n\nPrint Nat.log2_up.\n\nRequire Import FunInd.\n\nFunctional Scheme log2_up_ind := Induction for Nat.log2_up Sort Prop.\n\nCheck log2_up_ind.\n\n\nSearchAbout (_^(Nat.log2_up _)).\n\nLemma exp_log2_up : forall a, 0 < a -> a <= 2 ^ Nat.log2_up a.\nProof.\n  intros; apply Nat.log2_log2_up_spec; auto.\nQed.\n\nSearchAbout ((_^_)*(_^_)).\nCheck Nat.pow_mul_l.\n\nSearchAbout (_^_ <= _^_).\nCheck Nat.pow_le_mono_l.\n\nSearchAbout (_*_ <= _*_).\nCheck Nat.mul_le_mono_r.\n\nSearchAbout (_*(_/_)).\nCheck Nat.mul_div_le.\n\n\nLemma log_2_div : forall a b, 0 < a ->\n                              a * (b/2)^(Nat.log2_up a) <= b^(Nat.log2_up a).\nProof.\n  intros a b a_nz.\n  etransitivity.\n  eapply Nat.mul_le_mono_r.\n  apply exp_log2_up; auto.\n  rewrite <- Nat.pow_mul_l.\n  apply Nat.pow_le_mono_l.\n  apply Nat.mul_div_le; auto.\nQed.\n\nAxiom I_GIVE_UP : forall {P}, P.\n\n\nLemma baby_master_theorem_1 : forall g f a n,\n    n < Nat.log2 a ->\n    ValRel (T <n> :== a <*> (T (<n> </> 2)) <+> (g <@> <n>)) f\n    -> g ∈O (fun k => k ^ n)\n    -> f ∈O (fun k => k ^ (Nat.log2_up a)).\nProof.\n  intros g f a n crit f_eqn g_o_n.\n  (* idk_bounds ?[n] ?[C]. *)\n  eexists ?[n].\n  eexists ?[C].\n  induction M as (M, IH) using lt_wf_ind.\n  intro M_large_enough.\n  unfold ValRel in f_eqn; simpl in f_eqn.\n  rewrite f_eqn.\n  specialize IH with (m:= M/2).\n  eapply (Nat.le_trans _ (a * (?C * (M / 2) ^ Nat.log2_up a) + g M)).\n\n\n  -  repeat fast_progress_le_goal.\n     apply IH.\n     apply I_GIVE_UP.\n     apply I_GIVE_UP.\n  - Check log_2_div.\n    apply log_2_div.\n  \n  (* Focus 2. *)\n  (* SearchAbout (_ ^ (Nat.log2_up _)). *)\n  (* induction a; simpl. *)\n    \n  (* - fast_progress_le_goal. *)\n  (*   repeat fast_progress_le_goal. *)\n  (*   apply IH. *)\n  (*   * SearchAbout (_ / _ < _). *)\n  (*     apply Nat.div_lt_upper_bound; auto with arith. *)\n      \n\n  (* assert (H : (f (M/2) <= ?C * (M/2) ^ Nat.log2_up a)). *)\n  \nAdmitted.\n\nVariable log : nat -> nat -> nat.\n\nVariable log_up : nat -> nat -> nat.\n\n(* To express this, we need a log_b a function and a log_b_up one! *)\nTheorem master_theorem_1 : forall g f a b n,\n    n < log b a ->\n    ValRel (T <n> :== a <*> (T (<n> </> b)) <+> (g <@> <n>)) f\n    -> g ∈O (fun k => k ^ n)\n    -> f ∈O (fun k => k ^ (log_up b a)).\nProof.\nAdmitted.\n", "meta": {"author": "codyroux", "repo": "master_theorem", "sha": "dc1ad1a80e7626fac114302435abf283a032ac88", "save_path": "github-repos/coq/codyroux-master_theorem", "path": "github-repos/coq/codyroux-master_theorem/master_theorem-dc1ad1a80e7626fac114302435abf283a032ac88/rec_rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236824, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.686172228286146}}
{"text": "(* Exercise 12 *) \n\nRequire Import BenB.\n\nDefinition D := R.\nVariables P Q S T : D -> Prop.\nVariable RR : D -> D -> Prop.\n\nTheorem exercise_012 : \n  (forall x : D, (exists y : D, exists z:D, RR (y+z) x) -> P x) \n-> \n    (exists x : D, exists y : D, RR (x+y) y) \n  -> \n    (exists x : D, P (x+7)).\nProof.\nimp_i a1.\nimp_i a2.\nexi_e (exists x:D, exists y:D, RR (x + y) y) a a3.\nhyp a2.\nexi_e (exists y:D, RR (a + y) y) b a4.\nhyp a3.\nexi_i (b-7).\nreplace (b-7+7) with b.\nimp_e (exists y : D, exists z : D, RR (y + z) b).\nall_e (forall x : D, (exists y : D, exists z : D, RR (y + z) x) -> P x) b.\nhyp a1.\nexi_i a.\nexi_i b.\nhyp a4.\nlin_solve.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_real012.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6861217446887096}}
{"text": "(**\nHere we define the category of rings using the mechanism of algebras.\nNote: rings are commutative and always have `0` and `1`.\n *)\nRequire Import prelude.all.\nRequire Import syntax.hit_signature.\nRequire Import algebras.set_algebra.\n\nOpen Scope cat.\n\n(** We first define the signature. *)\n\n(** Operations *)\nDefinition ring_operations\n  : poly_code\n  := (I * I) (* plus *)\n     + (I * I) (* mult *)\n     + I (* minus *) \n     + C unitset (* zero *)\n     + C unitset (* one *).\n\n(** Labels of group axioms *)\nInductive ring_ax :=\n| p_assoc : ring_ax\n| p_unit : ring_ax\n| p_inv : ring_ax\n| p_com : ring_ax\n| m_assoc : ring_ax\n| m_unit : ring_ax\n| m_com : ring_ax\n| distr : ring_ax.\n\n(** Arguments for each label *)\nDefinition ring_arg\n  : ring_ax → poly_code\n  := fun j =>\n       match j with\n       | p_assoc => I * I * I \n       | p_unit => I\n       | p_inv => I\n       | p_com => I * I\n       | m_assoc => I * I * I\n       | m_unit => I\n       | m_com => I * I\n       | distr => I * I * I\n       end.\n\n(** Some convenient notation for the constructor terms. These represent the operations *)\nDefinition plus\n           {P : poly_code}\n           (e₁ e₂ : endpoint ring_operations P I)\n  : endpoint ring_operations P I.\nProof.\n  refine (comp _ constr).\n  refine (comp _ (ι₁ _ _)).\n  refine (comp _ (ι₁ _ _)).\n  refine (comp _ (ι₁ _ _)).\n  refine (comp _ (ι₁ _ _)).\n  exact (pair e₁ e₂).\nDefined.\n\nDefinition mult\n           {P : poly_code}\n           (e₁ e₂ : endpoint ring_operations P I)\n  : endpoint ring_operations P I.\nProof.\n  refine (comp _ constr).\n  refine (comp _ (ι₁ _ _)).\n  refine (comp _ (ι₁ _ _)).\n  refine (comp _ (ι₁ _ _)).\n  refine (comp _ (ι₂ _ _)).  \n  exact (pair e₁ e₂).\nDefined.\n\nDefinition minus\n           {P : poly_code}\n           (e : endpoint ring_operations P I)\n  : endpoint ring_operations P I.\nProof.\n  refine (comp _ constr).\n  refine (comp _ (ι₁ _ _)).\n  refine (comp _ (ι₁ _ _)).\n  refine (comp _ (ι₂ _ _)).\n  exact e.\nDefined.\n\nDefinition zero_el\n           {P : poly_code}\n  : endpoint ring_operations P I.\nProof.\n  refine (comp _ constr).\n  refine (comp _ (ι₁ _ _)).\n  refine (comp _ (ι₂ _ _)).\n  apply c.\n  exact tt.\nDefined.\n\nDefinition one_el\n           {P : poly_code}\n  : endpoint ring_operations P I.\nProof.\n  refine (comp _ constr).\n  refine (comp _ (ι₂ _ _)).\n  apply c.\n  exact tt.\nDefined.\n\n(** The left hand side of each equation *)\nDefinition ring_lhs\n  : ∏ (j : ring_ax), endpoint ring_operations (ring_arg j) I.\nProof.\n  induction j ; cbn.\n  - refine (plus (plus _ _) _). (* plus assoc *)\n    + exact (comp (π₁ _ _) (π₁ _ _)).\n    + exact (comp (π₁ _ _) (π₂ _ _)).\n    + exact (π₂ _ _).\n  - refine (plus _ _). (* plus zero *)\n    + apply zero_el.\n    + apply id_e.\n  - refine (plus _ _). (* plus minus *)\n    + apply minus.\n      apply id_e.\n    + apply id_e.\n  - refine (plus _ _). (* plus com *)\n    + exact (π₁ _ _).\n    + exact (π₂ _ _).\n  - refine (mult (mult _ _) _). (* mult assoc *)\n    + exact (comp (π₁ _ _) (π₁ _ _)).\n    + exact (comp (π₁ _ _) (π₂ _ _)).\n    + exact (π₂ _ _).\n  - refine (mult _ _). (* mult one *)\n    + apply one_el.\n    + apply id_e.\n  - refine (mult _ _). (* mult com *)\n    + exact (π₁ _ _).\n    + exact (π₂ _ _).\n  - refine (mult _ _). (* distr *)\n    + refine (comp _ _).\n      * exact (π₁ _ _).\n      * exact (π₁ _ _).\n    + refine (plus _ _).\n      * refine (comp _ _).\n        ** exact (π₁ _ _).\n        ** exact (π₂ _ _).\n      * exact (π₂ _ _).\nDefined.\n\n(** The right hand side of each equation *)\nDefinition ring_rhs\n  : ∏ (j : ring_ax), endpoint ring_operations (ring_arg j) I.\nProof.\n  induction j ; cbn.\n  - refine (plus _ (plus _ _)). (* plus assoc *)\n    + exact (comp (π₁ _ _) (π₁ _ _)).\n    + exact (comp (π₁ _ _) (π₂ _ _)).\n    + exact (π₂ _ _).\n  - apply id_e. (* plus zero *)\n  - apply zero_el. (* plus minus *)\n  - refine (plus _ _). (* plus com *)\n    + exact (π₂ _ _).\n    + exact (π₁ _ _).\n  - refine (mult _ (mult _ _)). (* mult assoc *)\n    + exact (comp (π₁ _ _) (π₁ _ _)).\n    + exact (comp (π₁ _ _) (π₂ _ _)).\n    + exact (π₂ _ _).\n  - apply id_e. (* mult one *)\n  - refine (mult _ _). (* mult com *)\n    + exact (π₂ _ _).\n    + exact (π₁ _ _).\n  - refine (plus _ _). (* distr *)\n    + refine (mult _ _).\n      * refine (comp _ _).\n        ** exact (π₁ _ _).\n        ** exact (π₁ _ _).\n      * refine (comp _ _).\n        ** exact (π₁ _ _).\n        ** exact (π₂ _ _).\n    + refine (mult _ _).\n      * refine (comp _ _).\n        ** exact (π₁ _ _).\n        ** exact (π₁ _ _).\n      * exact (π₂ _ _).\nDefined.\n\n(** The signature of ring as a HIT signature *)\nDefinition ring_signature\n  : hit_signature.\nProof.\n  use tpair.\n  - exact ring_operations.\n  - use tpair.\n    + exact ring_ax.\n    + use tpair.\n      * exact ring_arg.\n      * split.\n        ** exact ring_lhs.\n        ** exact ring_rhs.\nDefined.\n\n(** The interpretation of ring in set *)\nDefinition ring_cat\n  : univalent_category\n  := set_algebra ring_signature.\n\n(** Projections of a ring *)\nSection RingProjections.\n  Variable (R : ring_cat).\n\n  Definition ring_carrier : hSet\n    := pr11 R.\n\n  Definition ring_plus\n    : ring_carrier → ring_carrier → ring_carrier\n    := λ x₁ x₂, pr21 R (inl (inl (inl (inl (x₁ ,, x₂))))).\n\n  Local Notation \"x₁ + x₂\" := (ring_plus x₁ x₂).\n\n  Definition ring_mult\n    : ring_carrier → ring_carrier → ring_carrier\n    := λ x₁ x₂, pr21 R (inl (inl (inl (inr (x₁ ,, x₂))))).\n\n  Local Notation \"x₁ * x₂\" := (ring_mult x₁ x₂).\n\n  Definition ring_minus\n    : ring_carrier → ring_carrier\n    := λ x, pr21 R (inl (inl (inr x))).\n\n  Local Notation \"- x\" := (ring_minus x).\n\n  Definition ring_zero\n    : ring_carrier\n    := pr21 R (inl (inr tt)).\n\n  Local Notation \"'0'\" := ring_zero.\n\n  Definition ring_one\n    : ring_carrier\n    := pr21 R (inr tt).\n\n  Local Notation \"'1'\" := ring_one.\n\n  Definition ring_plus_assoc\n    : ∏ (x₁ x₂ x₃ : ring_carrier), (x₁ + x₂) + x₃ = x₁ + (x₂ + x₃)\n    := λ x₁ x₂ x₃, pr2 R p_assoc ((x₁ ,, x₂) ,, x₃).\n\n  Definition ring_zero_plus\n    : ∏ (x : ring_carrier), 0 + x = x\n    := λ x, pr2 R p_unit x.\n\n  Definition ring_min_plus\n    : ∏ (x : ring_carrier), (- x) + x = 0\n    := λ x, pr2 R p_inv x.\n\n  Definition ring_plus_com\n    : ∏ (x y : ring_carrier), x + y = y + x\n    := λ x y, pr2 R p_com (x ,, y).\n\n  Definition ring_plus_zero\n    : ∏ (x : ring_carrier), x + 0 = x\n    := λ x, ring_plus_com x 0 @ ring_zero_plus x.\n\n  Definition ring_plus_min\n    : ∏ (x : ring_carrier), x + (- x) = 0\n    := λ x, ring_plus_com x (- x) @ ring_min_plus x.\n\n  Definition ring_mult_assoc\n    : ∏ (x₁ x₂ x₃ : ring_carrier), (x₁ * x₂) * x₃ = x₁ * (x₂ * x₃)\n    := λ x₁ x₂ x₃, pr2 R m_assoc ((x₁ ,, x₂) ,, x₃).\n\n  Definition ring_one_mult\n    : ∏ (x : ring_carrier), 1 * x = x\n    := λ x, pr2 R m_unit x.\n\n  Definition ring_mult_com\n    : ∏ (x y : ring_carrier), x * y = y * x\n    := λ x y, pr2 R m_com (x ,, y).\n\n  Definition ring_mult_one\n    : ∏ (x : ring_carrier), x * 1 = x\n    := λ x, ring_mult_com x 1 @ ring_one_mult x.\n\n  Definition ring_left_distr\n    : ∏ (x₁ x₂ x₃ : ring_carrier), x₁ * (x₂ + x₃) = (x₁ * x₂) + (x₁ * x₃)\n    := λ x₁ x₂ x₃, pr2 R distr ((x₁ ,, x₂) ,, x₃).\n\n  Definition ring_right_distr\n    : ∏ (x₁ x₂ x₃ : ring_carrier), (x₂ + x₃) * x₁ = (x₂ * x₁) + (x₃ * x₁).\n  Proof.\n    intros x₁ x₂ x₃.\n    rewrite ring_mult_com.\n    rewrite ring_left_distr.\n    rewrite !(ring_mult_com _ x₁).\n    reflexivity.\n  Qed.\nEnd RingProjections.\n\n(** Builder for rings *)\nDefinition mk_ring\n           (R : hSet)\n           (plus : R → R → R)\n           (mult : R → R → R)\n           (min : R → R)\n           (z : R)\n           (o : R)\n           (plus_assoc : ∏ (x₁ x₂ x₃ : R),\n                         plus (plus x₁ x₂) x₃ = plus x₁ (plus x₂ x₃))\n           (zero_plus : ∏ (x : R), plus z x = x)\n           (plus_min : ∏ (x : R), plus (min x) x = z)\n           (plus_com : ∏ (x y : R), plus x y = plus y x)\n           (mult_assoc : ∏ (x₁ x₂ x₃ : R),\n                         mult (mult x₁ x₂) x₃ = mult x₁ (mult x₂ x₃))\n           (mult_one : ∏ (x : R), mult o x = x)\n           (mult_com : ∏ (x y : R), mult x y = mult y x)\n           (distr : ∏ (x y z : R), mult x (plus y z) = plus (mult x y) (mult x z))\n  : ring_cat.\nProof.\n  simple refine ((R ,, _) ,, _).\n  - cbn.\n    intros x.\n    induction x as [x | x].\n    + induction x as [x | x].\n      * induction x as [x | x].\n        ** induction x as [x | x].\n           *** exact (plus (pr1 x) (pr2 x)).\n           *** exact (mult (pr1 x) (pr2 x)).\n        ** exact (min x).\n      * exact z.\n    +  exact o.\n  - intros j.\n    induction j.\n    + exact (λ x, plus_assoc (pr11 x) (pr21 x) (pr2 x)).\n    + exact zero_plus.\n    + exact plus_min.\n    + exact (λ x, plus_com (pr1 x) (pr2 x)).\n    + exact (λ x, mult_assoc (pr11 x) (pr21 x) (pr2 x)).\n    + exact mult_one.\n    + exact (λ x, mult_com (pr1 x) (pr2 x)).\n    + exact (λ x, distr (pr11 x) (pr21 x) (pr2 x)).\nDefined.\n\n(** Some laws for rings *)\nSection Laws.\n  Context {Ring : ring_cat}.\n\n  Local Notation \"'R'\" := (alg_carrier Ring).\n  Local Notation \"x + y\" := (ring_plus Ring x y).\n  Local Notation \"x * y\" := (ring_mult Ring x y).\n  Local Notation \"- x\" := (ring_minus Ring x).\n  Local Notation \"'0'\" := (ring_zero Ring).\n  Local Notation \"'1'\" := (ring_one Ring).\n\n  Definition ring_cancel_plus_left\n    : ∏ {x y : R} (z : R), z + x = z + y → x = y.\n  Proof.\n    intros x y z H.\n    refine (_ @ maponpaths (λ r, (- z) + r) H @ _).\n    - rewrite <- ring_plus_assoc.\n      rewrite ring_min_plus.\n      rewrite ring_zero_plus.\n      reflexivity.\n    - rewrite <- ring_plus_assoc.\n      rewrite ring_min_plus.\n      rewrite ring_zero_plus.\n      reflexivity.\n  Qed.\n\n  Definition ring_cancel_plus_right\n    : ∏ {x y : R} ( z : R), x + z = y + z → x = y.\n  Proof.\n    intros x y z H.\n    refine (_ @ maponpaths (λ r, r + (- z)) H @ _).\n    - rewrite ring_plus_assoc.\n      rewrite ring_plus_min.\n      rewrite ring_plus_zero.\n      reflexivity.\n    - rewrite ring_plus_assoc.\n      rewrite ring_plus_min.\n      rewrite ring_plus_zero.\n      reflexivity.\n  Qed.      \n\n  Definition ring_minus_eq\n    : ∏ (x y : R), x + y = 0 → x = - y.\n  Proof.\n    intros x y H.\n    apply (ring_cancel_plus_right y).\n    rewrite H.\n    rewrite ring_min_plus.\n    reflexivity.\n  Qed.\n\n  Definition ring_inverse_unique'\n    : ∏ (x : R) {y z : R}, x + y = 0 → x + z = 0 → y = z.\n  Proof.\n    intros x y z H₁ H₂.\n    apply (ring_cancel_plus_left x).\n    exact (H₁ @ !H₂).\n  Qed.\n\n  Definition ring_inverse_unique\n    : ∏ {x y : R}, x + y = 0 → -x = y.\n  Proof.\n    intros x y H.\n    symmetry.\n    apply (ring_inverse_unique' x).\n    - exact H.\n    - apply ring_plus_min.\n  Qed.\n\n  Definition ring_mult_zero\n    : ∏ (x : R), x * 0 = 0.\n  Proof.\n    intro x.\n    apply (ring_cancel_plus_right (x * 0)).\n    rewrite ring_zero_plus.\n    rewrite <- ring_left_distr.\n    rewrite ring_zero_plus.\n    reflexivity.\n  Qed.\n  \n  Definition ring_zero_mult\n    : ∏ (x : R), 0 * x = 0.\n  Proof.\n    intro x.\n    rewrite ring_mult_com.\n    apply ring_mult_zero.\n  Qed.\n  \n  Definition ring_mult_minus\n    : ∏ (x y : R), x * (- y) = -(x * y).\n  Proof.\n    intros x y.\n    apply (ring_inverse_unique' (x * y)).\n    - rewrite <- ring_left_distr.\n      rewrite ring_plus_min.\n      apply ring_mult_zero.\n    - apply ring_plus_min.\n  Qed.\n\n  Definition ring_minus_zero\n    : - 0 = 0.\n  Proof.\n    apply ring_inverse_unique.\n    apply ring_plus_zero.\n  Qed.\n\n  Definition ring_minus_minus\n    : ∏ (x : R), -(- x) = x.\n  Proof.\n    intro x.\n    apply ring_inverse_unique.\n    apply ring_min_plus.\n  Qed.\n\n  Definition ring_inv_plus\n    : ∏ (x y : R), -(x + y) = (-x) + (-y).\n  Proof.\n    intros x y.\n    apply ring_inverse_unique.\n    rewrite (ring_plus_com _ x y).\n    rewrite ring_plus_assoc.\n    refine (_ @ _).\n    {\n      apply maponpaths.\n      rewrite <- ring_plus_assoc.\n      rewrite ring_plus_min.\n      apply ring_zero_plus.\n    }\n    apply ring_plus_min.\n  Qed.    \nEnd Laws.\n\n(** Builder for ring homomorphisms *)\nSection BuildRingMap.\n  Context {R₁ R₂ : ring_cat}.\n  Variable (f : alg_carrier R₁ → alg_carrier R₂)\n           (f_p : ∏ (x₁ x₂ : alg_carrier R₁),\n                  f (ring_plus R₁ x₁ x₂)\n                  =\n                  ring_plus R₂ (f x₁) (f x₂))\n           (f_m : ∏ (x₁ x₂ : alg_carrier R₁),\n                  f (ring_mult R₁ x₁ x₂)\n                  =\n                  ring_mult R₂ (f x₁) (f x₂))\n           (f_o : f (ring_one R₁) = ring_one R₂).\n\n  Local Definition f_z\n    : f (ring_zero R₁) = ring_zero R₂.\n  Proof.\n    apply (ring_cancel_plus_right (f (ring_zero R₁))).\n    rewrite ring_zero_plus.\n    rewrite <- f_p.\n    exact (maponpaths f (ring_plus_zero _ _)).\n  Qed.\n\n  Local Definition f_minus\n    : ∏ (x : alg_carrier R₁), f (ring_minus R₁ x) = ring_minus R₂ (f x).\n  Proof.\n    intro x.\n    apply ring_minus_eq.\n    rewrite <- f_p.\n    refine (_ @ f_z).\n    apply maponpaths.\n    apply ring_min_plus.\n  Qed.\n\n  Definition mk_ring_map\n    : R₁ --> R₂.\n  Proof.\n    use make_algebra_map.\n    - exact f.\n    - intros x.\n      induction x as [x | x].\n      + induction x as [x | x].\n        * induction x as [x | x].\n          ** induction x as [x | x].\n             *** apply f_p.\n             *** apply f_m.\n          ** exact (f_minus x).\n        * induction x.\n          exact f_z.\n      + induction x.\n        exact f_o.\n  Defined.\nEnd BuildRingMap.\n\n(** Laws of ring homomorphism *)\nSection RingMapProjections.\n  Context {R₁ R₂ : ring_cat}.\n  Variable (f : R₁ --> R₂).\n\n  Definition ring_map_plus\n    : ∏ (x y : alg_carrier R₁),\n      alg_map_carrier f (ring_plus R₁ x y)\n      =\n      ring_plus R₂ (alg_map_carrier f x) (alg_map_carrier f y)\n    := λ x y, eqtohomot (pr21 f) (inl (inl (inl (inl (x ,, y))))).\n\n  Definition ring_map_mult\n    : ∏ (x y : alg_carrier R₁),\n      alg_map_carrier f (ring_mult R₁ x y)\n      =\n      ring_mult R₂ (alg_map_carrier f x) (alg_map_carrier f y)\n    := λ x y, eqtohomot (pr21 f) (inl (inl (inl (inr (x ,, y))))).\n\n  Definition ring_map_minus\n    : ∏ (x : alg_carrier R₁),\n      alg_map_carrier f (ring_minus R₁ x)\n      =\n      ring_minus R₂ (alg_map_carrier f x)\n    := λ x, eqtohomot (pr21 f) (inl (inl (inr x))).\n\n  Definition ring_map_zero\n    : alg_map_carrier f (ring_zero R₁)\n      =\n      ring_zero R₂\n    := eqtohomot (pr21 f) (inl (inr tt)).\n\n  Definition ring_map_one\n    : alg_map_carrier f (ring_one R₁)\n      =\n      ring_one R₂\n    := eqtohomot (pr21 f) (inr tt).\nEnd RingMapProjections.\n", "meta": {"author": "UniMath", "repo": "SetHITs", "sha": "512f3c76926f458a130786891c2e325e66afeb21", "save_path": "github-repos/coq/UniMath-SetHITs", "path": "github-repos/coq/UniMath-SetHITs/SetHITs-512f3c76926f458a130786891c2e325e66afeb21/code/examples/rings.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6860465610527043}}
{"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(* non commutative rings *)\n\nRequire Import Setoid.\nRequire Import BinPos.\nRequire Import BinNat.\nRequire Export Morphisms Setoid Bool.\nRequire Export Algebra_syntax.\n\nSet Implicit Arguments.\n\nClass Ring (R:Type) := {\n ring0: R; ring1: R; \n ring_plus: R->R->R; ring_mult: R->R->R;\n ring_sub:  R->R->R; ring_opp: R->R; \n ring_eq : R -> R -> Prop;\n ring_setoid: Equivalence ring_eq;\n ring_plus_comp: Proper (ring_eq==>ring_eq==>ring_eq) ring_plus;\n ring_mult_comp: Proper (ring_eq==>ring_eq==>ring_eq) ring_mult;\n ring_sub_comp: Proper (ring_eq==>ring_eq==>ring_eq) ring_sub;\n ring_opp_comp: Proper (ring_eq==>ring_eq) ring_opp;\n\n ring_add_0_l    : forall x, ring_eq (ring_plus ring0 x) x;\n ring_add_comm    : forall x y, ring_eq (ring_plus x y) (ring_plus y x);\n ring_add_assoc  : forall x y z, ring_eq (ring_plus x (ring_plus y z))\n                                         (ring_plus (ring_plus x y) z);\n ring_mul_1_l    : forall x, ring_eq (ring_mult ring1 x) x;\n ring_mul_1_r    : forall x, ring_eq (ring_mult x ring1) x;\n ring_mul_assoc  : forall x y z, ring_eq (ring_mult x (ring_mult y z))\n                                         (ring_mult (ring_mult x y) z);\n ring_distr_l    : forall x y z, ring_eq (ring_mult (ring_plus x y) z)\n                                   (ring_plus (ring_mult x z) (ring_mult y z));\n ring_distr_r    : forall x y z, ring_eq (ring_mult z (ring_plus x y))\n                                  (ring_plus (ring_mult z x) (ring_mult z y));\n ring_sub_def    : forall x y, ring_eq (ring_sub x y) (ring_plus x (ring_opp y));\n ring_opp_def    : forall x, ring_eq (ring_plus x (ring_opp x)) ring0\n}.\n\n\nInstance zero_ring (R:Type)(Rr:Ring R) : Zero R := {zero := ring0}.\nInstance one_ring(R:Type)(Rr:Ring R) : One R := {one := ring1}.\nInstance addition_ring(R:Type)(Rr:Ring R) : Addition R :=\n  {addition x y := ring_plus x y}.\nInstance multiplication_ring(R:Type)(Rr:Ring R) : Multiplication:= \n  {multiplication x y := ring_mult x y}.\nInstance subtraction_ring(R:Type)(Rr:Ring R) : Subtraction R :=\n  {subtraction x y := ring_sub x y}.\nInstance opposite_ring(R:Type)(Rr:Ring R) : Opposite R := \n  {opposite x := ring_opp x}.\nInstance equality_ring(R:Type)(Rr:Ring R) : Equality :=\n  {equality x y := ring_eq x y}.\n\nExisting Instance ring_setoid.\nExisting Instance ring_plus_comp.\nExisting Instance ring_mult_comp.\nExisting Instance ring_sub_comp.\nExisting Instance ring_opp_comp.\n(** Interpretation morphisms definition*)\n\nClass Ring_morphism (C R:Type)`{Cr:Ring C} `{Rr:Ring R}:= {\n    ring_morphism_fun: C -> R;\n    ring_morphism0    : ring_morphism_fun 0 == 0;\n    ring_morphism1    : ring_morphism_fun 1 == 1;\n    ring_morphism_add : forall x y, ring_morphism_fun (x + y)\n                     == ring_morphism_fun x + ring_morphism_fun y;\n    ring_morphism_sub : forall x y, ring_morphism_fun (x - y)\n                     == ring_morphism_fun x - ring_morphism_fun y;\n    ring_morphism_mul : forall x y, ring_morphism_fun (x * y)\n                     == ring_morphism_fun x * ring_morphism_fun y;\n    ring_morphism_opp : forall x, ring_morphism_fun (-x)\n                          == -(ring_morphism_fun x);\n    ring_morphism_eq  : forall x y, x == y\n       -> ring_morphism_fun x == ring_morphism_fun y}.\n\nInstance bracket_ring (C R:Type)`{Cr:Ring C} `{Rr:Ring R}\n   `{phi:@Ring_morphism C R Cr Rr}\n  : Bracket C R  :=\n  {bracket x := ring_morphism_fun x}.\n\n(* Tactics for rings *)\n\nLemma ring_syntax1:forall (A:Type)(Ar:Ring A), (@ring_eq _ Ar) = equality.\nintros. symmetry. simpl; reflexivity. Qed.\nLemma ring_syntax2:forall (A:Type)(Ar:Ring A), (@ring_plus _ Ar) = addition.\nintros. symmetry. simpl; reflexivity. Qed.\nLemma ring_syntax3:forall (A:Type)(Ar:Ring A), (@ring_mult _ Ar) = multiplication.\nintros. symmetry. simpl; reflexivity. Qed.\nLemma ring_syntax4:forall (A:Type)(Ar:Ring A), (@ring_sub _ Ar) = subtraction.\nintros. symmetry. simpl; reflexivity. Qed.\nLemma ring_syntax5:forall (A:Type)(Ar:Ring A), (@ring_opp _ Ar) = opposite.\nintros. symmetry. simpl; reflexivity. Qed.\nLemma ring_syntax6:forall (A:Type)(Ar:Ring A), (@ring0 _ Ar) = zero.\nintros. symmetry. simpl; reflexivity. Qed.\nLemma ring_syntax7:forall (A:Type)(Ar:Ring A), (@ring1 _ Ar) = one.\nintros. symmetry. simpl; reflexivity. Qed.\nLemma ring_syntax8:forall (A:Type)(Ar:Ring A)(B:Type)(Br:Ring B)\n  (pM:@Ring_morphism A B Ar Br), (@ring_morphism_fun _ _ _ _ pM) = bracket.\nintros. symmetry. simpl; reflexivity. Qed.\n\nLtac set_ring_notations :=\n  repeat (rewrite ring_syntax1);\n  repeat (rewrite ring_syntax2);\n  repeat (rewrite ring_syntax3);\n  repeat (rewrite ring_syntax4);\n  repeat (rewrite ring_syntax5);\n  repeat (rewrite ring_syntax6);\n  repeat (rewrite ring_syntax7);\n  repeat (rewrite ring_syntax8).\n\nLtac unset_ring_notations :=\n  unfold equality, equality_ring, addition, addition_ring,\n     multiplication, multiplication_ring, subtraction, subtraction_ring,\n     opposite, opposite_ring, one, one_ring, zero, zero_ring,\n     bracket, bracket_ring.\n\nLtac ring_simpl := simpl; set_ring_notations.\n\nLtac ring_rewrite H:=\n  generalize H;\n  let h := fresh \"H\" in\n  unset_ring_notations; intro h;\n  rewrite h; clear h;\n  set_ring_notations.\n\nLtac ring_rewrite_rev H:=\n  generalize H;\n  let h := fresh \"H\" in\n  unset_ring_notations; intro h;\n  rewrite <- h; clear h;\n  set_ring_notations.\n\nLtac rrefl := unset_ring_notations; reflexivity.\n\nSection Ring.\n\nVariable R: Type.\nVariable Rr: Ring R.\n\n(* Powers *)\n\n Fixpoint pow_pos (x:R) (i:positive) {struct i}: R :=\n  match i with\n  | xH => x\n  | xO i => let p := pow_pos x i in p * p\n  | xI i => let p := pow_pos x i in x * (p * p)\n  end.\nAdd Setoid R ring_eq ring_setoid as R_set_Power.\n Add Morphism ring_mult : rmul_ext_Power. exact ring_mult_comp. Qed.\n\n Lemma pow_pos_comm : forall x j,  x * pow_pos x j == pow_pos x j * x.\ninduction j; ring_simpl. \nring_rewrite_rev ring_mul_assoc. ring_rewrite_rev ring_mul_assoc. \nring_rewrite_rev IHj. ring_rewrite (ring_mul_assoc (pow_pos x j) x (pow_pos x j)).\nring_rewrite_rev IHj. ring_rewrite_rev ring_mul_assoc. rrefl.\nring_rewrite_rev ring_mul_assoc. ring_rewrite_rev IHj.\nring_rewrite ring_mul_assoc. ring_rewrite IHj.\nring_rewrite_rev ring_mul_assoc. ring_rewrite IHj. rrefl. rrefl.\nQed.\n\n Lemma pow_pos_Psucc : forall x j, pow_pos x (Psucc j) == x * pow_pos x j.\n Proof.\n  induction j; ring_simpl. \n  ring_rewrite IHj. \nring_rewrite_rev (ring_mul_assoc x (pow_pos x j) (x * pow_pos x j)).\nring_rewrite (ring_mul_assoc (pow_pos x j) x  (pow_pos x j)).\n  ring_rewrite_rev pow_pos_comm. unset_ring_notations.\nrewrite <- ring_mul_assoc. reflexivity.\nrrefl. rrefl.\nQed.\n\n Lemma pow_pos_Pplus : forall x i j, pow_pos x (i + j) == pow_pos x i * pow_pos x j.\n Proof.\n  intro x;induction i;intros.\n  rewrite xI_succ_xO;rewrite Pplus_one_succ_r.\n  rewrite <- Pplus_diag;repeat rewrite <- Pplus_assoc.\n  repeat ring_rewrite IHi.\n  rewrite Pplus_comm;rewrite <- Pplus_one_succ_r;\n  ring_rewrite pow_pos_Psucc.\n  ring_simpl;repeat ring_rewrite ring_mul_assoc. rrefl.\n  rewrite <- Pplus_diag;repeat rewrite <- Pplus_assoc.\n  repeat ring_rewrite IHi. ring_rewrite ring_mul_assoc. rrefl.\n  rewrite Pplus_comm;rewrite <- Pplus_one_succ_r;ring_rewrite pow_pos_Psucc.\n   simpl. reflexivity. \n Qed.\n\n Definition pow_N (x:R) (p:N) :=\n  match p with\n  | N0 => 1\n  | Npos p => pow_pos x p\n  end.\n\n Definition id_phi_N (x:N) : N := x.\n\n Lemma pow_N_pow_N : forall x n, pow_N x (id_phi_N n) == pow_N x n.\n Proof.\n  intros; rrefl.\n Qed.\n\nEnd Ring.\n\n\n\n\nSection Ring2.\nVariable R: Type.\nVariable Rr: Ring R.\n (** Identity is a morphism *)\n Definition IDphi (x:R) := x.\n Lemma IDmorph : @Ring_morphism R R Rr Rr.\n Proof.\n  apply (Build_Ring_morphism Rr Rr IDphi);intros;unfold IDphi; try rrefl. trivial.\n Qed.\n\nLtac ring_replace a b :=\n  unset_ring_notations; setoid_replace a with b; set_ring_notations.\n\n (** rings are almost rings*)\n Lemma ring_mul_0_l : forall x, 0 * x == 0.\n Proof.\n  intro x. ring_replace (0*x) ((0+1)*x + -x). \n  ring_rewrite ring_add_0_l. ring_rewrite ring_mul_1_l .\n  ring_rewrite ring_opp_def ;rrefl.\n  ring_rewrite ring_distr_l ;ring_rewrite ring_mul_1_l .\n  ring_rewrite_rev ring_add_assoc ; ring_rewrite ring_opp_def .\n  ring_rewrite ring_add_comm ; ring_rewrite ring_add_0_l ;rrefl.\n Qed.\n\n Lemma ring_mul_0_r : forall x, x * 0 == 0.\n Proof.\n  intro x; ring_replace (x*0)  (x*(0+1) + -x).\n  ring_rewrite ring_add_0_l ; ring_rewrite ring_mul_1_r .\n  ring_rewrite ring_opp_def ;rrefl.\n\n  ring_rewrite ring_distr_r ;ring_rewrite ring_mul_1_r .\n  ring_rewrite_rev ring_add_assoc ; ring_rewrite ring_opp_def .\n  ring_rewrite ring_add_comm ; ring_rewrite ring_add_0_l ;rrefl.\n Qed.\n\n Lemma ring_opp_mul_l : forall x y, -(x * y) == -x * y.\n Proof.\n  intros x y;ring_rewrite_rev (ring_add_0_l (- x * y)).\n  ring_rewrite ring_add_comm .\n  ring_rewrite_rev (ring_opp_def (x*y)).\n  ring_rewrite ring_add_assoc .\n  ring_rewrite_rev ring_distr_l.\n  ring_rewrite (ring_add_comm (-x));ring_rewrite ring_opp_def .\n  ring_rewrite ring_mul_0_l;ring_rewrite ring_add_0_l ;rrefl.\n Qed.\n\nLemma ring_opp_mul_r : forall x y, -(x * y) == x * -y.\n Proof.\n  intros x y;ring_rewrite_rev (ring_add_0_l (x * - y)).\n  ring_rewrite ring_add_comm .\n  ring_rewrite_rev (ring_opp_def (x*y)).\n  ring_rewrite ring_add_assoc .\n  ring_rewrite_rev ring_distr_r .\n  ring_rewrite (ring_add_comm (-y));ring_rewrite ring_opp_def .\n  ring_rewrite ring_mul_0_r;ring_rewrite ring_add_0_l ;rrefl.\n Qed.\n\n Lemma ring_opp_add : forall x y, -(x + y) == -x + -y.\n Proof.\n  intros x y;ring_rewrite_rev (ring_add_0_l  (-(x+y))).\n  ring_rewrite_rev (ring_opp_def  x).\n  ring_rewrite_rev (ring_add_0_l  (x + - x + - (x + y))).\n  ring_rewrite_rev (ring_opp_def  y).\n  ring_rewrite (ring_add_comm  x).\n  ring_rewrite (ring_add_comm  y).\n  ring_rewrite_rev (ring_add_assoc  (-y)).\n  ring_rewrite_rev (ring_add_assoc  (- x)).\n  ring_rewrite (ring_add_assoc   y).\n  ring_rewrite (ring_add_comm  y).\n  ring_rewrite_rev (ring_add_assoc   (- x)).\n  ring_rewrite (ring_add_assoc  y).\n  ring_rewrite (ring_add_comm  y);ring_rewrite ring_opp_def .\n  ring_rewrite (ring_add_comm  (-x) 0);ring_rewrite ring_add_0_l .\n  ring_rewrite ring_add_comm; rrefl.\n Qed.\n\n Lemma ring_opp_opp : forall x, - -x == x.\n Proof.\n  intros x; ring_rewrite_rev (ring_add_0_l (- -x)).\n  ring_rewrite_rev (ring_opp_def x).\n  ring_rewrite_rev ring_add_assoc ; ring_rewrite ring_opp_def .\n  ring_rewrite (ring_add_comm  x); ring_rewrite ring_add_0_l . rrefl.\n Qed.\n\n Lemma ring_sub_ext :\n      forall x1 x2, x1 == x2 -> forall y1 y2, y1 == y2 -> x1 - y1 == x2 - y2.\n Proof.\n  intros.\n  ring_replace (x1 - y1)  (x1 + -y1).\n  ring_replace (x2 - y2)  (x2 + -y2).\n  ring_rewrite H;ring_rewrite H0;rrefl.\n  ring_rewrite ring_sub_def. rrefl.\n  ring_rewrite ring_sub_def. rrefl.\n Qed.\n\n Ltac mring_rewrite :=\n   repeat first\n     [ ring_rewrite ring_add_0_l\n     | ring_rewrite_rev (ring_add_comm 0)\n     | ring_rewrite ring_mul_1_l\n     | ring_rewrite ring_mul_0_l\n     | ring_rewrite ring_distr_l\n     | rrefl\n     ].\n\n Lemma ring_add_0_r : forall x, (x + 0) == x.\n Proof. intros; mring_rewrite. Qed.\n\n \n Lemma ring_add_assoc1 : forall x y z, (x + y) + z == (y + z) + x.\n Proof.\n  intros;ring_rewrite_rev (ring_add_assoc x).\n  ring_rewrite (ring_add_comm x);rrefl.\n Qed.\n\n Lemma ring_add_assoc2 : forall x y z, (y + x) + z == (y + z) + x.\n Proof.\n  intros; repeat ring_rewrite_rev ring_add_assoc.\n   ring_rewrite (ring_add_comm x); rrefl.\n Qed.\n\n Lemma ring_opp_zero : -0 == 0.\n Proof.\n  ring_rewrite_rev (ring_mul_0_r 0). ring_rewrite ring_opp_mul_l.\n  repeat ring_rewrite ring_mul_0_r. rrefl.\n Qed.\n\nEnd Ring2.\n\n(** Some simplification tactics*)\nLtac gen_reflexivity := rrefl.\n \nLtac gen_ring_rewrite :=\n  repeat first\n     [ rrefl\n     | progress ring_rewrite ring_opp_zero\n     | ring_rewrite ring_add_0_l\n     | ring_rewrite ring_add_0_r\n     | ring_rewrite ring_mul_1_l \n     | ring_rewrite ring_mul_1_r\n     | ring_rewrite ring_mul_0_l \n     | ring_rewrite ring_mul_0_r \n     | ring_rewrite ring_distr_l \n     | ring_rewrite ring_distr_r \n     | ring_rewrite ring_add_assoc \n     | ring_rewrite ring_mul_assoc\n     | progress ring_rewrite ring_opp_add \n     | progress ring_rewrite ring_sub_def \n     | progress ring_rewrite_rev ring_opp_mul_l \n     | progress ring_rewrite_rev ring_opp_mul_r ].\n\nLtac gen_add_push x :=\nset_ring_notations;\nrepeat (match goal with\n  | |- context [(?y + x) + ?z] =>\n     progress ring_rewrite (@ring_add_assoc2 _ _ x y z)\n  | |- context [(x + ?y) + ?z] =>\n     progress ring_rewrite  (@ring_add_assoc1 _ _ x y z)\n  end).\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/plugins/setoid_ring/Ring2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6860465610527043}}
{"text": "Require Import Coq.ZArith.ZArith Coq.micromega.Lia.\nRequire Import Coq.ZArith.Znumtheory Coq.ZArith.Zpow_facts.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.ZSimplify.Core.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma mod_r_distr_if (b : bool) x y z : z mod (if b then x else y) = if b then z mod x else z mod y.\n  Proof. destruct b; reflexivity. Qed.\n  Hint Rewrite mod_r_distr_if : push_Zmod.\n  Hint Rewrite <- mod_r_distr_if : pull_Zmod.\n\n  Lemma mod_l_distr_if (b : bool) x y z : (if b then x else y) mod z = if b then x mod z else y mod z.\n  Proof. destruct b; reflexivity. Qed.\n  Hint Rewrite mod_l_distr_if : push_Zmod.\n  Hint Rewrite <- mod_l_distr_if : pull_Zmod.\n\n  (** Version without the [n <> 0] assumption *)\n  Lemma mul_mod_full a b n : (a * b) mod n = ((a mod n) * (b mod n)) mod n.\n  Proof. auto using Zmult_mod. Qed.\n  Hint Rewrite <- mul_mod_full : pull_Zmod.\n  Hint Resolve mul_mod_full : zarith.\n\n  Lemma mul_mod_l a b n : (a * b) mod n = ((a mod n) * b) mod n.\n  Proof.\n    intros; rewrite (mul_mod_full a b), (mul_mod_full (a mod n) b).\n    autorewrite with zsimplify; reflexivity.\n  Qed.\n  Hint Rewrite <- mul_mod_l : pull_Zmod.\n  Hint Resolve mul_mod_l : zarith.\n\n  Lemma mul_mod_r a b n : (a * b) mod n = (a * (b mod n)) mod n.\n  Proof.\n    intros; rewrite (mul_mod_full a b), (mul_mod_full a (b mod n)).\n    autorewrite with zsimplify; reflexivity.\n  Qed.\n  Hint Rewrite <- mul_mod_r : pull_Zmod.\n  Hint Resolve mul_mod_r : zarith.\n\n  Lemma add_mod_full a b n : (a + b) mod n = ((a mod n) + (b mod n)) mod n.\n  Proof. auto using Zplus_mod. Qed.\n  Hint Rewrite <- add_mod_full : pull_Zmod.\n  Hint Resolve add_mod_full : zarith.\n\n  Lemma add_mod_l a b n : (a + b) mod n = ((a mod n) + b) mod n.\n  Proof.\n    intros; rewrite (add_mod_full a b), (add_mod_full (a mod n) b).\n    autorewrite with zsimplify; reflexivity.\n  Qed.\n  Hint Rewrite <- add_mod_l : pull_Zmod.\n  Hint Resolve add_mod_l : zarith.\n\n  Lemma add_mod_r a b n : (a + b) mod n = (a + (b mod n)) mod n.\n  Proof.\n    intros; rewrite (add_mod_full a b), (add_mod_full a (b mod n)).\n    autorewrite with zsimplify; reflexivity.\n  Qed.\n  Hint Rewrite <- add_mod_r : pull_Zmod.\n  Hint Resolve add_mod_r : zarith.\n\n  Lemma opp_mod_mod a n : (-a) mod n = (-(a mod n)) mod n.\n  Proof.\n    intros; destruct (Z_zerop (a mod n)) as [H'|H']; [ rewrite H' | ];\n      [ | rewrite !Z_mod_nz_opp_full ];\n      autorewrite with zsimplify; lia.\n  Qed.\n  Hint Rewrite <- opp_mod_mod : pull_Zmod.\n  Hint Resolve opp_mod_mod : zarith.\n\n  (** Give alternate names for the next three lemmas, for consistency *)\n  Lemma sub_mod_full a b n : (a - b) mod n = ((a mod n) - (b mod n)) mod n.\n  Proof. auto using Zminus_mod. Qed.\n  Hint Rewrite <- sub_mod_full : pull_Zmod.\n  Hint Resolve sub_mod_full : zarith.\n\n  Lemma sub_mod_l a b n : (a - b) mod n = ((a mod n) - b) mod n.\n  Proof. auto using Zminus_mod_idemp_l. Qed.\n  Hint Rewrite <- sub_mod_l : pull_Zmod.\n  Hint Resolve sub_mod_l : zarith.\n\n  Lemma sub_mod_r a b n : (a - b) mod n = (a - (b mod n)) mod n.\n  Proof. auto using Zminus_mod_idemp_r. Qed.\n  Hint Rewrite <- sub_mod_r : pull_Zmod.\n  Hint Resolve sub_mod_r : zarith.\n\n  Lemma lnot_mod_mod v m : (Z.lnot (v mod m) mod m) = (Z.lnot v) mod m.\n  Proof.\n    cbv [Z.lnot]; etransitivity; rewrite <- !Z.sub_1_r, Z.sub_mod_full, Z.opp_mod_mod, ?Zmod_mod; reflexivity.\n  Qed.\n  Hint Rewrite lnot_mod_mod : pull_Zmod.\n  Hint Resolve lnot_mod_mod : zarith.\n\n  Lemma mod_pow_full p q n : (p^q) mod n = ((p mod n)^q) mod n.\n  Proof.\n    destruct (Z_dec' n 0) as [ [H|H] | H]; subst;\n      [\n      | apply Zpower_mod; assumption\n      | rewrite !Zmod_0_r; reflexivity ].\n    { revert H.\n      rewrite <- (Z.opp_involutive (p^q)),\n      <- (Z.opp_involutive ((p mod n)^q)),\n      <- (Z.opp_involutive p),\n      <- (Z.opp_involutive n).\n      generalize (-n); clear n; intros n H.\n      rewrite !Zmod_opp_opp.\n      rewrite !Z.opp_involutive.\n      apply f_equal.\n      destruct (Z.Even_or_Odd q).\n      { rewrite !Z.pow_opp_even by (assumption || lia).\n        destruct (Z.eq_dec (p^q mod n) 0) as [H'|H'], (Z.eq_dec ((-p mod n)^q mod n) 0) as [H''|H''];\n          repeat first [ rewrite Z_mod_zero_opp_full by assumption\n                       | rewrite Z_mod_nz_opp_full by assumption\n                       | reflexivity\n                       | rewrite <- Zpower_mod, Z.pow_opp_even in H'' by (assumption || lia); lia\n                       | rewrite <- Zpower_mod, Z.pow_opp_even in H'' |- * by (assumption || lia); lia ]. }\n      { rewrite Z.pow_opp_odd, !Z.opp_involutive, <- Zpower_mod, Z.pow_opp_odd, ?Z.opp_involutive by (assumption || lia).\n        reflexivity. } }\n  Qed.\n  Hint Rewrite <- mod_pow_full : pull_Zmod.\n  Hint Resolve mod_pow_full : zarith.\n  Notation pow_mod_full := mod_pow_full.\n\n  Definition NoZMod (x : Z) := True.\n  Ltac NoZMod :=\n    lazymatch goal with\n    | [ |- NoZMod (?x mod ?y) ] => fail 0 \"Goal has\" x \"mod\" y\n    | [ |- NoZMod _ ] => constructor\n    end.\n\n  Lemma mul_mod_push a b n : NoZMod a -> NoZMod b -> (a * b) mod n = ((a mod n) * (b mod n)) mod n.\n  Proof. intros; apply mul_mod_full; assumption. Qed.\n  Hint Rewrite mul_mod_push using solve [ NoZMod ] : push_Zmod.\n\n  Lemma add_mod_push a b n : NoZMod a -> NoZMod b -> (a + b) mod n = ((a mod n) + (b mod n)) mod n.\n  Proof. intros; apply add_mod_full; assumption. Qed.\n  Hint Rewrite add_mod_push using solve [ NoZMod ] : push_Zmod.\n\n  Lemma mul_mod_l_push a b n : NoZMod a -> (a * b) mod n = ((a mod n) * b) mod n.\n  Proof. intros; apply mul_mod_l; assumption. Qed.\n  Hint Rewrite mul_mod_l_push using solve [ NoZMod ] : push_Zmod.\n\n  Lemma mul_mod_r_push a b n : NoZMod b -> (a * b) mod n = (a * (b mod n)) mod n.\n  Proof. intros; apply mul_mod_r; assumption. Qed.\n  Hint Rewrite mul_mod_r_push using solve [ NoZMod ] : push_Zmod.\n\n  Lemma add_mod_l_push a b n : NoZMod a -> (a + b) mod n = ((a mod n) + b) mod n.\n  Proof. intros; apply add_mod_l; assumption. Qed.\n  Hint Rewrite add_mod_l_push using solve [ NoZMod ] : push_Zmod.\n\n  Lemma add_mod_r_push a b n : NoZMod b -> (a + b) mod n = (a + (b mod n)) mod n.\n  Proof. intros; apply add_mod_r; assumption. Qed.\n  Hint Rewrite add_mod_r_push using solve [ NoZMod ] : push_Zmod.\n\n  Lemma sub_mod_push a b n : NoZMod a -> NoZMod b -> (a - b) mod n = ((a mod n) - (b mod n)) mod n.\n  Proof. intros; apply Zminus_mod; assumption. Qed.\n  Hint Rewrite sub_mod_push using solve [ NoZMod ] : push_Zmod.\n\n  Lemma sub_mod_l_push a b n : NoZMod a -> (a - b) mod n = ((a mod n) - b) mod n.\n  Proof. intros; symmetry; apply Zminus_mod_idemp_l; assumption. Qed.\n  Hint Rewrite sub_mod_l_push using solve [ NoZMod ] : push_Zmod.\n\n  Lemma sub_mod_r_push a b n : NoZMod b -> (a - b) mod n = (a - (b mod n)) mod n.\n  Proof. intros; symmetry; apply Zminus_mod_idemp_r; assumption. Qed.\n  Hint Rewrite sub_mod_r_push using solve [ NoZMod ] : push_Zmod.\n\n  Lemma opp_mod_mod_push a n : NoZMod a -> (-a) mod n = (-(a mod n)) mod n.\n  Proof. intros; apply opp_mod_mod; assumption. Qed.\n  Hint Rewrite opp_mod_mod_push using solve [ NoZMod ] : push_Zmod.\n\n  Lemma lnot_mod_mod_push v m : NoZMod v -> (Z.lnot v) mod m = (Z.lnot (v mod m) mod m).\n  Proof. intros; symmetry; apply lnot_mod_mod. Qed.\n  Hint Rewrite lnot_mod_mod_push using solve [ NoZMod ] : push_Zmod.\n\n  Lemma pow_mod_push p q n : NoZMod p -> (p^q) mod n = ((p mod n)^q) mod n.\n  Proof. intros; apply pow_mod_full. Qed.\n  Hint Rewrite pow_mod_push using solve [ NoZMod ] : push_Zmod.\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/Modulo/PullPush.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.686046542361035}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (lf3 : natural) : natural := plus z lf3.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_commut/goal33conj146_coqofml_qdzTPb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927012, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.6859954380742533}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\nRequire Import List Arith Nat Lia Relations Bool.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac utils_list fin_base.\n\nLocal Infix \"∈\" := In (at level 70, no associativity).\nLocal Infix \"⊆\" := incl (at level 70, no associativity).\nLocal Notation \"P ≅ Q\" := ((P -> Q) * (Q -> P))%type (at level 70, no associativity).\n\nSet Implicit Arguments.\n\nSection finite_t_upto.\n\n  Variable (X : Type) (R : X -> X -> Prop).\n\n  Definition fin_t_upto (P : X -> Type) := \n     { l : _ & (forall x, P x -> exists y, y ∈ l /\\ R x y) \n              *(forall x y, x ∈ l -> R x y -> P y) }%type.\n\n  Definition finite_t_upto := \n     { l : _ | forall x, exists y, y ∈ l /\\ R x y }.\n\n  Fact finite_t_fin_upto : finite_t_upto ≅ fin_t_upto (fun _ => True).\n  Proof. split; intros []; red; eauto; firstorder. Qed.\n\nEnd finite_t_upto.\n\nArguments finite_t_upto : clear implicits.\n\nSection finite_t_weak_dec_powerset.\n\n  (* We built a list containing all weakly decidable predicates,\n      ie the weakly decidable powerset build as from atoms \n        x = _ and x <> _  \n\n     We do NOT require that X is a discrete type. *)\n\n  Variable (X : Type).\n\n  Let wdec (R : X -> Prop) := forall x, R x \\/ ~ R x.\n   \n  Let pset_fin_t (l : list X) : { ll |  length ll = 2 ^ (length l)\n                                     /\\ forall R, wdec R \n                                   ->   exists T, T ∈ ll \n                                     /\\ forall x, x ∈ l -> R x <-> T x }.\n  Proof.\n    induction l as [ | x l IHl ].\n    + exists ((fun _ => True) :: nil); split; auto.\n      intros R HR; exists (fun _ => True); simpl; split; tauto.\n    + destruct IHl as (ll & Hl & Hll).\n      exists (map (fun T a => x<>a /\\ T a) ll ++ map (fun T a => x=a \\/ T a) ll); split.\n      1: rewrite app_length, !map_length; simpl; lia.\n      intros R HR.\n      destruct (Hll R) as (T & H1 & H2); auto.\n      destruct (HR x) as [ H0 | H0 ].\n      * exists (fun a => x = a \\/ T a); split.\n        - apply in_or_app; right.\n          apply in_map_iff; exists T; auto.\n        - intros y [ <- | H ]; simpl; try tauto.\n          rewrite H2; auto; split; auto.\n          intros [ -> | ]; auto.\n          apply H2; auto.\n      * exists (fun a => x <> a /\\ T a); split.\n        - apply in_or_app; left.\n          apply in_map_iff; exists T; auto.\n        - intros y [ <- | H ]; simpl; split; try tauto.\n          ++ rewrite <- H2; auto; split; auto.\n             contradict H0; subst; auto. \n          ++ rewrite <- H2; tauto.\n  Qed.\n\n  (* Because = is not supposed decidable (X is not discrete), we\n     cannot show that every element in ll below is weakly decidable *)\n\n  Theorem finite_t_weak_dec_powerset (h : finite_t X) : \n            { ll |  length ll = 2 ^ (length (proj1_sig h)) \n                 /\\ forall R, wdec R -> exists T, T ∈ ll /\\ forall x, R x <-> T x }.\n  Proof.\n    destruct h as (l & Hl).\n    destruct (pset_fin_t l) as (ll & H & Hll).\n    exists ll; split; auto.\n    intros R HR.\n    destruct (Hll _ HR) as (T & H1 & H2).\n    exists T; split; auto.\n  Qed.\n\nEnd finite_t_weak_dec_powerset.\n\n(* We show that there is a finite_t bound over weakly (hence also strongly) decidable  \n    binary relations upto equivalence. Notice that it is not guaranteed that the list l \n    below contains only decidable relations *)\n\nTheorem finite_t_weak_dec_rels X :\n           finite_t X \n        -> { ll | forall R, \n                      (forall x y : X, R x y \\/ ~ R x y) \n                   -> exists T, T ∈ ll /\\ forall x y, R x y <-> T x y }.\nProof.\n  intros h.\n  destruct finite_t_weak_dec_powerset with (h := finite_t_prod h h)\n    as (l & _ & Hl).\n  exists (map (fun P x y => P (x,y)) l).\n  intros R HR.\n  destruct (Hl (fun c => R (fst c) (snd c))) as (T & H1 & H2).\n  + intros []; apply HR.\n  + exists (fun x y => T (x,y)); split.\n    * apply in_map_iff; exists T; auto.\n    * intros x y; apply (H2 (x,y)).\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/Shared/Libs/DLW/Utils/fin_upto.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6859954333978944}}
{"text": "(** * Utheory.v: Specification of $U$, interval $[0,1]$ *)\n\nFrom ALEA Require Export Misc.\nFrom ALEA Require Export Ccpo.\nSet Implicit Arguments.\nOpen Scope O_scope.\n\n(** ** Basic operators of $U$ *)\n(** - Constants : $0$ and $1$\n    - Constructor : [Unth] $n (\\equiv \\frac{1}{n+1})$\n    - Operations : $x+y~(\\equiv min (x+y,1))$, $x*y$, [inv] $x~(\\equiv 1 -x)$\n    - Relations : $x\\leq y$, $x==y$\n*)\nModule Type Universe.\nParameter U : cpo.\nDeclare Scope U_scope.\n\nParameter U1 : U. \nParameters Uplus Umult Udiv: U -> U -> U.\nParameter Uinv : U -> U.\nParameter Unth : nat -> U.\n(*\nDefinition Uplus x y := UPlus x y.\nDefinition Umult x y := UMult x y.\n*)\n\nInfix \"+\" := Uplus : U_scope.\nInfix \"*\"  := Umult  : U_scope.\nInfix \"/\"  := Udiv  : U_scope.\nNotation \"[1-] x\" := (Uinv x)  (at level 35, right associativity) : U_scope.\nNotation \"1\" := U1 : U_scope.\nNotation \"[1/]1+ n\" := (Unth n) (at level 35, right associativity) : U_scope.\nOpen Scope U_scope.\n\n(** ** Basic Properties *)\n\nParameter Udiff_0_1 : ~0 == 1.\n\nParameter Unit : forall x:U, x <= 1. \n\nParameter Uplus_sym : forall x y:U, x + y == y + x.\nParameter Uplus_assoc : forall x y z:U, x + (y + z) == x + y + z.\nParameter Uplus_zero_left : forall x:U, 0 + x == x.\n\nParameter Umult_sym : forall x y:U, x * y == y * x.\nParameter Umult_assoc : forall x y z:U, x * (y * z) == x * y * z.\nParameter Umult_one_left : forall x:U, 1 * x == x.\n\nParameter Uinv_one : [1-] 1 == 0. \nParameter Uinv_opp_left : forall x, [1-] x + x == 1.\n\nParameter Umult_div : forall x y, ~0 == y -> x <= y -> y * (x/y) == x.\nParameter Udiv_le_one : forall x y,  ~0 == y -> y <= x -> (x/y) == 1.\nParameter Udiv_by_zero : forall x y,  0 == y -> (x/y) == 0.\n\n(** - Property  : $1 - (x+y) + x=1-y$ holds when $x+y$ does not overflow *)\nParameter Uinv_plus_left : forall x y, y <= [1-] x -> [1-] (x + y) + x == [1-] y.\n\n(** - Property  : $(x + y) \\times z  = x \\times z + y \\times z$ \n    holds when $x+y$ does not overflow *)\nParameter Udistr_plus_right : forall x y z (H : x <= [1-] y), (x + y) * z == x * z + y * z.\n\n(** - Property  : $1 - (x \\times y) = (1 - x)\\times y + (1-y)$ *)\nParameter Udistr_inv_right : forall x y:U,  [1-] (x * y) == ([1-] x) * y + [1-] y.\n\n(** - Totality of the order *)\nParameter Ule_class : forall x y : U, class (x <= y).\n\nParameter Ule_total : forall x y : U, orc (x<=y) (y<=x).\nArguments Ule_total : clear implicits.\n\n(** - The relation $x\\leq y$ is compatible with operators *)\n\nParameter Uplus_le_compat_right : forall x y z:U, y <= z -> x + y <= x + z.\n\nParameter Umult_le_compat_right : forall x y z:U, y <= z -> x * y <= x * z.\n\nParameter Uinv_le_compat : forall x y:U, x <= y -> [1-] y <= [1-] x.\n\n(** - Properties of simplification in case there is no overflow *)\nParameter Uplus_le_simpl_right : forall x y z, z <= [1-] x -> x + z <= y + z -> x <= y.\n\nParameter Umult_le_simpl_left : forall x y z: U, ~0 == z -> z * x <= z * y -> x <= y .\n\n(** -  Property [Unth] $\\frac{1}{n+1} == 1 - n \\times \\frac{1}{n+1}$ *)\nParameter Unth_prop : forall n, [1/]1+n == [1-](comp Uplus 0 (fun k => [1/]1+n) n).\n\n(** - Archimedian property *)\nParameter archimedian : forall x, ~0 == x -> exc (fun n => [1/]1+n <= x).\n\n(** - Stability properties of lubs with respect to [+] and [*] *)\n\nParameter Uplus_right_continuous : forall k, continuous (mk_fmono (Uplus_le_compat_right k)).\nParameter Umult_right_continuous : forall k, continuous (mk_fmono (Umult_le_compat_right k)).\n\nEnd Universe.\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/Utheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740728, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6859954311275986}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq             *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later            *)\nFrom mathcomp Require Import all_ssreflect ssralg fingroup finalg matrix.\nRequire Import Reals.\nFrom mathcomp Require Import Rstruct.\nRequire Import ssrR Reals_ext ssr_ext ssralg_ext logb Rbigop.\nRequire Import fdist entropy convex ln_facts jensen num_occ.\n\n(******************************************************************************)\n(*                         String entropy                                     *)\n(*                                                                            *)\n(* For details, see: Reynald Affeldt, Jacques Garrigue, and Takafumi Saikawa. *)\n(* Examples of formal proofs about data compression. International Symposium  *)\n(* on Information Theory and Its Applications (ISITA 2018), Singapore,        *)\n(* October 28--31, 2018, pages 633--637. IEEE, Oct 2018                       *)\n(*                                                                            *)\n(* Main reference:                                                            *)\n(*   Gonzalo Navarro. Compact Data Structures: A Practical Approach.          *)\n(*   Cambridge University Press, 2016.                                        *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope R_scope.\nLocal Open Scope num_occ_scope.\nLocal Open Scope entropy_scope.\nLocal Coercion INR : nat >-> R.\n\nDefinition simplR := (add0R, addR0, subR0, mul0R, mulR0, mul1R, mulR1).\n\nLocal Hint Resolve leRR : core.\nLocal Hint Resolve leR0n : core.\n\nSection seq_nat_fdist.\n\nVariables (A : finType) (f : A -> nat).\nVariable total : nat.\nHypothesis sum_f_total : (\\sum_(a in A) f a)%nat = total.\nHypothesis total_gt0 : total != O.\n\nLet f_div_total := [ffun a : A => f a / total].\n\nLemma f_div_total_pos c : 0 <= f_div_total c.\nProof.\nrewrite ffunE; apply mulR_ge0 => //.\napply /Rlt_le /invR_gt0 /ltR0n.\nby rewrite lt0n.\nQed.\n\nLemma f_div_total_1 : \\sum_(a in A) [ffun a : A => f a / total] a = 1.\nProof.\nunder eq_bigr do rewrite ffunE /=.\nrewrite /f_div_total -big_distrl -big_morph_natRD.\nby rewrite sum_f_total /= mulRV // INR_eq0'.\nQed.\n\nDefinition seq_nat_fdist := FDist.make f_div_total_pos f_div_total_1.\n\nEnd seq_nat_fdist.\n\nSection string.\n\nVariable A : finType.\n\nSection entropy.\nVariable S : seq A.\nHypothesis S_nonempty : size S != O.\n\nDefinition pchar c := N(c|S) / size S.\n\nDefinition num_occ_dist := seq_nat_fdist (sum_num_occ_size S) S_nonempty.\n\nDefinition Hs0 := `H num_occ_dist.\nEnd entropy.\n\nSection string_concat.\n\n(*\nDefinition Hs (s : seq A) :=\n \\rsum_(a in A)\n  if N(a|s) == 0%nat then 0 else\n  N(a|s) / size s * log (size s / N(a|s)).\n*)\n\nDefinition nHs (s : seq A) :=\n \\sum_(a in A)\n  if N(a|s) == 0%nat then 0 else\n  N(a|s) * log (size s / N(a|s)).\n\nLemma szHs_is_nHs s (H : size s != O) :\n  size s * `H (@num_occ_dist s H) = nHs s.\nProof.\nrewrite /entropy /nHs /num_occ_dist /= -mulRN1 big_distrl big_distrr /=.\napply eq_bigr => a _ /=; rewrite ffunE.\ncase: ifPn => [/eqP -> | Hnum]; first by rewrite !mulRA !simplR.\nrewrite {1}/Rdiv (mulRC N(a | s)) 3![in LHS]mulRA mulRV ?INR_eq0' // ?mul1R.\nrewrite -mulRA mulRN1 -logV; last by apply divR_gt0; rewrite ltR0n lt0n.\nrewrite Rinv_Rdiv //; apply/eqP; by rewrite INR_eq0'.\nQed.\n\nDefinition mulnRdep (x : nat) (y : x != O -> R) : R.\ncase/boolP: (x == O) => Hx.\n+ exact 0.\n+ exact (x * y Hx).\nDefined.\nArguments mulnRdep x y : clear implicits.\n\nLemma mulnRdep_0 y : mulnRdep 0 y = 0.\nProof. rewrite /mulnRdep /=. by destruct boolP. Qed.\n\nLemma mulnRdep_nz x y (Hx : x != O) : mulnRdep x y = x * y Hx.\nProof.\nrewrite /mulnRdep /=.\ndestruct boolP.\n  by elimtype False; rewrite i in Hx.\ndo 2!f_equal; apply eq_irrelevance.\nQed.\n\nLemma szHs_is_nHs_full s : mulnRdep (size s) (fun H => Hs0 H) = nHs s.\nProof.\nrewrite /mulnRdep; destruct boolP; last by apply szHs_is_nHs.\nrewrite /nHs (eq_bigr (fun a => 0)); first by rewrite big1.\nmove=> a _; suff -> : N(a|s) == O by [].\nby rewrite /num_occ -leqn0 -(eqP i) count_size.\nQed.\n\nTheorem concats_entropy ss :\n(*  \\rsum_(s <- ss) size s * Hs s\n       <= size (flatten ss) * Hs (flatten ss). *)\n(* \\rsum_(s <- ss) mulnRdep (size s) (fun H => Hs0 H)\n       <= mulnRdep (size (flatten ss)) (fun H => Hs0 H). *)\n  \\sum_(s <- ss) nHs s <= nHs (flatten ss).\nProof.\n(* (1) First simplify formula *)\n(*rewrite szHs_is_nHs.\nrewrite (eq_bigr _ (fun i _ => szHs_is_nHs i)).*)\nrewrite exchange_big /nHs /=.\n(* (2) Move to per-character inequalities *)\napply leR_sumR => a _.\n(* Remove strings containing no occurrences *)\nrewrite (bigID (fun s => N(a|s) == O)) /=.\nrewrite big1; last by move=> i ->.\nrewrite num_occ_flatten add0R.\nrewrite [in X in _ <= X](bigID (fun s => N(a|s) == O)).\nrewrite [in X in _ <= X]big1 //= ?add0n;\n  last by move=> i /eqP.\nrewrite (eq_bigr\n       (fun i => N(a|i) * log (size i / N(a|i))));\n  last by move=> i /negbTE ->.\nrewrite -big_filter -[in X in _ <= X]big_filter.\n(* ss' contains only strings with ocurrences *)\nset ss' := [seq s <- ss | N(a|s) != O].\ncase/boolP: (ss' == [::]) => Hss'.\n  by rewrite (eqP Hss') !big_nil eqxx.\nhave Hnum s : s \\in ss' -> (N(a|s) > 0)%nat.\n  by rewrite /ss' mem_filter lt0n => /andP [->].\nhave Hnum': 0 < N(a|flatten ss').\n  apply /ltR0n; destruct ss' => //=.\n  rewrite /num_occ count_cat ltn_addr //.\n  by rewrite Hnum // in_cons eqxx.\nhave Hsz: 0 < size (flatten ss').\n  apply (ltR_leR_trans Hnum').\n  by apply /le_INR /leP /count_size.\napply (@leR_trans ((\\sum_(i <- ss') N(a|i))%:R *\n    log (size (flatten ss') /\n      (\\sum_(i <- ss') N(a|i))%nat)));\n  last first.\n  (* Not mentioned in the book: one has to compensate for the discarding\n     of strings containing no occurences.\n     Works thanks to monotonicity of log. *)\n  (* (3) Compensate for removed strings *)\n  case: ifP => Hsum.\n    by rewrite (eqP Hsum) mul0R.\n  apply leR_wpmul2l => //.\n  apply Log_increasing_le => //.\n    apply/mulR_gt0 => //.\n    apply/invR_gt0/ltR0n.\n    by rewrite lt0n Hsum.\n  apply leR_wpmul2r.\n    apply /Rlt_le /invR_gt0 /ltR0n.\n    by rewrite lt0n Hsum.\n  apply /le_INR /leP.\n  rewrite !size_flatten !sumn_big_addn.\n  rewrite !big_map big_filter.\n  rewrite [in X in (_ <= X)%nat]\n    (bigID (fun s => N(a|s) == O)) /=.\n  by apply leq_addl.\n(* (4) Prepare to use jensen_dist_concave *)\nhave Htotal := esym (num_occ_flatten a ss').\nrewrite big_tnth in Htotal.\nhave Hnum2 : N(a|flatten ss') != O.\n  rewrite -lt0n -ltR0n'; exact/ltRP.\nset d := seq_nat_fdist Htotal Hnum2.\nset r := fun i =>\n  (size (tnth (in_tuple ss') i))\n  / N(a|tnth (in_tuple ss') i).\nhave Hr: forall i, r i \\in Rpos_interval.\n  rewrite /r /= => i.\n  rewrite classical_sets.in_setE; apply Rlt_mult_inv_pos; apply /ltR0n.\n    apply (@leq_trans N(a|tnth (in_tuple ss') i)).\n      by rewrite Hnum // mem_tnth.\n    by apply count_size.\n  by apply /Hnum /mem_tnth.\n(* (5) Apply Jensen *)\nmove: (jensen_dist_concave log_concave d Hr).\nrewrite /d /r /=.\nunder eq_bigr do rewrite ffunE /=.\nunder [X in _ <= log X -> _]eq_bigr do rewrite ffunE /=.\nrewrite -(big_tnth _ _ _ xpredT\n  (fun s => (N(a|s) / N(a|flatten ss')) *\n           log ((size s) / N(a|s)))).\nrewrite -(big_tnth _ _ _ xpredT\n  (fun s => (N(a|s) / N(a|flatten ss')) *\n           (size s / N(a|s)))).\n(* (6) Transform the statement to match the goal *)\nmove/(@leR_wpmul2r N(a|flatten ss') _ _ (leR0n _)).\nrewrite !big_distrl /=.\nrewrite (eq_bigr\n  (fun i => N(a|i) * log (size i / N(a|i))));\n  last first.\n  by move=> i _; rewrite mulRAC -!mulRA (mulRA (/ _)) mulVR ?mul1R // gtR_eqF.\nmove/leR_trans; apply. (* LHS matches *)\nrewrite mulRC -num_occ_flatten big_filter.\nrewrite (eq_bigr\n  (fun i => size i / N(a|flatten ss')));\n  last first.\n  move=> i Hi; rewrite mulRCA {1}/Rdiv mulRAC.\n  by rewrite mulRV ?mul1R // INR_eq0'.\nrewrite -big_filter -/ss' -big_distrl.\nrewrite -big_morph_natRD /=.\nby rewrite size_flatten sumn_big_addn big_map.\nQed.\n\nEnd string_concat.\n\nEnd string.\n\n(* tentative definition *)\nSection higher_order_empirical_entropy.\n\nVariables (A : finType) (l : seq A).\nHypothesis A0 : (O < #|A|)%nat.\nLet n := size l.\nLet def : A. Proof. move/card_gt0P : A0 => /sigW[def _]; exact def. Defined.\nHypothesis l0 : n != O.\n\n(* the string consisting of the concatenation of the symbols following w in s *)\nFixpoint takes {k : nat} (w : k.-tuple A) (s : seq A) {struct s} : seq A :=\n  if s is _ :: t then\n    let s' := takes w t in\n    if take k s == w then nth def (drop k s) O :: s' else s'\n  else\n    [::].\n\n(* sample ref: https://www.dcc.uchile.cl/~gnavarro/ps/jea08.2.pdf *)\nDefinition hoH (k : nat) := / n%:R *\n  \\sum_(w in {: k.-tuple A}) #|takes w l|%:R *\n    match Bool.bool_dec (size w != O) true with\n      | left H => `H (num_occ_dist H)\n      | _ => 0\n    end.\n\nLemma hoH_decr (k : nat) : hoH k.+1 <= hoH k.\nProof.\nrewrite /hoH; apply/leRP; rewrite leR_pmul2l'; last first.\n  by apply/ltRP/invR_gt0/ltRP; rewrite ltR0n' lt0n.\n(* TODO *)\nAbort.\n\nEnd higher_order_empirical_entropy.\n", "meta": {"author": "affeldt-aist", "repo": "infotheo", "sha": "5f9efb859dbadcbcae2330e2e21e76f9b632d879", "save_path": "github-repos/coq/affeldt-aist-infotheo", "path": "github-repos/coq/affeldt-aist-infotheo/infotheo-5f9efb859dbadcbcae2330e2e21e76f9b632d879/information_theory/string_entropy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6859954265191234}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (lf2 : natural) : natural := plus lf2 z.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj126_coqofml_ZwNWR5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6859954193688169}}
{"text": "(**\n    The \"classical\" definition of well-foundedness\n    Pierre Casteran\n\n keywords :  well-founded relations, classical logic, axiom of choice\n\n   \n *)\n\nRequire Import Relations.\n\n(** \n  Please consider the usual mathematical definition of well-founded relations :\n *)\n\n\nDefinition classic_wf {A}(R: relation A) :=\n  ~ exists (s: nat-> A),  forall i,  R (s (S i)) (s i).\n\n(** Prove that Coq's  definition entails the classical one *)\n\nTheorem wf_classic_wf {A} (R: relation A) : well_founded R -> classic_wf R.\nProof.\nAdmitted.\n\n(** Now, we work with some axioms (assumed in the following libraries) *)\n\nRequire Import Classical ClassicalChoice.\n\n\n\n(** In the current context, prove that the classical definition entails Coq's \n    (you may apply the following theorem)  *)\n\nAbout choice.\n\nPrint Assumptions choice.\n\n\nTheorem classic_wf_wf {A} (R: relation A) : classic_wf R -> well_founded R.\nProof.\nAdmitted.\n\n\n\nPrint Assumptions classic_wf_wf.\n\n(*\n\nAxioms:\nrelational_choice : forall (A B : Type) (R : A -> B -> Prop),\n                    (forall x : A, exists y : B, R x y) ->\n                    exists R' : A -> B -> Prop, subrelation R' R /\\ (forall x : A, exists ! y : B, R' x y)\ndependent_unique_choice : forall (A : Type) (B : A -> Type) (R : forall x : A, B x -> Prop),\n                          (forall x : A, exists ! y : B x, R x y) ->\n                          exists f : forall x : A, B x, forall x : A, R x (f x)\nclassic : forall P : Prop, P \\/ ~ P\n\n*)\n\nPrint Assumptions wf_classic_wf.\n\n(*\n\nClosed under the global context\n*)\n\n\n\n\n\n\n\n\n  \n", "meta": {"author": "coq-community", "repo": "coq-art", "sha": "b3aaf69bc0c4809e482e931b633fa88ba1646996", "save_path": "github-repos/coq/coq-community-coq-art", "path": "github-repos/coq/coq-community-coq-art/coq-art-b3aaf69bc0c4809e482e931b633fa88ba1646996/more_exercises/texts/classic_well_founded.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6859827143300669}}
{"text": "(* Exercise 5.4 *)\n\nDefinition dyslexic_imp := forall P Q : Prop, (P -> Q) -> (Q -> P).\nDefinition dyslexic_contrap := forall P Q : Prop, (P -> Q) -> (~P -> ~Q).\n\nTheorem dyslexic_imp_is_false : ~dyslexic_imp.\nProof.\n  unfold not.\n  unfold dyslexic_imp.\n  intros dyslexic_imp.\n  apply (dyslexic_imp False True).\n  intro false.\n  apply False_ind.\n  assumption.\n  apply I.\nQed.\n\nTheorem dyslexic_contrap_is_false : ~dyslexic_contrap.\nProof.\n  unfold not.\n  unfold dyslexic_contrap.\n  intros dyslexic_contrap.\n  apply (dyslexic_contrap False True).\n  intro false.\n  apply False_ind.\n  assumption.\n  intro false.\n  assumption.\n  apply I.\nQed.", "meta": {"author": "aymanosman", "repo": "coq-art-exercises", "sha": "ff7e2aba35a5094d366be5b9f55dfdd13d38cd48", "save_path": "github-repos/coq/aymanosman-coq-art-exercises", "path": "github-repos/coq/aymanosman-coq-art-exercises/coq-art-exercises-ff7e2aba35a5094d366be5b9f55dfdd13d38cd48/05_everyday_logic/exercise_04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6859827051172606}}
{"text": "Require Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Sets.Image.\n\nDefinition edge X := X -> X -> Prop.\n\nSection bisim.\n\nVariables (X: Type) (A: edge X)\n  (Y: Type) (B: edge Y).\nDefinition is_bisimulation (r: X -> Y -> Prop) : Prop :=\n (forall c1 c2 d2, (A c1 c2 /\\ r c2 d2 -> exists d1, B d1 d2 /\\ r c1 d1)) /\\\n (forall d1 d2 c2, (B d1 d2 /\\ r c2 d2 -> exists c1, A c1 c2 /\\ r c1 d1)).\n\nEnd bisim.\n\nLemma bisim_id: forall X A, is_bisimulation X A X A eq.\nintros X A.\nunfold is_bisimulation.\nsplit.\nintros c1 c2 d2 [H H0].\nexists c1;\nrewrite H0 in H; auto.\nintros d1 d2 c2 [H H0].\nexists d1.\nrewrite <- H0 in H; auto.\nQed.\n\nDefinition rel_comp {X Y Z} (r1: X -> Y -> Prop) (r2: Y -> Z -> Prop) :=\n  fun x z => exists y, r1 x y /\\ r2 y z.\n\nDefinition rel_inv {X Y} (r: X -> Y -> Prop): Y -> X -> Prop :=\n  fun y x => r x y.\n\nLemma bisim_comp: forall X A Y B Z C,\n  forall r1 r2, is_bisimulation X A Y B r1 -> is_bisimulation Y B Z C r2 ->\n    is_bisimulation X A Z C (rel_comp r1 r2).\nAdmitted.\n\nLemma bisim_inv: forall X A Y B,\n  forall r, is_bisimulation X A Y B r ->\n    is_bisimulation Y B X A (rel_inv r).\nAdmitted.\n\n\nSection set_relation.\nVariables (X: Type) (A: edge X) (a: X)\n  (Y: Type) (B: edge Y) (b: Y).\nDefinition set_equal: Prop :=\n  exists r, is_bisimulation X A Y B r /\\ r a b.\nEnd set_relation.\n\nDefinition set_member (X: Type) (A: edge X) (a: X)\n  (Y: Type) (B: edge Y) (b: Y): Prop :=\n  exists z, set_equal X A a Y B z /\\ B z b.\n\nDefinition set_subset (X: Type) (A: edge X) (a: X)\n  (Y: Type) (B: edge Y) (b: Y): Prop :=\n  forall Z C c, set_member Z C c X A a -> set_member Z C c Y B b.\n\n\nDefinition sum X Y := (X -> Prop) -> (Y -> Prop) -> Prop.\nDefinition inl {X Y} (a: X): sum X Y := fun p _ => p a.\nDefinition inr {X Y} (b: Y): sum X Y := fun _ q => q b.\nDefinition out {X Y} : sum X Y := fun _ _ => False.\n\nDefinition opt X := (X -> Prop) -> Prop.\nDefinition some {X} x: opt X := fun f => f x.\nDefinition none {X}: opt X := fun _ => False.\n\nDefinition cnat := forall X, (X -> X) -> X -> X.\nDefinition zero: cnat := fun f x => x.\nDefinition succ (n: cnat): cnat := fun X f x => f (n X f x).\nDefinition cle (n: cnat) (m: cnat) := forall P: cnat -> Prop, P n -> (forall z, P z -> P (succ z)) -> P m.\nDefinition clt n m := cle (succ n) m.\nDefinition wf_nat n := cle zero n.\n\nProposition inl_inr_disj: forall X Y (x: X) (y: Y), inl (Y := Y) x <> inr y.\nintros X Y x y H.\nspecialize (equal_f (A := X -> Prop) (B := (Y -> Prop) -> Prop) H (fun _ => False)).\nintro H0.\nspecialize (equal_f H0 (fun _ => True)).\nunfold inl, inr.\nintro H1.\nrewrite H1.\nexact I.\nQed.\n\n\nProposition inl_out_disj: forall X Y (x: X), inl (Y := Y) x <> out.\nintros X Y x H.\nspecialize (equal_f (A := X -> Prop) (B := (Y -> Prop) -> Prop) H (fun _ => True)).\nintro H0.\nspecialize (equal_f H0 (fun _ => True)).\nunfold inl, out.\nintro H1.\nrewrite <- H1.\nexact I.\nQed.\n\nProposition inr_out_disj: forall X Y (y: Y), inr (X := X) y <> out.\nintros X Y y H.\nspecialize (equal_f (A := X -> Prop) (B := (Y -> Prop) -> Prop) H (fun _ => True)).\nintro H0.\nspecialize (equal_f H0 (fun _ => True)).\nunfold inr, out.\nintro H1.\nrewrite <- H1.\nexact I.\nQed.\n\nProposition inl_inj: forall X Y, injective _ _(inl (X := X) (Y := Y)).\nintros X Y x1 x2 H.\nspecialize (equal_f H (fun z => z = x1)).\nintro H0.\nspecialize (equal_f H0 (fun _ => True)).\nunfold inl.\nintro.\nsymmetry.\nrewrite <- H1.\nauto.\nQed.\n\nProposition inr_inj: forall X Y, injective _ _ (inr (X := X) (Y := Y)).\nintros X Y y1 y2 H.\nspecialize (equal_f H (fun _ => True)).\nintro H0.\nspecialize (equal_f H0 (fun z => z = y2)).\nunfold inr.\nintro.\nrewrite H1.\nauto.\nQed.\n\n\nGoal forall n, cle n n.\nintros n P H H0.\nauto.\nQed.\n\nGoal forall l m n, cle l m -> cle m n -> cle l n.\nintros l m n H H0 P H1 H2.\napply H0.\napply H.\napply H1.\napply H2.\napply H2.\nQed.\n\n\n(* empty *)\n\nDefinition empty_c := forall X, (X -> X) -> X -> X.\nDefinition empty_e: edge empty_c := fun _ _ => False.\nDefinition empty_b: empty_c := fun _ x => x.\n\nTheorem axiom_empty: forall X A a, ~ set_member X A a empty_c empty_e empty_b.\nintros X A a H.\ndestruct H as [x [H H0]].\nauto.\nQed.\n\n(* pair *)\n\nSection pair.\n\nVariables (X: Type) (A: edge X) (a: X) (Y: Type) (B: edge Y) (b: Y).\nDefinition pair_c := sum X Y.\nDefinition pair_e: edge (sum X Y) :=\n  fun c1 c2 =>\n    (exists a1 a2, c1 = inl a1 /\\ c2 = inl a2 /\\ A a1 a2) \\/\n    (exists b1 b2, c1 = inr b1 /\\ c2 = inr b2 /\\ B b1 b2) \\/\n    (c1 = inl a /\\ c2 = out) \\/\n    (c1 = inr b /\\ c2 = out).\nDefinition pair_b: pair_c := out.\n\nEnd pair.\n\n\nLemma inl_pair_set_equal: forall Z C c X A a Y B b,\n  set_equal Z C c (pair_c X Y) (pair_e X A a Y B b) (inl a)\n  <-> set_equal Z C c X A a.\n\nsplit; intro H.\ndestruct H as [r [H H0]].\nexists (fun z x => r z (inl x)).\nsplit; auto; clear H0 c.\ndestruct H as [H H0].\nsplit.\nclear H0.\nintros c1 c2 d2.\nintros H1; destruct H1 as [H1 H2].\nspecialize (H c1 c2 (inl d2)).\ndestruct H as [d1 H3].\ntauto.\ndestruct H3 as [H H3].\nassert (exists x1, d1 = inl x1 /\\ A x1 d2).\n  destruct H as [H|[H|[H|H]]].\n  destruct H as [a1 [a2 [H [H5 H6]]]].\n  exists a1.\n  apply inl_inj in H5.\n  rewrite <- H5 in H6.\n  tauto.\n  destruct H as [_ [b2 [_ [H _]]]].\n  apply False_ind; apply (inl_inr_disj _ _ d2 b2); auto.\n  apply False_ind; apply (inl_out_disj _ Y d2); tauto.\n  apply False_ind; apply (inl_out_disj _ Y d2); tauto.\n\ndestruct H0 as [x1 [H0 H4]].\nexists x1.\nrewrite <- H0.\ntauto.\n\nclear H.\nintros d1 d0 c0 H1.\ndestruct H1 as [H1 H2].\nadmit.\n\n(* if part *)\n\n\nAdmitted.\n\nLemma inr_pair_set_equal: forall Z C c X A a Y B b,\n  set_equal Z C c (pair_c X Y) (pair_e X A a Y B b) (inr b)\n  <-> set_equal Z C c Y B b.\nAdmitted.\n\nTheorem pair_axiom:\n  forall X A a Y B b Z C c, set_member Z C c (pair_c X Y) (pair_e X A a Y B b) (pair_b X Y)\n    <-> set_equal Z C c X A a \\/ set_equal Z C c Y B b.\nsplit.\n\n\n(* z in {x, y} -> z = x \\/ z = y *)\nintros H.\ndestruct H as [sb [H H0]].\nunfold pair_b in H0.\ncase H0 as [H0| [H0| [H0| H0]]].\n\n(* case 1 *)\ndestruct H0 as [a1 [a2 H0]].\nabsurd (inl (Y := Y) a2 = out).\napply (inl_out_disj X Y a2).\nsymmetry.\ntauto.\n\n(* case 2 *)\ndestruct H0 as [b1 [b2 H0]].\nabsurd (inr (X := X) b2 = out).\napply (inr_out_disj X Y b2).\nsymmetry.\ntauto.\n\n(* case 3 *)\ndestruct H0 as [H0 _].\nleft.\nrewrite H0 in H.\napply inl_pair_set_equal in H.\nauto.\n\n(* case 4 *)\n\ndestruct H0 as [H0 _].\nright.\nrewrite H0 in H.\napply inr_pair_set_equal in H.\nauto.\n\n(* if part *)\nintros H.\ndestruct H as [H | H].\n\n  (* z = x *)\n  unfold set_member.\n  exists (inl a).\n  split.\n  apply inl_pair_set_equal; auto.\n  unfold pair_e.\n  tauto.\n  (* z = y *)\n  unfold set_member.\n  exists (inr b).\n  split.\n  apply inr_pair_set_equal; auto.\n  unfold pair_e.\n  tauto.\nQed.\n\n\nSection pow.\n\nVariable X: Type.\nVariables  (A: edge X) (a: X).\nDefinition pow_c := sum X (X -> Prop).\nDefinition pow_e (b1 b2: pow_c): Prop :=\n  (exists a1 a2, b1 = inl a1 /\\ b2 = inl a2 /\\ A a1 a2)\n  \\/ (exists a1 p, b1 = inl a1 /\\ b2 = inr p /\\ A a1 a /\\ p a1)\n  \\/ (exists p, b1 = inr p /\\ b2 = out).\nDefinition pow_b: pow_c := out.\nEnd pow.\n\nTheorem power_axiom: forall X A a Y B b,\n  set_member X A a (pow_c Y) (pow_e Y B b) (pow_b Y) <-> set_subset X A a Y B b.\nsplit.\n\n(* x in pow y -> x subset y *)\nintro H.\nunfold set_subset.\nintros Z C c H0.\ndestruct H as [s [H H1]].\ndestruct H1 as [H1| [H1| H1]].\n\n(* case 1 *)\ndestruct H1 as [a1 [a2 [H1 [H2 H3]]]].\nunfold pow_b in H2.\nabsurd (inl a2 = out (Y := Y -> Prop)).\napply inl_out_disj.\nsymmetry; auto.\n\n(* case 2 *)\ndestruct H1 as [a1 [p [H1 [H2 [H3 H4]]]]].\nsymmetry in H2.\napply inr_out_disj in H2; case H2.\n\n(* case 3 *)\n\ndestruct H1 as [p [H1 _]].\ndestruct H0 as [u [H0 H2]].\ndestruct H as [rp [H H3]].\ndestruct H0 as [r [H0 H4]].\nexists b.\n\nadmit.\n\n(* x subset y -> x in pow y *)\nadmit.\nAdmitted.\n\nDefinition U :=\n  (forall X: Type, (X -> X -> Prop) -> X -> Prop) -> Prop.\n\nDefinition i: forall X: Type, (X -> X -> Prop) -> X -> U.\nintros X A a f.\nexact (f X A a).\nDefined.\n\nDefinition set (u: U): Prop :=\n  exists X A a, u = i X A a.\n\nDefinition ueq (u1 u2: U): Prop := \nexists X A a Y B b, u1 = i X A a /\\ u2 = i Y B b /\\ set_equal X A a Y B b.\n\nDefinition elt (u1 u2: U): Prop :=\n  exists X A a Y B b, u1 = i X A a /\\ u2 = i Y B b /\\ set_member X A a Y B b.\n\n", "meta": {"author": "koba-e964", "repo": "coqworks", "sha": "d6d154e0fda8adc3d65a4ea78cdbc64993f7c59c", "save_path": "github-repos/coq/koba-e964-coqworks", "path": "github-repos/coq/koba-e964-coqworks/coqworks-d6d154e0fda8adc3d65a4ea78cdbc64993f7c59c/set-theory/iz.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6859826960204541}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import ssreflect ssrbool ssrfun ssrnat eqtype finfun fintype choice seq tuple path.\nFrom mathcomp Require Import finset perm fingroup matrix ssralg.\nRequire Import tools combclass subseq partition Yamanouchi permuted ordtype Schensted plactic Greene_inv std stdtab tableau.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope ring_scope.\nImport GRing.Theory.\nOpen Local Scope ring_scope.\n\n\nSection add_mx.\n(*Not in MathComp (as far as I know) but useful here : \nadding k in a cell of the matrix given by its coordinates\nThis cant be done with a map *)\nFact add_mx_key: unit. Proof. by []. Qed.  \nDefinition add_mx m n (A:'M_(m,n)) k i0 j0 : 'M_(m,n):=\n  \\matrix[add_mx_key]_(i,j) (if (i==i0)&&(j==j0) then ((A i0 j0) + k)%N else A i0 j0). \n  \nEnd add_mx.\n\n\nSection bimon_mat.\n\nVariables m' n': nat.\nNotation m := m'.+1.\nNotation n := n'.+1.\nDefinition alph := ('I_m * 'I_n)%type.\n\nCanonical alph_pordType := Eval hnf in POrdType alph (prodlex_pordMixin _ _).\n\nDefinition alph_ordMixin :=\n  Order.Mixin (T := alph_pordType) (@prodlex_total _ _).\nCanonical alph_ordType :=\n  Eval hnf in OrdType alph alph_ordMixin.\n\nDefinition bimon_of_mat (M : 'M[nat]_(m, n)) : seq alph :=\n  flatten [seq nseq (M a b) (a,b) | a <- enum 'I_m, b <- enum 'I_n].\n\nFixpoint mat_of_bimon (w : seq alph) : 'M_(m,n):=\n  match w with\n  | [::] => \\matrix_(i, j) (0%N)\n  | ((i0, j0) :: b) => let M := mat_of_bimon b in add_mx M 1 i0 j0\n  end.\n\nEnd bimon_mat.\n\n  (*Par récurrence sur le nombre de lignes => utiliser row' ou [u|d]submx ?\n    Dans tous les cas, il faut définir ce qu'est une matrice à laquelle on ajoute une ligne, col_mx doit pouvoir marcher la dessus\n*)\n(*\nDefinition col_mx_ind (A:'M[T]_(m.+1,n)) := let M':= row' (Ordinal (ltnSn m)) A in let r := row (Ordinal (ltnSn m)) A in A = col_mx M' r.\n*)\n\nSection Bla.\n\nVariables m' n': nat.\nNotation m := m'.+1.\nNotation n := n'.+1.\nNotation alph := (alph m' n').\n\nDefinition col_mx_ind (A:'M[nat]_(m'.+1, n'.+1)) :=\n  let M':= row' (Ordinal (ltnSn m')) A in\n  let r := row (Ordinal (ltnSn m')) A in A = col_mx M' r.\n\n\nLemma bimon_lex (M : 'M_(m,n)): is_row (bimon_of_mat M).\nProof.\n  \n  (*\n  elim: m M => [|m0 IHm0 M0].\n  - admit.\n  - *)\nAdmitted.\n\nLemma matK (M:'M_(m,n)): mat_of_bimon (bimon_of_mat M) = M.\nProof.\nAdmitted.\n  \nLemma bimonK (w: seq alph) : is_row w -> bimon_of_mat (mat_of_bimon w) = w.\nProof.\nAdmitted.\n\nDefinition bottomw_of_mat (M:'M_(m,n)): seq 'I_n :=\n  [seq p.2 | p <- (bimon_of_mat M)].\n\nDefinition upw_of_mat (M:'M_(m,n)): seq 'I_m :=\n  [seq p.1 | p <- (bimon_of_mat M)].\n\nEnd Bla.\n\nSection Schensted.\n\nVariables m' n' : nat.\nNotation m := m'.+1.\nNotation n := n'.+1.\nNotation alph := (alph m' n').\n\nFixpoint tab_of_yam_rev y (w: seq 'I_m) : seq (seq 'I_m) :=\n  if y is y0 :: y' then\n    if w is w0 :: w' then\n    append_nth (tab_of_yam_rev y' w') w0 y0\n    else [::]\n  else [::].\n\nDefinition tab_of_yam y w := tab_of_yam_rev y (rev w).\n\nDefinition RSKmap (M : 'M[nat]_(m, n)) : seq (seq 'I_n) * seq (seq 'I_m):=\n  let (P,Q) := RSmap (bottomw_of_mat M) in\n  (P, tab_of_yam Q (upw_of_mat M)).\n\n(*Definition istabpair (pair : seq(seq 'I_n) * seq (seq 'I_m)) :=\n  let: (P,Q) := pair in\n  is_tableau P && is_tableau Q.\n *)\n\nLemma RSKmap_spec M : let (P,Q) := RSKmap M in\n                      is_tableau P && is_tableau Q.\nProof.\n  admit.\nAdmitted.\n\n\n(*Definition de RSKmap_inv :\n-w=[::]\ntant que Q est non nul: \n  -parcourir Q en sens croissant à la recherche du plus grand élément\n  -enlever cet élément i et garder les ligne k_1...k_n dans l'ordre \n  -faire invinstab P [k] -> on obitent P' [j]\n  -w= (i,j)::w\nfin\nretourner w.\n*)                              \n\nVariable T: eqType.\n\nFixpoint remove_in_tab k (Q:seq (seq nat)) compt:=\n  match Q with\n  |(h::t) => let i := index k h in\n             let (Q',l) := remove_in_tab k t compt.+1 in\n             ((take i h)::Q', cat l (nseq (size (drop i h)) compt))\n  |[::] => ([::],[::])\n  end.\n\nFixpoint invinstabseq (P:seq (seq nat)) lnrow: (seq(seq nat)*seq nat):=\n  match lnrow with\n  |(nrow::ln') => let (P',l) := invinstabnrow P nrow in\n                  let (Q,l') := invinstabseq P' ln' in\n                  (Q, l::l')\n  |[::] => ([::],[::])\n  end.\n\n\nFixpoint RSK_inv (pair: seq(seq nat) * seq(seq nat)) (a:nat) : seq (seq (nat*nat)):=\n  let (P,Q) := pair in\n  let (Q',nrow) := remove_in_tab a Q 0 in\n  let (P',l) := invinstabseq P nrow in\n  if a is a'.+1 then\n    [seq (a,j)| j<-l]::RSK_inv (P',Q') a'\n  else\n    [seq (0%N,j)| j<-l] :: [::].\n\nDefinition RSKmap_inv pair:=\n  mat_of_bimon (flatten (RSK_inv pair)).\n\nEnd Schensted.\n", "meta": {"author": "thibautbenjamin", "repo": "ReprSymGroup", "sha": "58bd1e6c8ee838536dfbc1d05ad47d07737f1e7a", "save_path": "github-repos/coq/thibautbenjamin-ReprSymGroup", "path": "github-repos/coq/thibautbenjamin-ReprSymGroup/ReprSymGroup-58bd1e6c8ee838536dfbc1d05ad47d07737f1e7a/src/rsk.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.685982688849848}}
{"text": "Add LoadPath \"/Users/anikaitsingh/Desktop/coqSoftwareFoundations/chapter3/chapter1\".\nAdd LoadPath \"/Users/anikaitsingh/Desktop/coqSoftwareFoundations/chapter3/chapter2\".\nAdd LoadPath \"/Users/anikaitsingh/Desktop/coqSoftwareFoundations/chapter3/chapter3\".\n\nPrint LoadPath. \n\nRequire Export natList.\nRequire Export Basics.\n\n(*List Excercise 1*)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\nintros l.\ninduction l.\n- reflexivity.\n- simpl. rewrite -> IHl. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\nintros l1 l2.\ninduction l1.\n- simpl. induction l2.\n+ reflexivity.\n+ rewrite -> app_nil_r. reflexivity.\n-simpl. induction l2.\n+ simpl. rewrite -> app_nil_r. reflexivity.\n+ simpl. rewrite -> IHl1. simpl. rewrite <-app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\nintros l.\ninduction l.\n- simpl. reflexivity.\n- simpl. rewrite -> rev_app_distr. simpl. rewrite -> IHl. reflexivity.\nQed.\n\n Theorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\nintros l1 l2 l3 l4.\nrewrite -> app_assoc.\nrewrite -> app_assoc.\nreflexivity.\nQed.\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\nintros l1 l2.\ninduction l1.\n- simpl. reflexivity.\n- simpl. destruct n.\n+ rewrite <- IHl1. reflexivity.\n+ simpl. rewrite <- IHl1. reflexivity.\nQed.\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\nmatch l1 with\n|nil => \n  match l2 with \n  |nil => true\n  |a => false\n  end\n|s:: l1' =>\n  match l2 with  \n  |nil => false \n  |x :: l2' => \n    match beq_nat (x) (s) with\n    |true => beq_natlist (l1') (l2')\n    |false => false\n    end\n  end\nend.  \n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\n Proof. reflexivity. Qed.\n\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\n Proof. reflexivity. Qed.\n\nTheorem equality: forall n, beq_nat n n = true.\nProof.\nintros n.\ninduction n.\n- reflexivity.\n- simpl. rewrite <- IHn. reflexivity.\nQed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\n Proof. \nintros l.\ninduction l.\n- reflexivity.\n- simpl. rewrite <- IHl. simpl. rewrite -> equality. reflexivity.\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(*list exercise 2*)\nTheorem count_member_nonzero : forall(s : bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\nintros s.\nsimpl. reflexivity. Qed.\n\n Theorem 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.\nintros s.\ninduction s.\n- simpl. reflexivity.\n- simpl. destruct n.\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.\nintros l1 l2.\nintros H.\nrewrite <- rev_involutive.\nrewrite <- H.\nrewrite -> rev_involutive.\nreflexivity.\nQed.\n\n\n(*Options*)\n\n Inductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\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 beq_nat n O then Some a\n               else nth_error' l' (pred n)\n  end.\n\n Definition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n\nDefinition hd_error (l : natlist) : natoption :=\nmatch l with\n| nil => None\n| s :: n => Some s\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\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\nintros l.\nintros default.\ndestruct l.\n- simpl. reflexivity.\n- simpl. reflexivity.\nQed.\n\n(*Partial Map*)\n\n Inductive id : Type :=\n  | Id : nat -> id.\n\n Definition beq_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\nintros x.\ndestruct x.\nsimpl. rewrite -> equality. reflexivity. \nQed.\n\nInductive partial_map : Type :=\n  | empty : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\n Definition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n  match d with\n  | empty => None\n  | record y v d' => if beq_id x y\n                     then Some v\n                     else find x d'\n  end.\n\nTheorem update_eq :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\nintros d x v.\nsimpl.\ndestruct x.\nsimpl.\ninduction n.\n- reflexivity.\n- simpl.  rewrite -> equality. reflexivity. \nQed.\n\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    beq_id x y = false -> find x (update d y o) = find x d.\nProof.\nintros d x y o.\nsimpl.\nintros H.\nrewrite -> H. reflexivity.\nQed.\n\nInductive baz : Type :=\n  | Baz1 : baz -> baz\n  | Baz2 : baz -> bool -> baz.\n\n(*no constructor that defines a distinct baz. Such as O in a nat. Thus, 0 elements can be created from this definition.*)\n\n\n\n\n\n\n \n\n\n\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/listProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709795, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.6859747670438201}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Reflection between booleans and propositions                            *\n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibTactics.\nRequire Export LibBool LibLogic.\n\nImplicit Type P : Prop.\nImplicit Type b : bool.\n\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Reflection between booleans and propositions *)\n\n(** - [istrue b] produces a proposition that is [True] if and only if\n      the boolean [b] is equal to [true].\n\n    - [isTrue P] produces a boolean expression that is [true] if and only\n      if the proposition [P] is equal to [True]. *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Translation from booleans into propositions *)\n\n(** Any boolean [b] can be viewed as a proposition through the\n    relation [b = true]. *)\n\nCoercion istrue (b : bool) : Prop := (b = true).\n\n(** Specification *)\n\nLemma istrue_eq_eq_true : forall b,\n  istrue b = (b = true).\nProof using. reflexivity. Qed.\n\nLemma istrue_true_eq : \n  istrue true = True.\nProof using. rewrite istrue_eq_eq_true. extens*. Qed.\n\nLemma istrue_false_eq : \n  istrue false = False.\nProof using. rewrite istrue_eq_eq_true. extens. iff; auto_false. Qed.\n\nGlobal Opaque istrue.\n\n(** Proving the goals [true] and [~ false] *)\n\nLemma istrue_true : istrue true. (* [true] *)\nProof using. reflexivity. Qed.\n\nLemma not_istrue_false : ~ (istrue false). (* ~ false. *)\nProof using. rewrite istrue_false_eq. intuition. Qed.\n\n(** Equivalence of [false] and [False] *)\n\nLemma false_of_False : \n  False -> \n  false.\nProof using. intros K. false. Qed.\n\nLemma False_of_false : \n  false -> \n  False.\nProof using. intros K. rewrite~ istrue_false_eq in K. Qed.\n\n(** Hints for proving [false] and [False] *)\n\nHint Resolve istrue_true not_istrue_false.\n\nHint Extern 1 (istrue false) =>\n  apply false_of_False.\n\nHint Extern 1 (False) => match goal with\n  | H: istrue false |- _ => apply (not_istrue_false H) end.\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Translation from propositions into booleans *)\n\n(** The expression [isTrue P] evaluates to [true] if and only if\n    the proposition [P] is [True]. *)\n\nDefinition isTrue (P : Prop) : bool :=\n  If P then true else false.\n\n(** Specification *)\n\nLemma isTrue_eq_if : forall P,\n  isTrue P = If P then true else false.\nProof using. reflexivity. Qed.\n\nLemma isTrue_True : \n  isTrue True = true.\nProof using. unfolds. case_if; auto_false~. Qed.\n\nLemma isTrue_False : \n  isTrue False = false.\nProof using. unfolds. case_if; auto_false~. Qed.\n\nGlobal Opaque isTrue.\n\n(** Lemmas *)\n\nLemma isTrue_eq_true : forall P,\n  P -> \n  isTrue P = true.\nProof using. intros. rewrite isTrue_eq_if. case_if*. Qed.\n\nLemma isTrue_eq_false : forall P,\n  ~ P -> \n  isTrue P = false.\nProof using. intros. rewrite isTrue_eq_if. case_if*. Qed.\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Extensionality for boolean equality, stated using [istrue] *)\n\nLemma bool_ext : forall b1 b2,\n  (b1 <-> b2) -> \n  b1 = b2.\nProof using.\n  destruct b1; destruct b2; intros; auto_false.\n  destruct H. false H; auto.\n  destruct H. false H0; auto.\nQed.\n\nLemma bool_ext_eq : forall b1 b2,\n  (b1 = b2) = (b1 <-> b2).\nProof using.\n  intros. extens. iff M. { subst*. } { applys* bool_ext. }\nQed.\n\nInstance Extensionality_bool : Extensionality bool.\nProof using. apply (Extensionality_make bool_ext). Defined.\n\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Rewriting rules *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Rewriting rules for distributing [istrue] *)\n\nLemma istrue_isTrue_eq : forall P,\n  istrue (isTrue P) = P.\nProof using. extens. rewrite isTrue_eq_if. case_if; auto_false*. Qed.\n\nLemma istrue_neg_eq : forall b,\n  istrue (!b) = ~ (istrue b).\nProof using. extens. tautob. Qed.\n\nLemma istrue_and_eq : forall b1 b2,\n  istrue (b1 && b2) = (istrue b1 /\\ istrue b2).\nProof using. extens. tautob. Qed.\n\nLemma istrue_or_eq : forall b1 b2,\n  istrue (b1 || b2) = (istrue b1 \\/ istrue b2).\nProof using. extens. tautob. Qed.\n\n(** Corollary *)\n\nLemma istrue_neg_isTrue : forall P,\n  istrue (! isTrue P) = ~ P.\nProof using. intros. rewrite istrue_neg_eq. rewrite~ istrue_isTrue_eq. Qed.\n\n(** [istrue] and conditionals *)\n\nLemma If_istrue : forall b A (x y : A),\n    (If istrue b then x else y) \n  = (if b then x else y).\nProof using. intros. case_if as C; case_if as D; auto. Qed.\n\nLemma istrue_If_eq : forall P b1 b2,\n    istrue (If P then b1 else b2) \n  = (If P then istrue b1 else istrue b2).\nProof using. extens. case_if*. Qed.\n\nLemma istrue_if_eq : forall b1 b2 b3,\n    istrue (if b1 then b2 else b3) \n  = (If istrue b1 then istrue b2 else istrue b3).\nProof using. intros. do 2 case_if; auto. Qed.\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Rewriting rules for distributing [isTrue] *)\n\nLemma isTrue_istrue : forall b,\n  isTrue (istrue b) = b.\nProof using. extens. rewrite* istrue_isTrue_eq. Qed.\n\nLemma isTrue_not : forall P,\n  isTrue (~ P) = ! isTrue P.\nProof using. extens. do 2 rewrite isTrue_eq_if. do 2 case_if; auto_false*. Qed.\n\nLemma isTrue_and : forall P1 P2,\n  isTrue (P1 /\\ P2) = (isTrue P1 && isTrue P2).\nProof using. extens. do 3 rewrite isTrue_eq_if. do 3 case_if; auto_false*. Qed.\n\nLemma isTrue_or : forall P1 P2,\n  isTrue (P1 \\/ P2) = (isTrue P1 || isTrue P2).\nProof using. extens. do 3 rewrite isTrue_eq_if. do 3 case_if; auto_false*. Qed.\n\n(** Corollary *)\n\nLemma isTrue_not_istrue : forall b,\n  isTrue (~ istrue b) = !b.\nProof using. intros. rewrite isTrue_not. rewrite~ isTrue_istrue. Qed.\n\n(** Simplification of equalities involving isTrue *)\n\nSection IsTrueEqualities.\n\nLtac prove_isTrue_lemma :=\n  intros; try extens; try iff; rewrite isTrue_eq_if in *; case_if; auto_false*.\n\nLemma true_eq_isTrue_eq : forall P,\n  (true = isTrue P) = P.\nProof using. prove_isTrue_lemma. Qed.\n\nLemma isTrue_eq_true_eq : forall P,\n  (isTrue P = true) = P.\nProof using. prove_isTrue_lemma. Qed.\n\nLemma false_eq_isTrue_eq : forall P,\n  (false = isTrue P) = ~ P.\nProof using. prove_isTrue_lemma. Qed.\n\nLemma isTrue_eq_false_eq : forall P,\n  (isTrue P = false) = ~ P.\nProof using. prove_isTrue_lemma. Qed.\n\nLemma isTrue_eq_isTrue_eq : forall P1 P2,\n  (isTrue P1 = isTrue P2) = (P1 <-> P2).\nProof using.\n  intros. extens. iff; repeat rewrite isTrue_eq_if in *;\n  repeat case_if; auto_false*.\nQed.\n\nEnd IsTrueEqualities.\n\n(** [isTrue] and conditionals *)\n\nLemma if_isTrue : forall P A (x y : A),\n    (if isTrue P then x else y) \n  = (If P then x else y).\nProof using.\n  intros. case_if as C; case_if as D; auto.\n  { rewrite* isTrue_eq_true_eq in C. } \n  { rewrite* isTrue_eq_false_eq in C. } \nQed.\n\nLemma isTrue_If : forall P1 P2 P3,\n    isTrue (If P1 then P2 else P3) \n  = If P1 then isTrue P2 else isTrue P3.\nProof using. extens. case_if*. Qed.\n\nLemma isTrue_If_eq_if_isTrue : forall P1 P2 P3,\n    isTrue (If P1 then P2 else P3) \n  = (if isTrue P1 then isTrue P2 else isTrue P3).\nProof using. intros. rewrite if_isTrue. rewrite~ isTrue_If. Qed.\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Lemmas for testing booleans *)\n\nLemma bool_inv_or : forall b,\n  b \\/ !b.\nProof using. tautob. Qed.\n\nLemma bool_inv_or_eq : forall b,\n  b = true \\/ b = false.\nProof using. tautob. Qed.\n\nLemma xor_inv_or : forall b1 b2,\n  xor b1 b2 -> \n     (b1 = true /\\ b2 = false)\n  \\/ (b1 = false /\\ b2 = true).\nProof using. tautob; auto_false*. Qed.\n\nArguments xor_inv_or [b1] [b2].\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Lemmas for normalizing [b = true] and [b = false] terms *)\n\nLemma bool_eq_true_eq : forall b,\n  (b = true) = istrue b.\nProof using. extens. tautob. Qed.\n\nLemma bool_eq_false_eq : forall b,\n  (b = false) = istrue (!b).\nProof using. extens. tautob. Qed.\n\nLemma true_eq_bool_eq : forall b,\n  (true = b) = istrue b.\nProof using. extens. tautob. Qed.\n\nLemma false_eq_bool_eq : forall b,\n  (false = b) = istrue (!b).\nProof using. extens. tautob. Qed.\n\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Tactics *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Tactics [rew_istrue] to distribute [istrue] *)\n\n(** [rew_istrue] distributes [istrue]. It is useful to replace all\n    boolean operators with corresponding logical operators. *)\n\nHint Rewrite istrue_true_eq istrue_false_eq istrue_isTrue_eq\n  istrue_neg_eq istrue_and_eq istrue_or_eq \n  If_istrue istrue_If_eq istrue_if_eq: rew_istrue.\n\nTactic Notation \"rew_istrue\" :=\n  autorewrite with rew_istrue.\nTactic Notation \"rew_istrue\" \"in\" hyp(H) :=\n  autorewrite with rew_istrue in H.\nTactic Notation \"rew_istrue\" \"in\" \"*\" :=\n  autorewrite_in_star_patch ltac:(fun tt => autorewrite with rew_istrue).\n  (* autorewrite with rew_istrue in *. *)\n\nTactic Notation \"rew_istrue\" \"~\" :=\n  rew_istrue; auto_tilde.\nTactic Notation \"rew_istrue\" \"~\" \"in\" hyp(H) :=\n  rew_istrue in H; auto_tilde.\nTactic Notation \"rew_istrue\" \"~\" \"in\" \"*\" :=\n  rew_istrue in *; auto_tilde.\n\nTactic Notation \"rew_istrue\" \"*\" :=\n  rew_istrue; auto_star.\nTactic Notation \"rew_istrue\" \"*\" \"in\" hyp(H) :=\n  rew_istrue in H; auto_star.\nTactic Notation \"rew_istrue\" \"*\" \"in\" \"*\" :=\n  rew_istrue in *; auto_star.\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Tactics [rew_isTrue] to distribute [isTrue] *)\n\n(** [rew_isTrue] distributes [isTrue]. \n    This tactic is probably much less useful than [rew_istrue], since logical\n    operators are often simpler to work with. *)\n\nHint Rewrite isTrue_True isTrue_False isTrue_istrue\n  isTrue_not isTrue_and isTrue_or \n  if_isTrue isTrue_If : rew_isTrue.\n\nTactic Notation \"rew_isTrue\" :=\n  autorewrite with rew_isTrue.\nTactic Notation \"rew_isTrue\" \"in\" hyp(H) :=\n  autorewrite with rew_isTrue in H.\nTactic Notation \"rew_isTrue\" \"in\" \"*\" :=\n  autorewrite_in_star_patch ltac:(fun tt => autorewrite with rew_isTrue).\n  (* autorewrite with rew_isTrue in *. *)\n\nTactic Notation \"rew_isTrue\" \"~\" :=\n  rew_isTrue; auto_tilde.\nTactic Notation \"rew_isTrue\" \"~\" \"in\" hyp(H) :=\n  rew_isTrue in H; auto_tilde.\nTactic Notation \"rew_isTrue\" \"~\" \"in\" \"*\" :=\n  rew_isTrue in *; auto_tilde.\n\nTactic Notation \"rew_isTrue\" \"*\" :=\n  rew_isTrue; auto_star.\nTactic Notation \"rew_isTrue\" \"*\" \"in\" hyp(H) :=\n  rew_isTrue in H; auto_star.\nTactic Notation \"rew_isTrue\" \"*\" \"in\" \"*\" :=\n  rew_isTrue in *; auto_star.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Tactics useful for program verification, when reasoning about \n       the result of if-statements over boolean expressions, i.e. \n       an expression of the form [b = ..] or [.. = b], which produces\n       hypotheses of the form [true = ..] and [false = ..] or symmetric.\n       It is used as post-treatment for tactic [case_if]. *)\n\nHint Rewrite\n  true_eq_isTrue_eq isTrue_eq_true_eq\n  false_eq_isTrue_eq isTrue_eq_false_eq\n  isTrue_eq_isTrue_eq\n  not_not_eq\n  istrue_true_eq istrue_false_eq istrue_isTrue_eq\n  istrue_neg_eq istrue_and_eq istrue_or_eq\n  bool_eq_true_eq bool_eq_false_eq true_eq_bool_eq false_eq_bool_eq\n  : rew_bool_eq.\n\nTactic Notation \"rew_bool_eq\" :=\n  autorewrite with rew_bool_eq.\nTactic Notation \"rew_bool_eq\" \"~\" :=\n  rew_bool_eq; auto_tilde.\nTactic Notation \"rew_bool_eq\" \"*\" :=\n  rew_bool_eq; auto_star.\n\nTactic Notation \"rew_bool_eq\" \"in\" hyp(H) :=\n  autorewrite with rew_bool_eq in H.\nTactic Notation \"rew_bool_eq\" \"~\" \"in\" hyp(H) :=\n  rew_bool_eq in H; auto_tilde.\nTactic Notation \"rew_bool_eq\" \"*\" \"in\" hyp(H) :=\n  rew_bool_eq in H; auto_star.\n\nTactic Notation \"rew_bool_eq\" \"in\" \"*\" :=\n  autorewrite_in_star_patch ltac:(fun tt => autorewrite with rew_bool_eq).\n  (* autorewrite with rew_bool_eq in *. *)\nTactic Notation \"rew_bool_eq\" \"~\" \"in\" \"*\" :=\n  rew_bool_eq; auto_tilde.\nTactic Notation \"rew_bool_eq\" \"*\" \"in\" \"*\" :=\n  rew_bool_eq; auto_star.\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Tactics extended for reflection *)\n\n(** Extension of the tactic [case_if] to automatically performs\n    simplification using [logics]. \n    \n    For less aggressive introduction of [istrue], consider rewriting\n    without the lemmas:\n    [bool_eq_true_eq bool_eq_false_eq true_eq_bool_eq false_eq_bool_eq]\n*)\n\nLtac case_if_post H ::= \n  rew_bool_eq in H; tryfalse.\n\n(** Extension of the tactic [test_dispatch] from LibLogic.v, so as to\n    be able to call the tactic [tests] directly on boolean expressions *)\n\nLtac tests_bool_base E H1 H2 :=\n  tests_prop_base (istrue E) H1 H2.\n\nLtac tests_dispatch E H1 H2 ::=\n  match type of E with\n  | bool => tests_bool_base E H1 H2\n  | Prop => tests_prop_base E H1 H2\n  | {_}+{_} => tests_ssum_base E H1 H2\n  end.\n\n(** Extension of the tactic [apply_to_head_of] (see LibTactics). *)\n\nLtac apply_to_head_of E cont ::=\n  let go E := let P := get_head E in cont P in\n  match E with\n  | istrue ?A => go A\n  | istrue (neg ?A) => go A\n  | ?A = ?B => first [ go A | go B ]\n  | ?A => go A\n  end.\n\n", "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/LibReflect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.6859747533368036}}
{"text": "\n\nDefinition Regular_Induction := forall P, (P(0) /\\ (forall k, P(k) -> P(S k)))\n                                            -> (forall n, P(n)).\nDefinition Strong_Induction := forall P, (P(0) /\\\n                                         (forall k, (forall m, m <= k -> P(m)) -> P(S k)))\n                                            -> (forall n, P(n)).\n\nDefinition Generalized_Strong_Induction := forall P, P(0) /\\\n                                                     (forall k, (forall m, m <= k -> P(m)) -> P(S k))\n                                                     -> forall n m, m <= n -> P(m).\n\n\nLemma regular_implies_generalized_strong:\n  Regular_Induction -> Generalized_Strong_Induction.\nProof.\n  unfold Regular_Induction. unfold Generalized_Strong_Induction.\n  intros RI P H1.\n  induction n.\n  - intros m H2. inversion H2.  destruct H1. assumption.\n  - intros m H2. inversion H2.\n    + destruct H1. apply H1. intros m0 H3. apply IHn. assumption.\n    + apply IHn. assumption.\nQed.\n\n\n\nLemma generalized_strong_implies_strong:\n  Generalized_Strong_Induction -> Strong_Induction.\n  unfold Generalized_Strong_Induction. unfold Strong_Induction.\n  intros. specialize (H P). pose proof (H H0) as H1.\n  specialize (H1 n). specialize (H1 n).  apply H1. constructor.\nQed.\n\nLemma regular_implies_strong:\n  Regular_Induction -> Strong_Induction.\nProof.\n  intro H.\n  apply generalized_strong_implies_strong.\n  apply regular_implies_generalized_strong.\n  assumption.\nQed.\n\n\nLemma strong_implies_regular: Strong_Induction -> Regular_Induction.\nProof.\n  unfold Strong_Induction.  unfold Regular_Induction.\n  intros SI P H.\n  apply SI.\n  split.\n  - destruct H. apply H.\n  - intro k. intro A.\n    destruct H.  apply H0. apply A. auto.\nQed.\n\nTheorem strong_equals_regular: Strong_Induction <-> Regular_Induction.\n  split.\n  apply strong_implies_regular.\n  apply regular_implies_strong.\nQed.", "meta": {"author": "linoscope", "repo": "strongInd_equals_regularInd", "sha": "b9a2fcd9a0135561e908a360bbe6f6a7d5ff05ec", "save_path": "github-repos/coq/linoscope-strongInd_equals_regularInd", "path": "github-repos/coq/linoscope-strongInd_equals_regularInd/strongInd_equals_regularInd-b9a2fcd9a0135561e908a360bbe6f6a7d5ff05ec/strongInd_equals_regularInd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.6859747485497749}}
{"text": "Require Import Axiom_Extensionality.\nRequire Import Axiom_ProofIrrelevance.\nRequire Import Axiom_PropEqual.\n\nDefinition Relation (a b:Type) : Type := a -> b -> Prop.\n\nLemma eqRelation : forall (a b:Type) (r s:Relation a b),\n    (forall x y, r x y <-> s x y) -> r = s.\nProof.\n    intros a b r s H. apply extensionality2. intros x y.\n    apply eqProp. apply H. apply H.\nQed.\n\nDefinition Total (a b:Type) (r:Relation a b) : Prop :=\n    forall (x:a), exists (y:b), r x y.\n\nArguments Total {a} {b} _.\n\nDefinition Functional (a b:Type) (r:Relation a b) : Prop :=\n    forall (x:a) (y y':b), r x y -> r x y' -> y = y'.\n\nArguments Functional {a} {b} _.\n\nInductive Func (a b:Type) : Type :=\n    func : forall (r:Relation a b), Total r -> Functional r -> Func a b.\n\nArguments func {a} {b} _ _ _.\n\nNotation \"a ==> b\" := (Func a b) (at level 60, right associativity).\n\nDefinition rel (a b:Type) (f:a ==> b) : Relation a b :=\n    match f with\n    | func r _ _ => r\n    end.\n\nArguments rel {a} {b} _ _ _.\n\nLemma eqFunc : forall (a b:Type) (f g:a ==> b), rel f = rel g -> f = g.\nProof.\n    intros a b f g H. destruct f as [r fTot fFunc]. destruct g as [s gTot gFunc].\n    simpl in H. revert gTot gFunc fTot fFunc. rewrite H. clear H r.\n    intros gTot gFunc fTot fFunc.\n    rewrite (proof_irrelevance _ gTot fTot).\n    rewrite (proof_irrelevance _ gFunc fFunc).\n    reflexivity.\nQed.\n\nLemma eqFunc2 : forall (a b:Type) (f g:a ==> b), \n    (forall (x:a) (y:b), rel f x y <-> rel g x y) <-> f = g.\nProof.\n    intros a b f g. split.\n    - intros H. apply eqFunc. apply eqRelation. exact H.\n    - intros H x y. split.\n        + intros H'. rewrite <- H. exact H'.\n        + intros H'. rewrite H. exact H'.\nQed.\n\n\nLemma Func_exists : forall (a b:Type) (f:a ==> b) (x:a), \n    exists y, rel f x y. \nProof.\n    intros a b [r fTot fFunc] x. destruct (fTot x) as [y Hy].\n    exists y. exact Hy.\nQed.\n\nArguments Func_exists {a} {b} _ _.\n\nLemma Func_unique : forall (a b:Type) (f:a ==> b) (x:a) (y y':b),\n    rel f x y -> rel f x y' -> y = y'.\nProof.\n    intros a b [r fTot fFunc] x y y' Hy Hy'. simpl in Hy, Hy'.\n    apply (fFunc x). exact Hy. exact Hy'.\nQed.\n\nArguments Func_unique {a} {b} _ _ _ _ _ _.\n\nDefinition toRel (a b:Type) (f:a -> b): Relation a b :=\n    fun (x:a) (y:b) => f x = y.\n\nArguments toRel {a} {b} _ _ _.\n\nLemma toRelTotal : forall (a b:Type) (f:a -> b), Total (toRel f).\nProof.\n    intros a b f. unfold Total. intros x. unfold toRel. \n    exists (f x). reflexivity.\nQed.\n\nArguments toRelTotal {a} {b} _ _.\n\nLemma toRelFunctional : forall (a b:Type) (f:a -> b), Functional (toRel f).\nProof.\n    intros a b f. unfold Functional. intros x y y' Hy Hy'.\n    unfold toRel in Hy. unfold toRel in Hy'. rewrite <- Hy, <-Hy'.\n    reflexivity.\nQed.\n\nArguments toRelFunctional {a} {b} _ _ _ _ _ _.\n\n\nDefinition toFunc (a b:Type) (f:a -> b) : a ==> b :=\n    func (toRel f) (toRelTotal f) (toRelFunctional f).\n\nArguments toFunc {a} {b} _.\n\nLemma relToFunc : forall (a b:Type) (f:a -> b) (x:a) (y:b),\n    rel (toFunc f) x y = (f x = y).\nProof.\n    intros a b f x y. unfold toFunc. simpl. unfold toRel. reflexivity.\nQed.\n\nDefinition toRelComp (a b c:Type) (f:a ==> b) (g:b ==> c) : Relation a c :=\n    match f with\n      func r _ _  =>  \n        match g with\n          func s _ _  => \n            fun (x:a) => \n              fun (z:c) => \n                exists (y:b), r x y /\\ s y z \n        end\n    end.\n\nArguments toRelComp {a} {b} {c} _ _ _ _.\n\nLemma toRelCompTotal : forall (a b c:Type) (f:a ==> b) (g:b ==> c),\n    Total(toRelComp f g).\nProof.\n    intros a b c [r fTot fFunc] [s gTot gFunc]. unfold Total. intros x. \n    unfold toRelComp. destruct (fTot x) as [y Hy]. destruct (gTot y) as [z Hz].\n    exists z, y. split.\n    - exact Hy.\n    - exact Hz.\nQed.\n\nArguments toRelCompTotal {a} {b} {c} _ _ _.\n\nLemma toRelCompFunctional : forall (a b c:Type) (f:a ==> b) (g:b ==> c),\n    Functional(toRelComp f g).\nProof.\n    intros a b c [r fTot fFunc] [s gTot gFunc]. unfold Functional.\n    intros x z z'. unfold toRelComp. intros [y [Hy Hz]] [y' [Hy' Hz']].\n    assert (y = y') as E. { apply (fFunc x y y' Hy Hy'). }\n    apply (gFunc y z z' Hz). rewrite E. exact Hz'. \nQed.\n\nArguments toRelCompFunctional {a} {b} {c} _ _ _ _ _ _ _.\n\nDefinition composeFunc (a b c:Type) (f:a ==> b) (g:b ==> c) : a ==> c :=\n    func (toRelComp f g) (toRelCompTotal f g) (toRelCompFunctional f g).\n\nArguments composeFunc {a} {b} {c} _ _.\n\n\nNotation \"f ; g\" := (composeFunc f g) (at level 40, left associativity).\n\n\nLemma composeFunc_assoc:forall (a b c d:Type)(f:a ==> b)(g:b ==> c)(h: c ==> d),\n    f;g;h = f;(g;h).\nProof.\n    intros a b c d f g h. apply eqFunc2. intros x t.\n    destruct f as [rf fTot fFunc].\n    destruct g as [rg gTot gFunc].\n    destruct h as [rh hTot hFunc].\n    simpl. split.\n    - intros [z [[y [H1 H2]] H3]]. exists y. split.\n        + exact H1.\n        + exists z. split.\n            { exact H2. }\n            { exact H3. }\n    - intros [y [H1 [z [H2 H3]]]]. exists z. split.\n        + exists y. split.\n            { exact H1. }\n            { exact H2. }\n        + exact H3.\nQed.\n\nDefinition idRel (a:Type) : Relation a a := fun (x y:a) => y = x.\n\nLemma idRelTotal : forall (a:Type), Total (idRel a).\nProof. intros a. unfold Total. intros x. exists x. reflexivity. Qed.\n\n\nLemma idRelFunctional : forall (a:Type), Functional (idRel a).\nProof.\n    intros a. unfold Functional. intros x y y'. unfold idRel. intros Hy Hy'.\n    rewrite Hy, Hy'. reflexivity.\nQed.\n\nDefinition idFunc (a:Type) : a ==> a :=\n    func (idRel a) (idRelTotal a) (idRelFunctional a).\n\nDefinition compose (a b c:Type) (f:a -> b) (g:b -> c) : a -> c :=\n    fun (x:a) => g (f x).\n\nArguments compose {a} {b} {c} _ _ _.\n\nNotation \"g @ f\" := (compose f g) (at level 60, right associativity).\n\nLemma compose_assoc : forall (a b c d:Type) (f:a -> b) (g:b-> c) (h:c -> d),\n    h @ g @ f = (h @ g) @ f.\nProof.\n    intros a b c d f g h. apply extensionality. intros x. reflexivity.\nQed.\n\nDefinition id (a:Type) : a-> a := fun (x:a) => x.\n\nArguments id {a} _.\n\n\nLemma toFunc_compose : forall (a b c:Type) (f:a -> b) (g:b -> c),\n    toFunc (g @ f) = toFunc f ; toFunc g.\nProof.\n    intros a b c f g. apply eqFunc. unfold compose, composeFunc. simpl.\n    apply eqRelation. unfold toRel. intros x z. split.\n    - intros H. exists (f x). split.\n        + reflexivity.\n        + exact H.\n    - intros [y [H1 H2]]. rewrite H1. exact H2.\nQed.\n\n\nLemma toFunc_id : forall (a:Type), toFunc (id) = idFunc a.\nProof.\n    intros a. apply eqFunc2. intros x y. simpl. unfold idRel, toRel, id. split.\n    - intros H. symmetry. exact H.\n    - intros H. symmetry. 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/cat/Func.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764119, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.6859747351500443}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type :=  Nil : lst | Cons : natural -> lst -> lst .\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint 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. lfind.  simpl.  rewrite (eq_refl : Cons n Nil = rev (Cons n Nil)).  rewrite IHx.  rewrite rev_rev.  simpl.  reflexivity. \nAdmitted.\n              \n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/clam_lf_goal80_theorem0_59_rev_append/goal80.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.6859707434972593}}
{"text": "Require Export Relations Morphisms Setoid Equalities SetoidClass.\nRequire Import Basics.\nRequire Import Setof. \n\nClass SemiGroup {A} `{A_setoid : Setoid A} (op : A -> A -> A) :=\n  {\n     op_morphism :> Proper (equiv ==> equiv ==> equiv) op;\n     op_assoc : forall a1 a2 a3, op (op a1 a2) a3 == op a1 (op a2 a3)\n}.\n\nClass Monoid {A} `{A_setoid : Setoid A} (op : A -> A -> A) :=\n    {\n     wm :> SemiGroup op;\n     unit : A;\n     unit_lunit : forall a, op unit a == a;\n     unit_runit : forall a, op a unit == a\n}.\n\nClass Commutative {A} `{A_setoid : Setoid A} (op : A -> A -> A) :=\n  { op_commut : forall a1 a2, op a1 a2 == op a2 a1 }.\n\nClass Zero {A} `{A_setoid : Setoid A} (op : A -> A -> A) :=\n  { zero : A;\n    op_zero : forall a1, op a1 zero == zero }.\n\nClass Zeros {A} `{A_setoid : Setoid A} (op : A -> A -> A) :=\n  { zeros : Setof (A:=A) ;\n    op_zeros : forall zero, zeros zero -> forall a1, zeros (op a1 zero);\n    exist_zero : exists zero, zeros zero}.\n\n\nClass ManyUnits {A} `{A_setoid : Setoid A} (op : A -> A -> A)\n\t`{A_zero : Zeros A op} :=\n  { \n\tmany_units : \n\t   forall x, exists u, op x u == x \n\t                       /\\ (forall y, op y u == y \\/ zeros (op y u)) \n}.\n\nProgram Instance zeros_zero {A} `{A_setoid : Setoid A} (op : A -> A -> A) \n    { _ : Zero op} {_ : Proper (equiv ==> equiv ==> equiv) op}\n    : Zeros op := { zeros := singleton zero }.\nNext Obligation.\nexists zero.   split; try reflexivity. \nrewrite H3. rewrite H2.\napply op_zero.\nQed.\nNext Obligation.\nexists zero. exists zero. split; reflexivity.\nQed.    \n", "meta": {"author": "resource-reasoning", "repo": "coq", "sha": "6561111ab25f5e956a1fe726d5e244a92f893850", "save_path": "github-repos/coq/resource-reasoning-coq", "path": "github-repos/coq/resource-reasoning-coq/coq-6561111ab25f5e956a1fe726d5e244a92f893850/views/Monoids.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6859292695987973}}
{"text": "Require Import Coq.Arith.Arith\n               Coq.Numbers.Natural.Peano.NPeano\n               List.\n\nImport ListNotations.\nImport Nat. (* For 8.5.0 *)\nDefinition key := nat.\n\nInductive tree : Type :=\n|  Node: key -> tree -> tree -> tree\n|  Leaf : tree.\n\nDefinition priqueue := list tree.\n\nDefinition empty : priqueue := nil.\n\nNotation  \"a >? b\" := (ltb b a) (at level 70, only parsing) : nat_scope.\n\nDefinition smash (t u:  tree) : tree :=\n  match t , u with\n  |  Node x t1 Leaf, Node y u1 Leaf => \n                   if  x >? y then Node x (Node y u1 t1) Leaf\n                                else Node y (Node x t1 u1) Leaf\n  | _ , _ => Leaf  (* arbitrary bogus tree *)\n  end.\n\nFixpoint carry (q: list tree) (t: tree) : list tree := \n  match q, t with\n  | nil, Leaf        => nil\n  | nil, _            => t :: nil\n  | Leaf :: q', _  => t :: q'\n  | u :: q', Leaf  => u :: q'\n  | u :: q', _       => Leaf :: carry q' (smash t u)\n end.\n\nDefinition insert (x: key) (q: priqueue) : priqueue := \n     carry q (Node x Leaf Leaf).\n\nFixpoint join (p q: priqueue) (c: tree) : priqueue :=\n  match p, q, c with\n  | [], _ , _            => carry q c\n  | _, [], _             => carry p c\n  | Leaf::p', Leaf::q', _              => c :: join p' q' Leaf\n  | Leaf::p', q1::q', Leaf            => q1 :: join p' q' Leaf\n  | Leaf::p', q1::q', Node _ _ _  => Leaf :: join p' q' (smash c q1)\n  | p1::p', Leaf::q', Leaf            => p1 :: join p' q' Leaf\n  | p1::p', Leaf::q',Node _ _ _   => Leaf :: join p' q' (smash c p1)\n  | p1::p', q1::q', _                   => c :: join p' q' (smash p1 q1)\n  end.\n\nFixpoint unzip (t: tree) (cont: priqueue -> priqueue) : priqueue :=\n  match t with\n  | Node x t1 t2   => unzip t2 (fun q => Node x t1 Leaf  :: cont q)\n  | Leaf => cont nil\n  end.\n\nDefinition heap_delete_max (t: tree) : priqueue :=\n  match t with \n    Node x t1 Leaf  => unzip t1 (fun u => u)\n  | _ => nil   (* bogus value for ill-formed or empty trees *)\n  end.\n\nFixpoint find_max' (current: key) (q: priqueue) : key :=\n  match q with\n  |  []         => current\n  | Leaf::q' => find_max' current q'\n  | Node x _ _ :: q' => find_max' (if x >? current then x else current) q'\n  end.\n\nFixpoint find_max (q: priqueue) : option key :=\n  match q with\n  | [] => None\n  | Leaf::q' => find_max q'\n  | Node x _ _ :: q' => Some (find_max' x q')\n end.\n\nFixpoint delete_max_aux (m: key) (p: priqueue) : priqueue * priqueue :=\n  match p with\n  | Leaf :: p'   => let (j,k) := delete_max_aux m p'  in (Leaf::j, k)\n  | Node x t1 Leaf :: p' =>\n       if m >? x\n       then (let (j,k) := delete_max_aux m p'\n             in (Node x t1 Leaf::j,k))\n       else (Leaf::p', heap_delete_max (Node x t1 Leaf))\n  | _ => (nil, nil) (* Bogus value *)\n  end.\n\nDefinition delete_max (q: priqueue) : option (key * priqueue) :=\n  match find_max q with\n  | None => None\n  | Some  m => let (p',q') := delete_max_aux m q\n                            in Some (m, join p' q' Leaf)\n  end.\n\nDefinition merge (p q: priqueue) := join p q Leaf.\n\n\nDefinition main_easy :=\n let a := insert 5 (insert 3 (insert 7 empty)) in\n let b := insert 3 (insert 6 (insert 9 empty)) in\n let c := merge a b in\n match delete_max c with\n | Some (k, _) => k\n | None => 0\n end.\n\n\nFixpoint insert_list (l : list nat) (q : priqueue) :=\n    match l with\n    | [] => q\n    | x :: l => insert_list l (insert x q)\n    end.\n\n\nFixpoint make_list (n : nat) (l : list nat) :=\n  match n with\n  | 0 => 0 :: l\n  | S 0 => 1 :: l\n  | S (S n) => make_list n (S (S n) :: l)\n  end.   \n  \nDefinition main :=\n  let a := insert_list (make_list 2000 []) empty in\n  let b := insert_list (make_list 2001 []) empty in\n  let c := merge a b in\n  match delete_max c with\n  | Some (k, _) => k\n  | None => 0\n  end.\n\n", "meta": {"author": "CertiCoq", "repo": "certicoq", "sha": "2405e1012e9c0a58e49002d9779bb65527d6c323", "save_path": "github-repos/coq/CertiCoq-certicoq", "path": "github-repos/coq/CertiCoq-certicoq/certicoq-2405e1012e9c0a58e49002d9779bb65527d6c323/benchmarks/lib/Binom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6859110626441338}}
{"text": "\nFixpoint plus (x : nat) (y : nat) {struct x} : nat := \n  match x with \n    | 0 => y \n    | S x' => plus x' (S y)\n  end.\n\nFixpoint equal (x : nat) (y : nat) {struct x} : Prop := \n  match x with \n    | 0 => \n      match y with \n        | 0 => True \n        | S y' => False\n      end \n    | S x' =>\n      match y with \n        | 0 => False \n        | S y' => equal x' y'\n      end\n    end. \n\n(* distilled from conjecture: forall x y, equal (plus x y) (plus y x). *) \nDefinition conj (x : nat) (y : nat) : Prop := \n  let f1 := \n    (fix r (x : nat) (y : nat) {struct x} : Prop := \n      match x with \n        | 0 => \n          (let f2 := \n            (fix r (y : nat) : Prop := \n              match y with \n                | 0 => True\n                | S y' => r y'\n              end) \n            in f2 y)\n        | S x' => \n          match y with \n            | 0 => \n              (let f3 := \n                (fix r (x : nat) : Prop := \n                  match x with \n                    | 0 => True \n                    | S x' => r x'\n                  end) \n                in f3 x')\n            | S y' => r x' y'\n          end \n      end) \n    in f1 x y.\n\nLtac case_eq x := generalize (refl_equal x); pattern x at -1; case x.\n\n\nLemma conj_zero : forall x, conj x 0 -> conj (S x) 0.\nProof.\n  induction x. auto. simpl. simpl in IHx. intros. apply H.\nDefined.  \n  \n\nTheorem conj_correct : forall x y, conj x y.\nProof.\n  induction x ; induction y. firstorder. firstorder. \n  apply conj_zero. auto. firstorder.\nDefined. \n\nTheorem loop_correct : forall x, (fix r (x:nat) : Prop := match x with | 0 => True | S x' => r x' end) x.\nProof.\n  induction x. auto. auto.\nDefined.   \n\nTheorem conj_correct2 : forall x y, conj x y.\nProof.\n  induction x ; induction y. firstorder. firstorder.\n  simpl. cut (  True -> (fix r (x0 : nat) : Prop := match x0 with\n                               | 0 => True\n                               | S x' => r x'\n                               end) x). \n  intros. apply H. auto. intros. clear. induction x. auto. auto. \n  firstorder. \nDefined. \n\n\nTheorem conj_correct3 : forall x y, conj x y.\nProof.\n  induction x ; induction y. firstorder. firstorder.\n  simpl. apply loop_correct. firstorder.  \nDefined. \n\n\n\n\nTheorem plus_Z_x : forall x, equal (plus 0 x) x.\nProof. \n  intros. induction x. firstorder. simpl. simpl in IHx. auto.\nDefined.   \n\nTheorem plus_comm : forall x y, equal (plus x y) (plus y x).\n  intros. \n\nFixpoint plus_l (x : nat) (y : nat) {struct x} : nat := \n  match x with \n    | 0 => y \n    | S x' => plus_l x' (S y)\n  end.\n\nFixpoint plus_r (x : nat) (y : nat) {struct y} : nat := \n  match y with \n    | 0 => x \n    | S y' => plus_r (S x) y'\n  end.\n\nTheorem r_equal_l : forall (x : nat) (y : nat), equal (plus_l x y) (plus_r x y).\nProof.\n  induction x. induction y. firstorder. \n  Focus 2. intros. simpl. unfold plus_r.  \n\ninversion (plus_r x (S y)). \n  intros. unfold plus_l. unfold plus_r.  \n\n      \n", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6859110607495135}}
{"text": "Require Export XR_le_IZR.\nRequire Export XR_archimed.\nRequire Export XR_Rle_trans.\nRequire Export XR_Rle_lt_trans.\n\nLocal Open Scope R_scope.\n\nLemma one_IZR_r_R1 : forall r (n m:Z),\n  r < IZR n <= r + R1 ->\n  r < IZR m <= r + R1 ->\n  n = m.\nProof.\n  intros r n m ha hb.\n  destruct ha as [ hal har ].\n  destruct hb as [ hbl hbr ].\n  apply Z.le_antisymm.\n  {\n    apply Z.lt_succ_r.\n    apply lt_IZR.\n    unfold Z.succ.\n    rewrite plus_IZR.\n    simpl.\n    eapply Rle_lt_trans.\n    exact har.\n    apply Rplus_lt_compat_r.\n    exact hbl.\n  }\n  {\n    apply Z.lt_succ_r.\n    apply lt_IZR.\n    unfold Z.succ.\n    rewrite plus_IZR.\n    simpl.\n    eapply Rle_lt_trans.\n    exact hbr.\n    apply Rplus_lt_compat_r.\n    exact hal.\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_one_IZR_r_R1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6859110583461344}}
{"text": "Lemma id_P : forall P:Prop, P -> P.\nProof.\n intros ; assumption.\nQed.\n\nLemma id_PP : forall P:Prop, (P -> P) -> P -> P.\nProof.\n intros; assumption. \nQed.\n\nLemma imp_trans : forall P Q R :Prop, (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n intros P Q R H H0 p; apply H0; apply H; assumption. \nQed.\n\nLemma imp_perm :  forall P Q R :Prop, (P -> Q -> R) -> Q -> P -> R.\nProof.\n intros P Q R H q p ; apply H; assumption. \nQed.\n\nLemma ignore_Q : forall P Q R :Prop, (P -> R) -> P -> Q -> R.\nProof.\n intros P Q R H p q; apply H; assumption. \nQed.\n\nLemma delta_imp :  forall P Q :Prop,(P -> P -> Q) -> P -> Q.\nProof.\n intros P Q H p; apply H; assumption. \nQed.\n\nLemma delta_impR :forall P Q :Prop, (P -> Q) -> P -> P -> Q.\nProof.\n  intros P Q H p; apply H; assumption. \nQed.\n\nLemma diamond : forall P Q R T:Prop, (P -> Q) -> \n                                  (P -> R) -> \n                                  (Q -> R -> T) -> \n                                  P -> T.\nProof.\n intros P Q R T H H0 H1 p; apply H1. \n apply H; assumption. \n apply H0; assumption.\nQed.\n\nLemma weak_peirce : forall P Q:Prop, ((((P -> Q) -> P) -> P) -> Q) -> Q.\nProof.\n intros P Q H ; apply H ; intro H0.\n apply H0; intro p; apply H.\n intro; assumption.\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/everyday/SRC/peirce_etc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6859110580917548}}
{"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(*                              Relations_2.v                               *)\n(****************************************************************************)\n\nRequire Import Relations_1.\n\nSection Relations_2.\n   Variable U : Type.\n   Variable R : Relation U.\n   \n   Inductive Rstar : Relation U :=\n     | Rstar_0 : forall x : U, Rstar x x\n     | Rstar_n : forall x y z : U, R x y -> Rstar y z -> Rstar x z.\n   \n   Inductive Rstar1 : Relation U :=\n     | Rstar1_0 : forall x : U, Rstar1 x x\n     | Rstar1_1 : forall x y : U, R x y -> Rstar1 x y\n     | Rstar1_n : forall x y z : U, Rstar1 x y -> Rstar1 y z -> Rstar1 x z.\n   \n   Inductive Rplus : Relation U :=\n     | Rplus_0 : forall x y : U, R x y -> Rplus x y\n     | Rplus_n : forall x y z : U, R x y -> Rplus y z -> Rplus x z.\n   \n   Definition Strongly_confluent : Prop :=\n     forall x a b : U, R x a -> R x b -> exists z : U, R a z /\\ R b z.\n   \nEnd Relations_2.\nHint Resolve Rstar_0.\nHint Resolve Rstar1_0.\nHint Resolve Rstar1_1.\nHint Resolve Rplus_0.", "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/Relations_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6858742499504518}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.Bool.Bool.\nRequire Import Crypto.Util.ZUtil.Notations.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Testbit.\nLocal Open Scope bool_scope. Local Open Scope Z_scope.\n\nModule Z.\n  Lemma land_same_r : forall a b, (a &' b) &' b = a &' b.\n  Proof.\n    intros a b; apply Z.bits_inj'; intros n H.\n    rewrite !Z.land_spec.\n    case_eq (Z.testbit b n); intros;\n      rewrite ?Bool.andb_true_r, ?Bool.andb_false_r; reflexivity.\n  Qed.\n\n  Lemma land_m1'_l a : Z.land (-1) a = a.\n  Proof. apply Z.land_m1_l. Qed.\n#[global]\n  Hint Rewrite Z.land_m1_l land_m1'_l : zsimplify_const zsimplify zsimplify_fast.\n\n  Lemma land_m1'_r a : Z.land a (-1) = a.\n  Proof. apply Z.land_m1_r. Qed.\n#[global]\n  Hint Rewrite Z.land_m1_r land_m1'_r : zsimplify_const zsimplify zsimplify_fast.\n\n  Lemma sub_1_lt_le x y : (x - 1 < y) <-> (x <= y).\n  Proof. lia. Qed.\n\n  Lemma land_mod a b :\n    0 <= b ->\n    a &' b = (a mod (2 ^ (Z.log2 b + 1))) &' b.\n  Proof.\n    pose proof (Z.log2_nonneg b).\n    intros. rewrite <-Z.land_ones by lia.\n    rewrite <-Z.land_assoc, (Z.land_comm (Z.ones _)).\n    rewrite Z.land_ones_low; auto with zarith.\n  Qed.\n\n  Lemma land_add_high a b c d :\n    Z.log2 d < c ->\n    0 <= d ->\n    (a + b * 2 ^ c) &' d = a &' d.\n  Proof.\n    pose proof (Z.log2_nonneg d).\n    intros. rewrite land_mod by lia.\n    rewrite Z.add_mod, Z.mul_mod by (apply Z.pow_nonzero; lia).\n    match goal with\n    | |- context [?a ^ ?b mod ?a ^ ?c] =>\n      replace b with ((b - c) + c) by lia;\n        rewrite (Z.pow_add_r a (b - c) c) by lia;\n        rewrite Z.mod_mul by (apply Z.pow_nonzero; lia)\n    end.\n    rewrite Z.mul_0_r, Z.mod_0_l, Z.add_0_r, Z.mod_mod\n      by (apply Z.pow_nonzero; lia).\n    rewrite <-Z.land_ones, <-Z.land_assoc, (Z.land_comm (Z.ones _))\n      by auto with zarith.\n    rewrite Z.land_ones_low; auto with zarith.\n  Qed.\n\n  Lemma land_pow2 x n :\n    0 <= n ->\n    Z.land x (2^n-1) = x mod 2^n.\n  Proof.\n    intros. rewrite Z.sub_1_r, <- Z.ones_equiv.\n    apply Z.land_ones; auto with zarith.\n  Qed.\n  \n  Lemma land_pow2_testbit a b :\n  a &' 2^b = if Z.testbit a b then 2^b else 0.\n  Proof.\n    apply Z.bits_inj_iff; red; intros; rewrite Z.land_spec.\n    destruct (Z.testbit a b) eqn:E.\n    - destruct (Z.eqb_spec b n); subst.\n      + now rewrite E, andb_true_l.\n      + now rewrite Z.pow2_bits_false, andb_false_r.\n    - rewrite Z.testbit_0_l; destruct (Z.eqb_spec b n); subst.\n      + now rewrite E, andb_false_l.\n      + now rewrite Z.pow2_bits_false, andb_false_r. Qed.\n\n  Lemma land_pow2_small a b\n        (Ha : 0 <= a < 2^b) :\n    a &' 2^b = 0.\n  Proof. now rewrite land_pow2_testbit, Testbit.Z.bits_above_pow2. Qed.\n\n  Lemma land_pow2_small_neg a b\n        (Ha : - 2^b <= a < 0)\n        (Hb : 0 < b) :\n    a &' 2^b = 2^b.\n  Proof. now rewrite land_pow2_testbit, Testbit.Z.testbit_small_neg. Qed.\n\n  Lemma land_div2 a b (Ha : 0 <= a < 2^(b + 1))  :\n    a / 2 &' 2^b = 0.\n  Proof.\n    destruct (Z.ltb_spec b 0).\n    - now rewrite Pow.Z.base_pow_neg, Z.land_0_r.\n    - rewrite land_pow2_testbit, Z.div2_bits, Testbit.Z.bits_above_pow2; \n      try (replace (Z.succ b) with (b + 1); nia). Qed.\nEnd Z.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Util/ZUtil/Land.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6858742411046436}}
{"text": "(** * The Wainer hierarchy of rapidly growing functions (variant)\n\n\n    After Wainer, Ketonen, Solovay, etc .\n *)\n\n\nFrom hydras  Require Import  Iterates  Simple_LexProd Exp2.\nFrom hydras Require Import  E0 Canon Paths primRec Hprime.\nImport RelationClasses Relations.\n\nFrom Coq Require Import ArithRing Lia.\nRequire Import Compat815.\n\nFrom Equations Require Import Equations.\n\nFrom hydras Require Import primRec.\n\n(** For masking primRec's iterate *)\n\nImport Prelude.Iterates.\n\n\n\n(** ** Definition, using [coq-equations] \n\nThe following definition is not accepted by the [equations] plug-in.\n\n *)\n\n#[global] Instance Olt : WellFounded E0lt := E0lt_wf.\n\n(* begin snippet FailDemo *)\n(*  Works with Dev\nFail Equations F_ (alpha: E0) (i:nat) :  nat  by wf  alpha E0lt :=\n  F_ alpha  i with E0_eq_dec alpha E0zero :=\n    { | left _zero =>  i ;\n      | right _nonzero\n          with Utils.dec (E0limit alpha) :=\n          { | left _limit =>  F_ (Canon alpha i)  i ;\n          | right _notlimit =>  iterate (F_ (E0pred alpha)) (S i) i}}.\n*)\n(* end snippet FailDemo *)\n\n(**\n\n    Indeed, we define the $n$-th iterate of [F_ alpha] by well-founded\n    recursion  on the pair (alpha,n), then [F_ alpha] as the first iterate \n    of the defined function.\n *)\n\n\n\n(* begin snippet goodDefa:: no-out *)\nDefinition call_lt (c c' : E0 * nat) :=\n  lexico E0lt (Peano.lt) c c'.\n\nLemma call_lt_wf : well_founded call_lt.\n  unfold call_lt; apply Inverse_Image.wf_inverse_image,  wf_lexico.\n  -  apply E0lt_wf.\n  -  unfold Peano.lt; apply Nat.lt_wf_0. \nQed.\n\n#[ global ] Instance WF : WellFounded call_lt := call_lt_wf.\n\n(*  F_star (alpha,i) is intended to be the i-th iterate of F_ alpha *)\n\nEquations  F_star (c: E0 * nat) (i:nat) :  nat by wf  c call_lt :=\n  F_star (alpha, 0) i := i;\n  F_star (alpha, 1) i\n    with E0_eq_dec alpha E0zero :=\n    { | left _zero => S i ;\n      | right _nonzero\n          with Utils.dec (E0limit alpha) :=\n          { | left _limit => F_star (Canon alpha i,1) i ;\n            | right _notlimit =>\n              F_star (E0pred alpha, S i)  i}};\n  F_star (alpha,(S (S n))) i :=\n    F_star (alpha, 1) (F_star (alpha, (S n)) i).\n(* end snippet goodDefa *)\n\n\nNext Obligation.\n  left; cbn ; auto with E0. \nDefined.\n\nNext Obligation.\n  left; cbn; auto with E0.   \nDefined.\n\nNext Obligation.\n  right; cbn; auto with arith. \nDefined.\n\nNext Obligation.\n  right; cbn; auto with arith.\nDefined.\n\n(* begin snippet goodDefb *)\nDefinition F_ alpha i := F_star (alpha, 1) i.\n(* end snippet goodDefb *)\n\n(** ** We get the \"usual\" equations for [F_]  *)\n\n(** *** Relations between [F_star] and [F_] *)\n\nLemma F_star_zero_eqn : forall alpha i, F_star (alpha, 0) i = i.\nProof.\n  intros; now rewrite F_star_equation_1.\nQed.\n\nLemma Fstar_S : forall alpha n i, F_star (alpha, S (S n)) i =\n                                  F_ alpha  (F_star (alpha, S n) i).\nProof.  \n  unfold F_; intros; now rewrite F_star_equation_3.\nQed.\n\nLemma F_eq2 : forall alpha i,\n    E0is_succ alpha -> \n    F_ alpha i = F_star (E0pred alpha, S i) i.\nProof.\n  unfold F_; intros; rewrite F_star_equation_2.\n  destruct (E0_eq_dec alpha E0zero).\n  - subst alpha; discriminate H.\n  - cbn; destruct (Utils.dec (E0limit alpha)) .\n    + assert (true=false) by \n          ( now  destruct (Succ_not_T1limit _ H)). \n      discriminate.\n    + now cbn.\nQed.\n\nLemma F_star_Succ:  forall alpha n i,\n    F_star (alpha, S n) i = \n    F_ alpha (F_star (alpha, n) i).\nProof.\n  destruct n.\n  - intros; now rewrite F_star_zero_eqn.\n  - intros i; unfold F_; now rewrite Fstar_S.  \nQed.\n\nLemma F_star_iterate : forall alpha n i,\n    F_star (alpha, n) i =  iterate (F_ alpha) n i.\nProof.\n  induction n; intro i; simpl.\n  - now rewrite F_star_zero_eqn. \n  - specialize (IHn i); rewrite F_star_Succ in *;  now rewrite <- IHn.\nQed.\n\n\n(** *** Usual equations for [F_] *)\n\n(* begin snippet FEquations *)\n\nLemma F_zero_eqn : forall i, F_ E0zero i = S i.  (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  intro i. unfold F_; rewrite F_star_equation_2.\n  destruct (E0_eq_dec E0zero E0zero).\n  - now cbn.\n  - now destruct n.\nQed.\n(*||*)\n\nLemma F_lim_eqn : forall alpha i,\n    E0limit alpha ->\n    F_ alpha i = F_ (Canon alpha i) i. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  unfold F_; intros. rewrite F_star_equation_2.\n  destruct (E0_eq_dec alpha E0zero).\n  - now  destruct (Limit_not_Zero  H).\n  - cbn; destruct (Utils.dec (E0limit alpha)) .\n    + cbn; auto.\n    + red in H. rewrite e in H; discriminate.\nQed.\n(*||*)\n\nLemma F_succ_eqn : forall alpha i,\n    F_ (E0succ alpha) i = iterate (F_ alpha) (S i) i. (* .no-out *)\n(*| .. coq:: none |*)\nProof with auto with E0.\n  intros;rewrite F_eq2,  F_star_iterate ...\n  -  now rewrite E0pred_of_Succ.\nQed.\n(*||*)\n(* end snippet FEquations *)\n\n(** ** First steps of the hierarchy *)\n\n\n(** performs an induction only on the occ1-th and occ2_th occurrences of n *)\n\nTactic Notation \"undiag2\" constr(n) integer(occ1) integer(occ2) :=\n  let n' := fresh \"n\" in\n  generalize n at occ1 occ2; intro n'; induction n'.\n\n(* begin snippet FirstValues *)\n\nLemma LF1 : forall i,  F_ 1 i = S (2 * i). (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  intro i; unfold E0fin; rewrite FinS_Succ_eq, F_succ_eqn.\n  rewrite iterate_rw, F_zero_eqn.  \n  simpl; rewrite iterate_ext with (g := S).\n  - undiag2 i 1 3.\n    + simpl; abstract lia.\n    + simpl; auto.\n  - intro; now rewrite F_zero_eqn.\nQed. \n(*||*)\n\nLemma LF2 : forall i, exp2 i * i < F_ 2 i. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  intro i; ochange (E0fin 2) (E0succ 1); rewrite F_succ_eqn.\n  undiag2 i 1 3.\n  -  intros. cbn;  intros; cbn.  repeat rewrite LF1. abstract lia. \n  - intros; simpl exp2; ring_simplify. simpl (2+n)%nat.\n    rewrite iterate_S_eqn, LF1; abstract lia.\nQed.\n(*||*)\n(* end snippet FirstValues *)\n\nCorollary LF2' : forall i,  1 <= i -> exp2 i < F_ 2 i.\nProof.\n  intros;  apply Nat.le_lt_trans with (exp2 i * i).\n  - destruct (Compat815.mult_O_le (exp2 i) i).\n    + lia.\n    + now rewrite Nat.mul_comm.\n  -  apply LF2.\nQed.\n\n\n\n\nLemma F_alpha_0_eq : forall alpha: E0, F_ alpha 0 = 1.\n  intro alpha. pattern alpha; apply well_founded_induction with E0lt.\n  - apply E0lt_wf.\n  - clear alpha; intros alpha Halpha.\n    destruct (Zero_Limit_Succ_dec alpha).\n    destruct s.\n    + subst alpha; now rewrite F_zero_eqn.\n    +  rewrite F_lim_eqn;auto; unfold Canon. rewrite Halpha. auto.\n       Search (Canon ?a _ o< ?a).\n       apply  (@Canon_lt 0 alpha). \n       intro Heq; subst. discriminate. \n    +  destruct s; subst; rewrite F_succ_eqn; simpl; apply Halpha, Lt_Succ.\nQed.\n\n(** Properties of [F_ alpha]  *)\n(* begin hide *)\n\nSection Properties.\n  Record P (alpha:E0) : Prop :=\n    mkP {\n        PA : strict_mono (F_ alpha);\n        PB : forall n, n < F_ alpha n;\n        PC : F_ alpha <<= F_ (E0succ alpha);\n        PD : dominates_from 1 (F_ (E0succ alpha)) (F_ alpha);\n        PE : forall beta n, Canon_plus n alpha beta -> \n                            F_ beta n <= F_ alpha n}.\n\n  \n  Section The_induction.\n\n    (** Base step : (sequential) proof of (P 0) *)\n    \n    Lemma mono_F_Zero : strict_mono (F_ E0zero).\n    Proof. \n      intros n p H; repeat rewrite F_zero_eqn; auto with arith. \n    Qed. \n\n    Lemma Lt_n_F_Zero_n : forall n:nat, n < F_ E0zero n. \n    Proof. intros n ; rewrite F_zero_eqn; auto with arith. Qed.\n\n    Lemma F_One_Zero_dom : dominates_from 1 (F_ 1) (F_ E0zero).\n    Proof.\n      red;intros.\n      rewrite F_zero_eqn. rewrite LF1; abstract lia.\n    Qed.\n\n    #[local] Hint Resolve F_One_Zero_dom mono_F_Zero Lt_n_F_Zero_n : T1.\n\n    Lemma F_One_Zero_ge :  F_ E0zero <<= F_ 1.\n    Proof.\n      intro n; destruct n;\n        rewrite F_zero_eqn, LF1; abstract lia.  \n    Qed. \n\n    #[local] Hint Resolve  F_One_Zero_ge : T1.\n\n    Lemma PZero : P E0zero.\n    Proof. \n      split; auto with T1; ord_eq  (E0succ E0zero) (E0fin 1).\n      all: try (rewrite H;auto with T1).\n      unfold Canon_plus; intros beta n H0;\n        unfold E0zero in H0; simpl in H0.\n      destruct n.\n      - inversion H0. \n      - destruct (const_pathS_zero  H0). \n    Qed.   \n\n    Variable alpha : E0.\n    Hypothesis Halpha : forall beta, E0lt beta alpha -> P beta.\n\n    Ltac hdecomp := destruct Halpha.\n    Section alpha_Succ.\n      Variable beta: E0.\n      Hypothesis alpha_def : alpha = E0succ beta.\n\n      Remark R1 : strict_mono (F_ alpha).\n      Proof.\n        destruct (Halpha beta).\n        subst alpha; apply Lt_Succ.\n        red; intros.\n        subst alpha.\n        repeat rewrite F_succ_eqn.\n        induction H.\n        \n        rewrite (iterate_S_eqn (F_ beta) (S n)).\n        apply Nat.lt_le_trans with (F_ beta\n                                      (iterate (F_ beta) (S n) n)).\n        auto. \n        apply mono_weak; auto.\n        \n        apply Nat.lt_le_incl.\n        apply iterate_mono;auto.\n        destruct (Halpha beta).\n        apply Lt_Succ.\n        \n        \n        transitivity (iterate (F_ beta) (S m) m);auto.\n        rewrite (iterate_S_eqn (F_ beta) (S m)).\n        apply Nat.lt_le_trans with (F_ beta (iterate (F_ beta) (S m) m)).\n        auto.\n        apply mono_weak; auto.\n        apply Nat.lt_le_incl.\n        apply iterate_mono;auto.\n      Qed.\n\n      Remark RB : forall n, n < F_ alpha n.\n      Proof.\n        subst  alpha.\n        intro n. \n        rewrite F_succ_eqn.\n        destruct (Halpha beta).\n        apply Lt_Succ.\n        change n with (iterate (F_ beta) 0 n) at 1.\n        apply iterate_lt;auto with arith.\n      Qed.\n      \n      Remark RD : dominates_from 1 (F_ (E0succ alpha)) (F_ alpha).\n        generalize RB; intro RB'.\n        rewrite alpha_def .\n        \n        destruct (Halpha beta).\n        rewrite alpha_def ;apply Lt_Succ.\n        intros n Hn.\n        rewrite (F_succ_eqn (E0succ beta)).\n        apply Nat.lt_le_trans with (F_ (E0succ beta) (F_ (E0succ beta) n)).\n        \n        rewrite <- alpha_def.\n        apply RB'.\n        rewrite iterate_S_eqn2.\n        change (F_ (E0succ beta) (F_ (E0succ beta) n)) with\n            (iterate (F_ (E0succ beta)) 1 (F_ (E0succ beta) n)).\n        apply iterate_le.\n\n        generalize R1; intro R1'.\n        rewrite <- alpha_def. auto.\n        assumption.\n      Qed.\n\n\n      Remark RE : forall beta n, Canon_plus n alpha beta -> \n                                 F_ beta n <= F_ alpha n.\n      Proof.\n        destruct n.\n        repeat rewrite F_alpha_0_eq. \n        reflexivity.\n        intros. \n        transitivity (F_ beta (S n)).\n        rewrite alpha_def in H.\n        - destruct (Canon_plus_first_step  H).\n          subst beta0; reflexivity.\n          destruct (Halpha beta).\n          rewrite alpha_def.\n          apply Lt_Succ.\n          apply PE0.\n          auto.\n        - destruct (Halpha beta).\n          rewrite alpha_def.\n          apply Lt_Succ.\n          rewrite alpha_def.\n          apply Nat.lt_le_incl.\n          apply PD0.\n          auto with arith.\n      Qed.\n\n      Remark RC : F_ alpha <<= F_ (E0succ alpha).\n      Proof.\n        intro n; destruct n.\n        repeat rewrite F_alpha_0_eq. auto with arith.\n        apply Nat.lt_le_incl.\n        apply RD. auto with arith.\n      Qed.\n\n      Remark RP : P alpha.\n        split.\n        apply R1.\n        apply RB.\n        apply RC.\n        apply RD.\n        apply RE.\n      Qed.\n\n    End alpha_Succ.\n\n\n    Section alpha_limit.\n      Hypothesis Hlim : E0limit alpha.\n\n\n      Remark RBlim : forall n, n < F_ alpha n.\n        intro n.\n        rewrite F_lim_eqn.\n        destruct (Halpha (Canon alpha n)).\n        apply Canon_lt. \n        now apply Limit_not_Zero.\n        auto.\n        auto.\n      Qed.\n      \n      Remark RAlim : strict_mono (F_ alpha).\n      Proof.\n        red;intros m n H; destruct m.\n        - rewrite (F_lim_eqn alpha n);auto.\n          rewrite F_alpha_0_eq. (* bad name *)\n          destruct n. inversion H.\n          unfold Canon.\n          apply Nat.le_lt_trans with (S n).\n          auto with arith.\n          destruct (Halpha (Canon alpha (S n))).\n          apply CanonS_lt. \n          now apply Limit_not_Zero.\n          now apply PB0.\n          \n        - destruct n. inversion H.\n          rewrite (F_lim_eqn alpha (S n));auto.\n          rewrite (F_lim_eqn alpha (S m));auto.\n          assert (Canon_plus 1 (Canon alpha (S n)) (Canon alpha (S m))).\n          apply KS_thm_2_4_E0; auto.\n          auto with arith.\n          assert (Canon_plus (S n) (Canon alpha (S n)) (Canon alpha (S m))).\n          eapply Cor12_E0 with 0; auto with arith.\n          apply canonS_limit_mono; auto with T1.\n          auto with arith.\n          auto with E0.\n          auto with arith.\n          apply Nat.le_lt_trans with (F_ (Canon alpha (S n)) (S m) ).\n          destruct (Halpha (Canon alpha (S n))).\n          apply Canon_lt. \n          now apply Limit_not_Zero.\n          apply PE0. auto. auto.\n          eapply Cor12_E0 with 0; auto with arith.\n          apply canonS_limit_mono; auto with T1.\n          auto with arith.\n          destruct (Halpha (Canon alpha (S n))).\n          apply Canon_lt. \n          now apply Limit_not_Zero.\n          auto with E0.\n          auto with arith.\n          apply PA.\n          apply Halpha.\n          apply CanonS_lt.\n          auto with E0.\n          auto with arith.\n      Qed.\n\n\n\n      Remark RClim : F_ alpha <<= F_ (E0succ alpha).\n      Proof.\n        intro n; destruct n.\n        - repeat rewrite F_alpha_0_eq; auto with arith.\n        -  apply Nat.lt_le_incl;  rewrite F_succ_eqn.\n           change (F_ alpha (S n)) with (iterate (F_ alpha) 1 (S n)).\n           apply iterate_lt. \n           +  apply RAlim.\n           +  red;intros; apply RBlim.\n           +  auto with arith.\n      Qed.\n\n      Remark RDlim : dominates_from 1 (F_ (E0succ alpha)) (F_ alpha).\n      Proof.\n        red;intros; rewrite F_succ_eqn.\n        change (F_ alpha p) with (iterate (F_ alpha) 1 p);\n          apply iterate_lt. \n        -   apply RAlim.\n        -   red;intros; apply RBlim.\n        -   auto with arith.\n      Qed.\n\n      Remark RElim : forall beta n, Canon_plus n alpha beta -> \n                                    F_ beta n <= F_ alpha n.\n      Proof.\n        destruct n.\n        - now  repeat rewrite F_alpha_0_eq. \n        - intros H;  destruct (Canon_plus_first_step_lim  Hlim H).\n          +  rewrite (F_lim_eqn alpha _).\n             * now rewrite H0.\n             * auto.\n          +  rewrite (F_lim_eqn alpha _);auto.\n             destruct (Halpha (Canon alpha (S n))); auto.\n             apply CanonS_lt;  now apply Limit_not_Zero.\n      Qed.\n\n    End alpha_limit.\n\n    Lemma LL : P alpha.\n    Proof. \n      destruct (Zero_Limit_Succ_dec alpha).\n      destruct s.\n      - subst; apply PZero.\n      - split.\n        apply RAlim; auto.\n        apply RBlim; auto.\n        apply RClim; auto.\n        apply RDlim; auto.\n        apply RElim; auto.\n      - destruct s; split.\n        eapply R1;eauto.\n        eapply RB;eauto.\n        eapply RC;eauto.\n        eapply RD;eauto.\n        eapply RE;eauto.\n    Qed.\n\n  End The_induction.\n\n\n  Theorem TH_packed : forall alpha, P alpha.\n  Proof.\n    intro alpha; apply well_founded_induction with E0lt.\n    - exact E0lt_wf.\n    - apply LL.\n  Qed.\n\nEnd Properties.\n\n(* end hide *)\n\n(* begin snippet FalphaThms *)\n\nTheorem F_alpha_mono alpha : strict_mono (F_ alpha). (* .no-out *)\n(*| .. coq:: none |*)\nProof. now  destruct  (TH_packed alpha). Qed.\n(*||*)\n\nTheorem F_alpha_gt alpha : forall n, n < F_ alpha n. (* .no-out *)\n(*| .. coq:: none |*)\nProof. now  destruct  (TH_packed alpha). Qed.\n(*||*)\n\nCorollary F_alpha_positive alpha :  forall n, 0 < F_ alpha n. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  intro n; apply Nat.le_lt_trans with n; auto with arith.\n  apply F_alpha_gt.\nQed.\n\nTheorem F_alpha_Succ_le alpha : F_ alpha <<= F_ (E0succ alpha). \n(*| .. coq:: none |*)\nProof. now  destruct  (TH_packed alpha). Qed.\n(*||*)\n\n\nTheorem F_alpha_dom alpha :\n  dominates_from 1 (F_ (E0succ alpha)) (F_ alpha). (* .no-out *)\n(*| .. coq:: none |*)\nProof. now  destruct  (TH_packed alpha). Qed.\n(*||*)\n\nTheorem F_restricted_mono_l alpha :\n  forall beta n, Canon_plus n alpha beta -> \n                 F_ beta n <= F_ alpha n. (* .no-out *)\n(*| .. coq:: none |*)\nProof. now  destruct (TH_packed alpha). Qed.\n(*||*)\n\n(* end snippet FalphaThms *)\n #[deprecated(note=\"use F_alpha_gt\")]\n  Notation F_alpha_ge_S := StrictOrder_Transitive (only parsing).\n\n \n\nLemma LF2_0 : dominates_from 0 (F_ 2) (fun i => exp2 i * i).\nProof.\n  red. intros ; apply LF2 ; auto.  \nQed.\n\n\nLemma LF3_2  : dominates_from 2  (F_ 3) (fun  n => iterate exp2 (S n) n).\nProof.  \n  intros p H; assert (H0:= LF2_0).\n  ochange (E0fin 3) (E0succ 2); rewrite F_succ_eqn.\n  eapply iterate_dom_prop; eauto with arith. \n  - apply exp2_ge_S.\n  - apply exp2_mono.\n  - apply F_alpha_mono.\n  - red; intros; transitivity (exp2 p0 * p0)%nat; auto.\n    {  rewrite <- Nat.mul_1_r at 1; apply Nat.mul_lt_mono_pos_l; auto.\n       apply exp2_positive.\n    }\n    apply LF2_0; abstract lia.\nQed.\n\n(** From Ketonen and Solovay, page 284, op. cit. *)\n\n(* begin snippet FDomContext *)\n\nSection F_monotony_l.\n\n  Variables alpha beta : E0.\n  Hypothesis H'_beta_alpha : E0lt beta alpha.\n\n  (* end snippet FDomContext *)\n  \n  (* begin hide *)\n  Section case_eq.\n    Hypothesis Heq : alpha = E0succ beta.\n\n    Fact F2 : forall i, (1 <= i ->  F_ beta i < F_ alpha i)%nat.\n    Proof.\n      subst alpha; intros i H; apply (F_alpha_dom beta i H).\n    Qed.\n\n  End case_eq.\n\n\n  Section case_lt.\n    Variable n: nat.\n    Hypothesis Hlt :  E0lt (E0succ beta) alpha.\n    \n    Hypothesis Hd : Canon_plus (S n) alpha beta.\n\n    Fact F5 : Canon_plus (S (S n)) alpha (E0succ beta).\n    Proof.\n      destruct alpha, beta; cbn;  now apply L2_6_2.  \n    Qed.\n\n    \n    Fact F6 : forall i, (S n < i)%nat ->  Canon_plus i alpha (E0succ beta).\n    Proof.\n      destruct alpha, beta; unfold lt, Canon_plus in *; simpl in *.\n      intros i H; destruct i.\n      - inversion H.\n      - destruct i.\n        + inversion H. lia. \n        + apply Cor12_3 with (S (S n)); auto.\n          apply L2_6_2; auto.\n    Qed.   \n\n    Fact F7 : forall i, (S n < i -> F_ (E0succ beta) i <= F_ alpha i)%nat.\n    Proof.\n      intros; apply  F_restricted_mono_l; apply F6; auto.\n    Qed.\n\n    Fact F8 : forall i, (S n < i -> F_ beta i < F_ (E0succ beta) i)%nat.\n    Proof.\n      intros i H; apply  (F_alpha_dom beta i); abstract lia.\n    Qed.\n\n    Fact F9 : forall i, (S n < i -> F_ beta i < F_ alpha i)%nat.\n    Proof.\n      intros ? ?; eapply Nat.lt_le_trans.\n      - eapply F8;eauto.\n      - apply F7;auto.\n    Qed.\n\n  End case_lt.\n\n  (* end hide *)\n  \n  Lemma F_mono_l_0 : forall n,\n      Canon_plus (S n) alpha beta ->\n      forall i, (S n < i -> F_ beta i < F_ alpha i)%nat.\n  Proof.\n    assert (H: E0le (E0succ beta) alpha) by (now apply Lt_Succ_Le).\n    assert (H0: {alpha = E0succ beta} + {E0lt (E0succ  beta) alpha}).\n    {\n      rewrite <- lt_Succ_inv in H.\n      apply Lt_Succ_Le in H; destruct (E0.le_lt_eq_dec  H); auto.\n    }\n    destruct H0.\n    - intros; apply F2; [trivial | lia].\n    - intros; eapply F9; eauto.\n  Qed.\n\n  (* begin snippet FDom *)\n  \n  Lemma F_mono_l: dominates (F_ alpha) (F_ beta). (* .no-out *)\n  (*| .. coq:: none |*)\n  Proof.\n    destruct (Lemma2_6_1_E0  H'_beta_alpha) as [i Hi].\n    exists (S (S i)); intros p Hp; apply F_mono_l_0 with i;  auto.\n  Qed.\n  (*||*)\n  \nEnd  F_monotony_l.\n(* end snippet FDom *)\n\n\n(** * Comparison with the Hardy hierarchy \n       \n      [(F_ alpha (S n) <= H'_ (Phi0 alpha) (S n))]\n*)\n\n\n\nSection H'_F.\n  \n  Let P (alpha: E0) :=\n        forall n,  (F_ alpha (S n) <= H'_ (E0phi0 alpha) (S n))%nat.\n\n Variable alpha: E0.\n\n Hypothesis IHalpha : forall  beta, beta o< alpha -> P beta.\n\n Lemma HF0 : P E0zero.\n Proof.\n   intro n; rewrite F_zero_eqn.\n   replace (E0phi0 E0zero) with (E0fin 1).\n   - now rewrite H'_Fin.\n   - now apply E0_eq_intro.\n Qed.\n\n Lemma HFsucc : E0is_succ alpha -> P alpha.\n Proof.\n   intro H; destruct (Succb_Succ _ H) as [beta Hbeta]; subst.\n   intro n; rewrite H'_Phi0_succ.\n   unfold H'_succ_fun; rewrite F_succ_eqn.\n   specialize (IHalpha beta (Lt_Succ beta));  unfold P in IHalpha.\n   - apply iterate_mono_1 with 1.\n     + apply F_alpha_mono.\n     + intro k; apply F_alpha_gt.\n     + intros; destruct n0.\n       * lia.\n       * apply IHalpha.\n     +lia.\n Qed.\n\n\n  (** The following proof is far from being trivial.\n      It uses some lemmas from the Ketonen-Solovay machinery *)\n \n  Lemma HFLim : E0limit alpha -> P alpha.\n  Proof.\n    intros Halpha n; rewrite H'_eq3.\n    - rewrite CanonS_phi0_lim; [| trivial].\n      rewrite F_lim_eqn; auto.\n      + transitivity (H'_ (E0phi0 (Canon alpha (S n))) (S n)).\n        *  apply IHalpha.\n           apply CanonS_lt.\n           now apply Limit_not_Zero.\n        * (** Not trivial, since [H'_ ] is not monotonous ! *)\n\n          apply H'_restricted_mono_l.\n          \n          red; cbn; apply KS_thm_2_4_lemma5.\n          -- apply Cor12_1 with 0.\n           ++ apply nf_canon, cnf_ok.\n           ++ apply canonS_limit_mono.\n              ** apply cnf_ok.\n              ** destruct alpha; cbn; assumption. \n              ** auto with arith. \n           ++ auto with arith.\n           ++ apply KS_thm_2_4.\n              ** apply cnf_ok.\n              ** destruct alpha; auto.\n              ** auto with arith. \n          --  apply nf_canon, cnf_ok.\n          --  apply T1limit_canonS_not_zero.\n              ++ apply cnf_ok.\n              ++ now destruct alpha.\n    - apply T1limit_phi0.\n      apply Limit_not_Zero; auto. \nQed.\n\nEnd H'_F.\n\n(* begin snippet HprimeF:: no-out  *)\n\nLemma H'_F alpha : forall n,  F_ alpha (S n) <= H'_ (E0phi0 alpha) (S n).\nProof.\n  pattern alpha; apply well_founded_induction with E0lt.\n(* end snippet HprimeF *)\n  - apply E0lt_wf.  \n  -  clear alpha; intros alpha IHalpha.\n     destruct (Zero_Limit_Succ_dec alpha) as [[Hzero | Hlim] | Hsucc].\n    + subst; apply HF0.\n    + apply HFLim; auto.\n    + destruct Hsucc; subst; apply HFsucc.\n      intros; apply IHalpha; auto.\n      apply Succ_Succb.\n  Qed.\n\n\n(** * A variant (Lob-Wainer hierarchy) \n***************************************)\n\n\nEquations  f_star (c: E0 * nat) (i:nat) :  nat by wf c call_lt :=\n  f_star (alpha, 0) i := i;\n  f_star (alpha, 1) i\n    with E0_eq_dec alpha E0zero :=\n    { | left _zero => S i ;\n      | right _nonzero\n          with Utils.dec (E0limit alpha) :=\n          { | left _limit => f_star (Canon alpha i,1) i ;\n            | right _successor =>\n              f_star (E0pred alpha, i)  i}};\n  f_star (alpha,(S (S n))) i :=\n    f_star (alpha, 1) (f_star (alpha, (S n)) i).\n\nNext Obligation.\n  left; cbn ; auto with E0. \nDefined.\n\nNext Obligation.\n  left; cbn; auto with E0.   \nDefined.\n\nNext Obligation.\n  right; cbn; auto with arith. \nDefined.\n\nNext Obligation.\n  right; cbn; auto with arith.\nDefined.\n\n\n(**  Finally, [f_ alpha] is defined as its first iterate  ! *)\n\nDefinition f_ alpha i := f_star (alpha, 1) i.\n\n(** ** We get the \"usual\" equations for [F_]  *)\n\n(** *** Relations between [F_star] and [F_] *)\n\nLemma f_star_zero_eqn : forall alpha i, f_star (alpha, 0) i = i.\nProof.\n  intros; now rewrite f_star_equation_1.\nQed.\n\nLemma fstar_S : forall alpha n i, f_star (alpha, S (S n)) i =\n                                  f_ alpha  (f_star (alpha,  S n) i).\nProof.  \n  unfold F_; intros; now rewrite f_star_equation_3.\nQed.\n\nLemma f_eq2 : forall alpha i,\n    E0is_succ alpha -> \n    f_ alpha i = f_star (E0pred alpha,  i) i.\nProof.\n  unfold f_; intros; rewrite f_star_equation_2.\n  destruct (E0_eq_dec alpha E0zero).\n  - subst alpha; discriminate H.\n  - cbn; destruct (Utils.dec (E0limit alpha)) .\n    + assert (true=false) by \n          ( now  destruct (Succ_not_T1limit _ H)). \n      discriminate.\n    + now cbn.\nQed.\n\nLemma f_star_Succ:  forall alpha n i,\n    f_star (alpha, S n) i = \n    f_ alpha (f_star (alpha, n) i).\nProof.\n  destruct n.\n  - intros; now rewrite f_star_zero_eqn.\n  - intros i; unfold f_; now rewrite fstar_S.  \nQed.\n\nLemma f_star_iterate : forall alpha n i,\n    f_star (alpha, n) i =  iterate (f_ alpha) n i.\nProof.\n  induction n; intro i; simpl.\n  - now rewrite f_star_zero_eqn. \n  - specialize (IHn i); rewrite f_star_Succ in *;  now rewrite <- IHn.\nQed.\n\n\n\n(** *** Usual equations for [f_] *)\n\nLemma f_zero_eqn : forall i, f_ E0zero i = S i.\nProof.\n  intro i. unfold f_; rewrite f_star_equation_2.\n  destruct (E0_eq_dec E0zero E0zero).\n  - now cbn.\n  - now destruct n.\nQed.\n\n\nLemma f_lim_eqn : forall alpha i,  E0limit alpha ->\n                                   f_ alpha i = f_ (Canon alpha i) i.\nProof.\n  unfold f_; intros. rewrite f_star_equation_2.\n  destruct (E0_eq_dec alpha E0zero).\n  - now  destruct (Limit_not_Zero  H).\n  - cbn; destruct (Utils.dec (E0limit alpha)) .\n    + cbn; auto.\n    + red in H; rewrite e in H; discriminate.\nQed.\n\n\nLemma f_succ_eqn : forall alpha i,\n    f_ (E0succ alpha) i = iterate (f_ alpha) i i.\nProof with auto with E0.\n  intros;rewrite f_eq2,  f_star_iterate ...\n  -  now rewrite E0pred_of_Succ.\nQed.\n\n\nLemma id_le_f_alpha (alpha: E0) : forall i, i <= f_ alpha i. \nProof.\n pattern alpha; apply (well_founded_induction E0lt_wf);\n   clear alpha; intros alpha IHalpha.\n destruct (Zero_Limit_Succ_dec alpha) as [[HZero | Hlim] | Hsucc].\n   - subst; intros i ; rewrite !f_zero_eqn; auto with arith. \n   - intros i.  rewrite !(f_lim_eqn alpha).\n     + apply IHalpha,  Canon_lt; now apply Limit_not_Zero.\n     + apply Hlim.\n   - destruct Hsucc as [beta Hbeta]; subst; intro i; rewrite f_succ_eqn. \n     generalize i at 1 3; induction i. \n     + intros; cbn; auto with arith.  \n     + intros; cbn; transitivity (iterate (f_ beta) i i0); auto. \n     apply (IHalpha beta (Lt_Succ beta)). \nQed.\n\n\nSection Properties_of_f_alpha.\n\nRecord  Q (alpha:E0) : Prop :=\n    mkQ {\n        QA : strict_mono (f_ alpha);\n        QD : dominates_from 2 (f_ (E0succ alpha)) (f_ alpha);\n        QE : forall beta n, Canon_plus n alpha beta -> \n                            f_ beta n <= f_ alpha n}.\n\nSection The_induction.\n  \n  Lemma QA0 : strict_mono (f_ E0zero).\n  Proof. \n    intros n p H; repeat rewrite f_zero_eqn; auto with arith. \n  Qed. \n\n\n\n  Lemma QD0 : dominates_from 2 (f_ (E0succ E0zero)) (f_ E0zero).\n  Proof. \n    intros p Hp; rewrite f_succ_eqn, f_zero_eqn. \n    apply Nat.lt_le_trans with (iterate S p p).\n    - replace (iterate S p p) with (p + p).\n      + lia.\n      + clear Hp; generalize p at 2 4; induction p. \n        * cbn; reflexivity.\n        * intro p0; cbn; now rewrite IHp. \n    -  apply Nat.eq_le_incl, iterate_ext. intros ?; now rewrite f_zero_eqn.\n  Qed.\n\n  \n  (** TODO : Study the equality F_ alpha i = Nat.pred (f_ alpha (S i)) *)\n\n\n  \nEnd The_induction.\n\nEnd Properties_of_f_alpha.\n\n(* begin  snippet DemoAssumptions *)\nPrint Assumptions F_zero_eqn.\n\n(* end snippet DemoAssumptions *)\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/Epsilon0/F_alpha.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.6858403565037032}}
{"text": "(*|\n#################################################\nmutual recursion on an inductive type and ``nat``\n#################################################\n\n:Link: https://stackoverflow.com/q/50477918\n|*)\n\n(*|\nQuestion\n********\n\nConsider this example:\n|*)\n\nInductive T :=\n| foo : T\n| bar : nat -> T -> T.\n\nFail Fixpoint evalT (t : T) {struct t} : nat :=\n  match t with\n  | foo => 1\n  | bar n x => evalBar x n\n  end\nwith\nevalBar (x : T) (n : nat) {struct n} : nat :=\n  match n with\n  | O => 0\n  | S n' => evalT x + evalBar x n'\n  end. (* .fails .unfold *)\n\n(*|\nCoq rejects it.\n\nI understand that termination checker got confused by two unrelated\ninductive types (``T`` and ``nat``). However, it looks like the\nfunction I am trying to define will indeed terminate. How can I make\nCoq accept it?\n|*)\n\n(*|\nAnswer (eponier)\n****************\n\nAnother solution is to use a nested fixpoint.\n|*)\n\nFixpoint evalT (t : T) {struct t} : nat :=\n  match t with\n  | foo => 1\n  | bar n x => let fix evalBar n {struct n} :=\n                   match n with\n                   | 0 => 0\n                   | S n' => evalT x + evalBar n'\n                   end\n               in evalBar n\n  end.\n\n(*|\nThe important point is to remove the argument ``x`` from ``evalBar``.\nThus the recursive call to ``evalT`` is done on the ``x`` from ``bar n\nx``, not the ``x`` given as an argument to ``evalBar``, and thus the\ntermination checker can validate the definition of ``evalT``.\n\nThis is the same idea that makes the version with ``nat_rec`` proposed\nin another answer work.\n|*)\n\n(*|\nAnswer (krokodil)\n*****************\n\nOne solution I found is to use ``nat_rec`` instead of ``evalBar``:\n|*)\n\nReset evalT. (* .none *)\nFixpoint evalT (t : T) {struct t} : nat :=\n  match t with\n  | foo => 1\n  | bar n x => @nat_rec _ 0 (fun n' t' => evalT x + t') n\n  end.\n\n(*|\nIt works but I wish I could hide ``nat_rec`` under ``evalBar``\ndefinition to hide details. In my real project, such construct is used\nseveral times.\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/mutual-recursion-on-an-inductive-type-and-nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173791645582, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.6858403465087074}}
{"text": "(* ###################################################################### *)\n(* taken from http://www.cis.upenn.edu/~rrand/popl_2016/ *)\n(** * Proofs and Programs *)\n\n(** (We use [admit] and [Admitted] to hide solutions from exercises.) *)\n\nAxiom admit : forall {T}, T.\n\n(** Everything in Coq is built from scratch -- even booleans!\n    Fortunately, they are already provided by the Coq standard\n    library, but we'll review their definition here to get familiar\n    with the basic features of the system. *)\n\n(** [Inductive] is Coq's way of defining an algebraic datatype.  Its\n    syntax is similar to OCaml's ([type]) or Haskell's ([data]). Here,\n    we define [bool] as a simple algebraic datatype. *)\n\nModule Bool.\n\nInductive bool : Type :=\n| true : bool\n| false : bool.\n\n(** **** Exercise: 1 star (trivalue)  *)\n(** Define a three-valued data type, representing ternary logic.  Here\n    something can be true, false and unknown. *)\n\nInductive trivalue : Type :=\n(* SOLUTION: *)\n| tv_true\n| tv_false\n| tv_unknown\n.\n(** [] *)\n\n(** We can write functions that operate on [bool]s by simple pattern\n    matching, using the [match] keyword. *)\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\n(** We can pattern-match on multiple arguments simultaneously, and\n    also use \"_\" as a wildcard pattern. *)\n\nDefinition orb (b1 b2: bool) : bool :=\n  match b1, b2 with\n  | false, false => false\n  | _, _ => true\n  end.\n\nPrint orb.\n\n(** We can also use an [if] statement, which matches on the first\n    constructor of any two-constructor datatype, in our definition. *)\n\nDefinition andb (b1 b2: bool) : bool :=\n  if b1 then b2 else false.\n\n(** Let's test our functions. The [Compute] command tells Coq to\n    evaluate an expression and print the result on the screen.*)\n\nCompute (negb true).\nCompute (orb true false).\nCompute (andb true false).\n\n(** **** Exercise: 1 star (xor)  *)\n(** Define xor (exclusive or). *)\n\nDefinition xorb (b1 b2 : bool) : bool :=\n(* SOLUTION: *) if b1 then negb b2 else b2. \nCompute (xorb true true).\n(** [] *)\n\n\n(** What makes Coq different from normal functional programming\n    languages is that it allows us to formally _prove_ that our\n    programs satisfy certain properties. The system mechanically\n    verifies these proofs to ensure that they are correct.\n\n    We use [Lemma], [Theorem] and [Example] to write logical\n    statements. Coq requires us to prove these statements using\n    _tactics_, which are commands that manipulate formulas using basic\n    logic rules. Here's an example showing some basic tactics in\n    action. *)\n\n(** New tactics\n    -----------\n\n    - [intros]: Introduce variables into the context, giving them\n      names.\n\n    - [simpl]: Simplify the goal.\n\n    - [reflexivity]: Prove that some expression [x] is equal to itself. *)\n\nExample andb_false_l : forall b, andb false b = false.\nProof.\n(* WORKED IN CLASS *)\n  intros b. (* introduce the variable b *)\n  simpl. (* simplify the expression *)\n  reflexivity. (* solve for x = x *)\nQed.\n\n\n(** **** Exercise: 1 star (orb_true_l)  *)\nTheorem orb_true_l :\n  forall b, orb true b = true.\nProof.\n(* SOLUTION: *)\n  reflexivity.\nQed.\n(** [] *)\n\n(** Some proofs require case analysis. In Coq, this is done with the\n    [destruct] tactic. *)\n\n(** New tactic\n    ----------\n\n    - [destruct]: Consider all possible constructors of an inductive\n      data type, generating subgoals that need to be solved\n      separately. *)\n\n\n(*  FULL: Here's an example of [destruct] in action. *)\n\nLemma orb_true_r : forall b : bool, orb b true = true.\n(* Here we explicitly annotate b with its type, even though Coq could infer it. *)\nProof.\n(* WORKED IN CLASS *)\n  intros b.\n  simpl. (* This doesn't do anything, since orb pattern matches on the\n  first variable first. *)\n  destruct b. (* Do case analysis on b *)\n  + (* We use the \"bullets\" '+' '-' and '*' to delimit subgoals *)\n    (* true case *)\n    simpl.\n    reflexivity.\n  + (* false case *)\n    simpl.\n    reflexivity.\nQed.\n\n(** We can call [destruct] as many times as we want, generating deeper subgoals. *)\n\nTheorem andb_commutative : forall b1 b2 : bool, andb b1 b2 = andb b2 b1.\nProof.\n(* WORKED IN CLASS *)\n  intros b1 b2.\n  destruct b1.\n  + destruct b2.\n    - simpl. reflexivity.\n    - simpl. reflexivity. (* bullets need to be consistent *)\n\n(** Alternatively, if all the subgoals are solved the same way, we can\n    use the [;] operator to execute a tactic on _all_ the generated\n    subgoals, like this: *)\n\n  + destruct b2; simpl; reflexivity.\nQed.\n\n(** **** Exercise: 1 star (andb_false_r)  *)\n(** Show that b AND false is always false  *)\n\nTheorem andb_false_r :\n(* SOLUTION: *)\n  forall b, andb b false = false.\nProof.\n(* SOLUTION: *)\n  intros b. destruct b.\n  + reflexivity.\n  + reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (xorb_b_neg_b)  *)\n(** Show that b xor (not b) is always true. *)\n\nTheorem xorb_b_neg_b :\n(* SOLUTION: *)\n  forall b, xorb b (negb b) = true.\nProof.\n(* SOLUTION: *)\n  intros b. destruct b.\n  + reflexivity.\n  + reflexivity.\nQed.\n\n(** Sometimes, we want to show a result that requires hypotheses. In\n    Coq, [P -> Q] means that [P] implies [Q], or that [Q] is true\n    whenever [P] is. We can use [->] multiple times to express that\n    more than one hypothesis are needed; the syntax is similar to how\n    we write multiple-argument functions in OCaml or Haskell. For\n    example: *)\n\nTheorem rewrite_example : forall b1 b2 b3 b4,\n  b1 = b4 ->\n  b2 = b3 ->\n  andb b1 b2 = andb b3 b4.\n\n(** We can use the [intros] tactic to give hypotheses names,\n    bringing them into the proof context. *)\n\nProof.\n  intros b1 b2 b3 b4 eq14 eq23.\n\n(** Now, our context has two hypotheses: [eq14], which states\n    that [b1 = b4], and [eq23], stating that [b2 = b3]. \n\n     Here are some tactics for using hypotheses and previously proved\n    results: *)\n\n(** New tactics\n    -----------\n\n    - [rewrite]: Replace one side of an equation by the other.\n\n    - [apply]: Suppose that the current goal is [Q]. If [H : Q], then\n      [apply H] solves the goal. If [H : P -> Q], then [apply H]\n      replaces [Q] by [P] in the goal. If [H] has multiple hypotheses,\n      [H : P1 -> P2 -> ... -> Pn -> Q], then [apply H] generates one\n      subgoal for each [Pi]. *)\n\n  rewrite eq14. (* replace b1 with b4 in the goal *)\n  rewrite <- eq23. (* replace b3 with b2 in the goal. *)\n  apply andb_commutative. (* solve using our earlier theorem *)\nQed.\n\n\n(** **** Exercise: 1 star (xorb_same)  *)\n(** Show that if [b1 = b2] then b1 xor b2 is false. *)\n\nTheorem xorb_same :\n(* SOLUTION: *)\n  forall b1 b2, b1 = b2 -> xorb b1 b2 = false.\nProof.\n(* SOLUTION: *)\n  intros b1 b2 eq.\n  rewrite eq.\n  destruct b2.\n  + reflexivity.\n  + reflexivity.\nQed.\n\nEnd Bool.\n\n\n(* ###################################################################### *)\n\n(** We will use the following option to make polymorphism more\n    convenient. *)\n\nSet Implicit Arguments.\n\n(** * Lists *)\n\n(** We will now shift gears and study more interesting functional\n    programs; namely, programs that manipulate _lists_. *)\n\nModule List.\n\n(** Here's a polymorphic definition of a [list] type in Coq: *)\n\nInductive list (T : Type) :=\n| nil : list T\n| cons : T -> list T -> list T.\n\n(** Here's how we define a function to append two lists.\n    Note that we declare the type parameter T. *)\n\nFixpoint app T (l1 l2 : list T) : list T :=\n  match l1 with\n  | nil => l2\n  | cons h t  => cons h (app t l2)\n  end.\n\n(** Coq comes with a syntax extension mechanism for defining custom\n    notations. Without getting into details, here's how we can give\n    familiar syntax for lists. *)\n\nNotation \"h :: t\" := (cons h t) (at level 60, right associativity).\nNotation \"[ ]\" := (nil _).\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y [] ) ..).\nNotation \"l1 ++ l2\" := (app l1 l2) (at level 60, right associativity).\n\n(** Since [nil] can potentially be of any type, we add an underscore\n    to tell Coq to infer the type from the context. *)\n\n(** We can now check the types of expressions involving lists. *)\n\nCheck [].\nCheck true :: [].\nCheck [true ; false].\nCheck [true ; false] ++ [false].\n\n(** And compute the last. *)\nCompute [true ; false] ++ [false].\n\n(** Note that we can use define notations and functions\n    simultaneously: *)\n\nReserved Notation \"l1 @ l2\" (at level 60).\nFixpoint app' T (l1 l2 : list T) : list T :=\n  match l1 with\n  | [] => l2\n  | h :: t  => h :: (t @ l2)\n  end\n\n  where \"l1 @ l2\" := (app' l1 l2).\n\n\n(** **** Exercise: 1 star (snoc)  *)\n(** Define [snoc], which adds an element to the end of a list. *)\n\nFixpoint snoc T (l : list T) (x : T) : list T :=\n(* SOLUTION: *)\n  match l with\n  | [] => [x]\n  | h :: t => h :: snoc t x\n  end.\n\n(** It is easy to show that appending [nil] to the left of a list\n    yields the original list.  *)\n\nLemma app_nil_l: forall T (l : list T), [] ++ l  = l.\nProof.\n(* WORKED IN CLASS *)\n  intros T l.\n  simpl.\n  reflexivity.\nQed.\n\n(** Showing the symmetric result is more difficult\n    since it doesn't follow by simplification alone. *)\n\nLemma app_nil_r: forall T (l : list T), l ++ []  = l.\nProof.\n  intros T l.\n  simpl. (* Does nothing *)\n  destruct l as [| h t]. (* Notice the [as] clause, which allows us\n                            to name constructor arguments. *)\n  + simpl.\n    reflexivity.\n  + simpl. (* no way to proceed... *)\n\n(** The problem is that we can only prove the result for [h::t]\n    if we already know that it is valid for [t]. We need a bigger\n    hammer here... *)\n\n(** New tactic\n    ----------\n\n    - [induction]: Argue by induction. It works as [destruct], but\n    additionally giving us an inductive hypothesis in the inductive\n    case. *)\nRestart.\n  intros T l.\n  induction l as [| h t IH]. (* Note the additional name [IH], given to our\n                                inductive hypothesis *)\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IH.\n    reflexivity.\nQed.\n\n(** As a rule of thumb, when proving some property of a recursive\n    function, it is a good idea to do induction on the recursive\n    argument of the function. For instance, let's show that [app] is\n    associative: *)\n\nLemma app_assoc :\n  forall T (l1 l2 l3 : list T),\n    l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\nProof.\n(* WORKED IN CLASS *)\n  intros T l1 l2 l3.\n  induction l1 as [|h1 t1 IH]. (* l1 is the right choice here, since [app] is defined\n                                  by recursion on the first argument. *)\n  - (* [] *)\n    simpl.\n    reflexivity.\n  - (* h1 :: t1 *)\n    simpl.\n    rewrite IH.\n    reflexivity.\nQed.\n\n(** Exercise: Try to do induction on [l2] and [l3] in the\n    above proof, and see where it fails. *)\n\n(** **** Exercise: 2 stars (snoc_app)  *)\n(** Prove that [snoc l x] is equivalent to appending [x] to the end of\n    [l]. *)\n\nLemma snoc_app : forall T (l : list T) (x : T), snoc l x = l ++ [x].\nProof.\n(* SOLUTION: *)\n  intros T l x.\n  induction l as [|h t IH].\n  + reflexivity.\n  + simpl. rewrite IH. reflexivity.\nQed.\n(** [] *)\n\n(** The natural numbers are defined in Coq's standard library as follows:\n\n    Inductive nat : Type :=\n      | O : nat\n      | S : nat -> nat.\n\n    where [S] stands for \"Successor\".\n\n    Coq prints [S (S (S O))] as \"3\", as you might expect.\n\n*)\n\nSet Printing All.\n\nCheck 0.\nCheck 2.\nCheck 2 + 2.\n\nUnset Printing All.\n\nCheck S (S (S O)).\nCheck 2 + 3.\nCompute 2 + 3.\n\n(** Now we can define the [length] function: *)\n\nFixpoint length T (l : list T) :=\n  match l with\n  | [] => 0\n  | h :: t => 1 + length t\n  end.\n\nCompute length [1; 1; 1].\n\n(** **** Exercise: 3 stars (app_length)  *)\n\nLemma app_length : forall T (l1 l2 : list T),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n(* SOLUTION: *)\n  intros T l1 l2.\n  induction l1 as [|h t IH].\n  + reflexivity.\n  + simpl. rewrite IH. reflexivity.\nQed.\n\n(** Often we find ourselves needing to reason about _contradictory_\n    hypotheses. Whenever we have a hypothesis that equates two\n    expressions that start with different constructors, we can use the\n    [discriminate] tactic to prune that subgoal.\n\n    This is a particular case of what is known as _the principle of\n    explosion_, which states that a contradiction implies anything. *)\n\n(** New Tactic\n    ----------\n\n    - [discriminate]: Looks for an equation between terms starting\n      with different constructors, and solves the current goal. *)\n\n(* Let's try to prove that if [l1 ++ l2 = []] then [l1] is [[]] *)\n\nLemma app_eq_nil_l : forall T (l1 l2 : list T),\n  l1 ++ l2 = [] -> l1 = [].\nProof.\n(* WORKED IN CLASS *)\n  intros T l1 l2 H.\n  destruct l1 as [| h t].\n  + (* [] *)\n    reflexivity.\n  + (* h :: t *)\n    simpl in H.\n    discriminate.\nQed.\n\n(** **** Exercise: 2 stars (app_eq_nil_r)  *)\n(** Prove the same about [l2]. *)\n\nLemma plus_nil_r : forall T (l1 l2 : list T),\n  l1 ++ l2 = [] -> l2 = [].\nProof.\n(* SOLUTION: *)\n  intros T l1 l2 H.\n  destruct l1 as [|h t].\n  + apply H.\n  + discriminate.\nQed.\n(** [] *)\n\n(** Coq, like many other proof assistants, requires functions to\n    be _total_ and defined for all possible inputs; in particular,\n    recursive functions are always required to terminate.\n\n    Since there is no general algorithm for deciding whether a\n    function is terminating or not, Coq needs to settle for an\n    incomplete class of recursive functions that is easy to show\n    terminating. This means that, although every recursive function\n    accepted by Coq is terminating, there are many recursive functions\n    that always terminate but are not accepted by Coq, because it\n    isn't \"smart enough\" to realize that they indeed terminate.\n\n    The criterion adopted by Coq for deciding whether to accept a\n    definition or not is _structural recursion_: All recursive calls\n    must be performed on _sub-terms_ of the original argument.\n\n    Note that the definition of _sub-terms_ used in context is purely syntactic\n    hence the following definition fails.\n\n**)\n\nFail Fixpoint shuffle T (l1 l2 : list T) :=\n  match l1 with\n  | [] => l2\n  | h :: t => h :: shuffle l2 t\n  end.\n\n(** The [Fail] keyword instructs Coq to ignore a command when it\n    fails, but to fail if the command succeeds. It is useful for\n    showing certain pieces of code that are not accepted by the\n    language.\n\n    In this case, we can rewrite [shuffle] so that it is accepted by\n    Coq's termination checker: *)\n\nFixpoint shuffle T (l1 l2 : list T) :=\n  match l1, l2 with\n  | [], _ => l2\n  | _, [] => l1\n  | h1 :: t1, h2 :: t2 => h1 :: h2 :: shuffle t1 t2\n  end.\n\nPrint shuffle.\n\n\n(** Let's define list reversal function and prove some of its basic\n    properties. *)\n\nFixpoint rev T (l : list T) :=\n  match l with\n  | [] => []\n  | h :: t => (rev t) ++ [h]\n  end.\n\nLemma rev_app : forall T (l1 l2 : list T), rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n(* WORKED IN CLASS *)\n  intros T l1 l2.\n  induction l1 as [|h t IH].\n  + simpl.\n    rewrite app_nil_r.\n    reflexivity.\n  + simpl.\n    rewrite IH.\n    rewrite app_assoc.\n    reflexivity.\nQed.\n\n(** **** Exercise: 2 stars (rev_app)  *)\n(** Using [rev_app], prove that reversing a list twice results in the\n    same list. *)\n\nLemma rev_involutive : forall T (l : list T), rev (rev l) = l.\nProof.\n(* SOLUTION: *)\n  intros T l. induction l as [|h t IH].\n  + reflexivity.\n  + simpl. rewrite rev_app. rewrite IH. reflexivity.\nQed.\n\n(** Notice that the definition of list reversal given above runs in\n    quadratic time. Here is a tail-recursive equivalent that runs in\n    linear time. *)\n\nFixpoint tr_rev_aux T (l acc : list T) : list T :=\n  match l with\n  | [] => acc\n  | x :: l => tr_rev_aux l (x :: acc)\n  end.\n\nDefinition tr_rev T (l: list T) := tr_rev_aux l [].\n\n(** Here, [acc] is an accumulator argument that holds the portion of\n    the list that we have reversed so far. Let's prove that [tr_rev]\n    is equivalent to [rev]. For this we will need another tactic: *)\n\n\n(** New Tactic\n    ----------\n\n    - [unfold]: Calling [unfold foo] expands the definition of [foo]\n      in the goal.\n*)\n\nLemma tr_rev_eq_rev_try_one :\n  forall T (l : list T),\n    tr_rev l = rev l.\nProof.\n  intros T l.\n  unfold tr_rev.\n  induction l as [| h t IH].\n  + simpl.\n    reflexivity.\n  + simpl.\n    (* and now we're stuck... *)\nAbort.\n\n(** The problem is that the result we are trying to prove is not\n    general enough. We will need the following auxiliary lemma: *)\n\nLemma tr_rev_aux_eq_rev :\n  forall T (l1 l2 : list T),\n    tr_rev_aux l1 l2 = rev l1 ++ l2.\nProof.\n  intros T l1 l2.\n  induction l1 as [|x l1 IH].\n  - simpl. reflexivity.\n  - simpl.\n\n(** Our inductive hypothesis is too weak to proceed. We want\n    [tr_rev_aux l1 l2 = rev l1 ++ l2] for all [l2]. Let's try again\n    from the start. *)\n\nRestart.\n  intros T l1. (* Now we don't introduce l2, leaving it general. *)\n  induction l1 as [|x l1 IH].\n  - intros l2. simpl. reflexivity.\n  - intros l2. (* Behold our induction hypothesis! *)\n    simpl.\n    rewrite IH.\n\n(** We can use the [SearchAbout] command to look up lemmas that can be\n    used with certain expressions ([C-c C-a C-a] in Proof General). *)\n\n    SearchAbout (_ ++ _ ++ _).\n    rewrite <- app_assoc.\n    simpl.\n    reflexivity.\nQed.\n\n(** Our result follows easily: *)\n\nLemma tr_rev_eq_rev :\n  forall T (l : list T),\n    tr_rev l = rev l.\nProof.\n(* WORKED IN CLASS *)\n  intros T l.\n  unfold tr_rev.\n  rewrite tr_rev_aux_eq_rev.\n  SearchAbout (_ ++ []).\n  apply app_nil_r.\nQed.\n\nEnd List.\n\n\n(** You may have noticed that several of the proofs in this section,\n    particularly regarding the associativity of the append function,\n    closely resemble proofs about arithmetic. You might also be interested\n    in Coq for its ability to prove results in mathematics. The\n    material in this section should be sufficient for you to start\n    formulating theorems about the natural numbers, such as the\n    commutativity, associativity and distributivity of addition and\n    multiplication.\n\n    As noted above, the natural numbers are defined as follows:\n\n    Inductive nat : Type :=\n      | O : nat\n      | S : nat -> nat.\n\n    From there you can define +, -, *, /, ^ etc. We encourage you to\n    start on your own, but to help we've included a module on arithmetic\n    We hope you enjoy.\n\n*)\n", "meta": {"author": "santifa", "repo": "masterarbeit", "sha": "088210e071464831d3e496d3a8faac0aac494228", "save_path": "github-repos/coq/santifa-masterarbeit", "path": "github-repos/coq/santifa-masterarbeit/masterarbeit-088210e071464831d3e496d3a8faac0aac494228/learn-coq/list_basics.sol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.8791467627598857, "lm_q1q2_score": 0.6857282332340925}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) : natural := plus Zero (plus Zero lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj81_coqofml_Qep0xC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137997, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6856714888502254}}
{"text": "(* Additional definitions and lemmas on lists *)\n\nRequire Import Arith.\nRequire Import Max.\nRequire Import Min.\nRequire Import List.\nRequire Import Omega.\nRequire Import Ott.ott_list_support.\nRequire Import Ott.ott_list_base.\nRequire Import Ott.ott_list_nth.\nImport List_lib_Arith.\n\n\n\nSection Lists.\n\nVariables A B C : Type.\nImplicit Types x : A.\nImplicit Types y : B.\nImplicit Types z : C.\nImplicit Types xs l : list A.\nImplicit Types ys : list B.\nImplicit Types zs : list C.\nImplicit Types f : A -> B.\nImplicit Types g : B -> C.\nImplicit Types m n : nat.\nSet Implicit Arguments.\n\n\n\n(*** Prefix and suffix extraction ***)\n\nFixpoint take n l {struct l} : list A :=\n  match n, l with\n    | 0, _ => nil\n    | _, nil => nil\n    | S m, h::t => h :: (take m t)\n  end.\n\nLemma take_0 : forall l, take 0 l = nil.\nProof. destruct l; reflexivity. Qed.\nLemma take_nil : forall n, take n nil = nil.\nProof. destruct n; reflexivity. Qed.\n\nLemma take_all :\n  forall l n, length l <= n -> take n l = l.\nProof.\n  induction l; destruct n; intros; try reflexivity.\n  solve [inversion H].\n  simpl in * . apply (f_equal2 (@cons A)). reflexivity. apply IHl. omega.\nQed.\n\nLemma take_length :\n  forall l n, length (take n l) = min n (length l).\nProof.\n  induction l; destruct n; intros; simpl; try rewrite IHl; reflexivity.\nQed.\n\nLemma take_some_length :\n  forall l n, n <= length l -> length (take n l) = n.\nProof.\n  intros. rewrite take_length. auto with arith.\nQed.\n\nLemma take_nth :\n  forall l m n,\n    nth_error (take m l) n = if le_lt_dec m n then error else nth_error l n.\nProof.\n  intros until n. generalize dependent l. generalize dependent m.\n  induction n; intros; simpl.\n  destruct m; destruct l; reflexivity.\n  destruct l; simpl.\n  destruct (le_lt_dec m (S n)); destruct m; reflexivity.\n  destruct m. reflexivity.\n  rewrite IHn. symmetry. apply le_lt_dec_S.\nQed.\n\nLemma take_take :\n  forall l m n, take m (take n l) = take (min m n) l.\nProof.\n  induction l; intros; simpl.\n  destruct (min m n); destruct n; repeat rewrite take_nil; reflexivity.\n  destruct n; destruct m; try reflexivity.\n  simpl. rewrite IHl. reflexivity.\nQed.\n\nFixpoint drop n l {struct l} : list A :=\n  match n, l with\n    | 0, _ => l\n    | _, nil => nil\n    | S m, h::t => drop m t\n  end.\n\nLemma drop_0 : forall l, drop 0 l = l.\nProof. destruct l; reflexivity. Qed.\nLemma drop_nil : forall n, drop n nil = nil.\nProof. destruct n; reflexivity. Qed.\n\nLemma drop_all :\n  forall l n, length l <= n -> drop n l = nil.\nProof.\n  induction l; destruct n; intros; try reflexivity.\n  solve [inversion H].\n  simpl in * . apply IHl. omega.\nQed.\n\nLemma drop_length : forall l n, length (drop n l) = length l - n.\nProof.\n  induction l; destruct n; intros; simpl; try rewrite IHl; reflexivity.\nQed.\n\nLemma match_drop :\n  forall l n, match drop n l with\n                | nil => length l <= n\n                | _::_ => length l > n\n              end.\nProof.\n  intros. destruct (le_gt_dec (length l) n) as [Le | Gt].\n  rewrite drop_all; assumption.\n  generalize (conj (refl_equal (length (drop n l))) (refl_equal (drop n l))).\n  pattern (drop n l) at 1 3.\n  case (drop n l); intros; rewrite drop_length in H; destruct H; simpl in * .\n  elimtype False; omega.\n  rewrite <- H0. assumption.\nQed.\n\nLemma drop_nth :\n  forall l m n, nth_error (drop m l) n = nth_error l (m + n).\nProof.\n  induction l; intros.\n  rewrite drop_nil. repeat rewrite nth_error_nil. reflexivity.\n  destruct m; simpl; auto.\nQed.\n\nLemma drop_drop :\n  forall l m n, drop m (drop n l) = drop (n + m) l.\nProof.\n  intros; generalize dependent l. induction n; simpl; intros.\n  rewrite drop_0. reflexivity.\n  destruct l; simpl; [destruct m | rewrite IHn]; reflexivity.\nQed.\n\nLemma take_app_drop : forall l n, take n l ++ drop n l = l.\nProof.\n  intros l n; generalize dependent l; induction n; intros.\n  rewrite take_0; rewrite drop_0; reflexivity.\n  induction l; simpl. reflexivity.\n  rewrite IHn. reflexivity.\nQed.\n\nLemma take_app_exact :\n  forall l l' n, length l = n -> take n (l ++ l') = l.\nProof.\n  induction l; intros; subst n; simpl in * .\n  rewrite take_0. reflexivity.\n  rewrite IHl; reflexivity.\nQed.\n\nLemma drop_app_exact :\n  forall l l' n, length l = n -> drop n (l ++ l') = l'.\nProof.\n  induction l; intros; subst n; simpl in * .\n  rewrite drop_0. reflexivity.\n  rewrite IHl; reflexivity.\nQed.\n\nLemma take_app_long :\n  forall l l' n, n <= length l -> take n (l ++ l') = take n l.\nProof.\n  intros.\n  set (tmp := l) in |- * at 2. rewrite <- (take_app_drop l n). subst tmp.\n  rewrite app_ass. rewrite take_app_exact. reflexivity.\n  apply take_some_length. assumption.\nQed.\n\nLemma drop_app_long :\n  forall l l' n, n <= length l -> drop n (l ++ l') = drop n l ++ l'.\nProof.\n  intros.\n  set (tmp := l) in |- * at 2. rewrite <- (take_app_drop l n). subst tmp.\n  rewrite app_ass. rewrite drop_app_exact. reflexivity.\n  apply take_some_length. assumption.\nQed.\n\nLemma take_app_short :\n  forall l l' n, take (length l + n) (l ++ l') = l ++ take n l'.\nProof. intros. induction l; simpl; congruence. Qed.\n\nLemma drop_app_short :\n  forall l l' n, drop (length l + n) (l ++ l') = drop n l'.\nProof. intros. induction l; simpl; congruence. Qed.\n\nLemma take_from_app :\n  forall l l', take (length l) (l ++ l') = l.\nProof.\n  intros. replace (length l) with (length l + 0). 2: omega.\n  rewrite take_app_short. rewrite take_0.\n  symmetry. apply app_nil_end.\nQed.\n\nLemma drop_from_app :\n  forall l l', drop (length l) (l ++ l') = l'.\nProof.\n  intros. replace (length l) with (length l + 0). 2: omega.\n  rewrite drop_app_short. apply drop_0.\nQed.\n\nLemma take_take_app :\n  forall l l' n, n <= length l -> take n (take n l ++ l') = take n l.\nProof.\n  intros. rewrite take_app_long. rewrite take_take.\n  destruct (min_dec n n) as [Eq | Eq]; rewrite Eq; reflexivity.\n  rewrite take_some_length; trivial.\nQed.\n\nLemma drop_take_app :\n  forall l l' n, n <= length l -> drop n (take n l ++ l') = l'.\nProof.\n  intros. rewrite drop_app_exact. reflexivity.\n  apply take_some_length. assumption.\nQed.\n\n\n\n(*** End of the Lists section ***)\n\nEnd Lists.\n\nHint Rewrite take_0 take_nil take_length take_nth take_take : take_drop.\nHint Rewrite take_all : take_drop_short.\nHint Rewrite take_some_length : take_drop_long.\nHint Rewrite drop_0 drop_nil drop_length drop_nth drop_drop : take_drop.\nHint Rewrite drop_all : take_drop_short.\nHint Rewrite take_app_drop : take_drop.\nHint Rewrite take_app_exact drop_app_exact : take_drop_exact.\nHint Rewrite take_app_long drop_app_long : take_drop_long.\nHint Rewrite take_app_short drop_app_short : take_drop.\nHint Rewrite take_from_app drop_from_app : take_drop.\nHint Rewrite take_take_app drop_take_app : take_drop_long.\n\n(* Break the list [original] into two pieces [prefix] and [suffix]\n   at the location indicated by [cut_point]. [cut_point] indicates\n   the number of elements to retain in [prefix]; it may also be\n   a list whose length is used. This tactic leaves either one or two\n   goals. The first goal has a hypothesis stating that the length of\n   [prefix] is [cut_point]. The second goal has [original] left\n   unchanged and an additional hypothesis stating that\n   [length original < cut_point]; the tactic tries refuting this by\n   calling omega. *)\nLtac cut_list original cut_point prefix suffix :=\n  let l := fresh \"whole\" with Ineq := fresh \"Ineq\" with\n      Eq := fresh \"Decomposition\" with Eql := fresh \"Eqlen\" with\n      p := fresh \"prefix\" with s := fresh \"suffix\" with\n      n := match type of cut_point with\n             | nat => cut_point\n             | list _ => constr:(length cut_point)\n             | _ => fail \"cut_list: unrecognised cut_point type\"\n           end in (\n    destruct (le_lt_dec n (length original)) as [Ineq | Ineq]; [\n      (**length original >= n, so length prefix = n**)\n      assert (Eql := take_some_length original Ineq); clear Ineq;\n      generalize dependent original; intro l;\n      assert (Eq := take_app_drop l n);\n      set (p := (take n l)) in *; set (s := (drop n l)) in *;\n      clearbody p s; subst l;\n      (*We've done the cutting, now we try to do some simplifications*)\n      autorewrite with lists take_drop; intros;\n      rename p into prefix; rename s into suffix\n    | (**length original < n**)\n      try (equate_list_lengths; elimtype False; omega) ]\n  ).\n\n(* Look for equations between lists that can be simplified.\n   [?p ++ ?s = ?p' ++ ?s'] is simplified into [?p = ?p'] and [?s = ?s'] *)\nLtac parallel_split :=\n  let eq' := fresh \"eq\" with tmp := fresh \"tmp\" with\n      EqPrefix := fresh \"Eql\" with EqSuffix := fresh \"Eql\" in (\n    pose (eq' := eq);\n    repeat match goal with\n             | H : app ?p ?s = app ?p' ?s' |- _ =>\n               (\n                 assert (tmp : length p = length p');\n                   [equate_list_lengths; omega | idtac];\n                 assert (EqPrefix := app_inj_prefix_length_prefix _ _ _ _ tmp H);\n                 rewrite <- EqPrefix in H;\n                 assert (EqSuffix := app_inj_prefix _ _ _ H);\n                 clear tmp H\n               ) || (\n                 assert (tmp : length s = length s');\n                   [equate_list_lengths; omega | idtac];\n                 assert (EqSuffix := app_inj_prefix_length_suffix _ _ _ _ tmp H);\n                 rewrite <- EqSuffix in H;\n                 assert (EqPrefix := app_inj_suffix _ _ _ H);\n                 clear tmp H\n               ) || fold eq' in H\n             | H : cons ?a ?l = cons ?a' ?l' |- _ =>\n               injection H; intro; clear H; intro H\n           end;\n    unfold eq' in *; clear eq'\n  ).\n(* Ad-hoc obsolete tactic (superceded by [parallel_split]) *)\nLtac parallel_split_maps :=\n  repeat match goal with\n           | H : map ?f ?p ++ map ?f ?s = ?p' ++ ?s' |- _ =>\n             assert (Eqlen' : length (map f p) = length p');\n               [equate_list_lengths; omega | idtac];\n             assert (EqPrefix := app_inj_prefix_length_prefix _ _ _ _ Eqlen' H);\n             rewrite <- EqPrefix in H;\n             assert (EqSuffix := app_inj_prefix _ _ _ H);\n             clear Eqlen' H\n           | H : _ ++ _ = map _ _ ++ map _ _ |- _ => symmetry in H\n         end.\n\n\n\n\n(*** The End. ***)\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_takedrop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924672, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6856185084718237}}
{"text": "(** * Basics: Functional Programming in Coq *)\nPrint LoadPath.\n(* REMINDER:\n\n          #####################################################\n          ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n          #####################################################\n\n   (See the [Preface] for why.)\n*)\n\n(* ################################################################# *)\n(** * Introduction *)\n\n(** The functional programming style is founded on simple, everyday\n    mathematical intuition: If a procedure or method has no side\n    effects, then (ignoring efficiency) all we need to understand\n    about it is how it maps inputs to outputs -- that is, we can think\n    of it as just a concrete method for computing a mathematical\n    function.  This is one sense of the word \"functional\" in\n    \"functional programming.\"  The direct connection between programs\n    and simple mathematical objects supports both formal correctness\n    proofs and sound informal reasoning about program behavior.\n\n    The other sense in which functional programming is \"functional\" is\n    that it emphasizes the use of functions (or methods) as\n    _first-class_ values -- i.e., values that can be passed as\n    arguments to other functions, returned as results, included in\n    data structures, etc.  The recognition that functions can be\n    treated as data gives rise to a host of useful and powerful\n    programming idioms.\n\n    Other common features of functional languages include _algebraic\n    data types_ and _pattern matching_, which make it easy to\n    construct and manipulate rich data structures, and sophisticated\n    _polymorphic type systems_ supporting abstraction and code reuse.\n    Coq offers all of these features.\n\n    The first half of this chapter introduces the most essential\n    elements of Coq's functional programming language, called\n    _Gallina_.  The second half introduces some basic _tactics_ that\n    can be used to prove properties of Coq programs. *)\n\n(* ################################################################# *)\n(** * Data and Functions *)\n(* ================================================================= *)\n(** ** Enumerated Types *)\n\n(** One notable aspect of Coq is that its set of built-in\n    features is _extremely_ small.  For example, instead of providing\n    the usual palette of atomic data types (booleans, integers,\n    strings, etc.), Coq offers a powerful mechanism for defining new\n    data types from scratch, with all these familiar types as\n    instances.\n\n    Naturally, the Coq distribution comes preloaded with an extensive\n    standard library providing definitions of booleans, numbers, and\n    many common data structures like lists and hash tables.  But there\n    is nothing magic or primitive about these library definitions.  To\n    illustrate this, we will explicitly recapitulate all the\n    definitions we need in this course, rather than just getting them\n    implicitly from the library. *)\n\n(* ================================================================= *)\n(** ** Days of the Week *)\n\n(** To see how this definition mechanism works, let's start with\n    a very simple example.  The following declaration tells Coq that\n    we are defining a new set of data values -- a _type_. *)\n\nInductive day : Type :=\n  | monday\n  | tuesday\n  | wednesday\n  | thursday\n  | friday\n  | saturday\n  | sunday.\n\n(** The type is called [day], and its members are [monday],\n    [tuesday], etc. \n\n    Having defined [day], we can write functions that operate on\n    days. *)\n\nDefinition next_weekday (d:day) : day :=\n  match d with\n  | monday    => tuesday\n  | tuesday   => wednesday\n  | wednesday => thursday\n  | thursday  => friday\n  | friday    => monday\n  | saturday  => monday\n  | sunday    => monday\n  end.\n\n(** One thing to note is that the argument and return types of\n    this function are explicitly declared.  Like most functional\n    programming languages, Coq can often figure out these types for\n    itself when they are not given explicitly -- i.e., it can do _type\n    inference_ -- but we'll generally include them to make reading\n    easier. *)\n\n(** Having defined a function, we should check that it works on\n    some examples.  There are actually three different ways to do this\n    in Coq.  First, we can use the command [Compute] to evaluate a\n    compound expression involving [next_weekday]. *)\n\nCompute (next_weekday friday).\n(* ==> monday : day *)\n\nCompute (next_weekday (next_weekday saturday)).\n(* ==> tuesday : day *)\n\n(** (We show Coq's responses in comments, but, if you have a\n    computer handy, this would be an excellent moment to fire up the\n    Coq interpreter under your favorite IDE -- either CoqIde or Proof\n    General -- and try this for yourself.  Load this file, [Basics.v],\n    from the book's Coq sources, find the above example, submit it to\n    Coq, and observe the result.) *)\n\n(** Second, we can record what we _expect_ the result to be in the\n    form of a Coq example: *)\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\n(** This declaration does two things: it makes an\n    assertion (that the second weekday after [saturday] is [tuesday]),\n    and it gives the assertion a name that can be used to refer to it\n    later.  Having made the assertion, we can also ask Coq to verify\n    it, like this: *)\n\nProof. simpl. reflexivity.  Qed.\n\n(** The details are not important for now (we'll come back to\n    them in a bit), but essentially this can be read as \"The assertion\n    we've just made can be proved by observing that both sides of the\n    equality evaluate to the same thing, after some simplification.\"\n\n    Third, we can ask Coq to _extract_, from our [Definition], a\n    program in some other, more conventional, programming\n    language (OCaml, Scheme, or Haskell) with a high-performance\n    compiler.  This facility is very interesting, since it gives us a\n    way to go from proved-correct algorithms written in Gallina to\n    efficient machine code.  (Of course, we are trusting the\n    correctness of the OCaml/Haskell/Scheme compiler, and of Coq's\n    extraction facility itself, but this is still a big step forward\n    from the way most software is developed today.) Indeed, this is\n    one of the main uses for which Coq was developed.  We'll come back\n    to this topic in later chapters. *)\n\n(* ================================================================= *)\n(** ** Homework Submission Guidelines *)\n\n(** If you are using _Software Foundations_ in a course, your\n    instructor may use automatic scripts to help grade your homework\n    assignments.  In order for these scripts to work correctly (so\n    that you get full credit for your work!), please be careful to\n    follow these rules:\n      - The grading scripts work by extracting marked regions of the\n        [.v] files that you submit.  It is therefore important that\n        you do not alter the \"markup\" that delimits exercises: the\n        Exercise header, the name of the exercise, the \"empty square\n        bracket\" marker at the end, etc.  Please leave this markup\n        exactly as you find it.\n      - Do not delete exercises.  If you skip an exercise (e.g.,\n        because it is marked Optional, or because you can't solve it),\n        it is OK to leave a partial proof in your [.v] file, but in\n        this case please make sure it ends with [Admitted] (not, for\n        example [Abort]).\n      - It is fine to use additional definitions (of helper functions,\n        useful lemmas, etc.) in your solutions.  You can put these\n        between the exercise header and the theorem you are asked to\n        prove.\n\n    You will also notice that each chapter (like [Basics.v]) is\n    accompanied by a _test script_ ([BasicsTest.v]) that automatically\n    calculates points for the finished homework problems in the\n    chapter.  These scripts are mostly for the auto-grading\n    infrastructure that your instructor may use to help process\n    assignments, but you may also like to use them to double-check\n    that your file is well formatted before handing it in.  In a\n    terminal window either type [make BasicsTest.vo] or do the\n    following:\n\n       coqc -Q . LF Basics.v\n       coqc -Q . LF BasicsTest.v\n\n    There is no need to hand in [BasicsTest.v] itself (or [Preface.v]).\n\n    _If your class is using the Canvas system to hand in assignments_:\n      - If you submit multiple versions of the assignment, you may\n        notice that they are given different names.  This is fine: The\n        most recent submission is the one that will be graded.\n      - To hand in multiple files at the same time (if more than one\n        chapter is assigned in the same week), you need to make a\n        single submission with all the files at once using the button\n        \"Add another file\" just above the comment box. *)\n\n(* ================================================================= *)\n(** ** Booleans *)\n\n(** In a similar way, we can define the standard type [bool] of\n    booleans, with members [true] and [false]. *)\n\nInductive bool : Type :=\n  | true\n  | false.\n\n(** Although we are rolling our own booleans here for the sake\n    of building up everything from scratch, Coq does, of course,\n    provide a default implementation of the booleans, together with a\n    multitude of useful functions and lemmas.  (Take a look at\n    [Coq.Init.Datatypes] in the Coq library documentation if you're\n    interested.)  Whenever possible, we'll name our own definitions\n    and theorems so that they exactly coincide with the ones in the\n    standard library.\n\n    Functions over booleans can be defined in the same way as\n    above: *)\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\nDefinition orb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\n\n(** The last two of these illustrate Coq's syntax for\n    multi-argument function definitions.  The corresponding\n    multi-argument application syntax is illustrated by the following\n    \"unit tests,\" which constitute a complete specification -- a truth\n    table -- for the [orb] function: *)\n\nExample test_orb1:  (orb true  false) = true.\nProof. simpl. reflexivity.  Qed.\nExample test_orb2:  (orb false false) = false.\nProof. simpl. reflexivity.  Qed.\nExample test_orb3:  (orb false true)  = true.\nProof. simpl. reflexivity.  Qed.\nExample test_orb4:  (orb true  true)  = true.\nProof. simpl. reflexivity.  Qed.\n\n(** We can also introduce some familiar syntax for the boolean\n    operations we have just defined. The [Notation] command defines a new\n    symbolic notation for an existing definition. *)\n\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_orb5:  false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\n(** _A note on notation_: In [.v] files, we use square brackets\n    to delimit fragments of Coq code within comments; this convention,\n    also used by the [coqdoc] documentation tool, keeps them visually\n    separate from the surrounding text.  In the HTML version of the\n    files, these pieces of text appear in a [different font].\n\n    The command [Admitted] can be used as a placeholder for an\n    incomplete proof.  We'll use it in exercises, to indicate the\n    parts that we're leaving for you -- i.e., your job is to replace\n    [Admitted]s with real proofs. *)\n\n(** **** Exercise: 1 star, standard (nandb)  \n\n    Remove \"[Admitted.]\" and complete the definition of the following\n    function; then make sure that the [Example] assertions below can\n    each be verified by Coq.  (I.e., fill in each proof, following the\n    model of the [orb] tests above.) The function should return [true]\n    if either or both of its inputs are [false]. *)\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n    match b1 with\n  | true => negb b2\n  | false => true\nend .\n\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n\nExample test_nandb1:               (nandb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb2:               (nandb false false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb3:               (nandb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb4:               (nandb true true) = false.\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (andb3)  \n\n    Do the same for the [andb3] function below. This function should\n    return [true] when all of its inputs are [true], and [false]\n    otherwise. *)\n \nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  match b1 with\n  | false => false\n  | true => andb b2 b3\nend.\n\n\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n\nExample test_andb31:                 (andb3 true true true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_andb32:                 (andb3 false true true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb33:                 (andb3 true false true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb34:                 (andb3 true true false) = false.\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Types *)\n\n(** Every expression in Coq has a type, describing what sort of\n    thing it computes. The [Check] command asks Coq to print the type\n    of an expression. *)\n\nCheck true.\n(* ===> true : bool *)\nCheck (negb true).\n(* ===> negb true : bool *)\n\n(** Functions like [negb] itself are also data values, just like\n    [true] and [false].  Their types are called _function types_, and\n    they are written with arrows. *)\n\nCheck negb.\n(* ===> negb : bool -> bool *)\n\nCheck andb.\n\n(** The type of [negb], written [bool -> bool] and pronounced\n    \"[bool] arrow [bool],\" can be read, \"Given an input of type\n    [bool], this function produces an output of type [bool].\"\n    Similarly, the type of [andb], written [bool -> bool -> bool], can\n    be read, \"Given two inputs, both of type [bool], this function\n    produces an output of type [bool].\" *)\n\n(* ================================================================= *)\n(** ** New Types from Old *)\n\n(** The types we have defined so far are examples of \"enumerated\n    types\": their definitions explicitly enumerate a finite set of\n    elements, each of which is just a bare constructor.  Here is a\n    more interesting type definition, where one of the constructors\n    takes an argument: *)\n\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\n\nInductive color : Type :=\n  | black\n  | white\n  | primary (p : rgb).\n\n(** Let's look at this in a little more detail.\n\n    Every inductively defined type ([day], [bool], [rgb], [color],\n    etc.) contains a set of _constructor expressions_ built from\n    _constructors_ like [red], [primary], [true], [false], [monday],\n    etc. \n\n    The definitions of [rgb] and [color] say how expressions in the\n    sets [rgb] and [color] can be built:\n\n    - [red], [green], and [blue] are the constructors of [rgb];\n    - [black], [white], and [primary] are the constructors of [color];\n    - the expression [red] belongs to the set [rgb], as do the\n      expressions [green] and [blue];\n    - the expressions [black] and [white] belong to the set [color];\n    - if [p] is an expression belonging to the set [rgb], then\n      [primary p] (pronounced \"the constructor [primary] applied to\n      the argument [p]\") is an expression belonging to the set\n      [color]; and\n    - expressions formed in these ways are the _only_ ones belonging\n      to the sets [rgb] and [color]. *)\n\n(** We can define functions on colors using pattern matching just as\n    we have done for [day] and [bool]. *)\n\nDefinition monochrome (c : color) : bool :=\n  match c with\n  | black => true\n  | white => true\n  | primary q => false\n  end.\n\n(** Since the [primary] constructor takes an argument, a pattern\n    matching [primary] should include either a variable (as above --\n    note that we can choose its name freely) or a constant of\n    appropriate type (as below). *)\n\nDefinition isred (c : color) : bool :=\n  match c with\n  | black => false\n  | white => false\n  | primary red => true\n  | primary _ => false\n  end.\n\n(** The pattern [primary _] here is shorthand for \"[primary] applied\n    to any [rgb] constructor except [red].\"  (The wildcard pattern [_]\n    has the same effect as the dummy pattern variable [p] in the\n    definition of [monochrome].) *)\n\n(* ================================================================= *)\n(** ** Tuples *)\n\n(** A single constructor with multiple parameters can be used\n    to create a tuple type. As an example, consider representing\n    the four bits in a nybble (half a byte). We first define\n    a datatype [bit] that resembles [bool] (using the\n    constructors [B0] and [B1] for the two possible bit values),\n    and then define the datatype [nybble], which is essentially\n    a tuple of four bits. *)\n\nInductive bit : Type :=\n  | B0\n  | B1.\n\nInductive nybble : Type :=\n  | bits (b0 b1 b2 b3 : bit).\n\nCheck (bits B1 B0 B1 B0).\n(* ==> bits B1 B0 B1 B0 : nybble *)\n\n(** The [bits] constructor acts as a wrapper for its contents.\n    Unwrapping can be done by pattern-matching, as in the [all_zero]\n    function which tests a nybble to see if all its bits are O.\n    Note that we are using underscore (_) as a _wildcard pattern_ to\n    avoid inventing variable names that will not be used. *)\n\nDefinition all_zero (nb : nybble) : bool :=\n  match nb with\n    | (bits B0 B0 B0 B0) => true\n    | (bits _ _ _ _) => false\n  end.\n\nCompute (all_zero (bits B1 B0 B1 B0)).\n(* ===> false : bool *)\nCompute (all_zero (bits B0 B0 B0 B0)).\n(* ===> true : bool *)\n\n(* ================================================================= *)\n(** ** Modules *)\n\n(** Coq provides a _module system_, to aid in organizing large\n    developments.  In this course we won't need most of its features,\n    but one is useful: If we enclose a collection of declarations\n    between [Module X] and [End X] markers, then, in the remainder of\n    the file after the [End], these definitions are referred to by\n    names like [X.foo] instead of just [foo].  We will use this\n    feature to introduce the definition of the type [nat] in an inner\n    module so that it does not interfere with the one from the\n    standard library (which we want to use in the rest because it\n    comes with a tiny bit of convenient special notation).  *)\n\nModule NatPlayground.\n\n(* ================================================================= *)\n(** ** Numbers *)\n\n(** The types we have defined so far, \"enumerated types\" such as\n    [day], [bool], and [bit], and tuple types such as [nybble] built\n    from them, share the property that each type has a finite set of\n    values. The natural numbers are an infinite set, and we need to\n    represent all of them in a datatype with a finite number of\n    constructors. There are many representations of numbers to choose\n    from. We are most familiar with decimal notation (base 10), using\n    the digits 0 through 9, for example, to form the number 123.  You\n    may have encountered hexadecimal notation (base 16), in which the\n    same number is represented as 7B, or octal (base 8), where it is\n    173, or binary (base 2), where it is 1111011. Using an enumerated\n    type to represent digits, we could use any of these to represent\n    natural numbers. There are circumstances where each of these\n    choices can be useful.\n\n    Binary is valuable in computer hardware because it can in turn be\n    represented with two voltage levels, resulting in simple\n    circuitry. Analogously, we wish here to choose a representation\n    that makes _proofs_ simpler.\n\n    Indeed, there is a representation of numbers that is even simpler\n    than binary, namely unary (base 1), in which only a single digit\n    is used (as one might do while counting days in prison by scratching\n    on the walls). To represent unary with a Coq datatype, we use\n    two constructors. The capital-letter [O] constructor represents zero.\n    When the [S] constructor is applied to the representation of the\n    natural number _n_, the result is the representation of _n+1_.\n    ([S] stands for \"successor\", or \"scratch\" if one is in prison.)\n    Here is the complete datatype definition. *)\n\nInductive nat : Type :=\n  | O\n  | S (n : nat).\n\n(** With this definition, 0 is represented by [O], 1 by [S O],\n    2 by [S (S O)], and so on. *)\n\n(** The clauses of this definition can be read:\n      - [O] is a natural number (note that this is the letter \"[O],\"\n        not the numeral \"[0]\").\n      - [S] can be put in front of a natural number to yield another\n        one -- if [n] is a natural number, then [S n] is too. *)\n\n(** Again, let's look at this in a little more detail.  The definition\n    of [nat] says how expressions in the set [nat] can be built:\n\n    - [O] and [S] are constructors;\n    - the expression [O] belongs to the set [nat];\n    - if [n] is an expression belonging to the set [nat], then [S n]\n      is also an expression belonging to the set [nat]; and\n    - expressions formed in these two ways are the only ones belonging\n      to the set [nat]. *)\n\n(** The same rules apply for our definitions of [day], [bool],\n    [color], etc.\n\n    The above conditions are the precise force of the [Inductive]\n    declaration.  They imply that the expression [O], the expression\n    [S O], the expression [S (S O)], the expression [S (S (S O))], and\n    so on all belong to the set [nat], while other expressions built\n    from data constructors, like [true], [andb true false], [S (S\n    false)], and [O (O (O S))] do not.\n\n    A critical point here is that what we've done so far is just to\n    define a _representation_ of numbers: a way of writing them down.\n    The names [O] and [S] are arbitrary, and at this point they have\n    no special meaning -- they are just two different marks that we\n    can use to write down numbers (together with a rule that says any\n    [nat] will be written as some string of [S] marks followed by an\n    [O]).  If we like, we can write essentially the same definition\n    this way: *)\n\nInductive nat' : Type :=\n  | stop\n  | tick (foo : nat').\n\n(** The _interpretation_ of these marks comes from how we use them to\n    compute. *)\n\n(** We can do this by writing functions that pattern match on\n    representations of natural numbers just as we did above with\n    booleans and days -- for example, here is the predecessor\n    function: *)\n\nDefinition pred (n : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => n'\n  end.\n\n(** The second branch can be read: \"if [n] has the form [S n']\n    for some [n'], then return [n'].\"  *)\n\nEnd NatPlayground.\n\n(** Because natural numbers are such a pervasive form of data,\n    Coq provides a tiny bit of built-in magic for parsing and printing\n    them: ordinary decimal numerals can be used as an alternative to\n    the \"unary\" notation defined by the constructors [S] and [O].  Coq\n    prints numbers in decimal form by default: *)\n\nCheck (S (S (S (S O)))).\n  (* ===> 4 : nat *)\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n    | O => O\n    | S O => O\n    | S (S n') => n'\n  end.\n\nCompute (minustwo 4).\n  (* ===> 2 : nat *)\n\n(** The constructor [S] has the type [nat -> nat], just like\n    [pred] and functions like [minustwo]: *)\n\nCheck S.\nCheck pred.\nCheck minustwo.\n\n(** These are all things that can be applied to a number to yield a\n    number.  However, there is a fundamental difference between the\n    first one and the other two: functions like [pred] and [minustwo]\n    come with _computation rules_ -- e.g., the definition of [pred]\n    says that [pred 2] can be simplified to [1] -- while the\n    definition of [S] has no such behavior attached.  Although it is\n    like a function in the sense that it can be applied to an\n    argument, it does not _do_ anything at all!  It is just a way of\n    writing down numbers.  (Think about standard decimal numerals: the\n    numeral [1] is not a computation; it's a piece of data.  When we\n    write [111] to mean the number one hundred and eleven, we are\n    using [1], three times, to write down a concrete representation of\n    a number.)\n\n    For most function definitions over numbers, just pattern matching\n    is not enough: we also need recursion.  For example, to check that\n    a number [n] is even, we may need to recursively check whether\n    [n-2] is even.  To write such functions, we use the keyword\n    [Fixpoint]. *)\n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | O        => true\n  | S O      => false\n  | S (S n') => evenb n'\n  end.\n\n(** We can define [oddb] by a similar [Fixpoint] declaration, but here\n    is a simpler definition: *)\n\nDefinition oddb (n:nat) : bool   :=   negb (evenb n).\n\nExample test_oddb1:    oddb 1 = true.\nProof. simpl. reflexivity.  Qed.\nExample test_oddb2:    oddb 4 = false.\nProof. simpl. reflexivity.  Qed.\n\n(** (You will notice if you step through these proofs that\n    [simpl] actually has no effect on the goal -- all of the work is\n    done by [reflexivity].  We'll see more about why that is shortly.)\n\n    Naturally, we can also define multi-argument functions by\n    recursion.  *)\n\nModule NatPlayground2.\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\n(** Adding three to two now gives us five, as we'd expect. *)\n\nCompute (plus 3 2).\n\n(** The simplification that Coq performs to reach this conclusion can\n    be visualized as follows: *)\n\n(*  [plus (S (S (S O))) (S (S O))]\n==> [S (plus (S (S O)) (S (S O)))]\n      by the second clause of the [match]\n==> [S (S (plus (S O) (S (S O))))]\n      by the second clause of the [match]\n==> [S (S (S (plus O (S (S O)))))]\n      by the second clause of the [match]\n==> [S (S (S (S (S O))))]\n      by the first clause of the [match]\n*)\n\n(** As a notational convenience, if two or more arguments have\n    the same type, they can be written together.  In the following\n    definition, [(n m : nat)] means just the same as if we had written\n    [(n : nat) (m : nat)]. *)\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\n\nExample test_mult1: (mult 3 3) = 9.\nProof. simpl. reflexivity.  Qed.\n\n(** You can match two expressions at once by putting a comma\n    between them: *)\n\nFixpoint minus (n m:nat) : nat :=\n  match n, m with\n  | O   , _    => O\n  | S _ , O    => n\n  | S n', S m' => minus n' m'\n  end.\n\nEnd NatPlayground2.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n    | O => S O\n    | S p => mult base (exp base p)\n  end.\n\nCompute (exp 3 2).\nExample test1: (exp 3 2) = 9.\nProof. simpl. reflexivity. Qed.\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  | 0 => 1\n  | S p => mult n (factorial p)\nend. \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(** Again, we can make numerical expressions easier to read and write\n    by introducing notations for addition, multiplication, and\n    subtraction. *)\n\nNotation \"x + y\" := (plus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x - y\" := (minus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x * y\" := (mult x y)\n                       (at level 40, left associativity)\n                       : nat_scope.\n\nCheck ((0 + 1) + 1).\n\n(** (The [level], [associativity], and [nat_scope] annotations\n    control how these notations are treated by Coq's parser.  The\n    details are not important for our purposes, but interested readers\n    can refer to the \"More on Notation\" section at the end of this\n    chapter.)\n\n    Note that these do not change the definitions we've already made:\n    they are simply instructions to the Coq parser to accept [x + y]\n    in place of [plus x y] and, conversely, to the Coq pretty-printer\n    to display [plus x y] as [x + y]. *)\n\n(** When we say that Coq comes with almost nothing built-in, we really\n    mean it: even equality testing is a user-defined operation!\n\n    Here is a function [eqb], which tests natural numbers for\n    [eq]uality, yielding a [b]oolean.  Note the use of nested\n    [match]es (we could also have used a simultaneous match, as we did\n    in [minus].) *)\n\nFixpoint eqb (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => eqb n' m'\n            end\n  end.\n\n(** Similarly, the [leb] function tests whether its first argument is\n    less than or equal to its second argument, yielding a boolean. *)\n\nFixpoint leb (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => leb n' m'\n      end\n  end.\n\nExample test_leb1:             (leb 2 2) = true.\nProof. simpl. reflexivity.  Qed.\nExample test_leb2:             (leb 2 4) = true.\nProof. simpl. reflexivity.  Qed.\nExample test_leb3:             (leb 4 2) = false.\nProof. simpl. reflexivity.  Qed.\n\n(** Since we'll be using these (especially [eqb]) a lot, let's give\n    them infix notations. *)\n\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\nExample test_leb3':             (4 <=? 2) = false.\nProof. simpl. reflexivity.  Qed.\n\n(** **** Exercise: 1 star, 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  match leb n m with\n  | true => match eqb n m with \n            | true => false\n            | false => true\n          end\n  | false => false\n  end.\n\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\nExample test_ltb1:             (ltb 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_ltb2:             (ltb 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_ltb3:             (ltb 4 2) = false.\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Proof by Simplification *)\n\n(** Now that we've defined a few datatypes and functions, let's\n    turn to stating and proving properties of their behavior.\n    Actually, we've already started doing this: each [Example] in the\n    previous sections makes a precise claim about the behavior of some\n    function on some particular inputs.  The proofs of these claims\n    were always the same: use [simpl] to simplify both sides of the\n    equation, then use [reflexivity] to check that both sides contain\n    identical values.\n\n    The same sort of \"proof by simplification\" can be used to prove\n    more interesting properties as well.  For example, the fact that\n    [0] is a \"neutral element\" for [+] on the left can be proved just\n    by observing that [0 + n] reduces to [n] no matter what [n] is, a\n    fact that can be read directly off the definition of [plus]. *)\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. simpl. reflexivity.  Qed.\n\n(** (You may notice that the above statement looks different in\n    the [.v] file in your IDE than it does in the HTML rendition in\n    your browser, if you are viewing both. In [.v] files, we write the\n    [forall] universal quantifier using the reserved identifier\n    \"forall.\"  When the [.v] files are converted to HTML, this gets\n    transformed into an upside-down-A symbol.)\n\n    This is a good place to mention that [reflexivity] is a bit\n    more powerful than we have admitted. In the examples we have seen,\n    the calls to [simpl] were actually not needed, because\n    [reflexivity] can perform some simplification automatically when\n    checking that two sides are equal; [simpl] was just added so that\n    we could see the intermediate state -- after simplification but\n    before finishing the proof.  Here is a shorter proof of the\n    theorem: *)\n\nTheorem plus_O_n' : forall n : nat, 0 + n = n.\nProof.\n  intros n. reflexivity. Qed.\n\n(** Moreover, it will be useful later to know that [reflexivity]\n    does somewhat _more_ simplification than [simpl] does -- for\n    example, it tries \"unfolding\" defined terms, replacing them with\n    their right-hand sides.  The reason for this difference is that,\n    if reflexivity succeeds, the whole goal is finished and we don't\n    need to look at whatever expanded expressions [reflexivity] has\n    created by all this simplification and unfolding; by contrast,\n    [simpl] is used in situations where we may have to read and\n    understand the new goal that it creates, so we would not want it\n    blindly expanding definitions and leaving the goal in a messy\n    state.\n\n    The form of the theorem we just stated and its proof are almost\n    exactly the same as the simpler examples we saw earlier; there are\n    just a few differences.\n\n    First, we've used the keyword [Theorem] instead of [Example].\n    This difference is mostly a matter of style; the keywords\n    [Example] and [Theorem] (and a few others, including [Lemma],\n    [Fact], and [Remark]) mean pretty much the same thing to Coq.\n\n    Second, we've added the quantifier [forall n:nat], so that our\n    theorem talks about _all_ natural numbers [n].  Informally, to\n    prove theorems of this form, we generally start by saying \"Suppose\n    [n] is some number...\"  Formally, this is achieved in the proof by\n    [intros n], which moves [n] from the quantifier in the goal to a\n    _context_ of current assumptions.\n\n    The keywords [intros], [simpl], and [reflexivity] are examples of\n    _tactics_.  A tactic is a command that is used between [Proof] and\n    [Qed] to guide the process of checking some claim we are making.\n    We will see several more tactics in the rest of this chapter and\n    yet more in future chapters. *)\n\n(** Other similar theorems can be proved with the same pattern. *)\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. reflexivity.  Qed.\n\nTheorem mult_0_l : forall n:nat, 0 * n = 0.\nProof.\n  intros n. reflexivity.  Qed.\n\n(** The [_l] suffix in the names of these theorems is\n    pronounced \"on the left.\" *)\n\n(** It is worth stepping through these proofs to observe how the\n    context and the goal change.  You may want to add calls to [simpl]\n    before [reflexivity] to see the simplifications that Coq performs\n    on the terms before checking that they are equal. *)\n\n(* ################################################################# *)\n(** * Proof by Rewriting *)\n\n(** This theorem is a bit more interesting than the others we've\n    seen: *)\n\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + n = m + m.\n\n(** Instead of making a universal claim about all numbers [n] and [m],\n    it talks about a more specialized property that only holds when [n\n    = m].  The arrow symbol is pronounced \"implies.\"\n\n    As before, we need to be able to reason by assuming we are given such\n    numbers [n] and [m].  We also need to assume the hypothesis\n    [n = m]. The [intros] tactic will serve to move all three of these\n    from the goal into assumptions in the current context.\n\n    Since [n] and [m] are arbitrary numbers, we can't just use\n    simplification to prove this theorem.  Instead, we prove it by\n    observing that, if we are assuming [n = m], then we can replace\n    [n] with [m] in the goal statement and obtain an equality with the\n    same expression on both sides.  The tactic that tells Coq to\n    perform this replacement is called [rewrite]. *)\n\nProof.\n  (* move both quantifiers into the context: *)\n  intros n m.\n  (* move the hypothesis into the context: *)\n  intros H.\n  (* rewrite the goal using the hypothesis: *)\n  rewrite -> H.\n  reflexivity.  Qed.\n\n(** The first line of the proof moves the universally quantified\n    variables [n] and [m] into the context.  The second moves the\n    hypothesis [n = m] into the context and gives it the name [H].\n    The third tells Coq to rewrite the current goal ([n + n = m + m])\n    by replacing the left side of the equality hypothesis [H] with the\n    right side.\n\n    (The arrow symbol in the [rewrite] has nothing to do with\n    implication: it tells Coq to apply the rewrite from left to right.\n    To rewrite from right to left, you can use [rewrite <-].  Try\n    making this change in the above proof and see what difference it\n    makes.) *)\n\n(** **** Exercise: 1 star, 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 H.\n  intros M.\n  rewrite -> H.\n  rewrite -> M.\n  reflexivity.\nQed.\n(** [] *)\n\n(** The [Admitted] command tells Coq that we want to skip trying\n    to prove this theorem and just accept it as a given.  This can be\n    useful for developing longer proofs, since we can state subsidiary\n    lemmas that we believe will be useful for making some larger\n    argument, use [Admitted] to accept them on faith for the moment,\n    and continue working on the main argument until we are sure it\n    makes sense; then we can go back and fill in the proofs we\n    skipped.  Be careful, though: every time you say [Admitted] you\n    are leaving a door open for total nonsense to enter Coq's nice,\n    rigorous, formally checked world! *)\n\n(** We can also use the [rewrite] tactic with a previously proved\n    theorem instead of a hypothesis from the context. If the statement\n    of the previously proved theorem involves quantified variables,\n    as in the example below, Coq tries to instantiate them\n    by matching with the current goal. *)\n\nTheorem mult_0_plus : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity.  Qed.\n\n(** **** Exercise: 2 stars, 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 H.\n  rewrite -> H.\n  reflexivity.\nQed.\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\n(** Of course, not everything can be proved by simple\n    calculation and rewriting: In general, unknown, hypothetical\n    values (arbitrary numbers, booleans, lists, etc.) can block\n    simplification.  For example, if we try to prove the following\n    fact using the [simpl] tactic as above, we get stuck.  (We then\n    use the [Abort] command to give up on it for the moment.)*)\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n.\n  simpl.  (* does nothing! *)\nAbort.\n\n(** The reason for this is that the definitions of both\n    [eqb] and [+] begin by performing a [match] on their first\n    argument.  But here, the first argument to [+] is the unknown\n    number [n] and the argument to [eqb] is the compound\n    expression [n + 1]; neither can be simplified.\n\n    To make progress, we need to consider the possible forms of [n]\n    separately.  If [n] is [O], then we can calculate the final result\n    of [(n + 1) =? 0] and check that it is, indeed, [false].  And\n    if [n = S n'] for some [n'], then, although we don't know exactly\n    what number [n + 1] yields, we can calculate that, at least, it\n    will begin with one [S], and this is enough to calculate that,\n    again, [(n + 1) =? 0] will yield [false].\n\n    The tactic that tells Coq to consider, separately, the cases where\n    [n = O] and where [n = S n'] is called [destruct]. *)\n\nTheorem plus_1_neq_0 : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n. destruct n as [| n'] eqn:E.\n  - reflexivity.\n  - reflexivity.   Qed.\n\n(** The [destruct] generates _two_ subgoals, which we must then\n    prove, separately, in order to get Coq to accept the theorem.\n\n    The annotation \"[as [| n']]\" is called an _intro pattern_.  It\n    tells Coq what variable names to introduce in each subgoal.  In\n    general, what goes between the square brackets is a _list of\n    lists_ of names, separated by [|].  In this case, the first\n    component is empty, since the [O] constructor is nullary (it\n    doesn't have any arguments).  The second component gives a single\n    name, [n'], since [S] is a unary constructor.\n\n    In each subgoal, Coq remembers the assumption about [n] that is\n    relevant for this subgoal -- either [n = 0] or [n = S n'] for some\n    n'.  The [eqn:E] annotation tells [destruct] to give the name [E] to\n    this equation.  (Leaving off the [eqn:E] annotation causes Coq to\n    elide these assumptions in the subgoals.  This slightly\n    streamlines proofs where the assumptions are not explicitly used,\n    but it is better practice to keep them for the sake of\n    documentation, as they can help keep you oriented when working\n    with the subgoals.)\n\n    The [-] signs on the second and third lines are called _bullets_,\n    and they mark the parts of the proof that correspond to each\n    generated subgoal.  The proof script that comes after a bullet is\n    the entire proof for a subgoal.  In this example, each of the\n    subgoals is easily proved by a single use of [reflexivity], which\n    itself performs some simplification -- e.g., the second one\n    simplifies [(S n' + 1) =? 0] to [false] by first rewriting [(S n'\n    + 1)] to [S (n' + 1)], then unfolding [eqb], and then simplifying\n    the [match].\n\n    Marking cases with bullets is entirely optional: if bullets are\n    not present, Coq simply asks you to prove each subgoal in\n    sequence, one at a time. But it is a good idea to use bullets.\n    For one thing, they make the structure of a proof apparent, making\n    it more readable. Also, bullets instruct Coq to ensure that a\n    subgoal is complete before trying to verify the next one,\n    preventing proofs for different subgoals from getting mixed\n    up. These issues become especially important in large\n    developments, where fragile proofs lead to long debugging\n    sessions.\n\n    There are no hard and fast rules for how proofs should be\n    formatted in Coq -- in particular, where lines should be broken\n    and how sections of the proof should be indented to indicate their\n    nested structure.  However, if the places where multiple subgoals\n    are generated are marked with explicit bullets at the beginning of\n    lines, then the proof will be readable almost no matter what\n    choices are made about other aspects of layout.\n\n    This is also a good place to mention one other piece of somewhat\n    obvious advice about line lengths.  Beginning Coq users sometimes\n    tend to the extremes, either writing each tactic on its own line\n    or writing entire proofs on one line.  Good style lies somewhere\n    in the middle.  One reasonable convention is to limit yourself to\n    80-character lines.\n\n    The [destruct] tactic can be used with any inductively defined\n    datatype.  For example, we use it next to prove that boolean\n    negation is involutive -- i.e., that negation is its own\n    inverse. *)\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b eqn:E.\n  - reflexivity.\n  - reflexivity.  Qed.\n\n(** Note that the [destruct] here has no [as] clause because\n    none of the subcases of the [destruct] need to bind any variables,\n    so there is no need to specify any names.  (We could also have\n    written [as [|]], or [as []].)  In fact, we can omit the [as]\n    clause from _any_ [destruct] and Coq will fill in variable names\n    automatically.  This is generally considered bad style, since Coq\n    often makes confusing choices of names when left to its own\n    devices.\n\n    It is sometimes useful to invoke [destruct] inside a subgoal,\n    generating yet more proof obligations. In this case, we use\n    different kinds of bullets to mark goals on different \"levels.\"\n    For example: *)\n\nTheorem andb_commutative : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b eqn:Eb.\n  - destruct c eqn:Ec.\n    + reflexivity.\n    + reflexivity.\n  - destruct c eqn:Ec.\n    + reflexivity.\n    + reflexivity.\nQed.\n\n(** Each pair of calls to [reflexivity] corresponds to the\n    subgoals that were generated after the execution of the [destruct c]\n    line right above it. *)\n\n(** Besides [-] and [+], we can use [*] (asterisk) as a third kind of\n    bullet.  We can also enclose sub-proofs in curly braces, which is\n    useful in case we ever encounter a proof that generates more than\n    three levels of subgoals: *)\n\nTheorem andb_commutative' : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b eqn:Eb.\n  { destruct c eqn:Ec.\n    { reflexivity. }\n    { reflexivity. } }\n  { destruct c eqn:Ec.\n    { reflexivity. }\n    { reflexivity. } }\nQed.\n\n(** Since curly braces mark both the beginning and the end of a\n    proof, they can be used for multiple subgoal levels, as this\n    example shows. Furthermore, curly braces allow us to reuse the\n    same bullet shapes at multiple levels in a proof: *)\n\nTheorem andb3_exchange :\n  forall b c d, andb (andb b c) d = andb (andb b d) c.\nProof.\n  intros b c d. destruct b eqn:Eb.\n  - destruct c eqn:Ec.\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\n  - destruct c eqn:Ec.\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\nQed.\n\n(** Before closing the chapter, let's mention one final\n    convenience.  As you may have noticed, many proofs perform case\n    analysis on a variable right after introducing it:\n\n       intros x y. destruct y as [|y] eqn:E.\n\n    This pattern is so common that Coq provides a shorthand for it: we\n    can perform case analysis on a variable when introducing it by\n    using an intro pattern instead of a variable name. For instance,\n    here is a shorter proof of the [plus_1_neq_0] theorem\n    above.  (You'll also note one downside of this shorthand: we lose\n    the equation recording the assumption we are making in each\n    subgoal, which we previously got from the [eqn:E] annotation.) *)\n\nTheorem plus_1_neq_0' : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.  Qed.\n\n(** If there are no 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.\nintros b c .\n simpl.\n destruct c eqn:Ec.\n {\n  destruct b eqn:Eb.\n  -  simpl. reflexivity.\n  - reflexivity.\n}\n{\n  destruct b eqn:Eb.\n  - simpl. intros H.\n  rewrite -> H.\n  reflexivity.\n - simpl. intros H.\n  rewrite -> H.\n  reflexivity.\n}\nQed.\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].\n  {\n    reflexivity.\n  }\n  {\n    reflexivity.\n  }\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, standard, optional (decreasing)  \n\n    To get a concrete sense of this, find a way to write a sensible\n    [Fixpoint] definition (of a simple function on numbers, say) that\n    _does_ terminate on all inputs, but that Coq will reject because\n    of this restriction.  (If you choose to turn in this optional\n    exercise as part of a homework assignment, make sure you comment\n    out your solution so that it doesn't cause Coq to reject the whole\n    file!) *)\n\n(* \n\nFixpoint test' (x:nat) : nat :=\n  match x with\n  | 0 =>  0\n  | S _ =>  match evenb(x) with\n          | true => match x with \n                    | S (S k') => test' k'\n                    | _ => 0\n                  end\n          | false => test' (S x)\n        end\n  end.\n\n    [] *)\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** Each SF chapter comes with a tester file (e.g.  [BasicsTest.v]),\n    containing scripts that check most of the exercises. You can run\n    [make BasicsTest.vo] in a terminal and check its output to make\n    sure you didn't miss anything. *)\n\n(** **** Exercise: 1 star, standard (indentity_fn_applied_twice)  \n\n    Use the tactics you have learned so far to prove the following\n    theorem about boolean functions. *)\n\nTheorem identity_fn_applied_twice :\n  forall (f : bool -> bool),\n  (forall (x : bool), f x = x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n  intros f X Y.\n  rewrite -> X.\n  rewrite -> X.\n  trivial.\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 nengation_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 Y.\n  rewrite -> X.\n  rewrite -> X.\n  rewrite -> negb_involutive.\n  trivial.\nQed.\n\n(* The [Import] statement on the next line tells Coq to use the\n   standard library String module.  We'll use strings more in later\n   chapters, but for the moment we just need syntax for literal\n   strings for the grader comments. *)\nFrom Coq Require Export String.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_negation_fn_applied_twice : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (andb_eq_orb)  \n\n    Prove the following theorem.  (Hint: This one can be a bit tricky,\n    depending on how you approach it.  You will probably need both\n    [destruct] and [rewrite], but destructing everything in sight is\n    not the best way.) *)\n\n(*\nDefinition orb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true ⇒ true\n  | false ⇒ b2\n  end.\n\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true ⇒ b2\n  | false ⇒ false\n  end.\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  eqn:E.\n{ simpl. intro. rewrite -> H. trivial. }\n{ simpl. intro. rewrite -> H. reflexivity. }\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (binary)  \n\n    We can generalize our unary representation of natural numbers to\n    the more efficient binary representation by treating a binary\n    number as a sequence of constructors [A] and [B] (representing 0s\n    and 1s), terminated by a [Z]. For comparison, in the unary\n    representation, a number is a sequence of [S]s terminated by an\n    [O].\n\n    For example:\n\n        decimal            binary                           unary\n           0                   Z                              O\n           1                 B Z                            S O\n           2              A (B Z)                        S (S O)\n           3              B (B Z)                     S (S (S O))\n           4           A (A (B Z))                 S (S (S (S O)))\n           5           B (A (B Z))              S (S (S (S (S O))))\n           6           A (B (B Z))           S (S (S (S (S (S O)))))\n           7           B (B (B Z))        S (S (S (S (S (S (S O))))))\n           8        A (A (A (B Z)))    S (S (S (S (S (S (S (S O)))))))\n\n    Note that the low-order bit is on the left and the high-order bit\n    is on the right -- the opposite of the way binary numbers are\n    usually written.  This choice makes them easier to manipulate. *)\n\nInductive bin : Type :=\n  | Z\n  | A (n : bin)\n  | B (n : bin).\n\n(** (a) Complete the definitions below of an increment function [incr]\n        for binary numbers, and a function [bin_to_nat] to convert\n        binary numbers to unary numbers. *)\n\nFixpoint incr (m:bin) : bin\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nFixpoint bin_to_nat (m:bin) : nat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\n(**    (b) Write five unit tests [test_bin_incr1], [test_bin_incr2], etc.\n        for your increment and binary-to-unary functions.  (A \"unit\n        test\" in Coq is a specific [Example] that can be proved with\n        just [reflexivity], as we've done for several of our\n        definitions.)  Notice that incrementing a binary number and\n        then converting it to unary should yield the same result as\n        first converting it to unary and then incrementing. *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary : option (nat*string) := None.\n(** [] *)\n\n(* Wed Jan 9 12:02:44 EST 2019 *)\n", "meta": {"author": "infdahai", "repo": "Explore-of-PL", "sha": "7243bdc780e916249f7581bf799e05a9607108f0", "save_path": "github-repos/coq/infdahai-Explore-of-PL", "path": "github-repos/coq/infdahai-Explore-of-PL/Explore-of-PL-7243bdc780e916249f7581bf799e05a9607108f0/coq/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245617, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6856185021761001}}
{"text": "\nInductive unit : Set := \n| tt\n.\n\nLemma unit_singleton : forall (x:unit), x = tt.\nProof. intros x. destruct x. reflexivity. Qed.\n\n\nInductive Empty_set : Set :=.\n\n(*\nCheck Empty_set_ind.\n*)\n\nLemma the_sky_is_falling : forall (x:Empty_set), 2 + 2 = 5.\nProof. intros x. destruct x. Qed.\n\nDefinition e2u (e:Empty_set) : unit := match e with end.\n\nInductive bool : Set := \n| true\n| false\n.\n\nDefinition negb(b:bool) : bool := if b then false else true.\n\nLemma negb_inverse : forall (b:bool), negb (negb b) = b.\nProof. intros b. destruct b; reflexivity. Qed.\n\nLemma negb_ineq : forall (b:bool), negb b <> b.\nProof. destruct b; discriminate. Qed.\n\n(*\nCheck bool_ind.\n*)\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat\n.\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 m   => m\n    end.\n\n\nFixpoint plus (n m:nat) : nat :=\n    match n with \n    | O     => m\n    | S p   => S (plus p m)\n    end.\n\nLemma plus_O_n : forall (n:nat), plus O n = n.\nProof. intros n. reflexivity. Qed.\n\nLemma plus_n_O : forall (n:nat), plus n O = n.\nProof.\n    intros n. induction n as [|n IH].\n    - reflexivity.\n    - simpl. rewrite IH. reflexivity.\nQed.\n\nLemma S_inj : forall (n m:nat), S n = S m -> n = m.\nProof. intros n m H. injection H. trivial. Qed.\n\nInductive list (a:Set) : Set :=\n| Nil  : list a\n| Cons : a -> list a -> list a\n.\n\nArguments Nil {a}.\nArguments Cons {a} _ _.\n\n\nFixpoint length (a:Set) (xs:list a) : nat :=\n    match xs with\n    | Nil       => O\n    | Cons x ys => S (length a ys)\n    end.\n\nArguments length {a} _.\n\nLemma length_test : \n    length (Cons 0 (Cons 1 (Cons 2 Nil))) = S (S (S O)).\nProof. reflexivity. Qed.\n\nFixpoint append (a:Set) (xs ys:list a) : list a :=\n    match xs with\n    | Nil        => ys\n    | Cons x xs' => Cons x (append a xs' ys)\n    end.\n\nArguments append {a} _ _.\n\n\nLemma length_append : forall (a:Set) (xs ys:list a), \n    length (append xs ys) = plus (length xs) (length ys).\nProof.\n    intros a xs. induction xs as [|x xs IH]; intros ys; simpl.\n    - reflexivity.\n    - rewrite IH. reflexivity.\nQed.\n\nInductive btree (a:Set) : Set :=\n| Leaf : btree a\n| Node : btree a -> a -> btree a -> btree a\n.\n\nArguments Leaf {a}.\nArguments Node {a} _ _ _.\n\nFixpoint size (a:Set) (t:btree a) : nat :=\n    match t with\n    | Leaf          => S O\n    | Node t1 _ t2  => plus (size _ t1) (size _ t2)\n    end.\n\nArguments size {a}.\n\nFixpoint splice (t1 t2:btree nat) : btree nat :=\n    match t1 with\n    | Leaf          => Node t2 O Leaf\n    | Node s1 n s2  => Node (splice s1 t2) n s2\n    end.\n\nLemma plus_assoc : forall (n m p:nat), plus (plus n m) p = plus n (plus m p).\nProof.\n    intros n. induction n as [|n IH]; intros m p; simpl.\n    - reflexivity.\n    - rewrite IH. reflexivity.\nQed.\n\nLemma plus_n_Sm : forall (n m:nat), plus n (S m) = S (plus n m).\nProof.\n    intros n. induction n as [|n IH]; intros m; simpl.\n    - reflexivity.\n    - rewrite IH. reflexivity.\nQed.\n\nLemma plus_comm : forall (n m:nat), plus n m = plus m n.\nProof.\n    intros n. induction n as [|n IH]; intros m; simpl.\n    - symmetry. apply plus_n_O.\n    - rewrite IH. symmetry. apply plus_n_Sm.\nQed.\n\nLemma size_splice : forall (t1 t2:btree nat), \n    size (splice t1 t2) = plus (size t1) (size t2).\nProof.\n    intros t1. induction t1 as [|s1 IH1 n s2 IH2]; intros t2; simpl.\n    - rewrite plus_n_Sm. rewrite plus_n_O. reflexivity.  \n    - rewrite IH1. rewrite plus_assoc.\n      remember (plus (size t2) (size s2)) as e eqn:H.\n      rewrite plus_comm in H. rewrite H. symmetry. apply plus_assoc.\nQed.\n\n\nInductive even_list (a:Set) : Set :=\n| ENil  : even_list a\n| ECons : a -> odd_list a -> even_list a\nwith odd_list (a:Set) : Set :=\n| OCons : a -> even_list a -> odd_list a\n.\n\nInductive list0 (a:Set) : Set :=\n| Nil0  : list0 a\n| Cons0 : a -> list2 a -> list0 a\nwith list1 (a:Set) : Set :=\n| Cons1 : a -> list0 a -> list1 a\nwith list2 (a:Set) : Set :=\n| Cons2 : a -> list1 a -> list2 a\n.\n\nArguments Nil0 {a}.\nArguments Cons0 {a}.\nArguments Cons1 {a}.\nArguments Cons2 {a}.\n\nFixpoint length0 (a:Set) (xs: list0 a) : nat :=\n    match xs with\n    | Nil0       => O\n    | Cons0 _ xs => S (length2 a xs)\n    end\nwith length1 (a:Set) (xs:list1 a) : nat :=\n    match xs with\n    | Cons1 _ xs => S (length0 a xs)\n    end\nwith length2 (a:Set) (xs:list2 a) : nat :=\n    match xs with\n    | Cons2 _ xs => S (length1 a xs)\n    end\n.\n\nArguments length0 {a}.\nArguments length1 {a}.\nArguments length2 {a}.\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/chapt3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.6856184932195049}}
{"text": "(* START: C *)\nDefinition C (A:Set) (P:A -> nat -> Prop) : Set :=\n   {a : A | exists (an:nat), (P a an)}.\n(* STOP: C *)\nHint Unfold C.\n\n(* START: ret *)\nDefinition ret (A:Set) (P:A -> nat -> Prop) (a:A) (Pa0:P a 0) : C A P.\n(* STOP: ret *)\nProof.\n  exists a.\n  exists 0.\n  apply Pa0.\nDefined.\n\n(* START: bind *)\nDefinition bind (A:Set) (PA:A -> nat -> Prop)\n                (B:Set) (PB:B -> nat -> Prop)\n                (am:C A PA) \n                (bf:forall (a:A) (pa:exists an, PA a an),\n                  C B (fun b bn => forall an, PA a an -> PB b (an+bn)))\n: C B PB.\n(* STOP: bind *)\nProof.\n  destruct am as [a Pa].\n  edestruct (bf a Pa) as [b Pb].\n  exists b.\n  destruct Pa as [an Pa].\n  destruct Pb as [bn Pb].\n  exists (an + bn).\n  eapply Pb.\n  apply Pa.\nDefined.\n\n(* START: inc *)\nDefinition inc (A:Set) k (PA : A -> nat -> Prop)\n           (xc:C A (fun x xn => forall xm, xn + k = xm -> PA x xm))\n: C A PA.\n(* STOP: inc *)\nProof.\n  destruct xc as [x Px].\n  exists x.\n  destruct Px as [n Px].\n  exists (n + k).\n  apply Px.\n  reflexivity.\nDefined.\n\nNotation \"<== x\" := (ret _ _ x _) (at level 55).\nNotation \"+= k ; c\" := (inc _ k _ c) (at level 30, right associativity).\nNotation \"x <- y ; z\" := (bind _ _ _ _ y (fun (x : _) (am : _) => z) )\n                           (at level 30, right associativity).\nNotation \"x >>= y\" := (bind _ _ _ _ x y) (at level 55).\nNotation \"x >> y\" := (bind _ _ _ _ x (fun _ => y)) (at level 30, right associativity).\n\nNotation \"{! x !:! A !<! c !>!  P !}\" := (C A (fun (x:A) (c:nat) => P)) (at level 55).\n\n", "meta": {"author": "rfindler", "repo": "395-2013", "sha": "afaeb6f4076a1330bbdeb4537417906bbfab5119", "save_path": "github-repos/coq/rfindler-395-2013", "path": "github-repos/coq/rfindler-395-2013/395-2013-afaeb6f4076a1330bbdeb4537417906bbfab5119/monad/monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6855390942626229}}
{"text": "Require Import Blech.Defaults.\n\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Classes.SetoidClass.\n\nRequire Import Blech.Bishop.\nRequire Import Blech.Category.\n\nImport BishopNotations.\nImport CategoryNotations.\n\nOpen Scope bishop_scope.\nOpen Scope morphism_scope.\n\n#[universes(cumulative)]\nInductive free {O} (S: O → O → Type): O → O → Type :=\n| η {A B} (_: S A B): free S A B\n| id A: free S A A\n| compose {A B C} (f: free S B C) (g: free S A B): free S A C.\n\nArguments η {O S A B}.\nArguments id {O S}.\nArguments compose {O S A B C}.\n\nInductive equiv {O: Type} {S: O → O → Type} `{∀ A B, Setoid (S A B)} : forall {A B: O}, relation (free S A B) :=\n| reflexive {A B}: reflexive _ (@equiv O S _ A B)\n| symmetric {A B}: symmetric _ (@equiv O S _ A B)\n| transitive {A B}: transitive _ (@equiv O S _ A B)\n\n| η_compat {A B}: Proper (SetoidClass.equiv ==> @equiv O S _ A B) η\n\n| compose_assoc {A B C D} (f: free S C D) (g: free S B C) (h: free S A B):\n    equiv (compose f (compose g h)) (compose (compose f g) h)\n\n| compose_id_left {A B} (f: free S A B): equiv (compose (id _) f) f\n| compose_id_right {A B} (f: free S A B): equiv (compose f (id _)) f\n\n| compose_compat {A B C}: Proper (@equiv O S _ B C ==> @equiv O S _ A B ==> @equiv O S _ A C) compose\n.\nExisting Instance η_compat.\nExisting Instance compose_compat.\n\n#[global]\n#[program]\nInstance free_Setoid O (S: O → O → Type) `(forall A B, Setoid (S A B)) A B: Setoid (@free O S A B) := {\n  equiv := equiv ;\n}.\nNext Obligation.\nProof.\n  exists.\n  - apply reflexive.\n  - apply symmetric.\n  - apply transitive.\nQed.\n\nDefinition Free {O} (S: O → O → Type) `{∀ A B, Setoid (S A B)}: Category := {|\n  Obj := O ;\n  Mor A B := free S A B ;\n\n  Mor_Setoid := free_Setoid O S _ ;\n\n  Category.id := id ;\n  Category.compose := @compose _ _ ;\n\n  Category.compose_assoc := @compose_assoc _ _ _ ;\n  Category.compose_id_left := @compose_id_left _ _ _ ;\n  Category.compose_id_right := @compose_id_right _ _ _ ;\n  Category.compose_compat := @compose_compat _ _ _ ;\n|}.\n\nFixpoint ε {C: Category} {A B} (f: Free C A B): C A B :=\n  match f with\n  | η x => x\n  | id _ => Category.id _\n  | compose x y => ε x ∘ ε y\n  end.\n", "meta": {"author": "mstewartgallus", "repo": "category-fun", "sha": "436a90c0f9e8a729da6416a2c0e54611ca5e4575", "save_path": "github-repos/coq/mstewartgallus-category-fun", "path": "github-repos/coq/mstewartgallus-category-fun/category-fun-436a90c0f9e8a729da6416a2c0e54611ca5e4575/theories/Category/Free.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6855390756778372}}
{"text": "Set Implicit Arguments.\n\nDefinition default A def (x : option A) :=\n  match x with\n    | Some v => v\n    | None => def\n  end.\n\nDefinition option_dec A (x : option A) : {a | x = Some a} + {x = None}.\n  destruct x.\n  left.\n  exists a.\n  eauto.\n  right.\n  eauto.\nQed.\n\nLemma option_map_some_elim A B (f : A -> B) o b : option_map f o = Some b -> exists a, o = Some a /\\ f a = b.\nProof.\n  intros H.\n  destruct (option_dec o) as [[a Ha]| Hn]; [rewrite Ha in H | rewrite Hn in H; discriminate]; simpl in *.\n  injection H; intros; subst.\n  exists a; eauto.\nQed.\n\nLemma option_map_some_intro A B (f : A -> B) o a b : o = Some a -> b = f a -> option_map f o = Some b.\nProof.\n  intros Ho Hb.\n  destruct (option_dec o) as [[a' Ha]| Hn]; [rewrite Ha in * | rewrite Hn in *; discriminate]; simpl in *.\n  injection Ho; intros; subst.\n  eauto.\nQed.\n\n", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/Cito/Option.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.7956581000631541, "lm_q1q2_score": 0.6854898435330603}}
{"text": "(*\n  Copyright 2022 ZhengPu Shi\n  This file is part of CoqMatrix. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : Signature of Vector Theory\n  author    : ZhengPu Shi\n  date      : 2022.06\n  \n  reference :\n  1. Vector Calculus - Michael Corral\n  2. https://github.com/coq/coq/blob/master/test-suite/success/Nsatz.v\n     Note: there are geometrys in coq, including point, parallel, collinear, etc.\n  3. (in Chinese) Higher Mathematics Study Manual - Xu Xiao Zhan, p173\n     《高等数学学习手册》徐小湛，p173\n *)\n\nRequire Export BasicConfig TupleExt SetoidListListExt HierarchySetoid.\nRequire Export ElementType.\n\n\n(* ######################################################################### *)\n(** * Basic vector theory *)\nModule Type BasicVectorTheory (E : ElementType).\n\n  (* ==================================== *)\n  (** ** Vector element type *)\n  Export E.\n\n  Infix \"==\" := (eqlistA Aeq) : list_scope.\n\n  Open Scope nat_scope.\n  Open Scope A_scope.\n  Open Scope vec_scope.\n  \n  (* ==================================== *)\n  (** ** Vector type and basic operations *)\n  Parameter vec : nat -> Type.\n  \n  (** matrix equality *)\n  Parameter veq : forall {n}, vec n -> vec n -> Prop.\n  Infix \"==\" := veq : vec_scope.\n\n  (** meq is equivalence relation *)\n  Axiom veq_equiv : forall n, Equivalence (veq (n:=n)).\n\n  (** Get n-th element *)\n  Parameter vnth : forall {n} (v : vec n) (i : nat), A.\n\n  (** veq and mnth should satisfy this constraint *)\n  Axiom veq_iff_vnth : forall {n : nat} (v1 v2 : vec n),\n      (v1 == v2) <-> (forall i, i < n -> (vnth v1 i == vnth v2 i)%A).\n\n  (* ==================================== *)\n  (** ** Convert between list and vector *)\n  Parameter l2v : forall {n} (l : list A), vec n.\n  Parameter v2l : forall {n}, vec n -> list A.\n  \n  Axiom v2l_length : forall {n} (v : vec n), length (v2l v) = n.\n  \n  Axiom v2l_l2v_id : forall {n} (l : list A), length l = n -> (@v2l n (@l2v n l) == l)%list.\n  Axiom l2v_v2l_id : forall {n} (v : vec n), l2v (v2l v) == v.\n\n  (* ==================================== *)\n  (** ** Convert between tuples and vector *)\n  Parameter t2v_2 : @T2 A -> vec 2.\n  Parameter t2v_3 : @T3 A -> vec 3.\n  Parameter t2v_4 : @T4 A -> vec 4.\n  \n  Parameter v2t_2 : vec 2 -> @T2 A.\n  Parameter v2t_3 : vec 3 -> @T3 A.\n  Parameter v2t_4 : vec 4 -> @T4 A.\n  \n  (* Axiom t2v_v2t_id_2 : forall (v : vec 2), t2v_2 (v2t_2 v) == v. *)\n  (* Axiom v2t_t2v_id_2 : forall (t : A * A), v2t_2 (t2v_2 t) = t. *)\n\n  (* ==================================== *)\n  (** ** Mapping for vector *)\n  \n  (** Mapping a vector *)\n  Parameter vmap : forall {n} (v : vec n) (f : A -> A), vec n.\n  \n  (** Fold a vector *)\n  (*   Parameter vfold : forall {B : Type} {n} (v : vec n) (f : A -> B) (b : B), B. *)\n  \n  (** Mapping two vectors *)\n  Parameter vmap2 : forall {n} (v1 v2 : vec n) (f : A -> A -> A), vec n.\n\nEnd BasicVectorTheory.\n\n\n\n(* ######################################################################### *)\n(** * Ring vector theory *)\n\n(** zero vector, vector addition, opposition, substraction, scalar multiplication,\n    dot product *)\nModule Type RingVectorTheory (E : RingElementType) <: BasicVectorTheory E.\n\n  Export E.\n  Include (BasicVectorTheory E).\n\n  (** zero vector *)\n  Parameter vec0 : forall n, vec n.\n\n  (** *** Vector addition *)\n  Parameter vadd : forall {n} (v1 v2 : vec n), vec n.\n  Infix \"+\" := vadd : vec_scope.\n  Axiom vadd_comm : forall {n} (v1 v2 : vec n), (v1 + v2) == (v2 + v1).\n  Axiom vadd_assoc : forall {n} (v1 v2 v3 : vec n), (v1 + v2) + v3 == v1 + (v2 + v3).\n  Axiom vadd_0_l : forall {n} (v : vec n), (vec0 n) + v == v.\n  Axiom vadd_0_r : forall {n} (v : vec n), v + (vec0 n) == v.\n  \n  (** *** Vector opposition *)\n  Parameter vopp : forall {n} (v : vec n), vec n.\n  Notation \"- v\" := (vopp v) : vec_scope.\n  Axiom vadd_opp_l : forall {n} (v : vec n), (- v) + v == vec0 n.\n  Axiom vadd_opp_r : forall {n} (v : vec n), v + (- v) == vec0 n.\n\n  (** *** Vector subtraction *)\n  Parameter vsub : forall {n} (v1 v2 : vec n), vec n.\n  Infix \"-\" := vsub : vec_scope.\n\n  (** *** Vector scalar multiplication *)\n  Parameter vcmul : forall {n} (a : A) (v : vec n), vec n.\n  Parameter vmulc : forall {n} (v : vec n) (a : A), vec n.\n  Infix \"c*\" := vcmul : vec_scope.\n  Infix \"*c\" := vmulc : vec_scope.\n  Axiom vmulc_eq_vcmul : forall {n} a (v : vec n), v *c a == a c* v.\n  Axiom vcmul_assoc : forall {n} a b (v : vec n), a c* (b c* v) == (a * b)%A c* v.\n  Axiom vcmul_perm : forall {n} a b (v : vec n), a c* (b c* v) == b c* (a c* v).\n  Axiom vcmul_add_distr_l : forall {n} a b (v : vec n),\n      (a + b)%A c* v == (a c* v) + (b c* v).\n  Axiom vcmul_add_distr_r : forall {n} a (v1 v2 : vec n),\n      a c* (v1 + v2) == (a c* v1) + (a c* v2).\n  Axiom vcmul_0_l : forall {n} (v : vec n), A0 c* v == vec0 n.\n  Axiom vcmul_1_l : forall {n} (v : vec n), A1 c* v == v.\n\n  (** *** Vector dot product *)\n  Parameter vdot : forall {n} (v1 v2 : vec n), A.\n\nEnd RingVectorTheory.\n\n\n(* ######################################################################### *)\n(** * Decidable field vector theory *)\n\nModule Type DecidableFieldVectorTheory (E : DecidableFieldElementType)\n<: RingVectorTheory E.\n\n  Export E.\n  Include (RingVectorTheory E).\n\n  (** veq is decidable *)\n  Axiom veq_dec : forall (n : nat), Decidable (veq (n:=n)).\n\nEnd DecidableFieldVectorTheory.\n\n\n(** ** Others, later ... *)\n\n(*\n(** Assert that a vector is an zero vector. *)\nParameter vzero : forall {n} (v : vec n), Prop.\n\n(** Assert that a vector is an non-zero vector. *)\nParameter vnonzero : forall {n} (v : vec n), Prop.\n\n(** It is decidable that if a vector is zero vector. *)\nAxiom vzero_dec : forall {n} (v : vec n), {vzero v} + {vnonzero v}.\n\n(** vec0 is equal to mat0 with column 1 *)\n(*   Lemma vec0_eq_mat0 : forall n, vec0 n = mat0 n 1.\n  Proof. lma. Qed. *)\n\n(** If two nonzero vectors has scalar multiplcation relation, \n    then the scalar coefficient must non-zero *)\nAxiom vec_eq_vcmul_imply_coef_neq0 : forall {n} (v1 v2 : vec n) k,\n    vnonzero v1 -> vnonzero v2 -> (v1 = k c* v2) -> k <> A0.\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/VectorTheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6854456014262094}}
{"text": "Require Import Arith.\nRequire Import Relations.\n\nAxiom prop_ext: forall P Q : Prop, P <-> Q -> P = Q.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* The dual of [ultimately] is [often]. Whereas [ultimately x, P x] intuitively\n   means that, once [x] is large enough, [P x] holds always, [often x, P x]\n   means that it is not the case that, once [x] is large enough, [P x] is false\n   always. In other words, [often x, P x] means that there exist arbitrarily\n   large [x]'s such that [P x] holds. We use the positive formulation as a\n   definition. The fact this is equivalent to the doubly-negated form can be\n   proved by exploiting the principle of excluded middle. *)\n\nSection Often.\n\nVariable A : filterType.\n\nImplicit Type P Q : pred A.\n\nDefinition often P :=\n  forall Q, ultimately A Q -> exists a, P a /\\ Q a.\n\nLemma often_characterization:\n  forall P,\n  ~ ultimately A (fun x => ~ P x) <-> often P.\nProof.\n  unfold often. split.\n\n  (* Left-to-right implication. *) {\n  (* Reductio ad absurdum. If there did not exist [a] that satisfies [P /\\ Q],\n     then [~ (P /\\ Q)] would hold everywhere. *)\n  intros oftenP Q ultQ.\n  apply not_all_not_ex. intros nPQ.\n  (* Thus, [~ (P /\\ Q)] would hold ultimately. *)\n  specialize (filter_universe_alt nPQ). intro nPQ'.\n  (* However, by hypothesis, [Q] holds ultimately. By combining these facts,\n     we find that [~P] holds ultimately. *)\n  assert (ultimately A (fun a => ~ P a)).\n  { eapply filter_closed_under_intersection.\n    - exact ultQ.\n    - exact nPQ'.\n    - eauto. }\n  (* This contradicts the hypothesis [~ ultimately ~ P]. *)\n  tauto. }\n\n  (* Right-to-left implication. *)\n  { intros H unP. destruct (H _ unP). tauto. }\nQed.\n\n(* TEMPORARY the definition of [often] looks like a [limit] assertion. Is it one?\n   Is there a connection? *)\n\nEnd Often.\n\nArguments often : clear implicits.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Inclusion of filters. *)\n\nDefinition finer A (ult1 ult2 : filter A) :=\n  forall P, ult2 P -> ult1 P.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* The filter [on Q] represents validity everywhere in the set [Q].\n   In other words, [on Q P] holds if and only if [Q] implies [P]. *)\n\nSection On.\n\nVariable A : Type.\n\nVariable Q : pred A.\n\nHypothesis Qx : exists x, Q x.\n\nDefinition on : filter A :=\n  fun P => forall x, Q x -> P x.\n\nDefinition mixin_on : filterMixin on.\nProof.\n  unfold on.\n  constructor; eauto.\n  destruct Qx as [ x ? ]; exists x; eauto.\nQed.\n\nDefinition filter_on := FilterType mixin_on.\n\nGoal ultimately filter_on = on.\nProof. reflexivity. Qed.\n\nLemma onP:\n  forall P : pred A,\n  ultimately filter_on P =\n  forall x, Q x -> P x.\nProof. reflexivity. Qed.\n\nEnd On.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* As a special case, [on (fun _ => True)] is the universal quantifier. *)\n\nSection Forall.\n\nVariable A : Type.\n\nVariable x : A.\n\nDefinition _forall :=\n  on (fun (_: A) => True).\n\nDefinition filter_forall :=\n  filter_on (ex_intro _ x I).\n\nGoal ultimately filter_forall = _forall.\nProof. reflexivity. Qed.\n\nLemma forallP:\n  forall P : pred A,\n  ultimately filter_forall P =\n  forall x, P x.\nProof.\n  intros P. unfold filter_forall. rewrite onP.\n  apply prop_ext. intuition.\nQed.\n\nEnd Forall.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* The (infinite) union of a decreasing family of filters is a filter. *)\n\nSection Union.\n\nVariable A : Type.\n\nVariable ult : nat -> filter A.\n\nVariable mixin : forall i, filterMixin (ult i).\n\nVariable decreasing : forall i j, i <= j -> finer (ult j) (ult i).\n\nDefinition union : filter A :=\n  fun P => exists i, ult i P.\n\nDefinition mixin_union : filterMixin union.\nProof.\n  unfold union.\n  constructor.\n  { exists 0. destruct (mixin 0). eauto. }\n  { intros P [ i ? ]. destruct (mixin i). eauto. }\n  { intros P1 P2 P [ i1 h1 ] [ i2 h2 ] ?.\n    exists (max i1 i2).\n    destruct (mixin (max i1 i2)) as [ _ _ inter ].\n    eapply inter; [| | eauto].\n    { eapply decreasing; [ |eauto].\n      apply Nat.le_max_l. }\n    { eapply decreasing; [ |eauto].\n      apply Nat.le_max_r. }\n  }\nQed.\n\nDefinition filter_union := FilterType mixin_union.\n\nGoal ultimately filter_union = union.\nProof. reflexivity. Qed.\n\nLemma unionP:\n  forall P,\n  ultimately filter_union P =\n  exists i, ult i P.\nProof. reflexivity. Qed.\n\nEnd Union.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Going up in an ordered set. *)\n\n(* TEMPORARY maybe define [at_and_above i] first, then take the union? *)\n\nSection Up.\n\nVariable A : Type.\n\nVariable le : A -> A -> Prop.\n\nHypothesis le_refl : reflexive A le.\nHypothesis le_trans : transitive A le.\n\nVariable x : nat -> A.\n\nVariable increasing : forall i j, i <= j -> le (x i) (x j).\n\nDefinition up : filter A :=\n  union (fun i => on (le (x i))).\n\nDefinition mixin_up : filterMixin up.\nProof.\n  apply mixin_union.\n  { intros i. apply mixin_on. eauto. }\n  { unfold on. intros i j ij P. eauto. }\nQed.\n\nDefinition filter_up := FilterType mixin_up.\n\nGoal ultimately filter_up = up.\nProof. reflexivity. Qed.\n\nLemma upP:\n  forall P,\n  ultimately filter_up P =\n  exists i, forall y, le (x i) y -> P y.\nProof. reflexivity. Qed.\n\n(* TEMPORARY used? *)\nLemma prove_up:\n  forall i,\n  ultimately filter_up (fun y => le (x i) y).\nProof. intros i. unfold filter_up. exists i. unfold on. eauto. Qed.\n\nEnd Up.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* The standard filter on [nat]. *)\n\nDefinition up_nat : filter nat :=\n  up le id.\n\nDefinition filter_up_nat :=\n  filter_up le_refl le_trans (fun i j : nat => id).\n\nGoal\n  forall P : pred nat,\n  (ultimately filter_up_nat P) =\n  exists n, forall x, n <= x -> P x.\nProof.\n  intros P. unfold filter_up_nat. rewrite upP. reflexivity.\nQed.\n\nGoal ultimately filter_up_nat (fun x => 42 <= x).\nProof. exists 42. unfold on. tauto. Qed.\n\nGoal ultimately filter_up_nat (fun x => 42 <= x).\nProof. unfold filter_up_nat. rewrite upP. exists 42. tauto. Qed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Applying a function [f] to a filter [ult] produces another filter, known as\n   the image of [ult] under [f]. *)\n\nSection Image.\n\n  Variables A B : Type.\n\n  Variable f : A -> B.\n\n  Variable ult : filter A.\n\n  Definition image : filter B :=\n    fun P => ult (fun x => P (f x)).\n\n  Definition mixin_image : filterMixin ult -> filterMixin image.\n  Proof.\n    intros [ Huniverse Hnonempty Hclosed ].\n    unfold image.\n    econstructor; eauto.\n    intros P H. pose proof (Hnonempty _ H) as [ ? ? ].\n    eauto.\n  Qed.\n\nEnd Image.\n\nDefinition filter_image (A : filterType) B (f : A -> B) :=\n  FilterType (mixin_image f (mixin A)).\n\nLemma imageP:\n  forall (A : filterType) B (f : A -> B),\n  forall P,\n  ultimately (filter_image f) P =\n  ultimately A (fun x => P (f x)).\nProof. reflexivity. Qed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* A notion of limit, or convergence, or divergence -- it all depends on which\n   filters one uses. The assertion [limit f] states that any property [P] that\n   is ultimately true of [y] is ultimately true of [f x]. If [f] is a function\n   from [nat] to [nat], equipped with its standard filter, this means that [f x]\n   tends to infinity as [x] tends to infinity. *)\n\n(* [limit] could take two arguments of type [filter A] and [filter B]. Instead,\n   we take two arguments of type [filterType]. *)\n\nSection Limit.\n\nVariables A B : filterType.\n\nVariable f : A -> B.\n\nDefinition limit :=\n  finer (ultimately (filter_image f)) (ultimately B).\n\nLemma limitP:\n  limit =\n  forall P,\n  (ultimately B (fun y => P y)) ->\n  (ultimately A (fun x => P (f x))).\nProof.\n  reflexivity.\nQed.\n\nEnd Limit.\n\nArguments limit : clear implicits.\n\nLemma limit_id:\n  forall A : filterType,\n  limit A A (fun a : A => a).\nProof.\n  intros A. rewrite limitP. tauto.\nQed.\n\n(* TEMPORARY how about proving on a lemma on the limit of a\n   function composition? *)\n\nGoal limit filter_up_nat filter_up_nat (fun x => x + 1).\nProof.\n  intros P. unfold filter_up_nat. rewrite upP. rewrite imageP.\n  intros [ n Px ]. exists n.\n  intros x ?. apply Px.\n  auto with arith.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\nSection Within.\n\n(* If we have a filter on [A], and if [P] is a subset of [A], then [within P] is\n   also a filter on [A]. By definition, a formula [Q] is ultimately holds within\n   [P] if and only if [P -> Q] is ultimately true. *)\n\n(* There is a condition on [P], though. The formula [P] must not forbid `going\n   to the limit' in the sense of [ultimately]. To take a concrete example, if\n   our initial filter is [up_nat], then it would not make sense for [P] to be\n   the property [fun n => n <= k]. If we did choose such a [P], then [within P]\n   would be a filter that says ``when [n] tends towards infinity while remaining\n   under [k]''. This makes no sense.\n\n   What is an appropriate condition on [P]? We could require [ultimately P], but\n   that would be too strong; if ultimately [P] holds, then ultimately [P -> Q]\n   is equivalent to ultimately [Q]. (Another way to see that this is wrong is to\n   take an example where [P] is [fun (i, n) => i <= n]. This property does not\n   hold ultimately, yet it does make sense.)\n\n   An appropriate condition seems to be [~ ultimately ~ P], also known as [often\n   P]. Indeed, if [P] is ultimately false, this means that [P] `forbids going to\n   the limit'. We can see that if [P] is ultimately false, then [P -> Q] is\n   ultimately true, regardless of [Q], and that is not a good thing, as we\n   expect [ultimately (P -> Q)] to imply something about [Q]. Technically, the\n   condition [often P] seems to be exactly what is needed in order to prove that\n   [within P] does not accept an empty [Q]. *)\n\nVariable A : filterType.\n\nVariable P : pred A.\n\nHypothesis oftenP : often A P.\n\nDefinition within : filter A :=\n  fun Q => ultimately A (fun x => P x -> Q x).\n\nDefinition mixin_within : filterMixin within.\nProof.\n  unfold within.\n  constructor.\n  { apply filter_universe_alt. tauto. }\n  { intros Q hPQ. destruct (oftenP hPQ) as [x [? ?]].\n    eauto. }\n  { intros Q1 Q2 Q hPQ1 hPQ2 ?.\n    eapply filter_closed_under_intersection.\n    - exact hPQ1.\n    - exact hPQ2.\n    - eauto. }\nQed.\n\nDefinition filter_within := FilterType mixin_within.\n\nGoal ultimately filter_within = within.\nProof. reflexivity. Qed.\n\nLemma withinP:\n  forall Q,\n  ultimately filter_within Q =\n  ultimately A (fun x => P x -> Q x).\nProof. reflexivity. Qed.\n\nEnd Within.\n\nArguments within : clear implicits.\n\nSection FilterProduct.\n\n(* ... *)\n\n(* When the pair [a1, a2] goes to infinity, its components go to infinity. *)\n\nLemma limit_fst:\n  limit filter_product A1 fst.\nProof.\n  unfold limit. simpl. unfold image. unfold product. simpl. unfold finer.\n  intros P1 ?.\n  exists P1. exists (fun _ => True).\n  repeat split; eauto. apply filter_universe.\nQed.\n\nLemma limit_snd:\n  limit filter_product A2 snd.\nProof.\n  unfold limit. simpl. unfold image. unfold product. simpl. unfold finer.\n  intros P2 ?.\n  exists (fun _ => True). exists P2.\n  repeat split; eauto. apply filter_universe.\nQed.\n\n(* When both components go to infinity, the pair goes to infinity. *)\n\n(* The limit of a pair is a pair of the limits. *)\n\nLemma limit_pair :\n  forall A : filterType,\n  forall (f1 : A -> A1) (f2 : A -> A2),\n  limit A A1 f1 ->\n  limit A A2 f2 ->\n  limit A filter_product (fun a => (f1 a, f2 a)).\nProof.\n  unfold limit. simpl. unfold image. unfold product. unfold finer.\n  intros A f1 f2 lf1 lf2 P (P1 & P2 & uP1 & uP2 & ?).\n  eapply filter_closed_under_intersection.\n  { apply lf1. apply uP1. }\n  { apply lf2. apply uP2. }\n  eauto.\nQed.\n\nEnd FilterProduct.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* The product of two [up]-filters is the [up]-filter for the product ordering. *)\n\nSection FilterProductUp.\n\n\nVariable A1 A2 : Type.\n\nVariable le1 : A1 -> A1 -> Prop.\nVariable le2 : A2 -> A2 -> Prop.\n\nHypothesis le_refl1 : reflexive A1 le1.\nHypothesis le_trans1 : transitive A1 le1.\nHypothesis le_refl2 : reflexive A2 le2.\nHypothesis le_trans2 : transitive A2 le2.\n\nVariable x1 : nat -> A1.\nVariable x2 : nat -> A2.\n\nVariable increasing1 : forall i j, i <= j -> le1 (x1 i) (x1 j).\nVariable increasing2 : forall i j, i <= j -> le2 (x2 i) (x2 j).\n\nNotation filter1 := (filter_up le_refl1 le_trans1 increasing1).\nNotation filter2 := (filter_up le_refl2 le_trans2 increasing2).\nNotation filter  := (filter_product filter1 filter2).\n\n(* TEMPORARY this is not the right place to define the product of two orderings\n   and prove its basic properties. *)\nDefinition prod_le (x y : A1 * A2) : Prop :=\n  let (x1, x2) := x in\n  let (y1, y2) := y in\n  le1 x1 y1 /\\ le2 x2 y2.\n\nLemma prod_le_refl: reflexive (A1 * A2) prod_le.\nProof. intros [? ?]. unfold prod_le. split. apply le_refl1. apply le_refl2. Qed.\n\nLemma prod_le_trans: transitive (A1 * A2) prod_le.\nProof.\n  do 3 (intros [ ? ? ]). unfold prod_le.\n  intros [ h1 h2 ]. intros [ i1 i2 ].\n  split; [eapply le_trans1 | eapply le_trans2]; eauto.\nQed.\n\nLemma prod_le_increasing:\n  forall i j, i <= j -> prod_le (x1 i, x2 i) (x1 j, x2 j).\nProof. intros i j ?. unfold prod_le. eauto. Qed.\n\nLemma product_upP:\n  forall Q : pred (A1 * A2),\n  ultimately filter Q =\n  ultimately (filter_up prod_le_refl prod_le_trans prod_le_increasing) Q.\nProof.\n  intros Q.\n  (* RHS. *)\n  rewrite upP.\n  (* LHS. *)\n  unfold ultimately. simpl. unfold product.\n  (* Split. *)\n  apply prop_ext. split.\n\n  (* Left to right. *)\n  { intros (P1 & P2 & uP1 & uP2 & hQ).\n    rewrite upP in uP1. destruct uP1 as [ i1 hP1 ].\n    rewrite upP in uP2. destruct uP2 as [ i2 hP2 ].\n    exists (max i1 i2).\n    intros [ y1 y2 ].\n    intros [ hy1 hy2 ].\n    apply hQ.\n    { apply hP1. apply (@le_trans1 _ (x1 (max i1 i2))).\n      apply increasing1. apply Nat.le_max_l. assumption. }\n    { apply hP2. apply (@le_trans2 _ (x2 (max i1 i2))).\n      apply increasing2. apply Nat.le_max_r. assumption. }\n  }\n\n  (* Right to left. *)\n  { intros [ i hQ ].\n    exists (le1 (x1 i)).\n    exists (le2 (x2 i)).\n    repeat split; try (exists i; unfold on; tauto).\n    intros a1 a2 ha1 ha2.\n    apply hQ. split; [apply ha1 | apply ha2]. }\nQed.\n\nEnd FilterProductUp.\n\nGoal\n  ultimately (filter_product filter_up_nat filter_up_nat)\n    (fun p : nat * nat =>\n      let (x, y) := p in\n      (42 <= x) /\\ (64 <= y)).\nProof.\n  unfold filter_up_nat.\n  rewrite product_upP. rewrite upP.\n  exists 64.\n  intros [ x y ].\n  unfold prod_le.\n  omega.\nQed.\n\nGoal\n  ultimately (filter_product filter_up_nat filter_up_nat)\n    (fun p : nat * nat =>\n      let (x, y) := p in\n      (42 <= x) /\\ (64 <= y)).\nProof.\n  simpl. unfold product.\n  exists (fun x\t=> 42 <= x).\n  exists (fun y => 64 <= y).\n  unfold filter_up_nat.\n  repeat split.\n  { rewrite upP. eauto. }\n  { rewrite upP. eauto. }\n  eauto. eauto.\nQed.\n\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Canonical filter for a preorder in a meet-semilattice. *)\n\n(* TEMPORARY this should be defined somewhere else *)\nDefinition with_upper_bounds A (le: A -> A -> Prop) :=\n  forall x y, exists z, le x z /\\ le y z.\n\nArguments with_upper_bounds : clear implicits.\n\nDefinition inhab A :=\n  exists (x: A), True.\n\nSection Canonical.\n\nVariable A : Type.\n\nHypothesis A_inhab: inhab A.\n\nVariable le : A -> A -> Prop.\n\nHypothesis le_refl : reflexive A le.\nHypothesis le_trans : transitive A le.\nHypothesis le_ub : with_upper_bounds A le.\n\nDefinition canonical : filter A :=\n  fun P => exists x0, forall x, le x0 x -> P x.\n\nDefinition mixin_canonical : filterMixin canonical.\nProof.\n  unfold canonical.\n  constructor.\n  { destruct A_inhab as [ x0 _ ]. exists x0. tauto. }\n  { intros P [ x0 H ]. exists x0. apply H. apply le_refl. }\n  { intros P1 P2 P [ x0 H1 ] [ y0 H2 ] H.\n    pose proof (le_ub x0 y0) as [z0 [le_x0_z0 le_y0_z0]].\n    exists z0. intros.\n    apply H; [apply H1 | apply H2]; apply (@le_trans _ z0); tauto. }\nQed.\n\nDefinition filter_canonical := FilterType mixin_canonical.\n\nGoal ultimately filter_canonical = canonical.\nProof. reflexivity. Qed.\n\nLemma canonicalP:\n  forall P,\n  ultimately filter_canonical P =\n  exists x0, forall x, le x0 x -> P x.\nProof. reflexivity. Qed.\n\nEnd Canonical.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* The standard filter on [nat], defined using [canonical]. *)\n\nDefinition canonical_nat : filter nat :=\n  canonical le.\n\nLemma le_ub : with_upper_bounds nat le.\nProof.\n  unfold with_upper_bounds. intros x y.\n  exists (max x y). split.\n  - apply Nat.le_max_l.\n  - apply Nat.le_max_r.\nQed.\n\nDefinition filter_canonical_nat :=\n  filter_canonical (ex_intro _ 0 I) le_refl le_trans le_ub.\n\nGoal\n  forall P : pred nat,\n  (ultimately filter_canonical_nat P) =\n  exists n, forall x, n <= x -> P x.\nProof.\n  intros P. unfold filter_canonical_nat. rewrite canonicalP. reflexivity.\nQed.\n\nGoal ultimately filter_canonical_nat (fun x => 42 <= x).\nProof. exists 42. tauto. Qed.\n\nGoal ultimately filter_canonical_nat (fun x => 42 <= x).\nProof. unfold filter_canonical_nat. rewrite canonicalP. exists 42. tauto. Qed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* The product of two [canonical]-filters is the [canonical]-filter for the\n   product ordering. *)\n\nSection FilterProductCanonical.\n\nVariable A1 A2 : Type.\n\nHypothesis A1_inhab : inhab A1.\nHypothesis A2_inhab : inhab A2.\n\nVariable le1 : A1 -> A1 -> Prop.\nVariable le2 : A2 -> A2 -> Prop.\n\nHypothesis le_refl1 : reflexive A1 le1.\nHypothesis le_trans1 : transitive A1 le1.\nHypothesis le_refl2 : reflexive A2 le2.\nHypothesis le_trans2 : transitive A2 le2.\nHypothesis le_ub1 : with_upper_bounds A1 le1.\nHypothesis le_ub2 : with_upper_bounds A2 le2.\n\nNotation filter1 := (filter_canonical A1_inhab le_refl1 le_trans1 le_ub1).\nNotation filter2 := (filter_canonical A2_inhab le_refl2 le_trans2 le_ub2).\nNotation filter  := (filter_product filter1 filter2).\n\n(* TEMPORARY this should be defined someplace else *)\nLemma A1A2_inhab : inhab (A1 * A2).\nProof.\n  destruct A1_inhab as [ a1 _ ]. destruct A2_inhab as [ a2 _ ].\n  exists (a1, a2). tauto.\nQed.\n\nLemma prod_le_ub : with_upper_bounds (A1 * A2) (prod_le le1 le2).\nProof.\n  unfold with_upper_bounds.\n  intros [x0 y0] [x1 y1].\n  pose proof (le_ub1 x0 x1) as [zx [? ?]].\n  pose proof (le_ub2 y0 y1) as [zy [? ?]].\n  exists (zx, zy). unfold prod_le. eauto.\nQed.\n\nLemma product_canonicalP:\n  forall Q : pred (A1 * A2),\n  ultimately filter Q =\n  ultimately\n    (filter_canonical\n       A1A2_inhab\n       (prod_le_refl le_refl1 le_refl2)\n       (prod_le_trans le_trans1 le_trans2)\n       prod_le_ub)\n    Q.\nProof.\n  intros Q.\n  (* RHS. *)\n  rewrite canonicalP.\n  (* LHS. *)\n  unfold ultimately. simpl. unfold product.\n  (* Split. *)\n  apply prop_ext. split.\n\n  (* Left to right. *)\n  { intros (P1 & P2 & uP1 & uP2 & hQ).\n    rewrite canonicalP in uP1. destruct uP1 as [ x0 hP1 ].\n    rewrite canonicalP in uP2. destruct uP2 as [ y0 hP2 ].\n    exists (x0, y0).\n    intros [ x y ]. unfold prod_le.\n    intros [ hx hy ].\n    apply hQ; eauto. }\n\n  (* Right to left. *)\n  { intros [ [ x0 y0 ] hQ ].\n    exists (le1 x0).\n    exists (le2 y0).\n    repeat split. rewrite canonicalP.\n    - exists x0. tauto.\n    - exists y0. tauto.\n    - intros a1 a2 ha1 ha2.\n      apply hQ. split; [apply ha1 | apply ha2]. }\nQed.\n\nEnd FilterProductCanonical.\n\nGoal\n  ultimately (filter_product filter_canonical_nat filter_canonical_nat)\n    (fun p : nat * nat =>\n      let (x, y) := p in\n      (42 <= x) /\\ (64 <= y)).\nProof.\n  unfold filter_canonical_nat.\n  rewrite product_canonicalP. rewrite canonicalP.\n  exists (42, 64).\n  intros [ x y ].\n  unfold prod_le.\n  tauto.\nQed.\n\nGoal\n  ultimately (filter_product filter_canonical_nat filter_canonical_nat)\n    (fun p : nat * nat =>\n      let (x, y) := p in\n      (42 <= x) /\\ (64 <= y)).\nProof.\n  simpl. unfold product.\n  exists (fun x\t=> 42 <= x).\n  exists (fun y => 64 <= y).\n  unfold filter_canonical_nat.\n  repeat split.\n  { rewrite canonicalP. eauto. }\n  { rewrite canonicalP. eauto. }\n  eauto. eauto.\nQed.\n\n\n(* ---------------------------------------------------------------------------- *)\n\nModule OrderedFilter.\n\nRecord mixin_of (A : filterType) : Type := Mixin {\n  le : binary A;\n  _ : forall x : A, ultimately A (fun y => le x y)\n}.\n\nSection ClassDef.\n\nRecord class_of (A : Type) : Type := Class {\n  base : Filter.class_of A;\n  mixin : mixin_of (Filter.Pack base)\n}.\n\nStructure type := Pack { sort : Type; class : class_of sort }.\n\nDefinition filterType (cT : type) := @Filter.Pack (sort cT) (base (class cT)).\n(* TEMPORARY (?) this definition looks natural, but does not match (at least *)\n(*    obviously) the way similar ones are written in ssreflect *)\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Filter.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nCoercion filterType : type >-> Filter.type.\nNotation orderedFilterType := type.\nNotation OrderedFilterType T m := (@Pack T m).\nNotation OrderedFilterMixin := Mixin.\nEnd Exports.\n\nEnd OrderedFilter.\nExport OrderedFilter.Exports.\n\nDefinition filter_le T := OrderedFilter.le (OrderedFilter.class T).\nArguments filter_le : clear implicits.\n\nSection OrderedFilterLaws.\n\nVariable A : orderedFilterType.\n\nLemma orderedFilterP :\n  forall x, ultimately A (fun y => filter_le A x y).\nProof.\n  destruct A as [? [? M]]. destruct M. eauto.\nQed.\n\nEnd OrderedFilterLaws.\n\nArguments orderedFilterP : clear implicits.\n\nSection OrderedFilterProduct.\n\nVariable A1 A2 : orderedFilterType.\n\nDefinition product_orderedFilterMixin :\n  OrderedFilter.mixin_of (product_filterType A1 A2).\nProof.\n  eapply OrderedFilter.Mixin with\n    (prod2 (filter_le A1) (filter_le A2)).\n  intros [ x1 x2 ].\n  forwards H1: orderedFilterP A1 x1.\n  forwards H2: orderedFilterP A2 x2.\n  rewrite productP. do 2 eexists. splits; [apply H1 | apply H2 | ..].\n  unfold prod2. eauto.\nDefined.\n\nDefinition product_orderedFilterClass :\n  OrderedFilter.class_of (product_filterType A1 A2).\nProof.\n  eapply OrderedFilter.Class with\n    (Filter.class (product_filterType A1 A2)).\n  apply product_orderedFilterMixin.\nDefined.\n\nDefinition product_orderedFilterType :=\n  OrderedFilterType (A1 * A2) product_orderedFilterClass.\n\nEnd OrderedFilterProduct.\n\nLemma productOrdP :\n  forall (A1 A2 : orderedFilterType) P,\n  ultimately (product_orderedFilterType A1 A2) P =\n  (exists P1 P2,\n   ultimately A1 P1 /\\\n   ultimately A2 P2 /\\\n   (forall a1 a2, P1 a1 -> P2 a2 -> P (a1, a2))).\nProof. reflexivity. Qed.\n\nLemma productOrdLeP :\n  forall A1 A2 p1 p2,\n  filter_le (product_orderedFilterType A1 A2) p1 p2 =\n  (filter_le A1 (fst p1) (fst p2) /\\ filter_le A2 (snd p1) (snd p2)).\nProof. intros ? ? [? ?] [? ?]. reflexivity. Qed.\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/attic/Filter_.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.6854180560710569}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_TGsymmetric.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_TTorder : \n   forall A B C D E F G H, \n   TT A B C D E F G H ->\n   TT C D A B E F G H.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists J, (BetS E F J /\\ Cong F J G H /\\ TG A B C D E J)) by (conclude_def TT );destruct Tf as [J];spliter.\nassert (TG C D A B E J) by (conclude lemma_TGsymmetric).\nassert (TT C D A B E F G H) by (conclude_def TT ).\nclose.\nQed.\n\nEnd Euclid.", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_TTorder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6854180554944137}}
{"text": "Require Export D.\n\n\n\n(** **** Problem #7 : 2 stars (split) *)\n(** The function [split] is the right inverse of combine: it takes a\n    list of pairs and returns a pair of lists.  In many functional\n    programing languages, this function is called [unzip].\n\n    Uncomment the material below and fill in the definition of\n    [split].  Make sure it passes the given unit tests. *)\n\nFixpoint split\n           {X Y : Type} (l : list (X*Y))\n           : (list X) * (list Y) :=\n  match l with\n  | [] => ([], [])\n  | (a, b)::tl  => (a::fst(split tl), b::snd(split tl)) \n  end.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. reflexivity.  Qed.\n\nTheorem split_map: forall X Y (l: list (X*Y)),\n   fst (split l) = map fst l.\nProof.\n  intros. induction l. reflexivity. destruct x. simpl. rewrite->IHl. 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/P01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.8670357598021707, "lm_q1q2_score": 0.6854180554944136}}
{"text": "Require Export Basics_J.\n\nSet Asymmetric Patterns.\n\nInductive\n  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 nil nat.\nCheck 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.\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)\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\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\nArguments nil [X].\nArguments cons [X].\nArguments length [X].\nArguments app [X].\nArguments rev [X].\nArguments snoc [X].\n\n\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\nDefinition mynil : list nat := nil.\nCheck @nil.\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].\nEval simpl in list123'''.\nCheck list123'''.\n\nFixpoint repeat (X : Type) (n : X) (count : nat) : list X :=\n  match count with\n  | 0 => 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, forall v : X, 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    reflexivity.\n  Case \"s = v' :: s'\".\n    simpl. rewrite -> IHs'. reflexivity. Qed.\n\nTheorem snoc_with_append : forall X : Type, forall l1 l2 : list X, 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    reflexivity.\n  Case \"l1 = v' :: l1'\".\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\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) : list (X * Y) :=\n  match (lx, ly) with\n  | ([], _) => []\n  | (_, []) => []\n  | (x :: tx, y :: ty) => (x, y) :: (combine tx ty)\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} (ps : list (X * Y)) : (list X * list Y) :=\n  match ps with\n  | [] => ([], [])\n  | (x, y) :: ps' => match split ps' with\n                   | (xs, ys) => (x :: xs, y :: ys)\n                   end\n  end.\n\nExample test_split:\n  split [(1,false),(2,false)] = ([1,2],[false,false]).\nProof. 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) (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 := index 0 l.\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.\n\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} (f : X * Y -> Z) (x : X) (y : Y) : Z :=\n  f (x, y).\n\nDefinition prod_uncurry {X Y Z : Type}\n           (f : X -> Y -> Z) (p : X * Y) : Z := f (fst p) (snd p).\n\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. reflexivity. Qed.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                               (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros. destruct p. 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)\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 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\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\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.\n\nExample test_map3:\n    map (fun n => [evenb n,oddb n]) [2,1,2,5]\n  = [[true,false],[false,true],[true,false],[false,true]].\nProof. reflexivity.  Qed.\n\nTheorem 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).\nProof.\n  intros. induction l as [| x' l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = x' :: l'\".\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. induction l as [| x l'].\n  Case \"n = []\".\n    reflexivity.\n  Case \"n = x :: l'\".\n    simpl. rewrite <- IHl'. apply snoc_map. Qed.\n\nFixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X)\n                   : (list Y) :=\n  match l with\n  | [] => []\n  | h :: ts => (f h) ++ (flat_map f ts)\n  end.\n\nExample test_flat_map1:\n  flat_map (fun n => [n,n,n]) [1,5,4]\n  = [1, 1, 1, 5, 5, 5, 4, 4, 4].\nProof. reflexivity.  Qed.\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X) : option Y :=\n  match xo with\n  | None => None\n  | Some x => Some (f x)\n  end.\n\nFixpoint fold {X Y : Type} (f : X -> Y -> Y) (l : list X) (b : Y) : Y :=\n  match l with\n  | [] => b\n  | h :: t => f h (fold f t b)\n  end.\n\nCheck (fold 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 nat) [[1],[],[2,3],[4]] [] = [1,2,3,4].\nProof. reflexivity. Qed.\n\nDefinition constfun {X : Type} (x : X) : nat -> X :=\n  fun (k : nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\nDefinition override {X : Type} (f : nat -> X) (k : nat) (x : X) : nat -> X :=\n  fun (k' : nat) => if beq_nat k k' then x else f k'.\n\nDefinition fmostlytrue := override (override ftrue 1 false) 3 false.\n\nExample override_example1 : fmostlytrue 0 = true.\nProof. reflexivity. Qed.\n\nExample override_example2 : fmostlytrue 1 = false.\nProof. reflexivity. Qed.\n\nExample override_example3 : fmostlytrue 2 = true.\nProof. reflexivity. Qed.\n\nExample override_example4 : fmostlytrue 3 = false.\nProof. reflexivity. Qed.\n\nTheorem override_example : forall (b:bool),\n  (override (constfun b) 3 true) 2 = b.\n(* すべての真偽値 b について、 3 を受け取った場合に true を返し、 そうでなければ b を返す関数を 2 に適用した結果は b である  *)\nProof. reflexivity. Qed.\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  unfold plus3.\n  rewrite -> H.\n  reflexivity. Qed.\n\nTheorem override_eq : forall {X:Type} x k (f:nat->X),\n  (override f k x) k = x.\nProof.\n  intros X x k f.\n  unfold override.\n  rewrite <- beq_nat_refl.\n  reflexivity.  Qed.\n\nTheorem override_neq : forall {X:Type} x1 x2 k1 k2 (f : nat->X),\n  f k1 = x1 ->\n  beq_nat k2 k1 = false ->\n  (override f k2 x2) k1 = x1.\nProof.\n  intros X x1 x2 k1 k2 f H H'.\n  unfold override.\n  rewrite -> H'.\n  apply H. Qed.\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 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\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 eq0 eq1. inversion eq1. reflexivity. Qed.\n\nTheorem silly6 : forall (n : nat),\n    S n = O ->\n    2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem silly7 : forall (n m : nat),\n    false = true ->\n    [n] = [m].\nProof.\n  intros n m contra. inversion contra. Qed.\n\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 eq0 eq1. inversion eq0. Qed.\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 [| m'].\n    SCase \"m = 0\". reflexivity.\n    SCase \"m = S m'\". simpl. intros contra. inversion contra.\n  Case \"n = 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\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\". 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. intros eq.\n      apply eq_remove_S. apply IHm'. apply eq. Qed.\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 = []\".\n    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_0_l : forall n,\n  true = beq_nat 0 n -> 0 = n.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    intros contra. inversion contra. Qed.\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\". reflexivity.\n  Case \"n = S n'\".\n    intros contra. inversion contra. 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  Case \"n = 0\".\n    intros m. induction m as [| m'].\n    SCase \"m = 0\". reflexivity.\n    SCase \"m = S m'\". intros contra. inversion contra.\n  Case \"n = S n'\".\n    intros m. induction m as [| m'].\n    SCase \"m = 0\". intros contra. inversion contra.\n    SCase \"m = S m'\".\n    intros H. apply eq_remove_S. apply 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.\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  ->\n     true = beq_nat (S (S n)) 7.\nProof.\n  intros n eq H.\n  symmetry in H. apply eq in H. symmetry in H.\n  apply H. Qed.\n\nTheorem plus_n_n_injective : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    intros m. induction m as [| m'].\n    SCase \"m = 0\". reflexivity.\n    SCase \"m = S m'\". intros contra. inversion contra.\n  Case \"n = S n'\".\n    intros m H. induction m as [| m'].\n    SCase \"m = 0\". inversion H.\n    SCase \"m = S m'\".\n      rewrite <- plus_n_Sm in H. rewrite <- plus_n_Sm in H.\n      simpl in H. inversion H.\n      apply IHn' in H1.\n      apply eq_remove_S in H1.\n      apply H1. 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 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\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 x 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. Qed.\n\n\nTheorem split_combine : forall (X Y : Type) (l : list (X * Y)) (l1 : list X) (l2 : list Y),\n    split l = (l1, l2) -> combine l1 l2 = l.\nProof.\n  intros X Y l. induction l as [| [x y] l'].\n    Case \"l = []\".\n      intros l1 l2 H. simpl in H. inversion H. reflexivity.\n    Case \"l = [x y] :: l'\".\n      intros l1 l2 H.\n      simpl in H.\n      destruct (split l') as [xs ys].\n      inversion H.\n      simpl.\n      rewrite -> IHl'.\n      reflexivity.\n      reflexivity. Qed.\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.\n      destruct e5.\n        SCase \"beq_nat n 5 = true\". apply beq_nat_eq in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        SCase \"beq_nat n 5 = false\". inversion eq. Qed.\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  remember (beq_nat k1 k2) as eqk.\n  destruct eqk.\n    Case \"beq_nat k1 k2 = true\".\n      apply beq_nat_eq in Heqeqk.\n      rewrite <- Heqeqk. symmetry. apply H.\n    Case \"beq_nat k1 k2 = false\". reflexivity. Qed.\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 [| x' l'].\n    Case \"l = []\".\n      intros. inversion H.\n    Case \"l = x' :: l'\".\n      intros. unfold filter in H.\n      remember (test x') as eqt. destruct eqt.\n        SCase \"test x' = true\".\n          inversion H. rewrite <- H1. symmetry. apply Heqeqt.\n        SCase \"test x' = false\".\n          apply IHl' in H. apply H. 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  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\n  apply trans_eq with [c, d]. apply eq1. apply eq2. Qed.\n\nExample trans_eq_exercise : forall (n m o p : nat),\n    m = (minustwo o) ->\n    (n + p) = m ->\n    (n + p) = minustwo o.\nProof.\n  intros n m o p eq1 eq2.\n  apply trans_eq with m. apply eq2. apply eq1. Qed.\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  intros n m p eq1 eq2.\n  apply beq_nat_eq in eq1. apply beq_nat_eq in eq2.\n  rewrite -> (trans_eq n m p eq1 eq2).\n  apply beq_nat_refl. Qed.\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 X x1 x2 k1 k2 k3 f eq1.\n  unfold override. remember (beq_nat k1 k3) as eqk. destruct eqk.\n    Case \"beq_nat k1 k3 = true\".\n      apply beq_nat_eq in Heqeqk. rewrite -> Heqeqk in eq1. rewrite <- eq1. reflexivity.\n    Case \"beq_nat k1 k3 = false\".\n      reflexivity. Qed.\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. induction l as [| x l'].\n  Case \"l = []\". reflexivity.\n  Case \"l = x ::l'\".\n    simpl. rewrite <- IHl'. unfold fold_length. simpl. reflexivity. Qed.\n\nDefinition fold_map {X Y:Type} (f : X -> Y) (l : list X) : list Y :=\n  fold (fun x l' => cons (f x) l') l [].\n\nTheorem fold_map_correct : forall (X Y : Type) (f : X -> Y) (l : list X),\n    fold_map f l = map f l.\nProof.\n  intros X Y f l. induction l as [| x l'].\n  Case \"l = []\". reflexivity.\n  Case \"l = x :: l'\".\n    simpl. rewrite <- IHl'. unfold fold_map. simpl. reflexivity. Qed.\n\nModule MumbleBaz.\n  Inductive mumble : Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\n\n  Inductive grumble (X : Type) : Type :=\n  | d : mumble -> grumble X\n  | e : X -> grumble X.\n\n  Inductive baz : Type :=\n  | x : baz -> baz\n  | y : baz -> bool -> baz.\nEnd MumbleBaz.\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => true\n  | h :: t => if test h then forallb test t else false\n  end.\n\nFixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => false\n  | h :: t => if test h then true else existsb test t\n  end.\n\n\nExample test_forallb1 : forallb oddb [1,3,5,7,9] = true.\nProof. reflexivity. Qed.\n\nExample test_forallb2 : forallb negb [false,false] = true.\nProof. reflexivity. Qed.\n\nExample test_forall3 : forallb evenb [0,2,4,5] = false.\nProof. reflexivity. Qed.\n\nExample test_forallb4 : forallb (beq_nat 5) [] = true.\nProof. reflexivity. Qed.\n\nExample test_existsb1 : existsb (beq_nat 5) [0,2,3,6] = false.\nProof. reflexivity. Qed.\n\nExample test_existsb2 : existsb (andb true) [true,true,false] = true.\nProof. reflexivity. Qed.\n\nExample test_existsb3 : existsb oddb [1,0,0,0,0,3] = true.\nProof. reflexivity. Qed.\n\nExample test_existsb4 : existsb evenb [] = false.\nProof. reflexivity. Qed.\n\nDefinition existsb' {X : Type} (test : X -> bool) (l : list X) : bool :=\n  negb (forallb (fun x => (negb (test x))) l).\n\nTheorem existsb_correct : forall {X : Type} (test : X -> bool) (l : list X),\n    existsb' test l = existsb test l.\nProof.\n  induction l as [|x l'].\n  Case \"l = []\". reflexivity.\n  Case \"l = x :: l'\".\n    unfold existsb'. simpl.\n    destruct (test x).\n    SCase \"test x = true\". reflexivity.\n    SCase \"test x = false\".\n      rewrite <- IHl'. unfold existsb'.\n      simpl. reflexivity.\nQed.\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/Poly_J.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303137346446, "lm_q2_score": 0.8670357615200475, "lm_q1q2_score": 0.6854180525735996}}
{"text": "Require Import Raxiom Rconvenient.\n\nModule IZR (Import T : CReals).\n\nModule Rconvenient := Rconvenient T.\nImport Rconvenient.\n\nOpen Scope R_scope.\n\nDefinition INR := fix f n := match n with O => R0 | S n' => R1 + f n' end.\n\nLemma INR_add : forall a b, INR (a + b) == INR a + INR b.\nProof.\n  intros a b; induction a.\n    simpl; symmetry; apply Radd_0_l.\n    simpl; rewrite IHa; ring.\nQed.\n\nLemma INR_S : forall n, INR (S n) == R1 + INR n.\nProof.\n  intros; reflexivity.\nQed.\n\nLemma INR_mul : forall a b, INR (a * b) == INR a * INR b.\nProof.\n  intros a b; induction a.\n    simpl; symmetry; apply Rmul_0_l.\n    simpl; rewrite INR_add, IHa; ring.\nQed.\n\nLemma INR_IPR : forall p, INR (nat_of_P p) == IPR p.\nProof.\n  intros p.\n  induction p.\n    rewrite nat_of_P_xI, INR_S, INR_mul, IHp; simpl; ring.\n    rewrite nat_of_P_xO, INR_mul, IHp; simpl; ring.\n    simpl; ring.\nQed.\n\nLemma IZR_Zopp : forall z, IZR (- z) == - IZR z.\nProof.\n  intros z; induction z.\n    simpl; symmetry; apply Ropp_0.\n    reflexivity.\n    symmetry; apply Ropp_involutive.\nQed.\n\nLemma IZR_INR : forall n, IZR (Z_of_nat n) == INR n.\nProof.\n  intros n.\n  destruct n.\n  reflexivity.\n  \n  rewrite\n    <- nat_of_P_o_P_of_succ_nat_eq_succ,\n    <- Zpos_eq_Z_of_nat_o_nat_of_P,\n    INR_IPR.\n  reflexivity.\nQed.\n\nLemma INR_sub : forall a b, le b a -> INR (a - b) == INR a - INR b.\nProof.\n  intros a b ab.\n  rewrite (le_plus_minus b a ab) at 2.\n  unfold Rsub.\n  rewrite INR_add.\n  rewrite Radd_comm, <- Radd_assoc, (Radd_comm (- INR b)), Radd_opp_r, Radd_0_l.\n  reflexivity.\nQed.\n\n\nLemma Zopp_swap : forall a b, Z.opp a = b -> a = Z.opp b.\nProof.\n  intros a b H; rewrite <- H; ring.\nQed.\n\nLemma Zuminus : forall a b, (a + - b = a - b)%Z.\nProof.\n  intros; ring.\nQed.\n\nLemma Rpos_IPR : forall p, R0 < IPR p.\nProof.\nintros p; induction p; simpl.\n  apply Rlt_trans with (R0 + R1).\n  apply Req_lt_compat_r with R1; [ symmetry; apply Radd_0_l | apply Rlt_0_1 ].\n  \n  apply Radd_lt_compat_r.\n  eapply Req_lt_compat_l; [ apply Rmul_0_r | ].\n  apply Rmul_lt_compat_l.\n    apply Rlt_0_2.\n    apply IHp.\n  \n  eapply Req_lt_compat_l; [ apply Rmul_0_r | ].\n  apply Rmul_lt_compat_l.\n    apply Rlt_0_2.\n    apply IHp.\n  \n  apply Rlt_0_1.\nQed.\n\nLemma Rdiscr_IPR_0 : forall p, IPR p ## R0.\nProof.\nintros p; right; apply Rpos_IPR.\nQed.\n\nLemma IZR_opp : forall a, IZR (- a) == - IZR a.\nProof.\n  intros [ | p | p ]; simpl; symmetry.\n    apply Ropp_0.\n    reflexivity.\n    apply Ropp_involutive.\nQed.\n\nLemma IPR_psucc : forall a, IPR (Pos.succ a) == IPR a + R1.\nProof.\n  induction a.\n   simpl. rewrite IHa. now ring.\n   \n   simpl. now ring.\n   \n   simpl. ring.\nQed.\n\nLemma IPR_add_carry : forall a b, IPR (a + b) == IPR a + IPR b \n  /\\ IPR (Pplus_carry a b) == IPR a + IPR b + R1.\nProof.\n  induction a; simpl; intros.\n   destruct b.\n    simpl. destruct (IHa b) as [H1 H2]. rewrite H2. split.\n     now ring.\n     \n     now ring.\n    \n    simpl. destruct (IHa b) as [H1 H2]. rewrite H1, H2. split.\n     now ring.\n     \n     now ring.\n   \n   simpl. destruct (IHa 1%positive) as [H1 H2]. rewrite IPR_psucc. split.\n    now ring.\n    \n    now ring.\n   \n   destruct b; simpl.\n    destruct (IHa b) as [H1 H2]. split.\n     rewrite H1. now ring.\n     \n     rewrite H2. now ring.\n    \n    destruct (IHa b) as [H1 H2]. split.\n     rewrite H1. now ring.\n     \n     rewrite H1. now ring.\n   \n   destruct (IHa 1%positive) as [H1 H2 ]. split.\n    now intuition.\n    \n    rewrite IPR_psucc. simpl. now ring.\n  \n  destruct b.\n   simpl. split.\n    rewrite IPR_psucc. now ring.\n    \n    rewrite IPR_psucc. now ring.\n   \n   split.\n    simpl. now ring.\n    \n    simpl. rewrite IPR_psucc. now ring.\n  \n  simpl. split.\n   now ring.\n   \n   ring.\nQed.\n\nLemma IPR_add : forall a b, IPR (a + b) == IPR a + IPR b.\nProof.\n  apply IPR_add_carry.\nQed.\n\nLemma IPR_sub : forall a b, Pcompare a b Eq = Gt -> IPR (a - b) == IPR a - IPR b.\nProof.\n  intros a b Cab.\n  unfold Pminus.\n  remember (Pminus_mask a b) as pmab.\n  destruct (Pminus_mask_Gt _ _ Cab) as (z, (Hz, (eqz, Dz))).\n  destruct pmab as [ | p | ]; try congruence.\n  rewrite <- eqz.\n  unfold Rsub (* TODO BUG : the following rewrite does not work under Rsub *) .\n  rewrite IPR_add.\n  cut (p = z).\n    intro; subst; ring.\n    congruence.\nQed.\n\nLemma IZR_add : forall a b, IZR (a + b) == IZR a + IZR b.\nProof.\n  intros [ | a | a ] [ | b | b ]; simpl; try ring.\n    apply IPR_add.\n    \n    rewrite Z.pos_sub_spec; remember (a ?= b)%positive as Cab.\n    destruct Cab; simpl.\n      erewrite (Pcompare_Eq_eq a b); [ ring | ]; auto.\n      rewrite IPR_sub; [ ring | ]; apply ZC2; symmetry; assumption.\n      rewrite IPR_sub; [ ring | ]; auto.\n    \n    rewrite Z.pos_sub_spec; remember (b ?= a)%positive as Cab.\n    destruct Cab; simpl.\n      erewrite (Pcompare_Eq_eq b a); [ ring | ]; auto.\n      rewrite IPR_sub; [ ring | ]; apply ZC2; symmetry; assumption.\n      rewrite IPR_sub; [ ring | ]; auto.\n    \n    rewrite IPR_add; ring.\nQed.\n\nLemma IZR_sub : forall x y, IZR (x - y) == IZR x - IZR y.\nProof.\n  intros a b.\n  unfold Zminus, Rsub.\n  rewrite IZR_add, IZR_Zopp.\n  reflexivity.\nQed.\n\nLemma IZR_lt : forall x y, (x < y)%Z -> IZR x < IZR y.\nProof.\n  intros x y xy.\n  apply Radd_lt_cancel_l with (-IZR x).\n  eapply Req_lt_compat_l; [ apply Radd_comm | ].\n  eapply Req_lt_compat_l; [ symmetry; apply Radd_opp_r | ].\n  eapply Req_lt_compat_r; [ apply Radd_comm | ].\n  eapply Req_lt_compat_r.\n    rewrite <- IZR_Zopp, <- IZR_add; reflexivity.\n    \n    remember (y + - x)%Z as d.\n    assert (dp : (0 < d)%Z) by omega.\n    destruct d; try inversion dp.\n    simpl.\n    apply Rpos_IPR.\nQed.\n\nLemma IZR_le : forall x y, (x <= y)%Z -> IZR x <= IZR y.\nProof.\n  intros x y xy.\n  destruct (Z_le_lt_eq_dec _ _ xy).\n  left; apply IZR_lt; auto.\n  right; subst; apply Req_refl.\nQed.\n\nLemma IPR_mul : forall a b, IPR (a * b) == IPR a * IPR b.\nProof.\n  induction a.\n   simpl. intros. rewrite (IPR_add b ((a * b)~0)). simpl. rewrite IHa. now ring.\n   \n   intros. simpl. rewrite IHa. now ring.\n   \n   intros. simpl. ring.\nQed.\n\nLemma IZR_mul : forall a b, IZR (a * b) == IZR a * IZR b.\nProof.\n  intros [ | p | p ] [ | q | q ]; simpl; try rewrite IPR_mul; ring.\nQed.\n\nLemma IZR_eq : forall a b, a = b -> IZR a == IZR b.\nProof.\n  intros; subst; reflexivity.\nQed.\n\nLtac IZRify :=\n  replace R1 with (IZR 1) by reflexivity;\n  replace R0 with (IZR 0) by reflexivity;\n  repeat\n    (rewrite <- IZR_add ||\n    rewrite <- IZR_sub ||\n    rewrite <- IZR_mul ||\n    rewrite <- IZR_opp);\n  apply IZR_eq || apply IZR_lt || apply IZR_le || idtac.\n\nLtac eq_lt_compat_r_tac t := eapply Req_lt_compat_r; [ t; reflexivity | ].\nLtac eq_lt_compat_l_tac t := eapply Req_lt_compat_l; [ t; reflexivity | ].\nLtac eq_le_compat_r_tac t := eapply Req_le_compat_r; [ t; reflexivity | ].\nLtac eq_le_compat_l_tac t := eapply Req_le_compat_l; [ t; reflexivity | ].\nLtac eq_eq_compat_l_tac t := eapply Req_trans; [ symmetry; t; reflexivity | ].\nLtac eq_eq_compat_r_tac t := symmetry; eapply Req_trans; [ symmetry; t; reflexivity | ]; symmetry.\n\nLtac eq_compat_l_tac t := match goal with\n  | |- _ == _ => eq_eq_compat_l_tac t\n  | |- _ <  _ => eq_lt_compat_l_tac t\n  | |- _ <= _ => eq_le_compat_l_tac t end.\n\nLtac eq_compat_r_tac t := match goal with\n  | |- _ == _ => eq_eq_compat_r_tac t\n  | |- _ <  _ => eq_lt_compat_r_tac t\n  | |- _ <= _ => eq_le_compat_r_tac t end.\n\nLtac IZRrel :=\n  eq_compat_r_tac IZRify;\n  eq_compat_l_tac IZRify;\n  match goal with\n  | |- _ == _ => try apply IZR_eq\n  | |- _ <= _ => try apply IZR_le\n  | |- _ <  _ => try apply IZR_lt\n  end; try omega.\n\nEnd IZR.\n", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/src/Fresh/Reals/IZR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357632379241, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.6854180496527854}}
{"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", "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/Binomial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.6854180424907207}}
{"text": "Require Import Bool.\n \n(*Load Arith.*)\nRequire Import Arith.\nRequire Import Mult.\nRequire Import List.\nRequire Import Logic.\n\nSet Implicit Arguments.\nDefinition Alphabet := nat.\nInductive Fin : nat -> Type :=\n| f0 : forall n, Fin (S n)\n| fs : forall n, Fin n -> Fin (S n).\n\nLemma fin_isnotzero : forall (n:nat), Fin n -> match n with \n                                   | 0 => False\n                                   | _ => True\n                                       end.\nintros.\ninduction H.\nsplit.\nsplit.\nQed.\n\nLemma fin0empty : Fin 0 -> False.\nintro.\napply(fin_isnotzero H).\nQed.\n\n(**  * Coproducts : *)\nDefinition addfin : forall (m n : nat) , Fin m + Fin n -> Fin (m+n).\nintros.\ndestruct H.\ninduction f.\nsimpl.\napply (f0 (n0+ n)).\nsimpl.\napply (f0 (n0+n)).\nsimpl.\ninduction n.\napply fin0empty in f.\ndestruct f.\nsimpl.\nassert(m+S n = S(m+n)).\nauto.\nrewrite H.\napply (f0 (m+n)).\n\nDefined.\n\n\n\nDefinition addfin1 : forall (m n : nat), Fin (m+n) -> Fin m + Fin n.\ninduction n.\nintros.\nsimpl.\nassert(  m + 0 = m).\nauto with arith.\nrewrite H0 in H.\ntauto.\n\n(*\nexact(inl H). *)\nintros.\nCheck (f0 n).\nsimpl in *.\nassert(m+S n = S(m+n)).\nauto.\n\nrewrite H0 in H.\nassert (Fin (S n)).\napply (f0 n).\nCheck inr.\ntauto.\n\n(*\n\napply (inr (H1)). *)\nDefined. \n\nDefinition isoadd1 : forall (m n :nat),\n    (Fin m + Fin n -> Fin (m+n)) -> (Fin (m+n) -> Fin m+ Fin n) -> (Fin m+ Fin n -> Fin m + Fin n).\n\nintros.\napply H0.\napply H.\nassumption.\nQed.\n\n\nDefinition isoadd2: forall (m n:nat),\n  (Fin (m+n) -> Fin m + Fin n) -> (Fin m+Fin n-> Fin (m+n)) -> (Fin (m+n) -> Fin (m+n)).\nintros.\napply H0.\napply H.\nexact H1.\nQed. \n\nDefinition finl : forall (m n : nat) , Fin m -> Fin (m+n).\nintros.\ninduction n.\nsimpl.\nrewrite<- plus_n_O.\nexact H.\nsimpl.\nrewrite<-plus_n_Sm.\nexact (fs IHn).\nDefined.\nDefinition finr : forall ( m n : nat), Fin n -> Fin (m+n).\nintros.\ninduction m.\nsimpl.\nexact H.\nsimpl.\napply (fs IHm).\nDefined.\n\n  Inductive FinPlus ( m n: nat) : Fin (m + n) -> Set:=\n         | fsinl : forall i: Fin m , (FinPlus m n (finl n i))\n         | fsinr : forall j: Fin n, FinPlus m n (finr m j) .\n\nPrint FinPlus.\n\n\n(** * Products *)\nDefinition fst : forall (m n : nat) , Fin (m*n)-> Fin m.\nintros.\ninduction m.\nrewrite mult_0_l in H.\nexact H.\nsimpl in H.\nexact (f0 m).\nDefined.\n\nDefinition snd: forall (m n : nat) , Fin (m*n) -> Fin n.\nintros.\ninduction n.\nrewrite  mult_0_r in H.\nassumption.\nexact (f0 n).\nDefined.\nPrint fst.\nPrint snd.\nDefinition timesfin : forall (m n : nat) , Fin m * Fin n -> Fin (m*n) .\n\nintros.\ndestruct H.\n\ninduction m.\n\nrewrite mult_0_l .\nexact f.\nsimpl.\napply finl.\nexact f1.\nDefined.\n\nDefinition timesfin1: forall (n m : nat) , Fin (m*n) -> Fin m * Fin n.\ninduction n.\nsimpl.\nsimpl.\nintro.\nassert(m*0 =0).\nauto with arith.\nrewrite H.\nintro.\napply fin0empty in H0.\ndestruct H0.\nintros.\nassert(Fin m).\napply (fst  m (S n)).\nexact H.\nShow Proof.\nintuition.\nShow Proof.\napply (snd m (S n)).\nexact H.\nDefined.\n\nDefinition isomul1 : forall (m n: nat),\n   (Fin m * Fin n -> Fin (m*n)) -> (Fin (m*n) -> Fin m * Fin n) -> (Fin m * Fin n -> Fin m * Fin n).\n\nintros.\napply H0.\napply H.\nexact H1.\nQed.\n\nDefinition isomul2 : forall (m n : nat),\n   (Fin (m*n) ->Fin m * Fin n) -> (Fin m * Fin n -> Fin (m*n)) -> (Fin (m*n) -> Fin (m*n)).\nintros.\napply H0.\napply H.\nexact H1.\nQed.\n\n\nDefinition fincase : forall (m n p: nat) , (Fin m -> Fin p) -> (Fin n -> Fin p ) ->(Fin (m+n) -> Fin p). \n\nintros.\napply addfin1 in H1.\ndestruct H1.\napply H.\nexact f.\napply H0.\nexact f.\nDefined.\n\n(** Function composition *)\nLemma comp : forall (m n p :nat) , (Fin m ->Fin m + Fin n) -> (Fin m+ Fin n -> Fin p) ->\n         (Fin m -> Fin p).\nintros m n p in1 fg f.\napply fg.\napply in1.\nexact f.\nDefined.\n\n  \n\nLemma comp1 : forall (m n p:nat), (Fin n ->Fin m + Fin n) ->\n    (Fin m+ Fin n-> Fin p) -> (Fin n -> Fin p).\nintros m n p in2 fg g.\napply fg.\napply in2.\nexact g.\nDefined.\n\n(** Distributivity law *)\nDefinition dist: \n       forall (m n p :nat), Fin ( m * ( n+ p)) -> Fin ( m* n + m * p).\ninduction m.\nintros.\nsimpl in *.\napply fin0empty in H.\ndestruct H.\nintros.\n\napply addfin.\nrewrite mult_plus_distr_l in H.\napply addfin1 in H.\nassumption.\nDefined.\n\nDefinition dist2 :\n    forall (m n p : nat), Fin (m * n + m* p ) -> Fin (m * (n + p)).\ninduction m.\nintros.\nsimpl in *.\napply fin0empty in H.\ndestruct H.\nintros.\napply addfin1 in H.\nrewrite mult_plus_distr_l.\napply addfin.\nassumption.\nQed.\n\n(*\n Lemma fin_inl_inject : forall (n m : nat) (i j : Fin n), \n       finl m i = finl m j -> i = j.\ninduction i.\nintros.\n\nsimpl in *.\nassert( Fin (S n)).\n\napply (f0 n).\n\nadmit.\nintros.\nassert ( Fin ( m) -> Fin (m + ( n))).\napply (f0 n) .\ninduction H.\n\ndiscriminate H.\nLemma finlinj : forall (m n : nat) (i j : Fin n), \n       finl m i = finl n j -> i = j.\n\n\n\n\n\n*)\n\n\nFixpoint exps  (x n :nat):nat :=\n\n       match n with \n       | 0  => 1 \n       | S n' =>   mult x (exps x n') \n       end.\nEval compute in (exps 3 2).\n\nNotation \" x ^ y \" := (exps x y). \nEval compute in (0 ^9).\n\nDefinition existsf1   (n:nat)(p:Fin n -> bool) : bool.\ninduction n .\nexact false.\nexact( p (f0 n) || IHn (fun m : Fin n => p (fs m))).\nDefined.\nPrint existsf1.\nCheck In.\n\n\n(** Here, we prove the correctness of the existsf1 predicate , by evaluating it to the value\nof the exists quantifier in coq. we will also use proving by contradiction, as well as case analysis,\ndue to the disjunction [p(f0 n) || IHn (fun m : Fin n => p(fs m))] *)\n\n\nLemma exss : forall (n:nat)(p:Fin n -> bool), existsf1 p = true -> exists q:Fin n , p q =true.\nintros.\ninduction n.\nsimpl.\nsimpl in H.\ndiscriminate H.\nsimpl in  H.\n\n\ncase_eq ( p (f0 n)).\nintro.\nexists( f0 (n)).\nexact H0.\nintro.\nrewrite H0 in H.\nsimpl in H.\napply IHn in H.\ndestruct H.\nexists (fs x).\nexact H.\nQed.\n\n\nLemma exs : forall (n:nat)(p:Fin n -> bool),(exists q :Fin n, p q = true) ->  existsf1 p = true.\nintros.\ndestruct H.\nsimpl.\ninduction x.\nsimpl.\nrewrite H.\nsimpl.\nreflexivity.\n\ncase_eq (p (f0 n)).\nintro.\nsimpl.\nrewrite H0.\nsimpl.\nreflexivity.\nintro.\nsimpl.\nrewrite H0.\nsimpl.\napply IHx.\nexact H.\nQed.\n(*\n\nDefinition isoex1 :forall (n:nat) (p:Fin n -> bool) *)\n(*Definition isoex1 : forall (n : nat)(p : Fin n -> bool)(x: exists q:Fin n , p q = true) ,\n\n   exss  p (exs p x) =x.\nintros.\nsimpl in *.\nset (exs p x ).\nset (exss p e).\n\nassert(existsf1 p =true -> exists q:Fin n , p q =true).\nintros.\nexact x.\nassert((exists q :Fin n , p q =true) -> existsf1 p = true).\nintros.\napply e.\nset(exss p e).\nintuition.\nrewrite H0 in x.\nrewrite e0 in x. \n\n\n\nassert( exss p (exs p x) = exists q :Fin n , p q =true).\nintros.\nDefinition isoex1 : forall (n:nat)(p:Fin n -> bool) ,\n\n   (existsf1 p =true -> exists q:Fin n , p q =true) ->\n\n  ((exists q:Fin n , p q = true) -> existsf1 p =true) -> (existsf1 p = true -> existsf1 p = true).\nintros.\n\ntrivial.\n\napply H0.\n\n\nintros.\nsimpl in *.\n\n\n\n*)\n\n\n    \n       \n            \n(*We eill prove the isomorphism between tha fact that in our proof we can feed into 2 finite \nsets [(Fin m -> Fin n)] and obtain a new finite set with cardinality [Fin (n^m)]\n\n*)\n\n\nDefinition  allexp : forall(m n :nat) , (Fin m -> Fin n ) -> Fin ( n^m).\nintros.\ninduction m.\n\nsimpl.\nexact (f0 (pred 0)).\n(*base case *)\nsimpl.\neapply timesfin.\n(*use the definition of the product Fin m *FIn n -> Fin (m*n)*)\nsimpl.\ninduction n.\nsimpl.\napply timesfin1.\nsimpl.\napply H.\nexact (f0 m).\napply timesfin1.\nsimpl.\napply finl.\napply IHm.\nintro.\napply H.\nexact (f0 m).\nDefined. \nPrint allexp.\n\nDefinition es : forall (a b : nat) , Fin (b^a) -> (Fin a -> Fin b ).\nintros.\nsimpl.\ninduction a.\napply fin0empty in H0.\ndestruct H0.\nsimpl in H.\napply timesfin1 in H.\ndestruct H.\nexact f.\nDefined.\n\n(*Define an isomorphism between a predicate which contains n elements and the finite set with 2^n elements.\nThis is used when generating the power automaton. We will apply the lemmas that we have done before. *)\n\nDefinition allexp1 : forall (n : nat) , (Fin n -> bool) -> Fin (2^n).\nintros.\napply allexp.\nintro.\nexact (f0 1).\nDefined.\n\nDefinition allexp2 : forall (n : nat) , Fin (2^n) -> (Fin n -> bool).\nintros.\napply (es  2) in H.\nexact true.\napply allexp.\nintro.\nexact (f0 1).\nDefined.\n\n\n\nFixpoint equalsf (n m:nat) (p :Fin n) (q: Fin m) : bool := \n    match p with\n | f0 _ => match q with \n          | f0 _ => true\n          | _ => false\n          end\n | fs _ p' => match q with \n           | f0 _ => false\n           | fs _ q' =>  equalsf p' q' \n         end\n      end.\nPrint equalsf.\n\nDefinition eqf (n : nat) (p q : Fin n) : bool := equalsf p q.  \n\nDefinition eqftoprop (n:nat)(p q :Fin n) : Prop := \n       match eqf p q with \n     | true => True\n     | false => False\n     end.\n(** Apply a finite set case analysis taking 2 functions and check whether is there the element for the [Fin m],\n\nor the element from [Fin n] , that will be selected. From mapping two functions, \n[Fin m -> Fin p] and [Fin n -> Fin p] is a way of \"choosing\" and therefore we need to use a set\nthat has cardinality m+n, and see if it will be mapped on Fin p.\n\n*)\n\nDefinition finmn : forall (m n :nat), (Fin m + Fin n -> bool ) -> Fin (m+n) -> bool.\nintros.\napply H.\napply addfin1 in H0.\nassumption.\nDefined.\nDefinition finsum : forall (m n :nat),  Fin m ->  Fin n -> Fin m + Fin n.\nintros.\ninduction m.\napply fin0empty in H.\ndestruct H.\napply (inl H).\nDefined.\n\n\nDefinition finbool :forall (m n :nat), (Fin m -> bool) -> (Fin n -> bool) ->\n          Fin (m+n) -> bool.\nintros.\ninduction m.\nsimpl in *.\nexact true.\napply H.\nexact (f0 m).\n(*\napply IHm.\nintro.\napply H.\nexact (f0 m).\napply addfin1 in H1.\nadmit.*)\nDefined.\n\n \nDefinition finmbool : forall (a:Alphabet) (m n: nat), \n   (Fin m -> bool) -> (Fin (m+n) -> bool).\nintros.\ninduction m.\nexact false.\napply H.\nexact (f0 m).\n\nQed.\nDefinition finpp : forall (a:Alphabet)(m n :nat),\n  (Fin m -> Fin a -> Fin (2^m)) ->\n      (Fin n -> Fin a -> Fin (2^n)) ->\n      Fin (2^ (m+n)).\nintros.\napply allexp1.\nintro.\napply addfin1 in H1.\ninduction m.\nsimpl in H1.\nexact false.\napply IHm.\nintros.\napply allexp1.\nintro.\nexact true.\nintuition.\napply addfin1.\nadmit.\nQed.\n\n\n\n(*\nDefinition finpp : forall (a:Alphabet)(m n : nat),\n   (Fin m-> Fin a -> Fin (2^m)) ->( Fin n -> Fin a -> Fin (2^n)) ->\n   Fin (2 ^m + 2 ^n). \nintros.\n\ninduction m.\nsimpl.\nexact (f0 (2^n)).\ninduction n.\nsimpl .\nsimpl in *.\nsimpl.\nsimpl.\nadmit.\n\n\n\nintros.\nsimpl.\ninduction n.\nsimpl.\nassert (2^m+1 = S(2^m)).\nadmit.\nrewrite H1.\nexact (f0 (2^m)).\nsimpl.\ninduction m.\nsimpl.\nexact (f0 (add (2^n) (add (2^n) 0))).\nsimpl.\n\n\n*)\n", "meta": {"author": "radu07", "repo": "automat", "sha": "5d8c4ec7414025cb83ec094e45e09a7cd1d607da", "save_path": "github-repos/coq/radu07-automat", "path": "github-repos/coq/radu07-automat/automat-5d8c4ec7414025cb83ec094e45e09a7cd1d607da/autofin_new/Finitesets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6853757918948035}}
{"text": "(* Exercise 25 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_025 : ~(forall x, P x /\\ Q x) /\\ (forall x, P x) -> ~(forall x, Q x).\nProof.\nimp_i a1.\nneg_i (forall x:D, P x /\\ Q x) a2.\ncon_e1 (forall x:D, P x).\nhyp a1.\nall_i a.\ncon_i.\nall_e (forall x:D, P x) a.\ncon_e2 (~(forall x:D, P x /\\ Q x)).\nhyp a1.\nall_e (forall x:D, Q x) a.\nhyp a2.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred025.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6853406136041977}}
{"text": "From AlphaPearl Require Import Util.Nat Util.PlfTactics.\nFrom Coq Require Import Bool List ssreflect.\nImport ListNotations.\nFrom mathcomp Require Import bigop eqtype seq ssrbool ssrnat.\n\nSet Asymmetric Patterns.\nSet Bullet Behavior \"Strict Subproofs\".\nSet Implicit Arguments.\nUnset Printing Implicit Defensive.\n\n#[local] Open Scope list_scope.\n\nNotation \"x '∈' y\" := (x \\in y) (at level 70).\n\nNotation \"x '∉' y\" := (x \\notin y) (at level 70).\n\n(* Note that, at least for now, [maximum nil = 0]. *)\nDefinition maximum : list nat -> nat := foldr maxn 0.\n\nLemma maximum_correct : forall (l : list nat) (x : nat), x ∈ l -> x <= maximum l.\nProof.\n  induction l; intros.\n  { inverts H. }\n  rewrite /= leq_max.\n  rewrite in_cons in H. apply (rwP orP) in H as [].\n  - apply (rwP eqP) in H. subst. rewrite leqnn //.\n  - apply IHl in H. rewrite H orbT //.\nQed.\n\nLemma maxE r : maximum r = \\max_(i <- r) i. Proof. exact: foldrE. Qed.\n\nLemma bigmax_subset :\n  forall sub super : seq nat,\n    {subset sub <= super} ->\n    \\max_(x <- sub) x <= \\max_(x <- super) x.\nProof.\n  intros.\n  gen super. induction sub; intros; simpl in *.\n  - rewrite big_nil //.\n  - rewrite big_cons.\n    assert (a ∈ a :: sub). { rewrite in_cons eq_refl //. }\n    apply H in H0.\n    rewrite geq_max -{1}maxE maximum_correct //.\n    apply IHsub. intros_all.\n    apply H. rewrite in_cons.\n    destruct (x =P a); subst; auto.\nQed.\n\nLemma S_bigmax :\n  forall s : seq nat,\n    \\max_(x <- s) S x <= S (\\max_(x <- s) x).\nProof.\n  intros.\n  induction s.\n  { rewrite !big_nil //. }\n  rewrite !big_cons -!maxnSS geq_max leq_max leqnn leq_max IHs orbT //.\nQed.\n\nLemma maximum_in :\n  forall l : seq nat,\n    l = nil \\/ maximum l ∈ l.\nProof.\n  intros.\n  induction l; auto.\n  right.\n  rewrite in_cons.\n  destruct IHl as [IHl|IHl]; subst.\n  - rewrite eq_refl //.\n  - destruct (maxn_either a (maximum l)) as [Hmax|Hmax]; rewrite /= Hmax.\n    + rewrite eq_refl //.\n    + rewrite IHl orbT //.\nQed.\n\nLemma maximum_leq :\n  forall l1 l2 : seq nat,\n    (forall n, n ∈ l1 -> n <= maximum l2) ->\n      maximum l1 <= maximum l2.\nProof.\n  introv Hl12.\n  induction l1; auto.\n  rewrite /= geq_max -(rwP andP). split.\n  - rewrite Hl12 // mem_head //.\n  - apply IHl1. introv Hn.\n    rewrite Hl12 // in_cons Hn orbT //.\nQed.\n", "meta": {"author": "jgrosso", "repo": "coq-alpha-pearl", "sha": "1d0e55543bee26a0d403f5e095d1c58bf244c527", "save_path": "github-repos/coq/jgrosso-coq-alpha-pearl", "path": "github-repos/coq/jgrosso-coq-alpha-pearl/coq-alpha-pearl-1d0e55543bee26a0d403f5e095d1c58bf244c527/theories/Util/Seq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.6852934858630799}}
{"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 Rbase Rbasic_fun ROrderedType GenericMinMax.\n\n(** * Maximum and Minimum of two real numbers *)\n\nLocal Open Scope R_scope.\n\n(** The functions [Rmax] and [Rmin] implement indeed\n    a maximum and a minimum *)\n\nLemma Rmax_l : forall x y, y<=x -> Rmax x y = x.\nProof.\n unfold Rmax. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nLemma Rmax_r : forall x y, x<=y -> Rmax x y = y.\nProof.\n unfold Rmax. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nLemma Rmin_l : forall x y, x<=y -> Rmin x y = x.\nProof.\n unfold Rmin. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nLemma Rmin_r : forall x y, y<=x -> Rmin x y = y.\nProof.\n unfold Rmin. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nModule RHasMinMax <: HasMinMax R_as_OT.\n Definition max := Rmax.\n Definition min := Rmin.\n Definition max_l := Rmax_l.\n Definition max_r := Rmax_r.\n Definition min_l := Rmin_l.\n Definition min_r := Rmin_r.\nEnd RHasMinMax.\n\nModule R.\n\n(** We obtain hence all the generic properties of max and min. *)\n\nInclude UsualMinMaxProperties R_as_OT RHasMinMax.\n\n(** * Properties specific to the [R] domain *)\n\n(** Compatibilities (consequences of monotonicity) *)\n\nLemma plus_max_distr_l : forall n m p, Rmax (p + n) (p + m) = p + Rmax n m.\nProof.\n intros. apply max_monotone.\n intros x y. apply Rplus_le_compat_l.\nQed.\n\nLemma plus_max_distr_r : forall n m p, Rmax (n + p) (m + p) = Rmax n m + p.\nProof.\n intros. rewrite (Rplus_comm n p), (Rplus_comm m p), (Rplus_comm _ p).\n apply plus_max_distr_l.\nQed.\n\nLemma plus_min_distr_l : forall n m p, Rmin (p + n) (p + m) = p + Rmin n m.\nProof.\n intros. apply min_monotone.\n intros x y. apply Rplus_le_compat_l.\nQed.\n\nLemma plus_min_distr_r : forall n m p, Rmin (n + p) (m + p) = Rmin n m + p.\nProof.\n intros. rewrite (Rplus_comm n p), (Rplus_comm m p), (Rplus_comm _ p).\n apply plus_min_distr_l.\nQed.\n\n(** Anti-monotonicity swaps the role of [min] and [max] *)\n\nLemma opp_max_distr : forall n m : R, -(Rmax n m) = Rmin (- n) (- m).\nProof.\n intros. symmetry. apply min_max_antimonotone.\n do 3 red. intros; apply Rge_le. apply Ropp_le_ge_contravar; auto.\nQed.\n\nLemma opp_min_distr : forall n m : R, - (Rmin n m) = Rmax (- n) (- m).\nProof.\n intros. symmetry. apply max_min_antimonotone.\n do 3 red. intros; apply Rge_le. apply Ropp_le_ge_contravar; auto.\nQed.\n\nLemma minus_max_distr_l : forall n m p, Rmax (p - n) (p - m) = p - Rmin n m.\nProof.\n unfold Rminus. intros. rewrite opp_min_distr. apply plus_max_distr_l.\nQed.\n\nLemma minus_max_distr_r : forall n m p, Rmax (n - p) (m - p) = Rmax n m - p.\nProof.\n unfold Rminus. intros. apply plus_max_distr_r.\nQed.\n\nLemma minus_min_distr_l : forall n m p, Rmin (p - n) (p - m) = p - Rmax n m.\nProof.\n unfold Rminus. intros. rewrite opp_max_distr. apply plus_min_distr_l.\nQed.\n\nLemma minus_min_distr_r : forall n m p, Rmin (n - p) (m - p) = Rmin n m - p.\nProof.\n unfold Rminus. intros. apply plus_min_distr_r.\nQed.\n\nEnd R.\n", "meta": {"author": "JasonGross", "repo": "category-coq-experience-tests", "sha": "f9949ede618788fd051fe8327f997ee683388e49", "save_path": "github-repos/coq/JasonGross-category-coq-experience-tests", "path": "github-repos/coq/JasonGross-category-coq-experience-tests/category-coq-experience-tests-f9949ede618788fd051fe8327f997ee683388e49/coq/coq-8.3pl5-foundations/theories/Reals/Rminmax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.6852731703965407}}
{"text": "Notation add := ((fun m n x y => m x (n x y))).\nNotation time := ((fun m n x y => m (n x) y)).\nNotation two := (fun s n => s (s n)).\nNotation thr := (fun s n => s (s (s n))).\nCompute (add two thr S O) (*=> 5*).\nCompute (time two thr S O) (*=> 6*).\n\nFixpoint fn_walk n (s: nat -> nat) z :=\n  match n with\n  | O => z\n  | S n' => s (fn_walk n' s z)\n  end.\n\nDefinition fun_nat n :=\n  (fun s z => fn_walk n s z).\n\nLemma fun_nat_correct : forall n,\n    fun_nat n S O = n.\nProof.\n  induction n; simpl; auto.\nQed.\n\nNotation adds n1 n2 := (add (fun_nat n1) (fun_nat n2)).\nNotation times n1 n2 := (time (fun_nat n1) (fun_nat n2)).\n\nLemma add_correct : forall n m,\n    adds n m = fun_nat (n + m).\nProof.\n  unfold fun_nat; induction n; simpl; intros; auto.\n  rewrite <- IHn. reflexivity.\nQed.\n\nTheorem time_correct : forall n1 n2,\n    times n1 n2 = fun_nat (n1 * n2).\nProof.\n  induction n1; simpl; auto; intros.\n  rewrite <- add_correct. rewrite <- IHn1.\n  reflexivity.\nQed.\n\n\nFixpoint walk {A: Type} n (s: A -> A) z :=\n  match n with\n  | O => z\n  | S n' => s (walk n' s z)\n  end.\n\nDefinition fun_nat2 {A: Type} n :=\n  (fun (s: A -> A) z => walk n s z).\n\nNotation power := ((fun m n x y => n m x y)).\nNotation powers n1 n2 := (power (fun_nat2 n1)(fun_nat2 n2)).\nCompute (power two thr S O).\n\nFixpoint pow n1 n2 :=\n  match n2 with\n  | 0 => 1\n  | S n => n1 * (pow n1 n)\n  end.\nCompute (pow 3 2).\nCompute (pow 2 3).\n\nLemma pow_m_sn : forall n m,\n    pow m (S n) = m * (pow m n).\nProof.\n  induction n; simpl; intros; auto.\nQed.\n\nLemma walk__ : forall n,\n    walk n = fn_walk n.\nProof.\n  induction n; simpl; auto.\n  rewrite IHn. reflexivity.\nQed.\n\nLemma fun_nat12 : forall n,\n    fun_nat n = fun_nat2 n.\nProof.\n  unfold fun_nat, fun_nat2.\n  intros. rewrite walk__. reflexivity.\nQed.\n\nTheorem power_correct: forall n2 n1,\n    powers n1 n2 = fun_nat (pow n1 n2).\nProof.\n  induction n2; simpl; intros; auto.\n  rewrite IHn2. rewrite <- time_correct. rewrite <- fun_nat12. reflexivity.\nQed.\n\nTheorem power2 : forall n2 n1,\n    fun_nat2 (pow n1 n2) = ((fun_nat2 n2) (time (fun_nat n1)) (fun_nat 1)).\nProof.\n  induction n2; intros; simpl; auto.\n  rewrite <- IHn2. repeat rewrite <- fun_nat12. rewrite time_correct. reflexivity.\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/homework/time_pow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604134, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.685273154550473}}
{"text": "Inductive listn : nat -> Set :=\n  | niln : listn 0\n  | consn : forall n : nat, nat -> listn n -> listn (S n).\n\nAxiom\n  ax :\n    forall (n n' : nat) (l : listn (n + n')) (l' : listn (n' + n)),\n    existS _ (n + n') l = existS _ (n' + n) l'.\n\nLemma lem :\n forall (n n' : nat) (l : listn (n + n')) (l' : listn (n' + n)),\n n + n' = n' + n /\\ existT _ (n + n') l = existT _ (n' + n) l'.\nProof.\nintros n n' l l'.\n\n\ndependent rewrite (ax n n' l l').\n\n\nsplit; reflexivity.\nQed.", "meta": {"author": "UCL-PPLV", "repo": "inversion", "sha": "02c552dc3e3bd46186e736bf01a39dd264e72318", "save_path": "github-repos/coq/UCL-PPLV-inversion", "path": "github-repos/coq/UCL-PPLV-inversion/inversion-02c552dc3e3bd46186e736bf01a39dd264e72318/DepRewrite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6852497772382524}}
{"text": "From Coq Require Export ZArith List.\nImport ListNotations.\n\n#[global] Open Scope Z_scope.\n\nInductive cmd :=\n| forward\n| up\n| down\n.\n\nDeclare Custom Entry aoc02.\n\nNotation \"'input' x .. y\" := (cons x .. (cons y nil) ..) (at level 200, x custom aoc02, y custom aoc02, only parsing).\nNotation \"x y\" := (x, y) (in custom aoc02 at level 0, x constr at level 0, y constr at level 0).\n\nDefinition example := input\nforward 5\ndown 5\nforward 8\nup 3\ndown 8\nforward 2\n.\n\n(* Part One *)\n\nDefinition position : Type := Z * Z.\n\nDefinition eval1 (c : cmd) (n : Z) '((hpos, zpos) : position) : position :=\n  match c with\n  | forward => (hpos + n, zpos)\n  | up   => (hpos, zpos - n)\n  | down => (hpos, zpos + n)\n  end.\n\nFixpoint eval (xs : list (cmd * Z)) (current : position) : position :=\n  match xs with\n  | [] => current\n  | (c, n) :: xs => eval xs (eval1 c n current)\n  end.\n\nDefinition solve (xs : list (cmd * Z)) : Z :=\n  let '(hpos, zpos) := eval xs (0, 0) in\n  hpos * zpos.\n\n(* Compute solve example. *)\n\n(* Part Two *)\n\nDefinition position_2 : Type := Z * Z * Z.\n\nDefinition eval1_2 (c : cmd) (n : Z) '((hpos, zpos, aim) : position_2) : position_2 :=\n  match c with\n  | forward => (hpos + n, zpos + n * aim, aim)\n  | up => (hpos, zpos, aim - n)\n  | down => (hpos, zpos, aim + n)\n  end.\n\nFixpoint eval_2 (xs : list (cmd * Z)) (current : position_2) : position_2 :=\n  match xs with\n  | [] => current\n  | (c, n) :: xs => eval_2 xs (eval1_2 c n current)\n  end.\n\nDefinition solve2 (xs : list (cmd * Z)) : Z :=\n  let '(hpos, zpos, _aim) := eval_2 xs (0, 0, 0) in\n  hpos * zpos.\n\nDefinition solve12 (i : list (cmd * Z)) : Z * Z := (solve i, solve2 i).\n\n(* Compute solve2 example. *)\n\n(* The second part generalizes the first: the [aim] in Part Two plays the role of\n   depth ([zpos]) in Part One. *) \n\n(* We could prove this directly, but just to be fancy, let's make it explicit\n   that it relies on a _simulation argument_:\n   the single-step functions [eval1] and [eval1_2] preserve a relation [R] between [position]\n   and [position_2], so the iterated-step functions [eval] and [eval_2] also preserve [R]. *)\n\nLemma eval_sim : forall (R : position -> position_2 -> Prop),\n  (forall c n p p2, R p p2 -> R (eval1 c n p) (eval1_2 c n p2)) ->\n  forall xs p p2,\n  R p p2 -> R (eval xs p) (eval_2 xs p2).\nProof.\n  intros R SIM; induction xs as [ | [c n] xs IH ]; cbn.\n  - trivial.\n  - intros * H; apply IH, SIM, H.\nQed.\n\nLemma eval1_fact : forall c n hpos zpos aim,\n  eval1 c n (hpos, aim) = let '(hpos', _, aim') := eval1_2 c n (hpos, zpos, aim) in (hpos', aim').\nProof.\n  destruct c; reflexivity.\nQed.\n\nTheorem eval_fact : forall xs hpos zpos aim,\n  eval xs (hpos, aim) = let '(hpos', _, aim') := eval_2 xs (hpos, zpos, aim) in (hpos', aim').\nProof.\n  intros xs hpos zpos aim; apply eval_sim.\n  - intros c n _ [[? ?] ?] ->. apply eval1_fact.\n  - reflexivity.\nQed.\n", "meta": {"author": "Lysxia", "repo": "advent-of-coq-2021", "sha": "1416cf87898d4991fa918e8d1142f45fbde269e9", "save_path": "github-repos/coq/Lysxia-advent-of-coq-2021", "path": "github-repos/coq/Lysxia-advent-of-coq-2021/advent-of-coq-2021-1416cf87898d4991fa918e8d1142f45fbde269e9/src/aoc02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.6852458016437032}}
{"text": "Require Export Lists.\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 => O\n    | cons h t => S (length X t)\n  end.\n\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\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: rev bool (nil bool) = nil bool.\nProof. reflexivity. Qed.\n\nModule MumbleBaz.\n\n  Inductive mumble : Type :=\n    | a : mumble\n    | b : mumble -> nat -> mumble\n    | c : mumble.\n  Inductive grumble (X : Type) :=\n    | d : mumble -> grumble X\n    | e : X -> grumble X.\n\n  Inductive baz : Type :=\n    | x : baz -> baz\n    | y : baz -> bool -> baz.\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'.\nCheck app.\n\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\nArguments nil {X}.\nArguments cons {X} _ _.\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\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\nNotation \"x :: y\" := (cons x y) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y) (at level 60, right associativity).\n\nDefinition list123''' := [1;2;3].\nCheck ([3 + 4] ++ nil).\n\nFixpoint repeat {X : Type} (n : X) (count : nat) : list X :=\n  match count with\n    | O => []\n    | S n' => n :: repeat n n'\n  end.\n\nExample test_repeat1: repeat true 2 = cons true (cons true nil).\nProof. reflexivity. Qed.\n\nTheorem rev_snoc:\n  forall X : Type, forall v : X, forall s : list X,\n    rev (snoc s v) = v :: (rev s).\nProof.\n  intros X v s.\n  induction s as [| n s'].\n  Case \"s = nil\".\n  simpl. reflexivity.\n  Case \"s = cons\".\n  simpl.\n  rewrite -> IHs'.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem rev_involutive:\n  forall X : Type, forall l : list X,\n    rev (rev l) = l.\nProof.\n  intros X l.\n  induction l as [| n l'].\n  Case \"l = nil\".\n  simpl. reflexivity.\n  Case \"l = cons\".\n  simpl.\n  rewrite -> rev_snoc.\n  rewrite -> IHl'.\n  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).\nProof.\n  intros X l1 l2 v.\n  induction l1 as [| n l1'].\n  Case \"l1 = nil\".\n  simpl.  reflexivity.\n  Case \"l1 = cons\".\n  simpl.\n  rewrite -> IHl1'.\n  reflexivity.\nQed.\n\nInductive prod (X Y : Type) : Type :=\n  pair : X -> Y -> prod X Y.\n\nArguments pair {X} {Y} _ _.\n\nNotation \"( x , y )\" := (pair x y).\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.\n\nEval compute 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    | (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. reflexivity. Qed.\n\nInductive option (X : Type) : Type :=\n  | None : option X\n  | Some : X -> option X.\n\nArguments Some {X} _.\nArguments 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'\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    | nil => None\n    | x :: t => Some x\n  end.\n\nCheck hd_opt.\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.\n\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 := f (fst p) (snd p).\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry:\n  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:\n  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    | cons h t => if test h then h :: (filter test t) 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 [[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\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter evenb (filter (fun 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  ((filter test l), (filter (fun x => negb (test x)) 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    | [] => []\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: 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(* map f (snoc (rev l') n) = snoc (rev (map f l')) (f n) *)\n(*Theorem map_snoc:\n  forall (X Y : Type) (f : X -> Y) (l : list X),*)\n\nTheorem map_cons:\n  forall (X Y : Type) (f : X -> Y) (n : X) (l : list X),\n    map f (n::l) = (f n) :: map f l.\nProof.\n  intros X Y f n l.\n  simpl. reflexivity.\nQed.\n\nTheorem map_snoc:\n  forall (X Y : Type) (f : X -> Y) (n : X) (l : list X),\n   snoc (map f l) (f n) = map f (snoc l n).\nProof.\n  intros X Y f n l.\n  induction l as [| n' l'].\n  Case \"l = nil\".\n  simpl. reflexivity.\n  Case \"l = cons\".\n  simpl.\n  rewrite -> IHl'.\n  reflexivity.\nQed.\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 X Y f l.\n  induction l as [| n l'].\n  Case \"l = nil\".\n  simpl. reflexivity.\n  Case \"l = cons\".\n  simpl.\n  rewrite <- map_snoc.\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    | 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] = [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    | [] => b\n    | h :: t => f h (fold f t b)\n  end.\n\nCheck (fold andb).\n\nExample fold_example1 : fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 : fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 : fold app [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\nDefinition constfun {X : Type} (x : X) : nat -> X :=\n  fun (k : nat) => x.\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.\n\nExample override_example2 : fmostlytrue 1 = false.\nProof. reflexivity. Qed.\n\nExample override_example3 : fmostlytrue 2 = true.\nProof. reflexivity. Qed.\n\nExample override_example4 : fmostlytrue 3 = false.\nProof. reflexivity. Qed.\n\nTheorem override_example:\n  forall b : bool,\n    (override (constfun b) 3 true) 2 = b.\nProof.\n  intros b.\n  reflexivity.\nQed.\n\nTheorem unfold_example_bad:\n  forall m n,\n    3 + n = m -> plus3 n + 1 = m + 1.\nProof.\n  intros m n H.\nAbort.\n\nTheorem unfold_example:\n  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:\n  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.\nQed.\n\nTheorem override_neq:\n  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.\n  intros H I.\n  unfold override.\n  rewrite -> I.\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:\n  forall X (l : list X),\n    fold_length l = length l.\nProof.\n  intros X l.\n  induction l as [| n l'].\n  Case \"l = nil\".\n  simpl. reflexivity.\n  Case \"l = cons\".\n  unfold fold_length.\n  simpl.\n  rewrite <- IHl'.\n  unfold fold_length.\n  reflexivity.\nQed.\n\nDefinition fold_map {X Y:Type} (f : X -> Y) (l : list X) : list Y :=\n  fold (fun x => cons (f x)) l [].\n\nExample test_fold_map: fold_map (plus 3) [1;2;3] = [4;5;6].\nProof. reflexivity. Qed.\n\nTheorem eq_map_fold_map:\n  forall (X Y : Type) (f : X -> Y) (l : list X),\n    map f l = fold_map f l.\nProof.\n  intros X Y f l.\n  induction l as [| n l'].\n  Case \"l = nil\".\n  simpl. reflexivity.\n  Case \"l = cons\".\n  simpl.\n  unfold fold_map.\n  simpl.\n  rewrite -> IHl'.\n  unfold fold_map.\n  reflexivity.\nQed.\n", "meta": {"author": "abm", "repo": "software-foundations", "sha": "fcc4a39b688893ffd1744bff851590d28ddf8d68", "save_path": "github-repos/coq/abm-software-foundations", "path": "github-repos/coq/abm-software-foundations/software-foundations-fcc4a39b688893ffd1744bff851590d28ddf8d68/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.6852457966075708}}
{"text": "Set Implicit Arguments.\nRequire Import FunctionalExtensionality.\nRequire Import DblibTactics.\nRequire Import DeBruijn.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Environments map variables to data. *)\n\n(* Environments are homogeneous -- there is only one kind of variables --\n   and non-dependent -- variables do not occur within data. *)\n\n(* We represent environments as functions of type [nat -> option A], as\n   opposed to lists of type [list A], because functions are slightly more\n   pleasant to work with than lists. In particular, their domain need not\n   be contiguous, and this makes the definition of insertion more natural. *)\n\nDefinition env A :=\n  nat -> option A.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Operations on environments. *)\n\n(* The empty environment is undefined everywhere. *)\n\nDefinition empty A : env A :=\n  fun y => None.\n\n(* Environment lookup is just function application. *)\n\nDefinition lookup A (x : nat) (e : env A) : option A :=\n  e x.\n\n(* [insert x a e] inserts a new variable [x], associated with data [a], in the\n   environment [e]. The pre-existing environment entries at index [x] and\n   above are shifted up. Thus, [insert x] is closely analogous to [shift x]\n   for terms. *)\n\nDefinition insert A (x : nat) (a : A) (e : env A) : env A :=\n  fun y =>\n    match lt_eq_lt_dec x y with\n    | inleft (left _)  (* x < y *) => e (y - 1)\n    | inleft (right _) (* x = y *) => Some a\n    | inright _        (* x > y *) => e y\n    end.\n\n(* [remove x] is the inverse of [insert x a]. That is, [remove x e] destroys\n   the variable [x] in the environment [e]. The variables at index [x + 1]\n   and above are shifted down. Thus, [remove x] is closely analogous to\n   [subst v x] for terms. *)\n\n(* Experience suggests that it is good style to always work with [insert]\n   and avoid using [remove]. This leads to simpler goals and proofs. *)\n\nDefinition remove A (x : nat) (e : env A) : env A :=\n  fun y =>\n    match le_gt_dec x y with\n    | left _  (* x <= y *) => e (1 + y)\n    | right _ (* x > y *)  => e y\n    end.\n\n(* [map f e] is the environment obtained by applying [f] to every datum\n   in the environment [e]. *)\n\nDefinition map A (f : A -> A) (e : env A) :=\n  fun y =>\n    match e y with\n    | None   => None\n    | Some a => Some (f a)\n    end.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Basic arithmetic simplifications. *)\n\nLemma one_plus_x_minus_one_left:\n  forall x,\n  (1 + x) - 1 = x.\nProof.\n  intros. omega.\nQed.\n\nLemma one_plus_x_minus_one_right:\n  forall x,\n  x > 0 ->\n  1 + (x - 1) = x.\nProof.\n  intros. omega.\nQed.\n\nLtac one_plus_x_minus_one :=\n  repeat rewrite one_plus_x_minus_one_left;\n  repeat rewrite one_plus_x_minus_one_right by omega.\n  (* I tried [autorewrite with ... using omega]; it does not work. *)\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Interaction between [lookup] and [empty]. *)\n\nLemma lookup_empty_None:\n  forall A x,\n  lookup x (@empty A) = None.\nProof.\n  unfold lookup, empty. reflexivity.\nQed.\n\nLemma lookup_empty_Some:\n  forall A x (a : A),\n  lookup x (@empty _) = Some a ->\n  False.\nProof.\n  unfold lookup, empty. intros. congruence.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Interaction between [lookup] and [insert]. *)\n\nLemma lookup_insert_bingo:\n  forall A x y (a : A) e,\n  x = y ->\n  lookup x (insert y a e) = Some a.\nProof.\n  intros. subst. unfold lookup, insert. dblib_by_cases. reflexivity.\nQed.\n\nLemma lookup_insert_recent:\n  forall A x y (a : A) e,\n  x < y ->\n  lookup x (insert y a e) = lookup x e.\nProof.\n  intros. unfold lookup, insert. dblib_by_cases. reflexivity.\nQed.\n\nLemma lookup_insert_old:\n  forall A x y (a : A) e,\n  x > y ->\n  lookup x (insert y a e) = lookup (x - 1) e.\nProof.\n  intros. unfold lookup, insert. dblib_by_cases. reflexivity.\nQed.\n\nLemma lookup_shift_insert:\n  forall A x y (a : A) e,\n  lookup (shift y x) (insert y a e) = lookup x e.\nProof.\n  intros. destruct_lift_idx.\n  rewrite lookup_insert_old by omega. f_equal. omega.\n  rewrite lookup_insert_recent by omega. reflexivity.\nQed.\n\nLtac lookup_insert :=\n  first [\n    rewrite lookup_insert_bingo by omega\n  | rewrite lookup_insert_old by omega; one_plus_x_minus_one\n  | rewrite lookup_insert_recent by omega\n  | rewrite lookup_shift_insert\n  ].\n\nLtac lookup_insert_all :=\n  first [\n    rewrite lookup_insert_bingo in * by omega\n  | rewrite lookup_insert_old in * by omega; one_plus_x_minus_one\n  | rewrite lookup_insert_recent in * by omega\n  | rewrite lookup_shift_insert in *\n  ].\n\nHint Extern 1 (lookup _ (insert _ _ _) = _) =>\n  lookup_insert\n: lookup_insert.\n\nHint Extern 1 (lookup _ _ = _) =>\n  lookup_insert_all\n: lookup_insert.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Interaction between [lookup] and [map]. *)\n\nLemma lookup_map_some:\n  forall A x (a : A) e f,\n  lookup x e = Some a ->\n  lookup x (map f e) = Some (f a).\nProof.\n  unfold lookup, map. intros. case_eq (e x); intros; congruence.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* [insert] commutes itself, just like [lift] commutes with itself. *)\n\nLemma insert_insert:\n  forall A k s (a b : A) e,\n  k <= s ->\n  insert k a (insert s b e) = insert (1 + s) b (insert k a e).\nProof.\n  unfold insert. intros. extensionality y. dblib_by_cases; eauto with f_equal omega.\nQed.\n\n(* Attempting to rewrite in both directions may seem redundant, because of the\n   symmetry of the law [insert_insert]. It is not: because [omega] fails in\n   the presence of meta-variables, rewriting in one direction may be possible\n   while the other direction fails. *)\n\nLtac insert_insert :=\n  first [\n    rewrite insert_insert by omega; reflexivity\n  | rewrite <- insert_insert by omega; reflexivity\n  ].\n\nHint Extern 1 (insert _ _ (insert _ _ _) = _) =>\n  insert_insert\n: insert_insert.\n\nHint Extern 1 (_ = insert _ _ (insert _ _ _)) =>\n  insert_insert\n: insert_insert.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Interaction between [remove] and [insert]. *)\n\nLemma remove_insert:\n  forall A x (a : A) e,\n  remove x (insert x a e) = e.\nProof.\n  intros. unfold remove, insert. extensionality y.\n  dblib_by_cases; eauto with f_equal omega.\nQed.\n\nLemma insert_remove_bingo:\n  forall A x y (a : A) e,\n  lookup x e = Some a ->\n  y = x ->\n  insert y a (remove x e) = e.\nProof.\n  unfold lookup, remove, insert. intros. extensionality z.\n  dblib_by_cases; eauto with f_equal omega; congruence.\nQed.\n\nLemma insert_remove_recent:\n  forall A x y (a : A) e,\n  y <= x ->\n  insert y a (remove x e) = remove (1 + x) (insert y a e).\nProof.\n  intros. unfold insert, remove. extensionality z.\n  dblib_by_cases; eauto with f_equal omega.\nQed.\n\nLemma insert_remove_old:\n  forall A x y (a : A) e,\n  y >= x ->\n  insert y a (remove x e) = remove x (insert (1 + y) a e).\nProof.\n  intros. unfold insert, remove. extensionality z.\n  dblib_by_cases; eauto with f_equal omega.\nQed.\n\nLtac insert_remove :=\n  first [\n    rewrite insert_remove_recent by omega; reflexivity\n  | rewrite insert_remove_old by omega; reflexivity\n  | rewrite <- insert_remove_recent by omega; reflexivity\n  | rewrite <- insert_remove_old by omega; reflexivity\n  ].\n\nHint Extern 1 (remove _ (insert _ _ _) = insert _ _ (remove _ _)) =>\n  insert_remove\n: insert_remove.\n\nHint Extern 1 (insert _ _ (remove _ _)= remove _ (insert _ _ _) ) =>\n  insert_remove\n: insert_remove.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Interaction between [lookup] and [remove]. *)\n\nLemma lookup_remove:\n  forall A x y (e : env A),\n  lookup y (remove x e) = lookup (shift x y) e.\nProof.\n  intros.  unfold lookup, remove. destruct_lift_idx; reflexivity.\nQed.\n\nLemma lookup_remove_old:\n  forall A x y (e : env A),\n  y >= x ->\n  lookup y (remove x e) = lookup (1 + y) e.\nProof.\n  intros. unfold lookup, remove. dblib_by_cases; eauto with f_equal omega.\nQed.\n\nLemma lookup_remove_recent:\n  forall A x y (e : env A),\n  y < x ->\n  lookup y (remove x e) = lookup y e.\nProof.\n  intros. unfold lookup, remove. dblib_by_cases; eauto with f_equal omega.\nQed.\n\nLtac lookup_remove :=\n  first [\n    rewrite lookup_remove_old by omega; one_plus_x_minus_one\n  | rewrite lookup_remove_recent by omega\n  ].\n\nHint Extern 1 (lookup _ (remove _ _) = _) =>\n  lookup_remove\n: lookup_remove.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Interaction between [map] and [insert]. *)\n\nLemma map_insert:\n  forall A f x (a : A) e,\n  map f (insert x a e) = insert x (f a) (map f e).\nProof.\n  unfold map, insert. intros. extensionality y. dblib_by_cases; eauto with f_equal omega.\nQed.\n\nLtac map_insert :=\n  first [\n    rewrite map_insert; reflexivity\n  | rewrite <- map_insert; reflexivity\n  ].  \n\nHint Extern 1 (map _ (insert _ _ _) = insert _ _ (map _ _)) =>\n  map_insert\n: map_insert.\n\nHint Extern 1 (insert _ _ (map _ _) = map _ (insert _ _ _)) =>\n  map_insert\n: map_insert.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* [map] composes with itself. *)\n\nLemma map_map_fuse:\n  forall A f g h e,\n  (forall (d : A), f (g d) = h d) ->\n  map f (map g e) = map h e.\nProof.\n  intros. unfold map. extensionality y. case_eq (e y); congruence.\nQed.\n\nLemma map_map_exchange:\n  forall A f1 f2 g1 g2 e,\n  (forall (d : A), f1 (f2 d) = g1 (g2 d)) ->\n  map f1 (map f2 e) = map g1 (map g2 e).\nProof.\n  intros. unfold map. extensionality y. case_eq (e y); congruence.\nQed.\n\nLemma map_lift_map_lift:\n  forall T k s wk ws (e : env T),\n  forall `{Lift T},\n  @LiftLift T _ ->\n  k <= s ->\n  map (lift wk k) (map (lift ws s) e) = map (lift ws (wk + s)) (map (lift wk k) e).\nProof.\n  eauto using map_map_exchange, @lift_lift.\nQed.\n\nLemma map_map_vanish:\n  forall A f g (e : env A),\n  (forall x, f (g x) = x) ->\n  map f (map g e) = e.\nProof.\n  intros. unfold map. extensionality y. case_eq (e y); congruence.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* A definition of (an upper bound on) the length of an environment. *)\n\nDefinition length A (e : env A) (k : nat) :=\n  forall x,\n  k <= x ->\n  lookup x e = None.\n\n(* Every variable that is defined in the environment is less than the\n   length of the environment. *)\n\nLemma defined_implies_below_length:\n  forall A (e : env A) x k a,\n  length e k ->\n  lookup x e = Some a ->\n  x < k.\nProof.\n  intros.\n  (* If [x < k] holds, the result is immediate. Consider the other case,\n     [k <= x]. *)\n  case (le_gt_dec k x); intro; try tauto.\n  (* By definition of [length], [lookup x e] is [None]. *)\n  assert (lookup x e = None). auto.\n  (* We obtain a contradiction. *)\n  congruence.\nQed.\n\nHint Resolve defined_implies_below_length : lift_idx_hints.\n\n(* The empty environment has zero length. *)\n\nLemma length_empty:\n  forall A k,\n  length (@empty A) k.\nProof.\n  repeat intro. apply lookup_empty_None.\nQed.\n\n(* Extending an environment increments its length by one. *)\n\nLemma length_insert:\n  forall A (e : env A) k a,\n  length e k ->\n  length (insert 0 a e) (1 + k).\nProof.\n  unfold length; intros. lookup_insert. eauto with omega.\nQed.\n\nHint Resolve length_empty length_insert : length.\n\nHint Resolve length_insert : construction_closed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* A definition of when two environments agree up to length [k]. *)\n\nDefinition agree A (e1 e2 : env A) (k : nat) :=\n  forall x,\n  x < k ->\n  lookup x e1 = lookup x e2.\n\n(* A simple consequence of the definition. *)\n\nLemma agree_below:\n  forall A (e1 e2 : env A) x a k,\n  lookup x e1 = Some a ->\n  length e1 k ->\n  agree e1 e2 k ->\n  lookup x e2 = Some a.\nProof.\n  do 6 intro. intros hlookup ? ?.\n  rewrite <- hlookup. symmetry.\n  eauto using defined_implies_below_length.\nQed.\n\n(* The empty environment agrees with every environment up to length [0]. *)\n\nLemma agree_empty:\n  forall A (e : env A),\n  agree (@empty _) e 0.\nProof.\n  unfold agree. intros. elimtype False. omega.\nQed.\n\n(* If two environments that agree up to [k] are extended with a new variable,\n   then they agree up to [k+1]. *)\n\nLemma agree_insert:\n  forall A (e1 e2 : env A) k,\n  agree e1 e2 k ->\n  forall x a,\n  x <= k ->\n  agree (insert x a e1) (insert x a e2) (1 + k).\nProof.\n  unfold agree, lookup, insert. intros. dblib_by_cases; eauto with omega.\nQed.\n\nHint Resolve agree_below agree_empty agree_insert : agree.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Extending an environment with a list of bindings found in a pattern. *)\n\n(* Note that we cannot define the concatenation of two environments, because\n   we view environments as functions, so we do not have precise control over\n   their domain. Only a list has finite domain. *)\n\n(* Concatenation is just an iterated version of [insert 0]. *)\n\nFixpoint concat (A : Type) (e1 : env A) (e2 : list A) : env A :=\n  match e2 with\n  | nil =>\n      e1\n  | cons a e2 =>\n      concat (insert 0 a e1) e2\n  end.\n\n(* Concatenation acts upon the length of the environment in an obvious\n   manner. *)\n\nLemma length_concat:\n  forall A (e2 : list A) (e1 : env A) n1 n,\n  length e1 n1 ->\n  n1 + List.length e2 = n ->\n  length (concat e1 e2) n.\nProof.\n  induction e2; simpl; intros.\n  replace n with n1 by omega. assumption.\n  eauto using length_insert with omega.\nQed.\n\nHint Resolve length_concat : length construction_closed.\n\n(* If [e1] and [e2] agree up to depth [k], then, after extending them\n   with a common suffix [e], they agree up to depth [k + length e]. *)\n\nLemma agree_concat:\n  forall A (e : list A) (e1 e2 : env A) k n,\n  agree e1 e2 k ->\n  k + List.length e = n ->\n  agree (concat e1 e) (concat e2 e) n.\nProof.\n  induction e; simpl; intros.\n  replace n with k by omega. assumption.\n  eauto using agree_insert with omega.\nQed.\n\nHint Resolve agree_concat : agree.\n\n(* Concatenation and insertion commute. *)\n\nLemma insert_concat:\n  forall (A : Type) n x nx (a : A) e1 e2,\n  List.length e2 = n ->\n  n + x = nx ->\n  insert nx a (concat e1 e2) = concat (insert x a e1) e2.\nProof.\n  induction n; intros; subst; destruct e2; simpl in *; try discriminate; auto.\n  rewrite insert_insert by omega.\n  erewrite <- (IHn (1 + x)) by first [ congruence | eauto ].\n  eauto with f_equal omega.\nQed.\n\n(* [replicate n a] is a list of [n] elements, all of which are\n   equal to [a]. *)\n\nFixpoint replicate (A : Type) (n : nat) (a : A) : list A :=\n  match n with\n  | 0 =>\n      @nil _\n  | S n =>\n      cons a (replicate n a)\n  end.\n\n(* The list [replicate n a] has length [n]. *)\n\nLemma length_replicate:\n  forall (A : Type) n (a : A),\n  List.length (replicate n a) = n.\nProof.\n  induction n; simpl; auto.\nQed.\n\n(* A special case of [insert_concat]. *)\n\nLemma insert_concat_replicate:\n  forall (A : Type) n x nx (a b : A) e1,\n  n + x = nx ->\n  insert nx a (concat e1 (replicate n b)) = concat (insert x a e1) (replicate n b).\nProof.\n  eauto using insert_concat, length_replicate.\nQed.\n\n(* [concat . (replicate . a)] is just an iterated version of [insert . a]. *)\n\nLemma concat_replicate_is_iterated_insert:\n  forall (A : Type) n (a : A) e,\n  insert n a (concat e (replicate n a)) =\n  concat e (replicate (S n) a).\nProof.\n  intros. simpl. eauto using insert_concat, length_replicate.\nQed.\n\nHint Resolve insert_concat length_replicate insert_concat_replicate\nconcat_replicate_is_iterated_insert : insert_concat.\n\n(* A special case of [length_concat]. *)\n\nLemma length_concat_replicate:\n  forall A (a : A) (e1 : env A) n1 n2 n,\n  length e1 n1 ->\n  n1 + n2 = n ->\n  length (concat e1 (replicate n2 a)) n.\nProof.\n  intros. eapply length_concat. eauto. rewrite length_replicate. eauto.\nQed.\n\nHint Resolve length_concat_replicate : length construction_closed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Make some definitions opaque, so that Coq does not over-simplify in\n   unexpected (and fragile) ways. *)\n\nGlobal Opaque empty lookup insert remove map.\n\n", "meta": {"author": "dustinwendt", "repo": "session", "sha": "83919b3d84d87a6b295f95e1852f422d8e4d65c6", "save_path": "github-repos/coq/dustinwendt-session", "path": "github-repos/coq/dustinwendt-session/session-83919b3d84d87a6b295f95e1852f422d8e4d65c6/dblib/attic/EnvironmentsAsFunctions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.6852457947469384}}
{"text": "(**\nプログラミング Coq 証明駆動開発入門(1)\nhttp://www.iij-ii.co.jp/lab/techdoc/coqt/coqt8.html\n\nをSSReflectに書き直した。\nその上で、「Program Fixpoint」を使って定義をした。\n*)\n\nFrom mathcomp Require Import all_ssreflect.\nRequire Import Program.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Print All.\n\n\n(* ************ *)\n(* 不等号の証明 *)\n(* ************ *)\n(*\n(* lt なら le *)\n(* ltnW でよかった。 *)\nLemma lt__le n n' : n > n' -> n' <= n.\nProof.\n  move=> H.\n  rewrite leq_eqVlt.\n  by apply/orP; right.\nQed.\n\nLemma b_false__not_b b : b = false -> ~ b.\nProof.\n  Search _ (_ = false).\n  by apply/elimF/idP.\nQed.  \n\n(* le の否定が lt になる。 *)\nLemma not_le__lt n n' : ~ n <= n' <-> n' < n.\nProof.\n  rewrite /not ltnNge /negb.\n  split => H.\n  - case: (n <= n') H => H.\n    + exfalso.\n        by apply H.\n    + by [].\n  - case: (n <= n') H => H H'.\n    + by inversion H.\n    + by inversion H'.\nQed.\n\n(* 証明途中に出現するもの。 *)\nLemma test n n' : (n <= n') = false -> n' <= n.\nProof.\n  move=> H.\n  apply lt__le.\n  apply not_le__lt.\n  by apply b_false__not_b.\nQed.\n *)\n\nLemma le_false_lt n n' : (n <= n') = false -> n' < n.\nProof.\n  move=> H.\n  apply/ltP.\n  apply PeanoNat.Nat.nle_gt.\n  apply/leP.\n  by apply negbT.\nQed.\n\n(* Hint Resolve not_le__lt b_false__not_b : myleq. *)\nHint Resolve le_false_lt : myleq.\n\n(* **** *)\n(* 証明 *)\n(* **** *)\nLemma perm_refl' : forall l : seq nat, perm_eq l l.\nProof.\n  by [].\nQed.\n\nLemma perm_sym' : forall l l' : seq nat, perm_eq l l' -> perm_eq l' l.\nProof.\n  move=> l l'.\n  have H := @perm_eq_sym nat_eqType.\n  rewrite /symmetric in H.\n  by rewrite H.\nQed.\n\nLemma perm_trans' : forall l l' l'' : seq nat, \n    perm_eq l l' -> perm_eq l' l'' -> perm_eq l l''.\nProof.\n  move=> l l' l''.\n  have H := @perm_eq_trans nat_eqType.\n  rewrite /transitive in H.\n    by eapply H.\nQed.\n\nLemma perm_cons' : forall (n : nat) (l l' : seq nat), \n    perm_eq l l' -> perm_eq (n :: l) (n :: l').\nProof.\n  move=> n l l'.\n  have H := @perm_cons nat_eqType.\n    by rewrite H.\nQed.\n  \nLemma perm_iff : forall (m n : seq nat),\n                   (forall l, perm_eq m l = perm_eq n l) <-> perm_eq m n.\nProof.\n  move=> m n.\n  split=> H.\n  - by rewrite H.\n  - by apply/perm_eqlP.\nQed.\n\nLemma perm_swap : forall (l l' : seq nat) (x a : nat),\n                    perm_eq [:: x, a & l] l' = perm_eq [:: a, x & l] l'.\nProof.\n  move=> l l' x a.\n  apply perm_iff.\n  Check cat1s.\n  rewrite -[[:: x, a & l]]cat1s.\n  rewrite -[[:: a & l]]cat1s.\n  rewrite -[[:: a, x & l]]cat1s.\n  rewrite -[[:: x & l]]cat1s.\n  apply/perm_eqlP.\n  by apply (perm_catCA [:: x] [:: a] l).\nQed.\n\nHint Resolve perm_cons' perm_refl' perm_swap perm_trans' : perm.\n\n(* **** *)\n(* 証明 *)\n(* **** *)\nInductive LocallySorted (T : eqType) (R : rel T) : seq T -> Prop :=\n| LSorted_nil : LocallySorted R nil\n| LSorted_cons1 : forall a : T, LocallySorted R (a :: nil)\n| LSorted_consn : forall (a b : T) (l : seq T),\n                    LocallySorted R (b :: l) ->\n                    R a b -> LocallySorted R (a :: b :: l).\n\n\nHint Resolve LSorted_nil LSorted_cons1 LSorted_consn : sort.\n\n(* Permutation, seq.v *)\nCheck perm_eq (1::2::3::nil) (2::1::3::nil).\nEval compute in perm_eq (1::2::3::nil) (2::1::3::nil). (* true *)\nEval compute in perm_eq nil nil.                       (* true *)\n\n\n(* ソート処理の定義 *)\n\n(*\nうまくいかなかった定義：\n引数に事前条件を書くとうまくいかないようである。\n\nProgram Fixpoint insert' (a : nat) (l : {l : seq nat | LocallySorted leq l})\n        {measure (size l)}\n  : {s : seq nat | LocallySorted leq s /\\ perm_eq (a :: l) s} :=\n  match l with\n  | nil => a :: nil\n  | x :: xs => if a <= x then\n                 a :: l\n               else\n                 x :: insert' a xs\n  end.\n *)\n\nProgram Fixpoint insert n l {struct l} : \n  {l' : seq nat | perm_eq (n ::l) l' /\\\n                  (LocallySorted leq l -> LocallySorted leq l') /\\ \n                  (head n l' = n \\/ head n l' = head n l)} := \n  match l with\n  | nil => n :: nil\n  | n' :: l' => \n    if n <= n' then\n      n :: n' :: l'\n    else\n      n' :: insert n l'\n  end.\nObligations.\n\nNext Obligation.\n    by auto with sort.\nDefined.\n\nNext Obligation.\n  case Hnn' : (n <= n').\n  - by auto with sort.\n  - split.\n    + erewrite perm_swap.\n        by apply perm_cons'.\n      (* by eauto with sort. *)\n    + split.\n      * move=> H0.\n        assert (LocallySorted leq l') as H1 by (inversion H0; auto with sort).\n        assert (LocallySorted leq x)  as H2 by auto.\n        elim: x i l0 o H2.\n        ** by auto with sort.\n        ** inversion H0; subst.\n           *** move=> a l _ _ _ Ho H2; rewrite /= in Ho.\n               case: Ho => Ho; subst;\n                             by auto with sort myleq.\n               (*\n               **** apply sorted2; by [apply ltnW, not_le__lt, b_false__not_b |].\n               **** apply sorted2; by [apply ltnW, not_le__lt, b_false__not_b |].\n               *)\n           *** move=> a l' _ _ _ Ho H2; rewrite /= in Ho.\n               case: Ho => Ho; subst;\n                             by auto with sort myleq.\n               (*\n               **** apply sorted2; by [apply ltnW, not_le__lt, b_false__not_b |].\n               **** apply sorted2; by [].\n               *)\n      * by auto.\nDefined.\n\nProgram Fixpoint isort l {struct l} :  \n  {l' : seq nat | perm_eq l l' /\\ LocallySorted leq l'} := \nmatch l with \n| nil => nil\n| a::l' => insert a (isort l')\nend.\n\nNext Obligation.\n  by auto with sort.\nDefined.\n\nNext Obligation.\n  remember (insert a x).\n  case H : s => /= {Heqs}; subst.\n    by intuition; eauto with perm.\n    \n    Undo 1.\n  intuition.\n  Check @perm_trans' (a :: l') (a :: x).\n  - apply (@perm_trans' (a :: l') (a :: x)).\n    + by apply perm_cons'.\n    + by apply H.\n  - apply (@perm_trans' (a :: l') (a :: x)).\n    + by apply perm_cons'.\n    + by apply H.\nDefined.\n\nPrint sort.\n\nEval compute in proj1_sig (insert 1 nil).                (* [:: 1] *)\nEval compute in proj1_sig (insert 5 [:: 1; 4; 2; 9; 3]). (* [:: 1; 4; 2; 5; 9; 3] *)\nEval compute in proj1_sig (isort [:: 2; 4; 1; 5; 3]).    (* [:: 1; 2; 3; 4; 5] *)\n\nExtraction insert.\nExtraction isort.\n\n(* ******************* *)\n(* insert を使う merge *)\n(* ******************* *)\nLemma sorted_ind_inv h ls : LocallySorted leq (h :: ls) -> LocallySorted leq ls.\nProof.\n  move=> H.\n  inversion H.\n  - by auto with sort.\n  - by [].\nQed.\n\nHint Resolve sorted_ind_inv : sort.\n\nProgram Fixpoint merge' (ls1 ls2 : seq nat) :\n  {l' : seq nat | perm_eq (ls1 ++ ls2) l' /\\\n                  (LocallySorted leq ls1 /\\ LocallySorted leq ls2 ->\n                   LocallySorted leq l')} :=\n  match ls1 with\n  | nil => ls2\n  | h :: ls' => insert h (merge' ls' ls2)\n  end.\nObligations.\nNext Obligation.\n  split.\n  - by [].\n  - by case.\nDefined.\nNext Obligation.\n  remember (insert h x) as s.\n  case H : s => /= {Heqs}; subst.\n  intuition.                          (* ゴールの /\\ をsplit する。 *)\n  - by debug eauto with sort perm.\n  - by debug eauto with sort.\n  - by debug eauto with sort perm.\n  - by debug eauto with sort.\nDefined.\n\nPrint merge'.\n\n\n(* 未了 *)\n(* 補題が足らないので、続きをする場合は *)\n(* 新しくファイルを別にして、sortedなどの補題を充実させる。 *)\n(* 未了 *)\n\n(* *********************** *)\n(* insert を使わない merge *)\n(* *********************** *)\nProgram Fixpoint merge (ls1 ls2 : seq nat)\n  {measure (size ls1 + size ls2)} :\n  {l' : seq nat | perm_eq (ls1 ++ ls2) l' /\\\n                        (LocallySorted leq ls1 /\\ LocallySorted leq ls2 ->\n                         LocallySorted leq l')} :=\n  (* match (ls1, ls2) とすると、ペアどうしの代入の前提が解けない。 *)\n  (* 「'」をつけてもだめのよう。 *)\n  match ls1 with\n  | [::] => ls2\n  | x :: ls1' => match ls2 with\n                 | [::] => ls1\n                 | y :: ls2' => if x <= y then\n                                  x :: (merge ls1' ls2)\n                                else\n                                  y :: (merge ls1 ls2')\n                 end\n  end.\nObligations.\nNext Obligation.\n  split.\n  - by [].\n  - by case.\nDefined.\nNext Obligation.\n  intuition.\n  by rewrite cats0.\nDefined.\nNext Obligation.\n  apply/ltP.\n  by rewrite ltn_add2l.\nDefined.\nNext Obligation.\n  remember (merge ls1' (y :: ls2') _) as s.\n  case H : s => /= {Heqs}; subst.\n  remember (merge (x :: ls1') ls2' _) as s.\n  case H : s => /= {Heqs}; subst.\n  case H : (x <= y); split.\nAdmitted.\n\nProgram Fixpoint splits (ls : seq nat) :\n  { (ls1,ls2) : seq nat * seq nat |\n    perm_eq ls (ls1 ++ ls2) /\\\n    (LocallySorted leq ls -> LocallySorted leq ls1) /\\\n    (LocallySorted leq ls -> LocallySorted leq ls2) } :=\n  match ls with\n  | [::] => ([::], [::])\n  | [:: h] => ([:: h], [::])\n  | [:: h1, h2 & ls'] =>\n    let '(ls1, ls2) := splits ls' in (* let の左辺に\"'\"をつける。バニラCoq *)\n    (h1 :: ls1, h2 :: ls2)\n  end.\nObligations.\nNext Obligation.\n  Admitted.\nNext Obligation.\n  Admitted.\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_isort_prog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.6852457931591883}}
{"text": "Section Z1.\n\nVariables A B C : Prop.\n\nLemma z1l1: A -> (B -> A).\nProof.\n  intros.\n  assumption.\nQed.\n\nLemma z1l2: (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\n  intros.\n  apply H.\n  - assumption.\n  - apply H0.\n    assumption.\nQed.\n\nLemma z1l4: A -> ~~A.\nProof.\n  intros.\n  intro.\n  absurd A.\n  - assumption.\n  - assumption.\nQed.\n\nLemma z1l6: ~~~A -> ~A.\nProof.\n  intro.\n  (* tauto. *)\n  intro.\n  absurd A.\n  - intro.\n    apply H.\n    intro.\n    absurd A; assumption.\n  - assumption.\nQed.\n\n(* Lemma z1l7: (~A -> B) -> A *)\n(*              1  1 x  0 0 *)\n\nLemma z1l9: ((((A -> B) -> A) -> A) -> B) -> B.\nProof.\n  intros.\n  apply H.\n  intros.\n  apply H0.\n  intros.\n  apply H.\n  intros.\n  assumption.\nQed.\n\nLemma z1l10: (A -> B) -> (A -> ~B) -> A -> C.\nProof.\n  intros.\n  absurd B.\n  - apply H0; assumption.\n  - apply H; assumption.\nQed.\n\nRequire Import Classical.\n\nLemma z1l3: (~A -> A) -> A.\nProof.\n  intros.\n  destruct classic with A.\n  - assumption.\n  - apply H.\n    assumption.\nQed.\n\nLemma z1l5: ~~A -> A.\nProof.\n  apply NNPP.\nQed.\n\nLemma z1l8: ~(A -> B) -> A.\nProof.\n  intros.\n  apply NNPP.\n  intro.\n  apply H.\n  intro.\n  absurd A.\n  - assumption.\n  - assumption.\n  (* tauto. *)\nQed.\n\nEnd Z1.\n\n\nSection Z2.\n\nRequire Import Classical.\n\nVariable S T : Set.\nVariable A : S -> T -> Prop.\nVariable B : T -> Prop.\nVariable C : Prop.\n\n(* Lemma z2l1: (exists x, forall y, A x y) -> forall x, exists y, A x y. *)\n\nLemma z2l2: (~forall x, B x) -> exists x, ~(B x).\nProof.\n  intro.\n  apply NNPP.\n  intro.\n  apply H.\n  intro.\n  destruct classic with (B x).\n  - assumption.\n  - exfalso.\n    apply H0.\n    exists x.\n    assumption.\nQed.\n\nLemma z2l3: (exists x, ~(B x)) -> (~forall x, B x).\nProof.\n  intros.\n  intro.\n  destruct H.\n  absurd (B x).\n  - assumption.\n  - apply H0.\nQed.  \n\nLemma z2l4: (~exists x, B x) -> forall x, ~B x.\nProof.\n  intros.\n  intro.\n  apply H.\n  exists x.\n  assumption.\nQed.\n\nLemma z2l5: (forall x, ~B x) -> ~exists x, B x.\nProof.\n  intros.\n  intro.\n  destruct H0.\n  absurd (B x).\n  - apply H.\n  - assumption.\nQed.\n\n(* Lemma z2l6: (C -> exists x, B x) -> (exists x, C -> B x). *)\n  \nLemma z2l7: (exists x, C -> B x) -> C -> exists x, B x.\nProof.\n  intros.\n  destruct H.\n  exists x.\n  apply H.\n  assumption.\nQed.\n\n(* Lemma z2l8: exists x, forall y, B x -> B y. *)\n\n\nEnd Z2.\n\n\nSection Z3.\n\nVariable T : Set.\nVariable C : T -> Prop.\nVariable S : T -> Prop.\nVariable G : T -> T -> Prop.\n\nAxiom a3 :\nforall x, C x /\\ S x ->\nforall y, S y -> (~ G y y -> G x y) /\\ (G y y -> ~ G x y).\n\nLemma z3 : \n~ exists x, C x /\\ S x.\nProof.\n  intro.\n  destruct H.\n  apply a3 with (y:=x) in H as H1.\n  - apply H1; apply H1; intro; apply H1; assumption.\n  - apply H.\nQed.\n\nEnd Z3.\n\n\nSection Z4.\n\nVariables A B : Prop.\n\nLemma not_or: ~(A \\/ B) -> ~A /\\ ~B.\nProof.\n  intro.\n  split.\n  - intro.\n    apply H.\n    left.\n    assumption.\n  - intro.\n    apply H.\n    right.\n    assumption.\nQed.\n\nLemma and_not: ~A /\\ ~B -> ~(A \\/ B).\nProof.\n  intro.\n  intro.\n  destruct H0 as [HA | HB].\n  - absurd A.\n    + apply H.\n    + apply HA.\n  - absurd B.\n    + apply H.\n    + apply HB.\nQed.\n\nLemma or_not: ~A \\/ ~B -> ~(A /\\ B).\nProof.\n  intro.\n  intro.\n  destruct H.\n  - absurd A.\n    + assumption.\n    + apply H0.\n  - absurd B.\n    + assumption.\n    + apply H0.\nQed.\n\nRequire Import Classical.\n\nLemma not_and: ~(A /\\ B) -> ~A \\/ ~B.\nProof.\n  intro.\n  apply NNPP.\n  intro.\n  apply H.\n  split.\n  - apply NNPP.\n    intro.\n    apply H0.\n    left.\n    assumption.\n  - apply NNPP.\n    intro.\n    apply H0.\n    right.\n    assumption.\nQed.\n\nEnd Z4.\n\n\nSection Z5.\n\n(* Auto -\nThis tactic implements a Prolog-like resolution procedure to solve the current goal.\nIt first tries to solve the goal using the assumption tactic,\nthen it reduces the goal to an atomic one using intros\nand introduces the newly generated hypotheses as hints.\nThen it looks at the list of tactics associated to the head symbol of the goal\nand tries to apply one of them (starting from the tactics with lower cost).\nThis process is recursively applied to the generated subgoals.\n\nBy default, auto only uses the hypotheses of the current goal and\nthe hints of the database named core. *)\n\nVariables A B : Prop.\n\nLemma aux: A -> A /\\ A /\\ A /\\ A /\\ A.\nProof.\n  (* auto 4. *)\n  auto 5.\nQed.\n\nEnd Z5.\n\nPrint nat.\nPrint bool.\n\n\nLemma t: nat <> bool.\nProof.\n  intro.\nQed.\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/l1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.6852457894379231}}
{"text": "Require Export Poly_J.\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  Case \"n = O\". simpl. intros eq. destruct m as [| m'].\n    SCase \"m = O\". reflexivity.\n    SCase \"m = S m'\". inversion eq.\n  Case \"n = S n'\". intros eq. destruct m as [| m'].\n    SCase \"m = O\". inversion eq.\n    SCase \"m = S m'\".\n      assert (n' = m') as H.\n      SSCase \"Proof of assertion\".\nAdmitted.\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.     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\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\n", "meta": {"author": "denjiry", "repo": "pgeneral", "sha": "190a607a5071af6d41d1abe2af85b86dc085b9ea", "save_path": "github-repos/coq/denjiry-pgeneral", "path": "github-repos/coq/denjiry-pgeneral/pgeneral-190a607a5071af6d41d1abe2af85b86dc085b9ea/Gen_J.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.6852457845382315}}
{"text": "Require Import Reals.\n\nOpen Scope R_scope.\n\nDefinition Real := R.\n\n(* function parameter *)\nVariable s : Real.\n\n(* constant *)\nParameter Kt Bm Ke : Real.\n\n(* variables *)\nParameter Rm Lm Jm : Real.\n\n(* functions from s to real. *)\nVariables Um Im Om Tm : Real -> Real.\n\nDefinition tm1 := (Um s) - Rm * (Im s) - Lm * s * (Im s) - Ke * (Om s).\nDefinition tm2 := Kt * (Im s) - Jm * s * (Om s) - Bm * (Om s) - (Tm s).\nDefinition tm3 := (Tm s) * (Lm *s + Rm).\nDefinition tm4 := (Um s) * Kt - Kt * Ke * (Om s) - (Lm * s + Rm) * (Jm * s + Bm) * (Om s).\n\n(* assumptions of this deduction. *)\nAxiom e1 : tm1 = 0.\nAxiom e2 : tm2 = 0.\n\nDefinition tm5 :=  ((Um s) - Rm * (Im s) - (Lm * s) * (Im s)).\n\nLemma eq0_eq : forall y z, y-z = 0 -> y = z.\nintros.\napply sym_eq.\napply Rminus_diag_uniq_sym.\nassumption.\nQed.\n\n(* move Ke * (Om s) in tm1 to the  right of  = *)\nLemma tm5_eq : tm5  = Ke * (Om s).\napply eq0_eq.\napply e1.\nQed.\n\n\nDefinition tm6 :=  ((Um s) - (Rm + Lm * s) * (Im s)).\n\nLemma  tm6_eq_tm5 : tm6 = tm5.\nunfold tm5; unfold tm6.\nring.\nQed.\n\nLemma tm6_eq : tm6 = Ke * (Om s).\nrewrite tm6_eq_tm5.\napply tm5_eq.\nQed.\n\n", "meta": {"author": "darenme", "repo": "MyCoqScript", "sha": "cb88d115ec69ebf3d0b55d72c255a043ee3f143b", "save_path": "github-repos/coq/darenme-MyCoqScript", "path": "github-repos/coq/darenme-MyCoqScript/MyCoqScript-cb88d115ec69ebf3d0b55d72c255a043ee3f143b/deduce.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6852186035706244}}
{"text": "Theorem Disjunctive_syllogism : forall P Q: Prop, (P \\/ Q) -> ~P -> Q.\nintros.\ncase H.\nintros.\nexfalso.\napply H0.\napply H1.\nintros.\napply H1.\nQed.", "meta": {"author": "ashiato45", "repo": "CoqEx2014", "sha": "83750632bf6a78db93ed493a739b4aeae8505df1", "save_path": "github-repos/coq/ashiato45-CoqEx2014", "path": "github-repos/coq/ashiato45-CoqEx2014/CoqEx2014-83750632bf6a78db93ed493a739b4aeae8505df1/1/disjunctive_syllogism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.685218597069887}}
{"text": "Require Import List ListDec Arith.\nImport ListNotations.\n\nSection card.\nVariable X : Type.\nVariable P: X -> Prop.\n\nClass enum := {\n  enumeration: list X;\n  enum_spec: forall x, P x <-> In x enumeration;\n  enum_nodup: NoDup enumeration\n}.\nCoercion enumeration: enum >-> list.\n\nDefinition count (e: enum) := length enumeration.\nInductive card n := cardI e: count e = n -> card n.\n\nLemma card_well_defined: forall n m, card n -> card m -> n = m.\nProof.\n  intros n m [e1 H1] [e2 H2]. subst n m.\n  apply PeanoNat.Nat.le_antisymm.\n  - apply NoDup_incl_length.\n    + apply enum_nodup.\n    + intros x H. apply enum_spec. apply enum_spec in H. exact H.\n  - apply NoDup_incl_length.\n    + apply enum_nodup.\n    + intros x H. apply enum_spec. apply enum_spec in H. exact H.\nQed.\n\nEnd card.\nArguments enum {X}.\nArguments card {X}.\n\nDefinition all X := fun (x:X) => True.\n\n(* ** Counting three things *)\nVariant three := a | b | c.\nLemma decThree: forall (x y : three), {x = y} + {x <> y}.\nProof. decide equality. Defined.\n#[export] Instance three_enum: enum (all three).\nProof.\n  exists (a::b::c::nil).\n  - intros []; compute; tauto.\n  - apply <- (NoDup_count_occ decThree).\n    intros []; reflexivity.\nDefined.\n\nGoal card (all three) 3.\nProof. econstructor. reflexivity. Qed.\n\n(* ** Counting combinations of things *)\nFixpoint combinations {A : Type} (l: list A) d :=\nmatch d with\n| 0 => [[]]\n| S d => map (fun '(x, combination) => x::combination)\n             (list_prod l (combinations l d))\nend.\n\nCompute combinations three_enum 4.\n\nLemma combinations_length {A : Type} (l: list A) d:\n  length (combinations l d) = (length l)^d.\nProof.\n  induction d; [ reflexivity | ].\n  cbn. now rewrite map_length, prod_length, IHd.\nQed.\n\n(* ** sequences without repetitions *)\nSection seq_no_rep.\nVariable X : Type.\nVariable n : nat.\nDefinition P : list X -> Prop := fun l => NoDup l /\\ length l = n.\n\n#[export] Instance seq_no_rep_enum: enum P.\nProof.\n  unfold P. induction n as [| n' IH].\n  - exists [[]].\n    + intros l. split.\n      * intros [H0 H1%length_zero_iff_nil]. rewrite H1. now left.\n      * intros H. destruct H as [<- | []].\n        split; constructor.\n    + constructor; [apply in_nil | constructor].\n  -\nAbort.\n\nEnd seq_no_rep.\n", "meta": {"author": "haansn08", "repo": "coq-basic-combinatorics", "sha": "391e280605c2127142bc2cec20c0b874034d936a", "save_path": "github-repos/coq/haansn08-coq-basic-combinatorics", "path": "github-repos/coq/haansn08-coq-basic-combinatorics/coq-basic-combinatorics-391e280605c2127142bc2cec20c0b874034d936a/theories/counting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6852185883780922}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nCheck nat_eqType.\nPrint Canonical Projections.\nCompute Equality.sort nat_eqType.           (* nat *)\nCompute Monoid.operator addn_monoid.        (* addn *)\n\n(* 5.8 The generic theory of “big” operators *)\n\nFixpoint iota m n :=\n  if n is u.+1 then\n    m :: iota m.+1 u\n  else\n    [::].\nCompute iota 3 5.                           (* = [:: 3; 4; 5; 6; 7] *)\n\nReserved Notation \"\\sum''_ ( m <= i < n ) F\"\n         (at level 41, F at level 41, i, m, n at level 50,\n          format \"'[' \\sum''_ ( m  <=  i  <  n ) '/  '  F ']'\").\n\nReserved Notation \"\\sum'_ ( m <= i < n | P ) F\"\n         (at level 41, F at level 41, i, m, n at level 50,\n          format \"'[' \\sum'_ ( m  <=  i  <  n | P ) '/  '  F ']'\").\n\nReserved Notation \"\\sum'_ ( m <= i < n ) F\"\n         (at level 41, F at level 41, i, m, n at level 50,\n          format \"'[' \\sum'_ ( m  <=  i  <  n ) '/  '  F ']'\").\n\nReserved Notation \"\\big [ op / idx ]_ ( i <- r | P ) F\"\n         (at level 36, F at level 36, op, idx at level 10, i, r at level 50,\n          format \"'[' \\big [ op / idx ]_ ( i  <-  r  |  P ) '/  '  F ']'\").\n\nReserved Notation \"\\big [ op / idx ]_ ( i <- r ) F\"\n         (at level 36, F at level 36, op, idx at level 10, i, r at level 50,\n          format \"'[' \\big [ op / idx ]_ ( i  <-  r ) '/  '  F ']'\").\n\nReserved Notation \"\\big [ op / idx ]_ ( m <= i < n | P ) F\"\n         (at level 36, F at level 36, op, idx at level 10, m, i, n at level 50,\n          format \"'[' \\big [ op / idx ]_ ( m  <=  i  <  n  |  P )  F ']'\").\n\nReserved Notation \"\\big [ op / idx ]_ ( m <= i < n ) F\"\n         (at level 36, F at level 36, op, idx at level 10, m, i, n at level 50,\n          format \"'[' \\big [ op / idx ]_ ( m  <=  i  <  n )  F ']'\").\n\nReserved Notation \"\\sum_ ( m <= i < n | P ) F\"\n         (at level 41, F at level 41, i, m, n at level 50,\n          format \"'[' \\sum_ ( m  <=  i  <  n | P ) '/  '  F ']'\").\n\nReserved Notation \"\\sum_ ( m <= i < n ) F\"\n         (at level 41, F at level 41, i, m, n at level 50,\n          format \"'[' \\sum_ ( m  <=  i  <  n ) '/  '  F ']'\").\n\n(* 1.7 Iterators in mathematics *)\n(* もっとも簡単な定義 *)\n\nNotation \"\\sum''_ ( m <= i < n ) F\" :=\n  (foldr (fun i a => F + a) 0 (iota m (n - m))).\n\n(* 5.8 The generic theory of “big” operators *)\n\nDefinition index_iota m n :=                (* U(i=m, i<n)、n は含まない！ *)\n  iota m (n - m).\n\nCompute index_iota 3 5.                     (* = [:: 3; 4] = U(i=3, i<5) ... *)\n\nDefinition bigop' {R I : Type}\n           (idx : R)                        (* 初期値 *)\n           (op : R -> R -> R)               (* big-opに対するsmall-op *)\n           (r : seq I)                      (* リスト *)\n           (P : pred I)                     (* 取出す条件、引数はi (I -> bool) *)\n           (F : I -> R) :                   (* 個別の処理、引数はi *)\n  R :=                                      (* 結果 *)\n  foldr (fun (i : I) (x : R) => if P i then op (F i) x else x) idx r.\n\nLocal Notation \"+%N\" :=\n  addn (at level 0, only parsing).\n\nNotation \"\\sum'_ ( m <= i < n | P ) F\":=\n  (bigop' 0%N +%N (index_iota m n) P F%N) : nat_scope.\n\nNotation \"\\sum'_ ( m <= i < n ) F\":=\n  (bigop' 0%N +%N (index_iota m n) true F%N) : nat_scope.\n\n\n(* 5.9 Stable notations for big operators *)\n(* To solve these problems 以降を抜粋する。 *)\n(* やっていることは同じ。 *)\n\nInductive bigbody {R I : Type} :=\n  BigBody of I & (R -> R -> R) & bool & R.\n\nDefinition sum_odd_def_body i :=            (* 例 *)\n  BigBody i addn (odd i) i.\n\nDefinition applybig {R I} (body : @bigbody R I) acc :=\n  let: BigBody _ op b v := body in\n  if b then op v acc else acc.\n\nDefinition bigop {R I} idx r (body : I -> @bigbody R I) :=\n  foldr (applybig \\o body) idx r.\n\nNotation \"\\big [ op / idx ]_ ( i <- r | P ) F\" :=\n  (bigop idx r (fun i => BigBody i op P F)) : big_scope.\n\nNotation \"\\big [ op / idx ]_ ( i <- r ) F\" :=\n  (bigop idx r (fun i => BigBody i op true F)) : big_scope.\n\nNotation \"\\big [ op / idx ]_ ( m <= i < n | P ) F\" :=\n  (\\big[op/idx]_(i <- index_iota m n | P) F) : big_scope.\n\nNotation \"\\big [ op / idx ]_ ( m <= i < n ) F\" :=\n  (\\big[op/idx]_(i <- index_iota m n) F) : big_scope.\n\nLocal Notation \"+%N\" :=\n  addn (at level 0, only parsing).\n\nLocal Notation \"*%N\" :=\n  muln (at level 10, only parsing).\n\nNotation \"\\sum_ ( m <= i < n | P ) F\":=\n  (\\big[+%N/0%N]_(m <= i < n | P) F%N) : nat_scope.\n(*\n  (bigop 0%N (index_iota m n) (fun i => BigBody i addn P F%N)) : nat_scope.\n*)\n\nNotation \"\\sum_ ( m <= i < n ) F\":=\n  (\\big[+%N/0%N]_(m <= i < n) F%N) : nat_scope.\n(*\n  (bigop 0%N (index_iota m n) (fun i => BigBody i addn true F%N)) : nat_scope.\n*)\n\n(* *********** *)\n(* テストと証明 *)\n(* *********** *)\n\nEval compute in \\sum_(1 <= i < 5) (i * 2 - 1). (* = 16 : nat *)\nEval compute in \\sum_(1 <= i < 5) i.           (* = 10 : nat *)\n\n(* small-op (\\sum_ の addn) はモノイドでなければならない。 *)\nLemma mul1m {T : Type} (idm : T) (mul : Monoid.law idm) : left_id idm mul.\nProof.\n    by case mul.\nQed.\n\nLemma mulm1 {T : Type} (idm : T) (mul : Monoid.law idm) : right_id idm mul.\nProof.\n    by case mul.\nQed.\n\nLemma mulmA {T : Type} (idm : T) (mul : Monoid.law idm) :\n  associative mul.\nProof.\n    by case mul.\nQed.\n\n(* *********************** *)\n(* 条件式を個別の項に移す。 *)\n(* *********************** *)\nLemma big_mkcond {I R : Type} (idx : R) (op : Monoid.law idx)\n      (r : seq I) (P : pred I) (F : I -> R) :\n  \\big[op/idx]_(i <- r | P i) F i =\n  \\big[op/idx]_(i <- r) (if P i then F i else idx).\n (*\n  bigop idx r (fun i => @BigBody R I i op (P i) (F i)) =\n  bigop idx r (fun i => @BigBody R I i op true (if P i then F i else idx)).\n*)\nProof.\n  elim: r => //= i r ->.\n  case P => //=.\n  by rewrite mul1m.\nQed.\n\nLemma big_cat {I R : Type} (idx : R) (op : Monoid.law idx)\n      (r1 r2 : seq I) (P : pred I) (F : I -> R) :\n  \\big[op/idx]_(i <- r1 ++ r2 | P i) F i =\n  op (\\big[op/idx]_(i <- r1 | P i) F i) (\\big[op/idx]_(i <- r2 | P i) F i).\nProof.\n  elim: r1 => /= [|i' r1 ->]; rewrite (mul1m, mulmA).\n  - done.\n  - by case: (P i').\nQed.\n\nLemma big_cat_nat {R : Type} (idx : R) (op : Monoid.law idx)\n      (m n p : nat) (P : pred nat) (F : nat -> R) :\n  m <= n -> n <= p ->\n  \\big[op/idx]_(m <= i < p | P i) F i =\n  op (\\big[op/idx]_(m <= i < n | P i) F i) (\\big[op/idx]_(n <= i < p | P i) F i).\nProof.\n  move=> le_mn le_np.\n  rewrite -big_cat.\n  rewrite -{2}(subnKC le_mn) -iota_add subnDA.\n  now rewrite subnKC // leq_sub.\nQed.\n\nLemma big_ltn {R : Type} (idx : R) (op : Monoid.law idx)\n      (m n : nat) (F : nat -> R) :\n  m < n ->\n  \\big[op/idx]_(m <= i < n) F i = op (F m) (\\big[op/idx]_(m.+1 <= i < n) F i).\nProof.\n  Admitted.\n\nLemma big_geq {R : Type} (idx : R) (op : Monoid.law idx)\n      (m n : nat) (P : pred nat) (F : nat -> R) :\n  m >= n -> \\big[op/idx]_(m <= i < n | P i) F i = idx.\nProof.\n    by move=> ge_m_n; rewrite /index_iota (eqnP ge_m_n).\nQed.\n\nLemma big_nat1 {R : Type} (idx : R) (op : Monoid.law idx)\n      (n : nat) (F : nat -> R) :\n  \\big[op/idx]_(n <= i < n.+1) F i = F n.\nProof.\n  by rewrite big_ltn // big_geq // mulm1.\nQed.\n\n(* ********************************* *)\n(* 右側（大きい値）をBigOPの外に出す。 *)\n(* ********************************* *)\nLemma big_nat_recr {R : Type} (idx : R) (op : Monoid.law idx)\n      (n m : nat) (F : nat -> R) :\n    m <= n ->\n    \\big[op/idx]_(m <= i < n.+1) F i =\n    op (\\big[op/idx]_(m <= i < n) F i) (F n).\n(*\n    bigop idx (index_iota m n.+1) (fun i => @BigBody R nat i op true (F i)) =\n    op (bigop idx (index_iota m n) (fun i => BigBody i op true (F i))) (F n).\n*)\nProof.\n  move=> lemn.\n  Check (big_cat_nat idx op m n n.+1 (fun i => true) F).\n  rewrite (big_cat_nat idx op m n n.+1 (fun i => true) F).\n  - Check big_nat1.\n      by rewrite big_nat1.\n  - done.\n  - done.\nQed.\n\n(* **** *)\n(* 証明 *)\n(* **** *)\n\nLemma sum_odd_3 : \\sum_(0 <= i < 3.*2 | odd i) i = 3^2.\nProof.\n  by rewrite big_mkcond big_nat_recr //=.\nQed.\n\nLemma test : \\sum_(0 <= i < 6) i= (\\sum_(0 <= i < 5) i) + 5.\nProof.\n    by apply: big_nat_recr.\nQed.\n\n\n(* Exercise 16. Sum of 2n odd numbers *)\n\nLemma sum_odd n : \\sum_(0 <= i < n.*2 | odd i) i = n^2.\nProof.\n  elim: n => [|n IHn].\n  - done.\n  - rewrite doubleS.\n    rewrite big_mkcond.\n    rewrite big_nat_recr.\n    rewrite big_nat_recr.\n    rewrite -big_mkcond.\n    rewrite /=.\n    rewrite IHn.\n    rewrite odd_double.\n    rewrite /=.\n    rewrite addn0.\n    rewrite -addnn.\n    rewrite -!mulnn.\n    ring.\n   \n  Restart.\n\n  elim: n => [|n IHn]; first done.\n  rewrite doubleS big_mkcond 2?big_nat_recr // -big_mkcond /=.\n  rewrite {}IHn odd_double /= addn0 -addnn -!mulnn; 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/math-comp-book/suhara.ch5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198947, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.6852149409204141}}
{"text": "From Coq Require Import Relations.\nFrom Coq Require Import Relations.Relation_Operators.\nFrom KBase Require Import Tactics.\n\nSection Definitions.\n\nContext {A : Type}.\n\n(* Most of this file is inspired by \"Confluence and Normalization in Reduction Systems Lecture Notes\"\n   by Gert Smolka of Saarland University. December 16, 2015\n   https://www.ps.uni-saarland.de/courses/sem-ws15/ars.pdf *)\n\nDefinition joinable (R : relation A) (x y : A) : Prop :=\n  exists z, R x z /\\ R y z.\n\nDefinition diamond (R : relation A) : Prop :=\n  forall x y z, R x y -> R x z -> joinable R y z.\n\nDefinition confluent (R : relation A) : Prop :=\n  diamond (clos_refl_trans_1n A R).\n\nDefinition semi_confluent (R : relation A) : Prop :=\n  forall x y z, \n    R x y -> \n    clos_refl_trans_1n A R x z -> \n    joinable (clos_refl_trans_1n A R) y z.\n\nDefinition locally_confluent (R : relation A) : Prop :=\n  forall x y z, \n    R x y -> \n    R x z -> \n    joinable (clos_refl_trans_1n A R) y z.\n\nDefinition reducible (R : relation A) (x : A) : Prop :=\n  exists z, R x z.\n\nDefinition normal (R : relation A) (x : A) : Prop :=\n  ~ (reducible R x).\n\nDefinition terminal (R : relation A) (x y : A) : Prop :=\n  clos_refl_trans_1n A R x y /\\ normal R y.\n\n  (* Weak normalization *)\nDefinition WN (R : relation A) (x : A) : Prop :=\n  exists z, terminal R x z.\n\n  (* Strong normalization *)\nInductive SN (R : relation A) (x : A) : Prop :=\n  | sn_intro : (forall y, R x y -> SN R y) -> SN R x.\n\nDefinition terminating (R : relation A) : Prop :=\n    forall x, SN R x.\n\nFixpoint apply_n (n : nat) (f : A -> A) : A -> A :=\n  match n with\n    | 0 => fun x => x\n    | S n => fun x => f (apply_n n f x)\n  end. \n\nDefinition triangle_op (R : relation A) (f : A -> A) : Prop :=\n    forall x y, R x y -> R y (f x).\n\nEnd Definitions.\n\n#[global] Hint Resolve clos_rt1n_step : KBaseHints.\n#[global] Hint Resolve rt1n_refl : KBaseHints.\n\nTheorem clos_rt1n_trans : forall (A : Type) (R : relation A) x y z,\n  clos_refl_trans_1n A R x y ->\n  clos_refl_trans_1n A R y z ->\n  clos_refl_trans_1n A R x z.\nProof.\n  intros A R x y z x_y y_z;\n  apply clos_rt_rt1n;\n  apply clos_rt1n_rt in x_y;\n  apply clos_rt1n_rt in y_z;\n  eauto using rt_trans.\nQed.\n\nTheorem clos_rt1n_right : forall (A : Type) (R : relation A) x y z,\n  clos_refl_trans_1n A R x y ->\n  R y z ->\n  clos_refl_trans_1n A R x z.\nProof.\n  intros A R x y z x_y y_z;\n  apply (clos_rt1n_trans A R x y z); auto using clos_rt1n_step.\nQed.\n\n#[global] Hint Extern 1 (clos_refl_trans_1n ?A ?R ?x ?z) =>\n  match goal with\n  | H1: clos_refl_trans_1n A R x ?y,\n    H2: clos_refl_trans_1n A R ?y z |- _ => exact (clos_rt1n_trans A R x y z H1 H2)\n  | H: R x ?y |- _ => apply (rt1n_trans A R x y z H)\n  | H: clos_refl_trans_1n A R ?y z |- _ => apply (rt1n_trans A R x y z)\n  | H: R ?y z |- _ => apply (clos_rt1n_right A R x y z)\n  end : KBaseHints.\n\nSection Properties.\n  Context {A : Type}.\n\n  (* Facts about clos_refl_trans_1n *)\n\n  Theorem idempotence_rt : forall (R : relation A),\n    same_relation A (clos_refl_trans_1n A R) \n      (clos_refl_trans_1n A (clos_refl_trans_1n A R)).\n  Proof.\n    split; intros x y x_y.\n    - crush.\n    - induction x_y; crush.\n  Qed. \n  #[local] Hint Resolve idempotence_rt : KBaseHints.\n\n  Theorem monotonicity_rt : forall R1 R2, \n    inclusion A R1 R2 -> \n    inclusion A (clos_refl_trans_1n A R1) (clos_refl_trans_1n A R2).\n  Proof.\n    unfold inclusion;\n    intros R1 R2 H x y x_y;\n    induction x_y; crush; autoSpecialize; crush.\n  Qed.\n  #[local] Hint Resolve monotonicity_rt : KBaseHints.\n\n  Theorem preserve_rt : forall (R : relation A) (f : A -> A) x y,\n    (forall x y, R x y -> R (f x) (f y)) ->\n    clos_refl_trans_1n A R x y -> clos_refl_trans_1n A R (f x) (f y).\n  Proof.\n    intros R f x y H x_y;\n    induction x_y; crush.\n  Qed.\n\n  Theorem preserve_rt_left : forall (R : relation A) (f : A -> A -> A) x1 x2 z,\n    (forall x1 x2 z, R x1 x2 -> R (f x1 z) (f x2 z)) ->\n    clos_refl_trans_1n A R x1 x2 -> \n    clos_refl_trans_1n A R (f x1 z) (f x2 z).\n  Proof.\n    intros R f x1 x2 z HLeft x1_x2.\n    exact (preserve_rt R (fun x => f x z) x1 x2 \n      (fun x1 x2 x1_x2 => HLeft x1 x2 z x1_x2) x1_x2).\n  Qed.\n  #[local] Hint Resolve preserve_rt_left : KBaseHints.\n\n  Theorem preserve_rt_right : forall (R : relation A) (f : A -> A -> A) x z1 z2,\n    (forall x z1 z2, R z1 z2 -> R (f x z1) (f x z2)) ->\n    clos_refl_trans_1n A R z1 z2 -> \n    clos_refl_trans_1n A R (f x z1) (f x z2).\n  Proof.\n    intros R f x z1 z2 HRight z1_z2;\n    exact (preserve_rt R (fun z => f x z) z1 z2 \n      (fun z1 z2 z1_z2 => HRight x z1 z2 z1_z2) z1_z2).\n  Qed.\n  #[local] Hint Resolve preserve_rt_right : KBaseHints.\n\n  Theorem preserve_rt_para : forall (R : relation A) (f : A -> A -> A) x1 x2 z1 z2,\n    (forall x1 x2 z, R x1 x2 -> R (f x1 z) (f x2 z)) ->\n    (forall x z1 z2, R z1 z2 -> R (f x z1) (f x z2)) ->\n    clos_refl_trans_1n A R x1 x2 -> \n    clos_refl_trans_1n A R z1 z2 -> \n    clos_refl_trans_1n A R (f x1 z1) (f x2 z2).\n  Proof.\n    intros R f x1 x2 z1 z2 HLeft HRight x1_x2 z1_z2;\n    pose proof (preserve_rt_left R f x1 x2 z1 HLeft  x1_x2) as H1;\n    pose proof (preserve_rt_right R f x2 z1 z2 HRight  z1_z2) as H2.\n    crush.\n  Qed.\n\n  (* Facts about confluence and friend *)\n\n  Theorem confluent_semi_confluent : forall (R : relation A),\n  confluent R -> semi_confluent R.\n  Proof.\n    intros R C x y1 y2 x_y1 x_y2;\n    destruct (C x y1 y2 (clos_rt1n_step _ _ _ _ x_y1) x_y2);\n    ecrush.\n  Qed.\n\n  Theorem semi_confluent_confluent : forall (R : relation A),\n  semi_confluent R -> confluent R.\n  Proof.\n    unfold semi_confluent.\n    intros R D x y1 y2 y1H; generalize dependent y2.\n    induction y1H as [x | x y z x_y y_z H]; \n    intros y2 x_y2; unfold joinable.\n    - ecrush.\n    - destruct (D x y y2 x_y x_y2) as [u [y_u y2_u]];\n      destruct (H u y_u) as [v [z_v u_v]];\n      ecrush.\n  Qed. \n  #[local] Hint Resolve semi_confluent_confluent : KBaseHints.\n\n  Lemma diamond_semi_confluent : forall (R : relation A),\n    diamond R ->\n    semi_confluent R.\n  Proof.\n    intros R D x y1 y2 x_y1 x_y2; generalize dependent y1;\n    induction x_y2 as [x | x y2 z2 x_y2 y2_z2 H]; \n    intros y1 x_y1; unfold joinable.\n    - ecrush.\n    - destruct (D x y1 y2 x_y1 x_y2) as [u [y1_u y2_u]].\n      destruct (H u y2_u);\n      ecrush.\n  Qed.\n  #[local] Hint Resolve diamond_semi_confluent : KBaseHints.\n\n  Lemma sandwich_same_rt : forall R1 R2,\n    inclusion A R1 R2 ->\n    inclusion A R2 (clos_refl_trans_1n A R1) ->\n    same_relation A (clos_refl_trans_1n A R1) (clos_refl_trans_1n A R2).\n  Proof.\n    intros R1 R2 H1 H2;\n    pose proof (monotonicity_rt R1 R2 H1) as H3;\n    pose proof (monotonicity_rt R2 (clos_refl_trans_1n A R1) H2) as H4;\n    pose proof (idempotence_rt R1) as [_ H5];\n    split; ecrush.\n  Qed.\n  #[local] Hint Resolve sandwich_same_rt : KBaseHints.\n\n  Lemma sandwich_confluence : forall R1 R2,\n    inclusion A R1 R2 ->\n    inclusion A R2 (clos_refl_trans_1n A R1) ->\n    confluent R1 <-> confluent R2.\n  Proof.\n    intros R1 R2 R1inR2 R2inR1rt; \n    destruct (sandwich_same_rt _ _ R1inR2 R2inR1rt) as [H1 H2];\n    split; \n    intros C x y z x_y x_z; unfold joinable.\n    - assert (x_y_1 : clos_refl_trans_1n A R1 x y) by crush.\n      assert (x_z_1 : clos_refl_trans_1n A R1 x z) by crush.\n      destruct (C x y z x_y_1 x_z_1).\n      ecrush.\n    - assert (x_y_2 : clos_refl_trans_1n A R2 x y) by crush.\n      assert (x_z_2 : clos_refl_trans_1n A R2 x z) by crush.\n      destruct (C x y z x_y_2 x_z_2).\n      ecrush.\n  Qed.\n  #[local] Hint Resolve sandwich_confluence : KBaseHints.\n\n  Lemma sandwich_diamond : forall R1 R2,\n    inclusion A R1 R2 ->\n    inclusion A R2 (clos_refl_trans_1n A R1) ->\n    diamond R2 -> confluent R1.\n  Proof.\n    intros R1 R2 H1 H2 D;\n    assert (H : confluent R2) by crush;\n    pose proof (sandwich_confluence R1 R2 H1 H2) as H3;\n    crush.\n  Qed.\n  #[local] Hint Resolve sandwich_diamond : KBaseHints.\n\n  Theorem confluent_locally_confluent : forall (R : relation A),\n  confluent R -> locally_confluent R.\n  Proof.\n    intros R C x y1 y2 x_y1 x_y2;\n    destruct (C x y1 y2 (clos_rt1n_step _ _ _ _ x_y1) (clos_rt1n_step _ _ _ _ x_y2));\n    ecrush.\n  Qed.\n\n  (* Facts about reducibility, normal forms and friends *)\n\n  Theorem nf_terminal : forall (R : relation A) x,\n    normal R x -> terminal R x x.\n  Proof.\n    unfold terminal; crush.\n  Qed.\n  #[local] Hint Resolve nf_terminal : KBaseHints.\n\n  Theorem nf_rt_equal : forall (R : relation A) x y,\n    normal R x -> \n    clos_refl_trans_1n A R x y -> x = y.\n  Proof.\n    unfold normal; unfold reducible; \n    intros R x H y x_y; induction x_y; crush;\n    exfalso; eauto.\n  Qed.\n  #[local] Hint Resolve nf_rt_equal : KBaseHints.\n\n  Theorem nf_terminal_equal : forall (R : relation A) x y,\n    normal R x -> \n    terminal R x y -> x = y.\n  Proof.\n    unfold terminal; ecrush.\n  Qed. \n  #[local] Hint Resolve nf_terminal_equal : KBaseHints.\n\n  Theorem terminal_step : forall (R : relation A) x y z,\n    R x y -> terminal R y z -> terminal R x z.\n  Proof.\n    unfold terminal; ecrush.\n  Qed.\n\n  Lemma normal_step_false : forall (R : relation A) x y,\n    normal R x -> R x y -> False.\n  Proof.\n    unfold normal; unfold reducible; intros; ecrush.\n  Qed.\n  #[local] Hint Resolve normal_step_false : KBaseHints.\n\n  Theorem confluent_unique_nf : forall (R : relation A),\n    confluent R -> \n    forall x y z, terminal R x y -> terminal R x z -> y = z.\n  Proof.\n    intros R C x y z Ty Tz.\n    destruct Ty as [x_y nfy].\n    destruct Tz as [x_z nfz].\n    destruct (C x y z x_y x_z) as [u [y_u z_u]].\n    rewrite (nf_rt_equal R y u nfy y_u).\n    rewrite (nf_rt_equal R z u nfz z_u).\n    auto.\n  Qed.\n\n  Theorem terminating_confluence : forall (R : relation A),\n    terminating R ->\n    locally_confluent R ->\n    confluent R.\n  Proof.\n    intros R SNR C x; induction (SNR x) as [x H1 H2];\n    intros y z x_y x_z; unfold joinable;\n    destruct x_y as [| y y1 x_y y_y1 ].\n    - ecrush.\n    - destruct x_z as [| z z1 x_z z_z1].\n      * ecrush.\n      * destruct (C x y z x_y x_z) as [u [y_u z_u]].\n        destruct (H2 y x_y y1 u y_y1 y_u) as [y' [y1_y' u_y']]. \n        destruct (H2 z x_z z1 u z_z1 z_u) as [z' [z1_z' z_z']].\n        assert (H3 : clos_refl_trans_1n A R y z') by crush.\n        assert (H4 : clos_refl_trans_1n A R y y') by crush.\n        destruct (H2 y x_y z' y' H3 H4) as [t [z'_t y'_t]].\n        exists t; crush.\n  Qed.\n\n  (* Facts triangle operators and normalizer *)\n\n  Theorem triangle_diamond : forall (R : relation A) (f : A -> A),\n    triangle_op R f ->\n    diamond R.\n  Proof.\n    unfold triangle_op;\n    intros R f Tf x y z x_y x_z;\n    exists (f x); crush.\n  Qed.\n  #[local] Hint Resolve triangle_diamond : KBaseHints.\n\n  Theorem triangle_confluent : forall (R1 R2 : relation A) (f : A -> A),\n    inclusion A R1 R2 ->\n    inclusion A R2 (clos_refl_trans_1n A R1) ->\n    triangle_op R2 f ->\n    confluent R1.\n  Proof.\n    ecrush.\n  Qed.\n\nEnd Properties.\n\n#[global]\nHint Resolve \n  idempotence_rt\n  monotonicity_rt\n  preserve_rt\n  preserve_rt_left\n  preserve_rt_right\n  preserve_rt_para\n  diamond_semi_confluent\n  semi_confluent_confluent\n  nf_terminal\n  normal_step_false\n  confluent_unique_nf\n  terminating_confluence \n  nf_terminal_equal\n  nf_rt_equal\n  triangle_confluent\n  triangle_diamond\n  sandwich_diamond\n  sandwich_confluence \n  sandwich_same_rt : KBaseHints.\n\n#[global]\nHint Unfold joinable reducible normal terminal WN : KBaseHints.\n\n#[global]\nHint Extern 1 (terminal ?R ?x ?z) =>\nmatch goal with\n  | H: terminal ?R ?y z |- _ => apply (terminal_step R x y z)\n  | H: R x ?y |- _ => apply (terminal_step R x y z H)\n  end : KBaseHints.", "meta": {"author": "archambaultv", "repo": "KBase", "sha": "9e555c908979cb46838265278ac601c7ffcbf40d", "save_path": "github-repos/coq/archambaultv-KBase", "path": "github-repos/coq/archambaultv-KBase/KBase-9e555c908979cb46838265278ac601c7ffcbf40d/coq/Relations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516187, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6852149324212731}}
{"text": "(**********************************************************************)\n(*  v      *   Burrows-Wheeler transform defined in Coq.              *)\n(* <O___,, *   Coquistadores  -  Copyright (c) 2017                   *)\n(*   \\VV/  ************************************************************)\n(*    //   *   Authors:   Alan Padilla Chua, Hanlin He                *)\n(*         *              Paul Parrot, Sourav Dasgupta                *)\n(**********************************************************************)\n\nRequire Import List Nat Arith.\nRequire Import Ascii String.\nRequire Import Datatypes.\nRequire Import FunctionalExtensionality.\n\n(*Local Open Scope char_scope.*)\nLocal Open Scope string_scope.\nOpen Scope bool_scope.\n\n(** Define type for [char], [str], [str_matrix]. *)\nDefinition char := option nat.\nDefinition str := nat -> char.\nDefinition str_matrix := nat -> str.\n\nDefinition eqdec (A:Type) := forall x y:A, {x=y}+{x<>y}.\n\n(** A generic \"update\" function for mapping \"nat -> A\". *)\n(* Note: The definition might be generalized again to update mapping \"A -> B\",\n * but it would require to implement or pass as input an alternative comparing\n * function other than \"Nat.eqb\". *)\n\n\nDefinition update {A : Type} (f : nat -> A) (x: nat) (y: A) : nat -> A := \n  fun (n : nat) => if Nat.eq_dec n x then y else f n.\n\n(** Transform a string to a list of ascii. *)\nFixpoint string_to_list (s : string): list ascii := \n  match s with\n  | EmptyString => nil\n  | String h t => h :: string_to_list t\n  end.\n\n(** Map ascii to nat in a list. *)\nFixpoint ascii_to_nat_list (l : list ascii) : list char :=\n  match l with\n  | nil => nil\n  | h :: t => Some (nat_of_ascii h) :: ascii_to_nat_list t\n  end.\n\n(** Transform a nat list to a index -> nat mapping, i.e. nat -> option nat. *)\nFixpoint list_to_map (l : list char) (start_index : nat) : str :=\n  match l with\n  | nil => fun _ => None\n  | h :: t => update (list_to_map t (S start_index)) start_index h\n  end.\n\n(** Use function defined above, generate a index to nat mapping from given string. *)\nDefinition string_to_map (word : string) : str :=\n  list_to_map (ascii_to_nat_list (string_to_list word)) O.\n\n(** helper functions **)\n(* \"option_ascii_of_nat_option : option nat -> option ascii\" using library function \"ascii_of_nat : nat -> ascii\". *)\nDefinition option_ascii_of_nat_option (n : char) : option ascii :=\n  match n with\n  | None => None\n  | Some n' => Some (ascii_of_nat n')\n  end.\n(* \"option_nat_of_ascii_option : option ascii -> option nat\" using library function \"nat_of_ascii : ascii -> nat\". *)\nDefinition option_nat_of_ascii_option (a : option ascii) : char :=\n  match a with\n  | None => None\n  | Some a' => Some (nat_of_ascii a')\n  end.\n\n(*  Alternative definition of \"string_to_map\", which use library function\n    \"get : nat -> string -> option ascii\" directly. *)\nDefinition string_to_map' (word : string) : str :=\n  fun n => option_nat_of_ascii_option (get n word).\n\n(*  Mirror theorem for \"ascii_nat_embedding\" with option. *)\nTheorem ascii_nat_embedding_option :\n  forall a : option ascii, option_ascii_of_nat_option (option_nat_of_ascii_option a) = a.\nProof.\n  intros.\n  destruct a.\n  - simpl. rewrite -> ascii_nat_embedding. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(** Test \"string_to_map\". **)\nDefinition hello_world_str := \"Hello World!\".\nDefinition cat_str := \"Cat\".\n\nDefinition hello_world := string_to_map hello_world_str.\nDefinition hello_world_length := String.length hello_world_str.\n\nDefinition cat := string_to_map cat_str.\nDefinition cat_length := String.length cat_str.\n\n(** Prove that if given \"list_to_map\" a different index, to get the same element,\n    the parameter to the mapping should change the same difference. *)\nLemma list_to_map_index_difference:\n  forall (l : list char) (m n : nat),\n    (list_to_map l m) n = (list_to_map l (S m)) (S n).\nProof.\n  induction l; intros; simpl.\n  - reflexivity.\n  - unfold update. simpl. destruct (Nat.eq_dec n m).\n    + reflexivity.\n    + specialize (IHl (S m) n). exact IHl.\nQed.\n\n(** Prove that if prepend a character to a string, to get the same character again,\n    increase the index by 1. *)\nLemma prepend_string_to_map: \n  forall (s : string) (n : nat) (a : ascii),\n    string_to_map s n = string_to_map (String a s) (S n).\nProof.\n  unfold string_to_map.\n  induction s; induction n; simpl; unfold update; simpl.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - rewrite list_to_map_index_difference. reflexivity.\nQed.\n\n(** Prove the \"string_to_map\" create right mapping. **)\nTheorem String_to_Map:\n  forall (s : string) (n : nat),\n    option_ascii_of_nat_option (string_to_map s n) = String.get n s.\nProof.\n  induction s; intro n.\n  - simpl. reflexivity.\n  - destruct n; simpl.\n    + rewrite -> ascii_nat_embedding. reflexivity.\n    + rewrite <- prepend_string_to_map. specialize (IHs n). exact IHs.\nQed.\n\n(** Prove the \"string_to_map'\" create right mapping, might be trivial. **)\nTheorem String_to_Map':\n  forall (s : string) (n : nat),\n    option_ascii_of_nat_option (string_to_map' s n) = String.get n s.\nProof.\n  induction s; intros; simpl.\n  - reflexivity.\n  - induction n; unfold string_to_map'; simpl.\n    + rewrite -> ascii_nat_embedding. reflexivity.\n    + rewrite -> ascii_nat_embedding_option. reflexivity.\nQed.\n\n(* Following implementation relies on length of the string,\nwhich is hard to compute directly from the mapping,\nso the previously computed value used here (not good). *)\n\n(* Right-shift a mapping by one and return a new mapping. *)\nDefinition right_shift (m : str) (l : nat) : str :=\n  fun n =>\n    match n with\n    | O => m l\n    | S n' => m n'\n    end.\n\nExample hello_world_r1 := right_shift hello_world hello_world_length.\nExample hello_world_r2 := right_shift hello_world_r1 hello_world_length.\nExample hello_world_r3 := right_shift hello_world_r2 hello_world_length.\nExample hello_world_r4 := right_shift hello_world_r3 hello_world_length.\nExample hello_world_r5 := right_shift hello_world_r4 hello_world_length.\n\nCompute option_ascii_of_nat_option (hello_world_r1 0).\nCompute option_ascii_of_nat_option (hello_world_r2 1).\nCompute option_ascii_of_nat_option (hello_world_r3 1).\nCompute option_ascii_of_nat_option (hello_world_r4 1).\nCompute option_ascii_of_nat_option (hello_world_r5 1).\n\n\n(** String start with index 0. *)\n\n(** Get the first letter. *)\nDefinition first (m : str) : char := m O.\n\n(** Get the last letter. *)\nDefinition last (m : str) (length : nat) : char :=\n  match length with\n  | O => None\n  | S length' => m length'\n  end.\n\nEval compute in last hello_world hello_world_length.\n\n(* functional extensionality *)\n\n(** Generate right-shift permutation matrix of the string mapping. **)\n(*  Helper recursion definition, which keeps a constant length through recursion. *)\nFixpoint map_to_conjugacy' (m : str) (l length: nat) := (* Define the actual recursive function, induction on l. *)\n    match l with\n    | O => update (fun _ _ => None) O m\n    | S l' => let l'_conjugacy := map_to_conjugacy' m l' length in\n              update l'_conjugacy l (right_shift (l'_conjugacy l') length)\n    end.\n\nDefinition map_to_conjugacy (m : str) (length: nat) : str_matrix :=\n  map_to_conjugacy' m length length.\n\nExample hello_world_matrix := map_to_conjugacy hello_world hello_world_length.\n\nCompute option_ascii_of_nat_option (hello_world_matrix 0 0).\nCompute option_ascii_of_nat_option (hello_world_matrix 1 0).\nCompute option_ascii_of_nat_option (hello_world_matrix 2 0).\nCompute option_ascii_of_nat_option (hello_world_matrix 3 0).\nCompute option_ascii_of_nat_option (hello_world_matrix 3 2).\nCompute option_ascii_of_nat_option (hello_world_matrix 3 3).\n\n(** Extract the last column from the matrix. **)\n(* Originally both \"r\" and \"c\" were passed as parameter, and induction on r.\n * Now only length is passed, and internally a constant \"last_col_index\" was kept,\n * and induction directly on length. *)\n\nFixpoint lasts' (matrix : str_matrix) (row length : nat) :=\n  match row with\n  | O => update (fun _ => None) O (matrix O length)\n  | S row' => update (lasts' matrix row' length) row (matrix row length)\n  end.\n\nDefinition lasts (matrix : str_matrix) (length : nat) : str :=\n  lasts' matrix length length.\n\nExample last_col := lasts hello_world_matrix hello_world_length.\n\nCompute option_ascii_of_nat_option (last_col 0).\nCompute option_ascii_of_nat_option (last_col 1).\nCompute option_ascii_of_nat_option (last_col 2).\nCompute option_ascii_of_nat_option (last_col 3).\nCompute option_ascii_of_nat_option (last_col 11).\n\nFixpoint map_to_string' (len : nat) (i : nat) (map : str) : string :=\n  match len with\n  | O => EmptyString\n  | S len' => match option_ascii_of_nat_option (map i) with\n              | Some a => String a (map_to_string' len' (S i) map)\n              | None => map_to_string' len' (S i) map\n              end\n  end.\n\nDefinition map_to_string (len : nat) (map : str) : string :=\n  map_to_string' len (S O) map.\n\nEval compute in map_to_string hello_world_length last_col.\n\n(** Define whether two [str]s are reverse of each other at lenght \"n\". *)\nDefinition reverse_str (n : nat) (f1 f2 : str) : Prop :=\n  forall (n1 n2: nat), n1 + n2 = n <-> f1 n1 = f2 n2.\n\n(** Define whether two [str]s are the same. *)\nDefinition same_str (f1 f2 : str) : Prop :=\n  forall (n : nat), f1 n = f2 n.\n\n(** Prove that the last column of the right-shift permutation matrix is the reverse of the original string mapping. **)\nTheorem last_col_reverse:\n  forall (s : string) (l : nat) (m : nat -> option nat),\n    l = String.length s -> m = string_to_map s -> reverse_str l m (lasts (map_to_conjugacy m l) l).\nProof.\n  intros.\n  unfold map_to_conjugacy.\n  unfold lasts.\nAbort.\n\n(** Final BWT implementation taking a sort function as input. *)\nDefinition bwt (s : string) (sort: (nat -> nat -> option nat) -> (nat ->  nat -> option nat)) : string :=\n  let s_length := String.length s in\n  let s_map := string_to_map s in\n  let s_matrix := map_to_conjugacy s_map s_length in\n  let sorted_matrix := sort s_matrix in\n  map_to_string s_length (lasts sorted_matrix s_length).\n\n(* An example bwt without sorting. *)\nEval compute in bwt hello_world_str (fun x => x).\n\n\n(** Option nat order. *)\nDefinition optnat_leq (x y : option nat) :=\n  match y with None => True | Some n =>\n    match x with None => False | Some m => m <= n end\n  end.\n\n(** Option nat equility. *)\nDefinition optnat_eqb (a1 a2 : option nat) :=\n  match a1, a2 with\n  | None, None => True\n  | None, _ => False\n  | _, None => False\n  | Some a1', Some a2' => Nat.eqb a1' a2' = true\n  end.\n\n(** Generic sequence leq ordering. *)\nFixpoint leq_seq {A:Type} (eq leq : A -> A -> Prop) (k : nat) (s1 s2 : nat -> A) : Prop :=\n  match k with\n  | O => leq (s1 O) (s2 O)\n  | S m => (eq (s1 O) (s2 O) /\\ leq_seq eq leq m (fun i => s1 (S i)) (fun i => s2 (S i)))\n            \\/ leq (s1 O) (s2 O)\n  end.\n\n(** Generic sequence equility based on leq. *)\nFixpoint eq_seq {A:Type} (eq : A -> A -> Prop) (k : nat) (s1 s2 : nat -> A) : Prop :=\n  match k with\n  | O => eq (s1 O) (s2 O)\n  | S m => eq (s1 O) (s2 O) /\\ eq_seq eq m (fun i => s1 (S i)) (fun i => s2 (S i))\n  end.\n\n(** Option nat sequence leq ordering based on leq_seq. *)\nDefinition leq_optnatctx (k : nat) (s1 s2 : str) : Prop :=\n  leq_seq optnat_eqb optnat_leq k s1 s2.\n\n(** Option nat sequence equility  based on eq_seq. *)\nDefinition eq_optnatctx (k : nat) (s1 s2 : str) : Prop :=\n  eq_seq optnat_eqb k s1 s2.\n\n(** String matrix sequence equility  based on eq_seq. *)\nDefinition eq_matrix (k : nat) (s1 s2 : str_matrix) : Prop :=\n  eq_seq (eq_optnatctx k) k s1 s2.\n\n(** String leq ordering for all context. *)\nDefinition leq_optnatseq s1 s2 := forall k, leq_optnatctx k s1 s2.\n\n(** The image of function f is sorted with respect to order relation R. *)\nDefinition sorted {A:Type} (R: A -> A -> Prop) (f: nat -> A) :=\n  forall i, R (f i) (f (S i)).\n\n(* If relation R is reflexive and transitive, then image(f)'s ordering is also transitive. *)\nDefinition reflexive {A:Type} (R: A -> A -> Prop) :=\n  forall a, R a a.\n\nDefinition transitive {A:Type} (R: A -> A -> Prop) :=\n  forall a c b, R a b -> R b c -> R a c.\n\nTheorem sorted_transitive {A:Type}\n  (R: A -> A -> Prop) (RE: reflexive R) (TR: transitive R) :\n  forall (f: nat -> A) (SRT: sorted R f) i j, i <= j -> R (f i) (f j).\nProof.\n  intros f SRT i j. revert i. induction j; intros; inversion H.\n    apply RE.\n    apply RE.\n    eapply TR. apply IHj. assumption. apply SRT.\nQed.\n\n(* Permutation functions are injective and surjective. *)\nDefinition injective {A B:Type} (f: A -> B) :=\n  forall i j, f i = f j -> i=j.\n\nDefinition surjective {A B:Type} (f: A -> B) :=\n  forall j, exists i, f i = j.\n\nDefinition bijective {A B:Type} (f: A -> B) :=\n  injective f /\\ surjective f.\n\n\n\n(* Return the character at position i of string m *)\nDefinition lambda (m:nat -> option nat) (i:nat) := m i.\n\n(* Returns the position of an alphabet 'char' in string 'm' of length 'length' *)\nFixpoint get_pos (eq:eqdec (option nat)) (m:nat -> option nat) (length:nat) (char: option nat) : nat :=\n  match length with\n  |0 => if (eq (m 0) char) then 0 else (S length)\n  |S l => if (eq (m length) char) then length else (get_pos eq m l char)\n  end. \n\n(* Introduce sorted string as assumption, not sort it inside. *)\nDefinition pi (eq:eqdec (option nat)) (length:nat) (m sorted_m: str) : (nat -> nat):=\nfun (x:nat) => get_pos eq (sorted_m) length (m x).\n\nDefinition context (k:nat) (m: nat -> (option nat)) : (nat -> (option nat)) :=\nfun (x:nat) => if (x <? k) then (m x) else None.\n\n(* Use [pi'] instead of [pi]. *)\nFixpoint inverse_bwt' (eq:eqdec (option nat)) (tot_length:nat) (i k:nat) (m sorted_m :nat -> (option nat)) : (nat-> nat) :=\nlet p' := (pi eq k m sorted_m) in\nlet f := fun _ => (S tot_length) in\nmatch k with\n|O => f\n|S l => let rec :=  (inverse_bwt' eq tot_length i l m sorted_m) in \n       update rec k (p'(rec l)) (*  (lambda m ((pi eq l sort rec) k))   *)\nend.\n\n(** Use [inverse_bwt']. *)\nDefinition inverse_bwt (eq:eqdec (option nat)) (tot_length:nat) (i k:nat) (m sorted_m: str) :=\nfun n => lambda m (inverse_bwt' eq tot_length i k m sorted_m n).\n\n(* We tried to define what is a sorted string and string matrix. *)\nDefinition sorted_str (m m_sorted: str) (k : nat) : Prop := True.\nDefinition sorted_matrix (matrix : str_matrix) (k : nat) : Prop := True.\n\n(* Length is then a property like the following: *)\nDefinition haslen {A:Type} (f : nat -> option A) (len: nat) :=\n  (*forall i, len <= i <-> f i = None.*)\n  forall l, l > len -> f l = None.\n\nDefinition prepend (s : str) (c : option nat) : str :=\n  fun n =>\n    match n with\n    | O => c\n    | S n' => s n'\n    end.\n\nDefinition concat (s1 s2: str) (l1 l2 : nat) : str :=\n  fun n => if leb n l1 then s1 n else s2 (n - l1).\n\n(** Right shift is equivalent with prepend last letter. *)\nLemma context_k (w: str_matrix) (L : str) (length : nat) :\n  forall (k i : nat),\n    k <= length ->\n    i <= length ->\n    same_str (context (S k) (right_shift (w i) length)) (prepend (context k (w i)) (lambda L i)).\nProof.\n  induction k.\n  - intros. unfold right_shift.\nAdmitted.\n\nDefinition right_shift_matrix (w: str_matrix) (length : nat) : str_matrix :=\n  fun n => right_shift (w n) length.\n\nLemma Right_Shift (w : str_matrix) (length : nat) (sort : nat -> str_matrix -> str_matrix) :\n  forall t , \n    t < length ->\n    sorted (leq_optnatctx t) w ->\n    eq_matrix (S t) (sort 1 (right_shift_matrix w length)) (sort (S t) (right_shift_matrix w length)).\nProof.\nAdmitted.\n\nLemma sort_matrix (w: str_matrix) (length : nat) (k : nat) (sort : nat -> str_matrix -> str_matrix) (pi : nat -> nat) :\n  sorted_matrix w k ->\n  forall (n : nat), same_str (sort (S k) (right_shift_matrix w length) n) (right_shift (w (pi n)) length).\nProof.\nAdmitted.\n\nTheorem matrix (w1 w2 : str_matrix) (L L_sorted: str) (length : nat) (eq:eqdec (option nat)) (k : nat) :\n  forall (i: nat) ,\n    i <= length ->\n    haslen L length ->\n    haslen L_sorted length ->\n    sorted (leq_optnatctx k) w1 ->\n    sorted (leq_optnatctx (S k)) w2 ->\n    same_str L (lasts w1 length) ->\n    sorted_str L L_sorted length ->\n    forall x : nat, x <= k -> same_str (context x (w1 i)) (inverse_bwt eq length i x L L_sorted).\nProof.\n  induction x.\n  intros. \n  unfold same_str.\n  unfold context.\n  unfold inverse_bwt.\n  intro n. destruct n; simpl.\n  unfold lambda. rewrite H0. reflexivity. auto.\n  unfold lambda. rewrite H0. reflexivity. auto.\nAbort.\n\n", "meta": {"author": "alanpadillachua", "repo": "CS6301LBS", "sha": "28c29a696b90151efb18390e3c216a7fa837f346", "save_path": "github-repos/coq/alanpadillachua-CS6301LBS", "path": "github-repos/coq/alanpadillachua-CS6301LBS/CS6301LBS-28c29a696b90151efb18390e3c216a7fa837f346/bwt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.6852149273568936}}
{"text": "(* Exercise 119 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\nTheorem exercise_119 : ~~A -> ~~(A \\/ B).\nProof.\nimp_i a1.\nneg_i (~A) a2.\nhyp a1.\nneg_i (A \\/ B) a3.\nhyp a2.\ndis_i1.\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_prop119.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107843878722, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6851559784197304}}
{"text": "(* ************************************************************************** *)\n(*                                                                            *)\n(* Verified Flash Translation Layer                                           *)\n(*                                                                            *)\n(*                                                                            *)\n(*   Author: Yu Guo <aciclo@gmail.com>                                        *)\n(*                                        Computer Science Department, USTC   *)\n(*                                                                            *)\n(*           Hui Zhang <sa512073@mail.ustc.edu.cn>                            *)\n(*                                     School of Software Engineering, USTC   *)\n(*                                                                            *)\n(* ************************************************************************** *)\n\n(* Version 0.1 *)\n\nRequire Export Bool.\nRequire Import Arith.\n\n(* *********************************************************** *)\n\nTheorem nat_eq_dec : forall a b : nat, {a = b} + {a <> b}.\nProof.\n  intros; compare a b; auto.\nQed.\n\n(* *********************************************************** *)\n\nFixpoint blt_nat (n m : nat) {struct n} : bool :=\n  match n, m with\n  | O, O => false\n  | O, S _ => true\n  | S _, O => false\n  | S n', S m' => blt_nat n' m'\n  end.\n\nLemma blt_irrefl :\n  forall a : nat, blt_nat a a = false.\nProof.\n  induction a; simpl; auto.\nQed.\n\nLemma blt_irrefl_Prop :\n  forall a : nat, ~ (blt_nat a a = true).\nProof.\n  induction a; simpl; auto.\nQed.\n\nLemma blt_asym :\n  forall a b : nat, blt_nat a b = true\n    -> blt_nat b a = false.\nProof.\n  double induction a b; simpl; intros; auto.\nQed.\n\nLemma blt_O_Sn : \n  forall n : nat, blt_nat O (S n) = true.\nProof.\n  induction n; simpl; auto.\nQed.\n\nLemma blt_n_O : forall n,\n  blt_nat n O = false.\nProof.\n  induction n; simpl; auto.\nQed.\n\nLemma not_blt_n_O :\n  forall n : nat, ~ (blt_nat n 0 = true).\nProof.\n  induction n; simpl; auto.\nQed.\n\nLemma blt_true_lt : \n  forall a b : nat, blt_nat a b = true -> a < b.\nProof.\n  double induction a b; simpl; intros; \n    auto with arith; try discriminate.\nQed.\n\nLemma blt_false_le :\n  forall n m, blt_nat n m = false -> m <= n.\nProof.\n  double induction n m; simpl; intros; \n    auto with arith; discriminate.\nQed.\n\nLemma le_blt_false :\n  forall n m, n <= m -> blt_nat m n = false.\nProof.\n  double induction n m; simpl; intros; \n    auto with arith.\n  destruct (lt_n_O _ H0).\nQed.\n\nLemma lt_blt_true : \n  forall a b : nat, a < b -> blt_nat a b = true.\nProof.\n  double induction a b; simpl; intros; \n    auto with arith.\n  destruct (lt_irrefl 0 H).\n  destruct (lt_n_O (S n) H0).\nQed.\n\nLemma blt_n_Sn : \n  forall n : nat, blt_nat n (S n) = true.\nProof.\n  induction n; simpl; intros; auto with arith.\nQed.\n\nLemma blt_S_eq :\n  forall a b, blt_nat a b = blt_nat (S a) (S b).\nProof.\n  trivial.\nQed.\n\nLemma blt_n_Sm :\n  forall n m, blt_nat n m = true \n    -> blt_nat n (S m) = true.\nProof.\n  double induction n m; simpl; intros; auto with arith.\n  discriminate.\nQed.\n\nLemma blt_n_mk :\n  forall n m k, blt_nat n m = true\n    -> blt_nat n (m + k) = true.\nProof.\n  double induction n m; simpl; intros; \n    auto with arith;  discriminate.\nQed.\n\nLemma blt_n_km :\n  forall n m k, blt_nat n m = true\n    -> blt_nat n (k + m) = true.\nProof.\n  double induction n m; simpl; intros; \n    auto with arith; try discriminate.\n  replace (k + (S n0)) with ((S n0) + k);\n    [idtac | auto with arith].\n  simpl. trivial.\n  replace (k + (S n0)) with ((S n0) + k);\n    [idtac | auto with arith].\n  simpl. \n  replace (n0 + k) with (k + n0);\n    [idtac | auto with arith].\n  apply H0; trivial.\nQed.\n\nLemma blt_nat_dec : forall a b,\n  {blt_nat a b = true} + {blt_nat a b = false}.\nProof.\n  double induction a b; simpl; intros; try tauto || auto.\nQed.\n\n\n(* *********************************************************** *)\n\nDefinition ble_nat (n m : nat) : bool := \n  match blt_nat m n with \n    | true => false \n    | false => true\n  end.\n\n(* *********************************************************** *)\n\nFixpoint beq_nat (n m : nat)  {struct n} : bool :=\n  match n, m with\n  | O, O => true\n  | O, S _ => false\n  | S _, O => false\n  | S n1, S m1 => beq_nat n1 m1\n  end.\n\nLemma beq_refl : forall m, beq_nat m m = true.\nProof.\n  induction m; simpl; intros; auto.\nQed.\n\nLemma beq_trans : forall m n k, beq_nat m n = true\n  -> beq_nat n k = true \n  -> beq_nat m k = true.\nProof.\n  induction m; induction n; destruct k; \n    simpl; intros; discriminate || auto.\n  eapply IHm; eauto.\nQed.\n\nLemma beq_sym : forall m n b, \n  beq_nat m n = b -> beq_nat n m = b.\nProof.\n  double induction n m; simpl; intros; \n    auto with arith; discriminate.\nQed.\n\nLemma beq_sym2 : forall m n, \n  beq_nat m n = beq_nat n m.\nProof.\n  double induction n m; simpl; intros; \n    auto with arith; discriminate.\nQed.\n\nLemma beq_true_eq :\n  forall n m, beq_nat n m = true\n    -> n = m.\nProof. \n  double induction n m; simpl; intros; \n    auto with arith; discriminate.\nQed.\n\nLemma beq_false_neq :\n  forall n m, beq_nat n m = false\n    -> ~ (n = m).\nProof.\n  double induction n m; simpl; intros; \n    auto with arith; discriminate.\nQed.\n\nLemma eq_beq_true :\n  forall n m, n = m\n    -> beq_nat n m = true.\nProof. \n  double induction n m; simpl; intros; \n    auto with arith; discriminate.\nQed.\n\nLemma neq_beq_false :\n  forall n m, ~ (n = m) \n    -> beq_nat n m = false.\nProof.\n  double induction n m; simpl; intros; \n    auto with arith.\n  destruct (H (refl_equal _)).\nQed.\n\nLemma beq_nat_dec : forall a b,\n  {beq_nat a b = true} + {beq_nat a b = false}.\nProof.\n  double induction a b; simpl; intros; try tauto || auto.\nQed.\n\n(* *********************************************************** *)\n\nLemma blt_t_beq_f : \n  forall m n, blt_nat m n = true \n    -> beq_nat m n = false.\nProof.\n  double induction n m; simpl; intros; auto with arith.\nQed.\n\nLemma bgt_t_beq_f :\n  forall m n, blt_nat n m = true\n    -> beq_nat m n = false.\nProof.\n  double induction m n; simpl; intros; auto with arith.\nQed.\n\nLemma beq_t_blt_f : \n  forall m n, beq_nat m n = true\n    -> blt_nat m n = false. \nProof.\n  double induction m n; simpl; intros; auto with arith.\nQed.\n\nLemma beq_t_bgt_f :\n  forall m n, beq_nat m n = true\n    -> blt_nat n m = false.\nProof.\n  double induction n m; simpl; intros; auto with arith.\nQed.\n\nLemma blt_S_dec : \n  forall n m,\n    blt_nat n (S m) = true \n    -> blt_nat n m = true \\/ beq_nat n m = true.\nProof.\n  intros n m H.\n  assert (Hx:=blt_true_lt _ _ H).\n  apply lt_n_Sm_le in Hx.\n  apply le_lt_or_eq_iff in Hx.\n  destruct Hx.\n    left. \n    apply lt_blt_true; trivial.\n  right.\n  apply eq_beq_true; trivial.\nQed.\n\n(* *********************************************************** *)\n\nDefinition max_nat (m n : nat) : nat :=\n  if blt_nat m n then n else m.\n\nLemma max_nat_elim_l : forall m n : nat,\n  m <= max_nat m n.\nProof.\n  unfold max_nat; intros m n.\n  destruct (blt_nat_dec m n) as [Hb | Hb]; rewrite Hb.\n  assert (Hb' := blt_true_lt m n Hb).\n  auto with arith.\n  auto with arith.\nQed.\n\nLemma max_nat_elim_r : forall m n : nat,\n  n <= max_nat m n.\nProof.\n  unfold max_nat; intros m n.\n  destruct (blt_nat_dec m n) as [Hb | Hb]; rewrite Hb.\n  auto with arith.\n  assert (Hb' := blt_false_le m n Hb).\n  auto with arith.\nQed.\n\n(* *********************************************************** *)\n\nLtac rewrite_bnat t :=\n  match type of t with\n    | blt_nat ?a ?b = ?c => rewrite t\n    | beq_nat ?a ?b = ?c => rewrite t\n  end.\n\nLtac rewrite_bnat_H t H :=\n  match type of t with\n    | blt_nat ?a ?b = ?c => rewrite t in H\n    | beq_nat ?a ?b = ?c => rewrite t in H\n  end.\n\nLtac rewrite_bnat_all t :=\n  match goal with \n    | |- context[(blt_nat ?a ?b)] => rewrite_bnat t; rewrite_bnat_all t\n    | H : context[(blt_nat ?a ?b)] |- _ => rewrite_bnat_H t H; rewrite_bnat_all t\n    | |- context[(beq_nat ?a ?b)] => rewrite_bnat t; rewrite_bnat_all t\n    | H : context[(beq_nat ?a ?b)] |- _ => rewrite_bnat_H t H; rewrite_bnat_all t\n    | _ => idtac\n  end.\n\nLtac simplbnat := \n  match goal with\n    (* blt rewrite directly *)\n    | [H : blt_nat ?x ?y = ?f\n      |- context [(blt_nat ?x ?y)]] =>\n       rewrite H; simplbnat\n    | [H : blt_nat ?x ?y = ?f,\n       H0 : context [(blt_nat ?x ?y)] \n      |- _ ] =>\n       rewrite H in H0; simplbnat\n\n    (* beq rewrite directly *)\n    | [H : beq_nat ?x ?y = ?f \n      |- context [(beq_nat ?x ?y)]] =>\n       rewrite H; simplbnat\n    | [H : beq_nat ?x ?y = ?f,\n       H0 : context [(beq_nat ?x ?y)] |- _ ] =>\n       rewrite H in H0; simplbnat\n         \n    (* blt -> beq *)\n    | [H : blt_nat ?x ?y = true \n      |- context[(beq_nat ?x ?y)]] =>\n      rewrite (blt_t_beq_f x y H); simplbnat\n    | [H : blt_nat ?x ?y = true,\n       H0 : context[(beq_nat ?x ?y)] |- _ ] =>\n      rewrite (blt_t_beq_f x y H) in H0; simplbnat\n     \n    (* bgt -> beq *)\n    | [H : blt_nat ?y ?x = true \n      |- context[(beq_nat ?x ?y)]] =>\n      rewrite (bgt_t_beq_f x y H); simplbnat\n    | [H : blt_nat ?y ?x = true, \n       H0 : context[(beq_nat ?x ?y)] |- _ ] =>\n      rewrite (bgt_t_beq_f x y H) in H0; simplbnat\n         \n    (* beq -> blt *)\n    | [H : beq_nat ?y ?x = true \n      |- context[(blt_nat ?x ?y)]] =>\n      rewrite (beq_t_blt_f x y H); simplbnat\n    | [H : beq_nat ?y ?x = true, \n       H0 : context[(blt_nat ?x ?y)] |- _ ] =>\n      rewrite (beq_t_blt_f x y H) in H0; simplbnat\n         \n    (* beq -> bgt *)\n    | [H : beq_nat ?y ?x = true \n      |- context[(blt_nat ?y ?x)]] =>\n      rewrite (beq_t_bgt_f x y H); simplbnat\n    | [H : beq_nat ?y ?x = true, \n       H0 : context[(blt_nat ?y ?x)] |- _ ] =>\n      rewrite (beq_t_bgt_f x y H) in H0; simplbnat\n\n    (* blt_irrefl *)\n    | [ |- context [blt_nat ?x ?x]] =>\n      rewrite (blt_irrefl x); simplbnat\n    | [H : context [blt_nat ?x ?x] |- _ ] =>\n      rewrite (blt_irrefl x) in H; simplbnat\n\n    (* blt_asym *)\n    | [H : blt_nat ?x ?y = true \n      |- context [blt_nat ?y ?x]] =>\n      rewrite (blt_asym x y H); simplbnat\n    | [H : blt_nat ?x ?y = true,\n       H0 : context [blt_nat ?y ?x] |- _ ] =>\n      rewrite (blt_asym x y H) in H0; simplbnat\n\n    (* blt_O_Sn *)\n    | [ |- context [(blt_nat O (S ?x))]] =>\n      rewrite (blt_O_Sn x); simplbnat\n    | [H : context [(blt_nat O (S ?x))] |- _ ] =>\n      rewrite (blt_O_Sn x) in H; simplbnat\n\n    (* blt_n_O *)\n    | [ |- context [(blt_nat ?x O)]] =>\n      rewrite (blt_n_O x); simplbnat\n    | [H : context [(blt_nat ?x O)] |- _ ] =>\n      rewrite (blt_n_O x) in H; simplbnat\n\n    (* blt_n_Sn *)\n    | [ |- context [(blt_nat ?x (S ?x))]] =>          \n      rewrite (blt_n_Sn x); simplbnat\n    | [H : context [(blt_nat ?x (S ?x))] |- _ ] =>\n      rewrite (blt_n_Sn x) in H; simplbnat\n\n    (* blt_S_eq *)\n    | [ |- context [(blt_nat (S ?x) (S ?y))]] =>\n      rewrite <- (blt_S_eq x y); simplbnat\n    | [H : context [(blt_nat (S ?x) (S ?y))] |- _ ] =>\n      rewrite <- (blt_S_eq x y) in H; simplbnat\n\n    (* blt_n_Sm *)\n    | [H : blt_nat ?x ?y = true\n      |- context [(blt_nat ?x (S ?y))]] =>\n      rewrite (blt_n_Sm x y H); simplbnat\n    | [H : blt_nat ?x ?y = true,              \n       H0 : context [(blt_nat ?x (S ?y))] |- _ ] =>\n      rewrite <- (blt_n_Sm x y H) in H0; simplbnat\n\n    (* blt_n_mk *)\n    | [H : blt_nat ?x ?y = true                       \n      |- context [(blt_nat ?x (?y + ?k))]] =>\n      rewrite (blt_n_mk x y k H); simplbnat\n    | [H : blt_nat ?x ?y = true,              \n       H0 : context [(blt_nat ?x (?y + ?k))] |- _ ] =>\n      rewrite <- (blt_n_mk x y k H) in H0; simplbnat\n\n    (* blt_n_km *)\n    | [H : blt_nat ?x ?y = true                       \n      |- context [(blt_nat ?x (?k + ?y))]] =>\n      rewrite (blt_n_km x y k H); simplbnat\n    | [H : blt_nat ?x ?y = true,              \n       H0 : context [(blt_nat ?x (?k + ?y))] |- _ ] =>\n      rewrite <- (blt_n_km x y k H) in H0; simplbnat\n\n    (* beq_refl *)\n    | [ |- context [(beq_nat ?x ?x)] ] =>\n      rewrite (beq_refl x); simplbnat\n    | [H : context [(beq_nat ?x ?x)] |- _ ] => \n      rewrite (beq_refl x) in H; simplbnat\n\n    (* beq_sym *)\n    | [ H : beq_nat ?x ?y = ?b \n        |- context [(beq_nat ?y ?x)] ] =>\n      rewrite (beq_sym x y b H); simplbnat\n    | [H : beq_nat ?x ?y = ?b,\n       H0 : context [(beq_nat ?y ?x)] |- _ ] => \n      rewrite (beq_sym x y b H) in H0; simplbnat\n\n    | [ H : ?x <> ?y |- context [(beq_nat ?x ?y)] ] => \n      rewrite (neq_beq_false x y H); simplbnat\n    | [ H : ?x <> ?y, \n        H0 : context [(beq_nat ?x ?y)] |- _ ] => \n      rewrite (neq_beq_false x y H) in H0; simplbnat\n\n    | [ H : ?y <> ?x |- context [(beq_nat ?x ?y)] ] => \n      rewrite (neq_beq_false x y (sym_not_eq H)); simplbnat\n    | [ H : ?y <> ?x, \n        H0 : context [(beq_nat ?x ?y)] |- _ ] => \n      rewrite (neq_beq_false x y (sym_not_eq H)) in H0; simplbnat\n        \n    | [H : ?x = ?x |- _ ] => clear H; simplbnat\n    | [H : true = false |- _ ] => discriminate H\n    | [H : false = true |- _ ] => discriminate H\n    | _ => idtac\n  end.\n\nTactic Notation \"bnat simpl\" := simplbnat.\n\nLtac desbnatH H := \n  match goal with\n    | H : blt_nat ?a ?b = true |- _ =>\n        generalize (blt_true_lt a b H); clear H; intro H\n\n    | H : blt_nat ?a ?b = false |- _ =>\n        generalize (blt_false_le a b H); clear H; intro H\n\n    | H : beq_nat ?a ?b = true |- _ =>\n        generalize (beq_true_eq a b H); clear H; intro H\n\n    | H : beq_nat ?a ?b = false |- _ =>\n        generalize (beq_false_neq a b H); clear H; intro H\n\n    | _ => fail 1 \"not bnat found\"\n  end.\n\nLtac desbnat := \n  match goal with\n    | H : blt_nat ?a ?b = true |- _ =>\n        generalize (blt_true_lt a b H); clear H; intro H; desbnat\n\n    | H : blt_nat ?a ?b = false |- _ =>\n        generalize (blt_false_le a b H); clear H; intro H; desbnat\n\n    | H : beq_nat ?a ?b = true |- _ =>\n        generalize (beq_true_eq a b H); clear H; intro H; desbnat\n\n    | H : beq_nat ?a ?b = false |- _ =>\n        generalize (beq_false_neq a b H); clear H; intro H; desbnat\n\n    | _ => idtac\n  end.\n\nLtac conbnat := \n  match goal with\n    | |- blt_nat ?a ?b = true =>\n        apply (lt_blt_true a b)\n\n    | |- blt_nat ?a ?b = false =>\n        apply (le_blt_false b a)\n\n    | |- beq_nat ?a ?b = true =>\n        apply (eq_beq_true a b)\n\n    | |- beq_nat ?a ?b = false =>\n        apply (neq_beq_false a b)\n\n    | _ => fail 1 \"the goal is not bnat\"\n  end.\n\nLtac solvebnat :=\n  desbnat; conbnat; auto with arith.\n\n\n(* *********************************************************** *)\n\nTactic Notation \"rewbnat\" constr (t) :=\n  match t with \n    | beq_nat ?x ?y = ?f =>\n      let Hb := fresh \"Hb\" in\n        (assert (Hb : t); \n          [solvebnat | rewrite Hb; clear Hb])\n    | blt_nat ?x ?y = ?f =>\n      let Hb := fresh \"Hb\" in\n        (assert (Hb : t); \n          [solvebnat | rewrite Hb; clear Hb])\n    | _ =>\n      match type of t with\n        | beq_nat ?x ?y = true => rewrite (beq_true_eq x y t)\n        | _ => rewrite t\n      end\n  end.\n\nTactic Notation \"rewbnat\" constr (t) \"in\" hyp (H) :=\n  match t with \n    | beq_nat ?x ?y = ?f =>\n      let Hb := fresh \"Hb\" in\n        (assert (Hb : t); \n          [solvebnat | rewrite Hb in H; clear Hb])\n    | blt_nat ?x ?y = ?f =>\n      let Hb := fresh \"Hb\" in\n        (assert (Hb : t); \n          [solvebnat | rewrite Hb in H; clear Hb])\n    | _ =>\n      match type of t with\n        | beq_nat ?x ?y = true => rewrite (beq_true_eq x y t) in H\n        | _ => rewrite t in H\n      end\n  end.\n\nTactic Notation \"assertbnat\" constr (t) :=\n  let Hb := fresh \"Hb\" in (\n    match t with \n      | beq_nat ?x ?y = ?f =>\n        (assert (Hb : t); \n            [solvebnat | idtac])\n      | blt_nat ?x ?y = ?f =>\n        (assert (Hb : t); \n            [solvebnat | idtac])\n      | _ => fail 1 \"t must be a blt_nat or beq_nat equation\"\n    end).\n\nLtac discribnat := \n  desbnat; subst;\n  match goal with\n    | H : ?x <> ?x |- _ => destruct (H (refl_equal x))\n    | H : ?x = ?y |- _ => discriminate\n    | H : ?x < ?x |- _ => destruct (lt_irrefl x H)\n    | H : ?x < O |- _ => destruct (lt_n_O x H)\n    | H : beq_nat ?x ?x = false |- _ =>\n      desbnatH H; destruct (H (refl_equal x))\n    | _ => elimtype False; \n        auto with arith || fail 1 \"no discriminatable hypothesis\"\n  end.\n\nLtac substbnat_all := desbnat; subst.\n\nLtac substbnat_one f := desbnat; subst f.\n\nTactic Notation \"substbnat\" := substbnat_all.\n\nTactic Notation \"substbnat\" constr (f) := substbnat_one f.\n\n(*\nSection test.\n\nVariables (a b c d e f g : nat).\nHypotheses \n  (H0 : beq_nat a b = true)\n  (H1 : blt_nat c b = true)\n  (H2 : blt_nat b a = true)\n  (H3 : beq_nat a b = true)\n  (H4 : beq_nat a b = true)\n  (H5 : if beq_nat a b then True else False)\n.\n\nGoal if beq_nat a b then True else False.\nsimplbnat.\nrewrite_bnat_all H0.\nsubstbnat.\nrewbnat H0 in H3.\ninvbnat.\nbnat2nat.\nomega.\nsimplbnat.\n\nEnd test. *)\n\n(* *********************************************************** *)\n\nLtac decbeqnat x y :=\n  let Hb := fresh \"Hb\" in\n    (destruct (beq_nat_dec x y) as [Hb | Hb]; simplbnat).\n\nLtac decbltnat x y :=\n  let Hb := fresh \"Hb\" in\n    (destruct (blt_nat_dec x y) as [Hb | Hb]; simplbnat).\n\n(* *********************************************************** *)\n(* deprecate *)\n\nTactic Notation \"repbnat\" constr (t1) \"with\" constr (t2) :=\n  replace t1 with t2; [idtac | desbnat; auto with arith].\n\nTactic Notation \"repbnat\" constr (t1) \"with\" constr (t2) \"in\" hyp (H) :=\n  replace t1 with t2 in H; [idtac | desbnat; auto with arith].\n\nTactic Notation \"bool_destruct\" hyp (H) \"as\" simple_intropattern (pat) :=\n  let H0 := fresh \"H\" in\n    (rename H into H0;\n    match type of (H0) with\n      | (andb ?a ?b = true) => \n        destruct (andb_prop a b H0) as pat; clear H0\n      | (orb ?a ?b = true) =>\n        destruct (orb_prop a b H0) as pat; clear H0\n      | _ => fail \"not destructable\" \n    end).\n", "meta": {"author": "gy001", "repo": "veriFTL", "sha": "c594b083d12222cd13507acb1bef705f6f2d882e", "save_path": "github-repos/coq/gy001-veriFTL", "path": "github-repos/coq/gy001-veriFTL/veriFTL-c594b083d12222cd13507acb1bef705f6f2d882e/bast0-coq/bnat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.6851504278655061}}
{"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\nFrom Undecidability.Shared.Libs.DLW \n  Require Import utils_tac utils_nat gcd sums pos vec.\n\nSet Implicit Arguments.\n\nSet Default Proof Using \"Type\".\n\nLocal Notation power := (mscal mult 1).\n\nSection div_mult.\n\n  Variable (p q : nat) (Hp : p <> 0) (Hq : q <> 0).\n\n  Fact div_rem_mult n : div n (p*q) = div (div n p) q /\\ rem n (p*q) = rem n p + p*rem (div n p) q.\n  Proof using Hp Hq.\n    assert (p*q <> 0) as Hpq.\n    { intros E; apply mult_is_O in E; lia. }\n    apply div_rem_uniq with (p := p*q); auto.\n    + generalize (div_rem_spec1 n p)\n                 (div_rem_spec1 (div n p) q)\n                 (div_rem_spec1 n (p*q)); intros H1 H2 H3.\n      rewrite <- H3; rewrite H1 at 1; rewrite H2 at 1; ring.\n    + apply div_rem_spec2; auto.\n    + generalize (div_rem_spec2 n Hp)\n                 (div_rem_spec2 (div n p) Hq); intros H1 H2.\n      replace q with (1+(q-1)) at 2 by lia.\n      rewrite Nat.mul_add_distr_l.\n      apply plus_lt_le_compat; try lia.\n      apply mult_le_compat; lia.\n  Qed.\n\n  Corollary div_mult n : div n (p*q) = div (div n p) q.\n  Proof using Hp Hq. apply div_rem_mult. Qed.\n\n  Corollary rem_mult n : rem n (p*q) = rem n p + p*rem (div n p) q.\n  Proof using Hp Hq. apply div_rem_mult. Qed.\n\nEnd div_mult.\n\nSection nat_nat2_bij.\n\n  (* An easy to implement bijection nat <-> nat * nat *)\n\n  Let decomp_recomp_full n : n <> 0 -> { a & { b | n = power a 2 * (2*b+1) } }.\n  Proof.\n    induction on n as IHn with measure n; intros Hn.\n    generalize (euclid_2_div n); intros (H1 & H2).\n    case_eq (rem n 2).\n    + intros H.\n      destruct (IHn (div n 2)) as (a & b & H3); try lia.\n      exists (S a), b.\n      rewrite H1, H, H3, power_S; ring.\n    + intros [ | [ | k ] ] Hk; try lia.\n      exists 0, (div n 2); rewrite power_0.\n      rewrite H1 at 1; rewrite Hk; ring.\n  Qed.\n\n  Definition decomp_l n := projT1 (@decomp_recomp_full (S n) (Nat.neq_succ_0 _)).\n  Definition decomp_r n := proj1_sig (projT2 (@decomp_recomp_full (S n) (Nat.neq_succ_0 _))).\n \n  Fact decomp_lr_spec n : S n = power (decomp_l n) 2 * (2 * (decomp_r n) + 1).\n  Proof. apply (proj2_sig (projT2 (@decomp_recomp_full (S n) (Nat.neq_succ_0 _)))). Qed.\n\n  Definition recomp a b := power a 2 * (2*b+1) - 1.\n  \n  Fact recomp_decomp n : n = recomp (decomp_l n) (decomp_r n).\n  Proof. unfold recomp; rewrite <- decomp_lr_spec; lia. Qed.\n\n  Let power_mult_lt_inj a1 b1 a2 b2 : a1 < a2 -> power a1 2 * (2*b1+1) <> power a2 2 * b2.\n  Proof.\n    intros H1 H.\n    replace a2 with (a1+(S (a2-a1-1))) in H by lia.\n    rewrite power_plus in H.\n    rewrite <- mult_assoc, Nat.mul_cancel_l in H.\n    2: generalize (power2_gt_0 a1); lia.\n    revert H; rewrite power_S, <- mult_assoc.\n    generalize (power (a2-a1-1) 2*b1); intros; lia.\n  Qed.\n\n  Let comp_gt a b : power a 2 *(2*b+1) <> 0.\n  Proof. \n    intros E; apply mult_is_O in E.\n    generalize (power2_gt_0 a); intros; lia.\n  Qed. \n\n  Fact decomp_uniq a1 b1 a2 b2 : power a1 2 * (2*b1+1) = power a2 2 * (2*b2+1) -> a1 = a2 /\\ b1 = b2.\n  Proof.\n    intros H.\n    destruct (lt_eq_lt_dec a1 a2) as [ [ H1 | H1 ] | H1 ].\n    + exfalso; revert H; apply power_mult_lt_inj; auto.\n    + split; auto; subst a2.\n      rewrite Nat.mul_cancel_l in H; try lia.\n      generalize (power2_gt_0 a1); lia.\n    + exfalso; symmetry in H.\n      revert H; apply power_mult_lt_inj; auto.\n  Qed.\n\n  Let decomp_lr_recomp a b : decomp_l (recomp a b) = a /\\ decomp_r (recomp a b) = b.\n  Proof.\n    apply decomp_uniq; symmetry.\n    replace (power a 2 * (2*b+1)) with (S (recomp a b)).\n    + apply decomp_lr_spec.\n    + unfold recomp; generalize (power a 2 * (2*b+1)) (comp_gt a b); intros; lia.\n  Qed.\n\n  Fact decomp_l_recomp a b : decomp_l (recomp a b) = a.\n  Proof. apply decomp_lr_recomp. Qed.\n\n  Fact decomp_r_recomp a b : decomp_r (recomp a b) = b.\n  Proof. apply decomp_lr_recomp. Qed.\n\nEnd nat_nat2_bij.\n\nFixpoint inject n (v : vec nat n) : nat :=\n  match v with\n    | vec_nil => 0\n    | x##v    => recomp x (inject v)\n  end.\n\nFixpoint project n : nat -> vec nat n :=\n  match n with\n    | 0   => fun _ => vec_nil\n    | S n => fun x => decomp_l x ## project _ (decomp_r x)\n  end.\n\nFact project_inject n v : project _ (@inject n v) = v.\nProof.\n  induction v as [ | n x v IHv ]; simpl; auto.\n  rewrite decomp_l_recomp, decomp_r_recomp; f_equal; trivial.\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/MuRec/recomp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.7371581684030624, "lm_q1q2_score": 0.6851445871551272}}
{"text": "Require Export BaseLists Filter.\n\n(** *** Element removal *)\n\nSection Removal.\n  Variable X : eqType.\n  Implicit Types (x y: X) (A B: list X).\n\n  Definition rem A x : list X :=\n    filter (fun z => Dec (z <> x)) A.\n\n  Lemma in_rem_iff x A y :\n    x el rem A y <-> x el A /\\ x <> y.\n  Proof.\n    unfold rem. rewrite in_filter_iff, Dec_reflect. tauto.\n  Qed.\n\n  Lemma rem_not_in x y A :\n    x = y \\/ ~ x el A -> ~ x el rem A y.\n  Proof.\n    unfold rem. rewrite in_filter_iff, Dec_reflect. tauto.\n  Qed.\n\n  Lemma rem_incl A x :\n    rem A x <<= A.\n  Proof.\n    apply filter_incl.\n  Qed.\n\n  Lemma rem_mono A B x :\n    A <<= B -> rem A x <<= rem B x.\n  Proof.\n    apply filter_mono.\n  Qed.\n\n  Lemma rem_cons A B x :\n    A <<= B -> rem (x::A) x <<= B.\n  Proof.\n    intros E y F. apply E. apply in_rem_iff in F.\n    destruct F as [[|]]; congruence.\n  Qed.\n\n  Lemma rem_cons' A B x y :\n    x el B -> rem A y <<= B -> rem (x::A) y <<= B.\n  Proof.\n    intros E F u G. \n    apply in_rem_iff in G as [[[]|G] H]. exact E.\n    apply F. apply in_rem_iff. auto.\n  Qed.\n\n  Lemma rem_in x y A :\n    x el rem A y -> x el A.\n  Proof.\n    apply rem_incl.\n  Qed.\n\n  Lemma rem_neq x y A :\n    x <> y -> x el A -> x el rem A y.\n  Proof.\n    intros E F. apply in_rem_iff. auto.\n  Qed.\n\n  Lemma rem_app x A B :\n    x el A -> B <<= A ++ rem B x.\n  Proof.\n    intros E y F. decide (x=y) as [[]|]; auto using rem_neq.\n  Qed.\n\n  Lemma rem_app' x A B C :\n    rem A x <<= C -> rem B x <<= C -> rem (A ++ B) x <<= C.\n  Proof.\n    unfold rem; rewrite filter_app; auto.\n  Qed.\n\n  Lemma rem_equi x A :\n    x::A === x::rem A x.\n  Proof.\n    split; intros y; \n    intros [[]|E]; decide (x=y) as [[]|D]; \n    eauto using rem_in, rem_neq. \n  Qed.\n\n  Lemma rem_comm A x y :\n    rem (rem A x) y = rem (rem A y) x.\n  Proof.\n    apply filter_comm.\n  Qed.\n\n  Lemma rem_fst x A :\n    rem (x::A) x = rem A x.\n  Proof.\n    unfold rem. rewrite filter_fst'; auto.\n  Qed.\n\n  Lemma rem_fst' x y A :\n    x <> y -> rem (x::A) y = x::rem A y.\n  Proof.\n    intros E. unfold rem. rewrite filter_fst; auto.\n  Qed.\n\n  Lemma rem_id x A :\n    ~ x el A -> rem A x = A.\n  Proof.\n    intros D. apply filter_id. intros y E.\n    apply Dec_reflect. congruence.\n  Qed.\n\n  Lemma rem_reorder x A :\n    x el A -> A === x :: rem A x.\n  Proof.\n    intros D. rewrite <- rem_equi. apply equi_push, D.\n  Qed.\n\n  Lemma rem_inclr A B x :\n    A <<= B -> ~ x el A -> A <<= rem B x.\n  Proof.\n    intros D E y F. apply in_rem_iff.\n    intuition; subst; auto. \n  Qed.\n\nEnd Removal.\n\nHint Resolve rem_not_in rem_incl rem_mono rem_cons rem_cons' rem_app rem_app' rem_in rem_neq rem_inclr.\n", "meta": {"author": "uds-psl", "repo": "base-library", "sha": "d9f3b8abf379d4c12049dd25c8d1fdf1973dab48", "save_path": "github-repos/coq/uds-psl-base-library", "path": "github-repos/coq/uds-psl-base-library/base-library-d9f3b8abf379d4c12049dd25c8d1fdf1973dab48/Lists/Removal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6850618762434943}}
{"text": "(* ###################################################################### *)\n(* taken from http://www.cis.upenn.edu/~rrand/popl_2016/ *)\n(** * Proofs and Programs *)\n\n(** (We use [admit] and [Admitted] to hide solutions from exercises.) *)\n\nAxiom admit : forall {T}, T.\n\n(** Everything in Coq is built from scratch -- even booleans!\n    Fortunately, they are already provided by the Coq standard\n    library, but we'll review their definition here to get familiar\n    with the basic features of the system. *)\n\n(** [Inductive] is Coq's way of defining an algebraic datatype.  Its\n    syntax is similar to OCaml's ([type]) or Haskell's ([data]). Here,\n    we define [bool] as a simple algebraic datatype. *)\n\nModule Bool.\n\nInductive bool : Type :=\n| true : bool\n| false : bool.\n\n(** **** Exercise: 1 star (trivalue)  *)\n(** Define a three-valued data type, representing ternary logic.  Here\n    something can be true, false and unknown. *)\n\nInductive trivalue : Type :=\n| tru : trivalue\n| fals : trivalue\n| unknown : trivalue.\n(** [] *)\n\n(** We can write functions that operate on [bool]s by simple pattern\n    matching, using the [match] keyword. *)\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\n(** We can pattern-match on multiple arguments simultaneously, and\n    also use \"_\" as a wildcard pattern. *)\n\nDefinition orb (b1 b2: bool) : bool :=\n  match b1, b2 with\n  | false, false => false\n  | _, _ => true\n  end.\n\nPrint orb.\n\n(** We can also use an [if] statement, which matches on the first\n    constructor of any two-constructor datatype, in our definition. *)\n\nDefinition andb (b1 b2: bool) : bool :=\n  if b1 then b2 else false.\n\n(** Let's test our functions. The [Compute] command tells Coq to\n    evaluate an expression and print the result on the screen.*)\n\nCompute (negb true).\nCompute (orb true false).\nCompute (andb true false).\n\n(** **** Exercise: 1 star (xor)  *)\n(** Define xor (exclusive or). *)\n\nDefinition xorb (b1 b2 : bool) : bool :=\n  match b1, b2 with\n  | false, false => false\n  | true, true => false\n  | _, _ => true\n  end.\n(* FILL IN HERE *)\n\nCompute (xorb true true).\n(** [] *)\n\n\n(** What makes Coq different from normal functional programming\n    languages is that it allows us to formally _prove_ that our\n    programs satisfy certain properties. The system mechanically\n    verifies these proofs to ensure that they are correct.\n\n    We use [Lemma], [Theorem] and [Example] to write logical\n    statements. Coq requires us to prove these statements using\n    _tactics_, which are commands that manipulate formulas using basic\n    logic rules. Here's an example showing some basic tactics in\n    action. *)\n\n(** New tactics\n    -----------\n\n    - [intros]: Introduce variables into the context, giving them\n      names.\n\n    - [simpl]: Simplify the goal.\n\n    - [reflexivity]: Prove that some expression [x] is equal to itself. *)\n\nExample andb_false_l : forall b, andb false b = false.\nProof.\n(* WORKED IN CLASS *)\n  intros b. (* introduce the variable b *)\n  simpl. (* simplify the expression *)\n  reflexivity. (* solve for x = x *)\nQed.\n\n\n(** **** Exercise: 1 star (orb_true_l)  *)\nTheorem orb_true_l :\n  forall b, orb true b = true.\nProof.\nintros b.\nsimpl.\nreflexivity.\n(* FILL IN HERE *) Qed.\n(** [] *)\n\n(** Some proofs require case analysis. In Coq, this is done with the\n    [destruct] tactic. *)\n\n(** New tactic\n    ----------\n\n    - [destruct]: Consider all possible constructors of an inductive\n      data type, generating subgoals that need to be solved\n      separately. *)\n\n\n(*  FULL: Here's an example of [destruct] in action. *)\n\nLemma orb_true_r : forall b : bool, orb b true = true.\n(* Here we explicitly annotate b with its type, even though Coq could infer it. *)\nProof.\n(* WORKED IN CLASS *)\n  intros b.\n  simpl. (* This doesn't do anything, since orb pattern matches on the\n  first variable first. *)\n  destruct b. (* Do case analysis on b *)\n  + (* We use the \"bullets\" '+' '-' and '*' to delimit subgoals *)\n    (* true case *)\n    simpl.\n    reflexivity.\n  + (* false case *)\n    simpl.\n    reflexivity.\nQed.\n\n(** We can call [destruct] as many times as we want, generating deeper subgoals. *)\n\nTheorem andb_commutative : forall b1 b2 : bool, andb b1 b2 = andb b2 b1.\nProof.\n(* WORKED IN CLASS *)\n  intros b1 b2.\n  destruct b1.\n  + destruct b2.\n    - simpl. reflexivity.\n    - simpl. reflexivity. (* bullets need to be consistent *)\n\n(** Alternatively, if all the subgoals are solved the same way, we can\n    use the [;] operator to execute a tactic on _all_ the generated\n    subgoals, like this: *)\n\n  + destruct b2; simpl; reflexivity.\nQed.\n\n(** **** Exercise: 1 star (andb_false_r)  *)\n(** Show that b AND false is always false  *)\n\nTheorem andb_false_r : forall b: bool, andb b false = false.\nProof.\nintros b.\ndestruct b; simpl; reflexivity.\n(* FILL IN HERE *) Qed.\n(** [] *)\n\n(** **** Exercise: 1 star (xorb_b_neg_b)  *)\n(** Show that b xor (not b) is always true. *)\n\nTheorem xorb_b_neg_b : forall b: bool, xorb b (negb b) = true.\nProof.\nintros b.\ndestruct b; simpl; reflexivity.\n(* FILL IN HERE *) Qed.\n\n(** Sometimes, we want to show a result that requires hypotheses. In\n    Coq, [P -> Q] means that [P] implies [Q], or that [Q] is true\n    whenever [P] is. We can use [->] multiple times to express that\n    more than one hypothesis are needed; the syntax is similar to how\n    we write multiple-argument functions in OCaml or Haskell. For\n    example: *)\n\nTheorem rewrite_example : forall b1 b2 b3 b4,\n  b1 = b4 ->\n  b2 = b3 ->\n  andb b1 b2 = andb b3 b4.\n\n(** We can use the [intros] tactic to give hypotheses names,\n    bringing them into the proof context. *)\n\nProof.\n  intros b1 b2 b3 b4 eq14 eq23.\n\n(** Now, our context has two hypotheses: [eq14], which states\n    that [b1 = b4], and [eq23], stating that [b2 = b3]. \n\n     Here are some tactics for using hypotheses and previously proved\n    results: *)\n\n(** New tactics\n    -----------\n\n    - [rewrite]: Replace one side of an equation by the other.\n\n    - [apply]: Suppose that the current goal is [Q]. If [H : Q], then\n      [apply H] solves the goal. If [H : P -> Q], then [apply H]\n      replaces [Q] by [P] in the goal. If [H] has multiple hypotheses,\n      [H : P1 -> P2 -> ... -> Pn -> Q], then [apply H] generates one\n      subgoal for each [Pi]. *)\n\n  rewrite eq14. (* replace b1 with b4 in the goal *)\n  rewrite <- eq23. (* replace b3 with b2 in the goal. *)\n  apply andb_commutative. (* solve using our earlier theorem *)\nQed.\n\n\n(** **** Exercise: 1 star (xorb_same)  *)\n(** Show that if [b1 = b2] then b1 xor b2 is false. *)\n\nTheorem xorb_same : forall b1 b2: bool, b1 = b2 -> xorb b1 b2 = false.\nProof.\nintros b1 b2 eq.\nrewrite eq.\ndestruct b2; simpl; reflexivity.\n(* FILL IN HERE *) Qed.\n\nEnd Bool.\n\n\n(* ###################################################################### *)\n\n(** We will use the following option to make polymorphism more\n    convenient. *)\n\nSet Implicit Arguments.\n\n(** * Lists *)\n\n(** We will now shift gears and study more interesting functional\n    programs; namely, programs that manipulate _lists_. *)\n\nModule List.\n\n(** Here's a polymorphic definition of a [list] type in Coq: *)\n\nInductive list (T : Type) :=\n| nil : list T\n| cons : T -> list T -> list T.\n\n(** Here's how we define a function to append two lists.\n    Note that we declare the type parameter T. *)\n\nFixpoint app T (l1 l2 : list T) : list T :=\n  match l1 with\n  | nil _ => l2\n  | cons h t  => cons h (app t l2)\n  end.\n\n(** Coq comes with a syntax extension mechanism for defining custom\n    notations. Without getting into details, here's how we can give\n    familiar syntax for lists. *)\n\nNotation \"h :: t\" := (cons h t) (at level 60, right associativity).\nNotation \"[ ]\" := (nil _).\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y [] ) ..).\nNotation \"l1 ++ l2\" := (app l1 l2) (at level 60, right associativity).\n\n(** Since [nil] can potentially be of any type, we add an underscore\n    to tell Coq to infer the type from the context. *)\n\n(** We can now check the types of expressions involving lists. *)\n\nCheck [].\nCheck true :: [].\nCheck [true ; false].\nCheck [true ; false] ++ [false].\n\n(** And compute the last. *)\nCompute [true ; false] ++ [false].\n\n(** Note that we can use define notations and functions\n    simultaneously: *)\n\nReserved Notation \"l1 @ l2\" (at level 60).\nFixpoint app' T (l1 l2 : list T) : list T :=\n  match l1 with\n  | [] => l2\n  | h :: t  => h :: (t @ l2)\n  end\n\n  where \"l1 @ l2\" := (app' l1 l2).\n\n\n(** **** Exercise: 1 star (snoc)  *)\n(** Define [snoc], which adds an element to the end of a list. *)\n\nFixpoint snoc T (l : list T) (x : T) : list T :=\n  (l ++ (x :: [])).\n\n(** It is easy to show that appending [nil] to the left of a list\n    yields the original list.  *)\n\nLemma app_nil_l: forall T (l : list T), [] ++ l  = l.\nProof.\n(* WORKED IN CLASS *)\n  intros T l.\n  simpl.\n  reflexivity.\nQed.\n\n(** Showing the symmetric result is more difficult\n    since it doesn't follow by simplification alone. *)\n\nLemma app_nil_r: forall T (l : list T), l ++ []  = l.\nProof.\n  intros T l.\n  simpl. (* Does nothing *)\n  destruct l as [| h t]. (* Notice the [as] clause, which allows us\n                            to name constructor arguments. *)\n  + simpl.\n    reflexivity.\n  + simpl. (* no way to proceed... *)\n\n(** The problem is that we can only prove the result for [h::t]\n    if we already know that it is valid for [t]. We need a bigger\n    hammer here... *)\n\n(** New tactic\n    ----------\n\n    - [induction]: Argue by induction. It works as [destruct], but\n    additionally giving us an inductive hypothesis in the inductive\n    case. *)\nRestart.\n  intros T l.\n  induction l as [| h t IH]. (* Note the additional name [IH], given to our\n                                inductive hypothesis *)\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IH.\n    reflexivity.\nQed.\n\n(** As a rule of thumb, when proving some property of a recursive\n    function, it is a good idea to do induction on the recursive\n    argument of the function. For instance, let's show that [app] is\n    associative: *)\n\nLemma app_assoc :\n  forall T (l1 l2 l3 : list T),\n    l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\nProof.\n(* WORKED IN CLASS *)\n  intros T l1 l2 l3.\n  induction l1 as [|h1 t1 IH]. (* l1 is the right choice here, since [app] is defined\n                                  by recursion on the first argument. *)\n  - (* [] *)\n    simpl.\n    reflexivity.\n  - (* h1 :: t1 *)\n    simpl.\n    rewrite IH.\n    reflexivity.\nQed.\n\n(** Exercise: Try to do induction on [l2] and [l3] in the\n    above proof, and see where it fails. *)\n\n(** **** Exercise: 2 stars (snoc_app)  *)\n(** Prove that [snoc l x] is equivalent to appending [x] to the end of\n    [l]. *)\n\nLemma snoc_app : forall T (l : list T) (x : T), snoc l x = l ++ [x].\nProof.\nintros.\ninduction l.\n - simpl; reflexivity.\n - \n  simpl. reflexivity.\n(* FILL IN HERE *) Qed.\n(** [] *)\n\n(** The natural numbers are defined in Coq's standard library as follows:\n\n    Inductive nat : Type :=\n      | O : nat\n      | S : nat -> nat.\n\n    where [S] stands for \"Successor\".\n\n    Coq prints [S (S (S O))] as \"3\", as you might expect.\n\n*)\n\nSet Printing All.\n\nCheck 0.\nCheck 2.\nCheck 2 + 2.\n\nUnset Printing All.\n\nCheck S (S (S O)).\nCheck 2 + 3.\nCompute 2 + 3.\n\n(** Now we can define the [length] function: *)\n\nFixpoint length T (l : list T) :=\n  match l with\n  | [] => 0\n  | h :: t => 1 + length t\n  end.\n\nCompute length [1; 1; 1].\n\n(** **** Exercise: 3 stars (app_length)  *)\n\nLemma app_length : forall T (l1 l2 : list T),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\nintros.\ninduction l1.\ninduction length.\nsimpl; reflexivity.\nsimpl; reflexivity.\n\nsimpl; rewrite IHl1.\nreflexivity.\n(* FILL IN HERE *) Qed.\n\n(** Often we find ourselves needing to reason about _contradictory_\n    hypotheses. Whenever we have a hypothesis that equates two\n    expressions that start with different constructors, we can use the\n    [discriminate] tactic to prune that subgoal.\n\n    This is a particular case of what is known as _the principle of\n    explosion_, which states that a contradiction implies anything. *)\n\n(** New Tactic\n    ----------\n\n    - [discriminate]: Looks for an equation between terms starting\n      with different constructors, and solves the current goal. *)\n\n(* Let's try to prove that if [l1 ++ l2 = []] then [l1] is [[]] *)\n\nLemma app_eq_nil_l : forall T (l1 l2 : list T),\n  l1 ++ l2 = [] -> l1 = [].\nProof.\n(* WORKED IN CLASS *)\n  intros T l1 l2 H.\n  destruct l1 as [| h t].\n  + (* [] *)\n    reflexivity.\n  + (* h :: t *)\n    simpl in H.\n    discriminate.\nQed.\n\n(** **** Exercise: 2 stars (app_eq_nil_r)  *)\n(** Prove the same about [l2]. *)\n\nLemma plus_nil_r : forall T (l1 l2 : list T),\n  l1 ++ l2 = [] -> l2 = [].\nProof.\nintros T l1 l2 H.\ndestruct l1 as [| h t].\n + apply H.\n + simpl in H.\n   discriminate. \n(* FILL IN HERE *) Qed.\n(** [] *)\n\n(** Coq, like many other proof assistants, requires functions to\n    be _total_ and defined for all possible inputs; in particular,\n    recursive functions are always required to terminate.\n\n    Since there is no general algorithm for deciding whether a\n    function is terminating or not, Coq needs to settle for an\n    incomplete class of recursive functions that is easy to show\n    terminating. This means that, although every recursive function\n    accepted by Coq is terminating, there are many recursive functions\n    that always terminate but are not accepted by Coq, because it\n    isn't \"smart enough\" to realize that they indeed terminate.\n\n    The criterion adopted by Coq for deciding whether to accept a\n    definition or not is _structural recursion_: All recursive calls\n    must be performed on _sub-terms_ of the original argument.\n\n    Note that the definition of _sub-terms_ used in context is purely syntactic\n    hence the following definition fails.\n\n**)\n\nFail Fixpoint shuffle T (l1 l2 : list T) :=\n  match l1 with\n  | [] => l2\n  | h :: t => h :: shuffle l2 t\n  end.\n\n(** The [Fail] keyword instructs Coq to ignore a command when it\n    fails, but to fail if the command succeeds. It is useful for\n    showing certain pieces of code that are not accepted by the\n    language.\n\n    In this case, we can rewrite [shuffle] so that it is accepted by\n    Coq's termination checker: *)\n\nFixpoint shuffle T (l1 l2 : list T) :=\n  match l1, l2 with\n  | [], _ => l2\n  | _, [] => l1\n  | h1 :: t1, h2 :: t2 => h1 :: h2 :: shuffle t1 t2\n  end.\n\nPrint shuffle.\n\n\n(** Let's define list reversal function and prove some of its basic\n    properties. *)\n\nFixpoint rev T (l : list T) :=\n  match l with\n  | [] => []\n  | h :: t => (rev t) ++ [h]\n  end.\n\nLemma rev_app : forall T (l1 l2 : list T), rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n(* WORKED IN CLASS *)\n  intros T l1 l2.\n  induction l1 as [|h t IH].\n  + simpl.\n    rewrite app_nil_r.\n    reflexivity.\n  + simpl.\n    rewrite IH.\n    rewrite app_assoc.\n    reflexivity.\nQed.\n\n(** **** Exercise: 2 stars (rev_app)  *)\n(** Using [rev_app], prove that reversing a list twice results in the\n    same list. *)\n\nLemma rev_involutive : forall T (l : list T), rev (rev l) = l.\nProof.\nintros.\ninduction l as [| h t H].\n + simpl; reflexivity.\n + simpl. rewrite rev_app. rewrite H. simpl. reflexivity.\n\n(* FILL IN HERE *) Qed.\n\n(** Notice that the definition of list reversal given above runs in\n    quadratic time. Here is a tail-recursive equivalent that runs in\n    linear time. *)\n\nFixpoint tr_rev_aux T (l acc : list T) : list T :=\n  match l with\n  | [] => acc\n  | x :: l => tr_rev_aux l (x :: acc)\n  end.\n\nDefinition tr_rev T (l: list T) := tr_rev_aux l [].\n\n(** Here, [acc] is an accumulator argument that holds the portion of\n    the list that we have reversed so far. Let's prove that [tr_rev]\n    is equivalent to [rev]. For this we will need another tactic: *)\n\n\n(** New Tactic\n    ----------\n\n    - [unfold]: Calling [unfold foo] expands the definition of [foo]\n      in the goal.\n*)\n\nLemma tr_rev_eq_rev_try_one :\n  forall T (l : list T),\n    tr_rev l = rev l.\nProof.\n  intros T l.\n  unfold tr_rev.\n  induction l as [| h t IH].\n  + simpl.\n    reflexivity.\n  + simpl.\n    (* and now we're stuck... *)\nAbort.\n\n(** The problem is that the result we are trying to prove is not\n    general enough. We will need the following auxiliary lemma: *)\n\nLemma tr_rev_aux_eq_rev :\n  forall T (l1 l2 : list T),\n    tr_rev_aux l1 l2 = rev l1 ++ l2.\nProof.\n  intros T l1 l2.\n  induction l1 as [|x l1 IH].\n  - simpl. reflexivity.\n  - simpl.\n\n(** Our inductive hypothesis is too weak to proceed. We want\n    [tr_rev_aux l1 l2 = rev l1 ++ l2] for all [l2]. Let's try again\n    from the start. *)\n\nRestart.\n  intros T l1. (* Now we don't introduce l2, leaving it general. *)\n  induction l1 as [|x l1 IH].\n  - intros l2. simpl. reflexivity.\n  - intros l2. (* Behold our induction hypothesis! *)\n    simpl.\n    rewrite IH.\n\n(** We can use the [SearchAbout] command to look up lemmas that can be\n    used with certain expressions ([C-c C-a C-a] in Proof General). *)\n\n    SearchAbout (_ ++ _ ++ _).\n    rewrite <- app_assoc.\n    simpl.\n    reflexivity.\nQed.\n\n(** Our result follows easily: *)\n\nLemma tr_rev_eq_rev :\n  forall T (l : list T),\n    tr_rev l = rev l.\nProof.\n(* WORKED IN CLASS *)\n  intros T l.\n  unfold tr_rev.\n  rewrite tr_rev_aux_eq_rev.\n  SearchAbout (_ ++ []).\n  apply app_nil_r.\nQed.\n\nEnd List.\n\n\n(** You may have noticed that several of the proofs in this section,\n    particularly regarding the associativity of the append function,\n    closely resemble proofs about arithmetic. You might also be interested\n    in Coq for its ability to prove results in mathematics. The\n    material in this section should be sufficient for you to start\n    formulating theorems about the natural numbers, such as the\n    commutativity, associativity and distributivity of addition and\n    multiplication.\n\n    As noted above, the natural numbers are defined as follows:\n\n    Inductive nat : Type :=\n      | O : nat\n      | S : nat -> nat.\n\n    From there you can define +, -, *, /, ^ etc. We encourage you to\n    start on your own, but to help we've included a module on arithmetic\n    We hope you enjoy.\n\n*)\n", "meta": {"author": "santifa", "repo": "masterarbeit", "sha": "088210e071464831d3e496d3a8faac0aac494228", "save_path": "github-repos/coq/santifa-masterarbeit", "path": "github-repos/coq/santifa-masterarbeit/masterarbeit-088210e071464831d3e496d3a8faac0aac494228/learn-coq/list_basics.full.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.8723473713594991, "lm_q1q2_score": 0.6850618674770275}}
{"text": "From CoqAlgs Require Export Sorting.Sort.\nFrom CoqAlgs Require Export ListLemmas.\nFrom CoqAlgs Require Export PairingHeap.\n\nSet Implicit Arguments.\n\nFixpoint fromList {A : Type} (cmp : A -> A -> bool) (l : list A) : PairingHeap A :=\nmatch l with\n    | [] => empty\n    | h :: t => insert cmp h (fromList cmp t)\nend.\n\nFunction toList\n  {A : Type} (p : A -> A -> bool) (h : PairingHeap A) {measure size h}: list A :=\nmatch extractMin p h with\n    | None => []\n    | Some (m, h') => m :: toList p h'\nend.\nProof.\n  destruct h; cbn; intros; subst; inv teq.\n    rewrite size_mergePairs. apply le_n.\nDefined.\n\nDefinition pairingSort (A : Type) (p : A -> A -> bool) (l : list A) : list A :=\n  toList p (fromList p l).\n\n(** Properties of [fromList]. *)\n\nLemma Elem_fromList :\n  forall (A : Type) (cmp : A -> A -> bool) (x : A) (l : list A),\n    Elem x (fromList cmp l) <-> In x l.\nProof.\n  induction l as [| h t].\n    split; inv 1.\n    simpl. rewrite Elem_insert, IHt. firstorder.\nQed.\n\nLemma isHeap_fromList :\n  forall (A : Ord) (l : list A),\n    isHeap cmp (fromList cmp l).\nProof.\n  induction l as [| h t]; cbn.\n    constructor.\n    apply isHeap_insert. assumption.\nQed.\n\nLemma countTree_fromList :\n  forall (A : Type) (cmp : A -> A -> bool) (p : A -> bool) (l : list A),\n    countTree p (fromList cmp l) = count p l.\nProof.\n  induction l as [| h t].\n    cbn. reflexivity.\n    cbn. destruct (fromList cmp t) eqn: Heq.\n      cbn in *. unfold id. destruct (p h); lia.\n      rewrite <- IHt. destruct (cmp h a); cbn; destruct (p h), (p a); unfold id; lia.\nQed.\n\n(** Properties of [toList]. *)\n\nLemma countTree_toList :\n  forall (A : Type) (cmp : A -> A -> comparison) (p : A -> bool) (h : PairingHeap A),\n    (*isHeap cmp h ->*) countTree p h = count p (toList cmp h).\nProof.\n  intros until h.\n  functional induction toList cmp h.\n    destruct h; inv e.\n    destruct h; inv e. cbn. rewrite <- IHl, countTree_mergePairs. reflexivity.\nQed.\n\nLemma Sorted_toList :\n  forall (A : Ord) (h : PairingHeap A),\n    isHeap cmp h -> Sorted cmp (toList cmp h).\nProof.\n  intros. functional induction toList cmp h.\n    constructor.\n    rewrite toList_equation in *. destruct h'; cbn in *; constructor.\n      eapply extractMin_spec; eauto. erewrite Elem_extractMin; eauto. cbn. assumption.\n      eapply IHl, isHeap_extractMin; eauto.\nQed.\n\n(** Properties of [pairingSort]. *)\n\nTheorem Sorted_pairingSort :\n  forall (A : Ord) (l : list A),\n    Sorted cmp (pairingSort cmp l).\nProof.\n  intros. unfold pairingSort.\n  apply Sorted_toList, isHeap_fromList.\nQed.\n\nLemma perm_pairingSort :\n  forall (A : Type) (cmp : A -> A -> comparison) (l : list A),\n    perm (pairingSort cmp l) l.\nProof.\n  unfold perm, pairingSort. intros.\n  rewrite <- countTree_toList, countTree_fromList.\n    reflexivity.\nQed.\n\nTheorem Permutation_pairingSort :\n  forall {A : Ord} (l : list A),\n    Permutation (pairingSort cmp l) l.\nProof.\n  intros. apply perm_Permutation, perm_pairingSort.\nQed.\n\n#[export]\nInstance Sort_pairingSort (A : Ord) : Sort cmp :=\n{\n    sort := pairingSort cmp;\n    Sorted_sort := Sorted_pairingSort A;\n    Permutation_sort := Permutation_pairingSort;\n}.", "meta": {"author": "wkolowski", "repo": "coq-algs", "sha": "ee6c656314e3d93e3029dd5f845cfb5352c1b089", "save_path": "github-repos/coq/wkolowski-coq-algs", "path": "github-repos/coq/wkolowski-coq-algs/coq-algs-ee6c656314e3d93e3029dd5f845cfb5352c1b089/Sorting/PairingSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.6850074014477102}}
{"text": "\nFrom mathcomp Require Import ssreflect ssrbool eqtype.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLemma and_true_l (a b : bool) : a && b = true -> a = true.\nProof. by case: a. Qed.\n\nLemma and_true_r (a b : bool) : a && b = true -> b = true.\nProof. by case: a. Qed.\n\nLemma and_true (a b : bool) : a && b = true -> a = true /\\ b = true.\nProof. by case: a. Qed.\n\nLemma and_false (a b : bool) : a && b = false -> a = false \\/ b = false.\nProof.\n  case/nandP => H.\n  - left; exact: (negbTE H).\n  - right; exact: (negbTE H).\nQed.\n\nLemma neq_sym (T : eqType) (x y : T) : (x != y) = (y != x).\nProof.\n  case H: (x == y) => /=.\n  - rewrite eq_sym in H. rewrite H. reflexivity.\n  - rewrite eq_sym in H. rewrite H. reflexivity.\nQed.\n\nLemma expand_eq (b1 b2 : bool) : (b1 == b2) = ((b1 || ~~ b2) && (~~ b1 || b2)).\nProof. by case: b1; case: b2. Qed.\n\nLemma expand_neq (b1 b2 : bool) : (b1 != b2) = ((b1 || b2) && (~~ b1 || ~~ b2)).\nProof. by case: b1; case: b2. Qed.\n\nLemma neg_eq (b1 b2 : bool) : (~~ b1 == ~~ b2) = (b1 == b2).\nProof. by case: b1; case: b2. Qed.\n", "meta": {"author": "mht208", "repo": "coq-ssrlib", "sha": "6a3f3140a2641d74efee8dc79fa436057c98d2e4", "save_path": "github-repos/coq/mht208-coq-ssrlib", "path": "github-repos/coq/mht208-coq-ssrlib/coq-ssrlib-6a3f3140a2641d74efee8dc79fa436057c98d2e4/src/Bools.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.6850073880134209}}
{"text": "(**\nThe situation:\n1. There are 5 houses in five different colors.\n2. In each house lives a person with a different nationality.\n3. These five owners drink a certain type of beverage, smoke a certain brand of cigar and keep a certain pet.\n4. No owners have the same pet, smoke the same brand of cigar or drink the same beverage.\n\nHow do we encode these rules into Coq?\n\nThe situation stipulates that each person has a different house, drinks a different beverage,\nown a different pet and smokes a different type of cigar. Thus we can have a function type for each\nattribute that takes in the nationality and outputs the attribute. Then we require for different nationalities,\nthe attribute output must be distinct.\n\nHints:\n1. the Brit lives in the red house\n2. the Swede keeps dogs as pets\n3. the Dane drinks tea\n4. the green house is on the left of the white house\n5. the green house's owner drinks coffee\n6. the person who smokes Pall Mall rears birds\n7. the owner of the yellow house smokes Dunhill\n8. the man living in the center house drinks milk\n9. the Norwegian lives in the first house\n10. the man who smokes blends lives next to the one who keeps cats\n11. the man who keeps horses lives next to the man who smokes Dunhill\n12. the owner who smokes BlueMaster drinks beer\n13. the German smokes Prince\n14. the Norwegian lives next to the blue house\n15. the man who smokes blend has a neighbor who drinks water\n\n*)\n\nInductive nationality : Type :=\n  | British : nationality\n  | Swedish : nationality\n  | Danish : nationality\n  | Norwegian : nationality\n  | German : nationality.\n  \nInductive pet : Type :=\n  | Dog : pet\n  | Cat : pet\n  | Bird : pet\n  | Horse : pet\n  | Fish : pet.\n  \nInductive beverage : Type :=\n  | tea : beverage\n  | coffee : beverage\n  | milk : beverage\n  | beer : beverage\n  | water : beverage.\n  \nInductive house : Type :=\n  | red : house\n  | green : house\n  | white : house\n  | yellow : house\n  | blue : house.\n  \nInductive cigar : Type :=\n  | PallMall : cigar\n  | Dunhill : cigar\n  | BlueMaster : cigar\n  | Prince : cigar\n  | Blend : cigar.\n\n\n", "meta": {"author": "zunction", "repo": "Coqy", "sha": "a588f3b9000329eb1db25a4a81da8219bcb8f053", "save_path": "github-repos/coq/zunction-Coqy", "path": "github-repos/coq/zunction-Coqy/Coqy-a588f3b9000329eb1db25a4a81da8219bcb8f053/Others/ein.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143776, "lm_q2_score": 0.819893335913536, "lm_q1q2_score": 0.6850073742608596}}
{"text": "Set Implicit Arguments.\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| BLess  : AExp -> AExp -> BExp.\n\nNotation \"e1 :<: e2\" := (BLess e1 e2) (at level 40, left associativity).\nNotation \"e1 :+: e2\" := (APlus e1 e2) (at level 40, left associativity).\nNotation \"e1 :-: e2\" := (AMinus e1 e2) (at level 40, left associativity).\nNotation \"e1 :*: e2\" := (AMult e1 e2) (at level 40, left associativity).\n\nFixpoint aeval (e : AExp) : nat :=\n  match e 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\nFixpoint beval (e : BExp) : bool :=\n  match e with\n  | BTrue       => true\n  | BFalse      => false\n  | BLess e1 e2 => Nat.leb (aeval e1) (aeval e2)\n  end.\n", "meta": {"author": "nbun", "repo": "pps-coq", "sha": "4b7aa1a37e7fb80549d3d3e32b6f37a1c239660f", "save_path": "github-repos/coq/nbun-pps-coq", "path": "github-repos/coq/nbun-pps-coq/pps-coq-4b7aa1a37e7fb80549d3d3e32b6f37a1c239660f/src/Exercises/S0/Exp_1_Bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538935, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.684998586645736}}
{"text": "Set Implicit Arguments.\nSet Strict Implicit.\n\nSection PairWF.\n  Variables T U : Type.\n  Variable RT : T -> T -> Prop.\n  Variable RU : U -> U -> Prop.\n\n  Inductive R_pair : T * U -> T * U -> Prop :=\n  | L : forall l l' r r',\n    RT l l' -> R_pair (l,r) (l',r')\n  | R : forall l r r',\n    RU r r' -> R_pair (l,r) (l,r').\n\n  Hypothesis wf_RT : well_founded RT.\n  Hypothesis wf_RU : well_founded RU.\n\n  Theorem wf_R_pair : well_founded R_pair.\n  Proof.\n    red. intro x.\n    destruct x. generalize dependent u.\n    apply (well_founded_ind wf_RT (fun t => forall u : U, Acc R_pair (t, u))) .\n    do 2 intro.\n\n    apply (well_founded_ind wf_RU (fun u => Acc R_pair (x,u))). intros.\n    constructor. destruct y.\n    remember (t0,u). remember (x,x0). inversion 1; subst;\n    inversion H4; inversion H3; clear H4 H3; subst; eauto.\n  Defined.\nEnd PairWF.\n\nInductive R_nat : nat -> nat -> Prop :=\n| R_S : forall n, R_nat n (S n).\n\nTheorem wf_R_nat : well_founded R_nat.\nProof.\n  red; induction a; constructor; intros.\n    inversion H.\n    inversion H; subst; auto.\nDefined.\n\nFixpoint guard A (R : A -> A -> Prop) (n : nat) (wfR : well_founded R)\n  {struct n}: well_founded R :=\n  match n with\n    | 0 => wfR\n    | S n => fun x => Acc_intro x (fun y _ => guard n (guard n wfR) y)\n  end.", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/src/GenRec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6849885854300183}}
{"text": "From smpl Require Import Smpl.\nRequire Import Omega Lia.\nRequire Export Psatz Arith.\nRequire Export RelationClasses Morphisms.\n\n(* Congruence Lemmatas over nat*)\nInstance add_le_mono : Proper (le ==> le ==> le) plus.\nProof. repeat intro. now apply Nat.add_le_mono. Qed.\n\nInstance mult_le_mono : Proper (le ==> le ==> le) mult.\nProof. repeat intro. now apply Nat.mul_le_mono. Qed.\n\nInstance max_le_mono : Proper (le ==> le ==> le) max.\nProof. repeat intro. repeat eapply Nat.max_case_strong;lia. Qed.\n\nInstance max'_le_mono : Proper (le ==> le ==> le) Init.Nat.max.\nProof. repeat intro. repeat eapply Nat.max_case_strong;lia. Qed.\n\nInstance S_le_mono : Proper (le ==> le) S.\nProof. repeat intro. lia. Qed.\n\n", "meta": {"author": "uds-psl", "repo": "time-invariance-thesis-for-L", "sha": "41f4eb1f788cc4f096d9c7c286c9ca907588859f", "save_path": "github-repos/coq/uds-psl-time-invariance-thesis-for-L", "path": "github-repos/coq/uds-psl-time-invariance-thesis-for-L/time-invariance-thesis-for-L-41f4eb1f788cc4f096d9c7c286c9ca907588859f/theories/TM/Util/ArithPrelim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6849885687409961}}
{"text": "From Coq Require Import Bool ZArith Znumtheory micromega.Lia.\n\nFrom BY Require Import Zpower_nat InductionPrinciples Hierarchy.Definitions Impl Hierarchy.BigOp.\n\nLocal Open Scope Z_scope.\n\nImport Z.\n\nLemma mod_lemma a b (H : b <= a < 2*b) : a mod b = a - b.\nProof.\n  symmetry; destruct (Z_le_dec b 0); [apply mod_unique_neg with 1|apply mod_unique_pos with 1]; lia. Qed.\n\nLemma mod_half a b (H : 0 < b <= a) : a mod b <= a / 2.\nProof.\n  pose proof (mod_pos_bound a b ltac:(lia)).\n  pose proof (mul_succ_div_gt a 2 ltac:(lia)).\n  destruct (ltb_spec b (succ (a / 2))).\n  + lia.\n  + assert (a < 2*b) by lia.\n    rewrite mod_lemma; lia. Qed.\n\nLemma log2_half a (H : 0 < a) : log2 (a / 2) = log2 a - 1 \\/ a = 1.\nProof.\n  rewrite <- div2_div, div2_spec, log2_shiftr by assumption.\n  unfold max; destruct (compare_spec 0 (log2 a - 1)); auto.\n  - right; assert (log2 a = 0) by (pose proof log2_nonneg a; lia).\n    apply log2_null in H1; lia. Qed.\n\nLemma even_mul_2_l a : even (2 * a) = true.\nProof. rewrite even_mul; reflexivity. Qed.\n\nLemma even_mul_2_r a : even (a * 2) = true.\nProof. rewrite mul_comm; apply even_mul_2_l. Qed.\n\nLemma even_divide a : even a = true <-> (2 | a).\nProof.\n  split.\n  - intros. apply even_spec in H. destruct H as [x]. exists x; lia.\n  - intros [x ->]. apply even_mul_2_r. Qed.\n\nLemma odd_gcd a : odd a = true <-> gcd a 2 = 1.\nProof.\n  split; intros.\n  - rewrite odd_spec in H. rewrite <- Zodd_equiv in H. apply Zodd_ex in H.\n    destruct H. rewrite H. rewrite gcd_comm.\n    rewrite add_comm, mul_comm. rewrite gcd_add_mult_diag_r. reflexivity.\n  - apply gcd_bezout in H. destruct H. destruct H.\n    apply (f_equal odd) in H.\n    rewrite odd_add, !odd_mul in H. simpl in H.\n    destruct (odd a); rewrite !andb_false_r in H; easy. Qed.\n\nLemma odd_rel_prime a : odd a = true <-> rel_prime a 2.\nProof. pose proof Zgcd_1_rel_prime a 2; pose proof odd_gcd a; tauto. Qed.\n\nLemma rel_prime_pow a b n (Hn : (1 <= n)%nat) : rel_prime a b <-> rel_prime a (b ^+ n).\nProof.\n  split; intro.\n  - induction n.\n    + apply rel_prime_sym; apply rel_prime_1.\n    + destruct n.\n      * rewrite Zpower_nat_1_r; assumption.\n      * rewrite Zpower_nat_succ_r; apply rel_prime_mult. assumption.\n        apply IHn; lia.\n  - apply rel_prime_sym. apply rel_prime_div with (b ^+ n). apply rel_prime_sym.\n    assumption. red. exists (b ^+ (n - 1)). rewrite mul_comm, mul_base_pull. reflexivity. lia. Qed.\n\nLemma odd_rel_prime_pow a n (Hn : (1 <= n)%nat): odd a = true <-> rel_prime a (2 ^+ n).\nProof. pose proof rel_prime_pow a 2 n Hn. pose proof odd_rel_prime a. tauto. Qed.\n\nLemma odd_pow2 n (H : (0 < n)%nat) : odd (2 ^+ n) = false.\nProof.\n  rewrite mul_base_pull; [|lia]; rewrite odd_mul; reflexivity. Qed.\n\nLemma odd_mod_pow2 a n (H : (0 < n)%nat) : odd (a mod 2 ^+ n) = odd a.\nProof.\n  rewrite Zdiv.Zmod_eq_full, odd_sub, odd_mul, odd_pow2, andb_false_r, xorb_false_r. reflexivity.\n  lia. apply Zpower_nat_nonzero. lia. Qed.\n\nLemma mod_equiv a b m (H : m <> 0) : a mod m = b mod m <-> (m | a - b).\nProof.\n  split; intros.\n  - apply Zmod_divide. lia.\n    rewrite Zminus_mod. replace (a mod m - (b mod m)) with 0 by lia.\n    reflexivity.\n  - destruct H0. replace b with (a - x * m) by lia.\n    rewrite <- Zminus_mod_idemp_r, mod_mul, sub_0_r. reflexivity. lia. Qed.\n\nLemma even_div a : even a = true <-> (2 | a).\nProof.\n  split; intros.\n  - apply  Zeven_bool_iff in H; apply Zeven_ex in H. destruct H as [x]; exists x; lia.\n  - destruct H as [x]; rewrite H, even_mul, orb_true_r; reflexivity. Qed.\n\nLemma divide_lemma a b c (Hc : 0 < c) (Hcb : (c | b)) : (a | b / c) <-> (c * a | b).\nProof.\n  split; intros Habc.\n  - unfold divide in Habc. unfold divide.\n    destruct Habc as [k H]. exists k. replace (k * _) with (c * (b / c)) by lia.\n    rewrite <- Zdivide_Zdiv_eq by assumption. reflexivity.\n  - unfold divide in Habc. unfold divide.\n    destruct Habc as [k H]. exists k. replace b with (k * a * c) by lia.\n    rewrite Z.div_mul. reflexivity. lia. Qed.\n\nLemma log2_div a p (Ha : 0 < a) (Hp : 1 < p) : log2 (a / p) <= log2 a - 1 \\/ a = 1.\nProof.\n  pose proof log2_half a ltac:(lia).\n  destruct H; [left|right; assumption].\n  pose proof div_le_compat_l a 2 p ltac:(lia) ltac:(lia).\n  pose proof log2_le_mono (a / p) (a / 2) ltac:(assumption). lia. Qed.\n\nLemma odd_nonzero g : odd g = true -> g <> 0.\nProof. intros H Hg; subst; inversion H. Qed.\n\nLemma odd_divide a b : odd b = true -> (a | b) -> odd a = true.\nProof.\n  intros.\n  destruct (odd a) eqn:E.\n  - reflexivity.\n  - rewrite <- negb_even in E. apply negb_false_iff in E. apply even_div in E.\n    destruct E as [x]. destruct H0 as [z].\n    assert (2 | b).  exists (z * x).  lia. apply even_div in H2. rewrite <- negb_odd in H2.\n    apply negb_true_iff in H2. congruence. Qed.\n\nLemma gcd_odd_r a b : odd b = true -> odd (gcd a b) = true.\nProof. intros; eapply odd_divide. apply H. apply gcd_divide_r. Qed.\n\nLemma gcd_odd_l a b : odd a = true -> odd (gcd a b) = true.\nProof. intros; eapply odd_divide. apply H. apply gcd_divide_l. Qed.\n\nLemma divide_mul_l_l a b c : (a * b | c) -> (a | c).\nProof. intros [x]; exists (b * x); lia. Qed.\n\nLemma divide_mul_l_r a b c : (a * b | c) -> (b | c).\nProof. intros [x]; exists (a * x); lia. Qed.\n\nLemma mod2_dec a : { a mod 2 = 0 } + { a mod 2 = 1 }.\nProof. pose proof Zmod_even a; destruct (even a); auto. Qed.\n\nLemma min (f : nat -> Z) (H0 : f 0%nat <> 0) (H : exists N, f N = 0) :\n  exists K, f K <> 0 /\\ f (S K) = 0.\nProof.\n  destruct H as [N].\n  induction N.\n  - lia.\n  - destruct (eqb_spec (f N) 0).\n    + apply IHN. assumption.\n    + exists N. split.\n      * assumption.\n      * apply H. Qed.\n\nLemma gcd_rel_prime a b c : gcd a b = 1 -> gcd a c = gcd a (b * c).\nProof.\n  intros. symmetry. apply gcd_unique.\n  - apply gcd_nonneg.\n  - apply gcd_divide_l.\n  - apply divide_mul_r. apply gcd_divide_r.\n  - intros q qa qbc.\n    apply gauss in qbc.\n    + apply gcd_greatest; assumption.\n    + apply Zgcd_1_rel_prime. apply rel_prime_div with (p:=a).\n      apply Zgcd_1_rel_prime. assumption. assumption. Qed.\n\nNotation big_sum := (big_op op1 0)%RI.\n\nLemma big_sum_bound n f :\n  (forall i, (i <= n)%nat -> (1 <= f i)%nat) -> (n <= big_sum f 0 n)%nat.\nProof.\n  induction n; intros.\n  - cbn. lia.\n  - assert (forall i : nat, i <= n -> 1 <= f i)%nat by (intros; apply H; lia).\n    apply IHn in H0. rewrite big_op_S_r by lia.\n    assert (1 <= f n)%nat by (apply H; lia). cbn in *. lia. Qed.\n", "meta": {"author": "bshvass", "repo": "by-inversion", "sha": "281c10e6435a86e39b2c6e1829aa874e45147140", "save_path": "github-repos/coq/bshvass-by-inversion", "path": "github-repos/coq/bshvass-by-inversion/by-inversion-281c10e6435a86e39b2c6e1829aa874e45147140/src/Zlemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6849885667103864}}
{"text": "Require Import GeoCoq.Axioms.parallel_postulates.\nRequire Import GeoCoq.Tarski_dev.Annexes.saccheri.\n\nSection rah_thales_postulate.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma rah__thales_postulate : postulate_of_right_saccheri_quadrilaterals -> thales_postulate.\nProof.\n  intros rah A B C M HM HCong.\n  destruct (col_dec A B C).\n  { destruct (eq_dec_points A B).\n      treat_equalities; Perp.\n    destruct (l7_20 M A C); [ColR|Cong|..].\n      subst; Perp.\n    assert (B = C) by (apply l7_9 with M A; Midpoint).\n    subst; Perp.\n  }\n  apply (t22_17__rah _ _ _ M); assumption.\nQed.\n\nEnd rah_thales_postulate.", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Meta_theory/Parallel_postulates/rah_thales_postulate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6849435924544501}}
{"text": "(* A tiny example of Coq code *)\n\nSection EXAMPLE.\n   Variables A B C : Prop.\n   Theorem example : (A -> B) -> (B -> C) -> A -> C.\n   Proof.\n       intros H H' HA. apply H'. apply H. assumption. \n   Qed.\n\n   Definition example' : (A -> B) -> (B -> C) -> A -> C :=\n       fun (H : A -> B) (H' : B -> C) (HA : A) => H' (H HA).\n   Print example.\nEnd EXAMPLE.\n", "meta": {"author": "rodrigogribeiro", "repo": "unification", "sha": "f622364a63fdd959867410151749797c3e58e9b5", "save_path": "github-repos/coq/rodrigogribeiro-unification", "path": "github-repos/coq/rodrigogribeiro-unification/unification-f622364a63fdd959867410151749797c3e58e9b5/code/SBMF/Example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6849435836674974}}
{"text": "Require Import RBT.General.Basic.\nRequire Import RBT.General.BinaryTree.\n\nClass WithKey (Node Key: Type): Type :=\n  key: Node -> Key.\n\nSection SearchTree.\n\nContext {Node Key: Type} {WK: WithKey Node Key} {OK: ComputableTotalOrder Key}.\n\nInductive SearchTree': Key -> tree Node -> Key -> Prop :=\n| ST_E : forall lo hi, lo < hi -> SearchTree' lo E hi\n| ST_T: forall lo l x r hi,\n    SearchTree' lo l (key x) ->\n    SearchTree'  (key x) r hi ->\n    SearchTree' lo (T l x r) hi.\n\nInductive SearchTree: tree Node -> Prop :=\n| ST_intro: forall t lo hi, SearchTree' lo t hi -> SearchTree t.\n\nInductive SearchTree_half : Key -> list (half_tree Node) -> Key ->  Prop :=\n| ST_nil : forall lo hi, lo < hi -> SearchTree_half lo nil hi\n| ST_cons_LH : forall lo hi l x tree,\n  SearchTree_half lo l hi -> lo < key x -> key x < hi -> SearchTree' lo tree (key x) ->\n  SearchTree_half (key x) (LH x tree :: l) hi\n  (* TODO: (lo < key x) not necessary *)\n| ST_cons_RH : forall  lo  hi l x tree,\n  SearchTree_half lo l hi -> lo < key x -> key x < hi -> SearchTree' (key x) tree hi ->\n  SearchTree_half lo (RH tree x :: l) (key x).\n  (* TODO: (key x < hi) not necessary *)\n\nEnd SearchTree.\n\n", "meta": {"author": "maoliyuan", "repo": "avltree-verification", "sha": "1258e9bd5fa7d849ba8b387978bca41d56c64c9a", "save_path": "github-repos/coq/maoliyuan-avltree-verification", "path": "github-repos/coq/maoliyuan-avltree-verification/avltree-verification-1258e9bd5fa7d849ba8b387978bca41d56c64c9a/General/BinarySearchTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.684831484875008}}
{"text": "(** * CPDT Exercises 0.2 *)\n(* 1 *)\n(*\n  Prove these tautologies of propositional logic, using only the tactics apply, assumption,\n  constructor, destruct, intro, intros, left, right, split, and unfold.\n*)\nModule ex1.\n  Variable P Q R : Prop.\n\n  Theorem p1 : (True \\/ False) /\\ (False \\/ True).\n  Proof.\n    split; [ left; trivial | right; trivial].\n  Qed.\n\n  Theorem p2 : P -> ~ ~ P.\n  Proof.\n    unfold not; intros; apply H0; assumption.\n  Qed.\n\n  Theorem p3 : P /\\ (Q \\/ R) -> (P /\\ Q) \\/ (P /\\ R).\n  Proof.\n    destruct 1; destruct H0;\n      [ left; split; [ apply H | apply H0 ]\n      | right; split; [ apply H | apply H0 ]\n      ].\n  Qed.\n\nEnd ex1.\n\n(*\n  Prove the following tautology of first-order logic, using only the tactics apply, assert,\n  assumption, destruct, eapply, eassumption, and exists. You will probably find the\n  assert tactic useful for stating and proving an intermediate lemma, enabling a kind\n  of “forward reasoning,” in contrast to the “backward reasoning” that is the default for\n  Coq tactics. The tactic eassumption is a version of assumption that will do matching\n  of unification variables. Let some variable T of type Set be the set of individuals. x\n  is a constant symbol, p is a unary predicate symbol, q is a binary predicate symbol,\n  and f is a unary function symbol\n*)\n\nModule ex2.\n  Variable (T : Set) (x : T) (f : T -> T) (p : T -> Prop) (q : T -> T -> Prop).\n  Theorem tt : p x\n      -> (forall t, p t -> exists y, q t y)\n      -> (forall t y, q t y -> q y (f y))\n      -> (exists z, q z (f z)).\n  Proof.\n(* 1) if edestruct was permitted: *)\n(*    edestruct 2; [ eassumption | exists x0; apply H2 in H1; assumption ]. *)\n\n(* 2) apply with manually constructed proof is also a solution *)\n    apply (\n      fun (a : p x)\n          (b : forall t, p t -> exists y, q t y)\n          (c : forall t y, q t y -> q y (f y)) =>\n        match b x a with\n        | ex_intro _ k l => ex_intro (fun z => q z (f z)) k (c x k l)\n        end\n    ).\n  Qed.\nEnd ex2.\n\nModule ex3.\n  Require Import Arith Arith.Even Cpdt.CpdtTactics.\n\n  Inductive mult_6_or_10 : nat -> Prop :=\n    | m6 : forall n, mult_6_or_10 (n * 6)\n    | m10: forall n, mult_6_or_10 (n * 10).\n\n  Theorem not_satisfy_13 : ~ (mult_6_or_10 13).\n  Proof.\n    unfold not; inversion 1; crush.\n  Qed.\n\n  Hint Constructors even odd.\n  Theorem satisfy_even : forall n, mult_6_or_10 n -> even n.\n  Proof.\n    inversion 1; apply even_mult_r; auto 11.\n  Qed.\nEnd ex3.\n\nModule ex4.\n  Require Import Arith.\n\n  Definition var := nat.\n\n  Inductive exp : Set :=\n    | eConst : nat -> exp\n    | eAdd : nat -> nat -> exp\n    | ePair : exp -> exp -> exp\n    | eFst : exp -> exp\n    | eSnd : exp -> exp\n    | eVar : var -> exp.\n\n  Inductive cmd :=\n    | cExp : exp -> cmd\n    | cAss : var -> exp -> cmd -> cmd.\n\n  Definition map (T : Type) := var -> T.\n\n  Inductive value :=\n    | ConstValue : nat -> value\n    | PairValue : value -> value -> value.\n\n  Inductive assignType :=\n    | Env : map value -> assignType.\n\n  Inductive eval : exp -> assignType -> value -> Prop :=\n    | evV : forall n t, eval (eConst n) t (ConstValue n)\n    | evA : forall n1 n2 t, eval (eAdd n1 n2) t (ConstValue (n1 + n2))\n    | evP : forall e1 e2 t v1 v2,\n        eval e1 t v1 -> eval e1 t v2 -> eval (ePair e1 e2) t (PairValue v1 v2)\n    | evF : forall e1 e2 t v, eval e1 t v -> eval (ePair e1 e2) t v\n    | evS : forall e1 e2 t v, eval e2 t v -> eval (ePair e1 e2) t v\n    | evR : forall va (f : map value) v, f va = v -> eval (eVar va) (Env f) v.\n\n  Section example.\n    Variable a : assignType.\n    Example e : eval (eAdd 1 1) a (ConstValue 2). apply evA. Qed.\n  End example.\n\n  Inductive run : cmd -> assignType -> value -> Prop :=\n    | ruE : forall e v t, eval e t v -> run (cExp e) t v\n    | ruV : forall vV vE c eV cV f,\n        eval vE (Env f) eV ->\n        run c (Env (fun n => if eq_nat_dec n vV then eV else f n)) cV ->\n        run (cAss vV vE c) (Env f) cV.\n\n  Inductive typeType :=\n    | ConstType : typeType\n    | PairType : typeType -> typeType -> typeType.\n\n  Inductive typingType :=\n    | Typing : map typeType -> typingType.\n\n  Inductive isTypeOfExp : typingType -> typeType -> exp -> Prop :=\n    | isConst : forall t n, isTypeOfExp t ConstType (eConst n)\n    | isAdd : forall t n1 n2, isTypeOfExp t ConstType (eAdd n1 n2)\n    | isPair : forall t e1 t1, isTypeOfExp t t1 e1 -> forall e2 t2, isTypeOfExp t t2 e2 ->\n        isTypeOfExp t (PairType t1 t2) (ePair e1 e2)\n    | isFst : forall t e1 t1, isTypeOfExp t t1 e1 -> forall e2, isTypeOfExp t t1 (eFst (ePair e1 e2))\n    | isSnd : forall t e2 t2, isTypeOfExp t t2 e2 -> forall e1, isTypeOfExp t t2 (eSnd (ePair e1 e2))\n    | isVar : forall f v, isTypeOfExp (Typing f) (f v) (eVar v).\n\n  Inductive isTypeOfValue : typeType -> value -> Prop :=\n    | isC : forall n, isTypeOfValue ConstType (ConstValue n)\n    | isP : forall v1 t1, isTypeOfValue t1 v1 -> forall v2 t2, isTypeOfValue t2 v2 ->\n        isTypeOfValue (PairType t1 t2) (PairValue v1 v2).\n\n  Inductive isTypeOfCmd : typingType -> typeType -> cmd -> Prop :=\n    | isExp : forall t t1 e, isTypeOfExp t t1 e -> isTypeOfCmd t t1 (cExp e)\n    | isAss : forall f t1 e, isTypeOfExp (Typing f) t1 e ->\n        forall v c tc, isTypeOfCmd (Typing (fun m => if eq_nat_dec v m then t1 else f m)) tc c ->\n        isTypeOfCmd (Typing f) tc (cAss v e c).\n\n  Inductive varsType : assignType -> typingType -> Prop :=\n    | vtp : forall var fm tm v, fm var = v -> forall t, isTypeOfValue t v -> tm var = t ->\n        varsType (Env fm) (Typing tm).\n\n  Require Import Cpdt.CpdtTactics.\n\nEnd ex4.\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.2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.6848166936682434}}
{"text": "(** **** KE DING 8318 *)\n\n(** * 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    In this chapter we take a deeper look at the way propositions are\n    expressed in Coq and at the structure of the logical evidence that\n    we construct when we carry out proofs.  \n\n    Some of the concepts in this chapter may seem a bit abstract on a\n    first encounter.  We've included a _lot_ of exercises, most of\n    which should be quite approachable even if you're still working on\n    understanding the details of the text.  Try to work as many of\n    them as you can, especially the one-starred exercises. \n\n*)\n(* ##################################################### *)\n(** * Inductively Defined Propositions *)\n\n(** This chapter will take us on a first tour of the\n    propositional (logical) side of Coq.  As a running example, let's\n    define a simple property of natural numbers -- we'll call it\n    \"[beautiful].\" *)\n\n(** Informally, a number is [beautiful] if it is [0], [3], [5], or the\n    sum of two [beautiful] numbers.  \n\n    More pedantically, we can define [beautiful] numbers by giving four\n    rules:\n\n       - Rule [b_0]: The number [0] is [beautiful].\n       - Rule [b_3]: The number [3] is [beautiful]. \n       - Rule [b_5]: The number [5] is [beautiful]. \n       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is\n         their sum. *)\n\n(** We will see many definitions like this one during the rest\n    of the course, and for purposes of informal discussions, it is\n    helpful to have a lightweight notation that makes them easy to\n    read and write.  _Inference rules_ are one such notation: *)\n(**\n                              -----------                               (b_0)\n                              beautiful 0\n                              \n                              ------------                              (b_3)\n                              beautiful 3\n\n                              ------------                              (b_5)\n                              beautiful 5    \n\n                       beautiful n     beautiful m\n                       ---------------------------                      (b_sum)\n                              beautiful (n+m)   \n*)\n\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  The rules with no premises above the line are\n    called _axioms_.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8   \n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty) *)\n(** **** How many different ways are there to show that [8] is [beautiful]? *)\n(** **** Answer\n    (b_3)  (b_5)\n1) -------------- (b_sum)\n     beautiful 8\n\n    (b_5)  (b_3)\n2) -------------- (b_sum)\n     beautiful 8\n\n    (b_0)  (b_5)\n   -------------- (b_sum)  (b_3)\n3) ------------------------------ (b_sum)\n                    beautiful 8\n\n    (b_5)  (b_0)\n   -------------- (b_sum)  (b_3)\n4) ------------------------------ (b_sum)\n                    beautiful 8\n\n    (b_0)  (b_3)\n   -------------- (b_sum)  (b_5)\n5) ------------------------------ (b_sum)\n                    beautiful 8\n\n    (b_3)  (b_0)\n   -------------- (b_sum)  (b_5)\n6) ------------------------------ (b_sum)\n                    beautiful 8\n\nand 4 more. swap the first b_sum and the base beautiful number.\n\nSo that's 10.\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(** The first line declares that [beautiful] is a proposition -- or,\n    more formally, a family of propositions \"indexed by\" natural\n    numbers.  (That is, for each number [n], the claim that \"[n] is\n    [beautiful]\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.  Each of the remaining lines\n    embodies one of the rules for [beautiful] numbers.\n\n    We can use Coq's tactic scripting facility to assemble proofs that\n    particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the axiom [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have axioms for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(* ##################################################### *)\n(** * Proof Objects *)\n\n(** Look again at the formal definition of the [beautiful]\n    property.  The opening keyword, [Inductive], has been used up to\n    this point to declare new types of _data_, such as numbers and\n    lists.  Does this interpretation also make sense for the Inductive\n    definition of [beautiful]?  That is, can we view evidence of\n    beauty as some kind of data structure? Yes, we can!\n\n    The trick is to introduce an alternative pronunciation of \"[:]\".\n    Instead of \"has type,\" we can also say \"is a proof of.\"  For\n    example, the second line in the definition of [beautiful] declares\n    that [b_0 : beautiful 0].  Instead of \"[b_0] has type \n    [beautiful 0],\" we can say that \"[b_0] is a proof of [beautiful 0].\"\n    Similarly for [b_3] and [b_5]. *)\n\n(** This pun between types and propositions (between [:] as \"has type\"\n    and [:] as \"is a proof of\" or \"is evidence for\") is called the\n    _Curry-Howard correspondence_.  It proposes a deep connection\n    between the world of logic and the world of computation.\n<<\n                 propositions  ~  types\n                 proofs        ~  data values\n>>\n    Many useful insights follow from this connection.  To begin with, it\n    gives us a natural interpretation of the type of [b_sum] constructor: *)\n\nCheck b_sum.\n(* ===> b_sum : forall n m, \n                  beautiful n -> \n                  beautiful m -> \n                  beautiful (n+m) *)\n\n(** This can be read \"[b_sum] is a constructor that takes four\n    arguments -- two numbers, [n] and [m], and two values, of types\n    [beautiful n] and [beautiful m] -- and yields evidence for the\n    proposition [beautiful (n+m)].\" *)\n\n(** In view of this, we might wonder whether we can write an\n    expression of type [beautiful 8] by applying [b_sum] to\n    appropriate arguments.  Indeed, we can: *)\n\nCheck (b_sum 3 5 b_3 b_5).  \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(** ** 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\nPrint eight_is_beautiful''.\n\n(** At any given moment, Coq has constructed a term with some\n    \"holes\" (indicated by [?1], [?2], and so on), and it knows what\n    type of evidence is needed at each hole.  In the [Show Proof]\n    output, lines of the form [?1 -> beautiful n] record these\n    requirements.  (The [->] here has nothing to do with either\n    implication or function types -- it is just an unfortunate choice\n    of concrete syntax for the output!)  \n\n    Each of the holes corresponds to a subgoal, and the proof is\n    finished when there are no more subgoals.  At this point, the\n    [Theorem] command gives a name to the evidence we've built and\n    stores it in the global context. *)\n\n(** Tactic proofs are useful and convenient, but they are not\n    essential: in principle, we can always construct the required\n    evidence by hand.  Indeed, we don't even need the [Theorem]\n    command: we can instead use [Definition] to directly give a global\n    name to a piece of evidence. *)\n\nDefinition eight_is_beautiful''' : beautiful 8 :=\n  b_sum 3 5 b_3 b_5.\n\n(** All these different ways of building the proof lead to exactly the\n    same evidence being saved in the global environment. *)\n\nPrint eight_is_beautiful.\n(* ===> eight_is_beautiful    = b_sum 3 5 b_3 b_5 : beautiful 8 *)\nPrint eight_is_beautiful'.\n(* ===> eight_is_beautiful'   = b_sum 3 5 b_3 b_5 : beautiful 8 *)\nPrint eight_is_beautiful''.\n(* ===> eight_is_beautiful''  = b_sum 3 5 b_3 b_5 : beautiful 8 *)\nPrint eight_is_beautiful'''.\n(* ===> eight_is_beautiful''' = b_sum 3 5 b_3 b_5 : beautiful 8 *)\n\n(** **** Exercise: 1 star (six_is_beautiful) *)\n(** Give a tactic proof and a proof object showing that [6] is [beautiful]. *)\n\nTheorem six_is_beautiful :\n  beautiful 6.\nProof.\n  apply (b_sum 3 3 b_3 b_3).\nQed.\n\nDefinition six_is_beautiful' : beautiful 6 :=\n  b_sum 3 3 b_3 b_3.\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  apply (b_sum 3 6 b_3 six_is_beautiful').\nQed.\n\nDefinition nine_is_beautiful' : beautiful 9 :=\n  b_sum 6 3 six_is_beautiful b_3.\n(** [] *)\n\n\n(* ##################################################### *)\n(** ** Implications and Functions *)\n\n(** In Coq's computational universe (where we've mostly been living\n    until this chapter), there are two sorts of values with arrows in\n    their types: _constructors_ introduced by [Inductive]-ly defined\n    data types, and _functions_.\n\n    Similarly, in Coq's logical universe, there are two ways of giving\n    evidence for an implication: constructors introduced by\n    [Inductive]-ly defined propositions, and... functions!\n\n    For example, consider this statement: *)\n\nTheorem b_plus3: forall n, beautiful n -> beautiful (3+n).\nProof.\n   intros n H.\n   apply b_sum.\n   apply b_3.\n   apply H.\n   Show Proof.\nQed.\n\n(** What is the proof object corresponding to [b_plus3]? \n\n    We're looking for an expression whose _type_ is [forall n,\n    beautiful n -> beautiful (3+n)] -- that is, a _function_ that\n    takes two arguments (one number and a piece of evidence) and\n    returns a piece of evidence!  Here it is: *)\n\nDefinition b_plus3' : forall n, beautiful n -> beautiful (3+n) := \n  fun n => fun H : beautiful n =>\n    b_sum 3 n b_3 H.\n\nCheck b_plus3'.\n(* ===> b_plus3' : forall n, beautiful n -> beautiful (3+n) *)\n\n(** Recall that [fun n => blah] means \"the function that, given [n],\n    yields [blah].\"  Another equivalent way to write this definition is: *)\n\nDefinition b_plus3'' (n : nat) (H : beautiful n) : beautiful (3+n) := \n    b_sum 3 n b_3 H.\n\nCheck b_plus3''.\n(* ===> b_plus3'' : forall n, beautiful n -> beautiful (3+n) *)\n\n(** **** Exercise: 2 stars (b_times2) *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n  intros n.\n  assert (A : 2 * n = n + n).\n  Case \"Proof of assert\".\n    destruct n.\n    SCase \"n = 0\".\n      reflexivity.\n    SCase \"n = S n\".\n      simpl.\n      rewrite -> plus_0_r.\n      reflexivity.\n  rewrite -> A.\n  intros H.\n  apply (b_sum n n H H).\nQed.    \n      \nTheorem b_times2'': forall n, beautiful n -> beautiful (2*n).\nProof.\n  intros.\n  induction n.\n  Case \"n = 0\".\n    simpl.\n    apply b_0.\n  Case \"n = S n\".\n    simpl.\n    rewrite -> plus_0_r.\n    rewrite <- plus_Sn_m.\n    apply (b_sum (S n) (S n) H H).\nQed.    \n(** [] *)\n\n(** **** Exercise: 3 stars, optional (b_times2') *)\n(** Write a proof object corresponding to [b_times2] above *)\nCheck b_times2.\nPrint eq_ind_r.\nCheck eq_ind_r.\nDefinition b_times2': forall n, beautiful n -> beautiful (2*n) :=\n  fun n => fun H : beautiful n =>\n    b_sum n (n + 0) H (eq_ind_r (fun n' => beautiful n') H (plus_0_r n)).\nPrint eq_ind_r.\n(** **** Exercise: 2 stars (b_timesm) *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n  intros.\n  induction m.\n  Case \"m = 0\".\n    simpl.\n    apply b_0.\n  Case \"m = S m\".\n    simpl.\n    apply (b_sum n (m*n) H IHm).\nQed.\n(** [] *)\n\n(* ####################################################### *)\n(** ** Induction Over Proof Objects *)\n\n(** Since we use the keyword [Induction] to define primitive\n    propositions together with their evidence, we might wonder whether\n    there are some sort of induction principles associated with these\n    definitions.  Indeed there are, and in this section we'll take a\n    look at how they can be used.  *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells us not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    two constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]), \n      - [E] is [b_5] (and [n] is [5]), or \n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n    \n(** This gives rise to an _induction principle_ for proofs -- i.e., we\n    can use the [induction] tactic that we have already seen for\n    reasoning about inductively defined _data_ to reason about\n    inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree) *)\n(** **** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n*)\n(** **** Answer for gorgeous_tree\n                     gorgeous n                gorgeous n\n   ---------- [g_0]  -------------- [g_plus3]  -------------- [g_plus5]\n   gorgeous 0        gorgeous (3+n)            gorgeous (5+n)           \n**)\n\n(** It seems intuitively obvious that, although [gorgeous] and\n    [beautiful] are presented using slightly different rules, they are\n    actually the same property in the sense that they are true of the\n    same numbers.  Indeed, we can prove this. *)\n\nTheorem gorgeous__beautiful : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros n H.\n   induction H as [|n'|n'].\n   Case \"g_0\".\n       apply b_0.\n   Case \"g_plus3\". \n       apply b_sum. apply b_3.\n       apply IHgorgeous.\n   Case \"g_plus5\".\n       apply b_sum. apply b_5. apply IHgorgeous. \nQed.\n\n(** Notice that the argument proceeds by induction on the _evidence_ [H]! *) \n\n(** Let's see what happens if we try to prove this by induction on [n]\n   instead of induction on the evidence [H]. *)\n\nTheorem gorgeous__beautiful_FAILED : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAdmitted.\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(** **** Exercise: 1 star (gorgeous_plus13) *)\nTheorem gorgeous_plus13: forall n, \n   gorgeous n -> gorgeous (13+n).\nProof.\n   intros n H.\n   induction H as [|n' |n'].\n   Case \"g_0\".\n     simpl.\n     apply g_plus3.\n     apply g_plus5.\n     apply g_plus5.\n     apply g_0.\n   Case \"g_plus3\".\n     rewrite -> plus_assoc.\n     simpl.\n     apply g_plus3.\n     apply IHgorgeous.\n   Case \"g_plus5\".\n     rewrite -> plus_assoc.\n     simpl.\n     apply g_plus5.\n     apply IHgorgeous.\nShow Proof.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (gorgeous_plus13_po):\nGive the proof object for theorem [gorgeous_plus13] above. *)\n\nDefinition gorgeous_plus13_po: forall n, gorgeous n -> gorgeous (13+n):=\n  fun n => fun H : gorgeous n => g_plus3 (5+5+n) (g_plus5 (5+n) (g_plus5 n H)).\n\nCheck gorgeous_plus13.\nCheck gorgeous_plus13_po.\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.\n  induction Hn as [|n' |n'].\n  Case \"g_0\".\n    simpl.\n    intros Hm.\n    apply Hm.\n  Case \"g_plus3\".\n    intros Hm.\n    apply g_plus3.\n    apply (IHHn Hm).\n  Case \"g_plus5\".\n    intros Hm.\n    apply g_plus5.\n    apply (IHHn Hm).\nQed.\n    \n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n  intros n H.\n  induction H as [|_ |_ |p q].\n  Case \"b_0\".\n    apply g_0.\n  Case \"b_3\".\n    apply g_plus3.\n    apply g_0.\n  Case \"b_5\".\n    apply g_plus5.\n    apply g_0.\n  Case \"b_sum\".\n    apply (gorgeous_sum p q IHbeautiful1 IHbeautiful2).\nQed.\n\n(** **** Exercise: 3 stars, optional (b_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   Case \"g_0\".\n     simpl.\n     apply g_0.\n   Case \"g_plus3\".\n     rewrite -> helper_g_times2.\n     rewrite -> helper_g_times2.\n     rewrite -> helper_g_times2.\n     simpl.\n     apply g_plus3.\n     apply g_plus3.\n     rewrite -> helper_g_times2 in IHgorgeous.\n     apply IHgorgeous.\n   Case \"g_plus5\".\n     rewrite -> helper_g_times2.\n     rewrite -> helper_g_times2.\n     rewrite -> helper_g_times2.\n     simpl.\n     apply g_plus5.\n     apply g_plus5.\n     rewrite -> helper_g_times2 in IHgorgeous.\n     apply IHgorgeous.\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(** 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(** Construct a tactic proof of the following proposition. *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  intros.\n  induction n.\n    simpl.\n    apply ev_0.\n    simpl.\n    apply (ev_SS (double n) IHn).\nShow Proof.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (double_even_pfobj) *)\n(** **** Try to predict what proof object is constructed by the above\n    tactic proof.  (Before checking your answer, you'll want to\n    strip out any uses of [Case], as these will make the proof\n    object look a bit cluttered.) *)\n(** **** Answer\nDefinition double_even_pfobj (n : nat) : Prop :=\n  fun n => nat_ind (fun n' => ev (double n'))\n                   ev_0\n                   (fun _ IHn => ev_SS _ IHn)\n                   n.\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(** ** [Inversion] on Proof Objects *)\n\n(** Besides [induction], we can use the other tactics in our toolkit\n    to reason about evidence.  For example, this proof uses [destruct]\n    on 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'].\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 [destruct] on [n] instead of [E]? *)\n\nTheorem ev_minus2_fail: forall n,\n  ev n -> ev (pred (pred n)). \nProof.\n  intros n E.\n  destruct n as [|n'].\n    simpl. apply ev_0.\n    simpl. Admitted.\n(** **** Answer\n    we got stuck, since we must show [ev (S n)] -> [ev (pred n)] which is \n    be provable, because it is 1 step from n to n', and we need 2 step to\n    see even.\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\nTheorem ev__even' : forall n,\n  ev n -> even n.\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n = 0\".\n    intros ev.\n    unfold even.\n    reflexivity.\n  Case \"n = S n'\".\n    intros ev.\n    Admitted.\n(** **** Answer\n    we got stuck, since the two hypothesis in the context [ev (S n')] and [ev n']\n    are conflict that we can not use both. But without the hypothesis we can not \n    prove the proposition.\n**)     \n    \n\n(** [] *)\n\n(** The induction principle for inductively defined propositions does\n    not follow quite the same form as that of inductively defined\n    sets.  For now, you can take the intuitive view that induction on\n    evidence [ev n] is similar to induction on [n], but restricts our\n    attention to only those numbers for which evidence [ev n] could be\n    generated.  We'll look at the induction principle of [ev] in more\n    depth below, to explain what's really going on. *)\n\n(** **** Exercise: 1 star (l_fails) *)\n(** **** The following proof attempt will not succeed. **)\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  Briefly explain why.\nAnswer: \n  First, we can take the intuitive view that not all the n are even.\n  Then look at the definition of Inductive [ev], which is constructed \n  by [ev_0] and [ev_SS]. And the Case \"S\" can not be generated by neither \n  of the constructors or their combination.\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 evN evM.\n  induction evN as [|n'].\n  Case \"ev_0\".\n    simpl.\n    apply evM.\n  Case \"ev_SS\".\n    simpl.\n    apply (ev_SS (n' + m) IHevN).\nQed.\n\n(** [] *)\n\n(** Another situation where we want to analyze evidence for evenness\n    is when proving that, if [n+2] is even, then [n] is. *)\n\n(** Our first idea might be to use [destruct] for this kind of case\n    analysis: *)\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  (* Stuck: [destruct] gives us an unprovable subgoal here! *)\nAdmitted.\n\n(** In the first sub-goal, we've lost the information that [n] is [0].\n    We could have used [remember], but then we still need [inversion]\n    on both cases. *)\n\nTheorem SSev_ev_secondtry : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. remember (S (S n)) as n2.\n  destruct E as [| n' E'].\n  Case \"n = 0\". inversion Heqn2.\n  Case \"n = S n'\". inversion Heqn2. rewrite <- H0. apply E'.\nQed.\n\n(** There is a much simpler way to do this. We can use\n    [inversion] directly on the inductively defined proposition\n    [ev (S (S n))]. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. inversion E as [| n' E']. apply E'. Qed.\n\n(** This use 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    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(** **** Exercise: 1 star (inversion_practice) *)\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros.\n  inversion H.\n  inversion H1.\n  apply H3.\nQed.\n\n(** The [inversion] tactic can also be used to derive goals by showing\n    the absurdity of a hypothesis. *)\n\nTheorem even5_nonsense : \n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros.\n  inversion H.\n  inversion H1.\n  inversion H3.\nQed.\n(** [] *)\n\n(** We can generally use [inversion] on inductive propositions.\n    This illustrates that in general, we get one case for each\n    possible constructor.  Again, we also get some auxiliary\n    equalities that are rewritten in the goal but not in the other\n    hypotheses. *)\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\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 evS evN.\n  generalize dependent evS.\n  induction evN as [|n'].\n  Case \"ev_0\".\n    simpl.\n    intros evS.\n    apply evS.\n  Case \"ev_SS\".\n    simpl.\n    intros evS.\n    inversion evS.\n    apply (IHevN 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.  You'll want the [replace] tactic used for [plus_swap']\n    in Basics.v *)\nCheck plus_swap'.\nCheck ev_ev__ev.\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  intros n m p evNM evNP.\n  apply (ev_sum (n+m) (n+p) evNM) in evNP.\n  replace (n + m + (n + p)) with (n + n + (m + p)) in evNP.\n  replace (n + n) with (double n) in evNP.\n  apply (ev_ev__ev (double n) (m+p) evNP (double_even n)).\n  apply double_plus.\n  Check plus_swap'.\n  rewrite <- plus_assoc.\n  rewrite <- plus_assoc.\n  rewrite -> plus_swap' with (n := n) (m := m) (p := p).\n  reflexivity.\nQed.\n\n(** [] *)\n\n(* ####################################################### *)\n(** ** Building Proof Objects Incrementally (Optional) *)\n\n(** As you probably noticed while solving the exercises earlier in the\n    chapter, constructing proof objects is more involved than\n    constructing the corresponding tactic proofs. Fortunately, there\n    is a bit of syntactic sugar that we've already introduced to help\n    in the construction: the [admit] term, which we've sometimes used\n    to force Coq into accepting incomplete exercies. As an example,\n    let's walk through the process of constructing a proof object\n    demonstrating the beauty of [16]. *)\n\nDefinition b_16_atmpt_1 : beautiful 16 := admit.\n\n(** Maybe we can use [b_sum] to construct a term of type [beautiful 16]?\n    Recall that [b_sum] is of type\n\n    forall n m : nat, beautiful n -> beautiful m -> beautiful (n + m)\n\n    If we can demonstrate the beauty of [5] and [11], we should\n    be done. *)\n\nDefinition b_16_atmpt_2 : beautiful 16 := b_sum 5 11 admit admit.\n\n(** In the attempt above, we've omitted the proofs of the propositions\n    that [5] and [11] are beautiful. But the first of these is already\n    axiomatized in [b_5]: *)\n\nDefinition b_16_atmpt_3 : beautiful 16 := b_sum 5 11 b_5 admit.\n\n(** What remains is to show that [11] is beautiful. We repeat the\n    procedure: *)\n\nDefinition b_16_atmpt_4 : beautiful 16 :=\n  b_sum 5 11 b_5 (b_sum 5 6 admit admit).\n\nDefinition b_16_atmpt_5 : beautiful 16 :=\n  b_sum 5 11 b_5 (b_sum 5 6 b_5 admit).\n\nDefinition b_16_atmpt_6 : beautiful 16 :=\n  b_sum 5 11 b_5 (b_sum 5 6 b_5 (b_sum 3 3 admit admit)).\n\n(** And finally, we can complete the proof object: *)\n\nDefinition b_16 : beautiful 16 :=\n  b_sum 5 11 b_5 (b_sum 5 6 b_5 (b_sum 3 3 b_3 b_3)).\n\n(** To recap, we've been guided by an informal proof that we have in\n    our minds, and we check the high level details before completing\n    the intricacies of the proof. The [admit] term allows us to do\n    this. *)\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*)\nInductive pal {X : Type} : list X -> Prop :=\n  p_0 : pal []\n| p_1 : forall x : X, pal [x]\n| p_app : forall k l, pal l -> pal (k ++ l ++ (rev k)).\n\nExample test_pal0 : @pal nat [].\nProof. apply p_0.  Qed.\n\nExample test_pal1 : pal [2].\nProof. apply p_1.  Qed.\n\nExample test_pal2 : pal [2, 2].\nProof. apply (p_app [2] [] p_0).  Qed.\n\nExample test_pal3 : pal [2, 1, 1, 2].\nProof. apply (p_app [2,1] [] p_0).  Qed.\n\nExample test_pal4 : pal [2, 1, 0, 1, 2].\nProof. apply (p_app [2,1] [0] (p_1 0)).  Qed.\n\nLemma cons_append : forall {X : Type} (l: list X) (n : X),\n  n::l = [n] ++ l.\nProof.\n  intros X l n.\n  destruct l as [| n' l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l= n' :: l'\".\n    simpl.\n    reflexivity. \nQed.\n\nLemma snoc_append : forall {X : Type} (l: list X) (n : X),\n  snoc l n = l ++ [n].\nProof.\n  intros X l n.\n  induction l as [| n' l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l= n' :: l'\".\n    simpl.\n    rewrite -> IHl'.\n    reflexivity. \nQed.\n\nTheorem app_ass : forall {X : Type}, forall l1 l2 l3 : list X, \n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).   \nProof.\n  intros X l1 l2 l3. \n  induction l1 as [| n l1'].\n  Case \"l1 = nil\".\n    reflexivity.\n  Case \"l1 = cons n l1'\".\n    simpl. \n    rewrite -> IHl1'. \n    reflexivity.  \nQed.\n\nTheorem l_app_revl : forall {X : Type}, forall l : list X,\n  pal (l ++ rev l).\nProof.\n  intros.\n  induction l as [|x l'].\n  Case \"l = []\".\n    simpl.\n    apply p_0.\n  Case \"l = x::l'\".\n    simpl.\n    rewrite -> snoc_append.\n    rewrite -> cons_append.\n    rewrite <- app_ass with (l1:=l').\n    apply (p_app [x] (l'++ rev l') IHl').\nQed.\n\nLemma app_nil : forall X (l : list X), \n  l ++ [] = l.   \nProof.\n  induction l as [| n l'].\n  Case \"l = []\".\n  reflexivity.\n  Case \"l = n::l'\".\n  simpl.\n  rewrite -> IHl'.\n  reflexivity. Qed.\n\nLemma rev_app : forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros.\n  induction l1 as [|x1 l'].\n  Case \"l1 = []\".\n    simpl.\n    rewrite -> app_nil with (l := rev l2).\n    reflexivity.\n  Case \"l1 = x1::l'\".\n    simpl.\n    rewrite -> IHl'.\n    rewrite -> snoc_append.\n    rewrite -> snoc_append.\n    apply app_ass.\nQed.\n\nLemma rev_snoc_involutive : forall X (n : X) (l : list X),\n  rev (snoc l n) = n :: (rev l).\nProof.\n  intros.\n  induction l as [| n' l'].\n  Case \"l = []\".\n  reflexivity.\n  Case \"l = n' :: l'\".\n  simpl.\n  rewrite -> IHl'.\n  reflexivity. Qed.\n\nTheorem rev_involutive : forall X (l : list X),\n  rev (rev l) = l.\nProof.\n  intros.\n  induction l as [| n l'].\n  Case \"l = []\".\n  reflexivity.\n  Case \"l = n::l'\".\n  simpl.\n  rewrite -> rev_snoc_involutive.\n  rewrite -> IHl'.\n  reflexivity. Qed.\n\nTheorem pal_rev : forall {X : Type}, forall l : list X,\n  pal l -> l = rev l.\nProof.\n  intros.\n  induction H as [|x |k l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = [x]\".\n    reflexivity.\n  Case \"l = k++l'++k\".\n    rewrite -> rev_app.\n    rewrite -> rev_app.\n    rewrite -> rev_involutive.\n    rewrite <- IHpal.\n    symmetry.\n    apply app_ass.\nQed.\n(** [] *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse) *)\n(** **** Using your definition of [pal] from the previous exercise, prove\n    that\n     forall l, l = rev l -> pal l.\n*)\nTheorem rev_pal : forall {X : Type}, forall l : list X,\n  l = rev l -> pal l.\nProof.\n  intros.\n  induction l as [|x l'].\n  Case \"l = []\".\n    apply p_0.\n  Case \"l = x::l'\".\n    (** **** conflic here : \n      H : x :: l' = rev (x :: l')\n      IHl' : l' = rev l' -> pal l'\n      by H we cannot show that [l' = rev l'], without the prerequisite of IHl'\n      we can not continue the induction.\n      Is there some other way to divide the Case?\n     **)\nAdmitted.\n\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (subsequence) *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n    [1,2,3]\n    is a subsequence of each of the lists\n    [1,2,3]\n    [1,1,1,2,2,3]\n    [1,2,7,3]\n    [5,6,1,9,9,2,7,3,8]\n    but it is _not_ a subsequence of any of the lists\n    [1,2]\n    [1,3]\n    [5,6,2,1,7,3,8]\n\n    - Define an inductive proposition [subseq] on [list nat] that\n      captures what it means to be a subsequence. (Hint: You'll need\n      three cases.)\n\n    - Prove that subsequence is reflexive, that is, any list is a\n      subsequence of itself.  \n\n    - Prove that for any lists [l1], [l2], and [l3], if [l1] is a\n      subsequence of [l2], then [l1] is also a subsequence of [l2 ++\n      l3].\n\n    - (Optional, harder) Prove that subsequence is transitive -- that\n      is, if [l1] is a subsequence of [l2] and [l2] is a subsequence\n      of [l3], then [l1] is a subsequence of [l3].  Hint: choose your\n      induction carefully!\n*)\n\nFixpoint In {X : Type} (x : X) (l : list X) : Prop :=\n  match l with\n    | nil => False\n    | y :: l' => x = y /\\ In x l'\n  end.\n\nFixpoint trim_sub (sub l : list nat) : list nat :=\n  match sub, l with\n    | nil, _ => l\n    | _, nil => nil\n    | x::sub', y::l' => if (beq_nat x y) then trim_sub sub' l'\n                                         else trim_sub sub l'\n  end.\n  \nInductive subseq_fail : list nat -> list nat -> Prop :=\n    subseq_0 : forall l : list nat, subseq_fail [] l\n  | subseq_1 : forall (n : nat) (l : list nat), In n l -> subseq_fail [n] l\n  | subseq_ : forall (n : nat) (sub l : list nat), \n              subseq_fail sub l -> In n (trim_sub sub l) -> subseq_fail (snoc sub n) l.\n\nInductive subseq {X : Type} : list X -> list X -> Prop :=\n  | sub_nil   : forall (l : list X), subseq nil l\n  | sub_drop  : forall (x : X) (sub l : list X), \n    subseq sub l -> subseq sub (x :: l)\n  | sub_match : forall (x : X) (sub l : list X), \n    subseq sub l -> subseq (x :: sub) (x :: l).\n\nTheorem sub_app : forall {X : Type} (l1 l2 l3 : list X),\n  subseq l1 l2 -> subseq l1 (l2 ++ l3).\nProof.\n  intros.\n  induction H as [|x sub l |x sub l].\n  Case \"[sub_nil]\".\n    apply (sub_nil (l ++ l3)).\n  Case \"[sub_frop]\".\n    simpl.\n    apply (sub_drop x sub (l ++ l3) IHsubseq).\n  Case \"[sub_match]\".\n    simpl.\n    apply (sub_match x sub (l++l3) IHsubseq).\nQed.\n\nLemma subseq_cons : forall {X : Type} (x : X) (sub l : list X),\n  subseq (x::sub) l -> subseq sub l.\nProof.\n  intros.\n  induction l as [|y l'].\n  Case \"l = []\".\n    inversion H.\n  Case \"l = y::l'\".\n    inversion H.\n    SCase \"sub_drop\".\n      apply IHl' in H2.\n      apply (sub_drop y sub l' H2).\n    SCase \"sub_match\".\n      apply (sub_drop y sub l' H1).\nQed.\n  \nTheorem subseq_transitive_fail1 : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof.\n  intros l1 l2 l3 H12 H23.\n  induction H23 as [l3 |x l2 l3' |x l2' l3'].\n  Case \"sub_nil\".\n    inversion H12.\n    apply sub_nil.\n  Case \"sub_drop\".\n    apply IHsubseq in H12.\n    apply (sub_drop x l1 l3' H12).\n  Case \"sub_match\".\nAdmitted.\n\nTheorem subseq_transitive_fail2 : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof.\n  intros l1 l2 l3 H12 H23.\n  induction H12 as [l2 |x l1 l2' |x l1' l2'].\n  Case \"sub_nil\".\n    apply sub_nil.\n  Case \"sub_drop\".\n    apply subseq_cons in H23.\n    apply IHsubseq in H23.\n    apply H23.\n  Case \"sub_match\".\nAdmitted.    \n\nTheorem subseq_transitive : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof.\n  intros l1 l2 l3 H12 H23.\n  generalize dependent l1.\n  generalize dependent l3.\n  induction l2 as [|x' l'].\n  Case \"l = []\".\n    intros.\n    inversion H12.\n    apply sub_nil.\n  Case \"l = x'::l'\".\n    intros.\n    apply IHl'.\n    apply (subseq_cons x' l' l3) in H23.\n    apply H23.\nAdmitted.\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(** **** Answer for R_provability\n    - [R 2 [1,0]]\n    - [R 1 [1,2,1,0]]\n\nstandard R should be as below: \n\n  R 0 []\n  R 1 [0]\n  R 2 [1,0]\n  R 3 [2,1,0]\n  R 4 [3,2,1,0]\n  R 5 [4,3,2,1,0]\n  R 6 [5,4,3,2,1,0]\n\neasy to see that [R 2 [1,0]] is definitely right \nand [R 6 [3,2,1,0]] is definitely wrong.\naccording to c3, [R n list]'s checking is from [n]th element toward the low element,\nso [R 1 [1,2,1,0]] is provable too.\n**)\n\n\n(* ##################################################### *)\n(* ##################################################### *)\n(* ##################################################### *)\n(* ##################################################### *)\n\n(* $Date: 2013-02-05 15:23:05 -0500 (Tue, 05 Feb 2013) $ *)\n\n(** **** KE DING 8318 *)\n", "meta": {"author": "gf4t47", "repo": "coq", "sha": "420c6322eb340e0a0299f5ac07a2a6f495ffc72d", "save_path": "github-repos/coq/gf4t47-coq", "path": "github-repos/coq/gf4t47-coq/coq-420c6322eb340e0a0299f5ac07a2a6f495ffc72d/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.8872046026642944, "lm_q1q2_score": 0.6847831131318288}}
{"text": "(* --------------------------------------------------------------------\n * Copyright (c) - 2006--2012 - IMDEA Software Institute\n * Copyright (c) - 2006--2012 - Inria\n * Copyright (c) - 2006--2012 - Microsoft Coprporation\n *\n * Distributed under the terms of the CeCILL-B-V1 license\n * -------------------------------------------------------------------- *)\n\n\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(**********************************************************************\n    Proth.v                        \n                                                                     \n    Proth's Test \n                                                                 \n    Definition: ProthTest              \n **********************************************************************)\nRequire Import ZArith.\nRequire Import ZAux.\nRequire Import Pocklington.\n\nOpen Scope Z_scope.\n\nTheorem ProthTest: forall h k a, let n := h * 2 ^ k + 1 in 1 < a -> 0 < h < 2 ^k -> (a ^ ((n - 1) / 2) + 1) mod n = 0 -> prime n.\nintros h k a n; unfold n; intros H H1 H2.\nassert (Hu: 0 < h * 2 ^ k).\napply Zmult_lt_O_compat; auto with zarith.\nassert (Hu1: 0 < k).\ncase (Zle_or_lt k 0); intros Hv; auto.\ngeneralize H1 Hv; case k; simpl.\nintros (Hv1, Hv2); contradict Hv2; auto with zarith.\nintros p1 _ Hv1; contradict Hv1; auto with zarith.\nintros   p (Hv1, Hv2); contradict Hv2; auto with zarith.\napply PocklingtonCorollary1 with (F1 := 2 ^ k) (R1 := h); auto with zarith.\nring.\napply Zlt_le_trans with ((h + 1) * 2 ^ k); auto with zarith.\nrewrite Zmult_plus_distr_l; apply Zplus_lt_compat_l.\nrewrite Zmult_1_l; apply Zlt_le_trans with 2; auto with zarith.\nintros p H3 H4.\ngeneralize H2; replace (h * 2 ^ k + 1 - 1) with (h * 2 ^k); auto with zarith; clear H2; intros H2.\nexists a; split; auto; split.\npattern (h * 2 ^k) at 1; rewrite (Zdivide_Zdiv_eq  2 (h * 2 ^ k)); auto with zarith.\nrewrite (Zmult_comm 2); rewrite Zpower_mult; auto with zarith.\nrewrite Zmod_Zpower; auto with zarith.\nassert (tmp: forall p, p = (p + 1) -1); auto with zarith; rewrite (fun x => (tmp (a ^ x))).\nrewrite Zmod_minus; auto with zarith.\nrewrite H2.\nrewrite (Zmod_def_small 1); auto with zarith.\nrewrite <- Zmod_Zpower; auto with zarith.\nrewrite Zmod_def_small; auto with zarith.\nsimpl; unfold Zpower_pos; simpl; auto with zarith.\napply Zge_le; apply Z_div_ge0; auto with zarith.\napply Zdivide_trans with (2 ^ k).\napply Zpower_divide; auto with zarith.\napply Zdivide_factor_l; auto with zarith.\napply Zis_gcd_gcd; auto with zarith.\napply Zis_gcd_intro; auto with zarith.\nintros x HD1 HD2.\nassert (Hd1: p = 2).\napply prime_div_Zpower_prime with (4 := H4); auto with zarith.\napply prime2.\nassert (Hd2: (x | 2)).\nreplace 2 with ((a ^ (h * 2 ^ k / 2) + 1) - (a ^ (h * 2 ^ k/ 2) - 1)); auto with zarith.\napply Zdivide_minus_l; auto.\napply Zdivide_trans with (1 := HD2).\napply Zmod_divide; auto with zarith.\npattern 2 at 2; rewrite <- Hd1; auto.\nreplace 1 with ((h * 2 ^k + 1) - (h * 2 ^ k)); auto with zarith.\napply Zdivide_minus_l; auto.\napply Zdivide_trans with (1 := Hd2); auto.\napply Zdivide_trans with (2 ^ k).\napply Zpower_divide; auto with zarith.\napply Zdivide_factor_l; auto with zarith.\nQed.\n\n\nDefinition proth_test h k a :=\n  let n := h * 2 ^ k + 1 in \n   if (Z_lt_dec 1  a) then \n      if (Z_lt_dec 0 h) then\n        if (Z_lt_dec h (2 ^k)) then\n            if Z_eq_dec (Zpow_mod a  ((n - 1) / 2) n) (n - 1) then true\n            else false else false else false else false. \n\n \nTheorem ProthTestOp: forall h k a, proth_test h k a = true -> prime (h * 2 ^ k + 1).\nintros h k a; unfold proth_test.\nrepeat match goal with |- context[if ?X then _ else _] => case X end; try (intros; discriminate).\nintros H1 H2 H3 H4 _.\nassert (Hu: 0 < h * 2 ^ k).\napply Zmult_lt_O_compat; auto with zarith.\napply ProthTest with (a := a); auto.\nrewrite Zmod_plus; auto with zarith.\nrewrite <- Zpow_mod_Zpower_correct; auto with zarith.\nrewrite H1.\nrewrite (Zmod_def_small 1); auto with zarith.\nreplace (h * 2 ^ k + 1 - 1 + 1) with (h * 2 ^ k + 1); auto with zarith.\napply Zdivide_mod; auto with zarith.\napply Zge_le; apply Z_div_ge0; auto with zarith.\nQed.\n\nTheorem prime5: prime 5.\nexact (ProthTestOp 1 2 2 (refl_equal _)).\nQed.\n\nTheorem prime17: prime 17.\nexact (ProthTestOp 1 4 3 (refl_equal _)).\nQed.\n\nTheorem prime257:  prime 257.\nexact (ProthTestOp 1 8 3 (refl_equal _)).\nQed.\n\nTheorem prime65537:  prime 65537.\nexact (ProthTestOp 1 16 3 (refl_equal _)).\nQed.\n\n(* Too touch !! \nTheorem prime4294967297:  prime 4294967297.\nexact (ProthTestOp 1 32 3 (refl_equal _)).\nQed.\n*)\n", "meta": {"author": "EasyCrypt", "repo": "certicrypt", "sha": "7b3cd2fe4a317aec38dfff9eec902b265c575587", "save_path": "github-repos/coq/EasyCrypt-certicrypt", "path": "github-repos/coq/EasyCrypt-certicrypt/certicrypt-7b3cd2fe4a317aec38dfff9eec902b265c575587/Examples/Indifferentiability/ECurve/PrimalityTest/Proth.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6847831015173926}}
{"text": "From Coq Require Import ZArith ZArithRing Ring_polynom Bool List FunInd Lia.\nFrom CoLoR Require Import closure.\n\nFunction  all_coef_pos (p:Pol Z) : bool :=\n  match p with \n    | Pc c => match Z.compare 0 c with \n                | Gt => false \n                | _ => true \n              end\n    | Pinj _ p => all_coef_pos p\n    | PX p _ q => andb (all_coef_pos p) (all_coef_pos q)\n  end.\n\n\nFunction all_mem_pos (l:list Z) : Prop :=\n  match l with\n    | nil => True\n    | c::l => (0<=c)%Z /\\ all_mem_pos l\n  end.\nOpen Scope Z_scope.\n\nImport InitialRing.\nImport BinList.\nFunctional Scheme jump_ind := Induction for jump Sort Prop.\nOpen Scope Z_scope.\nLemma all_mem_pos_def : forall l, (forall c, In c l -> 0<= c) <-> all_mem_pos l.\nProof.\nintro l;split;intro H.\ninduction l. simpl. trivial.\nsimpl.\nsplit.\napply H;simpl;auto.\napply IHl;intro;simpl in H;auto.\nfunctional induction (all_mem_pos l).\nsimpl;tauto.\ndestruct H;simpl.\nintros x H';simpl in H';destruct H'.\nsubst.\nassumption.\nauto.\nQed.\n\n\nLemma tail_in : forall A (l:list A) x, In x (tail l) -> In x l.\nProof.\n  induction l.\n\n  simpl;tauto.\n  simpl.\n  auto.\nQed.\nLemma jump_in : forall A n l (x:A), In x (jump n l) -> @In A x l.\nProof.\nintros a n l;functional induction (jump n l).\nintros;apply tail_in;eauto.\neauto.\nintros;apply tail_in;auto.\nQed.\n\nLemma pos_expr_if_all_pos_aux : \n  forall (p:Pol Z), all_coef_pos p = true -> forall l, all_mem_pos l  -> \n    0<=Pphi  0 Zplus Zmult  (IDphi (R:=Z))  l p.\nProof.\n  intros p;functional induction (all_coef_pos p).\n\n  intro;discriminate.\n\n  intros _. \n  simpl.\n  destruct c;simpl in y;try discriminate;simpl;auto with zarith.\n  unfold IDphi;auto with zarith.\n\n  simpl.\n  intros H l H0.\n  apply IHb.\n  exact H.\n  rewrite <- all_mem_pos_def in H0|-*.\n  intros c H1.\n  apply H0.\n  apply jump_in with _x;exact H1.\n\n  simpl.\n  intros H l H0.\n\n  assert (0<=hd 0 l).\n  clear - H0.\n  induction l.\n  simpl;lia.\n  simpl.\n\n  rewrite <- all_mem_pos_def in H0;simpl in H0;eauto.\n  assert (0<= pow_pos Zmult (hd 0 l) _x).\n  set (u:=hd 0 l) in *;clearbody u.\n  clear - H1.\n  induction _x.\n  simpl;  auto with zarith.\n  simpl;  auto with zarith.\n  simpl;  auto with zarith.\nassert (0 <=\n   Pphi 0 Zplus Zmult (IDphi (R:=Z)) l p0).\napply IHb.\nsymmetry in H.\ndestruct (@andb_true_eq _ _ H);auto.\nassumption.\nassert (0<=Pphi 0 Zplus Zmult (IDphi (R:=Z)) (tail l) q).\napply IHb0.\nsymmetry in H;destruct (@andb_true_eq _ _ H);auto.\nrewrite <- all_mem_pos_def in H0|-*.\n  intros c H4;  apply H0;apply tail_in;exact H4.\nauto with zarith.\nQed.\n(*\nLemma pos_expr_if_all_pos_aux' : \n  forall (p:Pol Z), all_coef_pos p = true -> forall l, all_mem_pos l  -> \n    0<= @Pphi_dev _  0 1 Zplus Zmult Zminus Z.opp _ 0 1 Z.opp Zeq_bool  (IDphi (R:=Z)) get_signZ  l p.\nProof.\n  intros p H l H0.\n  rewrite (@Ring_polynom.Pphi_dev_ok\n    Z 0 1 Zplus Zmult Zminus Z.opp (@eq Z) InitialRing.Zsth InitialRing.Zeqe\n    (@Rth_ARth _ _ _ _ _ _ _ _ InitialRing.Zsth InitialRing.Zeqe InitialRing.Zth)\n    _ _ _ _ _ _ _ _ (IDphi (R:=Z))\n    (@IDmorph _ _ _ _ _ _ _ _  InitialRing.Zsth Zeq_bool InitialRing.Zeqb_ok) \n  ).\n  apply pos_expr_if_all_pos_aux;assumption.\n  constructor.\n  destruct c;simpl;try (intros;discriminate).\n  intros c H1;injection H1;intro;subst. unfold IDphi; reflexivity.\nQed.\n*)\n\n\nLemma pos_expr_if_all_pos_aux' : \n  forall (p:Pol Z), all_coef_pos p = true -> forall l, all_mem_pos l  -> \n    0<= \n    @Pphi_pow _  0 1 Zplus Zmult Zminus Z.opp _ 0 1 Zeq_bool  \n    (IDphi (R:=Z)) _ Z_of_N Zpower  get_signZ  l p.\nProof.\n  intros p H l H0.\n  replace ( @Pphi_pow _  0 1 Zplus Zmult Zminus Z.opp _ 0 1 Zeq_bool  (IDphi (R:=Z)) _ Z_of_N Zpower get_signZ l p)\n    with (Pphi 0 Zplus Zmult (@IDphi Z) l p).\n  apply pos_expr_if_all_pos_aux;assumption.\n  symmetry;eapply Pphi_pow_ok with (1:=InitialRing.Zsth) (C:= Z).\n  exact  InitialRing.Zeqe.\n  exact (@Rth_ARth _ _ _ _ _ _ _ _ InitialRing.Zsth InitialRing.Zeqe InitialRing.Zth).\n  eexact  (@IDmorph Z Z0 1 Zplus Zmult Zminus Z.opp _  InitialRing.Zsth Zeq_bool Zeq_bool_eq).\n  exact Zpower_theory.\n  apply get_signZ_th.\nQed.\n\n\nLemma pos_expr_if_all_pos' : \n  forall pe, \n    all_coef_pos \n    (norm_subst 0 1 Zplus Zmult Zminus Z.opp Zeq_bool Z.div_eucl ring_subst_niter nil pe) = true -> \n    forall l, all_mem_pos l  -> \n    0<= (PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower l pe) .\nProof.\n  intros p H l H0.\n  rewrite Zr_ring_lemma2 with \n    (n:=ring_subst_niter) (lH:=@nil (PExpr Z * PExpr Z)) \n    (l:=l) \n    (lmp:=@nil (Z*Mon * Pol Z)) \n    (pe:=p) \n    (npe:=\n      norm_subst 0 1 Zplus Zmult Zminus Z.opp Zeq_bool Z.div_eucl ring_subst_niter nil\n        p).\n  apply pos_expr_if_all_pos_aux';assumption.\n  vm_compute;exact I.\n  vm_compute;reflexivity.\n  reflexivity.\nQed.\n\n\nLemma pos_expr_if_all_pos : \n  forall pe1 pe2, \n    all_coef_pos (\n      norm_subst 0 1 Zplus Zmult Zminus Z.opp Zeq_bool Z.div_eucl ring_subst_niter\n        nil (PEsub pe2  pe1)\n    ) = true -> \n    forall l, all_mem_pos l  -> \n      PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower l pe1 <=  \n    PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower l pe2 .\nProof.\n  intros pe1 pe2 H l H0.\n  assert (0<= PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower l (PEsub pe2 pe1)).\n  apply pos_expr_if_all_pos'.\n  assumption.\n  assumption.\n  simpl in H1;auto with zarith.\nQed.\n\n\nLemma jump_nil : forall p, jump p (@nil Z) = nil .\nProof.\n  induction p;simpl.\n\n  do 2 rewrite IHp;reflexivity.\n\n  do 2 rewrite IHp;reflexivity.\n\n  reflexivity.\nQed.\n\nLemma Pphi_nil : forall p, \n  Pphi 0 Zplus Zmult (IDphi (R:=Z)) nil p = \n  match p with \n    | Pc c => c \n    | Pinj _ p => Pphi 0 Zplus Zmult (IDphi (R:=Z)) nil p\n    | PX _ _ p => Pphi 0 Zplus Zmult (IDphi (R:=Z)) nil p\n  end.\nProof.\ndestruct p.\n\nsimpl;unfold IDphi;reflexivity.\n\nsimpl.\nrewrite jump_nil;reflexivity.\nsimpl.\n\nreplace (pow_pos Zmult 0 p2) with 0.\nring.\nclear; induction p2; simpl.\n1, 3: reflexivity.\nrewrite <- IHp2;reflexivity.\nQed.\n\n\nFunction all_mem_bounded (l:list (Z*Z)) : Prop :=\n  match l with\n    | nil => True\n    | (b,z)::l => (b<=z)%Z /\\ all_mem_bounded l\n  end.\n\n\n\nLemma tail_length : forall A (l1 l2:list A), length l1 = length l2 -> \n  length (tail l1) = length (tail l2).\nProof.\n  induction l1 as [|x l1];destruct l2 as [|y l2];intros Hlength;simpl in Hlength;\n    try discriminate Hlength;simpl;auto.\nQed.\n\n\nLemma jump_length : forall A n (l1 l2:list A), length l1 = length l2 -> \n  length (jump n l1) = length (jump n l2).\nProof.\n  intros A n l1;functional induction (jump n l1);  simpl;  intros l2 Hlength.\n\n  apply IHl0;  apply IHl;  apply tail_length; apply Hlength.\n  apply IHl0;  apply IHl;   apply Hlength.\n  apply tail_length; apply Hlength.\nQed.\n\nLemma all_mem_pos_tail : forall (l:list Z), all_mem_pos l -> \n  all_mem_pos (tail l).\nProof. \n  intros l; functional induction all_mem_pos l. \n  vm_compute;trivial.\n  inversion 1;auto.\nQed.\n\nLemma all_mem_pos_jump : forall n (l:list Z), all_mem_pos l -> \n  all_mem_pos (jump n l).\nProof.\n  intros n l;functional induction (jump n l);simpl;intros Hmem.\n  apply IHl1;apply IHl0;apply all_mem_pos_tail; apply Hmem.\n  apply IHl1;apply IHl0;apply Hmem.\n  apply all_mem_pos_tail; apply Hmem.\nQed.\n\nFunctional Scheme combine_ind := Induction for combine Sort Prop.\n\n\nLemma combine_tail : forall A (l1 l2: list A), \n  combine (tail l1) (tail l2) =  tail (combine l1 l2).\nProof.\n  intros A l1 l2;functional induction (combine l1 l2).\n  vm_compute;reflexivity.\n  simpl;destruct tl; reflexivity.\n  simpl;reflexivity.\nQed.\n\nLemma combine_jump : forall A n (l1 l2: list A), \n  combine (jump n l1) (jump n l2) =  jump n (combine l1 l2).\nProof.\n  intros A n l1;functional induction (jump n l1);simpl;intros l2.\n  rewrite IHl0;rewrite IHl;rewrite combine_tail;reflexivity.\n  rewrite IHl0;rewrite IHl;reflexivity.\n  rewrite combine_tail;reflexivity.\nQed.\n\n\nLemma all_mem_bounded_tail : forall (l:list (Z*Z)), all_mem_bounded l -> \n  all_mem_bounded (tail l).\nProof.\n  intros l;functional induction (all_mem_bounded l);simpl.\n  trivial.\n  inversion 1;auto.\nQed.\n\n\nLemma all_mem_bounded_jump : forall n (l:list (Z*Z)), all_mem_bounded l -> \n  all_mem_bounded (jump n l).\nProof.\n  intros n l;functional induction (jump n l);simpl;intros H.\n  apply IHl1;apply IHl0;apply all_mem_bounded_tail;apply H.\n  apply IHl1;apply IHl0;apply H.\n  apply all_mem_bounded_tail;apply H.\nQed.\n\n\nLemma all_mem_pos_all_mem_bounded : \n  forall l1 l2, length l1 = length l2 -> all_mem_pos l1 -> \n    all_mem_bounded (combine l1 l2) -> all_mem_pos l2.\nProof.\n  intros l1 l2;functional induction (combine l1 l2).\n  destruct l';intros Hlength;try discriminate;tauto.\n  intros abs;discriminate.\n  intros Hlength;injection Hlength;clear Hlength;intro Hlength;simpl in *; inversion 1;\n    inversion 1;auto with zarith.\nQed.\n\nLemma Zmult_compat : forall n m, 0<=n -> 0<n*m -> 0<n /\\ 0<m.\nProof.\n  intros.\n  case (Z_lt_le_dec 0 n).\n  intros H'.\n  replace 0 with (0*n) in H0 by ring;\n  replace (n*m) with (m*n) in H0 by ring;\n  generalize (Zmult_gt_0_lt_reg_r _ _ _ (Z.lt_gt _ _ H') H0);auto.\n  intro;  assert (n=0) by lia.\n  subst;simpl in H0.\n  lia.\nQed.\n\nFunctional Scheme pow_pos_ind := Induction for pow_pos Sort Prop.\n\nLemma pow_pos_pos : forall z p, 0<=z -> 0<= pow_pos Zmult z p .\nProof.\nintros z p;functional induction  (pow_pos Zmult z p);\nauto with zarith.\nQed.\n\nLemma pow_pos_strict_pos : forall z p, 0<z -> 0< pow_pos Zmult z p .\nProof.\nintros z p; functional induction  (pow_pos Zmult z p). 3: easy.\n\nintros.\napply Zmult_lt_0_compat;auto.\napply Zmult_lt_0_compat;auto.\n\nintros.\napply Zmult_lt_0_compat;auto.\nQed.\n\nLemma pow_pos_monotonic : \n  forall p z1 z2, 0<=z1<=z2 -> pow_pos Zmult z1 p <= pow_pos Zmult z2 p.\nProof.\n  intros p z1 z2 z1_le_z2.\n  functional induction (pow_pos Zmult z1 p);simpl in *.\n  destruct z1_le_z2 as [le_z1 z1_le_z2].\n\n  apply Zmult_le_compat;try assumption.\n  apply Zmult_le_compat;try assumption.\n  apply pow_pos_pos;auto with zarith.\n  apply pow_pos_pos;auto with zarith.\n  apply Zmult_le_0_compat;apply pow_pos_pos;auto with zarith.\n\n  apply Zmult_le_compat;try assumption.\n  apply pow_pos_pos;auto with zarith.\n  apply pow_pos_pos;auto with zarith.\n\n  \n  auto with zarith.\nQed.\n\n\n\n\n\n\nLemma strict_pos_expr_if_all_pos_aux : \n  forall (p:Pol Z), all_coef_pos p = true -> forall lb, all_mem_pos lb  -> \n    forall lz, length lb = length lz -> all_mem_bounded (combine lb lz) ->\n    0 < Pphi  0 Zplus Zmult  (IDphi (R:=Z)) lb p ->\n    0< Pphi 0 Zplus Zmult  (IDphi (R:=Z))  lz p.\nProof.\n\n  induction p.\n\n  \n  intros H lb H0 lz H1 H2 H3;tauto.\n\n  simpl. intros Hp0 lb lb_pos lz Hlength lb_lz H.\n  apply IHp with (jump p lb);try assumption.\n  apply all_mem_pos_jump;exact lb_pos.\n  apply jump_length;exact Hlength.\n  rewrite combine_jump;apply all_mem_bounded_jump;exact lb_lz.\n\n\n  simpl. intros Hp1_p3 lb lb_pos lz Hlength lb_lz H.\n  assert(h1:0<=pow_pos Zmult (hd 0 lb) p2).\n  destruct lb.\n  simpl; clear;  induction p2; simpl; auto with zarith.\n  simpl. simpl in lb_pos. destruct lb_pos.\n  clear - H0.\n  induction p2; simpl; auto with zarith.\n  assert (h2:0<=Pphi 0 Zplus Zmult (IDphi (R:=Z)) lb p1).\n  apply  pos_expr_if_all_pos_aux.\n  symmetry in Hp1_p3;destruct (@andb_true_eq _ _ Hp1_p3);auto.\n  exact lb_pos.\n  assert (h3:0<=Pphi 0 Zplus Zmult (IDphi (R:=Z)) lb p1 * pow_pos Zmult (hd 0 lb) p2).\n  auto with zarith.\n  assert(h4:(0<Pphi 0 Zplus Zmult (IDphi (R:=Z)) (tail lb) p3)\\/0<Pphi 0 Zplus Zmult (IDphi (R:=Z)) lb p1 * pow_pos Zmult (hd 0 lb) p2).\n  case(Zle_lt_or_eq _ _ h3).\n  auto.\n  intro Heq;rewrite <- Heq in H;simpl in H;auto.\n  assert(h5:0<=pow_pos Zmult (hd 0 lz) p2).\n  destruct lz.\n  simpl; clear;  induction p2; simpl; auto with zarith.\n  simpl. \n  destruct lb;try discriminate. \n  simpl in lb_pos. destruct lb_pos.\n  simpl in lb_lz;destruct lb_lz.\n  assert (0<= z) by auto with zarith.\n  clear - H4.\n  induction p2; simpl; auto with zarith.\n  assert (h6:0<=Pphi 0 Zplus Zmult (IDphi (R:=Z)) lz p1).\n  apply  pos_expr_if_all_pos_aux.\n  symmetry in Hp1_p3;destruct (@andb_true_eq _ _ Hp1_p3);auto.\n  apply  all_mem_pos_all_mem_bounded with lb. exact Hlength. exact lb_pos.\n  exact lb_lz.\n  assert (h7:0<=Pphi 0 Zplus Zmult (IDphi (R:=Z)) lz p1 * pow_pos Zmult (hd 0 lz) p2).\n  auto with zarith.\n  case h4;clear h4;intro h4.\n\n  assert (h8:0< Pphi 0 Zplus Zmult (IDphi (R:=Z)) (tail lz) p3).\n  apply IHp2 with (tail lb).\n  symmetry in Hp1_p3;destruct (@andb_true_eq _ _ Hp1_p3);auto.\n  apply all_mem_pos_tail;exact lb_pos.\n  apply tail_length;exact Hlength.\n  rewrite combine_tail;apply all_mem_bounded_tail;exact lb_lz.\n  exact h4.\n  auto with zarith.\n\n\n  destruct (Zmult_compat _ _ h2 h4) as [h8 h9];clear h4.\n  assert (h10:0 < Pphi 0 Zplus Zmult (IDphi (R:=Z)) lz p1).\n  apply IHp1 with lb.\n  symmetry in Hp1_p3;destruct (@andb_true_eq _ _ Hp1_p3);auto.\n  exact lb_pos.\n  exact Hlength.\n  exact lb_lz.\n  exact h8.\n\n  assert (h11: 0 < pow_pos Zmult (hd 0 lz) p2).\n  destruct lz.\n  clear -  h9 Hlength lb_lz.\n  destruct lb;try discriminate.\n  simpl in h9|-*.\n  clear - h9;\n    apply False_ind.\n  replace  (pow_pos Zmult 0 p2) with 0 in *.\n  lia.\n  clear.\n  induction p2;simpl.\n  1, 3: reflexivity.\n  rewrite <- IHp2;ring.\n  simpl.\n  clear -  h9 Hlength lb_pos lb_lz.\n  destruct lb;try discriminate.\n  simpl in h9,lb_lz,lb_pos|-*.\n\n\n\n  destruct lb_lz as [h _].\n  destruct lb_pos as [h1 _].\n  clear - h h1 h9.\n  apply Z.lt_le_trans with (pow_pos Zmult z0 p2).\n  assumption.\n  apply pow_pos_monotonic;auto with zarith.\n  assert (0 <\n   Pphi 0 Zplus Zmult (IDphi (R:=Z)) lz p1 * pow_pos Zmult (hd 0 lz) p2).\n  apply Zmult_lt_0_compat;assumption.\n  assert ( 0<=Pphi 0 Zplus Zmult (IDphi (R:=Z)) (tail lz) p3).\n  apply pos_expr_if_all_pos_aux.\n  symmetry in Hp1_p3;destruct (@andb_true_eq _ _ Hp1_p3);auto.\n  apply all_mem_pos_tail. apply all_mem_pos_all_mem_bounded with lb; assumption.\n  lia.\nDefined.\n\n\nLemma strict_pos_expr_if_all_pos_aux' : \n  forall (p:Pol Z), all_coef_pos p = true -> forall lb, all_mem_pos lb  -> \n    forall lz, length lb = length lz -> all_mem_bounded (combine lb lz) -> \n    0<  @Pphi_pow _  0 1 Zplus Zmult Zminus Z.opp _ 0 1 Zeq_bool  (IDphi (R:=Z)) _ Z_of_N Zpower  (get_signZ)  lb p ->\n    0<  @Pphi_pow _  0 1 Zplus Zmult Zminus Z.opp _ 0 1 Zeq_bool  (IDphi (R:=Z)) _ Z_of_N Zpower  (get_signZ)  lz p.\nProof.\n  intros p H lb H0 lz H1 H2.\n replace ( @Pphi_pow _  0 1 Zplus Zmult Zminus Z.opp _ 0 1 Zeq_bool  (IDphi (R:=Z)) _ Z_of_N Zpower  (get_signZ)  lb p)\n    with (Pphi 0 Zplus Zmult (@IDphi Z) lb p).\n replace (Pphi_pow 0 1 Zplus Zmult Zminus Z.opp 0 1 Zeq_bool \n     (IDphi (R:=Z)) Z_of_N Zpower (get_signZ) lz p)\n    with (Pphi 0 Zplus Zmult (@IDphi Z) lz p).\n intro.\n apply strict_pos_expr_if_all_pos_aux with lb;assumption.\n symmetry;eapply Pphi_pow_ok with (1:=InitialRing.Zsth) (C:= Z).\n  exact  InitialRing.Zeqe.\n  exact (@Rth_ARth _ _ _ _ _ _ _ _ InitialRing.Zsth InitialRing.Zeqe InitialRing.Zth).\n  eexact  (@IDmorph Z Z0 1 Zplus Zmult Zminus Z.opp _  InitialRing.Zsth Zeq_bool Zeq_bool_eq).\n  exact Zpower_theory.\n  apply get_signZ_th.\n symmetry;eapply Pphi_pow_ok with (1:=InitialRing.Zsth) (C:= Z).\n  exact  InitialRing.Zeqe.\n  exact (@Rth_ARth _ _ _ _ _ _ _ _ InitialRing.Zsth InitialRing.Zeqe InitialRing.Zth).\n  eexact  (@IDmorph Z Z0 1 Zplus Zmult Zminus Z.opp _  InitialRing.Zsth Zeq_bool Zeq_bool_eq).\n  exact Zpower_theory.\n  apply get_signZ_th.\nQed.\n\nLemma strict_pos_expr_if_all_pos' : \n  forall pe, all_coef_pos (norm_subst 0 1 Zplus Zmult Zminus Z.opp Zeq_bool Z.div_eucl ring_subst_niter nil pe) = true -> \n    forall lb, all_mem_pos lb  -> \n      forall lz, length lb = length lz -> all_mem_bounded (combine lb lz) ->\n      0 < PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower lb pe -> \n      0< ( PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower lz pe) .\nProof.\n  intros pe H lb lb_pos lz Hlength Hlb_lz.\n\n\n  rewrite Zr_ring_lemma2 with (n:=ring_subst_niter) (lH:=@nil (PExpr Z * PExpr Z))  \n    (lmp:=@nil (Z*Mon * Pol Z)) (pe:=pe) (npe:=norm_subst 0 1 Zplus Zmult Zminus Z.opp Zeq_bool Z.div_eucl ring_subst_niter nil\n      pe).\n  rewrite Zr_ring_lemma2 with (n:=ring_subst_niter) (lH:=@nil (PExpr Z * PExpr Z))  \n    (lmp:=@nil (Z*Mon * Pol Z)) (pe:=pe) (npe:=norm_subst 0 1 Zplus Zmult Zminus Z.opp Zeq_bool Z.div_eucl ring_subst_niter nil\n      pe).\n  apply strict_pos_expr_if_all_pos_aux';assumption.\n  vm_compute;exact I.\n  vm_compute;reflexivity.\n  reflexivity.\n  vm_compute;exact I.\n  vm_compute;reflexivity.\n  reflexivity.\nQed.\n\nLemma strict_pos_expr_if_all_pos :   forall pe1 pe2, \n  all_coef_pos (norm_subst 0 1 Zplus Zmult Zminus Z.opp Zeq_bool Z.div_eucl ring_subst_niter nil  (PEsub pe2 pe1)) = true -> \n  forall lb, all_mem_pos lb -> \n    forall lz, length lb = length lz -> all_mem_bounded (combine lb lz) ->\n      PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower lb pe1 < \n      PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower lb pe2 -> \n      PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower lz pe1 < \n      ( PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower lz pe2) .\nProof.\n  intros pe1 pe2 H lb H0 lz H1 H2 H3.\n\n\n  assert (0<  PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower lz pe2  -\n    PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower lz pe1).\n  replace (PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower lz pe2  -\n    PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower lz pe1) with \n  (PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower lz (PEsub pe2  pe1)) by (vm_compute;reflexivity).\n  apply strict_pos_expr_if_all_pos' with lb.\n  assumption.\n  assumption. \n  assumption.\n  assumption.\n  simpl. auto with zarith.\n  auto with zarith.\nQed.\n\nFunction all_le (l1 l2:list Z) {struct l1}: Prop := \n  match l1 with \n    | nil => \n      match l2 with \n        | nil => True \n        | _ => False\n      end\n    | x::l1 => \n      match l2 with \n        | nil => False \n        | y::l2 => \n          x <= y /\\ all_le l1 l2\n      end\n  end\n.\n\nLemma all_le_def : forall l1 l2, all_le l1 l2 <-> (length l1 = length l2 /\\ forall x y, In (x,y) (combine l1 l2) -> x <= y).\nProof.\nintros l1 l2;functional induction (all_le l1 l2).\n\nsimpl;tauto.\n\nsimpl.\ndestruct l2.\nsplit;try tauto.\nsplit;try tauto.\nsimpl;inversion 1;discriminate.\n\nsimpl.\nsplit;try tauto.\nsimpl;inversion 1;discriminate.\n\n\nsimpl.\ndestruct IHP as [lhs rhs].\nsplit.\nintros [H1 H2]. \ndestruct (lhs H2) as [Heq Hforall];split.\nf_equal.\nexact Heq.\nintros x' y' [h|h].\ninjection h;clear h;intros;subst;exact H1.\nauto.\n\n\n\nclear lhs.\nintros [H1 H2].\nsplit;auto.\nQed.\n\nLemma jump_combine : \n  forall A n (l1 l2:list A), jump n (combine l1 l2) = combine (jump n l1) (jump n l2).\nProof.\n\n  induction n;  simpl.\n  \n  intros l1 l2.\n  do 2 rewrite <- IHn.\n  do 2 f_equal.\n  destruct l1;destruct l2;simpl;try reflexivity.\n  destruct l1;simpl;  reflexivity.\n\n  intros l1 l2.\n  do 2 rewrite <- IHn.\n  do 2 f_equal.\n\n  intros l1 l2.\n  destruct l1;destruct l2;simpl;try reflexivity.\n  destruct l1;simpl;  reflexivity.\nQed.\n\n\nLemma pos_pol_incr : \n  forall (p:Pol Z), all_coef_pos p = true -> \n    forall l1 l2, all_le l1 l2  -> all_mem_pos l1 -> \n     0<=Pphi  0 Zplus Zmult  (IDphi (R:=Z))  l1 p <= Pphi  0 Zplus Zmult  (IDphi (R:=Z))  l2 p.\nProof.\n  intros p;functional induction (all_coef_pos p).\n(**)\n  intro;discriminate.\n(**)\n  intros _. \n  simpl.\n  destruct c;simpl in y;try discriminate;simpl;split;unfold IDphi;auto with zarith.\n(**)\n  simpl.\n  intros H l1 l2 H0 H1.\n  apply IHb.\n  exact H.\n  rewrite  all_le_def in H0|-*.\n  destruct H0 as [Hlength Hforall].\n  split.\n  apply jump_length;exact Hlength.\n  intros x y H0;apply Hforall;apply jump_in with _x. \n  rewrite jump_combine;assumption.\n  rewrite <- all_mem_pos_def in H1|-*.\n  intros c H2;apply H1;apply jump_in with _x;assumption.\n(**)\n  simpl.\n  intros H l1 l2 H0 H1.\n  assert (0<=pow_pos Zmult (hd 0 l1) _x <= pow_pos Zmult (hd 0 l2) _x).\n  destruct l1;destruct l2;simpl in H0;try tauto;simpl;auto with zarith.\n  clear;induction _x;simpl;auto with zarith.\n\n  destruct H0.\n  simpl in H1;destruct H1 as [ H1 _ ].\n  clear - H0 H1. \n  assert (0<=z0);auto with zarith.\n  generalize dependent z0;generalize dependent z.\n  induction _x;simpl;intros.\n  assert (0<=pow_pos Zmult z _x) by (clear -H1;induction _x;simpl;auto with zarith).\n  assert (z*pow_pos Zmult z _x <= z0 * pow_pos Zmult z0 _x).\n    destruct (IH_x _ H1 _ H0 H);apply Z.le_trans with (z0*pow_pos Zmult z _x);\n      auto with zarith.\n    split.\n    auto with zarith.\n    destruct (IH_x _ H1 _ H0 H).\n    do 2 rewrite Zmult_assoc.\n    apply Z.le_trans with (z*pow_pos Zmult z _x * pow_pos Zmult z0 _x);auto with zarith.\n\n    destruct (IH_x _ H1 _ H0 H).     \n    split;auto with zarith.\n  assert (0<= pow_pos Zmult z0 _x).\n  apply Z.le_trans with (pow_pos Zmult z _x);auto with zarith.\n  apply Z.le_trans with (pow_pos Zmult z _x*pow_pos Zmult z0 _x);auto with zarith.\n  auto with zarith.\n\nassert (0 <= Pphi 0 Zplus Zmult (IDphi (R:=Z)) l1 p0 <= Pphi 0 Zplus Zmult (IDphi (R:=Z)) l2 p0).\napply IHb.\nsymmetry in H.\ndestruct (@andb_true_eq _ _ H);auto.\nassumption.\nassumption.\nassert (0<=Pphi 0 Zplus Zmult (IDphi (R:=Z)) (tail l1) q <= Pphi 0 Zplus Zmult (IDphi (R:=Z)) (tail l2) q).\napply IHb0.\nsymmetry in H;destruct (@andb_true_eq _ _ H);auto.\ndestruct l1;destruct l2;simpl in H0;simpl;auto;try tauto.\nrewrite <- all_mem_pos_def in H1|-*.\n  intros c H4;  apply H1;apply tail_in;exact H4.\ndestruct H2;destruct H3;destruct H4;split;auto with zarith.\nassert (0<=Pphi 0 Zplus Zmult (IDphi (R:=Z)) l2 p0) by \n  (apply Z.le_trans with (Pphi 0 Zplus Zmult (IDphi (R:=Z)) l1 p0);auto with zarith).\nassert (0<=Pphi 0 Zplus Zmult (IDphi (R:=Z)) (tail l2) q) by \n  (apply Z.le_trans with (Pphi 0 Zplus Zmult (IDphi (R:=Z)) (tail l1) q);auto with zarith).\nassert (0 <= pow_pos Zmult (hd 0 l2) _x) by \n  (apply Z.le_trans with (pow_pos Zmult (hd 0 l1) _x);auto with zarith).\nassert (Pphi 0 Zplus Zmult (IDphi (R:=Z)) l1 p0 * pow_pos Zmult (hd 0 l1) _x <= \n  Pphi 0 Zplus Zmult (IDphi (R:=Z)) l2 p0 * pow_pos Zmult (hd 0 l2) _x) \nby (apply Z.le_trans with (Pphi 0 Zplus Zmult (IDphi (R:=Z)) l2 p0 * pow_pos Zmult (hd 0 l1) _x);auto with zarith).\nauto with zarith.\nQed.\n\nLemma pos_pol_incr' : \n  forall (p:Pol Z), all_coef_pos p = true -> \n    forall l1 l2, all_le l1 l2  -> all_mem_pos l1 -> \n     0<=@Pphi_pow _  0 1 Zplus Zmult Zminus Z.opp _ 0 1  Zeq_bool  (IDphi (R:=Z)) _ Z_of_N Zpower  (get_signZ) l1 p <= \n     @Pphi_pow _  0 1 Zplus Zmult Zminus Z.opp _ 0 1  Zeq_bool  (IDphi (R:=Z)) _ Z_of_N Zpower  (get_signZ) l2 p.\nProof.\n  intros p H l1 l2 H0 H1.\n replace (@Pphi_pow _  0 1 Zplus Zmult Zminus Z.opp _ 0 1 Zeq_bool  (IDphi (R:=Z)) _ Z_of_N Zpower  (get_signZ)  l1 p)\n    with (Pphi 0 Zplus Zmult (@IDphi Z) l1 p).\n replace (Pphi_pow 0 1 Zplus Zmult Zminus Z.opp 0 1 Zeq_bool \n     (IDphi (R:=Z)) Z_of_N Zpower (get_signZ) l2 p)\n    with (Pphi 0 Zplus Zmult (@IDphi Z) l2 p).\n apply pos_pol_incr;assumption.\n symmetry;eapply Pphi_pow_ok with (1:=InitialRing.Zsth) (C:= Z).\n  exact  InitialRing.Zeqe.\n  exact (@Rth_ARth _ _ _ _ _ _ _ _ InitialRing.Zsth InitialRing.Zeqe InitialRing.Zth).\n  eexact  (@IDmorph Z Z0 1 Zplus Zmult Zminus Z.opp _  InitialRing.Zsth Zeq_bool Zeq_bool_eq).\n  exact Zpower_theory.\n  apply get_signZ_th.  \n symmetry;eapply Pphi_pow_ok with (1:=InitialRing.Zsth) (C:= Z).\n  exact  InitialRing.Zeqe.\n  exact (@Rth_ARth _ _ _ _ _ _ _ _ InitialRing.Zsth InitialRing.Zeqe InitialRing.Zth).\n  eexact  (@IDmorph Z Z0 1 Zplus Zmult Zminus Z.opp _  InitialRing.Zsth Zeq_bool Zeq_bool_eq).\n  exact Zpower_theory.\n  apply get_signZ_th.\nQed.\n\nLemma pos_expr_incr_aux :   \n  forall pe, \n  all_coef_pos (norm_subst 0 1 Zplus Zmult Zminus Z.opp Zeq_bool Z.div_eucl ring_subst_niter nil  pe) = true -> \n  forall l1 l2, all_le l1 l2 -> all_mem_pos l1 -> \n    0 <=  PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower l1 pe \n    <= ( PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower l2 pe) .\nProof.\n  intros pe H l1 l2 H0 H1.\n  \n  rewrite Zr_ring_lemma2 with (n:=ring_subst_niter) (lH:=@nil (PExpr Z * PExpr Z))  \n    (lmp:=@nil (Z * Mon * Pol Z)) (pe:=pe) (npe:=norm_subst 0 1 Zplus Zmult Zminus Z.opp Zeq_bool Z.div_eucl ring_subst_niter nil\n      pe).\n  rewrite Zr_ring_lemma2 with (n:=ring_subst_niter) (lH:=@nil (PExpr Z * PExpr Z))  \n    (lmp:=@nil (Z* Mon * Pol Z)) (pe:=pe) (npe:=norm_subst 0 1 Zplus Zmult Zminus Z.opp Zeq_bool Z.div_eucl ring_subst_niter nil\n      pe).\n  apply pos_pol_incr';assumption.\n  vm_compute;exact I.\n  vm_compute;reflexivity.\n  reflexivity.\n  vm_compute;exact I.\n  vm_compute;reflexivity.\n  reflexivity.\nQed.\n\nLemma pos_expr_incr :   \n  forall pe, \n  all_coef_pos (norm_subst 0 1 Zplus Zmult Zminus Z.opp Zeq_bool Z.div_eucl ring_subst_niter nil  pe) = true -> \n  forall l1 l2, all_le l1 l2 -> all_mem_pos l1 -> \n    PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower l1 pe \n    <= ( PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower l2 pe) .\nProof.\n  intros pe H l1 l2 H0 H1.\n  destruct (pos_expr_incr_aux pe H l1 l2 H0 H1) as [_ h];exact h.\nQed.\n\nLtac find_bounds_fv fv := \n  match goal with \n    | H: ?b <= fv |- _ => \n      match isZcst b with \n        | false => fail 1\n        | true => \n          match b with\n            | 0 => fail 2\n            | _ => constr:(b)\n          end\n      end\n    | _ => constr:(0)\n  end\n  .\n\n\nLtac map tac l := \n  match l with \n    | nil => constr:(@nil Z)\n    | ?x::?l => \n      let l' := map tac l in \n        let x' := tac x in \n          constr:(x'::l')\n  end.\n\n(* Import Ring_polynom. *)\nLtac ring_ineq := \n  match goal with \n    | |- ?p <= ?q => \n      let mkFV := FV Zcst Zpow_tac Zplus Zmult Zminus Z.opp Zpower in \n        let mkPol := mkPolexpr Z Zcst Zpow_tac Zplus Zmult Zminus Z.opp Zpower in\n          let fv := mkFV p (@List.nil Z) in\n          let fv := mkFV q fv in\n            let pe := mkPol p fv in\n            let qe := mkPol q fv in\n              let p' := constr:(Ring_polynom.PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower fv pe) in  \n                let q' := constr:(Ring_polynom.PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower fv qe) in \n                  let H:= fresh \"H\" in \n                  (assert (H':p' <= q');[\n                    apply pos_expr_if_all_pos;\n                      [vm_compute;reflexivity|\n                        simpl;repeat split;assumption]\n                    | vm_compute in H';exact H'\n                  ])\n    | |- ?p < ?q => \n      let mkFV := FV Zcst Zpow_tac Zplus Zmult Zminus Z.opp Zpower in \n        let mkPol := mkPolexpr Z Zcst Zpow_tac Zplus Zmult Zminus Z.opp Zpower in\n          let fv := mkFV p (@List.nil Z) in\n          let fv := mkFV q fv in\n            let pe := mkPol p fv in\n            let qe := mkPol q fv in\n              let p' := \n                constr:(\n                  Ring_polynom.PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower fv pe\n                ) \n                in  \n                let q' := \n                  constr:(\n                    Ring_polynom.PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower fv qe\n                  ) \n                  in \n                  let H:= fresh \"H\" in \n                  (assert (H':p' < q');[\n                    let lb := map find_bounds_fv fv in \n                      apply strict_pos_expr_if_all_pos with lb;[\n                        vm_compute;reflexivity|\n                          simpl;repeat split; auto with zarith|\n                            vm_compute;reflexivity|\n                              simpl;repeat split;assumption|\n                                vm_compute;reflexivity]\n                        | vm_compute in H';exact H'\n                  ]\n                  )\n  end.\n\nLtac modify_FV H l :=\n  match l with\n    | nil => constr:(@nil Z)\n    | ?x::?l =>\n        match type of H with\n          | ?p <= x  =>\n            match p with\n              | 0 => fail 1\n              | _ =>\n                constr:(p::l)\n            end\n      end\n    | ?y::?l => \n      let fv' := modify_FV H l in\n        constr:(y::fv')\n  end.\n\nLtac set_as_var_if_needed p := \n  let set_as_var :=       \n    let x := fresh \"x\" in\n      assert (0<=p) by ring_ineq\n        in\n        \n        match p with \n          | context [Zplus _ _] => set_as_var\n          | context [Zmult _ _] => set_as_var\n          | context [Zminus _ _] => set_as_var\n          | context [Z.opp _] => set_as_var\n          | _ => idtac \n        end\n.\n\n\n\nLtac ring_ineq_same_pol H :=\n  try exact H;\n  match type of H with \n    | ?p <= ?q => \n      (set_as_var_if_needed p;\n      set_as_var_if_needed q)\n  end;\n\n  match goal with\n    | |- ?p <= ?q =>\n      let mkFV := FV Zcst Zpow_tac Zplus Zmult Zminus Z.opp Zpower in\n        let mkPol := mkPolexpr Z Zcst Zpow_tac Zplus Zmult Zminus Z.opp Zpower in\n          let fv2 := mkFV q  (@List.nil Z) in\n            let fv1 := modify_FV H fv2 in\n            let qe := mkPol q fv2 in\n              let p' := constr:(Ring_polynom.PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower fv1 qe) in\n                let q' := constr:(Ring_polynom.PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower fv2 qe) in\n                  let H':= fresh \"H\" in\n                  (assert (H':p' <= q');[\n                    apply pos_expr_incr;\n                      [vm_compute;reflexivity|\n                        cbv beta iota zeta delta [all_le all_mem_pos];\n                          repeat split;auto with zarith|\n                            cbv beta iota zeta delta [all_le all_mem_pos];\n                          repeat split;auto with zarith\n                      ]\n                    | vm_compute in H'|-*;exact H'\n                  ])\n  end\n  .\n\nLtac get_fun p e := \n  let e' := eval pattern p in e in \n    match e' with \n      | ?f _ => constr:(f)\n    end\n.\n\n\n\n\nLtac check_goal continue_tac  Hacc order H trans_right trans_left p q lhs rhs := \n  match isZcst p with \n    | true => fail 1\n    | false => \n      match rhs with \n        | context [q] => \n          let f := get_fun q rhs in \n            apply (trans_right) with (f p);\n              [\n                match Hacc with \n                  | tt => clear H\n                  | ?Hacc => generalize (conj H Hacc);clear Hacc H;intro Hacc\n                end;continue_tac tt\n                |\n                let H' := fresh in \n                  let e := constr:(forall a b, 0 <= a -> order a b -> order (f a) (f b)) in\n                  assert (H':e);\n                    [\n                      let h := fresh \"h\" in \n                        (cbv beta;do 3 intro;intro h;ring_ineq_same_pol h)\n                      |\n                        cbv beta in H'; refine (H' _ _ _ H);ring_ineq\n                    ]\n              ]\n        | _ => \n          match lhs with \n            context [p] => \n            let f := get_fun p lhs in \n              apply (trans_left) with (f q);\n                [\n                  let H' := fresh \"H\" in\n                    assert (H':forall a b, 0 <= a -> order a b -> order (f a) (f b));\n                      [\n                        let h := fresh \"h\" in\n                          (cbv beta;do 3 intro;intro h;ring_ineq_same_pol h)\n                        |\n                          cbv beta in H'; refine (H' _ _ _ H);ring_ineq\n                      ]\n                  |              \n                    match Hacc with \n                      | tt => clear H\n                      | ?Hacc => generalize (conj H Hacc);clear Hacc H;intro Hacc\n                    end;continue_tac tt\n                ]\n          end \n          \n      end\n  end.        \n          \n\nLtac soft_prove_ineq continue_tac Hacc := \n  match goal with \n    | H:?p <= ?q |- ?lhs <= ?rhs => \n        check_goal continue_tac Hacc Z.le H Z.le_trans Z.le_trans p q lhs rhs \n    | H:?p <= ?q |- ?lhs < ?rhs => \n        check_goal continue_tac Hacc Z.le H Z.lt_le_trans Z.le_lt_trans p q lhs rhs \n    | H:?p < ?q |- ?lhs < ?rhs => \n      check_goal continue_tac Hacc Z.lt H Z.le_lt_trans Z.lt_le_trans p q lhs rhs\n    | _ => ring_ineq\n  end.\nFrom Coq Require Zwf.\nFrom CoLoR Require terminaison.\nLtac prove_ineq := soft_prove_ineq ltac:(fun _ => prove_ineq) tt.\n\nLtac isVar t := \n  match goal with \n    | v:Z |- _ => \n      match t with \n        v => constr:(true)\n      end\n    | _ => constr:(false)\n  end.\n\n\n(*\n      let mkFV := FV Zcst Zpow_tac Zplus Zmult Zminus Z.opp Zpower in\n        let mkPol := mkPolexpr Z Zcst Zpow_tac Zplus Zmult Zminus Z.opp Zpower in\n          let fv2 := mkFV q  (@List.nil Z) in\n            let fv1 := modify_FV H fv2 in\n            let qe := mkPol q fv2 in\n              let p' := constr:(Ring_polynom.PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower fv1 qe) in\n                let q' := constr:(Ring_polynom.PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower fv2 qe) in\n\nGoal \n  forall pe1 pe2 fv, \n  PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower fv pe1 - \n  PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower nil pe2\n    <= ( PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower fv pe2) - \n      PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower nil pe2\n ->   PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower fv pe1 \n    <= ( PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z))  Z_of_N Zpower fv pe2) .\nProof.\n  intros pe1 pe2 fv H.\n  lia.\nQed.\n*)\n\nLtac translate_vars := \n  match goal with \n    | H: ?p <= ?v |- _ => \n      match isZcst p with \n        | true => \n          match p with \n            | 0 => fail 2\n            | _ => \n              match isVar v with \n                | true =>\n                  let v' := fresh \"v\" in \n                    set (v':= v - p) in *;\n                      assert (v = v' + p) by (unfold v';ring);\n                        assert (0<=v') by auto with zarith;\n                          clearbody v';\n                            subst v ; try clear H                            \n                | false => \n                  let mkFV := FV Zcst Zpow_tac Zplus Zmult Zminus Z.opp Zpower in\n                    let mkPol := mkPolexpr Z Zcst Zpow_tac Zplus Zmult Zminus Z.opp Zpower in\n                      let fv := mkFV v  (@List.nil Z) in\n                        match fv with \n                          | _::nil => \n                            let ve := mkPol v fv in\n                              \n                              match eval vm_compute in (Ring_polynom.PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower nil ve) with\n                                | 0%Z => fail 5\n                                | _ => \n                                  let h := fresh \"h\" in \n                                    assert (h:p - Ring_polynom.PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower nil ve <=\n                                      Ring_polynom.PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower fv ve - Ring_polynom.PEeval 0 1 Zplus Zmult Zminus Z.opp (IDphi (R:=Z)) Z_of_N Zpower nil ve);\n                                    [     lazy beta delta  [Ring_polynom.PEeval IDphi BinList.nth hd] iota zeta; lia|\n                                      lazy beta delta  [Ring_polynom.PEeval IDphi BinList.nth hd] iota zeta in h;\n                                        ring_simplify in h;clear H]\n                            end\n                          | _ => fail 4\n\n                        end\n\n              end\n          end\n      end\n  end.\n\nFrom Coq Require Import Lia.\n\nFrom CoLoR Require interp.\nLtac full_prove_ineq \n  term_constructor\n  find_replacement \n  osl_star \n  mm\n  mm_star_monotonic \n  order \n  order_op \n  simplify_star_reduction_R \n  rew\n  gen_pos_hyp\n  pre_concl_tac\n  IHx\n  apply_subst :=\n  try (simplify_star_reduction_R tt );\n    first [\n      solve [apply IHx;clear IHx;\n        match goal with \n          |- order _ (mm (term_constructor ?f ?l)) => \n            let l' := find_replacement l in \n              apply (order_op).(interp.le_lt_compat_right) \n          with (mm (term_constructor f l') ) ;[|\n            apply mm_star_monotonic;\n              repeat apply osl_star;\n                (assumption || constructor 1)\n          ]\n        end;\n        clear;\n          simpl apply_subst;\n          rew tt;\n          repeat (gen_pos_hyp tt);\n            pre_concl_tac tt;\n            (lia) || \n              (repeat translate_vars;( ring_ineq|| prove_ineq ))]|\n      let IHx' := fresh \"IHx\" in\n        match goal with \n          | |- Acc ?R ?t => \n            assert (IHx':forall y, order (mm y) (mm t) -> Acc R y)\n        end;\n        [let y := fresh \"y\" in \n          let x := fresh \"x\" in\n            let H := fresh \"H\" in \n              intros y H;\n                apply IHx;clear IHx; \n                  match goal with \n                    |- order _ (mm (term_constructor ?f ?l)) => \n                      let l' := find_replacement l in \n                        apply (order_op).(interp.le_lt_compat_right) \n                    with (mm (term_constructor f l') ) ;[|\n                      apply mm_star_monotonic;\n                        repeat apply osl_star;\n                          (assumption || constructor 1)\n                    ]\n                  end;\n                  match type of H with \n                    | order _ ?u => \n                      apply (order_op).(interp.le_lt_compat_right)\n                    with u;[assumption|]\n                  end;\n                  clear;\nsimpl apply_subst;\n                    rew tt;\n                    repeat (gen_pos_hyp tt);\n                      pre_concl_tac tt;\n                        ((lia) || ((repeat translate_vars);\n                          prove_ineq))\n          | clear IHx;rename IHx' into IHx;\n            repeat match goal with | H: terminaison.star _ _ _ _ |- _ => clear H end\n        ]\n        \n    ].\n\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Coccinelle/examples/cime_trace/ring_extention.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6847830992678106}}
{"text": "Require Export Kami.Lib.Word.\nRequire Export Kami.Lib.HexNotation.\nOpen Scope word_scope.\n\nNotation \"'Ox' a\" := (NToWord _ (hex a)) (at level 50).\n\nNotation \"sz ''h' a\" := (NToWord sz (hex a)) (at level 50).\n\nGoal 8'h\"a\" = ZToWord 8 (wordVal _ (NToWord 4 10)).\nProof.\n  reflexivity.\nQed.\n\nGoal Ox\"41\" = ZToWord 7 65.\nProof.\n  reflexivity.\nQed.\n\nNotation \"sz ''b' a\" := (ZToWord sz (Z.of_nat (bin a))) (at level 50).\n\nNotation \"''b' a\" := (ZToWord _ (Z.of_nat (bin a))) (at level 50).\n\nGoal 'b\"00001010\" = ZToWord 8 (wordVal _ (NToWord 4 10)).\nProof.\n  reflexivity.\nQed.\n\nGoal 'b\"1000001\" = ZToWord 7 65.\nProof.\n  reflexivity.\nQed.\n", "meta": {"author": "sifive", "repo": "Kami", "sha": "ffb77238f27b603dbd42d2622ba911740bf5eadf", "save_path": "github-repos/coq/sifive-Kami", "path": "github-repos/coq/sifive-Kami/Kami-ffb77238f27b603dbd42d2622ba911740bf5eadf/Lib/HexNotationWord.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6847830923096209}}
{"text": "(** Reformulation of single Diophantine equations, i.e. p = q for Diophantine polynomials, without parameters. *)\n\nInductive dio_op_pfree := do_add_pfree | do_mul_pfree.\n\n(* Syntax without a constructor for parameters, variables fixed to range over nat *)\n\nInductive dio_polynomial_pfree : Set :=\n| dp_nat_pfree : nat -> dio_polynomial_pfree (* natural number constant *)\n| dp_var_pfree : nat -> dio_polynomial_pfree (* existentially quantified variable *)\n| dp_comp_pfree : dio_op_pfree -> dio_polynomial_pfree -> dio_polynomial_pfree -> dio_polynomial_pfree.\n\nFixpoint dp_eval_pfree φ p := \n  match p with\n  | dp_nat_pfree n => n\n  | dp_var_pfree v => φ v\n  | dp_comp_pfree do_add_pfree p q => dp_eval_pfree φ p + dp_eval_pfree φ q \n  | dp_comp_pfree do_mul_pfree p q => dp_eval_pfree φ p * dp_eval_pfree φ q \n  end.\n\nDefinition H10p_PROBLEM := (dio_polynomial_pfree * dio_polynomial_pfree)%type.\nDefinition H10p_sem e φ := dp_eval_pfree φ (fst e) = dp_eval_pfree φ (snd e). \nDefinition H10p (e : H10p_PROBLEM) := exists φ, H10p_sem e φ.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/H10/H10p.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875223, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6847830783932409}}
{"text": "Require Export Choice_Axiom.\n\n(* CARDINAL NUMBERS *)\n\nModule Cardinal.\n\n(* 144 Definition  x ≈ y if and only if there is a 1_1 function f with\n   domain f = x and range f = y. *)\n\nDefinition Equivalent x y : Prop :=\n  exists f, Function1_1 f /\\ dom(f) = x /\\ ran(f) = y.\n\nNotation \"x ≈ y\" := (Equivalent x y) (at level 70).\n\nHint Unfold Equivalent : set.\n\n\n(* 145 Theorem  x ≈ x. *)\n\nTheorem equiv_fix : forall x, x ≈ x.\nProof.\n  intros.\n  unfold Equivalent.\n  exists (\\{\\ λ u v, u ∈ x /\\ u = v \\}\\); split.\n  - unfold Function1_1; split.\n    + unfold Function; split; intros.\n      * unfold Relation; intros; PP H a b; Ens.\n      * destruct H; apply Axiom_SchemeP in H.\n        apply Axiom_SchemeP in H0; destruct H, H0, H1, H2.\n        rewrite <- H3, <- H4; auto.\n    + unfold Function; split; intros.\n      * unfold Relation; intros; PP H a b; Ens.\n      * unfold Inverse in H; destruct H; apply Axiom_SchemeP in H.\n        apply Axiom_SchemeP in H0; destruct H, H0.\n        apply Axiom_SchemeP in H1; apply Axiom_SchemeP in H2.\n        destruct H1, H2, H3, H4; rewrite H5, H6; auto.\n   - split.\n     + apply Axiom_Extent; split; intros.\n       * unfold Domain in H; apply Axiom_Scheme in H; destruct H, H0.\n         apply Axiom_SchemeP in H0; apply H0.\n       * unfold Domain; apply Axiom_Scheme; split; Ens.\n         exists z; apply Axiom_SchemeP; repeat split; auto.\n         apply ord_set; split; Ens.\n     + apply Axiom_Extent; split; intros.\n       * unfold Range in H; apply Axiom_Scheme in H; destruct H, H0.\n         apply Axiom_SchemeP in H0; destruct H0, H1.\n         rewrite H2 in H1; auto.\n       * unfold Range; apply Axiom_Scheme; split; Ens.\n         exists z; apply Axiom_SchemeP; repeat split; auto.\n         apply ord_set; split; Ens.\nQed.\n\nHint Resolve equiv_fix : set.\n\n\n(* 146 Theorem  If x ≈ y, then y ≈ x. *)\n\nTheorem equiv_com : forall x y, x ≈ y -> y ≈ x.\nProof.\n  intros.\n  unfold Equivalent in H; destruct H as [f H], H, H0.\n  unfold Equivalent; exists f⁻¹; split.\n  - unfold Function1_1 in H; destruct H.\n    unfold Function1_1; split; try rewrite rel_inv_fix; try apply H; auto.\n  - unfold Inverse; split.\n    + unfold Domain; apply Axiom_Extent; split; intros.\n      * apply Axiom_Scheme in H2; destruct H2, H3.\n        apply Axiom_SchemeP in H3; destruct H3.\n        apply Property_ran in H4; rewrite H1 in H4; auto.\n      * apply Axiom_Scheme; split; Ens.\n        rewrite <- H1 in H2; unfold Range in H2.\n        apply Axiom_Scheme in H2; destruct H2, H3.\n        exists (x0); apply Axiom_SchemeP; split; auto.\n        apply ord_set; AssE ([x0,z]).\n        apply ord_set in H4; destruct H4; Ens.\n    + unfold Range; apply Axiom_Extent; split; intros.\n      * apply Axiom_Scheme in H2; destruct H2, H3.\n        apply Axiom_SchemeP in H3; destruct H3.\n        apply Property_dom in H4; rewrite H0 in H4; auto.\n      * apply Axiom_Scheme; split; Ens.\n        rewrite <- H0 in H2; unfold Domain in H2.\n        apply Axiom_Scheme in H2; destruct H2, H3.\n        exists (x0); apply Axiom_SchemeP; split; auto.\n        apply ord_set; AssE ([z,x0]).\n        apply ord_set in H4; destruct H4; Ens.\nQed.\n\nHint Resolve equiv_com : set.\n\n\n(* 147 equiv_tran : If x ≈ y and y ≈ z, then x ≈ z. *)\n\nTheorem equiv_tran : forall x y z,\n  x ≈ y -> y ≈ z -> x ≈ z.\nProof.\n  intros.\n  unfold Equivalent in H, H0; unfold Equivalent.\n  destruct H as [f1 H], H0 as [f2 H0], H, H0, H1, H2.\n  exists (\\{\\λ u v, exists w, [u,w] ∈ f1 /\\ [w,v] ∈ f2\\}\\); split.\n  - unfold Function1_1; unfold Function1_1 in H, H0.\n    destruct H, H0; split.\n    + unfold Function; split; intros.\n      * unfold Relation; intros; PP H7 a b; Ens.\n      * destruct H7; apply Axiom_SchemeP in H7; destruct H7, H9.\n        apply Axiom_SchemeP in H8; destruct H8, H10; clear H7 H8.\n        unfold Function in H, H0; destruct H9, H10, H, H0.\n        add ([x0,x2] ∈ f1) H7; apply H11 in H7; rewrite H7 in H8.\n        add ([x2,z0] ∈ f2) H8; apply H12 in H8; auto.\n    + unfold Function; split; intros.\n      * unfold Relation; intros; PP H7 a b; Ens.\n      * unfold Inverse in H7; destruct H7; apply Axiom_SchemeP in H7.\n        apply Axiom_SchemeP in H8; destruct H7, H8; clear H7 H8.\n        apply Axiom_SchemeP in H9; destruct H9, H8.\n        apply Axiom_SchemeP in H10; destruct H10, H10; clear H7 H9.\n        unfold Function in H5, H6; destruct H8, H10, H5, H6.\n        assert ([x0,x1] ∈ f2⁻¹ /\\ [x0,x2] ∈ f2⁻¹).\n        { unfold Inverse; split.\n          - apply Axiom_SchemeP; split; auto; AssE [x1,x0].\n            apply ord_set in H13; destruct H13.\n            apply ord_set; split; auto.\n          - apply Axiom_SchemeP; split; auto; AssE [x2,x0].\n            apply ord_set in H13; destruct H13.\n            apply ord_set; split; auto. }\n        apply H12 in H13; rewrite H13 in H7; clear H8 H10 H12 H13.\n        assert ([x2,y0] ∈ f1⁻¹ /\\ [x2,z0] ∈ f1⁻¹).\n        { unfold Inverse; split.\n          - apply Axiom_SchemeP; split; auto; AssE [y0,x2].\n            apply ord_set in H8; destruct H8.\n            apply ord_set; split; auto.\n          - apply Axiom_SchemeP; split; auto; AssE [z0,x2].\n            apply ord_set in H8; destruct H8.\n            apply ord_set; split; auto. }\n        apply H11 in H8; auto.\n  - rewrite <- H1, <- H4; split.\n    + apply Axiom_Extent; split; intros.\n      * apply Axiom_Scheme in H5; destruct H5, H6.\n        apply Axiom_SchemeP in H6; destruct H6, H7, H7.\n        apply Property_dom in H7; auto.\n      * apply Axiom_Scheme; split; Ens; apply Axiom_Scheme in H5.\n        destruct H5, H6; double H6; apply Property_ran in H7.\n        rewrite H3 in H7; rewrite <- H2 in H7; apply Axiom_Scheme in H7.\n        destruct H7, H8; exists x1; apply Axiom_SchemeP; split; Ens.\n        AssE [z0,x0]; AssE [x0,x1]; apply ord_set in H9.\n        apply ord_set in H10; destruct H9, H10.\n        apply ord_set; split; auto.\n    + apply Axiom_Extent; split; intros.\n      * apply Axiom_Scheme in H5; destruct H5, H6.\n        apply Axiom_SchemeP in H6; destruct H6, H7, H7.\n        apply Property_ran in H8; auto.\n      * apply Axiom_Scheme; split; Ens; apply Axiom_Scheme in H5.\n        destruct H5, H6; double H6; apply Property_dom in H7.\n        rewrite H2 in H7; rewrite <- H3 in H7; apply Axiom_Scheme in H7.\n        destruct H7, H8; exists x1; apply Axiom_SchemeP; split; Ens.\n        AssE [x0,z0]; AssE [x1,x0]; apply ord_set in H9.\n        apply ord_set in H10; destruct H9, H10.\n        apply ord_set; split; auto.\nQed.\n\nHint Resolve equiv_tran : set.\n\n\n(* 148 Definition148  x is a cardinal number if and onlu if x is a ordinal\n   number and, if y∈R and y≺x, then it is false that x ≈ y. *)\n\nDefinition Cardinal_Number x : Prop :=\n  Ordinal_Number x /\\ (forall y, y∈R -> y ≺ x -> ~ (x ≈ y)).\n\nHint Unfold Cardinal_Number : set.\n\n\n(* 149 Definition  C = {x : x is a cardinal number}. *)\n\nDefinition C : Class := \\{ λ x, Cardinal_Number x \\}.\n\nHint Unfold C : set.\n\n\n(* 150 Theorem E well-orders C. *)\n\nTheorem well_order_E : WellOrdered E C.\nProof.\n  intros.\n  unfold WellOrdered; split; intros.\n  - unfold Connect; intros; destruct H; unfold C in H, H0.\n    apply Axiom_Scheme in H; apply Axiom_Scheme in H0; destruct H, H0.\n    unfold Cardinal_Number in H1, H2; destruct H1, H2; clear H3 H4.\n    unfold Ordinal_Number, R in H1, H2; apply Axiom_Scheme in H1.\n    apply Axiom_Scheme in H2; destruct H1, H2; add (Ordinal v) H3.\n    clear H1 H2 H4; apply ord_bel_eq in H3; destruct H3.\n    + left; unfold Rrelation, E; apply Axiom_SchemeP.\n      split; try apply ord_set; auto.\n    + destruct H1; auto; right; left; unfold Rrelation, E.\n      apply Axiom_SchemeP; split; try apply ord_set; auto.\n  - destruct H; assert (y ⊂ R).\n    { unfold Subclass; intros; unfold Subclass in H.\n      apply H in H1; unfold C in H1; apply Axiom_Scheme in H1.\n      destruct H1; unfold Cardinal_Number in H2; destruct H2.\n      unfold Ordinal_Number in H2; auto. }\n    add (y ≠ Φ) H1; apply sub_noteq_firstmemb in H1; Ens.\nQed.\n\nHint Resolve well_order_E : set.\n\n\n(* 151 Definition  P = { [x,y] : x ≈ y and y∈C }. *)\n\nDefinition P : Class := \\{\\ λ x y, x ≈ y /\\ y ∈ C \\}\\.\n\nHint Unfold P : set.\n\n\n(* 152 Theorem  P is a function, domain P = μ and range P = C. *)\n\nTheorem card_fun : Function P /\\ dom(P) = μ /\\ ran(P) = C.\nProof.\n  unfold P; repeat split; intros.\n  - unfold Relation; intros; PP H a b; Ens.\n  - destruct H; apply Axiom_SchemeP in H; apply Axiom_SchemeP in H0.\n    destruct H, H0, H1, H2; apply equiv_com in H1.\n    apply (equiv_tran _ _ z) in H1; auto; clear H H0 H2.\n    unfold C in H3, H4; apply Axiom_Scheme in H3; destruct H3.\n    apply Axiom_Scheme in H4; destruct H4.\n    unfold Cardinal_Number in H0, H3; destruct H0, H3.\n    unfold Ordinal_Number in H0, H3.\n    assert (Ordinal y /\\ Ordinal z).\n    { unfold R in H0, H3; apply Axiom_Scheme in H0.\n      apply Axiom_Scheme in H3; destruct H0, H3; split; auto. }\n    apply ord_bel_eq in H6; destruct H6.\n    + apply equiv_com in H1; apply H5 in H0; auto; try contradiction.\n    + destruct H6; auto; apply H4 in H3; auto; try contradiction.\n  - apply Axiom_Extent; split; intros; try apply bel_universe_set; Ens.\n    apply bel_universe_set in H; double H; apply exist_fun1_ordnum in H0.\n    destruct H0 as [f H0], H0, H1; apply Axiom_Scheme; split; auto.\n    assert (WellOrdered E \\{ λ x, x ≈ z /\\ Ordinal x \\}).\n    { assert (\\{ λ x, x ≈ z /\\ Ordinal x \\} ⊂ R).\n      { unfold Subclass; intros; apply Axiom_Scheme in H3.\n        destruct H3, H4; apply Axiom_Scheme; split; auto. }\n      apply (lem_order_pre_sec_sub _ E _) in H3; auto.\n      apply ord_well_order; apply ord_not_set_R. }\n    unfold WellOrdered in H3; destruct H3 as [H4 H3]; clear H4.\n    assert (\\{ λ x, x ≈ z /\\ Ordinal x \\} ⊂ \\{ λ x, x ≈ z /\\ Ordinal x \\}\n            /\\ \\{ λ x, x ≈ z /\\ Ordinal x \\} ≠ Φ).\n    { split; try unfold Subclass; auto.\n      apply not_zero_exist_bel; exists dom(f); apply Axiom_Scheme.\n      unfold Ordinal_Number, R in H2; apply Axiom_Scheme in H2; destruct H2.\n      split; auto; split; auto; unfold Equivalent; exists f; auto. }\n    apply H3 in H4; destruct H4; unfold FirstMember in H4; destruct H4.\n    apply Axiom_Scheme in H4; destruct H4, H6.\n    exists x; apply Axiom_SchemeP.\n    repeat split; try apply ord_set; auto.\n    + apply equiv_com; unfold Equivalent; Ens.\n    + unfold C; apply Axiom_Scheme; split; auto.\n      unfold Cardinal_Number; split; intros.\n      { unfold Ordinal_Number, R; apply Axiom_Scheme; auto. }\n      { unfold Less in H9; unfold R in H8.\n        apply Axiom_Scheme in H8; destruct H8; intro.\n        assert (y ∈ \\{ λ x,x ≈ z /\\ Ordinal x \\}).\n        { apply Axiom_Scheme; split; auto; split; auto.\n          apply equiv_com in H11; apply (equiv_tran _ x _); auto. }\n        apply H5 in H12; apply H12; unfold Rrelation, E.\n        apply Axiom_SchemeP; split; try apply ord_set; auto. }\n  - unfold Range; apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme in H; destruct H, H0.\n      apply Axiom_SchemeP in H0; apply H0.\n    + apply Axiom_Scheme; split; Ens; exists z; apply Axiom_SchemeP.\n      repeat split; try apply ord_set; Ens.\n      apply equiv_fix.\nQed.\n\nHint Resolve card_fun : set.\n\n\n(* A corollary of definition151. *)\n\nCorollary Property_PClass : forall x, Ensemble x -> P [x] ∈ C.\nProof.\n  intros.\n  generalize card_fun; intros; destruct H0, H1.\n  apply bel_universe_set in H; rewrite <- H1 in H.\n  apply Property_Value in H; auto.\n  apply Property_ran in H; rewrite H2 in H; auto.\nQed.\n\nHint Resolve Property_PClass : set.\n\n\n(* 153 Theorem  If x is a set, then P[x] ≈ x. *)\n\nTheorem card_equiv : forall x, Ensemble x -> P[x] ≈ x.\nProof.\n  intros.\n  generalize card_fun; intros; destruct H0, H1.\n  apply bel_universe_set in H; rewrite <- H1 in H.\n  apply Property_Value in H; auto.\n  unfold P at 2 in H; apply Axiom_SchemeP in H.\n  apply equiv_com; apply H.\nQed.\n\nHint Resolve card_equiv : set.\n\n\n(* 154 Theorem  If x and y are sets, then x ≈ y if and onlf if P[x] = P[y]. *)\n\nTheorem card_eq : forall x y,\n  Ensemble x /\\ Ensemble y -> (P[x] = P[y] <-> x ≈ y).\nProof.\n  intros; double H; destruct H, H0.\n  apply card_equiv in H0; apply card_equiv in H2; split; intros.\n  - rewrite H3 in H0; apply equiv_com in H0.\n    apply (equiv_tran _ P[y] _); auto.\n  - generalize card_fun; intros; destruct H4, H5.\n    double H; apply bel_universe_set in H; apply bel_universe_set in H1.\n    rewrite <- H5 in H, H1; apply Property_Value in H; auto.\n    apply Property_Value in H1; auto; apply Property_ran in H1.\n    rewrite H6 in H1; apply equiv_com in H2.\n    assert ([x, P [y]] ∈ P).\n    { unfold P at 2; apply Axiom_SchemeP; split.\n      - apply ord_set; split; Ens.\n      - split; try apply (equiv_tran _ y _); auto. }\n    unfold Function in H4; apply H4 with (x:=x); auto.\nQed.\n\nHint Resolve card_eq : set.\n\n\n(* 155 Theorem  P[ P[ x ] ] = P[ x ]. *)\n\nLemma card_fix : forall x, x ∈ C -> Ensemble x -> P[x] = x.\nProof.\n  intros.\n  double H0; apply Property_PClass in H1; AssE P[x].\n  unfold C in H, H1; apply Axiom_Scheme in H; apply Axiom_Scheme in H1.\n  clear H0 H2; destruct H, H1, H0, H2.\n  apply card_equiv in H; unfold Ordinal_Number in H0, H2.\n  double H0; double H2; unfold R in H5, H6; apply Axiom_Scheme in H5.\n  apply Axiom_Scheme in H6; destruct H5, H6; add (Ordinal P[x]) H7.\n  clear H1 H5 H6 H8; apply ord_bel_eq in H7; destruct H7.\n  + apply H4 in H1; auto; contradiction.\n  + symmetry; destruct H1; auto; apply H3 in H1; auto.\n    apply equiv_com in H; contradiction.\nQed.\n\nTheorem card_eq_inv : forall x, P[P[x]] = P[x].\nProof.\n  intros.\n  generalize card_fun; intros; destruct H, H0.\n  generalize (classic (Ensemble x)); intros; destruct H2.\n  - apply Property_PClass in H2; AssE P[x].\n    apply card_fix in H2; auto.\n  - generalize (classic (x ∈ dom(P))); intros; destruct H3.\n    + rewrite H0 in H3; apply bel_universe_set in H3; contradiction.\n    + apply dom_value in H3; rewrite H3.\n      generalize (classic (μ ∈ dom(P))); intros; destruct H4.\n      * generalize universe_notset; intros; elim H5; Ens.\n      * apply dom_value in H4; rewrite H4; auto.\nQed.\n\nHint Resolve card_fix card_eq_inv : set.\n\n\n(* 156 Theorem  x∈C if and only if x is a set and P[x] = x. *)\n\nTheorem card_iff_eq : forall x,\n  (Ensemble x /\\ P[x] = x) <-> x∈C.\nProof.\n  intros; split; intros.\n  - destruct H; apply Property_PClass in H.\n    rewrite H0 in H; auto.\n  - AssE x; apply card_fix in H; auto.\nQed.\n\nHint Resolve card_iff_eq : set.\n\n\n(* 157 Theorem  If y∈R and x⊂y, then P(x)≼y. *)\n\nTheorem card_int_le : forall x y,\n  y ∈ R /\\ x ⊂ y -> P[x] ≼ y.\nProof.\n  intros; destruct H.\n  unfold R in H; apply Axiom_Scheme in H; destruct H.\n  assert (WellOrdered E x /\\ WellOrdered E R).\n  { split; try (apply ord_well_order; apply ord_not_set_R).\n    apply ord_well_order in H1; apply (lem_order_pre_sec_sub _ _ y); auto. }\n  assert (Ensemble x /\\ ~ Ensemble R).\n  { split; try apply ord_not_set_R; apply sub_set in H0; Ens. }\n  destruct H3; apply well_order_pre_set in H2; auto; clear H4.\n  destruct H2 as [f H2], H2, H4; unfold Order_PXY in H4.\n  destruct H4, H6, H7, H8; apply order_pre_fun1_inv in H7; destruct H7.\n  unfold Function1_1 in H7; destruct H7 as [H11 H7]; clear H11.\n  generalize (Property_F11 f); intros; destruct H11.\n  assert (forall u, u ∈ x -> f[u] ≼ u).\n  { intros; rewrite <- H5 in H13; double H13.\n    apply Property_Value in H14; auto; apply Property_ran in H14.\n    assert (Ordinal u /\\ Ordinal f[u]).\n    { rewrite H5 in H13; apply H0 in H13.\n      add (u ∈ y) H1; apply ord_bel_ord in H1.\n      unfold Section in H9; destruct H9; apply H9 in H14.\n      unfold R in H14; apply Axiom_Scheme in H14; destruct H14; auto. }\n    apply ord_bel_eq in H15; AssE ([u,f[u]]); try apply ord_set; Ens.\n    assert (Section ran(f) E R /\\ Order_Pr f⁻¹ E E /\\ On f⁻¹ ran(f) /\\To f⁻¹ R).\n    { split; auto; split; auto; split; try (split; auto).\n      rewrite H12, H5; unfold Subclass; intros.\n      apply H0 in H17; add (z ∈ y) H1; apply ord_bel_ord in H1.\n      unfold R; apply Axiom_Scheme; split; Ens. }\n    apply sec_order_pre_not_rel with (u:= f[u]) in H17; auto; rewrite <- H12 in H13.\n    apply dom_ran_inv''' in H13; try rewrite (rel_inv_fix f) in *; try apply H2; auto.\n    rewrite <- H13 in H17; unfold LessEqual; destruct H15.\n    - unfold Rrelation, E in H17; elim H17.\n      apply Axiom_SchemeP; split; auto.\n    - destruct H15; try symmetry in H15; tauto. }\n  apply sec_R_ord in H9; clear H11 H12; double H0.\n  try apply sub_set in H11; auto; apply card_equiv in H11.\n  assert (x ≈ ran(f)). { unfold Equivalent; exists f; split; split; auto. }\n  assert (ran(f) ≼ y /\\ Ensemble ran(f)).\n  { assert (ran(f) ⊂ y).\n    { unfold Subclass; intros.\n      unfold Range in H14; apply Axiom_Scheme in H14; destruct H14, H15.\n      double H15; apply Property_dom in H16; double H16.\n      apply Property_Value in H17; auto; add ([x0,f[x0]] ∈ f) H15.\n      unfold Function in H2; apply H2 in H15; rewrite H15 in *.\n      clear H15 H17; rewrite H5 in H16; double H16; apply H13 in H16.\n      unfold LessEqual in H16; destruct H16.\n      - apply H0 in H15; unfold Ordinal in H1; destruct H1.\n        unfold full in H17; apply H17 in H15; apply H15 in H16; auto.\n      - rewrite H16; apply H0 in H15; auto. }\n    split; try apply sub_set with (x:= y); auto.\n    generalize (classic (ran(f) = y)); intros.\n    unfold LessEqual; destruct H15; try tauto.\n    apply ord_sub_full_bel in H14; auto; unfold Ordinal in H9; apply H9. }\n  destruct H14.\n  assert (WellOrdered E \\{ λ z, x ≈ z /\\ Ordinal z \\}).\n  { assert (\\{ λ z, x ≈ z /\\ Ordinal z \\} ⊂ R).\n    { unfold Subclass; intros; apply Axiom_Scheme in H16.\n      destruct H16, H17; apply Axiom_Scheme; split; auto. }\n    apply (lem_order_pre_sec_sub _ E _) in H16; auto. }\n  unfold WellOrdered in H16; destruct H16 as [H17 H16]; clear H17.\n  assert (\\{ λ z, x ≈ z /\\ Ordinal z \\} ⊂ \\{ λ z, x ≈ z /\\ Ordinal z \\}\n            /\\ \\{ λ z, x ≈ z /\\ Ordinal z \\} ≠ Φ).\n  { split; try unfold Subclass; auto.\n    apply not_zero_exist_bel; exists ran(f); apply Axiom_Scheme; split; auto. }\n  apply H16 in H17; clear H16; destruct H17; unfold FirstMember in H16.\n  destruct H16; apply Axiom_Scheme in H16; destruct H16, H18.\n  assert (x0 ∈ C).\n  { unfold C; apply Axiom_Scheme; split; auto.\n    unfold Cardinal_Number; split; intros.\n    - unfold Ordinal_Number, R; apply Axiom_Scheme; Ens.\n    - intro; assert (y0 ∈ \\{ λ z, x ≈ z /\\ Ordinal z \\}).\n      { unfold R in H20; apply Axiom_Scheme in H20; destruct H20.\n        apply Axiom_Scheme; split; auto; split; auto.\n        apply equiv_tran with (y:= x0); auto. }\n      apply H17 in H23; elim H23; clear H23.\n      unfold Rrelation, E; apply Axiom_SchemeP; unfold Less in H21.\n      split; auto; apply ord_set; Ens. }\n  apply card_iff_eq in H20; clear H16; destruct H20.\n  apply card_eq in H18; auto; rewrite H20 in H18; clear H20.\n  assert (ran(f)∈ \\{ λ z, x ≈ z /\\ Ordinal z \\}). { apply Axiom_Scheme; Ens. }\n  apply H17 in H20; clear H17; rewrite H18; unfold LessEqual.\n  add (Ordinal x0) H9; apply ord_bel_eq in H9; destruct H9 as [H9|[H9|H9]].\n  - elim H20; unfold Rrelation, E; apply Axiom_SchemeP.\n    split; try apply ord_set; Ens.\n  - destruct H14.\n    + unfold Ordinal in H1; destruct H1.\n      unfold full in H17; apply H17 in H14; clear H17.\n      unfold Subclass in H14; apply H14 in H9; auto.\n    + rewrite H14 in H9; auto.\n  - destruct H14; rewrite H9 in H14; auto.\nQed.\n\nHint Resolve card_int_le : set.\n\n\n(* 158 Theorem  If y is a set and x⊂y, then P[x]≼P[y]. *)\n\nTheorem card_le : forall x y,\n  Ensemble y /\\ x ⊂ y -> P[x] ≼ P[y].\nProof.\n  intros; destruct H.\n  assert (Ensemble x). { apply sub_set in H0; auto. }\n  double H; apply card_equiv in H2.\n  apply equiv_com in H2; unfold Equivalent in H2.\n  destruct H2 as [f H2], H2, H3; double H.\n  apply Property_PClass in H5; unfold C in H5.\n  apply Axiom_Scheme in H5; destruct H5; unfold Cardinal_Number in H6.\n  destruct H6; clear H7; unfold Ordinal_Number in H6.\n  assert (ran(f|(x)) ⊂ P[y]).\n  { rewrite <- H4; unfold Subclass; intros.\n    unfold Range in H7; apply Axiom_Scheme in H7; destruct H7, H8.\n    unfold Restriction in H8; apply bel_inter in H8; destruct H8.\n    apply Property_ran in H8; auto. }\n  add (ran(f|(x)) ⊂ P [y]) H6; apply card_int_le in H6.\n  assert (x ≈ ran(f|(x))).\n  { unfold Function1_1 in H2; destruct H2.\n    unfold Equivalent; exists (f|(x)); split.\n    - unfold Function1_1; split.\n      + unfold Function; split; intros.\n        * unfold Relation; intros; unfold Restriction in H9.\n          apply bel_inter in H9; destruct H9; PP H10 a b; Ens.\n        * destruct H9; unfold Restriction in H9, H10.\n          apply bel_inter in H9; apply bel_inter in H10.\n          destruct H9, H10; add ([x0,z] ∈ f) H9.\n          unfold Function in H2; apply H2 in H9; auto.\n      + unfold Function; split; intros.\n        * unfold Relation; intros; PP H9 a b; Ens.\n        * destruct H9; unfold Inverse in H9, H10.\n          apply Axiom_SchemeP in H9; apply Axiom_SchemeP in H10.\n          destruct H9, H10; unfold Restriction in H11, H12.\n          apply bel_inter in H11; apply bel_inter in H12.\n          destruct H11, H12; clear H13 H14.\n          assert ([x0,y0] ∈ f⁻¹ /\\ [x0,z] ∈ f⁻¹).\n          { unfold Inverse; split; apply Axiom_SchemeP; Ens. }\n          unfold Function in H8; apply H8 in H13; auto.\n    - split; auto; apply Axiom_Extent; intros; split; intros.\n      + unfold Domain in H9; apply Axiom_Scheme in H9; destruct H9, H10.\n        unfold Restriction in H10; apply bel_inter in H10; destruct H10.\n        unfold Cartesian in H11; apply Axiom_SchemeP in H11; apply H11.\n      + unfold Domain; apply Axiom_Scheme; split; Ens.\n        double H9; unfold Subclass in H0; apply H0 in H10.\n        rewrite <- H3 in H10; apply Property_Value in H10; auto.\n        exists f[z]; unfold Restriction; apply bel_inter; split; auto.\n        unfold Cartesian; apply Axiom_SchemeP; repeat split; Ens.\n        AssE [z,f[z]]; apply ord_set in H11; destruct H11.\n        apply bel_universe_set; auto. }\n  assert (Ensemble ran(f|(x))). { apply sub_set in H7; auto. }\n  apply card_eq in H8; auto; rewrite <- H8 in H6; auto.\nQed.\n\nHint Resolve card_le : set.\n\n\n(* 159 Theorem  If x and y are sets, u⊂x, v⊂y, x≈v, and y≈u, then x≈y. *)\n\nTheorem Schroder_Bernstein_theorem : forall (x y: Class),\n  Ensemble x /\\ Ensemble y ->\n  (forall u v, u ⊂ x /\\ v ⊂ y -> x ≈ v /\\ y ≈ u -> x ≈ y).\nProof.\n  intros; destruct H0, H1; elim H; intros.\n  assert (Ensemble x /\\ Ensemble v).\n  { split; apply sub_set in H2; auto. }\n  assert (Ensemble y /\\ Ensemble u).\n  { split; apply sub_set in H0; auto. }\n  apply card_eq in H; apply card_eq in H6.\n  apply card_eq in H7; apply H; apply H6 in H1.\n  apply H7 in H3; clear H H6 H7; double H4; double H5.\n  add (u ⊂ x) H4; add (v ⊂ y) H6; clear H0 H2.\n  apply card_le in H4; apply card_le in H6.\n  rewrite <- H3 in H4; rewrite <- H1 in H6; clear H1 H3.\n  apply Property_PClass in H; apply Property_PClass in H5.\n  unfold C in H, H5; apply Axiom_Scheme in H; apply Axiom_Scheme in H5.\n  destruct H, H5; unfold Cardinal_Number in H0, H2.\n  destruct H0, H2; unfold Ordinal_Number, R in H0, H2.\n  apply Axiom_Scheme in H0; apply Axiom_Scheme in H2; destruct H0, H2.\n  clear H H0 H1 H2 H3 H5.\n  assert (Ordinal P [x] /\\ Ordinal P [y]). { auto. }\n  assert (Ordinal P [y] /\\ Ordinal P [x]). { auto. }\n  apply ord_sub_iff_le in H; apply ord_sub_iff_le in H0; clear H7 H8.\n  apply H in H6; apply H0 in H4; clear H H0.\n  apply sub_eq; split; auto.\nQed.\n\nHint Resolve Schroder_Bernstein_theorem : set.\n\n\n(* Schroeder-Bernstein Theorem (proof without AC) *)\n\n(* Image Set *)\n\nDefinition Imgset f x := \\{ λ u, exists v, v ∈ x /\\ u = f[v] \\}.\n\nHint Unfold Imgset : set.\n\nInductive Ind := | fir : Ind | next : Ind -> Ind.\n\nFixpoint C' x u g f (n: Ind) : Class :=\n   match n with\n      | fir => (x ~ u)\n      | next p => Imgset g (Imgset f (C' x u g f p))\n       end.\n\nLemma tj : forall a b f, Function1_1 f -> b ∈ ran(f) -> a = f⁻¹[b] -> b = f [a].\nProof.\n  intros. pattern b.\n  rewrite dom_ran_inv''' with (f:=f); try apply H; auto.\n  rewrite H1; auto.\nQed.\n\nLemma tj0 : forall a b f, Function1_1 f -> a ∈ dom(f) -> b = f[a] -> a = f⁻¹[b].\nProof.\n  intros. pattern a.\n  rewrite tj with (f:=f⁻¹) (a:=b); auto.\n  - destruct H; split; auto.\n    rewrite rel_inv_fix; try apply H; auto.\n  - rewrite <- dom_ran_inv; auto.\n  - rewrite rel_inv_fix; try apply H; auto.\nQed.\n\nTheorem Cantor_Bernstein_Schroeder : forall x y u v,\n  Ensemble x -> Ensemble y -> u ⊂ x -> v ⊂ y -> x ≈ v -> y ≈ u -> x ≈ y.\nProof.\n  intros; destruct H3 as [f H3], H3, H5, H4 as [g H4], H4, H7.\n  set (C:= (C' x u g f)); set (CC:=  \\{ λ u, exists n, u = C n \\}).\n  assert (forall z, z ∈ x -> ~ z ∈ (∪ CC) -> z ∈ (x ~ (∪ CC))) as G1; intros.\n  { apply Axiom_Scheme; repeat split; Ens.\n    apply Axiom_Scheme; split; Ens. }\n  assert ((∪ CC) ⊂ x) as G2.\n  { red; intros.\n    apply Axiom_Scheme in H9; destruct H9, H10, H10.\n    apply Axiom_Scheme in H11; destruct H11, H12; subst x0.\n    clear H9 H11; generalize dependent z.\n    induction x1; intros; unfold C in H10; simpl in H10.\n    - apply Axiom_Scheme in H10; tauto.\n    - apply Axiom_Scheme in H10; destruct H10, H10, H10.\n      apply Axiom_Scheme in H10; destruct H10, H12, H12.\n      apply IHx1 in H12; subst x0 x v y u z.\n      apply Property_Value in H12; try apply H3.\n      apply Property_ran in H12; apply H2 in H12.\n      apply Property_Value in H12; try apply H4.\n      apply Property_ran in H12; auto. }\n  assert (forall z, z ∈ x -> ~ z ∈ (∪ CC) -> z ∈ ran( g)) as G3; intros.\n  { rewrite H8; destruct (classic (z ∈ u)); auto.\n    elim H10; apply Axiom_Scheme; split; Ens.\n    exists (C fir); unfold C; simpl; split.\n    - apply Axiom_Scheme; repeat split; Ens.\n      apply Axiom_Scheme; split; Ens.\n    - apply Axiom_Scheme; split.\n      + apply sub_set with (x:=x); auto.\n        red; intros; apply Axiom_Scheme in H12; tauto.\n      + exists fir; auto. }\n  exists \\{\\ λ p q, (p ∈ x) /\\ ((p ∈ (∪CC) -> q = f[p]) /\\ (p ∈ (x ~ (∪CC)) ->\n  q = g⁻¹[p])) \\}\\.\n  repeat split; intros.\n  - red; intros; PP H9 a b; eauto.\n  - destruct H9; apply Axiom_SchemeP in H9; destruct H9, H11, H12.\n    apply Axiom_SchemeP in H10; destruct H10, H14, H15, (classic (x0 ∈ (∪ CC))).\n    + rewrite H12, H15; auto.\n    + rewrite H13, H16; auto.\n  - red; intros; PP H9 a b; eauto.\n  - destruct H9; apply Axiom_SchemeP in H9; destruct H9.\n    apply Axiom_SchemeP in H10; destruct H10.\n    apply Axiom_SchemeP in H11; apply Axiom_SchemeP in H12. \n    destruct H11, H13, H14, H12, H16, H17.\n    destruct (classic (y0 ∈ (∪ CC))), (classic (z ∈ (∪ CC))).\n    + apply H14 in H19; apply H17 in H20; subst x.\n      apply tj0 in H19; apply tj0 in H20; auto.\n      rewrite H19, H20; auto.\n    + double H19; double H20; apply G1 in H20; auto.\n      apply H14 in H19; apply H18 in H20.\n      subst x; rewrite H19 in H20.\n      apply G3 in H16; apply tj in H20; auto.\n      elim H22; apply Axiom_Scheme; split; Ens.\n      apply Axiom_Scheme in H21; destruct H21, H21, H21.\n      apply Axiom_Scheme in H23; destruct H23, H24; subst x.\n      exists (C (next x1)); split.\n      * unfold C; simpl; apply Axiom_Scheme; split; Ens.\n        exists f[y0]; split; auto; apply Axiom_Scheme; split; Ens.\n        apply dom_value in H13; apply bel_universe_set; auto.\n      * apply Axiom_Scheme; split; Ens; unfold C; simpl.\n        apply sub_set with (x:= dom(f)); auto; red; intros.\n        apply Axiom_Scheme in H24; destruct H24, H25, H25; subst z0.\n        assert (x ∈ dom(g)).\n        { destruct (classic (x ∈ dom(g))); auto.\n          apply dom_value in H26; rewrite H26 in H24.\n          destruct (universe_notset H24). }\n        apply Property_Value in H26; try apply H4.\n        apply Property_ran in H26.\n        rewrite H8 in H26; auto.\n    + double H19; double H20; apply G1 in H19; auto.\n      apply H17 in H20; apply H15 in H19.\n      subst x; rewrite H20 in H19.\n      apply G3 in H13; apply tj in H19; auto.\n      elim H21; apply Axiom_Scheme; split; Ens.\n      apply Axiom_Scheme in H22; destruct H22, H22, H22.\n      apply Axiom_Scheme in H23; destruct H23, H24; subst x.\n      exists (C (next x1)); split.\n      * unfold C; simpl; apply Axiom_Scheme; split; Ens.\n        exists f[z]; split; auto; apply Axiom_Scheme; split; Ens.\n        apply dom_value in H16; apply bel_universe_set; auto.\n      * apply Axiom_Scheme; split; Ens; unfold C; simpl.\n        apply sub_set with (x:= dom(f)); auto; red; intros.\n        apply Axiom_Scheme in H24; destruct H24, H25, H25; subst z0.\n        assert (x ∈ dom(g)).\n        { destruct (classic (x ∈ dom(g))); auto.\n          apply dom_value in H26; rewrite H26 in H24.\n          destruct (universe_notset H24). }\n        apply Property_Value in H26; try apply H4.\n        apply Property_ran in H26.\n        rewrite H8 in H26; auto.\n    + double H13; double H16.\n      apply G3 in H21; apply G3 in H22; auto.\n      apply G1 in H19; apply G1 in H20; auto.\n      apply H15 in H19; apply H18 in H20; auto.\n      apply tj in H19; apply tj in H20; auto.\n      rewrite H19, H20; auto.\n  - apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme in H9; destruct H9, H10.\n      apply Axiom_SchemeP in H10; destruct H10; tauto.\n    + apply Axiom_Scheme; split; Ens.\n      destruct (classic (z ∈ (∪ CC))); subst x.\n      * exists f[z]; apply Axiom_SchemeP.\n        repeat split; intros; auto.\n        { apply ord_set; split; Ens.\n          apply bel_universe_set; apply dom_value; auto. }\n        { apply Axiom_Scheme in H5; destruct H5, H11.\n          apply Axiom_Scheme in H12; destruct H12; contradiction. }\n      * exists g ⁻¹[z]; apply Axiom_SchemeP.\n        repeat split; intros; auto; try tauto.\n        apply ord_set; split; Ens; apply bel_universe_set; apply dom_value.\n        rewrite <- dom_ran_inv', H8.\n        destruct (classic (z ∈ u)); auto.\n        elim H10; apply Axiom_Scheme; split; Ens.\n        exists (C fir); split; apply Axiom_Scheme; repeat split; Ens.\n        -- apply Axiom_Scheme; split; Ens.\n        -- apply sub_set with dom(f); auto. \n           red; intros; apply Axiom_Scheme in H11; tauto.\n  - apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme in H9; destruct H9, H10.\n      apply Axiom_SchemeP in H10; destruct H10, H11, H12.\n      destruct (classic (x0 ∈ (∪ CC))).\n      * apply H12 in H14; subst z.\n        apply H2; rewrite <- H6; rewrite <- H5 in H11.\n        apply Property_Value in H11; try apply H3.\n        apply Property_ran in H11; auto.\n      * double H11; apply G1 in H11; apply G3 in H15; auto.\n        apply H13 in H11; auto; rewrite dom_ran_inv' in H15.\n        apply Property_Value in H15; try apply H4.\n        apply Property_ran in H15; subst z.\n        rewrite <- dom_ran_inv, H7 in H15; auto.\n    + apply Axiom_Scheme; split; Ens.\n      destruct (classic (z ∈ (Imgset f (∪ CC)))).\n      * apply Axiom_Scheme in H10; destruct H10, H11, H11.\n        exists x0; apply Axiom_SchemeP; repeat split; auto; intros.\n        { apply ord_set; split; Ens. }\n        { apply Axiom_Scheme in H13; destruct H13, H14.\n          apply Axiom_Scheme in H15; destruct H15; contradiction. }\n      * assert (g[z] ∈ ran(g)).\n        { subst y; apply Property_Value in H9; try apply H4.\n          apply Property_ran in H9; Ens. }\n        assert (forall n, (C n) ⊂ (∪ CC)); intros.\n        { apply bel_ele; apply Axiom_Scheme; split; Ens. \n          apply sub_set with (x:=x); auto.\n          red; induction n; intros.\n          - apply Axiom_Scheme in H12; tauto.\n          - unfold C in H12; simpl in H12.\n            apply Axiom_Scheme in H12; destruct H12, H13, H13.\n            apply Axiom_Scheme in H13; destruct H13, H15, H15.\n            apply IHn in H15; subst x z0 x0 v y u.\n            apply Property_Value in H15; try apply H3.\n            apply Property_ran in H15; apply H2 in H15.\n            apply Property_Value in H15; try apply H4.\n            apply Property_ran in H15; auto. }\n        assert (~ g[z] ∈ (∪ CC)); try intro.\n        { apply Axiom_Scheme in H13; destruct H13, H14, H14.\n          apply Axiom_Scheme in H15; destruct H15, H16; subst x0 u.\n          destruct x1.\n          - apply Axiom_Scheme in H14; destruct H14, H14.\n            apply Axiom_Scheme in H16; apply H16; auto.\n          - unfold C in H14; simpl in H14.\n            apply Axiom_Scheme in H14; destruct H14, H14, H14.\n            apply Axiom_Scheme in H14; destruct H14, H17, H17.\n            assert (z = x0) as G4.\n            { rewrite dom_ran_inv''' with (f:=g⁻¹); try apply H4.\n              - pattern z; rewrite dom_ran_inv''' with (f:=g⁻¹); try apply H4.\n                + repeat rewrite rel_inv_fix; try apply H4; rewrite H16; auto.\n                + rewrite rel_inv_fix; apply H4.\n                + rewrite <- dom_ran_inv, H7; auto.\n              - rewrite rel_inv_fix; apply H4.\n              - rewrite <- dom_ran_inv; subst x x0 y v.\n                apply H12 in H17; apply G2 in H17.\n                apply Property_Value in H17; try apply H3.\n                apply Property_ran in H17; auto. }\n            subst x0 x; apply H10; apply Axiom_Scheme; split; Ens.\n            exists x2; split; auto.\n            apply Axiom_Scheme; split; Ens.\n            exists (C x1); split; auto.\n            apply Axiom_Scheme; split; eauto.\n            apply sub_set with (x:=∪ CC); auto.\n            apply sub_set with (x:=dom(f)); auto. }\n        exists g[z]; apply Axiom_SchemeP; repeat split; intros.\n        { apply ord_set; split; Ens. }\n        { subst u x; auto. }\n        { contradiction. }\n        { pattern g at 2; rewrite <- rel_inv_fix; try apply H4.\n          rewrite <- dom_ran_inv'''; auto; try apply H4.\n          - rewrite rel_inv_fix; apply H4.\n          - apply Property_Value' in H11; try apply H4.\n            apply Property_dom in H11; rewrite <- dom_ran_inv; auto. }\nQed.\n\nHint Resolve Cantor_Bernstein_Schroeder : set.\n\n\n(* 160 Theorem  If f is a function and f is a set, then P(range f)≼P(domain f). *)\n\nDefinition En_g f c : Class :=\n  \\{\\ λ v u, v ∈ ran(f) /\\ u = c[\\{ λ x, v = f[x] \\}] \\}\\.\n\nLemma lem_card_le_fun : forall c f y,\n  Function f -> Ensemble dom(f) -> ChoiceFunction c -> dom( c) = μ ~ [Φ] ->\n  y ∈ ran( f) -> \\{ λ x, y = f[x] \\} ∈ dom(c).\nProof.\n  intros.\n  unfold ChoiceFunction in H1; destruct H1.\n  unfold Range in H3; apply Axiom_Scheme in H3; destruct H3, H5.\n  rewrite H2; unfold Difference; apply bel_inter.\n  assert (Ensemble (\\{ λ x, y = f[x] \\})).\n  { apply sub_set with (x:= dom(f)); auto.\n    unfold Subclass; intros; apply Axiom_Scheme in H6; destruct H6.\n    rewrite H7 in H5; clear H7; apply Property_ran in H5.\n    apply Property_Value' in H5; auto; apply Property_dom in H5; auto. }\n  split; try apply bel_universe_set; auto.\n  unfold Complement; apply Axiom_Scheme; split; auto.\n  unfold NotIn; intro; unfold Singleton in H7.\n  apply Axiom_Scheme in H7; clear H6; destruct H7.\n  assert (Φ ∈ μ).\n  { apply bel_universe_set; generalize Axiom_Infinity; intros.\n    destruct H8; Ens; exists x0; apply H8. }\n  apply H7 in H8; clear H7.\n  assert (x ∈ \\{ λ x, y = f [x] \\}).\n  { apply Axiom_Scheme; double H5; apply Property_dom in H7.\n    split; Ens; apply Property_Value in H7; auto.\n    unfold Function in H; apply H with (x:=x); Ens. }\n  rewrite H8 in H7; generalize (not_bel_zero x); intros; contradiction.\nQed.\n\nTheorem card_le_fun : forall f,\n  Function f -> P[ran(f)] ≼ P[dom(f)].\nProof.\n  intros.\n  generalize (classic (Ensemble dom(f))); intros; destruct H0.\n  - generalize Axiom_Choice; intros; destruct H1 as [c H1], H1.\n    assert (Function1_1 (En_g f c)).\n    { unfold Function1_1, Function; repeat split; intros.\n      - unfold Relation; intros; PP H3 a b; Ens.\n      - unfold En_g in H3; destruct H3.\n        apply Axiom_SchemeP in H3; apply Axiom_SchemeP in H4.\n        destruct H3, H4, H5, H6; rewrite H7, H8; auto.\n      - unfold Relation; intros; PP H3 a b; Ens.\n      - unfold Inverse, En_g in H3; destruct H3.\n        apply Axiom_SchemeP in H3; apply Axiom_SchemeP in H4.\n        destruct H3, H4; clear H3 H4; apply Axiom_SchemeP in H5.\n        apply Axiom_SchemeP in H6; destruct H5, H6, H4, H6.\n        assert (\\{ λ x, y=f[x] \\} ∈ dom(c) /\\ \\{ λ x, z=f[x] \\} ∈ dom(c)).\n        { split; apply lem_card_le_fun; auto. }\n        destruct H9; apply H1 in H9; apply H1 in H10.\n        rewrite <- H7 in H9; rewrite <- H8 in H10; apply Axiom_Scheme in H9.\n        apply Axiom_Scheme in H10; destruct H9, H10; rewrite H11, H12; auto. }\n    assert (ran(En_g f c) ⊂ dom(f)).\n    { unfold Subclass; intros; unfold Range, En_g in H4; unfold Domain.\n      apply Axiom_Scheme in H4; destruct H4, H5; apply Axiom_SchemeP in H5.\n      destruct H5, H6; apply Axiom_Scheme; split; auto; exists f[z].\n      assert (\\{ λ x0, x = f [x0] \\} ∈ dom(c)). { apply lem_card_le_fun; auto. }\n      apply H1 in H8; rewrite <- H7 in H8.\n      apply Axiom_Scheme in H8; destruct H8.\n      rewrite H9 in H6; clear H9; apply Property_Value'; auto. }\n    assert (Ensemble dom(f) /\\ ran(En_g f c) ⊂ dom(f)); auto.\n    apply card_le in H5; auto.\n    assert (dom(En_g f c) ≈ ran(En_g f c)).\n    { unfold Equivalent; exists (En_g f c); auto. }\n    assert (dom(En_g f c) = ran(f)).\n    { apply Axiom_Extent; split; intros.\n      - unfold Domain, En_g in H7; apply Axiom_Scheme in H7.\n        destruct H7, H8; apply Axiom_SchemeP in H8; apply H8.\n      - unfold Domain, En_g; apply Axiom_Scheme; split; Ens.\n        exists c[\\{ λ x, z = f [x] \\}]; apply Axiom_SchemeP; split; auto.\n        apply ord_set; split; Ens; exists \\{ λ x, z = f [x] \\}.\n        unfold ChoiceFunction in H1; apply H1; apply lem_card_le_fun; auto. }\n    rewrite H7 in H6; clear H7.\n    assert (Ensemble ran(f) /\\ Ensemble ran(En_g f c)).\n    { double H0; split; try apply Axiom_Substitution in H0; auto.\n      apply sub_set with (x:= dom(f)); auto. }\n    apply card_eq in H7; apply H7 in H6; clear H7; rewrite H6; auto.\n  - generalize card_fun; intros; destruct H1, H2.\n    generalize (classic (dom(f) ∈ dom(P))); intros; destruct H4.\n    + rewrite H2 in H4; apply bel_universe_set in H4; contradiction.\n    + apply dom_value in H4; rewrite H4; clear H4.\n      generalize (classic (ran(f) ∈ dom(P))); intros; destruct H4.\n      * rewrite H2 in H4; apply bel_universe_set in H4.\n        apply Property_PClass in H4; unfold LessEqual.\n        left; apply bel_universe_set; Ens.\n      * apply dom_value in H4; rewrite H4; unfold LessEqual; tauto.\nQed.\n\nHint Resolve card_le_fun : set.\n\n\n(* 161 Theorem  If x is a set, then P[x] ≺ P[pow(x)]. *)\n\nTheorem card_lt_pow : forall x,\n  Ensemble x -> P[x] ≺ P[ pow(x) ].\nProof.\n  intros.\n  assert (x ≈ \\{ λ v, exists u, u∈x /\\ v = [u] \\}).\n  { unfold Equivalent; exists \\{\\ λ u v, u∈x /\\ v = [u] \\}\\.\n    repeat split; auto; unfold Relation; intros; try PP H0 a b; Ens.\n    - destruct H0; apply Axiom_SchemeP in H0; apply Axiom_SchemeP in H1.\n      destruct H0, H1, H2, H3; rewrite H4, H5; auto.\n    - destruct H0; apply Axiom_SchemeP in H0; apply Axiom_SchemeP in H1.\n      destruct H0, H1; apply Axiom_SchemeP in H2; apply Axiom_SchemeP in H3.\n      clear H0 H1; destruct H2, H3, H1, H3; rewrite H4 in H5.\n      assert (y∈[y]). { apply Axiom_Scheme; split; Ens. }\n      rewrite H5 in H6; apply Axiom_Scheme in H6; destruct H6.\n      apply H7; apply bel_universe_set; Ens.\n    - apply Axiom_Extent; split; intros.\n      + unfold Domain in H0; apply Axiom_Scheme in H0; destruct H0, H1.\n        apply Axiom_SchemeP in H1; apply H1.\n      + unfold Domain; apply Axiom_Scheme; split; Ens; exists [z].\n        AssE z; apply sing_set in H1; apply Axiom_SchemeP.\n        repeat split; try apply ord_set; Ens.\n    - apply Axiom_Extent; split; intros.\n      + unfold Range in H0; apply Axiom_Scheme in H0; destruct H0, H1.\n        apply Axiom_SchemeP in H1; destruct H1, H2; apply Axiom_Scheme; Ens.\n      + apply Axiom_Scheme in H0; destruct H0, H1, H1; unfold Range.\n        apply Axiom_Scheme; split; auto; exists x0; apply Axiom_SchemeP.\n        repeat split; try apply ord_set; Ens. }\n  assert (Ensemble pow(x) /\\ \\{λ v, exists u, u∈x /\\ v=[u]\\} ⊂ pow(x)).\n  { split; try apply pow_set in H; auto.\n    unfold Subclass; intros; apply Axiom_Scheme in H1; destruct H1, H2, H2.\n    rewrite H3 in *; clear H3; unfold PowerClass.\n    apply Axiom_Scheme; split; auto.\n    unfold Subclass; intros; apply Axiom_Scheme in H3; destruct H3.\n    rewrite H4; try apply bel_universe_set; Ens. }\n  assert (Ensemble x /\\ Ensemble \\{λ v, exists u, u∈x /\\ v=[u]\\}).\n  { split; auto; destruct H1; apply sub_set in H2; auto. }\n  apply card_le in H1; apply card_eq in H2; apply H2 in H0.\n  rewrite <- H0 in H1; clear H0 H2; unfold LessEqual in H1.\n  unfold Less; destruct H1; auto.\n  assert (Ensemble x /\\ Ensemble pow(x)).\n  { split; auto; apply pow_set in H; auto. }\n  apply card_eq in H1; apply H1 in H0; clear H1.\n  unfold Equivalent in H0; destruct H0 as [f H0], H0, H1.\n  assert (\\{λ v, v ∈ x /\\ v ∉ f[v]\\} ∈ ran(f)).\n  { assert (\\{λ v, v ∈ x /\\ v ∉ f[v]\\} ⊂ x).\n    { unfold Subclass; intros; apply Axiom_Scheme in H3; apply H3. }\n    double H3; apply sub_set in H4; auto; rewrite H2.\n    unfold PowerClass; apply Axiom_Scheme; split; auto. }\n  unfold Range in H3; apply Axiom_Scheme in H3; destruct H3, H4 as [u H4].\n  double H4; apply Property_dom in H5; unfold Function1_1 in H0.\n  destruct H0; clear H6; double H5; apply Property_Value in H6; auto.\n  rewrite H1 in H5; add ([u,f[u]] ∈ f) H4; apply H0 in H4; clear H6.\n  generalize (classic (u ∈ f[u])); intros; destruct H6.\n  - double H6; rewrite <- H4 in H7; apply Axiom_Scheme in H7.\n    destruct H7, H8; contradiction.\n  - elim H6; rewrite <- H4; apply Axiom_Scheme; Ens.\nQed.\n\nHint Resolve card_lt_pow : set.\n\n\n(* 162 Theorem  C is not a set. *)\n\nTheorem C_not_set : ~ Ensemble C.\nProof.\n  intro.\n  apply Axiom_Amalgamation in H; double H.\n  apply pow_set in H0; try apply C.\n  apply Property_PClass in H0.\n  assert (Ensemble (∪C) /\\ P[ pow( ∪C ) ] ⊂ ∪C).\n  { split; auto; apply bel_ele in H0; apply H0. }\n  apply card_le in H1; rewrite card_eq_inv in H1.\n  double H; apply card_lt_pow in H2; unfold Less in H2.\n  unfold LessEqual in H1; destruct H1.\n  - apply Property_PClass in H; generalize well_order_E; intros.\n    apply well_tran_asy in H3; destruct H3; unfold Asymmetric in H4.\n    assert (P[∪C] ∈ C /\\ P[pow(∪C)] ∈ C /\\ Rrelation P[∪C] E P[pow(∪C)]).\n    { repeat split; auto; unfold Rrelation, E.\n      apply Axiom_SchemeP; split; try apply ord_set; Ens. }\n    apply H4 in H5; apply H5; clear H4 H5.\n    unfold Rrelation, E; apply Axiom_SchemeP.\n    split; try apply ord_set; Ens.\n  - rewrite H1 in H2.\n    generalize (notin_fix P[∪C]); intros; contradiction.\nQed.\n\nHint Resolve C_not_set : set.\n\n\n(* We divide the cardinals into two classes, the finite cardinals and the\n   infinte cardinals. *)\n\n(* 163 Theorem  If x∈W, y∈W and x+1≈y+1, then x≈y. *)\n\nLtac SplitEns := apply Axiom_Scheme; split; Ens.\n\nLtac SplitEnsP := apply Axiom_SchemeP; split; try apply ord_set; Ens.\n\nDefinition En_g' f x y : Class :=\n  \\{\\ λ u v, [u,v] ∈ (f ~ ([[x,f[x]]] ∪ [[f⁻¹[y],y]])) \\/\n      [u,v] = [f⁻¹[y],f[x]] \\/ [u,v] = [x,y] \\}\\.\n\nTheorem equiv_plus_equiv : forall x y,\n  x∈W -> y∈W -> (PlusOne x) ≈ (PlusOne y) -> x ≈ y.\nProof.\n  intros.\n  unfold Equivalent in H1; destruct H1 as [f H1], H1, H2.\n  unfold Function1_1 in H1; destruct H1; unfold Equivalent.\n  exists ((En_g' f x y) | (x)); repeat split; intros.\n  - unfold Relation; intros; unfold Restriction in H5.\n    apply bel_inter in H5; destruct H5; PP H6 a b; Ens.\n  - destruct H5; unfold Restriction in H5, H6.\n    apply bel_inter in H5; apply bel_inter in H6.\n    destruct H5, H6; clear H8; unfold En_g' in H5, H6.\n    apply Axiom_SchemeP in H5; apply Axiom_SchemeP in H6; destruct H5,H6.\n    unfold Cartesian in H7; apply Axiom_SchemeP in H7; clear H5.\n    destruct H7, H7; clear H10; destruct H8, H9.\n    + unfold Difference in H8, H9; apply bel_inter in H8.\n      apply bel_inter in H9; destruct H8, H9; clear H10 H11.\n      unfold Function in H1; apply H1 with (x:= x0); auto.\n    + destruct H9.\n      * unfold Difference in H8; apply bel_inter in H8; destruct H8.\n        unfold Complement in H10; apply Axiom_Scheme in H10; clear H5.\n        destruct H10; elim H10; clear H10; apply bel_union.\n        right; apply Axiom_Scheme; split; auto; intros; clear H10.\n        apply ord_set in H6; apply ord_eq in H9; auto.\n        destruct H9; clear H10; double H8; apply Property_dom in H10.\n        apply Property_Value in H10; auto; add ([x0,f[x0]] ∈ f) H8.\n        apply H1 in H8; clear H10; rewrite H9 in H8.\n        rewrite <- dom_ran_inv''' in H8; auto. rewrite H8, H9; auto.\n        rewrite H3; unfold PlusOne; apply bel_union; right.\n        unfold Singleton; apply Axiom_Scheme; split; Ens.\n      * apply ord_set in H6; apply ord_eq in H9; auto; destruct H9.\n        rewrite H9 in H7; generalize (notin_fix x); contradiction.\n    + destruct H8.\n      * unfold Difference in H9; apply bel_inter in H9; destruct H9.\n        unfold Complement in H10; apply Axiom_Scheme in H10; clear H6.\n        destruct H10; elim H10; clear H10; apply bel_union.\n        right; apply Axiom_Scheme; split; auto; intros; clear H10.\n        apply ord_set in H5; apply ord_eq in H8; auto.\n        destruct H8; clear H10; double H9; apply Property_dom in H10.\n        apply Property_Value in H10; auto; add ([x0,f[x0]] ∈ f) H9.\n        apply H1 in H9; clear H10; rewrite H8 in H9.\n        rewrite <- dom_ran_inv''' in H9; auto. rewrite H8, H9; auto.\n        rewrite H3; unfold PlusOne; apply bel_union; right.\n        unfold Singleton; apply Axiom_Scheme; split; Ens.\n      * apply ord_set in H5; apply ord_eq in H8; auto; destruct H8.\n        rewrite H8 in H7; generalize (notin_fix x); contradiction.\n    + apply ord_set in H5; apply ord_set in H6.\n      destruct H8, H9; apply ord_eq in H8; apply ord_eq in H9; auto.\n      * destruct H8, H9; rewrite H10, H11; auto.\n      * destruct H9; rewrite H9 in H7.\n        generalize (notin_fix x); intros; contradiction.\n      * destruct H8; rewrite H8 in H7.\n        generalize (notin_fix x); intros; contradiction.\n      * destruct H8; rewrite H8 in H7.\n        generalize (notin_fix x); intros; contradiction.\n  - unfold Relation; intros; PP H5 a b; Ens.\n  - destruct H5; unfold Inverse, Restriction in H5, H6.\n    apply Axiom_SchemeP in H5; apply Axiom_SchemeP in H6; destruct H5, H6.\n    apply bel_inter in H7; apply bel_inter in H8; destruct H7, H8.\n    apply Axiom_SchemeP in H7; apply Axiom_SchemeP in H8; destruct H7, H8.\n    unfold Cartesian in H9; apply Axiom_SchemeP in H9; clear H7.\n    destruct H9, H9; clear H13; apply Axiom_SchemeP in H10; clear H8.\n    destruct H10, H10; clear H13; destruct H11, H12.\n    + unfold Difference in H11, H12; apply bel_inter in H11.\n      apply bel_inter in H12; destruct H11, H12; clear H13 H14.\n      assert ([x0,y0] ∈ f⁻¹ /\\ [x0,z] ∈ f⁻¹).\n      { unfold Inverse; split; apply Axiom_SchemeP; split; auto. }\n      unfold Function in H4; apply H4 in H13; auto.\n    + destruct H12.\n      * unfold Difference in H11; apply bel_inter in H11; destruct H11.\n        clear H13; apply ord_set in H8; apply ord_eq in H12; auto.\n        destruct H12; rewrite H13 in *; double H11.\n        apply Property_ran in H14; apply Property_Value' in H14; auto.\n        assert ([f[x],y0] ∈ f⁻¹ /\\ [f[x],x] ∈ f⁻¹).\n        { unfold Inverse; split; apply Axiom_SchemeP; split; auto;AssE [x,f[x]].\n          apply ord_set in H15; destruct H15; apply ord_set; auto. }\n        unfold Function in H4; apply H4 in H15; auto.\n        rewrite H15 in H9; generalize (notin_fix x); contradiction.\n      * unfold Difference in H11; apply bel_inter in H11; destruct H11.\n        unfold Complement in H13; apply Axiom_Scheme in H13; clear H7.\n        destruct H13; elim H13; clear H13; apply bel_union.\n        right; apply Axiom_Scheme; split; auto; intros; clear H13.\n        apply ord_set in H8; apply ord_eq in H12; auto.\n        destruct H12; rewrite H13 in *; clear H6 H8 H12 H13.\n        assert ([y,y0] ∈ f⁻¹). { apply Axiom_SchemeP; Ens. }\n        double H6; apply Property_dom in H8; apply Property_Value in H8; auto.\n        add ([y,y0] ∈ f⁻¹) H8; apply H4 in H8; rewrite H8; auto.\n    + destruct H11.\n      * unfold Difference in H12; apply bel_inter in H12; destruct H12.\n        clear H13; apply ord_set in H7; apply ord_eq in H11; auto.\n        destruct H11; rewrite H13 in *; double H12.\n        apply Property_ran in H14; apply Property_Value' in H14; auto.\n        assert ([f[x],z] ∈ f⁻¹ /\\ [f[x],x] ∈ f⁻¹).\n        { unfold Inverse; split; apply Axiom_SchemeP; split; auto;AssE [x,f[x]].\n          apply ord_set in H15; destruct H15; apply ord_set; auto. }\n        unfold Function in H4; apply H4 in H15; auto.\n        rewrite H15 in H10; generalize (notin_fix x); contradiction.\n      * unfold Difference in H12; apply bel_inter in H12; destruct H12.\n        unfold Complement in H13; apply Axiom_Scheme in H13; clear H8.\n        destruct H13; elim H13; clear H13; apply bel_union.\n        right; apply Axiom_Scheme; split; auto; intros; clear H13.\n        apply ord_set in H7; apply ord_eq in H11; auto.\n        destruct H11; rewrite H13 in *; clear H5 H7 H11 H13.\n        assert ([y,z] ∈ f⁻¹). { apply Axiom_SchemeP; Ens. }\n        double H5; apply Property_dom in H7; apply Property_Value in H7; auto.\n        add ([y,z] ∈ f⁻¹) H7; apply H4 in H7; rewrite H7; auto.\n    + apply ord_set in H7; apply ord_set in H8.\n      destruct H11, H12; apply ord_eq in H11; apply ord_eq in H12; auto.\n      * destruct H11, H12; rewrite H11, H12; auto.\n      * destruct H12; rewrite H12 in H10.\n        generalize (notin_fix x); intros; contradiction.\n      * destruct H11; rewrite H11 in H9.\n        generalize (notin_fix x); intros; contradiction.\n      * destruct H12; rewrite H12 in H10.\n        generalize (notin_fix x); intros; contradiction.\n  - apply Axiom_Extent; split; intros.\n    + unfold Domain in H5; apply Axiom_Scheme in H5; destruct H5, H6.\n      unfold Restriction in H6; apply bel_inter in H6; destruct H6.\n      unfold Cartesian in H7; apply Axiom_SchemeP in H7; apply H7.\n    + unfold Domain; apply Axiom_Scheme; split; Ens.\n      assert ([x,f[x]] ∈ f).\n      { apply Property_Value; auto; rewrite H2; unfold PlusOne.\n        apply bel_union; right; apply Axiom_Scheme; split; Ens. }\n      generalize (classic (z = f⁻¹[y])); intros; destruct H7.\n      * rewrite H7 in *; AssE [x,f[x]]; clear H6 H7.\n        apply ord_set in H8; destruct H8.\n        exists f[x]; unfold Restriction; apply bel_inter.\n        split; SplitEnsP; split; try apply bel_universe_set; auto.\n      * assert (z ∈ dom(f)). { rewrite H2; apply bel_union; tauto. }\n        apply Property_Value in H8; auto; AssE [z,f[z]].\n        apply ord_set in H9; destruct H9; exists f[z].\n        unfold Restriction; apply bel_inter; split; SplitEnsP.\n        { left; unfold Difference; apply bel_inter; split; auto.\n          unfold Complement; apply Axiom_Scheme; split; Ens.\n          intro; apply bel_union in H11; destruct H11.\n          - apply Axiom_Scheme in H11; destruct H11; clear H11.\n            assert ([x,f[x]] ∈ μ). { apply bel_universe_set; Ens. }\n            apply H12 in H11; clear H12; apply ord_eq in H11; auto.\n            destruct H11; rewrite H11 in H5; generalize (notin_fix x); auto.\n          - apply Axiom_Scheme in H11; destruct H11; clear H11.\n            assert ([(f⁻¹)[y],y] ∈ μ).\n            { apply bel_universe_set; Ens; exists f.\n              assert (y ∈ ran(f)).\n              { rewrite H3; unfold PlusOne; apply bel_union; right.\n                apply Axiom_Scheme; split; Ens. }\n              rewrite dom_ran_inv' in H11; apply Property_Value in H11; auto.\n              apply Axiom_SchemeP in H11; apply H11. }\n            apply H12 in H11; clear H12; apply ord_eq in H11; auto.\n            destruct H11; contradiction. }\n        { split; try apply bel_universe_set; auto. }\n  - apply Axiom_Extent; split; intros.\n    + unfold Range in H5; apply Axiom_Scheme in H5; destruct H5, H6.\n      unfold Restriction in H6; apply bel_inter in H6; destruct H6.\n      unfold Cartesian in H7; apply Axiom_SchemeP in H7; destruct H7.\n      clear H7; destruct H8; clear H8; unfold En_g' in H6.\n      apply Axiom_SchemeP in H6; destruct H6, H8 as [H8|[H8|H8]].\n      * unfold Difference in H8; apply bel_inter in H8; destruct H8.\n        unfold Complement in H9; apply Axiom_Scheme in H9; clear H6.\n        destruct H9; double H8; apply Property_ran in H10; rewrite H3 in H10.\n        unfold PlusOne in H10; apply bel_union in H10; destruct H10; auto.\n        apply Axiom_Scheme in H10; clear H5; destruct H10.\n        rewrite H10 in *; try apply bel_universe_set; Ens; clear H10.\n        double H8; apply Property_ran in H10; rewrite dom_ran_inv' in H10.\n        apply Property_Value in H10; auto; apply ord_set in H6.\n        destruct H6; clear H11; add ([y,x0] ∈ f⁻¹) H10; try SplitEnsP.\n        apply H4 in H10; rewrite H10 in H9; elim H9.\n        apply bel_union; right; SplitEns.\n      * apply ord_set in H6; apply ord_eq in H8; auto; destruct H8.\n        assert (x ∈ dom(f)).\n        { rewrite H2; unfold PlusOne; apply bel_union; right.\n          unfold Singleton; apply Axiom_Scheme; split; Ens. }\n        double H10; apply Property_Value in H11; auto.\n        apply Property_ran in H11; rewrite H3 in H11; unfold PlusOne in H11.\n        apply bel_union in H11; rewrite H9 in *; destruct H11; auto.\n        apply Axiom_Scheme in H11; clear H5; destruct H11.\n        rewrite <- H11 in H8; try apply bel_universe_set; Ens.\n        pattern f at 2 in H8; rewrite <- rel_inv_fix in H8; try apply H1.\n        rewrite <- dom_ran_inv''' in H8; try rewrite rel_inv_fix; try apply H1; auto.\n        { rewrite H8 in H7; generalize (notin_fix x); contradiction. }\n        { rewrite <- dom_ran_inv; auto. }\n      * apply ord_set in H6; apply ord_eq in H8; auto; destruct H8.\n        rewrite H8 in H7; generalize (notin_fix x); contradiction.\n    + unfold Range; apply Axiom_Scheme; split; Ens.\n      assert (z∈ran(f)). { rewrite H3; unfold PlusOne; apply bel_union; auto. }\n      generalize (classic (z = f[x])); intros; destruct H7.\n      * rewrite H7 in *; clear H7.\n        assert (y ∈ ran(f)).\n        { rewrite H3; unfold PlusOne; apply bel_union; right.\n          unfold Singleton; apply Axiom_Scheme; split; Ens. }\n        double H7; rewrite dom_ran_inv' in H8; apply Property_Value in H8; auto.\n        apply Property_ran in H8; rewrite <- dom_ran_inv in H8; rewrite H2 in H8.\n        unfold PlusOne in H8; apply bel_union in H8; destruct H8.\n        { exists (f⁻¹)[y]; unfold Restriction; apply bel_inter.\n          split; SplitEnsP; split; try apply bel_universe_set; Ens. }\n        { unfold Singleton in H8; apply Axiom_Scheme in H8; destruct H8.\n          rewrite <- H9 in H5; try apply bel_universe_set; Ens.\n          rewrite <- dom_ran_inv''' in H5; auto.\n          generalize (notin_fix y); intros; contradiction. }\n      * unfold Range in H6; apply Axiom_Scheme in H6; destruct H6, H8.\n        exists x0; AssE [x0,z]; unfold Restriction; apply bel_inter; split.\n        { unfold En_g'; apply Axiom_SchemeP; split; auto; left.\n          unfold Difference; apply bel_inter; split; auto; unfold Complement.\n          apply Axiom_Scheme; split; auto; intro; apply bel_union in H10.\n          destruct H10; apply Axiom_Scheme in H10; destruct H10.\n          - assert ([x,f[x]] ∈ μ); clear H10.\n            { apply bel_universe_set; Ens; exists f; apply Property_Value; auto.\n              rewrite H2; unfold PlusOne; apply bel_union; right.\n              unfold Singleton; apply Axiom_Scheme; split; Ens. }\n            apply H11 in H12; clear H11; apply ord_set in H9.\n            apply ord_eq in H12; auto; destruct H12; tauto.\n          - assert ([(f⁻¹)[y], y] ∈ μ); clear H10.\n            { apply bel_universe_set; Ens; exists f. assert (y ∈ ran(f)).\n              { rewrite H3; unfold PlusOne; apply bel_union; right.\n                apply Axiom_Scheme; split; Ens. }\n              rewrite dom_ran_inv' in H10; apply Property_Value in H10; auto.\n              apply Axiom_SchemeP in H10; apply H10. }\n            apply H11 in H12; clear H11; apply ord_set in H9.\n            apply ord_eq in H12; auto; destruct H12; rewrite H11 in H5.\n            generalize (notin_fix y); intros; contradiction. }\n        { double H8; apply Property_dom in H10; rewrite H2 in H10.\n          unfold PlusOne in H10; apply bel_union in H10; unfold Cartesian.\n          apply Axiom_SchemeP; repeat split; auto; try apply bel_universe_set; Ens.\n          destruct H10; auto; apply Axiom_Scheme in H10; destruct H10.\n          rewrite H11 in H8; try apply bel_universe_set; Ens; double H8.\n          apply Property_dom in H12; apply Property_Value in H12; auto.\n          add ([x,z] ∈ f) H12; apply H1 in H12; symmetry in H12; tauto. }\nQed.\n\nHint Resolve equiv_plus_equiv : set.\n\n\n(* 164 Theorem  w ⊂ C. *)\n\nTheorem W_sub_C : W ⊂ C.\nProof.\n  intros.\n  unfold Subclass; apply Mathematical_Induction.\n  - assert (Φ ∈ W); try apply zero_not_int; try apply W.\n    unfold W in H; apply Axiom_Scheme in H; destruct H; unfold NInteger in H0.\n    destruct H0; unfold C; apply Axiom_Scheme.\n    unfold Cardinal_Number, Ordinal_Number; repeat split; intros; auto.\n    + unfold R; apply Axiom_Scheme; split; auto.\n    + unfold Less in H3; generalize (not_bel_zero y); contradiction.\n  - intros; destruct H; double H; apply int_succ in H1; unfold W in H1.\n    apply Axiom_Scheme in H1; unfold NInteger in H1; destruct H1, H2.\n    unfold C in H0; apply Axiom_Scheme in H0; destruct H0.\n    unfold Cardinal_Number, Ordinal_Number in H4; destruct H4.\n    unfold C; apply Axiom_Scheme; split; auto; split; intros.\n    + unfold Ordinal_Number, R; apply Axiom_Scheme; split; auto.\n    + unfold Less, PlusOne in H7; apply bel_union in H7; destruct H7.\n      * assert (y ∈ W).\n        { unfold W; apply Axiom_Scheme; split; Ens.\n          unfold W in H; apply Axiom_Scheme in H; destruct H.\n          apply int_bel_int in H7; auto. }\n        intro; clear H6; double H8; apply Axiom_Scheme in H6; destruct H6.\n        unfold NInteger in H10; destruct H10; unfold WellOrdered in H11.\n        destruct H11 as [H12 H11]; clear H12.\n        generalize (classic (y = Φ)); intros; destruct H12.\n        { rewrite H12 in H9; clear H12; unfold Equivalent in H9.\n          destruct H9 as [f H9]; destruct H9, H12.\n          assert (k ∈ (PlusOne k)).\n          { unfold PlusOne; apply bel_union; right; unfold Singleton.\n            apply Axiom_Scheme; split; Ens. }\n          rewrite <- H12 in H14; unfold Function1_1 in H9; destruct H9.\n          apply Property_Value in H14; auto; apply Property_ran in H14.\n          rewrite H13 in H14; generalize (not_bel_zero f[k]); contradiction. }\n        { assert (y ⊂ y /\\ y ≠ Φ). { split; unfold Subclass; Ens. }\n          apply H11 in H13; clear H11 H12; destruct H13.\n          assert (y = PlusOne x).\n          { apply ordnum_plus_eq; split; auto; try apply Axiom_Scheme; Ens. }\n          unfold FirstMember in H11; destruct H11; clear H13.\n          rewrite H12 in H9; apply equiv_plus_equiv in H9; auto.\n          - assert (x ∈ R /\\ x ≺ k).\n            { unfold Less; split.\n              - unfold R; apply Axiom_Scheme; split; Ens.\n                apply ord_bel_ord with (x:= y); auto.\n              - unfold R in H4; apply Axiom_Scheme in H4; destruct H4.\n                unfold Ordinal, full in H13; destruct H13.\n                apply H14 in H7; apply H7 in H11; auto. }\n            destruct H13; apply H5 in H14; auto.\n          - generalize Property_W; intros; unfold Ordinal, full in H13.\n            destruct H13; apply H14 in H8; apply H8 in H11; auto. }\n      * unfold Singleton in H7; apply Axiom_Scheme in H7; destruct H7.\n        assert (k ∈ μ); try apply bel_universe_set; Ens; apply H8 in H9.\n        clear H6 H7 H8; rewrite H9; intro; clear H9; double H.\n        apply Axiom_Scheme in H7; clear H0; destruct H7; unfold NInteger in H7.\n        destruct H7; unfold WellOrdered in H8; destruct H8; clear H8.\n        generalize (classic (k = Φ)); intros; destruct H8.\n        { rewrite H8 in H6; clear H8; unfold Equivalent in H6.\n          destruct H6 as [f H6]; destruct H6, H8.\n          assert (Φ ∈ (PlusOne Φ)).\n          { unfold PlusOne; apply bel_union; right; unfold Singleton.\n            apply Axiom_Scheme; split; auto; generalize Axiom_Infinity; intros.\n            destruct H11, H11, H12; Ens. }\n          rewrite <- H8 in H11; unfold Function1_1 in H6; destruct H6.\n          apply Property_Value in H11; auto; apply Property_ran in H11.\n          rewrite H10 in H11; generalize (not_bel_zero f[Φ]); contradiction. }\n        { assert (k ⊂ k /\\ k ≠ Φ). { split; unfold Subclass; Ens. }\n          apply H9 in H10; clear H8 H9; destruct H10.\n          assert (k = PlusOne x).\n          { apply ordnum_plus_eq; split; auto; try apply Axiom_Scheme; Ens. }\n          unfold FirstMember in H8; destruct H8; clear H10.\n          pattern k at 2 in H6; rewrite H9 in H6; apply equiv_plus_equiv in H6; auto.\n          - apply H5 in H8; try contradiction; unfold R; apply Axiom_Scheme.\n            split; Ens; apply ord_bel_ord with (x:= k); auto.\n          - unfold W; apply Axiom_Scheme; split; Ens.\n            apply Axiom_Scheme in H; destruct H; apply int_bel_int in H8; auto. }\nQed.\n\nHint Resolve W_sub_C : set.\n\n\n(* 165 Theorem  W ∈ C. *)\n\nTheorem W_bel_C : W ∈ C.\nProof.\n  generalize W_bel_R; intros; AssE W.\n  unfold C; apply Axiom_Scheme; split; auto.\n  unfold Cardinal_Number; split; intros.\n  - unfold Ordinal_Number; auto.\n  - unfold Less in H2; intro; double H2.\n    apply int_succ in H4.\n    assert (Ensemble (PlusOne y) /\\ y ⊂ (PlusOne y)).\n    { split; Ens; unfold PlusOne, Subclass; intros.\n      apply bel_union; tauto. }\n    apply card_le in H5.\n    assert (Ensemble W /\\ (PlusOne y) ⊂ W).\n    { split; auto; unfold PlusOne, Subclass; intros.\n      apply bel_union in H6; destruct H6.\n      - unfold W in H2; apply Axiom_Scheme in H2; destruct H2.\n        unfold W; apply Axiom_Scheme; split; Ens.\n        apply int_bel_int in H6; auto.\n      - unfold Singleton in H6; apply Axiom_Scheme in H6; destruct H6.\n        rewrite H7; try apply bel_universe_set; Ens. }\n    apply card_le in H6; apply card_eq in H3; Ens.\n    unfold LessEqual in H5, H6; destruct H5, H6.\n    + generalize (not_bel_and P[y] P[PlusOne y]); intros.\n      rewrite H3 in H6; elim H7; split; auto.\n    + rewrite H3 in H6; rewrite <- H6 in H5.\n      generalize (notin_fix P[PlusOne y]); intros; contradiction.\n    + rewrite H3, H5 in H6.\n      generalize (notin_fix P[PlusOne y]); intros; contradiction.\n    + apply card_eq in H5; Ens.\n      apply W_sub_C in H4; unfold C in H4.\n      apply Axiom_Scheme in H4; destruct H4; unfold Cardinal_Number in H7.\n      destruct H7; apply H8 in H1.\n      * elim H1; apply equiv_com; auto.\n      * unfold Less, PlusOne; apply bel_union; right.\n        unfold Singleton; apply Axiom_Scheme; Ens.\nQed.\n\nHint Resolve W_bel_C : set.\n\n\n(* 166 Definition  x is finite if and only if P(x)∈W. *)\n\nDefinition Finite (x: Class) : Prop := P [x] ∈ W.\n\nCorollary Property_Finite : forall x, Finite x -> Ensemble x.\nProof.\n  intros; unfold Finite in H.\n  generalize (classic (Ensemble x)); intros; destruct H0; auto.\n  generalize card_fun; intros; destruct H1, H2.\n  assert (x ∉ dom(P)).\n  { rewrite H2; intro; apply bel_universe_set in H4; contradiction. }\n  apply dom_value in H4; rewrite H4 in H; AssE μ.\n  generalize universe_notset; intros; contradiction.\nQed.\n\nHint Unfold Finite : set.\n\n\n(* 167 Theorem  x is finite if and only if there is r such that r well-orders x\n   and r⁻¹ well-orders x. *)\n\nLemma lem_fin_iff_well : forall r x f,\n  WellOrdered r P[x] -> Function1_1 f -> dom(f) = x ->\n  ran(f) = P[x] -> WellOrdered \\{\\ λ u v, Rrelation f[u] r f[v] \\}\\ x.\nProof.\n  intros.\n  unfold Function1_1 in H0; destruct H0.\n  unfold WellOrdered; split; intros.\n  - unfold Connect; intros; destruct H4; rewrite <- H1 in H4, H5.\n    AssE u; AssE v; apply Property_Value in H4; auto.\n    apply Property_Value in H5; auto; double H4; double H5.\n    apply Property_ran in H8; apply Property_ran in H9.\n    rewrite H2 in H8, H9; unfold WellOrdered, Connect in H.\n    destruct H; clear H10; add (f[v] ∈ P[x]) H8; apply H in H8.\n    clear H H9; destruct H8 as [H | [H | H]].\n    + left; unfold Rrelation; apply Axiom_SchemeP;split;try apply ord_set;Ens.\n    + right; left; apply Axiom_SchemeP; split; try apply ord_set; auto.\n    + right; right; rewrite H in H4; clear H.\n      assert ([f[v],u] ∈ f⁻¹ /\\ [f[v],v] ∈ f⁻¹).\n      { unfold Inverse; split; apply Axiom_SchemeP; split; auto.\n        - apply ord_set; split; apply Property_ran in H4; Ens.\n        - apply ord_set; split; apply Property_ran in H5; Ens. }\n      unfold Function in H3; apply H3 in H; auto.\n  - assert (ran(f|(y)) ⊂ P [x] /\\ ran(f|(y)) ≠ Φ).\n    { destruct H4; split.\n      - unfold Subclass; intros; unfold Range in H6; apply Axiom_Scheme in H6.\n        destruct H6, H7; unfold Restriction in H7; apply bel_inter in H7.\n        destruct H7; apply Property_ran in H7; rewrite H2 in H7; auto.\n      - apply not_zero_exist_bel in H5; destruct H5; double H5; apply H4 in H6.\n        rewrite <- H1 in H6; apply Property_Value in H6; auto.\n        double H6; apply Property_ran in H7; apply not_zero_exist_bel.\n        exists f[x0]; unfold Range; apply Axiom_Scheme; split; Ens.\n        exists x0; unfold Restriction; apply bel_inter; split; auto.\n        unfold Cartesian; apply Axiom_SchemeP; repeat split; Ens.\n        apply bel_universe_set; Ens. }\n    apply H in H5; unfold FirstMember in H5; destruct H5, H5.\n    unfold Range in H5; apply Axiom_Scheme in H5; destruct H5, H7.\n    unfold Restriction in H7; apply bel_inter in H7; destruct H7.\n    exists x1; unfold FirstMember; split; intros.\n    + unfold Cartesian in H8; apply Axiom_SchemeP in H8; apply H8.\n    + clear H8; double H9; apply H4 in H9; rewrite <- H1 in H9.\n      apply Property_Value in H9; auto.\n      assert (f[y0] ∈ ran(f|(y))).\n      { AssE [y0,f[y0]]; apply ord_set in H10; destruct H10.\n        unfold Range; apply Axiom_Scheme; split; auto.\n        exists y0; unfold Restriction; apply bel_inter; split; auto.\n        apply Axiom_SchemeP; repeat split; try apply ord_set; auto.\n        apply bel_universe_set; auto. }\n      apply H6 in H10; clear H6; intro; elim H10; clear H10.\n      unfold Rrelation at 1 in H6; apply Axiom_SchemeP in H6; destruct H6.\n      double H7; apply Property_dom in H11; apply Property_Value in H11; Ens.\n      add ([x1,f[x1]] ∈ f) H7; apply H0 in H7; rewrite H7; auto.\nQed.\n\nTheorem fin_iff_well : forall x,\n  Finite x <-> exists r, WellOrdered r x /\\ WellOrdered (r⁻¹) x.\nProof.\n  intros; split; intros.\n  - double H; unfold Finite in H; apply Property_Finite in H0.\n    unfold W in H; apply Axiom_Scheme in H; destruct H.\n    unfold NInteger in H1; destruct H1; apply ord_well_order in H1.\n    apply card_equiv in H0; apply equiv_com in H0.\n    unfold Equivalent in H0; destruct H0 as [f H0], H0, H3.\n    exists (\\{\\ λ u v, Rrelation f[u] E f[v] \\}\\); split.\n    + apply lem_fin_iff_well; auto.\n    + assert (\\{\\ λ u v, Rrelation f [u] E f [v] \\}\\⁻¹ =\n              \\{\\ λ u v, Rrelation f [u] E⁻¹ f [v] \\}\\).\n      { apply Axiom_Extent; split; intros.\n        - PP H5 a b; apply Axiom_SchemeP.\n          apply Axiom_SchemeP in H6; destruct H6.\n          apply Axiom_SchemeP in H7; destruct H7; split; auto.\n          unfold Rrelation in H8; unfold Rrelation, Inverse.\n          apply Axiom_SchemeP; split; auto; AssE [f[b],f[a]].\n          apply ord_set in H9; destruct H9; apply ord_set; auto.\n        - PP H5 a b; apply Axiom_SchemeP in H6; destruct H6.\n          unfold Rrelation, Inverse in H7.\n          apply Axiom_SchemeP in H7; destruct H7.\n          apply ord_set in H6; destruct H6; apply Axiom_SchemeP.\n          split; try apply ord_set; auto; apply Axiom_SchemeP.\n          split; try apply ord_set; auto. }\n      rewrite H5; apply lem_fin_iff_well; auto.\n  - destruct H as [r H], H; unfold Finite.\n    generalize ord_not_set_R; intros; destruct H1; clear H2.\n    apply ord_well_order in H1; add (WellOrdered E R) H; clear H1.\n    apply well_order_pre in H; destruct H as [f H], H, H1.\n    unfold Order_PXY in H1; destruct H1, H3, H4, H5; double H6.\n    apply sec_R_ord in H7; add (Ordinal W) H7; try apply Property_W.\n    apply ord_bel_eq in H7; destruct H7.\n    + destruct H2.\n      * assert (P[x] = ran(f)).\n        { apply W_sub_C in H7; clear H0; AssE ran(f).\n          apply order_pre_fun1_inv in H4; destruct H4; clear H8.\n          assert (dom(f) ≈ ran(f)). { unfold Equivalent; exists f; auto. }\n          unfold Function1_1 in H4; destruct H4.\n          rewrite (dom_ran_inv f), (dom_ran_inv' f) in *.\n          apply Axiom_Substitution in H0; auto; rewrite H2 in *; double H0.\n          apply card_equiv in H0; apply Property_PClass in H10.\n          apply equiv_tran with (z:= dom(f⁻¹)) in H0; auto; clear H2 H8.\n          unfold C in H7, H10; apply Axiom_Scheme in H7.\n          apply Axiom_Scheme in H10.\n          destruct H7, H10; clear H2 H8; destruct H7, H10.\n          unfold Ordinal_Number in H2, H8; double H2; double H8.\n          unfold R in H11, H12; apply Axiom_Scheme in H11.\n          apply Axiom_Scheme in H12.\n          destruct H11, H12; add (Ordinal dom(f⁻¹)) H14; clear H11 H12 H13.\n          apply ord_bel_eq in H14; destruct H14 as [H11 | [H11 | H11]]; auto.\n          - apply H7 in H11; auto; apply equiv_com in H0; contradiction.\n          - apply H10 in H11; auto; contradiction. }\n          rewrite H8; auto.\n      * rewrite H2 in H7; add (W ∈ R) H7; try apply W_bel_R.\n        generalize (not_bel_and R W); intros; contradiction.\n    + assert (W ⊂ ran(f)).\n      { destruct H7; try (rewrite H7; unfold Subclass; auto).\n        apply sec_R_ord in H6; unfold Ordinal, full in H6.\n        destruct H6; apply H8 in H7; auto. }\n      assert (~ exists z, FirstMember z E⁻¹ W).\n      { intro; destruct H9; unfold FirstMember in H9; destruct H9.\n        AssE x0; apply int_succ in H9; AssE (PlusOne x0).\n        apply H10 in H9; elim H9; clear H9 H10.\n        unfold Rrelation, Inverse, E; apply Axiom_SchemeP.\n        split; try apply ord_set; auto; apply Axiom_SchemeP.\n        split; try apply ord_set; auto; unfold PlusOne.\n        apply bel_union; right; apply Axiom_Scheme; auto. }\n      double H5; unfold Section in H10; destruct H10; clear H11.\n      apply lem_order_pre_sec_sub with (r:= r⁻¹) in H10; auto; clear H6; double H4.\n      apply order_pre_fun1_inv in H6; destruct H6; clear H11; destruct H6 as [H11 H6].\n      clear H11; elim H9; clear H9; unfold WellOrdered in H10; destruct H10.\n      assert (ran(f⁻¹|(W)) ⊂ dom(f) /\\ ran(f⁻¹|(W)) ≠ Φ).\n      { split; unfold Subclass; intros.\n        - unfold Range in H11; apply Axiom_Scheme in H11; destruct H11, H12.\n          unfold Restriction in H12; apply bel_inter in H12; destruct H12.\n          unfold Inverse in H12; apply Axiom_SchemeP in H12; destruct H12.\n          apply Property_dom in H14; auto.\n        - assert (Φ ∈ W); try apply zero_not_int; auto; double H11.\n          apply H8 in H12; rewrite dom_ran_inv' in H12.\n          apply Property_Value in H12; auto; AssE [Φ,(f⁻¹)[Φ]].\n          apply ord_set in H13; destruct H13; apply not_zero_exist_bel.\n          exists f⁻¹[Φ]; unfold Range; apply Axiom_Scheme; split; auto.\n          exists Φ; unfold Restriction; apply bel_inter; split; auto.\n          apply Axiom_SchemeP; repeat split; try apply ord_set; auto.\n          apply bel_universe_set; auto. }\n      apply H10 in H11; clear H10; destruct H11; exists f[x0].\n      unfold FirstMember in H10; destruct H10.\n      unfold FirstMember; split; intros.\n      * clear H11; apply Axiom_Scheme in H10; destruct H10, H11.\n        unfold Restriction in H11; apply bel_inter in H11; destruct H11.\n        apply Axiom_SchemeP in H12; destruct H12 as [_ H12], H12 as [H12 _].\n        unfold Inverse in H11; apply Axiom_SchemeP in H11.\n        destruct H11; double H13.\n        apply Property_dom in H14; apply Property_Value in H14; auto.\n        add ([x0,f[x0]] ∈ f) H13; clear H14; unfold Function in H.\n        apply H in H13; rewrite H13 in H12; auto.\n      * double H12; apply H8 in H13; apply Axiom_Scheme in H13.\n        destruct H13, H14.\n        AssE [x1,y]; apply ord_set in H15; destruct H15; clear H16.\n        assert (x1 ∈ ran(f⁻¹|(W))).\n        { unfold Range; apply Axiom_Scheme; split; auto; exists y.\n          unfold Restriction; apply bel_inter; split.\n          - unfold Inverse; apply Axiom_SchemeP.\n            split; try apply ord_set; auto.\n          - unfold Cartesian; apply Axiom_SchemeP.\n            repeat split; try apply ord_set; auto; apply bel_universe_set; auto. }\n        apply H11 in H16; clear H11; unfold Range in H10.\n        apply Axiom_Scheme in H10.\n        destruct H10, H11; unfold Restriction in H11; apply bel_inter in H11.\n        destruct H11; clear H17; unfold Inverse in H11.\n        apply Axiom_SchemeP in H11.\n        clear H10; destruct H11; apply Property_dom in H11; double H14.\n        apply Property_dom in H17; add (x1 ∈ dom(f)) H11; double H11; clear H17.\n        unfold Connect in H9; apply H9 in H18; clear H9; intro.\n        unfold Rrelation, Inverse, E in H9; apply Axiom_SchemeP in H9.\n        destruct H9; clear H9; apply Axiom_SchemeP in H17; destruct H17.\n        destruct H18 as [H18|[H18|H18]]; try contradiction.\n        { clear H16; unfold Order_Pr in H4; destruct H11.\n          assert (x1 ∈ dom(f) /\\ x0 ∈ dom(f) /\\ Rrelation x1 r x0).\n          { repeat split; auto; unfold Rrelation, Inverse in H18.\n            apply Axiom_SchemeP in H18; unfold Rrelation; apply H18. }\n          apply H4 in H19; clear H4 H9 H13 H15; unfold Rrelation, E in H19.\n          apply Axiom_SchemeP in H19; destruct H19; clear H4.\n          apply Property_Value in H16; auto; add ([x1,f[x1]] ∈ f) H14.\n          apply H in H14; rewrite H14 in H17; add (f[x1] ∈ f[x0]) H17.\n          generalize (not_bel_and f[x0] f[x1]); intros; contradiction. }\n        { rewrite H18 in H17; clear H9 H15 H16; destruct H11.\n          apply Property_Value in H11; auto; add ([x1,y] ∈ f) H11.\n          unfold Function in H; apply H in H11; rewrite H11 in H17.\n          generalize (notin_fix y); intros; contradiction. }\nQed.\n\nHint Resolve fin_iff_well : set.\n\n\n(* Some properties about finite *)\n\nLemma Finite_Subclass : forall (A B: Class),\n  Finite A -> B ⊂ A -> Finite B.\nProof.\n  intros.\n  apply fin_iff_well in H; destruct H as [r H], H.\n  apply fin_iff_well; exists r; split.\n  - unfold WellOrdered, Connect in H; destruct H.\n    unfold WellOrdered, Connect; split; intros.\n    + destruct H3; apply H; auto.\n    + destruct H3; apply H2; split; auto.\n      add (B ⊂ A) H3; apply sub_tran in H3; auto.\n  - unfold WellOrdered, Connect in H1; destruct H1.\n    unfold WellOrdered, Connect; split; intros.\n    + destruct H3; apply H1; auto.\n    + destruct H3; apply H2; split; auto.\n      add (B ⊂ A) H3; apply sub_tran in H3; auto.\nQed.\n\n\nLemma Finite_Single : forall z, Ensemble z -> Finite ([z]).\nProof.\n  intros.\n  apply fin_iff_well; exists E; split.\n  - unfold WellOrdered; split; intros.\n    + unfold Connect; intros; destruct H0; unfold Singleton in H0, H1.\n      apply Axiom_Scheme in H0; apply Axiom_Scheme in H1.\n      destruct H0, H1; double H.\n      apply bel_universe_set in H; apply bel_universe_set in H4; apply H2 in H.\n      apply H3 in H4; rewrite <- H4 in H; tauto.\n    + destruct H0; apply not_zero_exist_bel in H1; destruct H1; exists x.\n      unfold FirstMember; split; auto; intros; unfold Subclass in H0.\n      apply H0 in H1; apply H0 in H2; unfold Singleton in H1, H2; double H.\n      apply Axiom_Scheme in H1; apply Axiom_Scheme in H2; destruct H1, H2.\n      apply bel_universe_set in H; apply bel_universe_set in H3; apply H4 in H.\n      apply H5 in H3; rewrite <- H3 in H; rewrite H.\n      intro; unfold Rrelation in H6; unfold E in H6; apply Axiom_SchemeP in H6.\n      destruct H6; generalize (notin_fix y0); intros; contradiction.\n  - unfold WellOrdered; split; intros.\n    + unfold Connect; intros; destruct H0; unfold Singleton in H0, H1.\n      apply Axiom_Scheme in H0; apply Axiom_Scheme in H1; destruct H0, H1.\n      double H; apply bel_universe_set in H; apply bel_universe_set in H4.\n      apply H2 in H; apply H3 in H4; rewrite <- H4 in H; tauto.\n    + destruct H0; apply not_zero_exist_bel in H1; auto; destruct H1; exists x.\n      unfold FirstMember; split; auto; intros; unfold Subclass in H0.\n      apply H0 in H1; apply H0 in H2; unfold Singleton in H1, H2; double H.\n      apply Axiom_Scheme in H1; apply Axiom_Scheme in H2; destruct H1, H2.\n      apply bel_universe_set in H; apply bel_universe_set in H3; apply H4 in H.\n      apply H5 in H3; rewrite <- H3 in H; rewrite H.\n      intro; unfold Rrelation, Inverse in H6; apply Axiom_SchemeP in H6.\n      destruct H6; unfold E in H7; apply Axiom_SchemeP in H7.\n      destruct H7; generalize (notin_fix y0); intros; contradiction.\nQed.\n\n\n(* 168 Theorem  If x and y are finite so is x∪y. *)\n\nTheorem fin_union : forall x y,\n  Finite x /\\ Finite y -> Finite (x ∪ y).\nProof.\n  intros; destruct H.\n  apply fin_iff_well in H; apply fin_iff_well in H0.\n  destruct H as [r H], H0 as [s H0], H, H0; apply fin_iff_well.\n  exists (\\{\\ λ u v, (u∈x /\\ v∈x /\\ Rrelation u r v) \\/ (u∈(y~x) /\\\n  v∈(y~x) /\\ Rrelation u s v) \\/ (u∈x /\\ v∈(y~x)) \\}\\); split.\n  - clear H1 H2; unfold WellOrdered in H, H0; destruct H, H0.\n    unfold WellOrdered; split; intros.\n    + clear H1 H2; unfold Connect in H, H0; unfold Connect; intros.\n      destruct H1; apply bel_union in H1; apply bel_union in H2.\n      unfold Rrelation; destruct H1, H2.\n      * clear H0; assert (u ∈ x /\\ v ∈ x); auto; apply H in H0.\n        clear H; destruct H0 as [H | [H | H]]; try tauto.\n        { left; SplitEnsP. } { right; left; SplitEnsP. }\n      * clear H0; generalize (classic (v ∈ x)); intros; destruct H0.\n        { assert (u ∈ x /\\ v ∈ x); auto; apply H in H3.\n          clear H; destruct H3 as [H | [H | H]]; try tauto.\n          - left; SplitEnsP.\n          - right; left; SplitEnsP. }\n        { left; SplitEnsP; right; right; split; auto; apply bel_inter.\n          split; auto; unfold Complement; SplitEns. }\n      * clear H0; generalize (classic (u ∈ x)); intros; destruct H0.\n        { assert (u ∈ x /\\ v ∈ x); auto; apply H in H3.\n          clear H; destruct H3 as [H | [H | H]]; try tauto.\n          - left; SplitEnsP.\n          - right; left; SplitEnsP. }\n        { right; left; SplitEnsP.\n          right; right; split; auto; unfold Difference; apply bel_inter.\n          split; auto; unfold Complement; SplitEns. }\n      * generalize (classic (u∈x)) (classic (v∈x)); intros; destruct H3, H4.\n        { clear H0; assert (u ∈ x /\\ v ∈ x); auto; apply H in H0.\n          clear H; destruct H0 as [H | [H | H]]; try tauto.\n          - left; SplitEnsP.\n          - right; left; SplitEnsP. }\n        { left; SplitEnsP; right; right; split; auto; apply bel_inter.\n          split; auto; unfold Complement; SplitEns. }\n        { right; left; SplitEnsP; right; right; split; auto; apply bel_inter.\n          split; auto; unfold Complement; SplitEns. }\n        { clear H; assert (u ∈ y /\\ v ∈ y); auto; apply H0 in H.\n          clear H0; destruct H as [H | [H | H]]; try tauto.\n          - left; SplitEnsP; right; left; repeat split; auto.\n            + apply bel_inter; split; auto; SplitEns.\n            + apply bel_inter; split; auto; SplitEns.\n          - right; left; SplitEnsP.\n            right; left; unfold Difference; repeat split; auto.\n            + apply bel_inter; split; auto; SplitEns.\n            + apply bel_inter; split; auto; SplitEns. }\n    + generalize (classic (\\{ λ z, z ∈ y0 /\\ z ∈ x \\} = Φ)).\n      clear H H0; destruct H3; intros; destruct H3.\n      * assert (y0 ⊂ y).\n        { unfold Subclass; intros; double H4.\n          apply H in H5; apply bel_union in H5; destruct H5; auto.\n          generalize (not_bel_zero z); intros; elim H6; clear H6.\n          rewrite <- H3; apply Axiom_Scheme; repeat split; Ens. }\n        add (y0 ≠ Φ) H4; apply H2 in H4; clear H0 H1 H2.\n        destruct H4 as [z H0]; exists z; unfold FirstMember in H0.\n        destruct H0; unfold FirstMember; split; auto; intros.\n        double H2; apply H1 in H4; clear H1; intro; elim H4; clear H4.\n        unfold Rrelation in H1; apply Axiom_SchemeP in H1; destruct H1.\n        unfold Rrelation; destruct H4 as [H4|[H4|H4]]; try apply H4.\n        { destruct H4; clear H5; generalize (not_bel_zero y1); intros.\n          elim H5; rewrite <- H3; apply Axiom_Scheme; repeat split; Ens. }\n        { destruct H4; clear H5; generalize (not_bel_zero y1); intros.\n          elim H5; rewrite <- H3; apply Axiom_Scheme; repeat split; Ens. }\n      * assert (\\{λ z, z∈y0 /\\ z∈x\\} ⊂ x).\n        { unfold Subclass; intros; apply Axiom_Scheme in H4; apply H4. }\n        add (\\{λ z, z∈y0 /\\ z∈x\\} <> Φ) H4; apply H1 in H4; clear H1 H2.\n        destruct H4 as [z H1]; exists z; unfold FirstMember in H1.\n        destruct H1; apply Axiom_Scheme in H1; destruct H1, H4.\n        unfold FirstMember; split; auto; intros.\n        generalize (classic (y1∈x)); intros; destruct H7.\n        { assert (y1 ∈ \\{λ z, z∈y0 /\\ z∈x\\}).\n          { apply Axiom_Scheme; repeat split; Ens. }\n          apply H2 in H8; intro; elim H8; clear H2 H8.\n          unfold Rrelation in H9; apply Axiom_SchemeP in H9; destruct H9.\n          unfold Rrelation; destruct H8 as [H8|[H8|H8]]; try apply H8.\n          - destruct H8; clear H9; unfold Difference in H8.\n            apply Axiom_Scheme in H8; destruct H8, H9; unfold Complement in H10.\n            apply Axiom_Scheme in H10; destruct H10; contradiction.\n          - destruct H8; clear H8; unfold Difference in H9.\n            apply Axiom_Scheme in H9; destruct H9, H9; unfold Complement in H10.\n            apply Axiom_Scheme in H10; destruct H10; contradiction. }\n        { intro; unfold Rrelation in H8; apply Axiom_SchemeP in H8.\n          destruct H8, H9 as [H9|[H9|H9]], H9; try contradiction.\n          destruct H10; clear H8 H9 H11; unfold Difference in H10.\n          apply Axiom_Scheme in H10; destruct H10, H9; unfold Complement in H10.\n          apply Axiom_Scheme in H10; destruct H10; contradiction. }\n  - unfold WellOrdered; split; intros.\n    + clear H1 H2; unfold WellOrdered in H, H0; destruct H, H0.\n      clear H1 H2; unfold Connect in H, H0; unfold Connect; intros.\n      destruct H1; apply bel_union in H1; apply bel_union in H2.\n      unfold Rrelation; destruct H1, H2.\n      * clear H0; assert (u ∈ x /\\ v ∈ x); auto; apply H in H0.\n        clear H; destruct H0 as [H | [H | H]]; try tauto.\n        { right; left; unfold Inverse; SplitEnsP; SplitEnsP. }\n        { left; SplitEnsP; SplitEnsP. }\n      * clear H0; generalize (classic (v ∈ x)); intros; destruct H0.\n        { assert (u ∈ x /\\ v ∈ x); auto; apply H in H3.\n          clear H; destruct H3 as [H | [H | H]]; try tauto.\n          - right; left; SplitEnsP; SplitEnsP.\n          - left; SplitEnsP; SplitEnsP. }\n        { right; left; SplitEnsP; SplitEnsP.\n          right; right; split; auto; apply bel_inter.\n          split; auto; unfold Complement; SplitEns. }\n      * clear H0; generalize (classic (u ∈ x)); intros; destruct H0.\n        { assert (u ∈ x /\\ v ∈ x); auto; apply H in H3.\n          clear H; destruct H3 as [H | [H | H]]; try tauto.\n          - right; left; SplitEnsP; SplitEnsP.\n          - left; SplitEnsP; SplitEnsP. }\n        { left; SplitEnsP; SplitEnsP.\n          right; right; split; auto; unfold Difference; apply bel_inter.\n          split; auto; unfold Complement; SplitEns. }\n      * generalize (classic (u∈x)) (classic (v∈x)); intros; destruct H3, H4.\n        { clear H0; assert (u ∈ x /\\ v ∈ x); auto; apply H in H0.\n          clear H; destruct H0 as [H | [H | H]]; try tauto.\n          - right; left; SplitEnsP; SplitEnsP.\n          - left; SplitEnsP; SplitEnsP. }\n        { right; left; SplitEnsP; SplitEnsP.\n          right; right; split; auto; apply bel_inter.\n          split; auto; unfold Complement; SplitEns. }\n        { left; SplitEnsP; SplitEnsP.\n          right; right; split; auto; unfold Difference; apply bel_inter.\n          split; auto; unfold Complement; SplitEns. }\n        { clear H; assert (u ∈ y /\\ v ∈ y); auto; apply H0 in H.\n          clear H0; destruct H as [H | [H | H]]; try tauto.\n          - right; left; SplitEnsP; SplitEnsP.\n            right; left; unfold Difference; repeat split; auto.\n            + apply bel_inter; split; auto; SplitEns.\n            + apply bel_inter; split; auto; SplitEns.\n          - left; SplitEnsP; SplitEnsP; right; left; repeat split; auto.\n            + apply bel_inter; split; auto; SplitEns.\n            + apply bel_inter; split; auto; SplitEns. }\n    + clear H H0; unfold WellOrdered in H1, H2.\n      destruct H1, H2; clear H H1; destruct H3.\n      generalize (classic (\\{λ z, z∈y0 /\\ z∈(y~x)\\}=Φ)); intros; destruct H3.\n      * assert (y0 ⊂ x).\n        { unfold Subclass; intros; double H4.\n          apply H in H5; apply bel_union in H5; destruct H5; auto.\n          generalize (classic (z ∈ x)); intros; destruct H6; auto.\n          generalize (not_bel_zero z); intros; elim H7; clear H7.\n          rewrite <- H3; apply Axiom_Scheme; repeat split; Ens.\n          unfold Difference; apply bel_inter; split; auto.\n          unfold Complement; apply Axiom_Scheme; split; Ens. }\n        add (y0 ≠ Φ) H4; apply H0 in H4; clear H0 H1 H2.\n        destruct H4 as [z H0]; exists z; unfold FirstMember in H0.\n        destruct H0; unfold FirstMember; split; auto; intros.\n        double H2; apply H1 in H4; clear H1; intro; elim H4; clear H4.\n        unfold Rrelation in H1; apply Axiom_SchemeP in H1; destruct H1.\n        apply Axiom_SchemeP in H4; destruct H4 as [H5 H4]; clear H5.\n        unfold Rrelation, Inverse; apply Axiom_SchemeP; split; auto.\n        destruct H4 as [H4|[H4|H4]]; try apply H4.\n        { destruct H4; clear H5; generalize (not_bel_zero z); intros.\n          elim H5; rewrite <- H3; apply Axiom_Scheme; repeat split; Ens. }\n        { destruct H4; clear H4; generalize (not_bel_zero y1); intros.\n          elim H4; rewrite <- H3; apply Axiom_Scheme; repeat split; Ens. }\n      * assert (\\{λ z, z∈y0 /\\ z∈(y~x)\\} ⊂ y).\n        { unfold Subclass; intros; apply Axiom_Scheme in H4; destruct H4, H5.\n          unfold Difference in H6; apply bel_inter in H6; apply H6. }\n        add (\\{λ z, z∈y0 /\\ z∈(y~x)\\} <> Φ) H4; apply H2 in H4; clear H0 H2.\n        destruct H4 as [z H0]; exists z; unfold FirstMember in H0.\n        destruct H0; apply Axiom_Scheme in H0; destruct H0, H4.\n        unfold Difference in H5; apply bel_inter in H5; destruct H5.\n        unfold Complement in H6; apply Axiom_Scheme in H6; clear H0.\n        destruct H6; unfold FirstMember; split; auto; intros.\n        generalize (classic (y1∈x)); intros; destruct H8.\n        { intro; unfold Rrelation in H9; apply Axiom_SchemeP in H9; destruct H9.\n          apply Axiom_SchemeP in H10; destruct H10 as [H11 H10]; clear H11.\n          destruct H10 as [H10|[H10|H10]], H10; try contradiction.\n          destruct H11; clear H9 H10 H12; unfold Difference in H11.\n          apply Axiom_Scheme in H11; destruct H11, H10;unfold Complement in H11.\n          apply Axiom_Scheme in H11; destruct H11; contradiction. }\n        { assert (y1 ∈ \\{λ z, z ∈ y0 /\\ z ∈ (y ~ x)\\}).\n          { apply Axiom_Scheme; repeat split; Ens; apply H in H7.\n            apply bel_union in H7; destruct H7; try contradiction.\n            apply bel_inter; split; auto; apply Axiom_Scheme; split; Ens. }\n          apply H2 in H9; intro; elim H9; clear H2 H9.\n          unfold Rrelation in H10; apply Axiom_SchemeP in H10; destruct H10.\n          apply Axiom_SchemeP in H9; destruct H9 as [H10 H9]; clear H10.\n          unfold Rrelation, Inverse; SplitEnsP.\n          destruct H9 as [H9|[H9|H9]], H9; try contradiction; apply H10. }\nQed.\n\nHint Resolve fin_union : set.\n\n\n(* 169 Theorem  If x is finite and each member of x is finite, then ∪x is\n   finite. *)\n\nLemma mem_fix_bel_sing : forall x y, x ∈ y -> y = (y ~ [x] ∪ [x]).\nProof.\n  intros.\n  apply Axiom_Extent; split; intros.\n  - generalize (classic (z ∈ [x])); intros; destruct H1.\n    + apply bel_union; right; auto.\n    + apply bel_union; left; unfold Difference; apply bel_inter.\n      split; auto; unfold Complement; apply Axiom_Scheme; Ens.\n  - apply bel_union in H0; destruct H0.\n    + unfold Difference in H0; apply bel_inter in H0; apply H0.\n    + unfold Singleton in H0; apply Axiom_Scheme in H0; destruct H0.\n      rewrite H1; try apply bel_universe_set; Ens.\nQed.\n\nLemma eleU_union : forall x y, ∪(x ∪ y) = (∪x) ∪ (∪y).\nProof.\n  intros.\n  apply Axiom_Extent; split; intros.\n  - apply Axiom_Scheme in H; destruct H, H0, H0.\n    apply bel_union in H1; destruct H1.\n    + apply bel_union; left; apply Axiom_Scheme; Ens.\n    + apply bel_union; right; apply Axiom_Scheme; Ens.\n  - apply bel_union in H; destruct H.\n    + apply Axiom_Scheme in H; destruct H, H0, H0.\n      apply Axiom_Scheme; split; Ens; exists x0.\n      split; auto; apply bel_union; auto.\n    + apply Axiom_Scheme in H; destruct H, H0, H0.\n      apply Axiom_Scheme; split; auto; exists x0.\n      split; auto; apply bel_union; auto.\nQed.\n\nTheorem fin_eleU : forall (x: Class),\n  Finite x -> (forall z, z∈x -> Finite z) -> Finite (∪ x).\nProof.\n  intros; double H.\n  unfold Finite in H; apply Property_Finite in H1.\n  assert (\\{λ u, u∈W /\\ (forall y, P[y] = u /\\ Ensemble y /\\\n            (forall z, z∈y -> Finite z) -> Finite (∪ y)) \\} = W).\n  { apply math_ind.\n    - unfold Subclass; intros; apply Axiom_Scheme in H2; apply H2.\n    - apply Axiom_Scheme; generalize (zero_not_int x); intros; destruct H2.\n      clear H3; repeat split; Ens; intros; destruct H3, H4.\n      generalize (classic (y = Φ)); intros; destruct H6.\n      + rewrite H6 in *; rewrite zero_eleU_zero; unfold Finite; rewrite H3; auto.\n      + apply not_zero_exist_bel in H6; destruct H6; apply card_equiv in H1.\n        apply card_equiv in H4; apply equiv_com in H4; unfold Equivalent in H4.\n        destruct H4 as [f H4], H4, H4, H7; rewrite <- H7 in H6.\n        apply Property_Value in H6; auto; apply Property_ran in H6.\n        rewrite H9, H3 in H6; generalize (not_bel_zero f[x0]); contradiction.\n    - intros; apply Axiom_Scheme in H2; apply Axiom_Scheme.\n      destruct H2, H3; double H3.\n      apply int_succ in H5; repeat split; Ens; intros; destruct H6, H7.\n      AssE y; clear H7; double H9; unfold PlusOne in H6; apply card_equiv in H9.\n      unfold Equivalent in H9; destruct H9 as [f H9], H9, H9, H10.\n      assert (u ∈ P[y]).\n      { rewrite H6; apply bel_union; right; unfold Singleton.\n        apply Axiom_Scheme; split; Ens. }\n      rewrite <- H10 in H13; apply Property_Value in H13; auto.\n      apply Property_ran in H13; rewrite H12 in H13.\n      apply mem_fix_bel_sing in H13; rewrite H13; clear H13.\n      rewrite eleU_union; apply fin_union; split.\n      + apply H4; assert (Ensemble (y ~ [f[u]])).\n        { apply (sub_set y _); auto; unfold Subclass; intros.\n          unfold Difference in H13; apply bel_inter in H13; apply H13. }\n        repeat split; auto; intros.\n        * apply W_sub_C in H3; apply card_iff_eq in H3; clear H2; destruct H3.\n          rewrite <- H3 at 2; add (Ensemble u) H13; apply card_eq in H13.\n          apply H13; clear H13; apply equiv_com; unfold Equivalent.\n          exists (f|(P[y]~[u])).\n          { repeat split; unfold Relation; intros.\n            - unfold Restriction in H13; apply bel_inter in H13.\n              destruct H13; PP H14 a b; Ens.\n            - unfold Restriction in H13; destruct H13; apply bel_inter in H13.\n              apply bel_inter in H14; destruct H13, H14; unfold Function in H9.\n              apply H9 with (x:= x0); split; auto.\n            - PP H13 a b; Ens.\n            - unfold Inverse, Restriction in H13; destruct H13.\n              apply Axiom_SchemeP in H13; apply Axiom_SchemeP in H14.\n              destruct H13, H14.\n              apply bel_inter in H15; apply bel_inter in H16; destruct H15, H16.\n              clear H17 H18; unfold Function in H11; apply H11 with (x:= x0).\n              split; apply Axiom_SchemeP; Ens.\n            - apply Axiom_Extent; split; intros.\n              + unfold Domain in H13; apply Axiom_Scheme in H13.\n                destruct H13, H14.\n                unfold Restriction in H14; apply bel_inter in H14; destruct H14.\n                clear H14; unfold Cartesian in H15; apply Axiom_SchemeP in H15.\n                destruct H15, H15; clear H16; unfold Difference in H15.\n                apply bel_inter in H15; destruct H15; rewrite H6 in H15.\n                apply bel_union in H15; destruct H15; auto.\n                unfold Complement in H16; apply Axiom_Scheme in H16.\n                destruct H16; contradiction.\n              + unfold Domain; apply Axiom_Scheme; split; Ens; exists f[z].\n                unfold Restriction; apply bel_inter.\n                assert (z ∈ dom(f)). { rewrite H10, H6; apply bel_union; tauto. }\n                apply Property_Value in H14; auto; split; auto.\n                unfold Cartesian; apply Axiom_SchemeP; split; Ens; double H14.\n                apply Property_ran in H15; split; try apply bel_universe_set; Ens.\n                clear H15; apply Property_dom in H14; unfold Difference.\n                apply bel_inter; rewrite H10 in H14; split; auto.\n                unfold Complement; apply Axiom_Scheme; split; Ens; intro.\n                apply Axiom_Scheme in H15; destruct H15.\n                rewrite H16 in H13; try apply bel_universe_set; Ens.\n                generalize (notin_fix u); intros; contradiction.\n            - apply Axiom_Extent; split; intros.\n              + unfold Range in H13; apply Axiom_Scheme in H13.\n                destruct H13, H14.\n                unfold Restriction in H14; apply bel_inter in H14; destruct H14.\n                unfold Cartesian in H15; apply Axiom_SchemeP in H15.\n                destruct H15.\n                clear H15; destruct H16; clear H16; unfold Difference in H15.\n                apply bel_inter in H15; destruct H15; double H15.\n                rewrite <- H10 in H15; rewrite H6 in H17.\n                apply bel_union in H17; destruct H17.\n                * clear H17; apply Property_Value in H15; auto.\n                  add ([x0,z] ∈ f) H15; apply H9 in H15; rewrite <- H15 in *.\n                  clear H15; unfold Difference; apply bel_inter; double H14.\n                  apply Property_ran in H15; rewrite H12 in H15; split; auto.\n                  unfold Complement; apply Axiom_Scheme; split; Ens; intro.\n                  apply Axiom_Scheme in H17; destruct H17; assert (u ∈ dom(f)).\n                  { rewrite H10, H6; apply bel_union; right.\n                    unfold Singleton; apply Axiom_Scheme; Ens. }\n                  apply Property_Value in H19; auto; AssE [u,f[u]].\n                  apply ord_set in H20; destruct H20.\n                  rewrite H18 in H14; try apply bel_universe_set; Ens.\n                  unfold Complement in H16; apply Axiom_Scheme in H16.\n                  destruct H16; elim H22; unfold Singleton.\n                  apply Axiom_Scheme; split; Ens; intros.\n                  apply H11 with (x:= f[u]); unfold Inverse.\n                  split; apply Axiom_SchemeP; split; try apply ord_set; auto.\n                * unfold Complement in H16; apply Axiom_Scheme in H16.\n                  destruct H16; contradiction.\n              + unfold Difference in H13; apply bel_inter in H13; destruct H13.\n                rewrite <- H12 in H13; apply Axiom_Scheme in H13.\n                destruct H13, H15.\n                unfold Range; apply Axiom_Scheme; split; Ens; exists x0.\n                unfold Restriction; apply bel_inter; split; auto.\n                unfold Cartesian; apply Axiom_SchemeP; split; Ens.\n                split; try apply bel_universe_set; Ens; apply bel_inter; double H15.\n                apply Property_dom in H16; rewrite <- H10; split; auto.\n                unfold Complement; apply Axiom_Scheme; split; Ens; intro.\n                apply Axiom_Scheme in H17; destruct H17.\n                rewrite H18 in *; try apply bel_universe_set; Ens.\n                apply Property_Value in H16; auto; clear H17 H18.\n                add ([u,z] ∈ f) H16; apply H9 in H16; rewrite H16 in H14.\n                unfold Complement in H14; apply Axiom_Scheme in H14; clear H13.\n                destruct H14; elim H14; apply Axiom_Scheme; Ens. }\n        * unfold Difference in H14; apply bel_inter in H14; destruct H14.\n          apply H8; auto.\n      + assert (f[u] ∈ y).\n        { assert (u ∈ dom(f)).\n          { rewrite H10, H6; apply bel_union; right; apply Axiom_Scheme; Ens. }\n          apply Property_Value in H13; auto; apply Property_ran in H13.\n          rewrite H12 in H13; auto. }\n        AssE f[u]; apply sing_ele in H14; destruct H14; rewrite H15.\n        clear H14 H15; apply H8; auto. }\n  rewrite <- H2 in H; clear H2; apply Axiom_Scheme in H; destruct H, H2.\n  apply H3; repeat split; auto.\nQed.\n\nHint Resolve fin_eleU : set.\n\n\n(* 170 Theorem  If x and y are finite so is x×y. *)\n\nTheorem fin_cart : forall x y,\n  Finite x /\\ Finite y -> Finite (x × y).\nProof.\n  intros; destruct H.\n  generalize (classic (y = Φ)); intros; destruct H1.\n  - rewrite H1 in *; clear H1.\n    assert ((x × Φ) = Φ).\n    { apply Axiom_Extent; split; intros.\n      - PP H1 a b; apply Axiom_SchemeP in H2; destruct H2, H3.\n        generalize (not_bel_zero b); intros; contradiction.\n      - generalize (not_bel_zero z); intros; contradiction. }\n    rewrite H1; auto.\n  - assert (∪ \\{ λ u, exists v, v∈x /\\ u = ([v] × y) \\} = x × y).\n    { clear H1; apply Axiom_Extent; split; intros.\n      - unfold Element_U in H1; apply Axiom_Scheme in H1; destruct H1, H2, H2.\n        apply Axiom_Scheme in H3; destruct H3, H4, H4; unfold Cartesian.\n        rewrite H5 in H2; PP H2 a b; apply Axiom_SchemeP in H6; destruct H6, H7.\n        apply Axiom_SchemeP; repeat split; auto; unfold Singleton in H7.\n        apply Axiom_Scheme in H7; destruct H7.\n        rewrite H9; try apply bel_universe_set; Ens.\n      - unfold Cartesian in H1; PP H1 a b; apply Axiom_SchemeP in H2.\n        destruct H2, H3; apply Axiom_Scheme.\n        split; auto; exists ([a] × y); split.\n        + unfold Cartesian; apply Axiom_SchemeP; repeat split; auto.\n          unfold Singleton; apply Axiom_Scheme; split; Ens.\n        + apply Axiom_Scheme; split; Ens; apply set_sing_cart; split; Ens.\n          apply Property_Finite; auto. }\n    rewrite <- H2; clear H2; apply fin_eleU; intros.\n    + assert (x ≈ \\{ λ u, exists v, v∈x /\\ u = ([v] × y) \\}).\n      { unfold Equivalent; exists (\\{\\ λ u v, u∈x /\\ v = ([u] × y) \\}\\).\n        repeat split; intros; try (unfold Relation; intros; PP H2 a b; Ens).\n        - destruct H2; apply Axiom_SchemeP in H2; apply Axiom_SchemeP in H3.\n          destruct H2, H3, H4, H5; rewrite H6, H7; auto.\n        - destruct H2; apply Axiom_SchemeP in H2; apply Axiom_SchemeP in H3.\n          destruct H2, H3; clear H2 H3; apply Axiom_SchemeP in H4.\n          apply Axiom_SchemeP in H5; destruct H4, H5, H3, H5; rewrite H7 in H6.\n          clear H7; generalize (classic (y0 = z)); intros; destruct H7; auto.\n          elim H7; clear H7; apply not_zero_exist_bel in H1; destruct H1.\n          assert ([y0,x1] ∈ ([z] × y)).\n          { rewrite H6; unfold Cartesian; apply Axiom_SchemeP.\n            repeat split; try apply ord_set; Ens.\n            unfold Singleton; apply Axiom_Scheme; split; Ens. }\n          unfold Cartesian in H7; apply Axiom_SchemeP in H7; destruct H7, H8.\n          unfold Singleton in H8; apply Axiom_Scheme in H8; destruct H8.\n          apply H10; apply bel_universe_set; Ens.\n        - apply Axiom_Extent; split; intros.\n          + unfold Domain in H2; apply Axiom_Scheme in H2; destruct H2, H3.\n            apply Axiom_SchemeP in H3; apply H3.\n          + unfold Domain; apply Axiom_Scheme; split; Ens.\n            exists ([z] × y); apply Axiom_SchemeP; repeat split; auto.\n            apply ord_set; split; Ens; apply Property_Finite in H0.\n            apply set_sing_cart; split; Ens.\n        - apply Axiom_Extent; split; intros.\n          + unfold Range in H2; apply Axiom_Scheme in H2; destruct H2, H3.\n            apply Axiom_SchemeP in H3; destruct H3, H4.\n            apply Axiom_Scheme; split; Ens.\n          + apply Axiom_Scheme in H2; destruct H2, H3, H3.\n            unfold Range; apply Axiom_Scheme; split; auto; exists x0.\n            apply Axiom_SchemeP; repeat split; try apply ord_set; Ens. }\n      assert (Ensemble x /\\ Ensemble \\{λ u, exists v, v∈x/\\u=([v]×y)\\}).\n      { apply Property_Finite in H; apply Property_Finite in H0; split; auto.\n        assert (Ensemble pow(x × y)).\n        { apply pow_set; auto; apply set_cart; split; auto. }\n        apply (sub_set pow(x × y) _); auto; unfold Subclass; intros.\n        apply Axiom_Scheme in H4; destruct H4, H5, H5; rewrite H6 in *.\n        clear H6; unfold PowerClass; apply Axiom_Scheme; split; auto.\n        unfold Subclass; intros.\n        PP H6 a b; apply Axiom_SchemeP in H7; destruct H7, H8.\n        apply Axiom_SchemeP.\n        repeat split; auto; unfold Singleton in H8; apply Axiom_Scheme in H8.\n        destruct H8; rewrite H10; try apply bel_universe_set; Ens. }\n      apply card_eq in H3; apply H3 in H2; clear H3.\n      unfold Finite; unfold Finite in H; rewrite <- H2; auto.\n    + apply Axiom_Scheme in H2; destruct H2, H3, H3; rewrite H4 in *; clear H4.\n      assert (y ≈ ([x0] × y)).\n      { unfold Equivalent; exists (\\{\\ λ u v, u∈y /\\ v = [x0,u] \\}\\).\n        repeat split; intros; try (unfold Relation; intros; PP H4 a b; Ens).\n        - destruct H4; apply Axiom_SchemeP in H4; apply Axiom_SchemeP in H5.\n          destruct H4, H5, H6, H7; rewrite H8, H9; auto.\n        - destruct H4; apply Axiom_SchemeP in H4; apply Axiom_SchemeP in H5.\n          destruct H4, H5; clear H4 H5; apply Axiom_SchemeP in H6.\n          apply Axiom_SchemeP in H7; destruct H6, H7, H5, H7; rewrite H9 in H8.\n          apply ord_eq in H8; destruct H8; Ens.\n        - apply Axiom_Extent; split; intros.\n          + unfold Domain in H4; apply Axiom_Scheme in H4; destruct H4, H5.\n            apply Axiom_SchemeP in H5; apply H5.\n          + unfold Domain; apply Axiom_Scheme; split; Ens.\n            exists [x0,z0]; apply Axiom_SchemeP; repeat split; auto.\n            apply ord_set; split; Ens; apply ord_set; Ens.\n        - apply Axiom_Extent; split; intros.\n          + unfold Range in H4; apply Axiom_Scheme in H4; destruct H4, H5.\n            apply Axiom_SchemeP in H5; destruct H5, H6; rewrite H7 in *.\n            clear H7; apply Axiom_SchemeP; repeat split; auto; unfold Singleton.\n            apply Axiom_Scheme; split; Ens.\n          + PP H4 a b; apply Axiom_SchemeP in H5; destruct H5, H6.\n            unfold Range; apply Axiom_Scheme; split; auto; exists b.\n            apply Axiom_SchemeP; repeat split; try apply ord_set; Ens.\n            unfold Singleton in H6; apply Axiom_Scheme in H6; destruct H6.\n            rewrite H8; try apply bel_universe_set; Ens. }\n      assert (Ensemble y /\\ Ensemble ([x0] × y)).\n      { apply Property_Finite in H; apply Property_Finite in H0; Ens. }\n      apply card_eq in H5; apply H5 in H4; clear H5.\n      unfold Finite; unfold Finite in H0; rewrite <- H4; auto.\nQed.\n\nHint Resolve fin_cart : set.\n\n\n(* 171 Theorem  If x is finite so is pow(x). *)\n\nLemma lem_fin_pow : forall x y,\n  y∈x -> pow(x) = pow(x~[y]) ∪ (\\{λ z, z ⊂ x /\\ y ∈ z\\}).\nProof.\n  intros; unfold PowerClass; apply Axiom_Extent.\n  split; intros; apply Axiom_Scheme in H0; destruct H0;\n  apply Axiom_Scheme; split; auto.\n  - generalize (classic (y ∈ z)); intros; destruct H2.\n    + right; apply Axiom_Scheme; split; auto.\n    + left; apply Axiom_Scheme; split; auto; unfold Subclass; intros; double H3.\n      unfold Difference; apply bel_inter; apply H1 in H4; split; auto.\n      unfold Complement; apply Axiom_Scheme; split; Ens; intro.\n      unfold Singleton in H5; apply Axiom_Scheme in H5; destruct H5.\n      rewrite H6 in H3; try contradiction; apply bel_universe_set; Ens.\n  - destruct H1; apply Axiom_Scheme in H1; try apply H1; clear H0; destruct H1.\n    unfold Subclass; intros; apply H1 in H2; unfold Difference in H2.\n    apply bel_inter in H2; apply H2.\nQed.\n\nTheorem fin_pow : forall (x: Class),\n  Finite x -> Finite pow(x).\nProof.\n  intros; double H.\n  unfold Finite in H; apply Property_Finite in H0.\n  assert (\\{λ u, u∈W /\\ (forall y, P[y] = u /\\ Ensemble y -> Finite pow(y))\\}\n            = W).\n  { apply math_ind.\n    - unfold Subclass; intros; apply Axiom_Scheme in H1; apply H1.\n    - apply Axiom_Scheme; generalize (zero_not_int x); intros; destruct H1.\n      clear H2; repeat split; Ens; intros; destruct H2; AssE y; clear H3.\n      generalize (classic (y = Φ)); intros; destruct H3.\n      + assert (pow(Φ) = [Φ]).\n        { unfold PowerClass, Singleton; apply Axiom_Extent.\n          split; intros; apply Axiom_Scheme in H5;\n          destruct H5; apply Axiom_Scheme.\n          - split; auto; intros; add (Φ ⊂ z) H6; try apply zero_sub.\n            apply sub_eq in H6; auto.\n          - split; auto; rewrite H6; try apply bel_universe_set; Ens.\n            unfold Subclass; intros; auto. }\n        rewrite H3 in *; rewrite H5; apply Finite_Single; Ens.\n      + apply not_zero_exist_bel in H3; destruct H3; apply card_equiv in H4.\n        apply equiv_com in H4; unfold Equivalent in H4.\n        destruct H4 as [f H4], H4, H4, H5; rewrite <- H5 in H3.\n        apply Property_Value in H3; auto; apply Property_ran in H3.\n        rewrite H7, H2 in H3; generalize (not_bel_zero f[x0]); contradiction.\n    - intros; apply Axiom_Scheme in H1; apply Axiom_Scheme.\n      destruct H1, H2; double H2.\n      apply int_succ in H4; repeat split; Ens; intros; destruct H5.\n      AssE y; clear H6; double H7; unfold PlusOne in H5; apply card_equiv in H7.\n      unfold Equivalent in H7; destruct H7 as [f H7], H7, H7, H8.\n      assert (u ∈ P[y]).\n      { rewrite H5; apply bel_union; right; unfold Singleton.\n        apply Axiom_Scheme; split; Ens. }\n      double H11; rewrite <- H8 in H12; apply Property_Value in H12; auto.\n      apply Property_ran in H12; rewrite H10 in H12; apply lem_fin_pow in H12.\n      rewrite H12; clear H12; apply fin_union.\n      assert (Finite pow(y ~ [f[u]])).\n      { apply H3; assert (Ensemble (y ~ [f[u]])).\n        { apply (sub_set y _); auto; unfold Subclass; intros.\n          unfold Difference in H12; apply bel_inter in H12; apply H12. }\n        repeat split; auto; intros; apply W_sub_C in H2.\n        apply card_iff_eq in H2; clear H1; destruct H2.\n        rewrite <- H2 at 2; add (Ensemble u) H12; apply card_eq in H12.\n        apply H12; clear H12; apply equiv_com; unfold Equivalent.\n        exists (f|(P[y]~[u])).\n        { repeat split; unfold Relation; intros.\n          - unfold Restriction in H12; apply bel_inter in H12.\n            destruct H12; PP H13 a b; Ens.\n          - unfold Restriction in H12; destruct H12; apply bel_inter in H12.\n            apply bel_inter in H13; destruct H12, H13; unfold Function in H7.\n            apply H7 with (x:= x0); split; auto.\n          - PP H12 a b; Ens.\n          - unfold Inverse, Restriction in H12; destruct H12.\n            apply Axiom_SchemeP in H12; apply Axiom_SchemeP in H13.\n            destruct H12, H13.\n            apply bel_inter in H14; apply bel_inter in H15; destruct H14, H15.\n            clear H16 H17; unfold Function in H9; apply H9 with (x:= x0).\n            split; apply Axiom_SchemeP; Ens.\n          - apply Axiom_Extent; split; intros.\n            + unfold Domain in H12; apply Axiom_Scheme in H12.\n              destruct H12, H13.\n              unfold Restriction in H13; apply bel_inter in H13; destruct H13.\n              clear H13; unfold Cartesian in H14; apply Axiom_SchemeP in H14.\n              destruct H14, H14; clear H15; unfold Difference in H14.\n              apply bel_inter in H14; destruct H14; rewrite H5 in H14.\n              apply bel_union in H14; destruct H14; auto.\n              apply Axiom_Scheme in H15; destruct H15; contradiction.\n            + unfold Domain; apply Axiom_Scheme; split; Ens; exists f[z].\n              unfold Restriction; apply bel_inter.\n              assert (z ∈ dom(f)). { rewrite H8, H5; apply bel_union; tauto. }\n              apply Property_Value in H13; auto; split; auto.\n              unfold Cartesian; apply Axiom_SchemeP; split; Ens; double H13.\n              apply Property_ran in H14; split; try apply bel_universe_set; Ens.\n              clear H14; apply Property_dom in H13; unfold Difference.\n              apply bel_inter; rewrite H8 in H13; split; auto.\n              unfold Complement; apply Axiom_Scheme; split; Ens; intro.\n              apply Axiom_Scheme in H14; destruct H14.\n              rewrite H15 in H12; try apply bel_universe_set; Ens.\n              generalize (notin_fix u); intros; contradiction.\n          - apply Axiom_Extent; split; intros.\n            + unfold Range in H12; apply Axiom_Scheme in H12; destruct H12, H13.\n              unfold Restriction in H13; apply bel_inter in H13; destruct H13.\n              unfold Cartesian in H14; apply Axiom_SchemeP in H14; destruct H14.\n              clear H14; destruct H15; clear H15; unfold Difference in H14.\n              apply bel_inter in H14; destruct H14; double H14.\n              rewrite <- H8 in H14; rewrite H5 in H16.\n              apply bel_union in H16; destruct H16.\n              * clear H16; apply Property_Value in H14; auto.\n                add ([x0,z] ∈ f) H14; apply H7 in H14; rewrite <- H14 in *.\n                clear H14; unfold Difference; apply bel_inter; double H13.\n                apply Property_ran in H14; rewrite H10 in H14; split; auto.\n                unfold Complement; apply Axiom_Scheme; split; Ens; intro.\n                apply Axiom_Scheme in H16; destruct H16; assert (u ∈ dom(f)).\n                { rewrite H8, H5; apply bel_union; right.\n                  unfold Singleton; apply Axiom_Scheme; Ens. }\n                apply Property_Value in H18; auto; AssE [u,f[u]].\n                apply ord_set in H19; destruct H19.\n                rewrite H17 in H13; try apply bel_universe_set; Ens.\n                unfold Complement in H15; apply Axiom_Scheme in H15.\n                destruct H15.\n                elim H21; unfold Singleton; apply Axiom_Scheme.\n                split; Ens; intros.\n                apply H9 with (x:= f[u]); unfold Inverse.\n                split; apply Axiom_SchemeP; split; try apply ord_set; auto.\n              * unfold Complement in H15; apply Axiom_Scheme in H15.\n                destruct H15; contradiction.\n            + unfold Difference in H12; apply bel_inter in H12; destruct H12.\n              rewrite <- H10 in H12; apply Axiom_Scheme in H12.\n              destruct H12, H14.\n              unfold Range; apply Axiom_Scheme; split; Ens; exists x0.\n              unfold Restriction; apply bel_inter; split; auto.\n              unfold Cartesian; apply Axiom_SchemeP; split; Ens.\n              split; try apply bel_universe_set; Ens; apply bel_inter; double H14.\n              apply Property_dom in H15; rewrite <- H8; split; Ens.\n              unfold Complement; apply Axiom_Scheme; split; Ens; intro.\n              apply Axiom_Scheme in H16; destruct H16.\n              rewrite H17 in *; try apply bel_universe_set; Ens.\n              apply Property_Value in H15; auto; clear H16 H17.\n              add ([u,z] ∈ f) H15; apply H7 in H15; rewrite H15 in H13.\n              unfold Complement in H13; apply Axiom_Scheme in H13; clear H12.\n              destruct H13; elim H13; apply Axiom_Scheme; Ens. } }\n      split; auto.\n      assert (pow(y ~ [f[u]]) ≈ \\{λ z, z ⊂ y /\\ f[u] ∈ z\\}).\n      { unfold Equivalent.\n        exists (\\{\\ λ v w, v ∈ pow(y~[f[u]]) /\\ w = v ∪ [f[u]] \\}\\).\n        repeat split; unfold Relation; intros; try PP H13 a b; Ens.\n        - destruct H13; apply Axiom_SchemeP in H13; apply Axiom_SchemeP in H14.\n          destruct H13, H14, H15, H16; rewrite H17, H18; auto.\n        - destruct H13; apply Axiom_SchemeP in H13; apply Axiom_SchemeP in H14.\n          destruct H13, H14; clear H13 H14; apply Axiom_SchemeP in H15.\n          apply Axiom_SchemeP in H16; destruct H15, H16, H14, H16.\n          rewrite H18 in H17; clear H13 H15 H18; unfold PowerClass in H14, H16.\n          apply Axiom_Scheme in H14; apply Axiom_Scheme in H16.\n          destruct H14, H16; apply Axiom_Extent; split; intros.\n          + assert (z0 ∈ (y0 ∪ [f[u]])). { apply bel_union; tauto. }\n            rewrite <- H17 in H19; apply bel_union in H19; destruct H19; auto.\n            apply H14 in H18; unfold Difference in H18; apply bel_inter in H18.\n            destruct H18; unfold Complement in H20; apply Axiom_Scheme in H20.\n            destruct H20; contradiction.\n          + assert (z0 ∈ (z ∪ [f[u]])). { apply bel_union; tauto. }\n            rewrite H17 in H19; apply bel_union in H19; destruct H19; auto.\n            apply H16 in H18; unfold Difference in H18; apply bel_inter in H18.\n            destruct H18; unfold Complement in H20; apply Axiom_Scheme in H20.\n            destruct H20; contradiction.\n        - unfold Domain; apply Axiom_Extent; split; intros.\n          + apply Axiom_Scheme in H13; destruct H13, H14.\n            apply Axiom_SchemeP in H14; apply H14.\n          + apply Axiom_Scheme; split; Ens; exists (z ∪ [f[u]]).\n            apply Axiom_SchemeP; repeat split; auto; apply ord_set.\n            split; Ens; apply Axiom_Union; split; Ens.\n            rewrite <- H8 in H11; apply Property_Value in H11; auto.\n            apply Property_ran in H11; AssE f[u]; apply sing_set; auto.\n        - unfold Range; apply Axiom_Extent; split; intros.\n          + apply Axiom_Scheme in H13; destruct H13, H14.\n            apply Axiom_SchemeP in H14.\n            destruct H14, H15; apply Axiom_Scheme; split; auto; rewrite H16.\n            clear H16; unfold PowerClass in H15; apply Axiom_Scheme in H15.\n            destruct H15; rewrite <- H8 in H11.\n            apply Property_Value in H11; auto; apply Property_ran in H11.\n            rewrite H10 in H11; split.\n            * unfold Subclass; intros; apply bel_union in H17; destruct H17.\n              { apply H16 in H17; apply bel_inter in H17; apply H17. }\n              { apply Axiom_Scheme in H17; destruct H17.\n                rewrite H18; try apply bel_universe_set; Ens. }\n            * apply bel_union; right; apply Axiom_Scheme; split; Ens.\n          + apply Axiom_Scheme in H13; destruct H13, H14; apply Axiom_Scheme.\n            split; auto; exists (z~[f[u]]); apply Axiom_SchemeP.\n            assert (Ensemble (z ~ [f[u]])).\n            { apply sub_set with (x:= z); auto; unfold Subclass.\n              intros; apply Axiom_Scheme in H16; apply H16. }\n            repeat split.\n            * apply ord_set; split; auto.\n            * unfold PowerClass; apply Axiom_Scheme; split; auto.\n              unfold Subclass; intros; apply Axiom_Scheme in H17.\n              destruct H17, H18; apply bel_inter; split; auto.\n            * apply Axiom_Extent; split; intros.\n              { generalize (classic (z0=f[u])); intros.\n                apply bel_union; destruct H18.\n                - right; apply Axiom_Scheme; split; Ens.\n                - left; unfold Difference; apply bel_inter; split; auto.\n                  apply Axiom_Scheme; split; Ens; intro.\n                  apply Axiom_Scheme in H19.\n                  destruct H19; rewrite H20 in H18; try tauto.\n                  apply bel_universe_set; Ens. }\n              { apply bel_union in H17; destruct H17.\n                - unfold Difference in H17; apply bel_inter in H17; apply H17.\n                - unfold Singleton; apply Axiom_Scheme in H17; destruct H17.\n                  rewrite H18; auto; apply bel_universe_set; Ens. } }\n      double H12; apply Property_Finite in H14; unfold Finite in H12.\n      unfold Finite; apply card_eq in H13; try rewrite <- H13; auto.\n      split; auto; clear H13 H15; apply pow_set in H6; auto.\n      apply sub_set with (x:= pow(y)); auto; unfold Subclass at 1; intros.\n      apply Axiom_Scheme in H13; destruct H13, H14, H15; unfold PowerClass.\n      apply Axiom_Scheme; split; auto. }\n  rewrite <- H1 in H; clear H1; apply Axiom_Scheme in H; destruct H, H1.\n  apply H2; split; auto.\nQed.\n\nHint Resolve fin_pow : set.\n\n\n(* 172 Theorem  If x is finite, y ⊂ x and P[y] = P[x], then x = y. *)\n\nTheorem fin_card_eq : forall x y,\n  Finite x -> y ⊂ x -> P[y] = P[x] -> x = y.\nProof.\n  intros.\n  double H; apply Property_Finite in H2; symmetry.\n  double H; unfold Finite in H3; unfold W in H3; apply Axiom_Scheme in H3.\n  destruct H3; unfold NInteger in H4; destruct H4; unfold WellOrdered in H5.\n  double H2; apply card_equiv in H6; apply equiv_com in H6.\n  unfold Equivalent in H6; destruct H6 as [f H6], H6, H6, H7.\n  generalize (classic (y = x)); intros; destruct H10; auto.\n  assert (y ⊊ x). { unfold ProperSubclass; split; auto. }\n  apply Property_ProperSubclass' in H11; destruct H11 as [z H11], H11.\n  generalize (classic (P[x] = Φ)); intros; destruct H13.\n  - rewrite <- H7 in H11; apply Property_Value in H11; auto.\n    apply Property_ran in H11; rewrite H9, H13 in H11.\n    generalize (not_bel_zero f[z]); intros; contradiction.\n  - assert (P[x] ⊂ P [x] /\\ P[x] ≠ Φ). { split; unfold Subclass; Ens. }\n    apply H5 in H14; clear H5 H13; destruct H14 as [u H5].\n    assert (P[x] ∈ R /\\ LastMember u E P[x]).\n    { split; auto; unfold R; apply Axiom_Scheme; split; auto. }\n    apply ordnum_plus_eq in H13; unfold FirstMember in H5; destruct H5; clear H14.\n    assert ((x ~ [z]) ≈ u).\n    { rewrite <- H9 in H5; apply Axiom_Scheme in H5; destruct H5; clear H5.\n      destruct H14; rewrite <- H7 in H11; apply Property_Value in H11; auto.\n      generalize (classic (z = x0)); intros; destruct H14.\n      - rewrite H14; unfold Equivalent; exists (f | (x ~ [x0])).\n        repeat split; unfold Relation; intros.\n        + apply bel_inter in H15; destruct H15; PP H16 a b; Ens.\n        + unfold Restriction in H15; destruct H15.\n          apply bel_inter in H15; apply bel_inter in H16.\n          destruct H15, H16; apply H6 with (x:= x1); auto.\n        + PP H15 a b; Ens.\n        + unfold Inverse, Restriction in H15; destruct H15.\n          apply Axiom_SchemeP in H15; apply Axiom_SchemeP in H16; destruct H15, H16.\n          apply bel_inter in H17; apply bel_inter in H18; destruct H17, H18.\n          apply H8 with (x:= x1); unfold Inverse; split; apply Axiom_SchemeP; Ens.\n        + apply Axiom_Extent; split; intros.\n          * unfold Domain in H15; apply Axiom_Scheme in H15; destruct H15, H16.\n            unfold Restriction in H16; apply bel_inter in H16; destruct H16.\n            unfold Cartesian in H17; apply Axiom_SchemeP in H17; apply H17.\n          * unfold Domain; apply Axiom_Scheme; split; Ens; exists f[z0]; double H15.\n            unfold Difference in H16; apply bel_inter in H16; destruct H16.\n            clear H17; rewrite <- H7 in H16; apply Property_Value in H16; auto.\n            unfold Restriction; apply bel_inter; split; auto; unfold Cartesian.\n            apply Axiom_SchemeP; repeat split; Ens; apply Property_ran in H16.\n            apply bel_universe_set; Ens.\n        + apply Axiom_Extent; split; intros.\n          * unfold Range in H15; apply Axiom_Scheme in H15; destruct H15, H16.\n            apply bel_inter in H16; destruct H16; double H16.\n            apply Property_ran in H18; rewrite H9, H13 in H18.\n            unfold PlusOne in H18; apply bel_union in H18; destruct H18; auto.\n            apply Axiom_Scheme in H18; destruct H18; unfold Cartesian in H17.\n            apply Axiom_SchemeP in H17; destruct H17, H20; clear H17 H18 H21.\n            unfold Difference in H20; apply bel_inter in H20; destruct H20.\n            clear H17; unfold Complement in H18; apply Axiom_Scheme in H18.\n            destruct H18; elim H18; clear H18; unfold Singleton; apply Axiom_Scheme.\n            split; auto; intros; clear H17 H18; apply H8 with (x:= u).\n            AssE [x0,u]; apply ord_set in H17; destruct H17.\n            rewrite H19 in H16; try apply bel_universe_set; Ens; clear H19.\n            split; apply Axiom_SchemeP; split; try apply ord_set; auto.\n            apply Property_dom in H16; split; Ens.\n          * unfold Range; apply Axiom_Scheme; split; Ens; assert (z0 ∈ ran(f)).\n            { rewrite H9, H13; unfold PlusOne; apply bel_union; tauto. }\n            unfold Range in H16; apply Axiom_Scheme in H16; destruct H16, H17.\n            exists x1; unfold Restriction; apply bel_inter; split; auto.\n            unfold Cartesian; apply Axiom_SchemeP; split; Ens; double H17.\n            split; try apply bel_universe_set; auto; unfold Difference.\n            apply Property_dom in H18; rewrite H7 in H18; apply bel_inter.\n            split; auto; unfold Complement; apply Axiom_Scheme; split; Ens; intro.\n            unfold Singleton in H19; apply Axiom_Scheme in H19; destruct H19.\n            double H5; apply Property_dom in H21; clear H18 H19.\n            rewrite H20 in H17; try apply bel_universe_set; Ens; clear H20 H21.\n            add ([x0,z0] ∈ f) H5; apply H6 in H5; clear H17.\n            rewrite H5 in H15; generalize (notin_fix z0); contradiction.\n      - unfold Equivalent; exists (\\{\\ λ v w, v ∈ (x ~ [z]) /\\\n        (v = x0 -> w = f[z]) /\\ (v <> x0 -> [v,w] ∈ f) \\}\\).\n        repeat split; unfold Relation; intros; try PP H15 a b; Ens.\n        + destruct H15; apply Axiom_SchemeP in H15; apply Axiom_SchemeP in H16.\n          destruct H15, H16, H17, H18; generalize (classic (x1 = x0)); intros.\n          destruct H21; double H21; apply H19 in H21; apply H20 in H22.\n          * rewrite H21, H22; auto.\n          * apply H6 with (x:= x1); auto.\n        + destruct H15; apply Axiom_SchemeP in H15; apply Axiom_SchemeP in H16.\n          destruct H15, H16; apply Axiom_SchemeP in H17; apply Axiom_SchemeP in H18.\n          destruct H17, H18; clear H17 H18; destruct H19, H20.\n          apply bel_inter in H17; apply bel_inter in H19; destruct H17, H19.\n          generalize (classic (y0 = x0)) (classic (z0 = x0)); intros.\n          destruct H23, H24; try rewrite H23, H24; apply H18 in H23;\n          apply H20 in H24; clear H18 H20; auto.\n          * rewrite <- H23 in H11; clear H23.\n            assert ([x1,z] ∈ f⁻¹ /\\ [x1,z0] ∈ f⁻¹).\n            { unfold Inverse; split; apply Axiom_SchemeP; split; Ens.\n              AssE [z,x1]; apply ord_set; apply ord_set in H18; tauto. }\n            apply H8 in H18; rewrite <- H18 in H22; clear H18 H24.\n            apply Axiom_Scheme in H22; destruct H22; elim H20; apply Axiom_Scheme; Ens.\n          * rewrite <- H24 in H11; clear H24.\n            assert ([x1,z] ∈ f⁻¹ /\\ [x1,y0] ∈ f⁻¹).\n            { unfold Inverse; split; apply Axiom_SchemeP; split; Ens.\n              AssE [z,x1]; apply ord_set; apply ord_set in H18; tauto. }\n            apply H8 in H18; rewrite <- H18 in H21; clear H16 H18 H19 H22 H23.\n            apply Axiom_Scheme in H21; destruct H21; elim H18; apply Axiom_Scheme; Ens.\n          * apply H8 with (x:= x1); split; apply Axiom_SchemeP; split; auto.\n        + apply Axiom_Extent; split; intros.\n          * unfold Domain in H15; apply Axiom_Scheme in H15; destruct H15, H16.\n            apply Axiom_SchemeP in H16; apply H16.\n          * unfold Domain; apply Axiom_Scheme; split; Ens.\n            generalize (classic (z0 = x0)); intros; destruct H16.\n            { exists f[z]; apply Axiom_SchemeP; repeat split; intros; try tauto.\n              apply Property_ran in H11; apply ord_set; split; Ens. }\n            { exists f[z0]; double H15; apply bel_inter in H17; destruct H17.\n              rewrite <- H7 in H17; apply Property_Value in H17; auto.\n              apply Axiom_SchemeP; repeat split; intros; try tauto; Ens. }\n        + apply Axiom_Extent; split; intros.\n          * unfold Range in H15; apply Axiom_Scheme in H15; destruct H15, H16.\n            apply Axiom_SchemeP in H16; destruct H16, H17.\n            generalize (classic (x1 = x0)); intros; destruct H19.\n            { apply H18 in H19; clear H18; rewrite H19; double H11.\n              apply Property_ran in H18; rewrite H9, H13 in H18.\n              apply bel_union in H18; destruct H18; auto; AssE [x0, u].\n              apply ord_set in H20; destruct H20; apply Axiom_Scheme in H18.\n              destruct H18; rewrite H22 in H11; try apply bel_universe_set; auto.\n              elim H14; apply H8 with (x:= u); unfold Inverse.\n              split; apply Axiom_SchemeP; split; try apply ord_set; Ens.\n              apply Property_dom in H11; split; Ens. }\n            { double H19; apply H18 in H20; clear H18; double H20.\n              apply Property_ran in H20; rewrite H9, H13 in H20; clear H15.\n              apply bel_union in H20; destruct H20; auto; apply Axiom_Scheme in H15.\n              destruct H15; AssE [x0,u]; apply ord_set in H21; destruct H21.\n              rewrite H20 in H18; try apply bel_universe_set; Ens; clear H20.\n              elim H19; apply H8 with (x:= u); unfold Inverse.\n              split; apply Axiom_SchemeP; split; try apply ord_set; Ens. }\n          * unfold Range; apply Axiom_Scheme; split; Ens.\n            assert (z0 ∈ ran(f)). { rewrite H9, H13; apply bel_union; tauto. }\n            unfold Range in H16; apply Axiom_Scheme in H16; destruct H16, H17.\n            generalize (classic (z0 = f[z])); intros; destruct H18.\n            { exists x0; apply Property_dom in H5; apply Axiom_SchemeP.\n              repeat split; intros; try tauto; try apply ord_set; Ens.\n              rewrite H7 in H5; unfold Difference; apply bel_inter; split; auto.\n              unfold Complement; apply Axiom_Scheme; split; Ens; intro.\n              unfold Singleton in H19; apply Axiom_Scheme in H19; destruct H19.\n              apply Property_dom in H11; rewrite H20 in H14; try tauto.\n              apply bel_universe_set; Ens. }\n            { exists x1; apply Axiom_SchemeP; repeat split; intros; Ens.\n              - double H17; apply Property_dom in H19; rewrite H7 in H19.\n                unfold Difference; apply bel_inter; split; auto.\n                apply Axiom_Scheme; split; Ens; intro; apply Axiom_Scheme in H20.\n                destruct H20; elim H18; apply H6 with (x:= z).\n                rewrite H21 in H17; try split; auto; apply bel_universe_set.\n                apply Property_dom in H11; Ens.\n              - rewrite H19 in H17; add ([x0,z0] ∈ f) H5; apply H6 in H5.\n                rewrite H5 in H15; generalize (notin_fix z0); contradiction. }}\n    assert (Ensemble (x ~ [z]) /\\ y ⊂ (x ~ [z])).\n    { split.\n      - apply (sub_set x _); auto; unfold Subclass; intros.\n        unfold Difference in H15; apply bel_inter in H15; apply H15.\n      - unfold Subclass, Difference; intros; apply bel_inter; split; auto.\n        unfold Complement; apply Axiom_Scheme; split; Ens; unfold Singleton; intro.\n        apply Axiom_Scheme in H16; destruct H16; rewrite H17 in H15; try contradiction.\n        apply bel_universe_set; Ens. }\n    elim H15; intros; apply card_le in H15; rewrite H1, H13 in H15.\n    clear H17; add (Ensemble u) H16; Ens; apply card_eq in H16.\n    apply H16 in H14; rewrite H14 in H15; clear H3 H13 H14 H16.\n    unfold Finite in H; unfold W in H; apply Axiom_Scheme in H; destruct H.\n    AssE u; apply int_bel_int in H5; auto.\n    assert (u ∈ C). { apply W_sub_C; apply Axiom_Scheme; split; auto. }\n    clear H5 H13; apply card_iff_eq in H14; destruct H14; rewrite H13 in H15.\n    assert (u ∈ (u ∪ [u])). { apply bel_union; right; apply Axiom_Scheme; Ens. }\n    clear H5 H13; unfold PlusOne, LessEqual in H15; destruct H15.\n    + generalize (not_bel_and (u ∪ [u]) u); intros; destruct H13; auto.\n    + rewrite H5 in H14; generalize (notin_fix u); contradiction.\nQed.\n\nHint Resolve fin_card_eq : set.\n\n\n(* 173 Theorem  If x is a set and x is not finite, then there is a subset y of\n   x such that y≠x and x≈y. *)\n\nLemma lem_notfin_exist_sub_eq : forall x0 x,\n  x0 ∈ P [x] -> ~ x0 ∈ W -> x0 ∈ (P [x] ~ W).\nProof.\n  intros; unfold Difference; apply bel_inter; split; auto.\n  unfold Complement; apply Axiom_Scheme; split; Ens.\nQed.\n\nTheorem notfin_exist_sub_eq : forall x,\n  Ensemble x /\\ ~ Finite x -> (exists y, y ⊂ x /\\ y ≠ x /\\ x ≈ y).\nProof.\n  intros; destruct H.\n  assert (W ⊂ P[x]).\n  { unfold Subclass; intros; double H; apply Property_PClass in H2.\n    unfold W in H1; unfold C in H2; apply Axiom_Scheme in H1; apply Axiom_Scheme in H2.\n    destruct H1, H2, H4; clear H5; unfold Ordinal_Number in H4; double H3.\n    unfold NInteger in H5; destruct H5; apply Axiom_Scheme in H4; clear H2 H6.\n    destruct H4; add (Ordinal z) H4; clear H5; apply ord_bel_eq in H4.\n    destruct H4 as [H4 | [H4 | H4]]; auto.\n    - apply int_bel_int in H4; auto; destruct H0; unfold Finite.\n      unfold W; apply Axiom_Scheme; split; auto.\n    - destruct H0; unfold Finite; rewrite H4; apply Axiom_Scheme; Ens. }\n  assert (P[x] ≈ (P[x] ~ [Φ])).\n  { unfold Equivalent; exists (\\{\\ λ u v, u ∈ P[x] /\\ ((u ∈ W -> v = PlusOne u)\n    /\\ (u ∈ (P[x] ~ W) -> v = u)) \\}\\).\n    repeat split; unfold Relation; intros; try PP H2 a b; Ens.\n    - destruct H2; apply Axiom_SchemeP in H2.\n      apply Axiom_SchemeP in H3; destruct H2, H3, H4, H5.\n      generalize (classic (x0 ∈ W)); intros; destruct H8.\n      + double H8; apply H6 in H8; apply H7 in H9; rewrite H8, H9; auto.\n      + apply lem_notfin_exist_sub_eq in H5; auto; clear H8; double H5.\n        apply H6 in H5; apply H7 in H8; rewrite H5, H8; auto.\n    - destruct H2; apply Axiom_SchemeP in H2.\n      apply Axiom_SchemeP in H3; destruct H2, H3; apply Axiom_SchemeP in H4.\n      apply Axiom_SchemeP in H5; destruct H4, H5, H6, H7.\n      generalize (classic (y ∈ W)) (classic (z ∈ W)); intros; destruct H10, H11.\n      + apply int_succ_eq; auto; apply H8 in H10; apply H9 in H11.\n        rewrite H10 in H11; auto.\n      + double H10; apply lem_notfin_exist_sub_eq in H7; auto; apply H8 in H10; apply H9 in H7.\n        rewrite H7 in H10; rewrite H10 in H11; apply int_succ in H12; tauto.\n      + double H11; apply lem_notfin_exist_sub_eq in H6; auto; apply H8 in H6; apply H9 in H11.\n        rewrite H6 in H11; rewrite H11 in H10; apply int_succ in H12; tauto.\n      + apply lem_notfin_exist_sub_eq in H6; apply lem_notfin_exist_sub_eq in H7; auto.\n        apply H8 in H6; apply H9 in H7; rewrite <- H6, <- H7; auto.\n    - apply Axiom_Extent; split; intros.\n      + unfold Domain in H2; apply Axiom_Scheme in H2; destruct H2, H3.\n        apply Axiom_SchemeP in H3; apply H3.\n      + unfold Domain; apply Axiom_Scheme; split; Ens.\n        generalize (classic (z ∈ W)); intros; destruct H3.\n        * exists (PlusOne z); apply Axiom_SchemeP; repeat split; intros; auto.\n          { apply int_succ in H3; apply ord_set; split; Ens. }\n          { unfold Difference in H4; apply bel_inter in H4; destruct H4.\n            apply Axiom_Scheme in H5; destruct H5; contradiction. }\n        * exists z; apply Axiom_SchemeP; repeat split; try apply ord_set; Ens.\n          intros; contradiction.\n    - apply Axiom_Extent; split; intros.\n      + unfold Range in H2; apply Axiom_Scheme in H2; destruct H2, H3.\n        apply Axiom_SchemeP in H3; destruct H3, H4.\n        generalize (classic (x0 ∈ W)); intros; destruct H6.\n        * double H6; apply H5 in H7; clear H5; double H6; double H6.\n          apply int_succ in H6; apply zero_not_int in H8; rewrite H7 in *.\n          clear H7; apply H1 in H6; unfold Difference; apply bel_inter.\n          split; auto; unfold Complement; apply Axiom_Scheme; split; Ens.\n          intro; apply Axiom_Scheme in H7; destruct H7; rewrite H9 in H8; auto.\n          apply bel_universe_set; Ens; exists W; apply zero_not_int; auto.\n        * double H4; apply lem_notfin_exist_sub_eq in H7; auto; apply H5 in H7; clear H5.\n          rewrite H7 in *; clear H7; unfold Difference; apply bel_inter.\n          split; auto; unfold Complement; apply Axiom_Scheme; split; Ens.\n          intro; apply Axiom_Scheme in H5; clear H2; destruct H5.\n          generalize (zero_not_int x0); intros; destruct H7; clear H8.\n          rewrite H5 in H6; try apply bel_universe_set; Ens.\n      + unfold Difference in H2; apply bel_inter in H2; destruct H2.\n        unfold Complement in H3; apply Axiom_Scheme in H3; destruct H3.\n        unfold Range; apply Axiom_Scheme; split; Ens.\n        generalize (classic (z ∈ W)); intros; destruct H5.\n        * unfold W in H5; apply Axiom_Scheme in H5; destruct H5; double H6.\n          unfold NInteger in H7; destruct H7, H8; clear H8.\n          assert (z ⊂ z /\\ z ≠ Φ).\n          { split; unfold Subclass; intros; auto; intro; destruct H4.\n            generalize (zero_not_int z); intros; destruct H4; rewrite H8.\n            clear H8 H10; apply Axiom_Scheme; split; Ens. }\n          apply H9 in H8; clear H9; destruct H8.\n          assert (z ∈ R /\\ LastMember x0 E z).\n          { split; auto; try apply Axiom_Scheme; Ens. }\n          apply ordnum_plus_eq in H9; unfold FirstMember in H8; destruct H8.\n          AssE x0; apply int_bel_int in H8; auto; clear H10; exists x0.\n          apply Axiom_SchemeP; repeat split; intros; try apply ord_set; Ens.\n          -- apply H1; apply Axiom_Scheme; Ens.\n          -- unfold Difference in H10; apply bel_inter in H10; destruct H10.\n             unfold Complement in H12; apply Axiom_Scheme in H12; destruct H12, H13.\n             unfold W; apply Axiom_Scheme; split; auto.\n        * exists z; apply Axiom_SchemeP; repeat split; try apply ord_set; Ens.\n          intros; contradiction. }\n  double H; apply card_equiv in H3; unfold Equivalent in H3.\n  destruct H3 as [f H3], H3, H3, H4.\n  assert (P[x] ~ [Φ] ≈ ran(f | (P[x] ~ [Φ]))).\n  { unfold Equivalent; exists (f | (P[x] ~ [Φ])).\n    repeat split; unfold Relation; intros; try PP H7 a b; Ens.\n    - unfold Restriction in H7; apply bel_inter in H7; destruct H7.\n      PP H8 a b; Ens.\n    - unfold Restriction in H7; destruct H7; apply bel_inter in H7.\n      apply bel_inter in H8; destruct H7, H8; apply H3 with (x:= x0); auto.\n    - unfold Restriction, Inverse in H7; destruct H7; apply Axiom_SchemeP in H7.\n      apply Axiom_SchemeP in H8; destruct H7, H8; apply bel_inter in H9.\n      apply bel_inter in H10; destruct H9, H10; apply H5 with (x:= x0).\n      unfold Inverse; split; apply Axiom_SchemeP; split; Ens.\n    - apply Axiom_Extent; split; intros.\n      + unfold Domain in H7; apply Axiom_Scheme in H7; destruct H7, H8.\n        unfold Restriction in H8; apply bel_inter in H8; destruct H8.\n        unfold Cartesian in H9; apply Axiom_SchemeP in H9; apply H9.\n      + unfold Domain; apply Axiom_Scheme; split; Ens; exists f[z].\n        unfold Restriction; apply bel_inter; double H7; unfold Difference in H8.\n        apply bel_inter in H8; destruct H8; clear H9; rewrite <- H4 in H8.\n        apply Property_Value in H8; auto; split; auto; unfold Cartesian.\n        apply Axiom_SchemeP; AssE ([z,f[z]]); apply Property_ran in H8.\n        repeat split; Ens; apply bel_universe_set; Ens. }\n  double H; apply card_equiv in H8; apply equiv_com in H8.\n  apply equiv_tran with (z:= P[x] ~ [Φ]) in H8; auto; clear H2.\n  apply equiv_tran with (z:= ran(f | (P[x] ~ [Φ]))) in H8; auto; clear H7.\n  exists ran(f | (P[x] ~ [Φ])); repeat split; auto.\n  - unfold Subclass; intros; unfold Range, Restriction in H2.\n    apply Axiom_Scheme in H2; destruct H2, H7; apply bel_inter in H7; destruct H7.\n    apply Property_ran in H7; rewrite H6 in H7; auto.\n  - generalize (zero_not_int x); intros; destruct H2; clear H7; apply H1 in H2.\n    rewrite <- H4 in H2; apply Property_Value in H2; auto; intro.\n    assert (f[Φ] ∈ ran(f | (P[x] ~ [Φ]))).\n    { rewrite H7; apply Property_ran in H2; rewrite H6 in H2; auto. }\n    unfold Range in H9; apply Axiom_Scheme in H9; destruct H9, H10.\n    unfold Restriction in H10; apply bel_inter in H10; destruct H10.\n    assert ([f[Φ],Φ] ∈ f⁻¹ /\\ [f[Φ],x0] ∈ f⁻¹).\n    { AssE [Φ,f[Φ]]; AssE [x0,f[Φ]]; apply ord_set in H12.\n      apply ord_set in H13; destruct H12, H13; clear H14 H15.\n      split; apply Axiom_SchemeP; split; try apply ord_set; auto. }\n    apply H5 in H12; rewrite H12 in H11; clear H12; unfold Cartesian in H11.\n    apply Axiom_SchemeP in H11; destruct H11, H12; clear H11 H13.\n    unfold Difference in H12; apply bel_inter in H12; destruct H12.\n    unfold Complement in H12; apply Axiom_Scheme in H12; destruct H12, H13.\n    unfold Singleton; apply Axiom_Scheme; split; Ens.\nQed.\n\nHint Resolve notfin_exist_sub_eq : set.\n\n\n(* 174 Theorem  If x ∈ (R ~ W), then P[x+1] = P[x]. *)\n\nLemma le_tran_eq : forall x y, x ≼ y -> y ≼ x -> x = y.\nProof.\n  intros; unfold LessEqual in H, H0; destruct H, H0; auto.\n  generalize (not_bel_and x y); intros; destruct H1; auto.\nQed.\n\nTheorem notint_card_plus_eq : forall x,\n  x ∈ (R ~ W) -> P[ PlusOne x ] = P[x].\nProof.\n  intros.\n  unfold Difference in H; apply bel_inter in H; destruct H.\n  double H; apply ordnum_succ_ordnum in H1; AssE (PlusOne x).\n  add (x⊂(PlusOne x)) H2; try (unfold Subclass; intros; apply bel_union; tauto).\n  apply card_le in H2; apply Axiom_Scheme in H0; destruct H0.\n  assert (Ensemble x /\\ ~ Finite x).\n  { split; auto; clear H1 H2; unfold Finite; intro; destruct H3.\n    generalize (Property_W); intros; unfold R in H; apply Axiom_Scheme in H.\n    clear H0; destruct H; assert (Ordinal W /\\ Ordinal x); auto; double H3.\n    apply ord_bel_eq in H3; apply ord_sub_iff_le in H4.\n    destruct H3 as [H3 | [H3 | H3]]; auto.\n    - assert (W ≼ x); unfold LessEqual; try tauto; apply H4 in H5; clear H4.\n      assert (Ensemble x /\\ W ⊂ x); auto; apply card_le in H4.\n      double H1; unfold W in H6; apply Axiom_Scheme in H6; destruct H6.\n      unfold NInteger in H7; destruct H7; clear H8.\n      assert (Ordinal P[x] /\\ Ordinal W); auto; apply ord_sub_iff_le in H8.\n      assert (P[x] ≼ W); unfold LessEqual; try auto; apply H8 in H9; clear H8.\n      assert (Ensemble W /\\ P [x] ⊂ W); Ens; apply card_le in H8; clear H9.\n      rewrite card_eq_inv in H8. apply le_tran_eq in H8; auto.\n      rewrite <- H8 in H1; clear H4 H8; generalize W_bel_C; intros.\n      apply card_iff_eq in H4; destruct H4; rewrite H8 in H1.\n      generalize (notin_fix W); intros; contradiction.\n    - rewrite H3 in H1; generalize W_bel_C; intros; rewrite H3 in H5.\n      apply card_iff_eq in H5; destruct H5; rewrite H6 in H1.\n      generalize (notin_fix x); intros; contradiction. }\n  apply notfin_exist_sub_eq in H4; destruct H4 as [u H4], H4, H5.\n  assert (P[PlusOne x] ≼ P[x]).\n  { assert (u ⊊ x). { split; auto. } apply Property_ProperSubclass' in H7.\n    destruct H7 as [z H7], H7, H6 as [f H6], H6, H6, H9.\n    assert (PlusOne x ≈ ran(\\{\\ λ v w, (v∈x /\\ w=f[v]) \\/ (v=x /\\ w=z) \\}\\)).\n    { unfold Equivalent; exists (\\{\\λ v w, (v∈x /\\ w=f[v]) \\/ (v=x /\\ w=z)\\}\\).\n      repeat split; unfold Relation; intros; try PP H12 a b; Ens.\n      - destruct H12; apply Axiom_SchemeP in H12; apply Axiom_SchemeP in H13.\n        destruct H12, H13, H14, H15, H14, H15; try rewrite H16, H17; auto.\n        + rewrite H15 in H14; generalize (notin_fix x); contradiction.\n        + rewrite H14 in H15; generalize (notin_fix x); contradiction.\n      - destruct H12; apply Axiom_SchemeP in H12; apply Axiom_SchemeP in H13.\n        destruct H12, H13; apply Axiom_SchemeP in H14; apply Axiom_SchemeP in H15.\n        destruct H14, H15, H16, H17, H16, H17.\n        + rewrite <- H9 in H16, H17; apply Property_Value in H16; auto.\n          apply Property_Value in H17; auto; rewrite H19 in *; clear H19.\n          rewrite H18 in *; clear H18; apply H10 with (x:= f[y]).\n          unfold Inverse; split; apply Axiom_SchemeP; Ens.\n        + rewrite <- H9 in H16; apply Property_Value in H16; auto.\n          apply Property_ran in H16; rewrite H11 in H16; rewrite <- H18 in H16.\n          rewrite H19 in H16; contradiction.\n        + rewrite <- H9 in H17; apply Property_Value in H17; auto.\n          apply Property_ran in H17; rewrite H11 in H17; rewrite <- H19 in H17.\n          rewrite H18 in H17; contradiction.\n        + rewrite H16, H17; auto.\n      - apply Axiom_Extent; split; intros.\n        + unfold PlusOne; apply bel_union; unfold Domain in H12.\n          apply Axiom_Scheme in H12; destruct H12, H13; apply Axiom_SchemeP in H13.\n          destruct H13, H14; destruct H14; try tauto; rewrite H14 in *.\n          right; unfold Singleton; apply Axiom_Scheme; split; Ens.\n        + unfold Domain; apply Axiom_Scheme; split; Ens; unfold PlusOne in H12.\n          apply bel_union in H12; destruct H12.\n          * double H12; rewrite <- H9 in H13; apply Property_Value in H13; auto.\n            exists f[z0]; apply Axiom_SchemeP; repeat split; intros; Ens.\n          * exists z; apply Axiom_SchemeP; split; try apply ord_set; Ens.\n            right; split; auto; unfold Singleton in H12; apply Axiom_Scheme in H12.\n            apply H12; apply bel_universe_set; auto. }\n    assert (Ensemble x /\\ ran(\\{\\λ v w, (v∈x/\\w=f[v]) \\/ (v=x/\\w=z) \\}\\) ⊂ x).\n    { split; auto; unfold Subclass; intros; apply Axiom_Scheme in H13.\n      destruct H13, H14; apply Axiom_SchemeP in H14; destruct H14, H15, H15.\n      - rewrite H16; rewrite <- H9 in H15; apply Property_Value in H15; auto.\n        apply Property_ran in H15; rewrite H11 in H15; auto.\n      - rewrite H16; auto. }\n    clear H0; elim H13; intros; apply card_le in H13.\n    apply card_eq in H12; try (split; Ens; apply (sub_set x _); auto).\n    rewrite <- H12 in H13; clear H12 H14; auto. }\n  apply le_tran_eq; auto.\nQed.\n\nHint Resolve notint_card_plus_eq : set.\n\n\n(* 175 Definition  max[x,y] = x ∪ y. *)\n\nDefinition Max x y : Class := x ∪ y.\n\nCorollary Property_Max : forall x y,\n  (Ordinal x -> Ordinal y -> x ∈ y -> Max x y = y) /\\ (x = y -> Max x y = y).\nProof.\n  split; intros; try (rewrite H; unfold Max; apply union_fix).\n  assert (x ≼ y); unfold LessEqual; try tauto.\n  apply ord_sub_iff_le in H2; auto; unfold Max; apply union_sub; auto.\nQed.\n\nCorollary Equal_Max : forall x y, Max x y = Max y x.\nProof.\n  intros; unfold Max; apply union_com.\nQed.\n\nHint Unfold Max : set.\nHint Resolve Property_Max : set.\nHint Rewrite Equal_Max : set.\n\n\n(* 176 Definition  《 = { z : for some [u,v] in R×R and some [x,y] in R×R,\n   z=[[u,v],[x,y]], and max[u,v] < max[x,y], or max[u,v] = max[x,y] and u<x,\n   or max[u,v] = max[x,y] and u=x and v<y }. *)\n\nDefinition LessLess : Class :=\n  \\{ λ z, exists u v x y, [u,v]∈(R×R) /\\ [x,y]∈(R×R) /\\ z = [[u,v],[x,y]] /\\\n  ((Max u v ≺ Max x y) \\/ (Max u v = Max x y /\\ u ≺ x) \\/ (Max u v = Max x y /\\\n  u = x /\\ v ≺ y)) \\}.\n\nNotation \"≪\" := (LessLess) (at level 0, no associativity).\n\nHint Unfold LessLess : set.\n\n\n(* 177 Theorem  《 well-orders R × R. *)\n\nDefinition En_y y : Class := \\{ λ z, exists u v, [u,v] ∈ y /\\ z = Max u v \\}.\n\nDefinition En_v v y : Class := \\{ λ z, [z,v] ∈ y /\\ z ∈ v \\}.\n\nDefinition En_u u y : Class := \\{ λ z, [u,z] ∈ y /\\ z ∈ u \\}.\n\nLemma lem_well_cartR_bd : forall a b c d,\n  [a, b] ∈ R × R -> [c, d] ∈ R × R -> Ensemble a -> Ensemble b ->\n  Ensemble c -> Ensemble d -> Ordinal a -> Ordinal b -> Ordinal c ->\n  Ordinal d -> Max a b = b -> Max c d = d ->\n  Rrelation ([a,b]) ≪ ([c,d]) \\/ Rrelation ([c,d]) ≪ ([a,b]) \\/ [a,b] = [c,d].\nProof.\n  intros.\n  assert (Ordinal b /\\ Ordinal d); auto; apply ord_bel_eq in H11.\n  destruct H11 as [H11 | [H11 | H11]].\n  - left; unfold Rrelation, LessLess; apply Axiom_Scheme.\n    split; try (apply ord_set; split; apply ord_set; auto).\n    exists a, b, c, d; repeat split; auto; left.\n    rewrite H9, H10; unfold Less; auto.\n  - right; left; unfold Rrelation, LessLess; apply Axiom_Scheme.\n    split; try (apply ord_set; split; apply ord_set; auto).\n    exists c, d, a, b; repeat split; auto; left.\n    rewrite H9, H10; unfold Less; auto.\n  - assert (Ordinal a /\\ Ordinal c); auto; apply ord_bel_eq in H12.\n    destruct H12 as [H12 | [H12 | H12]].\n    { left; unfold Rrelation, LessLess; apply Axiom_Scheme.\n      split; try (apply ord_set; split; apply ord_set; auto).\n      exists a, b, c, d; repeat split; auto; right; left.\n      rewrite H9, H10; unfold Less; split; auto. }\n    { right; left; unfold Rrelation, LessLess; apply Axiom_Scheme.\n      split; try (apply ord_set; split; apply ord_set; auto).\n      exists c, d, a, b; repeat split; auto; right; left.\n      rewrite H9, H10; unfold Less; split; auto. }\n    { right; right; rewrite H11, H12; auto. }\nQed.\n\nLemma lem_well_cartR_bc : forall a b c d,\n  [a, b] ∈ R × R -> [c, d] ∈ R × R -> Ensemble a -> Ensemble b ->\n  Ensemble c -> Ensemble d -> Ordinal a -> Ordinal b -> Ordinal c ->\n  Ordinal d -> Max a b = b -> Max c d = c ->\n  Rrelation ([a,b]) ≪ ([c,d]) \\/ Rrelation ([c,d]) ≪ ([a,b]) \\/ [a,b] = [c,d].\nProof.\n  intros; assert (Ordinal b /\\ Ordinal c); auto.\n  apply ord_bel_eq in H11; destruct H11 as [H11 | [H11 | H11]].\n  - left; unfold Rrelation, LessLess; apply Axiom_Scheme.\n    split; try (apply ord_set; split; apply ord_set; auto).\n    exists a, b, c, d; repeat split; auto; left.\n    rewrite H9, H10; unfold Less; auto.\n  - right; left; unfold Rrelation, LessLess; apply Axiom_Scheme.\n    split; try (apply ord_set; split; apply ord_set; auto).\n    exists c, d, a, b; repeat split; auto; left.\n    rewrite H9, H10; unfold Less; auto.\n  - assert (Ordinal a /\\ Ordinal c); auto; apply ord_bel_eq in H12.\n    destruct H12 as [H12 | [H12 | H12]].\n    { left; unfold Rrelation, LessLess; apply Axiom_Scheme.\n      split; try (apply ord_set; split; apply ord_set; auto).\n      exists a, b, c, d; repeat split; auto; right; left.\n      rewrite H9, H10; unfold Less; split; auto. }\n    { right; left; unfold Rrelation, LessLess; apply Axiom_Scheme.\n      split; try (apply ord_set; split; apply ord_set; auto).\n      exists c, d, a, b; repeat split; auto; right; left.\n      rewrite H9, H10; unfold Less; split; auto. }\n    { assert (Ordinal b /\\ Ordinal d); auto; apply ord_bel_eq in H13.\n      destruct H13 as [H13 | [H13 | H13]].\n      - left; unfold Rrelation, LessLess; apply Axiom_Scheme.\n        split; try (apply ord_set; split; apply ord_set; auto).\n        exists a, b, c, d; repeat split; auto; right; right.\n        rewrite H9, H10; unfold Less; auto.\n      - right; left; unfold Rrelation, LessLess; apply Axiom_Scheme.\n        split; try (apply ord_set; split; apply ord_set; auto).\n        exists c, d, a, b; repeat split; auto; right; right.\n        rewrite H9, H10; unfold Less; auto.\n      - right; right; rewrite H12, H13; auto. }\nQed.\n\nLemma lem_well_cartR_ac : forall a b c d,\n  [a, b] ∈ R × R -> [c, d] ∈ R × R -> Ensemble a -> Ensemble b ->\n  Ensemble c -> Ensemble d -> Ordinal a -> Ordinal b -> Ordinal c ->\n  Ordinal d -> Max a b = a -> Max c d = c ->\n  Rrelation ([a,b]) ≪ ([c,d]) \\/ Rrelation ([c,d]) ≪ ([a,b]) \\/ [a,b] = [c,d].\nProof.\n  intros; assert (Ordinal a /\\ Ordinal c); auto.\n  apply ord_bel_eq in H11; destruct H11 as [H11 | [H11 | H11]].\n  - left; unfold Rrelation, LessLess; apply Axiom_Scheme.\n    split; try (apply ord_set; split; apply ord_set; auto).\n    exists a, b, c, d; repeat split; auto; left.\n    rewrite H9, H10; unfold Less; auto.\n  - right; left; unfold Rrelation, LessLess; apply Axiom_Scheme.\n    split; try (apply ord_set; split; apply ord_set; auto).\n    exists c, d, a, b; repeat split; auto; left.\n    rewrite H9, H10; unfold Less; auto.\n  - assert (Ordinal b /\\ Ordinal d); auto; apply ord_bel_eq in H12.\n    destruct H12 as [H12 | [H12 | H12]].\n    { left; unfold Rrelation, LessLess; apply Axiom_Scheme.\n      split; try (apply ord_set; split; apply ord_set; auto).\n      exists a, b, c, d; repeat split; auto; right; right.\n      rewrite H9, H10; unfold Less; split; auto. }\n    { right; left; unfold Rrelation, LessLess; apply Axiom_Scheme.\n      split; try (apply ord_set; split; apply ord_set; auto).\n      exists c, d, a, b; repeat split; auto; right; right.\n      rewrite H9, H10; unfold Less; split; auto. }\n    { right; right; rewrite H11, H12; auto. }\nQed.\n\nLemma lem_well_cartR_v : forall x y u v,\n  x ∈ y -> y ⊂ (R × R) -> Max u v = v -> Rrelation x ≪ ([u,v]) ->\n  (exists a b, [a, b] ∈ y /\\ Ensemble a /\\ Ordinal a /\\ Ensemble b /\\ Ordinal b\n  /\\ ((Max a b) ∈ v \\/ Max a b = v /\\ a ∈ u \\/ Max a b = v /\\ a = u /\\ b ∈ v)).\nProof.\n  intros.\n  double H; apply H0 in H3; unfold Cartesian in H3; clear H0.\n  PP H3 a b; apply Axiom_SchemeP in H0; clear H3; exists a, b; split; auto.\n  destruct H0, H3; apply Axiom_Scheme in H3; apply Axiom_Scheme in H4; clear H0.\n  destruct H3, H4; unfold Rrelation, LessLess in H2; apply Axiom_Scheme in H2.\n  destruct H2, H6, H6, H6, H6, H6, H7, H8; clear H6 H7; apply ord_set in H2.\n  destruct H2; clear H2; apply ord_set in H6; destruct H6; unfold Less in H9.\n  apply ord_eq in H8; try (split; Ens; apply ord_set; Ens).\n  destruct H8; apply ord_eq in H7; apply ord_eq in H8; auto.\n  destruct H7, H8; rewrite <- H7, <- H8, <- H10, <- H11, H1 in H9; Ens.\nQed.\n\nLemma lem_well_cartR_u : forall x y u v,\n  x ∈ y -> y ⊂ (R × R) -> Max u v = u -> Rrelation x ≪ ([u,v]) ->\n  (exists a b, [a, b] ∈ y /\\ Ensemble a /\\ Ordinal a /\\ Ensemble b /\\ Ordinal b\n  /\\ ((Max a b) ∈ u \\/ Max a b = u /\\ a ∈ u \\/ Max a b = u /\\ a = u /\\ b ∈ v)).\nProof.\n  intros.\n  double H; apply H0 in H3; unfold Cartesian in H3; clear H0.\n  PP H3 a b; apply Axiom_SchemeP in H0; clear H3; exists a, b; split; auto.\n  destruct H0, H3; apply Axiom_Scheme in H3; apply Axiom_Scheme in H4; clear H0.\n  destruct H3, H4; unfold Rrelation, LessLess in H2; apply Axiom_Scheme in H2.\n  destruct H2, H6, H6, H6, H6, H6, H7, H8; clear H6 H7; apply ord_set in H2.\n  destruct H2; clear H2; apply ord_set in H6; destruct H6; unfold Less in H9.\n  apply ord_eq in H8; try (split; Ens; apply ord_set; Ens).\n  destruct H8; apply ord_eq in H7; apply ord_eq in H8; auto.\n  destruct H7, H8; rewrite <- H7, <- H8, <- H10, <- H11, H1 in H9; Ens.\nQed.\n\nTheorem well_order_cartR : WellOrdered ≪ (R × R).\nProof.\n  unfold WellOrdered; split; intros.\n  - unfold Connect; intros; destruct H; double H; double H0; PP H1 a b.\n    PP H2 c d; clear H1 H2; apply Axiom_SchemeP in H3; apply Axiom_SchemeP in H4.\n    destruct H3, H4; clear H1 H3; destruct H2, H4; unfold R in H1, H2, H3, H4.\n    apply Axiom_Scheme in H1; apply Axiom_Scheme in H2; apply Axiom_Scheme in H3.\n    apply Axiom_Scheme in H4; destruct H1, H2, H3, H4.\n    assert (Ordinal a /\\ Ordinal b); assert (Ordinal c /\\ Ordinal d); auto.\n    apply ord_bel_eq in H9; apply ord_bel_eq in H10.\n    destruct H9 as [H9 | [H9 | H9]], H10 as [H10 | [H10 | H10]];\n    apply Property_Max in H9; apply Property_Max in H10; auto.\n    + apply lem_well_cartR_bd; auto.\n    + rewrite Equal_Max in H10; apply lem_well_cartR_bc; auto.\n    + apply lem_well_cartR_bd; auto.\n    + rewrite Equal_Max in H9; apply (lem_well_cartR_bc c d a b) in H10; auto.\n      destruct H10 as [H10 | [H10| H10]]; try rewrite H10; auto.\n    + rewrite Equal_Max in H9, H10; apply lem_well_cartR_ac; auto.\n    + rewrite Equal_Max in H9; apply (lem_well_cartR_bc c d a b) in H10; auto.\n      destruct H10 as [H10 | [H10| H10]]; try rewrite H10; auto.\n    + apply lem_well_cartR_bd; auto.\n    + rewrite Equal_Max in H10; apply lem_well_cartR_bc; auto.\n    + apply lem_well_cartR_bd; auto.\n  - destruct H.\n    assert ((En_y y) ⊂ R /\\ (En_y y) ≠ Φ).\n    { split.\n      - unfold Subclass; intros; apply Axiom_Scheme in H1; destruct H1, H2, H2, H2.\n        apply H in H2; apply Axiom_SchemeP in H2; destruct H2, H4; clear H2.\n        apply Axiom_Scheme in H4; apply Axiom_Scheme in H5; destruct H4, H5.\n        assert (Ordinal x /\\ Ordinal x0); auto; apply ord_bel_eq in H7.\n        rewrite H3; destruct H7 as [H7|[H7|H7]]; apply Property_Max in H7;\n        auto; try (rewrite H7; unfold R; apply Axiom_Scheme; Ens).\n        rewrite Equal_Max in H7; rewrite H7; apply Axiom_Scheme; Ens.\n      - apply not_zero_exist_bel in H0; destruct H0; double H0; apply H in H1; PP H1 a b.\n        apply Axiom_SchemeP in H2; clear H1; destruct H2, H2; clear H1.\n        apply Axiom_Scheme in H2; apply Axiom_Scheme in H3.\n        destruct H2, H3; apply not_zero_exist_bel.\n        assert (Ordinal a /\\ Ordinal b); auto; apply ord_bel_eq in H5.\n        destruct H5 as [H5|[H5|H5]]; apply Property_Max in H5; auto.\n        + exists b; apply Axiom_Scheme; split; auto; exists a, b; auto.\n        + exists a; apply Axiom_Scheme; split; auto; exists a, b; split; auto.\n          rewrite Equal_Max; symmetry; auto.\n        + exists b; apply Axiom_Scheme; split; auto; exists a, b; auto. }\n    clear H0; apply sub_noteq_firstmemb in H1; unfold FirstMember in H1; destruct H1.\n    apply Axiom_Scheme in H0; destruct H0, H2 as [u [v H2]], H2.\n    generalize (classic ((En_v (∩ En_y y) y) = Φ)); intros; destruct H4.\n    + generalize (classic ((En_u (∩ En_y y) y) = Φ)); intros; destruct H5.\n      * double H2; apply H in H6; unfold Cartesian in H6; apply Axiom_SchemeP in H6.\n        destruct H6, H7; apply Axiom_Scheme in H7; apply Axiom_Scheme in H8; clear H6.\n        destruct H7, H8; assert (Ordinal u /\\ Ordinal v); auto.\n        apply ord_bel_eq in H10; destruct H10 as [H10 | [H10 | H10]].\n        { double H10; apply Property_Max in H11; auto.\n          rewrite H11 in H3; rewrite H3 in *; clear H3 H11.\n          assert (u ∈ (En_v v y)); try (apply Axiom_Scheme; Ens); rewrite H4 in H3.\n          generalize (not_bel_zero u); intros; contradiction. }\n        { double H10; apply Property_Max in H11; auto; rewrite Equal_Max in H11.\n          rewrite H11 in H3; rewrite H3 in *; clear H3 H11.\n          assert (v ∈ (En_u u y)); try (apply Axiom_Scheme; Ens); rewrite H5 in H3.\n          generalize (not_bel_zero v); intros; contradiction. }\n        { double H10; apply Property_Max in H11; rewrite H11 in H3.\n          rewrite H3, H10 in *; clear H3 H6 H8 H9 H10; exists [v,v].\n          unfold FirstMember; split; auto; intros; intro.\n          apply lem_well_cartR_v with (y:= y) in H6; auto; clear H3 H11.\n          destruct H6 as [a [b H6]], H6, H6, H8, H9, H10.\n          assert (Ordinal a /\\ Ordinal b); auto; apply ord_bel_eq in H12.\n          destruct H12 as [H12 | [H12 | H12]].\n          - apply Property_Max in H12; auto; rewrite H12 in H11.\n            destruct H11 as [H11 | [H11 | H11]].\n            + assert (b ∈ (En_y y)); try apply Axiom_Scheme; Ens.\n              apply H1 in H13; elim H13; clear H12 H13; unfold Rrelation, E.\n              apply Axiom_SchemeP; split; try apply ord_set; auto.\n            + destruct H11; rewrite H11 in *; clear H9 H10 H11.\n              assert (a ∈ (En_v v y)); try apply Axiom_Scheme; Ens.\n              rewrite H4 in H9; generalize (not_bel_zero a); contradiction.\n            + destruct H11, H13; rewrite H11 in H14.\n              generalize (notin_fix v); intros; contradiction.\n          - apply Property_Max in H12; auto; rewrite Equal_Max in H12.\n            rewrite H12 in H11; destruct H11 as [H11 | [H11 | H11]].\n            + assert (a ∈ (En_y y)); try apply Axiom_Scheme; Ens.\n              apply H1 in H13; elim H13; clear H12 H13; unfold Rrelation, E.\n              apply Axiom_SchemeP; split; try apply ord_set; auto.\n            + destruct H11; rewrite H11 in H13.\n              generalize (notin_fix v); intros; contradiction.\n            + destruct H11; clear H11; destruct H13; rewrite H11 in *.\n              clear H11 H12; assert (b ∈ (En_u v y)); try apply Axiom_Scheme; Ens.\n              rewrite H5 in H11; generalize (not_bel_zero b); contradiction.\n          - double H12; apply Property_Max in H13; auto; rewrite H13 in H11.\n            rewrite H12 in *; clear H9 H10 H12; destruct H11 as [H9|[H9|H9]].\n            + assert (b ∈ (En_y y)); try apply Axiom_Scheme; Ens.\n              apply H1 in H10; elim H10; clear H13 H10; unfold Rrelation, E.\n              apply Axiom_SchemeP; split; try apply ord_set; auto.\n            + destruct H9; rewrite H9 in H10.\n              generalize (notin_fix v); intros; contradiction.\n            + destruct H9, H10; rewrite H9 in H11.\n              generalize (notin_fix v); intros; contradiction. }\n      * assert ((En_u (∩ En_y y) y) ⊂ R /\\ (En_u (∩ En_y y) y) ≠ Φ).\n        { split; auto; unfold Subclass; intros; apply Axiom_Scheme in H6.\n          destruct H6, H7; apply H in H7; apply Axiom_SchemeP in H7; apply H7. }\n        apply sub_noteq_firstmemb in H6; clear H5; destruct H6; apply Axiom_Scheme in H5.\n        destruct H5, H7; exists [∩ (En_y y), ∩ (En_u (∩(En_y y)) y)].\n        clear H5; double H7; apply H in H7; apply Axiom_SchemeP in H7.\n        destruct H7; clear H7; destruct H9; apply Axiom_Scheme in H7.\n        apply Axiom_Scheme in H9; clear H0; destruct H7, H9.\n        double H8; apply Property_Max in H11; auto.\n        unfold FirstMember; split; auto; intros; intro.\n        apply lem_well_cartR_u with (y:= y) in H13; try rewrite Equal_Max; auto.\n        clear H12; destruct H13 as [a [b H13]], H13, H13, H14, H15, H16.\n        assert (Ordinal a /\\ Ordinal b); auto; apply ord_bel_eq in H18.\n        destruct H18 as [H18 | [H18 | H18]].\n        { double H18; apply Property_Max in H19; auto; rewrite H19 in H17.\n          destruct H17 as [H17 | [H17 | H17]].\n          - assert (b ∈ (En_y y)); try apply Axiom_Scheme; Ens.\n            apply H1 in H20; elim H20; clear H19 H20; unfold Rrelation, E.\n            apply Axiom_SchemeP; split; try apply ord_set; auto.\n          - destruct H17; rewrite H17 in *; clear H15 H16 H17.\n            assert (a ∈ (En_v (∩ En_y y) y)); try apply Axiom_Scheme; Ens.\n            rewrite H4 in H15; generalize (not_bel_zero a); contradiction.\n          - destruct H17, H20; rewrite <- H17 in H20; rewrite H20 in H18.\n            generalize (notin_fix b); intros; contradiction. }\n        { double H18; apply Property_Max in H19; auto; rewrite Equal_Max in H19.\n          rewrite H19 in H17; destruct H17 as [H17 | [H17 | H17]].\n          - assert (a ∈ (En_y y)); try apply Axiom_Scheme; Ens.\n            apply H1 in H20; elim H20; clear H19 H20; unfold Rrelation, E.\n            apply Axiom_SchemeP; split; try apply ord_set; auto.\n          - destruct H17; rewrite <- H17 in H20.\n            generalize (notin_fix a); intros; contradiction.\n          - destruct H17; clear H17; destruct H20; rewrite H17 in *.\n            assert (b∈(En_u (∩ En_y y) y)); try apply Axiom_Scheme; Ens.\n            apply H6 in H21. elim H21; unfold Rrelation, E.\n            apply Axiom_SchemeP; split; try apply ord_set; auto. }\n        { double H18; apply Property_Max in H19; rewrite H19 in H17.\n          rewrite H18 in *; clear H15 H16 H18; destruct H17 as [H15|[H15|H15]].\n          - assert (b ∈ (En_y y)); try apply Axiom_Scheme; Ens.\n            apply H1 in H16; elim H16; clear H19 H16; unfold Rrelation, E.\n            apply Axiom_SchemeP; split; try apply ord_set; auto.\n          - destruct H15; rewrite <- H15 in H16.\n            generalize (notin_fix b); intros; contradiction.\n          - destruct H15; clear H15; destruct H16; rewrite H15 in H16.\n            generalize (not_bel_and (∩ En_y y) (∩ En_u (∩ En_y y) y)); intros.\n            destruct H17; split; auto. }\n    + assert ((En_v (∩ En_y y) y) ⊂ R /\\ (En_v (∩ En_y y) y) ≠ Φ).\n      { split; auto; unfold Subclass; intros; apply Axiom_Scheme in H5.\n        destruct H5, H6; apply H in H6; apply Axiom_SchemeP in H6; apply H6. }\n      apply sub_noteq_firstmemb in H5; clear H4; destruct H5; apply Axiom_Scheme in H4.\n      destruct H4, H6; exists [∩ (En_v (∩ En_y y) y), ∩ (En_y y)].\n      clear H4; double H6; apply H in H6; apply Axiom_SchemeP in H6; destruct H6.\n      clear H6; destruct H8; apply Axiom_Scheme in H6; apply Axiom_Scheme in H8.\n      clear H0; destruct H6, H8; double H7; apply Property_Max in H10; auto.\n      unfold FirstMember; split; auto; intros; intro.\n      apply lem_well_cartR_v with (y:= y) in H12; auto; clear H11.\n      destruct H12 as [a [b H12]], H12, H12, H13, H14, H15.\n      assert (Ordinal a /\\ Ordinal b); auto; apply ord_bel_eq in H17.\n      destruct H17 as [H17 | [H17 | H17]].\n      { double H17; apply Property_Max in H18; auto; rewrite H18 in H16.\n        destruct H16 as [H16 | [H16 | H16]].\n        - assert (b ∈ (En_y y)); try apply Axiom_Scheme; Ens.\n          apply H1 in H19; elim H19; clear H18 H19; unfold Rrelation, E.\n          apply Axiom_SchemeP; split; try apply ord_set; auto.\n        - destruct H16; rewrite H16 in *; clear H14 H15 H16.\n          assert (a ∈ (En_v (∩ En_y y) y)); try apply Axiom_Scheme; Ens.\n          apply H5 in H14; destruct H14; unfold Rrelation, E.\n          apply Axiom_SchemeP; split; try apply ord_set; auto.\n        - destruct H16, H19; rewrite <- H16 in H20.\n          generalize (notin_fix b); intros; contradiction. }\n      { double H17; apply Property_Max in H18; auto; rewrite Equal_Max in H18.\n        rewrite H18 in H16; destruct H16 as [H16 | [H16 | H16]].\n        - assert (a ∈ (En_y y)); try apply Axiom_Scheme; Ens.\n          apply H1 in H19; destruct H19; unfold Rrelation, E.\n          apply Axiom_SchemeP; split; try apply ord_set; auto.\n        - destruct H16; rewrite H16 in H19.\n          generalize (not_bel_and (∩ En_y y) (∩ En_v (∩ En_y y) y)); intros.\n          destruct H20; split; auto.\n        - destruct H16, H19; rewrite <- H19, <- H16 in H7.\n          generalize (notin_fix a); intros; contradiction. }\n      { double H17; apply Property_Max in H18; rewrite H18 in H16.\n        rewrite H17 in *; clear H14 H15 H17; destruct H16 as [H14|[H14|H14]].\n        - assert (b ∈ (En_y y)); try apply Axiom_Scheme; Ens.\n          apply H1 in H15; destruct H15; unfold Rrelation, E.\n          apply Axiom_SchemeP; split; try apply ord_set; auto.\n        - destruct H14; rewrite <- H14 in *.\n          generalize (not_bel_and b (∩ En_v b y)); intros; destruct H16; auto.\n        - destruct H14, H15; rewrite <- H15, <- H14 in H7.\n          generalize (notin_fix b); intros; contradiction. }\nQed.\n\nHint Resolve well_order_cartR : set.\n\n\n(* 178 Theorem  If [u,v] 《 [x,y], then [u,v] ∈ (max[x,y]+1) × (max[x,y]+1). *)\n\nTheorem lele_bel_cart : forall u v x y,\n  Rrelation ([u,v]) ≪ ([x,y]) ->\n  [u,v] ∈ ((PlusOne (Max x y)) × (PlusOne (Max x y))).\nProof.\n  intros.\n  unfold Rrelation, LessLess in H; apply Axiom_Scheme in H.\n  destruct H, H0, H0, H0, H0, H0, H1, H2; apply ord_set in H; destruct H.\n  apply ord_eq in H2; auto; destruct H2; apply ord_set in H.\n  apply ord_set in H4; destruct H, H4; apply ord_eq in H2; auto.\n  apply ord_eq in H5; auto; destruct H2, H5; rewrite <- H2, <- H5 in *.\n  rewrite <- H8, <- H9 in *; clear H H2 H4 H5 H6 H7 H8 H9 x0 x1 x2 x3.\n  assert ((Max u v) ≼ (Max x y)).\n  { unfold LessEqual; destruct H3 as [H3|[H3|H3]]; try tauto. }\n  clear H3; unfold Cartesian in H0, H1; apply Axiom_SchemeP in H0.\n  apply Axiom_SchemeP in H1; destruct H0, H1, H2, H3; unfold R in H2, H3, H4, H5.\n  clear H0 H1; apply Axiom_Scheme in H2; apply Axiom_Scheme in H3; apply Axiom_Scheme in H4.\n  apply Axiom_Scheme in H5; destruct H2, H3, H4, H5, H.\n  - assert ((Max x y) ∈ R).\n    { assert (Ordinal x /\\ Ordinal y); auto; apply ord_bel_eq in H8.\n      destruct H8 as[H8|[H8|H8]]; apply Property_Max in H8;auto;try rewrite H8.\n      - unfold R; apply Axiom_Scheme; split; auto.\n      - rewrite Equal_Max in H8; rewrite H8; unfold R; apply Axiom_Scheme; auto.\n      - unfold R; apply Axiom_Scheme; split; auto. }\n    double H8; apply ordnum_succ_ordnum in H9; unfold R in H8, H9; apply Axiom_Scheme in H8.\n    apply Axiom_Scheme in H9; destruct H8, H9; unfold LessEqual in H.\n    assert ((Max x y) ∈ (PlusOne (Max x y))).\n    { unfold PlusOne; apply bel_union; right; apply Axiom_Scheme; split; auto. }\n    unfold Ordinal, full in H11; destruct H11 as [_ H11]; apply H11 in H12.\n    apply H12 in H; clear H8 H9 H10 H12; assert (Ordinal u /\\ Ordinal v); auto.\n    apply ord_bel_eq in H8; destruct H8 as [H8 | [H8 | H8]].\n    + double H8; apply Property_Max in H9; auto; rewrite H9 in H; clear H9.\n      double H; apply H11 in H9; apply H9 in H8; clear H9 H11; unfold Cartesian.\n      apply Axiom_SchemeP; repeat split; try apply ord_set; auto.\n    + double H8; apply Property_Max in H9; auto; rewrite Equal_Max in H9.\n      rewrite H9 in H; clear H9; double H; apply H11 in H9; apply H9 in H8.\n      clear H9 H11; unfold Cartesian; apply Axiom_SchemeP.\n      repeat split; try apply ord_set; auto.\n    + double H8; apply Property_Max in H9; auto; rewrite H9 in H; rewrite H8.\n      clear H8 H9 H11; apply Axiom_SchemeP; repeat split; try apply ord_set; auto.\n  - rewrite <- H in *; clear H; assert (Ordinal u /\\ Ordinal v); auto.\n    apply ord_bel_eq in H; destruct H as [H | [H | H]].\n    + double H; apply Property_Max in H8; auto; rewrite H8; clear H8.\n      unfold Cartesian; apply Axiom_SchemeP; repeat split; try apply ord_set; Ens.\n      * apply bel_union; tauto.\n      * apply bel_union; right; apply Axiom_Scheme; auto.\n    + double H; apply Property_Max in H8; auto; rewrite Equal_Max in H8.\n      rewrite H8; clear H8; unfold Cartesian; apply Axiom_SchemeP.\n      repeat split; try apply ord_set; auto; try (apply bel_union; tauto).\n      apply bel_union; right; apply Axiom_Scheme; auto.\n    + double H; apply Property_Max in H8; rewrite H8; clear H8; rewrite H at 1.\n      unfold Cartesian; apply Axiom_SchemeP; split; try apply ord_set; auto.\n      split; apply bel_union; right; apply Axiom_Scheme; auto.\nQed.\n\nHint Resolve lele_bel_cart : set.\n\n\n(* 179 Theorem  If x ∈ (C ~ W), then P(x × x) = x. *)\n\nDefinition En_Q u v x0 : Class :=\n  \\{\\ λ a b, Rrelation ([a,b]) ≪ ([u,v]) /\\ [a,b] ∈ x0 × x0 \\}\\.\n\nLemma card_eq_cart : forall x, Ensemble x -> P[x × x] = P[(P[x]) × (P[x])].\nProof.\n  intros.\n  double H; double H; apply Property_PClass in H0.\n  apply card_equiv in H1; apply equiv_com in H1.\n  unfold Equivalent in H1; destruct H1 as [f H1], H1, H2.\n  assert (Ensemble (x × x) /\\ Ensemble ((P[x]) × (P[x]))).\n  { split; apply set_cart; Ens. }\n  apply card_eq in H4; apply H4; clear H4.\n  unfold Equivalent.\n  exists \\{\\ λ a b, a ∈ (x × x) /\\ b = [f[First a], f[Second a]] \\}\\.\n  repeat split; unfold Relation; intros; try PP H4 c d; Ens.\n  - destruct H4; apply Axiom_SchemeP in H4; apply Axiom_SchemeP in H5.\n    destruct H4, H5, H6, H7; rewrite H8, H9; auto.\n  - destruct H4; apply Axiom_SchemeP in H4; apply Axiom_SchemeP in H5.\n    destruct H4, H5; apply Axiom_SchemeP in H6; apply Axiom_SchemeP in H7.\n    destruct H6, H7, H8, H9; rewrite H11 in H10; clear H4 H5 H6 H7 H11.\n    PP H8 a b; PP H9 c d; clear H8 H9; apply Axiom_SchemeP in H4; clear y z.\n    apply Axiom_SchemeP in H5; destruct H4, H5, H6, H7; apply ord_set in H4.\n    apply ord_set in H5; apply ordere_fst_snd in H4; apply ordere_fst_snd in H5.\n    destruct H4, H5; rewrite H4, H5, H11, H12 in H10; clear H4 H5 H11 H12.\n    rewrite <- H2 in H6, H7, H8, H9; destruct H1.\n    apply Property_Value in H6; apply Property_Value in H7; auto.\n    apply Property_Value in H8; apply Property_Value in H9; auto.\n    double H7; double H9; apply Property_ran in H7; apply Property_ran in H11.\n    AssE f[c]; AssE f[d]; apply ord_eq in H10; auto; clear H7 H11 H12 H13.\n    destruct H10; rewrite H7 in H5; rewrite H10 in H9; clear H7 H10.\n    assert ([f[a],a] ∈ f⁻¹ /\\ [f[a],c] ∈ f⁻¹).\n    { AssE [a,f[a]]; AssE [c,f[a]]; apply ord_set in H7; destruct H7.\n      apply ord_set in H10; destruct H10 as [H10 _]; unfold Inverse.\n      split; apply Axiom_SchemeP; split; try apply ord_set; auto. }\n    assert ([f[b],b] ∈ f⁻¹ /\\ [f[b],d] ∈ f⁻¹).\n    { AssE [b,f[b]]; AssE [d,f[b]]; apply ord_set in H10; destruct H10.\n      apply ord_set in H11; destruct H11 as [H11 _]; unfold Inverse.\n      split; apply Axiom_SchemeP; split; try apply ord_set; auto. }\n    apply H4 in H7; apply H4 in H10; rewrite H7, H10; auto.\n  - apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme in H4; destruct H4, H5; apply Axiom_SchemeP in H5; apply H5.\n    + apply Axiom_Scheme; split; Ens; PP H4 a b; exists [f[a],f[b]].\n      double H5; apply Axiom_SchemeP in H6; rewrite <- H2 in H6; destruct H6, H7.\n      destruct H1; apply Property_Value in H7; apply Property_Value in H8; Ens.\n      apply Property_ran in H7; apply Property_ran in H8.\n      apply Axiom_SchemeP; repeat split; try apply ord_set; try split; auto.\n      * apply ord_set; Ens.\n      * apply ord_set in H6; apply ordere_fst_snd in H6; destruct H6.\n        rewrite H6, H10; auto.\n  - apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme in H4; destruct H4, H5; apply Axiom_SchemeP in H5.\n      destruct H5, H6; PP H6 a b; AssE [a,b]; apply ord_set in H9.\n      apply ordere_fst_snd in H9; destruct H9; rewrite H9, H10 in H7; clear H9 H10.\n      rewrite H7 in *; clear H5 H6 H7; apply Axiom_SchemeP in H8; destruct H8,H6.\n      destruct H1; rewrite <- H2 in H6, H7; apply Property_Value in H6; auto.\n      apply Property_Value in H7; auto; apply Property_ran in H6.\n      apply Property_ran in H7; rewrite H3 in H6, H7; unfold Cartesian.\n      apply Axiom_SchemeP; repeat split; auto.\n    + apply Axiom_Scheme; split; Ens; PP H4 a b; clear H4; apply Axiom_SchemeP in H5.\n      destruct H5, H5; rewrite <- H3 in H5, H6; unfold Range in H5, H6.\n      apply Axiom_Scheme in H5; apply Axiom_Scheme in H6; destruct H5, H6, H7, H8.\n      double H7; double H8; apply Property_dom in H9; apply Property_dom in H10.\n      exists [x0,x1]; assert (Ensemble ([x0,x1])); try apply ord_set; Ens.\n      apply Axiom_SchemeP; split; try apply ord_set; split; auto.\n      * rewrite H2 in H9, H10; unfold Cartesian; apply Axiom_SchemeP.\n        repeat split; try apply ord_set; Ens.\n      * apply ord_set in H11; apply ordere_fst_snd in H11; destruct H1, H11.\n        rewrite H11, H13; clear H11 H13; apply Property_Value in H9; auto.\n        apply Property_Value in H10; auto; add ([x0, a] ∈ f) H9.\n        add ([x1, b] ∈ f) H10; apply H1 in H9; apply H1 in H10.\n        rewrite H9, H10; auto.\nQed.\n\nLemma equiv_cart_sing : forall x x0, Ensemble x0 -> x ≈ x × [x0].\nProof.\n  intros.\n  unfold Equivalent; exists (\\{\\ λ a b, a ∈ x /\\ b = [a,x0] \\}\\).\n  repeat split; intros; try (unfold Relation; intros; PP H0 a b; Ens).\n  - destruct H0; apply Axiom_SchemeP in H0; apply Axiom_SchemeP in H1.\n    destruct H0, H1, H2, H3; rewrite H4, H5; auto.\n  - destruct H0; apply Axiom_SchemeP in H0; apply Axiom_SchemeP in H1.\n    destruct H0, H1; apply Axiom_SchemeP in H2; apply Axiom_SchemeP in H3.\n    destruct H2, H3, H4, H5; apply ord_set in H0; destruct H0.\n    rewrite H6 in H7; apply ord_eq in H7; try apply H7; auto.\n  - apply Axiom_Extent; split; intros.\n    + unfold Domain in H0; apply Axiom_Scheme in H0; destruct H0, H1.\n      apply Axiom_SchemeP in H1; apply H1.\n    + unfold Domain; apply Axiom_Scheme; split; Ens; exists [z,x0].\n      apply Axiom_SchemeP; repeat split; auto; apply ord_set; split; Ens.\n      apply ord_set; split; Ens.\n  - apply Axiom_Extent; split; intros.\n    + unfold Range in H0; apply Axiom_Scheme in H0; destruct H0, H1.\n      apply Axiom_SchemeP in H1; destruct H1, H2; rewrite H3 in *.\n      unfold Cartesian; apply Axiom_SchemeP; repeat split; auto.\n      unfold Singleton; apply Axiom_Scheme; split; Ens.\n    + unfold Range; apply Axiom_Scheme; split; Ens; PP H0 a b.\n      apply Axiom_SchemeP in H1; destruct H1, H2; exists a.\n      apply Axiom_SchemeP; repeat split; auto; try apply ord_set; Ens.\n      apply ord_set in H1; apply ord_eq; auto; split; auto.\n      unfold Singleton in H3; apply Axiom_Scheme in H3; destruct H3.\n      apply H4; apply bel_universe_set; Ens.\nQed.\n\nLemma lem_notint_card_cart_eq : forall f u v x0 ,\n  Ensemble f[[u,v]] -> Ordinal f[[u, v]] -> x0 ∈ C ->\n  P[f[[u, v]]] ∈ x0 -> f[[u, v]] ∈ x0.\nProof.\n  intros; double H1.\n  apply card_iff_eq in H1; destruct H1; unfold C in H3.\n  apply Axiom_Scheme in H3; destruct H3 as [_ H3]; unfold Cardinal_Number in H3.\n  destruct H3 as [H3 _]; apply Axiom_Scheme in H3; destruct H3 as [_ H3].\n  assert (Ordinal f[[u, v]] /\\ Ordinal x0); auto.\n  apply ord_bel_eq in H5; destruct H5 as [H5 | [H5 | H5]]; auto.\n  - unfold Ordinal in H0; destruct H0 as [_ H0]; apply H0 in H5.\n    add (x0 ⊂ f [[u, v]]) H; apply card_le in H; clear H5.\n    rewrite H4 in H; unfold LessEqual in H; destruct H.\n    + generalize (not_bel_and x0 P[f[[u,v]]]); intros; destruct H5; auto.\n    + rewrite <- H in H2; generalize (notin_fix x0); contradiction.\n  - rewrite H5, H4 in H2; generalize (notin_fix x0); contradiction.\nQed.\n\nTheorem notint_card_cart_eq : forall x, x ∈ (C ~ W) -> P[x × x] = x.\nProof.\n  intros.\n  generalize well_order_E; intros.\n  unfold WellOrdered in H0; destruct H0; clear H0.\n  generalize (classic (\\{ λ z, z ∈ (C ~ W) /\\ P[z × z] <> z \\} = Φ)); intros.\n  destruct H0.\n  - generalize (classic (P[x × x] = x)); intros; destruct H2; auto.\n    assert (x ∈ Φ). { rewrite <- H0; apply Axiom_Scheme; Ens. }\n    generalize (not_bel_zero x); intros; contradiction.\n  - assert (\\{ λ z, z ∈ (C ~ W) /\\ P[z × z] <> z \\} ⊂ C /\\\n            \\{ λ z, z ∈ (C ~ W) /\\ P[z × z] <> z \\} ≠ Φ).\n    { split; auto; unfold Subclass; intros; apply Axiom_Scheme in H2.\n      destruct H2, H3; apply bel_inter in H3; apply H3. }\n    apply H1 in H2; clear H0 H1; destruct H2; unfold FirstMember in H0.\n    destruct H0; apply Axiom_Scheme in H0; destruct H0, H2.\n    generalize well_order_cartR, ord_not_set_R; intros; destruct H5.\n    assert (Ensemble x0 /\\ Ensemble x0); Ens; apply set_cart in H7.\n    assert (x0 × x0 ⊂ R × R).\n    { unfold Difference in H2; apply bel_inter in H2; destruct H2 as [H2 _].\n      unfold C in H2; apply Axiom_Scheme in H2; destruct H2 as [_ H2].\n      destruct H2 as [H2 _]; unfold Ordinal_Number in H2; unfold Ordinal in H5.\n      destruct H5 as [_ H5]; apply H5 in H2; clear H5.\n      unfold Cartesian, Subclass; intros; PP H5 a b; apply Axiom_SchemeP in H8.\n      destruct H8, H9; apply H2 in H9; apply H2 in H10; apply Axiom_SchemeP; Ens. }\n    apply lem_order_pre_sec_sub with (y:= x0 × x0) in H4; auto; clear H8.\n    apply ord_well_order in H5; add (WellOrdered E R) H4; auto; clear H5.\n    apply well_order_pre_set in H4; auto; clear H6 H7; destruct H4 as [f H4], H4, H5.\n    unfold Order_PXY in H5; destruct H5, H7, H8; clear H4 H5 H7; double H8.\n    apply order_pre_fun1_inv in H4; destruct H4 as [H4 _], H9.\n    assert (forall u v, [u,v] ∈ (x0 × x0) -> f[[u,v]] ∈ x0).\n    { intros.\n      assert ((En_Q u v x0) ⊂ ((PlusOne (Max u v)) × (PlusOne (Max u v)))).\n      { unfold Subclass; intros; PP H10 a b; apply Axiom_SchemeP in H11.\n        destruct H11, H12; apply lele_bel_cart; auto. }\n      assert (En_Q u v x0 ≈ f[[u, v]]).\n      { rewrite <- H6 in H9; apply Property_Value in H9; try apply H4.\n        apply Property_ran in H9; clear H10; unfold Equivalent.\n        exists (f|(En_Q u v x0)); destruct H4; double H4; double H10.\n        apply (fun_res_fun f (En_Q u v x0)) in H11; destruct H11, H13.\n        apply (fun_res_fun f⁻¹ f[[u, v]]) in H12; destruct H12, H15.\n        split; try split; auto; unfold Function, Relation.\n        - split; intros; try PP H17 a b; Ens; unfold Inverse in H17.\n          destruct H17; apply Axiom_SchemeP in H17; apply Axiom_SchemeP in H18.\n          destruct H17, H18; unfold Restriction in H19, H20.\n          apply bel_inter in H19; apply bel_inter in H20.\n          destruct H19 as [H19 _], H20 as [H20 _].\n          assert ([x1,z] ∈ f⁻¹ /\\ [x1,y] ∈ f⁻¹).\n          { unfold Inverse; split; apply Axiom_SchemeP; auto. }\n          apply H10 in H21; symmetry; auto.\n        - assert (En_Q u v x0 ⊂ dom(f)).\n          { unfold Subclass, En_Q; intros; PP H17 a b; rewrite H6.\n            apply Axiom_SchemeP in H18; apply H18. }\n          apply inter_sub in H17; rewrite H17 in H13; auto.\n        - apply Axiom_Extent; split; intros.\n          + unfold Range in H17; apply Axiom_Scheme in H17; destruct H17, H18.\n            unfold Restriction in H18; apply bel_inter in H18; destruct H18.\n            unfold Cartesian in H19; apply Axiom_SchemeP in H19.\n            destruct H19 as [_ H19], H19 as [H19 _]; PP H19 a b; clear H19.\n            apply Axiom_SchemeP in H20; destruct H20, H20; rewrite <- H6 in H21.\n            double H21; apply Property_Value in H22; auto.\n            add ([[a, b], z] ∈ f) H22; clear H18 H19; apply H4 in H22.\n            rewrite <- H22; clear H22; apply Property_Value' in H9; auto.\n            apply Property_dom in H9; unfold Order_Pr in H5.\n            assert ([a,b] ∈ dom( f) /\\ [u,v] ∈ dom( f) /\\ \n            Rrelation ([a,b]) ≪ ([u,v])); auto.\n            apply H5 in H18; unfold Rrelation, E in H18.\n            apply Axiom_SchemeP in H18; apply H18.\n          + unfold Range; apply Axiom_Scheme; split; Ens; double H8; double H9.\n            apply sec_R_ord in H18; destruct H18 as [_ H18].\n            apply H18 in H19; double H17; apply H19 in H20; clear H19 H18.\n            double H20; apply Axiom_Scheme in H19; destruct H19, H20; exists x1.\n            unfold Restriction; apply bel_inter; split; auto.\n            unfold Cartesian; apply Axiom_SchemeP; split; Ens.\n            split; try apply bel_universe_set; Ens; clear H H1 H2 H3 H13 H14 H15 H16.\n            apply order_pre_fun1_inv in H5; destruct H5 as [_ H5].\n            unfold Order_Pr in H5; rewrite <- dom_ran_inv' in H5.\n            assert (z∈ran(f) /\\ f[[u,v]]∈ran(f) /\\ Rrelation z E f[[u,v]]).\n            { repeat split; auto; unfold Rrelation, E; apply Axiom_SchemeP.\n              split; auto; apply ord_set; Ens. }\n            apply H5 in H; pattern f at 3 in H.\n            rewrite <- rel_inv_fix in H; try apply H4.\n            apply Property_Value' in H9; auto; apply Property_dom in H9.\n            rewrite dom_ran_inv in H9; double H20; apply Property_ran in H2.\n            rewrite<-dom_ran_inv''' in H; try rewrite rel_inv_fix; try apply H4;auto.\n            rewrite dom_ran_inv' in H2; apply Property_Value in H2; auto.\n            assert ([z,x1] ∈ f ⁻¹).\n            { apply Axiom_SchemeP; split; auto; apply ord_set.\n              AssE [x1,z]; apply ord_set in H3; destruct H3; auto. }\n            add ([z,x1] ∈ f ⁻¹) H2; apply H10 in H2; rewrite H2 in H.\n            apply Property_dom in H1; rewrite H6 in H1; clear H2 H3.\n            PP H1 a b; unfold En_Q; apply Axiom_SchemeP; repeat split; Ens. }\n      assert ([u,v] ∈ (W × W) -> f[[u,v]] ∈ x0).\n      { clear H9; intros; clear H x.\n        assert (W × W ⊂ x0 × x0).\n        { unfold Subclass; intros; PP H a b; apply Axiom_SchemeP in H12.\n          destruct H12, H13; double H13; double H14; unfold W in H15, H16.\n          apply Axiom_Scheme in H15; apply Axiom_Scheme in H16; destruct H15 as [_ H15].\n          destruct H16 as [_ H16], H15 as [H15 _], H16 as [H16 _].\n          apply Axiom_SchemeP; split; auto; apply bel_inter in H2; destruct H2.\n          unfold C in H2; apply Axiom_Scheme in H2; destruct H2 as [_ H2].\n          unfold Cardinal_Number, Ordinal_Number in H2; destruct H2 as [H2 _].\n          apply Axiom_Scheme in H2; destruct H2 as [_ H2]; apply Axiom_Scheme in H17.\n          destruct H17 as [_ H17]; add (Ordinal x0) H15; add (Ordinal x0) H16.\n          apply ord_bel_eq in H15; apply ord_bel_eq in H16.\n          destruct H15 as [H15|[H15|H15]], H16 as [H16|[H16|H16]]; auto.\n          - destruct H17; apply Axiom_Scheme; split; Ens.\n            apply (int_bel_int b _); auto; apply Axiom_Scheme in H14; apply H14.\n          - rewrite H16 in H14; contradiction.\n          - destruct H17; apply Axiom_Scheme; split; Ens.\n            apply (int_bel_int a _); auto; apply Axiom_Scheme in H13; apply H13.\n          - destruct H17; apply Axiom_Scheme; split; Ens.\n            apply (int_bel_int b _); auto; apply Axiom_Scheme in H14; apply H14.\n          - rewrite H16 in H14; contradiction.\n          - rewrite H15 in H13; contradiction.\n          - rewrite H15 in H13; contradiction.\n          - rewrite H15 in H13; contradiction. }\n      double H9; apply H in H9; rewrite <- H6 in H9.\n      apply Axiom_SchemeP in H12; destruct H12, H13.\n      assert (PlusOne (Max u v) ∈ W).\n      { apply int_succ; double H13; double H14; unfold W in H15, H16.\n        apply Axiom_Scheme in H15; apply Axiom_Scheme in H16; destruct H15 as [_ H15].\n        destruct H16 as [_ H16], H15 as [H15 _], H16 as [H16 _].\n        assert (Ordinal u /\\ Ordinal v); auto; apply ord_bel_eq in H17.\n        destruct H17 as [H17|[H17|H17]]; try apply Property_Max in H17; auto.\n        - rewrite H17; auto.\n        - rewrite Equal_Max in H17; rewrite H17; auto.\n        - rewrite H17; auto. }\n      assert (Finite (PlusOne (Max u v)) /\\ Finite (PlusOne (Max u v))).\n      { double H15; generalize W_sub_C; intros; apply H17 in H16.\n        clear H17; apply card_iff_eq in H16; destruct H16 as [_ H16].\n        unfold Finite; rewrite H16; auto. }\n      apply fin_cart in H16; unfold Finite in H16.\n      assert (Ensemble ((PlusOne (Max u v)) × (PlusOne (Max u v))) /\\\n      ((En_Q u v x0) ⊂ (PlusOne (Max u v)) × (PlusOne (Max u v)))).\n      { split; auto; apply set_cart; Ens. }\n      clear H10 H15; elim H17; intros; apply card_le in H17.\n      assert (P[En_Q u v x0] = P[f[[u, v]]]).\n      { apply sub_set in H15; auto; clear H10 H12 H13 H14 H16 H17.\n        apply Property_Value in H9; try apply H4; apply Property_ran in H9.\n        apply card_eq; Ens. }\n      rewrite H18 in H17; clear H11 H10 H15 H18.\n      apply Property_Value in H9; try apply H4; apply Property_ran in H9.\n      clear H12 H13 H14; apply H8 in H9; unfold R in H9; apply Axiom_Scheme in H9.\n      destruct H9; apply bel_inter in H2; double H2; destruct H11 as [H11 _].\n      apply Axiom_Scheme in H11; destruct H11 as [_ H11], H11 as [H11 _].\n      apply Axiom_Scheme in H11; destruct H11 as [_ H11].\n      assert (W ⊂ x0).\n      { unfold Subclass; intros; unfold W in H12; apply Axiom_Scheme in H12.\n        destruct H12; double H13; destruct H14 as [H14 _], H2.\n        apply Axiom_Scheme in H15; destruct H15 as [_ H15].\n        add (Ordinal x0) H14; apply ord_bel_eq in H14.\n        destruct H14 as [H14 | [H14 | H14]]; auto.\n        - destruct H15; apply Axiom_Scheme; split; Ens.\n          apply (int_bel_int z _); auto.\n        - destruct H15; rewrite <- H14; apply Axiom_Scheme; Ens. }\n      apply H12 in H16; clear H12.\n      assert (P[f[[u, v]]] ∈ x0).\n      { unfold LessEqual in H17; destruct H17; try rewrite H12; auto.\n        destruct H11 as [_ H11]; apply H11 in H16; apply H16 in H12; auto. }\n      apply lem_notint_card_cart_eq in H12; destruct H2; auto. }\n      intros; generalize (classic (x0 = W)); intros; destruct H13.\n      - rewrite H13 in H9; apply H12; auto.\n      - double H9; rewrite <- H6 in H9.\n        unfold Cartesian in H14; apply Axiom_SchemeP in H14; destruct H14, H15.\n        clear H x; unfold Difference in H2; apply bel_inter in H2.\n        destruct H2 as [H2 _]; double H2; unfold C in H2; apply Axiom_Scheme in H2.\n        destruct H2 as [_ H2]; unfold Cardinal_Number, Ordinal_Number in H2.\n        destruct H2 as [H2 _]; apply Axiom_Scheme in H2; destruct H2 as [_ H2].\n        clear H0; double H2; double H2; add (u ∈ x0) H2; add (v ∈ x0) H17.\n        apply ord_bel_ord in H2; apply ord_bel_ord in H17.\n        assert (Ordinal u /\\ Ordinal v); auto.\n        apply ord_bel_eq in H18; generalize (classic (Max u v ∈ W)); intros.\n        destruct H18 as [H18 | [H18 | H18]]; double H18.\n        + apply Property_Max in H20; auto; rewrite H20 in *.\n          clear H20; destruct H19.\n          * apply H12; apply Axiom_SchemeP; repeat split; auto.\n            apply Axiom_Scheme in H19; destruct H19; apply Axiom_Scheme; split; Ens.\n            apply int_bel_int in H18; auto.\n          * assert (v ∈ (R ~ W)).\n            { unfold Difference; apply bel_inter; split; apply Axiom_Scheme; Ens. }\n            apply notint_card_plus_eq in H20; clear H6 H7 H12 H14; destruct H4 as[H4 _].\n            apply Property_Value in H9;auto; apply Property_ran in H9.\n            apply H8 in H9; clear H8; assert (v ∈ R). apply Axiom_Scheme; Ens.\n            apply ordnum_succ_ordnum in H6; AssE (PlusOne v); clear H6.\n            assert(Ensemble((PlusOne v)×(PlusOne v)));try apply set_cart;Ens.\n            double H10; apply sub_set in H8; auto.\n            add (En_Q u v x0 ⊂ (PlusOne v) × (PlusOne v)) H6; clear H10.\n            apply card_le in H6; apply card_eq in H11; Ens.\n            rewrite H11 in H6; clear H8 H11; double H7; apply card_eq_cart in H7.\n            rewrite H7 in H6; clear H7; double H.\n            apply card_iff_eq in H7; destruct H7 as [_ H7].\n            assert (P[v] ≺ P[x0]).\n            { assert (Ordinal v /\\ Ordinal x0); auto; apply ord_sub_iff_le in H10.\n              assert (v ≼ x0); unfold LessEqual; try tauto; apply H10 in H11.\n              assert (Ensemble x0 /\\ v ⊂ x0); Ens; apply card_le in H12.\n              clear H10 H11; unfold LessEqual in H12; destruct H12; auto.\n              apply card_eq in H10; Ens; apply equiv_com in H10.\n              unfold C in H; apply Axiom_Scheme in H; destruct H.\n              apply H11 in H16; try contradiction; apply Axiom_Scheme; Ens. }\n            assert (P[(P[PlusOne v]) × (P[PlusOne v])] = P[PlusOne v]).\n            { apply Property_PClass in H8.\n              generalize (classic (P[(P[PlusOne v]) × (P[PlusOne v])] =\n              P[PlusOne v])); intros; destruct H11; auto.\n              assert (P[PlusOne v] ∈ \\{ λ z, z ∈ (C ~ W) /\\ P[z × z] <> z \\}).\n              { apply Axiom_Scheme; repeat split; Ens.\n                unfold Difference; apply bel_inter; split; auto.\n                apply Axiom_Scheme; split; Ens; intro; symmetry in H20.\n                assert (v ∈ (PlusOne v)).\n                { unfold PlusOne; apply bel_union; right; unfold Singleton.\n                  apply Axiom_Scheme; split; Ens. }\n                apply fin_card_eq in H20; auto.\n                - rewrite H20 in H14; generalize (notin_fix v); contradiction.\n                - assert (v ≼ (PlusOne v)); unfold LessEqual; auto.\n                  apply ord_sub_iff_le in H21; auto; clear H22; split; auto.\n                  assert (v ∈ R). apply Axiom_Scheme; Ens.\n                  apply ordnum_succ_ordnum in H22; apply Axiom_Scheme in H22; apply H22. }\n              apply H1 in H12; destruct H12; unfold Rrelation, E.\n              apply Axiom_SchemeP; split; try apply ord_set; Ens.\n              rewrite H20, <- H7; auto. }\n            rewrite H11, H20 in H6; clear H11 H20; rewrite H7 in H10.\n            assert (P[f[[u, v]]] ∈ x0).\n            { unfold LessEqual in H6; destruct H6; try rewrite H6; auto.\n              destruct H0; apply H11 in H10; apply H10 in H6; auto. }\n            unfold R in H9; apply Axiom_Scheme in H9; destruct H9.\n            apply lem_notint_card_cart_eq in H11; auto.\n        + apply Property_Max in H20; auto; rewrite Equal_Max in H20.\n          rewrite H20 in *; clear H20; destruct H19.\n          * apply H12; apply Axiom_SchemeP; repeat split; auto.\n            apply Axiom_Scheme in H19; destruct H19; apply Axiom_Scheme; split; Ens.\n            apply int_bel_int in H18; auto.\n          * assert (u ∈ (R ~ W)).\n            { unfold Difference; apply bel_inter; split; apply Axiom_Scheme; Ens. }\n            apply notint_card_plus_eq in H20; clear H6 H7 H12 H14; destruct H4 as[H4 _].\n            apply Property_Value in H9;auto; apply Property_ran in H9.\n            apply H8 in H9; clear H8; assert (u ∈ R). apply Axiom_Scheme; Ens.\n            apply ordnum_succ_ordnum in H6; AssE (PlusOne u); clear H6.\n            assert(Ensemble((PlusOne u)×(PlusOne u)));try apply set_cart;Ens.\n            double H10; apply sub_set in H8; auto.\n            add (En_Q u v x0 ⊂ (PlusOne u) × (PlusOne u)) H6; clear H10.\n            apply card_le in H6; apply card_eq in H11; Ens.\n            rewrite H11 in H6; clear H8 H11; double H7; apply card_eq_cart in H7.\n            rewrite H7 in H6; clear H7; double H.\n            apply card_iff_eq in H7; destruct H7 as [_ H7].\n            assert (P[u] ≺ P[x0]).\n            { assert (Ordinal u /\\ Ordinal x0); auto; apply ord_sub_iff_le in H10.\n              assert (u ≼ x0); unfold LessEqual; try tauto; apply H10 in H11.\n              assert (Ensemble x0 /\\ u ⊂ x0); Ens; apply card_le in H12.\n              clear H10 H11; unfold LessEqual in H12; destruct H12; auto.\n              apply card_eq in H10; Ens; apply equiv_com in H10.\n              unfold C in H; apply Axiom_Scheme in H; destruct H.\n              apply H11 in H15; try contradiction; apply Axiom_Scheme; Ens. }\n            assert (P[(P[PlusOne u]) × (P[PlusOne u])] = P[PlusOne u]).\n            { apply Property_PClass in H8.\n              generalize (classic (P[(P[PlusOne u]) × (P[PlusOne u])] =\n              P[PlusOne u])); intros; destruct H11; auto.\n              assert (P[PlusOne u] ∈ \\{ λ z, z ∈ (C ~ W) /\\ P[z × z] <> z \\}).\n              { apply Axiom_Scheme; repeat split; Ens.\n                unfold Difference; apply bel_inter; split; auto.\n                apply Axiom_Scheme; split; Ens; intro; symmetry in H20.\n                assert (u ∈ (PlusOne u)).\n                { unfold PlusOne; apply bel_union; right; unfold Singleton.\n                  apply Axiom_Scheme; split; Ens. }\n                apply fin_card_eq in H20; auto.\n                - rewrite H20 in H14; generalize (notin_fix u); contradiction.\n                - assert (u ≼ (PlusOne u)); unfold LessEqual; auto.\n                  apply ord_sub_iff_le in H21; auto; clear H22; split; auto.\n                  assert (u ∈ R). apply Axiom_Scheme; Ens.\n                  apply ordnum_succ_ordnum in H22; apply Axiom_Scheme in H22; apply H22. }\n              apply H1 in H12; destruct H12; unfold Rrelation, E.\n              apply Axiom_SchemeP; split; try apply ord_set; Ens.\n              rewrite H20, <- H7; auto. }\n            rewrite H11, H20 in H6; clear H11 H20; rewrite H7 in H10.\n            assert (P[f[[u, v]]] ∈ x0).\n            { unfold LessEqual in H6; destruct H6; try rewrite H6; auto.\n              destruct H0; apply H11 in H10; apply H10 in H6; auto. }\n            unfold R in H9; apply Axiom_Scheme in H9; destruct H9.\n            apply lem_notint_card_cart_eq in H11; auto.\n        + apply Property_Max in H20; auto; rewrite H18, H20 in *.\n          clear H16 H18 H20; destruct H19.\n          * apply H12; apply Axiom_SchemeP; repeat split; auto.\n          * assert (v ∈ (R ~ W)).\n            { unfold Difference; apply bel_inter; split; apply Axiom_Scheme; Ens. }\n            apply notint_card_plus_eq in H18; clear H6 H7 H12 H14; destruct H4 as[H4 _].\n            apply Property_Value in H9; auto; apply Property_ran in H9.\n            apply H8 in H9; clear H8; assert (v ∈ R). apply Axiom_Scheme; Ens.\n            apply ordnum_succ_ordnum in H6; AssE (PlusOne v); clear H6.\n            assert(Ensemble((PlusOne v)×(PlusOne v)));try apply set_cart;Ens.\n            double H10; apply sub_set in H8; auto.\n            add (En_Q v v x0 ⊂ (PlusOne v) × (PlusOne v)) H6; clear H10.\n            apply card_le in H6; apply card_eq in H11; Ens.\n            rewrite H11 in H6; clear H8 H11; double H7; apply card_eq_cart in H7.\n            rewrite H7 in H6; clear H7; double H.\n            apply card_iff_eq in H7; destruct H7 as [_ H7].\n            assert (P[v] ≺ P[x0]).\n            { assert (Ordinal v /\\ Ordinal x0); auto; apply ord_sub_iff_le in H10.\n              assert (v ≼ x0); unfold LessEqual; try tauto; apply H10 in H11.\n              assert (Ensemble x0 /\\ v ⊂ x0); Ens; apply card_le in H12.\n              clear H10 H11; unfold LessEqual in H12; destruct H12; auto.\n              apply card_eq in H10; Ens; apply equiv_com in H10.\n              unfold C in H; apply Axiom_Scheme in H; destruct H.\n              apply H11 in H15; try contradiction; apply Axiom_Scheme; Ens. }\n            assert (P[(P[PlusOne v]) × (P[PlusOne v])] = P[PlusOne v]).\n            { apply Property_PClass in H8.\n              generalize (classic (P[(P[PlusOne v]) × (P[PlusOne v])] =\n              P[PlusOne v])); intros; destruct H11; auto.\n              assert (P[PlusOne v] ∈ \\{ λ z, z ∈ (C ~ W) /\\ P[z × z] <> z \\}).\n              { apply Axiom_Scheme; repeat split; Ens.\n                unfold Difference; apply bel_inter; split; auto.\n                apply Axiom_Scheme; split; Ens; intro; symmetry in H18.\n                assert (v ∈ (PlusOne v)).\n                { unfold PlusOne; apply bel_union; right; unfold Singleton.\n                  apply Axiom_Scheme; split; Ens. }\n                apply fin_card_eq in H18; auto.\n                - rewrite H18 in H14; generalize (notin_fix v); contradiction.\n                - assert (v ≼ (PlusOne v)); unfold LessEqual; auto.\n                  apply ord_sub_iff_le in H19; auto; clear H20; split; auto.\n                  assert (v ∈ R). apply Axiom_Scheme; Ens.\n                  apply ordnum_succ_ordnum in H20; apply Axiom_Scheme in H20; apply H20. }\n              apply H1 in H12; destruct H12; unfold Rrelation, E.\n              apply Axiom_SchemeP; split; try apply ord_set; Ens.\n              rewrite H18, <- H7; auto. }\n            rewrite H11, H18 in H6; clear H11 H18; rewrite H7 in H10.\n            assert (P[f[[v, v]]] ∈ x0).\n            { unfold LessEqual in H6; destruct H6; try rewrite H6; auto.\n              destruct H0; apply H11 in H10; apply H10 in H6; auto. }\n            unfold R in H9; apply Axiom_Scheme in H9; destruct H9.\n            apply lem_notint_card_cart_eq in H11; auto. }\n    assert (P[x0 × x0] ≼ x0).\n    { assert (P[dom(f)] = P[ran(f)]).\n      { apply card_eq; unfold Equivalent; Ens.\n        assert (Ensemble x0 /\\ Ensemble x0); auto.\n        apply set_cart in H10; rewrite <- H6 in H10; split; auto.\n        apply Axiom_Substitution; auto; apply H4. }\n      assert (ran(f) ⊂ x0).\n      { unfold Subclass; intros; unfold Range in H11; apply Axiom_Scheme in H11.\n        destruct H11, H12; double H12; apply Property_dom in H13; double H13.\n        apply Property_Value in H13; try apply H4; add ([x1, f[x1]] ∈ f) H12.\n        apply H4 in H12; rewrite H12; clear H12 H13; rewrite H6 in H14.\n        PP H14 a b; apply H9 in H12; auto. }\n      add (ran( f) ⊂ x0) H0; apply card_le in H0; unfold Difference in H2.\n      clear H11; apply bel_inter in H2; destruct H2 as [H2 _].\n      apply card_iff_eq in H2; destruct H2 as [_ H2]; rewrite H2 in H0.\n      rewrite <- H6, H10; auto. }\n    unfold LessEqual in H10; destruct H10; try contradiction.\n    assert (P[x0] ≼ P[x0 × x0]).\n    { unfold Difference in H2; apply bel_inter in H2; destruct H2.\n      unfold Complement in H11; apply Axiom_Scheme in H11; destruct H11 as [_ H11].\n      generalize (classic (x0 = Φ)); intros; destruct H12.\n      - rewrite H12 in H11; generalize (zero_not_int x); intros.\n        destruct H13 as [H13 _]; contradiction.\n      - apply not_zero_exist_bel in H12; destruct H12 as [z H12].\n        assert (P[x0] = P[x0 × [z]]).\n        { apply card_eq; try split; auto; try apply equiv_cart_sing; Ens.\n          apply set_cart; split; try apply sing_set; Ens. }\n        rewrite H13; apply card_le; split; try apply set_cart; auto.\n        unfold Subclass; intros; PP H14 a b; apply Axiom_SchemeP in H15.\n        destruct H15, H16; unfold Singleton in H17; apply Axiom_Scheme in H17.\n        destruct H17; apply Axiom_SchemeP; repeat split; auto.\n        rewrite H18; try apply bel_universe_set; Ens. }\n    unfold LessEqual in H11; apply bel_inter in H2; destruct H2 as [H2 _].\n    double H2; apply card_iff_eq in H2; destruct H2 as [_ H2], H11.\n    + unfold C in H12; apply Axiom_Scheme in H12; destruct H12 as [_ H12].\n      unfold Cardinal_Number, Ordinal_Number in H12; destruct H12 as [H12 _].\n      apply Axiom_Scheme in H12; destruct H12 as [_ H12], H12 as [_ H12].\n      unfold full in H12; apply H12 in H10; apply H10 in H11.\n      rewrite H2 in H11; generalize (notin_fix x0); intros; contradiction.\n    + rewrite <- H11, H2 in H10; generalize (notin_fix x0); contradiction.\nQed.\n\nHint Resolve notint_card_cart_eq : set.\n\n\n(* 180 Theorem  If x and y are non-empty members of C, one of which fails to\n   belong to W, then P[x×y] = max[P[x],P[y]]. *)\n\nTheorem Theorem180_Not :\n  exists x y, x ∈ C /\\ y ∈ C /\\ x ∉ W /\\ P[x × y] <> Max P[x] P[y].\nProof.\n  exists W, Φ; generalize (zero_not_int Φ); intros.\n  destruct H as [H _]; double H; apply W_sub_C in H0.\n  repeat split; try apply W_bel_C; try apply notin_fix; auto.\n  generalize W_bel_C; intros; apply card_iff_eq in H0.\n  apply card_iff_eq in H1; destruct H0 as [_ H0], H1 as [_ H1].\n  assert (W × Φ = Φ).\n  { apply Axiom_Extent; split; intros.\n    - PP H2 a b; apply Axiom_SchemeP in H3; destruct H3, H4.\n      generalize (not_bel_zero b); intros; contradiction.\n    - generalize (not_bel_zero z); intros; contradiction. }\n  rewrite H2, H0, H1; clear H0 H1 H2; double H; unfold W in H0.\n  apply Axiom_Scheme in H0; destruct H0 as [_ H0], H0 as [H0 _].\n  generalize Property_W; intros; double H.\n  apply Property_Max in H2; auto; rewrite Equal_Max in H2; rewrite H2.\n  intro; rewrite H3 in H; generalize (notin_fix W); contradiction.\nQed.\n\nLemma Lemma180 : forall x y, x × y ≈ y × x.\nProof.\n  intros.\n  unfold Equivalent; exists \\{\\ λ a b, a ∈ (x × y) /\\ b ∈ [a]⁻¹ \\}\\.\n  repeat split; intros; try (unfold Relation; intros; PP H a b; Ens).\n  - destruct H; apply Axiom_SchemeP in H; apply Axiom_SchemeP in H0.\n    destruct H, H0, H1, H2; unfold Singleton in H3, H4.\n    PP H3 a b; PP H4 c d; clear H1 H2 H3 H4; apply Axiom_SchemeP in H5.\n    apply Axiom_SchemeP in H6; destruct H5, H6; apply Axiom_Scheme in H2.\n    apply Axiom_Scheme in H4; destruct H2, H4; clear H1 H2 H3 H4.\n    apply ord_set in H; apply ord_set in H0; destruct H.\n    destruct H0 as [_ H0]; assert (x0 ∈ μ); try apply bel_universe_set; Ens.\n    double H2; apply H5 in H2; apply H6 in H3; clear H5 H6.\n    rewrite <- H3 in H2; clear H3; apply ord_set in H1; destruct H1.\n    apply ord_eq in H2; auto; destruct H2; rewrite H2, H4; auto.\n  - destruct H; apply Axiom_SchemeP in H; apply Axiom_SchemeP in H0.\n    destruct H, H0; apply Axiom_SchemeP in H1; apply Axiom_SchemeP in H2.\n    destruct H1, H2; clear H H0 H1 H2; destruct H3, H4.\n    PP H0 a b; PP H2 c d; apply Axiom_SchemeP in H3; apply Axiom_SchemeP in H4.\n    destruct H3, H4; apply Axiom_Scheme in H5; apply Axiom_Scheme in H6.\n    destruct H5, H6; rewrite H7 in H8; try apply bel_universe_set; Ens.\n    apply H8; apply bel_universe_set; Ens.\n  - apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme in H; destruct H, H0.\n      apply Axiom_SchemeP in H0; apply H0.\n    + apply Axiom_Scheme; split; Ens; PP H a b; exists [b,a].\n      apply Axiom_SchemeP; assert (Ensemble ([a,b])); Ens.\n      apply ord_set in H1; destruct H1.\n      split; try (apply ord_set; split; apply ord_set; Ens).\n      split; auto; unfold Inverse; apply Axiom_SchemeP.\n      split; try apply ord_set; auto; unfold Singleton.\n      apply Axiom_Scheme; split; try apply ord_set; Ens.\n  - apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme in H; destruct H, H0.\n      apply Axiom_SchemeP in H0; destruct H0, H1; PP H1 a b; clear H1.\n      apply Axiom_SchemeP in H3; destruct H3, H3; unfold Inverse in H2.\n      PP H2 c d; clear H2; apply Axiom_SchemeP in H5; destruct H5.\n      clear H0 H2; unfold Singleton in H5; apply Axiom_Scheme in H5.\n      destruct H5; apply ord_set in H0.\n      assert ([a, b] ∈ μ); try apply bel_universe_set; Ens; apply H2 in H5.\n      apply ord_eq in H5; auto; clear H0 H2; destruct H5.\n      rewrite H0, H2; unfold Cartesian; apply Axiom_SchemeP.\n      repeat split; try apply ord_set; Ens.\n    + unfold Range; apply Axiom_Scheme; split; Ens; PP H a b.\n      apply Axiom_SchemeP in H0; destruct H0, H1; double H0; exists [b,a].\n      apply ord_set in H3; destruct H3; apply Axiom_SchemeP.\n      repeat split; try (apply ord_set; split; apply ord_set; Ens).\n      * unfold Cartesian; apply Axiom_SchemeP; repeat split; auto.\n        apply ord_set; split; auto.\n      * unfold Inverse, Singleton; apply Axiom_SchemeP; split; auto.\n        apply Axiom_Scheme; split; try apply ord_set; Ens.\nQed.\n\nLemma Lemma180' : forall x y,\n  x ∈ C -> y ∈ C -> x ∉ W -> x ≠ Φ -> y ≠ Φ -> P[x × y] = Max P[x] P[y].\nProof.\n  intros.\n  assert (x ∈ (C ~ W)).\n  { unfold Difference; apply bel_inter; split; auto.\n    unfold Complement; apply Axiom_Scheme; split; Ens. }\n  apply notint_card_cart_eq in H4; double H; double H0; unfold C in H5, H6.\n  apply Axiom_Scheme in H5; apply Axiom_Scheme in H6; destruct H5, H6.\n  unfold Cardinal_Number, Ordinal_Number in H7, H8; destruct H7, H8.\n  clear H5 H6 H9 H10; apply Axiom_Scheme in H7; apply Axiom_Scheme in H8.\n  destruct H7, H8; assert (Ordinal x /\\ Ordinal y); auto.\n  apply ord_bel_eq in H9; destruct H9 as [H9 | [H9 | H9]].\n  - assert (Ensemble (y × y) /\\ (x × y) ⊂ (y × y)).\n    { split; unfold Subclass; intros.\n      - apply set_cart; split; auto.\n      - unfold Ordinal, full in H8; destruct H8 as [_ H8]; apply H8 in H9.\n        PP H10 a b; clear H10; apply Axiom_SchemeP in H11; unfold Cartesian.\n        apply Axiom_SchemeP; destruct H11, H11; repeat split; auto. }\n    apply card_le in H10; apply not_zero_exist_bel in H2; destruct H2.\n    assert (y ≈ ([x0] × y)).\n    { apply equiv_tran with (y:= y × [x0]); try apply equiv_cart_sing; Ens.\n      apply Lemma180. }\n    assert (Ensemble (x × y) /\\ ([x0] × y) ⊂ (x × y)).\n    { split; try apply set_cart; Ens; unfold Subclass; intros.\n      PP H12 a b; apply Axiom_SchemeP in H13; destruct H13, H14.\n      apply Axiom_SchemeP; repeat split; auto; unfold Singleton in H14.\n      apply Axiom_Scheme in H14; destruct H14; rewrite H16; auto.\n      apply bel_universe_set; Ens. }\n    assert (Ensemble y /\\ Ensemble ([x0] × y)).\n    { split; auto; apply set_cart; split; auto; apply sing_set; Ens. }\n    apply card_le in H12; apply card_eq in H13; apply H13 in H11.\n    rewrite <- H11 in H12; clear H11 H13.\n    assert (y ∈ (C ~ W)).\n    { unfold Difference; apply Axiom_Scheme; repeat split; auto.\n      unfold Complement; apply Axiom_Scheme; split; auto; intro.\n      unfold W in H11; apply Axiom_Scheme in H11; destruct H11 as [_ H11].\n      apply int_bel_int in H9; auto; destruct H1; unfold W.\n      apply Axiom_Scheme; split; auto. }\n    apply notint_card_cart_eq in H11; rewrite H11 in H10; clear H5 H7 H11.\n    apply card_iff_eq in H; apply card_iff_eq in H0; destruct H, H0.\n    rewrite H5, H7 in *; apply Property_Max in H9; auto; rewrite H9.\n    apply le_tran_eq; auto.\n  - assert (Ensemble (x × x) /\\ (x × y) ⊂ (x × x)).\n    { split; unfold Subclass; intros; try (apply set_cart; Ens).\n      unfold Ordinal, full in H6; destruct H6 as [_ H6]; apply H6 in H9.\n      PP H10 a b; clear H10; apply Axiom_SchemeP in H11; unfold Cartesian.\n      apply Axiom_SchemeP; destruct H11, H11; repeat split; auto. }\n    apply card_le in H10; rewrite H4 in H10; clear H4.\n    apply not_zero_exist_bel in H3; destruct H3.\n    assert (x ≈ (x × [x0])); try apply equiv_cart_sing; Ens.\n    assert (Ensemble (x × y) /\\ (x × [x0]) ⊂ (x × y)).\n    { split; try apply set_cart; Ens; unfold Subclass; intros.\n      PP H11 a b; apply Axiom_SchemeP in H12; destruct H12, H13.\n      apply Axiom_SchemeP; repeat split; auto; unfold Singleton in H13.\n      apply Axiom_Scheme in H14; destruct H14; rewrite H15; auto.\n      apply bel_universe_set; Ens. }\n    assert (Ensemble x /\\ Ensemble (x × [x0])).\n    { split; auto; apply set_cart; split; auto; apply sing_set; Ens. }\n    apply card_le in H11; apply card_eq in H12; apply H12 in H4.\n    rewrite <- H4 in H11; clear H4 H5 H7 H12; apply card_iff_eq in H.\n    apply card_iff_eq in H0; destruct H, H0; rewrite H4, H5 in *.\n    apply Property_Max in H9; auto; rewrite Equal_Max in H9.\n    rewrite H9; apply le_tran_eq; auto.\n  - rewrite <- H9 in *; clear H0 H1 H2 H3 H5 H6 H7 H8 H9.\n    apply card_iff_eq in H; destruct H; rewrite H0; assert (x=x); auto.\n    apply Property_Max in H1; rewrite H1; auto.\nQed.\n\nTheorem Theorem180_Change : forall x y,\n  x ∈ C -> y ∈ C -> x ∉ W \\/ y ∉ W -> x ≠ Φ -> y ≠ Φ ->\n  P[x × y] = Max P[x] P[y].\nProof.\n  intros; destruct H1.\n  - apply Lemma180'; auto.\n  - assert (x × y ≈ y × x); try apply Lemma180.\n    assert (Ensemble (x × y) /\\ Ensemble (y × x)).\n    { split; apply set_cart; split; Ens. }\n    apply card_eq in H5; apply H5 in H4; clear H5.\n    rewrite H4, Equal_Max; apply Lemma180'; auto.\nQed.\n\nHint Resolve Theorem180_Not Theorem180_Change : set.\n\n\n(* 181 Theorem  There is a unique ≺-≺ order-preserving function with domain R\n   and range C ~ W.  *)\n\nTheorem cont_hypo : exists f, Order_Pr f E E /\\ dom(f) = R /\\ ran(f) = C ~ W.\nProof.\n  generalize ord_not_set_R; intros; destruct H; apply ord_well_order in H.\n  assert ((C ~ W) ⊂ R).\n  { unfold Subclass, Difference; intros; apply bel_inter in H1; destruct H1.\n    unfold C in H1; apply Axiom_Scheme in H1; unfold Cardinal_Number in H1.\n    destruct H1, H3; unfold Ordinal_Number in H3; auto. }\n  apply lem_order_pre_sec_sub with (r:= E) in H1; auto; add (WellOrdered E (C ~ W)) H.\n  clear H1; apply well_order_pre in H; destruct H as [f H], H, H1; exists f.\n  destruct H1, H3, H4, H5; split; auto; destruct H2; split; auto.\n  - rewrite <- H2 in H0; clear H2 H5.\n    apply order_pre_fun1_inv in H4; destruct H4 as [H2 _], H2.\n    generalize (classic (ran(f) = C ~ W)); intros; destruct H5; auto.\n    assert (Ensemble ran(f)).\n    { unfold Section in H6; destruct H6, H7 as [_ H7].\n      assert (ran(f) ⊊ C ~ W); unfold ProperSubclass; auto.\n      apply Property_ProperSubclass' in H8; destruct H8, H8.\n      assert (ran(f) ⊂ x).\n      { unfold Subclass; intros; double H10; apply H6 in H11.\n        assert (x ∈ (C ~ W) /\\ z ∈ (C ~ W)); auto.\n        unfold WellOrdered in H3; destruct H3 as [H3 _].\n        apply H3 in H12; destruct H12 as [H12 | [H12 | H12]].\n        - destruct H9; apply H7 with (v:= z); auto.\n        - unfold Rrelation, E in H12; apply Axiom_SchemeP in H12; apply H12.\n        - rewrite H12 in H9; contradiction. }\n      apply sub_set in H10; Ens. }\n    rewrite dom_ran_inv in H0; rewrite dom_ran_inv' in H7.\n    apply Axiom_Substitution in H7; auto; contradiction.\n  - clear H3 H4 H0 H6.\n    generalize (classic (dom(f) = R)); intros; destruct H0; auto.\n    assert (~ Ensemble ran(f)).\n    { rewrite H2; intro; generalize C_not_set, W_bel_C; intros.\n      add (Ensemble W) H3; Ens; apply Axiom_Union in H3; clear H6.\n      assert (C ~ W ∪ W = C).\n      { apply Axiom_Extent; unfold Difference; split; intros.\n        - apply bel_union in H6; destruct H6.\n          + apply bel_inter in H6; apply H6.\n          + generalize W_sub_C; intros; apply H7 in H6; auto.\n        - generalize (classic (z ∈ W)); intros; apply bel_union.\n          destruct H7; try tauto; left; apply bel_inter.\n          split; auto; unfold Complement; apply Axiom_Scheme; Ens. }\n      rewrite H6 in H3; contradiction. }\n    assert (Ensemble dom(f)); clear H2.\n    { intros; generalize ord_not_set_R; intros; destruct H2 as [H2 _]; double H5.\n      apply sec_R_ord in H5; assert (Ordinal dom(f) /\\ Ordinal R); auto.\n      apply ord_bel_eq in H6; destruct H6 as [H6|[H6|H6]]; try tauto; Ens.\n      apply H4 in H6; generalize (notin_fix R); intros; contradiction. }\n    apply Axiom_Substitution in H4; auto; contradiction.\nQed.\n\nTheorem cont_hypo' : forall f g,\n  Order_Pr f E E -> Order_Pr g E E -> dom(f) = R -> dom(g) = R ->\n  ran(f) = C ~ W -> ran(g) = C ~ W -> f = g.\nProof.\n  intros.\n  assert (Order_Pr f E E /\\ Order_Pr g E E); auto.\n  generalize ord_not_set_R; intros; destruct H6 as [H6 _]; apply ord_well_order in H6.\n  assert ((C ~ W) ⊂ R).\n  { unfold Subclass, Difference; intros; apply bel_inter in H7; destruct H7.\n    unfold C in H7; apply Axiom_Scheme in H7; unfold Cardinal_Number in H7.\n    destruct H7, H9; unfold Ordinal_Number in H9; auto. }\n  apply lem_order_pre_sec_sub with (r:= E) in H7; auto.\n  assert (Section dom(f) E R /\\ Section dom(g) E R).\n  { rewrite H1, H2; unfold Section, Subclass.\n    split; try (repeat split; try apply H6; intros; auto; try apply H8). }\n  assert (Section ran(f) E (C~W) /\\ Section ran(g) E (C~W)).\n  { rewrite H3, H4; unfold Section, Subclass.\n    split; try (repeat split; try apply H7; intros; auto; try apply H9). }\n  apply (order_pre_sec_sub f g E E R (C~W)) in H5; auto; clear H6 H7 H8 H9.\n  unfold Order_Pr in H, H0; destruct H, H0, H5.\n  - apply sub_eq; split; auto; unfold Subclass; intros.\n    rewrite fun_set_eq; rewrite fun_set_eq in H8; auto; PP H8 a b.\n    double H9; rewrite <- fun_set_eq in H9; auto; apply Axiom_SchemeP in H10.\n    destruct H10; apply Axiom_SchemeP; split; auto; rewrite H11 in *.\n    assert ([a,f[a]] ∈ f).\n    { apply Property_Value; auto; apply Property_dom in H9.\n      rewrite H2, <- H1 in H9; auto. }\n    apply H5 in H12; eapply H0; eauto.\n  - apply sub_eq; split; auto; unfold Subclass; intros.\n    rewrite fun_set_eq; rewrite fun_set_eq in H8; auto; PP H8 a b.\n    double H9; rewrite <- fun_set_eq in H9; auto; apply Axiom_SchemeP in H10.\n    destruct H10; apply Axiom_SchemeP; split; auto; rewrite H11 in *.\n    assert ([a,g[a]] ∈ g).\n    { apply Property_Value; auto; apply Property_dom in H9.\n      rewrite H1, <- H2 in H9; auto. }\n    apply H5 in H12; eapply H; eauto.\nQed.\n\nHint Resolve cont_hypo cont_hypo' : set.\n\nEnd Cardinal.\n\nExport Cardinal.\n\n", "meta": {"author": "styzystyzy", "repo": "Axiomatic_Set_Theory", "sha": "2e5f5daa427bd9d6045c4a210c920680b6904f2f", "save_path": "github-repos/coq/styzystyzy-Axiomatic_Set_Theory", "path": "github-repos/coq/styzystyzy-Axiomatic_Set_Theory/Axiomatic_Set_Theory-2e5f5daa427bd9d6045c4a210c920680b6904f2f/theories/Cardinal_Numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587668, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.6847641559342965}}
{"text": "Require Import Coq.Classes.SetoidClass.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.Arith.Peano_dec.\nRequire Import NatList.\nRequire Import MyInductions.\n\nModule PartialMap.\n\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\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id x1 x2 :=\n  match x1, x2 with\n    | Id n1, Id n2 => myeq_nat n1 n2\n  end.\n\nCheck beq_id.\n\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  intros.\n  induction x.  \n  simpl.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  assumption.\nQed.\n\n\nInductive partial_map : Type :=\n | empty : partial_map\n| record : id -> nat -> partial_map -> partial_map.\n\nDefinition update(d : partial_map) (key : id) (value : nat) : partial_map :=\n  record key value d.\n\nFixpoint find (key : id) (d : partial_map) : NatList.natoption :=\n  match d with\n    |empty => NatList.None\n    |record k v d' => if beq_id key k then NatList.Some v else find key d'\n  end.\n\nTheorem update_eq : \n  forall (d : partial_map) (k : id) (v : nat),\n    find k (update d k v) = NatList.Some v.\n  Proof.\n    intros.\n    induction d.\n    simpl.\n    rewrite <- beq_id_refl.\n    reflexivity.\n    simpl.\n    rewrite <- beq_id_refl.\n    reflexivity.\n  Qed.\n\nTheorem update_neq :\n  forall (d : partial_map) (m n : id) (o : nat), beq_id m n = false -> find m (update d n o) = find m d.\nProof.\n  intros.\n  simpl.\n  rewrite ->H.\n  reflexivity.\nQed.\n\nInductive list (X : Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\nPrint nat.\nCheck list.\n\nCheck nil.\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n| 0 => nil X\n| S count' => cons X x (repeat X x count')\n  end.\n\nExample test_repeat1 : repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof.\n  reflexivity.\nQed.\n\nExample test_repeat2 : repeat bool false 1 = cons bool false (nil bool).\nProof.\n  reflexivity.\nQed.\n\nModule MumbleGrumble.\n\nInductive mumble : Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\n\nInductive grumble (X:Type) : Type :=\n  | d : mumble -> grumble X\n  | e : X -> grumble X.\n\nDefinition toto := (d mumble (b a 5)).\n\nCheck toto.\n\nEnd MumbleGrumble.\n\nFixpoint repeat' X x count : list X :=\n  match count with\n| 0 => nil X\n| S count' => cons X x (repeat' X x count')\n  end.\n\nCheck repeat'.\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\nInductive list' {X:Type} : Type :=\n  | nil' : list'\n  | cons' : X -> list' -> list'.\n\nFixpoint app {X: Type} (l1 l2 : list X) : (list X) :=\n  match l1 with\n    | nil => l2\n    | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X: Type} (l : list X) : list X :=\n  match l with\n      | nil => nil\n      | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n    | nil => 0\n    | cons _ l' => S (length l')\n  end.\n\nFail Definition mynil := nil.\n\nCheck @nil.\nDefinition mynil' := @nil nat.\n\nNotation \"x :: y\" := (cons x y) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \" x ++ y\" := (app x y) (at level 60, right associativity).\n\nDefinition list123''' := [1;2;3].\nExample test_rev1 : rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\nCheck @doit3times.\n\nTheorem app_nil_r : forall (X:Type), forall l : list X, l ++ [] = l.\nProof.\n  intros.\n  induction l.\n  intros.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite ->IHl.\n  reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n : list A), l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros.\n  induction l.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite ->IHl.\n  reflexivity.\nQed.\n\nLemma app_length : forall (X : Type) (l1 l2 : list X), length(l1 ++ l2) = length l1 + length l2.\nProof.\n  intros.\n  induction l1.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite ->IHl1.\n  reflexivity.\nQed.\n\nTheorem rev_app_distr : forall (X : Type) (l1 l2 : list X), rev(l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros.\n  induction l1.\n  simpl.\n  rewrite -> app_nil_r.\n  reflexivity.\n  simpl.\n  rewrite -> IHl1.\n  rewrite <- app_assoc.\n  reflexivity.\nQed.\n\nTheorem rev_involutive : forall (X : Type) (l : list X), rev (rev l) = l.\nProof.\n  intros.\n  induction l.\n  simpl.\n  reflexivity.\n  simpl.\n  replace ([x]) with (rev [x]).\n  set (rev l).\n  set (rev [x]).\n  rewrite ->rev_app_distr.\n  unfold l1.  \n  unfold l0.\n  simpl.\n  rewrite ->IHl.\n  reflexivity.\n  simpl.\n  reflexivity.\nQed.\n\n(* Polymorphic Pairs *)\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, 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\nCheck @combine.\n\nCompute (combine [1;2] [false;false;true;true]).\n\nFixpoint first_on_list { X Y : Type } (lx : list ( X * Y )) : list (X) :=\n  match lx with\n    | [] => []\n    | x::t => (fst x)::(first_on_list t)\n  end.\n\nFixpoint snd_on_list { X Y : Type } (lx : list ( X * Y )) : list (Y) :=\n  match lx with\n    | [] => []\n    | x::t => (snd x)::(snd_on_list t)\n  end.\n  \n\nFixpoint split {X Y : Type} (l : list (X * Y)) : (list X) * (list Y) :=\n  (first_on_list l, snd_on_list l).\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof.\n  reflexivity.\nQed.\n\nCheck @split.\n\n(* Polymorphic Options *)\n\nInductive option2 ( X : Type ) : Type :=\n  | Some2 : X -> option2 X\n  | None2 : option2 X.\n\nArguments Some2 {X} _.\nArguments None2 {X}.\n\n\nFixpoint nth_error2 {X : Type } (l : list X) (n : nat) : option2 X :=\n  match l with\n    | [] => None2\n    | a :: l2 => if myeq_nat n 0 then Some2 a else nth_error2 l2 (n-1)\n  end.\n\nExample test_nth_error1 : nth_error2 [4;5;6;7] 0 = Some2 4.\nProof.\n  reflexivity.\nQed.\n\nExample test_nth_error2 : nth_error2 [[1];[2]] 1 = Some2 [2].\nProof.\n  simpl.\n  reflexivity.\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 oddb (n:nat) := negb (evenb (n)).\n\n      \n\nFixpoint filter { X : Type} (test : X -> bool) (l:list X) : (list X) :=\n  match l with\n    | [] => []\n    | h::t => if test h then h :: (filter test t) else filter test t\n  end.\n\nExample test_filter1 : filter evenb [1;2;3;4] = [2;4].\nProof.\n  reflexivity.\nQed.\n\nDefinition length_is_1 { X : Type } (l : list X) : bool :=\n  myeq_nat (length l) 1.\n\nExample test_filter2 : filter length_is_1 [ [1;2];[3];[4];[5;6;7];[];[8]] = [[3];[4];[8]].\nProof.\n  reflexivity.\nQed.\n\nDefinition countoddmembers' (l : list nat) : nat := length (filter oddb l).\n\nExample test_countoddmembers'1 : countoddmembers' [1;0;3;1;4;5] = 4.\nProof.\n  reflexivity.\nQed.\n\nExample test_countoddmembers'2: countoddmembers' [0;2;4] = 0.\nProof.\n  reflexivity.\nQed.\n\nExample test_countoddmembers'3: countoddmembers' nil = 0.\nProof.\n  reflexivity.\nQed.\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof.\n  reflexivity.\nQed.\n\nExample test_filter2' : filter (fun l => NatList.myeq_nat (length l) 1) [[1;2];[3];[4];[5;6;7];[];[8]] = [[3];[4];[8]].\nProof.\n  reflexivity.\nQed.\n\nDefinition filter_event_gt7 ( l : list nat) : list nat := \n  filter (fun h \n          => \n             if ( (oddb h) ) then true else false\n            \n         ) l.\n\nDefinition partition { X : Type } (test : X -> bool) (l : list X) : list X * list X :=\n  ((filter (fun h => (test h)) l), (filter (fun h => (negb (test h))) l)).\n\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof.\n  reflexivity.\nQed.\n\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof.\n  reflexivity.\nQed.\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\nTheorem map_app_distr :  forall (X Y : Type) (f : X -> Y) (l1 l2 : list X), map f (l1 ++ l2) = map f l1 ++ map f l2.\nProof.\n  intros.\n  induction l1.\n  simpl.\n  reflexivity.\n  replace (x::l1) with ([x]++l1).\n  rewrite <- app_assoc.\n  simpl.\n  rewrite <- IHl1.\n  reflexivity.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X), map f (rev l) = rev (map f l).\nProof.\n  intros.  \n  induction l.\n  simpl.\n  reflexivity.\n  replace ( x :: l) with ([x]++l).\n  rewrite -> rev_app_distr.\n  rewrite -> map_app_distr.\n  simpl.\n  rewrite <-IHl.\n  reflexivity.\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    | h::t => (let r := (f h) in\n              (r ++ (flat_map f t)))\n  end.\n\nExample test_flat_map1 : flat_map (fun n => [n;n;n]) [1;5;4] = [1;1;1;5;5;5;4;4;4].\nProof.\n  reflexivity.\nQed.\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\nCompute fold plus [1;2;3;4] 0.\n\n\nExample fold_example1 : fold mult [1;2;3;4] 1 = 24.\nProof.\n  reflexivity.\nQed.\n\nDefinition constfun {X : Type} (x : X) : nat -> X := fun (k : nat) => x.\n\nDefinition ftrue := constfun true.\n    \nExample constfun_example1 : ftrue 0 = true.\nProof.\n  reflexivity.\nQed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof.\n  reflexivity.\nQed.\n\nCheck plus.\n\nDefinition fold_length { X : Type } (l : list X) : nat := fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof.\n  reflexivity.\nQed.\n\nTheorem fold_length_app : forall X (l1 l2 : list X), \n                             fold_length (l1++l2) = fold_length (l1) + fold_length (l2).\nProof.\n  intros.\n  induction l1.\n  simpl.\n  reflexivity.\n  replace (x::l1) with ([x]++l1).\n  rewrite <- app_assoc.\n  unfold fold_length in IHl1.\n  unfold fold_length.\n  simpl.\n  rewrite <-IHl1.\n  reflexivity.\n  simpl.\n  reflexivity.\nQed.\n  \nTheorem fold_length_correct : forall X (l : list X), fold_length l = length l.\nProof.\n  intros.\n  induction l.\n  simpl.\n  unfold fold_length.\n  simpl.\n  reflexivity.\n  replace (x::l) with ([x]++l).\n  rewrite -> app_length.\n  rewrite -> fold_length_app.\n  rewrite -> IHl.\n  replace (length [x]) with 1.\n  replace (fold_length [x]) with 1.\n  reflexivity.\n  unfold fold_length.\n  unfold fold.\n  reflexivity.\n  simpl.\n  reflexivity.\n  simpl.\n  reflexivity.\nQed.\n\nDefinition toto := [1;2;3].\n\n(*Definition fold_map {X Y : Type} (f : X -> Y) (l : list X) : list Y := *)\nTheorem silly1 : forall (n m o p : nat), (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 = m -> (forall ( q r : nat), q = r -> [q;o] = [r;p]) -> [n;o] = [m;p].\nProof.\n  intros.\n  apply H0.\n  apply H.\nQed.\n\nTheorem silly2a : forall (n m : nat), (n,n) = (m,m) -> (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) -> [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2.\n  apply eq1.\nQed.\n\n(* Logical Connectives *)\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 =4.\nProof.\n  split.\n  reflexivity.\n  reflexivity.\nQed.\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\nQed.\n\nTheorem plus_0_n2 : forall n : nat, n + 0 = n.\nProof.\n  intros.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite ->IHn.\n  reflexivity.\nQed.\n\n\nTheorem a_n_0 : forall a : nat, S a <> 0.\nProof.\n  auto.\nQed.\n\nTheorem a_p_b : forall a b : nat, a + S b <> 0.\nProof.\n  intros.\n  induction a.\n  simpl.\n  auto.\n  simpl.\n  set (a + S b).\n  apply a_n_0.\nQed.\n\nTheorem and_exercise : forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros.\n  split.\n  destruct m.\n  rewrite <-H.\n  replace (n + 0) with n.\n  reflexivity.\n  rewrite -> plus_0_n2.\n  reflexivity.\n  absurd (n + S m = 0).\n  apply a_p_b.\n  assumption.\n  destruct n.\n  rewrite <- H.\n  simpl.\n  reflexivity.\n  absurd (S n + m = 0).\n  set (S n).\n  rewrite <- MyInductions.plus_comm.\n  unfold n0.\n  apply a_p_b.\n  assumption.\nQed.\n\nLemma proj2 : forall P Q : Prop, P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP.\nQed.\n\n\nTheorem and_commut : 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\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  assumption.\n  assumption.\n  assumption.\nQed.\n\nTheorem mult_0_r : forall n : nat, n * 0 = 0.\nProof.\n  intros n. induction n as [|n' IHn'].\n  reflexivity.\n  simpl. \n  assumption. \nQed.\n\nTheorem mult_0_elm : forall n : nat, n * 0 = 0.\nProof.\n  auto.\nQed.\n\nLemma or_example : 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_0_elm.\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 : forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  intros [|n].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\n    \nLemma toto100 : forall n, ((0 = (S n)) <-> False).\nProof.\n  intros.\n  split.\n  intro.\n  inversion H.\n  intro.\n  contradiction.\nQed.\n\n\n\n  \n\nLemma mult_eq_0 : forall n m, n *m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros.\n  induction n.\n  left.\n  reflexivity.\n  right.\n  admit.\nQed.\n\nTheorem or_commut : forall P Q : Prop, P \\/ Q -> Q \\/ P.\nProof.\n  intros.\n  destruct H as [H1 | H2].\n  right.\n  assumption.\n  left.\n  assumption.\nQed.\n\nFact not_implies_out_not : forall (P:Prop), ~P -> (forall (Q:Prop), P -> Q).\nProof.\n  intros.\n  elim H.\n  assumption.\nQed.\n\nTheorem zeo_not_one : ~(0 = 1).\nProof.\n  intros contra.\n  inversion contra.\nQed.\n\nCheck (0 <> 1).  \n\nTheorem zero_not_one : 0 <> 1.\nProof.\n  intros H.\n  inversion H.\nQed.\n\nTheorem not_False :\n  not False.\nProof.\n  unfold not.\n  intros H.\n  destruct H.\nQed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop, (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), (P -> Q) -> (~Q -> ~P).\nProof.\n  intros A B C.\n  unfold not.  \n  intro D.\n  intro E.\n  apply D.\n  apply C.\n  apply E.\nQed.\n\nTheorem not_both_true_and_false : forall P : Prop, ~( P /\\ ~P).\nProof.\n  unfold not.\n  intro H.\n  intro G.\n  apply G.\n  apply G.\nQed.\n\nTheorem ex_falso_quodlibet : forall (P:Prop), False -> P.\nProof.\n  intros P contra.\n  destruct contra.\nQed.\n\nLemma True_is_true : True.\n  Proof.\n    apply I.\n  Qed.\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, b<> true <-> b = false.\nProof.\n  intros b. split.\n  apply not_true_is_false.\n  intros H.  rewrite H. intros H'. inversion H'.\nQed.\n\nTheorem iff_refl : forall P : Prop, P <-> P.\nProof.\n  intro P.\n  split.\n  intros.\n  apply H.\n  intros.\n  apply H.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop, (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros.\n  split.\n  intros.\n  apply H0.\n  apply H.\n  assumption.\n  intros.\n  apply H.\n  apply H0.\n  apply H1.\nQed.\n\nTheorem or_distributes_over_and : forall P Q R : Prop, P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros.\n  split.\n  intro.\n  elim H.\n  intro.\n  split.\n  left.\n  apply H0.\n  left.\n  apply H0.\n  elim H.\n  intro.\n  intro.\n  split.\n  left.\n  apply H0.\n  left.\n  apply H0.\n  intro.\n  intro.  \n  split.\n  right.\n  elim H1.\n  intros.\n  apply H2.\n  right.\n  elim H1.\n  intros.\n  apply H3.\n  intros.\n  destruct H as [H1 H2].\n  elim H1.\n  elim H2.\n  intros.\n  left.\n  apply H0.\n  intros.\n  left.\n  apply H0.\n  intros.\n  destruct H2 as [H3 | H4].\n  left.\n  apply H3.\n  right.\n  split.\n  apply H.\n  apply H4.\nQed.\n\nLemma four_is_even : exists n : nat, 4 = n + n.\nProof.\n  exists 2. \n  reflexivity.\nQed.\n\nTheorem exists_example_2 : forall 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 : \n  forall (X : Type) (P : X -> Prop), (forall x, P x) -> ~ (exists x, ~P x).\n  intros.\n  unfold not.  \n  intros.\n  destruct H0 as [x G].\n  apply G.\n  apply H.\nQed.\n\nTheorem dist_exists_or : \n  forall (X : Type) (P Q : X -> Prop), (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\n  intros.\n  split.\n  intros.\n  left.\n  \nEnd PartialMap.\n\n\n(* MAP *)\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/PartialMap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.6847641498108517}}
{"text": "Require Import WildCat.\nRequire Import Spaces.Nat.\nRequire Export Classes.interfaces.abstract_algebra.\nRequire Import Algebra.AbGroups.\nRequire Export Classes.theory.rings.\nRequire Import Modalities.ReflectiveSubuniverse.\n\n(** Theory of commutative rings *)\n\n(** TODO: We should really develop the theory of non-commutative rings seperately, and have commutative rings as a special case of that theory. Similar to how we have Group and AbGroup. But since we are only interested in commutative rings for the time being, it makes sense to only consider them. *)\n\nDeclare Scope ring_scope.\n\nLocal Open Scope ring_scope.\n(** We want to print equivalences as [≅]. *)\nLocal Open Scope wc_iso_scope.\n\n(** A commutative ring consists of the following data *)\nRecord CRing := {\n  cring_type : Type;\n  cring_plus : Plus cring_type;\n  cring_mult : Mult cring_type;\n  cring_zero : Zero cring_type;\n  cring_one  : One  cring_type;\n  cring_negate : Negate cring_type;\n  cring_isring : IsRing cring_type;\n}.\n\nArguments cring_plus {_}.\nArguments cring_mult {_}.\nArguments cring_zero {_}.\nArguments cring_one {_}.\nArguments cring_negate {_}.\nArguments cring_isring {_}.\n\nDefinition issig_CRing : _ <~> CRing := ltac:(issig).\n\n(** We coerce rings to their underlying type. *)\nCoercion cring_type : CRing >-> Sortclass.\n(** All fields which are typeclasses are global instances *)\nGlobal Existing Instances cring_plus cring_mult cring_zero cring_one cring_negate cring_isring.\n\n(** A ring homomorphism between commutative rings is a map of the underlying type and a proof that this map is a ring homomorphism. *)\nRecord CRingHomomorphism (A B : CRing) := {\n  rng_homo_map : A -> B;\n  rng_homo_ishomo : IsSemiRingPreserving rng_homo_map;\n}.\n\nArguments Build_CRingHomomorphism {_ _} _ _.\n\nDefinition issig_CRingHomomorphism (A B : CRing)\n  : _ <~> CRingHomomorphism A B\n  := ltac:(issig).\n\n(** We coerce ring homomorphisms to their underlying maps *)\nCoercion rng_homo_map : CRingHomomorphism >-> Funclass.\nGlobal Existing Instance rng_homo_ishomo.\n\nDefinition equiv_path_cringhomomorphism `{Funext} {A B : CRing}\n  {f g : CRingHomomorphism A B} : f == g <~> f = g.\nProof.\n  refine ((equiv_ap (issig_CRingHomomorphism A B)^-1 _ _)^-1 oE _).\n  refine (equiv_path_sigma_hprop _ _ oE _).\n  apply equiv_path_forall.\nDefined.\n\nDefinition rng_homo_id (A : CRing) : CRingHomomorphism A A\n  := Build_CRingHomomorphism idmap _.\n\nDefinition rng_homo_compose {A B C : CRing}\n  (f : CRingHomomorphism B C) (g : CRingHomomorphism A B)\n  : CRingHomomorphism A C.\nProof.\n  snrapply Build_CRingHomomorphism.\n  1: exact (f o g).\n  rapply compose_sr_morphism.\nDefined.\n\n(** ** Ring laws *)\n\nSection RingLaws.\n\n  (** Many of these ring laws have already been proven. But we give them names here so that they are easy to find and use. *)\n\n  Context {A B : CRing} (f : CRingHomomorphism A B) (x y z : A).\n\n  Definition rng_dist_l : x * (y + z) = x * y + x * z := simple_distribute_l _ _ _.\n  Definition rng_dist_r : (x + y) * z = x * z + y * z := simple_distribute_r _ _ _.\n  Definition rng_plus_zero_l : 0 + x = x := left_identity _.\n  Definition rng_plus_zero_r : x + 0 = x := right_identity _.\n  Definition rng_plus_negate_l : (- x) + x = 0 := left_inverse _.\n  Definition rng_plus_negate_r : x + (- x) = 0 := right_inverse _.\n\n  Definition rng_plus_comm : x + y = y + x := commutativity x y.\n  Definition rng_plus_assoc : x + (y + z) = (x + y) + z := simple_associativity x y z.\n  Definition rng_mult_comm : x * y = y * x := commutativity x y.\n  Definition rng_mult_assoc : x * (y * z) = (x * y) * z := simple_associativity x y z.\n\n  Definition rng_negate_negate : - (- x) = x := negate_involutive _.\n\n  Definition rng_mult_one_l : 1 * x = x := left_identity _.\n  Definition rng_mult_one_r : x * 1 = x := right_identity _.\n  Definition rng_mult_zero_l : 0 * x = 0 := left_absorb _.\n  Definition rng_mult_zero_r : x * 0 = 0 := right_absorb _.\n  Definition rng_mult_negate : -1 * x = - x := (negate_mult _)^.\n  Definition rng_mult_negate_negate : -x * -y = x * y := negate_mult_negate _ _.\n  Definition rng_mult_negate_l : -x * y = -(x * y) := inverse (negate_mult_distr_l _ _).\n  Definition rng_mult_negate_r : x * -y = -(x * y) := inverse (negate_mult_distr_r _ _).\n\n  Definition rng_homo_plus : f (x + y) = f x + f y := preserves_plus x y.\n  Definition rng_homo_mult : f (x * y) = f x * f y := preserves_mult x y.\n  Definition rng_homo_zero : f 0 = 0 := preserves_0.\n  Definition rng_homo_one  : f 1 = 1 := preserves_1.\n  Definition rng_homo_negate : f (-x) = -(f x) := preserves_negate x.\n\n  Definition rng_homo_minus_one : f (-1) = -1\n    := preserves_negate 1%mc @ ap negate preserves_1.\n\nEnd RingLaws.\n\n(** Isomorphisms of commutative rings *)\nRecord CRingIsomorphism (A B : CRing) := {\n  rng_iso_homo : CRingHomomorphism A B ;\n  isequiv_rng_iso_homo : IsEquiv rng_iso_homo ;\n}.\n\nArguments rng_iso_homo {_ _ }.\nCoercion rng_iso_homo : CRingIsomorphism >-> CRingHomomorphism.\nGlobal Existing Instance isequiv_rng_iso_homo.\n\nDefinition issig_CRingIsomorphism {A B : CRing}\n  : _ <~> CRingIsomorphism A B := ltac:(issig).\n\n(** We can construct a ring isomorphism from an equivalence that preserves addition and multiplication. *)\nDefinition Build_CRingIsomorphism' (A B : CRing) (e : A <~> B)\n  `{!IsSemiRingPreserving e}\n  : CRingIsomorphism A B\n  := Build_CRingIsomorphism A B (Build_CRingHomomorphism e _) _.\n\n(** The inverse of a CRing isomorphism *)\nDefinition rng_iso_inverse {A B : CRing}\n  : CRingIsomorphism A B -> CRingIsomorphism B A.\nProof.\n  intros [f e].\n  snrapply Build_CRingIsomorphism.\n  { snrapply Build_CRingHomomorphism.\n    1: exact f^-1.\n    exact _. }\n  exact _.\nDefined.\n\n(** CRing isomorphisms are a reflexive relation *)\nGlobal Instance reflexive_cringisomorphism : Reflexive CRingIsomorphism\n  := fun x => Build_CRingIsomorphism _ _ (rng_homo_id x) _.\n\n(** CRing isomorphisms are a symmetric relation *)\nGlobal Instance symmetry_cringisomorphism : Symmetric CRingIsomorphism\n  := fun x y => rng_iso_inverse.\n\n(** CRing isomorphisms are a transitive relation *)\nGlobal Instance transitive_cringisomorphism : Transitive CRingIsomorphism\n  := fun x y z f g => Build_CRingIsomorphism _ _ (rng_homo_compose g f) _.\n\n(** Underlying abelian groups of rings *)\nDefinition abgroup_cring : CRing -> AbGroup.\nProof.\n  intro A.\n  snrapply Build_AbGroup.\n  - srapply (Build_Group (cring_type A)).\n  - exact _.\nDefined.\n\nCoercion abgroup_cring : CRing >-> AbGroup.\n\n(** Underlying group homomorphism of a ring homomorphism *)\nDefinition grp_homo_rng_homo {R S : CRing}\n  : CRingHomomorphism R S -> GroupHomomorphism R S\n  := fun f => @Build_GroupHomomorphism R S f _.\n\nCoercion grp_homo_rng_homo : CRingHomomorphism >-> GroupHomomorphism.\n\n(** We can construct a ring homomorphism from a group homomorphism that preserves multiplication *)\nDefinition Build_CRingHomomorphism' (A B : CRing) (map : GroupHomomorphism A B)\n  {H : IsMonoidPreserving (Aop:=cring_mult) (Bop:=cring_mult)\n    (Aunit:=one) (Bunit:=one) map}\n  : CRingHomomorphism A B\n  := Build_CRingHomomorphism map\n      (Build_IsSemiRingPreserving _ (grp_homo_ishomo _ _ map) H).\n\n(** We can construct a ring isomorphism from a group isomorphism that preserves multiplication *)\nDefinition Build_CRingIsomorphism'' (A B : CRing) (e : GroupIsomorphism A B)\n  {H : IsMonoidPreserving (Aop:=cring_mult) (Bop:=cring_mult) (Aunit:=one) (Bunit:=one) e}\n  : CRingIsomorphism A B\n  := @Build_CRingIsomorphism' A B e (Build_IsSemiRingPreserving e _ H).\n\n(** Here is an alternative way to build a commutative ring using the underlying abelian group. *)\nDefinition Build_CRing' (R : AbGroup)\n  `(Mult R, One R, LeftDistribute R mult (@group_sgop R))\n  (iscomm : @IsCommutativeMonoid R mult one)\n  : CRing\n  := Build_CRing R (@group_sgop R) _ (@group_unit R) _\n       (@group_inverse R) (Build_IsRing _ _ _ _).\n\n(** ** Ring movement lemmas *)\n\nSection RingMovement.\n\n  (** We adopt a similar naming convention to the [moveR_equiv] style lemmas that can be found in Types.Paths. *)\n\n  Context {R : CRing} {x y z : R}.\n\n  Definition rng_moveL_Mr : - y + x = z <~> x = y + z := @grp_moveL_Mg R x y z.\n  Definition rng_moveL_rM : x + - z = y <~> x = y + z := @grp_moveL_gM R x y z.\n  Definition rng_moveR_Mr : y = - x + z <~> x + y = z := @grp_moveR_Mg R x y z.\n  Definition rng_moveR_rM : x = z + - y <~> x + y = z := @grp_moveR_gM R x y z.\n\n  Definition rng_moveL_Vr : x + y = z <~> y = - x + z := @grp_moveL_Vg R x y z.\n  Definition rng_moveL_rV : x + y = z <~> x = z + - y := @grp_moveL_gV R x y z.\n  Definition rng_moveR_Vr : x = y + z <~> - y + x = z := @grp_moveR_Vg R x y z.\n  Definition rng_moveR_rV : x = y + z <~> x + - z = y := @grp_moveR_gV R x y z.\n\n  Definition rng_moveL_M0 : - y + x = 0 <~> x = y := @grp_moveL_M1 R x y.\n  Definition rng_moveL_0M :\tx + - y = 0 <~> x = y := @grp_moveL_1M R x y.\n  Definition rng_moveR_M0 : 0 = - x + y <~> x = y := @grp_moveR_M1 R x y.\n  Definition rng_moveR_0M : 0 = y + - x <~> x = y := @grp_moveR_1M R x y.\n\n  (** TODO: Movement laws about mult *)\n\nEnd RingMovement.\n\n(** ** Wild category of commutative rings *)\n\nGlobal Instance isgraph_cring : IsGraph CRing\n  := Build_IsGraph _ CRingHomomorphism.\n\nGlobal Instance is01cat_cring : Is01Cat CRing\n  := Build_Is01Cat _ _ rng_homo_id (@rng_homo_compose).\n\nGlobal Instance is2graph_cring : Is2Graph CRing\n  := fun A B => isgraph_induced (@rng_homo_map A B).\n\nGlobal Instance is01cat_cringhomomorphism {A B : CRing} : Is01Cat (A $-> B)\n  := is01cat_induced (@rng_homo_map A B).\n\nGlobal Instance is0gpd_cringhomomorphism {A B : CRing} : Is0Gpd (A $-> B)\n  := is0gpd_induced (@rng_homo_map A B).\n\nGlobal Instance is0functor_postcomp_cringhomomorphism {A B C : CRing} (h : B $-> C)\n  : Is0Functor (@cat_postcomp CRing _ _ A B C h).\nProof.\n  apply Build_Is0Functor.\n  intros [f ?] [g ?] p a ; exact (ap h (p a)).\nDefined.\n\nGlobal Instance is0functor_precomp_cringhomomorphism\n       {A B C : CRing} (h : A $-> B)\n  : Is0Functor (@cat_precomp CRing _ _ A B C h).\nProof.\n  apply Build_Is0Functor.\n  intros [f ?] [g ?] p a ; exact (p (h a)).\nDefined.\n\n(** CRing forms a 1Cat *)\nGlobal Instance is1cat_cring : Is1Cat CRing.\nProof.\n  by rapply Build_Is1Cat.\nDefined.\n\nGlobal Instance hasmorext_cring `{Funext} : HasMorExt CRing.\nProof.\n  srapply Build_HasMorExt.\n  intros A B f g; cbn in *.\n  snrapply @isequiv_homotopic.\n  1: exact (equiv_path_cringhomomorphism^-1%equiv).\n  1: exact _.\n  intros []; reflexivity. \nDefined.\n\nGlobal Instance hasequivs_cring : HasEquivs CRing.\nProof.\n  unshelve econstructor.\n  + exact CRingIsomorphism.\n  + exact (fun G H f => IsEquiv f).\n  + intros G H f; exact f.\n  + exact Build_CRingIsomorphism.\n  + intros G H; exact rng_iso_inverse.\n  + cbn; exact _.\n  + reflexivity.\n  + intros ????; apply eissect.\n  + intros ????; apply eisretr.\n  + intros G H f g p q.\n    exact (isequiv_adjointify f g p q).\nDefined.\n\n(** ** Product ring *)\n\nDefinition cring_product : CRing -> CRing -> CRing.\nProof.\n  intros R S.\n  snrapply Build_CRing'.\n  1: exact (ab_biprod R S).\n  1: exact (fun '(r1 , s1) '(r2 , s2) => (r1 * r2 , s1 * s2)).\n  1: exact (cring_one , cring_one).\n  { intros [r1 s1] [r2 s2] [r3 s3].\n    apply path_prod; cbn; apply rng_dist_l. }\n  repeat split.\n  1: exact _.\n  { intros [r1 s1] [r2 s2] [r3 s3].\n    apply path_prod; cbn; apply rng_mult_assoc. }\n  1: intros [r1 s1]; apply path_prod; cbn; apply rng_mult_one_l.\n  1: intros [r1 s1]; apply path_prod; cbn; apply rng_mult_one_r.\n  intros [r1 s1] [r2 s2]; apply path_prod; cbn; apply rng_mult_comm.\nDefined.\n\nInfix \"×\" := cring_product : ring_scope.\n\nDefinition cring_product_fst {R S : CRing} : R × S $-> R.\nProof.\n  snrapply Build_CRingHomomorphism.\n  1: exact fst.\n  repeat split.\nDefined.\n\nDefinition cring_product_snd {R S : CRing} : R × S $-> S.\nProof.\n  snrapply Build_CRingHomomorphism.\n  1: exact snd.\n  repeat split.\nDefined.\n\nDefinition cring_product_corec (R S T : CRing)\n  : (R $-> S) -> (R $-> T) -> (R $-> S × T).\nProof.\n  intros f g.\n  srapply Build_CRingHomomorphism'.\n  1: apply (ab_biprod_corec f g).\n  repeat split.\n  1: cbn; intros x y; apply path_prod; apply rng_homo_mult.\n  cbn; apply path_prod; apply rng_homo_one.\nDefined.\n\nDefinition equiv_cring_product_corec `{Funext} (R S T : CRing)\n  : (R $-> S) * (R $-> T) <~> (R $-> S × T).\nProof.\n  snrapply equiv_adjointify.\n  1: exact (uncurry (cring_product_corec _ _ _)).\n  { intros f.\n    exact (cring_product_fst $o f , cring_product_snd $o f). }\n  { hnf; intros f.\n    by apply path_hom. }\n  intros [f g].\n  apply path_prod.\n  1,2: by apply path_hom.\nDefined.\n\n(** ** Image ring *)\n\n(** The image of a ring homomorphism *)\nDefinition rng_image {R S : CRing} (f : R $-> S) : CRing.\nProof.\n  snrapply (Build_CRing' (abgroup_image f)).\n  { simpl.\n    intros [x p] [y q].\n    exists (x * y).\n    strip_truncations; apply tr.\n    destruct p as [p p'], q as [q q'].\n    exists (p * q).\n    refine (rng_homo_mult _ _ _ @ _).\n    f_ap. }\n  { exists 1.\n    apply tr.\n    exists 1.\n    exact (rng_homo_one f). }\n  (** Much of this proof is doing the same thing over, so we use some compact tactics. *)\n  2: repeat split.\n  2: exact _.\n  all: intros [].\n  1,2,5: intros [].\n  1,2: intros [].\n  all: apply path_sigma_hprop; cbn.\n  1: apply distribute_l.\n  1: apply associativity.\n  1: apply commutativity.\n  1: apply left_identity.\n  apply right_identity.\nDefined.\n\nLemma rng_homo_image_incl {R S} (f : CRingHomomorphism R S)\n  : rng_image f $-> S.\nProof.\n  snrapply Build_CRingHomomorphism.\n  1: exact pr1.\n  repeat split.\nDefined.\n\n(** Image of a surjective ring homomorphism *)\nLemma rng_image_issurj {R S} (f : CRingHomomorphism R S) {issurj : IsSurjection f}\n  : rng_image f ≅ S.\nProof.\n  snrapply Build_CRingIsomorphism.\n  1: exact (rng_homo_image_incl f).\n  exact _.\nDefined. \n\n(** *** More Ring laws *)\n\n(** Powers of ring elements *)\nFixpoint rng_power {R : CRing} (x : R) (n : nat) : R :=\n  match n with\n  | 0%nat => cring_one\n  | n.+1%nat => x * rng_power x n\n  end.\n\n(** Power laws *)\nLemma rng_power_mult_law {R : CRing} (x : R) (n m : nat)\n  : (rng_power x n) * (rng_power x m) = rng_power x (n + m).\nProof.\n  revert m.\n  induction n.\n  { intros m.\n    apply rng_mult_one_l. }\n  intros m; cbn.\n  refine ((rng_mult_assoc _ _ _)^ @ _).\n  f_ap.\nDefined.\n\n(** Powers commute with multiplication *)\nLemma rng_power_mult {R : CRing} (x y : R) (n : nat)\n  : rng_power (x * y) n = rng_power x n * rng_power y n.\nProof.\n  induction n.\n  1: symmetry; apply rng_mult_one_l.\n  cbn.\n  rewrite rng_mult_assoc.\n  rewrite <- (rng_mult_assoc x _ y).\n  rewrite (rng_mult_comm (rng_power x n) y).\n  rewrite rng_mult_assoc.\n  rewrite <- (rng_mult_assoc _ (rng_power x n)).\n  f_ap.\nDefined.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Algebra/Rings/CRing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579722, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.6847641418777055}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** Theorems about [gt] in [nat].\n\n This file is DEPRECATED now, see module [PeanoNat.Nat] instead,\n which favor [lt] over [gt].\n\n [gt] is defined in [Init/Peano.v] as:\n<<\nDefinition gt (n m:nat) := m < n.\n>>\n*)\n\nRequire Import PeanoNat Le Lt Plus.\nLocal Open Scope nat_scope.\n\n(** * Order and successor *)\n\nTheorem gt_Sn_O n : S n > 0.\nProof Nat.lt_0_succ _.\n\nTheorem gt_Sn_n n : S n > n.\nProof Nat.lt_succ_diag_r _.\n\nTheorem gt_n_S n m : n > m -> S n > S m.\nProof.\n apply Nat.succ_lt_mono.\nQed.\n\nLemma gt_S_n n m : S m > S n -> m > n.\nProof.\n apply Nat.succ_lt_mono.\nQed.\n\nTheorem gt_S n m : S n > m -> n > m \\/ m = n.\nProof.\n intro. now apply Nat.lt_eq_cases, Nat.succ_le_mono.\nQed.\n\nLemma gt_pred n m : m > S n -> pred m > n.\nProof.\n apply Nat.lt_succ_lt_pred.\nQed.\n\n(** * Irreflexivity *)\n\nLemma gt_irrefl n : ~ n > n.\nProof Nat.lt_irrefl _.\n\n(** * Asymmetry *)\n\nLemma gt_asym n m : n > m -> ~ m > n.\nProof Nat.lt_asymm _ _.\n\n(** * Relating strict and large orders *)\n\nLemma le_not_gt n m : n <= m -> ~ n > m.\nProof.\n apply Nat.le_ngt.\nQed.\n\nLemma gt_not_le n m : n > m -> ~ n <= m.\nProof.\n apply Nat.lt_nge.\nQed.\n\nTheorem le_S_gt n m : S n <= m -> m > n.\nProof.\n apply Nat.le_succ_l.\nQed.\n\nLemma gt_S_le n m : S m > n -> n <= m.\nProof.\n apply Nat.succ_le_mono.\nQed.\n\nLemma gt_le_S n m : m > n -> S n <= m.\nProof.\n apply Nat.le_succ_l.\nQed.\n\nLemma le_gt_S n m : n <= m -> S m > n.\nProof.\n apply Nat.succ_le_mono.\nQed.\n\n(** * Transitivity *)\n\nTheorem le_gt_trans n m p : m <= n -> m > p -> n > p.\nProof.\n intros. now apply Nat.lt_le_trans with m.\nQed.\n\nTheorem gt_le_trans n m p : n > m -> p <= m -> n > p.\nProof.\n intros. now apply Nat.le_lt_trans with m.\nQed.\n\nLemma gt_trans n m p : n > m -> m > p -> n > p.\nProof.\n intros. now apply Nat.lt_trans with m.\nQed.\n\nTheorem gt_trans_S n m p : S n > m -> m > p -> n > p.\nProof.\n intros. apply Nat.lt_le_trans with m; trivial. now apply Nat.succ_le_mono.\nQed.\n\n(** * Comparison to 0 *)\n\nTheorem gt_0_eq n : n > 0 \\/ 0 = n.\nProof.\n destruct n; [now right | left; apply Nat.lt_0_succ].\nQed.\n\n(** * Simplification and compatibility *)\n\nLemma plus_gt_reg_l n m p : p + n > p + m -> n > m.\nProof.\n apply Nat.add_lt_mono_l.\nQed.\n\nLemma plus_gt_compat_l n m p : n > m -> p + n > p + m.\nProof.\n apply Nat.add_lt_mono_l.\nQed.\n\n(** * Hints *)\n\nHint Resolve gt_Sn_O gt_Sn_n gt_n_S : arith.\nHint Immediate gt_S_n gt_pred : arith.\nHint Resolve gt_irrefl gt_asym : arith.\nHint Resolve le_not_gt gt_not_le : arith.\nHint Immediate le_S_gt gt_S_le : arith.\nHint Resolve gt_le_S le_gt_S : arith.\nHint Resolve gt_trans_S le_gt_trans gt_le_trans: arith.\nHint Resolve plus_gt_compat_l: arith.\n\n(* begin hide *)\nNotation gt_O_eq := gt_0_eq (only parsing).\n(* end hide *)\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Arith/Gt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.6847641386423976}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Functor.Functor Functor.Functor_Ops.\nRequire Import Coq_Cats.Type_Cat.Type_Cat.\nRequire Import Ext_Cons.Prod_Cat.Prod_Cat.\nRequire Import Cat.Cat.\nRequire Import NatTrans.NatTrans NatTrans.Operations NatTrans.Func_Cat NatTrans.NatIso.\n\nLocal Open Scope isomorphism_scope.\nLocal Open Scope morphism_scope.\nLocal Open Scope object_scope.\n\n(*\n(** If two categories are isomorphic, then so are their duals. *)\nSection Opposite_Cat_Iso.\n  Context {C D : Category} (I : C ≃≃ D ::> Cat).\n\n  Program Definition Opposite_Cat_Iso : (C^op)%category ≃≃ (D^op)%category ::> Cat\n    :=\n      {|\n        iso_morphism := ((iso_morphism I)^op)%functor;\n        inverse_morphism := ((inverse_morphism I)^op)%functor\n      |}.\n\n  Next Obligation.\n    change (I ⁻¹ ^op ∘ (iso_morphism I) ^op)%functor\n    with (((inverse_morphism I) ∘ (iso_morphism I))^op)%functor.\n    cbn_rewrite (left_inverse I).\n    trivial.\n  Qed.\n\n  Next Obligation.\n    change ((iso_morphism I) ^op ∘ I ⁻¹ ^op)%functor\n    with (((iso_morphism I) ∘ (inverse_morphism I))^op)%functor.\n    cbn_rewrite (right_inverse I).\n    trivial.\n  Qed.\n\nEnd Opposite_Cat_Iso.\n  \n(** Conversion from a category to another isomorphic category. *)\nSection Cat_IConv.\n  Context {C D : Category} (I : C ≃≃ D ::> Cat).\n\n  (** Object conversion through an isomorphism and its inverse isomorphism gives back the same object. *)\n  Definition Cat_Iso_Obj_conv (c : C) : c = (((inverse_morphism I) _o) (((iso_morphism I) _o) c))%object.\n  Proof.\n    change (I ⁻¹ _o ((iso_morphism I) _o c)) with ((I ⁻¹ ∘ I)%morphism _o c)%object;\n    rewrite (left_inverse I); trivial.\n  Qed.\n\n  (** Homomorphism types remain the smae after object conversion through an isomorphism and its inverse isomorphism. *)\n  Definition Cat_Iso_Hom_conv (c c' : C) :\n    ((((inverse_morphism I) _o) (((iso_morphism I) _o) c))\n      –≻\n      (((inverse_morphism I) _o) (((iso_morphism I) _o) c')))%morphism = (c –≻ c').\n  Proof.\n    do 2 rewrite <- Cat_Iso_Obj_conv; trivial.\n  Defined.\n\n  (** Type conversion to the original hom type after conversion with an isomorphism and its inverse. *)\n  Definition Cat_Iso_conv_inv {c c' : C}\n             (h :\n                (((inverse_morphism I) _o) (((iso_morphism I) _o) c))\n                  –≻ (((inverse_morphism I) _o) (((iso_morphism I) _o) c'))) : c –≻ c' :=\n    match Cat_Iso_Hom_conv c c' in _ = Y return Y with\n      eq_refl => h\n    end.\n\n  (** Heterogenous equality of type conversion to the original hom type after conversion with an isomorphism and its inverse. *)\n  Theorem Cat_Iso_conv_inv_JMeq {c c' : C}\n          (h :\n             (((inverse_morphism I) _o) (((iso_morphism I) _o) c))\n               –≻ (((inverse_morphism I) _o) (((iso_morphism I) _o) c'))) : Cat_Iso_conv_inv h ~= h.\n  Proof.\n    unfold Cat_Iso_conv_inv.\n    destruct Cat_Iso_Hom_conv.\n    trivial.\n  Qed.\n\n  (** Type conversion to the original hom type after conversion with the inverse of an isomorphism and that isomorphism. *)\n  Definition Cat_Iso_conv {c c' : C} (h : c –≻ c') :\n    (((inverse_morphism I) _o) (((iso_morphism I) _o) c))\n      –≻ (((inverse_morphism I) _o) (((iso_morphism I) _o) c'))\n    :=\n    match eq_sym (Cat_Iso_Hom_conv c c') in _ = Y return Y with\n      eq_refl => h\n    end.\n  \n  (** Heterogenous equality of type conversion to the original hom type after conversion with the inverse of an isomorphism and that isomorphism. *)\n  Theorem Cat_Iso_conv_JMeq {c c' : C} (h : c –≻ c') : Cat_Iso_conv h ~= h.\n  Proof.\n    unfold Cat_Iso_conv.\n    destruct Cat_Iso_Hom_conv.\n    trivial.\n  Qed.\n\n  (** Conversion once through an isomrphism and its inverse and once through its inverse and it gives back the same arrow as we strated with. *)\n  Theorem Cat_Iso_conv_inv_Cat_Iso_conv {c c' : C} (h : c –≻ c') : Cat_Iso_conv_inv (Cat_Iso_conv h) = h.\n  Proof.\n    unfold Cat_Iso_conv_inv, Cat_Iso_conv.\n    destruct Cat_Iso_Hom_conv; trivial.\n  Qed.\n\n  (** Conversion once through the inverse of an isomrphism and that isomorphism and once through that isomorphism and its inverse gives back the same arrow as we strated with. *)\n  Theorem Cat_Iso_conv_Cat_Iso_conv_inv {c c' : C}\n          (h :\n             (((inverse_morphism I) _o) (((iso_morphism I) _o) c))\n               –≻ (((inverse_morphism I) _o) (((iso_morphism I) _o) c')))\n    :\n      Cat_Iso_conv (Cat_Iso_conv_inv h) = h.\n  Proof.\n    unfold Cat_Iso_conv_inv, Cat_Iso_conv.\n    destruct Cat_Iso_Hom_conv; trivial.\n  Qed. \n\n  (** Conversion of an arrow through an ismorphism and its inverse (after correcting the homorphism type) is the same arrow as we started with. *)\n  Theorem Cat_Iso_conv_inv_I_inv_I {c c' : C} (h : c –≻ c') :\n    Cat_Iso_conv_inv (((inverse_morphism I) _a) (((iso_morphism I) _a) h)) = h.\n  Proof.\n    match goal with\n      [|- ?A = ?B] =>\n      let H := fresh \"H\" in\n      cut (A ~= B); [intros H; rewrite H; trivial|]\n    end.\n    unfold Cat_Iso_conv_inv.\n    destruct Cat_Iso_Hom_conv.\n    change (I ⁻¹ _a ((iso_morphism I) _a h)) with ((I ⁻¹ ∘ I)%morphism _a h).\n    apply (@JMeq_trans _ _ _ _ ((Functor_id _) _a h) _); trivial.\n    cbn_rewrite <- (left_inverse I).\n    trivial.\n  Qed.\n\n  (** Morphism composition commutes with conversion. *)\n  Theorem Cat_Iso_conv_inv_compose {c c' c'' : C}\n          (h :\n             (((inverse_morphism I) _o) (((iso_morphism I) _o) c))\n               –≻ (((inverse_morphism I) _o) (((iso_morphism I) _o) c'))\n          )\n          (h' :\n             (((inverse_morphism I) _o) (((iso_morphism I) _o) c'))\n               –≻ (((inverse_morphism I) _o) (((iso_morphism I) _o) c''))\n          )\n    :\n      Cat_Iso_conv_inv (compose C h h') = compose C (Cat_Iso_conv_inv h) (Cat_Iso_conv_inv h').\n  Proof.\n    unfold Cat_Iso_conv_inv, Cat_Iso_Hom_conv.\n    do 3 destruct Cat_Iso_Obj_conv; trivial.\n  Qed.\n\nEnd Cat_IConv.\n\nSection Cat_Iso_inv.\n  Context {C D : Category} (I : C ≃≃ D ::> Cat).\n\n  (** The main theorem of this module. Given an isomorphism I between categories C and D, for each morphism h: Hom (I _o c) (I _o c') in D, there is a morphism g in C such that the conversion of h through I (I _a g) gives back the smae arrow, i.e., h = (I _a h). *)\n  Theorem Cat_Iso_inv {c c' : C} (h : ((iso_morphism I) _o c) –≻ ((iso_morphism I) _o c'))\n    : {g : c –≻ c' | h = ((iso_morphism I) _a g)}.\n  Proof.\n    exists (Cat_Iso_conv_inv I ((inverse_morphism I) _a h)).\n    match goal with\n      [|- ?A = ?B] =>\n        etransitivity;\n        [apply (eq_sym (@Cat_Iso_conv_inv_I_inv_I D C (I⁻¹) _ _ A))|\n         etransitivity; [|apply (@Cat_Iso_conv_inv_I_inv_I D C (I⁻¹) _ _ B)]]\n    end.\n    do 2 apply f_equal.\n    match goal with\n      [|- ?A = ?B] =>\n        etransitivity;\n        [apply (eq_sym (@Cat_Iso_conv_Cat_Iso_conv_inv C D I _ _ A))|\n         etransitivity; [|apply (@Cat_Iso_conv_Cat_Iso_conv_inv C D I _ _ B)]]\n    end.\n    apply f_equal.\n    rewrite Cat_Iso_conv_inv_I_inv_I; trivial.\n  Qed.\n\nEnd Cat_Iso_inv.\n\n(**\nGiven I : C ≃ D for categories C and D and F : D -> E, F ∘ (I ∘ I⁻¹) and F are\nnaturally isomorphic.\n*)\nSection IsoCat_NatIso.\n  Context {C D : Category} (I : (C ≃≃ D ::> Cat)%morphism) {E : Category} (F : (D –≻ E)%functor).\n\n  Program Definition IsoCat_NatIso :\n    ((F ∘ ((iso_morphism I) ∘ (I⁻¹)%morphism))%functor ≃ F)%natiso :=\n    {|\n      iso_morphism := IsoCat_NatTrans I F;\n      inverse_morphism := IsoCat_NatTrans_back I F\n    |}\n  .\n\n  Next Obligation.\n  Proof.\n    apply NatTrans_eq_simplify.\n    FunExt.\n    cbn.\n    match goal with\n      [|- ((match ?e with _ => _ end) ∘ (match ?e with _ => _ end))%morphism = _] =>\n      destruct e\n    end.\n    auto.\n  Qed.\n\n  Next Obligation.\n  Proof.\n    apply NatTrans_eq_simplify.\n    FunExt.\n    cbn.\n    match goal with\n      [|- ((match ?e with _ => _ end) ∘ (match ?e with _ => _ end))%morphism = _] =>\n      destruct e\n    end.\n    auto.\n  Qed.\n\nEnd IsoCat_NatIso.\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/Cat/Cat_Iso.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.6847641339445593}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Bool List Relations Wf Eqdep_dec Omega.\n\nSet Implicit Arguments.\n\n(* Notations for subset or subrel set theoretic operators *)\n\nNotation \"X '⊆' Y\" := (forall x, X x -> Y x) (at level 75, format \"X  ⊆  Y\", no associativity).\nNotation \"X '≃' Y\" := ((X ⊆ Y) * (Y ⊆ X))%type (at level 75, format \"X  ≃  Y\", no associativity).\n\nFact inc1_refl X (A : X -> Type) : A ⊆ A.\nProof. auto. Qed.\n\nFact inc1_trans X (A B C : X -> Type) : A ⊆ B -> B ⊆ C -> A ⊆ C.\nProof. intros; auto. Qed.\n\nFact eq1_refl X (A : X -> Type) : A ≃ A.\nProof. tauto. Qed.\n\nFact eq1_sym X (A B : X -> Type) : A ≃ B -> B ≃ A.\nProof. tauto. Qed.\n\nFact eq1_trans X (A B C : X -> _) : A ≃ B -> B ≃ C -> A ≃ C.\nProof. intros [] [];  split; intros; auto. Qed.\n\nFact equal_eq1 X (A B : X -> _) : A = B -> A ≃ B.\nProof. intros []; auto. Qed.\n\n(* intersection *)\n\nNotation \"A '∩' B\" := (fun z => A z * B z : Type)%type (at level 50, format \"A  ∩  B\", left associativity).\nNotation \"A '∪' B\" := (fun z => A z + B z : Type)%type (at level 50, format \"A  ∪  B\", left associativity).\n\n(** ⊆ ≃ ∩ ∪ *)\n\nNotation \"X '≡' Y\" := ((X->Y)*(Y->X))%type (at level 80, format \"X  ≡  Y\", no associativity).\n\nNotation sg := (@eq _).\n\nFact sg_inc1 X (A : X -> Type) x : A x ≡ sg x ⊆ A. \nProof. \n  split.\n  + intros ? ? []; trivial.\n  + intros H; apply H; auto. \nQed.\n\n", "meta": {"author": "DmxLarchey", "repo": "Coq-Phase-Semantics", "sha": "52f7751ac71ab6d19fbc0a5a5c552a6ddd8e3b17", "save_path": "github-repos/coq/DmxLarchey-Coq-Phase-Semantics", "path": "github-repos/coq/DmxLarchey-Coq-Phase-Semantics/Coq-Phase-Semantics-52f7751ac71ab6d19fbc0a5a5c552a6ddd8e3b17/coq.nc/rel_utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.6847641328661235}}
{"text": "Require Export ZArith.\nRequire Export ZArithRing.\n\nOpen Scope Z_scope.\n\n(* The following tactic looks for all the instances of\n   \"Zpos (xO p)\" and \"Zpos (xI p)\" and replaces them with\n   polynomial expressions in p, but avoids doing it for the numbers\n   2 and 3 which are \"Zpos (xO xH)\" and \"Zpos (xI xH)\". *)\n\nLtac Zpos_x_tac :=\n match goal with\n   |- context [Zpos (xO ?P)] =>\n       match P with\n        | xH => fail 1\n        | ?X2 => rewrite (Zpos_xO X2); Zpos_x_tac\n       end\n | |- context [Zpos (xI ?P)] =>\n       match P with\n        | xH => fail 1\n        | ?X2 => rewrite (Zpos_xI X2); Zpos_x_tac\n       end\n | |- _ => idtac\n end.\n\n(* Here is an example using this tactic. *)\n\nTheorem ex1 :\n  forall p, Zpos (xO (xI p))=4*(Zpos p)+2.\nProof.\n intros p.\n Zpos_x_tac.\n rewrite Zmult_plus_distr_r; simpl (2*1).\n rewrite Zmult_assoc; reflexivity.\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/ch7_tactics_automation/SRC/Zpos_x_tac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6847621525228876}}
{"text": "Require Import Arith.\nRequire Import List.\nImport ListNotations.\n\nSet Implicit Arguments.\n\nLemma leb_false_lt : forall m n, leb m n = false -> n < m.\nProof.\n  induction m; intros.\n  - discriminate.\n  - simpl in *.\n    destruct n; subst; auto with arith.\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-serapi/tests/async/quote.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6847621314901646}}
{"text": "Require Import MSetInterface.\nModule RedBlackTree.\nDeclare Module X:OrderedType.\nDefinition key := X.t.\n\n\nInductive color := Red | Black.\n\nInductive tree :=\n  | Leaf : tree\n  | Node : tree -> key -> tree -> color -> tree.\n\n(** The [mem] function is deciding membership. It exploits the\n    binary search tree invariant to achieve logarithmic complexity. *)\nFixpoint mem x s :=\n   match s with\n     |  Leaf => false\n     |  Node l y r _ => match X.compare x y with\n             | Lt => mem x l\n             | Eq => true\n             | Gt => mem x r\n         end\n   end.\n\n(* inserts an element into a tree\n * needs and preserves red black binary search tree\n *)\nFixpoint insert (x:key) (t:tree) : tree := t.\n\n(* deleets an element out of a tree\n * needs and preserves red black binary search tree\n *)\nFixpoint delete (x:key) (t:tree) : tree := t.\n\n\n\n\n(** ** x is in a tree *)\n\nInductive isMem (x : key) : tree -> Prop :=\n  | IsMemRoot : forall l y r c, X.eq x y -> isMem x (Node l y r c)\n  | IsMemLeft : forall l y r c, isMem x l -> isMem x (Node l y r c)\n  | IsMemRight : forall l y r c, isMem x r -> isMem x (Node l y r c).\n\n\n\n\n(** ** Binary Search Tree property *)\n\n(* all elements in s are less than x *)\nDefinition lt_tree x s := forall y, isMem y s -> X.lt y x.\n(* all elemens in s are greater than x *)\nDefinition gt_tree x s := forall y, isMem y s -> X.lt x y.\n \n(** [BST t] : [t] is a binary search tree\n * all in l are less than x\n * all in r are greater than x\n *)\nInductive isBST : tree -> Prop :=\n  | BSTLeaf : isBST Leaf\n  | BSTNode : forall x l r h, isBST l -> isBST r ->\n     lt_tree x l -> gt_tree x r -> isBST (Node l x r h).\n\n\n\n(** ** Not Red Red property *)\n\nInductive isBlack : tree -> Prop :=\n  | IsBlackLeaf : isBlack Leaf\n  | IsBlackNode : forall l x r, isBlack (Node l x r Black).\n\n(* no two successing red nodes *)\nInductive isNotRedRed : tree -> Prop :=\n  | IsBlack: forall t, isBlack t -> isNotRedRed t\n  | IsNotRedRed : forall l x r, isBlack l -> isBlack r -> isNotRedRed (Node l x r Red).\n\n\n\n(** ** Same Black Heights *)\n\n(* \"to every leaf the number of black nodes is the same\" *)\nInductive isSameBlackdepth' : nat -> tree -> Prop :=\n  | IsSameBlackdepthLeaf : isSameBlackdepth' O Leaf\n  | IsSameBlackdepthRed   : forall n l x r, isSameBlackdepth' n l -> isSameBlackdepth' n r -> isSameBlackdepth' n (Node l x r Red)\n  | IsSameBlackdepthBlack : forall n l x r, isSameBlackdepth' n l -> isSameBlackdepth' n r -> isSameBlackdepth' (S n) (Node l x r Black).\n\nInductive isSameBlackdepth : tree -> Prop :=\n  | IsSameBlackdepth : forall t, (exists n, isSameBlackdepth' n t) -> isSameBlackdepth t.\n\n\n(** ** Red Black property *)\n\nInductive isRedBlack : tree -> Prop :=\n  | IsRedBlack : forall t, isNotRedRed t -> isSameBlackdepth t -> isRedBlack t.\n\n\n\n(** ** Red Black Binary Search Tree *)\n\nInductive isRBBST : tree -> Prop :=\n  | IsRBBST : forall t, isBST t -> isRedBlack t -> isRBBST t.\n\n\n\n(** ** Proof of [mem] **)\n\nLemma mem_spec : forall t x `{isBST t}, mem x t = true <-> isMem x t.\n\n\n\n(** ** Proofs of [insert] and [delete] *)\n\nDefinition stays_rbbst f := forall t, isRBBST t <-> isRBBST (f t).\n\n(** ** Proof of [insert] *)\n\nLemma insert_inserts : forall x t, isMem x (insert x t).\n\nLemma insert_stays_rbbst : forall x, stays_rbbst (insert x).\n\n\n\n(** ** Proof of [delete] *)\n\nLemma delete_deletes : forall x t, ~ isMem x (delete x t).\n\nLemma delete_stays_rbbst : forall x, stays_rbbst (delete x).\n\n\n", "meta": {"author": "payload", "repo": "coq-redblacktree-fun", "sha": "1c3fc8c45eac5c84c8142eca4515145d300b36d8", "save_path": "github-repos/coq/payload-coq-redblacktree-fun", "path": "github-repos/coq/payload-coq-redblacktree-fun/coq-redblacktree-fun-1c3fc8c45eac5c84c8142eca4515145d300b36d8/sketch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6847621222897843}}
{"text": "(* Require Import ZArith. *)\n(* Open Scope Z_scope. *)\n(* ... *)\n\n(* Open Scope nat_scope. *)\n\nLemma congruence_demo :\n  forall (f : nat -> nat -> nat) (g h : nat -> nat) (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.\nProof. congruence. Qed.\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)).\nProof. congruence. Qed.\n\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/s2.3.4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.68476104366833}}
{"text": "Axiom law_of_excluded_middle : forall (P : Prop), P \\/ ~P.\n\nTheorem neq_comm : forall (A: Type)(a b : A), a <> b -> b <> a.\nProof.\nintros. unfold not. intros. rewrite H0 in H. apply H. reflexivity.\nQed.\n\nTheorem de_morgan1 : forall (P Q R : Prop),\n  (P \\/ Q) /\\ R -> (P /\\ R) \\/ (Q /\\ R).\nProof.\nintros. destruct H. inversion H.\n- apply or_introl. apply conj. apply H1. apply H0.\n- apply or_intror. apply conj. apply H1. apply H0.\nQed.\n\nTheorem de_morgan2 : forall (P Q R : Prop),\n  (P /\\ Q) \\/ R -> (P \\/ R) /\\ (Q \\/ R).\nProof.\nintros. apply conj.\n- inversion H.\n  + apply proj1 in H0. apply or_introl. apply H0.\n  + apply or_intror. apply H0.\n- inversion H.\n  + apply proj2 in H0. apply or_introl. apply H0.\n  + apply or_intror. apply H0.\nQed.\n\nTheorem reduce_or_P_and_notP : forall (P Q : Prop),\n  (Q \\/ P) /\\ ~P -> Q.\nProof.\nintros. apply de_morgan1 in H. inversion H.\n- apply H0.\n- apply proj1 in H0 as H1. apply proj2 in H0 as H2. contradiction.\nQed.\n\nTheorem not_not_P : forall (P :Prop),\n  not (not P) <-> P.\nProof.\nintros. assert (lem : P \\/ ~P).\n{ apply law_of_excluded_middle. }\ninversion lem.\n- unfold iff. apply conj.\n  + intros. apply H.\n  + intros. intros H1. contradiction.\n- unfold iff. apply conj.\n  + intros. contradiction.\n  + intros. contradiction.\nQed.\n\nTheorem contrapositive : forall (P Q: Prop),\n  (P -> Q) <-> (~Q -> ~P).\nProof.\nintros. unfold iff. apply conj.\n- intros. intro. apply H0. apply H. apply H1.\n- intros. apply not_not_P. intro. apply H in H1. contradiction.\nQed.\n\nTheorem not_or : forall (P Q: Prop),\n  ~(P \\/ Q) <-> ~P /\\ ~Q.\nProof.\nintros. unfold iff. apply conj.\n- intros. apply conj. \n  + intro. apply H. left. apply H0.\n  + intro. apply H. right. apply H0.\n- intros. destruct H as [nP nQ].\n  intro. destruct H as [P_|Q_]. contradiction. contradiction.\nQed.\n\nTheorem not_and : forall (P Q: Prop),\n  ~(P /\\ Q) <-> ~P \\/ ~Q.\nProof.\nintros. unfold iff. apply conj.\n- intros. apply not_not_P. intro. apply not_or in H0. destruct H0 as [P_ Q_].\n  apply H. apply not_not_P with (P:=P) in P_. apply not_not_P with (P:=Q) in Q_.\n  apply conj. apply P_. apply Q_.\n- intros. intro. destruct H0 as [Pt Qt]. destruct H as [Pf|Qf]. contradiction. contradiction.\nQed. \n\nTheorem iff_iff_compat_l : forall A B C : Prop,\n(B <-> C) -> ((A <-> B) <-> (A <-> C)).\nProof.\nintros. apply iff_to_and. apply conj.\n- intros. apply iff_trans with (B:=B). apply H0. apply H.\n- intros. apply iff_trans with (B:=C). apply H0. apply iff_sym. apply H.\nQed.\n\nTheorem iff_iff_compat_r : forall A B C : Prop,\n(B <-> C) -> ((B <-> A) <-> (C <-> A)).\nProof.\nintros. apply iff_to_and. apply conj.\n- intros. apply iff_trans with (B:=B). apply iff_sym. apply H. apply H0.\n- intros. apply iff_trans with (B:=C). apply H. apply H0.\nQed.\n\nTheorem and_to_imply : forall A B C : Prop,\n  ((A /\\ B) -> C) <-> (A -> B -> C).\nProof.\nintros. unfold iff. apply conj.\n- intros. apply H. apply conj. apply H0. apply H1.\n- intros. apply H. apply H0. apply H0.\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/Logic_utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.6847610219615451}}
{"text": "From mathcomp Require Import ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nRequire Import function_theories.\n\nSection FunctionCompositeTheories.\n  Variable U:Type.\n  Variables F G H: U -> U.\n  Variables A B C D: Ensemble U.\n\n  Theorem function_composite_assoc:\n    forall (f g h: Ensemble (Ensemble (Ensemble U))),\n      f ≔ F ⊦ A ⟼ B /\\ g ≔ G ⊦ B ⟼ C /\\ h ≔ H ⊦ C ⟼ D -> h ∘ (g ∘ f) = (h ∘ g) ∘ f.\n  Proof.\n    move => f g h.\n    case => [[Hf HfS] [[Hg HgS] [Hh HhS]]].\n    move: (compound_correspondence_assoc) => H0.\n    apply (H0 U A B C D (fun (x y:U) => y = F x) (fun (x y:U) => y = G x) (fun (x y:U) => y = H x) f g h).\n    split.\n    apply Hf.\n    split.\n    apply Hg.\n    apply Hh.\n  Qed.\n\n  Theorem function_composite_image:\n    forall (f g: Ensemble (Ensemble (Ensemble U))) (X:Ensemble U),\n      X ⊂ A /\\ f ≔ F ⊦ A ⟼ B /\\ g ≔ G ⊦ B ⟼ C ->\n      (g ∘ f) '' X = g '' (f '' X).\n  Proof.\n    move => f g X.\n    case => HA [[Hf HfS] [Hg HgS]].\n    move: image_compound_correspondence_eq => H0.\n    apply (H0 U A B C X (fun x y:U => y = F x) (fun x y:U => y = G x) f g).\n    split; done.\n  Qed.\n\n  Theorem function_composite_value:\n    forall (f g: Ensemble (Ensemble (Ensemble U))) (x:U),\n      x ∈ A /\\ f ≔ F ⊦ A ⟼ B /\\ g ≔ G ⊦ B ⟼ C ->\n      (g ∘ f) '' {| x |} = g '' (f '' {| x |}).\n  Proof.\n    move => f g x.\n    case => HA [Hf Hg].\n    move: function_composite_image => H0.\n    apply (H0 f g {|x|}).\n    split.\n    move => x' Hx'.\n    apply singleton_eq_iff in Hx'.\n    rewrite Hx'.\n    done.\n    split; done.\n  Qed.\n\n  Goal forall (f idA: Ensemble (Ensemble (Ensemble U))),\n      f ≔ F ⊦ A ⟼ B /\\ IdentityMapping idA A -> f = f ∘ idA.\n  Proof.\n    move => f idA.\n    case => [[Hf HfS] [HidA HidAS]].\n    apply /Extensionality_Ensembles.\n    rewrite Hf HidA.\n    split => Z H0.\n    +inversion H0 as [x y].\n     inversion H1.\n     split.\n     exists x.\n     split.\n     split.\n     split.\n     reflexivity.\n     inversion H4.\n     inversion H5 as [x' [y']].\n     inversion H7.\n     inversion H9.\n     apply ordered_pair_iff in H11.\n     inversion H11.\n     rewrite H12.\n     split.\n     exists x'.\n     exists x'.\n     split.\n     apply H8.\n     split.\n     apply H8.\n     done.\n     rewrite H2.\n     apply H0.\n    +inversion H0.\n     inversion H1.\n     inversion H3.\n     inversion H4.\n     inversion H7.\n     apply ordered_pair_iff in H6.\n     inversion H6.\n     rewrite -H10.\n     rewrite -H8.\n     rewrite H11.\n     apply H5.\n  Qed.\n\n  Goal forall (f idB: Ensemble (Ensemble (Ensemble U))),\n      f ≔ F ⊦ A ⟼ B /\\ IdentityMapping idB B -> f = idB ∘ f.\n  Proof.\n    move => f idB.\n    case => [[Hf HfS] [HidB HidBS]].\n    rewrite Hf HidB.\n    apply /Extensionality_Ensembles.\n    split => Z H0.\n    +inversion H0 as [x y].\n     inversion H1.\n     inversion H4.\n     inversion H5 as [x' [y']].\n     inversion H7 as [H8 [H9 H10]].\n     apply ordered_pair_iff in H10.\n     inversion H10.\n     split.\n     exists y.\n     split.\n     rewrite H2.\n     apply H0.\n     split.\n     split.\n     reflexivity.\n     split.\n     exists y'.\n     exists y'.\n     split.\n     apply H9.\n     split.\n     apply H9.\n     rewrite H12.\n     done.\n    +inversion H0.\n     inversion H1 as [z [H3 H4]].\n     inversion H4 as [x' y' [H5 H6]].\n     rewrite H5 in H7.\n     apply ordered_pair_iff in H7.\n     inversion H7.\n     rewrite H8 in H9.\n     rewrite -H9.\n     apply H3.\n  Qed.\n\nEnd FunctionCompositeTheories.\n\nRequire Export function_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/function_composite_theories.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544448, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.684707701204559}}
{"text": "(** * Gambler.v : gambler dream to win a little might lead to loose a lot *)\n(** Source : Abstraction, refinement and proof for probabilistic systems \n    A. McIver and C. Morgan, Springer *)\nAdd Rec LoadPath \"../src\" as ALEA.\n\nRequire Export Cover.\nRequire Export Misc.\nRequire Export DistrTactic.\nRequire Export Arith.\n\n(* begin hide *)\nSet Implicit Arguments.\nOpen Local Scope U_scope.\nOpen Local Scope O_scope.\n\n(* end hide *)\n\n(** ** Strategy\nthe gambler doubles his bet until he wins or he runs out of money\nhe starts with enough money to play n-times, ie\n   (1 + 2 + ...+ 2^{n-1})b = (2^n-1)b\n<<\nlet rec play n b =\n        if n = 0 then 0 \n        else if flip then (2^n) b else play n (2b)\n>>\n*)\n\nSection Gamble.\n\nFixpoint pow2 (n:nat) : nat := \n   match n with O => 1%nat | S p => (2 * (pow2 p))%nat end.\n\nFixpoint play (n:nat) (b:nat) : distr nat := \n    match n with \n      O => Munit O\n    | S p => Mif Flip (Munit ((pow2 n) * b)%nat) (play p (2*b))\n    end.\n\nLemma pow2not0 : forall n, pow2 n <> O.\ninduction n; simpl; omega.\nSave.\nHint Resolve pow2not0.\n\n\nLemma proba_loose : forall n b, ~ b=O -> mu (play n b) (carac_eq O)== [1/2]^n.\ninduction n; intros.\nsimpl; auto.\nsimpl.\nreplace (pow2 n + (pow2 n + 0))%nat with (pow2 (S n)) by trivial.\nrewrite (cover_eq_zero _ (is_eq O)).\nrepeat Usimpl.\napply IHn.\nomega.\napply not_eq_sym.\napply NPeano.Nat.neq_mul_0; auto.\nSave.\n\nLemma proba_win : forall n b, ~ b=O -> mu (play n b) (carac_eq ((pow2 n) * b)%nat)== [1-]([1/2]^n).\ninduction n; intros.\nsimpl; repeat Usimpl.\nrewrite (cover_eq_zero _ (is_eq (b + 0))); intuition.\nsimpl.\nrewrite (cover_eq_one _ (is_eq (pow2 (S n) * b)%nat)); trivial.\nrepeat Usimpl.\nreplace ((pow2 n + (pow2 n + 0)) * b)%nat with (pow2 n * (2*b))%nat.\nrewrite IHn.\nrewrite <- Uinv_half; repeat Usimpl; auto.\nomega.\nring.\nSave.\n\nEnd Gamble.\n", "meta": {"author": "hivert", "repo": "Coq-HookLength", "sha": "f9f044a6defdeea7db48d8fe38735c32129cd928", "save_path": "github-repos/coq/hivert-Coq-HookLength", "path": "github-repos/coq/hivert-Coq-HookLength/Coq-HookLength-f9f044a6defdeea7db48d8fe38735c32129cd928/ALEA/examples/Gambler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.6846591655741942}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect.\nRequire Import ssrbool.\nRequire Import ssrfun.\nRequire Import eqtype.\nRequire Import ssrnat.\nRequire Import seq.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(* The basic theory of paths over a dataSet; this is essentially a   *)\n(* complement to seq.v.                                              *)\n(* Paths are non-empty sequences that obey a progression relation.   *)\n(* They are passed around in three parts : the head and tail of the  *)\n(* sequence, and a (boolean) predicate asserting the progression.    *)\n(* This is rarely embarrassing, as the first two are usually         *)\n(* implicit parameters inferred from the predicate, and it saves the *)\n(* hassle of constantly constructing and destructing a dependent     *)\n(* record. We allow duplicates; uniqueness, if desired (as is the    *)\n(* case for several geometric constructions), must be asserted       *)\n(* separately. We do provide shorthand, but for cycles only, because *)\n(* the equational properties of \"path\" and \"uniq\" are unfortunately  *)\n(* incompatible (esp. wrt \"cat\").                                    *)\n(*    We define similarly cycles, but in this case we allow the      *)\n(* empty sequence (which is a non-rooted empty cycle; by contrast,   *)\n(* the empty path from x is the one-item sequence containing only x) *)\n(*    We define notations for the common cases of function paths,    *)\n(* where the progress relation is actually a function. We also       *)\n(* define additional traversal/surgery operations, many of which     *)\n(* could have been in seq.v, but are here because they only really   *)\n(* are useful for sequences considered as paths :                    *)\n(*  - directed surgery : splitPl, splitP, splitPr are dependent      *)\n(*    predicates whose elimination splits a path x0:p at one of its  *)\n(*    elements (say x). The three variants differ as follows:        *)\n(*      - splitPl applies when x in in x0:p, generates two paths p1  *)\n(*        and p2, along with the equation x = (last x0 p), and       *)\n(*        replaces p with (cat p1 p2) in the goal (the patterned     *)\n(*        Elim can be used to select occurrences and generate an     *)\n(*        equation p = (cat p1 p2).                                  *)\n(*      - splitP applies when x is in p, and replaces p with         *)\n(*        (cat (add_last p1 x) p2), where x appears explicitly at    *)\n(*        the end of the left part.                                  *)\n(*      - splitPr similarly replaces p with (cat p1 (Adds x p2)),    *)\n(*        where appears explicitly at the right of the split, when x *)\n(*        is actually in p.                                          *)\n(*    The parts p1 and p2 are computed using index/take/drop. The    *)\n(*    splitP variant (but not the others) attempts to replace the    *)\n(*    explicit expressions for p1 and p2 by p1 and p2, respectively. *)\n(*    This is moderately useful, allows for defining other splitting *)\n(*    lemmas with conclusions of the form (split x p p1 p2), with    *)\n(*    other expressions for p1 and p2 that might be known to occur.  *)\n(*  - function trajectories: traject, and a looping predicate.       *)\n(*  - cycle surgery : arc extracts the sub-arc between two points    *)\n(*    (including the first, excluding the second). (arc p x y) is    *)\n(*    thus only meaningful if x and y are different points in p.     *)\n(*  - cycle traversal : next, prev                                   *)\n(*  - path order: mem2 checks whether two points belong to a         *)\n(*    and appear in order (i.e., (mem2 p x y) checks that y appears  *)\n(*    after an occurrence of x in p). This predicate a crucial part  *)\n(*    of the definition of the abstract Jordan property.             *)\n(*  - loop removal : shorten returns a shorter, duplicate-free path  *)\n(*    with the same endpoints as its argument. The related shortenP  *)\n(*    dependent predicate simultaneously substitutes a new path p',  *)\n(*    for (shorten e x p), (last x p') for (last x p), and generates *)\n(*    predicates asserting that p' is a duplicate-free subpath of p. *)\n(* Although these functions operate on the underlying sequences, we  *)\n(* provide a series of lemmas that define their interaction with the *)\n(* path and cycle predicates, e.g., the path_cat equation can be     *)\n(* used to split the path predicate after splitting the underlying   *)\n(* sequence.                                                         *)\n\nSection Paths.\n\nVariables (n0 : nat) (T : Type).\n\nSection Path.\n\nVariables (x0_cycle : T) (e : rel T).\n\nFixpoint path x (p : seq T) {struct p} :=\n  if p is y :: p' then e x y && path y p' else true.\n\nLemma path_cat : forall x p1 p2,\n  path x (p1 ++ p2) = path x p1 && path (last x p1) p2.\nProof.\nby move=> x p1 p2; elim: p1 x => [|y p1 Hrec] x //=; rewrite Hrec -!andbA.\nQed.\n\nLemma pathP : forall x p x0,\n  reflect (forall i, i < size p -> e (sub x0 (x :: p) i) (sub x0 p i))\n          (path x p).\nProof.\nmove=> x p x0; elim: p x => [|y p Hrec] x /=; first by left.\napply: (iffP andP) => [[Hxy Hp]|Hp].\n  move=> [|i] Hi //; exact: Hrec _ Hp i Hi.\nsplit; first exact: Hp 0 (leq0n (size p)).\napply/(Hrec y) => i; exact: Hp i.+1.\nQed.\n\nDefinition cycle p := if p is x :: p' then path x (add_last p' x) else true.\n\nLemma cycle_path : forall p, cycle p = path (last x0_cycle p) p.\nProof. by move=> [|x p] //=; rewrite -cats1 path_cat /= andbT andbC. Qed.\n\nLemma cycle_rot : forall p, cycle (rot n0 p) = cycle p.\nProof.\ncase: (n0) => [|n] [|y0 p] //=; first by rewrite /rot /= cats0.\nrewrite /rot /= -{3}(cat_take_drop n p) -cats1 -catA path_cat.\ncase: (drop n p) => [|z0 q]; rewrite /= -cats1 !path_cat /= !andbT andbC //.\nby rewrite last_cat; repeat bool_congr.\nQed.\n\nLemma cycle_rotr : forall p, cycle (rotr n0 p) = cycle p.\nProof. by move=> p; rewrite -cycle_rot rotrK. Qed.\n\nEnd Path.\n\nLemma eq_path : forall e e', e =2 e' -> path e =2 path e'.\nProof.\nby move=> e e' Ee x p; elim: p x => [|y p Hrec] x //=; rewrite Ee Hrec.\nQed.\n\nLemma sub_path : forall e e', subrel e e' ->\n  forall x p, path e x p -> path e' x p.\nProof.\nmove=> e e' He x p; elim: p x => [|y p Hrec] x //=.\nby move/andP=> [Hx Hp]; rewrite (He _ _ Hx) (Hrec _ Hp).\nQed.\n\nEnd Paths.\n\nImplicit Arguments pathP [T e x p].\nPrenex Implicits pathP.\n\nSection EqPath.\n\nVariables (n0 : nat) (T : eqType) (x0_cycle : T) (e : rel T).\n\nCoInductive split x : seq T -> seq T -> seq T -> Type :=\n  Split p1 p2 : split x (add_last p1 x ++ p2) p1 p2.\n\nLemma splitP : forall (p : seq T) x, x \\in p ->\n   let i := index x p in split x p (take i p) (drop i.+1 p).\nProof.\nmove=> p x Hx i; have := esym (cat_take_drop i p).\nhave Hi := Hx; rewrite -index_mem -/i in Hi; rewrite (drop_sub x Hi).\nby rewrite -cat_add_last {2}/i (sub_index x Hx) => Dp; rewrite {1}Dp.\nQed.\n\nCoInductive splitl (x1 x : T) : seq T -> Type :=\n  Splitl p1 p2 of last x1 p1 = x : splitl x1 x (p1 ++ p2).\n\nLemma splitPl : forall x1 p x, x \\in x1 :: p -> splitl x1 x p.\nProof.\nmove=> x1 p x; rewrite in_adds.\ncase: eqP => [->| _]; first by rewrite -(cat0s p).\ncase/splitP; split; exact: last_add_last.\nQed.\n\nCoInductive splitr x : seq T -> Type :=\n  Splitr p1 p2 : splitr x (p1 ++ x :: p2).\n\nLemma splitPr : forall (p : seq T) x, x \\in p -> splitr x p.\nProof. by move=> p x; case/splitP=> p1 p2; rewrite cat_add_last. Qed.\n\nFixpoint next_at (x y0 y : T) (p : seq T) {struct p} :=\n  match p with\n  | seq0 => if x == y then y0 else x\n  | y' :: p' => if x == y then y' else next_at x y0 y' p'\n  end.\n\nDefinition next p x := if p is y :: p' then next_at x y y p' else x.\n\nFixpoint prev_at (x y0 y : T) (p : seq T) {struct p} :=\n  match p with\n  | seq0     => if x == y0 then y else x\n  | y' :: p' => if x == y' then y else prev_at x y0 y' p'\n  end.\n\nDefinition prev p x := if p is y :: p' then prev_at x y y p' else x.\n\nLemma next_sub : forall p x,\n  next p x = if x \\in p then\n               if p is y :: p' then sub y p' (index x p) else x\n             else x.\nProof.\nmove=> [|y0 p] x //=; elim: p {2 3 5}y0 => [|y' p Hrec] y /=;\n  by rewrite (eq_sym y) in_adds; case (x == y); try exact: Hrec.\nQed.\n\nLemma prev_sub : forall p x,\n  prev p x = if x \\in p then\n               if p is y :: p' then sub y p (index x p') else x\n             else x.\nProof.\nmove=> [|y0 p] x //=; rewrite in_adds orbC.\nelim: p {2 5}y0 => [|y' p Hrec] y; rewrite /= ?in_adds // (eq_sym y').\nby case (x == y') => /=; auto.\nQed.\n\nLemma mem_next : forall (p : seq T) x, (next p x \\in p) = (x \\in p).\nProof.\nmove=> p x; rewrite next_sub; case Hpx: (x \\in p) => //.\ncase: p (index x p) Hpx => [|y0 p'] //= i _; rewrite in_adds.\ncase: (ltnP i (size p')) => Hi; first by rewrite /= (mem_sub y0 Hi) orbT.\nby rewrite (sub_default y0 Hi) eqxx.\nQed.\n\nLemma mem_prev : forall (p : seq T) x, (prev p x \\in p) = (x \\in p).\nProof.\nmove=> p x; rewrite prev_sub; case Hpx: (x \\in p) => //.\ncase: p Hpx => [|y0 p'] Hpx //.\nby apply mem_sub; rewrite /= ltnS index_size.\nQed.\n\n(* ucycleb is the boolean predicate, but ucycle is defined as a Prop *)\n(* so that it can be used as a coercion target. *)\nDefinition ucycleb p := cycle e p && uniq p.\nDefinition ucycle p : Prop := cycle e p && uniq p.\n\n(* Projections, used for creating local lemmas. *)\nLemma ucycle_cycle : forall p, ucycle p -> cycle e p.\nProof. by move=> p; case/andP. Qed.\n\nLemma ucycle_uniq : forall p, ucycle p -> uniq p.\nProof. by move=> p; case/andP. Qed.\n\nLemma next_cycle : forall p x, cycle e p -> x \\in p -> e x (next p x).\nProof.\nmove=> [|y0 p] //= x.\nelim: p {1 3 5}y0 => [|y' p Hrec] y /=; rewrite in_adds.\n  by rewrite andbT orbF => Hy Dy; rewrite Dy (eqP Dy).\nmove/andP=> [Hy Hp]; case: (x =P y) => [->|_] //; exact: Hrec.\nQed.\n\nLemma prev_cycle : forall p x, cycle e p -> x \\in p -> e (prev p x) x.\nProof.\nmove=> [|y0 p] //= x; rewrite in_adds orbC.\nelim: p {1 5}y0 => [|y' p Hrec] y /=; rewrite ?in_adds.\n  by rewrite andbT=> Hy Dy; rewrite Dy (eqP Dy).\nmove/andP=> [Hy Hp]; case: (x =P y') => [->|_] //; exact: Hrec.\nQed.\n\nLemma ucycle_rot : forall p, ucycle (rot n0 p) = ucycle p.\nProof. by move=> *; rewrite /ucycle uniq_rot cycle_rot. Qed.\n\nLemma ucycle_rotr : forall p, ucycle (rotr n0 p) = ucycle p.\nProof. by move=> *; rewrite /ucycle uniq_rotr cycle_rotr. Qed.\n\n(* The \"appears no later\" partial preorder defined by a path. *)\n\nDefinition mem2 (p : seq T) x y := y \\in drop (index x p) p.\n\nLemma mem2l : forall p x y, mem2 p x y -> x \\in p.\nProof.\nmove=> p x y; rewrite /mem2 -!index_mem size_drop; move=> Hxy.\nby rewrite -ltn_0sub -(ltn_predK Hxy) ltnS leq0n.\nQed.\n\nLemma mem2lf : forall (p : seq T) x,\n  (x \\in p) = false -> forall y, mem2 p x y = false.\nProof. move=> p x Hx y; apply/idP => Hp; case/idP: Hx; apply: mem2l Hp. Qed.\n\nLemma mem2r : forall p x y, mem2 p x y -> y \\in p.\nProof.\nrewrite /mem2; move=> p x y Hxy.\nby rewrite -(cat_take_drop (index x p) p) mem_cat Hxy orbT.\nQed.\n\nLemma mem2rf : forall (p : seq T) y,\n  (y \\in p) = false -> forall x, mem2 p x y = false.\nProof. move=> p y Hy x; apply/idP => [Hp]; case/idP: Hy; apply: mem2r Hp. Qed.\n\nLemma mem2_cat : forall p1 p2 x y,\n  mem2 (p1 ++ p2) x y = mem2 p1 x y || mem2 p2 x y || (x \\in p1) && (y \\in p2).\nProof.\nmove=> p1 p2 x y; rewrite {1}/mem2 index_cat drop_cat; case Hp1x: (x \\in p1).\n  rewrite index_mem Hp1x mem_cat /= -orbA.\n  by case Hp2: (y \\in p2); [ rewrite !orbT // | rewrite (mem2rf Hp2) ].\nby rewrite ltnNge leq_addr /= orbF addKn (mem2lf Hp1x).\nQed.\n\nLemma mem2_splice : forall p1 p3 x y p2,\n  mem2 (p1 ++ p3) x y -> mem2 (p1 ++ p2 ++ p3) x y.\nProof.\nmove=> p1 p3 x y p2 Hxy; move: Hxy; rewrite !mem2_cat mem_cat.\ncase: (mem2 p1 x y) (mem2 p3 x y) => [|] // [|] /=; first by rewrite orbT.\nby case: (x \\in p1) => [|] //= Hy; rewrite Hy !orbT.\nQed.\n\nLemma mem2_splice1 : forall p1 p3 x y z,\n  mem2 (p1 ++ p3) x y -> mem2 (p1 ++ z :: p3) x y.\nProof. move=> p1 p3 x y z; exact: (mem2_splice [::z]). Qed.\n\nLemma mem2_adds : forall x p y,\n  mem2 (x :: p) y =1 if x == y then predU1 x (mem p) : pred T else mem2 p y.\nProof. by move=> x p y z; rewrite {1}/mem2 /=; case (x == y). Qed.\n\nLemma mem2_last : forall y0 p x,\n  mem2 (y0 :: p) x (last y0 p) = (x \\in y0 :: p).\nProof.\nmove=> y0 p x; apply/idP/idP; first by apply mem2l.\nrewrite -index_mem /mem2; move: (index x _) => i Hi.\nby rewrite lastI drop_add_last ?size_belast // mem_add_last mem_head.\nQed.\n\nLemma mem2l_cat : forall (p1 : seq T) x, (x \\in p1) = false ->\n  forall p2, mem2 (p1 ++ p2) x =1 mem2 p2 x.\nProof. by move=> p1 x Hx p2 y; rewrite mem2_cat (Hx) (mem2lf Hx) /= orbF. Qed.\n\nLemma mem2r_cat : forall (p2 : seq T) y, (y \\in p2) = false ->\n   forall p1 x, mem2 (p1 ++ p2) x y = mem2 p1 x y.\nProof.\nby move=> p2 y Hy p1 x; rewrite mem2_cat (Hy) (mem2rf Hy) andbF !orbF.\nQed.\n\nLemma mem2lr_splice : forall (p2 : seq T) x y,\n    (x \\in p2) = false -> (y \\in p2) = false ->\n  forall p1 p3, mem2 (p1 ++ p2 ++ p3) x y = mem2 (p1 ++ p3) x y.\nProof.\nmove=> p2 x y Hx Hy p1 p3.\nby rewrite catA !mem2_cat !mem_cat Hx Hy (mem2lf Hx) !andbF !orbF.\nQed.\n\nCoInductive split2r (x y : T) : seq T -> Type :=\n  Split2r p1 p2 of y \\in x :: p2 : split2r x y (p1 ++ x :: p2).\n\nLemma splitP2r : forall p x y, mem2 p x y -> split2r x y p.\nProof.\nmove=> p x y Hxy; have Hx := mem2l Hxy.\nhave Hi := Hx; rewrite -index_mem in Hi.\nmove: Hxy; rewrite /mem2 (drop_sub x Hi) (sub_index x Hx).\nby case (splitP Hx); move=> p1 p2; rewrite cat_add_last; split.\nQed.\n\nFixpoint shorten x (p : seq T) {struct p} :=\n  if p is y :: p' then\n    if x \\in p then shorten x p' else y :: shorten y p'\n  else seq0.\n\nCoInductive shorten_spec (x : T) (p : seq T) : T -> seq T -> Type :=\n   ShortenSpec p' of path e x p' & uniq (x :: p') & subpred (mem p') (mem p) :\n     shorten_spec x p (last x p') p'.\n\nLemma shortenP : forall x p, path e x p ->\n   shorten_spec x p (last x p) (shorten x p).\nProof.\nmove=> x p Hp; have: x \\in x :: p by exact: mem_head.\nelim: p x {1 3 5}x Hp => [|y2 p Hrec] x y1.\n  by rewrite mem_seq1 => _; move/eqP->; split.\nrewrite in_adds orbC /=; case/andP=> Hy12 Hp.\ncase: ifP => y2p_x.\n  case: (Hrec _ _ Hp y2p_x) => p' Hp' Up' Hp'p _.\n  by split=> // y; move/Hp'p; exact: predU1r.\ncase: (Hrec y2 _ Hp) => /= [|p' Hp' Up' Hp'p]; first by rewrite mem_head.\nhave{Hp'p} Hp'p: subpred (mem (y2 :: p')) (mem (y2 :: p)).\n  by move=> z; rewrite /= !in_adds; case: (z == y2); last exact: Hp'p.\nrewrite y2p_x -(last_adds x); move/eqP=> xy1.\nsplit=> //=; first by rewrite xy1 Hy12.\nby rewrite {}Up' andbT; apply/negP; move/Hp'p; case/negPf.\nQed.\n\nEnd EqPath.\n\n(* Ordered paths and sorting. *)\n\nSection SortSeq.\n\nVariable T : eqType.\nVariable leT : rel T.\n\nDefinition sorted s := if s is x :: s' then path leT x s' else true.\n\nLemma path_sorted : forall x s, path leT x s -> sorted s.\nProof. by move=> x [|y s] //=; case/andP. Qed.\n\nSection Transitive.\n\nHypothesis leT_tr : transitive leT.\n\nLemma order_path_min : forall x s, path leT x s -> all (leT x) s.\nProof.\nmove=> x [|y s] //=; case/andP=> le_xy; rewrite le_xy /=.\nelim: s => //= z s IHs in y le_xy *; case/andP.\nmove/(leT_tr le_xy)=> le_xz; rewrite le_xz; exact: IHs.\nQed.\n\nLemma sorted_filter : forall a s, sorted s -> sorted (filter a s).\nProof.\nmove=> a s; elim: s => //= x s IHs ord_s.\nmove/(_ (path_sorted ord_s)): IHs; case: (a x) => //=.\ncase def_s': (filter a s) => //= [y s'] ->.\nrewrite (allP (order_path_min ord_s)) //.\nhave: y \\in filter a s by rewrite def_s' mem_head.\nby rewrite mem_filter; case/andP.\nQed.\n\nLemma sorted_uniq : irreflexive leT -> forall s, sorted s -> uniq s.\nProof.\nmove=> leT_irr; elim=> //= x s IHs s_ord.\nrewrite (IHs (path_sorted s_ord)) andbT; apply/negP=> s_x.\nby case/allPn: (order_path_min s_ord); exists x; rewrite // leT_irr.\nQed.\n\nLemma eq_sorted : antisymmetric leT -> forall s1 s2,\n   sorted s1 -> sorted s2 -> perm_eq s1 s2 -> s1 = s2.\nProof.\nmove=> leT_asym; elim=> [|x1 s1 IHs1] s2 //= ord_s1 ord_s2 eq_s12.\n  by case: {+}s2 (perm_eq_size eq_s12).\nhave s2_x1: x1 \\in s2 by rewrite -(perm_eq_mem eq_s12) mem_head.\ncase: s2 s2_x1 eq_s12 ord_s2 => //= x2 s2; rewrite in_adds.\ncase: eqP => [<- _| ne_x12 /= s2_x1] eq_s12 ord_s2.\n  by rewrite {IHs1}(IHs1 s2) ?(@path_sorted x1) // -(perm_adds x1).\ncase: (ne_x12); apply: leT_asym; rewrite (allP (order_path_min ord_s2)) //.\nhave: x2 \\in x1 :: s1 by rewrite (perm_eq_mem eq_s12) mem_head.\ncase/predU1P=> [eq_x12 | s1_x2]; first by case ne_x12.\nby rewrite (allP (order_path_min ord_s1)).\nQed.\n\nLemma eq_sorted_irr : irreflexive leT -> forall s1 s2,\n  sorted s1 -> sorted s2 -> s1 =i s2 -> s1 = s2.\nProof.\nmove=> leT_irr s1 s2 s1_sort s2_sort eq_s12.\nhave: antisymmetric leT.\n  move=> m n; case/andP=> ? ltnm; case/idP: (leT_irr m); exact: leT_tr ltnm.\nmove/eq_sorted; apply=> //; apply: uniq_perm_eq => //; exact: sorted_uniq.\nQed.\n\nEnd Transitive.\n\nHypothesis leT_total : total leT.\n\nFixpoint merge s1 :=\n  if s1 is x1 :: s1' then\n    let fix merge_s1 (s2 : seq T) :=\n      if s2 is x2 :: s2' then\n        if leT x2 x1 then x2 :: merge_s1 s2' else x1 :: merge s1' s2\n      else s1 in\n    merge_s1\n  else id.\n\nLemma path_merge : forall x s1 s2,\n  path leT x s1 -> path leT x s2 -> path leT x (merge s1 s2).\nProof.\nmove=> x s1 s2; elim: s1 s2 x => //= x1 s1 IHs1; elim=> //= x2 s2 IHs2 x.\ncase/andP=> le_x_x1 ord_s1; case/andP=> le_x_x2 ord_s2.\ncase: ifP => le_x21 /=; first by rewrite le_x_x2 {}IHs2 // le_x21.\nby rewrite le_x_x1 IHs1 //=; have:= leT_total x2 x1; rewrite le_x21 /= => ->.\nQed.\n\nLemma sorted_merge : forall s1 s2,\n  sorted s1 -> sorted s2 -> sorted (merge s1 s2).\nProof.\nmove=> [|x1 s1] [|x2 s2] //= ord_s1 ord_s2.\ncase: ifP => le_x21 /=.\n  by apply: (@path_merge x2 (x1 :: s1)) => //=; rewrite le_x21.\nby apply: path_merge => //=; have:= leT_total x2 x1; rewrite le_x21 /= => ->.\nQed.\n\nLemma perm_merge : forall s1 s2, perm_eql (merge s1 s2) (s1 ++ s2).\nProof.\nmove=> s1 s2; apply/perm_eqlP; rewrite perm_eq_sym.\nelim: s1 s2 => //= x1 s1 IHs1.\nelim=> [|x2 s2 IHs2]; rewrite /= ?cats0 //.\ncase: ifP => _ /=; last by rewrite perm_adds.\nby rewrite (perm_catCA (_ :: _) [::x2]) perm_adds.\nQed.\n\nLemma mem_merge : forall s1 s2, merge s1 s2 =i s1 ++ s2.\nProof. by move=> s1 s2; apply: perm_eq_mem; rewrite perm_merge. Qed.\n\nLemma size_merge : forall s1 s2, size (merge s1 s2) = size (s1 ++ s2).\nProof. by move=> s1 s2; apply: perm_eq_size; rewrite perm_merge. Qed.\n\nLemma uniq_merge : forall s1 s2, uniq (merge s1 s2) = uniq (s1 ++ s2).\nProof. by move=> s1 s2; apply: perm_eq_uniq; rewrite perm_merge. Qed.\n\nFixpoint merge_sort_push (s1 : seq T) (ss : seq (seq T)) {struct ss} :=\n  match ss with\n  | [::] :: ss' | [::] as ss' => s1 :: ss'\n  | s2 :: ss' => merge_sort_push (merge s1 s2) ss'\n  end.\n\nFixpoint merge_sort_pop (s1 : seq T) (ss : seq (seq T)) {struct ss} :=\n  if ss is s2 :: ss' then merge_sort_pop (merge s1 s2) ss' else s1.\n\nFixpoint merge_sort_rec (ss : seq (seq T)) (s : seq T) {struct s} :=\n  if s is [:: x1, x2 & s'] then\n    let s1 := if leT x1 x2 then [:: x1; x2] else [:: x2; x1] in\n    merge_sort_rec (merge_sort_push s1 ss) s'\n  else merge_sort_pop s ss.\n\nDefinition sort := merge_sort_rec [::].\n\nLemma sorted_sort : forall s, sorted (sort s).\nProof.\nrewrite /sort => s; have allss: all sorted [::] by [].\nelim: {s}_.+1 {-2}s [::] allss (ltnSn (size s)) => // n IHn s ss allss.\nhave: sorted s -> sorted (merge_sort_pop s ss).\n  elim: ss allss s => //= s2 ss IHss.\n  by case/andP=> *; exact: IHss (sorted_merge _ _).\ncase: s => [|x1 [|x2 s _]]; try by auto.\nmove/ltnW; move/IHn; apply; rewrite {n IHn s} ifE; set s1 := if_expr _ _ _.\nhave: sorted s1 by exact: (@sorted_merge [::x2] [::x1]).\nelim: ss {x1 x2}s1 allss => /= [|s2 ss IHss] s1; first by rewrite andbT.\ncase/andP=> ord_s2 ord_ss ord_s1.\nby case: {1}s2=> /= [|_ _]; [rewrite ord_s1 | exact: IHss (sorted_merge _ _)].\nQed.\n\nLemma perm_sort : forall s, perm_eql (sort s) s.\nProof.\nrewrite /sort => s; apply/perm_eqlP; pose catss := foldr (@cat T) [::].\nrewrite perm_eq_sym -{1}[s]/(catss [::] ++ s).\nelim: {s}_.+1 {-2}s [::] (ltnSn (size s)) => // n IHn s ss.\nhave: perm_eq (catss ss ++ s) (merge_sort_pop s ss).\n  elim: ss s => //= s2 ss IHss s1; rewrite -{IHss}(perm_eqrP (IHss _)).\n  by rewrite perm_catC catA perm_catC perm_cat2l -perm_merge.\ncase: s => // x1 [//|x2 s _]; move/ltnW; move/IHn=> {n IHn} IHs.\nrewrite -{IHs}(perm_eqrP (IHs _)) ifE; set s1 := if_expr _ _ _.\nrewrite (catA _ [::_;_] s) {s}perm_cat2r.\napply: (@perm_eq_trans _ (catss ss ++ s1)).\n  by rewrite perm_cat2l /s1 -ifE; case ifP; rewrite // (perm_catC [::_]).\nelim: ss {x1 x2}s1 => /= [|s2 ss IHss] s1; first by rewrite cats0.\nrewrite perm_catC; case def_s2: {2}s2=> /= [|y s2']; first by rewrite def_s2.\nby rewrite catA -{IHss}(perm_eqrP (IHss _)) perm_catC perm_cat2l -perm_merge.\nQed.\n\nLemma mem_sort : forall s, sort s =i s.\nProof. by move=> s; apply: perm_eq_mem; rewrite perm_sort. Qed.\n\nLemma size_sort : forall s, size (sort s) = size s.\nProof. by move=> s; apply: perm_eq_size; rewrite perm_sort. Qed.\n\nLemma uniq_sort : forall s, uniq (sort s) = uniq s.\nProof. by move=> s; apply: perm_eq_uniq; rewrite perm_sort. Qed.\n\nLemma perm_sortP : transitive leT -> antisymmetric leT ->\n  forall s1 s2, reflect (sort s1 = sort s2) (perm_eq s1 s2).\nProof.\nmove=> leT_tr leT_asym s1 s2; apply: (iffP idP) => eq12; last first.\n  by rewrite -perm_sort eq12 perm_sort.\napply: eq_sorted; rewrite ?sorted_sort //.\nby rewrite perm_sort (perm_eqlP eq12) -perm_sort.\nQed.\n\nEnd SortSeq.\n\nLemma sorted_ltn_uniq_leq : forall s, sorted ltn s = uniq s && sorted leq s.\nProof.\ncase=> //= n s; elim: s n => //= m s IHs n.\nrewrite inE ltn_neqAle negb_or IHs -!andbA.\ncase sn: (n \\in s); last do !bool_congr.\nrewrite andbF; apply/and5P=> [[ne_nm lenm _ _ le_ms]]; case/negP: ne_nm.\nrewrite eqn_leq lenm; exact: (allP (order_path_min leq_trans le_ms)).\nQed.\n\nLemma sorted_iota : forall i n, sorted leq (iota i n).\nProof. by move=> i n; elim: n i => // [[|n] //= IHn] i; rewrite IHn leqW. Qed.\n\nLemma sorted_ltn_iota : forall i n, sorted ltn (iota i n).\nProof. by move=> i n; rewrite sorted_ltn_uniq_leq sorted_iota uniq_iota. Qed.\n\n(* Function trajectories. *)\n\nNotation \"'fpath' f\" := (path (frel f))\n  (at level 10, f at level 8) : seq_scope.\n\nNotation \"'fcycle' f\" := (cycle (frel f))\n  (at level 10, f at level 8) : seq_scope.\n\nNotation \"'ufcycle' f\" := (ucycle (frel f))\n  (at level 10, f at level 8) : seq_scope.\n\nPrenex Implicits path next prev cycle ucycle mem2.\n\nSection Trajectory.\n\nVariables (T : Type) (f : T -> T).\n\nFixpoint traject x (n : nat) {struct n} :=\n  if n is n'.+1 then x :: traject (f x) n' else seq0.\n\nLemma size_traject : forall x n, size (traject x n) = n.\nProof. by move=> x n; elim: n x => [|n Hrec] x //=; nat_congr. Qed.\n\nLemma last_traject : forall x n, last x (traject (f x) n) = iter n f x.\nProof. by move=> x n; elim: n x => [|n Hrec] x //; rewrite -iter_f -Hrec. Qed.\n\nLemma sub_traject : forall i n, i < n ->\n  forall x, sub x (traject x n) i = iter i f x.\nProof.\nmove=> i n Hi x; elim: n {2 3}x i Hi => [|n Hrec] y [|i] Hi //=.\nby rewrite Hrec ?iter_f.\nQed.\n\nEnd Trajectory.\n\nSection EqTrajectory.\n\nVariables (T : eqType) (f : T -> T).\n\nLemma fpathP : forall x p,\n  reflect (exists n, traject f (f x) n = p) (fpath f x p).\nProof.\nmove=> x p; elim: p x => [|y p Hrec] x; first by left; exists 0.\nrewrite /= andbC; case: {Hrec}(Hrec y) => Hrec.\n  apply: (iffP eqP); first by case: Hrec => [n <-] <-; exists n.+1.\n  by case=> [] [|n] // [Dp].\nby right; move=> [[|n] // [Dy Dp]]; case: Hrec; exists n; rewrite -Dy -Dp.\nQed.\n\nLemma fpath_traject : forall x n, fpath f x (traject f (f x) n).\nProof. by move=> x n; apply/(fpathP x); exists n. Qed.\n\nDefinition looping x n := iter n f x \\in traject f x n.\n\nLemma loopingP : forall x n,\n  reflect (forall m, iter m f x \\in traject f x n) (looping x n).\nProof.\nmove=> x n; apply introP; last by move=> Hn Hn'; rewrite /looping Hn' in Hn.\ncase: n => [|n] Hn //; elim=> [|m Hrec]; first by exact: predU1l.\nmove: (fpath_traject x n) Hn; rewrite /looping -!f_iter -last_traject /=.\nrewrite /= in Hrec; case/splitPl: Hrec; move: (iter m f x) => y p1 p2 Ep1.\nrewrite path_cat last_cat Ep1; case: p2 => [|z p2] //; case/and3P=> [_ Dy _] _.\nby rewrite !(in_adds, mem_cat) (eqP Dy) eqxx !orbT.\nQed.\n\nLemma trajectP : forall x n y,\n  reflect (exists2 i, i < n & iter i f x = y) (y \\in traject f x n).\nProof.\nmove=> x n y; elim: n x => [|n Hrec] x; first by right; case.\n  rewrite /= in_adds orbC; case: {Hrec}(Hrec (f x)) => Hrec.\n  by left; case: Hrec => [i Hi <-]; exists i.+1; last by rewrite iter_f.\napply: (iffP eqP); first by exists 0; first by rewrite ltnNge.\nby move=> [[|i] Hi Dy] //; case Hrec; exists i; last by rewrite iter_f.\nQed.\n\nLemma looping_uniq : forall x n, uniq (traject f x n.+1) = ~~ looping x n.\nProof.\nmove=> x n; rewrite /looping; elim: n x => [|n Hrec] x //.\nrewrite -iter_f {2}[succn]lock /= -lock {}Hrec -negb_or in_adds; bool_congr.\nset y := iter n f (f x); case (trajectP (f x) n y); first by rewrite !orbT.\nrewrite !orbF => Hy; apply/idP/eqP => [Hx|Dy]; last first.\n  by rewrite -{1}Dy /y -last_traject mem_last.\ncase: {Hx}(trajectP _ n.+1 _ Hx) => [m Hm Dx].\nhave Hx': looping x m.+1 by rewrite /looping -iter_f Dx mem_head.\ncase/trajectP: (loopingP _ _ Hx' n.+1); rewrite -iter_f -/y.\nmove=> [|i] Hi //; rewrite -iter_f => Dy.\nby case: Hy; exists i; first exact (leq_trans Hi Hm).\nQed.\n\nEnd EqTrajectory.\n\nImplicit Arguments fpathP [T f x p].\nImplicit Arguments loopingP [T f x n].\nImplicit Arguments trajectP [T f x n y].\nPrenex Implicits traject fpathP loopingP trajectP.\n\nSection UniqCycle.\n\nVariables (n0 : nat) (T : eqType) (e : rel T) (p : seq T).\n\nHypothesis Up : uniq p.\n\nLemma prev_next : cancel (next p) (prev p).\nProof.\nmove=> x; rewrite prev_sub mem_next next_sub.\ncase Hpx: (x \\in p) => [|] //; case Dp: p Up Hpx => [|y p'] //.\nrewrite -(Dp) {1}Dp /=; move/andP=> [Hpy Hp'] Hx.\nset i := index x p; rewrite -(sub_index y Hx) -/i; congr (sub y).\nrewrite -index_mem -/i Dp /= ltnS leq_eqVlt in Hx.\ncase/predU1P: Hx => [Di|Hi]; last by apply: index_uniq.\nrewrite Di (sub_default y (leqnn _)).\nrewrite -index_mem -leqNgt in Hpy.\nby apply: eqP; rewrite eqn_leq Hpy /index find_size.\nQed.\n\nLemma next_prev : cancel (prev p) (next p).\nProof.\nmove=> x; rewrite next_sub mem_prev prev_sub.\ncase Hpx: (x \\in p) => [|] //; case Dp: p Up Hpx => [|y p'] //.\nrewrite -Dp => Hp Hpx; set i := index x p'.\nhave Hi: i < size p by rewrite Dp /= ltnS /i /index find_size.\nrewrite (index_uniq y Hi Hp); case Hx: (x \\in p'); first by apply: sub_index.\nrewrite Dp in_adds Hx orbF in Hpx; rewrite (eqP Hpx).\nby apply: sub_default; rewrite leqNgt /i index_mem Hx.\nQed.\n\nLemma cycle_next : fcycle (next p) p.\nProof.\ncase Dp: {-2}p Up => [|x p'] Up' //; apply/(pathP x)=> i; rewrite size_add_last => Hi.\nrewrite -cats1 -cat_adds sub_cat Hi /= next_sub {}Dp mem_sub //.\nrewrite index_uniq // sub_cat /=; rewrite ltnS leq_eqVlt in Hi.\ncase/predU1P: Hi => [Di|Hi]; last by rewrite Hi eqxx.\nby rewrite Di ltnn subnn sub_default ?leqnn /= ?eqxx.\nQed.\n\nLemma cycle_prev : cycle (fun x y => x == prev p y) p.\nProof.\napply: etrans cycle_next; symmetry; case Dp: p => [|x p'] //.\napply: eq_path; rewrite -Dp; exact (can2_eq prev_next next_prev).\nQed.\n\nLemma cycle_from_next : (forall x, x \\in p -> e x (next p x)) -> cycle e p.\nProof.\nmove=> He; case Dp: p cycle_next => [|x p'] //; rewrite -Dp !(cycle_path x).\nhave Hx: last x p \\in p by rewrite Dp /= mem_last.\nmove: (next p) He {Hx}(He _ Hx) => np.\nelim: (p) {x p' Dp}(last x p) => [|y p' Hrec] x He Hx //=.\ncase/andP=> [Dy Hp']; rewrite -{1}(eqP Dy) Hx /=.\napply: Hrec Hp' => [z Hz|]; apply: He; [exact: predU1r | exact: predU1l].\nQed.\n\nLemma cycle_from_prev : (forall x, x \\in p -> e (prev p x) x) -> cycle e p.\nProof.\nmove=> He; apply: cycle_from_next => [x Hx].\nby rewrite -{1}[x]prev_next He ?mem_next.\nQed.\n\nLemma next_rot : next (rot n0 p) =1 next p.\nProof.\nmove=> x; have Hp := cycle_next; rewrite -(cycle_rot n0) in Hp.\ncase Hx: (x \\in p); last by rewrite !next_sub mem_rot Hx.\nrewrite -(mem_rot n0) in Hx; exact (esym (eqP (next_cycle Hp Hx))).\nQed.\n\nLemma prev_rot : prev (rot n0 p) =1 prev p.\nProof.\nmove=> x; have Hp := cycle_prev; rewrite -(cycle_rot n0) in Hp.\ncase Hx: (x \\in p); last by rewrite !prev_sub mem_rot Hx.\nrewrite -(mem_rot n0) in Hx; exact (eqP (prev_cycle Hp Hx)).\nQed.\n\nEnd UniqCycle.\n\nSection UniqRotrCycle.\n\nVariables (n0 : nat) (T : eqType) (p : seq T).\n\nHypothesis Up : uniq p.\n\nLemma next_rotr : next (rotr n0 p) =1 next p. Proof. exact: next_rot. Qed.\n\nLemma prev_rotr : prev (rotr n0 p) =1 prev p. Proof. exact: prev_rot. Qed.\n\nEnd UniqRotrCycle.\n\nSection UniqCycleRev.\n\nVariable T : eqType.\n\nLemma prev_rev : forall p : seq T, uniq p -> prev (rev p) =1 next p.\nProof.\nmove=> p Up x; case Hx: (x \\in p); last first.\n  by rewrite next_sub prev_sub mem_rev Hx.\ncase/rot_to: Hx (Up) => [i p' Dp] Urp; rewrite -uniq_rev in Urp.\nrewrite -(prev_rotr i Urp); do 2 rewrite -(prev_rotr 1) ?uniq_rotr //.\nrewrite -rev_rot -(next_rot i Up) {i p Up Urp}Dp.\ncase: p' => [|y p'] //; rewrite !rev_adds rotr1_add_last /= eqxx.\nby rewrite -add_last_adds rotr1_add_last /= eqxx.\nQed.\n\nLemma next_rev : forall p : seq T, uniq p -> next (rev p) =1 prev p.\nProof. by move=> p Up x; rewrite -{2}[p]revK prev_rev // uniq_rev. Qed.\n\nEnd UniqCycleRev.\n\nSection MapPath.\n\nVariables (T T' : Type) (h : T' -> T) (e : rel T) (e' : rel T').\n\nDefinition rel_base (b : pred T) :=\n  forall x' y', ~~ b (h x') -> e (h x') (h y') = e' x' y'.\n\nLemma path_maps : forall b x' p', rel_base b ->\n    ~~ has (preim h b) (belast x' p') ->\n  path e (h x') (maps h p') = path e' x' p'.\nProof.\nmove=> b x' p' Hb; elim: p' x' => [|y' p' Hrec] x' //=; move/norP=> [Hbx Hbp].\ncongr andb; auto.\nQed.\n\nEnd MapPath.\n\nSection MapEqPath.\n\nVariables (T T' : eqType) (h : T' -> T) (e : rel T) (e' : rel T').\n\nHypothesis Hh : injective h.\n\nLemma mem2_maps : forall x' y' p',\n  mem2 (maps h p') (h x') (h y') = mem2 p' x' y'.\nProof. by move=> *; rewrite {1}/mem2 (index_maps Hh) -maps_drop mem_maps. Qed.\n\nLemma next_maps : forall p, uniq p ->\n  forall x, next (maps h p) (h x) = h (next p x).\nProof.\nmove=> p Up x; case Hx: (x \\in p); last by rewrite !next_sub (mem_maps Hh) Hx.\ncase/rot_to: Hx => [i p' Dp].\nrewrite -(next_rot i Up); rewrite -(uniq_maps Hh) in Up.\nrewrite -(next_rot i Up) -maps_rot {i p Up}Dp /=.\nby case: p' => [|y p] //=; rewrite !eqxx.\nQed.\n\nLemma prev_maps : forall p, uniq p ->\n  forall x, prev (maps h p) (h x) = h (prev p x).\nProof.\nby move=> p Up x; rewrite -{1}[x](next_prev Up) -(next_maps Up) prev_next ?uniq_maps.\nQed.\n\nEnd MapEqPath.\n\nDefinition fun_base (T T' : eqType) (h : T' -> T) f f' :=\n  rel_base h (frel f) (frel f').\n\nSection CycleArc.\n\nVariable T : eqType.\n\nDefinition arc (p : seq T) x y :=\n  let px := rot (index x p) p in take (index y px) px.\n\nLemma arc_rot : forall i p, uniq p -> {in p, arc (rot i p) =2 arc p}.\nProof.\nmove=> i p Up x Hx y; congr (fun q => take (index y q) q); move: Up Hx {y}.\nrewrite -{1 2 5 6}(cat_take_drop i p) /rot uniq_cat; move/and3P=> [_ Hp _].\nrewrite !drop_cat !take_cat !index_cat mem_cat orbC.\ncase Hx: (x \\in drop i p) => /= => [_|Hx'].\n  rewrite [x \\in _](negbET (hasPn Hp _ Hx)).\n  by rewrite index_mem Hx ltnNge leq_addr /= addKn catA.\nby rewrite Hx' index_mem Hx' ltnNge leq_addr /= addKn catA.\nQed.\n\nLemma left_arc : forall x y p1 p2,\n  let p := x :: p1 ++ y :: p2 in uniq p -> arc p x y = x :: p1.\nProof.\nmove=> x y p1 p2 p Up; rewrite /arc {1}/p /= eqxx rot0.\nmove: Up; rewrite /p -cat_adds uniq_cat index_cat; move: (x :: p1) => xp1.\nrewrite /= negb_or -!andbA; move/and3P=> [_ Hy _].\nby rewrite (negbET Hy) eqxx addn0 take_size_cat.\nQed.\n\nLemma right_arc : forall x y p1 p2,\n  let p := x :: p1 ++ y :: p2 in uniq p -> arc p y x = y :: p2.\nProof.\nmove=> x y p1 p2 p Up; set n := size (x :: p1); rewrite -(arc_rot n Up).\n  move: Up; rewrite -(uniq_rot n) /p -cat_adds /n rot_size_cat.\n  by move=> *; rewrite /= left_arc.\nby rewrite /p -cat_adds mem_cat /= mem_head orbT.\nQed.\n\nCoInductive rot_to_arc_spec (p : seq T) (x y : T) : Type :=\n    RotToArcSpec i p1 p2 of x :: p1 = arc p x y\n                          & y :: p2 = arc p y x\n                          & rot i p = x :: p1 ++ y :: p2 :\n    rot_to_arc_spec p x y.\n\nLemma rot_to_arc : forall p x y,\n  uniq p -> x \\in p -> y \\in p -> x != y -> rot_to_arc_spec p x y.\nProof.\nmove=> p x y Up Hx Hy Hxy; case: (rot_to Hx) (Hy) (Up) => [i p' Dp] Hy'.\nrewrite -(mem_rot i) Dp in_adds eq_sym (negPf Hxy) in Hy'.\nrewrite -(uniq_rot i) Dp.\ncase/splitPr: p' / Hy' Dp => [p1 p2] Dp Up'; exists i p1 p2; auto.\n  by rewrite -(arc_rot i Up Hx) Dp (left_arc Up').\nby rewrite -(arc_rot i Up Hy) Dp (right_arc Up').\nQed.\n\nEnd CycleArc.\n\nPrenex Implicits arc.\n\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/ssreflect/attic/ssreflect_82beta/theories/paths.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6846591614563097}}
{"text": "(**************************************************************************)\n(**  Mechanised Framework for Local Interactions & Distributed Algorithms   \n                                                                            \n     P. Courtieu, L. Rieg, X. Urbain                                        \n                                                                            \n     PACTOLE project                                                        \n                                                                            \n     This file is distributed under the terms of the CeCILL-C licence       \n                                                                          *)\n(**************************************************************************)\n\n\nRequire Import SetoidDec SetoidList.\nRequire Import Arith_base.\nRequire Import Lia.\nRequire Import Pactole.Util.Coqlib.\n\n\nSet Implicit Arguments.\nTypeclasses eauto := (bfs).\n\n\n(* TODO: should we add a fold operator? *)\n(* FIXME: change the equalities to use equiv and the Setoid class *)\n\n(** Finite sets as a prefix of natural numbers. *)\nNotation \"'fin' N\" := {n : nat | n < N} (at level 10).\n\nLemma subset_dec : forall N (x y : fin N), {x = y} + {x <> y}.\nProof using .\nintros N [x Hx] [y Hy]. destruct (Nat.eq_dec x y).\n+ subst. left. f_equal. apply le_unique.\n+ right. intro Habs. inv Habs. auto.\nQed.\n\nLemma eq_proj1 : forall N (x y : fin N), proj1_sig x = proj1_sig y -> x = y.\nProof using . intros N [x Hx] [y Hy] ?. simpl in *. subst. f_equal. apply le_unique. Qed.\n\nProgram Fixpoint build_enum N k (Hle : k <= N) acc : list (fin N) :=\n  match k with\n    | 0 => acc\n    | S m => @build_enum N m _ (exist (fun x => x < N) m _ :: acc)\n  end.\nNext Obligation.\nlia.\nQed.\n\n(** A list containing all elements of [fin N]. *)\nDefinition enum N : list (fin N) := build_enum (Nat.le_refl N) nil.\n\n(** Specification of [enum]. *)\nLemma In_build_enum : forall N k (Hle : k <= N) l x, In x (build_enum Hle l) <-> In x l \\/ proj1_sig x < k.\nProof using .\nintros N k. induction k; intros Hle l x; simpl.\n+ intuition.\n+ rewrite IHk. simpl. split; intro Hin.\n  - destruct Hin as [[Hin | Hin] | Hin]; intuition; [].\n    subst. simpl. right. lia.\n  - destruct Hin as [Hin | Hin]; intuition; [].\n    assert (Hcase : proj1_sig x < k \\/ proj1_sig x = k) by lia.\n    destruct Hcase as [Hcase | Hcase]; intuition; [].\n    subst. do 2 left. destruct x; f_equal; simpl in *. apply le_unique.\nQed.\n\nLemma In_enum : forall N x, In x (enum N) <-> proj1_sig x < N.\nProof using . intros. unfold enum. rewrite In_build_enum. simpl. intuition. Qed.\n\n(** Length of [enum]. *)\nLemma build_enum_length : forall N k (Hle : k <= N) l, length (build_enum Hle l) = k + length l.\nProof using .\nintros N k. induction k; intros Hle l; simpl.\n+ reflexivity.\n+ rewrite IHk. simpl. lia.\nQed.\n\nLemma enum_length : forall N, length (enum N) = N.\nProof using . intro. unfold enum. now rewrite build_enum_length. Qed.\n\n(** [enum] does not contain duplicates. *)\nLemma build_enum_NoDup : forall N k (Hle : k <= N) l,\n  (forall x, In x l -> k <= proj1_sig x) -> NoDup l -> NoDup (build_enum Hle l).\nProof using .\nintros N k. induction k; intros Hle l Hin Hl; simpl; auto; [].\napply IHk.\n+ intros x [Hx | Hx].\n  - now subst.\n  - apply Hin in Hx. lia.\n+ constructor; trivial; [].\n  intro Habs. apply Hin in Habs. simpl in Habs. lia.\nQed.\n\nLemma enum_NoDup : forall N, NoDup (enum N).\nProof using . intro. unfold enum. apply build_enum_NoDup; simpl; intuition; constructor. Qed.\n\n(** [enum] is sorted in increasing order. *)\nNotation Flt := (fun x y => lt (proj1_sig x) (proj1_sig y)).\n\nLemma build_enum_Sorted : forall N k (Hle : k <= N) l,\n  (forall x, In x l -> k <= proj1_sig x) -> Sorted Flt l -> Sorted Flt (build_enum Hle l).\nProof using .\nintros N k. induction k; intros Hle l Hin Hl; simpl; auto; [].\napply IHk.\n+ intros x [Hx | Hx].\n  - now subst.\n  - apply Hin in Hx. lia.\n+ constructor; trivial; [].\n  destruct l; constructor; []. simpl. apply Hin. now left.\nQed.\n\nLemma enum_Sorted : forall N, Sorted Flt (enum N).\nProof using . intro. unfold enum. apply build_enum_Sorted; simpl; intuition. Qed.\n\n(** Extensional equality of functions is decidable over finite domains. *)\nLemma build_enum_app_nil : forall N k (Hle : k <= N) l,\n  build_enum Hle l = build_enum Hle nil ++ l.\nProof using .\nintros N k. induction k; intros Hle l; simpl.\n+ reflexivity.\n+ now rewrite (IHk _ (_ :: nil)), IHk, <- app_assoc.\nQed.\n\nTheorem build_enum_eq : forall {A} eqA N (f g : fin N -> A) k (Hle : k <= N) l,\n  eqlistA eqA (List.map f (build_enum Hle l)) (List.map g (build_enum Hle l)) ->\n  forall x, proj1_sig x < k -> eqA (f x) (g x).\nProof using .\nintros A eqA N f g k. induction k; intros Hle l Heq x Hx; simpl.\n* destruct x; simpl in *; lia.\n* assert (Hlt : k <= N) by lia.\n  assert (Hcase : proj1_sig x < k \\/ proj1_sig x = k) by lia.\n  destruct Hcase as [Hcase | Hcase].\n  + apply IHk with (x := x) in Heq; auto.\n  + subst k. simpl in Heq. rewrite build_enum_app_nil, map_app, map_app in Heq.\n    destruct (eqlistA_app_split _ _ _ _ Heq) as [_ Heq'].\n    - now do 2 rewrite map_length, build_enum_length.\n    - simpl in Heq'. inv Heq'.\n      assert (Heqx : x = exist (fun x => x < N) (proj1_sig x) Hle).\n      { clear. destruct x; simpl. f_equal. apply le_unique. }\n      now rewrite Heqx.\nQed.\n\nCorollary enum_eq : forall {A} eqA N (f g : fin N -> A),\n  eqlistA eqA (List.map f (enum N)) (List.map g (enum N)) -> forall x, eqA (f x) (g x).\nProof using .\nunfold enum. intros A eqA N f g Heq x.\napply build_enum_eq with (x := x) in Heq; auto; []. apply proj2_sig.\nQed.\n\n(** Cutting [enum] after some number of elements. *)\nLemma firstn_build_enum_le : forall N k (Hle : k <= N) l k' (Hk : k' <= N), k' <= k ->\n  firstn k' (build_enum Hle l) = @build_enum N k' Hk nil.\nProof using .\nintros N k. induction k; intros Hk l k' Hk' Hle.\n* assert (k' = 0) by lia. now subst.\n* rewrite build_enum_app_nil, firstn_app, build_enum_length.\n  replace (k' - (S k + length (@nil (fin N)))) with 0 by lia.\n  rewrite app_nil_r.\n  destruct (Nat.eq_dec k' (S k)) as [Heq | Heq].\n  + subst k'. rewrite firstn_all2.\n    - f_equal. apply le_unique.\n    - rewrite build_enum_length. simpl. lia.\n  + simpl build_enum. erewrite IHk.\n    - f_equal.\n    - lia.\nQed.\n\nLemma firstn_build_enum_lt : forall N k (Hle : k <= N) l k', k <= k' ->\n  firstn k' (build_enum Hle l) = build_enum Hle (firstn (k' - k) l).\nProof using .\nintros N k. induction k; intros Hle l k' Hk.\n+ now rewrite Nat.sub_0_r.\n+ rewrite build_enum_app_nil, firstn_app, build_enum_length, Nat.add_0_r.\n  rewrite firstn_all2, <- build_enum_app_nil; trivial; [].\n  rewrite build_enum_length. simpl. lia.\nQed.\n\nLemma firstn_enum_le : forall N k (Hle : k <= N), firstn k (enum N) = build_enum Hle nil.\nProof using . intros. unfold enum. now apply firstn_build_enum_le. Qed.\n\nLemma firstn_enum_lt : forall N k, N <= k -> firstn k (enum N) = enum N.\nProof using . intros. unfold enum. now rewrite firstn_build_enum_lt, firstn_nil. Qed.\n\nLemma firstn_enum_spec : forall N k x, In x (firstn k (enum N)) <-> proj1_sig x < k.\nProof using .\nintros N k x. destruct (le_lt_dec k N) as [Hle | Hlt].\n+ rewrite (firstn_enum_le Hle), In_build_enum. simpl. intuition.\n+ rewrite (firstn_enum_lt (lt_le_weak _ _ Hlt)).\n  split; intro Hin.\n  - transitivity N; trivial; []. apply proj2_sig.\n  - apply In_enum, proj2_sig.\nQed.\n\n(** Removing some number of elements from the head of [enum]. *)\nLemma skipn_build_enum_lt : forall N k (Hle : k <= N) l k', k <= k' ->\n  skipn k' (build_enum Hle l) = skipn (k' - k) l.\nProof using .\nintros N k Hle l k' Hk'. apply app_inv_head with (firstn k' (build_enum Hle l)).\nrewrite firstn_skipn, firstn_build_enum_lt; trivial; [].\nrewrite (build_enum_app_nil Hle (firstn _ _)).\nnow rewrite build_enum_app_nil, <- app_assoc, firstn_skipn.\nQed.\n\nLemma skipn_enum_lt : forall N k, N <= k -> skipn k (enum N) = nil.\nProof using . intros. unfold enum. now rewrite skipn_build_enum_lt, skipn_nil. Qed.\n\nLemma skipn_enum_spec : forall N k x, In x (skipn k (enum N)) <-> k <= proj1_sig x < N.\nProof using .\nintros N k x. split; intro Hin.\n+ assert (Hin' : ~In x (firstn k (enum N))).\n  { intro Habs. rewrite <- InA_Leibniz in *. revert x Habs Hin. apply NoDupA_app_iff; autoclass; [].\n    rewrite firstn_skipn. rewrite NoDupA_Leibniz. apply enum_NoDup. }\n  rewrite firstn_enum_spec in Hin'. split; auto with zarith; []. apply proj2_sig.\n+ assert (Hin' : In x (enum N)) by apply In_enum, proj2_sig.\n  rewrite <- (firstn_skipn k), in_app_iff, firstn_enum_spec in Hin'. intuition lia.\nQed.\n\n(** ** Byzantine Robots *)\n\n(** We have finitely many robots. Some are good, others are Byzantine.\n    Both are represented by an abtract type that can be enumerated. *)\nClass Names := {\n  (** Number of good and Byzantine robots *)\n  nG : nat;\n  nB : nat;\n  (** Types representing good and Byzantine robots *)\n  G : Type;\n  B : Type;\n  (** Enumerations of robots *)\n  Gnames : list G;\n  Bnames : list B;\n  (** The enumerations are complete and without duplicates *)\n  In_Gnames : forall g : G, In g Gnames;\n  In_Bnames : forall b : B, In b Bnames;\n  Gnames_NoDup : NoDup Gnames;\n  Bnames_NoDup : NoDup Bnames;\n  (** There is the right amount of robots *)\n  Gnames_length : length Gnames = nG;\n  Bnames_length : length Bnames = nB;\n  (** We can tell robots apart *)\n  Geq_dec : forall g g' : G, {g = g'} + {g <> g'};\n  Beq_dec : forall b b' : B, {b = b'} + {b <> b'};\n  (** Being a finite type, extensional function equality is decidable *)\n  fun_Gnames_eq : forall {A : Type} eqA f g,\n    @eqlistA A eqA (List.map f Gnames) (List.map g Gnames) -> forall x, eqA (f x) (g x);\n  fun_Bnames_eq : forall {A : Type} eqA f g,\n    @eqlistA A eqA (List.map f Bnames) (List.map g Bnames) -> forall x, eqA (f x) (g x)}.\n\nGlobal Opaque In_Gnames In_Bnames Gnames_NoDup Bnames_NoDup\n              Gnames_length Bnames_length Geq_dec Beq_dec fun_Gnames_eq fun_Bnames_eq.\n\n(** Identifiers make good and Byzantine robots undistinguishable.\n    They have their own enumeration without duplicates,\n    and both equality and extensional function equality are decidable. *)\nInductive ident `{Names} : Type :=\n  | Good (g : G)\n  | Byz (b : B).\n\nDefinition names `{Names} : list ident := List.map Good Gnames ++ List.map Byz Bnames.\n\nLemma In_names `{Names} : forall r : ident, In r names.\nProof using .\nintro r. cbn. unfold names. rewrite in_app_iff. destruct r as [g | b].\n- left. apply in_map, In_Gnames.\n- right. apply in_map, In_Bnames.\nQed.\n\nLemma names_NoDup `{Names} : NoDup names.\nProof using .\nunfold names. rewrite <- NoDupA_Leibniz. apply (NoDupA_app _).\n+ apply (map_injective_NoDupA _ _).\n  - now repeat intro; hnf in *; subst.\n  - intros ? ? Heq. now inversion Heq.\n  - rewrite NoDupA_Leibniz. apply Gnames_NoDup.\n+ apply (map_injective_NoDupA _ _).\n  - now repeat intro; hnf in *; subst.\n  - intros ? ? Heq. now inversion Heq.\n  - rewrite NoDupA_Leibniz. apply Bnames_NoDup.\n+ intros id HinA HinB. rewrite (InA_map_iff _ _) in HinA. rewrite (InA_map_iff _ _) in HinB.\n  - destruct HinA as [? [? ?]], HinB as [? [? ?]]. subst. discriminate.\n  - now repeat intro; hnf in *; subst.\n  - now repeat intro; hnf in *; subst.\nQed.\n\nLemma names_length `{Names} : length names = nG + nB.\nProof using . unfold names. now rewrite app_length, map_length, map_length, Gnames_length, Bnames_length. Qed.\n\nLemma names_eq_dec `{Names} : forall id id' : ident, {id = id'} + { id <> id'}.\nProof using .\nintros id id'.\ndestruct id as [g | b], id' as [g' | b']; try (now right; discriminate); [|].\n+ destruct (Geq_dec g g').\n  - left; subst; auto.\n  - right; intro Habs. now injection Habs.\n+ destruct (Beq_dec b b').\n  - left; subst; auto.\n  - right; intro Habs. now injection Habs.\nQed.\n\nInstance ident_Setoid `{Names} : Setoid ident := { equiv := eq; setoid_equiv := eq_equivalence }.\nInstance ident_EqDec `{Names} : EqDec ident_Setoid := names_eq_dec.\n\nInstance fun_refl `{Names} : forall A (f : ident -> A) R,\n  Reflexive R -> Proper (@SetoidClass.equiv ident _ ==> R) f.\nProof using . intros A f R HR ? ? Heq. simpl in Heq. now subst. Qed.\n\nInstance list_ident_Setoid `{Names} : Setoid (list ident) := { equiv := eq; setoid_equiv := eq_equivalence }.\nInstance list_ident_Eqdec `{Names} : EqDec list_ident_Setoid := list_eq_dec ident_EqDec.\n\nLemma fun_names_eq `{Names} : forall {A : Type} eqA f g,\n  @eqlistA A eqA (List.map f names) (List.map g names) -> forall x, eqA (f x) (g x).\nProof using .\nintros A eqA f h Heq id.\nunfold names in Heq. repeat rewrite ?map_app, map_map in Heq. apply eqlistA_app_split in Heq.\n+ destruct id as [g | b].\n  - change (eqA ((fun x => f (Good x)) g) ((fun x => h (Good x)) g)). apply fun_Gnames_eq, Heq.\n  - change (eqA ((fun x => f (Byz x)) b) ((fun x => h (Byz x)) b)). apply fun_Bnames_eq, Heq.\n+ now do 2 rewrite map_length.\nQed.\n\n(** Given a number of good and byzntine robots, we can build canonical names.\n    It is not declared as a global instance to avoid creating spurious settings. *)\nDefinition Robots (n m : nat) : Names.\nProof.\nrefine {|\n  nG := n;\n  nB := m;\n  G := fin n;\n  B := fin m;\n  Gnames := enum n;\n  Bnames := enum m |}.\n+ abstract (intro g; apply In_enum, proj2_sig).\n+ abstract (intro b; apply In_enum, proj2_sig).\n+ apply enum_NoDup.\n+ apply enum_NoDup.\n+ apply enum_length.\n+ apply enum_length.\n+ apply subset_dec.\n+ apply subset_dec.\n+ intros ? ?. apply enum_eq.\n+ intros ? ?. apply enum_eq.\nDefined.\n\nGlobal Opaque G B.\n", "meta": {"author": "MathisBD", "repo": "pactole_stage", "sha": "4b63da0898ae4f48956408dc31f7831d3ad8930f", "save_path": "github-repos/coq/MathisBD-pactole_stage", "path": "github-repos/coq/MathisBD-pactole_stage/pactole_stage-4b63da0898ae4f48956408dc31f7831d3ad8930f/Core/Identifiers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.6846591606130907}}
{"text": "(** CS6225 -- Problem Set 3a (100 points) *)\n\n(** * 6.822 Formal Reasoning About Programs, Spring 2018 - Pset 1 *)\n\nRequire Import Frap.\n\n(* Authors:\n * Peng Wang (wangpeng@csail.mit.edu),\n * Adam Chlipala (adamc@csail.mit.edu),\n * Joonwon Choi (joonwonc@csail.mit.edu),\n * Benjamin Sherman (sherman@csail.mit.edu)\n *)\n\n(* In 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\nInductive Prog :=\n  | Done                             (* Don't modify the state. *)\n  | AddThen (n : nat) (p : Prog)     (* Add [n] to the state, then run [p]. *)\n  | MulThen (n : nat) (p : Prog)     (* Multiply the state by [n], then run [p]. *)\n  | SetToThen (n : nat) (p : Prog)   (* Set the state to [n], then run [p]. *)\n  .\n\n(* Your job is to define a module implementing the following\n * signature.  We ask you to implement a file Pset3a.v, where the skeleton is\n * already given, such that it can be checked against this signature by\n * successfully processing a third file (Pset3aCheck.v) with a command like so:\n * <<\n    Require Pset3aSig Pset3a.\n\n    Module M : Pset3aSig.S := Pset3a.\n   >>\n * You'll need to build your module first, which the default target of our\n * handy Makefile does for you automatically. Just issue [make] in this\n * directory.\n *\n * Note that the _CoqProject file included here is also important for making\n * compilation and interactive editing work.  Your Pset3a.v file is what you\n * upload to the course web site to get credit for doing the assignment.\n *)\n\n(* Finally, here's the actual signature to implement. *)\nModule Type S.\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  Parameter run : Prog -> nat -> nat.\n  (* 10 points *)\n\n  Axiom run_Example1 : run Done 0 = 0.\n  Axiom run_Example2 : run (MulThen 5 (AddThen 2 Done)) 1 = 7.\n  Axiom run_Example3 : run (SetToThen 3 (MulThen 2 Done)) 10 = 6.\n  (* 10 points *)\n\n  (* Define [numInstructions] to compute the number of instructions\n   * in a program, not counting [Done] as an instruction.\n   *)\n  Parameter numInstructions : Prog -> nat.\n  (* 10 points *)\n\n  Axiom numInstructions_Example :\n    numInstructions (MulThen 5 (AddThen 2 Done)) = 2.\n  (* 10 points *)\n\n  (* Define [concatProg] such that [concatProg p1 p2] is the program\n   * that first runs [p1] and then runs [p2].\n   *)\n  Parameter concatProg : Prog -> Prog -> Prog.\n  (* 10 points *)\n\n  Axiom concatProg_Example :\n     concatProg (AddThen 1 Done) (MulThen 2 Done)\n   = AddThen 1 (MulThen 2 Done).\n  (* 10 points *)\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  Axiom concatProg_numInstructions : forall p1 p2,\n      numInstructions (concatProg p1 p2)\n      = numInstructions p1 + numInstructions p2.\n  (* 20 points *)\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  Axiom concatProg_run : forall p1 p2 initState,\n      run (concatProg p1 p2) initState =\n      run p2 (run p1 initState).\n  (* 20 points *)\nEnd S.\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/pset3a/Pset3aSig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.6845784187632589}}
{"text": "From Nominal Require Export Prelude.\n\n(** *Group operations *)\nClass Neutral A := neutral : A.\n#[global] Hint Mode Neutral ! : typeclass_instances.\nNotation ɛ := neutral.\nNotation \"ɛ@{ A }\" := (@neutral A _) (only parsing) : nominal_scope.\n\nClass Operator A := op: A → A → A.\n#[global] Hint Mode Operator ! : typeclass_instances.\nInstance: Params (@op) 2 := {}.\n\nInfix \"+\" := op : nominal_scope.\nNotation \"(+)\" := op (only parsing) : nominal_scope.\nNotation \"(+ x )\" := (op x) (only parsing) : nominal_scope.\nNotation \"( x +)\" := (λ y, op y x) (only parsing) : nominal_scope.\n\nClass Inverse A := inv : A → A.\n#[global] Hint Mode Inverse ! : typeclass_instances.\nInstance: Params (@inv) 1 := {}.\n\nNotation \"- x\" := (inv x) : nominal_scope.\nNotation \"(-)\" := inv (only parsing) : nominal_scope.\nNotation \"x - y\" := (x + (-y))%nom : nominal_scope.\n\nClass Group (A : Type) `{Ntr: Neutral A, Opr: Operator A, Inv: Inverse A, Equiv A} : Prop := {\n  grp_setoid :> Equivalence(≡@{A});\n  grp_op_proper :> Proper ((≡@{A}) ⟹ (≡@{A}) ⟹ (≡@{A})) (+);\n  grp_inv_proper :> Proper ((≡@{A}) ⟹ (≡@{A})) (-);\n\n  grp_assoc : ∀ (x y z : A), x + (y + z) ≡@{A} (x + y) + z;\n\n  grp_left_id : ∀ (x : A), ɛ@{A} + x ≡@{A} x;\n  grp_right_id : ∀ (x : A), x + ɛ@{A} ≡@{A} x;\n\n  grp_left_inv : ∀ (x : A), (-x) + x ≡@{A} ɛ@{A};\n  grp_right_inv : ∀ (x : A), x - x ≡@{A} ɛ@{A};\n}.\n(* #[global] Hint Mode Group ! - - - -: typeclass_instances. *)\n\nArguments grp_assoc {_ _ _ _ _ Grp} : rename.\nArguments grp_left_id {_ _ _ _ _ Grp} : rename.\nArguments grp_right_id {_ _ _ _ _ Grp} : rename.\nArguments grp_left_inv {_ _ _ _ _ Grp} : rename.\nArguments grp_right_inv {_ _ _ _ _ Grp} : rename.\nArguments grp_op_proper {_ _ _ _ _ Grp} : rename.\nArguments grp_inv_proper {_ _ _ _ _ Grp} : rename.\n\n(* Basic group properties *)\nSection GroupProperties.\n  Context `{Group G}.\n\n  Lemma grp_inv_involutive (x: G): -(-x) ≡ x.\n  Proof with auto.\n    rewrite <-(grp_left_id x) at 2;\n     rewrite <-grp_left_inv, <-grp_assoc, grp_left_inv, grp_right_id...\n  Qed.\n\n  Corollary grp_inv_neutral: -ɛ ≡@{G} ɛ.\n  Proof with auto.\n    rewrite <-grp_left_inv at 1; rewrite grp_right_id, grp_inv_involutive...\n  Qed.\n\n  Corollary grp_inv_inj (x y: G): x ≡ y → (-x) ≡ (-y).\n  Proof. apply grp_inv_proper. Qed.\n\n  Lemma perm_op_inv (x y : G) : -x - y ≡ -(y + x).\n  Proof. Admitted.\nEnd GroupProperties.\n\n(* Group Action  *)\n(* Class Action `{Grp: Group A} A X := action: A -> X -> X. *)\nClass Action A X := action: A → X → X.\n#[global] Hint Mode Action ! ! : typeclass_instances.\n(* CAUSA PROBLEMAS COM REESCRITA ENVOLVENDO action (- p)\n  Instance: Params (@action) 2 := {}. *)\n\nInfix \"•\" := action (at level 60, right associativity) : nominal_scope.\nNotation \"(•)\" := action (only parsing) : nominal_scope.\nNotation \"(• x )\" := (action x) (only parsing) : nominal_scope.\nNotation \"( x •)\" := (λ y, action y x) (only parsing): nominal_scope.\n\n(* GroupAction não é uma ação, por isso preferimos a implementação abaixo. *)\n(* Section GroupAction.\n  Context (A X: Type) `{Grp: Group A, Act : Action A X, Equiv X}.\n\n  Class GAction : Prop := {\n    gact_group : Group A;\n    gact_setoid :> Equivalence(≡@{X});\n    gact_proper :> Proper ((≡@{A}) ==> (≡@{X}) ==> (≡@{X})) (•);\n\n    gact_id : ∀ (x: X), ɛ@{A} • x ≡@{X} x;\n    gact_compat: ∀ (p q: A) (x: X), p • (q • x) ≡@{X} (q + p) • x\n  }.\nEnd GroupAction. *)\n\nClass GAction `(Group G) (X : Type) `{Act : Action G X, Equiv X} : Prop := {\n  gact_setoid :> Equivalence(≡@{X});\n  gact_proper :> Proper ((≡@{G}) ⟹ (≡@{X}) ⟹ (≡@{X})) (•);\n\n  gact_id : ∀ (x: X), ɛ@{G} • x ≡@{X} x;\n  gact_compat: ∀ (p q: G) (x: X), p • (q • x) ≡@{X} (q + p) • x\n}.\n\nExisting Instance gact_proper.\n\nArguments gact_id {_ _ _ _ _ Grp _ _ _ GAct} : rename.\nArguments gact_compat {_ _ _ _ _ Grp _ _ _ GAct} : rename.\nArguments gact_proper {_ _ _ _ _ Grp _ _ _ GAct} : rename.\n\nSection GroupActionProperties.\n  Context `{GAction G X}.\n\n  Corollary perm_left_inv (x: X) (p : G): (-p) • p • x ≡ x.\n  Proof. rewrite gact_compat, grp_right_inv, gact_id; auto. Qed.\n\n  Corollary perm_rigth_inv (x: X) (p : G): p • (-p) • x ≡ x.\n  Proof. rewrite gact_compat, grp_left_inv, gact_id; auto. Qed.\n\n  Lemma perm_iff (x y: X) (p : G): p • x ≡ y ↔ x ≡ (-p) • y.\n  Proof. split; intros A; \n    [rewrite <-A, perm_left_inv | rewrite A, perm_rigth_inv]; auto.\n  Qed.\n\n  Lemma perm_inj (x y: X) (p : G): p • x ≡ p • y ↔ x ≡ y.\n  Proof. split; intros A; \n    [apply perm_iff in A; rewrite <-(perm_left_inv y p) | rewrite A]; auto.\n  Qed.\n\n  Lemma perm_inv_empty_act (x : X) : -ɛ@{G} • x ≡ x.\n  Proof. rewrite grp_inv_neutral; apply gact_id. Qed.\nEnd GroupActionProperties.", "meta": {"author": "fasapa", "repo": "nominal-choudhury", "sha": "922554726dc5ed3657f7916dc21a63c6bcc92817", "save_path": "github-repos/coq/fasapa-nominal-choudhury", "path": "github-repos/coq/fasapa-nominal-choudhury/nominal-choudhury-922554726dc5ed3657f7916dc21a63c6bcc92817/theories/Group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.6845783941254161}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Functor.Functor Functor.Const_Func.\nRequire Import NatTrans.NatTrans NatTrans.Func_Cat.\n\n(** The functor that maps each object c in C to the constant functor that maps each object of D to c in Func_Cat D C. *)\nSection Const_Func_Functor.\n  Context (C D : Category).\n\n  Program Definition Const_Func_Functor : (C –≻ (Func_Cat D C))%functor :=\n    {|\n      FO := fun c => Const_Func D c;\n      FA := fun _ _ h => {|Trans := fun c => h|}\n    |}.\n\nEnd Const_Func_Functor.", "meta": {"author": "amintimany", "repo": "Categories-HoTT", "sha": "fd6018c7abd496b44fd31b1119f6b31795c251d8", "save_path": "github-repos/coq/amintimany-Categories-HoTT", "path": "github-repos/coq/amintimany-Categories-HoTT/Categories-HoTT-fd6018c7abd496b44fd31b1119f6b31795c251d8/Functor/Const_Func_Functor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6845373326424332}}
{"text": "(*\nVerificación Formal - 2020-II\nArchivo de definiciones - Lógica Clásica \n\nDefiniciones de lógica clásica. \n\nSe define el operador binario cotenable, además de la definición de la notación para el operador\n*)\nDefinition cotenable (A B : Prop) := ~ (A -> ~ B).\nNotation \" A ° B \" := ( cotenable A B ) (at level 50, no associativity).\n", "meta": {"author": "cigarcial", "repo": "VF2020II", "sha": "3a283400575564770e47f54e7f7cc66f996da0f1", "save_path": "github-repos/coq/cigarcial-VF2020II", "path": "github-repos/coq/cigarcial-VF2020II/VF2020II-3a283400575564770e47f54e7f7cc66f996da0f1/Tarea2/Defs_LC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6845373191683417}}
{"text": "Require Import Coq.ZArith.ZArith. Local Open Scope Z_scope.\n\n(* For the division canceler, we use statements of the form (a = d * a') instead of\n   (a / d = a'), because the former also states that the remainder of the division is 0.\n   Using the following lemma, we can go from the former to the latter form: *)\nLemma cancel_div_done: forall [d x x': Z], d <> 0 -> x = d * x' -> x / d = x'.\nProof. intros. subst. rewrite Z.mul_comm. apply Z.div_mul. assumption. Qed.\n\nLemma cancel_div_same: forall (d: Z), d = d * 1. intros. symmetry. apply Z.mul_1_r. Qed.\n\nLemma cancel_div_add_eq: forall [d a b a' b': Z],\n    a = d * a' ->\n    b = d * b' ->\n    a + b = d * (a' + b').\nProof. intros. subst. symmetry. apply Z.mul_add_distr_l. Qed.\n\nLemma cancel_div_sub_eq: forall [d a b a' b': Z],\n    a = d * a' ->\n    b = d * b' ->\n    a - b = d * (a' - b').\nProof. intros. subst. symmetry. apply Z.mul_sub_distr_l. Qed.\n\nLemma cancel_div_opp_eq: forall [d a a': Z],\n    a = d * a' ->\n    - a = d * (- a').\nProof. intros. subst. symmetry. apply Z.mul_opp_r. Qed.\n\nLemma cancel_div_mul_l_eq: forall [d a a'] (b: Z),\n    a = d * a' ->\n    a * b = d * (a' * b).\nProof. intros. subst. symmetry. apply Z.mul_assoc. Qed.\n\nLemma cancel_div_mul_r_eq: forall [d b b': Z] (a: Z),\n    b = d * b' ->\n    a * b = d * (a * b').\nProof. intros. subst. ring. Qed.\n\n(* Given a divisor d and an expression e of type Z,\n   returns a proof of type `e = d * q` for some quotient q if possible, or else fails. *)\nLtac cancel_div_rec d e :=\n  lazymatch e with\n  | d => constr:(cancel_div_same d)\n  | Z.add ?a ?b =>\n      let pfa := cancel_div_rec d a in\n      let pfb := cancel_div_rec d b in\n      constr:(cancel_div_add_eq pfa pfb)\n  | Z.sub ?a ?b =>\n      let pfa := cancel_div_rec d a in\n      let pfb := cancel_div_rec d b in\n      constr:(cancel_div_sub_eq pfa pfb)\n  | Z.mul d ?a => constr:(@eq_refl Z e)\n  | Z.mul ?a d => constr:(Z.mul_comm a d)\n  | Z.mul ?a ?b =>\n      match constr:(Set) with\n      | _ => let pfa := cancel_div_rec d a in constr:(cancel_div_mul_l_eq b pfa)\n      | _ => let pfb := cancel_div_rec d b in constr:(cancel_div_mul_r_eq a pfb)\n      end\n  | Z.opp ?a => let pfa := cancel_div_rec d a in constr:(cancel_div_opp_eq pfa)\n  end.\n\n(* Given a divisor d, a proof that `d <> 0`, and an expression e of type Z,\n   returns a proof of type `e / d = q` for some quotient q if possible, or else fails. *)\nLtac cancel_div d d_nonzero_pf e :=\n  let e_eq_prod_pf := cancel_div_rec d e in\n  constr:(cancel_div_done d_nonzero_pf e_eq_prod_pf).\n\nGoal forall (i j k count d: Z),\n    d <> 0 ->\n    (d * j - i * d * k + count * d) / d = j - i * k + count.\nProof.\n  intros.\n  lazymatch goal with\n  | |- ?e / _ = _ => let r := cancel_div d H e in exact r\n  end.\nAbort.\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/bedrock2/src/bedrock2/cancel_div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6845373174064177}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(* ** Reification for bounded quantification *)\n\nRequire Import Arith Lia.\n\nSet Implicit Arguments.\n\n(* A nat indexed finite number of conjunctions *) \n\nDefinition fmap_reifier_t X (Q : nat -> X -> Prop) k : \n             (forall i, i < k -> sig (Q i))\n          -> { f : forall i, i < k -> X | forall i Hi, Q i (f i Hi) }.\nProof.\n  assert (H_lt_S_n : forall n m, S n < S m -> n < m) by (now intros; apply Nat.succ_lt_mono).\n  revert Q; induction k as [ | k IHk ]; intros Q HQ.\n  + assert (f : forall i, i < 0 -> X) by (intros i Hi; exfalso; revert Hi; apply Nat.nlt_0_r).\n    exists f; intros i Hi; exfalso; revert Hi; apply Nat.nlt_0_r.\n  + destruct (HQ 0) as (f0 & H0).\n    * apply Nat.lt_0_succ.\n    * destruct (IHk (fun i => Q (S i))) as (f & Hf).\n      - intros; apply HQ. apply -> Nat.succ_lt_mono; trivial.\n      - set (f' :=\n        fun i => match i return i < S k -> X with \n                   | 0   => fun _  => f0\n                   | S j => fun Hj => f j (H_lt_S_n _ _ Hj)\n                 end).\n        exists f'; intros [ | i ] Hi; simpl; trivial.\nDefined.\n\nDefinition fmap_reifier_t_default X (Q : nat -> X -> Prop) k (x : X) : \n             (forall i, i < k -> sig (Q i))\n          -> { f : nat -> X | forall i, i < k -> Q i (f i) }.\nProof.\n  intros H.\n  apply fmap_reifier_t in H.\n  destruct H as (f & Hf).\n  exists (fun i => match le_lt_dec k i with \n                          | left _ => x \n                          | right Hi => f i Hi \n                        end).\n  intros i Hi.\n  destruct (le_lt_dec k i) as [ H1 | ]; auto.\n  exfalso; revert Hi H1; apply Nat.lt_nge.\nDefined.\n\n(* Given predicate P : nat -> nat -> Prop such that\n      1/ P x is satisfiable for any x < n\n    \n    then there is a bound m such that for any x < n\n    P x y is satisfied for some y below m *)\n\nTheorem fmap_bound n P : \n           (forall x, x < n -> ex (P x)) \n        -> exists m, forall x, x < n -> exists y, y < m /\\ P x y.\nProof with try lia.\n  revert P; induction n as [ | n IHn ]; intros P HP.\n  + exists 0; intros...\n  + destruct (HP 0) as (m0 & H0)...\n    destruct (IHn (fun n => P (S n))) as (m1 & Hm1).\n    - intros; apply HP...\n    - exists (1+m0+m1); intros [ | x ] Hx.\n      * exists m0; split; auto...\n      * destruct (Hm1 x) as (y & H1 & H2)...\n        exists y; split; auto...\nQed.\n\nTheorem fmap_reifier_default X n (P : nat -> X -> Prop) : \n           inhabited X \n        -> (forall x, x < n -> ex (P x)) \n        -> exists f, forall x, x < n -> P x (f x).\nProof with try lia.\n  intros [ u ].\n  revert P; induction n as [ | n IHn ]; intros P HP.\n  + exists (fun _ => u); intros...\n  + destruct (IHn (fun i => P (S i))) as (f & Hf).\n    { intros; apply HP... }\n    destruct (HP 0) as (x & Hx)...\n    exists (fun i => match i with 0 => x | S i => f i end).\n    intros [|] ?; auto; apply Hf...\nQed. \n\nTheorem fmap_reifer_bound n P : \n           (forall x, x < n -> ex (P x)) \n        -> exists m f, forall x, x < n -> f x < m /\\ P x (f x).\nProof.\n  intros H.\n  apply fmap_bound in H.\n  destruct H as (m & Hm); exists m.\n  revert Hm; apply fmap_reifier_default; auto.\nQed.\n\n(* equal_upto m f g means f 0 = g 0, ... f (m-1) = g (m-1) *)\n\nLocal Notation equal_upto := (fun m (f g : nat -> nat) => forall n, n < m -> f n = g n).\n\n(* Given a predicate P over nat * (nat -> nat), which is supposed to be finitary \n\n  1/ for any x, P x only takes the first p values of its argument into acounts \n  2/ P x is satisfiable for any value of x lower than n\n\n  then there is a bound m such that for any x, there is always a solution f to\n  P x f which is uniformly bounded by m \n\n*)\n\nTheorem fmmap_bound p n (P : nat -> (nat -> nat) -> Prop) :\n             (forall x f g, equal_upto p f g -> P x f -> P x g)       \n          -> (forall x, x < n -> exists f, P x f) \n          -> exists m, forall x, x < n -> exists f, (forall i, i < p -> f i < m) /\\ P x f.\nProof.\n  revert P.\n  induction p as [ | p IHp ]; intros P HP H.\n  + exists 1; intros x Hx.\n    destruct (H _ Hx) as (f & Hf).\n    exists (fun _ => 0); split; auto.\n    apply (HP x f); auto.\n    intros ? ?; lia.\n  + set (Q x y := exists f, P x (fun i => match i with 0 => y | S i => f i end)).\n    destruct (@fmap_bound n Q) as (m1 & Hm1).\n    { intros x Hx.\n      destruct (H _ Hx) as (f & Hf).\n      exists (f 0); red.\n      exists (fun i => f (S i)).\n      revert Hf; apply HP.\n      intros [ | i ]; auto. }\n    set (R x f := exists y, y < m1 /\\ P x (fun i => match i with 0 => y | S i => f i end)).\n    destruct (IHp R) as (m2 & Hm2).\n    { intros x f g Hfg (y & H1 & H2); exists y; split; auto.\n      revert H2; apply HP; intros [ | ]; auto; intros; apply Hfg; lia. }\n    { intros x Hx. \n      destruct (Hm1 _ Hx) as (y & H1 & f & H2).\n      exists f, y; split; auto. }\n    exists (m1+m2).\n    intros x Hx.\n    destruct (Hm2 _ Hx) as (f & H1 & y & H2 & H3).\n    eexists; split; [ | exact H3 ].\n    intros [ | j ] Hj; try lia.\n    specialize (H1 j); intros; lia.\nQed.\n\nTheorem fmmap_reifer_bound p n (P : nat -> (nat -> nat) -> Prop) :\n             (forall x f g, equal_upto p f g -> P x f -> P x g)       \n          -> (forall x, x < n -> exists f, P x f) \n          -> exists m f, forall x, x < n -> (forall j, j < p -> f x j < m) /\\ P x (f x).\nProof.\n  intros H1 H2.\n  apply fmmap_bound with (1 := H1) in H2.\n  destruct H2 as (m & Hm).\n  apply fmap_reifier_default in Hm; auto.\n  destruct Hm as (f & Hf); exists m, f; auto.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-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/bounded_quantification.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6845373165771184}}
{"text": "Require Import Coq.ZArith.BinIntDef.\nRequire Import Coq.NArith.BinNatDef.\nRequire Import Coq.PArith.BinPosDef.\n\nRequire Coq.ZArith.Znumtheory Coq.Numbers.BinNums.\n\nRequire Crypto.Arithmetic.ModularArithmeticPre.\n\nDelimit Scope positive_scope with positive.\nBind Scope positive_scope with BinPos.positive.\nInfix \"+\" := BinPos.Pos.add : positive_scope.\nInfix \"*\" := BinPos.Pos.mul : positive_scope.\nInfix \"-\" := BinPos.Pos.sub : positive_scope.\nInfix \"^\" := BinPos.Pos.pow : positive_scope.\n\nDelimit Scope N_scope with N.\nBind Scope N_scope with BinNums.N.\nInfix \"+\" := BinNat.N.add : N_scope.\nInfix \"*\" := BinNat.N.mul : N_scope.\nInfix \"-\" := BinNat.N.sub : N_scope.\nInfix \"/\" := BinNat.N.div : N_scope.\nInfix \"^\" := BinNat.N.pow : N_scope.\n\nDelimit Scope Z_scope with Z.\nBind Scope Z_scope with BinInt.Z.\nInfix \"+\" := BinInt.Z.add : Z_scope.\nInfix \"*\" := BinInt.Z.mul : Z_scope.\nInfix \"-\" := BinInt.Z.sub : Z_scope.\nInfix \"/\" := BinInt.Z.div : Z_scope.\nInfix \"^\" := BinInt.Z.pow : Z_scope.\nInfix \"mod\" := BinInt.Z.modulo (at level 40, no associativity) : Z_scope.\n\nLocal Open Scope Z_scope.\nGlobal Coercion BinInt.Z.pos : BinPos.positive >-> BinInt.Z.\nGlobal Coercion BinInt.Z.of_N : BinNums.N >-> BinInt.Z.\nGlobal Set Printing Coercions.\n\nModule F.\n  Definition F (m : BinPos.positive) := { z : BinInt.Z | z = z mod m }.\n  Local Obligation Tactic := cbv beta; auto using ModularArithmeticPre.Z_mod_mod.\n  Program Definition of_Z  m  (a:BinNums.Z) : F m := a mod m.\n  Definition to_Z {m} (a:F m) : BinNums.Z := proj1_sig a.\n\n  Section FieldOperations.\n    Context {m : BinPos.positive}.\n    Definition zero : F m := of_Z m 0.\n    Definition one : F m := of_Z m 1.\n\n    Definition add (a b:F m) : F m := of_Z m (to_Z a + to_Z b).\n    Definition mul (a b:F m) : F m := of_Z m (to_Z a * to_Z b).\n    Definition opp (a : F m) : F m := of_Z m (0 - to_Z a).\n    Definition sub (a b:F m) : F m := add a (opp b).\n\n    Definition inv_with_spec : { inv : F m -> F m\n                               | inv zero = zero\n                                 /\\ ( Znumtheory.prime m ->\n                                      forall a, a <> zero -> mul (inv a) a = one )\n                               } := ModularArithmeticPre.inv_impl.\n    Definition inv : F m -> F m := Eval hnf in proj1_sig inv_with_spec.\n    Definition div (a b:F m) : F m := mul a (inv b).\n\n    Definition pow_with_spec : { pow : F m -> BinNums.N -> F m\n                               | forall a, pow a 0%N = one\n                                           /\\ forall x, pow a (1 + x)%N = mul a (pow a x)\n                               } := ModularArithmeticPre.pow_impl.\n    Definition pow : F m -> BinNums.N -> F m := Eval hnf in proj1_sig pow_with_spec.\n  End FieldOperations.\n\n  Definition of_nat m (n:nat) := F.of_Z m (BinInt.Z.of_nat n).\n  Definition to_nat {m} (x:F m) := BinInt.Z.to_nat (F.to_Z x).\n  Notation nat_mod := of_nat (only parsing).\n\n  Definition of_N m n := F.of_Z m (BinInt.Z.of_N n).\n  Definition to_N {m} (x:F m) := BinInt.Z.to_N (F.to_Z x).\n  Notation N_mod := of_N (only parsing).\n\n  Notation Z_mod := of_Z (only parsing).\nEnd F.\n\nNotation F := F.F.\nDeclare Scope F_scope.\nDelimit Scope F_scope with F.\nBind Scope F_scope with F.F.\nInfix \"+\" := F.add : F_scope.\nInfix \"*\" := F.mul : F_scope.\nInfix \"-\" := F.sub : F_scope.\nInfix \"/\" := F.div : F_scope.\nInfix \"^\" := F.pow : F_scope.\nNotation \"0\" := F.zero : F_scope.\nNotation \"1\" := F.one : F_scope.\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/Spec/ModularArithmetic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6845373165771184}}
{"text": "Fixpoint pow m n :=\n  match n with\n  | O => 1\n  | S n' => m * pow m n'\n  end.\n\nLemma pow_le : forall n x y,\n    n >= 1 ->\n    x <= y <-> pow n x <= pow n y.\nProof.\nAdmitted.\n\nLemma pow_plus : forall n x y,\n    pow n (x + y) = pow n x * pow n y.\nProof.\nAdmitted.\n\nInfix \"^^\" := pow (at level 30, right associativity) : nat_scope.", "meta": {"author": "yoshihiro503", "repo": "pfds_coq", "sha": "e7bf965ddeb329886210811e05f1bd4a1e7ccf53", "save_path": "github-repos/coq/yoshihiro503-pfds_coq", "path": "github-repos/coq/yoshihiro503-pfds_coq/pfds_coq-e7bf965ddeb329886210811e05f1bd4a1e7ccf53/common/Power.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6845321723989625}}
{"text": "Require Import RelationClasses.\n\nTheorem iff_refl: forall o:Prop, iff o o.\nProof.\n  intros;split;auto.\nQed.\n\nTheorem iff_symmetric: forall (o1 o2: Prop),\n  iff o1 o2 -> iff o2 o1.\nProof.\n  intros.\n  destruct H; split; auto.\nQed.\n\nTheorem iff_transitive: forall (o1 o2 o3: Prop),\n  iff o1 o2 -> iff o2 o3 -> iff o1 o3.\nProof.\n  intros; destruct H; destruct H0; split; auto.\nQed.\n\nTheorem iff_Equiv: Equivalence iff.\nProof.\n  intros.\n  eapply Build_Equivalence.\n  unfold Reflexive; apply iff_refl; auto.\n  unfold Symmetric; apply iff_symmetric; auto.\n  unfold Transitive; apply iff_transitive; auto.\nQed.", "meta": {"author": "doerrie", "repo": "confinement-proof", "sha": "db7bfb3522990d0820de64f13baa97b67e694c44", "save_path": "github-repos/coq/doerrie-confinement-proof", "path": "github-repos/coq/doerrie-confinement-proof/confinement-proof-db7bfb3522990d0820de64f13baa97b67e694c44/Iff_Equiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6845112575539878}}
{"text": "Require Import nat.\nRequire Import syntax.\nRequire Import transform.\nRequire Import fold_constants.\n\nFixpoint optimize_0plus_aexp (a:aexp) : aexp :=\n    match a with \n    | ANum n            => ANum n\n    | AKey k            => AKey k\n    | APlus (ANum 0) a2 => optimize_0plus_aexp a2\n    | APlus a1 a2       => APlus  (optimize_0plus_aexp a1)(optimize_0plus_aexp a2)\n    | AMinus a1 a2      => AMinus (optimize_0plus_aexp a1)(optimize_0plus_aexp a2)\n    | AMult a1 a2       => AMult  (optimize_0plus_aexp a1)(optimize_0plus_aexp a2)\n    end.\n\nDefinition optimize_0plus_bexp:= btrans optimize_0plus_aexp.\nDefinition optimize_0plus_com := ctrans optimize_0plus_aexp optimize_0plus_bexp.\n\nDefinition optimize_aexp (a:aexp) : aexp := \n    optimize_0plus_aexp(fold_constants_aexp a).\nDefinition optimize_bexp := btrans optimize_aexp.\nDefinition optimize_com  := ctrans optimize_aexp optimize_bexp.\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/optimize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.684435279354038}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (lf2 : natural) (lf1 : natural)\n  : natural := mult (Succ Zero) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj43_coqofml_0RahpM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6844352759803567}}
{"text": "Require Import init.\n\nRequire Export cauchy_real_plus.\n\nLemma cauchy_bounded : ∀ a : real_base, ∃ M, ∀ n, |r_seq a n| < M.\nProof.\n    intros [a a_cauchy]; cbn.\n    specialize (a_cauchy 1 one_pos) as [N a_cauchy].\n    pose (S := image_under (λ n, |a n|) (initial_segment N)).\n    assert (has_upper_bound le S) as [M M_max].\n    {\n        nat_destruct N.\n        {\n            exists 0.\n            intros x [n [n_lt n_eq]].\n            contradiction (nat_neg2 n_lt).\n        }\n        assert (simple_finite (set_type S)) as S_fin.\n        {\n            apply (simple_finite_trans _ _ (simple_finite_nat (nat_suc N))).\n            exists (λ x : set_type S, [ex_val [|x] | land (ex_proof [|x])]).\n            split.\n            intros x y.\n            rewrite set_type_eq2.\n            rewrite_ex_val m [m_lt x_eq].\n            rewrite_ex_val n [n_lt y_eq].\n            intros eq; subst n.\n            rewrite <- y_eq in x_eq.\n            rewrite set_type_eq in x_eq.\n            exact x_eq.\n        }\n        pose proof (simple_finite_max S_fin) as x_ex.\n        prove_parts x_ex.\n        {\n            exists (|a 0|).\n            exists 0.\n            split; [>|reflexivity].\n            apply nat_pos2.\n        }\n        destruct x_ex as [[x Sx] x_greatest].\n        exists x.\n        intros m Sm.\n        exact (x_greatest [m|Sm]).\n    }\n    exists (max (M + 1) (|a N| + 1)).\n    intros n.\n    classic_case (n < N) as [ltq|leq].\n    -   apply (lt_le_trans2 (lmax _ _)).\n        specialize (M_max (|a n|)).\n        prove_parts M_max; [>exists n; split; [>exact ltq|reflexivity]|].\n        apply (le_lt_trans M_max).\n        apply lt_plus_one.\n    -   apply (lt_le_trans2 (rmax _ _)).\n        rewrite nlt_le in leq.\n        specialize (a_cauchy n N leq (refl _)).\n        apply (le_lt_trans (abs_reverse_tri2 _ _)) in a_cauchy.\n        rewrite lt_plus_rlmove.\n        rewrite plus_comm.\n        exact a_cauchy.\nQed.\n\nLemma cauchy_mult : ∀ a b : real_base, cauchy_seq (λ n, r_seq a n * r_seq b n).\nProof.\n    intros a b ε ε_pos.\n    pose proof (cauchy_bounded a) as [M1 M1_gt].\n    pose proof (cauchy_bounded b) as [M2 M2_gt].\n    destruct a as [a a_cauchy], b as [b b_cauchy]; cbn in *.\n    assert (0 < M1) as M1_pos by (apply (le_lt_trans2 (M1_gt 0));apply abs_pos).\n    assert (0 < M2) as M2_pos by (apply (le_lt_trans2 (M2_gt 0));apply abs_pos).\n    pose proof (half_pos ε_pos) as ε2_pos.\n    specialize (a_cauchy _ (lt_mult (div_pos M2_pos) ε2_pos)) as [N1 a_cauchy].\n    specialize (b_cauchy _ (lt_mult (div_pos M1_pos) ε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    rewrite <- lt_mult_llmove_pos in a_cauchy by exact M2_pos.\n    rewrite <- lt_mult_llmove_pos in b_cauchy by exact M1_pos.\n    pose proof (lt_lrplus a_cauchy b_cauchy) as ltq.\n    rewrite plus_half in ltq.\n    rewrite <- (plus_rlinv (a i * b i) (a i * b j)).\n    rewrite <- mult_rneg, <- ldist.\n    rewrite <- plus_assoc.\n    rewrite <- mult_lneg, <- rdist.\n    rewrite (mult_comm _ (b j)).\n    apply (le_lt_trans (abs_tri _ _)).\n    rewrite plus_comm.\n    apply (le_lt_trans2 ltq).\n    do 2 rewrite abs_mult.\n    apply le_lrplus.\n    -   apply le_rmult_pos; [>apply abs_pos|].\n        apply M2_gt.\n    -   apply le_rmult_pos; [>apply abs_pos|].\n        apply M1_gt.\nQed.\n\nNotation \"a ⊗ b\" := (make_real _ (cauchy_mult a b)) : real_scope.\n\nLemma real_mult_wd : ∀ a b c d, a ~ b → c ~ d → a ⊗ c ~ b ⊗ d.\n    intros [a a_cauchy] b c [d d_cauchy] ab cd ε ε_pos.\n    pose proof (cauchy_bounded b) as [M1 M1_gt].\n    pose proof (cauchy_bounded c) as [M2 M2_gt].\n    destruct b as [b b_cauchy], c as [c c_cauchy]; cbn in *.\n    assert (0 < M1) as M1_pos by (apply (le_lt_trans2 (M1_gt 0));apply abs_pos).\n    assert (0 < M2) as M2_pos by (apply (le_lt_trans2 (M2_gt 0));apply abs_pos).\n    pose proof (half_pos ε_pos) as ε2_pos.\n    specialize (ab _ (lt_mult (div_pos M2_pos) ε2_pos)) as [N1 ab].\n    specialize (cd _ (lt_mult (div_pos M1_pos) ε2_pos)) as [N2 cd].\n    exists (max N1 N2).\n    intros i i_ge.\n    specialize (ab i (trans (lmax _ _) i_ge)).\n    specialize (cd i (trans (rmax _ _) i_ge)).\n    rewrite <- lt_mult_llmove_pos in ab by exact M2_pos.\n    rewrite <- lt_mult_llmove_pos in cd by exact M1_pos.\n    pose proof (lt_lrplus ab cd) as ltq.\n    rewrite plus_half in ltq.\n    rewrite <- (plus_rlinv (a i * c i) (b i * c i)).\n    rewrite <- mult_lneg, <- rdist.\n    rewrite <- plus_assoc.\n    rewrite <- mult_rneg, <- ldist.\n    rewrite (mult_comm _ (c i)).\n    apply (le_lt_trans (abs_tri _ _)).\n    apply (le_lt_trans2 ltq).\n    do 2 rewrite abs_mult.\n    apply le_lrplus.\n    -   apply le_rmult_pos; [>apply abs_pos|].\n        apply M2_gt.\n    -   apply le_rmult_pos; [>apply abs_pos|].\n        apply M1_gt.\nQed.\n\nGlobal Instance real_mult : Mult real := {\n    mult := binary_op (binary_self_wd real_mult_wd)\n}.\n\nGlobal Instance real_one : One real := {\n    one := rat_to_real 1\n}.\n\nDefinition real_div_base (a : real_base) :=\n    If (0 = to_equiv real_equiv a)\n    then λ _, 0\n    else λ n, /(r_seq a n).\n\nLemma cauchy_nz : ∀ a : real_base, 0 ≠ to_equiv real_equiv a →\n    ∃ ε N, 0 < ε ∧ (∀ i, N ≤ i → ε ≤ |r_seq a i|).\nProof.\n    intros [a a_cauchy] a_neq; cbn in *.\n    rewrite neq_sym in a_neq.\n    unfold zero in a_neq; cbn in a_neq.\n    unfold rat_to_real in a_neq; equiv_simpl in a_neq.\n    rewrite not_all in a_neq.\n    destruct a_neq as [ε a_neq].\n    rewrite not_impl in a_neq.\n    rewrite not_ex in a_neq.\n    destruct a_neq as [ε_pos a_neq].\n    specialize (a_cauchy _ (half_pos ε_pos)) as [N a_cauchy].\n    specialize (a_neq N).\n    rewrite not_all in a_neq.\n    destruct a_neq as [n a_neq].\n    rewrite not_impl in a_neq.\n    destruct a_neq as [n_ge an_ge].\n    rewrite nlt_le in an_ge.\n    rewrite neg_zero, plus_rid in an_ge.\n    exists (ε/2), N.\n    split; [>exact (half_pos ε_pos)|].\n    intros i i_ge.\n    specialize (a_cauchy n i n_ge i_ge).\n    apply (le_lt_trans (abs_reverse_tri2 _ _)) in a_cauchy.\n    rewrite <- lt_plus_rrmove in a_cauchy.\n    pose proof (le_lt_trans an_ge a_cauchy) as ltq.\n    rewrite <- (plus_half ε) in ltq at 1.\n    apply lt_plus_lcancel in ltq.\n    apply ltq.\nQed.\n\nLemma cauchy_div : ∀ a : real_base, cauchy_seq (real_div_base a).\n    intros [a a_cauchy].\n    unfold real_div_base; cbn.\n    case_if [a_eq|a_neq]; [>apply rat_to_real_cauchy|].\n    apply cauchy_nz in a_neq as [ε' [N1 [ε'_pos nz]]].\n    cbn in nz.\n    intros ε ε_pos.\n    pose proof (div_pos ε'_pos) as ε''_pos.\n    specialize (a_cauchy _ (lt_mult ε_pos (lt_mult ε'_pos ε'_pos)))\n        as [N2 a_cauchy].\n    exists (max N1 N2).\n    intros i j i_ge j_ge.\n    pose proof (nz i (trans (lmax N1 N2) i_ge)) as i_gt.\n    pose proof (nz j (trans (lmax N1 N2) j_ge)) as j_gt.\n    clear nz.\n    assert (0 ≠ a i) as ai_nz.\n    {\n        intros contr.\n        rewrite <- contr in i_gt.\n        rewrite <- abs_zero in i_gt.\n        destruct (lt_le_trans ε'_pos i_gt); contradiction.\n    }\n    assert (0 ≠ a j) as aj_nz.\n    {\n        intros contr.\n        rewrite <- contr in j_gt.\n        rewrite <- abs_zero in j_gt.\n        destruct (lt_le_trans ε'_pos j_gt); contradiction.\n    }\n    rewrite <- (mult_lrinv (/(a i)) (a j)) by exact aj_nz.\n    rewrite <- (mult_lrinv (/(a j)) (a i)) at 2 by exact ai_nz.\n    rewrite (mult_comm (/(a j))).\n    rewrite <- mult_lneg, <- rdist.\n    do 2 rewrite abs_mult.\n    specialize (a_cauchy j i (trans (rmax _ _) j_ge) (trans (rmax _ _) i_ge)).\n    rewrite mult_assoc.\n    rewrite <- abs_div by exact ai_nz.\n    rewrite <- abs_div by exact aj_nz.\n    rewrite <- lt_mult_rrmove_pos by (exact (abs_pos2 aj_nz)).\n    rewrite <- lt_mult_rrmove_pos by (exact (abs_pos2 ai_nz)).\n    apply (lt_le_trans a_cauchy).\n    rewrite <- mult_assoc.\n    apply le_lmult_pos; [>apply ε_pos|].\n    apply le_lrmult_pos.\n    -   apply ε'_pos.\n    -   apply ε'_pos.\n    -   apply j_gt.\n    -   apply i_gt.\nQed.\n\nNotation \"⊘ a\" := (make_real _ (cauchy_div a)) : real_scope.\n\nLemma real_div_wd : ∀ a b, a ~ b → ⊘a ~ ⊘b.\nProof.\n    intros a b ab ε ε_pos; cbn.\n    assert (to_equiv real_equiv a = to_equiv real_equiv b) as ab'\n        by (equiv_simpl; exact ab).\n    unfold real_div_base.\n    case_if [a_z|a_nz]; case_if [b_z|b_nz].\n    {\n        exists 0.\n        intros i i_ge.\n        rewrite neg_zero, plus_rid, <- abs_zero.\n        exact ε_pos.\n    }\n    {\n        rewrite <- ab' in b_nz.\n        contradiction.\n    }\n    {\n        rewrite ab' in a_nz.\n        contradiction.\n    }\n    clear ab'.\n    apply cauchy_nz in a_nz as [ε1 [N1 [ε1_pos a_nz]]].\n    apply cauchy_nz in b_nz as [ε2 [N2 [ε2_pos b_nz]]].\n    destruct a as [a a_cauchy], b as [b b_cauchy]; cbn in *.\n    specialize (ab _ (lt_mult ε_pos (lt_mult ε1_pos ε2_pos))) as [N ab].\n    exists (max N (max N1 N2)).\n    intros i i_ge.\n    specialize (a_nz i (trans (lmax _ _) (trans (rmax _ _) i_ge))).\n    specialize (b_nz i (trans (rmax _ _) (trans (rmax _ _) i_ge))).\n    specialize (ab i (trans (lmax _ _) i_ge)).\n    assert (0 ≠ a i) as ai_nz.\n    {\n        intros contr.\n        rewrite <- contr in a_nz.\n        rewrite <- abs_zero in a_nz.\n        destruct (lt_le_trans ε1_pos a_nz); contradiction.\n    }\n    assert (0 ≠ b i) as bi_nz.\n    {\n        intros contr.\n        rewrite <- contr in b_nz.\n        rewrite <- abs_zero in b_nz.\n        destruct (lt_le_trans ε2_pos b_nz); contradiction.\n    }\n    rewrite <- (mult_lrinv (/(a i)) (b i)) by exact bi_nz.\n    rewrite <- (mult_lrinv (/(b i)) (a i)) at 2 by exact ai_nz.\n    rewrite (mult_comm (/(a i))).\n    rewrite <- mult_lneg, <- rdist.\n    do 2 rewrite abs_mult.\n    rewrite mult_assoc.\n    rewrite <- abs_div by exact bi_nz.\n    rewrite <- abs_div by exact ai_nz.\n    rewrite <- lt_mult_rrmove_pos by (exact (abs_pos2 ai_nz)).\n    rewrite <- lt_mult_rrmove_pos by (exact (abs_pos2 bi_nz)).\n    rewrite abs_minus.\n    apply (lt_le_trans ab).\n    rewrite <- mult_assoc.\n    apply le_lmult_pos; [>apply ε_pos|].\n    apply le_lrmult_pos.\n    -   apply ε1_pos.\n    -   apply ε2_pos.\n    -   apply a_nz.\n    -   apply b_nz.\nQed.\n\nGlobal Instance real_div : Div real := {\n    div := unary_op (unary_self_wd real_div_wd)\n}.\n\nGlobal Instance real_ldist : Ldist real.\nProof.\n    split.\n    intros a b c.\n    equiv_get_value a b c.\n    unfold mult, plus; equiv_simpl.\n    intros ε ε_pos.\n    exists 0.\n    intros i i_ge.\n    rewrite ldist.\n    rewrite plus_rinv.\n    rewrite <- abs_zero.\n    exact ε_pos.\nQed.\n\nGlobal Instance real_mult_comm : MultComm real.\nProof.\n    split.\n    intros a b.\n    equiv_get_value a b.\n    unfold mult; equiv_simpl.\n    intros ε ε_pos.\n    exists 0.\n    intros i i_ge.\n    rewrite mult_comm.\n    rewrite plus_rinv.\n    rewrite <- abs_zero.\n    exact ε_pos.\nQed.\n\nGlobal Instance real_mult_assoc : MultAssoc real.\nProof.\n    split.\n    intros a b c.\n    equiv_get_value a b c.\n    unfold mult; equiv_simpl.\n    intros ε ε_pos.\n    exists 0.\n    intros i i_ge.\n    rewrite mult_assoc.\n    rewrite plus_rinv.\n    rewrite <- abs_zero.\n    exact ε_pos.\nQed.\n\nGlobal Instance real_mult_lid : MultLid real.\nProof.\n    split.\n    intros a.\n    equiv_get_value a.\n    unfold mult, one; equiv_simpl.\n    intros ε ε_pos.\n    exists 0.\n    intros i i_ge.\n    rewrite mult_lid.\n    rewrite plus_rinv.\n    rewrite <- abs_zero.\n    exact ε_pos.\nQed.\n\nGlobal Instance real_mult_linv : MultLinv real.\nProof.\n    split.\n    intros a a_nz.\n    equiv_get_value a.\n    unfold mult, div, one; cbn.\n    unfold rat_to_real; equiv_simpl.\n    intros ε ε_pos.\n    unfold real_div_base.\n    case_if [a_z|a_nz']; [>contradiction|].\n    apply cauchy_nz in a_nz' as [ε' [N [ε'_pos a_nz']]].\n    exists N.\n    intros i i_ge.\n    specialize (a_nz' i i_ge).\n    pose proof (lt_le_trans ε'_pos a_nz') as ai_pos.\n    destruct ai_pos as [ai_pos ai_nz].\n    rewrite abs_nz in ai_nz.\n    rewrite mult_linv by exact ai_nz.\n    rewrite plus_rinv.\n    rewrite <- abs_zero.\n    exact ε_pos.\nQed.\n\n#[refine]\nGlobal Instance real_not_trivial : NotTrivial real := {\n    not_trivial_a := 0;\n    not_trivial_b := 1;\n}.\nProof.\n    unfold zero, one; cbn.\n    unfold rat_to_real; equiv_simpl.\n    intros contr.\n    specialize (contr 1 one_pos) as [N contr].\n    specialize (contr N (refl _)).\n    rewrite abs_minus, neg_zero, plus_rid in contr.\n    rewrite abs_one in contr.\n    destruct contr; contradiction.\nQed.\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Number/Real/Cauchy/cauchy_real_mult.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6844256763586988}}
{"text": "Require Import Coq.Strings.String.\nRequire Import syntax.\n\n(* Helpers *)\nSection helpers.\n\nInductive freeVar (x1 : termId) : term -> Prop :=\n| freeEvar :\n    forall x2,\n    x1 = x2 ->\n    freeVar x1 (evar x2)\n| freeAbs :\n    forall x2 t e,\n    x1 <> x2 ->\n    freeVar x1 e ->\n    freeVar x1 (eabs x2 t e)\n| freeApp1 :\n    forall e1 e2,\n    freeVar x1 e1 ->\n    freeVar x1 (eapp e2 e1)\n| freeApp2 :\n    forall e1 e2,\n    freeVar x1 e2 ->\n    freeVar x1 (eapp e2 e1).\n\n(* Proves either equality or inequality of identifiers. *)\nTheorem eqId :\n  forall (idT : idType) (x1 : id idT) (x2 : id idT),\n  {x1 = x2} + {x1 <> x2}.\nProof.\n  intros T x1 x2.\n  destruct x1 as [H1 s1].\n  destruct x2 as [H1 s2].\n  pose (H2 := string_dec s1 s2).\n  case H2.\n  - intros H3.\n    apply left.\n    congruence.\n  - intros H3.\n    apply right.\n    congruence.\nQed.\n\n(* Look up variables in the context *)\nFixpoint lookupEvar (c1 : context) (x1 : termId) :=\n  match c1 with\n  | cempty => None\n  | cextend c2 x2 t =>\n    match eqId idTerm x1 x2 with\n    | left _ => Some t\n    | right _ => lookupEvar c2 x1\n    end\n  end.\n\nFixpoint subst (e1 : term) (x1 : termId) (e2 : term) :=\n  match e1 with\n  | eunit => e1\n  | evar x2 =>\n    match eqId idTerm x1 x2 with\n    | left _ => e2\n    | right _ => e1\n    end\n  | eabs x2 t e3 =>\n    match eqId idTerm x1 x2 with\n    | left _ => e1\n    | right _ => eabs x2 t (subst e3 x1 e2)\n    end\n  | eapp e3 e4 => eapp (subst e3 x1 e2) (subst e4 x1 e2)\n  end.\nEnd helpers.\n\n(* Typing rules *)\nInductive hasType : context -> term -> type -> Prop :=\n| tUnit :\n    forall c,\n    hasType c eunit tunit\n| tVar :\n    forall c x t,\n    lookupEvar c x = Some t ->\n    hasType c (evar x) t\n| tAbs :\n    forall c x e1 t1 t2,\n    hasType (cextend c x t2) e1 t1 ->\n    hasType c (eabs x t2 e1) (tarrow t2 t1)\n| tApp :\n    forall c e1 e2 t1 t2,\n    hasType c e2 (tarrow t1 t2) ->\n    hasType c e1 t1 ->\n    hasType c (eapp e2 e1) t2.\n\n(* Operational semantics *)\nInductive value : term -> Prop :=\n| valUnit : value eunit\n| valAbs : forall x e1 t1, value (eabs x t1 e1).\n\nInductive step : term -> term -> Prop :=\n| stAppAbs :\n    forall x e1 e2 t1,\n    value e2 ->\n    step (eapp (eabs x t1 e1) e2) (subst e1 x e2)\n| stApp1 :\n    forall e1 e2 e3,\n    step e1 e2 ->\n    step (eapp e1 e3) (eapp e2 e3)\n| stApp2 :\n    forall e1 e2 e3,\n    value e1 ->\n    step e2 e3 ->\n    step (eapp e1 e2) (eapp e1 e3).\n\nInductive bigstep : term -> term -> Prop :=\n| bigRefl :\n    forall e,\n    bigstep e e\n| bigInd :\n    forall e1 e2 e3,\n    bigstep e1 e2 ->\n    step e2 e3 ->\n    bigstep e1 e3.\n", "meta": {"author": "etawang", "repo": "coq-practice", "sha": "89af7aec8422f200d868f14ee4d60de3030d4bbc", "save_path": "github-repos/coq/etawang-coq-practice", "path": "github-repos/coq/etawang-coq-practice/coq-practice-89af7aec8422f200d868f14ee4d60de3030d4bbc/stlc/judgments.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6844256643736176}}
{"text": "(* Slope_base.v *)\n\nRequire Import Utf8.\nRequire Import QArith.\n\nDefinition slope_expr pt₁ pt₂ :=\n  (snd pt₂ - snd pt₁) / (fst pt₂ - fst pt₁).\n", "meta": {"author": "roglo", "repo": "puiseuxth", "sha": "5b1cdc4d42e3585f5fdd57431cc06a3ffcdc3fb5", "save_path": "github-repos/coq/roglo-puiseuxth", "path": "github-repos/coq/roglo-puiseuxth/puiseuxth-5b1cdc4d42e3585f5fdd57431cc06a3ffcdc3fb5/coq/Slope_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.684423412773414}}
{"text": "Require Import Arith.\nRequire Import Bool.\nRequire Import NAxioms NSub NZDiv.\n\n(* group size *)\nVariable gs : nat.\n\n(* max_lvl = number of levels - 1 (so nl=0 means one level).  The \"highest\" level\n   (i.e., the one numbered max_lvl) consists of a single group comprising the entire graph.\n   The \"lowest\" level (numbered 0) conceptually consists of gs^max_lvl groups, all of size 1. *)\nVariable max_lvl : nat.\n\n(* Graphs are assumed to have gs^max_lvl nodes numbered from 0 to gs^max_lvl - 1.\n   We represent them as boolean functions on pairs of nodes. *)\nDefinition node := nat.\nDefinition graph:= node -> node -> bool.\n \n \n(* has_path g n x y:  Graph g has a path of length n from node x to node y. *)\nInductive has_path (g:graph) : nat -> node -> node -> Prop :=\n| HP_Self (x:node): has_path g O x x\n| HP_Step (n:nat) (x y z:node) (ST: g x y = true) (HP: has_path g n y z): has_path g (S n) x z.\n\n(* number of level-v groups *)\nDefinition num_groups v := gs^(max_lvl-v).\n\n(* level-v group number containing node x *)\nDefinition group_of v x := x/(gs^v).\n\n(* Decide whether two groups are in the same super-group (one level up). *)\nDefinition same_supergroup p1 p2 := p1/gs = p2/gs.\n\n(* Strongly connected Netsukuku property: For every level v, and every pair of groups p1\n   and p2 at level v contained within the same supergroup (at level v+1), there exists a\n   path (having some length n) from a node x within p1 to a node y within p2. *)\nDefinition is_netsukuku_strong (g:graph) : Prop :=\n  forall v p1 p2, v <= max_lvl -> p1 < num_groups v -> p2 < num_groups v ->\n                  same_supergroup p1 p2 ->\n    exists n x y, group_of v x = p1 /\\ group_of v y = p2 /\\ has_path g n x y.\n\n(* Fully connected Netsukuku property: For every level v, and every pair of groups p1\n   and p2 at level v contained within the same supergroup (at level v+1), there exists a\n   direct link from a node x within p1 to a node y within p2. *)\nDefinition is_netsukuku_full (g:graph) : Prop :=\n  forall v p1 p2, v <= max_lvl -> p1 < num_groups v -> p2 < num_groups v ->\n                  same_supergroup p1 p2 ->\n    exists x y, group_of v x = p1 /\\ group_of v y = p2 /\\ g x y = true.\n\nDefinition mygraph (x y:nat):bool:=\n(Nat.eqb y (x+1) || Nat.eqb y (x-1)).\n\nLemma xyz:\n  forall x n, has_path mygraph n x (x+n) -> has_path mygraph n (x+n) x.\nProof.\n  induction n.\n  intros.\n  SearchAbout plus.\n  rewrite <- plus_n_O in H.\n  rewrite <- plus_n_O.\n  assumption.\n  intros.\n  inversion H. subst.\n  apply IHn with (n:=S n).\nAdmitted.\n(* If all we know is that a graph obeys the strongly connected Netsukuku property, then\n   there might exist nodes x and y such that the shortest path between them has length\n   gs^max_lvl - 1. *)\nTheorem strong_worst_case:\n  exists g x y, is_netsukuku_strong g /\\ x < gs^max_lvl /\\ y < gs^max_lvl /\\\n    forall n, has_path g n x y -> n >= gs^max_lvl - 1.\nProof.\n  exists mygraph.\n  exists (gs-1).\n  exists (gs-2).\n  split.\n    unfold is_netsukuku_strong.\n    intros.\n    exists (p2-p1).\n    exists (p1).\n    exists (p2).\n    split.\n    induction v.\n    unfold group_of. simpl.\n    \n    inversion H0. destruct H0.\n    inversion H1. destruct H1.\n    inversion H2. destruct H2.\n    \nAdmitted.\n\n\n\n(* But if we know a graph obeys the fully connected Netsukuku property, then the worst\n   path length is always less than 2^max_lvl. *)\nTheorem full_worst_case:\n  forall g x y, is_netsukuku_full g -> x < gs^max_lvl -> y < gs^max_lvl ->\n      exists n, n < 2^max_lvl /\\ has_path g n x y.\nProof.\n  intros.\n  exists O.\n  split.\n    induction max_lvl.\n    simpl.\n    apply Nat.lt_0_1.\n    SearchPattern (_<_).\n    admit.\nAdmitted.\n", "meta": {"author": "Ashwin1421", "repo": "ntk_p2p", "sha": "fce3780c037552bd6be7371d75c32b8a79e202b7", "save_path": "github-repos/coq/Ashwin1421-ntk_p2p", "path": "github-repos/coq/Ashwin1421-ntk_p2p/ntk_p2p-fce3780c037552bd6be7371d75c32b8a79e202b7/take-2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6843841216849601}}
{"text": "Require Import Reals Lra.\nFrom Coquelicot Require Import Coquelicot.\nRequire Import Interval.Tactic Interval.Plot.\nOpen Scope R_scope.\n\n(***************************************************************************)\n(****************************** Real functions *****************************)\n(***************************************************************************)\n\nCheck PI.\n\nLemma PI_approx2 : 3.14 <= PI <= 3.15.\nProof.\ninterval.\nQed.\n\nDefinition psin := ltac:(plot sin 0 PI).\n\nPlot psin.\n\nDefinition psinv := ltac:(plot (fun x => sin (1 / x)) (0.01) (0.2)).\n\nPlot psinv.\n(* By comparison, gnuplot has a strange and erroneous behavior close to 0.\n   Here is the command line:\n\n   echo \"set xrange [0.01:0.2]; plot sin(1/x)\" | gnuplot -p\n\n*)\n\n(* Decimal value of PI is 3.141592653589793238462643383279... *)\nLemma val_sin_gt0 : \n  forall x, (0 < sin 3.1415926535) /\\\n   (0 < x <= 3.14159265358979 -> 0 < sin x).\nProof.\nintros x.\n  split.\n    interval.\nset (y := 3.14159265358979).\nassert (x_lt_pi : 0 < y < PI).\n  unfold y; split. \n    interval.\n  Fail interval.\n  interval with (i_prec 128).\nintros intx.\napply sin_gt_0.\n  tauto.\napply Rle_lt_trans with y.\n  tauto.\ntauto.\nQed.\n\n(* This property can be visualize using gnuplot by typing\n  echo \"set xrange [0:10]; plot x, sin(x)\" | gnuplot -p\n*)\nLemma sinx_ltx x : 0 < x -> sin x < x.\nProof.\nintros xgt0.\nFail interval.\napply Rminus_gt_0_lt.\n(* Cut the proof in two parts: after PI/2 and before. *)\ncase (Rgt_ge_dec x (PI / 2)).\n  assert (sin x <= 1) by (assert (tmp := SIN_bound x); lra).\n  assert (tmp := PI2_1).\n  lra.\nintros xsmall.\n(* Show the value of the derivative. *)\nassert (der : forall c, 0 <= c <= x -> \n         derivable_pt_lim (fun x => x - sin x) c\n           (1 - cos c)).\n  intros c _.\n  auto_derive.\n    auto.\n  ring.\ndestruct (MVT_cor2 (fun x => x - sin x)\n           (fun x => 1 - cos x) 0 x xgt0 der) as\n  [c [feq cint]].\nrewrite sin_0, !Rminus_0_r in feq; rewrite feq.\napply Rmult_lt_0_compat; cycle 1.\n  auto.\nenough (cos c < 1) by lra.\nrewrite <- cos_0.\napply cos_decreasing_1.\n        lra.\n      lra.\n    lra.\n  lra.\nlra.\nQed.\n", "meta": {"author": "ybertot", "repo": "osxp_demos_coq", "sha": "7cf2d5428078c8af06c766547859ba88044a3eff", "save_path": "github-repos/coq/ybertot-osxp_demos_coq", "path": "github-repos/coq/ybertot-osxp_demos_coq/osxp_demos_coq-7cf2d5428078c8af06c766547859ba88044a3eff/Interval/sin_properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.6842925565588234}}
{"text": "From Hammer Require Import Hammer.\n\n\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Logic.\nRequire Coq.omega.Omega.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nInductive even : nat -> Prop :=\n| ev_0 : even 0\n| ev_SS (n : nat) (H : even n) : even (S (S n)).\n\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\n\n\n\n\n\n\n\n\n\n\n\nTheorem ev_4 : even 4.\nProof. hammer_hook \"IndProp\" \"IndProp.ev_4\". apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\n\n\nTheorem ev_4' : even 4.\nProof. hammer_hook \"IndProp\" \"IndProp.ev_4'\". apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\n\n\nTheorem ev_plus4 : forall n, even n -> even (4 + n).\nProof. hammer_hook \"IndProp\" \"IndProp.ev_plus4\".\nintros n. simpl. intros Hn.\napply ev_SS. apply ev_SS. apply Hn.\nQed.\n\n\nTheorem ev_double : forall n,\neven (double n).\nProof. hammer_hook \"IndProp\" \"IndProp.ev_double\".\nAdmitted.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nTheorem ev_inversion :\nforall (n : nat), even n ->\n(n = 0) \\/ (exists n', n = S (S n') /\\ even n').\nProof. hammer_hook \"IndProp\" \"IndProp.ev_inversion\".\nintros n E.\ndestruct E as [ | n' E'].\n-\nleft. reflexivity.\n-\nright. exists n'. split. reflexivity. apply E'.\nQed.\n\n\n\nTheorem ev_minus2 : forall n,\neven n -> even (pred (pred n)).\nProof. hammer_hook \"IndProp\" \"IndProp.ev_minus2\".\nintros n E.\ndestruct E as [| n' E'].\n-  simpl. apply ev_0.\n-  simpl. apply E'.\nQed.\n\n\n\nTheorem evSS_ev : forall n,\neven (S (S n)) -> even n.\n\nProof. hammer_hook \"IndProp\" \"IndProp.evSS_ev\".\nintros n E.\ndestruct E as [| n' E'].\n-\n\nAbort.\n\n\n\n\n\nTheorem evSS_ev : forall n, even (S (S n)) -> even n.\nProof. hammer_hook \"IndProp\" \"IndProp.evSS_ev\". intros n H. apply ev_inversion in H. destruct H.\n- discriminate H.\n- destruct H as [n' [Hnm Hev]]. injection Hnm.\nintro Heq. rewrite Heq. apply Hev.\nQed.\n\n\n\n\n\nTheorem evSS_ev' : forall n,\neven (S (S n)) -> even n.\nProof. hammer_hook \"IndProp\" \"IndProp.evSS_ev'\".\nintros n E.\ninversion E as [| n' E'].\n\napply E'.\nQed.\n\n\nTheorem one_not_even : ~ even 1.\nProof. hammer_hook \"IndProp\" \"IndProp.one_not_even\".\nintros H. apply ev_inversion in H.\ndestruct H as [ | [m [Hm _]]].\n- discriminate H.\n- discriminate Hm.\nQed.\n\nTheorem one_not_even' : ~ even 1.\nintros H. inversion H. Qed.\n\n\n\nTheorem SSSSev__even : forall n,\neven (S (S (S (S n)))) -> even n.\nProof. hammer_hook \"IndProp\" \"IndProp.SSSSev__even\".\nAdmitted.\n\n\n\n\nTheorem even5_nonsense :\neven 5 -> 2 + 2 = 9.\nProof. hammer_hook \"IndProp\" \"IndProp.even5_nonsense\".\nAdmitted.\n\n\n\n\nTheorem inversion_ex1 : forall (n m o : nat),\n[n; m] = [o; o] ->\n[n] = [m].\nProof. hammer_hook \"IndProp\" \"IndProp.inversion_ex1\".\nintros n m o H. inversion H. reflexivity. Qed.\n\nTheorem inversion_ex2 : forall (n : nat),\nS n = O ->\n2 + 2 = 5.\nProof. hammer_hook \"IndProp\" \"IndProp.inversion_ex2\".\nintros n contra. inversion contra. Qed.\n\n\n\n\n\nLemma ev_even_firsttry : forall n,\neven n -> exists k, n = double k.\nProof. hammer_hook \"IndProp\" \"IndProp.ev_even_firsttry\".\n\n\n\n\nintros n E. inversion E as [| n' E'].\n-\nexists 0. reflexivity.\n-  simpl.\n\n\n\nassert (I : (exists k', n' = double k') ->\n(exists k, S (S n') = double k)).\n{ intros [k' Hk']. rewrite Hk'. exists (S k'). reflexivity. }\napply I.\n\nAbort.\n\n\n\n\n\n\n\n\nLemma ev_even : forall n,\neven n -> exists k, n = double k.\nProof. hammer_hook \"IndProp\" \"IndProp.ev_even\".\nintros n E.\ninduction E as [|n' E' IH].\n-\nexists 0. reflexivity.\n-\ndestruct IH as [k' Hk'].\nrewrite Hk'. exists (S k'). reflexivity.\nQed.\n\n\n\n\n\nTheorem ev_even_iff : forall n,\neven n <-> exists k, n = double k.\nProof. hammer_hook \"IndProp\" \"IndProp.ev_even_iff\".\nintros n. split.\n-  apply ev_even.\n-  intros [k Hk]. rewrite Hk. apply ev_double.\nQed.\n\n\n\n\n\n\nTheorem ev_sum : forall n m, even n -> even m -> even (n + m).\nProof. hammer_hook \"IndProp\" \"IndProp.ev_sum\".\nAdmitted.\n\n\n\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\n\nTheorem even'_ev : forall n, even' n <-> even n.\nProof. hammer_hook \"IndProp\" \"IndProp.even'_ev\".\nAdmitted.\n\n\n\n\nTheorem ev_ev__ev : forall n m,\neven (n+m) -> even n -> even m.\nProof. hammer_hook \"IndProp\" \"IndProp.ev_ev__ev\".\nAdmitted.\n\n\n\n\nTheorem ev_plus_plus : forall n m p,\neven (n+m) -> even (n+p) -> even (m+p).\nProof. hammer_hook \"IndProp\" \"IndProp.ev_plus_plus\".\nAdmitted.\n\n\n\n\n\n\n\nModule Playground.\n\n\n\n\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\n\n\n\nTheorem test_le1 :\n3 <= 3.\nProof. hammer_hook \"IndProp\" \"IndProp.Playground.test_le1\".\n\napply le_n.  Qed.\n\nTheorem test_le2 :\n3 <= 6.\nProof. hammer_hook \"IndProp\" \"IndProp.Playground.test_le2\".\n\napply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n(2 <= 1) -> 2 + 2 = 5.\nProof. hammer_hook \"IndProp\" \"IndProp.Playground.test_le3\".\n\nintros H. inversion H. inversion H2.  Qed.\n\n\n\nEnd Playground.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n\n\nInductive square_of : nat -> nat -> Prop :=\n| sq 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\n\n\n\n\n\n\n\n\n\n\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof. hammer_hook \"IndProp\" \"IndProp.le_trans\".\nAdmitted.\n\nTheorem O_le_n : forall n,\n0 <= n.\nProof. hammer_hook \"IndProp\" \"IndProp.O_le_n\".\nAdmitted.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\nn <= m -> S n <= S m.\nProof. hammer_hook \"IndProp\" \"IndProp.n_le_m__Sn_le_Sm\".\nAdmitted.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\nS n <= S m -> n <= m.\nProof. hammer_hook \"IndProp\" \"IndProp.Sn_le_Sm__n_le_m\".\nAdmitted.\n\nTheorem le_plus_l : forall a b,\na <= a + b.\nProof. hammer_hook \"IndProp\" \"IndProp.le_plus_l\".\nAdmitted.\n\nTheorem plus_lt : forall n1 n2 m,\nn1 + n2 < m ->\nn1 < m /\\ n2 < m.\nProof. hammer_hook \"IndProp\" \"IndProp.plus_lt\".\nunfold lt.\nAdmitted.\n\nTheorem lt_S : forall n m,\nn < m ->\nn < S m.\nProof. hammer_hook \"IndProp\" \"IndProp.lt_S\".\nAdmitted.\n\nTheorem leb_complete : forall n m,\nn <=? m = true -> n <= m.\nProof. hammer_hook \"IndProp\" \"IndProp.leb_complete\".\nAdmitted.\n\n\n\nTheorem leb_correct : forall n m,\nn <= m ->\nn <=? m = true.\nProof. hammer_hook \"IndProp\" \"IndProp.leb_correct\".\nAdmitted.\n\n\n\nTheorem leb_true_trans : forall n m o,\nn <=? m = true -> m <=? o = true -> n <=? o = true.\nProof. hammer_hook \"IndProp\" \"IndProp.leb_true_trans\".\nAdmitted.\n\n\n\nTheorem leb_iff : forall n m,\nn <=? m = true <-> n <= m.\nProof. hammer_hook \"IndProp\" \"IndProp.leb_iff\".\nAdmitted.\n\n\nModule R.\n\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\n\nDefinition manual_grade_for_R_provability : option (nat*string) := None.\n\n\n\n\nDefinition fR : nat -> nat -> nat\n. Admitted.\n\nTheorem R_equiv_fR : forall m n o, R m n o <-> fR m n = o.\nProof. hammer_hook \"IndProp\" \"IndProp.R.R_equiv_fR\".\nAdmitted.\n\n\nEnd R.\n\n\n\nInductive subseq : list nat -> list nat -> Prop :=\n\n.\n\nTheorem subseq_refl : forall (l : list nat), subseq l l.\nProof. hammer_hook \"IndProp\" \"IndProp.subseq_refl\".\nAdmitted.\n\nTheorem subseq_app : forall (l1 l2 l3 : list nat),\nsubseq l1 l2 ->\nsubseq l1 (l2 ++ l3).\nProof. hammer_hook \"IndProp\" \"IndProp.subseq_app\".\nAdmitted.\n\nTheorem subseq_trans : forall (l1 l2 l3 : list nat),\nsubseq l1 l2 ->\nsubseq l2 l3 ->\nsubseq l1 l3.\nProof. hammer_hook \"IndProp\" \"IndProp.subseq_trans\".\nAdmitted.\n\n\n\n\n\n\n\n\n\n\n\n\n\nInductive reg_exp {T : Type} : Type :=\n| EmptySet\n| EmptyStr\n| Char (t : T)\n| App (r1 r2 : reg_exp)\n| Union (r1 r2 : reg_exp)\n| Star (r : reg_exp).\n\n\n\n\n\n\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) :\nexp_match (s1 ++ s2) (App re1 re2)\n| MUnionL s1 re1 re2\n(H1 : exp_match s1 re1) :\nexp_match s1 (Union re1 re2)\n| MUnionR re1 s2 re2\n(H2 : exp_match s2 re2) :\nexp_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)) :\nexp_match (s1 ++ s2) (Star re).\n\n\n\nNotation \"s =~ re\" := (exp_match s re) (at level 80).\n\n\n\n\n\nExample reg_exp_ex1 : [1] =~ Char 1.\nProof. hammer_hook \"IndProp\" \"IndProp.reg_exp_ex1\".\napply MChar.\nQed.\n\nExample reg_exp_ex2 : [1; 2] =~ App (Char 1) (Char 2).\nProof. hammer_hook \"IndProp\" \"IndProp.reg_exp_ex2\".\napply (MApp [1] _ [2]).\n- apply MChar.\n- apply MChar.\nQed.\n\n\n\nExample reg_exp_ex3 : ~ ([1; 2] =~ Char 1).\nProof. hammer_hook \"IndProp\" \"IndProp.reg_exp_ex3\".\nintros H. inversion H.\nQed.\n\n\n\nFixpoint reg_exp_of_list {T} (l : list T) :=\nmatch l with\n| [] => EmptyStr\n| x :: l' => App (Char x) (reg_exp_of_list l')\nend.\n\nExample reg_exp_ex4 : [1; 2; 3] =~ reg_exp_of_list [1; 2; 3].\nProof. hammer_hook \"IndProp\" \"IndProp.reg_exp_ex4\".\nsimpl. apply (MApp [1]).\n{ apply MChar. }\napply (MApp [2]).\n{ apply MChar. }\napply (MApp [3]).\n{ apply MChar. }\napply MEmpty.\nQed.\n\n\n\nLemma MStar1 :\nforall T s (re : @reg_exp T) ,\ns =~ re ->\ns =~ Star re.\nProof. hammer_hook \"IndProp\" \"IndProp.MStar1\".\nintros T s re H.\nrewrite <- (app_nil_r _ s).\napply (MStarApp s [] re).\n- apply H.\n- apply MStar0.\nQed.\n\n\n\n\n\nLemma empty_is_empty : forall T (s : list T),\n~ (s =~ EmptySet).\nProof. hammer_hook \"IndProp\" \"IndProp.empty_is_empty\".\nAdmitted.\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : @reg_exp T),\ns =~ re1 \\/ s =~ re2 ->\ns =~ Union re1 re2.\nProof. hammer_hook \"IndProp\" \"IndProp.MUnion'\".\nAdmitted.\n\n\n\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp),\n(forall s, In s ss -> s =~ re) ->\nfold app ss [] =~ Star re.\nProof. hammer_hook \"IndProp\" \"IndProp.MStar'\".\nAdmitted.\n\n\n\n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\ns1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof. hammer_hook \"IndProp\" \"IndProp.reg_exp_of_list_spec\".\nAdmitted.\n\n\n\n\n\n\nFixpoint re_chars {T} (re : reg_exp) : list T :=\nmatch 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\nend.\n\n\n\nTheorem in_re_match : forall T (s : list T) (re : reg_exp) (x : T),\ns =~ re ->\nIn x s ->\nIn x (re_chars re).\nProof. hammer_hook \"IndProp\" \"IndProp.in_re_match\".\nintros T s re x Hmatch Hin.\ninduction Hmatch\nas [| 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-\napply Hin.\n-\napply Hin.\n- simpl. rewrite In_app_iff in *.\ndestruct Hin as [Hin | Hin].\n+\nleft. apply (IH1 Hin).\n+\nright. apply (IH2 Hin).\n-\nsimpl. rewrite In_app_iff.\nleft. apply (IH Hin).\n-\nsimpl. rewrite In_app_iff.\nright. apply (IH Hin).\n-\ndestruct Hin.\n\n\n\n-\nsimpl. rewrite In_app_iff in Hin.\ndestruct Hin as [Hin | Hin].\n+\napply (IH1 Hin).\n+\napply (IH2 Hin).\nQed.\n\n\n\nFixpoint re_not_empty {T : Type} (re : @reg_exp T) : bool\n. Admitted.\n\nLemma re_not_empty_correct : forall T (re : @reg_exp T),\n(exists s, s =~ re) <-> re_not_empty re = true.\nProof. hammer_hook \"IndProp\" \"IndProp.re_not_empty_correct\".\nAdmitted.\n\n\n\n\n\n\n\nLemma star_app: forall T (s1 s2 : list T) (re : @reg_exp T),\ns1 =~ Star re ->\ns2 =~ Star re ->\ns1 ++ s2 =~ Star re.\nProof. hammer_hook \"IndProp\" \"IndProp.star_app\".\nintros T s1 s2 re H1.\n\n\n\ninduction H1\nas [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n|s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH\n|re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n\n\n\n-\nsimpl. intros H. apply H.\n\n\n\n-\nAbort.\n\n\n\nLemma star_app: forall T (s1 s2 : list T) (re re' : reg_exp),\nre' = Star re ->\ns1 =~ re' ->\ns2 =~ Star re ->\ns1 ++ s2 =~ Star re.\n\n\n\nAbort.\n\n\n\nLemma star_app: forall T (s1 s2 : list T) (re : reg_exp),\ns1 =~ Star re ->\ns2 =~ Star re ->\ns1 ++ s2 =~ Star re.\nProof. hammer_hook \"IndProp\" \"IndProp.star_app\".\nintros T s1 s2 re H1.\nremember (Star re) as re'.\n\n\n\ngeneralize dependent s2.\ninduction H1\nas [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n|s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH\n|re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n\n\n\n-   discriminate.\n-    discriminate.\n-     discriminate.\n-  discriminate.\n-  discriminate.\n\n\n\n-\ninjection Heqre'. intros Heqre'' s H. apply H.\n\n-\ninjection Heqre'. intros H0.\nintros s2 H1. rewrite <- app_assoc.\napply MStarApp.\n+ apply Hmatch1.\n+ apply IH2.\n* rewrite H0. reflexivity.\n* apply H1.\nQed.\n\n\n\n\n\nLemma MStar'' : forall T (s : list T) (re : reg_exp),\ns =~ Star re ->\nexists ss : list (list T),\ns = fold app ss []\n/\\ forall s', In s' ss -> s' =~ re.\nProof. hammer_hook \"IndProp\" \"IndProp.MStar''\".\nAdmitted.\n\n\n\n\nModule Pumping.\n\nFixpoint pumping_constant {T} (re : @reg_exp T) : nat :=\nmatch re with\n| EmptySet => 0\n| EmptyStr => 1\n| Char _ => 2\n| App re1 re2 =>\npumping_constant re1 + pumping_constant re2\n| Union re1 re2 =>\npumping_constant re1 + pumping_constant re2\n| Star _ => 1\nend.\n\n\n\nFixpoint napp {T} (n : nat) (l : list T) : list T :=\nmatch n with\n| 0 => []\n| S n' => l ++ napp n' l\nend.\n\nLemma napp_plus: forall T (n m : nat) (l : list T),\nnapp (n + m) l = napp n l ++ napp m l.\nProof. hammer_hook \"IndProp\" \"IndProp.Pumping.napp_plus\".\nintros T n m l.\ninduction n as [|n IHn].\n- reflexivity.\n- simpl. rewrite IHn, app_assoc. reflexivity.\nQed.\n\n\n\nLemma pumping : forall T (re : @reg_exp T) s,\ns =~ re ->\npumping_constant re <= length s ->\nexists s1 s2 s3,\ns = s1 ++ s2 ++ s3 /\\\ns2 <> [] /\\\nforall m, s1 ++ napp m s2 ++ s3 =~ re.\n\n\n\nImport Coq.omega.Omega.\n\nProof. hammer_hook \"IndProp\" \"IndProp.Pumping.pumping\".\nintros T re s Hmatch.\ninduction Hmatch\nas [ | 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-\nsimpl. omega.\nAdmitted.\n\nEnd Pumping.\n\n\n\n\n\n\n\nTheorem filter_not_empty_In : forall n l,\nfilter (fun x => n =? x) l <> [] ->\nIn n l.\nProof. hammer_hook \"IndProp\" \"IndProp.filter_not_empty_In\".\nintros n l. induction l as [|m l' IHl'].\n-\nsimpl. intros H. apply H. reflexivity.\n-\nsimpl. destruct (n =? m) eqn:H.\n+\nintros _. rewrite eqb_eq in H. rewrite H.\nleft. reflexivity.\n+\nintros H'. right. apply IHl'. apply H'.\nQed.\n\n\n\n\n\nInductive reflect (P : Prop) : bool -> Prop :=\n| ReflectT (H :   P) : reflect P true\n| ReflectF (H : ~ P) : reflect P false.\n\n\n\nTheorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.\nProof. hammer_hook \"IndProp\" \"IndProp.iff_reflect\".\n\nintros P b H. destruct b.\n- apply ReflectT. rewrite H. reflexivity.\n- apply ReflectF. rewrite H. intros H'. discriminate.\nQed.\n\n\n\n\nTheorem reflect_iff : forall P b, reflect P b -> (P <-> b = true).\nProof. hammer_hook \"IndProp\" \"IndProp.reflect_iff\".\nAdmitted.\n\n\n\n\nLemma eqbP : forall n m, reflect (n = m) (n =? m).\nProof. hammer_hook \"IndProp\" \"IndProp.eqbP\".\nintros n m. apply iff_reflect. rewrite eqb_eq. reflexivity.\nQed.\n\n\n\n\n\nTheorem filter_not_empty_In' : forall n l,\nfilter (fun x => n =? x) l <> [] ->\nIn n l.\nProof. hammer_hook \"IndProp\" \"IndProp.filter_not_empty_In'\".\nintros n l. induction l as [|m l' IHl'].\n-\nsimpl. intros H. apply H. reflexivity.\n-\nsimpl. destruct (eqbP n m) as [H | H].\n+\nintros _. rewrite H. left. reflexivity.\n+\nintros H'. right. apply IHl'. apply H'.\nQed.\n\n\n\nFixpoint count n l :=\nmatch l with\n| [] => 0\n| m :: l' => (if n =? m then 1 else 0) + count n l'\nend.\n\nTheorem eqbP_practice : forall n l,\ncount n l = 0 -> ~(In n l).\nProof. hammer_hook \"IndProp\" \"IndProp.eqbP_practice\".\nAdmitted.\n\n\n\n\n\n\n\n\n\nInductive nostutter {X:Type} : list X -> Prop :=\n\n.\n\n\nExample test_nostutter_1: nostutter [3;1;4;1;5;6].\nAdmitted.\n\n\nExample test_nostutter_2:  nostutter (@nil nat).\nAdmitted.\n\n\nExample test_nostutter_3:  nostutter [5].\nAdmitted.\n\n\nExample test_nostutter_4:      not (nostutter [3;1;1;4]).\nAdmitted.\n\n\n\nDefinition manual_grade_for_nostutter : option (nat*string) := None.\n\n\n\n\n\n\n\nDefinition manual_grade_for_filter_challenge : option (nat*string) := None.\n\n\n\n\n\n\n\n\n\n\n\nDefinition manual_grade_for_pal_pal_app_rev_pal_rev : option (nat*string) := None.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nDefinition manual_grade_for_NoDup_disjoint_etc : option (nat*string) := None.\n\n\n\n\n\n\nLemma in_split : forall (X:Type) (x:X) (l:list X),\nIn x l ->\nexists l1 l2, l = l1 ++ x :: l2.\nProof. hammer_hook \"IndProp\" \"IndProp.in_split\".\nAdmitted.\n\n\n\nInductive repeats {X:Type} : list X -> Prop :=\n\n.\n\n\n\nTheorem pigeonhole_principle: forall (X:Type) (l1  l2:list X),\nexcluded_middle ->\n(forall x, In x l1 -> In x l2) ->\nlength l2 < length l1 ->\nrepeats l1.\nProof. hammer_hook \"IndProp\" \"IndProp.pigeonhole_principle\".\nintros X l1. induction l1 as [|x l1' IHl1'].\nAdmitted.\n\n\nDefinition manual_grade_for_check_repeats : option (nat*string) := None.\n\n\n\n\n\n\n\n\nRequire Export Coq.Strings.Ascii.\n\nDefinition string := list ascii.\n\n\n\n\n\n\nLemma provable_equiv_true : forall (P : Prop), P -> (P <-> True).\nProof. hammer_hook \"IndProp\" \"IndProp.provable_equiv_true\".\nintros.\nsplit.\n- intros. constructor.\n- intros _. apply H.\nQed.\n\n\nLemma not_equiv_false : forall (P : Prop), ~P -> (P <-> False).\nProof. hammer_hook \"IndProp\" \"IndProp.not_equiv_false\".\nintros.\nsplit.\n- apply H.\n- intros. destruct H0.\nQed.\n\n\nLemma null_matches_none : forall (s : string), (s =~ EmptySet) <-> False.\nProof. hammer_hook \"IndProp\" \"IndProp.null_matches_none\".\nintros.\napply not_equiv_false.\nunfold not. intros. inversion H.\nQed.\n\n\nLemma empty_matches_eps : forall (s : string), s =~ EmptyStr <-> s = [ ].\nProof. hammer_hook \"IndProp\" \"IndProp.empty_matches_eps\".\nsplit.\n- intros. inversion H. reflexivity.\n- intros. rewrite H. apply MEmpty.\nQed.\n\n\nLemma empty_nomatch_ne : forall (a : ascii) s, (a :: s =~ EmptyStr) <-> False.\nProof. hammer_hook \"IndProp\" \"IndProp.empty_nomatch_ne\".\nintros.\napply not_equiv_false.\nunfold not. intros. inversion H.\nQed.\n\n\nLemma char_nomatch_char :\nforall (a b : ascii) s, b <> a -> (b :: s =~ Char a <-> False).\nProof. hammer_hook \"IndProp\" \"IndProp.char_nomatch_char\".\nintros.\napply not_equiv_false.\nunfold not.\nintros.\napply H.\ninversion H0.\nreflexivity.\nQed.\n\n\nLemma char_eps_suffix : forall (a : ascii) s, a :: s =~ Char a <-> s = [ ].\nProof. hammer_hook \"IndProp\" \"IndProp.char_eps_suffix\".\nsplit.\n- intros. inversion H. reflexivity.\n- intros. rewrite H. apply MChar.\nQed.\n\n\nLemma app_exists : forall (s : string) re0 re1,\ns =~ App re0 re1 <->\nexists s0 s1, s = s0 ++ s1 /\\ s0 =~ re0 /\\ s1 =~ re1.\nProof. hammer_hook \"IndProp\" \"IndProp.app_exists\".\nintros.\nsplit.\n- intros. inversion H. exists s1, s2. split.\n* reflexivity.\n* split. apply H3. apply H4.\n- intros [ s0 [ s1 [ Happ [ Hmat0 Hmat1 ] ] ] ].\nrewrite Happ. apply (MApp s0 _ s1 _ Hmat0 Hmat1).\nQed.\n\n\nLemma app_ne : forall (a : ascii) s re0 re1,\na :: s =~ (App re0 re1) <->\n([ ] =~ re0 /\\ a :: s =~ re1) \\/\nexists s0 s1, s = s0 ++ s1 /\\ a :: s0 =~ re0 /\\ s1 =~ re1.\nProof. hammer_hook \"IndProp\" \"IndProp.app_ne\".\nAdmitted.\n\n\n\nLemma union_disj : forall (s : string) re0 re1,\ns =~ Union re0 re1 <-> s =~ re0 \\/ s =~ re1.\nProof. hammer_hook \"IndProp\" \"IndProp.union_disj\".\nintros. 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\n\nLemma star_ne : forall (a : ascii) s re,\na :: s =~ Star re <->\nexists s0 s1, s = s0 ++ s1 /\\ a :: s0 =~ re /\\ s1 =~ Star re.\nProof. hammer_hook \"IndProp\" \"IndProp.star_ne\".\nAdmitted.\n\n\n\nDefinition refl_matches_eps m :=\nforall re : @reg_exp ascii, reflect ([ ] =~ re) (m re).\n\n\nFixpoint match_eps (re: @reg_exp ascii) : bool\n. Admitted.\n\n\n\nLemma match_eps_refl : refl_matches_eps match_eps.\nProof. hammer_hook \"IndProp\" \"IndProp.match_eps_refl\".\nAdmitted.\n\n\n\n\n\n\nDefinition is_der re (a : ascii) re' :=\nforall s, a :: s =~ re <-> s =~ re'.\n\n\nDefinition derives d := forall a re, is_der re a (d a re).\n\n\nFixpoint derive (a : ascii) (re : @reg_exp ascii) : @reg_exp ascii\n. Admitted.\n\n\n\nExample c := ascii_of_nat 99.\nExample d := ascii_of_nat 100.\n\n\nExample test_der0 : match_eps (derive c (EmptySet)) = false.\nProof. hammer_hook \"IndProp\" \"IndProp.test_der0\".\nAdmitted.\n\n\nExample test_der1 : match_eps (derive c (Char c)) = true.\nProof. hammer_hook \"IndProp\" \"IndProp.test_der1\".\nAdmitted.\n\n\nExample test_der2 : match_eps (derive c (Char d)) = false.\nProof. hammer_hook \"IndProp\" \"IndProp.test_der2\".\nAdmitted.\n\n\nExample test_der3 : match_eps (derive c (App (Char c) EmptyStr)) = true.\nProof. hammer_hook \"IndProp\" \"IndProp.test_der3\".\nAdmitted.\n\n\nExample test_der4 : match_eps (derive c (App EmptyStr (Char c))) = true.\nProof. hammer_hook \"IndProp\" \"IndProp.test_der4\".\nAdmitted.\n\n\nExample test_der5 : match_eps (derive c (Star (Char c))) = true.\nProof. hammer_hook \"IndProp\" \"IndProp.test_der5\".\nAdmitted.\n\n\nExample test_der6 :\nmatch_eps (derive d (derive c (App (Char c) (Char d)))) = true.\nProof. hammer_hook \"IndProp\" \"IndProp.test_der6\".\nAdmitted.\n\n\nExample test_der7 :\nmatch_eps (derive d (derive c (App (Char d) (Char c)))) = false.\nProof. hammer_hook \"IndProp\" \"IndProp.test_der7\".\nAdmitted.\n\n\nLemma derive_corr : derives derive.\nProof. hammer_hook \"IndProp\" \"IndProp.derive_corr\".\nAdmitted.\n\n\n\n\n\nDefinition matches_regex m : Prop :=\nforall (s : string) re, reflect (s =~ re) (m s re).\n\n\nFixpoint regex_match (s : string) (re : @reg_exp ascii) : bool\n. Admitted.\n\n\n\nTheorem regex_refl : matches_regex regex_match.\nProof. hammer_hook \"IndProp\" \"IndProp.regex_refl\".\nAdmitted.\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/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.6842925511296667}}
{"text": "Require Import Relations.\n\n(* Basic definitions and properties for relations, and relation equivalence *)\nDefinition rel_eq (A : Type) (R R' : relation A):= forall (x y : A), R x y <-> R' x y.\n\nLemma rel_eq_eq : forall (A :Type) (R : relation A), rel_eq A R R.\nintros. intros x y. split; auto.\nQed.\n\n\n\nLemma rel_eq_fun : forall (A : Type) (R R': relation A), rel_eq A R R' -> rel_eq A R (fun x y => R' x y).\nintros. intros x y. split;apply H.\nQed.\n\n\n\nDefinition rel_comp (A : Type) (R R' : relation A) : relation A := fun x y => exists z, R x z /\\ R' z y.\n\n\nLemma rel_eq_comp : forall (A : Type) (R R' R0 R0' : relation A), rel_eq A R R0 -> rel_eq A R' R0' -> rel_eq A (rel_comp A R R') (rel_comp A R0 R0').\nintros A R1 R2 R1' R2' re re'. intros x y. split; intro rc; induction rc as [z s]. \n+ exists z. split; [apply re|apply re']; apply s.\n+ exists z. split; [apply re|apply re']; apply s.\nQed.\n\n\nLemma rel_eq_sym : forall (A : Type) R R', rel_eq A R R' -> rel_eq A R' R.\nintros. intros x y. split; apply H.\nQed.\n\n(* Diagrams over relations: usefull for defining and reasoning about (strong or weak) bisimulations and bisimilarities *)\nSection Diagrams.\nVariable X : Type.\nVariable R : relation X.\nVariable T1 : relation X.\nVariable T2 : relation X.\nVariable R' : relation X.\n\nDefinition diagram := forall (x y z : X), R x y -> T1 x z -> exists z', T2 y z' /\\ R' z z'.\n\nEnd Diagrams.\n\n\n\nLemma diag_comp_trans : forall (A : Type) (R T T': relation A), diagram A R T T' R -> diagram A R (clos_trans A T) (clos_trans A T') R.\nintros A R T T' diag.\nintros x y z r tr.\nrevert r; revert y.\ninduction tr as [x z  t|x x' x'']; intros y r.\n+ edestruct diag as [z' s]; try eassumption.\n  exists z'.\n  split; [constructor|]; apply s.\n+ destruct (IHtr1 y r) as [y' hy'].\n  destruct (IHtr2 y') as [y'' hy'']; [apply hy'|].\n  exists y''.\n  split; [|apply hy''].\n  apply t_trans with y'.\n  apply hy'. apply hy''.\nQed.\n\nLemma diag_comp_rt : forall (A : Type) (R T T': relation A), diagram A R T T' R -> diagram A R (clos_refl_trans A T) (clos_refl_trans A T') R.\nintros A R T T' diag.\nintros x y z r tr.\nrevert r; revert y.\ninduction tr as [x z t| |x x' x'']; intros y r.\n+ edestruct diag as [z' s]; try eassumption.\n  exists z'.\n  split; [constructor|]; apply s.\n+ exists y. split; [|assumption]. apply rt_refl.\n+ destruct (IHtr1 y r) as [y' hy'].\n  destruct (IHtr2 y') as [y'' hy'']; [apply hy'|].\n  exists y''.\n  split; [|apply hy''].\n  apply rt_trans with y'.\n  apply hy'. apply hy''.\nQed.\n\nLemma diag_compose : forall (A : Type) (R T1 T2 R' T1' T2' R'' : relation A),\n diagram A R T1 T2 R' -> diagram A R' T1' T2' R'' \n -> diagram A R (rel_comp A T1 T1') (rel_comp A T2 T2') R''.\nintros A R T1 T2 R' T1' T2' R'' d1 d2.\nintros x y z r rc.\ndestruct rc as [x' s]; destruct s as [t1 t1'].\ndestruct (d1 x y x' r t1) as [y' s]; destruct s as [t2 r'].\ndestruct (d2 x' y' z r' t1') as [y'' s]; destruct s as [t2' r''].\nexists y''; split; [|apply r''].\nexists y'. split; assumption.\nQed. \n\nSection RevDiagrams.\nVariable X : Type.\nVariable R : relation X.\nVariable T1 : relation X.\nVariable T2 : relation X.\nVariable R' : relation X.\nDefinition rev_diagram := diagram X (transp X R) T1 T2 (transp X R').\n\nEnd RevDiagrams.\n\n\nArguments diagram [_] _ _ _ _.\nArguments rev_diagram [_] _ _ _ _.\n\nSection SymDiagrams.\nVariable X : Type.\nVariable R : relation X.\nVariable T1 : relation X.\nVariable T2 : relation X.\nVariable R' : relation X.\nDefinition sym_diagram := diagram R T1 T2 R' /\\ rev_diagram R T1 T2 R'.\nEnd SymDiagrams.\n\nArguments sym_diagram [_] _ _ _ _.\n\n\n(* Basic properties of diagrams and relations closures *)\n\nLemma equiv_diag : forall (A : Type) (R1 T1 T2 R2 R1' T1' T2' R2' : relation A), rel_eq A R1 R1' -> rel_eq A T1 T1' -> rel_eq A T2 T2' -> rel_eq A R2 R2' -> diagram R1 T1 T2 R2 -> diagram R1' T1' T2' R2'.\nintros. intros x y z h h'. destruct (H3 x y z). apply H. apply h. apply H0. apply h'. exists x0. split.\napply H1. apply H4. apply H2. apply H4. Qed.\n\n\n\n\nLemma trans_trans_eq : forall (A : Type) (R : relation A), rel_eq A (clos_trans A R) (clos_trans A (clos_trans A R)).\nintros. intros x y. split; intro h.\n+ constructor; assumption.\n+ induction h.\n  - apply H.\n  - eapply t_trans; eassumption.\nQed.\n\n\nLemma trans_trans_eq2 : forall (A : Type) (R : relation A), rel_eq A (clos_trans A (clos_trans A R)) (clos_trans A R).\nintros. intros x y. split; intro h.\n+ induction h.\n  - apply H.\n  - eapply t_trans; eassumption.\n+ constructor; assumption.\nQed.\n\n\n\nLemma trans_trans_refl_eq2 : forall (A : Type) (R : relation A), rel_eq A (clos_trans A (clos_refl_trans A R)) (clos_refl_trans A R).\nintros. intros x y. split; intro h.\n+ induction h.\n  - induction H. constructor; apply H. apply rt_refl. eapply rt_trans. apply IHclos_refl_trans1. apply IHclos_refl_trans2.\n  - eapply rt_trans; eassumption. \n+ induction h.\n  - constructor. constructor. assumption.\n  - apply t_step. apply rt_refl.\n  - eapply t_trans; eassumption. \nQed.\n\nLemma trans_refl_trans_refl_eq2 : forall (A : Type) (R : relation A), rel_eq A (clos_refl_trans A (clos_refl_trans A R)) (clos_refl_trans A R).\nintros. intros x y. split; intro h.\n+ induction h.\n  - induction H. constructor; apply H. apply rt_refl. eapply rt_trans. apply IHclos_refl_trans1. apply IHclos_refl_trans2.\n  - apply rt_refl.\n  - eapply rt_trans; eassumption. \n+ induction h.\n  - constructor. constructor. assumption.\n  - apply rt_step. apply rt_refl.\n  - eapply rt_trans; eassumption. \nQed.\n\n\nLemma weaker_refl_trans : forall (A : Type) (R R' : relation A), (forall x y, R x y -> R' x y) -> forall x y, clos_refl_trans A R x y -> clos_refl_trans A R' x y.\nintros A R R' h x y h'.\ninduction h' as [x y h' | | ].\n+ constructor. apply (h x y h').\n+ eapply rt_refl.\n+ eapply rt_trans with y; assumption.\nQed.\n\n\n\n", "meta": {"author": "adurier", "repo": "uniquesolution", "sha": "18999bdb903d883b0719468abfcfbc638cb74499", "save_path": "github-repos/coq/adurier-uniquesolution", "path": "github-repos/coq/adurier-uniquesolution/uniquesolution-18999bdb903d883b0719468abfcfbc638cb74499/source/rels.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.6842661813517755}}
{"text": "Require Import PeanoNat.\nRequire Import List.\nRequire Import Coq.omega.Omega.\nRequire Import FiatHelpers.\n\nSection ListHelpers.\n  Lemma nth_default_0: forall A: Type, forall a b : A, forall l: list A, \n        nth_default b (a::l) 0 = a.\n  Proof. \n    intros a l. \n    reflexivity. \n  Qed. \n\n  Lemma nth_default_nil: forall A: Type, forall b : A, forall i, \n          nth_default b nil i = b.\n  Proof. \n    intros A0. intros b. intros i. \n    unfold nth_default. \n    unfold nth_error. \n    destruct i. \n    - reflexivity. \n    - reflexivity. \n  Qed. \n\n  Lemma nth_default_S: forall A: Type, forall a b : A, forall l: list A, forall i, \n            nth_default b (a :: l) (S i) = nth_default b l i.\n  Proof. \n    intros A0 a b l i. \n    unfold nth_default. \n    unfold nth_error. \n    reflexivity. \n  Qed. \n\n\n  Lemma nth_default_map : forall A B X d d0 i, forall f: A -> B, \n        f (d) = d0 -> nth_default d0 (map f X) i =  f (nth_default d X i). \n  Proof. \n    intros A B X.  \n    induction X as [| v X IHX]. \n    - intros d d0 i0 f H. simpl. rewrite nth_default_nil. rewrite nth_default_nil. rewrite H. reflexivity. \n    - intros d d0 i0 f H. destruct i0. \n      + rewrite nth_default_0. simpl. rewrite nth_default_0. reflexivity. \n      + rewrite nth_default_S. simpl. rewrite nth_default_S. apply IHX. \n        apply H.\n  Qed.\n\n  Lemma nth_default_map_in_range : forall A B X d d0 i, forall f: A -> B, \n        i < length X -> nth_default d0 (map f X) i =  f (nth_default d X i). \n  Proof. \n    intros A B X.  \n    induction X as [| v X IHX]. \n    - intros d d0 i0 f H. inversion H. \n    - intros d d0 i0 f H. destruct i0. \n      + rewrite nth_default_0. simpl. rewrite nth_default_0. reflexivity. \n      + rewrite nth_default_S. simpl. rewrite nth_default_S. apply IHX. \n        simpl in H. omega. \n  Qed.\nEnd ListHelpers.\n\nLtac elim_bool:=\n  repeat match goal with\n         | [ |- context [Nat.eqb ?x ?y]] => let eq := fresh \"eq\" in destruct (x =? y) eqn: eq\n         | [H: ?x =? ?y = false |- _] => apply Nat.eqb_neq in H\n         | [H: ?x =? ?y = true |- _] => apply Nat.eqb_eq in H\n         | [H: ?x <? ?y = true |- _] => apply Nat.ltb_lt in H\n         | [H: ?x <? ?y = false |- _] => apply Nat.ltb_ge in H\n         | [H: ?x <=? ?y = true |- _] => apply Nat.leb_le in H\n         | [H: ?x <=? ?y = false |- _] => apply Nat.leb_gt in H\n         end.\n\nLtac is_variable A :=\n  match goal with\n  | [ B :_ |- _] =>\n    let eq := fresh \"eq\" in\n    assert (eq: A = B) by auto; clear eq\n  end.\n\nLtac is_constant a :=\n  let a := (eval compute in a) in\n  assert (a = a) by\n      (clear;\n       lazymatch goal with\n       | [ H: _ |- _ ] => fail \"NC\"\n       | _ => idtac\n       end;\n       reflexivity).\n\nLtac is_function a :=\n  let b := type of (a) in\n  match b with\n  | ?A -> ?B => idtac\n  end.\n\nLtac separable a := \n  tryif (is_constant a) then fail 0 \n  else tryif (is_variable a) then fail 0           \n    else tryif (is_function a) then fail 0\n      else idtac.\n\nLtac reveal_body_evar :=\n  match goal with\n  | [ H := ?x : methodType _ _ _ |- _ ] => is_evar x; progress unfold H\n                                                             (* | [ H := ?x : constructorType _ _ |- _ ] => is_evar x; progress unfold H *)\n  end.\n    \nLtac cleanup :=\n  repeat match goal with\n         | [ H: _ /\\ _ |- _ ] => destruct H\n         | _ => progress subst\n         | _ => progress (cbv iota)\n         | _ => progress simpl\n         | _ => simplify with monad laws\n         end.\n\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/MyHelpers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451416, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6842661733241318}}
{"text": "(* ***************************************************************** *)\n(*                                                                   *)\n(* Released: 2020/05/29.                                             *)\n(* Due: 2020/06/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 (Assignment9.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 \"Assignment9.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.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\nRequire Import PL.ImpExt4.\nRequire Import PL.Lambda.\n\n(* ################################################################# *)\n(** * Task 1: Mix Typed Expressions *)\n\nModule Task1.\nLocal Open Scope Z.\n\n(** This is our definition of mix typed expressions. In this task, you need to\n    answer questions about their evaluation process and type checking results. *)\n\nDefinition var: Type := nat.\n\nDefinition state: Type := var -> Z.\n\nInductive mexp : Type :=\n  | MNum (n : Z)\n  | MId (X : var)\n  | MPlus (a1 a2 : mexp)\n  | MMinus (a1 a2 : mexp)\n  | MMult (a1 a2 : mexp)\n  | MTrue\n  | MFalse\n  | MEq (a1 a2 : mexp)\n  | MLe (a1 a2 : mexp)\n  | MNot (b : mexp)\n  | MAnd (b1 b2 : mexp)\n.\n\n(** Here is some coercion and notations for pretty printing. *)\n\nDeclare Scope mexp.\nDelimit Scope mexp with mexp.\nLocal Open Scope mexp.\n\nCoercion MNum : Z >-> mexp.\nCoercion MId : var >-> mexp.\nNotation \"x + y\" := (MPlus x y) (at level 50, left associativity) : mexp.\nNotation \"x - y\" := (MMinus x y) (at level 50, left associativity) : mexp.\nNotation \"x * y\" := (MMult x y) (at level 40, left associativity) : mexp.\nNotation \"x <= y\" := (MLe x y) (at level 70, no associativity) : mexp.\nNotation \"x == y\" := (MEq x y) (at level 70, no associativity) : mexp.\nNotation \"x && y\" := (MAnd x y) (at level 40, left associativity) : mexp.\nNotation \"'!' b\" := (MNot b) (at level 39, right associativity) : mexp.\nNotation \"[ x ; .. ; y ]\" := (@cons mexp x .. (@cons mexp y (@nil mexp)) ..).\n\nModule Task1_Examples.\n\nParameter X: var.\nParameter S: var.\n  \n(** Suppose [X] and [S] are program variables and [st: state] satisfies:\n\n    - [st X = 0]\n\n    - [st S = 0].\n\n    Please describe the evaluation process of\n\n    - [S + (X == 0)]\n\n    on [st] using a Coq list. Specifically, this Coq list must demonstrate the\n    result of every step (see lecture notes: run time error 2) from the\n    beginning to the end. The ending expression can be a evaluation result (an\n    integer constant or a boolean constant) or a stuck state (no step can be\n    taken since an error occurs).\n*)\n\nDefinition my_answer_1: list mexp :=\n  [ S + (X == 0);\n    0 + (X == 0);\n    0 + (0 == 0);\n    0 + MTrue;\n    0 + 1;\n    1 ]\n.\n\n(** Suppose [X] and [S] are program variables and [st: state] satisfies:\n\n    - [st X = 0]\n\n    - [st S = 0].\n\n    Please describe the evaluation process of\n\n    - [S && (X == 0)]\n\n    on [st] using a Coq list. Specifically, this Coq list must demonstrate the\n    result of every step (see lecture notes: run time error 2) from the\n    beginning to the end. The ending expression can be a evaluation result (an\n    integer constant or a boolean constant) or a stuck state (no step can be\n    taken since an error occurs).\n*)\n\nDefinition my_answer_2: list mexp :=\n  [ S && (X == 0);\n    0 && (X == 0) ]\n.\n\nEnd Task1_Examples.\n\n(** **** Exercise: 2 stars, standard  *)\n\nParameter P: var.\nParameter X: var.\n\n(** Suppose [P] and [X] are program variables and [st: state] satisfies:\n\n    - [st P = 0]\n\n    - [st X = 1].\n\n    Please describe the evaluation process of\n\n    - [(P == 0) && (X && (X + 1))]\n\n    on [st] using a Coq list. Specifically, this Coq list must demonstrate the\n    result of every step (see lecture notes: run time error 2) from the\n    beginning to the end. The ending expression can be a evaluation result (an\n    integer constant or a boolean constant) or a stuck state (no step can be\n    taken since an error occurs).\n*)\n\nDefinition my_answer_1_1: list mexp := \n  [(P == 0) && (X && (X + 1));\n   (0 == 0) && (X && (X + 1));\n   MTrue && (X && (X + 1));\n   X && (X + 1);\n   1 && (X + 1)].\n(** [] *)\n\n(** **** Exercise: 2 stars, standard  *)\n\n(** This time, consider a slightly different situation. Suppose [st: state]\n    satisfies:\n\n    - [st P = 1]\n\n    - [st X = 1].\n\n    Please describe the evaluation process of\n\n    - [(P == 0) && (X && (X + 1))]\n\n    on [st] using a Coq list. Specifically, this Coq list must demonstrate the\n    result of every step (see lecture notes: run time error 2) from the\n    beginning to the end. The ending expression can be a evaluation result (an\n    integer constant or a boolean constant) or a stuck state (no step can be\n    taken since an error occurs).\n*)\n\nDefinition my_answer_1_2: list mexp :=\n  [(P == 0) && (X && (X + 1));\n   (1 == 0) && (X && (X + 1));\n   MFalse && (X && (X + 1));\n   MFalse].\n(** [] *)\n\n(** **** Exercise: 1 star, standard  *)\n\n(** Does [(P == 0) && (X && (X + 1))] type check?\n    1. Yes. 2. No.\n*)\n\nDefinition my_answer_1_3: Z := 2.\n(** [] *)\n\n(** **** Exercise: 1 star, standard  *)\n\n(** Does [(P == 0) && (P == 1) && (X && (X + 1))] type check?\n    1. Yes. 2. No.\n*)\n\nDefinition my_answer_1_4: Z := 2.\n(** [] *)\n\nImport ListNotations.\n\n(** **** Exercise: 1 star, standard  *)\n\n(** Which of the following statements are correct about [mexp]'s small step\n    semantics and type checking function?\n\n    1. Its semantics is type safe since it has the progress property and\n       the preservation property.\n\n    2. Every legal expression (according the type checking function) can be\n       evaluated safely to the end on any program state and the evaluation\n       process will either end in an integer constant or a boolean constant.\n\n    3. If an expression [m: mexp] can be safely evaluated on a state [st],\n       then [m] must be a well-typed expression.\n\n    4. If an expression [m: mexp] can be safely evaluated on any state [st],\n       then [m] must be a well-typed expression.\n\n    This is a multiple-choice problem. You should use an ascending Coq list to\n    describe your answer, e.g. [1; 2; 3], [1; 3], [2]. *)\n\nDefinition my_answer_1_5: list Z := [1;2].\n(** [] *)\n\nEnd Task1.\n\n(* ################################################################# *)\n(** * Task 2: Lambda Expressions *)\n\nModule Task2.\nImport LambdaIB.\nLocal Open Scope Z.\nLocal Open Scope string.\nNotation \"[ x ; .. ; y ]\" := (@cons tm x .. (@cons tm y (@nil tm)) ..).\n\n(** **** Exercise: 2 stars, standard  *)\n\n(** Please describe the evaluation process of\n\n    - [app\n         (app\n            (abs \"f\" (abs \"x\" (app \"f\" \"x\")))\n            (abs \"x\" (app (app Omult \"x\") \"x\")))\n         2].\n\n    If writing this expression in python, it is:\n\n    - [(lambda f: lambda x: f (x)) (lambda x: x * x) (2)].\n\n*)\n\nDefinition process_2_1: list tm :=\n  [app\n     (app\n        (abs \"f\" (abs \"x\" (app \"f\" \"x\")))\n        (abs \"x\" (app (app Omult \"x\") \"x\")))\n     2;\n  (app\n     (abs \"x\" (app (abs \"x\" (app (app Omult \"x\") \"x\")) \"x\"))\n     2);\n   app (abs \"x\" (app (app Omult \"x\") \"x\")) 2;\n   app (app Omult 2) 2;\n   4].\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard  *)\n\n(** Now you know the evaluation result is 4. Please prove it in Coq. *)\n\nExample result_2_1:\n  clos_refl_trans step\n    (app\n       (app (abs \"f\" (abs \"x\" (app \"f\" \"x\")))\n            (abs \"x\" (app (app Omult \"x\") \"x\")))\n       2)\n    4.\nProof.\n  etransitivity_1n.\n  { apply S_app1. apply S_beta. constructor. }\n  simpl subst. etransitivity_1n.\n  { apply S_beta. constructor. }\n  simpl subst. etransitivity_1n.\n  { apply S_beta. constructor. }\n  simpl subst. etransitivity_1n.\n  { apply S_base. constructor. }\n  reflexivity. \nQed. \n(** [] *)\n\n(** **** Exercise: 1 star, standard  *)\n\n(** We usually call [ abs \"f\" (abs \"x\" (app \"f\" \"x\")) ] the \"apply\" function. In\n    other words, it APPLIES function \"f\" on \"x\". Please prove that it is\n    well-typed. *)\n\nExample type_2_1: forall T1 T2: ty,\n  empty_context |-\n    (abs \"f\" (abs \"x\" (app \"f\" \"x\"))) \\in ((T1 ~> T2) ~> T1 ~> T2).\nProof.\n  intros.\n  apply T_abs.\n  apply T_abs.\n  eapply T_app;apply T_var;reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, standard  *)\n\n(** Please describe the evaluation process of\n\n    - [app\n         (abs \"x\"\n            (app (app (app Oifthenelse (app (app Oeq \"x\") 0)) 0) 1))\n         2].\n\n    If writing this expression in Coq, it is like:\n\n    - [ (fun x => if x ?= 0 then 0 else 1) 2 ].\n\n*)\n\nDefinition process_2_2: list tm :=\n  [app\n     (abs \"x\"\n        (app (app (app Oifthenelse (app (app Oeq \"x\") 0)) 0) 1))\n     2;\n   app (app (app Oifthenelse (app (app Oeq 2) 0)) 0) 1;\n   app (app (app Oifthenelse false) 0) 1;\n   1 ].\n(** [] *)\n\n(** **** Exercise: 2 stars, standard  *)\n\n(** In the example above, the function\n\n    - [ abs \"x\" (app (app (app Oifthenelse (app (app Oeq \"x\") 0)) 0) 1) ]\n\n    is usually called the \"test_zero\" function. If it applies to zero, the\n    result is zero. If it applies to non-zero, the result is one. Of course,\n    it has type [TInt ~> TInt]. But, if you write it in a wrong way, you can\n    easily make it ill-typed. For example, the following expression writes:\n    if \"x\" is non-zero, return false instead of one. This must cause a chaos\n    in types.\n\n    Hint: in order to prove the following property, you need to use [inversion]\n    to trace back through the type derivation. You may use\n\n    - [deduce_types_from_head]\n\n    to speed up. But it will only solve parts, but not all, of the problem. *)\n\nLemma ill_typed_example: forall Gamma T,\n  Gamma |-\n    abs \"x\" (app (app (app Oifthenelse (app (app Oeq \"x\") 0)) 0) false) \\in T ->\n  False.\nProof.\n  intros.\n  inversion H;subst.\n  deduce_types_from_head H4.\n  inversion H3;subst.\n  inversion H1;subst.\n  inversion H5;subst.\n  inversion H7.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard  *)\n\n(** It is a nice property that the small step semantics of lambda expressions\n    (as we introduced in lectures) are type safe. In other words, for any\n    [t: tm] and [T: ty], if\n\n    - [empty_context |- t \\in T]\n\n    then evaluating [t] must be safe. But, is the reverse direction also true?\n    In other words, is there such an expression [t] that evaluating [t] is safe\n    but no type [T] makes [empty_context |- t \\in T] true.\n\n    1. There exists such [t].\n\n    2. There does not exist such [t]. *)\n\nDefinition my_choice: Z := 1.\n(** [] *)\n\n(** You should start your proof with either one of the following:\n\n    - [ left; split; [reflexivity |] ]\n\n    - [ right; reflexivity ]\n\n*)\n\nLemma reverse_of_type_safe:\n  (my_choice = 1 /\\\n   exists t t', clos_refl_trans step t t' /\\ tm_halt t' /\\\n                (forall T, empty_context |- t \\in T -> False)) \\/\n  (my_choice = 2).\nProof.\n  left; split; [reflexivity |].\n  exists (app\n            (abs \"x\" (app (app (app Oifthenelse (app (app Oeq \"x\") 0)) 0) false))\n            5), false.\n  repeat split;[|constructor|].\n  - etransitivity_1n.\n    { apply S_beta. constructor. }\n    simpl subst. etransitivity_1n.\n    { apply S_app1. apply S_app1.\n      apply S_app2. constructor.\n      apply S_base. apply BS_eq_false. omega. }\n    etransitivity_1n.\n    { apply S_base. apply BS_if_false. }\n    reflexivity.\n  - intros. inversion H;subst.\n    apply (ill_typed_example _ _ H3).\nQed.\n\nEnd Task2.\n\n(* Fri May 29 22:59:47 CST 2020 *)\n", "meta": {"author": "ltzone", "repo": "2020Spring", "sha": "bc7fdf60850c81d77825cdcc77a1ad265da98f11", "save_path": "github-repos/coq/ltzone-2020Spring", "path": "github-repos/coq/ltzone-2020Spring/2020Spring-bc7fdf60850c81d77825cdcc77a1ad265da98f11/CS263/Assignment9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.6842661692928725}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Lia.\n\nFrom Undecidability.Shared.Libs.DLW.Utils\n  Require Import utils_tac utils_list utils_nat \n                 fin_base.\n\nFrom Undecidability.Shared.Libs.DLW.Vec\n  Require Import pos vec.\n\nSet Implicit Arguments.\n\n(* This files gathers all constructivelly valid choice principles *)\n\n(* This is standart constructive strong choice, no finiteness assumptions here *)\n\nTheorem constructive_choice X (T : X -> Type) (R : forall x, T x -> Prop) :\n          (forall x, sig (R x)) \n       -> { f : forall x, T x | forall x, R x (f x) }.\nProof.\n  intros f.\n  exists (fun x => proj1_sig (f x)).\n  intros x; apply (proj2_sig (f x)).\nQed.\n\nTheorem constructive_choice' X Y (R : X -> Y -> Prop) :\n          (forall x, sig (R x)) \n       -> { f | forall x, R x (f x) }.\nProof.\n  apply constructive_choice.\nQed.\n\nTheorem constructive_dep_choice X Y (P : X -> Prop) (R : X -> Y -> Prop) :\n          (forall x, P x -> sig (R x)) \n       -> { f : forall x, P x -> Y | forall x Hx, R x (f x Hx) }.\nProof.\n  intros f.\n  exists (fun x Hx => proj1_sig (f x Hx)).\n  intros x Hx; apply (proj2_sig (f x Hx)).\nQed.\n\nFact list_reif_t X Y (R : X -> Y -> Prop) l :\n          (forall x, In x l -> sig (R x)) \n       -> { f | forall x (Hx : In x l), R x (f x Hx) }.\nProof. apply constructive_dep_choice. Qed.\n\nFact pos_reif_t X n (R : pos n -> X -> Prop) : (forall p, { x | R p x }) -> { f | forall p, R p (f p) }.\nProof. apply constructive_choice. Qed.\n\nFact vec_reif_t X n (R : pos n -> X -> Prop) : (forall p, sig (R p)) -> { v | forall p, R p (vec_pos v p) }.\nProof.\n  intros H.\n  apply pos_reif_t in H.\n  destruct H as (f & Hf).\n  exists (vec_set_pos f).\n  intro; rewrite vec_pos_set; trivial.\nQed.\n\n(* Now weak choice principles that assume some finiteness and discreteness *)\n\nSection finite_discrete_choice.\n\n  Variable (X Y : Type) (R : X -> Y -> Prop) \n           (X_discrete : forall x y : X, { x = y } + { x <> y }).\n    \n  Theorem list_discrete_choice l :\n            (forall x, In x l -> ex (R x))\n         -> exists f, forall x (Hx : In x l), R x (f x Hx).\n  Proof using X_discrete.\n    induction l as [ | x l IHl ]; intros Hl.\n    + exists (fun x (Hx : @In X x nil) => False_rect Y Hx).\n      intros _ [].\n    + destruct (Hl x) as (y & Hy); simpl; auto.\n      destruct IHl as (f & Hf).\n      * intros; apply Hl; simpl; auto.\n      * assert (forall z, In z (x::l) -> x <> z -> In z l) as H1.\n        { intros z [ -> | ] ?; tauto. }\n        exists (fun z Hz => \n          match X_discrete x z with\n            | left   _ => y\n            | right  H => f z (H1 _ Hz H)\n          end).\n        intros z Hz.\n        destruct (X_discrete x z); subst; auto.\n  Qed.\n\n  Fact finite_discrete_choice :\n         finite X \n      -> (forall x, ex (R x)) -> exists f, forall x, R x (f x).\n  Proof using X_discrete.\n    intros (l & Hl) H.\n    destruct list_discrete_choice with (l := l) as (f & Hf); auto.\n    exists (fun x => f x (Hl x)); auto.\n  Qed.\n\nEnd finite_discrete_choice.\n\nLocal Hint Resolve finite_t_pos finite_t_finite : core.\n \nFact pos_reification X n (R : pos n -> X -> Prop) : (forall p, exists x, R p x) -> exists f, forall p, R p (f p).\nProof.\n  apply finite_discrete_choice; auto.\n  apply pos_eq_dec.\nQed.\n\nNotation pos_reif := pos_reification.\n\nFact vec_reif X n (R : pos n -> X -> Prop) : (forall p, ex (R p)) -> exists v, forall p, R p (vec_pos v p).\nProof.\n  intros H.\n  apply pos_reification in H.\n  destruct H as (f & Hf).\n  exists (vec_set_pos f).\n  intro; rewrite vec_pos_set; trivial.\nQed.\n\nSection finite_t_dec_choose_one.\n\n  (* This compares to Constructive Epsilon but here over a finite type\n      instead of nat *) \n\n  Variable (X : Type) (P Q : X -> Prop) \n           (HX : finite_t X)\n           (HQ : fin_t Q)\n           (Pdec : forall x, { P x } + { ~ P x }).\n\n  Fact list_dec_choose_one l : (exists x, In x l /\\ P x) -> { x | In x l /\\ P x }.\n  Proof using Pdec.\n    clear HX Q HQ.\n    induction l as [ | x l IHl ]; intros H.\n    + exfalso; destruct H as (_ & [] & _).\n    + destruct (Pdec x) as [ H1 | H1 ].\n      * exists x; simpl; auto.\n      * destruct IHl as (y & H2 & H3).\n        - destruct H as (y & [ -> | Hy ] & ?); firstorder.\n        - exists y; simpl; auto.\n  Qed.\n \n  Fact fin_t_dec_choose_one : \n         (exists x, Q x /\\ P x) -> { x | Q x /\\ P x }.\n  Proof using HQ Pdec.\n    revert HQ; intros (l & Hl) H.\n    destruct (list_dec_choose_one l) as (x & H1 & H2).\n    + destruct H as (x & ? & ?); exists x; rewrite <- Hl; auto.\n    + exists x; rewrite Hl; auto.\n  Qed.\n\n  Fact finite_t_dec_choose_one : ex P -> sig P. \n  Proof using HX Pdec.\n    clear Q HQ.\n    revert HX; intros (l & Hl) H.\n    destruct (list_dec_choose_one l) as (x & H1 & H2); firstorder.\n  Qed.\n\nEnd finite_t_dec_choose_one.\n\n(* Reification of a total relation into a function,\n    ie this is relational choice over a finite co-domain\n    with a decidable relation *)\n\nDefinition finite_t_dec_choice X Y (R : X -> Y -> Prop) :\n        finite_t Y\n     -> (forall x y, { R x y } + { ~ R x y })\n     -> (forall x, ex (R x))\n     -> { f | forall x, R x (f x) }.\nProof.\n  intros H2 H1 H3.\n  exists (fun x => proj1_sig (finite_t_dec_choose_one H2 (H1 x) (H3 x))).\n  intros x; apply (proj2_sig (finite_t_dec_choose_one H2 (H1 x) (H3 x))).\nQed.\n\nFact pos_dec_reif n (P : pos n -> Prop) (HP : forall p, { P p } + { ~ P p }) : ex P -> sig P.\nProof. apply finite_t_dec_choose_one; auto. Qed.\n\n(* This is needed to reify a computable binary relation representing a unary function\n    into an actual function *)\n\nFact pos_dec_rel2fun n (R : pos n -> pos n -> Prop) :\n         (forall a b, { R a b } + { ~ R a b }) \n      -> (forall p, ex (R p)) -> { f | forall p, R p (f p) }.\nProof. apply finite_t_dec_choice; auto. Qed.\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/fin_choice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8031738057795402, "lm_q1q2_score": 0.6842661682632604}}
{"text": "(* Author : Maciej Bendkowski <maciej.bendkowski@tcs.uj.edu.pl> *)\nSection LambdaUpsilon.\n\nRequire Import Arith.\nRequire Import Omega.\n\n(* binary trees *)\nInductive btree : Set :=\n| Leaf\n| Left  : btree -> btree\n| Right : btree -> btree\n| BNode : btree -> btree -> btree.\n\nHint Constructors btree.\n\n(* natural size of btrees *)\nFixpoint btree_size (bt : btree) : nat :=\n  match bt with\n    | Leaf         => 1\n    | Left t       => S (btree_size t)\n    | Right t      => S (btree_size t)\n    | BNode lt rt  => S (btree_size lt + btree_size rt)\n  end.\n\n(* de Bruijn indices *)\nInductive index : Set :=\n| Z\n| Succ : index -> index.\n\nHint Constructors index.\n\n(* appropriate index <-> nat conversions *)\nFixpoint index_to_nat (idx : index) : nat :=\n  match idx with\n    | Z      => 0\n    | Succ n => 1 + index_to_nat n\n  end.\n\nFixpoint nat_to_index (n : nat) : index :=\n  match n with\n    | 0 => Z\n    | S n' => Succ (nat_to_index n')\n  end.\n\nLemma nat_index_inv : forall (n : nat),\n  index_to_nat (nat_to_index n) = n.\nProof.\ninduction n.\n- trivial.\n- simpl; auto.\nQed.\n\n(* natural size of indices *)\nFixpoint index_size (idx : index) : nat :=\n  match idx with\n    | Z      => 1\n    | Succ n => S (index_size n)\n  end.\n\n(* The size of index n is n + 1 *)\nLemma index_size_conv : forall (n : nat),\n  index_size (nat_to_index n) = S n.\nProof.\ninduction n.\n- trivial.\n- simpl; auto.\nQed.\n\n(* lambda upsilon terms *)\nInductive term : Set :=\n| Abs     : term -> term\n| Index   : index -> term\n| App     : term -> term -> term\n| Closure : term -> subs -> term\n\nwith\n\n(* explicit substitutions *)\nsubs : Set :=\n| Lift   : subs -> subs\n| Slash  : term -> subs\n| Shift.\n\nHint Constructors term.\nHint Constructors subs.\n\n(* natural size of terms *)\nFixpoint term_size (t : term) : nat :=\n  match t with\n    | Index idx   => index_size idx\n    | Abs t'      => S (term_size t')\n    | App lt rt   => S (term_size lt + term_size rt)\n    | Closure t s => S (term_size t + subs_size s)\n  end\n\nwith\n\n(* natural size of substitutions *)\nsubs_size (s : subs) : nat :=\n  match s with\n    | Lift s' => S (subs_size s')\n    | Slash t => S (term_size t)\n    | Shift   => 1\n  end.\n\n(* auxiliary lifts helper *)\nFixpoint lifts (n : nat) (s : subs) : subs :=\n  match n with\n    | 0    => s\n    | S n' => Lift (lifts n' s)\n  end.\n\n(* auxiliary lifts lemmas *)\nLemma lifts_size : forall (n : nat) (s : subs),\n  subs_size (lifts n s) = n + subs_size s.\nProof.\ninduction n, s.\n(* base cases *)\n- simpl; trivial.\n- simpl; trivial.\n- simpl; trivial.\n(* successor cases *)\n- simpl; rewrite IHn; auto.\n- simpl; rewrite IHn; auto.\n- simpl; rewrite IHn; auto.\nQed.\n\nLemma lifts_ind : forall (n : nat) (s : subs),\n  lifts (S n) s = lifts n (Lift s).\nProof.\ninduction n.\n- intros. simpl. trivial.\n- intros. simpl lifts. f_equal.\n  rewrite <- IHn. simpl. trivial.\nQed.\n\nHint Resolve lifts_ind.\n\nLemma lifts_diff : forall (n : nat) (s : subs) (t : term),\n  Lift (lifts n s) <> lifts n (Slash t).\nProof.\ninduction n.\n- intros. simpl. discriminate.\n- intros. simpl. injection; intros.\n  specialize (IHn s t). injection H; intro.\n  contradiction.\nQed.\n\n(* lifts is injective *)\nLemma lifts_inj : forall (n : nat) (s s' : subs),\n  lifts n s = lifts n s' -> s = s'.\nProof.\ninduction n.\n- intros. simpl lifts in H. auto.\n- intros. simpl lifts in H. injection H; intros.\n  specialize (IHn s s'). auto.\nQed.\n\n(* translation from btrees to terms *)\nFixpoint btree_to_term (bt : btree) : term :=\n  match bt with\n    | Leaf         => Index Z\n    | Left t       => btree_to_term' 1 t\n    | Right t      => Abs (btree_to_term t)\n    | BNode lt rt  => App (btree_to_term lt) (btree_to_term rt)\n  end\n\nwith\n\nbtree_to_term' (n : nat) (bt : btree) : term :=\n  match bt with\n    | Leaf         => Index (nat_to_index n)\n    | Left t       => btree_to_term' (S n) t\n    | Right t      => Closure (btree_to_term t) (lifts (n-1) Shift)\n    | BNode lt rt  => Closure (btree_to_term rt) (lifts (n-1) (Slash (btree_to_term lt)))\n  end.\n\n(* translation preserves the structure size *)\nTheorem size_prop : forall (bt : btree) (n : nat),\n  term_size (btree_to_term bt) = btree_size bt /\\\n  term_size (btree_to_term' (S n) bt) = (S n) + btree_size bt.\nProof.\ninduction bt, n.\n(* Leaf cases *)\n- auto.\n- split. auto.\n  simpl. rewrite index_size_conv. omega.\n(* Left cases *)\n- simpl. split.\n  apply IHbt. apply IHbt.\n- simpl. split.\n  apply IHbt.\n  specialize (IHbt (S (S n))). omega.\n(* Right cases *)\n- simpl. specialize (IHbt 0).\n  split. omega. omega.\n- simpl. split. specialize (IHbt 0). omega.\n  rewrite lifts_size. simpl. specialize (IHbt (n+1)). omega.\n(* BNode cases *)\n- simpl. split.\n  specialize (IHbt1 0). specialize (IHbt2 0). omega.\n  specialize (IHbt1 0). specialize (IHbt2 0). omega.\n- simpl. split.\n  specialize (IHbt1 0). specialize (IHbt2 0). omega.\n  specialize (IHbt1 0). specialize (IHbt2 0).\n  rewrite lifts_size. simpl. omega.\nQed.\n\n(* structural invariant of btree_to_term' *)\nLemma btree_to_term'_inv : forall (bt : btree),\n  (forall (n : nat),\n    btree_to_term' (S n) bt = Index (nat_to_index (n + btree_size bt))) \\/\n  (forall (n : nat),\n    exists t s, btree_to_term' (S n) bt = Closure t (lifts n s)).\nProof.\ninduction bt.\n- left. intro. simpl.\n  induction n.\n    * auto.\n    * simpl. injection IHn.\n      intro. rewrite H. auto.\n- destruct IHbt.\n  * left. intro. simpl. rewrite H.\n    f_equal. auto with zarith.\n  * right. intro. simpl btree_to_term'.\n    specialize (H (S n)).\n    do 2 destruct H.\n    exists x. exists (Lift x0).\n    rewrite H. f_equal. eauto.\n- repeat (destruct IHbt;\n    right; intro; simpl;\n    exists (btree_to_term bt);\n    exists Shift;\n    replace (n - 0) with n;\n    trivial; omega).\n- repeat (destruct IHbt1; destruct IHbt2;\n    right; intro; simpl;\n    exists (btree_to_term bt2);\n    exists (Slash (btree_to_term bt1));\n    replace (n - 0) with n;\n    trivial; omega).\nQed.\n\n(* auxiliary size lemmas *)\nLemma contrapositive: forall (P Q : Prop),\n  (P -> Q) -> (~ Q -> ~ P).\nProof.\ntauto.\nQed.\n\n(* auxiliary proof arguments *)\nLemma diff_term_size : forall (t t' : term),\n  term_size t <> term_size t' -> t <> t'.\nProof.\nintros t t'.\napply contrapositive.\nintro. rewrite H. trivial.\nQed.\n\nHint Resolve diff_term_size.\n\nLemma diff_subs_size : forall (s s' : subs),\n  subs_size s <> subs_size s' -> s <> s'.\nProof.\nintros s s'.\napply contrapositive.\nintro. rewrite H. trivial.\nQed.\n\nHint Resolve diff_subs_size.\n\n(* positive size lemmas *)\nLemma positive_btree_size : forall (bt : btree),\n  btree_size bt > 0.\nProof.\nrepeat (induction bt;\n        simpl; omega).\nQed.\n\nHint Resolve positive_btree_size.\n\nLemma positive_index_size : forall (i : index),\n  index_size i > 0.\nProof.\nintros.\nrepeat (destruct i;\n        simpl; omega).\nQed.\n\nHint Resolve positive_index_size.\n\nLemma positive_term_size : forall (t : term),\n  term_size t > 0.\nProof.\nrepeat (induction t;\n        simpl; auto with arith).\nQed.\n\nHint Resolve positive_term_size.\n\n(* additional structural invariants of btree_to_term' *)\nLemma btree_to_term'_abs : forall (bt bt' : btree) (n : nat),\n  btree_to_term' (S n) bt <> Abs (btree_to_term bt').\nProof.\nintros.\ndestruct (btree_to_term'_inv bt).\nintuition. rewrite H in H0. discriminate H0.\nintuition. specialize (H n). do 2 destruct H.\nrewrite H in H0. discriminate H0.\nQed.\n\nLemma btree_to_term'_app : forall (bt bt' bt'' : btree) (n : nat),\n  btree_to_term' (S n) bt <> App (btree_to_term bt') (btree_to_term bt'').\nProof.\nintros.\ndestruct (btree_to_term'_inv bt).\nintuition. rewrite H in H0. discriminate H0.\nintuition. specialize (H n). do 2 destruct H.\nrewrite H in H0. discriminate H0.\nQed.\n\nLemma btree_to_term'_left_right : forall (n : nat) (bt bt' : btree),\n  btree_to_term' (S n) (Left bt) <> btree_to_term' (S n) (Right bt').\nProof.\nintros. simpl.\ndestruct (btree_to_term'_inv bt).\nrewrite (H (S n)). discriminate.\nspecialize (H (S n)). do 2 destruct H.\nrewrite H. injection; intros.\ndestruct x0.\n- apply (f_equal subs_size) in H1.\n  simpl subs_size in H1.\n  do 2 (rewrite lifts_size in H1).\n  simpl subs_size in H1.\n  omega.\n- apply (f_equal subs_size) in H1.\n  simpl subs_size in H1.\n  do 2 (rewrite lifts_size in H1).\n  simpl subs_size in H1.\n  omega.\n- injection H0; intros.\n  apply (f_equal subs_size) in H3.\n  simpl subs_size in H3.\n  do 2 (rewrite lifts_size in H3).\n  simpl subs_size in H3.\n  omega.\nQed.\n\nLemma btree_to_term'_left_bnode : forall (n : nat) (bt bt'1 bt'2 : btree),\n  btree_to_term' (S n) (Left bt) <> btree_to_term' (S n) (BNode bt'1 bt'2).\nProof.\nintros. simpl.\ndestruct (btree_to_term'_inv bt).\nrewrite (H (S n)). discriminate.\nspecialize (H (S n)). do 2 destruct H.\nrewrite H. injection; intros.\ncontradict H1. replace (n-0) with n.\napply lifts_diff. omega.\nQed.\n\nLemma btree_to_term'_right_bnode : forall (n : nat) (bt bt'1 bt'2 : btree),\n  btree_to_term' (S n) (Right bt) <> btree_to_term' (S n) (BNode bt'1 bt'2).\nProof.\nintros. simpl.\ninjection; intros.\ncontradict H0. replace (n-0) with n.\napply diff_subs_size.\nrewrite lifts_size. simpl.\nrewrite lifts_size. simpl.\npose proof (positive_term_size (btree_to_term bt'1)).\nomega. omega.\nQed.\n\n(* main proof: translation is injective *)\nTheorem injection_prop : forall (bt bt' : btree),\n  (btree_to_term bt = btree_to_term bt' -> bt = bt') /\\\n  (forall (n : nat),\n    btree_to_term' (S n) bt = btree_to_term' (S n) bt' -> bt = bt').\nProof.\ninduction bt.\n(* Leaf cases *)\n- intros. destruct bt'.\n  * split. trivial.\n    intro. trivial.\n  * split.\n      intro. contradict H. apply diff_term_size.\n      simpl. pose proof (size_prop bt' 0) as H. destruct H.\n      rewrite H0. pose proof (positive_btree_size bt'). omega.\n\n      intros. contradict H. apply diff_term_size.\n      simpl. rewrite index_size_conv.\n      pose proof (size_prop bt' (S n)) as H. destruct H.\n      rewrite H0. pose proof (positive_btree_size bt'). omega.\n  * split.\n      intro. contradict H. apply diff_term_size.\n      simpl. pose proof (size_prop bt' 0) as H. destruct H.\n      rewrite H. pose proof (positive_btree_size bt'). omega.\n\n      intros. contradict H. apply diff_term_size.\n      simpl. rewrite index_size_conv. rewrite lifts_size. simpl.\n      pose proof (size_prop bt' 0) as H. destruct H.\n      rewrite H. pose proof (positive_btree_size bt'). omega.\n  * split.\n      intro. contradict H. apply diff_term_size. simpl.\n      pose proof (size_prop bt'1 0) as H1. destruct H1. rewrite H.\n      pose proof (size_prop bt'2 0) as H2. destruct H2. rewrite H1.\n      pose proof (positive_btree_size bt'1).\n      pose proof (positive_btree_size bt'2).\n      omega.\n\n      intros. contradict H. apply diff_term_size.\n      simpl. rewrite index_size_conv. rewrite lifts_size. simpl.\n      pose proof (size_prop bt'1 0) as H1. destruct H1. rewrite H.\n      pose proof (size_prop bt'2 0) as H2. destruct H2. rewrite H1.\n      pose proof (positive_btree_size bt'1).\n      pose proof (positive_btree_size bt'2).\n      omega.\n(* Left cases *)\n- intros. destruct bt'.\n  * split.\n    intro. contradict H. apply diff_term_size. simpl.\n    pose proof (size_prop bt 0) as H. destruct H.\n    rewrite H0. pose proof (positive_btree_size bt). omega.\n\n    intros. simpl btree_to_term' in H at 1.\n    apply (f_equal term_size) in H.\n    pose proof (size_prop bt (S n)) as P. destruct P.\n    rewrite H in H1.\n    simpl btree_to_term' in H1.\n    simpl term_size in H1.\n    rewrite index_size_conv in H1.\n    contradict H1. pose proof (positive_btree_size bt).\n    omega.\n  * split.  (* both are Left *)\n    intros. simpl btree_to_term in H.\n    specialize (IHbt bt'). destruct IHbt.\n    specialize (H1 0). cut (bt = bt').\n    intros. apply (f_equal Left) in H2. auto. auto.\n\n    intros. simpl btree_to_term' in H.\n    specialize (IHbt bt'). destruct IHbt.\n    specialize (H1 (S n)). cut (bt = bt').\n    intros. apply (f_equal Left) in H2. auto. auto.\n  * split.\n    intros. simpl btree_to_term in H.\n    contradict H. apply btree_to_term'_abs.\n\n    intros.\n    pose proof (btree_to_term'_left_right n bt bt').\n    contradiction.\n  * split.\n    intros. simpl btree_to_term in H.\n    contradict H. apply btree_to_term'_app.\n\n    intros.\n    pose proof (btree_to_term'_left_bnode n bt bt'1 bt'2).\n    contradiction.\n(* Right cases *)\n- intros. destruct bt'.\n  * split.\n    intro. contradict H. apply diff_term_size. simpl.\n    pose proof (size_prop bt 0) as H. destruct H.\n    rewrite H. pose proof (positive_btree_size bt). omega.\n\n    intros. simpl btree_to_term' in H.\n    discriminate H.\n  * split.\n    intros. symmetry in H. simpl btree_to_term in H.\n    contradict H. apply btree_to_term'_abs.\n\n    intros.\n    pose proof (btree_to_term'_left_right n bt' bt).\n    symmetry in H. contradiction.\n  * split. (* both are Right *)\n    intros. simpl btree_to_term in H.\n    specialize (IHbt bt'). destruct IHbt. cut (bt = bt').\n    intros. apply (f_equal Right) in H2. auto. injection H. auto.\n\n    intros. simpl btree_to_term' in H.\n    specialize (IHbt bt'). destruct IHbt.\n    specialize (H1 (S n)). cut (bt = bt').\n    intros. apply (f_equal Right) in H2. auto.\n    injection H. auto.\n  * split.\n    intros. simpl btree_to_term in H.\n    discriminate H.\n\n    intros.\n    pose proof (btree_to_term'_right_bnode n bt bt'1 bt'2).\n    contradiction.\n(* BNode cases *)\n- intros. split.\n  * intros. simpl btree_to_term in H. destruct bt'.\n    + simpl btree_to_term in H. discriminate H.\n    + simpl btree_to_term in H.\n      pose proof (btree_to_term'_app bt' bt1 bt2 0).\n      symmetry in H. contradiction.\n    + simpl btree_to_term in H. discriminate H.\n    + simpl btree_to_term in H. injection H. intros.\n      specialize (IHbt1 bt'1). destruct IHbt1.\n      specialize (IHbt2 bt'2). destruct IHbt2.\n      assert (bt1 = bt'1). auto.\n      assert (bt2 = bt'2). auto.\n      f_equal. auto. auto.\n  * intros. destruct bt'.\n    + simpl btree_to_term' in H. discriminate H.\n    + symmetry in H.\n      pose proof (btree_to_term'_left_bnode n bt' bt1 bt2).\n      contradiction.\n    + symmetry in H.\n      pose proof (btree_to_term'_right_bnode n bt' bt1 bt2).\n      contradiction.\n    + simpl btree_to_term' in H. (* both are BNode *)\n      injection H; intros.\n      specialize (IHbt2 bt'2). destruct IHbt2.\n      replace (n-0) with n in H0.\n      apply lifts_inj in H0.\n      injection H0; intros.\n      specialize (IHbt1 bt'1). destruct IHbt1.\n      f_equal. auto. auto.\n      omega.\nQed.\n\nEnd LambdaUpsilon.\n\nExtraction Language Haskell.\nExtraction \"LambdaUpsilonCert.hs\" btree_to_term.", "meta": {"author": "maciej-bendkowski", "repo": "combinatorics-of-explicit-substitutions", "sha": "156575265b259f50150c4f66779b1326147c983a", "save_path": "github-repos/coq/maciej-bendkowski-combinatorics-of-explicit-substitutions", "path": "github-repos/coq/maciej-bendkowski-combinatorics-of-explicit-substitutions/combinatorics-of-explicit-substitutions-156575265b259f50150c4f66779b1326147c983a/src/LambdaUpsilon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.6842661632721397}}
{"text": "Load monoids_and_groups.\nOpen Scope nat_scope.\n\n(* The inclusion of natural numbers in integers *)\nDefinition nat_to_int : nat -> Int.\nProof.\n  intro n.\n  destruct n.\n  - exact Int.zero.\n  - apply pos.\n    induction n.\n    + exact Int.one.\n    + exact (Int.succ_pos IHn).\nDefined.\n\n(* The inclusion preserves sum *)\nDefinition nat_to_int_succ : forall m : nat, nat_to_int (m.+1) = succ_int (nat_to_int m).\nProof.\n  destruct m; reflexivity.\nDefined.\n\n(* succ_int and pred_int are inverses *)\nDefinition Int_succ_pred : forall a : Int, succ_int (pred_int a) = a.\nProof.\n  induction a; try induction p; try reflexivity.\nDefined.\n\nDefinition Int_pred_succ : forall a : Int, pred_int (succ_int a) = a.\nProof.\n  destruct a; try destruct p; try reflexivity.\nDefined.\n\n(* Multiplying with -1 *)\nDefinition Int_minus (a : Int) : Int :=\n  match a with\n  |neg p => pos p\n  |Int.zero => Int.zero\n  |pos p => neg p\n  end.\n\n(* Int_minus is its own inverse *)\nDefinition Int_minus_minus (a : Int) : Int_minus (Int_minus a) = a.\nProof.\n  destruct a; reflexivity.\nDefined.\n\n(* Successor of minus is minus of predecessor *)\nDefinition Int_succ_minus (a : Int) : succ_int (Int_minus a) = Int_minus (pred_int a).\nProof.\n  destruct a; try destruct p; try reflexivity.\nDefined.\n\n(* (* Add a positive integer to an integer *) *)\n(* Fixpoint Int_sum_pos (p : Pos) : Int -> Int. *)\n(*   destruct p. *)\n(*   - exact succ_int. *)\n(*   - exact (succ_int o (Int_sum_pos p)). *)\n(* Defined. *)\n\n(* Sum of two integers *)\nDefinition Int_sum (a : Int) : Int -> Int.\nProof.\n  destruct a.\n  (* a is negative *)\n  - induction p.\n    + exact pred_int.           (* -1 + n *)\n    + exact (pred_int o IHp). (* (-1-p) + n = -1 + (-p + n) *)\n  (* a is zero *)\n  - exact idmap.\n  (* a is positive *)\n  - induction p.\n    + exact succ_int.           (* 1+n *)\n    + exact (succ_int o IHp). (* (1+p) + n = 1 + (p+n) *)\nDefined.\n\n(* Sum of two positive integers *)\nFixpoint pos_sum (p : Pos) : Pos -> Pos.\nProof.\n  destruct p.\n  + exact succ_pos.\n  + exact (succ_pos o (pos_sum p)).\nDefined.\n\n(* Sum of positives is positive *)\nLemma Int_sum_pos (p q : Pos) : Int_sum (pos p) (pos q) = pos (pos_sum p q).\nProof.\n  induction p.\n  - reflexivity.\n  - change (Int_sum (pos (succ_pos p)) (pos q)) with (succ_int (Int_sum (pos p) (pos q))).\n    rewrite IHp. reflexivity.\nQed.\n\n(* Sum of negatives are negative *)\nLemma int_sum_neg (p q : Pos) : Int_sum (neg p) (neg q) = neg (pos_sum p q).\nProof.\n  induction p.\n  - reflexivity.\n  - change (Int_sum (neg (succ_pos p)) (neg q)) with (pred_int (Int_sum (neg p) (neg q))).\n    rewrite IHp. reflexivity.\nQed.  \n\n(* Sum preserves mines *)\nLemma Int_sum_minus (a b: Int) : Int_sum (Int_minus a) (Int_minus b) = Int_minus (Int_sum a b).\nProof.\n  destruct a; destruct b; try reflexivity.\n  - rewrite int_sum_neg. apply Int_sum_pos.\n  - \n    + apply Int_succ_minus.\n    + intro b. admit. \n  - reflexivity.\n  - \n  \n  simpl.\n  \n  unfold Int_minus. simpl.\n\n  simpl.\n  destruct a,b; try reflexivity. simpl.\n  \n\n(* Sum preserves successor (in first variable) *)\nDefinition Int_sum_succ : forall a b : Int, Int_sum (succ_int a) b = succ_int (Int_sum a b).\nProof. \n  intros a b.\n  destruct a.\n  (* a is negative *)\n  - destruct p.\n    + simpl. apply inverse. apply Int_succ_pred.\n    + (* change (neg (succ_pos p)) with (pred_int (neg p)). *)\n      rewrite (Int_succ_pred (neg p)).\n      \n\n    (* rewrite Int_succ_minus. rewrite Int_pred_succ. rewrite Int_minus_minus. reflexivity. *)\n    (* simpl. rewrite Int_succ_minus. rewrite Int_pred_succ. reflexivity. *) admit.\n  (* a is zero *)\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* The inclusion [nat -> Integer] preserves sum *)\nDefinition ishom_nat_to_int : forall m n : nat, nat_to_int (m + n) = Int_sum (nat_to_int m) (nat_to_int n).\nProof.\n  intros m n.\n  induction m; try reflexivity.\n  rewrite nat_to_int_succ. transitivity (succ_int (nat_to_int (m+n))).\n  { apply nat_to_int_succ. }\n  rewrite Int_sum_succ. exact (ap succ_int IHm).\nQed.\n\n(* Sum of integers is associative *)\nDefinition Int_sum_assoc : associative Int_sum.\nProof.\n  intros a b c.\n  destruct a.\n  - simpl. admit.               (* a is negative *)\n  - reflexivity.                (* a is zero *)\n  - simpl. induction p.\n    simpl. apply inverse. apply Int_sum_succ.\n    simpl.\n    \n\n    induction a.\n  (* a is negative *)\n  - admit. (* induction p. *)\n  (* (* a is -1 *) *)\n  (* + simpl. *)\n  (*   induction b as [q | q | q]; try reflexivity. *)\n  (*   (* b is positive *) *)\n  (*   * induction q. *)\n  (*     (* b is 1 *) *)\n  (*     { simpl. induction c; try reflexivity. induction p; reflexivity. } *)\n  (*     (* b is q+1 *) *)\n  (*     { simpl.  } *)\n    \n    \n  (* a is zero *)\n  - reflexivity.\n  (* a is positive *)\n  - induction p.\n    simpl.  Admitted.\n\n\n\n\n", "meta": {"author": "kalfsvag", "repo": "misc_coq", "sha": "9886ed4eb3dfc077afd1d769c910a729475fa173", "save_path": "github-repos/coq/kalfsvag-misc_coq", "path": "github-repos/coq/kalfsvag-misc_coq/misc_coq-9886ed4eb3dfc077afd1d769c910a729475fa173/Integers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.68426150443564}}
{"text": "(** * Algebraic CPOs, comorphisms, and their proof principles. *)\n\nFrom Coq Require Import\n  Basics\n  Morphisms\n  Equivalence\n.\n\nLocal Open Scope program_scope.\nLocal Open Scope equiv_scope.\n\nFrom algco Require Import\n  axioms\n  cpo\n  order\n  tactics\n.\n\nLocal Open Scope order_scope.\n\nCreate HintDb aCPO.\n\n(** The reason we don't use sigma types for monotone and continuous\n    functions is that you have to use weird syntax for function\n    application. Besides that, it would be pretty cool I think.. maybe\n    still worth it? *)\n\n(** Just as the continuous functions are the approximable functions,\n    the (co)continuous properties are the approximable properties. A\n    continuous property is true globally whenever it is true locally\n    *somewhere*. A cocontinuous property is true globally whenever it\n    is true locally *everywhere*. *)\n\nDefinition compact {A} `{OType A} (x : A) : Prop :=\n  forall f : nat -> A, directed f -> supremum x f -> exists i, f i === x.\n\n(** A space [A] is compact whenever none of its elements can be\n    non-trivially approximated. *)\nClass Compact (A : Type) `{OType A} : Prop :=\n  { compact_spec : forall x : A, compact x }.\n\n(** [B] is dense in [A] when there is an injective inclusion map and a\n    way to map an element [a : A] to a chain of elements of [B] that\n    converges to [a] (through the inclusion map). *)\nClass Dense (A B : Type) `{OType A} `{OType B} : Type :=\n  { incl : B -> A\n  ; ideal : A -> nat -> B\n  }.\n\n(** A is a CPO with basis B (B is compact and dense in A). *)\nClass aCPO (A B : Type) `{oA : OType A} `{oB : OType B}\n  { compact : Compact B} {dense : Dense A B} {cpoA : CPO A} : Prop :=\n  { incl_order : forall x y : B, x ⊑ y <-> incl x ⊑ incl y\n  ; chain_ideal : forall a : A, chain (ideal a)\n  ; monotone_ideal : monotone (@ideal _ _ _ _ dense)\n  ; continuous_ideal : forall n, continuous (flip (@ideal _ _ _ _ dense) n)\n  ; supremum_ideal : forall a : A, supremum a (incl ∘ ideal a)\n  }.\n\n#[global] Hint Resolve chain_ideal : aCPO.\n\n#[global]\n  Instance Compact_bool : Compact bool.\nProof.\n  constructor; intros [] f Hf Ha.\n  - contra HC.\n    assert (upper_bound false f).\n    { intro i.\n      destruct (f i) eqn:Hfi.\n      - exfalso; apply HC; exists i; rewrite Hfi; reflexivity.\n      - constructor. }\n    apply Ha in H; inv H.\n  - exists O; split.\n    + apply Ha.\n    + constructor.\nQed.\n\n(** Any monotone function on a compact space is continuous. *)\nLemma continuous_compact {A B} `{Compact A} `{OType B} (f : A -> B) :\n  monotone f ->\n  continuous f.\nProof.\n  intros Hmono ch Hch x Hx; unfold compose.\n  destruct H0 as [H0].\n  split.\n  - intro i; apply Hmono, Hx.\n  - intros ub Hub.\n    specialize (H0 x ch Hch Hx).\n    destruct H0 as [i Hi].\n    unfold monotone in Hmono.\n    rewrite <- Hi.\n    apply Hub.\nQed.\n#[global] Hint Resolve continuous_compact : aCPO.\n\n(** Any antimonotone function on a compact space is cocontinuous. *)\nLemma cocontinuous_compact {A B} `{Compact A} `{OType B} (f : A -> B) :\n  antimonotone f ->\n  cocontinuous f.\nProof.\n  intros Hmono ch Hch x Hx; unfold compose.\n  destruct H0 as [H0].\n  split.\n  - intro i; apply Hmono, Hx.\n  - intros ub Hub.\n    specialize (H0 x ch Hch Hx).\n    destruct H0 as [i Hi].\n    unfold antimonotone in Hmono.\n    rewrite <- Hi.\n    apply Hub.\nQed.\n#[global] Hint Resolve cocontinuous_compact : aCPO.\n\n(** Shorthand for referring to the basis of an aCPO. *)\nDefinition basis (A : Type) {B : Type} `{aCPO A B} : Type := B.\n#[global] Hint Transparent basis : aCPO.\n\nSection aCPO.\n  Context {A B : Type} `{aCPO A B}.\n\n  (** Continuous comorphism. *)\n  Definition co {C} `{OType C} (f : basis A -> C) (a : A) : C :=\n    sup (f ∘ ideal a).\n\n  (** Need decreasing version of ideal for this. *)\n  (* Definition dec_co {C} `{OType C} (f : basis A -> C) (a : A) : C := *)\n  (*   inf (f ∘ ideal a). *)\n\n  (** Co-continuous comorphism. *)\n  Definition coop {C} `{OType C} (f : basis A -> C) (a : A) : C :=\n    inf (f ∘ ideal a).\n\n  Lemma chain_f_ideal {C} `{OType C} (f : basis A -> C) (a : A) :\n    monotone f ->\n    chain (fun i => f (ideal a i)).\n  Proof. intro Hf; apply monotone_chain; auto; apply chain_ideal. Qed.\n\n  Lemma dec_chain_f_ideal {C} `{OType C} (f : basis A -> C) (a : A) :\n    antimonotone f ->\n    dec_chain (fun i => f (ideal a i)).\n  Proof. intro Hf; apply antimonotone_dec_chain; auto; apply chain_ideal. Qed.\n\n  Lemma directed_f_ideal {C} `{OType C} (f : basis A -> C) (a : A) :\n    monotone f ->\n    directed (fun i => f (ideal a i)).\n  Proof.\n    intro Hf.\n    apply monotone_directed; auto.\n    apply chain_directed, chain_ideal.\n  Qed.\n  Hint Resolve directed_f_ideal : aCPO.\n\n  Lemma downward_directed_f_ideal {C} `{OType C} (f : basis A -> C) (a : A) :\n    antimonotone f ->\n    downward_directed (fun i => f (ideal a i)).\n  Proof.\n    intro Hf.\n    apply antimonotone_downward_directed; auto.\n    apply chain_directed, chain_ideal.\n  Qed.\n\n  Lemma supremum_ideal_incl (b : basis A) :\n    supremum b (ideal (incl b)).\n  Proof.\n    unfold basis in *.\n    destruct H as [Hincl ? ? ? Hsup].\n    specialize (Hsup (incl b)); destruct Hsup as [Hub Hlub].\n    split.\n    - intro i.\n      specialize (Hub i); unfold compose in Hub.\n      apply Hincl; auto.\n    - intros x Hx.\n      apply Hincl.\n      apply Hlub.\n      intro i; unfold compose.\n      apply Hincl; auto.\n  Qed.\n\n  Lemma ideal_incl_le a i :\n    ideal (incl a) i ⊑ a.\n  Proof.\n    generalize (supremum_ideal_incl a); intros [Hub ?]; apply Hub.\n  Qed.\n\n  Lemma incl_ideal_le (a : A) i :\n    incl (ideal a i) ⊑ a.\n  Proof.\n    destruct H.\n    specialize (supremum_ideal0 a).\n    destruct supremum_ideal0 as [Hub Hlub].\n    apply Hub.\n  Qed.\n  \n  (** [co f] is the unique morphism (continuous function) satisfying\n      this equation. [co f] is equal to f on all basis elements for\n      which f was originally defined. *)\n  Theorem co_incl {C} `{CPO C} (f : basis A -> C) :\n    monotone f ->\n    co f ∘ incl === f.\n  Proof.\n    intro Hmono.\n    apply equ_arrow; intro b.\n    unfold co, compose.\n    apply supremum_sup.\n    apply continuous_compact; auto.\n    - apply chain_directed, chain_ideal.\n    - apply supremum_ideal_incl.\n  Qed.\n\n  (** Pointwise variant. *)\n  Corollary co_incl' {C} `{CPO C} (f : basis A -> C) (b : basis A) :\n    monotone f ->\n    co f (incl b) === f b.\n  Proof. intro Hmono; revert b; apply equ_arrow, co_incl; auto. Qed.\n\n  (** Pointwise variant. *)\n  Corollary co_incl'_ext {C} `{o : OType C} `{@CPO C o} `{@ExtType C o}\n    (f : basis A -> C) (b : basis A) :\n    monotone f ->\n    co f (incl b) = f b.\n  Proof. intro Hf; apply ext, co_incl'; auto. Qed.\n\n  (** [coop f] is the unique morphism (continuous function) satisfying\n      this equation. [coop f] is equal to f on all basis elements for\n      which f was originally defined. *)\n  Theorem coop_incl {C} `{lCPO C} (f : basis A -> C) :\n    antimonotone f ->\n    coop f ∘ incl === f.\n  Proof.\n    intro Hmono.\n    apply equ_arrow; intro b.\n    unfold coop, compose.\n    apply infimum_inf.\n    apply cocontinuous_compact; auto.\n    - apply chain_directed, chain_ideal.\n    - apply supremum_ideal_incl.\n  Qed.\n\n  (** Pointwise variant. *)\n  Corollary coop_incl' {C} `{lCPO C} (f : basis A -> C) (b : basis A) :\n    antimonotone f ->\n    coop f (incl b) === f b.\n  Proof. intro Hmono; revert b; apply equ_arrow, coop_incl; auto. Qed.\n\n  (** The co-version of any monotone basis function is monotone. *)\n  #[global]\n    Instance monotone_co {C} `{CPO C}\n    (f : basis A -> C) {_ : Proper (leq ==> leq) f}\n    : Proper (leq ==> leq) (co f).\n  Proof.\n    intros a b Hab.\n    apply ge_sup.\n    { apply directed_f_ideal; auto. }\n    intro i.\n    apply le_sup with i.\n    { apply directed_f_ideal; auto. }\n    apply H2, monotone_ideal; auto.\n  Qed.\n  Hint Resolve monotone_co : aCPO.\n\n  (** The coop-version of any antimonotone basis function is antimonotone. *)\n  #[global]\n    Instance antimonotone_coop {C} `{lCPO C}\n    (f : basis A -> C) {_ : Proper (leq ==> flip leq) f}\n    : Proper (leq ==> flip leq) (coop f).\n  Proof.\n    intros a b Hab.\n    unfold flip.\n    unfold co.\n    eapply monotone_inf.\n    { apply downward_directed_f_ideal; auto. }\n    { apply downward_directed_f_ideal; auto. }\n    intro i; apply H2, monotone_ideal; auto.\n  Qed.\n  Hint Resolve antimonotone_coop : aCPO.\n  \n  (** The approximate co-version of any monotone basis function is continuous. *)\n  Lemma continuous_f_ideal {C} `{OType C} (f : basis A -> C) (n : nat) :\n    monotone f ->\n    continuous (f ∘ flip ideal n).\n  Proof.\n    intro Hmono.\n    apply continuous_compose.\n    - apply continuous_ideal.\n    - apply continuous_compact; auto.\n  Qed.\n  \n  (** The approximate co-version of any antimonotone basis function is cocontinuous. *)\n  Lemma cocontinuous_f_ideal {C} `{OType C} (f : basis A -> C) (n : nat) :\n    antimonotone f ->\n    cocontinuous (f ∘ flip ideal n).\n  Proof.\n    intro Hmono.\n    apply continuous_cocontinuous_compose.\n    - apply continuous_ideal.\n    - apply cocontinuous_compact; auto.\n  Qed.\n\n  (** The co-version of any monotone basis function is continuous. *)\n  Theorem continuous_co {C} `{CPO C} (f : B -> C) :\n    monotone f ->\n    continuous (co f).\n  Proof.\n    intros Hmono ch Hch t Hsup; unfold compose; split.\n    - intro i; apply monotone_co; auto; apply Hsup.\n    - intros x Hx.\n      apply ge_sup.\n      { apply directed_f_ideal; auto. }\n      intro i.\n      eapply continuous_f_ideal; eauto.\n      unfold flip, compose; intro j; specialize (Hx j).\n      etransitivity; eauto.\n      generalize (sup_spec (fun x0 : nat => f (ideal (ch j) x0))).\n      intro Hwsup.\n      assert (Hch': directed (fun x0 : nat => f (ideal (ch j) x0))).\n      { apply directed_f_ideal; auto. }\n      apply Hwsup in Hch'.\n      destruct Hch' as [Hub Hlub].\n      apply Hub.\n  Qed.\n  Hint Resolve continuous_co : aCPO.\n\n  (** The coop-version of any antimonotone basis function is cocontinuous. *)\n  Theorem cocontinuous_coop {C} `{lCPO C} (f : basis A -> C) :\n    antimonotone f ->\n    cocontinuous (coop f).\n  Proof.\n    intros Hmono ch Hch t Hsup; unfold compose; split.\n    - intro i; apply antimonotone_coop; auto; apply Hsup.\n    - intros x Hx.\n      apply le_inf.\n      { apply downward_directed_f_ideal; auto. }\n      intro i.\n      eapply cocontinuous_f_ideal; eauto.\n      unfold flip, compose; intro j; specialize (Hx j).\n      etransitivity; eauto.\n      generalize (inf_spec (fun x0 : nat => f (ideal (ch j) x0))).\n      intro Hinf.\n      assert (Hch': downward_directed (fun x0 : nat => f (ideal (ch j) x0))).\n      { apply downward_directed_f_ideal; auto. }\n      apply Hinf in Hch'.\n      destruct Hch' as [Hub Hlub].\n      apply Hub.\n  Qed.\n  Hint Resolve cocontinuous_coop : aCPO.\n\n  Lemma monotone_incl : monotone incl.\n  Proof.\n    intros i j Hij.\n    destruct H as [Hincl _ _ _ _].\n    apply Hincl; auto.\n  Qed.\n  Hint Resolve monotone_incl : aCPO.\n    \n  Theorem co_le {C} `{CPO C} (f : basis A -> C) (g : A -> C) :\n    monotone f ->\n    wcontinuous g ->\n    f ⊑ g ∘ incl ->\n    co f ⊑ g.\n  Proof.\n    unfold basis, compose in *; intros Hf Hg Hgf.\n    intro a.\n    apply ge_sup.\n    { apply directed_f_ideal; auto. }\n    intro i; unfold compose.\n    simpl in *.\n    etransitivity; eauto.\n    apply wcontinuous_monotone; auto.\n    destruct H as [? ? ? ? Hsup].\n    destruct (Hsup a) as [Hub _].\n    apply Hub.\nQed.\n\n  (** Uniqueness property. This is the primary proof principle. *)\n  Theorem co_unique {C} `{CPO C} (f : basis A -> C) (g : A -> C) :\n    monotone f ->\n    wcontinuous g ->\n    g ∘ incl === f ->\n    g === co f.\n  Proof.\n    unfold basis, compose in *; intros Hf Hg [Hgf Hfg].\n    apply equ_arrow.\n    intro a.\n    symmetry.\n    apply supremum_sup.\n    split.\n    - intro i; unfold compose.\n      simpl in *.\n      etransitivity; eauto.\n      apply wcontinuous_monotone; auto.\n      destruct H as [? ? ? ? Hsup].\n      destruct (Hsup a) as [Hub _].\n      apply Hub.\n    - intros c Hc.\n      simpl in *.\n      destruct H as [? ? ? ? Hsup].\n      pose proof (Hsup a) as Ha.\n      apply Hg in Ha.\n      2: { apply chain_f_ideal; auto.\n           apply monotone_incl. }\n      destruct Ha as [Hub Hlub].\n      apply Hlub.\n      intro i; unfold compose.\n      etransitivity; eauto.\n  Qed.\n\n  (* (** Uniqueness property. This is the primary proof principle. *) *)\n  (* Theorem co_unique {C} `{CPO C} (f : basis A -> C) (g : A -> C) : *)\n  (*   monotone f -> *)\n  (*   continuous g -> *)\n  (*   g ∘ incl === f -> *)\n  (*   g === co f. *)\n  (* Proof. *)\n  (*   unfold basis, compose in *; intros Hf Hg [Hgf Hfg]. *)\n  (*   apply equ_arrow. *)\n  (*   intro a. *)\n  (*   symmetry. *)\n  (*   apply supremum_sup. *)\n  (*   split. *)\n  (*   - intro i; unfold compose. *)\n  (*     simpl in *. *)\n  (*     etransitivity; eauto. *)\n  (*     apply continuous_monotone; auto. *)\n  (*     destruct H as [? ? ? ? Hsup]. *)\n  (*     destruct (Hsup a) as [Hub _]. *)\n  (*     apply Hub. *)\n  (*   - intros c Hc. *)\n  (*     simpl in *. *)\n  (*     destruct H as [? ? ? ? Hsup]. *)\n  (*     pose proof (Hsup a) as Ha. *)\n  (*     apply Hg in Ha. *)\n  (*     2: { apply directed_f_ideal; auto. *)\n  (*          apply monotone_incl. } *)\n  (*     destruct Ha as [Hub Hlub]. *)\n  (*     apply Hlub. *)\n  (*     intro i; unfold compose. *)\n  (*     etransitivity; eauto. *)\n  (* Qed. *)\n  \n  Corollary co_unique_ext {C} `{o : OType C} `{@CPO C o} `{@ExtType C o}\n    (f : basis A -> C) (g : A -> C) :\n    monotone f ->\n    wcontinuous g ->\n    g ∘ incl = f ->\n    g = co f.\n  Proof.\n    intros Hf Hg Heq; apply ext, co_unique; auto; rewrite Heq; reflexivity.\n  Qed.\n\n  Lemma continuous_incl_ideal (P : A -> Prop) (a : A) :\n    continuous P ->\n    P a ->\n    exists i, P (incl (ideal a i)).\n  Proof.\n    intros HP HPa.\n    unfold continuous in HP.\n    assert (Ha: supremum a (incl ∘ ideal a)).\n    { apply supremum_ideal. }\n    apply HP in Ha.\n    2: { apply directed_f_ideal, monotone_incl. }\n    apply supremum_Prop' in Ha; intuition.\n  Qed.\n\n  Lemma cocontinuous_incl_ideal (P : A -> Prop) (a : A) (i : nat) :\n    cocontinuous P ->\n    P a ->\n    P (incl (ideal a i)).\n  Proof.\n    intros HP HPa.\n    unfold cocontinuous in HP.\n    assert (Ha: supremum a (incl ∘ ideal a)).\n    { apply supremum_ideal. }\n    apply HP in Ha.\n    2: { apply directed_f_ideal, monotone_incl. }\n    unfold compose in *.\n    destruct Ha as [Hlb Hglb].\n    apply Hlb; auto.\n  Qed.\n\n  (* (** Continuously constrained uniqueness principle (more powerful). *) *)\n  (* Theorem co_unique_continuous_P {C} `{CPO C} (P : A -> Prop) (f : basis A -> C) (g : A -> C) (a : A) : *)\n  (*   continuous P -> *)\n  (*   monotone f -> *)\n  (*   continuous g -> *)\n  (*   P a -> *)\n  (*   ((exists i, P (incl (ideal a i))) -> *)\n  (*    forall i, g (incl (ideal a i)) === f (ideal a i)) -> *)\n  (*   g a === co f a. *)\n  (* Proof. *)\n  (*   unfold basis, compose in *; intros HP Hf Hg HPa Hgf. *)\n  (*   symmetry. *)\n  (*   apply supremum_sup. *)\n  (*   split. *)\n  (*   - intro i; unfold compose. *)\n  (*     apply continuous_incl_ideal in HPa; auto. *)\n  (*     specialize (Hgf HPa). *)\n  (*     rewrite <- Hgf. *)\n  (*     apply continuous_monotone; auto. *)\n  (*     apply incl_ideal_le. *)\n  (*   - intros c Hc. *)\n  (*     simpl in *. *)\n  (*     destruct H as [? ? ? ? Hsup]. *)\n  (*     pose proof (Hsup a) as Ha. *)\n  (*     apply Hg in Ha. *)\n  (*     2: { apply directed_f_ideal; auto. *)\n  (*          apply monotone_incl. } *)\n  (*     destruct Ha as [Hub Hlub]. *)\n  (*     apply Hlub. *)\n  (*     intro i; unfold compose. *)\n  (*     unfold compose in *. *)\n  (*     rewrite Hgf. *)\n  (*     2: { apply continuous_incl_ideal; auto. } *)\n  (*     eauto. *)\n  (* Qed. *)\n\n  (* (** Cocontinuously constrained uniqueness principle (more powerful). *) *)\n  (* Theorem co_unique_cocontinuous_R {C} `{CPO C} *)\n  (*   (R : A -> A -> Prop) (f : basis A -> C) (g : A -> C) (a b : A) : *)\n  (*   cocontinuous R -> *)\n  (*   monotone f -> *)\n  (*   continuous g -> *)\n  (*   R a b -> *)\n  (*   ((forall i, R (incl (ideal a i)) (incl (ideal b i))) -> *)\n  (*    forall i, g (incl (ideal a i)) === f (ideal b i)) -> *)\n  (*   g a === co f b. *)\n  (* Proof. *)\n  (*   unfold basis, compose in *; intros HP Hf Hg HPa Hgf. *)\n  (*   symmetry. *)\n  (*   apply supremum_sup. *)\n  (*   split. *)\n  (*   - intro i; unfold compose. *)\n  (*     rewrite <- Hgf. *)\n  (*     2: { intro n. *)\n  (*          apply cocontinuous_incl_ideal. *)\n  (*     2: { intro; apply cocontinuous_incl_ideal; auto. } *)\n  (*     apply continuous_monotone; auto. *)\n  (*     apply incl_ideal_le. *)\n  (*   - intros c Hc. *)\n  (*     simpl in *. *)\n  (*     destruct H as [? ? ? ? Hsup]. *)\n  (*     pose proof (Hsup a) as Ha. *)\n  (*     apply Hg in Ha. *)\n  (*     2: { apply directed_f_ideal; auto. *)\n  (*          apply monotone_incl. } *)\n  (*     destruct Ha as [Hub Hlub]. *)\n  (*     apply Hlub. *)\n  (*     intro i; unfold compose. *)\n  (*     unfold compose in *. *)\n  (*     rewrite Hgf. *)\n  (*     2: { intro; apply cocontinuous_incl_ideal; auto. } *)\n  (*     eauto. *)\n  (* Qed. *)\n\n  (* (** Cocontinuously constrained uniqueness principle (more powerful). *) *)\n  (* Theorem co_unique_cocontinuous_P {C} `{CPO C} *)\n  (*   (P : A -> Prop) (f : basis A -> C) (g : A -> C) (a : A) : *)\n  (*   cocontinuous P -> *)\n  (*   monotone f -> *)\n  (*   continuous g -> *)\n  (*   P a -> *)\n  (*   ((forall i, P (incl (ideal a i))) -> *)\n  (*    forall i, g (incl (ideal a i)) === f (ideal a i)) -> *)\n  (*   g a === co f a. *)\n  (* Proof. *)\n  (*   unfold basis, compose in *; intros HP Hf Hg HPa Hgf. *)\n  (*   symmetry. *)\n  (*   apply supremum_sup. *)\n  (*   split. *)\n  (*   - intro i; unfold compose. *)\n  (*     rewrite <- Hgf. *)\n  (*     2: { intro; apply cocontinuous_incl_ideal; auto. } *)\n  (*     apply continuous_monotone; auto. *)\n  (*     apply incl_ideal_le. *)\n  (*   - intros c Hc. *)\n  (*     simpl in *. *)\n  (*     destruct H as [? ? ? ? Hsup]. *)\n  (*     pose proof (Hsup a) as Ha. *)\n  (*     apply Hg in Ha. *)\n  (*     2: { apply directed_f_ideal; auto. *)\n  (*          apply monotone_incl. } *)\n  (*     destruct Ha as [Hub Hlub]. *)\n  (*     apply Hlub. *)\n  (*     intro i; unfold compose. *)\n  (*     unfold compose in *. *)\n  (*     rewrite Hgf. *)\n  (*     2: { intro; apply cocontinuous_incl_ideal; auto. } *)\n  (*     eauto. *)\n  (* Qed. *)\n\n  (* (** Cocontinuously constrained uniqueness principle (more powerful). *) *)\n  (* Theorem co_unique_cocontinuous_P {C} `{CPO C} (P : A -> Prop) (f : basis A -> C) (g : A -> C) : *)\n  (*   cocontinuous P -> *)\n  (*   monotone f -> *)\n  (*   continuous g -> *)\n  (*   (forall b, P (incl b) -> g (incl b) === f b) -> *)\n  (*   forall a, P a -> g a === co f a. *)\n  (* Proof. *)\n  (*   unfold basis, compose in *; intros HP Hf Hg Hgf a HPa. *)\n  (*   symmetry. *)\n  (*   apply supremum_sup. *)\n  (*   split. *)\n  (*   - intro i; unfold compose. *)\n  (*     specialize (Hgf (ideal a i)). *)\n  (*     apply cocontinuous_incl_ideal with (i:=i) in HPa; auto. *)\n  (*     apply Hgf in HPa. *)\n  (*     rewrite <- HPa. *)\n  (*     apply continuous_monotone; auto. *)\n  (*     apply incl_ideal_le. *)\n  (*   - intros c Hc. *)\n  (*     simpl in *. *)\n  (*     destruct H as [? ? ? ? Hsup]. *)\n  (*     pose proof (Hsup a) as Ha. *)\n  (*     apply Hg in Ha. *)\n  (*     2: { apply directed_f_ideal; auto. *)\n  (*          apply monotone_incl. } *)\n  (*     destruct Ha as [Hub Hlub]. *)\n  (*     apply Hlub. *)\n  (*     intro i; unfold compose. *)\n  (*     unfold compose in *. *)\n  (*     rewrite Hgf. *)\n  (*     2: { apply cocontinuous_incl_ideal; auto. } *)\n  (*     eauto. *)\n  (* Qed. *)\n\n  (** The comorphism lemma. *)\n  Lemma co_exists_unique {C} `{CPO C} (f : basis A -> C) :\n    monotone f ->\n    co f ∘ incl === f /\\ forall g, continuous g -> g ∘ incl === f -> g === co f.\n  Proof.\n    intro Hf; split.\n    - apply co_incl; auto.\n    - intros; apply co_unique; auto with order.\n  Qed.\n\n  (** Useful variant. *)\n  Corollary co_unique' {C} `{CPO C} (f : basis A -> C) (g : A -> C) (a : A) :\n    monotone f ->\n    continuous g ->\n    (forall b, g (incl b) === f b) ->\n    g a === co f a.\n  Proof.\n    intros Hf Hg Hgf.\n    revert a; apply equ_arrow.\n    apply co_unique; auto with order.\n    apply equ_arrow; auto.\n  Qed.\n\n  Corollary Proper_coop {C} `{lCPO C} (f g : basis A -> C) :\n    antimonotone f ->\n    antimonotone g ->\n    f === g ->\n    coop f === coop g.\n  Proof.\n    intros Hf Hg Hfg.\n    unfold coop; unfold compose.\n    apply equ_arrow; intro x.\n    apply Proper_inf; eauto with order aCPO.\n    apply equ_arrow; intro i.\n    split; apply Hfg.\n  Qed.\n\n  Corollary Proper_coop' {C} `{lCPO C} (f g : basis A -> C) (x y : A) :\n    antimonotone f ->\n    antimonotone g ->\n    f === g ->\n    x === y ->\n    coop f x === coop g y.\n  Proof.\n    intros Hf Hg Hfg Hxy.\n    unfold antimonotone in Hf.\n    rewrite Hxy; clear Hxy.\n    revert y; apply equ_arrow, Proper_coop; auto.\n  Qed.\n\n  Theorem coop_unique {C} `{lCPO C} (f : basis A -> C) (g : A -> C) :\n    antimonotone f ->\n    cocontinuous g ->\n    g ∘ incl === f ->\n    g === coop f.\n  Proof.\n    intros Hf Hg Hfg.\n    etransitivity.\n    2: { apply Proper_coop; auto.\n         2: { apply Hfg. }\n         apply monotone_antimonotone_compose; auto with order aCPO. }\n    apply equ_arrow.\n    intro x.\n    unfold coop.\n    assert (x === sup (incl ∘ ideal x)).\n    { symmetry; apply supremum_sup, supremum_ideal. }\n    assert (Hgx: g x === g (sup (incl ∘ ideal x))).\n    { apply Proper_antimonotone_equ; auto.\n      apply cocontinuous_antimonotone; auto. }\n    rewrite Hgx.\n    rewrite cocontinuous_sup; auto.\n    - reflexivity.\n    - apply directed_f_ideal, monotone_incl.\n  Qed.\n\n  Corollary coop_unique_ext {C} `{o : OType C} `{@lCPO C o} `{@ExtType C o}\n    (f : basis A -> C) (g : A -> C) :\n    antimonotone f ->\n    cocontinuous g ->\n    g ∘ incl = f ->\n    g = coop f.\n  Proof.\n    intros Hf Hg Heq; apply ext, coop_unique; auto; rewrite Heq; reflexivity.\n  Qed.\n\n  (* (** Cocontinuously constrained uniqueness principle (more powerful). *) *)\n  (* Theorem coop_unique_constrained {C} `{lCPO C} (P : A -> Prop) (f : basis A -> C) (g : A -> C) : *)\n  (*   cocontinuous P -> *)\n  (*   antimonotone f -> *)\n  (*   cocontinuous g -> *)\n  (*   (forall b, P (incl b) -> g (incl b) === f b) -> *)\n  (*   forall a, P a -> g a === coop f a. *)\n  (* Proof. *)\n  (*   unfold basis, compose in *; intros HP Hf Hg Hgf a HPa. *)\n  (*   symmetry. *)\n  (*   apply infimum_inf. *)\n  (*   split. *)\n  (*   - intro i; unfold compose. *)\n  (*     specialize (Hgf (ideal a i)). *)\n  (*     apply cocontinuous_incl_ideal with (i:=i) in HPa; auto. *)\n  (*     apply Hgf in HPa. *)\n  (*     rewrite <- HPa. *)\n  (*     apply cocontinuous_antimonotone; auto. *)\n  (*     apply incl_ideal_le. *)\n  (*   - intros c Hc. *)\n  (*     simpl in *. *)\n  (*     destruct H as [? ? ? ? Hsup]. *)\n  (*     pose proof (Hsup a) as Ha. *)\n  (*     apply Hg in Ha. *)\n  (*     2: { apply directed_f_ideal; auto. *)\n  (*          apply monotone_incl. } *)\n  (*     destruct Ha as [Hub Hlub]. *)\n  (*     apply Hlub. *)\n  (*     intro i; unfold compose. *)\n  (*     unfold compose in *. *)\n  (*     rewrite Hgf. *)\n  (*     2: { apply cocontinuous_incl_ideal; auto. } *)\n  (*     eauto. *)\n  (* Qed. *)\n\n  Corollary coop_unique' {C} `{lCPO C} (f : basis A -> C) (g : A -> C) (a : A) :\n    antimonotone f ->\n    cocontinuous g ->\n    (forall b, g (incl b) === f b) ->\n    g a === coop f a.\n  Proof.\n    intros Hf Hg Hgf.\n    revert a; apply equ_arrow.\n    apply coop_unique; auto.\n    apply equ_arrow; auto.\n  Qed.\n\n  (** The anticomorphism lemma. *)\n  Lemma coop_exists_unique {C} `{lCPO C} (f : basis A -> C) :\n    antimonotone f ->\n    coop f ∘ incl === f /\\ forall g, cocontinuous g -> g ∘ incl === f -> g === coop f.\n  Proof.\n    intro Hf; split.\n    - apply coop_incl; auto.\n    - intros; apply coop_unique; auto.\n  Qed.\n\n  Lemma monotone_co_f {C} `{CPO C} (f g : basis A -> C) :\n    monotone f ->\n    monotone g ->\n    f ⊑ g ->\n    co f ⊑ co g.\n  Proof.\n    intros Hf Hg Hfg t.\n    apply ge_sup.\n    { apply directed_f_ideal; auto. }\n    intro i.\n    apply le_sup with (i:=i).\n    { apply directed_f_ideal; auto. }\n    apply Hfg.\n  Qed.\n\n  Lemma monotone_coop_f {C} `{lCPO C} (f g : basis A -> C) :\n    antimonotone f ->\n    antimonotone g ->\n    f ⊑ g ->\n    coop f ⊑ coop g.\n  Proof.\n    intros Hf Hg Hfg t.\n    apply le_inf.\n    { apply downward_directed_f_ideal; auto. }\n    intro i.\n    apply ge_inf with (i:=i).\n    { apply downward_directed_f_ideal; auto. }\n    apply Hfg.\n  Qed.\n\n  (** Two comorphisms are equal whenever their initial morphisms\n      are. Alternate version of the uniqueness property that is\n      sometimes useful. *)\n  Corollary Proper_co {C} `{CPO C} (f g : basis A -> C) :\n    monotone f ->\n    monotone g ->\n    f === g ->\n    co f === co g.\n  Proof.\n    intros Hf Hg Hfg.\n    apply co_unique; auto with order aCPO.\n    rewrite <- Hfg.\n    apply equ_arrow; intro b.\n    apply co_incl'; auto.\n  Qed.\n\n  Corollary Proper_co' {C} `{CPO C} (f g : basis A -> C) (x y : A) :\n    monotone f ->\n    monotone g ->\n    f === g ->\n    x === y ->\n    co f x === co g y.\n  Proof.\n    intros Hf Hg Hfg Hxy.\n    unfold monotone in Hf.\n    rewrite Hxy; clear Hxy.\n    revert y; apply equ_arrow, Proper_co; auto.\n  Qed.\n\n  Corollary Proper_co_ext {C} `{oC: OType C} `{@CPO _ oC} `{@ExtType _ oC}\n    (f g : basis A -> C) (x : A) :\n    monotone f ->\n    monotone g ->\n    f = g ->\n    co f x = co g x.\n  Proof.\n    intros Hf Hg Hfg.\n    apply ext, Proper_co'; auto.\n    - rewrite Hfg; reflexivity.\n    - reflexivity.\n  Qed.\n\n  Theorem co_intro (P : basis A -> Prop) (a : A) (i : nat) :\n    monotone P ->\n    P (ideal a i) ->\n    co P a.\n  Proof.\n    intros Hmono HP; unfold co.\n    assert (Hch: directed (P ∘ ideal a)).\n    { apply directed_f_ideal; auto. }\n    generalize (sup_spec (P ∘ ideal a) Hch).\n    intros [Hub Hlub].\n    eapply Hub; eauto.\n  Qed.\n\n  Theorem coop_intro (P : basis A -> Prop) (a : A) :\n    antimonotone P ->\n    (forall i, P (ideal a i)) ->\n    coop P a.\n  Proof.\n    intros Hmono HP; unfold coop.\n    assert (Hch: downward_directed (P ∘ ideal a)).\n    { apply downward_directed_f_ideal; auto. }\n    generalize (inf_spec (P ∘ ideal a) Hch).\n    intros [Hub Hlub].\n    unfold lower_bound in Hub.\n    simpl in *; unfold flip, impl in *.\n    eapply Hlub; eauto.\n    intro i; simpl; unfold flip, impl.\n    intro Hx; apply HP.\n  Qed.\n\n  Theorem co_elim (P : basis A -> Prop) (a : A) :\n    monotone P ->\n    co P a ->\n    exists i, P (ideal a i).\n  Proof.\n    intros Hmono HP; unfold co.\n    assert (Hch: directed (P ∘ ideal a)).\n    { apply directed_f_ideal; auto. }\n    generalize (sup_spec (P ∘ ideal a) Hch).\n    intros [Hub Hlub].\n    apply Hlub; auto.\n    intros i Hi; exists i; auto.\n  Qed.\n\n  Theorem coop_elim (P : basis A -> Prop) (a : A) :\n    antimonotone P ->\n    coop P a ->\n    forall i, P (ideal a i).\n  Proof.\n    intros Hmono HP; unfold coop.\n    assert (Hch: downward_directed (P ∘ ideal a)).\n    { apply downward_directed_f_ideal; auto. }\n    generalize (inf_spec (P ∘ ideal a) Hch).\n    intros [Hub Hlub] i.\n    apply Hub, HP.\n  Qed.\n\n  Theorem co_intro2 {C} (R : basis A -> C -> Prop) (a : A) (c : C) (i : nat) :\n    monotone R ->\n    R (ideal a i) c ->\n    co R a c.\n  Proof.\n    intros Hmono HR; unfold co.\n    assert (Hch: directed (R ∘ ideal a)).\n    { apply directed_f_ideal; auto. }\n    generalize (sup_spec (R ∘ ideal a) Hch).\n    intros [Hub Hlub].\n    eapply Hub; eauto.\n  Qed.\n  \n  Theorem coop_intro2 {C} (R : basis A -> C -> Prop) (a : A) (c : C) :\n    antimonotone R ->\n    (forall i, R (ideal a i) c) ->\n    coop R a c.\n  Proof.\n    intros Hmono HR; unfold coop.\n    assert (Hch: downward_directed (R ∘ ideal a)).\n    { apply downward_directed_f_ideal; auto. }\n    generalize (inf_spec (R ∘ ideal a) Hch).\n    intros [Hub Hlub].\n    unfold upper_bound in Hub.\n    simpl in *; unfold flip, impl in *.\n    eapply Hlub with (x := (fun x => forall i, R (ideal a i) x)).\n    { intros i x Hx; apply Hx. }\n    auto.\n  Qed.\n  \n  Theorem co_elim2 {C} (R : basis A -> C -> Prop) (a : A) (c : C) :\n    monotone R ->\n    co R a c ->\n    exists i, R (ideal a i) c.\n  Proof.\n    intros Hmono HR; unfold co.\n    assert (Hch: directed (R ∘ ideal a)).\n    { apply directed_f_ideal; auto. }\n    generalize (sup_spec (R ∘ ideal a) Hch).\n    intros [Hub Hlub].\n    unfold upper_bound in Hub.\n    assert (Hx: upper_bound (fun c => exists i, R (ideal a i) c) (R ∘ ideal a)).\n    { intro i; exists i; auto. }\n    apply Hlub in Hx.\n    apply Hx; auto.\n  Qed.\n\n  Theorem coop_elim2 {C} (R : basis A -> C -> Prop) (a : A) (c : C) :\n    antimonotone R ->\n    coop R a c ->\n    forall i, R (ideal a i) c.\n  Proof.\n    intros Hmono HR; unfold coop.\n    assert (Hch: downward_directed (R ∘ ideal a)).\n    { apply downward_directed_f_ideal; auto. }\n    generalize (inf_spec (R ∘ ideal a) Hch).\n    intros [Hub Hlub] i.\n    apply Hub, HR.\n  Qed.\n\n  Lemma coop_elim2' {C} (R : basis A -> C -> Prop) (a : A) (c : C) :\n    antimonotone R ->\n    coop R a c ->\n    forall i, R (ideal a i) c.\n  Proof.\n    intros Hmono HR; unfold coop.\n    assert (Hch: downward_directed (R ∘ ideal a)).\n    { apply downward_directed_f_ideal; auto. }\n    generalize (inf_spec (R ∘ ideal a) Hch).\n    intros [Hub Hlub] i.\n    apply Hub, HR.\n  Qed.\n\n  (** Every continuous function is a comorphism that is fully\n      determined by its behavior on basis elements. *)\n  Corollary continuous_co_incl {C} `{CPO C} (g : A -> C) :\n    continuous g ->\n    g === co (g ∘ incl).\n  Proof.\n    intro Hg.\n    apply equ_arrow; intro a.\n    unfold co, compose.\n    symmetry; apply supremum_sup.\n    apply Hg.\n    { apply directed_f_ideal, monotone_incl. }\n    apply supremum_ideal.\n  Qed.\n\n  Theorem cocontinuous_coop_incl {C} `{lCPO C} (g : A -> C) :\n    cocontinuous g ->\n    g === coop (g ∘ incl).\n  Proof.\n    intro Hg.\n    apply equ_arrow; intro a.\n    unfold coop, compose.\n    symmetry; apply infimum_inf.\n    apply Hg.\n    { apply directed_f_ideal, monotone_incl. }\n    apply supremum_ideal.\n  Qed.\n\n  Corollary continuous_ind {C} `{CPO C} (f : A -> C) (g : A -> C) :\n    continuous f ->\n    continuous g ->\n    f ∘ incl === g ∘ incl ->\n    f === g.\n  Proof.\n    intros Hf Hg Hfg.\n    pose proof Hf as Hf'.\n    apply continuous_co_incl in Hf'.\n    rewrite Hf'.\n    rewrite Proper_co.\n    { symmetry; apply continuous_co_incl; auto. }\n    { apply monotone_compose.\n      - apply monotone_incl.\n      - apply continuous_monotone; auto. }\n    { apply monotone_compose.\n      - apply monotone_incl.\n      - apply continuous_monotone; auto. }\n    auto.\n  Qed.\n\n  Corollary cocontinuous_ind {C} `{lCPO C} (f : A -> C) (g : A -> C) :\n    cocontinuous f ->\n    cocontinuous g ->\n    f ∘ incl === g ∘ incl ->\n    f === g.\n  Proof.\n    intros Hf Hg Hfg.\n    pose proof Hf as Hf'.\n    apply cocontinuous_coop_incl in Hf'.\n    rewrite Hf'.\n    rewrite Proper_coop.\n    { symmetry; apply cocontinuous_coop_incl; auto. }\n    { apply monotone_antimonotone_compose.\n      - apply monotone_incl.\n      - apply cocontinuous_antimonotone; auto. }\n    { apply monotone_antimonotone_compose.\n      - apply monotone_incl.\n      - apply cocontinuous_antimonotone; auto. }\n    auto.\n  Qed.\n\n  (* Corollary Proper_co_R {C} `{CPO C} (f g : basis A -> C) (R : basis A -> A -> Prop) (a b : A) : *)\n  (*   antimonotone R -> *)\n  (*   monotone f -> *)\n  (*   monotone g -> *)\n  (*   (forall i, P b -> f b === g b) -> *)\n  (*   coop P a -> *)\n  (*   co f a === co g b. *)\n  (* Proof. *)\n  (*   intros HP Hf Hg Hfg HPa. *)\n  (*   eapply co_unique_cocontinuous_P; eauto with aCPO order. *)\n  (*   intros Hi i. *)\n  (*   rewrite co_incl'; auto. *)\n  (*   apply Hfg. *)\n  (*   eapply coop_elim in HPa; eauto. *)\n  (* Qed. *)\n\n  (* Corollary Proper_co_P {C} `{CPO C} (f g : basis A -> C) (P : basis A -> Prop) (a : A) : *)\n  (*   antimonotone P -> *)\n  (*   monotone f -> *)\n  (*   monotone g -> *)\n  (*   (forall b, P b -> f b === g b) -> *)\n  (*   coop P a -> *)\n  (*   co f a === co g a. *)\n  (* Proof. *)\n  (*   intros HP Hf Hg Hfg HPa. *)\n  (*   eapply co_unique_cocontinuous_P; eauto with aCPO order. *)\n  (*   intros Hi i. *)\n  (*   rewrite co_incl'; auto. *)\n  (*   apply Hfg. *)\n  (*   eapply coop_elim in HPa; eauto. *)\n  (* Qed. *)\n\n  (* Corollary Proper_co_P_ext {C} `{oC: OType C} `{@CPO _ oC} `{@ExtType _ oC} *)\n  (*   (f g : basis A -> C) (P : basis A -> Prop) (a : A) : *)\n  (*   antimonotone P -> *)\n  (*   monotone f -> *)\n  (*   monotone g -> *)\n  (*   (forall b, P b -> f b = g b) -> *)\n  (*   coop P a -> *)\n  (*   co f a = co g a. *)\n  (* Proof. *)\n  (*   intros HP Hf Hg Hfg HPa. *)\n  (*   apply ext; eapply Proper_co_P; eauto. *)\n  (*   intros b HPb; rewrite Hfg; auto; reflexivity. *)\n  (* Qed. *)\nEnd aCPO.\n\n#[global] Hint Resolve directed_f_ideal : aCPO.\n#[global] Hint Resolve monotone_incl : aCPO.\n#[global] Hint Resolve monotone_co : aCPO.\n#[global] Hint Resolve continuous_co : aCPO.\n#[global] Hint Resolve antimonotone_coop : aCPO.\n#[global] Hint Resolve cocontinuous_coop : aCPO.\n\n(** Fusion rule for comorphism composition. A comorphism can be\n    extended by a continuous function at the front, resulting in a new\n    comorphism. I.e., given monotone f and continuous g:\n\n    [ g ∘ co f = co (g ∘ f) ]\n\n    An immediate consequence is that any chain of continuous function\n    compositions can be written as a single comorphism as long as the\n    rightmost (the one directly receiving the input) function in the\n    chain is a comorphism. We only need to maintain an algebraic hold\n    over the input space.  *)\n\nTheorem co_co {A aB B C} `{aCPO A aB} `{CPO B} `{CPO C}\n  (f : basis A -> B) (g : B -> C) :\n  monotone f ->\n  wcontinuous g ->\n  g ∘ co f === co (g ∘ f).\nProof.\n  intros Hf Hg.\n  unfold co, compose.\n  apply equ_arrow; intro t.\n  assert (Heq: g (sup (fun x : nat => f (ideal t x))) ===\n                 sup (fun i => g (f (ideal t i)))).\n  { apply wcontinuous_sup; auto; apply chain_f_ideal; auto. }\n  rewrite Heq; clear Heq.\n  reflexivity.\nQed.\n\n(** Pointwise variant of the fusion rule. *)\nCorollary co_co' {A aB B C} `{aCPO A aB} `{CPO B} `{CPO C}\n  (f : basis A -> B) (g : B -> C) (x : A) :\n  monotone f ->\n  wcontinuous g ->\n  g (co f x) === co (g ∘ f) x.\nProof.\n  intros Hf Hg; revert x; apply equ_arrow, co_co; auto with aCPO.\nQed.\n\n(** ExtType variant of fusion rule. *)\nCorollary co_co_ext {A aB B C} `{aCPO A aB} `{CPO B}\n  `{oC : OType C} `{@CPO _ oC} `{@ExtType _ oC}\n  (f : basis A -> B) (g : B -> C) (x : A) :\n  monotone f ->\n  wcontinuous g ->\n  g (co f x) = co (g ∘ f) x.\nProof. intros Hf Hg; apply ext, co_co'; auto. Qed.\n\nCorollary co_co'' {A aB B bB C} `{aCPO A aB} `{aCPO B bB} `{CPO C}\n  (f : basis A -> B) (g : basis B -> C) (x : A) :\n  monotone f ->\n  monotone g ->\n  co g (co f x) === co (co g ∘ f) x.\nProof.\n  intros Hf Hg; revert x; apply equ_arrow, co_co; auto with aCPO order.\nQed.\n\nTheorem coop_coop {A aB B C} `{aCPO A aB} `{lCPO B} `{lCPO C}\n  (f : basis A -> B) (g : B -> C) :\n  antimonotone f ->\n  dec_continuous g ->\n  g ∘ coop f === coop (g ∘ f).\nProof.\n  intros Hf Hg.\n  unfold co, coop, compose.\n  apply equ_arrow; intro t.\n  assert (Heq: g (inf (fun x : nat => f (ideal t x))) ===\n                 inf (fun i => g (f (ideal t i)))).\n  { apply dec_continuous_inf; auto.\n    apply downward_directed_f_ideal; auto. }\n  rewrite Heq; clear Heq.\n  reflexivity.\nQed.\n\nTheorem co_coop {A aB B C} `{aCPO A aB} `{CPO B} `{lCPO C}\n  (f : basis A -> B) (g : B -> C) :\n  monotone f ->\n  cocontinuous g ->\n  g ∘ co f === coop (g ∘ f).\nProof.\n  intros Hf Hg.\n  unfold co, coop, compose.\n  apply equ_arrow; intro t.\n  assert (Heq: g (sup (fun x : nat => f (ideal t x))) ===\n                 inf (fun i => g (f (ideal t i)))).\n  { apply cocontinuous_sup; auto.\n    apply directed_f_ideal; auto. }\n  rewrite Heq; clear Heq.\n  reflexivity.\nQed.\n\n(** Pointwise variant. *) \nCorollary co_coop' {A aB B C} `{aCPO A aB} `{CPO B} `{lCPO C}\n  (f : basis A -> B) (g : B -> C) (a : A) :\n  monotone f ->\n  cocontinuous g ->\n  g (co f a) === coop (g ∘ f) a.\nProof.\n  intros Hf Hg; revert a; apply equ_arrow.\n  apply co_coop; auto with aCPO.\nQed.\n\nTheorem coop_co {A aB B C} `{aCPO A aB} `{lCPO B} `{CPO C}\n  (f : basis A -> B) (g : B -> C) :\n  antimonotone f ->\n  dec_cocontinuous g ->\n  g ∘ coop f === co (g ∘ f).\nProof.\n  intros Hf Hg.\n  unfold co, coop, compose.\n  apply equ_arrow; intro t.\n  assert (Heq: g (inf (fun x : nat => f (ideal t x))) ===\n                 sup (fun i => g (f (ideal t i)))).\n  { apply dec_cocontinuous_inf; auto.\n    apply downward_directed_f_ideal; auto. }\n  rewrite Heq; clear Heq.\n  reflexivity.\nQed.\n\n(** Pointwise variant. *) \nCorollary coop_co' {A aB B C} `{aCPO A aB} `{lCPO B} `{CPO C}\n  (f : basis A -> B) (g : B -> C) (a : A) :\n  antimonotone f ->\n  dec_cocontinuous g ->\n  g (coop f a) === co (g ∘ f) a.\nProof.\n  intros Hf Hg; revert a; apply equ_arrow.\n  apply coop_co; auto with aCPO.\nQed.\n\nCorollary co_coP {A aB B} `{aCPO A aB} `{CPO B}\n  (f : basis A -> B) (g : B -> Prop) (x : A) :\n  monotone f ->\n  continuous g ->\n  g (co f x) <-> co (g ∘ f) x.\nProof. intros Hf Hg; apply equ_iff, co_co'; auto with order. Qed.\n\nTheorem co_coopP {A aB B C} `{aCPO A aB} `{CPO B} `{lCPO C}\n  (f : basis A -> B) (g : B -> Prop) (a : A) :\n  monotone f ->\n  cocontinuous g ->\n  g (co f a) <-> coop (g ∘ f) a.\nProof. intros Hf Hg; apply equ_iff, co_coop'; auto. Qed.\n\nCorollary coop_coP {A aB B} `{aCPO A aB} `{lCPO B}\n  (f : basis A -> B) (g : B -> Prop) (x : A) :\n  antimonotone f ->\n  dec_cocontinuous g ->\n  g (coop f x) <-> co (g ∘ f) x.\nProof.\n  intros Hf Hg.\n  cut (g (coop f x) === co (g ∘ f) x).\n  { firstorder. }\n  revert x; apply equ_arrow.\n  apply coop_co; auto.\nQed.\n\nLemma co_incl_id {A B} `{aCPO A B} :\n  co incl === @id A.\nProof.\n  symmetry; apply co_unique; auto with order.\n  - apply monotone_incl.\n  - reflexivity.\nQed.\n\nLemma co_incl_id' {A B} `{aCPO A B} (x : A) :\n  co incl x === x.\nProof. revert x; apply equ_arrow, co_incl_id. Qed.\n\nLtac cointro := try eapply co_intro; try eapply coop_intro.\nLtac cointro2 := try eapply co_intro2; try eapply coop_intro2.\nLtac coelim H := try eapply co_elim in H; try eapply coop_elim in H.\nLtac coelim2 := try eapply co_elim2; try eapply coop_elim2.\n", "meta": {"author": "bagnalla", "repo": "algco", "sha": "433836e4a0743c0443d530913769a00549b6993a", "save_path": "github-repos/coq/bagnalla-algco", "path": "github-repos/coq/bagnalla-algco/algco-433836e4a0743c0443d530913769a00549b6993a/aCPO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6841074601015404}}
{"text": "Require Import Coq.Bool.Bool.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import ExtLib.Tactics.Consider.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nClass CmpDec (T : Type) (equ : T -> T -> Prop) (ltu : T -> T -> Prop) : Type :=\n{ cmp_dec : T -> T -> comparison }.\n\nClass CmpDec_Correct T (equ ltu : T -> T -> Prop) (ED : CmpDec equ ltu) : Prop :=\n{ cmp_dec_correct : forall x y : T, \n  match cmp_dec x y with\n    | Eq => equ x y\n    | Lt => ltu x y\n    | Gt => ltu y x\n  end }.\n\nInductive cmp_case (P Q R : Prop) : comparison -> Prop :=\n| CaseEq : P -> cmp_case P Q R Eq\n| CaseLt : Q -> cmp_case P Q R Lt\n| CaseGt : R -> cmp_case P Q R Gt.\n\nSection pair.\n  Variable T U : Type.\n  Variables eqt ltt : T -> T -> Prop.\n  Variables equ ltu : U -> U -> Prop.\n\n  Definition eq_pair (a b : T * U) : Prop :=\n    eqt (fst a) (fst b) /\\ equ (snd a) (snd b).\n\n  Definition lt_pair (a b : T * U) : Prop :=\n    ltt (fst a) (fst b) \\/ (eqt (fst a) (fst b) /\\ ltu (snd a) (snd b)).\n\n  Variable cdt : CmpDec eqt ltt.\n  Variable cdu : CmpDec equ ltu.\n\n  Instance CmpDec_pair : CmpDec eq_pair lt_pair :=\n  { cmp_dec := fun a b =>\n    let '(al,ar) := a in\n    let '(bl,br) := b in\n    match cmp_dec al bl with\n      | Eq => cmp_dec ar br \n      | x => x \n    end }.\n\n  Variable cdtC : CmpDec_Correct cdt.\n  Variable cduC : CmpDec_Correct cdu.\n  Variable Symmetric_eqt : Symmetric eqt.\n\n  Instance CmpDec_Correct_pair : CmpDec_Correct CmpDec_pair.\n  Proof.\n    constructor. destruct x; destruct y; unfold eq_pair, lt_pair; simpl in *.\n    generalize (cmp_dec_correct t t0); destruct (cmp_dec t t0); simpl; intros; auto.\n    generalize (cmp_dec_correct u u0); destruct (cmp_dec u u0); simpl; intros; auto.\n  Qed.\nEnd pair.\n\n", "meta": {"author": "coq-community", "repo": "coq-ext-lib", "sha": "4811a83db9ccd81f4dcbf77eeff0484dfb21a48b", "save_path": "github-repos/coq/coq-community-coq-ext-lib", "path": "github-repos/coq/coq-community-coq-ext-lib/coq-ext-lib-4811a83db9ccd81f4dcbf77eeff0484dfb21a48b/theories/Core/CmpDec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648676, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6841074601015403}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\nRequire Import mathcomp.ssreflect.ssrbool.\nRequire Import mathcomp.ssreflect.eqtype.\nRequire Import mathcomp.ssreflect.ssrnat.\n\nSection HilbertSaxiom.\n  Variables A B C : Prop.\n  Lemma HilbertS : (A -> B -> C) -> (A -> B) -> A -> C.\n  Proof.\n    (* move => is equivalent to move=>, \n     * equivalent to intros hAiBiC hAiB hA\n     * moves hypotheses into context\n     * move is a tactic, => is a tactical \n     * move does nothing, *)\n    move => hAiBiC hAiB hA.\n    (* move : is equivalent to move:,\n     * equivalent to revert hAiBiC\n     * almost equivalent to generalize hAiBiC (which leaves in context) *)\n    move : hAiBiC.\n    apply.\n      by [].\n    (* apply : hAiB. is equivalent to move : hAiB. apply. *)\n    (* move: hAiB; apply. *)\n      (* move : hAiB. apply. by []. is equivalent to the below. *)\n    by apply: hAiB.\n  Qed.\n\n  Hypotheses (hAiBiC : A -> B -> C) (hAiB : A -> B) (hA : A).\n  Lemma HilbertS2 : C.\n  Proof.\n    (* only apply: hA to first subgoal generated. *)\n    apply: hAiBiC; first by apply: hA.\n    (* exact is kind of equivalent to apply. by []. *)\n    (* below is equivalent to move: hAiB; exact. *)\n    exact : hAiB.\n  Qed.\n\n  Lemma HilbertS3 : C.\n  Proof.\n    (* apply: hAiBiC; last exact: hAiB; exact. *)\n    by [apply: hAiBiC; last exact: hAiB].\n  Qed.\n\n  Lemma HilbertS4 : C.\n  Proof.\n    exact: (hAiBiC _ (hAiB _)).\n  Qed.\n\n  Lemma HilbertS5 : C.\n  Proof.\n    exact: hAiBiC (hAiB _).\n  Qed.\n\n  Lemma HilbertS6 : C.\n  Proof.\n    exact: HilbertS5.\n  Qed.\n\nEnd HilbertSaxiom.\n\nSection Symmetric_Conjunction_Disjunction.\n  Lemma andb_sym : forall A B : bool, A && B -> B && A.\n  Proof.\n    case.\n    (* case; by []. is equivalent to below. *)\n    by case.  \n      by [].\n  Qed.\n\n  Lemma andb_sym2 : forall A B : bool, A && B -> B && A.\n  Proof.\n    by [case; case].\n  Qed.\n\n  Lemma andb_sym3 : forall A B : bool, A && B -> B && A.\n  Proof.\n    by do 2! case.\n  Qed.\n\n  Lemma and_sym : forall A B : Prop, A /\\ B -> B /\\ A.\n  Proof.\n    (* move => A1 B; case. is equvialent to move => A1 B []. wtf??? *)\n    by [move => A1 B []].\n  Qed.\n\n  Lemma or_sym : forall A B : Prop, A \\/ B -> B \\/ A.\n  Proof.\n    (* move => A B; case => [hA | hB]. is equivalent to \n     * move=> A B [hA | hB]. *)    \n    (* move : or_intror. apply. is equivalent to apply : or_intror. *)\n    by move=> A B [hA | hB]; [apply: or_intror | apply: or_introl].\n  Qed.\n\n  Lemma or_sym2 : forall A B : bool, A \\/ B -> B \\/ A.\n  Proof.\n    (* apply / orP.  the / means apply it to the goal. *)\n    (* move: AorB; move/orP. is equivalent to  move/orP : AorB. *)\n      by move=> [] [] AorB; apply/orP; move/orP : AorB.\n  Qed.\n\nEnd Symmetric_Conjunction_Disjunction.\n\n\nSection R_sym_trans.\n  Variables (D : Type) (R : D -> D -> Prop).\n  Hypothesis R_sym : forall x y, R x y -> R y x.\n  Hypothesis R_trans : forall x y z, R x y -> R y z -> R x z.\n  \n  Lemma refl_if : forall x : D, (exists y, R x y) -> R x x.\n  Proof.\n    (* move=> x; case=> y Rxy. equivalent to below *)\n    move=> x [y Rxy].\n      by apply: R_trans _ _ _ _ (R_sym _ y _).\n  Qed.\nEnd R_sym_trans.\n\n\nSection Smullyan_drinker.\n  Variables (D : Type)(P : D -> Prop).\n  Hypothesis (d : D) (EM : forall A, A \\/ ~A).\n\n  Lemma drinker : exists x, P x -> forall y, P y.\n  Proof.\n    (* case: (EM (exists y, ~P y)) is equivalent to move: (EM (exists y, ~P y)); case. *)\n    case: (EM (exists y, ~P y)) => [[y notPy]| nonotPy]; first by exists y.\n    (*\n      exists d => _ y.\n      case : (EM (P y)).\n        done.\n        move => notPy.\n    *)\n    exists d => _ y; case: (EM (P y)) => // notPy.\n    by case: nonotPy; exists y.\n  Qed.\n\n  Lemma drinker2 : exists x, P x -> forall y, P y.\n  Proof.\n    case: (EM (exists y, ~P y)) => [[y notPy]| nonotPy]; first by exists y.\n    exists d => _ y.\n    case : (EM (P y)).\n    + done.\n    + move => notPy.                                                                    \n      by case: nonotPy; exists y.\n  Qed.\n      \n  Lemma drinker_unfold : exists x, P x -> forall y, P y.\n  Proof.\n    (* case: (EM (exists y, ~P y)) is equivalent to move: (EM (exists y, ~P y)); case. *)\n    (* case: (EM (exists y, ~P y)) => [[y notPy]| nonotPy]; first by exists y. *)\n    move : (EM (exists y, ~P y)).\n    case.\n    + move => [y notPy].\n      exists y.\n        by [].\n    + move => nonotPy.\n\n      (* exists d => _ y; case: (EM (P y)) => // notPy. *)\n      exists d.\n      move => foo y.\n      move : (EM (P y)).\n      case => // notPy.\n    \n      (* by case: nonotPy; exists y. *)\n      move : nonotPy.\n      case.\n      exists y.\n        by [].\n  Qed.\nEnd Smullyan_drinker.\n\n\nSection Equality.\n  Variable f : nat -> nat.\n\n  Hypothesis f00 : f 0 = 0.\n  Lemma fkk : forall k, k = 0 -> f k = k.\n  Proof.\n    move => k k0.\n    by rewrite k0.\n  Qed.\n\n  Lemma fkk2 : forall k, k = 0 -> f k = k.\n  Proof.\n    (* move=> k hyp; rewrite {} hyp. by []. *)\n    by move=> k ->.\n  Qed.\n\n  Variables (D : eqType) (x y : D).\n  Lemma eq_prop_bool : x = y -> x == y.\n  Proof.\n      by move/eqP.\n  Qed.\n  \n  Lemma eq_bool_prop : x == y -> x = y.\n  Proof. by move/eqP. Qed.\nEnd Equality.\n\n\nSection Using_Definition.\n  Variable U : Type.\n  Definition set := U -> Prop.\n  Definition subset (A B : set) := forall x, A x -> B x.\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  Lemma subset_trans : transitive set subset.\n  Proof.\n    (* rewrite /transitive /subset. equivalent to unfold transitive, subset *)\n    (* rewrite /transitive /subset; move=> x y z subxy subyz t xt. *)\n    (*\n    rewrite / transitive.\n    rewrite / subset.\n    move => x y z subxy subyz t xt.\n    *)\n    rewrite /transitive /subset => x y z subxy subyz t xt.\n      by apply: subyz; apply: subxy.\n  Qed.\n\n  Lemma subset_trans2 : transitive set subset.\n  Proof.\n    (* move forces unfolding *)\n    move=> x y z subxy subyz t.\n      by move/subxy; move/subyz.\n  Qed.\nEnd Using_Definition.", "meta": {"author": "ml4tp", "repo": "gamepad", "sha": "7092f50a96eae9a862e72ecb8a55a217fa97723c", "save_path": "github-repos/coq/ml4tp-gamepad", "path": "github-repos/coq/ml4tp-gamepad/gamepad-7092f50a96eae9a862e72ecb8a55a217fa97723c/examples/tutorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.8740772450055545, "lm_q1q2_score": 0.6841074545102503}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_congruenceflip.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_lessthancongruence.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_outerconnectivity.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_trichotomy1 : \n   forall A B C D, \n   ~ Lt A B C D -> ~ Lt C D A B -> neq A B -> neq C D ->\n   Cong A B C D.\nProof.\nintros.\nassert (neq B A) by (conclude lemma_inequalitysymmetric).\nlet Tf:=fresh in\nassert (Tf:exists P, (BetS B A P /\\ Cong A P A B)) by (conclude lemma_extension);destruct Tf as [P];spliter.\nassert (BetS P A B) by (conclude axiom_betweennesssymmetry).\nassert (neq A P) by (forward_using lemma_betweennotequal).\nassert (neq P A) by (conclude lemma_inequalitysymmetric).\nlet Tf:=fresh in\nassert (Tf:exists E, (BetS P A E /\\ Cong A E C D)) by (conclude lemma_extension);destruct Tf as [E];spliter.\nassert (~ BetS A B E).\n {\n intro.\n assert (Cong A B A B) by (conclude cn_congruencereflexive).\n assert (Lt A B A E) by (conclude_def Lt ).\n assert (Lt A B C D) by (conclude lemma_lessthancongruence).\n contradict.\n }\nassert (~ BetS A E B).\n {\n intro.\n assert (Lt C D A B) by (conclude_def Lt ).\n contradict.\n }\nassert (eq E B) by (conclude lemma_outerconnectivity).\nassert (Cong A B A B) by (conclude cn_congruencereflexive).\nassert (Cong A B A E) by (conclude cn_equalitysub).\nassert (Cong A B C D) by (conclude lemma_congruencetransitive).\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_trichotomy1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.6839984227851776}}
{"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.\nRequire Import Maps.\n\nDefinition state := total_map nat.\n\nDefinition empty_state : state := t_empty 0.\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 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\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   => 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\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\n(* Examples *)\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 infinite_loop : com :=\n  WHILE BTrue DO\n    SKIP\n  END.\n\n(* ----------------------------------------------------------------- *)\n(** *** Operational Semantics *)\n(*\n\n                           ----------------                            (E_Skip)\n                           SKIP / st \\\\ st\n\n                           aeval st a1 = n\n                   --------------------------------                     (E_Ass)\n                   x := a1 / st \\\\ (t_update st x n)\n\n                           c1 / st \\\\ st'\n                          c2 / st' \\\\ st''\n                         -------------------                            (E_Seq)\n                         c1;;c2 / st \\\\ st''\n\n                          beval st b1 = true\n                           c1 / st \\\\ st'\n                -------------------------------------                (E_IfTrue)\n                IF b1 THEN c1 ELSE c2 FI / st \\\\ st'\n\n                         beval st b1 = false\n                           c2 / st \\\\ st'\n                -------------------------------------               (E_IfFalse)\n                IF b1 THEN c1 ELSE c2 FI / st \\\\ st'\n\n                         beval st b = false\n                    ------------------------------                 (E_WhileEnd)\n                    WHILE b DO c END / st \\\\ st\n\n                          beval st b = true\n                           c / st \\\\ st'\n                  WHILE b DO c END / st' \\\\ st''\n                  ---------------------------------               (E_WhileLoop)\n                    WHILE b DO c END / st \\\\ st''\n*)\n\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,\n      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_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 \"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  apply E_Seq with (t_update empty_state X 2).\n    apply E_Ass. reflexivity.\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    (t_update (t_update (t_update empty_state X 0) Y 1) Z 2).\nProof.\n  (* FILL IN HERE *) Admitted.\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  induction E1;\n           intros st2 E2; inversion E2; subst.\n  - (* E_Skip *) reflexivity.\n  - (* E_Ass *) reflexivity.\n  - (* E_Seq *)\n    assert (st' = st'0) as EQ1.\n    { (* Proof of assertion *) apply IHE1_1; assumption. }\n    subst st'0.\n    apply IHE1_2. assumption.\n  - (* E_IfTrue, b1 evaluates to true *)\n      apply IHE1. assumption.\n  - (* E_IfTrue,  b1 evaluates to false (contradiction) *)\n      rewrite H in H5. inversion H5.\n  - (* E_IfFalse, b1 evaluates to true (contradiction) *)\n    rewrite H in H5. inversion H5.\n  - (* E_IfFalse, b1 evaluates to false *)\n      apply IHE1. assumption.\n  - (* E_WhileEnd, b1 evaluates to false *)\n    reflexivity.\n  - (* E_WhileEnd, b1 evaluates to true (contradiction) *)\n    rewrite H in H2. inversion H2.\n  - (* E_WhileLoop, b1 evaluates to false (contradiction) *)\n    rewrite H in H4. inversion H4.\n  - (* E_WhileLoop, b1 evaluates to true *)\n      assert (st' = st'0) as EQ1.\n      { (* Proof of assertion *) apply IHE1_1; assumption. }\n      subst st'0.\n      apply IHE1_2. assumption.  Qed.\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. clear Heval. simpl.\n  apply t_update_eq.\nQed.\n\nTheorem loop_never_stops : forall st st',\n  ~(infinite_loop / st \\\\ st').\nProof.\n  intros st st' contra. unfold infinite_loop in contra.\n  remember (WHILE BTrue DO SKIP END) as loopdef\n           eqn:Heqloopdef.\n  (* FILL IN HERE *) Admitted.\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", "meta": {"author": "ghulette", "repo": "small-step", "sha": "4d2316fab854cffe094dddea9d6795b8a332f953", "save_path": "github-repos/coq/ghulette-small-step", "path": "github-repos/coq/ghulette-small-step/small-step-4d2316fab854cffe094dddea9d6795b8a332f953/Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.68399842095369}}
{"text": "From Undecidability.Synthetic Require Import DecidabilityFacts EnumerabilityFacts ListEnumerabilityFacts.\nFrom Undecidability.Shared Require Import Dec.\n\nRequire Import List.\nImport ListNotations.\n\n#[local] Coercion dec2bool P (d: dec P) := if d then true else false.\n\nLemma enumerable_enum {X} {p : X -> Prop} :\n  enumerable p <-> list_enumerable p.\nProof.\n  split. eapply enumerable_list_enumerable. eapply list_enumerable_enumerable.\nQed.\n\nLemma enumerable_disj X (p q : X -> Prop) :\n  enumerable p -> enumerable q -> enumerable (fun x => p x \\/ q x).\nProof.\n  intros [Lp H] % enumerable_enum [Lq H0] % enumerable_enum.\n  eapply enumerable_enum.\n  exists (fix f n := match n with 0 => [] | S n => f n ++ (Lp n) ++ (Lq n) end).\n  intros x. split.\n  - intros [H1 | H1].\n    * eapply H in H1 as [m]. exists (1 + m). cbn.\n      apply in_or_app. right. apply in_or_app. now left.\n    * eapply H0 in H1 as [m]. exists (1 + m). cbn.\n      apply in_or_app. right. apply in_or_app. now right.\n  - intros [m]. induction m.\n    * inversion H1.\n    * apply in_app_iff in H1.\n      destruct H1 as [?|H1]; [now auto|].\n      apply in_app_iff in H1.\n      unfold list_enumerator in *; firstorder easy.\nQed.\n\nLemma enumerable_conj X (p q : X -> Prop) :\n  discrete X -> enumerable p -> enumerable q -> enumerable (fun x => p x /\\ q x).\nProof.\n  intros [] % discrete_iff [Lp] % enumerable_enum [Lq] % enumerable_enum.\n  eapply enumerable_enum.\n  exists (fix f n := match n with 0 => [] | S n => f n ++ (filter (fun x => Dec (In x (cumul Lq n))) (cumul Lp n)) end).\n  intros x. split.\n  + intros []. eapply (list_enumerator_to_cumul H) in H1 as [m1].\n    eapply (list_enumerator_to_cumul H0) in H2 as [m2].\n    exists (1 + m1 + m2). cbn. apply in_or_app. right.\n    apply filter_In. split.\n    * eapply cum_ge'; eauto; lia.\n    * eapply Dec_auto. eapply cum_ge'; eauto; lia.\n  + intros [m]. induction m.\n    * inversion H1.\n    * apply in_app_iff in H1. destruct H1 as [?|H1]; [now auto|].\n      apply filter_In in H1. destruct H1 as [? H1].\n      split. \n      ** eapply (list_enumerator_to_cumul H). eauto.\n      ** destruct (Dec _) in H1; [|easy].\n         eapply (list_enumerator_to_cumul H0). eauto.\nQed.\n\nLemma projection X Y (p : X * Y -> Prop) :\n  enumerable p -> enumerable (fun x => exists y, p (x,y)).\nProof.\n  intros [f].\n  exists (fun n => match f n with Some (x, y) => Some x | None => None end).\n  intros; split.\n  - intros [y ?]. eapply H in H0 as [n]. exists n. now rewrite H0.\n  - intros [n ?]. destruct (f n) as [ [] | ] eqn:E; inversion H0; subst.\n    exists y. eapply H. eauto.\nQed.\n\nLemma projection' X Y (p : X * Y -> Prop) :\n  enumerable p -> enumerable (fun y => exists x, p (x,y)).\nProof.\n  intros [f].\n  exists (fun n => match f n with Some (x, y) => Some y | None => None end).\n  intros y; split.\n  - intros [x ?]. eapply H in H0 as [n]. exists n. now rewrite H0.\n  - intros [n ?]. destruct (f n) as [ [] | ] eqn:E; inversion H0; subst.\n    exists x. eapply H. eauto.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/Synthetic/MoreEnumerabilityFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782012, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.6839858785746402}}
{"text": "From Hammer Require Export Tactics Reflect.\nRequire Import Recdef.\n\nRequire Export List.\nImport List.ListNotations.\nOpen Scope list_scope.\n\nClass DecTotalOrder (A : Type) := {\n  leb : A -> A -> bool;\n  leb_total : forall x y, leb x y \\/ leb y x;\n  leb_antisym : forall x y, leb x y -> leb y x -> x = y;\n  leb_trans : forall x y z, leb x y -> leb y z -> leb x z }.\n\nLemma leb_refl `{DecTotalOrder} : forall x, leb x x.\nProof.\n  intro x; destruct (leb_total x x); auto.\nQed.\n\nLemma lem_neg_leb `{DecTotalOrder} :\n  forall x y, ~ (leb x y) -> leb y x.\nProof.\n  qauto use: leb_total.\nQed.\n\nDefinition leb_total_dec `{DecTotalOrder} : forall x y, {leb x y}+{leb y x}.\n  intros x y.\n  sdestruct (leb x y).\n  - left; constructor.\n  - right; destruct (leb_total x y); auto.\nDefined.\n\nDefinition eq_dec {A} `{DecTotalOrder A} : forall x y : A, {x = y}+{x <> y}.\n  intros x y.\n  sdestruct (leb x y).\n  - sdestruct (leb y x).\n    + auto using leb_antisym.\n    + sauto.\n  - sdestruct (leb y x).\n    + sauto.\n    + destruct (leb_total_dec x y); auto.\nDefined.\n\nDefinition eqb `{DecTotalOrder} x y : bool :=\n  if eq_dec x y then\n    true\n  else\n    false.\n\nDefinition ltb `{DecTotalOrder} x y : bool :=\n  leb x y && negb (eqb x y).\n\nDefinition leb_ltb_dec `{DecTotalOrder} x y : {leb x y}+{ltb y x}.\n  destruct (leb_total_dec x y).\n  - left; sauto.\n  - unfold ltb, negb, eqb.\n    destruct (eq_dec y x).\n    + left; sauto.\n    + right; sauto brefl: on.\nDefined.\n\nLemma lem_ltb_leb_incl `{DecTotalOrder} :\n  forall x y : A, ltb x y -> leb x y.\nProof.\n  sauto brefl: on unfold: ltb.\nQed.\n\nFunction lexb `{DecTotalOrder} l1 l2 :=\n  match l1 with\n  | [] => true\n  | x :: l1' =>\n    match l2 with\n    | [] => false\n    | y :: l2' =>\n      if eq_dec x y then\n        lexb l1' l2'\n      else\n        leb x y\n    end\n  end.\n\nInstance dto_list {A} `{DecTotalOrder A} : DecTotalOrder (list A).\nProof.\n  apply Build_DecTotalOrder with (leb := lexb).\n  - induction x; sauto.\n  - intros x y.\n    functional induction (lexb x y).\n    + sauto inv: list.\n    + sauto.\n    + sauto.\n    + sauto inv: - use: leb_antisym.\n  - intros x y.\n    functional induction (lexb x y); sauto.\nDefined.\n\nInstance dto_nat : DecTotalOrder nat.\nProof.\n  apply Build_DecTotalOrder with (leb := Nat.leb);\n    induction x; sauto.\nDefined.\n", "meta": {"author": "lukaszcz", "repo": "sortalgs", "sha": "6e03cf693b6ed23565db0949d647efb96410ae09", "save_path": "github-repos/coq/lukaszcz-sortalgs", "path": "github-repos/coq/lukaszcz-sortalgs/sortalgs-6e03cf693b6ed23565db0949d647efb96410ae09/order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029117, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.6839858779622722}}
{"text": "(******************************************************************************)\n(* Reference                                                                  *)\n(* - Saidak, F. (2006). A New Proof of Euclid's Theorem. The American         *)\n(*   Mathematical Monthly, 113(10), 937-938. doi:10.2307/27642094             *)\n(******************************************************************************)\n\nSet Warnings \"-notation-overridden\".\nFrom mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nFixpoint f i :=\n  match i with\n    0 => 1\n  | i'.+1 => f i' * (f i').+1\n  end.\n\nDefinition p i := pdiv (f i).+1.\n\nPrint pdiv.\nCompute pdiv 4861.\nLocate pdiv.\nCompute prime 4861.\nLocate \"%|\".\nLocate dvdn.\nLocate Order.le.\nPrint dvdn.\nCompute dvdn 5 10.\nLocate \"<=\".\nCompute p 4.\n\nLemma lem1 i : f i > 0.\nProof. by elim: i => //= i IH; rewrite muln_gt0 IH ltnS (ltnW IH). Qed.\n\nTheorem all_elements_of_p_are_prime i : prime (p i).\nProof. by apply: pdiv_prime; exact: lem1. Qed.\n\nLemma lem2 i j : i <= j -> f i %| f j.\nProof. by move/leP; elim: j / => //= j _; exact: dvdn_mulr. Qed.\n\nLemma lem3 i j : i < j -> p i %| f j.\nProof.\nmove=> lt_ij.\napply: (@dvdn_trans (f i.+1)); last by exact: lem2.\nby rewrite /=; apply: dvdn_mull; exact: pdiv_dvd.\nQed.\n\nTheorem all_elements_of_p_are_distinct i j : p i = p j -> i = j.\nProof.\ncase: (i =P j) => // /eqP.\nrewrite neq_ltn.\nwlog lt_ij : i j / i < j.\n  move=> H /orP [lt_ij | lt_ji] Epij; first by apply: H; rewrite ?lt_ij.\n  by symmetry; apply: H; rewrite ?lt_ji.\nmove=> _ Epij.\nexfalso.\nhave dvd_pi_fj := lem3 lt_ij.\nhave dvd_pj_fj := pdiv_dvd (f j).+1.\nhave /(coprime_dvdl dvd_pi_fj)/(coprime_dvdr dvd_pj_fj) := coprimenS (f j).\nhave prime_pi := all_elements_of_p_are_prime i.\nhave pi_neq_1 : p i != 1 by rewrite neq_ltn prime_gt1 // orbT.\nhave prime_pj := all_elements_of_p_are_prime j.\nrewrite (prime_coprime _ prime_pi).\nby move/(prime_nt_dvdP prime_pj pi_neq_1).\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/the_infinity_of_primes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.683959191977703}}
{"text": "(* STV with fractional transfer (ANU Union rules) as instance of generic vote counting. *)\n \n(* the first section is the generic part of the formalisation.*)\n(*the second section is the specialized part of the formalisation under the section \"unionCount\", which is formalisation of ANU_Union STV*)\n\n(*In the section unionCount, lines 163-1539 consist of lemmas and functions that we use to prove the two main theorems; measure decrease and rule application*)\n(*lines 1540-2590 consist of formalisation of rules of counting for ANU_STV and main theorems.*)\n(*the theorem Measure-decrease is separated into lemmas from line 1854 to line 2170*)\n(*the theorem Rule application begins from line 2251*)\n(*the theorem that is extracted is in line 2561*)\n\nRequire Import Coq.Init.Peano.\nRequire Import Notations.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Arith.Le.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.Numbers.NatInt.NZMul.\nRequire Import Coq.Structures.OrdersFacts.\nRequire Import Coq.ZArith.Znat. \nRequire Import Coq.QArith.QArith_base.\nRequire Import  Coq.QArith.QOrderedType.\nRequire Import QArith_base Equalities Orders OrdersTac.\nRequire Import Coq.Sorting.Permutation.\nRequire Import Wf.\nRequire Import Lexicographic_Product.\nRequire Import Qreduction.\nRequire Import Coq.Bool.Bool.\nRequire Import Inverse_Image. \nRequire Import Coq.Bool.Sumbool.\nRequire Import Coq.Sorting.Mergesort.\nImport ListNotations.\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Arith.Wf_nat.\nRequire Import Program.\nRequire Import  Recdef.\nAdd LoadPath \"/home/users/u5711205/Modular-STVCalculi/\".\nRequire Export Parameters.\n(*Import Params.\n*)\n(*Import Instantiation.*)\n\nModule B (X: Params).\n(* notation for type level existential quantifier *)\nNotation \"'existsT' x .. y , p\" := (sigT (fun x => .. (sigT (fun y => p)) ..))\n  (at level 200, x binder, right associativity,\n   format \"'[' 'existsT' '/ ' x .. y , '/ ' p ']'\")\n  : type_scope.\n\nClose Scope Q_scope.\n\n(*Variable cand: Type.*)\n\nModule RatOrder  <: TotalLeBool.\n\n  Definition t := ({v : list X.cand | (NoDup v) /\\ ( [] <> v)} * Q)%type. (* (A * Q)%type. *)\n  \n  Definition leb (r1 : t) (r2 : t) := \n    match Q_dec (snd r1) (snd r2) with\n    | inleft l => match l with\n                  | left _ =>   true \n                  | right _ => false\n                  end\n    | inright r => true\n    end.  \n \n  Theorem leb_total : forall r1 r2, is_true (leb r1 r2) \\/ is_true (leb r2 r1).\n  Proof.   \n    intros r1 r2. unfold is_true, leb.\n    destruct (Q_dec (snd r1) (snd r2)). destruct s. auto.\n    right.  destruct (Q_dec (snd r2) (snd r1)). destruct s. auto.\n    pose proof (Qlt_trans (snd r1) (snd r2) (snd r1) q0 q).\n    pose proof (Qlt_irrefl (snd r1)). unfold not in H0.\n    pose proof (H0 H). inversion H1. auto. auto.\n  Qed.\n  \nEnd RatOrder.\n\nModule Import QSort := Sort RatOrder.\n\n\n\nDefinition Rat_eq r1 r2 := Qeq_bool r1 r2.\n\n\n\nFixpoint countem {A: Type} y (xs: list (A * Q)) : nat :=\n   match xs with\n   | [] => (0)%nat\n   | x :: more => if Qeq_bool (snd x) y then S (countem y more) else (0)%nat\n   end.\n\nLemma countem_len :\n  forall (A : Type) (q : Q) (l : list (A * Q)), ((countem q l) <= length l)%nat.\nProof.\n  intros. induction l.\n  simpl. omega.\n  simpl. destruct (Qeq_bool (snd a) q). omega. omega.\nQed.\n  \nFixpoint take {A: Type} (y : nat) (xs: list (A * Q)) :=\n   match y, xs with\n   | O, _ => []\n   | S y', [] => []\n   | S y', x :: more => x :: take y' more\n   end.\n\nFixpoint skip {A: Type} y (xs: list (A * Q)) :=\n   match y, xs with\n   | O, _ => xs\n   | S y', [] => []\n   | S y', x :: more => skip y' more\n   end.\n\nLemma skip_bounded:\n   forall (A: Type) (y: nat) xs, (length (@skip A y xs) <= length xs)%nat.\nProof.\n   intros A y xs. revert y.\n   induction xs; intros; simpl.\n   - destruct y; simpl; omega.\n   - destruct y; simpl; try omega.\n     rewrite IHxs. omega.\nQed.\n\nLemma take_skip:\n   forall (A: Type) k (xs : list (A * Q)) , (take k xs ++ skip k xs = xs)%nat.\nProof.\n   intros A k xs. revert k.\n   induction xs; intros; simpl.\n   - destruct k; simpl; auto.\n   - destruct k; simpl; auto.\n     rewrite IHxs. auto.\nQed.\n\nFunction groupbysimple {A: Type} (xs: list (A * Q)) { measure length xs } :=\n   match xs with\n   | [] => []\n   | x :: more =>\n        let k := countem (snd x) more in\n        (x :: take k more) :: @groupbysimple A (skip k more)\n   end.\nProof.\n   intros.\n   simpl.\n   assert (length (skip (countem (snd x) more) more) <= length more)%nat by\n       apply skip_bounded. intuition.\nDefined.\n\n\nFixpoint concat {A: Type} (l : list (list A)) : list A :=\n  match l with\n  | nil => nil\n  | cons x l => x ++ concat l\n  end.\n\nLemma groupby_identity:\n   forall (A : Type) xs, concat (groupbysimple A xs) = xs.\nProof.\n  intros. \n  functional induction (groupbysimple A xs).\n  - simpl. auto.\n  - simpl. rewrite IHl. rewrite take_skip. auto.\nQed.\n\n\nLemma concat_rat:\n  forall (l : list ({v : list X.cand | (NoDup v) /\\ ( [] <> v)} * Q)) ,\n    length l = length (concat (groupbysimple _ (sort l))).\nProof.\n  intros l.\n  pose proof (groupby_identity _ (sort l)).\n  rewrite H.\n  pose proof (Permuted_sort l).\n  pose proof (Permutation_length).\n  pose proof (H1 _ l (sort l) H0).\n  auto.\nQed.\n\n(*Eval compute in groupbysimple _ [(1%nat,(3 # 1)%Q); (1%nat,(3 # 1)%Q); (1%nat,(2 # 1)%Q); (0%nat,(2 # 3)%Q); (1%nat,(2 # 1)%Q)].\nEval compute in groupbysimple _ [(1%nat, (3 # 1)%Q)].\n*)\n \nLemma groupby_notempty :\n  forall  (A : Type) (l : list (A * Q)),\n    l <> [] -> last (groupbysimple _ l) [] <> [].\nProof.\n  intros A l H.\n  functional induction (groupbysimple A l).\n  + firstorder. \n  + simpl in *.\n    remember (skip (countem (snd x) more) more) as skl.\n    assert ({skl = []} + {skl <> []}). \n    pose proof (destruct_list skl). destruct X. destruct s.\n    destruct s. right. rewrite e. intuition. inversion H0.\n    left. auto.\n    destruct H0. rewrite e. firstorder.\n    pose proof (IHl0 n).\n    pose proof (destruct_list skl). destruct X. destruct s.\n    destruct s. rewrite e.\n    rewrite (groupbysimple_equation A (x0 :: x1)).\n    rewrite e in H0. rewrite (groupbysimple_equation _ (x0 :: x1)) in H0.\n    auto. rewrite e in n. firstorder.\nQed.\n\nLemma sortedList_notempty :\n  forall (l : list ({v : list X.cand | NoDup v /\\ [] <> v} * Q)),\n    l <> [] -> sort l <> [].\nProof.\n  intros l H.\n  remember (sort l) as t.\n  induction t.\n  pose proof (destruct_list l). destruct X. destruct s.\n  destruct s. rewrite e in Heqt.\n  pose proof (Permuted_sort l). rewrite e in H0.\n  rewrite <- Heqt in H0.\n  pose proof (Permutation_sym H0).\n  pose proof (Permutation_nil H1). rewrite H2 in e.\n  rewrite e in H. unfold not in H. pose proof (H eq_refl).\n  inversion H3. firstorder.\n  firstorder.\nQed.\n  \n  \nLemma sherin:\n  forall (l : list ({v : list X.cand | NoDup v /\\ [] <> v} * Q)),\n    l <> [] ->\n    last (groupbysimple _ (sort l)) [] <> [].\nProof.\n  intros l H. pose proof (groupby_notempty _ (sort l) (sortedList_notempty l H)).\n  auto.\nQed.\n\nLemma groupbysimple_not_empty: forall (l : list (list ({v : list X.cand | NoDup v /\\ [] <> v} * Q))), \n       last l []  <> [] -> l <> [].\nProof.\n intros.\n intro.\n rewrite H0 in H.\n simpl in H.\n contradict H.\n auto.\nQed.\n\n\n(* Section genericTermination.\nClose Scope Q_scope. *) \n \n(*Module Base.*)\n(*Close Scope Q_scope.*) \n\n(*\n(*Variable cand: Type.*)\nVariable cand_all: list cand.\nHypothesis cand_nodup: NoDup cand_all.\nHypothesis cand_finite: forall c, In c cand_all.\nHypothesis cand_eq_dec: forall c d:cand, {c=d} + {c<>d}.\nHypothesis cand_in_dec: forall c : cand, forall l : list cand, {In c l} + {~In c l}.\n*)\n(* a ballot is a permutation of the list of candidates and a transfer balue *)\n\n Definition ballot :=  ({v : list X.cand | (NoDup v) /\\ ( [] <> v)} * Q).\n\n(*\nVariable bs : list ballot.\nVariable st : nat. \nVariable quota : Q.\n*)\n\nDefinition length_empty: length ([]:list X.cand) <= X.st.\nProof.\n simpl.\n induction X.st.\n auto.\n auto.\nDefined.\n\nDefinition nbdy : list X.cand := [].                    (* empty candidate list *)\nDefinition nty  : X.cand -> Q := fun x => (0)%Q .          (* null tally *)\nDefinition nas  : X.cand -> list (list ballot) := fun x => []. (* null vote assignment *)\nDefinition emp_elec : {l: list X.cand | length l <= X.st} := \n exist _ ([] :list X.cand) length_empty.                (*empty list of elected candidates*)\nDefinition all_hopeful  := \n exist (fun v => NoDup v) X.cand_all X.cand_nodup.           (*inintial list of all candidates*)\n\n\n(*\nFixpoint have_same_val (r: Q) (l: (list ballot)) acc :=\n match l with \n  [] => acc\n |l0 :: ls => if Rat_eq r (snd l0) then have_same_val r ls (l0:: acc) else acc \n\n end.\n\n\nFixpoint Remove_ballotSame_rat (r: Q) (l: list ballot) acc :=\n  match l with \n   [] => acc\n |l0 :: ls => if Rat_eq r (snd l0) then Remove_ballotSame_rat r ls acc\n                  else Remove_ballotSame_rat r ls (l0:: acc)\n end.\n\nFixpoint Parcel_same_val (n:nat) l :=\n match n with\n    O => []\n   |S n' => match l with \n                 [] => []\n               | l0:: ls => (have_same_val (snd l0) (l0::ls) []) \n                                :: (Parcel_same_val n' (Remove_ballotSame_rat (snd l0) ls []))\n            end\n   end.\n  \n\n*)\n\n(* sum of weights in a list of ballots *)\nFixpoint sum_aux (l : list ballot) (acc:Q): Q :=\n match l with \n            | [] => acc\n            | l :: ls => sum_aux ls (Qred ((snd l) + acc)%Q)\n end. \n\nDefinition sum (l:list ballot) := sum_aux l (0).\n\nFixpoint SUM_AUX (l: list (list ballot)) (acc:Q): Q := \n match l with\n          | [] => acc\n          | l0 :: ls => SUM_AUX ls (Qred ((sum l0) + acc)%Q)\n end. \n\nDefinition SUM (l: list (list ballot)) := SUM_AUX l 0.\n\nFixpoint is_elem (l:list X.cand) (c : X.cand) :=\n match l with\n           [] => false\n           |l0::ls => if X.cand_eq_dec l0 c then true else is_elem ls c\n end.\n\n(*checks if list l has duplicate elements*)\nFixpoint nodup_elem (l:list X.cand) :=\n match l with\n          [] => true\n          |l0::ls => if is_elem ls l0 \n                       then false\n                     else nodup_elem ls      \n end. \n\nFixpoint non_empty (l:list X.cand):=\n match l with \n         [] => false\n         |_ => true\n end.\n\n\n(*filters ballots so that only formal ballots remain*)\nFixpoint Filter (l: list ballot):=\n match l with\n         [] => []\n         |l0::ls => let x := proj1_sig (fst l0) in\n                      if X.ValidBallot x\n                         then l0:: Filter ls\n                      else Filter ls  \n end.\n\n\nFixpoint Sum_nat (l: list nat) :=\n match l with\n   [] => (0)%nat\n  |l0::ls => (l0 + Sum_nat ls)%nat\nend.\n\nLemma map_cons: forall (A: Type) (l: list A) (x: A) (f: A -> nat), map f (x::l) = (f x) :: map f l. \nProof.\nintros.\ninduction l.\nsimpl. auto.\nsimpl.\nauto.\nQed.\n\nLemma map_ext_in {A B} (f f' : A -> B) (ls : list A)\n        (H : forall a, In a ls -> f a = f' a)\n    : map f ls = map f' ls.\n  Proof.\n    induction ls; simpl; trivial.\n    rewrite H, IHls.\n    { reflexivity. }\n    { intros; apply H; right; assumption. }\n    { left; reflexivity. }\n  Qed.\n\nLemma SumNat_app: forall l1 l2, Sum_nat (l1 ++ l2) = (Sum_nat l1 + (Sum_nat l2))%nat.\nProof.\nintros.\ninduction l1.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHl1.\nomega.\nQed.\n\nLemma sum_less_than : forall (f: X.cand -> nat) (f' : X.cand -> nat) (h: list X.cand) c,\n (forall d, d <> c -> (f d = f' d)) -> (f' c < f c)%nat -> (In c h) -> (NoDup h) ->\n (Sum_nat (map f' h) < Sum_nat (map f h))%nat.\nProof.\nintros f f' h c H1 H2 H3 H12.\n(*destruct H as [H1 [H2 [H3 H12]]].*)\nspecialize (in_split c h H3). intros H4. destruct H4 as [h1 [h2 H5]].\nrewrite H5.\nassert (hyp: forall g: X.cand -> nat, map g (h1++ c:: h2) = (map g h1) ++ ([g c] ++ (map g h2))). intro g.\nrewrite map_app.\nassert (hyp2: map g (c:: h2) = (g c) :: map g h2).\nrewrite map_cons. auto.\nrewrite hyp2.\napply (app_inv_head (map g h1)).\nsimpl. auto.\nspecialize (hyp f).\nassert (hyp': forall g': X.cand -> nat, map g' (h1++ c:: h2) = (map g' h1) ++ ([g' c] ++ (map g' h2))). intro g'.\nrewrite map_app.\nassert (hyp2: map g' (c:: h2) = (g' c) :: map g' h2).\nrewrite map_cons. auto.\nrewrite hyp2.\napply (app_inv_head (map g' h1)).\nsimpl. auto.\nspecialize (hyp' f').\nrewrite hyp.\nrewrite hyp'.\nsimpl.\nassert (hyp3: ~ In c h1).\nrewrite H5 in H12.\nspecialize (NoDup_remove_2 h1 h2 c H12). intro NoduplicateH1H2.\nintro.\napply NoduplicateH1H2.\napply in_or_app.\nleft;assumption.\nassert (hyp4: forall d, In d h1 -> f d = f' d).\nintros d auxHyp.\nassert (auxHyp2: d <> c).\nintro.\nrewrite H in auxHyp.\ncontradiction hyp3.\napply H1. assumption.\nassert (hyp5: ~ In c h2). \nrewrite H5 in H12.\nspecialize (NoDup_remove_2 h1 h2 c H12). intro.\nintro.\napply H.\napply in_or_app.\nright;auto.\nassert (hyp6: forall d, In d h2 -> f d = f' d).\nintros.\nassert (auxhyp: d <> c).\nintro.\nrewrite H0 in H.\napply hyp5. assumption.\napply H1. auto.\nspecialize (map_ext_in f f' h1 hyp4). intro HH.\nspecialize (map_ext_in f f' h2 hyp6). intro HH'.\nrewrite HH.\nrewrite HH'.\nassert (hyp7: Sum_nat (map f' h1 ++ f c:: map f' h2) = (Sum_nat (map f' h1) + (f c) + (Sum_nat (map f' h2)))%nat).\nrewrite SumNat_app.\nsimpl.\nomega.\nassert (hyp8: Sum_nat (map f' h1 ++ f' c:: map f' h2) = (Sum_nat (map f' h1) + (f' c) + (Sum_nat (map f' h2)))%nat). \nrewrite SumNat_app.\nsimpl.\nomega.\nrewrite hyp7.\nrewrite hyp8.\nomega.\nQed.\n\n\n(* we can find a candidate with least no of first prefs *)\nLemma list_min : forall A:Type, forall l: list A, forall f: A -> Q,\n (l = []) + (existsT m:A, (In m l /\\ (forall b:A, In b l ->(f m <= f b)%Q))).\nProof.\n intros.\n induction l as [ | l ls ].\n left. trivial.\n destruct IHls.\n right.\n exists l. split.\n apply (in_eq l ls). intros b ass.\n assert (l = b \\/ In b ls).\n apply (in_inv ass). destruct H. replace l with b. intuition. replace ls with ([] : list A) in H.\n contradict H.\n right. destruct s. destruct a. \n assert (sumbool ((f x < (f l))%Q) (((f l) <= (f x))%Q)).\n apply (Qlt_le_dec (f x) (f l))%Q.\n assert (sumbool ((f x <= (f l))%Q) (((f l) <= (f x))%Q)).\n intuition.\n destruct H2.\n  (* x is the minimum *)\n exists x. split.\n apply (in_cons l x ls). assumption. intros b ass.\n assert (l = b \\/ In b ls).\n apply (in_inv ass).\n destruct H2. replace b with l. assumption.\n apply (H0 b H2).\n  (* l is the minimum *)\n exists l. split.\n apply (in_eq l ls).\n intros b ass.\n assert (l = b \\/ In b ls). apply (in_inv ass). destruct H2. \n replace l with b. intuition.\n specialize (H0 b H2).\n apply (Qle_trans (f l) (f x) (f b)). assumption. assumption.\nDefined. \n\n(*if a list is not empty, then there exist an element which has the greatest value w.r.t. function f*)\nLemma list_max : forall A:Type, forall l: list A, forall f: A -> Q,\n   (l = []) + (existsT m:A, (In m l /\\ (forall b:A, In b l ->(f b <= f m)%Q))).\nProof.\n intros.\n induction l.\n left;auto.\n destruct IHl.\n right.\n subst.\n exists a.\n split.\n simpl;left;auto.\n intros.\n destruct H.\n subst.\n apply (Qle_refl (f b)).\n inversion H.\n right.\n destruct s.\n destruct a0.\n assert (sumbool ((f a < f x)%Q) ((f x <= f a)%Q)).\n apply (Qlt_le_dec (f a) (f x)).\n destruct H1.\n exists x.\n split.\n right;auto.\n intros.\n assert (a= b \\/ In b l) by apply (in_inv H1).\n destruct H2.\n subst.\n destruct H1.\n apply (Qlt_le_weak (f b)(f x)).\n assumption.\n apply H0.\n auto.\n apply H0.\n auto.\n exists a.\n split.\n left;auto.\n intros.\n assert (a=b \\/ In b l) by apply (in_inv H1).\n destruct H2.\n rewrite H2.\n apply (Qle_refl (f b)).\n apply (Qle_trans (f b)(f x)(f a)).\n apply H0.\n auto.\n assumption.\nQed.\n\nLemma list_max_cor: forall A:Type, forall l: list A, forall f: A -> Q,[]<> l -> existsT m:A, (In m l /\\ (forall a:A, In a l -> (f a <= f m)%Q)). \nProof.\n intros.\n specialize (list_max A l f).\n intros.\n destruct X.\n rewrite e in H.\n contradiction H.\n auto.\n assumption.\nQed.\n\n\n(*Section Generic_Machine.*)\n\n(* initial, intermediate and final states in vote counting *)\n\n Inductive Machine_States :=\n  initial:\n     list ballot -> Machine_States \n  |state:                                             (** intermediate states **)\n    list ballot                                       (* uncounted votes *)\n    * list (X.cand -> Q)                              (* tally *)\n    * (X.cand -> list (list ballot))                  (* pile of ballots *)\n    * ((list X.cand) * (list X.cand))                 (* backlog *)\n    * {elected: list X.cand | length  elected <= X.st}(* elected candidates *)\n    * {hopeful: list X.cand | NoDup hopeful}          (* continuing candidates *)\n      -> Machine_States\n  |winners:                                           (** final state **)\n      list X.cand -> Machine_States.                   (* election winners *)\n\nDefinition State_final (a : Machine_States) : Prop :=\n exists w, a = winners (w).\n\nDefinition State_initial (a : Machine_States) : Prop :=\n exists (ba : list ballot), a = initial (ba).\n\nLemma final_dec: forall j : Machine_States, (State_final j) + (not (State_final j)).\nProof. \n intro j. \n  destruct j;\n   repeat (right;unfold State_final;unfold not;intro H;destruct H;discriminate) \n     || \n       left;unfold State_final;exists l;reflexivity.\nDefined.\n\nLemma initial_dec: forall j: Machine_States, (State_initial j) + not (State_initial j).\nProof.\n intro j.\n  destruct j;\n    repeat (left;unfold State_initial;exists l;reflexivity)\n        ||\n          (right;intro H;inversion H; discriminate).\nQed.        \n \n\n(* Rules *)\nDefinition FT_Rule := Machine_States -> Machine_States -> Prop.\n\n(* The set (nat)^5 to be used as the set on which we impose a lexicographic order *)\nDefinition Product_Five_NatSet := nat * (nat * (nat * (nat * nat))). \n\n Definition DependentNat_Prod2 := sigT (A:= nat) (fun a => nat).\n Definition DependentNat_Prod3 := sigT (A:= nat) (fun a => DependentNat_Prod2).\n Definition DependentNat_Prod4 := sigT (A:= nat) (fun a => DependentNat_Prod3).\n Definition DependentNat_Prod5 := sigT (A:= nat) (fun a => DependentNat_Prod4).\n\n Definition Make_DependentNat2  :\n   nat * nat -> DependentNat_Prod2.\n  intros (p,q).\n  exists p.\n  exact q.\n Defined.\n\n Definition Make_DependentNat3 :\n   nat * (nat * nat) -> DependentNat_Prod3.\n  intros (n, p_q).\n  exists n.\n  exact (Make_DependentNat2 p_q).\n Defined. \n\n Definition Make_DependentNat4 :\n   nat * (nat * (nat * nat)) -> DependentNat_Prod4.\n  intros (m, n_p_q).\n  exists m.\n  exact (Make_DependentNat3 n_p_q).\n Defined.\n\n Definition Make_DependentNat5 :\n   nat * (nat * (nat * (nat * nat))) -> DependentNat_Prod5.\n  intros (m,n_p_q_r).\n  exists m.\n  exact (Make_DependentNat4 n_p_q_r).\n Defined.\n\n Definition LexOrdNat_Aux1 :\n DependentNat_Prod2 -> DependentNat_Prod2 -> Prop :=\n (lexprod nat (fun a => nat) Peano.lt (fun a:nat =>Peano.lt)).\n\n Definition LexOrdNat_Aux2 :\n DependentNat_Prod3 -> DependentNat_Prod3 -> Prop :=\n (lexprod nat (fun a => DependentNat_Prod2) Peano.lt (fun a:nat =>LexOrdNat_Aux1)).\n\n Definition LexOrdNat_Aux3 :\n DependentNat_Prod4 -> DependentNat_Prod4 -> Prop:=\n (lexprod nat (fun a => DependentNat_Prod3) Peano.lt (fun (a:nat) => LexOrdNat_Aux2)).\n\n Definition LexOrdNat:\n DependentNat_Prod5 -> DependentNat_Prod5 -> Prop :=\n (lexprod nat (fun a => DependentNat_Prod4) Peano.lt (fun (a:nat) => LexOrdNat_Aux3)).\n\nLemma wf_Lexprod1 : well_founded LexOrdNat_Aux2.\n unfold LexOrdNat_Aux2. apply wf_lexprod.\n apply lt_wf.\n intro n.\n unfold LexOrdNat_Aux1;apply wf_lexprod.\n apply lt_wf.\n intro m; apply lt_wf.\nQed.\n\n(*LexOrdNat_Aux3 is a well founded ordering*)\nLemma wf_Lexprod : well_founded LexOrdNat_Aux3.\nProof.\n red in |-*;apply wf_lexprod. apply lt_wf. intro n.\n red in |-*;apply wf_lexprod. apply lt_wf. intro m.\n red in |-*;apply wf_lexprod. apply lt_wf. intro p.\n apply lt_wf.\nQed.\n\n Lemma wf_LexOrdNat : well_founded LexOrdNat.\n Proof.\n  red in |-*; apply wf_lexprod. apply lt_wf. intro n.\n  red in |-*; apply wf_lexprod. apply lt_wf. intro m.\n  red in |-*; apply wf_lexprod. apply lt_wf. intro p.\n  red in |-*; apply wf_lexprod. apply lt_wf. intro r.\n  apply lt_wf.\n Qed.\n\n(* imposing a well-found ordering on (nat)^5 *)\n\n  Definition Order_NatProduct : Product_Five_NatSet -> Product_Five_NatSet -> Prop :=\n    (fun x y : nat * (nat * (nat * (nat * nat))) =>\n     LexOrdNat (Make_DependentNat5 x) (Make_DependentNat5 y)).\n\nLemma Order_NatProduct_wf : well_founded Order_NatProduct.\n unfold Order_NatProduct. \n apply wf_inverse_image.\n apply wf_LexOrdNat.\nQed.\n\n\n\n(* measure function maps to ({0,1},length h, Sum (map (\\.c -> length (concat p c)) snd bl), length bl, length ba) *)\n\n Definition Measure_States: {j:Machine_States |not (State_final j)} -> Product_Five_NatSet.\n  intro H. destruct H as [j ej]. destruct j.\n  split. exact 1.\n  split. exact 0. split. exact 0. split. exact 0. exact 0.\n  destruct p as [[[[[ba t] p] bl] e] h].\n  split. exact 0.\n  split. exact (length (proj1_sig h)).\n  split. exact (Sum_nat (map (fun c => length (concat (p c))) (snd bl)))%nat.\n  split. exact (length (fst bl)). exact (length ba).\n  contradiction ej.\n  unfold State_final. \n  exists l. reflexivity.\n Defined.\n\n(* lexicographic order behaves as expected *)\n\n Lemma wfo_aux:  forall a b c d a' b' c' d' e e': nat,\n     (LexOrdNat (Make_DependentNat5 (a, (b, (c, (d,e)))))\n                (Make_DependentNat5 (a', (b', (c',(d',e')))))) <->\n     (a < a' \\/\n     (a = a' /\\ b < b' \\/\n     (a = a' /\\ b = b' /\\ c < c' \\/\n     (a = a' /\\ b = b' /\\ c = c' /\\ d < d' \\/\n     (a = a' /\\ b = b' /\\ c = c' /\\ d = d' /\\ e < e'))))).\n\n Proof.\n intros. split. unfold LexOrdNat. unfold Make_DependentNat5. simpl. intro H. inversion H. subst. \n  (* case 1st component are below one another *)\n auto.\n  (* case 1st components are equal *)\n unfold LexOrdNat_Aux3 in H1. inversion H1. subst. auto.\n  (* case 1st and 2nd components are equal and 3rd are below one another *)\n  unfold LexOrdNat_Aux2 in H6.\n  inversion H6.\n  right;right;left;auto.\n  (* case where the first three components are equal but the last decreases*)\n  unfold LexOrdNat_Aux1 in H11. inversion H11. subst.\n  right;right;right;auto.        \n  (* the case where the first four are equal and the last decreases *)\n  right;right;right;right. subst. auto.\n  (* right-to-left direction *)\n intro H. destruct H.\n  (* case 1st components are below one another *)\n unfold LexOrdNat. apply left_lex. assumption.\n destruct H.\n  (* case 1st components are equal and 2nd components are below one another *)\n destruct H as [H1 H2]. subst. apply right_lex. apply left_lex. assumption.\n  (* case 1st and 2nd components are identical, and 3rd components are below one another *)\n destruct H as [H1 | H2]. destruct H1 as [H11 [H12 H13]]. subst. repeat apply right_lex || apply right_lex || apply left_lex. assumption. destruct H2 as [H1 | H2]. destruct H1 as [H11 [H12 [H13 H14]]]. subst.\n repeat apply right_lex || apply right_lex || apply left_lex. auto.\n destruct H2 as [H21 [H22 [H23 [H24 H25]]]]. subst. repeat apply right_lex. assumption.\nQed.\n\nDefinition IsNonFinal: forall j: Machine_States, forall e: not (State_final j), { j : Machine_States | not (State_final j) }.\n  intros j e. exists j. assumption.\nDefined.\n\n\n\n\n(*\nDefinition Is_Legitimate_Elim_two (R: Machine_States -> Machine_States -> Prop) :=\n   (forall premise, forall t p e h r, (premise = state ([],t, p, [], e, h, r)) ->\n     (exists c, In c r /\\\n       (p c) <> [] ) -> exists conc, R premise conc)  *\n   (forall premise conclusion, R premise conclusion ->\n     exists nba t p np e h r,\n     (premise = state ([], t, p, [], e, h, r)) /\\\n     exists c, In c (proj1_sig h) /\\ (length (np c)) < (length (p c)) /\\\n     (forall d, d <> c -> length (np d) = length (p d)) /\\   \n     (conclusion = state (nba, t, np, [], e, h, r))).\n\nLemma dec_ElimTwo : forall R (p c : Machine_States),\n (Is_Legitimate_Elim_two R) -> R p c -> forall (ep : ~ State_final p) (ec : ~ State_final c),\nOrder_NatProduct (Measure_States (IsNonFinal c ec))\n  (Measure_States (IsNonFinal p ep)).\nProof.\nintros R p c ss Hr ep ec.\nunfold Is_Legitimate_Elim_two in ss.\ndestruct ss as [ss1 s1].\nspecialize (s1 p c Hr).\ndestruct s1 as [nba [t [p0 [np [e [h [r s11]]]]]]]. \ndestruct s11 as [Hs1 [weak Hs3]].\ndestruct Hs3 as [Hs31 [Hs32 [Hs33 Hs34]]].\ndestruct p.\ninversion Hs1.\ndestruct c. inversion Hs34.\ndestruct p as [[[[[[ba11 t11] p11] bl11] e11] h11] r11].\ndestruct p1 as [[[[[[ba22 t22] p22] bl22] e22] h22] r22].\ninversion Hs1. inversion Hs34. subst.\nunfold Measure_States.\nsimpl.\nunfold Order_NatProduct.\nrewrite wfo_aux.\nright;left. split. auto.\nassert (hypo: forall d, d <> weak -> length (p0 d) = length (np d)).\nintros.\nspecialize (Hs33 d H).\nrewrite Hs33. auto.\nspecialize (sum_less_than (fun c => length (p0 c)) (fun c' => length (np c')) (proj1_sig h) \n                          weak hypo Hs32 Hs31 (proj2_sig h)). intro.\nomega.\ninversion Hs34.\ninversion Hs1.\nQed.\n*)  \nDefinition SanityCheck_Initial_App (R : Machine_States -> Machine_States -> Prop) :=  \n  forall premise, forall ba, (premise = initial ba) -> existsT conclusion,\n     (conclusion = state (Filter ba, [nty], nas, (nbdy,nbdy), emp_elec, all_hopeful)) *  \n      R premise conclusion.\n\nDefinition SanityCheck_Initial_Red (R : Machine_States -> Machine_States -> Prop) := \n  forall p c, R p c -> exists ba ba' t ass bl e h, (p = initial ba) /\\\n  (c = state (ba', t, ass, bl, e, h)).\n\nDefinition SanityCheck_Count_App (R: Machine_States -> Machine_States -> Prop) :=\n (forall premise, forall ba t p  bl h e , (premise = state (ba, t, p ,bl ,e, h)) -> (ba <> []) ->\n    existsT conclusion, (R premise conclusion)).\n\nDefinition SanityCheck_Count_Red (R: Machine_States -> Machine_States -> Prop) :=\n (forall (p: Machine_States) (c: Machine_States), R p c -> exists ba1 ba2 t1 t2 p1 p2 bl e h, \n   (p = state (ba1, t1, p1, bl, e, h)) /\\ \n   (c = state (ba2, t2 :: t1, p2, bl, e, h)) /\\ \n   ( length ba2 < length ba1) /\\\n   (Sum_nat (map (fun c => length (concat (p1 c))) (snd bl)) = \n         (Sum_nat (map (fun c => length (concat (p2 c))) (snd bl))))).\n(*\nDefinition Is_empty (l : list cand) :=\n match l with\n   [] => true\n  |_ => false\nend.\n*)\n(* note that I have put the null tally as the default value for head in case of empty list *)\n\n(* --------------------------------------------------------------------------------- *)\n  (* If we wish to keep the list of eliminated in the bl2 all the way up to the\n     end, then we need to consider the case that concatening the pile of the head of bl2 is \n       not empty so that we know which one of transfer-elected r transfer-removed should\n        correctly be applied. There is a cleaner way and that is to simply either allow the\n         bl2 to be empty or just include the most recently excluded candidate. This way we\n          can get rid of considering if concat of pile of head of bl2 is empty or not by\n            including a simpler check inside the transfer-excluded that ensures the \n              updated the head of the updated bl2 has some votes in it to distribute still *)\n(* \nDefinition SanityCheck_Transfer1_App (R: Machine_States -> Machine_States -> Prop) :=\n (forall premise, forall t p (bl: (list X.cand) * (list X.cand)) e h, \n (premise = state ([], t, p, (fst bl, []), e, h)) -> (length (proj1_sig e) < X.st) /\\ \n (fst bl <> []) /\\ (forall c, In c (proj1_sig h) -> ((hd nty t) c < X.quota)%Q) -> \n    existsT conc, R premise conc).\n\nDefinition SanityCheck_Transfer2_App (R: Machine_States -> Machine_States -> Prop) :=\n forall premise, forall t p bl1 bl2 c e h , (premise = state ([], t, p, (bl1, c::bl2), e, h)) ->\n (length (proj1_sig e) < X.st) /\\ (bl1 <> []) /\\ (concat (p c) = []) /\\ \n (forall c, In c (proj1_sig h) -> ((hd nty t) c < X.quota)%Q) ->\n     existsT conc, R premise conc.\n\nDefinition SanityCheck_Transfer3_App (R: Machine_States -> Machine_States -> Prop) :=\n forall premise, forall t p bl1 bl2 c e h , (premise = state ([], t, p, (bl1, c::bl2), e, h)) ->\n (length (proj1_sig e) < X.st) /\\ (bl1 <> []) /\\ (concat (p c) <> []) /\\ \n (forall c, In c (proj1_sig h) -> ((hd nty t) c < X.quota)%Q) ->\n     existsT conc, R premise conc.\n*)\n\nDefinition SanityCheck_TransferElected_App (R: Machine_States -> Machine_States -> Prop) :=\n (forall premise, forall t p bl1 bl2 e h, \n (premise = state ([], t, p, (bl1, bl2), e, h)) -> (length (proj1_sig e) < X.st) /\\ \n  (bl1 <> []) /\\ ((bl2 = []) \\/ (exists head tail, (bl2 = head :: tail) /\\ (concat (p head) = []))) /\\ \n  (forall c, In c (proj1_sig h) -> ((hd nty t) c < X.quota)%Q) -> \n    existsT conc, R premise conc).\n\nDefinition SanityCheck_TransferRemoved_App (R: Machine_States -> Machine_States -> Prop) :=\n forall premise, forall t p bl1 bl2 c e h , (premise = state ([], t, p, (bl1, c::bl2), e, h)) ->\n (length (proj1_sig e) < X.st) /\\ (concat (p c) <> []) /\\  \n (forall c, In c (proj1_sig h) -> ((hd nty t) c < X.quota)%Q) ->\n     existsT conc, R premise conc.\n\n \nDefinition SanityCheck_TransferElected_Red (R: Machine_States -> Machine_States -> Prop) :=\n (forall premise conclusion, R premise conclusion ->\n   exists nba t p np bl nbl h e,\n   (premise = state ([], t, p, bl, e, h)) /\\\n   (length (fst nbl) < length (fst bl)) /\\ \n       (Sum_nat (map (fun c => length (concat (p c))) (snd bl)) = \n             Sum_nat (map (fun c => length (concat (np c))) (snd nbl))) /\\\n    (conclusion = state (nba, t, np, nbl, e, h))). \n\nDefinition SanityCheck_TransferRemoved_Red (R: Machine_States -> Machine_States -> Prop) :=\n (forall premise conclusion, R premise conclusion ->\n   exists nba t p np bl nbl h e,\n   (premise = state ([], t, p, bl, e, h)) /\\\n   (length (fst nbl) = length (fst bl)) /\\ \n       (Sum_nat (map (fun c => length (concat (np c))) (snd nbl)) <  \n             Sum_nat (map (fun c => length (concat (p c))) (snd bl))) /\\\n    (conclusion = state (nba, t, np, nbl, e, h))). \n\n\nDefinition SanityCheck_Elect_App (R: Machine_States -> Machine_States -> Prop) :=\n (forall premise, forall t p bl e h, (premise = state ([], t, p, bl, e, h)) ->\n     (existsT (c: X.cand), \n     (length (proj1_sig e)) + 1 <= X.st /\\  \n     In c (proj1_sig h) /\\ ((hd nty t) (c) >= X.quota)%Q) -> existsT conc, R premise conc).\n\nDefinition SanityCheck_Elect_Red (R: Machine_States -> Machine_States -> Prop) :=\n (forall premise conclusion, R premise conclusion ->\n     exists t p np bl nbl e ne nh h, \n     (premise = state ([], t, p, bl, e, h)) /\\\n          (length (proj1_sig nh) < length (proj1_sig h)) /\\\n          (length (proj1_sig e) < length (proj1_sig ne)) /\\\n     (conclusion = state ([], t, np, nbl, ne, nh))).\n \n(* I have made bl2 empty because of the decision above, namely that bl2 is either empty or \n   has at most one element in it at each time. Now a candidate is eliminated only if there is\n   no vote to transfer either elected ones or removed one. *)\nDefinition SanityCheck_Elim_App (R: Machine_States -> Machine_States -> Prop) :=\n  (forall premise, forall t p e h bl2, (premise = state ([], t, p, ([], bl2), e, h)) ->\n     length (proj1_sig e) + length (proj1_sig h) > X.st /\\\n     ((bl2 = []) \\/ (exists head tail, bl2 = head :: tail /\\ (concat (p head) = []))) /\\\n     (forall c, In c (proj1_sig h) -> ((hd nty t) c < X.quota)%Q) -> existsT conc, R premise conc).\n\nDefinition SanityCheck_Elim_Red (R: Machine_States -> Machine_States -> Prop) :=\n (forall premise conclusion, R premise conclusion ->\n     exists nba t p np e h nh bl2 nbl2,\n     (premise = state ([], t, p, ([], bl2), e, h)) /\\\n     length (proj1_sig nh) < length (proj1_sig h) /\\\n     (conclusion = state (nba, t, np, ([], nbl2), e, nh))).\n\nDefinition SanityCheck_Hwin_App (R: Machine_States -> Machine_States -> Prop) :=\n  (forall premise, forall ba t p bl e h, (premise = state (ba, t, p, bl, e, h)) ->\n     length (proj1_sig e) + (length (proj1_sig h)) <= X.st -> existsT conc, R premise conc).\n\n\nDefinition SanityCheck_Hwin_Red (R: Machine_States -> Machine_States -> Prop) :=\n (forall premise conclusion, R premise conclusion ->\n     exists w ba t p bl e h,\n      (premise = state (ba, t, p, bl, e, h)) /\\\n      w = (proj1_sig e) ++ (proj1_sig h) /\\ \n      (conclusion = winners w)).\n\nDefinition SanityCheck_Ewin_App (R: Machine_States -> Machine_States -> Prop) :=\n (forall premise, forall ba t p bl e h, (premise = state (ba, t, p, bl, e, h)) ->\n    length (proj1_sig e) = X.st -> existsT conc, R premise conc).\n\nDefinition SanityCheck_Ewin_Red (R: Machine_States -> Machine_States -> Prop) :=\n (forall premise conclusion, R premise conclusion ->\n    exists w ba t p bl e h,\n    (premise = state (ba, t, p, bl, e, h)) /\\\n     w = (proj1_sig e) /\\ \n    (conclusion = winners (proj1_sig e))).\n\nRecord STV := \n   mkSTV {initStep: Machine_States -> Machine_States -> Prop;\n          evidence_applicability_initStep: (SanityCheck_Initial_App initStep);\n          evidence_reducibility_initStep: (SanityCheck_Initial_Red initStep);\n          count: Machine_States -> Machine_States -> Prop;\n          evidence_applicability_count: (SanityCheck_Count_App count);\n          evidence_reducibility_count: (SanityCheck_Count_Red count);    \n          transfer_elected: Machine_States -> Machine_States -> Prop;\n          evidence_applicability_transferElected: (SanityCheck_TransferElected_App transfer_elected);\n          evidence_reducibility_transferElected: (SanityCheck_TransferElected_Red transfer_elected);\n        (*  transfer2_elected: Machine_States -> Machine_States -> Prop;\n          evidence_applicability_transfer2_elected: (SanityCheck_Transfer2_App transfer2_elected);\n          evidence_reducibility_transfer2_elected: (SanityCheck_Transfer_Red transfer2_elected); *)\n          transfer_removed: Machine_States -> Machine_States -> Prop;\n          evidence_applicability_transferRemoved: (SanityCheck_TransferRemoved_App transfer_removed);\n          evidence_reducibility_transferRemoved: (SanityCheck_TransferRemoved_Red transfer_removed);\n          elect: Machine_States -> Machine_States -> Prop;\n          evidence_applicability_elect: (SanityCheck_Elect_App elect);\n          evidence_reducibility_elect: (SanityCheck_Elect_Red elect);\n          elim: Machine_States -> Machine_States -> Prop;\n          evidence_applicability_elim: (SanityCheck_Elim_App elim);\n          evidence_reducibility_elim: (SanityCheck_Elim_Red elim);\n          hwin: Machine_States -> Machine_States -> Prop;\n          evidence_applicability_hwin: (SanityCheck_Hwin_App hwin);\n          evidence_reducibility_hwin: (SanityCheck_Hwin_Red hwin);         \n          ewin: Machine_States -> Machine_States -> Prop;\n          evidence_applicability_ewin: (SanityCheck_Ewin_App ewin);\n          evidence_reducibility_ewin: (SanityCheck_Ewin_Red ewin)}.\n\n(* beginning of measure decreasing proof for new formalised rules*)\nLemma dec_Initial : forall (s: STV) (p c : Machine_States),\n initStep s p c  -> forall (ep : ~ State_final p) (ec : ~ State_final c),\nOrder_NatProduct (Measure_States (IsNonFinal c ec))\n  (Measure_States (IsNonFinal p ep)).\nProof. \n intros s p c H ep ec.\n destruct s. \n simpl in H.\n unfold SanityCheck_Initial_Red in evidence_reducibility_initStep0.\n destruct p.\n destruct c.\n specialize (evidence_reducibility_initStep0 (initial l) (initial l0)).\n intuition.\n destruct H0 as [ba [ba' [t [ass [bl [e [h [Hev21 Hev22]]]]]]]].\n inversion Hev22. \n destruct p as [[[[[ba1 t1] p1] bl1] e1] h1].\n unfold Measure_States.\n simpl.\n unfold Order_NatProduct.\n rewrite wfo_aux.\n left;auto.\n contradict ec. unfold State_final. exists l0. reflexivity.\n specialize (evidence_reducibility_initStep0 (state p) c).\n intuition.\n destruct H0 as [ba [ba' [t [ass [bl [e1 [h1 [Hev21 Hev22]]]]]]]].\n inversion Hev21.\n contradict ep. unfold State_final. exists l. auto.\nQed.\n\nLemma dec_Count : forall (s: STV) (p c : Machine_States),\n count s p c -> forall (ep : ~ State_final p) (ec : ~ State_final c),\nOrder_NatProduct (Measure_States (IsNonFinal c ec))\n  (Measure_States (IsNonFinal p ep)).\nProof.\n intros s p c Hr ep ec.\n destruct s. \n simpl in Hr.\n unfold SanityCheck_Count_Red in evidence_reducibility_count0.\n specialize (evidence_reducibility_count0 p c Hr).\n destruct  evidence_reducibility_count0 as [ba1 [ba2 [t1 [t2 [p1 [p2 [bl [e [h Hev21]]]]]]]]].\n destruct Hev21 as [Hev211 [Hev22 [Hev23 Hev24]]].\n destruct p. \n inversion Hev211.\n destruct c.\n inversion Hev22.\n destruct p as [[[[[ba11 t11] p11] bl11] e11] h11].\n destruct p0 as [[[[[ba22 t22] p22] bl22] e22] h22].\n unfold Measure_States.\n simpl.\n unfold Order_NatProduct.\n rewrite -> wfo_aux.\n inversion Hev22. inversion Hev211. subst. \n right. right. right. right.\n split. auto.\n split.  auto. rewrite Hev24. auto.\n contradict ec.\n unfold State_final. exists l. reflexivity.\n contradict ep. exists l. auto.\nQed.\n\nLemma dec_TransferElected : forall (s: STV) (p c : Machine_States),\n transfer_elected s p c -> forall (ep : ~ State_final p) (ec : ~ State_final c),\nOrder_NatProduct (Measure_States (IsNonFinal c ec))\n  (Measure_States (IsNonFinal p ep)).\nProof.\n intros s p c Hr ep ec.\n destruct s. \n simpl in Hr.\n unfold SanityCheck_TransferElected_Red in evidence_reducibility_transferElected0.\n specialize (evidence_reducibility_transferElected0 p c Hr).\n destruct evidence_reducibility_transferElected0 as [nba [t [p0 [np [bl [nbl [h [e [Hev21 [Hev22 [Hev22' Hev23]]]]]]]]]]].\n destruct p.\n inversion Hev21.\n destruct c.\n inversion Hev23.\n destruct p as [[[[[ba11 t11] p11] bl11] e11] h11].\n destruct p1 as [[[[[ba22 t22] p22] bl22] e22] h22].\n inversion Hev21. inversion Hev23. subst.\n unfold Measure_States.\n simpl.\n unfold Order_NatProduct.\n rewrite -> wfo_aux.\n (* destruct Hev22 as [Hev221 | Hev222]. *)\n right; right;right; left. intuition.\n(* right; right; left.  intuition. *) \n contradict ec; unfold State_final; exists l ;auto.\n contradict ep; exists l; auto.\nQed.\n\n(*\nLemma dec_TransferElected2 : forall (s: STV) (p c: Machine_States),\n transfer2_elected s p c -> forall (ep : ~ State_final p) (ec : ~ State_final c),\nOrder_NatProduct (Measure_States (IsNonFinal c ec))\n  (Measure_States (IsNonFinal p ep)).\nProof.\n intros s p c Hr ep ec.\n destruct s. \n simpl in Hr.\n unfold SanityCheck_Transfer_Red in evidence_reducibility_transfer2_elected0.\n specialize (evidence_reducibility_transfer2_elected0 p c Hr).\n destruct evidence_reducibility_transfer2_elected0 as \n             [nba [t [p0 [np [bl [nbl [h [e [Hev21 [Hev22 Hev23]]]]]]]]]].\n destruct p.\n inversion Hev21.\n destruct c.\n inversion Hev23.\n destruct p as [[[[[ba11 t11] p11] bl11] e11] h11].\n destruct p1 as [[[[[ba22 t22] p22] bl22] e22] h22].\n inversion Hev21. inversion Hev23. subst.\n unfold Measure_States.\n simpl.\n unfold Order_NatProduct.\n rewrite -> wfo_aux.\n destruct Hev22 as [Hev221 | Hev222].\n right; right;right; left. intuition.\n right; right; left.  intuition. \n contradict ec; unfold State_final; exists l ;auto.\n contradict ep; exists l; auto.\nQed.\n*)\n\nLemma dec_TransferRemoved : forall (s: STV) (p c : Machine_States),\n transfer_removed s p c -> forall (ep : ~ State_final p) (ec : ~ State_final c),\nOrder_NatProduct (Measure_States (IsNonFinal c ec))\n  (Measure_States (IsNonFinal p ep)).\nProof.\n intros s p c Hr ep ec.\n destruct s. \n simpl in Hr.\n unfold SanityCheck_TransferRemoved_Red in evidence_reducibility_transferRemoved0.\n specialize (evidence_reducibility_transferRemoved0 p c Hr).\n destruct evidence_reducibility_transferRemoved0 as [nba [t [p0 [np [bl [nbl [h [e [Hev21 [Hev22 [Hev22' Hev23]]]]]]]]]]].\n destruct p.\n inversion Hev21.\n destruct c.\n inversion Hev23.\n destruct p as [[[[[ba11 t11] p11] bl11] e11] h11].\n destruct p1 as [[[[[ba22 t22] p22] bl22] e22] h22].\n inversion Hev21. inversion Hev23. subst.\n unfold Measure_States.\n simpl.\n unfold Order_NatProduct.\n rewrite -> wfo_aux.\n (* destruct Hev22 as [Hev221 | Hev222]. *)\n right; right; left. intuition.\n (* right; right; left.  intuition. *) \n contradict ec; unfold State_final; exists l ;auto.\n contradict ep; exists l; auto.\nQed.\n \nLemma dec_Elect : forall (s: STV) (p c : Machine_States),\n elect s p c -> forall (ep : ~ State_final p) (ec : ~ State_final c),\nOrder_NatProduct (Measure_States (IsNonFinal c ec))\n  (Measure_States (IsNonFinal p ep)).\nProof.\n intros s p c Hr ep ec.\n destruct s.\n simpl in Hr.\n unfold SanityCheck_Elect_Red in evidence_reducibility_elect0.\n specialize (evidence_reducibility_elect0 p c Hr).\n destruct evidence_reducibility_elect0 as [t [p0 [np [bl [nbl [e [ne [nh [h [Hev1 [Hev2 [Hev3 Hev4]]]]]]]]]]]].\n destruct c.\n inversion Hev4.\n destruct p.\n inversion Hev1.\n destruct p as [[[[[ba11 t11] p11] bl11] e11] h11].\n destruct p1 as [[[[[ba22 t22] p22] bl22] e22] h22].\n inversion Hev1. inversion Hev4. subst.\n unfold Measure_States.\n simpl.\n unfold Order_NatProduct.\n rewrite -> wfo_aux.\n right; left.  intuition.\n inversion Hev1. \n inversion Hev4.\nQed.\n\nLemma dec_Elim : forall (s: STV) (p c : Machine_States),\n elim s p c -> forall (ep : ~ State_final p) (ec : ~ State_final c),\nOrder_NatProduct (Measure_States (IsNonFinal c ec))\n  (Measure_States (IsNonFinal p ep)).\nProof.\n intros s p c Hr ep ec.\n destruct s.\n simpl in Hr.\n unfold SanityCheck_Elim_Red in evidence_reducibility_elim0.\n specialize (evidence_reducibility_elim0 p c Hr).\n destruct evidence_reducibility_elim0 as [nba [t [p0 [np [e [h [nh [bl2 [nbl2 H]]]]]]]]].\n destruct p.\n destruct H as [HH HHH].\n inversion HH.\n destruct c.\n destruct H as [HH [HHH1 HHH2]].\n inversion HHH2.\n destruct p as [[[[[nba11 t11] p11] bl11] e11] h11].\n destruct p1 as [[[[[nb222 t22] p22] bl22] e22] h22].\n destruct H as [K1 [K2 K3]].\n inversion K1.\n inversion K3.\n subst.\n unfold Measure_States.\n simpl.\n unfold Order_NatProduct.\n rewrite wfo_aux.\n right;left. intuition.\n contradict ec; exists l; reflexivity.\n contradict ep; exists l; auto.\nQed.\n\nLemma dec_Hwin  : forall (s: STV) (p c : Machine_States),\n hwin s p c -> forall (ep : ~ State_final p) (ec : ~ State_final c),\nOrder_NatProduct (Measure_States (IsNonFinal c ec))\n  (Measure_States (IsNonFinal p ep)).\nProof.\n intros s p c Hr ep ec.\n destruct s.\n simpl in Hr.\n unfold SanityCheck_Hwin_Red in evidence_reducibility_hwin0.\n specialize (evidence_reducibility_hwin0 p c Hr).\n destruct evidence_reducibility_hwin0 as [w [ba [t [p0 [bl [e [h [Hev21 [Hev22 Hev23]]]]]]]]].\n destruct p.\n inversion Hev21.\n destruct c.\n inversion Hev23.\n inversion Hev23.\n contradict ec; exists l; reflexivity.\n contradict ep; exists l; auto.\nQed.\n\nLemma dec_Ewin : forall (s: STV) (p c : Machine_States),\n ewin s p c -> forall (ep : ~ State_final p) (ec : ~ State_final c),\nOrder_NatProduct (Measure_States (IsNonFinal c ec))\n  (Measure_States (IsNonFinal p ep)).\nProof.\n intros s p c Hr ep ec.\n destruct s.\n simpl in Hr.\n unfold SanityCheck_Ewin_Red in evidence_reducibility_ewin0.\n specialize (evidence_reducibility_ewin0 p c Hr).\n destruct evidence_reducibility_ewin0 as [w [ba [t [p0 [e [h [Hev21 [Hev22 [Hev23 Hev24]]]]]]]]].\n destruct p.\n inversion Hev21.\n inversion Hev22.\n destruct c.\n inversion Hev24.\n inversion Hev24.\n contradict ec; exists l; auto.\n contradict ep; exists l; auto.\nQed.\n   \n \nLemma measure_dec : forall (s: STV) (p c: Machine_States), \n    (initStep s p c) \n \\/ (count s p c) \n \\/ (elect s p c) \n \\/ (transfer_elected s p c) \n \\/ (transfer_removed s p c)  \n \\/ (elim s p c) \n \\/ (hwin s p c) \\/ (ewin s p c) -> \n    forall (ep : ~ State_final p) (ec: ~ State_final c), \n    Order_NatProduct (Measure_States (IsNonFinal c ec)) \n                     (Measure_States (IsNonFinal p ep)).   \nProof.\n intros s p c H ep ec.\n destruct H.\n apply (dec_Initial s p c H ep ec).\n destruct H.\n apply (dec_Count s p c H ep ec).\n destruct H.\n apply (dec_Elect s p c H ep ec).\n destruct H.\n apply (dec_TransferElected s p c H ep ec).\n(* destruct H.\n apply (dec_TransferElected2 s p c H ep ec). *)\n destruct H.\n apply (dec_TransferRemoved s p c H ep ec).\n destruct H.\n apply (dec_Elim s p c H ep ec).\n destruct H.\n apply (dec_Hwin s p c H ep ec).\n apply (dec_Ewin s p c H ep ec).\nQed.\n\n(*end of measure decreasing proof for new formalised rules*)\n(* start: Certificate st bs s (state (Filter bs, [nty], nas, [], \n                                    emp_elec,all_hopeful)) *)\n\n\nInductive Certificate \n   (st: nat) (bs: list ballot) \n   (s: STV) (j0: Machine_States): Machine_States -> Type:=\n  start:  \n  forall j, (j = j0) -> Certificate st bs s j0 j\n |appInit: \n  forall j1 j2, Certificate st bs s j0 j1 -> initStep s j1 j2 \n                 -> Certificate st bs s j0 j2 \n |appCount: \n  forall j1 j2, Certificate st bs s j0 j1 -> count s j1 j2 \n                 -> Certificate st bs s j0 j2   \n |appElect: \n  forall j1 j2, Certificate st bs s j0 j1 -> elect s j1 j2 \n                 -> Certificate st bs s j0 j2\n |appTransElected: \n  forall j1 j2, Certificate st bs s j0 j1 -> transfer_elected s j1 j2 \n                 -> Certificate st bs s j0 j2\n |appTransRemoved: \n  forall j1 j2, Certificate st bs s j0 j1 -> transfer_removed s j1 j2 \n                 -> Certificate st bs s j0 j2\n | appElim: \n  forall j1 j2, Certificate st bs s j0 j1 -> elim s j1 j2 \n                 -> Certificate st bs s j0 j2 \n | appHwin: \n  forall j1 j2, Certificate st bs s j0 j1 -> hwin s j1 j2 \n                 -> Certificate st bs s j0 j2\n | appEwin: \n  forall j1 j2, Certificate st bs s j0 j1 -> ewin s j1 j2 \n                 -> Certificate st bs s j0 j2.\n\nLemma Rule_Application : forall (s: STV) (j1: Machine_States), ~ (State_final j1) -> \n   existsT j2, {initStep s j1 j2} + {count s j1 j2} + {elect s j1 j2} + {transfer_elected s j1 j2} + \n   {transfer_removed s j1 j2} + {elim s j1 j2} + {hwin s j1 j2} + {ewin s j1 j2}. \nProof.\n intros s j1 H.\n destruct s.\n destruct j1.\n simpl.\n unfold SanityCheck_Initial_App in  evidence_applicability_initStep0. \n specialize (evidence_applicability_initStep0  (initial l) l (eq_refl)).\n destruct evidence_applicability_initStep0 as [conc [H11 H12]].\n exists conc.\n left; left; left; left; left;left. auto.\n simpl.\n destruct p as [[[[[ba t] pile] bl] e] h].\n specialize (lt_eq_lt_dec (length (proj1_sig e)) X.st). intro LenElected.\n (* examining if we have filled all seats *)\n destruct LenElected as [LenElected1 | LenElected2]. \n destruct LenElected1 as [LenElected11 | LenElected12].\n (* the case where there are seats to fill *)\n specialize (le_gt_dec (length (proj1_sig e) + length (proj1_sig h)) X.st). intro LenElectedHopeful.\n (* examining the length of elected and hopeful togather *)\n destruct LenElectedHopeful as [LenElectedHopeful1 | LenElectedHopeful2]. \n (* the case where len (e ++ h) <= st *)\n (*destruct evidence_hwin0 as [HevHwin1 HevHwin2].*)\n unfold SanityCheck_Hwin_App in evidence_applicability_hwin0.\n specialize (evidence_applicability_hwin0 (state (ba, t, pile, bl, e, h)) ba t pile bl e h  (eq_refl) LenElectedHopeful1).\n destruct evidence_applicability_hwin0 as [conc HevHwin11]. \n exists conc.\n left. right. assumption.\n (* the case where are more elected and hopeful than seats and less elected than seats*)\n destruct ba. \n assert (([]<> (proj1_sig h)) -> \n       existsT d, In d (proj1_sig h) /\\  (forall d', In d' (proj1_sig h) -> \n       ((hd nty t) d' <= (hd nty t) d)%Q)) by\n           apply (list_max_cor X.cand (proj1_sig h) (hd nty t)).\n assert (forall (q:Q), ((forall c, In c (proj1_sig h) -> \n   ((hd nty t)(c) < q)%Q) + (existsT c: X.cand, In c (proj1_sig h) /\\ ((hd nty t) (c) >= q)%Q))). \n induction (proj1_sig h).\n intro q0.\n left; intros. contradict H0.\n assert (forall a: X.cand, forall h : list X.cand, [] <> a::h).\n intros.\n intro.\n inversion H0.\n specialize (X (H0 a l)).\n destruct X.\n destruct a0.\n assert (forall (q1: Q), (sumbool (((hd nty t) x < q1)%Q) ((q1 <= (hd nty t) x)%Q))).\n intro q1.\n apply (Qlt_le_dec ((hd nty t) x) q1).\n intro q2.\n specialize (H3 q2).\n destruct H3.\n left.\n intros.\n specialize (H2 c H3).\n apply (Qle_lt_trans ((hd nty t) c) ((hd nty t) x) q2).\n auto. auto.\n right.\n exists x.\n split; auto ; auto.\n specialize (X0 X.quota).\n destruct X0.\n destruct bl as [bl1 bl2].\n destruct bl1.\n assert ((proj1_sig h) <> []).\n specialize (list_min X.cand (proj1_sig h) (hd nty t)).\n intro.\n destruct X0.\n destruct (proj1_sig h).\n simpl in LenElectedHopeful2. \n omega.\n inversion e0.\n destruct s.\n destruct a. \n intro. rewrite H2 in H0. inversion H0.\n (* the case for elimination or transfer_removed*)\n destruct bl2.\n (* elimination *)\n unfold SanityCheck_Elim_App in evidence_applicability_elim0.\n specialize (evidence_applicability_elim0 (state ([], t, pile, ([], []), e, h)) t pile e h [] (eq_refl)).\n intuition. \n destruct X1 as [conc Hconc]. trivial. auto.\n exists conc.\n left; left; right. auto.\n (* the case where bl2 is not empty *)\n  assert (Hyz: sumbool (concat (pile c) = []) (concat (pile c) <> [])).\n destruct (concat (pile c)). left;auto. right. intro XX. inversion XX.\n (* the case when c's votes have all been distributed*)\n destruct Hyz as [Hyz1 | Hyz2]. \n specialize(evidence_applicability_elim0 (state ([],t, pile,([],c:: bl2),e,h)) t pile e h (c::bl2) (eq_refl)). intuition.  \n destruct X2 as [conc Hconc].  exists c. exists bl2. auto. assumption.\n exists conc.\n left;left;right. auto.\n (* the case when c's votes have not all been distributed *)\n (* the case for transfer_removed *)\n unfold SanityCheck_TransferRemoved_App in evidence_applicability_transferRemoved0. \n specialize (evidence_applicability_transferRemoved0 (state ([], t, pile,([],c::bl2),e, h)) t pile [] bl2 c e h (eq_refl)). \n intuition.\n destruct X0 as [conc Hconc].\n exists conc.\n left; left; left; right. auto.\n (* the case of transfer *)\n unfold SanityCheck_TransferElected_App in evidence_applicability_transferElected0.\n (* here I pull the rabit out and destruct on the second component of backlog to take care of Victoria-elim*)\n destruct bl2.\n specialize (evidence_applicability_transferElected0 (state ([], t, pile, (c::bl1, []), e,h)) t pile (c::bl1) [] e h).\n simpl in evidence_applicability_transferElected0.\n intuition. \n assert (Hyp: c:: bl1 = [] -> False). intro Hyp1. simpl in Hyp1. inversion Hyp1. \n intuition.\n destruct X0 as [conc X31].\n exists conc. \n left; left;left;left. right. assumption.\n (* the case where the snd of backlog is not empty, still in transfer phase*)\n (* the following part is commented out because of the change for transferRemoved *)\n (* assert (Hyz: sumbool (concat (pile c0) = []) (concat (pile c0) <> [])).\n destruct (concat (pile c0)). left;auto. right. intro.  inversion H0.\n destruct Hyz as [i | j].\n (* if the snd of backlog is empty then continue with the noraml transfer of elected votes *) \n unfold SanityCheck_Transfer2_App in evidence_applicability_transfer2_elected0 . \n specialize (evidence_applicability_transfer2_elected0 (state ([], t,pile, (c::bl1, c0:: bl2), e, h)) t pile \n                 (c::bl1) bl2 c0 e h (eq_refl)).\n simpl in evidence_applicability_transfer2_elected0.\n assert (auxTransHyp1: c::bl1 <> []). intro myhyp. inversion myhyp.\n intuition.\n destruct X0 as [conc X11].\n exists conc. \n left;left;left; left. right. assumption. *)\n\n (* the case where bl2 is not empty*)\n  assert (Hyz: sumbool (concat (pile c0) = []) (concat (pile c0) <> [])).\n destruct (concat (pile c0)). left;auto. right. intro XX. inversion XX.\n destruct Hyz as [Hyz1 | Hyz2].\n(* the subcase where c0's votes have all been distributed*)\n(*specialize (evidence_applicability_transferElected0 (state ([],t,pile,(c::bl1,*)\nspecialize (evidence_applicability_transferElected0 (state ([],t,pile,(c::bl1,c0::bl2),e,h)) t pile (c::bl1) (c0::bl2) e h (eq_refl)).\n assert (HypoX: c :: bl1 <> []). intro XXX. inversion XXX.\nintuition. \ndestruct X2 as [conc Hconc]. exists c0. exists bl2. auto. auto.\n exists conc.  \nleft;left;left;left. right. auto.\n(* the subcase when c0's votes are not fully distributed*)\n specialize (evidence_applicability_transferRemoved0 (state ([], t, pile, (c::bl1, c0::bl2), e, h)) t pile\n                 (c::bl1) bl2 c0 e h (eq_refl)).\n simpl in evidence_applicability_transferRemoved0.\n assert (hypAux: c::bl1 <> []). intro myhyp. inversion myhyp.\n intuition.\n destruct X0 as [conc X11].\n exists conc.\n left; left; left; right. assumption.\n (* the case for electing *)\n unfold SanityCheck_Elect_App in evidence_applicability_elect0. \n specialize (evidence_applicability_elect0 (state ([], t, pile, bl, e, h)) t pile bl e h (eq_refl)).\n destruct s as [c s1].\n assert (HypE2: existsT c, (length (proj1_sig e)) + 1 <= X.st /\\ (In c (proj1_sig h)) \n                                                           /\\ (X.quota <= (hd nty t) c)%Q). \n exists c.\n split. omega. \n auto.\n specialize (evidence_applicability_elect0 HypE2).\n destruct evidence_applicability_elect0 as [conc HevElect21]. \n exists conc.\n left; left; left; left; left; right. assumption.\n (* the case for count application *)\n unfold SanityCheck_Count_App in evidence_applicability_count0.  \n specialize (evidence_applicability_count0 (state (b ::ba, t, pile, bl, e, h)) (b::ba) t pile bl h e (eq_refl)).\n assert (HyCount: (b:: ba) <> []). intro. inversion H0.\n specialize (evidence_applicability_count0 HyCount). \n destruct evidence_applicability_count0 as [conc HevCount].\n exists conc.\n left; left; left; left; left; left; right. auto.\n (* the case for ewin *)\n unfold SanityCheck_Ewin_App in evidence_applicability_ewin0.\n specialize (evidence_applicability_ewin0 (state (ba, t, pile, bl, e, h)) ba t pile bl e h  (eq_refl)). \n intuition.\n destruct X as [conc X1]. \n exists conc.\n right. assumption.\n (* the impossible case where len e > st *)\n destruct e as [e0 e1].\n simpl in LenElected2.\n omega.\n simpl.\n contradict H. exists l. reflexivity.\nQed.\n\nLemma Extending_Certificate : forall (bs: list ballot), \n  forall (s: STV),\n  forall j0 j1, forall (ej0: ~ State_final j0) (ej1: ~ State_final j1), Certificate X.st bs s j0 j1 ->\n    existsT j2, \n        (Certificate X.st bs s j0 j2) * \n        (forall ej2: (~ State_final j2), Order_NatProduct (Measure_States (IsNonFinal j2 ej2)) (Measure_States (IsNonFinal j1 ej1))).                     \nProof.\n intros bs s j0 j1 ej0 ej1 H0.\n specialize (Rule_Application s j1 ej1). intro H1.\n destruct H1 as [conc H11].\n destruct H11 as [LH11 | RH11]. \n destruct LH11 as [LLH11 | RLH11].\n destruct LLH11 as [LLLH11 | RLLH11]. \n destruct LLLH11 as [LLLLH11 | RLLLH11].\n destruct LLLLH11 as [LLLLLH11 | RLLLLH11].\n destruct LLLLLH11 as [L6H11 | RL5H11].\n destruct L6H11 as [L7H11 |L7H12].\n (*destruct L7H11 as [L8H11 | L8H12]. *)\n exists conc.\n split.\n apply (appInit X.st bs s j0 j1). assumption. auto.\n intro evconc. \n apply (dec_Initial s j1 conc L7H11). \n exists conc. \n split.\n apply (appCount X.st bs s j0 j1). assumption. auto.\n apply (dec_Count s j1 conc L7H12).\n exists conc.\n split.\n apply (appElect X.st bs s j0 j1). assumption. auto.\n apply (dec_Elect s j1 conc RL5H11). \n exists conc. \n split. \n apply (appTransElected X.st bs s j0 j1).  assumption. auto.\n apply (dec_TransferElected s j1 conc RLLLLH11).\n exists conc.\n split.\n(* apply (appTrans2 X.st bs s j0 j1). assumption. auto.\n apply (dec_TransferElected2 s j1 conc RLLLLH11).\n exists conc.\n split. *)\n apply (appTransRemoved X.st bs s j0 j1). assumption. auto.\n apply (dec_TransferRemoved s j1 conc RLLLH11).\n exists conc.\n split.\n apply (appElim X.st bs s j0 j1). assumption. auto.\n apply (dec_Elim s j1 conc RLLH11). \n exists conc.\n split.\n apply (appHwin X.st bs s j0 j1). assumption. auto.\n apply (dec_Hwin s j1 conc RLH11).\n exists conc.\n split.\n apply (appEwin X.st bs s j0 j1). assumption. auto.\n apply (dec_Ewin s j1 conc RH11). \nQed.\n\nLemma Termination_Aux : forall (bs: list ballot),\n  forall (s: STV), \n  forall n: Product_Five_NatSet, \n  forall j0 (evj0: ~ State_final j0),\n  forall j (evj: not (State_final j)), Measure_States (IsNonFinal j evj) = n -> \n        Certificate X.st bs s j0 j -> \n           existsT j', (State_final j') * (Certificate X.st bs s j0 j').\nProof.                                                \n intros bs s n j0 evj0. \n induction n as [w IH] using (well_founded_induction_type Order_NatProduct_wf).\n intros j evj Eqn Certj.\n assert (Hex: existsT j', \n   (Certificate X.st bs s j0 j') * \n   (forall evj' : not (State_final j'), Order_NatProduct (Measure_States (IsNonFinal j' evj')) (Measure_States (IsNonFinal j evj)))).  \n apply (Extending_Certificate bs s j0 j evj0 evj Certj). \n destruct Hex as [j' [Hex1 Hex2]].\n destruct (final_dec j') as [f | nf].\n exists j'. split. assumption. auto.\n specialize (Hex2 nf).\n rewrite <- Eqn in IH.\n destruct (IH (Measure_States (IsNonFinal j' nf)) Hex2 j' nf) as [j'' Hj''].\n reflexivity.  \n assumption.\n exists j''.\n auto.\nQed.\n\nTheorem Termination : forall (bs: list ballot),\nforall j0 (evj0: ~State_final j0), forall (s: STV), \n                            existsT j, (State_final j) * (Certificate X.st bs s j0 j).\nProof.\n intros bs j0 evj0 s.\n destruct (final_dec j0) as [f | ea].\n (*destruct (final_dec (state (Filter bs, [nty], nas, [], \n                                    emp_elec,all_hopeful))) as [f | ea].*)\n (*exists (state (Filter bs, [nty], nas, [], \n                                    emp_elec,all_hopeful)). *)\n contradict evj0.\n assumption.\n apply (Termination_Aux bs s (Measure_States (IsNonFinal j0 ea)) j0 ea j0 ea).  \n reflexivity.\n apply start. auto.\nQed. \n\n(*End Generic_Machine.*)\n\n(*Section Base_Proofs.*)\n\n(* relation for `first continuing candidate' on a ballot in the list of ballots requiring attention *)\nDefinition fcc (ba : list ballot) (h : list X.cand) (c : X.cand) (b : ballot): Prop := \n  In (proj1_sig (fst b)) ((map (fun (d: ballot) => (proj1_sig (fst d)))) ba) /\\\n  In c h /\\\n  (exists l1 l2 : list X.cand, \n      proj1_sig (fst b) = l1 ++ [c] ++ l2 /\\ \n      forall d, (In d l1 -> ~(In d h))).\n\n(*checks if no cadidate whose name is in h, does not precede the candidate c in the list l*)\nFixpoint is_first_hopeful (c: X.cand) (h: list X.cand) (l : list X.cand):=\n match l with\n          [] => false\n          |l0::ls =>  if (X.cand_in_dec c h) then\n                                               if X.cand_eq_dec l0 c then true \n                                               else                     \n                                                   if X.cand_in_dec l0 h then false\n                                                   else is_first_hopeful c h ls\n                      else false  \n end. \n\n\n\n(*collects all of the ballots where c is the first continuing preference*)\nFixpoint list_is_first_hopeful (c: X.cand) (h: list X.cand) (ba: list ballot):=\n match ba with\n          [] => []\n          |b0::bas => if (is_first_hopeful c h (proj1_sig (fst b0))) \n                         then b0::(list_is_first_hopeful c h bas)\n                      else (list_is_first_hopeful c h bas)        \n end.\n\nFixpoint List_IsFirst_Hopeful (c: X.cand) (h :list X.cand) (acc: list ballot) (ba: list ballot) :=\n match ba with\n         [] => acc\n        |b0 :: bas => if is_first_hopeful c h (proj1_sig (fst b0))\n                        then List_IsFirst_Hopeful c h (b0 :: acc) bas\n                      else List_IsFirst_Hopeful c h acc bas\n end.\n\n(*every ballot b which c is its first preference, is an elements of the uncounted ballots ba, so that ballots are not assigned to a cadidate from an illegal source*) \nLemma weakened_is_first_hopeful_ballot: forall c h ba, forall (d: ballot), In (proj1_sig (fst d)) (map (fun (d0: ballot) => (proj1_sig (fst (d0)))) (list_is_first_hopeful c h ba)) -> In (proj1_sig (fst d)) (map (fun (d: ballot) => (proj1_sig (fst d))) ba).\nProof.\n intros.\n induction ba.\n simpl in H.\n inversion H.\n specialize (list_eq_dec (X.cand_eq_dec) (proj1_sig (fst d)) (proj1_sig (fst a))).\n intro H'1.\n destruct H'1 as [e |n].\n rewrite e.\n simpl.\n left;auto.\n simpl in H.\n simpl.\n right.\n apply IHba.\n destruct is_first_hopeful.\n simpl in H.\n destruct H as [Hi |Hj].\n rewrite Hi in n.\n contradiction n;reflexivity.\n assumption.\n auto.\nQed.\n\nLemma nonempty_list_notempty: forall l1 l2 (c: X.cand), [] <> l1++[c]++l2.\nProof.\n intros l1' l2' c'.   \n intro H'.       \n induction l1'.\n simpl in H'.\n inversion H'.\n rewrite <- (app_comm_cons) in H'.       \n inversion H'.\nQed.\n\n\n(*if c is not the first continuing candidate in a ballot, then he does not receive that vote*) \nLemma first_hopeful_false: forall c h d0 l1 l2, In d0 l1 -> In d0 h -> NoDup (l1++[c]++l2) -> is_first_hopeful c h (l1++[c]++l2) = false.\nProof.\n intros c h d0 l1 l2 H1 H2 H3.\n induction l1.\n simpl.\n inversion H1.\n destruct (X.cand_eq_dec d0 a).\n simpl.\n destruct (X.cand_in_dec c h) as [CandInDec1 |CandInDec2].\n destruct (X.cand_eq_dec a c) as [i | j].\n rewrite i in H3.\n inversion H3.\n assert (Hypo: In c (l1++c::l2)).\n intuition.\n contradiction H4.\n destruct (X.cand_in_dec a h) as [p |q].\n auto.\n rewrite e in H2.\n contradiction q.  auto.\n simpl.\n destruct (X.cand_in_dec c h) as [CandInDec1 | CandInDec2].\n destruct (X.cand_eq_dec a c) as [i' | j'].\n rewrite i' in H3.\n inversion H3.\n exfalso.\n apply H4.\n intuition.\n destruct (X.cand_in_dec a h) as [p' |q'].\n auto.\n apply IHl1.\n destruct H1 as [H11 |H12].\n contradiction n;symmetry;auto.\n assumption.\n inversion H3.\n simpl;assumption.\n reflexivity.\nQed.\n\n(*if c is the first continuing candidate of a ballot, then he gets that vote*)\nLemma first_hopeful_true: forall c (h: {hopeful: list X.cand | NoDup hopeful}) (b: ballot) (ba: list ballot) l1 l2,(forall d, In d l1 -> ~ In d (proj1_sig h)) /\\ (exists (d: ballot), (proj1_sig (fst d)) = l1++[c]++l2) /\\ (In c (proj1_sig h)) -> is_first_hopeful c (proj1_sig h) (l1++[c]++l2) = true.\nProof.\n intros c h b ba l1 l2 H1.\n destruct H1 as [H11 [H12 H13]].\n assert (Hypo: NoDup (l1++[c]++l2) /\\ ( []<> l1++[c]++l2)).\n destruct H12 as [d H121].\n destruct d as [[b1 [b121 b122]] b2]. \n simpl in H121.\n split.\n simpl.\n rewrite <- H121.\n assumption.\n intro H3.\n simpl in H3.\n rewrite <- H121 in H3.\n apply b122.\n assumption.\n destruct Hypo as [Hypo1 Hypo2].\n induction l1.\n simpl.\n destruct (X.cand_in_dec c (proj1_sig h)) as [CandInDec1 | CandInDec2].\n destruct (X.cand_eq_dec c c) as [i1 |i2].\n auto.\n contradiction i2.\n auto.\n contradiction CandInDec2.\n simpl.\n destruct (X.cand_in_dec c (proj1_sig h) ) as [CandInDec3 | CandInDec4].\n destruct (X.cand_in_dec a (proj1_sig h)).\n specialize (H11 a).\n assert (Hypo: In a (a::l1)).\n left;auto.\n specialize (H11 Hypo).\n contradiction H11.\n destruct (X.cand_eq_dec a c) as [CandEqDec1 |CandEqDec2].\n reflexivity.\n apply IHl1.\n intros d0 H2.\n specialize (H11 d0).\n apply H11.\n right;assumption.\n specialize (nonempty_list_notempty l1 l2 c);intro Hypo5.\n assert (Hypo4: NoDup (l1++[c]++l2) /\\ ([] <> l1++[c]++l2)).\n inversion Hypo1.\n split;simpl.\n assumption.\n intro H5.\n contradiction Hypo5.\n exists ((exist (fun v => NoDup v /\\ ([] <> v)) (l1++[c]++l2) Hypo4), (1)%Q).\n simpl.\n auto.\n inversion Hypo1.\n simpl;assumption.\n specialize (nonempty_list_notempty l1 l2 c);intro Hypo6;auto.            \n contradiction CandInDec4.\nQed.\n\n(*c receives all of the ballots that prefer him as their first contiuing choice*)\nLemma fcc_listballot: forall ba (h: {hopeful: list X.cand | NoDup hopeful}),(forall c, forall d: ballot,  fcc ba (proj1_sig h) c d -> In (proj1_sig (fst d)) (map (fun (d0:ballot) => (proj1_sig (fst d0))) (list_is_first_hopeful c (proj1_sig h) ba))).\nProof.\n intros ba h c.\n intros d H4.\n unfold fcc in H4.\n destruct H4 as [H4_1 [H4_2 [l1 [l2 [H4_3 H4_4]]]]].\n induction ba.\n inversion H4_1.\n simpl.\n specialize (list_eq_dec (X.cand_eq_dec) (proj1_sig (fst d)) (proj1_sig (fst a))).\n intro H'.\n destruct H' as [i |j ].\n rewrite<- i.\n rewrite H4_3.\n rewrite (first_hopeful_true c h d ba l1 l2).\n left;auto.\n rewrite<- i.\n assumption.\n split.\n auto.\n split.\n exists d. assumption. assumption.\n destruct (is_first_hopeful).\n right.\n apply IHba.\n destruct H4_1.\n contradiction j.\n auto. \n assumption.\n apply IHba.\n destruct H4_1.\n contradiction j.\n auto.\n assumption.\nQed.\n\n(*if c is not a continuing candidate, he does not receive any vote any more*)\nLemma is_first_hopeful_In: forall (c:X.cand) h l, is_first_hopeful c h l =true -> In c l.\nProof.\n intros c h l H1.\n induction l.\n simpl in H1.\n inversion H1.\n destruct (X.cand_in_dec a h) as [i1 | i2].\n unfold is_first_hopeful in H1.\n destruct (X.cand_in_dec c h) as [p1 |p2].\n destruct (X.cand_eq_dec a c) as [j1 |j2].\n left;assumption.\n destruct (X.cand_in_dec a h) as [s1 |s2].\n inversion H1.\n contradiction s2.\n right.\n apply IHl.\n inversion H1.\n right.\n apply IHl. \n assert (Hypo: is_first_hopeful c h (a::l) = is_first_hopeful c h l).\n induction l.\n unfold is_first_hopeful in H1.\n destruct (X.cand_in_dec) as [CandInDec1 | CandInDec2].\n destruct (X.cand_eq_dec a c) as [CandEqDec1 |CandEqDec2].\n rewrite  CandEqDec1 in i2.\n contradiction i2.\n destruct (X.cand_in_dec a h) as [CandInDec3 | CandInDec4].\n contradiction i2.\n inversion H1.\n inversion H1.\n simpl.\n destruct (X.cand_in_dec c h) as [p1 |p2].\n destruct (X.cand_eq_dec a c ) as [p3 |p4].\n rewrite p3 in i2.\n contradiction i2.\n destruct (X.cand_in_dec a h) as [p5 |p6].\n contradiction i2.\n destruct (X.cand_eq_dec a0 c) as [p7 |p8].\n reflexivity.\n destruct (X.cand_in_dec a0 h) as [p9 |p10].\n reflexivity.\n reflexivity.\n reflexivity.\n rewrite <- Hypo.\n assumption.\nQed.\n\nLemma list_is_first_hopeful_In: forall (ba: list ballot) (b:ballot) (h: {hopeful:list X.cand | NoDup hopeful}) (c:X.cand),  In (proj1_sig (fst b)) (map (fun (d:ballot) => (proj1_sig (fst d))) (list_is_first_hopeful c (proj1_sig h) ba)) -> In c (proj1_sig (fst b)). \nProof.\n intros ba b h c H1.\n unfold list_is_first_hopeful in H1.\n induction ba.\n simpl in H1.\n exfalso.\n assumption.\n simpl in H1.\n specialize (is_first_hopeful_In c (proj1_sig h) (proj1_sig (fst a)));intro H2.\n destruct is_first_hopeful.\n simpl in H1.\n destruct H1.\n rewrite <- H.\n apply H2.\n reflexivity.\n apply IHba. \n auto.\n apply IHba.\n assumption.\nQed.\n\n(*all the ballots which have already been filtered have no duplicate*)\nLemma ballot_nodup: forall (ba: list ballot) (t : list (X.cand ->Q)) (p: X.cand -> list (list ballot)) bl (e: {elected: list X.cand | length elected <= X.st}) (h: {hopeful : list X.cand | NoDup hopeful}) s,s= state (ba, t, p, bl, e, h) -> forall b: ballot, NoDup (proj1_sig (fst b)).\nProof.\n intros ba t p bl e h  s H1 b.\n destruct b as [[b11 [b121 b122]] b2].\n simpl.\n  assumption.\nQed.\n\n\n(*if c is not the first continuing candidate in a ballot then c does not receives it*)\nLemma weakened_list_is_first_notin: forall (t: list (X.cand -> Q)) (e: {elected:list X.cand| length elected <= X.st}) (p: X.cand -> list (list ballot)) (bl: (list X.cand) * (list X.cand)) c (h: {hopeful: list X.cand | NoDup hopeful}) (n:Q) ba (d:ballot) (d0:X.cand) l1 l2, proj1_sig (fst d)= l1++[c]++l2 -> In d0 l1 -> In d0 (proj1_sig h) -> ~ In (proj1_sig (fst d)) (map (fun (d' :ballot) => (proj1_sig (fst d'))) (list_is_first_hopeful c (proj1_sig h) ba)).\nProof.\n intros t e p bl c h n ba d d0 l1 l2 H1 H2 H3.\n induction ba.\n simpl.\n intro.\n auto.\n intro H4.\n specialize (list_eq_dec (X.cand_eq_dec) (proj1_sig (fst (d))) (proj1_sig (fst a))).\n intro H'.       \n simpl in H4.\n destruct H' as [h' |h''].\n rewrite<-  h' in H4.\n rewrite H1 in H4.\n rewrite (first_hopeful_false c (proj1_sig h) d0 l1 l2) in H4.\n rewrite <- H1 in H4.        \n contradiction IHba.\n assumption.\n assumption.\n rewrite <- H1.\n apply (ballot_nodup ba t p bl e h (state (ba, t, p, bl, e, h))).\n reflexivity.\n destruct (is_first_hopeful).\n destruct H4.\n destruct a.\n destruct d.\n rewrite H in h''.\n contradiction h''.\n auto.\n contradiction IHba.\n contradiction IHba.\nQed.\n\n(*c gets exactly those ballots which have him as their first continuing candidate*)\nLemma listballot_fcc: forall ba (t: list (X.cand -> Q)) (p: X.cand -> list (list ballot)) (bl: (list X.cand) * (list X.cand)) (e: {elected: list X.cand | length elected <= X.st}) (h: {hopeful: list X.cand | NoDup hopeful}) (n:Q), (forall c, In c (proj1_sig h) -> forall d: ballot, In (proj1_sig (fst d)) (map (fun (d':ballot) => (proj1_sig (fst d'))) (list_is_first_hopeful c (proj1_sig h) ba)) <-> fcc ba (proj1_sig h) c d).\nProof.\n intros ba t p bl e h n.\n intros c H3.\n split.\n intro H4.\n unfold fcc.\n split.\n apply (weakened_is_first_hopeful_ballot  c (proj1_sig h) ba).\n assumption.\n split.\n assumption.\n assert (Hypo: In c (proj1_sig (fst d))).\n apply (list_is_first_hopeful_In ba d h c H4).\n specialize (in_split c (proj1_sig (fst d)) Hypo);intro H5.\n destruct H5 as [l1 [l2 H5_2]].\n exists l1.\n exists l2.\n split.\n auto.\n intros d0 H6.\n intro H7.\n assert (Hypo2: ~ In (proj1_sig (fst d)) (map (fun (d' :ballot) => (proj1_sig (fst d'))) (list_is_first_hopeful c (proj1_sig h) ba))). \n apply (weakened_list_is_first_notin t e p bl c h n ba d d0 l1 l2 H5_2 H6 H7).\n contradiction Hypo2.\n intro H4.\n specialize (fcc_listballot ba h c d H4);intro H5.\n assumption.\nQed.\n\nLemma list_nonempty: forall (A: Type) (l: list A), [] = l \\/ exists b l', l= b::l'.\nProof.\n intros A l.\n induction l.\n left.\n auto.\n destruct IHl as [i | j].\n right.\n exists a.\n exists ([]: list A).\n rewrite <- i.\n auto.\n destruct j as [b [l' H1]].\n right.\n exists a.\n exists (b::l').\n rewrite H1.\n reflexivity.\nQed.\n\nLemma list_nonempty_type: forall (A: Type) (l : list A), l <> [] -> existsT b l', l = b :: l'.\nProof.\n intros A l H.\n specialize (destruct_list l). intro.\n destruct X.\n destruct s.\n destruct s. \n exists x.\n exists x0.\n auto.\n contradict H. assumption.\nQed.\n\nDefinition eqe {A: Type} (x:A) (l: list A) (nl: list A) : Prop :=\n exists l1 l2: list A, \n  l = l1 ++ l2 /\\ \n  nl = l1 ++ [x] ++ l2 /\\ \n  (~ In x l1) /\\ \n  (~ In x l2).\n\nFixpoint remc (c: X.cand) (l: list X.cand) :=\n match l with \n    nil => nil\n   | cons l0 ls => if (X.cand_eq_dec c l0) then ls else cons l0 (remc c ls)\n end.\n\nLemma remc_ok : forall c:X.cand, forall l:list X.cand, NoDup l -> In c l -> eqe c (remc c l) l.\nProof.\n intros c l H1 H2.  \n induction l.\n inversion H2.\n assert (H3: {a =c} + {a <> c}) by apply (X.cand_eq_dec a c).\n destruct H3 as [H4 | H4].\n replace (remc c (a::l)) with l. \n unfold eqe.\n exists ([]:list X.cand).\n exists l.\n split.\n auto.\n split.\n rewrite H4.\n auto.\n split.\n intro H5.\n inversion H5.\n intro H5.\n inversion H1.\n rewrite<-  H4 in H5.\n intuition.\n rewrite H4.\n unfold remc.\n destruct (X.cand_eq_dec c c).\n reflexivity.\n contradiction n.\n auto.\n inversion H1.\n destruct H0 as [H5 H6].\n assert (H7: a =c \\/ In c l0) by apply (in_inv H2).\n destruct H7 as [H8 | H8].\n contradiction H4.\n assert (H9: (eqe c (remc c l0) l0 )) by apply (IHl H5 H8).\n replace (remc c (a::l0))  with (a::(remc c l0)).\n unfold eqe in H9.\n destruct H9 as [l1 H10].\n destruct H10 as [l2 H11].\n destruct H11 as [H12 [H13 H14]].\n unfold eqe.\n exists (a::l1).\n exists l2.\n split.\n simpl.\n rewrite H12.\n auto.\n split.\n simpl.\n rewrite H13.\n reflexivity.\n split.\n destruct H14 as [H15 H16].\n intro H17.\n destruct H17 as [H18 |H18].\n contradiction H4.\n contradiction H15.\n destruct H14 as [H15 H16].\n assumption.\n unfold remc.\n destruct (X.cand_eq_dec c a).\n contradict H4.\n symmetry.\n assumption.\n trivial.\nQed.\n\nLemma remc_contained_in_list: forall (l: list X.cand) c a, NoDup l -> In a (remc c l) -> In a l.\nProof.\n intros l c a H H1.\n induction l.\n simpl in H1.\n inversion H1.\n destruct (X.cand_eq_dec c a0) as [p |q].\n rewrite p in H1.\n simpl in H1.\n destruct (X.cand_eq_dec a0 a0) as [p1 | p2].\n right;assumption.\n contradiction p2;auto.\n assert (Hypo: (remc c (a0::l))= (a0::remc c l)).\n simpl.\n destruct (X.cand_eq_dec c a0) as [i | j].\n contradiction q.\n reflexivity.\n rewrite Hypo in H1.\n destruct H1 as [H1_1 | H1_2].\n left;assumption.\n right.\n apply IHl.\n inversion H.\n assumption.\n assumption.\nQed.\n\nLemma remc_nodup : forall (l : list X.cand) c, NoDup l -> In c l -> NoDup (remc c l).\nProof.\n intros l c H1 H2.\n induction l.\n inversion H2.\n destruct (X.cand_eq_dec c a) as [i |j].\n rewrite i.\n simpl.\n destruct (X.cand_eq_dec a a) as [ p |q].\n inversion H1.\n assumption.\n contradiction q;auto.\n replace (remc c (a::l)) with (a::remc c l).\n apply NoDup_cons.\n destruct H2 as [H2_1| H2_2].\n contradiction j.\n auto.\n inversion H1.\n intro H4.\n apply H2.\n apply (remc_contained_in_list l c a H3 H4).\n apply IHl.\n inversion H1.\n assumption.\n destruct H2 as [H2_1 |H2_2].\n contradiction j.\n auto.\n assumption.\n simpl.\n destruct (X.cand_eq_dec c a).\n contradiction j;auto.\n reflexivity.\nQed.\n\nInductive ordered {A : Type} (f : A -> Q) : list A -> Prop := \n  ord_emp : ordered f []  \n | ord_sing : forall x : A, ordered f [x]\n | ord_cons : forall l x y, ordered f (y :: l) -> (f(x) >= f(y))%Q -> ordered f (x :: y :: l).\n\nDefinition Leqe {A:Type} (k :list A) (l: list A) (nl: list A): Prop:=\n Permutation nl (l++k).\n\nLemma ordered_head: forall (A: Type) (x y:A) r f, ordered f (x::y::r) -> (f x >= f y)%Q.\nProof.\n intros.\n inversion H.\n auto.\nQed.\n\n(*if a list is ordered w.r.t. function f, then its tail is also ordered w.r.t.*)\nLemma ordered_tl: forall (A:Type)(a:A) f l, ordered f (a::l) -> ordered f l.\nProof.\n intros A a f l H0.\n inversion H0.\n apply ord_emp.\n auto.\nQed.\n\nLemma ordered_is_ordered: forall (A:Type) f (a b:A) l l'', (forall l', ordered f (l++[a]++l'++[b]++l'')) -> (f b <= f a)%Q.\nProof.\n intros.\n induction l.\n specialize (H ([]:list A)).\n simpl in H.\n apply (ordered_head A a b l'' f) in H.\n auto.\n apply IHl.\n intro.\n specialize (H l').\n rewrite<- app_comm_cons in H.\n apply (ordered_tl A a0 f (l++[a]++l'++[b]++l'')).\n auto.\nQed.\n\nLemma ordered_head_greatest: forall A:Type, forall f, forall a, forall b:A, forall l', (forall l,ordered f (a::(l++[b]++l')) )-> ( f b <= f a)%Q.\nProof.\n intros.\n specialize (ordered_is_ordered A f a b [] l').\n intros.\n apply H0.\n simpl.\n auto.\nQed.\n\nLemma ordered_head_rep: forall (A:Type) f (l:list A) (a b:A), ordered f (a::l) -> (f a <= f b)%Q -> ordered f (b::l).\nProof.\n intros.\n induction l.\n apply ord_sing.\n apply ord_cons.\n specialize (ordered_tl A a f (a0::l) H);intro.\n auto.\n apply (Qle_trans ( f a0) (f a) (f b)).\n apply (ordered_head A a a0 l f).\n auto.\n auto.\nQed.\n\n(*if a list is ordered w.r.t. f, then if one removes any segment ffrom it, the remainder list is ordered still.*) \nLemma ordered_remove: forall (A:Type) f (l:list A) l' (a b:A), ordered f (a::l++[b]++l') -> ordered f (a::b::l').\nProof.\n intros.\n induction l.\n auto.\n apply IHl.\n inversion H. \n apply (ordered_head_rep A f (l++[b]++l') a0 a H2).\n auto.\nQed.\n\n(* if a list is ordered w.r.t. function f, given a new element a, one can always insert a into the list without destroying the order.*)\nLemma extend_ordered_type: forall A:Type, forall f: A -> Q, forall x: list A, ordered f x -> (forall a:A, (existsT y z, x =y++z /\\ ordered f (y++[a]++z))).\nProof.\n intros A f x H1 a.\n induction x.\n exists ([]: list A).\n exists ([]: list A).\n split.\n auto.\n apply ord_sing.\n destruct IHx.\n apply (ordered_tl A a0 f x).\n auto.\n destruct s as [z H2].\n destruct H2 as [H5 H6].\n assert (Hyp: sumbool ((f a0 < f a)%Q) ((f a <= f a0)%Q)) by apply (Qlt_le_dec (f a0)(f a)).\n destruct Hyp as [Hyp1 | Hyp2].\n destruct x0.\n simpl in H6.\n simpl in H5.\n rewrite H5 in H1.\n exists ([]: list A).\n exists (a0::z).\n repeat split.\n rewrite H5;auto.\n simpl.\n apply (Qlt_le_weak (f a0) (f a)) in Hyp1.\n apply ord_cons.\n auto.\n auto.\n rewrite H5 in H1.\n rewrite <- app_comm_cons in H1.\n specialize (ordered_head A a0 a1 (x0++z) f H1);intro.\n rewrite <- app_comm_cons in H6.\n specialize (ordered_head_greatest A f a1 a z).\n intro.\n specialize (ordered_remove A f x0 z a1 a H6);intro.\n specialize (ordered_head A a1 a z f H2);intro H11.\n specialize (Qlt_not_le (f a0) (f a) Hyp1);intro.\n specialize (Qle_trans (f a) (f a1) (f a0) H11 H);intro.\n contradiction.\n exists (a0::x0).\n exists z.\n rewrite H5.\n repeat split.\n induction x0.\n apply ord_cons.\n auto.\n assumption.\n rewrite H5 in H1.\n rewrite<- (app_comm_cons (a1::x0) ([a]++z) a0).\n apply (ord_cons f (x0++[a]++z) a0 a1).\n auto.\n specialize (ordered_head A a0 a1 (x0++z) f H1);intro.\n auto.\nQed.\n\n(*if a list has no duplication, then adding elements which were not in it does not creat duplication.*)\nLemma NoDup_middle: forall (a:X.cand) m1 m2, ~ In a (m1++m2) -> NoDup (m1++m2) -> NoDup (m1++[a]++m2).\nProof.\n intros a m1 m2 H1 H2.\n induction m1.\n apply NoDup_cons.\n auto.\n assumption.\n rewrite <-app_comm_cons .\n apply NoDup_cons.\n rewrite <- app_comm_cons in H2.\n inversion H2.\n intro h.\n apply H3.\n specialize (in_app_or m1 ([a]++m2) a0 h);intro h1.\n destruct h1 as [h2 | h3].\n intuition.\n destruct h3 as [h4 | h5].\n rewrite h4 in H1.\n destruct H1.\n left;auto.\n intuition.\n apply IHm1.\n intro h.\n apply H1.\n rewrite <- app_comm_cons.\n right.\n assumption.\n rewrite <- app_comm_cons in H2.\n inversion H2.\n assumption.\nQed.\n\n(*if there are vacancies, we can construct a list electable candidates who have reached the quota. Besides this list is orderedw.r.t. tally, and it contains all of such electable candidates.*)\nLemma constructing_electable_first: forall (e: {elected:list X.cand | length elected <= X.st}) (f: X.cand -> Q) (h: {hopeful: list X.cand | NoDup hopeful}) (qu:Q), X.st > length (proj1_sig e) -> NoDup (proj1_sig h) -> (existsT m, (forall x: X.cand, In x m -> In x (proj1_sig h) /\\ (qu <= f x)%Q) /\\ (ordered f m) /\\ NoDup m /\\ (length m <= X.st - (length (proj1_sig e))) /\\ (forall x, In x (proj1_sig h) /\\ (qu <= f x)%Q /\\ length m < X.st - length (proj1_sig e) -> In x m)). \nProof.\n intros e f h qu H H1. \n induction (proj1_sig h).\n exists ([]:list X.cand).\n split.\n intros x H2.\n inversion H2. \n split.\n apply ord_emp.\n split.\n assumption.\n split.\n simpl.\n omega.\n intros x H2.\n destruct H2 as [H2_1 H2_2].\n inversion H2_1.\n specialize (NoDup_remove_1 [] l a H1);intro H2.\n simpl in H2.\n assert (Hyp1: sumbool ((f a < qu)%Q) ((qu <= f a)%Q)) by apply (Qlt_le_dec (f a) qu).\n destruct Hyp1 as [Hyp1_1 | Hyp1_2].\n specialize (IHl H2).\n destruct IHl as [m H3].\n destruct H3 as [H3_1[ H3_2 H3_3 ]].\n destruct (X.cand_in_dec a m) as [i | j].\n specialize (H3_1 a i).\n destruct H3_1 as [H3_11 H3_12].\n specialize (Qlt_not_le (f a) qu Hyp1_1);intros H3_4.\n contradiction H3_4.\n exists m.\n split.\n intros x H4.\n split.\n destruct (X.cand_eq_dec a x) as [p | q].\n rewrite p in j.\n contradiction j.\n right.\n specialize (H3_1 x H4).\n intuition.\n specialize (H3_1 x H4).\n intuition.\n split.\n assumption.\n split.\n intuition.\n split.\n intuition.\n intros x H4.\n apply H3_3.\n destruct H4 as [H4_1 [H4_2 H4_3]].\n destruct H4_1 as [H4_11 | H4_12].\n rewrite H4_11 in Hyp1_1.\n specialize (Qlt_not_le (f x) qu Hyp1_1);intro H5.\n contradiction H5.                       \n repeat split;assumption.\n specialize (IHl H2).\n destruct IHl as [m H3].\n destruct H3 as [H3_1 [H3_2 H3_3]].\n destruct (X.cand_in_dec a m) as [i | j].\n specialize (H3_1 a i).\n destruct H3_1 as [H3_11 H3_12].\n specialize (NoDup_remove_2 [] l a H1);intros H5.\n contradiction H5.\n destruct H3_3 as [H3_31 [H3_32 H3_4]].\n specialize (le_lt_eq_dec (length m) (X.st - length (proj1_sig e)) H3_32);intro H3_33.\n destruct H3_33 as [H3_331 | H3_332].\n specialize (extend_ordered_type X.cand (f: X.cand -> Q) m H3_2 a);intro H4.\n destruct H4 as [m1 [m2 H4_1]].\n destruct H4_1 as [H4_5 H4_6].\n exists (m1++[a] ++m2).\n split.\n intros x H5.\n split.\n specialize (in_app_or m1 ([a]++m2) x H5);intro H6.\n destruct H6 as [H6_1 | H6_2].\n assert (Hyp2: In x m).\n rewrite H4_5.\n intuition.\n specialize (H3_1 x Hyp2).\n right.\n intuition.\n destruct H6_2 as [H6_3 | H6_4].\n left.\n assumption.\n right.\n assert (Hyp3: In x m).\n rewrite H4_5.\n intuition.\n specialize (H3_1 x).\n intuition.\n specialize (H3_1 x).\n destruct (X.cand_eq_dec a x) as [p |q].\n rewrite p in Hyp1_2.\n assumption.\n assert (Hyp4: In x m).\n specialize (in_app_or m1 ([a]++m2) x H5);intro H6.\n destruct H6 as [H6_1 | H6_2].\n rewrite H4_5.\n intuition.\n destruct H6_2 as [H6_3 | H6_4].\n contradiction q.\n rewrite H4_5.\n intuition.\n intuition.\n split.\n assumption.\n split.\n apply (NoDup_middle a m1 m2).\n rewrite H4_5 in j.\n assumption.\n rewrite <- H4_5.\n intuition.\n split.\n rewrite app_length.\n simpl.\n rewrite H4_5 in H3_331.\n rewrite app_length in H3_331.\n omega.\n intros x H5.\n destruct (X.cand_eq_dec a x) as [p | q].\n rewrite p.\n intuition.\n destruct H5 as [H5_1 [H5_2 H5_3]].\n destruct H5_1 as [H5_11 | H5_12].\n contradiction q.\n specialize (H3_4 x).\n intuition.\n rewrite H4_5 in H0.\n specialize (in_app_or m1 m2 x H0);intro H6.\n destruct H6 as [H6_1 | H6_2].\n apply (in_or_app).\n left;assumption.\n intuition.\n (* this is when a is over the quota but already we have filled all of the vacancies *)\n (* so I will simply ignore that a is electable. If a tie has occurred essentially the one preceding a wins *)\n exists m.\n split. \n intros x H4.\n split.\n right.\n specialize (H3_1 x).\n intuition.  \n specialize (H3_1 x).\n intuition.\n split.\n assumption.\n split.  \n auto.\n split.\n apply not_gt.\n intro H5.\n rewrite H3_332 in H5.\n omega.  \n intros x H5.\n destruct H5 as [H5_1 [H5_2 H5_3]].\n rewrite H3_332 in H5_3.\n omega.\nQed.\n\nDefinition update_pile (p: X.cand -> list (list ballot)) (t: list (X.cand -> Q)) l (q:Q) (c:X.cand): list (list ballot):=   \n if X.cand_in_dec c l \n    then  \n        map (map (fun (b : ballot) => \n        (fst b, (Qred (snd b * (Qred ((hd nty t)(c)- q)/(hd nty t)(c))))%Q))) (p c)\n    else ( p c).\n\nDefinition Update_transVal (c: X.cand) (p: X.cand -> list (list ballot)) (t: X.cand -> Q) :=\n let Sum_parcel := sum (last (p c) []) in\n  let r :=  (Qred ((Qred ((t c) - X.quota)) / Sum_parcel)) in\n    match (Qlt_le_dec 0 Sum_parcel) with\n       left _ => match (Qlt_le_dec r 1) with\n                    left _ => r\n                   |right _ => (1)%Q\n                 end\n       |right _ => (1)%Q\n    end.\n\n\nDefinition update_pile_ManualACT (p: X.cand -> list (list ballot)) (t: X.cand -> Q) (l: list X.cand) (q:Q) (c: X.cand):=\n if X.cand_in_dec c l\n    then\n       map (map (fun (b : ballot) =>\n         (fst b, (Qred (snd b * (Update_transVal c p t)))%Q))) [(last (p c) [])] \n    else (p c).\n\n(*removes every element of the list k which exist in the list l*)\nFixpoint Removel (k :list X.cand) (l :list X.cand) :list X.cand:=\n match l with\n        [] => []\n        |l0::ls => if (X.cand_in_dec l0 k) then (Removel k ls) else (l0::(Removel k ls))\n end.\n\n(*if a is not in l, then it is already removed from l*)\nLemma Removel_extra_element: forall a, forall k1 k2 l:list X.cand, ~ In a l -> Removel (k1++[a]++k2) l = Removel (k1++k2) l. \nProof.\n intros a k1 k2 l H1.\n induction l.\n simpl.\n auto.\n simpl.\n destruct (X.cand_in_dec a0 (k1++k2)) as [ i | j].\n assert (Hyp: ~ In a l).\n intro.\n apply H1.\n right;assumption.\n specialize (IHl Hyp).\n rewrite <- IHl.\n simpl.\n assert (In a0 (k1++[a]++k2)).\n specialize (in_app_or k1 k2 a0 i);intro Hyp2.\n destruct Hyp2 as [Hyp21 |Hyp22].\n intuition.\n intuition.\n destruct (X.cand_in_dec a0 (k1++a::k2)).\n auto.\n contradiction n.\n destruct (X.cand_in_dec a0 (k1++a::k2)).\n assert (Hyp3: ~ In a0 (k1++a::k2)).\n intro.\n specialize (in_app_or k1 (a::k2) a0 H);intro H3.\n destruct H3 as [H4 |H5].\n apply j.\n intuition.\n destruct H5 as [H51 |H52].\n apply H1.\n left.\n symmetry;assumption.\n apply j.\n intuition.\n contradiction Hyp3.\n assert (Hyp4: ~ In a l).\n intro.\n apply H1.\n intuition.\n specialize (IHl Hyp4).\n simpl in IHl.\n rewrite IHl.\n auto.\nQed.\n\n(*to remove particular elements from a list, one can split this removal into two parts*)\nLemma Removel_segmentation: forall k l1 l2: list X.cand, Removel k (l1++l2) = (Removel k l1) ++ (Removel k l2).\nProof.\n intros k l1 l2.\n induction l1.\n simpl.\n auto.\n rewrite<- (app_comm_cons l1 l2 a).\n simpl.\n destruct (X.cand_in_dec a k) as [ i |j].\n assumption.\n rewrite <- (app_comm_cons ).\n rewrite IHl1.\n auto.\nQed.\n\n(*if the orginal list is duplicate-free, so is any remainder list after removal of some elements*)\nLemma Removel_nodup: forall (k l :list X.cand), NoDup l -> NoDup (Removel k l).\nProof.\n intros k l H1.\n induction k.\n assert (Hyp: Removel [] l = l).\n induction l.\n simpl.\n auto.\n simpl.\n destruct (X.cand_in_dec a []).\n inversion i.\n rewrite IHl.\n auto.\n inversion H1.\n assumption.\n rewrite Hyp.\n assumption.\n destruct (X.cand_in_dec a l) as [i | j].\n specialize (in_split a l i);intro H2.\n destruct H2 as [l1 [l2 H3]].\n rewrite H3.\n rewrite (Removel_segmentation (a::k) l1 (a::l2)).\n rewrite H3 in H1.\n specialize (NoDup_remove_2 l1 l2 a H1);intro H4.\n assert (Hyp2: ~ In a l1 /\\ ~ In a l2).\n split.\n intuition.\n intuition.\n assert (Hyp3: Removel (a::k) l1 = Removel k l1).\n apply (Removel_extra_element a [] k l1).\n intuition.\n rewrite Hyp3.\n assert (Hyp5: Removel (a::k) (a::l2) = Removel k l2).\n assert (Hypo: a::l2 = [a]++l2).\n simpl.\n auto.\n rewrite Hypo.\n rewrite (Removel_segmentation (a::k) [a] l2).  \n assert (Hyp6: Removel (a::k) [a] = []).\n simpl.\n destruct (X.cand_in_dec a (a::k)).\n auto.\n contradiction n.\n left;auto.\n rewrite Hyp6.\n simpl.\n apply (Removel_extra_element a [] k l2).\n intuition.\n rewrite Hyp5. \n rewrite H3 in IHk.\n rewrite (Removel_segmentation k l1 (a::l2)) in IHk.\n assert (Hypo: a::l2 = [a]++l2).\n simpl;auto.\n rewrite Hypo in IHk.\n rewrite (Removel_segmentation k [a] l2) in IHk.\n assert (Hypo7: Removel k [a] = [] \\/ Removel k [a] = [a]).\n simpl.\n destruct (X.cand_in_dec a k) as [ p | q].\n left;auto.\n right;auto.\n destruct Hypo7 as [Hypo71 | Hypo72].\n rewrite Hypo71 in IHk.\n simpl in IHk.\n assumption.\n rewrite Hypo72 in IHk.\n apply (NoDup_remove_1 (Removel k l1) (Removel k l2) a).\n assumption.\n assert (Hyp: a::k = [a]++k).\n simpl;auto.\n rewrite Hyp.\n assert (Hyp8: [a]++k = []++[a]++k).\n simpl.\n auto.\n rewrite Hyp8.\n rewrite (Removel_extra_element a [] k l).\n simpl.\n assumption.\n assumption.\nQed.\n\n(*if l is a permutation of a list l', then if one changes the position of one element, still he gets a permutation of l*) \nLemma Permutation_reorder: forall (A :Type) (l: list A) k1 k2, forall a:A, Permutation l (k1++[a]++k2) -> Permutation l ((a::k1)++k2).\nProof.\n intros A l k1 k2 a H1.\n induction k1.\n auto.\n apply (Permutation_trans H1 ).\n apply Permutation_sym.\n rewrite <-(app_comm_cons (a0::k1) k2 a).\n apply Permutation_middle.\nQed.\n\nLemma Removel_empty: forall k, Removel [] k = k.\nProof.\n intros k.\n induction k.\n simpl.\n auto.\n simpl.\n destruct (X.cand_in_dec a []) as [ i | j].\n inversion i.\n rewrite IHk.\n auto.\nQed.\n\nLemma nodup_permutation: forall (k l :list X.cand), (forall x, In x k -> In x l) -> NoDup k -> NoDup l -> Leqe (Removel k l) k l.\nProof.\n intros k l H1 H2 H3.\n induction k.\n rewrite (Removel_empty l).\n unfold Leqe.\n simpl.\n apply (Permutation_refl l).\n assert (H12: forall x, In x k -> In x l).\n intros x H.\n apply H1.\n right;auto.\n destruct (X.cand_in_dec a l) as [ i | j].\n specialize (in_split a l i);intro H4.\n destruct H4 as [l1 [l2 H5]].\n assert (Hyp1: Removel (a::k) l = (Removel k l1) ++ Removel k l2).\n rewrite H5.\n rewrite (Removel_segmentation (a::k) l1 (a::l2)).\n rewrite H5 in H3.\n specialize (NoDup_remove_2 l1 l2 a H3);intro H7.\n assert (Hyp2: Removel (a::k) l1 = Removel k l1 /\\ Removel (a::k) l2 = Removel k l2).\n split.\n assert (Hyp3: a::k = []++[a]++k).\n simpl;auto.\n rewrite Hyp3.\n apply (Removel_extra_element a [] k l1).\n intuition.\n apply (Removel_extra_element a [] k l2).\n intuition.\n destruct Hyp2 as [Hyp21 Hyp22].\n rewrite Hyp21.\n assert (Hyp3: Removel (a::k) (a::l2) = Removel k l2).\n simpl.\n destruct (X.cand_in_dec a (a::k)) as [p |q].\n apply (Removel_extra_element a [] k l2).\n intuition.\n contradiction q.\n left;auto.\n rewrite Hyp3.\n auto.\n rewrite Hyp1.\n inversion H2.\n specialize (IHk H12 H6).\n rewrite H5 in IHk.\n rewrite (Removel_segmentation k l1 (a::l2))in IHk. \n assert (Hyp9: a::l2 = [a]++l2).\n simpl;auto.\n rewrite Hyp9 in IHk.\n rewrite (Removel_segmentation k [a] l2) in IHk.\n assert (Hyp10: Removel k [a] = [a]).\n simpl.\n destruct (X.cand_in_dec a k) as [p | q]. \n contradiction H4.\n auto.\n rewrite Hyp10 in IHk.\n unfold Leqe.\n unfold Leqe in IHk.\n assert (Hyp7: k++(Removel k l1)++[a]++(Removel k l2) = (k++(Removel k l1))++[a]++(Removel k l2)).\n rewrite (app_assoc k (Removel k l1) ([a]++(Removel k l2))).\n auto.\n rewrite Hyp7 in IHk.\n specialize (Permutation_reorder X.cand (l1++[a]++l2) (k++Removel k l1) (Removel k l2) a IHk);intro H7.\n rewrite H5.\n simpl.\n assert (Hyp11: (a::k ++ Removel k l1)++Removel k l2 = a::k++(Removel k l1)++Removel k l2).\n simpl.\n rewrite (app_assoc k (Removel k l1) (Removel k l2)).\n auto.\n rewrite Hyp11 in H7. \n assumption.\n assert (H: In a (a::k)).\n left;auto.\n specialize (H1 a H).\n contradiction H1.\nQed.\n\nLemma Permutation_App: forall l l1 l2:list X.cand, Permutation l (l1++l2) -> Permutation l (l2++l1).\nProof.\n intros l l1 l2 H1.\n induction l1.\n rewrite app_nil_r.\n rewrite app_nil_l in H1.\n auto.\n apply (Permutation_trans H1).\n apply (Permutation_app_comm).\nQed.  \n\nCheck proj1_sig. \nLemma Filter_segmentation: forall l a, Filter (a::l) = Filter l \\/ (Filter (a::l) = a::Filter l).\nProof.\n intros l a.\n simpl.\n destruct (X.ValidBallot (` (fst a))).\n right.\n reflexivity.\n left.\n auto.\nQed.\n\n\nLemma Permutation_reorder2: forall (A:Type) l k1 k2 (a:A), Permutation l ((a::k1)++k2) -> Permutation l (k1++a::k2).\nProof.\n intros A l k1 k2 a.\n intro H.\n induction k1.\n auto.\n apply (Permutation_trans H).\n assert (Hypo: (a::a0::k1)++k2 = a::((a0::k1)++k2)).\n simpl. auto.\n rewrite Hypo.\n apply Permutation_middle.\nQed.\n\nLemma Filter_Permutation_ballot: forall l:list ballot, exists (l1: list ballot), Permutation (l1++ (Filter l)) l.\nProof.\n intro l.\n induction l.\n simpl.\n exists ([]:list ballot).\n simpl.\n apply Permutation_refl.\n specialize (Filter_segmentation l a);intro H.\n destruct H as [H1| H2].\n rewrite H1.\n destruct IHl as [l1 IHl1].\n exists (a::l1).\n rewrite <- (app_comm_cons).\n apply (perm_skip). assumption.\n rewrite H2.\n destruct IHl as [l1 IHl1].\n exists l1.\n apply Permutation_sym.\n simpl.\n apply (Permutation_reorder2 ballot (a::l) l1 (Filter l) a).\n simpl.\n apply perm_skip.\n apply Permutation_sym.\n assumption.\nQed.\n\n(*End Base_Proofs.*)\n\n(*End Generic_Machine.*)\n(*\nSection ANUnion.\n\n(* above this line may be added to the base of the framework *)\n(* ********************************************************************************************** *)\n(* The following excluded lemmas may be proved later *********************************\n\nLemma List_IsFirst_decompose : forall c h ba acc, (List_IsFirst_Hopeful c h acc ba) = acc \\/ \n  (exists l, List_IsFirst_Hopeful c h acc ba = l ++ acc). \n\nLemma In_acc_IsIn_List_IsFirst : forall c h acc ba d, In d acc -> In d (List_IsFirst_Hopeful c h acc ba).\n\nLemma list_is_first_hopeful_Eq_List_IsFirst_Hopeful : \n forall c h ba, forall b, In b (list_is_first_hopeful c h ba) -> In b (List_IsFirst_Hopeful c h [] ba).\n*) \n\n\nDefinition Union_InitStep (prem :Machine_States) (conc :Machine_States): Prop :=\n exists ba ba',  \n  prem = initial ba /\\\n  ba' = (Filter ba) /\\\n  conc = state(ba', [nty], nas, (nbdy, nbdy), emp_elec, all_hopeful).\n\nLemma UnionInitStep_SanityCheck_App : SanityCheck_Initial_App Union_InitStep.\nProof.\n unfold SanityCheck_Initial_App.  \n intros.\n exists (state (Filter ba, [nty], nas, (nbdy, nbdy), emp_elec, all_hopeful)). \n split. auto.\n unfold Union_InitStep.\n exists ba.\n exists (Filter ba).\n split. assumption.\n split;auto. \nQed. \n\nLemma UnionInitStep_SanityCheck_Red: SanityCheck_Initial_Red Union_InitStep.\n unfold SanityCheck_Initial_Red.\n intros.\n unfold Union_InitStep in H.\n destruct H as [ba [ba' H1]]. \n exists ba. exists ba'. exists [nty]. exists nas. exists (nbdy, nbdy). exists emp_elec. exists all_hopeful.\n split;auto.\n intuition.\n intuition.\nQed.\n\nDefinition Union_count (prem: Machine_States) (conc: Machine_States) : Prop :=\n exists ba t nt p np bl h e,                (** count the ballots requiring attention **)\n  prem = state (ba, t, p, bl, e, h) /\\     (* if we are in an intermediate state of the count *) \n  [] <> ba /\\                                        (* and there are ballots requiring attention *)\n  (forall c, if (cand_in_dec c (proj1_sig h)) \n      then \n  (exists l,                     \n    np(c) = p(c) ++ [l] /\\                       \n    (forall b, In (proj1_sig (fst b)) (map (fun (d:ballot) => (proj1_sig (fst d))) l) <-> \n                                                               fcc ba (proj1_sig h) c b) /\\ \n    (nt (c) = SUM (np(c)))) \n      else ((nt c) = (hd nty t) c) /\\ (np c) = (p c)) /\\                 \n  conc = state ([], nt :: t, np, bl, e, h).     \n\nHypothesis Bl_hopeful_NoIntersect : forall j: Machine_States, forall ba t p bl e h, j = state (ba,t,p,bl,e,h) ->\n (forall c, In c (snd bl) -> ~ In c (proj1_sig h)) * (forall c, In c (fst bl) -> ~ In c (snd bl)).\n\nLemma UnionCount_SanityCheck_App : SanityCheck_Count_App Union_count.\nProof.\n unfold SanityCheck_Count_App. \n intros.\n exists (state ([], (fun (c:cand) =>  if (cand_in_dec c (proj1_sig h)) then SUM (p (c) ++ [list_is_first_hopeful c (proj1_sig h) ba]) else (hd nty t) c) :: t, fun (c:cand) => (if (cand_in_dec c (proj1_sig h)) then (p (c) ++ [list_is_first_hopeful c (proj1_sig h) ba]) else (p c)), bl, e, h)).\n unfold Union_count.\n exists ba.\n exists t.\n exists ((fun (c:cand) =>  if (cand_in_dec c  (proj1_sig h)) then SUM (p (c) ++ [list_is_first_hopeful c (proj1_sig h) ba]) else ((hd nty t) c))).\n exists p.\n exists (fun (c:cand) => (if (cand_in_dec c (proj1_sig h)) then (p (c) ++ [list_is_first_hopeful c (proj1_sig h) ba]) else (p c))). \n exists bl.\n exists h.\n exists e.\n split; auto.\n split; auto.\n split.\n intro c.\n destruct (cand_in_dec c (proj1_sig h)).\n exists (list_is_first_hopeful c (proj1_sig h) ba).\n split; auto.\n split.\n intro b.   \n apply (listballot_fcc ba t p bl e h quota c i b). \n simpl.\n destruct (cand_in_dec c (proj1_sig h)). auto.\n contradict n. assumption.\n simpl.\n destruct (cand_in_dec c (proj1_sig h)).\n contradict n. assumption.\n auto. auto.\nQed.\n\nLemma UnionCount_SanityCheck_Red: SanityCheck_Count_Red Union_count.\n Proof.\n unfold SanityCheck_Count_Red.\n intros.\n unfold Union_count in H.\n destruct H as [ba [t [nt [ p0 [np [bl [h [e H1]]]]]]]].\n destruct H1 as [H11 [H12 [H13 H14]]].\n assert (old_new_pile_equal_bl: forall c, In c (snd bl) -> p0 c = np c).\n specialize (Bl_hopeful_NoIntersect p ba t p0 bl e h H11). \n intros c0  Hyp.\n destruct Bl_hopeful_NoIntersect as [NoIntersect1 NoIntersect2].\n specialize (NoIntersect1 c0 Hyp).\n specialize (H13 c0).\n destruct (cand_in_dec c0 (proj1_sig h)).\n contradict NoIntersect1.\n assumption.\n intuition.\n exists ba; exists ([]: list ballot); exists t. exists nt; exists p0. \n exists np; exists bl; exists e; exists h. split. intuition. \n split; intuition.\n specialize (list_nonempty ballot ba). intro Hyp.\n intuition.\n destruct H as [b [l Hyp1]].\n rewrite Hyp1.\n simpl. \n omega. \n assert (hyp2: forall c, In c (snd bl) -> length (concat (p0 c)) = length (concat (np c))).\n intros.\n specialize (old_new_pile_equal_bl c0 H). \n rewrite old_new_pile_equal_bl.\n reflexivity.\n specialize (map_ext_in (fun c0 => length (concat (p0 c0))) (fun c0 => length (concat (np c0))) (snd bl) hyp2).\n intro.\n rewrite H. auto.\nQed.\n\nDefinition Union_hwin (prem: Machine_States) (conc: Machine_States) : Prop :=\n  exists w ba t p bl e h,                            \n   prem = state (ba, t, p, bl, e, h) /\\           \n   length (proj1_sig e) + length (proj1_sig h) <= st /\\ \n   w = (proj1_sig e) ++ (proj1_sig h) /\\                        \n   conc = winners (w).\n\nLemma  UnionHwin_SanityCheck_App : SanityCheck_Hwin_App Union_hwin.                           \nProof.\n unfold SanityCheck_Hwin_App.\n intros.\n unfold Union_hwin.\n exists (winners ((proj1_sig e) ++ (proj1_sig h))).\n exists ((proj1_sig e) ++ (proj1_sig h)).\n exists ba; exists t; exists p; exists bl; exists e; exists h.  \n auto.\nQed.\n\nLemma UnionHwin_SanityCheck_Red : SanityCheck_Hwin_Red Union_hwin.\nProof.\n unfold SanityCheck_Hwin_Red.\n intros.\n unfold Union_hwin in H. \n destruct H as [w [ba [t [p [bl [e [h H1]]]]]]]. \n exists w; exists ba; exists t; exists p; exists bl; exists e; exists h. \n intuition.\nQed.\n\nDefinition Union_ewin (prem: Machine_States) (conc: Machine_States) : Prop :=\n  exists w ba t p bl e h,                    (** elected win **)\n   prem = state (ba, t, p, bl, e, h) /\\   (* if at any time *)\n   length (proj1_sig e) = st /\\             (* we have as many elected candidates as seats *) \n   w = (proj1_sig e) /\\                        (* and the winners are precisely the electeds *)\n   conc = winners (w).                      (* they are declared the winners *)\n\nLemma UnionEwin_SanityCheck_App : SanityCheck_Ewin_App Union_ewin.\nProof.\n unfold SanityCheck_Ewin_App.\n intros.\n unfold Union_ewin.\n exists (winners (proj1_sig e)). \n exists (proj1_sig e). exists ba. exists t. exists p. exists bl. exists e. exists h.\n intuition.\nQed.\n\nLemma UnionEwin_SanityCheck_Red : SanityCheck_Ewin_Red Union_ewin.\nProof.\n unfold SanityCheck_Ewin_Red.\n intros.\n unfold Union_ewin in H.\n destruct H as [w [ba [t [p [bl [e [h H1]]]]]]].\n exists w. exists ba. exists t. exists p. exists bl. exists e. exists h. \n intuition.\n rewrite <- H0.\n assumption.\nQed.\n\nDefinition Union_transfer (prem: Machine_States) (conc: Machine_States) : Prop :=\n exists nba t p np bl nbl h e,         (** transfer votes **) \n  prem = state ([], t, p, bl, e, h) /\\ \n    (length (proj1_sig e) < st) /\\\n    (forall c, In c (proj1_sig h) -> ((hd nty t) c < quota)%Q) /\\        (* and we can't elect any candidate *)\n    exists l c,                          (* and there exists a list l and a candidate c *)\n     (bl = (c :: l, []) /\\                     (* such that c is the head of the backlog *)\n     nbl = (l, []) /\\                          (* and the backlog is updated by removing the head c *)\n     nba = flat_map (fun x => x) (p c) /\\            (* and the pile of ballots for c is the new list of ballots requiring attention *)\n     np(c) = [] /\\                                (* and the new pile for c is empty *)\n     (forall d, d <> c -> np(d) = p(d))) /\\ (* and the piles for every other candidate remain the same *)   \n   conc = state (nba, t, np, nbl, e, h).  \n\nLemma UnionTransfer_SanityCheck_App : SanityCheck_Transfer1_App Union_transfer.\nProof.\n unfold SanityCheck_Transfer1_App.\n intros.\n unfold Union_transfer.\n destruct H0 as [H01 [H02 H03]]. \n specialize (list_nonempty_type cand (fst bl) H02). intro Nonempty_bl.\n destruct Nonempty_bl as [c s].  \n destruct s as [bls H3].  \n exists (state (flat_map (fun x => x) (p c), t, fun d => \n                                                        if (cand_eq_dec d c) then [] else p d, \n                                                        (bls, []), e, h)).\n exists (flat_map (fun x => x) (p c)). exists t. exists p. \n exists (fun d => if (cand_eq_dec d c) then [] else p d). exists (c::bls, ([]: list cand)). \n exists (bls, ([]: list cand)). exists h.\n exists e. \n intuition.\n rewrite H3 in H. assumption.\n exists bls. exists c.\n intuition.\n destruct (cand_eq_dec c c). reflexivity.\n contradict f. auto.\n destruct (cand_eq_dec d c).\n contradict H0. assumption.\n auto.\nQed.\n\nLemma UnionTransfer_SanityCheck_Red : SanityCheck_Transfer_Red Union_transfer.\n Proof.\n unfold SanityCheck_Transfer_Red.\n intros.\n unfold Union_transfer in H.\n destruct H as [nba [t [p [np [bl [nbl [h [e H1]]]]]]]].\n destruct H1 as [H11 [H12 [H13 H14]]].\n destruct H14 as [l [ c H141]].\n exists nba; exists t; exists p; exists np; exists bl; exists nbl; exists h; exists e.\n intuition.\n left.\n rewrite H1.\n rewrite H.\n simpl.\n omega.\nQed.\n\nDefinition Union_elim (prem: Machine_States) (conc: Machine_States) : Prop :=\n  exists nba t p np e h nh bl2,                    \n   prem = state ([], t, p, ([], bl2), e, h) /\\         \n   length (proj1_sig e) + length (proj1_sig h) > st /\\ \n   (forall c, In c (proj1_sig h) -> (hd nty t(c) < quota)%Q) /\\ \n   exists c,                                            \n     ((forall d, In d (proj1_sig h) -> (hd nty t(c) <= hd nty t(d)))%Q /\\            \n     eqe c (proj1_sig nh) (proj1_sig h) /\\                                   \n     nba = flat_map (fun x => x) (p c) /\\                                   \n     np(c)=[] /\\                                       \n     (forall d, d <> c -> np (d) = p (d)) /\\                       \n   conc = state (nba, t, np, ([], []), e, nh)). \n\nLemma UnionElim_SanityCheck_App : SanityCheck_Elim_App Union_elim.\nProof.\n unfold SanityCheck_Elim_App.\n intros.\n unfold Union_elim.\n specialize (list_min cand (proj1_sig h) (hd nty t)). intro min_hopeful.\n destruct min_hopeful.\n rewrite e0 in H0.\n destruct H0 as [H01 H02].\n destruct e.\n simpl in H01.\n omega.\n destruct s as [min [s1 s2]].\n specialize (remc_nodup (proj1_sig h) min (proj2_sig h) s1);intro H'1.\n exists (state (flat_map (fun x => x) (p min), t, fun d => if (cand_eq_dec d min) then [] else (p d),\n                                                ([], []), e, exist _ (remc min (proj1_sig h)) H'1)). \n exists (flat_map (fun x => x) (p min)).\n exists t. exists p. exists (fun d => if (cand_eq_dec d min) then [] else (p d)). exists e. exists h. \n exists (exist _ (remc min (proj1_sig h)) H'1).\n intuition.\n exists bl2.\n intuition.\n simpl.\n exists min.\n intuition.\n apply (remc_ok min (proj1_sig h) (proj2_sig h) s1).\n destruct (cand_eq_dec min min). reflexivity.\n contradict f. auto.\n destruct (cand_eq_dec d min). contradiction H0. reflexivity.\nQed.\n\nLemma UnionElim_SanityCheck_Red : SanityCheck_Elim_Red Union_elim.\n Proof.\n unfold SanityCheck_Elim_Red.\n intros. \n unfold Union_elim in H.\n destruct H as [nba [t [p [np [e [h [nh [bl2 H1]]]]]]]].\n destruct H1 as [H11 [H12 [H13 H14]]].\n destruct H14 as [weakest H141]. \n exists nba. exists t. exists p. exists np. exists e. exists h. exists nh.  \n intuition.\n unfold eqe in H1.\n destruct H1 as [l1 [l2 [H' [H'' [H''' H'''']]]]].\n rewrite H'.\n rewrite H''.\n assert (Hyp : length (l1 ++ [weakest] ++ l2) = (length l1 + (length ([weakest] ++ l2)))% nat).\n simpl.\n rewrite (app_length).\n simpl. auto.  \n rewrite Hyp.\n simpl.\n rewrite (app_length).\n exists bl2. \n exists ([]: list cand).\n intuition.\nQed.\n\nDefinition Union_elect (prem: Machine_States) (conc: Machine_States) : Prop :=\n exists t p np (bl nbl: (list cand) * (list cand)) (nh h: {hopeful: list cand | NoDup hopeful})(e ne: {l : list cand | length l <= st }),\n    prem = state ([], t, p, bl, e, h) /\\ \n    exists l,                                      \n     (l <> [] /\\                                  \n     length l <= st - length (proj1_sig e) /\\    \n     (forall c, In c l -> In c (proj1_sig h) /\\ (hd nty t (c) >= quota)%Q) /\\      \n     ordered (hd nty t) l /\\ \n     Leqe l (proj1_sig nh) (proj1_sig h) /\\          \n     Leqe l (proj1_sig e) (proj1_sig ne) /\\     \n     (forall c, In c l -> ((np c) = map (map (fun (b : ballot) => \n        (fst b, (Qred (snd b * (Qred ((hd nty t)(c)- quota)/(hd nty t)(c))))%Q))) (p c))) /\\  \n     (forall c, ~ In c l -> np (c) = p (c)) /\\  \n    fst nbl = (fst bl) ++ l) /\\                                 \n  conc = state ([], t, np, nbl, ne, nh).      \n\nLemma UnionElect_SanityCheck_App : SanityCheck_Elect_App Union_elect.\nProof.\n unfold SanityCheck_Elect_App.\n intros.\n unfold Union_elect.\n specialize (constructing_electable_first).  \n intro H1.\n destruct X as [c [X1 X2]].\n assert (Hyp: length (proj1_sig e) < st).\n omega.\n specialize (H1 e (hd nty t) h quota Hyp (proj2_sig h)).\n destruct H1 as [listElected H11].\n destruct H11 as [H111 [H112 [H113 [H114 H115]]]].\n specialize (Removel_nodup listElected (proj1_sig h) (proj2_sig h)). intro NoDupH.\n assert (Assum: length ((proj1_sig e) ++ listElected) <= st).\n rewrite app_length.\n omega.\n exists (state ([], t, fun c => update_pile p t listElected quota c, ((fst bl) ++ listElected, snd bl), \n exist _ ((proj1_sig e) ++ listElected) Assum, exist _ (Removel listElected (proj1_sig h)) NoDupH)).\n exists t. exists p. exists (fun x => update_pile p t listElected quota x).\n exists bl. exists ((fst bl) ++ listElected, snd bl). exists (exist _ (Removel listElected (proj1_sig h)) NoDupH).\n exists h. exists e. exists (exist (fun v => length v <= st) ((proj1_sig e) ++ listElected) Assum). \n split. auto.\n exists listElected.\n intuition.\n assert (NonEmptyElected: length listElected = 0). \n rewrite H2.\n simpl. reflexivity.\n assert (VacantSeat: length (listElected) < st - (length (proj1_sig e))).\n rewrite app_length in Assum.\n rewrite NonEmptyElected in Assum.\n omega.\n specialize (H115 c). \n intuition.\n rewrite H2 in H3.\n inversion H3.\n simpl.\n unfold Leqe.\n apply Permutation_App.\n apply (nodup_permutation).\n intros candid HypCand. \n specialize (H111 candid HypCand).\n intuition.\n assumption. \n apply (proj2_sig h).\n simpl.\n unfold Leqe.\n apply Permutation_refl.\n unfold update_pile.\n destruct (cand_in_dec c0 listElected).\n trivial.\n contradict f. assumption.\n unfold update_pile.\n destruct (cand_in_dec c0 listElected).\n contradict H2.\n assumption.\n auto.\nQed.\n\nLemma UnionElect_SanityCheck_Red : SanityCheck_Elect_Red Union_elect.\nProof.\n unfold SanityCheck_Elect_Red.\n intros.\n unfold Union_elect in H.\n destruct H as [t [p [np [bl [nbl [nh [h [e [ne H1]]]]]]]]].\n exists t. exists p; exists np. exists bl. exists nbl. exists e. exists ne. exists nh. exists h. \n destruct H1 as [H11 H12].\n destruct H12 as [l H121].\n intuition.\n unfold Leqe in H4.  \n specialize (Permutation_length H4). intro Permut_length.\n rewrite Permut_length.\n rewrite  app_length.\n specialize (list_nonempty_type cand l H1). intro.\n destruct X as [c [l' HX]].\n rewrite HX.\n simpl. \n omega.\n unfold Leqe in H5.\n specialize (Permutation_length H5). intro.\n rewrite H8.\n rewrite app_length.\n specialize (list_nonempty_type cand l H1). intro.\n destruct X as [c [l' HX]]. \n rewrite HX.\n simpl.\n omega.\nQed.\n\nDefinition Union_quota := \n (((inject_Z (Z.of_nat (length (Filter bs)))) / (1 + inject_Z (Z.of_nat st)) + 1)%Q). \n\nDefinition VicTas_TransferElected2 (prem: Machine_States) (conc: Machine_States) :=\n exists nba t p np bl nbl h e,         \n  prem = state ([], t, p, bl, e, h) /\\ \n    (length (proj1_sig e) < st) /\\\n    (forall c, In c (proj1_sig h) -> ((hd nty t) c < quota)%Q) /\\       \n    exists l c c' l',                          \n     (bl = (c :: l, c'::l') /\\                   \n     nbl = (l, l') /\\                          \n     nba = concat (p c) /\\\n     concat (p c') = [] /\\           \n     np(c) = [] /\\                                 \n     (forall d, d <> c -> np(d) = p(d))) /\\    \n   conc = state (nba, t, np, nbl, e, h). \n\nLemma VicTasTran2_SanityCheck_App : SanityCheck_Transfer2_App VicTas_TransferElected2. \nProof.\n unfold SanityCheck_Transfer2_App.\n intros. \n unfold VicTas_TransferElected2.\n destruct H0 as [H1 [H2 [H3 H4]]].\n specialize (list_nonempty_type cand bl1 H2). intro Nonempty_bl.\n destruct Nonempty_bl as [Headbl1 [Tailbl1 bl1None]].\n \n exists (state (concat (p Headbl1), t, fun x => if (cand_eq_dec x Headbl1) then [] else p x, \n                (Tailbl1, bl2), e, h)).  \n exists (concat (p Headbl1)).\n exists t. exists p. exists (fun x => if (cand_eq_dec x Headbl1) then [] else (p x)).\n exists (Headbl1:: Tailbl1, c:: bl2). exists (Tailbl1,bl2). exists h. exists e.\n rewrite bl1None in H.\n intuition.\n exists Tailbl1. exists Headbl1. exists c. exists bl2.\n intuition.\n destruct (cand_eq_dec Headbl1 Headbl1).\n reflexivity.\n contradict f.  auto.\n destruct (cand_eq_dec d Headbl1).\n contradict H0.\n auto.\n reflexivity.\nQed.\n\nLemma VicTasTran2_SanityCheck_Red : SanityCheck_Transfer_Red VicTas_TransferElected2.\nProof.\n unfold SanityCheck_Transfer_Red.\n intros.\n unfold VicTas_TransferElected2 in H.\n destruct H as [nba [t [p [np [bl [nbl [h [e H1]]]]]]]].\n destruct H1 as [H11 [H12 [H13 H14]]].\n destruct H14 as [Tbl1 [Hbl1 [Hbl2 [Tbl2 H15]]]].\n exists nba.\n exists t. exists p. exists np. exists bl. exists nbl. exists h. exists e.\n destruct H15 as [H15 H152].\n destruct H15 as [HH1 HH2].\n destruct HH2 as [HH21 [HH22 [HH23 [HH24 HH25]]]].\n assert (Hypo: forall d, In d Tbl2 -> p (d) = np (d)).\n intros d Hy.\n assert (hypos: d <> Hbl1). intro contHypos. rewrite contHypos in Hy.\n specialize (Bl_hopeful_NoIntersect (state ([],t,p,bl, e,h)) [] t p bl e h (eq_refl)).  \n destruct Bl_hopeful_NoIntersect as [i j]. \n specialize (j Hbl1).\n rewrite HH1 in j.\n assert (hyu: In Hbl1 (fst (Hbl1:: Tbl1, Hbl2:: Tbl2))).\n simpl. left;auto.\n specialize (j hyu).\n apply j.\n simpl.\n right;assumption.\n specialize (HH25 d hypos).\n auto.\n split.  auto.\n split. left. rewrite HH1. rewrite HH21. \n simpl. rewrite HH23.\n assert (Leneq: forall d, In d Tbl2 -> length (concat (p d)) = length (concat (np d))).\n intros d he.\n specialize (Hypo d he). rewrite Hypo. auto.\n specialize (map_ext_in (fun c => length (concat (p c))) (fun d => length (concat (np d))) Tbl2 Leneq). \n intro map_equal.\n rewrite map_equal.\n simpl.\n omega.\n auto.\nQed.\n\nDefinition VicTas_TransferElim (prem: Machine_States) (conc: Machine_States) :=\n exists nba t p np bl nbl h e,         \n  prem = state ([], t, p, bl, e, h) /\\ \n    (length (proj1_sig e) < st) /\\\n    (forall c, In c (proj1_sig h) -> ((hd nty t) c < quota)%Q) /\\       \n    exists l c c' l',                          \n     (bl = (c :: l, c'::l') /\\                   \n     nbl = (c::l, c'::l') /\\\n      (concat (p c') <> []) /\\ \n      let x:= (groupbysimple _ (sort (concat (p c')))) in\n       (nba = last x []) /\\\n       np c' = (removelast x) /\\                                        \n     (forall d, d <> c' -> np(d) = p(d))) /\\    \n   conc = state (nba, t, np, nbl, e, h). \n\nHypothesis Bl_NoDup : forall j: Machine_States, forall ba t p bl e h, \n  j = state (ba,t,p,bl,e,h) -> NoDup (snd bl).\n\n\nLemma VicTas_TransferElim_SanityCheck_App : SanityCheck_Transfer3_App VicTas_TransferElim.\nProof.\n unfold SanityCheck_Transfer3_App.\n intros.\n destruct H0 as [H1 [H2 [H3 H4]]].\n unfold VicTas_TransferElim.\n exists (state (((last (groupbysimple _ (sort (concat (p c)))) []): list ballot),\n t, fun d => if (cand_eq_dec d c) then (removelast (groupbysimple _ (sort (concat (p c))))) else p d, (bl1, c::bl2), e, h)). \n exists (last (groupbysimple _ (sort (concat (p c)))) []). \n exists t. exists p. exists (fun d => if (cand_eq_dec d c) \n   then (removelast ((groupbysimple _ (sort (concat (p c))))))  else p d). \n exists (bl1,c::bl2). exists (bl1, c::bl2). exists h. exists e. intuition.\n specialize (list_nonempty_type cand bl1 H2). intro Nbl1.\n destruct Nbl1 as [Hbl1 [Tbl1 bl1N]].\n exists Tbl1. exists Hbl1. exists c. exists bl2.\n rewrite bl1N.\n intuition.\n destruct (cand_eq_dec c c) as [i | j].\n auto. contradict j. reflexivity.\n destruct (cand_eq_dec d c) as [i |j].\n contradiction H0. reflexivity.\nQed.\n\nLemma concat_app : forall (A:Type) (l1: list (list A)) l2, concat (l1 ++ l2) = concat l1 ++ concat l2.\nProof.\n  intros.\n  induction l1 as [|x l1 IH]. induction l2. simpl.\n  reflexivity. simpl. auto.\n  simpl. rewrite IH; apply app_assoc.\nQed.\n \nLemma VicTas_TransferElim_SanityCheck_Red: SanityCheck_Transfer_Red VicTas_TransferElim.\nProof.\n unfold SanityCheck_Transfer_Red. \n intros.\n unfold VicTas_TransferElim in H.\n destruct H as [nba [t [p [np [bl [nbl [h [e H1]]]]]]]].\n destruct H1 as [H11 [H12 [H13 H14]]].\n destruct H14 as [Tbl1 [Hbl1 [Hbl2 [Tbl2 H15]]]].\n destruct H15 as [H151 H152].  \n destruct H151 as [K1 K2].\n destruct K2 as [K21 [K22 [K23 [K24 K25]]]].\n exists nba. exists t. exists p. exists np. exists bl. exists nbl. exists h. exists e.\n split. assumption.\n split. right. rewrite K1. rewrite K21. simpl. split. auto.\n assert (Tbl2_NoDup: NoDup (Hbl2 :: Tbl2)). \n specialize (Bl_NoDup (state ([],t,p,bl,e,h)) [] t p bl e h (eq_refl)).\n rewrite K1 in Bl_NoDup.\n simpl in Bl_NoDup.\n assumption.\n assert (Hbl2_notInTail: ~ In Hbl2 Tbl2). \n intro Cont.\n inversion Tbl2_NoDup.\n apply H1. assumption.\n assert (Piles_eq_Tbl2: forall d, In d Tbl2 -> p d = np d).\n intros d InTbl2.\n assert (not_eq_d: d <> Hbl2).\n intro cont. rewrite cont in InTbl2. apply Hbl2_notInTail. assumption.\n specialize (K25 d not_eq_d).\n auto.\n assert (Len_piles_eq: forall d, In d Tbl2 -> length (concat (p d)) = length (concat (np d))).\n intros d Hy.\n specialize (Piles_eq_Tbl2 d Hy).\n rewrite Piles_eq_Tbl2. auto.\n specialize (map_ext_in (fun c => length (concat (p c))) (fun c => length (concat (np c))) Tbl2 Len_piles_eq). \n intro nice.\n rewrite nice.  \n rewrite K24.\n assert (Hypo: (groupbysimple _ (sort (concat (p Hbl2)))) <> []).\n apply groupbysimple_not_empty.\n apply sherin. \n auto.  \n assert (Hypo2: groupbysimple _ (sort (concat (p Hbl2))) = \n(removelast (groupbysimple _ (sort (concat (p Hbl2))))) ++ [last (groupbysimple _ (sort (concat (p Hbl2)))) []]).\n apply app_removelast_last.\n assumption.\n assert (Hypo222: concat (groupbysimple _ (sort (concat (p Hbl2)))) =\n                  concat ((removelast (groupbysimple _ (sort (concat (p Hbl2)))))\n                            ++\n                            [last (groupbysimple _ (sort (concat (p Hbl2)))) []])).\n apply f_equal. assumption.\n rewrite concat_app in Hypo222. \n\n assert (Hypo22: length (concat (groupbysimple _ (sort (concat (p Hbl2))))) = \n (length (concat (removelast (groupbysimple _ (sort (concat (p Hbl2)))))) + \n  length (concat [last (groupbysimple _ (sort (concat (p Hbl2)))) []]))%nat).\n rewrite <- app_length. apply f_equal. auto.\n assert (Hypolen : length\n            (concat (groupbysimple {v : list cand | NoDup v /\\ [] <> v} (sort (concat (p Hbl2))))) = \n                   length (concat (p Hbl2))).\n rewrite <- concat_rat. auto.\n rewrite <- Hypolen.\n rewrite  Hypo22.\n simpl.\n assert (Hlen : forall (A : Type) (l : list A),\n            l <> []  -> 0 < length l).  \n intros. destruct l. contradiction H. auto. simpl. omega.\n specialize (groupby_notempty _ (sort (concat (p Hbl2)))). intros.\n pose proof (sortedList_notempty (concat (p Hbl2)) K22).\n specialize (H H0). \n specialize (Hlen _ _ H).\n rewrite app_nil_r.\n apply Nat.add_lt_mono_r.\n apply NPeano.Nat.lt_add_pos_r. trivial.\n auto.\nQed.\n\nDefinition UnionSTV := (mkSTV (quota)  \n    (Union_InitStep) (UnionInitStep_SanityCheck_App) (UnionInitStep_SanityCheck_Red) \n    (Union_count) (UnionCount_SanityCheck_App) (UnionCount_SanityCheck_Red)\n    (Union_transfer) (UnionTransfer_SanityCheck_App) (UnionTransfer_SanityCheck_Red)\n    (VicTas_TransferElected2) (VicTasTran2_SanityCheck_App) (VicTasTran2_SanityCheck_Red)\n    (VicTas_TransferElim) (VicTas_TransferElim_SanityCheck_App) (VicTas_TransferElim_SanityCheck_Red)\n    (Union_elect) (UnionElect_SanityCheck_App) (UnionElect_SanityCheck_Red)\n    (Union_elim) (UnionElim_SanityCheck_App) (UnionElim_SanityCheck_Red)\n    (Union_hwin) (UnionHwin_SanityCheck_App) (UnionHwin_SanityCheck_Red)\n    (Union_ewin) (UnionEwin_SanityCheck_App) (UnionEwin_SanityCheck_Red)).\n\n\nLemma init_stages_R_initial : ~ State_final (initial (Filter bs)).\nProof.\n intro.\n unfold State_final in H.\n destruct H.\n inversion H.\nQed.\n \nDefinition Union_Termination := Termination (initial (Filter bs)) init_stages_R_initial UnionSTV.\n\nEnd ANUnion.\n*)\n(*\nDefinition ACT_TransferElected (prem: Machine_States) (conc: Machine_States) : Prop :=\n exists nba t p np bl nbl h e,\n  prem = state ([], t, p, bl, e, h) /\\\n  (length (proj1_sig e) < st) /\\\n  (forall c, In c (proj1_sig h) -> ((hd nty t) c < quota)%Q) /\\\n  exists l c,\n   (bl = (c :: l,[]) /\\\n   nbl = (l,[]) /\\\n   nba = last (p c) [] /\\ np(c) = [] /\\\n     (forall d, d <> c -> np(d) = p(d))) /\\\n   conc = state (nba, t, np, nbl, e, h).\n\nLemma ACT_TransferElected_SanityCheck_App : SanityCheck_Transfer1_App ACT_TransferElected.\nProof.\n unfold SanityCheck_Transfer1_App.\n intros.\n destruct H0 as [H1 [H2 H3]].\n specialize (list_nonempty_type cand (fst bl) H2). intro Hyp. destruct Hyp as [head [tail Hyp1]].\n exists (state (last (p head) [], t, fun d => if (cand_eq_dec d head) then [] else (p d), (tail,[]), e, h)).\n unfold ACT_TransferElected. exists (last (p head) []). exists t. exists p.\n exists (fun d => if (cand_eq_dec d head) then [] else (p d)).\n exists (head::tail, []). exists (tail,[]). exists h. exists e. rewrite Hyp1 in H. simpl in H.\n intuition.\n exists tail. exists head.\n intuition.\n destruct (cand_eq_dec head head). reflexivity. contradict f. auto.\n destruct (cand_eq_dec d head). contradiction H0. reflexivity.\nQed.\n\nLemma ACT_TransferElected_SanityCheck_Red : SanityCheck_Transfer_Red ACT_TransferElected.\nProof.\n unfold SanityCheck_Transfer_Red.\n intros.\n unfold ACT_TransferElected in H.\n destruct H as [nba [t [p [np [bl [nbl [h [e H1]]]]]]]].\n destruct H1 as [H11 [H12 [H13 H14]]].\n destruct H14 as [l [candid H141]].\n destruct H141 as [H1411 H1412].\n destruct H1411 as [H3 [H4 H5]].\n exists nba. exists t. exists p. exists np. exists bl. exists nbl. exists h. exists e.\n intuition.  \n rewrite H3.\n rewrite H4.\n simpl.\n left.\n omega.\nQed.\n\n\n(* transfer value has changed so that only last parcel is to be transferred at a Manual_ACT rate*)\n(* note that only the last parcel is kept after being updated. The rest of the parcel is thrown out! *)\nDefinition ACT_Elect (prem: Machine_States) (conc: Machine_States) : Prop :=\n exists t p np (bl nbl: (list cand) * (list cand)) nh h (e ne: {l : list cand | length l <= st }),\n    prem = state ([], t, p, bl, e, h) /\\\n    exists l,\n     (l <> [] /\\\n     length l <= st - length (proj1_sig e) /\\\n     (forall c, In c l -> In c (proj1_sig h) /\\ (hd nty t (c) >= quota)%Q) /\\    \n     ordered (hd nty t) l /\\\n     Leqe l (proj1_sig nh) (proj1_sig h) /\\\n     Leqe l (proj1_sig e) (proj1_sig ne) /\\\n     (forall c, In c l -> ((np c) = map (map (fun (b : ballot) =>\n         (fst b, (Qred (snd b * (Update_transVal c p (hd nty t))))%Q))) [(last (p c) [])])) /\\\n     (forall c, ~ In c l -> np (c) = p (c)) /\\\n     fst nbl = (fst bl) ++ l) /\\\n  conc = state ([], t, np, nbl, ne, nh).\n\nLemma ACT_Elect_SanityCheck_App : SanityCheck_Elect_App ACT_Elect.\nProof.\n unfold SanityCheck_Elect_App. \n intros.\n unfold ACT_Elect.\n specialize (constructing_electable_first).\n intro H1.\n destruct X as [c [X1 X2]].\n assert (Hyp: length (proj1_sig e) < st).\n omega. \n specialize (H1 e (hd nty t) h quota Hyp (proj2_sig h)).\n destruct H1 as [listElected H11].\n destruct H11 as [H111 [H112 [H113 [H114 H115]]]].\n specialize (Removel_nodup listElected (proj1_sig h) (proj2_sig h)). intro NoDupH.\n assert (Assum: length ((proj1_sig e) ++ listElected) <= st).\n rewrite app_length.\n omega.\n exists (state ([], t, fun c => update_pile_ManualACT p (hd nty t) listElected quota c, \n((fst bl) ++ listElected, snd bl), exist _ ((proj1_sig e) ++ listElected) Assum, \n                                   exist _ (Removel listElected (proj1_sig h)) NoDupH)). \n exists t. exists p. exists (fun x => update_pile_ManualACT p (hd nty t) listElected quota x).\n exists bl. exists ((fst bl) ++ listElected, snd bl). exists (exist _ (Removel listElected (proj1_sig h)) NoDupH).\n exists h. exists e. exists (exist _ ((proj1_sig e) ++ listElected) Assum).\n split. auto.\n exists listElected.\n intuition.\n assert (NonEmptyElected: length listElected = 0).\n rewrite H2.\n simpl. reflexivity.\n assert (VacantSeat: length (listElected) < st - (length (proj1_sig e))).\n rewrite app_length in Assum.\n rewrite NonEmptyElected in Assum.\n omega.\n specialize (H115 c).\n intuition. \n rewrite H2 in H3.\n inversion H3. \n simpl.\n unfold Leqe.\n apply Permutation_App.\n apply (nodup_permutation).\n intros candid HypCand. \n specialize (H111 candid HypCand).\n intuition. \n assumption.\n apply (proj2_sig h).\n simpl.\n unfold Leqe.\n apply Permutation_refl.\n unfold update_pile_ManualACT.\n destruct (cand_in_dec c0 listElected).\n trivial. \n contradict f. assumption.\n unfold update_pile_ManualACT.\n destruct (cand_in_dec c0 listElected).\n contradict H2.\n assumption.\n auto. \nQed.\n\nLemma ACT_Elect_SanityCheck_Red : SanityCheck_Elect_Red ACT_Elect.\nProof.\n unfold SanityCheck_Elect_Red.\n intros.\n unfold ACT_Elect in H.\n destruct H as [t [p [np [bl [nbl [nh [h [e [ne H1]]]]]]]]].\n exists t. exists p; exists np. exists bl. exists nbl. exists e. exists ne. exists nh. exists h. \n destruct H1 as [H11 H12].\n destruct H12 as [l H121].\n intuition.\n unfold Leqe in H4.\n specialize (Permutation_length H4). intro Permut_length.\n rewrite Permut_length.\n rewrite  app_length.\n specialize (list_nonempty_type cand l H1). intro.\n destruct X as [c [l' HX]].\n rewrite HX.\n simpl.  \n omega.  \n unfold Leqe in H5.\n specialize (Permutation_length H5). intro.\n rewrite H8.\n rewrite app_length.\n specialize (list_nonempty_type cand l H1). intro.\n destruct X as [c [l' HX]]. \n rewrite HX.\n simpl.\n omega.\nQed.\n\n\nDefinition ActSTV := (mkSTV (quota)  \n    (Union_InitStep) (UnionInitStep_SanityCheck_App) (UnionInitStep_SanityCheck_Red) \n    (Union_count) (UnionCount_SanityCheck_App) (UnionCount_SanityCheck_Red)\n    (ACT_TransferElected) (ACT_TransferElected_SanityCheck_App) (ACT_TransferElected_SanityCheck_Red)\n    (VicTas_TransferElected2) (VicTasTran2_SanityCheck_App) (VicTasTran2_SanityCheck_Red)\n    (VicTas_TransferElim) (VicTas_TransferElim_SanityCheck_App) (VicTas_TransferElim_SanityCheck_Red)\n    (ACT_Elect) (ACT_Elect_SanityCheck_App) (ACT_Elect_SanityCheck_Red)\n    (Union_elim) (UnionElim_SanityCheck_App) (UnionElim_SanityCheck_Red)\n    (Union_hwin) (UnionHwin_SanityCheck_App) (UnionHwin_SanityCheck_Red)\n    (Union_ewin) (UnionEwin_SanityCheck_App) (UnionEwin_SanityCheck_Red)).\n\nLemma init_stages_R_initial : ~ State_final (initial (Filter bs)).\nProof.\n intro.\n unfold State_final in H.\n destruct H.\n inversion H.\nQed.\n \nDefinition Act_Termination := Termination (initial (Filter bs)) init_stages_R_initial ActSTV.\n\n\n\n (* Below is the transfer rule changed so that all backlog is emptied in one go *)\n (* Replacing this Transfer with Union_transfer, gets us close to ACT Legislative Assembly *)\n\n(*\nLemma Emptying_Piles_Correct1 : forall (d: cand) (bl :list cand) (p: cand -> list (list ballot)), \n In d bl -> (fun c => if (cand_in_dec c bl) then [] else p (c)) d = []. \nProof.\n intros.\n simpl.\n destruct (cand_in_dec d bl).\n auto.\n contradict n.\n assumption.\nQed.\n\nLemma Emptying_Piles_Correct2 : forall (d:cand) (bl: list cand) (p: cand -> list (list ballot)),\n not (In d bl) -> (fun c => if (cand_in_dec c bl) then [] else p (c)) d = p (d). \nProof.\n intros.\n simpl.\n destruct (cand_in_dec d bl). \n contradict H.\n assumption.\n reflexivity.\nQed.\n\n\nDefinition ACT_LH_transfer (prem: Machine_States) (conc: Machine_States) : Prop :=\n exists nba t p np bl nbl h e,         (** transfer votes **) \n  prem = state ([], t, p, bl, e, h) /\\ \n  (length (proj1_sig e) < st) /\\\n  (forall c, In c (proj1_sig h) -> ((hd nty t) c < quota)%Q) /\\        (* and we can't elect any candidate *)\n  exists l c,                          (* and there exists a list l and a candidate c *)\n   (bl = c :: l /\\                     (* such that c is the head of the backlog *)\n   nbl = [] /\\                          (* and the backlog is updated by removing the head c *)\n   nba = fold_left (fun (acc: list ballot) => (fun (c: cand) => (acc ++ (flat_map (fun x => x) (p c))))) bl []\n    /\\ forall d, In d bl -> np(d) = [] /\\                                (* and the new pile for c is empty *)\n     (forall d, not (In d bl) -> np(d) = p(d))) /\\    \n   conc = state (nba, t, np, nbl, e, h).  \n\nLemma ACT_LH_Transfer_IsLegitimate : Is_Legitimate_Transfer ACT_LH_transfer.\nProof.\n intros.\n unfold Is_Legitimate_Transfer.\n split.\n intros.\n destruct H0 as [H1 [H2 H3]]. \n exists (state \n         (fold_left (fun (acc: list ballot) => (fun (c: cand) => (acc ++ (flat_map (fun x => x) (p c))))) bl [],\n         t, fun c => if (cand_in_dec c bl) then [] else (p c), [], e, h)).\n unfold ACT_LH_transfer.\n exists (fold_left (fun (acc: list ballot) => (fun (c: cand) => (acc ++ (flat_map (fun x => x) (p c))))) bl []).\n exists t. exists p. exists (fun c => if (cand_in_dec c bl) then [] else (p c)). exists bl. exists [].\n exists h. exists e. intuition.  \n specialize (list_nonempty_type cand bl H2). intro Hyp. destruct Hyp as [ head [tail Hyp1]].\n exists tail. exists head. intuition. \n destruct (cand_in_dec d bl) as [i1 | i2]. reflexivity. contradict i2. assumption.\n destruct (cand_in_dec d0 bl) as [s1 | s2]. contradiction H4. auto.\n intros.\n unfold ACT_LH_transfer in H.\n destruct H as [nba [t [p [np [bl [nbl [h [e H1]]]]]]]].\n exists nba.\n exists t. exists p. exists np.\n exists bl. exists []. exists h. exists e. intuition. destruct H3 as [tail [head [H31 H32]]].\n destruct H31 as [H311 H312].\n rewrite H311.\n simpl.\n omega.\n destruct H3 as [l [candid [H31 H32]]]. \n intuition.\n rewrite H4 in H32.\n assumption.\nQed.\n\nDefinition ACTLH_STV := (mkSTV (quota)  \n                         (Union_InitStep) (UnionInitStep_IsLegitimate) \n                         (Union_count) (UnionCount_IsLegitimate)\n                         (ACT_LH_transfer) (ACT_LH_Transfer_IsLegitimate)\n                          (Union_elect) (UnionElect_IsLegitimate)\n                         (Union_elim) (UnionElim_IsLegitimate)\n                          (Union_hwin) (UnionHwin_IsLegitimate)\n                         (Union_ewin) (UnionEwin_IsLegitimate)).\n\nDefinition ACTLH_Termination := Termination (initial (Filter bs)) init_stages_R_initial ACTLH_STV.\n\n\n(* transferring only the last parcel of the head of the backlog *)\nDefinition LastParcel_transfer (prem: Machine_States) (conc: Machine_States) : Prop :=\n exists nba t p np bl nbl h e,         (** transfer votes **) \n  prem = state ([], t, p, bl, e, h) /\\ \n  (length (proj1_sig e) < st) /\\\n  (forall c, In c (proj1_sig h) -> ((hd nty t) c < quota)%Q) /\\        (* and we can't elect any candidate *)\n  exists l c,                          (* and there exists a list l and a candidate c *)\n   (bl = c :: l /\\                     (* such that c is the head of the backlog *)\n   nbl = l /\\                          (* and the backlog is updated by removing the head c *)\n   nba = last (p c) [] /\\ np(c) = [] /\\                                (* and the new pile for c is empty *)\n     (forall d, d <> c -> np(d) = p(d))) /\\    \n   conc = state (nba, t, np, nbl, e, h).  \n\nLemma LastParcel_Transfer_IsLegitimate : Is_Legitimate_Transfer LastParcel_transfer.\nProof.\n unfold Is_Legitimate_Transfer. \n split. \n intros.\n destruct H0 as [H1 [H2 H3]].\n specialize (list_nonempty_type cand bl H2). intro Hyp. destruct Hyp as [head [tail Hyp1]].\n exists (state (last (p head) [], t, fun d => if (cand_eq_dec d head) then [] else (p d), tail, e, h)).  \n unfold LastParcel_transfer. exists (last (p head) []). exists t. exists p. \n exists (fun d => if (cand_eq_dec d head) then [] else (p d)). \n exists bl. exists tail. exists h. exists e. \n intuition.\n exists tail. exists head.\n intuition.\n destruct (cand_eq_dec head head). reflexivity. contradict f. auto.\n destruct (cand_eq_dec d head). contradiction H0. reflexivity. \n intros.\n unfold LastParcel_transfer in H.\n destruct H as [nba [t [p [np [bl [nbl [h [e H1]]]]]]]].\n destruct H1 as [H11 [H12 [H13 H14]]].\n exists nba. exists t. exists p. exists np. exists bl. exists nbl. exists h. exists e.\n intuition. \n destruct H14 as [l [candid H141]]. \n destruct H141 as [H1411 H1412].\n destruct H1411 as [H3 [H4 H5]].\n rewrite H3. \n rewrite H4.\n simpl.\n omega.\n destruct H14 as [tail [head [H141 H142]]].\n assumption.\nQed.\n\nDefinition LastParcelTrans_STV := \n                (mkSTV (quota)  \n                       (Union_InitStep) (UnionInitStep_IsLegitimate) \n                       (Union_count) (UnionCount_IsLegitimate)\n                       (LastParcel_transfer) (LastParcel_Transfer_IsLegitimate)\n                       (Union_elect) (UnionElect_IsLegitimate)\n                       (Union_elim) (UnionElim_IsLegitimate)\n                       (Union_hwin) (UnionHwin_IsLegitimate)\n                       (Union_ewin) (UnionEwin_IsLegitimate)).\n\nDefinition LastParcelTrans_Termination := \n        Termination (initial (Filter bs)) init_stages_R_initial LastParcelTrans_STV.\n\nDefinition Update_transVal (c: cand) (p: cand -> list (list ballot)) (t: cand -> Q) :=\n let Sum_parcel := sum (last (p c) []) in\n  let r :=  (Qred ((Qred ((t c) - quota)) / Sum_parcel)) in\n    match (Qlt_le_dec 0 Sum_parcel) with\n       left _ => match (Qlt_le_dec r 1) with\n                    left _ => r\n                   |right _ => (1)%Q\n                 end\n       |right _ => (1)%Q\n    end.\n\n(* transfer value has changed so that only last parcel is to be transferred at a Manual_ACT rate*)\n(* note that only the last parcel is kept after being updated. The rest of the parcel is thrown out! *)\nDefinition ManualACT_elect (prem: Machine_States) (conc: Machine_States) : Prop :=\n exists t p np (bl nbl: list cand) nh h (e ne: {l : list cand | length l <= st }),\n    prem = state ([], t, p, bl, e, h) /\\ \n    exists l,                                      \n     (l <> [] /\\                                  \n     length l <= st - length (proj1_sig e) /\\    \n     (forall c, In c l -> In c (proj1_sig h) /\\ (hd nty t (c) >= quota)%Q) /\\      \n     ordered (hd nty t) l /\\ \n     Leqe l (proj1_sig nh) (proj1_sig h) /\\          \n     Leqe l (proj1_sig e) (proj1_sig ne) /\\     \n     (forall c, In c l -> ((np c) = map (map (fun (b : ballot) => \n         (fst b, (Qred (snd b * (Update_transVal c p (hd nty t))))%Q))) [(last (p c) [])])) /\\  \n     (forall c, ~ In c l -> np (c) = p (c)) /\\  \n     nbl = bl ++ l) /\\                                 \n  conc = state ([], t, np, nbl, ne, nh).      \n\nDefinition update_pile_ManualACT (p: cand -> list (list ballot)) (t: cand -> Q) (l: list cand) (q:Q) (c:cand):=   \n if cand_in_dec c l \n    then  \n       map (map (fun (b : ballot) => \n         (fst b, (Qred (snd b * (Update_transVal c p t)))%Q))) [(last (p c) [])] \n    else (p c).\n\nLemma ManualACT_elect_IsLegitimate: Is_Legitimate_Elect ManualACT_elect.\nProof.\n intros.\n unfold Is_Legitimate_Elect.\n split.\n intros.\n unfold Union_elect.\n specialize (constructing_electable_first).  \n intro H1.\n destruct X as [c [X1 X2]].\n assert (Hyp: length (proj1_sig e) < st).\n omega.\n specialize (H1 e (hd nty t) h quota Hyp (proj2_sig h)).\n destruct H1 as [listElected H11].\n destruct H11 as [H111 [H112 [H113 [H114 H115]]]].\n specialize (Removel_nodup listElected (proj1_sig h) (proj2_sig h)). intro NoDupH.\n assert (Assum: length ((proj1_sig e) ++ listElected) <= st).\n rewrite app_length.\n omega.\n exists (state ([], t, fun c => update_pile_ManualACT p (hd nty t) listElected quota c, bl ++ listElected, \n exist _ ((proj1_sig e) ++ listElected) Assum, exist _ (Removel listElected (proj1_sig h)) NoDupH)).\n exists t. exists p. exists (fun x => update_pile_ManualACT p (hd nty t) listElected quota x).\n exists bl. exists (bl ++ listElected). exists (exist _ (Removel listElected (proj1_sig h)) NoDupH).\n exists h. exists e. exists (exist _ ((proj1_sig e) ++ listElected) Assum). \n split. auto.\n exists listElected.\n intuition.\n assert (NonEmptyElected: length listElected = 0). \n rewrite H2.\n simpl. reflexivity.\n assert (VacantSeat: length (listElected) < st - (length (proj1_sig e))).\n rewrite app_length in Assum.\n rewrite NonEmptyElected in Assum.\n omega.\n specialize (H115 c). \n intuition.\n rewrite H2 in H3.\n inversion H3.\n simpl.\n unfold Leqe.\n apply Permutation_App.\n apply (nodup_permutation).\n intros candid HypCand. \n specialize (H111 candid HypCand).\n intuition.\n assumption. \n apply (proj2_sig h).\n simpl.\n unfold Leqe.\n apply Permutation_refl.\n unfold update_pile_ManualACT.\n destruct (cand_in_dec c0 listElected).\n trivial.\n contradict f. assumption.\n unfold update_pile_ManualACT.\n destruct (cand_in_dec c0 listElected).\n contradict H2.\n assumption.\n auto.\n intros.\n unfold Union_elect in H.\n destruct H as [t [p [np [bl [nbl [nh [h [e [ne H1]]]]]]]]].\n exists t. exists p; exists np. exists bl. exists nbl. exists e. exists ne. exists nh. exists h. \n destruct H1 as [H11 H12].\n destruct H12 as [l H121].\n intuition.\n unfold Leqe in H4.  \n specialize (Permutation_length H4). intro Permut_length.\n rewrite Permut_length.\n rewrite  app_length.\n specialize (list_nonempty_type cand l H1). intro.\n destruct X as [c [l' HX]].\n rewrite HX.\n simpl. \n omega.\n unfold Leqe in H5.\n specialize (Permutation_length H5). intro.\n rewrite H8.\n rewrite app_length.\n specialize (list_nonempty_type cand l H1). intro.\n destruct X as [c [l' HX]]. \n rewrite HX.\n simpl.\n omega.\nQed.\n\nDefinition ManualACT_STV := \n                (mkSTV (quota)  \n                       (Union_InitStep) (UnionInitStep_IsLegitimate) \n                       (Union_count) (UnionCount_IsLegitimate)\n                       (LastParcel_transfer) (LastParcel_Transfer_IsLegitimate)\n                       (ManualACT_elect) (ManualACT_elect_IsLegitimate)\n                       (Union_elim) (UnionElim_IsLegitimate)\n                       (Union_hwin) (UnionHwin_IsLegitimate)\n                       (Union_ewin) (UnionEwin_IsLegitimate)).\n\nDefinition ManualACT_Termination := \n        Termination (initial (Filter bs)) init_stages_R_initial ManualACT_STV.\n*)\n*)\n\n(*End Base.*)\n\nEnd B.\n\n(*Module M := B Instantiation.*)\n\n(*\nExtraction Language Haskell.\nExtraction \"Lib.hs\" Act_Termination.\n*)\n(*Extraction \"Lib.hs\" Union_Termination.*)\n\n(*\nExtraction Language Haskell.\nExtraction \"Lib.hs\" ManualACT_Termination. \n*)\n\n(*\nExtraction Language Haskell.\nExtraction \"Lib.hs\" LastParcelTrans_Termination.\n*)\n\n(*\nExtraction Language Haskell.\nExtraction \"Lib.hs\" ACTLH_Termination. \n*)\n\n\n(* Extraction Language Haskell.\nExtraction \"Lib.hs\" Union_Termination. *)\n\n \n", "meta": {"author": "MiladKetabGhale", "repo": "Modular-STVCalculi", "sha": "e19b6c8e1d23e25e9f9a06becba20f11c2ed386a", "save_path": "github-repos/coq/MiladKetabGhale-Modular-STVCalculi", "path": "github-repos/coq/MiladKetabGhale-Modular-STVCalculi/Modular-STVCalculi-e19b6c8e1d23e25e9f9a06becba20f11c2ed386a/FrameBase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6839172568117746}}
{"text": "(* Fsummation.v *)\n\n(* summations on a field *)\n\nRequire Import Utf8.\nRequire Import QArith.\nRequire Import NPeano.\n\nRequire Import Misc.\nRequire Import Field2.\n\nSet Implicit Arguments.\n\nFixpoint summation_aux α (r : ring α) b len g :=\n  match len with\n  | O => 0%K\n  | S len₁ => (g b + summation_aux r (S b) len₁ g)%K\n  end.\n\nDefinition summation α {R : ring α} b e g := summation_aux R b (S e - b) g.\n\nNotation \"'Σ' ( i = b , e ) , g\" := (summation b e (λ i, (g)))\n  (at level 0, i at level 0, b at level 60, e at level 60, g at level 40).\n\nSection theorems_summation.\n\nVariable α : Type.\nVariable r : ring α.\nVariable f : field r.\n\nOpen Scope nat_scope.\n\nTheorem summation_aux_compat : ∀ g h b₁ b₂ len,\n  (∀ i, 0 ≤ i < len → (g (b₁ + i)%nat = h (b₂ + i)%nat)%K)\n  → (summation_aux r b₁ len g = summation_aux r b₂ len h)%K.\nProof.\nintros g h b₁ b₂ len Hgh.\nrevert b₁ b₂ Hgh.\ninduction len; intros; [ reflexivity | simpl ].\nrewrite IHlen.\n apply rng_add_compat_r.\n assert (0 ≤ 0 < S len) as H.\n  split; [ reflexivity | apply Nat.lt_0_succ ].\n\n  apply Hgh in H.\n  do 2 rewrite Nat.add_0_r in H; assumption.\n\n intros i Hi.\n do 2 rewrite Nat.add_succ_l, <- Nat.add_succ_r.\n apply Hgh.\n split; [ apply Nat.le_0_l | idtac ].\n apply lt_n_S.\n destruct Hi; assumption.\nQed.\n\nTheorem summation_compat : ∀ g h b k,\n  (∀ i, b ≤ i ≤ k → (g i = h i)%K)\n  → (Σ (i = b, k), g i = Σ (i = b, k), h i)%K.\nProof.\nintros g h b k Hgh.\napply summation_aux_compat.\nintros i (_, Hi).\napply Hgh.\nsplit; [ apply Nat.le_add_r | idtac ].\napply Nat.lt_add_lt_sub_r, le_S_n in Hi.\nrewrite Nat.add_comm; assumption.\nQed.\n\nTheorem summation_mul_comm : ∀ g h b k,\n  (Σ (i = b, k), g i * h i\n   = Σ (i = b, k), h i * g i)%K.\nProof.\nintros g h b len.\napply summation_compat; intros i Hi.\napply rng_mul_comm.\nQed.\n\nTheorem all_0_summation_aux_0 : ∀ g b len,\n  (∀ i, (b ≤ i < b + len) → (g i = 0)%K)\n  → (summation_aux r b len (λ i, g i) = 0)%K.\nProof.\nintros g b len H.\nrevert b H.\ninduction len; intros; [ reflexivity | simpl ].\nrewrite H; [ idtac | split; auto ].\n rewrite rng_add_0_l, IHlen; [ reflexivity | idtac ].\n intros i (Hbi, Hib); apply H.\n rewrite Nat.add_succ_r, <- Nat.add_succ_l.\n split; [ apply Nat.lt_le_incl; auto | auto ].\n\n rewrite Nat.add_succ_r.\n apply le_n_S, le_plus_l.\nQed.\n\nTheorem all_0_summation_0 : ∀ g i₁ i₂,\n  (∀ i, i₁ ≤ i ≤ i₂ → (g i = 0)%K)\n  → (Σ (i = i₁, i₂), g i = 0)%K.\nProof.\nintros g i₁ i₂ H.\napply all_0_summation_aux_0.\nintros i (H₁, H₂).\napply H.\nsplit; [ assumption | idtac ].\ndestruct (le_dec i₁ (S i₂)) as [H₃| H₃].\n rewrite Nat.add_sub_assoc in H₂; auto.\n rewrite minus_plus in H₂.\n apply le_S_n; auto.\n\n apply not_le_minus_0 in H₃.\n rewrite H₃, Nat.add_0_r in H₂.\n apply Nat.nle_gt in H₂; contradiction.\nQed.\n\nTheorem summation_aux_succ_last : ∀ g b len,\n  (summation_aux r b (S len) g =\n   summation_aux r b len g + g (b + len)%nat)%K.\nProof.\nintros g b len.\nrevert b.\ninduction len; intros.\n simpl.\n rewrite rng_add_0_l, rng_add_0_r, Nat.add_0_r.\n reflexivity.\n\n remember (S len) as x; simpl; subst x.\n rewrite IHlen.\n simpl.\n rewrite rng_add_assoc, Nat.add_succ_r.\n reflexivity.\nQed.\n\nTheorem summation_aux_rtl : ∀ g b len,\n  (summation_aux r b len g =\n   summation_aux r b len (λ i, g (b + len - 1 + b - i)%nat))%K.\nProof.\nintros g b len.\nrevert g b.\ninduction len; intros; [ reflexivity | idtac ].\nremember (S len) as x.\nrewrite Heqx in |- * at 1.\nsimpl; subst x.\nrewrite IHlen.\nrewrite summation_aux_succ_last.\nrewrite Nat.add_succ_l, Nat_sub_succ_1.\ndo 2 rewrite Nat.add_succ_r; rewrite Nat_sub_succ_1.\nrewrite Nat.add_sub_swap, Nat.sub_diag; auto.\nrewrite rng_add_comm.\napply rng_add_compat_r, summation_aux_compat.\nintros; reflexivity.\nQed.\n\nTheorem summation_rtl : ∀ g b k,\n  (Σ (i = b, k), g i = Σ (i = b, k), g (k + b - i)%nat)%K.\nProof.\nintros g b k.\nunfold summation.\nrewrite summation_aux_rtl.\napply summation_aux_compat; intros i (Hi, Hikb).\ndestruct b; simpl.\n rewrite Nat.sub_0_r; reflexivity.\n\n rewrite Nat.sub_0_r.\n simpl in Hikb.\n eapply Nat.le_lt_trans in Hikb; eauto .\n apply lt_O_minus_lt, Nat.lt_le_incl in Hikb.\n remember (b + (k - b))%nat as x eqn:H .\n rewrite Nat.add_sub_assoc in H; auto.\n rewrite Nat.add_sub_swap in H; auto.\n rewrite Nat.sub_diag in H; subst x; reflexivity.\nQed.\n\nTheorem summation_aux_mul_swap : ∀ a g b len,\n  (summation_aux r b len (λ i, a * g i) =\n   a * summation_aux r b len g)%K.\nProof.\nintros a g b len; revert b.\ninduction len; intros; simpl.\n rewrite rng_mul_0_r; reflexivity.\n\n rewrite IHlen, rng_mul_add_distr_l.\n reflexivity.\nQed.\n\nTheorem summation_aux_summation_aux_mul_swap : ∀ g₁ g₂ g₃ b₁ b₂ len,\n  (summation_aux r b₁ len\n     (λ i, summation_aux r b₂ (g₁ i) (λ j, g₂ i * g₃ i j))\n   = summation_aux r b₁ len\n       (λ i, g₂ i * summation_aux r b₂ (g₁ i) (λ j, g₃ i j)))%K.\nProof.\nintros g₁ g₂ g₃ b₁ b₂ len.\nrevert b₁ b₂.\ninduction len; intros; [ reflexivity | simpl ].\nrewrite IHlen.\napply rng_add_compat_r.\napply summation_aux_mul_swap.\nQed.\n\nTheorem summation_summation_mul_swap : ∀ g₁ g₂ g₃ k,\n  (Σ (i = 0, k), Σ (j = 0, g₁ i), g₂ i * g₃ i j\n   = Σ (i = 0, k), g₂ i * Σ (j = 0, g₁ i), g₃ i j)%K.\nProof.\nintros g₁ g₂ g₃ k.\napply summation_aux_summation_aux_mul_swap.\nQed.\n\nTheorem summation_only_one_non_0 : ∀ g b v k,\n  (b ≤ v ≤ k)\n  → (∀ i, (b ≤ i ≤ k) → (i ≠ v) → (g i = 0)%K)\n    → (Σ (i = b, k), g i = g v)%K.\nProof.\nintros g b v k (Hbv, Hvk) Hi.\nunfold summation.\nrewrite Nat.sub_succ_l; [ idtac | etransitivity; eassumption ].\nremember (k - b) as len.\nreplace k with (b + len) in * .\n clear k Heqlen.\n revert b v Hbv Hvk Hi.\n induction len; intros.\n  simpl.\n  rewrite rng_add_0_r.\n  replace b with v ; [ reflexivity | idtac ].\n  rewrite Nat.add_0_r in Hvk.\n  apply Nat.le_antisymm; assumption.\n\n  remember (S len) as x; simpl; subst x.\n  destruct (eq_nat_dec b v) as [H₁| H₁].\n   subst b.\n   rewrite all_0_summation_aux_0.\n    rewrite rng_add_0_r; reflexivity.\n\n    intros j (Hvj, Hjv).\n    simpl in Hjv.\n    apply le_S_n in Hjv.\n    apply Hi; [ split; auto; apply Nat.lt_le_incl; auto | idtac ].\n    intros H; subst j.\n    revert Hvj; apply Nat.nle_succ_diag_l.\n\n   rewrite Nat.add_succ_r, <- Nat.add_succ_l in Hvk.\n   rewrite Hi; auto.\n    rewrite rng_add_0_l.\n    apply IHlen; auto; [ apply Nat_le_neq_lt; auto | idtac ].\n    intros j (Hvj, Hjvl) Hjv.\n    rewrite Nat.add_succ_l, <- Nat.add_succ_r in Hjvl.\n    apply Hi; auto; split; auto.\n    apply Nat.lt_le_incl; auto.\n\n    split; auto.\n    apply Nat.le_sub_le_add_l.\n    rewrite Nat.sub_diag.\n    apply Nat.le_0_l.\n\n subst len.\n eapply Nat.le_trans in Hvk; eauto .\n rewrite Nat.add_sub_assoc; auto.\n rewrite Nat.add_comm.\n apply Nat.add_sub.\nQed.\n\nTheorem summation_shift : ∀ b g k,\n  b ≤ k\n  → (Σ (i = b, k), g i =\n     Σ (i = 0, k - b), g (b + i)%nat)%K.\nProof.\nintros b g k Hbk.\nunfold summation.\nrewrite Nat.sub_0_r.\nrewrite Nat.sub_succ_l; [ idtac | assumption ].\napply summation_aux_compat; intros j Hj.\nreflexivity.\nQed.\n\nTheorem summation_summation_shift : ∀ g k,\n  (Σ (i = 0, k), Σ (j = i, k), g i j =\n   Σ (i = 0, k), Σ (j = 0, k - i), g i (i + j)%nat)%K.\nProof.\nintros g k.\napply summation_compat; intros i Hi.\nunfold summation.\nrewrite Nat.sub_0_r.\nrewrite Nat.sub_succ_l; [ idtac | destruct Hi; assumption ].\napply summation_aux_compat; intros j Hj.\nrewrite Nat.add_0_l; reflexivity.\nQed.\n\nTheorem summation_only_one : ∀ g n, (Σ (i = n, n), g i = g n)%K.\nProof.\nintros g n.\nunfold summation.\nrewrite Nat.sub_succ_l; [ idtac | reflexivity ].\nrewrite Nat.sub_diag; simpl.\nrewrite rng_add_0_r; reflexivity.\nQed.\n\nTheorem summation_split_last : ∀ g b k,\n  (b ≤ S k)\n  → (Σ (i = b, S k), g i = Σ (i = b, k), g i + g (S k))%K.\nProof.\nintros g b k Hbk.\nunfold summation.\nrewrite Nat.sub_succ_l; [ idtac | assumption ].\nrewrite summation_aux_succ_last.\nrewrite Nat.add_sub_assoc; [ idtac | assumption ].\nrewrite Nat.add_comm, Nat.add_sub.\nreflexivity.\nQed.\n\nTheorem summation_aux_succ_first : ∀ g b len,\n  summation_aux r b (S len) g = (g b + summation_aux r (S b) len g)%K.\nProof. reflexivity. Qed.\n\nTheorem summation_split_first : ∀ g b k,\n  b ≤ k\n  → Σ (i = b, k), g i = (g b + Σ (i = S b, k), g i)%K.\nProof.\nintros g b k Hbk.\nunfold summation.\nrewrite Nat.sub_succ.\nrewrite <- summation_aux_succ_first.\nrewrite <- Nat.sub_succ_l; [ reflexivity | assumption ].\nQed.\n\nTheorem summation_add_distr : ∀ g h b k,\n  (Σ (i = b, k), (g i + h i) =\n   Σ (i = b, k), g i + Σ (i = b, k), h i)%K.\nProof.\nintros g h b k.\ndestruct (le_dec b k) as [Hbk| Hbk].\n revert b Hbk.\n induction k; intros.\n  destruct b.\n   do 3 rewrite summation_only_one; reflexivity.\n\n   unfold summation; simpl; rewrite rng_add_0_r; reflexivity.\n\n  rewrite summation_split_last; [ idtac | assumption ].\n  rewrite summation_split_last; [ idtac | assumption ].\n  rewrite summation_split_last; [ idtac | assumption ].\n  destruct (eq_nat_dec b (S k)) as [H₂| H₂].\n   subst b.\n   unfold summation; simpl.\n   rewrite Nat.sub_diag; simpl.\n   do 2 rewrite rng_add_0_l; rewrite rng_add_0_l.\n   reflexivity.\n\n   apply Nat_le_neq_lt in Hbk; [ idtac | assumption ].\n   apply Nat.succ_le_mono in Hbk.\n   rewrite IHk; [ idtac | assumption ].\n   do 2 rewrite <- rng_add_assoc.\n   apply rng_add_compat_l.\n   rewrite rng_add_comm.\n   rewrite <- rng_add_assoc.\n   apply rng_add_compat_l.\n   rewrite rng_add_comm.\n   reflexivity.\n\n unfold summation.\n apply Nat.nle_gt in Hbk.\n replace (S k - b) with O by fast_omega Hbk; simpl.\n rewrite rng_add_0_r; reflexivity.\nQed.\n\nTheorem summation_summation_exch : ∀ g k,\n  (Σ (j = 0, k), Σ (i = 0, j), g i j =\n   Σ (i = 0, k), Σ (j = i, k), g i j)%K.\nProof.\nintros g k.\ninduction k; [ reflexivity | idtac ].\nrewrite summation_split_last; [ idtac | apply Nat.le_0_l ].\nrewrite summation_split_last; [ idtac | apply Nat.le_0_l ].\nrewrite summation_split_last; [ idtac | apply Nat.le_0_l ].\nrewrite IHk.\nrewrite summation_only_one.\nrewrite rng_add_assoc.\napply rng_add_compat_r.\nrewrite <- summation_add_distr.\napply summation_compat; intros i (_, Hi).\nrewrite summation_split_last; [ reflexivity | idtac ].\napply Nat.le_le_succ_r; assumption.\nQed.\n\nTheorem summation_aux_ub_add : ∀ g b k₁ k₂,\n  (summation_aux r b (k₁ + k₂) g =\n   summation_aux r b k₁ g + summation_aux r (b + k₁) k₂ g)%K.\nProof.\nintros g b k₁ k₂.\nrevert b k₁.\ninduction k₂; intros.\n simpl.\n rewrite Nat.add_0_r, rng_add_0_r; reflexivity.\n\n rewrite Nat.add_succ_r, <- Nat.add_succ_l.\n rewrite IHk₂; simpl.\n rewrite <- Nat.add_succ_r.\n rewrite rng_add_assoc.\n apply rng_add_compat_r.\n clear k₂ IHk₂.\n revert b.\n induction k₁; intros; simpl.\n  rewrite Nat.add_0_r.\n  apply rng_add_comm.\n\n  rewrite <- rng_add_assoc.\n  rewrite IHk₁.\n  rewrite Nat.add_succ_r, <- Nat.add_succ_l; reflexivity.\nQed.\n\nTheorem summation_ub_add : ∀ g k₁ k₂,\n  (Σ (i = 0, k₁ + k₂), g i =\n   Σ (i = 0, k₁), g i + Σ (i = S k₁, k₁ + k₂), g i)%K.\nProof.\nintros g k₁ k₂.\nunfold summation.\ndo 2 rewrite Nat.sub_0_r.\nrewrite <- Nat.add_succ_l.\nrewrite summation_aux_ub_add; simpl.\nrewrite Nat.add_comm, Nat.add_sub; reflexivity.\nQed.\n\nTheorem summation_aux_mul_summation_aux_summation_aux : ∀ g k n,\n  (summation_aux r 0 (S k * S n) g =\n   summation_aux r 0 (S k)\n     (λ i, summation_aux r 0 (S n) (λ j, g (i * S n + j)%nat)))%K.\nProof.\nintros g k n.\nrevert n; induction k; intros.\n simpl; rewrite Nat.add_0_r, rng_add_0_r; reflexivity.\n\n remember (S n) as x.\n remember (S k) as y.\n simpl; subst x y.\n rewrite Nat.add_comm.\n rewrite summation_aux_ub_add, IHk.\n symmetry; rewrite rng_add_comm.\n symmetry.\n rewrite summation_aux_succ_first.\n rewrite rng_add_shuffle0, rng_add_comm.\n symmetry.\n replace (S k) with (k + 1)%nat by fast_omega.\n rewrite summation_aux_ub_add.\n rewrite <- rng_add_assoc.\n apply rng_add_compat_l.\n simpl.\n rewrite rng_add_comm.\n apply rng_add_compat_l.\n symmetry; rewrite Nat.add_comm; simpl.\n rewrite Nat.add_0_r, rng_add_0_r.\n apply rng_add_compat_l.\n apply summation_aux_compat; intros i Hi; simpl.\n rewrite Nat.add_succ_r; reflexivity.\nQed.\n\nTheorem summation_mul_summation_summation : ∀ g n k,\n  (0 < n)%nat\n  → (0 < k)%nat\n    → (Σ (i = 0, k * n - 1), g i =\n       Σ (i = 0, k - 1), Σ (j = 0, n - 1), g (i * n + j)%nat)%K.\nProof.\nintros g n k Hn Hk.\nunfold summation.\ndo 2 rewrite Nat.sub_0_r.\ndestruct n; [ exfalso; revert Hn; apply Nat.lt_irrefl | clear Hn ].\ndestruct k; [ exfalso; revert Hk; apply Nat.lt_irrefl | clear Hk ].\nrewrite Nat.sub_succ, Nat.sub_0_r.\nrewrite <- Nat.sub_succ_l, Nat.sub_succ, Nat.sub_0_r.\n rewrite summation_aux_mul_summation_aux_summation_aux.\n apply summation_aux_compat; intros i Hi.\n rewrite Nat.sub_succ, Nat.sub_0_r, Nat.sub_0_r.\n reflexivity.\n\n simpl; apply le_n_S, Nat.le_0_l.\nQed.\n\nTheorem inserted_0_summation : ∀ g h k n,\n  n ≠ O\n  → (∀ i, i mod n ≠ O → (g i = 0)%K)\n    → (∀ i, (g (n * i)%nat = h i)%K)\n      → (Σ (i = 0, k * n), g i = Σ (i = 0, k), h i)%K.\nProof.\nintros g h k n Hn Hf Hfg.\ndestruct k.\n rewrite Nat.mul_0_l.\n apply summation_compat; intros i (_, Hi).\n apply Nat.le_0_r in Hi; subst i.\n rewrite <- Hfg, Nat.mul_0_r; reflexivity.\n\n destruct n; [ exfalso; apply Hn; reflexivity | clear Hn ].\n replace (S k * S n)%nat with (S k * S n - 1 + 1)%nat.\n  rewrite summation_ub_add.\n  rewrite summation_mul_summation_summation; try apply Nat.lt_0_succ.\n  rewrite Nat_sub_succ_1, Nat.add_comm, summation_only_one.\n  simpl; do 2 rewrite Nat.sub_0_r.\n  symmetry.\n  rewrite <- Nat.add_1_r, summation_ub_add, Nat.add_1_r.\n  rewrite summation_only_one, rng_add_comm, <- Hfg.\n  symmetry.\n  rewrite rng_add_comm.\n  apply rng_add_compat; [ symmetry; rewrite Nat.mul_comm; reflexivity |  ].\n  apply summation_compat; intros i Hi.\n  rewrite summation_only_one_non_0 with (v := 0).\n   rewrite Nat.add_0_r, Nat.mul_comm; apply Hfg.\n\n   split; [ reflexivity | apply Nat.le_0_l ].\n\n   intros j Hjn Hj.\n   rewrite Hf; [ reflexivity |  ].\n   rewrite Nat.add_comm.\n   rewrite Nat.mod_add; [  | apply Nat.neq_succ_0 ].\n   intros H; apply Hj; clear Hj.\n   apply Nat.mod_divides in H; auto.\n   destruct H as (c, Hc).\n   destruct c.\n    rewrite Nat.mul_0_r in Hc; assumption.\n\n    rewrite Hc in Hjn.\n    rewrite Nat.mul_comm in Hjn.\n    simpl in Hjn.\n    destruct Hjn as (_, H).\n    apply Nat.nlt_ge in H.\n    exfalso; apply H.\n    apply le_n_S, Nat.le_add_r.\n\n  rewrite Nat.sub_add; [ apply eq_refl |  ].\n  simpl; apply le_n_S, Nat.le_0_l.\n\nQed.\n\nTheorem summation_add_add_sub : ∀ g b k n,\n  (Σ (i = b, k), g i = Σ (i = b + n, k + n), g (i - n)%nat)%K.\nProof.\nintros g b k n.\nunfold summation.\nreplace (S (k + n) - (b + n))%nat with (S k - b)%nat by fast_omega.\napply summation_aux_compat.\nintros i Hi.\nreplace (b + n + i - n)%nat with (b + i)%nat by fast_omega.\nreflexivity.\nQed.\n\nTheorem summation_succ_succ : ∀ b k g,\n  (Σ (i = S b, S k), g i = Σ (i = b, k), g (S i))%K.\nProof.\nintros b k g.\nunfold summation.\nrewrite Nat.sub_succ.\nremember (S k - b)%nat as len; clear Heqlen.\nrevert b.\ninduction len; intros; [ reflexivity | simpl ].\nrewrite IHlen; reflexivity.\nQed.\n\nEnd theorems_summation.\n", "meta": {"author": "roglo", "repo": "puiseuxth", "sha": "5b1cdc4d42e3585f5fdd57431cc06a3ffcdc3fb5", "save_path": "github-repos/coq/roglo-puiseuxth", "path": "github-repos/coq/roglo-puiseuxth/puiseuxth-5b1cdc4d42e3585f5fdd57431cc06a3ffcdc3fb5/coq/Fsummation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6837211217908498}}
{"text": "Inductive 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 :=\nmatch c with\n| black => true\n| white => true\n| primary q => false\nend.\n\nDefinition isred (c : color) : bool :=\nmatch c with\n| black => false\n| white => false\n| primary red => true\n| primary _ => false\nend.\n\nExample test_color1:  (monochrome black)  = true.\nProof. simpl. reflexivity.  Qed.\n\nExample test_color2:  (monochrome (primary red))  = false.\nProof. simpl. reflexivity.  Qed.\n\nExample test_color3:  (isred (primary red))  = true.\nProof. simpl. reflexivity.  Qed.\n\nExample test_color4:  (isred black)  = false.\nProof. simpl. reflexivity.  Qed.\n", "meta": {"author": "TysonSir", "repo": "coq", "sha": "3d5cd319a377acbdad1bec34061d298043c9bc18", "save_path": "github-repos/coq/TysonSir-coq", "path": "github-repos/coq/TysonSir-coq/coq-3d5cd319a377acbdad1bec34061d298043c9bc18/week2/demo_1_color.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6837211177296549}}
{"text": "(** * SfLib: Software Foundations Library *)\n\n(** Here we collect together several useful definitions and theorems\n    from Basics.v, List.v, Poly.v, Ind.v, and Logic.v that are not\n    already in the Coq standard library.  From now on we can [Import]\n    or [Export] this file, instead of cluttering our environment with\n    all the examples and false starts in those files. *)\n\n(** * From the Coq Standard Library *)\n\nRequire Omega.   (* needed for using the [omega] tactic *)\nRequire Export Bool.\nRequire Export List.\nExport ListNotations.\nRequire Export Arith.\nRequire Export Arith.EqNat.  (* Contains [beq_nat], among other things *)\n\n(** * From Basics.v *)\n\nDefinition admit {T: Type} : T.  Admitted.\n\nFixpoint ble_nat (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => ble_nat n' m'\n      end\n  end.\n\nTheorem andb_true_elim1 : forall b c,\n  andb b c = true -> b = true.\nProof.\n  intros b c H.\n  destruct b.\n  - (* b = true *)\n    reflexivity.\n  - (* b = false *)\n    rewrite <- H. reflexivity.  Qed.\n\nTheorem andb_true_elim2 : forall b c,\n  andb b c = true -> c = true.\nProof.\n(* An exercise in Basics.v *)\nAdmitted.\n\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\n(* An exercise in Lists.v *)\nAdmitted.\n\n(** * From Props.v *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(** * From Logic.v *)\n\nTheorem andb_true : forall b c,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  intros b c H.\n  destruct b.\n    destruct c.\n      apply conj. reflexivity. reflexivity.\n      inversion H.\n    inversion H.  Qed.\n\nTheorem false_beq_nat: forall n n' : nat,\n     n <> n' ->\n     beq_nat n n' = false.\nProof. \n(* An exercise in Logic.v *)\nAdmitted.\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  intros P contra.\n  inversion contra.  Qed.\n\nTheorem ev_not_ev_S : forall n,\n  ev n -> ~ ev (S n).\nProof. \n(* An exercise in Logic.v *)\nAdmitted.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\n(* An exercise in Logic.v *)\nAdmitted.\n\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\n(* An exercise in Logic.v *)\nAdmitted.\n\nInductive appears_in (n : nat) : list nat -> Prop :=\n| ai_here : forall l, appears_in n (n::l)\n| ai_later : forall m l, appears_in n l -> appears_in n (m::l).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n  | nn : next_nat n (S n).\n\nInductive total_relation : nat -> nat -> Prop :=\n  tot : forall n m : nat, total_relation n m.\n\nInductive empty_relation : nat -> nat -> Prop := .\n\n(** * From Later Files *)\n\nDefinition relation (X:Type) := X -> X -> Prop.\n\nDefinition deterministic {X: Type} (R: relation X) :=\n  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2. \n\nInductive multi (X:Type) (R: relation X) \n                            : X -> X -> Prop :=\n  | multi_refl  : forall (x : X),\n                 multi X R x x\n  | multi_step : forall (x y z : X),\n                    R x y ->\n                    multi X R y z ->\n                    multi X R x z.\nImplicit Arguments multi [[X]]. \n\nTheorem multi_R : forall (X:Type) (R:relation X) (x y : X),\n       R x y -> multi R x y.\nProof.\n  intros X R x y r.\n  apply multi_step with y. apply r. apply multi_refl.   Qed.\n\nTheorem multi_trans :\n  forall (X:Type) (R: relation X) (x y z : X),\n      multi R x y  ->\n      multi R y z ->\n      multi R x z.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(**  Identifiers and polymorphic partial maps. *)\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   - (* n1 = n2 *)\n     left. rewrite Heq. reflexivity.\n   - (* n1 <> n2 *)\n     right. intros contra. inversion contra. apply Hneq. apply H0.\nDefined. \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); try reflexivity. \n  apply ex_falso_quodlibet; auto.\nQed.\n\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  (* FILL IN HERE *) Admitted.\n\nDefinition partial_map (A:Type) := id -> option A.\n\nDefinition empty {A:Type} : partial_map A := (fun _ => None). \n\nNotation \"'\\empty'\" := empty.\n\nDefinition extend {A:Type} (Gamma : partial_map A) (x:id) (T : A) :=\n  fun x' => if eq_id_dec x x' then Some T else Gamma x'.\n\nLemma extend_eq : forall A (ctxt: partial_map A) x T,\n  (extend ctxt x T) x = Some T.\nProof.\n  intros. unfold extend. rewrite eq_id; auto. \nQed.\n\nLemma extend_neq : forall A (ctxt: partial_map A) x1 T x2,\n  x2 <> x1 ->\n  (extend ctxt x2 T) x1 = ctxt x1.\nProof.\n  intros. unfold extend. rewrite neq_id; auto. \nQed.\n\nLemma extend_shadow : forall A (ctxt: partial_map A) t1 t2 x1 x2,\n  extend (extend ctxt x2 t1) x2 t2 x1 = extend ctxt x2 t2 x1.\nProof with auto.\n  intros. unfold extend. destruct (eq_id_dec x2 x1)...\nQed.\n\n(** -------------------- *)\n\n(** * Some useful tactics *)\n\nTactic Notation \"solve_by_inversion_step\" tactic(t) :=  \n  match goal with  \n  | H : _ |- _ => solve [ inversion H; subst; t ] \n  end\n  || fail \"because the goal is not solvable by inversion.\".\n\nTactic Notation \"solve\" \"by\" \"inversion\" \"1\" :=\n  solve_by_inversion_step idtac.\nTactic Notation \"solve\" \"by\" \"inversion\" \"2\" :=\n  solve_by_inversion_step (solve by inversion 1).\nTactic Notation \"solve\" \"by\" \"inversion\" \"3\" :=\n  solve_by_inversion_step (solve by inversion 2).\nTactic Notation \"solve\" \"by\" \"inversion\" :=\n  solve by inversion 1.\n\n(** $Date: 2015-08-10 11:00:14 -0500 (Mon, 10 Aug 2015) $ *)\n\n", "meta": {"author": "isu-cs641s16-axum", "repo": "axum", "sha": "cf441c47f4ba5d85c869c5a425193bfdc02b5982", "save_path": "github-repos/coq/isu-cs641s16-axum-axum", "path": "github-repos/coq/isu-cs641s16-axum-axum/axum-cf441c47f4ba5d85c869c5a425193bfdc02b5982/SfLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.6837211147529116}}
{"text": "Require Import Coq.Lists.Streams.\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Setoids.Setoid.\n\nSection Stream_LE.\n  Context { A : Type }.\n  Context { Eq Le : relation A }.\n\n  Inductive stream_le_gen `{ PartialOrder A Eq Le} stream_le :\n    Stream A -> Stream A -> Prop :=\n  | Stream_le : forall h1 h2 t1 t2 ,\n      Le h1 h2 ->\n      (Eq h1 h2 -> stream_le t1 t2) ->\n      stream_le_gen stream_le (Cons h1 t1) (Cons h2 t2).\n\n  CoInductive stream_le `{ PartialOrder A Eq Le } :\n    Stream A -> Stream A -> Prop :=\n  | Stream_le_fold : forall s1 s2,\n      stream_le_gen stream_le s1 s2 -> stream_le s1 s2.\nEnd Stream_LE.\n\nSection Stream_LE_Theorem.\n  Variable A : Type.\n  Variable Eq Le : relation A.\n  Context `{ PartialOrder A Eq Le }.\n\n  Hint Constructors stream_le_gen stream_le.\n  \n  Ltac inv_stream_le :=\n    match goal with\n    | [H: stream_le (Cons _ _) (Cons _ _) |- _ ] =>\n      inversion H; subst; clear H\n    | [H: stream_le_gen _ _ _ |- _ ] =>\n      inversion H; subst; clear H\n    end.\n\n  Theorem stream_le_trans : forall (a b c : Stream A),\n      stream_le a b ->\n      stream_le b c ->\n      stream_le a c.\n  Proof.\n    cofix. constructor.\n    destruct a; destruct b; destruct c.\n    repeat inv_stream_le. constructor.\n    - eapply PreOrder_Transitive; eassumption.\n    - intros. rewrite H0 in H5. apply (antisymmetry H4) in H5.\n      rewrite H0 in H7. rewrite H5 in H7.\n      eapply stream_le_trans; eauto.\n      apply H7. apply Equivalence_Reflexive.\n  Qed.\nEnd Stream_LE_Theorem.\n", "meta": {"author": "lastland", "repo": "CoInduction-Study", "sha": "b7d79e816717c7a84689b1140ad8f1cbc58bdfb2", "save_path": "github-repos/coq/lastland-CoInduction-Study", "path": "github-repos/coq/lastland-CoInduction-Study/CoInduction-Study-b7d79e816717c7a84689b1140ad8f1cbc58bdfb2/Streams.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6836875194006922}}
{"text": "(* External import(s). *)\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Arith.EqNat.\n\nInductive identifier: Type :=\n  Identifier (i:nat).\n\nDefinition id_eqb (i i':identifier): bool :=\n  match (i, i') with\n  | (Identifier x, Identifier x') => beq_nat x x'\n  end.\n\nLemma id_eqb_refl: forall i i',\n  id_eqb i i' = true <-> i = i'.\nProof.\n  intros. destruct i, i'; unfold id_eqb; split; intro.\n  - apply PeanoNat.Nat.eqb_eq in H.\n    congruence.\n  - apply PeanoNat.Nat.eqb_eq.\n    congruence.\nQed.\n\nLemma id_eqb_refl_converse: forall i i',\n  id_eqb i i' = false <-> i <> i'.\nProof.\n  intros. destruct i, i'; unfold id_eqb; split; intro.\n  - apply PeanoNat.Nat.eqb_neq in H.\n    congruence.\n  - apply PeanoNat.Nat.eqb_neq.\n    congruence.\nQed.\n\nLemma id_eqb_sym: forall i i',\n  id_eqb i i' = id_eqb i' i.\nProof.\n  intros. destruct i, i'; unfold id_eqb.\n  apply PeanoNat.Nat.eqb_sym.\nQed.\n\nLemma id_eqb_equiv_eq: forall i i',\n  id_eqb i i' = true <-> i = i'.\nProof.\n  intros. destruct i, i'; unfold id_eqb; split; intro.\n  - apply PeanoNat.Nat.eqb_eq in H.\n    congruence.\n  - apply PeanoNat.Nat.eqb_eq.\n    congruence.\nQed.\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/Basics/Identifier.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.683687511550657}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Coq_Cats.Type_Cat.Type_Cat.\n\n(** A cardinality restriction for types is a property that holds for a type\n    if and only if it holds for all types isomorphic to it. *)\nRecord Card_Restriction : Type :=\n{\n  Card_Rest : Type → Prop;\n\n  Card_Rest_Respect : ∀ (A B : Type),\n      (A ≃≃ B ::> Type_Cat)%isomorphism → Card_Rest A → Card_Rest B\n}.\n\nCoercion Card_Rest : Card_Restriction >-> Funclass.\n\n(** A type is finite if it is isomorphic to a subset of natural numbers\n    less than n for soem natural number n. *)\nProgram Definition Finite : Card_Restriction :=\n  {|\n    Card_Rest :=\n      fun A => inhabited {n : nat & (A ≃≃ {x : nat | x < n} ::> Type_Cat)%isomorphism}\n  |}.\n\nNext Obligation.\nProof.\n  destruct H as [[n I]].\n  eexists.\n  refine (existT _ n (I ∘ (X⁻¹)%isomorphism)%isomorphism).\nQed.", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/Categories/Coq_Cats/Type_Cat/Card_Restriction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542283, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6835870068866984}}
{"text": "(* Copyright 2012-2015 by Adam Petcher.\t\t\t\t*\n * Use of this source code is governed by the license described\t*\n * in the LICENSE file at the root of the source tree.\t\t*)\n\nSet Implicit Arguments.\n\nRequire Import otp.Crypto.\nRequire Import otp.RndNat.\nRequire Import otp.NotationV1.\n\nDefinition Bernoulli(r : Rat) : Comp bool :=\n  match r with\n    | RatIntro n d =>\n      v <-$ RndNat d; ret (if (lt_dec v n) then true else false)\n  end.\n\n\nTheorem Bernoulli_correct : \n  forall (r : Rat),\n    r <= 1 ->\n    Pr[Bernoulli r] == r.\n\n  unfold Bernoulli.\n  intuition.\n  destruct r.\n\n  rewrite RndNat_seq.\n  \n  rewrite (sumList_filter_partition (fun z => if (lt_dec z n) then true else false)).\n  eapply eqRat_trans.\n  eapply ratMult_eqRat_compat.\n  eapply eqRat_refl.\n  eapply ratAdd_eqRat_compat.\n\n  eapply sumList_all.\n  intros.\n  destruct ( lt_dec a n).\n  simpl.\n  destruct ( EqDec_dec bool_EqDec true true).\n  eapply eqRat_refl.\n  intuition.\n  apply filter_In in H0.\n  intuition.\n  exfalso.\n  destruct (lt_dec a n); intuition.\n\n  eapply sumList_0.\n  intros.\n  apply filter_In in H0.\n  intuition.\n  destruct (lt_dec a n); simpl in *.\n  discriminate.\n  destruct (EqDec_dec bool_EqDec false true); intuition.\n\n  rewrite allNatsLt_filter_lt.\n  rewrite <- ratAdd_0_r.\n  rewrite ratMult_1_r.\n  rewrite allNatsLt_length.\n  rewrite <- ratMult_num_den.\n  eapply eqRat_terms.\n  omega.\n  unfold posnatMult, posnatToNat, natToPosnat.\n  destruct p.\n  omega.\n\n  eapply rat_le_1_if; trivial.\n\nQed.\n\nTheorem Bernoulli_wf : \n  forall r, \n    well_formed_comp (Bernoulli r).\n\n  intuition.\n  unfold Bernoulli.\n  destruct r.\n  wftac.\n\nQed.\n\nTheorem Bernoulli_correct_complement : \n  forall (r : Rat),\n    r <= 1 ->\n    evalDist (Bernoulli r) false == \n    ratSubtract 1 r.\n\n  intuition.\n  eapply eqRat_trans.\n  eapply evalDist_complement.\n  eapply Bernoulli_wf.\n  eapply ratSubtract_eqRat_compat; intuition.\n  eapply Bernoulli_correct.\n  trivial.\nQed.\n", "meta": {"author": "GaloisInc", "repo": "cryptol-semantics", "sha": "b4d8b55ec9b3b796427eb9e270e73e1857c597bf", "save_path": "github-repos/coq/GaloisInc-cryptol-semantics", "path": "github-repos/coq/GaloisInc-cryptol-semantics/cryptol-semantics-b4d8b55ec9b3b796427eb9e270e73e1857c597bf/otp/Bernoulli.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.8080672135527631, "lm_q1q2_score": 0.6835783544189141}}
{"text": "Require Import Relations.\nRequire Import PreLattice.\nRequire Import Chains.\n\nDefinition per A := { R : relation A | PER R }.\n\nDefinition toPER {A} (R: relation A) {E: PER R} : per A :=\n  exist PER R E.\n\nDefinition coarser {A} (R1 R2: per A) :=\n  forall x y, proj1_sig R2 x y -> proj1_sig R1 x y.\n\nInstance coarser_PreOrder {A} : PreOrder (@coarser A).\nProof.\nconstructor.\n+ intros ? ? ? ?. trivial.\n+ intros ? ? ? ? ? ? ? ?. auto.\nQed.\n\nDefinition intersection A (R1 R2: per A) : per A.\nProof.\ndestruct R1 as [R1 [Hsym1 Htrans1]].\ndestruct R2 as [R2 [Hsym2 Htrans2]].\nexists (fun x y => R1 x y /\\ R2 x y).\nconstructor.\n* intros ? ? [? ?]. split.\n    apply Hsym1. trivial.\n    apply Hsym2. trivial.\n* intros ? ? ? [? ?] [? ?]. split.\n    eapply Htrans1. eassumption. trivial.\n    eapply Htrans2. eassumption. trivial.\nDefined.\n\nInstance PERJoinPreLattice {A} : JoinPreLattice (per A) coarser :=\n{ join := intersection A }.\nProof.\n* intros [? [? ?]] [? [? ?]] ? ? [? ?]. trivial.\n* intros [? [? ?]] [? [? ?]] ? ? [? ?]. trivial.\n* intros [? [? ?]] [? [? ?]] [? [? ?]] ? ? ? ? ?.\n    unfold coarser in *. simpl in *. split; auto.\nDefined.\n\nDefinition union A (R1 R2: per A) : per A.\nProof.\ndestruct R1 as [R1 [Hsym1 Htrans1]].\ndestruct R2 as [R2 [Hsym2 Htrans2]].\nexists (clos_trans A (union A R1 R2)).\nconstructor.\n* intros x y Hxy. induction Hxy.\n  - destruct H.\n    + apply t_step. left. apply Hsym1. trivial.\n    + apply t_step. right. apply Hsym2. trivial.\n  - apply (t_trans A (union A R1 R2) z y x); trivial.\n* intros x y z Hxy Hyz. generalize dependent z.\n  induction Hxy; intros t Hyt.\n  - apply (t_trans A (union A R1 R2) x y t).\n    + apply t_step. destruct H; [left|right]; assumption.\n    + assumption.\n  - apply (t_trans A (union A R1 R2) x z t).\n    + apply IHHxy1. assumption.\n    + assumption.\nDefined.\n\nInstance PERMeetPreLattice {A} : MeetPreLattice (per A) coarser :=\n{ meet := union A }.\nProof.\n* intros [? [? ?]] [? [? ?]] ? ? ?. apply t_step. left. trivial.\n* intros [? [? ?]] [? [? ?]] ? ? ?. apply t_step. right. trivial.\n* intros [R1 [Hsym1 Htrans1]]\n         [R2 [Hsym2 Htrans2]]\n         [R3 [Hsym3 Htrans3]] H12 H23 x y Hplus.\n  unfold coarser in *; simpl in *. induction Hplus.\n  - destruct H; auto.\n  - eauto.\nDefined.\n\nDefinition per_top A : per A.\nProof.\nexists (fun _ _ => False). intuition.\nDefined.\n\nInstance PERHasTop {A} : HasTop (per A) coarser :=\n{ top := per_top A }.\nProof.\nunfold per_top. simpl.\nintros ? ? ? ?. simpl in *. tauto.\nDefined.\n\nDefinition per_bottom A : per A.\nProof.\nexists (fun _ _ => True). intuition.\nDefined.\n\nInstance PERHasBottom {A} : HasBottom (per A) coarser :=\n{ bottom := per_bottom A }.\nProof.\nunfold per_bottom.\nintros ? ? ? ?. simpl in *. trivial.\nDefined.\n\nModule FAMILY.\n\n  Definition big_union {A B} (f: A -> per B) : per B.\n  Proof.\n  exists (fun x y => forall a, proj1_sig (f a) x y).\n  constructor.\n  * intros x y H a. specialize (H a).\n    destruct (f a) as [R [Hsym Htrans]].\n    simpl in *. auto.\n  * intros x y z Hxy Hyz a.\n    specialize (Hxy a). specialize (Hyz a).\n    destruct (f a) as [R [Hsym Htrans]].\n    simpl in *. eauto.\n  Defined.\n\n  Lemma big_union_upper_bound {A B} :\n    forall (f: A -> per B),\n    forall a, coarser (f a) (big_union f).\n  Proof.\n  intros f a x y H. auto.\n  Qed.\n\n  Lemma big_union_least {A B} :\n    forall (f: A -> per B),\n    forall (bound: per B),\n      (forall a, coarser (f a) bound) ->\n      coarser (big_union f) bound.\n  Proof.\n  intros f bound Hbound x y H a. specialize (Hbound a x y H). trivial.\n  Qed.\n\n  Lemma big_union_monotone_zero {A} (zero: per A) (f: per A -> per A):\n    monotone f ->\n    monotone (fun zero => FAMILY.big_union (fun n => n_iter f n zero)).\n  Proof.\n    intros Hf R1 R2 HR x y Hxy n.\n    unfold FAMILY.big_union in Hxy. simpl in Hxy.\n    apply (n_iter_monotone_zero f Hf n R1 R2 HR x y).\n    auto.\n  Qed.\n\n  Definition big_intersection {A B} (f: A -> per B) : per B.\n  Proof.\n  exists (clos_trans _ (fun x y => exists a, proj1_sig (f a) x y)).\n  constructor.\n  * intros x y H. induction H.\n    + apply t_step. destruct H as [a H].\n      exists a.\n      destruct (f a) as [R [HRefl Hsym]].\n      simpl in *. auto.\n    + apply (t_trans _ _ z y x); auto.\n  * intros x y z Hxy Hyz. apply (t_trans _ _ x y z); auto.\n  Defined.\n\n  Lemma big_intersection_lower_bound {A B} :\n    forall (f: A -> per B),\n    forall a, coarser (big_intersection f) (f a).\n  Proof.\n  intros f a x y H. apply t_step. eauto.\n  Qed.\n\n  Lemma big_intersection_greatest {A B} :\n    forall (f: A -> per B),\n    forall (bound: per B),\n      (forall a, coarser bound (f a)) ->\n      coarser bound (big_intersection f).\n  Proof.\n  intros f bound Hbound x y H.\n  simpl in H. induction H.\n  * destruct H as [a H]. apply (Hbound a _ _ H).\n  * destruct bound as [bound [Hrefl Hsym]]. simpl in *. eauto.\n  Qed.\n\n  Lemma big_intersection_monotone_zero {A} (zero: per A) (f: per A -> per A):\n    monotone f ->\n    monotone (fun zero => FAMILY.big_intersection (fun n => n_iter f n zero)).\n  Proof.\n    intros Hf R1 R2 HR x y Hxy.\n    unfold FAMILY.big_intersection in *. simpl in *.\n    induction Hxy.\n    * apply t_step. destruct H as [n H]. exists n.\n      apply (n_iter_monotone_zero f Hf n R1 R2 HR x y). trivial.\n    * apply (t_trans _ _ x y z); auto.\n  Qed.\n\nEnd FAMILY.\n\nModule SET.\n\n  Definition big_union {A} (S: per A -> Prop) : per A.\n  Proof.\n  exists (fun x y => forall R, S R -> proj1_sig R x y).\n  constructor.\n  * intros x y Hxy R HR. specialize (Hxy R HR).\n    destruct R as [R [Hsym Htrans]]. simpl in *. auto.\n  * intros x y z Hxy Hyz R HR.\n    specialize (Hxy R HR). specialize (Hyz R HR).\n    destruct R as [R [Hsym Htrans]]. simpl in *. eauto.\n  Defined.\n\n  Lemma big_union_is_sup {A} :\n    forall (S: per A -> Prop), is_sup S (big_union S).\n  Proof.\n  intros S. split.\n  * intros R HR x y Runion. apply Runion. trivial.\n  * Require Import Classical.\n    intros R HR. apply NNPP.\n    unfold coarser; simpl. intro H.\n    assert (exists x y, proj1_sig R x y /\\ exists R, S R /\\ ~ proj1_sig R x y)\n      as [x [y [Hxy [R' [HR' HR'xy]]]]] by firstorder.\n    clear H.\n    apply HR'xy. apply HR; trivial.\n  Qed.\n\n  Definition big_intersection {A} (S: per A -> Prop) : per A.\n  Proof.\n  exists (clos_trans _ (fun x y => exists R, S R /\\ proj1_sig R x y)).\n  constructor.\n  * intros x y Hxy. induction Hxy.\n    + apply t_step. destruct H as [R [HSR HRxy]].\n      exists R. split; trivial.\n      destruct R as [R [Hrefl Hsym]]. simpl in *. auto.\n    + apply (t_trans _ _ z y x); auto.\n  * intros x y z Hxy Hyz. apply (t_trans _ _ x y z); auto.\n  Defined.\n\n  Lemma big_intersection_is_inf {A} :\n    forall (S: per A -> Prop), is_inf S (big_intersection S).\n  Proof.\n  intros S. split.\n  * intros R HR x y Runion. apply t_step. eauto.\n  * intros R HR x y Hxy. unfold big_intersection in Hxy. simpl in Hxy.\n    induction Hxy.\n    + destruct H as [R' [HSR' HR'xy]].\n      apply (HR R' HSR' _ _ HR'xy).\n    + destruct R as [R [Hrefl Hsym]]. simpl in *. eauto.\n  Qed.\n\nEnd SET.\n\nInstance PERJoinCompletePreLattice {A} :\n  JoinCompletePreLattice (per A) coarser := { }.\nProof.\nintros P.\nexists (SET.big_union P). apply SET.big_union_is_sup.\nDefined.\n\nInstance ERMeetCompletePreLattice {A} :\n  MeetCompletePreLattice (per A) coarser := { }.\nProof.\nintros P.\nexists (SET.big_intersection P). apply SET.big_intersection_is_inf.\nDefined.\n", "meta": {"author": "esope", "repo": "robustness_coq", "sha": "149b3b60f5f018237ad5371212cdb1e9e4603fdf", "save_path": "github-repos/coq/esope-robustness_coq", "path": "github-repos/coq/esope-robustness_coq/robustness_coq-149b3b60f5f018237ad5371212cdb1e9e4603fdf/PERLattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6835688968662865}}
{"text": "Require Export TopologicalSpaces.\nRequire Export Ensembles.\nFrom ZornsLemma Require Import EnsemblesImplicit.\nRequire Export InteriorsClosures.\n\nDefinition open_neighborhood {X:TopologicalSpace}\n  (U:Ensemble (point_set X)) (x:point_set X) :=\n  open U /\\ In U x.\n\nDefinition neighborhood {X:TopologicalSpace}\n  (N:Ensemble (point_set X)) (x:point_set X) :=\n  exists U:Ensemble (point_set X),\n    open_neighborhood U x /\\ Included U N.\n\nLemma open_neighborhood_is_neighborhood: forall {X:TopologicalSpace}\n  (U:Ensemble (point_set X)) (x:point_set X),\n  open_neighborhood U x -> neighborhood U x.\nProof.\nintros.\nexists U; auto with sets.\nQed.\n\nLemma neighborhood_interior: forall {X:TopologicalSpace}\n  (N:Ensemble (point_set X)) (x:point_set X),\n  neighborhood N x -> In (interior N) x.\nProof.\nintros.\ndestruct H.\ndestruct H.\ndestruct H.\nassert (Included x0 (interior N)).\napply interior_maximal; trivial.\nauto with sets.\nQed.\n\nLemma interior_neighborhood: forall {X:TopologicalSpace}\n  (N:Ensemble (point_set X)) (x:point_set X),\n  In (interior N) x -> neighborhood N x.\nProof.\nintros.\nexists (interior N).\nrepeat split.\napply interior_open.\nassumption.\napply interior_deflationary.\nQed.\n", "meta": {"author": "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/Neighborhoods.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6835688922301228}}
{"text": "Require Import QArith. \n(* ================================================================== *)\n(* ===== Point2D ==================================================== *)\n(* ================================================================== *)\nStructure Point2D := {\nid:> nat;\nx:> Q;\ny:> Q;\n}.\nDefinition Xp (pt : Point2D) : Q := x pt.\nDefinition Yp (pt : Point2D) : Q := y pt.\nAxiom Point2D_eq: forall (p q : Point2D), eq_nat (id p)(id q) -> p = q.", "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/Convex Hull/Point2D.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6835451097608617}}
{"text": "(* Exercise 82 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_082 : (forall x : D, P x) -> (forall x y z : D, P x /\\ P y /\\ P z).\nProof.\nimp_i a1.\nall_i a.\nall_i b.\nall_i c.\ncon_i.\nall_e (forall x:D, P x) a.\nhyp a1.\ncon_i.\nall_e (forall x:D, P x) b.\nhyp a1.\nall_e (forall x:D, P x) c.\nhyp a1.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred082.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6835451080073013}}
{"text": "Require Export TopologicalSpaces.\nRequire Export Nets.\nRequire Export FilterLimits.\nRequire Export Continuity.\n\nLocal Unset Standard Proposition Elimination Names.\nSet Asymmetric Patterns.\n\nDefinition compact (X:TopologicalSpace) :=\n  forall C:Family (point_set X),\n    (forall U:Ensemble (point_set X), In C U -> open U) ->\n    FamilyUnion C = Full_set ->\n    exists C':Family (point_set X),\n      Finite _ C' /\\ Included C' C /\\\n      FamilyUnion C' = Full_set.\n\nLemma compactness_on_indexed_covers:\n  forall (X:TopologicalSpace) (A:Type) (C:IndexedFamily A (point_set X)),\n    compact X ->\n    (forall a:A, open (C a)) -> IndexedUnion C = Full_set ->\n  exists A':Ensemble A, Finite _ A' /\\\n    IndexedUnion (fun a':{a':A | In A' a'} => C (proj1_sig a')) = Full_set.\nProof.\nintros.\npose (cover := ImageFamily C).\ndestruct (H cover) as [subcover].\nintros.\ndestruct H2.\nrewrite H3; apply H0.\nunfold cover; rewrite <- indexed_to_family_union; trivial.\ndestruct H2 as [? []].\ndestruct (finite_choice _ _\n  (fun (U:{U:Ensemble (point_set X) | In subcover U}) (a:A) =>\n      proj1_sig U = C a)) as [choice_fun].\napply Finite_ens_type; trivial.\ndestruct x as [U].\nsimpl.\napply H3 in i.\ndestruct i.\nexists x; trivial.\n\nexists (Im Full_set choice_fun).\nsplit.\napply FiniteT_img.\napply Finite_ens_type; trivial.\nintros; apply classic.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nrewrite <- H4 in H6.\ndestruct H6.\nassert (In (Im Full_set choice_fun) (choice_fun (exist _ S H6))).\nexists (exist _ S H6).\nconstructor.\ntrivial.\nexists (exist _ (choice_fun (exist _ S H6)) H8).\nsimpl.\nrewrite <- H5.\nsimpl.\ntrivial.\nQed.\n\nLemma compact_finite_nonempty_closed_intersection:\n  forall X:TopologicalSpace, compact X ->\n  forall F:Family (point_set X),\n    (forall G:Ensemble (point_set X), In F G -> closed G) ->\n    (forall F':Family (point_set X), Finite _ F' -> Included F' F ->\n     Inhabited (FamilyIntersection F')) ->\n    Inhabited (FamilyIntersection F).\nProof.\nintros.\napply NNPP; red; intro.\npose (C := [ U:Ensemble (point_set X) | In F (Complement U) ]).\nunshelve refine (let H3:=(H C _ _) in _).\nintros.\ndestruct H3.\napply H0 in H3.\napply closed_complement_open; trivial.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\napply NNPP; red; intro.\ncontradiction H2.\nexists x.\nconstructor.\nintros.\napply NNPP; red; intro.\ncontradiction H4.\nexists (Complement S).\nconstructor.\nrewrite Complement_Complement; trivial.\nexact H6.\n\ndestruct H3 as [C' [? [? ?]]].\npose (F' := [G : Ensemble (point_set X) | In C' (Complement G)]).\nunshelve refine (let H6 := (H1 F' _ _) in _).\nassert (F' = Im C' Complement).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H6.\nexists (Complement x); trivial.\nsymmetry; apply Complement_Complement.\ndestruct H6.\nconstructor.\nrewrite H7; rewrite Complement_Complement; trivial.\nrewrite H6; apply finite_image.\nassumption.\n\nred; intros.\ndestruct H6.\napply H4 in H6.\ndestruct H6.\nrewrite Complement_Complement in H6; trivial.\n\ndestruct H6 as [x0].\ndestruct H6.\nassert (In (FamilyUnion C') x).\nrewrite H5; constructor.\ndestruct H7.\nassert (In (Complement S) x).\napply H6.\nconstructor.\nrewrite Complement_Complement; trivial.\ncontradiction H9.\nQed.\n\nLemma finite_nonempty_closed_intersection_impl_compact:\n  forall X:TopologicalSpace,\n  (forall F:Family (point_set X),\n    (forall G:Ensemble (point_set X), In F G -> closed G) ->\n    (forall F':Family (point_set X), Finite _ F' -> Included F' F ->\n     Inhabited (FamilyIntersection F')) ->\n    Inhabited (FamilyIntersection F)) ->\n  compact X.\nProof.\nintros.\nred; intros.\napply NNPP; red; intro.\npose (F := [ G:Ensemble (point_set X) | In C (Complement G) ]).\nunshelve refine (let H3 := (H F _ _) in _).\nintros.\ndestruct H3.\napply H0; trivial.\nintros.\napply NNPP; red; intro.\ncontradiction H2.\nexists [ U:Ensemble (point_set X) | In F' (Complement U) ].\nrepeat split.\nassert ([U:Ensemble (point_set X) | In F' (Complement U)] =\n  Im F' Complement).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H6.\nexists (Complement x); trivial.\nsymmetry; apply Complement_Complement.\nconstructor.\ndestruct H6.\nrewrite H7; rewrite Complement_Complement; trivial.\nrewrite H6; apply finite_image; trivial.\n\nred; intros.\ndestruct H6.\napply H4 in H6.\ndestruct H6.\nrewrite Complement_Complement in H6; trivial.\n\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\napply NNPP; red; intro.\ncontradiction H5.\nexists x.\nconstructor.\nintros.\napply NNPP; red; intro.\ncontradiction H7.\nexists (Complement S).\nconstructor.\nrewrite Complement_Complement; trivial.\nexact H9.\n\ndestruct H3.\nassert (In (FamilyUnion C) x).\nrewrite H1; constructor.\ndestruct H4.\nassert (In (Complement S) x).\ndestruct H3.\napply H3.\nconstructor.\nrewrite Complement_Complement; trivial.\ncontradiction H6.\nQed.\n\nLemma compact_impl_filter_cluster_point:\n  forall X:TopologicalSpace, compact X ->\n    forall F:Filter (point_set X), exists x0:point_set X,\n    filter_cluster_point F x0.\nProof.\nintros.\npose proof (compact_finite_nonempty_closed_intersection\n  _ H [ G:Ensemble (point_set X) | In (filter_family F) G /\\\n                                   closed G ]) as [x0].\nintros.\ndestruct H0 as [[]]; trivial.\nintros.\nassert (closed (FamilyIntersection F')).\napply closed_family_intersection.\nintros.\napply H1 in H2.\ndestruct H2 as [[]]; trivial.\nassert (In (filter_family F) (FamilyIntersection F')).\nclear H2.\ninduction H0.\nrewrite empty_family_intersection.\napply filter_full.\nreplace (FamilyIntersection (Add A x)) with\n  (Intersection (FamilyIntersection A) x).\napply filter_intersection.\napply IHFinite.\nauto with sets.\nassert (In (Add A x) x) by (right; constructor).\napply H1 in H3.\ndestruct H3 as [[]]; trivial.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H3.\nconstructor.\nintros.\ndestruct H5.\ndestruct H3.\napply H3; trivial.\ndestruct H5; trivial.\ndestruct H3.\nconstructor.\nconstructor; intros.\napply H3.\nauto with sets.\napply H3.\nauto with sets.\napply NNPP; intro.\ncontradiction (filter_empty _ F).\nreplace (@Empty_set (point_set X)) with (FamilyIntersection F'); trivial.\napply Extensionality_Ensembles; split; red; intros.\ncontradiction H4.\nexists x; trivial.\ndestruct H5.\n\nexists x0.\nred; intros.\ndestruct H0.\napply H0.\nconstructor.\nsplit.\napply filter_upward_closed with S; trivial.\napply closure_inflationary.\napply closure_closed.\nQed.\n\nLemma filter_cluster_point_impl_compact:\n  forall X:TopologicalSpace,\n    (forall F:Filter (point_set X), exists x0:point_set X,\n      filter_cluster_point F x0) -> compact X.\nProof.\nintros.\napply finite_nonempty_closed_intersection_impl_compact.\nintros.\nunshelve refine (let H2:=_ in let filt := Build_Filter_from_subbasis F H2 in _).\nintros.\nrewrite indexed_to_family_intersection.\napply H1.\napply FiniteT_img; trivial.\nintros; apply classic.\nred; intros.\ndestruct H4.\nrewrite H5; apply H3.\nassert (filter_subbasis filt F) by apply filter_from_subbasis_subbasis.\ndestruct (H filt) as [x0].\nexists x0.\nconstructor; intros.\nassert (closed S) by (apply H0; trivial).\nassert (In (filter_family filt) S).\napply (filter_subbasis_elements _ _ H3); trivial.\npose proof (H4 _ H7).\nrewrite closure_fixes_closed in H8; trivial.\nQed.\n\nLemma ultrafilter_limit_impl_compact:\n  forall X:TopologicalSpace,\n    (forall U:Filter (point_set X), ultrafilter U ->\n      exists x0:point_set X, filter_limit U x0) -> compact X.\nProof.\nintros.\napply filter_cluster_point_impl_compact.\nintros.\ndestruct (ultrafilter_extension F) as [U].\ndestruct H0.\ndestruct (H _ H1) as [x0].\nexists x0.\nred; intros.\napply filter_limit_is_cluster_point in H2.\napply H0 in H3.\napply H2; trivial.\nQed.\n\nLemma compact_impl_net_cluster_point:\n  forall X:TopologicalSpace, compact X ->\n    forall (I:DirectedSet) (x:Net I X), inhabited (DS_set I) ->\n    exists x0:point_set X, net_cluster_point x x0.\nProof.\nRequire Import FiltersAndNets.\nintros.\ndestruct (compact_impl_filter_cluster_point\n  _ H (tail_filter x H0)) as [x0].\nexists x0.\napply tail_filter_cluster_point_impl_net_cluster_point with H0.\napply H1.\nQed.\n\nLemma net_cluster_point_impl_compact: forall X:TopologicalSpace,\n  (forall (I:DirectedSet) (x:Net I X), inhabited (DS_set I) ->\n    exists x0:point_set X, net_cluster_point x x0) ->\n  compact X.\nProof.\nintros.\napply filter_cluster_point_impl_compact.\nintros.\ndestruct (H _ (filter_to_net _ F)) as [x0].\ncut (inhabited (point_set X)).\nintro.\ndestruct H0 as [x].\nexists.\nsimpl.\napply Build_filter_to_net_DS_set with Full_set x.\napply filter_full.\nconstructor.\napply NNPP; intro.\ncontradiction (filter_empty _ F).\nreplace (@Empty_set (point_set X)) with (@Full_set (point_set X)).\napply filter_full.\napply Extensionality_Ensembles; split; red; intros.\ncontradiction H0.\nexists; exact x.\ndestruct H1.\n\nexists x0.\napply filter_to_net_cluster_point_impl_filter_cluster_point.\ntrivial.\nQed.\n\nRequire Export SeparatednessAxioms.\nRequire Export SubspaceTopology.\n\nLemma compact_closed: forall (X:TopologicalSpace)\n  (S:Ensemble (point_set X)), Hausdorff X ->\n  compact (SubspaceTopology S) -> closed S.\nProof.\nintros.\ndestruct (classic (Inhabited S)).\nassert (closure S = S).\napply Extensionality_Ensembles; split.\nred; intros.\ndestruct (net_limits_determine_topology _ _ H2) as [I0 [y []]].\npose (yS (i:DS_set I0) := exist (fun x:point_set X => In S x) (y i) (H3 i)).\nassert (inhabited (point_set (SubspaceTopology S))).\ndestruct H1.\nexists.\nexists x0; trivial.\nassert (inhabited (DS_set I0)) as HinhI0.\nred in H4.\ndestruct (H4 Full_set) as [i0]; auto with topology.\nconstructor.\npose proof (compact_impl_net_cluster_point\n  (SubspaceTopology S) H0 _ yS HinhI0).\ndestruct H6 as [[x0]].\napply net_cluster_point_impl_subnet_converges in H6.\ndestruct H6 as [J [y' []]].\ndestruct H6.\nassert (net_limit (fun j:DS_set J => y (h j)) x0).\napply continuous_func_preserves_net_limits with\n  (f:=subspace_inc S) (Y:=X) in H7.\nsimpl in H7.\nassumption.\napply continuous_func_continuous_everywhere.\napply subspace_inc_continuous.\nassert (net_limit (fun j:DS_set J => y (h j)) x).\napply subnet_limit with I0 y; trivial.\nconstructor; trivial.\nassert (x = x0).\nexact (Hausdorff_impl_net_limit_unique _ H _ _ H10 H9).\nrewrite H11; trivial.\ndestruct (H4 Full_set).\napply open_full.\nconstructor.\nexists; exact x1.\ndestruct H1.\n\napply closure_inflationary.\nrewrite <- H2; apply closure_closed.\n\nred.\nassert (Complement S = Full_set).\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nred; intro.\ncontradiction H1; exists x; trivial.\nrewrite H2; apply open_full.\nQed.\n\nLemma closed_compact: forall (X:TopologicalSpace) (S:Ensemble (point_set X)),\n  compact X -> closed S -> compact (SubspaceTopology S).\nProof.\nintros.\napply net_cluster_point_impl_compact.\nintros.\ndestruct (compact_impl_net_cluster_point _ H\n  _ (fun i:DS_set I => subspace_inc _ (x i))) as [x0].\ntrivial.\nassert (In S x0).\nrewrite <- (closure_fixes_closed S); trivial.\napply net_cluster_point_in_closure with\n  (2:=H2).\ndestruct H1 as [i0].\nexists i0.\nintros.\ndestruct (x j).\nsimpl.\ntrivial.\nexists (exist _ x0 H3).\nred; intros.\nred; intros.\ndestruct (subspace_topology_topology _ _ _ H4) as [V []].\nrewrite H7 in H5.\ndestruct H5.\nsimpl in H5.\ndestruct (H2 V H6 H5 i) as [j []]; trivial.\nexists j; split; trivial.\nrewrite H7.\nconstructor.\ntrivial.\nQed.\n\nLemma compact_image: forall {X Y:TopologicalSpace}\n  (f:point_set X->point_set Y),\n  compact X -> continuous f -> surjective f -> compact Y.\nProof.\nintros.\nred; intros.\npose (B := fun U:{U:Ensemble (point_set Y) | In C U} =>\n           inverse_image f (proj1_sig U)).\ndestruct (compactness_on_indexed_covers _ _ B H) as [subcover].\ndestruct a as [U].\nunfold B; simpl.\napply H0.\napply H2; trivial.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nassert (In (FamilyUnion C) (f x)).\nrewrite H3; constructor.\ninversion_clear H5 as [V].\nexists (exist _ V H6).\nunfold B; simpl.\nconstructor; trivial.\ndestruct H4.\n\nexists (Im subcover (@proj1_sig _ (fun U:Ensemble (point_set Y) => In C U))).\nrepeat split.\napply finite_image; trivial.\nred; intros V ?.\ndestruct H6 as [[U]].\nsimpl in H7.\ncongruence.\napply Extensionality_Ensembles; split; red; intros y ?.\nconstructor.\ndestruct (H1 y) as [x].\nassert (In (IndexedUnion\n  (fun a':{a' | In subcover a'} => B (proj1_sig a'))) x).\nrewrite H5; constructor.\ndestruct H8 as [[[U]]].\nexists U.\nsimpl in H8.\nexists (exist _ U i); trivial.\nunfold B in H8; simpl in H8.\ndestruct H8.\ncongruence.\nQed.\n\nLemma compact_Hausdorff_impl_normal_sep: forall X:TopologicalSpace,\n  compact X -> Hausdorff X -> normal_sep X.\nProof.\nintros.\nassert (T3_sep X).\nRequire Import ClassicalChoice.\ndestruct (choice (fun (xy:{xy:point_set X * point_set X |\n                  let (x,y):=xy in x <> y})\n  (UV:Ensemble (point_set X) * Ensemble (point_set X)) =>\n  match xy with | exist (x,y) i =>\n    let (U,V):=UV in\n  open U /\\ open V /\\ In U x /\\ In V y /\\ Intersection U V = Empty_set\n  end)) as\n[choice_fun].\ndestruct x as [[x y] i].\ndestruct (H0 _ _ i) as [U [V]].\nexists (U, V); trivial.\n\npose (choice_fun_U := fun (x y:point_set X)\n  (Hineq:x<>y) => fst (choice_fun (exist _ (x,y) Hineq))).\npose (choice_fun_V := fun (x y:point_set X)\n  (Hineq:x<>y) => snd (choice_fun (exist _ (x,y) Hineq))).\nassert (forall (x y:point_set X) (Hineq:x<>y),\n  open (choice_fun_U x y Hineq) /\\\n  open (choice_fun_V x y Hineq) /\\\n  In (choice_fun_U x y Hineq) x /\\\n  In (choice_fun_V x y Hineq) y /\\\n  Intersection (choice_fun_U x y Hineq) (choice_fun_V x y Hineq) = Empty_set).\nintros.\nunfold choice_fun_U; unfold choice_fun_V.\npose proof (H1 (exist _ (x,y) Hineq)).\ndestruct (choice_fun (exist _ (x,y) Hineq)).\nexact H2.\nclearbody choice_fun_U choice_fun_V; clear choice_fun H1.\n\nsplit.\napply Hausdorff_impl_T1_sep; trivial.\nintros.\npose proof (closed_compact _ _ H H1).\nassert (forall y:point_set X, In F y -> x <> y).\nintros.\ncongruence.\npose (cover := fun (y:point_set (SubspaceTopology F)) =>\n  let (y,i):=y in inverse_image (subspace_inc F)\n                     (choice_fun_V x y (H5 y i))).\ndestruct (compactness_on_indexed_covers _ _ cover H4) as [subcover].\ndestruct a as [y i].\napply subspace_inc_continuous.\napply H2.\napply Extensionality_Ensembles; split; red; intros y ?.\nconstructor.\nexists y.\ndestruct y as [y i].\nsimpl.\nconstructor.\nsimpl.\napply H2.\ndestruct H6.\n\nexists (IndexedIntersection\n  (fun y:{y:point_set (SubspaceTopology F) | In subcover y} =>\n    let (y,_):=y in let (y,i):=y in choice_fun_U x y (H5 y i))).\nexists (IndexedUnion\n  (fun y:{y:point_set (SubspaceTopology F) | In subcover y} =>\n    let (y,_):=y in let (y,i):=y in choice_fun_V x y (H5 y i))).\nrepeat split.\napply open_finite_indexed_intersection.\napply Finite_ens_type; trivial.\ndestruct a as [[y]].\napply H2.\napply open_indexed_union.\ndestruct a as [[y]].\napply H2.\ndestruct a as [[y]].\napply H2.\nred; intros y ?.\nassert (In (IndexedUnion\n  (fun y:{y:point_set (SubspaceTopology F) | In subcover y} =>\n    cover (proj1_sig y))) (exist _ y H8)).\nrewrite H7; constructor.\nremember (exist (In F) y H8) as ysig.\ndestruct H9 as [[y']].\nrewrite Heqysig in H9; clear x0 Heqysig.\nsimpl in H9.\ndestruct y' as [y'].\nsimpl in H9.\ndestruct H9.\nsimpl in H9.\nexists (exist _ (exist _ y' i0) i).\ntrivial.\n\napply Extensionality_Ensembles; split; auto with sets; red; intros y ?.\ndestruct H8.\ndestruct H8.\ndestruct H9.\npose proof (H8 a).\ndestruct a as [[y]].\nreplace (@Empty_set (point_set X)) with\n  (Intersection (choice_fun_U x y (H5 y i))\n                (choice_fun_V x y (H5 y i))).\nconstructor; trivial.\napply H2.\n\ndestruct (choice (fun (xF:{p:point_set X * Ensemble (point_set X) |\n                        let (x,F):=p in closed F /\\ ~ In F x})\n  (UV:Ensemble (point_set X) * Ensemble (point_set X)) =>\n  let (p,i):=xF in let (x,F):=p in\n  let (U,V):=UV in\n  open U /\\ open V /\\ In U x /\\ Included F V /\\\n  Intersection U V = Empty_set)) as [choice_fun].\ndestruct x as [[x F] []].\ndestruct H1.\ndestruct (H4 x F H2 H3) as [U [V]].\nexists (U,V); trivial.\n\npose (choice_fun_U := fun (x:point_set X) (F:Ensemble (point_set X))\n  (HC:closed F) (Hni:~ In F x) =>\n  fst (choice_fun (exist _ (x,F) (conj HC Hni)))).\npose (choice_fun_V := fun (x:point_set X) (F:Ensemble (point_set X))\n  (HC:closed F) (Hni:~ In F x) =>\n  snd (choice_fun (exist _ (x,F) (conj HC Hni)))).\nassert (forall (x:point_set X) (F:Ensemble (point_set X))\n  (HC:closed F) (Hni:~ In F x),\n  open (choice_fun_U x F HC Hni) /\\\n  open (choice_fun_V x F HC Hni) /\\\n  In (choice_fun_U x F HC Hni) x /\\\n  Included F (choice_fun_V x F HC Hni) /\\\n  Intersection (choice_fun_U x F HC Hni) (choice_fun_V x F HC Hni) =\n     Empty_set).\nintros.\npose proof (H2 (exist _ (x,F) (conj HC Hni))).\nunfold choice_fun_U; unfold choice_fun_V;\n  destruct (choice_fun (exist _ (x,F) (conj HC Hni))); trivial.\nclearbody choice_fun_U choice_fun_V; clear choice_fun H2.\nsplit.\napply H1.\nintros.\npose proof (closed_compact _ _ H H2).\nassert (forall x:point_set X, In F x -> ~ In G x).\nintros.\nintro.\nabsurd (In Empty_set x).\nred; destruct 1.\nrewrite <- H5; split; trivial.\n\npose (cover := fun x:point_set (SubspaceTopology F) =>\n  let (x,i):=x in inverse_image (subspace_inc F)\n                   (choice_fun_U x G H4 (H7 x i))).\ndestruct (compactness_on_indexed_covers _ _ cover H6) as [subcover].\ndestruct a as [x i].\napply subspace_inc_continuous.\napply H3.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nexists x.\ndestruct x.\nsimpl cover.\nconstructor.\nsimpl.\napply H3.\ndestruct H8.\n\nexists (IndexedUnion\n  (fun x:{x:point_set (SubspaceTopology F) | In subcover x} =>\n     let (x,i):=proj1_sig x in choice_fun_U x G H4 (H7 x i))).\nexists (IndexedIntersection\n  (fun x:{x:point_set (SubspaceTopology F) | In subcover x} =>\n     let (x,i):=proj1_sig x in choice_fun_V x G H4 (H7 x i))).\nrepeat split.\napply open_indexed_union.\ndestruct a as [[x]].\nsimpl.\napply H3.\napply open_finite_indexed_intersection.\napply Finite_ens_type; trivial.\ndestruct a as [[x]].\nsimpl.\napply H3.\nintros x ?.\nassert (In (@Full_set (point_set (SubspaceTopology F))) (exist _ x H10))\n  by constructor.\nrewrite <- H9 in H11.\nremember (exist _ x H10) as xsig.\ndestruct H11.\ndestruct a as [x'].\ndestruct x' as [x'].\nrewrite Heqxsig in H11; clear x0 Heqxsig.\nsimpl in H11.\ndestruct H11.\nsimpl in H11.\nexists (exist _ (exist _ x' i0) i).\nsimpl.\ntrivial.\ndestruct a as [x'].\nsimpl.\ndestruct x' as [x'].\nassert (Included G (choice_fun_V x' G H4 (H7 x' i0))) by apply H3.\nauto.\n\napply Extensionality_Ensembles; split; auto with sets; red; intros.\ndestruct H10.\ndestruct H10.\ndestruct H11.\npose proof (H11 a).\ndestruct a as [[x']].\nsimpl in H12.\nsimpl in H10.\nreplace (@Empty_set (point_set X)) with (Intersection\n  (choice_fun_U x' G H4 (H7 x' i))\n  (choice_fun_V x' G H4 (H7 x' i))).\nconstructor; trivial.\napply H3.\nQed.\n", "meta": {"author": "verimath", "repo": "topology", "sha": "9405aaf18d99c718769f1d2af8e030a902687837", "save_path": "github-repos/coq/verimath-topology", "path": "github-repos/coq/verimath-topology/topology-9405aaf18d99c718769f1d2af8e030a902687837/src/top/Compactness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6835451062983509}}
{"text": "Variables A B C : Prop.\nLemma ex4 : ((A /\\ B) -> C) -> (A -> B -> C).\nProof.\n  intro Ha_and_Hb_implies_Hc.\n  intro Ha.\n  intro Hb.\n  apply Ha_and_Hb_implies_Hc.\n  split.\n    +\n      assumption.\n    +\n      assumption.\nQed.", "meta": {"author": "alvarofpp", "repo": "course-coq", "sha": "64dc0d9a2e6564f9fa5df508fa946a137901feee", "save_path": "github-repos/coq/alvarofpp-course-coq", "path": "github-repos/coq/alvarofpp-course-coq/course-coq-64dc0d9a2e6564f9fa5df508fa946a137901feee/logica_proposicional_e_predicados/conjuncao/exercicio_04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.683545099417939}}
{"text": "From Coqprime Require Import PocklingtonRefl.\n\nLocal Open Scope positive_scope.\n\nLemma primo80 : prime 208870589.\nProof.\n apply (Pocklington_refl\n         (Pock_certif 208870589 2 ((211, 1)::(2,2)::nil) 1028)\n        ((Proof_certif 211 prime211) ::\n         (Proof_certif 2 prime2) ::\n          nil)).\n native_cast_no_check (refl_equal true).\nQed.\n\n", "meta": {"author": "mukeshtiwari", "repo": "Formally_Verified_Verifiable_Group_Generator", "sha": "e80e8d43e81b5201d6ab82a8ebc07a5cef03476b", "save_path": "github-repos/coq/mukeshtiwari-Formally_Verified_Verifiable_Group_Generator", "path": "github-repos/coq/mukeshtiwari-Formally_Verified_Verifiable_Group_Generator/Formally_Verified_Verifiable_Group_Generator-e80e8d43e81b5201d6ab82a8ebc07a5cef03476b/primality/p5_80.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6835450977535982}}
{"text": "(**\n\nThis file contains formalizations of lists. First over sets as the initial algebra of the list\nfunctor ([List]) and then more generally over any type defined as iterated products ([list]).\n\nWritten by: Anders Mörtberg, 2016\n\n*)\nRequire Import UniMath.Foundations.PartD.\nRequire Import UniMath.Foundations.Propositions.\nRequire Import UniMath.Foundations.Sets.\nRequire Import UniMath.Foundations.NaturalNumbers.\n\nRequire Import UniMath.Combinatorics.Lists.\n\nRequire Import UniMath.MoreFoundations.PartA. (* flip *)\nRequire Import UniMath.MoreFoundations.Tactics.\n\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.limits.graphs.colimits.\nRequire Import UniMath.CategoryTheory.categories.HSET.Core.\nRequire Import UniMath.CategoryTheory.categories.HSET.Limits.\nRequire Import UniMath.CategoryTheory.categories.HSET.Colimits.\nRequire Import UniMath.CategoryTheory.limits.initial.\nRequire Import UniMath.CategoryTheory.FunctorAlgebras.\nRequire Import UniMath.CategoryTheory.limits.binproducts.\nRequire Import UniMath.CategoryTheory.limits.terminal.\nRequire Import UniMath.CategoryTheory.Chains.All.\nRequire Import UniMath.CategoryTheory.exponentials.\nRequire Import UniMath.CategoryTheory.limits.bincoproducts.\nRequire Import UniMath.CategoryTheory.PrecategoryBinProduct.\n\nLocal Open Scope cat.\n\n(** * Lists as the colimit of a chain given by the list functor: F(X) = 1 + A * X *)\nSection lists.\n\nVariable A : HSET.\n\nLocal Open Scope cocont_functor_hset_scope.\n\n(** F(X) = 1 + (A * X) *)\nDefinition L_A : omega_cocont_functor HSET HSET := '1 + 'A * Id.\n\nLet listFunctor : functor HSET HSET := pr1 L_A.\n\nLet is_omega_cocont_listFunctor : is_omega_cocont listFunctor := pr2 L_A.\n\nLemma listFunctor_Initial :\n  Initial (category_FunctorAlg listFunctor).\nProof.\napply (colimAlgInitial InitialHSET is_omega_cocont_listFunctor (ColimCoconeHSET _ _)).\nDefined.\n\n(** The type of lists of A's *)\nDefinition μL_A : HSET :=\n  alg_carrier _ (InitialObject listFunctor_Initial).\n\nDefinition List : UU := pr1 μL_A.\n\nLet List_mor : HSET⟦listFunctor μL_A,μL_A⟧ :=\n  alg_map _ (InitialObject listFunctor_Initial).\n\nLet List_alg : algebra_ob listFunctor :=\n  InitialObject listFunctor_Initial.\n\nDefinition nil_map : HSET⟦unitHSET,μL_A⟧ :=\n  BinCoproductIn1 (BinCoproductsHSET _ _) · List_mor.\n\nDefinition nil : List := nil_map tt.\n\nDefinition cons_map : HSET⟦(A × μL_A)%set,μL_A⟧ :=\n  BinCoproductIn2 (BinCoproductsHSET _ _) · List_mor.\n\nDefinition cons : pr1 A → List -> List := λ a l, cons_map (a,,l).\n\n(** Get recursion/iteration scheme:\n<<\n     x : X           f : A × X -> X\n  ------------------------------------\n       foldr x f : List A -> X\n>>\n*)\nDefinition make_listAlgebra (X : HSET) (x : pr1 X)\n  (f : HSET⟦(A × X)%set,X⟧) : algebra_ob listFunctor.\nProof.\nset (x' := λ (_ : unit), x).\napply (tpair _ X (sumofmaps x' f) : algebra_ob listFunctor).\nDefined.\n\nDefinition foldr_map (X : HSET) (x : pr1 X) (f : HSET⟦(A × X)%set,X⟧) :\n  algebra_mor _ List_alg (make_listAlgebra X x f).\nProof.\napply (InitialArrow listFunctor_Initial (make_listAlgebra X x f)).\nDefined.\n\n(** Iteration/fold *)\nDefinition foldr (X : HSET) (x : pr1 X)\n  (f : pr1 A → pr1 X → pr1 X) : List → pr1 X.\nProof.\napply (foldr_map _ x (λ a, f (pr1 a) (pr2 a))).\nDefined.\n\n(* Maybe quantify over \"λ _ : unit, x\" instead of nil? *)\nLemma foldr_nil (X : hSet) (x : X) (f : pr1 A → X -> X) : foldr X x f nil = x.\nProof.\nassert (F := maponpaths (λ x, BinCoproductIn1 (BinCoproductsHSET _ _) · x)\n                        (algebra_mor_commutes _ _ _ (foldr_map X x (λ a, f (pr1 a) (pr2 a))))).\napply (toforallpaths _ _ _ F tt).\nQed.\n\nLemma foldr_cons (X : hSet) (x : X) (f : pr1 A → X -> X)\n                 (a : pr1 A) (l : List) :\n  foldr X x f (cons a l) = f a (foldr X x f l).\nProof.\nassert (F := maponpaths (λ x, BinCoproductIn2 (BinCoproductsHSET _ _) · x)\n                        (algebra_mor_commutes _ _ _ (foldr_map X x (λ a, f (pr1 a) (pr2 a))))).\nassert (Fal := toforallpaths _ _ _ F (a,,l)).\nclear F.\nunfold compose in Fal.\nsimpl in Fal.\napply Fal.\nOpaque foldr_map.\nQed. (* This Qed is slow unless foldr_map is Opaque *)\nTransparent foldr_map.\n\n(** The induction principle for lists defined using foldr *)\nSection list_induction.\n\nVariables (P : List -> UU) (PhSet : ∏ l, isaset (P l)).\nVariables (P0 : P nil)\n          (Pc : ∏ a l, P l -> P (cons a l)).\n\nLet P' : UU := ∑ l, P l.\nLet P0' : P' := (nil,, P0).\nLet Pc' : pr1 A  → P' -> P' :=\n  λ (a : pr1 A) (p : P'), cons a (pr1 p),,Pc a (pr1 p) (pr2 p).\n\nDefinition P'HSET : HSET.\nProof.\napply (tpair _ P').\nabstract (apply (isofhleveltotal2 2); [ apply setproperty | intro x; apply PhSet ]).\nDefined.\n\n(** This line is crucial for isalghom_pr1foldr to typecheck *)\nOpaque is_omega_cocont_listFunctor.\n\nLemma isalghom_pr1foldr :\n  is_algebra_mor listFunctor List_alg List_alg (λ l, pr1 (foldr P'HSET P0' Pc' l)).\nProof.\napply (BinCoproductArrow_eq_cor _ BinCoproductsHSET).\n- apply funextfun; intro x; induction x.\n  apply (maponpaths pr1 (foldr_nil P'HSET P0' Pc')).\n- apply funextfun; intro x; destruct x as [a l].\n  apply (maponpaths pr1 (foldr_cons P'HSET P0' Pc' a l)).\nQed.\n\n(* Transparent is_omega_cocont_listFunctor. *)\n\nDefinition pr1foldr_algmor : algebra_mor listFunctor List_alg List_alg.\nProof.\n  use tpair.\n  - exact (λ l, pr1 (foldr P'HSET P0' Pc' l)).\n  - hnf. apply isalghom_pr1foldr.\nDefined.\n\nTransparent is_omega_cocont_listFunctor.\n\nLemma pr1foldr_algmor_identity : identity List_alg = pr1foldr_algmor.\nProof.\nnow rewrite (@InitialEndo_is_identity _ listFunctor_Initial pr1foldr_algmor).\nQed.\n\n(** The induction principle for lists *)\nLemma listInd l : P l.\nProof.\n  assert (H : pr1 (foldr P'HSET P0' Pc' l) = l).\n  apply (toforallpaths _ _ _ (maponpaths pr1 (!pr1foldr_algmor_identity)) l).\nrewrite <- H.\napply (pr2 (foldr P'HSET P0' Pc' l)).\nDefined.\n\nEnd list_induction.\n\nLemma listIndhProp (P : List → hProp) :\n  P nil → (∏ a l, P l → P (cons a l)) → ∏ l, P l.\nProof.\nintros Pnil Pcons.\napply listInd; try assumption.\nintro l; apply isasetaprop, propproperty.\nDefined.\n\n(* This variation is easier to use *)\nLemma listIndProp (P : List → UU) (HP : ∏ l, isaprop (P l)) :\n  P nil → (∏ a l, P l → P (cons a l)) → ∏ l, P l.\nProof.\nintros Pnil Pcons.\napply listInd; try assumption.\nintro l; apply isasetaprop, HP.\nDefined.\n\nLocal Open Scope nat_scope.\n\nLocal Notation \"'A'\" := (pr1 A).\n\nDefinition length : List -> nat := foldr natHSET 0 (λ _ (n : nat), 1 + n).\n\nDefinition map (f : A -> A) : List -> List :=\n  foldr _ nil (λ (x : A) (xs : List), cons (f x) xs).\n\nLemma length_map (f : A -> A) : ∏ xs, length (map f xs) = length xs.\nProof.\napply listIndProp.\n- intros l; apply isasetnat.\n- now unfold map; rewrite foldr_nil.\n- simpl; unfold map, length; simpl; intros a l Hl.\n  now rewrite !foldr_cons, <- Hl.\nQed.\n\nDefinition concatenate : List -> List -> List :=\n  λ l l', foldr _ l cons l'.\n\nEnd lists.\n\n(** Some examples of computations with lists over nat *)\nSection nat_examples.\n\nDefinition cons_nat a l : List natHSET := cons natHSET a l.\n\nLocal Infix \"::\" := cons_nat.\nLocal Notation \"[]\" := (nil natHSET) (at level 0, format \"[]\").\n\nDefinition testlist : List natHSET := 5 :: 2 :: [].\n\nDefinition testlistS : List natHSET :=\n  map natHSET S testlist.\n\nDefinition sum : List natHSET -> nat :=\n  foldr natHSET natHSET 0 (λ x y, x + y).\n\n(* None of these compute *)\n(* Eval cbn in length _ (nil natHSET). *)\n(* Eval vm_compute in length _ testlist. *)\n(* Eval vm_compute in length _ testlistS. *)\n(* Eval vm_compute in sum testlist. *)\n(* Eval vm_compute in sum testlistS. *)\n\n(* All of these compute *)\nGoal length _ (nil natHSET) = 0. reflexivity. Qed.\nGoal length _ testlist = length _ testlistS. reflexivity. Qed.\nGoal sum testlistS = sum testlist + length _ testlist. lazy. reflexivity. Qed.\nGoal length _ (concatenate _ testlist testlistS) = length _ testlist + length _ testlistS. reflexivity. Qed.\nGoal sum (concatenate _ testlist testlistS) = sum testlistS + sum testlist. reflexivity. Qed.\n\nGoal (∏ l, length _ (2 :: l) = S (length _ l)).\nsimpl.\nintro l.\ntry apply idpath. (* this doesn't work *)\nunfold length, cons_nat.\nrewrite foldr_cons. cbn.\napply idpath.\nAbort.\n\n(* some experiments: *)\n\n(* Definition const {A B : UU} : A -> B -> A := λ x _, x. *)\n\n(* Eval compute in const 0 (nil natHSET). *)\n\n(* Axiom const' : ∏ {A B : UU}, A -> B -> A. *)\n\n(* Eval compute in const' 0 1. *)\n(* Eval compute in const' 0 (nil natHSET). *)\n\n(* Time Eval vm_compute in nil natHSET.  (* This crashes my computer by using up all memory *) *)\n\nEnd nat_examples.\n\n(** * Equivalence with lists as iterated products *)\nSection list.\n\nLemma isaset_list (A : HSET) : isaset (list (pr1 A)).\nProof.\napply isaset_total2; [apply isasetnat|].\nintro n; induction n as [|n IHn]; simpl; [apply isasetunit|].\napply isaset_dirprod; [ apply setproperty | apply IHn ].\nQed.\n\nDefinition to_List (A : HSET) : list (pr1 A) -> List A.\nProof.\nintros l.\ndestruct l as [n l].\ninduction n as [|n IHn].\n+ exact (nil A).\n+ apply (cons _ (pr1 l) (IHn (pr2 l))).\nDefined.\n\nDefinition to_list (A : HSET) : List A -> list (pr1 A).\nProof.\napply (foldr A (list (pr1 A),,isaset_list A)).\n* apply (0,,tt).\n* intros a L; simpl in *.\n  apply (tpair _ (S (pr1 L)) (a,,pr2 L)).\nDefined.\n\nLemma to_listK (A : HSET) : ∏ x : list (pr1 A), to_list A (to_List A x) = x.\nProof.\nintro l; destruct l as [n l]; unfold to_list, to_List.\ninduction n as [|n IHn]; simpl.\n- rewrite foldr_nil.\n  now destruct l.\n- rewrite foldr_cons; simpl.\n  now rewrite IHn.\nQed.\n\nLemma to_ListK (A : HSET) : ∏ y : List A, to_List A (to_list A y) = y.\nProof.\napply listIndProp.\n* intro l; apply setproperty.\n* now unfold to_list; rewrite foldr_nil.\n* unfold to_list, to_List; intros a l IH.\n  rewrite foldr_cons; simpl.\n  apply maponpaths, pathsinv0.\n  eapply pathscomp0; [eapply pathsinv0, IH|]; simpl.\n  now destruct foldr.\nQed.\n\n(** Equivalence between list and List for A a set *)\nLemma weq_list (A : HSET) : list (pr1 A) ≃ List A.\nProof.\nuse tpair.\n- apply to_List.\n- use isweq_iso.\n  + apply to_list.\n  + apply to_listK.\n  + apply to_ListK.\nDefined.\n\n(* This doesn't compute: *)\n(* Eval compute in (to_list _ testlist). *)\n\n(* This does compute: *)\nGoal to_list _ testlist = 2,,5,,2,,tt. reflexivity. Qed.\n\nEnd list.\n\n(** Alternative version of lists using a more direct proof of omega-cocontinuity. This definition\n    has slightly better computational properties. *)\nModule AltList.\n\n(* The functor \"x * F\" is omega_cocont. This is only proved for set at the\n   moment as it needs that the category is cartesian closed *)\nSection constprod_functor.\n\nVariables (x : hSet).\n\nDefinition constprod_functor : functor HSET HSET :=\n  BinProduct_of_functors HSET HSET BinProductsHSET (constant_functor HSET HSET x)\n                                         (functor_identity HSET).\n\nLemma omega_cocontConstProdFunctor : is_omega_cocont constprod_functor.\nProof.\nintros hF c L ccL HcL cc.\nuse tpair.\n- transparent assert (HX : (cocone hF (funset x HcL))).\n  {  use make_cocone.\n    * simpl; intro n; apply flip, (curry (Z := λ _,_)), (pr1 cc).\n    * abstract (destruct cc as [f hf]; simpl; intros m n e;\n                rewrite <- (hf m n e); destruct e; simpl;\n                repeat (apply funextfun; intro); apply idpath).\n  }\n  use tpair.\n  + simpl; apply uncurry, flip.\n    apply (colimArrow (make_ColimCocone _ _ _ ccL) (funset x HcL)).\n    apply HX.\n  + cbn.\n    destruct cc as [f hf]; simpl; intro n.\n    apply funextfun; intro p.\n    change p with (pr1 p,,pr2 p).\n    assert (XR := colimArrowCommutes (make_ColimCocone hF c L ccL) _ HX n).\n    unfold flip, curry, colimIn in *; simpl in *.\n    now rewrite <- (toforallpaths _ _ _ (toforallpaths _ _ _ XR (pr2 p)) (pr1 p)).\n- abstract (\n  intro p; unfold uncurry; simpl; apply subtypePath; simpl;\n  [ intro g; apply impred; intro t;\n    use (let ff : HSET ⟦(x × dob hF t)%set,HcL⟧ := _ in _);\n    [ simpl; apply (pr1 cc)\n    | apply (@has_homsets_HSET _ HcL _ ff) ]\n  | destruct p as [t p]; simpl;\n    apply funextfun; intro xc; destruct xc as [x' c']; simpl;\n    use (let g : HSET⟦colim (make_ColimCocone hF c L ccL),\n                                funset x HcL⟧ := _ in _);\n    [ simpl; apply flip, (curry (Z := λ _,_)), t\n    | rewrite <- (colimArrowUnique _ _ _ g); [apply idpath | ];\n      destruct cc as [f hf]; unfold is_cocone_mor in p; simpl in *;\n      now intro n; simpl; rewrite <- (p n) ]\n  ]).\nDefined.\n\nEnd constprod_functor.\n\n(* The functor \"x + F\" is omega_cocont.\n   Assumes that the category has coproducts *)\nSection constcoprod_functor.\n\nVariables (C : category) (x : C) (PC : BinCoproducts C).\n\nDefinition constcoprod_functor : functor C C :=\n  BinCoproduct_of_functors C C PC (constant_functor C C x) (functor_identity C).\n\nLemma omega_cocontConstCoprodFunctor : is_omega_cocont constcoprod_functor.\nProof.\nintros hF c L ccL HcL cc.\nuse tpair.\n- use tpair.\n  + eapply BinCoproductArrow.\n    * exact (BinCoproductIn1 (PC x (dob hF 0)) · pr1 cc 0).\n    * use (let ccHcL : cocone hF HcL := _ in _).\n      { use make_cocone.\n        - intros n; exact (BinCoproductIn2 (PC x (dob hF n)) · pr1 cc n).\n        -   abstract (\n            intros m n e; destruct e; simpl;\n            destruct cc as [f hf]; simpl in *;\n            rewrite <- (hf m _ (idpath _)), !assoc; apply cancel_postcomposition;\n            unfold constcoprod_functor; cbn;\n            apply pathsinv0; etrans; [apply BinCoproductOfArrowsIn2|]; apply idpath). }\n      apply (pr1 (pr1 (ccL HcL ccHcL))).\n  + abstract (\n    destruct cc as [f hf]; simpl in *;\n    simpl; intro n; unfold constcoprod_functor; cbn;\n    etrans; [apply precompWithBinCoproductArrow |]; apply pathsinv0, BinCoproductArrowUnique; red in hf;\n    [ rewrite id_left; induction n as [|n IHn]; [apply idpath|];\n      etrans; [| apply IHn]; unfold constant_functor; simpl; rewrite <- (hf n _ (idpath _)), assoc;\n      unfold constant_functor; simpl; apply pathsinv0;\n      etrans; [apply cancel_postcomposition; apply BinCoproductOfArrowsIn1 |]; now rewrite id_left\n    | rewrite <- (hf n _ (idpath _)); destruct ccL as [t p]; destruct t as [t p0]; simpl in *;\n      rewrite p0; simpl; now apply maponpaths, hf]).\n- abstract (\n      destruct cc as [f hf]; simpl in *;\n      intro t; apply subtypePath; simpl;\n      [  intro g; apply impred; intro; apply C\n       | destruct t as [t p]; destruct ccL as [t0 p0]; unfold is_cocone_mor in *;\n         unfold constcoprod_functor; destruct t0 as [t0 p1]; simpl;\n         apply BinCoproductArrowUnique;\n         [  unfold coconeIn in p; simpl in p;\n            rewrite <- (p 0), assoc;\n            apply cancel_postcomposition; apply pathsinv0; etrans; [apply  BinCoproductOfArrowsIn1 |]; apply id_left\n         |  use (let temp : ∑ x0 : C ⟦ c, HcL ⟧, ∏ v : nat,\n                                coconeIn L v · x0 = BinCoproductIn2 (PC x (dob hF v)) · f v := _ in _);\n            [ apply (tpair _ (BinCoproductIn2 (PC x c) · t));\n              intro n; unfold coconeIn in p; simpl in p; rewrite <- (p n), !assoc;\n              apply cancel_postcomposition; apply pathsinv0; etrans; [apply  BinCoproductOfArrowsIn2 |];\n              apply idpath|];\n            apply (maponpaths pr1 (p0 temp))]]).\nDefined.\n\nEnd constcoprod_functor.\n\n(* Lists as the colimit of a chain given by the list functor: F(X) = 1 + A * X *)\nSection lists.\n\nVariable A : HSET.\n\n(* F(X) = A * X *)\nDefinition stream : functor HSET HSET := constprod_functor1 BinProductsHSET A.\n\n(* F(X) = 1 + (A * X) *)\nDefinition listFunctor : functor HSET HSET :=\n  functor_composite stream (constcoprod_functor _ unitHSET BinCoproductsHSET).\n\nLemma omega_cocont_listFunctor : is_omega_cocont listFunctor.\nProof.\napply (is_omega_cocont_functor_composite).\n- apply omega_cocontConstProdFunctor.\n(* If I use this length doesn't compute with vm_compute... *)\n(* - apply (omega_cocont_constprod_functor1 _ _ has_homsets_HSET Exponentials_HSET). *)\n- apply (omega_cocontConstCoprodFunctor _).\nDefined.\n\nLemma listFunctor_Initial :\n  Initial (category_FunctorAlg listFunctor).\nProof.\napply (colimAlgInitial InitialHSET omega_cocont_listFunctor (ColimCoconeHSET _ _)).\nDefined.\n\nDefinition List : HSET :=\n  alg_carrier _ (InitialObject listFunctor_Initial).\n\nLet List_mor : HSET⟦listFunctor List,List⟧ :=\n  alg_map _ (InitialObject listFunctor_Initial).\n\nLet List_alg : algebra_ob listFunctor :=\n  InitialObject listFunctor_Initial.\n\nDefinition nil_map : HSET⟦unitHSET,List⟧.\nProof.\nsimpl; intro x.\nuse List_mor.\napply inl.\nexact x.\nDefined.\n\nDefinition nil : pr1 List := nil_map tt.\n\nDefinition cons_map : HSET⟦(A × List)%set,List⟧.\nProof.\nintros xs.\nuse List_mor.\nexact (inr xs).\nDefined.\n\nDefinition cons : pr1 A × pr1 List -> pr1 List := cons_map.\n\n(* Get recursion/iteration scheme: *)\n\n(*    x : X           f : A × X -> X *)\n(* ------------------------------------ *)\n(*       foldr x f : List A -> X *)\n\nDefinition make_listAlgebra (X : HSET) (x : pr1 X)\n  (f : HSET⟦(A × X)%set,X⟧) : algebra_ob listFunctor.\nProof.\nset (x' := λ (_ : unit), x).\napply (tpair _ X (sumofmaps x' f) : algebra_ob listFunctor).\nDefined.\n\nDefinition foldr_map (X : HSET) (x : pr1 X) (f : HSET⟦(A × X)%set,X⟧) :\n  algebra_mor _ List_alg (make_listAlgebra X x f).\nProof.\napply (InitialArrow listFunctor_Initial (make_listAlgebra X x f)).\nDefined.\n\nDefinition foldr (X : HSET) (x : pr1 X)\n  (f : pr1 A × pr1 X -> pr1 X) : pr1 List -> pr1 X.\nProof.\napply (foldr_map _ x f).\nDefined.\n\n(* Maybe quantify over \"λ _ : unit, x\" instead of nil? *)\nLemma foldr_nil (X : hSet) (x : X) (f : pr1 A × X -> X) : foldr X x f nil = x.\nProof.\nassert (F := maponpaths (λ x, BinCoproductIn1 (BinCoproductsHSET _ _) · x)\n                        (algebra_mor_commutes _ _ _ (foldr_map X x f))).\napply (toforallpaths _ _ _ F tt).\nQed.\n\nLemma foldr_cons (X : hSet) (x : X) (f : pr1 A × X -> X)\n                 (a : pr1 A) (l : pr1 List) :\n  foldr X x f (cons (a,,l)) = f (a,,foldr X x f l).\nProof.\nassert (F := maponpaths (λ x, BinCoproductIn2 (BinCoproductsHSET _ _) · x)\n                        (algebra_mor_commutes _ _ _ (foldr_map X x f))).\napply (toforallpaths _ _ _ F (a,,l)).\nQed.\n\n(* This defines the induction principle for lists using foldr *)\nSection list_induction.\n\nVariables (P : pr1 List -> UU) (PhSet : ∏ l, isaset (P l)).\nVariables (P0 : P nil)\n          (Pc : ∏ (a : pr1 A) (l : pr1 List), P l -> P (cons (a,,l))).\n\nLet P' : UU := ∑ l, P l.\nLet P0' : P' := (nil,, P0).\nLet Pc' : pr1 A × P' -> P' :=\n  λ ap : pr1 A × P', cons (pr1 ap,, pr1 (pr2 ap)),,Pc (pr1 ap) (pr1 (pr2 ap)) (pr2 (pr2 ap)).\n\nDefinition P'HSET : HSET.\nProof.\napply (tpair _ P').\nabstract (apply (isofhleveltotal2 2); [ apply setproperty | intro x; apply PhSet ]).\nDefined.\n\nLemma isalghom_pr1foldr :\n  is_algebra_mor _ List_alg List_alg (λ l, pr1 (foldr P'HSET P0' Pc' l)).\nProof.\napply BinCoproductArrow_eq_cor.\n- apply funextfun; intro x; destruct x; apply idpath.\n- apply funextfun; intro x; destruct x as [a l].\n  apply (maponpaths pr1 (foldr_cons P'HSET P0' Pc' a l)).\nQed.\n\nDefinition pr1foldr_algmor : algebra_mor _ List_alg List_alg :=\n  tpair _ _ isalghom_pr1foldr.\n\nLemma pr1foldr_algmor_identity : identity _ = pr1foldr_algmor.\nProof.\nnow rewrite (@InitialEndo_is_identity _ listFunctor_Initial pr1foldr_algmor).\nQed.\n\nLemma listInd l : P l.\nProof.\nassert (H : pr1 (foldr P'HSET P0' Pc' l) = l).\n  apply (toforallpaths _ _ _ (maponpaths pr1 (!pr1foldr_algmor_identity)) l).\nrewrite <- H.\napply (pr2 (foldr P'HSET P0' Pc' l)).\nDefined.\n\nEnd list_induction.\n\nLemma listIndProp (P : pr1 List -> UU) (HP : ∏ l, isaprop (P l)) :\n  P nil -> (∏ a l, P l → P (cons (a,, l))) -> ∏ l, P l.\nProof.\nintros Pnil Pcons.\napply listInd; try assumption.\nintro l; apply isasetaprop, HP.\nDefined.\n\nDefinition natHSET : HSET.\nProof.\nexists nat.\nabstract (apply isasetnat).\nDefined.\n\nDefinition length : pr1 List -> nat :=\n  foldr natHSET 0 (λ x, S (pr2 x)).\n\nDefinition map (f : pr1 A -> pr1 A) : pr1 List -> pr1 List :=\n  foldr _ nil (λ xxs : pr1 A × pr1 List, cons (f (pr1 xxs),, pr2 xxs)).\n\nLemma length_map (f : pr1 A -> pr1 A) : ∏ xs, length (map f xs) = length xs.\nProof.\napply listIndProp.\n- intros l; apply isasetnat.\n- apply idpath.\n- simpl; unfold map, length; simpl; intros a l Hl.\n  simpl.\n  now rewrite !foldr_cons, <- Hl.\nQed.\n\nEnd lists.\n\n(* Some examples of computations with lists over nat *)\nSection nat_examples.\n\nDefinition cons_nat a l : pr1 (List natHSET) := cons natHSET (a,,l).\n\nInfix \"::\" := cons_nat.\nNotation \"[]\" := (nil natHSET) (at level 0, format \"[]\").\n\nDefinition testlist : pr1 (List natHSET) := 5 :: 2 :: [].\n\nDefinition testlistS : pr1 (List natHSET) :=\n  map natHSET S testlist.\n\nDefinition sum : pr1 (List natHSET) -> nat :=\n  foldr natHSET natHSET 0 (λ xy, pr1 xy + pr2 xy).\n\n(* All of these work *)\n(* Eval cbn in length _ (nil natHSET). *)\n(* Eval vm_compute in length _ testlist. *)\n(* Eval vm_compute in length _ testlistS. *)\n(* Eval vm_compute in sum testlist. *)\n(* Eval vm_compute in sum testlistS. *)\n\n(* Goal length _ testlist = 2. *)\n(* vm_compute. *)\n(* Restart. *)\n(* cbn. *)\n(* Restart. *)\n(* compute.  (* does not work when foldr is opaque with \"Opaque foldr.\" *) *)\n(* Restart. *)\n(* cbv.   (* does not work when foldr is opaque with \"Opaque foldr.\" *) *)\n(* Restart. *)\n(* native_compute. *)\n(* Abort. *)\n\nGoal (∏ l, length _ (2 :: l) = S (length _ l)).\nsimpl.\nintro l.\ntry apply idpath. (* this doesn't work *)\nunfold length, cons_nat.\nrewrite foldr_cons. cbn.\napply idpath.\nAbort.\n\nEnd nat_examples.\nEnd AltList.\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/Inductives/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318195, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6835268303960522}}
{"text": "Parameter A : Type.\nParameter P : A -> Prop.\nParameter Q : A -> Prop.\n\nDefinition spec__exist := exists a, P a /\\ Q a.\nDefinition spec__impl  := forall a, P a -> Q a.\n\nSection Exist_Impl.\n\n  Hypothesis P_functional :\n    forall a1 a2, P a1 -> P a2 -> a1 = a2.\n\n  Goal spec__exist -> spec__impl.\n  Proof.\n    cbv.\n    intros.\n    destruct H as [a' H]; destruct H as [H1 H2].\n    rewrite (P_functional a a') by assumption.\n    assumption.\n  Qed.\n\nEnd Exist_Impl.\n\n\nSection Impl_Exist.\n\n  Hypothesis P_total :\n    exists a, P a.\n\n  Goal spec__impl -> spec__exist.\n  Proof.\n    cbv.\n    intros.\n    destruct P_total as [a H1].\n    specialize (H a). exists a.\n    split.\n    - assumption.\n    - apply H.\n      assumption.\n  Qed.\n\nEnd Impl_Exist.\n", "meta": {"author": "asosyuk", "repo": "asn1verification", "sha": "55395d63c2dcd512a28d9cd42d788e12f91e7641", "save_path": "github-repos/coq/asosyuk-asn1verification", "path": "github-repos/coq/asosyuk-asn1verification/asn1verification-55395d63c2dcd512a28d9cd42d788e12f91e7641/doc/tutorial/exist_vs_impl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6835268190657534}}
{"text": "Require Import Reals.\nRequire Import Interval.Interval_tactic.\nRequire Import Coquelicot.Coquelicot.\n\nOpen Scope R_scope.\n\n(* The following are from Definition 12 \n   from section 2 of the paper. *)\n\nDefinition asinh x := ln (x + sqrt (x^2 + 1)).\n\nDefinition S := (1/(2 * sqrt 2)) / asinh (1/(2 * sqrt 2)).\n\nDefinition K := 2 * (sqrt 3) / S.\n\nDefinition h z  := (1 + z^2) / (z * (1 - z^2)).\n\nDefinition gU z := (1 + z^2) / (2 * (z ^ 3)).\n\nDefinition gL z := (1 + z^2)^2 / (2 * z^3 * (3 - z^2)).\n\nDefinition H z := (h z) / K.\n\nDefinition GU z := (gU z) / K.\n\nDefinition GL z := (gL z) / K.\n\nNotation \"x ^ y\" := (powerRZ x y).\n\n(* At this point we just copy in things from Maxima,\n   using Maxima's grind command.\n*)\nDefinition FU z := -(z^4+6*z^2+4*z+1)/((z+1)*(z^2+1)^2).\nDefinition FL z := -(z^6+7*z^4+12*z^3-9*z^2-4*z+1)/((z+1)*(z^2+1)*(z^2-2*z-1)*(z^2+2*z-1)).\n\nDefinition PHU z := RInt FU 1 z.\nDefinition fU z := K * (1 - z) * exp (- PHU z).\n\nDefinition PHL z := RInt FL 1 z.\nDefinition fL z := K * (1 - z) * exp (- PHL z).\n\nDefinition LB_igd w :=\n  2^(7/2)*sqrt(3)*asinh(1/2^(3/2))*w^2*(w^2-3)*(w^4+4*w^2-1)\n                                                 /((w^2+1)^2*(w^2-2*w-1)*(w^2+2*w-1)).\nDefinition LB z := (1/4) * RInt LB_igd z 1.\n\nDefinition UB_igd w :=\n  2^(7/2)*sqrt(3)*asinh(1/2^(3/2))*w^2*(w^4+4*w^2-1)/(w^2+1)^3.\nDefinition UB z := (1/4) * RInt UB_igd z 1.\n\nLemma fU_concavity:\n  forall z, 811/1000 <= z <= 1 ->\n            -2*(z^8+6*z^6+32*z^4+10*z^2-1)/((z+1)*(z^2+1)^4) < 0.\nProof.\n  intros. interval with (i_bisect_diff z).\nQed.\n\nLemma fL_concavity:\n  forall z, 811/1000 <= z <= 1 -> \n  -2*(z^12-4*z^10+17*z^8-248*z^6+203*z^4-36*z^2+3)\n       /((z+1)*(z^2+1)^2*(z^2-2*z-1)^2*(z^2+2*z-1)^2) > 0.\nProof.\n  intros. interval with (i_bisect_diff z).\nQed.\n\nLemma LB_concavity:\n  forall z,\n    811/1000 <= z <= 1 ->\n    (5*z^8-6*z^6+88*z^4-26*z^2+3) > 0.\nProof.\n  intros. interval with (i_bisect_diff z).\nQed.\n\nLemma UB_concavity:\n  forall z,\n    811/1000 <= z <= 1 ->\n    z^4-10*z^2+1 < 0.\nProof.\n  intros. interval with (i_bisect_diff z).\nQed.\n\n(* The above lemmata prove something slightly stronger\n   than Lemma 25, namely that the consequents of Lemma\n   25 hold when z is in [0.811,1]. We now prove xi > 0.811. *)\n\n(* The following long expression is grind(-factor(expand(FL + 1/(1-z)))). \n   It has the same sign as the derivative of fL. *)\n\nLemma fL_decreasing:\n  forall z,\n    811/1000 <= z <= 812/1000 ->\n    2*z*(z^2-3)*(z^4+4*z^2-1)/((z-1)*(z+1)*(z^2+1)*(z^2-2*z-1)*(z^2+2*z-1)) < 0.\nProof.\n  intros. interval with (i_bisect_diff z).\nQed.\n\n(* Since fL is decreasing on [0.811, 0.812], fL - k has at most one root there\n   for any real k. fL - fU(sqrt(1/3)) has such a root by the intermediate value theorem.\n   Since fL is differentiable, one could prove this constructively without an appeal to IVT.\n   We will not do so now. *)\n\nLtac unfold_defs := unfold fU; unfold PHU; unfold FU;\n                    unfold fL; unfold PHL; unfold FL;\n                    unfold UB; unfold UB_igd;\n                    unfold LB; unfold LB_igd;\n                    unfold K; unfold S; unfold asinh.\n\nLemma fU_xi_bounds:\n  686533 / 1000000 < fU(sqrt(1/3)) < 686537 / 1000000.\nProof.\n  split; unfold_defs; interval.\nQed.\n\nLemma fL_xi_bounds:\n  fL(8112/10000) > 686537/1000000 /\\ fL(8113/10000) < 686533/1000000.\nProof.\n  split; unfold_defs; interval.\nQed.\n\n(* Therefore, by the intermediate value theorem,\n   there is a unique point xi between 0.8112 and\n   0.8113 such that fL(xi) = fU(sqrt(1/3)). *)\n\n(* Now we get bounds on DV. We want a lemma\n   of the form DV < TH -> fL(BL(DV)) < fU(sqrt(1/3)).\n   \n   We begin by showing it makes sense to consider this,\n   since fU(sqrt(1/3)) is in the domain of invertibility of fL\n   near 1 (viz., [sqrt(sqrt(5)-2), infty]).\n*)\n\nLemma fU_sqrt_DV_bounds:\n  fU(sqrt(1/3)) > sqrt(sqrt(5)-2).\nProof.\n  unfold_defs. interval.\nQed.\n\n(* fL(BL(DV)) < fU(sqrt(1/3)) is implied by\n   fL(BL(DV)) < 0.686533, since 0.686533 < fU(sqrt(1/3)).\n   \n   We show next that fL(x) < 0.686533 is implied by\n   x > 0.81127. We can do this just by showing fL(0.81127) < 0.686533,\n   since fL is decreasing on [sqrt(sqrt(5)-2), infty).\n*)\nLemma fL_DV_bounds:\n  fL(81127/100000) < 686533/1000000.\nProof.\n  unfold_defs; interval.\nQed.\n\n(* Finally we want some way to imply BL(DV) > 0.81127, which is\n   to say (since LB is decreasing on (sqrt(sqrt(5)-2), 1))\n   DV < LB(0.81127). If TH < LB(0.81127) we can imply this by\n   DV < TH. It suffices to pick TH = 0.15326.\n *)\n\nLemma DV_bounds:\n  15326/100000 < LB(81127/100000).\nProof.\n  unfold_defs; interval.\nQed.\n\n(* And finally, now for the bounds on alpha, beta, and gamma.\n   \n   For the bound on alpha, we rewrite PHU(xi) - PHL(xi) as\n   a single integral, rewriting the integrand. By grinding from\n   Maxima, we get that this integrand is as given below. After\n   loading pams.mac, the command that gets us the definition below is\n\n   grind(factor(expand(FU - FL)));\n\n *)\n\nDefinition alpha_igd z := 8*z*(z^4+4*z^2-1)/((z^2+1)^2*(z^2-2*z-1)*(z^2+2*z-1)).\n\n(* We can't define alpha, since we haven't defined xi yet.\n   So instead we will just derive an upper bound on alpha. *)\n\nLemma alpha_igd_ineq : forall z, 81127/100000 <= z <= 1 -> (alpha_igd z) < 0.\nProof.\n  intros. unfold alpha_igd.\n  interval with (i_bisect_diff z).\nQed.\n\n(* Let A(z) be the integral of alpha_igd from 1 to z. Then\n   A'(z) = alpha_igd(z). So A is decreasing (on [sqrt(1/3),1]).\n   Hence A(xi-eps) is an upper bound on A(xi) for small eps > 0.\n   Likewise 1-xi+eps is an upper bound on 1-xi for eps > 0.\n   We pick eps = xi - 0.81127. Also, since TH < Theta, 1/TH > 1/Theta.\n *)\n\nCheck PI.\n\nLemma alpha_bound :\n  (K * (1 - 81127/100000)/(2*PI*15326/100000))\n  * exp (RInt alpha_igd 1 (81127/100000)) < 97/100.\nProof.\n  unfold alpha_igd. unfold_defs.\n  interval.\nQed.\n\n(* In fact, beta is (2*pi)^2*Theta/fL(xi). So to get an\n   upper bound on beta, we get an upper bound on Theta\n   and on fL(xi). We begin with an upper bound on Theta.\n   Theta is LB(xi). Since LB is decreasing, LB(xi-eps)\n   is greater than LB(xi) for eps > 0 small enough.\n   So an upper bound on LB(0.8112) is an upper bound \n   on Theta.\n *)\n\nLemma theta_upper_bound :\n  LB(8112/10000) < 1562/10000.\nProof.\n  unfold_defs. interval.\nQed.\n\n(* Next an upper bound on 1/fL(xi). Since \n   fL is decreasing, 1/fL is increasing.\n   So 1/fL(xi) < 1/fL(xi+eps).\n *)\n\nLemma fL_inv_upper_bound :\n  1 / (fL (8113/10000)) < 1457/100.\nProof.\n  unfold_defs. interval.\nQed.\n\nLemma beta_bound :\n  (2*PI)^2 * (1562/10000) * (1457/1000) > 895/100.\nProof.\n  interval.\nQed.\n\n(* Now for gamma. gamma is pi^2*e^(PHU(xi)).\n   PHU' is FU. Now, FU is negative on the \n   given interval.\n *)\n\nLemma FU_neg:\n  forall z, 811/1000 <= z <= 1 ->\n            FU z < 0.\nProof.\n  intros. unfold_defs. interval with (i_bisect_diff z).\nQed.\n\n(* Therefore, PHU is a decreasing function there.\n   So exp o PHU is likewise a decreasing function.\n   So exp(PHU(xi-eps)) > exp(PHU(xi)) for eps > 0.\n *)\n\nLemma gamma_bound :\n  PI^2 * exp(PHU(8112/10000)) < 134/10.\nProof.\n  unfold_defs. interval.\nQed.\n\n(* Finally for the slope bound. fU is decreasing,\n   so 1/sqrt(fU(x)) is an increasing function of\n   x; so 1/sqrt(fU(BU(TH))) < 1/sqrt(fU(BU(TH)+eps))\n   for eps > 0 small. Hence if BU(TH) < BB then\n   an upper bound on 1/sqrt(fU(BB)) will suffice.\n\n   Now BU(TH) < BB when TH > UB(BB). So now we need\n   a lower bound on Theta.\n *)\n\nLemma theta_lower_bound :\n  LB(8113/10000) > 153/1000.\nProof.\n  unfold_defs. interval.\nQed.\n\nLemma BB_bound :\n  153/1000 > UB(758/1000).\nProof.\n  unfold_defs. interval.\nQed.\n\n(* So BB = 0.758 suffices. Thus finally we arrive\n   at the following bound.\n *)\n\nLemma slope_bound :\n  85/10 > 2*PI/sqrt(fU(758/1000)).\nProof.\n  unfold_defs. interval.\nQed.\n", "meta": {"author": "bobbycyiii", "repo": "cheeky", "sha": "7501122677d8de97e2f7e317133c574cbfd17865", "save_path": "github-repos/coq/bobbycyiii-cheeky", "path": "github-repos/coq/bobbycyiii-cheeky/cheeky-7501122677d8de97e2f7e317133c574cbfd17865/dehn_bounds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6835268167996936}}
{"text": "\nRequire Import Coq.Setoids.Setoid Coq.PArith.BinPos Coq.PArith.Pnat.\n\nSet Automatic Introduction.\n\nSection P_of_nat.\n\n  Variables (n: nat) (E: n <> O).\n\n  Lemma P_of_nat: positive.\n   apply P_of_succ_nat.\n   destruct n as [|p].\n    exfalso. apply E. reflexivity.\n   exact p.\n  Defined.\n\n  Lemma P_of_nat_correct: nat_of_P P_of_nat = n.\n   unfold P_of_nat.\n   destruct n. exfalso. intuition.\n   apply nat_of_P_o_P_of_succ_nat_eq_succ.\n  Qed.\n\nEnd P_of_nat.\n\nLemma nat_of_P_inj_iff (p q : positive): nat_of_P p = nat_of_P q <-> p = q.\nProof with auto.\n split; intro. apply nat_of_P_inj... subst...\nQed.\n\nLemma nat_of_P_nonzero (p: positive): nat_of_P p <> 0.\nProof.\n intro H.\n apply Lt.lt_irrefl with 0.\n rewrite <- H at 2.\n apply lt_O_nat_of_P.\nQed.\n\n#[global]\nHint Immediate nat_of_P_nonzero.\n\nLemma Plt_lt (p q: positive): Pos.lt p q <-> (nat_of_P p < nat_of_P q).\nProof.\n split. apply nat_of_P_lt_Lt_compare_morphism.\n apply nat_of_P_lt_Lt_compare_complement_morphism.\nQed.\n\nLemma Ple_le (p q: positive): Pos.le p q <-> le (nat_of_P p) (nat_of_P q).\nProof.\n rewrite Pos.le_lteq, Plt_lt, Lt.le_lt_or_eq_iff, nat_of_P_inj_iff.\n reflexivity.\nQed.\n\nLemma Ple_refl p: Pos.le p p.\nProof. intros. apply Pos.le_lteq. firstorder. Qed.\n", "meta": {"author": "coq-community", "repo": "corn", "sha": "cfbf6b297643935f0fe7e22d2b14b462bf7e3095", "save_path": "github-repos/coq/coq-community-corn", "path": "github-repos/coq/coq-community-corn/corn-cfbf6b297643935f0fe7e22d2b14b462bf7e3095/stdlib_omissions/P.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6835268166278191}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\nRequire Import Rbase.\nRequire Import Rfunctions.\nRequire Import Ranalysis1.\nRequire Import RList.\nRequire Import Classical_Prop.\nRequire Import Classical_Pred_Type.\nLocal Open Scope R_scope.\n\n\n\nDefinition included (D1 D2:R -> Prop) : Prop := forall x:R, D1 x -> D2 x.\nDefinition disc (x:R) (delta:posreal) (y:R) : Prop := Rabs (y - x) < delta.\nDefinition neighbourhood (V:R -> Prop) (x:R) : Prop :=\nexists delta : posreal, included (disc x delta) V.\nDefinition open_set (D:R -> Prop) : Prop :=\nforall x:R, D x -> neighbourhood D x.\nDefinition complementary (D:R -> Prop) (c:R) : Prop := ~ D c.\nDefinition closed_set (D:R -> Prop) : Prop := open_set (complementary D).\nDefinition intersection_domain (D1 D2:R -> Prop) (c:R) : Prop := D1 c /\\ D2 c.\nDefinition union_domain (D1 D2:R -> Prop) (c:R) : Prop := D1 c \\/ D2 c.\nDefinition interior (D:R -> Prop) (x:R) : Prop := neighbourhood D x.\n\nLemma interior_P1 : forall D:R -> Prop, included (interior D) D.\nProof. hammer_hook \"Rtopology\" \"Rtopology.interior_P1\".  \nintros; unfold included; unfold interior; intros;\nunfold neighbourhood in H; elim H; intros; unfold included in H0;\napply H0; unfold disc; unfold Rminus;\nrewrite Rplus_opp_r; rewrite Rabs_R0; apply (cond_pos x0).\nQed.\n\nLemma interior_P2 : forall D:R -> Prop, open_set D -> included D (interior D).\nProof. hammer_hook \"Rtopology\" \"Rtopology.interior_P2\".  \nintros; unfold open_set in H; unfold included; intros;\nassert (H1 := H _ H0); unfold interior; apply H1.\nQed.\n\nDefinition point_adherent (D:R -> Prop) (x:R) : Prop :=\nforall V:R -> Prop,\nneighbourhood V x ->  exists y : R, intersection_domain V D y.\nDefinition adherence (D:R -> Prop) (x:R) : Prop := point_adherent D x.\n\nLemma adherence_P1 : forall D:R -> Prop, included D (adherence D).\nProof. hammer_hook \"Rtopology\" \"Rtopology.adherence_P1\".  \nintro; unfold included; intros; unfold adherence;\nunfold point_adherent; intros; exists x;\nunfold intersection_domain; split.\nunfold neighbourhood in H0; elim H0; intros; unfold included in H1; apply H1;\nunfold disc; unfold Rminus; rewrite Rplus_opp_r;\nrewrite Rabs_R0; apply (cond_pos x0).\napply H.\nQed.\n\nLemma included_trans :\nforall D1 D2 D3:R -> Prop,\nincluded D1 D2 -> included D2 D3 -> included D1 D3.\nProof. hammer_hook \"Rtopology\" \"Rtopology.included_trans\".  \nunfold included; intros; apply H0; apply H; apply H1.\nQed.\n\nLemma interior_P3 : forall D:R -> Prop, open_set (interior D).\nProof. hammer_hook \"Rtopology\" \"Rtopology.interior_P3\".  \nintro; unfold open_set, interior; unfold neighbourhood;\nintros; elim H; intros.\nexists x0; unfold included; intros.\nset (del := x0 - Rabs (x - x1)).\ncut (0 < del).\nintro; exists (mkposreal del H2); intros.\ncut (included (disc x1 (mkposreal del H2)) (disc x x0)).\nintro; assert (H5 := included_trans _ _ _ H4 H0).\napply H5; apply H3.\nunfold included; unfold disc; intros.\napply Rle_lt_trans with (Rabs (x3 - x1) + Rabs (x1 - x)).\nreplace (x3 - x) with (x3 - x1 + (x1 - x)); [ apply Rabs_triang | ring ].\nreplace (pos x0) with (del + Rabs (x1 - x)).\ndo 2 rewrite <- (Rplus_comm (Rabs (x1 - x))); apply Rplus_lt_compat_l;\napply H4.\nunfold del; rewrite <- (Rabs_Ropp (x - x1)); rewrite Ropp_minus_distr;\nring.\nunfold del; apply Rplus_lt_reg_l with (Rabs (x - x1));\nrewrite Rplus_0_r;\nreplace (Rabs (x - x1) + (x0 - Rabs (x - x1))) with (pos x0);\n[ idtac | ring ].\nunfold disc in H1; rewrite <- Rabs_Ropp; rewrite Ropp_minus_distr; apply H1.\nQed.\n\nLemma complementary_P1 :\nforall D:R -> Prop,\n~ (exists y : R, intersection_domain D (complementary D) y).\nProof. hammer_hook \"Rtopology\" \"Rtopology.complementary_P1\".  \nintro; red; intro; elim H; intros;\nunfold intersection_domain, complementary in H0; elim H0;\nintros; elim H2; assumption.\nQed.\n\nLemma adherence_P2 :\nforall D:R -> Prop, closed_set D -> included (adherence D) D.\nProof. hammer_hook \"Rtopology\" \"Rtopology.adherence_P2\".  \nunfold closed_set; unfold open_set, complementary; intros;\nunfold included, adherence; intros; assert (H1 := classic (D x));\nelim H1; intro.\nassumption.\nassert (H3 := H _ H2); assert (H4 := H0 _ H3); elim H4; intros;\nunfold intersection_domain in H5; elim H5; intros;\nelim H6; assumption.\nQed.\n\nLemma adherence_P3 : forall D:R -> Prop, closed_set (adherence D).\nProof. hammer_hook \"Rtopology\" \"Rtopology.adherence_P3\".  \nintro; unfold closed_set, adherence;\nunfold open_set, complementary, point_adherent;\nintros;\nset\n(P :=\nfun V:R -> Prop =>\nneighbourhood V x ->  exists y : R, intersection_domain V D y);\nassert (H0 := not_all_ex_not _ P H); elim H0; intros V0 H1;\nunfold P in H1; assert (H2 := imply_to_and _ _ H1);\nunfold neighbourhood; elim H2; intros; unfold neighbourhood in H3;\nelim H3; intros; exists x0; unfold included;\nintros; red; intro.\nassert (H8 := H7 V0);\ncut (exists delta : posreal, (forall x:R, disc x1 delta x -> V0 x)).\nintro; assert (H10 := H8 H9); elim H4; assumption.\ncut (0 < x0 - Rabs (x - x1)).\nintro; set (del := mkposreal _ H9); exists del; intros;\nunfold included in H5; apply H5; unfold disc;\napply Rle_lt_trans with (Rabs (x2 - x1) + Rabs (x1 - x)).\nreplace (x2 - x) with (x2 - x1 + (x1 - x)); [ apply Rabs_triang | ring ].\nreplace (pos x0) with (del + Rabs (x1 - x)).\ndo 2 rewrite <- (Rplus_comm (Rabs (x1 - x))); apply Rplus_lt_compat_l;\napply H10.\nunfold del; simpl; rewrite <- (Rabs_Ropp (x - x1));\nrewrite Ropp_minus_distr; ring.\napply Rplus_lt_reg_l with (Rabs (x - x1)); rewrite Rplus_0_r;\nreplace (Rabs (x - x1) + (x0 - Rabs (x - x1))) with (pos x0);\n[ rewrite <- Rabs_Ropp; rewrite Ropp_minus_distr; apply H6 | ring ].\nQed.\n\nDefinition eq_Dom (D1 D2:R -> Prop) : Prop :=\nincluded D1 D2 /\\ included D2 D1.\n\nInfix \"=_D\" := eq_Dom (at level 70, no associativity).\n\nLemma open_set_P1 : forall D:R -> Prop, open_set D <-> D =_D interior D.\nProof. hammer_hook \"Rtopology\" \"Rtopology.open_set_P1\".  \nintro; split.\nintro; unfold eq_Dom; split.\napply interior_P2; assumption.\napply interior_P1.\nintro; unfold eq_Dom in H; elim H; clear H; intros; unfold open_set;\nintros; unfold included, interior in H; unfold included in H0;\napply (H _ H1).\nQed.\n\nLemma closed_set_P1 : forall D:R -> Prop, closed_set D <-> D =_D adherence D.\nProof. hammer_hook \"Rtopology\" \"Rtopology.closed_set_P1\".  \nintro; split.\nintro; unfold eq_Dom; split.\napply adherence_P1.\napply adherence_P2; assumption.\nunfold eq_Dom; unfold included; intros;\nassert (H0 := adherence_P3 D); unfold closed_set in H0;\nunfold closed_set; unfold open_set;\nunfold open_set in H0; intros; assert (H2 : complementary (adherence D) x).\nunfold complementary; unfold complementary in H1; red; intro;\nelim H; clear H; intros _ H; elim H1; apply (H _ H2).\nassert (H3 := H0 _ H2); unfold neighbourhood;\nunfold neighbourhood in H3; elim H3; intros; exists x0;\nunfold included; unfold included in H4; intros;\nassert (H6 := H4 _ H5); unfold complementary in H6;\nunfold complementary; red; intro;\nelim H; clear H; intros H _; elim H6; apply (H _ H7).\nQed.\n\nLemma neighbourhood_P1 :\nforall (D1 D2:R -> Prop) (x:R),\nincluded D1 D2 -> neighbourhood D1 x -> neighbourhood D2 x.\nProof. hammer_hook \"Rtopology\" \"Rtopology.neighbourhood_P1\".  \nunfold included, neighbourhood; intros; elim H0; intros; exists x0;\nintros; unfold included; unfold included in H1;\nintros; apply (H _ (H1 _ H2)).\nQed.\n\nLemma open_set_P2 :\nforall D1 D2:R -> Prop,\nopen_set D1 -> open_set D2 -> open_set (union_domain D1 D2).\nProof. hammer_hook \"Rtopology\" \"Rtopology.open_set_P2\".  \nunfold open_set; intros; unfold union_domain in H1; elim H1; intro.\napply neighbourhood_P1 with D1.\nunfold included, union_domain; tauto.\napply H; assumption.\napply neighbourhood_P1 with D2.\nunfold included, union_domain; tauto.\napply H0; assumption.\nQed.\n\nLemma open_set_P3 :\nforall D1 D2:R -> Prop,\nopen_set D1 -> open_set D2 -> open_set (intersection_domain D1 D2).\nProof. hammer_hook \"Rtopology\" \"Rtopology.open_set_P3\".  \nunfold open_set; intros; unfold intersection_domain in H1; elim H1;\nintros.\nassert (H4 := H _ H2); assert (H5 := H0 _ H3);\nunfold intersection_domain; unfold neighbourhood in H4, H5;\nelim H4; clear H; intros del1 H; elim H5; clear H0;\nintros del2 H0; cut (0 < Rmin del1 del2).\nintro; set (del := mkposreal _ H6).\nexists del; unfold included; intros; unfold included in H, H0;\nunfold disc in H, H0, H7.\nsplit.\napply H; apply Rlt_le_trans with (pos del).\napply H7.\nunfold del; simpl; apply Rmin_l.\napply H0; apply Rlt_le_trans with (pos del).\napply H7.\nunfold del; simpl; apply Rmin_r.\nunfold Rmin; case (Rle_dec del1 del2); intro.\napply (cond_pos del1).\napply (cond_pos del2).\nQed.\n\nLemma open_set_P4 : open_set (fun x:R => False).\nProof. hammer_hook \"Rtopology\" \"Rtopology.open_set_P4\".  \nunfold open_set; intros; elim H.\nQed.\n\nLemma open_set_P5 : open_set (fun x:R => True).\nProof. hammer_hook \"Rtopology\" \"Rtopology.open_set_P5\".  \nunfold open_set; intros; unfold neighbourhood.\nexists (mkposreal 1 Rlt_0_1); unfold included; intros; trivial.\nQed.\n\nLemma disc_P1 : forall (x:R) (del:posreal), open_set (disc x del).\nProof. hammer_hook \"Rtopology\" \"Rtopology.disc_P1\".  \nintros; assert (H := open_set_P1 (disc x del)).\nelim H; intros; apply H1.\nunfold eq_Dom; split.\nunfold included, interior, disc; intros;\ncut (0 < del - Rabs (x - x0)).\nintro; set (del2 := mkposreal _ H3).\nexists del2; unfold included; intros.\napply Rle_lt_trans with (Rabs (x1 - x0) + Rabs (x0 - x)).\nreplace (x1 - x) with (x1 - x0 + (x0 - x)); [ apply Rabs_triang | ring ].\nreplace (pos del) with (del2 + Rabs (x0 - x)).\ndo 2 rewrite <- (Rplus_comm (Rabs (x0 - x))); apply Rplus_lt_compat_l.\napply H4.\nunfold del2; simpl; rewrite <- (Rabs_Ropp (x - x0));\nrewrite Ropp_minus_distr; ring.\napply Rplus_lt_reg_l with (Rabs (x - x0)); rewrite Rplus_0_r;\nreplace (Rabs (x - x0) + (del - Rabs (x - x0))) with (pos del);\n[ rewrite <- Rabs_Ropp; rewrite Ropp_minus_distr; apply H2 | ring ].\napply interior_P1.\nQed.\n\nLemma continuity_P1 :\nforall (f:R -> R) (x:R),\ncontinuity_pt f x <->\n(forall W:R -> Prop,\nneighbourhood W (f x) ->\nexists V : R -> Prop,\nneighbourhood V x /\\ (forall y:R, V y -> W (f y))).\nProof. hammer_hook \"Rtopology\" \"Rtopology.continuity_P1\".  \nintros; split.\nintros; unfold neighbourhood in H0.\nelim H0; intros del1 H1.\nunfold continuity_pt in H; unfold continue_in in H; unfold limit1_in in H;\nunfold limit_in in H; simpl in H; unfold R_dist in H.\nassert (H2 := H del1 (cond_pos del1)).\nelim H2; intros del2 H3.\nelim H3; intros.\nexists (disc x (mkposreal del2 H4)).\nintros; unfold included in H1; split.\nunfold neighbourhood, disc.\nexists (mkposreal del2 H4).\nunfold included; intros; assumption.\nintros; apply H1; unfold disc; case (Req_dec y x); intro.\nrewrite H7; unfold Rminus; rewrite Rplus_opp_r; rewrite Rabs_R0;\napply (cond_pos del1).\napply H5; split.\nunfold D_x, no_cond; split.\ntrivial.\napply (not_eq_sym (A:=R)); apply H7.\nunfold disc in H6; apply H6.\nintros; unfold continuity_pt; unfold continue_in;\nunfold limit1_in; unfold limit_in;\nintros.\nassert (H1 := H (disc (f x) (mkposreal eps H0))).\ncut (neighbourhood (disc (f x) (mkposreal eps H0)) (f x)).\nintro; assert (H3 := H1 H2).\nelim H3; intros D H4; elim H4; intros; unfold neighbourhood in H5; elim H5;\nintros del1 H7.\nexists (pos del1); split.\napply (cond_pos del1).\nintros; elim H8; intros; simpl in H10; unfold R_dist in H10; simpl;\nunfold R_dist; apply (H6 _ (H7 _ H10)).\nunfold neighbourhood, disc; exists (mkposreal eps H0);\nunfold included; intros; assumption.\nQed.\n\nDefinition image_rec (f:R -> R) (D:R -> Prop) (x:R) : Prop := D (f x).\n\n\nLemma continuity_P2 :\nforall (f:R -> R) (D:R -> Prop),\ncontinuity f -> open_set D -> open_set (image_rec f D).\nProof. hammer_hook \"Rtopology\" \"Rtopology.continuity_P2\".  \nintros; unfold open_set in H0; unfold open_set; intros;\nassert (H2 := continuity_P1 f x); elim H2; intros H3 _;\nassert (H4 := H3 (H x)); unfold neighbourhood, image_rec;\nunfold image_rec in H1; assert (H5 := H4 D (H0 (f x) H1));\nelim H5; intros V0 H6; elim H6; intros; unfold neighbourhood in H7;\nelim H7; intros del H9; exists del; unfold included in H9;\nunfold included; intros; apply (H8 _ (H9 _ H10)).\nQed.\n\n\nLemma continuity_P3 :\nforall f:R -> R,\ncontinuity f <->\n(forall D:R -> Prop, open_set D -> open_set (image_rec f D)).\nProof. hammer_hook \"Rtopology\" \"Rtopology.continuity_P3\".  \nintros; split.\nintros; apply continuity_P2; assumption.\nintros; unfold continuity; unfold continuity_pt;\nunfold continue_in; unfold limit1_in;\nunfold limit_in; simpl; unfold R_dist;\nintros; cut (open_set (disc (f x) (mkposreal _ H0))).\nintro; assert (H2 := H _ H1).\nunfold open_set, image_rec in H2; cut (disc (f x) (mkposreal _ H0) (f x)).\nintro; assert (H4 := H2 _ H3).\nunfold neighbourhood in H4; elim H4; intros del H5.\nexists (pos del); split.\napply (cond_pos del).\nintros; unfold included in H5; apply H5; elim H6; intros; apply H8.\nunfold disc; unfold Rminus; rewrite Rplus_opp_r;\nrewrite Rabs_R0; apply H0.\napply disc_P1.\nQed.\n\n\nTheorem Rsepare :\nforall x y:R,\nx <> y ->\nexists V : R -> Prop,\n(exists W : R -> Prop,\nneighbourhood V x /\\\nneighbourhood W y /\\ ~ (exists y : R, intersection_domain V W y)).\nProof. hammer_hook \"Rtopology\" \"Rtopology.Rsepare\".  \nintros x y Hsep; set (D := Rabs (x - y)).\ncut (0 < D / 2).\nintro; exists (disc x (mkposreal _ H)).\nexists (disc y (mkposreal _ H)); split.\nunfold neighbourhood; exists (mkposreal _ H); unfold included;\ntauto.\nsplit.\nunfold neighbourhood; exists (mkposreal _ H); unfold included;\ntauto.\nred; intro; elim H0; intros; unfold intersection_domain in H1;\nelim H1; intros.\ncut (D < D).\nintro; elim (Rlt_irrefl _ H4).\nchange (Rabs (x - y) < D);\napply Rle_lt_trans with (Rabs (x - x0) + Rabs (x0 - y)).\nreplace (x - y) with (x - x0 + (x0 - y)); [ apply Rabs_triang | ring ].\nrewrite (double_var D); apply Rplus_lt_compat.\nrewrite <- Rabs_Ropp; rewrite Ropp_minus_distr; apply H2.\napply H3.\nunfold Rdiv; apply Rmult_lt_0_compat.\nunfold D; apply Rabs_pos_lt; apply (Rminus_eq_contra _ _ Hsep).\napply Rinv_0_lt_compat; prove_sup0.\nQed.\n\nRecord family : Type := mkfamily\n{ind : R -> Prop;\nf :> R -> R -> Prop;\ncond_fam : forall x:R, (exists y : R, f x y) -> ind x}.\n\nDefinition family_open_set (f:family) : Prop := forall x:R, open_set (f x).\n\nDefinition domain_finite (D:R -> Prop) : Prop :=\nexists l : Rlist, (forall x:R, D x <-> In x l).\n\nDefinition family_finite (f:family) : Prop := domain_finite (ind f).\n\nDefinition covering (D:R -> Prop) (f:family) : Prop :=\nforall x:R, D x ->  exists y : R, f y x.\n\nDefinition covering_open_set (D:R -> Prop) (f:family) : Prop :=\ncovering D f /\\ family_open_set f.\n\nDefinition covering_finite (D:R -> Prop) (f:family) : Prop :=\ncovering D f /\\ family_finite f.\n\nLemma restriction_family :\nforall (f:family) (D:R -> Prop) (x:R),\n(exists y : R, (fun z1 z2:R => f z1 z2 /\\ D z1) x y) ->\nintersection_domain (ind f) D x.\nProof. hammer_hook \"Rtopology\" \"Rtopology.restriction_family\".  \nintros; elim H; intros; unfold intersection_domain; elim H0; intros;\nsplit.\napply (cond_fam f0); exists x0; assumption.\nassumption.\nQed.\n\nDefinition subfamily (f:family) (D:R -> Prop) : family :=\nmkfamily (intersection_domain (ind f) D) (fun x y:R => f x y /\\ D x)\n(restriction_family f D).\n\nDefinition compact (X:R -> Prop) : Prop :=\nforall f:family,\ncovering_open_set X f ->\nexists D : R -> Prop, covering_finite X (subfamily f D).\n\n\nLemma family_P1 :\nforall (f:family) (D:R -> Prop),\nfamily_open_set f -> family_open_set (subfamily f D).\nProof. hammer_hook \"Rtopology\" \"Rtopology.family_P1\".  \nunfold family_open_set; intros; unfold subfamily;\nsimpl; assert (H0 := classic (D x)).\nelim H0; intro.\ncut (open_set (f0 x) -> open_set (fun y:R => f0 x y /\\ D x)).\nintro; apply H2; apply H.\nunfold open_set; unfold neighbourhood; intros; elim H3;\nintros; assert (H6 := H2 _ H4); elim H6; intros; exists x1;\nunfold included; intros; split.\napply (H7 _ H8).\nassumption.\ncut (open_set (fun y:R => False) -> open_set (fun y:R => f0 x y /\\ D x)).\nintro; apply H2; apply open_set_P4.\nunfold open_set; unfold neighbourhood; intros; elim H3;\nintros; elim H1; assumption.\nQed.\n\nDefinition bounded (D:R -> Prop) : Prop :=\nexists m : R, (exists M : R, (forall x:R, D x -> m <= x <= M)).\n\nLemma open_set_P6 :\nforall D1 D2:R -> Prop, open_set D1 -> D1 =_D D2 -> open_set D2.\nProof. hammer_hook \"Rtopology\" \"Rtopology.open_set_P6\".  \nunfold open_set; unfold neighbourhood; intros.\nunfold eq_Dom in H0; elim H0; intros.\nassert (H4 := H _ (H3 _ H1)).\nelim H4; intros.\nexists x0; apply included_trans with D1; assumption.\nQed.\n\n\nLemma compact_P1 : forall X:R -> Prop, compact X -> bounded X.\nProof. hammer_hook \"Rtopology\" \"Rtopology.compact_P1\".  \nintros; unfold compact in H; set (D := fun x:R => True);\nset (g := fun x y:R => Rabs y < x);\ncut (forall x:R, (exists y : _, g x y) -> True);\n[ intro | intro; trivial ].\nset (f0 := mkfamily D g H0); assert (H1 := H f0);\ncut (covering_open_set X f0).\nintro; assert (H3 := H1 H2); elim H3; intros D' H4;\nunfold covering_finite in H4; elim H4; intros; unfold family_finite in H6;\nunfold domain_finite in H6; elim H6; intros l H7;\nunfold bounded; set (r := MaxRlist l).\nexists (- r); exists r; intros.\nunfold covering in H5; assert (H9 := H5 _ H8); elim H9; intros;\nunfold subfamily in H10; simpl in H10; elim H10; intros;\nassert (H13 := H7 x0); simpl in H13; cut (intersection_domain D D' x0).\nelim H13; clear H13; intros.\nassert (H16 := H13 H15); unfold g in H11; split.\ncut (x0 <= r).\nintro; cut (Rabs x < r).\nintro; assert (H19 := Rabs_def2 x r H18); elim H19; intros; left; assumption.\napply Rlt_le_trans with x0; assumption.\napply (MaxRlist_P1 l x0 H16).\ncut (x0 <= r).\nintro; apply Rle_trans with (Rabs x).\napply RRle_abs.\napply Rle_trans with x0.\nleft; apply H11.\nassumption.\napply (MaxRlist_P1 l x0 H16).\nunfold intersection_domain, D; tauto.\nunfold covering_open_set; split.\nunfold covering; intros; simpl; exists (Rabs x + 1);\nunfold g; pattern (Rabs x) at 1; rewrite <- Rplus_0_r;\napply Rplus_lt_compat_l; apply Rlt_0_1.\nunfold family_open_set; intro; case (Rtotal_order 0 x); intro.\napply open_set_P6 with (disc 0 (mkposreal _ H2)).\napply disc_P1.\nunfold eq_Dom; unfold f0; simpl;\nunfold g, disc; split.\nunfold included; intros; unfold Rminus in H3; rewrite Ropp_0 in H3;\nrewrite Rplus_0_r in H3; apply H3.\nunfold included; intros; unfold Rminus; rewrite Ropp_0;\nrewrite Rplus_0_r; apply H3.\napply open_set_P6 with (fun x:R => False).\napply open_set_P4.\nunfold eq_Dom; split.\nunfold included; intros; elim H3.\nunfold included, f0; simpl; unfold g; intros; elim H2;\nintro;\n[ rewrite <- H4 in H3; assert (H5 := Rabs_pos x0);\nelim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H5 H3))\n| assert (H6 := Rabs_pos x0); assert (H7 := Rlt_trans _ _ _ H3 H4);\nelim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H6 H7)) ].\nQed.\n\n\nLemma compact_P2 : forall X:R -> Prop, compact X -> closed_set X.\nProof. hammer_hook \"Rtopology\" \"Rtopology.compact_P2\".  \nintros; assert (H0 := closed_set_P1 X); elim H0; clear H0; intros _ H0;\napply H0; clear H0.\nunfold eq_Dom; split.\napply adherence_P1.\nunfold included; unfold adherence;\nunfold point_adherent; intros; unfold compact in H;\nassert (H1 := classic (X x)); elim H1; clear H1; intro.\nassumption.\ncut (forall y:R, X y -> 0 < Rabs (y - x) / 2).\nintro; set (D := X);\nset (g := fun y z:R => Rabs (y - z) < Rabs (y - x) / 2 /\\ D y);\ncut (forall x:R, (exists y : _, g x y) -> D x).\nintro; set (f0 := mkfamily D g H3); assert (H4 := H f0);\ncut (covering_open_set X f0).\nintro; assert (H6 := H4 H5); elim H6; clear H6; intros D' H6.\nunfold covering_finite in H6; decompose [and] H6;\nunfold covering, subfamily in H7; simpl in H7;\nunfold family_finite, subfamily in H8; simpl in H8;\nunfold domain_finite in H8; elim H8; clear H8; intros l H8;\nset (alp := MinRlist (AbsList l x)); cut (0 < alp).\nintro; assert (H10 := H0 (disc x (mkposreal _ H9)));\ncut (neighbourhood (disc x (mkposreal alp H9)) x).\nintro; assert (H12 := H10 H11); elim H12; clear H12; intros y H12;\nunfold intersection_domain in H12; elim H12; clear H12;\nintros; assert (H14 := H7 _ H13); elim H14; clear H14;\nintros y0 H14; elim H14; clear H14; intros; unfold g in H14;\nelim H14; clear H14; intros; unfold disc in H12; simpl in H12;\ncut (alp <= Rabs (y0 - x) / 2).\nintro; assert (H18 := Rlt_le_trans _ _ _ H12 H17);\ncut (Rabs (y0 - x) < Rabs (y0 - x)).\nintro; elim (Rlt_irrefl _ H19).\napply Rle_lt_trans with (Rabs (y0 - y) + Rabs (y - x)).\nreplace (y0 - x) with (y0 - y + (y - x)); [ apply Rabs_triang | ring ].\nrewrite (double_var (Rabs (y0 - x))); apply Rplus_lt_compat; assumption.\napply (MinRlist_P1 (AbsList l x) (Rabs (y0 - x) / 2)); apply AbsList_P1;\nelim (H8 y0); clear H8; intros; apply H8; unfold intersection_domain;\nsplit; assumption.\nassert (H11 := disc_P1 x (mkposreal alp H9)); unfold open_set in H11;\napply H11.\nunfold disc; unfold Rminus; rewrite Rplus_opp_r;\nrewrite Rabs_R0; apply H9.\nunfold alp; apply MinRlist_P2; intros;\nassert (H10 := AbsList_P2 _ _ _ H9); elim H10; clear H10;\nintros z H10; elim H10; clear H10; intros; rewrite H11;\napply H2; elim (H8 z); clear H8; intros; assert (H13 := H12 H10);\nunfold intersection_domain, D in H13; elim H13; clear H13;\nintros; assumption.\nunfold covering_open_set; split.\nunfold covering; intros; exists x0; simpl; unfold g;\nsplit.\nunfold Rminus; rewrite Rplus_opp_r; rewrite Rabs_R0;\nunfold Rminus in H2; apply (H2 _ H5).\napply H5.\nunfold family_open_set; intro; simpl; unfold g;\nelim (classic (D x0)); intro.\napply open_set_P6 with (disc x0 (mkposreal _ (H2 _ H5))).\napply disc_P1.\nunfold eq_Dom; split.\nunfold included, disc; simpl; intros; split.\nrewrite <- (Rabs_Ropp (x0 - x1)); rewrite Ropp_minus_distr; apply H6.\napply H5.\nunfold included, disc; simpl; intros; elim H6; intros;\nrewrite <- (Rabs_Ropp (x1 - x0)); rewrite Ropp_minus_distr;\napply H7.\napply open_set_P6 with (fun z:R => False).\napply open_set_P4.\nunfold eq_Dom; split.\nunfold included; intros; elim H6.\nunfold included; intros; elim H6; intros; elim H5; assumption.\nintros; elim H3; intros; unfold g in H4; elim H4; clear H4; intros _ H4;\napply H4.\nintros; unfold Rdiv; apply Rmult_lt_0_compat.\napply Rabs_pos_lt; apply Rminus_eq_contra; red; intro;\nrewrite H3 in H2; elim H1; apply H2.\napply Rinv_0_lt_compat; prove_sup0.\nQed.\n\n\nLemma compact_EMP : compact (fun _:R => False).\nProof. hammer_hook \"Rtopology\" \"Rtopology.compact_EMP\".  \nunfold compact; intros; exists (fun x:R => False);\nunfold covering_finite; split.\nunfold covering; intros; elim H0.\nunfold family_finite; unfold domain_finite; exists nil; intro.\nsplit.\nsimpl; unfold intersection_domain; intros; elim H0.\nelim H0; clear H0; intros _ H0; elim H0.\nsimpl; intro; elim H0.\nQed.\n\nLemma compact_eqDom :\nforall X1 X2:R -> Prop, compact X1 -> X1 =_D X2 -> compact X2.\nProof. hammer_hook \"Rtopology\" \"Rtopology.compact_eqDom\".  \nunfold compact; intros; unfold eq_Dom in H0; elim H0; clear H0;\nunfold included; intros; assert (H3 : covering_open_set X1 f0).\nunfold covering_open_set; unfold covering_open_set in H1; elim H1;\nclear H1; intros; split.\nunfold covering in H1; unfold covering; intros;\napply (H1 _ (H0 _ H4)).\napply H3.\nelim (H _ H3); intros D H4; exists D; unfold covering_finite;\nunfold covering_finite in H4; elim H4; intros; split.\nunfold covering in H5; unfold covering; intros;\napply (H5 _ (H2 _ H7)).\napply H6.\nQed.\n\n\nLemma compact_P3 : forall a b:R, compact (fun c:R => a <= c <= b).\nProof. hammer_hook \"Rtopology\" \"Rtopology.compact_P3\".  \nintros a b; destruct (Rle_dec a b) as [Hle|Hnle].\nunfold compact; intros f0 (H,H5);\nset\n(A :=\nfun x:R =>\na <= x <= b /\\\n(exists D : R -> Prop,\ncovering_finite (fun c:R => a <= c <= x) (subfamily f0 D))).\ncut (A a); [intro H0|].\ncut (bound A); [intro H1|].\ncut (exists a0 : R, A a0); [intro H2|].\npose proof (completeness A H1 H2) as (m,H3); unfold is_lub in H3.\ncut (a <= m <= b); [intro H4|].\nunfold covering in H; pose proof (H m H4) as (y0,H6).\nunfold family_open_set in H5; pose proof (H5 y0 m H6) as (eps,H8).\ncut (exists x : R, A x /\\ m - eps < x <= m);\n[intros (x,((H9 & Dx & H12 & H13),(Hltx,_)))|].\ndestruct (Req_dec m b) as [->|H11].\nset (Db := fun x:R => Dx x \\/ x = y0); exists Db;\nunfold covering_finite; split.\nunfold covering; intros x0 (H14,H18);\nunfold covering in H12; destruct (Rle_dec x0 x) as [Hle'|Hnle'].\ncut (a <= x0 <= x); [intro H15|].\npose proof (H12 x0 H15) as (x1 & H16 & H17); exists x1;\nsimpl; unfold Db; split; [ apply H16 | left; apply H17 ].\nsplit; assumption.\nexists y0; simpl; split.\napply H8; unfold disc;\nrewrite <- Rabs_Ropp, Ropp_minus_distr, Rabs_right.\napply Rlt_trans with (b - x).\nunfold Rminus; apply Rplus_lt_compat_l, Ropp_lt_gt_contravar;\nauto with real.\napply Rplus_lt_reg_l with (x - eps);\nreplace (x - eps + (b - x)) with (b - eps);\n[ replace (x - eps + eps) with x; [ apply Hltx | ring ] | ring ].\napply Rge_minus, Rle_ge, H18.\nunfold Db; right; reflexivity.\nunfold family_finite, domain_finite.\nintros; unfold family_finite in H13; unfold domain_finite in H13;\ndestruct H13 as (l,H13); exists (cons y0 l);\nintro; split.\nintro H14; simpl in H14; unfold intersection_domain in H14;\nspecialize H13 with x0; destruct H13 as (H13,H15);\ndestruct (Req_dec x0 y0) as [H16|H16].\nsimpl; left; apply H16.\nsimpl; right; apply H13.\nsimpl; unfold intersection_domain; unfold Db in H14;\ndecompose [and or] H14.\nsplit; assumption.\nelim H16; assumption.\nintro H14; simpl in H14; destruct H14 as [H15|H15]; simpl;\nunfold intersection_domain.\nsplit.\napply (cond_fam f0); rewrite H15; exists b; apply H6.\nunfold Db; right; assumption.\nsimpl; unfold intersection_domain; elim (H13 x0).\nintros _ H16; assert (H17 := H16 H15); simpl in H17;\nunfold intersection_domain in H17; split.\nelim H17; intros; assumption.\nunfold Db; left; elim H17; intros; assumption.\nset (m' := Rmin (m + eps / 2) b).\ncut (A m'); [intro H7|].\ndestruct H3 as (H14,H15); unfold is_upper_bound in H14.\nassert (H16 := H14 m' H7).\ncut (m < m'); [intro H17|].\nelim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H16 H17))...\nunfold m', Rmin; destruct (Rle_dec (m + eps / 2) b) as [Hle'|Hnle'].\npattern m at 1; rewrite <- Rplus_0_r; apply Rplus_lt_compat_l;\nunfold Rdiv; apply Rmult_lt_0_compat;\n[ apply (cond_pos eps) | apply Rinv_0_lt_compat; prove_sup0 ].\ndestruct H4 as (_,[]).\nassumption.\nelim H11; assumption.\nunfold A; split.\nsplit.\napply Rle_trans with m.\nelim H4; intros; assumption.\nunfold m'; unfold Rmin; case (Rle_dec (m + eps / 2) b); intro.\npattern m at 1; rewrite <- Rplus_0_r; apply Rplus_le_compat_l; left;\nunfold Rdiv; apply Rmult_lt_0_compat;\n[ apply (cond_pos eps) | apply Rinv_0_lt_compat; prove_sup0 ].\ndestruct H4.\nassumption.\nunfold m'; apply Rmin_r.\nset (Db := fun x:R => Dx x \\/ x = y0); exists Db;\nunfold covering_finite; split.\nunfold covering; intros x0 (H14,H18);\nunfold covering in H12; destruct (Rle_dec x0 x) as [Hle'|Hnle'].\ncut (a <= x0 <= x); [intro H15|].\npose proof (H12 x0 H15) as (x1 & H16 & H17); exists x1;\nsimpl; unfold Db; split; [ apply H16 | left; apply H17 ].\nsplit; assumption.\nexists y0; simpl; split.\napply H8; unfold disc, Rabs; destruct (Rcase_abs (x0 - m)) as [Hlt|Hge].\nrewrite Ropp_minus_distr; apply Rlt_trans with (m - x).\nunfold Rminus; apply Rplus_lt_compat_l; apply Ropp_lt_gt_contravar;\nauto with real.\napply Rplus_lt_reg_l with (x - eps);\nreplace (x - eps + (m - x)) with (m - eps).\nreplace (x - eps + eps) with x.\nassumption.\nring.\nring.\napply Rle_lt_trans with (m' - m).\nunfold Rminus; do 2 rewrite <- (Rplus_comm (- m));\napply Rplus_le_compat_l; elim H14; intros; assumption.\napply Rplus_lt_reg_l with m; replace (m + (m' - m)) with m'.\napply Rle_lt_trans with (m + eps / 2).\nunfold m'; apply Rmin_l.\napply Rplus_lt_compat_l; apply Rmult_lt_reg_l with 2.\nprove_sup0.\nunfold Rdiv; rewrite <- (Rmult_comm (/ 2)); rewrite <- Rmult_assoc;\nrewrite <- Rinv_r_sym.\nrewrite Rmult_1_l; pattern (pos eps) at 1; rewrite <- Rplus_0_r;\nrewrite double; apply Rplus_lt_compat_l; apply (cond_pos eps).\ndiscrR.\nring.\nunfold Db; right; reflexivity.\nunfold family_finite, domain_finite;\nunfold family_finite, domain_finite in H13;\ndestruct H13 as (l,H13); exists (cons y0 l);\nintro; split.\nintro H14; simpl in H14; unfold intersection_domain in H14;\nspecialize (H13 x0); destruct H13 as (H13,H15);\ndestruct (Req_dec x0 y0) as [Heq|Hneq].\nsimpl; left; apply Heq.\nsimpl; right; apply H13; simpl;\nunfold intersection_domain; unfold Db in H14;\ndecompose [and or] H14.\nsplit; assumption.\nelim Hneq; assumption.\nintros [H15|H15]. split.\napply (cond_fam f0); rewrite H15; exists m; apply H6.\nunfold Db; right; assumption.\nelim (H13 x0); intros _ H16.\nassert (H17 := H16 H15).\nsimpl in H17.\nunfold intersection_domain in H17.\nsplit.\nelim H17; intros; assumption.\nunfold Db; left; elim H17; intros; assumption.\nelim (classic (exists x : R, A x /\\ m - eps < x <= m)); intro H9.\nassumption.\nelim H3; intros H10 H11; cut (is_upper_bound A (m - eps)).\nintro H12; assert (H13 := H11 _ H12); cut (m - eps < m).\nintro H14; elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H13 H14)).\npattern m at 2; rewrite <- Rplus_0_r; unfold Rminus;\napply Rplus_lt_compat_l; apply Ropp_lt_cancel; rewrite Ropp_involutive;\nrewrite Ropp_0; apply (cond_pos eps).\nset (P := fun n:R => A n /\\ m - eps < n <= m);\nassert (H12 := not_ex_all_not _ P H9); unfold P in H12;\nunfold is_upper_bound; intros x H13;\nassert (H14 := not_and_or _ _ (H12 x)); elim H14;\nintro H15.\nelim H15; apply H13.\ndestruct (not_and_or _ _ H15) as [H16|H16].\ndestruct (Rle_dec x (m - eps)) as [H17|H17].\nassumption.\nelim H16; auto with real.\nunfold is_upper_bound in H10; assert (H17 := H10 x H13); elim H16; apply H17.\nelim H3; clear H3; intros.\nunfold is_upper_bound in H3.\nsplit.\napply (H3 _ H0).\nclear H5.\napply (H4 b); unfold is_upper_bound; intros x H5; unfold A in H5; elim H5;\nclear H5; intros H5 _; elim H5; clear H5; intros _ H5;\napply H5.\nexists a; apply H0.\nunfold bound; exists b; unfold is_upper_bound; intros;\nunfold A in H1; elim H1; clear H1; intros H1 _; elim H1;\nclear H1; intros _ H1; apply H1.\nunfold A; split.\nsplit; [ right; reflexivity | apply Hle ].\nunfold covering in H; cut (a <= a <= b).\nintro H1; elim (H _ H1); intros y0 H2; set (D' := fun x:R => x = y0); exists D';\nunfold covering_finite; split.\nunfold covering; simpl; intros x H3; cut (x = a).\nintro H4; exists y0; split.\nrewrite H4; apply H2.\nunfold D'; reflexivity.\nelim H3; intros; apply Rle_antisym; assumption.\nunfold family_finite; unfold domain_finite;\nexists (cons y0 nil); intro; split.\nsimpl; unfold intersection_domain; intros (H3,H4).\nunfold D' in H4; left; apply H4.\nsimpl; unfold intersection_domain; intros [H4|[]].\nsplit; [ rewrite H4; apply (cond_fam f0); exists a; apply H2 | apply H4 ].\nsplit; [ right; reflexivity | apply Hle ].\napply compact_eqDom with (fun c:R => False).\napply compact_EMP.\nunfold eq_Dom; split.\nunfold included; intros; elim H.\nunfold included; intros; elim H; clear H; intros;\nassert (H1 := Rle_trans _ _ _ H H0); elim Hnle; apply H1.\nQed.\n\nLemma compact_P4 :\nforall X F:R -> Prop, compact X -> closed_set F -> included F X -> compact F.\nProof. hammer_hook \"Rtopology\" \"Rtopology.compact_P4\".  \nunfold compact; intros; elim (classic (exists z : R, F z));\nintro Hyp_F_NE.\nset (D := ind f0); set (g := f f0); unfold closed_set in H0.\nset (g' := fun x y:R => f0 x y \\/ complementary F y /\\ D x).\nset (D' := D).\ncut (forall x:R, (exists y : R, g' x y) -> D' x).\nintro; set (f' := mkfamily D' g' H3); cut (covering_open_set X f').\nintro; elim (H _ H4); intros DX H5; exists DX.\nunfold covering_finite; unfold covering_finite in H5; elim H5;\nclear H5; intros.\nsplit.\nunfold covering; unfold covering in H5; intros.\nelim (H5 _ (H1 _ H7)); intros y0 H8; exists y0; simpl in H8; simpl;\nelim H8; clear H8; intros.\nsplit.\nunfold g' in H8; elim H8; intro.\napply H10.\nelim H10; intros H11 _; unfold complementary in H11; elim H11; apply H7.\napply H9.\nunfold family_finite; unfold domain_finite;\nunfold family_finite in H6; unfold domain_finite in H6;\nelim H6; clear H6; intros l H6; exists l; intro; assert (H7 := H6 x);\nelim H7; clear H7; intros.\nsplit.\nintro; apply H7; simpl; unfold intersection_domain;\nsimpl in H9; unfold intersection_domain in H9; unfold D';\napply H9.\nintro; assert (H10 := H8 H9); simpl in H10; unfold intersection_domain in H10;\nsimpl; unfold intersection_domain;\nunfold D' in H10; apply H10.\nunfold covering_open_set; unfold covering_open_set in H2; elim H2;\nclear H2; intros.\nsplit.\nunfold covering; unfold covering in H2; intros.\nelim (classic (F x)); intro.\nelim (H2 _ H6); intros y0 H7; exists y0; simpl; unfold g';\nleft; assumption.\ncut (exists z : R, D z).\nintro; elim H7; clear H7; intros x0 H7; exists x0; simpl;\nunfold g'; right.\nsplit.\nunfold complementary; apply H6.\napply H7.\nelim Hyp_F_NE; intros z0 H7.\nassert (H8 := H2 _ H7).\nelim H8; clear H8; intros t H8; exists t; apply (cond_fam f0); exists z0;\napply H8.\nunfold family_open_set; intro; simpl; unfold g';\nelim (classic (D x)); intro.\napply open_set_P6 with (union_domain (f0 x) (complementary F)).\napply open_set_P2.\nunfold family_open_set in H4; apply H4.\napply H0.\nunfold eq_Dom; split.\nunfold included, union_domain, complementary; intros.\nelim H6; intro; [ left; apply H7 | right; split; assumption ].\nunfold included, union_domain, complementary; intros.\nelim H6; intro; [ left; apply H7 | right; elim H7; intros; apply H8 ].\napply open_set_P6 with (f0 x).\nunfold family_open_set in H4; apply H4.\nunfold eq_Dom; split.\nunfold included, complementary; intros; left; apply H6.\nunfold included, complementary; intros.\nelim H6; intro.\napply H7.\nelim H7; intros _ H8; elim H5; apply H8.\nintros; elim H3; intros y0 H4; unfold g' in H4; elim H4; intro.\napply (cond_fam f0); exists y0; apply H5.\nelim H5; clear H5; intros _ H5; apply H5.\n\ncut (compact F).\nintro; apply (H3 f0 H2).\napply compact_eqDom with (fun _:R => False).\napply compact_EMP.\nunfold eq_Dom; split.\nunfold included; intros; elim H3.\nassert (H3 := not_ex_all_not _ _ Hyp_F_NE); unfold included; intros;\nelim (H3 x); apply H4.\nQed.\n\n\nLemma compact_P5 : forall X:R -> Prop, closed_set X -> bounded X -> compact X.\nProof. hammer_hook \"Rtopology\" \"Rtopology.compact_P5\".  \nintros; unfold bounded in H0.\nelim H0; clear H0; intros m H0.\nelim H0; clear H0; intros M H0.\nassert (H1 := compact_P3 m M).\napply (compact_P4 (fun c:R => m <= c <= M) X H1 H H0).\nQed.\n\n\nLemma compact_carac :\nforall X:R -> Prop, compact X <-> closed_set X /\\ bounded X.\nProof. hammer_hook \"Rtopology\" \"Rtopology.compact_carac\".  \nintro; split.\nintro; split; [ apply (compact_P2 _ H) | apply (compact_P1 _ H) ].\nintro; elim H; clear H; intros; apply (compact_P5 _ H H0).\nQed.\n\nDefinition image_dir (f:R -> R) (D:R -> Prop) (x:R) : Prop :=\nexists y : R, x = f y /\\ D y.\n\n\nLemma continuity_compact :\nforall (f:R -> R) (X:R -> Prop),\n(forall x:R, continuity_pt f x) -> compact X -> compact (image_dir f X).\nProof. hammer_hook \"Rtopology\" \"Rtopology.continuity_compact\".  \nunfold compact; intros; unfold covering_open_set in H1.\nelim H1; clear H1; intros.\nset (D := ind f1).\nset (g := fun x y:R => image_rec f0 (f1 x) y).\ncut (forall x:R, (exists y : R, g x y) -> D x).\nintro; set (f' := mkfamily D g H3).\ncut (covering_open_set X f').\nintro; elim (H0 f' H4); intros D' H5; exists D'.\nunfold covering_finite in H5; elim H5; clear H5; intros;\nunfold covering_finite; split.\nunfold covering, image_dir; simpl; unfold covering in H5;\nintros; elim H7; intros y H8; elim H8; intros; assert (H11 := H5 _ H10);\nsimpl in H11; elim H11; intros z H12; exists z; unfold g in H12;\nunfold image_rec in H12; rewrite H9; apply H12.\nunfold family_finite in H6; unfold domain_finite in H6;\nunfold family_finite; unfold domain_finite;\nelim H6; intros l H7; exists l; intro; elim (H7 x);\nintros; split; intro.\napply H8; simpl in H10; simpl; apply H10.\napply (H9 H10).\nunfold covering_open_set; split.\nunfold covering; intros; simpl; unfold covering in H1;\nunfold image_dir in H1; unfold g; unfold image_rec;\napply H1.\nexists x; split; [ reflexivity | apply H4 ].\nunfold family_open_set; unfold family_open_set in H2; intro;\nsimpl; unfold g;\ncut ((fun y:R => image_rec f0 (f1 x) y) = image_rec f0 (f1 x)).\nintro; rewrite H4.\napply (continuity_P2 f0 (f1 x) H (H2 x)).\nreflexivity.\nintros; apply (cond_fam f1); unfold g in H3; unfold image_rec in H3; elim H3;\nintros; exists (f0 x0); apply H4.\nQed.\n\nLemma prolongement_C0 :\nforall (f:R -> R) (a b:R),\na <= b ->\n(forall c:R, a <= c <= b -> continuity_pt f c) ->\nexists g : R -> R,\ncontinuity g /\\ (forall c:R, a <= c <= b -> g c = f c).\nProof. hammer_hook \"Rtopology\" \"Rtopology.prolongement_C0\".  \nintros; elim H; intro.\nset\n(h :=\nfun x:R =>\nmatch Rle_dec x a with\n| left _ => f0 a\n| right _ =>\nmatch Rle_dec x b with\n| left _ => f0 x\n| right _ => f0 b\nend\nend).\nassert (H2 : 0 < b - a).\napply Rlt_Rminus; assumption.\nexists h; split.\nunfold continuity; intro; case (Rtotal_order x a); intro.\nunfold continuity_pt; unfold continue_in;\nunfold limit1_in; unfold limit_in;\nsimpl; unfold R_dist; intros; exists (a - x);\nsplit.\nchange (0 < a - x); apply Rlt_Rminus; assumption.\nintros; elim H5; clear H5; intros _ H5; unfold h.\ncase (Rle_dec x a) as [|[]].\ncase (Rle_dec x0 a) as [|[]].\nunfold Rminus; rewrite Rplus_opp_r, Rabs_R0; assumption.\nleft; apply Rplus_lt_reg_l with (- x);\ndo 2 rewrite (Rplus_comm (- x)); apply Rle_lt_trans with (Rabs (x0 - x)).\napply RRle_abs.\nassumption.\nleft; assumption.\nelim H3; intro.\nassert (H5 : a <= a <= b).\nsplit; [ right; reflexivity | left; assumption ].\nassert (H6 := H0 _ H5); unfold continuity_pt in H6; unfold continue_in in H6;\nunfold limit1_in in H6; unfold limit_in in H6; simpl in H6;\nunfold R_dist in H6; unfold continuity_pt;\nunfold continue_in; unfold limit1_in;\nunfold limit_in; simpl; unfold R_dist;\nintros; elim (H6 _ H7); intros; exists (Rmin x0 (b - a));\nsplit.\nunfold Rmin; case (Rle_dec x0 (b - a)); intro.\nelim H8; intros; assumption.\nchange (0 < b - a); apply Rlt_Rminus; assumption.\nintros; elim H9; clear H9; intros _ H9; cut (x1 < b).\nintro; unfold h; case (Rle_dec x a) as [|[]].\ncase (Rle_dec x1 a) as [Hlta|Hnlea].\nunfold Rminus; rewrite Rplus_opp_r; rewrite Rabs_R0; assumption.\ncase (Rle_dec x1 b) as [Hleb|[]].\nelim H8; intros; apply H12; split.\nunfold D_x, no_cond; split.\ntrivial.\nred; intro; elim Hnlea; right; symmetry ; assumption.\napply Rlt_le_trans with (Rmin x0 (b - a)).\nrewrite H4 in H9; apply H9.\napply Rmin_l.\nleft; assumption.\nright; assumption.\napply Rplus_lt_reg_l with (- a); do 2 rewrite (Rplus_comm (- a));\nrewrite H4 in H9; apply Rle_lt_trans with (Rabs (x1 - a)).\napply RRle_abs.\napply Rlt_le_trans with (Rmin x0 (b - a)).\nassumption.\napply Rmin_r.\ncase (Rtotal_order x b); intro.\nassert (H6 : a <= x <= b).\nsplit; left; assumption.\nassert (H7 := H0 _ H6); unfold continuity_pt in H7; unfold continue_in in H7;\nunfold limit1_in in H7; unfold limit_in in H7; simpl in H7;\nunfold R_dist in H7; unfold continuity_pt;\nunfold continue_in; unfold limit1_in;\nunfold limit_in; simpl; unfold R_dist;\nintros; elim (H7 _ H8); intros; elim H9; clear H9;\nintros.\nassert (H11 : 0 < x - a).\napply Rlt_Rminus; assumption.\nassert (H12 : 0 < b - x).\napply Rlt_Rminus; assumption.\nexists (Rmin x0 (Rmin (x - a) (b - x))); split.\nunfold Rmin; case (Rle_dec (x - a) (b - x)) as [Hle|Hnle].\ncase (Rle_dec x0 (x - a)) as [Hlea|Hnlea].\nassumption.\nassumption.\ncase (Rle_dec x0 (b - x)) as [Hleb|Hnleb].\nassumption.\nassumption.\nintros x1 (H13,H14); cut (a < x1 < b).\nintro; elim H15; clear H15; intros; unfold h; case (Rle_dec x a) as [Hle|Hnle].\nelim (Rlt_irrefl _ (Rle_lt_trans _ _ _ Hle H4)).\ncase (Rle_dec x b) as [|[]].\ncase (Rle_dec x1 a) as [Hle0|].\nelim (Rlt_irrefl _ (Rle_lt_trans _ _ _ Hle0 H15)).\ncase (Rle_dec x1 b) as [|[]].\napply H10; split.\nassumption.\napply Rlt_le_trans with (Rmin x0 (Rmin (x - a) (b - x))).\nassumption.\napply Rmin_l.\nleft; assumption.\nleft; assumption.\nsplit.\napply Ropp_lt_cancel; apply Rplus_lt_reg_l with x;\napply Rle_lt_trans with (Rabs (x1 - x)).\nrewrite <- Rabs_Ropp; rewrite Ropp_minus_distr; apply RRle_abs.\napply Rlt_le_trans with (Rmin x0 (Rmin (x - a) (b - x))).\nassumption.\napply Rle_trans with (Rmin (x - a) (b - x)).\napply Rmin_r.\napply Rmin_l.\napply Rplus_lt_reg_l with (- x); do 2 rewrite (Rplus_comm (- x));\napply Rle_lt_trans with (Rabs (x1 - x)).\napply RRle_abs.\napply Rlt_le_trans with (Rmin x0 (Rmin (x - a) (b - x))).\nassumption.\napply Rle_trans with (Rmin (x - a) (b - x)); apply Rmin_r.\nelim H5; intro.\nassert (H7 : a <= b <= b).\nsplit; [ left; assumption | right; reflexivity ].\nassert (H8 := H0 _ H7); unfold continuity_pt in H8; unfold continue_in in H8;\nunfold limit1_in in H8; unfold limit_in in H8; simpl in H8;\nunfold R_dist in H8; unfold continuity_pt;\nunfold continue_in; unfold limit1_in;\nunfold limit_in; simpl; unfold R_dist;\nintros; elim (H8 _ H9); intros; exists (Rmin x0 (b - a));\nsplit.\nunfold Rmin; case (Rle_dec x0 (b - a)); intro.\nelim H10; intros; assumption.\nchange (0 < b - a); apply Rlt_Rminus; assumption.\nintros; elim H11; clear H11; intros _ H11; cut (a < x1).\nintro; unfold h; case (Rle_dec x a) as [Hlea|Hnlea].\nelim (Rlt_irrefl _ (Rle_lt_trans _ _ _ Hlea H4)).\ncase (Rle_dec x1 a) as [Hlea'|Hnlea'].\nelim (Rlt_irrefl _ (Rle_lt_trans _ _ _ Hlea' H12)).\ncase (Rle_dec x b) as [Hleb|Hnleb].\ncase (Rle_dec x1 b) as [Hleb'|Hnleb'].\nrewrite H6; elim H10; intros; destruct Hleb'.\napply H14; split.\nunfold D_x, no_cond; split.\ntrivial.\nred; intro; rewrite <- H16 in H15; elim (Rlt_irrefl _ H15).\nrewrite H6 in H11; apply Rlt_le_trans with (Rmin x0 (b - a)).\napply H11.\napply Rmin_l.\nrewrite H15; unfold Rminus; rewrite Rplus_opp_r; rewrite Rabs_R0;\nassumption.\nrewrite H6; unfold Rminus; rewrite Rplus_opp_r; rewrite Rabs_R0;\nassumption.\nelim Hnleb; right; assumption.\nrewrite H6 in H11; apply Ropp_lt_cancel; apply Rplus_lt_reg_l with b;\napply Rle_lt_trans with (Rabs (x1 - b)).\nrewrite <- Rabs_Ropp; rewrite Ropp_minus_distr; apply RRle_abs.\napply Rlt_le_trans with (Rmin x0 (b - a)).\nassumption.\napply Rmin_r.\nunfold continuity_pt; unfold continue_in;\nunfold limit1_in; unfold limit_in;\nsimpl; unfold R_dist; intros; exists (x - b);\nsplit.\nchange (0 < x - b); apply Rlt_Rminus; assumption.\nintros; elim H8; clear H8; intros.\nassert (H10 : b < x0).\napply Ropp_lt_cancel; apply Rplus_lt_reg_l with x;\napply Rle_lt_trans with (Rabs (x0 - x)).\nrewrite <- Rabs_Ropp; rewrite Ropp_minus_distr; apply RRle_abs.\nassumption.\nunfold h; case (Rle_dec x a) as [Hle|Hnle].\nelim (Rlt_irrefl _ (Rle_lt_trans _ _ _ Hle H4)).\ncase (Rle_dec x b) as [Hleb|Hnleb].\nelim (Rlt_irrefl _ (Rle_lt_trans _ _ _ Hleb H6)).\ncase (Rle_dec x0 a) as [Hlea'|Hnlea'].\nelim (Rlt_irrefl _ (Rlt_trans _ _ _ H1 (Rlt_le_trans _ _ _ H10 Hlea'))).\ncase (Rle_dec x0 b) as [Hleb'|Hnleb'].\nelim (Rlt_irrefl _ (Rle_lt_trans _ _ _ Hleb' H10)).\nunfold Rminus; rewrite Rplus_opp_r; rewrite Rabs_R0; assumption.\nintros; elim H3; intros; unfold h; case (Rle_dec c a) as [[|]|].\nelim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H4 H6)).\nrewrite H6; reflexivity.\ncase (Rle_dec c b) as [|[]].\nreflexivity.\nassumption.\nexists (fun _:R => f0 a); split.\napply derivable_continuous; apply (derivable_const (f0 a)).\nintros; elim H2; intros; rewrite H1 in H3; cut (b = c).\nintro; rewrite <- H5; rewrite H1; reflexivity.\napply Rle_antisym; assumption.\nQed.\n\n\nLemma continuity_ab_maj :\nforall (f:R -> R) (a b:R),\na <= b ->\n(forall c:R, a <= c <= b -> continuity_pt f c) ->\nexists Mx : R, (forall c:R, a <= c <= b -> f c <= f Mx) /\\ a <= Mx <= b.\nProof. hammer_hook \"Rtopology\" \"Rtopology.continuity_ab_maj\".  \nintros;\ncut\n(exists g : R -> R,\ncontinuity g /\\ (forall c:R, a <= c <= b -> g c = f0 c)).\nintro HypProl.\nelim HypProl; intros g Hcont_eq.\nelim Hcont_eq; clear Hcont_eq; intros Hcont Heq.\nassert (H1 := compact_P3 a b).\nassert (H2 := continuity_compact g (fun c:R => a <= c <= b) Hcont H1).\nassert (H3 := compact_P2 _ H2).\nassert (H4 := compact_P1 _ H2).\ncut (bound (image_dir g (fun c:R => a <= c <= b))).\ncut (exists x : R, image_dir g (fun c:R => a <= c <= b) x).\nintros; assert (H7 := completeness _ H6 H5).\nelim H7; clear H7; intros M H7; cut (image_dir g (fun c:R => a <= c <= b) M).\nintro; unfold image_dir in H8; elim H8; clear H8; intros Mxx H8; elim H8;\nclear H8; intros; exists Mxx; split.\nintros; rewrite <- (Heq c H10); rewrite <- (Heq Mxx H9); intros;\nrewrite <- H8; unfold is_lub in H7; elim H7; clear H7;\nintros H7 _; unfold is_upper_bound in H7; apply H7;\nunfold image_dir; exists c; split; [ reflexivity | apply H10 ].\napply H9.\nelim (classic (image_dir g (fun c:R => a <= c <= b) M)); intro.\nassumption.\ncut\n(exists eps : posreal,\n(forall y:R,\n~\nintersection_domain (disc M eps)\n(image_dir g (fun c:R => a <= c <= b)) y)).\nintro; elim H9; clear H9; intros eps H9; unfold is_lub in H7; elim H7;\nclear H7; intros;\ncut (is_upper_bound (image_dir g (fun c:R => a <= c <= b)) (M - eps)).\nintro; assert (H12 := H10 _ H11); cut (M - eps < M).\nintro; elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H12 H13)).\npattern M at 2; rewrite <- Rplus_0_r; unfold Rminus;\napply Rplus_lt_compat_l; apply Ropp_lt_cancel; rewrite Ropp_0;\nrewrite Ropp_involutive; apply (cond_pos eps).\nunfold is_upper_bound, image_dir; intros; cut (x <= M).\nintro; destruct (Rle_dec x (M - eps)) as [H13|].\napply H13.\nelim (H9 x); unfold intersection_domain, disc, image_dir; split.\nrewrite <- Rabs_Ropp; rewrite Ropp_minus_distr; rewrite Rabs_right.\napply Rplus_lt_reg_l with (x - eps);\nreplace (x - eps + (M - x)) with (M - eps).\nreplace (x - eps + eps) with x.\nauto with real.\nring.\nring.\napply Rge_minus; apply Rle_ge; apply H12.\napply H11.\napply H7; apply H11.\ncut\n(exists V : R -> Prop,\nneighbourhood V M /\\\n(forall y:R,\n~ intersection_domain V (image_dir g (fun c:R => a <= c <= b)) y)).\nintro; elim H9; intros V H10; elim H10; clear H10; intros.\nunfold neighbourhood in H10; elim H10; intros del H12; exists del; intros;\nred; intro; elim (H11 y).\nunfold intersection_domain; unfold intersection_domain in H13;\nelim H13; clear H13; intros; split.\napply (H12 _ H13).\napply H14.\ncut (~ point_adherent (image_dir g (fun c:R => a <= c <= b)) M).\nintro; unfold point_adherent in H9.\nassert\n(H10 :=\nnot_all_ex_not _\n(fun V:R -> Prop =>\nneighbourhood V M ->\nexists y : R,\nintersection_domain V (image_dir g (fun c:R => a <= c <= b)) y) H9).\nelim H10; intros V0 H11; exists V0; assert (H12 := imply_to_and _ _ H11);\nelim H12; clear H12; intros.\nsplit.\napply H12.\napply (not_ex_all_not _ _ H13).\nred; intro; cut (adherence (image_dir g (fun c:R => a <= c <= b)) M).\nintro; elim (closed_set_P1 (image_dir g (fun c:R => a <= c <= b)));\nintros H11 _; assert (H12 := H11 H3).\nelim H8.\nunfold eq_Dom in H12; elim H12; clear H12; intros.\napply (H13 _ H10).\napply H9.\nexists (g a); unfold image_dir; exists a; split.\nreflexivity.\nsplit; [ right; reflexivity | apply H ].\nunfold bound; unfold bounded in H4; elim H4; clear H4; intros m H4;\nelim H4; clear H4; intros M H4; exists M; unfold is_upper_bound;\nintros; elim (H4 _ H5); intros _ H6; apply H6.\napply prolongement_C0; assumption.\nQed.\n\n\nLemma continuity_ab_min :\nforall (f:R -> R) (a b:R),\na <= b ->\n(forall c:R, a <= c <= b -> continuity_pt f c) ->\nexists mx : R, (forall c:R, a <= c <= b -> f mx <= f c) /\\ a <= mx <= b.\nProof. hammer_hook \"Rtopology\" \"Rtopology.continuity_ab_min\".  \nintros.\ncut (forall c:R, a <= c <= b -> continuity_pt (- f0) c).\nintro; assert (H2 := continuity_ab_maj (- f0)%F a b H H1); elim H2;\nintros x0 H3; exists x0; intros; split.\nintros; rewrite <- (Ropp_involutive (f0 x0));\nrewrite <- (Ropp_involutive (f0 c)); apply Ropp_le_contravar;\nelim H3; intros; unfold opp_fct in H5; apply H5; apply H4.\nelim H3; intros; assumption.\nintros.\nassert (H2 := H0 _ H1).\napply (continuity_pt_opp _ _ H2).\nQed.\n\n\n\n\n\n\nDefinition ValAdh (un:nat -> R) (x:R) : Prop :=\nforall (V:R -> Prop) (N:nat),\nneighbourhood V x ->  exists p : nat, (N <= p)%nat /\\ V (un p).\n\nDefinition intersection_family (f:family) (x:R) : Prop :=\nforall y:R, ind f y -> f y x.\n\nLemma ValAdh_un_exists :\nforall (un:nat -> R) (D:=fun x:R =>  exists n : nat, x = INR n)\n(f:=\nfun x:R =>\nadherence\n(fun y:R => (exists p : nat, y = un p /\\ x <= INR p) /\\ D x))\n(x:R), (exists y : R, f x y) -> D x.\nProof. hammer_hook \"Rtopology\" \"Rtopology.ValAdh_un_exists\".  \nintros; elim H; intros; unfold f in H0; unfold adherence in H0;\nunfold point_adherent in H0;\nassert (H1 : neighbourhood (disc x0 (mkposreal _ Rlt_0_1)) x0).\nunfold neighbourhood, disc; exists (mkposreal _ Rlt_0_1);\nunfold included; trivial.\nelim (H0 _ H1); intros; unfold intersection_domain in H2; elim H2; intros;\nelim H4; intros; apply H6.\nQed.\n\nDefinition ValAdh_un (un:nat -> R) : R -> Prop :=\nlet D := fun x:R =>  exists n : nat, x = INR n in\nlet f :=\nfun x:R =>\nadherence\n(fun y:R => (exists p : nat, y = un p /\\ x <= INR p) /\\ D x) in\nintersection_family (mkfamily D f (ValAdh_un_exists un)).\n\nLemma ValAdh_un_prop :\nforall (un:nat -> R) (x:R), ValAdh un x <-> ValAdh_un un x.\nProof. hammer_hook \"Rtopology\" \"Rtopology.ValAdh_un_prop\".  \nintros; split; intro.\nunfold ValAdh in H; unfold ValAdh_un;\nunfold intersection_family; simpl;\nintros; elim H0; intros N H1; unfold adherence;\nunfold point_adherent; intros; elim (H V N H2);\nintros; exists (un x0); unfold intersection_domain;\nelim H3; clear H3; intros; split.\nassumption.\nsplit.\nexists x0; split; [ reflexivity | rewrite H1; apply (le_INR _ _ H3) ].\nexists N; assumption.\nunfold ValAdh; intros; unfold ValAdh_un in H;\nunfold intersection_family in H; simpl in H;\nassert\n(H1 :\nadherence\n(fun y0:R =>\n(exists p : nat, y0 = un p /\\ INR N <= INR p) /\\\n(exists n : nat, INR N = INR n)) x).\napply H; exists N; reflexivity.\nunfold adherence in H1; unfold point_adherent in H1; assert (H2 := H1 _ H0);\nelim H2; intros; unfold intersection_domain in H3;\nelim H3; clear H3; intros; elim H4; clear H4; intros;\nelim H4; clear H4; intros; elim H4; clear H4; intros;\nexists x1; split.\napply (INR_le _ _ H6).\nrewrite H4 in H3; apply H3.\nQed.\n\nLemma adherence_P4 :\nforall F G:R -> Prop, included F G -> included (adherence F) (adherence G).\nProof. hammer_hook \"Rtopology\" \"Rtopology.adherence_P4\".  \nunfold adherence, included; unfold point_adherent; intros;\nelim (H0 _ H1); unfold intersection_domain;\nintros; elim H2; clear H2; intros; exists x0; split;\n[ assumption | apply (H _ H3) ].\nQed.\n\nDefinition family_closed_set (f:family) : Prop :=\nforall x:R, closed_set (f x).\n\nDefinition intersection_vide_in (D:R -> Prop) (f:family) : Prop :=\nforall x:R,\n(ind f x -> included (f x) D) /\\\n~ (exists y : R, intersection_family f y).\n\nDefinition intersection_vide_finite_in (D:R -> Prop)\n(f:family) : Prop := intersection_vide_in D f /\\ family_finite f.\n\n\nLemma compact_P6 :\nforall X:R -> Prop,\ncompact X ->\n(exists z : R, X z) ->\nforall g:family,\nfamily_closed_set g ->\nintersection_vide_in X g ->\nexists D : R -> Prop, intersection_vide_finite_in X (subfamily g D).\nProof. hammer_hook \"Rtopology\" \"Rtopology.compact_P6\".  \nintros X H Hyp g H0 H1.\nset (D' := ind g).\nset (f' := fun x y:R => complementary (g x) y /\\ D' x).\nassert (H2 : forall x:R, (exists y : R, f' x y) -> D' x).\nintros; elim H2; intros; unfold f' in H3; elim H3; intros; assumption.\nset (f0 := mkfamily D' f' H2).\nunfold compact in H; assert (H3 : covering_open_set X f0).\nunfold covering_open_set; split.\nunfold covering; intros; unfold intersection_vide_in in H1;\nelim (H1 x); intros; unfold intersection_family in H5;\nassert\n(H6 := not_ex_all_not _ (fun y:R => forall y0:R, ind g y0 -> g y0 y) H5 x);\nassert (H7 := not_all_ex_not _ (fun y0:R => ind g y0 -> g y0 x) H6);\nelim H7; intros; exists x0; elim (imply_to_and _ _ H8);\nintros; unfold f0; simpl; unfold f';\nsplit; [ apply H10 | apply H9 ].\nunfold family_open_set; intro; elim (classic (D' x)); intro.\napply open_set_P6 with (complementary (g x)).\nunfold family_closed_set in H0; unfold closed_set in H0; apply H0.\nunfold f0; simpl; unfold f'; unfold eq_Dom;\nsplit.\nunfold included; intros; split; [ apply H4 | apply H3 ].\nunfold included; intros; elim H4; intros; assumption.\napply open_set_P6 with (fun _:R => False).\napply open_set_P4.\nunfold eq_Dom; unfold included; split; intros;\n[ elim H4\n| simpl in H4; unfold f' in H4; elim H4; intros; elim H3; assumption ].\nelim (H _ H3); intros SF H4; exists SF;\nunfold intersection_vide_finite_in; split.\nunfold intersection_vide_in; simpl; intros; split.\nintros; unfold included; intros; unfold intersection_vide_in in H1;\nelim (H1 x); intros; elim H6; intros; apply H7.\nunfold intersection_domain in H5; elim H5; intros; assumption.\nassumption.\nelim (classic (exists y : R, intersection_domain (ind g) SF y)); intro Hyp'.\nred; intro; elim H5; intros; unfold intersection_family in H6;\nsimpl in H6.\ncut (X x0).\nintro; unfold covering_finite in H4; elim H4; clear H4; intros H4 _;\nunfold covering in H4; elim (H4 x0 H7); intros; simpl in H8;\nunfold intersection_domain in H6; cut (ind g x1 /\\ SF x1).\nintro; assert (H10 := H6 x1 H9); elim H10; clear H10; intros H10 _; elim H8;\nclear H8; intros H8 _; unfold f' in H8; unfold complementary in H8;\nelim H8; clear H8; intros H8 _; elim H8; assumption.\nsplit.\napply (cond_fam f0).\nexists x0; elim H8; intros; assumption.\nelim H8; intros; assumption.\nunfold intersection_vide_in in H1; elim Hyp'; intros; assert (H8 := H6 _ H7);\nelim H8; intros; cut (ind g x1).\nintro; elim (H1 x1); intros; apply H12.\napply H11.\napply H9.\napply (cond_fam g); exists x0; assumption.\nunfold covering_finite in H4; elim H4; clear H4; intros H4 _;\ncut (exists z : R, X z).\nintro; elim H5; clear H5; intros; unfold covering in H4; elim (H4 x0 H5);\nintros; simpl in H6; elim Hyp'; exists x1; elim H6;\nintros; unfold intersection_domain; split.\napply (cond_fam f0); exists x0; apply H7.\napply H8.\napply Hyp.\nunfold covering_finite in H4; elim H4; clear H4; intros;\nunfold family_finite in H5; unfold domain_finite in H5;\nunfold family_finite; unfold domain_finite;\nelim H5; clear H5; intros l H5; exists l; intro; elim (H5 x);\nintros; split; intro;\n[ apply H6; simpl; simpl in H8; apply H8 | apply (H7 H8) ].\nQed.\n\nTheorem Bolzano_Weierstrass :\nforall (un:nat -> R) (X:R -> Prop),\ncompact X -> (forall n:nat, X (un n)) ->  exists l : R, ValAdh un l.\nProof. hammer_hook \"Rtopology\" \"Rtopology.Bolzano_Weierstrass\".  \nintros; cut (exists l : R, ValAdh_un un l).\nintro; elim H1; intros; exists x; elim (ValAdh_un_prop un x); intros;\napply (H4 H2).\nassert (H1 :  exists z : R, X z).\nexists (un 0%nat); apply H0.\nset (D := fun x:R =>  exists n : nat, x = INR n).\nset\n(g :=\nfun x:R =>\nadherence (fun y:R => (exists p : nat, y = un p /\\ x <= INR p) /\\ D x)).\nassert (H2 : forall x:R, (exists y : R, g x y) -> D x).\nintros; elim H2; intros; unfold g in H3; unfold adherence in H3;\nunfold point_adherent in H3.\nassert (H4 : neighbourhood (disc x0 (mkposreal _ Rlt_0_1)) x0).\nunfold neighbourhood; exists (mkposreal _ Rlt_0_1);\nunfold included; trivial.\nelim (H3 _ H4); intros; unfold intersection_domain in H5; decompose [and] H5;\nassumption.\nset (f0 := mkfamily D g H2).\nassert (H3 := compact_P6 X H H1 f0).\nelim (classic (exists l : R, ValAdh_un un l)); intro.\nassumption.\ncut (family_closed_set f0).\nintro; cut (intersection_vide_in X f0).\nintro; assert (H7 := H3 H5 H6).\nelim H7; intros SF H8; unfold intersection_vide_finite_in in H8; elim H8;\nclear H8; intros; unfold intersection_vide_in in H8;\nelim (H8 0); intros _ H10; elim H10; unfold family_finite in H9;\nunfold domain_finite in H9; elim H9; clear H9; intros l H9;\nset (r := MaxRlist l); cut (D r).\nintro; unfold D in H11; elim H11; intros; exists (un x);\nunfold intersection_family; simpl;\nunfold intersection_domain; intros; split.\nunfold g; apply adherence_P1; split.\nexists x; split;\n[ reflexivity\n| rewrite <- H12; unfold r; apply MaxRlist_P1; elim (H9 y); intros;\napply H14; simpl; apply H13 ].\nelim H13; intros; assumption.\nelim H13; intros; assumption.\nelim (H9 r); intros.\nsimpl in H12; unfold intersection_domain in H12; cut (In r l).\nintro; elim (H12 H13); intros; assumption.\nunfold r; apply MaxRlist_P2;\ncut (exists z : R, intersection_domain (ind f0) SF z).\nintro; elim H13; intros; elim (H9 x); intros; simpl in H15;\nassert (H17 := H15 H14); exists x; apply H17.\nelim (classic (exists z : R, intersection_domain (ind f0) SF z)); intro.\nassumption.\nelim (H8 0); intros _ H14; elim H1; intros;\nassert\n(H16 :=\nnot_ex_all_not _ (fun y:R => intersection_family (subfamily f0 SF) y) H14);\nassert\n(H17 :=\nnot_ex_all_not _ (fun z:R => intersection_domain (ind f0) SF z) H13);\nassert (H18 := H16 x); unfold intersection_family in H18;\nsimpl in H18;\nassert\n(H19 :=\nnot_all_ex_not _ (fun y:R => intersection_domain D SF y -> g y x /\\ SF y)\nH18); elim H19; intros; assert (H21 := imply_to_and _ _ H20);\nelim (H17 x0); elim H21; intros; assumption.\nunfold intersection_vide_in; intros; split.\nintro; simpl in H6; unfold f0; simpl; unfold g;\napply included_trans with (adherence X).\napply adherence_P4.\nunfold included; intros; elim H7; intros; elim H8; intros; elim H10;\nintros; rewrite H11; apply H0.\napply adherence_P2; apply compact_P2; assumption.\napply H4.\nunfold family_closed_set; unfold f0; simpl;\nunfold g; intro; apply adherence_P3.\nQed.\n\n\n\n\n\nDefinition uniform_continuity (f:R -> R) (X:R -> Prop) : Prop :=\nforall eps:posreal,\nexists delta : posreal,\n(forall x y:R,\nX x -> X y -> Rabs (x - y) < delta -> Rabs (f x - f y) < eps).\n\nLemma is_lub_u :\nforall (E:R -> Prop) (x y:R), is_lub E x -> is_lub E y -> x = y.\nProof. hammer_hook \"Rtopology\" \"Rtopology.is_lub_u\".  \nunfold is_lub; intros; elim H; elim H0; intros; apply Rle_antisym;\n[ apply (H4 _ H1) | apply (H2 _ H3) ].\nQed.\n\nLemma domain_P1 :\nforall X:R -> Prop,\n~ (exists y : R, X y) \\/\n(exists y : R, X y /\\ (forall x:R, X x -> x = y)) \\/\n(exists x : R, (exists y : R, X x /\\ X y /\\ x <> y)).\nProof. hammer_hook \"Rtopology\" \"Rtopology.domain_P1\".  \nintro; elim (classic (exists y : R, X y)); intro.\nright; elim H; intros; elim (classic (exists y : R, X y /\\ y <> x)); intro.\nright; elim H1; intros; elim H2; intros; exists x; exists x0; intros.\nsplit;\n[ assumption\n| split; [ assumption | apply (not_eq_sym (A:=R)); assumption ] ].\nleft; exists x; split.\nassumption.\nintros; case (Req_dec x0 x); intro.\nassumption.\nelim H1; exists x0; split; assumption.\nleft; assumption.\nQed.\n\nTheorem Heine :\nforall (f:R -> R) (X:R -> Prop),\ncompact X ->\n(forall x:R, X x -> continuity_pt f x) -> uniform_continuity f X.\nProof. hammer_hook \"Rtopology\" \"Rtopology.Heine\".  \nintros f0 X H0 H; elim (domain_P1 X); intro Hyp.\n\nunfold uniform_continuity; intros; exists (mkposreal _ Rlt_0_1);\nintros; elim Hyp; exists x; assumption.\nelim Hyp; clear Hyp; intro Hyp.\n\nunfold uniform_continuity; intros; exists (mkposreal _ Rlt_0_1);\nintros; elim Hyp; clear Hyp; intros; elim H4; clear H4;\nintros; assert (H6 := H5 _ H1); assert (H7 := H5 _ H2);\nrewrite H6; rewrite H7; unfold Rminus; rewrite Rplus_opp_r;\nrewrite Rabs_R0; apply (cond_pos eps).\n\nassert\n(X_enc :\nexists m : R, (exists M : R, (forall x:R, X x -> m <= x <= M) /\\ m < M)).\nassert (H1 := compact_P1 X H0); unfold bounded in H1; elim H1; intros;\nelim H2; intros; exists x; exists x0; split.\napply H3.\nelim Hyp; intros; elim H4; intros; decompose [and] H5;\nassert (H10 := H3 _ H6); assert (H11 := H3 _ H8);\nelim H10; intros; elim H11; intros;\ndestruct (total_order_T x x0) as [[|H15]|H15].\nassumption.\nrewrite H15 in H13, H7; elim H9; apply Rle_antisym;\napply Rle_trans with x0; assumption.\nelim (Rlt_irrefl _ (Rle_lt_trans _ _ _ (Rle_trans _ _ _ H13 H14) H15)).\nelim X_enc; clear X_enc; intros m X_enc; elim X_enc; clear X_enc;\nintros M X_enc; elim X_enc; clear X_enc Hyp; intros X_enc Hyp;\nunfold uniform_continuity; intro;\nassert (H1 : forall t:posreal, 0 < t / 2).\nintro; unfold Rdiv; apply Rmult_lt_0_compat;\n[ apply (cond_pos t) | apply Rinv_0_lt_compat; prove_sup0 ].\nset\n(g :=\nfun x y:R =>\nX x /\\\n(exists del : posreal,\n(forall z:R, Rabs (z - x) < del -> Rabs (f0 z - f0 x) < eps / 2) /\\\nis_lub\n(fun zeta:R =>\n0 < zeta <= M - m /\\\n(forall z:R, Rabs (z - x) < zeta -> Rabs (f0 z - f0 x) < eps / 2))\ndel /\\ disc x (mkposreal (del / 2) (H1 del)) y)).\nassert (H2 : forall x:R, (exists y : R, g x y) -> X x).\nintros; elim H2; intros; unfold g in H3; elim H3; clear H3; intros H3 _;\napply H3.\nset (f' := mkfamily X g H2); unfold compact in H0;\nassert (H3 : covering_open_set X f').\nunfold covering_open_set; split.\nunfold covering; intros; exists x; simpl; unfold g;\nsplit.\nassumption.\nassert (H4 := H _ H3); unfold continuity_pt in H4; unfold continue_in in H4;\nunfold limit1_in in H4; unfold limit_in in H4; simpl in H4;\nunfold R_dist in H4; elim (H4 (eps / 2) (H1 eps));\nintros;\nset\n(E :=\nfun zeta:R =>\n0 < zeta <= M - m /\\\n(forall z:R, Rabs (z - x) < zeta -> Rabs (f0 z - f0 x) < eps / 2));\nassert (H6 : bound E).\nunfold bound; exists (M - m); unfold is_upper_bound;\nunfold E; intros; elim H6; clear H6; intros H6 _;\nelim H6; clear H6; intros _ H6; apply H6.\nassert (H7 :  exists x : R, E x).\nelim H5; clear H5; intros; exists (Rmin x0 (M - m)); unfold E; intros;\nsplit.\nsplit.\nunfold Rmin; case (Rle_dec x0 (M - m)); intro.\napply H5.\napply Rlt_Rminus; apply Hyp.\napply Rmin_r.\nintros; case (Req_dec x z); intro.\nrewrite H9; unfold Rminus; rewrite Rplus_opp_r; rewrite Rabs_R0;\napply (H1 eps).\napply H7; split.\nunfold D_x, no_cond; split; [ trivial | assumption ].\napply Rlt_le_trans with (Rmin x0 (M - m)); [ apply H8 | apply Rmin_l ].\ndestruct (completeness _ H6 H7) as (x1,p).\ncut (0 < x1 <= M - m).\nintros (H8,H9); exists (mkposreal _ H8); split.\nintros; cut (exists alp : R, Rabs (z - x) < alp <= x1 /\\ E alp).\nintros; elim H11; intros; elim H12; clear H12; intros; unfold E in H13;\nelim H13; intros; apply H15.\nelim H12; intros; assumption.\nelim (classic (exists alp : R, Rabs (z - x) < alp <= x1 /\\ E alp)); intro.\nassumption.\nassert\n(H12 :=\nnot_ex_all_not _ (fun alp:R => Rabs (z - x) < alp <= x1 /\\ E alp) H11);\nunfold is_lub in p; elim p; intros; cut (is_upper_bound E (Rabs (z - x))).\nintro; assert (H16 := H14 _ H15);\nelim (Rlt_irrefl _ (Rlt_le_trans _ _ _ H10 H16)).\nunfold is_upper_bound; intros; unfold is_upper_bound in H13;\nassert (H16 := H13 _ H15); case (Rle_dec x2 (Rabs (z - x)));\nintro.\nassumption.\nelim (H12 x2); split; [ split; [ auto with real | assumption ] | assumption ].\nsplit.\napply p.\nunfold disc; unfold Rminus; rewrite Rplus_opp_r;\nrewrite Rabs_R0; simpl; unfold Rdiv;\napply Rmult_lt_0_compat; [ apply H8 | apply Rinv_0_lt_compat; prove_sup0 ].\nelim H7; intros; unfold E in H8; elim H8; intros H9 _; elim H9; intros H10 _;\nunfold is_lub in p; elim p; intros; unfold is_upper_bound in H12;\nunfold is_upper_bound in H11; split.\napply Rlt_le_trans with x2; [ assumption | apply (H11 _ H8) ].\napply H12; intros; unfold E in H13; elim H13; intros; elim H14; intros;\nassumption.\nunfold family_open_set; intro; simpl; elim (classic (X x));\nintro.\nunfold g; unfold open_set; intros; elim H4; clear H4;\nintros _ H4; elim H4; clear H4; intros; elim H4; clear H4;\nintros; unfold neighbourhood; case (Req_dec x x0);\nintro.\nexists (mkposreal _ (H1 x1)); rewrite <- H6; unfold included; intros;\nsplit.\nassumption.\nexists x1; split.\napply H4.\nsplit.\nelim H5; intros; apply H8.\napply H7.\nset (d := x1 / 2 - Rabs (x0 - x)); assert (H7 : 0 < d).\nunfold d; apply Rlt_Rminus; elim H5; clear H5; intros;\nunfold disc in H7; apply H7.\nexists (mkposreal _ H7); unfold included; intros; split.\nassumption.\nexists x1; split.\napply H4.\nelim H5; intros; split.\nassumption.\nunfold disc in H8; simpl in H8; unfold disc; simpl;\nunfold disc in H10; simpl in H10;\napply Rle_lt_trans with (Rabs (x2 - x0) + Rabs (x0 - x)).\nreplace (x2 - x) with (x2 - x0 + (x0 - x)); [ apply Rabs_triang | ring ].\nreplace (x1 / 2) with (d + Rabs (x0 - x)); [ idtac | unfold d; ring ].\ndo 2 rewrite <- (Rplus_comm (Rabs (x0 - x))); apply Rplus_lt_compat_l;\napply H8.\napply open_set_P6 with (fun _:R => False).\napply open_set_P4.\nunfold eq_Dom; unfold included; intros; split.\nintros; elim H4.\nintros; unfold g in H4; elim H4; clear H4; intros H4 _; elim H3; apply H4.\nelim (H0 _ H3); intros DF H4; unfold covering_finite in H4; elim H4; clear H4;\nintros; unfold family_finite in H5; unfold domain_finite in H5;\nunfold covering in H4; simpl in H4; simpl in H5; elim H5;\nclear H5; intros l H5; unfold intersection_domain in H5;\ncut\n(forall x:R,\nIn x l ->\nexists del : R,\n0 < del /\\\n(forall z:R, Rabs (z - x) < del -> Rabs (f0 z - f0 x) < eps / 2) /\\\nincluded (g x) (fun z:R => Rabs (z - x) < del / 2)).\nintros;\nassert\n(H7 :=\nRlist_P1 l\n(fun x del:R =>\n0 < del /\\\n(forall z:R, Rabs (z - x) < del -> Rabs (f0 z - f0 x) < eps / 2) /\\\nincluded (g x) (fun z:R => Rabs (z - x) < del / 2)) H6);\nelim H7; clear H7; intros l' H7; elim H7; clear H7;\nintros; set (D := MinRlist l'); cut (0 < D / 2).\nintro; exists (mkposreal _ H9); intros; assert (H13 := H4 _ H10); elim H13;\nclear H13; intros xi H13; assert (H14 : In xi l).\nunfold g in H13; decompose [and] H13; elim (H5 xi); intros; apply H14; split;\nassumption.\nelim (pos_Rl_P2 l xi); intros H15 _; elim (H15 H14); intros i H16; elim H16;\nintros; apply Rle_lt_trans with (Rabs (f0 x - f0 xi) + Rabs (f0 xi - f0 y)).\nreplace (f0 x - f0 y) with (f0 x - f0 xi + (f0 xi - f0 y));\n[ apply Rabs_triang | ring ].\nrewrite (double_var eps); apply Rplus_lt_compat.\nassert (H19 := H8 i H17); elim H19; clear H19; intros; rewrite <- H18 in H20;\nelim H20; clear H20; intros; apply H20; unfold included in H21;\napply Rlt_trans with (pos_Rl l' i / 2).\napply H21.\nelim H13; clear H13; intros; assumption.\nunfold Rdiv; apply Rmult_lt_reg_l with 2.\nprove_sup0.\nrewrite Rmult_comm; rewrite Rmult_assoc; rewrite <- Rinv_l_sym.\nrewrite Rmult_1_r; pattern (pos_Rl l' i) at 1; rewrite <- Rplus_0_r;\nrewrite double; apply Rplus_lt_compat_l; apply H19.\ndiscrR.\nassert (H19 := H8 i H17); elim H19; clear H19; intros; rewrite <- H18 in H20;\nelim H20; clear H20; intros; rewrite <- Rabs_Ropp;\nrewrite Ropp_minus_distr; apply H20; unfold included in H21;\nelim H13; intros; assert (H24 := H21 x H22);\napply Rle_lt_trans with (Rabs (y - x) + Rabs (x - xi)).\nreplace (y - xi) with (y - x + (x - xi)); [ apply Rabs_triang | ring ].\nrewrite (double_var (pos_Rl l' i)); apply Rplus_lt_compat.\napply Rlt_le_trans with (D / 2).\nrewrite <- Rabs_Ropp; rewrite Ropp_minus_distr; apply H12.\nunfold Rdiv; do 2 rewrite <- (Rmult_comm (/ 2));\napply Rmult_le_compat_l.\nleft; apply Rinv_0_lt_compat; prove_sup0.\nunfold D; apply MinRlist_P1; elim (pos_Rl_P2 l' (pos_Rl l' i));\nintros; apply H26; exists i; split;\n[ rewrite <- H7; assumption | reflexivity ].\nassumption.\nunfold Rdiv; apply Rmult_lt_0_compat;\n[ unfold D; apply MinRlist_P2; intros; elim (pos_Rl_P2 l' y); intros;\nelim (H10 H9); intros; elim H12; intros; rewrite H14;\nrewrite <- H7 in H13; elim (H8 x H13); intros;\napply H15\n| apply Rinv_0_lt_compat; prove_sup0 ].\nintros; elim (H5 x); intros; elim (H8 H6); intros;\nset\n(E :=\nfun zeta:R =>\n0 < zeta <= M - m /\\\n(forall z:R, Rabs (z - x) < zeta -> Rabs (f0 z - f0 x) < eps / 2));\nassert (H11 : bound E).\nunfold bound; exists (M - m); unfold is_upper_bound;\nunfold E; intros; elim H11; clear H11; intros H11 _;\nelim H11; clear H11; intros _ H11; apply H11.\nassert (H12 :  exists x : R, E x).\nassert (H13 := H _ H9); unfold continuity_pt in H13;\nunfold continue_in in H13; unfold limit1_in in H13;\nunfold limit_in in H13; simpl in H13; unfold R_dist in H13;\nelim (H13 _ (H1 eps)); intros; elim H12; clear H12;\nintros; exists (Rmin x0 (M - m)); unfold E;\nintros; split.\nsplit;\n[ unfold Rmin; case (Rle_dec x0 (M - m)); intro;\n[ apply H12 | apply Rlt_Rminus; apply Hyp ]\n| apply Rmin_r ].\nintros; case (Req_dec x z); intro.\nrewrite H16; unfold Rminus; rewrite Rplus_opp_r; rewrite Rabs_R0;\napply (H1 eps).\napply H14; split;\n[ unfold D_x, no_cond; split; [ trivial | assumption ]\n| apply Rlt_le_trans with (Rmin x0 (M - m)); [ apply H15 | apply Rmin_l ] ].\ndestruct (completeness _ H11 H12) as (x0,p).\ncut (0 < x0 <= M - m).\nintro; elim H13; clear H13; intros; exists x0; split.\nassumption.\nsplit.\nintros; cut (exists alp : R, Rabs (z - x) < alp <= x0 /\\ E alp).\nintros; elim H16; intros; elim H17; clear H17; intros; unfold E in H18;\nelim H18; intros; apply H20; elim H17; intros; assumption.\nelim (classic (exists alp : R, Rabs (z - x) < alp <= x0 /\\ E alp)); intro.\nassumption.\nassert\n(H17 :=\nnot_ex_all_not _ (fun alp:R => Rabs (z - x) < alp <= x0 /\\ E alp) H16);\nunfold is_lub in p; elim p; intros; cut (is_upper_bound E (Rabs (z - x))).\nintro; assert (H21 := H19 _ H20);\nelim (Rlt_irrefl _ (Rlt_le_trans _ _ _ H15 H21)).\nunfold is_upper_bound; intros; unfold is_upper_bound in H18;\nassert (H21 := H18 _ H20); case (Rle_dec x1 (Rabs (z - x)));\nintro.\nassumption.\nelim (H17 x1); split.\nsplit; [ auto with real | assumption ].\nassumption.\nunfold included, g; intros; elim H15; intros; elim H17; intros;\ndecompose [and] H18; cut (x0 = x2).\nintro; rewrite H20; apply H22.\nunfold E in p; eapply is_lub_u.\napply p.\napply H21.\nelim H12; intros; unfold E in H13; elim H13; intros H14 _; elim H14;\nintros H15 _; unfold is_lub in p; elim p; intros;\nunfold is_upper_bound in H16; unfold is_upper_bound in H17;\nsplit.\napply Rlt_le_trans with x1; [ assumption | apply (H16 _ H13) ].\napply H17; intros; unfold E in H18; elim H18; intros; elim H19; intros;\nassumption.\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/Rtopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6835268119238249}}
{"text": "(* Software Foundations *)\n(* Exercice 1 star, ev_minus2_n *)\n\nInductive ev: nat -> Prop :=\n|ev_0: ev 0\n|ev_ss: forall n: nat, ev n -> ev (S (S n)).\n\n\nTheorem ev_minus2_n: forall n,\nev n -> ev (pred (pred n)).\n\nProof.\n    intros.\n    destruct H.\n    simpl. apply ev_0.\n    simpl. apply H.\nQed.\n\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter9_Library_Prop/ev_minus2_n.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6835139678697127}}
{"text": "(** * boolean: Booleans as a lattice, and as a monoid *)\n\nRequire Import monoid prop sups.\n\n(** * Booleans as a lattice *)\n\nCanonical Structure bool_lattice_ops: lattice.ops := {|\n  leq := le_bool;\n  weq := eq;\n  cup := orb;\n  cap := andb;\n  neg := negb;\n  bot := false;\n  top := true\n|}.\n\n(** [is_true] is a bounded distributive lattice homomorphism from [bool] to [Prop].\n   (Actually a Boolean lattice homomorphism, but we don't need it here.) *)\n#[export] Instance mm_bool_Prop: morphism BDL is_true.\nProof.\n  constructor; simpl.\n  now auto.\n  intros ? ?. now rewrite eq_bool_iff. \n  intros _ [|] [|]; firstorder. \n  intros _ [|] [|]; firstorder. \n  intros _. easy.\n  tauto.\n  intros _ [|]. firstorder auto with bool. easy.\nQed.\n\n(* #[export] Instance mm_negb l: morphism l bool_lops (dual_ops bool_ops) negb. *)\n\n(** we get most lattice laws by the faithful embedding into [Prop]  *)\n#[export] Instance bool_lattice_laws: lattice.laws (BL+STR+CNV+DIV) bool_lattice_ops.\nProof. \n  assert(H: lattice.laws BDL bool_lattice_ops).\n   apply (laws_of_injective_morphism is_true mm_bool_Prop).\n   auto. \n   intros x y. apply eq_bool_iff.\n  constructor; try apply H; (try now left); intros _ [|]; reflexivity. \nQed.\n\n(** simple characterisation of finite sups and infs in [bool] *)\n\nLemma is_true_sup I J (f: I -> bool): \\sup_(i\\in J) f i <-> (exists i, List.In i J /\\ f i).\nProof. \n  unfold is_true. induction J; simpl. firstorder; discriminate. \n  rewrite Bool.orb_true_iff. firstorder congruence. \nQed.\n\nLemma is_true_inf I J (f: I -> bool): \\inf_(i\\in J) f i <-> (forall i, List.In i J -> f i).\nProof. \n  unfold is_true. induction J; simpl. firstorder.\n  rewrite Bool.andb_true_iff. firstorder congruence. \nQed.\n\n\n\n\n(** * Boolean as a (flat) monoid\n   this is useful:\n   - to construct boolean matrices, \n   - to consider regex.epsilon as a functor) *)\n\n(** this monoid is flat: this is a one object category. \n   We use the following singleton type to avoid confusion with the\n   singleton types of other flat structures *)\nCoInductive bool_unit := bool_tt.\n\n(** note that the trivial type information is simply ignored *)\nCanonical Structure bool_ops: monoid.ops := {|\n  ob := bool_unit;\n  mor n m := bool_lattice_ops;\n  dot n m p := andb;\n  one n := true;\n  itr n x := x;\n  str n x := true;\n  cnv n m x := x;\n  ldv n m p x y := !x ⊔ y;\n  rdv n m p x y := !x ⊔ y\n|}.\n\n(** shorthand for [bool], when a morphism is expected *)\nNotation bool' := (bool_ops bool_tt bool_tt).\n\n(** we actually have all laws on [bool] *)\n#[export] Instance bool_laws: laws (BL+STR+CNV+DIV) bool_ops.\nProof.\n  constructor; (try now left);repeat right; intros.\n   apply bool_lattice_laws.\n   apply capA.\n   apply captx.\n   apply weq_leq. simpl. apply capC.\n   reflexivity.\n   now intros ? ? ?.\n   reflexivity.\n   all: try setoid_rewrite <- le_bool_spec.\n   all: try case x; try case y; try case z; reflexivity.\nQed.\n\n\n\n(** * properties of the [ofbool] injection *)\n\nSection ofbool.\n\nOpen Scope bool_scope.\nImplicit Types a b c: bool.\nContext {X: ops} {l} {L: laws l X} {n: ob X}.\nNotation ofbool := (@ofbool X n).\n\nLemma andb_dot `{BOT ≪ l} a b: ofbool (a&&b) ≡ ofbool a ⋅ ofbool b.\nProof. \n  symmetry. case a. apply dot1x. \n  apply antisym. now apply weq_leq, dot0x. apply leq_bx. \nQed.\n\nLemma orb_pls `{CUP+BOT ≪ l} a b: ofbool (a||b) ≡ ofbool a + ofbool b.\nProof. symmetry. case a; simpl. case b; simpl; lattice. lattice. Qed.\n\n#[export] Instance ofbool_leq `{BOT ≪ l}: Proper (leq ==> leq) ofbool.\nProof. intros [|] b E; simpl. now rewrite E. apply leq_bx. Qed.\n\nLemma dot_ofboolx `{BOT ≪ l} b (x: X n n): ofbool b⋅x ≡ x⋅ofbool b.\nProof. case b; simpl. now rewrite dot1x, dotx1. now rewrite dot0x, dotx0. Qed.\n\nEnd ofbool.\n\n(** [is_true] is also monotone *)\n#[export] Instance is_true_leq: Proper (leq ==> leq) is_true. \nProof. intros [|] b E; simpl. now rewrite E. discriminate. Qed.\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/boolean.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6835139676715576}}
{"text": "(** * Tactics: More Basic Tactics *)\n\n(** This chapter introduces several additional proof strategies\n    and tactics that allow us to begin proving more interesting\n    properties of functional programs.\n\n    We will see:\n    - how to use auxiliary lemmas in both \"forward-\" and\n      \"backward-style\" proofs;\n    - how to reason about data constructors -- in particular, how to\n      use the fact that they are injective and disjoint;\n    - how to strengthen an induction hypothesis, and when such\n      strengthening is required; and\n    - more details on how to reason by case analysis. *)\n\nSet Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export Poly.\n\n(* ################################################################# *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    _exactly_ the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m : nat),\n  n = m ->\n  n = m.\nProof.\n  intros n m eq.\n\n(** Here, we could finish with \"[rewrite -> eq.  reflexivity.]\" as we\n    have done several times before.  Alternatively, we can finish in\n    a single step by using the [apply] tactic: *)\n\n  apply eq.  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  (n = m -> [n;o] = [m;p]) ->\n  [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] that introduces some _universally quantified\n    variables_.  When Coq matches the current goal against the\n    conclusion of [H], it will try to find appropriate values for\n    these variables.  For example, when we do [apply eq2] in the\n    following proof, the universal variable [q] in [eq2] gets\n    instantiated with [n], and [r] gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n  (n,n) = (m,m)  ->\n  (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n  [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, standard, optional (silly_ex)\n\n    Complete the following proof 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 eq1 eq2 eq3 eq4.\n  apply eq3.\n  apply eq2.\n  apply eq4.\n  Qed.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal exactly (perhaps after\n    simplification) -- for example, [apply] will not work if the left\n    and right sides of the equality are swapped. *)\n\nTheorem silly3 : forall (n m : nat),\n  n = m ->\n  m = n.\nProof.\n  intros n m H.\n\n  (** Here we cannot use [apply] directly... *)\n\n  Fail apply H.\n\n  (** but we can use the [symmetry] tactic, which switches the left\n     and right sides of an equality in the goal. *)\n\n  symmetry. apply H.  Qed.\n\n(** **** Exercise: 2 stars, standard (apply_exercise1)\n\n    You can use [apply] with previously defined theorems, not\n    just hypotheses in the context.  Use [Search] to find a\n    previously-defined theorem about [rev] from [Lists].  Use\n    that theorem as part of your (relatively short) solution to this\n    exercise. You do not need [induction]. *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n  l = rev l' ->\n  l' = rev l.\nProof.\n  intros l l' eq.\n  rewrite -> eq.\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\n(** - [apply] cannot be applied instead of [rewrite <- H],\n      I should use [symmetry] before.\n    - [apply] automatically solves a goal.\n    - [apply] can work with conditional hypotheses. *)\n(** [] *)\n\n(* ################################################################# *)\n(** * The [apply with] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a;b]] to [[e;f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might like to pull it out as a\n    lemma that records, once and for all, the fact that equality is\n    transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to prove the above\n    example.  However, to do this we need a slight refinement of the\n    [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n\n(** If we simply tell Coq [apply trans_eq] at this point, it can\n    tell (by matching the goal against the conclusion of the lemma)\n    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and\n    [o] with [[e,f]].  However, the matching process doesn't determine\n    an instantiation for [m]: we have to supply one explicitly by\n    adding \"[with (m:=[c,d])]\" to the invocation of [apply]. *)\n\n  apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2.   Qed.\n\n(** Actually, the name [m] in the [with] clause is not required,\n    since Coq is often smart enough to figure out which variable we\n    are instantiating. We could instead simply write [apply trans_eq\n    with [c;d]]. *)\n\n(** Coq also has a built-in tactic [transitivity] that\n    accomplishes the same purpose as applying [trans_eq]. The tactic\n    requires us to state the instantiation we want, just like [apply\n    with] does. *)\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  transitivity [c;d].\n  apply eq1. apply eq2.   Qed.\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 eq1 eq2.\n  apply trans_eq with m. apply eq2. apply eq1.\nQed.\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    It is obvious from this definition that every number has one of\n    two forms: either it is the constructor [O] or it is built by\n    applying the constructor [S] to another number.  But there is more\n    here than meets the eye: implicit in the definition are two\n    additional 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 every inductively defined type:\n    all 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 nor\n    there.)  And so on. *)\n\n(** We can _prove_ the injectivity of [S] by using the [pred] function\n    defined in [Basics.v]. *)\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H1.\n  assert (H2: n = pred (S n)). { reflexivity. }\n  rewrite H2. rewrite H1. simpl. 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.\n\n    As a more convenient alternative, Coq provides a tactic called\n    [injection] that allows us to exploit the injectivity of any\n    constructor.  Here is an alternate proof of the above theorem\n    using [injection]: *)\n\nTheorem S_injective' : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n\n(** By writing [injection H 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\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(** **** Exercise: 3 stars, standard (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 eq1 eq2.\n  injection eq1 as H G.\n  rewrite eq2 in G.\n  injection G as G.\n  rewrite H. rewrite G.\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\n    with 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., [false = true]), and it solves the current\n    goal immediately.  Some examples: *)\n\nTheorem discriminate_ex1 : forall (n m : nat),\n  false = true ->\n  n = m.\nProof.\n  intros n m contra. discriminate contra. Qed.\n\nTheorem discriminate_ex2 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. discriminate contra. Qed.\n\n(** These examples are instances of a logical principle known as the\n    _principle of explosion_, which asserts that a contradictory\n    hypothesis entails anything (even manifestly false things!). *)\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.\n\n    We'll explore the principle of explosion in more detail in the\n    next chapter. *)\n\n(** **** Exercise: 1 star, standard (discriminate_ex3) *)\nExample discriminate_ex3 :\n  forall (X : Type) (x y z : X) (l j : list X),\n    x :: y :: l = [] ->\n    x = z.\nProof.\n  intros X x y z l j contra.\n  discriminate contra.\nQed.\n(** [] *)\n\n(** For a slightly more involved example, we can use [discriminate] to\n    make a connection between the two different notions of\n    equality ([=] and [=?]) on natural numbers. *)\nTheorem eqb_0_l : forall n,\n   0 =? n = true -> n = 0.\nProof.\n  intros n.\n\n(** We can proceed by case analysis on [n]. The first case is\n    trivial. *)\n\n  destruct n as [| n'] eqn:E.\n  - (* n = 0 *)\n    intros H. reflexivity.\n\n(** However, the second one doesn't look so simple: assuming [0\n    =? (S n') = true], we must show [S n' = 0]!  The way forward is to\n    observe that the assumption itself is nonsensical: *)\n\n  - (* n = S n' *)\n    simpl.\n\n(** If we use [discriminate] on this hypothesis, Coq confirms\n    that the subgoal we are working on is impossible and removes it\n    from further consideration. *)\n\n    intros H. discriminate H.\nQed.\n\n(** The injectivity of constructors allows us to reason that\n    [forall (n m : nat), S n = S m -> n = m].  The converse of this\n    implication is an instance of a more general fact about both\n    constructors and functions, which we will find convenient in a few\n    places below: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.\n\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(** There is also a tactic named `f_equal` that can prove such\n    theorems directly.  Given a goal of the form [f a1 ... an = g b1\n    ... bn], the tactic [f_equal] will produce subgoals of the form [f\n    = g], [a1 = b1], ..., [an = bn]. At the same time, any of these\n    subgoals that are simple enough (e.g., immediately provable by\n    [reflexivity]) will be automatically discharged by [f_equal]. *)\n\nTheorem eq_implies_succ_equal' : forall (n m : nat),\n  n = m -> S n = S m.\nProof. intros n m H. f_equal. apply H. Qed.\n\n(* ################################################################# *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic \"[simpl in H]\" performs simplification on\n    the hypothesis [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n  ((S n) =? (S m)) = b  ->\n  (n =? m) = b.\nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, [apply L in H] matches some conditional statement\n    [L] (of the form [X -> Y], say) against a hypothesis [H] in the\n    context.  However, unlike ordinary [apply] (which rewrites a goal\n    matching [Y] into a subgoal [X]), [apply L in H] matches [H]\n    against [X] and, if successful, replaces it with [Y].\n\n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\": given [X -> Y] and a hypothesis matching [X], it\n    produces a hypothesis matching [Y].\n\n    By contrast, [apply L] is \"backward reasoning\": it says that if we\n    know [X -> Y] and we are trying to prove [Y], it suffices to prove\n    [X].\n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\nTheorem silly4 : forall (n m p q : nat),\n  (n = m -> p = q) ->\n  m = n ->\n  q = p.\nProof.\n  intros n m p q EQ H.\n  symmetry in H. apply EQ in H. symmetry in H.\n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_ and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n\n    The informal proofs seen in math or computer science classes tend\n    to use forward reasoning.  By contrast, idiomatic use of Coq\n    generally favors backward reasoning, though in some situations the\n    forward style can be easier to think about. *)\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 sometimes need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose\n    we want to show that [double] is injective -- i.e., that it maps\n    different arguments to different results:\n\n       Theorem double_injective: forall n m,\n         double n = double m -> n = m.\n\n    The way we start this proof is a bit delicate: if we begin it with\n\n       intros n. induction n.\n\n    then all is well.  But if we begin it with introducing both variables\n\n       intros n m. induction n.\n\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n  double n = double m ->\n  n = m.\nProof.\n  intros n m. induction n as [| n' 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.\n\n(** At this point, the induction hypothesis ([IHn']) does _not_ give us\n    [n' = m'] -- there is an extra [S] in the way -- so the goal is\n    not provable. *)\n\nAbort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context --\n    intuitively, we have told Coq, \"Let's consider some particular [n]\n    and [m]...\" and we now have to prove that, if [double n = double\n    m] for _these particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove, for\n    _all_ [n], that the proposition\n\n      - [P n] = \"if [double n = double m], then [n = m]\"\n\n    holds, by showing\n\n      - [P O]\n\n         (i.e., \"if [double O = double m] then [O = m]\") and\n\n      - [P n -> P (S n)]\n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help at all with proving\n    [R]!  If we tried to prove [R] from [Q], we would start with\n    something like \"Suppose [double (S n) = 10]...\" but then we'd be\n    stuck: knowing that [double (S n)] is [10] tells us nothing\n    helpful about whether [double n] is [10] (indeed, it strongly\n    suggests that [double n] is _not_ [10]!!), so [Q] is useless. *)\n\n(** Trying to carry out this proof by induction on [n] when [m] is\n    already in the context doesn't work because we are then trying to\n    prove a statement involving _every_ [n] but just a _single_ [m]. *)\n\n(** A successful proof of [double_injective] leaves [m] universally\n    quantified in the goal statement at the point where the\n    [induction] tactic is invoked on [n]: *)\n\nTheorem double_injective : forall n m,\n  double n = double m ->\n  n = m.\nProof.\n  intros n. induction n as [| n' IHn'].\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' *)\n\n(** Notice that both the goal and the induction hypothesis are\n    different this time: the goal asks us to prove something more\n    general (i.e., we must prove the statement for _every_ [m]), but\n    the IH is correspondingly more flexible, allowing us to choose any\n    [m] we like when we apply the IH. *)\n\n    intros m eq.\n\n(** Now we've chosen a particular [m] and introduced the assumption\n    that [double n = double m].  Since we are doing a case analysis on\n    [n], we also need a case analysis on [m] to keep the two \"in sync.\" *)\n\n    destruct m as [| m'] eqn:E.\n    + (* m = O *)\n\n(** The 0 case is trivial: *)\n\n    discriminate eq.\n    + (* m = S m' *)\n      apply f_equal.\n\n(** At this point, since we are in the second branch of the [destruct\n    m], the [m'] mentioned in the context is the predecessor of the\n    [m] we started out talking about.  Since we are also in the [S]\n    branch of the induction, this is perfect: if we instantiate the\n    generic [m] in the IH with the current [m'] (this instantiation is\n    performed automatically by the [apply] in the next step), then\n    [IHn'] gives us exactly what we need to finish the proof. *)\n\n      apply IHn'. simpl in eq. injection eq as goal. apply goal. Qed.\n\n(** The thing to take away from all this is that you need to be\n    careful, when using induction, that you are not trying to prove\n    something too specific: When proving a property involving two\n    variables [n] and [m] by induction on [n], it is sometimes crucial\n    to leave [m] generic. *)\n\n(** The following exercise, which further strengthens the link between\n    [=?] and [=], follows the same pattern. *)\n\n(** **** Exercise: 2 stars, standard (eqb_true) *)\nTheorem eqb_true : forall n m,\n  n =? m = true -> n = m.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = O *)\n    destruct m.\n    + reflexivity.\n    + intros contra. discriminate contra.\n  - (* n = S n' *)\n    destruct m.\n    + intros contra. discriminate contra.\n    + intros H. apply IHn' in H.\n      rewrite -> H. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (eqb_true_informal)\n\n    Give a careful informal proof of [eqb_true], stating the induction\n    hypothesis explicitly and being as explicit as possible about\n    quantifiers, everywhere. *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_proof : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, especially useful (plus_n_n_injective)\n\n    In addition to being careful about how you use [intros], practice\n    using \"in\" variants 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 n. induction n as [| n'].\n  - (* n = 0 *)\n    destruct m.\n    + reflexivity.\n    + intros contra.\n      discriminate contra.\n  - (* n = S n' *)\n    destruct m.\n    + intros contra. discriminate contra.\n    + intros H.\n      rewrite <- plus_n_Sm in H.\n      rewrite <- plus_n_Sm in H.\n      injection H as H1.\n      apply IHn' in H1.\n      rewrite <- H1.\n      reflexivity.\nQed.\n(** [] *)\n\n(** The strategy of doing fewer [intros] before an [induction] to\n    obtain a more general IH doesn't always work by itself; sometimes\n    some _rearrangement_ of quantified variables is needed.  Suppose,\n    for example, that we wanted to prove [double_injective] by\n    induction on [m] instead of [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n  double n = double m ->\n  n = m.\nProof.\n  intros n m. induction m as [| m' IHm'].\n  - (* m = O *) simpl. intros eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) discriminate eq.\n  - (* m = S m' *) intros eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) discriminate eq.\n    + (* n = S n' *) apply f_equal.\n        (* We are stuck here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (And if we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce [n]\n    for us!)  *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    works, but it's not nice: We don't want to have to twist the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them!  Rather we want to state them in the clearest and\n    most natural way. *)\n\n(** What we can do instead is to first introduce all the quantified\n    variables and then _re-generalize_ one or more of them,\n    selectively taking variables out of the context and putting them\n    back at the beginning of the goal.  The [generalize dependent]\n    tactic does this. *)\n\nTheorem double_injective_take2 : forall n m,\n  double n = double m ->\n  n = m.\nProof.\n  intros n m.\n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m' IHm'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) discriminate eq.\n  - (* m = S m' *) intros n eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) discriminate eq.\n    + (* n = S n' *) apply f_equal.\n      apply IHm'. injection eq as goal. apply goal. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n    _Theorem_: For any nats [n] and [m], if [double n = double m], then\n      [n = m].\n\n    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n      any [n], if [double n = double m] then [n = m].\n\n      - First, suppose [m = 0], and suppose [n] is a number such\n        that [double n = double m].  We must show that [n = 0].\n\n        Since [m = 0], by the definition of [double] we have [double n =\n        0].  There are two cases to consider for [n].  If [n = 0] we are\n        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']\n        for some [n'], we derive a contradiction: by the definition of\n        [double], we can calculate [double n = S (S (double n'))], but\n        this contradicts the assumption that [double n = 0].\n\n      - Second, suppose [m = S m'] and that [n] is again a number such\n        that [double n = double m].  We must show that [n = S m'], with\n        the induction hypothesis that for every number [s], if [double s =\n        double m'] then [s = m'].\n\n        By the fact that [m = S m'] and the definition of [double], we\n        have [double n = S (S (double m'))].  There are two cases to\n        consider for [n].\n\n        If [n = 0], then by definition [double n = 0], a contradiction.\n\n        Thus, we may assume that [n = S n'] for some [n'], and again by\n        the definition of [double] we have [S (S (double n')) =\n        S (S (double m'))], which implies by injectivity that [double n' =\n        double m'].  Instantiating the induction hypothesis with [n'] thus\n        allows us to conclude that [n' = m'], and it follows immediately\n        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just\n        what we wanted to show. [] *)\n\n(** **** Exercise: 3 stars, standard, especially useful (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 as [| x l'].\n  - reflexivity.\n  - destruct n.\n    + intros contra. discriminate contra.\n    + intros H. injection H as H1. simpl. apply IHl' in H1. apply H1.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Unfolding Definitions *)\n\n(** It sometimes happens that we need to manually unfold a name that\n    has been introduced by a [Definition] so that we can manipulate\n    the expression it denotes.  For example, if we define... *)\n\nDefinition square n := n * n.\n\n(** ... and try to prove a simple fact about [square]... *)\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\n  simpl.\n\n(** ... we appear to be stuck: [simpl] doesn't simplify anything, and\n    since we haven't proved any other facts about [square], there is\n    nothing we can [apply] or [rewrite] with. *)\n\n(** To make progress, we can manually [unfold] the definition of\n    [square]: *)\n\n  unfold square.\n\n(** Now we have plenty to work with: both sides of the equality are\n    expressions involving multiplication, and we have lots of facts\n    about multiplication at our disposal.  In particular, we know that\n    it is commutative and associative, and from these it is not hard\n    to finish the proof. *)\n\n  rewrite mult_assoc.\n  assert (H : n * m * n = n * n * m).\n    { rewrite mul_comm. apply mult_assoc. }\n  rewrite H. rewrite mult_assoc. reflexivity.\nQed.\n\n(** At this point, some deeper discussion of unfolding and\n    simplification is in order.\n\n    We already have observed that tactics like [simpl], [reflexivity],\n    and [apply] will often unfold the definitions of functions\n    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\n    [reflexivity], if we omit the [simpl]) will unfold [foo m] to\n    [(fun x => 5) m] and then further simplify this expression to just\n    [5]. *)\n\nFact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.\nProof.\n  intros m.\n  simpl.\n  reflexivity.\nQed.\n\n(** But this automatic unfolding is somewhat conservative.  For\n    example, if we define a slightly more complicated function\n    involving a pattern match... *)\n\nDefinition bar x :=\n  match x with\n  | O => 5\n  | S _ => 5\n  end.\n\n(** ...then the analogous proof will get stuck: *)\n\nFact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  simpl. (* Does nothing! *)\nAbort.\n\n(** The reason that [simpl] doesn't make progress here is that it\n    notices that, after tentatively unfolding [bar m], it is left with\n    a match whose scrutinee, [m], is a variable, so the [match] cannot\n    be simplified further.  It is not smart enough to notice that the\n    two branches of the [match] are identical, so it gives up on\n    unfolding [bar m] and leaves it alone.\n\n    Similarly, tentatively unfolding [bar (m+1)] leaves a [match]\n    whose scrutinee is a function application (that cannot itself be\n    simplified, even after unfolding the definition of [+]), so\n    [simpl] leaves it alone. *)\n\n(** At this point, there are two ways to make progress.  One is to use\n    [destruct m] to break the proof into two cases, each focusing on a\n    more concrete choice of [m] ([O] vs [S _]).  In each case, the\n    [match] inside of [bar] can now make progress, and the proof is\n    easy to complete. *)\n\nFact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  destruct m eqn:E.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(** This approach works, but it depends on our recognizing that the\n    [match] hidden inside [bar] is what was preventing us from making\n    progress. *)\n\n(** A more straightforward way forward is to explicitly tell Coq to\n    unfold [bar]. *)\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n\n(** Now it is apparent that we are stuck on the [match] expressions on\n    both sides of the [=], and we can use [destruct] to finish the\n    proof without thinking too hard. *)\n\n  destruct m eqn:E.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where [destruct] is used to\n    perform case analysis of the value of some variable.  Sometimes we\n    need to reason by cases on the result of some _expression_.  We\n    can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if n =? 3 then false\n  else if n =? 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (n =? 3) eqn:E1.\n    - (* n =? 3 = true *) reflexivity.\n    - (* n =? 3 = false *) destruct (n =? 5) eqn:E2.\n      + (* n =? 5 = true *) reflexivity.\n      + (* n =? 5 = false *) reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (n =? 3) then ... else ...].  But either\n    [n] is equal to [3] or it isn't, so we can use [destruct (eqb\n    n 3)] to let us reason about the two cases.\n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c]. *)\n\n(** **** Exercise: 3 stars, standard (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.\n  - intros l1 l2 H. simpl in H. injection H as H. rewrite <- H. rewrite <- H0. reflexivity.\n  - destruct x as (x, y).\n    destruct l1 as [| x'].\n    + intros l2 H. simpl in H. destruct (split l) in H. discriminate H.\n    + destruct l2 as [| y'].\n      * intros H. simpl in H. destruct (split l) in H. discriminate H.\n      * intros H.\n        simpl.\n        assert (G: split l = (l1, l2)). {\n          simpl in H. destruct (split l).\n          injection H as H. rewrite -> H0. rewrite -> H2. reflexivity.\n        }\n        apply IHl in G.\n        simpl in H. destruct (split l) in H. injection H as H.\n        rewrite -> G. rewrite <- H. rewrite <- H1. reflexivity.\nQed.\n(** [] *)\n\n(** The [eqn:] part of the [destruct] tactic is optional; although\n    we've chosen to include it most of the time, for the sake of\n    documentation, it can often be omitted without harm.\n\n    However, when [destruct]ing compound expressions, the information\n    recorded by the [eqn:] can actually be critical: if we leave it\n    out, then [destruct] can erase information we need to complete a\n    proof.\n\n    For example, suppose we define a function [sillyfun1] like\n    this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if n =? 3 then true\n  else if n =? 5 then true\n  else false.\n\n(** Now suppose that we want to convince Coq that [sillyfun1 n]\n    yields [true] only when [n] is odd.  If we start the proof like\n    this (with no [eqn:] on the [destruct])... *)\n\nTheorem 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).\n  (* stuck... *)\nAbort.\n\n(** ... then we are stuck at this point because the context does\n    not contain enough information to prove the goal!  The problem is\n    that the substitution performed by [destruct] is quite brutal --\n    in this case, it throws away every occurrence of [n =? 3], but we\n    need to keep some memory of this expression and how it was\n    destructed, because we need to be able to reason that, since [n =?\n    3 = true] in this branch of the case analysis, it must be that [n\n    = 3], from which it follows that [n] is odd.\n\n    What we want here is to substitute away all existing occurrences of\n    [n =? 3], but at the same time add an equation to the context that\n    records which case we are in.  This is precisely what the [eqn:]\n    qualifier does. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n  sillyfun1 n = true ->\n  odd 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 b.\n  + destruct (f true) eqn:T.\n    - rewrite -> T. rewrite -> T. reflexivity.\n    - destruct (f false) eqn:F.\n      * rewrite -> T. reflexivity.\n      * rewrite -> F. reflexivity.\n  + destruct (f false) eqn:F.\n    - destruct (f true) eqn:T.\n      * rewrite -> T. reflexivity.\n      * rewrite -> F. reflexivity.\n    - rewrite -> F. rewrite -> F. reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Review *)\n\n(** We've now seen many of Coq's most fundamental tactics.  We'll\n    introduce a few more in the coming chapters, and later on we'll\n    see some more powerful _automation_ tactics that make Coq help us\n    with low-level details.  But basically we've got what we need to\n    get work done.\n\n    Here are the ones we've seen:\n\n      - [intros]: move hypotheses/variables from goal to context\n\n      - [reflexivity]: finish the proof (when the goal looks like [e =\n        e])\n\n      - [apply]: prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: apply a hypothesis, lemma, or constructor to\n        a hypothesis in the context (forward reasoning)\n\n      - [apply... with...]: explicitly specify values for variables\n        that cannot be determined by pattern matching\n\n      - [simpl]: simplify computations in the goal\n\n      - [simpl in H]: ... or a hypothesis\n\n      - [rewrite]: use an equality hypothesis (or lemma) to rewrite\n        the goal\n\n      - [rewrite ... in H]: ... or a hypothesis\n\n      - [symmetry]: changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]: changes a hypothesis of the form [t=u] into\n        [u=t]\n\n      - [transitivity y]: prove a goal [x=z] by proving two new subgoals,\n        [x=y] and [y=z]\n\n      - [unfold]: replace a defined constant by its right-hand side in\n        the goal\n\n      - [unfold... in H]: ... or a hypothesis\n\n      - [destruct... as...]: case analysis on values of inductively\n        defined types\n\n      - [destruct... eqn:...]: specify the name of an equation to be\n        added to the context, recording the result of the case\n        analysis\n\n      - [induction... as...]: induction on values of inductively\n        defined types\n\n      - [injection... as...]: reason by injectivity on equalities\n        between values of inductively defined types\n\n      - [discriminate]: reason by disjointness of constructors on\n        equalities between values of inductively defined types\n\n      - [assert (H: e)] (or [assert (e) as H]): introduce a \"local\n        lemma\" [e] and call it [H]\n\n      - [generalize dependent x]: move the variable [x] (and anything\n        else that depends on it) from the context back to an explicit\n        hypothesis in the goal formula\n\n      - [f_equal]: change a goal of the form [f x = f y] into [x = y] *)\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:E.\n  + (* true *)\n    symmetry. apply eqb_true in E. rewrite -> E. apply eqb_refl.\n  + (* false *)\n    generalize dependent m.\n    induction n.\n    - destruct m.\n      * intros E. discriminate E.\n      * reflexivity.\n    - destruct m.\n      * reflexivity.\n      * intros E. simpl in E. apply IHn in E. simpl. rewrite <- E. 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 eq1 eq2.\n  apply eqb_true in eq1. apply eqb_true in eq2.\n  rewrite -> eq1. rewrite <- eq2.\n  apply eqb_refl.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine)\n\n    We proved, in an exercise above, that [combine] is the inverse of\n    [split].  Complete the definition of [split_combine_statement]\n    below with a property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds.\n\n    Hint: Take a look at the definition of [combine] in [Poly].\n    Your property will need to account for the behavior of [combine]\n    in its base cases, which possibly drop some list elements. *)\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 (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.\n  induction l1 as [| x].\n  + intros l2 H.\n    destruct l2 as [| y].\n    - reflexivity.\n    - discriminate H.\n  + intros l2 H. destruct l2 as [| y].\n    - discriminate H.\n    - injection H as H. apply IHl1 in H.\n      simpl. rewrite -> H.\n      reflexivity.\nQed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_split_combine : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise) *)\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  destruct l as [| x'].\n  + simpl. intros H. discriminate H.\n  + induction (x' :: l).\n    - simpl. intros H. discriminate H.\n    - simpl. destruct (test x0) eqn:T.\n      * intros H. injection H as H. rewrite -> H in T. apply T.\n      * apply IHl0.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, especially useful (forall_exists_challenge)\n\n    Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n\n      forallb odd [1;3;5;7;9] = true\n      forallb negb [false;false] = true\n      forallb even [0;2;4;5] = false\n      forallb (eqb 5) [] = true\n\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n\n      existsb (eqb 5) [0;2;3;6] = false\n      existsb (andb true) [true;true;false] = true\n      existsb odd [1;0;0;0;0;3] = true\n      existsb even [] = false\n\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n\n    Finally, prove a theorem [existsb_existsb'] stating that\n    [existsb'] and [existsb] have the same behavior.\n*)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool\n  := match l with\n     | [] => true\n     | x :: l' => if test x then forallb test l' else false\n     end.\n\nExample test_forallb_1 : forallb odd [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 even [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     | [] => false\n     | x :: l' => if test x then true else existsb test l'\n     end.\n\nExample test_existsb_1 : existsb (eqb 5) [0;2;3;6] = false.\nProof. reflexivity. Qed.\n\nExample test_existsb_2 : existsb (andb true) [true;true;false] = true.\nProof. reflexivity. Qed.\n\nExample test_existsb_3 : existsb odd [1;0;0;0;0;3] = true.\nProof. reflexivity. Qed.\n\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\nTheorem existsb_existsb' : forall (X : Type) (test : X -> bool) (l : list X),\n  existsb test l = existsb' test l.\nProof. intros X test.\n  induction l.\n  + reflexivity.\n  + simpl.\n    unfold existsb'.\n    destruct (test x) eqn:T.\n    - simpl. rewrite -> T. reflexivity.\n    - simpl. rewrite -> T. rewrite -> IHl. reflexivity.\nQed.\n\n(** [] *)\n\n(* 2022-08-08 17:13 *)\n", "meta": {"author": "marshall-lee", "repo": "software_foundations", "sha": "d45ee7466f45de8d836692a3455742764ed58b83", "save_path": "github-repos/coq/marshall-lee-software_foundations", "path": "github-repos/coq/marshall-lee-software_foundations/software_foundations-d45ee7466f45de8d836692a3455742764ed58b83/lf/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.8824278587245935, "lm_q1q2_score": 0.6835139570923026}}
{"text": "From Hammer Require Import Hammer.\n\nFrom Topology Require Export Subbases.\nFrom ZornsLemma Require Export Relation_Definitions_Implicit.\nFrom Topology Require Export SeparatednessAxioms.\n\nSection OrderTopology.\n\nVariable X:Type.\nVariable R:relation X.\nHypothesis R_ord: order R.\n\nInductive order_topology_subbasis : Family X :=\n| intro_lower_interval: forall x:X,\nIn order_topology_subbasis [ y:X | R y x /\\ y <> x ]\n| intro_upper_interval: forall x:X,\nIn order_topology_subbasis [ y:X | R x y /\\ y <> x].\n\nDefinition OrderTopology : TopologicalSpace :=\nBuild_TopologicalSpace_from_subbasis X order_topology_subbasis.\n\nSection if_total_order.\n\nHypothesis R_total: forall x y:X, R x y \\/ R y x.\n\nLemma lower_closed_interval_closed: forall x:X,\nclosed [ y:X | R y x ] (X:=OrderTopology).\nProof. hammer_hook \"OrderTopology\" \"OrderTopology.lower_closed_interval_closed\".\nintro.\nred.\nmatch goal with |- open ?U => cut (U = interior U) end.\nintro.\nrewrite H; apply interior_open.\napply Extensionality_Ensembles; split.\n2:apply interior_deflationary.\nintros y ?.\nred in H.\nred in H.\nassert (R x y).\ndestruct (R_total x y); trivial.\ncontradiction H.\nconstructor; trivial.\nexists ([z:X | R x z /\\ z <> x]).\nconstructor; split.\napply (Build_TopologicalSpace_from_subbasis_subbasis\n_ order_topology_subbasis).\nconstructor.\nred; intros z ?.\ndestruct H1.\ndestruct H1.\nintro.\ndestruct H3.\ncontradiction H2.\napply (ord_antisym R_ord); trivial.\nconstructor.\nsplit; trivial.\nintro.\ncontradiction H.\nconstructor.\ndestruct H1; apply (ord_refl R_ord).\nQed.\n\nLemma upper_closed_interval_closed: forall x:X,\nclosed [y:X | R x y] (X:=OrderTopology).\nProof. hammer_hook \"OrderTopology\" \"OrderTopology.upper_closed_interval_closed\".\nintro.\nred.\nmatch goal with |- open ?U => cut (U = interior U) end.\nintro.\nrewrite H; apply interior_open.\napply Extensionality_Ensembles; split.\n2:apply interior_deflationary.\nintros y ?.\nred in H.\nred in H.\nassert (R y x).\ndestruct (R_total x y); trivial.\ncontradiction H.\nconstructor; trivial.\nexists ([z:X | R z x /\\ z <> x]).\nconstructor; split.\napply (Build_TopologicalSpace_from_subbasis_subbasis\n_ order_topology_subbasis).\nconstructor.\nred; intros z ?.\ndestruct H1.\ndestruct H1.\nintro.\ndestruct H3.\ncontradiction H2.\napply (ord_antisym R_ord); trivial.\nconstructor.\nsplit; trivial.\nintro.\ncontradiction H.\nconstructor.\ndestruct H1; apply (ord_refl R_ord).\nQed.\n\nLemma order_topology_Hausdorff: Hausdorff OrderTopology.\nProof. hammer_hook \"OrderTopology\" \"OrderTopology.order_topology_Hausdorff\".\nred.\nmatch goal with |- forall x y:point_set OrderTopology, ?P =>\ncut (forall x y:point_set OrderTopology, R x y -> P)\nend.\nintros.\ndestruct (R_total x y).\nexact (H x y H1 H0).\nassert (y <> x).\nauto.\ndestruct (H y x H1 H2) as [V [U [? [? [? []]]]]].\nexists U; exists V; repeat split; trivial.\ntransitivity (Intersection V U); trivial.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H8; constructor; trivial.\ndestruct H8; constructor; trivial.\n\nintros.\npose proof (Build_TopologicalSpace_from_subbasis_subbasis\n_ order_topology_subbasis).\ndestruct (classic (exists z:X, R x z /\\ R z y /\\ z <> x /\\ z <> y)).\ndestruct H2 as [z [? [? []]]].\nexists ([w:X | R w z /\\ w <> z]);\nexists ([w:X | R z w /\\ w <> z]).\nrepeat split; trivial.\napply H1.\nconstructor.\napply H1.\nconstructor.\nauto.\nauto.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H6.\ndestruct H6.\ndestruct H7.\ndestruct H6.\ndestruct H7.\ncontradiction H8.\napply (ord_antisym R_ord); trivial.\ndestruct H6.\n\nexists ([w:X | R w y /\\ w <> y]);\nexists ([w:X | R x w /\\ w <> x]).\nrepeat split.\napply H1.\nconstructor.\napply H1.\nconstructor.\ntrivial.\ntrivial.\ntrivial.\nauto.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H3.\ndestruct H3.\ndestruct H4.\ndestruct H3.\ndestruct H4.\ncontradiction H2.\nexists x0; repeat split; trivial.\ndestruct H3.\nQed.\n\nEnd if_total_order.\n\nEnd OrderTopology.\n\nArguments OrderTopology {X}.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/topology/OrderTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705732, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6835139536979877}}
{"text": "\nRequire Import Iron.Language.Simple.Step.\nRequire Import Iron.Language.Simple.SubstExpExp.\nRequire Import Iron.Language.Simple.Ty.\n\n\n(* If a closed, well typed expression takes an evaluation step \n   then the result has the same type as before. *)\nTheorem preservation\n :  forall x x' t\n ,  TYPE nil x  t\n -> STEP x x'\n -> TYPE nil x' t.\nProof.\n intros x x' t HT HS. gen t.\n induction HS; rip.\n\n Case \"EsContext\".\n  destruct H; inverts_type; burn.\n\n Case \"EsLamApp\".\n  inverts_type.\n  burn using subst_exp_exp.\nQed.\n\n\n(* If a closed, well typed expression takes several evaluation steps\n   then the result has the same type as before. *)\nLemma preservation_steps\n :  forall x1 t1 x2\n ,  TYPE nil x1 t1\n -> STEPS    x1 x2\n -> TYPE nil x2 t1.\nProof.\n intros x1 t1 x2 HT HS.\n induction HS; burn using preservation.\nQed.\n\n\n(* If a closed, well typed expression takes several evaluation steps\n   then the result has the same type as before. \n   Usses the left linearised version of steps judement. *)\nLemma preservation_stepsl\n :  forall x1 t1 x2\n ,  TYPE nil x1 t1\n -> STEPSL   x1 x2\n -> TYPE nil x2 t1.\nProof.\n intros x1 t1 x2 HT HS.\n induction HS; burn using preservation.\nQed.\n\n", "meta": {"author": "varomodt", "repo": "coq-scaffold", "sha": "8481bb46fdc34b0fc854343f1d7bfa53c7a1ef5f", "save_path": "github-repos/coq/varomodt-coq-scaffold", "path": "github-repos/coq/varomodt-coq-scaffold/coq-scaffold-8481bb46fdc34b0fc854343f1d7bfa53c7a1ef5f/lib/Iron/Language/Simple/Preservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6834704149460107}}
{"text": "Set Implicit Arguments.\n\nRequire Import\n        Discrete.DiscType\n        List\n        Tactics.Tactics.\n\nImport ListNotations.\n\n(** decidabitity of list membership *)\n\nFixpoint In {A : discType}(x : A)(xs : list A) : Prop :=\n  match xs with\n  | [] => False\n  | (y :: ys) => x = y \\/ In x ys\n  end.\n\nInstance In_dec {A : discType} : forall (x : A) xs, dec (In x xs).\nProof.\n  intros x xs ; gen x ; induction xs ; intros ; crush.\nQed.\n\nNotation \"x 'el' A\" := (In x A) (at level 70).\n\n(** facts about In *)\n\nLemma In_app_iff {A : discType}\n  : forall xs ys (x : A), In x (xs ++ ys) <-> In x xs \\/ In x ys.\nProof.\n  induction xs ; intros ; crush.\n  +\n    destruct* (IHxs ys x) ; crush.\nQed.\n\nHint Resolve In_app_iff.\n\nLemma In_rev_iff {A : discType}\n  : forall xs (x : A) , In x (rev xs) <-> In x xs.\nProof.\n  induction xs ; crush ; try solve [apply In_app_iff ; crush].\n  +\n    apply In_app_iff in H ; crush.\n    destruct* (IHxs x) ; right*.\nQed.\n\nHint Resolve In_rev_iff.\n\n\nLemma In_map {A B : discType}\n  : forall (xs : list A)(f : A -> B)(x : A),\n    In x xs -> In (f x) (map f xs).\nProof.\n  induction xs ; crush.\nQed.\n\n\nLemma In_map_iff {A B : discType}\n  : forall (xs : list A)(f : A -> B)(x : B),\n    In x (map f xs) <-> exists (y : A), f y = x /\\ In y xs.\nProof.\n  induction xs ; intros f x ; splits ; intros H ; try solve [crush].\n  +\n    simpl in *.\n    destruct H. exists* a.\n    destruct (IHxs f x) as [Hl Hr].\n    specialize (Hl H). crush. eexists ; eauto.\n  +\n    crush.\n    apply In_map with (f0 := f) in H.\n    destruct (IHxs f (f x0)) as [Hl Hr].\n    specialize (Hl H).\n    crush ; eexists ; eauto.\nQed.\n\nHint Resolve In_map.\n\nLemma In_eq {A : discType}\n  : forall (xs : list A) x, In x (x :: xs).\nProof.\n  crush.\nQed.\n\nLemma In_cons {A : discType}\n  : forall (xs : list A) x y, In x xs -> In x (y :: xs).\nProof.\n  induction xs ; crush.\nQed.\n\nLemma In_nil {A : discType}\n  : forall (x : A), ~ In x nil.\nProof.\n  crush.\nQed.\n\nLemma In_sing {A : discType}\n  : forall (x y : A), In x (y :: []) -> x = y.\nProof.\n  crush.\nQed.\n\nLemma In_cons_neq {A : discType}\n  : forall (xs : list A) x y, In x (y :: xs) -> x <> y -> In x xs.\nProof.\n  induction xs ; crush.\nQed.\n\nLemma not_In_cons {A : discType}\n  : forall (xs : list A) x y, ~ In x (y :: xs) -> x <> y /\\ ~ In x xs.\nProof.\n  induction xs ; crush.\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/Discrete/In.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118068790619, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.683452402809205}}
{"text": "Require Import List.\nSet Implicit Arguments.\n\n(* infinite lists *)\nCoInductive stream (A:Type): Type :=\n  | Cons : A -> stream A -> stream A.\n\n(* finite or infinite lists *)\nCoInductive llist (A:Type): Type :=\n  | LNil : llist A\n  | LCons : A -> llist A -> llist A.\n\n(* finite or infinite binary trees *)\nCoInductive ltree (A:Type): Type :=\n  | LLeaf : ltree A\n  | LBin  : A -> ltree A -> ltree A -> ltree A.\n\n\nCheck (LCons 1 (LCons 2 (LCons 3 (LNil nat)))).\n\nFixpoint embed {A:Type} (l:list A) : llist A :=\n  match l with\n    | nil       => LNil A\n    | cons a l' => LCons a (embed l')\n  end. \n\nLemma embed_injective: forall (A:Type)(l m:list A),\n  embed l = embed m -> l = m.\nProof.\n  intros A l. elim l.\n    clear l. intros m. elim m.\n      clear m. intros. reflexivity.\n      clear m. simpl. intros. discriminate.\n    clear l. intros a l IH m. elim m.\n      clear m. simpl. intros. discriminate.\n      clear m. intros b m H0 H1. clear H0.\n        simpl in H1. injection H1. clear H1. intros H1 H2.\n        rewrite <- H2. rewrite (IH m). reflexivity. exact H1.\nQed.\n\n(* cannot use a recursive definition with 'Fixpoint' *)\nCoFixpoint from (n:nat) : llist nat := LCons n (from (S n)). \n\nDefinition Nats : llist nat := from 0.\n\nCheck Nats.\n\n(* 'cofix' for anonymous co-recursive functions *)\nDefinition Squares_from :=\n  let sqr := fun n:nat => n*n in\n  cofix F : nat -> llist nat :=\n    fun n:nat => LCons (sqr n)(F (S n)).\n\n(* insight : co-recursive -> codomain is a coinductive type\n             recursive    -> domain is an inductive type\n*)\n\nEval simpl in (from 3).\n\nEval compute in (from 3).\n\nCoFixpoint repeat {A:Type}(a:A) : llist A :=  LCons a (repeat a).\n\n\nCoFixpoint lappend {A:Type}(u v: llist A) : llist A :=\n  match u with\n    | LNil        => v\n    | LCons a u'  => LCons a (lappend u' v)\n  end.\n\n\n\n\n\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/stream.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.8267117855317473, "lm_q1q2_score": 0.6834523975147813}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** Properties of addition.\n\n This file is mostly OBSOLETE now, see module [PeanoNat.Nat] instead.\n\n [Nat.add] is defined in [Init/Nat.v] as:\n<<\nFixpoint add (n m:nat) : nat :=\n  match n with\n  | O => m\n  | S p => S (p + m)\n  end\nwhere \"n + m\" := (add n m) : nat_scope.\n>>\n*)\n\nRequire Import PeanoNat.\n\nLocal Open Scope nat_scope.\n\n(** * Neutrality of 0, commutativity, associativity *)\n\nNotation plus_0_l := Nat.add_0_l (only parsing).\nNotation plus_0_r := Nat.add_0_r (only parsing).\nNotation plus_comm := Nat.add_comm (only parsing).\nNotation plus_assoc := Nat.add_assoc (only parsing).\n\nNotation plus_permute := Nat.add_shuffle3 (only parsing).\n\nDefinition plus_Snm_nSm : forall n m, S n + m = n + S m :=\n Peano.plus_n_Sm.\n\nLemma plus_assoc_reverse n m p : n + m + p = n + (m + p).\nProof.\n  symmetry. apply Nat.add_assoc.\nQed.\n\n(** * Simplification *)\n\nLemma plus_reg_l n m p : p + n = p + m -> n = m.\nProof.\n apply Nat.add_cancel_l.\nQed.\n\nLemma plus_le_reg_l n m p : p + n <= p + m -> n <= m.\nProof.\n apply Nat.add_le_mono_l.\nQed.\n\nLemma plus_lt_reg_l n m p : p + n < p + m -> n < m.\nProof.\n apply Nat.add_lt_mono_l.\nQed.\n\n(** * Compatibility with order *)\n\nLemma plus_le_compat_l n m p : n <= m -> p + n <= p + m.\nProof.\n apply Nat.add_le_mono_l.\nQed.\n\nLemma plus_le_compat_r n m p : n <= m -> n + p <= m + p.\nProof.\n apply Nat.add_le_mono_r.\nQed.\n\nLemma plus_lt_compat_l n m p : n < m -> p + n < p + m.\nProof.\n apply Nat.add_lt_mono_l.\nQed.\n\nLemma plus_lt_compat_r n m p : n < m -> n + p < m + p.\nProof.\n apply Nat.add_lt_mono_r.\nQed.\n\nLemma plus_le_compat n m p q : n <= m -> p <= q -> n + p <= m + q.\nProof.\n apply Nat.add_le_mono.\nQed.\n\nLemma plus_le_lt_compat n m p q : n <= m -> p < q -> n + p < m + q.\nProof.\n apply Nat.add_le_lt_mono.\nQed.\n\nLemma plus_lt_le_compat n m p q : n < m -> p <= q -> n + p < m + q.\nProof.\n apply Nat.add_lt_le_mono.\nQed.\n\nLemma plus_lt_compat n m p q : n < m -> p < q -> n + p < m + q.\nProof.\n apply Nat.add_lt_mono.\nQed.\n\nLemma le_plus_l n m : n <= n + m.\nProof.\n apply Nat.le_add_r.\nQed.\n\nLemma le_plus_r n m : m <= n + m.\nProof.\n rewrite Nat.add_comm. apply Nat.le_add_r.\nQed.\n\nTheorem le_plus_trans n m p : n <= m -> n <= m + p.\nProof.\n  intros. now rewrite <- Nat.le_add_r.\nQed.\n\nTheorem lt_plus_trans n m p : n < m -> n < m + p.\nProof.\n  intros. apply Nat.lt_le_trans with m. trivial. apply Nat.le_add_r.\nQed.\n\n(** * Inversion lemmas *)\n\nLemma plus_is_O n m : n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  destruct n; now split.\nQed.\n\nDefinition plus_is_one m n :\n  m + n = 1 -> {m = 0 /\\ n = 1} + {m = 1 /\\ n = 0}.\nProof.\n  destruct m as [| m]; auto.\n  destruct m; auto.\n  discriminate.\nDefined.\n\n(** * Derived properties *)\n\nNotation plus_permute_2_in_4 := Nat.add_shuffle1 (only parsing).\n\n(** * Tail-recursive plus *)\n\n(** [tail_plus] is an alternative definition for [plus] which is\n    tail-recursive, whereas [plus] is not. This can be useful\n    when extracting programs. *)\n\nFixpoint tail_plus n m : nat :=\n  match n with\n    | O => m\n    | S n => tail_plus n (S m)\n  end.\n\nLemma plus_tail_plus : forall n m, n + m = tail_plus n m.\nProof.\ninduction n as [| n IHn]; simpl; auto.\nintro m; rewrite <- IHn; simpl; auto.\nQed.\n\n(** * Discrimination *)\n\nLemma succ_plus_discr n m : n <> S (m+n).\nProof.\n apply Nat.succ_add_discr.\nQed.\n\nLemma n_SSn n : n <> S (S n).\nProof (succ_plus_discr n 1).\n\nLemma n_SSSn n : n <> S (S (S n)).\nProof (succ_plus_discr n 2).\n\nLemma n_SSSSn n : n <> S (S (S (S n))).\nProof (succ_plus_discr n 3).\n\n\n(** * Compatibility Hints *)\n\nHint Immediate plus_comm : arith.\nHint Resolve plus_assoc plus_assoc_reverse : arith.\nHint Resolve plus_le_compat_l plus_le_compat_r : arith.\nHint Resolve le_plus_l le_plus_r le_plus_trans : arith.\nHint Immediate lt_plus_trans : arith.\nHint Resolve plus_lt_compat_l plus_lt_compat_r : arith.\n\n(** For compatibility, we \"Require\" the same files as before *)\n\nRequire Import Le Lt.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Arith/Plus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012104, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.6834523886907438}}
{"text": "Require Export D.\n\n\n\n(** **** Exercise: 3 stars (eval__multistep)  *)\n(** The key idea behind the proof comes from the following picture:\n       P t1 t2 ==>            (by ST_Plus1) \n       P t1' t2 ==>           (by ST_Plus1)  \n       P t1'' t2 ==>          (by ST_Plus1) \n       ...                \n       P (C n1) t2 ==>        (by ST_Plus2)\n       P (C n1) t2' ==>       (by ST_Plus2)\n       P (C n1) t2'' ==>      (by ST_Plus2)\n       ...                \n       P (C n1) (C n2) ==>    (by ST_PlusConstConst)\n       C (n1 + n2)              \n    That is, the multistep reduction of a term of the form [P t1 t2]\n    proceeds in three phases:\n       - First, we use [ST_Plus1] some number of times to reduce [t1]\n         to a normal form, which must (by [nf_same_as_value]) be a\n         term of the form [C n1] for some [n1].\n       - Next, we use [ST_Plus2] some number of times to reduce [t2]\n         to a normal form, which must again be a term of the form [C\n         n2] for some [n2].\n       - Finally, we use [ST_PlusConstConst] one time to reduce [P (C\n         n1) (C n2)] to [C (n1 + n2)]. *)\n\n(** To formalize this intuition, you'll need to use the congruence\n    lemmas from above (you might want to review them now, so that\n    you'll be able to recognize when they are useful), plus some basic\n    properties of [==>*]: that it is reflexive, transitive, and\n    includes [==>]. *)\n\nTheorem multi_R : forall (X:Type) (R:relation X) (x y : X),\n       R x y -> (multi R) x y.\nProof.\n  intros X R x y H.\n  apply multi_step with y. apply H. apply multi_refl.   Qed.\n\nTheorem multi_trans :\n  forall (X:Type) (R: relation X) (x y z : X),\n      multi R x y  ->\n      multi R y z ->\n      multi R x z.\nProof.\n  intros X R x y z G H.\n  induction G.\n    - (* multi_refl *) assumption.\n    - (* multi_step *)\n      apply multi_step with y. assumption.\n      apply IHG. assumption.  Qed.\n\nLemma multistep_congr_1 : forall t1 t1' t2,\n     t1 ==>* t1' ->\n     P t1 t2 ==>* P t1' t2.\nProof.\n  intros t1 t1' t2 H. induction H.\n    - (* multi_refl *) apply multi_refl.\n    - (* multi_step *) apply multi_step with (P y t2).\n        apply ST_Plus1. apply H.\n        apply IHmulti.  Qed.\n\nLemma multistep_congr_2 : forall t1 t2 t2',\n     value t1 ->\n     t2 ==>* t2' ->\n     P t1 t2 ==>* P t1 t2'.\nProof.\n  intros t1 t2 t2' Ht1 H. induction H.\n  - apply multi_refl.\n  - apply multi_step with (P t1 y).\n    inversion Ht1. apply ST_Plus2. assumption. assumption. \nQed.\n\nTheorem eval__multistep : forall t n,\n  t \\\\ n -> t ==>* C n.\nProof.\n  intros t n H. induction H.\n  - apply multi_refl.\n  - apply multistep_congr_1 with (t1 := t1) (t1' := C n1) (t2 := t2) in IHeval1.\n    apply multistep_congr_2 with (t1 := C n1) (t2 := t2) (t2' := C n2) in IHeval2.\n    apply multi_trans with (x := P t1 t2) (y := P (C n1) t2) (z := P (C n1) (C n2))in IHeval1.\n    apply multi_trans with (x := P t1 t2) (y := P (C n1) (C n2)) (z := C (n1 + n2)).\n    assumption.  apply multi_R. constructor. assumption. constructor.\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/10/P01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.68342849216554}}
{"text": "(* \n  Copyright 2022 ZhengPu Shi\n  This file is part of CoqExt. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n\n  在解一元二次方程时碰到的一个问题：\n  标准库提供了 Rsqr_sol_eq_0_1 引理，提供了求根公式，但是要求 nonzeroreal 类型，\n  该类型是一个struct，内部使用了 Real 类型。\n  \n  现在想要建立一个 Real 类型的引理，如何将“nonzeroreal类型”予以回避，或者内部封装起来？\n*)\n  \n\nRequire Import Reals.\nOpen Scope R.\n\n(* 检查一些定义 *)\nPrint nonzeroreal.\nCheck Rsqr_sol_eq_0_1.\n\n(* nonzeroreal类型可直接使用 *)\nLemma quadratic_equation_prop1 : forall (a:nonzeroreal) (b c x:R) ,\n  x = (-b + sqrt(b² - 4 * a * c)) * ( / (2 * a)) ->\n  0 <= b² - 4 * a * c ->\n  a * x² + b * x + c = 0.\n  intros.\n  apply Rsqr_sol_eq_0_1.\n  - trivial.\n  - left. unfold sol_x1, Delta. auto.\nQed.\n\n(* Real类型暂时没有办法 *)\nLemma quadratic_equation_prop2 : forall (a b c x:R) ,\n  x = (-b + sqrt(b² - 4 * a * c)) * ( / (2 * a)) ->\n  0 <= b² - 4 * a * c ->\n  a * x² + b * x + c = 0.\n  intros.\n  Abort.\n\n(* 找到 Rsqr_sol_eq_0_1 源码，仿照其实现重写一个版本 *)\nLemma Rsqr_sol_eq_0_1' :\n  forall (a:R) (b c x:R),\n    a <> 0 ->\n    0 <= b ^ 2 - 4 * a * c ->\n    x = (- b + sqrt (b ^ 2 - 4 * a * c)) / (2 * a) \\/ \n    x = (- b - sqrt (b ^ 2 - 4 * a * c)) / (2 * a) \n    -> a * x ^ 2 + b * x + c = 0.\nProof.\n  intros.\n  elim H1.\n  - intro.\n    rewrite H2. field_simplify; auto.\n    rewrite <- (Rsqr_pow2 (sqrt (b ^ 2 - 4 * a * c))).\n    rewrite Rsqr_sqrt; auto.\n    field; auto.\n  - intro.\n    rewrite H2. field_simplify; auto.\n    rewrite <- (Rsqr_pow2 (sqrt (b ^ 2 - 4 * a * c))).\n    rewrite Rsqr_sqrt; auto.\n    field; auto.\nQed.\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/CoqExt/old-code/nonzeroreal_and_R_problem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634456, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.6834284849237227}}
{"text": "(*\n * Module: TLB\n *\n * Description:\n *  This module defines the functions used to represent a TLB entry.\n *)\n\nRequire Import Arith.\n\n(*\n * Define basic inductive types for a TLB entry.\n *)\nInductive ReadTy  : Type := | Read  | NoRead.\nInductive WriteTy : Type := | Write | NoWrite.\nInductive ExecTy  : Type := | Exec  | NoExec.\nInductive TLBTy : Type :=\n  | emptyTLB\n  | TLB : nat -> ReadTy -> WriteTy -> ExecTy -> TLBTy.\n\n(*\n * Function: definedTLB\n *\n * Description:\n *   Determine whether this TLB represents a defined translation from a\n *   virtual address to a physical address.\n *)\nDefinition definedTLB (tlb : TLBTy) :=\n  match tlb with\n  | emptyTLB => False\n  | TLB n R W X => True\nend.\n\n(*\n * Function: getPhysical\n *\n * Description:\n *   Get the physical address out of the TLB.\n *)\nDefinition getPhysical (tlb : TLBTy) :=\n  match tlb with\n  | emptyTLB => 0\n  | TLB n R W X => n\nend.\n\n(*\n * Functions for determining whether a TLB entry permits\n * read/write/execute access.\n *)\nDefinition TLBPermitsRead (tlb : TLBTy) : Prop :=\n  match tlb with \n  | emptyTLB => False\n  | TLB n Read   W X => True\n  | TLB n NoRead W X => False\nend.\n\nDefinition TLBPermitsWrite (tlb : TLBTy) : Prop :=\n  match tlb with \n  | emptyTLB => False\n  | TLB n R Write   X => True\n  | TLB n R NoWrite X => False\nend.\n\nDefinition TLBPermitsExec (tlb : TLBTy) : Prop :=\n  match tlb with \n  | emptyTLB => False\n  | TLB n R W Exec => True\n  | TLB n R W NoExec => False\nend.\n\nLemma PermitsWriteImpliesWrite : forall (n : nat) (r : ReadTy) (w : WriteTy) (e : ExecTy),\nTLBPermitsWrite (TLB n r w e) -> w = Write.\nintros.\ninduction w.\nreflexivity.\ncontradiction H.\nQed.\n\n", "meta": {"author": "jtcriswell", "repo": "Pudding", "sha": "1ea9885e213771bf923f9791b9bdf41a19a0be1e", "save_path": "github-repos/coq/jtcriswell-Pudding", "path": "github-repos/coq/jtcriswell-Pudding/Pudding-1ea9885e213771bf923f9791b9bdf41a19a0be1e/TLB.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6833606792532985}}
{"text": "(* http://www.iij-ii.co.jp/lab/techdoc/coqt/coqt4.html *)\nRequire Import Arith.\n\nGoal forall (n : nat), (exists m : nat, n = m * 4) -> exists k : nat, n = k * 2.\n  intros.destruct H.exists (x * 2).rewrite mult_assoc_reverse.simpl.apply H.Qed.\n\nTheorem lt_Snm_nm : forall (n m :nat), S n < m -> n < m.\n  intros.apply (lt_trans n (S n) m).apply lt_n_Sn.apply H.Qed.\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.\n\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.\ninduction xs.\nsimpl in H.\napply False_ind.\napply (lt_n_O 0 H).\nsimpl in H.\ndestruct a.\napply lt_Snm_nm in H.\napply IHxs in H.\ndestruct H.\nexists x.\nconstructor.\napply H.\ndestruct a.\nsimpl in H.\napply lt_S_n in H.\napply IHxs in H.\ndestruct H.\nexists x.\nconstructor.\napply H.\nexists a.\nconstructor.\nQed.", "meta": {"author": "unaoya", "repo": "coq_intro", "sha": "c417320df036d96f22744c7bb90695160c012e91", "save_path": "github-repos/coq/unaoya-coq_intro", "path": "github-repos/coq/unaoya-coq_intro/coq_intro-c417320df036d96f22744c7bb90695160c012e91/arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6833606743307691}}
{"text": "Require Import Nat.\nRequire Import List.\nRequire Import Program.\nImport ListNotations.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.Euclid.\nRequire Import Coq.Init.Logic.\nRequire Import Coq.Program.Wf.\nRequire Import Coq.Logic.Classical_Prop.\n\nDefinition sort : Type :=\n  forall (A : Type), (A -> A -> bool) -> list A -> list A.\n\nDefinition sort_length (f : sort) : Prop :=\n  forall (A : Type) (le : A -> A -> bool) (xs : list A),\n  length (f A le xs) = length xs.\n\nInductive list_sorted {A : Type} (le : A -> A -> bool): list A -> Prop :=\n| sorted_nil : list_sorted le []\n| sorted_cons :\n    forall x xs,\n    Forall (fun y => le x y = true) xs\n    -> list_sorted le xs\n    -> list_sorted le (x :: xs).\n\nDefinition sort_sorted (f : sort) : Prop :=\n  forall (A : Type) (le : A -> A -> bool) (xs : list A),\n  (forall h k l : A, le h k = true -> le k l = true -> le h l = true) ->\n  (forall k l : A, le k l = le l k -> l = k) ->\n  (forall k : A, le k k = true) ->\n  list_sorted le (f A le xs).\n\nDefinition sort_members (f : sort) : Prop :=\n  forall (A : Type) (le : A -> A -> bool) (xs : list A) (x : A),\n  In x xs <-> In x (f A le xs).\n\nDefinition valid_sort sort : Prop :=\n  sort_length sort /\\ sort_sorted sort /\\ sort_members sort.\n\nFixpoint split_at {A : Type} (n : nat) (xs : list A) : list A * list A :=\n  match n, xs with\n  | O, _ => ([], xs)\n  | S _, [] => ([], [])\n  | S n', x :: xs' =>\n      let (ys, zs) := split_at n' xs' in\n      (x :: ys, zs)\n  end.\n\nTheorem list_sorted_cons :\n  forall (A : Type) (le : A -> A -> bool) (a b : A) (xs : list A),\n  (forall h k l : A, le h k = true -> le k l = true -> le h l = true) ->\n  le a b = true -> list_sorted le (b :: xs) ->\n  list_sorted le (a :: b :: xs).\nProof.\n  intros A le a b xs le_trans le_a_b H.\n  constructor; try assumption.\n  constructor; try assumption.\n  inversion H.\n  apply Forall_impl with (P:=fun y : A => le b y = true); try assumption.\n  intro. apply le_trans. assumption.\nQed.\n\nTheorem list_sorted_cons_cons :\n  forall (A : Type) (le : A -> A -> bool) (a b : A) (xs : list A),\n  list_sorted le (a :: b :: xs) -> le a b = true.\nProof.\n  intros A le a b xs H.\n  inversion H.\n  destruct (Forall_forall (fun y : A => le a y = true) (b :: xs)) as (Hall & _).\n  apply Hall.\n  assumption.\n  constructor.\n  reflexivity.\nQed.\n\nTheorem list_sorted_cons_cons_sorted :\n  forall (A : Type) (le : A -> A -> bool) (a b : A) (xs : list A),\n  list_sorted le (a :: b :: xs) -> list_sorted le (a :: xs).\nProof.\n  intros A le a b xs H.\n  constructor.\n  - inversion H. inversion H2. assumption.\n  - inversion H. inversion H3. assumption.\nQed.\n\nLemma split_at_concat : forall (A : Type) (n : nat) (xs ys zs : list A),\n    (ys, zs) = split_at n xs -> ys ++ zs = xs.\nProof.\n  induction n; induction xs;\n    simpl; intros ys zs H; try (inversion H; reflexivity).\n  destruct (split_at n xs) as (ys' & zs') eqn:S in H. inversion H. simpl.\n  rewrite (IHn xs ys' zs' (eq_sym S)). reflexivity.\nQed.\n\nLemma split_at_length : forall (A : Type) (n : nat) (xs ys zs : list A),\n    n < length xs -> (ys, zs) = split_at n xs -> length ys = n.\nProof.\n  intros A n.\n  induction n as [|n'].\n  - intros xs ys zs Hlt Hsplit. simpl in Hsplit. inversion Hsplit. reflexivity.\n  - induction xs as [|x xs'].\n    * intros ys zs Hlt Hsplit. inversion Hlt.\n    * intros ys zs Hlt Hsplit.\n      simpl in Hsplit. destruct (split_at n' xs') eqn:S in Hsplit.\n      inversion Hsplit. simpl.\n      simpl in Hlt. apply lt_S_n in Hlt.\n      rewrite (IHn' xs' l l0 Hlt (eq_sym S)).\n      reflexivity.\nQed.\n\nDefinition split {A : Type} (xs : list A) : list A * list A :=\n  match xs with\n  | [] => ([], [])\n  | _ :: _ =>\n    match eucl_dev 2 (gt_Sn_O 1) (length xs) with\n    | divex _ _ q r _ _ => split_at q xs\n    end\n  end.\n\nTheorem split_concat :\n  forall (A : Type) (xs ys zs : list A), (ys, zs) = split xs -> ys ++ zs = xs.\nProof.\n  induction xs; try (intros ys zs H; inversion H; reflexivity).\n  unfold split.\n  destruct (eucl_dev 2 (gt_Sn_O 1) (length (a :: xs))).\n  apply split_at_concat.\nQed.\n\nTheorem split_length :\n  forall (A : Type) (xs ys zs : list A),\n  (ys, zs) = split xs -> length ys + length zs = length xs.\nProof.\n  intros A xs ys zs H.\n  rewrite <- split_concat with (xs:=xs) (ys:=ys) (zs:=zs); try assumption.\n  symmetry. apply app_length.\nQed.\n\nTheorem split_members :\n  forall (A : Type) (a : A) (xs ys zs : list A),\n  (ys, zs) = split xs -> In a ys \\/ In a zs <-> In a xs.\nProof.\n  intros A a xs ys zs Hsplit.\n  split; intro H.\n  - rewrite <- split_concat with (ys:=ys) (zs:=zs); try assumption.\n    apply in_or_app; assumption.\n  - rewrite <- split_concat with (ys:=ys) (zs:=zs) in H; try assumption.\n    apply in_app_or; assumption.\nQed.\n\nTheorem split_smaller_l :\n  forall (A : Type) (a b : A) (xs ys zs : list A),\n  (ys, zs) = split (a :: b :: xs) -> length ys < length (a :: b :: xs).\nProof.\n  intros A a b xs ys zs H.\n  simpl in H. destruct (eucl_dev 2 (gt_Sn_O 1) (S (S (length xs)))).\n  destruct q.\n  - simpl in e. unfold gt in g. rewrite <- e in g.\n    repeat apply lt_S_n in g. inversion g.\n  - assert (forall n : nat, n < S (n * 2) + r).\n    {\n      induction n.\n      * apply Nat.lt_0_succ.\n      * simpl. apply lt_n_S. rewrite <- plus_Sn_m.\n        apply Nat.lt_lt_succ_r. apply IHn.\n    }\n    rewrite split_at_length with (n:=S q) (xs:=a::b::xs) (zs:=zs);\n      apply H || simpl; rewrite e; simpl; apply lt_n_S; apply H0.\nQed.\n\nTheorem split_smaller_r : forall (A : Type) (a b : A) (xs ys zs : list A),\n    (ys, zs) = split (a :: b :: xs) -> length zs < length (a :: b :: xs).\nProof.\n  intros A a b xs ys zs H.\n  rewrite <- split_concat with (xs:=a::b::xs) (ys:=ys) (zs:=zs).\n  - rewrite app_length. apply Nat.lt_add_pos_l.\n    simpl in H. destruct (eucl_dev 2 (gt_Sn_O 1) (S (S (length xs)))).\n    destruct q.\n    * simpl in e. rewrite <- e in g.\n      repeat apply lt_S_n in g. inversion g.\n    * rewrite split_at_length with (n:=S q) (xs:=a::b::xs) (ys:=ys) (zs:=zs).\n      apply Nat.lt_0_succ.\n      simpl. rewrite e. rewrite Nat.mul_comm. apply lt_plus_trans. simpl.\n      apply lt_n_S. apply Nat.lt_add_pos_r. apply Nat.lt_0_succ.\n      assumption.\n  - assumption.\nQed.\n\nProgram Fixpoint merge_sorted_lists {A : Type} (le : A -> A -> bool)\n    (xs ys : list A) { measure (length (xs ++ ys)) } : list A :=\n  match xs, ys with\n  | [], _ => ys\n  | _, [] => xs\n  | x :: xs', y :: ys' =>\n      if le x y\n        then x :: merge_sorted_lists le xs' ys\n        else y :: merge_sorted_lists le xs ys'\n  end.\nNext Obligation.\n  rewrite app_length. rewrite app_length. simpl.\n  destruct (length xs'); try auto.\n  simpl. repeat rewrite <- Nat.succ_lt_mono. rewrite <- Nat.add_lt_mono_l.\n  auto.\nQed.\n\nLemma merge_sorted_lists_body :\n  forall (A : Type) (le : A -> A -> bool) (xs ys : list A),\n  merge_sorted_lists le xs ys =\n  match xs, ys with\n  | [], _ => ys\n  | _, [] => xs\n  | x :: xs', y :: ys' =>\n      if le x y\n        then x :: merge_sorted_lists le xs' ys\n        else y :: merge_sorted_lists le xs ys'\n  end.\nProof.\n  intros A le xs ys.\n  unfold merge_sorted_lists.\n  unfold merge_sorted_lists_func; rewrite WfExtensionality.fix_sub_eq_ext;\n    fold merge_sorted_lists_func; simpl.\n  destruct xs; destruct ys; try reflexivity.\nQed.\n\nLemma merge_sorted_lists_length :\n  forall (A : Type) (le : A -> A -> bool) (xs ys : list A),\n  length (merge_sorted_lists le xs ys) = length xs + length ys.\nProof.\n  intros A le xs ys.\n  rewrite merge_sorted_lists_body.\n  revert ys; induction xs as [|x xs']; try reflexivity.\n  induction ys as [|y ys']; simpl; try rewrite Nat.add_0_r; try reflexivity.\n  destruct (le x y).\n  - simpl. apply eq_S. rewrite merge_sorted_lists_body.\n    apply IHxs' with (ys:=y::ys').\n  - simpl. apply eq_S. rewrite merge_sorted_lists_body.\n    rewrite <- plus_n_Sm. apply IHys'.\nQed.\n\nTheorem merge_sorted_lists_nil_l :\n  forall (A : Type) (le : A -> A -> bool) (xs : list A),\n  merge_sorted_lists le [] xs = xs.\nProof.\n  intros A le xs.\n  rewrite merge_sorted_lists_body.\n  reflexivity.\nQed.\n\nTheorem merge_sorted_lists_nil_r :\n  forall (A : Type) (le : A -> A -> bool) (xs : list A),\n  merge_sorted_lists le xs [] = xs.\nProof.\n  intros A le xs.\n  rewrite merge_sorted_lists_body.\n  destruct xs; reflexivity.\nQed.\n\nLemma merge_sorted_lists_singleton_le_l :\n  forall (A : Type) (le : A -> A -> bool) (a y : A) (ys : list A),\n  le a y = true ->\n  merge_sorted_lists le [a] (y :: ys) = a :: y :: ys.\nProof.\n  intros A le a y ys H.\n  rewrite merge_sorted_lists_body. rewrite H.\n  reflexivity.\nQed.\n\nLemma merge_sorted_lists_singleton_le_r :\n  forall (A : Type) (le : A -> A -> bool) (a y : A) (ys : list A),\n  (forall k l : A, le k l = le l k -> l = k) ->\n  list_sorted le (y :: ys) -> le a y = true ->\n  merge_sorted_lists le (y :: ys) [a] = a :: y :: ys.\nProof.\n  intros A le a y ys le_antisymm Hsorted le_a_y.\n  rewrite merge_sorted_lists_body.\n  destruct (le y a) eqn:le_y_a.\n  - rewrite <- le_antisymm  with (k:=a) (l:=y); try assumption.\n    induction ys as [|y' ys]; try reflexivity.\n    destruct (le y' y) eqn:le_yp_a.\n    * inversion Hsorted.\n      assert (y = y') as Hyyp.\n      {\n        destruct (Forall_forall (fun y0 : A => le y y0 = true) (y' :: ys))\n          as (Hall & _).\n        rewrite le_antisymm with (k:=y') (l:=y);\n          try assumption; try reflexivity.\n        rewrite Hall. assumption. assumption. constructor. reflexivity.\n      }\n      rewrite merge_sorted_lists_body. rewrite le_yp_a. rewrite <- Hyyp.\n      rewrite IHys.\n      repeat rewrite merge_sorted_lists_body. reflexivity.\n      rewrite <- Hyyp in H2. assumption.\n    * rewrite merge_sorted_lists_body. rewrite le_yp_a.\n      rewrite merge_sorted_lists_body. reflexivity.\n    * rewrite le_a_y; rewrite le_y_a; reflexivity.\n  - rewrite merge_sorted_lists_nil_r.\n    reflexivity.\nQed.\n\nTheorem merge_sorted_lists_same_head :\n  forall (A : Type) (le : A -> A -> bool) (a : A) (xs ys : list A),\n  (forall k l : A, le k l = le l k -> l = k) ->\n  list_sorted le (a :: xs) -> list_sorted le (a :: ys) ->\n  merge_sorted_lists le (a :: xs) (a :: ys)\n    = a :: a :: merge_sorted_lists le xs ys.\nProof.\n  intros A le a xs ys le_antisymm. revert ys.\n  induction xs as [|x xs']; induction ys as [|y ys']; intros H1 H2.\n  - repeat rewrite merge_sorted_lists_body. destruct (le a a); reflexivity.\n  - rewrite merge_sorted_lists_body.\n    destruct (le a a).\n    * repeat rewrite merge_sorted_lists_body. reflexivity.\n    * rewrite merge_sorted_lists_singleton_le_l; try reflexivity.\n      apply list_sorted_cons_cons with (xs:=ys').\n      assumption.\n  - destruct (le a a) eqn:le_a_a;\n      rewrite merge_sorted_lists_nil_r; rewrite merge_sorted_lists_body;\n      rewrite le_a_a; try (rewrite merge_sorted_lists_body; reflexivity).\n    rewrite merge_sorted_lists_singleton_le_r;\n      inversion H1; try (reflexivity || assumption).\n    destruct (Forall_forall (fun y : A => le a y = true) (x :: xs'))\n      as (Hall & _).\n    apply Hall with (x0:=x). assumption. constructor; reflexivity.\n\n  (* xs := x :: xs' and ys := y :: ys' *)\n  - rewrite merge_sorted_lists_body.\n    destruct (le a a) eqn:le_a_a.\n\n    (* le a a = true *)\n    * destruct (le x a) eqn:le_x_a.\n      + inversion H1.\n        rewrite le_antisymm with (k:=a) (l:=x); try assumption.\n        rewrite IHxs'; try assumption.\n        rewrite merge_sorted_lists_body with (xs:=a::xs').\n        inversion H2.\n        destruct (Forall_forall (fun y : A => le a y = true) (y :: ys'))\n          as (Hall & _).\n        rewrite Hall with (x:=y); try (reflexivity || assumption).\n        constructor; reflexivity.\n        apply list_sorted_cons_cons_sorted with (b:=x); assumption.\n        destruct (Forall_forall (fun y : A => le a y = true) (x :: xs'))\n          as (Hall & _).\n        rewrite Hall with (x0:=x); try assumption.\n        rewrite le_x_a; reflexivity.\n        constructor; reflexivity.\n      + rewrite merge_sorted_lists_body. rewrite le_x_a. reflexivity.\n\n    (* le a a = false *)\n    * rewrite merge_sorted_lists_body.\n      inversion H2.\n      destruct (Forall_forall (fun y : A => le a y = true) (y :: ys'))\n        as (Hall & _).\n      rewrite Hall with (x:=y).\n      reflexivity. assumption. constructor. reflexivity.\nQed.\n\nTheorem merge_sorted_lists_cons_l :\n  forall (A : Type) (le : A -> A -> bool) (x : A) (xs ys : list A),\n  (forall k l : A, le k l = le l k -> l = k) ->\n  list_sorted le (x :: xs) -> list_sorted le (x :: ys) ->\n  merge_sorted_lists le (x :: xs) ys = x :: merge_sorted_lists le xs ys.\nProof.\n  intros A le x xs ys le_antisymm Hxxs_sorted Hxys_sorted.\n  rewrite merge_sorted_lists_body.\n  induction ys as [|y ys'].\n  - rewrite merge_sorted_lists_nil_r. reflexivity.\n  - inversion Hxys_sorted.\n    assert (le x y = true) as le_x_y.\n    { inversion H1. assumption. }\n    rewrite le_x_y.\n    reflexivity.\nQed.\n\nTheorem merge_sorted_lists_cons_r :\n  forall (A : Type) (le : A -> A -> bool) (y : A) (xs ys : list A),\n  (forall k l : A, le k l = le l k -> l = k) ->\n  list_sorted le (y :: xs) -> list_sorted le (y :: ys) ->\n  merge_sorted_lists le xs (y :: ys) = y :: merge_sorted_lists le xs ys.\nProof.\n  intros A le y xs ys le_antisymm Hyxs_sorted Hyys_sorted.\n  induction xs as [|x xs'].\n  - rewrite merge_sorted_lists_body.\n    rewrite merge_sorted_lists_nil_l. reflexivity.\n  - inversion Hyxs_sorted.\n    rewrite merge_sorted_lists_body.\n    destruct (le x y) eqn:le_x_y; try reflexivity.\n    assert (x = y) as eq_x_y.\n    {\n      inversion Hyxs_sorted.\n      destruct (Forall_forall (fun y0 : A => le y y0 = true) (x :: xs'))\n        as (Hall & _).\n      apply le_antisymm with (k:=y) (l:=x).\n      rewrite le_x_y. apply Hall.\n      assumption. constructor; reflexivity.\n    }\n    rewrite merge_sorted_lists_cons_l; try (reflexivity || assumption).\n    rewrite IHxs'.\n    rewrite eq_x_y; reflexivity.\n    apply list_sorted_cons_cons_sorted with (b:=x); assumption.\n    rewrite eq_x_y; assumption.\nQed.\n\nTheorem merge_sorted_lists_comm :\n  forall (A : Type) (le : A -> A -> bool) (xs ys : list A),\n  (forall k l : A, le k l = le l k -> l = k) ->\n  list_sorted le xs -> list_sorted le ys ->\n  merge_sorted_lists le xs ys = merge_sorted_lists le ys xs.\nProof.\n  intros A le xs ys le_antisymm. revert ys.\n  induction xs as [|x xs'];\n    try (intro; rewrite merge_sorted_lists_nil_l;\n          rewrite merge_sorted_lists_nil_r; reflexivity).\n  induction ys as [|y ys'];\n    try (rewrite merge_sorted_lists_nil_l; rewrite merge_sorted_lists_nil_r;\n          reflexivity).\n  intros Hxs_sorted Hys_sorted; inversion Hxs_sorted; inversion Hys_sorted.\n  rewrite merge_sorted_lists_body;\n    rewrite merge_sorted_lists_body with (xs:=y::ys') (ys:=x::xs').\n  destruct (le x y) eqn:le_x_y; destruct (le y x) eqn:le_y_x.\n\n  (* le x y = true and le y x = true *)\n  - rewrite le_antisymm with (k:=x) (l:=y) at 2; try assumption.\n    rewrite IHxs'; try assumption.\n    rewrite le_antisymm with (k:=x) (l:=y); try assumption.\n    assert (list_sorted le (x :: ys')) as Hxysp_sorted.\n    {\n      rewrite <- le_antisymm with (k:=x) (l:=y).\n      assumption. rewrite le_y_x. assumption.\n    }\n    rewrite merge_sorted_lists_cons_l;\n      try rewrite merge_sorted_lists_cons_r;\n      try reflexivity; try assumption.\n    rewrite le_y_x; rewrite le_x_y; reflexivity.\n    rewrite le_y_x; rewrite le_x_y; reflexivity.\n\n  (* le x y = true and le y x = false *)\n  - rewrite IHxs' with (ys:=y::ys'); try (reflexivity || assumption).\n\n  (* le x y = false and le y x = true *)\n  - rewrite IHys'; try (reflexivity || assumption).\n\n  (* le x y = false and le y x = false *)\n  - rewrite le_antisymm with (k:=x) (l:=y); try assumption.\n    rewrite IHys'; try assumption.\n    assert (list_sorted le (x :: ys')).\n    {\n      rewrite <- le_antisymm with (k:=x) (l:=y).\n      assumption. rewrite le_x_y. rewrite le_y_x. reflexivity.\n    }\n    rewrite merge_sorted_lists_cons_l;\n      try rewrite merge_sorted_lists_cons_r;\n      try reflexivity; try assumption.\n    rewrite le_x_y. rewrite le_y_x. reflexivity.\nQed.\n\nTheorem merge_sorted_lists_members :\n  forall (A : Type) (le : A -> A -> bool) (a : A) (xs ys : list A),\n  In a (merge_sorted_lists le xs ys) <-> In a xs \\/ In a ys.\nProof.\n  induction xs as [|x xs']; induction ys as [|y ys']; try simpl; try tauto.\n  split; rewrite merge_sorted_lists_body; destruct (le x y) eqn:le_x_y; intro H.\n\n  - inversion H.\n    * auto.\n    * destruct IHxs' with (ys:=y::ys') as (H1 & _).\n      destruct (H1 H0); try auto.\n\n  - inversion H; try auto.\n    destruct IHys' as (H1 & _).\n    destruct (H1 H0); auto.\n\n  - destruct IHxs' with (ys:=y::ys') as (_ & H1).\n    simpl. destruct H; destruct H; try auto.\n    * right. apply H1. simpl. auto.\n    * right. apply H1. simpl. auto.\n\n  - destruct IHys' as (_ & H1).\n    simpl. destruct H; destruct H; try auto.\n    * right. apply H1. simpl. auto.\n    * right. apply H1. simpl. auto.\nQed.\n\n(* Lemma merge_sorted_lists_sorted_1 :\n  forall (A : Type) (le : A -> A -> bool) (x y : A) (xs ys : list A),\n  list_sorted le (x :: xs) -> list_sorted le (y ::ys) -> le x y = true ->\n  list_sorted le (x :: merge_sorted_lists le xs (y :: ys)). *)\n\nLemma le_trans_contra :\n  forall (A : Type) (le : A -> A -> bool) (h k l : A),\n  (forall h k l : A, le h k = true -> le k l = true -> le h l = true) ->\n  (forall k l : A, le k l = le l k -> l = k) ->\n  le k l = true -> le k h = false -> le h l = true.\nProof.\n  intros A le h k l le_trans le_antisymm H1 H2.\n  destruct (le h k) eqn:le_h_k.\n  - apply le_trans with (k:=k); assumption.\n  - rewrite le_antisymm with (l:=h) (k:=k).\n    assumption. rewrite H2. rewrite le_h_k. reflexivity.\nQed.\n\nTheorem merge_sorted_lists_sorted :\n  forall (A : Type) (le : A -> A -> bool) (xs ys : list A),\n  (forall h k l : A, le h k = true -> le k l = true -> le h l = true) ->\n  (forall k l : A, le k l = le l k -> l = k) ->\n  (forall k : A, le k k = true) ->\n  list_sorted le xs -> list_sorted le ys ->\n  list_sorted le (merge_sorted_lists le xs ys).\nProof.\n  intros A le xs ys le_trans le_antisymm  le_refl Hxs Hys.\n  revert ys Hys. induction xs as [|x xs']; intros ys Hys; try apply Hys.\n  induction ys as [|y ys']; try apply Hxs.\n  rewrite merge_sorted_lists_body.\n  destruct (le x y) eqn:le_x_y.\n\n  (* le x y = true *)\n  - inversion Hxs.\n    constructor; try (apply IHxs' with (ys:=y::ys'); assumption).\n    apply Forall_forall; intros a Ha.\n    destruct merge_sorted_lists_members\n      with (le:=le) (a:=a) (xs:=xs') (ys:=y::ys') as (Hin & _).\n    destruct (Hin Ha).\n    * destruct (Forall_forall (fun y : A => le x y = true) xs') as (Hall & _).\n      apply Hall; try assumption.\n    * inversion H3.\n      + rewrite <- H4. assumption.\n      + apply le_trans with (k:=y); try assumption.\n        inversion Hys.\n        destruct (Forall_forall (fun y0 : A => le y y0 = true) ys')\n          as (Hall & _).\n        apply Hall; try assumption.\n\n  (* le x y = false *)\n  - inversion Hys.\n    constructor; try (apply IHys'; assumption).\n    apply Forall_forall; intros a Ha.\n    destruct merge_sorted_lists_members\n      with (a:=a) (le:=le) (xs:=x::xs') (ys:=ys') as (Hin & _).\n    destruct (Hin Ha).\n    * apply le_trans_contra with (k:=x); try assumption.\n      inversion H3.\n      rewrite H4. apply le_refl.\n      inversion Hxs.\n      destruct (Forall_forall (fun y : A => le x y = true) xs') as (Hall & _).\n      apply Hall; try assumption.\n    * destruct (Forall_forall (fun y0 : A => le y y0 = true) ys') as (Hall & _).\n      apply Hall; try assumption.\nQed.\n\nProgram Fixpoint merge_sort (A : Type) (le : A -> A -> bool)\n    (xs : list A) { measure (length xs) } : list A :=\n  match xs with\n  | [] => []\n  | [x] => [x]\n  | _ :: _ :: _ =>\n    match split xs with\n    | (ys, zs) =>\n      let sorted_ys := merge_sort A le ys in\n      let sorted_zs := merge_sort A le zs in\n      merge_sorted_lists le sorted_ys sorted_zs\n    end\n  end.\n\nNext Obligation.\n  apply split_smaller_l with (zs:=zs).\n  assumption.\nQed.\n\nNext Obligation.\n  apply split_smaller_r with (ys:=ys).\n  assumption.\nQed.\n\nTheorem merge_sort_nil :\n  forall (A : Type) (le : A -> A -> bool), merge_sort A le [] = [].\nProof. reflexivity. Qed.\n\nExample merge_sort_list_nat :\n  merge_sort nat leb [1;7;2;9;3;5;2] = [1;2;2;3;5;7;9].\nProof. reflexivity. Qed.\n\nLemma merge_sort_body :\n  forall (A : Type) (le : A -> A -> bool) (xs : list A),\n  merge_sort A le xs =\n  match xs with\n  | [] => []\n  | [x] => [x]\n  | _ :: _ :: _ =>\n    match split xs with\n    | (ys, zs) =>\n      let sorted_ys := merge_sort A le ys in\n      let sorted_zs := merge_sort A le zs in\n      merge_sorted_lists le sorted_ys sorted_zs\n    end\n  end.\nProof.\n  intros A le xs.\n  unfold merge_sort.\n  unfold merge_sort_func; rewrite WfExtensionality.fix_sub_eq_ext;\n    fold merge_sort_func; simpl.\n  induction xs; try reflexivity.\n  induction xs; try reflexivity.\n  destruct (split (a :: a0 :: xs)).\n  reflexivity.\nQed.\n\nLemma merge_sort_length_le_n0 :\n  forall (A : Type) (le : A -> A -> bool) (n0 : nat) (xs : list A),\n  length xs <= n0 -> length (merge_sort A le xs) = length xs.\nProof.\n  induction n0 as [|n0']; intros.\n  - destruct xs. reflexivity. inversion H.\n  - induction xs as [|a xs]; try reflexivity.\n    induction xs as [|b xs]; try reflexivity.\n    rewrite merge_sort_body.\n    destruct (split (a :: b :: xs)) as (ys & zs) eqn:S; symmetry in S.\n    simpl. rewrite merge_sorted_lists_length.\n    repeat rewrite IHn0'.\n    rewrite split_length with (xs:=a::b::xs); reflexivity || assumption.\n    apply lt_n_Sm_le;\n      apply lt_le_trans with (m:=length (a::b::xs)); try assumption.\n    apply split_smaller_r with (ys:=ys). assumption.\n    apply lt_n_Sm_le;\n      apply lt_le_trans with (m:=length (a::b::xs)); try assumption.\n    apply split_smaller_l with (zs:=zs). assumption.\nQed.\n\nTheorem merge_sort_length : sort_length merge_sort.\nProof.\n  intros A le xs.\n  apply merge_sort_length_le_n0 with (n0:=length xs).\n  apply Nat.le_refl.\nQed.\n\nLemma merge_sort_sorted_le_n0 :\n  forall (A : Type) (le : A -> A -> bool) (n0 : nat) (xs : list A),\n  (forall h k l : A, le h k = true -> le k l = true -> le h l = true) ->\n  (forall k l : A, le k l = le l k -> l = k) ->\n  (forall k : A, le k k = true) ->\n  length xs <= n0 -> list_sorted le (merge_sort A le xs).\nProof.\n  intros A le n0 xs le_trans le_antisymm le_refl.\n  revert xs; induction n0 as [|n0']; intros xs H.\n  - destruct xs. constructor. inversion H.\n  - induction xs as [|a xs]; try constructor.\n    induction xs as [|b xs].\n    * constructor. apply Forall_nil. constructor.\n    * rewrite merge_sort_body.\n      destruct (split (a::b::xs)) eqn:Hsplit.\n      simpl.\n      apply merge_sorted_lists_sorted; try assumption; try apply IHn0'.\n      + apply lt_n_Sm_le.\n        apply Nat.lt_le_trans with (m:=length (a::b::xs)); try assumption.\n        apply split_smaller_l with (a:=a) (b:=b) (xs:=xs) (ys:=l) (zs:=l0).\n        symmetry; assumption.\n      + apply lt_n_Sm_le.\n        apply Nat.lt_le_trans with (m:=length (a::b::xs)); try assumption.\n        apply split_smaller_r with (a:=a) (b:=b) (xs:=xs) (ys:=l) (zs:=l0).\n        symmetry; assumption.\nQed.\n\nTheorem merge_sort_sorted : sort_sorted merge_sort.\nProof.\n  intros A le xs le_trans le_antisymm le_refl.\n  apply merge_sort_sorted_le_n0 with (n0:=length xs); try assumption.\n  apply Nat.le_refl.\nQed.\n\nLemma merge_sort_members_le_n0 :\n  forall (A : Type) (le : A -> A -> bool) (n0 : nat) (x : A) (xs : list A),\n  length xs <= n0 ->\n  In x xs <-> In x (merge_sort A le xs).\nProof.\n  intros A le n0 x.\n  induction n0 as [|n0']; intros xs Hlen.\n  - destruct xs. rewrite merge_sort_nil. tauto. inversion Hlen.\n  - induction xs as [|a xs]; try (simpl; tauto).\n    induction xs as [|b xs]; try (simpl; tauto).\n    split; intro H.\n\n    (* In x (a :: b :: xs) -> In x (merge_sort A le (a :: b :: xs)) *)\n    * rewrite merge_sort_body.\n      destruct (split (a::b::xs)) eqn:Hsplit.\n      simpl.\n      destruct merge_sorted_lists_members\n        with (le:=le) (a:=x) (xs:=merge_sort A le l) (ys:=merge_sort A le l0)\n        as (_ & Hin).\n      apply Hin.\n      destruct IHn0' with (xs:=l) as (Hl & _).\n        apply lt_n_Sm_le. apply Nat.lt_le_trans with (m:=length (a::b::xs)).\n        apply split_smaller_l with (zs:=l0). symmetry; assumption. assumption.\n      destruct IHn0' with (xs:=l0) as (Hl0 & _).\n        apply lt_n_Sm_le. apply Nat.lt_le_trans with (m:=length (a::b::xs)).\n        apply split_smaller_r with (ys:=l). symmetry; assumption. assumption.\n      apply imply_and_or2 with (P:=In x l); try assumption.\n      apply or_comm.\n      apply imply_and_or2 with (P:=In x l0); try assumption.\n      apply or_comm.\n      apply in_app_or with (a:=x) (l:=l) (m:=l0).\n      rewrite split_concat with (xs:=a::b::xs); try symmetry; try assumption.\n\n    (* In x (merge_sort A le (a :: b :: xs)) -> In x (a :: b :: xs) *)\n    * rewrite merge_sort_body in H.\n      destruct (split (a::b::xs)) eqn:Hsplit.\n      simpl in H.\n      destruct merge_sorted_lists_members\n        with (le:=le) (a:=x) (xs:=merge_sort A le l) (ys:=merge_sort A le l0)\n        as (Hin & _).\n      destruct (split_members A x (a::b::xs) l l0) as (Hin' & _);\n        try (symmetry; assumption).\n      apply Hin'.\n      destruct (Hin H).\n      + left.\n        destruct IHn0' with (xs:=l) as (_ & Hinl).\n          apply lt_n_Sm_le. apply Nat.lt_le_trans with (m:=length (a::b::xs)).\n          apply split_smaller_l with (zs:=l0). symmetry; assumption. assumption.\n        apply Hinl. assumption.\n      + right.\n        destruct IHn0' with (xs:=l0) as (_ & Hinl0).\n          apply lt_n_Sm_le. apply Nat.lt_le_trans with (m:=length (a::b::xs)).\n          apply split_smaller_r with (ys:=l). symmetry; assumption. assumption.\n        apply Hinl0. assumption.\nQed.\n\nTheorem merge_sort_members : sort_members merge_sort.\nProof.\n  intros A le xs x.\n  apply merge_sort_members_le_n0 with (n0:=length xs).\n  auto.\nQed.\n\nTheorem merge_sort_valid : valid_sort merge_sort.\nProof.\n  split.\n  apply merge_sort_length.\n  split.\n  apply merge_sort_sorted.\n  apply merge_sort_members.\nQed.\n", "meta": {"author": "thoferon", "repo": "coq-practice", "sha": "ff8ce42853a959dbe902a84823654ae7d1a9cb6f", "save_path": "github-repos/coq/thoferon-coq-practice", "path": "github-repos/coq/thoferon-coq-practice/coq-practice-ff8ce42853a959dbe902a84823654ae7d1a9cb6f/sorting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6833606701823948}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nSection Relations_1.\nVariable U : Type.\n\nDefinition Relation := U -> U -> Prop.\nVariable R : Relation.\n\nDefinition Reflexive : Prop := forall x:U, R x x.\n\nDefinition Transitive : Prop := forall x y z:U, R x y -> R y z -> R x z.\n\nDefinition Symmetric : Prop := forall x y:U, R x y -> R y x.\n\nDefinition Antisymmetric : Prop := forall x y:U, R x y -> R y x -> x = y.\n\nDefinition contains (R R':Relation) : Prop :=\nforall x y:U, R' x y -> R x y.\n\nDefinition same_relation (R R':Relation) : Prop :=\ncontains R R' /\\ contains R' R.\n\nInductive Preorder : Prop :=\nDefinition_of_preorder : Reflexive -> Transitive -> Preorder.\n\nInductive Order : Prop :=\nDefinition_of_order :\nReflexive -> Transitive -> Antisymmetric -> Order.\n\nInductive Equivalence : Prop :=\nDefinition_of_equivalence :\nReflexive -> Transitive -> Symmetric -> Equivalence.\n\nInductive PER : Prop :=\nDefinition_of_PER : Symmetric -> Transitive -> PER.\n\nEnd Relations_1.\nHint Unfold Reflexive Transitive Antisymmetric Symmetric contains\nsame_relation: sets.\nHint Resolve Definition_of_preorder Definition_of_order\nDefinition_of_equivalence Definition_of_PER: sets.\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/Sets/Relations_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.683360663185678}}
{"text": "Require Import ZArith PArith.\nRequire Import ASN1FP.Aux.StructTactics ASN1FP.Aux.Bits.\nRequire Import Coq.Logic.ProofIrrelevance.\nRequire Import Lia.\n\nRequire Import Coq.ZArith.ZArith.\nRequire Import ASN1FP.Aux.Zlib.\n\nOpen Scope Z.\n\nDefinition nblen (n : Z) : nat := Z.to_nat (Z.log2 n + 1).\n\nInductive container (l : nat) :=\n  cont (v : Z) (N : 0 <= v) (L : (nblen v <= l)%nat) : container l.\n\nDefinition cast_cont {l1 l2 : nat} (c1 : container l1) (E : l1 = l2) : container l2 :=\n  match E in _ = p return container p with\n  | eq_refl => c1\n  end.\n\nHint Rewrite\n     two_power_nat_correct\n     Zpower_nat_Z\n     two_power_nat_equiv\n     Z2Nat.id\n  : rew_Z_bits.\n\nFact join_nneg (l2 : nat) {v1 v2 : Z} (N1 : 0 <= v1) (N2 : 0 <= v2) :\n  0 <= v1 * two_power_nat l2 + v2.\nProof.\n  autorewrite with rew_Z_bits.\n  remember (Z.of_nat l2) as p.\n  remember (2 ^ p) as p2.\n  assert(0 <= p2).\n  {\n    subst.\n    apply Z.pow_nonneg.\n    lia.\n  }\n  eauto with zarith.\nQed.\n\nLemma Zmul_lt_trans (x y a b : Z) :\n  x <= y ->\n  a < x * b ->\n  0 <= b ->\n  a < y * b.\nProof.\n  intros XY A B.\n  replace y with (x + (y - x)) by lia.\n  assert (0 <= y - x) by lia.\n  remember (y - x) as c; clear Heqc XY y.\n  rewrite Z.mul_add_distr_r.\n  generalize (Z.mul_nonneg_nonneg c b H B).\n  lia.\nQed.\n\nLemma Zpow2_positive (x : Z) :\n  0 <= x ->\n  1 <= 2 ^ x.\nProof.\n  intros X.\n  replace 1 with (2 ^ 0).\n  apply Z.log2_le_pow2.\n  apply Z.pow_pos_nonneg.\n  all: try lia.\n  apply Z.log2_nonneg.\nQed.\n\nFact join_nblen\n      {l1 l2 : nat}\n      {v1 v2 : Z}\n      (N1 : 0 <= v1) (N2 : 0 <= v2)\n      (L1 : (nblen v1 <= l1)%nat)\n      (L2 : (nblen v2 <= l2)%nat):\n  (nblen (v1 * two_power_nat l2 + v2) <= l1 + l2)%nat.\nProof.\n  unfold nblen in *.\n  apply Nat2Z.inj_le.\n  rewrite Z2Nat.id.\n  -\n    apply Nat2Z.inj_le in L1.\n    apply Nat2Z.inj_le in L2.\n    rewrite Z2Nat.id in L1.\n    rewrite Z2Nat.id in L2.\n    +\n      assert (Z.log2 (v1 * two_power_nat l2 + v2) < Z.of_nat (l1 + l2)); [|lia].\n      generalize (Nat2Z.is_nonneg l1); intros P1.\n      generalize (Nat2Z.is_nonneg l2); intros P2.\n      rewrite Nat2Z.inj_add, two_power_nat_equiv.\n      remember (Z.of_nat l1) as z1.\n      remember (Z.of_nat l2) as z2.\n      clear Heqz1 Heqz2 l1 l2.\n      assert (Q1 : Z.log2 v1 < z1) by lia; clear L1.\n      assert (Q2 : Z.log2 v2 < z2) by lia; clear L2.\n      assert (Z1 : 1 <= 2 ^ z1) by (apply Zpow2_positive; auto).\n      assert (Z2 : 1 <= 2 ^ z2) by (apply Zpow2_positive; auto).\n      destruct (Z.eq_dec v1 0); [subst; simpl; lia|].\n      assert (W1 : 0 < v1) by lia; clear N1 n.\n      apply Z.log2_lt_pow2 in Q1; auto.\n      assert (T : 0 < v1 * 2 ^ z2 + v2).\n      {\n        remember (2 ^ z2) as p2.\n        assert (0 < v1 * p2) by (apply Z.mul_pos_pos; lia).\n        lia.\n      }\n      destruct (Z.eq_dec v2 0).\n      assert (v1 * 2 ^ z2 + v2 < 2 ^ (z1 + z2)).\n      rewrite Z.pow_add_r by auto.\n      apply Z.mul_lt_mono_pos_r with (p := 2 ^ z2) in Q1; try lia.\n      apply Z.log2_lt_pow2 in H; try apply T.\n      clear T.\n      apply H.\n      assert (W2 : 0 < v2) by lia; clear N2 n.\n\n      apply Z.log2_lt_pow2 in Q2.\n      apply Z.log2_lt_pow2; [apply T|].\n      rewrite Z.pow_add_r by auto.\n      remember (2 ^ z1) as p1; remember (2 ^ z2) as p2;\n        clear Heqp1 Heqp2 P1 P2 z1 z2.\n      assert (V1 : v1 <= p1 - 1) by lia;\n        assert (V2 : v2 <= p2 - 1) by lia;\n        clear Q1 Q2.\n      apply Z.mul_le_mono_nonneg_r with (p := p2) in V1; lia.\n      apply W2.\n    +\n      assert(0<=Z.log2 v2) by apply Z.log2_nonneg; lia.\n    +\n      assert(0<=Z.log2 v1) by apply Z.log2_nonneg; lia.\n  -\n    assert(0<=(Z.log2 (v1 * two_power_nat l2 + v2))) by apply Z.log2_nonneg.\n    lia.\nQed.\n\n\nDefinition join_cont {l1 l2 : nat} (c1 : container l1) (c2 : container l2)\n  : container (l1 + l2) :=\n  match c1, c2 with\n  | cont _ v1 N1 L1, cont _ v2 N2 L2 =>\n    cont (l1 + l2)\n         (v1 * two_power_nat l2 + v2)\n         (join_nneg l2 N1 N2)\n         (join_nblen N1 N2 L1 L2)\n  end.\n\nFact split_div_nneg (l2 : nat) {v : Z} (N : 0 <= v):\n  0 <= v / two_power_nat l2.\nProof.\n  autorewrite with rew_Z_bits.\n  apply Z.div_pos; auto.\n  apply Z.pow_pos_nonneg; lia.\nQed.\n\nFact split_mod_nneg (l2 : nat) {v : Z} (N : 0 <= v) :\n  0 <= v mod two_power_nat l2.\nProof.\n  autorewrite with rew_Z_bits.\n  assert(0 < 2 ^ Z.of_nat l2) by (apply Z.pow_pos_nonneg; lia).\n  apply Z.mod_pos_bound, H.\nQed.\n\nFact split_div_nblen {l1 l2 : nat} {v : Z} (N : 0 <= v)\n      (B : (nblen v <= l1 + l2)%nat) :\n  (0 < l1)%nat ->\n  (0 < l2)%nat ->\n  (nblen (v / two_power_nat l2) <= l1)%nat.\nProof.\n  intros L1 L2.\n  unfold nblen in *.\n  apply Nat2Z.inj_le.\n  apply Nat2Z.inj_le in B.\n  rewrite Z2Nat.id in *;\n    [\n      |(generalize (Z.log2_nonneg v); lia)\n      |(generalize (Z.log2_nonneg (v / two_power_nat l2)); lia)\n    ].\n  rewrite Nat2Z.inj_add in B; rewrite two_power_nat_equiv.\n  assert (N1 : 0 < Z.of_nat l1) by lia; remember (Z.of_nat l1) as n1; clear Heqn1 L1 l1.\n  assert (N2 : 0 < Z.of_nat l2) by lia; remember (Z.of_nat l2) as n2; clear Heqn2 L2 l2.\n  assert (V : Z.log2 v < n1 + n2) by lia; clear B.\n\n  destruct (Z.eq_dec 0 v); [subst; simpl; lia|].\n  assert (P : 0 < v) by lia; clear N n.\n  \n  apply Z.log2_lt_pow2 in V; auto.\n  rewrite Z.pow_add_r in V; try lia.\n  rewrite Z.mul_comm in V.\n  apply Z.div_lt_upper_bound in V.\n  - destruct (Z_lt_le_dec 0 (v / 2 ^ n2)).\n    apply Z.log2_lt_pow2 in V.\n    + lia.\n    + auto.\n    + rewrite Z.log2_nonpos; lia.\n  - replace 0 with (0 ^ n2) by\n        (rewrite Z.pow_0_l by auto; reflexivity).\n    apply Z.pow_lt_mono_l; lia.\nQed.\n\nFact split_mod_nblen {l1 l2 : nat} {v : Z} (N : 0 <= v)\n      (B : (nblen v <= l1 + l2)%nat) :\n  (0 < l1)%nat ->\n  (0 < l2)%nat ->\n  (nblen (v mod two_power_nat l2) <= l2)%nat.\nProof.\n  intros L1 L2.\n  clear L1 B l1.\n  unfold nblen.\n  apply Nat2Z.inj_le.\n  rewrite two_power_nat_equiv.\n  assert (N2 : 0 < Z.of_nat l2) by lia; remember (Z.of_nat l2) as n2; clear Heqn2 L2 l2.\n  rewrite Z2Nat.id; [| generalize (Z.log2_nonneg (v mod 2 ^ n2)); lia].\n  assert (0 < 2 ^ n2) by (apply Z.pow_pos_nonneg; lia).\n  generalize (Z.mod_pos_bound v (2 ^ n2) H);\n    clear H; intros H; destruct H.\n  destruct (Z.eq_dec (v mod 2 ^ n2) 0); [rewrite e; simpl; lia |].\n  assert (P : 0 < v mod 2 ^ n2) by lia; clear H n.\n  apply Z.log2_lt_pow2 in H0; lia.\nQed.\n\nDefinition split_cont {l1 l2: nat} (c : container (l1+l2)) (L1 : (0 < l1)%nat) (L2 : (0 < l2)%nat)\n  : container l1 * container l2 :=\n  match c with\n  | cont _ v N B =>\n    ((cont l1\n           (v / (two_power_nat l2))\n           (split_div_nneg l2 N)\n           (split_div_nblen N B L1 L2)),\n     (cont l2\n           (v mod (two_power_nat l2))\n           (split_mod_nneg l2 N)\n           (split_mod_nblen N B L1 L2)))\n  end.\n\nLemma nblen_positive (x : Z) :\n  (0 < nblen x)%nat.\nProof.\n  unfold nblen.\n  generalize (Z.log2_nonneg x); intros.\n  replace 0%nat with (Z.to_nat 0) by trivial.\n  apply Z2Nat.inj_lt; lia.\nQed.\n\nLemma cont_len_positive {l : nat} (c : container l) :\n  (0 < l)%nat.\nProof.\n  destruct c.\n  generalize (nblen_positive v).\n  lia.\nQed.\n\nDefinition Z_of_cont {l : nat} (c : container l) :=\n  match c with cont _ v _ _ => v end.\n\n(** * common container lengths *)\n\nDefinition cont1 := container 1.\nDefinition cont2 := container 2.\nDefinition cont8 := container 8.\n\nDefinition b1_cont (v : Z) (N : 0 <= v) (L : (nblen v <= 1)%nat) : cont1\n:= cont 1 v N L.\nDefinition b2_cont (v : Z) (N : 0 <= v) (L : (nblen v <= 2)%nat) : cont2\n:= cont 2 v N L.\nDefinition b8_cont (v : Z) (N : 0 <= v) (L : (nblen v <= 8)%nat) : cont8\n:= cont 8 v N L.\n\n(* create and append containers of common lengths *)\nDefinition append_b1_cont (v : Z) (N : 0 <= v) (L : (nblen v <= 1)%nat)\n        {l : nat} (c : container l)\n: container (1 + l) := join_cont (b1_cont v N L) c.\n\nDefinition append_b2_cont (v : Z) (N : 0 <= v) (L : (nblen v <= 2)%nat)\n        {l : nat} (c : container l)\n: container (2 + l) := join_cont (b2_cont v N L) c.\n\nDefinition append_b8_cont (v : Z) (N : 0 <= v) (L : (nblen v <= 8)%nat)\n        {l : nat} (c : container l)\n: container (8 + l) := join_cont (b8_cont v N L) c.\n\n(* common operations *)\nDefinition c2z {l : nat} (c : container l) := Z_of_cont c.\nDefinition c2n {l : nat} (c : container l) := Z.to_nat (c2z c).\n\n(* cut containers of common lengths (from left *)\nFact O_lt_1 : (0 < 1)%nat.\nProof. lia. Qed.\n\nDefinition cut_b1_cont {l : nat} (c : container (1 + l)) (L : (0 < l)%nat)\n: cont1 * container l := split_cont c O_lt_1 L.\n\nFact O_lt_2 : (0 < 2)%nat.\nProof. lia. Qed.\n\nDefinition cut_b2_cont {l : nat} (c : container (2 + l)) (L : (0 < l)%nat)\n: cont2 * container l := split_cont c O_lt_2 L.\n\nFact O_lt_8 : (0 < 8)%nat.\nProof. lia. Qed.\n\nDefinition cut_b8_cont {l : nat} (c : container (8 + l)) (L : (0 < l)%nat)\n: cont8 * container l := split_cont c O_lt_8 L.\n\nLtac uncont :=\n  unfold c2n, c2z, Z_of_cont in *; try reflexivity.\n  \n  \n", "meta": {"author": "digamma-ai", "repo": "asn1fpcoq", "sha": "05094f3824393aeb74e58e4b84f570529a55799c", "save_path": "github-repos/coq/digamma-ai-asn1fpcoq", "path": "github-repos/coq/digamma-ai-asn1fpcoq/asn1fpcoq-05094f3824393aeb74e58e4b84f570529a55799c/coq/Types/BitContainer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6833606631856779}}
{"text": "(**\n挿入ソートの証明駆動開発\n *)\n\n(** * はじめに *)\n\n(**\n挿入ソート (Insertion Sort) を Coq の 「Programコマンド」を使って証明駆動開発してみます。\n\nプログラムの定義や検証の方法は以下のサイトに基づいていますから、併読してください。\nただし、証明そのものは少し違うところがあります。\n\n#<a href=\"http://www.iij-ii.co.jp/lab/techdoc/coqt/coqt8.html\">\nプログラミング Coq 証明駆動開発入門(1)\n</a>#\n*)\n\n(**\nソースコードは、\n#<a href=\"https://github.com/suharahiromichi/coq/blob/master/prog/coq_isort_prog2.v\">\nここ\n</a>\nにあります。\n *)\n\nRequire Import List.\nRequire Import Arith.\nRequire Import Sorting.Permutation.\nRequire Import Sorting.Sorted.\nRequire Import Program.\n\n(** * 準備 *)\n\n(** 証明に perm と sort のコンストラクタを使いますから、\nこれらをHintデータベースに追加します。 *)\n\nHint Resolve perm_nil perm_skip perm_swap perm_trans Permutation_cons : perm.\n\nHint Resolve LSorted_nil LSorted_cons1 LSorted_consn : sort.\n\n(** さらに不等号についての補題\n\n[n < m -> n <= m]\n\nをHintデータベースに追加します。*)\n  \nHint Resolve lt_le_weak : lt_le.\n\n(** * insert の定義と証明 *)\n\n(**\n最初に挿入関数 [insert] を証明付きで定義します。\n定義自体は最初の参考文献とおなじです。\n\nこの関数では、リスト [l] に [a] を挿入した結果が関数の値 [l'] になるので、\nこれらをソートのために使う場合は次の関係を満たす必要があります。\n\n(1) [a] と [l] を結合(cons)したものと、[l'] が Permutation の関係にあること。\n\n(2) [l] がソートされているなら、[l'] もソートされていること。\n\nのふたつです。これに加えて\n\n(3) [a] と リスト [l] と [l'] との関係として、\n\n(3.1) [a] は [l'] の先頭である（[a]が[l]の先頭に置かれる場合）、または、\n\n(3.2) [l] と [l'] の先頭が同じ（[a]が[l]の途中以降に挿入される場合）\n\nを追加しておきます。以上を連言でつないでいます。\nそれを関数の値に記載して、証明することになります。\n\n関数の定義では、サブタイプコアーションが働くので、insert の再帰呼び出しでは、\n証明の部分を無視して、リストだけを返す関数として使うことができます。\n*)\n\nProgram Fixpoint insert (a : nat) (l : list nat) {struct l} : \n  {l' : list nat | Permutation (a :: l) l' /\\\n                   (LocallySorted le l -> LocallySorted le l') /\\\n                   (hd a l' = a \\/ hd a l' = hd a l)} := \n  match l with\n  | nil => a :: nil\n  | x :: l' => \n    if le_gt_dec a x then\n      a :: x :: l'\n  else\n    x :: (insert a l')\n  end.\nObligation 1.\nProof.\n  now auto with sort.\nDefined.\nObligation 2.\n  now auto with sort.\nDefined.\nObligation 3.\nProof.\n  split.\n  - rewrite perm_swap.\n    now auto with perm.\n  - split.\n    + intros Hxl'.\n      assert (LocallySorted le l') as H1 by (inversion Hxl'; auto with sort).\n      assert (LocallySorted le x0) as H2 by auto.\n      destruct x0.\n      * now auto with sort.\n      * inversion Hxl'; simpl in o; destruct o; subst;\n          now auto with sort lt_le.\n    + now auto.\nDefined.\n\n(**\nrewrite では、通常の [=] ではなく、\nPermutation に対する rewrite が行われていることに注意してください。\n\nゴール [Permutation (a :: x :: l') (x :: x0)] に対して、\n[[\nperm_swap : forall (A : Type) (x y : A) (l : list A),\n       Permutation (y :: x :: l) (x :: y :: l)\n]]\nでrewriteすることで、ゴールのPermutationの左側が書き換えられ、\n\n[Permutation (x :: a :: l') (x :: x0)]\n\nが得られます。\nそれができるのは、Import している [Sorting/Permutation.v] のなかで、\n[Instance Permutation_Equivalence] が定義されているからですが、\nこのあたりについては、\n\n#<a href=\"http://www.labri.fr/perso/casteran/CoqArt/TypeClassesTut/typeclassestut.pdf\">\nA Gentle Introduction to Type Classes and Relations in Coq\n</a>#\n\nを参照してください。\n *)\n\n(**\nまた、[auto with sort lt_le] では、\n[apply LSorted_consn] と [apply lt_le] が実行されています。\n *)\n\n(**\n実行してみます。証明の部分を取り除いて値だけを取り出すために、\n[proj1_sig] の演算子 [`] を使います。\n*)\n\nCompute ` (insert 1 [2; 3]).             (** ==> [[1; 2; 3]]  *)\n\nCompute ` (insert 2 [1; 3]).             (** ==> [[1; 2; 3]]  *)\n\n(**\nOCaml のコードを生成してみます。証明の部分のコードは含まれていません。\n *)\n\nExtraction insert.\n(**\n[[\nval insert : nat -> nat list -> nat list\n\nlet rec insert a = function\n| Nil -> Cons (a, Nil)\n| Cons (x, l') ->\n  (match le_gt_dec a x with\n   | Left -> Cons (a, (Cons (x, l')))\n   | Right -> Cons (x, (insert a l')))\n]]\n*)\n\n\n(** * Insertion Sort の定義と証明  *)\n\n(**\n最後にソート関数 isort を証明付きで定義します。\n定義自体は最初の参考文献とおなじです。\n\nまた、その正しさの証明も同じで、ソート前の引数 [l] と、ソート結果の関数値 [l'] に対して、\n\n(1) [l] と [l'] が Permutation の関係であること。\n\n(2) [l'] がソートされていること。\n\nのふたつで、それらを連言でつないでいます。\nそれを関数の値に記載して、証明することになります。\n\n関数の定義では、サブタイプコアーションが働くので、isort の再帰呼び出しのみならず、\n下位処理として呼び出す insert もリストだけを返す関数として使うことができます。\n  *)\n\nProgram Fixpoint isort l {struct l} :  \n  {l' : list nat | Permutation l l' /\\ LocallySorted le l'} := \n  match l with \n  | nil => nil\n  | a :: l' => insert a (isort l')\n  end.\nObligations.\nObligation 1.\nProof.\n  now auto with sort perm.\nDefined.\nObligation 2.\nProof.\n  remember (insert a x).\n  destruct s; subst.\n  destruct a0; subst.\n  simpl.\n  split.\n  - eauto with perm.\n  - destruct a0; now auto.\nDefined.\n\n(**\n実行してみます。証明の部分を取り除いて値だけを取り出すために、\n[proj1_sig] の演算子 [`] を使います。\n*)\n\nCompute ` (isort [0; 2; 1; 3]).             (** ==> [[0; 1; 2; 3]]  *)\n\n\n(**\nOCaml のコードを生成してみます。証明の部分のコードは含まれていません。\n *)\n\nExtraction isort.\n(**\n[[\nval isort : nat list -> nat list\n\nlet rec isort = function\n| Nil -> Nil\n| Cons (a, l') -> insert a (isort l')\n]]\n*)\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/prog/coq_isort_prog2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6833606624115226}}
{"text": "Require Export TopologicalSpaces.\nFrom ZornsLemma Require Export InverseImage.\nRequire Export Continuity.\n\n(* Also called \"final topology\". Its construction is dual\n   (in the categorical sense) to the construction of the weak topology. *)\n\nSection StrongTopology.\n\nVariable A:Type.\nVariable X:forall a:A, TopologicalSpace.\nVariable Y:Type.\nVariable f:forall a:A, point_set (X a) -> Y.\n\nDefinition strong_open (S:Ensemble Y) : Prop :=\n  forall a:A, open (inverse_image (f a) S).\n\nDefinition StrongTopology : TopologicalSpace.\nrefine (Build_TopologicalSpace Y strong_open _ _ _).\n- intros.\n  red; intro.\n  assert (inverse_image (f a) (FamilyUnion F) =\n    IndexedUnion (fun U:{ U:Ensemble Y | In F U } =>\n                   inverse_image (f a) (proj1_sig U))).\n  { apply Extensionality_Ensembles; red; split; red; intros.\n    - destruct H0.\n      inversion H0.\n      exists (exist _ S H1).\n      constructor.\n      exact H2.\n    - destruct H0. destruct H0.\n      destruct a0 as [U].\n      constructor.\n      exists U; trivial.\n  }\n  rewrite H0.\n  apply open_indexed_union.\n  intros.\n  destruct a0 as [U].\n  simpl.\n  apply H; trivial.\n- intros.\n  red; intro.\n  rewrite inverse_image_intersection.\n  apply open_intersection2; (apply H || apply H0).\n- red; intro.\n  rewrite inverse_image_full.\n  apply open_full.\nDefined.\n\nLemma strong_topology_makes_continuous_funcs:\n  forall a:A, continuous (f a) (Y:=StrongTopology).\nProof.\nintros.\nred.\nintros.\nauto.\nQed.\n\nLemma strong_topology_strongest: forall (T':Ensemble Y->Prop)\n  (H1:_) (H2:_) (H3:_),\n  (forall a:A, continuous (f a)\n          (Y:=Build_TopologicalSpace Y T' H1 H2 H3)) ->\n  forall V:Ensemble Y, T' V -> strong_open V.\nProof.\nintros.\nunfold continuous in H.\nsimpl in H.\nred; intros; apply H; trivial.\nQed.\n\nLemma strong_topology_continuous_char (Z : TopologicalSpace)\n      (g : point_set StrongTopology -> point_set Z) :\n  continuous g <->\n  forall a, continuous (compose g (f a)).\nProof.\nsplit.\n- intros. unfold compose.\n  apply continuous_composition; auto.\n  apply strong_topology_makes_continuous_funcs.\n- intros.\n  red; intros.\n  simpl. red. intros.\n  rewrite <- inverse_image_composition.\n  apply H.\n  assumption.\nQed.\n\nEnd StrongTopology.\n\nArguments StrongTopology {A} {X} {Y}.\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/StrongTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6833606603373357}}
{"text": "(* Internal import(s). *)\nRequire Import Basics.Identifier.\nRequire Import Basics.Map.\n\nInductive exp: Type :=\n  (* Primitives. *)\n  | ENat  (x: nat)\n  | EBool (x: bool)\n  | EId   (x: identifier)\n  (* Arithmetic operators. *)\n  | EAdd (e e': exp)\n  | ESub (e e': exp)\n  | EMul (e e': exp)\n  | EDiv (e e': exp)\n  (* Logical operators. *)\n  | EEq  (e e': exp)\n  | ELt  (e e': exp)\n  | ENot (e   : exp)\n  | EAnd (e e': exp)\n  (* If-then-else. *)\n  | EIte   (e e' e'': exp)\n  (* Lambdas. *)\n  | EAbs (x   : identifier) (e: exp)\n  | EFix (x   : identifier) (e: exp)\n  | EApp (e e': exp)\n  (* Hole. *)\n  | EHole.\n\nInductive stack: Type :=\n  | EmptyStack\n  | Stack      (e: exp) (s:stack).\n\nInductive cfg: Type := \n  Cfg (s: stack) (m: map_id_nat).\nDefinition emptyCfg := Cfg EmptyStack map_id_nat_empty.\n\nCoercion ENat : nat        >-> exp.\nCoercion EBool: bool       >-> exp.\nCoercion EId  : identifier >-> exp.\nInfix \"+\"      := EAdd (at level 50, left associativity).\nInfix \"-\"      := ESub (at level 50, left associativity).\nInfix \"*\"      := EMul (at level 40, left associativity).\nInfix \"/\"      := EDiv (at level 40, left associativity).\nInfix \"==?\"    := EEq  (at level 55, left associativity).\nInfix \"<?\"     := ELt  (at level 54, left associativity).\nInfix \"&\"      := EAnd (at level 56, left associativity).\nNotation \"! b\" := (ENot b)   (at level 30, right associativity).\n\nNotation \"'ITE' b 'THEN' c1 'ELSE' c2 'ETI'\" :=\n  (EIte b c1 c2)\n  (at level 70, right associativity).\n\nNotation \"e '~>' st\" := (Stack e st) (at level 80, right associativity).\nNotation \"[ s | m ]\" := (Cfg s m)    (at level 90).\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/Fun/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6833606508793538}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := cons : Nat -> Lst -> Lst |  nil : Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : Lst) : Lst\n           := match rev_arg0 with\n              | nil => nil\n              | cons x y => append (rev y) (cons x nil)\n              end.\n\nTheorem theorem0 : forall (x : Lst) (y : Nat), eq (rev (append x (cons y nil))) (cons y (rev x)).\nProof.\ninduction x.\n- intros. simpl. rewrite IHx. reflexivity.\n- intros. reflexivity.\nQed.\n\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/goal58.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6832920920083636}}
{"text": "Require Import Coq.Unicode.Utf8_core.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Arith.Arith.\n\n\nInductive varSet : Type :=\n| Empty : varSet\n| Var   : nat -> varSet -> varSet.\n\nFixpoint member_ (vs: varSet) (n:nat) : bool :=\nmatch vs with\n| Empty        => false\n| Var m rest => if (beq_nat n m) then true else member_ rest n\nend.\n\nInductive member : varSet -> nat -> Prop :=\n| member_var : forall n rest,  member (Var n rest) n\n| member_rest : forall n1 n2 rest, not (n1 = n2) ->\n                                   member rest n1 ->\n                                   member (Var n2 rest) n2.\n\nInductive notMember : varSet -> nat -> Prop :=\n| notMember_empty : forall n, notMember Empty n\n| notMember_var   : forall n n1 rest, not (n = n1) ->\n                                      notMember rest n ->\n                                      notMember (Var n1 rest) n.\n\nFixpoint add_ (vs : varSet) (n: nat) : varSet :=\n  if (member_ vs n) then\n    vs\n  else\n    (Var n vs).\n\nInductive add : varSet -> nat -> varSet -> Prop :=\n| IsMember : forall n vs, member vs n -> add vs n vs\n| IsNotMember : forall n vs, notMember vs n -> add vs n (Var n vs).\n\nInductive unique : varSet -> Prop :=\n| unique_empty : unique Empty\n| unique_var   : forall n rest, notMember rest n ->\n                                unique rest ->\n                                unique (Var n rest).\n\nFixpoint union_ (vs1 vs2: varSet) : varSet :=\nmatch vs1 with\n| Empty      => vs2\n| Var n rest => union_ rest (add_ vs2 n)\nend.\n\nInductive union : varSet -> varSet -> varSet -> Prop :=\n| union_empty : forall vs, union Empty vs vs\n| union_var   : forall n rest vs vsInt vsRes, add vs n vsInt ->\n                                              union rest vsInt vsRes ->\n                                              union (Var n rest) vs vsRes.\n\nTheorem union_comm :\n  forall v1 v2 vRes,\n    union v1 v2 vRes ->\n    union v2 v1 vRes.\nAdmitted.\n\nTheorem union_unique :\n  forall vs1 vs2 vsRes, unique vs1 ->\n                        unique vs2 ->\n                        union vs1 vs2 vsRes -> \n                        unique vsRes.\nProof.\n  intros vs1 vs2 vsRes Hvs1 Hvs2 Hunion.\n  induction Hunion.\n  - assumption.\n  - apply IHHunion.\n    + inversion Hvs1. subst. assumption.\n    + inversion H; subst.\n      * assumption.\n      * constructor. assumption. assumption.\nQed.\n\nInductive disjoint : varSet -> varSet -> Prop :=\n| disjoint_empty : forall vs, disjoint Empty vs\n| disjoint_var   : forall n rest vs, notMember vs n ->\n                                     disjoint rest vs ->\n                                     disjoint (Var n rest) vs.\n\nInductive subset : varSet -> varSet -> Prop :=\n| subset_empty : forall vs, subset Empty vs\n| subset_var   : forall n rest vs, member vs n ->\n                                   subset rest vs ->\n                                   subset (Var n rest) vs.\n\nTheorem subsets_disjoint :\n  forall v1 v2 va vb,\n  subset v1 va ->\n  subset v2 vb ->\n  disjoint va vb ->\n  disjoint v1 v2.\nProof.\n  Admitted.\n \n\nInductive equal : varSet -> varSet -> Prop :=\n| equal_ : forall vs1 vs2, subset vs1 vs2 -> subset vs2 vs1 -> equal vs1 vs2.\n\nTheorem union_lvar :\n  forall n rest v2 vInt vRes,\n  union rest v2 vInt ->\n  union (Var n rest) v2 vRes ->\n  equal vRes (Var n vInt).\nAdmitted.\n\nTheorem union_rvar :\n  forall n rest v2 vInt vRes,\n  union v2 rest vInt ->\n  union v2 (Var n rest) vRes ->\n  equal vRes (Var n vInt).\nAdmitted.\n\nTheorem subsets_union :\n  forall v1 v2 v3 va vb vc,\n    subset v1 va ->\n    subset v2 vb ->\n    union v1 v2 v3 ->\n    union va vb vc ->\n    subset v3 vc.\nAdmitted.\n\nTheorem self_union :\n  forall v,\n    union v v v.\nAdmitted.\n\nTheorem union_implies_subset :\n  forall a b c,\n    union a b c -> subset a c.\nAdmitted.\n\nTheorem subset_transitivity :\n  forall a b c,\n    subset a b -> subset b c -> subset a c.\nAdmitted.\n\nTheorem union_symmetry :\n  forall a b c,\n    union a b c -> union b a c.\nAdmitted.\n\nTheorem exists_union :\n  forall a b,\n  exists c, union a b c.\nAdmitted.\n\n", "meta": {"author": "SHoltzen", "repo": "verified-sdd", "sha": "d400630db6526997226d6723ff8aedc0f1466901", "save_path": "github-repos/coq/SHoltzen-verified-sdd", "path": "github-repos/coq/SHoltzen-verified-sdd/verified-sdd-d400630db6526997226d6723ff8aedc0f1466901/coq/VarSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564152, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6832920837693617}}
{"text": "Require Import List Program Arith String.\nOpen Scope string_scope.\nOpen Scope list_scope.\n\nRequire Import PFDS.common.DecidableOrder.\nRequire Import PFDS.common.Power.\nRequire Import PFDS.common.Result.\nRequire Import PFDS.common.Util.\n\nDeclare Module Seed : DecidableOrder.Seed.\nModule Elem := DecidableOrder.Make(Seed).\nImport Elem.Op.\n  \nInductive heap : Set :=\n| E : heap\n| T : nat -> Elem.T -> heap -> heap -> heap.\n\nInductive HeapForall (P : Elem.T -> Prop) : heap -> Prop :=\n| HFE : HeapForall P E\n| HFT : forall r x a b, HeapForall P a -> HeapForall P b -> P x -> HeapForall P (T r x a b).\n\nLemma HeapForall_impl : forall (P Q: Elem.T -> Prop),\n    (forall x, P x -> Q x) ->\n    forall h, HeapForall P h -> HeapForall Q h.\nProof.\n  intros P Q Hpq h HForallP. induction HForallP.\n  - now constructor.\n  - now constructor; [| | apply Hpq].\nQed.\n\nFixpoint right_spine(h : heap) :=\n  match h with\n  | E => []\n  | T r x left_ right_ => x :: right_spine right_\n  end.\n\nDefinition calc_rank(h : heap) := List.length (right_spine h).\n\nLemma rank_T : forall r x left_ right_,\n    calc_rank(T r x left_ right_) = 1 + calc_rank(right_).\nProof.\n  now intros.\nQed.\n\nFixpoint size(h : heap) :=\n  match h with\n  | E => 0\n  | T _ _ a b => 1 + size(a) + size(b)\n  end.\n\nInductive Leftist : heap -> Prop :=\n| LeftistE : Leftist E\n| LeftistT : forall a b r x,\n    (calc_rank b <= calc_rank a)%nat -> Leftist a -> Leftist b -> Leftist (T r x a b).\n\n(** ** Exercise 3.1 *)\n\nLemma ex3_1_aux : forall t, Leftist t -> (2 ^^ (calc_rank t) <= size t + 1)%nat.\nProof.\n  induction t as[| r x a IHa b IHb].\n  - reflexivity.\n  - rewrite rank_T. simpl size. intro HLeftist.\n    cutrewrite (S (size a + size b) + 1 = (size a + 1) + (size b + 1)); [| ring].\n    inversion HLeftist as [|a0 b0 r0 x0 Hrank HLa HLb]. subst. apply IHa in HLa. apply IHb in HLb.\n    apply (le_trans _ (pow 2 (calc_rank a) + (size b + 1))); [|now apply plus_le_compat_r].\n    apply (le_trans _ (pow 2 (calc_rank a) + pow 2 (calc_rank b))); [|now apply plus_le_compat_l].\n    rewrite pow_plus. simpl (pow 2 1).\n    cutrewrite (2 * pow 2 (calc_rank b) = pow 2 (calc_rank b) + pow 2 (calc_rank b)); [|ring].\n    apply (plus_le_compat_r). now apply pow_le; [now auto with arith|].\nQed.\n\n(**\n   ** merge関数\n   > どの右スパインの長さもたかだか対数のオーダーであるから、[merge]は O(log n) 時間で実行される。 (p.28)\n *)\n\n(**\n   *** merge関数の実装\n *)\n\nDefinition rank h :=\n  match h with\n  | E => 0\n  | T r _ _ _ => r\n  end.\n\nDefinition makeT x a b :=\n  if le_lt_dec (rank b) (rank a) then T (1 + rank b) x a b\n  else T (1 + rank a) x b a.\n\nRequire Import Recdef.\n\nFunction merge h1_h2 {measure (pair_size size size) h1_h2} :=\n  match (h1_h2) with\n  | (E, h2) => h2\n  | (h1, E) => h1\n  | (T _ x a1 b1 as h1, T _ y a2 b2 as h2) =>\n    if Elem.leq_bool x y then\n      makeT x a1 (merge (b1, h2))\n    else\n      makeT y a2 (merge (h1, b2))\n  end.\nProof. (* 停止性の証明 *)\n  - simpl. now auto with arith.\n  - simpl. now auto with arith.\nDefined.\n\n(**\n   *** merge関数の証明\n*)\n\n(**\n   **** merge関数でrank関数の健全性が保たれる\n*)\n\nInductive RankSound : heap -> Prop :=\n| RSE : RankSound E\n| RST : forall r x a b, RankSound a -> RankSound b -> rank (T r x a b) = calc_rank (T r x a b) -> RankSound(T r x a b).\n\nLemma RankSound_eq : forall h,\n    RankSound h -> rank h = calc_rank h.\nProof.\n  intros h Hrank. now induction Hrank.\nQed.\n\nLemma makeT_rank : forall x a b,\n  RankSound a -> RankSound b ->\n    RankSound (makeT x a b).\nProof.\n  intros x a b Hranka Hrankb. unfold makeT.\n  destruct (le_lt_dec (rank b) (rank a)).\n  - constructor; [assumption| assumption|]. rewrite rank_T. now rewrite (RankSound_eq _ Hrankb).\n  - constructor; [assumption| assumption|]. rewrite rank_T. now rewrite (RankSound_eq _ Hranka).\nQed.\n\nLemma merge_rank : forall h1 h2,\n  RankSound h1 -> RankSound h2 -> RankSound (merge (h1,h2)).\nProof.\n  cut (forall h1h2, RankSound (fst h1h2) -> RankSound (snd h1h2) -> RankSound (merge h1h2)); [intros; now apply H|].\n  intros h1h2. apply merge_ind.\n  - now intros.\n  - now intros.\n  - simpl. intros h1_h2 _r1 x a1 b1 _r2 y a2 b2 Heq Hleq IH Hrank1 Hrank2. subst.\n    inversion Hrank1. inversion Hrank2. subst.\n    apply makeT_rank; [assumption|]. now apply IH.\n  - simpl. intros h1_h2 _r1 x a1 b1 _r2 y a2 b2 Heq Hleq IH Hrank1 Hrank2. subst.\n    inversion Hrank1. inversion Hrank2. subst.\n    apply makeT_rank; [assumption|]. now apply IH.\nQed.\n\n(**\n   **** merge関数でLeftist性が保存される\n*)\n\nLemma makeT_Leftist : forall x a b,\n    RankSound a -> RankSound b ->\n    Leftist a -> Leftist b ->\n    Leftist (makeT x a b).\nProof.\n  intros x a b Hra Hrb Hla Hlb. unfold makeT.\n  destruct (le_lt_dec _ _).\n  - constructor; [|assumption|assumption].\n    now rewrite <- (RankSound_eq _ Hrb), <- (RankSound_eq _ Hra).\n  - constructor; [|assumption|assumption].\n    apply lt_le_weak. now rewrite <- (RankSound_eq _ Hrb), <- (RankSound_eq _ Hra).\nQed.\n\nLemma merge_Leftist : forall h1 h2,\n      RankSound h1 -> RankSound h2 ->\n      Leftist h1 -> Leftist h2 ->\n      Leftist (merge (h1, h2)).\nProof.\n  cut (forall h1h2, RankSound (fst h1h2) -> RankSound (snd h1h2) -> Leftist (fst h1h2) -> Leftist (snd h1h2) -> Leftist (merge h1h2)); [intros; now apply H|].\n  intros h1h2. apply merge_ind.\n  - now intros.\n  - now intros.\n  - simpl. intros h1_h2 _r1 x a1 b1 _r2 y a2 b2 Heq _ IH Hr1 Hr2 Hl1 Hl2.\n    inversion Hr1. inversion Hl1. subst.\n    inversion Hr2. inversion Hl2. subst.\n    apply makeT_Leftist; [assumption| | assumption|].\n    + now apply merge_rank.\n    + now apply IH.\n  - simpl. intros h1_h2 _r1 x a1 b1 _r2 y a2 b2 Heq _ IH Hr1 Hr2 Hl1 Hl2.\n    inversion Hr1. inversion Hl1. subst.\n    inversion Hr2. inversion Hl2. subst.\n    apply makeT_Leftist; [assumption | | assumption|].\n    + now apply merge_rank.\n    + now apply IH.\nQed.\n\n(**\n   **** merge関数とHeapForallのいい関係\n*)\n\nLemma makeT_Forall : forall P x a b,\n    (HeapForall P a /\\ HeapForall P b /\\ P x) <-> HeapForall P (makeT x a b).\nProof.\n  intros P x a b. unfold makeT. destruct (le_lt_dec _ _); split; intros.\n  + now constructor.\n  + now inversion H.\n  + now constructor.\n  + now inversion H.\nQed.\n\nLemma merge_Forall : forall P h1 h2,\n    (HeapForall P h1 /\\ HeapForall P h2) <-> HeapForall P (merge (h1,h2)).\nProof.\n  intros P. cut (forall p, HeapForall P (fst p) /\\ HeapForall P (snd p) <-> HeapForall P (merge p)); [intros; now destruct (H (h1,h2))|].\n  intros h1h2. apply merge_ind.\n  - intros. simpl. split; [tauto|]. now split; [constructor | ].\n  - intros. simpl. split; [tauto|]. now split; [ | constructor].\n  - simpl. intros h1_h2 _r1 x a1 b1 _r2 y a2 b2 Heq _ IH.\n    rewrite <- makeT_Forall. rewrite <- IH. split.\n    + intros H. destruct H as [H1 H2]. inversion H1. now inversion H2.\n    + intros H. split; [|tauto]. now constructor.\n  - simpl. intros h1_h2 _r1 x a1 b1 _r2 y a2 b2 Heq _ IH.\n    rewrite <- makeT_Forall. rewrite <- IH. split.\n    + intros H. destruct H as [H1 H2]. inversion H1. now inversion H2.\n    + intros H. split; [tauto|]. now constructor.\nQed.\n\n\n(**\n   **** merge関数でヒープとしての性質: 「常にrootノードの値が最小値」を保存することを証明\n*)\n\nInductive Heap : heap -> Prop :=\n| HeapE : Heap E\n| HeapT : forall r x a b, Heap a -> Heap b -> HeapForall (fun elem => x <= elem) (T r x a b) -> Heap (T r x a b).\n\nLemma makeT_Heap : forall x a b,\n    Heap a -> Heap b ->\n    HeapForall (fun elem => x <= elem) a ->\n    HeapForall (fun elem => x <= elem) b ->\n    Heap (makeT x a b).\nProof.\nAdmitted.\n\nLemma merge_Heap : forall h1 h2,\n    Heap h1 -> Heap h2 ->\n    Heap (merge (h1,h2)).\nProof.\n  cut (forall p, Heap (fst p) -> Heap (snd p) -> Heap (merge p)); [intros; now apply H|].\n  intro h1h2. apply merge_ind.\n  - now intros.\n  - now intros.\n  - simpl. intros h1_h2 _r1 x a1 b1 _r2 y a2 b2 Heq Hleq IH Hh1 Hh2.\n    inversion Hh1. inversion Hh2. subst.\n    inversion H5. inversion H12. subst.\n    apply makeT_Heap; [assumption| now apply IH|assumption|].\n    apply merge_Forall. split; [assumption |].\n    eapply HeapForall_impl; [|now apply H12]. simpl. intros elem Helem.\n    apply (Elem.Ord.le_trans _ y); [|assumption]. now apply Elem.leq_bool_correct.\n  - simpl. intros h1_h2 _r1 x a1 b1 _r2 y a2 b2 Heq Hleq IH Hh1 Hh2.\n    inversion Hh1. inversion Hh2. subst.\n    inversion H5. inversion H12. subst.\n    apply makeT_Heap; [assumption| now apply IH|assumption|].\n    apply merge_Forall. split; [| assumption].\n    rewrite Elem.leq_bool_correct_inv in Hleq. apply Elem.Ord.not_le_lt in Hleq. apply Elem.Ord.lt_le_incl in Hleq.\n    constructor.\n    + eapply HeapForall_impl; [ |now apply H3]. simpl. intros elem Helem.\n      now apply (Elem.Ord.le_trans _ x).\n    + eapply HeapForall_impl; [ |now apply H7]. simpl. intros elem Helem.\n      now apply (Elem.Ord.le_trans _ x).\n    + assumption.\nQed.\n\n(**\n   ** insert\n*)\n\n(**\n   *** insert関数の実装\n*)\n\nDefinition insert x h := merge (T 1 x E E, h).\n\n(**\n   ** findMin\n*)\n\n(**\n   *** findMin 関数の実装\n*)\n\nDefinition findMin h :=\n  match h with\n  | E => Error \"Empty Heap\"\n  | T _ x _ _ => Ok x\n  end.\n\n(**\n   ** deleteMin\n*)\n\n(**\n   *** deleteMin関数の実装\n*)\n\nDefinition deleteMin h :=\n  match h with\n  | E => Error \"Empty Heap\"\n  | T _ _ a b => Ok (merge(a, b))\n  end.\n", "meta": {"author": "yoshihiro503", "repo": "pfds_coq", "sha": "e7bf965ddeb329886210811e05f1bd4a1e7ccf53", "save_path": "github-repos/coq/yoshihiro503-pfds_coq", "path": "github-repos/coq/yoshihiro503-pfds_coq/pfds_coq-e7bf965ddeb329886210811e05f1bd4a1e7ccf53/3/LeftistHeap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6832910684003707}}
{"text": "Inductive SC : Type :=\n| Value : nat -> SC\n| Unknown : SC.\n\nInductive NatStack : Type :=\n| Empty : NatStack\n| Add : nat -> NatStack -> NatStack.\n\nDefinition pop(s:NatStack) : NatStack :=\nmatch s with\n| Empty => Empty\n| Add _ xs => xs\nend.\n\nDefinition top(s:NatStack) : SC :=\nmatch s with\n| Empty => Unknown\n| Add s' _ => Value s'\nend.\n\nFixpoint isEmpty (s:NatStack):bool:=\nmatch s with\n| Empty => true\n| Add _ s' => false\nend.\n\n(* \nAdd::\nAdd is already a constructor in Inductive Definition. So, need not explicitly define it again.\nPrecondition : Add doesnot have any precondition.\nPost Condition : If we add an element to stack and evaluate top of stack, \n                 it should return the same value.\n                   (top ( Add x xs )) = Value x.\nInvariant : Add an element into stack and pop the stack, \n            will return the original stack eliminating the top value.\n                   (pop ( Add x xs )) = xs.\n*)\n\nTheorem add_post_condition : forall x xs, (top ( Add x xs )) = Value x.\nProof.\n intros.\n simpl.\n reflexivity.\nQed.\n\nTheorem add_invariant : forall x xs, pop ( Add x xs ) = xs.\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\n(*\nPop::\nPrecondition : The stack is not empty.\nPoscondition : This is similar to the invariant of Add.\n               pop ( Add x xs ) = xs.\ninvariant : The post condition is an invariant itself.\n*)\n\nTheorem pop_post_condition : forall x xs, pop ( Add x xs ) = xs.\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\n(*\ntop::\nPrecondition : The stack is not empty.\nPostcondition : Add an element and return the top of the stack,\n                should return the element which we added.\n                    top ( Add x xs) = Value x.\nInvariant : Since top operation not changing the other elements of stack, it should remain unchanged.\n*)\n\nTheorem top_post_condition : forall x xs, top ( Add x xs) = Value x.\nProof.\n intros.\n simpl.\n reflexivity.\nQed.\n\n(*\nisEmpty ::\nPrecondition : Doesn't have any precondition\nPostCondition : The result should return  boolean value(true) if the stack is empty and viceversa.\ninvariant : Since this doesn't have any effects, no invariant exists. \n*)\n\nTheorem isEmpty_post_condition : isEmpty ( Empty ) = true.\nProof.\nsimpl.\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/Exercise2/Ex1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.6832372930777109}}
{"text": "(* This file is distributed under the terms of the MIT License, also\n   known as the X11 Licence.  A copy of this license is in the README\n   file that accompanied the original distribution of this file.\n\n   Based on code written by:\n     Brian Aydemir\n     Arthur Charg\\'eraud *)\n\n(** Lemmas and tactics for working with and solving goals related to\n    non-membership in finite sets.  The main tactic of interest here\n    is [solve_notin].\n\n    Implicit arguments are declared by default in this library. *)\n\nRequire Import Coq.FSets.FSetInterface.\n\nRequire Import Metalib.CoqFSetDecide.\n\n\n(* Suppress warnings about Hint Resolve *)\nLocal Set Warnings \"-fragile-hint-constr\".\n\n\n(* *********************************************************************** *)\n(** * Implementation *)\n\nModule Notin_fun\n  (E : DecidableType) (Import X : FSetInterface.WSfun E).\n\nModule Import D := CoqFSetDecide.WDecide_fun E X.\n\n(* *********************************************************************** *)\n(** * Facts about set non-membership *)\n\nSection Lemmas.\n\nVariables x y  : elt.\nVariable  s s' : X.t.\n\nLemma notin_empty_1 :\n  ~ In x empty.\nProof. fsetdec. Qed.\n\nLemma notin_add_1 :\n  ~ In y (add x s) ->\n  ~ E.eq x y.\nProof. fsetdec. Qed.\n\nLemma notin_add_1' :\n  ~ In y (add x s) ->\n  x <> y.\nProof. fsetdec. Qed.\n\nLemma notin_add_2 :\n  ~ In y (add x s) ->\n  ~ In y s.\nProof. fsetdec. Qed.\n\nLemma notin_add_3 :\n  ~ E.eq x y ->\n  ~ In y s ->\n  ~ In y (add x s).\nProof. fsetdec. Qed.\n\nLemma notin_singleton_1 :\n  ~ In y (singleton x) ->\n  ~ E.eq x y.\nProof. fsetdec. Qed.\n\nLemma notin_singleton_1' :\n  ~ In y (singleton x) ->\n  x <> y.\nProof. fsetdec. Qed.\n\nLemma notin_singleton_2 :\n  ~ E.eq x y ->\n  ~ In y (singleton x).\nProof. fsetdec. Qed.\n\nLemma notin_remove_1 :\n  ~ In y (remove x s) ->\n  E.eq x y \\/ ~ In y s.\nProof. fsetdec. Qed.\n\nLemma notin_remove_2 :\n  ~ In y s ->\n  ~ In y (remove x s).\nProof. fsetdec. Qed.\n\nLemma notin_remove_3 :\n  E.eq x y ->\n  ~ In y (remove x s).\nProof. fsetdec. Qed.\n\nLemma notin_remove_3' :\n  x = y ->\n  ~ In y (remove x s).\nProof. fsetdec. Qed.\n\nLemma notin_union_1 :\n  ~ In x (union s s') ->\n  ~ In x s.\nProof. fsetdec. Qed.\n\nLemma notin_union_2 :\n  ~ In x (union s s') ->\n  ~ In x s'.\nProof. fsetdec. Qed.\n\nLemma notin_union_3 :\n  ~ In x s ->\n  ~ In x s' ->\n  ~ In x (union s s').\nProof. fsetdec. Qed.\n\nLemma notin_inter_1 :\n  ~ In x (inter s s') ->\n  ~ In x s \\/ ~ In x s'.\nProof. fsetdec. Qed.\n\nLemma notin_inter_2 :\n  ~ In x s ->\n  ~ In x (inter s s').\nProof. fsetdec. Qed.\n\nLemma notin_inter_3 :\n  ~ In x s' ->\n  ~ In x (inter s s').\nProof. fsetdec. Qed.\n\nLemma notin_diff_1 :\n  ~ In x (diff s s') ->\n  ~ In x s \\/ In x s'.\nProof. fsetdec. Qed.\n\nLemma notin_diff_2 :\n  ~ In x s ->\n  ~ In x (diff s s').\nProof. fsetdec. Qed.\n\nLemma notin_diff_3 :\n  In x s' ->\n  ~ In x (diff s s').\nProof. fsetdec. Qed.\n\nEnd Lemmas.\n\n\n(* *********************************************************************** *)\n(** * Hints *)\n\n#[global]\nHint Resolve\n  @notin_empty_1 @notin_add_3 @notin_singleton_2 @notin_remove_2\n  @notin_remove_3 @notin_remove_3' @notin_union_3 @notin_inter_2\n  @notin_inter_3 @notin_diff_2 @notin_diff_3 : core. \n\n\n(* *********************************************************************** *)\n(** * Tactics for non-membership *)\n\n(** [destruct_notin] decomposes all hypotheses of the form [~ In x s]. *)\n\nLtac destruct_notin :=\n  match goal with\n    | H : In ?x ?s -> False |- _ =>\n      change (~ In x s) in H;\n      destruct_notin\n    | |- In ?x ?s -> False =>\n      change (~ In x s);\n      destruct_notin\n    | H : ~ In _ empty |- _ =>\n      clear H;\n      destruct_notin\n    | H : ~ In ?y (add ?x ?s) |- _ =>\n      let J1 := fresh \"NotInTac\" in\n      let J2 := fresh \"NotInTac\" in\n      pose proof H as J1;\n      pose proof H as J2;\n      apply notin_add_1 in H;\n      apply notin_add_1' in J1;\n      apply notin_add_2 in J2;\n      destruct_notin\n    | H : ~ In ?y (singleton ?x) |- _ =>\n      let J := fresh \"NotInTac\" in\n      pose proof H as J;\n      apply notin_singleton_1 in H;\n      apply notin_singleton_1' in J;\n      destruct_notin\n    | H : ~ In ?y (remove ?x ?s) |- _ =>\n      let J := fresh \"NotInTac\" in\n      apply notin_remove_1 in H;\n      destruct H as [J | J];\n      destruct_notin\n    | H : ~ In ?x (union ?s ?s') |- _ =>\n      let J := fresh \"NotInTac\" in\n      pose proof H as J;\n      apply notin_union_1 in H;\n      apply notin_union_2 in J;\n      destruct_notin\n    | H : ~ In ?x (inter ?s ?s') |- _ =>\n      let J := fresh \"NotInTac\" in\n      apply notin_inter_1 in H;\n      destruct H as [J | J];\n      destruct_notin\n    | H : ~ In ?x (diff ?s ?s') |- _ =>\n      let J := fresh \"NotInTac\" in\n      apply notin_diff_1 in H;\n      destruct H as [J | J];\n      destruct_notin\n    | _ =>\n      idtac\n  end.\n\n(** [solve_notin] decomposes hypotheses of the form [~ In x s] and\n    then tries some simple heuristics for solving the resulting\n    goals. *)\n\nLtac solve_notin :=\n  intros;\n  destruct_notin;\n  repeat first [ apply notin_union_3\n               | apply notin_add_3\n               | apply notin_singleton_2\n               | apply notin_empty_1\n               ];\n  auto;\n  try tauto;\n  fail \"Not solvable by [solve_notin]; try [destruct_notin]\".\n\n\n(* *********************************************************************** *)\n(** * Examples and test cases *)\n\n(** These examples and test cases are not meant to be exhaustive. *)\n\nLemma test_solve_notin_1 : forall x E F G,\n  ~ In x (union E F) ->\n  ~ In x G ->\n  ~ In x (union E G).\nProof. solve_notin. Qed.\n\nLemma test_solve_notin_2 : forall x y E F G,\n  ~ In x (union E (union (singleton y) F)) ->\n  ~ In x G ->\n  ~ In x (singleton y) /\\ ~ In y (singleton x).\nProof. split. solve_notin. solve_notin. Qed.\n\nLemma test_solve_notin_3 : forall x y,\n  ~ E.eq x y ->\n  ~ In x (singleton y) /\\ ~ In y (singleton x).\nProof. split. solve_notin. solve_notin. Qed.\n\nLemma test_solve_notin_4 : forall x y E F G,\n  ~ In x (union E (union (singleton x) F)) ->\n  ~ In y G.\nProof. solve_notin. Qed.\n\nLemma test_solve_notin_5 : forall x y E F,\n  ~ In x (union E (union (singleton y) F)) ->\n  ~ In y E ->\n  ~ E.eq y x /\\ ~ E.eq x y.\nProof. split. solve_notin. solve_notin. Qed.\n\nLemma test_solve_notin_6 : forall x y E,\n  ~ In x (add y E) ->\n  ~ E.eq x y /\\ ~ In x E.\nProof. split. solve_notin. solve_notin. Qed.\n\nLemma test_solve_notin_7 : forall x,\n  ~ In x (singleton x) ->\n  False.\nProof. solve_notin. Qed.\n\nEnd Notin_fun.\n", "meta": {"author": "plclub", "repo": "metalib", "sha": "4ea92d82286cf66e54b4119b2bb2b039827204ab", "save_path": "github-repos/coq/plclub-metalib", "path": "github-repos/coq/plclub-metalib/metalib-4ea92d82286cf66e54b4119b2bb2b039827204ab/Metalib/FSetWeakNotin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126791, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.6832372786818298}}
{"text": "(*\n  Verificación Formal - Unam 2020-2\n  Ciro Iván García López \n  Proyecto 1. Session Type Systems Verification\n*)\n\n\n(*\nDefinición 2.1, ULL Propositions\n*)\nInductive Proposition : Type := \n  | ONE : Proposition\n  | ABS : Proposition\n  | TEN (A : Proposition) (B : Proposition) : Proposition\n  | PAR (A : Proposition) (B : Proposition) : Proposition\n(*   | ULLT_IMP (A : ULLType) (B : ULLType) : ULLType  *)\n  | EXP (A : Proposition) : Proposition\n  | MOD (A : Proposition) : Proposition.\nHint Constructors Proposition : core.\n\n\n(*\nNotación análoga a la propuesta por el artículo.\nLos niveles de asociatividad se dan siguiendo las ideas de Honda.\n*)\nNotation \"¶\" := ONE.\nNotation \"⊥\" := ABS.\nNotation \"A ⊗ B\" := (TEN A B)(at level 70, right associativity).\nNotation \"A ⅋ B\" := (PAR A B)(at level 70, right associativity).\n(* Notation \"A −∘ B\" := (ULLT_IMP A B)(at level 50, left associativity). *)\nNotation \"! A\" := (EXP A)(at level 60, right associativity).\nNotation \"? A\" := (MOD A)(at level 60, right associativity).\n\n\n(*\nDefinicion 2.2, Dualidad\n*)\nFixpoint Dual_Prop ( T : Proposition ) : Proposition := \nmatch T with \n  | ¶ => ⊥\n  | ⊥ => ¶\n  | A ⊗ B => (Dual_Prop A) ⅋ (Dual_Prop B)\n  | A ⅋ B => (Dual_Prop A) ⊗ (Dual_Prop B)\n  | ! A => ? (Dual_Prop A)\n  | ? A => ! (Dual_Prop A)\nend.\nHint Unfold Dual_Prop : core.\nNotation \"A '^⊥'\" := (Dual_Prop A)(at level 60, right associativity).\n\n\n(*\nDefinición del operador −∘ de acuerdo a los descrito en el primer parrafo de la Definición 2.2.\n*)\nDefinition ULLT_IMP (A : Proposition) (B : Proposition) : Proposition := (A^⊥) ⅋ B.\nNotation \"A −∘ B\" := (ULLT_IMP A B)(at level 70, right associativity).\n\n(*\n⊥\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/ProyI/Defs_Proposition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.78793120560257, "lm_q1q2_score": 0.6831645369357391}}
{"text": "Inductive listN : Set :=\n | Nil : listN\n | Cons : nat -> listN -> listN.\n\nFixpoint app (u1 : listN) (u2 : listN) : listN :=\n  match u1 with\n   | Nil => u2\n   | Cons x r1 => Cons x (app r1 u2)\n  end.\n\nInfix \"::\" := Cons (at level 60, right associativity).\nNotation \"[ ]\" := Nil (format \"[ ]\").\nInfix \"@\" := app (right associativity, at level 60).\n\n(* Révisions (utile pour la suite) *)\nTheorem app_neutre_droite : forall u, u @ [] = u.\nProof.\n  induction u.\n  - reflexivity.\n  - simpl. rewrite IHu. reflexivity.\nQed.\n\nTheorem app_assoc : forall u1 u2 u3, (u1 @ u2) @ u3 = u1 @ (u2 @ u3).\nProof.\n  induction u1.\n  - reflexivity.\n  - simpl. intros. rewrite IHu1. reflexivity.\nQed.\n\nFixpoint rv (u : listN) : listN :=\n  match u with\n   | [] => []\n   | x :: u' => (rv u') @ (x :: [])\n  end.\n\nFixpoint rv_acc (u : listN) (a : listN) : listN :=\n  match u with\n   | [] => a\n   | x :: u' =>  rv_acc u' (x :: a)\n  end.\n\n(* Trouver le lemme auxiliaire utile ! *)\nTheorem rv_acc_rv : forall u, rv_acc u [] = rv u.\nProof.\nAdmitted.\n\n(* Si temps disponible *)\n\nLemma rv_app : forall u v, rv (u @ v) = rv v @ rv u.\nProof.\nAdmitted.\n\nTheorem rv_rv : forall u, rv (rv u) = u.\nProof.\nAdmitted.", "meta": {"author": "LilianSOLER", "repo": "PF7", "sha": "dbe343844a602990cc9061a37d175d4c46e3eef3", "save_path": "github-repos/coq/LilianSOLER-PF7", "path": "github-repos/coq/LilianSOLER-PF7/PF7-dbe343844a602990cc9061a37d175d4c46e3eef3/tps-pf/td5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6831645326180418}}
{"text": "Add LoadPath \"D:\\sfsol\".\nRequire Export Stlc.\n\nModule STLCChecker.\nImport STLC.\n\nFixpoint beq_ty (T1 T2:ty) : bool :=\n  match T1,T2 with\n  | TBool, TBool =>\n      true\n  | TArrow T11 T12, TArrow T21 T22 =>\n      andb (beq_ty T11 T21) (beq_ty T12 T22)\n  | _,_ =>\n      false\n  end.\n\nLemma beq_ty_refl : forall T1,\n  beq_ty T1 T1 = true.\nProof.\n  intros T1. induction T1; simpl.\n    reflexivity.\n    rewrite IHT1_1. rewrite IHT1_2. reflexivity. Qed.\n\nLemma beq_ty__eq : forall T1 T2,\n  beq_ty T1 T2 = true -> T1 = T2.\nProof with auto.\n  intros T1. induction T1; intros T2 Hbeq; destruct T2; inversion Hbeq.\n  Case \"T1=TBool\".\n    reflexivity.\n  Case \"T1=TArrow T1_1 T1_2\".\n    apply andb_true in H0. inversion H0 as [Hbeq1 Hbeq2].\n    apply IHT1_1 in Hbeq1. apply IHT1_2 in Hbeq2. subst... Qed.\n\nFixpoint type_check (Gamma:context) (t:tm) : option ty :=\n  match t with\n  | tvar x => Gamma x\n  | tabs x T11 t12 => match type_check (extend Gamma x T11) t12 with\n                          | Some T12 => Some (TArrow T11 T12)\n                          | _ => None\n                        end\n  | tapp t1 t2 => match type_check Gamma t1, type_check Gamma t2 with\n                      | Some (TArrow T11 T12),Some T2 =>\n                        if beq_ty T11 T2 then Some T12 else None\n                      | _,_ => None\n                    end\n  | ttrue => Some TBool\n  | tfalse => Some TBool\n  | tif x t f => match type_check Gamma x with\n                     | Some TBool =>\n                       match type_check Gamma t, type_check Gamma f with\n                         | Some T1, Some T2 =>\n                           if beq_ty T1 T2 then Some T1 else None\n                         | _,_ => None\n                       end\n                     | _ => None\n                   end\n  end.\n\nTheorem type_checking_sound : forall Gamma t T,\n  type_check Gamma t = Some T -> has_type Gamma t T.\nProof with eauto.\n  intros Gamma t. generalize dependent Gamma.\n  t_cases (induction t) Case; intros Gamma T Htc; inversion Htc.\n  Case \"tvar\"...\n  Case \"tapp\".\n    remember (type_check Gamma t1) as TO1.\n    remember (type_check Gamma t2) as TO2.\n    destruct TO1 as [T1|]; try solve by inversion;\n    destruct T1 as [|T11 T12]; try solve by inversion.\n    destruct TO2 as [T2|]; try solve by inversion.\n    destruct (beq_ty T11 T2) eqn: Heqb;\n    try solve by inversion.\n    apply beq_ty__eq in Heqb.\n    inversion H0; subst...\n  Case \"tabs\".\n    rename i into y. rename t into T1.\n    remember (extend Gamma y T1) as G'.\n    remember (type_check G' t0) as TO2.\n    destruct TO2; try solve by inversion.\n    inversion H0; subst...\n  Case \"ttrue\"...\n  Case \"tfalse\"...\n  Case \"tif\".\n    remember (type_check Gamma t1) as TOc.\n    remember (type_check Gamma t2) as TO1.\n    remember (type_check Gamma t3) as TO2.\n    destruct TOc as [Tc|]; try solve by inversion.\n    destruct Tc; try solve by inversion.\n    destruct TO1 as [T1|]; try solve by inversion.\n    destruct TO2 as [T2|]; try solve by inversion.\n    destruct (beq_ty T1 T2) eqn:Heqb;\n    try solve by inversion.\n    apply beq_ty__eq in Heqb.\n    inversion H0. subst. subst...\nQed.\n\nTheorem type_checking_complete : forall Gamma t T,\n  has_type Gamma t T -> type_check Gamma t = Some T.\nProof with auto.\n  intros Gamma t T Hty.\n  has_type_cases (induction Hty) Case; simpl.\n  Case \"T_Var\"...\n  Case \"T_Abs\". rewrite IHHty...\n  Case \"T_App\".\n    rewrite IHHty1. rewrite IHHty2.\n    rewrite (beq_ty_refl T11)...\n  Case \"T_True\"...\n  Case \"T_False\"...\n  Case \"T_If\". rewrite IHHty1. rewrite IHHty2.\n    rewrite IHHty3. rewrite (beq_ty_refl T)...\nQed.\n\nEnd STLCChecker.", "meta": {"author": "mmalone", "repo": "sfsol", "sha": "5888f4532a1ec1ababa21bef39e25eb26279f0e4", "save_path": "github-repos/coq/mmalone-sfsol", "path": "github-repos/coq/mmalone-sfsol/sfsol-5888f4532a1ec1ababa21bef39e25eb26279f0e4/Typechecking.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.6831645239483414}}
{"text": "Set Implicit Arguments.\n\nRequire Import set.\nRequire Import subset.\nRequire Import equiv.\nRequire Import subset_transitive.\n\nProposition equiv_transitive: forall (a b c:set),\n  equiv a b -> equiv b c -> equiv a c.\nProof.\n  intros a b c Hab Hbc.\n  unfold equiv in Hab. unfold equiv in Hbc.\n  elim Hab. clear Hab. intros Hab Hba.\n  elim Hbc. clear Hbc. intros Hbc Hcb.\n  unfold equiv. split.\n  apply subset_transitive with (b:= b). exact Hab. exact Hbc.\n  apply subset_transitive with (b:= b). exact Hcb. exact Hba.\nQed.\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/set2/equiv_transitive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.6831645120575206}}
{"text": "(**************************************************************************)\n(*           *                                                            *)\n(*     _     *   The Coccinelle Library / Evelyne Contejean               *)\n(*    <o>    *          CNRS-LRI-Universite Paris Sud                     *)\n(*  -/@|@\\-  *                   A3PAT Project                            *)\n(*  -@ | @-  *                                                            *)\n(*  -\\@|@/-  *      This file is distributed under the terms of the       *)\n(*    -v-    *      CeCILL-C licence                                      *)\n(*           *                                                            *)\n(**************************************************************************)\n\nSet Implicit Arguments. \n\nFrom Coq Require Import Setoid Relations List Wellfounded.\nFrom CoLoR Require Export TransClosure.\n\nLemma acc_trans :\n forall A (R : relation A) a, Acc R a -> Acc (trans_clos R) a.\nProof.\nintros A R a Acc_R_a.\ninduction Acc_R_a as [a Acc_R_a IH].\napply Acc_intro.\nintros b b_Rp_a; induction b_Rp_a.\napply IH; trivial.\napply Acc_inv with y.\napply IHb_Rp_a; trivial.\napply t_step; trivial.\nDefined.\n\nLemma wf_trans :\n  forall A (R : relation A) , well_founded R -> well_founded (trans_clos R).\nProof.\nunfold well_founded; intros A R WR.\nintro; apply acc_trans; apply WR; trivial.\nDefined.\n\n\nLemma trans_incl :\n  forall A (R1 R2 : relation A), inclusion _ R1 R2 -> inclusion _ (trans_clos R1) (trans_clos R2).\nProof.\nintros A R1 R2 R1_in_R2 a b H; induction H as [a' b' H | a' b' c' H1 H2].\napply t_step; apply R1_in_R2; trivial.\napply t_trans with b'; trivial.\napply R1_in_R2; trivial.\nQed.\n\nLemma refl_trans_incl :\n  forall A (R1 R2 : relation A), inclusion _ R1 R2 -> inclusion _ (refl_trans_clos R1) (refl_trans_clos R2).\nProof.\nintros A R1 R2 R1_in_R2 a b [a' | a' b' H].\nleft.\napply t_clos; apply trans_incl with R1; assumption.\nQed.\n\nLemma trans_incl2 :\n  forall A B (f : A -> B) (R1 : relation A) (R2 : relation B), \n  (forall a1 a2, R1 a1 a2 -> R2 (f a1) (f a2)) -> \n\tforall a1 a2, trans_clos R1 a1 a2 ->  trans_clos R2 (f a1) (f a2).\nProof.\nintros A B f R1 R2 R1_in_R2 a b H; induction H as [a' b' H | a' b' c' H1 H2].\napply t_step; apply R1_in_R2; trivial.\napply t_trans with (f b'); trivial.\napply R1_in_R2; trivial.\nQed.\n\nLemma trans_with_eq : \n  forall A (R : relation A) a1 a2, \n  trans_clos (union A (@eq _) R) a1 a2 <-> refl_trans_clos R a1 a2.\nProof.\nintros A R a1 a2; split.\nintro H; induction H as [b1 b2 H | b1 b2 b3 H1 H2]. \ndestruct H as [H | H].\nsubst b2; apply r_step; assumption.\napply t_clos; apply t_step; assumption.\ndestruct H1 as [H1 | H1].\nsubst b2; assumption.\ndestruct IHH2 as [b2 | b2 b3 H3].\napply t_clos; apply t_step; assumption.\napply t_clos; apply t_trans with b2; assumption.\n\nintro H; destruct H as [a1 | a1 a2 H].\napply t_step; left; apply eq_refl.\napply (@trans_incl _ R); trivial.\nright; assumption.\nQed.\n\nLemma acc_star : \n   forall A (R : relation A) a, Acc R a -> forall b,  refl_trans_clos  R b a -> Acc R b.\nProof.\nintros A R a Acc_a b H; destruct H as [a1 | a1 a2 H].\nassumption.\napply Acc_incl with (trans_clos R).\nintros b1 b2 H'; apply t_step; assumption.\napply Acc_inv with a2; trivial.\napply acc_trans; trivial.\nQed.\n\nInductive compose_rel A (R1 R2 : relation A) : relation A :=\n  Comp : forall a1 a2 a3, R1 a1 a2 -> R2 a2 a3 -> compose_rel R1 R2 a1 a3.\n\nSection Compose.\nVariable A : Type.\nVariable R1 : relation A.\nVariable R2 : relation A.\n\nLemma trans_union :\n  forall a b,\n  trans_clos (union _ R1 R2) a b <-> \n  union _ (trans_clos R1) \n            (compose_rel (refl_trans_clos R1) (trans_clos (compose_rel R2 (refl_trans_clos R1)))) a b.\nProof.\nintros a b; split.\n(* 1/2 -> *)\nintro H; induction H as [x y H1 | x y z H1 Hn].\ndestruct H1 as [H1 | H1].\nleft; apply t_step; assumption.\nright; apply Comp with x.\napply r_step.\napply t_step.\napply Comp with y; trivial.\napply r_step.\ndestruct H1 as [H1 | H2]; destruct IHHn as [IHHn | IHHn].\nleft; apply t_trans with y; trivial.\nright; inversion IHHn as [x' y' z' K1 K2]; subst x' z'; clear IHHn.\napply Comp with y'.\ninversion K1 as [y1 | y1 y2 K1']; clear K1.\nsubst y1 y'; apply t_clos; apply t_step; trivial.\nsubst y1 y2; apply t_clos; apply t_trans with y; trivial.\ntrivial.\nright.\napply Comp with x.\napply r_step.\napply t_step; apply Comp with y; trivial.\napply t_clos; trivial.\nright; inversion IHHn as [x' y' z' K1 K2]; subst x' z'; clear IHHn.\napply Comp with x.\napply r_step.\napply t_trans with y'; trivial.\napply Comp with y; trivial.\n(* 1/1 <- *)\nintros [H | H].\napply trans_incl with R1; trivial.\nintros; left; trivial.\ninversion H as [x' y' z' K1 K2]; clear H; subst x' z'.\ninversion K1 as [y1 | y1 y2 K1']; clear K1.\nsubst y1 y'.\napply trans_clos_is_clos.\napply trans_incl with (compose_rel R2 (refl_trans_clos R1)); trivial.\nclear a b K2; intros a b K2.\ninversion K2 as [x' y' z' K1 K2']; clear K2; subst x' z'.\ninversion K2' as [y1 | y1 y2 K2'']; clear K2'.\nsubst y1 y'; apply t_step; right; trivial.\nsubst y1 y2.\napply t_trans with y'.\nright; trivial.\napply trans_incl with R1; trivial.\nintros; left; trivial.\nsubst y1 y2.\napply trans_clos_is_trans with y'.\napply trans_incl with R1; trivial.\nintros; left; trivial.\napply trans_clos_is_clos.\napply trans_incl with (compose_rel R2 (refl_trans_clos R1)); trivial.\nclear a b y' K1' K2; intros a b K2.\ninversion K2 as [x' y' z' K1 K2']; clear K2; subst x' z'.\ninversion K2' as [y1 | y1 y2 K2'']; clear K2'.\nsubst y' y1.\nleft; right; trivial.\nsubst y1 y2.\nright with y'.\nright; trivial.\napply trans_incl with R1; trivial.\nintros; left; trivial.\nQed.\n\nLemma trans_union_alt :\n  forall a b,\n  trans_clos (union _ R1 R2) a b <-> \n  union _ (trans_clos R1) \n             (compose_rel (trans_clos (compose_rel (refl_trans_clos R1) R2)) \n                                  (refl_trans_clos R1)) a b.\nProof.\nintros a b; split.\n(* 1/2 -> *)\nrewrite trans_clos_trans_clos_alt in *; intro H; induction H as [x y H1 | x y z H1 IHH1 Hn].\n(* 1/3 one step *)\ndestruct H1 as [H1 | H1].\nleft; left; assumption.\nright; apply Comp with y.\nleft; apply Comp with x; trivial.\nleft.\nleft.\n(* 1/2 several steps *)\ndestruct IHH1 as [IHH1 | IHH1]; destruct Hn as [Hn | Hn].\n(* 1/5 *)\nleft; rewrite trans_clos_trans_clos_alt in *; right with y; trivial.\n(* 1/4 *)\nright; apply Comp with z.\nleft; apply Comp with y; trivial.\nright; trivial.\nleft.\n(* 1/3 *)\ninversion IHH1 as [x' y' z' K1 K2]; subst x' z'; clear IHH1.\nright; apply Comp with y'; trivial.\ninversion K2 as [y'' | a a' K2' K2''].\nsubst y' y''.\nright; left; trivial.\nsubst a a'; right; apply trans_clos_is_trans with y; trivial.\nleft; trivial.\n(* 1/2 *)\ninversion IHH1 as [x' y' z' K1 K2]; subst x' z'; clear IHH1.\nright.\napply Comp with z.\napply trans_clos_is_trans with y'; trivial.\nleft; apply Comp with y; trivial.\nleft.\n(* 1/1 <- *)\nintros [H | H].\napply trans_incl with R1; trivial.\nintros; left; trivial.\ninversion H as [x' y' z' K1 K2]; clear H; subst x' z'.\ninversion K2 as [y1 | y1 y2 K2']; clear K2.\nsubst y1 y'.\napply trans_clos_is_clos.\napply trans_incl with (compose_rel (refl_trans_clos R1) R2); trivial.\nclear a b K1; intros a b H.\ninversion H as [x' y' z' K1 K2]; subst x' z'; clear H.\ninversion K1 as [y1 | y1 y2 K1']; clear K1.\nsubst y1 y'; apply t_step; right; trivial.\nsubst y1 y2.\napply trans_clos_is_trans with y'.\napply trans_incl with R1; trivial.\nintros; left; trivial.\nleft; right; trivial.\nsubst y1 y2.\napply trans_clos_is_trans with y'.\napply trans_clos_is_clos.\napply trans_incl with (compose_rel (refl_trans_clos R1) R2); trivial.\nclear a b y' K1 K2'; intros a b H.\ninversion H as [x' y' z' K1 K2]; subst x' z'; clear H.\ninversion K1 as [y1 | y1 y2 K1']; clear K1.\nsubst y1 y'; apply t_step; right; trivial.\nsubst y1 y2.\napply trans_clos_is_trans with y'.\napply trans_incl with R1; trivial.\nintros; left; trivial.\nleft; right; trivial.\napply trans_incl with R1; trivial.\nintros; left; trivial.\nQed.\n\nLemma acc_union :\n  well_founded R1 ->\n  forall a, Acc (compose_rel R2 (refl_trans_clos R1)) a <-> Acc (union _ R1 R2) a.\nProof.\nintros W1'.\nassert (W1 := wf_trans W1'); clear W1'.\nintros a; split.\nintro Acc_a; induction Acc_a as [a Acc_a' IH2].\nassert (Acc_a : Acc (compose_rel R2 (refl_trans_clos R1)) a).\napply Acc_intro; trivial.\nclear Acc_a'.\nrevert IH2 Acc_a.\npattern a; apply (well_founded_ind W1); clear a.\nintros a IH1 IH2 Acc_a.\napply Acc_intro.\nintros b [H1 | H2].\napply IH1.\napply t_step; trivial.\nintros c H2; apply IH2.\ninversion H2 as [c' d' b' H H']; subst.\napply Comp with d'; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; trivial.\napply Acc_intro; intros c H2.\napply Acc_inv with a; trivial.\ninversion H2 as [c' d' b' H H']; subst.\napply Comp with d'; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; trivial.\napply IH2.\napply Comp with a; trivial.\napply r_step.\n\nintro Acc_a; apply Acc_incl with (trans_clos (union _ R1 R2)).\nintros a1 a3 H; inversion H as [b1 b2 b3 H1 H2]; clear H; subst a1 a3.\ninversion H2 as [b | a2 a3 K2]; clear H2; subst.\nleft; right; assumption.\napply t_trans with b2.\nright; assumption.\napply trans_incl with R1; trivial.\nintros x y H; left; assumption.\napply acc_trans; assumption.\nQed.\n\nLemma acc_union_weak :\n  forall a, Acc (compose_rel R2 (refl_trans_clos R1)) a -> \n              (forall b, refl_trans_clos (compose_rel R2 (refl_trans_clos R1)) b a -> Acc R1 b) -> \n              Acc (union _ R1 R2) a.\nProof.\nintros a Acc_a H; \ninduction Acc_a as [a Acc_a' IH2].\nassert (Acc_a : Acc (compose_rel R2 (refl_trans_clos R1)) a).\napply Acc_intro; trivial.\nclear Acc_a'.\nassert (Acc1_a : Acc R1 a).\napply H; left.\nrevert IH2 H Acc_a.\ninduction Acc1_a as [a Acc1_a IH1].\nintros IH2 H Acc_a.\napply Acc_intro.\nintros b [H1 | H2].\napply IH1; trivial.\nintros c H2; apply IH2.\ninversion H2 as [c' d' b' h H']; subst.\napply Comp with d'; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; trivial.\nintros c K; inversion K; clear K; subst.\napply Acc1_a; assumption.\napply H.\nrewrite trans_clos_trans_clos_alt in H0.\ninversion H0; clear H0; subst.\nright; left.\ninversion H2; clear H2; subst.\napply Comp with a2; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; exact H1.\ninversion H3; clear H3; subst.\napply refl_trans_clos_is_trans with y; trivial.\nright; rewrite trans_clos_trans_clos_alt; assumption.\nright; left.\napply Comp with a2; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; exact H1.\napply Acc_intro; intros c K.\napply Acc_inv with a; trivial.\ninversion K; clear K; subst.\napply Comp with a2; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; exact H1.\n\napply IH2.\napply Comp with a; [assumption | left].\nintros c K; apply H.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; apply Comp with a; [assumption | left].\nQed.\n\nLemma acc_union_alt :\n  well_founded R1 ->\n  forall a, (forall b, refl_trans_clos R1 b a -> Acc (compose_rel (refl_trans_clos R1) R2) b) <-> Acc (union _ R1 R2) a.\nProof.\nintros W1'; split.\nintro Ha; apply acc_union_weak; trivial.\napply Acc_intro; intros b4 H.\ninversion H as [a4 b2 a1 H' H21]; clear H; subst.\nassert (Acc_b2 := Ha b2 H21).\nrevert a Ha b4 H' H21; induction Acc_b2 as [b2 Acc_b2 IH].\nintros a Ha b4 H' H21.\napply Acc_intro.\nintros b6 H.\ninversion H as [a6 b5 a4 H65 H54]; clear H; subst.\napply IH with b5 b4; trivial.\napply Comp with b4; trivial.\nintros b7 H7.\napply Acc_b2.\napply Comp with b4; trivial.\n\nintros Acc_a b H; apply Acc_incl with (trans_clos (union _ R1 R2)).\nclear b H; intros a1 a3 H; inversion H as [b1 b2 b3 H1 H2]; clear H; subst a1 a3.\ninversion H1 as [b | a2 a3 K1]; clear H1; subst.\nleft; right; assumption.\napply trans_clos_is_trans with b2.\napply trans_incl with R1; trivial.\nintros x y H; left; assumption.\nleft; right; assumption.\ninversion H as [a' | b' a' K]; clear H.\napply acc_trans; assumption.\nsubst; apply Acc_inv with a.\napply acc_trans; assumption.\napply trans_incl with R1; trivial.\nintros x y H; left; assumption.\nQed.\n\nLemma acc_union_alt_weak :\n  forall a, (forall b, refl_trans_clos (compose_rel R2 (refl_trans_clos R1)) b a -> Acc R1 b) ->\n               (forall b, refl_trans_clos R1 b a -> Acc (compose_rel (refl_trans_clos R1) R2) b) -> \n              Acc (union _ R1 R2) a.\nProof.\nintros a H1a H2a.\napply acc_union_weak; trivial.\nclear H1a.\napply Acc_intro; intros b4 H.\ninversion H as [a4 b2 a1 H' H21]; clear H; subst.\nassert (Acc_b2 := H2a b2 H21).\nrevert a H2a b4 H' H21; induction Acc_b2 as [b2 Acc_b2 IH].\nintros a Ha b4 H' H21.\napply Acc_intro.\nintros b6 H.\ninversion H as [a6 b5 a4 H65 H54]; clear H; subst.\napply IH with b5 b4; trivial.\napply Comp with b4; trivial.\nintros b7 H7.\napply Acc_b2.\napply Comp with b4; trivial.\nQed.\n\nLemma wf_union_alt :\n  well_founded R1 ->\n  (well_founded (compose_rel (refl_trans_clos R1) R2) <-> well_founded (union _ R1 R2)).\nProof.\nintros W1'; split.\nintro W; intro a; rewrite <- acc_union; trivial.\nassert (W1 := wf_trans W1'); clear W1'.\napply Acc_intro.\nintros b4 H.\ninversion H as [a4 b2 a1 H' H21]; clear H; subst.\nclear a H21.\nrevert b4 H'.\npattern b2; apply (well_founded_ind (wf_trans W)); clear b2.\nintros a IH b H.\napply Acc_intro; intros c K.\ninversion K as [d' c' b' H1 H2];clear K; subst.\napply IH with c'; trivial.\nleft; apply Comp with b; trivial.\n\nintros W a; apply Acc_incl with (trans_clos (union _ R1 R2)).\nintros a1 a3 H; inversion H as [b1 b2 b3 H1 H2]; clear H; subst a1 a3.\ninversion H1 as [b | a2 a3 K1]; clear H1; subst.\nleft; right; assumption.\napply trans_clos_is_trans with b2.\napply trans_incl with R1; trivial.\nintros x y H; left; assumption.\nleft; right; assumption.\napply acc_trans; apply W.\nQed.\n\nLemma acc_comp_incl :\n  forall R, (forall a, Acc R a -> Acc (union _ R1 R2) a) -> \n  forall a, Acc R a -> Acc (compose_rel (refl_trans_clos R1) R2) a.\nProof.\nintros R H a Acc_a.\napply Acc_incl with (trans_clos (union _ R1 R2)).\nclear; intros a b H.\ninversion H as [c1 c2 c3 K1 K2]; clear H; subst.\ninversion K1 as [c | b1 b2 K3 K4]; clear K1; subst.\nleft; right; assumption.\napply trans_clos_is_trans with c2.\napply trans_incl with R1; trivial.\nclear; intros a b H; left; assumption.\nleft; right; assumption.\napply acc_trans.\napply H; assumption.\nQed.\n\nEnd Compose.\n\nDefinition rest A P R := fun (a b : A) => R a b /\\ P a /\\ P b.\n\nLemma rest_union : forall A P (R1 R2 : relation A) a b, rest P (union _ R1 R2) a b <-> union _ (rest P R1) (rest P R2) a b.\nintros A P R1 R2 a b; split.\nintros [[H1 | H2] [Pa Pb]]; [left | right]; repeat split; assumption.\nintros [[H1 [Pa Pb]] | [H2 [Pa Pb]]]; repeat split; trivial.\nleft; assumption.\nright; assumption.\nQed.\n\nLemma rest_trans : \n   forall A (P : A -> Prop) (R : relation A), (forall a b, P a -> R b a -> P b) -> \n\tforall a, P a -> forall b, trans_clos (rest P R) b a <-> trans_clos R b a.\nProof.\nintros A P R Inv a Pa b; split.\napply trans_incl; intros x y [H _]; assumption.\nintro H; rewrite trans_clos_trans_clos_alt in H; rewrite trans_clos_trans_clos_alt.\ninduction H as [x y K | x y z K1 K2].\nleft; repeat split; trivial.\napply Inv with y; assumption.\nassert (Py := Inv _ _ Pa H).\nright with y.\nexact (K2 Py).\nrepeat split; assumption.\nQed.\n\nLemma acc_rest : \n  forall A (R : relation A) (P : A -> Prop),\n  (forall (a b : A), P a -> R b a -> P b) -> \n  (forall a, (P a -> Acc R a) <-> Acc (rest P R) a).\nProof.\nintros A R P Inv a; split.\nintro K; apply Acc_intro; intros b [H [Wb Wa]].\napply Acc_inv with a; trivial.\napply Acc_incl with R.\nclear; intros a b [H _]; assumption.\napply K; assumption.\nrepeat split; assumption.\nintro Acc_a; induction Acc_a as [a Acc_a IH].\nintro Pa; apply Acc_intro; intros b H.\napply IH.\nrepeat split; trivial.\napply Inv with a; assumption.\napply Inv with a; assumption.\nQed.\n\nLemma wf_rest : \n  forall A (R : relation A) (P : A -> Prop),\n  (forall (a b : A), P a -> R b a -> P b) -> \n  ((forall a, P a -> Acc R a) <->  well_founded (rest P R)).\nProof.\nintros A R P Inv; split.\nintros W a; rewrite <- acc_rest; trivial.\napply W.\nintros W a; rewrite acc_rest; trivial.\nQed.\n\nLemma acc_union_rest :\n  forall A (R1 R2 : relation A) (P : A -> Prop),\n  (forall (a b : A), P a -> R1 b a -> P b) -> \n  (forall (a b : A), P a -> R2 b a -> P b) -> \n  (forall a, P a -> Acc R1 a) ->\n  forall a, P a -> Acc (compose_rel R2 (refl_trans_clos R1)) a -> Acc (union _ R1 R2) a.\nProof.\nintros A R1 R2 P Inv1 Inv2 W1' a Wa Acc_a.\nrewrite wf_rest in W1'.\nset (R1' := fun a b => R1 a b /\\ P a /\\ P b) in *.\nassert (W1 := wf_trans W1'); clear W1'.\nrevert Wa; induction Acc_a as [a Acc_a' IH2].\nassert (Acc_a : Acc (compose_rel R2 (refl_trans_clos R1)) a).\napply Acc_intro; trivial.\nclear Acc_a'.\nrevert IH2 Acc_a.\npattern a; apply (well_founded_ind W1); clear a.\nintros a IH1 IH2 Acc_a Wa.\napply Acc_intro.\nintros b [H1 | H2].\napply IH1.\napply t_step; repeat split; trivial.\napply Inv1 with a; trivial.\nintros c H2; apply IH2.\ninversion H2 as [c' d' b' H H']; subst.\napply Comp with d'; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; trivial.\napply Acc_intro; intros c H2.\napply Acc_inv with a; trivial.\ninversion H2 as [c' d' b' H H']; subst.\napply Comp with d'; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; trivial.\napply Inv1 with a; trivial.\napply IH2.\napply Comp with a; trivial.\napply r_step.\napply Inv2 with a; trivial.\ntrivial.\nQed.\n\nLemma acc_union_rest_alt :\n  forall A (R1 R2 : relation A) (P : A -> Prop),\n  (forall (a b : A), P a -> R1 b a -> P b) -> \n  (forall (a b : A), P a -> R2 b a -> P b) -> \n  (forall a, P a -> Acc R1 a) ->\n  (forall a, (forall b, refl_trans_clos R1 b a -> Acc (compose_rel (refl_trans_clos R1) R2) b) -> P a -> Acc (union _ R1 R2) a).\nProof.\nintros A R1 R2 P Inv1 Inv2 W1' a W Pa.\nassert (H : Acc (union _ (rest P R1) (rest P R2)) a).\nrewrite <- acc_union_alt.\nintros b H; apply Acc_incl with (compose_rel (refl_trans_clos R1) R2).\nclear; intros a1 a2 H; inversion H as [c1 a c2 H1 [H2 _]]; subst.\napply Comp with a; [idtac | assumption].\napply refl_trans_incl with (rest P R1); [idtac | assumption].\nclear; intros a1 a2 [H _]; assumption.\napply W.\napply refl_trans_incl with (rest P R1); [idtac | assumption].\nclear; intros a1 a2 [H _]; assumption.\nrewrite wf_rest in W1'; assumption.\nclear W; revert Pa; induction H as [a Acc_a IH].\nintro Pa; apply Acc_intro; intros a1 [H1 | H2]; apply IH.\nleft; repeat split; trivial.\napply Inv1 with a; assumption.\napply Inv1 with a; assumption.\nright; repeat split; trivial.\napply Inv2 with a; assumption.\napply Inv2 with a; assumption.\nQed.\n\nLemma acc_union_rest_alt_weak :\n  forall A (R1 R2 : relation A) (P : A -> Prop),\n  (forall (a b : A), P a -> R1 b a -> P b) -> \n  (forall (a b : A), P a -> R2 b a -> P b) -> \n  forall a, (forall b, refl_trans_clos (compose_rel R2 (refl_trans_clos R1)) b a -> Acc R1 b) ->\n               (forall b, refl_trans_clos R1 b a -> Acc (compose_rel (refl_trans_clos R1) R2) b) -> \n               P a -> Acc (union _ R1 R2) a.\nProof.\nintros A R1 R2 P Inv1 Inv2 a H1a H2a Pa.\nassert (H : Acc (union _ (rest P R1) (rest P R2)) a).\napply acc_union_alt_weak.\nintros b H; apply Acc_incl with R1.\nclear; intros a1 a2 [H _]; assumption.\napply H1a.\napply refl_trans_incl with (compose_rel (rest P R2) (refl_trans_clos (rest P R1))); trivial.\nclear; intros a1 a2 H; inversion H as [c1 a c2 H1 H2]; subst.\napply Comp with a.\ninversion H1; trivial.\napply refl_trans_incl with (rest P R1); [idtac | assumption].\nclear; intros a1 a2 [H _]; assumption.\n\nintros b H; apply Acc_incl with (compose_rel (refl_trans_clos R1) R2).\nclear; intros a1 a2 H; inversion H as [c1 a c2 H1 [H2 _]]; subst.\napply Comp with a; [idtac | assumption].\napply refl_trans_incl with (rest P R1); [idtac | assumption].\nclear; intros a1 a2 [H _]; assumption.\napply H2a.\napply refl_trans_incl with (rest P R1); [idtac | assumption].\nclear; intros a1 a2 [H _]; assumption.\nclear H1a H2a; revert Pa; induction H as [a Acc_a IH].\nintro Pa; apply Acc_intro; intros a1 [H1 | H2]; apply IH.\nleft; repeat split; trivial.\napply Inv1 with a; assumption.\napply Inv1 with a; assumption.\nright; repeat split; trivial.\napply Inv2 with a; assumption.\napply Inv2 with a; assumption.\nQed.\n\nLemma accR2 : forall A (R : relation A) a, Acc R a <-> Acc (compose_rel R R) a.\nProof.\nintros A R a; split.\nintro Acc_a; apply Acc_incl with (trans_clos R).\nintros x z H; inversion H as [x' y z' H1 H2]; clear H; subst; apply t_trans with y; trivial.\napply t_step; trivial.\napply acc_trans; trivial.\nintros Acc_a; induction Acc_a as [a Acc_a IH].\napply Acc_intro; intros b H; apply Acc_intro; intros c H'.\napply IH; apply Comp with b; trivial.\nQed.\n\nLemma acc_inv_im : \n\tforall A B (R1 : relation A) (R2 : relation B) (f : A -> B),\n\t(forall a1 a2, R1 a1 a2 -> R2 (f a1) (f a2)) ->\n\tforall a, Acc R2 (f a) -> Acc R1 a.\nProof.\nintros A B R1 R2 f H a.\nset (b := f a) in *.\nassert (b_eq_fa := eq_refl b).\nunfold b at 2 in b_eq_fa; clearbody b.\nintro Acc_b; revert a b_eq_fa; induction Acc_b as [b Acc_b IH].\nintros a b_eq_fa; apply Acc_intro; intros a' H'.\napply IH with (f a'); trivial.\nsubst b; apply H; trivial.\nQed.\n\nLemma acc_inv_im2 :\n   forall A B (R1 : relation A) (R2 : relation B) (f : A -> B),\n  forall a, (forall a1 a2 a3, R1 a3 a2 -> R1 a2 a1 -> refl_trans_clos R1 a1 a -> R2 (f a2) (f a1)) ->\n  Acc R2 (f a) -> Acc R1 a.\nProof.\nintros A B R1 R2 f a Hinv Acc_b.\nset (b := f a) in *.\nassert (b_eq_fa := eq_refl b).\nunfold b at 2 in b_eq_fa; clearbody b.\nrevert a b_eq_fa Hinv; induction Acc_b as [b Acc_b IH].\nintros a b_eq_fa Hinv.\napply Acc_intro; intros a2 H2.\napply Acc_intro; intros a3 H3.\napply Acc_inv with a2; trivial.\napply IH with (f a2); trivial.\nsubst b; apply Hinv with a3; trivial.\nleft.\nrevert Hinv H2; clear; intros Hinv H2.\nintros b1 b2 b3 K3 K2 K1.\napply Hinv with b3; trivial.\ninversion K1 as [b | b' a' K1'].\nright; left; assumption.\nright; apply trans_clos_is_trans with a2; trivial.\nleft; assumption.\nQed.\n\nLemma acc_inv_im3 :\n   forall A B (R1 : relation A) (R2 : relation B) (f : A -> B),\n  forall a, (forall a1 a2, R1 a2 a1 -> refl_trans_clos R1 a1 a -> R2 (f a2) (f a1)) ->\n  Acc R2 (f a) -> Acc R1 a.\nProof.\nintros A B R1 R2 f a Hinv Acc_b.\nset (b := f a) in *.\nassert (b_eq_fa := eq_refl b).\nunfold b at 2 in b_eq_fa; clearbody b.\nrevert a b_eq_fa Hinv; induction Acc_b as [b Acc_b IH].\nintros a b_eq_fa Hinv.\napply Acc_intro; intros a2 H2.\napply IH with (f a2); trivial.\nsubst b; apply Hinv; trivial.\nleft.\nrevert Hinv H2; clear; intros Hinv H2.\nintros b1 b2 K2 K1.\napply Hinv; trivial.\ninversion K1 as [b | b' a' K1'].\nright; left; assumption.\nright; apply trans_clos_is_trans with a2; trivial.\nleft; assumption.\nQed.\n\nLemma union_equiv : \nforall A R1 R2 R3 R4 (R1_equiv_R3: forall x y, R1 x y <-> R3 x y)\n(R2_equiv_R4: forall x y, R2 x y <-> R4 x y) x y,\n(union A R1 R2 x y <-> union _ R3 R4 x y).\nProof.\n  intros A R1 R2 R3 R4 R1_equiv_R3 R2_equiv_R4 x y.\n  split;intro H;case H.\n  rewrite R1_equiv_R3;intro H';left;exact H'.\n  rewrite R2_equiv_R4;intro H';right;exact H'.\n  rewrite <- R1_equiv_R3;intro H';left;exact H'.\n  rewrite <- R2_equiv_R4;intro H';right;exact H'.\nQed.\n\nLemma union_sym : forall A R1 R2 x y, union A R1 R2 x y <-> union A R2 R1 x y.\nProof. \n  intros A R1 R2 x y.\n  split;  (inversion_clear 1;[right|left];assumption).\nQed.\n\nLemma union_assoc : \n  forall A R1 R2 R3 x y, union A (union A R1 R2) R3 x y <-> union A R1 (union A R2 R3) x y.\nProof.\n  intros A R1 R2 R3 x y.\n  split.\n  intro H.\n  case H;clear H;intro H.\n  case H;clear H;intro H.\n  left;assumption.\n  right;left;assumption.\n  right;right;assumption.\n  intro H.\n  case H;clear H;intro H.\n  left;left;assumption.\n  case H;clear H;intro H.\n  left;right;assumption.\n  right;assumption.\nQed.\n\nLemma union_idem : forall A R x y, union A R R x y <-> R x y.\nProof.\n  intros A R x y.\n  split.\n  inversion_clear 1;assumption.\n  intro H;left;assumption.\nQed.\n\nLemma union_idem_strong : forall A (R R': A -> A -> Prop) (H:forall x y, R x y -> R' x y) x y, (union A R R' x y <-> R' x y).\nProof.\n  intros A R R' H x y.\n  split.\n  inversion_clear 1. apply H;assumption.\n  assumption.\n  intro H';right;assumption.\nQed.\n\n\nSection star.\nUnset Implicit Arguments.\nVariable A:Type.\nVariable R : A -> A -> Prop.\nInductive star (x:A) : A -> Prop := \n| star_refl : star x x\n| star_step : forall y, star x y -> forall z, R y z -> star x z\n.\n\n\nLemma star_trans: forall x y z, star x y -> star y z -> star x z.\nProof. \nintros x y z H H1;revert x H; \ninduction H1.\n\ntauto.\nintros.\neconstructor 2 with y0;auto.\nQed.\n\nLemma star_R : forall x y, R x y -> star x y.\nProof.\nintros x y H;constructor 2 with x;[constructor|assumption].\nQed.\n\nLemma star_ind2 : forall  x (P:A -> Prop),\n  (P x) -> \n  (forall y, P y -> forall z, R y z -> P z) ->\n  forall a, star x a -> P a.\nProof.\n  intros x P H H0 a H1.\n  induction H1.\n  exact H.\n  apply H0 with (y:=y);assumption.\nQed.\n\nEnd star.\n\nLemma star_equiv :  forall A (R1 R2: A -> A -> Prop), (forall l r, R1 r l <-> R2 r l) -> \n  forall l r, star _ R1 r l <-> star _ R2 r l.\nProof.\n  intros A R1 R2 H l r.\n  split;induction 1;try constructor.\n  constructor 2 with y;auto.\n  rewrite H in H1;assumption.\n  constructor 2 with y;auto.\n  rewrite H;assumption.\nQed.\n\nSet Implicit Arguments.\n\nInductive product_o A B (R1 : relation A) (R2 : relation B) : relation (A*B)%type :=\n\t| CaseA : forall a a' b, R1 a a' -> product_o R1 R2 (a,b) (a',b)\n\t| CaseB : forall a b b', R2 b b' -> product_o R1 R2 (a,b) (a,b').\n\nLemma acc_and :\n   forall A B (R1 : relation A) (R2 : relation B),\n   forall a b, Acc R1 a -> Acc R2 b -> Acc (product_o R1 R2) (a,b). \nProof. \nintros A B R1 R2 a b Acc_a; generalize b; clear b;\ninduction Acc_a as [a Acc_a IHa].\nintros b Acc_b; generalize a Acc_a IHa; clear a Acc_a IHa;\ninduction Acc_b as [b Acc_b IHb]; intros a Acc_a IHa;\napply Acc_intro; intros [a' b'] H; inversion H; clear H; subst.\napply IHa; trivial.\napply Acc_intro; trivial.\napply IHb; trivial.\nDefined.\n\nDefinition nf A (R : relation A) t := forall s, R s t -> False.\n\nLemma acc_nf : forall A (R : relation A) FB, (forall t s, In s (FB t) <-> R s t) ->\n                          forall t, Acc R t -> { s : A | nf R s /\\ (s = t \\/ trans_clos R s t)}.\nProof.\nintros A R FB red_dec t Acc_t; induction Acc_t as [t Acc_t IH].\ncase_eq (FB t).\nintro H; exists t; split.\nintros s H'; rewrite <- red_dec in H';  rewrite H in H'; trivial.\nleft; trivial.\nintros a l H; destruct (IH a) as [a' [nf_a'  H']].\nrewrite <- red_dec; rewrite H; left; trivial.\nexists a'; split; trivial.\ndestruct H' as [a'_eq_a | H'].\nsubst; right; apply t_step; rewrite <- red_dec; rewrite H; left; trivial.\nright; apply trans_clos_is_trans with a; trivial.\napply t_step; rewrite <- red_dec; rewrite H; left; trivial.\nDefined.\n\nLemma dec_nf : forall A (R : relation A) FB, (forall t s, In s (FB t) <-> R s t) ->\n                          forall t, {nf R t}+{~nf R t}.\nProof.\nintros A R FB red_dec t.\ncase_eq (FB t).\nintro H; left; unfold nf; intros s H'; rewrite <- red_dec in H'; rewrite H in H'; contradiction.\nintros a l H.\nright; intro H'; apply H' with a.\nrewrite <- red_dec; rewrite H; left; trivial.\nDefined.\n\nLemma cycle_not_acc : forall A (R : relation A) (a : A), R a a -> ~Acc R a.\nProof.\nintros A R a H Acc_a; generalize H; clear H; \ninduction Acc_a as [a Acc_a IH].\nintro H; apply (IH a); trivial.\nQed.\n\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Coccinelle/basis/closure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025423, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6831572291687049}}
{"text": "\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Sets.Ensembles.\nRequire Import Coq.Logic.Classical_Prop.\n\nRequire Import Category.\n\n\nDefinition set_hom {U : Type} (X Y : Ensemble U) : Type :=\n    {f : U -> U | forall x : U, In U X x -> In U Y (f x)}.\n\nDefinition set_hom_fn {U : Type} {X Y : Ensemble U} (hom : set_hom X Y) : U -> U :=\n    match hom with exist f _ => f end.\n\nTheorem set_hom_eq {U : Type} {X Y : Ensemble U} (f g : set_hom X Y) : set_hom_fn f = set_hom_fn g -> f = g.\n    destruct f as [f pF]; destruct g as [g pG].\n    simpl.\n    intro H.\n    subst f.\n    assert (pF = pG) by (apply proof_irrelevance).\n    rewrite H.\n    reflexivity.\nQed.\n\nDefinition id_set {U : Type} (X : Ensemble U) : set_hom X X.\n    refine (exist _ (fun u => u) _).\n    trivial.\nDefined.\n\nDefinition comp_set\n        {U : Type} {X Y Z: Ensemble U}\n        (f : set_hom Y Z) (g : set_hom X Y)\n            : set_hom X Z.\n    refine (match f with\n        | exist f' pf =>\n            match g with\n                | exist g' pg =>\n                    exist _ (fun (x : U) => f' (g' x)) _\n                end\n       end).\n    unfold In in *.\n    intuition.\nDefined.\n\nInstance SetIsCat (U : Type) : Category id_set (@comp_set U).\n    Hint Unfold comp_set set_hom_fn id_set.\n    split; intros; apply set_hom_eq;\n        try (\n            (*left/right identity*)\n            destruct f;\n            reflexivity\n        ).\n        (*composition*)\n        destruct x.\n        destruct y.\n        destruct z.\n        reflexivity.\nQed.\n\nDefinition SetCat (U : Type) : Cat :=\n    cons_cat (Ensemble U) set_hom id_set (@comp_set U) (SetIsCat U).", "meta": {"author": "kavigupta", "repo": "ct4s-examples", "sha": "ad032b754b9c090caa5144018e5633dfc67f6e0e", "save_path": "github-repos/coq/kavigupta-ct4s-examples", "path": "github-repos/coq/kavigupta-ct4s-examples/ct4s-examples-ad032b754b9c090caa5144018e5633dfc67f6e0e/src/Cat/SetCategory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025423, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6831572243533119}}
{"text": "Require Import XR_Rabs.\nRequire Import XR_Rabs_right.\nRequire Import XR_Rabs_R0.\nRequire Import XR_Rabs_Ropp.\nRequire Import XR_IZR.\nRequire Import XR_pos_INR.\n\nLocal Open Scope R_scope.\n\nLemma Rabs_Zabs : forall z:Z, Rabs (IZR z) = IZR (Z.abs z).\nProof.\n  intros z.\n  destruct z as [  | z | z ].\n  {\n    simpl.\n    rewrite Rabs_R0.\n    reflexivity.\n  }\n  {\n    simpl.\n    rewrite Rabs_right.\n    { reflexivity. }\n    { apply pos_INR. }\n  }\n  {\n    simpl.\n    rewrite Rabs_Ropp.\n    rewrite Rabs_right.\n    { reflexivity. }\n    { apply pos_INR. }\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_Rabs_Zabs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.68315722221126}}
{"text": "Require Export D.\n\n\n\n(** **** Exercise: 2 stars, optional (t_update_shadow)  *)\n(** If we update a map [m] at a key [x] with a value [v1] and then\n    update again with the same key [x] and another value [v2], the\n    resulting map behaves the same (gives the same result when applied\n    to any key) as the simpler map obtained by performing just\n    the second [update] on [m]: *)\n\nLemma t_update_shadow : forall A (m: total_map A) v1 v2 x,\n    t_update (t_update m x v1) x v2\n  = t_update m x v2.\nProof.\n  intros. unfold t_update. apply functional_extensionality.\n  intros. destruct (beq_id x x0).\n  - reflexivity.\n  - reflexivity.\nQed.", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/07/P01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.6831501416630803}}
{"text": "Require Import HoTT.\nLocal Open Scope path_scope.\nLocal Open Scope equiv_scope.\n\n(* Exercise 3.1 *)\n\nTheorem ex3_1 : forall A B, Equiv A B -> IsHSet A -> IsHSet B.\n  intros A B eq h.\n  destruct eq as [f i].\n\n  (* There is a very important fact to remember about ap and equivalences! You\n     will have a hard time solving this question without remembering it. *)\n  SearchAbout ap IsEquiv.\n\n  (* Annoyingly enough, this seems to be the idiomatic way to construct\n     an IsHSet. Just cargo-cult it. *)\n  intros x y; apply hprop_allpath; intros p q.\n\n  (* Intuitively, the proof uses the equivalence to ferry an appropriate equality\n     from the known set to the unknown set.  Of course, the details are a little touchy. *)\n\n  assert (ap f^-1 p = ap f^-1 q) as H by (apply h).\n  exact ((ap (ap f^-1))^-1 H).\nQed.\n\n(* A generalized version of this statement is proved in the library. *)\nTheorem ex3_1_library : forall A B, Equiv A B -> IsHSet A -> IsHSet B.\n  intros A B e h.\n  exact (trunc_equiv (equiv_fun _ _ e)).\nQed.\n\n(* Here is a different proof that utilizes univalence.  Because it requires\n   an axiom, it might be considered an inferior proof, but it is quite simple! *)\nTheorem ex3_1_ua `{Univalence} : forall A B, Equiv A B -> IsHSet A -> IsHSet B.\n  intros A B eq h.\n  exact (transport IsHSet (equiv_path_universe _ _ eq) h).\nQed.\n\n(* Exercise 3.2 *)\n\nTheorem ex3_2 : forall A B, IsHSet A -> IsHSet B -> IsHSet (A + B).\n  intros A B g h.\n  (* Intuitively, this proof is all about the codes. Analyzing the path space\n     over A + B otherwise is difficult.  In Chapter 2, we re-did the codes;\n     here, we'll use a code provided by the standard library. *)\n  SearchAbout sum paths.\n\n  intros x y; apply hprop_allpath; intros p q.\n\n  assert ((path_sum x y)^-1 p = (path_sum x y)^-1 q) as H.\n    pose proof ((path_sum x y)^-1 p). (* just a little trick to make contradiction work *)\n    destruct x; destruct y; try apply g; try apply h; try contradiction.\n\n  exact ((ap (path_sum x y)^-1)^-1 H).\nQed.\n\n(* The HoTT library has rather sophisticated type-class machinery for\n   generating proofs of set-likeness, and this can be used to automatically\n   dispatch the appropriate already existing lemma. *)\nTheorem ex3_2_library : forall A B, IsHSet A -> IsHSet B -> IsHSet (A + B).\n  typeclasses eauto.\nQed.\n\n(* Exercise 3.3 *)\n\n(* Warmup: *)\nExample thm3_1_5 : forall A B, IsHSet A -> IsHSet B -> IsHSet (A * B).\n  intros A B h g.\n  intros x y; apply hprop_allpath; intros p q.\n  assert (path_prod _ _ (ap fst p) (ap snd p) = p) as a by apply eta_path_prod.\n  assert (path_prod _ _ (ap fst q) (ap snd q) = q) as b by apply eta_path_prod.\n  assert (path_prod _ _ (ap fst p) (ap snd p) = path_prod _ _ (ap fst q) (ap snd q)) as c.\n    f_ap. apply h. apply g.\n  exact (a^ @ c @ b).\nQed.\n\nTheorem ex3_3 : forall A B, IsHSet A -> (forall x : A, IsHSet (B x)) -> IsHSet (sigT B).\n  intros A B h g.\n  intros x y; apply hprop_allpath; intros p q.\n  assert (path_sigma_uncurried _ _ _ (p..1; p..2) = p) as a by apply eta_path_sigma_uncurried.\n  assert (path_sigma_uncurried _ _ _ (q..1; q..2) = q) as b by apply eta_path_sigma_uncurried.\n  assert (p..1 = q..1) as sa by apply h.\n  assert (path_sigma_uncurried _ _ _ (p..1; p..2) = path_sigma_uncurried _ _ _ (q..1; q..2)) as c.\n    f_ap. (* f_ap seems to not know to do path_sigma_uncurried *)\n    apply path_sigma_uncurried. exists sa. apply g. (* NB: we don't have to worry about transport! Try simpl *)\n  exact (a^ @ c @ b).\nQed.\n\n(* XXX Despite its simplicity, I think this exercise is quite hard (much like exercise 2.7),\nbecause the added dependence makes many plausible approaches not work.  Here are some\napproaches that no longer work:\n\n * 'p..2 = q..2' does not typecheck (the direct approach). More generally, things\n   which you would like to have the same type don't, and inserting transports yourself\n   don't seem to help things (similarly, consider eta_path_sigma)\n * You cannot 'destruct' the term 'sa : p..1 = q..2' on account of dependence (the \"oh\n   let's try path induction willy-nilly)\n * Using the curried path_sigma function means you cannot apply f_ap to take\n   advantage of the structure of the path space revealed by path_sigma (the \"surely\n   the shorter name is better crowd\")\n\nThe key insight of this problem is that the path space of a sigma type... is a sigma\ntype itself, which is witnessed by the equivalence path_sigma_uncurried (note the\nuncurried: the sigma does NOT show up when things are curried; it's an implicit phenomenon\ndue to dependence in that case). So if we need to analyze a complicated path like\np = q, we turn it into a path of sigma types, and then use standard techniques (path_sigma\n/again/) to finally crack it.\n\nI suspect the lessons learned here also may provide some clues for how to improve f_ap\nfurther, in the face of dependence and multiple arguments (model them as sigmas!)\n\n*)\n\nTheorem ex3_3_library : forall A B, IsHSet A -> (forall x : A, IsHSet (B x)) -> IsHSet (sigT B).\n  typeclasses eauto.\nQed.\n\n(* Exercise 3.4 *)\nLemma ex3_4_right `{Funext} : forall A, IsHProp A -> Contr (A -> A).\n  intros A h. refine (BuildContr _ (fun x => x) _).\n  intro f. apply path_forall. intro x. apply h. (* NB: tc resolution seems to defeat auto *)\nQed.\n\nLemma ex3_4_left : forall A, Contr (A -> A) -> IsHProp A.\n  intros A [center h]. apply hprop_allpath; intros x y.\n  SearchAbout pointwise_paths.\n  pose proof (ap10 (h (fun _ => x)) x) ^ as p.\n  pose proof (ap10 (h (fun _ => y)) x) as q.\n  transitivity (center x); auto.\nQed.\n\nHint Resolve ex3_4_left ex3_4_right.\nTheorem ex3_4 `{Funext} : forall A, IsHProp A <-> Contr (A -> A).\n  constructor; auto.\nQed.\n\n(* Exercise 3.5 *)\n\nDefinition ex3_5_f A (h : IsHProp A) := fun x => BuildContr _ x (fun y => allpath_hprop x y).\nDefinition ex3_5_inverse A (g : A -> Contr A) := hprop_allpath A (fun x y => let H := g x in path_contr x y).\nDefinition ex3_5_inverse' A (g : A -> Contr A) := fun x y => let H := g x in contr_paths_contr x y.\n\nTheorem ex3_5 `{Funext} : forall A, Equiv (IsHProp A) (A -> Contr A).\n  intro A.\n  apply (equiv_adjointify (ex3_5_f A) (ex3_5_inverse A)); unfold Sect, ex3_5_f, ex3_5_inverse.\n  intro f. apply path_forall. intro x. assert (IsHProp (Contr_internal A)) as X by typeclasses eauto. apply X.\n  intro h. assert (IsHProp (IsHProp A)) as X by typeclasses eauto. apply X.\nQed.\n\nTheorem ex3_5_library `{Funext} : forall A, Equiv (IsHProp A) (A -> Contr A).\n  intros; apply equiv_hprop_inhabited_contr.\nQed.\n\n(* Exercise 3.6 *)\n\nTheorem ex3_6 `{Funext} : forall A, IsHProp A -> IsHProp (A + ~A).\n  intros A h.\n  apply hprop_allpath; intros x y.\n  destruct x; destruct y; try contradiction; f_ap.\n    apply h.\n    apply path_forall; intro. contradiction. (* honestly, this should be a lemma *)\nQed.\n(* NB: you can't do it without extensionality! *)\n\n(* Exercise 3.7 *)\n\nTheorem ex3_7 : forall A B, IsHProp A -> IsHProp B -> ~ (A * B) -> IsHProp (A + B).\n  intros A B h g e.\n  apply hprop_allpath; intros x y.\n  destruct x; destruct y; try contradiction (e (a,b)); f_ap.\n    apply h. apply g.\nQed.\n\n(* Exercise 3.8 *)\n\nRequire Import Truncations.\nCheck Truncation.\nNotation Squash A := (Truncation minus_one A).\n\nDefinition qinv {A B} (f : A -> B) := {g : B -> A & ((f o g = idmap) * (g o f = idmap))}.\n\nDefinition squash_qinv `{Funext} {A B} (f : A -> B) : Squash (qinv f) -> IsEquiv f.\n  assert (IsHProp (IsEquiv f)) as t by typeclasses eauto.\n  intro sq.\n(*  Set Typeclasses Debug. *)\n(*  refine (@Truncation_rect_nondep _ _ (IsEquiv f) _ (fun q => _) sq). *)\n(*  infinite loops?\nDebug: 1.1: exact t on (IsHProp (IsEquiv f))\nDebug: 1.1: eapply cancelL_isequiv on (IsEquiv f)\nDebug: 1.1.1.1: apply isequiv_path on (IsEquiv ?1060)\nDebug: 1.1.2.1: apply @isequiv_compose on\n(IsEquiv (transport idmap ?1065 o f))\nDebug: 1.1.2.1.1.1: eapply cancelL_isequiv on (IsEquiv f)\nDebug: 1.1.2.1.1.1.1.1: apply isequiv_path on (IsEquiv ?1107)\nDebug: 1.1.2.1.1.1.2.1: apply @isequiv_compose on\n(IsEquiv (transport idmap ?1112 o f))\n*)\nAbort.\n\n(* Exercise 3.9 *)\n\n(* oops, HoTT library doesn't seem to have LEM, see https://github.com/HoTT/HoTT/issues/299 *)\nClass LEM :=\n  { lem :> forall (A : Type), IsHProp A -> A + ~A }.\n\n(* computation rules *)\nLemma lem_unit `{LEM} : lem Unit _ = inl tt.\n  destruct (lem Unit _). destruct u. auto.\n  contradiction (n tt).\nQed.\nLemma lem_empty `{LEM} `{Funext} : lem Empty _ = inr idmap.\n  destruct (lem Empty _). contradiction. f_ap. apply ap10^-1. intro x. contradiction.\nQed.\n\nDefinition ex3_9_f `{LEM} : sigT IsHProp -> Bool.\n  intro x.\n  destruct (lem x.1 x.2).\n  exact true.\n  exact false.\nDefined.\n\nDefinition ex3_9_inverse : Bool -> sigT IsHProp.\n  intro b.\n  destruct b.\n  exists Unit; typeclasses eauto.\n  exists Empty; typeclasses eauto.\nDefined.\n\nTheorem ex3_9 `{LEM} `{Univalence} : sigT IsHProp <~> Bool.\n  apply (equiv_adjointify ex3_9_f ex3_9_inverse); unfold Sect, ex3_9_f, ex3_9_inverse.\n    destruct x; simpl.\n      (* meh, too difficult to do the rewrite *)\n      destruct (lem Unit _); auto. contradiction (n tt).\n      destruct (lem Empty _); auto. contradiction.\n    destruct x as [A h]; simpl. destruct (lem A h).\n      pose proof (contr_inhabited_hprop A a).\n      pose proof equiv_contr_unit as g'.\n      pose proof ((path_universe g') ^) as g.\n      try apply (path_sigma IsHProp (Unit; trunc_succ) (A; h) g).\n      (* universe inconsistency *)\nAbort.\n\n(* Exercise 3.10 *)\n\n(* Exercise 3.11 *)\n\nDefinition thm3_2_2_e : Bool <~> Bool.\n  apply (equiv_adjointify negb negb); unfold Sect; destruct x; trivial.\nDefined.\n\nTheorem thm3_2_2 `{Univalence} `{Funext} : ~ (forall A, ~~A -> A).\n  intro f.\n  (* NB: happly is called apD10 *)\n  (* to work around universe inconsistency, you cannot path_universe in a Definition *)\n  pose proof (fun u => apD10 (apD f (path_universe thm3_2_2_e)) u) as h.\n  (* NB: lemma 2.9.4 is transport_arrow *)\n  pose proof (fun u => @transport_arrow _ (fun A => ~~A) (fun A => A) _ _ (path_universe thm3_2_2_e) (f Bool) u) as g.\n  assert (forall (u v : ~~Bool), u = v) as eq.\n    intros; apply path_forall; intro x; contradiction (u x).\n  assert (forall (u : ~~Bool), transport (fun A => ~~A) (path_universe thm3_2_2_e)^ u = u) as i.\n    intros; apply eq.\n  pose proof (fun u => (h u)^ @ g u @ ap (fun z => transport idmap (path_universe thm3_2_2_e) (f Bool z)) (i u)) as j.\n  (* NB: 2.10 discussion is transport_path_universe *)\n  pose proof (fun u => j u @ transport_path_universe thm3_2_2_e (f Bool u)) as k.\n  assert (forall x : Bool, ~(thm3_2_2_e x = x)) as X.\n    destruct x; unfold thm3_2_2_e; simpl. apply false_ne_true. apply true_ne_false.\n  apply (X (f Bool (fun k => k true)) (k (fun k => k true))^).\nQed.\n\nCorollary thm3_2_7 `{Univalence} `{Funext} : ~ (forall A, A + ~A).\n  intro g.\n  refine (thm3_2_2 (fun A => _)).\n  intro u.\n  destruct (g A). trivial. contradiction (u n).\nQed.\n\n(* This is a copy-paste of Theorem 3.2.2, but with ~~ replaced with Squash and relevant proof terms adjusted *)\nTheorem ex3_11 `{Univalence} `{Funext} : ~ (forall A, Squash A -> A).\n  intro f.\n  pose proof (fun u => apD10 (apD f (path_universe thm3_2_2_e)) u) as h.\n  pose proof (fun u => @transport_arrow _ (fun A => Squash A) (fun A => A) _ _ (path_universe thm3_2_2_e) (f Bool) u) as g.\n  assert (forall (u v : Squash Bool), u = v) as eq.\n    intros. pose proof (istrunc_truncation minus_one Bool) as X. apply X.\n  assert (forall (u : Squash Bool), transport (fun A => Squash A) (path_universe thm3_2_2_e)^ u = u) as i.\n    intros; apply eq.\n  pose proof (fun u => (h u)^ @ g u @ ap (fun z => transport idmap (path_universe thm3_2_2_e) (f Bool z)) (i u)) as j.\n  pose proof (fun u => j u @ transport_path_universe thm3_2_2_e (f Bool u)) as k.\n  assert (forall x : Bool, ~(thm3_2_2_e x = x)) as X.\n    destruct x; unfold thm3_2_2_e; simpl. apply false_ne_true. apply true_ne_false.\n  apply (X (f Bool (truncation_incl true)) (k (truncation_incl true))^).\nQed.\n\n(* The result of this exercise is a generalization of Theorem 3.2.2, in\nthe following sense: *)\nTheorem thm3_2_2' `{Univalence} `{Funext} : ~ (forall A, ~~A -> A).\n  intro f.\n  refine (ex3_11 (fun A => _)). intro sa. apply f.\n  refine (Truncation_rect_nondep (fun a p => p a) sa).\nQed.\n(* NB: typeclasses automatically resolved the proof that ~~A is an HProp *)\n(* We will consider how to go the other direction in a later exercise. *)\n\n(* jgross suggests an alternate proof uses HITs (observing that the circle\n   is connected (squash) but not contractible (not squashed)). The basic idea\n   is the same: here, we use univalence to construct a nontrivial path space,\n   in the alternate proof, the circle provides the nontrivial path space. *)\n\n(* Exercise 3.12 *)\n\nTheorem ex3_12 `{LEM} : forall A, Squash (Squash A -> A).\n  intro.\n  apply truncation_incl. (* This can't be right. *)\nAbort.\n\n(* Exercise 3.13 *)\n\nTheorem ex3_13 : (forall A, A + ~A) -> (forall X Y, IsHSet X -> (forall (x : X), IsHSet (Y x)) -> (forall x, Squash (Y x)) -> Squash (forall x, Y x)).\n  intros lemi X Y xset yset h.\n  destruct (lemi X).\n  refine (Truncation_rect_nondep (fun syx => truncation_incl (fun x' => _)) (h x)).\nAbort.", "meta": {"author": "ezyang", "repo": "HoTT-coqex", "sha": "54e5f14408ff330e219821b183cd9edb3cdbfccb", "save_path": "github-repos/coq/ezyang-HoTT-coqex", "path": "github-repos/coq/ezyang-HoTT-coqex/HoTT-coqex-54e5f14408ff330e219821b183cd9edb3cdbfccb/ch3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6831501224841384}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Import Coq.omega.Omega.\nRequire Import Maps.\nRequire Import Imp.\n\nLtac inv H := inversion H; subst; clear H.\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  induction E1; intros st2 E2; inv E2.\n  - (* E_Skip *) reflexivity.\n  - (* E_Ass *) reflexivity.\n  - (* E_Seq *)\n    assert (st' = st'0) as EQ1.\n    { (* Proof of assertion *) apply IHE1_1; apply H1. }\n    subst st'0.\n    apply IHE1_2. assumption.\n  (* E_IfTrue *)\n  - (* b evaluates to true *)\n    apply IHE1. assumption.\n  - (* b evaluates to false (contradiction) *)\n    rewrite H in H5. inversion H5.\n  (* E_IfFalse *)\n  - (* b evaluates to true (contradiction) *)\n    rewrite H in H5. inversion H5.\n  - (* b evaluates to false *)\n    apply IHE1. assumption.\n  (* E_WhileFalse *)\n  - (* b evaluates to false *) reflexivity.\n  - (* b evaluates to true (contradiction) *) rewrite H in H2. inversion H2.\n  (* E_WhileTrue *)\n  - (* b evaluates to false (contradiction) *)\n    rewrite H in H4. inversion H4.\n  - (* b evaluates to true *)\n    assert (st' = st'0).\n    { (* Proof of assertion *) apply IHE1_1. assumption. }\n    subst st'0. apply IHE1_2. assumption. Qed.\n\n\n(* The auto tactic *)\n\nExample auto_example_1 : forall (P Q R: Prop),\n  (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n  intros P Q R H1 H2 H3.\n  apply H2. apply H1. assumption.\nQed.\n\nExample auto_example_1' : forall (P Q R: Prop),\n  (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n  auto.\nQed.\n\nExample auto_example_2: forall P Q R S T U : Prop,\n  (P -> Q) ->\n  (P -> R) ->\n  (T -> R) ->\n  (S -> T -> U) ->\n  ((P -> Q) -> (P -> S)) ->\n  T ->\n  P ->\n  U.\nProof.\n  auto.\nQed.\n\nExample auto_example_3 : forall (P Q R S T U: Prop),\n  (P -> Q) ->\n  (Q -> R) ->\n  (R -> S) ->\n  (S -> T) ->\n  (T -> U) ->\n  P ->\n  U.\nProof.\n  (* When it cannot solve the goal, auto does nothing *)\n  auto.\n  (* Optional argument says how deep to search (default is 5) *)\n  auto 6.\nQed.\n\nExample auto_example_4 : forall P Q R : Prop,\n  Q ->\n  (Q -> R) ->\n  P \\/ (Q /\\ R).\nProof. auto. Qed.\n\nLemma le_antisym : forall n m: nat, (n <= m /\\ m <= n) -> (n = m).\nProof. intros. omega. Qed.\n\nExample auto_example_6 : forall n m p : nat,\n  (n <= p -> (n <= m /\\ m <= n)) ->\n  n <= p ->\n  n = m.\nProof.\n  intros.\n  auto using le_antisym.\nQed.\n\nHint Resolve le_antisym.\n\nExample auto_example_6' : forall n m p : nat,\n  (n <= p -> (n <= m /\\ m <= n)) ->\n  n <= p ->\n  n = m.\nProof.\n  intros.\n  auto.\nQed.\n\nDefinition is_fortytwo x := (x = 42).\n\nExample auto_example_7: forall x,\n  (x <= 42 /\\ 42 <= x) -> is_fortytwo x.\nProof.\n  auto. (* does nothing *)\nAbort.\n\nHint Unfold is_fortytwo.\n\nExample auto_example_7': forall x,\n  (x <= 42 /\\ 42 <= x) -> is_fortytwo x.\nProof.\n  auto.\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    induction E1; intros st2 E2; inv E2; auto.\n  - (* E_Seq *)\n    assert (st' = st'0) as EQ1 by auto.\n    subst st'0. auto.\n  - (* E_IfTrue *) \n    + (* b evaluates to false (contradiction) *) rewrite H in H5. inversion H5.\n  - (* E_IfFalse *)\n    + (* b evaluates to true (contradiction) *) rewrite H in H5. inversion H5.\n  - (* E_WhileFalse *)\n    + (* b evaluates to true (contradiction) *) rewrite H in H2; inversion H2.\n  - (* E_WhileTrue *)\n    + (* b evaluates to false (contradiction) *) rewrite H in H4; inversion H4.\n  - (* E_WhileTrue *)\n    + (* b evaluates to true *) \n      assert (st' = st'0) as EQ1 by auto.\n      subst st'. auto.\nQed.\n\nTheorem ceval_deterministic'_alt: forall c st st1 st2,\n  c / st \\\\ st1 ->\n  c / st \\\\ st2 ->\n  st1 = st2.\nProof with auto.\n  intros c st st1 st2 E1 E2.\n  generalize dependent st2;\n  induction E1; \n      intros; inv E2...\n  - (* E_Seq *)\n    assert (st' = st'0) as EQ1...\n    subst st'0...\n  - (* E_IfTrue *) \n    + (* b evaluates to false (contradiction) *) rewrite H in H5. inversion H5.\n  - (* E_IfFalse *)\n    + (* b evaluates to true (contradiction) *) rewrite H in H5. inversion H5.\n  - (* E_WhileFalse *)\n    + (* b evaluates to true (contradiction) *) rewrite H in H2; inversion H2.\n  - (* E_WhileTrue *)\n    + (* b evaluates to false (contradiction) *) rewrite H in H4; inversion H4.\n  - (* E_WhileTrue *)\n    + (* b evaluates to true *) \n      assert (st' = st'0) as EQ1...\n      subst st'...\nQed.\n\n\nLtac rwinv H1 H2 := rewrite H1 in H2; inv H2.\n\nTheorem ceval_deterministic'': forall c st st1 st2,\n  c / st \\\\ st1 ->\n  c / st \\\\ st2 ->\n  st1 = st2.\nProof with auto.\n  intros c st st1 st2 E1 E2.\n  generalize dependent st2;\n  induction E1; intros st2 E2; inv E2...\n  - (* E_Seq *)\n    assert (st' = st'0) as EQ1...\n    subst st'0...\n  - (* E_IfTrue *) \n    + (* b evaluates to false (contradiction) *) rwinv H H5.\n  - (* E_IfFalse *)\n    + (* b evaluates to true (contradiction) *) rwinv H H5.\n  - (* E_WhileFalse *)\n    + (* b evaluates to true (contradiction) *) rwinv H H2.\n  - (* E_WhileTrue *)\n    + (* b evaluates to false (contradiction) *) rwinv H H4.\n  - (* E_WhileTrue *)\n    + (* b evaluates to true *) \n      assert (st' = st'0) as EQ1...\n      subst st'...\nQed.\n\nLtac find_rwinv :=\n  match goal with\n    H1 : ?E = true,\n    H2 : ?E = false\n    |- _ => rwinv H1 H2\n  end.\n\nTheorem ceval_deterministic''': forall c st st1 st2,\n  c / st \\\\ st1 ->\n  c / st \\\\ st2 ->\n  st1 = st2.\nProof with auto.\n  intros c st st1 st2 E1 E2;\n  generalize dependent st2;\n  induction E1; intros st2 E2; inv E2; try find_rwinv; auto.\n  - (* E_Seq *)\n    assert (st' = st'0) as EQ1...\n    subst st'0...\n  - (* E_WhileTrue *)\n    + (* b evaluates to true *)\n      assert (st' = st'0) as EQ1...\n      subst st'0...\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  induction E1; intros st2 E2; inv E2; try find_rwinv; auto.\n  - (* E_Seq *)\n    rewrite (IHE1_1 st'0 H1) in *. auto.\n  - (* E_WhileTrue *)\n    + (* b evaluates to true *)\n      rewrite (IHE1_1 st'0 H3) in *. auto.\nQed.\n\nLtac find_eqn :=\n  match goal with\n    H1: forall x, ?P x -> ?L = ?R,\n    H2: ?P ?X\n    |- _ => rewrite (H1 X H2) in *\n  end.\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  induction E1; intros st2 E2; inv E2; try find_rwinv;\n    repeat find_eqn; auto.\nQed.\n\nModule Repeat.\n\nInductive com : Type :=\n  | CSkip : com\n  | CAsgn : string -> aexp -> com\n  | CSeq : com -> com -> com\n  | CIf : bexp -> com -> com -> com\n  | CWhile : bexp -> com -> com\n  | CRepeat : com -> bexp -> com.\n\nNotation \"'SKIP'\" :=\n  CSkip.\nNotation \"c1 ; c2\" :=\n  (CSeq c1 c2) (at level 80, right associativity).\nNotation \"X '::=' a\" :=\n  (CAsgn X a) (at level 60).\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).\nNotation \"'REPEAT' e1 'UNTIL' b2 'END'\" :=\n  (CRepeat e1 b2) (at level 80, right associativity).\n\nInductive ceval : state -> com -> state -> Prop :=\n  | E_Skip : forall st,\n      ceval st SKIP st\n  | E_Ass : forall st a1 n X,\n      aeval st a1 = n ->\n      ceval st (X ::= a1) (t_update st X n)\n  | E_Seq : forall st st' st'' c1 c2,\n      ceval st c1 st' ->\n      ceval st' c2 st'' ->\n      ceval st (c1 ; c2) st''\n  | E_IfTrue : forall b c1 c2 st st',\n      beval st b = true ->\n      ceval st c1 st' ->\n      ceval st (IFB b THEN c1 ELSE c2 FI) st'\n  | E_IfFalse : forall b c1 c2 st st',\n      beval st b = false ->\n      ceval st c2 st' ->\n      ceval st (IFB b THEN c1 ELSE c2 FI) st'\n  | E_WhileFalse : forall b c st,\n      beval st b = false ->\n      ceval st (WHILE b DO c END) st\n  | E_WhileTrue : forall b c st st' st'',\n      beval st b = true ->\n      ceval st c st' ->\n      ceval st' (WHILE b DO c END) st'' ->\n      ceval st (WHILE b DO c END) st''\n  | E_RepeatEnd : forall b c st st',\n      ceval st c st' ->\n      beval st b = true ->\n      ceval st (CRepeat c b) st'\n  | E_RepeatLoop : forall b c st st' st'',\n      ceval st c st' ->\n      beval st b = false ->\n      ceval st' (CRepeat c b) st'' ->\n      ceval st (CRepeat c b) st''.\n\nNotation \"c1 '|' st '\\\\' st'\" := (ceval st c1 st')\n                                 (at level 40, st at level 39).\n\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  induction E1; intros st2 E2; inv E2; try find_rwinv;\n  repeat find_eqn; auto.\nQed.\n\nEnd Repeat.\n\nExample ceval_example1:\n  (X ::= 2;;\n   IFB X <= 1\n    THEN Y ::= 3\n    ELSE Z ::= 4\n   FI)\n  / { --> 0 }\n  \\\\ { X --> 2 ; Z --> 4 }.\nProof.\n  (* We supply the intermediate state st'... *)\n  apply E_Seq with { X --> 2 }.\n  - apply E_Ass. reflexivity.\n  - apply E_IfFalse. reflexivity. apply E_Ass. reflexivity.\nQed.\n\n\nExample ceval'_example1:\n  (X ::= 2;;\n   IFB X <= 1\n    THEN Y ::= 3\n    ELSE Z ::= 4\n   FI)\n  / { --> 0 }\n  \\\\ { X --> 2 ; Z --> 4 }.\nProof.\n  eapply E_Seq. (* 1 *)\n  - apply E_Ass. (* 2 *)\n    reflexivity. (* 3 *)\n  - (* 4 *) apply E_IfFalse. reflexivity. apply E_Ass. reflexivity.\nQed.\n\nHint Constructors ceval.\nHint Transparent state.\nHint Transparent total_map.\n\nDefinition st12 := { X --> 1 ; Y --> 2 }.\nDefinition st21 := { X --> 2 ; Y --> 1 }.\n\nExample eauto_example : exists s',\n  (IFB X <= Y\n     THEN Z ::= Y - X\n     ELSE Y ::= X + Z\n   FI) / st21 \\\\ s'.\nProof. eauto. Qed.\n\n\n\n\n\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/Auto_psp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478254, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.6831501088100668}}
{"text": "(** * Counting ones in [positive] and [N] *)\n\nRequire Import Coq.PArith.PArith.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Omega.\n\nRequire Import Data.Bits.\n\nLemma Pos_popcount_pow2:\n  forall n, Pos_popcount (Pos.pow 2 n) = 1%positive.\nProof.\n  apply Pos.peano_ind; intros.\n  * reflexivity.\n  * rewrite Pos.pow_succ_r.\n    apply H.\nQed.\n\nLemma Pos_popcount_1_Is_power (p : positive) :\n  Pos_popcount p = 1%positive -> Is_power p.\nProof.\n  induction p as [p IH | p IH |]; simpl; auto.\n  specialize (Pos.succ_not_1 (Pos_popcount p)); contradiction.\nQed.\n\n(** And now for [N] *)\n\nLemma N_popcount_double:\n  forall n, N_popcount (N.double n) = N_popcount n.\nProof.\n  intros.\n  destruct n.\n  * reflexivity.\n  * reflexivity.\nQed.\n\nLemma N_popcount_Ndouble:\n  forall n, N_popcount (Pos.Ndouble n) = N_popcount n.\nProof.\n  intros.\n  destruct n.\n  * reflexivity.\n  * reflexivity.\nQed.\n\nLemma N_popcount_Nsucc_double:\n  forall n, N_popcount (Pos.Nsucc_double n) = N.succ (N_popcount n).\nProof.\n  intros.\n  destruct n.\n  * reflexivity.\n  * reflexivity.\nQed.\n\n\nLemma N_popcount_pow2:\n  forall n, N_popcount (N.pow 2 n) = 1%N.\nProof.\n  apply N.peano_ind; intros.\n  * reflexivity.\n  * rewrite N.pow_succ_r by apply N.le_0_l.\n    rewrite <- N.double_spec.\n    rewrite N_popcount_double.\n    assumption.\nQed.\n\nLemma N_popcount_1_pow2 (n : N) :\n  N_popcount n = 1%N -> exists i : N, (2^i = n)%N.\nProof.\n  destruct n as [|p]; simpl; [discriminate | intros def_Npcp].\n  assert (Pos_popcount p = 1%positive) as def_pcp by (inversion def_Npcp; reflexivity).\n  apply Pos_popcount_1_Is_power, Is_power_correct in def_pcp.\n  destruct def_pcp as [y def_p]; rewrite def_p.\n  specialize (shift_nat_correct y 1); rewrite Z.mul_1_r, Zpower_nat_Z; intros def_power.\n  exists (N.of_nat y). \n  rewrite <-N2Z.inj_iff, N2Z.inj_pow; simpl.\n  rewrite def_power, nat_N_Z; reflexivity.\nQed.\n\nLemma N_double_succ:\n  forall n,\n  N.double (N.succ n) = N.succ (N.succ (N.double n)).\nProof.\n  destruct n.\n  * reflexivity.\n  * reflexivity.\nQed.\n\nLemma Pop_popcount_diff:\n  forall p1 p2,\n  (N.pos (Pos_popcount p1) + N.pos (Pos_popcount p2) =\n  N_popcount (Pos.ldiff p1 p2) + N_popcount (Pos.ldiff p2 p1) + N.double (N_popcount (Pos.land p2 p1)))%N.\nProof.\n  induction p1; intros; destruct p2.\n  all: try (\n    simpl;\n    try specialize (IHp1 p2);\n    rewrite ?N_popcount_Ndouble, ?N_popcount_Nsucc_double,\n            ?N_double_succ;\n    zify; omega\n  ).\n  * simpl.\n    destruct (Pos_popcount p2); simpl in *; try rewrite <- Pplus_one_succ_r; try reflexivity.\nQed.\n\n\nLemma N_popcount_diff:\n  forall n1 n2,\n  (N_popcount n1 + N_popcount n2 =\n  N_popcount (N.ldiff n1 n2) + N_popcount (N.ldiff n2 n1) + N.double (N_popcount (N.land n2 n1)))%N.\nProof.\n  intros. destruct n1, n2; try reflexivity.\n  apply Pop_popcount_diff.\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/base-thy/Data/Bits/Popcount.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6831076471069478}}
{"text": "Require Import Reals.\nRequire Import Lra.\nLocal Open Scope R_scope.\nRequire Import Vector.\nRequire Import utils.\n\n\nTheorem R_isring : ring_theory 0 1 Rplus Rmult Rminus Ropp eq.\nProof.\n  constructor.\n  (* addition *)\n  (* left identity *) apply Rplus_0_l.\n  (* commutativity *) apply Rplus_comm.\n  (* associativity *) intros; rewrite Rplus_assoc; easy.\n  (* multiplication *)\n  (* left identity *) apply Rmult_1_l.\n  (* commutativity *) apply Rmult_comm.\n  (* associativity *) intros; rewrite Rmult_assoc; easy.\n  (* distributivity *) apply Rmult_plus_distr_r.\n  (* sub = opp *) reflexivity.\n  (* additive inverse *) apply Rplus_opp_r.\nQed.\n\nInstance Rring : Ring R :=\n  {\n  r0 := 0;\n  r1 := 1;\n  radd := Rplus;\n  rmult := Rmult;\n  rainv := Ropp;\n  rminus := Rminus;\n  req := eq;\n  isring := R_isring;\n  }.\n\n\n\nTheorem R_isfield : field_theory R0 R1 Rplus Rmult Rminus Ropp Rdiv Rinv eq.\nProof.\n  constructor.\n  (* ring axioms *) apply R_isring.\n  (* 0 <> 1 *) apply R1_neq_R0.\n  (* div = inv *) reflexivity.\n  (* multiplicative inverse *) apply Rinv_l.\nQed.\n\nInstance Rfield : Field R :=\n  {\n  fdiv := Rdiv;\n  finv := Rinv;\n  isfield := R_isfield;\n  }.\n\nDefinition Rscalar_mult {A : Type} `{Field A} {n : nat}\n           (k : R) (xs : t R n) :=\n  map (fun x => rmult k x) xs.\n\nDefinition Raddition {A : Type} `{Field A} {n : nat}\n           (xs ys : t R n) :=\n  zipwith radd xs ys.\n\n\nTheorem Raddition_commu {n : nat}\n        (xs ys : t R n) : Raddition xs ys = Raddition ys xs.\nProof.\n  unfold Raddition; apply zipwith_commu.\n  intros a b; simpl; lra.\nQed.\n\nDefinition additive_inverse {A : Type} `{Field A} {n : nat} (x : t A n) : t A n :=\n  map rainv x.\n\n\nFixpoint Vzero {F : Type} `{Ring F} (n : nat) : t F n :=\n  match n with\n  | 0 => nil F\n  | S n' => cons F r0 n' (Vzero n')\n  end.\n\n\nTheorem R2_isvectorspace : vectorspace_theory Rscalar_mult Raddition (@Vzero R Rring 2).\nProof.\n  split; intros.\n  - apply Raddition_commu.\n  - split; intros.\nAdmitted.\n\n\nInstance R2 : VectorSpace R (t R 2) :=\n  {\n  vscalar_mult := Rscalar_mult;\n  vaddition := Raddition;\n  v0 := Vzero 2;\n  isvectorspace := R2_isvectorspace;\n  }.\n", "meta": {"author": "quinn-dougherty", "repo": "ladr", "sha": "a3137394831791ad29c5bbfe6241d1fb233d67cb", "save_path": "github-repos/coq/quinn-dougherty-ladr", "path": "github-repos/coq/quinn-dougherty-ladr/ladr-a3137394831791ad29c5bbfe6241d1fb233d67cb/src/instances/Rvec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.6831076445781954}}
{"text": "Require Export Coq.Sorting.Permutation. \nRequire Export Omega.   \nRequire Export List. \nExport ListNotations. \nRequire Export hetList. \nRequire Import ZArith.\nOpen Scope Z_scope.\n\n(*looks nicer in unicode*)\nDefinition int := Z. \n\nFixpoint sum (l : list int) : int := \n  match l with\n      |hd::tl => hd + sum tl\n      |List.nil => 0\n  end. \n\n(*split L l1 l2: L is composed of l1 and l2*)\nInductive split : list int -> list int -> list int -> Prop :=\n|splitNil : split nil nil nil\n|splitConsL : forall a x b1 b2 c,\n                split a (b1++b2) c ->\n                split (x::a) (b1++x::b2) c\n|splitConsR : forall a x b c1 c2,\n                split a b (c1++c2) ->\n                split (x::a) b (c1++x::c2). \n\nInductive partition (k:int) (l:list int) : Prop :=\n|partition_ : forall (l1 l2 : list int), \n                sum l = k * 2 -> split l l1 l2 ->\n                sum l1 = k -> sum l2 = k -> partition k l. \n\n(*triple of integers*)\nDefinition vote : Type := prod (prod int int) int. \n\nDefinition add_votes v1 v2 :=\n  match v1, v2 with\n      |(a,b,c), (d,e,f) => (a+d,b+e,c+f)\n  end. \n\nFixpoint score_votes vs :=\n  match vs with\n      |v::vs => add_votes v (score_votes vs)\n      |nil => (0,0,0)\n  end. \n\n(*The convention here is that the first position corresponds to the \n**candidate the manipulators want to win << p, a, b >> *)\nInductive p_wins : vote -> Prop :=\n|p_wins_ : forall p a b, p > a -> p > b -> p_wins(p, a, b). \n\n(*make a vote of weight 2k*)\nInductive mkVote k : vote -> Prop :=\n|veto_a : mkVote k (k*2, 0, k*2)\n|veto_b : mkVote k (k*2, k*2, 0).\n\n(*construct a list of votes given a list of weights*)\nInductive mkVotes : list int -> list vote -> Prop :=\n|mkVotesNil : mkVotes nil nil\n|mkVotesNonNil : forall ks vs k v, \n                   mkVotes ks vs -> mkVote k v ->\n                   mkVotes (k::ks) (v::vs). \n\n(*base_vote is the vote of the non manipulator.  \n**weights are the weights of the manipulators*)\nInductive manipulate (base_vote : vote) (weights : list int) : Prop := \n|manipulate_ : forall votes, \n                 mkVotes weights votes -> \n                 p_wins (score_votes (base_vote::votes)) ->\n                 manipulate base_vote weights. \n\nDefinition reduce k (l:list int) := ((0,k*2-1,k*2-1), l). \n\nLtac inv H := inversion H; subst; clear H. \n\nLtac copy H :=\n  match type of H with\n      |?x => assert(x) by auto\n  end. \n\nLtac invertHyp := \n  match goal with\n      |H:exists x, ?P |- _ => inv H; try invertHyp \n      |H:?A /\\ ?B |- _ => inv H; try invertHyp\n  end. \n\nTheorem sumRemoveMid : forall a b c k, sum (a++b::c) = k -> \n                                  sum (a++c) = k - b. \nProof.\n  induction a; intros. \n  {simpl in *. symmetry in H. apply Zplus_minus_eq in H. auto. }\n  {simpl in *. symmetry in H. apply Zplus_minus_eq in H. eapply IHa in H. \n   rewrite H. rewrite Z.add_sub_assoc. rewrite Zplus_minus. auto. }\nQed. \n\nLtac votesEq :=\n  match goal with\n      | |- (?a,?b,?c)=(?a,?b,?f) =>\n        let n := fresh \n        in assert(n:c=f) by omega; rewrite n; try votesEq\n      | |- (?a,?b,?c)=(?a,?e,?f) =>\n        let n := fresh \n        in assert(n:b=e) by omega; rewrite n; try votesEq\n      | |- (?a,?b,?c)=(?d,?e,?f) =>\n        let n := fresh \n        in assert(n:a=d) by omega; rewrite n; try votesEq\n      | |- _ => eauto\n  end. \n\nTheorem mkVotesSum : forall weights l1 l2 k1 k2,\n                       sum l1 = k1 -> sum l2 = k2 -> split weights l1 l2 ->\n                       exists vs, mkVotes weights vs /\\ \n                             score_votes vs = ((k1+k2)*2, k2*2, k1*2). \nProof.\n  intros. genDeps {{ k1; k2 }}. induction H1; intros. \n  {simpl in *. subst. exists nil. simpl. repeat constructor. }\n  {apply sumRemoveMid in H. eapply IHsplit in H; eauto. invertHyp.\n   exists ((x*2,0,x*2)::x0). split. constructor. auto. constructor.\n   simpl. rewrite H0. votesEq. }\n  {apply sumRemoveMid in H0. eapply IHsplit in H0; eauto. invertHyp.\n   exists ((x*2,x*2,0)::x0). split. constructor. auto. constructor.\n   simpl. rewrite H0. votesEq. }\nQed. \n\nTheorem score_votes_total : forall vs, \n                              exists s1 s2 s3, score_votes vs = (s1,s2,s3). \nProof.\n  induction vs.\n  {exists 0. exists 0. exists 0. simpl. auto. }\n  {destruct a. destruct p. invertHyp. repeat econstructor. \n   simpl. rewrite H. auto. }\nQed. \n\nTheorem add_votesSub : forall k1 k2 k3 vs s1 s2 s3, \n                         add_votes (k1,k2,k3) vs = (s1,s2,s3) ->\n                         vs = (s1-k1,s2-k2,s3-k3). \nProof.\n  intros. simpl in *. destruct vs. destruct p. inv H. \n  repeat (rewrite <- Z.add_sub_assoc; rewrite Zplus_minus). auto. \nQed. \n\nDefinition multOf x k := exists y, y * k = x. \n\nTheorem mustBe4K : forall weights k votes s1 s2 s3, \n                 sum weights = k  ->\n                 mkVotes weights votes -> \n                 score_votes votes = (s1,s2,s3) -> \n                 s1  = k * 2 /\\ s2 + s3 = s1 /\\ multOf s2 2 /\\ multOf s3 2. \nProof.\n  intros. genDeps {{ k; s1; s2; s3 }}. induction H0; intros. \n  {simpl in *. inv H1. split; auto. split; auto. unfold multOf.\n   split; exists 0; auto. }\n  {simpl in *. symmetry in H2. apply Zplus_minus_eq in H2. inv H.\n   {apply add_votesSub in H1. eapply IHmkVotes in H1; eauto. invertHyp. \n    unfold multOf in *. invertHyp. split. omega. split. omega. split. \n    exists (x0). omega. exists (x+k). omega. }\n   {apply add_votesSub in H1. eapply IHmkVotes in H1; eauto. split. omega. split. \n    omega. unfold multOf in *. invertHyp. split. exists (x0+k). omega. exists x. omega. }\n  }\nQed. \n\nLtac solveByInv := \n  match goal with\n      |H:_ |- _ => solve[inv H]\n  end. \n\nTheorem weightsToVotes : forall votes weights s1 s2 s3, \n                  mkVotes weights votes ->\n                  score_votes votes = (s1,s2,s3) ->\n                  exists l1 l2, split weights l1 l2 /\\ sum l1 * 2 = s2 /\\ sum l2 * 2 = s3. \nProof.\n  intros. genDeps {{ s1; s2; s3 }}. induction H; intros. \n  {simpl in H0. inv H0. exists nil. exists nil. split. constructor. auto. }\n  {simpl in H1. inv H0. \n   {apply add_votesSub in H1. eapply IHmkVotes in H1. invertHyp. \n    exists x. exists (nil++k::x0). split. constructor. simpl. auto. simpl. \n    split; omega. }\n   {apply add_votesSub in H1. eapply IHmkVotes in H1. invertHyp. \n    exists (nil++k::x). exists x0. split. constructor. simpl. auto. simpl. \n    split; omega. }\n  }\nQed. \n\nTheorem veto_npc : forall l k nonManipVote weights,\n                     reduce k l = (nonManipVote, weights) -> sum l = k*2 ->\n                     (partition k l <-> manipulate nonManipVote weights). \nProof.\n  intros. split; intros. \n  {unfold reduce in H. inv H. inversion H1. eapply mkVotesSum in H2; eauto. \n   invertHyp. econstructor. eauto. simpl. rewrite H3. constructor; omega. }\n  {unfold reduce in *. inv H. inv H1.  \n   assert(exists s1 s2 s3, score_votes votes = (s1,s2,s3)). apply score_votes_total. \n   invertHyp. simpl in H2. rewrite H3 in H2. inv H2. copy H0. \n   eapply mustBe4K in H1; eauto. invertHyp. unfold multOf in *. invertHyp.  \n   assert(x1 <= k). omega. assert(x <= k). omega. rewrite <- Z.mul_assoc in H1. \n   simpl in H1. assert((x1+x) = k * 2). omega. assert(x1=k /\\ x=k). omega. invertHyp.\n   eapply weightsToVotes in H; eauto. invertHyp. econstructor; eauto. \n   erewrite Z.mul_cancel_r in H; auto.  omega. erewrite Z.mul_cancel_r in H10; auto. \n   omega. }\nQed. \n\n\n\n\n\n\n", "meta": {"author": "lexxx320", "repo": "TheoryThinkTank", "sha": "e55c332cecaebf0c7556ca5a7ff74768254db389", "save_path": "github-repos/coq/lexxx320-TheoryThinkTank", "path": "github-repos/coq/lexxx320-TheoryThinkTank/TheoryThinkTank-e55c332cecaebf0c7556ca5a7ff74768254db389/case_study/veto_npc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6831076266624064}}
{"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 exo1.\n  \n  \n\n  (* Programme annoté :\n\n  { y = 2 }\n    Auto0:x <- (y + 3)\n  { (x = 5 and y = 2) }\n\n  *)\n\n  (* Valeurs des Weakest Least Preconditions (WLP) *)\n  Definition Post (x y : nat) := (x = 5 /\\ y = 2).\n  Definition Pre (x y : nat) := y = 2.\n  Definition Auto0 (x y : nat) := ((y + 3) = 5 /\\ y = 2).\n\n  (* Obligations de preuve engendrées *)\n  Lemma obligation_Pre : forall x y : nat,\n    (y = 2 -> ((y + 3) = 5 /\\ y = 2)).\n  Proof.\n    intros.\n    split.\n    rewrite H.\n    trivial.\n    assumption.\n  Qed.\n  \n\n  \n\nEnd exo1.\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/exo1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6831076260838488}}
{"text": "Require Import Bool Arith List Cpdt.CpdtTactics.\n\nNotation \"'Yes'\" := (left _ _).\nNotation \"'No'\" := (right _ _).\nNotation \"'Reduce' x\" := (if x then Yes else No) (at level 50).\n\nDefinition compare : 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", "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/0.4-1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.6830975967347722}}
{"text": "(* ###################################################################### *)\n(* taken from http://www.cis.upenn.edu/~rrand/popl_2016/ *)\n(** * Case study: Red-Black Trees *)\n\nOpen Scope bool_scope.\nRequire Import Coq.Arith.Arith_base.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Psatz.\n\n(** (We use [admit] and [Admitted] to hide solutions from exercises.) *)\n\nAxiom admit : forall {T : Type}, T.\n\n(** We will now see how we can use Coq's language to implement an\n    interesting functional program: a red-black tree module. Red-black\n    trees are binary search trees that use an intricate invariant to\n    guarantee that they are well-balanced.\n\n    We state our definitions inside of a Coq [Section], which allows\n    us parameterize them by the type of elements to be\n    stored. Specifically, we use the [Parameter] and [Hypothesis]\n    keywords to introduce parameters and hypothesis that can be\n    invoked in definitions and lemmas inside the [Section]. *)\n\nSection RedBlack.\n\n(** Our definitions are parameterized by a type [A] and a comparison\n    function [comp] between elements of [A]. The [comparison] type is\n    defined in the standard library, and represents the result of\n    comparing two elements of a totally ordered type. *)\n\nParameter A : Type.\nParameter comp : A -> A -> comparison.\n(* Inductive comparison : Type := Eq | Lt | Gt. *)\n\n(** In order for our definitions to work, we must assume that a few\n    properties hold of the [comp] operator. First, we assume that\n    [comp] is _transitive_: that is, if [x] is less than [y] and [y]\n    is less than [z], then [x] is less than [z]. *)\n\nHypothesis comp_trans :\n  forall x y z, comp x y = Lt ->\n                comp y z = Lt ->\n                comp x z = Lt.\n\n(** Next, we assume that [comp] is reflexive, and that elements that\n    test for [Eq] are equal. *)\n\nHypothesis comp_refl_iff :\n  forall x y, comp x y = Eq <-> x = y.\n\n(** [A <-> B] (\"A if and only if B\") states that [A] and [B] are\n    _logically equivalent_, i.e., that [A] implies [B] and [B] implies\n    [A]. It can be applied in either direction with the [apply]\n    tactic. It can also be rewritten with [rewrite]. *)\n\n(** **** Exercise: 1 star (comp_refl)  *)\n(** Practice the use of [rewrite] to prove the following. *)\n\nLemma comp_refl : forall x, comp x x = Eq.\nProof.\nintro. rewrite comp_refl_iff. reflexivity.\nQed.\n(* FILL IN HERE *)\n(** [] *)\n\n(** Finally, we assume that if [x] is less than [y], then [y] is\n    greater than [x]. The [CompOpp] function swaps [Lt] and [Gt]. *)\n\nHypothesis comp_opp :\n  forall x y, comp x y = CompOpp (comp y x).\n\n(** Red-black trees are binary search trees that contain elements of\n    [A] on their internal nodes, and such that every internal node is\n    colored with either [Red] or [Black]. [Leaf] represents an empty\n    tree. [Node c left x right] represents an internal node colored\n    [c], with children [left] and [right], storing element [x : A]. *)\n\nInductive color := Red | Black.\n\nInductive tree :=\n| Leaf : tree\n| Node : color -> tree -> A -> tree -> tree.\n\n(** **** Exercise: 2 stars (elements)  *)\n\n(** Using the list functions we have already studied, complete the\n    definition of the [elements] function below. Your implementation\n    should perform an inorder traversal of the elements of [t] and\n    accumulate them in a list. *)\n\nFixpoint elements (t : tree) : list A :=\n match t with\n  | Leaf => []\n  | Node _ l x r => (elements l) ++ x :: [] ++ (elements r)\n end.\n(* FILL IN HERE *)\n(** [] *)\n\n(** Before getting into details about the red-black invariants, let's\n    study the following function, which looks up an element [x] of [A]\n    on a tree. *)\n\nFixpoint member x t : bool :=\n  match t with\n  | Leaf => false\n  | Node _ t1 x' t2 =>\n    match comp x x' with\n    | Lt => member x t1\n    | Eq => true\n    | Gt => member x t2\n    end\n  end.\n\n(** **** Exercise: 1 star (member_ex)  *)\n\n(** To test your understanding of [member], prove the following\n    result. *)\n\nExample member_ex :\n  forall x tl y tr,\n    member x tl = true ->\n    comp x y = Lt ->\n    member x (Node Black tl y tr) = true.\nProof.\nintros c tl y tr.\nintros mem_left x_le_y.\nsimpl. rewrite x_le_y. rewrite mem_left. reflexivity.\nQed.\n(* FILL IN HERE *)\n\n(** [] *)\n\n(** We want to state a specification for [member] and prove that it is\n    valid. First, we formalize what it means for a tree to be a binary\n    search tree. This requires the following function, which tests\n    whether a property [f] holds of the elements of a tree [t]: *)\n\nFixpoint all (f : A -> bool) (t : tree) : bool :=\n  match t with\n  | Leaf => true\n  | Node _ t1 x t2 => all f t1 && f x && all f t2\n  end.\n\n(** Let's prove the following simple property of [all], which will\n    be useful later. *)\n\nLemma all_weaken :\n  forall f g,\n    (forall x, f x = true -> g x = true) ->\n    forall t, all f t = true -> all g t = true.\nProof.\n  intros f g Hfg t.\n\n(** New tactic\n    ----------\n\n    - [trivial]: solves simple goals through [reflexivity] and by\n      looking for assumptions in the context that apply directly. If\n      it cannot solve the goal, it does nothing. *)\n\n  induction t as [|c t1 IH1 x t2 IH2].\n  - trivial.\n  - simpl. intros H. \n\n(** Often, tactics generate multiple subgoals that can be solved\n    with simple (or very similar) proofs. We can handle these\n    simultaneously using the tactic sequencing operator [;]. *)\n\n(** New Tactics\n    -----------\n\n    - [;]: An expression such as [foo; bar] first calls [foo], then\n      calls [bar] on all generated subgoals. A common idiom is [foo;\n      trivial], which solves the trivial subgoals and does nothing on\n      the remaining ones.\n\n    - [try]: Calling [try foo] tries to execute [foo], doing nothing\n      if [foo] raises any errors. In particular, if [foo] is a\n      _terminating tactic_ such as [discriminate], [try foo] attempts\n      to solve the goal, and does nothing if it fails.\n\n    - [destruct ... eqn: ...]: Do case analysis on an expression while\n      generating an equation. *)\n\n(* WORKED IN CLASS *)\n    destruct (all f t1) eqn:H1; try discriminate.\n    destruct (f x) eqn:H2; try discriminate.\n    destruct (all f t1) eqn:H3; try discriminate.\n    rewrite IH1; trivial.\n    rewrite Hfg; trivial.\n    rewrite IH2; trivial.\nQed.\n\n(** We can now state the binary-tree invariant: Each element [x]\n    on an internal node is strictly greater than those to its left,\n    and strictly smaller than those to its right. The auxiliary\n    function [ltb] tests whether an element of [A] is smaller than\n    another one. *)\n\nDefinition ltb x y :=\n  match comp x y with\n  | Lt => true\n  | _ => false\n  end.\n\nFixpoint search_tree (t : tree) : bool :=\n  match t with\n  | Leaf => true\n  | Node _ t1 x t2 =>\n    all (fun y => ltb y x) t1\n    && all (ltb x) t2\n    && search_tree t1\n    && search_tree t2\n  end.\n\n(** In order to state the specification of [member], we define a\n    function [occurs] that looks up an element [x] on all nodes of a\n    tree [t]. The [eqb] function tests whether two elements of [A] are\n    equal. *)\n\nDefinition eqb x y :=\n  match comp x y with\n  | Eq => true\n  | _ => false\n  end.\n\nFixpoint occurs (x : A) (t : tree) : bool :=\n  match t with\n  | Leaf => false\n  | Node _ t1 y t2 => occurs x t1 || eqb x y || occurs x t2\n  end.\n\n(** **** Exercise: 2 stars (eqb_eq)  *)\n\n(** Show that [eqb] implies equality. *)\n\nLemma eqb_eq : forall x y, eqb x y = true -> x = y.\nProof.\n\nintros x y.\nunfold eqb.\nrewrite <- comp_refl_iff.\ndestruct comp eqn:f.\n+ trivial.\n+ intro. discriminate.\n+ intro. discriminate.\nQed.\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars (none_occurs)  *)\n(** If [x] is strictly smaller (or bigger) than the elements of a tree\n    [t], we know that [x] cannot occur in [t], thanks to the following\n    general result. Your job is to prove it and then use it to show\n    the [member_prune_right] and [member_prune_left] lemmas below. *)\n\nLemma none_occurs :\n  forall (x : A) (f : A -> bool) (t : tree),\n    f x = false ->\n    all f t = true -> \n    occurs x t = false.\nProof.\nintros.\ndestruct all eqn:H1.\ninduction t.\n- trivial.\n- simpl.\n\nsimpl in H1.\ndestruct (all f t1) eqn:H3; trivial.\ndestruct (all f t2) eqn:H4; trivial.\ndestruct (f a) eqn:H2; trivial.\nrewrite IHt1 in H1.\nrewrite IHt1.\nrewrite IHt2.\n+\n\n\n\n\n\ndestruct (all f t1) eqn:H1 in H0; try discriminate.\nsimpl in H0.\ndestruct (f a) eqn:H2; try discriminate.\nsimpl in H0.\n\napply IHt2 in H0.\napply IHt1 in H1.\n\nsimpl.\nrewrite H0.\nrewrite H1.\n\nsimpl.\nunfold eqb.\nrewrite <- H2.\ndestruct all eqn:H3.\ndestruct all eqn:H4.\ndestruct all eqn:H5.\nrewrite <- H.\ndestruct comp; trivial.\n- rewrite H. rewrite H2. \n\nsymmetry in IHt1.\nsimpl in H0.\ndestruct (all f t2) eqn:H2; try discriminate.\nrewrite <- IHt1; trivial.\nsimpl.\nrewrite IHt1; trivial.\nrewrite IHt2; trivial.\n\nsimpl in H0.\nsimpl in H0.\n\nsimpl.\n\nrewrite <- H.\n\n\nunfold eqb.\ndestruct comp.\nsimpl.\n\napply f.\ndestruct eqb eqn:H4.\nsimpl.\ndestruct (all f t2); try discriminate.\nrewrite <- IHt1; trivial.\n\n\ninduction (Node c t1 a t2).\n++\ntrivial.  \n++\n\n\nrewrite <- H.\ndestruct occurs.\n++\nrewrite <- H.\napply all.\nrewrite <- IHt2.\nrewrite IHt2.\n\ndestruct occurs.\nrewrite IHt1.\n\ndestruct all in IHt1.\n\n\ndestruct occurs.\nrewrite <- IHt1.\n++\n\ndestruct all in IHt2.\ndestruct occurs.\ndestruct occurs eqn:H2 in IHt2.\ndestruct occurs eqn:H1 in IHt1.\nrewrite <- IHt1.\ndestruct occurs eqn:H1.\ndestruct occurs eqn:H2 in IHt2.\nrewrite <- IHt1.\nrewrite IHt2.\ndestruct occurs eqn:H3.\ndestruct occurs.\nrewrite <- IHt1.\n++\n+++\nrewrite <- H0.\n\ntrivial.\nsimpl.\nrewrite <- H.\n\nsimpl.\nsimpl in H0.\ntrivial.\nsimpl in H0.\n\n++\ndestruct H0 eqn:H1.\n++\nsimpl.\n\n+++\n\nsimpl.\n\nunfold occurs.\n\nunfold all in H0.\n++\n\n\n(* FILL IN HERE *) Admitted.\n\nLemma member_prune_right :\n  forall x y t,\n    comp y x = Lt ->\n    all (ltb x) t = true ->\n    occurs y t = false.\nProof.\n(* FILL IN HERE *) Admitted.\n\nLemma member_prune_left :\n  forall x y t,\n    comp y x = Gt ->\n    all (fun z => ltb z x) t = true ->\n    occurs y t = false.\nProof.\n(* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** With these results, we are ready to prove the correctness of\n    [member]. Notice that we state the lemma in a slightly different\n    form, using an [if] expression instead of an implication\n    ([->]). This allows the Coq simplification engine to perform a few\n    deduction steps as we progress through the proof. *)\n\nLemma member_correct :\n  forall x t,\n    if search_tree t then member x t = occurs x t\n    else True.\nProof.\n  intros x t.\n  induction t as [|c t1 IH1 y t2 IH2]; simpl; trivial.\n  destruct (all (fun z => ltb z y) t1) eqn:H1; simpl; trivial.\n  destruct (all (ltb y) t2) eqn:H2; simpl; trivial.\n\n(** Notice how the induction hypotheses change after the following\n    lines. *)\n\n  destruct (search_tree t1) eqn:H3; simpl; trivial.\n  destruct (search_tree t2) eqn:H4; simpl; trivial.\n  unfold eqb. rewrite IH1, IH2.\n\n(** Note that we can apply lemmas with universally quantified\n    variables and hypotheses as functions. This has the effect of\n    instantiating these quantified variables and providing proofs for\n    the required hypotheses directly. *)\n(** Cf. the use of [member_prune_left] and [member_prune_right]\n    below. *)\n\n(* WORKED IN CLASS *)\n  destruct (comp x y) eqn:Hxy.\n  - rewrite Bool.orb_true_r. reflexivity.\n  - rewrite (member_prune_right y x t2 Hxy H2).\n    rewrite Bool.orb_false_r. rewrite Bool.orb_false_r. reflexivity.\n  - rewrite (member_prune_left y x t1 Hxy H1). reflexivity.\nQed.\n\n\n(** ** The Invariant\n\n    We now turn our attention to the actual red-black invariant. A\n    red-black tree is _valid_ if (1) all paths from the root of the\n    tree to its leaves go through the same number of black nodes, and\n    (2) if red nodes only have black children (we stipulate that the\n    leaves of the tree are black). *)\n(** The [well_colored] function below checks whether (2) holds\n    or not. To check (1), we use the [black_height] function defined\n    below: [black_height n t] returns [true] if and only if every path\n    from the root of the tree to a leaf goes through exactly [n] black\n    nodes. *)\n\nDefinition tree_color (t : tree) : color :=\n  match t with\n  | Leaf => Black\n  | Node c _ _ _ => c\n  end.\n\nFixpoint well_colored (t : tree) : bool :=\n  match t with\n  | Leaf => true\n  | Node c t1 _ t2 =>\n\n    let colors_ok :=\n      match c, tree_color t1, tree_color t2 with\n      | Red, Black, Black => true\n      | Red, _, _ => false\n      | Black, _, _ => true\n      end in\n    colors_ok && well_colored t1 && well_colored t2\n  end.\n\nFixpoint black_height n (t : tree) : bool :=\n  match t, n with\n  | Leaf, 0 => true\n  | Node Red tl _ tr, _ =>\n    black_height n tl && black_height n tr\n  | Node Black tl _ tr, S n =>\n    black_height n tl && black_height n tr\n  | _, _ => false\n  end.\n\n(** We combine both invariants in a single [is_red_black]\n    function: *)\n\nDefinition is_red_black n (t : tree) : bool :=\n  well_colored t && black_height n t.\n\n(** The red-black invariant implies that the height of the tree is\n    logarithmic on the number of nodes. To prove that this is the\n    case, we define a [size] function for computing various measures\n    on trees. Notice that [size] takes a function argument, which\n    determines which measure [size] actually computes. We can see that\n    [size max] computes the height of the tree, [size min] computes\n    the size of the smallest path from the root to a leaf, and [size\n    plus] computes the total number of elements stored on the tree. *)\n\nFixpoint size (f : nat -> nat -> nat) (t : tree) : nat :=\n  match t with\n  | Leaf => 0\n  | Node _ t1 _ t2 => S (f (size f t1) (size f t2))\n  end.\n\n(** It seems natural to claim that the black height of a tree is at\n    most the size of its minimal path. Showing this result is\n    easy. Here, we use the order relation on naturals provided by the\n    standard library. *)\n\nLemma size_min_black_height :\n  forall t n,\n    if black_height n t then n <= size min t\n    else True.\nProof.\n  intros t.\n  induction t as [|[] tl IHl x tr IHr]; intros n; simpl.\n  - destruct n as [|n]; trivial.\n\n(** Many of the results we will encounter involve integer\n    inequalities. To solve these goals, we can use the [lia] tactic.\n\n    New Tactics\n    -----------\n\n    - [lia]: Short for \"Linear Integer Arithmetic\"; tries to solve\n      goals that involve linear systems of inequalites on integers.\n\n    - [specialize]: Instantiate a universally quantified hypothesis *)\n\n  - specialize (IHl n). specialize (IHr n).\n    destruct (black_height n tl); trivial. simpl.\n    destruct (black_height n tr); trivial. lia.\n\n(* WORKED IN CLASS *)\n  - destruct n as [|n]; trivial.\n    specialize (IHl n). specialize (IHr n).\n    destruct (black_height n tl); trivial. simpl.\n    destruct (black_height n tr); trivial. lia.\nQed.\n\n(** We also need to relate the black and maximal heights of a\n    tree. Unlike the preceeding lemma, however, this result requires a\n    clever generalization to allow the induction to go through. *)\n\n(** **** Exercise: 2 stars (size_max_black_height)  *)\n\n(** The last part of the following proof covers trees with black\n    roots, and is very similar to the analogous one for red\n    roots. Your job is to complete it. *)\n\nLemma size_max_black_height :\n  forall t n,\n    if is_red_black n t then\n      match tree_color t with\n      | Red => size max t <= 2 * n + 1\n      | Black => size max t <= 2 * n\n      end\n    else True.\nProof.\n  intros t. unfold is_red_black.\n  induction t as [|[] tl IHl x tr IHr]; simpl; intros n.\n  - (* t is a Leaf *)\n    destruct n; trivial.\n  - (* t has a red root *)\n    destruct (tree_color tl); simpl; trivial.\n    destruct (tree_color tr); simpl; trivial.\n    specialize (IHl n). specialize (IHr n).\n    destruct (well_colored tl); simpl in *; trivial.\n    destruct (well_colored tr); simpl in *; trivial.\n    destruct (black_height n tl); simpl in *; trivial.\n    destruct (black_height n tr); simpl in *; trivial.\n    lia.\n  - (* t has a black root *)\n    (* FILL IN HERE *) admit.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars (size_max_size_min)  *)\n\n(** The previous two results imply the next one, which relates the\n    height of the tree to the length of its mininal path. The [assert]\n    tactic is used below to bring those results into the context as\n    explicit hypotheses. Finish the proof. *)\n\nLemma size_max_size_min :\n  forall t n,\n    if is_red_black n t then size max t <= 2 * size min t + 1\n    else True.\nProof.\n  intros t n.\n  assert (H1 := size_min_black_height t n).\n  assert (H2 := size_max_black_height t n).\n  unfold is_red_black in *.\n(* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** Finally, we derive the bound we sought by appealing to the\n    following lemma, proved using results from Coq's standard\n    library.\n\n    New Tactics\n    -----------\n\n    - [assert]: Introduce a new hypothesis in the context, requiring\n      us to prove that it holds. The curly braces [{}] allow us to\n      focus on the current subgoal, like [+] and [-]. *)\n\nLemma size_min_size_plus :\n  forall t,\n    size min t <= log2 (size plus t + 1).\nProof.\n  intros t. apply Nat.log2_le_pow2; try lia.\n  induction t as [|c t1 IH1 x t2 IH2]; simpl; trivial.\n  assert (H1 : 2 ^ min (size min t1) (size min t2)\n               <= 2 ^ size min t1).\n  { apply Nat.pow_le_mono_r; lia. }\n  assert (H2 : 2 ^ min (size min t1) (size min t2)\n               <= 2 ^ size min t2).\n  { apply Nat.pow_le_mono_r; lia. }\n  lia.\nQed.\n\nLemma is_red_black_balanced :\n  forall t n,\n    is_red_black n t = true ->\n    size max t <= 2 * log2 (size plus t + 1) + 1.\nProof.\n  intros t n H.\n  assert (H1 := size_max_size_min t n). rewrite H in H1.\n  assert (H2 := size_min_size_plus t). lia.\nQed.\n\n(** ** Insertion\n\n    Knowing that red-black trees are balanced would be useless if that\n    invariant were not preserved by tree operations. To conclude this\n    module, we define an insertion operation and show that it\n    preserves the red-black invariant.\n\n    Our definition is adapted from Chris Okasaki's classical paper\n    \"Red-Black Trees in a Functional Setting\". It is essentially a\n    standard insertion function on binary trees, except for an\n    additional balancing step for restoring the tree invariants. *)\n\nDefinition balance_black_left tl x tr : tree :=\n  match tl, x, tr with\n  | Node Red (Node Red t1 x1 t2) x2 t3, x3, t4\n  | Node Red t1 x1 (Node Red t2 x2 t3), x3, t4 =>\n    Node Red (Node Black t1 x1 t2) x2 (Node Black t3 x3 t4)\n  | _, _, _ => Node Black tl x tr\n  end.\n\nDefinition balance_black_right tl x tr : tree :=\n  match tl, x, tr with\n  | t1, x1, Node Red (Node Red t2 x2 t3) x3 t4\n  | t1, x1, Node Red t2 x2 (Node Red t3 x3 t4) =>\n    Node Red (Node Black t1 x1 t2) x2 (Node Black t3 x3 t4)\n  | _, _, _ => Node Black tl x tr\n  end.\n\nDefinition balance_left c t1 x t2 : tree :=\n  match c with\n  | Red => Node c t1 x t2\n  | Black => balance_black_left t1 x t2\n  end.\n\nDefinition balance_right c t1 x t2 : tree :=\n  match c with\n  | Red => Node c t1 x t2\n  | Black => balance_black_right t1 x t2\n  end.\n\nFixpoint insert_aux x t : tree :=\n  match t with\n  | Leaf => Node Red Leaf x Leaf\n  | Node c t1 x' t2 =>\n    match comp x x' with\n    | Eq => t (* Element was already present *)\n    | Lt => balance_left c (insert_aux x t1) x' t2\n    | Gt => balance_right c t1 x' (insert_aux x t2)\n    end\n  end.\n\nDefinition make_black t : tree :=\n  match t with\n  | Leaf => Leaf\n  | Node _ t1 x t2 => Node Black t1 x t2\n  end.\n\nDefinition insert x t : tree :=\n  make_black (insert_aux x t).\n\n(** The next lemmas are not strictly necessary, but they greatly\n    help us reasoning about the behavior of the balancing functions\n    above. Although they rely on a feature that we're not discussing\n    here in detail -- namely, _inductive propositions_ --, their use\n    is relatively simple, and is illustrated in the proof of the\n    [black_height_balance_left] lemma below. *)\n\nInductive balance_left_spec : color -> tree -> A -> tree -> tree -> Prop :=\n| BalanceLeftSpec1 :\n    forall t1 x1 t2 x2 t3 x3 t4,\n      balance_left_spec Black (Node Red (Node Red t1 x1 t2) x2 t3) x3 t4\n                        (Node Red (Node Black t1 x1 t2) x2 (Node Black t3 x3 t4))\n| BalanceLeftSpec2 :\n    forall t1 x1 t2 x2 t3 x3 t4,\n      balance_left_spec Black (Node Red t1 x1 (Node Red t2 x2 t3)) x3 t4\n                        (Node Red (Node Black t1 x1 t2) x2 (Node Black t3 x3 t4))\n| BalanceLeftSpec3 :\n    forall c t1 x t2,\n      balance_left_spec c t1 x t2 (Node c t1 x t2).\n\nLemma case_balance_left :\n  forall c t1 x t2,\n    balance_left_spec c t1 x t2 (balance_left c t1 x t2).\nProof.\n  intros [] t1 x t2; simpl; try constructor.\n  destruct t1 as [|[] [|[]] ? [|[]]]; simpl; constructor.\nQed.\n\nInductive balance_right_spec : color -> tree -> A -> tree -> tree -> Prop :=\n| BalanceRightSpec1 :\n    forall t1 x1 t2 x2 t3 x3 t4,\n      balance_right_spec Black t1 x1 (Node Red (Node Red t2 x2 t3) x3 t4)\n                         (Node Red (Node Black t1 x1 t2) x2 (Node Black t3 x3 t4))\n| BalanceRightSpec2 :\n    forall t1 x1 t2 x2 t3 x3 t4,\n      balance_right_spec Black t1 x1 (Node Red t2 x2 (Node Red t3 x3 t4))\n                         (Node Red (Node Black t1 x1 t2) x2 (Node Black t3 x3 t4))\n| BalanceRightSpec3 :\n    forall c t1 x t2,\n      balance_right_spec c t1 x t2 (Node c t1 x t2).\n\nLemma case_balance_right :\n  forall c t1 x t2,\n    balance_right_spec c t1 x t2 (balance_right c t1 x t2).\nProof.\n  intros [] t1 x t2; simpl; try constructor.\n  destruct t2 as [|[] [|[]] ? [|[]]]; simpl; constructor.\nQed.\n\nLemma black_height_balance_left :\n  forall c t1 x t2 n,\n    black_height n (balance_left c t1 x t2)\n    = black_height n (Node c t1 x t2).\nProof.\n  intros c t1 x t2 n.\n  destruct (case_balance_left c t1 x t2)\n    as [t1 x1 t2 x2 t3 x3 t4|t1 x1 t2 x2 t3 x3 t4|c t1 x t2]; simpl; trivial.\n  - destruct n as [|n]; trivial.\n    rewrite Bool.andb_assoc. reflexivity.\n  - destruct n as [|n]; trivial.\n    rewrite Bool.andb_assoc, Bool.andb_assoc.\n    reflexivity.\nQed.\n\n(** **** Exercise: 2 stars (black_height_balance_right)  *)\n\n(** Using the previous lemma as a template, complete the proof of\n    [black_height_balance_right] below. *)\n\nLemma black_height_balance_right :\n  forall c t1 x t2 n,\n    black_height n (balance_right c t1 x t2)\n    = black_height n (Node c t1 x t2).\nProof.\n(* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 3 stars (height_ok_insert_aux)  *)\n\n(** Use the last two results to show that the black height invariant\n    is preserved by [insert_aux]. *)\n\nLemma height_ok_insert_aux :\n  forall x t n,\n    black_height n (insert_aux x t)\n    = black_height n t.\nProof.\n(* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** The most complicated part of the invariant preservation proof for\n    the insertion algorithm is showing that nodes are still colored\n    correctly after an insertion step. One problem is that, even after\n    a balancing step, [insert_aux] may produce a tree that is colored\n    incorrectly at its root. We formalize this property with the\n    following definition: *)\n\nDefinition almost_well_colored t : bool :=\n  match t with\n  | Leaf => true\n  | Node _ t1 _ t2 => well_colored t1 && well_colored t2\n  end.\n\n(** **** Exercise: 1 star (well_colored_weaken)  *)\n\n(** Show that well-colored trees are almost well-colored. *)\n\nLemma well_colored_weaken :\n  forall t,\n    well_colored t = true ->\n    almost_well_colored t = true.\nProof.\n(* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** The following two lemmas show that tree balancing restores the\n    coloring invariant if one of the trees is almost\n    well-colored. They use more advanced proof automation features to\n    consider many of the cases arising in this proof at once. You\n    don't have to understand how these proofs work right now, but they\n    will be needed later for showing our final result. *)\n\nLemma well_colored_balance_black_left :\n  forall t1 x t2,\n    almost_well_colored t1 = true ->\n    well_colored (balance_black_left t1 x t2)\n    = well_colored t2.\nProof.\n  intros t1 x t2.\n  refine (match t1 with\n          | Node Red (Node Red _ _ _) _ _ => _\n          | Node Red _ _ (Node Red _ _ _) => _\n          | _ => _\n          end); simpl; try reflexivity;\n  repeat match goal with\n  | |- context[match ?b with _ => _ end] =>\n    destruct b; simpl; try discriminate\n  | |- context[?b && _ = true] =>\n    destruct b; simpl; try discriminate\n  | |- _ = true -> _ =>\n    intros H; rewrite H\n  end; reflexivity.\nQed.\n\nLemma well_colored_balance_black_right :\n  forall t1 x t2,\n    almost_well_colored t2 = true ->\n    well_colored (balance_black_right t1 x t2)\n    = well_colored t1.\nProof.\n  intros t1 x t2.\n  refine (match t2 with\n          | Node Red (Node Red _ _ _) _ _ => _\n          | Node Red _ _ (Node Red _ _ _) => _\n          | _ => _\n          end); simpl; try reflexivity;\n  repeat match goal with\n  | |- ?b = true -> _ =>\n    match b with\n    | context[tree_color ?t] =>\n      destruct (tree_color t); simpl; try discriminate\n    | context[well_colored ?t] =>\n      destruct (well_colored t); simpl; try discriminate\n    end\n  end; repeat rewrite Bool.andb_true_r; reflexivity.\nQed.\n\nLemma well_colored_insert_aux :\n  forall x t,\n    if well_colored t then\n      match tree_color t with\n      | Red => almost_well_colored (insert_aux x t)\n      | Black => well_colored (insert_aux x t)\n      end = true\n    else True.\nProof.\n  intros x t.\n  induction t as [|[] t1 IH1 x' t2 IH2]; trivial; simpl.\n  - reflexivity.\n  - destruct (tree_color t1); simpl; trivial.\n    destruct (tree_color t2); simpl; trivial.\n    destruct (comp x x'); simpl.\n    + destruct (well_colored t1 && well_colored t2); trivial.\n    + destruct (well_colored t1); simpl; trivial.\n      destruct (well_colored t2); simpl; trivial.\n      rewrite IH1. reflexivity.\n    + destruct (well_colored t1); simpl; trivial.\n  - destruct (comp x x'); simpl.\n    + destruct (well_colored t1 && well_colored t2); trivial.\n    + destruct (well_colored t1); simpl; trivial.\n      assert (IH1' : almost_well_colored (insert_aux x t1) = true).\n      { destruct (tree_color t1); trivial.\n        apply well_colored_weaken. trivial. }\n      rewrite well_colored_balance_black_left; trivial.\n      destruct (well_colored t2); trivial.\n    + rewrite Bool.andb_comm.\n      destruct (well_colored t2); simpl; trivial.\n      assert (IH1' : almost_well_colored (insert_aux x t2) = true).\n      { destruct (tree_color t2); trivial.\n        apply well_colored_weaken. trivial. }\n      rewrite well_colored_balance_black_right; trivial.\n      destruct (well_colored t1); trivial.\nQed.\n\nDefinition new_height n c :=\n  match c with\n  | Red => S n\n  | Black => n\n  end.\n\nLemma black_height_make_black :\n  forall t n,\n    black_height (new_height n (tree_color t)) (make_black t)\n    = black_height n t.\nProof. intros [|[] t1 x t2]; reflexivity. Qed.\n\nLemma almost_well_colored_make_black :\n  forall t, well_colored (make_black t) = almost_well_colored t.\nProof. intros [|c t1 x t2]; reflexivity. Qed.\n\nLemma is_red_black_insert :\n  forall x n t,\n    if is_red_black n t then\n      is_red_black (new_height n (tree_color (insert_aux x t))) (insert x t) = true\n    else True.\nProof.\n  intros x n t.\n  unfold insert, is_red_black.\n  assert (H1 := well_colored_insert_aux x t).\n  assert (H2 := height_ok_insert_aux x t).\n  rewrite black_height_make_black.\n  rewrite H2.\n  rewrite almost_well_colored_make_black.\n  destruct (well_colored t); simpl; trivial.\n  destruct (tree_color t).\n  - rewrite H1. destruct (black_height n t); trivial.\n  - rewrite well_colored_weaken; trivial.\n    destruct (black_height n t); trivial.\nQed.\n\nEnd RedBlack.\n", "meta": {"author": "santifa", "repo": "masterarbeit", "sha": "088210e071464831d3e496d3a8faac0aac494228", "save_path": "github-repos/coq/santifa-masterarbeit", "path": "github-repos/coq/santifa-masterarbeit/masterarbeit-088210e071464831d3e496d3a8faac0aac494228/learn-coq/redblack.full.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744806385542, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.683070023953015}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** Properties of the greatest common divisor *)\n\nRequire Import NAxioms NSub NZGcd.\n\nModule Type NGcdProp\n (Import A : NAxiomsSig')\n (Import B : NSubProp A).\n\n Include NZGcdProp A A B.\n\n(** Results concerning divisibility*)\n\nDefinition divide_1_r n : (n | 1) -> n == 1\n := divide_1_r_nonneg n (le_0_l n).\n\nDefinition divide_antisym n m : (n | m) -> (m | n) -> n == m\n := divide_antisym_nonneg n m (le_0_l n) (le_0_l m).\n\nLemma divide_add_cancel_r : forall n m p, (n | m) -> (n | m + p) -> (n | p).\nProof.\n intros n m p (q,Hq) (r,Hr).\n exists (r-q). rewrite mul_sub_distr_r, <- Hq, <- Hr.\n now rewrite add_comm, add_sub.\nQed.\n\nLemma divide_sub_r : forall n m p, (n | m) -> (n | p) -> (n | m - p).\nProof.\n intros n m p H H'.\n destruct (le_ge_cases m p) as [LE|LE].\n apply sub_0_le in LE. rewrite LE. apply divide_0_r.\n apply divide_add_cancel_r with p; trivial.\n now rewrite add_comm, sub_add.\nQed.\n\n(** Properties of gcd *)\n\nDefinition gcd_0_l n : gcd 0 n == n := gcd_0_l_nonneg n (le_0_l n).\nDefinition gcd_0_r n : gcd n 0 == n := gcd_0_r_nonneg n (le_0_l n).\nDefinition gcd_diag n : gcd n n == n := gcd_diag_nonneg n (le_0_l n).\nDefinition gcd_unique' n m p := gcd_unique n m p (le_0_l p).\nDefinition gcd_unique_alt' n m p := gcd_unique_alt n m p (le_0_l p).\nDefinition divide_gcd_iff' n m := divide_gcd_iff n m (le_0_l n).\n\nLemma gcd_add_mult_diag_r : forall n m p, gcd n (m+p*n) == gcd n m.\nProof.\n intros. apply gcd_unique_alt'.\n intros. rewrite gcd_divide_iff. split; intros (U,V); split; trivial.\n apply divide_add_r; trivial. now apply divide_mul_r.\n apply divide_add_cancel_r with (p*n); trivial.\n now apply divide_mul_r. now rewrite add_comm.\nQed.\n\nLemma gcd_add_diag_r : forall n m, gcd n (m+n) == gcd n m.\nProof.\n intros n m. rewrite <- (mul_1_l n) at 2. apply gcd_add_mult_diag_r.\nQed.\n\nLemma gcd_sub_diag_r : forall n m, n<=m -> gcd n (m-n) == gcd n m.\nProof.\n intros n m H. symmetry.\n rewrite <- (sub_add n m H) at 1. apply gcd_add_diag_r.\nQed.\n\n(** On natural numbers, we should use a particular form\n  for the Bezout identity, since we don't have full subtraction. *)\n\nDefinition Bezout n m p := exists a b, a*n == p + b*m.\n\nInstance Bezout_wd : Proper (eq==>eq==>eq==>iff) Bezout.\nProof.\n unfold Bezout. intros x x' Hx y y' Hy z z' Hz.\n setoid_rewrite Hx. setoid_rewrite Hy. now setoid_rewrite Hz.\nQed.\n\nLemma bezout_1_gcd : forall n m, Bezout n m 1 -> gcd n m == 1.\nProof.\n intros n m (q & r & H).\n apply gcd_unique; trivial using divide_1_l, le_0_1.\n intros p Hn Hm.\n apply divide_add_cancel_r with (r*m).\n now apply divide_mul_r.\n rewrite add_comm, <- H. now apply divide_mul_r.\nQed.\n\n(** For strictly positive numbers, we have Bezout in the two directions. *)\n\nLemma gcd_bezout_pos_pos : forall n, 0<n -> forall m, 0<m ->\n Bezout n m (gcd n m) /\\ Bezout m n (gcd n m).\nProof.\n intros n Hn. rewrite <- le_succ_l, <- one_succ in Hn.\n pattern n. apply strong_right_induction with (z:=1); trivial.\n unfold Bezout. solve_proper.\n clear n Hn. intros n Hn IHn.\n intros m Hm. rewrite <- le_succ_l, <- one_succ in Hm.\n pattern m. apply strong_right_induction with (z:=1); trivial.\n unfold Bezout. solve_proper.\n clear m Hm. intros m Hm IHm.\n destruct (lt_trichotomy n m) as [LT|[EQ|LT]].\n (* n < m *)\n destruct (IHm (m-n)) as ((a & b & EQ), (a' & b' & EQ')).\n rewrite one_succ, le_succ_l.\n apply lt_add_lt_sub_l; now nzsimpl.\n apply sub_lt; order'.\n split.\n exists (a+b). exists b.\n rewrite mul_add_distr_r, EQ, mul_sub_distr_l, <- add_assoc.\n rewrite gcd_sub_diag_r by order.\n rewrite sub_add. reflexivity. apply mul_le_mono_l; order.\n exists a'. exists (a'+b').\n rewrite gcd_sub_diag_r in EQ' by order.\n rewrite (add_comm a'), mul_add_distr_r, add_assoc, <- EQ'.\n rewrite mul_sub_distr_l, sub_add. reflexivity. apply mul_le_mono_l; order.\n (* n = m *)\n rewrite EQ. rewrite gcd_diag.\n split.\n exists 1. exists 0. now nzsimpl.\n exists 1. exists 0. now nzsimpl.\n (* m < n *)\n rewrite gcd_comm, and_comm.\n apply IHn; trivial.\n now rewrite <- le_succ_l, <- one_succ.\nQed.\n\nLemma gcd_bezout_pos : forall n m, 0<n -> Bezout n m (gcd n m).\nProof.\n intros n m Hn.\n destruct (eq_0_gt_0_cases m) as [EQ|LT].\n rewrite EQ, gcd_0_r. exists 1. exists 0. now nzsimpl.\n now apply gcd_bezout_pos_pos.\nQed.\n\n(** For arbitrary natural numbers, we could only say that at least\n  one of the Bezout identities holds. *)\n\nLemma gcd_bezout : forall n m,\n Bezout n m (gcd n m) \\/ Bezout m n (gcd n m).\nProof.\n intros n m.\n destruct (eq_0_gt_0_cases n) as [EQ|LT].\n right. rewrite EQ, gcd_0_l. exists 1. exists 0. now nzsimpl.\n left. now apply gcd_bezout_pos.\nQed.\n\nLemma gcd_mul_mono_l :\n  forall n m p, gcd (p * n) (p * m) == p * gcd n m.\nProof.\n intros n m p.\n apply gcd_unique'.\n apply mul_divide_mono_l, gcd_divide_l.\n apply mul_divide_mono_l, gcd_divide_r.\n intros q H H'.\n destruct (eq_0_gt_0_cases n) as [EQ|LT].\n rewrite EQ in *. now rewrite gcd_0_l.\n destruct (gcd_bezout_pos n m) as (a & b & EQ); trivial.\n apply divide_add_cancel_r with (p*m*b).\n now apply divide_mul_l.\n rewrite <- mul_assoc, <- mul_add_distr_l, add_comm, (mul_comm m), <- EQ.\n rewrite (mul_comm a), mul_assoc.\n now apply divide_mul_l.\nQed.\n\nLemma gcd_mul_mono_r :\n forall n m p, gcd (n*p) (m*p) == gcd n m * p.\nProof.\n intros. rewrite !(mul_comm _ p). apply gcd_mul_mono_l.\nQed.\n\nLemma gauss : forall n m p, (n | m * p) -> gcd n m == 1 -> (n | p).\nProof.\n intros n m p H G.\n destruct (eq_0_gt_0_cases n) as [EQ|LT].\n rewrite EQ in *. rewrite gcd_0_l in G. now rewrite <- (mul_1_l p), <- G.\n destruct (gcd_bezout_pos n m) as (a & b & EQ); trivial.\n rewrite G in EQ.\n apply divide_add_cancel_r with (m*p*b).\n now apply divide_mul_l.\n rewrite (mul_comm _ b), mul_assoc. rewrite <- (mul_1_l p) at 2.\n rewrite <- mul_add_distr_r, add_comm, <- EQ.\n now apply divide_mul_l, divide_factor_r.\nQed.\n\nLemma divide_mul_split : forall n m p, n ~= 0 -> (n | m * p) ->\n exists q r, n == q*r /\\ (q | m) /\\ (r | p).\nProof.\n intros n m p Hn H.\n assert (G := gcd_nonneg n m). le_elim G.\n destruct (gcd_divide_l n m) as (q,Hq).\n exists (gcd n m). exists q.\n split. now rewrite mul_comm.\n split. apply gcd_divide_r.\n destruct (gcd_divide_r n m) as (r,Hr).\n rewrite Hr in H. rewrite Hq in H at 1.\n rewrite mul_shuffle0 in H. apply mul_divide_cancel_r in H; [|order].\n apply gauss with r; trivial.\n apply mul_cancel_r with (gcd n m); [order|].\n rewrite mul_1_l.\n rewrite <- gcd_mul_mono_r, <- Hq, <- Hr; order.\n symmetry in G. apply gcd_eq_0 in G. destruct G as (Hn',_); order.\nQed.\n\n(** TODO : relation between gcd and division and modulo *)\n\n(** TODO : more about rel_prime (i.e. gcd == 1), about prime ... *)\n\nEnd NGcdProp.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Numbers/Natural/Abstract/NGcd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.8175744850834649, "lm_q1q2_score": 0.6830700159449068}}
{"text": "(*|\n###########################################################################\nCoq can't compute a well-founded function on ``Z``, but it works on ``nat``\n###########################################################################\n\n:Link: https://stackoverflow.com/q/44186751\n|*)\n\n(*|\nQuestion\n********\n\nI'm writing (for myself) an explanation of how to do well-founded\nrecursion in Coq. (see i.e. the Coq'Art book, chapter 15.2). First I\nmade an example function based on ``nat`` and that worked fine, but\nthen I did it again for ``Z``, and when I use ``Compute`` to evaluate\nit, it doesn't reduce all the way down to a ``Z`` value. Why?\n\nHere is my example (I put the text inside comments so one can\ncopy-paste the whole thing into your editor):\n|*)\n\n(* Test of well-founded recursion *)\n\n(* TL;DR: To do well-founded recursion, first create 'functional' and\nthen create the recursive function using Acc_iter, the iterator for\naccessible relations *)\n\n(* As an example, compute the sum of the series from 1 to n, something\nlike this sketch:\n\nfix f n := (if n = 0 then 0 else n + f (n-1))\n\nNow, let's not use structural recursion on n.\n\nInstead, we use well-founded recursion on n, using that the relation\nless-than ('lt') is wellfounded. The function f terminates because the\nrecursive call is made on a structurally smaller term (in the\ndecreasing Acc-chain). *)\n\n(* First we do it for nat *)\n\nRequire Import Arith.Arith.\nRequire Import Program.Utils. (* for 'dec' *)\nRequire Import Wellfounded.\n\n(* From a proof that a relation is wellfounded, we can get a proof\nthat a particular element in its domain is accessible.\n\nThe Check commands here are not necessary, just for documentation,\ndear reader. *)\n\nCheck well_founded : forall A : Type, (A -> A -> Prop) -> Prop.\nCheck lt_wf : well_founded lt.\nCheck (lt_wf 4711 : Acc lt 4711).\n\n(* First define a 'functional' F for f. It is a function that takes a\nfunction F_rec for the 'recursive call' as an argument. Because we\nneed to know n <> 0 in the second branch we use 'dec' to turn the\nboolean if-condition into a sumbool. This we get info about it into\nthe branches.\n\nWe write most of it with refine, and leave some holes to be filled in\nwith tactics later. *)\n\nDefinition F (n : nat) (F_rec : (forall y : nat, y < n -> nat)) : nat.\n  refine (if dec (n =? 0) then 0 else n + (F_rec (n - 1) _ )).\n  (* now we need to show that n-1 < n, which is true for nat if n<>0 *)\n  destruct n; now auto with *.\nDefined.\n\n(* The functional can be used by an iterator to call f as many times\nas is needed.\n\nSide note: One can either make an iterator that takes the maximal\nrecursive depth d as a nat argument, and recurses on d, but then one\nhas to provide d, and also a 'default value' to return in case d\nreaches zero and one must terminate early.\n\nThe neat thing with well-founded recursion is that the iterator can\nrecurse on the proof of wellfoundedness and doesnt need any other\nstructure or default value to guarantee it will terminate. *)\n\n(* The type of Acc_iter is pretty hairy *)\n\nCheck Acc_iter :\n  forall (A : Type) (R : A -> A -> Prop) (P : A -> Type),\n    (forall x : A, (forall y : A, R y x -> P y) -> P x) ->\n    forall x : A, Acc R x -> P x.\n\n(* P is there because the return type could be dependent on the\nargument, but in our case, f:nat->nat, and R = lt, so we have *)\n\nCheck Acc_iter (R:=lt) (fun _:nat=>nat) :\n  (forall n : nat, (forall y : nat, y < n -> nat) -> nat) ->\n  forall n : nat, Acc lt n -> nat.\n\n(* Here the first argument is the functional that the iterator takes,\nthe second argument n is the input to f, and the third argument is a\nproof that n is accessible. The iterator returns the value of f\napplied to n.\n\nSeveral of Acc_iter's arguments are implicit, and some can be\ninferred. Thus we can define f simply as follows: *)\n\nDefinition f n := Acc_iter _ F (lt_wf n).\n\n(* It works like a charm *)\n\nCompute (f 50). (* This prints 1275 *)\nCheck eq_refl : f 50 = 1275.\n\n(* Now let's do it for Z. Here we can't use lt, or lt_wf because they\nare for nat. For Z we can use Zle and (Zwf c) which takes a lower\nbound. It needs a lower bound under which we know that the function\nwill always terminate to guarantee termination. Here we use (Zwf 0) to\nsay that our function will always terminate at or below 0. We also\nhave to change the if-statement to 'if n <= 0 then 0 else ...' so we\nreturn zero for arguments less than zero. *)\n\nRequire Import ZArith.\nRequire Import Zwf.\n\nOpen Scope Z.\n\n(* Now we define the function g based on the functional G *)\n\nDefinition G (n : Z) (G_rec : (forall y : Z, Zwf 0 y n -> Z)) : Z.\n  refine (if dec (n <? 0) then 0 else n + (G_rec (n - 1) _ )).\n  (* now we need to show that n-1 < n *)\n  now split; [apply Z.ltb_ge | apply Z.lt_sub_pos].\nDefined.\n\nDefinition g n := Acc_iter _ G (Zwf_well_founded 0 n).\n\n(* But now we can't compute! *)\n\nCompute (g 1).\n\n(* We just get a huge a term *)\n\n(*|\nComment: I noticed that ``Zwf_well_founded`` is defined as ``Opaque``\nin the library, so I tried to make it ``Transparent`` by copying the\nproof and ending the lemma with ``Defined.`` instead of ``Qed.`` but\nthat didn't help...\n\nAdded observation:\n\nIf I define ``f'`` for ``nat`` with ``Fixpoint`` instead, and recurse\non the accesibility proof, *and end with* ``Defined``. then it\ncomputes. But if I end with ``Qed.``. it doesn't reduce. Is this\nrelated? I guess there is an issue of transparency in the definition\nof ``G`` or ``g`` somewhere... Or am I completely mistaken?\n|*)\n\nClose Scope Z. (* .none *)\nFixpoint f' (n : nat) (H: Acc lt n) : nat.\n  refine (if dec (n <=? 0) then 0 else n + (f' (n - 1) (Acc_inv H _))).\n  apply Nat.leb_gt in e.\n  apply Nat.sub_lt; auto with *.\nDefined.\n(* Compute (f' 10 (lt_wf 10)). doesn't evaluate to a nat if ended with Qed. *)\n\n(*| Anyway, my problem persists for ``Z``. |*)\n\nOpen Scope Z. (* .none *)\nFixpoint g' (n : Z) (H : Acc (Zwf 0) n) : Z.\n  refine (if dec (n <=? 0) then 0 else n + (g' (n - 1) (Acc_inv H _))).\n  split; now apply Z.leb_gt in e; auto with *.\nDefined.\n\nCompute (g' 10 (Zwf_well_founded 0 10)).\n\n(*|\n----\n\n**A:** This is a related `question\n<https://stackoverflow.com/questions/32354286/compute-with-a-recursive-function-defined-by-well-defined-induction>`__.\n\n**A:** This `one <https://stackoverflow.com/questions/28478445/>`__ is\nsomewhat related as well.\n|*)\n\n(*|\nAnswer\n******\n\nMaking `Zwf_well_founded\n<https://coq.inria.fr/library/Coq.ZArith.Zwf.html#Zwf_well_founded>`__\ntransparent won't help, because of the way it is defined in the\nstandard library:\n\n.. code-block:: coq\n\n    Lemma Zwf_well_founded : well_founded (Zwf c).\n      ...\n      case (Z.le_gt_cases c y); intro; auto with zarith.\n      ...\n    Qed.\n\nIf you replace the line in the proof above with\n\n.. code-block:: coq\n\n      case (Z_le_gt_dec c y); intro; auto with zarith.\n\nand replace ``Qed.`` with ``Defined.`` (which you already did)\neverything should work. This is due the fact that the original proof\ndepends on a logical term, and that prevents the evaluator from doing\npattern-matching, because logical entity ``Z.le_gt_cases`` is opaque,\nwhile computational entity ``Z_le_gt_dec`` is transparent. See `Using\nCoq's evaluation mechanisms in anger\n<http://gallium.inria.fr/blog/coq-eval/>`__ blog post by Xavier Leroy.\nYou might also find useful `Qed Considered Harmful\n<https://gmalecha.github.io/reflections/2017/qed-considered-harmful>`__\npost by Gregory Malecha.\n\nInstead of modifying the proof of ``Zwf_well_founded`` you can reuse\n`Zlt_0_rec\n<https://coq.inria.fr/library/Coq.ZArith.Wf_Z.html#Zlt_0_rec>`__ like\nso:\n|*)\n\nRequire Import Coq.ZArith.ZArith.\n\nOpen Scope Z.\n\nDefinition H (x : Z) (H_rec : (forall y : Z, 0 <= y < x -> Z))\n           (nonneg : 0 <= x) : Z.\n  refine (if Z_zerop x then 0 else x + (H_rec (Z.pred x) _ )).\n  auto with zarith.\nDefined.\n\nDefinition h (z : Z) : Z :=\n  match Z_lt_le_dec z 0 with left _ => 0 | right pf => (Zlt_0_rec _ H z pf) end.\n\nCheck eq_refl : h 100 = 5050.\n\n(*|\nIt's a bit less convenient because now we have to deal with negative\nnumbers in ``h``.\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-cant-compute-a-well-founded-function-on-z-but-it-works-on-nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.6830700029471332}}
{"text": "Require Export SfLib. \n\nDefinition multiset (A:Type) := list A. \n\nDefinition In (A:Type) T e := @In A e T. \n\nDefinition Union (A:Type) (m1 m2 : multiset A) := m1 ++ m2. \n\nDefinition Add (A:Type) (m:multiset A) (a:A) := m++[a]. \n\nDefinition Empty_set (A:Type) := @nil A. \n\nAxiom classicT : forall (P : Prop), {P} + {~ P}.\n\nFixpoint Subtract (A:Type) (m:multiset A) (e:A) :=\n  match m with\n    |m::ms => if classicT (m = e)\n              then ms\n              else m::Subtract A ms e\n    |nil => nil\n  end. \n\nDefinition Single (A:Type) (m1 : A) : multiset A := [m1]. \n\nDefinition Couple (A:Type) (m1 m2 : A) : multiset A := [m1;m2]. \n\nAxiom MultisetExtensionality : forall A (M1 M2 : multiset A),\n                                 (forall x:A, In A M1 x -> In A M2 x) /\\\n                                 (forall x:A, In A M2 x -> In A M1 x) -> M1 = M2. \n\nHint Unfold In. \nLtac invUnion :=\n  unfold In in *; \n  match goal with\n      |H:List.In ?x (Union ?A ?T1 ?T2) |- _ => apply in_app_iff in H\n      | |- List.In ?x (Union ?A ?T1 ?T2) => apply in_app_iff\n  end. \n \nHint Resolve in_app_iff.\n\nTheorem Union_commutative : forall A (M1 M2 : multiset A), Union A M1 M2 = Union A M2 M1. \nProof.\n  intros. apply MultisetExtensionality. split; intros. \n  {repeat invUnion. inversion H; auto. }\n  {repeat invUnion. inversion H; eauto. }\nQed. \n\nTheorem Union_associative : forall A (M1 M2 M3 : multiset A), \n                              Union A M1 (Union A M2 M3) = Union A (Union A M1 M2) M3. \nProof.\n  intros. apply MultisetExtensionality. split; intros. \n  {repeat invUnion. inversion H. left. invUnion; auto. invUnion. \n   inversion H0; auto. left. invUnion; auto. }\n  {repeat invUnion. inversion H. invUnion. inversion H0. auto. right. \n   invUnion. auto. right. invUnion. auto. }\nQed. \n\nTheorem union_empty_r : forall A T, Union A T (Empty_set A) = T. \nProof. \n  intros. rewrite Union_commutative. simpl. auto. \nQed. \n\nTheorem couple_swap : forall (T:Type) (t1 t2:T), Couple T t1 t2 = Couple T t2 t1. \nProof.\n  intros. apply MultisetExtensionality. split; intros. \n  {inversion H. subst. simpl. right. auto. inversion H0. subst. simpl. auto. \n   inversion H1. }\n  {inversion H. subst. simpl. right. auto. inversion H0. subst. simpl. auto. \n   inversion H1. }\nQed. \n\nTheorem pullOut : forall (A:Type) T (e:A),\n                    In A T e -> T = Union A (Subtract A T e) (Single A e). \nProof.\n  induction T; intros. \n  {inversion H. }\n  {inversion H; subst. \n   {simpl. destruct (classicT (e=e)). \n    {rewrite Union_commutative. simpl. auto. }\n    {exfalso. apply n; auto. }\n   }\n   {simpl. destruct (classicT (a=e)). \n    {subst. rewrite Union_commutative. simpl. auto. }\n    {simpl. erewrite <- IHT; eauto. }\n   }\n  }\nQed. \n\nTheorem UnionSubtract : forall (X:Type) T (x:X),\n                          Subtract X (Union X T (Single X x)) x = T. \nProof.\n  induction T; intros. \n  {simpl. destruct (classicT(x=x)). auto. exfalso; apply n; auto. }\n  {simpl. destruct (classicT(a=x)). subst. rewrite Union_commutative. \n   simpl; auto. rewrite IHT. auto. }\nQed. \n\nTheorem subtractSingle : forall (X:Type) T (x1:X), \n              (Subtract X (Union X (Subtract X T x1) (Single X x1)) x1) =\n              Subtract X T x1. \nProof.\n  induction T; intros. \n  {simpl. destruct (classicT (x1=x1)); auto. exfalso; apply n; auto. }\n  {simpl. destruct (classicT(a=x1)). \n   {rewrite UnionSubtract. auto. }\n   {simpl. destruct (classicT(a=x1)); try contradiction. \n    rewrite IHT; eauto. }\n  }\nQed. \n\nTheorem UnionSwap: forall (X : Type) (T1 T2 T3 : multiset X),\n                     Union X (Union X T1 T2) T3 = Union X (Union X T1 T3) T2.\nProof.\n  intros. rewrite <- Union_associative. rewrite (Union_commutative X T2). \n  rewrite Union_associative. auto. \nQed. \n\nTheorem coupleUnion : forall (U:Type) (t1 t2 : U), \n                        Couple U t1 t2 = Union U (Single U t1) (Single U t2). \nProof.\n  intros. simpl. unfold Couple. unfold Single. auto. \nQed. \n\nLtac flipCouples :=\n  rewrite couple_swap; rewrite coupleUnion; try flipCouples; rewrite <- coupleUnion. \n\nLtac flipCouplesIn H :=\n  rewrite couple_swap in H; rewrite coupleUnion in H; try flipCouplesIn H; rewrite <- coupleUnion in H. \n\nTheorem pullOutL : forall (A:Type) (T1 : multiset A) T2 T3,\n                     Union A T1 (Couple A T2 T3) = \n                     Union A (Union A T1 (Single A T3)) (Single A T2).\nProof.\n  intros. rewrite coupleUnion. rewrite Union_associative. \n  rewrite UnionSwap. auto. \nQed. \n\nTheorem pullOutR : forall (A:Type) (T1 : multiset A) T2 T3,\n                     Union A T1 (Couple A T2 T3) = \n                     Union A (Union A T1 (Single A T2)) (Single A T3).\nProof.\n  intros. rewrite coupleUnion. rewrite Union_associative. \n  rewrite UnionSwap. auto. \nQed. \n\nTheorem subtractUnion : forall (A:Type) T (e:A),\n                          In A T e -> Union A (Subtract A T e) (Single A e) = T.\nProof.\n  induction T; intros. \n  {inversion H. }\n  {inversion H; subst. simpl. destruct (classicT(e=e)). \n   {rewrite Union_commutative. simpl. auto. }\n   {exfalso. apply n; auto. }\n   {simpl. destruct (classicT(a=e)). \n    {subst. rewrite Union_commutative. simpl. auto. }\n    {simpl. rewrite IHT; auto. }\n   }\n  }\nQed. \n\n\nTheorem UnionEqSingleton : forall (A:Type) (T:multiset A) t t',\n                             Union A T (Single A t) = (Single A t') ->\n                             t = t' /\\ T = Empty_set A. \nProof.\n  intros. destruct T. \n  {inversion H. auto. }\n  {inversion H; subst. rewrite Union_commutative in H2. simpl in *. \n   inversion H2. }\nQed. \n\nTheorem union_empty_l : forall (A:Type) (T:multiset A),\n                           Union A (Empty_set A) T = T. \nProof.\n  intros. simpl. auto. \nQed. \n\nTheorem UnionSwapR : forall (A:Type) T (t1 t2 t3 : A),\n                       Union A (Union A T (Single A t1)) (Couple A t2 t3) = \n                       Union A (Union A T (Single A t3)) (Couple A t2 t1).\nProof.\n  intros. repeat rewrite <- Union_associative. repeat rewrite coupleUnion. \n  rewrite (Union_associative A (Single A t1)). \n  rewrite (Union_commutative A (Single A t1)). rewrite <- Union_associative. \n  rewrite (Union_commutative A (Single A t1)).\n  rewrite (Union_associative A (Single A t2)). \n  rewrite (Union_commutative A (Single A t2)). rewrite <- Union_associative. \n  auto. \nQed. \n\nTheorem UnionSwapL : forall (A:Type) T (t1 t2 t3 : A),\n                       Union A (Union A T (Single A t1)) (Couple A t2 t3) = \n                       Union A (Union A T (Single A t2)) (Couple A t1 t3).\nProof.\n  intros. repeat rewrite <- Union_associative. rewrite coupleUnion. \n  rewrite coupleUnion. rewrite (Union_associative A (Single A t1)). \n  rewrite (Union_commutative A (Single A t1)). \n  rewrite <- Union_associative. rewrite <- (coupleUnion A t1). auto. \nQed. \n", "meta": {"author": "lexxx320", "repo": "PersonalProjects", "sha": "bc83fb250467b013d9db9fe535ff7bd314632d4c", "save_path": "github-repos/coq/lexxx320-PersonalProjects", "path": "github-repos/coq/lexxx320-PersonalProjects/PersonalProjects-bc83fb250467b013d9db9fe535ff7bd314632d4c/newest/multiset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.68307000181946}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Essentials.HoTT_Facts.\nRequire Import Category.Main.\nRequire Import Basic_Cons.Product.\nRequire Import Coq_Cats.Type_Cat.Type_Cat.\n\nLocal Obligation Tactic := basic_simpl; auto 2.\n\nDefinition SumType (A B : Type_Cat) : hSet.\nProof.\n  refine\n    (\n      @BuildTruncType 0 (A + B)%type _\n    ).\nDefined.\n  \n(** The sum of types in coq is the categorical notion of sum in category of types. *)\nProgram Definition sum_Sum (A B : Type_Cat) : @Sum Type_Cat A B.\nProof.\n  refine\n    (\n      @Build_Product\n        (Type_Cat^op)\n        A\n        B\n        (SumType A B)\n        inl\n        inr\n        (\n          fun p'\n              r1\n              r2\n              x =>\n            match x return p' with\n            | inl a => r1 a\n            | inr b => r2 b\n            end\n        )\n        _\n        _\n        _\n    ); auto.\n  intros p' r1 r2 f g H1 H2 H3 H4.\n  rewrite <- H3 in H1.\n  rewrite <- H4 in H2.\n  clear H3 H4.\n  extensionality x.\n  destruct x;\n    match goal with\n        [|- f (?m ?y) = g (?m ?y)] =>\n        apply (@equal_f _ _ (fun x => f (m x)) (fun x => g (m x)))\n    end; auto.\nDefined.\n\n(* sum_Sum defined *)\n\nProgram Instance Type_Cat_Has_Sums : Has_Sums Type_Cat := sum_Sum.\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/Coq_Cats/Type_Cat/Sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6829342576356539}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (z : natural) (lf2 : natural)\n  : natural := plus lf1 Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj164_coqofml_6GH8Ww.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6829342495998603}}
{"text": "Require Import QArith Qround QvecArith PerceptronDef.\nRequire Import TerminationRefinement MCEBounds PerceptronSound.\n\nDefinition Qfloor_nat (q : Q) : nat := Z.to_nat (Qfloor q).\n\nLemma AB_limit : forall (A B C: Q),\n  0 < A -> 0 < B -> 0 < C -> C > B / A -> A * C *C > B * C.\nProof.\n  intros. unfold Qdiv in H2. apply (Qmult_lt_l _ _ A H) in H2.\n  rewrite (Qmult_comm B _) in H2. rewrite Qmult_assoc in H2.\n  rewrite Qmult_inv_r in H2. rewrite Qmult_1_l in H2.\n  apply (Qmult_lt_r _ _ C H1) in H2. unfold Qmult;\n  repeat rewrite Qred_correct. apply H2. unfold not. intros.\n  apply Qlt_not_le in H. apply H. rewrite H3. apply Qle_refl. Qed.\n\nLemma Qfloor_lt' : forall (x : Q),\n  x < 1 + inject_Z (Qfloor x).\nProof.\n  intros. assert (1 = inject_Z 1%Z). reflexivity. rewrite H.\n  unfold Qplus; rewrite Qred_correct.\n  rewrite <- inject_Z_plus. rewrite Zplus_comm. apply Qlt_floor. Qed.\n\nLemma Nat_Z_inj : forall (n : nat),\n  inject_nat n == inject_Z (Z.of_nat n).\nProof.\n  intros. induction n. reflexivity. simpl.\n  rewrite Zpos_P_of_succ_nat. rewrite <- Z.add_1_l.\n  rewrite inject_Z_plus. rewrite IHn. unfold Qplus.\n  rewrite Qred_correct. reflexivity. Qed.\n\nLemma Z_pos_nat_inj : forall (x : Z),\n  (0 <= x -> Z.of_nat (Z.to_nat x) = x)%Z.\nProof.\n  intros. induction x. reflexivity. simpl.\n  apply positive_nat_Z. assert (H3 := Zlt_neg_0 p). omega. Qed.\n\n (****************************************************************************************\n    Show that MCEBounds -> MCE reaches a fixed point.\n  ****************************************************************************************)\nLemma linearly_separable_MCE : forall {n : nat} (w0 : Qvec (S n)) (T : list ((Qvec n)*bool)),\n  linearly_separable T -> exists (E0 : nat),\n  MCE E0 T w0 = MCE (S E0) T w0.\nProof.\n  intros. apply (linearly_separable_bound T w0) in H. simpl in H.  destruct H as [A [B [C H]]].\n  exists (S (Qfloor_nat (C / A))).\n  assert (H0 := (H (S (Qfloor_nat (C / A))))).\n  assert (H1 := (MCE_progress (S (Qfloor_nat (C / A))) w0 T)).\n  inversion H1.\n  {\n    destruct H0 as [HA [HB [HC HAC]]].\n    unfold MCE in H2. inversion H2.\n    { fold (MCE (S (Qfloor_nat (C / A))) T w0) in H3.\n      fold (MCE (S (Qfloor_nat (C / A))) T w0) in H2. rewrite <- H3 in HAC.\n      assert (0 < inject_nat (S (Qfloor_nat (C / A)))). simpl.\n      unfold Qplus; rewrite Qred_correct.\n      apply (Qplus_lt_le_compat 0 _ 0 _). reflexivity. apply Qnat_le_0.\n      assert (C / A < inject_nat (S (Qfloor_nat (C / A)))). simpl.\n      rewrite Nat_Z_inj. unfold Qfloor_nat. rewrite Z_pos_nat_inj.\n      apply Qfloor_lt'. assert (0%Z = Qfloor 0). reflexivity.\n      rewrite H4. apply Qfloor_resp_le. apply Qlt_le_weak.\n      unfold Qdiv. rewrite <- (Qmult_0_l (/ A)). apply Qmult_lt_r.\n      apply Qinv_lt_0_compat. apply HA. apply HC.\n      assert (HCA := (AB_limit A C (inject_nat (S (Qfloor_nat (C / A)))) HA HC H0 H4)).\n      clear - HAC HCA. apply Qlt_not_le in HCA. exfalso. apply HCA.\n      destruct HAC as [HleA HleC]. apply (Qle_trans _ _ _ HleA HleC).\n    }\n    fold (MCE (S (Qfloor_nat (C / A))) T w0) in H2. fold (MCE (S (Qfloor_nat (C / A))) T w0) in H0.\n    rewrite <- H0 in HAC. assert (HCA := (AB_limit A C (inject_nat (S m)) HA HC)). exfalso.\n    apply Qlt_not_le in HCA. apply HCA. destruct HAC as [HleA HleC]. apply (Qle_trans _ _ _ HleA HleC).\n    simpl. unfold Qplus; rewrite Qred_correct.\n    apply (Qplus_lt_le_compat 0 _ 0 _). reflexivity. apply Qnat_le_0.\n    assert (C / A < inject_nat (S (Qfloor_nat (C / A)))).\n    simpl. rewrite Nat_Z_inj. unfold Qfloor_nat. rewrite Z_pos_nat_inj.\n    apply Qfloor_lt'. assert (0%Z = Qfloor 0). reflexivity.\n    rewrite H4. apply Qfloor_resp_le. apply Qlt_le_weak.\n    unfold Qdiv. rewrite <- (Qmult_0_l (/ A)). apply Qmult_lt_r.\n    apply Qinv_lt_0_compat. apply HA. apply HC. apply (Qlt_trans _ _ _ H4).\n    apply Qnat_lt. apply le_lt_n_Sm. apply H3.\n  } apply H2. Qed.\n\n (****************************************************************************************\n    Show that perceptron_MCE reaches a fixed point. (MCE fixed point + termination refinement)\n  ****************************************************************************************)\nTheorem linearly_separable_perceptron_MCE : forall {n : nat} (w0 : Qvec (S n)) (T : (list ((Qvec n)*bool))),\n  linearly_separable T ->\n  exists (E0 : nat) M (w : (Qvec (S n))), forall E, (E >= E0)%nat -> perceptron_MCE E T w0 = Some (M, w).\nProof.\n  intros. apply linearly_separable_MCE with w0 T in H. destruct H as [E0 H].\n  exists (S E0). exists (MCE E0 T w0). exists (Qvec_sum_class w0 (MCE E0 T w0)). intros E.\n  intros H1. apply MCE_eq_perceptron_MCE in H. apply perceptron_MCE_done with (S E0). omega. apply H. Qed.\n\n (****************************************************************************************\n  (Show that perceptron reaches a fixed point (converges)\n    perceptron_MCE reaches a fixed point + termination refinement\n ****************************************************************************************)\nTheorem linearly_separable_perceptron : forall {n : nat} (w0 : Qvec (S n)) (T : (list ((Qvec n)*bool))),\n  linearly_separable T <->\n  exists (E0 : nat) (w : (Qvec (S n))), forall E, (E >= E0)%nat -> perceptron E T w0 = Some w.\nProof.\n  split; intros. apply linearly_separable_perceptron_MCE with w0 T in H.\n  destruct H as [E0 [M [w H]]]. exists E0. exists w. intros. apply H in H0.\n  apply perceptron_MCE_perceptron. exists M. auto.\n  destruct H as [E0 [w H]].\n  apply (perceptron_linearly_separable (S E0) w0 w).\n  apply H. auto. Qed.\n\n(*******************************************************************************************\n  Show that Average Perceptron reaches a fixed point (converges)\n    linearly_separable_perceptron + termination refinement\n *******************************************************************************************)\nTheorem linearly_separable_average_perceptron : forall {n : nat} (w0 : Qvec (S n)) (T : (list ((Qvec n)*bool))),\n    linearly_separable T <->\n    exists (E0 : nat) (w : (Qvec (S n))), forall E, (E >= E0)%nat -> average_perceptron E T w0 = Some w.\nProof.\n  split; intros. apply linearly_separable_perceptron with w0 T in H.\n  destruct H as [E0 [w H]].\n  assert (forall E, (E >= E0)%nat -> exists w, average_perceptron E T w0 = Some w).\n  { intros. apply H in H0. apply perceptron_average_perceptron. exists w. auto. }\n  clear H. exists E0. assert (E0 >= E0)%nat. omega. apply H0 in H.\n  destruct H as [? H]. exists x. clear -H.\n  intros. eapply average_perceptron_done. apply H0. apply H.\n  destruct H as [E0 [w H]]. assert (E0 >= E0)%nat. omega.\n  apply H in H0. assert (exists w, perceptron E0 T w0 = Some w).\n  apply perceptron_average_perceptron. exists w. apply H0.\n  destruct H1 as [? H1]. apply (perceptron_linearly_separable E0 w0 x).\n  apply H1.\nQed.\n\nPrint Assumptions linearly_separable_perceptron.", "meta": {"author": "tm507211", "repo": "CoqPerceptron", "sha": "ce154b357c0cd6f072159d26c9b6c88f28c6af5b", "save_path": "github-repos/coq/tm507211-CoqPerceptron", "path": "github-repos/coq/tm507211-CoqPerceptron/CoqPerceptron-ce154b357c0cd6f072159d26c9b6c88f28c6af5b/PerceptronConvergence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6829342468254817}}
{"text": "(******************************************************************************)\n(** Imports **)\n\n(* Disable notation conflict warnings *)\nSet Warnings \"-notation-overridden\".\n\n(* SSReflect *)\nFrom Coq Require Import ssreflect ssrbool ssrfun.\nFrom mathcomp Require Import ssrnat seq eqtype.\nSet Bullet Behavior \"Strict Subproofs\".\n\n(* Sortedness *)\nRequire Import Coq.Sorting.Sorted Coq.Sorting.Permutation.\n\n(* Basic Haskell libraries *)\nRequire Import GHC.Base      Proofs.GHC.Base.\nRequire Import Data.Foldable Proofs.Data.Foldable.\nRequire Import Data.OldList  Proofs.Data.OldList.\n\n(* Working with Haskell *)\nRequire Import SortSorted.\nRequire Import OrdTactic.\nRequire Import HSUtil.\n\n(******************************************************************************)\n(** Name dismabiguation -- copied from HSUtil **)\n\nNotation list    := Coq.Init.Datatypes.list.\nNotation seq     := Coq.Lists.List.seq.\nNotation reflect := ssrbool.reflect.\n\n(******************************************************************************)\n(** Basic facts about StronglySorted **)\n\nTheorem StronglySorted_R_ext' {A} (R1 R2 : A -> A -> Prop) (xs : list A) :\n  (forall a b, R1 a b <-> R2 a b) ->\n  StronglySorted R1 xs -> StronglySorted R2 xs.\nProof.\n  move=> R12_iff; elim: xs => [|x xs IH] SS1; first by constructor.\n  inversion SS1 as [|x' xs' SS1' All1]; subst x' xs'.\n  constructor; first by apply IH.\n  eapply Forall_impl; last exact All1.\n  apply R12_iff.\nQed.\n\nCorollary StronglySorted_R_ext {A} (R1 R2 : A -> A -> Prop) (xs : list A) :\n  (forall a b, R1 a b <-> R2 a b) ->\n  StronglySorted R1 xs <-> StronglySorted R2 xs.\nProof. by split; apply StronglySorted_R_ext'; last symmetry. Qed.\n\nTheorem StronglySorted_snoc {A} (R : A -> A -> Prop) (x : A) (xs : list A) :\n  StronglySorted R xs -> Forall (R^~ x) xs -> StronglySorted R (xs ++ [:: x]).\nProof.\n  elim: xs => [|x' xs IH] /= SS' AllRev'; first by constructor.\n  inversion SS'     as [|x'' xs' SS   All];    subst x'' xs'.\n  inversion AllRev' as [|x'' xs' Rx'x AllRev]; subst x'' xs'.\n  constructor.\n  - by apply IH.\n  - move: All AllRev; rewrite !Forall_forall => /= All AllRev a.\n    rewrite in_app_iff => -[IN | [? | //]]; last subst a=> //.\n    by apply All.\nQed.\n\nTheorem StronglySorted_rev' {A} (R : A -> A -> Prop) (xs : list A) :\n  StronglySorted R xs -> StronglySorted (fun a b => R b a) (rev xs).\nProof.\n  elim: xs => [|x xs IH] /= SS'; first by constructor.\n  inversion SS' as [|x' xs' SS All]; subst x' xs'.\n  move: (IH SS) => IH'.\n  apply StronglySorted_snoc; first by apply IH.\n  move: All; rewrite !Forall_forall => All a; rewrite -in_rev; apply All.\nQed.\n\nCorollary StronglySorted_rev {A} (R : A -> A -> Prop) (xs : list A) :\n  StronglySorted R xs <-> StronglySorted (fun a b => R b a) (rev xs).\nProof.\n  split; first apply StronglySorted_rev'.\n  rewrite -{2}(rev_involutive xs)=> SS.\n  by eapply StronglySorted_rev', StronglySorted_R_ext; last exact SS.\nQed.\n\nTheorem StronglySorted_app {A} (R : A -> A -> Prop) (xs ys : list A) :\n  StronglySorted R (xs ++ ys) -> StronglySorted R xs /\\ StronglySorted R ys.\nProof.\n  elim: xs => [|x xs IH] //= SS; first by auto using StronglySorted.\n  inversion SS as [|x' rest SS' All E1]; subst x' rest.\n  move: (IH SS') => [SS_xs SS_ys]; split=> //.\n  constructor=> //.\n  apply/Forall_forall=> a In_a; move: All => /Forall_forall/(_ a).\n  by rewrite in_app_iff; apply; left.\nQed.\n\n(******************************************************************************)\n(** StronglySorted and NoDup (and similar) **)\n\nTheorem StronglySorted_irrefl_not_in {A} (R : A -> A -> Prop) (x : A) (xs : list A) :\n  (forall a, ~ R a a) ->\n  StronglySorted R (x :: xs) ->\n  ~ In x xs.\nProof.\n  move=> irrefl_R SS_xxs; inversion SS_xxs as [|x' xs' SS_xs R_x_xs E1]; subst x' xs'; clear SS_xxs.\n  elim: xs SS_xs R_x_xs => [|x' xs IH] SS_xs R_x_xs //=.\n  move=> [? | In_x_xs]; first subst x'.\n  - inversion_clear R_x_xs; eapply irrefl_R; eassumption.\n  - apply IH=> //.\n    + by inversion SS_xs.\n    + by inversion R_x_xs.\nQed.\n\nTheorem StronglySorted_irrefl_NoDup {A} (R : A -> A -> Prop) (xs : list A) :\n  (forall a, ~ R a a) ->\n  StronglySorted R xs ->\n  NoDup xs.\nProof.\n  move=> irrefl_R.\n  elim: xs => [|x xs IH] SS_xxs //=; constructor.\n  - eapply StronglySorted_irrefl_not_in; eassumption.\n  - by apply IH; inversion SS_xxs.\nQed.\n\nTheorem StronglySorted_eq_In {A} (R : A -> A -> Prop) (xs ys : list A) :\n  (forall a, ~ R a a) ->\n  (forall a b c, R a b -> R b c -> R a c) ->\n  StronglySorted R xs ->\n  StronglySorted R ys ->\n  (xs = ys) <-> (forall a, In a xs <-> In a ys).\nProof.\n  move=> irrefl_R trans_R SS_xs; elim: SS_xs ys =>  {xs} [|x xs SS_xs IH_xs R_xs] /= ys SS_ys.\n  all: case: ys SS_ys => [|y ys] //= SS_ys.\n  all: split; try discriminate.\n  all: try by (move=> /(_ x) || move=> /(_ y)); simpl; tauto.\n  - by inversion 1.\n  - move=> ext_eq.\n    have NIn_x_xs: ~ In x xs by eapply StronglySorted_irrefl_not_in; eauto using StronglySorted.\n    have NIn_y_ys: ~ In y ys by eapply StronglySorted_irrefl_not_in.\n    have E: x = y; last subst y. {\n      inversion SS_ys; subst.\n      move: (ext_eq x) => [fwd_x bwd_x].\n      move: (ext_eq y) => [fwd_y bwd_y].\n      case: (fwd_x (or_introl erefl)) => [// | In_x_ys].\n      case: (bwd_y (or_introl erefl)) => [// | In_y_xs].\n      have Rxy: (R x y) by eapply Forall_forall; eassumption.\n      have Ryx: (R y x) by eapply Forall_forall; eassumption.\n      by move: (trans_R _ _ _ Rxy Ryx) => /irrefl_R.\n    }\n    f_equal.\n    apply IH_xs; first by inversion SS_ys.\n    move=> a; move: (ext_eq a) => [fwd bwd].\n    split=> [a_xs | a_ys].\n    + have x_a_disj: (x <> a) by contradict NIn_x_xs; subst.\n      by move: (fwd (or_intror a_xs))=> [].\n    + have x_a_disj: (x <> a) by contradict NIn_y_ys; subst.\n      by move: (bwd (or_intror a_ys))=> [].\nQed.\n\nTheorem StronglySorted_NoDup {A} (R R' : A -> A -> Prop) :\n  (forall x,       R  x x) ->\n  (forall x,     ~ R' x x) ->\n\n  (forall x y z, R  x y -> R  y z -> R  x z) ->\n  (forall x y z, R' x y -> R' y z -> R' x z) ->\n\n  (forall x y, R  x y <-> (x =  y \\/ R' x y)) ->\n  (forall x y, R' x y <-> (x <> y /\\ R  x y)) ->\n\n  forall xs,\n    StronglySorted R xs -> NoDup xs -> StronglySorted R' xs.\nProof.\n  move=> R_refl R'_irrefl R_trans R'_trans R_def R'_def.\n  elim=> [|x xs IH] //= Sorted_xxs NoDup_xxs; first by constructor.\n  inversion Sorted_xxs as [|x' xs' Sorted_xs R_x_xs E1];  subst x' xs'; clear Sorted_xxs.\n  inversion NoDup_xxs  as [|x' xs' NIn_x_xs NoDup_xs E1]; subst x' xs'; clear NoDup_xxs.\n  constructor; first by apply IH.\n  clear IH Sorted_xs NoDup_xs.\n  elim: xs R_x_xs NIn_x_xs => [|x' xs IH] //= R_x_x'xs NIn_x_x'xs.\n  inversion R_x_x'xs as [|x'' xs' R_x_x' R_x_xs E1]; subst x'' xs'; clear R_x_x'xs.\n  constructor.\n  - apply R'_def; split=> //.\n    by contradict NIn_x_x'xs; subst; left.\n  - apply IH=> //=.\n    by contradict NIn_x_x'xs; right.\nQed.\n\n(******************************************************************************)\n(** Previous StronglySorted theorems with specific relations **)\n\nCorollary StronglySorted_Zlt_eq_In (xs ys : list Int) :\n  StronglySorted Z.lt xs ->\n  StronglySorted Z.lt ys ->\n  (xs = ys) <-> (forall a, In a xs <-> In a ys).\nProof. apply StronglySorted_eq_In; [exact Z.lt_irrefl | exact Z.lt_trans]. Qed.\n\nCorollary StronglySorted_Nlt_eq_In (xs ys : list N) :\n  StronglySorted N.lt xs ->\n  StronglySorted N.lt ys ->\n  (xs = ys) <-> (forall a, In a xs <-> In a ys).\nProof. apply StronglySorted_eq_In; [exact N.lt_irrefl | exact N.lt_trans]. Qed.\n\n\nCorollary StronglySorted_Ord_eq_In {A} `{OrdLaws A} (xs ys : list A) :\n  StronglySorted _<_ xs ->\n  StronglySorted _<_ ys ->\n  (xs = ys) <-> (forall a, In a xs <-> In a ys).\nProof.\n  apply StronglySorted_eq_In; order A.\nQed.\n\nCorollary StronglySorted_NoDup_Ord {A} `{OrdLaws A} `{!EqExact A} (xs : list A) :\n  StronglySorted _<=_ xs ->\n  NoDup xs ->\n  StronglySorted _<_ xs.\nProof.\n  apply StronglySorted_NoDup; try order A.\n  - move=> x y; split=> [LExy | [-> | LTxy]]; try order A.\n    move: LExy. destruct (compare x y) eqn:Cxy; try order A.\n    move: Cxy => /Ord_compare_Eq/Eq_eq; order A.\n  - move=> x y; split=> [LTxy | [Nxy LExy]]; try order A.\n    rewrite Ord_lt_le; apply/negP; contradict Nxy.\n    by apply/Eq_eq; order A.\nQed.\n\n(******************************************************************************)\n(** Basic facts about NoDup **)\n\nTheorem NoDup_reorder {A} (pre : list A) (x : A) (post : list A) :\n  NoDup (pre ++ x :: post) <-> NoDup (x :: (pre ++ post)).\nProof.\n  elim: pre => [|p pre IH] //=; split=> [ND_mid | ND_fst].\n  - inversion ND_mid as [|p' rest NIn_p ND_mid' E1]; subst p' rest.\n    move/IH in ND_mid'; inversion ND_mid' as [|x' rest NIn_x ND_mid'' E1]; subst x' rest.\n    constructor=> //.\n    + move=> [? | //]; subst p.\n      apply NIn_p; rewrite in_app_iff /=; auto.\n    + constructor=> //.\n      contradict NIn_p; move: NIn_p.\n      rewrite !in_app_iff /=; tauto.\n  - inversion ND_fst  as [|x' rest NIn_x ND_fst'  E1]; subst x' rest.\n    inversion ND_fst' as [|p' rest NIn_p ND_fst'' E1]; subst p' rest.\n    constructor=> //.\n    + contradict NIn_p; move: NIn_p.\n      rewrite !in_app_iff /= => -[? | [? | ?]]; try tauto; subst p.\n      by exfalso; apply NIn_x; left.\n    + apply IH; constructor=> //.\n      by contradict NIn_x; right.\nQed.\n\n(******************************************************************************)\n(** Theorems about sort and nub **)\n\nTheorem sortN {A} `{OrdLaws A} :\n  sort [::] = [::].\nProof. done. Qed.\n\nTheorem sort1 {A} `{OrdLaws A} `{!EqExact A} (x : A) :\n  sort [:: x] = [:: x].\nProof. done. Qed.\n\nTheorem sort_StronglySorted {A} `{OrdLaws A} (xs : list A) :\n  StronglySorted _<=_ (sort xs).\nProof.\n  eapply Sorted_StronglySorted, sort_sorted; try typeclasses eauto.\n  order A.\nQed.\n\nTheorem sort_elem {A} `{Ord A} (xs : list A) :\n  forall x, elem x (sort xs) = elem x xs.\nProof. apply elem_Permutation, sort_permutation. Qed.\n\nTheorem sort_In {A} `{Ord A} (xs : list A) :\n  forall x, In x (sort xs) <-> In x xs.\nProof. move=> ?; apply (Permutation_in' erefl), sort_permutation. Qed.\n\nTheorem sort_NoDup {A} `{OrdLaws A} `{!EqExact A} (xs : list A) :\n  NoDup xs <-> NoDup (sort xs).\nProof. apply Permutation_NoDup', Permutation_sym, sort_permutation. Qed.\n\nTheorem nub_NoDup {A} `{EqExact A} (xs : list A) : NoDup (nub xs).\nProof.\n  rewrite /nub /nubBy.\n  have: NoDup ([::] : list A) by constructor.\n  move: {1 3}[::].\n  elim: xs => [|x xs IH] /= acc acc_uniq; first by constructor.\n  case MEM: (elem_by _==_ x acc).\n  + by apply IH.\n  + constructor.\n    * clear IH.\n      have: In x (x :: acc) by constructor.\n      move: (x :: acc); clear acc acc_uniq MEM.\n      elim: xs => [|x' xs IH] acc IN //=.\n      destruct (x == x') eqn:EQ => //=.\n      -- move/Eq_eq in EQ; subst x'.\n         by move: (IN) => /elem_byP ->; apply IH.\n      -- case MEM': (elem_by _==_ x' acc) => //=; first by apply IH.\n         move=> [? | IN']; first by subst x'; contradict EQ; rewrite Eq_refl.\n         eapply IH; last apply IN'.\n         by right.\n    * eapply IH; constructor=> //.\n      by apply/elem_byP; rewrite MEM.\nQed.\n\nCorollary StronglySorted_sort_nub {A} `{OrdLaws A} `{!EqExact A} (xs : list A) :\n  StronglySorted _<_ (sort (nub xs)).\nProof.\n  apply StronglySorted_NoDup_Ord; first by apply sort_StronglySorted.\n  have decA: forall x y : A, {x = y} + {x <> y} by move=> x y; case: (EqExact_cases x y); tauto.\n  rewrite -sort_NoDup; apply nub_NoDup.\nQed.\n\nCorollary StronglySorted_sort_nub_Zlt (xs : list Int) :\n  StronglySorted Z.lt (sort (nub xs)).\nProof.\n  eapply StronglySorted_R_ext; last by apply StronglySorted_sort_nub.\n  by unfold \"<\", Ord_Integer___ => /= a b; rewrite -Z.ltb_lt.\nQed.\n\nCorollary StronglySorted_sort_nub_Nlt (xs : list N) :\n  StronglySorted N.lt (sort (nub xs)).\nProof.\n  eapply StronglySorted_R_ext; last by apply StronglySorted_sort_nub.\n  by unfold \"<\", Ord_Char___ => /= a b; rewrite -N.ltb_lt.\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/SortedUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.6828550078391282}}
{"text": "(**\n多数決関数とfull adder\n========================\n\n@suharahiromichi\n\n2020/04/30\n *)\n\nFrom mathcomp Require Import all_ssreflect.\nRequire Import ssr_omega.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n(* Set Print All. *)\n\nSection Majority.\n\n  Definition maj3 (b c d : bool) : bool := if (b + c + d <= 1) then false else true.\n\n  Definition maj3_0 (a b c : bool) : bool :=\n    a && b && ~~c || ~~a && b && c || a && ~~b && c || a && b && c.\n  Definition maj3_1 (a b c : bool) : bool := a && b || b && c || c && a.\n  Definition maj3_2 (a b c : bool) : bool := a * b + b * c + c * a != 0.\n  \n  Goal forall (a b c : bool), maj3_0 a b c = maj3_1 a b c.\n  Proof.\n    move=> a b c.\n    rewrite /maj3_0 /maj3_1.\n    \n    rewrite [_ || a && b && c]orbC !orbA.   (* 先頭に移動する。 *)\n    rewrite -[a && b && c]Bool.orb_diag.    (* 項を複製する。 *)\n    rewrite -{1}[a && b && c]Bool.orb_diag. (* 項を複製する。 *)\n    rewrite [_ || a && ~~b && c]orbC !orbA. (* 先頭に移動する。 *)\n    have -> : a && ~~b && c || a && b && c = a && c.\n      (* 一旦右結合にして、~~bとbを末尾にして、左結合に戻す。 *)\n      by rewrite -!andbA [~~b && _]andbC [b && _]andbC ?andbA\n         -andb_orr orbC orbN andbT andbC.\n    rewrite [a && c]andbC.\n    \n    rewrite [_ || a && b && c]orbC !orbA.   (* 先頭に移動する。 *)\n    rewrite [_ || ~~a && b && c]orbC !orbA. (* 先頭に移動する。 *)\n    have -> : ~~ a && b && c || a && b && c = b && c.\n      (* 一旦右結合にして、~~aとaを末尾にして、左結合に戻す。 *)\n      by rewrite -!andbA [~~a && _]andbC [a && _]andbC ?andbA\n         -andb_orr orbC orbN andbT andbC.\n      \n    rewrite [_ || a && b && c]orbC !orbA.   (* 先頭に移動する。 *)\n    rewrite [_ || a && b && ~~c]orbC !orbA. (* 先頭に移動する。 *)\n    have -> : a && b && ~~c || a && b && c = a && b\n      (* すでに、~~cとcは末尾にある。 *)\n      by rewrite -andb_orr orbC orbN andbT andbC.                                             done.\n  Qed.\n\n  Lemma test2 (a b :nat) : (a + b != 0) = (a != 0) || (b != 0).\n  Proof.\n      by elim: a; elim: b.\n  Qed.\n  \n  Lemma test a : (nat_of_bool a != 0) = a.\n  Proof.\n    by case: a.\n  Qed.\n  \n  Goal forall (a b c : bool), maj3_1 a b c = maj3_2 a b c.\n  Proof.\n    move=> a b c.\n    rewrite /maj3_1 /maj3_2.\n    rewrite !mulnb.\n    rewrite 2!test2.\n    rewrite 3!test.\n    done.\n  Qed.\n  \n  Goal forall (a b c : bool), maj3 a b c = maj3_1 a b c.\n  Proof.\n      by case; case; case.\n  Qed.\n\nEnd Majority.\n\nSection Median.\n  \n  (* 5回比較するので、効率悪い *)\n  Definition median (m n p : nat) := maxn (maxn (minn m n) (minn n p)) (minn p m).\n  \n  (* 展開したバブルソート *)\n  Definition median' (n1 n2 n3 : nat) :=\n    let (n1', n2') := if n1 < n2 then (n1, n2) else (n2, n1) in\n    let (n2'', n3') := if n2' < n3 then (n2', n3) else (n3, n2') in\n    let (n1'', n2''') := if (n1' < n2'') then (n1', n2'') else (n2'', n1') in n2'''.\n  \n  (* 上記をswapなしにしたもの *)\n  Definition median'' (m n p : nat) :=\n    if m < n then\n      if n < p then n else (if m < p then p else m)\n    else\n      if m < p then m else (if n < p then p else n).\n  \n  (* bool で証明する。 *)\n  \n  Goal forall (a b c : bool), median a b c = maj3 a b c.\n  Proof.\n      by case; case; case.\n  Qed.\n\n  Goal forall (a b c : bool), median a b c = median' a b c.\n  Proof.\n    rewrite /median /median'.\n      by case; case; case.\n  Qed.\n  \n  Goal forall (a b c : bool), median a b c = median'' a b c.\n  Proof.\n    rewrite /median /median'.\n      by case; case; case.\n  Qed.\n  \n  (* nat で証明する。 *)\n  \n  (* ゴールと前提にある if式の条件で場合分けする。 *)\n  Ltac if_condition' :=\n    intros;\n    repeat match goal with\n           | [ |- context[if ?b then _ else _] ] =>\n             let H' := fresh in destruct b eqn: H'\n           | [ H : context[if ?b then _ else _] |- _ ] =>\n             let H' := fresh in destruct b eqn: H'\n           | _ => idtac\n           end.\n  \n  Ltac if_condition :=\n    if_condition'; try done; ssromega.\n  \n  Goal forall (m n p : nat), median' m n p = median'' m n p.\n  Proof.\n    move=> m n p.\n    rewrite /median' /median''.\n    if_condition.\n  Qed.\n  \n  Goal forall (m n p : nat), median m n p = median'' m n p.\n  Proof.\n    move=> m n p.\n    rewrite /median /median'' /maxn /minn.\n    if_condition.\n  Qed.\n  \n  Goal forall (m n p : nat), median m n p = median' m n p.\n  Proof.\n    move=> m n p.\n    rewrite /median /median' /maxn /minn.\n    if_condition.\n  Qed.\n  \n  (* MathComp 風に rewrite で簡単にする。遅い。 *)\n  \n  Goal forall (m n p : nat), median' m n p = median'' m n p.\n  Proof.\n    move=> m n p.\n    rewrite /median' /median''.\n    case: ifP => Hmn; case: ifP => Hnp; case: ifP => Hpm; ssromega.\n  Qed.\n  \n  Goal forall (m n p : nat), median m n p = median'' m n p.\n  Proof.\n    move=> m n p.\n    rewrite /median /median'' /maxn /minn.\n    case Hmn : (m < n); case Hnp : (n < p); case Hpm : (p < m);\n      case Hmp : (m < p); case Hnm : (n < m);\n        case Hpp : (p < p); case Hnn : (n < n); case Hmm : (m < m);\n        rewrite ?Hmn ?Hnp ?Hpm ?Hmp ?Hnm ?Hpp ?Hnn; ssromega.\n  Qed.\n  \n  Goal forall (m n p : nat), median m n p = median' m n p.\n  Proof.\n    move=> m n p.\n    rewrite /median /median' /maxn /minn.\n    case Hmn : (m < n); case Hnp : (n < p); case Hpm : (p < m);\n      case Hmp : (m < p); case Hnm : (n < m);\n        case Hpp : (p < p); case Hnn : (n < n); case Hmm : (m < m);\n        rewrite ?Hmn ?Hnp ?Hpm ?Hmp ?Hnm ?Hpp ?Hnn; ssromega.\n  Qed.\n  \nEnd Median.\n\n\nSection FullAdder.\n\n  (* majority3 *)\n  Definition maj (a b c : bool) : bool := (2 <= a + b + c).\n  \n  (* parity3 *)\n  Definition par (a b c : bool) : bool := odd (a + b + c).\n\n  \n  Compute maj false false false.             (* false *)\n  Compute maj true false false.              (* false *)\n  Compute maj true false true.               (* true *)\n  Compute maj true true true.                (* true *)\n\n  Compute par false false false.             (* false *)\n  Compute par true false false.              (* true *)\n  Compute par true false true.               (* false *)\n  Compute par true true true.                (* true *)  \n\n  Goal forall (a b c : bool),\n      a + b + c = 2 * maj a b c + par a b c.\n  Proof.\n      by case; case; case.\n  Qed.\n\nEnd FullAdder.\n\n\n(* おまけ *)\n\nGoal forall (a b c : bool), maj3 a b c = maj a b c.\nProof.\n    by case; case; 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/math/ssr_median.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.6828550078391282}}
{"text": "Require Import ZArith.\nRequire Import NAux.\nRequire Import NPolS.\nRequire Import PolSBase.\nRequire Import PolFBase.\nRequire Import PolAux.\nRequire Import PolAuxList.\nRequire Import NSignTac.\n\n\nDefinition Zfactor := \n  factor Z Zplus Zmult Z.opp 0%Z 1%Z is_Z1 is_Z0 is_Zpos is_Zdiv Z.div Zgcd.\n\nDefinition Zfactor_minus := \n  factor_sub Z Zplus Zmult Z.opp 0%Z 1%Z is_Z1 is_Z0 is_Zpos is_Zdiv Z.div Zgcd.\n\n\nDefinition Zget_delta := \n get_delta Z Zplus Zmult Z.opp 0%Z 1%Z is_Z1 is_Z0 is_Zpos is_Zdiv Z.div Zgcd.\n\n\nLtac\nNfactor_term term1 term2 :=\nlet term := constr:(Nminus term1 term2) in\nlet rfv := FV NCst Nplus Nmult Nminus Nopp term (@nil N) in\nlet fv := Trev rfv in\nlet expr1 := mkPolexpr Z NCst Nplus Nmult Nminus Nopp term1 fv in\nlet expr2 := mkPolexpr Z NCst Nplus Nmult Nminus Nopp term2 fv in\nlet re := eval vm_compute in (Zfactor_minus (PEsub expr1 expr2)) in\nlet factor := match re with (PEmul ?X1 _) => X1 end in\nlet expr3 := match re with (PEmul _ (PEsub ?X1 _)) => X1 end in\nlet expr4 := match re with (PEmul _ (PEsub _ ?X1 )) => X1 end in\nlet\n re1' :=\n  eval\n     unfold\n      Nconvert_back, convert_back,  pos_nth,  jump, \n         hd,  tl in (Nconvert_back (PEmul factor expr3) fv) in\nlet re1'' := eval lazy beta in re1' in\nlet re1''' := clean_zabs_N re1'' in\nlet\n re2' :=\n  eval\n     unfold\n      Nconvert_back, convert_back,  pos_nth,  jump, \n         hd,  tl in (Nconvert_back (PEmul factor expr4) fv) in\nlet re2'' := eval lazy beta in re2' in \nlet re2''' := clean_zabs_N re2'' in\nreplace2_tac term1 term2 re1''' re2'''; [idtac| ring | ring].\n\n\nLtac Npolf :=\nprogress (\n(try \nmatch goal with\n| |- (?X1 = ?X2)%N =>  Nfactor_term X1 X2 \n| |- (?X1 <> ?X2)%N =>  Nfactor_term X1 X2 \n| |- N.lt ?X1 ?X2 => Nfactor_term X1 X2\n| |- N.gt ?X1 ?X2 =>Nfactor_term X1 X2\n| |- N.le ?X1 ?X2 => Nfactor_term X1 X2\n| |- N.ge ?X1 ?X2 =>Nfactor_term X1 X2\n| _ => fail end)); try (Nsign_tac); try repeat (rewrite Nmult_1_l || rewrite Nmult_1_r).\n\n\nLtac hyp_Npolf H := \nprogress (\ngeneralize H; \n(try \nmatch type of H with\n  (?X1 = ?X2)%N =>  Nfactor_term X1 X2 \n| (?X1 <> ?X2)%N =>  Nfactor_term X1 X2 \n| N.lt ?X1 ?X2 => Nfactor_term X1 X2\n| N.gt ?X1 ?X2 =>Nfactor_term X1 X2\n| N.le ?X1 ?X2 => Nfactor_term X1 X2 \n| N.ge ?X1 ?X2 =>Nfactor_term X1 X2\n| _ => fail end)); clear H; intros H; try hyp_Nsign_tac H; try repeat rewrite Nmult_1_l in H.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/PolTac/NPolF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443463, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6828325216701986}}
{"text": "Require Export Ltree  building  graft.\n\nSet Implicit Arguments.\n\n(*  having some infinite branch *)\n\nCoInductive SomeInf (A:Type):(LTree A)->Prop :=\n   InfLeft : forall (a:A)(t1 t2:LTree A),\n                                    SomeInf t1 ->\n                                    SomeInf (LBin a t1 t2)\n|  InfRight : forall (a:A)(t1 t2:LTree A),\n                                     SomeInf t2 ->\n                                     SomeInf (LBin a t1 t2).\n\n(*  every branch is infinite *)\nCoInductive EveryInf (A:Type) :(LTree A)->Prop :=\n  InfI : forall (a:A) (t1 t2: LTree A),\n                                EveryInf t1 ->\n                                EveryInf t2 ->\n                                EveryInf (LBin a t1 t2).\n\n\n(* having some finite branch *)\n\nInductive SomeFin (A:Type) : (LTree A)->Prop :=\n  SomeFin_leaf : SomeFin LLeaf\n| SomeFin_left : forall (a:A) (t1 t2: LTree A),\n                                      SomeFin t1 ->\n                                      SomeFin (LBin a t1 t2)\n| SomeFin_right : forall (a:A) (t1 t2: LTree A),\n                                      SomeFin t2 ->\n                                      SomeFin (LBin a t1 t2).\n\n(* Every branch is finite (i.e. this is a finite tree) *)\n\n\nInductive Finite (A:Type) :(LTree A)->Prop :=\n  Finite_leaf : Finite LLeaf \n| Finite_bin : forall (a:A) (t1 t2: LTree A),\n                                      Finite t1 ->\n                                      Finite t2 ->\n                                      Finite (LBin a t1 t2).\n\nHint Resolve Finite_leaf Finite_bin SomeFin_leaf \nSomeFin_left  SomeFin_right.\n\n\n\n(* we prove that the tree built in module building has \n   only infinite branches *)\n\n(* technical unfolding lemma *)\n\nLemma Positive_tree_from_unfold : \n  forall p, Positive_Tree_from p =\n            LBin p (Positive_Tree_from (xO p)) (Positive_Tree_from (xI p)).\nProof.\n  intros p; now LTree_unfold (Positive_Tree_from p).\nQed.  \n\n\nLemma Positive_tree_from_inf : forall p, EveryInf  (Positive_Tree_from  p).\nProof.\n cofix.\n intro p; rewrite (Positive_tree_from_unfold p); split; auto.\nQed.\n\n(* a tree with an infinite branch *)\n\nCoFixpoint zigzag (b:bool): LTree bool :=\n    if b then (LBin b LLeaf (zigzag false))\n         else (LBin b (zigzag true) LLeaf ).\n           \n(*\n       true\n      /   \\\n    Leaf  false\n          /   \\\n       true    Leaf\n      /   \\\n    Leaf  false\n          /   \\\n       true    Leaf\n      /   \\\n    Leaf  false\n          /   \\\n       true    Leaf\n       ...\n*)\n\n\n\nLemma zigzag_unfold : forall b,\n                        zigzag b =\n                        if b\n                        then LBin b LLeaf (zigzag false)\n                        else LBin b (zigzag true) LLeaf.\nProof.\n intro b;LTree_unfold (zigzag b); cbn ; case b; simpl; auto.\nQed.\n\nLemma zigzag_inf : forall b, SomeInf (zigzag b).\nProof.\n  cofix H;  intro b;   rewrite (zigzag_unfold b);\n  case b; cbn; [right|left]; auto.\nQed.\n\n\n(* Some Finite/Infinite relationships *)\n\n\nLemma Finite_Not_SomeInf : forall (A:Type) (t: LTree A),\n                              Finite t -> ~ SomeInf t.\nProof.\n intros A t H; induction  H as [| a t1 t2 H1 IHt1 H2 IHt2].\n -  red; inversion 1.\n -  inversion 1; tauto. \nQed.\n\n\nLemma SomeInf_Not_Finite : forall (A:Type) (t: LTree A),\n                             SomeInf t -> ~ Finite t.\nProof.\n intros A t; generalize (Finite_Not_SomeInf (t:=t)); tauto.\nQed.\n\n\nLemma SomeFin_Not_EveryInf : forall (A:Type)(t: LTree A),\n                              SomeFin t -> ~ EveryInf t.\nProof.\n  intros A t Ht; induction Ht;   red; inversion 1; auto.\nQed.\n\nLemma Not_SomeFin_EveryInf : forall (A:Type)(t: LTree A),\n                              ~ SomeFin t -> EveryInf t.\nProof.\n intros A ; cofix H.\n intro t; destruct  t as [| a t1 t2].\n -  destruct 1; constructor.\n -  intro H0; split ; apply H; red; auto. \nQed.\n\n\nSection classic.\n  Hypothesis class:forall P:Prop, ~~P ->P.\n\n\n  Remark demorgan : forall P Q, ~(~P /\\ ~Q)-> P \\/ Q.\n  Proof.  \n    intros; apply class; tauto.\n  Qed.\n\n  Remark  Not_Finite_or : forall (A:Type) (a:A) (t1 t2: LTree A),\n                          ~ Finite (LBin a t1 t2) ->\n                          ~ Finite t1  \\/  ~Finite t2.\n  Proof.\n   intros A a t1 t2 H; apply demorgan;   intro; apply H.\n   right; apply class; tauto.\n  Qed.\n\n  Lemma Not_Finite_SomeInf : forall (A:Type)(t: LTree A),\n                               ~Finite t -> SomeInf t.\n  Proof.\n   intro A; cofix the_thm.\n   intro t ; destruct  t as [| a t1 t2].\n   - destruct 1; left.\n   - intro H; case (Not_Finite_or H); [left|right];\n      apply the_thm ; auto.\n   Qed.\n    \nEnd classic.\n\nTheorem graft_Finite_LLeaf : forall (A:Type) (t: LTree A),\n                             Finite t ->\n                             graft t LLeaf = t.\nProof.\n intros A t H; induction H as  [| a t1 t2 H1 IHt1 H2 IHt2].\n -  rewrite graft_unfold; auto.\n -  rewrite graft_unfold, IHt1,  IHt2; auto.\nQed.\n\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch13_co_inductive_types/SRC/Tree_Inf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6828323650575238}}
{"text": "Require Import PeanoNat.\nLocal Open Scope nat_scope.\n\n\nInductive ErrorNat :=\n|Error : ErrorNat\n|Num: nat -> ErrorNat.\n\nInductive Exp :=\n| number : ErrorNat -> Exp\n| plus : Exp -> Exp -> Exp\n| minus : Exp -> Exp -> Exp\n| mult : Exp -> Exp -> Exp\n| div : Exp -> Exp -> Exp.\n\nCoercion number : ErrorNat >-> Exp.\nCoercion Num : nat >-> ErrorNat.\n\nFixpoint plusErr (n1 : ErrorNat) (n2 : ErrorNat) : ErrorNat :=\n  match n1,n2 with\n  | Error, _ => Error\n  | _ , Error => Error\n  | Num n1',Num n2' => Num (n1' + n2')\n  end.\n\n\nFixpoint minusErr (n1 : ErrorNat) (n2 : ErrorNat) : ErrorNat :=\n  match n1,n2 with\n  | Error, _ => Error\n  | _ , Error => Error\n  | Num n1',Num n2' => if n1' <? n2' then Error else Num (n1' - n2') \n  end.\n\nFixpoint multiplyErr (n1 : ErrorNat) (n2 : ErrorNat) : ErrorNat :=\n  match n1,n2 with\n  | Error, _ => Error\n  | _ , Error => Error\n  | Num n1',Num n2' => Num (n1' * n2')\n  end.\n\nFixpoint divisionErr (n1 : ErrorNat) (n2 : ErrorNat) : ErrorNat :=\n  match n1,n2 with\n  | Error, _ => Error\n  | _ , Error => Error\n  | Num n1',Num n2' => if n2' =? 0 then Error else Num (n1' / n2') \n  end.\n\nFixpoint eval (exp: Exp) : ErrorNat :=\n  match exp with\n    |number n => n \n    |plus exp1 exp2 => plusErr (eval exp1)(eval exp2)\n    |minus exp1 exp2 => minusErr (eval exp1)(eval exp2)\n    |mult exp1 exp2 => multiplyErr(eval exp1)(eval exp2)\n    |div exp1 exp2 => divisionErr(eval exp1)(eval exp2)\n  end.\n\nCompute (eval(div 7 2)).\nCompute (eval (plus 12 3)).\nCompute (eval (mult 12 0)).\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/errornat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6828323588590214}}
{"text": "Set Implicit Arguments.\nRequire Import TLC.LibTactics.\nRequire Import TLC.LibIntTactics.\nRequire Import TLC.LibListZ.\n(* Load the CFML library, with time credits. *)\nRequire Import CFML.CFLibCredits.\n(* Load the big-O library. *)\nRequire Import Dominated.\nRequire Import UltimatelyGreater.\nRequire Import Monotonic.\nRequire Import elia.\nRequire Import PolTac.PolTac.\n(* Load the custom CFML tactics with support for big-Os *)\nRequire Import CFMLBigO.\n(* Load the examples CF definitions. *)\nRequire Import Composing_specs_ml.\n\nNotation \"'len'\" := LibListZ.length.\n\n(* length --------------------------------------------------------------------*)\n\nLemma length_spec_explicit : forall A (l: list A),\n  app length [l]\n    PRE (\\$ (len l + 1))\n    POST (fun y => \\[ y = len l ]).\nProof.\n  intros. induction l as [| x l].\n  { xcf. xpay. xvals. xmatch. xrets~. }\n  { xcf. xpay. now rewrite credits_split_eq; hsimpl.\n    xvals. xmatch. xapps. rewrite length_cons, !credits_split_eq. hsimpl.\n    xrets. now rewrite length_cons. }\nQed.\n\nClass length_spec_constants_pack := {\n  length_cost_a : Z;\n  length_cost_b : Z;\n  length_spec_constants : forall A (l: list A),\n    app length [l]\n      PRE (\\$ (length_cost_a * len l + length_cost_b))\n      POST (fun y => \\[ y = len l ]);\n}.\n\nInstance length_spec_constants_proof : length_spec_constants_pack.\nProof.\n  refine {| length_cost_a := 1; length_cost_b := 1; length_spec_constants := _ |}.\n  (* cheat a bit, and simply repackage [length_spec_explicit] *)\n  intros. xapp_spec length_spec_explicit. hsimpl_credits. math.\nQed.\n\nLemma length_spec_bigO :\n  specZ [costf \\in_O (fun n => n)] (forall A (l: list A),\n    app length [l]\n      PRE (\\$ costf (len l))\n      POST (fun y => \\[ y = len l ])).\nProof.\n  (* also cheat a bit, and re-package length_spec_explicit *)\n  xspecO (fun n => n + 1). intros; now xapp_spec length_spec_explicit.\n  monotonic. dominated.\nQed.\n\n(* length2 -------------------------------------------------------------------*)\n\nLemma length2_spec_explicit : forall A (l: list A),\n  app length2 [l]\n    PRE (\\$ (2 * len l + 3))\n    POST (fun y => \\[ y = 2 * len l ]).\nProof.\n  intros. xcf. weaken.\n  xpay.\n  xapps_spec length_spec_explicit.\n  xapps_spec length_spec_explicit.\n  xrets. math. math.\nQed.\n\nClass length2_spec_constants_pack := {\n  length2_cost_a : Z;\n  length2_cost_b : Z;\n  length2_spec_constants : forall A (l: list A),\n    app length2 [l]\n      PRE (\\$ (length2_cost_a * len l + length2_cost_b))\n      POST (fun y => \\[ y = 2 * len l ]);\n}.\n\nInstance length2_spec_constants_proof : length2_spec_constants_pack.\nProof.\n  (* Heavy handed version using defer+elia *)\n  begin defer assuming a b.\n  refine {| length2_cost_a := a; length2_cost_b := b;\n            length2_spec_constants := _ |}.\n  intros. xcf. weaken. xpay.\n  xapps_spec length_spec_constants.\n  xapps_spec length_spec_constants.\n  xrets. math.\n  (* Ideally (instead of what follows):\n     - [generalize (len l) (length_nonneg l); defer.]\n     - then have an automated solver *)\n  { defer?: (2 * length_cost_a <= a). defer?: (2 * length_cost_b + 1 <= b).\n    math_nia. }\n  end defer. elia.\nQed.\n\nLemma length2_spec_bigO :\n  specZ [costf \\in_O (fun n => n)] (forall A (l: list A),\n    app length2 [l]\n      PRE (\\$ costf (len l))\n      POST (fun y => \\[ y = 2 * len l ])).\nProof.\n  xspecO_refine straight_line. intros.\n  xcf. xpay.\n  xapps_spec (spec length_spec_bigO). (*hack*) set (ll:=len l). piggybank: *rhs.\n  xapps_spec (spec length_spec_bigO). (*hack*) set (ll:=len l). piggybank: *rhs.\n  xrets. math.\n  cleanup_cost. monotonic. dominated.\nQed.\n\n(* loop ----------------------------------------------------------------------*)\n\nLemma loop_spec_bigO :\n  specZ [costf \\in_O (fun n => n^2)] (forall A (l: list A),\n    app loop [l]\n      PRE (\\$ costf (len l))\n      POST (fun (_:Z) => \\[ True ])).\nProof.\n  xspecO_refine recursive. intros costf M D g.\n  induction l.\n  { xcf. weaken. xpay. xmatch. xrets~. rew_cost.\n    rewrite length_nil. defer. }\n  { xcf. weaken. xpay. xmatch.\n    xapps; =>_. xapps_spec (spec length_spec_bigO). xrets~.\n    rewrite length_cons. rew_cost.\n    generalize (len l) (length_nonneg l). defer. }\n  close_cost.\n  exists (fun n => n * cost length_spec_bigO n + n + 1). repeat split.\n  math.\n  intros.\n(*  apply Z.max_case.\n  { pols. forwards: cost_monotonic length_spec_bigO z (1+z); math_nia. }\n  { pols.\n  forwards: cost_nonneg length_spec_bigO z.\n  forwards: cost_nonneg length_spec_bigO (1+z). math_nia.*) admit.\n\n  cleanup_cost.\n  monotonic. (* ugh *) admit.\n  setoid_rewrite Z.pow_2_r. dominated.\n  setoid_rewrite <-Z.mul_1_l at 1. apply dominated_mul; dominated.\nAdmitted.\n", "meta": {"author": "isergeyam", "repo": "coq-bigO", "sha": "2b91cd9dbc3d9efc620dd87f0eb05c7816bee9c2", "save_path": "github-repos/coq/isergeyam-coq-bigO", "path": "github-repos/coq/isergeyam-coq-bigO/coq-bigO-2b91cd9dbc3d9efc620dd87f0eb05c7816bee9c2/examples/proofs/Composing_specs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711870587668, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.682674579097243}}
{"text": "Require Import ZArith.\n\nRequire Import Statement ThreadedPredicative Wpr.\n\nRequire Import Lia.\n\nOpen Scope stmt_scope.\n\nDefinition spec := ⟨fun '(i,n) '(i',n') => i <= n /\\ i' = n /\\ n = n'⟩.\n\nDefinition prog := WWhile (fun '(i,n) => i <> n) Do '(i,n) := (i+1,n) Done.\n\n\nTheorem correctness : prog ⊑ spec.\nProof.\n  intros (i,n) ((u,v),(HHin,_)); clear u v.\n  set (K := wpr prog (pred spec)).\n  generalize i HHin; clear i HHin.\n  induction n; intros i HHin.\n  { apply wpr_while_construct; right; simpl. lia. }\n  { apply Lt.le_lt_or_eq in HHin.\n    destruct HHin as [ HHin | HHin ].\n    { assert (i <= n) as HHin' by lia. \n      cut ((fun '(i,n) '(i',n') => i' <= n' /\\ K (i,S n) (i',S n')) (i, n) (i, n)).\n      { intros (HH1,HH2); auto. }\n      { apply (IHn _ HHin'); clear i n HHin HHin' IHn.\n        intros (i,n) (i',n'). intros [ (HHin,(HHi'n',HHind)) | HH ]; split; try lia.\n        { apply wpr_while_construct; left; split; auto. lia. }\n        { simpl in HH; apply wpr_while_construct; left; split; try lia; fold prog K.\n          apply wpr_while_construct; right; simpl. lia.\n        }\n      }\n    }\n    { apply wpr_while_construct; right; simpl. lia. }\n  }\nQed.\n\n\n", "meta": {"author": "bsall", "repo": "AMToPR-ICFEM-2019", "sha": "980d6d6ef5c9ad72a6b2cbd4fa549bc4705f0bed", "save_path": "github-repos/coq/bsall-AMToPR-ICFEM-2019", "path": "github-repos/coq/bsall-AMToPR-ICFEM-2019/AMToPR-ICFEM-2019-980d6d6ef5c9ad72a6b2cbd4fa549bc4705f0bed/src/examples/wpr/Count.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.682643282445973}}
{"text": "From Coq Require Import ssreflect ssrfun.\nSet Bullet Behavior \"Strict Subproofs\".\n\nRequire Import GHC.Base.\nRequire Import GHC.Enum.\n\n(******************************************************************************)\n(** `iterates'` and `iterates` functions -- used for specification **)\n\nFixpoint iterates' {A} (n : nat) (f : A -> A) (z : A) : list A :=\n  match n with\n  | O    => nil\n  | S n' => z :: iterates' n' f (f z)\n  end.\n\nFixpoint iterates {A} (n : nat) (f : A -> A) (z : A) : list A :=\n  z :: match n with\n       | O    => nil\n       | S n' => iterates n' f (f z)\n       end.\n\nTheorem iterates_iterates' {A} (n : nat) (f : A -> A) (z : A) :\n  iterates n f z = iterates' (S n) f z.\nProof. by elim: n z => [|n IH] z //=; rewrite IH. Qed.\n\nTheorem iterates'_ext {A} (n : nat) (f1 f2 : A -> A) (z : A) :\n  f1 =1 f2 ->\n  iterates' n f1 z = iterates' n f2 z.\nProof. by move=> f_eq; elim: n z => [|n IH] z //=; rewrite f_eq IH. Qed.\n\nTheorem iterates_ext {A} (n : nat) (f1 f2 : A -> A) (z : A) :\n  f1 =1 f2 ->\n  iterates n f1 z = iterates n f2 z.\nProof. rewrite !iterates_iterates'; apply iterates'_ext. Qed.\n\nTheorem iterates'_map {A} (n : nat) (f : A -> A) (z : A) :\n  iterates' n f z = Coq.Lists.List.map (fun n => Nat.iter n f z) (seq 0 n).\nProof.\n  elim: n z => [|n IH] z //=.\n  rewrite -seq_shift map_map IH /=.\n  f_equal; apply map_ext => i.\n  by elim: i => [|i IH'] //=; rewrite IH'.\nQed.\n\nTheorem iterates_map {A} (n : nat) (f : A -> A) (z : A) :\n  iterates n f z = Coq.Lists.List.map (fun n => Nat.iter n f z) (seq 0 (S n)).\nProof. rewrite iterates_iterates'; apply iterates'_map. Qed.\n\nTheorem iterates'_length {A} (n : nat) (f : A -> A) (z : A) :\n  length (iterates' n f z) = n.\nProof. by rewrite iterates'_map map_length seq_length. Qed.\n\nTheorem iterates_length {A} (n : nat) (f : A -> A) (z : A) :\n  length (iterates n f z) = S n.\nProof. rewrite iterates_iterates'; apply iterates'_length. Qed.\n\nTheorem iterates'_In {A} (n : nat) (f : A -> A) (z : A) (a : A) :\n  In a (iterates' n f z) <-> ex2 (fun i => i < n)%nat (fun i => a = Nat.iter i f z).\nProof.\n  rewrite iterates'_map in_map_iff.\n  split=> [[i [def_a i_in_seq]] | [i LT def_a]]; subst; exists i; try split; try done.\n  - move: i_in_seq => /in_seq [] //=.\n  - apply in_seq => //=; split => //.\n    apply Nat.le_0_l.\nQed.\n\nTheorem iterates_In {A} (n : nat) (f : A -> A) (z : A) (a : A) :\n  In a (iterates n f z) <-> ex2 (fun i => i <= n)%nat (fun i => a = Nat.iter i f z).\nProof.\n  rewrite iterates_iterates' iterates'_In.\n  split=> [[i LT def_a] | [i LE def_a]]; exists i=> //; omega.\nQed.\n\n(******************************************************************************)\n(** Lemmas about `Nat.iter` **)\n\nLemma iter_plus_nat (m n : nat) : Nat.iter m S n = (m + n)%nat.\nProof. by elim: m => [|m IH] //=; rewrite IH. Qed.\n\nLemma iter_plus_N (m : nat) (n : N) : Nat.iter m N.succ n = (N.of_nat m + n)%N.\nProof. by elim: m => [|m IH] //; rewrite Nat2N.inj_succ N.add_succ_l /= IH. Qed.\n\nLemma iter_plus_Z (m : nat) (n : Z) : Nat.iter m Z.succ n = (Z.of_nat m + n)%Z.\nProof. by elim: m => [|m IH] //; rewrite Nat2Z.inj_succ Z.add_succ_l /= IH. Qed.\n\n(******************************************************************************)\n(** `eftInt`, including `eftInt_aux` and `enumFromTo` **)\n\n(* Unrolling `eftInt_aux` *)\n\nDefinition eftInt_aux_rhs (y x : Int) (pf : (x <= y)%Z) : list Int :=\n  x :: match Z.eq_dec x y with\n       | left  _   => nil\n       | right neq => eftInt_aux y (x+1) (eftInt_aux_pf pf neq)\n       end%Z.\n\nLemma eftInt_aux_unroll (to from : Int) (pf : (from <= to)%Z) :\n  eftInt_aux to from pf = eftInt_aux_rhs to from pf.\nProof.\n  rewrite /eftInt_aux /eftInt_aux_func Wf.WfExtensionality.fix_sub_eq_ext /= /eftInt_aux_rhs.\n  by case: (Z.eq_dec from to).\nQed.\n\n(* Specifying `eftInt_aux`, `eftInt`, and `enumFromTo` in terms of\n   `iterate`/`iterate'` *)\n\nTheorem eftInt_aux_iterates (to from : Int) (pf : (from <= to)%Z) :\n  eftInt_aux to from pf = iterates (Z.to_nat (to - from)) Z.succ from.\nProof.\n  remember (Z.to_nat (to - from)) as diff eqn:def_diff.\n  elim: diff to from pf def_diff => [|diff IH] to from pf def_diff /=;\n    rewrite eftInt_aux_unroll /eftInt_aux_rhs.\n  - case: (Z.eq_dec _ _) => [// | NEQ].\n    suff LE: (to - from <= 0)%Z by omega.\n    move: def_diff; case: (to - from)%Z => //=.\n    move=> p ZERO; move: (Pos2Nat.is_pos p) => POS; omega.\n  - case: (Z.eq_dec _ _) => [? | NEQ]; first by subst; rewrite Z.sub_diag in def_diff.\n    rewrite IH //.\n    by rewrite Z.sub_add_distr Z2Nat.inj_sub //= -def_diff /Pos.to_nat /= Nat.sub_0_r.\nQed.\n\nTheorem eftInt_iterates' (from to : Int) :\n  eftInt from to = iterates' (Z.to_nat (to - from + 1)) Z.succ from.\nProof.\n  rewrite /eftInt; case: (Z_gt_dec _ _) => [GT | LE].\n  - have: (to - from < 0)%Z by omega.\n    case: (to - from)%Z => //=.\n    case=> //=.\n  - rewrite eftInt_aux_iterates iterates_iterates'; f_equal.\n    rewrite Z.add_1_r Z2Nat.inj_succ //; omega.\nQed.\n\nTheorem enumFromTo_Int_iterates' (from to : Int) :\n  enumFromTo from to = iterates' (Z.to_nat (to - from + 1)) Z.succ from.\nProof. apply eftInt_iterates'. Qed.\n\n(* Specifying `eftInt_aux`, `eftInt`, and `enumFromTo` in terms of membership *)\n\nTheorem eftInt_aux_In (to from : Int) (pf : (from <= to)%Z) (a : Int) :\n  In a (eftInt_aux to from pf) <-> (from <= a <= to)%Z.\nProof.\n  rewrite eftInt_aux_iterates iterates_In.\n  split=> [[i LE ->{a}] | [LE_a a_LE]].\n  - rewrite iter_plus_Z.\n    move: LE => /inj_le; rewrite Z2Nat.id => [|LE]; omega.\n  - remember (Z.to_nat (to - from)) as diff eqn:def_diff.\n    elim: diff from pf def_diff LE_a => [|diff IH] from pf def_diff LE_a.\n    + exists 0 => //=.\n      suff LE: (to - from <= 0)%Z by apply Z.le_antisymm; omega.\n      move: def_diff; case: (to - from)%Z => //= p.\n      move: (Pos2Nat.is_pos p) => *; omega.\n    + case: (Z.eq_dec from a) => [? | NEQ]; first by subst a; exists 0 => //=; omega.\n      have LE_a': (from < a)%Z by omega.\n      case: (IH (Z.succ from)) => [| | | i LE_i def_a]; try omega.\n      * by rewrite Z.sub_succ_r Z2Nat.inj_pred -def_diff.\n      * exists (S i); first by apply le_n_S.\n        by rewrite def_a /Nat.iter nat_rect_succ_r.\nQed.\n\nTheorem eftInt_In (from to : Int) (a : Int) :\n  In a (eftInt from to) <-> (from <= a <= to)%Z.\nProof.\n  rewrite /eftInt; case: (Z_gt_dec _ _) => ?; [simpl; omega | apply eftInt_aux_In].\nQed.\n\nTheorem enumFromTo_Int_In (from to : Int) (a : Int) :\n  In a (enumFromTo from to) <-> (from <= a <= to)%Z.\nProof. apply eftInt_In. Qed.\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/base-thy/GHC/Enum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.6825923102295818}}
{"text": "(* \n  Autor(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\nRequire Import ssreflect ssrbool ssrfun.\nRequire Import Arith Psatz.\nRequire Import List.\nImport ListNotations.\n\nSet Default Proof Using \"Type\".\nSet Default Goal Selector \"!\".\n\n(* misc facts *)\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\n(* transforms a goal (A -> B) -> C into goals A and B -> C *)\nLemma unnest {A B C: Prop} : A -> (B -> C) -> (A -> B) -> C.\nProof. auto. Qed.\n\n(* duplicates argument *)\nLemma copy {A: Prop} : A -> A * A.\nProof. done. Qed.\n\nLemma eta_reduction {X Y: Type} (f: X -> Y) : (fun x => f x) = f.\nProof. done. Qed.\n\n(* list facts *)\n\nLemma nil_or_ex_max (A : list nat) : A = [] \\/ exists a, In a A /\\ Forall (fun b => a >= b) A.\nProof.\n  elim: A; first by left.\n  move=> a A [-> | [b [? Hb]]]; right.\n  - exists a. constructor; by [left | constructor].\n  - case: (le_lt_dec a b)=> ?.\n    + exists b. constructor; by [right | constructor].\n    + exists a. constructor; first by left.\n      constructor; first done.\n      apply: Forall_impl Hb. by lia.\nQed.\n\n(* count_occ facts *)\nLemma count_occ_cons {X : Type} {D : forall x y : X, {x = y} + {x <> y}} {A a c}:\ncount_occ D (a :: A) c = count_occ D (locked [a]) c + count_occ D A c.\nProof.\n  rewrite /count_occ /is_left -lock. by case: (D a c).\nQed.\n\n(* Forall facts *)\nLemma Forall_singleton_iff {X: Type} {P: X -> Prop} {x} : Forall P [x] <-> P x.\nProof.\n  rewrite Forall_cons_iff. by constructor; [case |].\nQed.\n\n(* usage: rewrite ? Forall_norm *)\nDefinition Forall_norm := (@Forall_app, @Forall_singleton_iff, @Forall_cons_iff, @Forall_nil_iff).\n\n(* seq facts *)\nLemma seq_last start length : seq start (S length) = (seq start length) ++ [start + length].\nProof.\n  by rewrite (ltac:(lia) : S length = length + 1) seq_app.\nQed.\n\n(* repeat facts *)\nLemma Forall_repeat {X: Type} {a} {A: list X} : Forall (fun b => a = b) A -> A = repeat a (length A).\nProof.\n  elim: A; first done.\n  move=> b A IH. rewrite Forall_norm => [[? /IH ->]]. subst b.\n  cbn. by rewrite repeat_length.\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/SetConstraints/Util/Facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.6825922903852177}}
{"text": "Require Export euclidean__axioms.\nRequire Export lemma__congruencesymmetric.\nDefinition lemma__congruencetransitive : forall A B C D E F, (euclidean__axioms.Cong A B C D) -> ((euclidean__axioms.Cong C D E F) -> (euclidean__axioms.Cong A B E F)).\nProof.\nintro A.\nintro B.\nintro C.\nintro D.\nintro E.\nintro F.\nintro H.\nintro H0.\nassert (* Cut *) (euclidean__axioms.Cong C D A B) as H1.\n- apply (@lemma__congruencesymmetric.lemma__congruencesymmetric C A B D H).\n- assert (* Cut *) (euclidean__axioms.Cong A B E F) as H2.\n-- apply (@euclidean__axioms.cn__congruencetransitive A B E F C D H1 H0).\n-- exact H2.\nQed.\n", "meta": {"author": "Karnaj", "repo": "dktactgeo", "sha": "f98a62e5ffa2030dc89962e1349e0c273cc911b9", "save_path": "github-repos/coq/Karnaj-dktactgeo", "path": "github-repos/coq/Karnaj-dktactgeo/dktactgeo-f98a62e5ffa2030dc89962e1349e0c273cc911b9/lemma__congruencetransitive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6825851441017867}}
{"text": "From VLSM.Lib Require Import SsrExport.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(** * Definition of possibly-infinite traces *)\n\nLtac invs h := inversion h; subst => {h}.\n\nSection sec_traces.\n\nContext {A B : Type}.\n\n(** ** Core trace definition and decomposition *)\n\n(**\n  This definition is similar to that for lazy lists from Chapter 13\n  of the #<a href=\"https://github.com/coq-community/coq-art\">Coq'Art book</a>#.\n  However, to support traces following labeled transition relations, constructors\n  have additional elements.\n*)\n\nCoInductive trace : Type :=\n| Tnil : A -> trace\n| Tcons : A -> B -> trace -> trace.\n\nDefinition hd tr :=\nmatch tr with\n| Tnil a => a\n| Tcons a b tr0 => a\nend.\n\nDefinition trace_decompose (tr : trace) : trace :=\nmatch tr with\n| Tnil a => Tnil a\n| Tcons a b tr' => Tcons a b tr'\nend.\n\nLemma trace_destr : forall tr, tr = trace_decompose tr.\nProof. by case. Qed.\n\n(** ** Bisimulations between traces *)\n\nCoInductive bisim : trace -> trace -> Prop :=\n| bisim_nil : forall a,\n   bisim (Tnil a) (Tnil a)\n| bisim_cons : forall a b tr tr',\n   bisim tr tr' ->\n   bisim (Tcons a b tr) (Tcons a b tr').\n\nLemma bisim_refl : forall tr, bisim tr tr.\nProof.\ncofix CIH.\ncase => [a | a b tr]; first exact: bisim_nil.\nexact/bisim_cons/CIH.\nQed.\n\nLemma bisim_sym : forall tr1 tr2, bisim tr1 tr2 -> bisim tr2 tr1.\nProof.\ncofix CIH.\ncase => [a | a b tr1] tr2 Hbs; invs Hbs; first exact: bisim_nil.\nexact/bisim_cons/CIH.\nQed.\n\nLemma bisim_trans : forall tr1 tr2 tr3,\n bisim tr1 tr2 -> bisim tr2 tr3 -> bisim tr1 tr3.\nProof.\ncofix CIH.\ncase => [a | a b tr1] tr2 tr0 Hbs Hbs'; invs Hbs; invs Hbs'; first exact: bisim_nil.\nexact: (bisim_cons _ _ (CIH _ _ _ H3 H4)).\nQed.\n\nLemma bisim_hd : forall tr0 tr1, bisim tr0 tr1 -> hd tr0 = hd tr1.\nProof. by move => tr0 tr1 []. Qed.\n\n(** ** Appending traces to one another *)\n\nCoFixpoint trace_append (tr tr' : trace) : trace :=\nmatch tr with\n| Tnil a => tr'\n| Tcons a b tr0 => Tcons a b (trace_append tr0 tr')\nend.\n\n#[local] Infix \"+++\" := trace_append (at level 60, right associativity).\n\nLemma trace_append_nil : forall a tr, (Tnil a) +++ tr = tr.\nProof.\nmove => a tr.\nrewrite [Tnil a +++ tr]trace_destr.\nby case tr.\nQed.\n\nLemma trace_append_cons : forall a b tr tr',\n (Tcons a b tr) +++ tr' = Tcons a b (tr +++ tr').\nProof.\nmove => a b tr tr'.\nrewrite [Tcons a b tr +++ tr']trace_destr.\nby case tr.\nQed.\n\nLemma trace_append_bism : forall tr1 tr2 tr3 tr4,\n bisim tr1 tr2 -> bisim tr3 tr4 -> bisim (tr1 +++ tr3) (tr2 +++ tr4).\nProof.\ncofix CIH.\nmove => tr1 tr2 tr3 tr4 [a1 | a1 b1 tr1' tr2' Hbs1'] Hbs2.\n- rewrite 2!trace_append_nil. exact: Hbs2.\n- rewrite 2!trace_append_cons.\n  exact/bisim_cons/CIH.\nQed.\n\nEnd sec_traces.\n\nInfix \"+++\" := trace_append (at level 60, right associativity).\n", "meta": {"author": "runtimeverification", "repo": "vlsm", "sha": "9115beb539257427467872ce65a224a0268cdae7", "save_path": "github-repos/coq/runtimeverification-vlsm", "path": "github-repos/coq/runtimeverification-vlsm/vlsm-9115beb539257427467872ce65a224a0268cdae7/theories/VLSM/Lib/Traces.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979306, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6824901556245062}}
{"text": "Require Import Coq.ZArith.ZArith.\n\nSection Imp.\n\nContext {Var: Type}.\n\nDefinition stack := Var -> Z.\nDefinition heap := Z -> option Z.\nDefinition state: Type := stack * heap.\n\nDefinition update_stack (st : stack) (x : Var) (n : Z) (st': stack): Prop :=\n  st' x = n /\\\n  (forall x0, x0 <> x -> st x0 = st' x0).\n\nDefinition update_heap (st : heap) (x : Z) (n : option Z) (st': heap): Prop :=\n  st' x = n /\\\n  (forall x0, x0 <> x -> st x0 = st' x0).\n\nInductive aexp : Type :=\n  | AVar : Var -> aexp\n  | ANum : Z -> aexp\n  | APlus : aexp -> aexp -> aexp\n  | AMinus : aexp -> aexp -> aexp\n  | AMult : aexp -> aexp -> aexp.\n\nInductive bexp : Type :=\n  | BTrue : bexp\n  | BFalse : bexp\n  | BEq : aexp -> aexp -> bexp\n  | BLe : aexp -> aexp -> bexp\n  | BNot : bexp -> bexp\n  | BAnd : bexp -> bexp -> bexp.\n\nFixpoint aeval (st : stack) (a : aexp) : Z :=\n  match a with\n  | AVar x => st x\n  | ANum n => n\n  | APlus a1 a2 => (aeval st a1) + (aeval st a2)\n  | AMinus a1 a2  => (aeval st a1) - (aeval st a2)\n  | AMult a1 a2 => (aeval st a1) * (aeval st a2)\n  end.\n\nFixpoint beval (st : stack) (b : bexp) : bool :=\n  match b with\n  | BTrue       => true\n  | BFalse      => false\n  | BEq a1 a2   => Zeq_bool (aeval st a1) (aeval st a2)\n  | BLe a1 a2   => Zle_bool (aeval st a1) (aeval st a2)\n  | BNot b1     => negb (beval st b1)\n  | BAnd b1 b2  => andb (beval st b1) (beval st b2)\n  end.\n\nInductive cmd : Type :=\n  | CSkip : cmd\n  | CSet : Var -> aexp -> cmd\n  | CLoad : Var -> Var -> cmd\n  | CStore : Var -> Var -> cmd\n  | CSeq : cmd -> cmd -> cmd\n  | CIf : bexp -> cmd -> cmd -> cmd\n  | CWhile : bexp -> cmd -> cmd.\n\nNotation \"'SKIP'\" :=\n  CSkip.\nNotation \"x '::=' a\" :=\n  (CSet x a) (at level 60).\nNotation \"x '::=' '<<' y '>>'\" :=\n  (CLoad x y) (at level 58).\nNotation \"'<<' x '>>' '::=' y\" :=\n  (CStore x y) (at level 58).\nNotation \"c1 ;; c2\" :=\n  (CSeq c1 c2) (at level 80, right associativity).\nNotation \"'WHILE' b 'DO' c 'END'\" :=\n  (CWhile b c) (at level 80, right associativity).\nNotation \"'IFB' c1 'THEN' c2 'ELSE' c3 'FI'\" :=\n  (CIf c1 c2 c3) (at level 80, right associativity).\n\nReserved Notation \" t '/' st '==>' t' '/' st' \" \n                  (at level 40, st at level 39, t' at level 39).\n\nInductive cstep : (cmd * state) -> (cmd * state) -> Prop :=\n  | CS_Set : forall st st' i n a,\n      aeval (fst st) a = n ->\n      update_stack (fst st) i n (fst st') ->\n      snd st = snd st' ->\n      (i ::= a) / st ==> SKIP / st'\n  | CS_Load : forall (st st': state) i x n,\n      snd st (fst st x) = Some n ->\n      update_stack (fst st) i n (fst st') ->\n      snd st = snd st' ->\n      (i ::= << x >>) / st ==> SKIP / st'\n  | CS_Store : forall (st st': state) i x n,\n      snd st (fst st x) = Some n ->\n      update_heap (snd st) (fst st x) (Some (fst st i)) (snd st') ->\n      fst st = fst st' ->\n      (CStore x i) / st ==> SKIP / st'\n  | CS_SeqStep : forall st c1 c1' st' c2,\n      c1 / st ==> c1' / st' ->\n      (c1 ;; c2) / st ==> (c1' ;; c2) / st'\n  | CS_SeqFinish : forall st c2,\n      (SKIP ;; c2) / st ==> c2 / st\n  | CS_IfTrue : forall st b c1 c2,\n      beval (fst st) b = true ->\n      IFB b THEN c1 ELSE c2 FI / st ==> c1 / st\n  | CS_IfFalse : forall st b c1 c2,\n      beval (fst st) b = false ->\n      IFB b THEN c1 ELSE c2 FI / st ==> c2 / st\n  | CS_WhileTrue : forall st b c1,\n      beval (fst st) b = true ->\n      (WHILE b DO c1 END) / st ==> (c1;; (WHILE b DO c1 END)) / st\n  | CS_WhileFalse : forall st b c1,\n      beval (fst st) b = false ->\n      (WHILE b DO c1 END) / st ==> SKIP / st\n\n  where \" t '/' st '==>' t' '/' st' \" := (cstep (t,st) (t',st')).\n", "meta": {"author": "QinxiangCao", "repo": "UnifySL", "sha": "cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d", "save_path": "github-repos/coq/QinxiangCao-UnifySL", "path": "github-repos/coq/QinxiangCao-UnifySL/UnifySL-cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d/examples/HeapOp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7956581000631541, "lm_q1q2_score": 0.682490140711198}}
{"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(** Basic specifications : sets that may contain logical information *)\n\nSet Implicit Arguments.\n\nRequire Import Notations.\nRequire Import Datatypes.\nRequire Import Logic.\n\n(** Subsets and Sigma-types *)\n\n(** [(sig A P)], or more suggestively [{x:A | P x}], denotes the subset\n    of elements of the type [A] which satisfy the predicate [P].\n    Similarly [(sig2 A P Q)], or [{x:A | P x & Q x}], denotes the subset\n    of elements of the type [A] which satisfy both [P] and [Q]. *)\n\nInductive sig (A:Type) (P:A -> Prop) : Type :=\n    exist : forall x:A, P x -> sig P.\n\nInductive sig2 (A:Type) (P Q:A -> Prop) : Type :=\n    exist2 : forall x:A, P x -> Q x -> sig2 P Q.\n\n(** [(sigT A P)], or more suggestively [{x:A & (P x)}] is a Sigma-type.\n    Similarly for [(sigT2 A P Q)], also written [{x:A & (P x) & (Q x)}]. *)\n\nInductive sigT (A:Type) (P:A -> Type) : Type :=\n    existT : forall x:A, P x -> sigT P.\n\nInductive sigT2 (A:Type) (P Q:A -> Type) : Type :=\n    existT2 : forall x:A, P x -> Q x -> sigT2 P Q.\n\n(* Notations *)\n\nArguments Scope sig [type_scope type_scope].\nArguments Scope sig2 [type_scope type_scope type_scope].\nArguments Scope sigT [type_scope type_scope].\nArguments Scope sigT2 [type_scope type_scope type_scope].\n\nNotation \"{ x  |  P }\" := (sig (fun x => P)) : type_scope.\nNotation \"{ x  |  P  & Q }\" := (sig2 (fun x => P) (fun x => Q)) : type_scope.\nNotation \"{ x : A  |  P }\" := (sig (fun x:A => P)) : type_scope.\nNotation \"{ x : A  |  P  & Q }\" := (sig2 (fun x:A => P) (fun x:A => Q)) :\n  type_scope.\nNotation \"{ x : A  & P }\" := (sigT (fun x:A => P)) : type_scope.\nNotation \"{ x : A  & P  & Q }\" := (sigT2 (fun x:A => P) (fun x:A => Q)) :\n  type_scope.\n\nAdd Printing Let sig.\nAdd Printing Let sig2.\nAdd Printing Let sigT.\nAdd Printing Let sigT2.\n\n\n(** Projections of [sig]\n\n    An element [y] of a subset [{x:A & (P x)}] is the pair of an [a]\n    of type [A] and of a proof [h] that [a] satisfies [P].  Then\n    [(proj1_sig y)] is the witness [a] and [(proj2_sig y)] is the\n    proof of [(P a)] *)\n\n\nSection Subset_projections.\n\n  Variable A : Type.\n  Variable P : A -> Prop.\n\n  Definition proj1_sig (e:sig P) := match e with\n                                    | exist a b => a\n                                    end.\n\n  Definition proj2_sig (e:sig P) :=\n    match e return P (proj1_sig e) with\n    | exist a b => b\n    end.\n\nEnd Subset_projections.\n\n\n(** Projections of [sigT]\n\n    An element [x] of a sigma-type [{y:A & P y}] is a dependent pair\n    made of an [a] of type [A] and an [h] of type [P a].  Then,\n    [(projT1 x)] is the first projection and [(projT2 x)] is the\n    second projection, the type of which depends on the [projT1]. *)\n\nSection Projections.\n\n  Variable A : Type.\n  Variable P : A -> Type.\n\n  Definition projT1 (x:sigT P) : A := match x with\n                                      | existT a _ => a\n                                      end.\n  Definition projT2 (x:sigT P) : P (projT1 x) :=\n    match x return P (projT1 x) with\n    | existT _ h => h\n    end.\n\nEnd Projections.\n\n(** [sigT] of a predicate is equivalent to [sig] *)\n\nLemma sig_of_sigT : forall (A:Type) (P:A->Prop), sigT P -> sig P.\nProof. destruct 1 as (x,H); exists x; trivial. Defined.\n\nLemma sigT_of_sig : forall (A:Type) (P:A->Prop), sig P -> sigT P.\nProof. destruct 1 as (x,H); exists x; trivial. Defined.\n\nCoercion sigT_of_sig : sig >-> sigT.\nCoercion sig_of_sigT : sigT >-> sig.\n\n(** [sumbool] is a boolean type equipped with the justification of\n    their value *)\n\nInductive sumbool (A B:Prop) : Set :=\n  | left : A -> {A} + {B}\n  | right : B -> {A} + {B}\n where \"{ A } + { B }\" := (sumbool A B) : type_scope.\n\nAdd Printing If sumbool.\n\nImplicit Arguments left [[A] [B]] [A].\nImplicit Arguments right [[A] [B]] [B].\n\n(** [sumor] is an option type equipped with the justification of why\n    it may not be a regular value *)\n\nInductive sumor (A:Type) (B:Prop) : Type :=\n  | inleft : A -> A + {B}\n  | inright : B -> A + {B}\n where \"A + { B }\" := (sumor A B) : type_scope.\n\nAdd Printing If sumor.\n\n(** Various forms of the axiom of choice for specifications *)\n\nSection Choice_lemmas.\n\n  Variables S S' : Set.\n  Variable R : S -> S' -> Prop.\n  Variable R' : S -> S' -> Set.\n  Variables R1 R2 : S -> Prop.\n\n  Lemma Choice :\n   (forall x:S, {y:S' | R x y}) -> {f:S -> S' | forall z:S, R z (f z)}.\n  Proof.\n   intro H.\n   exists (fun z => proj1_sig (H z)).\n   intro z; destruct (H z); assumption.\n  Defined.\n\n  Lemma Choice2 :\n   (forall x:S, {y:S' & R' x y}) -> {f:S -> S' & forall z:S, R' z (f z)}.\n  Proof.\n    intro H.\n    exists (fun z => projT1 (H z)).\n    intro z; destruct (H z); assumption.\n  Defined.\n\n  Lemma bool_choice :\n   (forall x:S, {R1 x} + {R2 x}) ->\n     {f:S -> bool | forall x:S, f x = true /\\ R1 x \\/ f x = false /\\ R2 x}.\n  Proof.\n    intro H.\n    exists (fun z:S => if H z then true else false).\n    intro z; destruct (H z); auto.\n  Defined.\n\nEnd Choice_lemmas.\n\nSection Dependent_choice_lemmas.\n\n  Variables X : Set.\n  Variable R : X -> X -> Prop.\n\n  Lemma dependent_choice :\n    (forall x:X, {y | R x y}) ->\n    forall x0, {f : nat -> X | f O = x0 /\\ forall n, R (f n) (f (S n))}.\n  Proof.\n    intros H x0.\n    set (f:=fix f n := match n with O => x0 | S n' => proj1_sig (H (f n')) end).\n    exists f.\n    split. reflexivity.\n    induction n; simpl; apply proj2_sig.\n  Defined.\n\nEnd Dependent_choice_lemmas.\n\n\n (** A result of type [(Exc A)] is either a normal value of type [A] or\n     an [error] :\n\n     [Inductive Exc [A:Type] : Type := value : A->(Exc A) | error : (Exc A)].\n\n     It is implemented using the option type. *)\n\nDefinition Exc := option.\nDefinition value := Some.\nDefinition error := @None.\n\nImplicit Arguments error [A].\n\nDefinition except := False_rec. (* for compatibility with previous versions *)\n\nImplicit Arguments except [P].\n\nTheorem absurd_set : forall (A:Prop) (C:Set), A -> ~ A -> C.\nProof.\n  intros A C h1 h2.\n  apply False_rec.\n  apply (h2 h1).\nDefined.\n\nHint Resolve left right inleft inright: core v62.\nHint Resolve exist exist2 existT existT2: core.\n\n(* Compatibility *)\n\nNotation sigS := sigT (only parsing).\nNotation existS := existT (only parsing).\nNotation sigS_rect := sigT_rect (only parsing).\nNotation sigS_rec := sigT_rec (only parsing).\nNotation sigS_ind := sigT_ind (only parsing).\nNotation projS1 := projT1 (only parsing).\nNotation projS2 := projT2 (only parsing).\n\nNotation sigS2 := sigT2 (only parsing).\nNotation existS2 := existT2 (only parsing).\nNotation sigS2_rect := sigT2_rect (only parsing).\nNotation sigS2_rec := sigT2_rec (only parsing).\nNotation sigS2_ind := sigT2_ind (only parsing).\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/Init/Specif.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.6824901382667039}}
{"text": "Definition id {A : Type} (a : A) : A := a.\n\nDefinition compose {A B C : Type} (g : B -> C) (f : A -> B): A -> C :=\n    fun a : A => g (f a).\n\nClass Functor (functor: Type -> Type) := {\n    fmap: forall {A B : Type}, (A -> B) -> functor A -> functor B;\n\n    functors_preserve_composition\n        : forall (A B C: Type)\n        , forall (g : B -> C)\n        , forall (f : A -> B)\n        , forall (c : functor A)\n        , (compose (fmap g) (fmap f)) c = fmap (compose g f) c;\n\n    functor_id_law\n        : forall (A : Type), forall (c : functor A), fmap id c = id c\n}.\n\nClass Applicative (F: Type -> Type) := {\n    (* It must also be a functor *)\n    is_functor :> Functor F;\n\n    (* functions *)\n    unit : forall {A : Type}, A -> F A;\n    apply : forall {A B : Type}, F (A -> B) -> F A -> F B;\n\n\n    (* laws *)\n    unit_identity\n        : forall (A : Type) (x : F A), apply (unit id) x = x;\n\n    unit_compose\n        : forall (A B C : Type) (u : F (B -> C)) (v : F (A -> B)) (w : F A)\n        , apply (apply (apply (unit compose) u) v) w = apply u (apply v w);\n\n    unit_homomorphism\n        : forall (A B : Type) (f : A -> B) (x : A)\n        , apply (unit f) (unit x) = unit (f x);\n\n    unit_interchange\n        : forall (A B : Type) (u : F (A -> B)) (x : A)\n        , apply u (unit x) = apply (unit (fun (f : A -> B) => f x)) u;\n\n    unit_fmap\n        : forall (A B : Type) (f : A -> B) (x : F A)\n        , fmap f x = apply (unit f) x\n}.\n\nNotation \"v <*> w\" := (apply v w) (at level 50).\n\nClass Monad (M: Type -> Type) := {\n    (* Must be an applicative functor *)\n    monads_are_applicative :> Applicative M;\n\n    (* functions *)\n    join : forall {A : Type}, M (M A) -> M A;\n\n    (* Monad Laws *)\n\n    monad_unit_left_identity\n        : forall (A B : Type) (f : A -> M B) (x : A)\n        , f x = join (fmap f (unit x));\n\n    monad_unit_right_identity\n        : forall (A : Type) (m : M A)\n        , id m = join (fmap unit m);\n\n    (* monad_join_associative\n        : forall (A : Type) (m : M (M (M A)))\n        , join m = fmap join m *)\n\n    monad_join_fmap_associative\n        : forall (A B C : Type) (m : M A) (k : A -> M B) (h : B -> M C)\n        , join (fmap (fun x : A => join (fmap h (k x))) m) = join (fmap h (join (fmap k m)))\n\n}.\n\nDefinition bind {M : Type -> Type} {ismonad : Monad M} {A B : Type} (m : M A) (f : A -> M B) : M B :=\n    join (fmap f m).\n\nNotation \"m >>= f\" := (bind m f) (at level 50).\n\nTheorem bind_associative \n    : forall (A B C : Type) (M : Type -> Type) (monad_dict : Monad M) (m : M A) (k : A -> M B) (h : B -> M C)\n    , m >>= (fun (x : A) => (k x >>= h)) = (m >>= k) >>= h.\nProof.\n    intros.\n    unfold bind.\n    apply monad_join_fmap_associative.\nQed.\n\n\nInductive myMaybe (A : Type) : Type :=\n    | empty : myMaybe A\n    | just : A -> myMaybe A.\n\nDefinition maybeMap {A B : Type} (f : A -> B) (m : @myMaybe A) : @myMaybe B :=\n    match m with\n        | empty => empty B\n        | just x => just B (f x)\n    end.\n\nDefinition applyMaybe {A B : Type} (mf : @myMaybe (A -> B)) (m : @myMaybe A) : @myMaybe B :=\n    match mf with\n        | empty => empty B\n        | just f => match m with\n            | empty => empty B\n            | just x => just B (f x)\n        end\n    end.\n\nDefinition joinMaybe {A : Type} (mm : @myMaybe (@myMaybe A)) : @myMaybe A :=\n    match mm with\n        | empty => empty A\n        | just m => m\n    end.\n\nInstance maybe_functor : Functor myMaybe := {\n    fmap := @maybeMap\n}.\nProof.\n    intros.\n    unfold compose.\n    unfold maybeMap.\n    destruct c.\n    reflexivity.\n    reflexivity.\n    intros.\n    unfold maybeMap.\n    destruct c.\n    unfold id.\n    reflexivity.\n    unfold id.\n    reflexivity.\nDefined.\n\nInstance maybe_applicative : Applicative myMaybe := {\n    unit := @just;\n    apply := @applyMaybe\n}.\nProof.\n    - intros. unfold applyMaybe. destruct x as [| x']. reflexivity. unfold id. reflexivity.\n    - intros.\n        unfold applyMaybe.\n        destruct u as [| uf].\n        reflexivity.\n        destruct v as [| vf].\n        reflexivity.\n        destruct w as [| w'].\n        reflexivity.\n        unfold compose.\n        reflexivity.\n    - intros.\n        unfold applyMaybe.\n        reflexivity.\n    -   intros.\n        unfold applyMaybe.\n        destruct u as [| uf].\n        reflexivity.\n        reflexivity.\n    -   intros.\n        simpl.\n        destruct x as [| x'].\n        unfold maybeMap.\n        reflexivity.\n        unfold maybeMap.\n        reflexivity.\nDefined.\n\nInstance maybe_monad : Monad myMaybe := {\n    join := @joinMaybe\n}.\nProof.\n    - intros.\n        unfold joinMaybe.\n        unfold fmap.\n        unfold is_functor.\n        unfold maybe_applicative.\n        unfold maybe_functor.\n        unfold maybeMap.\n        unfold unit.\n        reflexivity.\n    - intros.\n        unfold id.\n        unfold joinMaybe.\n        unfold fmap.\n        unfold is_functor.\n        unfold maybe_applicative.\n        unfold maybe_functor.\n        unfold maybeMap.\n        destruct m as [| x].\n        reflexivity.\n        unfold unit.\n        reflexivity.\n    - intros.\n        unfold fmap.\n        unfold is_functor.\n        unfold maybe_applicative.\n        unfold maybe_functor.\n        unfold maybeMap.\n        destruct m as [| x].\n        simpl.\n        reflexivity.\n        destruct (k x) as [| kx].\n        simpl.\n        reflexivity.\n        simpl.\n        reflexivity.\nDefined.\n", "meta": {"author": "domdere", "repo": "haskell-coq", "sha": "83c7ffec0fb78a246d350621ff5c76577916d417", "save_path": "github-repos/coq/domdere-haskell-coq", "path": "github-repos/coq/domdere-haskell-coq/haskell-coq-83c7ffec0fb78a246d350621ff5c76577916d417/Haskell.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7956581024858785, "lm_q1q2_score": 0.6824901370033994}}
{"text": "(* -*- mode: coq; mode: visual-line -*-  *)\nRequire Import HoTT.Basics HoTT.Types.\nRequire Import HFiber Extensions Limits.Pullback.\nRequire Import Modality Accessible Localization.\n\nLocal Open Scope path_scope.\nLocal Open Scope subuniverse_scope.\n\n(** * Descent between subuniverses *)\n\n(** We study here a strengthening of the relation [O << O'] saying that [O]-modal type families descend along [O']-equivalences.  Pairs of reflective subuniverses with this relation share nearly all the properties of a reflective subuniverse [O] paired with its subuniverse [Sep O] of separated types (see [Separated.v]) and also many of those of a single left exact modality (see [Lex.v]).  Thus, many of the results herein generalize those of RSS for lex modalities and those of CORS for separated subuniverses.\n\nNote that this kind of descent is not the same as the \"modal descent\" of Cherubini and Rijke.  When we get around to formalizing that, we may need to worry about disambiguating the names. *)\n\n(** ** Definitions *)\n\n(** This definition is an analogue of the statement of Lemma 2.19 of CORS, and of Theorem 3.1(xiii) of RSS.  Note that CORS Lemma 2.19 includes uniqueness of the extension, which we don't assert explicitly.  However, uniqueness follows from the [ReflectsD] parameter -- see [ooextendable_TypeO_lex_leq] below. *)\nClass Descends@{i} (O' O : Subuniverse@{i}) (T : Type@{i})\n      `{ReflectsD@{i} O' O T} :=\n{\n  OO_descend :\n    forall (P : T -> Type@{i}) {P_inO : forall x, In O (P x)},\n      O_reflector O' T -> Type@{i} ;\n  OO_descend_inO :\n    forall (P : T -> Type@{i}) {P_inO : forall x, In O (P x)} (x : O_reflector O' T),\n      In O (OO_descend P x) ;\n  OO_descend_beta :\n    forall (P : T -> Type@{i}) {P_inO : forall x, In O (P x)} (x : T),\n      OO_descend P (to O' T x) <~> P x ;\n}.\n\nGlobal Existing Instance OO_descend_inO.\nArguments OO_descend O' O {T _ _ _} P {P_inO} x.\nArguments OO_descend_inO O' O {T _ _ _} P {P_inO} x.\nArguments OO_descend_beta O' O {T _ _ _} P {P_inO} x.\n\nClass O_lex_leq (O1 O2 : ReflectiveSubuniverse) `{O1 << O2} :=\n  O_lex_leq_descends : forall A, Descends O2 O1 A.\n\nInfix \"<<<\" := O_lex_leq : subuniverse_scope.\nGlobal Existing Instance O_lex_leq_descends.\n\n(** Unfortunately, it seems that generalizing binders don't work on notations: writing [`{O <<< O'}] doesn't automatically add the precondition [O << O'], although writing [`{O_lex_leq O O'}] does. *)\n\nDefinition O_lex_leq_eq {O1 O2 O3 : ReflectiveSubuniverse}\n           `{O1 <=> O2} `{O2 << O3, O2 <<< O3}\n           (Hstrong := O_strong_leq_trans_l O1 O2 O3)\n  : O1 <<< O3.\nProof.\n  intros A; unshelve econstructor; intros P P_inO1.\n  all:pose (P_inO2 := fun x => inO_leq O1 O2 _ (P_inO1 x)).\n  - apply (OO_descend O3 O2 P).\n  - intros x; apply (inO_leq O2 O1), (OO_descend_inO O3 O2 P).\n  - apply (OO_descend_beta O3 O2 P).\nDefined.\n\n(** ** Left exactness properties *)\n\n(** We prove analogues of the properties in section 2.4 of CORS and Theorem 3.1 of RSS, but in a different order, with different proofs, to increase the generality.  The proofs in CORS use Proposition 2.26 for everything else, but it seems that most of the other results are true in the generality of two reflective subuniverses with [O <<< O'], so we give different proofs for some of them.  (To show that this generality is non-spurious, note that a lex modality [O] satisfies [O <<< O], but does not generally coincide with [Sep O].)\n\nIn the case of a single modality, most of these statements are equivalent to lex-ness (as stated in Theorem 3.1 of RSS).  We do not know if anything similar is true more generally. *)\n\nSection LeftExactness.\nUniverse i.\nContext (O' O : ReflectiveSubuniverse@{i}) `{O << O', O <<< O'}.\n\n(** Proposition 2.30 of CORS and Theorem 3.1(xii) of RSS: any [O']-equivalence is [O]-connected.  The special case when [f = to O' A] requires only [O << O'], but the general case seems to require [O <<< O']. *)\nGlobal Instance conn_map_OO_inverts\n       {A B : Type} (f : A -> B) `{O_inverts O' f}\n  : IsConnMap O f.\nProof.\n  apply conn_map_from_extension_elim.\n  intros P P_inO.\n  assert (E : ExtendableAlong 1%nat f P); [ | exact (fst E) ].\n  assert (Qp := OO_descend_beta O' O P).\n  assert (Q_inO := OO_descend_inO O' O P).\n  set (Q := OO_descend O' O P) in *.\n  refine (extendable_postcompose' _ (Q o to O' B) P f Qp _).\n  refine (cancelL_extendable _ Q f (to O' B) _ _).\n  1:srapply (extendable_conn_map_inO O).\n  refine (extendable_homotopic _ _ (O_functor O' f o to O' A) (to_O_natural O' f) _).\n  srapply extendable_compose.\n  1:srapply extendable_equiv.\n  srapply (extendable_conn_map_inO O).\nDefined.\n\n(** A generalization of Lemma 2.27 of CORS: [functor_sigma] of a family of [O]-equivalences over an [O']-equivalence is an [O]-equivalence.  CORS Lemma 2.27 is the case when [f = to O' A] and [g] is a family of identities. *)\nDefinition OO_inverts_functor_sigma \n       {A B : Type} {P : A -> Type} {Q : B -> Type}\n       (f : A -> B) (g : forall a, P a -> Q (f a))\n       `{O_inverts O' f} `{forall a, O_inverts O (g a)}\n  : O_inverts O (functor_sigma f g).\nProof.\n  srapply isequiv_homotopic'.\n  - refine (equiv_O_sigma_O O _ oE _ oE (equiv_O_sigma_O O _)^-1).\n    refine (Build_Equiv _ _ (O_functor O (functor_sigma f (fun x => O_functor O (g x)))) _).\n  - apply O_indpaths. intros [x u]; cbn.\n    rewrite !to_O_natural, O_rec_beta; cbn.\n    rewrite !to_O_natural, O_rec_beta.\n    reflexivity.\nDefined.\n\n(** Families of [O]-modal types descend along all [O']-equivalences (not just the [O']-units, as asserted in the definition of [<<<]. *)\nDefinition OO_descend_O_inverts\n           {A B : Type} (f : A -> B) `{O_inverts O' f}\n           (P : A -> Type) {P_inO : forall x, In O (P x)}\n  : B -> Type.\nProof.\n  intros b.\n  pose (Q := OO_descend O' O P).\n  exact (Q ((O_functor O' f)^-1 (to O' B b))).\nDefined.\n\nGlobal Instance OO_descend_O_inverts_inO\n       {A B : Type} (f : A -> B) `{O_inverts O' f}\n       (P : A -> Type) {P_inO : forall x, In O (P x)} (b : B)\n  : In O (OO_descend_O_inverts f P b)\n  := _.\n\nDefinition OO_descend_O_inverts_beta\n           {A B : Type} (f : A -> B) `{O_inverts O' f}\n           (P : A -> Type) {P_inO : forall x, In O (P x)} (a : A)\n  : (OO_descend_O_inverts f P (f a)) <~> P a.\nProof.\n  unfold OO_descend_O_inverts.\n  refine (OO_descend_beta O' O P a oE _).\n  assert (p := (to_O_natural O' f a)^).\n  apply moveR_equiv_V in p.\n  exact (equiv_transport _ p).\nDefined.\n\n(** Morally, an equivalent way of saying [O <<< O'] is that the universe of [O]-modal types is [O']-modal.  We can't say this directly since this type lives in a higher universe, but here is a rephrasing of it. *)\nDefinition ooextendable_TypeO_lex_leq `{Univalence}\n           {A B : Type} (f : A -> B) `{O_inverts O' f}\n  : ooExtendableAlong f (fun _ => Type_ O).\nProof.\n  rapply ooextendable_TypeO_from_extension; intros P.\n  exists (fun x => (OO_descend_O_inverts f P x ;\n                    OO_descend_O_inverts_inO f P x)).\n  intros x; apply path_TypeO, path_universe_uncurried; cbn.\n  exact (OO_descend_O_inverts_beta f P x).\nDefined.\n\n(** We can also state it in terms of belonging to a subuniverse if we lift [O'] accessibly (an analogue of Theorem 3.11(iii) of RSS). *)\nGlobal Instance inO_TypeO_lex_leq `{Univalence} `{IsAccRSU O'}\n  : In (lift_accrsu O') (Type_ O)\n  := fun i => ooextendable_TypeO_lex_leq (acc_lgen O' i).\n\n(** If [f] is an [O']-equivalence, then [ap f] is an [O]-equivalence. *)\nGlobal Instance OO_inverts_ap@{}\n       {A B : Type@{i}} (f : A -> B) `{O_inverts O' f} (x y : A)\n  : O_inverts O (@ap _ _ f x y).\nProof.\n  assert (Pb := OO_descend_O_inverts_beta f (fun y:A => O (x = y))).\n  assert (P_inO := OO_descend_O_inverts_inO f (fun y:A => O (x = y))).\n  set (P := OO_descend_O_inverts f (fun y:A => O (x = y))) in *.\n  clearbody P; cbn in *.\n  srapply isequiv_adjointify.\n  - intros q.\n    pose (t := fun p => @transport B P (f x) (f y) p ((Pb x)^-1 (to O (x = x) 1))).\n    exact (Pb y (O_rec t q)).\n  - apply O_indpaths; intros p; cbn.\n    rewrite O_rec_beta.\n    assert (g := extension_conn_map_elim O (functor_sigma f (fun (a:A) (p:P (f a)) => p))\n                                         (fun bp => O (f x = bp.1)) (fun u => O_functor O (ap f) (Pb u.1 u.2))). \n    pose (g1 b p := g.1 (b;p)). cbn in g1.\n    assert (e : (fun u => g1 u.1 u.2) == g.1). \n    1:intros [a b]; reflexivity.\n    assert (g2 := fun a p => e _ @ g.2 (a;p)); cbn in g2.\n    refine ((g2 y _)^ @ _).\n    rewrite (ap_transport p g1).\n    rewrite (g2 x ((Pb x)^-1 (to O (x = x) 1))).\n    rewrite eisretr, to_O_natural; cbn.\n    rewrite <- (ap_transport p (fun b => to O (f x = b))).\n    apply ap.\n    rewrite transport_paths_r.\n    apply concat_1p.\n  - apply O_indpaths; intros p; cbn.\n    rewrite to_O_natural, O_rec_beta.\n    destruct p; cbn.\n    srapply eisretr.\nDefined.\n\nDefinition equiv_O_functor_ap_OO_inverts\n       {A B : Type} (f : A -> B) `{O_inverts O' f} (x y : A)\n  : O (x = y) <~> O (f x = f y)\n  := Build_Equiv _ _ (O_functor O (ap f)) _.\n\n(** Theorem 3.1(i) of RSS: path-spaces of [O']-connected types are [O]-connected. *)\nDefinition OO_isconnected_paths\n           {A : Type} `{IsConnected O' A} (x y : A)\n  : IsConnected O (x = y).\nProof.\n  rapply (contr_equiv' _ (equiv_O_functor_ap_OO_inverts (const_tt _) x y)^-1).\nDefined.\n\n(** Proposition 2.26 of CORS and Theorem 3.1(ix) of RSS; also generalizes Theorem 7.3.12 of the book.  Here we need to add the extra assumption that [O' <= Sep O], which is satisfied when [O' = Sep O] but also when [O] is lex and [O' = O].  That some such extra hypothesis is necessary can be seen from the fact that [Tr (-2) <<< O'] for any [O'], whereas this statement is certainly not true in that generality. *)\nDefinition path_OO `{O' <= Sep O}\n           {X : Type@{i}} (x y : X)\n  : O (x = y) -> (to O' X x = to O' X y).\nProof.\n  nrefine (O_rec (O := O) (@ap X (O' X) (to O' X) x y)).\n  - rapply (@inO_leq O' (Sep O)).\n  - exact _.\nDefined.\n\nGlobal Instance isequiv_path_OO `{O' <= Sep O}\n       {X : Type@{i}} (x y : X)\n  : IsEquiv (path_OO x y).\nProof.\n  nrefine (isequiv_O_rec_O_inverts O _).\n  (** Typeclass search can find this, but it's quicker (and may help the reader) to give it explicitly. *)\n  apply (OO_inverts_ap (to O' X)).\nDefined.\n\nDefinition equiv_path_OO `{O' <= Sep O}\n           {X : Type@{i}} (x y : X)\n  : O (x = y) <~> (to O' X x = to O' X y)\n  := Build_Equiv _ _ (path_OO x y) _.\n\n(** [functor_hfiber] on a pair of [O']-equivalences is an [O]-equivalence. *)\nGlobal Instance OO_inverts_functor_hfiber\n       {A B C D : Type} {f : A -> B} {g : C -> D} {h : A -> C} {k : B -> D}\n       (p : k o f == g o h) (b : B)\n       `{O_inverts O' h, O_inverts O' k}\n  : O_inverts O (functor_hfiber p b).\nProof.\n  unfold functor_hfiber.\n  simple notypeclasses refine (OO_inverts_functor_sigma _ _).\n  1:exact _.\n  intros a; cbn.\n  refine (isequiv_homotopic (O_functor O (concat (p a)^) o O_functor O (@ap _ _ k (f a) b)) _).\n  symmetry; apply O_functor_compose.\nDefined.\n\n(** Corollary 2.29 of CORS: [O'] preserves fibers up to [O]-equivalence. *)\nGlobal Instance OO_inverts_functor_hfiber_to_O\n       {Y X : Type} (f : Y -> X) (x : X)\n  : O_inverts O (functor_hfiber (fun a => (to_O_natural O' f a)^) x).\nProof.\n  (** Typeclass search can find this, but it's faster to give it explicitly. *)\n  exact (OO_inverts_functor_hfiber _ _).\nDefined.\n\nDefinition equiv_OO_functor_hfiber_to_O\n           {Y X : Type@{i} } (f : Y -> X) (x : X)\n  : O (hfiber f x) <~> O (hfiber (O_functor O' f) (to O' X x))\n  := Build_Equiv _ _ _ (OO_inverts_functor_hfiber_to_O f x).\n\n(** Theorem 3.1(iii) of RSS: any map between [O']-connected types is [O]-connected.  (Part (ii) is just the version for dependent projections.) *)\nDefinition OO_conn_map_isconnected\n       {Y X : Type} `{IsConnected O' Y, IsConnected O' X} (f : Y -> X)\n  : IsConnMap O f.\nProof.\n  intros x; rapply (contr_equiv' _ (equiv_OO_functor_hfiber_to_O f x)^-1).\nDefined.\n\nDefinition OO_isconnected_hfiber\n       {Y X : Type} `{IsConnected O' Y, IsConnected O' X} (f : Y -> X) (x : X)\n  : IsConnected O (hfiber f x)\n  := OO_conn_map_isconnected f x.\n\n(** Theorem 3.1(iv) of RSS: an [O]-modal map between [O']-connected types is an equivalence. *)\nGlobal Instance OO_isequiv_mapino_isconnected\n       {Y X : Type} `{IsConnected O' Y, IsConnected O' X} (f : Y -> X) `{MapIn O _ _ f}\n  : IsEquiv f.\nProof.\n  apply (isequiv_conn_ino_map O).\n  - apply OO_conn_map_isconnected.\n  - assumption.\nDefined.\n\n(** Theorem 3.1(vi) of RSS (and part (v) is just the analogue for dependent projections). *)\nDefinition OO_conn_map_functor_hfiber {A B C D : Type}\n           {f : A -> B} {g : C -> D} {h : A -> C} {k : B -> D}\n           `{IsConnMap O' _ _ h, IsConnMap O' _ _ k}\n           (p : k o f == g o h) (b : B)\n  : IsConnMap O (functor_hfiber p b).\nProof.\n  intros [c q].\n  nrefine (isconnected_equiv' O _ (hfiber_functor_hfiber p b c q)^-1 _).\n  apply OO_isconnected_hfiber.\nDefined.\n\n(** An enhancement of Corollary 2.29 of CORS, corresponding to Theorem 3.1(viii) of RSS: when [O'] is a modality, the map between fibers is not just an O-equivalence but is O-connected. *)\nGlobal Instance OO_conn_map_functor_hfiber_to_O `{IsModality O'}\n       {Y X : Type} (f : Y -> X) (x : X)\n  : IsConnMap O (functor_hfiber (fun y => (to_O_natural O' f y)^) x).\nProof.\n  apply OO_conn_map_functor_hfiber.\nDefined.\n\n(** Theorem 3.1(vii) of RSS *)\nDefinition OO_ispullback_connmap_mapino\n           {A B C D : Type} {f : A -> B} {g : C -> D} {h : A -> C} {k : B -> D}\n           (p : k o f == g o h)\n           `{O_inverts O' h, O_inverts O' k, MapIn O _ _ f, MapIn O _ _ g}\n  : IsPullback p.\nProof.\n  apply ispullback_isequiv_functor_hfiber; intros b.\n  apply (isequiv_O_inverts O).\n  apply OO_inverts_functor_hfiber; exact _.\nDefined.\n\n(** [functor_pullback] on a triple of [O']-equivalences is an [O]-equivalence. *)\nGlobal Instance OO_inverts_functor_pullback\n       {A1 B1 C1 A2 B2 C2 : Type}\n       (f1 : B1 -> A1) (g1 : C1 -> A1)\n       (f2 : B2 -> A2) (g2 : C2 -> A2)\n       (h : A1 -> A2) (k : B1 -> B2) (l : C1 -> C2)\n       (p : f2 o k == h o f1) (q : g2 o l == h o g1)\n       `{O_inverts O' h, O_inverts O' k, O_inverts O' l}\n  : O_inverts O (functor_pullback f1 g1 f2 g2 h k l p q).\nProof.\n  unfold functor_pullback.\n  simple notypeclasses refine (OO_inverts_functor_sigma _ _).\n  1:exact _.\n  intros b1; cbn.\n  simple notypeclasses refine (OO_inverts_functor_sigma _ _).\n  1:exact _.\n  intros c1; cbn.\n  pose @isequiv_compose. (* Speed up typeclass search. *)\n  refine (isequiv_homotopic (O_functor O (fun r => r @ (q c1)^) o O_functor O (concat (p b1)) o O_functor O (@ap _ _ h (f1 b1) (g1 c1))) _).\n  intros r; symmetry. \n  refine (_ @ _).\n  2:apply O_functor_compose.\n  cbn; srapply O_functor_compose.\nDefined.\n\n(** Proposition 2.28 of CORS, and Theorem 3.1(x) of RSS: the functor [O'] preserves pullbacks up to [O]-equivalence. *)\nGlobal Instance OO_inverts_functor_pullback_to_O\n       {A B C : Type} (f : B -> A) (g : C -> A)\n  : O_inverts O (functor_pullback f g (O_functor O' f) (O_functor O' g)\n                                  (to O' A) (to O' B) (to O' C)\n                                  (to_O_natural O' f) (to_O_natural O' g)).\nProof.\n  apply OO_inverts_functor_pullback; exact _.\nDefined.\n\nDefinition equiv_OO_pullback {A B C : Type} (f : B -> A) (g : C -> A)\n  : O (Pullback f g) <~> O (Pullback (O_functor O' f) (O_functor O' g))\n  := Build_Equiv _ _ _ (OO_inverts_functor_pullback_to_O f g).\n\n(** The \"if\" direction of CORS Proposition 2.31, and the nontrivial part of Theorem 3.1(xi) of RSS.  Note that we could also deduce Theorem 3.1(iii) of RSS from this. *)\nDefinition OO_cancelL_conn_map\n           {Y X Z : Type} (f : Y -> X) (g : X -> Z)\n           `{IsConnMap O' _ _ (g o f)} `{IsConnMap O' _ _ g}\n  : IsConnMap O f.\nProof.\n  apply conn_map_OO_inverts.\n  nrapply (cancelL_isequiv (O_functor O' g)).\n  1:exact _.\n  rapply (isequiv_homotopic _ (O_functor_compose O' f g)).\nDefined.\n\nEnd LeftExactness.\n\n(** Here's the \"only if\" direction of CORS Proposition 2.31.  Note that the hypotheses are different from those of the \"if\" direction, and the proof is shorter than the one given in CORS. *)\nDefinition OO_cancelR_conn_map\n       (O' O : ReflectiveSubuniverse@{u}) `{O_leq@{u u u} O O', O' <= Sep O}\n       {Y X Z : Type} (f : Y -> X) (g : X -> Z)\n       `{IsConnMap O' _ _ (g o f)} `{IsConnMap O _ _ f}\n  : IsConnMap O' g.\nProof.\n  apply conn_map_from_extension_elim.\n  intros P P_inO h.\n  exists (conn_map_elim O' (g o f) P (h o f)).\n  nrefine (conn_map_elim O f _ _); [ exact _ | .. ].\n  - intros x.\n    pose proof (fun z => inO_leq O' (Sep O) (P z) (P_inO z)).\n    exact _.\n  - intros y.\n    apply (conn_map_comp O' (g o f)).\nDefined.\n\nDefinition OO_isconnected_from_conn_map\n       (O' O : ReflectiveSubuniverse) `{O <= O', O' <= Sep O}\n       {Y X : Type} (f : Y -> X)\n       `{IsConnected O' Y} `{IsConnMap O _ _ f}\n  : IsConnected O' X.\nProof.\n  apply isconnected_conn_map_to_unit.\n  apply (OO_cancelR_conn_map O' O f (const_tt _)).\nDefined.\n\n(** An interesting scholium to Proposition 2.31. *)\nDefinition OO_inverts_conn_map_factor_conn_map\n       (O' O : ReflectiveSubuniverse) `{O << O', O <<< O', O' <= Sep O}\n       {Y X Z : Type} (f : Y -> X) (g : X -> Z)\n       `{IsConnMap O' _ _ (g o f)} `{IsConnMap O _ _ f}\n  : O_inverts O' f.\nProof.\n  nrapply (cancelL_isequiv (O_functor O' g)).\n  - apply O_inverts_conn_map.\n    apply (OO_cancelR_conn_map O' O f g).\n  - rapply (isequiv_homotopic _ (O_functor_compose O' f g)).\nDefined.\n\nDefinition OO_inverts_conn_map_isconnected_domain\n       (O' O : ReflectiveSubuniverse) `{O << O', O <<< O', O' <= Sep O}\n       {Y X : Type} (f : Y -> X)\n       `{IsConnected O' Y} `{IsConnMap O _ _ f}\n  : O_inverts O' f.\nProof.\n  apply (OO_inverts_conn_map_factor_conn_map O' O f (const_tt _)).\nDefined.\n\n(** Here is the converse of [ooextendable_TypeO_lex_leq]. *)\nDefinition O_lex_leq_extendable_TypeO\n           (O' O : ReflectiveSubuniverse) `{O << O'}\n           (e : forall (A:Type) (g:A->Type_ O), ExtensionAlong (to O' A) (fun _ => Type_ O) g)\n  : O <<< O'.\nProof.\n  intros A; unshelve econstructor; intros P' P_inO; pose (P := fun x => (P' x ; P_inO x) : Type_ O).\n  - exact (fun x => ((e A P).1 x).1).\n  - exact (fun x => ((e A P).1 x).2).\n  - intros x.\n    apply equiv_path.\n    exact (((e A P).2 x)..1).\nDefined.\n\n(** And a version for the accessible case. *)\nDefinition O_lex_leq_inO_TypeO\n           (O' O : ReflectiveSubuniverse) `{O << O'}\n           `{IsAccRSU O'} `{In (lift_accrsu O') (Type_ O)}\n  : O <<< O'.\nProof.\n  apply O_lex_leq_extendable_TypeO.\n  intros A g.\n  assert (O_inverts (lift_accrsu O') (to O' A)).\n  - rapply (O_inverts_O_leq' (lift_accrsu O') O').\n  - exact (fst (ooextendable_O_inverts (lift_accrsu O') (to O' A) (Type_ O) 1%nat) g).\nDefined.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Modalities/Descent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6824901365549264}}
{"text": "(*Robert Hughes\nComp 293 Hw 1\nThis is the document for the first homework for the software reliability class*)\n\n\n(*Question #1*)\nTheorem question_1: forall f:bool -> bool, forall x: bool,\n  (f x) = x ->\n  f(f x) = x.\n\nProof.\n  intros.\n  rewrite H.\n  rewrite H.\n  reflexivity.\nQed.\n\n\n\n(*Question 2*)\nTheorem question_2: forall b c : bool,\nandb b c =  orb b c ->\nb = c.\n\nProof.\n  intros b c.\n  destruct b. destruct c.\n  reflexivity. simpl.\n  intros H1. rewrite H1.\n  reflexivity. simpl.\n  destruct c. intros H2. rewrite H2. reflexivity. reflexivity.\nQed.\n\n(*Question 3*)\nInductive bin: Type :=\n| Zero: bin\n| Two: bin -> bin\n| Two_one: bin -> bin.\n\n\n(*Question 4*)\nFixpoint bin_inc(b: bin): bin :=\n  match b with\n    | Zero => Two_one Zero\n    | Two x => Two_one x\n    | Two_one x => Two (bin_inc x)\n  end.\n\n(*Question 5*)\nFixpoint bin_to_nat (b: bin): nat :=\n  match b with\n    | Zero => O\n    | Two x => (bin_to_nat x) + (bin_to_nat x)\n    | Two_one x => S  ((bin_to_nat x) + (bin_to_nat x))\n  end.\n\n\n(*Question 6*)\nTheorem bin_to_nat_pres_incr_original : forall b : bin,\n  bin_to_nat (bin_inc b) = 1 + (bin_to_nat b).\nProof.\n  intros b.\n  induction b as [|b'|b2'].\n  - reflexivity.\n  - reflexivity.\n  - simpl.\n    rewrite -> IHb2'.\n    rewrite -> plus_n_Sm.\n    reflexivity.\nQed.\n\n(*Question 7 -- from CA03 *)\nTheorem question_7 : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros. induction n as [|n' IHn'].\n  reflexivity.\n  simpl. rewrite -> IHn'. reflexivity.  Qed.\n\n(*Question 8*)\n\n(*taken from class work*)\nLemma mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros. induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.  Qed.\n\nLemma plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\n    intros. induction n as [|n' IHn'].\n    reflexivity.\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n\nLemma plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros. induction n as [|n' IHn'].\n  reflexivity.\n  simpl. rewrite -> IHn'. reflexivity.  Qed.\n\nLemma plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros. induction n as [|n' IHn'].\n  - rewrite <- plus_n_O.\n    + reflexivity.\n  - simpl. rewrite -> IHn'. rewrite plus_n_Sm. reflexivity.  Qed.\n\n(*This is needed for the communative multiply to work for the second half of the theorem*)\nLemma mult_n_Sm : forall n m:nat, n * m + n = n * S m.\nProof.\n  intros. induction n as [| n'].\n  reflexivity.\n  simpl. rewrite <- IHn'.\n  simpl. rewrite -> plus_n_Sm. rewrite -> plus_n_Sm. \n  rewrite -> plus_assoc. reflexivity.\nQed.\n\nTheorem question_8 : forall n m : nat,\n  n * m = m * n.\nProof.\n  intros n m. induction m as [|m' IHm'].\n  simpl. rewrite mult_0_r. reflexivity.\n  simpl. rewrite <- mult_n_Sm. rewrite <- plus_comm.\n  rewrite -> IHm'. reflexivity. Qed.\n\n\n(*Question 9*)\n(*From class work*)\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\nTheorem question_9 : forall n : nat,\n  leb n n = true.\nProof.\n  intros. induction n as [| n'].\n  simpl. reflexivity.\n  simpl. rewrite IHn'. reflexivity.\nQed.\n  \n\n\n(*Question 10*)\nTheorem question_10 : forall b : bool,\n  andb b false = false.\nProof.\n  intros. destruct b. simpl.\n  reflexivity. simpl. reflexivity. Qed.\n\n\n(*Question 11*)\nTheorem question_11: forall n m p: nat,\nleb n m = true ->\nleb (p + n) (p + m) = true.\nProof.\n  intros. induction p as [|p' IHp'].\n  - simpl. rewrite H. reflexivity.\n  - simpl. rewrite IHp'. reflexivity.\nQed.\n\n\n(*Question 12*)\nLemma plus_n_O : forall n:nat, n = n + 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)    reflexivity.\n  - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity.  Qed.\n\nTheorem question_12: forall n : nat,\n  1 * n = n.\nProof.\n  intros. induction n as [| n'].\n  reflexivity.\n  simpl. rewrite plus_n_O. reflexivity.  Qed.\n\n\n(*Question 13*)\nTheorem question_13: forall x y: bool,\norb (andb x y ) (orb (negb x) (negb y)) = true.\nProof.\n intros. destruct x.\n  - destruct y.\n    + reflexivity.\n    + reflexivity.\n  - reflexivity.\nQed.\n\n\n\n(*Question 14*)\n\nTheorem question_14 : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof.\n  intros. induction n as [| n'].\n  reflexivity.\n  simpl. rewrite IHn'. rewrite plus_assoc. reflexivity.  Qed.\n\n\n(*Question 15*)\n\nTheorem question_15 : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\n  intros. induction n as [| n'].\n  reflexivity.\n  simpl. rewrite IHn'. rewrite question_14. reflexivity.\nQed.\n\n\n(*Question 16*)\n\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nFixpoint half (n : nat) : nat :=\n    match n with\n      | O => O\n      | S O => O\n      | S (S n) => S (half n)\n    end.\n\n\nTheorem question_16 : forall n : nat,\n  half(double(n)) = n.\nProof.\n  intros.\n  induction n as [| n'].\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\n  \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Robert-M-Hughes", "repo": "software-foundations-work", "sha": "e000fe8cd3b2e36c79765c413c534d8d287755db", "save_path": "github-repos/coq/Robert-M-Hughes-software-foundations-work", "path": "github-repos/coq/Robert-M-Hughes-software-foundations-work/software-foundations-work-e000fe8cd3b2e36c79765c413c534d8d287755db/HW1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6824901336619594}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra.\nRequire Import Psatz Poly_complements seq_base.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nImport GRing.Theory.\nLocal Open Scope ring_scope.\n\nSection Tcheby.\nVariable R : ringType.\nImplicit Types (l : seq R) (p: {poly R}) .\n\n(* Chebyshev polynomials introduced via their recursion scheme *)\n\nFixpoint pT_expanded_def (n : nat) {struct n} : {poly R} :=\n  if n is n1.+1 then\n    if n1 is n2.+1 then 'X *+2 * pT_expanded_def n1 - pT_expanded_def n2\n    else 'X\n  else 1.\n\nFact pT_key : unit. Proof. by []. Qed.\nDefinition pT := locked_with pT_key pT_expanded_def.\nCanonical pT_unlockable := [unlockable fun pT].\n\nNotation \"'T_ n\" := (pT n)\n  (at level 3, n at level 2, format \"''T_' n \").\n\nLemma pT0 : 'T_0 = 1 :> {poly R}.\nProof. by rewrite unlock /pT_expanded_def. Qed.\n\nLemma pT1 : 'T_1 = 'X :> {poly R}.\nProof.\nby rewrite unlock /pT_expanded_def.\nQed.\n\nLemma pTSS : forall n, 'T_n.+2 = 'X *+2 * 'T_n.+1 - 'T_n :> {poly R}.\nProof. by move => n; rewrite unlock. Qed.\n\nNotation \"'T_ n\" := (pT n)\n  (at level 3, n at level 2, format \"''T_' n \").\n\nLemma horner1_pT n : ('T_n).[1: R] = 1.\nProof.\nelim/ltn_ind: n => [] [|[|n]] IH; first by rewrite pT0 hornerC.\n  by rewrite pT1 hornerX.\nrewrite pTSS hornerD hornerN mulrnAl hornerMn.\nby rewrite -commr_polyX hornerMX !IH // !mulr1 mulrS [1+ _]addrC addrK.\nQed.\n\nLemma hornerN1_pT n : ('T_n).[-1: R] = (-1) ^+ n.\nProof.\nelim/ltn_ind : n => [] [|[|n]] IH; first by rewrite pT0 hornerC.\n  by rewrite pT1 hornerX.\nrewrite pTSS hornerD hornerN mulrnAl hornerMn.\nrewrite -commr_polyX hornerMX !IH //.\nby rewrite !exprS !(mulN1r, mulrN1, opprK) mulr2n addrK.\nQed.\n\nLemma commr_pT p n : GRing.comm p ('T_n).\nProof.\nelim/ltn_ind : n => [] [|[|n]] IH; first by rewrite pT0; apply: commr1.\n  by rewrite pT1; apply: commr_polyX.\nrewrite pTSS; apply: commrD; last by apply: commrN; apply: IH.\nby rewrite mulrnAl; apply: commrMn; apply: commrM;\n [exact: commr_polyX | apply: IH].\nQed.\n\nDefinition pU := fix pU_rec (n : nat) {struct n} : {poly R} :=\n  if n is n1.+1 then\n    if n1 is n2.+1 then 'X *+ 2 * pU_rec n1 - pU_rec n2\n    else 'X *+ 2\n  else 1.\n\nNotation \"'U_ n\" := (pU n)\n  (at level 3, n at level 2, format \"''U_' n \").\n\nLemma pU0 : 'U_0 = 1.\nProof. by []. Qed.\n\nLemma pU1 : 'U_1 = 'X *+ 2.\nProof. by []. Qed.\n\nLemma pUSS n : 'U_n.+2 = 'X *+ 2 * 'U_n.+1 - 'U_n.\nProof. by []. Qed.\n\nLemma horner1_pU n : ('U_n).[1] = n.+1%:R.\nProof.\nelim/ltn_ind : n => [] [|[|n]] IH; first by rewrite hornerC.\n  by rewrite pU1 hornerMn hornerX.\nrewrite pUSS hornerD hornerN mulrnAl hornerMn.\nrewrite -commr_polyX hornerMX mulr1 !IH //.\nrewrite -mulr_natl -natrM -natrB; last first.\n  by rewrite mulSn !addSnnS addnS ltnS leq_addr.\nby rewrite mul2n -addnn -addSnnS addnK.\nQed.\n\nLemma commr_pU p n : GRing.comm p ('U_n).\nProof.\nelim/ltn_ind : n => [] [|[|n]] IH; first  by exact: commr1.\n  by rewrite pU1; apply: commrMn; exact: commr_polyX.\nrewrite pUSS; apply: commrD; last by apply: commrN; apply: IH.\nby rewrite mulrnAl; apply: commrMn; apply: commrM;\n   [exact: commr_polyX | apply: IH].\nQed.\n\nLemma pT_pU n : 'T_n.+1 = 'U_n.+1 - 'X * 'U_n.\nProof.\nhave F: pU 1 - 'X * pU 0 = 'X by rewrite pU1 pU0 mulr1 addrK.\nelim/ltn_ind : n  => [] [|n] IH; first by rewrite pT1 F.\nrewrite pTSS pUSS IH // mulrDr -!addrA; congr (_ + _). \ncase: n IH => [_|m IH].\n  rewrite pT0 pU0 pU1 addrC mulrN; congr (_ - _).\n  by rewrite mulr1 mulrnAl mulrnAr.\nrewrite IH // pUSS addrC opprD -!addrA; congr (_ + _).\nrewrite mulrDr !mulrN opprB opprK; congr (_ - _).\nby rewrite !mulrA commr_polyX.\nQed.\n\nLemma deriv_pT n: ('T_n.+1)^`() = 'U_n *+ n.+1.\nProof.\nelim/ltn_ind : n => [] [|n] IH; first by rewrite pT1 derivX.\nrewrite pTSS derivD derivM derivMn derivX !IH // pT_pU.\ncase: n IH => [_|n IH].\n  by rewrite pU0 pU1 pT0 derivN derivC subr0 mulr_natl mulrnBl !mulr1 addrK.\nrewrite derivN IH // pUSS mulr_natl !(mulrnDl, mulrnBl).\nrewrite !(mulrnAl, mulrnAr) -!mulrnA.\nset x := 'X * _; set y := pU n.\nrewrite -[x *+ _ + _ *+ _]addrC -3!addrA addrC.\nrewrite addrA -[(2 * 2)%N]/(2 + 2)%N mulrnDr.\nrewrite mulNrn addrK.\nrewrite -mulrnDr mulnC; rewrite -addrA; congr (_ + _)=> //.\n  congr (_ *+ _); rewrite !mul2n //.\nby rewrite -mulNrn -mulrnDr addnC.\nQed.\n\nLemma coef_pU : forall n i,\n  ('U_n)`_i =\n    if (n < i)%N || odd (n + i) then 0 else\n    let k := (n - i)./2 in ((-1)^+k * (2^i * 'C(n-k,k))%:R).\nProof.\nelim/ltn_ind => [] [|[|n]] IH i.\n- by case: i => [|i]; rewrite pU0 ?coefC //= mul1r.\n  by rewrite coefMn coefX; case: i=> [|[|i]] //=;\n     rewrite ?mul0rn //= -mulr_natl mulr1 mul1r.\nrewrite pUSS coefB mulrnAl coefMn coefXM !IH //.\ncase: i=> [|i].\n  rewrite !addn0 mul0rn sub0r subn0 /=; case O1: (odd _).\n    by rewrite oppr0.\n  rewrite !mul1n /= exprS !mulNr subSS mul1r.\n  rewrite -{2 6}[n]odd_double_half O1 add0n subSn -addnn ?leq_addr //.\n  by rewrite  addnK !binn.\nrewrite !addSn !addnS /=; case O1: (odd _); last first.\n   by rewrite !orbT mul0rn  subrr.\nrewrite !orbF !subSS; case: leqP=> Hm; last first.\n  rewrite ltnS (leq_trans _ Hm); last by  exact: (leq_addl 2 n).\n  by rewrite mul0rn  sub0r oppr0.\nrewrite ltnS.\nmove: Hm; rewrite leq_eqVlt; case/orP=> [/eqP->|].\n  by rewrite subnn leqnSn !mul1r !bin0 !muln1 subr0 -mulr_natl -natrM.\nrewrite ltnS leq_eqVlt; case/orP; [move/eqP->|move=>Him].\n  by rewrite leqnn subSnn !subn0 expr0 !bin0\n             subr0 !mul1r !muln1 -mulr_natl -natrM expnS.\nrewrite leqNgt Him /= subSn; last by exact: ltnW.\nhave->: ((n - i).+1./2 = (n - i)./2.+1).\n rewrite -{1}[(n - i)%N]odd_double_half.\n rewrite (oddB (ltnW _)) // -oddD O1.\n by rewrite /= (half_bit_double _ false).\nhave->: ((n - i.+1)./2 = (n - i)./2).\n rewrite subnS -{1}[(n - i)%N]odd_double_half.\n rewrite (oddB (ltnW _)) // -oddD O1.\n by rewrite /= (half_bit_double _ false).\nset u := (n - i)./2.\nrewrite !subSS subSn.\n  rewrite binS mulnDr mulrnDr mulrDr; congr (_ + _).\n    by rewrite -mulrnAr -mulr_natl -natrM mulnA expnS.\n  by rewrite -mulN1r mulrA exprS.\napply: (leq_trans (half_leq (leq_subr i n))).\nby rewrite -{2}[n]odd_double_half -addnn addnA leq_addl.\nQed.\n\nLemma coef_pUn n : ('U_n)`_n = (2^n)%:R.\nProof.\nby rewrite coef_pU ltnn addnn odd_double subnn /= bin0 mul1r muln1.\nQed.\n\nLemma size_pU_leq n : (size ('U_n) <= n.+1)%N.\nProof. by apply/leq_sizeP=> j Hj; rewrite coef_pU Hj. Qed.\n\nLemma coef_pT n i :\n  ('T_n)`_i =\n    if (n < i)%N || odd (n + i) then 0 : R else\n    if n is 0 then 1 else\n    let k := (n - i)./2 in\n    (-1) ^+ k * ((2^i * n * 'C(n-k,k)) %/ (n-k).*2)%:R.\nProof.\ncase: n => [|n]; first by rewrite pT0 coefC; case: i.\nrewrite pT_pU coefB coefXM !coef_pU.\ncase: leqP; last first.\n  by case: i=> [|i] //; rewrite ltnS=> ->; exact: subrr.\ncase: i => [_|i Hi].\n  rewrite addn0; case O1: (odd _); first by exact: subr0.\n  rewrite !subr0 !subn0 !mul1n; congr (_ * _); congr (_%:R).\n  have F: n.+1 = (n.+1)./2.*2 by rewrite-{1}[(n.+1)%N]odd_double_half O1.\n  by rewrite {8}F -[_./2.*2]addnn addnK -F mulKn // mul1n.\nrewrite subSS addnS /=; case O1: (odd _); first by rewrite orbT subr0.\nrewrite orbF; move: (Hi); rewrite ltnS leqNgt; move/negPf->.\nrewrite -mulrBr; congr (_ * _).\nrewrite -natrB; last first.\n  apply: leq_mul; first rewrite leq_exp2l //.\n  by apply: leq_bin2l; apply: leq_sub2r.\ncongr (_%:R).\nhave F: (n-i = (n-i)./2.*2)%N\n   by rewrite-{1}[(n-i)%N]odd_double_half oddB // -oddD O1.\nset u := (n - i)./2.\nhave F1: (u <= n)%N.\n  by apply: leq_trans (leq_subr i _); rewrite F -addnn leq_addl.\nrewrite subSn //.\nhave->: (n - u = i + u)%N.\n  rewrite ltnS in Hi; rewrite -{1}(subnK Hi) [(_ + i)%N]addnC.\n  by rewrite -addnBA;\n     [rewrite {1}F -addnn addnK | rewrite F -addnn leq_addr].\nset v := (i + u)%N.\nrewrite {2}expnS -!mulnA -mul2n divnMl //.\npose k := (u`! * (v.+1 - u)`!)%N.\nhave Fk: k != 0%N.\n  apply/eqP=> Hk; move: (leqnn k); rewrite {2}Hk leqNgt.\n  by rewrite /k !(muln_gt0,fact_gt0).\napply/eqP; rewrite -[_ == _]orFb -(negPf Fk).\nhave F2: (u <= v)%N by apply: leq_addl.\nhave F3 : (u <= v.+1)%N   by apply: (leq_trans F2).\nhave F4: (u + v = n)%N by rewrite addnC -addnA addnn -F addnC subnK.\nrewrite -eqn_mul2r mulnBl -!mulnA bin_fact //.\nrewrite expnSr -mulnA -mulnBr {1}/k subSn // [(_ - _).+1`!]factS.\nrewrite [((_ - _).+1 * _)%N]mulnC 2!mulnA -[('C(_,_) * _ * _)%N]mulnA.\nrewrite bin_fact ?leqDl // [(2 * _)%N]mulnC.\nrewrite factS [(v.+1 * _)%N]mulnC -!mulnA -mulnBr.\nrewrite -subSn // subnBA //.\nrewrite [(_ + u)%N]addnC muln2 -addnn !addnA addnK.\nrewrite divn_mulAC.\n  rewrite -!mulnA bin_fact //.\n  rewrite factS [(v.+1 * _)%N]mulnC !mulnA mulnK //.\n  by apply/eqP; rewrite -!mulnA addnS F4 [(v`! * _)%N]mulnC.\nrewrite dvdn_mull // -F4 -addnS mulnDl dvdn_add //; last first.\n  by rewrite /dvdn; apply/eqP; exact: modnMr.\ncase: {1 2}u=> [|u1]; first by exact: dvdn0.\nrewrite -mul_bin_diag.\nby rewrite /dvdn; apply/eqP; exact: modnMr.\nQed.\n\nLemma coef_pTK  n i :\n   ~~ odd (n + i) -> (i <= n)%N ->\n  let k := (n - i)./2 in\n  ('T_n)`_i *+ (n-k).*2 = (-1)^+k * (2^i * n * 'C(n-k,k))%:R :> R.\nProof.\nmove=> O1 L1; rewrite coef_pT; move/negPf: (O1)->.\nmove: (L1); rewrite leqNgt; move/negPf->.\ncase: n L1 O1 => [|n] L1  O1 /=; first by rewrite !muln0 mulr0.\nrewrite -mulrnAr; congr (_ * _); rewrite -mulr_natl -natrM; congr (_%:R).\ncase: i L1 O1 => [|i L1 O1].\n  rewrite addn0 subn0=> _ O1.\n  have F: n.+1 = (n.+1)./2.*2\n    by rewrite-{1}[n.+1]odd_double_half // (negPf O1).\n  have ->: (n.+1 - (n.+1)./2 = (n.+1)./2)%N by rewrite {1}F -addnn addnK.\n  by rewrite -F mul1n mulKn //.\nset u := (n.+1 -i.+1)./2.\nhave F: (n.+1 - i.+1 = u.*2)%N.\n  by rewrite-{1}[(n.+1 - i.+1)%N]odd_double_half\n             /u oddB // -oddD (negPf O1).\nhave->: (n.+1 - u = i.+1 + u)%N.\n  rewrite -{1}(subnK L1) [(_ + i.+1)%N]addnC.\n  by rewrite -addnBA;\n     [rewrite {1}F -addnn addnK | rewrite F -addnn leq_addr].\nrewrite expnS -!mul2n -!mulnA divnMl //;  congr (_ * _)%N.\napply/eqP; rewrite mulnC -dvdn_eq.\nhave->: (n.+1 = u + (i.+1 + u))%N by rewrite addnC -addnA addnn -F addnC subnK.\napply: dvdn_mull.\ncase: {F}u=> [|u]; first by rewrite !muln1 !addn0 dvdnn.\nby rewrite mulnDl dvdn_add //; first rewrite addnS -mul_bin_diag;\n   apply: dvdn_mulr; exact: dvdnn.\nQed.\n\nLemma coef_pTn n : ('T_n)`_n = (2 ^ n.-1)%:R :> R.\nProof.\ncase: n => [|n]; rewrite coef_pT ltnn addnn odd_double //= subnn subn0.\nrewrite mul1r expnS [(2 * _)%N]mulnC -!mulnA [(2 * _)%N]mulnA mul2n.\nby rewrite mulnC -!mulnA mulKn // bin0 mul1n.\nQed.\n\nLemma size_pT_leq n : (size ('T_n) <= n.+1)%N.\nProof.\nby apply/leq_sizeP => j Hj; rewrite coef_pT Hj.\nQed.\n\n(* Pell equation *)\n\nLemma pell n : ('T_n.+1)^+2 - ('X^2 - 1) * ('U_n) ^+ 2 = 1.\nProof.\nsuff F: (pU n.+1)^+ 2 + (pU n)^+2 = 'X *+ 2 * pU n.+1 * pU n + 1.\n  rewrite pT_pU exprS expr1 !mulrDl !mulrDr opprD !mulNr.\n  rewrite !addrA addrC opprK mul1r !addrA [_^+2 + _]addrC F.\n  apply: trans_equal (addr0 _); rewrite [_+1]addrC -!addrA; congr (_ + _).\n  rewrite mulrN mulrA commr_polyX !addrA !mulrDl addrK.\n  rewrite -mulrA -commr_pU mulrA addrN sub0r.\n  by rewrite mulrN opprK -mulrA -commr_pU exprS expr1 exprS expr1 !mulrA addrN.\nelim: n => [| n IH].\n  by rewrite pU1 pU0 mulr1 expr1n exprS expr1.\nrewrite pUSS exprS !mulrBr !mulrBl -!addrA; congr (_ + _).\n  rewrite !(mulrnAl,mulrnAr); do 2 congr (_ *+ _).\n  by rewrite -!mulrA; congr (_ * _); rewrite -commr_pU mulrA.\ncongr (_ + _); first by rewrite -commr_pU -!mulrA commr_pU.\nby rewrite opprB addrC addrA IH [_+1]addrC addrK.\nQed.\nEnd Tcheby.\n\nNotation \"'T_ n \" := (pT _ n)\n  (at level 3, n at level 2, format \"''T_' n\").\n\nLemma induc2 (P: nat -> Prop):\n\tP 0%nat -> P 1%nat -> \n  (forall n, P n -> P (n.+1) -> P (n.+2)) -> forall n, P n.\nProof.\nmove=> HP0 HP1 HPn n.\nelim/ltn_ind : n => [] [|[|n]] IH //.\nby apply: HPn; apply: IH.\nQed.\n\nSection LINEAR_INDEPENDENCE.\nVariable R: unitRingType.\n\nLemma lreg_neq0 (l x: R): GRing.lreg l -> x != 0 -> l * x != 0.\nProof.\nmove => Hl;  apply: contra => /eqP H; apply/eqP.\nby apply: Hl; rewrite H rm0.\nQed.\n\nHypothesis lr2 : GRing.lreg (2%:R : R).\n\nLemma rr2: GRing.rreg (2%:R :R).\nProof.\nmove => x y; rewrite mulr_natr [y*_]mulr_natr -mulr_natl -[y *+ _]mulr_natl => eq.\nby apply lr2.\nQed.\n\nLemma size_pT n : size ('T_ n : {poly R}) = n.+1.\nProof.\nelim/induc2: n => [ | | n ih1 ih2]; first by rewrite pT0 size_poly1.\n\tby rewrite pT1 size_polyX.\nsuff/leP leq: (n.+3 <= size ('T_n.+2: {poly R}))%nat by have/leP leq':= size_pT_leq R (n.+2); lia.\napply: gtn_size.\nrewrite pTSS coefD coef_opp_poly -scaler_nat -scalerAl coefZ coef_mul_poly.\nunder eq_bigr do rewrite coefX.\nrewrite big_ord_recl big_ord_recl big1; last by move => i _ /=; rewrite !rm0.\nrewrite !lift0 -{2 }[ord0.+1]add1n !rm0 !rm1 coef_pTn (coef_pT R n) /=.\nhave ->: (n < n.+2)%N || odd (n + n.+2) by apply /orP; left.\nrewrite rm0 natrX -exprS -[_ ^+ _]mulr1; apply: lreg_neq0; last by rewrite oner_eq0.\nby apply GRing.lregX.\nQed.\n\nLemma pT_neq0 n: 'T_n != 0 :> {poly R}.\nProof. by rewrite -size_poly_eq0 size_pT. Qed.\n\nLemma coef_pTn_reg n: GRing.rreg ('T_n: {poly R})`_n.\nProof. by rewrite coef_pTn natrX; apply /GRing.rregX /rr2. Qed.\n\nLemma size_sum_pT (p: {poly R}):\n\tsize (\\sum_(i < size p) p`_i *: 'T_i) = size p.\nProof.\nrewrite (@size_polybase _ (fun i => 'T_i)) => // [| n ]; first by apply size_pT.\nby rewrite lead_coefE size_pT; apply: coef_pTn_reg.\nQed.\n\nLemma pT_eq (p q : {poly R}):\n\tp = q <->\n\t\\sum_(i < size p) p`_i *: 'T_ i = \\sum_(i < size q) q`_i *: 'T_ i.\nProof.\nsplit=> [->//|/eqP].\nrewrite -(@polybase_widen _ (fun i => 'T_i) _ _ (leq_maxl (size p) (size q))).\nrewrite -(@polybase_widen _ (fun i => 'T_i) _ _ (leq_maxr (size p) (size q))).\nrewrite -subr_eq0 -sumrB.\nunder eq_bigr do rewrite -scalerBl -coefB; move => /eqP eq.\napply: subr0_eq; rewrite -polyP => i; rewrite coef0.\nhave [ineq|ineq]:= (ltnP i (maxn (size p) (size q))).\n\tapply: seqbase_coef_eq0; [exact: size_pT | | exact: eq | exact ineq].\n\tmove => n; rewrite lead_coefE size_pT.\n\texact: coef_pTn_reg.\napply/ leq_sizeP; last apply ineq.\nby rewrite -[size q]size_opp size_add.\nQed.\n\nLemma pT_eq0 (p: {poly R}):\n\tp = 0 <-> \\sum_(i < size p) p`_i *: 'T_i = 0.\nProof. by rewrite pT_eq size_poly0 big_ord0. Qed.\nEnd LINEAR_INDEPENDENCE.\n\nSection Multiplication.\n\nVariable (R: unitRingType).\n\nDefinition absn m n := (m - n + (n - m))%nat.\n\nLemma subn_leq m n : (n <= m -> n - m = 0)%nat.\nProof. by move => ineq; apply /eqP; rewrite subn_eq0. Qed.\n\nLemma absnE m n : absn m n = (if m <= n then n - m else m - n)%nat.\nProof.\nrewrite /absn; case: leqP => H; first by rewrite subn_leq.\nby rewrite [(n - m)%nat]subn_leq ?addn0 // ltnW.\nQed.\n\nLemma absnC : commutative absn.\nProof. by move => m n; rewrite /absn addnC. Qed.\n\nLemma absnn n : absn n n = 0%nat.\nProof. by rewrite /absn !subnn addn0. Qed.\n\nLemma absn_eq0 m n : (absn m n = 0 -> m = n)%nat.\nProof.\nmove=>/eqP; rewrite addn_eq0 => H; apply/eqP.\nby rewrite eqn_leq.\nQed.\n\nLemma absnSS n m : absn m.+1 n.+1 = absn m n.\nProof. by rewrite /absn !subSS. Qed.\n\nLemma abs0n n :\tabsn 0 n = n.\nProof. by rewrite /absn sub0n subn0 add0n. Qed.\n\nLemma absn0 n : absn n 0 = n.\nProof. by rewrite absnC abs0n. Qed.\n\nLemma absn1S n : absn 1 n.+1 = n%nat.\nProof. by rewrite absnSS abs0n. Qed.\n\nLemma absnS1 n : absn n.+1 1 = n%nat.\nProof. by rewrite absnC absn1S. Qed.\n\nLemma absn_max_min m n : (absn m n = maxn m n - minn m n)%nat.\nProof.\nrewrite /absn maxnE minnE.\ncase: (leqP n m) => H.\n  by rewrite subKn // (subn_leq H) !addn0.\nby rewrite (subn_leq) 1?ltnW // subn0 addKn.\nQed.\n\nLemma subn_eq m n p: (p > 0 -> m - n = p -> m = p + n)%nat.\nProof.\nmove => pgt E; rewrite -E subnK //.\nby apply: ltnW; rewrite -subn_gt0 E.\nQed.\n\nLemma absnnD n m : absn n (n + m) = m.\nProof.\nrewrite /absn (subn_leq); last by rewrite leq_addr.\nby rewrite add0n addnC -addnBA// subnn addn0.\nQed.\n\nLemma subnSn n : (n - n.+1 = 0)%nat.\nProof. by elim: n. Qed.\n\nLemma absnif n m:\n\t(absn m n.+1 = if m <= n then (absn m n).+1 else (absn m n).-1)%nat.\nProof.\nrewrite absnC !absnE leqNgt ltnS.\ncase: leqP => //=; first exact: subSn.\nby rewrite subnS.\nQed.\n\nLemma absn_pT n m:\n\t'X *+2 * 'T_(absn m n.+1) - 'T_(absn m n) = 'T_(absn m n.+2) :> {poly R}.\nProof.\nrewrite !absnif; case: leqP => [H|]; first by rewrite ltnW // -pTSS.\nrewrite leq_eqVlt => /orP[/eqP<-|ineq].\n  rewrite leqnn absnC -[n.+1]addn1 absnnD.\n\tby rewrite pT0 pT1 mulr1 -addrA subrr addr0.\nrewrite leqNgt ineq /= -(subnK ineq) -!addSnnS addnC absnC absnnD /=.\nby rewrite pTSS subKr.\nQed.\n\nLemma mul_pT n m :\n\t2%:R *: 'T_n * 'T_m = 'T_(n + m) + 'T_(absn m n) :> {poly R}.\nProof.\nelim/ltn_ind : n m => // [] [|[|n]] IH m.\n- by rewrite pT0 absn0 mulr2n scalerDl scale1r mulrDl mul1r.\n- rewrite pT1 scaler_nat add1n.\n\tcase: m => [|m]; first by rewrite pT0 pT1 /absn rm1 mulr2n.\n\tby rewrite absnS1 pTSS -addrA [-'T_m + 'T_m]addrC subrr rm0.\nrewrite pTSS scalerDr mulrDl -!scalerAl mulNr.\nrewrite scalerN !scalerAl IH; last by rewrite -ltnS ltnW.\nrewrite -scaler_nat -!scalerAl -mulrA -commr_polyX.\nrewrite  scalerAl scalerAl scalerAl IH //.\nrewrite !addSn pTSS scalerDr mulrDl -scalerAl commr_polyX.\nrewrite scalerAl scaler_nat -!addrA.\ncongr (_ + _).\nrewrite opprD addrA [_ - 'T_(n+m)]addrC -addrA.\ncongr (_ + _).\nrewrite -scalerAl commr_polyX scalerAl scaler_nat.\nexact: absn_pT.\nQed.\n\nLemma pT_mulX_weak n :  'X *+ 2 * 'T_n.+1 = 'T_n + 'T_n.+2 :> {poly R}.\nProof. by rewrite pTSS addrCA subrr rm0. Qed.\n\nLemma pT_mulX n :\n  (2%:R : R) \\is a GRing.unit -> 'X * 'T_n.+1 = 2%:R ^-1 *: 'T_n + 2%:R ^-1 *: 'T_n.+2 :> {poly R}.\nProof.\nmove => I2; rewrite pTSS scalerDr addrCA scalerN subrr addr0.\nby rewrite -scaler_nat -scalerAl scalerA mulVr // scale1r.\nQed.\nEnd Multiplication.\n\nSection pTab.\n\nVariable R: fieldType.\n\nDefinition Tab (a b: R) := \t(1 + 1)/(b - a) *: 'X + (- (a + b) / (b - a))%:P.\n\nLemma Taba a b: b != a -> (Tab a b).[a] = -1.\nProof.\nmove =>neq; rewrite /Tab !hornerE.\nrewrite opprD !mulrDl mul1r mulrC addrA -[a / (b - a) + _ + _]addrA.\nrewrite mulNr subrr rm0 -mulrDl -[a-b]opprB mulNr divrr //.\nby rewrite unitfE; apply: contra neq => eq; rewrite -subr_eq0.\nQed.\n\nLemma Tabb a b: b != a -> (Tab a b).[b] = 1.\nProof.\nmove => neq; rewrite /Tab !hornerE.\nrewrite opprD !mulrDl mul1r mulrC addrC addrA -[- a / (b - a) + _ + _]addrA.\nrewrite [- b / (b- a) + _]addrC [- b / _]mulNr subrr rm0 addrC -mulrDl divrr //.\nby rewrite unitfE; apply: contra neq => eq; rewrite -subr_eq0.\nQed.\n\nDefinition pTab a b n := 'T_n \\Po (Tab a b).\n\nNotation \"''T^(' a ',' b ')_' n\" := (pTab a b n)\n  (at level 3, n at level 2, format \"''T^(' a ',' b ')_' n\").\n\nLemma size_pTab n a b :\n   2%:R != 0 :> R -> a != b -> size ('T^(a,b)_n) = n.+1.\nProof.\nmove=> H aDb.\nhave D :  b + - a != 0 by rewrite subr_eq0 eq_sym.\nhave E : GRing.lreg ((1 + 1) / (b - a)).\n  by apply/GRing.lregM; apply/lregP => //; apply: invr_neq0.\nrewrite size_comp_poly2 ?size_pT //; first by apply/lregP.\nrewrite /Tab size_addl lreg_size ?size_polyX //.\nby rewrite size_polyC; case: (_ == _).\nQed.\n\n(* The condition GRing.lreg (2%:R : R) is unnecessary but makes live easier *)\nLemma coef_pTab n a b :\n  2%:R != 0 :> R -> 'T^(a, b)_n`_n = (2^n.*2.-1)%:R /(b - a)^+n.\nProof.\nmove=> H.\nrewrite ['T^(a, b)_n]comp_polyE coef_sum.\nhave rTA k : k%:R = (k%:R)%:A :> {poly R}.\n    elim: k => /= [|k IH]; first by rewrite !rm0.\n    by rewrite -addn1 !natrD IH scalerDl !rm1 /= scale1r.\nhave F : (n < size ('T_n : {poly R}))%nat by rewrite size_pT //; apply/lregP.\nrewrite (bigD1 (Ordinal F)) //= big1 => [|i /eqP/val_eqP /= H1]; last first.\n  rewrite coefZ exprDn coef_sum big1 => [|j _]; first by rewrite rm0.\n  rewrite -mulr_natl -polyC_exp mulrCA mulrC.\n  rewrite rTA alg_polyC -polyCM coefCM exprZn coefZ.\n  rewrite coefXn.\n  have : (i < n.+1)%nat.\n    by rewrite -[n.+1](@size_pT R) //; apply/lregP.\n  rewrite ltnS leq_eqVlt (negPf H1) /= => HH.\n  have : (i - j < n)%nat.\n    by apply: leq_ltn_trans (leq_subr _ _) HH.\n  rewrite ltn_neqAle eq_sym => /andP[/negPf-> _].\n  by rewrite !rm0.\nrewrite coefZ addr0 exprDn coef_sum.\nrewrite big_ord_recl /= big1 => [|i _].\n  rewrite !rm0 bin0 !rm1 subn0 exprZn coef_pTn.\n  rewrite coefZ coefXn eqxx rm1 -[1 + 1]/(2%:R).\n  rewrite expr_div_n mulrA -natrX -natrM -expnD.\n  by congr ((_ ^ _)%:R / _); rewrite -addnn; case: (n).\nrewrite [bump _ _]add1n.\nrewrite -mulr_natl -polyC_exp mulrCA mulrC.\nrewrite rTA alg_polyC -polyCM coefCM exprZn coefZ coefXn.\ncase: i => ii /= _; case: (n) => [|nn].\n  by rewrite bin0n !rm0.\nhave : (nn.+1 - ii.+1 < nn.+1)%nat.\n  by apply: leq_ltn_trans (leq_subr _ _) (ltnSn _).\nrewrite ltn_neqAle eq_sym => /andP[/negPf-> _].\nby rewrite !rm0.\nQed.\n\nLemma horner_pTab a b n (x: R) :\n  ('T^(a,b)_n).[x] = ('T_n).[(x*+2 - a - b) / (b - a)].\nProof.\nrewrite /pTab horner_comp /Tab.\nrewrite hornerD hornerZ hornerX hornerC.\ncongr (_.[_]).\nrewrite mulr2n -{2 3}[x]mul1r -[1 * x + 1 * x]mulrDl -addrA [RHS]mulrDl.\nby rewrite -[-a-b]opprD -{3}[b-a]mulr1 -mulf_div divr1.\nQed.\n\nLemma horner_pTab_a a b n :\n\tb != a -> \t('T^(a,b)_n).[a] = ('T_n).[-1].\nProof. by move => ineq; rewrite /pTab horner_comp Taba. Qed.\n\nLemma horner_pTab_b a b n :\n\tb != a -> ('T^(a,b)_n).[b] = ('T_n).[1].\nProof. by move => ineq; rewrite /pTab horner_comp Tabb. Qed.\n\nDefinition CPolyab a b l : {poly R} := \\sum_(i < (size l)) l`_i *: 'T^(a,b)_i.\n\nLemma CPolyabN a b p :\n  (CPolyab a b [seq - i | i <- p] = - (CPolyab a b p)).\nProof.\nrewrite /CPolyab size_map -sumrN.\napply: eq_bigr => i _.\nby rewrite (nth_map 0) // scaleNr.\nQed.\n\nLemma CPolyabD a b p q :\n  size p = size q ->\n  (CPolyab a b [seq i.1 + i.2 | i <- (zip p q)] =\n     CPolyab a b p + CPolyab a b q).\nProof.\nmove=> Hs.\nrewrite /CPolyab size_map size1_zip // Hs ?leqnn // -big_split.\napply: eq_bigr => i _.\nby rewrite (nth_map 0) ?size2_zip ?Hs // scalerDl nth_zip.\nQed.\n\nLemma CPolyabB a b p q :\n  size p = size q ->\n  (CPolyab a b [seq i.1 - i.2 | i <- (zip p q)] =\n     CPolyab a b p - CPolyab a b q).\nProof.\nmove=> Hs.\nrewrite /CPolyab size_map size1_zip // Hs ?leqnn // -sumrB.\napply: eq_bigr => i _.\nby rewrite (nth_map 0) ?size2_zip ?Hs // scalerBl nth_zip.\nQed.\n\nEnd pTab.\n\nNotation \"''T^(' a ',' b ')_' n\" := (pTab a b n)\n  (at level 3, n at level 2, format \"''T^(' a ',' b ')_' n\").\n\nRequire Import Rstruct.\n\nSection Int.\n\nVariable R: fieldType.\n\nLemma deriv_pT0 : ('T_1)^`() = 'T_0 :> {poly R}.\nProof. by rewrite pT1 pT0 derivX. Qed.\n\nLemma deriv_pT1 : [char R]%RR =i pred0 -> \n  (4%:R^-1 *: 'T_2)^`() = 'T_1 :> {poly R}.\nProof.\nmove=> /GRing.charf0P Hf.\nrewrite derivZ pTSS pT1 pT0 mulrnAl derivB derivMn -expr2 derivXn derivC.\nby rewrite subr0 -mulrnA -scaler_nat scalerA mulVf ?Hf ?scale1r.\nQed.\n\nLemma deriv_pTSS n: (1 < n)%nat -> [char R]%RR =i pred0 -> \n  (n.+1.*2%:R^-1 *: 'T_n.+1 - n.-1.*2%:R^-1 *: 'T_n.-1)^`() = \n    'T_n :> {poly R}.\nProof.\ncase: n => [] // [] // n _ /GRing.charf0P Hf.\nrewrite !(derivB, derivZ, deriv_pT) -!scaler_nat !scalerA.\ndo 2 rewrite -muln2 natrM invfM mulrC mulrA mulfV ?Hf // mul1r.\nrewrite -scalerBr pT_pU pUSS -addrA -opprD -mulr2n mulrnAl -mulrnBl.\nrewrite -[(_ + _) *+ _]scaler_nat scalerA mulVf ?Hf // scale1r.\nby rewrite addrAC mulr2n addrK.\nQed.\n\nVariables a b : R.\n\nLemma deriv_Tab : (Tab  a b )^`() = ((1 + 1) / (b - a))%:P.\nProof. by rewrite !derivE addr0 alg_polyC. Qed.\n\nLemma deriv_pTabn n : \n  ('T^(a,b)_n)^`() = 2%:R / (b - a) *: (('T_n)^`() \\Po Tab a b).\nProof. by rewrite deriv_comp deriv_Tab [_ * _%:P]mulrC mul_polyC. Qed.\n\nLemma deriv_pTab0 : a != b -> 2%:R != 0 :> R ->\n ((b - a) / 2%:R *: 'T^(a,b)_1)^`() = 'T^(a,b)_0 :> {poly R}.\nProof.\nmove=> aDb twoNZ.\nrewrite !derivE deriv_pTabn deriv_pT0 scalerA.\nby rewrite mulrA divfK // mulfV ?scale1r // subr_eq0 eq_sym.\nQed.\n\nLemma deriv_pTab1 : a != b -> [char R]%RR =i pred0 -> \n  (((b - a)/ 8%:R) *: 'T^(a,b)_2)^`() = 'T^(a,b)_1 :> {poly R}.\nProof.\nrewrite eq_sym -subr_eq0 => bDaNeq0 Hc.\nhave /GRing.charf0P Hf := Hc.\nrewrite !derivE deriv_pTabn scalerA mulrAC !mulrA [_ * 2%:R]mulrC mulfK //.\nrewrite -[8%:R]/((2 * 4)%:R) natrM invfM mulrA mulfV ?Hf // mul1r.\nby rewrite -comp_polyZ -derivZ deriv_pT1.\nQed.\n\nLemma deriv_pTabSS n: (1 < n)%nat -> a != b -> [char R]%RR =i pred0 -> \n  ((b - a) / 2%:R *: (n.+1.*2%:R^-1 *:\n    'T^(a,b)_n.+1 - n.-1.*2%:R^-1 *: 'T^(a,b)_n.-1))^`() = \n    'T^(a,b)_n :> {poly R}.\nProof.\nrewrite eq_sym -subr_eq0 => n_gt1 bDaNeq0 Hc.\nhave /GRing.charf0P Hf := Hc.\nrewrite !derivE !deriv_pTabn.\nrewrite !scalerA ![_ * (_ / _)]mulrC -!scalerA -!scalerBr !scalerA.\nrewrite !divfK ?Hf // mulfV // scale1r.\nby rewrite -!comp_polyZ -comp_polyB -!derivE deriv_pTSS.\nQed.\n\nVariable f : nat -> R.\n\nVariable k : nat.\nHypothesis fk1 : f (k.+1) = 0.\nHypothesis fk2 : f (k.+2) = 0.\n\n\nLemma deriv_sum_pT : (0 < k)%N -> [char R]%RR =i pred0 -> \n  ((f 0 / 2%:R) *: 'T_1 + \n    \\sum_(1 <= i < k.+2) ((f i.-1 - f i.+1) / (i.*2%:R)) *: 'T_i)^`() = \n    \\sum_(0 <= i < k.+1) f i *: 'T_i.\nProof.\nmove=> k_gt0 Hc.\nhave /GRing.charf0P Hf := Hc.\nunder eq_bigr do rewrite mulrBl scalerBl.\nrewrite sumrB.\nrewrite big_add1.\nhave <-/= := @big_add1 _ _ _ 1 k.+4.-1 xpredT (fun i => (f i / i.-1.*2%:R) *: 'T_i.-1).\nrewrite big_ltn // big_ltn //.\nrewrite [\\sum_(_ <= _ < _.+3) _]big_nat_recr //= fk2 mul0r scale0r addr0.\nrewrite [\\sum_(_ <= _ < _.+2) _]big_nat_recr //= fk1 mul0r scale0r addr0.\nrewrite -!addrA -sumrB.\nunder eq_bigr do rewrite -!scalerA -scalerBr.\nrewrite !derivE !deriv_pT0 -[_ *: _^`()]scalerA -derivE deriv_pT1 //.\nrewrite addrA -scalerDl -mulrDr -mulr2n -mulr_natl mulfV ?Hf // mulr1.\nrewrite (big_morph _ (@derivD R) (@deriv0 R)).\nrewrite [RHS]big_ltn //; congr (_ + _).\nrewrite [RHS]big_ltn //; congr (_ + _).\nrewrite [RHS]big_nat_cond [LHS]big_nat_cond.\napply: eq_bigr => i /andP[/andP[i_gt1 iLk _]].\nby rewrite derivE deriv_pTSS.\nQed.\n\nLemma deriv_sum_pTab : (0 < k)%N -> a != b -> [char R]%RR =i pred0 -> \n  (((b - a) / 2%:R * (f 0 / 2%:R)) *: 'T^(a,b)_1 + \n    \\sum_(1 <= i < k.+2)\n       ((b - a) / 2%:R * (f i.-1 - f i.+1) / (i.*2%:R)) *: 'T^(a,b)_i)^`() = \n    \\sum_(0 <= i < k.+1) f i *: 'T^(a,b)_i.\nProof.\nmove => k_gt0 aDb Hc.\nhave /GRing.charf0P Hf := Hc.\nunder eq_bigr do rewrite mulrBr mulrBl scalerBl.\nrewrite sumrB.\nrewrite big_add1.\nhave <-/= := @big_add1 _ _ _ 1 k.+4.-1 xpredT \n             (fun i => ((b - a) / 2%:R  * f i / i.-1.*2%:R) *: 'T^(a,b)_i.-1).\nrewrite big_ltn // big_ltn //.\nrewrite [\\sum_(_ <= _ < _.+3) _]big_nat_recr //= fk2 mulr0 mul0r scale0r addr0.\nrewrite [\\sum_(_ <= _ < _.+2) _]big_nat_recr //= fk1 mulr0 mul0r scale0r addr0.\nrewrite -!addrA -sumrB.\nunder eq_bigr do rewrite -!scalerA -scalerBr.\nrewrite !derivE.\nrewrite addrA -scalerDl mulrA -mulrDr -mulrA mulrC.\nrewrite -[_ *:  'T^(a,b)_1^`()]scalerA.\nrewrite -[_ *: 'T^(a,b)_1^`()]derivE deriv_pTab0 ?Hf //.\nrewrite -mulr2n -mulr_natl mulfV ?Hf // mulr1.\nrewrite [RHS]big_ltn //; congr (_ _ _).\nrewrite [_ * f 1]mulrC -2!mulrA -invfM ?Hf // -natrM -scalerA.\nrewrite -derivE deriv_pTab1 //.\nrewrite [RHS]big_ltn //; congr (_ _ _).\nrewrite (big_morph _ (@derivD R) (@deriv0 R)).\nrewrite [RHS]big_nat_cond [LHS]big_nat_cond.\napply: eq_bigr => i /andP[/andP[i_gt1 iLk _]].\nby rewrite -!scalerBr !scalerA mulrC -scalerA derivE deriv_pTabSS.\nQed.\n\n\n\nEnd Int.", "meta": {"author": "FlorianSteinberg", "repo": "Cheby", "sha": "2b082ee667336fa6872d00085270c7656becf2bd", "save_path": "github-repos/coq/FlorianSteinberg-Cheby", "path": "github-repos/coq/FlorianSteinberg-Cheby/Cheby-2b082ee667336fa6872d00085270c7656becf2bd/CPoly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463334, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.6824901270611936}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import Psatz.\n\nRequire Import kernel_numeric.\n\nNotation \"'all' i : V , P\" := (forall i : nat, i < V -> P) (at level 20, i at level 99).\nNotation \"'some' i : V , P\" := (exists i : nat, i < V /\\ P) (at level 20, i at level 99).\n\nStructure Graph := {\n  V :> nat ; (* The number of vertices. So the vertices are numbers 0, 1, ..., V-1. *)\n  E :> nat -> nat -> Prop ; (* The edge relation *)\n  E_decidable : forall x y : nat, ({E x y} + {~ E x y}) ;\n  E_irreflexive : all x : V, ~ E x x ;\n  E_symmetric : all x : V, all y : V, (E x y -> E y x)\n}.\n\nTheorem simetricnost_povezav (G : Graph):\n  (all x : V G , all y : V G, \n  ((if E_decidable G x y then 1 else 0) = \n  (if E_decidable G y x then 1 else 0))).\nProof.\n  intros x p y q.\n  destruct (E_decidable G x y); destruct (E_decidable G y x).\n  - auto.\n  - firstorder using E_symmetric.\n  - firstorder using E_symmetric.\n  - auto.\nQed.\n\n(** Given a decidable predicate [P] on [nat], we can count how many numbers up to [n] satisfy [P]. *)\nDefinition count (n : nat) {P : nat -> Prop} (decP : forall x, {P x} + {~ P x})  :=\n  sum' n (fun x => if decP x then 1 else 0).\n\n(** The number of edges in a graph. *)\nDefinition edges (G : Graph) : nat :=\n  sum' (V G) (fun x => count x (E_decidable G x)).\n\n(** The degree of a vertex. We define it so that it\n    return 0 if we give it a number which is not\n    a vertex. *)\nDefinition degree (G : Graph) (x : nat) :=\n  count (V G) (E_decidable G x).\n\n(*\nTheorem hand_shake (G : Graph) :\n  2 * edges G = sum' (V G) (degree G).\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/compact_old_version/kernel_graph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6824164140801291}}
{"text": "(* Exercise 3 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_003 :\n  (forall x y : D, R x y -> ~ R y x)\n->\n  forall x : D, ~ R x x.\nProof.\nimp_i a1.\nall_i a.\nneg_i (R a a) a2.\nimp_e (R a a).\nall_e (forall y:D, R a y -> ~R y a) a.\nall_e (forall x:D, forall y:D, (R x y -> ~R y x)) a.\nhyp a1.\nhyp a2.\nhyp a2.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak11/Taak11_pred003.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6823926087839182}}
{"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(* ** Luca's theorem *)\n\nRequire Import Arith Nat Lia List.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac gcd prime binomial sums rel_iter.\n\nFrom Undecidability.H10.ArithLibs \n  Require Import Zp.\n\nSet Implicit Arguments.\n\nSet Default Proof Using \"Type\".\n\nLocal Notation power := (mscal mult 1).\nLocal Notation expo := (mscal mult 1).\n\nSection fact.\n\n  Let factorial_cancel n a b : fact n * a = fact n * b -> a = b.\n  Proof.\n    apply Nat.mul_cancel_l.\n    generalize (fact_gt_0 n); intro; lia.\n  Qed.\n  \n  Notation Π := (msum mult 1).\n\n  Notation mprod_an := (fun a n => Π n (fun i => i+a)).\n\n  Fact mprod_factorial n : fact n = mprod_an 1 n.\n  Proof.\n    induction n as [ | n IHn ].\n    + rewrite msum_0; auto.\n    + rewrite msum_plus1; auto.\n      rewrite mult_comm, <- IHn, fact_S.\n      f_equal; lia.\n  Qed.\n\n  Variable (p : nat) (Hp : p <> 0).\n\n  Notation \"〚 x 〛\" := (nat2Zp Hp x).\n\n  Let expo_p_cancel n a b : expo n p * a = expo n p * b -> a = b.\n  Proof.\n    apply Nat.mul_cancel_l.\n    generalize (power_ge_1 n Hp); intros; lia.\n  Qed.\n\n  Fact mprod_factorial_Zp i n :〚mprod_an (i*p+1) n〛=〚fact n〛.\n  Proof.\n    rewrite mprod_factorial.\n    induction n as [ | n IHn ].\n    + do 2 rewrite msum_0; auto.\n    + do 2 (rewrite msum_plus1; auto).\n      do 2 rewrite nat2Zp_mult; f_equal; auto.\n      apply nat2Zp_inj.\n      rewrite (plus_comm n), <- plus_assoc, plus_comm.\n      rewrite <- rem_plus_div; auto.\n      * f_equal; lia.\n      * apply divides_mult, divides_refl.\n  Qed.\n\n  Notation φ := (fun n r => mprod_an (n*p+1) r).\n  Notation Ψ := (fun n => Π n (fun i => mprod_an (i*p+1) (p-1))).\n\n  Let phi_Zp_eq n r :〚φ n r〛=〚fact r〛.\n  Proof. apply mprod_factorial_Zp. Qed.\n\n  Fact mprod_factorial_mult n : fact (n*p) = expo n p * fact n * Ψ n.\n  Proof using Hp.\n    induction n as [ | n IHn ].\n    + rewrite Nat.mul_0_l, msum_0, mscal_0, fact_0; auto.\n    + replace (S n*p) with (n*p+p) by ring.\n      rewrite mprod_factorial, msum_plus, <- mprod_factorial; auto.\n      replace p with (S (p-1)) at 2 by lia.\n      rewrite msum_plus1; auto.\n      rewrite <- plus_assoc.\n      replace (p-1+1) with p by lia.\n      replace (n*p+p) with ((S n)*p) by ring.\n      rewrite mscal_S, fact_S, msum_S.\n      rewrite IHn.\n      repeat rewrite mult_assoc.\n      rewrite (mult_comm _ p).\n      repeat rewrite <- mult_assoc.\n      do 2 f_equal.\n      rewrite (mult_comm (S n)).\n      repeat rewrite <- mult_assoc; f_equal.\n      repeat rewrite mult_assoc; f_equal.\n      rewrite msum_ext with (f := fun i => n*p+i+1)\n                            (g := fun i => i+(n*p+1)).\n      2: intros; ring. \n      rewrite <- msum_plus1; auto.\n  Qed.\n \n  Lemma mprod_factorial_euclid n r : fact (n*p+r) = expo n p * fact n * φ n r * Ψ n.\n  Proof using Hp.\n    rewrite mprod_factorial, msum_plus; auto.\n    rewrite <- mprod_factorial.\n    rewrite msum_ext with (f := fun i => n*p+i+1)\n                          (g := fun i => i+(n*p+1)).\n    2: intros; ring. \n    rewrite mprod_factorial_mult; auto; ring.\n  Qed.\n\n  Notation Zp := (Zp_zero Hp).\n  Notation Op := (Zp_one Hp).\n  Notation \"∸\" := (Zp_opp Hp).\n  Infix \"⊗\" := (Zp_mult Hp) (at level 40, left associativity).\n  Notation expoZp := (mscal (Zp_mult Hp) (Zp_one Hp)).\n\n  Hint Resolve Nat_mult_monoid : core.\n\n  Let Psi_Zp_eq n :〚Ψ n〛= expoZp n〚fact (p-1)〛.\n  Proof.\n    induction n as [ | n IHn ].\n    + rewrite msum_0, mscal_0; auto.\n    + rewrite msum_plus1, nat2Zp_mult.\n      rewrite mscal_plus1; auto.\n      2: apply Zp_mult_monoid.\n      2: apply Nat_mult_monoid.\n      f_equal; auto.\n  Qed.\n\n  Hypothesis (Hprime : prime p).\n\n  Let phi_Zp_invertible n r : r < p -> Zp_invertible Hp 〚φ n r〛.\n  Proof.\n    intros H; simpl; rewrite phi_Zp_eq.\n    apply Zp_invertible_factorial; auto.\n  Qed.\n\n  Let Psi_Zp_invertible n : Zp_invertible Hp 〚Ψ n〛.\n  Proof.\n    simpl; rewrite (Psi_Zp_eq n).\n    apply Zp_expo_invertible, Zp_invertible_factorial; auto; lia.\n  Qed.\n\n  (* rewrite the binomial theorem\n\n               fact k * fact (n-k) * binomial n k = fact n   \n\n      when      \n\n         k = K*p + k0\n         n = N*p + n0\n\n      with\n       \n      1)  K <= N & k0 <= n0\n   \n      we get n-k = (N-K)*p + (n0-k0) and\n\n        expo K     p * fact K     * φ K      k0     * Ψ K\n      .* expo (N-K) p * fact (N-K) * φ (N-K) (n0-k0) * Ψ (N-K)\n      .* binomial n k \n      = expo N p     * fact N     * φ N      n0     * Ψ N.\n\n      hence, simplifying by expo N p  we get\n\n        fact K * fact (N-K) * φ K k0 * Ψ K * φ (N-K) (n0-k0) * Ψ (N-K) * binomial n k = fact N * φ N n0 * Ψ N. \n\n      then in Z/Zp we derive (modulo Wilson's theorem, unnecessary here〚fact (p-1)〛=〚-1〛) \n\n       〚fact K〛⊗〚fact (N-K)〛⊗〚fact k0〛⊗〚-1〛^K⊗〚fact (n0-k0)〛⊗〚-1〛^(N-K)⊗〚binomial n k〛\n      =〚fact N〛⊗〚fact n0〛⊗〚-1〛^N\n\n        that we combine with 〚fact K〛⊗〚fact (N-K)〛⊗〚binomial N K〛=〚fact N〛\n                        and  〚fact k0〛⊗〚fact (n0-k0)〛⊗〚binomial n0 k0〛=〚fact n0〛\n\n        to derive the result:〚binomial n k 〛=〚binomial N K〛⊗〚binomial n0 k0〛\n\n      with \n \n      2) K < N & n0 < k0\n\n      we have n-k = (N-(K+1))*p + (p-(k0-n0)) and\n\n        expo K         p * fact K         * φ K          k0         * Ψ K\n      .* expo (N-(K+1)) p * fact (N-(K+1)) * φ (N-(K+1)) (p-(k0-n0)) * Ψ (N-(K+1))\n      .* binomial n k \n      = expo N p     * fact N     * φ N      n0     * Ψ N.\n\n      hence\n \n         fact K * φ K k0 * Ψ K * fact (N-(K+1)) * φ (N-(K+1)) (p-(k0-n0)) * Ψ (N-(K+1)) * binomial n k \n       = p * ....\n\n      then in Z/Zp all the left factor are invertible except binomial n k which must thus be〚0〛 *)\n\n  Section binomial_without_p_not_zero.\n\n    Variable (n N n0 k K k0 : nat) (Hn : n = N*p+n0) (Hk : k = K*p+k0) (H1 : K <= N) (H2 : k0 <= n0).\n\n    Let Hkn : k <= n.\n    Proof.\n      rewrite Hn, Hk.\n      replace N with (K+(N-K)) by lia.\n      rewrite Nat.mul_add_distr_r.\n      generalize ((N-K)*p); intros; lia.\n    Qed.\n   \n    Let Hnk : n - k = (N-K)*p+(n0-k0).\n    Proof.\n      rewrite Hn, Hk, Nat.mul_sub_distr_r.\n      cut (K*p <= N*p).\n      + generalize (K*p) (N*p); intros; lia.\n      + apply mult_le_compat; auto.\n    Qed.\n  \n    Fact binomial_wo_p : φ K k0 * Ψ K * φ (N-K) (n0-k0) * Ψ (N-K) * binomial n k \n                       = binomial N K * φ N n0 * Ψ N.\n    Proof using Hkn.\n      apply (factorial_cancel (N-K)); repeat rewrite mult_assoc.\n      rewrite (mult_comm (fact _) (binomial _ _)).\n      apply (factorial_cancel K); repeat rewrite mult_assoc.\n      rewrite (mult_comm (fact _) (binomial _ _)).\n      rewrite <- binomial_thm; auto.\n      apply expo_p_cancel with N.\n      repeat rewrite mult_assoc.\n      rewrite <- mprod_factorial_euclid, <- Hn.\n      rewrite binomial_thm with (1 := Hkn).\n      rewrite Hnk. \n      rewrite Hk at 3.\n      replace N with (K+(N-K)) at 1 by lia.\n      rewrite power_plus.\n      do 2 rewrite mprod_factorial_euclid.\n      ring.\n    Qed.\n\n    Hypothesis (Hn0 : n0 < p).\n\n    Hint Resolve Zp_mult_monoid : core.\n\n    Fact binomial_Zp_prod :〚binomial n k〛=〚binomial N K〛⊗〚binomial n0 k0〛.\n    Proof using Hkn Hn0 Hprime.\n      generalize binomial_wo_p; intros G.\n      apply f_equal with (f := nat2Zp Hp) in G.\n      repeat rewrite nat2Zp_mult in G.\n      repeat rewrite Psi_Zp_eq in G.\n      repeat rewrite phi_Zp_eq in G.\n      rewrite binomial_thm with (1 := H2) in G.\n      repeat rewrite nat2Zp_mult in G.\n      rewrite (Zp_mult_comm _ _〚 fact k0 〛) in G.\n      repeat rewrite Zp_mult_assoc in G.\n      rewrite (Zp_mult_comm _ _〚 fact k0 〛) in G.\n      repeat rewrite <- Zp_mult_assoc in G.\n      apply Zp_invertible_cancel_l in G.\n      2: apply Zp_invertible_factorial; auto; lia.\n      repeat rewrite Zp_mult_assoc in G.\n      do 2 rewrite (Zp_mult_comm _ _〚 fact _ 〛) in G.\n      repeat rewrite <- Zp_mult_assoc in G.\n      apply Zp_invertible_cancel_l in G.\n      2: apply Zp_invertible_factorial; auto; lia.\n      repeat rewrite Zp_mult_assoc in G.\n      rewrite <- mscal_plus in G; auto.\n      replace (K+(N-K)) with N in G by lia.\n      rewrite (Zp_mult_comm _ _ (expoZp _ _)) in G.\n      apply Zp_invertible_cancel_l in G; trivial.\n      apply Zp_expo_invertible, Zp_invertible_factorial; auto; lia.\n    Qed.\n\n  End binomial_without_p_not_zero.\n\n  Section binomial_without_p_zero.\n\n    Variable (n N n0 k K k0 : nat) (Hn : n = N*p+n0) (Hk : k = K*p+k0) \n             (H1 : K < N) (H2 : n0 < k0) (Hk0 : k0 < p).\n\n    Let H3 : p - (k0-n0) < p.    Proof. lia. Qed.\n    Let H4 : S (N-1) = N.        Proof. lia. Qed.\n    Let H5 : N-1 = K+(N-(K+1)).  Proof. lia. Qed.\n    Let H6 : N = K+1+(N-(K+1)).  Proof. lia. Qed.\n    Let HNK : N-K = S (N-(K+1)). Proof. lia. Qed.\n\n    Let Hkn : k <= n.\n    Proof.\n      rewrite Hn, Hk, H6.\n      do 2 rewrite Nat.mul_add_distr_r.\n      generalize ((N-(K+1))*p); clear H3 H4 H5 H6 HNK; intros; lia.\n    Qed.\n   \n    Let Hnk : n - k = (N-(K+1))*p+(p-(k0-n0)).\n    Proof.\n      rewrite Hn, Hk, Nat.mul_sub_distr_r.\n      cut ((K+1)*p <= N*p).\n      + rewrite Nat.mul_add_distr_r.\n        generalize (K*p) (N*p); clear H3 H4 H5 H6 HNK Hkn; intros; lia.\n      + apply mult_le_compat; auto; clear H3 H4 H5 H6 HNK Hkn; lia.\n    Qed.\n\n    Fact binomial_with_p : fact K * fact (N-(K+1)) * φ K k0 * Ψ K * φ (N-(K+1)) (p-(k0-n0)) * Ψ (N-(K+1)) * binomial n k \n                         = p * fact N * φ N n0 * Ψ N.\n    Proof using Hkn.\n      apply expo_p_cancel with (N-1).\n      repeat rewrite mult_assoc.\n      rewrite (mult_comm (expo _ _) p).\n      rewrite <- mscal_S.\n      rewrite H4, <- mprod_factorial_euclid, <- Hn.\n      rewrite binomial_thm with (1 := Hkn).\n      rewrite Hnk.\n      rewrite Hk at 3.\n      do 2 rewrite mprod_factorial_euclid.\n      rewrite H5 at 1.\n      rewrite power_plus.\n      ring.\n    Qed.\n\n    Fact binomial_with_p' : φ K k0 * Ψ K * φ (N-(K+1)) (p-(k0-n0)) * Ψ (N-(K+1)) * binomial n k \n                          = p * binomial N K * (N-K) * φ N n0 * Ψ N.\n    Proof using Hkn.\n      apply (factorial_cancel (N-(K+1))); repeat rewrite mult_assoc.\n      apply (factorial_cancel K); repeat rewrite mult_assoc.\n      rewrite binomial_with_p.\n      rewrite binomial_thm with (n := N) (p := K).\n      2: { apply lt_le_weak; auto. }\n      rewrite HNK at 1.\n      rewrite fact_S.\n      rewrite <- HNK.\n      ring.\n    Qed.\n \n    Fact binomial_Zp_zero :〚binomial n k〛= Zp.\n    Proof using Hkn Hprime.\n      generalize binomial_with_p'; intros G.\n      apply f_equal with (f := nat2Zp Hp) in G.\n      repeat rewrite nat2Zp_mult in G.\n      rewrite nat2Zp_p in G.\n      repeat rewrite Zp_mult_zero in G.\n      apply Zp_invertible_eq_zero in G; auto.\n      repeat (apply Zp_mult_invertible; auto).\n    Qed.\n\n  End binomial_without_p_zero.\n\nEnd fact.\n\nSection lucas_lemma.\n\n  (* https://math.stackexchange.com/questions/1463758/proof-of-lucas-theorem-without-the-polynomial-hint *)\n\n  Variables (p : nat) (Hprime : prime p).\n\n  Let Hp : p <> 0.\n  Proof.\n    generalize (prime_ge_2 Hprime); intro; lia.\n  Qed.\n\n  Variables (n N n0 k K k0 : nat)\n            (G1 : n = N*p+n0)  (G2 : n0 < p)\n            (G3 : k = K*p+k0)  (G4 : k0 < p).\n\n  Let choice : (K <= N  /\\ k0 <= n0)\n            \\/ (n0 < k0 /\\ K < N)\n            \\/ ((n0 < k0 \\/ N < K) /\\ n < k).\n  Proof.\n    destruct (le_lt_dec k n) as [ H0 | H0 ];\n    destruct (le_lt_dec k0 n0) as [ H1 | H1 ];\n    destruct (le_lt_dec K N) as [ H2 | H2 ]; try lia.\n    + do 2 right; split; auto.\n      rewrite G1, G3.\n      replace K with (N+1+(K-N-1)) by lia.\n      do 2 rewrite Nat.mul_add_distr_r.\n      generalize ((K-N-1)*p); intros; lia.\n    + destruct (eq_nat_dec N K); try lia.\n    + do 2 right; split; auto.\n      rewrite G1, G3.\n      replace K with (N+1+(K-N-1)) by lia.\n      do 2 rewrite Nat.mul_add_distr_r.\n      generalize ((K-N-1)*p); intros; lia.\n  Qed.\n\n  Theorem lucas_lemma : rem (binomial n k) p = rem (binomial N K * binomial n0 k0) p.\n  Proof using choice.\n    destruct choice as [ (H1 & H2) \n                     | [ (H1 & H2)\n                       | (H1 & H2) ] ]; clear choice.\n    3: { rewrite binomial_gt with (1 := H2).\n         f_equal.\n         destruct H1 as [ H1 | H1 ]; \n           rewrite binomial_gt with (1 := H1); ring. }\n    + apply nat2Zp_inj with (Hp := Hp).\n      rewrite nat2Zp_mult.\n      apply binomial_Zp_prod; auto.\n    + rewrite binomial_gt with (1 := H1).\n      rewrite Nat.mul_0_r.\n      apply nat2Zp_inj with (Hp := Hp).\n      rewrite nat2Zp_zero.\n      apply binomial_Zp_zero with (2 := G1) (3 := G3); auto.\n  Qed.\n\nEnd lucas_lemma.\n\n(* Eval compute in binomial 3 0. *)\n\nSection lucas_theorem.\n\n  Variable (p : nat) (Hp : prime p).\n\n  Implicit Types (l m : list nat).\n\n  (* base_p [x0;x1;x2;...] =  x0 + x1*p + x2*p² ...*)\n\n  Notation base_p := (expand p).\n\n  Fixpoint binomial_p l :=\n    match l with\n      | nil  => fix loop m := match m with\n        | nil  => 1\n        | y::m => binomial 0 y * loop m\n      end\n      | x::l => fun m => match m with\n        | nil   => binomial x 0 * binomial_p l nil \n        | y::m  => binomial x y * binomial_p l m\n      end\n    end.\n\n  Fact binomial_p_fix00 : binomial_p nil nil = 1.\n  Proof. auto. Qed.\n\n  Fact binomial_p_fix01 y m : binomial_p nil (y::m) = binomial 0 y * binomial_p nil m.\n  Proof. auto. Qed.\n\n  Fact binomial_p_fix10 x l : binomial_p (x::l) nil = binomial x 0 * binomial_p l nil.\n  Proof. auto. Qed.\n\n  Fact binomial_p_fix11 x l y m : binomial_p (x::l) (y::m) = binomial x y * binomial_p l m.\n  Proof. auto. Qed.\n\n  (* This is Luca's thm as described eg on Wikipedia\n\n      if p is prime\n      and x = x0 + x1*p + x2*p² ...\n      and y = y0 + y1*p + y2*p² ...\n\n      then the identity \n \n         binomial x y = binomial x0 y0 * binomial x1 y1 * binomial x2 y2 * ...\n\n      holds modulo p\n\n   *)\n\n  Theorem lucas_theorem (l m : list nat) : \n         Forall (fun i => i < p) l               (* digits must be less than p*)\n      -> Forall (fun i => i < p) m               (* digits must be less than p*)\n      -> rem (binomial (base_p l) (base_p m)) p \n       = rem (binomial_p l m) p.\n  Proof using Hp.\n    intros H; revert H m.\n    induction 1 as [ | x l H1 H2 IH2 ];\n    induction 1 as [ | y m H3 H4 IH4 ].\n    + simpl; auto.\n    + rewrite binomial_p_fix01; simpl base_p.\n      rewrite <- rem_mult_rem, <- IH4, rem_mult_rem, \n              (mult_comm p), plus_comm, (mult_comm (binomial _ _)).\n      apply lucas_lemma; auto; simpl; lia.\n    + rewrite binomial_p_fix10; simpl base_p.\n      rewrite <- rem_mult_rem, <- IH2, rem_mult_rem; auto.\n      rewrite (mult_comm p), plus_comm, (mult_comm (binomial _ _)).\n      apply lucas_lemma; auto; simpl; lia.\n    + rewrite binomial_p_fix11; simpl base_p.\n      rewrite <- rem_mult_rem, <- IH2, rem_mult_rem; auto.\n      rewrite !(mult_comm p), !(plus_comm _ (_ * _)), (mult_comm (binomial _ _)).\n      apply lucas_lemma; auto; simpl; lia.\n  Qed.\n\nEnd lucas_theorem.\n\n(* Check lucas_theorem. *)\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/H10/ArithLibs/luca.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6823926033686784}}
{"text": "From mathcomp Require Import ssreflect.\nFrom Category.Base Require Import Logic Category Functor NatTran.\n\nSection mono_epi.\n\n  Context {C : Category}.\n  \n  Definition mono {X Y : Obj C} (f : Hom X Y) :=\n    forall (A : Obj C) (g1 g2 : Hom A X), f \\o g1 = f \\o g2 -> g1 = g2.\n\n  Definition epi {X Y : Obj C} (f : Hom X Y) :=\n    forall (A : Obj C) (g1 g2 : Hom A X), f \\o g1 = f \\o g2 -> g1 = g2.\n\n  Lemma iso_mono {X Y : Obj C}:\n    forall (f : Hom X Y), isomorphism f -> mono f.\n  Proof.\n    move => f.\n    case.\n    move => g.\n    case.\n    move => eqgf eqfg.\n    move => A g1 g2.\n    move/ (f_equal (fun x => g \\o x)).\n    repeat rewrite <- Hom_assoc.\n    move: eqgf =>->.\n    repeat rewrite Hom_IdL.\n    by [].\n  Qed.\n\n  Lemma id_mono {X : Obj C} :\n    mono (\\Id X).\n  Proof.\n    apply: iso_mono.\n    exact: isomorphism_id.\n  Qed.\n    \n  Lemma mono_comp {X Y Z : Obj C} :\n    forall (f : Hom Y Z) (g : Hom X Y), mono f -> mono g -> mono (f \\o g).\n  Proof.\n    move => f g.\n    move => mono_f mono_g.\n    move => A h1 h2.\n    repeat rewrite Hom_assoc.\n    move/ mono_f.\n    exact: mono_g.\n  Qed.\n\n  Lemma iso_epi {X Y : Obj C}:\n    forall (f : Hom X Y), isomorphism f -> epi f.\n  Proof.\n    move => f.\n    case.\n    move => g.\n    case.\n    move => eqgf eqfg.\n    move => A g1 g2.\n    move/ (f_equal (fun x => g \\o x)).\n    repeat rewrite <- Hom_assoc.\n    move: eqgf =>->.\n    repeat rewrite Hom_IdL.\n    by [].\n  Qed.\n\n  Lemma id_epi {X : Obj C} :\n    epi (\\Id X).\n  Proof.\n    apply: iso_epi.\n    exact: isomorphism_id.\n  Qed.    \n        \n  Lemma epi_comp {X Y Z : Obj C} :\n    forall (f : Hom Y Z) (g : Hom X Y), epi f -> epi g -> epi (f \\o g).\n  Proof.\n    move => f g.\n    move => mono_f mono_g.\n    move => A h1 h2.\n    repeat rewrite Hom_assoc.\n    move/ mono_f.\n    exact: mono_g.\n  Qed.\n\nEnd mono_epi.\n", "meta": {"author": "k27c8ff627uxz", "repo": "category_theory", "sha": "d5568b2ba04120a4f0e5bc7f2d61297c3cf42b9e", "save_path": "github-repos/coq/k27c8ff627uxz-category_theory", "path": "github-repos/coq/k27c8ff627uxz-category_theory/category_theory-d5568b2ba04120a4f0e5bc7f2d61297c3cf42b9e/src/Base/epi_mono.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6823399784477339}}
{"text": "Require Import Setoids.\nRequire Import Category7.\nRequire Import Eq_Category7.\n\nRecord Functor (C D:Category) : Type := functor\n    { Func_         : Arr C -> Arr D\n    ; Func_compat_  : forall (f g:Arr C), f == g -> Func_ f == Func_ g\n    ; Func_source_  : forall (f:Arr C), source (Func_ f) == Func_ (source f)\n    ; Func_target_  : forall (f:Arr C), target (Func_ f) == Func_ (target f)\n    ; Func_compose_ : forall (f g:Arr C),\n        forall (p: target f == source g) (q: target (Func_ f) == source (Func_ g)),\n        Func_ (compose_ C g f p) == compose_ D (Func_ g) (Func_ f) q\n      \n    }\n    .\n\nArguments Func_ {C} {D} _ _.\n\nLemma Functor_obj_ : forall (C D:Category)(F:Functor C D)(a:Arr C),\n    source a == a -> source (Func_ F a) == Func_ F a.\nProof.\n    intros C D F a H. apply trans with (Func_ F (source a)).\n    - apply Func_source_.\n    - apply Func_compat_. assumption.\nQed.\n\nArguments Functor_obj_ {C} {D} _ _ _.\n\n\nDefinition apply (C D:Category) (F:Functor C D)(a:Obj C) : Obj D :=\n    match a with \n    | obj a' p      => obj (Func_ F a') (Functor_obj_ F a' p)\n    end.\n\nArguments apply {C} {D} _ _.\n\nNotation \"F $ a\" := (apply F a) (at level 0, right associativity) : categ.\n\nDefinition lift_arrow_(C D:Category)(a b:Obj C)(F:Functor C D)(f:Hom a b):Arr D :=\n    match f with\n    | hom f' p q    => Func_ F f'\n    end.\n\nArguments lift_arrow_ {C} {D} {a} {b} _ _.\n\nDefinition lift_source_:forall (C D:Category)(a b:Obj C)(F:Functor C D)(f:Hom a b),\n    source (lift_arrow_ F f) == arr (F $ a).\nProof.\n    intros C D [a Ha] [b Hb] F [f p q]. simpl. simpl in p.\n    apply trans with (Func_ F (source f)).\n    - apply Func_source_.\n    - apply Func_compat_. assumption.\nQed.\n\nArguments lift_source_ {C} {D} {a} {b} _ _.\n     \nOpen Scope categ.\n\nDefinition lift_target_:forall (C D:Category)(a b:Obj C)(F:Functor C D)(f:Hom a b),\n    target (lift_arrow_ F f) == arr F $ b.\nProof.\n    intros C D [a Ha] [b Hb] F [f p q]. simpl. simpl in q.\n    apply trans with (Func_ F (target f)).\n    - apply Func_target_.\n    - apply Func_compat_. assumption.\nQed.\n\nArguments lift_target_ {C} {D} {a} {b} _ _.\n\nDefinition lift(C D:Category)(a b:Obj C)(F:Functor C D)(f:Hom a b):\n  Hom (F $ a) (F $ b) := hom (lift_arrow_ F f)(lift_source_ F f)(lift_target_ F f).\n\nArguments lift {C} {D} {a} {b} _ _.\n\nNotation \"F <$> f\" := (lift F f) (at level 0, right associativity) : categ.\n\n\nLemma functor_id : forall (C D:Category) (F:Functor C D) (a:Obj C),\n    i F<$>(id a) == i (id F $ a).\nProof. intros C D F [a Ha]. simpl. apply refl. Qed.\n\nLemma functor_law : forall (C D:Category) (F:Functor C D) (a b c:Obj C),\n    forall (g:Hom b c) (f:Hom a b), i F<$>(g # f) == i (F<$>g # F<$>f).\nProof.\n    intros C D F [a Ha] [b Hb] [c Hc] [g Ag Bg] [f Af Bf]. simpl.\n    unfold compose_arrow. simpl. apply Func_compose_.\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/cat/Functor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6823399760130746}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (lf3 : natural) : natural := plus lf3 z.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_commut/goal33conj146_coqofml_AN3VQP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6823399716031231}}
{"text": "(* This module only serves to demonstrate that defining the notion of well-     *)\n(* formed type expression without reference to valid contexts is legitimate.    *)\n(* More precisely, we define an alternative definition of validity which is     *)\n(* coupled with the definition of well-formed type expressions, where those     *)\n(* can only occur in a valid context. We show that this new notion of valid     *)\n(* context is equivalent to our existing notion (see Theorem below).            *)\n\nRequire Import Logic.STLC.Valid.\nRequire Import Logic.STLC.Syntax.\nRequire Import Logic.STLC.IsType.\nRequire Import Logic.STLC.Context.\n\n(* New notion of validity and new notion of well-formed type expression,        *)\n(* defined as mutually recursive predicates. We now require the context         *)\n(* involved in a well-formed type expression to be valid.                       *)\n(* Note that these definitions cannot be decoupled from one another.            *)\n(* Compare with the definiton of Valid.                                         *)\nInductive Valid2 (b v:Type) : Context -> Prop :=\n| Valid2O   : Valid2 b v O\n| Valid2Ty  : forall (G:Context) (t:b),\n    Valid2 b v G -> Valid2 b v (G ; t ::: *)\n| Valid2Var : forall (G:Context) (x:v) (Ty:T b),\n    Valid2 b v G -> IsType2 b v G Ty -> Valid2 b v (G ; x ::: Ty) \n(* Compare with the definition of IsType.                                       *)\nwith IsType2 (b v:Type) : @Context b v -> T b -> Prop :=\n| TVar2 : forall (G:Context) (t:b),\n    Valid2 b v G    ->          (* We require the context to be valid.          *)\n    G >> t          ->\n    IsType2 b v G 't\n| TFun2 : forall (G:Context) (Ty Ty':T b),\n    Valid2 b v G        ->      (* We require the context to be valid.          *)\n    IsType2 b v G Ty    ->\n    IsType2 b v G Ty'   ->\n    IsType2 b v G (Ty :-> Ty')\n.\n\nArguments Valid2    {b} {v}.\nArguments Valid2O   {b} {v}.\nArguments Valid2Ty  {b} {v}.\nArguments Valid2Var {b} {v}.\nArguments IsType2   {b} {v}.\nArguments TVar2     {b} {v}.\nArguments TFun2     {b} {v}.\n\n(* The defining requirements for IsType2 appear to be stronger than those of    *)\n(* IsType, so we expect the implication IsType2 G Ty -> IsType G Ty to hold.    *)\nLemma IsType2IsType : forall (b v:Type) (G:@Context b v) (Ty:T b),\n    IsType2 G Ty -> G :> Ty.\nProof.\n   intros b v G Ty H1. induction H1 as [G Ty H2 H3|G Ty Ty' H2 H3 IH1 H4 IH2]. \n   - constructor. assumption.\n   - constructor; assumption.\nQed.\n\n(* The defining requirements for Valid2 are based on a stronger IsType2, so we  *)\n(* expect the implication Valid2 G -> Valid G to hold.                          *)\nLemma Valid2Valid : forall (b v:Type) (G:@Context b v),\n    Valid2 G -> Valid G.\nProof.\n    intros b v G H1. induction H1 as [ |G Ty H2 IH|G x Ty H2 IH H3]. \n    - constructor.\n    - constructor. assumption.\n    - constructor; try assumption. apply IsType2IsType. assumption.\nQed.\n\n(* We cannot expect the implication IsType G Ty -> IsType2 G Ty to hold, but    *)\n(* this is however true if the context involved is 'strongly' valid.            *)\nLemma IsTypeIsType2 : forall (b v:Type) (G:@Context b v) (Ty:T b),\n    Valid2 G -> G :> Ty -> IsType2 G Ty.\nProof.\n    intros b v G Ty H H1. revert H.\n    induction H1 as [G t|G Ty Ty' H2 IH1 H3 IH2].\n    - intros H4. constructor; assumption.\n    - intros H4. constructor.\n        + assumption.\n        + apply IH1. assumption.\n        + apply IH2. assumption.\nQed.\n\n(* This is the main helper lemma: the conclusion of this lemma needs to be      *)\n(* strong enough so we are able to carry out the induction argument.            *)\nLemma ValidValid2IsType2 : forall (b v:Type) (G:@Context b v),\n    Valid G -> Valid2 G /\\ (forall (Ty:T b), G :> Ty -> IsType2 G Ty).\nProof.\n    intros b v G H1. induction H1 as [ |G t H2 IH|G x Ty H2 IH H3].\n    - split; try constructor. intros Ty H2. \n      apply notIsTypeInO in H2. contradiction.\n    - destruct IH as [IH1 IH2]. split.\n        + constructor. assumption.\n        + intros Ty H3. apply IsTypeIsType2; try assumption.\n          constructor. assumption.\n    - destruct IH as [IH1 IH2]. split.\n        + constructor; try assumption. apply IH2. assumption.\n        + intros Ty' H4. apply IsTypeIsType2; try assumption.\n          constructor; try assumption. apply IH2. assumption.\nQed.\n\n(* This is a strenghening of the IsTypeIsType2 result, where we can now rely    *)\n(* on the weaker assumption that the context is simply valid (not 'strongly').  *)\nLemma IsTypeIsType2' : forall (b v:Type) (G:@Context b v) (Ty:T b),\n    Valid G -> G :> Ty -> IsType2 G Ty.\nProof.\n    intros b v G Ty H1 H2. apply ValidValid2IsType2 in H1.\n    destruct H1 as [H1 H3]. apply H3. assumption.\nQed.\n\n(* So our seemingly weaker notion of validity actually implies strong validity. *)\nLemma ValidValid2 : forall (b v:Type) (G:@Context b v),\n    Valid G -> Valid2 G.\nProof.\n    intros b v G H1. apply ValidValid2IsType2 in H1.\n    destruct H1 as [H1 H2]. assumption.\nQed.\n\n(* This vindicates our approach of decoupling the notions of valid context and  *)\n(* well-formed type expressions, where the latter need not require validity.    *)\nTheorem ValidValid2Same : forall (b v:Type) (G:@Context b v),\n    Valid G <-> Valid2 G.\nProof.\n    intros b v G. split; intros H1.\n    - apply ValidValid2. assumption.\n    - apply Valid2Valid. 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/STLC/Valid2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6823399715265626}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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 := 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_80_plus_succ/goal33conj3411_coqofml_7jiyRA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6823315240703239}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) : natural := mult z y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj186_coqofml_x7Iama.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.682331519374556}}
{"text": "Require Import WildCat\n  AbelianGroup AbHom Centralizer AbProjective\n  Groups.FreeGroup.\n\n(** * Cyclic groups *)\n\n(** ** The free group on one generator *)\n\n(** We can define the integers as the free group on one generator, which we denote [Z1] below. Results from Centralizer.v and Groups.FreeGroup let us show that [Z1] is abelian. *)\n\n(** We define [Z] as the free group with a single generator. *)\nDefinition Z1 := FreeGroup Unit.\nDefinition Z1_gen : Z1 := freegroup_in tt. (* The generator *)\n\n(** The recursion principle of [Z1] and its computation rule. *)\nDefinition Z1_rec {G : Group@{u}} (g : G) : Z1 $-> G\n  := FreeGroup_rec Unit G (unit_name g).\n\nDefinition Z1_rec_beta {G : Group} (g : G) : Z1_rec g Z1_gen = g\n  := FreeGroup_rec_beta _ _ _.\n\n(* The free group [Z] on one generator is isomorphic to the subgroup of [Z] generated by the generator.  And such cyclic subgroups are known to be commutative, by [commutative_cyclic_subgroup]. *)\nGlobal Instance Z1_commutative `{Funext} : Commutative (@group_sgop Z1)\n  := commutative_iso_commutative iso_subgroup_incl_freegroupon.\n(* [Funext] is used in [isfreegroupon_freegroup], but there is a comment there saying that it can be removed.  If that is done, don't need it here either. A different proof of this result, directly using the construction of the free group, could probably also avoid [Funext]. *)\n\nDefinition ab_Z1 `{Funext} : AbGroup\n  := Build_AbGroup Z1 _.\n\n(** The universal property of [ab_Z1]. *)\nLemma equiv_Z1_hom@{u v | u < v} `{Funext} (A : AbGroup@{u})\n  : GroupIsomorphism (ab_hom@{u v} ab_Z1@{u v} A) A.\nProof.\n  snrapply Build_GroupIsomorphism'.\n  - refine (_ oE (equiv_freegroup_rec@{u u u v} A Unit)^-1).\n    symmetry. refine (Build_Equiv _ _ (fun a => unit_name a) _).\n  - intros f g. cbn. reflexivity.\nDefined.\n\nDefinition nat_to_Z1 : nat -> Z1\n  := fun n => grp_pow Z1_gen n.\n\nDefinition Z1_mul_nat `{Funext} (n : nat) : ab_Z1 $-> ab_Z1\n  := Z1_rec (nat_to_Z1 n).\n\nLemma Z1_mul_nat_beta {A : AbGroup} (a : A) (n : nat)\n  : Z1_rec a (nat_to_Z1 n) = ab_mul_nat n a.\nProof.\n  induction n as [|n H].\n  1: easy.\n  refine (grp_pow_homo _ _ _ @ _); simpl.\n  by rewrite grp_unit_r.\nDefined.\n\n(** [ab_Z1] is projective. *)\nGlobal Instance ab_Z1_projective `{Funext}\n  : IsAbProjective ab_Z1.\nProof.\n  intros A B p f H1.\n  pose proof (a := @center _ (H1 (f Z1_gen))).\n  strip_truncations.\n  snrefine (tr (Z1_rec a.1; _)).\n  cbn beta. apply ap10.\n  apply ap. (* of the coercion [grp_homo_map] *)\n  apply path_homomorphism_from_free_group.\n  simpl.\n  intros [].\n  refine (_ @ a.2).\n  exact (ap p (grp_unit_r _)).\nDefined.\n\n(** * Finite cyclic groups *)\n\n(** The [n]-th cyclic group is the cokernel of [Z1_mul_nat n]. *)\nDefinition cyclic@{u v | u < v} `{Funext} (n : nat) : AbGroup@{u}\n  := ab_cokernel@{u v} (Z1_mul_nat n).\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Algebra/AbGroups/Cyclic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6823315052872515}}
{"text": "Require Import rt.util.all rt.util.divround.\nRequire Import rt.model.arrival.basic.task rt.model.arrival.basic.job rt.model.arrival.basic.task_arrival.\nRequire Import rt.model.schedule.global.response_time rt.model.schedule.global.schedulability\n               rt.model.schedule.global.workload.\nRequire Import rt.model.schedule.global.basic.schedule.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq div fintype bigop path.\n\nModule WorkloadBound.\n  \n  Import Job SporadicTaskset Schedule ScheduleOfSporadicTask TaskArrival ResponseTime Schedulability Workload.\n\n  Section WorkloadBoundDef.\n\n    Context {sporadic_task: eqType}.\n    Variable task_cost: sporadic_task -> time.\n    Variable task_period: sporadic_task -> time.\n\n    (* Consider any task tsk with response-time bound R_tsk,\n       that is scheduled in an interval of length delta. *)\n    Variable tsk: sporadic_task.\n    Variable R_tsk: time.\n    Variable delta: time.\n    \n    (* Based on the number of jobs that execute completely in the interval, ... *)\n    Definition max_jobs :=\n      div_floor (delta + R_tsk - task_cost tsk) (task_period tsk).\n\n    (* ... Bertogna and Cirinei's workload bound is defined as follows. *)\n    Definition W :=\n      let e_k := (task_cost tsk) in\n      let p_k := (task_period tsk) in            \n        minn e_k (delta + R_tsk - e_k - max_jobs * p_k) + max_jobs * e_k.\n\n  End WorkloadBoundDef.\n  \n  Section BasicLemmas.\n\n    Context {sporadic_task: eqType}.\n    Variable task_cost: sporadic_task -> time.\n    Variable task_period: sporadic_task -> time.\n\n    (* Let tsk be any task...*)\n    Variable tsk: sporadic_task.\n\n    (* ... with period > 0. *)\n    Hypothesis H_period_positive: task_period tsk > 0.\n\n    (* Let R1 <= R2 be two response-time bounds that\n       are larger than the cost of the tsk. *)\n    Variable R1 R2: time.\n    Hypothesis H_R_lower_bound: R1 >= task_cost tsk.\n    Hypothesis H_R1_le_R2: R1 <= R2.\n      \n    Let workload_bound := W task_cost task_period tsk.\n\n    (* Then, Bertogna and Cirinei's workload bound is monotonically increasing. *) \n    Lemma W_monotonic :\n      forall t1 t2,\n        t1 <= t2 ->\n        workload_bound R1 t1 <= workload_bound R2 t2.\n    Proof.\n      intros t1 t2 LEt.\n      unfold workload_bound, W, max_jobs, div_floor; rewrite 2!subndiv_eq_mod.\n      set e := task_cost tsk; set p := task_period tsk.\n      set x1 := t1 + R1.\n      set x2 := t2 + R2.\n      set delta := x2 - x1.\n      rewrite -[x2](addKn x1) -addnBA; fold delta;\n        last by apply leq_add.\n      \n      induction delta; first by rewrite addn0 leqnn.\n      {\n         apply (leq_trans IHdelta).\n\n         (* Prove special case for p <= 1. *)\n         destruct (leqP p 1) as [LTp | GTp].\n         {\n           rewrite leq_eqVlt in LTp; move: LTp => /orP LTp; des;\n             last by rewrite ltnS in LTp; apply (leq_trans H_period_positive) in LTp. \n           {\n             rewrite LTp 2!modn1 2!divn1.\n             rewrite leq_add2l leq_mul2r; apply/orP; right.\n             by rewrite leq_sub2r // leq_add2l.\n           }\n         }\n         (* Harder case: p > 1. *)\n         {\n           assert (EQ: (x1 + delta.+1 - e) = (x1 + delta - e).+1).\n           {\n             rewrite -[(x1 + delta - e).+1]addn1.\n             rewrite [_+1]addnC addnBA; last first.\n             {\n               apply (leq_trans H_R_lower_bound).\n               by rewrite -addnA addnC -addnA leq_addr.\n             }\n             by rewrite [1 + _]addnC -addnA addn1.\n           } rewrite -> EQ in *; clear EQ.\n         \n         have DIV := divSn_cases (x1 + delta - e) p GTp; des.\n         {\n           rewrite DIV leq_add2r leq_min; apply/andP; split;\n             first by rewrite geq_minl.\n           by apply leq_trans with (n := (x1 + delta - e) %% p);\n             [by rewrite geq_minr | by rewrite -DIV0 addn1 leqnSn].\n         }\n         {\n           rewrite -[minn e _]add0n -addnA; apply leq_add; first by ins.\n           rewrite -DIV mulnDl mul1n [_ + e]addnC.\n           by apply leq_add; [by rewrite geq_minl | by ins].\n         }\n       }\n     }\n   Qed.\n\n  End BasicLemmas.\n \n  Section ProofWorkloadBound.\n \n    Context {sporadic_task: eqType}.\n    Variable task_cost: sporadic_task -> time.\n    Variable task_period: sporadic_task -> time.\n    Variable task_deadline: sporadic_task -> time.\n    \n    Context {Job: eqType}.\n    Variable job_arrival: Job -> time.\n    Variable job_cost: Job -> time.\n    Variable job_task: Job -> sporadic_task.\n    Variable job_deadline: Job -> time.\n\n    Variable arr_seq: arrival_sequence Job.\n\n    (* Assume that all jobs have valid parameters *)\n    Hypothesis H_jobs_have_valid_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    (* Consider any schedule. *)\n    Context {num_cpus: nat}.\n    Variable sched: schedule Job num_cpus.\n    Hypothesis H_jobs_come_from_arrival_sequence:\n      jobs_come_from_arrival_sequence sched arr_seq.\n\n    (* Assumption: jobs only execute if they arrived.\n       This is used to eliminate jobs that arrive after end of the interval t1 + delta. *)\n    Hypothesis H_jobs_must_arrive_to_execute: jobs_must_arrive_to_execute job_arrival sched.\n\n    (* Assumption: jobs do not execute after they completed.\n       This is used to eliminate jobs that complete before the start of the interval t1. *)\n    Hypothesis H_completed_jobs_dont_execute: completed_jobs_dont_execute job_cost sched.\n\n    (* Assumption: Jobs are sequential.\n       This is required to use interval lengths as a measure of service. *)\n    Hypothesis H_sequential_jobs: sequential_jobs sched.\n\n    (* Assumption: sporadic task model.\n       This is necessary to conclude that consecutive jobs ordered by arrival times\n       are separated by at least 'period' times units. *)\n    Hypothesis H_sporadic_tasks: sporadic_task_model task_period job_arrival job_task arr_seq.\n\n    (* Before starting the proof, let's give simpler names to the definitions. *)\n    Let job_has_completed_by := completed job_cost sched.\n\n    Let workload_of (tsk: sporadic_task) (t1 t2: time) := workload job_task sched tsk t1 t2.\n\n    (* Now we define the theorem. Let tsk be any task in the taskset. *)\n    Variable tsk: sporadic_task.\n\n    (* Assumption: the task must have valid parameters:\n         a) period > 0 (used in divisions)\n         b) deadline of the jobs = deadline of the task\n         c) cost <= period\n            (used to prove that the distance between the first and last\n             jobs is at least (cost + n*period), where n is the number\n             of middle jobs. If cost >> period, the claim does not hold\n             for every task set. *)\n    Hypothesis H_valid_task_parameters:\n      is_valid_sporadic_task task_cost task_period task_deadline tsk.\n\n    (* Assumption: the task must have a constrained deadline.\n       This is required to prove that n_k (max_jobs) from Bertogna\n       and Cirinei's formula accounts for at least the number of\n       middle jobs (i.e., number of jobs - 2 in the worst case). *)\n    Hypothesis H_constrained_deadline: task_deadline tsk <= task_period tsk.\n      \n    (* Consider an interval [t1, t1 + delta). *)\n    Variable t1 delta: time.\n\n    (* Assume that a response-time bound R_tsk for that task in any\n       schedule of this processor platform is also given, ... *)\n    Variable R_tsk: time.\n\n    Hypothesis H_response_time_bound :    \n      forall j,\n        arrives_in arr_seq j ->\n        job_task j = tsk ->\n        job_arrival j + R_tsk < t1 + delta ->\n        job_has_completed_by j (job_arrival j + R_tsk).\n\n    (* ... such that R_tsk >= task_cost tsk and R_tsk <= task_deadline tsk. *)    \n    Hypothesis H_response_time_ge_cost: R_tsk >= task_cost tsk.\n    Hypothesis H_no_deadline_miss: R_tsk <= task_deadline tsk.\n    \n    Section MainProof.\n\n      (* In this section, we prove that the workload of a task in the\n         interval [t1, t1 + delta) is bounded by W. *)\n\n      (* Let's simplify the names a bit. *)\n      Let t2 := t1 + delta.\n      Let n_k := max_jobs task_cost task_period tsk R_tsk delta.\n      Let workload_bound := W task_cost task_period tsk R_tsk delta.\n      \n      (* Since we only care about the workload of tsk, we restrict\n         our view to the set of jobs of tsk scheduled in [t1, t2). *)\n      Let scheduled_jobs :=\n        jobs_of_task_scheduled_between job_task sched tsk t1 t2.\n\n      (* Now, let's consider the list of interfering jobs sorted by arrival time. *)\n      Let earlier_arrival := fun x y => job_arrival x <= job_arrival y.\n      Let sorted_jobs := sort earlier_arrival scheduled_jobs.\n\n      (* The first step consists in simplifying the sum corresponding\n         to the workload. *)\n      Section SimplifyJobSequence.\n\n        (* After switching to the definition of workload based on a list\n           of jobs, we show that sorting the list preserves the sum. *)\n        Lemma workload_bound_simpl_by_sorting_scheduled_jobs :\n          workload_joblist job_task sched tsk t1 t2 =\n           \\sum_(i <- sorted_jobs) service_during sched i t1 t2.\n        Proof.\n          unfold workload_joblist; fold scheduled_jobs.\n          rewrite (eq_big_perm sorted_jobs) /= //.\n          by rewrite -(perm_sort earlier_arrival).\n        Qed.\n\n        (* Remember that both sequences have the same set of elements *)\n        Lemma workload_bound_job_in_same_sequence :\n          forall j,\n            (j \\in scheduled_jobs) = (j \\in sorted_jobs).\n        Proof.\n          by apply perm_eq_mem; rewrite -(perm_sort earlier_arrival).\n        Qed.\n\n        (* Remember that all jobs in the sorted sequence is an\n           interfering job of task tsk. *)\n        Lemma workload_bound_all_jobs_from_tsk :\n          forall j_i,\n            j_i \\in sorted_jobs ->\n            arrives_in arr_seq j_i /\\\n            job_task j_i = tsk /\\\n            service_during sched j_i t1 t2 != 0 /\\\n            j_i \\in jobs_scheduled_between sched t1 t2.\n        Proof.\n          rename H_jobs_come_from_arrival_sequence into FROMarr.\n          intros j_i LTi.\n          rewrite -workload_bound_job_in_same_sequence mem_filter in LTi; des.\n          have IN := LTi0.\n          unfold jobs_scheduled_between in *; rewrite mem_undup in IN.\n          apply mem_bigcat_nat_exists in IN; des.\n          rewrite mem_scheduled_jobs_eq_scheduled in IN.\n          repeat split; try (by done); first by apply (FROMarr j_i i).\n          unfold jobs_scheduled_between in *; rewrite mem_undup in LTi0.\n          apply mem_bigcat_nat_exists in LTi0; des.\n          rewrite mem_scheduled_jobs_eq_scheduled in LTi0.\n          apply service_implies_cumulative_service with (t := i);\n            first by apply/andP; split.\n          by rewrite -not_scheduled_no_service negbK.\n        Qed.\n\n        (* Remember that consecutive jobs are ordered by arrival. *)\n        Lemma workload_bound_jobs_ordered_by_arrival :\n          forall i elem,\n            i < (size sorted_jobs).-1 ->\n            earlier_arrival (nth elem sorted_jobs i) (nth elem sorted_jobs i.+1).\n        Proof.\n          intros i elem LT.\n          assert (SORT: sorted earlier_arrival sorted_jobs).\n            by apply sort_sorted; unfold total, earlier_arrival; ins; apply leq_total.\n          by destruct sorted_jobs; simpl in *; [by rewrite ltn0 in LT | by apply/pathP].\n        Qed.\n\n      End SimplifyJobSequence.\n\n      (* Next, we show that if the number of jobs is no larger than n_k,\n         the workload bound trivially holds. *)\n      Section WorkloadNotManyJobs.\n\n        Lemma workload_bound_holds_for_at_most_n_k_jobs :\n          size sorted_jobs <= n_k ->\n          \\sum_(i <- sorted_jobs) service_during sched i t1 t2 <=\n            workload_bound.\n        Proof.\n        intros LEnk.\n        rewrite -[\\sum_(_ <- _ | _) _]add0n leq_add //.\n        apply leq_trans with (n := \\sum_(x <- sorted_jobs) task_cost tsk);\n          last by rewrite big_const_seq iter_addn addn0 mulnC leq_mul2r; apply/orP; right.\n        {\n          rewrite [\\sum_(_ <- _) service_during _ _ _ _]big_seq_cond.\n          rewrite [\\sum_(_ <- _) task_cost _]big_seq_cond.\n          apply leq_sum; intros j_i; move/andP => [INi _].\n          apply workload_bound_all_jobs_from_tsk in INi; des. \n          eapply cumulative_service_le_task_cost;\n            [by apply H_completed_jobs_dont_execute | by apply INi0 |].\n          by apply H_jobs_have_valid_parameters.\n        }\n      Qed.\n\n      End WorkloadNotManyJobs.\n\n      (* Otherwise, assume that the number of jobs is larger than n_k >= 0.\n         First, consider the simple case with only one job. *)\n      Section WorkloadSingleJob.\n\n        (* Assume that there's at least one job in the sorted list. *)\n        Hypothesis H_at_least_one_job: size sorted_jobs > 0.\n\n        Variable elem: Job.\n        Let j_fst := nth elem sorted_jobs 0.\n\n        (* The first job is an interfering job of task tsk. *)\n        Lemma workload_bound_j_fst_is_job_of_tsk :\n          arrives_in arr_seq j_fst /\\\n          job_task j_fst = tsk /\\\n          service_during sched j_fst t1 t2 != 0 /\\\n          j_fst \\in jobs_scheduled_between sched t1 t2.\n        Proof.\n          by apply workload_bound_all_jobs_from_tsk, mem_nth.\n        Qed.\n\n        (* The workload bound holds for the single job. *)\n        Lemma workload_bound_holds_for_a_single_job :\n          \\sum_(0 <= i < 1) service_during sched (nth elem sorted_jobs i) t1 t2 <=\n          workload_bound.\n        Proof.\n          unfold workload_bound, W; fold n_k.\n          have INfst := workload_bound_j_fst_is_job_of_tsk; des.\n          rewrite big_nat_recr // big_geq // [nth]lock /= -lock add0n.\n          destruct n_k; last first.\n          {\n            rewrite -[service_during _ _ _ _]add0n; rewrite leq_add //.\n            rewrite -[service_during _ _ _ _]add0n [_* task_cost tsk]mulSnr.\n            apply leq_add; first by done.\n            by eapply cumulative_service_le_task_cost;\n              [| by apply INfst0\n               | by apply H_jobs_have_valid_parameters].\n          }\n          {\n            rewrite 2!mul0n addn0 subn0 leq_min; apply/andP; split.\n            {\n              by eapply cumulative_service_le_task_cost;\n                 [| by apply INfst0\n                | by apply H_jobs_have_valid_parameters].\n            }\n            {\n              rewrite -addnBA // -[service_during _ _ _ _]addn0.\n              apply leq_add; last by done.\n              by apply cumulative_service_le_delta.\n            }\n          }\n        Qed.\n\n      End WorkloadSingleJob.\n\n      (* Next, consider the last case where there are at least two jobs:\n         the first job j_fst, and the last job j_lst. *)\n      Section WorkloadTwoOrMoreJobs.\n\n        (* There are at least two jobs. *)\n        Variable num_mid_jobs: nat.\n        Hypothesis H_at_least_two_jobs : size sorted_jobs = num_mid_jobs.+2.\n        \n        Variable elem: Job.\n        Let j_fst := nth elem sorted_jobs 0.\n        Let j_lst := nth elem sorted_jobs num_mid_jobs.+1.\n\n        (* The last job is an interfering job of task tsk. *)\n        Lemma workload_bound_j_lst_is_job_of_tsk :\n          arrives_in arr_seq j_lst /\\\n          job_task j_lst = tsk /\\\n          service_during sched j_lst t1 t2 != 0 /\\\n          j_lst \\in jobs_scheduled_between sched t1 t2.\n        Proof.\n          apply workload_bound_all_jobs_from_tsk, mem_nth.\n          by rewrite H_at_least_two_jobs.\n        Qed.\n\n        (* The response time of the first job must fall inside the interval. *)\n        Lemma workload_bound_response_time_of_first_job_inside_interval :\n          t1 <= job_arrival j_fst + R_tsk.\n        Proof.\n          rewrite leqNgt; apply /negP; unfold not; intro LTt1.\n          exploit workload_bound_all_jobs_from_tsk.\n          {\n            apply mem_nth; instantiate (1 := 0).\n            apply ltn_trans with (n := 1); [by done | by rewrite H_at_least_two_jobs].\n          }\n          instantiate (1 := elem); move => [FSTarr [FSTtsk [/eqP FSTserv FSTin]]].\n          apply FSTserv.\n          apply (cumulative_service_after_job_rt_zero job_arrival job_cost) with (R := R_tsk);\n            try (by done); last by apply ltnW.\n          apply H_response_time_bound; try (by done).\n          by apply leq_trans with (n := t1); last by apply leq_addr.\n        Qed.\n\n        (* The arrival of the last job must also fall inside the interval. *)\n        Lemma workload_bound_last_job_arrives_before_end_of_interval :\n          job_arrival j_lst < t2.\n        Proof.\n          rewrite leqNgt; apply/negP; unfold not; intro LT2.\n          exploit workload_bound_all_jobs_from_tsk.\n          {\n            apply mem_nth; instantiate (1 := num_mid_jobs.+1).\n            by rewrite -(ltn_add2r 1) addn1 H_at_least_two_jobs addn1.\n          }  \n          instantiate (1 := elem); move => [LSTarr [LSTtsk [/eqP LSTserv LSTin]]].\n          unfold service_during; apply LSTserv.\n          by apply cumulative_service_before_job_arrival_zero with (job_arrival0 := job_arrival).\n        Qed.\n\n        (* Next, we upper-bound the service of the first and last jobs using their arrival times. *)\n        Lemma workload_bound_service_of_first_and_last_jobs :\n          service_during sched j_fst t1 t2 +\n          service_during sched j_lst t1 t2 <=\n            (job_arrival j_fst  + R_tsk - t1) + (t2 - job_arrival j_lst).\n        Proof.\n          apply leq_add; unfold service_during.\n          {\n            rewrite -[_ + _ - _]mul1n -[1*_]addn0 -iter_addn -big_const_nat.\n            apply leq_trans with (n := \\sum_(t1 <= t < job_arrival j_fst + R_tsk)\n                                        service_at sched j_fst t);\n              last by apply leq_sum; ins; apply service_at_most_one.\n            destruct (job_arrival j_fst + R_tsk < t2) eqn:LEt2; last first.\n            {\n              unfold t2; apply negbT in LEt2; rewrite -ltnNge in LEt2.\n              rewrite -> big_cat_nat with (n := t1 + delta) (p := job_arrival j_fst + R_tsk);\n                [by apply leq_addr | by apply leq_addr | by done].\n            }\n            {\n              rewrite -> big_cat_nat with (n := job_arrival j_fst + R_tsk);\n                [| by apply workload_bound_response_time_of_first_job_inside_interval\n                 | by apply ltnW].\n              rewrite -{2}[\\sum_(_ <= _ < _) _]addn0 /= leq_add2l leqn0; apply/eqP.\n              apply (cumulative_service_after_job_rt_zero job_arrival job_cost) with (R := R_tsk); try (by done).\n              exploit workload_bound_all_jobs_from_tsk.\n                by apply mem_nth; instantiate (1 := 0); rewrite H_at_least_two_jobs.\n              instantiate (1 := elem); move => [FSTarr [FSTtsk _]].\n              by apply H_response_time_bound.\n            }\n          }\n          {\n            rewrite -[_ - _]mul1n -[1 * _]addn0 -iter_addn -big_const_nat.\n            destruct (job_arrival j_lst <= t1) eqn:LT.\n            {\n              apply leq_trans with (n := \\sum_(job_arrival j_lst <= t < t2)\n                                          service_at sched j_lst t);\n                first by rewrite -> big_cat_nat with (m := job_arrival j_lst) (n := t1);\n                  [by apply leq_addl | by ins | by apply leq_addr].\n              by apply leq_sum; ins; apply service_at_most_one.\n            }\n            {\n              apply negbT in LT; rewrite -ltnNge in LT.\n              rewrite -> big_cat_nat with (n := job_arrival j_lst);\n                [| by apply ltnW\n                 | by apply ltnW, workload_bound_last_job_arrives_before_end_of_interval].\n              rewrite /= -[\\sum_(_ <= _ < _) 1]add0n; apply leq_add.\n              rewrite (cumulative_service_before_job_arrival_zero job_arrival);\n                [by apply leqnn | by ins | by apply leqnn].\n              by apply leq_sum; ins; apply service_at_most_one.\n            }\n          }\n        Qed.\n\n        (* Simplify the expression from the previous lemma. *)\n        Lemma workload_bound_simpl_expression_with_first_and_last :\n          job_arrival j_fst + R_tsk - t1 + (t2 - job_arrival j_lst) =\n                       delta + R_tsk - (job_arrival j_lst - job_arrival j_fst).\n        Proof.\n          have lemma1 := workload_bound_last_job_arrives_before_end_of_interval.\n          have lemma2 := workload_bound_response_time_of_first_job_inside_interval.\n          rewrite addnBA; last by apply ltnW.\n          rewrite subh1 // -addnBA; last by apply leq_addr.\n          rewrite addnC [job_arrival _ + _]addnC.\n          unfold t2; rewrite [t1 + _]addnC -[delta + t1 - _]subnBA // subnn subn0.\n          rewrite addnA -subnBA; first by ins.\n          unfold j_fst, j_lst. rewrite -[_.+1]add0n.\n          apply prev_le_next; last by rewrite H_at_least_two_jobs add0n leqnn.\n          by ins; apply workload_bound_jobs_ordered_by_arrival.\n        Qed.\n\n        (* Bound the service of the middle jobs. *)\n        Lemma workload_bound_service_of_middle_jobs :\n          \\sum_(0 <= i < num_mid_jobs)\n            service_during sched (nth elem sorted_jobs i.+1) t1 t2 <=\n            num_mid_jobs * task_cost tsk.\n        Proof.\n          apply leq_trans with (n := num_mid_jobs * task_cost tsk);\n            last by rewrite leq_mul2l; apply/orP; right. \n          apply leq_trans with (n := \\sum_(0 <= i < num_mid_jobs) task_cost tsk);\n            last by rewrite big_const_nat iter_addn addn0 mulnC subn0.\n          rewrite big_nat_cond [\\sum_(0 <= i < num_mid_jobs) task_cost _]big_nat_cond.\n          apply leq_sum; intros i; rewrite andbT; move => /andP LT; des.\n          exploit workload_bound_all_jobs_from_tsk.\n          {\n            instantiate (1 := nth elem sorted_jobs i.+1).\n            apply mem_nth; rewrite H_at_least_two_jobs.\n            by rewrite ltnS; apply leq_trans with (n := num_mid_jobs).\n          }\n          move => [ARR [TSK _]].\n          by eapply cumulative_service_le_task_cost; eauto 2.\n        Qed.\n\n        (* Conclude that the distance between first and last is at least num_mid_jobs + 1 periods. *)\n        Lemma workload_bound_many_periods_in_between :\n          job_arrival j_lst - job_arrival j_fst >= num_mid_jobs.+1 * (task_period tsk).\n        Proof.\n          assert (EQnk: num_mid_jobs.+1=(size sorted_jobs).-1).\n            by rewrite H_at_least_two_jobs.\n          unfold j_fst, j_lst; rewrite EQnk telescoping_sum;\n            last by ins; apply workload_bound_jobs_ordered_by_arrival.\n          rewrite -[_ * _ tsk]addn0 mulnC -iter_addn -{1}[_.-1]subn0 -big_const_nat. \n          rewrite big_nat_cond [\\sum_(0 <= i < _)(_-_)]big_nat_cond.\n          apply leq_sum; intros i; rewrite andbT; move => /andP LT; des.\n\n          (* To simplify, call the jobs 'cur' and 'next' *)\n          set cur := nth elem sorted_jobs i.\n          set next := nth elem sorted_jobs i.+1.\n\n          (* Show that cur arrives earlier than next *)\n          assert (ARRle: job_arrival cur <= job_arrival next).\n            by unfold cur, next; apply workload_bound_jobs_ordered_by_arrival.\n             \n          feed (workload_bound_all_jobs_from_tsk cur).\n            by apply mem_nth, (ltn_trans LT0); destruct sorted_jobs.\n          intros [CURarr [CURtsk [_ CURin]]].\n\n          feed (workload_bound_all_jobs_from_tsk next).\n            by apply mem_nth; destruct sorted_jobs.\n          intros [NEXTarr [NEXTtsk [_ NEXTin]]].\n\n          (* Use the sporadic task model to conclude that cur and next are separated\n             by at least (task_period tsk) units. Of course this only holds if cur != next.\n             Since we don't know much about the list (except that it's sorted), we must\n             also prove that it doesn't contain duplicates. *)\n          assert (CUR_LE_NEXT: job_arrival cur + task_period (job_task cur) <= job_arrival next).\n          {\n            apply H_sporadic_tasks; try (by done).\n            unfold cur, next, not; intro EQ; move: EQ => /eqP EQ.\n            rewrite nth_uniq in EQ; first by move: EQ => /eqP EQ; intuition.\n              by apply ltn_trans with (n := (size sorted_jobs).-1); destruct sorted_jobs; ins.\n              by destruct sorted_jobs; ins.\n              by rewrite sort_uniq -/scheduled_jobs filter_uniq // undup_uniq.\n              by rewrite CURtsk.\n          }\n          by rewrite subh3 // addnC -CURtsk.\n        Qed.\n\n        (* Prove that n_k is at least the number of the middle jobs *)\n        Lemma workload_bound_n_k_covers_middle_jobs :\n          n_k >= num_mid_jobs.\n        Proof.\n          rename H_valid_task_parameters into PARAMS.\n          unfold is_valid_sporadic_task in *; des.\n          rewrite leqNgt; apply/negP; unfold not; intro LTnk.\n          assert (DISTmax: job_arrival j_lst - job_arrival j_fst >= delta + task_period tsk).\n          {\n            apply leq_trans with (n := n_k.+2 * task_period tsk).\n            {\n              rewrite -addn1 mulnDl mul1n leq_add2r.\n              apply leq_trans with (n := delta + R_tsk - task_cost tsk);\n                first by rewrite -addnBA //; apply leq_addr.\n              by apply ltnW, ltn_ceil, PARAMS0.\n            }\n            apply leq_trans with (num_mid_jobs.+1 * task_period tsk); \n              first by rewrite leq_mul2r; apply/orP; right.\n            by apply workload_bound_many_periods_in_between.\n          }\n          rewrite <- leq_add2r with (p := job_arrival j_fst) in DISTmax.\n          rewrite addnC subh1 in DISTmax; last first.\n          {\n            unfold j_fst, j_lst; rewrite -[_.+1]add0n.\n            apply prev_le_next; last by rewrite H_at_least_two_jobs add0n leqnn.\n            by ins; apply workload_bound_jobs_ordered_by_arrival.\n          }\n          rewrite -subnBA // subnn subn0 in DISTmax.\n          rewrite [delta + task_period tsk]addnC addnA in DISTmax.\n          have BEFOREt2 := workload_bound_last_job_arrives_before_end_of_interval.\n          generalize BEFOREt2; move: BEFOREt2; rewrite {1}ltnNge; move => /negP BEFOREt2'.\n          intros BEFOREt2; apply BEFOREt2'; clear BEFOREt2'.\n          apply leq_trans with (n := job_arrival j_fst + task_deadline tsk + delta);\n            last by apply leq_trans with (n := job_arrival j_fst + task_period tsk + delta);\n              [rewrite leq_add2r leq_add2l; apply H_constrained_deadline | apply DISTmax].\n          unfold t2; rewrite leq_add2r.\n          apply leq_trans with (n := job_arrival j_fst + R_tsk);\n            last by rewrite leq_add2l.\n          by apply workload_bound_response_time_of_first_job_inside_interval.\n        Qed.\n\n        (* If n_k = num_mid_jobs, then the workload bound holds. *)\n        Lemma workload_bound_n_k_equals_num_mid_jobs :\n          num_mid_jobs = n_k ->\n          service_during sched j_lst t1 t2 +\n            service_during sched j_fst t1 t2 +\n            \\sum_(0 <= i < num_mid_jobs)\n             service_during sched (nth elem sorted_jobs i.+1) t1 t2\n          <= workload_bound.\n        Proof.\n          rename H_valid_task_parameters into PARAMS.\n          unfold is_valid_sporadic_task in *; des.\n          unfold workload_bound, W; fold n_k.\n          move => NK; rewrite -NK.\n          apply leq_add;\n            last by apply workload_bound_service_of_middle_jobs.\n          apply leq_trans with (delta + R_tsk - (job_arrival j_lst - job_arrival j_fst)).\n          {\n            rewrite addnC -workload_bound_simpl_expression_with_first_and_last.\n            by apply workload_bound_service_of_first_and_last_jobs.\n          }\n          rewrite leq_min; apply/andP; split.\n          {\n            rewrite leq_subLR [_ + task_cost _]addnC -leq_subLR.\n            apply leq_trans with (num_mid_jobs.+1 * task_period tsk);\n              last by apply workload_bound_many_periods_in_between.\n            rewrite NK ltnW // -ltn_divLR;\n              last by apply PARAMS0.\n            by unfold n_k, max_jobs, div_floor.\n          }\n          {\n            rewrite -subnDA; apply leq_sub2l.\n            apply leq_trans with (n := num_mid_jobs.+1 * task_period tsk);\n              last by apply workload_bound_many_periods_in_between.\n            rewrite -addn1 addnC mulnDl mul1n.\n            by rewrite leq_add2l; last by apply PARAMS3.\n          }\n        Qed.\n\n        (* If n_k = num_mid_jobs + 1, then the workload bound holds. *)\n        Lemma workload_bound_n_k_equals_num_mid_jobs_plus_1 :\n          num_mid_jobs.+1 = n_k ->\n          service_during sched j_lst t1 t2 +\n            service_during sched j_fst t1 t2 +\n            \\sum_(0 <= i < num_mid_jobs)\n             service_during sched (nth elem sorted_jobs i.+1) t1 t2\n          <= workload_bound.\n        Proof.\n          have MID := workload_bound_service_of_middle_jobs. \n          rename H_jobs_have_valid_parameters into JOBPARAMS.\n          unfold workload_bound, W; fold n_k.\n          move => NK; rewrite -NK.\n          rewrite -{2}addn1 mulnDl mul1n [_* _ + _]addnC addnA addn_minl.\n          apply leq_add; last by apply MID.\n          rewrite leq_min; apply/andP; split.\n          {\n            assert (SIZE: 0 < size sorted_jobs).\n              by rewrite H_at_least_two_jobs.\n            have INfst := workload_bound_j_fst_is_job_of_tsk SIZE elem;\n            have INlst := workload_bound_j_lst_is_job_of_tsk; des.\n            have PARAMSfst := JOBPARAMS j_fst INfst; des.\n            have PARAMSlst := JOBPARAMS j_lst INlst; des.\n            by apply leq_add; apply cumulative_service_le_task_cost with\n                    (task_deadline0 := task_deadline)\n                    (job_cost0 := job_cost) (job_deadline0 := job_deadline) (job_task0 := job_task).\n          }\n          {\n            rewrite subnAC subnK; last first.\n            {\n              assert (TMP: delta + R_tsk = task_cost tsk + (delta + R_tsk - task_cost tsk));\n                first by rewrite subnKC; [by ins | by rewrite -[task_cost _]add0n; apply leq_add].\n              rewrite TMP; clear TMP.\n              rewrite -{1}[task_cost _]addn0 -addnBA NK; [by apply leq_add | by apply leq_trunc_div].\n            }\n            apply leq_trans with (delta + R_tsk - (job_arrival j_lst - job_arrival j_fst)).\n            {\n              rewrite addnC -workload_bound_simpl_expression_with_first_and_last.\n              by apply workload_bound_service_of_first_and_last_jobs.\n            }\n            {\n              by apply leq_sub2l, workload_bound_many_periods_in_between.\n            }\n          }\n        Qed.\n        \n      End WorkloadTwoOrMoreJobs.\n\n      (* Using the lemmas above, we prove the main theorem about the workload bound. *)\n      Theorem workload_bounded_by_W :\n        workload_of tsk t1 (t1 + delta) <= workload_bound.\n      Proof.\n        unfold workload_of, workload_bound, W in *; ins; des.\n        fold n_k.\n\n        (* Use the definition of workload based on list of jobs. *)\n        rewrite workload_eq_workload_joblist.\n\n        (* Now we order the list by job arrival time. *)\n        rewrite workload_bound_simpl_by_sorting_scheduled_jobs.\n\n        (* Next, we show that the workload bound holds if n_k\n           is no larger than the number of interferings jobs. *)\n        destruct (size sorted_jobs <= n_k) eqn:NUM;\n          first by apply workload_bound_holds_for_at_most_n_k_jobs.\n        apply negbT in NUM; rewrite -ltnNge in NUM.\n\n        (* Find some dummy element to use in the nth function *)\n        assert (EX: exists elem: Job, True).\n          destruct sorted_jobs; [ by rewrite ltn0 in NUM | by exists s].\n        destruct EX as [elem _].\n\n        (* Now we index the sum to access the first and last elements. *)\n        rewrite (big_nth elem).\n\n        (* First, we show that the bound holds for an empty list of jobs. *)\n        destruct (size sorted_jobs) as [| n] eqn:SIZE;\n          first by rewrite big_geq.\n        \n        (* Then, we show the same for a singleton set of jobs. *)\n        destruct n as [| num_mid_jobs];\n          first by apply workload_bound_holds_for_a_single_job; rewrite SIZE.\n        \n        (* Knowing that we have at least two elements, we take first and last out of the sum *) \n        rewrite [nth]lock big_nat_recl // big_nat_recr // /= -lock.\n        rewrite addnA addnC addnA.\n    \n        (* There are two cases to be analyze since n <= n_k < n + 2,\n           where n is the number of middle jobs. *)\n        have NK := workload_bound_n_k_covers_middle_jobs num_mid_jobs SIZE elem.\n        move: NK; rewrite leq_eqVlt orbC leq_eqVlt; move => /orP [NK | /eqP NK].\n        move: NK => /orP [/eqP NK | NK]; last by rewrite ltnS leqNgt NK in NUM.\n        {\n          (* Case 1: n_k = n + 1, where n is the number of middle jobs. *)\n          by apply (workload_bound_n_k_equals_num_mid_jobs_plus_1 num_mid_jobs).\n        }\n        {\n          (* Case 2: n_k = n, where n is the number of middle jobs. *)\n          by apply (workload_bound_n_k_equals_num_mid_jobs num_mid_jobs).\n        }\n      Qed.\n\n    End MainProof.\n    \n  End ProofWorkloadBound.\n\nEnd WorkloadBound.", "meta": {"author": "cd-public", "repo": "rt-proofs", "sha": "ebef0b65460fe009c51f638fe2b459f16a6d1dd5", "save_path": "github-repos/coq/cd-public-rt-proofs", "path": "github-repos/coq/cd-public-rt-proofs/rt-proofs-ebef0b65460fe009c51f638fe2b459f16a6d1dd5/analysis/apa/workload_bound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6823203549355076}}
{"text": "From Tweetnacl Require Import Libs.Export.\nRequire Import ssreflect.\n\nOpen Scope Z.\n\n\nDefinition red_by_P n :=\n  let n' := n - (2^255-19) in\n  if Z.leb 0 n' then\n    let n'' := n' - (2^255-19) in \n    if Z.leb 0 n'' then\n      n''\n    else\n      n'\n  else\n    n.\n\nDefinition ZPack25519 n := \n  Z.modulo n (Z.pow 2 255 - 19).\n\nLemma reduce_pos :  forall n, 0 <= n -> 0 <= red_by_P n.\nProof. move=> n Hn ; rewrite /red_by_P.\nflatten.\napply Zle_bool_imp_le in Eq0.\nomega.\napply Zle_bool_imp_le in Eq.\nomega.\nQed.\n\nLemma reduce_max : forall n, n < 2^256 -> red_by_P n < 2 ^ 255 - 19.\nProof.\nmove => n Hn ; rewrite /red_by_P.\nflatten.\n{\napply Zle_bool_imp_le in Eq0.\napply Zle_bool_imp_le in Eq.\nassert(n - (2 ^ 255 - 19) - (2 ^ 255 - 19) < 2 ^ 256 - (2 ^ 255 - 19) - (2 ^ 255 - 19)) by omega.\nchange (2 ^ 256 - (2 ^ 255 - 19) - (2 ^ 255 - 19)) with 38 in H.\nchange (2^255 - 19) with (57896044618658097711785492504343953926634992332820282019728792003956564819949) in *.\nomega.\n}\n{\napply Zle_bool_imp_le in Eq.\napply Z.leb_gt in Eq0.\nomega.\n}\n{\napply Z.leb_gt in Eq.\nomega.\n}\nQed.\n\nTheorem reduce_P_mod_correct : forall n,\n  (red_by_P n) mod (2^255-19) = n mod (2^255-19).\nProof.\n  intros.\n  rewrite /red_by_P.\n  flatten;\n  repeat match goal with \n    | _ => reflexivity\n    | _ => rewrite -Zminus_0_l_reverse Z.mod_mod\n    | _ => rewrite Zminus_mod ; change ((2 ^ 255 - 19) :𝓖𝓕) with 0\n    | |- _ <> _ => compute ; go\n  end.\nQed.\n\nTheorem reduce_P_is_mod : forall n,\n  0 <= n < 2 ^ 256 ->\n  ZPack25519 n = red_by_P n.\nProof. intros.\nrewrite /ZPack25519 -reduce_P_mod_correct.\napply Zmod_small.\nsplit.\napply reduce_pos ; omega.\napply reduce_max ; omega.\nQed.\n\nLemma sub_div_256_pos : forall n, 0 <= n < 2 ^256 -> \n  0 <= n - (2^255 - 19) ->\n  0 <= (n - (2^255 - 19)) / 2 ^ 256 .\nProof.\nintros.\napply Z_div_pos.\ncompute ; go.\nassumption.\nQed.\n\nLemma sub_div_256_neg : forall n, 0 <= n < 2 ^256 -> \n  n - (2^255 - 19) < 0 ->\n  (n - (2^255 - 19)) / 2 ^ 256 = -1.\nProof.\nintros.\nassert((n - (2 ^ 255 - 19)) / 2 ^ 256 < 0).\napply Zdiv_lt_upper_bound.\ncompute ; go.\nchange(0 * 2^256) with 0.\nassumption.\nassert(-1 <= (n - (2 ^ 255 - 19)) / 2 ^ 256).\napply Z.div_le_lower_bound.\ncompute ; go.\nchange (2 ^ 256) with 115792089237316195423570985008687907853269984665640564039457584007913129639936 in *.\nchange (2^255 - 19) with 57896044618658097711785492504343953926634992332820282019728792003956564819949 in *.\nomega.\nomega.\nQed.\n\nClose Scope Z.", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/proofs/spec/Mid/Pack25519.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6823102057165572}}
{"text": "Require Import Problem.\n\nLemma lemma : forall l a, list_in l a = false -> list_in (unique l) a = false.\nProof.\n  intros.\n  induction l; simpl; [auto|].\n  simpl in H.\n  remember (Nat.eqb a a0).\n  destruct b.\n  discriminate.\n  destruct (list_in l a0); [auto|].\n  simpl.\n  rewrite <- Heqb.\n  auto.\nQed.\n\nTheorem solution : task.\nProof.\n  unfold Problem.task.\n  induction l; simpl; [auto|].\n  simpl.\n  remember (list_in l a).\n  destruct b; [auto|].\n  simpl.\n  rewrite IHl.\n  rewrite lemma; 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/018/Solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6822971377195631}}
{"text": "(*\n  The \"Tm\" type and the previously defined transition judgements.\n  Do not modify these!\n\n  The task starts at line 180.\n*)\n\nRequire Import Nat.\nRequire Import Arith.\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\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\nDelimit Scope term_scope with term.\n(* Bind Scope term_scope with Tm. *)\nOpen Scope term_scope.\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  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  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(* 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\n(*\n  2.27. Tétel.\n  Theorem of type preservation.\n*)\n\nTheorem type_preservation {t t' : Tm} :\n  (t |-> t') -> (forall A : Ty, (t :: A) -> (t' :: A))\n.\nProof.\n  intros H.\n  induction H.\n\n  (* sum *)\n  - intros. inversion H0. exact TJ_num.\n\n  (* isZero_true *)\n  - intros. inversion H. exact TJ_true.\n\n  (* isZero_false *)\n  - intros. inversion H0. exact TJ_false.\n\n  (* ifThenElse_true *)\n  - intros. inversion H. exact j'.\n\n  (* ifThenElse_false *)\n  - intros. inversion H. exact j''.\n\n  (* plus_left *)\n  - intros. inversion H0.\n    refine (TJ_plus _ j').\n    + pose (ir := IHOneStepTransitionJudgement Nat j).\n      exact ir.\n\n  (* plus_right *)\n  - intros. inversion H1.\n    refine (TJ_plus j _).\n    + pose (ir := IHOneStepTransitionJudgement Nat j').\n      exact ir.\n\n  (* isZero *)\n  - intros. inversion H0.\n    refine (TJ_isZero _).\n    + exact (IHOneStepTransitionJudgement Nat j).\n\n  (* ifThenElse *)\n  - intros. inversion H0.\n    refine (TJ_ifThenElse _ j' j'').\n    + exact (IHOneStepTransitionJudgement Bool j).\nQed.\n\n\n(* ------------------------------ *)\n\n(*\n  Prove the following theorem!\n*)\n\nTheorem any_step_type_preservation {t t' : Tm} :\n  (t |->* t') -> (forall A : Ty, (t :: A) -> (t' :: A))\n.\nProof.\n  intro. induction H. \n  + intros. exact H.\n  + intros. pose (singleStepTyPres := type_preservation H).\n    apply IHAnyStepTransitionJudgement. \n    apply singleStepTyPres. exact H1. \nQed.", "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/any_step_type_preservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6822971270504379}}
{"text": "Require Export Ensembles.\nRequire Import EnsemblesImplicit.\nRequire Export Families.\nRequire Export IndexedFamilies.\nRequire Export FiniteTypes.\nRequire Import EnsemblesSpec.\n\nRecord TopologicalSpace : Type := {\n  point_set : Type;\n  open : Ensemble point_set -> Prop;\n  open_family_union : forall F : Family point_set,\n    (forall S : Ensemble point_set, In F S -> open S) ->\n    open (FamilyUnion F);\n  open_intersection2: forall U V:Ensemble point_set,\n    open U -> open V -> open (Intersection U V);\n  open_full : open Full_set\n}.\n\nImplicit Arguments open [[t]].\nImplicit Arguments open_family_union [[t]].\nImplicit Arguments open_intersection2 [[t]].\n\nLemma open_empty: forall X:TopologicalSpace,\n  open (@Empty_set (point_set X)).\nProof.\nintros.\nrewrite <- empty_family_union.\napply open_family_union.\nintros.\ndestruct H.\nQed.\n\nLemma open_union2: forall {X:TopologicalSpace}\n  (U V:Ensemble (point_set X)), open U -> open V -> open (Union U V).\nProof.\nintros.\nassert (Union U V = FamilyUnion (Couple U V)).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H1.\nexists U; auto with sets.\nexists V; auto with sets.\ndestruct H1.\ndestruct H1.\nleft; trivial.\nright; trivial.\n\nrewrite H1; apply open_family_union.\nintros.\ndestruct H2; trivial.\nQed.\n\nLemma open_indexed_union: forall {X:TopologicalSpace} {A:Type}\n  (F:IndexedFamily A (point_set X)),\n  (forall a:A, open (F a)) -> open (IndexedUnion F).\nProof.\nintros.\nrewrite indexed_to_family_union.\napply open_family_union.\nintros.\ndestruct H0.\nrewrite H1; apply H.\nQed.\n\nLemma open_finite_indexed_intersection:\n  forall {X:TopologicalSpace} {A:Type}\n    (F:IndexedFamily A (point_set X)),\n    FiniteT A -> (forall a:A, open (F a)) ->\n    open (IndexedIntersection F).\nProof.\nintros.\ninduction H.\nrewrite empty_indexed_intersection.\napply open_full.\n\nassert (IndexedIntersection F = Intersection\n  (IndexedIntersection (fun x:T => F (Some x)))\n  (F None)).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H1.\nconstructor.\nconstructor.\nintros; apply H1.\napply H1.\ndestruct H1.\ndestruct H1.\nconstructor.\ndestruct a.\napply H1.\napply H2.\nrewrite H1.\napply open_intersection2.\napply IHFiniteT.\nintros; apply H0.\napply H0.\n\ndestruct H1.\nassert (IndexedIntersection F =\n  IndexedIntersection (fun x:X0 => F (f x))).\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\ndestruct H3.\nintro; apply H3.\nconstructor.\ndestruct H3.\nintro; rewrite <- H2 with a.\napply H3.\nrewrite H3.\napply IHFiniteT.\nintro; apply H0.\nQed.\n\nDefinition closed {X:TopologicalSpace} (F:Ensemble (point_set X)) :=\n  open (Ensembles.Complement F).\n\nLemma closed_complement_open: forall {X:TopologicalSpace}\n  (U:Ensemble (point_set X)), closed (Ensembles.Complement U) ->\n  open U.\nProof.\nintros.\nred in H.\nrewrite Complement_Complement in H.\nassumption.\nQed.\n\nLemma closed_union2: forall {X:TopologicalSpace}\n  (F G:Ensemble (point_set X)),\n  closed F -> closed G -> closed (Union F G).\nProof.\nintros.\nred in H, H0.\nred.\nassert (Ensembles.Complement (Union F G) =\n  Intersection (Ensembles.Complement F)\n               (Ensembles.Complement G)).\nunfold Ensembles.Complement.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nauto with sets.\nauto with sets.\ndestruct H1.\nred; red; intro.\ndestruct H3.\napply (H1 H3).\napply (H2 H3).\n\nrewrite H1.\napply open_intersection2; assumption.\nQed.\n\nLemma closed_intersection2: forall {X:TopologicalSpace}\n  (F G:Ensemble (point_set X)),\n  closed F -> closed G -> closed (Intersection F G).\nProof.\nintros.\nred in H, H0.\nred.\nassert (Ensembles.Complement (Intersection F G) =\n  Union (Ensembles.Complement F)\n        (Ensembles.Complement G)).\napply Extensionality_Ensembles; split; red; intros.\napply NNPP.\nred; intro.\nunfold Ensembles.Complement in H1.\nunfold In in H1.\ncontradict H1.\nconstructor.\napply NNPP.\nred; intro.\nauto with sets.\napply NNPP.\nred; intro.\nauto with sets.\n\nred; red; intro.\ndestruct H2.\ndestruct H1; auto with sets.\n\nrewrite H1; apply open_union2; trivial.\nQed.\n\nLemma closed_family_intersection: forall {X:TopologicalSpace}\n  (F:Family (point_set X)),\n  (forall S:Ensemble (point_set X), In F S -> closed S) ->\n  closed (FamilyIntersection F).\nProof.\nintros.\nunfold closed in H.\nred.\nassert (Ensembles.Complement (FamilyIntersection F) =\n  FamilyUnion [ S:Ensemble (point_set X) |\n                  In F (Ensembles.Complement S) ]).\napply Extensionality_Ensembles; split; red; intros.\napply NNPP.\nred; intro.\nred in H0; red in H0.\ncontradict H0.\nconstructor.\nintros.\napply NNPP.\nred; intro.\ncontradict H1.\nexists (Ensembles.Complement S).\nconstructor.\nrewrite Complement_Complement; assumption.\nassumption.\ndestruct H0.\nred; red; intro.\ndestruct H2.\ndestruct H0.\npose proof (H2 _ H0).\ncontradiction H3.\n\nrewrite H0; apply open_family_union.\nintros.\ndestruct H1.\npose proof (H _ H1).\nrewrite Complement_Complement in H2; assumption.\nQed.\n\nLemma closed_indexed_intersection: forall {X:TopologicalSpace}\n  {A:Type} (F:IndexedFamily A (point_set X)),\n  (forall a:A, closed (F a)) -> closed (IndexedIntersection F).\nProof.\nintros.\nrewrite indexed_to_family_intersection.\napply closed_family_intersection.\nintros.\ndestruct H0.\nrewrite H1; trivial.\nQed.\n\nLemma closed_finite_indexed_union: forall {X:TopologicalSpace}\n  {A:Type} (F:IndexedFamily A (point_set X)),\n  FiniteT A -> (forall a:A, closed (F a)) ->\n  closed (IndexedUnion F).\nProof.\nintros.\nred.\nassert (Ensembles.Complement (IndexedUnion F) =\n  IndexedIntersection (fun a:A => Ensembles.Complement (F a))).\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nintros.\nred; red; intro.\ncontradiction H1.\nexists a.\nassumption.\ndestruct H1.\nred; red; intro.\ndestruct H2.\ncontradiction (H1 a).\n\nrewrite H1; apply open_finite_indexed_intersection; trivial.\nQed.\n\nHint Unfold closed : topology.\nHint Resolve (@open_family_union) (@open_intersection2) open_full\n  open_empty (@open_union2) (@open_indexed_union)\n  (@open_finite_indexed_intersection) (@closed_complement_open)\n  (@closed_union2) (@closed_intersection2) (@closed_family_intersection)\n  (@closed_indexed_intersection) (@closed_finite_indexed_union)\n  : topology.\n\nSection Build_from_closed_sets.\n\nVariable X:Type.\nVariable closedP : Ensemble X -> Prop.\nHypothesis closedP_empty: closedP Empty_set.\nHypothesis closedP_union2: forall F G:Ensemble X,\n  closedP F -> closedP G -> closedP (Union F G).\nHypothesis closedP_family_intersection: forall F:Family X,\n  (forall G:Ensemble X, In F G -> closedP G) ->\n  closedP (FamilyIntersection F).\n\nDefinition Build_TopologicalSpace_from_closed_sets : TopologicalSpace.\nrefine (Build_TopologicalSpace X\n  (fun U:Ensemble X => closedP (Ensembles.Complement U)) _ _ _).\nintros.\nreplace (Ensembles.Complement (FamilyUnion F)) with\n  (FamilyIntersection [ G:Ensemble X | In F (Ensembles.Complement G) ]).\napply closedP_family_intersection.\ndestruct 1.\nrewrite <- Complement_Complement.\napply H; trivial.\napply Extensionality_Ensembles; split; red; intros.\nintro.\ndestruct H1.\ndestruct H0.\nabsurd (In (Ensembles.Complement S) x).\nintro.\ncontradiction H3.\napply H0.\nconstructor.\nrewrite Complement_Complement; trivial.\nconstructor.\ndestruct 1.\napply NNPP; intro.\ncontradiction H0.\nexists (Ensembles.Complement S); trivial.\n\nintros.\nreplace (Ensembles.Complement (Intersection U V)) with\n  (Union (Ensembles.Complement U) (Ensembles.Complement V)).\napply closedP_union2; trivial.\napply Extensionality_Ensembles; split; red; intros.\nintro.\ndestruct H2.\ndestruct H1; contradiction H1.\napply NNPP; intro.\ncontradiction H1.\nconstructor; apply NNPP; intro; contradiction H2;\n  [ left | right ]; trivial.\n\napply eq_ind with (1 := closedP_empty).\napply Extensionality_Ensembles; split; auto with sets;\n  red; intros.\ncontradiction H.\nconstructor.\nDefined.\n\nLemma Build_TopologicalSpace_from_closed_sets_closed:\n  forall (F:Ensemble (point_set Build_TopologicalSpace_from_closed_sets)),\n  closed F <-> closedP F.\nProof.\nintros.\nunfold closed.\nsimpl.\nrewrite Complement_Complement.\nsplit; trivial.\nQed.\n\nEnd Build_from_closed_sets.\n\nImplicit Arguments Build_TopologicalSpace_from_closed_sets [[X]].\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/TopologicalSpaces.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6822971263211945}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\n\nInductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\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\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'.\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} x count.\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\nInductive list' {X:Type} : Type :=\n  | nil'\n  | cons' (x : X) (l : list').\n\nFixpoint app {X : Type} (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity. Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity. Qed.\n\nFail Definition mynil := 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\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros X l. induction l as [| h t IHt'].\n  - reflexivity. \n  - simpl. rewrite -> IHt'. reflexivity. Qed.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros A l m n. induction l as [|h t IHt].\n  - simpl. reflexivity. \n  - simpl. rewrite -> IHt. reflexivity. Qed.\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 [|h t IHt].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHt. reflexivity. Qed.\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. induction l1 as [|h t IHt].\n  - simpl. assert(app_nil_right: rev l2 ++ [ ] = rev l2). \n    { induction l2 as [|h' t' IHt']. \n      - simpl. reflexivity. \n      - simpl. rewrite <- app_assoc. rewrite <- IHt'. reflexivity. } \n    rewrite -> app_nil_right. reflexivity.\n  - simpl. rewrite -> IHt. rewrite <- app_assoc. reflexivity. Qed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros X l. induction l as [| h t IHt]. \n  - simpl. reflexivity.\n  - simpl. rewrite -> rev_app_distr. rewrite -> IHt. simpl. reflexivity. Qed.\n\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\n\nArguments pair {X} {Y} _ _.\n\nNotation \"( x , y )\" := (pair x y).\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 (*standard, optional (combine_checks)*)\n (* type of combine -> forall X Y : Type, list X -> list Y -> list (X * Y)*)\n (*Compute (combine [1;2] [false;false;true;true]). -> [(1,false);(2,false)]]*)\nCompute (combine [1;2] [false;false;true;true]).\n\n (*standard, recommended (split)*)\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y):=\n  match l with\n  | nil => ([],[])\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.\n  simpl. reflexivity. Qed.\n\n\nModule OptionPlayground.\n\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\n\nArguments Some {X} _.\nArguments None {X}.\n\nEnd OptionPlayground.\n\nRequire Import PeanoNat.\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if n =? O then Some a else nth_error l' (pred n)\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\n\n (*standard, optional (hd_error_poly)*)\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n  | nil => None\n  | h :: t => Some h\n  end.\n\nCheck @hd_error.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\nProof.\n  simpl. reflexivity. Qed.\nExample test_hd_error2 : hd_error [[1];[2]] = Some [1].\nProof.\n  simpl. reflexivity. Qed.\n\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 :=\n  match n with\n    | O => O\n    | S O => O\n    | S (S n') => n'\n  end.\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity. Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | [] => []\n  | h :: t => if test h then h :: (filter test t)\n                        else filter test t\n  end.\n\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_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity. Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  (length l) =? 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\n\n (*standard (filter_even_gt7)*)\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\nFixpoint more_than (a b:nat) : bool :=\n  match a with\n  | O => match b with\n         | O => false\n         | S b' => false\n         end\n  | S a' => match b with\n            | O => true\n            | S b' => more_than a' b'\n            end\n  end.\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n => andb (evenb n) (more_than n 7)) l.\n\nCompute(filter_even_gt7 [1;2;6;9;10;3;12;8]).\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity. Qed. \n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = []. \nProof. reflexivity. Qed. \n\n\n (*standard (partition)*)\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\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\nCompute(partition oddb [1;2;3;4;5] ).\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) : (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\n (*standard (map_rev)*)\nLemma map_app : forall (X Y : Type) (f : X -> Y) (l1 l2 : list X),\n  map f (l1 ++ l2) = map f l1 ++ map f l2.\nProof.\n  intros X Y f l1 l2. induction l1 as [| h1 t1 IHt1].\n  - simpl. reflexivity. \n  - simpl. rewrite -> IHt1. 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 [| h t IHt].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHt. rewrite -> map_app. reflexivity. Qed.\n (*/standard (map_rev)*)\n\n(*standard, recommended (flat_map)*) \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(*/standard, recommended (flat_map)*) \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 (*standard, optional (implicit_args)*)\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' X test t)\n                        else filter' X test t\n  end.\n\nExample test_filter'1: filter' nat evenb [1;2;3;4] = [2;4].\nProof. reflexivity. Qed.\n\nExample test_filter'2:\n    filter' (list nat) length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\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' X Y f t)\n  end.\n\nExample test_map'1: map' nat nat (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\nExample test_map'2:\n  map' nat bool oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity. Qed.\n\nExample test_map'3:\n    map' nat (list bool) (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity. Qed. \n(*/standard, optional (implicit_args)*)\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).\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 (* standard (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_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros X l. induction l as [|h t IHt].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHt. reflexivity. Qed.\n (* /standard (fold_length)*)\n\n (*standard (fold_map)*)\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y :=\n  fold (fun x ly => (f x) :: ly) l [].\n\nTheorem map_fold_map_eq :\n  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. induction l as [| h t IHt].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHt. reflexivity. Qed.\n (*/standard (fold_map)*)\n\n\n(*advanced (currying)*)\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 := (f (fst p))(snd p).\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  intros X Y Z x y z. reflexivity. Qed.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros X Y Z f p. destruct p as [x y]. reflexivity. Qed.\n(*/advanced (currying)*)\n\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\n\n(*advanced (church_succ)*)\nDefinition succ (n : cnat) : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f(n X f x).\n\nExample succ_1 : succ zero = one.\nProof. reflexivity. Qed.\n\nExample succ_2 : succ one = two.\nProof. reflexivity. Qed.\n\nExample succ_3 : succ two = three.\nProof. reflexivity. Qed.\n\nEnd Church.\n(*/advanced (church_succ)*)\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/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.8688267762381843, "lm_q1q2_score": 0.6822971226848942}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Omega Wellfounded Relations.\n\nRequire Import base.\n\nSet Implicit Arguments.\n\nLocal Notation \"A ⊆ B\" := (∀x y, A x y -> B x y).\n\n(** Symbols for copy/paste: ∩ ∪ ⊆ ⊇ ⊔ ⊓ ⊑ ≡  ⋅ ↑ ↓ ⇑ ⇓ ∀ ∃ *)\n\nSection IND.\n\n  (* This characterization of well_founded comes from Berardi's paper *)\n\n  (* A R-inductive property *)\n\n   Definition IND I (R : I -> I -> Prop) (P : I -> Prop) := forall x, (forall y, R y x -> P y) -> P x.\n\n   Variable (X : Type) (D : X -> Prop) (R : X -> X -> Prop).\n   \n   Implicit Type (P : X -> Prop).\n\n  (* A R-inductive property over a subtype D *)\n\n  Definition IND_st P := forall x, D x -> (forall y, D y -> R y x -> P y) -> P x.\n    \n  (* P is R-inductive over subtype D iff P restricted to D is (R restricted to D)-inductive *)\n    \n  Theorem IND_st_IND P : IND_st P <-> IND (R⬇D) (P↡D).\n  Proof.\n    split.\n    * intros H (x & Hx) H1; simpl.\n      apply (H _ Hx).\n      intros y Hy; apply (H1 (exist _ y Hy)).\n    * intros H x Hx H1.\n      apply (H (exist _ x Hx)).\n      intros (y & ?); cbv; auto.\n  Qed.\n\n  (* a point is R-well-founded iff it is contained in any R-inductive property *)\n  \n  Definition wf x := ∀P, IND R P -> P x.\n  \n  (* This is the same as accessibility *)\n  \n  Lemma wf_eq_Acc x : wf x <-> Acc R x.\n  Proof.\n    split.\n    * intros H; apply H.\n      intro; apply Acc_intro.\n    * intros H P HP; revert H.\n      induction 1 as [ x _ IHx ].\n      apply HP, IHx.\n  Qed.\n  \n  (* a relation is well_founded iff all its points are well-founded *)\n\n  Theorem well_founded_all_wf : well_founded R <-> ∀ x, wf x.\n  Proof. split; intros H x; generalize (H x); apply wf_eq_Acc. Qed.\n  \n  (* a point is R-well-founded over D iff it is contained in D and in any R-inductive property over D *)\n\n  Definition wf_st x := D x /\\ ∀P, IND_st P -> P x.\n  \n  (* This is the same as accessibility in the subtype *)\n  \n  Lemma wf_st_eq_Acc x : wf_st x <-> D x /\\ ∀H, Acc (R⬇D) (exist _ x H).\n  Proof.\n    split.\n    * intros (H & H1); split; auto; clear H.\n      apply H1.\n      intros y H2 H3 H4.\n      constructor 1.\n      intros (z & Hz) H5.\n      apply H3; auto.\n    * intros (H1 & H2).\n      split; auto; intros P HP.\n      change (P (proj1_sig (exist _ x H1))).\n      generalize (exist _ x H1) (H2 H1); clear x H1 H2.\n      induction 1 as [ (x & Hx) H IH ]; simpl.\n      apply HP; auto.\n      intros y H3 H4.\n      apply (IH (exist _ y H3)); auto.\n  Qed.\n\n  Theorem well_founded_all_wf_st : well_founded (R⬇D) <->  ∀ x P, D x -> IND_st P -> P x.\n  Proof.\n    split.\n    * intros H x P H1; revert P.\n      apply (wf_st_eq_Acc x); split; auto.\n    * intros H (x & Hx).\n      apply wf_st_eq_Acc; split; auto.\n      intro; apply H; auto.\n  Qed.\n\nEnd IND.\n\n", "meta": {"author": "DmxLarchey", "repo": "Ramsey", "sha": "24510f63d4290149c4944fe68267d342345621ed", "save_path": "github-repos/coq/DmxLarchey-Ramsey", "path": "github-repos/coq/DmxLarchey-Ramsey/Ramsey-24510f63d4290149c4944fe68267d342345621ed/src/wf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.682297120986632}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral}.\n\nLemma lemma_s_incirc_within_radius :\n\tforall P J U V W X Y,\n\tCI J U V W ->\n\tBetS U Y X ->\n\tCong U X V W ->\n\tCong U P U Y ->\n\tInCirc P J.\nProof.\n\tintros P J U V W X Y.\n\tintros CI_J_U_VW.\n\tintros BetS_U_Y_X.\n\tintros Cong_UX_VW.\n\tintros Cong_UP_UY.\n\tunfold InCirc.\n\texists X, Y, U, V, W.\n\tsplit.\n\texact CI_J_U_VW.\n\tright.\n\trepeat split.\n\texact BetS_U_Y_X.\n\texact Cong_UX_VW.\n\texact Cong_UP_UY.\nQed.\n\nEnd Euclid.\n\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_s_incirc_within_radius.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6822971173503313}}
{"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\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.\nFrom PLF Require Import Maps.\nFrom PLF Require Import Imp.\n\n Inductive tm : Type :=\n  | C : nat -> tm        (* Constant *)\n  | P : tm  -> tm -> tm. (* Plus *)\n\nFixpoint evalF (t : tm) : nat :=\n  match t with\n  | C n   => n\n  | P a b => evalF a + evalF b\n  end.\n\nReserved Notation \" t '==>' n \" (at level 50, left associativity).\nInductive eval : tm -> nat -> Prop :=\n  | E_Const : forall n,\n      C n ==> n\n  | E_Plus : forall t1 t2 n1 n2,\n      t1 ==> n1 ->\n      t2 ==> n2 ->\n      P t1 t2 ==> (n1 + n2)\nwhere \" t '==>' n \" := (eval t n).\n\n\n\nModule SimpleArith1.\n  Reserved Notation \" t '-->' t' \" (at level 40).\n  Inductive step : tm -> tm -> Prop :=\n    | ST_PlusConstConst : forall n m,\n        P (C n) (C m) --> C (n + m)\n    | ST_Plus1 : forall t1 t1' t2,\n        t1 --> t1' ->\n        P t1 t2 --> P t1' t2\n    | ST_Plus2 : forall n t2 t2',\n        t2 --> t2' ->\n        P (C n) t2 --> P (C n) t2'\n    where \" t '-->' t' \" := (step t t').\n\n   Example test_step_2 :\n        P\n          (C 0)\n          (P\n            (C 2)\n            (P (C 1) (C 3)))\n        -->\n        P\n          (C 0)\n          (P\n            (C 2)\n            (C 4)).\n  Proof.\n    apply ST_Plus2.\n    apply ST_Plus2.\n    apply ST_PlusConstConst.\n  Qed.\nEnd SimpleArith1.\n\n\n(* See Rel.v in vol1 *)\nDefinition relation (X : Type) := X -> X -> Prop.\n\nDefinition deterministic {X : Type} (R : relation X) :=  forall x y1 y2 : X, \n  R x y1 -> R x y2 -> y1 = y2.\n\nModule SimpleArith2.\n  Import SimpleArith1.\n  Theorem step_deterministic:  deterministic step.\n  Proof.\n    unfold deterministic. intros x y1 y2 Hy1 Hy2.\n    generalize dependent y2.\n    induction Hy1; intros y2 Hy2.\n    - (* ST_PlusConstConst *) inversion Hy2; subst.\n      + (* ST_PlusConstConst *) reflexivity.\n      + (* ST_Plus1 *) inversion H2.\n      + (* ST_Plus2 *) inversion H2.\n    - (* ST_Plus1 *) inversion Hy2; subst.\n      + (* ST_PlusConstConst *)\n        inversion Hy1.\n      + (* ST_Plus1 *)\n        apply IHHy1 in H2. rewrite H2. reflexivity.\n      + (* ST_Plus2 *)\n        inversion Hy1.\n    - (* ST_Plus2 *) inversion Hy2; subst.\n      + (* ST_PlusConstConst *)\n        inversion Hy1.\n      + (* ST_Plus1 *) inversion H2.\n      + (* ST_Plus2 *)\n        apply IHHy1 in H2. rewrite H2. reflexivity.\n  Qed.\nEnd SimpleArith2.\n\nLtac solve_by_inverts n :=\n  match goal with \n  | H : ?T |- _ =>\n    match type of T with \n    | Prop =>\n      solve [\n        inversion H;\n        match n with S (S (?n')) => subst; solve_by_inverts (S n') end ]\n    end \n  end.\n\nLtac solve_by_invert :=  solve_by_inverts 1.\n\nModule SimpleArith3.\n  Import SimpleArith1.\n  Theorem step_deterministic_alt: deterministic step.\n  Proof.\n    intros x y1 y2 Hy1 Hy2.\n    generalize dependent y2.\n    induction Hy1; intros y2 Hy2;\n      inversion Hy2; subst; try solve_by_invert.\n    - (* ST_PlusConstConst *) reflexivity.\n    - (* ST_Plus1 *)\n      apply IHHy1 in H2. rewrite H2. reflexivity.\n    - (* ST_Plus2 *)\n      apply IHHy1 in H2. rewrite H2. reflexivity.\n  Qed.\nEnd SimpleArith3.\n\n\n\nInductive value : tm -> Prop :=\n  | v_const: forall n, value (C n).\n\nReserved Notation \" t '-->' t' \" (at level 40).\nInductive step : tm -> tm -> Prop :=\n  | ST_PlusConstConst : forall n m,\n          P (C n) (C m) --> C (n + m)\n  | ST_Plus1 : forall t1 t1' t2,\n        t1 --> t1' -> P t1 t2 --> P t1' t2\n  | ST_Plus2 : forall v t2 t2',\n        value v ->\n        t2 --> t2' ->\n        P v t2 --> P v t2'\n  where \" t '-->' t' \" := (step t t').\n\nTheorem step_deterministic :  deterministic step.\nProof.\n  unfold deterministic. intros x y1 y2 H1 H2.\n  generalize dependent y2.\n  induction H1; intros y2 H2.\n  - inversion H2; subst.\n    + reflexivity.\n    + inversion H3.\n    + inversion H4.\n  - inversion H2; subst.\n    + inversion H1.\n    + assert (G: t1' = t1'0). {\n        apply IHstep.\n        apply H4.\n      }\n      rewrite G.\n      reflexivity.\n    + inversion H3; subst.\n      inversion H1.\n  - inversion H2; subst.\n    + inversion H1.\n    + inversion H; subst.\n      inversion H5.\n    + assert (G: t2' = t2'0). {\n        apply IHstep.\n        apply H6.\n      }\n      rewrite G. reflexivity.\nQed.\n\nTheorem strong_progress : forall t,\n  value t \\/ (exists t', t --> t').\nProof.\n  intro t.\n  induction t.\n  - left. apply v_const.\n  - right.\n    destruct IHt1 as [Ht1Val | Ht1Red].\n    + inversion Ht1Val; subst.\n      destruct IHt2 as [Ht2Val | Ht2Red].\n      * inversion Ht2Val; subst.\n        eexists.\n        apply ST_PlusConstConst.\n      * destruct Ht2Red as [t' Ht'].\n        eexists.\n        apply ST_Plus2.\n        apply Ht1Val.\n        apply Ht'.\n    + destruct Ht1Red as [t' Ht'].\n      eexists.\n      apply ST_Plus1.\n      apply Ht'.\nQed.\n\n\nDefinition normal_form {X : Type} (R : relation X) (t : X) : Prop :=\n  ~(exists t', R t t').\n\nLemma value_is_nf : forall v,\n  value v -> normal_form step v.\nProof.\n  intros v H H1.\n  inversion H.\n  subst.\n  destruct H1 as [t' H1'].\n  inversion H1'.\nQed.\n\nLemma nf_is_value : forall t,\n  normal_form step t -> value t.\nProof.\n  unfold normal_form. intros t H.\n  assert (G : value t \\/ exists t', t --> t').\n  { apply strong_progress. }\n  destruct G as [G | G].\n  - (* l *) apply G.\n  - (* r *) exfalso. apply H. assumption.\nQed.\n\nCorollary nf_same_as_value : forall t,\n  normal_form step t <-> value t.\nProof.\n  split. apply nf_is_value. apply value_is_nf.\nQed.\n\n\n\n\nModule Temp1.\n  Inductive value : tm -> Prop :=\n    | v_const : forall n, value (C n)\n    | v_funny : forall t1 n2, (* <--- NEW *)\n                  value (P t1 (C n2)).\n  Reserved Notation \" t '-->' t' \" (at level 40).\n  Inductive step : tm -> tm -> Prop :=\n    | ST_PlusConstConst : forall n1 n2,\n        P (C n1) (C n2) --> C (n1 + n2)\n    | ST_Plus1 : forall t1 t1' t2,\n        t1 --> t1' ->\n        P t1 t2 --> P t1' t2\n    | ST_Plus2 : forall v1 t2 t2',\n        value v1 ->\n        t2 --> t2' ->\n        P v1 t2 --> P v1 t2'\n    where \" t '-->' t' \" := (step t t').\n\n  Lemma value_not_same_as_normal_form :\n    exists v, value v /\\ ~ normal_form step v.\n  Proof.\n    exists (P (C 0) (C 0)).\n    split.\n    - apply v_funny.\n    - intro Hcontra. unfold normal_form in Hcontra.\n      apply Hcontra.\n      exists (C 0).\n      apply ST_PlusConstConst.\n  Qed.\nEnd Temp1.\n\nModule Temp2.\n  Inductive value : tm -> Prop :=\n    | v_const : forall n, value (C n). (* Original definition *)\n\n  Reserved Notation \" t '-->' t' \" (at level 40).\n  Inductive step : tm -> tm -> Prop :=\n    | ST_Funny : forall n,\n        C n --> P (C n) (C 0) (* <--- NEW *)\n    | ST_PlusConstConst : forall n1 n2,\n        P (C n1) (C n2) --> C (n1 + n2)\n    | ST_Plus1 : forall t1 t1' t2,\n        t1 --> t1' ->\n        P t1 t2 --> P t1' t2\n    | ST_Plus2 : forall v1 t2 t2',\n        value v1 ->\n        t2 --> t2' ->\n        P v1 t2 --> P v1 t2'\n    where \" t '-->' t' \" := (step t t').\n\n  Lemma value_not_same_as_normal_form :\n    exists v, value v /\\ ~normal_form step v.\n  Proof.\n    exists (C 0).\n    split.\n    - apply v_const.\n    - intro HContra. apply HContra.\n      exists (P (C 0) (C 0)).\n      apply ST_Funny.\n  Qed.\nEnd Temp2.\n\nModule Temp3.\n  Inductive value : tm -> Prop :=\n    | v_const : forall n, value (C n).\n\n  Reserved Notation \" t '-->' t' \" (at level 40).\n  Inductive step : tm -> tm -> Prop :=\n    | ST_PlusConstConst : forall n1 n2,\n        P (C n1) (C n2) --> C (n1 + n2)\n    | ST_Plus1 : forall t1 t1' t2,\n        t1 --> t1' ->\n        P t1 t2 --> P t1' t2\n    where \" t '-->' t' \" := (step t t').\n\n  Lemma value_not_same_as_normal_form :\n    exists t, ~ value t /\\ normal_form step t.\n  Proof.\n    exists (P (C 0) (P (C 0) (C 0))).\n    split.\n    - intros HContra. inversion HContra.\n    - intros HContra. destruct HContra as [t' HContra].\n      inversion HContra; subst. inversion H2.\n  Qed. \nEnd Temp3.\n\nModule Temp4.\n  Inductive tm : Type :=\n    | tru : tm\n    | fls : tm\n    | test : tm -> tm -> tm -> tm.\n  Inductive value : tm -> Prop :=\n    | v_tru : value tru\n    | v_fls : value fls.\n\n  Reserved Notation \" t '-->' t' \" (at level 40).\n  Inductive step : tm -> tm -> Prop :=\n    | ST_IfTrue : forall t1 t2,\n        test tru t1 t2 --> t1\n    | ST_IfFalse : forall t1 t2,\n        test fls t1 t2 --> t2\n    | ST_If : forall t1 t1' t2 t3,\n        t1 --> t1' ->\n        test t1 t2 t3 --> test t1' t2 t3\n    where \" t '-->' t' \" := (step t t').\n\n  (* Definition bool_step_prop1 :=  fls --> fls. *)\n  (*\n  Definition bool_step_prop2 :=\n       test\n         tru\n         (test tru tru tru)\n         (test fls fls fls)\n    -->\n       tru.\n  *)\n  (*\n  Definition bool_step_prop3 :=\n       test\n         (test tru tru tru)\n         (test tru tru tru)\n         fls\n     -->\n       test\n         tru\n         (test tru tru tru)\n         fls.\n  *)\n\n  Theorem strong_progress_bool : forall t,\n    value t \\/ (exists t', t --> t').\n  Proof.\n    intro t. induction t.\n    - left. constructor.\n    - left. constructor.\n    - right.\n      destruct t1.\n      + eexists. apply ST_IfTrue.\n      + eexists. apply ST_IfFalse.\n      + destruct IHt1 as [Hl | Hr].\n        * inversion Hl.\n        * destruct Hr as [t' Hr].\n          exists (test t' t2 t3).\n          apply ST_If. assumption.\n  Qed.\n\n  Lemma test_true: forall t f x, test tru t f --> x -> x = t.\n  Proof.\n    intros t f x H.\n    inversion H; subst.\n    - reflexivity.\n    - inversion H4.\n  Qed.\n\n  Lemma test_false: forall t f x, test fls t f --> x -> x = f.\n  Proof.\n    intros t f x H.\n    inversion H; subst.\n    - reflexivity.\n    - inversion H4.\n  Qed.\n\n  Theorem step_deterministic :\n    deterministic step.\n  Proof.\n    unfold deterministic. intro x. induction x; intros y1 y2 H1 H2.\n    - inversion H1; subst.\n    - inversion H1; subst.\n    - destruct x1; subst.\n      + (* x1 = true *) \n        rewrite (test_true _ _ _ H1).\n        rewrite (test_true _ _ _ H2).\n        reflexivity.\n      + (* x1 = false *) \n        rewrite (test_false _ _ _ H1).\n        rewrite (test_false _ _ _ H2).\n        reflexivity.\n      + inversion H1; subst. inversion H2; subst.\n        assert (G: t1' = t1'0). {\n          apply IHx1. apply H5. apply H6.\n        }\n        rewrite G. reflexivity.\n  Qed.\n\n  Module Temp5.\n    Reserved Notation \" t '-->' t' \" (at level 40).\n    Inductive step : tm -> tm -> Prop :=\n      | ST_IfTrue : forall t1 t2,\n          test tru t1 t2 --> t1\n      | ST_IfFalse : forall t1 t2,\n          test fls t1 t2 --> t2\n      | ST_If : forall t1 t1' t2 t3,\n          t1 --> t1' ->\n          test t1 t2 t3 --> test t1' t2 t3\n      | ST_ShortCircuit : forall t1 t2,\n          test t1 t2 t2 --> t2\n      where \" t '-->' t' \" := (step t t').\n\n    Definition bool_step_prop4 :=\n             test\n                (test tru tru tru)\n                fls\n                fls\n         -->\n             fls.\n    Example bool_step_prop4_holds :\n      bool_step_prop4.\n    Proof.\n      unfold bool_step_prop4.\n      apply ST_ShortCircuit.\n    Qed.\n\n    Theorem step_with_short_circ_not_deterministic :\n      ~(deterministic step).\n    Proof.\n      unfold deterministic.\n      intro H.\n      assert (G: fls = test tru fls fls). {\n        apply H with (x := test (test tru tru tru) fls fls).\n        - apply ST_ShortCircuit.\n        - apply ST_If. apply ST_IfTrue.\n      }\n      inversion G.\n    Qed.\n\n    Theorem strong_progress_bool : forall t,\n      value t \\/ (exists t', t --> t').\n    Proof.\n      intro t. induction t.\n      - left. constructor.\n      - left. constructor.\n      - right.\n        destruct t1.\n        + eexists. apply ST_IfTrue.\n        + eexists. apply ST_IfFalse.\n        + destruct IHt1 as [Hl | Hr].\n          * inversion Hl.\n          * destruct Hr as [t' Hr].\n            exists (test t' t2 t3).\n            apply ST_If. assumption.\n    Qed.\n  End Temp5.\nEnd Temp4.\n\nInductive multi {X : Type} (R : relation X) : relation X :=\n  | multi_refl : forall (x : X), \n                    multi R x x\n  | multi_step : forall (x y z : X),\n                    R x y ->\n                    multi R y z ->\n                    multi R x z.\n\nNotation \" t '-->*' t' \" := (multi step t t') (at level 40).\n\nTheorem multi_R : forall (X : Type) (R : relation X) (x y : X),\n    R x y -> (multi R) x y.\nProof. intros X R x y H. \n  apply (multi_step R x y y H).\n  apply multi_refl.\nQed.\n\n\nTheorem multi_trans :  forall (X : Type) (R : relation X) (x y z : X),\n      multi R x y ->\n      multi R y z ->\n      multi R x z.\nProof.\n  intros X R x y z H1 H2.\n  induction H1.\n  - (* refl *)apply H2.\n  - (* step *)apply multi_step with y.\n    apply H.\n    apply IHmulti.\n    apply H2.\nQed.\n\nPrint multi_trans.\nPrint multi_ind.\n\n\nLemma test_multistep_1:\n      P\n        (P (C 0) (C 3))\n        (P (C 2) (C 4))\n   -->*\n      C ((0 + 3) + (2 + 4)).\nProof.\n  apply multi_step with (P (C (0 + 3)) (P (C 2) (C 4))).\n  { apply ST_Plus1. apply ST_PlusConstConst. }\n  apply multi_step with (P (C (0 + 3)) (C (2 + 4))).\n  { apply ST_Plus2. apply v_const. apply ST_PlusConstConst. }\n  apply multi_R.\n  apply ST_PlusConstConst.\nQed.\n\nLemma test_multistep_1':\n      P\n        (P (C 0) (C 3))\n        (P (C 2) (C 4))\n  -->*\n      C ((0 + 3) + (2 + 4)).\nProof.\n  eapply multi_step. { apply ST_Plus1. apply ST_PlusConstConst. }\n  eapply multi_step. { apply ST_Plus2. apply v_const. apply ST_PlusConstConst. }\n  eapply multi_step. { apply ST_PlusConstConst. }\n  apply multi_refl.\nQed.\n\nLemma test_multistep_2:\n  C 3 -->* C 3.\nProof.\n  apply multi_refl.\nQed.\n\nLemma test_multistep_3:\n      P (C 0) (C 3)\n   -->*\n      P (C 0) (C 3).\nProof.\n  apply multi_refl.\nQed.\n\nLemma test_multistep_4:\n      P\n        (C 0)\n        (P\n          (C 2)\n          (P (C 0) (C 3)))\n  -->*\n      P\n        (C 0)\n        (C (2 + (0 + 3))).\nProof.\n  apply multi_step with (P\n        (C 0)\n        (P\n          (C 2)\n          (C (0 + 3)))). { apply ST_Plus2. apply v_const. apply ST_Plus2. apply v_const. apply ST_PlusConstConst. }\n  eapply multi_step. { apply ST_Plus2. apply v_const. apply ST_PlusConstConst. }\n  apply multi_refl.\nQed.\n\n\nDefinition step_normal_form := normal_form step.\nDefinition normal_form_of (t t' : tm) :=  (t -->* t' /\\ step_normal_form t').\n\nTheorem normal_forms_unique:  deterministic normal_form_of.\nProof.\n  unfold deterministic. unfold normal_form_of.\n  intros x y1 y2 P1 P2.\n  destruct P1 as [P11 P12].\n  destruct P2 as [P21 P22].\n  induction P11.\n  - inversion P21; subst.\n    + reflexivity.\n    + exfalso. apply P12. exists y. assumption.\n  - inversion P21; subst.\n    + exfalso. apply P22. exists y. assumption.\n    + assert (G: y = y0). { apply (step_deterministic _ _ _ H H0). }\n      apply IHP11.\n      apply P12.\n      rewrite G.\n      assumption.\nQed.\n\nDefinition normalizing {X : Type} (R : relation X) :=\n  forall t, exists t',\n    (multi R) t t' /\\ normal_form R t'.\n\n\nLemma multistep_congr_1 : forall t1 t1' t2,\n     t1 -->* t1' ->\n     P t1 t2 -->* P t1' t2.\nProof.\n  intros t1 t1' t2 H.\n  induction H.\n  - (* refl *) apply multi_refl.\n  - apply multi_step with (P y t2). apply ST_Plus1. apply H.\n    assumption.\nQed.\n\nLemma multistep_congr_2 : forall t1 t2 t2',\n     value t1 ->\n     t2 -->* t2' ->\n     P t1 t2 -->* P t1 t2'.\nProof.\n  intros t1 t2 t2' Hv H.\n  induction H.\n  - (* refl *) apply multi_refl.\n  - apply multi_step with (P t1 y). apply ST_Plus2. apply Hv. apply H.\n    assumption.\nQed.\n\nTheorem step_normalizing :\n  normalizing step.\nProof.\n  unfold normalizing.\n  induction t.\n  - (* C *)\n    exists (C n).\n    split.\n    + (* l *) apply multi_refl.\n    + (* r *)\n      (* We can use rewrite with \"iff\" statements, not\n           just equalities: *)\n      apply nf_same_as_value. apply v_const.\n  - (* P *)\n    destruct IHt1 as [t1' [Hsteps1 Hnormal1] ].\n    destruct IHt2 as [t2' [Hsteps2 Hnormal2] ].\n    apply nf_same_as_value in Hnormal1.\n    apply nf_same_as_value in Hnormal2.\n    destruct Hnormal1 as [n1].\n    destruct Hnormal2 as [n2].\n    exists (C (n1 + n2)).\n    split.\n    + (* l *)\n      apply multi_trans with (P (C n1) t2).\n      * apply multistep_congr_1. apply Hsteps1.\n      * apply multi_trans with (P (C n1) (C n2)).\n        { apply multistep_congr_2. apply v_const. apply Hsteps2. }\n        apply multi_R. apply ST_PlusConstConst.\n    + (* r *)\n      apply nf_same_as_value. apply v_const.\nQed.\n\nTheorem eval__multistep : forall t n,\n  t ==> n -> t -->* C n.\nProof.\n  intros t n H.\n  induction H.\n  - apply multi_refl.\n  - induction t1.\n    + (* const *) induction t2.\n      * (* const *) \n        inversion IHeval1; subst.\n        inversion IHeval2; subst.\n        eapply multi_step. apply ST_PlusConstConst. apply multi_refl.\n        inversion H0; subst. eapply multi_step. apply ST_PlusConstConst. apply multi_refl.\n        inversion H0; subst. inversion H; subst. eapply multi_step. apply ST_PlusConstConst. apply multi_refl.\n      * (* _ + _ *)\n        inversion H; subst.\n        assert (G: P (C n1) (P t2_1 t2_2) -->* P (C n1) (C n2)). {\n          apply multistep_congr_2.\n          apply v_const.\n          apply IHeval2.\n        }\n        apply multi_trans with (P (C n1) (C n2)).\n        apply G.\n        eapply multi_step. apply ST_PlusConstConst. apply multi_refl.\n    + (* _ + _ *)\n      assert (G: P (P t1_1 t1_2) t2 -->* P (C n1) t2). {\n        apply multistep_congr_1.\n        apply IHeval1.\n      }\n      apply multi_trans with (P (C n1) t2).\n      apply G.\n      assert (G': P (C n1) t2 -->* P (C n1) (C n2)). {\n        apply multistep_congr_2. \n        apply v_const.\n        apply IHeval2.\n      }\n      apply multi_trans with (P (C n1) (C n2)).\n      apply G'.\n      eapply multi_step. apply ST_PlusConstConst. apply multi_refl.\nQed.\n\n\nLemma step__eval : forall t t' n,\n     t --> t' ->\n     t' ==> n ->\n     t ==> n.\nProof.\n  intros t t' n Hs. generalize dependent n.\n  induction Hs.\n  - intros k H.\n    inversion H; subst.\n    apply E_Plus.\n    + constructor.\n    + constructor.\n  - intros n H.\n    inversion H; subst.\n    apply E_Plus.\n    + apply IHHs. assumption.\n    + assumption.\n  - intros n H'.\n    inversion H'; subst.\n    apply E_Plus.\n    + assumption.\n    + apply IHHs. assumption.\nQed.\n\nTheorem multistep__eval : forall t t',\n  normal_form_of t t' -> exists n, t' = C n /\\ t ==> n.\nProof.\n  intro t.\n  induction t; intros t' Hn; unfold normal_form_of in Hn; destruct Hn as [Hnl Hnr].\n  - exists n.\n    split.\n    + inversion Hnl; subst; try reflexivity.\n      inversion H.\n    + constructor.\n  -\n    assert (G1: exists n1, t1 ==> n1). {\n      destruct (step_normalizing t1) as [a [b c]].\n      destruct (IHt1 a).\n      split. apply b. apply c.\n      destruct H. exists x. assumption.\n    }\n    assert (G2: exists n2, t2 ==> n2). {\n      destruct (step_normalizing t2) as [a [b c]].\n      destruct (IHt2 a).\n      split. apply b. apply c.\n      destruct H. exists x. assumption.\n    }\n    clear IHt1 IHt2.\n    destruct G1 as [n1 H1].\n    destruct G2 as [n2 H2].\n    exists (n1 + n2). split; try reflexivity.\n    + apply eval__multistep in H1.\n      apply eval__multistep in H2.\n      assert (G: P t1 t2 -->* P (C n1) t2). {\n        apply multistep_congr_1.\n        apply H1.\n      }\n      assert (G1: P (C n1) t2 -->* P (C n1) (C n2)). {\n        apply multistep_congr_2.\n        constructor.\n        apply H2.\n      }\n      assert (G2: P t1 t2 -->*P (C n1) (C n2)). {\n        eapply multi_trans.\n        apply G.\n        apply G1.\n      }\n      assert (G3: P t1 t2 -->* C (n1 + n2)). {\n        eapply multi_trans.\n        apply G2.\n        eapply multi_step. constructor. eapply multi_refl.\n      }\n      assert (G5: t' = C (n1 + n2)). {\n        apply (normal_forms_unique (P t1 t2)).\n        - split. apply Hnl. apply Hnr.\n        - split. apply G3. \n          unfold step_normal_form, normal_form.\n          intros [a b]. inversion b.\n      }\n      apply G5.\n    + constructor. assumption. assumption.\nQed.\n\nTheorem evalF_eval : forall t n,\n  evalF t = n <-> t ==> n.\nProof.\n  intros t n. split; intro H.\n  generalize dependent n.\n  - induction t.\n    + intros n' H. simpl in H; subst. constructor.\n    + intros n H. simpl in H.\n      rewrite <- H.\n      apply (E_Plus t1 t2).\n      * apply IHt1. reflexivity.\n      * apply IHt2. reflexivity.\n  - induction H.\n    + reflexivity.\n    + simpl. auto.\nQed.\n\n\n\nModule Combined.\nInductive tm : Type :=\n  | C : nat -> tm\n  | P : tm -> tm -> tm\n  | tru : tm\n  | fls : tm\n  | test : tm -> tm -> tm -> tm.\n\nInductive value : tm -> Prop :=\n  | v_const : forall n, value (C n)\n  | v_tru : value tru\n  | v_fls : value fls.\n\nReserved Notation \" t '-->' t' \" (at level 40).\nInductive step : tm -> tm -> Prop :=\n  | ST_PlusConstConst : forall n1 n2,\n      P (C n1) (C n2) --> C (n1 + n2)\n  | ST_Plus1 : forall t1 t1' t2,\n      t1 --> t1' ->\n      P t1 t2 --> P t1' t2\n  | ST_Plus2 : forall v1 t2 t2',\n      value v1 ->\n      t2 --> t2' ->\n      P v1 t2 --> P v1 t2'\n  | ST_IfTrue : forall t1 t2,\n      test tru t1 t2 --> t1\n  | ST_IfFalse : forall t1 t2,\n      test fls t1 t2 --> t2\n  | ST_If : forall t1 t1' t2 t3,\n      t1 --> t1' ->\n      test t1 t2 t3 --> test t1' t2 t3\n  where \" t '-->' t' \" := (step t t').\n\n\nTheorem combined_deterministic: deterministic step.\nProof.\n  unfold deterministic.\n  intros x y1 y2 H1 H2.\n  generalize dependent y2.\n  induction H1; intros y2 H2.\n  - (*ST_PlusConstConst*) inversion H2; subst.\n    + reflexivity.\n    + inversion H3.\n    + inversion H4.\n  - (* ST_Plus1 *) inversion H2; subst.\n    + inversion H1.\n    + apply IHstep in H4. subst. reflexivity.\n    + inversion H3; subst. inversion H1. inversion H1. inversion H1.\n  - (* ST_Plus2 *) inversion H; subst.\n    + inversion H2; subst. \n      * inversion H1.\n      * inversion H5.\n      * inversion H2; subst. inversion H3.\n        apply IHstep in H8; subst. reflexivity.\n    + inversion H2. inversion H5; subst.\n      apply IHstep in H6. subst. reflexivity.\n    + inversion H2. inversion H5; subst.\n      apply IHstep in H6. subst. reflexivity.\n  - (* ST_IfTrue *) inversion H2; subst. reflexivity. inversion H4.\n  - (* ST_IfFalse *) inversion H2; subst. reflexivity. inversion H4.\n  - (* ST_If *) inversion H2; subst.\n    + inversion H1.\n    + inversion H1.\n    + apply IHstep in H5. subst. reflexivity.\nQed.\nEnd Combined.\n\n\n\n\nInductive aval : aexp -> Prop :=\n  | av_num : forall n, aval (ANum n).\n\n\nReserved Notation \" a '/' st '-->a' a' \" (at level 40, st at level 39).\nInductive astep (st : state) : aexp -> aexp -> Prop :=\n  | AS_Id : forall (i : string),\n      i / st -->a (st i)\n  | AS_Plus1 : forall a1 a1' a2,\n      a1 / st -->a a1' ->\n      <{ a1 + a2 }> / st -->a <{ a1' + a2 }>\n  | AS_Plus2 : forall v1 a2 a2',\n      aval v1 ->\n      a2 / st -->a a2' ->\n      <{ v1 + a2 }> / st -->a <{ v1 + a2' }>\n  | AS_Plus : forall (n1 n2 : nat),\n      <{ n1 + n2 }> / st -->a (n1 + n2)\n  | AS_Minus1 : forall a1 a1' a2,\n      a1 / st -->a a1' ->\n      <{ a1 - a2 }> / st -->a <{ a1' - a2 }>\n  | AS_Minus2 : forall v1 a2 a2',\n      aval v1 ->\n      a2 / st -->a a2' ->\n      <{ v1 - a2 }> / st -->a <{ v1 - a2' }>\n  | AS_Minus : forall (n1 n2 : nat),\n      <{ n1 - n2 }> / st -->a (n1 - n2)\n  | AS_Mult1 : forall a1 a1' a2,\n      a1 / st -->a a1' ->\n      <{ a1 * a2 }> / st -->a <{ a1' * a2 }>\n  | AS_Mult2 : forall v1 a2 a2',\n      aval v1 ->\n      a2 / st -->a a2' ->\n      <{ v1 * a2 }> / st -->a <{ v1 * a2' }>\n  | AS_Mult : forall (n1 n2 : nat),\n      <{ n1 * n2 }> / st -->a (n1 * n2)\n  where \" a '/' st '-->a' a' \" := (astep st a a').\n\nReserved Notation \" b '/' st '-->b' b' \" (at level 40, st at level 39).\nInductive bstep (st : state) : bexp -> bexp -> Prop :=\n  | BS_Eq1 : forall a1 a1' a2,\n      a1 / st -->a a1' ->\n      <{ a1 = a2 }> / st -->b <{ a1' = a2 }>\n  | BS_Eq2 : forall v1 a2 a2',\n      aval v1 ->\n      a2 / st -->a a2' ->\n      <{ v1 = a2 }> / st -->b <{ v1 = a2' }>\n  | BS_Eq : forall (n1 n2 : nat),\n      <{ n1 = n2 }> / st -->b\n      (if (n1 =? n2) then <{ true }> else <{ false }>)\n  | BS_LtEq1 : forall a1 a1' a2,\n      a1 / st -->a a1' ->\n      <{ a1 <= a2 }> / st -->b <{ a1' <= a2 }>\n  | BS_LtEq2 : forall v1 a2 a2',\n      aval v1 ->\n      a2 / st -->a a2' ->\n      <{ v1 <= a2 }> / st -->b <{ v1 <= a2' }>\n  | BS_LtEq : forall (n1 n2 : nat),\n      <{ n1 <= n2 }> / st -->b\n      (if (n1 <=? n2) then <{ true }> else <{ false }>)\n  | BS_NotStep : forall b1 b1',\n      b1 / st -->b b1' ->\n      <{ ~b1 }> / st -->b <{ ~b1' }>\n  | BS_NotTrue : <{ ~true }> / st -->b <{ false }>\n  | BS_NotFalse : <{ ~false }> / st -->b <{ true }>\n  | BS_AndStep : forall b1 b1' b2,\n      b1 / st -->b b1' ->\n      <{ b1 && b2 }> / st -->b <{ b1' && b2 }>\n  | BS_AndTrueStep : forall b2 b2',\n      b2 / st -->b b2' ->\n      <{ true && b2 }> / st -->b <{ true && b2' }>\n  | BS_AndFalse : forall b2,\n      <{ false && b2 }> / st -->b <{ false }>\n  | BS_AndTrueTrue : <{ true && true }> / st -->b <{ true }>\n  | BS_AndTrueFalse : <{ true && false }> / st -->b <{ false }>\nwhere \" b '/' st '-->b' b' \" := (bstep st b b').\n\n\n\nReserved Notation \" t '/' st '-->' t' '/' st' \"    (at level 40, st at level 39, t' at level 39).\nInductive cstep : (com * state) -> (com * state) -> Prop :=\n  | CS_AsgnStep : forall st i a1 a1',\n      a1 / st -->a a1' ->\n      <{ i := a1 }> / st --> <{ i := a1' }> / st\n  | CS_Asgn : forall st i (n : nat),\n      <{ i := n }> / st --> <{ skip }> / (i !-> n ; st)\n  | CS_SeqStep : forall st c1 c1' st' c2,\n      c1 / st --> c1' / st' ->\n      <{ c1 ; c2 }> / st --> <{ c1' ; c2 }> / st'\n  | CS_SeqFinish : forall st c2,\n      <{ skip ; c2 }> / st --> c2 / st\n  | CS_IfStep : forall st b1 b1' c1 c2,\n      b1 / st -->b b1' ->\n      <{ if b1 then c1 else c2 end }> / st  -->  <{ if b1' then c1 else c2 end }> / st\n  | CS_IfTrue : forall st c1 c2,\n      <{ if true then c1 else c2 end }> / st --> c1 / st\n  | CS_IfFalse : forall st c1 c2,\n      <{ if false then c1 else c2 end }> / st --> c2 / st\n  | CS_While : forall st b1 c1,\n      <{ while b1 do c1 end }> / st  -->  <{ if b1 then c1; while b1 do c1 end else skip end }> / st\nwhere \" t '/' st '-->' t' '/' st' \" := (cstep (t,st) (t',st')).\n\n\n\nModule CImp.\n\nInductive com : Type :=\n  | CSkip : com\n  | CAsgn : string -> aexp -> com\n  | CSeq : com -> com -> com\n  | CIf : bexp -> com -> com -> com\n  | CWhile : bexp -> com -> com\n  | CPar : com -> com -> com. (* <--- NEW *)\n\nNotation \"x || y\" :=\n         (CPar x y) (in custom com at level 90, right associativity).\nNotation \"'skip'\" :=\n         CSkip (in custom com at level 0).\nNotation \"x := y\" :=\n         (CAsgn x y) (in custom com at level 0, x constr at level 0, y at level 85, no associativity).\nNotation \"x ; y\" :=\n         (CSeq x y) (in custom com at level 90, right associativity).\nNotation \"'if' x 'then' y 'else' z 'end'\" :=\n         (CIf x y z) (in custom com at level 89, x at level 99, y at level 99, z at level 99).\nNotation \"'while' x 'do' y 'end'\" :=\n         (CWhile x y) (in custom com at level 89, x at level 99, y at level 99).\n\nInductive cstep : (com * state) -> (com * state) -> Prop :=\n  | CS_AsgnStep : forall st i a1 a1',\n      a1 / st -->a a1' ->\n      <{ i := a1 }> / st --> <{ i := a1' }> / st\n  | CS_Asgn : forall st i (n : nat),\n      <{ i := n }> / st --> <{ skip }> / (i !-> n ; st)\n  | CS_SeqStep : forall st c1 c1' st' c2,\n      c1 / st --> c1' / st' ->\n      <{ c1 ; c2 }> / st --> <{ c1' ; c2 }> / st'\n  | CS_SeqFinish : forall st c2,\n      <{ skip ; c2 }> / st --> c2 / st\n  | CS_IfStep : forall st b1 b1' c1 c2,\n      b1 / st -->b b1' ->\n      <{ if b1 then c1 else c2 end }> / st\n      -->\n      <{ if b1' then c1 else c2 end }> / st\n  | CS_IfTrue : forall st c1 c2,\n      <{ if true then c1 else c2 end }> / st --> c1 / st\n  | CS_IfFalse : forall st c1 c2,\n      <{ if false then c1 else c2 end }> / st --> c2 / st\n  | CS_While : forall st b1 c1,\n      <{ while b1 do c1 end }> / st\n      -->\n      <{ if b1 then c1; while b1 do c1 end else skip end }> / st\n  (**** New part: ****)\n  | CS_Par1 : forall st c1 c1' c2 st',\n      c1 / st --> c1' / st' ->\n      <{ c1 || c2 }> / st --> <{ c1' || c2 }> / st'\n  | CS_Par2 : forall st c1 c2 c2' st',\n      c2 / st --> c2' / st' ->\n      <{ c1 || c2 }> / st --> <{ c1 || c2' }> / st'\n  | CS_ParDone : forall st,\n      <{ skip || skip }> / st --> <{ skip }> / st\nwhere \" t '/' st '-->' t' '/' st' \" := (cstep (t,st) (t',st')).\n\n\nDefinition cmultistep := multi cstep.\nNotation \" t '/' st '-->*' t' '/' st' \" :=\n   (cmultistep (t,st) (t',st')) (at level 40, st at level 39, t' at level 39).\n\nDefinition par_loop : com :=\n  <{ Y := 1 || while (Y = 0) do X := X + 1 end }>.\n\nLemma par_body_n__Sn : forall n st,\n  st X = n /\\ st Y = 0 ->\n  par_loop / st -->* par_loop / (X !-> S n ; st).\nProof.\n  intros n st [Hx Hy].\n  eapply multi_step. apply CS_Par2. apply CS_While.\n\n  eapply multi_step. apply CS_Par2. apply CS_IfStep.\n  eapply BS_Eq1. apply AS_Id.\n\n  eapply multi_step. apply CS_Par2. apply CS_IfStep. rewrite -> Hy.\n  eapply BS_Eq. \n\n  eapply multi_step. apply CS_Par2. apply CS_IfTrue.\n\n  eapply multi_step. apply CS_Par2. apply CS_SeqStep.\n  apply CS_AsgnStep. apply AS_Plus1. apply AS_Id. rewrite -> Hx.\n\n  eapply multi_step. apply CS_Par2. apply CS_SeqStep.\n  apply CS_AsgnStep. apply AS_Plus.\n\n  eapply multi_step. apply CS_Par2. apply CS_SeqStep.\n  apply CS_Asgn.\n\n  eapply multi_step. apply CS_Par2. apply CS_SeqFinish.\n  fold par_loop.\n  assert (G: n + 1 = S n). { lia. }\n  rewrite -> G.\n\n  apply multi_refl.\nQed.\n\nLemma par_body_n : forall n st,\n  st X = 0 /\\ st Y = 0 ->\n  exists st', par_loop / st -->* par_loop / st' /\\ st' X = n /\\ st' Y = 0.\nProof.\n(* it looks like mistake, we need n > 0 *)\nAdmitted.\n\nTheorem par_loop_any_X:\n  forall n, exists st',\n    par_loop / empty_st -->* <{skip}> / st'\n    /\\ st' X = n.\nProof.\n  intros n.\n  destruct (par_body_n n empty_st).\n    split; reflexivity.\n  rename x into st.\n  inversion H as [H' [HX HY] ]; clear H.\n  exists (Y !-> 1 ; st). split.\n  eapply multi_trans with (par_loop,st). apply H'.\n  eapply multi_step. apply CS_Par1. apply CS_Asgn.\n  eapply multi_step. apply CS_Par2. apply CS_While.\n  eapply multi_step. apply CS_Par2. apply CS_IfStep.\n    apply BS_Eq1. apply AS_Id. rewrite t_update_eq.\n  eapply multi_step. apply CS_Par2. apply CS_IfStep.\n    apply BS_Eq. simpl.\n  eapply multi_step. apply CS_Par2. apply CS_IfFalse.\n  eapply multi_step. apply CS_ParDone.\n  apply multi_refl.\n  rewrite t_update_neq. assumption. intro X; inversion X.\nQed.\n\nEnd CImp.\n\n\n\n\n\nDefinition stack := list nat.\nDefinition prog := list sinstr.\nInductive stack_step (st : state) : prog * stack -> prog * stack -> Prop :=\n  | SS_Push : forall stk n p,\n    stack_step st (SPush n :: p, stk) (p, n :: stk)\n  | SS_Load : forall stk i p,\n    stack_step st (SLoad i :: p, stk) (p, st i :: stk)\n  | SS_Plus : forall stk n m p,\n    stack_step st (SPlus :: p, n::m::stk) (p, (m+n)::stk)\n  | SS_Minus : forall stk n m p,\n    stack_step st (SMinus :: p, n::m::stk) (p, (m-n)::stk)\n  | SS_Mult : forall stk n m p,\n    stack_step st (SMult :: p, n::m::stk) (p, (m*n)::stk).\n\nTheorem stack_step_deterministic : forall st,\n  deterministic (stack_step st).\nProof.\n  unfold deterministic. intros st x y1 y2 H1 H2.\n  induction H1; inversion H2; reflexivity.\nQed.\n\nDefinition stack_multistep st := multi (stack_step st).\n\nFixpoint s_compile (e : aexp) : list sinstr := \n  match e with\n  | ANum n => SPush n :: nil\n  | AId  x => SLoad x :: nil\n  | AMult  a1 a2 => (s_compile a1 ++ s_compile a2) ++ [SMult]\n  | APlus  a1 a2 => (s_compile a1 ++ s_compile a2) ++ [SPlus]\n  | AMinus a1 a2 => (s_compile a1 ++ s_compile a2) ++ [SMinus]\n  end.\n(* TODO : *)\nDefinition compiler_is_correct_statement : Prop. Admitted.\n\n\n\n\n\n\n\n\n\nTactic Notation \"print_goal\" :=\n  match goal with |- ?x => idtac x end.\nTactic Notation \"normalize\" :=\n  repeat (print_goal; eapply multi_step ; [ (eauto 10; fail) | (instantiate; simpl) ]);\n  apply multi_refl.\nHint Constructors step value : core.\n\n\nExample step_example1'' :\n  (P (C 3) (P (C 3) (C 4))) -->* (C 10).\nProof.\n  normalize.\nQed.\n\nExample step_example1''' : exists e',\n  (P (C 3) (P (C 3) (C 4))) -->* e'.\nProof.\n  eexists. normalize.\nQed.\n\nTheorem normalize_ex : exists e',\n  (P (C 3) (P (C 2) (C 1))) -->* e' /\\ value e'.\nProof.\n  eexists. split.\n  - normalize.\n  - constructor.\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/vol2_plf/Smallstep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.6822819344539989}}
{"text": "\n(** %\\chapter{%#<H0>#Finite automata%}%#</H0># *)\n\n(* Proofs *)\n Section Automata.\n(*Load FinSets.*)\nLoad Finitesets.\nRequire Import List.\n\nSet Implicit Arguments.\n\n\n(*Definition Alphabet := nat.*)\n(*Variable Sigma : Alphabet. *) \n\n(** * Introduction \n\n  In finite automata theory, the basic element that we need to use in order  to reason about the behaviour of an automaton is the _word_ . \n\n  By definition, we call  a word to be a list of _symbols_. \n\n    \n  - A symbol is an element of an alphabet( usually denoted as $\\Sigma $ ).\n\n  - A set of words is defined to be called a _language_ .\n\n  In our implementation , a language is represented as a function that takes a word \n\n  and decides whether it is a member of the set (type [Prop]).\n\n      *)\nDefinition Word(x:Alphabet) := list (Fin x).\n\nDefinition Language (a:Alphabet):= Word a -> Prop.\n\n\n(** An empty word is defined as the [nil] list constructor *)\n\n\n\nDefinition eps (a:Alphabet):Word a:=nil.\n\n\n\n(**  * Deterministic finite automata \n\n  As in \"Automata and theory of computation\"(J.Hopcroft), a deterministic finite automaton\n  \n (DFA) is defined a 5-uple (Q,$\\Sigma $ , $\\sigma $, ${q}_{0}$, F)\n\n  - A finite set of states Q (here denoted by [states])\n\n  - A set of symbols ([Fin a])\n\n  - A transition function $\\sigma $ : Q * $\\Sigma $ -> Q , denoted by [delta]\n\n  - An initial state ${q}_{0}$\n\n  - A set of final states F .\n\n*)\n\nRecord dfa (n:nat) (a:Alphabet) :Type:= DFA {  \n  states :=  Fin n; (*finite sets*) \n  symbol := Fin a;  \n  delta : Fin n ->Fin a  -> Fin n; \n  q0 : Fin n ; (*only 1 initial state*)\n  final :Fin n -> bool (*multiple states*)\n}.\nCheck dfa.\n\n(** * Language of a finite deterministic automaton *)\n\n\n(*Definition is_accepting (n:nat)(a:Alphabet)(d:dfa n a)(q: states d)  := In q (final d).*)\n\n(** Below, we have the extended transition function for a DFA , [deltah] : *)\n\n\nFixpoint deltah (n:nat)(a:Alphabet)(d: dfa n a)(q: Fin n) (w: Word a) : (Fin n):=\n  match w with\n     | nil => q\n     | h :: t => (deltah d (delta  d q h ) t) \n  end.\nLemma deltah_prop:\n  forall (a:Alphabet)(n:nat)(q:Fin n) (d:dfa n a) (xs ys :Word a),\n   deltah d (q) (xs++ ys) = deltah d (deltah d (q) xs) ys.\n\ninduction xs.\nsimpl in *.\nreflexivity.\nsimpl in *.\n\nintros.\nsimpl in *.\n(*induction ys.\nsimpl in *.\nassert (xs++nil = xs).\nintuition.\nrewrite H.\nreflexivity.\nsimpl in *.\nintuition. *)\nadmit.\nQed.\nLemma deltah_property :\n    forall (a:Alphabet)(n:nat) (d:dfa n a)(q:Fin n)(xs ys zs :Word a) ,\n   deltah d (q) (xs ++ ys ++ zs) =\n    deltah d(deltah d (deltah d (q) xs) ys ) zs.\ninduction xs.\nsimpl.\ninduction ys.\nsimpl in *.\nreflexivity.\nsimpl in *.\napply deltah_prop.\n\n\nsimpl in *.\nintros.\nassert (xs ++ ys ++ zs = (xs ++ ys)++ zs).\nauto with *.\nadmit.\n\n\n\n(*simpl in *.\ninduction xs.\n\n\ninduction zs.\nsimpl in *.\nintuition.\nassert (ys ++ nil = ys).\nintuition.\n (*very well known property*)\nrewrite H.\nreflexivity.\nsimpl in *. *)\n\nQed.\n\n\nNotation \" x ^ y \" := (exps x y).\n\nDefinition dfa_lang1 (n:nat)(a:Alphabet)(d: dfa n a) :Language a := \n  fun w:Word a => final  d (deltah  d(q0 d ) w)=true.\n\n\n(** The actual definition of the language of a DFA *)\n\nDefinition dfa_lang (n:nat)(a:Alphabet)(d: dfa n a) :Language a := \n  fun w:Word a => match  final  d (deltah  d(q0 d ) w)  with \n              | true => True\n              | false => False\n             end.\n\nCheck dfa_lang.\nCheck tt.\n\n\n\n(** Empty automaton : a (initial )state with no final states*)\n\n\nDefinition dfa_void(q:Fin 1)(a:Alphabet) : dfa 1 a := \n          DFA (fun x:Fin 1 => fun b:Fin a => q ) q (fun x:Fin 1 => false).\n\nPrint dfa_void.\n\n(** The empty automaton will not accept any word *)\n\nDefinition empty_lang (a:Alphabet):Language a:= fun w:Word a=>False.\n\nDefinition isNil (a:Alphabet) (w:Word a): Prop :=\n    match w with  |nil => True\n                  | _  => False\n                              end. \n\nDefinition eps_lang (a:Alphabet) :Language a := \n\n             fun w:Word a=> w=nil.\n\n              (*fun w:Word a => match w with  |nil => True\n                                            | _  => False\n                              end. *)\n\nDefinition eps_lang1 (a:Alphabet) :Language a := \n        fun w:Word a => w =nil.\n\n\nLemma dfa_void_correct: forall (a:Alphabet)(q:Fin 1) (w:Word a),\n     dfa_lang (dfa_void q a) w -> empty_lang w.\nintros.\nunfold dfa_lang in H.\nunfold empty_lang.\nsimpl in H.\n\nauto with *.\nQed.\n\n(*The automaton that will take the epsilon language *)\n\nPrint option.\nCheck (S (S 0)).\nDefinition dfa_epsilon (q:Fin 1)(a:Alphabet) : dfa (1) a := \n   DFA( fun _:Fin 1 => fun _:Fin a=> q) q   (fun x:Fin 1 => eqf q x).\n\nPrint dfa_epsilon.\n\nDefinition dfa_compl (a:Alphabet)(n:nat)(d:dfa n a) : dfa n a :=\n\n   DFA( delta d) (q0 d) (fun q : Fin n=> \n\n    negb (final d q)).\nInductive empty :Set := .\nInductive singleton :Set := emptyx : singleton. \nPrint emptyx.\n\n\n\n(** Remove states that are unreachable !!! *)\n\n\nDefinition reachable_immediate (a:Alphabet) (n:nat) (d: dfa n a)(x y :Fin n)  :=\n\n  exists c:Fin a,   (delta d x c) = y.\n\n\nDefinition reachable (a:Alphabet)(n:nat) (d:dfa n a) (y:Fin n) :=\n\n   exists w:Word a , deltah d ( q0 d)w = y.\n\n\nDefinition isconnected (a:Alphabet)(n:nat) (d:dfa n a) :=\n\n    forall (x:Fin n), exists w:Word a, deltah d (q0 d) w = x.\n\n(** * Nondeterministic finite automaton \n\n   A _nondeterministic finite automaton_ (NFA) A is defined as a 5-uple Q,$\\Sigma $ , $\\sigma $, S, F), \n   where :\n\n   - [Q] represent a finite set of initial states ( [nstates])\n\n   - A set of symbols $\\Sigma $ ([Fin a])\n\n   - A transition function $\\sigma $ : Q * $\\Sigma $ -> $P (Q)$ ([ndelta])\n\n   - A set of initial states [S] , denoted by [ninitial]\n\n   - A set of final states [F], denoted by [nfinal].\n\n   \n*)\n\n\nRecord nfa (n:nat)(a:Alphabet) := NFA {\n   \n   nstates :=Fin n; \n   nsymbol := Fin a; \n   ndelta : Fin n-> Fin a  ->Fin (2^n); \n   ninitial : Fin n -> bool (* multiple states*);\n   nfinal : Fin n -> bool\n }.\nCheck nfa.\n\n(** We want to generate the union of 2 sets, taking into account the isomorphism [(Fin n -> bool) <-> Fin (2^n)], proven in the library of\n\n    finite sets. *)\n\n\nDefinition unionf (n:nat) (sets : (Fin n -> bool) -> bool) (x:Fin n) : bool := \n  existsf1 (fun q : Fin (2^n) => sets( allexp2 q) && allexp2 q x).\n\nDefinition prepare (n:nat)(a:Alphabet) (nr:nfa n a)(states : Fin (2^n)) (x:Fin a)  : (Fin n -> bool)  :=\n   fun s : Fin n  => existsf1 (fun st : Fin n => allexp2 (states) (st) &&  allexp2(ndelta  nr st x) s). \n\n\n(** The extended transition function for an NFA  [ndeltah]: *)\n\nFixpoint ndeltah (n : nat) (a:Alphabet) (nr: nfa n a) (qs : (Fin (2^ n))) (w:Word a) :(Fin (2^n)) :=\n       match w with \n     | nil    =>  qs\n     | h :: t =>  (ndeltah nr (allexp1 (prepare nr qs h)) t)   \n       end.\n(*Definition nfa_lang (n:nat)(a:Alphabet) (nr: nfa n a) :Language a := \n  fun w :Word a => (existsf1(fun q :Fin n=>( allexp2(ndeltah nr (allexp1 (ninitial nr) ) w)) q && (nfinal  nr q)))=true. \n*)\nDefinition nfa_lang (n:nat)(a:Alphabet) (nr: nfa n a) :Language a := \n  fun w :Word a => match (existsf1(fun q :Fin n=>( allexp2(ndeltah nr (allexp1 (ninitial nr) ) w)) q && (nfinal  nr q))) with\n                   | true => True\n                  | false => False\n                   end .\nDefinition nfa_lang1 (n:nat)(a:Alphabet) (nr: nfa n a) :Language a := \n  fun w :Word a => (existsf1(fun q :Fin n=>( allexp2(ndeltah nr (allexp1 (ninitial nr) ) w)) q && (nfinal  nr q)))=true. \n\n(** * The subset construction *)\n\n(*Convert a dfa to an nfa: *)\n\nDefinition dfa2nfa (n:nat) (a:Alphabet) (d:dfa n a): nfa n a :=\n    NFA(fun k : Fin n => fun a : Fin a => \n    \n     (allexp1 ( fun x:Fin n => eqf x (delta d k a) ))) (fun x:Fin n => eqf x (q0 d)) (final d).\n\n\n\n\n(* union of ndelta *)\n\n  \nDefinition nfa2dfa (n:nat) (a:Alphabet) (nr: nfa n a) : dfa (2^n) a :=\n\n DFA (fun k:Fin (2^n)=> fun a : Fin a => allexp1 (prepare nr k a)) (allexp1 (ninitial nr )) \n    (fun k:Fin (2^n)=>existsf1(fun q:Fin n=> (allexp2 k q ) && nfinal nr  q)).\n\nDefinition nfa_void (a:Alphabet) : nfa 1 a :=\n  NFA(fun x:Fin 1 => fun a:Fin a=> allexp1 (fun y:Fin 1 => false)) \n      (fun x:Fin 1 =>existsf1 (fun y:Fin 1 => eqf x y))\n       (fun x:Fin 1 =>existsf1 (fun y:Fin 1 => false)).\n\nLemma nfa_void_lang :  forall (a:Alphabet)(w:Word a),\n     nfa_lang (nfa_void a) w -> empty_lang w.\nintros.\nunfold empty_lang.\nunfold nfa_lang in H.\nsimpl in H.\nauto with *.\n\nQed.\nPrint eps.\n(*\nDefinition chec (a:Alphabet) (p :Fin a) :=\n\n if (p::nil)=eps a then true else false.*)\n\nDefinition nfa_eps(a:Alphabet):nfa 1 a :=\n\n  NFA(fun x:Fin 1 => fun a0:Fin a => allexp1 (fun y:Fin 1 => eqf x  y))\n   (fun x:Fin 1 => true ) (fun x:Fin 1 => true).\n\n\nPrint nfa_eps.\n\nPrint option.\n\nLemma nfa_eps_lang1 : forall (a:Alphabet)(w:Word a) ,\n     eps_lang w -> nfa_lang (nfa_eps a) w.\nintros.\nunfold eps_lang in H.\nunfold nfa_lang.\nsimpl.\nsplit.\nQed.\nLemma nfa_eps_lang :forall (a:Alphabet) (w:Word a) ,\n   nfa_lang (nfa_eps a) w -> eps_lang w.\nintros.\nunfold eps_lang.\n\nunfold nfa_lang in H.\nsimpl in *.\n\nadmit.\nQed.\n\n\nDefinition nfa_var (a:Alphabet) :=\n\n   NFA (fun xs : Fin 2 => fun c:Fin a => \n\n     allexp1 (fun ys : Fin 2 => eqf xs ys =false) )\n\n     (fun xs :Fin 2 =>   \n\nDefinition nfa_var(a:Alphabet)(cc:Fin a)  :=\n    NFA( fun it :Fin 2 => fun aa :Fin a =>  allexp1 (fun final:Fin 2=>if negb (eqf it final)&& eqf cc aa then true  else  false ))\n      (fun x : Fin 2 => existsf1 (fun y: Fin 2 => eqf x y) )\n    (fun x:Fin 2 => existsf1 ( fun y :Fin 2 => eqf x y)).\n\nPrint nfa_var.\n(*\nDefinition nfa_var1(a:Alphabet)(x:Fin a) : nfa 2 a:=\n\n   NFA (fun xs :Fin 2 => fun c :Fin a => allexp1(existsf1(fun y:Fin 2 =>\n           end))) tt tt. *)\n  \n\nDefinition single_lang (a:Alphabet):Language a:=\n  fun w => \n\nmatch w with \n        | a::nil => True\n        | _ => False\n     end.\nPrint single_lang.\n\nDefinition single_lang1 (a:Alphabet)(x:Fin a) :Language a :=\n  fun w : Word a => match w with \n    \n     | p :: nil => if eqf p x then True else False\n     | _ => False\n    end. \nLemma nfa_var_lang : forall (a:Alphabet)(w:Word a)(cc:Fin a) , \n    nfa_lang (nfa_var  cc) w -> single_lang1 cc w.\nintros.\nunfold nfa_lang in H.\n(*intuition.\n(*We want to prove that in an nfa with the epsilon language does not accept a word\ndifferent from <nil>  useful in the theorem of correctness nfa_eps_lang *)\nrewrite H0 in H.\nassert(False). *)\nunfold nfa_var in *.\nsimpl in *.\nunfold single_lang1.\nsimpl.\nadmit.\nQed.\nPrint nfa_var.\n\nPrint sum.\nPrint prod.\n\n\n\nDefinition condition1 (a:Alphabet)(p q :nat) (c:Fin a) (n1:nfa p a)(n2:nfa q a) (xd : Fin (p+q)) : bool :=\n\n         match (addfin1 p q xd) with \n        | inl x => existsf1 (fun tx:Fin(2^p) => eqf tx (ndelta n1 x c))\n\n        | inr y => existsf1 (fun ty :Fin (2^q) => eqf ty (ndelta n2 y c))\n\n       end.\n       \n\nDefinition nfa_disj (a:Alphabet)(p q :nat) (n1:nfa p a)(n2:nfa q a) : nfa(p+q) a :=\n\n    NFA( fun xs : Fin (p+q) => fun c:Fin a => \n\n    allexp1 (fun xss :Fin (p+q) => eqf xs xss &&  condition1 c n1 n2 xss))\n   \n    (fun xs :Fin (p+q) =>\n\n       match (addfin1 p q xs) with \n    \n          | inl x => ninitial n1 x\n\n          | inr y => ninitial n2 y\n\n     end)\n\n\n    (fun xs :Fin (p+q)  =>\n\n       match (addfin1 p q xs) with \n    \n          | inl x => nfinal n1 x\n\n          | inr y => nfinal n2 y\n\n     end) .\n\nDefinition lang_conc(a:Alphabet)(l1:Language a)(l2:Language a):Language a:=\n    fun w:Word a=> exists w1:Word a, exists w2:Word a,  w1 ++ w2=w /\\ l1 w1 /\\ l2 w2.\n\nDefinition lang_union(a:Alphabet) (l1:Language a )(l2:Language a):Language a:=\n    fun w:Word a=>  l1 w \\/ l2 w.\nPrint nfa_lang1.\nLemma nfa_disj_lang : forall (a:Alphabet) (p q:nat) (n1: nfa p a) (n2: nfa q a) (w:Word a), \n\n        nfa_lang1 ( nfa_disj n1 n2 ) w -> lang_union (nfa_lang1 n1  ) (nfa_lang1 n2 ) w.\nintros.\nunfold lang_union.\nunfold nfa_lang1 in *.\nsimpl.\nsimpl in *.\nset( PP:= fun qx :Fin (p+q) => match addfin1 p q qx with \n  | inl x => nfinal n1 x\n \n  | inr y => nfinal n2 y end).\n\nleft.\nadmit.\nQed.\n\nLemma nfa_disj_lang1 : forall (a:Alphabet) (p q:nat) (n1: nfa p a) (n2: nfa q a) (w:Word a), \n\n       lang_union (nfa_lang1 n1  ) (nfa_lang1 n2 ) w -> nfa_lang1 ( nfa_disj n1 n2 ) w.\nintros.\nunfold lang_union in *.\nunfold nfa_lang1 in *.\ndestruct H.\nsimpl in *.\nset( PP:= fun qx :Fin (p+q) => match addfin1 p q qx with \n  | inl x => nfinal n1 x\n \n  | inr y => nfinal n2 y end).\n\nset (pp:= fun q :Fin p => nfinal n1 q).\nadmit.\n\nsimpl in *.\nadmit.\n\n(*\nintros.\nunfold lang_union.\nunfold nfa_lang.\nsimpl in *.\nunfold nfa_lang in H.\nsimpl in *.\nleft.\ncase_eq( existsf1(fun q1:Fin p => nfinal n1 q1)).\nintro.\nsplit.\nintro.\n\n\nleft.*)\n\nQed.\n\nEval compute in existsf1( fun y: Fin 3=>(existsf1 (fun x:Fin 2 => true&& false))).\n\nPrint sum.\n\n(*Inductive empty :Set := .*)\n(**For a set with a single element, we consider an element x defined itself on  the singleton.\n\n*)\n(*Inductive singleton :Set := emptyx : singleton.  *)\n\nCheck (inr  emptyx).\nCheck existsf1(fun (t:Fin 2)=> existsf1 (fun o : Fin 2 => eqf t o )).\n\nPrint nfa_disj.\n\nCheck ( fun (c:Fin 2) => fun (d:Fin 3)=> inr (Fin 3) c).\n\n\nDefinition nfa_conc(a:Alphabet)(p q:nat) (n1:nfa p a) (n2:nfa q a) : nfa( p+q) a:=\n\n    NFA( fun xs:(Fin (p+q)) => fun c:Fin a=>\n  ( allexp1( fun xss:Fin (p+q) => eqf xss xs && (  existsf1 (fun x:Fin p=> existsf1(fun y:Fin q =>\n\n          (*\n      match addfin1 x , addfin1 y with \n\n      | inl x , inl y =>  existsf1 (fun t:Fin (2^p) => (eqf(ndelta n1 x c) t))\n\n      | inl x, inr y =>  (nfinal n1 x) && ndelta (n2) *)\n  \n      \n         match (addfin1 p q xs) with\n       | inl  x => existsf1 (fun t:Fin (2^p) => (eqf(ndelta n1 x c) t)) ||\n\n                          existsf1 (fun q'': Fin q => existsf1 (fun q' :Fin p => \n\n                     existsf1 (fun tx:Fin (2^p)=>\n\n                        (nfinal n1 q') && (ninitial n2 q'') && (allexp2 (ndelta n1 x c) q'))))\n\n       | inr  y => existsf1( fun tr: Fin (2^q) => (eqf(ndelta n2 y c) tr))\n\n        end ))))))\n      (fun xs :Fin (p+q) =>\n          existsf1(fun x:Fin p => existsf1(fun y:Fin q =>\n\n           match  (addfin1 p q xs) with\n         | inl x =>  ninitial n1 x\n\n         | inr y => nfinal n2 y && existsf1( fun t: Fin p => ninitial n1 t && nfinal n1 t)\n\n         end)))\n\n     (fun xs :Fin (p+q) =>\n        existsf1 (fun x:Fin p=> existsf1(fun y:Fin q =>\n           match  (addfin1 p q xs) with\n\n         | inl x =>  false\n\n         | inr y => nfinal n2 y \n        end ))).\n         \n    \nPrint nfa_conc.\n\n\nLemma nfa_conc1 : forall (a:Alphabet) (p q:nat)\n        (n1 :nfa p a) (n2 : nfa q a)  (w:Word a) ,\n\n   nfa_lang1 (nfa_conc n1 n2) w -> lang_conc (nfa_lang1 n1) (nfa_lang1 n2) w.\n\nintros.\nunfold lang_conc in *.\nunfold nfa_lang1 in *.\nsimpl in *.\nadmit . (*??*)\nQed.\nDefinition nfa_star (a:Alphabet) (p:nat) (n1:nfa p a) : nfa (p+1) a := \n\n    NFA( fun xs:Fin (p+1) => fun c:Fin a=>  \n\n    allexp1 (fun xss:Fin(p+1) => eqf xs xss && existsf1( fun _:Fin p =>\n\n        match (addfin1 p 1 xs) with\n\n     | inl x => existsf1 (fun tx:Fin (2^p) => eqf tx (ndelta n1 x c)) ||\n\n                existsf1 (fun q' :Fin p => existsf1 (fun tx:Fin (p) =>\n\n                           (ninitial n1 q') &&  (allexp2  (ndelta n1 x c) tx )&& (nfinal n1 tx)))\n\n     | inr y => false\n\n   end )))\n    \n    (fun xs:Fin (p+1) => \n\n        match (addfin1 p 1 xs) with\n\n    | inl x => ninitial n1 x\n   \n    | inr y => true\n \n\n       end)\n\n     (fun xs:Fin (p+1) => \n\n        match (addfin1 p 1 xs) with\n\n    | inl x => nfinal n1 x\n   \n    | inr y => true\n \n\n       end) .\n\n    \n\n\n     \n\n     \nLemma nfa_eps_lang :  forall (a:Alphabet)(w:Word a),\n     nfa_lang1 (nfa_eps a) w -> eps_lang1 w.\n\nintros.\nunfold nfa_lang1 in H.\n\nunfold eps_lang1.\n\nsimpl in *.\ndestruct w.\nsplit.\ninversion H.\ninduction w.\nsimpl.\nsplit.\nsimpl.\nrewrite IHw.\n\nsimpl in H.\nsimpl in IHw.\ninversion H.\nsimpl in IHw.\nunfold isNil in IHw.\n(*induction w.\nsplit.\nsimpl in H.\nsimpl in IHw.\napply IHw in H.\nsimpl in H. *)\n\nadmit.\nQed. *)\nCheck negb.\nPrint negb.\nCheck inl.\n\n\nLemma dfa2nfa_correct2 : forall (n:nat)(a:Alphabet)(w:Word a)(d:dfa n a), \n              dfa_lang d w-> nfa_lang (dfa2nfa d)w.\nintros.\nunfold dfa_lang in H.\nunfold nfa_lang.\nsimpl.\n      \n\ncase_eq (existsf1 (fun q:Fin n => final d q)).\nintros.\nsplit.\nintro.\nassert( final d (deltah d (q0 d) w)=false).\nadmit.\n\n(*must prove that if there is no state that is final, then \nalso the initial state cannot be final, taken as a particular case of the problem *)\n\nrewrite H1 in H.\ndestruct H.\n(*reflexivity.*)\nQed.\n\nLemma dfa2nfa_correct1 : forall (n:nat)(a:Alphabet)(w:Word a)(d:dfa n a), \n               nfa_lang (dfa2nfa d)w-> dfa_lang d w .\n(*intros.\nunfold nfa_lang1 in *.\nunfold dfa_lang1 in *.\nsimpl in *.*)\n\n\n\n\nintros.\nunfold nfa_lang in H.\nsimpl in H.\nunfold dfa_lang.\nsimpl.\nsimpl in H.\ncase_eq (existsf1 (fun q:Fin n => final d q)).\nintro.\nsimpl.\nsimpl in *.\nrewrite H0 in H.\n\ncase_eq (final d (deltah d (q0 d) w)).\nsplit.\nintro.\nadmit.\nintro.\n\nrewrite H0 in H.\ndestruct H.\nQed.\n\n\nTheorem nfa2dfa_correct1 :forall (n:nat)(a:Alphabet)(w:Word a) (nr:nfa n a),\n       dfa_lang (nfa2dfa nr) w -> nfa_lang nr w.\nProof.\nintros.\nunfold dfa_lang in H.\nunfold nfa_lang.\nsimpl in H.\nsimpl.\nexact H.\nQed.\n\nTheorem nfa2dfa_correct2: forall (n:nat)(a:Alphabet)(w:Word a) (nr:nfa n a),\n       nfa_lang nr w -> dfa_lang (nfa2dfa nr) w.\nProof.\nintros.\nunfold dfa_lang.\nunfold nfa_lang in H.\nsimpl.\nsimpl in H.\nassumption.\nQed.\n\n(*Lemma for the equivalence of extended transition functions of a DFA and an NFA*)\nLemma eqref: forall (n:nat) (p :Fin n)  , equalsf p p =true.\nintros.\ninduction n.\nsimpl.\n\nassert (False).\napply fin0empty.\nexact p.\ndestruct H.\n\nunfold equalsf.\nunfold equalsf in IHn.\nsimpl.\nadmit. (*prove inductive step *)\nQed.\nLemma ext_delta_coincide: forall (n:nat)(a:Alphabet) (nr:nfa n a)(w:Word a) , \n    eqf (ndeltah nr  (allexp1(ninitial nr)) w)(deltah (nfa2dfa nr) (q0 (nfa2dfa nr)) w)=true.\n\nintros.\nunfold eqf.\nsimpl.\ninduction w.\nsimpl.\nrewrite eqref.\n\n\nreflexivity.\n\nset(P:=deltah (nfa2dfa nr) (allexp1 (ninitial nr )) w).\n\nassert(deltah (nfa2dfa nr) (allexp1 (ninitial nr)) (a0:: w) = \n\n      (deltah (nfa2dfa nr) (delta  (nfa2dfa nr) (allexp1 (ninitial nr)) a0 ) w)).\nsimpl. \nreflexivity.\nsimpl.\ntrivial.\n\nQed.\n \n\n\n\n\nEnd Automata.", "meta": {"author": "radu07", "repo": "automat", "sha": "5d8c4ec7414025cb83ec094e45e09a7cd1d607da", "save_path": "github-repos/coq/radu07-automat", "path": "github-repos/coq/radu07-automat/automat-5d8c4ec7414025cb83ec094e45e09a7cd1d607da/auto/auto/Automata.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.6822819299483172}}
{"text": "Require Export DMFP.Day08_sets.\n\n(* ================================================================= *)\n(** ** Case study: DNA edit distance *)\n\n(** A key biological question of interest is _similarity_. How similar\n    are two individuals of the same species? How similar are two\n    species? When we see similarities or differences in expressed\n    behavior (_phenotype_), can we trace these to corresponding\n    similarities or differences in genetics (_genotype_)?\n *)\n\n(** To ask these questions in a formal way, we need measures of\n    similarity. One popular quantitative measure for any list-based\n    data is called _edit distance_. Given two strands of DNA, how many\n    edits do we need to make to get from one to the other?\n\n    For example, consider the following DNA sequences.\n *)\n\nDefinition dna_src  : strand := [G; C; A; T].\nDefinition dna_tgt1 : strand := [T; C; A; T].\nDefinition dna_tgt2 : strand := [C; A; T].\nDefinition dna_tgt3 : strand := [C; A; T; G].\n\n(** What edits might we need to make to get from [dna_src] to each of\n    the [dna_tgt]s?\n\n    To change [dna_src] into [dna_tgt1], we should replace the first\n    [G], substituting it with a [T].\n\n    To change [dna_src] into [dna_tgt2], we should delete the first\n    [G].\n\n    To change [dna_src] into [dna_tgt3], we should delete the first\n    [G] and add a [G] at the end.\n\n*)\n\n(** We can formalize this idea explicitly: we'll define a type [edit]\n    and say what it means to 'apply' an edit.\n\n    Here's what an edit is: you can either [copy] a nucleotide,\n    [delete] a nucleotide, [add] a nucleotide, or [substitute] a\n    nucleotide for what was already there.  *)\n\nInductive edit : Type :=\n| copy\n| delete\n| add (e : base)\n| substitute (e : base).\n\n(** These aren't the only edits we could have defined. For example, we\n    don't _need_ [substitute], since we can always [delete] and then\n    [add] (or vice versa). We could add a [move] edit that somehow\n    said where to move the current base (i.e., in changing [dna_src]\n    to [dna_tgt3], we could say that that [G] _moves_ to the end).\n\n    We've chosen these edits because they correspond to the edits\n    invented by Vladimir Levenshtein in 1966, and are used to compute\n    the widely used Levenshtein distance (see\n    https://en.wikipedia.org/wiki/Levenshtein_distance). It's worth\n    noting that this distance is _very_ useful in computational\n    applications in a variety of domains, but (according to folklore),\n    Levenshtein didn't get to use computers at his Soviet institute!\n\n    In order to justify [substitute]'s presence when [add] and\n    [delete] would do, we define a notion of [cost]. It's free to\n    [copy], but every other edit has a cost of 1.\n *)\n\nDefinition cost (edit : edit) : nat :=\n  match edit with\n  | copy => 0\n  | delete => 1\n  | add _ => 1\n  | substitute _ => 1\n  end.\n\n(** Given a list of edits, the cost is just the sum of the costs of\n    every constituent edit. *)\nFixpoint total_cost (edits : list edit) : nat :=\n  match edits with\n  | [] => 0\n  | e::edits' => cost e + total_cost edits'\n  end.\n\n(** We've only given an intuition for edits. How do they actually\n    work? We must define what it means to apply an edit. We'll do it\n    in two parts: first, given an edit and a strand of DNA we're\n    editing, [apply_edit] returns two things: first, an optional\n    nucleotide which will appear at the front of the new, edited\n    strand; and second, a (possibly modified) DNA strand that we're\n    working on. *)\n\nDefinition apply_edit (edit : edit) (orig : strand) : option base * strand :=\n  match edit with\n  | copy =>\n    match orig with\n    | [] => (None, [])\n    | b::orig' => (Some b, orig')\n    end\n  | delete => (None, match orig with\n                     | [] => []\n                     | _::orig' => orig'\n                     end)\n  | add b => (Some b, orig)\n  | substitute b => (Some b, match orig with\n                             | [] => [] (* just act like add *)\n                             | _::orig' => orig'\n                             end)\n  end.\n\n(** It's worth paying close attention to this function, as there\n    are several corner cases.\n\n    - [copy] has two possibilities. Either the strand we're editing is\n      done, in which there's nothing to add and nothing to continue\n      with... or the strand has some base [b] at the front, which (a)\n      we'll make sure to copy to the front of the new strand ([Some\n      b]), and (b) we'll return the rest of the strand ([orig']).\n\n    - [delete] is slightly simpler. We'll never add anything to the\n      front ([None]), and we'll knock off the base at the front of the\n      strand we're working with, returning whatever may be left\n      ([orig']).\n\n    - [add b] is the simplest case: add [b] to the front and leave the\n      strand we're editing alone.\n\n    - [susbtitute b] is trickier. We'll put [b] at the front no matter\n      what ([Some b]), but what should we do if we're supposed to\n      substitute [b] but the strand we're editing is empty? We choose\n      to shrug and say, \"That's fine, we'll pretend you meant [add b]\n      and not worry about having nothing to substitute for.\" If, on\n      the other hand, [orig = b'::orig'], then we'll ignore [b']\n      (which is what we substituted for) and give [orig'] to keep\n      editing.\n *)\n\n(** Once we know how to apply an individual edit, it's easy enough to\n    apply a list of edits. We walk down the list and, for each edit,\n    we see what should be added to the front ([new]) and what remains\n    of the strand of DNA we're editing ([orig']). *)\n\nFixpoint apply_edits (orig : strand) (edits : list edit) : strand :=\n  match edits with\n  | [] => orig\n  | edit::edits' =>\n    let (new, orig') := apply_edit edit orig in\n    match new with\n    | None => apply_edits orig' edits'\n    | Some b => b::apply_edits orig' edits'\n    end\n  end.\n\n(** With a notion of edits in hand, let's verify that our formal model\n    matches our intuition. Can we come up with the 'valid' edits that\n    match our informal descriptions above? *)\n\nDefinition valid_edit (src : strand) (tgt : strand) (edits : list edit) :=\n  eq_strand (apply_edits src edits) tgt.\n\nDefinition edit_tgt1 : list edit := [substitute T; copy; copy; copy].\nDefinition edit_tgt1_worse : list edit := [delete; add T; copy; copy; copy].\nDefinition edit_tgt1_same : list edit := [substitute T].\n\nCompute (valid_edit dna_src dna_tgt1 edit_tgt1).\nCompute (valid_edit dna_src dna_tgt1 edit_tgt1_worse).\nCompute (leb (total_cost edit_tgt1) (total_cost edit_tgt1_worse)).\nCompute (eqb (total_cost edit_tgt1) (total_cost edit_tgt1_same)).\n\n(** **** Exercise: 3 stars, standard (edit_tgt23)\n\n    Write edits that take [dna_src] to [dna_tgt2] and [dna_tgt3]. Your\n    edits should be _minimal_, i.e., the lowest cost possible, while\n    still being valid. *)\n\nDefinition edit_tgt2 : list edit := [delete; copy; copy ; copy].\n\nCompute (valid_edit dna_src dna_tgt2 edit_tgt2).\n\nDefinition edit_tgt3 : list edit := [delete; copy; copy; copy; add G].\n\nCompute (valid_edit dna_src dna_tgt3 edit_tgt3).\n(* Do not modify the following line: *)\nDefinition manual_grade_for_edit_tgt23 : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (delete_add_edit)\n\n    With our notion of edits in hand, we can contemplate defining\n    algorithms that compute edits from one strand to another. Let's\n    begin with the simplest one: the [delete_add_edit].\n\n    To go from [src] to [tgt], first delete everything in [src] and\n    then add everything in [tgt].\n\n    Now, [delete_add_edit] won't be minimal, but it's a place to\n    start!\n\n    We'll define it in three parts: [delete_edit] takes a [src] strand\n    and produces the correct number of [delete] edits; [add_edit]\n    takes a [tgt] strand and produces the correct number of [add]\n    edits with the right bases; and [delete_add_edit] combines the\n    two.\n*)\n\n(** NOTE: your solutions should:\n\n    (a) be only line each\n\n    (b) for [delete_edit] and [add_edit], use the [map] function\n\n    (c) for [delete_add_edit], use [delete_edit] and [add_edit].\n *)\n\nDefinition delete_edit (src : strand) : list edit := map (fun n  => delete ) src.\n\nDefinition add_edit (tgt : strand) : list edit := map add tgt.\n\nDefinition delete_add_edit (src : strand) (tgt : strand) : list edit := delete_edit src ++ add_edit tgt.\n(** [] *)\n\n(** With those definitions under our belt, we can write a more\n    interesting edit function: substitute when possible, only adding\n    or deleting when one list runs out. *)\n\nFixpoint naive_sub_edit (src : strand) (tgt : strand) : list edit :=\n  match (src, tgt) with\n  | ([], tgt) => add_edit tgt\n  | (src, []) => delete_edit src\n  | (_::src', b2::tgt') =>\n    substitute b2 :: naive_sub_edit src' tgt'\n  end.\n\n(** **** Exercise: 2 stars, standard (sub_edit)\n\n    [naive_sub_edit] is a little bit, well, naive. Give an example of\n    a pair of DNA strands [naive_src] and [naive_tgt] for which\n    [naive_sub_edit] gives a high cost when it could give a very low\n    cost. *)\nDefinition naive_src : strand := [T; G; T; C].\nDefinition naive_tgt : strand := [A; G; T; C].\n\n(** Explain why [naive_sub_edit naive_src naive_tgt] is so high\n    cost. What should happen differently?  *)\n\n(* It is because naive_sub_edit is just substituting the bases in naive_src with the bases in naive_tgt, regardless of whether the base in src matches the base in tgt.\n What should be done is that it copys the base in tgt if the base in src matches the base in tgt  *)\n\n(** Define a function [sub_edit] that generates an edit similarly to\n    [naive_sub_edit], but without the naivete. *)\nFixpoint sub_edit (src : strand) (tgt : strand) : list edit :=\n  match (src, tgt) with\n  | ([], tgt) => add_edit tgt\n  | (src, []) => delete_edit src\n  | (bl::src', b2::tgt') => match eq_base bl b2 with\n                            | true=> copy :: sub_edit src' tgt'\n                            | false => substitute b2 :: sub_edit src' tgt'\n                            end\n  end.\n(** [] *)\n\n(* ################################################################# *)\n(** * Levenshtein's edit distance *)\n\n(** **** Exercise: 3 stars, standard (levenshtein)\n\n    We've looked at a bunch of different edit functions: it's time to\n    look at Vladimir Levenshtein's!\n\n    The key idea is to consider four possible edits at each juncture\n    and choose the cheapest one. Suppose we're trying to edit [b1 ::\n    src] into [b2 :: tgt]. (When one is empty, things are simpler.)\n\n    - If [b1] and [b2] are the same, we can [copy], continuing with\n      [src] and [tgt].\n\n    - If [b1] and [b2] are different, we can [substitute b2],\n      continuing with [src] and [tgt].\n\n    - We can delete [b1], continuing with [src] and [b2 :: tgt].\n\n    - We can add [b2], continuing with [b1 :: src] and [tgt].\n\n    You'll want to use [argmin3] to select the best possible\n    choice. You'll also need to use the [let fix] trick we used to\n    define [merge] (and you used to define [subset]).  *)\nFixpoint levenshtein (src tgt : strand) : list edit :=\n  let fix inner tgt :=\n      match src, tgt with\n      | src, [] => delete_edit src\n      | [], tgt  => add_edit tgt\n      | b1 :: src, b2 :: tgt =>\n        let copy_sub_edit :=\n            (if eq_base b1 b2 then copy else substitute b2) :: levenshtein src tgt in\n        let add_edit := (add b2) :: inner tgt in\n        let delete_edit := delete :: levenshtein src (b2 :: tgt) in\n        argmin3 total_cost copy_sub_edit add_edit delete_edit\n      end\n  in\n  inner tgt.\n                                   \n(** [] *)\n\n(** If you're stuck, here's a concrete example:\n\n    levenshtein [C; A; T] [C; G; T]\n\n    should generate [ [copy; substitute G; copy] ].\n\n    How will it do that? Well, looking at the bullet points in the\n    comments, it'll start by comparing [C] and [C], with [ [A; T] ]\n    remaining as [src'] and [ [G;T] ] remaining as [tgt'].\n\n    Since they're the same, a copy edit is possible and it's senseless\n    to use a substitute. But you could still end up with add or delete\n    edits being better (well, delete, at least). So consider each of\n    those.\n\n    So you have three possiblities:\n\n    - [ copy   :: levenshtein   [A;T]   [G;T] ]\n    - [ delete :: levenshtein   [A;T] [C;G;T] ]\n    - [ add C  :: levenshtein [C;A;T]   [G;T] ]\n\n    The Levenshtein algorithm looks at all three of these and picks\n    the best (this is where we use [argmin3]).\n*)\nCompute(apply_edits dna_src (levenshtein dna_src dna_tgt3)).\n(** **** Exercise: 1 star, standard (levenshtein__sub_edit)\n\n    Later on we'll prove that [levenshtein] produces _optimal_ edits,\n    i.e., you can't do better. That might not be obvious, though!\n\n    Give an example of a pair of DNA strands where [levenshtein] does\n    _much_ better than [sub_edit]. Our testing script asks for twice\n    as good. *)\nDefinition levenshtein__sub_edit_src : strand := [A; T].\nDefinition levenshtein__sub_edit_tgt : strand := [C; G; A; T].\n\n(** You've got it right when the first is less than or equal to the second. *)\nCompute (2 * (total_cost (levenshtein levenshtein__sub_edit_src levenshtein__sub_edit_tgt))).\nCompute      (total_cost (sub_edit    levenshtein__sub_edit_src levenshtein__sub_edit_tgt)).\n\n(** Why is [levenshtein] better than [sub_edit]? Try to make your\n    answer general. What can [levenshtein] do that [sub_edit] can't?\n    The best answer characterizes the difference, giving a _recipe_\n    for writing pairs of strands that will do better under\n    [levenshtein] than [sub_edit]. *)\n\n(* Levenshtein can utilize add and delete if and when they are needed at the beginning of editing src into tgt. However, sub_edit cannot use add and delete at the beginning of editing an src. Instead, sub_edit must use substitute first untill either src or tgt ends. Then it uses add and delete, even if some of the bases in tgt are in the same order  as those in src.That is why the cost of sub_edit is higher than the cost of levenshtein.    *)\n(* Do not modify the following line: *)\nDefinition manual_grade_for_levenshtein__sub_edit_tgt : option (nat*string) := None.\n(** [] *)\n\n(* 2021-09-13 09:44 *)\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/Day09_levenshtein.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.6822819293109255}}
{"text": "(** * Properties of Binary Positive Numbers *)\n\nFrom Coq Require Import\n  Classes.DecidableClass Classes.Morphisms Lia PArith.PArith.\nFrom DEZ.Has Require Export\n  ArithmeticOperations.\nFrom DEZ.Is Require Export\n  Commutative Group Semigroup Monoid.\n\n#[export] Instance positive_has_one : HasOne positive := xH.\n\nModule Pos.\n\n(** We extend the [Pos] module here. *)\n\nExport BinPos.Pos.\n\nLocal Open Scope N_scope.\nLocal Open Scope positive_scope.\n\n(** This incomplete set of corollaries\n    would be generated by the equations plugin. *)\n\nCorollary pred_N_equation_1 (p : positive) : pred_N (xI p) = Npos (xO p).\nProof. reflexivity. Qed.\n\nCorollary pred_N_equation_2 (p : positive) :\n  pred_N (xO p) = Npos (pred_double p).\nProof. reflexivity. Qed.\n\nCorollary pred_N_equation_3 : pred_N xH = N0.\nProof. reflexivity. Qed.\n\n#[export] Hint Rewrite @pred_N_equation_1 @pred_N_equation_2 @pred_N_equation_3 : pred_N.\n\nCorollary pos_shiftl_equation_1 (p : positive) : shiftl p N0 = p.\nProof. reflexivity. Qed.\n\nCorollary pos_shiftl_equation_2 (p n0 : positive) :\n  shiftl p (Npos n0) = iter xO p n0.\nProof. reflexivity. Qed.\n\n#[export] Hint Rewrite @pos_shiftl_equation_1 @pos_shiftl_equation_2 : shiftl.\n\nCorollary iter_equation_1 (A : Type) (f : A -> A) (x : A) (n' : positive) :\n  iter f x (xI n') = f (iter f (iter f x n') n').\nProof. reflexivity. Qed.\n\nCorollary iter_equation_2 (A : Type) (f : A -> A) (x : A) (n' : positive) :\n  iter f x (xO n') = iter f (iter f x n') n'.\nProof. reflexivity. Qed.\n\nCorollary iter_equation_3 (A : Type) (f : A -> A) (x : A) :\n  iter f x xH = f x.\nProof. reflexivity. Qed.\n\n#[export] Hint Rewrite @iter_equation_1 @iter_equation_2 @iter_equation_3 : iter.\n\n(** Whether the given number is a power of two or not. *)\n\nEquations bin (n : positive) : bool :=\n  bin (xO p) := bin p;\n  bin (xI p) := false;\n  bin xH := true.\n\n(** These lemmas are missing from the standard library. *)\n\nLemma shiftl_0_r (a : positive) : shiftl a N0 = a.\nProof. reflexivity. Qed.\n\n(** These instances are missing from the standard library. *)\n\nGlobal Program Instance Decidable_equiv_positive (x y : positive) :\n  Decidable (x = y) := {\n  Decidable_witness := eqb x y;\n  Decidable_spec := _;\n}.\nNext Obligation. intros x y. apply eqb_eq. Qed.\n\nGlobal Program Instance Decidable_le_positive (x y : positive) :\n  Decidable (x <= y) := {\n  Decidable_witness := leb x y;\n  Decidable_spec := _;\n}.\nNext Obligation. intros x y. apply leb_le. Qed.\n\nGlobal Program Instance Decidable_lt_positive (x y : positive) : Decidable (x < y) := {\n  Decidable_witness := ltb x y;\n  Decidable_spec := _;\n}.\nNext Obligation. intros x y. apply ltb_lt. Qed.\n\nGlobal Instance le_add_wd : Proper (le ==> le ==> le) add.\nProof. intros n p l n' p' l'. apply add_le_mono; [lia |]. lia. Qed.\n\nGlobal Instance le_mul_wd : Proper (le ==> le ==> le) mul.\nProof. intros n p l n' p' l'. apply mul_le_mono; [lia |]. lia. Qed.\n\nGlobal Instance le_div2_wd : Proper (le ==> le) div2.\nProof. intros n p l. destruct n, p; unfold div2; lia. Qed.\n\nGlobal Instance le_sqrt_wd : Proper (le ==> le) sqrt.\nProof.\n  intros n p l. unfold sqrt. destruct\n  (sqrtrem_spec n) as [s x | s x r],\n  (sqrtrem_spec p) as [s' x' | s' x' r']; cbn; nia.\nQed.\n\n(** Whether the given number is even or not. *)\n\nEquations even (n : positive) : bool :=\n  even (xI p) := false;\n  even (xO p) := true;\n  even xH := false.\n\n(** Whether the given number is odd or not. *)\n\nEquations odd (n : positive) : bool :=\n  odd n := negb (even n).\n\nEnd Pos.\n\nModule Additive.\n\nGlobal Instance positive_has_bin_op : HasBinOp positive := Pos.add.\n\nGlobal Instance positive_bin_op_is_assoc : IsAssoc _=_ Pos.add.\nProof. intros x y z. apply Pos.add_assoc. Defined.\n\nGlobal Instance positive_bin_op_is_semigrp : IsSemigrp _=_ Pos.add.\nProof. esplit; typeclasses eauto. Defined.\n\nGlobal Instance positive_bin_op_is_comm_bin_op : IsCommBinOp _=_ Pos.add.\nProof. intros x y. apply Pos.add_comm. Defined.\n\nEnd Additive.\n\nModule Multiplicative.\n\nGlobal Instance positive_bin_op_has_bin_op : HasBinOp positive := Pos.mul.\nGlobal Instance positive_has_null_op : HasNullOp positive := xH.\n\nGlobal Instance positive_bin_op_is_assoc : IsAssoc _=_ Pos.mul.\nProof. intros x y z. apply Pos.mul_assoc. Defined.\n\nGlobal Instance positive_bin_op_is_semigrp : IsSemigrp _=_ Pos.mul.\nProof. esplit; typeclasses eauto. Defined.\n\nGlobal Instance positive_bin_op_is_bin_op : IsCommBinOp _=_ Pos.mul.\nProof. intros x y. apply Pos.mul_comm. Defined.\n\nGlobal Instance positive_bin_op_null_op_is_unl_l : IsUnlElemL _=_ xH Pos.mul.\nProof. intros x. apply Pos.mul_1_l. Defined.\n\nGlobal Instance positive_bin_op_null_op_is_unl_r : IsUnlElemR _=_ xH Pos.mul.\nProof. intros x. apply Pos.mul_1_r. Defined.\n\nGlobal Instance positive_bin_op_null_op_is_unl : IsUnlElem _=_ xH Pos.mul.\nProof. esplit; typeclasses eauto. Defined.\n\nGlobal Instance positive_bin_op_null_op_is_mon : IsMon _=_ xH Pos.mul.\nProof. esplit; typeclasses eauto. Defined.\n\nEnd Multiplicative.\n", "meta": {"author": "Tuplanolla", "repo": "dez", "sha": "c2eadc2e032094c3504ec3803c000dba4feb547e", "save_path": "github-repos/coq/Tuplanolla-dez", "path": "github-repos/coq/Tuplanolla-dez/dez-c2eadc2e032094c3504ec3803c000dba4feb547e/fowl/Justifies/PositiveTheorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.68228191966217}}
{"text": "(************************************************************************)\n(* Copyright 2022 Frédéric Dabrowski                                    *)\n(* \n    This program is free software:: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    Foobar 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 General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with Foobar.  If not, see <https://www.gnu.org/licenses/>.    *)\n(************************************************************************)\n\n(** * Lattices *)\n\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Classes.RelationClasses.\n\nClass JoinLattice {A : Type} (eqA : relation A) `{equ : Equivalence A eqA}\n(R : relation A) `{partialOrder : PartialOrder A eqA R} (join : A -> A -> A)  :=\n{\n    join_bound1 (x y : A) : R x (join x y);\n    join_bound2 (x y : A) : R y (join x y);\n    join_least_upper_bound (x y z : A) : R x z -> R y z -> R (join x y) z \n}.\n\nClass MeetLattice {A : Type} (eqA : relation A) `{equ : Equivalence A eqA}\n(R : relation A) `{partialOrder : PartialOrder A eqA R} (meet : A -> A -> A)  :=\n{\n    meet_bound1 (x y : A) : R (meet x y) x;\n    meet_bound2 (x y : A) : R (meet x y) y;\n    meet_greatest_lower_bound (x y z : A) : R z x -> R z y -> R z (meet x y)\n}.\n\nClass Lattice {A : Type} (eqA : relation A) `{equ : Equivalence A eqA}\n(R : relation A) `{partialOrder : PartialOrder A eqA R}\n(join : A -> A -> A) (meet : A -> A -> A): Type :=\n{\n    Lattice_JoinLattice :> JoinLattice eqA R join; \n    Lattice_MeetLattice :> MeetLattice  eqA R meet\n}.", "meta": {"author": "DabrowskiFr", "repo": "mssl", "sha": "8daf11bb2b9e9f73db1fad383a9d410f31fb27b7", "save_path": "github-repos/coq/DabrowskiFr-mssl", "path": "github-repos/coq/DabrowskiFr-mssl/mssl-8daf11bb2b9e9f73db1fad383a9d410f31fb27b7/theories/Lattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6822507671445158}}
{"text": "(**\nスタックコンパイラの証明\n========\n@suharahiromichi\n\n2014_04_30\n *)\nRequire Import ssreflect ssrbool ssrnat seq eqtype ssrfun.\n(**\n算術式をスタック指向のプログラミング言語にコンパイルするコンパイラ\n（スタックコンパイラ）が正しく動作することの証明をする。\n証明は SSReflect を使っておこなう。\n\nソースコードは以下にあります。\n\nhttps://github.com/suharahiromichi/coq/blob/master/ssr/ssr_stack_compiler.v\n*)\n(**\n# ソース言語（算術式）の定義\n *)\n(**\n状態`state`はプログラムの実行のある時点のすべての変数の現在値を表す。\n *)\nInductive id : Type := \n  Id of nat.\n\nDefinition state := id -> nat.\n\n(**\nソース言語である算術式 `aexp` を定義する。\n *)\nInductive aexp : Type :=\n| ANum of nat\n| AId of id\n| APlus of aexp & aexp\n| AMinus of aexp & aexp\n| AMult of aexp & aexp.\n\n(**\n変数の略記法を以下に定義する。\n *)\nDefinition X : id := Id 0.\nDefinition Y : id := Id 1.\nDefinition Z : id := Id 2.\n\n(**\n`aexp` を評価する関数を定義する。\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\n(**\n# スタック指向のプログラミング言語（スタック言語）\n *)\n(**\nスタック言語の命令セット`sinstr`は、以下の命令から構成される:\n\n- `SPush n`: 数 `n` をスタックにプッシュする。\n- `SLoad X`: ストアから識別子 `X` に対応する値を読み込み、スタックにプッシュする。\n- `SPlus`:   スタックの先頭の 2 つの数をポップし、それらを足して、結果をスタックにプッシュする。\n- `SMinus`:  上と同様。ただし引く。\n- `SMult`:   上と同様。ただし掛ける。\n*)\n\nInductive sinstr : Type :=\n| SPush of nat\n| SLoad of id\n| SPlus\n| SMinus\n| SMult.\n\n(**\nスタック言語のプログラムを評価するための関数を書く。\n *)\nFixpoint s_exec (st : state) (ins : sinstr) (stack : seq nat) : seq nat :=\n  match ins with\n    | SPush n =>  n :: stack\n    | SLoad idx => (st idx) :: stack\n    | SPlus => match stack with\n                 | b :: a :: stack' => (a + b) :: stack'\n                 | _ => stack\n               end\n    | SMinus => match stack with\n                 | b :: a :: stack' => (a - b) :: stack'\n                 | _ => stack\n               end\n    | SMult => match stack with\n                 | b :: a :: stack' => (a * b) :: stack'\n                 | _ => stack\n               end\n  end.\n(**\n補足：stack underflow の判定をまとめて前に出すと、証明がたいへんになるだろう。\nまた、そのときの例外処理を行わないが、それによって、s_compile_correct_app \nの証明が簡単になっていると思う。\n *)\n\nFixpoint s_execute (st : state) (stack : seq nat) (prog : seq sinstr) : seq nat :=\n  match prog with\n    | [::] =>\n      stack\n    | ins :: prog' =>\n      s_execute st (s_exec st ins stack) prog'\n  end.\n\n(**\n`aexp` をスタック言語の命令列にコンパイルする関数 `s_compile` を書く。\n *)\nFixpoint s_compile (e : aexp) : seq sinstr :=\n  match e with\n    | ANum n => [:: SPush n]\n    | AId id => [:: SLoad id]\n    | APlus a b =>  (s_compile a) ++ (s_compile b) ++ [:: SPlus]\n    | AMinus a b => (s_compile a) ++ (s_compile b) ++ [:: SMinus]\n    | AMult a b =>  (s_compile a) ++ (s_compile b) ++ [:: SMult]\n  end.\n\n(**\n# コンパイルが正しいことの証明\n *)\n(**\n以下で、`s_compile` 関数が正しく振る舞うことを述べる定理を証明する。\n *)\n(**\n最初に補題として、スタック言語の命令列が append できることを証明する。\n *)\nLemma s_compile_correct_app : forall (st : state)\n  (stack1 stack2 stack3: seq nat)\n  (prog1 prog2 : seq sinstr),\n  s_execute st stack1 prog1 = stack2 -> \n  s_execute st stack2 prog2 = stack3 -> \n  s_execute st stack1 (prog1 ++ prog2) = stack3.\nProof.\n  move=> st stack1 stack2 stack3 prog1.\n  elim: prog1 stack1 stack2 stack3.\n    by move=> stack1 stack2 stack3 prog2; rewrite cat0s; move=> <- <-.\n  move=> a prog1' IHprog1' stack1 stack2 stack3.\n  elim: a;\n    by move=> ?; apply IHprog1' with (stack2 := stack2).\nQed.\n\n(**\nより一般的な、stackが任意の状態の場合について、\n`aexp`をコンパイルしたスタック言語の命令列を実行した結果（左辺）と、\n`aexp`を直接実行した結果（右辺）が一致することを証明する。\n *)\nLemma s_compile_correct_stack : forall (st : state) (stack : seq nat) (e : aexp),\n  s_execute st stack (s_compile e) = [:: aeval st e] ++ stack.\nProof.\n  move=> st stack e.\n  elim: e stack;                            (* 「stack」をpushするのが肝。 *)\n    (* ANum, AId の場合 *)\n    try by [];\n  (* APlus, AMinus, AMult の場合 *)\n  try move=> e1 IHe1 e2 IHe2 st0;\n    apply s_compile_correct_app with (stack2 := aeval st e1 :: st0);\n    by [rewrite IHe1 |\n       apply s_compile_correct_app with (stack2 := aeval st e2 :: aeval st e1 :: st0);\n            [rewrite (IHe2 (aeval st e1 :: st0)) |]].\nQed.\n\n(**\n最後に、stackが初期状態（空[]）の場合について、\n`aexp`をコンパイルしたスタック言語の命令列を実行した結果（左辺）と、\n`aexp`を直接実行した結果（右辺）が一致することを証明する。\n *)\nTheorem s_compile_correct : forall (st : state) (e : aexp),\n  s_execute st [::] (s_compile e) = [:: aeval st e].\nProof.\n  move=> st e.\n  apply s_compile_correct_stack.\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/ssr/ssr_stack_compiler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6822268154568536}}
{"text": "Require Export Order.\n\nTheorem wellorder_subst {R A X} :\n  well_order R A -> X ⊂ A -> well_order R X.\nProof.\n  intros H XA.\n  induction H as [W T].\n  unfold well_found in W.\n  induction T as [trans_ T].\n  induction T as [notrefl tri].\n  split.\n  + intros Y YX notY.\n    apply W.\n    - intros y yY.\n      apply (XA y (YX y yY)).\n    - done.\n  + split.\n    intros x y z xX yX zX xyR yzR.\n    apply (trans_ x y z (XA x xX) (XA y yX) (XA z zX) xyR yzR).\n    split.\n    * intros x xX H.\n      apply ((notrefl x (XA x xX)) H) .\n    * intros x y xX yX.\n      induction (tri x y (XA x xX) (XA y yX)).\n      apply (or_introl H).\n      induction H.\n      apply (or_intror (or_introl H)).\n      apply (or_intror (or_intror H)).\nQed.\n      \n\n\n", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "sets", "sha": "4db587e90349f1c8786dae9ffd14f56535512e07", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-sets", "path": "github-repos/coq/gaxiiiiiiiiiiii-sets/sets-4db587e90349f1c8786dae9ffd14f56535512e07/Order_Theorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6822268129356809}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := mult x y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj1910_coqofml_7kZckx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.682226805953445}}
{"text": "Require Export Arith.\nRequire Export ArithRing.\nRequire Export Lia.\nRequire Export Wf_nat.\n \nFixpoint div2 (n : nat) : nat :=\n match n with S (S p) => S (div2 p) | _ => 0 end.\n \nTheorem div2_ind:\n forall (P : nat ->  Prop),\n P 0 -> P 1 -> (forall n, P n ->  P (S (S n))) -> forall n,  P n.\nProof.\nintros P H0 H1 Hstep n.\nassert (H : P n /\\ P (S n)) by (elim n; intuition).\n now destruct H.\nQed.\n \nTheorem div2_lt: forall n,  (div2 (S n) < S n).\nProof.\nintros; elim n  using div2_ind; simpl; intros; lia.\nQed.\n \nDefinition log2_it_F (log2 : nat ->  nat) (n : nat) : nat :=\n   match n with\n     0 => 0\n    | 1 => 0\n    | S (S p) => S (log2 (div2 (S (S p))))\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 log2_terminates:\n forall (n : nat),\n  ({v : nat | exists p : nat , forall k g, p < k ->  iter log2_it_F k g n = v }).\nProof. \n intros n; elim n  using (well_founded_induction lt_wf); clear n.\n intros n; case n.\n - intros; exists 0, 0;  intros k; case k.\n   + intros; lia.\n   + intros k' g _; simpl; auto.\n - intros n'; case n'.\n   + intros; exists 0; exists 0; intros k; case k.\n     * intros; lia.\n     * intros k' g_; simpl; auto.\n   + intros p f; assert (Hlt: div2 (S (S p)) < S (S p))\n                 by apply div2_lt.\n     destruct (f (div2 (S (S p))) Hlt) as [v Hex];exists (S v).\n     destruct Hex as [p' Heq];exists (S p').\n     intros k g; case k.\n     * intros; lia.\n     * intros k' Hltk;rewrite <- (Heq k' g); auto.\n       lia.\nQed.\n \nDefinition log2 (n : nat) : nat :=\n   match log2_terminates n with exist _ v _ => v end.\n \nTheorem log2_fix_eqn:\n forall n,  log2 n = match n with\n                       0 => 0\n                      | 1 => 0\n                      | S (S p) => S (log2 (div2 (S (S p))))\n                     end.\nProof. \n intros n; unfold log2; case (log2_terminates n); case n.\n - intros v [p Heq]; rewrite <- (Heq (S p) log2); auto.\n - intros n'; case n'.\n   + intros v [p Heq];rewrite <- (Heq (S p) log2); auto.\n   + intros n'' v [p Heq];case (log2_terminates (div2 (S (S n'')))).\n     intros v' [p' Heq'];\n     rewrite <- (Heq (S (S (p + p'))) log2),\n             <- (Heq' (S (p + p')) log2); auto.\n     lia.\n     lia.\nQed.\n \nTheorem div2_eq: forall n,  2 * div2 n = n \\/ 2 * div2 n + 1 = n.\nProof.\nintros n; elim n  using div2_ind; simpl; lia.\nQed.\n \nFixpoint exp2 (n : nat) : nat :=\n match n with 0 => 1 | S p => 2 * exp2 p end.\n \nTheorem log2_power:\n forall n, 0 < n ->  ( exp2 (log2 n) <= n < 2 * exp2 (log2 n) ).\nProof. \nintros n; elim n  using (well_founded_ind lt_wf).\nintros x; case x.\n- simpl; intros; lia.\n- intros x'; case x'.\n  + rewrite (log2_fix_eqn 1); simpl; auto with arith.\n  + intros p Hrec; elim (Hrec (div2 (S (S p)))).\n    * intros Hle Hlt _; rewrite (log2_fix_eqn (S (S p))).\n      cbv zeta iota beta delta [exp2]; fold exp2.\n      split.\n      apply le_trans with (2 * div2 (S (S p))).\n      auto with arith.\n      elim (div2_eq (S (S p))).\n      lia.\n      lia.\n      apply le_lt_trans with (2 * div2 (S (S p)) + 1).\n      elim (div2_eq (S (S p))).\n      lia.\n      lia.\n      lia.\n    * apply div2_lt; simpl; auto with arith.\n    *  simpl; auto with arith.\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/ch15_general_recursion/SRC/log2_it.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6822268034322722}}
{"text": "Require Import UniMath.Foundations.PartD.\nRequire Import UniMath.Foundations.Sets.\nRequire Import UniMath.Foundations.NaturalNumbers.\n\nDefinition graph: UU := total2 (fun S: (dirprod hSet hSet) => dirprod ((pr2 S) -> (pr1 S)) ((pr2 S) -> (pr1 S))).\n\nDefinition make_graph (V E : hSet) (s t : E -> V) : graph := tpair (fun S : (dirprod hSet hSet) => dirprod ((pr2 S) -> (pr1 S)) ((pr2 S) -> (pr1 S))) (make_dirprod V E) (make_dirprod s t).\n\nDefinition vertices_of (g : graph) := dirprod_pr1 (pr1 g).\nDefinition edges_of (g : graph) := dirprod_pr2 (pr1 g).\nDefinition source_of (g : graph) := dirprod_pr1 (pr2 g).\nDefinition target_of (g : graph) := dirprod_pr2 (pr2 g).\n\nDefinition path_of_length (g : graph) : nat -> (vertices_of g) -> (vertices_of g) -> UU := nat_rect _ (fun (v1 v2 : (vertices_of g)) => paths v1 v2) (fun (m : nat) (pths_of_m : _) => (fun (v1 v2 : (vertices_of g)) => (total2 (fun u : (vertices_of g) => dirprod (pths_of_m v1 u) (total2 (fun (e : (edges_of g)) => dirprod (paths u ((source_of g) e)) (paths v2 ((target_of g) e)))))))).\n\nDefinition cycle (g : graph) : UU := (total2 (fun (v : vertices_of g) => total2 (fun (n : nat) => dirprod (n != 0) (path_of_length g n v v)))).\n\nDefinition acyclic (g : graph) : hProp := make_hProp (neg (ishinh (cycle g))) (isapropneg _).\n\nDefinition empty_isaset: (isaset empty) := empty_rect (fun (x: empty) => (∏ x': empty, isaprop (paths x x'))).\nDefinition emptyset: hSet := make_hSet empty empty_isaset.\n\nDefinition underlined : nat -> hSet := nat_rect _ emptyset (fun (_ : _) (prev : _) => setcoprod prev unitset).\n\nDefinition I_or_O (V : hSet) (f : V -> nat) := total2_hSet (fun v : V => underlined (f v)).\n\nDefinition tuple (m n : nat) : UU := total2 (fun V : hSet => total2 (fun in_out : dirprod (V -> nat) (V -> nat) => weq (setcoprod (underlined m) (I_or_O V (dirprod_pr2 in_out))) (setcoprod (underlined n) (I_or_O V (dirprod_pr1 in_out))))).\n\nDefinition vertices {m n : nat} (t : tuple m n) := pr1 t.\nDefinition in_func {m n : nat} (t : tuple m n) := dirprod_pr1 (pr1 (pr2 t)).\nDefinition out_func {m n : nat} (t : tuple m n) := dirprod_pr2 (pr1 (pr2 t)).\nDefinition i_func {m n : nat} (t : tuple m n) := pr1 (pr2 (pr2 t)).\nDefinition i_property {m n : nat} (t : tuple m n) := pr2 (pr2 (pr2 t)).\n\nDefinition internal_flow_graph_of {m n : nat} (t : tuple m n) : graph := make_graph (vertices t) (total2_hSet (fun uivj : dirprod_hSet (I_or_O (vertices t) (out_func t)) (I_or_O (vertices t) (in_func t)) => hProp_to_hSet (eqset ((i_func t) (inr (dirprod_pr1 uivj))) (inr (dirprod_pr2 uivj))))) (fun uivj : _ => pr1 (dirprod_pr2 (pr1 uivj))) (fun uivj : _ => pr1 (dirprod_pr1 (pr1 uivj))).\n\nDefinition port_graph (m n : nat) : UU := total2 (fun t : tuple m n => acyclic (internal_flow_graph_of t)).\n\nDefinition topological_order (g : graph) : UU := total2 (fun enumeration : (vertices_of g) -> nat => forall e : edges_of g, natlth (enumeration ((source_of g) e)) (enumeration ((target_of g) e))).\n\nLemma trivial_case (g : graph) (top_order : topological_order g) (v1 : vertices_of g) : forall u : vertices_of g, ((paths 0 0) -> empty) -> (path_of_length g 0 v1 u) -> natlth ((pr1 top_order) v1) ((pr1 top_order) u).\nProof.\n  intros u prop.\n  apply (fromempty (prop (idpath 0))).\nQed.\n\nLemma trivial_case_for_next_step (g : graph) (top_order : topological_order g) (v1 v : vertices_of g) (n : nat) (path : path_of_length g (S (S n)) v1 v) : natlth ((pr1 top_order) (pr1 path)) ((pr1 top_order) v).\nProof.\n  rewrite (dirprod_pr2 (pr2 (dirprod_pr2 (pr2 path)))).\n  apply (paths_rect _ (source_of g (pr1 (dirprod_pr2 (pr2 path)))) (fun (ver : vertices_of g) (_ : _) => natlth ((pr1 top_order) ver) ((pr1 top_order) (target_of g (pr1 (dirprod_pr2 (pr2 path)))))) ((pr2 top_order) (pr1 (dirprod_pr2 (pr2 path)))) (pr1 path) (pathsinv0 (dirprod_pr1 (pr2 (dirprod_pr2 (pr2 path)))))).\nQed.\n\nLemma next_step (g : graph) (top_order : topological_order g) (v1 : vertices_of g) (n : nat) (prev_step : forall u : vertices_of g, ((paths n 0) -> empty) -> (path_of_length g n v1 u) -> natlth ((pr1 top_order) v1) ((pr1 top_order) u)) : forall v : vertices_of g, ((paths (S n) 0) -> empty) -> (path_of_length g (S n) v1 v) -> natlth ((pr1 top_order) v1) ((pr1 top_order) v).\nProof.\n  intros v prop path.\n  unfold path_of_length in path.\n  induction n.\n  unfold nat_rect in path.\n  rewrite (dirprod_pr1 (pr2 path)).\n  unfold topological_order in top_order.\n  rewrite (dirprod_pr2 (pr2 (dirprod_pr2 (pr2 path)))).\n  apply (paths_rect _ (source_of g (pr1 (dirprod_pr2 (pr2 path)))) (fun (ver : vertices_of g) (_ : _) => natlth ((pr1 top_order) ver) ((pr1 top_order) (target_of g (pr1 (dirprod_pr2 (pr2 path)))))) ((pr2 top_order) (pr1 (dirprod_pr2 (pr2 path)))) (pr1 path) (pathsinv0 (dirprod_pr1 (pr2 (dirprod_pr2 (pr2 path)))))).\n  apply (natlehlthtrans _ _ _ (natlthtoleh _ _ (prev_step (pr1 path) (negpathssx0 n) (dirprod_pr1 (pr2 path)))) (trivial_case_for_next_step g top_order v1 v n path)).\nQed.\n\nLemma extended_topological_order (g : graph) : (topological_order g) -> total2 (fun enumeration : (vertices_of g) -> nat => forall (v1 v2 : vertices_of g) (n : total2 (fun m : nat => (paths m 0) -> empty)), (path_of_length g (pr1 n) v1 v2) -> natlth (enumeration v1) (enumeration v2)).\nProof.\n  intros top_order.\n  unfold topological_order in top_order.\n  exists (pr1 top_order).\n  intros v1 v2 n.\n  intros path.\n  unfold path_of_length in path.\n  induction n as [n prop].\n  apply (nat_rect (fun (n : nat)  => forall u : vertices_of g, ((paths n 0) -> empty) -> (path_of_length g n v1 u) -> natlth ((pr1 top_order) v1) ((pr1 top_order) u)) (trivial_case g top_order v1) (next_step g top_order v1) n v2 prop path).\nQed.\n\nTheorem topological_order_acyclic (g : graph) : (topological_order g) -> (acyclic g).\nProof.\n  unfold acyclic.\n  intros top_order cycle.\n  unfold topological_order in top_order.\n  (**unfold cycle in cycle.**)\n  Print ishinh_UU.\n  apply (cycle hfalse (fun cycle' => (isirreflnatlth _ ((pr2 (extended_topological_order g top_order)) (pr1 cycle') (pr1 cycle') (tpair (fun n : nat => n != 0) (pr1 (pr2 cycle')) (dirprod_pr1 (pr2 (pr2 cycle')))) (dirprod_pr2 (pr2 (pr2 cycle'))))))).\nQed.\n\nDefinition in_example : boolset -> nat := fun (b : boolset) => 1.\nDefinition out_example : boolset -> nat := fun (b : boolset) => 1.\nDefinition in_out_example := make_dirprod in_example out_example.\n\nDefinition i_func_example : (setcoprod (underlined 2) (I_or_O boolset (dirprod_pr2 in_out_example))) -> (setcoprod (underlined 2) (I_or_O boolset (dirprod_pr1 in_out_example))).\n  intros out.\n  induction out.\n  unfold underlined in a.\n  unfold nat_rect in a.\n  induction a.\n  induction a.\n  apply (fromempty (a)).\n  unfold I_or_O.\n  unfold underlined.\n  unfold dirprod_pr1.\n  unfold in_out_example.\n  unfold make_dirprod.\n  unfold pr1.\n  unfold in_example.\n  unfold nat_rect.\n  apply (inr (tpair _ true (inr tt))).\n  apply (inr (tpair _ false (inr tt))).\n  unfold in_out_example in b.\n  unfold make_dirprod in b.\n  unfold dirprod_pr2 in b.\n  unfold pr2 in b.\n  unfold I_or_O in b.\n  induction b as [v i].\n  induction v.\n  unfold out_example in i.\n  unfold underlined in i.\n  unfold nat_rect in i.\n  induction i.\n  apply (fromempty (a)).\n  apply (inl (inl (inr tt))).\n  unfold out_example in i.\n  unfold underlined in i.\n  unfold nat_rect in i.\n  induction i.\n  apply (fromempty (a)).\n  apply (inl (inr tt)).\nDefined.\n\nDefinition i_func_example_reverse : (setcoprod (underlined 2) (I_or_O boolset (dirprod_pr1 in_out_example))) -> (setcoprod (underlined 2) (I_or_O boolset (dirprod_pr2 in_out_example))).\n  intros in_.\n  induction in_.\n  unfold underlined in a.\n  unfold nat_rect in a.\n  induction a.\n  induction a.\n  apply (fromempty (a)).\n  unfold I_or_O.\n  unfold underlined.\n  unfold dirprod_pr2.\n  unfold in_out_example.\n  unfold make_dirprod.\n  unfold pr2.\n  unfold out_example.\n  unfold nat_rect.\n  apply (inr (tpair _ true (inr tt))).\n  apply (inr (tpair _ false (inr tt))).\n  unfold in_out_example in b.\n  unfold make_dirprod in b.\n  unfold dirprod_pr1 in b.\n  unfold pr1 in b.\n  unfold I_or_O in b.\n  induction b as [v i].\n  induction v.\n  unfold in_example in i.\n  unfold underlined in i.\n  unfold nat_rect in i.\n  induction i.\n  apply (fromempty (a)).\n  apply (inl (inl (inr tt))).\n  unfold in_example in i.\n  unfold underlined in i.\n  unfold nat_rect in i.\n  induction i.\n  apply (fromempty (a)).\n  apply (inl (inr tt)).\nDefined.\n\nTheorem is_iso_i_example_1 : ∏ out_ : (setcoprod (underlined 2) (I_or_O boolset (dirprod_pr2 in_out_example))), i_func_example_reverse (i_func_example out_) = out_.\n  intros out_.\n  induction out_.\n  unfold underlined in a.\n  unfold nat_rect in a.\n  induction a.\n  induction a.\n  apply (fromempty a).\n  unfold i_func_example.\n  unfold coprod_rect.\n  unfold i_func_example_reverse.\n  unfold coprod_rect.\n  unfold bool_rect.\n  apply (maponpaths).\n  apply (maponpaths).\n  apply (maponpaths).\n  apply isProofIrrelevantUnit.\n  unfold i_func_example.\n  unfold coprod_rect.\n  unfold i_func_example_reverse.\n  unfold coprod_rect.\n  unfold bool_rect.\n  apply maponpaths.\n  apply maponpaths.\n  apply isProofIrrelevantUnit.\n  unfold in_out_example in b.\n  unfold make_dirprod in b.\n  unfold dirprod_pr2 in b.\n  unfold pr2 in b.\n  unfold I_or_O in b.\n  induction b as [v i].\n  induction v.\n  unfold out_example in i.\n  unfold underlined in i.\n  unfold nat_rect in i.\n  induction i.\n  apply (fromempty a).\n  unfold i_func_example.\n  unfold coprod_rect.\n  unfold bool_rect.\n  unfold i_func_example_reverse.\n  unfold coprod_rect.\n  apply maponpaths.\n  apply maponpaths.\n  apply maponpaths.\n  apply isProofIrrelevantUnit.\n  unfold out_example in i.\n  unfold underlined in i.\n  unfold nat_rect in i.\n  induction i.\n  apply (fromempty a).\n  unfold i_func_example.\n  unfold coprod_rect.\n  unfold bool_rect.\n  unfold i_func_example_reverse.\n  unfold coprod_rect.\n  apply maponpaths.\n  apply maponpaths.\n  apply maponpaths.\n  apply isProofIrrelevantUnit.\nQed.\n\nTheorem is_iso_i_example_2 : ∏ in_ : (setcoprod (underlined 2) (I_or_O boolset (dirprod_pr1 in_out_example))), i_func_example (i_func_example_reverse in_) = in_.\n  intros in_.\n  induction in_.\n  unfold underlined in a.\n  unfold nat_rect in a.\n  induction a.\n  induction a.\n  apply (fromempty a).\n  unfold i_func_example.\n  unfold coprod_rect.\n  unfold i_func_example_reverse.\n  unfold coprod_rect.\n  unfold bool_rect.\n  apply (maponpaths).\n  apply (maponpaths).\n  apply (maponpaths).\n  apply isProofIrrelevantUnit.\n  unfold i_func_example.\n  unfold coprod_rect.\n  unfold i_func_example_reverse.\n  unfold coprod_rect.\n  unfold bool_rect.\n  apply maponpaths.\n  apply maponpaths.\n  apply isProofIrrelevantUnit.\n  unfold in_out_example in b.\n  unfold make_dirprod in b.\n  unfold dirprod_pr2 in b.\n  unfold pr2 in b.\n  unfold I_or_O in b.\n  induction b as [v i].\n  induction v.\n  unfold out_example in i.\n  unfold underlined in i.\n  unfold nat_rect in i.\n  induction i.\n  apply (fromempty a).\n  unfold i_func_example.\n  unfold coprod_rect.\n  unfold bool_rect.\n  unfold i_func_example_reverse.\n  unfold coprod_rect.\n  apply maponpaths.\n  apply maponpaths.\n  apply maponpaths.\n  apply isProofIrrelevantUnit.\n  unfold out_example in i.\n  unfold underlined in i.\n  unfold nat_rect in i.\n  induction i.\n  apply (fromempty a).\n  unfold i_func_example.\n  unfold coprod_rect.\n  unfold bool_rect.\n  unfold i_func_example_reverse.\n  unfold coprod_rect.\n  apply maponpaths.\n  apply maponpaths.\n  apply maponpaths.\n  apply isProofIrrelevantUnit.\nQed.\n\nDefinition i_example : weq (setcoprod (underlined 2) (I_or_O boolset (dirprod_pr2 in_out_example))) (setcoprod (underlined 2) (I_or_O boolset (dirprod_pr1 in_out_example))).\n  unfold weq.\n  exists i_func_example.\n  apply (isweq_iso _ i_func_example_reverse is_iso_i_example_1 is_iso_i_example_2).\nDefined.\n\nDefinition tuple_example : tuple 2 2.\n  unfold tuple.\n  exists boolset.\n  exists in_out_example.\n  apply i_example.\nDefined.\n\nLemma setcoprod_injective: ∏ (A B: hSet), ∏ (a: A), ∏ (b: B), (paths (inl a) (inr b)) -> empty.\n  intros.\n  exact (transportf (coprod_rect (fun (_: setcoprod A B) => Type)  (fun _ => unit) (fun _ => empty)) X tt).\nQed.\n\nDefinition acyclicity_tuple_example_1 : acyclic (internal_flow_graph_of tuple_example).\napply topological_order_acyclic.\n  unfold topological_order.\n  exists (bool_rect _ 1 2).\n  intros e.\n  unfold internal_flow_graph_of in e.\n  unfold tuple_example in e.\n  unfold edges_of in e.\n  unfold make_graph in e.\n  unfold dirprod_pr2 in e.\n  unfold make_dirprod in e.\n  unfold pr2 in e.\n  unfold pr1 in e.\n  induction e as [uivj prop].\n  unfold vertices in uivj.\n  unfold pr1 in uivj.\n  unfold out_func in uivj.\n  unfold in_func in uivj.\n  unfold dirprod_pr2 in uivj.\n  unfold dirprod_pr1 in uivj.\n  unfold pr1 in uivj.\n  unfold pr2 in uivj.\n  unfold in_out_example in uivj.\n  unfold make_dirprod in uivj.\n  unfold I_or_O in uivj.\n  induction uivj as [ui vj].\n  induction ui as [u i].\n  induction vj as [v j].\n  unfold i_func in prop.\n  unfold in_out_example in prop.\n  unfold make_dirprod in prop.\n  unfold dirprod_pr1 in prop.\n  unfold pr1 in prop.\n  unfold pr2 in prop.\n  induction u.\n  unfold out_example in i.\n  unfold underlined in i.\n  unfold nat_rect in i.\n  induction i.\n  apply (fromempty a).\n  induction v.\n  unfold out_example in j.\n  unfold underlined in j.\n  unfold nat_rect in j.\n  induction j.\n  apply (fromempty a).\n  apply (fromempty (setcoprod_injective _ _ _ _ prop)).\n  unfold in_example in j.\n  unfold underlined in j.\n  unfold nat_rect in j.\n  induction j.\n  apply (fromempty a).\n  apply (fromempty (setcoprod_injective _ _ _ _ prop)).\n  unfold out_example in i.\n  unfold underlined in i.\n  unfold nat_rect in i.\n  induction i.\n  apply (fromempty a).\n  induction v.\n  unfold in_example in j.\n  unfold underlined in j.\n  unfold nat_rect in j.\n  induction j.\n  apply (fromempty a).\n  apply (fromempty (setcoprod_injective _ _ _ _ prop)).\n  unfold in_example in j.\n  unfold underlined in j.\n  unfold nat_rect in j.\n  induction j.\n  apply (fromempty a).\n  apply (fromempty (setcoprod_injective _ _ _ _ prop)).\nDefined.\n\nDefinition acyclicity_tuple_example_2 : acyclic (internal_flow_graph_of tuple_example).\napply topological_order_acyclic.\n  unfold topological_order.\n  exists (bool_rect _ 2 1).\n  intros e.\n  unfold internal_flow_graph_of in e.\n  unfold tuple_example in e.\n  unfold edges_of in e.\n  unfold make_graph in e.\n  unfold dirprod_pr2 in e.\n  unfold make_dirprod in e.\n  unfold pr2 in e.\n  unfold pr1 in e.\n  induction e as [uivj prop].\n  unfold vertices in uivj.\n  unfold pr1 in uivj.\n  unfold out_func in uivj.\n  unfold in_func in uivj.\n  unfold dirprod_pr2 in uivj.\n  unfold dirprod_pr1 in uivj.\n  unfold pr1 in uivj.\n  unfold pr2 in uivj.\n  unfold in_out_example in uivj.\n  unfold make_dirprod in uivj.\n  unfold I_or_O in uivj.\n  induction uivj as [ui vj].\n  induction ui as [u i].\n  induction vj as [v j].\n  unfold i_func in prop.\n  unfold in_out_example in prop.\n  unfold make_dirprod in prop.\n  unfold dirprod_pr1 in prop.\n  unfold pr1 in prop.\n  unfold pr2 in prop.\n  induction u.\n  unfold out_example in i.\n  unfold underlined in i.\n  unfold nat_rect in i.\n  induction i.\n  apply (fromempty a).\n  induction v.\n  unfold out_example in j.\n  unfold underlined in j.\n  unfold nat_rect in j.\n  induction j.\n  apply (fromempty a).\n  apply (fromempty (setcoprod_injective _ _ _ _ prop)).\n  unfold in_example in j.\n  unfold underlined in j.\n  unfold nat_rect in j.\n  induction j.\n  apply (fromempty a).\n  apply (fromempty (setcoprod_injective _ _ _ _ prop)).\n  unfold out_example in i.\n  unfold underlined in i.\n  unfold nat_rect in i.\n  induction i.\n  apply (fromempty a).\n  induction v.\n  unfold in_example in j.\n  unfold underlined in j.\n  unfold nat_rect in j.\n  induction j.\n  apply (fromempty a).\n  apply (fromempty (setcoprod_injective _ _ _ _ prop)).\n  unfold in_example in j.\n  unfold underlined in j.\n  unfold nat_rect in j.\n  induction j.\n  apply (fromempty a).\n  apply (fromempty (setcoprod_injective _ _ _ _ prop)).\nDefined.\n\nDefinition example_of_port_graph : port_graph 2 2.\n  unfold port_graph.\n  exists tuple_example.\n  apply acyclicity_tuple_example_1.\nDefined.\n\nDefinition example2_of_port_graph : port_graph 2 2.\n  unfold port_graph.\n  exists tuple_example.\n  apply acyclicity_tuple_example_2.\nDefined.\n\nLemma do_acyclisity_proofs_equal : paths acyclicity_tuple_example_1 acyclicity_tuple_example_2.\n  apply (propproperty (acyclic (internal_flow_graph_of tuple_example))).\nQed.\n\nTheorem do_examples_equal : paths example_of_port_graph example2_of_port_graph.\n  unfold example_of_port_graph.\n  unfold example2_of_port_graph.\n  apply (maponpaths _ do_acyclisity_proofs_equal).\nQed.\n\n\nPrint example_of_port_graph.\n\nSearch natgth.\n\n\n  (**apply (inr (tpair (fun vi : (boolset × natset)%set => dirprod_pr2 vi > 0 × dirprod_pr2 vi ≤ dirprod_pr1 in_out_example (dirprod_pr1 vi)) (make_dirprod true 1) (make_dirprod (natgthsnn 0) (isreflnatleh 1)))).\n  apply (inr (tpair (fun vi : (boolset × natset)%set => dirprod_pr2 vi > 0 × dirprod_pr2 vi ≤ dirprod_pr1 in_out_example (dirprod_pr1 vi)) (make_dirprod false 1) (make_dirprod (natgthsnn 0) (isreflnatleh 1)))).\n  induction b as [vi prop].\n  induction vi as [v i].\n  induction v.\n  unfold in_out_example in prop.\n  unfold dirprod_pr2 in prop.\n  unfold pr2 in prop.\n  unfold make_dirprod in prop.\n  unfold out_example in prop.\n  induction i.\n  apply (fromempty (negnatgth0n 0 (pr1 prop))).\n  induction i.\n  unfold underlined.\n  unfold nat_rect.\n  apply (inl (inl (inr tt))).**)\n\n(**Definition i_func_example :  (setcoprod (underlined 2) (I_or_O boolset (dirprod_pr2 in_out_example))) -> (setcoprod (underlined 2) (I_or_O boolset (dirprod_pr1 in_out_example))).\n  intros out.\n  induction out.\n  induction a as [n prop].\n  induction n.\n  unfold hProp_to_hSet in prop.\n  apply (fromempty (negnatgth0n 0 (pr1 prop))).\n  induction n.\n  unfold I_or_O.\n  apply (inr (tpair (fun vi : (boolset × natset)%set => dirprod_pr2 vi > 0 × dirprod_pr2 vi ≤ dirprod_pr1 in_out_example (dirprod_pr1 vi)) (make_dirprod false 1) (make_dirprod (natgthsnn 0) (isreflnatleh 1)))).\n  induction n.\n  apply (inr (tpair (fun vi : (boolset × natset)%set => dirprod_pr2 vi > 0 × dirprod_pr2 vi ≤ dirprod_pr1 in_out_example (dirprod_pr1 vi)) (make_dirprod true 1) (make_dirprod (natgthsnn 0) (isreflnatleh 1)))).\n  apply (fromempty (negnatlehsnn 0 ((natlehandplusrinv 1 0 2) (pr2 prop)))).\n  induction b as [vi prop].\n  induction vi as [v i].\n  induction v.\n  unfold in_out_example in prop.\n  unfold dirprod_pr2 in prop.\n  unfold pr2 in prop.\n  unfold out_example in prop.\n  unfold dirprod_pr1 in prop.\n  unfold pr1 in prop.\n  unfold make_dirprod in prop.\n  induction i.\n  apply (fromempty (negnatgth0n 0 (pr1 prop))).\n  induction i.\n  unfold underlined.\n  apply (inl (tpair (fun n : nat => dirprod (natgth n 0) (natleh n 2)) 2 (make_dirprod (natgthsn0 0) (natlehnsn 1)))).\n  apply (fromempty (negnatlehsnn 0 ((natlehandplusrinv 1 0 1) (pr2 prop)))).\n  unfold in_out_example in prop.\n  unfold dirprod_pr2 in prop.\n  unfold pr2 in prop.\n  unfold out_example in prop.\n  unfold dirprod_pr1 in prop.\n  unfold pr1 in prop.\n  unfold make_dirprod in prop.\n  induction i.\n  apply (fromempty (negnatgth0n 0 (pr1 prop))).\n  induction i.\n  unfold underlined.\n  apply (inl (tpair (fun n : nat => dirprod (natgth n 0) (natleh n 2)) 1 (make_dirprod (natgthsn0 0) (natlehnsn 1)))).\n  apply (fromempty (negnatlehsnn 0 ((natlehandplusrinv 1 0 1) (pr2 prop)))).\nDefined.\n\nDefinition i_func_example_reverse : (setcoprod (underlined 2) (I_or_O boolset (dirprod_pr1 in_out_example))) -> (setcoprod (underlined 2) (I_or_O boolset (dirprod_pr2 in_out_example))).\nintros out.\n  induction out.\n  induction a as [n prop].\n  induction n.\n  unfold hProp_to_hSet in prop.\n  apply (fromempty (negnatgth0n 0 (pr1 prop))).\n  induction n.\n  unfold I_or_O.\n  apply (inr (tpair (fun vi : (boolset × natset)%set => dirprod_pr2 vi > 0 × dirprod_pr2 vi ≤ dirprod_pr1 in_out_example (dirprod_pr1 vi)) (make_dirprod true 1) (make_dirprod (natgthsnn 0) (isreflnatleh 1)))).\n  induction n.\n  apply (inr (tpair (fun vi : (boolset × natset)%set => dirprod_pr2 vi > 0 × dirprod_pr2 vi ≤ dirprod_pr1 in_out_example (dirprod_pr1 vi)) (make_dirprod false 1) (make_dirprod (natgthsnn 0) (isreflnatleh 1)))).\n  apply (fromempty (negnatlehsnn 0 ((natlehandplusrinv 1 0 2) (pr2 prop)))).\n  induction b as [vi prop].\n  induction vi as [v i].\n  induction v.\n  unfold in_out_example in prop.\n  unfold dirprod_pr2 in prop.\n  unfold pr2 in prop.\n  unfold out_example in prop.\n  unfold dirprod_pr1 in prop.\n  unfold pr1 in prop.\n  unfold make_dirprod in prop.\n  induction i.\n  apply (fromempty (negnatgth0n 0 (pr1 prop))).\n  induction i.\n  unfold underlined.\n  apply (inl (tpair (fun n : nat => dirprod (natgth n 0) (natleh n 2)) 2 (make_dirprod (natgthsn0 0) (natlehnsn 1)))).\n  apply (fromempty (negnatlehsnn 0 ((natlehandplusrinv 1 0 1) (pr2 prop)))).\n  unfold in_out_example in prop.\n  unfold dirprod_pr2 in prop.\n  unfold pr2 in prop.\n  unfold out_example in prop.\n  unfold dirprod_pr1 in prop.\n  unfold pr1 in prop.\n  unfold make_dirprod in prop.\n  induction i.\n  apply (fromempty (negnatgth0n 0 (pr1 prop))).\n  induction i.\n  unfold underlined.\n  apply (inl (tpair (fun n : nat => dirprod (natgth n 0) (natleh n 2)) 1 (make_dirprod (natgthsn0 0) (natlehnsn 1)))).\n  apply (fromempty (negnatlehsnn 0 ((natlehandplusrinv 1 0 1) (pr2 prop)))).\nDefined.\n\nPrint i_func_example.\n\nTheorem is_iso_i_example_1 : ∏ out_ : (setcoprod (underlined 2) (I_or_O boolset (dirprod_pr2 in_out_example))), i_func_example_reverse (i_func_example out_) = out_.\n  intros out_.\n  induction out_.\n  induction a as [n prop].\n  induction n.\n  apply (fromempty (negnatgth0n 0 (pr1 prop))).\n  induction n.\n  unfold i_func_example.\n  unfold nat_rect.\n  unfold coprod_rect.\n  unfold i_func_example_reverse.\n  unfold nat_rect.\n  unfold coprod_rect.\n  unfold bool_rect.\n  unfold in_example.\n  unfold out_example.\n  unfold pr1.\n  unfold pr2.\n  unfold dirprod_pr1.\n  unfold dirprod_pr2.\n  auto.\n\n\nDefinition i_boolset : weq (setcoprod (underlined 2) (I_or_O boolset (dirprod_pr2 in_out_boolset))) (setcoprod (underlined 2) (I_or_O boolset (dirprod_pr1 in_out_boolset))).\n  unfold weq.\n  unfold I_or_O.\n\n\n\n\n\n\n\n  Check (fun (n : nat) => (fun (u : vertices_of g) => ((paths n 0) -> empty) -> (path_of_length g n v1 u) -> natlth ((pr1 top_order) v1) ((pr1 top_order) u))).\n  Check nat_rect (fun (n : nat) => (fun (u : vertices_of g) => ((paths n 0) -> empty) -> (path_of_length g n v1 u) -> natlth ((pr1 top_order) v1) ((pr1 top_order) u))).\n  Check nat_rect (fun (n : nat) (u : vertices_of g) => ((paths n 0) -> empty) -> (path_of_length g n v1 u) -> natlth ((pr1 top_order) v1) ((pr1 top_order) u)).\n  Check (fun (n : nat) => ((path n 0) -> empty) -> (total2 (fun (u : vertices_of g) => path_of_length g n v1 u)) -> natlth ((pr1 top_order) v1) ((pr1 top_order) u)).\n  Check (fun (n : nat) => ((paths n 0) -> empty)) -> (total2 (fun (u : vertices_of g) => path_of_length g n v1 u)) -> natlth ((pr1 top_order) v1) ((pr1 top_order) u).\n  Check nat_rect (fun (n : nat) (u : vertices_of g) => ((paths n 0) -> empty) -> (path_of_length g n v1 u) -> natlth ((pr1 top_order) v1) ((pr1 top_order) v2)).\n\n\n\n\n  Check nat_rect (fun (n : nat) => ((paths n 0) -> empty) -> nat_rect (fun (m : nat) (u : vertices_of g) => (path_of_length g m v1 u) -> (pr1 top_order) v1 < (pr1 top_order) u) )\n\n\n\n\n  Check nat_rect.\n  Check nat_rect (fun (n : nat) => ((paths n 0) -> empty) -> (path_of_length g n v1 v2) -> natlth ((pr1 top_order) v1) ((pr1 top_order) v2)) case1\n\n\n\n\n\n\n\n\n\n\n\nLemma case1 (g : graph) (top_order : topoligical_order g) (v1 v2 : vertices_of g) : ((paths 0 0) -> empty) -> (path_of_length g 0 v1 v2) -> natlth ((pr1 top_order) v1) ((pr1 top_order) v2).\nProof.\n  intros prop.\n  apply (fromempty (prop (idpath 0))).\nQed.\n\nCheck nat_rect.\n\nLemma case2 (g : graph) (top_order : topoligical_order g) (v1 v2 : vertices_of g) (n : nat) (Pn : ((paths n 0) -> empty) -> (path_of_length g n v1 v2) -> natlth ((pr1 top_order) v1) ((pr1 top_order) v2)) : ((paths (S n) 0) -> empty) -> (path_of_length g (S n) v1 v2) -> natlth\n\n\n\n\n\n\n  induction n.\n  apply (fromempty (prop (idpath 0))).\n  unfold pr1 in path.\n  induction n.\n  unfold nat_rect in path.\n  rewrite (dirprod_pr1 (pr2 path)).\n  rewrite (dirprod_pr1 (pr2 (dirprod_pr2 (pr2 path)))).\n  rewrite (dirprod_pr2 (pr2 (dirprod_pr2 (pr2 path)))).\n\n   ((pr2 top_order) (pr1 (dirprod_pr2 (pr2 path)))).\n  unfold nat_rect in path.\n\n\n\n\n  g : graph\n  top_order : ∑ enumeration : vertices_of g → nat,\n              ∏ e : edges_of g, enumeration (source_of g e) < enumeration (target_of g e)\n  v1, v2 : vertices_of g\n  n : ∑ m : nat, m = 0 → ∅\n  path : nat_rect (λ _ : nat, vertices_of g → vertices_of g → UU)\n           (λ v1 v2 : vertices_of g, v1 = v2)\n           (λ (_ : nat) (pths_of_m : vertices_of g → vertices_of g → UU)\n            (v1 _ : vertices_of g),\n            ∑ u : vertices_of g,\n            pths_of_m v1 u × (∑ e : edges_of g, u = source_of g e × u = target_of g e))\n           (pr1 n) v1 v2\n  ============================\n  pr1 top_order v1 < pr1 top_order v2\n\n\n\n\n\n\n\n\n\n\nPrint port_graph.\n\nDefinition internal_flow_graph_of {m n : nat} (t : tuple m n) : graph := make_graph (vertices t) (total2_hSet (fun ui : I_or_O (vertices t) (out_func t) => hProp_to_hSet (eqset (coprodtobool ((i_func t) (inr ui))) false))).\n\n\n\n\n\n\n\n\n\nRecord graph (V : UU) := mk_graph {A : UU; s : A -> V; t : A -> V}.\n\nArguments A {_} _.\nArguments s {_} _.\nArguments t {_} _.\n\nDefinition graph_mul {V : UU} := fun (g1 : graph V) (g2 : graph V) => mk_graph V (total2 (fun a1a2 : (dirprod (A g1) (A g2)) => paths ((t g1) (dirprod_pr1 a1a2)) ((s g2) (dirprod_pr2 a1a2)))) (fun a : _ => (s g1) (dirprod_pr1 (pr1 a))) (fun a : _ => (t g2) (dirprod_pr2 (pr1 a))).\n\nDefinition power {V : UU} (g : graph V) : nat -> graph V := nat_rect _ g (fun (n : _) (gn : _) => graph_mul g gn).\n\nDefinition func_union {A B C : UU} (f1 : A -> C) (f2 : B -> C) : (coprod A B) -> C := coprod_rect _  f1 f2.\n\nDefinition graph_union {V : UU} := fun (g1 : graph V) (g2 : graph V) => mk_graph V (coprod (A g1) (A g2)) (func_union (s g1) (s g2)) (func_union (t g1) (t g2)).\n\nDefinition transitive_closure {V : UU} (g : graph V) := g. (* to do: should be union of all natural powers of g *)\n\nDefinition acyclisity {V : UU} (g : graph V) := forall a : (A g), ((s g) a) <> ((t g) a).\n\nRecord port_graph (m n : nat) := mk_port_graph {V : UU; in : V -> nat; out : V -> nat; }\n\n\nDefinition something {S : hSet} {s s' : S} (x x' : paths s s') (prop : isaprop (pr1 (s = s')%set)) : iscontr (paths x x').\nProof.\n  unfold isaprop in prop.\n  unfold isofhlevel in prop.\n  Check prop x x'.\n  apply (prop x x').\nDefined.\n\n\nDefinition something2 {S : hSet} {s s' : S} {x x' : paths s s'} (contr : iscontr (paths x x')) (e e' : paths x x') : paths e e'.\n  unfold iscontr in contr.\n  rewrite (pr2 contr e).\n  rewrite (pr2 contr e').\n  apply (idpath (pr1 contr)).\nDefined.\n\n\n\nTheorem help (S : hSet) (s s' : S) : isaset (paths s s').\nProof.\n  unfold isaset.\n  intros x x'.\n  unfold isaprop.\n  unfold isofhlevel.\n  intros e e'.\n  unfold iscontr.\n  exists (something2 (something x x' (propproperty (eqset s s'))) e e').\n  intros t0.\n  unfold propproperty.\n  unfold eqset.\n  unfold pr2.\n  unfold make_hProp.\n  unfold something.\n  unfold something2.\n  unfold internal_paths_rew_r.\n  Check something x x' (propproperty (eqset s s')).\n  Check (propproperty (eqset s s')).\n\n\n\n  Definition graph_union {V : UU} := fun (g1 : graph V) (g2 : graph V) => mk_graph V (coprod)\n\nDefinition graph (V : UU) {A : UU} := dirprod UU (dirprod UU (dirprod (A -> V) (A -> V))).\nDefinition make_graph (V A : UU) (s t : A -> V) : graph V := make_dirprod V (make_dirprod A (make_dirprod s t)).\n\nDefinition not_set_graph_mul {V : UU} := fun (g1 : graph V) (g2 : graph V) => make_graph V (total2 (fun a1a2 : (dirprod A1 A2) => paths (t1 (dirprod_pr1 a1a2)) (s2 (dirprod_pr2 a1a2)))) (fun x : _ => s1 (dirprod_pr1 (pr1 x))) (fun x : _ => t2 (dirprod_pr2 (pr1 x))) where \"A1\" := (dirprod_pr1 (dirprod_pr2 g1)).\n\nFixpoint power (n : nat) {V A1 A2 : UU} {s1 t1 : A1 -> V} {s2 t2 : A2 -> V} (g : not_set_graph V A1 s1 t1) : not_set_graph V A2 s2 t2 :=\n  match n with\n    | 0 => g\n    | S p => (not_set_graph_mul g (power p g))\n  end.\n\n\nDefinition graph (V A : hSet) (s t : A -> V) := UU.\n\nVariable (V A1 A2 : hSet) (s1 t1 : A1 -> V) (s2 t2 : A2 -> V) (a1a2 : dirprod_hSet A1 A2).\nCheck dirprod_hSet A1 A2.\nCheck paths (t1 (pr1 a1a2)) (s2 (pr2 a1a2)).\nCheck isaset (paths (t1 (pr1 a1a2)) (s2 (pr2 a1a2))).\nCheck forall a1a2 : (dirprod_hSet A1 A2), paths (t1 (pr1 a1a2)) (s2 (pr2 a1a2)).\nCheck total2 (fun a1a2 : (dirprod_hSet A1 A2) => paths (t1 (pr1 a1a2)) (s2 (pr2 a1a2))).\nCheck paths (t1 (pr1 a1a2)) (s2 (pr2 a1a2)).\n\nTheorem h (e e' : paths (t1 (pr1 a1a2)) (s2 (pr2 a1a2))) (x x' : paths e e') : paths x x'.\n  Check setproperty V.\n  Print isaset.\n  Print isaprop.\n\nTheorem help : isaset (paths (t1 (pr1 a1a2)) (s2 (pr2 a1a2))).\n  unfold isaset.\n  intros e e'.\n  unfold isaprop.\n  unfold isofhlevel.\n  intros x x'.\n  unfold iscontr.\n  Check total2_rect.\n  Check tpair.\n  Check tpair (fun cntr : (paths x x') => forall t : _, paths t cntr).\nCheck forall_hSet (fun x : (total2 (fun a1a2 : (dirprod_hSet A1 A2) => paths (t1 (pr1 a1a2)) (s2 (pr2 a1a2)))) => pr1 x).\nCheck pr1.\nCheck pr1 (total2 (fun a1a2 : (dirprod_hSet A1 A2) => paths (t1 (pr1 a1a2)) (s2 (pr2 a1a2)))).\n\n\nDefinition graph_mul (V : hSet) {A1 A2 : hSet} {s1 t1 : A1 -> V} {s2 t2 : A2 -> V} := fun (g1 : graph V A1 s1 t1) (g2 : graph V A2 s2 t2) => graph V\n**)\n", "meta": {"author": "Ilya-Kolomin", "repo": "PortGraphs", "sha": "f396ab67941b6a02d6307bac738c4ee43dfe9659", "save_path": "github-repos/coq/Ilya-Kolomin-PortGraphs", "path": "github-repos/coq/Ilya-Kolomin-PortGraphs/PortGraphs-f396ab67941b6a02d6307bac738c4ee43dfe9659/portGraphs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6822268009110991}}
{"text": "Require  Export Bool.\n\nInductive L : Set :=\n| L_true  | L_false \n| L_disj (l1 l2 : L) | L_conj (l1 l2 : L) | L_impl (l1 l2 : L)\n| L_not (l : L).\n\n\nFixpoint L_value (l : L): bool :=\n match l with\n | L_true => true\n | L_false => false\n | L_disj l1 l2 => L_value l1 || L_value l2\n | L_conj l1 l2 => L_value l1 &&  L_value l2\n | L_impl l1 l2 => implb (L_value l1) (L_value l2)\n | L_not l1 => negb (L_value l1)\n end.\n\n\n(* infix notations *)\n\nDeclare Scope prop_scope.\n\nNotation \"A * B\"  := (L_conj A B) : prop_scope.\n\nNotation \"A + B\"  := (L_disj A B) : prop_scope.\n\nNotation \"A <= B\" := (L_impl A B) : prop_scope.\n\nNotation \"'tt'\" := L_true : prop_scope.\n\nNotation \"'ff'\" := L_false : prop_scope.\n\nNotation \"- A\" := (L_not A) : prop_scope.\n\n\nOpen Scope prop_scope.\n\n(** Tests : \n\nCompute L_value (tt * ff).\n\nCompute L_value (tt * ff + (tt <= ff)).\n\nCompute L_value (- (tt * ff + (tt <= ff))).\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/ch6_inductive_data/SRC/propositional.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6822267967406774}}
{"text": "Require Import Coq.Lists.List Coq.Classes.EquivDec Lia. Import ListNotations.\nRequire Import SyDPaCC.Core.Bmf  SyDPaCC.Support.List.\nSet Implicit Arguments.\nGeneralizable All Variables.\n\n(* ---------------------------------------------------- *)\n\n(** * Count *)\n\nSection Count.\n\n  Variable A : Type.\n  Variable predicate : { pred: A -> bool & { a : A | pred a = true} }.\n  Definition p : A->bool := projT1 predicate.\n \n  (** ** Specification of the problem *)\n  \n  Definition count_spec (l:list A) : nat :=  \n    length (filter p l).\n\n  (** ** [count_spec] is both leftwards and rightwards *)\n  \n  Definition opl (a:A)(count:nat) : nat :=\n    count + (if (p a) then 1 else 0). \n  \n  Instance count_leftwards : Leftwards count_spec opl 0.\n  Proof.\n    constructor; induction l as [ | x xs IH ]; simpl.\n    - trivial.\n    - rewrite <- IH; clear IH; unfold opl, count_spec; simpl.\n      destruct(p x); simpl; lia.\n  Qed.\n\n  Definition opr (count:nat)(a:A) : nat :=\n    count + (if (p a) then 1 else 0). \n  \n  Instance count_rightwards: Rightwards count_spec opr 0.\n  Proof.\n    constructor; induction l as [ | x xs IH ] using rev_ind; simpl.\n    - trivial.\n    - unfold count_spec in *; simpl.\n      rewrite fold_left_app, filter_app; simpl.\n      autorewrite with length. unfold opr at 1.\n      destruct(p x); auto.\n  Qed.\n\n  (** ** [count_spec] has a weak right inverse if its predicate argument is\n      true for at least one element *)\n\n  Definition default : A := proj1_sig (projT2 predicate).\n  Lemma default_prop : p default = true.\n    unfold p, default; destruct predicate as [ p [ a Ha ]]; simpl;  auto.\n  Qed.\n\n  Definition count_inv (n:nat) : list A :=\n    map(fun x=>default) (seq 0 n).\n\n  Lemma length_filter_count_inv:\n    forall n, length(filter p (count_inv n)) = n.\n  Proof.\n    intro; unfold count_inv.\n    rewrite filter_true\n      by (intros a Ha; rewrite in_map_iff in Ha; destruct Ha as [ y [ Heq _ ]];\n          rewrite <- Heq; apply default_prop).\n    now autorewrite with length.\n  Qed.\n\n  Hint Rewrite length_filter_count_inv : length.\n  \n  Instance count_right_inverse :\n    Right_inverse count_spec count_inv.\n  Proof.\n    constructor; induction l as [|x xs IH].\n    - trivial.\n    - unfold count_spec; now autorewrite with length.\n  Qed.\n\n  (** ** [count_spec] is an homomorphism *)\n  Global Instance count:\n    Homomorphic count_spec\n                (fun l r=>count_spec(count_inv l ++ count_inv r)).\n  typeclasses eauto.\n  Qed.\n  \n  (** ** Optimization of this homomophism *)\n  \n  Global Instance opt_op : Optimised_op count_spec.\n  Proof.\n    constructor; unfold count_spec; eexists.\n    intros a b. rewrite filter_app;  autorewrite with length.\n    reflexivity.\n  Defined.\n\n  Global Instance opt_f : Optimised_f count_spec.\n  Proof.\n    constructor; unfold count_spec; eexists; intro a; simpl.\n    replace(length (if p a then [a] else [])) with (if p a then 1 else 0).\n    reflexivity.\n    destruct(p a);auto.\n  Defined.\n\nEnd Count.\n", "meta": {"author": "SyDPaCC", "repo": "sydpacc", "sha": "640f0f74f21524ee203b192255ecfa9e456fb7d1", "save_path": "github-repos/coq/SyDPaCC-sydpacc", "path": "github-repos/coq/SyDPaCC-sydpacc/sydpacc-640f0f74f21524ee203b192255ecfa9e456fb7d1/Applications/Count.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.6821518037868309}}
{"text": "Require Import Bool.\nRequire Import List.\nRequire Import Arith.\n\nRequire Import typed.\nRequire Import Utils.nat.\n\n\nLemma blt_nat_test1: blt_nat 0 0 = false.\nProof. reflexivity. Qed.\n\nLemma blt_nat_test2: blt_nat 1 0 = false.\nProof. reflexivity. Qed.\n\nLemma blt_nat_test3: blt_nat 0 1 = true.\nProof. reflexivity. Qed.\n\nLemma blt_nat_test4: blt_nat 1 1 = false.\nProof. reflexivity. Qed.\n\nLemma typeDenote_test1: typeDenote Nat = nat.\nProof. reflexivity. Qed.\n\nLemma typeDenote_test2: typeDenote Bool = bool.\nProof. reflexivity. Qed.\n\nLemma tbinopDenote_test1: tbinopDenote TPlus = plus.\nProof. reflexivity. Qed.\n\nLemma tbinopDenote_test2: tbinopDenote TTimes = mult.\nProof. reflexivity. Qed.\n\nLemma tbinopDenote_test3: tbinopDenote (TEq Nat) = beq_nat.\nProof. reflexivity. Qed.\n\nLemma tbinopDenote_test4: tbinopDenote (TEq Bool) = eqb.\nProof. reflexivity. Qed.\n\nLemma tbinopDenote_test5: tbinopDenote TLt = blt_nat.\nProof. reflexivity. Qed.\n\nLemma texpDenote_test1: texpDenote (TNConst 42) = 42.\nProof. reflexivity. Qed.\n\nLemma texpDenote_test2: texpDenote (TBConst true) = true.\nProof. reflexivity. Qed.\n\nLemma texpDenote_test3: texpDenote (TBConst false) = false.\nProof. reflexivity. Qed.\n\nLemma texpDenote_test4: texpDenote \n    ( TBinop TTimes \n        (TBinop TPlus (TNConst 2)(TNConst 3)) \n        (TNConst 7)) = 35.\nProof. reflexivity. Qed.\n\nLemma texpDenote_test5: texpDenote \n    ( TBinop (TEq Nat) \n        (TBinop TPlus (TNConst 4) (TNConst 3))\n        (TNConst 7)) = true.\nProof. reflexivity. Qed.\n\nLemma texpDenote_test6: texpDenote \n    ( TBinop (TEq Bool) \n        (TBinop (TEq Nat) (TNConst 2) (TNConst 3))\n        (TBConst false)) = true.\nProof. reflexivity. Qed.\n\nLemma texpDenote_test7: texpDenote \n    ( TBinop TLt\n        (TBinop TPlus (TNConst 2) (TNConst 3))\n        (TNConst 7)) = true.\nProof. reflexivity. Qed.\n\n\nDefinition x : unit := tt.\n\n(*\nPrint tcompile.\n*)\n\nLemma tcompile_test1: \n    tprogDenote (tcompile (TNConst 42) nil) tt = (42,tt). \nProof. reflexivity. Qed.\n\nLemma tcompile_test2: \n    tprogDenote (tcompile (TBConst true) nil) tt = (true,tt). \nProof. reflexivity. Qed.\n \nLemma tcompile_test3: \n    tprogDenote (tcompile (TBConst false) nil) tt = (false,tt). \nProof. reflexivity. Qed.\n\nLemma tcompile_test4:\n    tprogDenote \n        (tcompile \n            (TBinop TTimes \n                (TBinop TPlus (TNConst 2) (TNConst 3))\n                (TNConst 7)) nil) tt = (35,tt).\nProof. reflexivity. Qed.\n\nLemma tcompile_test5:\n    tprogDenote\n        (tcompile\n            (TBinop (TEq Nat)\n                (TBinop TPlus (TNConst 2) (TNConst 3))\n                (TNConst 7)) nil) tt = (false, tt).\nProof. reflexivity. Qed.\n\nLemma tcompile_test6:\n    tprogDenote\n        (tcompile\n            (TBinop (TEq Nat)\n                (TBinop TPlus (TNConst 2) (TNConst 3))\n                (TNConst 5)) nil) tt = (true, tt).\nProof. reflexivity. Qed.\n\n\nLemma tcompile_test7:\n    tprogDenote\n        (tcompile\n            (TBinop (TEq Bool)\n                (TBinop (TEq Nat) (TNConst 2) (TNConst 2))\n                (TBConst true)) nil) tt = (true, tt).\nProof. reflexivity. Qed.\n\nLemma tcompile_test8:\n    tprogDenote\n        (tcompile\n            (TBinop (TEq Bool)\n                (TBinop (TEq Nat) (TNConst 3) (TNConst 2))\n                (TBConst true)) nil) tt = (false, tt).\nProof. reflexivity. Qed.\n\n\nLemma tcompile_test9:\n    tprogDenote\n        (tcompile\n            (TBinop TLt\n                (TBinop TPlus (TNConst 2) (TNConst 3))\n                (TNConst 5)) nil) tt = (false, tt).\nProof. reflexivity. Qed.\n\nLemma tcompile_test10:\n    tprogDenote\n        (tcompile\n            (TBinop TLt\n                (TBinop TPlus (TNConst 2) (TNConst 3))\n                (TNConst 6)) nil) tt = (true, tt).\nProof. reflexivity. Qed.\n\n(*\nExtraction Language Haskell.\nExtraction tcompile.\n*)\n\n\n\n\n\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/cpdt/Test/typed_t.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504226, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.6821517947575617}}
{"text": "Require Import Omega List prelim.\nImport ListNotations.\n\n(* * H10 *)\nInductive deq :=\n| Con (x c: nat)\n| Add (x y z: nat)\n| Mul (x y z: nat).\n\n\nNotation \"x =ₑ c\" := (Con x c) (at level 66).\nNotation \"x +ₑ y =ₑ z\" := (Add x y z) (at level 66, y at next level).\nNotation \"x *ₑ y =ₑ z\" := (Mul x y z) (at level 66, y at next level).\nReserved Notation \"sigma ⊢ₑ e\" (at level 60, e at level 99).\n\nInductive sol (sigma: nat -> nat) : deq -> Prop :=\n| solC x c: sigma x = c -> sigma ⊢ₑ x =ₑ c\n| solA x y z: sigma x + sigma y = sigma z -> sigma ⊢ₑ x +ₑ y =ₑ z\n| solM x y z: sigma x * sigma y = sigma z -> sigma ⊢ₑ x *ₑ y =ₑ z\nwhere \"sigma ⊢ₑ e\" := (sol sigma e).\n\nDefinition Sol (sigma: nat -> nat) (E: list deq) := forall e, e ∈ E -> sigma ⊢ₑ e.\nNotation \"sigma ⊢⁺ₑ E\" := (Sol sigma E) (at level 60, E at level 99).\nDefinition H10 (E: list deq) := exists sigma, sigma ⊢⁺ₑ E.\n\n\n\nDefinition vars__de (e: deq) :=\n  match e with\n  | x =ₑ c => [x]\n  | x +ₑ y =ₑ z => [x; y; z]\n  | x *ₑ y =ₑ z => [x; y; z]\n  end.\n\nDefinition Vars__de E :=\n  nodup Nat.eq_dec (flat_map vars__de E).\n\n\n\nLemma Vars__de_in e E:\n  e ∈ E -> forall y, y ∈ vars__de e -> y ∈ Vars__de E.\nProof.\n  unfold Vars__de; intros; eapply nodup_In, in_flat_map.\n  exists e. intuition. \nQed.                               \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "uds-psl", "repo": "higher-order-unification-undecidability", "sha": "c1772adedca22d74f8c8d94b8610c31d22d46c7a", "save_path": "github-repos/coq/uds-psl-higher-order-unification-undecidability", "path": "github-repos/coq/uds-psl-higher-order-unification-undecidability/higher-order-unification-undecidability-c1772adedca22d74f8c8d94b8610c31d22d46c7a/coq/second_order/diophantine_equations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6820625896204854}}
{"text": "Require Import List.\nExport ListNotations.\nRequire Export ZArith.\nRequire Import Init.Datatypes.\n\nInductive IPE2: Type :=\n | zero_pe2    \n | one_pe2.\n\nInductive PE2 : Type := \n | i_pe2      : IPE2 -> PE2\n | u_pe2      : PE2.\n\nDefinition P2 : Type := list PE2.\n \nFunction beq_IPE2 (i i' : IPE2) : bool := \n  match i, i' with\n    | zero_pe2, zero_pe2 => true\n    | one_pe2, one_pe2 => true\n    | _, _ => false\n  end.\n\nFunction beq_PE2 (p p' : PE2) : bool :=\n  match p, p' with\n    | i_pe2 x, i_pe2 y => beq_IPE2 x y\n    | u_pe2, u_pe2 => true\n    | _, _ => false\n  end.\n \nFunction beq_path2 (p q : P2) : bool := \n  match p, q with\n    | [], [] => true\n    | x :: p', y :: q' => andb (beq_PE2 x y) (beq_path2 p' q')\n    | _  , _ => false\n  end.\n", "meta": {"author": "briangmilnes", "repo": "CycloneCoqSemantics", "sha": "190c0fc57d5aebfde244efb06a119f108de7a150", "save_path": "github-repos/coq/briangmilnes-CycloneCoqSemantics", "path": "github-repos/coq/briangmilnes-CycloneCoqSemantics/CycloneCoqSemantics-190c0fc57d5aebfde244efb06a119f108de7a150/3/modules/InversionExperimentWorking.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6820408197383999}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (z : natural) (x : natural)\n  : natural := lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj275_coqofml_Mg0H39.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6820272203768034}}
{"text": "(* These exercises require inductive proofs. *)\n(* Now that you have some experience with Coq, \n   you can use 'auto' tactic to avoid solving simple subgoals manually. *)\n\nRequire Import b1.\nRequire Import b2.\nRequire Import List.\nImport ListNotations. \n\nSection NatDict'Proofs.\n  Context {V: Type}.\n\n Lemma n_eq_or_neq (n n': nat): (n=n')\\/(n<>n').\n  Proof.\n  pattern n, n'.\n  apply (nat_double_ind).\n  {\n    intros n0.\n    destruct n0.\n    auto.\n    auto.\n  }\n  {\n    intros n0.\n    auto.\n  }\n  {\n    intros n0 m.\n    intros h.\n    destruct h.\n    auto.\n    auto.\n  }\nQed.\n\n\nLemma noeq_impl_nat_eq_false (n1:nat) (n2:nat) : n1 <> n2 -> nat_eq n1 n2 = false.\n    Proof.\n      intros.\n      remember H as H'.\n      remember (nat_eq_neg_spec n1 n2) as nat_eq_neg.\n      unfold iff in nat_eq_neg.\n      destruct nat_eq_neg as (nat_eq_neg_l & nat_eq_neg_r).\n      (*Reset Heqn1.*)\n      auto.\n    Qed.\n    \n\n  (* Prove that 'remove' operation actually removes a key. *)\n  (* The list inside nat_dict_list consists of pairs.\n     To extract components of such list's head, \n     either perform pattern matching in 'induction' tactics\n     or directly 'destruct' the element of nat*V type. *)\n  Lemma removed_not_contained (d: @nat_dict_list V) (n: nat):\n    contains'' (remove'' d n) n = false.\n  Proof.\n  induction d.\n  auto.\n\n(*  unfold contains''.\n  unfold get''.*)\n  destruct a.\n  destruct (n_eq_or_neq n n0).\n  {\n    apply eq_implies_nat_eq in H.\n    simpl.\n    rewrite H.\n    auto.\n  }\n  apply noeq_impl_nat_eq_false in H.\n  simpl.\n  rewrite H.\n  simpl.\n  rewrite H.\n  \n(*rewrite Heqaaa.\n  pattern (remove'' d n), n in Heqaaa.\n   \n  pattern (remove'' d n), n.\n  fold (@contains'' V).\n  fold ((contains'' (remove'' d n) n)).\n  inversion (get'' (remove'' d n) n).\n  \n  fold (@contains'' V).\n  \n  unfold contains'' in IHd.\n  \n  fold (@contains'' V) n (remove'' d n).\n  IHd.\n  unfold contains'' in IHd.\n  red in IHd.\n  rewrite IHd.\n  destruct IHd.\n  auto.\n*)\n  \n\n  \n  \n  \nAdmitted.\n\n  (* Define a mapping function similar to one defined for regular lists.\n     It should replace values stored in dict but keep them under the same keys. *)\n  Fixpoint map'' {W: Type} (f: V -> W) (d: @nat_dict_list V): @nat_dict_list W :=\n      (* place your code here *)\n      match d with\n      | nil => nil\n      | cons (k, v) t => cons (k, f v) (map'' f t)\n      end.\n\n      \n  (* Prove that a value stored in a mapped dict \n     requires a corresponding value stored in an original dict. *)\n  Lemma dict_map_get {W: Type} (m: V -> W) (d: @nat_dict_list V):\n    forall n w,\n      (get'' (map'' m d) n = Some w) <->\n      (exists v, get'' d n = Some v /\\ m v = w).\n  Proof.\n  unfold iff.\n  split.\n  {\n    intros.\n    induction d as [| a l ih].\n    {unfold get''.\n      simpl in H.\n      inversion H.\n    }\n    destruct a.\n    destruct (n_eq_or_neq n n0).\n    {\n      rewrite H0.\n      simpl.\n      exists v.\n      (*eapply ex_intro.*)\n      rewrite nat_eq_refl.\n      split.\n      {reflexivity. }\n      rewrite H0 in H.\n      simpl in H.\n      rewrite nat_eq_refl in H.\n      inversion H.\n      reflexivity.\n    }\n    simpl in H.\n    remember H0 as H0'.\n    remember (nat_eq_neg_spec n n0) as nat_eq_neg.\n    unfold iff in nat_eq_neg.\n    destruct nat_eq_neg as (nat_eq_neg_l & nat_eq_neg_r).\n    (*Reset Heqn1.*)\n    remember (nat_eq_neg_r H0') as H1.\n    rewrite H1 in H.\n    apply ih in H.\n\n    unfold get''.\n    simpl.\n    rewrite H1.\n    auto.\n    }\n\n    intros.\n    destruct H as (v & H).\n    destruct H as (H1 & H2).\n    induction d as [| a l ih].\n    {\n      simpl in H1.\n      inversion H1.\n    }\n    destruct a.\n    destruct (n_eq_or_neq n n0).\n    {\n    apply eq_implies_nat_eq in H.\n    simpl in H1.\n    rewrite H in H1.\n    simpl.\n    rewrite H.\n    inversion H1.\n    destruct H2.\n    reflexivity.\n    }\n    apply noeq_impl_nat_eq_false in H.\n    simpl in H1.\n    rewrite H in H1.\n    simpl.\n    rewrite H.\n    auto.\nQed.\n    \n    \n\n\n\n\n  (* Implement a filtering function. \n     The result should contain only those keys whose values satisfy the predicate;\n     in this case they remain unchanged. *)\n  Fixpoint filter'' {U: Type} (f: U -> bool) (d: @nat_dict_list U): @nat_dict_list U :=\n      (* place your code here *)\n      match d with\n      | nil => nil\n      | cons (k, v) t => if (f v) then cons (k, v) (filter'' f t) else (filter'' f t)\n      end.\n\n  \n\n(*...*)\n\n  (* Prove that the result of filtering is actually filtered *)\n  Lemma filter_elem (f: V -> bool) (d: @nat_dict_list V):\n    forall n,\n      (contains'' (filter'' f d) n = true) <->\n      (exists v, get'' d n = Some v /\\ f v = true).\n  Proof.\n  intros.\n  unfold iff.\n  split.\n  {\n    induction d.\n    {\n      intros.\n      simpl in H.\n      inversion H.\n    }\n    destruct a.\n    destruct (n_eq_or_neq n n0).\n    {\n       apply (eq_implies_nat_eq n n0) in H.\n       intros.\n       exists v.\n       unfold get''.\n       simpl.\n       rewrite H.\n       split.\n       reflexivity.\n       unfold contains'' in H0.\n       simpl in H0.\n       remember (bool_true_or_false (f v)).\n       destruct o.\n       apply e.\n       rewrite e in H0.\n       apply IHd in H0.\n       desrtuct \n       red in  H0.\n       \n\n\n  \nAdmitted.\n\n\n  (* You (most probably) implemented list-based dictionary in a way\n     that doesn't distinguish, say, [(1, 2), (3, 4)] and [(3, 4), (1, 2)] dicts. *)\n  (* That is, the results of 'insert', 'contains' and other interface operations\n     should be the same for them. *)\n  (* Such lists are not-equal, though, \n     since the only list equal to [(1, 2), (3, 4)] is exactly [(1, 2), (3, 4)]. *)\n  (* We can formalize the specific notion of equivalence for dictionaries \n     to prove their more complicated properties. *)\n  (* Note that this equ ivalence only deals with dict interface \n     and not the particular implementation. *)\n  Definition sim_dicts (d1 d2: @nat_dict_list V) :=\n    forall n, get'' d1 n = get'' d2 n.\n\n(*...*)\n\n  (* Prove that an insertion makes a preceding removal pointless. \n     To ease the proof, you may want to prove separately that:\n     - sim_dicts relation is transitive\n     - an insertion of the same key-value pair preserves sim_dicts\n     - a double insertion of the same key-value pair\n       is similar (in terms of sim_dicts) to a single insertion\n     - insertions of separate keys commute\n       (that is, their results are related by sim_dicts).\n     Also, it can be easier to operate on level of a higher level of 'insert's \n     instead of a lower level of list 'cons'es. \n     To replace 'cons' with 'insert', use 'fold' tactic. \n*)\n  Lemma insert_remove_simpl (d: @nat_dict_list V) (n: nat) (v: V):\n    sim_dicts (insert'' (remove'' d n) n v) (insert'' d n v).\n  Proof.\nAdmitted.\n  \nEnd NatDict'Proofs.   \n", "meta": {"author": "Dmitry-Ivashkov", "repo": "coq-intro-sirius-2021", "sha": "1930c88e8fef6c2ff53987649d67a058a28362d8", "save_path": "github-repos/coq/Dmitry-Ivashkov-coq-intro-sirius-2021", "path": "github-repos/coq/Dmitry-Ivashkov-coq-intro-sirius-2021/coq-intro-sirius-2021-1930c88e8fef6c2ff53987649d67a058a28362d8/src/b3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.6819239728414657}}
{"text": "(* Concrete Semantics with Isabelle/HOLに出てくるプログラムをCoqで実装 *)\n\nSection Chapter3.\n  (* 主にIMPという言語についてのお話 *)\n  (* 正直 い つ も の *)\n  Require Import String.\n  Open Scope string.\n  \n  Definition vname := string.\n  Inductive aexp := \n    | N : forall n: nat, aexp (* 原文はint *)\n    | V : forall s: vname, aexp (* 変数 *)\n    | Plus : forall l r: aexp, aexp. (* 加算 *)\n\n  Definition val := nat.\n  Definition state := vname -> val. (* コンテキスト *)\n\n  Fixpoint aval (e: aexp) (s: state) : val :=\n    match e with\n    | N n => n\n    | V x => s x\n    | Plus l r => aval l s + aval r s\n    end.\n\n  Compute aval (Plus (N 3) (V \"x\")) (fun _ => 5).\n\n  (* 定数同士のPlusのときに簡単にする最適化 *)\n  Fixpoint asimp_const (e: aexp) : aexp :=\n    match e with\n    | N n => N n\n    | V x => V x\n    | Plus l r =>\n      match (asimp_const l, asimp_const r) with\n      | (N n0, N n1) => N (n0 + n1)\n      | (e0, e1) => Plus e0 e1\n      end\n    end.\n\n  Compute asimp_const (Plus (V \"x\") (Plus (N 3) (N 1))).\n\n  (* asimp_constがaexpの意味を変えないことの証明 *)\n  Lemma aval_asimp_const : forall (e: aexp) (s: state), aval (asimp_const e) s = aval e s.\n  Proof.\n    induction e; intros; simpl.\n    - reflexivity.\n    - reflexivity.\n    - specialize (IHe1 s); specialize (IHe2 s).\n      rewrite <- IHe1; rewrite <- IHe2.\n      destruct (asimp_const e1); destruct (asimp_const e2); simpl; try reflexivity.\n  Qed.      \n\n  (* asimp_constをより最適化 *)\n  Definition plus (l r: aexp) : aexp :=\n    match (l, r) with\n    | (N n0, N n1) => N (n0 + n1)\n    | (N n, e) => if Nat.eqb n 0 then e else Plus (N n) e\n    | (e, N n) => if Nat.eqb n 0 then e else Plus e (N n)\n    | (e0, e1) => Plus e0 e1\n    end.\n\n  (* aval_asimpと同じ感じ *)\n  Lemma aval_plus : \n    forall (e0 e1: aexp) (s: state), aval (plus e0 e1) s = aval e0 s + aval e1 s.\n  Proof.\n    SearchPattern (_ = _ + 0).\n    induction e0; induction e1; intros; simpl; try reflexivity;\n    destruct n; simpl; try apply plus_n_O; try reflexivity.\n  Qed.\n\n  (* Plusをplusに置き換え *)\n  Fixpoint asimp (e: aexp) : aexp :=\n    match e with\n    | N n => N n\n    | V x => V x\n    | Plus e0 e1 => plus (asimp e0) (asimp e1)\n    end.\n\n  (* avalのあれ *)\n  Lemma aval_asimp : forall (e: aexp) (s: state), aval (asimp e) s = aval e s.\n  Proof.\n    induction e; intros; simpl; try reflexivity.\n    specialize (IHe1 s); specialize (IHe2 s).\n    rewrite <- IHe1; rewrite <- IHe2.\n    apply aval_plus.\n  Qed.\n\n  (* Ex 3.1 *)\n  Definition optimal (e: aexp) : Prop :=\n    match e with\n    | Plus e0 e1 =>\n      match (e0, e1) with\n      | (N _, N _) => False\n      | _ => True\n      end\n    | _ => True\n    end.\n\n  Lemma asimp_const_optimal: forall (e: aexp), optimal (asimp_const e).\n  Proof.\n    induction e; intros; simpl; try apply I.\n    destruct (asimp_const e1); destruct (asimp_const e2); simpl; apply I.\n  Qed.\n\n  (* Ex 3.2 *)\n  Fixpoint full_asimp (e: aexp) : aexp :=\n    match e with\n    | N n => N n\n    | V x => V x\n    | Plus e0 e1 => \n      match (full_asimp e0, full_asimp e1) with\n      | (N n0, N n1) => N (n0 + n1)\n      | (N n, Plus n0 n1) => \n        match (n0, n1) with\n        | (N n', _) => Plus (N (n + n')) n1\n        | (_, N n') => Plus n0 (N (n + n'))\n        | (_, _) => Plus e0 e1\n        end\n      | (Plus n0 n1, N n) =>\n        match (n0, n1) with\n        | (N n', _) => Plus (N (n + n')) n1\n        | (_, N n') => Plus n0 (N (n + n'))\n        | (_, _) => Plus e0 e1\n        end\n      | (Plus n0 n1, Plus n2 n3) =>\n        match (n0, n1, n2, n3) with\n        | (N n0', _, N n2', _) => Plus (N (n0' + n2')) (Plus n1 n3)\n        | (N n0', _, _, N n3') => Plus (N (n0' + n3')) (Plus n1 n2)\n        | (_, N n1', N n2', _) => Plus (N (n1' + n2')) (Plus n0 n3)\n        | (_, N n1', _, N n3') => Plus (N (n1' + n3')) (Plus n0 n2)\n        | _ => Plus e0 e1\n        end\n      | (_, _) => Plus e0 e1 (* どっちかにVがあるとどうしようもない *)\n      end\n    end.\n\n  Compute full_asimp (Plus (N 1) (Plus (V \"x\") (N 2))).\n\n  Require Import Lia.\n  \n  Fact add_shuffle_4 : forall a b c d: nat, a + b + (c + d) = c + (a + b + d).\n  Proof.\n    intros; lia.\n  Qed.    \n\n  Create HintDb chapter3.\n  Hint Resolve add_shuffle_4 : chapter3.\n  SearchPattern(_ + (_ + _) = _ + (_ + _)).\n\n  Lemma aval_full_asimp : \n    forall (e: aexp) (s: state), aval (full_asimp e) s = aval e s.\n  Proof.\n    induction e; intros; simpl; try reflexivity.\n    specialize (IHe1 s); specialize (IHe2 s).\n    rewrite <- IHe1; rewrite <- IHe2.\n    destruct (full_asimp e1); destruct (full_asimp e2); simpl; try reflexivity;\n      try rewrite <- IHe1; try rewrite <- IHe2; simpl; try reflexivity.\n    destruct a1; destruct a2; simpl; intuition.\n    Focus 2.\n  Admitted. (* とてつもなくめんどくさそうなので保留 *)\n\n  Compute (string_dec \"hoge\" \"hoge\").\n\n  Fixpoint subst' (s: vname) (e0 e1: aexp) : aexp :=\n    match e1 with\n    | N n => N n\n    | V x => \n      match string_dec s x with\n      | left _ => e0\n      | right _ => (V x)\n      end\n    | Plus n0 n1 => Plus (subst' s e0 n0) (subst' s e0 n1)\n    end.\n\n  Compute subst' \"x\" (N 3) (Plus (V \"x\") (V \"y\")).\n\n  Lemma subst'_lemma: forall (e0 e1 elm: aexp) (x: vname) (s: state), \n      aval e0 s = aval e1 s -> aval (subst' x elm e0) s = aval (subst' x elm e1) s.\n  Proof.\n    intros.\n    induction e0; induction e1.\n    simpl in *. assumption.\n    simpl. \n    repeat match goal with\n    | [ |- context[if ?P then _ else _]] => destruct P; simpl; try assumption\n    end.\n  Admitted.\n\n  (* 証明ムズイ *)\n\n  (* 3.2 *)\n\n  Require Import Bool.\n\n  Inductive bexp := \n  | Bc : forall b: bool, bexp\n  | Not : forall b: bexp, bexp\n  | And : forall b0 b1: bexp, bexp\n  | Less : forall a0 a1: aexp, bexp.\n\n  Fixpoint bval (b: bexp) (s: state) : bool :=\n    match b with\n    | Bc v => v\n    | Not b' => negb (bval b' s)\n    | And b0 b1 => andb (bval b0 s) (bval b1 s)\n    | Less a0 a1 => Nat.leb (aval a0 s) (aval a1 s)\n    end.\n\n  Definition not (b: bexp) : bexp :=\n    match b with\n    | Bc true => Bc false\n    | Bc false => Bc true\n    | _ => Not b\n    end.\n\n  Definition and (b0 b1: bexp) : bexp :=\n    match (b0, b1) with\n    | (Bc true, b1') => b1'\n    | (b0', Bc true) => b0'\n    | (Bc false, _) => Bc false\n    | (_, Bc false) => Bc false\n    | (_, _) => And b0 b1\n    end.\n\n  Definition less (a0 a1: aexp) : bexp :=\n    match (a0, a1) with\n    | (N n0, N n1) => Bc (Nat.leb n0 n1)\n    | (_, _) => Less a0 a1\n    end.\n\n  Fixpoint bsimp (b: bexp) : bexp :=\n    match b with\n    | Bc v => Bc v\n    | Not b' => not (bsimp b')\n    | And b0 b1 => and (bsimp b0) (bsimp b1)\n    | Less a0 a1 => less (asimp a0) (asimp a1)\n    end.\n\n  (* 演習は省略 *)\n  \n  (* 3.3 *)\n  Inductive instr :=\n  | LOADI : forall (n: val), instr\n  | LOAD  : forall (s: vname), instr\n  | ADD : instr.\n\n  Require Import List.\n  \n  Definition stack := list nat.\n\n  Definition hd2 (l: list nat) := List.hd 0 (List.tl l).\n\n  Definition tl2 (l: list nat) := List.tl (List.tl l).\n\n  Definition exec1 (i: instr) (s: state) (stk: stack) : stack :=\n    match i with\n    | LOADI n => n :: stk\n    | LOAD  x => (s x) :: stk\n    | Add => (hd2 stk + hd 0 stk) :: tl2 stk\n    end.\n\n  (* headはデフォルト引数が必要だったらしい *)", "meta": {"author": "awazoooo", "repo": "concrete-semantics-coq", "sha": "c76fe40e672288050078eaea79f655d86943ea64", "save_path": "github-repos/coq/awazoooo-concrete-semantics-coq", "path": "github-repos/coq/awazoooo-concrete-semantics-coq/concrete-semantics-coq-c76fe40e672288050078eaea79f655d86943ea64/concrete-semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.6819239723474035}}
{"text": "Require Export Basics_J.\n\nModule NatList.\n  (* Inductive natprod : Type := *)\n  (*   pair : nat -> nat -> natprod. *)\n\n  (* Definition fst (p : natprod) : nat := *)\n  (*   match p with *)\n  (*   | pair x y => x *)\n  (*   end. *)\n\n  (* Definition snd (p : natprod) : nat := *)\n  (*   match p with *)\n  (*   | pair x y => y *)\n  (*   end. *)\n\n  (* Notation \"( x , y )\" := (pair x y). *)\n\n  (* Eval simpl in (fst (3, 4)). *)\n\n  (* Definition fst' (p : natprod) : nat := *)\n  (*   match p with *)\n  (*   | (x, y) => x *)\n  (*   end. *)\n\n  (* Definition snd' (p : natprod) : nat := *)\n  (*   match p with *)\n  (*   | (x, y) => y *)\n  (*   end. *)\n\n  (* Definition swap_pair (p : natprod) : natprod := *)\n  (*   match p with *)\n  (*   | (x, y) => (y, x) *)\n  (*   end. *)\n\n  (* Theorem surjective_pairing' : forall (n m : nat), *)\n  (*     (n, m) = (fst (n, m), snd (n, m)). *)\n  (* Proof. *)\n  (*   reflexivity. *)\n  (* Qed. *)\n\n  (* Theorem subjective_pairing : forall (p : natprod), *)\n  (*     p = (fst p, snd p). *)\n  (* Proof. *)\n  (*   intros. destruct p as (n, m). simpl. reflexivity. *)\n  (* Qed. *)\n\n  (* Theorem snd_fst_is_swap : forall (p : natprod), *)\n  (*     (snd p, fst p) = swap_pair p. *)\n  (* Proof. *)\n  (*   intros p. destruct p as (n, m). simpl. reflexivity. *)\n  (* Qed. *)\n\n  Inductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\n  Notation \"x :: l\" := (cons x l) (at level 60, right associativity).\n  Notation \"[]\" := nil.\n  Notation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n\n  Fixpoint repeat (n count : nat) : natlist :=\n    match count with\n    | O => nil\n    | S count' => n :: (repeat n count')\n    end.\n\n  Fixpoint length (l : natlist) : nat :=\n    match l with\n    | nil => O\n    | h :: t => S (length t)\n    end.\n\n  Fixpoint app (l1 l2 : natlist) : natlist :=\n    match l1 with\n    | nil => l2\n    | h :: t => h :: (app t l2)\n    end.\n\n  Notation \"x ++ y\" := (app x y) (right associativity, at level 60).\n\n  Example test_app1 : [1, 2, 3] ++ [4, 5] = [1, 2, 3, 4, 5].\n  Proof. reflexivity. Qed.\n  Example test_app2 : nil ++ [4, 5] = [4, 5].\n  Proof. reflexivity. Qed.\n  Example test_app3 : [1, 2, 3] ++ nil = [1, 2, 3].\n  Proof. reflexivity. Qed.\n\n  Definition hd (default : nat) (l : natlist) : nat :=\n    match l with\n    | nil => default\n    | h :: t => h\n    end.\n\n  Definition tail (l : natlist) : natlist :=\n    match l with\n    | nil => nil\n    | h :: t => t\n    end.\n\n  Example test_hd1:             hd 0 [1,2,3] = 1.\n  Proof. reflexivity.  Qed.\n  Example test_hd2:             hd 0 [] = 0.\n  Proof. reflexivity.  Qed.\n  Example test_tail:            tail [1,2,3] = [2,3].\n  Proof. reflexivity.  Qed.\n\n  Fixpoint nonzeros (l:natlist) : natlist :=\n    match l with\n    | nil => nil\n    | h :: t => match h with\n                | O => nonzeros t\n                | _ => cons h (nonzeros t)\n                end\n    end.\n\n  Example test_nonzeros:            nonzeros [0,1,0,2,3,0,0] = [1,2,3].\n  Proof. reflexivity. Qed.\n\n  Fixpoint oddmembers (l:natlist) : natlist :=\n    match l with\n    | nil => nil\n    | h :: t => match oddb h with\n                | true => cons h (oddmembers t)\n                | false => oddmembers t\n                end\n    end.\n\n  Example test_oddmembers:            oddmembers [0,1,0,2,3,0,0] = [1,3].\n  Proof. reflexivity. Qed.\n\n  Fixpoint countoddmembers (l:natlist) : nat :=\n    match l with\n    | nil => O\n    | h :: t => match oddb h with\n                | true => S (countoddmembers t)\n                | false => countoddmembers t\n                end\n    end.\n\n  Example test_countoddmembers1:    countoddmembers [1,0,3,1,4,5] = 4.\n  Proof. reflexivity. Qed.\n  Example test_countoddmembers2:    countoddmembers [0,2,4] = 0.\n  Proof. reflexivity. Qed.\n  Example test_countoddmembers3:    countoddmembers nil = 0.\n  Proof. reflexivity. Qed.\n\n  Fixpoint alternate (l1 l2 : natlist) : natlist :=\n    match l1 with\n    | nil => l2\n    | h1 :: t1 => match l2 with\n                  | nil => l1\n                  | h2 :: t2 => cons h1 (cons h2 (alternate t1 t2))\n                  end\n    end.\n\n  Example test_alternate1:        alternate [1,2,3] [4,5,6] = [1,4,2,5,3,6].\n  Proof. reflexivity. Qed.\n  Example test_alternate2:        alternate [1] [4,5,6] = [1,4,5,6].\n  Proof. reflexivity. Qed.\n  Example test_alternate3:        alternate [1,2,3] [4] = [1,4,2,3].\n  Proof. reflexivity. Qed.\n  Example test_alternate4:        alternate [] [20,30] = [20,30].\n  Proof. reflexivity. Qed.\n\n  Definition bag := natlist.\n\n  Fixpoint count (v:nat) (s:bag) : nat :=\n    match s with\n    | nil => 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\n  Example test_count1:              count 1 [1,2,3,1,4,1] = 3.\n  Proof. reflexivity. Qed.\n  Example test_count2:              count 6 [1,2,3,1,4,1] = 0.\n  Proof. reflexivity. Qed.\n\n  Definition sum : bag -> bag -> bag := app.\n\n  Example test_sum1:              count 1 (sum [1,2,3] [1,4,1]) = 3.\n  Proof. reflexivity. Qed.\n\n  Definition add (v:nat) (s:bag) : bag := cons v s.\n\n  Example test_add1:                count 1 (add 1 [1,4,1]) = 3.\n  Proof. reflexivity. Qed.\n  Example test_add2:                count 5 (add 1 [1,4,1]) = 0.\n  Proof. reflexivity. Qed.\n\n  Definition member (v:nat) (s:bag) : bool :=\n    blt_nat 0 (count v s).\n\n  Example test_member1:             member 1 [1,4,1] = true.\n  Proof. reflexivity. Qed.\n  Example test_member2:             member 2 [1,4,1] = false.\n  Proof. reflexivity. Qed.\n\n  Fixpoint remove_one (v:nat) (s:bag): bag :=\n    match s with\n    | nil => nil\n    | h :: t => match beq_nat v h with\n                | true => t\n                | false => h :: (remove_one v t)\n                end\n    end.\n\n  Example test_remove_one1:         count 5 (remove_one 5 [2,1,5,4,1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_one2:         count 5 (remove_one 5 [2,1,4,1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_one3:         count 4 (remove_one 5 [2,1,4,5,1,4]) = 2.\n  Proof. reflexivity. Qed.\n  Example test_remove_one4:\n    count 5 (remove_one 5 [2,1,5,4,5,1,4]) = 1.\n  Proof. reflexivity. Qed.\n\n  Fixpoint remove_all (v:nat) (s:bag) : bag :=\n    match s with\n    | 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  Example test_remove_all1:          count 5 (remove_all 5 [2,1,5,4,1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_all2:          count 5 (remove_all 5 [2,1,4,1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_all3:          count 4 (remove_all 5 [2,1,4,5,1,4]) = 2.\n  Proof. reflexivity. Qed.\n  Example test_remove_all4:          count 5 (remove_all 5 [2,1,5,4,5,1,4,5,1,4]) = 0.\n  Proof. reflexivity. Qed.\n\n  Fixpoint subset (s1:bag) (s2:bag) : bool :=\n    match s1 with\n    | nil => true\n    | h :: t => match member h s2 with\n                | true => subset t (remove_one h s2)\n                | false => false\n                end\n    end.\n\n  Example test_subset1:              subset [1,2] [2,1,4,1] = true.\n  Proof. reflexivity. Qed.\n  Example test_subset2:              subset [1,2,2] [2,1,4,1] = false.\n  Proof. reflexivity. Qed.\n\n  Theorem nil_app : forall l : natlist,\n      [] ++ l = l.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Theorem tl_length_pred : forall l : natlist,\n      pred (length l) = length (tail l).\n  Proof.\n    intros l. destruct l as [| n l'].\n    Case \"l = nil\".\n      reflexivity.\n    Case \"l = cons n l'\".\n      reflexivity.\n  Qed.\n\n  Theorem app_ass : forall l1 l2 l3 : natlist,\n      (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\n  Proof.\n    intros l1 l2 l3. induction l1 as [| n l'].\n    Case \"l1 = nil\".\n      reflexivity.\n    Case \"l1 = cons n l1\".\n      simpl. rewrite -> IHl'. reflexivity.\n  Qed.\n\n  Theorem app_length : forall l1 l2 : natlist,\n      length (l1 ++ l2) = (length l1) + (length l2).\n  Proof.\n    intros l1 l2. induction l1 as [| n l'].\n    Case \"l = nil\".\n      reflexivity.\n    Case \"l = cons n l'\".\n      simpl.  rewrite -> IHl'. reflexivity.\n  Qed.\n\n  Fixpoint snoc (l :natlist) (v : nat) : natlist :=\n    match l with\n    | nil => [v]\n    | h :: t => cons h (snoc t v)\n    end.\n\n  Fixpoint rev (l : natlist) : natlist :=\n    match l with\n    | nil => nil\n    | h :: t => snoc (rev t) h\n    end.\n\n  Example test_rev1:            rev [1,2,3] = [3,2,1].\n  Proof. reflexivity.  Qed.\n  Example test_rev2:            rev nil = nil.\n  Proof. reflexivity.  Qed.\n\n  Theorem length_snoc : forall n : nat, forall l : natlist,\n        length (snoc l n) = S (length l).\n  Proof.\n    intros n l. induction l as [| n' l'].\n    Case \"l = nil\".\n      reflexivity.\n    Case \"l = n' l'\".\n      simpl. rewrite -> IHl'. reflexivity.\n  Qed.\n\n  Theorem rev_length_firsttry : forall l : natlist,\n      length (rev l) = length l.\n  Proof.\n    intros l. induction l as [| n l'].\n    Case \"l = nil\".\n      reflexivity.\n    Case \"l = n l'\".\n      simpl. rewrite -> length_snoc. rewrite <- IHl'. reflexivity.\n  Qed.\n\n  Theorem app_nil_end : forall l : natlist,\n      l ++ [] = l.\n  Proof.\n    intros l. induction l as [| n l'].\n    Case \"l = nil\".\n      reflexivity.\n    Case \"l = n l'\".\n      simpl. rewrite -> IHl'. reflexivity.\n  Qed.\n\n  Theorem rev_snoc : forall l : natlist, forall n : nat,\n      rev (snoc l n) = n :: (rev l).\n  Proof.\n    intros. induction l as [| n' l'].\n    Case \"l = nil\".\n      reflexivity.\n    Case \"l = n' l'\".\n      simpl. rewrite -> IHl'. simpl. reflexivity.\n  Qed.\n\n  Theorem rev_involutive : forall l : natlist,\n      rev (rev l) = l.\n  Proof.\n    intros l. induction l as [| n l'].\n    Case \"l = nil\".\n      reflexivity.\n    Case \"l = n l'\".\n      simpl. rewrite -> rev_snoc. rewrite -> IHl'. reflexivity.\n  Qed.\n\n  Theorem snoc_append : forall l1 l2 : natlist, forall n : nat,\n      snoc (l1 ++ l2) n = l1 ++ snoc l2 n.\n  Proof.\n    intros l1 l2 n. induction l1 as [| n' l1'].\n    Case \"l1 = nil\".\n      reflexivity.\n    Case \"l1 = n' ++ l1'\".\n      simpl. rewrite IHl1'. reflexivity.\n  Qed.\n\n  Theorem distr_rev : forall l1 l2 : natlist,\n      rev (l1 ++ l2) = (rev l2) ++ (rev l1).\n  Proof.\n    intros l1 l2. induction l1 as [| n l1'].\n    Case \"l1 = nil\".\n      simpl. rewrite -> app_nil_end. reflexivity.\n    Case \"l1 = n l1'\".\n      simpl. rewrite IHl1'. rewrite snoc_append. reflexivity.\n  Qed.\n\n  Theorem app_ass4 : forall l1 l2 l3 l4 : natlist,\n      l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\n  Proof.\n    intros l1 l2 l3 l4. rewrite -> app_ass. rewrite -> app_ass. reflexivity.\n  Qed.\n\n  Theorem snoc_appended : forall (l : natlist) (n : nat),\n      snoc l n = l ++ [n].\n  Proof.\n    intros l n. induction l as [| n' l'].\n    Case \"l = nil\".\n      reflexivity.\n    Case \"l = n' :: l'\".\n      simpl. rewrite -> IHl'. reflexivity.\n    Qed.\n\n  Lemma nonzeros_length : forall l1 l2 : natlist,\n      nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\n  Proof.\n    intros l1 l2. induction l1 as [| n' l1'].\n    Case \"l1 = nil\".\n      reflexivity.\n    Case \"l1 = n' :: l1'\".\n      simpl. induction n' as [| n''].\n      rewrite -> IHl1'. reflexivity.\n      simpl. rewrite IHl1'. reflexivity.\n  Qed.\n\n  Theorem count_member_nonzero : forall (s : bag),\n      ble_nat 1 (count 1 (1 :: s)) = true.\n  Proof.\n    intros s. reflexivity.\n  Qed.\n\n  Theorem ble_n_Sn : forall n,\n      ble_nat n (S n) = true.\n  Proof.\n    intros n. induction n as [| n'].\n    Case \"O\".\n      simpl. reflexivity.\n    Case \"S n\".\n      simpl. rewrite -> IHn'. reflexivity.\n  Qed.\n\n  Theorem remove_decreases_count: forall (s : bag),\n      ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\n  Proof.\n    intros s. induction s as [| n s'].\n    Case \"s = 0\".\n      reflexivity.\n    Case \"s = n :: s'\".\n      simpl. induction n as [| n'].\n      simpl. rewrite -> ble_n_Sn. reflexivity.\n      simpl. rewrite IHs'. reflexivity.\n  Qed.\n\n  Theorem rev_injective : forall (l1 l2 : natlist),\n      rev l1 = rev l2 -> l1 = l2.\n  Proof.\n    intros l1 l2 H.\n    rewrite <- rev_involutive.\n    rewrite <- H.\n    rewrite -> rev_involutive.\n    reflexivity.\n  Qed.\n\n  Inductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n  Fixpoint index_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\n  Fixpoint 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  Example test_index1 : index 0 [4,5,6,7] = Some 4.\n  Proof. reflexivity. Qed.\n  Example test_index2 :    index 3 [4,5,6,7]  = Some 7.\n  Proof. reflexivity.  Qed.\n  Example test_index3 :    index 10 [4,5,6,7] = None.\n  Proof. reflexivity.  Qed.\n\n  Definition option_elim (o : natoption) (d : nat) : nat :=\n    match o with\n    | Some n' => n'\n    | None => d\n    end.\n\n  Definition hd_opt (l : natlist) : natoption :=\n    match l with\n    | nil => None\n    | h :: t => Some h\n    end.\n\n  Example test_hd_opt1 : hd_opt [] = None.\n  Proof. reflexivity. Qed.\n\n  Example test_hd_opt2 : hd_opt [1] = Some 1.\n  Proof. reflexivity. Qed.\n\n  Example test_hd_opt3 : hd_opt [5,6] = Some 5.\n  Proof. reflexivity. Qed.\n\n  Theorem option_elim_hd : forall (l:natlist) (default:nat),\n      hd default l = option_elim (hd_opt l) default.\n  Proof.\n    intros l default. induction l as [| n l'].\n    Case \"l = nil\".\n    reflexivity.\n    Case \"l = n :: l'\".\n    reflexivity.\n  Qed.\n\n  Fixpoint beq_natlist (l1 l2 : natlist) : bool :=\n    match l1 with\n    | nil => match l2 with\n             | nil => true\n             | h :: t => false\n             end\n    | h1 :: t1 => match l2 with\n                  | nil => false\n                  | h2 :: t2 => match beq_nat h1 h2 with\n                                | true => beq_natlist t1 t2\n                                | false => false\n                                end\n                  end\n    end.\n\n  Example test_beq_natlist1 :   (beq_natlist nil nil = true).\n  Proof. simpl. reflexivity. Qed.\n  Example test_beq_natlist2 :   beq_natlist [1,2,3] [1,2,3] = true.\n  Proof. simpl. reflexivity. Qed.\n  Example test_beq_natlist3 :   beq_natlist [1,2,3] [1,2,4] = false.\n  Proof. simpl. reflexivity. Qed.\n\n  Theorem beq_natlist_refl : forall l:natlist,\n      true = beq_natlist l l.\n  Proof.\n    intros l. induction l as [|n l'].\n    Case \"l = nil\".\n      reflexivity.\n    Case \"l = n :: l'\".\n      simpl. replace (beq_nat n n) with (true). rewrite <- IHl'. reflexivity.\n      induction n as [| n'].\n      reflexivity.\n      simpl. rewrite <- IHn'. reflexivity.\n  Qed.\n\n  Theorem silly1 : forall (n m o p : nat),\n      n = m  ->\n      [n,o] = [n,p] ->\n      [n,o] = [m,p].\n  Proof.\n    intros n m o p eq1 eq2.\n    rewrite <- eq1.\n    apply eq2.\n  Qed.\n\n  Theorem 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].\n  Proof.\n    intros n m o p eq1 eq2.\n    apply eq2. apply eq1.\n  Qed.\n\n  Theorem silly2a : forall (n m : nat),\n      (n,n) = (m,m)  ->\n      (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n      [n] = [m].\n  Proof.\n    intros n m eq1 eq2.\n    apply eq2. apply eq1.\n  Qed.\n\n  Theorem silly_ex :\n    (forall n, evenb n = true -> oddb (S n) = true) ->\n    evenb 3 = true ->\n    oddb 4 = true.\n  Proof.\n    intros eq1 eq2.\n    apply eq1. apply eq2.\n  Qed.\n\n  Theorem silly3_firsttry : forall (n : nat),\n      true = beq_nat n 5  ->\n      beq_nat (S (S n)) 7 = true.\n  Proof.\n    intros n H.\n    symmetry.\n    simpl.\n    apply H.\n  Qed.\n\n  Theorem rev_exercise1 : forall (l l' : natlist),\n      l = rev l' ->\n      l' = rev l.\n  Proof.\n    intros l l' H.\n    rewrite -> H.\n    symmetry.\n    apply rev_involutive.\n  Qed.\n\n  Theorem app_ass' : forall l1 l2 l3 : natlist,\n      (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\n  Proof.\n    intros l1. induction l1 as [ | n l1'].\n    Case \"l1 = nil\".\n      reflexivity.\n    Case \"l1 = n :: l1'\".\n      simpl. intros l2 l3. rewrite IHl1'. reflexivity.\n  Qed.\n\n  Theorem beq_nat_sym : forall (n m : nat),\n      beq_nat n m = beq_nat m n.\n  Proof.\n    intros n. induction n as [| n'].\n    Case \"n = 0\".\n      destruct m.\n        reflexivity.\n        reflexivity.\n    Case \"n = S n'\".\n      destruct m.\n        reflexivity.\n        apply IHn'.\n  Qed.\nEnd NatList.\n\nModule Dictionary.\n  Inductive dictionary : Type :=\n  | empty : dictionary\n  | record : nat -> nat -> dictionary -> dictionary.\n\n  Definition insert (key value : nat) (d : dictionary) : dictionary :=\n    record key value d.\n\n  Fixpoint 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  Theorem dictionary_invariant1 : forall (d : dictionary) (k v: nat),\n      (find k (insert k v d)) = Some v.\n  Proof.\n    intros.\n    simpl.\n    replace (beq_nat k k) with true.\n    reflexivity.\n    apply beq_nat_refl.\n  Qed.\n\n  Theorem dictionary_invariant2 : forall (d : dictionary) (m n o: nat),\n      (beq_nat m n) = false -> (find m d) = (find m (insert n o d)).\n  Proof.\n    intros.\n    simpl. rewrite H. reflexivity.\n  Qed.\nEnd Dictionary.\n\nDefinition beq_nat_sym := NatList.beq_nat_sym.\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/Lists_J.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.6819239703970864}}
{"text": "Add LoadPath \"..\".\nRequire Import Paths Fibrations Funext UnivalenceAxiom.\n\n(* By using impredicative set and functional extensionality, we can\n   *define* a higher inductive type and prove its non-dependent\n   computation rule.  Here we do the interval. *)\n\nDefinition interval : Set := forall (X : Set) (a b : X) (p : a == b), X.\n\nDefinition zero : interval := fun X a b p => a.\n\nDefinition one : interval := fun X a b p => b.\n\nDefinition segment : zero == one.\nProof.\n  apply funext_dep with (f := zero) (g := one); intro X.\n  apply funext_dep; intro a.\n  apply funext_dep; intro b.\n  apply funext_dep; intro p.\n  unfold zero, one; exact p.\nDefined.\n\nDefinition interval_rec : forall (X : Set) (a b : X) (p : a == b), interval -> X :=\n  fun X a b p i => i X a b p.\n\n(* It's sort of stupid to use this interval to prove functional\n   extensionality, since we already had to assume funext in order to\n   define [segment], but it shows that the computation rules really do\n   hold definitionally. *)\n\nDefinition funext_dep_statement_inSet :=\n  forall (X : Set) (P : X -> Set) (f g : forall x : X, P x),\n    (forall x : X, f x == g x) -> f == g.\n\nTheorem interval_implies_funext_dep : funext_dep_statement_inSet.\nProof.\n  intros X P f g p.\n  set (mate := fun (i:interval) x => interval_rec _ _ _ (p x) i).\n  path_via (mate zero).\n  apply opposite.\n  path_via (fun x => f x).\n  apply funext_dep; auto.\n  path_via (mate one).\n  exact segment.\n  path_via (fun x => g x).\n  apply funext_dep; auto.\nDefined.\n\nDefinition interval_compute_segment :\n  forall (X : Set) (a b : X) (p : a == b),\n    map (interval_rec X a b p) segment == p.\nProof.\n  intros X a b p.\n  unfold interval_rec.\n  (* First we change this map into a bunch of [happly_dep]s. *)\n  path_via (map ((fun z => z p) ○ (fun z => z b) ○ (fun z => z a) ○ (fun i => i X)) segment).\n  do_compose_map.\n  change (happly_dep (happly_dep (happly_dep (happly_dep segment X) a) b) p == p).\n  unfold segment.\n  (* Now each [happly_dep] matches up exactly with one occurrence of\n     [funext_dep] in [segment].  Thus we just have to kill them off one\n     by one from the inside out. *)\n  repeat match goal with | |- ?s == ?t =>\n    match s with\n      | context cxt [ happly_dep (funext_dep ?P' _ _ ?p') ?x' ] =>\n        let mid := context cxt [ p' x' ] in\n          apply @concat with (y := mid);\n            [ repeat (apply_happly; apply map);\n              apply funext_dep_compute with (P := P') (x := x')\n              | ]\n    end\n  end.\n  auto.\nDefined.\n\n(*\nLocal Variables:\ncoq-prog-args: (\"-emacs\" \"-impredicative-set\")\nEnd:\n*)\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/contrib/old/HIT/ImpredicativeInterval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.681910344152949}}
{"text": "\n(* Definitions of asymptotic notions such as polynomial and negligible functions, and related theory. *)\n\nSet Implicit Arguments.\n\nRequire Import StdNat.\n\nDefinition polynomial (f : nat -> nat) :=\n    exists x c1 c2, forall n,\n      (f n <= c1 * expnat n x + c2)%nat.\n\nDefinition polynomial_nz(f : nat -> nat) :=\n  exists x c1 c2, \n    x > 0 /\\ c1 > 0 /\\ c2 > 0 /\\\n    forall n, \n      (f n <= c1 * expnat n x + c2)%nat.\n\nTheorem polynomial_nz_equiv : \n  forall f, \n    polynomial f ->\n    polynomial_nz f.\n  \n  intuition.\n  unfold polynomial, polynomial_nz in *.\n  do 3 (destruct H).\n  exists (S x).\n  exists (S x0).\n  exists (x0 + S x1).\n  intuition.\n  rewrite H.\n  rewrite plus_assoc.\n  eapply plus_le_compat; intuition.\n  simpl.\n  destruct (eq_nat_dec x 0).\n  subst.\n  simpl.\n  repeat rewrite mult_1_r.\n  rewrite <- plus_0_l at 1.\n  eapply plus_le_compat; intuition.\n  \n  rewrite <- plus_0_l at 1.\n  rewrite <- plus_0_r at 1.\n  \n  eapply plus_le_compat; intuition.\n  eapply plus_le_compat; intuition.\n  eapply mult_le_compat; intuition.\n  destruct (eq_nat_dec n 0); subst.\n  \n  rewrite expnat_0;\n    omega.\n  \n  rewrite <- mult_1_l at 1.\n  eapply mult_le_compat; intuition.\nQed.        \n\nTheorem polynomial_plus : \n  forall f1 f2 ,\n    polynomial f1 ->\n    polynomial f2 ->\n    polynomial (fun n => f1 n + f2 n).\n  \n  intuition.\n  \n  apply polynomial_nz_equiv in H.\n  apply polynomial_nz_equiv in H0.\n  \n  unfold polynomial, polynomial_nz in *.\n  \n  Ltac des := \n    match goal with\n      | [H : exists _, _ |- _] => destruct H\n    end.\n  repeat des.\n  intuition.\n  exists (max x2 x).\n  exists (x3 + x0).\n  exists (x4 + x1).\n  intuition.\n  \n  eapply le_trans.\n  eapply plus_le_compat.\n  eapply H6; trivial.\n  eapply H7; trivial.\n  rewrite mult_plus_distr_r.\n  repeat rewrite plus_assoc.\n  eapply plus_le_compat; trivial.\n  rewrite plus_comm.\n  rewrite plus_assoc.\n  eapply plus_le_compat; trivial.\n  rewrite plus_comm.\n  eapply plus_le_compat;\n    eapply mult_le_compat; intuition.\n  \n  eapply expnat_exp_le; intuition.\n  eapply expnat_exp_le; intuition.\nQed.\n\nTheorem polynomial_const : \n  forall c, \n    polynomial (fun n => c).\n  \n  intuition.\n  unfold polynomial.\n  exists 0.\n  exists 0.\n  exists c.\n  intuition.\nQed.\n\nTheorem polynomial_ident :\n  polynomial (fun n => n).\n  \n  unfold polynomial.\n  intuition.\n  exists 1.\n  exists 1.\n  exists 0.\n  intuition.\n  simpl.\n  omega.\n  \nQed.\n\nTheorem polynomial_mult : \n  forall f1 f2 ,\n    polynomial f1 ->\n    polynomial f2 ->\n    polynomial (fun n => f1 n * f2 n).\n  \n  intuition.\n  apply polynomial_nz_equiv in H.\n  apply polynomial_nz_equiv in H0.\n  \n  unfold polynomial, polynomial_nz in *.\n  repeat des.\n  intuition.\n  exists (x + x2).\n  exists (3 * (x3 * x0 * x4 * x1)).\n  exists (x4 * x1).\n  intuition.\n  eapply le_trans.\n  eapply mult_le_compat.\n  eapply H6; intuition.\n  eapply H7; intuition.\n  repeat rewrite mult_plus_distr_l.\n  repeat rewrite mult_plus_distr_r.\n  \n  rewrite plus_assoc.\n  eapply plus_le_compat; trivial.\n  \n  rewrite expnat_plus.\n  simpl.\n  rewrite plus_0_r.\n  repeat rewrite mult_plus_distr_r.\n  rewrite plus_assoc.\n  eapply plus_le_compat.\n  eapply plus_le_compat.\n  rewrite (mult_comm (expnat n x)).\n  repeat rewrite mult_assoc.\n  eapply mult_le_compat; intuition.\n  rewrite mult_comm.\n  rewrite mult_assoc.\n  eapply mult_le_compat; intuition.\n  rewrite <- mult_1_r at 1.\n  rewrite <- mult_1_r at 1.\n  eapply mult_le_compat; intuition.\n  eapply mult_le_compat; intuition.\n  rewrite mult_comm.\n  intuition.\n  \n  destruct (eq_nat_dec n 0); subst.\n  repeat rewrite expnat_0.\n  simpl.\n  repeat rewrite mult_0_r.\n  intuition.\n  trivial.\n  trivial.\n  rewrite (mult_comm (expnat n x)).\n  repeat rewrite mult_assoc.\n  eapply mult_le_compat; trivial.\n  rewrite <- mult_1_r at 1.\n  eapply mult_le_compat; trivial.\n  rewrite <- mult_1_r at 1.\n  eapply mult_le_compat; trivial.\n  rewrite mult_comm.\n  eapply mult_le_compat; trivial.\n  rewrite <- mult_1_l at 1.\n  eapply mult_le_compat; trivial.\n  eapply expnat_ge_1.\n  omega.\n  \n  destruct (eq_nat_dec n 0); subst.\n  repeat rewrite expnat_0.\n  simpl.\n  repeat rewrite mult_0_r.\n  intuition.\n  trivial.\n  trivial.\n  rewrite (mult_comm (expnat n x)).\n  repeat rewrite mult_assoc.\n  rewrite <- mult_1_r at 1.\n  eapply mult_le_compat; trivial.\n  rewrite <- mult_assoc.\n  rewrite (mult_comm (expnat n x2)).\n  rewrite mult_assoc.\n  eapply mult_le_compat; trivial.\n  eapply mult_le_compat; trivial.\n  rewrite <- mult_1_r at 1.\n  eapply mult_le_compat; trivial.\n  rewrite <- mult_1_r at 1.\n  eapply mult_le_compat; trivial.\n  eapply expnat_ge_1.\n  omega.\nQed.     \n      \n\nRequire Import Rat.\nLocal Open Scope rat_scope.\n\nDefinition negligible(f : nat -> Rat) :=\n  forall c, exists n, forall x (pf_nz : nz x),\n    x > n ->\n    ~ ((1 / expnat x c) <= f x)%rat.\n\n\nTheorem negligible_eq : \n  forall (f1 f2 : nat -> Rat),\n    negligible f1 ->\n    (forall n, f1 n == f2 n) ->\n    negligible f2.\n\n  intuition.\n  unfold negligible in *.\n  intuition.\n  edestruct H.\n  econstructor.\n  intuition.\n  eapply H1.\n  eauto.\n  rewrite H3.\n  rewrite <- H0.\n  intuition.\n\nQed.\n\nLemma negligible_le : \n  forall f1 f2,\n    (forall n, f2 n <= f1 n)%rat ->\n    negligible f1 ->\n    negligible f2.\n  \n  intuition.\n  unfold negligible in *.\n  intuition.\n  edestruct H0.\n  econstructor.\n  intuition.\n  eapply H1.\n  eauto.\n  rewrite H3.\n  eauto.\n  \nQed.\n\nLemma negligible_plus : \n  forall f1 f2,\n    negligible f1 ->\n    negligible f2 ->\n    negligible (fun n => f1 n + f2 n)%rat.\n  \n  unfold negligible in *.\n  intuition.\n  \n  destruct (H (S c)).\n  destruct (H0 (S c)).\n  exists (max 1 (max x x0)).\n  intuition.\n  \n  apply Nat.max_lub_lt_iff in H3.\n  intuition.\n  \n  assert (1 / expnat x1 c <= 2/1 * (maxRat (f1 x1) (f2 x1)))%rat.\n  eapply leRat_trans.\n  eapply H4.\n  \n  eapply ratAdd_2_ratMax.\n  \n  assert (1 / expnat x1 (S c) <= RatIntro 1 (posnatMult (pos 2) (pos (expnat x1 c))))%rat.\n  eapply leRat_terms; intuition.\n  unfold natToPosnat, posnatToNat, posnatMult.\n  eapply expnat_double_le.\n  omega.\n  \n  unfold maxRat in *.\n  case_eq (bleRat (f1 x1) (f2 x1)); intuition.\n  rewrite H8 in H3.\n  \n  eapply H2.\n  eapply le_lt_trans.\n  eapply Max.le_max_r.\n  eauto.\n\n  rewrite H7.\n  rewrite rat_mult_den.\n  rewrite H3.\n  rewrite <- ratMult_assoc.\n  \n  rewrite <- ratMult_num_den.\n  rewrite num_dem_same_rat1.\n  rewrite ratMult_1_l.\n  intuition.\n  unfold posnatMult, natToPosnat, posnatToNat.\n  omega.\n  \n  rewrite H8 in H3.\n  eapply H1.\n  eapply le_lt_trans.\n  eapply Max.le_max_l.\n  eauto.\n  \n  rewrite H7.\n  rewrite rat_mult_den.\n  rewrite H3.\n  rewrite <- ratMult_assoc.\n  \n  rewrite <- ratMult_num_den.\n  rewrite num_dem_same_rat1.\n  rewrite ratMult_1_l.\n  intuition.\n  unfold posnatMult, natToPosnat, posnatToNat.\n  omega.\nQed.\n\n\n(* We need several facts about arithmetic to show that an inverse exponential function is negligible. *)\nLocal Open Scope nat_scope.\nTheorem double_log_plus_3_le_h : \n  forall y x,\n    y = log2 x ->\n    y >= 4 ->\n    2 * y + 3 <= x.\n  \n  induction y; intuition; simpl in *.\n  rewrite plus_0_r in *.\n  \n  assert (S (y + S y + 3)  = \n    (y + y + 3) + 2).\n  omega.\n  rewrite H1.\n  \n  destruct (eq_nat_dec y 3).\n  subst.\n  assert (x >= pow 2 4).\n  rewrite H.\n  eapply Nat.log2_spec.\n  destruct (eq_nat_dec x 0).\n  subst.\n  rewrite log2_0 in H.\n  omega.\n  omega.\n  \n  eapply le_trans.\n  Focus 2.\n  eapply H2.\n  simpl.\n  omega.\n  \n  assert ( y + y + 3 <= div2 x).\n  eapply IHy.\n  \n  symmetry.\n  apply log2_div2.\n  trivial.\n  omega.\n  \n  assert (2 <= div2 x).\n  assert (2 = div2 4).\n  trivial.\n  rewrite H3.\n  eapply div2_le_mono.\n  eapply le_trans.\n  Focus 2.\n  eapply Nat.log2_le_lin.\n  destruct (eq_nat_dec 0 x); subst.\n  rewrite log2_0 in H.\n  omega.\n  omega.\n  omega.\n  \n  eapply le_trans.\n  eapply plus_le_compat.\n  eapply H2.\n  \n  eapply H3.\n  \n  eapply div2_ge_double.\n  \nQed.\n\nTheorem S_log_square_lt_h : \n  forall y x,\n    y = log2 x ->\n    6 <= log2 x->\n    S y * S y <= x.\n  \n  induction y; intuition; simpl in *.\n  assert (y = log2 (div2 x)).\n  symmetry.\n  eapply log2_div2.\n  trivial.\n\n  rewrite (mult_comm _ (S (S y))).\n  simpl.\n  rewrite (mult_comm _ (S y)) in IHy.\n  simpl in *.\n  \n  assert ( S (S (y + S (S (y + (y + (y + y * y)))))) = \n    (S (y + (y + y * y))) + (2 * y + 3)).\n  omega.\n  rewrite H2.\n  clear H2.\n  \n  destruct (eq_nat_dec (log2 x) 6).\n  \n  assert (y = 5).\n  assert (S y = 6).\n  rewrite H.\n  trivial.\n  omega.\n  rewrite H2.\n  simpl.\n  assert (x >= pow 2 6).\n  rewrite <- e.\n  \n  eapply Nat.log2_spec.\n  \n  destruct (eq_nat_dec x 0).\n  subst.\n  rewrite log2_0 in H.\n  omega.\n  omega.\n  \n  eapply le_trans.\n  Focus 2.\n  eapply H3.\n  simpl.\n  omega.\n  \n  assert ( S (y + (y + y * y)) <= div2 x).\n  eapply IHy.\n  trivial.\n  omega.\n  \n  assert (2 * y + 3 <= div2 x).\n  eapply double_log_plus_3_le_h; trivial.\n  omega.\n  eapply le_trans.\n  eapply plus_le_compat.\n  eapply H2.\n  eapply H3.\n  \n  eapply div2_ge_double.\n  \nQed.\n\nTheorem S_log_square_lt : \n  forall x, \n    pow 2 6 <= x->\n    S (log2 x) * S (log2 x) <= x.\n  \n  intuition.\n  eapply S_log_square_lt_h; trivial.\n  eapply le_trans.\n  Focus 2.\n  eapply Nat.log2_le_mono.\n  eapply H.\n  rewrite Nat.log2_pow2; omega.\nQed.\n\nTheorem log_square_lt : \n  forall x, \n    pow 2 6 <= x->\n    log2 x * log2 x < x.\n  \n  intuition.\n  \n  assert (log2 x < S (log2 x)).\n  omega.\n  eapply lt_le_trans.\n  \n  eapply mult_lt_compat.\n  eapply H0.\n  eapply H0.\n  eapply S_log_square_lt.\n  trivial.\nQed.\n\nTheorem poly_lt_exp_ge_6 : \n  forall c x, \n    x >= (pow 2 c) ->\n    x >= (pow 2 6) ->\n    pow x c < pow 2 x.\n  \n  intuition.\n  \n  specialize (Nat.log2_spec_alt); intuition.\n  destruct (H1 x).\n  eapply lt_le_trans.\n  Focus 2.\n  eapply H.\n  eapply (expnat_2_ge_1 c).\n  \n  intuition.\n  (* This case split probably isn't necessary *)\n  destruct (eq_nat_dec x0 0).\n  rewrite e in H3.\n  rewrite plus_0_r in *.\n  rewrite H3.\n  rewrite <- Nat.pow_mul_r.\n  \n  eapply Nat.pow_lt_mono_r.\n  omega.\n  rewrite <- H3.\n\n  assert (c <= log2 x).\n  eapply (@Nat.pow_le_mono_r_iff 2).\n  omega.\n  rewrite <- H3.\n  trivial.\n  eapply le_lt_trans.\n  eapply mult_le_compat.\n  eapply le_refl.\n  eapply H4.\n  \n  eapply log_square_lt.\n  eapply le_trans.\n  Focus 2.\n  eapply H0.\n  eapply Nat.pow_le_mono_r.\n  omega.\n  omega.\n  \n  destruct (eq_nat_dec c 0).\n  rewrite e.\n  simpl.\n  eapply le_lt_trans.\n  assert (1 <= expnat 2 0).\n  trivial.\n  eapply H4.\n  eapply Nat.pow_lt_mono_r.\n  omega.\n  omega.\n  \n  assert (expnat x c < expnat (2 ^ S (log2 x)) c).\n  eapply Nat.pow_lt_mono_l.\n  omega.\n  eapply log2_spec.\n  omega.\n  eapply lt_le_trans.\n  eapply H4.\n      \n  rewrite <- Nat.pow_mul_r.\n  eapply Nat.pow_le_mono_r.\n  omega.\n  assert (c <= S (log2 x)).\n  eapply (@Nat.pow_le_mono_r_iff 2).\n  omega.\n  eapply le_trans.\n  eapply H.\n  \n  eapply lt_le_weak.\n  eapply log2_spec.\n  omega.\n  \n  eapply le_trans.\n  eapply mult_le_compat.\n  eapply le_refl.\n  eapply H6.\n  \n  eapply S_log_square_lt.\n  eapply le_trans.\n  Focus 2.\n  eapply H0.\n  eapply Nat.pow_le_mono_r.\n  omega.\n  omega.\nQed.\n\nTheorem poly_lt_exp : \n  forall c, \n    exists x, \n      forall y, y >= x ->\n        expnat y c < expnat 2 y.\n  \n  intuition.\n  exists (expnat 2 (max c 6)).\n  intuition.\n  eapply poly_lt_exp_ge_6.\n  eapply le_trans.\n  Focus 2.\n  eapply H.\n  eapply Nat.pow_le_mono_r.\n  omega.\n  eapply Max.le_max_l.\n  \n  eapply le_trans.\n  Focus 2.\n  eapply H.\n  eapply Nat.pow_le_mono_r.\n  omega.\n  eapply Max.le_max_r.\nQed.\n    \nTheorem negligible_exp_den : \n  negligible (fun n => 1 / expnat 2 n)%rat.\n  \n  unfold negligible in *.\n  \n  intuition.\n  destruct (poly_lt_exp c).\n  exists x.\n  intuition.\n  \n  eapply (rat_num_not_le).\n  eapply H1.\n  \n  unfold posnatToNat, natToPosnat.\n  eapply H.\n  omega.\nQed.\n\n\nTheorem negligible_const_mult : \n  forall (n : nat) d f,\n    negligible f -> \n    negligible (fun x => (RatIntro n d) * (f x))%rat.\n  \n  unfold negligible in *.\n  intuition.\n  \n  destruct (eq_nat_dec n 0).\n  subst.\n  exists 1.\n  intuition.\n  \n  assert ((1 / expnat x c) == 0)%rat.\n  \n  eapply leRat_0_eq.\n  rewrite H1.\n  rewrite rat_num_0.\n  rewrite ratMult_0_l.\n  intuition.\n  \n  eapply rat_num_nz; [idtac | eauto].\n  omega.\n  \n  destruct (H (c + n)).\n  exists (x + n)%nat.\n  intuition.\n  eapply H0.\n  omega.\n  \n  assert (1 / expnat x0 (c + n) == RatIntro 1 (pos  (expnat x0 c)) * RatIntro 1 (pos (expnat x0 n)))%rat.\n  rewrite <- ratMult_num_den.\n  eapply eqRat_terms.\n  symmetry.\n  eapply mult_1_r.\n  unfold natToPosnat, posnatToNat, posnatMult.\n  rewrite expnat_plus.\n  trivial.\n  \n  rewrite H3.\n  rewrite H2.\n  rewrite ratMult_comm.\n  rewrite <- ratMult_assoc.\n  \n  eapply leRat_trans.\n  Focus 2.\n  eapply eqRat_impl_leRat.\n  rewrite <- ratMult_1_l.\n  eapply eqRat_refl.\n  eapply ratMult_leRat_compat; intuition.\n  \n  eapply rat_le_1.\n  destruct d.\n  unfold natToPosnat, posnatToNat, posnatMult.\n  rewrite mult_comm.\n  eapply mult_le_compat.\n      \n  eapply le_trans.\n  eapply le_expnat_2.\n  eapply expnat_base_le.\n  omega.\n  omega.\n\nQed.\n\nTheorem negligible_mult_ident : \n  forall f,\n    negligible f -> \n    negligible (fun x => (x / 1) * (f x))%rat.\n  \n  unfold negligible in *.\n  intuition.\n  \n  destruct (H (S c)).\n  exists x.\n  intuition.\n  eapply H0.\n  omega.\n  simpl.\n  \n  assert ( (RatIntro 1 (natToPosnat (expnat_nz (S c) pf_nz)))  == \n    RatIntro 1 (posnatMult (pos x0) (pos expnat x0 c)) )%rat.\n  eapply eqRat_terms; trivial.\n  \n  simpl in *.\n  rewrite H3.\n  rewrite ratMult_denom.\n  rewrite H2.\n  rewrite <- ratMult_assoc.\n  rewrite <- ratMult_num_den.\n  rewrite num_dem_same_rat1.\n  rewrite ratMult_1_l.\n  intuition.\n  unfold natToPosnat, posnatToNat, posnatMult.\n  omega.\nQed.\n\nTheorem negligible_exp : \n  forall z, \n    negligible (fun n => expnat n z / expnat 2 n)%rat.\n  \n  induction z; simpl in *; intuition.\n  \n  eapply negligible_exp_den.\n  \n  eapply negligible_eq.\n  eapply negligible_mult_ident.\n  eauto.\n  intuition.\n  rewrite <- ratMult_num_den.\n  eapply eqRat_terms; trivial.\n  unfold posnatToNat, natToPosnat, posnatMult.\n  eapply mult_1_l.\n  \nQed.\n\nTheorem negligible_const_num : \n  forall k,\n    negligible (fun n => k / expnat 2 n)%rat.\n  \n  intuition.\n  eapply negligible_eq.\n  eapply (@negligible_const_mult k (pos 1)).\n  eapply negligible_exp_den.\n  intuition.\n  rewrite <- ratMult_num_den.\n  eapply eqRat_terms.\n  eapply mult_1_r.\n  unfold natToPosnat, posnatToNat, posnatMult.\n  eapply mult_1_l.\nQed.\n\nTheorem negligible_poly_num : \n  forall f,\n    polynomial f ->\n    negligible (fun n => f n / expnat 2 n)%rat.\n  \n  intuition.\n  unfold polynomial in *.\n  do 3 destruct H.\n  eapply negligible_le.\n  intuition.\n  eapply leRat_terms.\n  eapply H.\n  eapply le_refl.\n  \n  eapply negligible_eq. \n  eapply negligible_plus.\n  eapply negligible_const_mult.\n  eapply negligible_exp.\n  eapply negligible_const_num.\n  \n  intuition.\n  symmetry.\n  \n  rewrite ratAdd_num.\n  eapply ratAdd_eqRat_compat.\n  rewrite <- ratMult_num_den.\n  eapply eqRat_terms.\n  eauto.\n  assert (posnatToNat (pos expnat 2 n) = posnatToNat (posnatMult (pos 1) (pos expnat 2 n))).\n  unfold natToPosnat, posnatToNat, posnatMult.\n  symmetry.\n  eapply mult_1_l.\n  eapply H0.\n  eapply eqRat_refl.\nQed.", "meta": {"author": "FreeAndFair", "repo": "RLA", "sha": "4295e4bb700ebbfe69affeb35dda7ed42273c3a1", "save_path": "github-repos/coq/FreeAndFair-RLA", "path": "github-repos/coq/FreeAndFair-RLA/RLA-4295e4bb700ebbfe69affeb35dda7ed42273c3a1/src/fcf/Asymptotic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6818044393982107}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_NCdistinct.\nRequire Export GeoCoq.Elements.OriginalProofs.proposition_28A.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_collinearparallel.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_parallelsymmetric.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma proposition_28D : \n   forall B D E G H, \n   BetS E G H -> CongA E G B G H D -> OS B D G H ->\n   Par G B H D.\nProof.\nintros.\nassert (nCol G H B) by (conclude_def OS ).\nassert (nCol G H D) by (conclude_def OS ).\nassert (neq H D) by (forward_using lemma_NCdistinct).\nassert (neq D H) by (conclude lemma_inequalitysymmetric).\nassert (neq G B) by (forward_using lemma_NCdistinct).\nassert (neq B G) by (conclude lemma_inequalitysymmetric).\nlet Tf:=fresh in\nassert (Tf:exists A, (BetS B G A /\\ Cong G A G B)) by (conclude lemma_extension);destruct Tf as [A];spliter.\nassert (BetS A G B) by (conclude axiom_betweennesssymmetry).\nlet Tf:=fresh in\nassert (Tf:exists C, (BetS D H C /\\ Cong H C H D)) by (conclude lemma_extension);destruct Tf as [C];spliter.\nassert (BetS C H D) by (conclude axiom_betweennesssymmetry).\nassert (Par A B C D) by (conclude proposition_28A).\nassert (Col D H C) by (conclude_def Col ).\nassert (Col C D H) by (forward_using lemma_collinearorder).\nassert (neq H D) by (forward_using lemma_NCdistinct).\nassert (Par A B H D) by (conclude lemma_collinearparallel).\nassert (Par H D A B) by (conclude lemma_parallelsymmetric).\nassert (Col B G A) by (conclude_def Col ).\nassert (Col A B G) by (forward_using lemma_collinearorder).\nassert (Par H D G B) by (conclude lemma_collinearparallel).\nassert (Par G B H D) by (conclude lemma_parallelsymmetric).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/proposition_28D.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6817370501926318}}
{"text": "Require Import List.\n(* Require Import Arith. *)\n\nDefinition length_tl :\n  forall (A : Type) (xs : list A), {n : nat | n = length xs}.\nProof.\n  intros A xs.\n\n  refine (\n      let fix iter n ys :=\n          match ys with\n            | nil      => n\n            | _ :: ys' => iter (S n) ys'\n          end\n      in exist _ (iter 0 xs) _\n    ).\n\n  info assert (Hiter: forall ys n, iter n ys = n + iter 0 ys).\n  info (induction ys; simpl).\n\n  apply plus_n_O.\n\n  intro n.\n  rewrite (IHys (S n)), (IHys 1).\n  apply plus_n_Sm.\n\n  induction xs; simpl.\n  reflexivity.\n\n  rewrite <- IHxs.\n  apply Hiter.\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/s2.2.2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6817370447160535}}
{"text": "Require Import NArith.\n\nGeneralizable All Variables.\n\nDefinition lift `(f:A->B) : option A -> option B :=\n  fun x => match x with\n        | Some v => Some(f v)\n        | None => None\n        end.\n\nDefinition decr :=\n  lift (fun x => (x - 1)%N).\n\nDefinition incr :=\n  lift (fun x => (x + 1)%N).\n", "meta": {"author": "SyDPaCC", "repo": "sydpacc", "sha": "640f0f74f21524ee203b192255ecfa9e456fb7d1", "save_path": "github-repos/coq/SyDPaCC-sydpacc", "path": "github-repos/coq/SyDPaCC-sydpacc/sydpacc-640f0f74f21524ee203b192255ecfa9e456fb7d1/Tree/Support/NOption.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224068675884, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6817370306221238}}
{"text": "(********************************************************************)\n(*                                                                  *)\n(*  The Why3 Verification Platform   /   The Why3 Development Team  *)\n(*  Copyright 2010-2019   --   Inria - CNRS - Paris-Sud University  *)\n(*                                                                  *)\n(*  This software is distributed under the terms of the GNU Lesser  *)\n(*  General Public License version 2.1, with the special exception  *)\n(*  on linking described in file LICENSE.                           *)\n(*                                                                  *)\n(********************************************************************)\n\n(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire Reals.R_sqrt.\nRequire Reals.Rbasic_fun.\nRequire Reals.Rtrigo_def.\nRequire Reals.Rtrigo1.\nRequire Reals.Ratan.\nRequire BuiltIn.\nRequire real.Real.\nRequire real.Abs.\nRequire real.Square.\n\nRequire Import Reals.\n\n(* Why3 comment *)\n(* cos is replaced with (Reals.Rtrigo_def.cos x) by the coq driver *)\n\n(* Why3 comment *)\n(* sin is replaced with (Reals.Rtrigo_def.sin x) by the coq driver *)\n\n(* Why3 goal *)\nLemma Pythagorean_identity :\n  forall (x:Reals.Rdefinitions.R),\n  (((Reals.RIneq.Rsqr (Reals.Rtrigo_def.cos x)) +\n    (Reals.RIneq.Rsqr (Reals.Rtrigo_def.sin x)))%R\n   = 1%R).\nProof.\nintros x.\nrewrite Rplus_comm.\napply sin2_cos2.\nQed.\n\n(* Why3 goal *)\nLemma Cos_le_one :\n  forall (x:Reals.Rdefinitions.R),\n  ((Reals.Rbasic_fun.Rabs (Reals.Rtrigo_def.cos x)) <= 1%R)%R.\nProof.\nintros x.\napply Abs.Abs_le.\napply COS_bound.\nQed.\n\n(* Why3 goal *)\nLemma Sin_le_one :\n  forall (x:Reals.Rdefinitions.R),\n  ((Reals.Rbasic_fun.Rabs (Reals.Rtrigo_def.sin x)) <= 1%R)%R.\nProof.\nintros x.\napply Abs.Abs_le.\napply SIN_bound.\nQed.\n\n(* Why3 goal *)\nLemma Cos_0 : ((Reals.Rtrigo_def.cos 0%R) = 1%R).\nProof.\napply cos_0.\nQed.\n\n(* Why3 goal *)\nLemma Sin_0 : ((Reals.Rtrigo_def.sin 0%R) = 0%R).\nProof.\napply sin_0.\nQed.\n\n(* Why3 comment *)\n(* pi is replaced with Reals.Rtrigo1.PI by the coq driver *)\n\n(* Why3 goal *)\nLemma Pi_double_precision_bounds :\n  ((7074237752028440 / 2251799813685248)%R < Reals.Rtrigo1.PI)%R /\\\n  (Reals.Rtrigo1.PI < (7074237752028441 / 2251799813685248)%R)%R.\nProof.\nreplace PI with (4 * (PI / 4))%R by field.\nrewrite <- atan_1.\nadmit. (* to avoid a dependency on CoqInterval *)\n(*\nRequire Import Interval_tactic.\nsplit ; interval with (i_prec 55). \n*)\nAdmitted.\n\n(* Why3 goal *)\nLemma Cos_pi : ((Reals.Rtrigo_def.cos Reals.Rtrigo1.PI) = (-1%R)%R).\nProof.\napply cos_PI.\nQed.\n\n(* Why3 goal *)\nLemma Sin_pi : ((Reals.Rtrigo_def.sin Reals.Rtrigo1.PI) = 0%R).\nProof.\napply sin_PI.\nQed.\n\n(* Why3 goal *)\nLemma Cos_pi2 :\n  ((Reals.Rtrigo_def.cos ((5 / 10)%R * Reals.Rtrigo1.PI)%R) = 0%R).\nProof.\nreplace (5 / 10 * PI)%R with (PI / 2)%R by field.\napply cos_PI2.\nQed.\n\n(* Why3 goal *)\nLemma Sin_pi2 :\n  ((Reals.Rtrigo_def.sin ((5 / 10)%R * Reals.Rtrigo1.PI)%R) = 1%R).\nProof.\nreplace (5 / 10 * PI)%R with (PI / 2)%R by field.\napply sin_PI2.\nQed.\n\n(* Why3 goal *)\nLemma Cos_plus_pi :\n  forall (x:Reals.Rdefinitions.R),\n  ((Reals.Rtrigo_def.cos (x + Reals.Rtrigo1.PI)%R) =\n   (-(Reals.Rtrigo_def.cos x))%R).\nProof.\nintros x.\napply neg_cos.\nQed.\n\n(* Why3 goal *)\nLemma Sin_plus_pi :\n  forall (x:Reals.Rdefinitions.R),\n  ((Reals.Rtrigo_def.sin (x + Reals.Rtrigo1.PI)%R) =\n   (-(Reals.Rtrigo_def.sin x))%R).\nProof.\nintros x.\napply neg_sin.\nQed.\n\n(* Why3 goal *)\nLemma Cos_plus_pi2 :\n  forall (x:Reals.Rdefinitions.R),\n  ((Reals.Rtrigo_def.cos (x + ((5 / 10)%R * Reals.Rtrigo1.PI)%R)%R) =\n   (-(Reals.Rtrigo_def.sin x))%R).\nProof.\nintros x.\nrewrite cos_sin.\nreplace (PI / 2 + (x + 5 / 10 * PI))%R with (x + PI)%R by field.\napply neg_sin.\nQed.\n\n(* Why3 goal *)\nLemma Sin_plus_pi2 :\n  forall (x:Reals.Rdefinitions.R),\n  ((Reals.Rtrigo_def.sin (x + ((5 / 10)%R * Reals.Rtrigo1.PI)%R)%R) =\n   (Reals.Rtrigo_def.cos x)).\nProof.\nintros x.\nrewrite cos_sin.\napply f_equal.\nfield.\nQed.\n\n(* Why3 goal *)\nLemma Cos_neg :\n  forall (x:Reals.Rdefinitions.R),\n  ((Reals.Rtrigo_def.cos (-x)%R) = (Reals.Rtrigo_def.cos x)).\nProof.\nintros x.\napply cos_neg.\nQed.\n\n(* Why3 goal *)\nLemma Sin_neg :\n  forall (x:Reals.Rdefinitions.R),\n  ((Reals.Rtrigo_def.sin (-x)%R) = (-(Reals.Rtrigo_def.sin x))%R).\nProof.\nintros x.\napply sin_neg.\nQed.\n\n(* Why3 goal *)\nLemma Cos_sum :\n  forall (x:Reals.Rdefinitions.R) (y:Reals.Rdefinitions.R),\n  ((Reals.Rtrigo_def.cos (x + y)%R) =\n   (((Reals.Rtrigo_def.cos x) * (Reals.Rtrigo_def.cos y))%R -\n    ((Reals.Rtrigo_def.sin x) * (Reals.Rtrigo_def.sin y))%R)%R).\nProof.\nintros x y.\napply cos_plus.\nQed.\n\n(* Why3 goal *)\nLemma Sin_sum :\n  forall (x:Reals.Rdefinitions.R) (y:Reals.Rdefinitions.R),\n  ((Reals.Rtrigo_def.sin (x + y)%R) =\n   (((Reals.Rtrigo_def.sin x) * (Reals.Rtrigo_def.cos y))%R +\n    ((Reals.Rtrigo_def.cos x) * (Reals.Rtrigo_def.sin y))%R)%R).\nProof.\nintros x y.\napply sin_plus.\nQed.\n\n(* Why3 goal *)\nLemma tan_def :\n  forall (x:Reals.Rdefinitions.R),\n  ((Reals.Rtrigo1.tan x) =\n   ((Reals.Rtrigo_def.sin x) / (Reals.Rtrigo_def.cos x))%R).\nProof.\nintros x.\napply eq_refl.\nQed.\n\n(* Why3 comment *)\n(* atan is replaced with (Reals.Ratan.atan x) by the coq driver *)\n\n(* Why3 goal *)\nLemma Tan_atan :\n  forall (x:Reals.Rdefinitions.R),\n  ((Reals.Rtrigo1.tan (Reals.Ratan.atan x)) = x).\nProof.\nintros x.\napply atan_right_inv.\nQed.\n\n", "meta": {"author": "schrodibear", "repo": "why3", "sha": "9f8eb767380987a28e43b81729ae1d682363bb49", "save_path": "github-repos/coq/schrodibear-why3", "path": "github-repos/coq/schrodibear-why3/why3-9f8eb767380987a28e43b81729ae1d682363bb49/lib/coq/real/Trigonometry.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6817341906427089}}
{"text": "Require Export SpecSyntax.\nSet Implicit Arguments.\n\n(******************************************************************************)\n(* Shifting                                                                   *)\n(******************************************************************************)\n\nFixpoint tshiftIndex (c : hnat) (i : nat) : nat :=\n  match c , i with\n    | HO    , _   => S i\n    | HSm c , _   => tshiftIndex c i\n    | HSy c , O   => O\n    | HSy c , S i => S (tshiftIndex c i)\n  end.\n\nFixpoint tshiftTy (c : hnat) (T : Ty) : Ty :=\n  match T with\n    | tvar X     => tvar (tshiftIndex c X)\n    | tarr T1 T2 => tarr (tshiftTy c T1) (tshiftTy c T2)\n    | tall T     => tall (tshiftTy (HSy c) T)\n    | texist T   => texist (tshiftTy (HSy c) T)\n    | tprod T1 T2 => tprod (tshiftTy c T1) (tshiftTy c T2)\n  end.\n\nFixpoint tshiftTm (c : hnat) (t : Tm) : Tm :=\n  match t with\n  | var x         => var x\n  | abs T1 t2     => abs (tshiftTy c T1) (tshiftTm (HSm c) t2)\n  | app t1 t2     => app (tshiftTm c t1) (tshiftTm c t2)\n  | tabs t2       => tabs (tshiftTm (HSy c) t2)\n  | tapp t1 T2    => tapp (tshiftTm c t1) (tshiftTy c T2)\n  | pack T1 t T2  => pack (tshiftTy c T1) (tshiftTm c t) (tshiftTy c T2)\n  | unpack t1 t2  => unpack (tshiftTm c t1) (tshiftTm (HSm (HSy c)) t2)\n  | prod t1 t2    => prod (tshiftTm c t1) (tshiftTm c t2)\n  | case t1 p t2  => case (tshiftTm c t1) p (tshiftTm (c + bindPat p) t2)\n  end.\n\nFixpoint shiftIndex (c : hnat) (i : nat) : nat :=\n  match c , i  with\n    | HO    , _   => S i\n    | HSm c , O   => O\n    | HSm c , S i => S (shiftIndex c i)\n    | HSy c , _   => shiftIndex c i\n  end.\n\nFixpoint shiftTm (c : hnat) (t : Tm) : Tm :=\n  match t with\n  | var x        => var (shiftIndex c x)\n  | abs T1 t2    => abs T1 (shiftTm (HSm c) t2)\n  | app t1 t2    => app (shiftTm c t1) (shiftTm c t2)\n  | tabs t2      => tabs (shiftTm (HSy c) t2)\n  | tapp t1 T2   => tapp (shiftTm c t1) T2\n  | pack T1 t T2  => pack T1 (shiftTm c t) T2\n  | unpack t1 t2  => unpack (shiftTm c t1) (shiftTm (HSm (HSy c)) t2)\n  | prod t1 t2   => prod (shiftTm c t1) (shiftTm c t2)\n  | case t1 p t2 => case (shiftTm c t1) p (shiftTm (hplus c (bindPat p)) t2)\n  end.\n\nFixpoint weakenTm (t : Tm) (k : hnat) : Tm :=\n  match k with\n    | HO    => t\n    | HSm k => shiftTm HO (weakenTm t k)\n    | HSy k => tshiftTm HO (weakenTm t k)\n  end.\n\nFixpoint weakenTy (T : Ty) (k : hnat) : Ty :=\n  match k with\n    | HO    => T\n    | HSm k => weakenTy T k\n    | HSy k => tshiftTy HO (weakenTy T k)\n  end.\n\n(******************************************************************************)\n(* Type substitution.                                                         *)\n(******************************************************************************)\n\nFixpoint tsubstIndex (X : hnat) (T' : Ty) (Y : nat) : Ty :=\n  match X , Y with\n    | HO    , O   => T'\n    | HO    , S Y => tvar Y\n    | HSm X , Y   => tsubstIndex X T' Y\n    | HSy X , O   => tvar O\n    | HSy X , S Y => tshiftTy HO (tsubstIndex X T' Y)\n  end.\n\nFixpoint tsubstTy (X : hnat) (T' : Ty) (T : Ty) : Ty :=\n  match T with\n    | tvar Y      => tsubstIndex X T' Y\n    | tarr T1 T2  => tarr (tsubstTy X T' T1) (tsubstTy X T' T2)\n    | tall T      => tall (tsubstTy (HSy X) T' T)\n    | texist T    => texist (tsubstTy (HSy X) T' T)\n    | tprod T1 T2 => tprod (tsubstTy X T' T1) (tsubstTy X T' T2)\n  end.\n\nFixpoint tsubstTm (X : hnat) (T' : Ty) (t : Tm) : Tm :=\n  match t with\n  | var x         => var x\n  | abs T1 t2     => abs  (tsubstTy X T' T1) (tsubstTm (HSm X) T' t2)\n  | app t1 t2     => app  (tsubstTm X T' t1) (tsubstTm X T' t2)\n  | tabs t2       => tabs (tsubstTm (HSy X) T' t2)\n  | tapp t1 T2    => tapp (tsubstTm X T' t1) (tsubstTy X T' T2)\n  | pack T1 t T2  => pack (tsubstTy X T' T1) (tsubstTm X T' t) (tsubstTy X T' T2)\n  | unpack t1 t2  => unpack (tsubstTm X T' t1) (tsubstTm (HSm (HSy X)) T' t2)\n  | prod t1 t2    => prod (tsubstTm X T' t1) (tsubstTm X T' t2)\n  | case t1 p t2  => case (tsubstTm X T' t1) p\n                       (tsubstTm (hplus X (bindPat p)) T' t2)\n  end.\n\n(******************************************************************************)\n(* Term substitutions.                                                        *)\n(******************************************************************************)\n\nFixpoint substIndex (x : hnat) (t : Tm) (y : nat) : Tm :=\n  match x , y with\n    | HO    , O   => t\n    | HO    , S y => var y\n    | HSm x , O   => var O\n    | HSm x , S y => shiftTm HO (substIndex x t y)\n    | HSy x , y   => tshiftTm HO (substIndex x t y)\n  end.\n\nFixpoint substTm (x : hnat) (t' : Tm) (t : Tm) : Tm :=\n  match t with\n    | var y        => substIndex x t' y\n    | abs T1 t2    => abs T1 (substTm (HSm x) t' t2)\n    | app t1 t2    => app (substTm x t' t1) (substTm x t' t2)\n    | tabs t2      => tabs (substTm (HSy x) t' t2)\n    | tapp t1 T2   => tapp (substTm x t' t1) T2\n    | pack T1 t T2 => pack T1 (substTm x t' t) T2\n    | unpack t1 t2 => unpack (substTm x t' t1) (substTm (HSm (HSy x)) t' t2)\n    | prod t1 t2   => prod (substTm x t' t1) (substTm x t' t2)\n    | case t1 p t2 => case (substTm x t' t1) p\n                        (substTm (hplus x (bindPat p)) t' t2)\n  end.\n\n(******************************************************************************)\n(* Context extensions.                                                        *)\n(******************************************************************************)\n\nFixpoint append (Δ1 Δ2 : Env) : Env :=\n  match Δ2 with\n    | empty     => Δ1\n    | evar Δ2 T => evar (append Δ1 Δ2) T\n    | etvar Δ2  => etvar (append Δ1 Δ2)\n  end.\n\nFixpoint dom (Δ : Env) : hnat :=\n  match Δ with\n    | empty    => HO\n    | evar Δ _ => HSm (dom Δ)\n    | etvar Δ  => HSy (dom Δ)\n  end.\n\nFixpoint tshiftEnv (c : hnat) (Δ : Env) : Env :=\n  match Δ with\n    | empty     => empty\n    | evar Δ T  => evar (tshiftEnv c Δ) (tshiftTy (c + dom Δ) T)\n    | etvar Δ   => etvar (tshiftEnv c Δ)\n  end.\n\nFixpoint tsubstEnv (X : hnat) (T' : Ty) (Δ : Env) : Env :=\n  match Δ with\n    | empty    => empty\n    | evar Δ T => evar (tsubstEnv X T' Δ) (tsubstTy (X + dom Δ) T' T)\n    | etvar Δ  => etvar (tsubstEnv X T' Δ)\n  end.\n\n(******************************************************************************)\n(* Context lookups.                                                           *)\n(******************************************************************************)\n\nInductive lookup_etvar : Env → nat → Prop :=\n  | lookup_etvar_here {Γ} :\n      lookup_etvar (etvar Γ) O\n  | lookup_etvar_there_evar {Γ T X} :\n      lookup_etvar Γ X →\n      lookup_etvar (evar Γ T) X\n  | lookup_etvar_there_etvar {Γ X} :\n      lookup_etvar Γ X →\n      lookup_etvar (etvar Γ) (S X).\nHint Constructors lookup_etvar.\n\nInductive lookup_evar : Env → nat → Ty → Prop :=\n  | lookup_evar_here {Γ T} :\n      lookup_evar (evar Γ T) O T\n  | lookup_evar_there_evar {Γ T T' X} :\n      lookup_evar Γ X T →\n      lookup_evar (evar Γ T') (S X) T\n  | lookup_evar_there_etvar {Γ T X} :\n      lookup_evar Γ X T →\n      lookup_evar (etvar Γ) X (tshiftTy HO T).\nHint Constructors lookup_evar.\n\n(******************************************************************************)\n(* Well-formed types.                                                         *)\n(******************************************************************************)\n\nInductive wfTy : Env → Ty → Prop :=\n  | wf_tvar {Γ X} :\n      lookup_etvar Γ X → wfTy Γ (tvar X)\n  | wf_tarr {Γ T1 T2} :\n      wfTy Γ T1 → wfTy Γ T2 → wfTy Γ (tarr T1 T2)\n  | wf_tall {Γ T} :\n      wfTy (etvar Γ) T → wfTy Γ (tall T)\n  | wf_texist {Γ T} :\n      wfTy (etvar Γ) T → wfTy Γ (texist T).\nHint Constructors wfTy.\n", "meta": {"author": "Blaisorblade", "repo": "knot-esop-2017-case-study", "sha": "cf541cb38a483a514474f4c948bf005bc49b1e6f", "save_path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study", "path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study/knot-esop-2017-case-study-cf541cb38a483a514474f4c948bf005bc49b1e6f/casestudy/manual/fexistsprod/BoilerplateFunctions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6817341835054516}}
{"text": "From Coq Require Import QArith Qround.\n\nRequire Arith2.\n\nLemma Q_floor_via_Z (a: Z) (b: positive):\n  Qfloor (a # b) = (a / Zpos b)%Z.\nProof.\nrewrite Zdiv_Qdiv.\nrewrite Qmake_Qdiv.\ntrivial.\nQed.\n\nLemma Q_ceiling_via_Z (a: Z) (b: positive):\n  Qceiling (a # b) = (- ((- a) / Zpos b))%Z.\nProof.\nunfold Qround.Qceiling.\nrewrite Qmake_Qdiv.\nrewrite Zdiv_Qdiv.\nrewrite inject_Z_opp.\nf_equal. f_equal.\nunfold Qdiv. unfold Qmult. cbn.\nrepeat rewrite Z.mul_1_r.\ntrivial.\nQed.\n\nLemma Q_ceiling_via_Z_floor (a: Z) (b: positive):\n  Qceiling (a # b) = ((a + Z.pos b - 1) / Zpos b)%Z.\nProof.\nrewrite Q_ceiling_via_Z.\napply Arith2.Z_ceiling_via_floor.\nrewrite<- Z.leb_le.\ntrivial.\nQed.", "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/QArith2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6817296724703409}}
{"text": "From stars Require Import definitions.\n\nLtac lift_distr H := intros x y z; symmetry; apply H.\nLtac auto_resolve := repeat split; c.\n\n(*** Arithmetic of Boolean logic. *)\nSection Boolean.\n\nGlobal Instance : Equiv bool := eq.\nGlobal Instance : Zero bool := false.\nGlobal Instance : One bool := true.\nGlobal Instance : Add bool := orb.\nGlobal Instance : Mul bool := andb.\nGlobal Instance : Star bool := λ _, 1.\n\nGlobal Instance : Kleene_Algebra bool.\nProof. repeat split; repeat intros []; cbn; done. Qed.\n\nEnd Boolean.\n\n(*** Arithmetic of Peano numbers. *)\nSection Natural.\n\nGlobal Instance : Equiv nat := eq.\nGlobal Instance : Zero nat := 0%nat.\nGlobal Instance : One nat := 1%nat.\nGlobal Instance : Join nat := Nat.max.\nGlobal Instance : Meet nat := Nat.min.\nGlobal Instance : Add nat := Nat.add.\nGlobal Instance : Mul nat := Nat.mul.\n\nGlobal Instance : Assoc (=) max := Nat.max_assoc.\nGlobal Instance : Assoc (=) min := Nat.min_assoc.\nGlobal Instance : Assoc (=) add := Nat.add_assoc.\nGlobal Instance : Assoc (=) mul := Nat.mul_assoc.\n\nGlobal Instance : Comm (=) max := Nat.max_comm.\nGlobal Instance : Comm (=) min := Nat.min_comm.\nGlobal Instance : Comm (=) add := Nat.add_comm.\nGlobal Instance : Comm (=) mul := Nat.mul_comm.\n\nGlobal Instance : IdemP (=) max := Nat.max_id.\nGlobal Instance : IdemP (=) min := Nat.min_id.\nGlobal Instance : Absorb (=) max min := Nat.min_max_absorption.\nGlobal Instance : Absorb (=) min max := Nat.max_min_absorption.\n\nGlobal Instance : LeftId (=) 0 max := Nat.max_0_l.\nGlobal Instance : RightId (=) 0 max := Nat.max_0_r.\nGlobal Instance : LeftId (=) 0 add := Nat.add_0_l.\nGlobal Instance : RightId (=) 0 add := Nat.add_0_r.\nGlobal Instance : LeftId (=) 1 mul := Nat.mul_1_l.\nGlobal Instance : RightId (=) 1 mul := Nat.mul_1_r.\n\nGlobal Instance : LeftAbsorb (=) 0 min := Nat.min_0_l.\nGlobal Instance : RightAbsorb (=) 0 min := Nat.min_0_r.\nGlobal Instance : LeftAbsorb (=) 0 mul := Nat.mul_0_l.\nGlobal Instance : RightAbsorb (=) 0 mul := Nat.mul_0_r.\n\nGlobal Instance : LeftDistr (=) mul add := Nat.mul_add_distr_l.\nGlobal Instance : RightDistr (=) mul add := Nat.mul_add_distr_r.\nGlobal Instance : LeftDistr (=) add min. lift_distr Nat.add_min_distr_l. Qed.\nGlobal Instance : RightDistr (=) add min. lift_distr Nat.add_min_distr_r. Qed.\nGlobal Instance : LeftDistr (=) add min. lift_distr Nat.add_min_distr_l. Qed.\nGlobal Instance : RightDistr (=) add min. lift_distr Nat.add_min_distr_r. Qed.\n\nGlobal Instance : Lattice nat. auto_resolve. Qed.\nGlobal Instance : Semiring nat. auto_resolve. Qed.\n\nEnd Natural.\n\n(*** Arithmetic of binary numbers. *)\nSection Positive.\n\nGlobal Instance : Equiv N := eq.\nGlobal Instance : Zero N := 0%N.\nGlobal Instance : One N := 1%N.\nGlobal Instance : Join N := N.max.\nGlobal Instance : Meet N := N.min.\nGlobal Instance : Add N := N.add.\nGlobal Instance : Mul N := N.mul.\n\nGlobal Instance : Assoc (=) join := N.max_assoc.\nGlobal Instance : Assoc (=) meet := N.min_assoc.\nGlobal Instance : Assoc (=) add := N.add_assoc.\nGlobal Instance : Assoc (=) mul := N.mul_assoc.\n\nGlobal Instance : Comm (=) join := N.max_comm.\nGlobal Instance : Comm (=) meet := N.min_comm.\nGlobal Instance : Comm (=) add := N.add_comm.\nGlobal Instance : Comm (=) mul := N.mul_comm.\n\nGlobal Instance : IdemP (=) join := N.max_id.\nGlobal Instance : IdemP (=) meet := N.min_id.\nGlobal Instance : Absorb (=) join meet := N.min_max_absorption.\nGlobal Instance : Absorb (=) meet join := N.max_min_absorption.\n\nGlobal Instance : LeftId (=) 0 join := N.max_0_l.\nGlobal Instance : RightId (=) 0 join := N.max_0_r.\nGlobal Instance : LeftId (=) 0 add := N.add_0_l.\nGlobal Instance : RightId (=) 0 add := N.add_0_r.\nGlobal Instance : LeftId (=) 1 mul := N.mul_1_l.\nGlobal Instance : RightId (=) 1 mul := N.mul_1_r.\n\nGlobal Instance : LeftAbsorb (=) 0 meet := N.min_0_l.\nGlobal Instance : RightAbsorb (=) 0 meet := N.min_0_r.\nGlobal Instance : LeftAbsorb (=) 0 mul := N.mul_0_l.\nGlobal Instance : RightAbsorb (=) 0 mul := N.mul_0_r.\n\nGlobal Instance : LeftDistr (=) mul add := N.mul_add_distr_l.\nGlobal Instance : RightDistr (=) mul add := N.mul_add_distr_r.\nGlobal Instance : LeftDistr (=) add meet. lift_distr N.add_min_distr_l. Qed.\nGlobal Instance : RightDistr (=) add meet. lift_distr N.add_min_distr_r. Qed.\nGlobal Instance : LeftDistr (=) add meet. lift_distr N.add_min_distr_l. Qed.\nGlobal Instance : RightDistr (=) add meet. lift_distr N.add_min_distr_r. Qed.\n\nGlobal Instance : Lattice N. auto_resolve. Qed.\nGlobal Instance : Semiring N. auto_resolve. Qed.\n\nEnd Positive.\n\n(*** Arithmetic of rational numbers. *)\nSection Rational.\n\nCoercion inject_Z : Z >-> Q.\n\nGlobal Instance : Equiv Q := Qeq.\nGlobal Instance : Zero Q := 0%Z.\nGlobal Instance : One Q := 1%Z.\nGlobal Instance : Add Q := Qplus.\nGlobal Instance : Mul Q := Qmult.\n\nGlobal Instance : RelDecision Qeq := Qeq_dec.\nGlobal Instance : Assoc (≡) add := Qplus_assoc.\nGlobal Instance : Assoc (≡) mul := Qmult_assoc.\nGlobal Instance : Comm (≡) add := Qplus_comm.\nGlobal Instance : Comm (≡) mul := Qmult_comm.\nGlobal Instance : LeftId (≡) 0 add := Qplus_0_l.\nGlobal Instance : RightId (≡) 0 add := Qplus_0_r.\nGlobal Instance : LeftId (≡) 1 mul := Qmult_1_l.\nGlobal Instance : RightId (≡) 1 mul := Qmult_1_r.\nGlobal Instance : LeftAbsorb (≡) 0 mul := Qmult_0_l.\nGlobal Instance : RightAbsorb (≡) 0 mul := Qmult_0_r.\nGlobal Instance : LeftDistr (≡) mul add := Qmult_plus_distr_r.\nGlobal Instance : RightDistr (≡) mul add := Qmult_plus_distr_l.\nGlobal Instance : Semiring Q. auto_resolve. Qed.\n\nEnd Rational.\n\n(*** Arithmetic of minimum and addition. *)\n(* Tropical is a reference to the climate of Brazil, where Imre Simon lived. *)\n(* Imre Simon (1943-2009) founded the topic of tropical mathematics. *)\nSection Tropical.\n\nVariable X : Type.\nContext `{Equiv X, Equivalence X (≡), Meet X, Add X, Zero X}.\nContext `{Semilattice X (≡) meet, Monoid X (≡) add 0}.\nContext `{LeftAbsorb X (≡) 0 meet, RightAbsorb X (≡) 0 meet}.\nContext `{LeftDistr X (≡) add meet, RightDistr X (≡) add meet}.\n\nInductive trop := Tropical (x : X) | TInfinity.\n\nGlobal Instance : Equiv trop := λ a b,\n  match a, b with\n  | Tropical x, Tropical y => x ≡ y\n  | TInfinity, TInfinity => True\n  | _, _ => False\n  end.\n\nGlobal Instance : Infinity trop := TInfinity.\nGlobal Instance : Zero trop := TInfinity.\nGlobal Instance : One trop := Tropical 0.\n\nGlobal Instance : Add trop :=\n  λ a b, match a, b with\n  | TInfinity, _ => b\n  | _, TInfinity => a\n  | Tropical x, Tropical y => Tropical (x ∧ y)\n  end.\n\nGlobal Instance : Mul trop :=\n  λ a b, match a, b with\n  | TInfinity, _ => TInfinity\n  | _, TInfinity => TInfinity\n  | Tropical x, Tropical y => Tropical (x + y)\n  end.\n\nGlobal Instance trop_star : Star trop :=\n  λ _, 1.\n\nGlobal Instance : Kleene_Algebra trop.\nProof.\nrepeat split.\n4,9: intros [] [] A [] [] B; cbn in *; try done; rewrite A, B; done.\nall: repeat intros []; cbn; try done; f_equal. apply Equivalence_Transitive.\napply (assoc meet). apply (comm meet). apply (assoc add).\napply (left_id 0 add). apply (right_id 0 add). apply (idemp meet).\n1,2: rewrite (left_id 0 add); intros; apply (idemp meet).\n1,2: rewrite (right_id 0 add); intros; apply (idemp meet).\nQed.\n\nEnd Tropical.\n\nArguments Tropical {_}.\nArguments TInfinity {_}.\n\n(*** One-point compactification of the rational numbers. *)\nSection Compact.\n\nInductive frac :=\n  | Frac (q : Q)\n  | Inf.\n\nCoercion Frac : Q >-> frac.\n\nGlobal Instance : Equiv frac := λ x y,\n  match x, y with\n  | Frac p, Frac q => p == q\n  | Inf, Inf => True\n  | _, _ => False\n  end.\n\nGlobal Instance : Infinity frac := Inf.\nGlobal Instance : Zero frac := 0%Z.\nGlobal Instance : One frac := 1%Z.\n\nDefinition frac_simplify (x : frac) :=\n  match x with\n  | Inf => Inf\n  | Frac p => Frac (Qred p)\n  end.\n\nDefinition frac_add (x y : frac) : frac :=\n  match x, y with\n  | Inf, _ => Inf\n  | _, Inf => Inf\n  | Frac p, Frac q => (p + q)%Q\n  end.\n\nDefinition frac_mul (x y : frac) : frac :=\n  match x, y with\n  | Frac (0 # _), Inf => 0\n  | Inf, Frac (0 # _) => 0\n  | Inf, _ => Inf\n  | _, Inf => Inf\n  | Frac p, Frac q => (p * q)%Q\n  end.\n\nGlobal Instance add_frac : Add frac := λ x y, frac_simplify (frac_add x y).\nGlobal Instance mul_frac : Mul frac := λ x y, frac_simplify (frac_mul x y).\n\nGlobal Instance : Star frac := λ x,\n  match x with\n  | Frac ((Z.pos m # n) as p) =>\n    if Pos.eqb m n then Inf else Qred (/(1 - p))\n  | Frac p => Qred (/(1 - p))\n  | Inf => Inf\n  end.\n\nGlobal Instance : Equivalence (≡).\nProof.\nsplit.\n- intros []; done.\n- intros [] [] H; done.\n- intros [] [] [] H H'; try done; cbn; trans q0; done.\nQed.\n\nGlobal Instance : RelDecision (≡).\nProof.\nintros [p|] [q|]. apply (decide (p ≡ q)).\n1,2: right; intro H; done. left; done.\nQed.\n\n(***\nThe general proof strategy is as follows:\n1. [_intros] Destruct frac values (Inf, 0, positive and negative rationals).\n2. [_unwrap] Unfold add and mul, and remove frac_simplify.\n3. [_reduce, _simpl] Rewrite with Inf reductions, or evaluate the term.\n*)\n\nLtac _intro := let i := fresh \"i\" in intros [[[] i]|].\nLtac _intros := repeat (_intro || let H := fresh \"H\" in intro H).\n\nLocal Lemma zero_frac i : 0 # i ≡ zero.\nProof. apply Qreduce_zero. Qed.\n\nLocal Lemma frac_simplify_id x : frac_simplify x ≡ x.\nProof. destruct x. apply Qred_correct. done. Qed.\n\nLocal Lemma _red_0 x : frac_add Inf x = Inf. done. Qed.\nLocal Lemma _red_1 x : frac_add x Inf = Inf. revert x; _intro; done. Qed.\nLocal Lemma _red_2 i j : frac_mul Inf (Z.pos i # j) = Inf. done. Qed.\nLocal Lemma _red_3 i j : frac_mul Inf (Z.neg i # j) = Inf. done. Qed.\nLocal Lemma _red_4 i j : frac_mul (Z.pos i # j) Inf = Inf. done. Qed.\nLocal Lemma _red_5 i j : frac_mul (Z.neg i # j) Inf = Inf. done. Qed.\n\nLtac _unwrap := unfold add, add_frac, mul, mul_frac; rewrite ?frac_simplify_id.\nLtac _red_step := rewrite ?_red_0, ?_red_1, ?_red_2, ?_red_3, ?_red_4, ?_red_5.\nLtac _reduce := rewrite ?zero_frac; repeat _red_step.\nLtac _simpl := cbn in *; try done.\n\nSection Morphisms.\n\nLemma frac_add_hom p q : frac_add (Frac p) (Frac q) ≡ Frac (p + q)%Q.\nProof. done. Qed.\n\nLemma frac_mul_hom p q : frac_mul (Frac p) (Frac q) ≡ Frac (p * q)%Q.\nProof. destruct p as [[] i], q as [[] j]; done. Qed.\n\nLemma add_frac_hom p q : Frac p + Frac q ≡ Frac (p + q)%Q.\nProof. _unwrap; apply frac_add_hom. Qed.\n\nLemma mul_frac_hom p q : Frac p * Frac q ≡ Frac (p * q)%Q.\nProof. _unwrap; apply frac_mul_hom. Qed.\n\nGlobal Instance : Proper ((≡) ==> (≡)) Frac.\nProof. intros x y H; done. Qed.\n\nGlobal Instance proper_frac_simplify : Proper ((≡) ==> (≡)) frac_simplify.\nProof. intros x y H; rewrite ?frac_simplify_id; done. Qed.\n\nGlobal Instance proper_frac_add : Proper ((≡) ==> (≡) ==> (≡)) frac_add.\nProof. _intros; _simpl; apply Qplus_comp; done. Qed.\n\nGlobal Instance proper_frac_mul : Proper ((≡) ==> (≡) ==> (≡)) frac_mul.\nProof. _intros; _simpl; apply Qmult_comp; done. Qed.\n\nLtac lift_proper H := repeat intros ?; apply proper_frac_simplify, H; done. \n\nGlobal Instance : Proper ((≡) ==> (≡) ==> (≡)) add.\nProof. lift_proper proper_frac_add. Qed.\n\nGlobal Instance : Proper ((≡) ==> (≡) ==> (≡)) mul.\nProof. lift_proper proper_frac_mul. Qed.\n\nGlobal Instance : Proper ((≡) ==> (≡)) star.\nProof.\n_intros; _simpl; try (rewrite H; done).\ndestruct (p =? i)%positive eqn:E.\n- apply Pos.eqb_eq in E; subst. unfold Qeq in H; cbn in H.\n  rewrite Z.mul_comm in H; apply Z.mul_cancel_r, Zpos_eq_iff in H; subst.\n  rewrite Pos.eqb_refl; done. done.\n- apply Pos.eqb_neq in E; destruct (p0 =? i0)%positive eqn:E0.\n  apply Pos.eqb_eq in E0; subst. unfold Qeq in H; cbn in H.\n  rewrite Z.mul_comm in H; apply Z.mul_cancel_l, Zpos_eq_iff in H; subst; done.\n  cbn; rewrite H; done.\nQed.\n\nEnd Morphisms.\n\nLtac _transfer := repeat (rewrite ?frac_add_hom, ?frac_mul_hom).\nLtac lift_Qplus H := repeat intros []; _unwrap; _reduce; try done; apply H.\nLtac lift_Qmult H := _intros; _unwrap; _reduce; try done; apply H.\n\nGlobal Instance : Assoc (≡) add. lift_Qplus Qplus_assoc. Qed.\nGlobal Instance : Comm (≡) add. lift_Qplus Qplus_comm. Qed.\nGlobal Instance : Comm (≡) mul. lift_Qmult Qmult_comm. Qed.\nGlobal Instance : LeftId (≡) 0 add. lift_Qplus Qplus_0_l. Qed.\nGlobal Instance : RightId (≡) 0 add. lift_Qplus Qplus_0_r. Qed.\nGlobal Instance : LeftId (≡) 1 mul. lift_Qmult Qmult_1_l. Qed.\nGlobal Instance : RightId (≡) 1 mul. lift_Qmult Qmult_1_r. Qed.\nGlobal Instance : LeftAbsorb (≡) 0 mul. lift_Qmult Qmult_0_l. Qed.\nGlobal Instance : RightAbsorb (≡) 0 mul. lift_Qmult Qmult_0_r. Qed.\n\nGlobal Instance : Assoc (≡) mul.\nProof.\nintros x y z; _unwrap; revert x y z.\n_intros; _reduce; try done; apply Qmult_assoc.\nQed.\n\nGlobal Instance : LeftDistr (≡) mul add.\nProof.\nintros x y z; _unwrap; revert x y z.\n_intros; _reduce; _transfer; try done; try apply Qmult_plus_distr_r.\n(* If x = ∞, y = 1, z = -1, then the equality fails. *)\nAdmitted.\n\nGlobal Instance : RightDistr (≡) mul add.\nProof.\nintros x y z; _unwrap; revert x y z.\n_intros; _reduce; _transfer; try done; try apply Qmult_plus_distr_l.\n(* If x = 1, y = -1, z = ∞, then the equality fails. *)\nAdmitted.\n\nLemma star_frac_neq_1 q :\n  Frac q ≢ 1 -> (Frac q){*} ≡ /(1 - q).\nProof.\ndestruct q as [[] i]; intros; _simpl; try apply Qred_correct.\ndestruct (p =? i)%positive eqn:E. 2: apply Qred_correct.\nexfalso; apply H; apply Pos.eqb_eq in E; subst.\nunfold Qeq; cbn; apply Z.mul_comm.\nQed.\n\nLemma expand_star_frac q :\n  ¬ q == 1 -> / (1 - q) == 1 + q * / (1 - q).\nProof.\nintros Hq; rewrite <-Qmult_inv_r with (x:=(1 - q)%Q) at 2.\n- rewrite <-Qmult_plus_distr_l; unfold Qminus at 2.\n  rewrite <-Qplus_assoc, (Qplus_comm _ q).\n  rewrite Qplus_opp_r, Qplus_0_r, Qmult_1_l; done.\n- intros Hq'; apply Hq; unfold Qminus in Hq'.\n  symmetry; rewrite <-Qplus_0_r, <-Qplus_opp_r with (q:=q).\n  rewrite (Qplus_comm q), Qplus_assoc, Hq', Qplus_0_l; done.\nQed.\n\nGlobal Instance : Star_Semiring frac.\nProof.\nrepeat split; try c.\nall: intros []. 2,4: done.\nall: destruct (decide (Frac q ≡ 1)) as [->|Hq]. 1,3: done.\nall: rewrite (star_frac_neq_1 _ Hq). 2: rewrite (comm mul).\nall: rewrite (expand_star_frac _ Hq) at 1.\nall: rewrite <-add_frac_hom, <-mul_frac_hom; done.\nQed.\n\nEnd Compact.\n", "meta": {"author": "bergwerf", "repo": "star_semiring", "sha": "a321ef5d19ab1529c9c9e6410f9a4a930ae29fa0", "save_path": "github-repos/coq/bergwerf-star_semiring", "path": "github-repos/coq/bergwerf-star_semiring/star_semiring-a321ef5d19ab1529c9c9e6410f9a4a930ae29fa0/arithmetic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6815997019099155}}
{"text": "(* Copyright (c) 2006, 2011-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 Lia.\n\nRequire Import Cpdt.CpdtTactics Cpdt.Coinductive.\n\nRequire Extraction.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n(* end hide *)\n\n\n(** %\\chapter{General Recursion}% *)\n\n(** Termination of all programs is a crucial property of Gallina.  Non-terminating programs introduce logical inconsistency, where any theorem can be proved with an infinite loop.  Coq uses a small set of conservative, syntactic criteria to check termination of all recursive definitions.  These criteria are insufficient to support the natural encodings of a variety of important programming idioms.  Further, since Coq makes it so convenient to encode mathematics computationally, with functional programs, we may find ourselves wanting to employ more complicated recursion in mathematical definitions.\n\n   What exactly are the conservative criteria that we run up against?  For _recursive_ definitions, recursive calls are only allowed on _syntactic subterms_ of the original primary argument, a restriction known as%\\index{primitive recursion}% _primitive recursion_.  In fact, Coq's handling of reflexive inductive types (those defined in terms of functions returning the same type) gives a bit more flexibility than in traditional primitive recursion, but the term is still applied commonly.  In Chapter 5, we saw how _co-recursive_ definitions are checked against a syntactic guardedness condition that guarantees productivity.\n\n   Many natural recursion patterns satisfy neither condition.  For instance, there is our simple running example in this chapter, merge sort.  We will study three different approaches to more flexible recursion, and the latter two of the approaches will even support definitions that may fail to terminate on certain inputs, without any up-front characterization of which inputs those may be.\n\n   Before proceeding, it is important to note that the problem here is not as fundamental as it may appear.  The final example of Chapter 5 demonstrated what is called a%\\index{deep embedding}% _deep embedding_ of the syntax and semantics of a programming language.  That is, we gave a mathematical definition of a language of programs and their meanings.  This language clearly admitted non-termination, and we could think of writing all our sophisticated recursive functions with such explicit syntax types.  However, in doing so, we forfeit our chance to take advantage of Coq's very good built-in support for reasoning about Gallina programs.  We would rather use a%\\index{shallow embedding}% _shallow embedding_, where we model informal constructs by encoding them as normal Gallina programs.  Each of the three techniques of this chapter follows that style. *)\n\n\n(** * Well-Founded Recursion *)\n\n(** The essence of terminating recursion is that there are no infinite chains of nested recursive calls.  This intuition is commonly mapped to the mathematical idea of a%\\index{well-founded relation}% _well-founded relation_, and the associated standard technique in Coq is%\\index{well-founded recursion}% _well-founded recursion_.  The syntactic-subterm relation that Coq applies by default is well-founded, but many cases demand alternate well-founded relations.  To demonstrate, let us see where we get stuck on attempting a standard merge sort implementation. *)\n\nSection mergeSort.\n  Variable A : Type.\n  Variable le : A -> A -> bool.\n\n  (** We have a set equipped with some \"less-than-or-equal-to\" test. *)\n\n  (** A standard function inserts an element into a sorted list, preserving sortedness. *)\n\n  Fixpoint insert (x : A) (ls : list A) : list A :=\n    match ls with\n      | nil => x :: nil\n      | h :: ls' =>\n\tif le x h\n\t  then x :: ls\n\t  else h :: insert x ls'\n    end.\n\n  (** We will also need a function to merge two sorted lists.  (We use a less efficient implementation than usual, because the more efficient implementation already forces us to think about well-founded recursion, while here we are only interested in setting up the example of merge sort.) *)\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  (** The last helper function for classic merge sort is the one that follows, to split a list arbitrarily into two pieces of approximately equal length. *)\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\tlet (ls1, ls2) := split ls' in\n\t  (h1 :: ls1, h2 :: ls2)\n    end.\n\n  (** Now, let us try to write the final sorting function, using a natural number \"[<=]\" test [leb] from the standard library.\n[[\n  Fixpoint mergeSort (ls : list A) : list A :=\n    if leb (length ls) 1\n      then ls\n      else let lss := split ls in\n\tmerge (mergeSort (fst lss)) (mergeSort (snd lss)).\n]]\n\n<<\nRecursive call to mergeSort has principal argument equal to\n\"fst (split ls)\" instead of a subterm of \"ls\".\n>>\n\nThe definition is rejected for not following the simple primitive recursion criterion.  In particular, it is not apparent that recursive calls to [mergeSort] are syntactic subterms of the original argument [ls]; indeed, they are not, yet we know this is a well-founded recursive definition.\n\nTo produce an acceptable definition, we need to choose a well-founded relation and prove that [mergeSort] respects it.  A good starting point is an examination of how well-foundedness is formalized in the Coq standard library. *)\n\n  Print well_founded.\n  (** %\\vspace{-.15in}% [[\nwell_founded = \nfun (A : Type) (R : A -> A -> Prop) => forall a : A, Acc R a\n]]\n\nThe bulk of the definitional work devolves to the%\\index{accessibility relation}\\index{Gallina terms!Acc}% _accessibility_ relation [Acc], whose definition we may also examine. *)\n\n(* begin hide *)\n(* begin thide *)\nDefinition Acc_intro' := Acc_intro.\n(* end thide *)\n(* end hide *)\n\n  Print Acc.\n(** %\\vspace{-.15in}% [[\nInductive Acc (A : Type) (R : A -> A -> Prop) (x : A) : Prop :=\n    Acc_intro : (forall y : A, R y x -> Acc R y) -> Acc R x\n]]\n\nIn prose, an element [x] is accessible for a relation [R] if every element \"less than\" [x] according to [R] is also accessible.  Since [Acc] is defined inductively, we know that any accessibility proof involves a finite chain of invocations, in a certain sense that we can make formal.  Building on Chapter 5's examples, let us define a co-inductive relation that is closer to the usual informal notion of \"absence of infinite decreasing chains.\" *)\n\n  CoInductive infiniteDecreasingChain A (R : A -> A -> Prop) : stream A -> Prop :=\n  | ChainCons : forall x y s, infiniteDecreasingChain R (Cons y s)\n    -> R y x\n    -> infiniteDecreasingChain R (Cons x (Cons y s)).\n\n(** We can now prove that any accessible element cannot be the beginning of any infinite decreasing chain. *)\n\n(* begin thide *)\n  Lemma noBadChains' : forall A (R : A -> A -> Prop) x, Acc R x\n    -> forall s, ~infiniteDecreasingChain R (Cons x s).\n    induction 1; crush;\n      match goal with\n        | [ H : infiniteDecreasingChain _ _ |- _ ] => inversion H; eauto\n      end.\n  Qed.\n\n(** From here, the absence of infinite decreasing chains in well-founded sets is immediate. *)\n\n  Theorem noBadChains : forall A (R : A -> A -> Prop), well_founded R\n    -> forall s, ~infiniteDecreasingChain R s.\n    destruct s; apply noBadChains'; auto.\n  Qed.\n(* end thide *)\n\n(** Absence of infinite decreasing chains implies absence of infinitely nested recursive calls, for any recursive definition that respects the well-founded relation.  The [Fix] combinator from the standard library formalizes that intuition: *)\n\n  Check Fix.\n(** %\\vspace{-.15in}%[[\nFix\n     : forall (A : Type) (R : A -> A -> Prop),\n       well_founded R ->\n       forall P : A -> Type,\n       (forall x : A, (forall y : A, R y x -> P y) -> P x) ->\n       forall x : A, P x\n]]\n\nA call to %\\index{Gallina terms!Fix}%[Fix] must present a relation [R] and a proof of its well-foundedness.  The next argument, [P], is the possibly dependent range type of the function we build; the domain [A] of [R] is the function's domain.  The following argument has this type:\n[[\n       forall x : A, (forall y : A, R y x -> P y) -> P x\n]]\n\nThis is an encoding of the function body.  The input [x] stands for the function argument, and the next input stands for the function we are defining.  Recursive calls are encoded as calls to the second argument, whose type tells us it expects a value [y] and a proof that [y] is \"less than\" [x], according to [R].  In this way, we enforce the well-foundedness restriction on recursive calls.\n\nThe rest of [Fix]'s type tells us that it returns a function of exactly the type we expect, so we are now ready to use it to implement [mergeSort].  Careful readers may have noticed that [Fix] has a dependent type of the sort we met in the previous chapter.\n\nBefore writing [mergeSort], we need to settle on a well-founded relation.  The right one for this example is based on lengths of lists. *)\n\n  Definition lengthOrder (ls1 ls2 : list A) :=\n    length ls1 < length ls2.\n\n  (** We must prove that the relation is truly well-founded.  To save some space in the rest of this chapter, we skip right to nice, automated proof scripts, though we postpone introducing the principles behind such scripts to Part III of the book.  Curious readers may still replace semicolons with periods and newlines to step through these scripts interactively. *)\n\n  Hint Constructors Acc.\n\n  Lemma lengthOrder_wf' : forall len, forall ls, length ls <= len -> Acc lengthOrder ls.\n  Proof.\n    Admitted.\n    (* unfold lengthOrder; induction len; crush.\n  Defined. *)\n\n  Theorem lengthOrder_wf : well_founded lengthOrder.\n    red; intro; eapply lengthOrder_wf'; eauto.\n  Defined.\n\n  (** Notice that we end these proofs with %\\index{Vernacular commands!Defined}%[Defined], not [Qed].  Recall that [Defined] marks the theorems as %\\emph{%#<i>#transparent#</i>#%}%, so that the details of their proofs may be used during program execution.  Why could such details possibly matter for computation?  It turns out that [Fix] satisfies the primitive recursion restriction by declaring itself as _recursive in the structure of [Acc] proofs_.  This is possible because [Acc] proofs follow a predictable inductive structure.  We must do work, as in the last theorem's proof, to establish that all elements of a type belong to [Acc], but the automatic unwinding of those proofs during recursion is straightforward.  If we ended the proof with [Qed], the proof details would be hidden from computation, in which case the unwinding process would get stuck.\n\n     To justify our two recursive [mergeSort] calls, we will also need to prove that [split] respects the [lengthOrder] relation.  These proofs, too, must be kept transparent, to avoid stuckness of [Fix] evaluation.  We use the syntax [@foo] to reference identifier [foo] with its implicit argument behavior turned off.  (The proof details below use Ltac features not introduced yet, and they are safe to skip for now.) *)\n\n  Lemma split_wf : forall len ls, 2 <= length ls <= len\n    -> let (ls1, ls2) := split ls in\n      lengthOrder ls1 ls /\\ lengthOrder ls2 ls.\n    unfold lengthOrder; induction len; crush; do 2 (destruct ls; crush);\n      destruct (le_lt_dec 2 (length ls));\n        repeat (match goal with\n                  | [ _ : length ?E < 2 |- _ ] => destruct E\n                  | [ _ : S (length ?E) < 2 |- _ ] => destruct E\n                  | [ IH : _ |- context[split ?L] ] =>\n                    specialize (IH L); destruct (split L); destruct IH\n                end; crush).\n  Defined.\n\n  Ltac split_wf := intros ls ?; intros; generalize (@split_wf (length ls) ls);\n    destruct (split ls); destruct 1; crush.\n\n  Lemma split_wf1 : forall ls, 2 <= length ls\n    -> lengthOrder (fst (split ls)) ls.\n    split_wf.\n  Defined.\n\n  Lemma split_wf2 : forall ls, 2 <= length ls\n    -> lengthOrder (snd (split ls)) ls.\n    split_wf.\n  Defined.\n\n  Hint Resolve split_wf1 split_wf2.\n\n  (** To write the function definition itself, we use the %\\index{tactics!refine}%[refine] tactic as a convenient way to write a program that needs to manipulate proofs, without writing out those proofs manually.  We also use a replacement [le_lt_dec] for [leb] that has a more interesting dependent type.  (Note that we would not be able to complete the definition without this change, since [refine] will generate subgoals for the [if] branches based only on the _type_ of the test expression, not its _value_.) *)\n\n  Definition mergeSort : list A -> list A.\n(* begin thide *)\n    refine (Fix lengthOrder_wf (fun _ => list A)\n      (fun (ls : list A)\n        (mergeSort : forall ls' : list A, lengthOrder ls' ls -> list A) =>\n        if le_lt_dec 2 (length ls)\n\t  then let lss := split ls in\n            merge (mergeSort (fst lss) _) (mergeSort (snd lss) _)\n\t  else ls)); subst lss; eauto.\n  Defined.\n(* end thide *)\nEnd mergeSort.\n\n(** The important thing is that it is now easy to evaluate calls to [mergeSort]. *)\n\nEval compute in mergeSort leb (1 :: 2 :: 36 :: 8 :: 19 :: nil).\n(** [= 1 :: 2 :: 8 :: 19 :: 36 :: nil] *)\n\n(** %\\smallskip{}%Since the subject of this chapter is merely how to define functions with unusual recursion structure, we will not prove any further correctness theorems about [mergeSort]. Instead, we stop at proving that [mergeSort] has the expected computational behavior, for all inputs, not merely the one we just tested. *)\n\n(* begin thide *)\nTheorem mergeSort_eq : forall A (le : A -> A -> bool) ls,\n  mergeSort le ls = if le_lt_dec 2 (length ls)\n    then let lss := split ls in\n      merge le (mergeSort le (fst lss)) (mergeSort le (snd lss))\n    else ls.\n  intros; apply (Fix_eq (@lengthOrder_wf A) (fun _ => list A)); intros.\n\n  (** The library theorem [Fix_eq] imposes one more strange subgoal upon us.  We must prove that the function body is unable to distinguish between \"self\" arguments that map equal inputs to equal outputs.  One might think this should be true of any Gallina code, but in fact this general%\\index{extensionality}% _function extensionality_ property is neither provable nor disprovable within Coq.  The type of [Fix_eq] makes clear what we must show manually: *)\n\n  Check Fix_eq.\n(** %\\vspace{-.15in}%[[\nFix_eq\n     : forall (A : Type) (R : A -> A -> Prop) (Rwf : well_founded R)\n         (P : A -> Type)\n         (F : forall x : A, (forall y : A, R y x -> P y) -> P x),\n       (forall (x : A) (f g : forall y : A, R y x -> P y),\n        (forall (y : A) (p : R y x), f y p = g y p) -> F x f = F x g) ->\n       forall x : A,\n       Fix Rwf P F x = F x (fun (y : A) (_ : R y x) => Fix Rwf P F y)\n]]\n\n  Most such obligations are dischargeable with straightforward proof automation, and this example is no exception. *)\n\n  match goal with\n    | [ |- context[match ?E with left _ => _ | right _ => _ end] ] => destruct E\n  end; simpl; f_equal; auto.\nQed.\n(* end thide *)\n\n(** As a final test of our definition's suitability, we can extract to OCaml. *)\n\nExtraction mergeSort.\n\n(** <<\nlet rec mergeSort le x =\n  match le_lt_dec (S (S O)) (length x) with\n  | Left ->\n    let lss = split x in\n    merge le (mergeSort le (fst lss)) (mergeSort le (snd lss))\n  | Right -> x\n>>\n\n  We see almost precisely the same definition we would have written manually in OCaml!  It might be a good exercise for the reader to use the commands we saw in the previous chapter to clean up some remaining differences from idiomatic OCaml.\n\n  One more piece of the full picture is missing.  To go on and prove correctness of [mergeSort], we would need more than a way of unfolding its definition.  We also need an appropriate induction principle matched to the well-founded relation.  Such a principle is available in the standard library, though we will say no more about its details here. *)\n\nCheck well_founded_induction.\n(** %\\vspace{-.15in}%[[\nwell_founded_induction\n     : forall (A : Type) (R : A -> A -> Prop),\n       well_founded R ->\n       forall P : A -> Set,\n       (forall x : A, (forall y : A, R y x -> P y) -> P x) ->\n       forall a : A, P a\n]]\n\n  Some more recent Coq features provide more convenient syntax for defining recursive functions.  Interested readers can consult the Coq manual about the commands %\\index{Function}%[Function] and %\\index{Program Fixpoint}%[Program Fixpoint]. *)\n\n\n(** * A Non-Termination Monad Inspired by Domain Theory *)\n\n(** The key insights of %\\index{domain theory}%domain theory%~\\cite{WinskelDomains}% inspire the next approach to modeling non-termination.  Domain theory is based on _information orders_ that relate values representing computation results, according to how much information these values convey.  For instance, a simple domain might include values \"the program does not terminate\" and \"the program terminates with the answer 5.\"  The former is considered to be an _approximation_ of the latter, while the latter is _not_ an approximation of \"the program terminates with the answer 6.\"  The details of domain theory will not be important in what follows; we merely borrow the notion of an approximation ordering on computation results.\n\n   Consider this definition of a type of computations. *)\n\nSection computation.\n  Variable A : Type.\n  (** The type [A] describes the result a computation will yield, if it terminates.\n\n     We give a rich dependent type to computations themselves: *)\n\n  Definition computation :=\n    {f : nat -> option A\n      | forall (n : nat) (v : A),\n\tf n = Some v\n\t-> forall (n' : nat), n' >= n\n\t  -> f n' = Some v}.\n\n  (** A computation is fundamentally a function [f] from an _approximation level_ [n] to an optional result.  Intuitively, higher [n] values enable termination in more cases than lower values.  A call to [f] may return [None] to indicate that [n] was not high enough to run the computation to completion; higher [n] values may yield [Some].  Further, the proof obligation within the subset type asserts that [f] is _monotone_ in an appropriate sense: when some [n] is sufficient to produce termination, so are all higher [n] values, and they all yield the same program result [v].\n\n  It is easy to define a relation characterizing when a computation runs to a particular result at a particular approximation level. *)\n\n  Definition runTo (m : computation) (n : nat) (v : A) :=\n    proj1_sig m n = Some v.\n\n  (** On top of [runTo], we also define [run], which is the most abstract notion of when a computation runs to a value. *)\n\n  Definition run (m : computation) (v : A) :=\n    exists n, runTo m n v.\nEnd computation.\n\n(** The book source code contains at this point some tactics, lemma proofs, and hint commands, to be used in proving facts about computations.  Since their details are orthogonal to the message of this chapter, I have omitted them in the rendered version. *)\n(* begin hide *)\n\nHint Unfold runTo.\n\nLtac run' := unfold run, runTo in *; try red; crush;\n  repeat (match goal with\n            | [ _ : proj1_sig ?E _ = _ |- _ ] =>\n              match goal with\n                | [ x : _ |- _ ] =>\n                  match x with\n                    | E => destruct E\n                  end\n              end\n            | [ |- context[match ?M with exist _ _ => _ end] ] => let Heq := fresh \"Heq\" in\n              case_eq M; intros ? ? Heq; try rewrite Heq in *; try subst\n            | [ _ : context[match ?M with exist _ _ => _ end] |- _ ] => let Heq := fresh \"Heq\" in\n              case_eq M; intros ? ? Heq; try rewrite Heq in *; subst\n            | [ H : forall n v, ?E n = Some v -> _,\n                _ : context[match ?E ?N with Some _ => _ | None => _ end] |- _ ] =>\n              specialize (H N); destruct (E N); try rewrite (H _ (eq_refl _)) by auto; try discriminate\n            | [ H : forall n v, ?E n = Some v -> _, H' : ?E _ = Some _ |- _ ] => rewrite (H _ _ H') by auto\n          end; simpl in *); eauto 7.\n\nLtac run := run'; repeat (match goal with\n                            | [ H : forall n v, ?E n = Some v -> _\n                                |- context[match ?E ?N with Some _ => _ | None => _ end] ] =>\n                              specialize (H N); destruct (E N); try rewrite (H _ (eq_refl _)) by auto; try discriminate\n                          end; run').\n\nLemma ex_irrelevant : forall P : Prop, P -> exists n : nat, P.\n  exists 0; auto.\nQed.\n\nHint Resolve ex_irrelevant.\n\nRequire Import Max.\n\nTheorem max_spec_le : forall n m, n <= m /\\ max n m = m \\/ m <= n /\\ max n m = n.\n  induction n; destruct m; simpl; intuition;\n    specialize (IHn m); intuition.\nQed.\n\nLtac max := intros n m; generalize (max_spec_le n m); crush.\n\nLemma max_1 : forall n m, max n m >= n.\n  max.\nQed.\n\nLemma max_2 : forall n m, max n m >= m.\n  max.\nQed.\n\nHint Resolve max_1 max_2.\n\nLemma ge_refl : forall n, n >= n.\n  crush.\nQed.\n\nHint Resolve ge_refl.\n\nHint Extern 1 => match goal with\n                   | [ H : _ = exist _ _ _ |- _ ] => rewrite H\n                 end.\n(* end hide *)\n(** remove printing exists *)\n\n(** Now, as a simple first example of a computation, we can define [Bottom], which corresponds to an infinite loop.  For any approximation level, it fails to terminate (returns [None]).  Note the use of [abstract] to create a new opaque lemma for the proof found by the #<tt>#%\\coqdocvar{%run%}%#</tt># tactic.  In contrast to the previous section, opaque proofs are fine here, since the proof components of computations do not influence evaluation behavior.  It is generally preferable to make proofs opaque when possible, as this enforces a kind of modularity in the code to follow, preventing it from depending on any details of the proof. *)\n\nSection Bottom.\n  Variable A : Type.\n\n  Definition Bottom : computation A.\n    exists (fun _ : nat => @None A); abstract run.\n  Defined.\n\n  Theorem run_Bottom : forall v, ~run Bottom v.\n    run.\n  Qed.\nEnd Bottom.\n\n(** A slightly more complicated example is [Return], which gives the same terminating answer at every approximation level. *)\n\nSection Return.\n  Variable A : Type.\n  Variable v : A.\n\n  Definition Return : computation A.\n    intros; exists (fun _ : nat => Some v); abstract run.\n  Defined.\n\n  Theorem run_Return : run Return v.\n    run.\n  Qed.\nEnd Return.\n\n(** The name [Return] was meant to be suggestive of the standard operations of %\\index{monad}%monads%~\\cite{Monads}%.  The other standard operation is [Bind], which lets us run one computation and, if it terminates, pass its result off to another computation.  We implement bind using the notation [let (x, y) := e1 in e2], for pulling apart the value [e1] which may be thought of as a pair.  The second component of a [computation] is a proof, which we do not need to mention directly in the definition of [Bind]. *)\n\nSection Bind.\n  Variables A B : Type.\n  Variable m1 : computation A.\n  Variable m2 : A -> computation B.\n\n  Definition Bind : computation B.\n    exists (fun n =>\n      let (f1, _) := m1 in\n      match f1 n with\n\t| None => None\n\t| Some v =>\n\t  let (f2, _) := m2 v in\n\t    f2 n\n      end); abstract run.\n  Defined.\n\n  Theorem run_Bind : forall (v1 : A) (v2 : B),\n    run m1 v1\n    -> run (m2 v1) v2\n    -> run Bind v2.\n    run; match goal with\n           | [ x : nat, y : nat |- _ ] => exists (max x y)\n         end; run.\n  Qed.\nEnd Bind.\n\n(** A simple notation lets us write [Bind] calls the way they appear in Haskell. *)\n\nNotation \"x <- m1 ; m2\" :=\n  (Bind m1 (fun x => m2)) (right associativity, at level 70).\n\n(** We can verify that we have indeed defined a monad, by proving the standard monad laws.  Part of the exercise is choosing an appropriate notion of equality between computations.  We use \"equality at all approximation levels.\" *)\n\nDefinition meq A (m1 m2 : computation A) := forall n, proj1_sig m1 n = proj1_sig m2 n.\n\nTheorem left_identity : forall A B (a : A) (f : A -> computation B),\n  meq (Bind (Return a) f) (f a).\n  run.\nQed.\n\nTheorem right_identity : forall A (m : computation A),\n  meq (Bind m (@Return _)) m.\n  run.\nQed.\n\nTheorem associativity : forall A B C (m : computation A)\n  (f : A -> computation B) (g : B -> computation C),\n  meq (Bind (Bind m f) g) (Bind m (fun x => Bind (f x) g)).\n  run.\nQed.\n\n(** Now we come to the piece most directly inspired by domain theory.  We want to support general recursive function definitions, but domain theory tells us that not all definitions are reasonable; some fail to be _continuous_ and thus represent unrealizable computations.  To formalize an analogous notion of continuity for our non-termination monad, we write down the approximation relation on computation results that we have had in mind all along. *)\n\nSection lattice.\n  Variable A : Type.\n\n  Definition leq (x y : option A) :=\n    forall v, x = Some v -> y = Some v.\nEnd lattice.\n\n(** We now have the tools we need to define a new [Fix] combinator that, unlike the one we saw in the prior section, does not require a termination proof, and in fact admits recursive definition of functions that fail to terminate on some or all inputs. *)\n\nSection Fix.\n\n  (** First, we have the function domain and range types. *)\n\n  Variables A B : Type.\n\n  (** Next comes the function body, which is written as though it can be parameterized over itself, for recursive calls. *)\n\n  Variable f : (A -> computation B) -> (A -> computation B).\n\n  (** Finally, we impose an obligation to prove that the body [f] is continuous.  That is, when [f] terminates according to one recursive version of itself, it also terminates with the same result at the same approximation level when passed a recursive version that refines the original, according to [leq]. *)\n\n  Hypothesis f_continuous : forall n v v1 x,\n    runTo (f v1 x) n v\n    -> forall (v2 : A -> computation B),\n      (forall x, leq (proj1_sig (v1 x) n) (proj1_sig (v2 x) n))\n      -> runTo (f v2 x) n v.\n\n  (** The computational part of the [Fix] combinator is easy to define.  At approximation level 0, we diverge; at higher levels, we run the body with a functional argument drawn from the next lower level. *)\n\n  Fixpoint Fix' (n : nat) (x : A) : computation B :=\n    match n with\n      | O => Bottom _\n      | S n' => f (Fix' n') x\n    end.\n\n  (** Now it is straightforward to package [Fix'] as a computation combinator [Fix]. *)\n\n  Hint Extern 1 (_ >= _) => lia.\n  Hint Unfold leq.\n\n  Lemma Fix'_ok : forall steps n x v, proj1_sig (Fix' n x) steps = Some v\n    -> forall n', n' >= n\n      -> proj1_sig (Fix' n' x) steps = Some v.\n    unfold runTo in *; induction n; crush;\n      match goal with\n        | [ H : _ >= _ |- _ ] => inversion H; crush; eauto\n      end.\n  Qed.\n\n  Hint Resolve Fix'_ok.\n\n  Hint Extern 1 (proj1_sig _ _ = _) => simpl;\n    match goal with\n      | [ |- proj1_sig ?E _ = _ ] => eapply (proj2_sig E)\n    end.\n\n  Definition Fix : A -> computation B.\n    intro x; exists (fun n => proj1_sig (Fix' n x) n); abstract run.\n  Defined.\n\n  (** Finally, we can prove that [Fix] obeys the expected computation rule. *)\n\n  Theorem run_Fix : forall x v,\n    run (f Fix x) v\n    -> run (Fix x) v.\n    run; match goal with\n           | [ n : nat |- _ ] => exists (S n); eauto\n         end.\n  Qed.\nEnd Fix.\n\n(* begin hide *)\nLemma leq_Some : forall A (x y : A), leq (Some x) (Some y)\n  -> x = y.\n  intros ? ? ? H; generalize (H _ (eq_refl _)); crush.\nQed.\n\nLemma leq_None : forall A (x y : A), leq (Some x) None\n  -> False.\n  intros ? ? ? H; generalize (H _ (eq_refl _)); crush.\nQed.\n\nLtac mergeSort' := run;\n  repeat (match goal with\n            | [ |- context[match ?E with O => _ | S _ => _ end] ] => destruct E\n          end; run);\n  repeat match goal with\n           | [ H : forall x, leq (proj1_sig (?f x) _) (proj1_sig (?g x) _) |- _ ] =>\n             match goal with\n               | [ H1 : f ?arg = _, H2 : g ?arg = _ |- _ ] =>\n                 generalize (H arg); rewrite H1; rewrite H2; clear H1 H2; simpl; intro\n             end\n         end; run; repeat match goal with\n                            | [ H : _ |- _ ] => (apply leq_None in H; tauto) || (apply leq_Some in H; subst)\n                          end; auto.\n(* end hide *)\n\n(** After all that work, it is now fairly painless to define a version of [mergeSort] that requires no proof of termination.  We appeal to a program-specific tactic whose definition is hidden here but present in the book source. *)\n\nDefinition mergeSort' : forall A, (A -> A -> bool) -> list A -> computation (list A).\n  refine (fun A le => Fix\n    (fun (mergeSort : list A -> computation (list A))\n      (ls : list A) =>\n      if le_lt_dec 2 (length ls)\n\tthen let lss := split ls in\n          ls1 <- mergeSort (fst lss);\n          ls2 <- mergeSort (snd lss);\n          Return (merge le ls1 ls2)\n\telse Return ls) _); abstract mergeSort'.\nDefined.\n\n(** Furthermore, \"running\" [mergeSort'] on concrete inputs is as easy as choosing a sufficiently high approximation level and letting Coq's computation rules do the rest.  Contrast this with the proof work that goes into deriving an evaluation fact for a deeply embedded language, with one explicit proof rule application per execution step. *)\n\nLemma test_mergeSort' : run (mergeSort' leb (1 :: 2 :: 36 :: 8 :: 19 :: nil))\n  (1 :: 2 :: 8 :: 19 :: 36 :: nil).\n  exists 4; reflexivity.\nQed.\n\n(** There is another benefit of our new [Fix] compared with the one we used in the previous section: we can now write recursive functions that sometimes fail to terminate, without losing easy reasoning principles for the terminating cases.  Consider this simple example, which appeals to another tactic whose definition we elide here. *)\n\n(* begin hide *)\nLtac looper := unfold leq in *; run;\n  repeat match goal with\n           | [ x : unit |- _ ] => destruct x\n           | [ x : bool |- _ ] => destruct x\n         end; auto.\n(* end hide *)\n\nDefinition looper : bool -> computation unit.\n  refine (Fix (fun looper (b : bool) =>\n    if b then Return tt else looper b) _); abstract looper.\nDefined.\n\nLemma test_looper : run (looper true) tt.\n  exists 1; reflexivity.\nQed.\n\n(** As before, proving outputs for specific inputs is as easy as demonstrating a high enough approximation level.\n\n   There are other theorems that are important to prove about combinators like [Return], [Bind], and [Fix].  In general, for a computation [c], we sometimes have a hypothesis proving [run c v] for some [v], and we want to perform inversion to deduce what [v] must be.  Each combinator should ideally have a theorem of that kind, for [c] built directly from that combinator.  We have omitted such theorems here, but they are not hard to prove.  In general, the domain theory-inspired approach avoids the type-theoretic \"gotchas\" that tend to show up in approaches that try to mix normal Coq computation with explicit syntax types.  The next section of this chapter demonstrates two alternate approaches of that sort.  In the final section of the chapter, we review the pros and cons of the different choices, coming to the conclusion that none of them is obviously better than any one of the others for all situations. *)\n\n\n(** * Co-Inductive Non-Termination Monads *)\n\n(** There are two key downsides to both of the previous approaches: both require unusual syntax based on explicit calls to fixpoint combinators, and both generate immediate proof obligations about the bodies of recursive definitions.  In Chapter 5, we have already seen how co-inductive types support recursive definitions that exhibit certain well-behaved varieties of non-termination.  It turns out that we can leverage that co-induction support for encoding of general recursive definitions, by adding layers of co-inductive syntax.  In effect, we mix elements of shallow and deep embeddings.\n\n   Our first example of this kind, proposed by Capretta%~\\cite{Capretta}%, defines a silly-looking type of thunks; that is, computations that may be forced to yield results, if they terminate. *)\n\nCoInductive thunk (A : Type) : Type :=\n| Answer : A -> thunk A\n| Think : thunk A -> thunk A.\n\n(** A computation is either an immediate [Answer] or another computation wrapped inside [Think].  Since [thunk] is co-inductive, every [thunk] type is inhabited by an infinite nesting of [Think]s, standing for non-termination.  Terminating results are [Answer] wrapped inside some finite number of [Think]s.\n\n   Why bother to write such a strange definition?  The definition of [thunk] is motivated by the ability it gives us to define a \"bind\" operation, similar to the one we defined in the previous section. *)\n\nCoFixpoint TBind A B (m1 : thunk A) (m2 : A -> thunk B) : thunk B :=\n  match m1 with\n    | Answer x => m2 x\n    | Think m1' => Think (TBind m1' m2)\n  end.\n\n(** Note that the definition would violate the co-recursion guardedness restriction if we left out the seemingly superfluous [Think] on the righthand side of the second [match] branch.\n\n   We can prove that [Answer] and [TBind] form a monad for [thunk].  The proof is omitted here but present in the book source.  As usual for this sort of proof, a key element is choosing an appropriate notion of equality for [thunk]s. *)\n\n(* begin hide *)\nCoInductive thunk_eq A : thunk A -> thunk A -> Prop :=\n| EqAnswer : forall x, thunk_eq (Answer x) (Answer x)\n| EqThinkL : forall m1 m2, thunk_eq m1 m2 -> thunk_eq (Think m1) m2\n| EqThinkR : forall m1 m2, thunk_eq m1 m2 -> thunk_eq m1 (Think m2).\n\nSection thunk_eq_coind.\n  Variable A : Type.\n  Variable P : thunk A -> thunk A -> Prop.\n\n  Hypothesis H : forall m1 m2, P m1 m2\n    -> match m1, m2 with\n         | Answer x1, Answer x2 => x1 = x2\n         | Think m1', Think m2' => P m1' m2'\n         | Think m1', _ => P m1' m2\n         | _, Think m2' => P m1 m2'\n       end.\n\n  Theorem thunk_eq_coind : forall m1 m2, P m1 m2 -> thunk_eq m1 m2.\n    cofix thunk_eq_coind; intros;\n      match goal with\n        | [ H' : P _ _ |- _ ] => specialize (H H'); clear H'\n      end; destruct m1; destruct m2; subst; repeat constructor; auto.\n  Qed.\nEnd thunk_eq_coind.\n(* end hide *)\n\n(** In the proofs to follow, we will need a function similar to one we saw in Chapter 5, to pull apart and reassemble a [thunk] in a way that provokes reduction of co-recursive calls. *)\n\nDefinition frob A (m : thunk A) : thunk A :=\n  match m with\n    | Answer x => Answer x\n    | Think m' => Think m'\n  end.\n\nTheorem frob_eq : forall A (m : thunk A), frob m = m.\n  destruct m; reflexivity.\nQed.\n\n(* begin hide *)\nTheorem thunk_eq_frob : forall A (m1 m2 : thunk A),\n  thunk_eq (frob m1) (frob m2)\n  -> thunk_eq m1 m2.\n  intros; repeat rewrite frob_eq in *; auto.\nQed.\n\nLtac findDestr := match goal with\n                    | [ |- context[match ?E with Answer _ => _ | Think _ => _ end] ] =>\n                      match E with\n                        | context[match _ with Answer _ => _ | Think _ => _ end] => fail 1\n                        | _ => destruct E\n                      end\n                  end.\n\nTheorem thunk_eq_refl : forall A (m : thunk A), thunk_eq m m.\n  intros; apply (thunk_eq_coind (fun m1 m2 => m1 = m2)); crush; findDestr; reflexivity.\nQed.\n\nHint Resolve thunk_eq_refl.\n\nTheorem tleft_identity : forall A B (a : A) (f : A -> thunk B),\n  thunk_eq (TBind (Answer a) f) (f a).\n  intros; apply thunk_eq_frob; crush.\nQed.\n\nTheorem tright_identity : forall A (m : thunk A),\n  thunk_eq (TBind m (@Answer _)) m.\n  intros; apply (thunk_eq_coind (fun m1 m2 => m1 = TBind m2 (@Answer _))); crush;\n    findDestr; reflexivity.\nQed.\n\nLemma TBind_Answer : forall (A B : Type) (v : A) (m2 : A -> thunk B),\n  TBind (Answer v) m2 = m2 v.\n  intros; rewrite <- (frob_eq (TBind (Answer v) m2));\n    simpl; findDestr; reflexivity.\nQed.\n\nHint Rewrite TBind_Answer.\n\n(** printing exists $\\exists$ *)\n\nTheorem tassociativity : forall A B C (m : thunk A) (f : A -> thunk B) (g : B -> thunk C),\n  thunk_eq (TBind (TBind m f) g) (TBind m (fun x => TBind (f x) g)).\n  intros; apply (thunk_eq_coind (fun m1 m2 => (exists m,\n    m1 = TBind (TBind m f) g\n    /\\ m2 = TBind m (fun x => TBind (f x) g))\n  \\/ m1 = m2)); crush; eauto; repeat (findDestr; crush; eauto).\nQed.\n(* end hide *)\n\n(** As a simple example, here is how we might define a tail-recursive factorial function. *)\n\nCoFixpoint fact (n acc : nat) : thunk nat :=\n  match n with\n    | O => Answer acc\n    | S n' => Think (fact n' (S n' * acc))\n  end.\n\n(** To test our definition, we need an evaluation relation that characterizes results of evaluating [thunk]s. *)\n\nInductive eval A : thunk A -> A -> Prop :=\n| EvalAnswer : forall x, eval (Answer x) x\n| EvalThink : forall m x, eval m x -> eval (Think m) x.\n\nHint Rewrite frob_eq.\n\nLemma eval_frob : forall A (c : thunk A) x,\n  eval (frob c) x\n  -> eval c x.\n  crush.\nQed.\n\nTheorem eval_fact : eval (fact 5 1) 120.\n  repeat (apply eval_frob; simpl; constructor).\nQed.\n\n(** We need to apply constructors of [eval] explicitly, but the process is easy to automate completely for concrete input programs.\n\n   Now consider another very similar definition, this time of a Fibonacci number function. *)\n\nNotation \"x <- m1 ; m2\" :=\n  (TBind m1 (fun x => m2)) (right associativity, at level 70).\n\n(* begin hide *)\n(* begin thide *)\nDefinition fib := pred.\n(* end thide *)\n(* end hide *)\n\n(** %\\vspace{-.3in}%[[\nCoFixpoint fib (n : nat) : thunk nat :=\n  match n with\n    | 0 => Answer 1\n    | 1 => Answer 1\n    | _ => n1 <- fib (pred n);\n      n2 <- fib (pred (pred n));\n      Answer (n1 + n2)\n  end.\n]]\n\nCoq complains that the guardedness condition is violated.  The two recursive calls are immediate arguments to [TBind], but [TBind] is not a constructor of [thunk].  Rather, it is a defined function.  This example shows a very serious limitation of [thunk] for traditional functional programming: it is not, in general, possible to make recursive calls and then make further recursive calls, depending on the first call's result.  The [fact] example succeeded because it was already tail recursive, meaning no further computation is needed after a recursive call.\n\n%\\medskip%\n\nI know no easy fix for this problem of [thunk], but we can define an alternate co-inductive monad that avoids the problem, based on a proposal by Megacz%~\\cite{Megacz}%.  We ran into trouble because [TBind] was not a constructor of [thunk], so let us define a new type family where \"bind\" is a constructor. *)\n\nSet Universe Polymorphism.\n\nCoInductive comp (A : Type) : Type :=\n| Ret : A -> comp A\n| Bnd : forall B, comp B -> (B -> comp A) -> comp A.\n\n(** This example shows off Coq's support for%\\index{recursively non-uniform parameters}% _recursively non-uniform parameters_, as in the case of the parameter [A] declared above, where each constructor's type ends in [comp A], but there is a recursive use of [comp] with a different parameter [B].  Beside that technical wrinkle, we see the simplest possible definition of a monad, via a type whose two constructors are precisely the monad operators.\n\n   It is easy to define the semantics of terminating [comp] computations. *)\n\nInductive exec A : comp A -> A -> Prop :=\n| ExecRet : forall x, exec (Ret x) x\n| ExecBnd : forall B (c : comp B) (f : B -> comp A) x1 x2, exec (A := B) c x1\n  -> exec (f x1) x2\n  -> exec (Bnd c f) x2.\n\n(** We can also prove that [Ret] and [Bnd] form a monad according to a notion of [comp] equality based on [exec], but we omit details here; they are in the book source at this point. *)\n\n(* begin hide *)\nHint Constructors exec.\n\nDefinition comp_eq A (c1 c2 : comp A) := forall r, exec c1 r <-> exec c2 r.\n\nLtac inverter := repeat match goal with\n                          | [ H : exec _ _ |- _ ] => inversion H; []; crush\n                        end.\n\nTheorem cleft_identity : forall A B (a : A) (f : A -> comp B),\n  comp_eq (Bnd (Ret a) f) (f a).\n  red; crush; inverter; eauto.\nQed.\n\nTheorem cright_identity : forall A (m : comp A),\n  comp_eq (Bnd m (@Ret _)) m.\n  red; crush; inverter; eauto.\nQed.\n\nLemma cassociativity1 : forall A B C (f : A -> comp B) (g : B -> comp C) r c,\n  exec c r\n  -> forall m, c = Bnd (Bnd m f) g\n   -> exec (Bnd m (fun x => Bnd (f x) g)) r.\n  induction 1; crush.\n  match goal with\n    | [ H : Bnd _ _ = Bnd _ _ |- _ ] => injection H; clear H; intros; try subst\n  end.\n  try subst B. (* This line expected to fail in Coq 8.4 and succeed in Coq 8.6. *)\n  crush.\n  inversion H; clear H; crush.\n  eauto.\nQed.\n\nLemma cassociativity2 : forall A B C (f : A -> comp B) (g : B -> comp C) r c,\n  exec c r\n  -> forall m, c = Bnd m (fun x => Bnd (f x) g)\n   -> exec (Bnd (Bnd m f) g) r.\n  induction 1; crush.\n  match goal with\n    | [ H : Bnd _ _ = Bnd _ _ |- _ ] => injection H; clear H; intros; try subst\n  end.\n  try subst A. (* Same as above *)\n  crush.\n  inversion H0; clear H0; crush.\n  eauto.\nQed.\n\nHint Resolve cassociativity1 cassociativity2.\n\nTheorem cassociativity : forall A B C (m : comp A) (f : A -> comp B) (g : B -> comp C),\n  comp_eq (Bnd (Bnd m f) g) (Bnd m (fun x => Bnd (f x) g)).\n  red; crush; eauto.\nQed.\n(* end hide *)\n\n(** Not only can we define the Fibonacci function with the new monad, but even our running example of merge sort becomes definable.  By shadowing our previous notation for \"bind,\" we can write almost exactly the same code as in our previous [mergeSort'] definition, but with less syntactic clutter. *)\n\nNotation \"x <- m1 ; m2\" := (Bnd m1 (fun x => m2)).\n\nCoFixpoint mergeSort'' A (le : A -> A -> bool) (ls : list A) : comp (list A) :=\n  if le_lt_dec 2 (length ls)\n    then let lss := split ls in\n      ls1 <- mergeSort'' le (fst lss);\n      ls2 <- mergeSort'' le (snd lss);\n      Ret (merge le ls1 ls2)\n    else Ret ls.\n\n(** To execute this function, we go through the usual exercise of writing a function to catalyze evaluation of co-recursive calls. *)\n\nDefinition frob' A (c : comp A) :=\n  match c with\n    | Ret x => Ret x\n    | Bnd _ c' f => Bnd c' f\n  end.\n\nLemma exec_frob : forall A (c : comp A) x,\n  exec (frob' c) x\n  -> exec c x.\n  destruct c; crush.\nQed.\n\n(** Now the same sort of proof script that we applied for testing [thunk]s will get the job done. *)\n\nLemma test_mergeSort'' : exec (mergeSort'' leb (1 :: 2 :: 36 :: 8 :: 19 :: nil))\n  (1 :: 2 :: 8 :: 19 :: 36 :: nil).\n  repeat (apply exec_frob; simpl; econstructor).\nQed.\n\n(** Have we finally reached the ideal solution for encoding general recursive definitions, with minimal hassle in syntax and proof obligations?  Unfortunately, we have not, as [comp] has a serious expressivity weakness.  Consider the following definition of a curried addition function: *)\n\nDefinition curriedAdd (n : nat) := Ret (fun m : nat => Ret (n + m)).\n\n(** This definition works fine, but we run into trouble when we try to apply it in a trivial way.\n[[\nDefinition testCurriedAdd := Bnd (curriedAdd 2) (fun f => f 3).\n]]\n\n<<\nError: Universe inconsistency.\n>>\n\nThe problem has to do with rules for inductive definitions that we will study in more detail in Chapter 12.  Briefly, recall that the type of the constructor [Bnd] quantifies over a type [B].  To make [testCurriedAdd] work, we would need to instantiate [B] as [nat -> comp nat].  However, Coq enforces a %\\emph{predicativity restriction}% that (roughly) no quantifier in an inductive or co-inductive type's definition may ever be instantiated with a term that contains the type being defined.  Chapter 12 presents the exact mechanism by which this restriction is enforced, but for now our conclusion is that [comp] is fatally flawed as a way of encoding interesting higher-order functional programs that use general recursion. *)\n\n\n(** * Comparing the Alternatives *)\n\n(** We have seen four different approaches to encoding general recursive definitions in Coq.  Among them there is no clear champion that dominates the others in every important way.  Instead, we close the chapter by comparing the techniques along a number of dimensions.  Every technique allows recursive definitions with termination arguments that go beyond Coq's built-in termination checking, so we must turn to subtler points to highlight differences.\n\n   One useful property is automatic integration with normal Coq programming.  That is, we would like the type of a function to be the same, whether or not that function is defined using an interesting recursion pattern.  Only the first of the four techniques, well-founded recursion, meets this criterion.  It is also the only one of the four to meet the related criterion that evaluation of function calls can take place entirely inside Coq's built-in computation machinery.  The monad inspired by domain theory occupies some middle ground in this dimension, since generally standard computation is enough to evaluate a term once a high enough approximation level is provided.\n\n   Another useful property is that a function and its termination argument may be developed separately.  We may even want to define functions that fail to terminate on some or all inputs.  The well-founded recursion technique does not have this property, but the other three do.\n\n   One minor plus is the ability to write recursive definitions in natural syntax, rather than with calls to higher-order combinators.  This downside of the first two techniques is actually rather easy to get around using Coq's notation mechanism, though we leave the details as an exercise for the reader.  (For this and other details of notations, see Chapter 12 of the Coq 8.4 manual.)\n\n   The first two techniques impose proof obligations that are more basic than termination arguments, where well-founded recursion requires a proof of extensionality and domain-theoretic recursion requires a proof of continuity.  A function may not be defined, and thus may not be computed with, until these obligations are proved.  The co-inductive techniques avoid this problem, as recursive definitions may be made without any proof obligations.\n\n   We can also consider support for common idioms in functional programming.  For instance, the [thunk] monad effectively only supports recursion that is tail recursion, while the others allow arbitrary recursion schemes.\n\n   On the other hand, the [comp] monad does not support the effective mixing of higher-order functions and general recursion, while all the other techniques do.  For instance, we can finish the failed [curriedAdd] example in the domain-theoretic monad. *)\n\nDefinition curriedAdd' (n : nat) := Return (fun m : nat => Return (n + m)).\n\nDefinition testCurriedAdd := Bind (curriedAdd' 2) (fun f => f 3).\n\n(** The same techniques also apply to more interesting higher-order functions like list map, and, as in all four techniques, we can mix primitive and general recursion, preferring the former when possible to avoid proof obligations. *)\n\nFixpoint map A B (f : A -> computation B) (ls : list A) : computation (list B) :=\n  match ls with\n    | nil => Return nil\n    | x :: ls' => Bind (f x) (fun x' =>\n      Bind (map f ls') (fun ls'' =>\n        Return (x' :: ls'')))\n  end.\n\n(** remove printing exists *)\nTheorem test_map : run (map (fun x => Return (S x)) (1 :: 2 :: 3 :: nil))\n  (2 :: 3 :: 4 :: nil).\n  exists 1; reflexivity.\nQed.\n\n(** One further disadvantage of [comp] is that we cannot prove an inversion lemma for executions of [Bind] without appealing to an _axiom_, a logical complication that we discuss at more length in Chapter 12.  The other three techniques allow proof of all the important theorems within the normal logic of Coq.\n\nPerhaps one theme of our comparison is that one must trade off between, on one hand, functional programming expressiveness and compatibility with normal Coq types and computation; and, on the other hand, the level of proof obligations one is willing to handle at function definition time. *)\n", "meta": {"author": "haoyang9804", "repo": "CPDT", "sha": "ab053fe3c88ab66a6a514ddbfdbbec6744d34e7d", "save_path": "github-repos/coq/haoyang9804-CPDT", "path": "github-repos/coq/haoyang9804-CPDT/CPDT-ab053fe3c88ab66a6a514ddbfdbbec6744d34e7d/src/GeneralRec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867825403176, "lm_q2_score": 0.8539127603871312, "lm_q1q2_score": 0.6815818787835254}}
{"text": "(** Introduction to Coq exercises for the Bindel group meeting 09/23/2022 **)\n\n(** Note: In the web-based environment for Coq, you can move down through proof\n   scripts using Alt+p and up through proof scripts using Alt+n . **)\n\n\n(** Example Set 1 **)\nTheorem id_test : \nforall P : Prop, P -> P.\nProof.\n(* apply the inference rule of implication elimination, using the intros tactic *)\nintros P.\n(* The Show Proof command displays the proof object that's been built so far. Incomplete\n  parts of the proof -- holes -- are denoted with a ? prefix. *)\nShow Proof.\n(* apply the inference rule of implication elimination, using the intros tactic *)\nintros X.\nShow Proof.\n(* TODO *)\nAdmitted.\n\n(* We can see id_test's proof object and type using the Print command. *)\n\nPrint id_test.\n\n(* We can provide the proof object directly as an alternative proof. *)\n\nTheorem id_test_alt: \nforall P : Prop, P -> P.\nProof.\napply (fun P => fun X => X).\nQed.\n\nPrint id_test_alt.\n\n\nTheorem app_test1 :\n  forall A B , (A -> B) -> A -> B.\nProof.\n(* Function application binds tighter than abstraction. *)\napply (fun A B => fun HAB => fun HA => HAB HA).\nQed.\n\nTheorem app_test2 :\n  forall A B C, (A -> B) -> (B -> C) -> A -> C.\nProof.\napply (fun A B C => fun HAB HBC HA => HBC (HAB HA)).\nQed.\n\nTheorem app_test3 :\n  forall A B C, (A -> B -> C) -> A -> B -> C.\nProof.\n(* Function application is left associative. *)\napply (fun A B C => fun HABC A B => HABC A B).\nQed.\n\n\n(** Example Set 2 : Inductive Definitions **)\nModule BindelGroupIntro.\n(** NOTE : Module System **)\n(** All declarations between Module X and End X markers are referred to by names like X.foo \nin the remainder of the file (instead of just foo). Use this feature to limit the scope of \ndefinitions, so that you can reuse names. **)\n\n(** From Software Foundations: \"The set of built-in features in Coq is extremely small. \nFor example, instead of providing the usual palette of atomic data types \n(booleans, integers, strings, etc.), Coq offers a powerful mechanism for \ndefining new data types from scratch, with all these familiar types as instances.\nNaturally, the Coq distribution comes with an extensive standard library providing \ndefinitions of booleans, numbers, and many common data structures like lists and hash tables. \nBut there is nothing magic or primitive about these library definitions\". **)\n\n(** We can define a new type inductively, called day, whose members are monday, tuesday, etc. **)\n\nInductive day : Type :=\n  | monday\n  | tuesday\n  | wednesday\n  | thursday\n  | friday\n  | saturday\n  | sunday.\n\n(** An Inductive definition does two things:\n(#1.) It defines a set of new constructors. monday is a constructor.\n(#2.) It groups them into a new named type. day is a new named type. **)\n\n(** day is the type of the constructor monday **)\nCheck monday.\n(** Set is the type of day. **)\nCheck day.\n(** Type is the type of Set. *)\nCheck Set.\n\n(** Having defined day, we can write functions that operate on days. **)\n\nDefinition next_weekday (d:day) : day :=\n  match d with\n  | monday => tuesday\n  | tuesday => wednesday\n  | wednesday => thursday\n  | thursday => friday\n  | _ => monday\n  end.\n\nEnd BindelGroupIntro.\n\n\n(** Every nat is either built with O or with S. **)\nPrint nat.\n(** What's the type of S ? **)\nCheck S.\n(* If a nat is built with S we can extract the underlying natural number. *)\nCheck S O.\n\nDefinition minus_one (n : nat) : nat :=\n  match n with \n    | 0 => 0\n    | S n' => n'\n  end.\n\nCheck minus_one.\n\n(** Observe that minus_one and S appear to have the same type. \n In fact S is more than just a function nat -> nat: we can pattern \n match on S but we can't pattern match on minus_one. **)\n\n(*\nDefinition minus_two (n: nat) : nat :=\n  match n with \n    | O => O\n    | minus_one n' => minus_one n'\n  end.\n*)\n\n\n(** TODO : define minus_two **)\n\n(** Coq provides several evaluation mechanisms. **)\nEval compute in (minus_one (S ( S 0))).\n\n(** There are different ways to define objects in \n Coq. We can construct a definition of\n \"minus_one\" in \"proof mode.\" **)\nDefinition minus_one_transparent (n : nat) : nat.\nexact (n - 1). Defined.\n\nPrint minus_one.\nPrint minus_one_transparent.\n\n(** Defined marks a definition as transparent, \nallowing it to be unfolded; Qed marks a definition as \nopaque, preventing unfolding. *)\nEval compute in (minus_one_transparent 3).\n\nDefinition minus_one_opaque (n : nat) : nat.\nexact (n - 1). Qed.\n\nEval compute in (minus_one_opaque 3).\n\nLemma equal_defs n :\nminus_one n = minus_one_transparent n.\nProof.\nunfold minus_one_transparent, minus_one.\n(* Perform case analysis by generating a subgoal \n for each constructor of the inductive type using the\n destruct tactic *)\ndestruct n.\n- (* bullets allow us to focus on a subgoal *)\n(* how do we finish this proof? *)\n(* we can look at available lemmas *)\nSearch (0 - _)%nat.\nAbort.\n\n(** a standard prelude module provides the standard logic connectives, \nand a few arithmetic notions. If you want to load and open other modules \nfrom the library, you have to use the Require command. **)\n\nRequire Import Arith.\n\n(* we can look at available lemmas *)\nSearch ( 0 - _)%nat.\n\nLemma equal_defs n :\nminus_one n = minus_one_transparent n.\nProof.\nunfold minus_one_transparent, minus_one.\ndestruct n.\n-\nrewrite Nat.sub_0_l.\nreflexivity.\n-\nrewrite Nat.sub_1_r.\nrewrite Nat.pred_succ.\nreflexivity.\nQed.\n\n(** Example Set 3: Recursive Functions & Inductively Defined Properties **)\n\n(** Recursive functions are defined with the keyword Fixpoint instead of Definition.**) \nPrint fact.\n\nEval compute in (fact 4).\n\n(** We can express the concept \"m is n!\" as an inductively defined property of \n  natural numbers. **) \n\nInductive fact_rel : nat -> nat -> Prop :=\n  | zero : fact_rel 0 1 (* \"1 is 0!\" *)\n  | plus_one : forall n m, fact_rel n m -> fact_rel (n + 1) (( n + 1) * m)\n    (* \"if m is n! then (n+1) * m is (n + 1)!\" *)\n    .\n\nCheck zero.\n\n(* import some tactics for integers *)\nRequire Import Lia.\n\n\nTheorem fact_correct1 :\n  forall (n m : nat), fact_rel n (fact n).\nProof.\nintros; induction n. \n-\napply zero.\n(* can also use the tactic \"constructor\" *)\n-\nunfold fact.\nreplace (S n) with (n + 1)%nat by lia.\nconstructor.\nfold fact.\nexact IHn.\nQed.\n\n\n(** Example Set 4: Real Analysis **)\n\n(** The literature: \"Coquelicot: A User-Friendly Library of Real Analysis for Coq\" \n  by Sylvie Boldo and co-authors. **)\nRequire Import Reals.\n(** \"The formalization of real numbers from the standard library is axiomatic \nrather than definitional. Instead of building reals as Cauchy sequences or\nDedekind cuts of rational numbers and proving their properties, Coq developers \nhave assumed the existence of a set with the usual properties of the real line.\" **)\n\nRequire Import Coquelicot.Coquelicot.\n\n\n", "meta": {"author": "ak-2485", "repo": "introduction_to_Coq", "sha": "e092ecfbd6e631a2319957fe75668aecd01234aa", "save_path": "github-repos/coq/ak-2485-introduction_to_Coq", "path": "github-repos/coq/ak-2485-introduction_to_Coq/introduction_to_Coq-e092ecfbd6e631a2319957fe75668aecd01234aa/coq_intro1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.6815818724202563}}
{"text": "Require Import ZArith.\n\nRequire Import List.\n\nSet Implicit Arguments.\n\nOpen Scope Z_scope.\nInductive Sorted : list Z -> Prop := \n  | sorted0 : Sorted nil \n  | sorted1 : forall z:Z, Sorted (z :: nil) \n  | sorted2 : forall (z1 z2:Z) (l:list Z), \n        z1 <= z2 -> Sorted (z2 :: l) -> Sorted (z1 :: z2 :: l). \nClose Scope Z_scope.\n\nFixpoint count (z:Z) (l:list Z) {struct l} : nat :=\n  match l with\n  | nil => 0%nat     (* %nat to force the interpretation in nat, since have we open Z_scope *)\n  | (z' :: l') =>\n      match Z.eq_dec z z' with\n      | left _ => S (count z l')\n      | right _ => count z l'\n      end\n  end.\n\nDefinition Perm (l1 l2:list Z) : Prop :=\n                                 forall z, count z l1 = count z l2.\n\nLemma Perm_cons : forall a l1 l2, Perm l1 l2 -> Perm (a::l1) (a::l2).\nProof.\n  intros.\n  unfold Perm. intro. simpl. elim (Z.eq_dec z a).\n  - intros. rewrite Nat.succ_inj_wd. unfold Perm in H. apply H.\n  - intros. unfold Perm in H; apply H.\nQed.\n\n\nLemma Perm_cons_cons : forall x y l, Perm (x::y::l) (y::x::l).\nProof.\n  intros.\n  unfold Perm.\n  intros. simpl. elim (Z.eq_dec z x).\n  - intros. elim (Z.eq_dec z y).\n    + intros; reflexivity.\n    + intros; reflexivity.\n  - intros; elim (Z.eq_dec z y).\n    + intros; reflexivity.\n    + intros; reflexivity.\nQed.\n\n(* ------------ *)\n\nRequire Import Recdef.\n\nFunction merge (p:list Z*list Z)\n{measure (fun p=>(length (fst p))+(length (snd p)))} : list Z :=\n  match p with\n  | (nil,l) => l\n  | (l,nil) => l\n  | (x::xs,y::ys) => if Z_lt_ge_dec x y\n                     then x::(merge (xs,y::ys))\n                     else y::(merge (x::xs,ys))\n  end.\n  intros.\n  simpl; auto with arith.\n  intros. simpl. omega.\n  Qed.\n\n\nTheorem merge_correct : forall (p:list Z*list Z), Perm (merge p) ((fst p) ++ (snd p)) /\\ Sorted (merge p).\nProof.\n  Admitted.\n\n(* Garante que o resultado é igual ao comprimento da lista *)\nDefinition comprimentoLista (A : Type) (l : list A) (res : nat) : Prop :=\n            forall n:nat, n < res <-> exists a:A, nth_error l n = Some a.\n\nTheorem comprimentoLista_correct : forall (A:Type) (l : list A), { n:nat | comprimentoLista l n }.\nProof.\n  intros. unfold comprimentoLista. induction l.\n  - exists 0. split.\n    + intros. contradict H. omega.\n    + intros. destruct H. contradict H. induction n.\n      * simpl. discriminate.\n      * simpl; discriminate.\n  - destruct IHl. exists (S x). intros. induction n.\n    + simpl. split.\n      * intros. exists a; reflexivity.\n      * intros. omega.\n    + simpl; split.\n      * intros. destruct i with n. apply H0. omega.\n      * intros. destruct i with n. Search (S _ < S _). apply lt_n_S. exact (H1 H).\nQed.\n\nDefinition soma (A:Type) (l : list (A*nat)) (res : nat) : Prop :=\n            res = fold_right (fun x y:nat => x+y) 0 (map (fun p => snd p) l).\n\nTheorem soma_correct : forall (A:Type) (l : list(A*nat)), { n: nat | soma l n}.\nProof.\n  unfold soma. intros. induction l.\n  - simpl. exists 0. reflexivity.\n  - simpl. destruct IHl. exists ((snd a) + x). subst. reflexivity.\nQed.\n\n(* Set Extraction AccessOpaque.*)\nRequire Extraction. \n\nExtraction Language Haskell.\n\nRecursive Extraction comprimentoLista_correct.\n\nRecursive Extraction soma_correct.", "meta": {"author": "JaK0be", "repo": "VF", "sha": "4d886d958200df476b3ece5c2194ee5ff1f149d5", "save_path": "github-repos/coq/JaK0be-VF", "path": "github-repos/coq/JaK0be-VF/VF-4d886d958200df476b3ece5c2194ee5ff1f149d5/TPC6/ficha3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.681581866699602}}
{"text": "From Undecidability Require Import Definitions.\nFrom Undecidability Require Import mu_nat partial equiv_on.\n\nFrom Undecidability Require Import simple principles EnumerabilityFacts.\n\nRequire Import Nat Arith Lia.\n\nNotation least' p n k := (n <= k /\\ p k /\\ forall i, n <= i -> p i -> k <= i)%nat.\n\nSection WO.\n\n  Variable p : nat -> Prop.\n\n  (* Guardedness predicate *)\n  Inductive G (n: nat) : Prop :=\n  | GI : (~ p n -> G (S n)) -> G n.\n\n  Lemma G_sig n :\n    G n -> ~~ exists k, least' (fun k => p k) n k.\n  Proof.\n    induction 1 as [n _ IH].\n    intros G.\n    assert (~~ (p n \\/ ~ p n)) as H by tauto. apply H. clear H. intros [H | H].\n    - apply G. exists n. repeat split; eauto.\n    - apply (IH H). intros (k & Hle & Hk & Hleast'). apply G.\n      exists k. repeat split.\n      + lia.\n      + exact Hk.\n      + intros i Hi. inversion Hi.\n        * congruence.\n        * eapply Hleast'; eauto. lia.\n  Defined.\n\n  Lemma G_zero n :\n    G n -> G 0.\n  Proof.\n    induction n as [|n IH].\n    - intros H. exact H.\n    - intros H. apply IH. constructor. intros _. exact H.\n  Defined.\n\n  Theorem mu_nat :\n    (exists n, p n) -> ~~ exists n, least' p 0 n.\n  Proof.\n    intros H. apply (G_sig 0).\n    destruct H as [n H].  \n    apply (G_zero n).\n    constructor. tauto.\n  Defined.\n\nEnd WO.\n\nDefinition the_least_pred (P : nat -> Prop) : nat -> Prop :=\n  fun y => P y /\\ forall y', P y' -> y <= y'.\n\nLemma the_least_pred_unique {P : nat -> Prop} {x y} :\n  the_least_pred P x -> the_least_pred P y -> x = y.\nProof.\n  firstorder lia.\nQed.\n\nLemma the_least_pred_impl' {P Q : nat -> Prop} {x} :\n  the_least_pred P x -> (forall x, P x <-> Q x) -> the_least_pred Q x.\nProof.\n  intros [H2 H3] H1. eapply H1 in H2. split. exact H2. intros y'. rewrite <- H1. apply H3.\nQed.\n\nLemma the_least_pred_equiv {P Q : nat -> Prop} {x} :\n  (forall x, P x <-> Q x) -> the_least_pred P x <-> the_least_pred Q x.\nProof.\n  intros. split; intros; eapply the_least_pred_impl'; eauto; firstorder.\nQed.\n\nLemma the_least_pred_impl {P Q : nat -> Prop} {x} :\n  the_least_pred P x -> (forall x, P x -> exists y, Q y) -> ~~ exists x, the_least_pred Q x.\nProof.\n  intros [H2 H3] H1. eapply H1 in H2.\n  clear H1 H3 P.\n  assert (exists x, Q x) as H by eauto. clear x H2. eapply mu_nat in H.\n  intros G. apply H. intros (x & H1 & H2 & H3).  apply G.\n  exists x. split. auto. intros. eapply H3. 1:lia. auto.\nQed.\n\nLemma the_least_ex (P : nat -> Prop) :\n  (exists n, P n) -> ~~ exists n, the_least_pred P n.\nProof.\n  intros H % mu_nat.\n  intros G. apply H. intros (n & H1 & H2 & H3).\n  apply G. exists n. split; auto with arith.\nQed.\n\nRecord FunRel X Y := {\n  the_rel :> X -> Y -> Prop ;\n  is_fun : (forall x y1 y2, the_rel x y1 -> the_rel x y2 -> y1 = y2) (* ; *)\n  (* is_wtotal : (forall x, ~~ exists y, the_rel x y) *) }.\n\nDefinition on_value {X Y} (R : FunRel X Y) (P : Y -> Prop) x :=\n  forall y, R x y -> P y.\n\nDefinition on_value' {X Y} (R : FunRel X Y) (P : Y -> Prop) x :=\n  exists y, R x y /\\ P y.\n\nLemma on_value_iff1 {X Y} (R : FunRel X Y) (P : Y -> Prop) x :\n  on_value' R P x -> on_value R P x.\nProof.\n  intros (y & H1 & H2) y' H.\n  now rewrite <- (is_fun _ _ R _ _ _ H1 H).\nQed.\n\nDefinition total {X Y} (R : X -> Y -> Prop) :=\n  forall x, exists y, R x y.\n\nLemma on_value_iff2 {X Y} (R : FunRel X Y) (P : Y -> Prop) x :\n  total R ->\n  on_value R P x -> on_value' R P x.\nProof.\n  intros Htot H.\n  destruct (Htot x) as [y Hy].\n  exists y. split; [ assumption | ].\n  eapply (H _ Hy).\nQed.\n\nDefinition weakly_total {X Y} (R : X -> Y -> Prop) :=\n  forall x, ~~ exists y, R x y.\n\nLemma on_value_iff2' {X Y} (R : FunRel X Y) (P : Y -> Prop) x :\n  weakly_total R ->\n  on_value R P x -> ~~ on_value' R P x.\nProof.\n  intros Htot H G.\n  apply (Htot x); intros [y Hy].\n  apply G.\n  exists y. split; [ assumption | ].\n  eapply (H _ Hy).\nQed.\n\nLemma on_value_imp {X Y} {P Q : Y -> Prop} R (x : X) :\n  on_value R P x -> (forall y, P y -> Q y) -> on_value R Q x.\nProof.\n  intros H1 H y Hy. apply H, H1, Hy.\nQed.\n\nLemma on_value_neg {X Y} {P : Y -> Prop} R (x : X) :\n  ~ on_value R P x -> on_value R (fun y => ~ P y) x.\nProof.\n  intros H y Hy G; cbn in *. apply H. intros y' Hy'. cbn in *.\n  enough (y = y') as -> by assumption. eapply R; eauto.\nQed.\n\nProgram Definition the_least {X} (R : X -> nat -> Prop) : FunRel X nat :=\n  {|\n  the_rel x := the_least_pred (R x) ;\n  is_fun := fun x y1 y2 H1 H2 => the_least_pred_unique H1 H2\n  |}.\n\nAxiom tonat : list bool -> nat.\nAxiom ofnat : nat -> list bool.\n\nAxiom ofnat_tonat : forall l, ofnat (tonat l) = l.\nAxiom tonat_ofnat : forall n, tonat (ofnat n) = n.\nAxiom length_log : forall n, length (ofnat n) <= Nat.log2 n.\nAxiom length_mono : forall x y, x <= y -> length (ofnat x) <= length (ofnat y).\n\nHint Rewrite ofnat_tonat tonat_ofnat : length.\nHint Rewrite List.app_length : length.\n\nNotation \"| n |\" := (length (ofnat n)) (at level 10).\n\nNotation \"⟨ x , y ⟩\" := (tonat (ofnat x ++ ofnat y)) (at level 0).\n\nLemma length_pair x y : | ⟨x,y⟩ | = |x| + |y|.\nProof.\n  now autorewrite with length.\nQed.\n\nLemma length_sublinear d : ~ forall n, n <= |n| + d.\nProof.\n  intros H.\n  pose (n := 1 + 2 * S d).\n  assert (2 ^ n > n + S d).\n  { subst n. rewrite Nat.pow_add_r, Nat.pow_mul_r.\n    generalize (S d). cbn. induction n; cbn; lia.\n  }\n  specialize (H (2 ^ n)).\n  pose proof (length_log (2 ^ n)).\n  rewrite Nat.log2_pow2 in *; lia.\nQed.\n\nAxiom Part : partiality.\nExisting Instance Part.\nAxiom ϕ : nat -> nat ↛ nat.\n\nNotation \"x ▷ y\" := (@hasvalue Part nat x y) (at level 50).\nDefinition C := the_least (fun x s => exists c y, s = |c| + |y| /\\ ϕ c y ▷ x).\n\nInstance equiv_part {A} : equiv_on (part A) := {| equiv_rel := @partial.equiv _ A |}.\n\nDefinition universal u := forall c, exists x, forall y, ϕ c y ≡{_} (ϕ u ⟨x,y⟩).\n\nDefinition C_ u := the_least (fun x s => exists y, s = |y| /\\ ϕ u y ▷ x).\n\nDefinition strongly_universal u := forall c i, ϕ c i ≡{_} ϕ u ⟨c,i⟩.\n\nLemma strongly_universal_universal u :\n  strongly_universal u -> universal u.\nProof.\n  intros H c'. red in H. setoid_rewrite <- H. exists c'. reflexivity.\nQed.\n\nHint Rewrite List.app_nil_l @list.nil_length : length.\n\nSet Default Goal Selector \"!\".\n\nLemma strongly_universal_equivalence u :\n  strongly_universal u -> forall x y, C x y <-> C_ u x y.\nProof.\n  intros Huniv x y. rename u into c.  eapply the_least_pred_equiv. \n  intros e. split.\n  - intros (e' & i & -> & HH).\n    eexists. eexists. 1:now rewrite <- length_pair.\n    red in Huniv. unfold equiv_part in Huniv.\n    do 2 red in Huniv. now  rewrite <- Huniv.\n  - intros (i & -> & Hn). exists (tonat nil), i.\n    split. 1:now autorewrite with length. \n    eapply Huniv. now autorewrite with length.\nQed.\n\nAxiom EPF : forall f : nat -> nat ↛ nat,\n    exists γ, forall i, ϕ (γ i) ≡{_} f i.\n\nLemma EPF_univ_tot {u} : universal u ->\n                     forall f : nat -> nat, exists c, forall x, ϕ u ⟨c,x⟩ ▷ f x.\nProof.\n  intros Hu f.\n  specialize (EPF (fun _ x => ret (f x))) as [γ H].\n  destruct (Hu (γ 0)) as [c Hc].\n  exists c. intros. cbn in * |-. red in H, Hc.\n  rewrite <- Hc, H. eapply ret_hasvalue.\nQed.\n\nLemma EPF_univ {u} : universal u ->\n                     forall f : nat ↛ nat, exists c, forall x, ϕ u ⟨c,x⟩ ≡{_} f x.\nProof.\n  intros Hu f.\n  specialize (EPF (fun _ => f)) as [γ H].\n  destruct (Hu (γ 0)) as [c Hc].\n  exists c. intros.\n  rewrite <- Hc. eapply H.\nQed.\n\nLemma C_weakly_total u x :\n  universal u -> ~~ exists y, C_ u x y.\nProof.\n  intros Hu. eapply the_least_ex.\n  destruct (EPF_univ_tot Hu (fun _ => x)) as [c Hc % fun H => H 0].\n  eauto. \nQed.\n\nTheorem Invariance u :\n  universal u -> forall u', exists d,\n  forall x y, C_ u x y -> forall y', C_ u' x y' -> y <= y' + d.\nProof.\n  intros Hu u'.\n  destruct (Hu u') as [d Hd]. exists (|d|).\n  intros x ? ((y & -> & H) & Hleast) _ ((y' & -> & H2) & Hleast2).\n  eapply Hd in H2.\n  rewrite Hleast. 2: eauto.\n  rewrite length_pair. lia.\nQed.\n\nAxiom u : nat.\nAxiom univ_u : universal u.\n\nDefinition N (x : nat) :=\n  exists y, ϕ u y ▷ x /\\ |y| < |x|.\n\nDefinition R (x : nat) :=\n  forall y, ϕ u y ▷ x -> |y| >= |x|.\n\nLemma R_neg_N x :\n  R x <-> ~ N x.\nProof.\n  split.\n  - intros H (y & H1 % H & H2). lia.\n  - intros H y H1.\n    assert (|y| >= |x| \\/ |y| < |x|) as [ Ha | Ha ] by lia; [ auto | ].\n    destruct H. exists y. eauto.\nQed.\n\nLemma MP_choice (R : nat -> nat -> Prop) : MP -> enumerable (fun '(x,y) => R x y) ->\n  (forall x, ~~ exists y, R x y) -> exists f, forall x, R x (f x).\nProof.\n  intros.\n  eapply enumerable_AC; eauto.\n  intros x. eapply MP_to_MP_semidecidable in H.\n  red in H. eapply H with (p := fun x => exists n, R x n).\n  - eapply SemiDecidabilityFacts.semi_decidable_ex.\n    eapply SemiDecidabilityFacts.enumerable_semi_decidable; eauto.\n    eapply ReducibilityFacts.enumerable_red.\n    4: exact H0. all:eauto.\n    exists (fun '(x,y) => (y, x)). intros []. firstorder.\n  - eauto.\nQed.\n\nLemma enum_to:\n  forall q : nat -> Prop, enumerable q -> enumerable (fun '(x, y) => x < | y | /\\ q y).\nProof.\n  intros q [f Hf].\n  exists (fun nx => let (n, x) := embed_nat.unembed nx in if f n is Some y then if x <? |y| then Some (x, y) else None else None).\n  intros (x, y). cbn -[Nat.ltb]. split.\n  - intros [H1 [n H2] % Hf]. exists (embed_nat.embed (n, x)).\n    rewrite embed_nat.embedP, H2.\n    destruct (Nat.ltb_spec x (|y|)).\n    + reflexivity.\n    + lia.\n  - intros (nx & H).\n    destruct (embed_nat.unembed nx) as [n x'].\n    destruct (f n) as [y'|] eqn:E; inversion H.\n    destruct (Nat.ltb_spec x' (|y'|)); inversion H; subst.\n    firstorder.\nQed.\n\nLemma par_enum_ϕ :\n  enumerable (fun '(x, y) => ϕ u y ▷ x).\nProof.\n  eapply ReducibilityFacts.enumerable_red.\n  4: eapply enumerable_graph_part; eauto.\n  all: eauto.\n  exists (fun '(x,y) => (y, x)). intros [].  cbn. reflexivity.\nQed.\n\nLemma enumerable_N :\n  enumerable N.\nProof.\n  destruct (par_enum_ϕ) as [f Hf].\n  exists (fun n => if f n is Some (x,y) then if Nat.ltb (|y|) (|x|) then Some x else None else None).\n  red. intros x. split.\n  - intros (y & H1 & H2).\n    eapply (Hf (x, y)) in H1 as [n Hn].\n    exists n. rewrite Hn.\n    destruct (Nat.ltb_spec (|y|) (|x|)).\n    + reflexivity.\n    + lia.\n  - intros [n Hn]. destruct (f n) as [[x' y] | ] eqn:E; inversion Hn.\n    destruct (Nat.ltb_spec (|y|) (|x'|)).\n    + inversion Hn. subst. exists y. split; eauto.\n      eapply (Hf (x, y)). eauto.\n    + congruence.\nQed.\n\nFrom Undecidability Require Import FinitenessFacts.\nFrom stdpp Require Import base.\nRequire Import List.\n\nLemma list_max_spec L x :\n  In x L -> x <= list_max L.\nProof.\n  induction L.\n  - firstorder.\n  - intros [-> | ]; cbn.\n    + lia.\n    + eapply IHL in H. unfold list_max in H. lia.\nQed.\n\nFrom Undecidability Require Import Pigeonhole.\n\nFrom Undecidability Require Import Dec.\n\nLemma non_finite_unbounded_fun (p : nat -> Prop) f :\n  (forall n, exists L, forall x, f x <= n -> In x L) ->\n  ~ exhaustible p -> forall x, ~~ exists y : nat, f y >= x /\\ p y.\nProof.\n  intros Hsur Hfin n. rewrite non_finite_spec in Hfin.\n  2: intros; destruct (Nat.eq_decidable x1 x2); tauto.\n\n  destruct (Hsur n) as [L HL].\n  specialize (Hfin L).\n  cunwrap. destruct Hfin as (y & H1 & H2).\n  cprove exists y. split; [|eauto].\n  unshelve cstart. 1:eapply le_dec.\n  intros H. apply H2, HL. lia.\nQed.\n\nLemma unbounded_non_finite_fun (p : nat -> Prop) (f : nat -> nat) :\n  (forall k, ~~ exists x, f x >= k /\\ p x) -> ~ exhaustible p.\nProof.\n  intros Hfin. eapply non_finite_nat.\n  intros n H.\n  pose (N := 1 + list_max (map f (seq 0 n))).\n  eapply (Hfin N).\n  intros (x & H1 & H2).\n  apply H. eexists; split. 2: eauto.\n  assert (x < n \\/ x >= n) as [ | ] by lia; try lia.\n  enough (f x > f x) by lia. subst N.\n  unfold gt. unfold ge in H1.\n  eapply Nat.lt_le_trans. 2: eauto. red. cbn.\n  rewrite <- Nat.succ_le_mono.\n  eapply list_max_spec.\n  eapply in_map_iff. exists x. split; eauto.\n  eapply in_seq. lia.\nQed.\n\nLemma NoDup_app {X} (l1 l2 : list X) :\n  NoDup l1 -> NoDup l2 -> (forall x, In x l1 -> ~ (In x l2)) -> NoDup (l1 ++ l2).\nProof.\n  induction 1 in l2 |- *.\n  - eauto.\n  - intros Hl2 Hel. cbn. econstructor. 2:eapply IHNoDup; eauto.\n    + intros [ | ] % in_app_iff; firstorder.\nQed.\n\nLemma NoDup_map {X Y} (f : X -> Y) l :\n  Inj (=) (=) f -> NoDup l -> NoDup (map f l).\nProof.\n  induction 2; cbn; econstructor.\n  1:intros (? & ? % H & ?) % in_map_iff.\n  all: firstorder congruence.\nQed.\n\nLemma bitlist_for_k k :\n  exists l : list (list bool), (forall x, In x l <-> length x = k) /\\ NoDup l /\\ length l = 2 ^ k.\nProof.\n  induction k.\n  - exists (nil :: nil). split; [ | split ].\n    + cbn. intros []; cbn in *; firstorder congruence.\n    + repeat econstructor; eauto.\n    + reflexivity.\n  - destruct IHk as (L & IH1 & IH2 & IH3).\n    exists (map (cons true) L ++ map (cons false) L).\n    split; [ | split].\n    + intros l.\n      rewrite in_app_iff, !in_map_iff.\n      setoid_rewrite IH1.\n      destruct l as [ | ].\n      * cbn. split. 2:lia.\n        intros [(? & [=] & ?) | (? & [=] & ?)].\n      * cbn. split. \n        -- intros [(? & [=] & ?) | (? & [=] & ?)]; subst; lia.\n        -- destruct b; intros [=]; eauto.\n    + eapply NoDup_app; try eapply NoDup_map; eauto.\n      intros ? (? & <- & ?) % in_map_iff (? & ? & ?) % in_map_iff.\n      congruence.\n    + rewrite app_length, !map_length, IH3. cbn. lia.\nQed.\n\nLemma list_for_k k :\n  exists l, (forall x, In x l <-> | x | = k) /\\ NoDup l /\\ length l = 2 ^ k.\nProof.\n  destruct (bitlist_for_k k) as (l & H1 & H2 & H3).\n  exists (map tonat l). split; [ | split].\n  - intros x. cbn. rewrite in_map_iff.\n    setoid_rewrite H1. split.\n    + intros (y & <- & <-). now autorewrite with length.\n    + intros <-. exists (ofnat x). now autorewrite with length. \n  - eapply NoDup_map; auto. intros ? ? E % (f_equal ofnat).\n    now rewrite !ofnat_tonat in E.\n  - now rewrite map_length.\nQed.\n\nLemma list_for_le_k k :\n  exists l, (forall x, In x l <-> | x | <= k) /\\ NoDup l /\\ length l = 2 ^ (S k) - 1.\nProof.\n  induction k.\n  - cbn. exists [ tonat nil ]. \n    split; [ | split ].\n    + cbn. split.\n      * intros [ <- | []]. now autorewrite with length.\n      * intros H. left. destruct (ofnat x) eqn:E; inversion H.\n        rewrite <- E. now autorewrite with length.\n    + repeat econstructor. firstorder.\n    + reflexivity.\n  - cbn. destruct IHk as (l1 & IH1 & IH2 & IH3).\n    destruct (list_for_k (S k)) as (l2 & H1 & H2 & H3).\n    exists (l1 ++ l2). split; [ | split].\n    + intros. rewrite in_app_iff, IH1, H1.\n      lia.\n    + eapply NoDup_app; firstorder lia.\n    + rewrite app_length, IH3, H3. cbn; lia.\nQed.\n\nLemma at_most k : k > 0 ->\n  forall l, (forall x, In x l -> | x | < k) -> NoDup l -> length l <= 2^ k - 1.\nProof.\n  intros Hk l H1 H2. unfold lt in H1.\n  destruct k.\n  - lia.\n  - setoid_rewrite <- Nat.succ_le_mono in H1.\n    destruct (list_for_le_k k) as (l2 & H3 & H4 & H5).\n    assert (length l <= length l2). {\n      eapply NoDup_incl_length; firstorder.\n    }\n    enough (length l2 <= 2 ^ (S k) - 1) by lia.\n    rewrite H5. lia.\nQed.\n\nDefinition injective {X Y} (R : X -> Y -> Prop) :=\n  forall x1 x2 y, R x1 y -> R x2 y -> x1 = x2.\n\nLemma Forall2_ex_r {X Y} (R : X -> Y -> Prop) l1 l2 y :\n  Forall2 R l1 l2 ->\n  In y l2 -> exists x, In x l1 /\\ R x y.\nProof.\n  induction 1; repeat firstorder subst.\nQed.\n\nLemma functional_NoDup (R : nat -> nat -> Prop) l :\n  injective R ->\n  (forall x, In x l -> exists y, R x y) ->\n  NoDup l ->\n  exists l', NoDup l' /\\ Forall2 R l l'.\nProof.\n  intros HR Htot Hl. induction Hl.\n  - exists []. split; econstructor. \n  - destruct IHHl as (l' & H1 & H2).\n    + firstorder.\n    + destruct (Htot x) as [y Hy].\n      1: firstorder.\n      exists (y :: l'). split.\n      * econstructor; [ | eauto].\n        intros Hin.\n        edestruct @Forall2_ex_r as (x' & H3 & H4); eauto.\n        eapply H. eapply HR in H4 as <-; eauto.\n      * econstructor; eauto.\nQed.\n\nLemma nonrandom_k k :\n  ~ forall x, |x| = k -> N x.\nProof.\n  intros H.\n  destruct (list_for_k k) as (l & H1 & H2 & H3).\n  eapply (functional_NoDup (fun x y => ϕ u y ▷ x ∧ | y | < | x |)) in H2 as (l' & H4 & H5).\n  - assert (Forall (fun y => |y| < k) l'). {\n      eapply list.Forall2_Forall_r; eauto.\n      cbn. eapply Forall_forall.\n      intros ? ? % H1. lia.\n    } \n    assert (length l' = 2 ^ k). { erewrite <- list.Forall2_length; eauto. }\n    destruct k.\n    + cbn in *. destruct H0.  1:inversion H2. cbn in *. lia.\n    + unshelve epose proof (@at_most (S k) _ l' _ _).\n      * lia.\n      * eapply Forall_forall. eauto.\n      * eauto.\n      * rewrite H2 in H6.\n        enough (2 ^ S k > S k) by lia.\n        eapply Nat.pow_gt_lin_r. lia.\n  - intros x1 x2 y [Hx1 Hx11] [Hx2 Hx22]. eapply hasvalue_det; eauto.\n  - intros x (y & ? & ?) % H1 % H. eauto.\nQed.\n\nLemma unboundedR :\n  forall k, ~~ exists x, | x | = k /\\ R x.\nProof.\n  setoid_rewrite R_neg_N. intros k G.\n  assert (forall x, |x| = k -> ~~ N x) by firstorder. clear G.\n  pose proof (nonrandom_k k).\n  pose proof (list_for_k k) as (l & H1 & H2 & H3).\n  setoid_rewrite <- H1 in H.\n  setoid_rewrite <- H1 in H0. clear - H H0.\n  induction l.\n  - eapply H0. firstorder.\n  - eapply H.\n    + now left.\n    + intros Ha. eapply IHl.\n      * intros HH. eapply H0. intros. inversion H1 as [-> | ]; eauto.\n      * firstorder.\nQed.\n\nLemma non_finite_length (p : nat -> Prop) :\n  ~ exhaustible p -> forall x, ~~ exists y, x < | y | /\\ p y.\nProof.\n  intros H.\n  unshelve epose proof (non_finite_unbounded_fun _ (fun x => |x|) _ H).\n  - cbn. intros n.\n    destruct (@list_for_le_k n) as [L HL].\n    exists L. intros. eapply HL. eauto.\n  - intros x. specialize (H0 (S x)). cunwrap.\n    destruct H0 as (y & H1 & H2). cprove exists y.\n    split. 1:lia. assumption.\nQed.\n\nLemma classical_finite {X} (p q : X -> Prop):\n  listable p -> (forall x, p x -> ~~ q x) -> ~~ forall x, p x -> q x.\nProof.\n  intros [l Hl]. red in Hl.\n  setoid_rewrite Hl. clear p Hl.\n  induction l.\n  - firstorder.\n  - cbn. intros H.\n    specialize (IHl ltac:(firstorder)).\n    cunwrap. ccase (q a) as [Ha | Ha].\n    + cprove intros ? [-> | ]; eauto.\n    + specialize (H a); firstorder.\nQed.\n\nLemma non_finite_R :\n  ~ exhaustible R.\nProof.\n  eapply unbounded_non_finite_fun with (f := fun x => |x|).\n  intros k G.\n  setoid_rewrite R_neg_N in G.\n  assert (forall x, |x| = k -> ~~ N x).\n  { intros x Hx GG. apply G. exists x. split. 1:lia. assumption. }\n  clear G.\n\n  eapply classical_finite in H.\n  1:cstart; cunwrap; intros _; now eapply (nonrandom_k k).\n  destruct (list_for_k k) as (L & H1 & _ & _).\n  firstorder.\nQed.\n\nLemma dist f :\n  exists d, forall x, exists y_x, ϕ u y_x ▷ f x /\\ | y_x| < |x| + d.\nProof.\n  destruct (EPF_univ_tot univ_u f) as [c Hc].\n  exists (|c| + 1). intros x.\n  exists (⟨ c, x ⟩). split. 1: eauto.\n  autorewrite with length. lia.\nQed.\n\nLemma subset :\n  MP -> forall q : nat -> Prop, (forall x, q x -> R x) -> enumerable q -> ~ exhaustible q -> False.\nProof.\n  intros mp q H1 H2 H3.\n  unshelve epose proof (MP_choice _ mp _ (non_finite_length _ H3)) as [f Hf].\n  1: now eapply enum_to.\n  assert (forall k y, ϕ u y ▷ f k -> |f k| <= |y|). {\n    intros. destruct (Hf k) as [Hk1 Hk2]. \n    eapply H1; eauto.\n  }\n  destruct (dist f) as [d Hd].\n  eapply (length_sublinear d). intros k.\n  transitivity (|f k|). 1:eapply Nat.lt_le_incl, Hf.\n  destruct (Hd k) as (y_k & Hk1 & Hk2).\n  transitivity (|y_k|). 1: eauto.\n  lia.\nQed.\n\nLemma get_partial_choice (R : nat -> nat -> Prop) :\n  enumerable (fun '(x,y) => R x y) ->\n  exists f : nat ↛ nat, forall x v_x,\n    (f x ▷ v_x -> R x v_x) /\\ (R x v_x -> exists v', f x ▷ v').\nProof.\n  intros [f Hf].\n  exists (fun x => bind (mu_tot (fun n => if f n is Some (x', y) then x =? x' else false))\n                (fun n => if f n is Some (x', y) then ret y else undef)).\n  intros x v_x. rewrite bind_hasvalue.\n  split.\n  - intros (n & (H1 & H3) % mu_tot_hasvalue & H2).\n    destruct (f n) as [ [x' y] | ]eqn:E; try congruence.\n    destruct (Nat.eqb_spec x x'); try congruence. subst.\n    eapply ret_hasvalue_iff in H2. subst.\n    eapply (Hf (x', v_x)). eauto.\n  - intros [n Hn] % (Hf (x, v_x)).\n    edestruct (mu_tot_ter) as [a Ha].\n    2:{ destruct (f a) as [[x' y'] | ] eqn:E.\n        - eexists. eapply bind_hasvalue. exists a. split. 1: eapply Ha.\n          rewrite E. eapply ret_hasvalue.\n        - eapply mu_tot_hasvalue in Ha as [Ha _].\n          rewrite E in Ha. congruence.\n    }\n    cbn. rewrite Hn. eapply Nat.eqb_refl.\nQed.\n\nLemma dist_strong R :\n  weakly_total R -> enumerable (fun '(x,y) => R x y) ->\n  exists d, forall x, exists y_x, ~~ exists v_x, R x v_x /\\ ϕ u y_x ▷ v_x /\\ | y_x| < |x| + d.\nProof.\n  intros Htot [f Hf] % get_partial_choice.\n  destruct (EPF_univ univ_u f) as [c Hc].\n  exists (|c| + 1). intros x.\n  exists (⟨ c, x ⟩).\n  specialize (Htot x). cunwrap. destruct Htot as [v_x' Hvx].\n  pose proof (Hvx' := Hvx).\n  eapply Hf in Hvx as [v_x Hvx].\n  cprove exists v_x.\n  repeat split.\n  - eapply Hf. eauto.\n  - eapply Hc. eauto.\n  - autorewrite with length. lia.\nQed.\n\nLemma subset_strong :\n  forall q : nat -> Prop, (forall x, q x -> R x) -> enumerable q -> ~ exhaustible q -> False.\nProof.\n  intros q H1 H2 H3.\n  destruct (dist_strong (fun k x => k < |x| /\\ q x)) as [d Hd].\n  - exact (non_finite_length _ H3).\n  - now eapply enum_to.\n  - eapply (length_sublinear d). intros k.\n    destruct (Hd k) as [y_k H].\n    unshelve cstart. 1:eapply le_dec.\n    cunwrap. destruct H as (x_k & [H4 H5] & H6 & H7).\n    cprove idtac.\n    transitivity (|x_k|). 1:eapply Nat.lt_le_incl, H4.\n    transitivity (|y_k|). 1: eapply H1; eauto. lia.\nQed.\n\nLemma exhaustible_ext {X} (p q : X -> Prop) :\n  exhaustible p -> (forall x, p x <-> q x) -> exhaustible q.\nProof.\n  firstorder.\nQed.\n\nLemma simple_N : MP -> simple N.\nProof.\n  split. 2: split.\n  - eapply enumerable_N.\n  - intros ?. eapply non_finite_R, exhaustible_ext. 1: eauto.\n    intros. now rewrite R_neg_N.\n  - intros (q & H1 & H2 & H3). eapply subset; try eassumption.\n    intros. eapply R_neg_N; eauto. firstorder.\nQed.\n\nLemma simple_N_strong : simple N.\nProof.\n  split. 2: split.\n  - eapply enumerable_N.\n  - intros ?. eapply non_finite_R, exhaustible_ext. 1: eauto.\n    intros. now rewrite R_neg_N.\n  - intros (q & H1 & H2 & H3). eapply subset_strong; try eassumption.\n    intros. eapply R_neg_N; eauto. firstorder.\nQed.\n\nLemma dist_again :\n  forall f : nat -> nat, exists d, forall x y, C_ u (f x) y -> y <= |x| + d.\nProof.\n  intros f.\n  destruct (dist f) as [d Hd]. exists d.\n  intros x y H. destruct (Hd x) as (y_x & H1 & H2).\n  etransitivity.\n  - eapply H; eauto.\n  - lia.\nQed.\n\nLemma R_undecidable :\n  MP -> ~ decidable R.\nProof.\n  intros mp Hdec.\n  unshelve epose proof (MP_choice _ mp _ unboundedR) as [g Hg].\n  - cbn. eapply decidable_enumerable. 2:eauto.\n    eapply DecidabilityFacts.decidable_iff.\n    eapply DecidabilityFacts.decidable_iff in Hdec. destruct Hdec.\n    econstructor. intros (x, y).\n    exact _.\n  - destruct (dist_again g) as [d].\n    eapply length_sublinear with (d := d).\n    intros k.\n    unshelve cstart.  1:eapply le_dec.\n    pose proof (C_weakly_total u (g k) univ_u) as Hk. cunwrap.\n    destruct Hk as [C_u_k Hcuk].\n    cprove idtac.\n    transitivity (| g k|).\n    1:{ eapply Nat.eq_le_incl. symmetry. eapply Hg. }\n    destruct Hcuk as ([? [-> H1]] & H2).\n    etransitivity.\n    1:{ eapply Hg. eapply H1. }\n    eapply H. cbn. firstorder.\nQed.\n\nLemma dist_again_strong R :\n  weakly_total R -> enumerable (fun '(x,y) => R x y) ->\n  exists d, forall x, ~~ exists v_x, R x v_x /\\ forall y, C_ u (v_x) y -> y <= |x| + d.\nProof.\n  intros H1 H2.\n  destruct (dist_strong R H1 H2) as [d Hd].\n  exists d. intros x.\n  destruct (Hd x) as [y_x Hyx].\n  cunwrap. destruct Hyx as (v_x & H3 & H4 & H5).\n  cprove exists v_x. split; eauto.\n  intros.\n  etransitivity. 1:eapply H; eauto.\n  lia.\nQed.\n\nLemma R_undecidable_strong :\n  ~ decidable R.\nProof.\n  intros Hdec.\n  destruct (dist_again_strong (fun k x => |x| = k /\\ R x)) as [d Hd]. \n  - exact unboundedR.\n  - cbn. eapply decidable_enumerable. 2:eauto.\n    eapply DecidabilityFacts.decidable_iff.\n    eapply DecidabilityFacts.decidable_iff in Hdec. destruct Hdec.\n    econstructor. intros (x, y).\n    exact _.\n  - eapply length_sublinear with (d := d).\n    intros k.\n    specialize (Hd k).\n    unshelve cstart.  1:eapply le_dec. cunwrap.\n    destruct Hd as (x_k & [H1 H2] & H3).\n    rewrite <- H1 at 1.\n    pose proof (C_weakly_total u x_k univ_u) as Hk. cunwrap.\n    destruct Hk as [C_u_k Hcuk].\n    destruct Hcuk as ([? [-> H4]] & H5).\n    cprove idtac.\n    etransitivity. 1:{ eapply H2. eauto. }\n    eapply H3. cbn. firstorder.\nQed.\n", "meta": {"author": "yforster", "repo": "coq-kolmogorov-complexity", "sha": "0a287dec30d1ace090d7a15475e006a5cefeb28d", "save_path": "github-repos/coq/yforster-coq-kolmogorov-complexity", "path": "github-repos/coq/yforster-coq-kolmogorov-complexity/coq-kolmogorov-complexity-0a287dec30d1ace090d7a15475e006a5cefeb28d/Synthetic/Kolmogorov.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985637, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.6815818577973126}}
{"text": "Require Import Rsequence.\nRequire Import Rseries_def Rseries_base_facts Rseries_cv_facts Rseries_pos_facts.\n\nRequire Import Lra MyRIneq.\n\nLocal Open Scope R_scope.\nLocal Open Scope Rseq_scope.\n\n(** Remainder caracterization *)\n\nLemma Rser_rem_ext: forall An l Hl Bn l' Hl' n,\n  An == Bn -> Rser_rem An l Hl n = Rser_rem Bn l' Hl' n.\nProof.\nintros ; apply Rminus_eq_compat ;\n [eapply Rser_cv_unique | eapply Rseq_sum_ext] ;\n [ | erewrite Rser_cv_ext |] ; eassumption.\nQed.\n\nLemma Rser_rem_cv : forall An l (Hl : Rser_cv An l ) (n : nat), \n    Rser_cv (Rseq_shifts An (S n)) (Rser_rem An l Hl n).\nProof.\nintros An l Hl n ; unfold Rser_cv ; eapply Rseq_cv_eq_compat.\n intro p ; eapply Rseq_sum_shifts_compat.\n unfold Rser_rem ; apply Rseq_cv_minus_compat.\n  apply Rseq_cv_shifts_compat_reciprocal ; assumption.\n  apply Rseq_constant_cv.\nQed.\n\n(** Compatibility between remainder and usual operations *)\n\nLemma Rser_rem_scal_compat_l: forall An l (k : R) Hkl Hl,\n  Rser_rem (k * An) (k * l) Hkl == k * Rser_rem An l Hl.\nProof.\nintros An l k Hkl Hl n ; unfold Rser_rem ; rewrite Rseq_sum_scal_compat_l ;\n unfold Rseq_plus, Rseq_minus, Rseq_constant, Rseq_mult ;  ring.\nQed.\n\nLemma Rser_rem_scal_compat_r: forall An l (k : R) Hlk Hl,\n  Rser_rem (An * k) (l * k) Hlk == Rser_rem An l Hl * k.\nProof.\nintros An l k Hlk Hl n ; unfold Rser_rem ; rewrite Rseq_sum_scal_compat_r ;\n unfold Rseq_plus, Rseq_minus, Rseq_constant, Rseq_mult ;  ring.\nQed.\n\nLemma Rser_rem_opp_compat: forall An l Hl Hl2,\n  Rser_rem (- An) (- l) Hl == - Rser_rem An l Hl2.\nProof.\nintros An l Hl Hl2 n ; unfold Rser_rem ; rewrite Rseq_sum_opp_compat ;\n unfold Rseq_plus, Rseq_minus, Rseq_opp ; ring.\nQed.\n\nLemma Rser_rem_plus_compat: forall An Bn la lb Hla Hlb Hlab,\n  Rser_rem An la Hla + Rser_rem Bn lb Hlb == Rser_rem (An + Bn) (la + lb) Hlab.\nProof.\nintros An Bn la lb Hla Hlb Hlab n ; unfold Rser_rem ;\n rewrite Rseq_sum_plus_compat ; unfold Rseq_plus, Rseq_minus ; ring.\nQed.\n\nLemma Rser_rem_minus_compat: forall An Bn la lb Hla Hlb Hlab,\n  Rser_rem An la Hla - Rser_rem Bn lb Hlb == Rser_rem (An - Bn) (la - lb) Hlab.\nProof.\nintros An Bn la lb Hla Hlb Hlab n ; unfold Rser_rem ;\n rewrite Rseq_sum_minus_compat ; unfold Rseq_plus, Rseq_minus ; ring.\nQed.\n\n(** Convergence results *)\n\nLemma Rser_Rser_rem_equiv: forall An Bn x l (H : Rser_cv Bn l) n,\n  (forall k, An k = Rseq_shifts Bn (S n) k) -> \n  Rser_cv An x -> x = Rser_rem Bn l H n.\nProof.\nintros An Bn x l Hl n Heq Hx ; eapply Rser_cv_unique.\n apply Hx.\n eapply Rser_cv_ext with (Rseq_shifts Bn (S n)).\n  intro ; apply Heq.\n  apply Rser_cv_shifts ; assumption.\nQed.\n\nLemma Rser_rem_pos: forall An k l (Hl : Rser_cv An l) , \n  (forall n, (n > k)%nat -> An n >= 0) ->\n  {n | (n > k)%nat /\\ An n > 0} ->\n  Rser_rem An l Hl k > 0.\nProof.\nintros An k l Hl An_pos [n [nk Hn]] ; apply Rlt_Rminus, Rlt_le_trans with (Rseq_sum An n).\n destruct n ; [inversion nk |].\n  rewrite Rseq_sum_simpl ;apply Rle_lt_trans with (Rseq_sum An n) ; [| lra].\n  clear Hn ; induction n.\n   assert (k = O) by omega ; subst ; reflexivity.\n   destruct (eq_nat_dec k (S n)).\n    subst ; reflexivity.\n    assert (S n > k)%nat by omega ; assert (0 <= An (S n)) by (apply Rge_le, An_pos ; auto) ;\n    rewrite Rseq_sum_simpl ; transitivity (Rseq_sum An n) ; [intuition | lra].\n   eapply Rseq_limit_comparison with (Rseq_sum An n) (Rseq_shifts (Rseq_sum An) n).\n   intro p ; induction p ; unfold Rseq_constant, Rseq_shifts in *.\n    rewrite plus_0_r ; reflexivity.\n    rewrite <- plus_n_Sm, Rseq_sum_simpl ; assert (0 <= An (S (n +p)))\n     by (apply Rge_le, An_pos ; omega) ; lra.\n   apply Rseq_constant_cv.\n   apply Rseq_cv_shifts_compat_reciprocal ; assumption.\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/Reals/Rseries/Rseries_remainder_facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162774, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.6815818566653665}}
{"text": "Require Export ZArith.\n\nInductive Z_btree : Set :=\n  Z_leaf : Z_btree | Z_bnode : Z->Z_btree->Z_btree->Z_btree.\n\nInductive btree (A:Type) :Type :=\n  bleaf : btree A | 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 => bnode Z x\n                         (Z_btree_to_btree t1)\n                         (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 => Z_bnode x\n                         (btree_to_Z_btree t1)\n                         (btree_to_Z_btree t2)\n  end.\n\nTheorem btree_to_Z_inv :\n forall t, Z_btree_to_btree (btree_to_Z_btree t) = t.\nProof.\n intros t; elim t; simpl; auto.\n intros x t1 IHt1 t2 IHt2; rewrite IHt1; rewrite IHt2;auto.\nQed.\n\nTheorem Z_btree_to_inv :\n forall t, btree_to_Z_btree (Z_btree_to_btree t) = t.\nProof.\n intros t; elim t; simpl; auto.\n intros x t1 IHt1 t2 IHt2; rewrite IHt1; rewrite IHt2;auto.\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/poly_tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.6815818546156784}}
{"text": "\n(**************************************************************************)\n(**  Mechanised Framework for Local Interactions & Distributed Algorithms   \n                                                                            \n     T. Balabonski, P. Courtieu, L. Rieg, X. Urbain                         \n                                                                            \n     PACTOLE project                                                        \n                                                                            \n     This file is distributed under the terms of the CeCILL-C licence     *)\n(**************************************************************************)\n\n\n(**************************************************************************)\n(* Author : Mathis Bouverot-Dupuis (June 2022).\n\n * This file implements an algorithm to ALIGN all robots on an arbitrary \n * axis, in the plane (R²). The algorithm assumes there are no byzantine robots,\n * and works in a RIGID and SEMI-SYNCHRONOUS setting.\n\n * The algorithm is as follows : all robots go towards the 'weber point' of \n * the configuration. The weber point, also called geometric median, is unique \n * if the robots are not aligned, and has the property that moving any robot\n * towards the weber point in a straight line doesn't change the weber point. \n * It thus remains at the same place throughout the whole execution.  *)\n(**************************************************************************)\n\n\nRequire Import Bool.\nRequire Import Arith.Div2.\nRequire Import Lia Field.\nRequire Import Rbase Rbasic_fun R_sqrt Rtrigo_def.\nRequire Import List.\nRequire Import SetoidList.\nRequire Import Relations.\nRequire Import RelationPairs.\nRequire Import Morphisms.\nRequire Import Psatz.\nRequire Import Inverse_Image.\nRequire Import FunInd.\nRequire Import FMapFacts.\n\n(* Helping typeclass resolution avoid infinite loops. *)\nTypeclasses eauto := (bfs).\n\n(* Pactole basic definitions *)\nRequire Export Pactole.Setting.\n(* Specific to R^2 topology *)\nRequire Import Pactole.Spaces.R2.\n(* Specific to gathering *)\nRequire Pactole.CaseStudies.Gathering.WithMultiplicity.\nRequire Import Pactole.CaseStudies.Gathering.Definitions.\n(* Specific to multiplicity *)\nRequire Import Pactole.Observations.MultisetObservation.\n(* Specific to rigidity *)\nRequire Import Pactole.Models.Rigid.\n(* Specific to settings with no Byzantine robots *)\nRequire Import Pactole.Models.NoByzantine.\n(* Utility lemmas. *)\nRequire Import Pactole.CaseStudies.Gathering.InR2.Weber.Utils.\n(* Specific to definition and properties of the weber point. *)\nRequire Import Pactole.CaseStudies.Gathering.InR2.Weber.Weber_point.\n\n\n(* User defined *)\nImport Permutation.\nImport Datatypes.\n\nSet Implicit Arguments.\nClose Scope R_scope.\nClose Scope VectorSpace_scope.\n\n\n\nSection Alignment.\n\n(* We assume the existence of a function that calculates a weber point of a collection\n * (even when the weber point is not unique).\n * This is a very strong assumption : such a function may not exist in closed form, \n * and the Weber point can only be approximated. *)\nAxiom weber_calc : list R2 -> R2.\nAxiom weber_calc_correct : forall ps, Weber ps (weber_calc ps).\n(* We also suppose this function doesn't depend on the order of the points. \n* This is probably not necessary (we can show that it holds when the points aren't colinear) \n* but simplifies the proof a bit. *)\nAxiom weber_calc_compat : Proper (PermutationA equiv ==> equiv) weber_calc.\nLocal Existing Instance weber_calc_compat.\n \n(* The number of robots *)\nVariables n : nat.\nHypothesis lt_0n : 0 < n.\n\n\n(* There are no byzantine robots. *)\nLocal Instance N : Names := Robots n 0.\nLocal Instance NoByz : NoByzantine.\nProof using . now split. Qed.\n\n(* The robots are in the plane (R^2). *)\nLocal Instance Loc : Location := make_Location R2.\nLocal Instance LocVS : RealVectorSpace location := R2_VS.\nLocal Instance LocES : EuclideanSpace location := R2_ES.\n\n(* Refolding typeclass instances *)\nLtac foldR2 :=\n  change R2 with location in *;\n  change R2_Setoid with location_Setoid in *;\n  change state_Setoid with location_Setoid in *;\n  change R2_EqDec with location_EqDec in *;\n  change state_EqDec with location_EqDec in *;\n  change R2_VS with LocVS in *;\n  change R2_ES with LocES in *.\n\n\n(* Robots don't have an state (and thus no memory) apart from their location. *)\nLocal Instance St : State location := OnlyLocation (fun f => True).\nLocal Instance RobotC : robot_choice location := {| robot_choice_Setoid := location_Setoid |}.\n\n(* Robots view the other robots' positions up to a similarity. *)\nLocal Instance FrameC : frame_choice (similarity location) := FrameChoiceSimilarity.\nLocal Instance UpdateC : update_choice unit := NoChoice.\nLocal Instance InactiveC : inactive_choice unit := NoChoiceIna.\n\n(* We are in a rigid and semi-synchronous setting. *)\nLocal Instance UpdateF : update_function _ _ _.\n  refine {| update := fun _ _ _ target _ => target |}.\nProof using . now repeat intro. Defined. \nLocal Instance InactiveF : inactive_function _.\n  refine {| inactive := fun config id _ => config id |}.\nProof using . repeat intro. now subst. Defined.\nLocal Instance Rigid : RigidSetting.\nProof using . split. reflexivity. Qed.\n\n(* The support of a multiset, but elements are repeated \n * a number of times equal to their multiplicity. \n * This is needed to convert an observation from multiset to list format, \n * so that we can use functions [colinear_dec] and [weber_calc]. *)\nDefinition multi_support {A} `{EqDec A} (s : multiset A) :=\n  List.flat_map (fun '(x, mx) => alls x mx) (elements s).\n\nLocal Instance multi_support_compat {A} `{EqDec A} : Proper (equiv ==> PermutationA equiv) (@multi_support A _ _).\nProof using . \nintros s s' Hss'. unfold multi_support. f_equiv.\n+ intros [x mx] [y my] Hxy. inv Hxy. simpl in H0, H1. now rewrite H0, H1.\n+ now apply elements_compat.\nQed.\n\n\n(* The main algorithm : just move towards the weber point until all robots are aligned. *)\nDefinition gatherW_pgm obs : location := \n  if aligned_dec (multi_support obs) \n  (* Don't move (the robot's local frame is always centered on itself, i.e. its position is at the origin). *)\n  then origin \n  (* Go towards the weber point. *)\n  else weber_calc (multi_support obs).\n\nLocal Instance gatherW_pgm_compat : Proper (equiv ==> equiv) gatherW_pgm.\nProof using .\nintros s1 s2 Hs. unfold gatherW_pgm.\nrepeat destruct_match.\n+ reflexivity.\n+ rewrite Hs in a. now intuition.\n+ rewrite Hs in n0. now intuition.\n+ apply weber_unique with (multi_support s1) ; auto.\n  - rewrite Hs. now apply weber_calc_correct.\n  - now apply weber_calc_correct.\nQed.\n\nDefinition gatherW : robogram := {| pgm := gatherW_pgm |}.\n\nLemma multi_support_add {A : Type} `{EqDec A} s x k : ~ In x s -> k > 0 ->\n  PermutationA equiv (multi_support (add x k s)) (alls x k ++ multi_support s).\nProof using . \nintros Hin Hk. unfold multi_support. \ntransitivity (flat_map (fun '(x0, mx) => alls x0 mx) ((x, k) :: elements s)).\n+ f_equiv.\n  - intros [a ka] [b kb] [H0 H1]. cbn in H0, H1. now rewrite H0, H1.\n  - apply elements_add_out ; auto.\n+ now cbn -[elements].\nQed.\n\nLemma multi_support_countA {A : Type} `{eq_dec : EqDec A} s x :\n  countA_occ equiv eq_dec x (multi_support s) == s[x]. \nProof using .\npattern s. apply MMultisetFacts.ind.\n+ intros m m' Hm. f_equiv. \n  - apply countA_occ_compat ; autoclass. now rewrite Hm.\n  - now rewrite Hm.\n+ intros m x' n' Hin Hn IH. rewrite add_spec, multi_support_add, countA_occ_app by auto.\n  destruct_match.\n  - now rewrite <-e, countA_occ_alls_in, Nat.add_comm, IH ; autoclass.\n  - now rewrite countA_occ_alls_out, IH, Nat.add_0_l ; auto.  \n+ now reflexivity.\nQed.\n\n(* This is the main result about multi_support. *)\nLemma multi_support_config config id : \n  PermutationA equiv \n    (multi_support (obs_from_config config (config id))) \n    (config_list config).\nProof using .\ncbv -[multi_support config_list equiv make_multiset List.map]. rewrite List.map_id.\napply PermutationA_countA_occ. intros x. rewrite multi_support_countA. now apply make_multiset_spec.\nQed. \n\nCorollary multi_support_map f config id : \n  Proper (equiv ==> equiv) (projT1 f) ->\n  PermutationA equiv \n    (multi_support (obs_from_config (map_config (lift f) config) (lift f (config id))))\n    (List.map (projT1 f) (config_list config)).\nProof using .  \nintros H. destruct f as [f Pf]. cbn -[equiv config_list multi_support]. \nchange (f (config id)) with (map_config f config id).\nnow rewrite multi_support_config, config_list_map.\nQed.\n\n(* Simplify the [round] function and express it in the global frame of reference. *)\n(* All the proofs below use this simplified version. *)\nLemma round_simplify da config : similarity_da_prop da -> \n  round gatherW da config == \n  fun id => \n    if activate da id then \n      if aligned_dec (config_list config) then config id \n      else weber_calc (config_list config)\n    else config id.\nProof using . \nintros Hsim. apply no_byz_eq. intros g. unfold round. \ncbn -[inverse equiv lift location config_list origin].\ndestruct_match ; try reflexivity.\npose (f := existT (fun _ : location -> location => True)\n  (frame_choice_bijection (change_frame da config g))\n  (precondition_satisfied da config g)).\npose (f_inv := existT (fun _ : location -> location => True)\n  (frame_choice_bijection (change_frame da config g) ⁻¹)\n  (precondition_satisfied_inv da config g)).\nchange_LHS (lift f_inv (gatherW_pgm (obs_from_config \n  (map_config (lift f) config) \n  ((lift f) (config (Good g)))\n))).\nassert (Proper (equiv ==> equiv) (projT1 f)) as f_compat.\n{ unfold f ; cbn -[equiv]. intros x y Hxy ; now rewrite Hxy. }\nunfold gatherW_pgm ; destruct_match.\n+ rewrite multi_support_map in a by auto.\n  cbn -[equiv inverse config_list location] in *. \n  rewrite <-aligned_similarity in a. change_LHS (center (change_frame da config g)).\n  rewrite Hsim ; cbn -[equiv config_list] ; unfold id.\n  now destruct_match ; intuition.\n+ rewrite multi_support_map in * by auto.\n  cbn -[equiv inverse config_list location multi_support] in *.\n  pose (sim := change_frame da config g) ; fold sim in n0 ; fold sim.\n  rewrite <-aligned_similarity in n0. destruct_match ; intuition.\n  apply weber_unique with (config_list config) ; auto ; [now apply weber_calc_correct|].\n  apply weber_similarity with sim. cbn -[config_list]. rewrite Bijection.section_retraction.\n  now apply weber_calc_correct.\nQed.\n  \n(* This is the goal (for all demons and configs). *)\nDefinition eventually_aligned config (d : demon) (r : robogram) := \n  Stream.eventually \n    (Stream.forever (Stream.instant (fun c => aligned (config_list c)))) \n    (execute r d config).\n\n(* If the robots are aligned, they stay aligned. *)\nLemma round_preserves_aligned da config : similarity_da_prop da ->\n  aligned (config_list config) -> aligned (config_list (round gatherW da config)).\nProof using . \nintros Hsim Halign. assert (round gatherW da config == config) as H.\n{ intros id. rewrite round_simplify by auto. repeat destruct_match ; auto. }\nnow rewrite H.\nQed.\n\nLemma aligned_over config (d : demon) :\n  Stream.forever (Stream.instant similarity_da_prop) d ->\n  aligned (config_list config) -> \n  Stream.forever (Stream.instant (fun c => aligned (config_list c))) (execute gatherW d config).\nProof using .\nrevert config d. \ncofix Hind. intros config d Hsim Halign. constructor.\n+ cbn -[config_list]. apply Halign.\n+ cbn -[config_list]. simple apply Hind ; [apply Hsim |]. \n  apply round_preserves_aligned ; [apply Hsim | apply Halign].\nQed.\n\nLemma sub_lt_sub (i j k : nat) : j < i <= k -> k - i < k - j.\nProof using lt_0n. lia. Qed.\n\nLemma list_in_length_n0 {A : Type} x (l : list A) : List.In x l -> length l <> 0.\nProof using . intros Hin. induction l as [|y l IH] ; cbn ; auto. Qed.\n\n(* This would have been much more pleasant to do with mathcomp's tuples. *)\nLemma config_list_In_combine x x' c c' : \n  List.In (x, x') (combine (config_list c) (config_list c')) <-> \n  exists id, x == c id /\\ x' == c' id.\nProof using lt_0n.\nassert (g0 : G).\n{ change G with (fin n). apply (exist _ 0). lia. }\nsplit.\n+ intros Hin. apply (@In_nth (location * location) _ _ (c (Good g0), c' (Good g0))) in Hin.\n  destruct Hin as [i [Hi Hi']]. \n  rewrite combine_nth in Hi' by now repeat rewrite config_list_length. inv Hi'.\n  assert (i < n) as Hin.\n  { \n    eapply Nat.lt_le_trans ; [exact Hi|]. rewrite combine_length.\n    repeat rewrite config_list_length. rewrite Nat.min_id. cbn. lia. \n  }\n  pose (g := exist (fun x => x < n) i Hin).\n  change (fin n) with G in *. exists (Good g) ;\n  split ; rewrite config_list_spec, map_nth ; f_equiv ; unfold names ;\n    rewrite app_nth1, map_nth by (now rewrite map_length, Gnames_length) ;\n    f_equiv ; cbn ; change G with (fin n) ; apply nth_enum.  \n+ intros [[g|b] [Hx Hx']]. \n  - assert ((x, x') = nth (proj1_sig g) (combine (config_list c) (config_list c')) (c (Good g0), c' (Good g0))) as H.\n    { \n      rewrite combine_nth by now repeat rewrite config_list_length.\n      destruct g as [g Hg].\n      repeat rewrite config_list_spec, map_nth. rewrite Hx, Hx'. unfold names.\n      repeat rewrite app_nth1, map_nth by now rewrite map_length, Gnames_length.\n      repeat f_equal ; cbn ; change G with (fin n) ; erewrite nth_enum ; reflexivity.   \n    }\n    rewrite H. apply nth_In. rewrite combine_length. repeat rewrite config_list_length.\n    rewrite Nat.min_id. cbn. destruct g. cbn. lia.\n  - exfalso. assert (Hbyz := In_Bnames b). apply list_in_length_n0 in Hbyz. rewrite Bnames_length in Hbyz. auto.\nQed.\n\n(* This measure strictly decreases whenever a robot moves. *)\nDefinition measure config := \n  let ps := config_list config in \n  n - countA_occ equiv R2_EqDec (weber_calc ps) ps.\n\nLocal Instance measure_compat : Proper (equiv ==> eq) measure.\nProof using . intros c c' Hc. unfold measure. now rewrite Hc. Qed.\n\n(* All the magic is here : when the robots move \n * they go towards the weber point so it is preserved. \n * This still holds in a flexible and/or asynchronous setting.\n * The point calculated by weber_calc thus stays the same during an execution,\n * until the robots are colinear. *)\nLemma round_preserves_weber config da w :\n  similarity_da_prop da -> Weber (config_list config) w -> \n    Weber (config_list (round gatherW da config)) w.\nProof using lt_0n. \nintros Hsim Hweb. apply weber_contract with (config_list config) ; auto.\nunfold contract. rewrite Forall2_Forall, Forall_forall by now repeat rewrite config_list_length.\nintros [x x']. rewrite config_list_In_combine.\nintros [id [Hx Hx']]. revert Hx'. rewrite round_simplify by auto. \nrepeat destruct_match ; intros Hx' ; rewrite Hx, Hx' ; try apply segment_end.\nassert (w == weber_calc (config_list config)) as Hw.\n{ apply weber_unique with (config_list config) ; auto. now apply weber_calc_correct. }\nrewrite <-Hw. apply segment_start.\nQed.\n\n(* If a robot moves, either the measure decreases or the robots become colinear. *)\nLemma round_decreases_measure config da : \n  similarity_da_prop da ->\n  moving gatherW da config <> nil -> \n    aligned (config_list (round gatherW da config)) \\/ \n    measure (round gatherW da config) < measure config.\nProof using lt_0n. \nintros Hsim Hmove. \ndestruct (aligned_dec (config_list (round gatherW da config))) as [Rcol | RNcol] ; [now left|right].\nassert (weber_calc (config_list (round gatherW da config)) == weber_calc (config_list config)) as Hweb.\n{ \n  apply weber_unique with (config_list (round gatherW da config)) ; auto.\n  + apply round_preserves_weber ; [auto | apply weber_calc_correct].\n  + apply weber_calc_correct.  \n}\nunfold measure. apply sub_lt_sub. split.\n+ destruct (not_nil_In Hmove) as [i Hi]. apply moving_spec in Hi.\n  rewrite Hweb. apply countA_occ_lt.\n  - rewrite Forall2_Forall, Forall_forall. intros [x x'] Hin.\n    apply config_list_In_combine in Hin. destruct Hin as [j [-> ->]].\n    rewrite round_simplify by auto. repeat destruct_match ; intuition.\n    repeat rewrite config_list_length. reflexivity.\n  - apply Exists_exists. exists (config i, round gatherW da config i).\n    split ; [| now auto].\n    apply config_list_In_combine. exists i ; intuition.\n+ etransitivity ; [apply countA_occ_length_le|].\n  rewrite config_list_length. cbn ; lia.\nQed.\n\nLemma gathered_aligned ps x : \n  (Forall (fun y => y == x) ps) -> aligned ps.\nProof using . \nrewrite Forall_forall. intros Hgathered.\nunfold aligned. rewrite ForallTriplets_forall.\nintros a b c Ha Hb Hc.\napply Hgathered in Ha, Hb, Hc. rewrite Ha, Hb, Hc, add_opp.\napply colinear_origin_r.\nQed.\n\n(* If the robots aren't aligned yet then there exists at least one robot which, \n * if activated, will move. \n * Any robot that isn't on the weber point will do the trick. *)\nLemma one_must_move config : ~aligned (config_list config) ->\n  exists r, forall da, similarity_da_prop da -> activate da r = true ->\n                       round gatherW da config r =/= config r.\nProof using .\nintros Nalign.\ncut (exists r, config r =/= weber_calc (config_list config)). \n{\n  intros [r Hr]. exists r. intros da Hsim Hact. rewrite round_simplify by auto.\n  repeat destruct_match ; intuition.\n}\nassert (List.Exists (fun x => x =/= weber_calc (config_list config)) (config_list config)) as HE.\n{ \n  apply neg_Forall_Exists_neg ; [intros ; apply equiv_dec|].\n  revert Nalign. apply contra. apply gathered_aligned.\n}\nrewrite Exists_exists in HE. destruct HE as [x [Hin Hx]].\napply (@In_InA R2 equiv _) in Hin. \nfoldR2. change location_Setoid with state_Setoid in *. rewrite config_list_InA in Hin.\ndestruct Hin as [r Hr]. exists r. now rewrite <-Hr.\nQed.\n\n(* Fairness entails progress. *)\nLemma fair_first_move (d : demon) config : \n  Fair d -> Stream.forever (Stream.instant similarity_da_prop) d ->\n  ~(aligned (config_list config)) -> FirstMove gatherW d config.\nProof using .\nintros Hfair Hsim Nalign.\ndestruct (one_must_move config Nalign) as [id Hmove].\ndestruct Hfair as [locallyfair Hfair].\nspecialize (locallyfair id).\nrevert config Nalign Hmove.\ninduction locallyfair as [d Hnow | d] ; intros config Nalign Hmove.\n* apply MoveNow. apply Hmove in Hnow.\n  + rewrite <-(moving_spec gatherW (Stream.hd d) config id) in Hnow.\n    intros Habs. now rewrite Habs in Hnow.   \n  + apply Hsim.\n* destruct (moving gatherW (Stream.hd d) config) as [| id' mov] eqn:Hmoving.\n  + apply MoveLater ; trivial.\n    apply IHlocallyfair.\n    - apply Hfair.\n    - apply Hsim.\n    - apply no_moving_same_config in Hmoving. now rewrite Hmoving.\n    - intros da Hda Hactive. apply no_moving_same_config in Hmoving.\n      rewrite (Hmoving id).\n      apply (round_compat (reflexivity gatherW) (reflexivity da)) in Hmoving. \n      rewrite (Hmoving id).\n      now apply Hmove.\n  + apply MoveNow. rewrite Hmoving. discriminate.\nQed.\n\n(* The proof is essentially a well-founded induction on [measure config].\n * Fairness ensures that the measure must decrease at some point. *)\nTheorem weber_correct (d : demon) config : \n  Fair d -> \n  Stream.forever (Stream.instant similarity_da_prop) d ->\n  eventually_aligned config d gatherW.\nProof using lt_0n.\nremember (measure config) as k. \ngeneralize dependent d. generalize dependent config.\npattern k. apply (well_founded_ind lt_wf). clear k.\nintros k IHk config Hk d Hfair Hsim.\ndestruct (aligned_dec (config_list config)) as [align | Nalign] ;\n  [now apply Stream.Now, aligned_over|].\ninduction (fair_first_move config Hfair Hsim Nalign) as [d config Hmove | d config Hmove FM IH_FM] ;\n  destruct Hsim as [Hsim_hd Hsim_tl] ; cbn in Hsim_hd ; apply Stream.Later.\n+ destruct (round_decreases_measure config Hsim_hd Hmove) as [Ralign | Rmeasure].\n  - now apply Stream.Now, aligned_over.\n  - eapply IHk. \n    * rewrite Hk. exact Rmeasure.  \n    * reflexivity.\n    * destruct Hfair as [_ Hfair_tl]. exact Hfair_tl.\n    * exact Hsim_tl.\n+ apply no_moving_same_config in Hmove.\n  apply IH_FM ; (try rewrite Hmove) ; auto.\n  destruct Hfair as [_ Hfair_tl]. exact Hfair_tl.\nQed.\n\nEnd Alignment.\n", "meta": {"author": "MathisBD", "repo": "pactole_stage", "sha": "4b63da0898ae4f48956408dc31f7831d3ad8930f", "save_path": "github-repos/coq/MathisBD-pactole_stage", "path": "github-repos/coq/MathisBD-pactole_stage/pactole_stage-4b63da0898ae4f48956408dc31f7831d3ad8930f/CaseStudies/Gathering/InR2/Weber/Align_rigid_ssync.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646393, "lm_q2_score": 0.7401743735019594, "lm_q1q2_score": 0.6815449230885653}}
{"text": "(*\n  This file proves that the width used by the rem register in\n  Hausner's implementation if large enough to store any intermediate\n  value that may result while computing the quotient of two\n  floating point binary numbers.\n*)\n\nRequire Import aux.\nRequire Import base.\nRequire Import Reals.\nRequire Import micromega.Lra.\n\nOpen Scope R_scope.\n\n(** Represents the dividend. *)\nParameter a : R.\n\n(** Represents the divisor. *)\nParameter b : R.\n\n(**\n  Asserts the lower and upper bounds on the\n  dividend and divisor.\n\n  These follow because both [a] and [b], have\n  the form: 1.b0b1...bn.\n*)\nAxiom a_lower_bound : 1 <= a.\nAxiom a_upper_bound : a < 2.\nAxiom b_lower_bound : 1 <= b.\nAxiom b_upper_bound : b < 2.\n\n(**\n  Accepts a natural number, [n], and returns the\n  bit append onto our quotient approximation in\n  the n-th iteration.\n*)\nParameter bit : nat -> R.\n\n(**\n  Accepts a natural number, [n], and returns\n  the quotient approximation generated in the\n  n-th iteration.\n*)\nParameter approx : nat -> R.\n\nAxiom bit_0 : forall n : nat, a < b * (approx n + 1/2^n) -> bit n = 0.\n\nAxiom bit_1 : forall n : nat, b * (approx n + 1/2^n) <= a -> bit n = 1.\n\n(**\n  Asserts that [bit n] always returns a binary\n  digit - i.e. a bit.\n*)\nLemma bit_is_bit\n  : forall n : nat, bit n = 0 \\/ bit n = 1.\nProof.\n  exact\n    (fun n\n      => or_ind\n          (fun H : a < b * (approx n + 1/2^n)\n            => or_introl (bit n = 1) (bit_0 n H))\n          (fun H : b * (approx n + 1/2^n) <= a\n            => or_intror (bit n = 0) (bit_1 n H))\n          (Rlt_or_le a (b * (approx n + 1/2^n)))).\nQed.\n\n(**\n  Asserts that the initial quotient approximation\n  is 0.\n*)\nAxiom approx_0 : approx 0 = 0.\n\n(**\n  Asserts that each quotient approximation is\n  produced by appending a bit onto the end of\n  the previous approximation.\n*)\nAxiom approx_Sn : forall n : nat, approx (S n) = approx n + bit n/2^n.\n\n(**\n  Accepts a natural number, [n], and returns\n  a measure of the error between the current\n  quotient approximation and the true value.\n*)\nParameter error : nat -> R.\n\n(** Represents the error equation. *)\nAxiom error_n : forall n : nat, error n = a - b * approx n.\n\n(** Asserts that the error is always positive. *)\nAxiom error_is_pos : forall n : nat, 0 <= error n.\n\nLemma bit_0_inv\n  : forall n : nat, bit n = 0 -> a < b * (approx n + 1/2^n).\nProof.\n  exact\n    (fun n H\n      => or_ind\n           (fun H0 : a < b * (approx n + 1/2^n)\n             => H0)\n           (fun H0 : b * (approx n + 1/2^n) <= a\n             => False_ind _\n                  (R1_neq_R0 (H || X = 0 @X by <- bit_1 n H0)))\n           (Rlt_or_le a (b * (approx n + 1/2^n)))).\nQed.\n\nLemma bit_1_inv\n  : forall n : nat, bit n = 1 -> b * (approx n + 1/2^n) <= a.\nProof.\n  exact\n    (fun n H\n      => or_ind\n           (fun H0 : a < b * (approx n + 1/2^n)\n             => False_ind _\n                  (R1_neq_R0 (eq_sym (H || X = 1 @X by <- bit_0 n H0))))\n           (fun H0 : b * (approx n + 1/2^n) <= a\n             => H0)\n           (Rlt_or_le a (b * (approx n + 1/2^n)))).\nQed.\n\nLemma approx_lower_bound_aux_0 : 0 <= 0 + 2. Proof. lra. Qed.\n\nLemma approx_lower_bound_aux_1\n  : forall n : nat, bit n = 0 -> b * (approx n + 1/2^n) = b * (approx (S n) + 2/2^(S n)).\nProof.\n  intros n H.\n  apply (Rmult_eq_compat_l b (approx n + 1/2^n) (approx (S n) + 2/2^(S n))).\n  rewrite (approx_Sn n).\n  rewrite (Rplus_assoc (approx n) (bit n/2^n) (2/2^(S n))).\n  apply (Rplus_eq_compat_l (approx n) (1/2^n) (bit n/2^n + 2/2^(S n))).\n  rewrite H.\n  unfold Rdiv.\n  rewrite (Rmult_0_l (/2^n)).\n  simpl.\n  rewrite (Rinv_mult_distr 2 (2^n) neq_2_0 (pow_nonzero 2 n neq_2_0)).\n  rewrite <- (Rmult_assoc 2 (/2) (/2^n)).\n  rewrite (Rinv_r 2 neq_2_0).\n  fold (Rdiv 1 (2^n)).\n  rewrite (Rplus_0_l (1/2^n)).\n  reflexivity.\nQed.\n  \nLemma approx_lower_bound_aux_2\n  : forall n : nat, approx n + 1/2^n + 1/2^n = approx n + 2/2^n.\nProof.\n  intro n.\n  rewrite (Rplus_assoc (approx n) (1/2^n) (1/2^n)).\n  apply (Rplus_eq_compat_l (approx n) (1/2^n + 1/2^n) (2/2^n)).\n  unfold Rdiv.\n  rewrite <- (Rmult_plus_distr_r 1 1 (/2^n)).\n  rewrite (ltac:(lra) : 1 + 1 = 2).\n  reflexivity.\nQed.\n\nLemma approx_lower_bound_aux_3\n  : forall n : nat, 2/2^(S n) = 1/2^n.\nProof.\n  intro n.\n  simpl.\n  unfold Rdiv.\n  rewrite (Rinv_mult_distr 2 (2^n) neq_2_0 (pow_nonzero 2 n neq_2_0)).\n  rewrite <- (Rmult_assoc 2 (/2) (/2^n)).\n  rewrite (Rinv_r 2 neq_2_0).\n  reflexivity.\nQed.\n\nLemma approx_lower_bound \n  :  forall n : nat, a < b * (approx n + 2/2^n).\nProof.\n  exact\n    (nat_ind _\n      (Rlt_le_trans a 2 (b * (0 + 2))\n        a_upper_bound \n        (Rle_trans 2 (1 * (0 + 2)) (b * (0 + 2))\n          (ltac:(lra) : 2 <= 1 * (0 + 2))\n          (Rmult_le_compat_r (0 + 2) 1 b\n            approx_lower_bound_aux_0\n            b_lower_bound))\n        || a < b * (X + 2) @X by approx_0\n        || a < b * (approx 0 + X) @X by (ltac:(field) : 2/2^0 = 2))\n      (fun n (H : a < b * (approx n + 2/2^n))\n        => or_ind\n             (fun H0 : bit n = 0\n               => ltac:(\n                    rewrite <- (approx_lower_bound_aux_1 n H0);\n                    exact (bit_0_inv n H0)) :\n                  a < b * (approx (S n) + 2 / 2 ^ S n))\n             (fun H0 : bit n = 1\n               => H\n                  || a < b * X @X by approx_lower_bound_aux_2 n\n                  || a < b * (approx n + X/2^n + 1/2^n) @X by H0\n                  || a < b * (X + 1/2^n) @X by approx_Sn n\n                  || a < b * (approx (S n) + X) @X by approx_lower_bound_aux_3 n)\n             (bit_is_bit n))).\nQed.\n\nLemma error_upper_bound_aux_0 : forall n : nat, 0 < 2/2^n.\nProof.\n  intro n.\n  unfold Rdiv.\n  exact (Rmult_lt_0_compat 2 (/2^n) lt_0_2 (Rlt_inv_2n n)).\nQed.\n\nLemma error_upper_bound_aux_1 : forall n : nat, 4/2^n = 2 * (2/2^n).\nProof.\n  intro n.\n  rewrite <- (eq_2_2_4).\n  unfold Rdiv.\n  exact (Rmult_assoc 2 2 (/2^n)).\nQed.\n\nTheorem error_upper_bound\n  :  forall n : nat, error n < 4/2^n.\nProof.\n  exact\n    (fun n\n      => Rlt_trans\n           (error n) (b * (2/2^n)) (2 * (2/2^n))\n           (Rplus_lt_compat_r\n             (- (b * approx n)) a (b * approx n + b * (2/2^n))\n             (approx_lower_bound n\n               || a < X @X by <- Rmult_plus_distr_l b (approx n) (2/2^n))\n             || X < b * approx n + b * (2/2^n) - b * approx n @X by error_n n\n             || error n < X @X by (ltac:(ring) : b * approx n - b * approx n + b * (2/2^n) = b * approx n + b * (2/2^n) - b * approx n)\n             || error n < X + b * (2/2^n) @X by <- Rplus_opp_r (b * approx n)\n             || error n < X @X by <- Rplus_0_l (b * (2/2^n)))\n           (Rmult_lt_compat_r (2/2^n) b 2\n             (error_upper_bound_aux_0 n)\n              b_upper_bound) \n           || error n < X @X by error_upper_bound_aux_1 n).\nQed.\n", "meta": {"author": "llee454", "repo": "FPU-Verification", "sha": "c8bbb7b9dd08b6f0a054463f7737aac77c4e144c", "save_path": "github-repos/coq/llee454-FPU-Verification", "path": "github-repos/coq/llee454-FPU-Verification/FPU-Verification-c8bbb7b9dd08b6f0a054463f7737aac77c4e144c/verification/division.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.6815444868245544}}
{"text": "(** * Tests for vectors as iterated products. *)\n(** Gianluca Amato,  Marco Maggesi, Cosimo Perini Brogi 2019-2021 *)\n\nRequire Import UniMath.Combinatorics.StandardFiniteSets.\nRequire Import UniMath.Combinatorics.Vectors.\n\nLocal Open Scope stn.\n\nSection Tests_el.\n\n  Context {A : UU} {a b c d:A}.\n\n  Let v := vcons a (vcons b (vcons c (vcons d vnil))).\n\n  Goal el v (●0) = a. reflexivity. Qed.\n  Goal el v (●1) = b. reflexivity. Qed.\n  Goal el v (●2) = c. reflexivity. Qed.\n  Goal el v (●3) = d. reflexivity. Qed.\n\n  Goal make_vec (el v) = v. reflexivity. Qed.\n\n  Let f : ⟦ 4 ⟧ → A := Eval compute in (el v).\n\n  Goal (el (make_vec f) = f). reflexivity. Qed.\n\nEnd Tests_el.\n\nSection Test_vec_foldr.\n\n  Context {A B : UU} (f : A -> B -> B) (b : B) (p q r : A).\n\n  Let v := vcons p (vcons q (vcons r vnil)).\n\n  Eval compute in vec_foldr f b v.\n\n  Goal vec_foldr f b v = f p (f q (f r b)). reflexivity. Qed.\n\nEnd Test_vec_foldr.\n\nSection Test_vec_foldr1.\n\n  Context {A : UU} (f : A -> A -> A)  (p q r t : A).\n\n  Let v := vcons p (vcons q (vcons r (vcons t vnil))).\n\n  Eval compute in vec_foldr1 f v.\n\n  Goal vec_foldr1 f v = f p (f q (f r t)). reflexivity. Qed.\n\nEnd Test_vec_foldr1.\n\nSection Test_vec_append.\n\n  Context {A : UU} {a b c d e : A}.\n\n  Let u := vcons a (vcons b (vcons c vnil)).\n  Let v := vcons d (vcons e vnil).\n  Let w := vcons a (vcons b (vcons c (vcons d (vcons e vnil)))).\n\n  Eval compute in vec_append u v.\n\n  Goal vec_append u v = w. reflexivity. Qed.\n\nEnd Test_vec_append.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/Combinatorics/VectorsTests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.6815444763324224}}
{"text": "(*******************************************************************************\n\nTitle: Equalizers.v\nAuthors: Jeremy Avigad, Chris Kapulkin, Peter LeFanu Lumsdaine\nDate: 1 March 2013\n\nBasic results on equalizers. Just a stub for now; given a file of its\nown since it is used in both [Limits.v] and [Pullbacks.v], which are\notherwise independent.\n\nTODO (mid): add a section on the universal property of equalizers.\n\n*******************************************************************************)\n\nRequire Import HoTT.\nRequire Import Auxiliary.\n\nSection Equalizers.\n\nDefinition equalizer {A B : Type} (f : A -> B) (g : A -> B)\n  := { x:A & (f x) = (g x) }.\n\nEnd Equalizers.\n\n(*\nLocal Variables:\ncoq-prog-name: \"hoqtop\"\nEnd:\n*)\n", "meta": {"author": "peterlefanulumsdaine", "repo": "hott-limits", "sha": "188e627b0bd27b5252c1a7c2b405220077780eb7", "save_path": "github-repos/coq/peterlefanulumsdaine-hott-limits", "path": "github-repos/coq/peterlefanulumsdaine-hott-limits/hott-limits-188e627b0bd27b5252c1a7c2b405220077780eb7/Equalizers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.6815444760582285}}
{"text": "Require Export List. Export ListNotations.\nRequire Import ZArith.\nLocal Open Scope Z_scope.\nRequire Import VST.floyd.sublist.\n\nFixpoint repeat_op_nat{T: Type}(n: nat)(start: T)(op: T -> T): T := match n with\n| O => start\n| S m => op (repeat_op_nat m start op)\nend.\n\nDefinition repeat_op{T: Type}(n: Z)(start: T)(op: T -> T): T := repeat_op_nat (Z.to_nat n) start op.\n\nLemma repeat_op_step: forall {T: Type} (i: Z) (start: T) (op: T -> T),\n  0 <= i ->\n  repeat_op (i + 1) start op = op (repeat_op i start op).\nProof.\n  intros. unfold repeat_op. rewrite Z2Nat.inj_add by omega.\n  rewrite Nat.add_1_r. simpl. reflexivity.\nQed.\n\nFixpoint repeat_op_table_nat{T: Type}(n: nat)(start: T)(op: T -> T): list T := match n with\n| O => []\n| S m => (repeat_op_table_nat m start op) ++ [repeat_op_nat m start op]\nend.\n\nDefinition repeat_op_table{T: Type}(n: Z)(start: T)(op: T -> T): list T :=\n  repeat_op_table_nat (Z.to_nat n) start op.\n\nLemma repeat_op_table_step: forall {T: Type} (i: Z) (start: T) (op: T -> T),\n  0 <= i ->\n  repeat_op_table (i + 1) start op = (repeat_op_table i start op) ++ [repeat_op i start op].\nProof.\n  intros. unfold repeat_op_table. rewrite Z2Nat.inj_add by omega.\n  rewrite Nat.add_1_r. simpl. reflexivity.\nQed.\n\nLemma repeat_op_table_nat_length: forall {T: Type} (i: nat) (x: T) (f: T -> T),\n  length (repeat_op_table_nat i x f) = i.\nProof.\n  intros. induction i. reflexivity. simpl. rewrite app_length. simpl.\n  rewrite IHi. omega.\nQed.\n\nLemma repeat_op_table_length: forall {T: Type} (i: Z) (x: T) (f: T -> T),\n  0 <= i ->\n  Zlength (repeat_op_table i x f) = i.\nProof.\n  intros. unfold repeat_op_table.\n  rewrite Zlength_correct. rewrite repeat_op_table_nat_length.\n  apply Z2Nat.id. assumption.\nQed.\n\nLemma repeat_op_nat_id: forall {T: Type} (n: nat) (v: T),\n  repeat_op_nat n v id = v.\nProof.\n  intros. induction n.\n  - reflexivity.\n  - simpl. apply IHn.\nQed.\n\nLemma repeat_op_table_nat_id_app: forall {T: Type} (len1 len2: nat) (v: T),\n  repeat_op_table_nat (len1 + len2) v id \n  = repeat_op_table_nat len1 v id ++ repeat_op_table_nat len2 v id.\nProof.\n  intros. induction len2.\n  - simpl. replace (len1 + 0)%nat with len1 by omega. rewrite app_nil_r. reflexivity.\n  - replace (len1 + S len2)%nat with (S (len1 + len2)) by omega. simpl.\n    rewrite IHlen2. rewrite <- app_assoc. f_equal. f_equal. do 2 rewrite repeat_op_nat_id.\n    reflexivity.\nQed.\n\nLemma sublist_repeat_op_table_id: forall {T: Type} (lo n: Z) (v: T),\n  0 <= lo ->\n  0 <= n ->\n  sublist lo (lo + n) (repeat_op_table (lo + n) v id) = repeat_op_table n v id.\nProof.\n  intros.\n  replace (lo + n) with (Zlength (repeat_op_table (lo + n) v id)) at 1\n    by (apply repeat_op_table_length; omega).\n  rewrite sublist_skip by omega.\n  unfold repeat_op_table at 1. rewrite Z2Nat.inj_add by omega.\n  rewrite repeat_op_table_nat_id_app.\n  rewrite Zskipn_app1 by (\n    rewrite Zlength_correct;\n    rewrite repeat_op_table_nat_length;\n    rewrite Z2Nat.id; omega\n  ).\n  rewrite skipn_short; [ reflexivity | ].\n  rewrite repeat_op_table_nat_length. omega.\nQed.\n\nFixpoint fill_list_nat{T: Type}(n: nat)(f: nat -> T): list T := match n with\n| O => []\n| S m => (fill_list_nat m f) ++ [f m]\nend.\n\nDefinition fill_list{T: Type}(n: Z)(f: Z -> T): list T :=\n  fill_list_nat (Z.to_nat n) (fun i => f (Z.of_nat i)).\n\nLemma fill_list_step: forall {T: Type} (n: Z) (f: Z -> T),\n  0 <= n ->\n  fill_list (n + 1) f = fill_list n f ++ [f n].\nProof.\n  intros. unfold fill_list. rewrite Z2Nat.inj_add by omega.\n  rewrite Nat.add_1_r. simpl. rewrite Z2Nat.id by omega. reflexivity.\nQed.\n\nLtac eval_list l :=\n  let l' := eval hnf in l in lazymatch l' with\n  | ?h :: ?tl => let tl' := eval_list tl in constr:(h :: tl')\n  | (@nil ?T) => constr:(@nil T)\n  end.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/aes/list_utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388040954683, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.6815444691777214}}
{"text": "Require Export Base.\n\n\n\n\nSection operations.\n\n\n\nVariable T : finType.\nVariables A B C : {set T}.\n\n(*2.1*)\nLemma cup_def :\n    A ∪ B = [set x | (x ∈ A) || (x ∈ B)].\nProof.\n    auto.\nQed.\n\n(*2.2*)\nLemma sub_cup_l :\n    A ⊂ (A ∪ B).\nProof.\n    apply subsetUl.\nQed.\n\nLemma sub_cup_r :\n    B ⊂ (A ∪ B).\nProof.    \n    apply subsetUr.\nQed.\n\n(*2.3*)\nLemma subsub__Usub :\n    A ⊂ C -> B ⊂ C -> (A ∪ B) ⊂ C.\nProof.\n    move => AC AB; apply /subUsetP => //=.\nQed.    \n\n\n(*2.4*)\nLemma setU_self :\n    A ∪ A = A.\nProof.\n    apply extension; apply /subsetP => x H.\n    +   case /setUP : H => //.\n    +   apply /setUP; left => //.\nQed.\n\n(*2.5*)\nLemma cup_comm :\n    A ∪ B = B ∪ A.\nProof.\n    apply setUC.\nQed.\n\n(*2.6*)\nLemma cup_assoc :\n    (A ∪ B) ∪ C = A ∪ (B ∪ C).\nProof.\n    apply extension; apply /subsetP => x H; \n        apply /setUP; case /setUP : H => H;\n        try (case /setUP : H => H).\n    +   left => //.\n    +   right; apply /setUP; left => //.\n    +   right; apply /setUP; right => //.\n    +   left; apply /setUP; left => //.\n    +   left; apply /setUP; right => //.\n    +   right => //.\nRestart.\n    by rewrite -setUA.\nQed.\n\n(*2.7*)\nLemma sub__setU :\n    A ⊂ B <-> A ∪ B = B.\nProof.\n    split => H. \n    +   move /subsetP : H => H.\n        apply extension; apply /subsetP => x Hx.\n        -   case /setUP : Hx => H0 => //.\n            apply H => //.\n        -   apply /setUP; right => //.\n    +   rewrite -H.\n        apply subsetUl.\nQed.\n\n(*2.8*)\nLemma sub__UsubU :\n    A ⊂ B -> (A ∪ C) ⊂ (B ∪ C).\nProof.\n    move /subsetP => H.\n    apply /subsetP => x Hx.\n    case /setUP : Hx => H0; apply /setUP; [left|right] => //.\n    by apply H.\nQed.    \n\n(*2.9*)\nLemma empty_cup :\n    ∅ ∪ A = A.\nProof.\n    apply set0U.\nQed.\n\n(*2.10*)\nGoal (A ∪ B) ∩ C = (A ∩ C) ∪ (B ∩ C).\napply setIUl. Qed.\n\nGoal (A ∩ B) ∪ C = (A ∪ C) ∩ (B ∪ C).\napply setUIl. Qed.\n\n\n(*2.11*)\nGoal (A ∪ B) ∩ A = A.\napply setUK. Qed.\n\nGoal (A ∩ B) ∪ A = A.\napply setIK. Qed.\n\n(*2.12*)\nGoal A ∩ (¬ A) = ∅.\nProof.\n    apply setICr.\nRestart.\n    apply extension; apply /subsetP => x H.\n    +   case /setIP : H => H /setCP F => //.\n    +   rewrite in_set0 in H.\n        inversion H.\nQed.        \n\n\nGoal A ∪ (¬ A) = setT.\nProof.\n    apply setUCr.\nRestart.\n    apply extension; apply /subsetP => x H.\n    +   apply in_setT.\n    +   apply /setUP.\n        remember (x ∈ A) as Hx.\n        destruct Hx; [left => //|right].\n        apply /setCP => F.\n        rewrite F in HeqHx => //.\nQed.  \n\n(*2.13*)\nGoal ¬ (¬ A) = A.\nProof.\n    apply extension; apply /subsetP => x;\n    rewrite 2!in_setC; rewrite Bool.negb_involutive => //.\nQed.\n\n(*2.14*)\nGoal  ¬ ∅ = [set: T].\nProof.\n    apply setC0.\nRestart.\n    apply extension; apply /subsetP => x Hx.\n    +   apply in_setT.\n    +   rewrite in_setC.\n        rewrite in_set0 => //.\nQed.\n\nGoal ¬ [set : T] = ∅.\nProof.\n    apply setCT.\nRestart.\n    apply extension; apply /subsetP => x Hx.\n    +   rewrite in_setC in Hx.\n        rewrite in_setT in Hx.\n        inversion Hx.\n    +   rewrite in_set0 in Hx.\n        inversion Hx.\nQed.\n\n\n(*2.15*)\nGoal A ⊂ B -> (¬ B) ⊂ (¬ A).\nProof.\n    move => /subsetP H.\n    apply /subsetP => x /setCP Hb.\n    apply /setCP => F.\n    contradict Hb; apply H => //.\nQed.\n\n\n(*2.16*)\n\nGoal ¬ (A ∪ B) = (¬ A) ∩ (¬ B).\nProof.\n    apply setCU.\nRestart.\n    apply extension; apply /subsetP => x Hx.\n    +   move /setCP : Hx => Hx.\n        apply /setIP; split; apply /setCP => F; \n        apply Hx; apply /setUP; [left|right] => //.\n    +   move /setIP : Hx => [/setCP nHa /setCP nHb].\n        apply /setCP; case /setUP => [Ha|Hb] => //.\nQed.\n\n\n\nGoal ¬ (A ∩ B) = (¬ A) ∪ (¬ B).\n    apply setCI.\nRestart.\n    apply extension; apply /subsetP => x Hx.\n    +   apply /setUP.\n        rewrite in_setC in Hx.\n        move /setIP : Hx => Hx. (* H : ~~ b に対しても    、bP : reflect P b　が使える *)\n        case : (not_and_or _ _ Hx) => H ;\n        [left|right]; apply /setCP => //.\n    +   apply /setCP => /setIP [Ha Hb].\n        move /setUP : Hx => [/setCP nHa |/ setCP nHb] => //.\nQed.\n\nGoal A ⊂ B -> (¬ B) ⊂ (¬ A).\nProof.\n    move => /subsetP H.\n    apply /subsetP => x /setCP nHB.\n    apply /setCP => HA.\n    apply nHB; apply H => //.\nQed.\n\nVariable me : T.\n\nGoal forall someone, someone ∈ ¬ [set me] -> someone <> me.\nProof.\n    move => someone /setCP H /eqP F.\n    apply H; rewrite in_set1 => //.\nQed. \n\nEnd operations.\n\n\n(* 2.17 *)\nSection bigop1.\nVariable (T : finType) (A C : {set T}) (U : {set {set T}}).\n\n\nGoal A ∈ U -> A ⊂ (⊔ U).\nProof.\n    move => AU; apply /subsetP => x xA; apply /bigUP; exists A => //.\nQed.\n\nGoal A ∈ U -> ⊓ U ⊂ A.\nProof.\n    move => AU; apply /subsetP => x /bigIP H; apply H => //.\nQed.\n\nEnd bigop1.\n\nSection bigop2.\n\nVariable (T : finType) (C : {set T}) (U : {set {set T}}).\n\nGoal (forall A, A ∈ U -> A ⊂ C) -> ⊔ U ⊂ C.\nProof.\n    move => H; apply /subsetP => x /bigUP [Y [xY YU]].\n    move : (H Y YU); move /subsetP; apply => //.\nQed.\n\n\nGoal (forall A, A ∈ U -> C ⊂ A) -> C ⊂ ⊓ U.\nProof.\n    move => H; apply /subsetP => x xC; apply /bigIP => Y YU.\n    move : (H Y YU); move /subsetP; apply => //.\nQed.\n\nEnd bigop2.\n\n\n\n        \n        \n\n\n\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": "gaxiiiiiiiiiiii", "repo": "SetTheory", "sha": "2dba76ac2e4fb14380b5efc8c25001858ef6fb73", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-SetTheory", "path": "github-repos/coq/gaxiiiiiiiiiiii-SetTheory/SetTheory-2dba76ac2e4fb14380b5efc8c25001858ef6fb73/Ops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.681518453236808}}
{"text": "(*|\n################\nSubtyping in Coq\n################\n\n:Link: https://stackoverflow.com/q/41306638\n|*)\n\n(*|\nQuestion\n********\n\nI defined Subtype as follows\n|*)\n\nRecord Subtype {T : Type} (P : T -> Prop) := {\n    subtype       :> Type;\n    subtype_inj   :> subtype -> T;\n    subtype_isinj : forall s t : subtype,\n      (subtype_inj s = subtype_inj t) -> s = t;\n    subtype_h     : forall x : T, P x -> (exists s : subtype,x = subtype_inj s);\n    subtype_h0    : forall s : subtype, P (subtype_inj s)\n  }.\n\n(*| Can the following theorem be proven? |*)\n\nTheorem Subtypes_Exist : forall {T} (P : T -> Prop), Subtype P.\nAbort. (* .none *)\n\n(*|\nIf not, is it provable from any well-known compatible axiom? Or Can I\nadd this as an axiom? Would it conflict with any usual axiom? (like\nextensionality, functional choice, etc.)\n|*)\n\n(*|\nAnswer\n******\n\nYour definition is practically identical to the one of MathComp;\nindeed, what you are missing mainly is injectivity due to proof\nrelevance.\n\nFor that, I am afraid you will need to assume propositional\nirrelevance:\n|*)\n\nRequire Import ProofIrrelevance.\n\nTheorem Subtypes_Exist : forall {T} (P : T -> Prop), Subtype P.\nProof.\n  intros T P; set (subtype_inj := @proj1_sig T P).\n  apply (@Build_Subtype _ _ { x | P x} subtype_inj).\n  + intros [s Ps] [t Pt]; simpl; intros ->.\n    now rewrite (proof_irrelevance _ Ps Pt).\n  + now intros x Px; exists (exist _ x Px).\n  + now intro H; destruct H.\nQed.\n\n(*|\nYou can always restrict you predicate ``P`` to a type which is\neffectively proof-irrelevant, of course.\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/subtyping-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.6814486332135691}}
{"text": "Require Import Rbase Ranalysis.\nRequire Import Rinterval Rfunctions Rfunction_def Rfunction_facts.\nRequire Import Ranalysis_def Ranalysis_def_simpl.\nRequire Import MyRIneq MyR_dist Lra.\n\nLocal Open Scope R_scope.\n\n(** stricly_whatever implies whatever *)\n\nLemma strictly_increasing_in_increasing_in : forall D f,\n  strictly_increasing_in D f -> increasing_in D f.\nProof.\nintros D f f_incr x y Dx Dy [Hlt | Heq].\n left ; apply f_incr ; assumption.\n subst ; reflexivity.\nQed.\n\nLemma strictly_decreasing_in_decreasing_in : forall D f,\n  strictly_decreasing_in D f -> decreasing_in D f.\nProof.\nintros D f f_decr x y Dx Dy [Hlt | Heq].\n left ; apply f_decr ; assumption.\n subst ; reflexivity.\nQed.\n\nLemma strictly_monotonous_in_monotonous_in : forall D f,\n strictly_monotonous_in D f -> monotonous_in D f.\nProof.\nintros D f [Hd | Hi] ;\n [left ; apply strictly_decreasing_in_decreasing_in |\n right ; apply strictly_increasing_in_increasing_in] ; assumption.\nQed.\n\nLemma strictly_increasing_increasing f : strictly_increasing f -> increasing f.\nProof.\n  apply strictly_increasing_in_increasing_in.\nQed.\n\nLemma strictly_decreasing_decreasing f : strictly_decreasing f -> decreasing f.\nProof.\n  apply strictly_decreasing_in_decreasing_in.\nQed.\n\nLemma strictly_monotonous_monotonous f : strictly_monotonous f -> monotonous f.\nProof.\n  apply strictly_monotonous_in_monotonous_in.\nQed.\n\n(** Strict monotonicity implies injectivity *)\n\nLemma strictly_increasing_in_injective_in : forall D f,\n  strictly_increasing_in D f -> injective_in D f.\nProof.\nintros D f f_inc x y x_in y_in feq ; destruct (Rtotal_order x y) as [Hlt | [Heq | Hgt]].\n destruct (Rlt_irrefl (f y)) ; apply Rle_lt_trans with (f x).\n  rewrite feq ; reflexivity.\n  apply f_inc ; assumption.\n assumption.\n destruct (Rlt_irrefl (f x)) ; apply Rle_lt_trans with (f y).\n  rewrite feq ; reflexivity.\n  apply f_inc ; assumption.\nQed.\n\nLemma strictly_decreasing_in_injective_in : forall D f,\n  strictly_decreasing_in D f -> injective_in D f.\nProof.\nintros D f f_dec x y x_in y_in feq ; destruct (Rtotal_order x y) as [Hlt | [Heq | Hgt]].\n destruct (Rlt_irrefl (f x)) ; apply Rle_lt_trans with (f y).\n  rewrite feq ; reflexivity.\n  apply f_dec ; assumption.\n assumption.\n destruct (Rlt_irrefl (f y)) ; apply Rle_lt_trans with (f x).\n  rewrite feq ; reflexivity.\n  apply f_dec ; assumption.\nQed.\n\nLemma strictly_monotonous_in_injective_in : forall D f,\n  strictly_monotonous_in D f -> injective_in D f.\nProof.\nintros D f [f_dec | f_inc] ;\n [apply strictly_decreasing_in_injective_in |\n  apply strictly_increasing_in_injective_in] ; assumption.\nQed.\n\nLemma strictly_increasing_injective f : strictly_increasing f -> injective f.\nProof.\n  apply strictly_increasing_in_injective_in.\nQed.\n\nLemma strictly_decreasing_injective f : strictly_decreasing f -> injective f.\nProof.\n  apply strictly_decreasing_in_injective_in.\nQed.\n\nLemma strictly_monotonous_injective f : strictly_monotonous f -> injective f.\nProof.\n  apply strictly_monotonous_in_injective_in.\nQed.\n\n(** It also helps simplify Rmin / Rmax statements *)\n\nLemma increasing_in_Rmin_simpl :\n  forall D f, increasing_in D f ->\n  forall x y, D x -> D y -> x <= y -> Rmin (f x) (f y) = f x.\nProof.\nintros D f f_inc x y Dx Dy Hxy ;\n assert (flb_lt_fub : f x <= f y) by (apply f_inc ; assumption) ;\n unfold Rmin ; destruct (Rle_dec (f x) (f y)) ; intuition.\nQed.\n\nLemma increasing_in_Rmax_simpl :\n  forall D f, increasing_in D f ->\n  forall x y, D x -> D y -> x <= y -> Rmax (f x) (f y) = f y.\nProof.\nintros D f f_inc x y Dx Dy Hxy ;\n assert (flb_lt_fub : f x <= f y) by (apply f_inc ; assumption) ;\n unfold Rmax ; destruct (Rle_dec (f x) (f y)) ; intuition.\nQed.\n\nLemma decreasing_in_Rmin_simpl :\n  forall D f, decreasing_in D f ->\n  forall x y, D x -> D y -> x <= y -> Rmin (f x) (f y) = f y.\nProof.\nintros D f f_dec x y Dx Dy Hxy ;\n assert (flb_lt_fub : f y <= f x) by (apply f_dec ; assumption) ;\n unfold Rmin ; destruct (Rle_dec (f x) (f y)) ; intuition.\nQed.\n\nLemma decreasing_in_Rmax_simpl :\n  forall D f, decreasing_in D f ->\n  forall x y, D x -> D y -> x <= y -> Rmax (f x) (f y) = f x.\nProof.\nintros D f f_dec x y Dx Dy Hxy ;\n assert (flb_lt_fub : f y <= f x) by (apply f_dec ; assumption) ;\n unfold Rmax ; destruct (Rle_dec (f x) (f y)) ; intuition.\nQed.\n\n(** Image of an interval throught a monotonous function *)\n\nLemma increasing_interval_image : forall f lb ub x,\n  increasing_interval lb ub f -> interval lb ub x ->\n  interval (f lb) (f ub) (f x).\nProof.\nintros f lb ub x Hf x_in ; assert (lb_le_ub : lb <= ub) by\n (eapply interval_inhabited ; eassumption) ; split ; apply Hf.\n apply interval_l ; assumption.\n assumption.\n apply x_in.\n assumption.\n apply interval_r ; assumption.\n apply x_in.\nQed. \n\nLemma decreasing_interval_image : forall f lb ub x,\n  decreasing_interval lb ub f -> interval lb ub x ->\n  interval (f ub) (f lb) (f x).\nProof.\nintros f lb ub x Hf x_in ; assert (lb_le_ub : lb <= ub) by\n (eapply interval_inhabited ; eassumption) ; split ; apply Hf.\n assumption.\n apply interval_r ; assumption.\n apply x_in.\n apply interval_l ; assumption.\n assumption.\n apply x_in.\nQed.\n\nLemma monotonous_interval_image : forall f lb ub x,\n  monotonous_interval lb ub f -> interval lb ub x ->\n  interval (Rmin (f lb) (f ub)) (Rmax (f lb) (f ub)) (f x).\nProof.\nintros f lb ub x [f_dec | f_inc] x_in ;\n assert (lbub : lb <= ub) by (eapply interval_inhabited, x_in).\n erewrite decreasing_in_Rmax_simpl, decreasing_in_Rmin_simpl ; try eassumption.\n  apply decreasing_interval_image ; assumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\n erewrite increasing_in_Rmax_simpl, increasing_in_Rmin_simpl ; try eassumption.\n  apply increasing_interval_image ; assumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\nQed.\n\nLemma strictly_increasing_interval_image : forall f lb ub x,\n  strictly_increasing_interval lb ub f -> open_interval lb ub x ->\n  open_interval (f lb) (f ub) (f x).\nProof.\nintros f lb ub x Hf x_in ; assert (lb_le_ub : lb <= ub) by\n (left ; eapply open_interval_inhabited ; eassumption) ; split ; apply Hf.\n apply interval_l ; assumption.\n apply open_interval_interval ; assumption.\n apply x_in.\n apply open_interval_interval ; assumption.\n apply interval_r ; assumption.\n apply x_in.\nQed. \n\nLemma strictly_decreasing_interval_image : forall f lb ub x,\n  strictly_decreasing_interval lb ub f -> open_interval lb ub x ->\n  open_interval (f ub) (f lb) (f x).\nProof.\nintros f lb ub x Hf x_in ; assert (lb_le_ub : lb <= ub) by\n (left ; eapply open_interval_inhabited ; eassumption) ; split ; apply Hf.\n apply open_interval_interval ; assumption.\n apply interval_r ; assumption.\n apply x_in.\n apply interval_l ; assumption.\n apply open_interval_interval ; assumption.\n apply x_in.\nQed.\n\nLemma strictly_monotonous_interval_image : forall f lb ub x,\n  strictly_monotonous_interval lb ub f -> open_interval lb ub x ->\n  open_interval (Rmin (f lb) (f ub)) (Rmax (f lb) (f ub)) (f x).\nProof.\nintros f lb ub x [f_dec | f_inc] x_in ;\n assert (lbub : lb <= ub) by (left ; eapply open_interval_inhabited, x_in).\n erewrite decreasing_in_Rmax_simpl, decreasing_in_Rmin_simpl.\n  apply strictly_decreasing_interval_image ; assumption.\n  apply strictly_decreasing_in_decreasing_in ; eassumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\n  assumption.\n  apply strictly_decreasing_in_decreasing_in ; eassumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\n  assumption.\n erewrite increasing_in_Rmax_simpl, increasing_in_Rmin_simpl.\n  apply strictly_increasing_interval_image ; assumption.\n  apply strictly_increasing_in_increasing_in ; eassumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\n  assumption.\n  apply strictly_increasing_in_increasing_in ; eassumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\n  assumption.\nQed.\n\n(** Compatibility of variations with operations *)\n\nLemma increasing_in_opp : forall D f,\n  increasing_in D f -> decreasing_in D (-f)%F.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_le_contravar, Hf ; assumption.\nQed.\n\nLemma increasing_in_opp_rev : forall D f,\n  increasing_in D (- f)%F -> decreasing_in D f.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_le_cancel, Hf ; assumption.\nQed.\n\nLemma strictly_increasing_in_opp : forall D f,\n  strictly_increasing_in D f -> strictly_decreasing_in D (-f)%F.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_lt_contravar, Hf ; assumption.\nQed.\n\nLemma strictly_increasing_in_opp_rev : forall D f,\n  strictly_increasing_in D (- f)%F -> strictly_decreasing_in D f.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_lt_cancel, Hf ; assumption.\nQed.\n\nLemma decreasing_in_opp : forall D f,\n  decreasing_in D f -> increasing_in D (-f)%F.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_le_contravar, Hf ; assumption.\nQed.\n\nLemma decreasing_in_opp_rev : forall D f,\n  decreasing_in D (- f)%F -> increasing_in D f.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_le_cancel, Hf ; assumption.\nQed.\n\nLemma strictly_decreasing_in_opp : forall D f,\n  strictly_decreasing_in D f -> strictly_increasing_in D (-f)%F.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_lt_contravar, Hf ; assumption.\nQed.\n\nLemma strictly_decreasing_in_opp_rev : forall D f,\n  strictly_decreasing_in D (- f)%F -> strictly_increasing_in D f.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_lt_cancel, Hf ; assumption.\nQed.\n\n(* TODO: more generic lemmas like these ones *)\n\nLemma increasing_in_plus : forall D f g,\n  increasing_in D f -> increasing_in D g -> increasing_in D (f + g)%F.\nProof.\nintros D f g Hf Hg x y Dx Dy Hxy ; unfold plus_fct ;\n apply Rplus_le_compat ; [apply Hf | apply Hg] ; assumption.\nQed.\n\nLemma increasing_in_minus : forall D f g,\n  increasing_in D f -> decreasing_in D g -> increasing_in D (f - g)%F.\nProof.\nintros D f g Hf Hg x y Dx Dy Hxy ; unfold plus_fct ;\n apply Rplus_le_compat ; [apply Hf | apply Ropp_le_contravar, Hg] ; assumption.\nQed.\n\n\nLemma strictly_increasing_strictly_decreasing_interval2 : forall f lb ub,\n  strictly_increasing_interval lb ub f ->\n  strictly_decreasing_interval (- ub) (- lb) (fun x => f(-x)).\nProof.\nintros f c r f_incr ; intros x y x_in_B y_in_B x_lt_y.\n apply f_incr ; unfold interval in * ; try split ; intuition ; lra.\nQed.\n\nLemma strictly_decreasing_strictly_increasing_interval2 : forall f lb ub,\n  strictly_decreasing_interval lb ub f ->\n  strictly_increasing_interval (-ub) (-lb) (fun x => f(-x)).\nProof.\nintros f c r f_decr ; intros x y x_in_B y_in_B x_lt_y.\n apply f_decr ; unfold interval in * ; try split ; intuition ; lra.\nQed.\n\nLemma strictly_increasing_reciprocal_interval_compat : forall f g lb ub,\n  strictly_increasing_interval lb ub f ->\n  reciprocal_interval (f lb) (f ub) f g ->\n  (forall x, interval (f lb) (f ub) x -> interval lb ub (g x)) ->\n  strictly_increasing_interval (f lb) (f ub) g.\nProof.\nintros f g lb ub f_incr f_recip_g g_ok x y x_in_I y_in_I x_lt_y.\n destruct (Rlt_le_dec (g x) (g y)) as [T | F].\n  assumption.\n  destruct F as [F | F].\n   assert (Hf : y < x).\n    unfold reciprocal_interval, id in f_recip_g ; rewrite <- f_recip_g.\n    apply Rgt_lt ; rewrite <- f_recip_g.\n    unfold comp ; apply f_incr ; [apply g_ok | apply g_ok |] ; assumption.\n    assumption.\n    assumption.\n   apply False_ind ; apply Rlt_irrefl with x ; apply Rlt_trans with y ; assumption.\n   assert (Hf : x = y).\n    unfold reciprocal_interval, id in f_recip_g ; rewrite <- f_recip_g.\n    symmetry ; rewrite <- f_recip_g.\n    unfold comp ; rewrite F ; reflexivity.\n    assumption.\n    assumption.\n   rewrite Hf in x_lt_y ; elim (Rlt_irrefl _ x_lt_y).\nQed.\n\nLemma strictly_increasing_reciprocal_interval_comm: forall f g lb ub,\n  (forall x, interval (f lb) (f ub) x -> interval lb ub (g x)) ->\n  strictly_increasing_interval lb ub f ->\n  reciprocal_interval (f lb) (f ub) f g ->\n  reciprocal_interval lb ub g f.\nProof.\nintros f g lb ub g_ok f_sinc Hfg x x_in ;\n assert (f_inc : increasing_interval lb ub f).\n  apply strictly_increasing_in_increasing_in ; assumption.\n destruct (Req_dec (g (f x)) x) as [Heq | Hneq].\n  assumption.\n  destruct (Rlt_irrefl (f x)).\n  destruct (Rdichotomy _ _ Hneq) as [Hlt | Hlt].\n  apply Rle_lt_trans with (f (g (f x))).\n   right ; rewrite Hfg.\n    reflexivity.\n    apply increasing_interval_image ; [apply strictly_increasing_in_increasing_in |] ; assumption.\n   apply f_sinc ; [apply g_ok, increasing_interval_image | |] ; assumption.\n  apply Rlt_le_trans with (f (g (f x))).\n   apply f_sinc ; [| apply g_ok, increasing_interval_image |] ; assumption.\n  right ; rewrite Hfg.\n   reflexivity.\n   apply increasing_interval_image ; assumption.\nQed.\n\nLemma strictly_decreasing_reciprocal_interval_comm: forall f g lb ub,\n  (forall x, interval (f ub) (f lb) x -> interval lb ub (g x)) ->\n  strictly_decreasing_interval lb ub f ->\n  reciprocal_interval (f ub) (f lb) f g ->\n  reciprocal_interval lb ub g f.\nProof.\nintros f g lb ub g_ok f_sdec Hfg x x_in ;\n assert (f_dec : decreasing_interval lb ub f).\n  apply strictly_decreasing_in_decreasing_in ; assumption.\n destruct (Req_dec (g (f x)) x) as [Heq | Hneq].\n  assumption.\n  destruct (Rlt_irrefl (f x)).\n  destruct (Rdichotomy _ _ Hneq) as [Hlt | Hlt].\n  apply Rlt_le_trans with (f (g (f x))).\n   apply f_sdec ; [apply g_ok, decreasing_interval_image | |] ; assumption.\n  right ; rewrite Hfg.\n   reflexivity.\n   apply decreasing_interval_image ; assumption.\n  apply Rle_lt_trans with (f (g (f x))).\n   right ; rewrite Hfg.\n    reflexivity.\n    apply decreasing_interval_image ; assumption.\n   apply f_sdec ; [| apply g_ok, decreasing_interval_image |] ; assumption.\nQed.\n\n(** Knowing f's variations and the ordering of f a and f b we can deduce a and b's ordering *)\n\nLemma strictly_increasing_open_interval_order : forall f lb ub a b,\n  open_interval lb ub a -> open_interval lb ub b ->\n  strictly_increasing_open_interval lb ub f ->\n  f a < f b -> a < b.\nProof.\nintros f lb ub a b a_in b_in Hf Hfafb ; destruct (Rlt_le_dec a b) as [altb | blea].\n assumption.\n destruct blea as [blta | beqa].\n  destruct (Rlt_irrefl (f a)) ; transitivity (f b).\n   assumption.\n   apply Hf ; assumption.\n  rewrite beqa in Hfafb ; destruct (Rlt_irrefl _ Hfafb).\nQed.\n\nLemma strictly_increasing_interval_order : forall f lb ub a b,\n  open_interval lb ub a -> open_interval lb ub b ->\n  strictly_increasing_open_interval lb ub f ->\n  f a <= f b -> a <= b.\nProof.\nintros f lb ub a b a_in b_in Hf Hfafb ; destruct (Rle_lt_dec a b) as [aleb | blta].\n assumption.\n destruct (Rlt_irrefl (f a)) ; apply Rle_lt_trans with (f b).\n  assumption.\n  apply Hf ; assumption.\nQed.\n", "meta": {"author": "coq-community", "repo": "coqtail-math", "sha": "be26e1a6a52f2e13e0779c68aba685ddfb4f0535", "save_path": "github-repos/coq/coq-community-coqtail-math", "path": "github-repos/coq/coq-community-coqtail-math/coqtail-math-be26e1a6a52f2e13e0779c68aba685ddfb4f0535/Reals/Ranalysis/Ranalysis_monotonicity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6813838127923033}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Import PeanoNat.\n\nLocal Open Scope nat_scope.\nImplicit Types m n p : nat.\n\nNotation min := Nat.min (only parsing).\n\nDefinition min_0_l := Nat.min_0_l.\nDefinition min_0_r := Nat.min_0_r.\nDefinition succ_min_distr := Nat.succ_min_distr.\nDefinition plus_min_distr_l := Nat.add_min_distr_l.\nDefinition plus_min_distr_r := Nat.add_min_distr_r.\nDefinition min_case_strong := Nat.min_case_strong.\nDefinition min_spec := Nat.min_spec.\nDefinition min_dec := Nat.min_dec.\nDefinition min_case := Nat.min_case.\nDefinition min_idempotent := Nat.min_id.\nDefinition min_assoc := Nat.min_assoc.\nDefinition min_comm := Nat.min_comm.\nDefinition min_l := Nat.min_l.\nDefinition min_r := Nat.min_r.\nDefinition le_min_l := Nat.le_min_l.\nDefinition le_min_r := Nat.le_min_r.\nDefinition min_glb_l := Nat.min_glb_l.\nDefinition min_glb_r := Nat.min_glb_r.\nDefinition min_glb := Nat.min_glb.\n\n\n\nNotation min_case2 := min_case (only parsing).\nNotation min_SS := Nat.succ_min_distr (only parsing).\n\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Arith/Min.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7826624688140728, "lm_q1q2_score": 0.6813838126907915}}
{"text": "Require Import Mem.\nRequire Import List Omega Ring Word Pred Prog Hoare SepAuto BasicProg Array.\nRequire Import FunctionalExtensionality.\n\nSet Implicit Arguments.\nSet Default Proof Using \"Type\".\n\n(* bijection on restricted domain *)\n\nSection COND_BIJECTION.\n\n  Variables A B : Type.\n  Variable f : A -> B.\n  Variable PA : A -> Prop.\n  Variable PB : B -> Prop.\n\n  Definition cond_injective :=\n    forall x y : A, PA x -> PA y -> f x = f y -> x = y.\n\n  Definition cond_surjective :=\n    forall y : B, PB y -> {x : A | PA x /\\ f x = y}.\n\n  Inductive cond_bijective : Prop :=\n    CondBijective : cond_injective -> cond_surjective -> cond_bijective.\n\n  Section BIJECTION_INVERSION.\n\n    Variable f' : B -> A.\n\n    Definition cond_left_inverse := \n      forall x : A, PA x -> PB (f x) /\\ f' (f x) = x.\n\n    Definition cond_right_inverse := \n      forall y : B, PB y -> PA (f' y) /\\ f (f' y) = y.\n\n    Definition cond_inverse := \n      cond_left_inverse /\\ cond_right_inverse.\n\n    Lemma cond_left_inv_inj : cond_left_inverse -> cond_injective.\n    Proof.\n      intros H x y P1 P2 H0.\n      pose proof (H x P1) as [P3 P4].\n      rewrite <- P4.\n      rewrite H0.\n      apply H.\n      auto.\n    Qed.\n\n    Lemma cond_right_inv_surj : cond_right_inverse -> cond_surjective.\n    Proof.\n      intros H y P1.\n      pose proof (H y P1) as [P2 P3].\n      rewrite <- P3.\n      exists (f' y); intuition.\n    Qed.\n\n    Lemma cond_inv2bij : cond_inverse -> cond_bijective.\n    Proof.\n      intros [H1 H2].\n      constructor.\n      eapply cond_left_inv_inj; eauto.\n      eapply cond_right_inv_surj; eauto.\n    Qed.\n\n    Lemma cond_inv_rewrite_right : forall y,\n      cond_inverse -> PB y -> f (f' y) = y.\n    Proof.\n      intros; apply H; auto.\n    Qed.\n\n    Lemma cond_inv_rewrite_left : forall x,\n      cond_inverse -> PA x -> f' (f x) = x.\n    Proof.\n      intros; apply H; auto.\n    Qed.\n\n    Lemma cond_inv_domain_right : forall y,\n      cond_inverse -> PB y -> PA (f' y).\n    Proof.\n      intros; apply H; auto.\n    Qed.\n\n    Lemma cond_inv_domain_left : forall x,\n      cond_inverse -> PA x -> PB (f x).\n    Proof.\n      intros; apply H; auto.\n    Qed.\n\n  End BIJECTION_INVERSION.\n\nEnd COND_BIJECTION.\n\n\nTheorem cond_inverse_sym : forall A B PA PB (f : A -> B) (f' : B -> A),\n  cond_inverse f PA PB f'\n  -> cond_inverse f' PB PA f.\nProof.\n  firstorder.\nQed.\n\nTheorem cond_inv2bij_inv : forall A B PA PB (f : A -> B) (f' : B -> A),\n  cond_inverse f PA PB f'\n  -> cond_bijective f' PB PA.\nProof.\n  intros.\n  eapply cond_inv2bij.\n  apply cond_inverse_sym; eauto.\nQed.\n\nSection MEMMATCH.\n\n  Variable AT1 : Type.\n  Variable AT2 : Type.\n  Variable atrans : AT1 -> AT2.\n\n  Variable AEQ1 : EqDec AT1.\n  Variable AEQ2 : EqDec AT2.\n  Variable V : Type.\n  Variable m1 : @mem AT1 AEQ1 V.\n  Variable m2 : @mem AT2 AEQ2 V.\n\n  (* restrictions on atrans' domain and codomain *)\n  Variable AP1 : AT1 -> Prop.\n  Variable AP2 : AT2 -> Prop.\n\n  (* decidablity of subdomain *)\n  Variable AP1_dec : forall a1, AP1 a1 \\/ ~ AP1 a1.\n  Variable AP2_dec : forall a2, AP2 a2 \\/ ~ AP2 a2.\n\n  (* well-formedness of memory addresses *)\n  Variable AP1_ok : forall a1, indomain a1 m1 -> AP1 a1.\n  Variable AP2_ok : forall a2, indomain a2 m2 -> AP2 a2.\n\n  Definition mem_atrans AT1 AEQ1 V AT2 AEQ2\n    f (m : @mem AT1 AEQ1 V) (m' : @mem AT2 AEQ2 V) (P : AT1 -> Prop) :=\n    forall a, P a -> m a = m' (f a).\n\n  Variable MTrans : mem_atrans atrans m1 m2 AP1.\n\n  Lemma mem_atrans_indomain : forall a1 x,\n    indomain a1 m1 ->\n    m1 a1 = x -> m2 (atrans a1) = x.\n  Proof using MTrans AP1_ok.\n    intros.\n    apply AP1_ok in H.\n    rewrite <- (MTrans H); auto.\n  Qed.\n\n  Lemma mem_atrans_mem_except : forall a (ap : AP1 a),\n    cond_bijective atrans AP1 AP2 ->\n    mem_atrans atrans (mem_except m1 a) (mem_except m2 (atrans a)) AP1.\n  Proof using MTrans AP1_ok.\n    intros; unfold mem_atrans, mem_except; intro x.\n    destruct (AEQ1 x a); destruct (AEQ2 (atrans x) (atrans a));\n      subst; auto; try tauto.\n    destruct (indomain_dec x m1); auto.\n    contradict n.\n    apply H; auto.\n  Qed.\n\n  Section MEMMATCH_INVERSION.\n\n    Variable ainv : AT2 -> AT1.\n    Variable HInv : cond_inverse atrans AP1 AP2 ainv.\n\n    Lemma mem_ainv_any : forall a (ap : AP2 a) x,\n      m1 (ainv a) = x -> m2 a = x.\n    Proof using MTrans HInv.\n      intros.\n      replace a with (atrans (ainv a)) by (apply HInv; auto).\n      assert (AP1 (ainv a)) as Hx by (apply HInv; auto).\n      rewrite <- (MTrans Hx); auto.\n    Qed.\n\n    Lemma mem_atrans_inv_ptsto : forall a (ap : AP2 a) F v,\n      (F * (ainv a) |-> v)%pred m1\n      -> (any * a |-> v)%pred m2.\n    Proof using MTrans HInv.\n      intros.\n      apply any_sep_star_ptsto.\n      eapply mem_ainv_any; eauto.\n      eapply ptsto_valid'; eauto.\n    Qed.\n\n    Lemma mem_atrans_inv_notindomain : forall a (ap : AP2 a),\n      notindomain (ainv a) m1 -> notindomain a m2.\n    Proof using MTrans HInv.\n      unfold notindomain; intros.\n      eapply mem_ainv_any; eauto.\n    Qed.\n\n    Lemma mem_atrans_inv_indomain : forall a (ap : AP2 a),\n      indomain (ainv a) m1 -> indomain a m2.\n    Proof using MTrans HInv.\n      unfold indomain; intros.\n      destruct H; eexists.\n      eapply mem_ainv_any; eauto.\n    Qed.\n\n    Lemma mem_atrans_emp :\n      emp m1 -> emp m2.\n    Proof using MTrans HInv AP2_ok AP2_dec.\n      unfold emp; intros.\n      destruct (AP2_dec a).\n\n      replace a with (atrans (ainv a)).\n      apply mem_ainv_any; auto.\n      replace (atrans (ainv a)) with a; auto.\n      apply eq_sym; apply HInv; auto.\n      apply HInv; auto.\n\n      destruct (indomain_dec a m2); auto.\n      contradict H0.\n      apply AP2_ok; auto.\n    Qed.\n\n    Lemma mem_ainv_mem_except : forall a (ap : AP2 a),\n      mem_atrans atrans (mem_except m1 (ainv a)) (mem_except m2 a) AP1.\n    Proof using MTrans HInv AP1_ok.\n      intros; unfold mem_atrans, mem_except; intro x.\n      destruct (AEQ1 x (ainv a)); destruct (AEQ2 (atrans x) a);\n        try subst; auto; try tauto.\n\n      contradict n.\n      apply HInv; auto.\n      destruct (indomain_dec x m1); auto.\n      contradict n.\n      apply eq_sym.\n      apply HInv; auto.\n    Qed.\n\n    Lemma mem_ainv_mem_upd : forall a v (ap : AP2 a),\n      mem_atrans atrans (Mem.upd m1 (ainv a) v) (Mem.upd m2 a v) AP1.\n    Proof using MTrans HInv.\n      intros; unfold mem_atrans, Mem.upd; intro x.\n      destruct (AEQ1 x (ainv a)); destruct (AEQ2 (atrans x) a); auto.\n      contradict n; subst.\n      apply HInv; auto.\n\n      intros; subst.\n      contradict n.\n      erewrite cond_inv_rewrite_left; eauto.\n    Qed.\n\n    Lemma mem_atrans_cond_inv : mem_atrans ainv m2 m1 AP2.\n    Proof using HInv MTrans.\n      cbv [mem_atrans cond_inverse cond_left_inverse cond_right_inverse] in *.\n      destruct HInv as [_ H'].\n      intros a ?; specialize (H' a).\n      rewrite MTrans by intuition.\n      f_equal. intuition.\n    Qed.\n\n  End MEMMATCH_INVERSION.\n\nEnd MEMMATCH.\n\n", "meta": {"author": "mit-pdos", "repo": "fscq", "sha": "2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0", "save_path": "github-repos/coq/mit-pdos-fscq", "path": "github-repos/coq/mit-pdos-fscq/fscq-2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0/src/MemMatch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636752, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6813491245273773}}
{"text": "(******************************************************************************)\n(* Dr Daniel Kirk (c) 2021                                                    *)\n(******************************************************************************)\n(* ringIBN.axiom R == for a ring R, a proposition that:                       *)\n(*                    forall n m : nat,                                       *)\n(*                       lmodIsomType R\\lmod^n R\\lmod^m -> n == m             *)\n(* ringIBNType     == a record consisting of a ringType 'sort' and a proof    *)\n(*                    that (ringIBN.axiom sort holds).                        *)\n(*                    R : ringIBN coerces to ringType                         *)\n(******************************************************************************)\n(* IBN_equiv_equal_basis_nums == proof that all bases of M have the same size *)\n(******************************************************************************)\n(* Let R : ringIBNType, and let A, B : fdFreeLmodType R                       *)\n(******************************************************************************)\n(* \\dim(A)         == the unique basis number of M                            *)\n(* dim_of_oplus    == proof that \\dim(A \\oplus B) = \\dim(A) + \\dim(B)         *)\n(******************************************************************************)\n(* Let I : linIsomType A B                                                    *)\n(******************************************************************************)\n(* dim_of_isom I   == proof that \\dim(A) = \\dim(B)                            *)\n(******************************************************************************)\n(* Let F : finType and I : F -> fdFreeLmodType R                              *)\n(******************************************************************************)\n(* dim_of_bigoplus == proof that \\dim(\\bigoplus_F I) = \\sum_(f : F)\\dim(I f)  *)\n(******************************************************************************)\n\nFrom Coq.Logic Require Import ProofIrrelevance FunctionalExtensionality.\nRequire Import Coq.Init.Datatypes.\nFrom mathcomp Require Import ssreflect ssrfun eqtype seq fintype bigop.\n\nSet Warnings \"-parsing\". (* Some weird bug in ssrbool throws out parsing warnings*)\n  From mathcomp Require Import ssrbool ssrnat.\nSet Warnings \"parsing\".\n\nSet Warnings \"-ambiguous-paths\". (* Some weird bug in ssralg throws out coercion warnings*)\n  From mathcomp Require Import ssralg.\nSet Warnings \"ambiguous-paths\".\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Import Modules Linears lmodLC DirectSum Basis FreeModules.\n\nOpen Scope lmod_scope.\nOpen Scope ring_scope.\nModule ringIBN.\n  Section Def.\n    Definition axiom (R : ringType) :=\n      forall n m : nat,\n        (linIsomType (R\\lmod^n) (R\\lmod^m)) -> n == m.\n\n    Record mixin (R : ringType) := Mixin { _ : axiom R; }.\n    Record type := Pack { sort : _;  class_of : mixin sort; }.\n  End Def.\n  Section Result.\n    Variable (R : ringType).\n    Theorem IBN_equiv_equal_basis_nums : axiom R <->\n      forall (M : fdFreeLmodType R) (B1 B2 : lmodFinBasisType M),\n      (basis_number B1) == (basis_number B2).\n    Proof.\n      split; rewrite/axiom=>H.\n        move=>M B1 B2.\n        move: (H (basis_number B1) (basis_number B2))=>H2.\n        have N1 : (basis_number B1) = size (enum (to_FinType (fdBasis (fdFreeLmodPack B1)))) by rewrite -cardT.\n        have N2 : (basis_number B2) = size (enum (to_FinType (fdBasis (fdFreeLmodPack B2)))) by rewrite -cardT.\n        apply (H _ _ (linIsomConcat (linIsomInvert (freeLinear.to_row N1)) (freeLinear.to_row N2))).\n\n        move=>n m f.\n        move: (H (fdFreeLmod_vector R m)\n          (fdBasis (fdFreeLmod_vector R m))\n          (@lmodBasis_to_finLmodBasis _ _\n            (lmodBasis.isomorphicBasis f (lmodFinBasis_to_lmodBasis (fdBasis (fdFreeLmod_vector R n))))\n            (Finite.class (ordinal_finType n))\n          )).\n      by rewrite /basis_number card_ord card_ord eq_sym.\n    Qed.\n  End Result.\n\n  Module Exports.\n    Notation \"'\\' 'dim' '(' M ')'\" := (basis_number (fdBasis M)) (at level 0, format \"'\\' 'dim' '(' M ')'\") : lmod_scope.\n    Notation ringIBNType := type.\n    Coercion sort : type >-> ringType.\n    Coercion class_of : type >-> mixin.\n  End Exports.\n\n  Section Results.\n    Variable (R : type).\n    Export Exports.\n    Open Scope nat_scope.\n    Lemma dim_of_oplus : forall (M1 M2 : fdFreeLmodType R),\n    \\dim(M1 \\foplus M2) = \\dim(M1) + \\dim(M2).\n    Proof. move=> M1 M2.\n      by rewrite /dsFdFreeLmod.Pair.fdFreeLmod/lmodFinBasis.basis_number card_sum.\n    Qed.\n\n    Lemma dim_of_bigoplus : forall {F : finType} (I : F -> fdFreeLmodType R),\n      \\dim(\\fbigoplus I) = \\sum_f (\\dim(I f)).\n    Proof. move => F I.\n      rewrite /dsFdFreeLmod.type/dsFdFreeLmod.Seq.fdFreeLmod -big_enum enumT =>/=.\n      induction(Finite.enum F); by [\n      rewrite /lmodFinBasis.basis_number big_nil card_void|\n      rewrite big_cons -IHl -dim_of_oplus /dsFdFreeLmod.Pair.fdFreeLmod/dsFdFreeLmod.Seq.basis].\n    Qed.\n\n    Lemma dim_of_isom : forall (M1 M2 : fdFreeLmodType R) (I : linIsomType M1 M2),\n      \\dim(M1) = \\dim(M2).\n    Proof. move=>M1 M2 I.\n      move:(linIsom.Concat (linIsom.Concat (linIsom.Invert (freeLinear.to_row (fdFreeLmod.erefl M1))) I) (freeLinear.to_row (fdFreeLmod.erefl M2)))=>II.\n      destruct R as [R' [A]].\n      move:(A _ _ II)=>B; move/eqP in B.\n      by rewrite /basis_number !cardT.\n    Qed.\n\n\n    Close Scope nat_scope.\n  End Results.\nEnd ringIBN.\nExport ringIBN.Exports.\n\nClose Scope ring_scope.\nClose Scope lmod_scope.", "meta": {"author": "Modularius", "repo": "MathcompFreeModules", "sha": "5731747c5bcbafe914687d44e74f112632f07ec7", "save_path": "github-repos/coq/Modularius-MathcompFreeModules", "path": "github-repos/coq/Modularius-MathcompFreeModules/MathcompFreeModules-5731747c5bcbafe914687d44e74f112632f07ec7/theories/Modules/RingIBN.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6813491097728505}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Functor.Main.\nRequire Import Basic_Cons.Terminal.\nRequire Import Ext_Cons.Arrow.\nRequire Import Coq_Cats.Type_Cat.Card_Restriction.\nRequire Export NatTrans.NatTrans NatTrans.Operations.\nRequire Export KanExt.Local KanExt.Global KanExt.GlobalDuality\n        KanExt.GlobaltoLocal KanExt.LocaltoGlobal KanExt.LocalFacts.Main.\nRequire Export Cat.Cat_Terminal.\n\nLocal Open Scope functor_scope.\n\n(** Definition of limits and colimits using right and left kan extensions along the functor to\nthe terminal category. *)\nSection Limit.\n  Context {J C : Category} (D : J –≻ C).\n\n  Definition Cone := LoKan_Cone (Functor_To_1_Cat J) D.\n\n  Definition Cone_Morph Cn Cn' := @LoKan_Cone_Morph _ _ (Functor_To_1_Cat J) _ D Cn Cn'.\n  \n  Definition Limit : Type := Local_Right_KanExt (Functor_To_1_Cat J) D.\n\n  Definition limit_to_cone (l : Limit) : Cone := (LRKE l).\n\n  Coercion limit_to_cone : Limit >-> Cone.\n  \n  Definition cone_to_obj (cn : Cone) : C := (cone_apex cn) _o tt.\n\n  Coercion cone_to_obj : Cone >-> Obj.\n\n  Definition is_Limit (Cn : Cone) := is_Cone_Local_Right_KanExt (Functor_To_1_Cat J) D Cn.\n\n  Definition is_Limit_Limit {Cn : Cone} (il : is_Limit Cn) : Limit :=\n    is_Cone_Local_Right_KanExt_Local_Right_KanExt (Functor_To_1_Cat J) D il.\n\n  Definition Limit_is_Limit {L : Limit} : is_Limit L :=\n    Local_Right_KanExt_is_Cone_Local_Right_KanExt (Functor_To_1_Cat J) D L.\n  \nEnd Limit.\n\n(** Limits are unique up to isomorphism. *)\nProgram Definition Limit_Iso {J C : Category} {D : J –≻ C} (l l' : Limit D) :\n  (l ≃≃ l' ::> C)%isomorphism :=\n  {|\n    iso_morphism :=\n      Trans\n        (cone_morph (iso_morphism (Local_Right_KanExt_unique _ _ l l')))\n        tt;\n    inverse_morphism :=\n      Trans\n        (cone_morph (inverse_morphism (Local_Right_KanExt_unique _ _ l l')))\n        tt\n  |}.\n\nNext Obligation.\nProof (\n    f_equal\n      (fun x : LoKan_Cone_Morph l l => Trans (cone_morph x) tt)\n      (left_inverse (Local_Right_KanExt_unique _ _ l l'))\n  ).\n\nNext Obligation.\nProof (\n    f_equal\n      (fun x : LoKan_Cone_Morph l' l' => Trans (cone_morph x) tt)\n      (right_inverse (Local_Right_KanExt_unique _ _ l l'))\n  ).\n\n(** Proposition stating that category C has all limits of cardinality specified by P *)\nDefinition Has_Restr_Limits (C : Category) (P : Card_Restriction) :=\n  ∀ {J : Category} (D : J –≻ C), P J → P (Arrow J) → Limit D.\n\n(** A complete category has all limits – here it has global right kan extension *)\nDefinition Complete (C : Category) := ∀ J : Category, Right_KanExt (Functor_To_1_Cat J) C.\n\nExisting Class Complete.\n\n(** If a category is complete, we can produce all limits. *)\nDefinition Limit_of {C D : Category} {H : Complete D} (F : C –≻ D) : Limit F :=\n  Global_to_Local_Right _ _ (H _) F.\n\n(** A category having restricted limitis where the restriction always holds \nis just complete. *)\nSection Restricted_Limits_to_Complete.\n  Context {C : Category} {P : Card_Restriction} (HRL : Has_Restr_Limits C P).\n\n  Definition No_Restriction_Complete : (∀ t, P t) → Complete C :=\n    fun All_Ps J => Local_to_Global_Right _ _ (fun D => HRL _ D (All_Ps J) (All_Ps (Arrow J))).\n\nEnd Restricted_Limits_to_Complete.\n\n(** A complete category has restricted limits for any restriction. *)\nSection Complete_to_Restricted_Limits.\n  Context (C : Category) {CC : Complete C} (P : Card_Restriction).\n  \n  Definition Complete_Has_Restricted_Limits : Has_Restr_Limits C P :=\n    fun J D _ _ => Global_to_Local_Right _ _ (CC _) D.\n\nEnd Complete_to_Restricted_Limits.\n\n(** A functor is continuous if it preserces all limits. *)\nSection Continuous.\n  Context\n    {C D : Category}\n    (CC : Complete C)\n    (G : (C –≻ D)%functor)\n  .\n\n  Section Cone_Conv.\n    Context\n      {J : Category}\n      {F : (J –≻ C)%functor}\n      (Cn : Cone F)\n    .\n    \n    Program Definition Cone_Conv : Cone (G ∘ F)%functor\n      :=\n        {|\n          cone_apex :=\n            (G ∘ (cone_apex Cn))%functor;\n          cone_edge :=\n            (((NatTrans_id G) ∘_h (cone_edge Cn)) ∘ (NatTrans_Functor_assoc _ _ _))%nattrans\n        |}\n    .\n\n  End Cone_Conv.\n\n  Definition Continuous :=\n    ∀ (J : Category) (F : (J –≻ C)%functor),\n      is_Cone_Local_Right_KanExt _ _ (Cone_Conv (LRKE (Limit_of F)))\n  .\n\nEnd Continuous.\n\n(** CoLimits *)\n\nSection CoLimit.\n  Context {J C : Category} (D : J –≻ C).\n\n  Definition CoCone :=\n    LoKan_Cone (Functor_To_1_Cat J^op) (D^op).\n\n  Definition CoCone_Morph Cn Cn' :=\n    @LoKan_Cone_Morph _ _ (Functor_To_1_Cat J^op) _ (D^op) Cn Cn'.\n\n  Definition CoLimit := Local_Left_KanExt (Functor_To_1_Cat J) D.\n\n  Definition is_CoLimit (Cn : CoCone) := is_Cone_Local_Right_KanExt (Functor_To_1_Cat (J^op)) (D^op) Cn.\n\n  Definition is_CoLimit_CoLimit {Cn : CoCone} (il : is_CoLimit Cn) : CoLimit :=\n    is_Cone_Local_Right_KanExt_Local_Right_KanExt (Functor_To_1_Cat (J^op)) (D^op) il.\n\n  Definition CoLimit_is_CoLimit {L : CoLimit} : is_CoLimit L :=\n    Local_Right_KanExt_is_Cone_Local_Right_KanExt (Functor_To_1_Cat (J^op)) (D^op) L.\n\nEnd CoLimit.\n\n(** Proposition stating that category C has all colimits of cardinality specified by P *)\nDefinition Has_Restr_CoLimits (C : Category) (P : Card_Restriction) :=\n  ∀ {J : Category} (D : J –≻ C), P J → P (Arrow J) → CoLimit D.\n\n(** A cocomplete category has all colimits – here it has global left kan extension *)\nDefinition CoComplete (C : Category) := ∀ J : Category, Left_KanExt (Functor_To_1_Cat J) C.\n\nExisting Class CoComplete.\n\n(** If a category is cocomplete, we can produce all colimits. *)\nDefinition CoLimit_of {C D : Category} {H : CoComplete D} (F : C –≻ D) : CoLimit F :=\n  Global_to_Local_Left _ _ (H _) F.\n\n(** If a category is complete, its dual is cocomplete *)\nDefinition Complete_to_CoComplete_Op {C : Category} {CC : Complete C} : CoComplete (C ^op) :=\n  fun D => KanExt_Right_to_Left (Functor_To_1_Cat D ^op) C (CC (D ^op)%category).\n\n(** If a category is cocomplete, its dual is complete *)\nDefinition CoComplete_to_Complete_Op {C : Category} {CC : CoComplete C} : Complete (C ^op) :=\n    fun D => KanExt_Left_to_Right (Functor_To_1_Cat D ^op) C (CC (D ^op)%category).\n\n(** A category having restricted colimitis where the restriction always holds \nis just cocomplete. *)\nSection Restricted_CoLimits_to_CoComplete.\n  Context {C : Category} {P : Card_Restriction} (HRL : Has_Restr_CoLimits C P).\n\n  Definition No_Restriction_CoComplete : (∀ t, P t) → CoComplete C :=\n    fun All_Ps J =>\n      Local_to_Global_Left _ _ (fun D => HRL _ D (All_Ps J) (All_Ps (Arrow J))).\n\nEnd Restricted_CoLimits_to_CoComplete.\n\n(** A cocomplete category has restricted colimits for any restriction. *)\nSection CoComplete_to_Restricted_CoLimits.\n  Context (C : Category) {CC : CoComplete C} (P : Card_Restriction).\n  \n  Definition CoComplete_Has_Restricted_CoLimits : Has_Restr_CoLimits C P :=\n    fun J D _ _ => Global_to_Local_Left _ _ (CC _) D.\n\nEnd CoComplete_to_Restricted_CoLimits.\n\n(** If a category has restricted limits, its dual has restricted colomits *)\nDefinition Has_Restr_Limits_to_Has_Restr_CoLimits_Op\n        {C : Category} {P : Card_Restriction}\n        (HRL : Has_Restr_Limits C P) :\n  Has_Restr_CoLimits (C ^op) P :=\n  (fun (D : Category)\n       (F : D –≻ C ^op)\n       (H1 : P D)\n       (H2 : P (Arrow D)) =>\n     HRL\n       (D ^op)%category\n       (F ^op)%functor H1\n       (Card_Rest_Respect P (Arrow D) (Arrow (D^op)) (Arrow_OP_Iso D) H2)\n  ).\n\n(** If a category has restricted colimits, its dual has restricted lomits *)\nDefinition Has_Restr_CoLimits_to_Has_Restr_Limits_Op\n        {C : Category}\n        {P : Card_Restriction}\n        (HRL : Has_Restr_CoLimits C P) :\n  Has_Restr_Limits (C ^op) P :=\n  (fun (D : Category)\n       (F : D –≻ C ^op)\n       (H1 : P D)\n       (H2 : P (Arrow D)) =>\n     HRL\n       (D ^op)%category\n       (F ^op)%functor\n       H1\n       (Card_Rest_Respect P (Arrow D) (Arrow (D^op)) (Arrow_OP_Iso D) H2)\n  ).\n\n(** A functor is co-continuous if it preserces all co-limits. *)\nSection CoContinuous.\n  Context\n    {C D : Category}\n    (CC : CoComplete C)\n    (G : (C –≻ D)%functor)\n  .\n\n  Section CoCone_Conv.\n    Context\n      {J : Category}\n      {F : (J –≻ C)%functor}\n      (Cn : CoCone F)\n    .\n    \n    Program Definition CoCone_Conv : CoCone (G ∘ F)%functor\n      :=\n        {|\n          cone_apex :=\n            ((G ^op) ∘ (cone_apex Cn))%functor;\n          cone_edge := _\n            (((NatTrans_id (G ^op)) ∘_h (cone_edge Cn)) ∘ (NatTrans_Functor_assoc _ _ _))%nattrans\n        |}\n    .\n\n  End CoCone_Conv.\n\n  Definition CoContinuous :=\n    ∀ (J : Category) (F : (J –≻ C)%functor),\n      is_Cone_Local_Right_KanExt _ _ (CoCone_Conv (LRKE (CoLimit_of F)))\n  .\n\nEnd CoContinuous.", "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/Limits/Limit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605411, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6813491077244305}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Omega List Permutation.\n\nRequire Import utils ill_form ill_rules phase_sem rules_algebra.\n\nSet Implicit Arguments.\n\nSection Okada.\n\n(*  Hint Resolve ill_cf_perm_bang_t. *)\n\n  Variables (sc : bool) (* commutativity switch *).\n\n  Notation comp := (comp_ctx sc).\n\n  Notation sg := (@eq _).\n  Infix \"∘\" := (Composes comp) (at level 50, no associativity).\n  Infix \"⊸\" := (Magicwand_l comp) (at level 51, right associativity).\n  Infix \"⟜\" := (Magicwand_r comp) (at level 52, left associativity).\n\n  Let cl := cl_ctx sc false.\n\n  Let cl_increase X : X ⊆ cl X.\n  Proof. apply cl_ctx_increase. Qed.\n \n  Let cl_mono X Y : X ⊆ Y -> cl X ⊆ cl Y.\n  Proof. apply cl_ctx_mono. Qed.\n  \n  Let cl_idem X : cl (cl X) ⊆  cl X.\n  Proof. apply cl_ctx_idem. Qed.\n\n  Let cl_stable_l : forall X Y, cl X ∘ Y ⊆ cl (X ∘ Y).\n  Proof. apply cl_ctx_stable_l; eauto. Qed.\n\n  Let cl_stable_r : forall X Y, X ∘ cl Y ⊆ cl (X ∘ Y).\n  Proof. apply cl_ctx_stable_r; eauto. Qed.\n \n  Notation \"↓\" := (fun A Γ => ill_proof sc false Γ A).\n  Notation K := (fun Δ => { Γ | Δ = ‼Γ }).\n\n  Let dc_closed A : cl (↓A) ⊆ ↓A.\n  Proof. apply dc_closed. Qed.\n\n  Let v x := ↓ (£x).\n\n  Let Hv x : cl (v x) ⊆ v x.\n  Proof. apply dc_closed. Qed.\n\n  Notation \"'⟦' A '⟧'\" := (Form_sem cl comp ∅ K v A) (at level 49).\n\n  Let cl_sem_closed A : cl (⟦A⟧) ⊆ ⟦A⟧.\n  Proof. apply closed_Form_sem; eauto. Qed.\n \n  Section Okada.\n\n    (** This is Okada's lemma which states that the interpretation ⟦A⟧\n        of A is nearly identical to ↓A, \n\n               A::nil ∈ ⟦A⟧ ⊆ ↓A.\n\n        a result which is similar to what happens in the Lidenbaum construction.\n        Indeed, in Lidenbaum construction, one proves \n\n                 ⟦A⟧ ≃ ↓A\n\n        but that result needs the cut-rule.  \n\n        The MAJOR difference is that Okada's proof does not require \n        the use of cut. It is done by induction on A.\n\n         But first, let us give the algebraic interpretation\n         of the rules of the cut-free ILL sequent calculus *)\n\n    Let rule_ax A : ↓A (A::∅). \n    Proof. apply in_llp_ax. Qed.\n\n    Let rule_limp_l A B : (↓A ⊸ cl (sg (B::∅))) (A -o B::∅). \n    Proof. \n      apply rule_limp_l_eq; eauto. \n      intros ? ? ? ?; apply in_llp_limp_l. \n    Qed.\n\n    Let rule_limp_r A B : sg (A::∅) ⊸ ↓B ⊆ ↓(A -o B).\n    Proof. \n      apply rule_limp_r_eq; eauto. \n      intros ?; apply in_llp_limp_r. \n    Qed.\n\n    Let rule_rimp_l A B : (cl (sg (B::∅)) ⟜ ↓A) (B o- A::∅).\n    Proof. \n      apply rule_rimp_l_eq; eauto. \n      intros ? ? ? ?; apply in_llp_rimp_l. \n    Qed.\n\n    Let rule_rimp_r A B : ↓B ⟜ sg (A::∅) ⊆ ↓(B o- A).\n    Proof. \n      apply rule_rimp_r_eq; eauto.\n      intros ?; apply in_llp_rimp_r.\n    Qed.\n\n    Let rule_times_l A B : cl (sg (A::B::nil)) (A⊗B::nil).\n    Proof.\n      apply rule_times_l_eq.\n      intros ? ? ?; apply in_llp_times_l.\n    Qed.\n\n    Let rule_times_r A B : ↓A ∘ ↓B ⊆ ↓(A⊗B).\n    Proof.\n      apply rule_times_r_eq; eauto.\n      intros ? ?; apply in_llp_times_r.\n    Qed.\n\n    Let rule_with_l1 A B : cl (sg (A::∅)) (A&B::∅).\n    Proof.\n      apply rule_with_l1_eq.\n      intros ? ? ?; apply in_llp_with_l1.\n    Qed.\n \n    Let rule_with_l2 A B : cl (sg (B::∅)) (A&B::∅).\n    Proof.\n      apply rule_with_l2_eq.\n      intros ? ? ?; apply in_llp_with_l2.\n    Qed.\n\n    Let rule_with_r A B : ↓A ∩ ↓B ⊆ ↓(A & B).\n    Proof.\n      apply rule_with_r_eq.\n      intros ?; apply in_llp_with_r.\n    Qed.\n\n    Let rule_plus_l A B : cl (sg (A::∅) ∪ sg (B::∅)) (A⊕B::∅).\n    Proof.\n      apply rule_plus_l_eq.\n      intros ? ?; apply in_llp_plus_l.\n    Qed.\n\n    Let rule_plus_r1 A B : ↓A ⊆ ↓(A⊕B).\n    Proof.\n      apply rule_plus_r1_eq.\n      intro; apply in_llp_plus_r1.\n    Qed.\n\n    Let rule_plus_r2 A B : ↓B ⊆ ↓(A⊕B).\n    Proof.\n      apply rule_plus_r2_eq.\n      intro; apply in_llp_plus_r2.\n    Qed.\n\n    Let rule_bang_l A : cl (sg (A::∅)) (!A::∅).\n    Proof.\n      apply rule_bang_l_eq.\n      intros ? ?; apply in_llp_bang_l.\n    Qed.\n\n    Let rule_bang_r A : K ∩ ↓A ⊆ ↓(!A).\n    Proof.\n      apply rule_bang_r_eq.\n      intros ?; apply in_llp_bang_r.\n    Qed.\n\n    Let rule_unit_l : cl (sg ∅) (𝝐::nil).\n    Proof.\n      apply rule_unit_l_eq.\n      intros ?; apply in_llp_unit_l.\n    Qed.\n    \n    Let rule_unit_r : sg ∅ ⊆ ↓𝝐.\n    Proof.\n      apply rule_unit_r_eq.\n      apply in_llp_unit_r.\n    Qed.\n\n    Let rule_bot_l : cl (fun _ => False) (⟘::∅).\n    Proof. \n      apply rule_bot_l_eq, in_llp_bot_l.\n    Qed.\n\n    Let rule_top_r : (fun _ => True) ⊆ ↓⟙ .\n    Proof.\n      apply rule_top_r_eq, in_llp_top_r. \n    Qed.\n\n    Let mwl_mono (X Y X' Y' : _ -> Type) : X ⊆ X' -> Y ⊆ Y' -> X' ⊸ Y ⊆ X ⊸ Y'.\n    Proof. apply magicwand_l_monotone; auto. Qed.\n\n    Let mwr_mono (X Y X' Y' : _ -> Type) : X ⊆ X' -> Y ⊆ Y' -> Y ⟜ X' ⊆ Y' ⟜ X.\n    Proof. apply magicwand_r_monotone; auto. Qed.\n\n    Let inc1_prop (K : Type) (X Y : K -> Type)  x : Y ⊆ X -> Y x -> X x.\n    Proof. simpl; auto. Qed.\n\n    Let cl_under_closed X Y : cl Y ⊆ Y -> X ⊆ Y -> cl X ⊆ Y.\n    Proof. apply cl_closed; eauto. Qed.\n \n    Lemma Okada_formula A : ((sg (A::nil) ⊆ ⟦A⟧) * (⟦A⟧ ⊆ ↓A))%type.\n    Proof.\n      induction A as [ | [] | A [H1 H2] | [] A [H1 H2] B [H3 H4] ]; auto.\n      + split; simpl; auto.\n        intros _ []; apply rule_ax.\n      + split. \n        * intros _ []; apply rule_unit_l.\n        * simpl; apply cl_under_closed; auto; apply rule_unit_r.\n      + split.\n        * intros _ []; apply rule_bot_l.\n        * simpl; apply cl_under_closed; auto; intros _ [].\n      + split; simpl; red; auto.\n      + split.\n        * intros _ [].\n          simpl.\n          intros Th De B H.\n          apply H with (ϴ := !A::nil); split.\n          - exists (A::nil); auto.\n          - apply inc1_prop with (2 := @rule_bang_l _).\n            apply cl_under_closed; auto.\n        * simpl; apply cl_under_closed; auto.\n          intros x []; apply rule_bang_r; split; auto.\n      + split.\n        * intros _ [].\n          simpl; split.\n          - apply cl_under_closed with (2 := H1); auto.\n          - apply cl_under_closed with (2 := H3); auto.\n        * intros Ga (? & ?); apply rule_with_r; auto.\n      + split.\n        * intros _ []; simpl.\n          apply inc1_prop with (2 := @rule_limp_l _ _).\n          apply mwl_mono; auto; apply cl_under_closed; auto.\n        * simpl; intros x Hx; apply rule_limp_r.\n          revert Hx; apply mwl_mono; auto.\n      + split.\n        * intros _ []; simpl.\n          apply inc1_prop with (2 := @rule_rimp_l _ _).\n          apply mwr_mono; auto; apply cl_under_closed; auto.\n        * simpl; intros x Hx; apply rule_rimp_r.\n          revert Hx; apply mwr_mono; auto.\n      + split.\n        * intros _ [].\n          apply inc1_prop with (2 := @rule_times_l _ _).\n          simpl; apply cl_mono.\n          intros _ []; constructor 1 with (A::∅) (B::∅); auto.\n          red; simpl; auto.\n        * simpl; apply cl_under_closed; auto.\n          intros x Hx; apply rule_times_r.\n          revert Hx; apply composes_monotone; eauto.\n      + split.\n        * intros _ [].\n          apply inc1_prop with (2 := @rule_plus_l _ _).\n          simpl; apply cl_mono; eauto.\n          intros _ [ [] | [] ]; auto.\n        * simpl; apply cl_under_closed; auto.\n          intros x [ Hx | Hx ]; auto.\n          - apply rule_plus_r1; auto.\n          - apply rule_plus_r2; auto.\n    Qed.\n\n  End Okada.\n\n  Notation \"'⟬߭' Γ '⟭'\" := (list_Form_sem cl comp ∅ K v Γ) (at level 49).\n\n  (* We lift the result to contexts, ie list of formulas *)\n\n  Lemma Okada_ctx Γ: ⟬߭Γ⟭  Γ.\n  Proof.\n    induction Γ as [ | A ga Hga ]; simpl; \n      apply cl_increase; auto.\n    constructor 1 with (A :: nil) ga; auto.\n    + apply Okada_formula; auto.\n    + red; auto.\n  Qed.\n\nEnd Okada.\n\n(** The notation Γ ⊢ A [comm,cut] is for the type of proofs of the sequent Γ ⊢ A\n    * in commutative ILL if comm=true; ILLNC if comm=false\n    * with cut if cut=true; cut-free if cut=false\n*)\n\nSection NC_cut_admissibility.\n\n  Theorem ill_nc_cut_elimination Γ A : Γ ⊢ A [false,true] -> Γ ⊢ A [false,false].\n  Proof.\n     intros H.\n     apply rules_nc_sound with (s1 := false) (s2 := false) (v := fun x ga => ill_proof false false ga (£x)) in H.\n     + apply Okada_formula, H, Okada_ctx.\n     + intros x Ga H1; red in H1.\n       replace Ga with (nil++Ga++nil); [ apply H1 | ]; intros; rewrite <- app_nil_end; auto.\n  Qed.\n\nEnd NC_cut_admissibility.\n\nSection COMM_cut_admissibility.\n\n  Theorem ill_comm_cut_elimination Γ A : Γ ⊢ A [true,true] -> Γ ⊢ A [true,false].\n  Proof.\n     intros H.\n     apply rules_comm_sound with (s1 := true) (s2 := false) (v := fun x ga => ill_proof true false ga (£x)) in H; auto.\n     + apply Okada_formula, H, Okada_ctx.\n     + intros x Ga H1; red in H1.\n       replace Ga with (nil++Ga++nil); [ apply H1 | ]; intros; rewrite <- app_nil_end; auto.\n  Qed.\n\nEnd COMM_cut_admissibility.\n\nCheck ill_nc_cut_elimination.\nPrint Assumptions ill_nc_cut_elimination.\n\nCheck ill_comm_cut_elimination.\nPrint Assumptions ill_comm_cut_elimination.\n\n\n", "meta": {"author": "DmxLarchey", "repo": "Coq-Phase-Semantics", "sha": "52f7751ac71ab6d19fbc0a5a5c552a6ddd8e3b17", "save_path": "github-repos/coq/DmxLarchey-Coq-Phase-Semantics", "path": "github-repos/coq/DmxLarchey-Coq-Phase-Semantics/Coq-Phase-Semantics-52f7751ac71ab6d19fbc0a5a5c552a6ddd8e3b17/coq.gen/cut_elim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6813157492974787}}
{"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.\nRequire int.Abs.\nRequire int.EuclideanDivision.\nRequire int.ComputerDivision.\nRequire number.Parity.\nRequire number.Divisibility.\nRequire number.Gcd.\nRequire number.Prime.\n\n(* Why3 assumption *)\nDefinition coprime (a:Z) (b:Z): Prop := ((number.Gcd.gcd a b) = 1%Z).\n\nLemma coprime_is_Zrel_prime :\n  forall a b, coprime a b <-> Znumtheory.rel_prime a b.\nintros.\nunfold coprime.\nunfold Znumtheory.rel_prime.\nsplit; intro h.\nrewrite <- h; apply Znumtheory.Zgcd_is_gcd.\napply Znumtheory.Zis_gcd_gcd; auto with zarith.\nQed.\n\n(* Why3 goal *)\nLemma prime_coprime :\nforall (p:Z),\n (number.Prime.prime p) <->\n ((2%Z <= p)%Z /\\ forall (n:Z), ((1%Z <= n)%Z /\\ (n < p)%Z) -> (coprime n p)).\nintros p.\n(*\nZnumtheory.prime_intro:\n  forall p : int,\n  (1 < p)%Z ->\n  (forall n : int, (1 <= n < p)%Z -> Znumtheory.rel_prime n p) ->\n  Znumtheory.prime p\n*)\nrewrite Prime.prime_is_Zprime.\nsplit.\nintro h; inversion h; clear h.\nsplit; auto with zarith.\nintros n h.\nrewrite coprime_is_Zrel_prime.\napply H0; auto.\nintros (h1,h2).\nconstructor; auto with zarith.\nintros n h.\nrewrite <- coprime_is_Zrel_prime.\napply h2; auto.\nQed.\n\n(* Why3 goal *)\nLemma Gauss :\nforall (a:Z) (b:Z) (c:Z),\n ((number.Divisibility.divides a (b * c)%Z) /\\ (coprime a b)) ->\n (number.Divisibility.divides a c).\nintros a b c (h1,h2).\napply Znumtheory.Gauss with b; auto.\nrewrite <- coprime_is_Zrel_prime; auto.\nQed.\n\n(* Why3 goal *)\nLemma Euclid :\nforall (p:Z) (a:Z) (b:Z),\n ((number.Prime.prime p) /\\ (number.Divisibility.divides p (a * b)%Z)) ->\n ((number.Divisibility.divides p a) \\/ (number.Divisibility.divides p b)).\nintros p a b (h1,h2).\napply Znumtheory.prime_mult; auto.\nnow rewrite <- Prime.prime_is_Zprime.\nQed.\n\n(* Why3 goal *)\nLemma gcd_coprime :\nforall (a:Z) (b:Z) (c:Z),\n (coprime a b) -> ((number.Gcd.gcd a (b * c)%Z) = (number.Gcd.gcd a c)).\nintros a b c h1.\napply Z.gcd_unique.\n- apply Z.gcd_nonneg.\n- apply Gcd.gcd_def1.\n- apply Divisibility.divides_multl.\n  apply Gcd.gcd_def2.\n- intros q h2 h3.\n  apply Gcd.gcd_def3.\n  trivial.\n  apply Gauss with b; split; auto.\n  rewrite coprime_is_Zrel_prime.\n  rewrite coprime_is_Zrel_prime in h1.\n  now apply Znumtheory.rel_prime_div with (2:=h2).\nQed.\n\n", "meta": {"author": "florianschanda", "repo": "why3", "sha": "dc0d2720d58c6d130b9c3e1db820a07275a133eb", "save_path": "github-repos/coq/florianschanda-why3", "path": "github-repos/coq/florianschanda-why3/why3-dc0d2720d58c6d130b9c3e1db820a07275a133eb/lib/coq/number/Coprime.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6813157454797649}}
{"text": "Module tmp.\nInductive day : Type :=\n| monday : day\n| tuesday : day\n| wednesday : day\n| thursday : day\n| friday : day\n| saturday : day\n| sunday : day.\n\nDefinition next_weekday (d:day) : day :=\n  match d with\n    | monday => tuesday\n    | tuesday => wednesday\n    | wednesday => thursday\n    | thursday => friday\n    | friday => monday\n    | saturday => monday\n    | sunday => monday\n  end.\n\nEval simpl in (next_weekday friday).\nEval simpl in (next_weekday (next_weekday saturday)).\n\nExample text_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\nProof. simpl. reflexivity. Qed.\n\nInductive bool: Type :=\n| true : bool\n| false : bool.\n\nDefinition negb (b:bool) : bool :=\n  match b with\n    | true => false\n    | false => true\n  end.\n\nDefinition andb (b1: bool) (b2: bool) : bool :=\n  match b1 with\n    | true => b2\n    | false => false\n  end.\n\nDefinition orb (b1: bool) (b2: bool) : bool :=\n  match b1 with\n    | true => true\n    | false => b2\n  end.\n\nExample test_orb1: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb2: (orb false false) = false.\nProof. simpl. reflexivity. Qed.\nExample test_orb3: (orb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb4: (orb true true) = true.\nProof. simpl. reflexivity. Qed.\n\nDefinition admit {T: Type} : T. Admitted.\n\nDefinition nandb (b1: bool) (b2: bool) : bool :=\n  match b1 with\n    | true => negb b2\n    | false => true\n  end.\n\nExample test_nandb1: (nandb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb2: (nandb false false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb3: (nandb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb4: (nandb true true) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  match b1 with\n    | true => andb b2 b3\n    | false => false\n  end.\n\nExample test_andb31: (andb3 true true true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_andb32: (andb3 false true true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb33: (andb3 true false true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb34: (andb3 true true false) = false.\nProof. simpl. reflexivity. Qed.\n\nCheck (negb true).\nCheck negb.\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\n\nCheck (S (S (S (S 0)))).\n\nEval simpl in (minustwo 4).\n\nCheck S.\nCheck pred.\nCheck minustwo.\n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n    | O => true\n    | S O => false\n    | S (S n') => evenb n'\n  end.\n\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\nExample test_oddb1: (oddb (S O)) = true.\nProof. simpl. reflexivity. Qed.\nExample test_oddb2: (oddb (S (S (S (S O))))) = false.\nProof. simpl. reflexivity. Qed.\n\nModule Playground2.\n\n  Fixpoint plus (n : nat) (m : nat) : nat :=\n    match n with\n      | O => m\n      | S n' => S (plus n' m)\n    end.\n\n  Eval simpl in (plus (S (S (S 0)))) (S (S 0)).\n\n  Fixpoint mult (n m : nat) : nat :=\n    match n with\n      | O => O\n      | S n' => plus m (mult n' m)\n    end.\n\n  Fixpoint minus (n m: nat) : nat :=\n    match n, m with\n      | O, _ => O\n      | S _, O => n\n      | S n', S m' => minus n' m'\n    end.\nEnd Playground2.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n    | O => S O\n    | S p => mult base (exp base p)\n  end.\n\nExample test_mult1: (mult 3 3) = 9.\nProof. simpl. reflexivity. Qed.\n\nFixpoint factorial (n:nat) : nat :=\n  match n with\n    | O => 1\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) (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 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\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\nFixpoint blt_nat (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 n' m'\n  end.\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\nTheorem plus_0_n : forall n: nat, 0 + n = n.\nProof. simpl. reflexivity. Qed.\n\nTheorem plus_0_n' : forall n: nat, 0 + n = n.\nProof. reflexivity. Qed.\n\nEval simpl in (forall n: nat, n + 0 = n).\nEval simpl in (forall n: nat, 0 + n = n).\n\nTheorem plus_0_n'' : forall n: nat, 0 + n = n.\nProof. intros n. reflexivity. Qed.\n\nTheorem plus_1_l : forall n: nat, 1 + n = S n.\nProof. intros. reflexivity. Qed.\n\nTheorem mult_0_l : forall n:nat, 0 * n = 0.\nProof. intros. reflexivity. Qed.\n\nTheorem plus_id_example : forall n m : nat,\n                            n = m -> n + n = m + m.\nProof. intros n m. intros H. rewrite -> H. reflexivity. Qed.  \n\nTheorem plus_id_exercise : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o.\n  intros H.\n  intros I.\n  rewrite -> H.\n  rewrite -> I.\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  rewrite -> plus_0_n.\n  reflexivity.\nQed.\n\nTheorem mult_1_plus : forall n m : nat,\n                        (1 + n) * m = m + (n * m).\nProof.\n  intros n m.\n  rewrite -> plus_1_l.\n  reflexivity.\nQed.\n\nTheorem plus_1_neq_0 : forall n : nat,\n                         beq_nat(n + 1) 0 = false.\nProof.\n  intros n. destruct n as [| n'].\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem negb_involtive : 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.\n  reflexivity.\n  reflexivity.\nQed.\n\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n  match reverse goal with\n    | H : _ |- _ => try move x after H\n  end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n  let H := fresh in\n  assert (x = v) as H by reflexivity;\n    clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n  first [\n      set (x := name); move_to_top x\n    | assert_eq x name; move_to_top x\n    | fail 1 \"because we are working on a different case\"\n    ].\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.\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  rewrite <- H.\n  reflexivity.\n  rewrite <- H.\n  destruct b.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem plus_0_r : forall n:nat, n + 0 = n.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\". simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem minus_diag : forall n,\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_0_r : forall n:nat,\n                     n * 0 = 0.\nProof.\n  intros n.\n  induction n as [| n'].\n  + simpl.\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 m.\n  induction n as [| n'].\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\nLemma succ : forall n m : nat,\n               S(n + m) = n + S(m).\nProof.\n  intros n m.\n  induction n.\n  + reflexivity.\n  + simpl.\n    rewrite IHn.\n    reflexivity.\nQed.\n\nTheorem plus_comm : forall n m : nat,\n                      n + m = m + n.\nProof.\n  intros n m.\n  induction n as [| n'].\n  + simpl.\n    rewrite plus_0_r.\n    reflexivity.\n  + simpl.\n    rewrite IHn'.\n    destruct m.\n    reflexivity.\n    induction m as [| m'].\n    * reflexivity.\n    * simpl.\n      rewrite succ.\n      reflexivity.\nQed.\n\nFixpoint double (n: nat) :=\n  match n with\n    | O => O\n    | S n' => S (S (double n'))\n  end.\n\nLemma double_plus : forall n, double n = n + n.\nProof.\n  intros n.\n  induction n as [| n'].\n  + reflexivity.\n  + simpl.\n    rewrite <- succ.\n    rewrite <- IHn'.\n    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.\n    rewrite IHn'.\n    reflexivity.\nQed.\n\nTheorem mult_0_plus' : forall n m : nat,\n                         (0 + n) * m = n * m.\nProof.\n  intros n m.\n  assert (H: 0 + n = n).\n  + reflexivity.\n  + rewrite -> H.\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.\n  induction n as [|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  assert(H: (n + m) + p = n + (m + p)).\n  + rewrite <-plus_assoc.\n    reflexivity.\n  + assert(I: (m + n) + p = m + (n + p)).\n      rewrite <- plus_assoc.\n      reflexivity.\n  rewrite <- H.\n  rewrite <- I.\n  assert(J: n + m = m + n).\n  rewrite <- plus_comm.\n  reflexivity.\n  rewrite J.\n  reflexivity.\nQed.\n\nTheorem ble_nat_refl : forall n: nat,\n                         true = ble_nat n n.\nProof.\n  intros n.\n  induction n as [|n'].\n  + simpl. reflexivity.\n  + simpl. rewrite IHn'.\n    reflexivity.\nQed.\n\nTheorem zero_nbeq_S : forall n:nat,\n                        beq_nat 0 (S n) = false.\nProof.\n  intros n.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem andb_false_r : forall b : bool,\n                         andb b false = false.\nProof.\n  intros b.\n  destruct b.\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 m p.\n  intros H.\n  induction p as [| p'].\n  + simpl. rewrite H. reflexivity.\n  + simpl. rewrite IHp'. reflexivity.\nQed.\n\n\nTheorem S_nbeq_0 : forall n: nat,\n                     beq_nat (S n) 0 = false.\nProof.\n  intros n.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem mult_1_l : forall n:nat, 1*n = n.\nProof.\n  intros n.\n  simpl.\n  rewrite plus_0_r.\n  reflexivity.\nQed.\n\nTheorem all3_spec : forall b c : bool,\n                      orb (andb b c)\n                          (orb (negb b)\n                               (negb c)) = true.\nProof.\n  intros b c.\n  destruct b.\n  + simpl.\n    destruct c.\n    simpl.\n    reflexivity.\n    simpl.\n    reflexivity.\n  + simpl.\n    reflexivity.\nQed.\n\n\n\nInductive bin: Type :=\n| O  : bin\n| B  : bin -> bin\n| Bp : bin -> bin.\n\n\nFixpoint binc (b : bin) :bin :=\n  match b with\n    | O     => Bp O\n    | B b'  => Bp b'\n    | Bp b' => B (binc b')\n  end.\n\nFixpoint bin_to_nat (b: bin) :nat :=\n  match b with\n    | O     => 0\n    | B O   => 0\n    | B b'  => 2 * (bin_to_nat b')\n    | Bp b' => 2 * (bin_to_nat b') + 1\n  end.\n\nFixpoint nat_to_bin (n : nat) : bin :=\n  match n with\n    | 0 => O\n    | S (n') => binc (nat_to_bin n')\n  end.\n\nFixpoint normalize (b: bin) : bin :=\n  match bin_to_nat b with\n    | 0    => O\n    | S n  => binc (nat_to_bin n)\n  end.\n\nEnd tmp.", "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/tmp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.6813049154876563}}
{"text": "Require Export Logic.\n\nPrint beautiful.\nCheck b_sum.\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\nPrint eight_is_beautiful.\nCheck (b_sum 3 5 b_3 b_5).\n\nTheorem eight_is_beautiful': beautiful 8.\nProof.\n    apply (b_sum 3 5 b_3 b_5).\nQed.\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\nDefinition eight_is_beautiful''' : beautiful 8 :=\n    b_sum 3 5 b_3 b_5.\n\nPrint eight_is_beautiful.\nPrint eight_is_beautiful'.\nPrint eight_is_beautiful''.\nPrint eight_is_beautiful'''.\n\nTheorem six_is_beautiful : beautiful 6.\nProof.\n    apply b_sum with (n:=3) (m:=3).\n    apply b_3.\n    apply b_3.\nQed.\n\nDefinition six_is_beautiful' : beautiful 6 :=\n    b_sum 3 3 b_3 b_3.\n\nTheorem nine_is_beautiful :\n    beautiful 9.\nProof.\n    apply b_sum with (n:=3) (m:=6).\n    apply b_3.\n    apply six_is_beautiful.\nQed.\n\nDefinition nine_is_beautiful' : beautiful 9 :=\n    b_sum 3 6 b_3 six_is_beautiful'.\n\nTheorem b_plus3: forall n, beautiful n -> beautiful (3+n).\nProof.\n    intros n H.\n    apply b_sum.\n    apply b_3.\n    apply H.\nQed.\n\nDefinition b_plus3' : forall n, beautiful n -> beautiful (3+n) :=\n    fun (n : nat) => fun (H : beautiful n) =>\n        b_sum 3 n b_3 H.\n\nCheck b_plus3'.\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\nDefinition beautiful_plus3 : Prop :=\n    forall n, forall(E : beautiful n), beautiful (n+3).\n\nDefinition beautiful_plus3' : Prop :=\n    forall n, forall(_ : beautiful n), beautiful (n+3).\n\nDefinition beatufiul_plus3'' : Prop :=\n    forall n, beautiful n -> beautiful (n+3).\n\n(* \"P -> Q\" is a syntatic sugar for \"forall (_:P), Q\" *)\n\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n    intros.\n    simpl.\n    apply b_sum.\n        Case \"n\".\n            apply H.\n        Case \"n + 0\".\n            apply b_sum.\n            SCase \"n\". apply H.\n\n            SCase \"0\". apply b_0.\nQed.\n\nDefinition b_times2': forall n, beautiful n -> beautiful (2*n) :=\n    fun (n : nat) => fun (H : beautiful n) =>\n        b_sum n (n+0) H (b_sum n 0 H b_0).\n\nDefinition gorgeous_plus13_po : forall n, gorgeous n -> gorgeous (13+n) :=\n    fun (n : nat) => fun (H : gorgeous n) =>\n        g_plus5 (8+n) (g_plus5 (3+n) (g_plus3 n H)).\n\nTheorem and_example :\n    (beautiful 0) /\\ (beautiful 3).\nProof.\n    apply conj.\n        apply b_0.\n        apply b_3.\nQed.\n\nPrint and_example.\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.\nQed.\n\nPrint and_commut.\n\nCheck plus_comm.\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.\nQed.\n\n(* In this case giving just one argument would be sufficient *)\nLemma plus_comm_r' : forall a b c, c + (b + a) = c + (a + b).\nProof.\n    intros a b c.\n    rewrite (plus_comm b).\n    reflexivity.\nQed.\n\n(* Arguments must be given in order, but wildcards (_) may be used to\n    * skip arguments that Coq can infer *)\nLemma plus_comm_r'' : forall a b c, c + (b + a) = c + (a + b).\nProof.\n    intros a b c.\n    rewrite (plus_comm _ a).\n    reflexivity.\nQed.\n\nLemma plus_comm_r''' : forall a b c, c + (b + a) = c + (a + b).\nProof.\n    intros a b c.\n    rewrite plus_comm with (n := b).\n    reflexivity.\nQed.\n", "meta": {"author": "montekki", "repo": "sf", "sha": "f91b70058bfeca1427fd402f0be158f6c779dffe", "save_path": "github-repos/coq/montekki-sf", "path": "github-repos/coq/montekki-sf/sf-f91b70058bfeca1427fd402f0be158f6c779dffe/ProofObjects/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.6813049144351242}}
{"text": "(* sem1.v *)\n\n(**** Expressions ****)\n\n(* Integer expressions with variables *)\n\nRequire Export ZArith.\nOpen Scope Z.\n\nInductive value : Set :=\n| Val : Z -> value\n| Err : value.\n\nDefinition context := nat -> (option Z).\n\nInductive expr : Set :=\n| Cte : Z -> expr\n| Var : nat -> expr\n| Plus : expr -> expr -> expr\n| Moins : expr -> expr -> expr\n| Mult : expr -> expr -> expr\n| Div : expr -> expr -> expr.\n\nInductive eval (env : context) : expr -> value -> Prop :=\n| ECte : forall c : Z , eval env (Cte c) (Val c)\n| EVar : forall (i : nat) (v : Z), (env i) = Some v -> eval env (Var i) (Val v)\n| EVar_Err : forall (i : nat), (env i) = None -> eval env (Var i) Err\n| EPlus : forall (e1 e2 : expr) (v1 v2 v : Z),\n  eval env e1 (Val v1) -> eval env e2 (Val v2) -> v = v1 + v2 ->\n  eval env (Plus e1 e2) (Val v)\n| EPlus_Err1 : forall (e1 e2 : expr),\n  eval env e1 Err -> eval env (Plus e1 e2) Err\n| EPlus_Err2 : forall (e1 e2 : expr) (v1 : Z),\n  eval env e1 (Val v1) -> eval env e2 Err -> eval env (Plus e1 e2) Err\n| EMoins : forall (e1 e2 : expr) (v1 v2 v : Z),\n  eval env e1 (Val v1) -> eval env e2 (Val v2) -> v = v1 - v2 ->\n  eval env (Moins e1 e2) (Val v)\n| EMoins_Err1 : forall (e1 e2 : expr),\n  eval env e1 Err -> eval env (Moins e1 e2) Err\n| EMoins_Err2 : forall (e1 e2 : expr) (v1 : Z),\n  eval env e1 (Val v1) -> eval env e2 Err -> eval env (Moins e1 e2) Err\n| EMult : forall (e1 e2 : expr) (v1 v2 v : Z),\n  eval env e1 (Val v1) -> eval env e2 (Val v2) -> v = v1 * v2 ->\n  eval env (Mult e1 e2) (Val v)\n| EMult_Err1 : forall (e1 e2 : expr),\n  eval env e1 Err -> eval env (Mult e1 e2) Err\n| EMult_Err2 : forall (e1 e2 : expr) (v1 : Z),\n  eval env e1 (Val v1) -> eval env e2 Err -> eval env (Mult e1 e2) Err\n| EDiv : forall (e1 e2 : expr) (v1 v2 v : Z),\n  eval env e1 (Val v1) -> eval env e2 (Val v2) -> v = v1 / v2 ->\n  eval env (Div e1 e2) (Val v)\n| EDiv_Err1 : forall (e1 e2 : expr),\n  eval env e1 Err -> eval env (Div e1 e2) Err\n| EDiv_Err2 : forall (e1 e2 : expr) (v1 : Z),\n  eval env e1 (Val v1) -> eval env e2 Err -> eval env (Div e1 e2) Err.\n\nDefinition env0 (n : nat) : (option Z) :=\n  match n with\n  | 0%nat => Some 2\n  | _ => None\n  end.\n\nLemma eval0 : eval env0 (Plus (Var 0) (Cte 1)) (Val 3).\nProof.\n  eapply EPlus.\n  apply EVar; simpl; auto.\n  apply ECte.\n  auto.\nSave.\n\nLemma eval1 :\n  eval env0 (Mult (Plus (Cte 4) (Var 0)) (Moins (Cte 9) (Var 0))) (Val 42).\nProof.\n  eapply EMult.\n  eapply EPlus.\n  apply ECte.\n  apply EVar; simpl; auto.\n  auto.\n  eapply EMoins.\n  apply ECte.\n  apply EVar; simpl; auto.\n  auto.\n  auto.\nSave.\n\nLemma eval2 :\n  eval env0 (Mult (Plus (Cte 4) (Var 1)) (Moins (Cte 9) (Var 0))) Err.\nProof.\n  apply EMult_Err1.\n  eapply EPlus_Err2.\n  apply ECte.\n  apply EVar_Err; simpl; auto.\nSave.\n\nLtac apply_eval_val :=\n  repeat\n    eapply EPlus || eapply EMoins || eapply EMult || eapply EDiv ||\n    apply ECte || (apply EVar; simpl; auto) || auto.\n\nLtac apply_eval_err :=\n  match goal with\n  | |- eval _ (Var _) Err => apply EVar_Err; simpl; auto\n  | |- eval _ (Plus _ _) Err =>\n    (apply EPlus_Err1; apply_eval_err) ||\n    (eapply EPlus_Err2; [ apply_eval_val | apply_eval_err])\n  | |- eval _ (Moins _ _) Err =>\n    (apply EMoins_Err1; apply_eval_err) ||\n    (eapply EMoins_Err2; [ apply_eval_val | apply_eval_err])\n  | |- eval _ (Mult _ _) Err =>\n    (apply EMult_Err1; apply_eval_err) ||\n    (eapply EMult_Err2; [ apply_eval_val | apply_eval_err])\n  | |- eval _ (Div _ _) Err =>\n    (apply EDiv_Err1; apply_eval_err) ||\n    (eapply EDiv_Err2; [ apply_eval_val | apply_eval_err])\n  end.\n\nLemma eval0b : eval env0 (Plus (Var 0) (Cte 1)) (Val 3).\nProof.\n  apply_eval_val.\nSave.\n\nLemma eval1b :\n  eval env0 (Mult (Plus (Cte 4) (Var 0)) (Moins (Cte 9) (Var 0))) (Val 42).\nProof.\n  apply_eval_val.\nSave.\n\nLemma eval2b :\n  eval env0 (Mult (Plus (Cte 4) (Var 1)) (Moins (Cte 9) (Var 0))) Err.\nProof.\n  apply_eval_err.\nSave.\n\nFixpoint f_eval (env : context) (e : expr) : value :=\n  match e with\n  | Cte c => Val c\n  | Var i => \n    match (env i) with\n    | Some v => Val v\n    | None => Err\n    end\n  | Plus e1 e2 =>\n    let v1 := f_eval env e1 in\n    match v1 with\n    | Err => Err\n    | Val z1 =>\n      let v2 := f_eval env e2 in\n      match v2 with\n      | Err => Err\n      | Val z2 => Val (z1 + z2)\n      end\n    end\n  | Moins e1 e2 =>\n    let v1 := f_eval env e1 in\n    match v1 with\n    | Err => Err\n    | Val z1 =>\n      let v2 := f_eval env e2 in\n      match v2 with\n      | Err => Err\n      | Val z2 => Val (z1 - z2)\n      end\n    end\n  | Mult e1 e2 =>\n    let v1 := f_eval env e1 in\n    match v1 with\n    | Err => Err\n    | Val z1 =>\n      let v2 := f_eval env e2 in\n      match v2 with\n      | Err => Err\n      | Val z2 => Val (z1 * z2)\n      end\n    end\n  | Div e1 e2 =>\n    let v1 := f_eval env e1 in\n    match v1 with\n    | Err => Err\n    | Val z1 =>\n      let v2 := f_eval env e2 in\n      match v2 with\n      | Err => Err\n      | Val z2 => Val (z1 / z2)\n      end\n    end\n  end.\n\nLemma eval0t :  f_eval env0 (Plus (Var 0) (Cte 1)) = (Val 3).\nProof.\n  simpl; reflexivity.\nSave.\n\nLemma eval1t :\n  f_eval env0 (Mult (Plus (Cte 4) (Var 0)) (Moins (Cte 9) (Var 0))) = (Val 42).\nProof.\n  simpl; reflexivity.\nSave.\n\nLemma eval2t :\n  f_eval env0 (Mult (Plus (Cte 4) (Var 1)) (Moins (Cte 9) (Var 0))) = Err.\nProof.\n  simpl; reflexivity.\nSave.\n\nFunctional Scheme f_eval_ind := Induction for f_eval Sort Prop.\n\nTheorem f_eval_sound : forall (env : context) (e : expr) (v : value),\n  (f_eval env e) = v -> eval env e v.\nProof.\n  do 2 intro; functional induction (f_eval env e) using f_eval_ind; intros.\n  rewrite <- H; apply ECte.\n  rewrite <- H; apply EVar; auto.\n  rewrite <- H; apply EVar_Err; auto.\n  rewrite <- H;\n    apply EPlus with (v1 := z1) (v2 := z2);\n      [ apply (IHv (Val z1)); auto | apply (IHv0 (Val z2)); auto | auto ].\n  rewrite <- H;\n    apply EPlus_Err2 with (v1 := z1);\n      [ apply (IHv (Val z1)); auto | apply (IHv0 Err); auto ].\n  rewrite <- H; apply EPlus_Err1; apply (IHv Err); auto.\n  rewrite <- H;\n    apply EMoins with (v1 := z1) (v2 := z2);\n      [ apply (IHv (Val z1)); auto | apply (IHv0 (Val z2)); auto | auto ].\n  rewrite <- H;\n    apply EMoins_Err2 with (v1 := z1);\n      [ apply (IHv (Val z1)); auto | apply (IHv0 Err); auto ].\n  rewrite <- H; apply EMoins_Err1; apply (IHv Err); auto.\n  rewrite <- H;\n    apply EMult with (v1 := z1) (v2 := z2);\n      [ apply (IHv (Val z1)); auto | apply (IHv0 (Val z2)); auto | auto ].\n  rewrite <- H;\n    apply EMult_Err2 with (v1 := z1);\n      [ apply (IHv (Val z1)); auto | apply (IHv0 Err); auto ].\n  rewrite <- H; apply EMult_Err1; apply (IHv Err); auto.\n  rewrite <- H;\n    apply EDiv with (v1 := z1) (v2 := z2);\n      [ apply (IHv (Val z1)); auto | apply (IHv0 (Val z2)); auto | auto ].\n  rewrite <- H;\n    apply EDiv_Err2 with (v1 := z1);\n      [ apply (IHv (Val z1)); auto | apply (IHv0 Err); auto ].\n  rewrite <- H; apply EDiv_Err1; apply (IHv Err); 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/sem1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6811216661629576}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra.\nImport GRing.\nImport FracField.\nRequire Import q_tools.\n\nLocal Open Scope ring_scope.\n\nSection q_analogue.\nVariable (R : rcfType) (q : R).\nHypothesis Hq : q - 1 != 0.\n\nNotation \"f ** g\" := (fun x => f x * g x) (at level 40).\nNotation \"f // g\" := (fun x => f x / g x) (at level 40).\nNotation \"a */ f\" := (fun x => a * (f x)) (at level 40).\n(* q-differential *)\nDefinition dq (f : R -> R) x := f (q * x) - f x.\n\n(* q-differential product rule *)\nLemma dq_prod f g x :\n  dq (f ** g) x = (f (q * x)) * dq g x + (g x) * dq f x.\nProof.\n  rewrite /dq !mulrBr.\n  rewrite [g x * f (q * x)]mulrC.\n  by rewrite [g x * f x]mulrC subrKA.\nQed.\n\n(* q-derivative *)\nDefinition Dq f := dq f // dq id.\n\nFixpoint hoDq n f := match n with\n  | 0 => f\n  | n.+1 => Dq (hoDq n f)\n  end.\n\n(* q-derivative for const is 0 *)\nLemma Dq_const x c : Dq (fun x => c) x = 0.\nProof. by rewrite /Dq /dq addrK' mul0r. Qed.\n\n(* q-derivative is linear *)\nLemma Dq_is_linear a b f g x :\n  Dq ((a */ f) \\+ (b */ g)) x = a * (Dq f x) + b * (Dq g x).\nProof.\n  rewrite /Dq /dq !mulrA.\n  case Hx : (x == 0).\n  - move: Hx => /eqP ->.\n    by rewrite mulr0 !addrK' !mulr0 -mulrDl addr0.\n  - rewrite add_div.\n      rewrite !mulrBr opprD !addrA.\n      rewrite [a * f (q * x) + b * g (q * x) - a * f x]addrC.\n      rewrite [(a * f (q * x) + b * g (q * x))]addrC addrA.\n      rewrite [- (a * f x) + b * g (q * x) + a * f (q * x)] addrC.\n      by rewrite addrA.\n  apply denom_is_nonzero => //.\n  by rewrite Hx.\nQed.\n\n(* q-analogue of natural number *)\nDefinition qnat n : R := (q ^ n - 1) / (q - 1).\n\n(* qnat 0 is 0 *)\nLemma qnat0 : qnat 0 = 0.\nProof. by rewrite /qnat expr0z addrK' mul0r. Qed.\n\nLemma qnat1 : qnat 1 = 1.\nProof. by rewrite /qnat expr1z divff. Qed.\n\nLemma qnatE (n : nat) : qnat n.+1 = \\sum_(0 <= i < n.+1) (q ^ i).\nProof.\n  elim: n => [|n IH].\n  - by rewrite qnat1 big_nat1 expr0z.\n  - have -> : qnat n.+2 = qnat n.+1 + q ^ n.+1.\n      apply (same_prod _ (q - 1)) => //.\n      by rewrite mulrDl !denomK // mulrBr mulr1 -exprSzr [RHS]addrC subrKA.\n    by rewrite IH [RHS](@big_cat_nat _ _ _ n.+1) //= big_nat1.\nQed.\n\nLemma qnat_cat {n} j : (j < n)%N ->\n  qnat n.+1 = qnat j.+1 + q ^ j.+1 * qnat (n.+1 - j.+1)%N.\nProof.\n  move=> Hjn.\n  have Hjn' : (j < n.+1)%N by apply ltnW.\n  have Hjn'' : (0 < n.+1 - j.+1)%N.\n    by rewrite subn_gt0.\n  rewrite !qnatE (@big_cat_nat _ _ _ j.+1) //=.\n  have {2}-> : j.+1 = (0 + j.+1)%N by [].\n  rewrite big_addn.\n  have -> : (n.+1 - j.+1)%N = (n.+1 - j.+1 - 1).+1.\n    by rewrite subn1 prednK // // subn_gt0.\n  f_equal.\n  under eq_bigr do rewrite exprzD_nat.\n  by rewrite sum_distr qnatE.\nQed.\n\nLemma qnat_cat1 n : qnat n.+1 = 1 + q * qnat n.\nProof.\n  destruct n.\n  - by rewrite qnat1 qnat0 mulr0 addr0.\n  - by rewrite (qnat_cat 0) ?qnat1 ?expr1z ?subn1.\nQed.\n\nLemma qnat_catn n : qnat n.+1 = qnat n + q ^ n.\nProof.\n  destruct n.\n  - by rewrite qnat1 qnat0 add0r expr0z.\n  - by rewrite (qnat_cat n) ?subSnn ?qnat1 ?mulr1.\nQed.\n\n(* q-derivative of x ^ n *)\nLemma Dq_pow n x :\n  x != 0 -> Dq (fun x => x ^ n) x = qnat n * x ^ (n - 1).\nProof.\n  move=> Hx.\n  rewrite /Dq /dq /qnat.\n  rewrite -{4}(mul1r x) -mulrBl expfzMl -add_div; last by apply mulf_neq0.\n  rewrite [in x ^ n](_ : n = (n -1) +1) //; last by rewrite subrK.\n  rewrite expfzDr ?expr1z ?mulrA -?mulNr ?red_frac_r ?add_div //.\n  rewrite -{2}[x ^ (n - 1)]mul1r -mulrBl mulrC mulrA.\n  by rewrite [in (q - 1)^-1 * (q ^ n - 1)] mulrC.\nQed.\n\n(* q-derivative product rule *)\nLemma Dq_prod f g x : x != 0 ->\n  Dq (f ** g) x = f (q * x) * Dq g x + (g x) * Dq f x.\nProof.\n  move=> Hx.\n  rewrite /Dq dq_prod -add_div.\n    by rewrite !mulrA.\n  by apply denom_is_nonzero.\nQed.\n\n(* q-derivative product rule' *)\nLemma Dq_prod' f g x : x != 0 ->\n   Dq (f ** g) x = (f x) * Dq g x + g (q * x) * Dq f x.\nProof.\n  move=> Hx.\n  have -> : Dq (f ** g) x = Dq (g ** f) x.\n    by rewrite /Dq /dq (mulrC (f (q * x))) (mulrC (f x)).\n  by rewrite Dq_prod // addrC.\nQed.\n\n(* reduce fraction in q-derivative *)\nLemma Dq_divff f g x : g x != 0 -> g (q * x) != 0 ->\n  Dq (g ** (f // g)) x = Dq f x.\nProof.\n  move=> Hgx Hgqx.\n  rewrite /Dq /dq.\n  rewrite [f (q * x) / g (q * x)] mulrC.\n  rewrite [f x / g x] mulrC.\n  by rewrite !mulrA !divff // !mul1r.\nQed.\n\n(* q-derivative quotient rule *)\nLemma Dq_quot f g x : x != 0 -> g x != 0 -> g (q * x) != 0 ->\n  Dq (f // g) x =\n  (g x * Dq f x - f x * Dq g x) / (g x * g (q * x)).\nProof.\n  move=> Hx Hgx Hgqx.\n  rewrite -add_div.\n    rewrite red_frac_l // mulNr.\n    apply /rtransposition /(same_prod _ (g (q * x))) => //.\n    rewrite mulrDl.\n    rewrite -[f x * Dq g x / (g x * g (q * x)) * g (q * x)]\n              mulrA.\n    rewrite [(g x * g (q * x))^-1 * g (q * x)] mulrC.\n    rewrite mulrA red_frac_r //.\n    rewrite -[Dq f x / g (q * x) * g (q * x)] mulrA.\n    rewrite [(g (q * x))^-1 * g (q * x)] mulrC.\n    rewrite divff // mulr1 mulrC.\n    rewrite -[f x * Dq g x / g x] mulrA.\n    rewrite [Dq g x / g x] mulrC.\n    rewrite [f x * ((g x)^-1 * Dq g x)] mulrA.\n    rewrite -Dq_prod //.\n    by apply Dq_divff.\n  by apply mulf_neq0.\nQed.\n\n(* q-derivative quotient rule' *)\nLemma Dq_quot' f g x : x != 0 ->\n  g x != 0 -> g (q * x) != 0 ->\n  Dq (f // g) x =\n  (g (q * x) * Dq f x\n   - f (q * x) * Dq g x) / (g x * g (q * x)).\nProof.\n  move=> Hx Hgx Hgqx.\n  rewrite -add_div; last by apply mulf_neq0.\n  rewrite [g x * g (q * x)] mulrC.\n  rewrite red_frac_l // mulNr.\n  apply /rtransposition /(same_prod _ (g x)) => //.\n  rewrite mulrDl.\n  rewrite [f (q * x) * Dq g x / (g (q * x) * g x) * g x]mulrC.\n  rewrite [g (q * x) * g x]mulrC mulrA red_frac_l //.\n  rewrite -[Dq f x / g x * g x]mulrA [(g x)^-1 * g x]mulrC.\n  rewrite divff // mulr1 mulrC.\n  rewrite -[f (q * x) * Dq g x / g (q * x)]mulrA.\n  rewrite [Dq g x / g (q * x)]mulrC.\n  rewrite [f (q * x) * ((g (q * x))^-1 * Dq g x)]mulrA.\n  rewrite -Dq_prod' //.\n  by apply Dq_divff.\nQed.\n\n(* q-analogue of polynomial for nat *)\nFixpoint qbinom_pos a n x := match n with\n  | 0 => 1\n  | n.+1 => (qbinom_pos a n x) * (x - q ^ n * a)\n  end.\n\nLemma qbinom_pos_head a n x:\n   qbinom_pos a n.+1 x =\n  (x - a) * qbinom_pos (q * a) n x.\nProof.\n  elim: n => [|n IH] /=.\n  - by rewrite expr0z !mul1r mulr1.\n  - by rewrite !mulrA -IH exprSzr.\nQed.\n\nLemma qbinomxa a n : qbinom_pos a n.+1 a = 0.\nProof. by rewrite qbinom_pos_head addrK' mul0r. Qed.\n\nLemma qbinomx0 a n :\n  qbinom_pos (- a) n 0 = q ^+((n * (n - 1))./2) * a ^+ n.\nProof.\n  elim: n => [| n IH] //.\n  - by rewrite mul0n /= expr0 mulr1.\n  - destruct n.\n      by rewrite /= !mul1r sub0r opp_oppE expr1.\n    case Hq0 : (q == 0).\n    + rewrite qbinom_pos_head.\n      destruct n.\n        rewrite /= expr0z.\n        move: Hq0 => /eqP ->.\n        by rewrite opp_oppE add0r mul1r expr1 sub0r !mul0r mul1r oppr0 mulr0.\n      rewrite qbinom_pos_head.\n      move: Hq0 => /eqP ->.\n      rewrite mul0r subr0 mulrA !mulr0 !mul0r.\n      have -> : (n.+3 * (n.+3 - 1))./2 =\n                ((n.+3 * (n.+3 - 1))./2 - 1)%N.+1.\n        by rewrite -[RHS]addn1 subnK.\n      by rewrite expr0n mul0r.\n    + rewrite /= in IH.\n      rewrite [LHS] /= IH // sub0r -mulrN opp_oppE.\n      rewrite [q ^ n.+1 * a] mulrC.\n      rewrite mulrA mulrC 2!mulrA -exprD.\n      have -> : (n.+1 + (n.+1 * (n.+1 - 1))./2 =\n                (n.+2 * (n.+2 - 1))./2)%N.\n        by rewrite !subn1 /= half_add.\n      by rewrite -mulrA -(exprSzr a n.+1).\nQed.\n\n(* q-derivative of q-polynomial for nat *)\nTheorem Dq_qbinom_pos a n x : x != 0 ->\n  Dq (qbinom_pos a n.+1) x =\n  qnat n.+1 * qbinom_pos a n x.\nProof.\n  move=> Hx.\n  elim: n => [|n IH].\n  - rewrite /Dq /dq /qbinom_pos /qnat.\n    rewrite !mul1r mulr1 expr1z.\n    rewrite opprB subrKA !divff //.\n    by rewrite denom_is_nonzero.\n  - rewrite (_ : Dq (qbinom_pos a n.+2) x =\n                 Dq ((qbinom_pos a n.+1) **\n                 (fun x => (x - q ^ (n.+1) * a))) x) //.\n    rewrite Dq_prod' //.\n    rewrite [Dq (+%R^~ (- (q ^ n.+1 * a))) x]/Dq /dq.\n    rewrite opprB subrKA divff //; last by apply denom_is_nonzero.\n    rewrite mulr1 exprSz.\n    rewrite -[q * q ^ n * a]mulrA -(mulrBr q) IH.\n    rewrite -[q * (x - q ^ n * a) * (qnat n.+1 * qbinom_pos a n x)]mulrA.\n    rewrite [(x - q ^ n * a) * (qnat n.+1 * qbinom_pos a n x)]mulrC.\n    rewrite -[qnat n.+1 * qbinom_pos a n x * (x - q ^ n * a)]mulrA.\n    rewrite (_ : qbinom_pos a n x * (x - q ^ n * a) = qbinom_pos a n.+1 x) //.\n    rewrite mulrA -{1}(mul1r (qbinom_pos a n.+1 x)).\n    by rewrite -mulrDl -qnat_cat1.\nQed.\n\n(* q-polynomial exponential law for nat *)\nLemma qbinom_pos_explaw x a m n :\n  qbinom_pos a (m + n) x =\n    qbinom_pos a m x * qbinom_pos (q ^ m * a) n x.\nProof.\n  elim: n.\n  - by rewrite addn0 /= mulr1.\n  - elim => [_|n _ IH].\n    + by rewrite addnS /= addn0 expr0z !mul1r.\n    + rewrite addnS [LHS]/= IH /= !mulrA.\n      by rewrite -[q ^ n.+1 * q ^ m] expfz_n0addr // addnC.\nQed.\n\nLemma qbinom_exp_non0l x a m n :\n  qbinom_pos a (m + n) x != 0 -> qbinom_pos a m x != 0.\nProof.\n  rewrite qbinom_pos_explaw.\n  by apply mulnon0.\nQed.\n\nLemma qbinom_exp_non0r x a m n :\n  qbinom_pos a (m + n) x != 0 -> qbinom_pos (q ^ m * a) n x != 0.\nProof.\n  rewrite qbinom_pos_explaw mulrC.\n  by apply mulnon0.\nQed.\n\n(* q-polynomial for neg *)\nDefinition qbinom_neg a n x := 1 / qbinom_pos (q ^ ((Negz n) + 1) * a) n x.\n\n(* q-poly_nat 0 = q-poly_neg 0 *)\nLemma qbinom_0 a x : qbinom_neg a 0 x = qbinom_pos a 0 x.\nProof. by rewrite /qbinom_neg /= -[RHS] (@divff _ 1) ?oner_neq0. Qed.\n\nTheorem qbinom_neg_inv a n x :\n  qbinom_pos (q ^ (Negz n + 1) * a) n x != 0 ->\n  qbinom_neg a n x * qbinom_pos (q ^ (Negz n + 1) * a) n x = 1.\nProof.\n  move=> H.\n  by rewrite /qbinom_neg mulrC mulrA mulr1 divff.\nQed.\n\n(* q-analogue polynomial for int *)\nDefinition qbinom a n x :=\n  match n with\n  | Posz n0 => qbinom_pos a n0 x\n  | Negz n0 => qbinom_neg a n0.+1 x\n  end.\n\nDefinition qbinom_denom a n x :=\n match n with\n  | Posz n0 => 1\n  | Negz n0 => qbinom_pos (q ^ Negz n0 * a) n0.+1 x\n  end.\n\nLemma Dq_qbinom_int_to_neg a n x :\n  Dq (qbinom a (Negz n)) x = Dq (qbinom_neg a (n + 1)) x.\nProof. by rewrite /Dq /dq /= addn1. Qed.\n\nLemma qbinom_exp_0 a m n x : m = 0 \\/ n = 0 ->\n  qbinom a (m + n) x = qbinom a m x * qbinom (q ^ m * a) n x.\nProof.\n  move=> [->|->].\n  - by rewrite add0r expr0z /= !mul1r.\n  - by rewrite addr0 /= mulr1.\nQed.\n\nLemma qbinom_exp_pos_neg a (m n : nat) x : q != 0 ->\n  qbinom_pos (q ^ (Posz m + Negz n) * a) n.+1 x != 0 ->\n  qbinom a (Posz m + Negz n) x = qbinom a m x * qbinom (q ^ m * a) (Negz n) x.\nProof.\n  move=> Hq0 Hqbinommn.\n  case Hmn : (Posz m + Negz n) => [l|l]  /=.\n  - rewrite /qbinom_neg mul1r.\n    rewrite (_ : qbinom_pos a m x = qbinom_pos a (l + n.+1) x).\n      rewrite qbinom_pos_explaw.\n      have -> : q ^ (Negz n.+1 + 1) * (q ^ m * a) = q ^ l * a.\n        by rewrite mulrA -expfzDr // -addn1 Negz_addK addrC Hmn.\n      rewrite -{2}(mul1r (qbinom_pos (q ^ l * a) n.+1 x)) red_frac_r.\n        by rewrite divr1.\n      by rewrite -Hmn.\n    apply Negz_transp in Hmn.\n    apply (eq_int_to_nat R) in Hmn.\n    by rewrite Hmn.\n  - rewrite /qbinom_neg.\n    have Hmn' : n.+1 = (l.+1 + m)%N.\n      move /Negz_transp /esym in Hmn.\n      rewrite addrC in Hmn.\n      move /Negz_transp /(eq_int_to_nat R) in Hmn.\n      by rewrite addnC in Hmn.\n    rewrite (_ : qbinom_pos (q ^ (Negz n.+1 + 1) * (q ^ m * a)) n.+1 x \n               = qbinom_pos (q ^ (Negz n.+1 + 1) * (q ^ m * a))\n                              (l.+1 + m) x).\n      rewrite qbinom_pos_explaw.\n      have -> : q ^ (Negz n.+1 + 1) * (q ^ m * a) =\n                q ^ (Negz l.+1 + 1) * a.\n        by rewrite mulrA -expfzDr // !NegzS addrC Hmn.\n      have -> : q ^ l.+1 * (q ^ (Negz l.+1 + 1) * a) = a.\n        by rewrite mulrA -expfzDr // NegzS NegzK expr0z mul1r.\n      rewrite mulrA.\n      rewrite [qbinom_pos (q ^ (Negz l.+1 + 1) * a) l.+1 x *\n               qbinom_pos a m x]mulrC.\n      rewrite red_frac_l //.\n      have -> : a = q ^ l.+1 * (q ^ (Posz m + Negz n) * a) => //.\n        by rewrite mulrA -expfzDr // Hmn NegzK expr0z mul1r.\n      apply qbinom_exp_non0r.\n      rewrite -Hmn' //.\n    by rewrite Hmn'.\nQed.\n\nLemma qbinom_exp_neg_pos a m n x : q != 0 ->\n  qbinom_pos (q ^ Negz m * a) m.+1 x != 0 ->\n  qbinom a (Negz m + Posz n) x =\n  qbinom a (Negz m) x * qbinom (q ^ Negz m * a) n x.\nProof.\n  move=> Hq0 Hqbinomm.\n  case Hmn : (Negz m + n) => [l|l] /=.\n  - rewrite /qbinom_neg.\n    rewrite (_ : qbinom_pos (q ^ Negz m * a) n x =\n                 qbinom_pos (q ^ Negz m * a)\n                   (m.+1 + l) x).\n      rewrite qbinom_pos_explaw.\n      have -> : q ^ (Negz m.+1 + 1) * a = q ^ Negz m * a.\n        by rewrite -addn1 Negz_addK.\n      have -> : q ^ m.+1 * (q ^ Negz m * a) = a.\n        by rewrite mulrA -expfzDr // NegzK expr0z mul1r.\n      rewrite mulrC mulrA mulr1.\n      rewrite -{2}[qbinom_pos (q ^ Negz m * a) m.+1 x]mulr1.\n      rewrite red_frac_l //.\n      by rewrite divr1.\n    move: Hmn.\n    rewrite addrC.\n    move /Negz_transp /eq_int_to_nat.\n    by rewrite addnC => ->.\n  - rewrite /qbinom_neg.\n    have Hmn' : m.+1 = (n + l.+1)%N.\n      rewrite addrC in Hmn.\n      move /Negz_transp /esym in Hmn.\n      rewrite addrC in Hmn.\n      by move /Negz_transp /(eq_int_to_nat R) in Hmn.\n    rewrite {2}Hmn'.\n    rewrite qbinom_pos_explaw.\n    have -> : q ^ n * (q ^ (Negz m.+1 + 1) * a) =\n                q ^ (Negz l.+1 + 1) * a.\n      by rewrite mulrA -expfzDr // !NegzS addrC Hmn.\n    have -> : q ^ (Negz m.+1 + 1) * a = q ^ Negz m * a.\n      by rewrite NegzS.\n    rewrite [RHS] mulrC mulrA red_frac_l //.\n    apply (@qbinom_exp_non0l x _ n l.+1).\n    by rewrite -Hmn'.\nQed.\n\nLemma qbinom_exp_neg_neg a m n x : q != 0 ->\n  qbinom a (Negz m + Negz n) x =\n  qbinom a (Negz m) x * qbinom (q ^ Negz m * a) (Negz n) x .\nProof.\n  move=> Hq0 /=.\n  rewrite /qbinom_neg.\n  have -> : (m + n).+2 = ((n.+1) + (m.+1))%N.\n    by rewrite addnC addnS -addn2.\n  rewrite qbinom_pos_explaw.\n  have -> : q ^ n.+1 * (q ^ (Negz (n.+1 + m.+1) + 1) * a) =\n              q ^ (Negz m.+1 + 1) * a.\n    rewrite mulrA -expfzDr //.\n    have -> : Posz n.+1 + (Negz (n.+1 + m.+1) + 1) = Negz m.+1 + 1 => //.\n    by rewrite Negz_add 2!addrA NegzK add0r.\n  have -> : (q ^ (Negz n.+1 + 1) * (q ^ Negz m * a)) =\n              (q ^ (Negz (n.+1 + m.+1) + 1) * a).\n    by rewrite mulrA -expfzDr // NegzS -Negz_add addnS NegzS.\n  rewrite mulf_div mulr1.\n  by rewrite [qbinom_pos (q ^ (Negz (n.+1 + m.+1) + 1) * a) n.+1 x *\n            qbinom_pos (q ^ (Negz m.+1 + 1) * a) m.+1 x] mulrC.\nQed.\n\nTheorem qbinom_explaw a m n x : q != 0 ->\n  qbinom_denom a m x != 0 ->\n  qbinom_denom (q ^ m * a) n x != 0 ->\n  qbinom a (m + n) x = qbinom a m x * qbinom (q ^ m * a) n x.\nProof.\n  move=> Hq0.\n  case: m => m Hm.\n  - case: n => n Hn.\n    + by apply qbinom_pos_explaw.\n    + rewrite qbinom_exp_pos_neg //.\n      by rewrite addrC expfzDr // -mulrA.\n  - case: n => n Hn.\n    + by rewrite qbinom_exp_neg_pos.\n    + by apply qbinom_exp_neg_neg.\nQed.\n\n(* q-derivative of q-polynomial for 0 *)\nLemma Dq_qbinomn0 a x :\n  Dq (qbinom a 0) x = qnat 0 * qbinom a (- 1) x.\nProof. by rewrite Dq_const qnat0 mul0r. Qed.\n\nLemma qbinom_qx a m n x : q != 0 ->\n  qbinom_pos (q ^ m * a) n (q * x) =\n    q ^ n * qbinom_pos (q ^ (m - 1) * a) n x.\nProof.\n  move=> Hq0.\n  elim: n => [|n IH] /=.\n  - by rewrite expr0z mul1r.\n  - rewrite IH.\n    rewrite exprSzr -[RHS]mulrA.\n    rewrite [q * (qbinom_pos (q ^ (m - 1) * a) n x *\n              (x - q ^ n * (q ^ (m - 1) * a)))]mulrA.\n    rewrite [q * qbinom_pos (q ^ (m - 1) * a) n x]mulrC.\n    rewrite -[qbinom_pos (q ^ (m - 1) * a) n x * q *\n               (x - q ^ n * (q ^ (m - 1) * a))]mulrA.\n    rewrite [q * (x - q ^ n * (q ^ (m - 1) * a))]mulrBr.\n    rewrite [q * (q ^ n * (q ^ (m - 1) * a))]mulrA.\n    rewrite [q * q ^ n]mulrC.\n    rewrite -[q ^ n * q * (q ^ (m - 1) * a)]mulrA.\n    rewrite (_ : q * (q ^ (m - 1) * a) = q ^ m * a).\n      by rewrite [RHS] mulrA.\n    by rewrite mulrA -{1}(expr1z q) -expfzDr // addrC subrK.\nQed.\n\n(* q-derivative of q-polynomial for neg *)\nTheorem Dq_qbinom_neg a n x : q != 0 -> x != 0 ->\n  (x - q ^ (Negz n) * a) != 0 ->\n  qbinom_pos (q ^ (Negz n + 1) * a) n x != 0 ->\n  Dq (qbinom_neg a n) x = qnat (Negz n + 1) * qbinom_neg a (n.+1) x.\nProof.\n  move=> Hq0 Hx Hqn Hqbinom.\n  destruct n.\n  - by rewrite /Dq /dq /qbinom_neg /= addrK' qnat0 !mul0r.\n  - rewrite Dq_quot //.\n      rewrite Dq_const mulr0 mul1r sub0r.\n      rewrite Dq_qbinom_pos // qbinom_qx // -mulNr.\n      rewrite [qbinom_pos (q ^ (Negz n.+1 + 1) * a) n.+1 x *\n                (q ^ n.+1 * qbinom_pos (q ^ (Negz n.+1 + 1 - 1) *\n                  a) n.+1 x)] mulrC.\n      rewrite -mulf_div.\n      have -> : qbinom_pos (q ^ (Negz n.+1 + 1) * a) n x /\n                    qbinom_pos (q ^ (Negz n.+1 + 1) * a) n.+1 x =\n                      1 / (x - q ^ (- 1) * a).\n        rewrite -(mulr1 (qbinom_pos (q ^ (Negz n.+1 + 1) * a) n x)) /=.\n        rewrite red_frac_l.\n          rewrite NegzE mulrA -expfzDr // addrA -addn2.\n          rewrite (_ : Posz (n + 2)%N = Posz n + 2) //.\n          by rewrite -{1}(add0r (Posz n)) addrKA.\n        by rewrite /=; apply mulnon0 in Hqbinom.\n      rewrite mulf_div.\n      rewrite -[q ^ n.+1 *\n                 qbinom_pos (q ^ (Negz n.+1 + 1 - 1) * a) n.+1 x *\n                   (x - q ^ (-1) * a)]mulrA.\n      have -> : qbinom_pos (q ^ (Negz n.+1 + 1 - 1) * a) n.+1 x *\n                (x - q ^ (-1) * a) =\n                qbinom_pos (q ^ (Negz (n.+1)) * a) n.+2 x => /=.\n        have -> : Negz n.+1 + 1 - 1 = Negz n.+1.\n          by rewrite addrK.\n        have -> : q ^ n.+1 * (q ^ Negz n.+1 * a) = q ^ (-1) * a => //.\n        rewrite mulrA -expfzDr // NegzE.\n        have -> : Posz n.+1 - Posz n.+2 = - 1 => //.\n        rewrite -addn1 -[(n + 1).+1]addn1.\n        rewrite (_ : Posz (n + 1)%N = Posz n + 1) //.\n        rewrite (_ : Posz (n + 1 + 1)%N = Posz n + 1 + 1) //.\n        rewrite -(add0r (Posz n + 1)).\n        by rewrite addrKA.\n      rewrite /qbinom_neg /=.\n      rewrite (_ : Negz n.+2 + 1 = Negz n.+1) // -mulf_div.\n      congr (_ * _).\n      rewrite NegzE mulrC /qnat -mulNr mulrA.\n      congr (_ / _).\n      rewrite opprB mulrBr mulr1 mulrC divff; last by rewrite expnon0.\n      rewrite invr_expz (_ : - Posz n.+2 + 1 = - Posz n.+1) //.\n      rewrite -addn1 (_ : Posz (n.+1 + 1)%N = Posz n.+1 + 1) //.\n      by rewrite addrC [Posz n.+1 + 1]addrC -{1}(add0r 1) addrKA sub0r.\n    rewrite qbinom_qx // mulf_neq0 ?expnon0 //.\n    rewrite qbinom_pos_head mulf_neq0 //.\n    rewrite (_ : Negz n.+1 + 1 - 1 = Negz n.+1) ?addrK //.\n    move: Hqbinom => /=.\n    move/mulnon0.\n    by rewrite addrK mulrA -{2}(expr1z q) -expfzDr.\nQed.\n\nTheorem Dq_qbinom a n x : q != 0 -> x != 0 ->\n  x - q ^ (n - 1) * a != 0 ->\n  qbinom (q ^ n * a) (- n) x != 0 ->\n  Dq (qbinom a n) x = qnat n * qbinom a (n - 1) x.\nProof.\n  move=> Hq0 Hx Hxqa Hqbinom.\n  case: n Hxqa Hqbinom => [|/=] n Hxqa Hqbinom.\n  - destruct n.\n    + by rewrite Dq_qbinomn0.\n    + rewrite Dq_qbinom_pos //.\n      rewrite (_ : Posz n.+1 - 1 = n) // -addn1.\n      by rewrite (_ : Posz (n + 1)%N = Posz n + 1) ?addrK.\n  - rewrite Dq_qbinom_int_to_neg Dq_qbinom_neg //.\n        rewrite Negz_addK.\n        rewrite (_ : (n + 1).+1 = (n + 0).+2) //.\n        by rewrite addn0 addn1.\n      rewrite (_ : Negz (n + 1) = Negz n - 1) //.\n      by apply itransposition; rewrite Negz_addK.\n    by rewrite Negz_addK addn1.\nQed.\n\nFixpoint qfact n := match n with\n  | 0 => 1\n  | n.+1 => qfact n * qnat n.+1\n  end.\n\nLemma qfact_nat_non0 n : qfact n.+1 != 0 -> qnat n.+1 != 0.\nProof.\n  rewrite /= mulrC.\n  by apply mulnon0.\nQed.\n\nLemma qfact_lenon0 m n : qfact (m + n) != 0 -> qfact m != 0.\nProof.\n  elim: n => [|n IH].\n  - by rewrite addn0.\n  - rewrite addnS /=.\n    move/ mulnon0.\n    apply IH.\nQed.\n\n(* Lemma qfact_non0 n : qfact n != 0.\nProof.\n  elim: n => [|n IH] //=.\n  - by apply oner_neq0.\n  - Search (_ * _ != 0).\n    apply mulf_neq0 => //.\nAdmitted. *)\n\nDefinition qbicoef n j :=\n  qfact n / (qfact j * qfact (n - j)).\n\nLemma qbicoefn0 n : qfact n != 0 -> qbicoef n 0 = 1.\nProof.\nmove=> H.\nby rewrite /qbicoef /= mul1r subn0 divff.\nQed.\n\nLemma qbicoefnn n : qfact n != 0 -> qbicoef n n = 1.\nProof.\n  move=> H.\n  rewrite /qbicoef.\n  by rewrite -{3}(addn0 n) addKn /= mulr1 divff.\nQed.\n\n(* Lemma qfact1 n : (n <= 0)%N -> qfact n = 1.\nProof.\n  move=> Hn.\n  have -> : (n = 0)%N => //.\n  apply /eqP.\n  by rewrite -(subn0 n) subn_eq0 //. \nQed. *)\n\n(*Lemma qbicoef_jn n j : (n - j <= 0)%N ->\n  q_coef n j = qfact n / qfact j.\nProof.\n  move=> Hjn.\n  rewrite /q_coef.\n  by rewrite (qfact1 (n - j)%N) // mulr1.\nQed. *)\n\n(* Lemma qfact_jn n j : (n - j <= 0)%N ->\n  qfact j = qfact (n - (n - j)).\nProof.\nQed. *)\n\nLemma qbicoef_compute n j : qfact n != 0 -> (j < n)%N ->\n  qbicoef n j * qfact j * qnat (n - j.+1).+1 =\n  qbicoef n j.+1 * (qfact j * qnat j.+1).\nProof.\nmove=> Hfact Hj.\n  rewrite (mulrC (qbicoef n j)) -mulrA mulrC (mulrC (qfact j)) [RHS]mulrA.\n  f_equal.\n  rewrite /qbicoef -mulrA -[RHS]mulrA.\n  f_equal => /=.\n  rewrite mulrC subnSK //.\n  have -> : qfact (n - j) = qfact (n - j.+1) * qnat (n - j)%N.\n    by rewrite -(subnSK Hj) /=.\n  rewrite mulrA -{1}(mul1r (qnat (n - j)%N)) red_frac_r; last first.\n    rewrite -(subnSK Hj).\n    apply /qfact_nat_non0 /(qfact_lenon0 _ j).\n    rewrite subnSK ?subnK //.\n    by apply ltnW.\n  rewrite [RHS]mulrC [qfact j * qnat j.+1]mulrC -{1}(mulr1 (qnat j.+1)).\n  rewrite -[qnat j.+1 * qfact j * qfact (n - j.+1)]mulrA red_frac_l //.\n  apply /qfact_nat_non0 /(qfact_lenon0 _ (n - j.+1)%N).\n  by rewrite subnKC.\nQed.\n\nLemma qbicoefE n j : (j <= n)%N ->\n  qbicoef n (n - j) = qbicoef n j.\nProof.\n  move=> Hjn.\n  rewrite /qbicoef.\n  rewrite subKn //.\n  by rewrite [qfact (n - j) * qfact j] mulrC.\nQed.\n\nLemma q_pascal n j : (j < n)%N ->\n  qfact j.+1 != 0 ->\n  qfact (n - j) != 0 ->\n  qbicoef n.+1 j.+1 = qbicoef n j +\n                 q ^ j.+1 * qbicoef n j.+1.\nProof.\n  move=> Hjn Hj0 Hnj0.\n  rewrite [LHS] /qbicoef [qfact n.+1] /= (qnat_cat j) // mulrDr -add_div.\n    have -> : qfact n * qnat j.+1 / (qfact j.+1 * qfact (n.+1 - j.+1)) =\n              qbicoef n j.\n      rewrite -mulrA -(mul1r (qnat j.+1)).\n      rewrite [qfact j.+1 * qfact (n.+1 - j.+1)] mulrC /=.\n      rewrite [qfact (n.+1 - j.+1) * (qfact j * qnat j.+1)] mulrA.\n      rewrite red_frac_r //.\n        rewrite mul1r subSS.\n        by rewrite [qfact (n - j) * qfact j] mulrC.\n      by apply qfact_nat_non0.\n    rewrite mulrA [qfact n * q ^ j.+1]mulrC subSS -subnSK //.\n    rewrite [qfact (n - j.+1).+1] /= mulrA red_frac_r.\n      by rewrite mulrA.\n    apply qfact_nat_non0.\n    rewrite subnSK //.\n  by apply mulf_neq0.\nQed.\n\nFixpoint hoD {A} D n (f : A) := match n with\n  | 0 => f\n  | n.+1 => D (hoD D n f)\n  end.\n\nNotation \"D \\^ n\" := (hoD D n) (at level 49).\n\nDefinition islinear (D : {poly R} -> {poly R}) :=\n  forall a b f g, D ((a *: f) + (b *: g)) = a *: D f + b *: D g.\n\nLemma linear_add D f g : islinear D -> D (f + g) = D f + D g.\nProof.\n  move=> HlD.\n  by rewrite -(scale1r f) -(scale1r g) HlD !scale1r.\nQed.\n\nLemma linear0 D : islinear D -> D 0 = 0.\nProof.\n  move=> HlD.\n  by rewrite -(addr0 0) -(scale0r 0%:P) HlD !scale0r.\nQed.\n\nLemma nth_islinear D n : islinear D -> islinear (D \\^ n).\nProof.\n  elim: n => [|n IH] //=.\n  move=> HlD a b f g.\n  by rewrite IH.\nQed.\n\nLemma linear_distr D n c F : islinear D ->\n  D (\\sum_(0 <= i < n.+1) c i *: F i) = \\sum_(0 <= i < n.+1) c i *: D (F i).\nProof.\n  move=> HlD.\n  elim: n => [|n IH].\n  - rewrite !big_nat1.\n    have -> : c 0%N *: F 0%N = c 0%N *: F 0%N + 0 *: 0%:P.\n      by rewrite scale0r addr0.\n    by rewrite HlD scale0r addr0.\n  - rewrite (@big_cat_nat _ _ _ n.+1) //= big_nat1.\n    rewrite -(scale1r (\\sum_(0 <= i < n.+1) c i *: F i)).\n    rewrite HlD scale1r IH.\n    by rewrite [RHS](@big_cat_nat _ _ _ n.+1) //= big_nat1.\nQed.\n\nLemma linear_distr' D j n c F : islinear D -> (j < n)%N ->\n  D (\\sum_(j.+1 <= i < n.+1) c i *: F i) =\n  \\sum_(j.+1 <= i < n.+1) c i *: D (F i).\nProof.\n  move=> HlD Hjn.\n  have Hjn' : (j < n.+1)%N.\n    by apply ltnW.\n  move: (linear_distr D n c F HlD).\n  rewrite (@big_cat_nat _ _ _ j.+1) //=.\n  rewrite linear_add // linear_distr //.\n  rewrite (@big_cat_nat _ _ _ j.+1 0 n.+1) //=.\n  by move /same_addl.\nQed.\n\nDefinition isfderiv D (P : nat -> {poly R}) := forall n,\n  match n with\n  | 0 => (D (P n)) = 0\n  | n.+1 => (D (P n.+1)) = P n\n  end.\n\nLemma poly_basis n (P : nat -> {poly R}) (f : {poly R}) :\n  (forall m, size (P m) = m.+1) ->\n  (size f <= n.+1)%N ->\n  exists (c : nat -> R), f = \\sum_(0 <= i < n.+1)\n          c i *: P i.\nProof.\n  elim: n.+1 f => {n} [|n IH] f HP Hf //=.\n  - exists (fun i => 0).\n    rewrite big_nil.\n    move: Hf.\n    by rewrite leqn0 -/(nilp f) nil_poly => /eqP.\n  - set cn := f`_n / (P n)`_n.\n    set f' := f - cn *: P n.\n    destruct (IH f') as [c Hc] => //.\n      have Hf' : (size f' <= n.+1)%N.\n        rewrite /f' -scaleNr.\n        move: (size_add f (- cn *: P n)).\n        rewrite leq_max.\n        move /orP => [H1 | H2].\n        + by apply (leq_trans H1 Hf).\n        + move: (size_scale_leq (- cn) (P n)).\n          move: (HP n) -> => HP'.\n          by apply (leq_trans H2 HP').\n      have Hf'n : f'`_n = 0.\n        rewrite /f' /cn coefB coefZ denomK ?addrK' //.\n        have {2}-> : n = n.+1.-1 by [].\n        move: (HP n) <-.\n        rewrite -lead_coefE.\n        case H : (lead_coef (P n) == 0) => //.\n        move: H.\n        rewrite lead_coef_eq0 -size_poly_eq0.\n        by move: (HP n) ->.\n      move /leq_sizeP in Hf'.\n      have Hf'' : forall j : nat, (n <= j)%N -> f'`_j = 0.\n        move=> j.\n        rewrite leq_eqVlt.\n        move/orP => [/eqP <-|] //.\n        by apply Hf'.\n      by apply /leq_sizeP.\n    exists (fun i => if i == n then cn else c i).\n    rewrite big_nat_recr //=.\n    under eq_big_nat => i /andP [_].\n      rewrite ltn_neqAle => /andP [/negbTE ] -> _.\n    over.\n    by rewrite -Hc eqxx /f' subrK.\nQed.\n\nLemma nthisfderiv_pos j D P : isfderiv D P ->\n  forall i, (i >= j)%N -> (D \\^ j) (P i) = P (i - j)%N.\nProof.\n  move=> Hd i.\n  elim: j => [|j IH] Hij //=.\n  - by rewrite subn0.\n  - rewrite IH.\n      have -> : (i - j)%N = (i - j.+1)%N.+1.\n        rewrite -subSn // subSS.\n      by apply (Hd _.+1).\n    by apply ltnW.\nQed.\n\nLemma nthisfderiv_0 j D P : islinear D -> isfderiv D P ->\n  forall i, (i < j)%N -> (D \\^ j) (P i) = 0.\nProof.\n  move=> HlD Hd i.\n  elim: j => [|j IH] Hij //=.\n  case Hij' : (i == j).\n  - move: (Hij') => /eqP ->.\n    rewrite nthisfderiv_pos // subnn.\n    by apply (Hd 0%N).\n  - have Hij'' : (i < j)%N.\n      rewrite ltn_neqAle.\n      apply /andP; split.\n      + by rewrite Hij'.\n      + by rewrite -ltnS.\n    by rewrite IH // linear0.\nQed.\n\nTheorem general_Taylor D n P (f : {poly R}) a :\n  islinear D -> isfderiv D P ->\n  (P 0%N).[a] = 1 ->\n  (forall n, (P n.+1).[a] = 0) ->\n  (forall m, size (P m) = m.+1) ->\n  size f = n.+1 ->\n  f = \\sum_(0 <= i < n.+1)\n          ((D \\^ i) f).[a] *: P i.\nProof.\n  move=> Hl Hd HP0 HP HdP Hdf.\n  have Hdf' : (size f <= n.+1)%N.\n    by rewrite Hdf leqnn.\n  move: (poly_basis n P f HdP Hdf') => [c] Hf.\n  have Hc0 : c 0%N = ((D \\^ 0) f).[a] => /=.\n    rewrite Hf.\n    destruct n.\n      by rewrite big_nat1 hornerZ HP0 mulr1.\n    rewrite hornersumD.\n    rewrite (@big_cat_nat _ _ _ 1) //= big_nat1.\n    rewrite hornerZ HP0 mulr1.\n    have -> : (1 = 0 + 1)%N by [].\n    rewrite big_addn subn1 /=.\n    under eq_big_nat => i /andP [_ _].\n      rewrite hornerZ addn1 HP mulr0.\n    over.\n    by rewrite big1 // addr0.\n  have ithD : forall j, (j.+1 <= n)%N ->\n    (D \\^ j.+1) f = \\sum_(j.+1 <= i < n.+1) c i *: P (i - j.+1)%N.\n    move=> j Hj.\n    rewrite Hf linear_distr; last by apply nth_islinear.\n    rewrite {1}(lock j.+1).\n    rewrite (@big_cat_nat _ _ _ j.+1) //=; last by apply leqW.\n    rewrite -lock.\n    under eq_big_nat => i /andP [_ Hi].\n      rewrite nthisfderiv_0 // scaler0.\n    over.\n    rewrite big1 // add0r.\n    by under eq_big_nat => i /andP [Hi _] do rewrite nthisfderiv_pos //.\n  have coef : forall j, (j <= n)%N -> c j = ((D \\^ j) f).[a].\n    move=> j Hj.\n    destruct j => //.\n    rewrite ithD //.\n    rewrite (@big_cat_nat _ _ _ j.+2) //= big_nat1 hornerD.\n    rewrite subnn hornerZ HP0 mulr1 hornersumD.\n    under eq_big_nat => i /andP [Hi Hi'].\n      rewrite hornerZ.\n      move: (Hi).\n      rewrite -addn1 -leq_subRL //; last by apply ltnW.\n      case: (i - j.+1)%N => // k Hk.\n      rewrite HP mulr0.\n    over.\n    by rewrite big1 // addr0.\n  rewrite {1}Hf big_nat_cond [RHS]big_nat_cond.\n  apply eq_bigr => i /andP [/andP [Hi Hi'] _].\n  by rewrite coef.\nQed.\n\nDefinition ap_op_poly (D : (R -> R) -> (R -> R)) (p : {poly R}) :=\n  D (fun (x : R) => p.[x]).\n\nNotation \"D # p\" := (ap_op_poly D p) (at level 49).\n\nDefinition scale_var (p : {poly R}):= \\poly_(i < size p) (q ^ i * p`_i).\n\nLemma scale_var_scale a p : scale_var (a *: p) = a *: scale_var p.\nProof.\n  rewrite /scale_var; apply polyP => j.\n  case Ha : (a == 0).\n  - move/eqP : Ha ->; rewrite !scale0r.\n    by rewrite coef_poly size_poly0 //= coef0.\n  - have Ha' : a != 0 by rewrite Ha.\n    rewrite size_scale // coefZ !coef_poly.\n    case : (j < size p)%N; last by rewrite mulr0.\n    by rewrite scalerAr'.\nQed.\n\nLemma scale_varC c : scale_var c%:P = c%:P.\nProof.\n  rewrite /scale_var poly_def.\n  rewrite (sumW _ (fun i => (q ^ i * c%:P`_i) *: 'X^i)) size_polyC.\n  case Hc : (c == 0) => /=.\n  - rewrite big_nil.\n    by move /eqP : Hc ->.\n  - by rewrite big_nat1 expr0z mul1r coefC /= -mul_polyC mulr1.\nQed.\n\nLemma scale_var_add p p' : scale_var (p + p') = scale_var p + scale_var p'.\nProof.\n  rewrite /scale_var.\n  rewrite (polyW' R (p + p') (maxn (size p) (size p'))); last by apply size_add.\n  rewrite (polyW' R p (maxn (size p) (size p'))); last by apply leq_maxl.\n  rewrite (polyW' R p' (maxn (size p) (size p'))); last by apply leq_maxr.\n  rewrite sum_add.\n  by under eq_bigr do rewrite coefD mulrDr scalerDl.\nQed.\n\nLemma scale_var_prodX p : scale_var ('X * p) = scale_var 'X * scale_var p.\nProof.\n  case Hp : (p == 0).\n    move /eqP : Hp ->.\n    by rewrite mulr0 scale_varC mulr0.\n  rewrite /scale_var !poly_def.\n  rewrite (sumW _ (fun i => (q ^ i * ('X * p)`_i) *: 'X^i)).\n  rewrite (sumW _ (fun i => (q ^ i * 'X`_i) *: 'X^i)).\n  rewrite (sumW _ (fun i => (q ^ i * p`_i) *: 'X^i)).\n  rewrite size_polyX.\n  rewrite (@big_cat_nat  _ _ _ 1 _ 2) //= !big_nat1.\n  rewrite !coefX /= mulr0 scale0r add0r expr1z mulr1.\n  rewrite -sum_distr.\n  have -> : size ('X * p) = (size p).+1.\n    by rewrite mulrC size_mulX ?Hp.\n  rewrite (@big_cat_nat _ _ _ 1) //= !big_nat1.\n  rewrite coefXM /= mulr0 scale0r add0r.\n  have -> : (1 = 0 + 1)%N by [].\n  rewrite big_addn subn1 /=.\n  under eq_big_nat => i /andP [] _ Hi.\n    rewrite coefXM addn1 /= exprSzr -mulrA [q * p`_i]mulrC mulrA.\n    rewrite -scalerA exprSr scalerAr -{2}(expr1 'X) -(add0n 1%N) scalerAl.\n  over.\n  done.\nQed.\n\nLemma scale_var_prod (p p' : {poly R}) :\n  scale_var (p * p') = scale_var p * scale_var p'.\nProof.\n  pose n := size p.\n  have : (size p <= n)%N by [].\n  clearbody n.\n  have Hp0 : forall (p : {poly R}), size p = 0%N ->\n    scale_var (p * p') = scale_var p * scale_var p'.\n    move=> p0 /eqP.\n    rewrite size_poly_eq0.\n    move/eqP ->.\n    by rewrite mul0r scale_varC mul0r.\n  elim: n p => [|n IH] p Hsize.\n    move: Hsize.\n    rewrite leqn0 => /eqP.\n    by apply Hp0.\n  case Hp : (size p == 0%N).\n    rewrite Hp0 //.\n    by apply/eqP.\n  have -> : p = p - (p`_0)%:P + (p`_0)%:P by rewrite subrK.\n  set p1 := (\\poly_(i < (size p).-1) p`_i.+1).\n  have -> : p - (p`_0)%:P = 'X * p1.\n    rewrite -{1}(coefK p) poly_def.\n    rewrite (sumW _ (fun i => p`_i *: 'X^i)).\n    rewrite (@big_cat_nat _ _ _ 1) //=; last by apply neq0_lt0n.\n    rewrite big_nat1 -mul_polyC mulr1 (addrC (p`_0)%:P) addrK.\n    have -> : (1 = 0 + 1)%N by [].\n    rewrite big_addn subn1.\n    under eq_bigr do rewrite addn1 exprSr scalerAl.\n    by rewrite sum_distr /p1 poly_def -sumW.\n  rewrite mulrDl [LHS]scale_var_add mul_polyC scale_var_scale -mulrA scale_var_prodX.\n  have -> : scale_var (p1 * p') = scale_var p1 * scale_var p'.\n    rewrite IH //.\n    apply (@leq_trans (size p).-1).\n      apply size_poly.\n    rewrite -(leq_add2r 1).\n    have -> : ((size p).-1 + 1 = size p)%N.\n      rewrite addn1 prednK //.\n      by apply neq0_lt0n.\n    by rewrite addn1.\n  by rewrite mulrA -scale_var_prodX -mul_polyC -mulrDl -{1}scale_varC -scale_var_add.\nQed.\n\nLemma scale_varX a : scale_var ('X - a%:P) = q *: 'X - a%:P.\nProof.\n  rewrite /scale_var poly_def size_XsubC.\n  rewrite (sumW _ (fun i => (q ^ i * ('X - a%:P)`_i) *: 'X^i)).\n  rewrite (@big_cat_nat _ _ _ 1) //= !big_nat1.\n  rewrite addrC expr1z expr0z !coefB !coefX !coefC /=.\n  by rewrite subr0 sub0r mulrN mulr1 mul1r scale_constpoly mulr1 polyCN.\nQed.\n\nLemma scale_varXn n : scale_var ('X ^+ n) = (q ^ n) *: 'X ^+ n.\nProof.\n  rewrite /scale_var poly_def size_polyXn.\n  rewrite (sumW _ (fun i => (q ^ i * 'X^n`_i) *: 'X^i)).\n  rewrite (@big_cat_nat _ _ _ n) //= big_nat1 coefXn.\n  have -> : (eq_op n n) => //=.\n  rewrite mulr1.\n  under eq_big_nat => i /andP [] _ Hi.\n    rewrite coefXn.\n    have -> : (eq_op i n) = false => /=.\n    by apply ltn_eqF.\n    rewrite -mul_polyC mulr0 polyC0 mul0r.\n  over.\n  by rewrite big1 ?add0r.\nQed.\n\nDefinition dqp p := scale_var p - p.\n\nLemma dqppXE p : dqp p = 'X * \\poly_(i < size p) ((q ^ i.+1 - 1) * p`_i.+1).\nProof.\n  rewrite /dqp /scale_var.\n  rewrite -{3}(coefK p).\n  rewrite !poly_def.\n  rewrite (sumW _ (fun i => (q ^ i * p`_i) *: 'X^i)).\n  rewrite (sumW _ (fun i => (p`_i *: 'X^i))).\n  rewrite (sumW _ (fun i => (((q ^ i.+1 - 1) * p`_i.+1) *: 'X^i))).\n  rewrite sum_sub.\n  case Hsize : (size p == 0%N).\n  - move /eqP : Hsize ->.\n    by rewrite !big_nil mulr0.\n  - rewrite (@big_cat_nat _ _ _ 1) //=; last by apply size_N0_lt.\n    rewrite big_nat1 expr0z mul1r addrK' add0r.\n    have -> : (1 = 0 + 1)%N by [].\n    rewrite big_addn -sum_distr.\n    rewrite [RHS](@big_cat_nat _ _ _ (size p - 1)) //=; last by rewrite subn1 leq_pred.\n    have {4}-> : size p = ((size p) - 1).+1.\n      rewrite subn1 prednK //.\n      by apply size_N0_lt.\n    rewrite big_nat1.\n    have -> : p`_(size p - 1).+1 = 0.\n      rewrite subn1 prednK //.\n        by apply /(leq_sizeP _ (size p)) => //=.\n      by apply size_N0_lt.\n    rewrite mulr0 scale0r mul0r addr0.\n    under eq_bigr => i _.\n      rewrite -scalerBl addn1 -{2}(mul1r p`_i.+1) -mulrBl exprSr scalerAl.\n    over.\n    by move=> /=.\nQed.\n\nLemma dqp_prod' p p' : dqp (p * p') = p * dqp p' + scale_var p' * dqp p.\nProof.\n  rewrite /dqp.\n  rewrite scale_var_prod // !mulrBr [RHS]addrC addrA.\n  f_equal.\n  rewrite -addrA [- (scale_var p' * p) + p * scale_var p']addrC.\n  by rewrite [p * scale_var p']mulrC addrK' addr0 mulrC.\nQed.\n\nLemma dqpXE : dqp 'X = (q - 1) *: 'X.\nProof.\n  rewrite /dqp /scale_var.\n  rewrite poly_def size_polyX.\n  rewrite (sumW _ (fun i => (q ^ i * 'X`_i) *: 'X^i)).\n  rewrite (@big_cat_nat _ _ _ 1) //= !big_nat1.\n  rewrite !coefX /=.\n  by rewrite mulr0 scale0r add0r expr1z mulr1 scalerBl scale1r.\nQed.\n\nLemma dqp_dqE p x : (dqp p).[x] = (dq # p) x.\nProof.\n  rewrite /dqp /scale_var /(_ # _) /dq.\n  rewrite hornerD hornerN.\n  f_equal.\n  rewrite -{3}(coefK p).\n  rewrite !horner_poly.\n  have -> : \\sum_(i < size p) q ^ i * p`_i * x ^+ i =\n            \\sum_(0 <= i < size p) q ^ i * p`_i * x ^+ i.\n    by rewrite big_mkord.\n  rewrite (sumW _ (fun i => p`_i * (q * x) ^+ i)).\n  apply esym.\n  under eq_big_nat => i /andP [] Hi _.\n    rewrite exprMn_comm ?mulrA ?[p`_i * q ^+ i]mulrC.\n  over.\n    by rewrite /GRing.comm mulrC.\n  done.\nQed.\n\nDefinition Dqp p := dqp p %/ dqp 'X.\n\nLemma Dqp_ok p : dqp 'X %| dqp p.\nProof. by rewrite dqpXE dvdpZl ?dqppXE ?dvdp_mulIl. Qed.\n\nLocal Notation tofrac := (@tofrac [idomainType of {poly R}]).\nLocal Notation \"x %:F\" := (tofrac x).\n\nTheorem Dqp_ok_frac p : (dqp p)%:F / (dqp 'X)%:F = (Dqp p)%:F.\nProof.\nLocate tofrac_eq.\n  have Hn0 : (dqp 'X)%:F != 0.\n    rewrite tofrac_eq dqpXE lreg_polyZ_eq0 ?polyX_eq0 //.\n    rewrite /(GRing.lreg) /(injective) => x y.\n    rewrite mulrC (mulrC (q - 1)).\n    by apply same_prod.\n  apply (frac_same_prod _ _ _ (dqp 'X)%:F) => //.\n  rewrite [LHS]mulC mulA (mulC ((dqp 'X))%:F) -mulA.\n  rewrite (mulC ((dqp 'X))%:F) mulV_l // mulC mul1_l.\n  rewrite /(Dqp) -tofracM.\n  apply /eqP.\n  rewrite tofrac_eq.\n  apply /eqP.\n  by rewrite divpK ?Dqp_ok.\nQed.\n\nLemma DqpE' p : Dqp p = dqp p %/ ((q - 1) *: 'X).\nProof. by rewrite /Dqp dqpXE. Qed.\n\nLemma Dqp_prod' p p' : Dqp (p * p') = p * Dqp p' + scale_var p' * Dqp p.\nProof.\n  rewrite /Dqp !divp_mulA ?Dqp_ok //.\n  by rewrite -divpD dqp_prod'.\nQed.\n\nLemma Dqp_const c : Dqp c%:P = 0%:P.\nProof.\n  rewrite /Dqp.\n  have -> : dqp c%:P = 0.\n    rewrite /dqp /scale_var poly_def size_polyC.\n    rewrite (sumW _ (fun i => (q ^ i * c%:P`_i) *: 'X^i)).\n    case Hc : (c != 0) => /=.\n    - rewrite big_nat1.\n      rewrite expr0z mul1r.\n      have -> : 'X^0 = 1%:P by [].\n      by rewrite coefC /= polyC1 alg_polyC addrK'.\n    - rewrite big_nil.\n      move: Hc.\n      rewrite /(_ != 0) /=.\n      case Hc : (c == 0) => //= _.\n      move/ eqP : Hc ->.\n      by rewrite polyC0 subr0.\n    by rewrite div0p.\nQed.\n\nDefinition Dqp' (p : {poly R}) := \\poly_(i < size p) (qnat (i.+1) * p`_i.+1).\n\nLemma Dqp_Dqp'E p : Dqp p = Dqp' p.\nProof.\n  case Hsize : (size p == 0%N).\n  - move: Hsize.\n    rewrite size_poly_eq0 => /eqP ->.\n    rewrite Dqp_const.\n    rewrite /Dqp' poly_def.\n    rewrite (sumW _ (fun i => (qnat i.+1 * 0%:P`_i.+1) *: 'X^i)).\n    by rewrite size_poly0 big_nil.\n  - rewrite DqpE' /dqp /scale_var /Dqp' -{3}(coefK p) !poly_def.\n    rewrite (sumW _ (fun i => (q ^ i * p`_i) *: 'X^i)).\n    rewrite (sumW _ (fun i => p`_i *: 'X^i)).\n    rewrite (sumW _ (fun i => (qnat i.+1 * p`_i.+1) *: 'X^i)).\n    rewrite sum_sub.\n    rewrite divpsum.\n    under eq_bigr => i _.\n      rewrite -scalerBl -{2}(mul1r p`_i) -mulrBl scale_div //.\n      have -> : (q ^ i - 1) * p`_i / (q - 1) = (q ^ i - 1) / (q - 1) * p`_i.\n        by rewrite -mulrA [p`_i / (q - 1)]mulrC mulrA.\n      rewrite -/(qnat i).\n    over.\n    move=> /=.\n    rewrite (@big_cat_nat _ _ _ 1) //=; last by apply size_N0_lt.\n    rewrite big_nat1 qnat0 mul0r scale0r add0r.\n    have -> : (1 = 0 + 1)%N by [].\n    rewrite big_addn.\n    under eq_bigr do rewrite addn1 polyX_div.\n    rewrite (@big_cat_nat _ _ _ (size p - 1) 0 (size p)) //=; last by rewrite subn1 leq_pred.\n    have {4}-> : size p = ((size p) - 1).+1.\n      rewrite subn1 prednK //.\n      by apply size_N0_lt.\n    rewrite big_nat1.\n    have -> : p`_(size p - 1).+1 = 0.\n      rewrite subn1 prednK //.\n        by apply /(leq_sizeP _ (size p)) => //=.\n      by apply size_N0_lt.\n    by rewrite mulr0 scale0r addr0.\nQed.\n\nLemma hoDqp_Dqp'E n p :\n  (Dqp \\^ n) p = ((Dqp' \\^ n) p).\nProof.\n  elim: n => [|n IH] //=.\n  by rewrite Dqp_Dqp'E IH.\nQed.\n\nLemma Dqp'_prod' p p' :\n   Dqp' (p * p') = p * Dqp' p' + scale_var p' * Dqp' p.\nProof. by rewrite -!Dqp_Dqp'E Dqp_prod'. Qed.\n\nLemma Dqp'_DqE p x : x != 0 -> (Dqp' p).[x] = (Dq # p) x.\nProof.\n  move=> Hx.\n  rewrite /Dqp' /(_ # _) /Dq /dq.\n  rewrite horner_poly !horner_coef.\n  rewrite (sumW _ (fun i => (qnat i.+1 * p`_i.+1 * x ^+ i))).\n  rewrite (sumW _ (fun i => p`_i * (q * x) ^+ i)).\n  rewrite (sumW _ (fun i => p`_i * x ^+ i)). \n  rewrite sum_sub.\n  case Hsize : (size p == 0%N).\n  - rewrite size_poly_eq0 in Hsize.\n    move/eqP : (Hsize) ->.\n    by rewrite size_poly0 !big_nil mul0r.\n  - have Hsize' : (0 < size p)%N.\n      rewrite ltn_neqAle.\n      apply /andP; split => //.\n      move: Hsize.\n      by rewrite eq_sym => ->.\n    rewrite mulrC -sum_distr.\n    rewrite [RHS](@big_cat_nat _ _ _ 1 0 (size p)) //=.\n    rewrite !big_nat1 !expr0 addrK' mul0r add0r.\n    have -> : (1 = 0 + 1)%N by [].\n    rewrite big_addn.\n    rewrite (@big_cat_nat _ _ _ (size p - 1)) //=.\n      have -> : \\sum_(size p - 1 <= i < size p)\n                  qnat i.+1 * p`_i.+1 * x ^+ i = 0.\n        under eq_big_nat => i /andP [Hi Hi'].\n          move : Hi.\n          rewrite leq_subLR addnC addn1.\n          move/leq_sizeP -> => //.\n          rewrite mulr0 mul0r.\n        over.\n        by rewrite big1.\n      rewrite addr0.\n      apply eq_big_nat => i /andP [Hi Hi'].\n      rewrite addn1 /qnat.\n      have -> : (q * x) ^+ i.+1 = (q * x) ^ (Posz i.+1) by [].\n      have -> : x ^+ i.+1 = 1 * x ^+ i.+1.\n        by rewrite mul1r.\n      have {5}-> : x = 1 * x.\n        by rewrite mul1r.\n      rewrite expfzMl -mulrBr -!mulrBl -mulf_div -!mulrA.\n      rewrite [p`_i.+1 * x ^+ i]mulrC [RHS]mulrC !mulrA.\n      congr (_ * _).\n      rewrite [(q - 1)^-1 * (q ^ i.+1 - 1)]mulrC -!mulrA.\n      congr (_ * _).\n      congr (_ * _).\n      by rewrite exprSzr -mulrA divff // mulr1.\n    by rewrite leq_subLR.\nQed.\n\nLemma hoDqp'_DqE p x n : q != 0 -> x != 0 ->\n  ((Dqp' \\^ n) p).[x] = ((Dq \\^ n) # p) x.\nProof.\n  move=> Hq0 Hx.\n  rewrite /(_ # _).\n  elim: n x Hx => [|n IH] x Hx //=.\n  rewrite Dqp'_DqE // {2}/Dq /dq -!IH //.\n  by apply mulf_neq0 => //.\nQed.\n\nLemma Dqp'_islinear_add (p p' : {poly R}) : Dqp' (p + p') = Dqp' p + Dqp' p'.\nProof.\n  rewrite /Dqp'.\n  rewrite (polyW R (p + p') (maxn (size p) (size p'))); last apply size_add.\n  rewrite (polyW R p (maxn (size p) (size p'))); last by apply leq_maxl.\n  rewrite (polyW R p' (maxn (size p) (size p'))); last by apply leq_maxr.\n  rewrite sum_add.\n  by under eq_bigr do rewrite coefD mulrDr scalerDl.\nQed.\n\nLemma Dqp'_islinear_scale a p : Dqp' (a *: p) = a *: Dqp' p.\nProof.\n  rewrite /Dqp'; apply polyP => j.\n  case Ha : (a == 0).\n  - move/eqP : Ha ->; rewrite !scale0r.\n    by rewrite coef_poly size_poly0 //= coef0.\n  - have Ha' : a != 0 by rewrite Ha.\n    rewrite size_scale // coefZ !coef_poly.\n    case : (j < size p)%N.\n    + by rewrite scalerAr'.\n    + by rewrite mulr0.\nQed.\n\nLemma Dqp'_islinear : islinear Dqp'.\nProof.\n  move=> a b p p'.\n  by rewrite Dqp'_islinear_add !Dqp'_islinear_scale.\nQed.\n\nLemma Dqp'_const a : Dqp' a%:P = 0.\nProof. by rewrite -Dqp_Dqp'E Dqp_const. Qed.\n\nLemma Dqp'X : Dqp' 'X = 1%:P.\nProof.\n  rewrite /Dqp' poly_def size_polyX.\n  rewrite (sumW _ (fun i => (qnat i.+1 * 'X`_i.+1) *: 'X^i)).\n  rewrite (@big_cat_nat _ _ _ 1) //= !big_nat1.\n  by rewrite !coefX /= mulr0 scale0r !qnat1 mulr1 scale1r addr0.\nQed.\n\nLemma Dqp'Xsub a : Dqp' ('X - a%:P) = 1%:P.\nProof. by rewrite Dqp'_islinear_add -polyCN Dqp'_const addr0 Dqp'X. Qed.\n\nLemma Dqp'_pow n : Dqp' ('X^n.+1) = (qnat n.+1) *: 'X^n.\nProof.\n  elim: n => [|n IH].\n  - by rewrite Dqp'X qnat1 scale1r.\n  - rewrite exprS Dqp'_prod' IH Dqp'X mulrC.\n    rewrite -mul_polyC -mulrA mul_polyC -exprSzr.\n    rewrite [scale_var ('X^n.+1) * 1%:P]mulrC.\n    by rewrite mul_polyC scale1r scale_varXn -scalerDl -qnat_catn.\nQed.\n\nFixpoint qbinom_pos_poly a n := match n with\n  | 0 => 1\n  | n.+1 => (qbinom_pos_poly a n) * ('X - (q ^ n * a)%:P)\n  end.\n\nLemma qbinom_size a n : size (qbinom_pos_poly a n) = n.+1.\nProof.\n  elim: n => [|n IH] => //=.\n  - by rewrite size_poly1.\n  - rewrite size_Mmonic.\n        by rewrite IH size_XsubC addn2.\n      by rewrite -size_poly_gt0 IH.\n    by apply monicXsubC.\nQed.\n\nLemma qbinom_posE a n x :\n  qbinom_pos a n x = (qbinom_pos_poly a n).[x].\nProof.\n  elim: n => [|n IH] //=.\n  - by rewrite hornerC.\n  - by rewrite hornerM -IH hornerXsubC.\nQed.\n\nLemma Dqp'_qbinom_poly a n :\n  Dqp' (qbinom_pos_poly a n.+1) = (qnat n.+1) *: (qbinom_pos_poly a n).\nProof.\n  elim: n => [|n IH].\n  - rewrite /qbinom_pos_poly.\n    rewrite expr0z !mul1r /Dqp'.\n    rewrite poly_def.\n    have -> : size ('X - a%:P) = 2%N.\n      by rewrite size_XsubC.\n    have -> : \\sum_(i < 2) (qnat i.+1 * ('X - a%:P)`_i.+1) *: 'X^i =\n              \\sum_(0 <= i < 2) (qnat i.+1 * ('X - a%:P)`_i.+1) *: 'X^i.\n      by rewrite big_mkord.\n    rewrite (@big_cat_nat _ _ _ 1) //= !big_nat1.\n    rewrite !coefB !coefC /= !subr0.\n    by rewrite !coefX /= scale_constpoly !mulr1 mulr0 scale0r addr0 alg_polyC.\n  - have -> : qbinom_pos_poly a n.+2 =\n              (qbinom_pos_poly a n.+1) * ('X - (q ^ n.+1 * a)%:P) by [].\n    rewrite Dqp'_prod' Dqp'Xsub mulr1 scale_varX IH.\n    rewrite exprSz -mulrA -scale_constpoly -scalerBr.\n    rewrite -!mul_polyC mulrA mulrC23 -mulrA.\n    rewrite [('X - (q ^ n * a)%:P) * qbinom_pos_poly a n]mulrC.\n    rewrite -/(qbinom_pos_poly a n.+1).\n    rewrite (mul_polyC q) scale_constpoly (mul_polyC (q * qnat n.+1)).\n    rewrite -{1}(scale1r (qbinom_pos_poly a n.+1)) -scalerDl.\n    by rewrite mul_polyC -qnat_cat1.\nQed.\n\nLemma Dqp'_isfderiv a : (forall n, qfact n != 0) ->\n  isfderiv Dqp' (fun i : nat => qbinom_pos_poly a i / (qfact i)%:P).\nProof.\n  move=> Hqnat.\n  rewrite /isfderiv.\n  destruct n => //.\n  - have -> : (GRing.one (poly_ringType R) / 1%:P) = 1%:P.\n      by rewrite polyCV mul1r invr1.\n    rewrite /Dqp' (polyW _ _ 1).\n      rewrite big_nat1.\n      by rewrite coefC /= mulr0 scale0r.\n    by apply size_polyC_leq1.\n  - have -> : qbinom_pos_poly a n.+1 / (qfact n.+1)%:P =\n              (qfact n.+1)^-1 *: qbinom_pos_poly a n.+1.\n      by rewrite mulrC polyCV mul_polyC.\n    rewrite Dqp'_islinear_scale -mul_polyC mulrC.\n    rewrite Dqp'_qbinom_poly -mul_polyC.\n    rewrite [(qnat n.+1)%:P * qbinom_pos_poly a n]mulrC.\n    rewrite -polyCV -mulrA.\n    f_equal.\n    rewrite polyCV mul_polyC.\n    rewrite scale_constpoly /=.\n    rewrite -{1}(mul1r (qnat n.+1)).\n    rewrite red_frac_r ?mul1r ?polyCV //.\n    by apply qfact_nat_non0.\nQed.\n\nTheorem q_Taylorp n (f : {poly R}) c :\n  (forall n, qfact n != 0) ->\n  size f = n.+1 ->\n  f =\n    \\sum_(0 <= i < n.+1)\n   ((Dqp' \\^ i) f).[c] *: (qbinom_pos_poly c i / (qfact i)%:P).\nProof.\n  move=> Hfact Hsizef.\n  apply general_Taylor => //.\n  - by apply Dqp'_islinear.\n  - by apply Dqp'_isfderiv.\n  - by rewrite invr1 mulr1 hornerC.\n  - move=> m.\n    by rewrite hornerM -qbinom_posE qbinomxa mul0r.\n  - move=> m.\n    rewrite polyCV mulrC size_Cmul.\n      by rewrite qbinom_size.\n    by apply /invr_neq0.\nQed.\n\nTheorem q_Taylor n (f : {poly R}) x c :\n  q != 0 ->\n  c != 0 ->\n  (forall n, qfact n != 0) ->\n  size f = n.+1 ->\n  f.[x] =  \\sum_(0 <= i < n.+1)\n             ((Dq \\^ i) # f) c * qbinom_pos c i x / qfact i.\nProof.\n  move=> Hq0 Ha Hfact Hsf.\n  under eq_bigr do rewrite qbinom_posE.\n  rewrite sum_poly_div.\n  under eq_bigr do rewrite -hornerZ.\n  rewrite -hornersumD.\n  f_equal.\n  under eq_bigr do rewrite -hoDqp'_DqE //.\n  by apply q_Taylorp.\nQed.\n\nLemma hoDqp'_pow n j : qfact n != 0 -> (j <= n)%N ->\n  (Dqp' \\^ j) 'X^n = (qbicoef n j * qfact j) *: 'X^(n - j).\nProof.\n  move=> Hn.\n  elim: j => [|j IH] Hj /=.\n  - by rewrite qbicoefn0 ?mul1r ?scale1r ?subn0.\n  - rewrite IH; last by apply ltnW.\n    rewrite Dqp'_islinear_scale.\n    have -> : (n - j = (n - j.+1).+1)%N by rewrite subnSK.\n    rewrite Dqp'_pow -mul_polyC -mul_polyC mulrA -[RHS]mul_polyC.\n    f_equal.\n    rewrite mul_polyC scale_constpoly.\n    f_equal.\n    by rewrite qbicoef_compute //.\nQed.\n\nLemma hoDqp'_pow1 n j : qfact n != 0 -> (j <= n)%N ->\n  ((Dqp' \\^ j) 'X^n).[1] = (qbicoef n j * qfact j).\nProof.\n  move=> Hn Hj.\n  by rewrite hoDqp'_pow // hornerZ hornerXn expr1n mulr1.\nQed.\n\nLemma q_Taylorp_pow n : (forall n, qfact n != 0) ->\n  'X^n = \\sum_(0 <= i < n.+1) (qbicoef n i *: qbinom_pos_poly 1 i).\nProof.\n  move=> Hfact.\n  rewrite (q_Taylorp n 'X^n 1) //; last by rewrite size_polyXn.\n  under eq_big_nat => i /andP [_ Hi].\n    rewrite hoDqp'_pow1 //.\n    rewrite [(qbinom_pos_poly 1 i / (qfact i)%:P)]mulrC.\n    rewrite polyCV scalerAl scale_constpoly -mulrA divff //.\n    rewrite mulr1 mul_polyC.\n  over.\n  done.\nQed.\n\n(* Lemma q_Taylor_pow x n : (forall n, qfact n != 0) ->\n  x ^+ n = \\sum_(0 <= i < n.+1) (qbicoef n i * qbinom_pos 1 i x). *)\n\nLemma hoDqp'_qbinom n j a : qfact n != 0 -> (j <= n)%N ->\n  (Dqp' \\^ j) (qbinom_pos_poly (- a) n) =\n  (qbicoef n j * qfact j) *: (qbinom_pos_poly (-a) (n - j)).\nProof.\n  move=> Hfact.\n  elim: j => [|j IH] Hj /=.\n  - by rewrite subn0 qbicoefn0 ?mulr1 ?scale1r.\n  - rewrite IH; last by apply ltnW.\n    rewrite Dqp'_islinear_scale.\n    have -> : (n - j = (n - j.+1).+1)%N by rewrite subnSK.\n    rewrite Dqp'_qbinom_poly -mul_polyC -mul_polyC mulrA -[RHS]mul_polyC.\n    f_equal.\n    rewrite mul_polyC scale_constpoly.\n    f_equal.\n    by rewrite qbicoef_compute //.\nQed.\n\nLemma qbinom_pos_qbinom0 a n :\n  (qbinom_pos_poly (- a) n).[0] = q ^+ (n * (n - 1))./2 * a ^+ n.\nProof. by rewrite -qbinom_posE qbinomx0. Qed.\n\nLemma hoDqp'_qbinom0 n j a : qfact n != 0 -> (j <= n)%N ->\n  ((Dqp' \\^ j) (qbinom_pos_poly (- a) n)).[0] =\n  (qbicoef n j * qfact j) *\n   q ^+ ((n - j) * (n - j - 1))./2 * a ^+ (n - j).\nProof.\n  move=> Hfact Hj.\n  by rewrite hoDqp'_qbinom // hornerZ qbinom_pos_qbinom0 mulrA.\nQed.\n\nLemma qbinom_x0 n : qbinom_pos_poly 0 n = 'X^n.\nProof.\n  elim: n => [|n IH] /=.\n  - by rewrite expr0.\n  - by rewrite IH mulr0 subr0 exprSr.\nQed.\n\nTheorem Gauss_binomial a n : (forall n, qfact n != 0) ->\n  qbinom_pos_poly (-a) n =\n  \\sum_(0 <= i < n.+1)\n    (qbicoef n i * q ^+ (i * (i - 1))./2 * a ^+ i) *: 'X^(n - i).\nProof.\n  move=> Hfact.\n  rewrite big_nat_rev //=.\n  under eq_big_nat => i /andP [_ Hi].\n    rewrite add0n subSS subKn // qbicoefE //.\n  over.\n  rewrite (q_Taylorp n (qbinom_pos_poly (-a) n) 0) //; last by rewrite qbinom_size.\n  under eq_big_nat => i /andP [_ Hi].\n    rewrite hoDqp'_qbinom0 //.\n    rewrite [(qbinom_pos_poly 0 i / (qfact i)%:P)]mulrC.\n    rewrite polyCV scalerAl scale_constpoly.\n    have -> : qbicoef n i * qfact i * q ^+ ((n - i) * (n - i - 1))./2 *\n              a ^+ (n - i) / qfact i =\n              qbicoef n i * q ^+ ((n - i) * (n - i - 1))./2 * a ^+ (n - i).\n      rewrite -!mulrA; f_equal; f_equal.\n      rewrite mulrC -mulrA; f_equal.\n      by rewrite denomK.\n    rewrite mul_polyC qbinom_x0.\n  over.\n  done.\nQed.\n\nLemma Gauss_binomialf a n x : (forall n, qfact n != 0) ->\n  qbinom_pos (-a) n x =\n  \\sum_(0 <= i < n.+1)\n    (qbicoef n i * q ^+ (i * (i - 1))./2 * a ^+ i) * x ^+ (n - i).\nProof.\n  move=> Hfact.\n  rewrite qbinom_posE Gauss_binomial // hornersumD.\n  by under eq_big_nat do rewrite hornerZ hornerXn.\nQed.\n\nEnd q_analogue.\n\nSection q_chain_rule.\nLocal Open Scope ring_scope.\nVariable (R : rcfType).\n\nLemma qchain q u f a b x : dq R q u x != 0 -> u = (fun x => a * x ^ b) ->\n  Dq R q (f \\o u) x = (Dq R (q^b) f (u x)) * (Dq R q u x).\nProof.\n  move=> Hqu Hu.\n  rewrite Hu /Dq /dq mulf_div /=.\n  rewrite [(q ^ b * (a * x ^ b) - a * x ^ b) * (q * x - x)] mulrC.\n  rewrite expfzMl !mulrA.\n  rewrite [a * q ^ b] mulrC.\n  rewrite red_frac_r //.\n  move: Hqu.\n  by rewrite /dq Hu expfzMl mulrA mulrC.\nQed.\nEnd q_chain_rule.", "meta": {"author": "nakamurakaoru", "repo": "q-analogue", "sha": "ee9af7a058e4449335c77ed744a061e38f6b19ac", "save_path": "github-repos/coq/nakamurakaoru-q-analogue", "path": "github-repos/coq/nakamurakaoru-q-analogue/q-analogue-ee9af7a058e4449335c77ed744a061e38f6b19ac/q_analogue.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6811216638856967}}
{"text": "From Coq Require Import Arith.Arith.\nFrom Coq Require Import Arith.EqNat.\nFrom Coq Require Import Arith.PeanoNat. Import Nat.\nFrom Coq Require Import micromega.Lia.\nFrom Coq Require Import micromega.Zify.\nFrom Coq Require Import Lists.List.\nFrom Coq Require Import Bool.Bool.\nFrom Coq Require Import Reals.Reals. Import Rdefinitions. Import RIneq.\nFrom Coq Require Import ZArith.Zdiv.\nFrom Coq Require Import ZArith.Int.\nFrom Coq Require Import ZArith.Znat.\nFrom Coq Require Import Setoids.Setoid.\nFrom Coq Require Import Logic.FunctionalExtensionality.\nFrom Coq Require Import Classes.Morphisms.\n\nFrom ATL Require Import Tactics.\n\nOpen Scope Z_scope.\n\nDefinition div_ceil (n d : Z) : Z := (n + d - 1) / d.\n  \nNotation \"a // b\" := (div_ceil a b) (at level 10, left associativity).\n\nTheorem zero_div : forall n, 0 < n -> 0 // n = 0.\nProof.\n  intros.\n  apply Zdiv_small.\n  lia.\nQed.\n\nTheorem div_zero : forall n, n // 0 = 0.\nProof.  intros. unfold div_ceil. apply Zdiv_0_r. Qed.\n\nDefinition div_ceil_n (n d : nat) : nat := ((n + d - 1) / d)%nat.\n\nNotation \"a //n b\" := (div_ceil_n a b) (at level 10, left associativity).\nArguments div_ceil_n : simpl never.\n\nTheorem of_nat_div_distr : forall n c,\n    (Z.of_nat n) // (Z.of_nat c) = Z.of_nat ( n //n c).\nProof.\n  intros.\n  destruct c.\n  - rewrite div_zero. reflexivity.\n  - unfold div_ceil, div_ceil_n.\n    rewrite <- Nat2Z.inj_add.\n    replace 1 with (Z.of_nat (S O)) by reflexivity.\n    rewrite <- Nat2Z.inj_sub by lia.\n    rewrite <- div_Zdiv by lia.\n    reflexivity.\nQed.\n\nTheorem znat_id_distr : forall n c,\n    (Z.to_nat (Z.of_nat n // (Z.of_nat c))) =\n    (Z.to_nat (Z.of_nat n)) //n (Z.to_nat (Z.of_nat c)).\nProof.\n  intros.\n  rewrite of_nat_div_distr.\n  repeat rewrite Nat2Z.id.\n  reflexivity.\nQed.\n      \nTheorem mul_add_lt : forall i j n m,\n    0 <= i ->\n    i < n ->\n    0 <= j ->\n    j < m ->\n    i * m + j < n * m.\nProof.\n  intros.\n  assert (i*m <= (n-1) * m).\n  {\n    apply Z.mul_le_mono_nonneg_r. lia. lia.\n  }\n  assert ((n-1)*m + j < (n-1)*m + m).\n  {\n    apply Zplus_lt_compat_l. auto.\n  }\n  assert (i*m + j <= (n-1)*m + j).\n  {\n    apply Zplus_le_compat_r. auto.\n  }\n  eapply Z.le_lt_trans.\n  apply H5.\n  rewrite Zmult_succ_l_reverse in H4.\n  assert (Z.succ (n-1) = n). lia.\n  rewrite H6 in H4. auto.\nQed.\n\nClose Scope Z_scope.\n\nTheorem nat_mul_div_id : forall n m,\n    0 < m ->\n    (n * m) //n m = n.\nProof.\n  intros.\n  unfold div_ceil_n.\n  rewrite <- add_sub_assoc by lia.\n  rewrite div_add_l by lia.\n  rewrite div_small. lia. lia.\nQed.\n\nTheorem ndiv_pos : forall n m,\n    0 < n ->\n    0 < m ->\n    0 < n //n m .\nProof.\n  intros.\n  unfold \"_ //n _\".\n  destruct n. lia.\n  simpl.\n  rewrite sub_0_r.\n  apply div_str_pos.\n  lia.\nQed.\nHint Extern 1 (0 < _ //n _) => apply ndiv_pos : crunch.\n\nTheorem div_pos : forall n m,\n    (0 < n)%Z ->\n    (0 < m)%Z ->\n    (0 < n // m)%Z.\nProof.\n  intros. unfold div_ceil.\n  apply Z.div_str_pos. lia.\nQed.\nHint Extern 1 ((0 < _ // _)%Z) => apply div_pos : crunch.\n\nTheorem div_nonneg : forall n m,\n    (0 <= n)%Z ->\n    (0 < m)%Z ->\n    (0 <= n // m)%Z.\nProof.\n  intros. unfold div_ceil.\n  apply Z.div_pos; lia.\nQed.\nHint Extern 1 ((0 <= _ // _)%Z) => apply div_nonneg : crunch.\n\nLemma of_nat_nonneg : forall x,\n    (0 <= Z.of_nat x)%Z.\nProof.\n  intros. zify. lia.\nQed.\nHint Extern 1 ((0 <= _)%Z) => apply of_nat_nonneg : crunch.\n\nLemma znat_lt : forall x n,\n    (0 <= x)%Z ->\n    (x < Z.of_nat n)%Z ->\n    Z.to_nat x < n.\nProof.\n  intros.\n  zify. lia.\nQed.                   \n\nHint Extern 5 (Z.to_nat _ < _) => apply znat_lt : crunch.\n\nLemma pos_nat_succ : forall p, exists n, Pos.to_nat p = S n.\nProof.\n  intros p.\n  specialize (Pos2Nat.is_pos p); intros.\n  destruct (Pos.to_nat p); try lia; eauto.\nQed.\n\nLtac posnat :=\n  match goal with\n  | [ |- context[Pos.to_nat ?p] ] => specialize (pos_nat_succ p);\n                                     intros [pn Hpos]; rewrite Hpos\n  end.\n\nLemma znat_0lt : forall x, (0 < x)%Z -> 0 < (Z.to_nat x).\nProof.\n  intros. zify. lia.\nQed.\n\nHint Resolve znat_0lt : crunch.\n\nLemma natz_0lt : forall x, 0 < x -> (0 < (Z.of_nat x))%Z.\nProof.\n  intros. zify. lia.\nQed.\n\nHint Resolve natz_0lt : crunch.\n\nLemma weaker_Z2Nat_injlt : forall i j,\n    Z.to_nat i < Z.to_nat j ->\n    (0 <= i)%Z ->\n    (i < j)%Z.\nProof.\n  intros. destruct j eqn:e.\n  - simpl in *. lia.\n  - rewrite <- e in *.\n    apply Z2Nat.inj_lt in H; auto.\n    subst.\n    apply Zle_0_pos.\n  - simpl in *. lia.\nQed.\n\nLemma factor_unique : forall i i0 i1 i2 m,\n    (0 <= i0 < m)%Z ->\n    (0 <= i2 < m)%Z ->    \n    ((i * m + i0 =? i1 * m + i2)%Z =\n     (i=?i1)%Z && (i0=?i2)%Z).\nProof.\n  intros.\n  unbool.  \n  split; intros.  \n  - eapply Z.div_mod_unique.\n    left.\n    eauto.\n    left.\n    lia.\n    rewrite Z.mul_comm. rewrite H1. rewrite Z.mul_comm. reflexivity.\n  - destruct H1. subst. reflexivity.\nQed.  \n\nLemma div_eucl_div : forall a b,\n    (b > 0)%Z ->\n    let (q,_) := Z.div_eucl a b in\n    q = (a / b)%Z.\nProof.\n  intros.\n  pose (Z_div_mod a b). peel_hyp.\n  destruct (Z.div_eucl a b) eqn:e. destruct y.\n  subst.\n  rewrite Z.add_comm.\n  rewrite Z.mul_comm.\n  rewrite Z_div_plus by auto.\n  rewrite Zdiv_small; auto.\nQed.  \n\nLemma mul_lt : forall z k x,\n  (0 <= z < k)%Z ->\n  ((z < k * x)%Z <-> (0 < x)%Z).\nProof.\n  intros.\n  split; intros.\n  - destruct x. lia. zlia. \n    assert (0 < k * Z.neg p)%Z by lia.\n    assert (0 < k)%Z by lia.\n    apply Z.lt_0_mul in H1.\n    lia.\n  - destruct x; zify; try lia.\n    assert (1 <= Z.pos p )%Z by (zify; lia).\n    replace z with (z * 1)%Z by lia.\n    destruct (1 =? Z.pos p)%Z eqn:ee; unbool.\n    * rewrite <- ee.\n      lia.\n    * assert (1 < Z.pos p)%Z by lia.\n      apply Z.mul_lt_mono_nonneg; try lia.\nQed.\n\nLemma mul_le : forall z k x,\n    (0 <= z < k)%Z ->\n    (k * x <= z <-> x <= 0)%Z.\nProof.\n  intros.\n  split; intros.\n  - destruct x; zify; try lia.\n    assert (k < k * Z.pos p)%Z.\n    assert (1 <= Z.pos p )%Z by (zify; lia).\n    destruct (1 =? Z.pos p)%Z eqn:ee; unbool.\n    + rewrite <- ee in *. rewrite Z.mul_1_r in *. lia.\n    + assert (1 < Z.pos p)%Z by lia.\n      replace k with (k * 1)%Z at 1 by lia.\n      apply Zmult_lt_compat_l; lia.\n    + lia.\n  - destruct (x =? 0)%Z eqn:ee; unbool.\n    + subst. rewrite Z.mul_0_r. lia.\n    + assert (x < 0)%Z by lia.\n      assert (k * x < 0)%Z.\n      apply Z.mul_pos_neg; lia.\n      lia.\nQed.\n\nLemma floor_lt_ceil : forall x y,\n    (0 <= x)%Z ->\n    (0 < y)%Z ->\n    (x / y <= x // y)%Z.\nProof.\n  intros.\n  unfold div_ceil.\n  apply Z_div_le. lia. lia.\nQed.\n\nLemma div_eq_num_diff : forall a b c,\n    (0 <= a)%Z ->\n    (0 <= b)%Z ->\n    (0 < c)%Z ->\n    (a / c = b / c)%Z ->\n    (a < b)%Z ->\n    (b - a < c)%Z.\nProof.\n  intros.\n  pose (Z_div_mod a c). peel_hyp.\n  pose (Z_div_mod b c). peel_hyp.\n  destruct (Z.div_eucl a c).\n  destruct (Z.div_eucl b c).\n  destruct y. destruct y0. subst.\n  rewrite Z.sub_add_distr.\n  repeat rewrite (Z.mul_comm c) in H2.\n  repeat rewrite Z.div_add_l in H2 by lia.\n  repeat rewrite Z.div_small in H2 by lia.\n  repeat rewrite Z.add_0_r in H2.\n  subst. lia.\nQed.\n\nLemma floor_lt_ceil_mono_l : forall i k n,\n    (0 <= i)%Z ->\n    (i < n)%Z ->\n    (0 < k)%Z ->\n    (0 < n)%Z ->\n    (i / k < n // k)%Z.\nProof.\n  intros. unfold div_ceil.\n  pose proof (Z.div_le_mono i (n+k-1)%Z k). peel_hyp; try lia.\n  destruct (i / k =? (n + k - 1) / k)%Z eqn:e; unbool.\n  - rewrite <- e in *. clear H3.\n    apply div_eq_num_diff in e; try lia.\n  - lia.\nQed.\nHint Resolve floor_lt_ceil_mono_l : crunch.\n\nLemma floor_lt_nat_ceil_mono_l : forall i k n,\n    (0 <= i)%Z ->\n    (i < Z.of_nat n)%Z ->\n    0 < k ->\n    0 < n ->\n    (i / Z.of_nat k < Z.of_nat (n //n k))%Z.\nProof.\n  intros.\n  rewrite <- of_nat_div_distr.\n  apply floor_lt_ceil_mono_l; auto with crunch.\nQed.\nHint Resolve floor_lt_nat_ceil_mono_l : crunch.\n\nTheorem pos_zofnat : forall n,\n    0 < n ->\n    (0 < Z.of_nat n)%Z.\nProof. intros. lia. Qed.\nHint Resolve pos_zofnat : crunch.\nHint Resolve Z.div_pos : crunch.\n\nLemma expand_Zmod : forall i m,\n    (0 < m)%Z ->\n    (i - i / m * m = Zmod i m)%Z.\nProof.\n  intros. unfold Zmod.\n  pose proof (Z_div_mod i m).\n  assert (m > 0)%Z by lia.\n  apply H0 in H1.\n  destruct (Z.div_eucl i m) eqn:e.\n  destruct H1.\n  rewrite H1.\n  rewrite Z.mul_comm.\n  rewrite Z_div_plus_full_l by lia.\n  rewrite Zdiv_small by lia.\n  rewrite Z.add_0_r. lia.\nQed.\n\nLemma Zplus_assoc : forall p m n, (n + (m + p))%Z = (n + m + p)%Z.\nProof. intros. lia. Qed.\n\nLemma div_ceil_n_lower_bound : forall n k,\n    0 < k ->\n    n <= n //n k * k.\nProof.\n  intros n k Hk_pos.\n  unfold div_ceil_n.\n  assert (k <> 0) as Hk_nzero by lia.\n  pose proof (div_mod (n + k - 1) k Hk_nzero).\n  assert ((n + k - 1) mod k < k) by (apply mod_upper_bound; apply Hk_nzero).\n  assert (n <= k * ((n + k - 1) / k)) by lia.\n  rewrite mul_comm. assumption.\nQed.\n\nHint Resolve div_ceil_n_lower_bound : crunch.\n\nLemma mod_upper_bound : forall k i,\n    (0 < k)%Z ->\n    (i mod k < k)%Z.\nProof.\n  intros.\n  pose proof (Z.mod_pos_bound i k).\n  peel_hyp. lia.\nQed.\n\nLemma mod_nonneg : forall k i,\n    (0 < k)%Z ->\n    (0 <= i mod k)%Z.\nProof.\n  intros.\n  pose proof (Z.mod_pos_bound i k).\n  peel_hyp. lia.\nQed.  \n\nHint Resolve mod_upper_bound mod_nonneg : crunch.\n\nTheorem div_mod_eq : forall i k,\n    (0 < k)%Z ->\n    (i / k * k + i mod k = i)%Z.\nProof.\n  intros.\n  rewrite <- expand_Zmod by lia.\n  rewrite Zplus_minus.\n  reflexivity.\nQed.\n\nLemma gt_add_r : forall k a b,\n    (0 <= a)%Z ->\n    (k <= b)%Z ->\n    (k <= a + b)%Z.\nProof. intros. lia. Qed.\n\nHint Resolve Z.max_lub Z.min_glb Z.le_max_l Z.le_min_r Z.le_min_l : crunch.\n\nLemma ceil_div_pos : forall (m k : Z),\n    (0 < m)%Z ->\n    (0 < k)%Z ->\n    (0 < m // k)%Z.\nProof.\n  intros.\n  unfold div_ceil.\n  assert (m + k - 1 >= k)%Z by lia.\n  apply Z.div_str_pos.\n  split; lia.\nQed.\n\nLemma ceil_div_nonneg : forall (m k : Z),\n    (0 <= m)%Z ->\n    (0 < k)%Z ->\n    (0 <= m // k)%Z.\nProof.\n  intros.\n  assert (m = 0 \\/ 0 < m)%Z as [ Hm_zero | Hm_pos ] by lia.\n  {\n    rewrite Hm_zero in *.\n    rewrite zero_div by assumption.\n    lia.\n  }\n  {\n    pose proof (ceil_div_pos m k Hm_pos H0).\n    lia.\n  }\nQed.\n\nLemma ceil_div_mod_pos : forall (m k : Z),\n    (0 < m)%Z ->\n    (0 < k)%Z ->\n    (0 < (m mod k) // k)%Z \\/ (0 < m /k)%Z.\nProof.\n  intros m k H H0.\n  assert (0 <= m)%Z as H' by lia.\n  pose proof (Z.mod_bound_pos m k H' H0) as [Hlb Hub].\n  assert ((m mod k = 0)%Z \\/ (0 < m mod k)%Z) as [Heq | Hgt]by lia.\n  {\n    assert (k <> 0)%Z as Hk_nzero by lia.\n    pose proof (Znumtheory.Zmod_divide m k Hk_nzero Heq).\n    right.\n    assert (k = 1 \\/ 1 < k)%Z as [Hk_eq1 | Hk_gt1] by lia.\n    {\n      rewrite Hk_eq1 in *.\n      rewrite Z.div_1_r.\n      assumption.\n    }\n    {\n      pose proof (Znumtheory.Zdivide_Zdiv_lt_pos k m Hk_gt1 H H1) as [H_goal _].\n      apply H_goal.\n    }\n  }\n  {\n    left.\n    apply ceil_div_pos; assumption.\n  }\nQed.\n\nLemma split_floor_rest_nonneg : forall m k,\n    (0 < m)%Z ->\n    (0 < k)%Z ->\n    (0 < m / k + (m mod k) // k)%Z.\nProof.\n  intros.\n  assert (0 <= m / k)%Z as Hdiv_nneg.\n  {\n    apply Z.div_pos; lia.\n  }\n  assert (0 <= (m mod k) // k)%Z as Hdiv_mod_nneg.\n  {\n    apply ceil_div_nonneg.\n    { apply mod_nonneg; assumption. }\n    { assumption. }\n  }\n  pose proof (ceil_div_mod_pos m k H H0) as [ Hdiv_mod_pos | H_div_pos ];\n  lia.\nQed.\n\nLemma floor_div_mono_helper : forall (n k : Z),\n  (0 < k)%Z -> (n < k * (n / k) + k)%Z.\nProof.\n  intros n k Hk_pos.\n  assert (k <> 0)%Z as Hk_nzero by lia.\n  pose proof (Z.div_mod n k Hk_nzero).\n  pose proof (mod_upper_bound k n Hk_pos).\n  lia.\nQed.\n\nLemma floor_div_mono_strict : forall (n m k : Z),\n    (0 < k)%Z ->\n    (n / k < m / k)%Z ->\n    (n < m)%Z.\nProof.\n  intros.\n  assert (k * (n / k) < k * (m / k))%Z as H_mul_lt.\n  { apply Z.mul_lt_mono_pos_l; assumption. }\n  pose proof (floor_div_mono_helper n k H).\n  pose proof (Z.mul_div_le m k H).\n  assert ((n / k) + 1 <= (m / k))%Z by lia.\n  assert (k * ((n / k) + 1) <= k * ((m / k)))%Z.\n  { apply Z.mul_le_mono_nonneg_l; lia. }\n  assert (k * (n / k) + k <= m)%Z.\n  { rewrite Z.mul_add_distr_l in H4. lia. }\n  lia.\nQed.\n\n\nLemma floor_div_mono_upper : forall (n m k : Z),\n  (0 < k)%Z ->\n  (m < n / k)%Z ->\n  (m * k <= n - k)%Z.\nProof.\n  intros.\n  assert (m * k / k <= (n - k) / k)%Z as H_div_bound.\n  {\n    rewrite Z.div_mul by lia.\n    replace (n - k)%Z with (n + -1 * k)%Z by lia.\n    rewrite Z.div_add; lia.\n  }\n  assert (m * k / k = (n - k) / k \\/ m * k / k < (n - k) / k)%Z as [ H_div_eq | H_div_lt ] by lia.\n  {\n    rewrite Z.div_mul in H_div_eq by lia.\n    rewrite H_div_eq in *.\n    rewrite Z.mul_comm.\n    apply Z.mul_div_le.\n    assumption.\n  }\n  {\n    pose proof (floor_div_mono_strict (m * k) (n - k) k H H_div_lt).\n    lia.\n  }\nQed.\n\nLemma floor_div_mul_lt : forall n k i0 i1,\n    (0 < k)%Z ->\n    (0 <= i0)%Z ->\n    (i0 < n / k)%Z ->\n    (0 <= i1)%Z ->\n    (i1 < k)%Z ->\n    (i0 * k + i1 < n)%Z.\nProof.\n  intros.\n  assert (i0 * k <= n - k)%Z.\n  { apply floor_div_mono_upper; assumption. }\n  { lia. }\nQed.\n\nHint Resolve floor_div_mul_lt split_floor_rest_nonneg Z.div_pos  : crunch.\n\nLemma Z_div_mod_eq : forall (n k : Z),\n    (k <> 0)%Z ->\n    (k * (n / k) = n - (n mod k))%Z.\nProof.\n  intros n k Hk_nzero.\n  pose proof (Z.div_mod n k Hk_nzero).\n  lia.\nQed.\n\nLemma ceil_floor_mod : forall n k,\n    (0 <= n)%Z ->\n    (0 < k)%Z ->\n    (n//k = n/k + ((n mod k) // k))%Z.\nProof.\n  intros n k Hn_nneg Hk_pos.\n  unfold div_ceil.\n  apply Z.mul_cancel_l with (p := k).\n  { lia. }\n  rewrite Z.mul_add_distr_l.\n  assert (k <> 0)%Z as Hk_nzero by lia.\n  repeat rewrite Z_div_mod_eq by assumption.\n  replace (n - n mod k + (n mod k + k - 1 - (n mod k + k - 1) mod k))%Z\n    with (n + k - 1 - (n mod k + k - 1) mod k)%Z by lia.\n  assert ((n + k - 1) mod k = (n mod k + k - 1) mod k)%Z.\n  2: lia.\n  replace (n + k - 1)%Z with (n + (k - 1))%Z by lia.\n  replace (n mod k + k - 1)%Z with (n mod k + (k - 1))%Z by lia.\n  rewrite Z.add_mod by assumption.\n  symmetry.\n  rewrite Z.add_mod by assumption.\n  rewrite Z.mod_mod by assumption.\n  lia.\nQed.\n", "meta": {"author": "ChezJrk", "repo": "verified-scheduling", "sha": "e9876602147114e4378f10ac1402bd5705c0cef0", "save_path": "github-repos/coq/ChezJrk-verified-scheduling", "path": "github-repos/coq/ChezJrk-verified-scheduling/verified-scheduling-e9876602147114e4378f10ac1402bd5705c0cef0/src/Div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.681113331266551}}
{"text": "Require Export section_07_equivalences.\n\n(** Section 8.1 Contractible types *)\n\n(** Definition 8.1.1 *)\n\nDefinition is_contr (A : Type) : Type :=\n  Sigma A (fun a => forall x, a == x).\n\nDefinition center {A : Type} : is_contr A -> A := pr1.\n\nDefinition contraction' {A : Type} (c : is_contr A) (x y : A) : x == y :=\n  concat (inv (pr2 c x)) (pr2 c y).\n\nDefinition contraction {A : Type} (c : is_contr A) :\n  forall x, (center c) == x :=\n  contraction' c (center c).\n\nDefinition coh_contraction {A : Type} (c : is_contr A) :\n  contraction c (center c) == refl := left_inv.\n\n(** Remark 8.1.3 *)\n\nDefinition contraction_unit : forall x, star == x.\nProof.\n  intro x. now destruct x.\nDefined.\n\nTheorem is_contr_unit : is_contr unit.\nProof.\n  exact (pair star contraction_unit).\nDefined.\n\n(** Definition 8.1.4 *)\n\nDefinition ev_pt {A} {B : A -> Type} (a : A) :\n  (forall x, B x) -> B a :=\n  fun h => h a.\n\nDefinition Ind_sing {A} (a : A) : Type :=\n  forall (B : A -> Type), sec (@ev_pt A B a).\n\n(** Remark 8.1.5 *)\n\nDefinition ind_sing_unit (B : unit -> Type) (b : B star) (x : unit) : B x.\nProof.\n  now destruct x.\nDefined.\n\nDefinition comp_sing_unit (B : unit -> Type) (b : B star) :\n  ev_pt star (ind_sing_unit B b) == b.\nProof.\n  reflexivity.\nDefined.\n\nDefinition Ind_sing_unit : Ind_sing star.\nProof.\n  intro B.\n  apply (pair (ind_sing_unit B)).\n  exact (comp_sing_unit B).\nDefined.\n\n(** Theorem 8.1.6 *)\n\nDefinition ind_sing_is_contr {A} {a : A} (c : is_contr A) {B : A -> Type}\n           (b : B a) : forall x, B x :=\n  fun x => tr B (contraction' c a x) b.\n\nDefinition comp_sing_is_contr {A} {a : A} (c : is_contr A) {B : A -> Type}\n           (b : B a) :\n  ev_pt a (ind_sing_is_contr c b) == b :=\n  ap (fun p => tr B p b) left_inv.\n\nTheorem Ind_sing_is_contr {A} (c : is_contr A) (a : A) : Ind_sing a.\nProof.\n  intro B.\n  exact (pair (ind_sing_is_contr c) (comp_sing_is_contr c)).\nDefined.\n\nTheorem is_contr_Ind_sing {A} (a : A) (H : Ind_sing a) : is_contr A.\nProof.\n  apply (pair a).\n  now apply (map_sec (H (fun x => a == x))).\nDefined.\n\n(** Theorem 8.1.7 *)\n\nDefinition total_path {A} (a : A) : Type :=\n  Sigma A (fun x => a == x).\n\nDefinition pt_total_path {A} (a : A) : total_path a :=\n  pair a refl.\n\nDefinition ev_refl {A} (a : A) {B : forall x, a == x -> Type} :\n  (forall x p, B x p) -> B a refl :=\n  fun h => h a refl.\n\nDefinition ind_sing_total_path {A} (a : A) {B : total_path a -> Type}\n           (b : B (pt_total_path a)) :\n  forall x, B x.\nProof.\n  intro x.\n  destruct x as [x p].\n  now destruct p.\nDefined.\n\nDefinition comp_sing_total_path {A} (a : A) {B : total_path a -> Type}\n           (b : B (pt_total_path a)) :\n  ev_pt (pt_total_path a) (ind_sing_total_path a b) == b := refl.\n\nDefinition Ind_sing_total_path {A} (a : A) :\n  @Ind_sing (Sigma A (fun x => a == x)) (pair a refl).\nProof.\n  intro B.\n  apply (pair (ind_sing_total_path a)).\n  exact (comp_sing_total_path a).\nDefined.\n\nTheorem is_contr_total_path {A} (a : A) : is_contr (total_path a).\nProof.\n  apply (is_contr_Ind_sing (pt_total_path a)).\n  exact (Ind_sing_total_path a).\nDefined.\n\n(** Section 8.2 Contractible maps *)\n\n(** Definition 8.2.1 *)\n\nDefinition fib {A B} (f : A -> B) (b : B) : Type :=\n  Sigma A (fun x => f x == b).\n\n(** Definition 8.2.2 *)\n\nDefinition Eq_fib {A B} (f : A -> B) {b : B} (s t : fib f b) : Type :=\n  Sigma (pr1 s == pr1 t) (fun p => pr2 s == concat (ap f p) (pr2 t)).\n\nDefinition refl_Eq_fib {A B} (f : A -> B) {b : B} (s : fib f b) :\n  Eq_fib f s s := pair refl refl.\n\n(** Lemma 8.2.3 *)\n\nDefinition Eq_fib_eq {A B} (f : A -> B) {b : B} {s t : fib f b} :\n  s == t -> Eq_fib f s t.\nProof.\n  intro p; destruct p.\n  apply refl_Eq_fib.\nDefined.\n\nDefinition eq_Eq_fib {A B} (f : A -> B) {b : B} {s t : fib f b} :\n  Eq_fib f s t -> s == t.\nProof.\n  induction s as [x p]; induction t as [y q].\n  intro e; destruct e as [u v].\n  cbn in u; induction u.\n  cbn in v; now induction v.\nDefined.\n\nDefinition is_sec_eq_Eq_fib {A B} (f : A -> B) {b : B} {s t : fib f b} :\n  comp (@Eq_fib_eq _ _ f b s t) (eq_Eq_fib f) ~ idmap.\nProof.\n  induction s as [x p]; induction t as [y q].\n  intro e; destruct e as [u v].\n  cbn in u; induction u.\n  cbn in v; now induction v.\nDefined.\n\nDefinition is_retr_eq_Eq_fib {A B} (f : A -> B) {b : B} {s t : fib f b} :\n  comp (eq_Eq_fib f) (@Eq_fib_eq _ _ f b s t) ~ idmap.\nProof.\n  intro p; destruct p; now destruct s.\nDefined.\n\nTheorem is_equiv_Eq_fib_eq {A B} (f : A -> B) {b : B} {s t : fib f b} :\n  is_equiv (@Eq_fib_eq _ _ f b s t).\nProof.\n  apply (is_equiv_has_inverse (eq_Eq_fib f)).\n  - exact (is_sec_eq_Eq_fib f).\n  - exact (is_retr_eq_Eq_fib f).\nDefined.\n\nTheorem is_equiv_eq_Eq_fib {A B} (f : A -> B) {b : B} {s t : fib f b} :\n  is_equiv (@eq_Eq_fib _ _ f b s t).\nProof.\n  apply (is_equiv_has_inverse (Eq_fib_eq f)).\n  - exact (is_retr_eq_Eq_fib f).\n  - exact (is_sec_eq_Eq_fib f).\nDefined.\n\n(** Definition 8.2.4 *)\n\nDefinition is_contr_map {A B} (f : A -> B) : Type :=\n  forall b, is_contr (fib f b).\n\n(** Theorem 8.2.5 *)\n\nDefinition inv_is_contr_map {A B} {f : A -> B} (c : is_contr_map f) :\n  B -> A.\nProof.\n  intro b.\n  exact (pr1 (center (c b))).\nDefined.\n\nDefinition is_sec_inv_is_contr_map {A B} {f : A -> B} (c : is_contr_map f) :\n  comp f (inv_is_contr_map c) ~ idmap.\nProof.\n  intro b.\n  exact (pr2 (center (c b))).\nDefined.\n\n(** Sometimes Coq pretends it cannot apply a tactic, while it should certainly\n    accept my steps. This is one of those cases, where it is easier to just\n    write out the proof term than to convince Coq of some sequence of tactics. *)\n\nDefinition is_retr_inv_is_contr_map {A B} {f : A -> B} (c : is_contr_map f) :\n  comp (inv_is_contr_map c) f ~ idmap.\nProof.\n  intro a.\n  set (g := inv_is_contr_map c).\n  assert (p : f (g (f a)) == f a) by apply is_sec_inv_is_contr_map.\n  assert (q : pair (g (f a)) p == pair a refl) by apply (contraction' (c (f a))).\n  exact (ap pr1 q).\nDefined.\n\nTheorem is_equiv_is_contr_map {A B} {f : A -> B} :\n  is_contr_map f -> is_equiv f.\nProof.\n  intro is_contr_f.\n  apply (is_equiv_has_inverse (inv_is_contr_map is_contr_f)).\n  - apply is_sec_inv_is_contr_map.\n  - apply is_retr_inv_is_contr_map.\nDefined.\n\n(** Section 8.3 Equivalences are contractible maps *)\n\n(** Definition 8.3.1 *)\n\nDefinition is_coh_invertible {A B} (f : A -> B) : Type :=\n  Sigma\n    (B -> A)\n    (fun g => Sigma\n                (comp f g ~ idmap)\n                (fun G => Sigma\n                            (comp g f ~ idmap)\n                            (fun H =>\n                               right_whisker_htpy G f ~\n                                                  left_whisker_htpy f H))).\n\nDefinition inv_is_coh_invertible {A B} {f : A -> B} :\n  is_coh_invertible f -> B -> A := pr1.\n\nDefinition is_sec_inv_is_coh_invertible {A B} {f : A -> B}\n           (I : is_coh_invertible f) :\n  comp f (inv_is_coh_invertible I) ~ idmap := pr1 (pr2 I).\n\nDefinition is_retr_inv_is_coh_invertible {A B} {f : A -> B}\n           (I : is_coh_invertible f) :\n  comp (inv_is_coh_invertible I) f ~ idmap := pr1 (pr2 (pr2 I)).\n\nDefinition coh_inv_is_coh_invertible {A B} {f : A -> B}\n           (I : is_coh_invertible f) :\n  right_whisker_htpy (is_sec_inv_is_coh_invertible I) f ~\n                     left_whisker_htpy f (is_retr_inv_is_coh_invertible I) :=\n  pr2 (pr2 (pr2 I)).\n\n(** Lemma 8.3.2 *)\n\nDefinition center_fib_is_coh_invertible {A B} {f : A -> B}\n           (I : is_coh_invertible f) (b : B) : fib f b :=\n  pair (inv_is_coh_invertible I b) (is_sec_inv_is_coh_invertible I b).\n\nDefinition contraction_fib_is_coh_invertible {A B} {f : A -> B}\n           (I : is_coh_invertible f) (b : B) (x : fib f b) :\n  center_fib_is_coh_invertible I b == x.\nProof.\n  apply (eq_Eq_fib f).\n  destruct x as [x p]; destruct p.\n  apply (pair (is_retr_inv_is_coh_invertible I x)).\n  transitivity (ap f (is_retr_inv_is_coh_invertible I x)).\n  - apply (coh_inv_is_coh_invertible I).\n  - apply inv; apply right_unit.\nDefined.\n\nTheorem is_contr_map_is_coh_invertible {A B} {f : A -> B} :\n  is_coh_invertible f -> is_contr_map f.\nProof.\n  intros I b.\n  apply (pair (center_fib_is_coh_invertible I b)).\n  exact (contraction_fib_is_coh_invertible I b).\nDefined.\n  \n(** Definition 8.3.3 *)\n\nDefinition nat_htpy {A B} {f g : A -> B} (H : f ~ g) {x y : A} (p : x == y) :\n  concat (ap f p) (H y) == concat (H x) (ap g p).\nProof.\n  destruct p.\n  apply inv; apply right_unit.\nDefined.\n\n(** Definition 8.3.4 *)\n\nDefinition left_unwhisk {A} {x y z : A} (p : x == y) {q r : y == z} :\n  concat p q == concat p r -> q == r.\nProof.\n  now destruct p.\nDefined.\n\nDefinition right_unwhisk {A} {x y z : A} {p q : x == y} (r : y == z) :\n  concat p r == concat q r -> p == q.\nProof.\n  destruct r.\n  intro s.\n  exact (concat (inv right_unit) (concat s right_unit)).\nDefined.\n\nDefinition reduce_htpy {A} {f : A -> A} {H : f ~ idmap} {x : A} :\n  ap f (H x) == H (f x).\nProof.\n  apply (right_unwhisk (H x)).\n  transitivity (concat (H (f x)) (ap idmap (H x))).\n  apply nat_htpy.\n  apply (ap (concat (H (f x)))).\n  apply inv. apply ap_id.\nDefined.\n\n(** Lemma 8.3.5 *)\n\nDefinition mod_is_sec_inv_has_inverse {A B} {f : A -> B} (I : has_inverse f) :\n  comp f (inv_has_inverse I) ~ idmap.\nProof.\n  intro y.\n  transitivity (f (inv_has_inverse I (f (inv_has_inverse I y)))).\n  - apply inv.\n    exact (is_sec_inv_has_inverse I (f (inv_has_inverse I y))).\n  - transitivity (f (inv_has_inverse I y)).\n    * exact (ap f (is_retr_inv_has_inverse I (inv_has_inverse I y))).\n    * exact (is_sec_inv_has_inverse I y).\nDefined.\n\nDefinition coh_inv_has_inverse {A B} {f : A -> B} (I : has_inverse f) :\n  right_whisker_htpy (mod_is_sec_inv_has_inverse I) f ~\n                     left_whisker_htpy f (is_retr_inv_has_inverse I).\nProof.\n  intro x.\n  apply inv; apply inv_con; apply inv.\n  transitivity (concat (ap (comp f (comp (inv_has_inverse I) f)) (is_retr_inv_has_inverse I x)) (is_sec_inv_has_inverse I (f x))).\n  - apply (ap (concat' (is_sec_inv_has_inverse I (f x)))).\n    transitivity (ap f (ap (comp (inv_has_inverse I) f) (is_retr_inv_has_inverse I x))).\n    * apply (ap (ap f)).\n      apply inv. exact reduce_htpy.\n    * apply ap_comp.\n  - apply (nat_htpy (right_whisker_htpy (is_sec_inv_has_inverse I) f)).\nDefined.\n\nLemma is_coh_invertible_has_inverse {A B} {f : A -> B} :\n  has_inverse f -> is_coh_invertible f.\nProof.\n  intro I.\n  apply (pair (inv_has_inverse I)).\n  apply (pair (mod_is_sec_inv_has_inverse I)).\n  apply (pair (is_retr_inv_has_inverse I)).\n  exact (coh_inv_has_inverse I).\nDefined.\n\n(** Theorem 8.3.6 *)\n\nLemma is_contr_map_has_inverse {A B} {f : A -> B} :\n  has_inverse f -> is_contr_map f.\nProof.\n  intro I.\n  apply is_contr_map_is_coh_invertible.\n  now apply is_coh_invertible_has_inverse.\nDefined.\n\nTheorem is_contr_map_is_equiv {A B} {f : A -> B} : is_equiv f -> is_contr_map f.\nProof.\n  intro is_equiv_f.\n  apply is_contr_map_has_inverse.\n  now apply has_inverse_is_equiv.\nDefined.\n\n(** Corollary 8.3.7 *)\n\nDefinition total_path' {A} (a : A) : Type :=\n  Sigma A (fun x => x == a).\n\nLemma is_contr_map_idmap {A} : is_contr_map (@idmap A).\nProof.\n  apply is_contr_map_is_equiv.\n  exact is_equiv_idmap.\nDefined.\n\nDefinition is_contr_total_path' {A} (a : A) : is_contr (total_path' a) :=\n  is_contr_map_idmap a.\n\n(** Exercises *)\n\n(** Exercise 8.1 *)\n\nDefinition is_prop_is_contr {A} (c : is_contr A) {x y : A} : is_contr (x == y).\nProof.\n  apply (pair (contraction' c x y)).\n  intro p; destruct p.\n  apply left_inv.\nDefined.\n\n(** Exercise 8.2 *)\n\nDefinition is_contr_retract {A B} (R : sr_pair A B) :\n  is_contr B -> is_contr A.\nProof.\n  destruct R as [i [r H]].\n  intro is_contr_B; destruct is_contr_B as [b c].\n  apply (pair (r b)).\n  intro x.\n  transitivity (r (i x)).\n  - now apply (ap r).\n  - now apply H.\nDefined.\n\n(** Exercise 8.3 *)\n\n(** Exercise 8.3.a *)\n\nDefinition sr_pair_is_equiv {A B} {f : A -> B} :\n  is_equiv f -> sr_pair A B.\nProof.\n  intro H.\n  exact (pair f (retr_is_equiv H)).\nDefined.\n\nDefinition is_contr_is_equiv_const_star {A} :\n  is_equiv (@const A unit star) -> is_contr A.\nProof.\n  intro H.\n  apply (is_contr_retract (sr_pair_is_equiv H)).\n  exact is_contr_unit.\nDefined.\n\nDefinition is_equiv_const_star_is_contr {A} :\n  is_contr A -> is_equiv (@const A unit star).\nProof.\n  intro c.\n  apply (is_equiv_has_inverse (const (center c))).\n  exact (contraction is_contr_unit).\n  exact (contraction c).\nDefined.\n\n(** Exercise 8.3.b *)\n\nDefinition is_contr_is_equiv {A B} {f : A -> B} :\n  is_equiv f -> is_contr B -> is_contr A.\nProof.\n  intro H.\n  apply is_contr_retract.\n  apply (sr_pair_is_equiv H).\nDefined.\n\nDefinition is_contr_equiv {A B} (e : A <~> B) :\n  is_contr B -> is_contr A :=\n  is_contr_is_equiv (is_equiv_map_equiv e).\n\nDefinition is_contr_is_equiv' {A B} {f : A -> B} :\n  is_equiv f -> is_contr A -> is_contr B.\nProof.\n  intro H.\n  exact (is_contr_is_equiv (is_equiv_inv_is_equiv H)).\nDefined.\n\nDefinition is_contr_equiv' {A B} (e : A <~> B) :\n  is_contr A -> is_contr B :=\n  is_contr_is_equiv' (is_equiv_map_equiv e).\n\nDefinition is_equiv_is_contr {A B} (f : A -> B) :\n  is_contr A -> is_contr B -> is_equiv f.\nProof.\n  intros CA CB.\n  apply (@is_equiv_right_factor A B unit\n                                (@const A unit star)\n                                (@const B unit star)\n                                (pair f (@refl_htpy _ _ (@const A unit star)))).\n  - now apply is_equiv_const_star_is_contr.\n  - now apply is_equiv_const_star_is_contr.\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_08_contractible.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.6811133293912756}}
{"text": "Require Import Arith MoreInversion Coq.Lists.List Setoid Coq.Lists.SetoidList Omega.\nRequire Import Len.\n(*Require Import EqDec AutoIndTac.*)\n\nSet Implicit Arguments.\n\nInductive length_eq X Y : list X -> list Y -> Type :=\n  | LenEq_nil : length_eq nil nil\n  | LenEq_cons x XL y YL : length_eq XL YL -> length_eq (x::XL) (y::YL).\n\nSmpl Add 100\n     match goal with\n     | [ H : @length_eq _ _ ?L ?L' |- _ ]\n       => inv_if_one_ctor H L L'\n     end : inv_trivial.\n\nLemma length_eq_refl X (XL:list X)\n  : length_eq XL XL.\nProof.\n  induction XL; eauto using length_eq.\nQed.\n\nLemma length_eq_sym X Y (XL:list X) (YL:list Y)\n  : length_eq XL YL -> length_eq YL XL.\nProof.\n  intros A. induction A;eauto using length_eq.\nQed.\n\nLemma length_eq_trans X Y Z (XL:list X) (YL:list Y) (ZL:list Z)\n  : length_eq XL YL -> length_eq YL ZL -> length_eq XL ZL.\nProof.\n  intros A. revert ZL.\n  induction A; inversion 1; eauto using length_eq.\nQed.\n\nLemma length_length_eq X Y (L:list X) (L':list Y)\n  : length L = length L' -> length_eq L L'.\nProof.\n  revert L'.\n  induction L; destruct L'; inversion 1; eauto using length_eq.\nQed.\n\nLemma length_eq_length X Y (L:list X) (L':list Y)\n  : length_eq L L' -> length L = length L'.\nProof.\n  revert L'.\n  induction L; destruct L'; inversion 1; simpl; eauto.\nQed.\n\nLtac length_equify :=\n  repeat (match goal with\n            | [ H : length ?A = length ?B |- _ ] =>\n              eapply length_length_eq in H\n          end).\n\nHint Immediate length_eq_length : len.\nHint Resolve length_length_eq : len.\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Infra/LengthEq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.6811133256407244}}
{"text": "(* List_Type_ Library *)\n\n(** * Copy of some List library with parameters with Type output *)\n\n\nRequire Export List.\n\nSet Implicit Arguments.\n\n\nSection In.\n\nVariable A:Type.\n\nFixpoint In_Type (a:A) (l:list A) : Type :=\n    match l with\n      | nil => False\n      | b :: m => sum (b = a) (In_Type a m)\n    end.\n\n  (** Characterization of [In] *)\n\n  Theorem in_Type_eq : forall (a:A) (l:list A), In_Type a (a :: l).\n  Proof.\n    simpl; auto.\n  Qed.\n\n  Theorem in_Type_cons : forall (a b:A) (l:list A), In_Type b l -> In_Type b (a :: l).\n  Proof.\n    simpl; auto.\n  Qed.\n\n  Theorem not_in_Type_cons (x a : A) (l : list A):\n    (In_Type x (a::l) -> False) -> (x<>a) * (In_Type x l -> False).\n  Proof.\n    simpl. intuition.\n  Qed.\n\n  Theorem cons_not_in_Type (x a : A) (l : list A):\n    x<>a -> (In_Type x l -> False) -> In_Type x (a::l) -> False.\n  Proof.\n    simpl. intuition.\n  Qed.\n\n  Theorem in_Type_nil : forall a:A, In_Type a nil -> False.\n  Proof.\n    unfold not; intros a H; inversion_clear H.\n  Qed.\n\n  Theorem in_Type_split : forall x (l:list A), In_Type x l ->\n    { l' | l = (fst l')++(x::snd l') }.\n  Proof.\n  induction l; simpl; destruct 1.\n  subst a; auto.\n  exists (nil, l) ; auto.\n  destruct (IHl i) as ((l1,l2),H0).\n  exists (a::l1, l2); simpl. apply f_equal. auto.\n  Qed.\n\n  (** Inversion *)\n  Lemma in_Type_inv : forall (a b:A) (l:list A), In_Type b (a :: l) ->\n    sum (a = b) (In_Type b l).\n  Proof.\n    intros a b l H; inversion_clear H; auto.\n  Qed.\n\n  (** Decidability of [In] *)\n  Theorem in_Type_dec :\n    (forall x y:A, {x = y} + {x <> y}) ->\n    forall (a:A) (l:list A), (In_Type a l) + (In_Type a l -> False).\n  Proof.\n    intro H; induction l as [| a0 l IHl].\n    right; apply in_Type_nil.\n    destruct (H a0 a); simpl; auto.\n    destruct IHl; simpl; auto.\n    right; unfold not; intros [Hc1| Hc2]; auto.\n  Defined.\n\n  (** Compatibility with other operations *)\n  Lemma in_Type_app_or : forall (l m:list A) (a:A), In_Type a (l ++ m) ->\n    In_Type a l + In_Type a m.\n  Proof.\n    intros l m a.\n    elim l; simpl; auto.\n    intros a0 y H H0.\n    now_show (sum (sum (a0 = a) (In_Type a y)) (In_Type a m)).\n    elim H0; auto.\n    intro H1.\n    now_show (sum (sum (a0 = a) (In_Type a y)) (In_Type a m)).\n    elim (H H1); auto.\n  Qed.\n\n  Lemma in_Type_or_app : forall (l m:list A) (a:A),\n    sum (In_Type a l) (In_Type a m) -> In_Type a (l ++ m).\n  Proof.\n    intros l m a.\n    elim l; simpl; intro H.\n    now_show (In_Type a m).\n    elim H; auto; intro H0.\n    now_show (In_Type a m).\n    elim H0. (* subProof completed *)\n    intros y H0 H1.\n    destruct H1 ; intuition.\n  Qed.\n\nEnd In.\n\nHint Resolve in_Type_eq in_Type_cons in_Type_inv in_Type_nil in_Type_app_or\n  in_Type_or_app: datatypes.\n\n  (**************************)\n  (** Facts about [app] *)\n  (**************************)\n\nSection App.\n\n\n  Variable A : Type.\n\n  (** Facts deduced from the result of a concatenation *)\n\n  Theorem app_eq_nil_Type : forall l l':list A, l ++ l' = nil -> (l = nil) * (l' = nil).\n  Proof.\n    destruct l as [| x l]; destruct l' as [| y l']; simpl; auto.\n    intro; discriminate.\n    intros H; discriminate H.\n  Qed.\n\n  Theorem app_eq_unit_Type :\n    forall (x y:list A) (a:A),\n      x ++ y = a::nil -> ((x = nil) * (y = a::nil)) + ((x = a::nil) * (y = nil)).\n  Proof.\n    destruct x as [| a l]; [ destruct y as [| a l] | destruct y as [| a0 l0] ];\n      simpl.\n    intros a H; discriminate H.\n    left; split; auto.\n    right; split; auto.\n    generalize H.\n    generalize (app_nil_r l); intros E.\n    rewrite -> E; auto.\n    intros.\n    injection H as H H0.\n    assert (nil = l ++ a0 :: l0) by auto.\n    apply app_cons_not_nil in H1 as [].\n  Qed.\n\nEnd App.\n\n\n\n(*********************************************)\n(** Reverse Induction Principle on Lists  *)\n(*********************************************)\n\n  Section Reverse_Induction.\n\n  Variable A : Type.\n\n    Lemma rev_list_ind_Type :\n      forall P:list A-> Type,\n\tP nil ->\n\t(forall (a:A) (l:list A), P (rev l) -> P (rev (a :: l))) ->\n\tforall l:list A, P (rev l).\n    Proof.\n      induction l; auto.\n    Qed.\n\n    Theorem rev_ind_Type :\n      forall P:list A -> Type,\n\tP nil ->\n\t(forall (x:A) (l:list A), P l -> P (l ++ x :: nil)) -> forall l:list A, P l.\n    Proof.\n      intros.\n      generalize (rev_involutive l).\n      intros E; rewrite <- E.\n      apply (rev_list_ind_Type P).\n      - auto.\n      - simpl.\n        intros.\n        apply (X0 a (rev l0)).\n        auto.\n    Qed.\n\n  End Reverse_Induction.\n\n\n(***************************************************)\n(** * Applying functions to the elements of a list *)\n(***************************************************)\n\n(************)\n(** ** Map  *)\n(************)\n\nSection Map.\n  Variables (A : Type) (B : Type).\n  Variable f : A -> B.\n\n  Lemma in_Type_map :\n    forall (l:list A) (x:A), In_Type x l -> In_Type (f x) (map f l).\n  Proof.\n    induction l; firstorder (subst; auto).\n  Qed. \n\n  Lemma in_Type_map_inv : forall l y, In_Type y (map f l) ->\n    { x : _ & prod (f x = y) (In_Type x l) }.\n  Proof.\n    induction l; firstorder (subst; auto).\n  Qed.\n\n  Lemma in_Type_flat_map : forall (f:A->list B)(l:list A)(y:B),\n    In_Type y (flat_map f l) -> { x : _ & prod (In_Type x l) (In_Type y (f x)) }.\n  Proof using A B.\n    induction l; simpl; intros.\n    contradiction.\n    destruct (in_Type_app_or _ _ _ X).\n    - exists a; auto.\n    - destruct (IHl y i) as (x,(H1,H2)).\n      exists x; auto.\n  Qed.\n\n  Lemma flat_map_in_Type : forall (f:A->list B)(l:list A)(y:B),\n    { x : _ & prod (In_Type x l) (In_Type y (f x)) } -> In_Type y (flat_map f l).\n  Proof using A B.\n    induction l; simpl; intros.\n    destruct X as (x,(X,_)); contradiction.\n    apply in_Type_or_app.\n    destruct X as (x,(H0,H1)); destruct H0.\n    - subst; auto.\n    - right ; apply (IHl y (existT _ x (i,H1))).\n  Qed.\n\nEnd Map.\n\nLemma map_ext_in_Type :\n  forall (A B : Type)(f g:A->B) l, (forall a, In_Type a l -> f a = g a) -> map f l = map g l.\nProof.\n  induction l; simpl; auto.\n  intros; rewrite H by intuition; rewrite IHl; auto.\nQed.\n\nLemma ext_in_Type_map :\n  forall (A B : Type)(f g:A->B) l, map f l = map g l -> forall a, In_Type a l -> f a = g a.\nProof. induction l; intros [=] ? []; subst; auto. Qed.\n\nArguments ext_in_Type_map [A B f g l].\n\n\n(******************************)\n(** ** Set inclusion on list  *)\n(******************************)\n\nSection SetIncl.\n\n  Variable A : Type.\n\n  Definition incl_Type (l m:list A) := forall a:A, In_Type a l -> In_Type a m.\n  Hint Unfold incl_Type.\n\n  Lemma incl_Type_refl : forall l:list A, incl_Type l l.\n  Proof.\n    auto.\n  Qed.\n  Hint Resolve incl_Type_refl.\n\n  Lemma incl_Type_tl : forall (a:A) (l m:list A), incl_Type l m -> incl_Type l (a :: m).\n  Proof.\n    unfold incl_Type ; intros.\n    simpl ; intuition.\n  Qed.\n  Hint Immediate incl_Type_tl.\n\n  Lemma incl_Type_tran : forall l m n:list A, incl_Type l m -> incl_Type m n -> incl_Type l n.\n  Proof.\n    auto.\n  Qed.\n\n  Lemma incl_Type_appl : forall l m n:list A, incl_Type l n -> incl_Type l (n ++ m).\n  Proof.\n    auto with datatypes.\n  Qed.\n  Hint Immediate incl_Type_appl.\n\n  Lemma incl_Type_appr : forall l m n:list A, incl_Type l n -> incl_Type l (m ++ n).\n  Proof.\n    auto with datatypes.\n  Qed.\n  Hint Immediate incl_Type_appr.\n\n  Lemma incl_Type_cons :\n    forall (a:A) (l m:list A), In_Type a m -> incl_Type l m -> incl_Type (a :: l) m.\n  Proof.\n    unfold incl_Type; simpl; intros a l m H H0 a0 H1.\n    now_show (In_Type a0 m).\n    elim H1.\n    now_show (a = a0 -> In_Type a0 m).\n    elim H1; auto; intro H2.\n    now_show (a = a0 -> In_Type a0 m).\n    elim H2; auto. (* solves subgoal *)\n    now_show (In_Type a0 l -> In_Type a0 m).\n    auto.\n  Qed.\n  Hint Resolve incl_Type_cons.\n\n  Lemma incl_Type_app : forall l m n:list A, incl_Type l n -> incl_Type m n ->\n    incl_Type (l ++ m) n.\n  Proof.\n    unfold incl_Type; simpl; intros l m n H H0 a H1.\n    now_show (In_Type a n).\n    elim (in_Type_app_or _ _ _ H1); auto.\n  Qed.\n  Hint Resolve incl_Type_app.\n\nEnd SetIncl.\n\nHint Resolve incl_Type_refl incl_Type_tl incl_Type_tran incl_Type_appl incl_Type_appr\n  incl_Type_cons incl_Type_app: datatypes.\n\n\n\nSection Exists_Forall.\n\n  (** * Existential and universal predicates over lists *)\n\n  Variable A:Type.\n\n  Section One_predicate.\n\n    Variable P:A->Type.\n\n    Inductive Exists_Type : list A -> Type :=\n      | Exists_Type_cons_hd : forall x l, P x -> Exists_Type (x::l)\n      | Exists_Type_cons_tl : forall x l, Exists_Type l -> Exists_Type (x::l).\n\n    Hint Constructors Exists_Type.\n\n    Lemma Exists_Type_nil : Exists_Type nil -> False.\n    Proof. inversion 1. Qed.\n\n    Lemma Exists_Type_cons x l:\n      Exists_Type (x::l) -> P x + Exists_Type l.\n    Proof. inversion 1; auto. Qed.\n\n    Lemma Exists_Type_dec l:\n      (forall x:A, P x + (P x -> False)) ->\n      Exists_Type l + (Exists_Type l -> False).\n    Proof.\n      intro Pdec. induction l as [|a l' Hrec].\n      - right. now apply Exists_Type_nil.\n      - destruct Hrec as [Hl'|Hl'].\n        * left. now apply Exists_Type_cons_tl.\n        * destruct (Pdec a) as [Ha|Ha].\n          + left. now apply Exists_Type_cons_hd.\n          + right. now inversion_clear 1.\n    Qed.\n\n    Inductive Forall_Type : list A -> Type :=\n      | Forall_Type_nil : Forall_Type nil\n      | Forall_Type_cons : forall x l, P x -> Forall_Type l -> Forall_Type (x::l).\n\n    Hint Constructors Forall_Type.\n\n    Lemma Forall_Type_forall (l:list A):\n      Forall_Type l -> forall x, In_Type x l -> P x.\n    Proof.\n      induction 1; firstorder; subst; auto.\n    Qed.\n\n    Lemma forall_Forall_Type (l:list A):\n      (forall x, In_Type x l -> P x) -> Forall_Type l.\n    Proof.\n      induction l; firstorder.\n    Qed.\n\n    Lemma Forall_Type_inv : forall (a:A) l, Forall_Type (a :: l) -> P a.\n    Proof.\n      intros ? ? H ; inversion H ; trivial.\n    Qed.\n\n    Lemma Forall_Type_dec :\n      (forall x:A, P x + (P x -> False)) ->\n      forall l:list A, Forall_Type l + (Forall_Type l -> False).\n    Proof.\n      intro Pdec. induction l as [|a l' Hrec].\n      - left. apply Forall_Type_nil.\n      - destruct Hrec as [Hl'|Hl'].\n        + destruct (Pdec a) as [Ha|Ha].\n          * left. now apply Forall_Type_cons.\n          * right. abstract now inversion 1.\n        + right. abstract now inversion 1.\n    Defined.\n\n  End One_predicate.\n\n  Lemma Forall_Exists_neg_Type (P:A->Type)(l:list A) :\n   Forall_Type (fun x => P x -> False) l -> Exists_Type P l -> False.\n  Proof.\n   induction l ; intros HF HE ; inversion HE ; inversion HF ; subst ; auto.\n  Qed.\n\n  Lemma Exists_neg_Forall_Type (P:A->Type)(l:list A) :\n   (Exists_Type P l -> False) -> Forall_Type (fun x => P x -> False) l.\n  Proof.\n   induction l ; intros HE ; constructor.\n   - intros Ha ; apply HE.\n     now constructor.\n   - apply IHl ; intros HF ; apply HE.\n     now constructor.\n  Qed.\n\n  Lemma Exists_Forall_neg_Type (P:A->Type)(l:list A) :\n    Exists_Type (fun x => P x -> False) l -> Forall_Type P l -> False.\n  Proof.\n   induction l ; intros HE HF ; inversion HE ; inversion HF ; subst ; auto.\n  Qed.\n\n  Lemma Forall_neg_Exists_Type (P:A->Type)(l:list A) :\n    (forall x, P x + (P x -> False)) ->\n    (Forall_Type P l -> False) -> Exists_Type (fun x => P x -> False) l.\n  Proof.\n   intro Dec.\n   induction l ; intros HF.\n   - contradiction HF. constructor.\n   - destruct (Dec a) as [ Ha | Hna ].\n     + apply Exists_Type_cons_tl.\n       apply IHl.\n       intros HFl.\n       apply HF ; now constructor.\n     + now apply Exists_Type_cons_hd.\n  Qed.\n\n  Lemma neg_Forall_Exists_neg_Type (P:A->Type) (l:list A) :\n    (forall x:A, P x + (P x -> False)) ->\n    (Forall_Type P l -> False) ->\n    Exists_Type (fun x => (P x -> False)) l.\n  Proof.\n    intro Dec.\n    apply Forall_neg_Exists_Type; intros.\n    destruct (Dec x); auto.\n  Qed.\n\n  Lemma Forall_Exists_Type_dec (P:A->Type) :\n    (forall x:A, P x + (P x -> False)) ->\n    forall l:list A,\n    Forall_Type P l + Exists_Type (fun x => P x -> False) l.\n  Proof.\n    intros Pdec l.\n    destruct (Forall_Type_dec P Pdec l); [left|right]; trivial.\n    now apply neg_Forall_Exists_neg_Type.\n  Defined.\n\n  Lemma Forall_Type_arrow : forall (P Q : A -> Type), (forall a, P a -> Q a) ->\n    forall l, Forall_Type P l -> Forall_Type Q l.\n  Proof.\n    induction l ; intros H ; inversion H ; constructor ; auto.\n  Qed.\n\nEnd Exists_Forall.\n\nHint Constructors Exists_Type.\nHint Constructors Forall_Type.\n\nSection Forall2.\n\n  (** [Forall2]: stating that elements of two lists are pairwise related. *)\n\n  Variables A B : Type.\n  Variable R : A -> B -> Type.\n\n  Inductive Forall2_Type : list A -> list B -> Type :=\n    | Forall2_Type_nil : Forall2_Type nil nil\n    | Forall2_Type_cons : forall x y l l',\n      R x y -> Forall2_Type l l' -> Forall2_Type (x::l) (y::l').\n\n  Hint Constructors Forall2_Type.\n\n  Theorem Forall2_Type_refl : Forall2_Type nil nil.\n  Proof. intros; apply Forall2_Type_nil. Qed.\n\n  Theorem Forall2_Type_app_inv_l : forall l1 l2 l0,\n    Forall2_Type (l1 ++ l2) l0 ->\n    { l'' : { l' : _ & Forall2_Type l1 (fst l') & Forall2_Type l2 (snd l') }\n          | l0 = fst (projT1 (sigT_of_sigT2 l'')) ++ snd (projT1 (sigT_of_sigT2 l'')) }.\n  Proof.\n    induction l1; intros.\n    - assert (Forall2_Type nil nil) as H1 by auto.\n      assert (Forall2_Type l2 l0) as H2 by auto.\n      exists (existT2 _ _ (nil,l0) H1 H2).\n      reflexivity.\n    - simpl in X; inversion X; subst; clear X.\n      apply IHl1 in X1 as (l0' & Hl).\n      destruct l0' as [ l'' H1 H2 ].\n      simpl in Hl.\n      assert (Forall2_Type (a :: l1) (y :: fst l'')) as H3 by auto.\n      exists (existT2 _ _ (y :: fst l'', snd l'') H3 H2).\n      simpl ; rewrite Hl ; auto.\n  Qed.\n\n  Theorem Forall2_Type_app_inv_r : forall l1 l2 l0,\n    Forall2_Type l0 (l1 ++ l2) ->\n    { l'' : { l' : _ & Forall2_Type (fst l') l1 & Forall2_Type (snd l') l2 }\n          | l0 = fst (projT1 (sigT_of_sigT2 l'')) ++ snd (projT1 (sigT_of_sigT2 l'')) }.\n  Proof.\n    induction l1; intros.\n    - assert (Forall2_Type nil nil) as H1 by auto.\n      assert (Forall2_Type l0 l2) as H2 by auto.\n      exists (existT2 _ _ (nil,l0) H1 H2).\n      reflexivity.\n    - simpl in X; inversion X; subst; clear X.\n      apply IHl1 in X1 as (l0' & Hl).\n      destruct l0' as [ l'' H1 H2 ].\n      simpl in Hl.\n      assert (Forall2_Type (x :: fst l'') (a :: l1)) as H3 by auto.\n      exists (existT2 _ _ (x :: fst l'', snd l'') H3 H2).\n      simpl ; rewrite Hl ; auto.\n  Qed.\n\n  Theorem Forall2_Type_app : forall l1 l2 l1' l2',\n    Forall2_Type l1 l1' -> Forall2_Type l2 l2' -> Forall2_Type (l1 ++ l2) (l1' ++ l2').\n  Proof.\n    intros. induction l1 in l1', X, X0 |- *; inversion X; subst; simpl; auto.\n  Qed.\nEnd Forall2.\n\nHint Constructors Forall2.\n\n", "meta": {"author": "olaure01", "repo": "yalla", "sha": "9c6a66fa3a3d68b5a21ce7fa695402a0f2dda4d7", "save_path": "github-repos/coq/olaure01-yalla", "path": "github-repos/coq/olaure01-yalla/yalla-9c6a66fa3a3d68b5a21ce7fa695402a0f2dda4d7/ollibs/List_Type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.6811133145946064}}
{"text": "(* \n  Autor(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\n(* \n  Reduction from:\n    Finite Multiset Constraint Solvability (FMsetC_SAT)\n  to:\n    Linear Polynomial (over N) Constraint Solvability (LPolyNC_SAT)\n*)\n\nRequire Import List PeanoNat Lia.\nImport ListNotations.\n\nRequire Import Undecidability.SetConstraints.FMsetC.\nRequire Import Undecidability.PolynomialConstraints.LPolyNC.\n\nRequire Import Undecidability.Synthetic.Definitions.\n\nFrom Undecidability.PolynomialConstraints.Util Require Import PolyFacts.\nRequire Undecidability.SetConstraints.Util.mset_eq_utils.\n\nRequire Import ssreflect ssrbool ssrfun.\n\nSet Default Goal Selector \"!\".\n\nModule Argument.\nLocal Arguments poly_add !p !q.\n\nLocal Notation \"p ≃ q\" := (poly_eq p q) (at level 65).\nLocal Notation \"A ≡ B\" := (mset_eq A B) (at level 65).\n\nDefinition encode_msetc (c : msetc) : polyc :=\n  match c with\n  | msetc_zero x => polyc_one x\n  | msetc_sum x y z => polyc_sum x y z\n  | msetc_h x y => polyc_prod x y\n  end.\n\n(* count the number of occurrences of each element *)\nFixpoint mset_to_poly (A: list nat) := \n  match A with\n  | [] => []\n  | a :: A => poly_add (repeat 0 a ++ [1]) (mset_to_poly A)\n  end.\n\nLemma mset_to_poly_shift {a A B} : mset_to_poly (A ++ a :: B) ≃ mset_to_poly (a :: A ++ B).\nProof.\n  elim: A; first done.\n  move=> c A + i => /(_ i) /=. rewrite ?poly_add_nthP. by lia.\nQed.\n\nLemma mset_to_poly_appP {A B} : mset_to_poly (A ++ B) ≃ poly_add (mset_to_poly A) (mset_to_poly B).\nProof. \n  elim: A; first done.\n  move=> a A + i => /(_ i) /=. rewrite ?poly_add_nthP. by lia.\nQed.\n\nLemma mset_to_poly_mapP {A} : mset_to_poly (map S A) ≃ 0 :: mset_to_poly A.\nProof. \n  elim: A; first by (case; [done | by case]).\n  move=> a A + i => /(_ i). case: i.\n  - by rewrite /map -/(map _ _) ?poly_add_nthP.\n  - move=> i. rewrite /map -/(map _ _) /mset_to_poly -/(mset_to_poly).\n    rewrite /= ?poly_add_nthP /=. by lia.\nQed.\n\nLemma poly_add_0I {p q r} : r ≃ [] -> p ≃ q -> p ≃ poly_add q r.\nProof.\n  move=> + + i => /(_ i) + /(_ i). rewrite poly_add_nthP.\n  case: i=> /=; by lia.\nQed.\n\nLemma poly_shiftI {p} : (0 :: p) ≃ poly_mult [0; 1] p.\nProof.\n  rewrite /poly_mult.\n  have ->: map (fun x => 0 * x) p = repeat 0 (length p).\n  { elim: p; [done | by move=> > /= ->]. }\n  rewrite [poly_add (repeat _ _) _] poly_add_comm.\n  apply: poly_add_0I; first by apply: repeat_0P.\n  under map_ext => a do have -> : 1 * a = a by lia.\n  rewrite -/(poly_eq _ _) map_id. apply: poly_eq_consI; first done.\n  apply: poly_add_0I; last done.\n  by apply: (repeat_0P (n := 1)).\nQed.\n\nLemma mset_to_poly_eqI {A B} : A ≡ B -> mset_to_poly A ≃ mset_to_poly B.\nProof.\n  elim: A B.\n  - by move=> B /mset_eq_utils.eq_nilE ->.\n  - move=> a A IH B /mset_eq_utils.eq_consE [B1 [B2 [-> /IH {}IH]]].\n    apply: poly_eq_sym.\n    apply: (poly_eq_trans mset_to_poly_shift) => /=. \n    move=> i. move: (IH i). rewrite ?poly_add_nthP. by lia.\nQed.\n\nLemma completeness {l} : FMsetC_SAT l -> LPolyNC_SAT (map encode_msetc l).\nProof.\n  move=> [φ]. rewrite -Forall_forall => Hφ.\n  exists (fun x => mset_to_poly (φ x)). rewrite -Forall_forall Forall_map.\n  apply: Forall_impl; last by eassumption. case.\n  - by move=> x /= /mset_eq_utils.eq_symm /mset_eq_utils.eq_singletonE ->.\n  - move=> x y z /= /mset_to_poly_eqI. move /poly_eq_trans. apply.\n    by apply mset_to_poly_appP.\n  - move=> x y /= /mset_to_poly_eqI. move /poly_eq_trans. apply.\n    apply: (poly_eq_trans _ poly_shiftI).\n    by apply: mset_to_poly_mapP.\nQed.\n    \nFixpoint poly_to_mset (p: list nat) := \n  match p with\n  | [] => []\n  | a :: p => (repeat 0 a) ++ map S (poly_to_mset p)\n  end.\n\nLemma count_occ_poly_to_msetP {a p}: count_occ Nat.eq_dec (poly_to_mset p) a = nth a p 0.\nProof.\n  elim: a p.\n  - case; first done.\n    move=> + p /=. elim; first by elim: (poly_to_mset p).\n    by move=> ? /= ->.\n  - move=> i IH. case; first done.\n    move=> a p /=. rewrite count_occ_app.\n    rewrite -(count_occ_map S Nat.eq_dec) ?IH; first by lia.\n    by elim a.\nQed.\n\nLemma poly_to_mset_eqI {p q} : p ≃ q -> poly_to_mset p ≡ poly_to_mset q.\nProof. move=> + a. by rewrite ?count_occ_poly_to_msetP. Qed.\n\nLemma poly_to_mset_addP {p q} : poly_to_mset (poly_add p q) ≡ poly_to_mset p ++ poly_to_mset q.\nProof. move=> a. by rewrite count_occ_app ? count_occ_poly_to_msetP poly_add_nthP. Qed.\n\nLemma poly_to_mset_consP {p} : poly_to_mset (0 :: p) = map S (poly_to_mset p).\nProof. done. Qed.\n\nLemma soundness {l} : LPolyNC_SAT (map encode_msetc l) -> FMsetC_SAT l.\nProof.\n  move=> [ψ]. rewrite -Forall_forall Forall_map => Hψ.\n  exists (fun x => poly_to_mset (ψ x)). rewrite -Forall_forall.\n  apply: Forall_impl; last by eassumption. case.\n  - by move=> x /= /poly_to_mset_eqI.\n  - move=> x y z /= /poly_to_mset_eqI. move /mset_eq_utils.eq_trans. apply.\n    by apply: poly_to_mset_addP.\n  - move=> x y /= /poly_to_mset_eqI. move /mset_eq_utils.eq_trans. apply.\n    move: (ψ y) => p. rewrite -poly_to_mset_consP. apply: poly_to_mset_eqI.\n    apply: poly_eq_sym.\n    by apply: (poly_eq_trans _ poly_shiftI).\nQed.\n\nEnd Argument.\n\n(* many-one reduction from FMsetC_SAT to LPolyNC_SAT *)\nTheorem reduction : FMsetC_SAT ⪯ LPolyNC_SAT.\nProof.\n  exists (map Argument.encode_msetc) => l. constructor.\n  - exact Argument.completeness.\n  - exact Argument.soundness.\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/PolynomialConstraints/Reductions/FMsetC_SAT_to_LPolyNC_SAT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6810962204391006}}
{"text": "Require Import Arith.\nRequire Import Reals.\nRequire Import Psatz.\nRequire Import Coq.Init.Nat.\nRequire Import QArith. \nRequire Import QArith.QArith_base.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import ZArith.\nRequire Import BinNat Bool Equalities GenericMinMax\n OrdersFacts ZAxioms ZProperties.\nRequire Import BinIntDef BinInt Zorder Zcompare Znat Zmin Zmax Zminmax\n Zabs Zeven auxiliary ZArith_dec Zbool Zmisc Wf_Z  \n Zcomplements Zsqrt_compat Zpow_def Zpow_alt Zpower Zdiv Zwf  Int Zpow_facts Zdigits.\nRequire BinIntDef.\nRequire Lra.\nRequire Import Ring.\nAxiom Q_equality : forall (q1 q2 : Q), q1 == q2 -> q1 = q2.\n\n\nLemma Qlt_dec: forall (q1 q2:Q), {q1<q2} + {~ q1 < q2}.\nProof.\nintros.\ncase (Qlt_le_dec q1 q2).\n-intro. auto.\n-intro. apply Qle_not_lt in q. auto.\nDefined. \n\nLemma Q_mult_dist: forall (a b c : Q) , a * (b - c) == a * b - a * c.\nProof. intros. lra. Qed.\n\nLemma Q_mult: forall (a b c d : Q), (a - b) * (c - d) == a*c - a*d - b*c + b*d.\nProof. intros.\n lra. Qed. \nLemma Qle_neq_lt : forall (r1 r2 : Q),\n  r1 <= r2 -> r1 <> r2 -> r1 < r2.\nProof.\nintros r1 r2 H1 H2. apply Qle_lteq in H1. destruct H1.  \ntauto. apply Q_equality in H. tauto.\nQed.\n\nLemma Q_gt_0_plus : forall (r1 r2 : Q),\n  r1 > 0 -> r2 > 0 -> r1 + r2 > 0.\nProof.\nintros r1 r2 H1 H2. lra.\nQed.\nLemma Q_gt_0_mult : forall (r1 r2 : Q),\n  r1 > 0 -> r2 > 0 -> r1 * r2 > 0.\nProof.\nintros. assert (H1:= Qmult_lt_compat_r 0 r1 r2) . \napply H1 in H0. - lra. - tauto.\nQed.\n\nLemma Q_gt_0_div : forall (r1 r2 : Q),\n  r1 > 0 -> r2 > 0 -> r1 * / r2 > 0.\nProof.\nintros r1 r2 H1 H2.\napply Q_gt_0_mult.\n assumption. apply Qinv_lt_0_compat . tauto.\nQed.\nLemma Q_lt_0_plus : forall (r1 r2 : Q),\n  r1 < 0 -> r2 < 0 -> r1 + r2 < 0.\nProof.\nintros r1 r2 H1 H2. lra.\nQed.\nLemma Z_neg_mult: forall (a b:Z) , (a < 0)%Z -> (b<0)%Z -> (a*b >0)%Z.\nProof.\nintros.\nassert(H2:=Z.mul_neg_neg a b). apply Zgt_iff_lt. tauto.\nQed.\n\nLemma Q_lt_0_mult : forall (r1 r2 : Q),\n  r1 < 0 -> r2 < 0 -> r1 * r2 > 0.\nProof.\nintros. \n unfold Qgt in *. simpl in *. rewrite Z.mul_comm in H.\n rewrite Z.mul_1_l in H.  rewrite Z.mul_comm in H0.\n rewrite Z.mul_1_l in H0. rewrite <- Z.gt_lt_iff in H. rewrite <- Z.gt_lt_iff in H0.\nrewrite <- Z.gt_lt_iff . rewrite Z.mul_comm. rewrite Z.mul_1_l.\napply Zgt_iff_lt. apply (Z.mul_neg_neg (Qnum r1) (Qnum r2)).\napply Zgt_iff_lt in H. tauto. apply Zgt_iff_lt in H0. tauto.\nQed.\nLemma Q_lt_0_neg: forall(a:Q) , a<0 -> -a > 0.\nProof. intros.\napply Qlt_minus_iff in H.\nassert (H1:= (Qplus_0_l (-a)) ). rewrite H1 in H. tauto.\nQed.\nLemma Q_gt_0_neg: forall(a:Q) , a>0 -> -a < 0.\nProof. intros. lra.\nQed.\nLemma Q_mult_negpos: forall (a b:Q) , a<0 -> b>0 -> a * b < 0.\nProof.\nintros. \n apply Q_lt_0_neg in H.   assert (H2:-a * b > 0).\n apply (Q_gt_0_mult ). tauto. tauto. \nlra.\nQed.\nLemma Q_lt_0_div : forall (r1 r2 : Q),\n  r1 < 0 -> r2 < 0 -> 0 <r1  */ r2 .\nProof.\nintros.\napply Q_lt_0_mult. tauto. apply Q_lt_0_neg in H0.\napply Qinv_lt_0_compat in H0. apply Q_gt_0_neg in H0. \ninduction r2. simpl in *. unfold Qinv in *. simpl.\ninduction Qnum. simpl in *. lra. tauto. tauto.\nQed.\nLemma Q_mult_div : forall (r1 r2 r3 : Q),\n  r1 = r2 * r3 -> r2 > 0 -> r1 * / r2 = r3.\nProof.\nintros r1 r2 r3 H1 H2.\nsubst r1. assert (H:=Qmult_comm r2 r3). apply Q_equality in H.\nrewrite H. assert (H1:= Qdiv_mult_l r3 r2). apply Q_equality. apply H1.\nlra.\nQed.\n \nLemma Q_mult_dist_eq: forall(r1 r2 r3 r4 :Q),\n(r1-r2)*(r3-r4)=r1*r3-r1*r4-r2*r3+r2*r4.\nProof.\nintros. assert (H: (r1 - r2) * (r3 - r4) == r1 * r3 - r1 * r4 - r2 * r3 + r2 * r4).\napply Q_mult.\napply Q_equality. tauto.\nQed.\n\nLemma Q_mult_par: forall (a b c :Q), a* (b * c) == a* b * c.\nProof. intros. lra.\nQed.\n\nLemma Qmult_minus_dist : forall (a b c :Q) , a * (b  -  c) == a* b - a*c.\nProof.\nintros. lra.\nQed.\nLemma Q_mult_sign_ch:forall (a b :Q) , a * (-b) == (-a) * b.\nProof.\nintros. lra. \nQed. \n\nLemma Q_inv_sign_ch:forall (a b :Q) , a */ (-b) == (-a) */ b.\nProof. intros. induction b. induction a.\n\n unfold Qinv in *. simpl.\ninduction (Qnum ). simpl in *. lra. simpl. unfold Qeq. simpl. lia.\nsimpl. unfold Qeq. simpl. lia.\nQed. \nLemma Q_div_sign_ch: forall (a b :Q) ,  a / -b == -a / b.\nProof. intros.\n unfold Qdiv. rewrite Q_inv_sign_ch. lra.\nQed.\nLemma Q_div_plus_denum: forall(a b c:Q) , a/b + c/b == (a+c)/b.\nProof. intros. unfold Qdiv. lra.\nQed.\nLemma Q_div_minus_denum: forall(a b c:Q) , a/b - c/b == (a-c)/b.\nProof. intros. unfold Qdiv. lra.\nQed.\nLemma Q_mult_div_nom: forall (a b c:Q) , a * (b/c) == (a *b) / c.\nProof. intros.\nunfold Qdiv. lra.\nQed.\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/Convex Hull/MyQ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6810962156660837}}
{"text": "(** * 6.887 Formal Reasoning About Programs, Spring 2017 - Pset 8 *)\n\nRequire Import Frap.\n\n(* Authors: \n * Peng Wang (wangpeng@csail.mit.edu)\n * Adam Chlipala (adamc@csail.mit.edu) \n *)\n\nSet Implicit Arguments.\n\n(** * Subtyping *)\n\n(* We can't resist fitting in another crucial aspect of type systems:\n * *subtyping*, which formalizes when any value of one type should also be\n * permitted as a value of some other type.  Languages like Java include\n * *nominal* subtyping, based on declared type hierarchies.  Instead, here we\n * will prove soundness of *structural* subtyping, whose rules we'll get to\n * shortly.  The simply typed lambda calculus will be our starting point. *)\n\n(* Expression syntax *)\nInductive exp  :=\n(* Our old friends from simply typed lambda calculus *)\n| Var (x : var)\n| Abs (x : var) (e1 : exp)\n| App (e1 e2 : exp)\n\n(* New features, surrounding *tuple* types, which build composite types out of\n * constituents *)\n| TupleNil\n(* Empty tuple (no fields *)\n| TupleCons (e1 e2 : exp)\n(* Nonempty tuple, where [e1] is the first field of the tuple, and [e2] is a\n * nested tuple with all the remaining fields *)\n| Proj (e : exp) (n : nat)\n(* Grab the [n]th field of tuple [e]. *)\n.\n\n(* Values (final results of evaluation) *)\nInductive value : exp -> Prop :=\n| VAbs : forall x e1, value (Abs x e1)\n| VTupleNil : value TupleNil\n| VTupleCons : forall e1 e2, value e1 -> value e2 -> value (TupleCons e1 e2)\n.\n\n(* The next few definitions are quite routine and should be safe to skim through\n * quickly; but start paying more attention when we get to defining the\n * subtyping relation! *)\n\n(* Substitution (not capture-avoiding, for the usual reason) *)\nFixpoint subst (e1 : exp) (x : var) (e2 : exp) : exp :=\n  match e2 with\n  | Var y => if y ==v x then e1 else Var y\n  | Abs y e2' => Abs y (if y ==v x then e2' else subst e1 x e2')\n  | App e2' e2'' => App (subst e1 x e2') (subst e1 x e2'')\n  | TupleNil => TupleNil\n  | TupleCons e2' e2'' => TupleCons (subst e1 x e2') (subst e1 x e2'')\n  | Proj e2' n => Proj (subst e1 x e2') n\n  end.\n\n(* Evaluation contexts *)\nInductive context :=\n| Hole\n| App1 (C : context) (e2 : exp)\n| App2 (v1 : exp) (C : context)\n| TupleCons1 (C : context) (e2 : exp)\n| TupleCons2 (v1 : exp) (C : context)\n| Proj1 (C : context) (n : nat)\n.\n\n(* Plugging an expression into a context *)\nInductive plug : context -> exp -> exp -> Prop :=\n| PlugHole : forall e, plug Hole e e\n| PlugApp1 : forall e e' C e2,\n    plug C e e'\n    -> plug (App1 C e2) e (App e' e2)\n| PlugApp2 : forall e e' v1 C,\n    value v1\n    -> plug C e e'\n    -> plug (App2 v1 C) e (App v1 e')\n| PlugTupleCons1 : forall C e e' e2,\n    plug C e e'\n    -> plug (TupleCons1 C e2) e (TupleCons e' e2)\n| PlugTupleCons2 : forall v1 C e e',\n    value v1\n    -> plug C e e'\n    -> plug (TupleCons2 v1 C) e (TupleCons v1 e')\n| PlugProj : forall C e e' n,\n    plug C e e'\n    -> plug (Proj1 C n) e (Proj e' n)\n.\n\n(* Small-step, call-by-value evaluation *)\nInductive step0 : exp -> exp -> Prop :=\n| Beta : forall x e v,\n    value v\n    -> step0 (App (Abs x e) v) (subst v x e)\n\n(* To project field 0 out of a tuple, just grab the first component. *)\n| Proj0 : forall v1 v2,\n    value v1\n    -> value v2\n    -> step0 (Proj (TupleCons v1 v2) 0) v1\n\n(* To project field [1+n], drop the first component and continue with [n]. *)\n| ProjS : forall v1 v2 n,\n    value v1\n    -> value v2\n    -> step0 (Proj (TupleCons v1 v2) (1 + n)) (Proj v2 n)\n.\n\nInductive step : exp -> exp -> Prop :=\n| StepRule : forall C e1 e2 e1' e2',\n    plug C e1 e1'\n    -> plug C e2 e2'\n    -> step0 e1 e2\n    -> step e1' e2'.\n\nDefinition trsys_of (e : exp) :=\n  {| Initial := {e}; Step := step |}.\n\n(* Syntax of types *)\nInductive type :=\n| Fun (dom ran : type)\n| TupleTypeNil\n| TupleTypeCons (t1 t2 : type)\n.\n\nInductive subtype : type -> type -> Prop :=\n\n(* Two function types are related if their components are related pairwise.\n * Counterintuitively, we *reverse* the comparison order for function domains!\n * It may be worth working through some examples to see why the relation would\n * otherwise be unsound. *)\n| StFun : forall t1' t2' t1 t2,\n    subtype t1 t1' ->\n    subtype t2' t2 ->\n    subtype (Fun t1' t2') (Fun t1 t2)\n\n(* An empty tuple type is its own subtype. *)\n| StTupleNilNil :\n    subtype TupleTypeNil TupleTypeNil\n\n(* However, a nonempty tuple type is also a subtype of the empty tuple type.\n * This rule gives rise to *width* subtyping, where we can drop some fields of\n * a tuple type to produce a subtype. *)\n| StTupeNilCons : forall t1 t2,\n    subtype (TupleTypeCons t1 t2) TupleTypeNil\n\n(* We also have *depth* subtyping: we can replace tuple components with\n * subtypes. *)\n| StTupleCons : forall t1' t2' t1 t2,\n    subtype t1' t1 ->\n    subtype t2' t2 ->\n    subtype (TupleTypeCons t1' t2') (TupleTypeCons t1 t2)\n.\n\n(* Here's a more compact notation for subtyping. *)\nInfix \"$<:\" := subtype (at level 70).\n\nHint Constructors subtype.\n\n(* Projecting out the nth field of a tuple type *)\nInductive proj_t : type -> nat -> type -> Prop :=\n| ProjT0 : forall t1 t2,\n    proj_t (TupleTypeCons t1 t2) 0 t1\n| ProjTS : forall t1 t2 n t,\n    proj_t t2 n t ->\n    proj_t (TupleTypeCons t1 t2) (1 + n) t\n.\n\n(* Expression typing relation *)\nInductive hasty : fmap var type -> exp -> type -> Prop :=\n| HtVar : forall G x t,\n    G $? x = Some t ->\n    hasty G (Var x) t\n| HtAbs : forall G x e1 t1 t2,\n    hasty (G $+ (x, t1)) e1 t2 ->\n    hasty G (Abs x e1) (Fun t1 t2)\n| HtApp : forall G e1 e2 t1 t2,\n    hasty G e1 (Fun t1 t2) ->\n    hasty G e2 t1 ->\n    hasty G (App e1 e2) t2\n| HtTupleNil : forall G,\n    hasty G TupleNil TupleTypeNil\n| HtTupleCons: forall G e1 e2 t1 t2,\n    hasty G e1 t1 ->\n    hasty G e2 t2 ->\n    hasty G (TupleCons e1 e2) (TupleTypeCons t1 t2)\n| HtProj : forall G e n t t',\n    hasty G e t' ->\n    proj_t t' n t ->\n    hasty G (Proj e n) t\n\n(* This is the crucial rule: when an expression has a type, it also has any\n * supertype of that type.  We call this rule *subsumption*. *)\n| HtSub : forall G e t t',\n    hasty G e t' ->\n    t' $<: t ->\n    hasty G e t\n.\n\nHint Constructors value plug step0 step proj_t hasty.\n\n(* BEGIN handy tactic that we suggest for these proofs *)\nLtac t0 := match goal with\n           | [ H : ex _ |- _ ] => invert H\n           | [ H : _ /\\ _ |- _ ] => invert H\n           | [ |- context[_ $+ (?x, _) $? ?y] ] => cases (x ==v y); simplify\n           | [ |- context[?x ==v ?y] ] => cases (x ==v y); simplify\n\n           | [ H : step _ _ |- _ ] => invert H\n           | [ H : step0 _ _ |- _ ] => invert1 H\n           | [ H : hasty _ _ _ |- _ ] => invert1 H\n           | [ H : proj_t _ _ _ |- _ ] => invert1 H\n           | [ H : plug _ _ _ |- _ ] => invert1 H\n           | [ H : subtype _ _ |- _ ] => invert1 H\n           | [ H : Some _ = Some _ |- _ ] => invert H\n           end; subst.\n\nLtac t := simplify; subst; propositional; repeat (t0; simplify); try equality.\n(* END handy tactic *)\n\n\nModule Type S.\n  (* Prove these two basic algebraic properties of subtyping. *)\n  Axiom subtype_refl : forall t, t $<: t.\n  Axiom subtype_trans : forall t1 t2 t3, t1 $<: t2 -> t2 $<: t3 -> t1 $<: t3.\n\n  (* The real prize: prove soundness of this type system.\n   * We suggest starting from a copy of the type-safety proof from the book's\n   * LambdaCalculusAndTypeSoundness.v.  Essentially all of the lemmas from that\n   * proof will be useful here, too, though some of their proofs need to\n   * change. *)\n  Axiom safety :\n    forall e t,\n      hasty $0 e t -> invariantFor (trsys_of e)\n                                   (fun e' => value e'\n                                              \\/ exists e'', step e' e'').\nEnd S.\n", "meta": {"author": "mit-frap", "repo": "spring17", "sha": "9b8aeb81712ca6e623c1d03baec84d291719debb", "save_path": "github-repos/coq/mit-frap-spring17", "path": "github-repos/coq/mit-frap-spring17/spring17-9b8aeb81712ca6e623c1d03baec84d291719debb/pset8/Pset8Sig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.681072089371916}}
{"text": "   Theorem t54_10: forall A B C : Prop,\n                     (A -> C) -> (B -> C) -> (A \\/ B) -> C.\n   Proof.\n      intros. elim H1. intros. apply H. assumption.\n      intros. apply H0. assumption.\n   Qed.\n\n   Theorem t54_11: forall A1 A2 B : Prop,\n                     (A1 -> B) -> (A2 -> B) -> ((A1 /\\ ~A2) \\/ (~A1 /\\ A2)) -> B.\n   Proof.\n      intros. elim H1. intros. apply H. apply H2.\n      intros. apply H0. apply H2.\n   Qed.\n\n   Theorem t54_12: forall A B C D : Prop,\n                     (A -> C) -> (B -> D) -> (A \\/ B) -> (C \\/ D).\n   Proof.\n      intros. elim H1. intros. left. apply H. assumption.\n      intros. right. apply H0. assumption.\n   Qed.\n\n   Theorem t54_13: forall A B C D : Prop,\n                     (C -> A) -> (C -> B) -> (~A \\/ ~B) -> ~C.\n   Proof.\n      intros. elim H1. intros. intro. elim H2. apply H. assumption.\n                       intros. intro. elim H2. apply H0. assumption.\n   Qed.\n\n   Theorem t54_14: forall A B1 B2 : Prop,\n                (A -> B1) -> (A -> B2) -> ((~B1 /\\ ~(~B2)) \\/ (~(~B1) /\\ ~B2)) -> ~A.\n   Proof.\n      intros. intro. elim H1. intros. elim H3. intros. apply H4. apply H. assumption.\n                             intros. elim H3. intros. apply H5. apply H0. assumption.\n   Qed.\n\n   Theorem t54_15: forall A B C D : Prop,\n                     (C -> A) -> (D -> B) -> (~A \\/ ~B) -> (~C \\/ ~D).\n   Proof.\n      intros. elim H1. intros. left. intro. apply H2. apply H. assumption.\n      intros. right. intro. apply H2. apply H0. assumption.\n   Qed.\n\n   Theorem t54_16: forall A1 A2 A3 B : Prop,\n                     (A1 -> B) -> (A2 -> B) -> (A3 -> B) -> (A1 \\/ A2 \\/ A3) -> B.\n   Proof.\n      intros. elim H2. intros. apply H. assumption.\n      intros. elim H3. intros. apply H0. assumption.\n      intros. apply H1. assumption.\n   Qed.\n\n   Theorem t54_17: forall A1 A2 A3 B1 B2 B3 : Prop,\n    (A1 -> B1) -> (A2 -> B2) -> (A3 -> B3) -> (A1 \\/ A2 \\/ A3) -> (B1 \\/ B2 \\/ B3).\n   Proof.\n      intros. elim H2. intros. left. apply H. assumption.\n      intros. elim H3. intros. right. left. apply H0. assumption.\n      intros. right. right. apply H1. assumption.\n   Qed.\n\n   Theorem t54_18: forall A B1 B2 B3 : Prop,\n    (A -> B1) -> (A -> B2) -> (A -> B3) -> (~B1 \\/ ~B2 \\/ ~B3) -> ~A.\n   Proof.\n      intros. intro. elim H2. intros. apply H4. apply H. assumption.\n      intros. elim H4. intros. apply H5. apply H0. assumption.\n      intros. apply H5. apply H1. assumption.\n   Qed.\n\n   Theorem t54_19: forall A1 A2 A3 B1 B2 B3 : Prop,\n              (A1 -> B1) -> (A2 -> B2) -> (A3 -> B3) -> \n              (~B1 \\/ ~B2 \\/ ~B3) -> (~A1 \\/ ~A2 \\/ ~A3).\n   Proof.\n      intros. elim H2. intros. left. intro. apply H3. apply H. assumption.\n      intro. elim H3. intros. right. left. intro. apply H4. apply H0. assumption.\n      intros. right. right. intro. apply H4. apply H1. assumption.\n   Qed.", "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/Lab1/PetrovPrPrLab1-t54_10-t54_19.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6810720780580498}}
{"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(** A modular implementation of mergesort (the complexity is O(n.log n) in\n   the length of the list) *)\n\n(* Initial author: Hugo Herbelin, Oct 2009 *)\n\nRequire Import List Setoid Permutation Sorted Orders.\n\n(** Notations and conventions *)\n\nLocal Notation \"[ ]\" := nil.\nLocal Notation \"[ a ; .. ; b ]\" := (a :: .. (b :: []) ..).\n\nOpen Scope bool_scope.\n\nLocal Coercion is_true : bool >-> Sortclass.\n\n(** The main module defining [mergesort] on a given boolean\n    order [<=?]. We require minimal hypotheses : this boolean\n    order should only be total: [forall x y, (x<=?y) \\/ (y<=?x)].\n    Transitivity is not mandatory, but without it one can\n    only prove [LocallySorted] and not [StronglySorted].\n*)\n\nModule Sort (Import X:Orders.TotalLeBool').\n\nFixpoint merge l1 l2 :=\n  let fix merge_aux l2 :=\n  match l1, l2 with\n  | [], _ => l2\n  | _, [] => l1\n  | a1::l1', a2::l2' =>\n      if a1 <=? a2 then a1 :: merge l1' l2 else a2 :: merge_aux l2'\n  end\n  in merge_aux l2.\n\n(** We implement mergesort using an explicit stack of pending mergings.\n    Pending merging are represented like a binary number where digits are\n    either None (denoting 0) or Some list to merge (denoting 1). The n-th\n    digit represents the pending list to be merged at level n, if any.\n    Merging a list to a stack is like adding 1 to the binary number\n    represented by the stack but the carry is propagated by merging the\n    lists. In practice, when used in mergesort, the n-th digit, if non 0,\n    carries a list of length 2^n. For instance, adding singleton list\n    [3] to the stack Some [4]::Some [2;6]::None::Some [1;3;5;5]\n    reduces to propagate the carry [3;4] (resulting of the merge of [3]\n    and [4]) to the list Some [2;6]::None::Some [1;3;5;5], which reduces\n    to propagating the carry [2;3;4;6] (resulting of the merge of [3;4] and\n    [2;6]) to the list None::Some [1;3;5;5], which locally produces\n    Some [2;3;4;6]::Some [1;3;5;5], i.e. which produces the final result\n    None::None::Some [2;3;4;6]::Some [1;3;5;5].\n\n    For instance, here is how [6;2;3;1;5] is sorted:\n\n<<\n       operation             stack                list\n       iter_merge            []                   [6;2;3;1;5]\n    =  append_list_to_stack  [ + [6]]             [2;3;1;5]\n    -> iter_merge            [[6]]                [2;3;1;5]\n    =  append_list_to_stack  [[6] + [2]]          [3;1;5]\n    =  append_list_to_stack  [ + [2;6];]          [3;1;5]\n    -> iter_merge            [[2;6];]             [3;1;5]\n    =  append_list_to_stack  [[2;6]; + [3]]       [1;5]\n    -> merge_list            [[2;6];[3]]          [1;5]\n    =  append_list_to_stack  [[2;6];[3] + [1]     [5]\n    =  append_list_to_stack  [[2;6] + [1;3];]     [5]\n    =  append_list_to_stack  [ + [1;2;3;6];;]     [5]\n    -> merge_list            [[1;2;3;6];;]        [5]\n    =  append_list_to_stack  [[1;2;3;6];; + [5]]  []\n    -> merge_stack           [[1;2;3;6];;[5]]\n    =                                             [1;2;3;5;6]\n>>\n    The complexity of the algorithm is n*log n, since there are\n    2^(p-1) mergings to do of length 2, 2^(p-2) of length 4, ..., 2^0\n    of length 2^p for a list of length 2^p. The algorithm does not need\n    explicitly cutting the list in 2 parts at each step since it the\n    successive accumulation of fragments on the stack which ensures\n    that lists are merged on a dichotomic basis.\n*)\n\nFixpoint merge_list_to_stack stack l :=\n  match stack with\n  | [] => [Some l]\n  | None :: stack' => Some l :: stack'\n  | Some l' :: stack' => None :: merge_list_to_stack stack' (merge l' l)\n  end.\n\nFixpoint merge_stack stack :=\n  match stack with\n  | [] => []\n  | None :: stack' => merge_stack stack'\n  | Some l :: stack' => merge l (merge_stack stack')\n  end.\n\nFixpoint iter_merge stack l :=\n  match l with\n  | [] => merge_stack stack\n  | a::l' => iter_merge (merge_list_to_stack stack [a]) l'\n  end.\n\nDefinition sort := iter_merge [].\n\n(** The proof of correctness *)\n\nLocal Notation Sorted := (LocallySorted leb) (only parsing).\n\nFixpoint SortedStack stack :=\n  match stack with\n  | [] => True\n  | None :: stack' => SortedStack stack'\n  | Some l :: stack' => Sorted l /\\ SortedStack stack'\n  end.\n\nLocal Ltac invert H := inversion H; subst; clear H.\n\nFixpoint flatten_stack (stack : list (option (list t))) :=\n  match stack with\n  | [] => []\n  | None :: stack' => flatten_stack stack'\n  | Some l :: stack' => l ++ flatten_stack stack'\n  end.\n\nTheorem Sorted_merge : forall l1 l2,\n  Sorted l1 -> Sorted l2 -> Sorted (merge l1 l2).\nProof.\ninduction l1; induction l2; intros; simpl; auto.\n  destruct (a <=? a0) as ()_eqn:Heq1.\n    invert H.\n      simpl. constructor; trivial; rewrite Heq1; constructor.\n      assert (Sorted (merge (b::l) (a0::l2))) by (apply IHl1; auto).\n      clear H0 H3 IHl1; simpl in *.\n      destruct (b <=? a0); constructor; auto || rewrite Heq1; constructor.\n    assert (a0 <=? a) by\n      (destruct (leb_total a0 a) as [H'|H']; trivial || (rewrite Heq1 in H'; inversion H')).\n    invert H0.\n      constructor; trivial.\n      assert (Sorted (merge (a::l1) (b::l))) by auto using IHl1.\n      clear IHl2; simpl in *.\n      destruct (a <=? b); constructor; auto.\nQed.\n\nTheorem Permuted_merge : forall l1 l2, Permutation (l1++l2) (merge l1 l2).\nProof.\n  induction l1; simpl merge; intro.\n    assert (forall l, (fix merge_aux (l0 : list t) : list t := l0) l = l)\n    as -> by (destruct l; trivial). (* Technical lemma *)\n    apply Permutation_refl.\n  induction l2.\n    rewrite app_nil_r. apply Permutation_refl.\n    destruct (a <=? a0).\n      constructor; apply IHl1.\n      apply Permutation_sym, Permutation_cons_app, Permutation_sym, IHl2.\nQed.\n\nTheorem Sorted_merge_list_to_stack : forall stack l,\n  SortedStack stack -> Sorted l -> SortedStack (merge_list_to_stack stack l).\nProof.\n  induction stack as [|[|]]; intros; simpl.\n    auto.\n    apply IHstack. destruct H as (_,H1). fold SortedStack in H1. auto.\n      apply Sorted_merge; auto; destruct H; auto.\n      auto.\nQed.\n\nTheorem Permuted_merge_list_to_stack : forall stack l,\n  Permutation (l ++ flatten_stack stack) (flatten_stack (merge_list_to_stack stack l)).\nProof.\n  induction stack as [|[]]; simpl; intros.\n    reflexivity.\n    rewrite app_assoc.\n    etransitivity.\n      apply Permutation_app_tail.\n      etransitivity.\n        apply Permutation_app_comm.\n      apply Permuted_merge.\n    apply IHstack.\n    reflexivity.\nQed.\n\nTheorem Sorted_merge_stack : forall stack,\n  SortedStack stack -> Sorted (merge_stack stack).\nProof.\ninduction stack as [|[|]]; simpl; intros.\n  constructor; auto.\n  apply Sorted_merge; tauto.\n  auto.\nQed.\n\nTheorem Permuted_merge_stack : forall stack,\n  Permutation (flatten_stack stack) (merge_stack stack).\nProof.\ninduction stack as [|[]]; simpl.\n  trivial.\n  transitivity (l ++ merge_stack stack).\n    apply Permutation_app_head; trivial.\n    apply Permuted_merge.\n  assumption.\nQed.\n\nTheorem Sorted_iter_merge : forall stack l,\n  SortedStack stack -> Sorted (iter_merge stack l).\nProof.\n  intros stack l H; induction l in stack, H |- *; simpl.\n    auto using Sorted_merge_stack.\n    assert (Sorted [a]) by constructor.\n    auto using Sorted_merge_list_to_stack.\nQed.\n\nTheorem Permuted_iter_merge : forall l stack,\n  Permutation (flatten_stack stack ++ l) (iter_merge stack l).\nProof.\n  induction l; simpl; intros.\n    rewrite app_nil_r. apply Permuted_merge_stack.\n    change (a::l) with ([a]++l).\n    rewrite app_assoc.\n    etransitivity.\n      apply Permutation_app_tail.\n    etransitivity.\n    apply Permutation_app_comm.\n    apply Permuted_merge_list_to_stack.\n    apply IHl.\nQed.\n\nTheorem Sorted_sort : forall l, Sorted (sort l).\nProof.\nintro; apply Sorted_iter_merge. constructor.\nQed.\n\nCorollary LocallySorted_sort : forall l, Sorted.Sorted leb (sort l).\nProof. intro; eapply Sorted_LocallySorted_iff, Sorted_sort; auto. Qed.\n\nTheorem Permuted_sort : forall l, Permutation l (sort l).\nProof.\nintro; apply (Permuted_iter_merge l []).\nQed.\n\nCorollary StronglySorted_sort : forall l,\n  Transitive leb -> StronglySorted leb (sort l).\nProof. auto using Sorted_StronglySorted, LocallySorted_sort. Qed.\n\nEnd Sort.\n\n(** An example *)\n\nModule NatOrder <: TotalLeBool.\n  Definition t := nat.\n  Fixpoint leb x y :=\n    match x, y with\n    | 0, _ => true\n    | _, 0 => false\n    | S x', S y' => leb x' y'\n    end.\n  Infix \"<=?\" := leb (at level 35).\n  Theorem leb_total : forall a1 a2, a1 <=? a2 \\/ a2 <=? a1.\n  Proof.\n    induction a1; destruct a2; simpl; auto.\n  Qed.\nEnd NatOrder.\n\nModule Import NatSort := Sort NatOrder.\n\nExample SimpleMergeExample := Eval compute in sort [5;3;6;1;8;6;0].\n\n", "meta": {"author": "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/Sorting/Mergesort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.7905303087996142, "lm_q1q2_score": 0.6810720751754797}}
{"text": "(**\nThis library provides vernacular files containing a formalization of real\nanalysis for Coq. It is a conservative extension of the standard library Reals\nwith a focus on usability. It has been developed by Sylvie Boldo, Catherine\nLelay, and Guillaume Melquiond.\n\nThe goal of Coquelicot is to ease the writing of formulas and theorem statements\nfor real analysis. This is achieved by using total functions in place of\ndependent types for limits, derivatives, integrals, power series, and so on.\nTo help with the proof process, the library comes with a comprehensive set\nof theorems that cover not only these notions, but also some extensions such\nas parametric integrals, two-dimensional differentiability, asymptotic\nproperties. It also offers some automations for performing differentiability\nproofs. Since Coquelicot is a conservative extension of Coq's standard\nlibrary, we provide correspondence theorems between the two libraries.\n\n\n* Main types\n\n\n- [R]: the set of real numbers defined by Coq's standard library.\n- [Rbar]: [R] extended with signed infinities [p_infty] and [m_infty]. There is\n  a coercion from [R] to [Rbar].\n- [C]: the set of complex numbers, defined as pairs of real numbers. There is a\n  coercion from [R] to [C].\n- [@matrix T m n]: matrices with m rows and n columns of coefficients of type T.\n\n\n* Main classes\n\n\n- [UniformSpace]: a uniform space with a predicate [ball] defining an ecart.\n- [CompleteSpace]: a [UniformSpace] that is also complete.\n- [AbelianGroup]: a type with a commutative operator [plus] and a neutral\n  element [zero]; elements are invertible ([opp], [minus]).\n- [Ring]: an [AbelianGroup] with a noncommutative operator [mult] that is\n  distributive with respect to [plus]; [one] is the neutral element of [mult].\n- [AbsRing]: a [Ring] with an operator [abs] that is subdistributive\n  with respect to [plus] and [mult].\n- [ModuleSpace]: an [AbelianGroup] with an operator [scal] that defines a\n  left module over a [Ring].\n- [NormedModule]: a [ModuleSpace] that is also a [UniformSpace]; it provides an\n  operator [norm] that defines the same topology as [ball].\n- [CompleteNormedModule]: a [NormedModule] that is also a [CompleteSpace].\n\n\nIn the following definitions, K will designate either a [Ring] or an [AbsRing],\nwhile U and V will designate a [ModuleSpace], a [NormedModule], or a\n[CompleteNormedModule].\n\n\n* Low-level concepts of topology\n\n\nLimits and neighborhoods are expressed in terms of filters, that is, predicates\nof type [(T -> Prop) -> Prop]. Sets from a filter are stable by intersection and\nextension. Filters are used to describe limit points and how they are approached.\nThe properties of a filter are described by the [Filter] record. If a filter\ndoes not contain the empty set, it is also a [PerfectFilter].\n\n\nIn a [UniformSpace], [ball x eps y] states that y lies in a ball of center x and\nradius eps. [locally x] is the filter generated by all the balls of center x. As\nsuch, its single limit point is x. Thus [locally x] matches the traditional notion\nof convergence toward [x] in a metric space. Note: [locally x] is also the set of\nneighborhoods of x.\n\n\nThe supported filters are as follows:\n- [locally x].\n- [locally' x] is similar to [locally x], except that x is missing from every\n  set. Thus, while its limit point is x too, properties at point x do not\n  matter.\n- [Rbar_locally x] is defined for x in [Rbar]. It is [locally x] if x is finite,\n  otherwise it is the set of half-bounded open intervals extending to either\n  [m_infty] or [p_infty], depending on which infinity x is. In the latter case,\n  the limit described by the filter is plus or minus infinity.\n- [Rbar_locally' x] is to [Rbar_locally x] what [locally' x] is to [locally x].\n- [at_left x] restricts the balls of [locally x] to points strictly less\n  than x, thus properties of points on the right of x do not matter.\n- [at_right x] is analogous to [at_left x] and is used to take limits on the right.\n- [filter_prod G H] is a filter describing the neighborhoods of point (g,h) if\n  G describes the neighborhoods of g while H describes the neighborhoods of h.\n- [eventually] is a filter on natural numbers that converges to plus infinity.\n- [within dom F] weakens a filter F by only considering points that satisfy dom.\n\n\nExamples:\n- [locally x P] can be interpreted in several ways depending on the meaning of P.\n  As a set, it means that P contains a ball centered at x, that is, P is a\n  neighborhood of x. As a predicate, it means that P holds on a neighborhood of x.\n- [locally 2 (fun x => 0 < ln x)] means that [ln] has positive values in\n  a neighborhood of 2.\n- [at_left 1 (fun x => -1 < ln x < 0)] means that [ln] has values between -1\n  and 0 in the left part of a neighborhood of 1.\n\n\nOpen sets are described by the [open] predicate. It states that a set is open\nif it is a neighborhood of any of its points (in terms of [locally]). Closed sets\nare described by [closed].\n\n\n* Limits and continuity\n\n\nLimits and continuity are expressed with filters using predicate [filterlim :\n(S -> T) -> ((S -> Prop) -> Prop) -> ((T -> Prop) -> Prop)]. Property\n[filterlim f K L] means that the preimage of any set of L by f is a set of K.\nIn other words, function f, at the limit point described by filter K tends to\nthe limit point described by filter L.\n\n\nExamples:\n- [filterlim f (locally x) (locally (f x))] means that f is continuous\n  at point x. [filterlim f (locally' x) (locally (f x))] is another way to state\n  it, since x is necessarily in the preimage of f x and thus can be ignored.\n- [filterlim f (at_right x) (locally y)] means that f t tends to y when t tends\n  to x from the right.\n- [filterlim exp (Rbar_locally m_infty) (at_right 0)] means that [exp] tends\n  to 0 at minus infinity but only takes positive values there.\n- [forall x y : R, filterlim (fun z => fst z + snd z) (filter_prod (locally x)\n  (locally y)) (locally (x + y))] states that [Rplus] is continuous.\n\n\nLemma [filterlim_locally] gives the traditional epsilon-delta definition of\ncontinuity. Compatibility with the [continuity_pt] predicate from the standard\nlibrary is provided by lemmas such as [continuity_pt_filterlim].\n\n\nThe following predicates specialize [filterlim] to the usual cases of\nreal-valued sequences and functions:\n- [is_lim_seq : (nat -> R) -> Rbar -> Prop], e.g. [is_lim_seq (fun n => 1 + /\n  INR n) 1].\n- [is_lim : (R -> R) -> Rbar -> Rbar -> Prop], e.g. [is_lim exp p_infty\n  p_infty].\n\n\nThe unicity of the limits is given by lemmas [is_lim_seq_unique] and\n[is_lim_unique]. The compatibility with the arithmetic operators is given\nby lemmas such as [is_lim_seq_plus] and [is_lim_seq_plus']. They are\nderived from the generic lemmas [filterlim_plus] and [filterlim_comp_2].\n\n\nLemmas [is_lim_seq_spec] and [is_lim_sprec] gives the traditional epsilon-delta\ndefinition of convergence. Compatibility with the [Un_cv] and [limit1_in]\npredicates from the standard library is provided by lemmas [is_lim_seq_Reals]\nand [is_lim_Reals].\n\n\nWhen only the convergence matters but not the actual value of the limit, the\nfollowing predicates can be used instead, depending on whether the value can\nbe infinite or not:\n- [ex_lim_seq : (nat -> R) -> Prop].\n- [ex_lim : (R -> R) -> Rbar -> Prop].\n- [ex_finite_lim_seq : (nat -> R) -> Prop].\n- [ex_finite_lim : (R -> R) -> Rbar -> Prop].\n\n\nFinally, there are also some total functions that are guaranteed to return the\nproper limits if the sequences or functions actually converge:\n- [Lim_seq : (nat -> R) -> Rbar], e.g. [Lim_seq (fun n => 1 + / INR n)] is equal\n  to 1.\n- [Lim : (R -> R) -> Rbar -> Rbar].\n\n\nIf they do not converge, the returned value is arbitrary and no interesting\nresults can be derived. These functions are related to the previous predicates\nby lemmas [Lim_seq_correct] and [Lim_correct].\n\n\nAs with predicates [filterlim], [is_lim_seq], and [is_lim], compatibility with\nthe arithmetic operators is given by lemmas such as [ex_lim_seq_mult] and\n[Lim_inv].\n\n\nCompatibility with predicates [Un_cv] and [limit1_in] from the standard library\nis provided by lemmas [is_lim_seq_Reals] and [is_lim_Reals].\n\n\n* Derivability and differentiability\n\n\nThe predicate of differentiability is [filterdiff : (U -> V) -> ((U -> Prop) ->\nProp) -> (U -> V) -> Prop]. Property [filterdiff f K l] means that, at the\nlimit point described by filter K, the differential of function f is the linear\nfunction l. Linearity is described by the predicate [is_linear].\n\n\nWhile [filterdiff_ext] states that two functions extensionally equal have the\nsame differential, [filterdiff_ext_lin] states that the differential can be\nreplaced by any linear function that is extensionally equal.\n\n\nWhen the domain space of the function is an [AbsRing] rather than just a\n[NormedModule] and the filter is [locally], the following specialized predicates\ncan be used instead:\n- [is_derive : (K -> V) -> K -> V -> Prop].\n- [ex_derive : (K -> V) -> K -> V -> Prop].\n\n\nFor real-valued functions, the following total function gives the value of the\nderivative, if it exists: [Derive : (R -> R) -> R -> R]. The specification of\nthis function is given by lemma [Derive_correct]. Compatibility of the\npredicates with [derivable_pt_lim] from the standard library is given by\n[is_derive_Reals].\n\n\nTactic [auto_derive] can be used to automatically solve goals about [is_derive],\n[ex_derive], [derivable_pt_lim], and [derivable_pt].\n\n\n* Riemann integrals\n\n\nThe main predicate is [is_RInt : (R -> V) -> R -> R -> V -> Prop]. [is_RInt f a\nb l] means that the Riemann sums of function f between a and b converge and\ntheir limit is equal to l. This is a specialization of [filterlim] for a\nfunction built using [Riemann_sum] and the [Riemann_fine] filter.\n\n\nAs before, there are a predicate and a total function related to it:\n- [ex_RInt : (R -> V) -> R -> R -> Prop].\n- [RInt : (R -> R) -> R -> R -> R].\n\n\nCompatibility with predicate [Riemann_integrable] from the standard library is\nprovided by lemmas [ex_RInt_Reals_0] and [ex_RInt_Reals_1].\n\n\n* Series and power series\n\n\nThe main predicates are [is_series : (nat -> V) -> V -> Prop] and [is_pseries :\n(nat -> V) -> K -> V -> Prop].\n\n\nThe associated predicates and functions are as follows:\n- [ex_series : (nat -> V) -> Prop].\n- [ex_pseries : (nat -> V) -> K -> Prop].\n- [Series : (nat -> R) -> R].\n- [PSeries : (nat -> R) -> R -> R].\n\n\nThere is also a function [CV_radius : (nat -> R) -> Rbar] that returns the\npossibly infinite convergence radius.\n\n\nCompatibility with predicates [infinite_sum] and [Pser] from the standard\nlibrary is provided by lemmas [is_series_Reals] and [is_pseries_Reals].\n\n\n* Naming conventions\n\n\n- Theorems about a given predicate start with its name, generally followed\n  by the name of the object it is applied to, e.g. [is_RInt_plus], or a property\n  of the object, e.g. [filterdiff_linear].\n- Correspondence theorems with the standard library end with [_Reals].\n- Extensionality theorems end with [_ext]. If the equality only needs to\n  be local, they end with [_ext_loc] instead.\n- Uniqueness theorems end with [_unique].\n- Theorems about asymptotic properties at plus, resp. minus, infinity end with\n  [_p], resp. [_m].\n  if they are at infinite points.\n- Theorems about constant functions, resp. identity, end with [_const], resp.\n  [_id].\n\n*)\n\nRequire Export AutoDerive Compactness Complex Continuity Derive.\nRequire Export Derive_2d Equiv ElemFct Hierarchy Lim_seq.\nRequire Export Lub Markov PSeries Rbar Rcomplements.\nRequire Export RInt RInt_gen RInt_analysis Seq_fct Series SF_seq.\n\n(** #<img src=\"deps.png\" usemap=\"##coquelicot_deps\" /># *)\n\n(**\nThis file is part of the Coquelicot formalization of real\nanalysis in Coq: http://coquelicot.saclay.inria.fr/\n\nCopyright (C) 2011-2015 Sylvie Boldo\n#<br />#\nCopyright (C) 2011-2015 Catherine Lelay\n#<br />#\nCopyright (C) 2011-2015 Guillaume Melquiond\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 3 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nCOPYING file for more details.\n*)\n", "meta": {"author": "CohenCyril", "repo": "coquelicot", "sha": "680ca5870fc96442b01c0b61e57ca8238634739d", "save_path": "github-repos/coq/CohenCyril-coquelicot", "path": "github-repos/coq/CohenCyril-coquelicot/coquelicot-680ca5870fc96442b01c0b61e57ca8238634739d/theories/Coquelicot.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.6810720611233188}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** Euclidean Division *)\n\nRequire Import NZAxioms NZMulOrder.\n\n(** The first signatures will be common to all divisions over NZ, N and Z *)\n\nModule Type DivMod (Import A : Typ).\n Parameters Inline div modulo : t -> t -> t.\nEnd DivMod.\n\nModule Type DivModNotation (A : Typ)(Import B : DivMod A).\n Infix \"/\" := div.\n Infix \"mod\" := modulo (at level 40, no associativity).\nEnd DivModNotation.\n\nModule Type DivMod' (A : Typ) := DivMod A <+ DivModNotation A.\n\nModule Type NZDivSpec (Import A : NZOrdAxiomsSig')(Import B : DivMod' A).\n Declare Instance div_wd : Proper (eq==>eq==>eq) div.\n Declare Instance mod_wd : Proper (eq==>eq==>eq) modulo.\n Axiom div_mod : forall a b, b ~= 0 -> a == b*(a/b) + (a mod b).\n Axiom mod_bound_pos : forall a b, 0<=a -> 0<b -> 0 <= a mod b < b.\nEnd NZDivSpec.\n\n(** The different divisions will only differ in the conditions\n    they impose on [modulo]. For NZ, we have only described the\n    behavior on positive numbers.\n*)\n\nModule Type NZDiv (A : NZOrdAxiomsSig) := DivMod A <+ NZDivSpec A.\nModule Type NZDiv' (A : NZOrdAxiomsSig) := NZDiv A <+ DivModNotation A.\n\nModule Type NZDivProp\n (Import A : NZOrdAxiomsSig')\n (Import B : NZDiv' A)\n (Import C : NZMulOrderProp A).\n\n(** Uniqueness theorems *)\n\nTheorem div_mod_unique :\n forall b q1 q2 r1 r2, 0<=r1<b -> 0<=r2<b ->\n  b*q1+r1 == b*q2+r2 -> q1 == q2 /\\ r1 == r2.\nProof.\nintros b.\nassert (U : forall q1 q2 r1 r2,\n            b*q1+r1 == b*q2+r2 -> 0<=r1<b -> 0<=r2 -> q1<q2 -> False).\n intros q1 q2 r1 r2 EQ LT Hr1 Hr2.\n contradict EQ.\n apply lt_neq.\n apply lt_le_trans with (b*q1+b).\n rewrite <- add_lt_mono_l. tauto.\n apply le_trans with (b*q2).\n rewrite mul_comm, <- mul_succ_l, mul_comm.\n apply mul_le_mono_nonneg_l; intuition; try order.\n rewrite le_succ_l; auto.\n rewrite <- (add_0_r (b*q2)) at 1.\n rewrite <- add_le_mono_l. tauto.\n\nintros q1 q2 r1 r2 Hr1 Hr2 EQ; destruct (lt_trichotomy q1 q2) as [LT|[EQ'|GT]].\nelim (U q1 q2 r1 r2); intuition.\nsplit; auto. rewrite EQ' in EQ. rewrite add_cancel_l in EQ; auto.\nelim (U q2 q1 r2 r1); intuition.\nQed.\n\nTheorem div_unique:\n forall a b q r, 0<=a -> 0<=r<b ->\n   a == b*q + r -> q == a/b.\nProof.\nintros a b q r Ha (Hb,Hr) EQ.\ndestruct (div_mod_unique b q (a/b) r (a mod b)); auto.\napply mod_bound_pos; order.\nrewrite <- div_mod; order.\nQed.\n\nTheorem mod_unique:\n forall a b q r, 0<=a -> 0<=r<b ->\n  a == b*q + r -> r == a mod b.\nProof.\nintros a b q r Ha (Hb,Hr) EQ.\ndestruct (div_mod_unique b q (a/b) r (a mod b)); auto.\napply mod_bound_pos; order.\nrewrite <- div_mod; order.\nQed.\n\nTheorem div_unique_exact a b q:\n 0<=a -> 0<b -> a == b*q -> q == a/b.\nProof.\n intros Ha Hb H. apply div_unique with 0; nzsimpl; now try split.\nQed.\n\n(** A division by itself returns 1 *)\n\nLemma div_same : forall a, 0<a -> a/a == 1.\nProof.\nintros. symmetry. apply div_unique_exact; nzsimpl; order.\nQed.\n\nLemma mod_same : forall a, 0<a -> a mod a == 0.\nProof.\nintros. symmetry.\napply mod_unique with 1; intuition; try order.\nnow nzsimpl.\nQed.\n\n(** A division of a small number by a bigger one yields zero. *)\n\nTheorem div_small: forall a b, 0<=a<b -> a/b == 0.\nProof.\nintros. symmetry.\napply div_unique with a; intuition; try order.\nnow nzsimpl.\nQed.\n\n(** Same situation, in term of modulo: *)\n\nTheorem mod_small: forall a b, 0<=a<b -> a mod b == a.\nProof.\nintros. symmetry.\napply mod_unique with 0; intuition; try order.\nnow nzsimpl.\nQed.\n\n(** * Basic values of divisions and modulo. *)\n\nLemma div_0_l: forall a, 0<a -> 0/a == 0.\nProof.\nintros; apply div_small; split; order.\nQed.\n\nLemma mod_0_l: forall a, 0<a -> 0 mod a == 0.\nProof.\nintros; apply mod_small; split; order.\nQed.\n\nLemma div_1_r: forall a, 0<=a -> a/1 == a.\nProof.\nintros. symmetry. apply div_unique_exact; nzsimpl; order'.\nQed.\n\nLemma mod_1_r: forall a, 0<=a -> a mod 1 == 0.\nProof.\nintros. symmetry.\napply mod_unique with a; try split; try order; try apply lt_0_1.\nnow nzsimpl.\nQed.\n\nLemma div_1_l: forall a, 1<a -> 1/a == 0.\nProof.\nintros; apply div_small; split; auto. apply le_0_1.\nQed.\n\nLemma mod_1_l: forall a, 1<a -> 1 mod a == 1.\nProof.\nintros; apply mod_small; split; auto. apply le_0_1.\nQed.\n\nLemma div_mul : forall a b, 0<=a -> 0<b -> (a*b)/b == a.\nProof.\nintros; symmetry. apply div_unique_exact; trivial.\napply mul_nonneg_nonneg; order.\napply mul_comm.\nQed.\n\nLemma mod_mul : forall a b, 0<=a -> 0<b -> (a*b) mod b == 0.\nProof.\nintros; symmetry.\napply mod_unique with a; try split; try order.\napply mul_nonneg_nonneg; order.\nnzsimpl; apply mul_comm.\nQed.\n\n\n(** * Order results about mod and div *)\n\n(** A modulo cannot grow beyond its starting point. *)\n\nTheorem mod_le: forall a b, 0<=a -> 0<b -> a mod b <= a.\nProof.\nintros. destruct (le_gt_cases b a).\napply le_trans with b; auto.\napply lt_le_incl. destruct (mod_bound_pos a b); auto.\nrewrite lt_eq_cases; right.\napply mod_small; auto.\nQed.\n\n\n(* Division of positive numbers is positive. *)\n\nLemma div_pos: forall a b, 0<=a -> 0<b -> 0 <= a/b.\nProof.\nintros.\nrewrite (mul_le_mono_pos_l _ _ b); auto; nzsimpl.\nrewrite (add_le_mono_r _ _ (a mod b)).\nrewrite <- div_mod by order.\nnzsimpl.\napply mod_le; auto.\nQed.\n\nLemma div_str_pos : forall a b, 0<b<=a -> 0 < a/b.\nProof.\nintros a b (Hb,Hab).\nassert (LE : 0 <= a/b) by (apply div_pos; order).\nassert (MOD : a mod b < b) by (destruct (mod_bound_pos a b); order).\nrewrite lt_eq_cases in LE; destruct LE as [LT|EQ]; auto.\nexfalso; revert Hab.\nrewrite (div_mod a b), <-EQ; nzsimpl; order.\nQed.\n\nLemma div_small_iff : forall a b, 0<=a -> 0<b -> (a/b==0 <-> a<b).\nProof.\nintros a b Ha Hb; split; intros Hab.\ndestruct (lt_ge_cases a b); auto.\nsymmetry in Hab. contradict Hab. apply lt_neq, div_str_pos; auto.\napply div_small; auto.\nQed.\n\nLemma mod_small_iff : forall a b, 0<=a -> 0<b -> (a mod b == a <-> a<b).\nProof.\nintros a b Ha Hb. split; intros H; auto using mod_small.\nrewrite <- div_small_iff; auto.\nrewrite <- (mul_cancel_l _ _ b) by order.\nrewrite <- (add_cancel_r _ _ (a mod b)).\nrewrite <- div_mod, H by order. now nzsimpl.\nQed.\n\nLemma div_str_pos_iff : forall a b, 0<=a -> 0<b -> (0<a/b <-> b<=a).\nProof.\nintros a b Ha Hb; split; intros Hab.\ndestruct (lt_ge_cases a b) as [LT|LE]; auto.\nrewrite <- div_small_iff in LT; order.\napply div_str_pos; auto.\nQed.\n\n\n(** As soon as the divisor is strictly greater than 1,\n    the division is strictly decreasing. *)\n\nLemma div_lt : forall a b, 0<a -> 1<b -> a/b < a.\nProof.\nintros.\nassert (0 < b) by (apply lt_trans with 1; auto using lt_0_1).\ndestruct (lt_ge_cases a b).\nrewrite div_small; try split; order.\nrewrite (div_mod a b) at 2 by order.\napply lt_le_trans with (b*(a/b)).\nrewrite <- (mul_1_l (a/b)) at 1.\nrewrite <- mul_lt_mono_pos_r; auto.\napply div_str_pos; auto.\nrewrite <- (add_0_r (b*(a/b))) at 1.\nrewrite <- add_le_mono_l. destruct (mod_bound_pos a b); order.\nQed.\n\n(** [le] is compatible with a positive division. *)\n\nLemma div_le_mono : forall a b c, 0<c -> 0<=a<=b -> a/c <= b/c.\nProof.\nintros a b c Hc (Ha,Hab).\nrewrite lt_eq_cases in Hab. destruct Hab as [LT|EQ];\n [|rewrite EQ; order].\nrewrite <- lt_succ_r.\nrewrite (mul_lt_mono_pos_l c) by order.\nnzsimpl.\nrewrite (add_lt_mono_r _ _ (a mod c)).\nrewrite <- div_mod by order.\napply lt_le_trans with b; auto.\nrewrite (div_mod b c) at 1 by order.\nrewrite <- add_assoc, <- add_le_mono_l.\napply le_trans with (c+0).\nnzsimpl; destruct (mod_bound_pos b c); order.\nrewrite <- add_le_mono_l. destruct (mod_bound_pos a c); order.\nQed.\n\n(** The following two properties could be used as specification of div *)\n\nLemma mul_div_le : forall a b, 0<=a -> 0<b -> b*(a/b) <= a.\nProof.\nintros.\nrewrite (add_le_mono_r _ _ (a mod b)), <- div_mod by order.\nrewrite <- (add_0_r a) at 1.\nrewrite <- add_le_mono_l. destruct (mod_bound_pos a b); order.\nQed.\n\nLemma mul_succ_div_gt : forall a b, 0<=a -> 0<b -> a < b*(S (a/b)).\nProof.\nintros.\nrewrite (div_mod a b) at 1 by order.\nrewrite (mul_succ_r).\nrewrite <- add_lt_mono_l.\ndestruct (mod_bound_pos a b); auto.\nQed.\n\n\n(** The previous inequality is exact iff the modulo is zero. *)\n\nLemma div_exact : forall a b, 0<=a -> 0<b -> (a == b*(a/b) <-> a mod b == 0).\nProof.\nintros. rewrite (div_mod a b) at 1 by order.\nrewrite <- (add_0_r (b*(a/b))) at 2.\napply add_cancel_l.\nQed.\n\n(** Some additional inequalities about div. *)\n\nTheorem div_lt_upper_bound:\n  forall a b q, 0<=a -> 0<b -> a < b*q -> a/b < q.\nProof.\nintros.\nrewrite (mul_lt_mono_pos_l b) by order.\napply le_lt_trans with a; auto.\napply mul_div_le; auto.\nQed.\n\nTheorem div_le_upper_bound:\n  forall a b q, 0<=a -> 0<b -> a <= b*q -> a/b <= q.\nProof.\nintros.\nrewrite (mul_le_mono_pos_l _ _ b) by order.\napply le_trans with a; auto.\napply mul_div_le; auto.\nQed.\n\nTheorem div_le_lower_bound:\n  forall a b q, 0<=a -> 0<b -> b*q <= a -> q <= a/b.\nProof.\nintros a b q Ha Hb H.\ndestruct (lt_ge_cases 0 q).\nrewrite <- (div_mul q b); try order.\napply div_le_mono; auto.\nrewrite mul_comm; split; auto.\napply lt_le_incl, mul_pos_pos; auto.\napply le_trans with 0; auto; apply div_pos; auto.\nQed.\n\n(** A division respects opposite monotonicity for the divisor *)\n\nLemma div_le_compat_l: forall p q r, 0<=p -> 0<q<=r ->\n    p/r <= p/q.\nProof.\n intros p q r Hp (Hq,Hqr).\n apply div_le_lower_bound; auto.\n rewrite (div_mod p r) at 2 by order.\n apply le_trans with (r*(p/r)).\n apply mul_le_mono_nonneg_r; try order.\n apply div_pos; order.\n rewrite <- (add_0_r (r*(p/r))) at 1.\n rewrite <- add_le_mono_l. destruct (mod_bound_pos p r); order.\nQed.\n\n\n(** * Relations between usual operations and mod and div *)\n\nLemma mod_add : forall a b c, 0<=a -> 0<=a+b*c -> 0<c ->\n (a + b * c) mod c == a mod c.\nProof.\n intros.\n symmetry.\n apply mod_unique with (a/c+b); auto.\n apply mod_bound_pos; auto.\n rewrite mul_add_distr_l, add_shuffle0, <- div_mod by order.\n now rewrite mul_comm.\nQed.\n\nLemma div_add : forall a b c, 0<=a -> 0<=a+b*c -> 0<c ->\n (a + b * c) / c == a / c + b.\nProof.\n intros.\n apply (mul_cancel_l _ _ c); try order.\n apply (add_cancel_r _ _ ((a+b*c) mod c)).\n rewrite <- div_mod, mod_add by order.\n rewrite mul_add_distr_l, add_shuffle0, <- div_mod by order.\n now rewrite mul_comm.\nQed.\n\nLemma div_add_l: forall a b c, 0<=c -> 0<=a*b+c -> 0<b ->\n (a * b + c) / b == a + c / b.\nProof.\n intros a b c. rewrite (add_comm _ c), (add_comm a).\n intros. apply div_add; auto.\nQed.\n\n(** Cancellations. *)\n\nLemma div_mul_cancel_r : forall a b c, 0<=a -> 0<b -> 0<c ->\n (a*c)/(b*c) == a/b.\nProof.\n intros.\n symmetry.\n apply div_unique with ((a mod b)*c).\n apply mul_nonneg_nonneg; order.\n split.\n apply mul_nonneg_nonneg; destruct (mod_bound_pos a b); order.\n rewrite <- mul_lt_mono_pos_r; auto. destruct (mod_bound_pos a b); auto.\n rewrite (div_mod a b) at 1 by order.\n rewrite mul_add_distr_r.\n rewrite add_cancel_r.\n rewrite <- 2 mul_assoc. now rewrite (mul_comm c).\nQed.\n\nLemma div_mul_cancel_l : forall a b c, 0<=a -> 0<b -> 0<c ->\n (c*a)/(c*b) == a/b.\nProof.\n intros. rewrite !(mul_comm c); apply div_mul_cancel_r; auto.\nQed.\n\nLemma mul_mod_distr_l: forall a b c, 0<=a -> 0<b -> 0<c ->\n  (c*a) mod (c*b) == c * (a mod b).\nProof.\n intros.\n rewrite <- (add_cancel_l _ _ ((c*b)* ((c*a)/(c*b)))).\n rewrite <- div_mod.\n rewrite div_mul_cancel_l; auto.\n rewrite <- mul_assoc, <- mul_add_distr_l, mul_cancel_l by order.\n apply div_mod; order.\n rewrite <- neq_mul_0; intuition; order.\nQed.\n\nLemma mul_mod_distr_r: forall a b c, 0<=a -> 0<b -> 0<c ->\n  (a*c) mod (b*c) == (a mod b) * c.\nProof.\n intros. rewrite !(mul_comm _ c); now rewrite mul_mod_distr_l.\nQed.\n\n(** Operations modulo. *)\n\nTheorem mod_mod: forall a n, 0<=a -> 0<n ->\n (a mod n) mod n == a mod n.\nProof.\n intros. destruct (mod_bound_pos a n); auto. now rewrite mod_small_iff.\nQed.\n\nLemma mul_mod_idemp_l : forall a b n, 0<=a -> 0<=b -> 0<n ->\n ((a mod n)*b) mod n == (a*b) mod n.\nProof.\n intros a b n Ha Hb Hn. symmetry.\n generalize (mul_nonneg_nonneg _ _ Ha Hb).\n rewrite (div_mod a n) at 1 2 by order.\n rewrite add_comm, (mul_comm n), (mul_comm _ b).\n rewrite mul_add_distr_l, mul_assoc.\n intros. rewrite mod_add; auto.\n now rewrite mul_comm.\n apply mul_nonneg_nonneg; destruct (mod_bound_pos a n); auto.\nQed.\n\nLemma mul_mod_idemp_r : forall a b n, 0<=a -> 0<=b -> 0<n ->\n (a*(b mod n)) mod n == (a*b) mod n.\nProof.\n intros. rewrite !(mul_comm a). apply mul_mod_idemp_l; auto.\nQed.\n\nTheorem mul_mod: forall a b n, 0<=a -> 0<=b -> 0<n ->\n (a * b) mod n == ((a mod n) * (b mod n)) mod n.\nProof.\n intros. rewrite mul_mod_idemp_l, mul_mod_idemp_r; trivial. reflexivity.\n now destruct (mod_bound_pos b n).\nQed.\n\nLemma add_mod_idemp_l : forall a b n, 0<=a -> 0<=b -> 0<n ->\n ((a mod n)+b) mod n == (a+b) mod n.\nProof.\n intros a b n Ha Hb Hn. symmetry.\n generalize (add_nonneg_nonneg _ _ Ha Hb).\n rewrite (div_mod a n) at 1 2 by order.\n rewrite <- add_assoc, add_comm, mul_comm.\n intros. rewrite mod_add; trivial. reflexivity.\n apply add_nonneg_nonneg; auto. destruct (mod_bound_pos a n); auto.\nQed.\n\nLemma add_mod_idemp_r : forall a b n, 0<=a -> 0<=b -> 0<n ->\n (a+(b mod n)) mod n == (a+b) mod n.\nProof.\n intros. rewrite !(add_comm a). apply add_mod_idemp_l; auto.\nQed.\n\nTheorem add_mod: forall a b n, 0<=a -> 0<=b -> 0<n ->\n (a+b) mod n == (a mod n + b mod n) mod n.\nProof.\n intros. rewrite add_mod_idemp_l, add_mod_idemp_r; trivial. reflexivity.\n now destruct (mod_bound_pos b n).\nQed.\n\nLemma div_div : forall a b c, 0<=a -> 0<b -> 0<c ->\n (a/b)/c == a/(b*c).\nProof.\n intros a b c Ha Hb Hc.\n apply div_unique with (b*((a/b) mod c) + a mod b); trivial.\n (* begin 0<= ... <b*c *)\n destruct (mod_bound_pos (a/b) c), (mod_bound_pos a b); auto using div_pos.\n split.\n apply add_nonneg_nonneg; auto.\n apply mul_nonneg_nonneg; order.\n apply lt_le_trans with (b*((a/b) mod c) + b).\n rewrite <- add_lt_mono_l; auto.\n rewrite <- mul_succ_r, <- mul_le_mono_pos_l, le_succ_l; auto.\n (* end 0<= ... < b*c *)\n rewrite (div_mod a b) at 1 by order.\n rewrite add_assoc, add_cancel_r.\n rewrite <- mul_assoc, <- mul_add_distr_l, mul_cancel_l by order.\n apply div_mod; order.\nQed.\n\nLemma mod_mul_r : forall a b c, 0<=a -> 0<b -> 0<c ->\n a mod (b*c) == a mod b + b*((a/b) mod c).\nProof.\n intros a b c Ha Hb Hc.\n apply add_cancel_l with (b*c*(a/(b*c))).\n rewrite <- div_mod by (apply neq_mul_0; split; order).\n rewrite <- div_div by trivial.\n rewrite add_assoc, add_shuffle0, <- mul_assoc, <- mul_add_distr_l.\n rewrite <- div_mod by order.\n apply div_mod; order.\nQed.\n\n(** A last inequality: *)\n\nTheorem div_mul_le:\n forall a b c, 0<=a -> 0<b -> 0<=c -> c*(a/b) <= (c*a)/b.\nProof.\n intros.\n apply div_le_lower_bound; auto.\n apply mul_nonneg_nonneg; auto.\n rewrite mul_assoc, (mul_comm b c), <- mul_assoc.\n apply mul_le_mono_nonneg_l; auto.\n apply mul_div_le; auto.\nQed.\n\n(** mod is related to divisibility *)\n\nLemma mod_divides : forall a b, 0<=a -> 0<b ->\n (a mod b == 0 <-> exists c, a == b*c).\nProof.\n split.\n intros. exists (a/b). rewrite div_exact; auto.\n intros (c,Hc). rewrite Hc, mul_comm. apply mod_mul; auto.\n rewrite (mul_le_mono_pos_l _ _ b); auto. nzsimpl. order.\nQed.\n\nEnd NZDivProp.\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/NatInt/NZDiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.6810654958488386}}
{"text": "(** * Perm: Basic Techniques for Comparisons and Permutations *)\n\n(** Consider these algorithms and data structures:\n    - sort a sequence of numbers\n    - finite maps from numbers to (arbitrary-type) data\n    - finite maps from any ordered type to (arbitrary-type) data\n    - priority queues: finding/deleting the highest number in a set\n\n    To prove the correctness of such programs, we need to reason about\n    comparisons, and about whether two collections have the same\n    contents.  In this chapter, we introduce some techniques for\n    reasoning about:\n\n    - less-than comparisons on natural numbers, and\n    - permutations (rearrangements of lists).\n\n    In later chapters, we'll apply these proof techniques to reasoning\n    about algorithms and data structures. *)\n\nSet Warnings \"-notation-overridden,-parsing,-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(* ################################################################# *)\n(** * The Less-Than Order on the Natural Numbers *)\n\n(** In our proofs about searching and sorting algorithms, we often\n    have to reason about the less-than order on natural numbers.\n    greater-than. Recall that the Coq standard library contains both\n    propositional and Boolean less-than operators on natural numbers.\n    We write [x < y] for the proposition that [x] is less than [y]: *)\n\nLocate \"_ < _\". (* \"x < y\" := lt x y *)\nCheck lt : nat -> nat -> Prop.\n\n(** And we write [x <? y] for the computation that returns [true] or\n    [false] depending on whether [x] is less than [y]: *)\n\nLocate \"_ <? _\". (* x <? y  := Nat.ltb x y *)\nCheck Nat.ltb : nat -> nat -> bool.\n\n(** Operation [<] is a reflection of [<?], as discussed in\n    [Logic] and [IndProp]. The [Nat] module has a\n    theorem showing how they relate: *)\n\nCheck Nat.ltb_lt : forall n m : nat, (n <? m) = true <-> n < m.\n\n(** The [Nat] module contains a synonym for [lt]. *)\n\nPrint Nat.lt. (* Nat.lt = lt *)\n\n(** For unknown reasons, [Nat] does not define notations\n    for [>?] or [>=?].  So we define them here: *)\n\nNotation  \"a >=? b\" := (Nat.leb b a)\n                          (at level 70) : nat_scope.\nNotation  \"a >? b\"  := (Nat.ltb b a)\n                         (at level 70) : nat_scope.\n\n(* ================================================================= *)\n(** ** The Lia Tactic *)\n\n(** Reasoning about inequalities by hand can be a little painful. Luckily, Coq\n    provides a tactic called [lia] that is quite helpful. *)\n\nTheorem lia_example1:\n forall i j k,\n    i < j ->\n    ~ (k - 3 <= j) ->\n   k > i.\nProof.\n  intros.\n\n(** The hard way to prove this is by hand. *)\n\n  (* try to remember the name of the lemma about negation and [<=] *)\n  Search (~ _ <= _ -> _).\n  apply not_le in H0.\n  (* try to remember the name of the transitivity lemma about [>] *)\n  Search (_ > _ -> _ > _ -> _ > _).\n  apply gt_trans with j.\n  apply gt_trans with (k-3).\n  (* Is [k] greater than [k-3]? On the integers, sure. But we're working\n     with natural numbers, which truncate subtraction at zero. *)\nAbort.\n\nTheorem truncated_subtraction: ~ (forall k:nat, k > k - 3).\nProof.\n  intros contra.\n  (* [specialize] applies a hypothesis to an argument *)\n  specialize (contra 0).\n  simpl in contra.\n  inversion contra.\nQed.\n\n(** Since subtraction is truncated, does [lia_example1] actually hold?\n    It does. Let's try again, the hard way, to find the proof. *)\n\nTheorem lia_example1:\n forall i j k,\n    i < j ->\n    ~ (k - 3 <= j) ->\n   k > i.\nProof. (* try again! *)\n  intros.\n  apply not_le in H0.\n  unfold gt in H0.\n  unfold gt.\n  (* try to remember the name ... *)\n  Search (_ < _ -> _ <= _ -> _ < _).\n  apply lt_le_trans with j.\n  apply H.\n  apply le_trans with (k-3).\n  Search (_ < _ -> _ <= _).\n  apply lt_le_weak.\n  auto.\n  apply le_minus.\nQed.\n\n(** That was tedious.  Here's a much easier way: *)\n\nTheorem lia_example2:\n forall i j k,\n    i < j ->\n    ~ (k - 3 <= j) ->\n   k > i.\nProof.\n  intros.\n  lia.\nQed.\n\n(** Lia is a decision procedure for integer linear arithemetic.\n    The [lia] tactic was made available by importing [Lia] at the\n    beginning of the file.  The tactic\n    works with Coq types [Z] and [nat], and these operators: [<] [=] [>]\n    [<=] [>=] [+] [-] [~], as well as multiplication by small integer\n    literals (such as 0,1,2,3...), and some uses of [\\/], [/\\], and [<->].\n\n    Lia does not \"understand\" other operators.  It treats\n    expressions such as [f x y] as variables.  That is, it\n    can prove [f x y > a * b -> f x y + 3 >= a * b], in the same way it\n    would prove [u > v -> u + 3 >= v].\n*)\n\nTheorem lia_example_3 : forall (f : nat -> nat -> nat) a b x y,\n    f x y > a * b -> f x y + 3 >= a * b.\nProof.\n  intros. lia.\nQed.\n\n\n\n(* ################################################################# *)\n(** * Swapping *)\n\n(** Consider trying to sort a list of natural numbers.  As a small piece of\n    a sorting algorithm, we might need to swap the first two elements of a list\n    if they are out of order. *)\n\nDefinition maybe_swap (al: list nat) : list nat :=\n  match al with\n  | a :: b :: ar => if a >? b then b :: a :: ar else a :: b :: ar\n  | _ => al\n  end.\n\nExample maybe_swap_123:\n  maybe_swap [1; 2; 3] = [1; 2; 3].\nProof. reflexivity. Qed.\n\nExample maybe_swap_321:\n  maybe_swap [3; 2; 1] = [2; 3; 1].\nProof. reflexivity. Qed.\n\n(** Applying [maybe_swap] twice should give the same result as applying it once.\n    That is, [maybe_swap] is _idempotent_. *)\n\nTheorem maybe_swap_idempotent: forall al,\n    maybe_swap (maybe_swap al) = maybe_swap al.\nProof.\n  intros [ | a [ | b al]]; simpl; try reflexivity.\n  destruct (b <? a) eqn:Hb_lt_a; simpl.\n  - destruct (a <? b) eqn:Ha_lt_b; simpl.\n    + (** Now what?  We have a contradiction in the hypotheses: it\n          cannot hold that [a] is less than [b] and [b] is less than\n          [a].  Unfortunately, [lia] cannot immediately show that\n          for us, because it reasons about comparisons in [Prop] not\n          [bool]. *)\n      Fail lia.\nAbort.\n\n(** Of course we could finish the proof by reasoning directly about\n    inequalities in [bool].  But this situation is going to occur\n    repeatedly in our study of sorting. *)\n\n(** Let's set up some machinery to enable using [lia] on boolean\n    tests. *)\n\n(* ================================================================= *)\n(** ** Reflection *)\n\n(** The [reflect] type, defined in the standard library (and presented\n    in [IndProp]), relates a proposition to a Boolean. That is,\n    a value of type [reflect P b] contains a proof of [P] if [b] is\n    [true], or a proof of [~ P] if [b] is [false]. *)\n\nPrint reflect.\n\n(*\nInductive reflect (P : Prop) : bool -> Set :=\n  | ReflectT :   P -> reflect P true\n  | ReflectF : ~ P -> reflect P false\n *)\n\n(** The standard library proves a theorem that says if [P] is provable\n    whenever [b = true] is provable, then [P] reflects [b]. *)\n\nCheck iff_reflect : forall (P : Prop) (b : bool),\n    P <-> b = true -> reflect P b.\n\n(** Using that theorem, we can quickly prove that the propositional\n    (in)equality operators are reflections of the Boolean\n    operators. *)\n\nLemma eqb_reflect : forall x y, reflect (x = y) (x =? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.eqb_eq.\nQed.\n\nLemma ltb_reflect : forall x y, reflect (x < y) (x <? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.ltb_lt.\nQed.\n\nLemma leb_reflect : forall x y, reflect (x <= y) (x <=? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.leb_le.\nQed.\n\n(** Here's an example of how you could use these lemmas.  Suppose you\n    have this simple program, [(if a <? 5 then a else 2)], and you\n    want to prove that it evaluates to a number smaller than 6.  You\n    can use [ltb_reflect] \"by hand\": *)\n\nExample reflect_example1: forall a,\n    (if a <? 5 then a else 2) < 6.\nProof.\n  intros a.\n  (* The next two lines aren't strictly necessary, but they\n     help make it clear what [destruct] does. *)\n  assert (R: reflect (a < 5) (a <? 5)) by apply ltb_reflect.\n  remember (a <? 5) as guard.\n  destruct R as [H|H] eqn:HR.\n  * (* ReflectT *) lia.\n  * (* ReflectF *) lia.\nQed.\n\n(** For the [ReflectT] constructor, the guard [a <? 5] must be equal\n    to [true]. The [if] expression in the goal has already been\n    simplified to take advantage of that fact. Also, for [ReflectT] to\n    have been used, there must be evidence [H] that [a < 5] holds.\n    From there, all that remains is to show [a < 5] entails [a < 6].\n    The [lia] tactic, which is capable of automatically proving some\n    theorems about inequalities, succeeds.\n\n    For the [ReflectF] constructor, the guard [a <? 5] must be equal\n    to [false]. So the [if] expression simplifies to [2 < 6], which is\n    immediately provable by [lia]. *)\n\n(** A less didactic version of the above proof wouldn't do the\n    [assert] and [remember]: we can directly skip to [destruct]. *)\n\nExample reflect_example1': forall a,\n    (if a <? 5 then a else 2) < 6.\nProof.\n  intros a. destruct (ltb_reflect a 5); lia.\nQed.\n\n(** But even that proof is a little unsatisfactory. The original expression,\n    [a <? 5], is not perfectly apparent from the expression [ltb_reflect a 5]\n    that we pass to [destruct]. *)\n\n(** It would be nice to be able to just say something like [destruct\n    (a <? 5)] and get the reflection \"for free.\"  That's what we'll\n    engineer, next. *)\n\n(* ================================================================= *)\n(** ** A Tactic for Boolean Destruction *)\n\n(** We're now going to build a tactic that you'll want to _use_, but\n    you won't need to understand the details of how to _build_ it\n    yourself.\n\n    Let's put several of these [reflect] lemmas into a Hint database.\n    We call it [bdestruct], because we'll use it in our\n    boolean-destruction tactic: *)\n\nHint Resolve ltb_reflect leb_reflect eqb_reflect : bdestruct.\n\n(** Here is the tactic, the body of which you do not need to\n    understand.  Invoking [bdestruct] on Boolean expression [b] does\n    the same kind of reasoning we did above: reflection and\n    destruction.  It also attempts to simplify negations involving\n    inequalities in hypotheses. *)\n\nLtac bdestruct X :=\n  let H := fresh in let e := fresh \"e\" in\n   evar (e: Prop);\n   assert (H: reflect e X); subst e;\n    [eauto with bdestruct\n    | destruct H as [H|H];\n       [ | try first [apply not_lt in H | apply not_le in H]]].\n\n(** This tactic makes quick, easy-to-read work of our running example. *)\n\nExample reflect_example2: forall a,\n    (if a <? 5 then a else 2) < 6.\nProof.\n  intros.\n  bdestruct (a <? 5);  (* instead of: [destruct (ltb_reflect a 5)]. *)\n  lia.\nQed.\n\n(* ================================================================= *)\n(** ** Finishing the [maybe_swap] Proof *)\n\n(** Now that we have [bdestruct], we can finish the proof of [maybe_swap]'s\n    idempotence. *)\n\nTheorem maybe_swap_idempotent: forall al,\n    maybe_swap (maybe_swap al) = maybe_swap al.\nProof.\n  intros [ | a [ | b al]]; simpl; try reflexivity.\n  bdestruct (a >? b); simpl.\n  (** Note how [b < a] is a hypothesis, rather than [b <? a = true]. *)\n  - bdestruct (b >? a); simpl.\n    + (** [lia] can take care of the contradictory propositional inequalities. *)\n      lia.\n    + reflexivity.\n  - bdestruct (a >? b); simpl.\n    + lia.\n    + reflexivity.\nQed.\n\n(** When proving theorems about a program that uses Boolean\n    comparisons, use [bdestruct] followed by [lia], rather than\n    [destruct] followed by application of various theorems about\n    Boolean operators. *)\n\n(* ################################################################# *)\n(** * Permutations *)\n\n(** Another useful fact about [maybe_swap] is that it doesn't add or\n    remove elements from the list: it only reorders them.  That is,\n    the output list is a permutation of the input.  List [al] is a\n    _permutation_ of list [bl] if the elements of [al] can be\n    reordered to get the list [bl].  Note that reordering does not\n    permit adding or removing duplicate elements. *)\n\n(** Coq's [Permutation] library has an inductive definition of\n    permutations. *)\n\nPrint Permutation.\n\n(*\n Inductive Permutation {A : Type} : list A -> list A -> Prop :=\n  | perm_nil : Permutation [] []\n  | perm_skip : forall (x : A) (l l' : list A),\n                Permutation l l' ->\n                Permutation (x :: l) (x :: l')\n  | perm_swap : forall (x y : A) (l : list A),\n                Permutation (y :: x :: l) (x :: y :: l)\n  | perm_trans : forall l l' l'' : list A,\n                 Permutation l l' ->\n                 Permutation l' l'' ->\n                 Permutation l l''.\n *)\n\n(** You might wonder, \"is that really the right definition?\"  And\n    indeed, it's important that we get a right definition, because\n    [Permutation] is going to be used in our specifications of\n    searching and sorting algorithms.  If we have the wrong\n    specification, then all our proofs of \"correctness\" will be\n    useless.\n\n    It's not obvious that this is indeed the right specification of\n    permutations. (It happens to be, but that's not obvious.) To gain\n    confidence that we have the right specification, let's use it\n    prove some properties that permutations ought to have. *)\n\n(** **** Exercise: 2 stars, standard (Permutation_properties)\n\n    Think of some desirable properties of the [Permutation] relation\n    and write them down informally in English, or a mix of Coq and\n    English.  Here are four to get you started:\n\n     - 1. If [Permutation al bl], then [length al = length bl].\n     - 2. If [Permutation al bl], then [Permutation bl al].\n     - 3. [[1;1]] is NOT a permutation of [[1;2]].\n     - 4. [[1;2;3;4]] IS a permutation of [[3;4;2;1]].\n\n   YOUR TASK: Add three more properties. Write them here: *)\n\n(** Now, let's examine all the theorems in the Coq library about\n    permutations: *)\n\nSearch Permutation.  (* Browse through the results of this query! *)\n\n(** Which of the properties that you wrote down above have already\n    been proved as theorems by the Coq library developers?  Answer\n    here:\n\n*)\n(* Do not modify the following line: *)\nDefinition manual_grade_for_Permutation_properties : option (nat*string) := None.\n(** [] *)\n\n(** Let's use the permutation theorems in the library to prove the\n    following theorem. *)\n\nExample butterfly: forall b u t e r f l y : nat,\n  Permutation ([b;u;t;t;e;r]++[f;l;y]) ([f;l;u;t;t;e;r]++[b;y]).\nProof.\n  intros.\n  (** Let's group [[u;t;t;e;r]] together on both sides.  Tactic\n      [change t with u] replaces [t] with [u].  Terms [t] and [u] must\n      be _convertible_, here meaning that they evalute to the same\n      term. *)\n  change [b;u;t;t;e;r] with ([b]++[u;t;t;e;r]).\n  change [f;l;u;t;t;e;r] with ([f;l]++[u;t;t;e;r]).\n\n  (** We don't actually need to know the list elements in\n      [[u;t;t;e;r]].  Let's forget about them and just remember them\n      as a variable named [utter]. *)\n  remember [u;t;t;e;r] as utter. clear Hequtter.\n\n  (** Likewise, let's group [[f;l]] and remember it as a variable. *)\n  change [f;l;y] with ([f;l]++[y]).\n  remember [f;l] as fl. clear Heqfl.\n\n  (** Next, let's cancel [fl] from both sides.  In order to do that,\n      we need to bring it to the beginning of each list. For the right\n      list, that follows easily from the associativity of [++].  *)\n  replace ((fl ++ utter) ++ [b;y]) with (fl ++ utter ++ [b;y])\n    by apply app_assoc.\n\n  (** But for the left list, we can't just use associativity.\n      Instead, we need to reason about permutations and use some\n      library theorems. *)\n  apply perm_trans with (fl ++ [y] ++ ([b] ++ utter)).\n  - replace (fl ++ [y] ++ [b] ++ utter) with ((fl ++ [y]) ++ [b] ++ utter).\n    + apply Permutation_app_comm.\n    + rewrite <- app_assoc. reflexivity.\n\n  - (** A library theorem will now help us cancel [fl]. *)\n    apply Permutation_app_head.\n\n  (** Next let's cancel [utter]. *)\n    apply perm_trans with (utter ++ [y] ++ [b]).\n    + replace ([y] ++ [b] ++ utter) with (([y] ++ [b]) ++ utter).\n      * apply Permutation_app_comm.\n      * rewrite app_assoc. reflexivity.\n    + apply Permutation_app_head.\n\n      (** Finally we're left with just [y] and [b]. *)\n      apply perm_swap.\nQed.\n\n(** That example illustrates a general method for proving permutations\n    involving cons [::] and append [++]:\n\n    - Identify some portion appearing in both sides.\n    - Bring that portion to the front on each side using lemmas such\n      as [Permutation_app_comm] and [perm_swap], with generous use of\n      [perm_trans].\n    - Use [Permutation_app_head] to cancel an appended head.  You can\n      also use [perm_skip] to cancel a single element. *)\n\n(** **** Exercise: 3 stars, standard (permut_example)\n\n    Use the permutation rules in the library to prove the following\n    theorem.  The following [Check] commands are a hint about useful\n    lemmas.  You don't need all of them, and depending on your\n    approach you will find lemmas to be more useful than others. Use\n    [Search Permutation] to find others, if you like. *)\n\nCheck perm_skip.\nCheck perm_trans.\nCheck Permutation_refl.\nCheck Permutation_app_comm.\nCheck app_assoc.\nCheck app_nil_r.\nCheck app_comm_cons.\n\nExample permut_example: forall (a b: list nat),\n  Permutation (5 :: 6 :: a ++ b) ((5 :: b) ++ (6 :: a ++ [])).\nProof.\n  intros.\n  change (5 :: 6 :: a ++ b) with (5 :: (6 :: a) ++ b).\n  change ((5 :: b) ++ 6 :: a ++ []) with (5 :: (b ++ (6 :: a) ++ [])).\n  remember (6 :: a) as a'. clear Heqa'.\n  rewrite app_nil_r.\n  apply perm_skip.\n  apply Permutation_app_comm.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (not_a_permutation)\n\n    Prove that [[1;1]] is not a permutation of [[1;2]].\n    Hints are given as [Check] commands. *)\n\nCheck Permutation_cons_inv.\nCheck Permutation_length_1_inv.\n\nExample not_a_permutation:\n  ~ Permutation [1;1] [1;2].\nProof.\n  unfold not. intros.\n  apply Permutation_cons_inv in H.\n  apply Permutation_length_1_inv in H.\n  discriminate H.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Correctness of [maybe_swap] *)\n\n(** Now we can prove that [maybe_swap] is a permutation: it reorders\n    elements but does not add or remove any. *)\n\nTheorem maybe_swap_perm: forall al,\n  Permutation al (maybe_swap al).\nProof.\n  (* WORKED IN CLASS *)\n  unfold maybe_swap.\n  destruct al as [ | a [ | b al]].\n  - simpl. apply perm_nil.\n  - apply Permutation_refl.\n  - bdestruct (b <? a).\n    + apply perm_swap.\n    + apply Permutation_refl.\nQed.\n\n(** And, we can prove that [maybe_swap] permutes elements such that\n    the first is less than or equal to the second. *)\n\nDefinition first_le_second (al: list nat) : Prop :=\n  match al with\n  | a :: b :: _ => a <= b\n  | _ => True\n  end.\n\nTheorem maybe_swap_correct: forall al,\n    Permutation al (maybe_swap al)\n    /\\ first_le_second (maybe_swap al).\nProof.\n  intros. split.\n  - apply maybe_swap_perm.\n  - (* WORKED IN CLASS *)\n    unfold maybe_swap.\n    destruct al as [ | a [ | b al]]; simpl; auto.\n    bdestruct (a >? b); simpl; lia.\nQed.\n\n(* ################################################################# *)\n(** * Summary: Comparisons and Permutations *)\n\n(** To prove correctness of algorithms for sorting and searching,\n    we'll reason about comparisons and permutations using the tools\n    developed in this chapter.  The [maybe_swap] program is a tiny\n    little example of a sorting program.  The proof style in\n    [maybe_swap_correct] will be applied (at a larger scale) in\n    the next few chapters. *)\n\n(** **** Exercise: 3 stars, standard (Forall_perm)\n\n    To close, we define a utility tactic and lemma.  First, the\n    tactic. *)\n\n(** Coq's [inversion H] tactic is so good at extracting\n    information from the hypothesis [H] that [H] sometimes becomes\n    completely redundant, and one might as well [clear] it from the\n    goal.  Then, since the [inversion] typically creates some equality\n    facts, why not then [subst] ?  Tactic [inv] does just that. *)\n\nLtac inv H := inversion H; clear H; subst.\n\n(** Second, the lemma.  You will find [inv] useful in proving it.\n\n    [Forall] is Coq library's version of the [All] proposition defined\n    in [Logic], but defined as an inductive proposition rather\n    than a fixpoint.  Prove this lemma by induction.  You will need to\n    decide what to induct on: [al], [bl], [Permutation al bl], and\n    [Forall f al] are possibilities. *)\n\nTheorem Forall_perm: forall {A} (f: A -> Prop) al bl,\n  Permutation al bl ->\n  Forall f al -> Forall f bl.\nProof.\n  intros A f al  bl H__permutation H__forall.\n  induction H__permutation.\n  - (* nil *) constructor.\n  - (* x :: l *)\n    inv H__forall.\n    auto.\n  - (* x :: y :: l *)\n    inv H__forall. inv H2.\n    auto.\n  - (* l -> l' -> l'' *)\n    auto.\nQed.\n\n(** [] *)\n\n(* 2021-08-11 15:15 *)\n", "meta": {"author": "luisholanda", "repo": "software-foundations", "sha": "a9c5d7ddb3dca0465dee4ca8519b5de971e482de", "save_path": "github-repos/coq/luisholanda-software-foundations", "path": "github-repos/coq/luisholanda-software-foundations/software-foundations-a9c5d7ddb3dca0465dee4ca8519b5de971e482de/Volume3/Perm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173801068221, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.6810654892225417}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) : natural := plus lf1 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/goal33conj15_coqofml_9smukv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6810502182057152}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) : natural := plus Zero lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj15_coqofml_ngY8BD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6810502091743186}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_s_sumsupp :\n\tforall A B C D E F X Y Z U V,\n\tSupp X Y U V Z ->\n\tCongA A B C X Y U ->\n\tCongA D E F V Y Z ->\n\tSumSupp A B C D E F.\nProof.\n\tintros A B C D E F X Y Z U V.\n\tintros Supp_XYU_VYZ.\n\tintros CongA_ABC_XYU.\n\tintros CongA_DEF_VYZ.\n\tunfold SumSupp.\n\texists X, Y, Z, U, V.\n\tsplit.\n\texact Supp_XYU_VYZ.\n\tsplit.\n\texact CongA_ABC_XYU.\n\texact CongA_DEF_VYZ.\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_sumsupp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6810502087186961}}
{"text": "Require Import HoTT.\n\nRequire Import quotient.\nRequire Import syntax.\nRequire Import nat_struct.\nRequire Import cmono_group.\nRequire Import hit.minus1Trunc.\nRequire Import hit.unique_choice.\n\nImport Distributive.\n\nLemma prod_eq_dec : forall A (Ha : DecidablePaths A) B (Hb : DecidablePaths B),\nDecidablePaths (A*B).\nProof.\nintros.\nintros [a b] [c d].\ndestruct (Ha a c) as [? | H]. destruct (Hb b d) as [? | H].\nleft. apply ap11;[apply ap|];assumption.\nright;intro Hn. apply H;apply (ap snd Hn).\nright;intro Hn. apply H;apply (ap fst Hn).\nDefined.\n\n\n\nModule Relative.\nImport GroupOfCMono.\n\nDefinition Z := @quotU nat (+).\nInstance ZPrering : PreringFull Z.\nProof.\nsplit.\napply (@quotOp nat plus _).\napply (LL_L2 _ (quotPrering nat_LLRRR)).\napply (@quotRel nat (nat_LLRRR:(PlusApart nat))).\napply (@quotRel nat (nat_LLRRR:(PlusLeq nat))).\napply (@quotRel nat (nat_LLRRR:(PlusLt nat))).\nDefined.\n\nInstance ZRing : IsRing ZPrering.\nProof.\nunfold ZPrering.\nchange (IsRing (quotPrering nat_LLRRR)).\napply _.\nDefined.\n\nDefinition z0 := (@ZeroV Z ZPrering ZRing).\nDefinition z1 := (@OneV Z ZPrering ZRing).\n\nInstance zLeq_prop : @RelationProp Z (<=).\nProof.\nred;apply _.\nDefined.\n\nInstance zLeq_dec : @Decidable Z (<=).\nProof.\nunfold ZPrering. unfold leq. simpl.\napply (@quotrel_dec _ (nat_LLRRR:(PlusLeq nat)));try apply _;simpl.\nexact nle_prop.\napply nplus_nle_invariant.\napply nplus_nle_regular.\napply nle_dec.\nDefined.\n\nInstance zLeq_total_order : @ConstrTotalOrder Z (<=).\nProof.\nsplit.\napply (@quotrel_poset _ (nat_LLRRR:PlusLeq nat));try apply _.\nexact nle_prop. apply nplus_nle_invariant.\napply nplus_nle_regular.\napply nle_total_order.\napply dec_linear_constrlinear. apply _.\napply (@quotrel_linear _ (nat_LLRRR:PlusLeq nat)).\napply constrlinear_linear. apply nle_total_order.\nDefined.\n\nDefinition zIn : nat*nat -> Z := quotIn (+).\n\nDefinition zEquiv : Rel (nat*nat) := equivU (+).\n\nInstance ZRing_set : IsHSet Z := _.\n\nInstance zEquiv_prop : RelationProp zEquiv.\nProof.\nred;apply _.\nDefined.\n\nDefinition z_rect : forall (P : Z -> Type) \n(dclass : forall m n, P (zIn (m, n))),\n(forall a b a' b' (Hequiv : zEquiv (a,b) (a',b')),\n transport _ (@related_classes_eq _ zEquiv _ _ Hequiv) (dclass a b)\n   = (dclass a' b')) ->\nforall z, P z.\nProof.\nintros P dclass H.\napply quotU_rect with (fun p => match p as p' return (P (quotIn (+) p'))\n with | (a,b) => dclass a b end).\nintros.\ndestruct x, y.\napply H.\nDefined.\n\nDefinition z_rect' : forall (P : Z -> Type) \n(dclass : forall x, P (zIn x)),\n(forall a b (Hequiv : zEquiv a b),\n transport _ (@related_classes_eq _ zEquiv _ _ Hequiv) (dclass a)\n   = (dclass b)) ->\nforall z, P z.\nProof.\napply quotU_rect.\nDefined.\n\nDefinition z_ind : forall (P : Z -> Type),\n(forall a b, IsHProp (P (zIn (a, b)))) ->\n(forall a b, P (zIn (a, b))) ->\nforall z, P z.\nProof.\nintros P Hp Hd. apply quotU_ind.\napply quotU_ind. intros;apply _.\nintros [a b]. apply Hp.\nsimpl. intros [a b];apply Hd.\nDefined.\n\nDefinition z_ind' : forall P : Z -> Type,\n(forall x, IsHProp (P (zIn x))) ->\n(forall x, P (zIn x)) ->\nforall z, P z.\nProof.\nintros P Hp Hd. apply quotU_ind.\napply quotU_ind. intros;apply _.\napply _.\napply Hd.\nDefined.\n\nDefinition z_ind_contr : forall (P : Z -> Type),\n(forall a b, Contr (P (zIn (a, b)))) ->\nforall z, Contr (P z).\nProof.\nintros P Hd. apply quotU_rect with\n (fun p => match p as p' return (Contr (P (quotIn (+) p'))) with\n   | (a,b) => Hd a b end).\nintros.\napply hprop_contr.\nDefined.\n\nLemma z_rect_compute : forall (P : Z -> Type)\n(dclass : forall m n, P (zIn (m, n))) H a b,\n z_rect P dclass H (zIn (a, b)) = dclass a b.\nProof.\nintros. reflexivity.\nDefined.\n\nSection NotaSec.\nNotation \"[ a , b ]\" := (zIn (a, b)).\n\nDefinition z0_class : [0, 0] = z0 := idpath.\nDefinition z1_class : [S 0, 0] = z1 := idpath.\n\nLemma zEquiv_eval : forall a b c d, zEquiv (a,b) (c,d) = (a+d = c+b).\nProof.\nintros;reflexivity.\nDefined.\n\nDefinition zplus_eval : forall a b c d, \n[a,b] + [c,d] = [a+c, b+d].\nProof.\nintros. reflexivity.\nDefined.\n\nDefinition zmult_eval : forall a b c d, \n[a,b] ° [c,d] = [a°c + b°d, a°d + c°b].\nProof.\nintros;reflexivity.\nDefined.\n\nDefinition zOpp : forall x : Z, Inverse (+) x := ropp.\nDefinition zOppV : Z -> Z := fun x => inverse_val (zOpp x).\nGlobal Instance zOppP : forall x : Z, IsInverse (+) x (zOppV x) := _.\n\nLemma zOpp_eval : forall a b, zOppV [a, b] = [b, a].\nProof.\nintros;reflexivity.\nDefined.\n\nLemma z_related_classes_eq : forall a b c d, zEquiv (a,b) (c,d) -> \n[a, b] = [c, d].\nProof.\nintros ? ? ? ?. apply related_classes_eq.\nDefined.\n\nLemma z_classes_eq_related : forall a b, zIn a = zIn b -> \nzEquiv a b.\nProof.\napply classes_eq_related.\nDefined.\n\n(*\nDefinition zCanon (z : Z) (x : nat*nat) :=\n (z = zIn x) * minus1Trunc (fst x = 0 \\/ snd x = 0).\n\nDefinition is_zCanon : forall x, (fst x = 0 \\/ snd x = 0) ->\n zCanon (zIn x) x := fun x H => (idpath , min1 H).\n\nDefinition zCanon_or : forall z x, zCanon z x -> (fst x = 0 \\/ snd x = 0).\nProof.\nintros ? ? H.\ndestruct (eq_nat_dec (fst x) 0) as [? | H']. left. assumption.\nright.\neapply minus1Trunc_rect_nondep;[| |apply H].\nintros H0. destruct H0. destruct H';assumption. assumption.\napply nat_set.\nDefined.\n\nGlobal Instance zCanon_prop : forall z x, IsHProp (zCanon z x).\nProof.\nintros. apply @trunc_prod. apply hprop_allpath;apply quotient_is_set.\napply minus1Trunc_is_prop.\nDefined.\n\nLemma zCanon_atmost : forall z, atmost1P (zCanon z).\nProof.\nintros. red. intros [xa xb] [ya yb] Hx Hy.\nassert (Heq : quotIn (+) (xa, xb) = quotIn (+) (ya, yb)). path_via z.\nsymmetry;apply Hx. apply Hy.\napply zCanon_or in Hx;apply zCanon_or in Hy.\nsimpl in Hx,Hy.\nclear z.\napply z_classes_eq_related in Heq. red in Heq;red in Heq;simpl in Heq.\ndestruct Hx as [Hx | Hx];destruct Hy as [Hy | Hy];\napply inverse in Hx;apply inverse in Hy;destruct Hx,Hy.\napply ap. symmetry. assumption.\nsymmetry in Heq.\napply nplus_0_0_back in Heq;destruct Heq as [[] []];reflexivity.\napply nplus_0_0_back in Heq;destruct Heq as [[] []];reflexivity.\napply (ap (fun g => (g, 0))).\npath_via (xa + 0). apply inverse. apply nplus_0_r.\npath_via (ya + 0). apply nplus_0_r.\nDefined.\n\nGlobal Instance zCanonT_prop : forall z, IsHProp (sigT (zCanon z)).\nProof.\nintros. apply hprop_inhabited_contr.\nintro X. exists X. intro Y.\ndestruct X as [x Hx];destruct Y as [y Hy].\napply path_sigma with (zCanon_atmost _ _ _ Hx Hy).\napply zCanon_prop.\nDefined.\n\nDefinition canonT : forall z, sigT (zCanon z).\nProof.\napply z_ind. apply _.\nintros.\ndestruct (nle_linear a b) as [H | H];apply nle_exists in H;destruct H as [k []].\nexists (0, k). split.\napply z_related_classes_eq. red;red. simpl.\npath_via (k + a). apply commutative;apply nat_issemiring.\napply min1. left;reflexivity.\nexists (k,0). split.\napply z_related_classes_eq;red;red;simpl. apply nplus_0_r.\napply min1;right;reflexivity.\nDefined.\n\n(*\n!!Does not compute!!\nBecause canonT uses the axiom z_related_classes_eq\n*)\nDefinition z_canon_rect : forall P : Z -> Type,\n(forall a, P [a, 0]) -> \n(forall b, P [0, b]) ->\nforall z, P z.\nProof.\nintros ? H H' ?.\ndestruct (canonT z) as [x Hc].\neapply transport. symmetry;apply (fst Hc).\napply zCanon_or in Hc. destruct x as [a b];simpl in Hc;destruct Hc as [He | He];\napply inverse in He;destruct He;eauto.\nDefined.\n\nLemma Z_repr : forall x : Z, exists p, zIn p = x.\nProof.\napply z_canon_rect;intros;econstructor;reflexivity.\nDefined.\n\n*)\n\nDefinition eq_z_dec : DecidablePaths Z.\nProof.\nred.\nassert (forall x y : Z, IsHProp ((x=y) \\/ ~ x=y)).\nintros. apply hprop_sum. intros;auto.\napply (z_ind' (fun x => forall y, _) _).\nintro x. apply z_ind'. apply _.\nintro y.\n\ndestruct (eq_nat_dec (fst x + snd y) (fst y + snd x)) as [H|H].\nleft. apply related_classes_eq. assumption.\nright;intro H'. apply H.\napply classes_eq_related in H'. assumption.\nDefined.\n\nLemma zLeq_repr : forall x y, zIn x <= zIn y -> quotRelU (+ <=) x y.\nProof.\napply quotRel_repr;try apply _.\nexact nle_prop.\napply nplus_nle_invariant.\napply nplus_nle_regular.\nDefined.\n\nLemma repr_zLeq : forall x y, quotRelU (+ <=) x y -> zIn x <= zIn y.\nProof.\napply repr_quotRel.\nDefined.\n\n\nLemma zApart_repr : forall x y, zIn x # zIn y ->\n quotRelU (+ #) x y.\nProof.\napply quotRel_repr;try apply _.\nred;red. unfold rrel;unfold gop;simpl.\nintros ? ? ? H H'.\napply H. apply nplus_cancel with z. assumption.\nred;red. unfold rrel;unfold gop;simpl.\nintros z x y H H'. apply H. destruct H'. reflexivity.\nDefined.\n\nGlobal Instance zApart_prop : @RelationProp Z (#).\nProof.\nred;apply _.\nDefined.\n\nGlobal Instance zApart_trivial : @TrivialApart Z (#).\nProof.\nred.\nassert (forall x y : Z, x#y -> x!=y).\napply (z_ind (fun x => forall y, _ -> _) _).\nintros a b. apply (z_ind (fun y => _->_) _).\nintros c d.\nintros H.\nred in H;simpl in H. apply zApart_repr in H.\nsimpl in H. unfold gop in H.\nintro H'.\napply z_classes_eq_related in H'. red in H';red in H';simpl in H'.\nauto.\n\nassert (forall x y : Z, x!=y -> x#y).\napply (z_ind (fun x => forall y, _ -> _) _).\nintros a b;apply (z_ind (fun y => _ -> _) _).\nintros c d.\nintros H.\napply repr_quotRel. simpl.\nunfold gop;simpl;intro H'.\napply H. apply related_classes_eq. assumption.\n\nintros;split;auto.\nDefined.\n\nGlobal Instance zApart_apart : @Apartness Z apart.\nProof.\napply neq_apart. apply eq_z_dec.\napply zApart_trivial.\nDefined.\n\n\nLemma zLt_repr : forall x y, (zIn x) < (zIn y) -> \n quotRelU (+ <) x y.\nProof.\napply quotRel_repr;try apply _.\nintros x y. apply nle_prop.\nred;red. unfold rrel. simpl. unfold gop. change lt with (fun x => leq (S x)).\nsimpl.\nintros z x y H. pattern (S (@plus nat nplus z x)).\napply transport with (z + (S x)). apply nplus_S_r.\napply nplus_nle_invariant;assumption.\nred;red. unfold gop;unfold rrel. simpl.\nintros z x y H. apply (nplus_nle_regular z). unfold gop;unfold rrel.\nsimpl. pattern (@plus _ nplus z (S x)). eapply transport;[|apply H].\nsymmetry. apply nplus_S_r.\nDefined.\n\nLemma repr_zLt : forall x y, quotRelU (+ <) x y -> (zIn x) < (zIn y).\nProof.\napply repr_quotRel.\nDefined.\n\nGlobal Instance zApart_dec : @Decidable Z (#).\nProof.\nintros x y.\ndestruct (eq_z_dec x y).\nright. intro H'.\napply zApart_trivial in H'. auto.\nleft. apply zApart_trivial. assumption.\nDefined.\n\n\nLemma zLt_iff_not_zLeq : forall x y : Z, x < y <-> ~ y <= x.\nProof.\nsplit;revert y;revert x;\napply (z_ind' (fun x => forall y, _ -> _) _);\nintro x;apply (z_ind' (fun y => _ -> _) _);\nintro y;\nintros H.\n\n- intros H'.\n  apply zLt_repr in H;apply zLeq_repr in H'.\n  simpl in H,H'.\n  eapply nlt_not_nle;[apply H|apply H'].\n\n- apply repr_zLt. apply not_nle_nlt. intro H'.\n  apply H;apply repr_zLeq. assumption.\nDefined.\n\nLemma zLeq_by_not : forall {x y : Z}, ~ y <= x -> x <= y.\nProof.\nintros. destruct (isconstrlinear x y). assumption. destruct X;assumption.\nDefined.\n\nInstance zLt_trans : Transitive (<).\nProof.\napply (@quotrel_trans nat (+ <));try apply _.\nintros x y. apply nle_prop.\nred;red. unfold rrel. simpl. unfold gop. change lt with (fun x => leq (S x)).\nsimpl.\nintros z x y H. pattern (S (@plus nat nplus z x)).\napply transport with (z + (S x)). apply nplus_S_r.\napply nplus_nle_invariant;assumption.\nred;red. unfold gop;unfold rrel. simpl.\nintros z x y H. apply (nplus_nle_regular z). unfold gop;unfold rrel.\nsimpl. pattern (@plus _ nplus z (S x)). eapply transport;[|apply H].\nsymmetry. apply nplus_S_r.\n\nunfold rrel. simpl.\nassert (@RelationProp nat lt). intros x y. apply nle_prop.\napply (@fullpseudo_is_fullposet _ _ _ nat_fullpseudo).\nDefined.\n\nInstance zLt_irrefl : Irreflexive (<).\nProof.\nred. apply (z_ind (fun x => _ -> _) _).\nintros a b. intros. apply zLt_repr in H.\napply nlt_not_nle in H. apply H. apply nle_n.\nDefined.\n\nGlobal Instance zLt_trichotomic : @Trichotomic Z (<).\nProof.\napply quotrel_trichotomic;try apply _.\n\nintros x y. apply nle_prop.\nred;red. unfold rrel. simpl. unfold gop. change lt with (fun x => leq (S x)).\nsimpl.\nintros z x y H. pattern (S (@plus nat nplus z x)).\napply transport with (z + (S x)). apply nplus_S_r.\napply nplus_nle_invariant;assumption.\nred;red. unfold gop;unfold rrel. simpl.\nintros z x y H. apply (nplus_nle_regular z). unfold gop;unfold rrel.\nsimpl. pattern (@plus _ nplus z (S x)). eapply transport;[|apply H].\nsymmetry. apply nplus_S_r.\n\napply (@pseudo_is_strict nat nat_LLRRR). intros x y;apply nle_prop.\napply nat_fullpseudo.\nDefined.\n\nGlobal Instance z_fullpseudoorder : FullPseudoOrder ZPrering.\nProof.\nsplit. split.\napply _.\nintros. apply zLt_irrefl with x.\napply zLt_trans with y;assumption.\n\nred. unfold rrel.\nintros ? ? H ?.\napply min1. destruct (zLt_trichotomic x z) as [?|[p|H']].\nleft;assumption. right; destruct p;assumption.\nright;eapply zLt_trans. apply H'. apply H.\n\nsplit;intro H.\ndestruct (zLt_trichotomic x y) as [H'|H'].\nleft;assumption.\nright. destruct H'. destruct p. apply zApart_apart in H. destruct H.\nassumption.\napply zApart_trivial. intro H';destruct H';destruct H as [H|H];\neapply zLt_irrefl;apply H.\n\nsplit;revert y;revert x.\napply (z_ind' (fun x => forall y, _ -> _) _).\nintro x. apply (z_ind' (fun y => _ -> _) _).\nintro y.\nintros H H';apply zLeq_repr in H;apply zLt_repr in H'.\neapply nle_not_nlt;[apply H|apply H'].\n\napply (z_ind' (fun x => forall y, _ -> _) _).\nintro x. apply (z_ind' (fun y => _ -> _) _).\nintro y.\nintros H. apply repr_zLeq. apply not_nlt_nle. intro H'.\napply H. apply repr_zLt. assumption.\nDefined.\n\nDefinition zNat : nat -> Z := fun n => zIn (n, 0).\n\nDefinition zNat_quotEmbed : zNat = quotEmbed _ := idpath.\n\nGlobal Instance zNat_leq_embedding : IsEmbedding (<=) (<=) zNat.\nProof.\nsplit.\nred. unfold rrel.\nintros;apply repr_quotRel. simpl. change (@gidV nat _ _) with (@ZeroV nat _ _).\nunfold gop.\npattern (@plus _ nplus x 0). apply transport with x.\napply inverse. apply nplus_0_r.\napply transport with y.\napply inverse. apply nplus_0_r.\nassumption.\n\nred. unfold rrel.\nintros. apply zLeq_repr in H.\nred in H. simpl in H. unfold gop,rrel in H.\npattern x;apply transport with (x+0).\napply nplus_0_r.\napply transport with (y+0).\napply nplus_0_r.\nassumption.\nDefined.\n\n(*Nb: means zNat is injective*)\nGlobal Instance zNat_eq_embedding : IsEmbedding (paths) (paths) zNat.\nProof.\nsplit.\nred. unfold rrel.\napply ap.\n\nred. unfold rrel.\nintros. apply classes_eq_related in H.\nred in H. simpl in H.\npath_via (x+0). apply inverse;apply nplus_0_r.\npath_via (y+0). apply nplus_0_r.\nDefined.\n\nGlobal Instance zNat_neq_embedding : IsEmbedding (#) (#) zNat.\nProof.\nsplit;red;unfold rrel.\nintros. apply zApart_trivial. intro H.\napply X. apply zNat_eq_embedding. assumption.\n\nintros;intro H.\napply zApart_repr in X. apply X.\nsimpl. path_via x.\napply nplus_0_r.\npath_via y. apply inverse;apply nplus_0_r.\nDefined.\n\nLemma zLt_iff_zLeq_S : forall x y : Z, x < y <-> z1+x <= y.\nProof.\nsplit;revert y;revert x.\napply (z_ind' (fun x => forall y, _ -> _) _).\nintro x. apply (z_ind' (fun y => _ -> _) _).\nintro y.\nintros H.\nchange (z1 + zIn x) with (zIn (1%nat + fst x, snd x)).\napply repr_zLeq.\nred. simpl. unfold rrel,gop.\nchange (fst x + snd y < fst y + snd x).\napply zLt_repr in H. assumption.\n\napply (z_ind' (fun x => forall y, _ -> _) _).\nintro x. apply (z_ind' (fun y => _ -> _) _).\nintro y.\nintros H.\napply repr_zLt. red. unfold gop,rrel.\nchange (fst (1%nat + fst x, snd x) + snd y <= fst y + snd (1%nat + fst x, snd x)).\napply zLeq_repr.\napply H.\nDefined.\n\nGlobal Instance zNat_lt_embedding : IsEmbedding (<) (<) zNat.\nProof.\nsplit;red;unfold rrel,gop.\nintros ? ? H. apply zLt_iff_zLeq_S. change (zNat (1%nat+x) <= zNat y).\napply zNat_leq_embedding. assumption.\n\nintros. apply zLt_iff_zLeq_S in H.\nchange (1%nat+x <= y). apply zNat_leq_embedding. assumption.\nDefined.\n\nGlobal Instance zNat_plus_morphism : Magma.IsMorphism (+) (+) zNat.\nProof.\neapply transport. symmetry;apply zNat_quotEmbed.\napply quotEmbed_morphism.\nDefined.\n\nGlobal Instance zNat_mult_morphism : Magma.IsMorphism (°) (°) zNat.\nProof.\nred;unfold gop.\nintros.\napply (ap (class_of _)).\nunfold multU. simpl.\nchange (0 ° 0) with 0.\napply path_prod';apply inverse.\napply nplus_0_r.\npath_via (0+0).\napply ap11;[apply ap|];apply nmult_0_r.\nDefined.\n\nGlobal Instance exists_zNat_is_prop : forall z, IsHProp (exists n, zNat n = z).\nProof.\nintros. apply hprop_allpath.\nintros [n Hn] [m Hm].\ndestruct Hn.\nassert (p:m = n). apply zNat_eq_embedding. assumption.\napply path_sigma' with (inverse p).\napply ZRing_set.\nDefined.\n\nLemma zPlus_0_r : forall x, x + z0 = x.\nProof.\napply right_id. apply id_is_right. apply (@ZeroP Z ZPrering ZRing).\nDefined.\n\nLemma zLeq_exists : forall x y : Z, x <= y <~> exists n, zNat n = y + (zOppV x).\nProof.\nintros;apply equiv_iff_hprop;revert y;revert x;\napply (z_ind' (fun x => forall y, _ -> _) _);intro x;\napply (z_ind' (fun y => _ -> _) _);intro y;intro H.\n\napply zLeq_repr in H. simpl in H. apply nle_exists in H.\nexists (H.1). destruct H as [k H].\nunfold gop in H. simpl.\napply (@right_cancel Z (+) (zIn x) _). unfold gop.\npath_via (zIn y).\napply related_classes_eq. red. simpl. unfold gop.\nchange (0 + snd x) with (snd x).\neapply concat;[|apply H]. apply inverse;apply associative.\n apply nat_issemiring.\npath_via (zIn y + (zOppV (zIn x) + zIn x)).\npath_via (zIn y + z0).\napply inverse. apply zPlus_0_r.\napply ap.\napply (id_unique (+)). apply Zero.\napply (zOppP (zIn x)).\napply associative. apply ZRing.\n\napply repr_zLeq. red;simpl. unfold gop,rrel.\napply exists_nle. exists (H.1).\ndestruct H as [k H].\nsimpl.\nchange (zNat k = zIn (fst y + snd x, snd y + fst x)) in H.\napply classes_eq_related in H.\nred in H. simpl in H. unfold gop in H.\npath_via (k + (snd y + fst x)).\napply ap. apply commutative. apply nat_issemiring.\netransitivity. apply H.\napply nplus_0_r.\nDefined.\n\nLemma z0_z1_apart : z0 # z1.\nProof.\napply repr_quotRel.\nred;simpl. unfold rrel.\nintro H;apply inverse in H;apply S_0_neq in H;assumption.\nDefined.\n\nLemma z0_z1_neq : z0 != z1.\nProof.\napply zApart_trivial. apply z0_z1_apart.\nDefined.\n\n\nDefinition zAbs : Z -> nat.\nProof.\nintros z.\ndestruct (isconstrlinear z0 z) as [H|H];\nexact ((zLeq_exists _ _ H).1).\nDefined.\n\nLemma zAbs_pos_eval : forall n, zAbs (zIn (n, 0)) = n.\nProof.\nintros. unfold zAbs.\ndestruct (isconstrlinear z0 [n, 0]).\ndestruct (zLeq_exists z0 [n, 0] l).\nsimpl.\nchange (zNat x = zNat (n + 0)) in p.\napply zNat_eq_embedding in p.\npath_via (n+0). apply nplus_0_r.\n\ndestruct (zLeq_exists [n, 0] z0 l).\nsimpl. change (zNat x = [0, n]) in p.\napply classes_eq_related in p. red in p;simpl in p.\napply nplus_0_0_back in p;destruct p.\npath_via 0.\nDefined.\n\nLemma zAbs_neg_eval : forall n, zAbs (zIn (0, n)) = n.\nProof.\nintros. unfold zAbs.\ndestruct (isconstrlinear z0 [0, n]).\ndestruct (zLeq_exists z0 [0, n] l).\nsimpl.\nchange (zNat x = [0, n+0]) in p.\napply classes_eq_related in p. red in p;simpl in p.\napply nplus_0_0_back in p. destruct p.\npath_via 0. path_via (n+0). apply nplus_0_r.\n\ndestruct (zLeq_exists [0, n] z0 l).\nsimpl.\nchange (zNat x = zNat n) in p.\napply zNat_eq_embedding in p. assumption.\nDefined.\n\n(*NB: related_classes_eq means it doesn't compute well, so only use it for hprops*)\nLemma z_posneg_ind : forall P : Z -> Type,\n(forall z, IsHProp (P z)) ->\n(forall n, P [n, 0]) -> (forall n, P [0, n]) ->\nforall z, P z.\nProof.\nintros ? Hp Hv Hv'.\napply z_ind'. apply _.\nintros x.\ndestruct (isconstrlinear (snd x) (fst x));\napply nle_exists in l;destruct l as [k H].\napply transport with [k, 0].\napply related_classes_eq. red. simpl. path_via (fst x).\napply inverse;apply nplus_0_r.\napply Hv.\napply transport with [0, k].\napply related_classes_eq. red. simpl. path_via (snd x).\npath_via (k + fst x). apply commutative. apply nat_issemiring.\napply Hv'.\nDefined.\n\nLemma zAbs_0_back : forall x : Z, 0 = zAbs x -> z0 = x.\nProof.\napply (z_posneg_ind (fun x => _ -> _) _).\nintros.\nassert (0 = n). path_via (zAbs [n, 0]). apply zAbs_pos_eval.\napply (ap (fun k => [k, 0])). assumption.\n\nintros.\nassert (0 = n). path_via (zAbs [0, n]). apply zAbs_neg_eval.\napply (ap (fun k => [0, k])). assumption.\nDefined.\n\nLemma zAbs_zMult : forall a b, zAbs (a°b) = zAbs a ° zAbs b.\nProof.\napply (z_posneg_ind (fun x => forall y, _) _);intro n;\napply (z_posneg_ind (fun y => _) _);intro m;apply (@concat _ _ (n°m)).\n\n- transitivity (zAbs [n°m, 0]).\n  apply (ap (fun x => zAbs (class_of _ x))).\n  unfold multU. simpl.\n  apply path_prod'.\n  apply nplus_0_r.\n  change (n°0 + m°0 = 0 + 0).\n  apply ap11;[apply ap|];apply nmult_0_r.\n  apply zAbs_pos_eval.\n- apply inverse;apply ap11;[apply ap|];apply zAbs_pos_eval.\n\n- transitivity (zAbs [0, n°m]).\n  apply (ap (fun x => zAbs (class_of _ x))).\n  unfold multU;simpl.\n  apply path_prod'.\n  apply (@concat _ _ (n°0)).\n  apply nplus_0_r. apply nmult_0_r.\n  apply nplus_0_r.\n  apply zAbs_neg_eval.\n- apply inverse;apply ap11;[apply ap|].\n  apply zAbs_pos_eval.\n  apply zAbs_neg_eval.\n\n- apply (@concat _ _ (zAbs [0, n°m])).\n  apply (ap (fun x => zAbs (class_of _ x))).\n  unfold multU;simpl.\n  apply path_prod'.\n  change (n°0 = 0). apply nmult_0_r.\n  change (m°n = n°m). apply nmult_comm.\n  apply zAbs_neg_eval.\n- apply inverse;apply ap11;[apply ap|].\n  apply zAbs_neg_eval.\n  apply zAbs_pos_eval.\n\n- apply(@concat _ _ (zAbs [n°m, 0])).\n  apply (ap (fun x => zAbs (class_of _ x))).\n  unfold multU;simpl;apply path_prod'.\n  reflexivity.\n  reflexivity.\n  apply zAbs_pos_eval.\n- apply inverse;apply ap11;[apply ap|];apply zAbs_neg_eval.\nQed.\n\nGlobal Instance Z_strict_integral : IsStrictIntegral ZPrering.\nProof.\nred.\nchange ZeroV with [0, 0].\nintros. apply min1.\napply (ap zAbs) in H.\nassert (H' : 0 = zAbs a ° zAbs b).\napply (@concat _ _(zAbs (a°b))).\napply (@concat _ _ (zAbs [0, 0])).\napply inverse;apply zAbs_pos_eval.\napply H.\n\napply zAbs_zMult.\napply nmult_integral in H'.\nclear H. destruct H' as [H|H];[left|right];apply zAbs_0_back;assumption.\nDefined.\n\nEnd NotaSec.\n\nEnd Relative.\n\n\n\n", "meta": {"author": "SkySkimmer", "repo": "HoTT-algebra", "sha": "d5a4627d5d222e0f889591296d84f60234a00daa", "save_path": "github-repos/coq/SkySkimmer-HoTT-algebra", "path": "github-repos/coq/SkySkimmer-HoTT-algebra/HoTT-algebra-d5a4627d5d222e0f889591296d84f60234a00daa/z_struct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6809724762331162}}
{"text": "(* (c) Copyright 2006-2018 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat.\n\n(******************************************************************************)\n(* We define two combinatorial functions:                                     *)\n(*        dyck n == the number of balanced bracket words of length n          *)\n(*  gen_dyck m n == the number of balanced bracket word fragments of length n *)\n(*                  with m-1 extra closing brackets: dyck n = gen_dyck 1 n    *)\n(* These ``Dyck numbers'', are closely related to the well-known Catalan      *)\n(* numbers,                                                                   *)\n(*            1   /2n\\                                                        *)\n(*     C_n = --- (    )                                                       *)\n(*           n+1  \\ n/                                                        *)\n(* More precisely, dick n = C_(n/2) if n is even, and 0 if n is odd; the      *)\n(* gen_dyck m n are similarly related to the Catalan-Fuss (or Raney) numbers  *)\n(* A_{(n+1-m)/2}(2,m); however they are defined using a non-standard          *)\n(* recurrence that simplifies the correctness proof of the initial data of    *)\n(* the reducibility check. Indeed, Dyck numbers are the only link between the *)\n(* initial color and (chromo)gram trees.                                      *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nFixpoint gen_dyck m n {struct n} :=\n  match n, m with\n  | 0, 1 => 1\n  | n'.+1, m'.+1 => gen_dyck m.+1 n' + gen_dyck m' n'\n  | _, _ => 0\n  end.\n\nDefinition dyck := gen_dyck 1.\n\nLemma gen_dyck_max m n : n.+1 < m -> gen_dyck m n = 0.\nProof.\nelim: n m => [|n IHn] [] //= => [[] // | m lt_n1_m].\nby rewrite !IHn // 2?ltnW.\nQed.\n\nLemma gen_dyck_all_close m : gen_dyck m.+1 m = 1.\nProof. by elim: m => //= m ->; rewrite gen_dyck_max. Qed.\n\nLemma even_dyck_pos n : 0 < dyck n.*2.\nProof.\nrewrite -[n.*2]addn0 /dyck; elim: n {-1}0 => [|n IHn] m.\n  by rewrite gen_dyck_all_close.\nby rewrite doubleS addSnnS addSn ltn_addr.\nQed.\n", "meta": {"author": "coq-community", "repo": "fourcolor", "sha": "e831b0b00e264285f91938917a0a5ef64ec1a829", "save_path": "github-repos/coq/coq-community-fourcolor", "path": "github-repos/coq/coq-community-fourcolor/fourcolor-e831b0b00e264285f91938917a0a5ef64ec1a829/theories/dyck.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.680972475902521}}
{"text": "\nSection Sets.\n\n  (* Extensional: Enumeration *)\n  (* Seen this style of definition before... *)\n  Definition Set' (A : Type) := list A.\n\n  (* Intensional: Characteristic 'Function' *)\n  Definition Bool_Set (A : Type) := A -> bool.\n\n  (* Definition evens' : Bool_Set nat := evenb. *)\n\n  Definition In_b {A} (a : A) (e : Bool_Set A) : Prop :=\n    e a = true.\n\n  Definition Same_Set' {A} (e1 e2 : Bool_Set A) : Prop :=\n    forall x, e1 x = e2 x.\n\n  (* How to define Intersection, Union, Subset ? *)\n  Definition Union' {A} (e1 e2 : Bool_Set A) : Bool_Set A :=\n    fun x => orb (e1 x) (e2 x).\n\n  Definition Intersection' {A} (e1 e2 : Bool_Set A)\n    : Bool_Set A :=\n    fun x => andb (e1 x) (e2 x).\n\n  Definition Subset' {A} (e1 e2 : Bool_Set A) : Prop :=\n    forall x, In_b e1 x -> In_b e2 x.\n\n  (* This encoding of sets means membership is always decideable! *)\n  \nEnd Sets.\n\nSection Fixpoints.\n\n  (* Propositional analogues to definitions from above. *)\n\n  Definition PSet (A : Type) := A -> Prop.\n  \n  Definition In {A} (a : A) (e : PSet A) : Prop := e a.\n  Notation \"x '∈' e\" := (In x e) (at level 60).\n\n  Definition Subset {A} (e1 e2 : PSet A) : Prop :=\n    forall x, x ∈ e1 -> x ∈ e2.\n  \n  Notation \"s1 ⊆ s2\" := (Subset s1 s2) (at level 60).\n  \n  Context {U : Type}. (* The universal set, i.e. our domain of discourse. *)\n  Variable F : (PSet U) -> PSet U. (* Our generating function--\n  takes a set of Us and builds a new set.*)\n\n  (* A generator function is monotone if it preserves the subset\n  relation on its argument. *)\n  Definition Monotone_F : Prop :=\n    forall (S S' : PSet U),\n      S ⊆ S' -> F S ⊆ F S'.\n  \n  Definition FClosed (S : PSet U) : Prop := F S ⊆ S.\n  \n  Definition FConsistent (S : PSet U) : Prop := S ⊆ F S.\n  \n  Definition FixedPoint (S : PSet U) : Prop :=\n    S ⊆ F S /\\ F S ⊆ S.\n\n  (* The least fixed point of a monotone generator function exists,\n   and it is the intersection of all F-closed sets. *)\n  Definition LFP : PSet U :=\n    fun a => forall S, FClosed S -> S a.\n\n  (* The greatest fixed point of a generator function exists, \n   and it is the union of all F-consistent sets. *)\n  Definition GFP : PSet U :=\n    fun a => exists S, FConsistent S /\\ S a.\n\n  Lemma GFP_is_FConsistent \n    : Monotone_F -> FConsistent GFP.\n  Proof.\n    intros F_Monotone. \n    unfold FConsistent.\n    intros ? ?.\n    (* By the definition of GFP, there must be some F-consistent set, X, that contains x *)\n    destruct H as [X [? ?] ]. \n    (* Since X is F-consistent, by definition x is a member of F X. *)\n    apply H in H0.\n    (* We have now established that F X ⊆ F GFP: *)\n    revert x H0; fold (Subset (F X) (F GFP)).\n    (* Since F is monotone, it suffices to show that X ⊆ GFP *)\n    eapply F_Monotone.\n    (* To show X ⊆ GFP, we just need to show that every x in X is in GFP *)\n    intros ? ?.\n    (* By definition, x is an element of GFP if it is a member of an\n    F-consistent set. By assumption, x is in X and F is F-consistent,\n    so we're done!*)\n    unfold In, GFP.\n    eexists X.\n    eauto.\n  Qed.\n  \n  Lemma GFP_is_FClosed \n    : Monotone_F -> FClosed GFP.\n  Proof.\n    intros F_Monotone ? ?.\n    (* By our previous lemma, we know that GFP ⊆ F GFP. By monotonicity of \n       F, F GFP ⊆ F (F GFP). *)\n    assert (F GFP ⊆ F (F GFP)).\n    { apply F_Monotone.\n      apply GFP_is_FConsistent.\n      eassumption. }\n    (* By definition, this means F GFP is F-consistent. *)\n    assert (FConsistent (F GFP)).\n    { intros ? ?.\n      apply H0.\n      assumption. }\n    (* Since F is a member of an F-consistent set, it must be a member\n    of GFP.*)\n    unfold In, GFP.\n    exists (F GFP).\n    eauto.\n  Qed.\n  \n  Theorem GFP_is_FixedPoint\n    : Monotone_F -> FixedPoint GFP.\n  Proof.\n    intro F_Monotone.\n    unfold FixedPoint.\n    split.\n    - apply GFP_is_FConsistent; eauto.\n    - apply GFP_is_FClosed; eauto.\n  Qed.\n  \n  Theorem LFP_is_FClosed\n    : Monotone_F -> FClosed LFP.\n  Proof.\n  Admitted.\n    \n  Theorem LFP_is_FConsistent\n    : Monotone_F -> FConsistent LFP.\n  Proof.\n  Admitted.\n\n  Theorem LFP_is_FixedPoint\n    : Monotone_F -> FixedPoint LFP.\n  Proof.\n    intro F_Monotone.\n    unfold FixedPoint.\n    split.\n    - apply LFP_is_FConsistent; eauto.\n    - apply LFP_is_FClosed; eauto.\n  Qed.\n  \n  Lemma Ind \n    : forall (Ind : PSet U),\n      FClosed Ind -> forall a, LFP a -> Ind a.\n  Proof.\n    unfold LFP, FClosed; intros; eapply H0; eauto.\n  Qed.\n  \n  Lemma CoInd \n    : forall (Ind : PSet U),\n      FConsistent Ind -> forall a, Ind a -> GFP a.\n  Proof.\n    unfold GFP, FConsistent; intros; eauto.\n  Qed.\n\nEnd Fixpoints.\n\nInductive isEven : nat -> Prop :=\n| isEvenZero : isEven 0\n| isEvenSS : forall (n : nat), isEven n -> isEven (S (S n)).\n  \nDefinition isEven_F : PSet nat -> PSet nat :=\n  fun X n => (n = 0) \\/ (exists n', X n' /\\ n = S (S n')).\n\nDefinition isEven' := LFP isEven_F.\n\nTheorem isEven_eqv : forall n,\n    isEven n <-> isEven' n.\nProof.\n  split; intro.\n  - induction H.\n    + unfold isEven', LFP. \n      intros.\n      apply H.\n      unfold isEven_F, In; intuition.\n    + unfold isEven', LFP. \n      intros.\n      apply H0.\n      unfold isEven_F, In; right.\n      eexists; intuition.\n      unfold isEven' in IHisEven.\n      apply IHisEven in H0; eauto.\n  - unfold LFP in H. eapply Ind; try eassumption.\n    intros ? ?; unfold In in *.\n    destruct H0 as [ | [n' [? ?] ] ]; subst.\n    + econstructor.\n    + econstructor.\n      eassumption.\nQed.\n\n(* Start coinduction chapter from CPDT here. *)\n\nSection stream.\n  Context (A : Type).\n\n  CoInductive stream : Type :=\n  | Cons : A -> stream -> stream.\nEnd stream.\n\nArguments Cons {A} _ _.\n\nCoFixpoint zeroes : stream nat := Cons 0 zeroes.\n\n(** We can also define a stream that alternates between [true] and [false]. *)\n\nCoFixpoint trues_falses : stream bool := Cons true falses_trues\nwith falses_trues : stream bool := Cons false trues_falses.\n\n(** Co-inductive values are fair game as arguments to recursive\nfunctions, and we can use that fact to write a function to take a\nfinite approximation of a stream. *)\n\nFixpoint approx {A} (s : stream A) (n : nat) : list A :=\n  match n with\n    | O => nil\n    | S n' =>\n      match s with\n        | Cons h t => h :: approx t n'\n      end\n  end.\n\nEval simpl in approx zeroes 10.\n\nEval simpl in approx trues_falses 10.\n\nFail CoFixpoint looper : stream nat := looper.\n\nSection map.\n  Variables A B : Type.\n  Variable f : A -> B.\n\n  CoFixpoint map (s : stream A) : stream B :=\n    match s with\n      | Cons h t => Cons (f h) (map t)\n    end.\nEnd map.\n\nSection interleave.\n  Variable A : Type.\n\n  CoFixpoint interleave (s1 s2 : stream A) : stream A :=\n    match s1, s2 with\n      | Cons h1 t1, Cons h2 t2 => Cons h1 (Cons h2 (interleave t1 t2))\n    end.\nEnd interleave.\n\nSection map'.\n  Variables A B : Type.\n  Variable f : A -> B.\n\n  Fail CoFixpoint map' (s : stream A) : stream B :=\n    match s with\n      | Cons h t => interleave (Cons (f h) (map' t)) (Cons (f h) (map' t))\n    end.\n\nEnd map'.\n\nDefinition tl A (s : stream A) : stream A :=\n  match s with\n    | Cons _ s' => s'\n  end.\n\nFail CoFixpoint bad : stream nat := tl _ (Cons 0 bad).\n\nFail CoFixpoint bad : stream nat := bad.\n\n(** * Infinite Proofs *)\n\n(** Let us say we want to give two different definitions of a stream\nof all ones, and then we want to prove that they are equivalent. *)\n\nCoFixpoint ones : stream nat := Cons 1 ones.\nDefinition ones' := map _ _ S zeroes.\n\n(** The obvious statement of the equality is this: *)\n\nTheorem ones_eq : ones = ones'.\n  \nAbort.\n\nSection stream_eq.\n  Context {A : Type}.\n\n  CoInductive stream_eq : stream A -> stream A -> Prop :=\n  | Stream_eq : forall h t1 t2,\n    stream_eq t1 t2\n    -> stream_eq (Cons h t1) (Cons h t2).\nEnd stream_eq.\n\nTheorem ones_eq : stream_eq ones ones'.\n\n  cofix ones_eq.\n\n  assumption.\n\n  Undo.\n  simpl.\n\nAbort.\n\n(** First, we need to define a function that seems pointless at first glance. *)\n\nDefinition frob {A} (s : stream A) : stream A :=\n  match s with\n    | Cons h t => Cons h t\n  end.\n\n(** Next, we need to prove a theorem that seems equally pointless. *)\n\nTheorem frob_eq : forall {A} (s : stream A), s = frob s.\n  destruct s; reflexivity.\nQed.\n\n(** But, miraculously, this theorem turns out to be just what we needed. *)\n\nTheorem ones_eq : stream_eq ones ones'.\n  cofix ones_eq.\n\n  (** We can use the theorem to rewrite the two streams. *)\n\n  rewrite (frob_eq ones).\n  rewrite (frob_eq ones').\n\n  simpl.\n\n  constructor.\n\n  assumption.\nQed.\n\nRequire Coq.Setoids.Setoid.\n\nDefinition stream_eq_F {A : Type} : PSet (stream A * stream A) -> PSet (stream A * stream A) :=\n  fun X s => exists h t1 t2, In (t1, t2) X /\\ fst s = (Cons h t1) /\\ snd s = (Cons h t2).\n\nDefinition stream_eq' {A} := GFP (@stream_eq_F A).\n\nTheorem ones_eq' : stream_eq' (ones, ones').\n  unfold stream_eq'.\n  eapply CoInd.\n  unfold FConsistent, Subset, In.\n  intros [t1 t2].\n  instantiate (1 := fun s => s = (ones, ones')).\n  simpl; intros.\n  injection H; intros.\n  subst.\n  unfold stream_eq_F.\n  eexists 1, ones, ones'; intuition.\n  simpl; rewrite (frob_eq ones) at 1; reflexivity.\n  simpl; rewrite (frob_eq ones') at 1; reflexivity.\n  reflexivity.\nQed.\n", "meta": {"author": "Kraks", "repo": "playground", "sha": "677da3823615d4e241f7d1de05ee9b79ddabb118", "save_path": "github-repos/coq/Kraks-playground", "path": "github-repos/coq/Kraks-playground/playground-677da3823615d4e241f7d1de05ee9b79ddabb118/coq/FixpointsWalkthrough.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6809649104560392}}
{"text": "Require Import Coq.Lists.ListSet.\nRequire Import CpdtTactics.\nRequire Import List.\n\n\nDefinition set_eq {A} (s t : set A) := forall x, set_In x s <-> set_In x t.\nLemma empty_elim {A} (s : A) : ~ set_In s (empty_set A).\nintro.\nunfold set_In, empty_set in *.\ndestruct H.\nQed.\n\nDefinition set_disjoint {A} (H : forall x y : A, {x=y} + {x <> y}) (s t : set A) :=\n  forall x, ~ (set_In x (set_inter H s t)).\n\nFixpoint allpairs {A} (xs : list A) : list (A * A) :=\n  match xs with\n  | nil => nil\n  | h :: t =>\n    map (fun y => (h,y)) t ++ allpairs t\n  end.\n    \n           \n\nDefinition set_pairwise_disjoint {A} (H : forall x y : A, {x=y} + {x <> y}) (xs : list (set A)) :=\n  fold_left (fun acc p => acc /\\ set_disjoint H (fst p) (snd p)) (allpairs xs) True.\n\n  Lemma set_union_assoc {A : Set} {eqA : forall (x y : A), {x = y} + {x <> y}} : forall (s1 s2 s3 : set A),\n      set_eq (set_union eqA s1 (set_union eqA s2 s3)) (set_union eqA (set_union eqA s1 s2) s3).\n    intros.\n    unfold set_eq.\n    split.\n    intros.\n    apply set_union_elim in H; destruct H.\n    apply set_union_intro.\n    left; apply set_union_intro; left; crush.\n    apply set_union_elim in H; destruct H.\n    apply set_union_intro; left; apply set_union_intro; right; crush.\n    apply set_union_intro; right; crush.\n    intros.\n    apply set_union_elim in H; destruct H as [H1 | H2]; [apply set_union_elim in H1; destruct H1 | idtac].\n    apply set_union_intro; left; crush.\n    apply set_union_intro; right; apply set_union_intro; left; crush.\n    apply set_union_intro; right; apply set_union_intro; right; crush.\n  Qed.\n\n\n  Lemma set_union_not_in {A : Set} {eqA : forall (x y : A), {x = y} + {x <> y}} : forall (s1 s2 : set A) x,\n      ~ (set_In x (set_union eqA s1 s2)) -> (~ set_In x s1) /\\ (~ set_In x s2).\n    intros.\n    split; intro.\n    apply H.\n    apply set_union_intro; left; crush.\n    apply H.\n    apply set_union_intro; right; crush.\n Qed.\n\n\n  Lemma set_union_cong {A : Set} {eqA : forall (x y : A), {x = y} + {x <> y}} : forall (s1 s2 s3 s4 : set A),\n      set_eq s1 s2 -> set_eq s3 s4 -> set_eq (set_union eqA s1 s3) (set_union eqA s2 s4).\n    intros; unfold set_eq in *.\n    intros; split; intros.\n    apply set_union_elim in H1; destruct H1.\n    apply set_union_intro; left; apply H; crush.\n    apply set_union_intro; right; apply H0; crush.\n\n    apply set_union_elim in H1; destruct H1.\n    apply set_union_intro; left; apply H; crush.\n    apply set_union_intro; right; apply H0; crush.\n  Qed.\n\n  Lemma set_union_symm {A : Set} {eqA : forall (x y : A), {x = y} + {x <> y}} : forall (s1 s2 : set A), set_eq (set_union eqA s1 s2) (set_union eqA s2 s1).\n    intros.\n    unfold set_eq.\n    intros; split; intros H; apply set_union_elim in H; destruct H; apply set_union_intro; crush.\n  Qed.\n\n  Lemma set_diff_cong {A : Set} {eqA : forall (x y : A), {x = y} + {x <> y}} : forall (s1 s2 s3 s4 : set A),\n      set_eq s1 s2 -> set_eq s3 s4 -> set_eq (set_diff eqA s1 s3) (set_diff eqA s2 s4).\n    intros.\n    unfold set_eq; intros; split; intros G; apply set_diff_iff in G; destruct G; apply set_diff_iff.\n    split; [apply H | intro; apply H2; apply H0]; crush.\n    split; [apply H | intro; apply H2; apply H0]; crush.\n  Qed.\n\n  Lemma set_eq_refl : forall {A : Set} (s : set A), set_eq s s.\n    unfold set_eq; crush.\n  Qed.\n\n  Lemma set_eq_trans : forall {A : Set} (s1 s2 s3 : set A), set_eq s1 s2 -> set_eq s2 s3 -> set_eq s1 s3.\n    intros; unfold set_eq in *.\n    split; intros.\n    apply H0; apply H; crush.\n    apply H; apply H0; crush.\n  Qed.\n", "meta": {"author": "gancherj", "repo": "formal-prot", "sha": "49dbdfa5855a4cf05a30a72df9de1953e2fea743", "save_path": "github-repos/coq/gancherj-formal-prot", "path": "github-repos/coq/gancherj-formal-prot/formal-prot-49dbdfa5855a4cf05a30a72df9de1953e2fea743/coq/SetLems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.6809649071609697}}
{"text": "(* Copyright (c) 2008-2012, 2015, Adam Chlipala\n * \n * This work is licensed under a\n * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0\n * Unported License.\n * The license text is available at:\n *   http://creativecommons.org/licenses/by-nc-nd/3.0/\n *)\n\n(* begin hide *)\nRequire Import List.\n\nRequire Import Cpdt.CpdtTactics Cpdt.MoreSpecif.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n(* end hide *)\n\n\n(** %\\chapter{Proof by Reflection}% *)\n\n(** The last chapter highlighted a very heuristic approach to proving.  In this chapter, we will study an alternative technique,%\\index{proof by reflection}% _proof by reflection_ %\\cite{reflection}%.  We will write, in Gallina, decision procedures with proofs of correctness, and we will appeal to these procedures in writing very short proofs.  Such a proof is checked by running the decision procedure.  The term _reflection_ applies because we will need to translate Gallina propositions into values of inductive types representing syntax, so that Gallina programs may analyze them, and translating such a term back to the original form is called _reflecting_ it. *)\n\n\n(** * Proving Evenness *)\n\n(** Proving that particular natural number constants are even is certainly something we would rather have happen automatically.  The Ltac-programming techniques that we learned in the last chapter make it easy to implement such a procedure. *)\n\nInductive isEven : nat -> Prop :=\n| Even_O : isEven O\n| Even_SS : forall n, isEven n -> isEven (S (S n)).\n\n(* begin thide *)\nLtac prove_even := repeat constructor.\n(* end thide *)\n\nTheorem even_256 : isEven 256.\n  prove_even.\nQed.\n\nPrint even_256.\n(** %\\vspace{-.15in}% [[\neven_256 = \nEven_SS\n  (Even_SS\n     (Even_SS\n        (Even_SS\n    ]]\n\n    %\\noindent%...and so on.  This procedure always works (at least on machines with infinite resources), but it has a serious drawback, which we see when we print the proof it generates that 256 is even.  The final proof term has length super-linear in the input value.  Coq's implicit arguments mechanism is hiding the values given for parameter [n] of [Even_SS], which is why the proof term only appears linear here.  Also, proof terms are represented internally as syntax trees, with opportunity for sharing of node representations, but in this chapter we will measure proof term size as simple textual length or as the number of nodes in the term's syntax tree, two measures that are approximately equivalent.  Sometimes apparently large proof terms have enough internal sharing that they take up less memory than we expect, but one avoids having to reason about such sharing by ensuring that the size of a sharing-free version of a term is low enough.\n\n    Superlinear evenness proof terms seem like a shame, since we could write a trivial and trustworthy program to verify evenness of constants.  The proof checker could simply call our program where needed.\n\n    It is also unfortunate not to have static typing guarantees that our tactic always behaves appropriately.  Other invocations of similar tactics might fail with dynamic type errors, and we would not know about the bugs behind these errors until we happened to attempt to prove complex enough goals.\n\n    The techniques of proof by reflection address both complaints.  We will be able to write proofs like in the example above with constant size overhead beyond the size of the input, and we will do it with verified decision procedures written in Gallina.\n\n    For this example, we begin by using a type from the [MoreSpecif] module (included in the book source) to write a certified evenness checker. *)\n\n(* begin hide *)\n(* begin thide *)\nDefinition paartial := partial.\n(* end thide *)\n(* end hide *)\n\nPrint partial.\n(** %\\vspace{-.15in}% [[\nInductive partial (P : Prop) : Set :=  Proved : P -> [P] | Uncertain : [P]\n    ]]\n\n    A [partial P] value is an optional proof of [P]. The notation [[P]] stands for [partial P]. *)\n\nLocal Open Scope partial_scope.\n\n(** We bring into scope some notations for the [partial] type.  These overlap with some of the notations we have seen previously for specification types, so they were placed in a separate scope that needs separate opening. *)\n\n(* begin thide *)\nDefinition check_even : forall n : nat, [isEven n].\n  Hint Constructors isEven.\n\n  refine (fix F (n : nat) : [isEven n] :=\n    match n with\n      | 0 => Yes\n      | 1 => No\n      | S (S n') => Reduce (F n')\n    end); auto.\nDefined.\n\n(** The function [check_even] may be viewed as a _verified decision procedure_, because its type guarantees that it never returns %\\coqdocnotation{%#<tt>#Yes#</tt>#%}% for inputs that are not even.\n\n   Now we can use dependent pattern-matching to write a function that performs a surprising feat.  When given a [partial P], this function [partialOut] returns a proof of [P] if the [partial] value contains a proof, and it returns a (useless) proof of [True] otherwise.  From the standpoint of ML and Haskell programming, it seems impossible to write such a type, but it is trivial with a [return] annotation. *)\n\nDefinition partialOut (P : Prop) (x : [P]) :=\n  match x return (match x with\n                    | Proved _ => P\n                    | Uncertain => True\n                  end) with\n    | Proved pf => pf\n    | Uncertain => I\n  end.\n\n(** It may seem strange to define a function like this.  However, it turns out to be very useful in writing a reflective version of our earlier [prove_even] tactic: *)\n\nLtac prove_even_reflective :=\n  match goal with\n    | [ |- isEven ?N] => exact (partialOut (check_even N))\n  end.\n(* end thide *)\n\n(** We identify which natural number we are considering, and we \"prove\" its evenness by pulling the proof out of the appropriate [check_even] call.  Recall that the %\\index{tactics!exact}%[exact] tactic proves a proposition [P] when given a proof term of precisely type [P]. *)\n\nTheorem even_256' : isEven 256.\n  prove_even_reflective.\nQed.\n\nPrint even_256'.\n(** %\\vspace{-.15in}% [[\neven_256' = partialOut (check_even 256)\n     : isEven 256\n    ]]\n\n    We can see a constant wrapper around the object of the proof.  For any even number, this form of proof will suffice.  The size of the proof term is now linear in the number being checked, containing two repetitions of the unary form of that number, one of which is hidden above within the implicit argument to [partialOut].\n\n    What happens if we try the tactic with an odd number? *)\n\nTheorem even_255 : isEven 255.\n  (** %\\vspace{-.275in}%[[\n  prove_even_reflective.\n]]\n\n<<\nUser error: No matching clauses for match goal\n>>\n\n  Thankfully, the tactic fails.  To see more precisely what goes wrong, we can run manually the body of the [match].\n\n  %\\vspace{-.15in}%[[\n  exact (partialOut (check_even 255)).\n]]\n\n<<\n  Error: The term \"partialOut (check_even 255)\" has type\n \"match check_even 255 with\n  | Yes => isEven 255\n  | No => True\n  end\" while it is expected to have type \"isEven 255\"\n>>\n\n  As usual, the type checker performs no reductions to simplify error messages.  If we reduced the first term ourselves, we would see that [check_even 255] reduces to a %\\coqdocnotation{%#<tt>#No#</tt>#%}%, so that the first term is equivalent to [True], which certainly does not unify with [isEven 255]. *)\n\nAbort.\n\n(** Our tactic [prove_even_reflective] is reflective because it performs a proof search process (a trivial one, in this case) wholly within Gallina, where the only use of Ltac is to translate a goal into an appropriate use of [check_even]. *)\n\n\n(** * Reifying the Syntax of a Trivial Tautology Language *)\n\n(** We might also like to have reflective proofs of trivial tautologies like this one: *)\n\nTheorem true_galore : (True /\\ True) -> (True \\/ (True /\\ (True -> True))).\n  tauto.\nQed.\n\n(* begin hide *)\n(* begin thide *)\nDefinition tg := (and_ind, or_introl).\n(* end thide *)\n(* end hide *)\n\nPrint true_galore.\n(** %\\vspace{-.15in}% [[\ntrue_galore = \nfun H : True /\\ True =>\nand_ind (fun _ _ : True => or_introl (True /\\ (True -> True)) I) H\n     : True /\\ True -> True \\/ True /\\ (True -> True)\n    ]]\n\n    As we might expect, the proof that [tauto] builds contains explicit applications of natural deduction rules.  For large formulas, this can add a linear amount of proof size overhead, beyond the size of the input.\n\n   To write a reflective procedure for this class of goals, we will need to get into the actual \"reflection\" part of \"proof by reflection.\"  It is impossible to case-analyze a [Prop] in any way in Gallina.  We must%\\index{reification}% _reify_ [Prop] into some type that we _can_ analyze.  This inductive type is a good candidate: *)\n\n(* begin thide *)\nInductive taut : Set :=\n| TautTrue : taut\n| TautAnd : taut -> taut -> taut\n| TautOr : taut -> taut -> taut\n| TautImp : taut -> taut -> taut.\n\n(** We write a recursive function to _reflect_ this syntax back to [Prop].  Such functions are also called%\\index{interpretation function}% _interpretation functions_, and we have used them in previous examples to give semantics to small programming languages. *)\n\nFixpoint tautDenote (t : taut) : Prop :=\n  match t with\n    | TautTrue => True\n    | TautAnd t1 t2 => tautDenote t1 /\\ tautDenote t2\n    | TautOr t1 t2 => tautDenote t1 \\/ tautDenote t2\n    | TautImp t1 t2 => tautDenote t1 -> tautDenote t2\n  end.\n\n(** It is easy to prove that every formula in the range of [tautDenote] is true. *)\n\nTheorem tautTrue : forall t, tautDenote t.\n  induction t; crush.\nQed.\n\n(** To use [tautTrue] to prove particular formulas, we need to implement the syntax reification process.  A recursive Ltac function does the job. *)\n\nLtac tautReify P :=\n  match P with\n    | True => TautTrue\n    | ?P1 /\\ ?P2 =>\n      let t1 := tautReify P1 in\n      let t2 := tautReify P2 in\n        constr:(TautAnd t1 t2)\n    | ?P1 \\/ ?P2 =>\n      let t1 := tautReify P1 in\n      let t2 := tautReify P2 in\n        constr:(TautOr t1 t2)\n    | ?P1 -> ?P2 =>\n      let t1 := tautReify P1 in\n      let t2 := tautReify P2 in\n        constr:(TautImp t1 t2)\n  end.\n\n(** With [tautReify] available, it is easy to finish our reflective tactic.  We look at the goal formula, reify it, and apply [tautTrue] to the reified formula. *)\n\nLtac obvious :=\n  match goal with\n    | [ |- ?P ] =>\n      let t := tautReify P in\n        exact (tautTrue t)\n  end.\n\n(** We can verify that [obvious] solves our original example, with a proof term that does not mention details of the proof. *)\n(* end thide *)\n\nTheorem true_galore' : (True /\\ True) -> (True \\/ (True /\\ (True -> True))).\n  obvious.\nQed.\n\nPrint true_galore'.\n(** %\\vspace{-.15in}% [[\ntrue_galore' = \ntautTrue\n  (TautImp (TautAnd TautTrue TautTrue)\n     (TautOr TautTrue (TautAnd TautTrue (TautImp TautTrue TautTrue))))\n     : True /\\ True -> True \\/ True /\\ (True -> True)\n    ]]\n\n    It is worth considering how the reflective tactic improves on a pure-Ltac implementation.  The formula reification process is just as ad-hoc as before, so we gain little there.  In general, proofs will be more complicated than formula translation, and the \"generic proof rule\" that we apply here _is_ on much better formal footing than a recursive Ltac function.  The dependent type of the proof guarantees that it \"works\" on any input formula.  This benefit is in addition to the proof-size improvement that we have already seen.\n\n    It may also be worth pointing out that our previous example of evenness testing used a function [partialOut] for sound handling of input goals that the verified decision procedure fails to prove.  Here, we prove that our procedure [tautTrue] (recall that an inductive proof may be viewed as a recursive procedure) is able to prove any goal representable in [taut], so no extra step is necessary. *)\n\n\n(** * A Monoid Expression Simplifier *)\n\n(** Proof by reflection does not require encoding of all of the syntax in a goal.  We can insert \"variables\" in our syntax types to allow injection of arbitrary pieces, even if we cannot apply specialized reasoning to them.  In this section, we explore that possibility by writing a tactic for normalizing monoid equations. *)\n\nSection monoid.\n  Variable A : Set.\n  Variable e : A.\n  Variable f : A -> A -> A.\n\n  Infix \"+\" := f.\n\n  Hypothesis assoc : forall a b c, (a + b) + c = a + (b + c).\n  Hypothesis identl : forall a, e + a = a.\n  Hypothesis identr : forall a, a + e = a.\n\n  (** We add variables and hypotheses characterizing an arbitrary instance of the algebraic structure of monoids.  We have an associative binary operator and an identity element for it.\n\n     It is easy to define an expression tree type for monoid expressions.  A [Var] constructor is a \"catch-all\" case for subexpressions that we cannot model.  These subexpressions could be actual Gallina variables, or they could just use functions that our tactic is unable to understand. *)\n\n(* begin thide *)\n  Inductive mexp : Set :=\n  | Ident : mexp\n  | Var : A -> mexp\n  | Op : mexp -> mexp -> mexp.\n\n  (** Next, we write an interpretation function. *)\n\n  Fixpoint mdenote (me : mexp) : A :=\n    match me with\n      | Ident => e\n      | Var v => v\n      | Op me1 me2 => mdenote me1 + mdenote me2\n    end.\n\n  (** We will normalize expressions by flattening them into lists, via associativity, so it is helpful to have a denotation function for lists of monoid values. *)\n\n  Fixpoint mldenote (ls : list A) : A :=\n    match ls with\n      | nil => e\n      | x :: ls' => x + mldenote ls'\n    end.\n\n  (** The flattening function itself is easy to implement. *)\n\n  Fixpoint flatten (me : mexp) : list A :=\n    match me with\n      | Ident => nil\n      | Var x => x :: nil\n      | Op me1 me2 => flatten me1 ++ flatten me2\n    end.\n\n  (** This function has a straightforward correctness proof in terms of our [denote] functions. *)\n\n  Lemma flatten_correct' : forall ml2 ml1,\n    mldenote ml1 + mldenote ml2 = mldenote (ml1 ++ ml2).\n    induction ml1; crush.\n  Qed.\n\n  Theorem flatten_correct : forall me, mdenote me = mldenote (flatten me).\n    Hint Resolve flatten_correct'.\n\n    induction me; crush.\n  Qed.\n\n  (** Now it is easy to prove a theorem that will be the main tool behind our simplification tactic. *)\n\n  Theorem monoid_reflect : forall me1 me2,\n    mldenote (flatten me1) = mldenote (flatten me2)\n    -> mdenote me1 = mdenote me2.\n    intros; repeat rewrite flatten_correct; assumption.\n  Qed.\n\n  (** We implement reification into the [mexp] type. *)\n\n  Ltac reify me :=\n    match me with\n      | e => Ident\n      | ?me1 + ?me2 =>\n        let r1 := reify me1 in\n        let r2 := reify me2 in\n          constr:(Op r1 r2)\n      | _ => constr:(Var me)\n    end.\n\n  (** The final [monoid] tactic works on goals that equate two monoid terms.  We reify each and change the goal to refer to the reified versions, finishing off by applying [monoid_reflect] and simplifying uses of [mldenote].  Recall that the %\\index{tactics!change}%[change] tactic replaces a conclusion formula with another that is definitionally equal to it. *)\n\n  Ltac monoid :=\n    match goal with\n      | [ |- ?me1 = ?me2 ] =>\n        let r1 := reify me1 in\n        let r2 := reify me2 in\n          change (mdenote r1 = mdenote r2);\n            apply monoid_reflect; simpl\n    end.\n\n  (** We can make short work of theorems like this one: *)\n\n(* end thide *)\n\n  Theorem t1 : forall a b c d, a + b + c + d = a + (b + c) + d.\n    intros; monoid.\n    (** [[\n  ============================\n   a + (b + (c + (d + e))) = a + (b + (c + (d + e)))\n \n        ]]\n\n        Our tactic has canonicalized both sides of the equality, such that we can finish the proof by reflexivity. *)\n\n    reflexivity.\n  Qed.\n\n  (** It is interesting to look at the form of the proof. *)\n\n  Print t1.\n  (** %\\vspace{-.15in}% [[\nt1 = \nfun a b c d : A =>\nmonoid_reflect (Op (Op (Op (Var a) (Var b)) (Var c)) (Var d))\n  (Op (Op (Var a) (Op (Var b) (Var c))) (Var d))\n  (eq_refl (a + (b + (c + (d + e)))))\n     : forall a b c d : A, a + b + c + d = a + (b + c) + d\n      ]]\n\n      The proof term contains only restatements of the equality operands in reified form, followed by a use of reflexivity on the shared canonical form. *)\n\nEnd monoid.\n\n(** Extensions of this basic approach are used in the implementations of the %\\index{tactics!ring}%[ring] and %\\index{tactics!field}%[field] tactics that come packaged with Coq. *)\n\n\n(** * A Smarter Tautology Solver *)\n\n(** Now we are ready to revisit our earlier tautology solver example.  We want to broaden the scope of the tactic to include formulas whose truth is not syntactically apparent.  We will want to allow injection of arbitrary formulas, like we allowed arbitrary monoid expressions in the last example.  Since we are working in a richer theory, it is important to be able to use equalities between different injected formulas.  For instance, we cannot prove [P -> P] by translating the formula into a value like [Imp (Var P) (Var P)], because a Gallina function has no way of comparing the two [P]s for equality.\n\n   To arrive at a nice implementation satisfying these criteria, we introduce the %\\index{tactics!quote}%[quote] tactic and its associated library. *)\n\nRequire Import Quote.\n\n(* begin thide *)\nInductive formula : Set :=\n| Atomic : index -> formula\n| Truth : formula\n| Falsehood : formula\n| And : formula -> formula -> formula\n| Or : formula -> formula -> formula\n| Imp : formula -> formula -> formula.\n(* end thide *)\n\n(** The type %\\index{Gallina terms!index}%[index] comes from the [Quote] library and represents a countable variable type.  The rest of [formula]'s definition should be old hat by now.\n\n   The [quote] tactic will implement injection from [Prop] into [formula] for us, but it is not quite as smart as we might like.  In particular, it wants to treat function types specially, so it gets confused if function types are part of the structure we want to encode syntactically.  To trick [quote] into not noticing our uses of function types to express logical implication, we will need to declare a wrapper definition for implication, as we did in the last chapter. *)\n\nDefinition imp (P1 P2 : Prop) := P1 -> P2.\nInfix \"-->\" := imp (no associativity, at level 95).\n\n(** Now we can define our denotation function. *)\n\nDefinition asgn := varmap Prop.\n\n(* begin thide *)\nFixpoint formulaDenote (atomics : asgn) (f : formula) : Prop :=\n  match f with\n    | Atomic v => varmap_find False v atomics\n    | Truth => True\n    | Falsehood => False\n    | And f1 f2 => formulaDenote atomics f1 /\\ formulaDenote atomics f2\n    | Or f1 f2 => formulaDenote atomics f1 \\/ formulaDenote atomics f2\n    | Imp f1 f2 => formulaDenote atomics f1 --> formulaDenote atomics f2\n  end.\n(* end thide *)\n\n(** The %\\index{Gallina terms!varmap}%[varmap] type family implements maps from [index] values.  In this case, we define an assignment as a map from variables to [Prop]s.  Our interpretation function [formulaDenote] works with an assignment, and we use the [varmap_find] function to consult the assignment in the [Atomic] case.  The first argument to [varmap_find] is a default value, in case the variable is not found. *)\n\nSection my_tauto.\n  Variable atomics : asgn.\n\n  Definition holds (v : index) := varmap_find False v atomics.\n\n  (** We define some shorthand for a particular variable being true, and now we are ready to define some helpful functions based on the [ListSet] module of the standard library, which (unsurprisingly) presents a view of lists as sets. *)\n\n  Require Import ListSet.\n\n  Definition index_eq : forall x y : index, {x = y} + {x <> y}.\n    decide equality.\n  Defined.\n\n  Definition add (s : set index) (v : index) := set_add index_eq v s.\n\n  Definition In_dec : forall v (s : set index), {In v s} + {~ In v s}.\n    Local Open Scope specif_scope.\n\n    intro; refine (fix F (s : set index) : {In v s} + {~ In v s} :=\n      match s with\n        | nil => No\n        | v' :: s' => index_eq v' v || F s'\n      end); crush.\n  Defined.\n\n  (** We define what it means for all members of an index set to represent true propositions, and we prove some lemmas about this notion. *)\n\n  Fixpoint allTrue (s : set index) : Prop :=\n    match s with\n      | nil => True\n      | v :: s' => holds v /\\ allTrue s'\n    end.\n\n  Theorem allTrue_add : forall v s,\n    allTrue s\n    -> holds v\n    -> allTrue (add s v).\n    induction s; crush;\n      match goal with\n        | [ |- context[if ?E then _ else _] ] => destruct E\n      end; crush.\n  Qed.\n\n  Theorem allTrue_In : forall v s,\n    allTrue s\n    -> set_In v s\n    -> varmap_find False v atomics.\n    induction s; crush.\n  Qed.\n\n  Hint Resolve allTrue_add allTrue_In.\n\n  Local Open Scope partial_scope.\n\n  (** Now we can write a function [forward] that implements deconstruction of hypotheses, expanding a compound formula into a set of sets of atomic formulas covering all possible cases introduced with use of [Or].  To handle consideration of multiple cases, the function takes in a continuation argument, which will be called once for each case.\n\n     The [forward] function has a dependent type, in the style of Chapter 6, guaranteeing correctness.  The arguments to [forward] are a goal formula [f], a set [known] of atomic formulas that we may assume are true, a hypothesis formula [hyp], and a success continuation [cont] that we call when we have extended [known] to hold new truths implied by [hyp]. *)\n\n  Definition forward : forall (f : formula) (known : set index) (hyp : formula)\n    (cont : forall known', [allTrue known' -> formulaDenote atomics f]),\n    [allTrue known -> formulaDenote atomics hyp -> formulaDenote atomics f].\n    refine (fix F (f : formula) (known : set index) (hyp : formula)\n      (cont : forall known', [allTrue known' -> formulaDenote atomics f])\n      : [allTrue known -> formulaDenote atomics hyp -> formulaDenote atomics f] :=\n      match hyp with\n        | Atomic v => Reduce (cont (add known v))\n        | Truth => Reduce (cont known)\n        | Falsehood => Yes\n        | And h1 h2 =>\n          Reduce (F (Imp h2 f) known h1 (fun known' =>\n            Reduce (F f known' h2 cont)))\n        | Or h1 h2 => F f known h1 cont && F f known h2 cont\n        | Imp _ _ => Reduce (cont known)\n      end); crush.\n  Defined.\n\n  (** A [backward] function implements analysis of the final goal.  It calls [forward] to handle implications. *)\n\n(* begin thide *)\n  Definition backward : forall (known : set index) (f : formula),\n    [allTrue known -> formulaDenote atomics f].\n    refine (fix F (known : set index) (f : formula)\n      : [allTrue known -> formulaDenote atomics f] :=\n      match f with\n        | Atomic v => Reduce (In_dec v known)\n        | Truth => Yes\n        | Falsehood => No\n        | And f1 f2 => F known f1 && F known f2\n        | Or f1 f2 => F known f1 || F known f2\n        | Imp f1 f2 => forward f2 known f1 (fun known' => F known' f2)\n      end); crush; eauto.\n  Defined.\n(* end thide *)\n\n  (** A simple wrapper around [backward] gives us the usual type of a partial decision procedure. *)\n\n  Definition my_tauto : forall f : formula, [formulaDenote atomics f].\n(* begin thide *)\n    intro; refine (Reduce (backward nil f)); crush.\n  Defined.\n(* end thide *)\nEnd my_tauto.\n\n(** Our final tactic implementation is now fairly straightforward.  First, we [intro] all quantifiers that do not bind [Prop]s.  Then we call the [quote] tactic, which implements the reification for us.  Finally, we are able to construct an exact proof via [partialOut] and the [my_tauto] Gallina function. *)\n\nLtac my_tauto :=\n  repeat match goal with\n           | [ |- forall x : ?P, _ ] =>\n             match type of P with\n               | Prop => fail 1\n               | _ => intro\n             end\n         end;\n  quote formulaDenote;\n  match goal with\n    | [ |- formulaDenote ?m ?f ] => exact (partialOut (my_tauto m f))\n  end.\n(* end thide *)\n\n(** A few examples demonstrate how the tactic works. *)\n\nTheorem mt1 : True.\n  my_tauto.\nQed.\n\nPrint mt1.\n(** %\\vspace{-.15in}% [[\nmt1 = partialOut (my_tauto (Empty_vm Prop) Truth)\n     : True\n    ]]\n\n    We see [my_tauto] applied with an empty [varmap], since every subformula is handled by [formulaDenote]. *)\n\nTheorem mt2 : forall x y : nat, x = y --> x = y.\n  my_tauto.\nQed.\n\n(* begin hide *)\n(* begin thide *)\nDefinition nvm := (Node_vm, Empty_vm, End_idx, Left_idx, Right_idx).\n(* end thide *)\n(* end hide *)\n\nPrint mt2.\n(** %\\vspace{-.15in}% [[\nmt2 = \nfun x y : nat =>\npartialOut\n  (my_tauto (Node_vm (x = y) (Empty_vm Prop) (Empty_vm Prop))\n     (Imp (Atomic End_idx) (Atomic End_idx)))\n     : forall x y : nat, x = y --> x = y\n    ]]\n\n    Crucially, both instances of [x = y] are represented with the same index, [End_idx].  The value of this index only needs to appear once in the [varmap], whose form reveals that [varmap]s are represented as binary trees, where [index] values denote paths from tree roots to leaves. *)\n\nTheorem mt3 : forall x y z,\n  (x < y /\\ y > z) \\/ (y > z /\\ x < S y)\n  --> y > z /\\ (x < y \\/ x < S y).\n  my_tauto.\nQed.\n\nPrint mt3.\n(** %\\vspace{-.15in}% [[\nfun x y z : nat =>\npartialOut\n  (my_tauto\n     (Node_vm (x < S y) (Node_vm (x < y) (Empty_vm Prop) (Empty_vm Prop))\n        (Node_vm (y > z) (Empty_vm Prop) (Empty_vm Prop)))\n     (Imp\n        (Or (And (Atomic (Left_idx End_idx)) (Atomic (Right_idx End_idx)))\n           (And (Atomic (Right_idx End_idx)) (Atomic End_idx)))\n        (And (Atomic (Right_idx End_idx))\n           (Or (Atomic (Left_idx End_idx)) (Atomic End_idx)))))\n     : forall x y z : nat,\n       x < y /\\ y > z \\/ y > z /\\ x < S y --> y > z /\\ (x < y \\/ x < S y)\n    ]]\n\n    Our goal contained three distinct atomic formulas, and we see that a three-element [varmap] is generated.\n\n    It can be interesting to observe differences between the level of repetition in proof terms generated by [my_tauto] and [tauto] for especially trivial theorems. *)\n\nTheorem mt4 : True /\\ True /\\ True /\\ True /\\ True /\\ True /\\ False --> False.\n  my_tauto.\nQed.\n\nPrint mt4.\n(** %\\vspace{-.15in}% [[\nmt4 = \npartialOut\n  (my_tauto (Empty_vm Prop)\n     (Imp\n        (And Truth\n           (And Truth\n              (And Truth (And Truth (And Truth (And Truth Falsehood))))))\n        Falsehood))\n     : True /\\ True /\\ True /\\ True /\\ True /\\ True /\\ False --> False\n    ]]\n    *)\n\nTheorem mt4' : True /\\ True /\\ True /\\ True /\\ True /\\ True /\\ False -> False.\n  tauto.\nQed.\n\n(* begin hide *)\n(* begin thide *)\nDefinition fi := False_ind.\n(* end thide *)\n(* end hide *)\n\nPrint mt4'.\n(** %\\vspace{-.15in}% [[\nmt4' = \nfun H : True /\\ True /\\ True /\\ True /\\ True /\\ True /\\ False =>\nand_ind\n  (fun (_ : True) (H1 : True /\\ True /\\ True /\\ True /\\ True /\\ False) =>\n   and_ind\n     (fun (_ : True) (H3 : True /\\ True /\\ True /\\ True /\\ False) =>\n      and_ind\n        (fun (_ : True) (H5 : True /\\ True /\\ True /\\ False) =>\n         and_ind\n           (fun (_ : True) (H7 : True /\\ True /\\ False) =>\n            and_ind\n              (fun (_ : True) (H9 : True /\\ False) =>\n               and_ind (fun (_ : True) (H11 : False) => False_ind False H11)\n                 H9) H7) H5) H3) H1) H\n     : True /\\ True /\\ True /\\ True /\\ True /\\ True /\\ False -> False\n    ]]\n\nThe traditional [tauto] tactic introduces a quadratic blow-up in the size of the proof term, whereas proofs produced by [my_tauto] always have linear size. *)\n\n(** ** Manual Reification of Terms with Variables *)\n\n(* begin thide *)\n(** The action of the [quote] tactic above may seem like magic.  Somehow it performs equality comparison between subterms of arbitrary types, so that these subterms may be represented with the same reified variable.  While [quote] is implemented in OCaml, we can code the reification process completely in Ltac, as well.  To make our job simpler, we will represent variables as [nat]s, indexing into a simple list of variable values that may be referenced.\n\n   Step one of the process is to crawl over a term, building a duplicate-free list of all values that appear in positions we will encode as variables.  A useful helper function adds an element to a list, preventing duplicates.  Note how we use Ltac pattern matching to implement an equality test on Gallina terms; this is simple syntactic equality, not even the richer definitional equality.  We also represent lists as nested tuples, to allow different list elements to have different Gallina types. *)\n\nLtac inList x xs :=\n  match xs with\n    | tt => false\n    | (x, _) => true\n    | (_, ?xs') => inList x xs'\n  end.\n\nLtac addToList x xs :=\n  let b := inList x xs in\n    match b with\n      | true => xs\n      | false => constr:(x, xs)\n    end.\n\n(** Now we can write our recursive function to calculate the list of variable values we will want to use to represent a term. *)\n\nLtac allVars xs e :=\n  match e with\n    | True => xs\n    | False => xs\n    | ?e1 /\\ ?e2 =>\n      let xs := allVars xs e1 in\n        allVars xs e2\n    | ?e1 \\/ ?e2 =>\n      let xs := allVars xs e1 in\n        allVars xs e2\n    | ?e1 -> ?e2 =>\n      let xs := allVars xs e1 in\n        allVars xs e2\n    | _ => addToList e xs\n  end.\n\n(** We will also need a way to map a value to its position in a list. *)\n\nLtac lookup x xs :=\n  match xs with\n    | (x, _) => O\n    | (_, ?xs') =>\n      let n := lookup x xs' in\n        constr:(S n)\n  end.\n\n(** The next building block is a procedure for reifying a term, given a list of all allowed variable values.  We are free to make this procedure partial, where tactic failure may be triggered upon attempting to reify a term containing subterms not included in the list of variables.  The type of the output term is a copy of [formula] where [index] is replaced by [nat], in the type of the constructor for atomic formulas. *)\n\nInductive formula' : Set :=\n| Atomic' : nat -> formula'\n| Truth' : formula'\n| Falsehood' : formula'\n| And' : formula' -> formula' -> formula'\n| Or' : formula' -> formula' -> formula'\n| Imp' : formula' -> formula' -> formula'.\n\n(** Note that, when we write our own Ltac procedure, we can work directly with the normal [->] operator, rather than needing to introduce a wrapper for it. *)\n\nLtac reifyTerm xs e :=\n  match e with\n    | True => constr:Truth'\n    | False => constr:Falsehood'\n    | ?e1 /\\ ?e2 =>\n      let p1 := reifyTerm xs e1 in\n      let p2 := reifyTerm xs e2 in\n        constr:(And' p1 p2)\n    | ?e1 \\/ ?e2 =>\n      let p1 := reifyTerm xs e1 in\n      let p2 := reifyTerm xs e2 in\n        constr:(Or' p1 p2)\n    | ?e1 -> ?e2 =>\n      let p1 := reifyTerm xs e1 in\n      let p2 := reifyTerm xs e2 in\n        constr:(Imp' p1 p2)\n    | _ =>\n      let n := lookup e xs in\n        constr:(Atomic' n)\n  end.\n\n(** Finally, we bring all the pieces together. *)\n\nLtac reify :=\n  match goal with\n    | [ |- ?G ] => let xs := allVars tt G in\n      let p := reifyTerm xs G in\n        pose p\n  end.\n\n(** A quick test verifies that we are doing reification correctly. *)\n\nTheorem mt3' : forall x y z,\n  (x < y /\\ y > z) \\/ (y > z /\\ x < S y)\n  -> y > z /\\ (x < y \\/ x < S y).\n  do 3 intro; reify.\n\n(** Our simple tactic adds the translated term as a new variable:\n[[\nf := Imp'\n         (Or' (And' (Atomic' 2) (Atomic' 1)) (And' (Atomic' 1) (Atomic' 0)))\n         (And' (Atomic' 1) (Or' (Atomic' 2) (Atomic' 0))) : formula'\n]]\n*)\nAbort.\n\n(** More work would be needed to complete the reflective tactic, as we must connect our new syntax type with the real meanings of formulas, but the details are the same as in our prior implementation with [quote]. *)\n(* end thide *)\n\n\n(** * Building a Reification Tactic that Recurses Under Binders *)\n\n(** All of our examples so far have stayed away from reifying the syntax of terms that use such features as quantifiers and [fun] function abstractions.  Such cases are complicated by the fact that different subterms may be allowed to reference different sets of free variables.  Some cleverness is needed to clear this hurdle, but a few simple patterns will suffice.  Consider this example of a simple dependently typed term language, where a function abstraction body is represented conveniently with a Coq function. *)\n\nInductive type : Type :=\n| Nat : type\n| NatFunc : type -> type.\n\nInductive term : type -> Type :=\n| Const : nat -> term Nat\n| Plus : term Nat -> term Nat -> term Nat\n| Abs : forall t, (nat -> term t) -> term (NatFunc t).\n\nFixpoint typeDenote (t : type) : Type :=\n  match t with\n    | Nat => nat\n    | NatFunc t => nat -> typeDenote t\n  end.\n\nFixpoint termDenote t (e : term t) : typeDenote t :=\n  match e with\n    | Const n => n\n    | Plus e1 e2 => termDenote e1 + termDenote e2\n    | Abs _ e1 => fun x => termDenote (e1 x)\n  end.\n\n(** Here is a %\\%naive%{}% first attempt at a reification tactic. *)\n\n(* begin hide *)\nDefinition red_herring := O.\n(* end hide *)\nLtac refl' e :=\n  match e with\n    | ?E1 + ?E2 =>\n      let r1 := refl' E1 in\n      let r2 := refl' E2 in\n        constr:(Plus r1 r2)\n\n    | fun x : nat => ?E1 =>\n      let r1 := refl' E1 in\n        constr:(Abs (fun x => r1 x))\n\n    | _ => constr:(Const e)\n  end.\n\n(** Recall that a regular Ltac pattern variable [?X] only matches terms that _do not mention new variables introduced within the pattern_.  In our %\\%naive%{}% implementation, the case for matching function abstractions matches the function body in a way that prevents it from mentioning the function argument!  Our code above plays fast and loose with the function body in a way that leads to independent problems, but we could change the code so that it indeed handles function abstractions that ignore their arguments.\n\n   To handle functions in general, we will use the pattern variable form [@?X], which allows [X] to mention newly introduced variables that are declared explicitly.  A use of [@?X] must be followed by a list of the local variables that may be mentioned.  The variable [X] then comes to stand for a Gallina function over the values of those variables.  For instance: *)\n\nReset refl'.\n(* begin hide *)\nReset red_herring.\nDefinition red_herring := O.\n(* end hide *)\nLtac refl' e :=\n  match e with\n    | ?E1 + ?E2 =>\n      let r1 := refl' E1 in\n      let r2 := refl' E2 in\n        constr:(Plus r1 r2)\n\n    | fun x : nat => @?E1 x =>\n      let r1 := refl' E1 in\n        constr:(Abs r1)\n\n    | _ => constr:(Const e)\n  end.\n\n(** Now, in the abstraction case, we bind [E1] as a function from an [x] value to the value of the abstraction body.  Unfortunately, our recursive call there is not destined for success.  It will match the same abstraction pattern and trigger another recursive call, and so on through infinite recursion.  One last refactoring yields a working procedure.  The key idea is to consider every input to [refl'] as _a function over the values of variables introduced during recursion_. *)\n\nReset refl'.\n(* begin hide *)\nReset red_herring.\n(* end hide *)\nLtac refl' e :=\n  match eval simpl in e with\n    | fun x : ?T => @?E1 x + @?E2 x =>\n      let r1 := refl' E1 in\n      let r2 := refl' E2 in\n        constr:(fun x => Plus (r1 x) (r2 x))\n\n    | fun (x : ?T) (y : nat) => @?E1 x y =>\n      let r1 := refl' (fun p : T * nat => E1 (fst p) (snd p)) in\n        constr:(fun u => Abs (fun v => r1 (u, v)))\n\n    | _ => constr:(fun x => Const (e x))\n  end.\n\n(** Note how now even the addition case works in terms of functions, with [@?X] patterns.  The abstraction case introduces a new variable by extending the type used to represent the free variables.  In particular, the argument to [refl'] used type [T] to represent all free variables.  We extend the type to [T * nat] for the type representing free variable values within the abstraction body.  A bit of bookkeeping with pairs and their projections produces an appropriate version of the abstraction body to pass in a recursive call.  To ensure that all this repackaging of terms does not interfere with pattern matching, we add an extra [simpl] reduction on the function argument, in the first line of the body of [refl'].\n\n   Now one more tactic provides an example of how to apply reification.  Let us consider goals that are equalities between terms that can be reified.  We want to change such goals into equalities between appropriate calls to [termDenote]. *)\n\nLtac refl :=\n  match goal with\n    | [ |- ?E1 = ?E2 ] =>\n      let E1' := refl' (fun _ : unit => E1) in\n      let E2' := refl' (fun _ : unit => E2) in\n        change (termDenote (E1' tt) = termDenote (E2' tt));\n          cbv beta iota delta [fst snd]\n  end.\n\nGoal (fun (x y : nat) => x + y + 13) = (fun (_ z : nat) => z).\n  refl.\n(** %\\vspace{-.15in}%[[\n  ============================\n   termDenote\n     (Abs\n        (fun y : nat =>\n         Abs (fun y0 : nat => Plus (Plus (Const y) (Const y0)) (Const 13)))) =\n   termDenote (Abs (fun _ : nat => Abs (fun y0 : nat => Const y0)))\n]]\n*)\n\nAbort.\n\n(** Our encoding here uses Coq functions to represent binding within the terms we reify, which makes it difficult to implement certain functions over reified terms.  An alternative would be to represent variables with numbers.  This can be done by writing a slightly smarter reification function that identifies variable references by detecting when term arguments are just compositions of [fst] and [snd]; from the order of the compositions we may read off the variable number.  We leave the details as an exercise (though not a trivial one!) for the reader. *)\n", "meta": {"author": "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/Reflection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580952177051, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.6809648977739655}}
{"text": "Definition name : Type := nat.\n\nInductive aexp : Type :=\n  | ANum (n : nat)\n  | AVar (x : name)\n  | APlus (a a' : aexp).\n\nCoercion ANum : nat >-> aexp.\nCoercion AVar : name >-> aexp.\nNotation \"a1 +' a2\" := (APlus a1 a2) (at level 50).\n\nDefinition W : name := 1.\nDefinition X : name := 2.\nDefinition Y : name := 3.\nDefinition Z : name := 4.\n\nDefinition state : Type := name -> nat.\nDefinition update (x : name)(n : nat)(s : state)\n : state := fun x' => if Nat.eqb x x' then n else s x'.\nDefinition empty : state := fun _ => 0.\n\nInductive fstep : aexp * state -> nat -> Prop :=\n  | num (n : nat)(s : state) : fstep (ANum n , s) n\n  | var (x : name)(s : state) : fstep (AVar x , s) (s x)\n  | fplusr (n i : nat)(a2 : aexp)(s : state) :\n           fstep (a2 , s) i -> \n           fstep (n +' a2 , s) (n + i).\nInductive step : aexp * state -> aexp * state -> Prop :=\n  | plusl (a1 a2 a1t : aexp)(s : state) :\n          step (a1 , s) (a1t , s) -> \n          step (a1 +' a2 , s) (a1t +' a2 , s)\n  | fplusl (a1 a2 : aexp)(s : state)(i : nat) :\n           fstep (a1 , s) i ->\n           step (a1 +' a2 , s) (i +' a2 , s)\n  | plusr (a2 a2t : aexp)(s : state)(n : nat) :\n          step (a2 , s) (a2t , s) ->\n          step (n +' a2 , s) (n +' a2t , s).\n\nNotation \"w f=> i\" := (fstep w i) (at level 50).\nNotation \"w s=> w'\" := (step w w') (at level 50).\n\nRequire Import Coq.Arith.Plus.\n\nLemma lem1 : (ANum 3 , empty) f=> 100 -> False.\nintros.\ninversion H. Qed.\n\nLemma lem2 : forall n s1 s2 i, (ANum n , s1) f=> i -> (ANum n , s2) f=> i.\nintros.\ninversion H. \napply num. Qed.\n\nFixpoint aeval (a : aexp)(s : state) : nat :=\n  match a with\n  | ANum n => n\n  | AVar x => s x\n  | APlus a1 a2 => aeval a1 s + aeval a2 s\n  end.\n\nInductive bstep : aexp * state -> nat -> Prop :=\n  | bnum (n : nat)(s : state) : bstep (ANum n , s) n\n  | bvar (x : name)(s : state) : bstep (AVar x , s) (s x)\n  | bsum (a1 a2 : aexp)(s : state)(n1 n2 : nat) :\n      bstep (a1 , s) n1 -> bstep (a2 , s) n2 -> bstep (a1 +' a2 , s) (n1 + n2).\n\nNotation \"w ˇ i\" := (bstep w i) (at level 50).\n\nLemma todenot : forall a s n, (a , s) ˇ n -> aeval a s = n.\nintros.  induction a. simpl. inversion H. reflexivity.\nsimpl. inversion H. reflexivity. inversion H. rewrite -> (IHa1 a1 H4).\n\nLemma fromdenot : forall a s n, aeval a s = n -> (a , s) ˇ n.\nAdmitted.\n \n\n\n", "meta": {"author": "marko1777", "repo": "FormSzem", "sha": "7162911df76ca0fad2fb1b535affba2b2ed19cd7", "save_path": "github-repos/coq/marko1777-FormSzem", "path": "github-repos/coq/marko1777-FormSzem/FormSzem-7162911df76ca0fad2fb1b535affba2b2ed19cd7/08/08.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.6809648950896848}}
{"text": "Require Import Nat Util Get.\n\nNotation \"'list_max' L\" := (fold_left max L 0) (at level 50).\n\nLemma list_max_swap L x\n: max (list_max L) x = fold_left max L x.\nProof.\n  general induction L; simpl; eauto.\n  setoid_rewrite <- IHL; eauto.\n  setoid_rewrite Max.max_comm at 4.\n  rewrite Max.max_assoc; eauto.\nQed.\n\nLemma list_max_get L n x\n: get L n x\n  -> x <= list_max L.\nProof.\n  intros. general induction L; eauto; invt get; simpl.\n  - rewrite <- list_max_swap. eapply Max.le_max_r.\n  - rewrite <- list_max_swap. rewrite <- Max.le_max_l; eauto.\nQed.\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Infra/ListMax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6808906362185235}}
{"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom VFA Require Import Perm.\nHint Constructors Permutation : core.\nFrom Coq Require Export Lists.List.\n\nFixpoint select (x: nat) (l: list nat) : (nat * list nat) :=\n  match l with\n  | []      => (x, [])\n  | h :: t  =>\n    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\nFail Fixpoint selsort (l : list nat) : list nat :=\n  match l with\n  | []      => []\n  | x :: r  => let (y, r') := select x r in y :: selsort r'\n  end.\n\nFixpoint selsort (l : list nat) (n : nat) : list nat :=\n  match l, n with\n  | _     , O     => [] (* ran out of fuel *)\n  | []    , _     => []\n  | x :: r, S n'  => let (y, r') := select x r in y :: selsort r' n'\nend.\n\nDefinition selection_sort (l : list nat) : list nat := selsort l (length l).\n\n\nExample sort_pi :\n  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.\n  unfold selection_sort.\n  simpl. reflexivity.\nQed.\n\n\n\nInductive sorted: list nat -> Prop :=\n | sorted_nil: sorted []\n | sorted_1: forall i, sorted [i]\n | sorted_cons: forall i j l, i <= j -> sorted (j :: l) -> sorted (i :: j :: l).\nHint Constructors sorted : core.\n\nDefinition is_a_sorting_algorithm (f: list nat -> list nat) := forall al,\n    Permutation al (f al) /\\ sorted (f al).\n\n\nExample pairs_example : forall (a c x : nat) (b d l : list nat),\n    (a, b) = (let (c, d) := select x l in (c, d)) ->\n    (a, b) = select x l.\nProof.\n  intros. destruct (select x l) eqn:E. auto.\nQed.\n\nLtac gen x := generalize dependent x.\n\nLemma select_perm: forall x l y r,\n    (y, r) = select x l -> Permutation (x :: l) (y :: r).\nProof.\n  intros x l. gen x.\n  induction l; simpl; intros x y r H.\n  - injection H as Hl Hr; subst.\n    constructor.\n    constructor.\n  - bdestruct (a >=? x).\n    + destruct (select x l) eqn:E.\n      injection H as Hl Hr; subst.\n      change (x :: a :: l) with ([x] ++ [a] ++ l).\n      change (n :: a :: l0) with ([n] ++ [a] ++ l0).\n      apply perm_trans with ([a] ++ [x] ++ l).\n      * apply Permutation_app_swap_app.\n      * apply perm_trans with ([a] ++ [n] ++ l0).\n        ** simpl. \n           apply perm_skip.\n           apply IHl.\n           symmetry.\n           assumption.\n        ** apply Permutation_app_swap_app.\n    + destruct (select a l) eqn:E.\n      injection H as Hl Hr; subst.\n      change (n :: x :: l0) with ([n] ++ [x] ++ l0).\n      apply perm_trans with ([x] ++ [n] ++ l0).\n      * simpl.\n        apply perm_skip.\n        apply IHl.\n        symmetry.\n        assumption.\n      * apply Permutation_app_swap_app.\nQed.\n\nLemma selsort_perm: forall n l,\n    length l = n -> Permutation l (selsort l n).\nProof.\n  intros n.\n  induction n; intros l Hlen; simpl in Hlen.\n  - simpl. destruct l. \n      constructor. \n      simpl in Hlen. discriminate.\n  - unfold selsort.\n    fold selsort.\n    destruct l.\n    + constructor.\n    + destruct (select n0 l) eqn:E.\n      symmetry in E.\n      apply select_perm in E.\n      apply perm_trans with (n1 :: l0).\n      * assumption.\n      * apply perm_skip.\n        apply IHn.\n        simpl in Hlen.\n        Search Permutation.\n        apply Permutation_length in E.\n        simpl in E.\n        lia.\nQed.\n\nLemma selection_sort_perm: forall l,\n    Permutation l (selection_sort l).\nProof.\n  intro l.\n  unfold selection_sort.\n  apply selsort_perm.\n  reflexivity.\nQed.\n\nLemma select_rest_length : forall x l y r,\n    select x l = (y, r) -> length l = length r.\nProof.\n  intros.\n  symmetry in H.\n  apply select_perm in H.\n  apply Permutation_length in H.\n  simpl in H.\n  lia.\nQed.\n\n\nLemma select_fst_leq: forall al bl x y,\n    select x al = (y, bl) ->  y <= x.\nProof.\n  intro al.\n  induction al; simpl; intros bl x y Hsel.\n  - injection Hsel as Exy.\n    lia.\n  - bdestruct (a >=? x).\n    + destruct (select x al) eqn:E.\n      injection Hsel as Hs1 Hs2.\n      subst.\n      apply IHal with l.\n      assumption.\n    + destruct (select a al) eqn:E.\n      injection Hsel as Hs1 Hs2.\n      subst.\n      assert (G: y <= a). {\n        apply IHal with l.\n        assumption.\n      }\n      lia.\nQed.\n\nDefinition le_all x xs := Forall (fun y => x <= y) xs.\n\nInfix \"<=*\" := le_all (at level 70, no associativity).\n\nLemma select_smallest: forall al bl x y,\n    select x al = (y, bl) ->\n    y <=* bl.\nProof.\n  intro al.\n  induction al; simpl; intros bl x y H.\n  - injection H as Hl Hr.\n    subst.\n    unfold le_all.\n    Search Forall.\n    apply Forall_nil.\n  - bdestruct (a >=? x).\n    + destruct (select x al) eqn:E.\n      injection H as Hl Hr.\n      subst.\n      assert (G1: y <=* l). {\n        apply IHal with x.\n        assumption.\n      }\n      assert (G2: y <= a). {\n        apply select_fst_leq in E.\n        lia.\n      }\n      apply Forall_cons.\n      apply G2.\n      apply G1.\n    + destruct (select a al) eqn:E.\n      injection H as Hl Hr.\n      subst.\n      assert (G1: y <=* l). {\n        apply IHal with a.\n        assumption.\n      }\n      assert (G2: y <= x). {\n        apply select_fst_leq in E.\n        lia.\n      }\n      apply Forall_cons.\n      apply G2.\n      apply G1.\nQed.\n\nLemma select_in : forall al bl x y,\n    select x al = (y, bl) ->\n    In y (x :: al).\nProof.\n  intro al.\n  induction al; simpl; intros bl x y H.\n  - injection H as Hl Hr. left. assumption.\n  - bdestruct (a >=? x).\n    + destruct (select x al) eqn:E.\n      injection H as Hl Hr.\n      subst.\n      apply IHal in E.\n      destruct E.\n      * left. assumption.\n      * right. right. assumption.\n    + destruct (select a al) eqn:E.\n      injection H as Hl Hr.\n      subst.\n      apply IHal in E.\n      destruct E.\n      * right. left. assumption.\n      * right. right. assumption.\nQed.\n\n\nLemma tst: forall l x y, x <=* l -> In y l -> x <= y.\nProof.\n  intros l x y H1 H2.\n  induction H1.\n  - exfalso. apply H2.\n  - destruct H2.\n    + lia.\n    + apply IHForall. apply H0.\nQed.\n\nLemma cons_of_small_maintains_sort: forall bl y n,\n    n = length bl ->\n    y <=* bl ->\n    sorted (selsort bl n) ->\n    sorted (y :: selsort bl n).\nProof.\n  intros bl y n. gen bl. gen y.\n  induction n; simpl; intros y bl Hn Hle Hsort.\n  - destruct bl.\n    + constructor.\n    + simpl in Hn. discriminate Hn.\n  - destruct bl as [| bh bt ].\n    + simpl in Hn. discriminate Hn.\n    + destruct (select bh bt) eqn:E.\n      constructor.\n      * apply select_in in E.\n        apply tst with  (bh :: bt).\n          assumption.\n          assumption.\n      * apply Hsort.\nQed.\n\nLemma selsort_sorted : forall n al,\n    length al = n -> sorted (selsort al n).\nProof.\n  intro n.\n  induction n; simpl in *; intros al Hlen.\n  - destruct al.\n    + constructor.\n    + discriminate Hlen.\n  - destruct al.\n    + discriminate Hlen.\n    + destruct (select n0 al) eqn:E.\n      Print sorted.\n      apply cons_of_small_maintains_sort.\n      * simpl in Hlen. apply select_rest_length in E. lia.\n      * apply select_smallest in E. assumption.\n      * apply IHn. apply select_rest_length in E. simpl in Hlen. lia.\nQed.\n\nLemma selection_sort_sorted : forall al,\n    sorted (selection_sort al).\nProof.\n  unfold selection_sort.\n  intros al.\n  apply selsort_sorted.\n  reflexivity.\nQed.\n\nTheorem selection_sort_is_correct :\n  is_a_sorting_algorithm selection_sort.\nProof.\n  intro a.\n  split.\n  - apply selection_sort_perm.\n  - apply selection_sort_sorted.\nQed.\n\n\n\nFrom VFA Require Import Multiset.\nFrom Coq Require Import FunctionalExtensionality.\n\nModule MultiserProof.\n\nDefinition is_a_sorting_algorithm' (f: list nat -> list nat) := forall al,\n    contents al = contents (f al) /\\ sorted (f al).\n\nLemma contents_cons: forall x l r, \n  contents l = contents r -> contents (x :: l) = contents (x :: r).\nProof.\n  intros x l.\n  induction l; intros r H.\n  - simpl in H.\n    simpl.\n    rewrite <- H.\n    reflexivity.\n  - simpl in *.\n    rewrite H.\n    reflexivity.\nQed.\n\nLemma select_rest_multiset : forall x l y r,\n    select x l = (y, r) -> contents (x :: l) = contents (y :: r).\nProof.\n  intros x l. gen x.\n  induction l; intros x y r H.\n  - extensionality o.\n    simpl in H.\n    injection H as Hl Hr. subst.\n    reflexivity.\n  - extensionality o.\n    simpl in H.\n    bdestruct (a >=? x).\n    + destruct (select x l) eqn:E.\n      injection H as Hl Hr. subst.\n      simpl.\n      rewrite (union_swap (singleton x) (singleton a)).\n      rewrite (union_swap (singleton y) (singleton a)).\n      simpl in IHl.\n      rewrite (IHl _ y l0).\n        reflexivity.\n        assumption.\n    + destruct (select a l) eqn:E.\n      injection H as Hl Hr. subst.\n      simpl. simpl in IHl.\n      rewrite (union_swap (singleton y) (singleton x)).\n      rewrite <- (IHl a y l0).\n        reflexivity.\n        assumption.\nQed.\n\nLemma same_contents_same_len: forall l1 l2, \n  contents l1 = contents l2 -> length l1 = length l2.\nProof.\n  intro l1.\n  induction l1; intros l2 H.\n  - simpl in H.\n    destruct l2.\n    + reflexivity.\n    + exfalso.\n      apply equal_f with v in H.\n      simpl in H.\n      unfold union, singleton, empty in H.\n      rewrite Nat.eqb_refl in H.\n      discriminate H.\n  - assert (G: S (contents l1 a) = contents l2 a). {\n      apply equal_f with a in H.\n      simpl in H.\n      unfold union, singleton, empty in H.\n      rewrite Nat.eqb_refl in H.\n      simpl in H.\n      assumption.\n    }\n    destruct (contents_cons_inv _ _ _ G) as [l1' [l2' [Hl Hcont]]].\n    rewrite Hl.\n    rewrite app_length. simpl.\n    rewrite Nat.add_comm. simpl.\n    rewrite <- app_length.\n    rewrite <- (IHl1 (l2' ++ l1')).\n    + reflexivity.\n    + extensionality o.\n      rewrite Hl in H.\n      rewrite contents_distr in *.\n      simpl in H.\n      apply equal_f with o in H.\n      unfold union, singleton, empty in *.\n      bdestruct (o =? a).\n      * lia.\n      * lia.\nQed.\n\nLemma selsort_multiset: forall n l,\n    length l = n -> contents l = contents (selsort l n).\nProof.\n  intros n.\n  induction n; intros l Hlen; simpl in Hlen.\n  - extensionality o.\n    simpl. destruct l. \n      constructor. \n      simpl in Hlen. discriminate.\n  - unfold selsort.\n    fold selsort.\n    destruct l.\n    + constructor.\n    + destruct (select v l) eqn:E.\n      apply select_rest_multiset in E.\n      extensionality o.\n      assert (E' := E).\n      eapply equal_f in E.\n      rewrite E.\n      simpl.\n      rewrite <- IHn.\n      * reflexivity.\n      * simpl in Hlen.\n        assert (G: length l0 = length l). {\n          apply same_contents_same_len in E'.\n          simpl in E'.\n          injection E' as E'.\n          rewrite E'.\n          reflexivity.\n        }\n        rewrite <- G in Hlen.\n        injection Hlen as Hlen.\n        apply Hlen.\nQed.\n\nLemma selection_sort_multiset : forall al,\n    contents al = contents (selection_sort al).\nProof.\n  intro al.\n  apply selsort_multiset.\n  reflexivity.\nQed.\n\nTheorem selection_sort_is_correct' :\n  is_a_sorting_algorithm' selection_sort.\nProof.\n  intro a.\n  split.\n  - apply selection_sort_multiset.\n  - apply selection_sort_sorted.\nQed.\n\nEnd MultiserProof.\n\n\n\nRequire Import Recdef.\n\nFunction selsort' l {measure length l} :=\n  match l with\n  | []      => []\n  | x :: r  => let (y, r') := select x r\n               in y :: selsort' r'\nend.\n\nProof.\n  intros.\n  assert (Hperm: Permutation (x :: r) (y :: r')).\n  { apply select_perm. auto. }\n  apply Permutation_length in Hperm.\n  inv Hperm. simpl. lia.\nDefined.\n\nPrint selsort'.\nPrint selsort'_terminate.\nCheck selsort'_equation.\n\n\nLemma selsort'_perm : forall n l,\n    length l = n -> Permutation l (selsort' l).\nProof.\n(* TODO *)\nAdmitted.\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/Selection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6808906318619792}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import PeanoNat.\n(* Import Nat. *)\nRequire Import Ring.\n(* Require Import Arith. *)\n(* Import ArithRing. *)\n(* Require Import NArithRing. *)\n(* Require Import NArith. *)\nRequire Import FunctionalExtensionality.\nRequire Import BinInt.\nRequire Import ZArith.\nRequire Import ZArithRing.\nImport Z.\nOpen Scope Z_scope.\n\nSet Implicit Arguments.\n\nDefinition Vector (A : Type) := list A.\n\n\n(* Vector functions *)\n\nFixpoint alignWith (A : Type) (f : A -> A -> A) (v1 v2 : Vector A) :=\n  match v1, v2 with\n  | [], _ => v2\n  | _, [] => v1\n  | a1 :: v12, a2 :: v22 => f a1 a2 :: alignWith f v12 v22\n  end.\n\n\n(* Laws about Vector functions *)\n\nLemma map_alignWith :\n  forall A (f : A -> A -> A) (g : A -> A),\n      (forall (x y : A), g (f x y) = f (g x) (g y)) ->\n      forall (v1 v2 : Vector A), map g (alignWith f v1 v2) = alignWith f (map g v1) (map g v2).\nProof.\n  induction v1; destruct v2; simpl alignWith; simpl map; try reflexivity; rewrite H; rewrite IHv1; reflexivity.\nQed.\n\n\n(* Addition *)\n\nDefinition zero : Vector Z := [].\n\nDefinition plus (v1 v2 : Vector Z) : Vector Z :=\n  alignWith add v1 v2.\n\nHint Unfold plus.\nLtac simpl_plus := unfold plus; simpl alignWith.\n\n(* Auxiliary lemmas *)\n\nLemma map_plus :\n  forall (n : Z) (v1 v2 : Vector Z),\n    map (mul n) (plus v1 v2) = plus (map (mul n) v1) (map (mul n) v2).\nProof.\n  intros n v1 v2; unfold plus.\n  rewrite map_alignWith; try reflexivity.\n  apply mul_add_distr_l.\nQed.\n\nLemma plus_cons :\n  forall (n1 n2 : Z) (v1 v2 : Vector Z),\n    n1 + n2 :: plus v1 v2 = plus (n1 :: v1) (n2 :: v2).\nProof.\n  reflexivity.\nQed.\n\n\n(* Properties of plus *)\n\nLemma plus_comm :\n  forall (v1 v2 : Vector Z),\n    plus v1 v2 = plus v2 v1.\nProof.\n  induction v1; destruct v2;\n    simpl_plus; try reflexivity; rewrite add_comm;\n      rewrite <- IHv1; reflexivity.\nQed.\n\nLemma plus_0_l :\n  forall (v : Vector Z),\n    plus zero v = v.\nProof.\n  unfold zero, plus.\n  simpl alignWith.\n  reflexivity.\nQed.\n\nLemma plus_0_r :\n  forall (v : Vector Z),\n    plus v zero = v.\nProof.\n  intro v.\n  rewrite plus_comm.\n  apply plus_0_l.\nQed.\n\nLemma plus_assoc :\n  forall (v1 v2 v3 : Vector Z),\n    plus v1 (plus v2 v3) = plus (plus v1 v2) v3.\nProof.\n  induction v1; destruct v2, v3; try reflexivity;\n    simpl_plus; simpl alignWith; rewrite IHv1, add_assoc; reflexivity.\nQed.\n\n\n(* Derived lemmas about plus *)\n\nLemma plus_swap_1 :\n  forall (v1 v2 v3 : Vector Z),\n    plus v1 (plus v2 v3) = plus v2 (plus v1 v3).\nProof.\n  intros v1 v2 v3.\n  rewrite plus_assoc, plus_comm with (v1 := v1), <- plus_assoc.\n  reflexivity.\nQed.\n\nLemma plus_swap_2 :\n  forall (v1 v2 v3 v4 : Vector Z),\n    plus (plus v1 v2) (plus v3 v4) = plus (plus v1 v3) (plus v2 v4).\nProof.\n  intros v1 v2 v3 v4.\n  rewrite plus_assoc, <- plus_assoc with (v1 := v1), plus_comm with (v1 := v2), plus_assoc, plus_assoc.\n  reflexivity.\nQed.\n\n\nDefinition one : Vector Z := [1].\n\nFixpoint mult (v1 v2 : Vector Z) : Vector Z :=\n  match v1, v2 with\n  | [], _ => []\n  | _, [] => []\n  | n :: v12, _ => plus (map (mul n) v2) (0 :: mult v12 v2)\n  end.\n\n\n(* Auxiliary lemmas about mult *)\n\nLemma map_mult :\n  forall (n : Z) (v1 v2 : Vector Z),\n    map (mul n) (mult v1 v2) = mult (map (mul n) v1) v2.\nProof.\n  intros v.\n  induction v1; intros v2; simpl mult; try reflexivity.\n  destruct v2; try reflexivity.\n  rewrite map_plus, map_map, <- IHv1.\n  simpl map.\n  rewrite mul_0_r.\n  do 2 f_equal.\n  - ring.\n  - f_equal.\n    extensionality x.\n    ring.\nQed.\n\n\nLemma map_add_0 :\n  forall (v : Vector Z), map (fun n => n + 0) v = v.\nProof.\n  induction v; simpl; try reflexivity.\n  rewrite add_0_r, IHv.\n  reflexivity.\nQed.\n\n\n(* Properties of mult *)\n\nLemma mult_comm :\n  forall (v1 v2 : Vector Z),\n    mult v1 v2 = mult v2 v1.\nProof.\n  induction v1; induction v2; simpl; try reflexivity.\n  rewrite <- IHv2, IHv1.\n  do 2 rewrite <- plus_cons.\n  f_equal.\n  - ring.\n  - simpl.\n    destruct v1, v2; only 1-3: simpl; try reflexivity.\n    + rewrite plus_0_r, plus_0_l.\n      simpl_plus.\n      rewrite plus_0_r, add_0_r.\n      reflexivity.\n    + rewrite plus_0_l, plus_0_r.\n      simpl_plus.\n      rewrite plus_0_r, add_0_r.\n      reflexivity.\n    + rewrite plus_swap_1. rewrite <- IHv1.\n      reflexivity.\nQed.\n\nLemma mult_0_l :\n  forall (v : Vector Z),\n    mult zero v = zero.\nProof.\n  reflexivity.\nQed.\n\nLemma mult_0_r :\n  forall (v : Vector Z),\n    mult v zero =  zero.\nProof.\n  intros v1.\n  rewrite mult_comm, mult_0_l.\n  reflexivity.\nQed.\n\nLemma alignWith_nil_r :\n  forall A (f : A -> A -> A) v, alignWith f v [] = v.\nProof.\n  intros A f v.\n  induction v; reflexivity.\nQed.\n\nLemma mult_1_l :\n  forall (v : Vector Z),\n    mult one v = v.\nProof.\n  intros v.\n  unfold one.\n  destruct v; simpl; try reflexivity.\n  simpl_plus.\n  rewrite alignWith_nil_r.\n  rewrite map_ext with (g := id); try (intros; unfold id; ring).\n  rewrite map_id.\n  destruct z; try reflexivity.\nQed.\n\nLemma mult_1_r :\n  forall (v : Vector Z),\n    mult v one = v.\nProof.\n  intros v.\n  rewrite mult_comm.\n  apply mult_1_l.\nQed.\n\n\n(* Auxiliary lemma for proving associativity and distributivity *)\n\nLemma mult_plus_distr_r :\n  forall (v1 v2 v3 : Vector Z),\n    mult v1 (plus v2 v3) = plus (mult v1 v2) (mult v1 v3).\nProof.\n  induction v1; intros v2 v3; simpl mult; try reflexivity.\n  destruct v2.\n  - rewrite plus_0_l.\n    destruct v3; try reflexivity.\n  - destruct v3.\n    + rewrite plus_0_r.\n      reflexivity.\n    + unfold plus.\n      simpl.\n      ring_simplify (a * (z + z0) + 0) (a * z + 0 + (a * z0 + 0)).\n      rewrite map_plus.\n      do 2 rewrite plus_cons.\n      rewrite IHv1.\n      rewrite plus_swap_2.\n      reflexivity.\nQed.\n\nLemma mult_plus_distr_l :\n  forall (v1 v2 v3 : Vector Z),\n    mult (plus v1 v2) v3 = plus (mult v1 v3) (mult v2 v3).\nProof.\n  intros v1 v2 v3.\n  rewrite mult_comm, mult_plus_distr_r, mult_comm, (mult_comm v3).\n  reflexivity.\nQed.\n\nLemma mult_assoc :\n  forall (v1 v2 v3 : Vector Z),\n    mult v1 (mult v2 v3) = mult (mult v1 v2) v3.\nProof.\n  induction v1; intros v2 v3; simpl mult; try reflexivity.\n  rewrite IHv1.\n  destruct v2.\n  - rewrite mult_0_l.\n    reflexivity.\n  - destruct v3; simpl; try reflexivity.\n    rewrite <- plus_cons, <- plus_cons.\n    f_equal.\n    + ring.\n    + rewrite mult_plus_distr_l, <- IHv1, plus_assoc.\n      unfold plus.\n      rewrite map_alignWith.\n      * rewrite map_map, map_mult.\n        do 3 f_equal.\n        extensionality x.\n        ring.\n      * apply mul_add_distr_l.\nQed.\n", "meta": {"author": "ichistmeinname", "repo": "HenningIndexVerification", "sha": "c9e8e0509f06f7d1d94225b02dbb0f870e9e6009", "save_path": "github-repos/coq/ichistmeinname-HenningIndexVerification", "path": "github-repos/coq/ichistmeinname-HenningIndexVerification/HenningIndexVerification-c9e8e0509f06f7d1d94225b02dbb0f870e9e6009/Vector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.6808906194110552}}
{"text": "(* -*- mode: coq; mode: visual-line -*- *)\n\nRequire Import HoTT.Basics.\nRequire Import Types.Prod Types.Sigma Types.Forall Types.Arrow Types.Paths.\n\nLocal Open Scope path_scope.\n\n(** * Equivalences *)\n\nSection AssumeFunext.\n  Context `{Funext}.\n\n  (** We begin by showing that, assuming function extensionality, [IsEquiv f] is an hprop. *)\n  Global Instance hprop_isequiv {A B} `(f : A -> B)\n  : IsHProp (IsEquiv f).\n  Proof.\n    apply hprop_inhabited_contr; intros feq.\n    (* We will show that if [IsEquiv] is inhabited, then it is contractible, because it is equivalent to a sigma of a pointed path-space over a pointed path-space, both of which are contractible. *)\n    refine (contr_equiv' { g : B -> A & g = f^-1 } _).\n    equiv_via ({ g:B->A & { r:g=f^-1 & { s:g=f^-1 & r=s }}}); apply equiv_inverse.\n    1:exact (equiv_functor_sigma' 1 (fun _ => equiv_sigma_contr _ )).\n    (* First we apply [issig], peel off the first component, and convert to pointwise paths. *)\n    refine (_ oE (issig_isequiv f)^-1).\n    refine (equiv_functor_sigma' (equiv_idmap (B -> A)) _); intros g; simpl.\n    equiv_via ({ r : g == f^-1 & { s : g == f^-1 & r == s }}).\n    (* Now the idea is that if [f] is an equivalence, then [g f == 1] and [f g == 1] are both equivalent to [g == f^-1]. *)\n    { refine (equiv_functor_sigma'\n                (equiv_functor_forall idmap (fun b p => (ap f)^-1 (p @ (eisretr f b)^)))\n                (fun r => equiv_functor_sigma'\n                            (equiv_functor_forall f (fun a p => p @ (eissect f a)))^-1 _));\n      intros s; simpl.\n      (* What remains is to show that under these equivalences, the remaining datum [eisadj] reduces simply to [r == s].  Pleasingly, Coq can compute for us exactly what this means. *)\n      apply equiv_inverse;\n        refine (equiv_functor_forall' (Build_Equiv _ _ f _) _);\n        intros a; simpl; unfold functor_forall.\n      rewrite transport_paths_FlFr.\n      (* At this point it's just naturality wrangling, potentially automatable.  It's a little unusual because what we have to prove is not just the existence of some path, but that one path-type is equivalent to another one, but we can mostly still use [rewrite]. *)\n      Open Scope long_path_scope.\n      rewrite ap_pp, !concat_p_pp, eisadj, <- !ap_V, <- !ap_compose.\n      rewrite (concat_pA1_p (eissect f) (eissect f a)^).\n      rewrite (concat_A1p s (eissect f a)^).\n      rewrite (concat_pp_A1 (fun x => (eissect f x)^) (eissect f a)).\n      (* Here instead of [whiskerR] we have to be a bit fancier. *)\n      refine (_ oE (equiv_ap (equiv_concat_r (eissect f a)^ _) _ _)^-1).\n      rewrite concat_pV_p.\n      refine (_ oE equiv_ap (ap f) _ _).\n      (* Now we can get rid of the [<~>] and reduce the question to constructing some path. *)\n      apply equiv_concat_l.\n      rewrite !ap_pp, !ap_V, <- !eisadj, <- ap_compose.\n      rewrite_moveL_Vp_p.\n      symmetry; exact (concat_A1p (eisretr f) (r (f a))).\n      Close Scope long_path_scope. }\n    (* The leftover goal is just nested applications of funext. *)\n    { refine (equiv_functor_sigma' (equiv_path_arrow g f^-1)\n                                   (fun r => equiv_functor_sigma' (equiv_path_arrow g f^-1) _));\n      intros s; simpl.\n      refine (_ oE equiv_path_forall r s).\n      exact (equiv_ap (path_forall g f^-1) r s). }\n  Qed.\n\n  (** Thus, paths of equivalences are equivalent to paths of functions. *)\n  Lemma equiv_path_equiv {A B : Type} (e1 e2 : A <~> B)\n  : (e1 = e2 :> (A -> B)) <~> (e1 = e2 :> (A <~> B)).\n  Proof.\n    equiv_via ((issig_equiv A B) ^-1 e1 = (issig_equiv A B) ^-1 e2).\n    2: symmetry; apply equiv_ap; refine _.\n    exact (equiv_path_sigma_hprop ((issig_equiv A B)^-1 e1) ((issig_equiv A B)^-1 e2)).\n  Defined.\n\n  Definition path_equiv {A B : Type} {e1 e2 : A <~> B}\n  : (e1 = e2 :> (A -> B)) -> (e1 = e2 :> (A <~> B))\n    := equiv_path_equiv e1 e2.\n\n  Global Instance isequiv_path_equiv {A B : Type} {e1 e2 : A <~> B}\n  : IsEquiv (@path_equiv _ _ e1 e2)\n    (* Coq can find this instance by itself, but it's slow. *)\n    := equiv_isequiv (equiv_path_equiv e1 e2).\n\n  (** This implies that types of equivalences inherit truncation.  Note that we only state the theorem for [n.+1]-truncatedness, since it is not true for contractibility: if [B] is contractible but [A] is not, then [A <~> B] is not contractible because it is not inhabited.\n\n   Don't confuse this lemma with [trunc_equiv], which says that if [A] is truncated and [A] is equivalent to [B], then [B] is truncated.  It would be nice to find a better pair of names for them. *)\n  Global Instance istrunc_equiv {n : trunc_index} {A B : Type} `{IsTrunc n.+1 B}\n  : IsTrunc n.+1 (A <~> B).\n  Proof.\n    simpl. intros e1 e2.\n    apply (trunc_equiv _ (equiv_path_equiv e1 e2)).\n  Defined.\n\n  (** In the contractible case, we have to assume that *both* types are contractible to get a contractible type of equivalences. *)\n  Global Instance contr_equiv_contr_contr {A B : Type} `{Contr A} `{Contr B}\n  : Contr (A <~> B).\n  Proof.\n    exists equiv_contr_contr.\n    intros e. apply path_equiv, path_forall. intros ?; apply contr.\n  Defined.\n\n  (** The type of *automorphisms* of an hprop is always contractible *)\n  Global Instance contr_aut_hprop A `{IsHProp A}\n  : Contr (A <~> A).\n  Proof.\n    exists 1%equiv.\n    intros e; apply path_equiv, path_forall. intros ?; apply path_ishprop.\n  Defined.\n\n  (** Equivalences are functorial under equivalences. *)\n  Definition functor_equiv {A B C D} (h : A <~> C) (k : B <~> D)\n  : (A <~> B) -> (C <~> D)\n  := fun f => ((k oE f) oE h^-1).\n\n  Global Instance isequiv_functor_equiv {A B C D} (h : A <~> C) (k : B <~> D)\n  : IsEquiv (functor_equiv h k).\n  Proof.\n    refine (isequiv_adjointify _\n              (functor_equiv (equiv_inverse h) (equiv_inverse k)) _ _).\n    - intros f; apply path_equiv, path_arrow; intros x; simpl.\n      exact (eisretr k _ @ ap f (eisretr h x)).\n    - intros g; apply path_equiv, path_arrow; intros x; simpl.\n      exact (eissect k _ @ ap g (eissect h x)).\n  Defined.\n\n  Definition equiv_functor_equiv {A B C D} (h : A <~> C) (k : B <~> D)\n  : (A <~> B) <~> (C <~> D)\n  := Build_Equiv _ _ (functor_equiv h k) _.\n\n  (** Reversing equivalences is an equivalence *)\n  Global Instance isequiv_equiv_inverse {A B}\n  : IsEquiv (@equiv_inverse A B).\n  Proof.\n    refine (isequiv_adjointify _ equiv_inverse _ _);\n      intros e; apply path_equiv; reflexivity.\n  Defined.\n\n  Definition equiv_equiv_inverse A B\n  : (A <~> B) <~> (B <~> A)\n    := Build_Equiv _ _ (@equiv_inverse A B) _.\n\nEnd AssumeFunext.\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/Types/Equiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6808906156732194}}
{"text": "Require Import Braun.common.util Braun.common.le_util.\nRequire Import Braun.common.log Braun.common.big_oh Braun.common.pow.\nRequire Import Braun.monad.monad Braun.arith.plus Braun.fib.fib.\nRequire Import Program Div2 Omega Even.\n\n\nFixpoint fib_rec_time (n:nat) :=\n  match n with\n    | O => 1\n    | S n' =>\n      match n' with\n        | O => 1\n        | S n'' => (fib_rec_time n'') + (fib_rec_time n') + 1\n      end\n  end.\n\nDefinition fib_rec_result (n:nat) (res:nat) (c:nat) :=\n    Fib n res /\\\n    c = fib_rec_time n.\n\nLoad \"fib_rec_gen.v\".\n\nNext Obligation.\nProof.\n  split;eauto.\nQed.\n\nNext Obligation.\nProof.\n  split;eauto.\nQed.\n\nNext Obligation.\nProof.\n  clear am H3 am0 H2.\n  rename H1 into FR_A.\n  rename H0 into FR_B.\n\n  destruct FR_A as [FIBA FIBTIMEA].\n  destruct FR_B as [FIBB FIBTIMEB].\n  unfold fib_rec_result in *.\n  split.\n  eauto.\n  rename n'' into n.\n  destruct n as [|n]; subst; simpl; omega.\nQed.\n\nProgram Lemma fib_big_oh_fib:\n  big_oh fib fib_rec_time.\nProof.\n  exists 0 1.\n  apply (well_founded_induction lt_wf (fun n => 0 <= n -> fib n <= 1 * (fib_rec_time n))).\n  intros n IH _.\n  destruct n as [|n]. simpl. omega.\n  destruct n as [|n]. simpl. auto.\n  replace (fib_rec_time (S (S n))) with\n    ((fib_rec_time n) + (fib_rec_time (S n)) + 1); auto.\n\n  assert (fib n <= 1 * (fib_rec_time n)) as IHn.\n  eapply IH. auto. omega.\n  assert (fib (S n) <= 1 * (fib_rec_time (S n))) as IHSn.\n  eapply IH. auto. omega.\n\n  rewrite mult_1_l in *.\n\n  clear IH.\n  replace (fib (S (S n))) with (fib n + fib (S n)); auto.\n  omega.\nQed.\n\nFixpoint fib_rec_time2 (n:nat) :=\n  match n with\n    | O => 0\n    | S n' =>\n      match n' with\n        | O => 1\n        | S n'' => (fib_rec_time2 n'') + (fib_rec_time2 n') + 1\n      end\n  end.\n\nLemma fib_rec_time12 : big_oh fib_rec_time fib_rec_time2.\nProof.\n  exists 1 11.\n  intros n LT.\n  destruct n. intuition.\n  clear LT.\n  apply (well_founded_induction\n           lt_wf\n           (fun n => fib_rec_time (S n) <= 11 * (fib_rec_time2 (S n)))).\n  clear n; intros n IND.\n  destruct n.\n  simpl.\n  omega.\n  destruct n.\n  simpl.\n  omega.\n  replace (fib_rec_time (S (S (S n)))) \n  with (fib_rec_time (S n) + fib_rec_time (S (S n)) + 1);\n    [|unfold fib_rec_time;omega].\n  replace (fib_rec_time2 (S (S (S n)))) \n  with (fib_rec_time2 (S n) + fib_rec_time2 (S (S n)) + 1);\n    [|unfold fib_rec_time2;omega].\n  repeat (rewrite mult_plus_distr_l).\n  apply plus_le_compat.\n  apply plus_le_compat;apply IND;auto.\n  omega.\nQed.\n\nLemma fib_rec_time2_fib_relationship : \n  forall n, fib_rec_time2 n + 1 = (fib (S (S n))).\nProof.\n  intros.\n  apply (well_founded_induction\n           lt_wf\n           (fun n => fib_rec_time2 n + 1 = (fib (S (S n))))).\n  clear n; intros n IND.\n  destruct n.\n  simpl; reflexivity.\n  destruct n.\n  simpl; reflexivity.\n  replace (fib_rec_time2 (S (S n))) with (fib_rec_time2 (S n) + fib_rec_time2 n + 1);\n    [|unfold fib_rec_time2;omega].\n  rewrite fib_SS.\n  replace (fib_rec_time2 (S n) + fib_rec_time2 n + 1 + 1)\n  with ((fib_rec_time2 (S n) + 1) + (fib_rec_time2 n + 1));[|omega].\n  rewrite IND; auto.\nQed.\n\nLemma fib_rec_time23 : big_oh fib_rec_time2 fib.\nProof.\n  exists 0 3.\n  intros n _.\n  assert ((fib_rec_time2 n + 1) <= S (3 * fib n));[|omega].\n  rewrite fib_rec_time2_fib_relationship.\n  replace (S (3 * fib n)) with (3 * fib n + 1);[|omega].\n  rewrite fib_SS.\n  replace (3 * fib n + 1) with (2 * fib n + 1 + fib n);[|omega].\n  apply plus_le_compat; auto.\n  destruct n.\n  simpl.\n  omega.\n  rewrite fib_SS.\n  replace (2 * fib (S n) + 1) with (fib (S n) + (fib (S n) + 1));[|omega].\n  apply plus_le_compat;auto.\n  apply le_plus_trans.\n  apply fib_monotone; auto.\nQed.\n\nTheorem fib_big_theta_fib:\n  big_theta fib fib_rec_time.\nProof.\n  split. \n  apply fib_big_oh_fib.\n  apply big_oh_rev.\n  apply (big_oh_trans fib_rec_time fib_rec_time2).\n  apply fib_rec_time12.\n  apply fib_rec_time23.\nQed.\n\n", "meta": {"author": "rfindler", "repo": "395-2013", "sha": "afaeb6f4076a1330bbdeb4537417906bbfab5119", "save_path": "github-repos/coq/rfindler-395-2013", "path": "github-repos/coq/rfindler-395-2013/395-2013-afaeb6f4076a1330bbdeb4537417906bbfab5119/fib/fib_rec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.6808739099389808}}
{"text": "From mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat ssrfun eqtype seq choice fintype.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n \nInductive BinaryTree (T : Type) : Type :=\n    | Nill : BinaryTree T\n    | Node : BinaryTree T -> BinaryTree T -> T -> BinaryTree T -> BinaryTree T\n    .\n\nCheck (Nill nat).\nCheck (Node (Nill nat) (Nill nat) 5 (Nill nat)).\nCheck (Node (Nill nat) (Nill nat) 5 \n      (Node (Nill nat) (Nill nat) 7 (Nill nat))).\n\n(* ========================= *)\n(* Functions of BinaryTree T *)\n(* ========================= *)\n\nDefinition Lst {T} (tree : BinaryTree T) : BinaryTree T :=\n  match tree with\n  | Nill => Nill T\n  | Node _ Left _ _ => Left\n  end.\n\nDefinition Rst {T} (tree : BinaryTree T) : BinaryTree T :=\n  match tree with\n  | Nill => Nill T\n  | Node _ _ _ Right => Right\n  end.\n\nNotation null := (Nill nat).\nNotation \"l -| v |- r\" := (Node (Nill nat) l v r) (at level 43, left associativity).\nNotation \"@ v \" := (null -| v |- null) (at level 43, left associativity).\n\nEval compute in (Lst null).\nEval compute in (Rst null).\n\nEval compute in (Lst (@5)).\nEval compute in (Rst (@5)).\n\nEval compute in (Lst ((@3) -| 5 |- (@7))).\nEval compute in (Rst ((@3) -| 5 |- (@7))).\n\nFixpoint nodes {T} (tree : BinaryTree T) : seq T := \n  match tree with\n  | Nill => [::]\n  | Node _ Left value Right => value :: (nodes Left ++ nodes Right)\n  end.\n\n(* ====================== *)\n(* Height of BinaryTree T *)\n(* ====================== *)\n\nFixpoint height {T} (tree : BinaryTree T) : nat :=\n    match tree with\n    | Nill              => 0\n    | Node _ Left _ Right => 1 + maxn (height Left) (height Right)\n    end.\n\nLemma height_nill : forall {T}, height (Nill T) = 0.\nProof. \n  done.\nQed.\n\nLemma height_empty_tree : forall {T} (tree : BinaryTree T),\n  height tree = 0 <-> tree = Nill T.\nProof. \n  by move => T; case.\nQed.\n\nLemma height_subtrees : forall {T} (tree : BinaryTree T),\n  tree <> Nill T <-> height tree = 1 + maxn (height (Lst tree)) (height (Rst tree)).\nProof.\n  by move => T; case.\nQed.\n\n(* Count of BinaryTree T *)\n\nFixpoint count {T} (tree : BinaryTree T) : nat :=\n    match tree with\n    | Nill              => 0\n    | Node _ Left _ Right => 1 + (count Left) + (count Right)\n    end.\n\nEval compute in (height null).\nEval compute in (count null).\n\nEval compute in (height (@5)).\nEval compute in (count (@5)).\n\nEval compute in (height ((@3) -| 5 |- (@7))).\nEval compute in (count ((@3) -| 5 |- (@7))).\n\nEval compute in (height ((@3) -| 5 |- ((@6) -| 7 |- (@8)))).\nEval compute in (count ((@3) -| 5 |- ((@6) -| 7 |- (@8)))).\n\nLemma count_nill : forall {T}, count (Nill T) = 0.\nProof.\n  done.\nQed.\n\nLemma count_empty_tree : forall {T} (tree : BinaryTree T),\n  count tree = 0 <-> tree = Nill T.\nProof.\n  by move => T; case.\nQed.\n\nLemma count_subtrees : forall {T} (tree : BinaryTree T),\n  tree <> Nill T <-> count tree = 1 + count (Lst tree) + count (Rst tree).\nProof.\n  by move => T; case.\nQed.\n\n(* =================================================== *)\n(* Connection between height and count of BinaryTree T *)\n(* =================================================== *)\n\nTheorem leq_height_count : forall {T} (tree : BinaryTree T),\n  height tree <= count tree.\nProof.\n  move => T; elim => [| _ _ Ltree iHl value Rtree iHr] /= //.\n\n    rewrite (leq_add2l 1 _ (_ + _)).\n\n  - suff: forall a b c d, (maxn a b <= maxn c d) \n          -> (maxn a b <= c + d).\n    move => L1; apply: L1.\n\n  - suff: forall a b c d, a <= c -> b <= d -> a + b <= c + d\n          -> maxn a b <= maxn c d.\n    move => L2; apply: L2.\n    apply: iHl. apply: iHr.\n\n    by apply: leq_add.\n\n    (* first subgoal *)\n    move => a b c d acH bdH H.\n    case: (leqP b a) => abH.\n    - rewrite maxnC maxnE subnKC => //.\n      case: (leqP d c) => cdH.\n      - rewrite maxnC maxnE subnKC => //.\n      - rewrite maxnE subnKC.\n        - apply: ltnW. apply: leq_ltn_trans.\n          apply: acH. apply: cdH.\n        - by apply: ltnW.\n    - rewrite maxnE subnKC.\n      case: (leqP d c) => cdH.\n      - rewrite maxnC maxnE subnKC => //.\n        apply: leq_trans. apply: bdH. \n        apply: cdH.\n      - rewrite maxnE subnKC => //.\n        - apply: ltnW => //.\n        - apply: ltnW => //.\n\n    (* Auxiliary lemma *)\n    have: forall x y, maxn x y <= x + y.\n    elim => [x | x iHx y] .\n    - rewrite max0n => //.\n    - case: y => [| y]; first\n      rewrite maxn0 addn0 => //.\n      - rewrite maxnSS -add1n -(add1n x)\n        (leq_add2l 1 _ (_ + _)) addnS.\n        by apply: leqW.\n\n    move => leq_maxn_sum.\n\n    (* second subgoal *)\n    move => a b c d H.\n    apply: leq_trans. apply: H. \n    apply: leq_maxn_sum.\nQed.\n\nLtac solve :=\n  do ![try case: andP => //; case];\n  try split => //; try done.\n\n(* ============================================================ *)\n(* ### ----- Canonical comparison and eqType for BynaryTree T.  *)\n(* ============================================================ *)\n\nSection EqTree.\n\nVariables T : eqType.\nImplicit Type t : BinaryTree T.\n\nFixpoint eqtree t1 t2 {struct t1} := \n  match t1, t2 with\n  | Nill, Nill => true\n  | Node P1 L1 v1 R1, Node P2 L2 v2 R2 =>\n    (v1 == v2) && eqtree P1 P2 && eqtree L1 L2 && eqtree R1 R2\n  | _, _ => false\n  end.\n\nLemma eqtreeP : Equality.axiom eqtree.\nProof.\n  move; elim => [| tp1 iHtp tl1 iHtl v1 tr1 iHtr] [| tp2 tl2 v2 tr2];\n        do [by constructor | simpl].\n  - case: andP.\n    - case; case: andP => //; case.\n      case: andP => //; case => eqv eqtp _ eqtl _ eqtr.\n      constructor.\n      case: iHtp eqtp => Htp _ //.\n      case: iHtl eqtl => Htl _ //.\n      case: iHtr eqtr => Htr _ //.\n      case: eqP eqv => /= // Hv _.\n      by rewrite Htp Htl Hv Htr.\n  - move => H. constructor => H'. inversion H'.\n     apply: H. solve.\n    - case: iHtr H4 => //.\n    - case: iHtl H2 => //.\n    - case: eqP H3 => //.\n    - case: iHtp H1 => //.\nQed.\n\nCanonical tree_eqMixin := EqMixin eqtreeP.\nCanonical tree_eqType := Eval hnf in EqType (BinaryTree T) tree_eqMixin.\n\nLemma eqtreeE : eqtree = eq_op.\nProof.\n  elim: eqtree => //; do [by constructor].\nQed.\n\nEnd EqTree.\n\nImplicit Arguments eqtreeP [T x y].\n\nEval compute in (null == null).\nEval compute in (null == (@4) -| 5 |- (@6)).\nEval compute in ((@4) -| 5 |- (@6) == (@4) -| 5 |- (@6)).\nEval compute in ((@3) -| 5 |- (@6) == (@4) -| 5 |- (@6)).\n\n(* ================== *)\n(* Binary search tree *)\n(* ================== *)\n\nFixpoint Is_cond (s : seq nat) (P : nat -> bool) : bool :=\n  match s with \n  | [::]    => true\n  | y :: ys => P y && Is_cond ys P \n  end.\n\nFixpoint Left_cond (tree : BinaryTree nat) : bool := \n  match tree with\n  | Nill => true\n  | Node _ Left value Right => Is_cond (nodes (Lst tree)) (fun y => y < value)\n    && Left_cond Left && Left_cond Right\n  end.\n\nFixpoint Right_cond (tree : BinaryTree nat) : bool := \n  match tree with\n  | Nill => true\n  | Node _ Left value Right => Is_cond (nodes (Rst tree)) (fun y => value < y)\n    && Right_cond Left && Right_cond Right\n  end.\n\nEval compute in (Left_cond (((@1) -| 2 |- (@3)) -| 4 |- (@ 6))).\nEval compute in (Left_cond (((@3) -| 2 |- (@1)) -| 4 |- (@ 6))).\nEval compute in (Right_cond (((@1) -| 2 |- (@3)) -| 4 |- (@ 6))).\nEval compute in (Right_cond (((@3) -| 2 |- (@1)) -| 4 |- (@ 6))).\n\nInductive BST : BinaryTree nat -> Prop :=\n  | bst_nill : BST null\n  | bst_node : forall tree, Left_cond tree -> Right_cond tree ->\n    BST (Lst tree) -> BST (Rst tree) -> BST tree.\n\nLemma BST_Nill : BST null.\nProof.\n  apply: bst_nill.\nQed.\n\nLemma BST_Combine : forall tp tl v tr,\n  Left_cond (Node tp tl v tr) -> Right_cond (Node tp tl v tr) -> \n  BST tl -> BST tr -> BST (Node tp tl v tr).\nProof.\n  move => tp tl value tr Lc Rc lH rH.\n  by apply: bst_node.\nQed.\n\nLemma BST_One : forall y, BST (@ y).\nProof.\n  move => y;\n  apply: bst_node => //;\n  do [apply: BST_Nill]. \nQed.\n\nLemma BST_Example_1 : BST ((@3) -| 5 |- (@ 7)).\nProof.\n  apply: bst_node => //;\n  do [apply: BST_One].\nQed.\n\nLemma BST_Two_l : forall a b, b < a -> \n  BST ((@ b) -| a |- null).\nProof.\n  move => a b cond.\n  apply: bst_node => // /=.\n  - solve.\n  - apply: BST_One.\n  - apply: BST_Nill.\nQed.\n\nLemma BST_Two_r : forall a b, a < b -> \n  BST (null -| a |- (@ b)).\nProof.\n  move => a b cond.\n  apply: bst_node => // /=.\n  - solve.\n  - apply: BST_Nill.\n  - apply: BST_One.\nQed.\n\nLemma BST_Tree : forall a b c, b < a < c -> \n  BST ((@ b) -| a |- (@ c)).\nProof.\n  move => a b c cond.\n  apply: bst_node => /=.\n  - solve.\n    by case: andP cond => //; case.\n  - solve.\n    by case: andP cond => //; case.\n  - apply: BST_One.\n  - apply: BST_One.\nQed.\n\nLemma BST_Example_2 : BST ((null -| 3 |- (@ 4)) -| 5 |- (@ 7)).\nProof.\n  by apply: bst_node => //;\n  do [apply: BST_Two_r| apply: BST_One].\nQed.\n\n(* ============= *)\n(* Insert in BST *)\n(* ============= *) \n\nFixpoint BST_insert (value : nat) (tree : BinaryTree nat) : BinaryTree nat :=\n    match tree with\n    | Nill                => null -| value |- null\n    | Node _ Left y Right =>\n        if value < y\n        then (BST_insert value Left) -| y |- Right\n        else if y < value \n        then Left -| y |- (BST_insert value Right)\n        else tree\n    end. \n\nNotation \"v >> t\" := (BST_insert v t) (at level 43, left associativity).\n\nEval compute in (2 >> null).\nEval compute in (2 >> (@ 3)).\nEval compute in (2 >> (@ 1)).\nEval compute in (1 >> ((@ 2) -| 4 |- (@ 6))).\nEval compute in (3 >> ((@ 2) -| 4 |- (@ 6))).\nEval compute in (5 >> ((@ 2) -| 4 |- (@ 6))).\nEval compute in (7 >> ((@ 2) -| 4 |- (@ 6))).\n\nAxiom Insert_cond : forall value tree, \n  nodes (value >> tree) = value :: (nodes tree).\n\nLemma Safety_Left_cond : forall tree y, Left_cond tree -> Left_cond (y >> tree).\nProof.\n  elim => /= [y _ | tp _ tl iHtl z tr iHtr w H] //.\n  - case: andP H => //; case; solve => condL lH _ rH _.\n    case: (ltngtP w z) => cond /=; solve.\n    - rewrite Insert_cond => /=; solve.\n    - apply: iHtl lH.\n    - apply: iHtr rH.\nQed.\n\nLemma Safety_Right_cond : forall tree y, Right_cond tree -> Right_cond (y >> tree).\nProof.\n  elim => /= [y _ | tp _ tl iHtl z tr iHtr w H] //.\n  - case: andP H => //; case; solve => condR lH _ rH _.\n    case: (ltngtP w z) => cond /=; solve.\n    - apply: iHtl lH.\n    - apply: iHtr rH.\n    - rewrite Insert_cond => /=.\n      by solve; apply: ltnW.\nQed.\n\nTheorem Safety_BST_insert : forall tree y, BST tree -> BST (y >> tree).\nProof.\n  elim => /= [y _ | tp _ tl iHtl z tr iHtr w H] //.\n  - apply: BST_One.\n    inversion H.\n    inversion H0; case: andP H6 => //; case.\n    case: andP => //; case => condL lH _ rH _;\n    inversion H1; case: andP H6 => //; case.\n    case: andP => //; case => condR lH' _ rH' _.\n    case: (ltngtP w z) => cond //.\n    - apply: BST_Combine => /= //.\n      - solve.\n        - rewrite Insert_cond => /=; solve.\n        - apply: Safety_Left_cond lH.\n      - solve.\n        apply: Safety_Right_cond lH'.\n      - apply: iHtl H2.\n    - apply: BST_Combine => /= //.\n      - solve; apply: Safety_Left_cond rH.\n      - solve.\n        - apply: Safety_Right_cond rH'.\n        - rewrite Insert_cond => /=.\n          by solve; apply: ltnW.\n      - apply: iHtr H3.\nQed.\n\n(* ======================== *)\n(* BST with bool definition *)\n(* ======================== *)\n\nFixpoint BSTeq (tree : BinaryTree nat) : bool := \n  match tree with\n  | Nill => true\n  | Node _ Left value Right => \n    Left_cond tree && Right_cond tree &&\n    BSTeq Left && BSTeq Right\n  end.\n\nLemma BSTeq_Nill : BSTeq null.\nProof.\n  done.\nQed.\n\nLemma BSTeq_Combine : forall tp tl v tr,\n  Left_cond (Node tp tl v tr) -> Right_cond (Node tp tl v tr) -> \n  BSTeq tl -> BSTeq tr -> BSTeq (Node tp tl v tr).\nProof.\n  move => /= tp tl value tr Lc Rc lH rH.\n  case: andP => //; case.\n  case: andP => //; case.\n  by case: andP => //; case.\nQed.\n\nLemma BSTeq_One : forall y, BSTeq (null -| y |- null).\nProof.\n  done.\nQed.\n\nLemma BSTeq_Example_1 : BSTeq ((@ 3) -| 5 |- (@ 7)).\nProof.\n  done.\nQed.\n\nLemma BSTeq_Two_l : forall a b, b < a -> \n  BSTeq ((@ b) -| a |- null).\nProof.\n  move => /= a b cond.\n  solve.\nQed.\n\nLemma BSTeq_Two_r : forall a b, a < b -> \n  BSTeq (null -| a |- (@ b)).\nProof.\n  move => /= a b cond; solve.\nQed.\n\nLemma BSTeq_Tree : forall a b c, b < a < c -> \n  BSTeq ((@ b) -| a |- (@ c)).\nProof.\n  move => /= a b c cond; solve.\n  - by case: andP cond => //; case.\n  - by case: andP cond => //; case.\nQed.\n\nLemma BSTeq_Example_2 : BSTeq ((null -| 3 |- (@ 4)) -| 5 |- (@ 7)).\nProof.\n  done.\nQed.\n\nTheorem Safety_BSTeq_insert : forall tree y, BSTeq tree -> BSTeq (y >> tree).\nProof.\n  elim => /= [y _ | tp _ tl iHtl z tr iHtr w] //.\n  case: andP => //; case.\n  case: andP => //; case.\n  case: andP => //; case => condL condR _ lH _ rH _.\n  case: andP condR => //; case.\n  case: andP => //; case => condtR LH _ RH _.\n  case: andP condL => //; case.\n  case: andP => //; case => condtL LH' _ RH' _.\n  case: (ltngtP w z) => cond /= //. \n  - rewrite Insert_cond /=; solve.\n    - apply: iHtl lH.\n    - apply: Safety_Right_cond LH.\n    - apply: Safety_Left_cond LH'.\n  - rewrite Insert_cond /=; solve.\n    - apply: iHtr rH.\n    - apply: Safety_Right_cond RH.\n    - apply: Safety_Left_cond RH'.\n  solve.\nQed.\n\n(* =========================== *)\n(* Reflect betwen BST and BST' *)\n(* =========================== *)\n\nTheorem bstP (tree : BinaryTree nat) : reflect (BST tree) (BSTeq tree).\nProof.\n  elim: tree => [| tp _ tl iHtl z tr iHtr] /=.\n  - constructor; apply: BST_Nill.\n  - case: andP.\n    - case; case: andP => //; case.\n      case; case: andP => //. case => condL condR _ lH _ rH.\n      constructor.\n      apply: BST_Combine => //.\n      - by case: iHtl lH.\n      - by case: iHtr rH.\n    - move => H1. constructor. move => H2.\n      apply: H1. inversion H2.\n      case: andP => //; case.\n      - solve. move: H3.\n        rewrite Rst_elem. case: iHtr => //.\n      - case: andP => //; case.\n        - split => //. move: H1.\n          rewrite Lst_elem; case: iHtl => //.\n        - split => //.\nQed.\n\nLemma BST_Example_3 : BST (((@2) -| 3 |- (@ 4)) -| 5 |- ((@6) -| 7 |- (@ 9))).\nProof.\n  by apply: bstP.\nQed.\n\n(* =========================== *)\n(* ### ----- Tree with parents *)\n(* =========================== *)\n\nDefinition Pst {T} (tree : BinaryTree T) : BinaryTree T :=\n  match tree with\n  | Nill => Nill T\n  | Node Parent _ _ _ => Parent\n  end.\n\nFixpoint Parent_cond {T: eqType} (tree : BinaryTree T) : bool := \n  match tree with\n  | Nill => true\n  | Node P L _ R => \n    (if P == Nill T then true\n     else (Lst P == tree) || (Rst P == tree)) &&\n    (if L == Nill T then true\n     else Pst L == tree) &&\n    (if R == Nill T then true\n     else Pst R == tree) &&\n    Parent_cond P && Parent_cond L && Parent_cond R\n  end.\n\n(* =========================== *)\n(* ### ------ BST with parents *)\n(* =========================== *)\n\nInductive BSTwP : BinaryTree nat -> Prop :=\n  | wP_constr : forall tree, BST tree -> Parent_cond tree -> BSTwP tree.\n\nDefinition BSTwPeq (tree : BinaryTree nat) : bool :=\n  BSTeq tree && Parent_cond tree.\n\nLemma bstwpP (tree : BinaryTree nat) : reflect (BSTwP tree) (BSTwPeq tree).\nProof.\n  unfold BSTwPeq.\n  case: andP => cond; constructor.\n  - constructor; case: cond => //;\n    case: bstP => //.\n  - move => H; apply: cond.\n    case: H => t bst_cond parent_cond. split => //.\n    by case: bstP.\nQed.\n\nFixpoint BSTwP_insert (value : nat) (tree : BinaryTree nat) : BinaryTree nat :=\n    match tree with\n    | Nill                => Node (null -| 5 |- null) null value null\n    | Node _ Left y Right =>\n        if value < y\n        then (BSTwP_insert value Left) -| y |- Right\n        else if y < value \n        then Left -| y |- (BSTwP_insert value Right)\n        else tree\n    end.\n\nNotation \"v >>wP t\" := (BSTwP_insert v t) (at level 43, left associativity).\n\nEval compute in (2 >>wP null).\nEval compute in (2 >>wP (@ 3)).\nEval compute in (2 >>wP (@ 1)).\nEval compute in (1 >>wP ((@ 2) -| 4 |- (@ 6))).\nEval compute in (3 >>wP ((@ 2) -| 4 |- (@ 6))).\nEval compute in (5 >>wP ((@ 2) -| 4 |- (@ 6))).\nEval compute in (7 >>wP ((@ 2) -| 4 |- (@ 6))).\n\nAxiom Insert_cond_wP : forall value tree, \n  nodes (value >>wP tree) = value :: (nodes tree).\n\nLemma bst_insertP (tree : BinaryTree nat) (y : nat) : \n  reflect (BSTeq (y >> tree)) (BSTeq (y >>wP tree)).\nProof.\n  elim: tree y => [| tp iHtp tl iHtl v tr iHtr y] /=; \n        do [by constructor|].\n  case: (ltngtP y v) => cond /= //.\n  - case: andP => //.\n    case: andP => //.\n    case: andP => //.\n    case: andP => //.\n    case: andP => //.\n    case: andP => //.\n    case: andP => //.\n    case: andP => //.\n    by constructor.\n    constructor => /=.\n    case: n. solve.\n    case: p4 => _.\n    case: iHtl => //.\nAdmitted.\n\n\n(* =========================== *)\n(* ### ------------ Splay tree *)\n(* =========================== *)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "arrival3000", "repo": "Specification-of-data-structures-in-Coq", "sha": "1b7dab19e46b14ef3b44d14dc72d4f7c6ce55773", "save_path": "github-repos/coq/arrival3000-Specification-of-data-structures-in-Coq", "path": "github-repos/coq/arrival3000-Specification-of-data-structures-in-Coq/Specification-of-data-structures-in-Coq-1b7dab19e46b14ef3b44d14dc72d4f7c6ce55773/Tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.6808738946094146}}
{"text": "(* Re-doing Examples/Specware-Overview/MergeSort.sw in SpecwareCoq *)\n\nLoad DivideAndConquer.\n\nRequire Import List.\nImport ListNotations.\nRequire Import Coq.Arith.Arith_base.\nRequire Import Coq.Arith.Div2.\nRequire Import Coq.Wellfounded.Wellfounded.\nRequire Import Coq.Relations.Relation_Operators.\n\n\n(***\n *** Definitions of \"sorted\" and \"permutation-of\"\n ***)\n\n(* A list is sorted iff it is empty, a singleton, or its first element is no\ngreater than its second and its tail is sorted. *)\nFixpoint sorted (l: list nat) : Prop :=\n  match l with\n    | [] => True\n    | x::l' =>\n      (match l' with\n         | [] => True\n         | y::_ => x <= y /\\ sorted l'\n       end)\n  end.\n\n(* Two lists are permutations of each other iff they have the same number of\noccurrences of all elements. *)\nDefinition permOf (l1 l2: list nat) : Prop :=\n  forall x, count_occ eq_nat_dec l1 x = count_occ eq_nat_dec l2 x.\n\nLemma permOf_refl l : permOf l l.\n  intro x; reflexivity.\nQed.\n\nLemma permOf_sym l1 l2 : permOf l1 l2 -> permOf l2 l1.\n  intros pof x; symmetry; apply (pof x).\nQed.\n\nLemma permOf_trans l1 l2 l3 :\n  permOf l1 l2 -> permOf l2 l3 -> permOf l1 l3.\n  intros pof12 pof23 x.\n  rewrite (pof12 x). apply pof23.\nQed.\n\nLemma permOf_cons x l1 l2 :\n  permOf l1 l2 -> permOf (x::l1) (x::l2).\n  intros pof y. destruct (eq_nat_dec x y).\n  rewrite (count_occ_cons_eq _ _ e); rewrite (count_occ_cons_eq _ _ e).\n  f_equal; apply pof.\n  rewrite (count_occ_cons_neq _ _ n); rewrite (count_occ_cons_neq _ _ n).\n  apply pof.\nQed.\n\nLemma permOf_swap x y l : permOf (x::y::l) (y::x::l).\n  intro z; unfold count_occ; fold (count_occ eq_nat_dec l).\n  destruct (eq_nat_dec x z); destruct (eq_nat_dec y z); reflexivity.\nQed.\n\nLemma permOf_nil_cons x l : ~(permOf [] (x::l)).\n  intro pof.\n  assert (0 = count_occ eq_nat_dec (x::l) x); [ apply pof | ].\n  rewrite (count_occ_cons_eq eq_nat_dec l eq_refl) in H.\n  discriminate.\nQed.\n\nLemma permOf_app_cons l1 x l2 :\n  permOf (l1 ++ x::l2) (x::l1 ++ l2).\n  induction l1.\n  intro y; reflexivity.\n  intro y.\n  unfold app; fold (app l1).\n  unfold count_occ; fold (count_occ eq_nat_dec (l1++x::l2));\n  fold (count_occ eq_nat_dec (l1++l2)).\n  rewrite (IHl1 y).\n  case_eq (eq_nat_dec a y); intros; case_eq (eq_nat_dec x y); intros.\n  unfold count_occ; rewrite H0; reflexivity.\n  unfold count_occ; rewrite H0; reflexivity.\n  unfold count_occ; rewrite H0; reflexivity.\n  unfold count_occ; rewrite H0; reflexivity.\nQed.\n\n\nLemma permOf_cons_in x l1 l2 :\n  permOf (x::l1) l2 -> In x l2.\n  intro pof.\n  apply (proj2 (count_occ_In eq_nat_dec _ _)).\n  rewrite <- pof.\n  unfold count_occ; destruct (eq_nat_dec x x).\n  apply lt_0_Sn.\n  elimtype False; apply (n eq_refl).\nQed.\n\nLemma in_split_set x l :\n  In x l -> { l1 : list nat & { l2 : list nat & l = l1 ++ x :: l2 } }.\n  induction l; intros.\n  elimtype False; apply H.\n  destruct (eq_nat_dec a x).\n  rewrite e. exists []; exists l; reflexivity.\n  assert (In x l).\n  destruct H; [ contradiction | assumption ].\n  destruct (IHl H0) as [ l1 X ]; destruct X as [ l2 e ].\n  exists (a::l1); exists l2. rewrite e. reflexivity.\nQed.\n\nLemma permOf_cons_inv x l1 l2 :\n  permOf (x::l1) (x::l2) -> permOf l1 l2.\n  intros pof y.\n  assert (count_occ eq_nat_dec (x::l1) y =\n          count_occ eq_nat_dec (x::l2) y); [ apply pof | ].\n  unfold count_occ in H; fold (count_occ eq_nat_dec) in H.\n  destruct (eq_nat_dec x y).\n  injection H; intros; assumption.\n  assumption.\nQed.\n\nLemma permOf_app l1 l1' l2 l2' :\n  permOf l1 l1' -> permOf l2 l2' -> permOf (l1++l2) (l1'++l2').\n  revert l1' l2 l2'; induction l1; intros.\n  destruct l1'.\n  assumption.\n  elimtype False; apply (permOf_nil_cons n l1'); assumption.\n  assert (In a l1').\n  apply (permOf_cons_in _ l1); assumption.\n  destruct (in_split_set a l1' H1) as [ l1'' X ]; destruct X as [ l2'' e ].\n  rewrite e. rewrite <- app_assoc.\n  rewrite <- app_comm_cons. rewrite <- app_comm_cons.\n  apply (permOf_trans _ (a :: l1'' ++ l2'' ++ l2')).\n  apply permOf_cons.\n  rewrite app_assoc.\n  apply IHl1.\n  rewrite e in H.\n  apply (permOf_cons_inv a).\n  apply (permOf_trans _ _ _ H).\n  apply permOf_app_cons.\n  assumption.\n  apply permOf_sym.\n  apply permOf_app_cons.\nQed.\n\n\n(***\n *** The high-level spec for sorting\n ***)\n\nSpec Sorting.\n\nSpec Variable sort : (list nat -> list nat).\nSpec Axiom sort_correct :\n  (forall l, sorted (sort l) /\\ permOf l (sort l)).\n\nSpec End Sorting.\n\n\n(***\n *** The MergeSort0 spec, which instantiates all the elements of the\n *** DivideAndConquer_base spec for merge-sort.\n ***)\n\nSpec MergeSort0.\n\n(* Domain and range types *)\nSpec Definition D : Type := (list nat).\nSpec Definition R : Type := (list nat).\n\n(* Input / output predicate *)\nSpec Definition IO : (D -> R -> Prop) :=\n  (fun lin lout => sorted lout /\\ permOf lin lout).\n\n(* The well-founded partial order on the inputs *)\nSpec Definition smaller : (D -> D -> Prop) :=\n  (fun l1 l2 => length l1 < length l2).\n\n(* Proof that smaller is well-founded. Note that we make this a Definition\ninstead of a Theorem because DivideAndConquer_base requires well-foundedness to\nbe a subtype predicate and not an axiom. *)\nDefinition smaller_wf : (well_founded smaller) :=\n  (well_founded_ltof _ _).\n\n\n(***\n *** The base case, which is directly sorting a singleton list\n ***)\n\n(* Test if a list is empty or a singleton; leb is the decision procedure for\ndeciding less-than-or-equal. *)\nSpec Definition primitive : (D -> bool) :=\n  (fun l => leb (length l) 1).\n\n(* Sorting for an empty or singleton list is just the identity *)\nSpec Definition direct_solve : (D -> R) := (fun l => l).\n\n\n(***\n *** The decompose operation; requires list prefix and suffix\n ***)\n\n(* Take the prefix of l of length <= n *)\nFixpoint list_prefix n l : list nat :=\n  match n with\n    | 0 => []\n    | S n' =>\n      match l with\n        | [] => []\n        | x::l' => x :: list_prefix n' l'\n      end\n  end.\n\n(* Lemma: the length of list_prefix n l is no greater than n *)\nLemma list_prefix_len n l : length (list_prefix n l) <= n.\n  revert l; induction n; intros.\n  reflexivity.\n  destruct l.\n  apply le_0_n.\n  apply le_n_S. apply IHn.\nQed.\n\n(* Take the suffix of l, removing the first n elements, if they exist *)\nFixpoint list_suffix n l : list nat :=\n  match n with\n    | 0 => l\n    | S n' =>\n      match l with\n        | [] => []\n        | x::l' => list_suffix n' l'\n      end\n  end.\n\n(* Lemma: the length of list_suffix n l is length l - n *)\nLemma list_suffix_len n l : length (list_suffix n l) = length l - n.\n  revert l; induction n; intro l; destruct l; try reflexivity.\n  unfold list_suffix; fold list_suffix.\n  unfold length; fold (length l); fold (length (list_suffix n l)).\n  apply IHn.\nQed.\n\n(* Appending the prefix and the suffix yields the original list *)\nLemma list_prefix_suffix_eq n l : list_prefix n l ++ list_suffix n l = l.\n  revert l; induction n; intro l; [ | destruct l ].\n  reflexivity.\n  reflexivity.\n  unfold list_prefix; fold list_prefix.\n  unfold list_suffix; fold list_suffix.\n  unfold app; fold (app (list_prefix n l)).\n  f_equal.\n  apply IHn.\nQed.\n\n(* The decompose operator splits a list into prefix and suffix *)\nSpec Definition decompose : (D -> D * D) :=\n  (fun l => (list_prefix (div2 (length l)) l,\n             list_suffix (div2 (length l)) l)).\n\n(* Proof that decompose yields smaller lists. As with smaller_wf, we make this a\nDefinition and not a Theorem because DivideAndConquer_base needs it as a proof\nof a subtype predicate. *)\nDefinition decompose_smallerH l :\n  primitive l = false ->\n  smaller (fst (decompose l)) l /\\ smaller (snd (decompose l)) l.\n  intro H; unfold decompose, smaller, def, fst, snd.\n  assert (1 < length l).\n  apply leb_complete_conv. assumption.\n  split.\n  apply (le_lt_trans _ (div2 (length l))).\n  apply list_prefix_len. apply lt_div2.\n  transitivity 1; [ constructor | assumption ].\n  rewrite list_suffix_len.\n  apply lt_minus.\n  apply lt_le_weak. apply lt_div2.\n  transitivity 1; [ constructor | assumption ].\n  destruct l.\n  inversion H0.\n  destruct l.\n  inversion H0; inversion H2.\n  apply lt_0_Sn.\nQed.\n\nDefinition decompose_smaller :\n  (forall l,\n     primitive l = false ->\n     smaller (fst (decompose l)) l /\\ smaller (snd (decompose l)) l) :=\n  decompose_smallerH.\n\n\n(***\n *** The compose operation, which requires list merge\n ***)\n\n(* The length order on pairs of lists, which requires one of the two lists in\nthe pair to be smaller and the other to be the same list; this is called the\nsymmetric product of the length ordering. *)\nDefinition list_pair_smaller : list nat * list nat -> list nat * list nat -> Prop :=\n  symprod _ _ smaller smaller.\n\n(* Merge two lists *)\nFunction merge_lists (l_pair: list nat * list nat) {wf list_pair_smaller l_pair} : list nat :=\n  let (l1,l2) := l_pair in\n  match l1 with\n    | [] => l2\n    | x1::l1' =>\n      match l2 with\n        | [] => l1\n        | x2::l2' =>\n          if lt_dec x1 x2 then\n            x1::merge_lists (l1',l2)\n          else\n            x2::merge_lists (l1,l2')\n      end\n  end.\nintros. apply left_sym. apply le_n.\nintros. apply right_sym. apply le_n.\napply wf_symprod; apply smaller_wf.\nDefined.\n\n(* Helper lemma: merge_lists applied to two cons lists yields a result whose\nhead is one of the two heads of the two lists. *)\nLemma merge_lists_cons_cons x1 l1 x2 l2 :\n  {merge_lists (x1::l1, x2::l2) = x1::merge_lists (l1,x2::l2)} +\n  {merge_lists (x1::l1, x2::l2) = x2::merge_lists (x1::l1,l2)}.\n  assert (forall l_pair,\n            l_pair = (x1::l1, x2::l2) ->\n            {merge_lists l_pair = x1::merge_lists (l1,x2::l2)} +\n            {merge_lists l_pair = x2::merge_lists (x1::l1,l2)}).\n  intro l_pair; functional induction (merge_lists l_pair); intros; try discriminate.\n  injection H; intros.\n  rewrite H0; rewrite H1; rewrite H2; rewrite H3; left; reflexivity.\n  injection H; intros.\n  rewrite H0; rewrite H1; rewrite H2; rewrite H3; right; reflexivity.\n  apply H; reflexivity.\nQed.\n\n(* Helper lemma: merging two sorted lists is sorted *)\nLemma merge_lists_sorted l_pair :\n  sorted (fst l_pair) -> sorted (snd l_pair) -> sorted (merge_lists l_pair).\n  functional induction (merge_lists l_pair); unfold fst, snd; intros; try assumption.\n  unfold sorted; fold sorted.\n  destruct l1' as [ | x1' l1' ].\n  split.\n  apply lt_le_weak; assumption.\n  apply IHl; [ constructor | assumption ].\n  destruct (merge_lists_cons_cons x1' l1' x2 l2') as [ e_ml | e_ml ];\n    rewrite e_ml; rewrite <- e_ml.\n  split.\n  destruct H; assumption.\n  apply IHl; [ destruct H | ]; assumption.\n  split.\n  apply lt_le_weak; assumption.\n  apply IHl; [ destruct H | ]; assumption.\n  unfold sorted; fold sorted.\n  destruct l2' as [ | x2' l2' ].\n  split.\n  destruct (le_or_lt x2 x1); [ assumption | contradiction ].\n  assumption.\n  destruct (merge_lists_cons_cons x1 l1' x2' l2') as [ e_ml | e_ml ];\n    rewrite e_ml; rewrite <- e_ml.\n  split.\n  destruct (le_or_lt x2 x1); [ assumption | contradiction ].\n  apply IHl; [ assumption | destruct H0; assumption ].\n  split.\n  destruct H0; assumption.\n  apply IHl; [ assumption | destruct H0; assumption ].\nQed.\n\n(* Helper lemma: merging lists yields a permutation of the original lists *)\nLemma merge_lists_permOf l_pair :\n  permOf (fst l_pair ++ snd l_pair) (merge_lists l_pair).\n  functional induction (merge_lists l_pair); unfold fst, snd.\n  intro x; reflexivity.\n  intro x; rewrite app_nil_r; reflexivity.\n  apply permOf_cons; fold (app l1'); apply IHl.\n  apply (permOf_trans _ (x2 :: (x1 :: l1') ++ l2')).\n  apply permOf_app_cons.\n  apply permOf_cons. apply IHl.\nQed.\n\nSpec Definition compose : (R -> R -> R) := (fun l1 l2 => merge_lists (l1,l2)).\n\n\n(***\n *** Correctness theorems for the base and step cases\n ***)\n\n(* Theorem: direct_solve is correct for primitive problems *)\nSpec Theorem direct_solve_correct :\n  (forall l, primitive l = true -> IO l (direct_solve l)).\n  unfold primitive, D, IO, direct_solve, def; intros.\n  destruct l.\n  (* Prove correctness for the empty list *)\n  split.\n  unfold sorted; trivial.\n  unfold permOf; intros; reflexivity.\n\n  destruct l.\n  (* Prove correctness for singleton lists *)\n  split.\n  unfold sorted; trivial.\n  unfold permOf; intros; reflexivity.\n\n  (* Lists with more than 1 element contradict primitive l = true *)\n  discriminate H.\nQed.\n\n\n(* Theorem: if we solve the two decomposed problems then composing them is a\nsolution *)\nSpec Theorem solve_soundness :\n  (forall l lout1 lout2,\n     IO (fst (decompose l)) lout1 ->\n     IO (snd (decompose l)) lout2 ->\n     IO l (compose lout1 lout2)).\n  unfold D, R, decompose, compose, IO, def, fst, snd.\n  intros l lout1 lout2 conj1 conj2; destruct conj1; destruct conj2.\n  split.\n  apply merge_lists_sorted; assumption.\n  rewrite <- (list_prefix_suffix_eq (div2 (length l)) l).\n  apply (permOf_trans _ (lout1 ++ lout2)).\n  apply permOf_app; assumption.\n  fold (fst (lout1,lout2)); fold (snd (lout1,lout2)).\n  apply merge_lists_permOf.\nQed.\n\nSpec End MergeSort0.\n\n\n(***\n *** Now we make an interpretation from DivideAndConquer_base to MergeSort0\n ***)\n\nSpec Interpretation DC_MergeSort0 : DivideAndConquer_base -> MergeSort0.\nprove_simple_interp {{ }}.\napply (MergeSort0.smaller_wf (D__proof__param:=pf) (smaller__proof__param:=eq_refl)).\nintros d H.\nCheck MergeSort0.decompose_smaller.\napply (MergeSort0.decompose_smaller\n         (smaller__proof__param:=pf2) (primitive__proof__param:=pf3)\n         (decompose__proof__param:=eq_refl)\n         d H).\napply (MergeSort0.direct_solve_correct\n         (D__param:=t) (D__proof__param:=pf) (R__param:=t0) (R__proof__param:=pf0)\n         (IO__param:=t1) (IO__proof__param:=pf1)\n         (primitive__param:=t3) (primitive__proof__param:=pf3)\n         (direct_solve__proof__param:=pf4)\n         d H).\napply (MergeSort0.solve_soundness\n         (IO__proof__param:=pf1) (smaller__proof__param:=pf2)\n         (decompose__proof__param:=pf5) (compose__proof__param:=pf6)\n         _ _ _ H H0).\napply (MergeSort0.solve_soundness\n         (IO__proof__param:=pf1) (smaller__proof__param:=pf2)\n         (decompose__proof__param:=pf5) (compose__proof__param:=pf6)\n         _ _ _ H H0).\nDefined.\n", "meta": {"author": "KestrelInstitute", "repo": "SpecwareC", "sha": "b1234db75aeaaa91e66b15dae79b3ec195e12e41", "save_path": "github-repos/coq/KestrelInstitute-SpecwareC", "path": "github-repos/coq/KestrelInstitute-SpecwareC/SpecwareC-b1234db75aeaaa91e66b15dae79b3ec195e12e41/examples/MergeSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199673867852, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.6808738905610529}}
{"text": "(** * Basics: Functional Programming in Coq *)\n\n(* REMINDER:\n\n        #####################################################\n        ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n        #####################################################\n\n   (See the [Preface] for why.)\n*)\n\n(* ################################################################# *)\n(** * Introduction *)\n\n(** The functional style of programming is founded on simple, everyday\n    mathematical intuition: If a procedure or method has no side\n    effects, then (ignoring efficiency) all we need to understand\n    about it is how it maps inputs to outputs -- that is, we can think\n    of it as just a concrete method for computing a mathematical\n    function.  This is one sense of the word \"functional\" in\n    \"functional programming.\"  The direct connection between programs\n    and simple mathematical objects supports both formal correctness\n    proofs and sound informal reasoning about program behavior.\n\n    The other sense in which functional programming is \"functional\" is\n    that it emphasizes the use of functions as _first-class_ values --\n    i.e., values that can be passed as arguments to other functions,\n    returned as results, included in data structures, etc.  The\n    recognition that functions can be treated as data gives rise to a\n    host of useful and powerful programming idioms.\n\n    Other common features of functional languages include _algebraic\n    data types_ and _pattern matching_, which make it easy to\n    construct and manipulate rich data structures, and _polymorphic\n    type systems_ supporting abstraction and code reuse.  Coq offers\n    all of these features.\n\n    The first half of this chapter introduces the most essential\n    elements of Coq's native functional programming language, called\n    _Gallina_.  The second half introduces some basic _tactics_ that\n    can be used to prove properties of Gallina programs. *)\n\n(* ################################################################# *)\n(** * Data and Functions *)\n\n(* ================================================================= *)\n(** ** Enumerated Types *)\n\n(** One notable aspect of Coq is that its set of built-in\n    features is _extremely_ small.  For example, instead of providing\n    the usual palette of atomic data types (booleans, integers,\n    strings, etc.), Coq offers a powerful mechanism for defining new\n    data types from scratch, with all these familiar types as\n    instances.\n\n    Naturally, the Coq distribution comes with an extensive standard\n    library providing definitions of booleans, numbers, and many\n    common data structures like lists and hash tables.  But there is\n    nothing magic or primitive about these library definitions.  To\n    illustrate this, in this course we will explicitly recapitulate\n    (almost) all the definitions we need, rather than getting them\n    from the standard library. *)\n\n(* ================================================================= *)\n(** ** Days of the Week *)\n\n(** To see how this definition mechanism works, let's start with\n    a very simple example.  The following declaration tells Coq that\n    we are defining a set of data values -- a _type_. *)\n\n        Inductive day : Type :=\n        | monday\n        | tuesday\n        | wednesday\n        | thursday\n        | friday\n        | saturday\n        | sunday.\n\t\t\n    (** The new type is called [day], and its members are [monday],\n        [tuesday], etc.\n\t\t\n        Having defined [day], we can write functions that operate on\n        days. *)\n\t\t\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\t\t\n    (** One point to note is that the argument and return types of\n        this function are explicitly declared.  Like most functional\n        programming languages, Coq can often figure out these types for\n        itself when they are not given explicitly -- i.e., it can do _type\n        inference_ -- but we'll generally include them to make reading\n        easier. *)\n\t\t\n    (** Having defined a function, we should next check that it\n        works on some examples.  There are actually three different ways\n        to do the examples in Coq.  First, we can use the command\n        [Compute] to evaluate a compound expression involving\n        [next_weekday]. *)\n\t\t\n    Compute (next_weekday friday).\n    (* ==> monday : day *)\n\t\t\n    Compute (next_weekday (next_weekday saturday)).\n    (* ==> tuesday : day *)\n\t\t\n    (** (We show Coq's responses in comments, but, if you have a\n        computer handy, this would be an excellent moment to fire up the\n        Coq interpreter under your favorite IDE -- either CoqIde or Proof\n        General -- and try it for yourself.  Load this file, [Basics.v],\n        from the book's Coq sources, find the above example, submit it to\n        Coq, and observe the result.) *)\n\t\t\n    (** Second, we can record what we _expect_ the result to be in the\n        form of a Coq example: *)\n\t\t\n    Example test_next_weekday:\n        (next_weekday (next_weekday saturday)) = tuesday.\n\t\t\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\t\t\n    Proof. simpl. reflexivity.  Qed.\n\t\t\n    (** The details are not important just now, but essentially this\n        can be read as \"The assertion we've just made can be proved by\n        observing that both sides of the equality evaluate to the same\n        thing.\"\n\t\t\n        Third, we can ask Coq to _extract_, from our [Definition], a\n        program in another, more conventional, programming\n        language (OCaml, Scheme, or Haskell) with a high-performance\n        compiler.  This facility is very interesting, since it gives us a\n        path from proved-correct algorithms written in Gallina to\n        efficient machine code.  (Of course, we are trusting the\n        correctness of the OCaml/Haskell/Scheme compiler, and of Coq's\n        extraction facility itself, but this is still a big step forward\n        from the way most software is developed today.) Indeed, this is\n        one of the main uses for which Coq was developed.  We'll come back\n        to this topic in later chapters. *)\n\t\t\n    (* ================================================================= *)\n    (** ** Homework Submission Guidelines *)\n\t\t\n    (** If you are using _Software Foundations_ in a course, your\n        instructor may use automatic scripts to help grade your homework\n        assignments.  In order for these scripts to work correctly (and\n        give you that you get full credit for your work!), please be\n        careful to follow these rules:\n            - Do not change the names of exercises. Otherwise the grading\n              scripts will be unable to find your solution.\n            - Do not delete exercises.  If you skip an exercise (e.g.,\n              because it is marked \"optional,\" or because you can't solve it),\n              it is OK to leave a partial proof in your [.v] file; in\n              this case, please make sure it ends with [Admitted] (not, for\n              example [Abort]).\n            - It is fine to use additional definitions (of helper functions,\n              useful lemmas, etc.) in your solutions.  You can put these\n              before the theorem you are asked to prove.\n            - If you introduce a helper lemma that you end up being unable\n              to prove, hence end it with [Admitted], then make sure to also\n              end the main theorem in which you use it with [Admitted], not\n              [Qed].  That will help you get partial credit, in case you\n              use that main theorem to solve a later exercise.\n\t\t\n        You will also notice that each chapter (like [Basics.v]) is\n        accompanied by a _test script_ ([BasicsTest.v]) that automatically\n        calculates points for the finished homework problems in the\n        chapter.  These scripts are mostly for the auto-grading\n        tools, but you may also want to use them to double-check\n        that your file is well formatted before handing it in.  In a\n        terminal window, either type \"[make BasicsTest.vo]\" or do the\n        following:\n\t\t\n             coqc -Q . LF Basics.v\n             coqc -Q . LF BasicsTest.v\n\t\t\n        See the end of this chapter for more information about how to interpret\n        the output of test scripts.\n\t\t\n        There is no need to hand in [BasicsTest.v] itself (or [Preface.v]).\n\t\t\n        If your class is using the Canvas system to hand in assignments...\n            - If you submit multiple versions of the assignment, you may\n              notice that they are given different names.  This is fine: The\n              most recent submission is the one that will be graded.\n            - To hand in multiple files at the same time (if more than one\n              chapter is assigned in the same week), you need to make a\n              single submission with all the files at once using the button\n              \"Add another file\" just above the comment box. *)\n\t\t\n    (** The [Require Export] statement on the next line tells Coq to use\n        the [String] module from the standard library.  We'll use strings\n        ourselves in later chapters, but we need to [Require] it here so\n        that the grading scripts can use it for internal purposes. *)\n    From Coq Require Export String.\n\t\t\n    (* ================================================================= *)\n    (** ** Booleans *)\n\t\t\n    (** Following the pattern of the days of the week above, we can\n        define the standard type [bool] of booleans, with members [true]\n        and [false]. *)\n\t\t\n    Inductive bool : Type :=\n        | true\n        | false.\n\t\t\n    (** Functions over booleans can be defined in the same way as\n        above: *)\n\t\t\n    Definition negb (b:bool) : bool :=\n        match b with\n        | true => false\n        | false => true\n        end.\n\t\t\n    Definition andb (b1:bool) (b2:bool) : bool :=\n        match b1 with\n        | true => b2\n        | false => false\n        end.\n\t\t\n    Definition orb (b1:bool) (b2:bool) : bool :=\n        match b1 with\n        | true => true\n        | false => b2\n        end.\n\t\t\n    (** (Although we are rolling our own booleans here for the sake\n        of building up everything from scratch, Coq does, of course,\n        provide a default implementation of the booleans, together with a\n        multitude of useful functions and lemmas.  Whenever possible,\n        we'll name our own definitions and theorems so that they exactly\n        coincide with the ones in the standard library.) *)\n\t\t\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\t\t\n    Example test_orb1:  (orb true  false) = true.\n    Proof. simpl. reflexivity.  Qed.\n    Example test_orb2:  (orb false false) = false.\n    Proof. simpl. reflexivity.  Qed.\n    Example test_orb3:  (orb false true)  = true.\n    Proof. simpl. reflexivity.  Qed.\n    Example test_orb4:  (orb true  true)  = true.\n    Proof. simpl. reflexivity.  Qed.\n\t\t\n    (** We can also introduce some familiar infix syntax for the\n        boolean operations we have just defined. The [Notation] command\n        defines a new symbolic notation for an existing definition. *)\n\t\t\n    Notation \"x && y\" := (andb x y).\n    Notation \"x || y\" := (orb x y).\n\t\t\n    Example test_orb5:  false || false || true = true.\n    Proof. simpl. reflexivity. Qed.\n\t\t\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\t\t\n    (** These examples are also an opportunity to introduce one more small\n        feature of Coq's programming language: conditional expressions... *)\n\t\t\n    Definition negb' (b:bool) : bool :=\n        if b then false\n        else true.\n\t\t\n    Definition andb' (b1:bool) (b2:bool) : bool :=\n        if b1 then b2\n        else false.\n\t\t\n    Definition orb' (b1:bool) (b2:bool) : bool :=\n        if b1 then true\n        else b2.\n\t\t\n    (** Coq's conditionals are exactly like those found in any other\n        language, with one small generalization.  Since the [bool] type is\n        not built in, Coq actually supports conditional expressions over\n        _any_ inductively defined type with exactly two clauses in its\n        definition.  The guard is considered true if it evaluates to the\n        \"constructor\" of the first clause of the [Inductive]\n        definition (which just happens to be called [true] in this case)\n        and false if it evaluates to the second. *)\n\t\t\n    (** **** Exercise: 1 star, standard (nandb)\n\t\t\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\t\t\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\t\t\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\t\t\n    Definition nandb (b1:bool) (b2:bool) : bool\n    :=\n    orb (negb b1) (negb b2).\n\t\t\n    Example test_nandb1:               (nandb true false) = true.\n    (* FILL IN HERE *) Proof. simpl. reflexivity. Qed.\n    Example test_nandb2:               (nandb false false) = true.\n    (* FILL IN HERE *) Proof. simpl. reflexivity. Qed.\n    Example test_nandb3:               (nandb false true) = true.\n    (* FILL IN HERE *) Proof. simpl. reflexivity. Qed.\n    Example test_nandb4:               (nandb true true) = false.\n    (* FILL IN HERE *) Proof. simpl. reflexivity. Qed.\n    (** [] *)\n\t\t\n    (** **** Exercise: 1 star, standard (andb3)\n\t\t\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\t\t\n    Definition andb3 (b1:bool) (b2:bool) (b3:bool) : bool\n    := (andb b1 (andb b2 b3)).\n\t\t\n    Example test_andb31:                 (andb3 true true true) = true.\n    Proof. simpl. reflexivity. Qed.\n    Example test_andb32:                 (andb3 false true true) = false.\n    Proof. simpl. reflexivity. Qed.\n    Example test_andb33:                 (andb3 true false true) = false.\n    Proof. simpl. reflexivity. Qed.\n    Example test_andb34:                 (andb3 true true false) = false.\n    Proof. simpl. reflexivity. Qed.\n    (** [] *)\n\t\t\n    (* ================================================================= *)\n    (** ** Types *)\n\t\t\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\t\t\n    Check true.\n    (* ===> true : bool *)\n\t\t\n    (** If the expression after [Check] is followed by a colon and a type,\n        Coq will verify that the type of the expression matches the given\n        type and halt with an error if not. *)\n\t\t\n    Check true\n        : bool.\n    Check (negb true)\n        : bool.\n\t\t\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\t\t\n    Check negb\n        : bool -> bool.\n\t\t\n    (** The type of [negb], written [bool -> bool] and pronounced\n        \"[bool] arrow [bool],\" can be read, \"Given an input of type\n        [bool], this function produces an output of type [bool].\"\n        Similarly, the type of [andb], written [bool -> bool -> bool], can\n        be read, \"Given two inputs, each of type [bool], this function\n        produces an output of type [bool].\" *)\n\t\t\n    (* ================================================================= *)\n    (** ** New Types from Old *)\n\t\t\n    (** The types we have defined so far are examples of \"enumerated\n        types\": their definitions explicitly enumerate a finite set of\n        elements, called _constructors_.  Here is a more interesting type\n        definition, where one of the constructors takes an argument: *)\n\t\t\n    Inductive rgb : Type :=\n        | red\n        | green\n        | blue.\n\t\t\n    Inductive color : Type :=\n        | black\n        | white\n        | primary (p : rgb).\n\t\t\n    (** Let's look at this in a little more detail.\n\t\t\n        An [Inductive] definition does two things:\n\t\t\n        - It defines a set of new _constructors_. E.g., [red],\n            [primary], [true], [false], [monday], etc. are constructors.\n\t\t\n        - It groups them into a new named type, like [bool], [rgb], or\n            [color].\n\t\t\n        _Constructor expressions_ are formed by applying a constructor\n        to zero or more other constructors or constructor expressions,\n        obeying the declared number and types of the constructor arguments.\n        E.g.,\n              - [red]\n              - [true]\n              - [primary red]\n              - etc.\n        But not\n              - [red primary]\n              - [true red]\n              - [primary (primary red)]\n              - etc.\n    *)\n\t\t\n    (** In particular, the definitions of [rgb] and [color] say\n        which constructor expressions belong to the sets [rgb] and\n        [color]:\n\t\t\n        - [red], [green], and [blue] belong to the set [rgb];\n        - [black] and [white] belong to the set [color];\n        - if [p] is a constructor expression belonging to the set [rgb],\n            then [primary p] (pronounced \"the constructor [primary] applied\n            to the argument [p]\") is a constructor expression belonging to\n            the set [color]; and\n        - constructor expressions formed in these ways are the _only_ ones\n            belonging to the sets [rgb] and [color]. *)\n\t\t\n    (** We can define functions on colors using pattern matching just as\n        we did for [day] and [bool]. *)\n\t\t\n    Definition monochrome (c : color) : bool :=\n        match c with\n        | black => true\n        | white => true\n        | primary p => false\n        end.\n\t\t\n    (** Since the [primary] constructor takes an argument, a pattern\n        matching [primary] should include either a variable (as above --\n        note that we can choose its name freely) or a constant of\n        appropriate type (as below). *)\n\t\t\n    Definition isred (c : color) : bool :=\n        match c with\n        | black => false\n        | white => false\n        | primary red => true\n        | primary _ => false\n        end.\n\t\t\n    (** The pattern \"[primary _]\" here is shorthand for \"the constructor\n        [primary] applied to any [rgb] constructor except [red].\"  (The\n        wildcard pattern [_] has the same effect as the dummy pattern\n        variable [p] in the definition of [monochrome].) *)\n\t\t\n    (* ================================================================= *)\n    (** ** Modules *)\n\t\t\n    (** Coq provides a _module system_ to aid in organizing large\n        developments.  We won't need most of its features,\n        but one is useful: If we enclose a collection of declarations\n        between [Module X] and [End X] markers, then, in the remainder of\n        the file after the [End], these definitions are referred to by\n        names like [X.foo] instead of just [foo].  We will use this\n        feature to limit the scope of definitions, so that we are free to\n        reuse names. *)\n\t\t\n    Module Playground.\n        Definition b : rgb := blue.\n    End Playground.\n\t\t\n    Definition b : bool := true.\n\t\t\n    Check Playground.b : rgb.\n    Check b : bool.\n\t\t\n    (* ================================================================= *)\n    (** ** Tuples *)\n\t\t\n    Module TuplePlayground.\n\t\t\n    (** A single constructor with multiple parameters can be used\n        to create a tuple type. As an example, consider representing\n        the four bits in a nybble (half a byte). We first define\n        a datatype [bit] that resembles [bool] (using the\n        constructors [B0] and [B1] for the two possible bit values)\n        and then define the datatype [nybble], which is essentially\n        a tuple of four bits. *)\n\t\t\n    Inductive bit : Type :=\n        | B0\n        | B1.\n\t\t\n    Inductive nybble : Type :=\n        | bits (b0 b1 b2 b3 : bit).\n\t\t\n    Check (bits B1 B0 B1 B0)\n        : nybble.\n\t\t\n    (** The [bits] constructor acts as a wrapper for its contents.\n        Unwrapping can be done by pattern-matching, as in the [all_zero]\n        function which tests a nybble to see if all its bits are [B0].  We\n        use underscore (_) as a _wildcard pattern_ to avoid inventing\n        variable names that will not be used. *)\n\t\t\n    Definition all_zero (nb : nybble) : bool :=\n        match nb with\n        | (bits B0 B0 B0 B0) => true\n        | (bits _ _ _ _) => false\n        end.\n\t\t\n    Compute (all_zero (bits B1 B0 B1 B0)).\n    (* ===> false : bool *)\n    Compute (all_zero (bits B0 B0 B0 B0)).\n    (* ===> true : bool *)\n\t\t\n    End TuplePlayground.\n\t\t\n    (* ================================================================= *)\n    (** ** Numbers *)\n\t\t\n    (** We put this section in a module so that our own definition of\n        natural numbers does not interfere with the one from the\n        standard library.  In the rest of the book, we'll want to use\n        the standard library's. *)\n\t\t\n    Module NatPlayground.\n\t\t\n    (** All the types we have defined so far -- both \"enumerated\n        types\" such as [day], [bool], and [bit] and tuple types such as\n        [nybble] built from them -- are finite.  The natural numbers, on\n        the other hand, are an infinite set, so we'll need to use a\n        slightly richer form of type declaration to represent them.\n\t\t\n        There are many representations of numbers to choose from. We are\n        most familiar with decimal notation (base 10), using the digits 0\n        through 9, for example, to form the number 123.  You may have\n        encountered hexadecimal notation (base 16), in which the same\n        number is represented as 7B, or octal (base 8), where it is 173,\n        or binary (base 2), where it is 1111011. Using an enumerated type\n        to represent digits, we could use any of these as our\n        representation natural numbers. Indeed, there are circumstances\n        where each of these choices would be useful.\n\t\t\n        The binary representation is valuable in computer hardware because\n        the digits can be represented with just two distinct voltage\n        levels, resulting in simple circuitry. Analogously, we wish here\n        to choose a representation that makes _proofs_ simpler.\n\t\t\n        In fact, there is a representation of numbers that is even simpler\n        than binary, namely unary (base 1), in which only a single digit\n        is used (as our ancient forebears might have done to count days by\n        making scratches on the walls of their caves). To represent unary\n        numbers with a Coq datatype, we use two constructors. The\n        capital-letter [O] constructor represents zero.  When the [S]\n        constructor is applied to the representation of the natural number\n        n, the result is the representation of n+1, where [S] stands for\n        \"successor\" (or \"scratch\").  Here is the complete datatype\n        definition. *)\n\t\t\n    Inductive nat : Type :=\n        | O\n        | S (n : nat).\n\t\t\n    (** With this definition, 0 is represented by [O], 1 by [S O],\n        2 by [S (S O)], and so on. *)\n\t\t\n    (** Informally, the clauses of the definition can be read:\n            - [O] is a natural number (remember this is the letter \"[O],\"\n              not the numeral \"[0]\").\n            - [S] can be put in front of a natural number to yield another\n              one -- if [n] is a natural number, then [S n] is too. *)\n\t\t\n    (** Again, let's look at this in a little more detail.  The definition\n        of [nat] says how expressions in the set [nat] can be built:\n\t\t\n        - the constructor expression [O] belongs to the set [nat];\n        - if [n] is a constructor expression belonging to the set [nat],\n            then [S n] is also a constructor expression belonging to the set\n            [nat]; and\n        - constructor expressions formed in these two ways are the only\n            ones belonging to the set [nat]. *)\n\t\t\n    (** These conditions are the precise force of the [Inductive]\n        declaration.  They imply that the constructor expression [O], the\n        constructor expression [S O], the constructor expression [S (S\n        O)], the constructor expression [S (S (S O))], and so on all\n        belong to the set [nat], while other constructor expressions, like\n        [true], [andb true false], [S (S false)], and [O (O (O S))] do\n        not.\n\t\t\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\t\t\n    Inductive nat' : Type :=\n        | stop\n        | tick (foo : nat').\n\t\t\n    (** The _interpretation_ of these marks comes from how we use them to\n        compute. *)\n\t\t\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\t\t\n    Definition pred (n : nat) : nat :=\n        match n with\n        | O => O\n        | S n' => n'\n        end.\n\t\t\n    (** The second branch can be read: \"if [n] has the form [S n']\n        for some [n'], then return [n'].\"  *)\n\t\t\n    (** The following [End] command closes the current module, so\n        [nat] will refer back to the type from the standard library. *)\n\t\t\n    End NatPlayground.\n\t\t\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\t\t\n    Check (S (S (S (S O)))).\n    (* ===> 4 : nat *)\n\t\t\n    Definition minustwo (n : nat) : nat :=\n        match n with\n        | O => O\n        | S O => O\n        | S (S n') => n'\n        end.\n\t\t\n    Compute (minustwo 4).\n    (* ===> 2 : nat *)\n\t\t\n    (** The constructor [S] has the type [nat -> nat], just like functions\n        such as [pred] and [minustwo]: *)\n\t\t\n    Check S        : nat -> nat.\n    Check pred     : nat -> nat.\n    Check minustwo : nat -> nat.\n\t\t\n    (** These are all things that can be applied to a number to yield a\n        number.  However, there is a fundamental difference between [S]\n        and the other two: functions like [pred] and [minustwo] are\n        defined by giving _computation rules_ -- e.g., the definition of\n        [pred] says that [pred 2] can be simplified to [1] -- while the\n        definition of [S] has no such behavior attached.  Although it is\n        _like_ a function in the sense that it can be applied to an\n        argument, it does not _do_ anything at all!  It is just a way of\n        writing down numbers.\n\t\t\n        (Think about standard decimal numerals: the numeral [1] is not a\n        computation; it's a piece of data.  When we write [111] to mean\n        the number one hundred and eleven, we are using [1], three times,\n        to write down a concrete representation of a number.)\n\t\t\n        Now let's go on and define some more functions over numbers.\n\t\t\n        For most interesting computations involving numbers, simple\n        pattern matching is not enough: we also need recursion.  For\n        example, to check that a number [n] is even, we may need to\n        recursively check whether [n-2] is even.  Such functions are\n        introduced with the keyword [Fixpoint] instead of [Definition]. *)\n\t\t\n    Fixpoint even (n:nat) : bool :=\n        match n with\n        | O        => true\n        | S O      => false\n        | S (S n') => even n'\n        end.\n\t\t\n    (** We could define [odd] by a similar [Fixpoint] declaration, but\n        here is a simpler way: *)\n\t\t\n    Definition odd (n:nat) : bool :=\n        negb (even n).\n\t\t\n    Example test_odd1:    odd 1 = true.\n    Proof. simpl. reflexivity.  Qed.\n    Example test_odd2:    odd 4 = false.\n    Proof. simpl. reflexivity.  Qed.\n\t\t\n    (** (You may notice if you step through these proofs that\n        [simpl] actually has no effect on the goal -- all of the work is\n        done by [reflexivity].  We'll discuss why that is shortly.)\n\t\t\n        Naturally, we can also define multi-argument functions by\n        recursion.  *)\n\t\t\n    Module NatPlayground2.\n\t\t\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\t\t\n    (** Adding three to two now gives us five, as we'd expect. *)\n\t\t\n    Compute (plus 3 2).\n    (* ===> 5 : nat *)\n\t\t\n    (** The steps of simplification that Coq performs can be\n        visualized as follows: *)\n\t\t\n    (*      [plus 3 2]\n         i.e. [plus (S (S (S O))) (S (S O))]\n        ==> [S (plus (S (S O)) (S (S O)))]\n                by the second clause of the [match]\n        ==> [S (S (plus (S O) (S (S O))))]\n                by the second clause of the [match]\n        ==> [S (S (S (plus O (S (S O)))))]\n                by the second clause of the [match]\n        ==> [S (S (S (S (S O))))]\n                by the first clause of the [match]\n         i.e. [5]  *)\n\t\t\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\t\t\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\t\t\n    Example test_mult1: (mult 3 3) = 9.\n    Proof. simpl. reflexivity.  Qed.\n\t\t\n    (** You can match two expressions at once by putting a comma\n        between them: *)\n\t\t\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\t\t\n    End NatPlayground2.\n\t\t\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\t\t\n    (** **** Exercise: 1 star, standard (factorial)\n\t\t\n        Recall the standard mathematical factorial function:\n\t\t\n             factorial(0)  =  1\n             factorial(n)  =  n * factorial(n-1)     (if n>0)\n\t\t\n        Translate this into Coq.\n\t\t\n        Make sure you put a [:=] between the header we've given you and\n        your definition.  If you see an error like \"The reference\n        factorial was not found in the current environment,\" it means\n        you've forgotten the [:=]. *)\n\t\t\n    Fixpoint factorial (n:nat) : nat\n        := \n        match n with \n        | S n' => mult n (factorial n')\n        | O => 1\n        end.\n\t\t\n    Example test_factorial1:          (factorial 3) = 6.\n    (* FILL IN HERE *) Proof. simpl. reflexivity. Qed.\n    Example test_factorial2:          (factorial 5) = (mult 10 12).\n    (* FILL IN HERE *) Proof. simpl. reflexivity. Qed.\n    (** [] *)\n\t\t\n    (** Again, we can make numerical expressions easier to read and write\n        by introducing notations for addition, multiplication, and\n        subtraction. *)\n\t\t\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\t\t\n    Check ((0 + 1) + 1) : nat.\n\t\t\n    (** (The [level], [associativity], and [nat_scope] annotations\n        control how these notations are treated by Coq's parser.  The\n        details are not important for present purposes, but interested\n        readers can refer to the \"More on Notation\" section at the end of\n        this chapter.)\n\t\t\n        Note that these declarations do not change the definitions we've\n        already made: they are simply instructions to the Coq parser to\n        accept [x + y] in place of [plus x y] and, conversely, to the Coq\n        pretty-printer to display [plus x y] as [x + y]. *)\n\t\t\n    (** When we say that Coq comes with almost nothing built-in, we really\n        mean it: even equality testing is a user-defined operation!\n        Here is a function [eqb], which tests natural numbers for\n        [eq]uality, yielding a [b]oolean.  Note the use of nested\n        [match]es (we could also have used a simultaneous match, as we did\n        in [minus].) *)\n\t\t\n    Fixpoint 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\t\t\n    (** Similarly, the [leb] function tests whether its first argument is\n        less than or equal to its second argument, yielding a boolean. *)\n\t\t\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\t\t\n    Example test_leb1:                leb 2 2 = true.\n    Proof. simpl. reflexivity.  Qed.\n    Example test_leb2:                leb 2 4 = true.\n    Proof. simpl. reflexivity.  Qed.\n    Example test_leb3:                leb 4 2 = false.\n    Proof. simpl. reflexivity.  Qed.\n\t\t\n    (** We'll be using these (especially [eqb]) a lot, so let's give\n        them infix notations. *)\n\t\t\n    Notation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\n    Notation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\t\t\n    Example test_leb3': (4 <=? 2) = false.\n    Proof. simpl. reflexivity.  Qed.\n\t\t\n    (** We now have two symbols that look like equality: [=] and\n        [=?].  We'll have much more to say about the differences and\n        similarities between them later. For now, the main thing to notice\n        is that [x = y] is a logical _claim_ -- a \"proposition\" -- that we\n        can try to prove, while [x =? y] is an _expression_ whose\n        value (either [true] or [false]) we can compute. *)\n\t\t\n    (** **** Exercise: 1 star, standard (ltb)\n\t\t\n        The [ltb] function tests natural numbers for [l]ess-[t]han,\n        yielding a [b]oolean.  Instead of making up a new [Fixpoint] for\n        this one, define it in terms of a previously defined\n        function.  (It can be done with just one previously defined\n        function, but you can use two if you want.) *)\n\t\t\n    Definition ltb (n m : nat) : bool\n    := ((leb n m) && (negb (eqb n m))).\n\t\t\n    Notation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\t\t\n    Example test_ltb1:             (ltb 2 2) = false.\n    Proof. simpl. reflexivity. Qed.\n    Example test_ltb2:             (ltb 2 4) = true.\n    Proof. simpl. reflexivity. Qed.\n    Example test_ltb3:             (ltb 4 2) = false.\n    Proof. simpl. reflexivity. Qed.\n    (** [] *)\n\t\t\n    (* ################################################################# *)\n    (** * Proof by Simplification *)\n\t\t\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\t\t\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\t\t\n    Theorem plus_O_n : forall n : nat, 0 + n = n.\n    Proof.\n        intros n. simpl. reflexivity.  Qed.\n\t\t\n    (** (You may notice that the above statement looks different in\n        the [.v] file in your IDE than it does in the HTML rendition in\n        your browser. In [.v] files, we write the universal quantifier\n        [forall] using the reserved identifier \"forall.\"  When the [.v]\n        files are converted to HTML, this gets transformed into the\n        standard upside-down-A symbol.)\n\t\t\n        This is a good place to mention that [reflexivity] is a bit more\n        powerful than we have acknowledged. In the examples we have seen,\n        the calls to [simpl] were actually not needed, because\n        [reflexivity] can perform some simplification automatically when\n        checking that two sides are equal; [simpl] was just added so that\n        we could see the intermediate state -- after simplification but\n        before finishing the proof.  Here is a shorter proof of the\n        theorem: *)\n\t\t\n    Theorem plus_O_n' : forall n : nat, 0 + n = n.\n    Proof.\n        intros n. reflexivity. Qed.\n\t\t\n    (** Moreover, it will be useful to know that [reflexivity] does\n        somewhat _more_ simplification than [simpl] does -- for example,\n        it tries \"unfolding\" defined terms, replacing them with their\n        right-hand sides.  The reason for this difference is that, if\n        reflexivity succeeds, the whole goal is finished and we don't need\n        to look at whatever expanded expressions [reflexivity] has created\n        by all this simplification and unfolding; by contrast, [simpl] is\n        used in situations where we may have to read and understand the\n        new goal that it creates, so we would not want it blindly\n        expanding definitions and leaving the goal in a messy state.\n\t\t\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\t\t\n        First, we've used the keyword [Theorem] instead of [Example].\n        This difference is mostly a matter of style; the keywords\n        [Example] and [Theorem] (and a few others, including [Lemma],\n        [Fact], and [Remark]) mean pretty much the same thing to Coq.\n\t\t\n        Second, we've added the quantifier [forall n:nat], so that our\n        theorem talks about _all_ natural numbers [n].  Informally, to\n        prove theorems of this form, we generally start by saying \"Suppose\n        [n] is some number...\"  Formally, this is achieved in the proof by\n        [intros n], which moves [n] from the quantifier in the goal to a\n        _context_ of current assumptions. Note that we could have used\n        another identifier instead of [n] in the [intros] clause, (though\n        of course this might be confusing to human readers of the proof): *)\n\t\t\n    Theorem plus_O_n'' : forall n : nat, 0 + n = n.\n    Proof.\n        intros m. reflexivity. Qed.\n\t\t\n    (** The keywords [intros], [simpl], and [reflexivity] are examples of\n        _tactics_.  A tactic is a command that is used between [Proof] and\n        [Qed] to guide the process of checking some claim we are making.\n        We will see several more tactics in the rest of this chapter and\n        many more in future chapters. *)\n\t\t\n    (** Other similar theorems can be proved with the same pattern. *)\n\t\t\n    Theorem plus_1_l : forall n:nat, 1 + n = S n.\n    Proof.\n        intros n. reflexivity.  Qed.\n\t\t\n    Theorem mult_0_l : forall n:nat, 0 * n = 0.\n    Proof.\n        intros n. reflexivity.  Qed.\n\t\t\n    (** The [_l] suffix in the names of these theorems is\n        pronounced \"on the left.\" *)\n\t\t\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\t\t\n    (* ################################################################# *)\n    (** * Proof by Rewriting *)\n\t\t\n    (** The following theorem is a bit more interesting than the\n        ones we've seen: *)\n\t\t\n    Theorem plus_id_example : forall n m:nat,\n        n = m ->\n        n + n = m + m.\n\t\t\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\t\t\n        As before, we need to be able to reason by assuming we are given such\n        numbers [n] and [m].  We also need to assume the hypothesis\n        [n = m]. The [intros] tactic will serve to move all three of these\n        from the goal into assumptions in the current context.\n\t\t\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\t\t\n    Proof.\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\t\t\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\t\t\n        (The arrow symbol in the [rewrite] has nothing to do with\n        implication: it tells Coq to apply the rewrite from left to right.\n        In fact, you can omit the arrow, and Coq will default to rewriting\n        in this direction.  To rewrite from right to left, you can use\n        [rewrite <-].  Try making this change in the above proof and see\n        what difference it makes.) *)\n\t\t\n    (** **** Exercise: 1 star, standard (plus_id_exercise)\n\t\t\n        Remove \"[Admitted.]\" and fill in the proof. *)\n\t\t\n    Theorem plus_id_exercise : forall n m o : nat,\n        n = m -> m = o -> n + m = m + o.\n            Proof.\n            intros n m o.\n            intros H1 H2.\n            rewrite -> H1.\n            rewrite <- H2.\n            reflexivity.\n        Qed.\n\t\t\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\t\t\n    (** The [Check] command can also be used to examine the statements of\n        previously declared lemmas and theorems.  The two examples below\n        are lemmas about multiplication that are proved in the standard\n        library.  (We will see how to prove them ourselves in the next\n        chapter.) *)\n\t\t\n    Check mult_n_O.\n    (* ===> forall n : nat, 0 = n * 0 *)\n\t\t\n    Check mult_n_Sm.\n    (* ===> forall n m : nat, n * m + n = n * S m *)\n\t\t\n    (** We can use the [rewrite] tactic with a previously proved theorem\n        instead of a hypothesis from the context. If the statement of the\n        previously proved theorem involves quantified variables, as in the\n        example below, Coq tries to instantiate them by matching with the\n        current goal. *)\n\t\t\n    Theorem mult_n_0_m_0 : forall p q : nat,\n        (p * 0) + (q * 0) = 0.\n    Proof.\n        intros p q.\n        rewrite <- mult_n_O.\n        rewrite <- mult_n_O.\n        reflexivity. Qed.\n\t\t\n    (** **** Exercise: 1 star, standard (mult_n_1)\n\t\t\n        Use those two lemmas about multiplication that we just checked to\n        prove the following theorem.  Hint: recall that [1] is [S O]. *)\n\t\t\n    Theorem mult_n_1 : forall p : nat,\n        p * 1 = p.\n    Proof.\n        intros p.\n        rewrite  <- mult_n_Sm.\n        rewrite <- mult_n_O.\n        simpl.\n        reflexivity.\n\tQed.\n    (** [] *)\n\t\t\n    (* ################################################################# *)\n    (** * Proof by Case Analysis *)\n\t\t\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\t\t\n    Theorem plus_1_neq_0_firsttry : forall n : nat,\n        (n + 1) =? 0 = false.\n    Proof.\n        intros n.\n        simpl.  (* does nothing! *)\n    Abort.\n\t\t\n    (** The reason for this is that the definitions of both [eqb]\n        and [+] begin by performing a [match] on their first argument.\n        But here, the first argument to [+] is the unknown number [n] and\n        the argument to [eqb] is the compound expression [n + 1]; neither\n        can be simplified.\n\t\t\n        To make progress, we need to consider the possible forms of [n]\n        separately.  If [n] is [O], then we can calculate the final result\n        of [(n + 1) =? 0] and check that it is, indeed, [false].  And if\n        [n = S n'] for some [n'], then, although we don't know exactly\n        what number [n + 1] represents, we can calculate that, at least,\n        it will begin with one [S], and this is enough to calculate that,\n        again, [(n + 1) =? 0] will yield [false].\n\t\t\n        The tactic that tells Coq to consider, separately, the cases where\n        [n = O] and where [n = S n'] is called [destruct]. *)\n\t\t\n    Theorem plus_1_neq_0 : forall n : nat,\n        (n + 1) =? 0 = false.\n    Proof.\n        intros n. destruct n as [| n'] eqn:E.\n        - reflexivity.\n        - reflexivity.   Qed.\n\t\t\n    (** The [destruct] generates _two_ subgoals, which we must then\n        prove, separately, in order to get Coq to accept the theorem.\n\t\t\n        The annotation \"[as [| n']]\" is called an _intro pattern_.  It\n        tells Coq what variable names to introduce in each subgoal.  In\n        general, what goes between the square brackets is a _list of\n        lists_ of names, separated by [|].  In this case, the first\n        component is empty, since the [O] constructor is nullary (it\n        doesn't have any arguments).  The second component gives a single\n        name, [n'], since [S] is a unary constructor.\n\t\t\n        In each subgoal, Coq remembers the assumption about [n] that is\n        relevant for this subgoal -- either [n = 0] or [n = S n'] for some\n        n'.  The [eqn:E] annotation tells [destruct] to give the name [E]\n        to this equation.  Leaving off the [eqn:E] annotation causes Coq\n        to elide these assumptions in the subgoals.  This slightly\n        streamlines proofs where the assumptions are not explicitly used,\n        but it is better practice to keep them for the sake of\n        documentation, as they can help keep you oriented when working\n        with the subgoals.\n\t\t\n        The [-] signs on the second and third lines are called _bullets_,\n        and they mark the parts of the proof that correspond to the two\n        generated subgoals.  The part of the proof script that comes after\n        a bullet is the entire proof for the corresponding subgoal.  In\n        this example, each of the subgoals is easily proved by a single\n        use of [reflexivity], which itself performs some simplification --\n        e.g., the second one simplifies [(S n' + 1) =? 0] to [false] by\n        first rewriting [(S n' + 1)] to [S (n' + 1)], then unfolding\n        [eqb], and then simplifying the [match].\n\t\t\n        Marking cases with bullets is optional: if bullets are not\n        present, Coq simply asks you to prove each subgoal in sequence,\n        one at a time. But it is a good idea to use bullets.  For one\n        thing, they make the structure of a proof apparent, improving\n        readability. Also, bullets instruct Coq to ensure that a subgoal\n        is complete before trying to verify the next one, preventing\n        proofs for different subgoals from getting mixed up. These issues\n        become especially important in large developments, where fragile\n        proofs lead to long debugging sessions.\n\t\t\n        There are no hard and fast rules for how proofs should be\n        formatted in Coq -- e.g., where lines should be broken and how\n        sections of the proof should be indented to indicate their nested\n        structure.  However, if the places where multiple subgoals are\n        generated are marked with explicit bullets at the beginning of\n        lines, then the proof will be readable almost no matter what\n        choices are made about other aspects of layout.\n\t\t\n        This is also a good place to mention one other piece of somewhat\n        obvious advice about line lengths.  Beginning Coq users sometimes\n        tend to the extremes, either writing each tactic on its own line\n        or writing entire proofs on a single line.  Good style lies\n        somewhere in the middle.  One reasonable guideline is to limit\n        yourself to 80-character lines.\n\t\t\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\t\t\n    Theorem negb_involutive : forall b : bool,\n        negb (negb b) = b.\n    Proof.\n        intros b. destruct b eqn:E.\n        - reflexivity.\n        - reflexivity.  Qed.\n\t\t\n    (** Note that the [destruct] here has no [as] clause because\n        none of the subcases of the [destruct] need to bind any variables,\n        so there is no need to specify any names.  In fact, we can omit\n        the [as] clause from _any_ [destruct] and Coq will fill in\n        variable names automatically.  This is generally considered bad\n        style, since Coq often makes confusing choices of names when left\n        to its own devices.\n\t\t\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\t\t\n    Theorem andb_commutative : forall b c, andb b c = andb c b.\n    Proof.\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.\n    Qed.\n\t\t\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\t\t\n    (** Besides [-] and [+], we can use [*] (asterisk) or any repetition\n        of a bullet symbol (e.g. [--] or [***]) as a bullet.  We can also\n        enclose sub-proofs in curly braces: *)\n\t\t\n    Theorem andb_commutative' : forall b c, andb b c = andb c b.\n    Proof.\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. } }\n    Qed.\n\t\t\n    (** Since curly braces mark both the beginning and the end of a proof,\n        they can be used for multiple subgoal levels, as this example\n        shows. Furthermore, curly braces allow us to reuse the same bullet\n        shapes at multiple levels in a proof. The choice of braces,\n        bullets, or a combination of the two is purely a matter of\n        taste. *)\n\t\t\n    Theorem andb3_exchange :\n        forall b c d, andb (andb b c) d = andb (andb b d) c.\n    Proof.\n        intros b c d. destruct b eqn:Eb.\n        - destruct c eqn:Ec.\n        { destruct d eqn:Ed.\n            - reflexivity.\n            - reflexivity. }\n        { destruct d eqn:Ed.\n            - reflexivity.\n            - reflexivity. }\n        - destruct c eqn:Ec.\n        { destruct d eqn:Ed.\n            - reflexivity.\n            - reflexivity. }\n        { destruct d eqn:Ed.\n            - reflexivity.\n            - reflexivity. }\n    Qed.\n\t\t\n    (** **** Exercise: 2 stars, standard (andb_true_elim2)\n\t\t\n        Prove the following claim, marking cases (and subcases) with\n        bullets when you use [destruct].\n\t\t\n        Hint: You will eventually need to destruct both Booleans, as in\n        the theorems above. But, delay introducing the hypothesis until\n        after you have an opportunity to simplify it.\n\t\t\n        Hint 2: When you reach contradiction in the hypotheses, focus\n        on how to [rewrite] with that contradiction. *)\n\t\t\n    Theorem andb_true_elim2 : forall b c : bool,\n        andb b c = true -> c = true.\n    Proof.\n        intros b c.\n        intros H.\n        destruct b.\n        - destruct c.\n            -- reflexivity.   \n            -- rewrite <- H. reflexivity.\n        - destruct c.\n            -- reflexivity.\n            -- rewrite <- H. reflexivity.\n    Qed.\n\t\t\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\t\t\n             intros x y. destruct y as [|y] eqn:E.\n\t\t\n        This pattern is so common that Coq provides a shorthand for it: we\n        can perform case analysis on a variable when introducing it by\n        using an intro pattern instead of a variable name. For instance,\n        here is a shorter proof of the [plus_1_neq_0] theorem\n        above.  (You'll also note one downside of this shorthand: we lose\n        the equation recording the assumption we are making in each\n        subgoal, which we previously got from the [eqn:E] annotation.) *)\n\t\t\n    Theorem plus_1_neq_0' : forall n : nat,\n        (n + 1) =? 0 = false.\n    Proof.\n        intros [|n].\n        - reflexivity.\n        - reflexivity.  Qed.\n\t\t\n    (** If there are no constructor arguments that need names, we can just\n        write [[]] to get the case analysis. *)\n\t\t\n    Theorem andb_commutative'' :\n        forall b c, andb b c = andb c b.\n    Proof.\n        intros [] [].\n        - reflexivity.\n        - reflexivity.\n        - reflexivity.\n        - reflexivity.\n    Qed.\n\t\t\n    (** **** Exercise: 1 star, standard (zero_nbeq_plus_1) *)\n    Theorem zero_nbeq_plus_1 : forall n : nat,\n        0 =? (n + 1) = false.\n    Proof.\n        intros n.\n        destruct n as [|n'].\n        - reflexivity.\n        - simpl. reflexivity.\n    Qed.\n\t\t\n    (* ================================================================= *)\n    (** ** More on Notation (Optional) *)\n\t\t\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\t\t\n        Recall the notation definitions for infix plus and times: *)\n\t\t\n    Notation \"x + y\" := (plus 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\t\t\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\t\t\n        Each notation symbol is also associated with a _notation scope_.\n        Coq tries to guess what scope is meant from context, so when it\n        sees [S(O*O)] it guesses [nat_scope], but when it sees the product\n        type [bool*bool] (which we'll see in later chapters) it guesses\n        [type_scope].  Occasionally, it is necessary to help it out with\n        percent-notation by writing [(x*y)%nat], and sometimes in what Coq\n        prints it will use [%nat] to indicate what scope a notation is in.\n\t\t\n        Notation scopes also apply to numeral notation ([3], [4], [5], [42],\n        etc.), so you may sometimes see [0%nat], which means [O] (the\n        natural number [0] that we're using in this chapter), or [0%Z],\n        which means the integer zero (which comes from a different part of\n        the standard library).\n\t\t\n        Pro tip: Coq's notation mechanism is not especially powerful.\n        Don't expect too much from it. *)\n\t\t\n    (* ================================================================= *)\n    (** ** Fixpoints and Structural Recursion (Optional) *)\n\t\t\n    (** Here is a copy of the definition of addition: *)\n\t\t\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\t\t\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\t\t\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\t\t\n    (** **** Exercise: 2 stars, standard, optional (decreasing)\n\t\t\n        To get a concrete sense of this, find a way to write a sensible\n        [Fixpoint] definition (of a simple function on numbers, say) that\n        _does_ terminate on all inputs, but that Coq will reject because\n        of this restriction.  (If you choose to turn in this optional\n        exercise as part of a homework assignment, make sure you comment\n        out your solution so that it doesn't cause Coq to reject the whole\n        file!) *)\n\t\t\n    (* FILL IN HERE\n\t\t\n        [] *)\n\t\t\n    (* ################################################################# *)\n    (** * More Exercises *)\n\t\t\n    (** **** Exercise: 1 star, standard (identity_fn_applied_twice)\n\t\t\n        Use the tactics you have learned so far to prove the following\n        theorem about boolean functions. *)\n\t\t\n    Theorem identity_fn_applied_twice :\n        forall (f : bool -> bool),\n        (forall (x : bool), f x = x) ->\n        forall (b : bool), f (f b) = b.\n    Proof.\n        intros.\n        destruct b0 as [|].\n        - rewrite H. rewrite H. reflexivity.\n        - rewrite H. rewrite H. reflexivity.\n    Qed.\n\t\t\n    (** [] *)\n\t\t\n    (** **** Exercise: 1 star, standard (negation_fn_applied_twice)\n\t\t\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\t\t\n    (* FILL IN HERE *)\n\t\t\n    (* Do not modify the following line: *)\n    Definition manual_grade_for_negation_fn_applied_twice : option (nat*string) := None.\n    (** (The last definition is used by the autograder.)\n\t\t\n        [] *)\n\t\t\n    (** **** Exercise: 3 stars, standard, optional (andb_eq_orb)\n\t\t\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\t\t\n    Theorem andb_eq_orb :\n        forall (b c : bool),\n        (andb b c = orb b c) ->\n        b = c.\n    Proof.\n        intros b c.\n        destruct b.\n        - destruct c.\n            -- reflexivity.\n            -- simpl. intros H. rewrite <- H. reflexivity.\n        - destruct c.\n            -- simpl. intros H. rewrite <- H. reflexivity.\n            -- reflexivity.\n    Qed.\n\t\t\n    (** **** Exercise: 3 stars, standard (binary)\n\t\t\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\t\t\n        For example:\n\t\t\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\t\t\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\t\t\n    Inductive bin : Type :=\n        | Z\n        | B0 (n : bin)\n        | B1 (n : bin).\n\t\n    (** Complete the definitions below of an increment function [incr]\n        for binary numbers, and a function [bin_to_nat] to convert\n        binary numbers to unary numbers. *)\n\t\t\n    Fixpoint incr (m:bin) : bin :=\n    match m with\n    | Z => B1 Z\n    | B0 b1 => B1 b1\n    | B1 b1 => B0 (incr b1)\n    end\n    .\n\t\t\n    Fixpoint bin_to_nat (m:bin) : nat :=\n    match m with\n    | Z => O\n    | B0 b1 => 2 * (bin_to_nat b1)\n    | B1 b1 => 1 + 2 * (bin_to_nat b1)\n    end\n    .\n\t\t\n    (** The following \"unit tests\" of your increment and binary-to-unary\n        functions should pass after you have defined those functions correctly.\n        Of course, unit tests don't fully demonstrate the correctness of\n        your functions!  We'll return to that thought at the end of the\n        next chapter. *)\n\t\t\n    Example test_bin_incr1 : (incr (B1 Z)) = B0 (B1 Z).\n    (* FILL IN HERE *) \n    Proof. reflexivity. Qed.\n\t\t\n    Example test_bin_incr2 : (incr (B0 (B1 Z))) = B1 (B1 Z).\n    Proof. reflexivity. Qed.\n\t\t\n    Example test_bin_incr3 : (incr (B1 (B1 Z))) = B0 (B0 (B1 Z)).\n    Proof. reflexivity. Qed.\n\t\t\n    Example test_bin_incr4 : bin_to_nat (B0 (B1 Z)) = 2.\n    Proof. reflexivity. Qed.\n\t\t\n    Example test_bin_incr5 :\n        bin_to_nat (incr (B1 Z)) = 1 + bin_to_nat (B1 Z).\n                Proof. reflexivity. Qed.\n\t\t\n    Example test_bin_incr6 :\n        bin_to_nat (incr (incr (B1 Z))) = 2 + bin_to_nat (B1 Z).\n                Proof. reflexivity. Qed.\n\t\t\n    (** [] *)\n\t\t\n    (* ################################################################# *)\n    (** * Testing Your Solutions *)\n\t\t\n    (** Each SF chapter comes with a test file containing scripts that\n        check whether you have solved the required exercises. If you're\n        using SF as part of a course, your instructors will likely be\n        running these test files to autograde your solutions. You can also\n        use these test files, if you like, to make sure you haven't missed\n        anything.\n\t\t\n        Important: This step is _optional_: if you've completed all the\n        non-optional exercises and Coq accepts your answers, this already\n        shows that you are in good shape.\n\t\t\n        The test file for this chapter is [BasicsTest.v]. To run it, make\n        sure you have saved [Basics.v] to disk.  Then do this:\n\t\t\n             coqc -Q . LF Basics.v\n             coqc -Q . LF BasicsTest.v\n\t\t\n        (Make sure you do this in a directory that also contains a file named\n        [_CoqProject] containing the single line [-Q . LF].)\n\t\t\n        If you accidentally deleted an exercise or changed its name, then\n        [make BasicsTest.vo] will fail with an error that tells you the\n        name of the missing exercise.  Otherwise, you will get a lot of\n        useful output:\n\t\t\n        - First will be all the output produced by [Basics.v] itself.  At\n            the end of that you will see [COQC BasicsTest.v].\n\t\t\n        - Second, for each required exercise, there is a report that tells\n            you its point value (the number of stars or some fraction\n            thereof if there are multiple parts to the exercise), whether\n            its type is ok, and what assumptions it relies upon.\n\t\t\n            If the _type_ is not [ok], it means you proved the wrong thing:\n            most likely, you accidentally modified the theorem statement\n            while you were proving it.  The autograder won't give you any\n            points for that, so make sure to correct the theorem.\n\t\t\n            The _assumptions_ are any unproved theorems which your solution\n            relies upon.  \"Closed under the global context\" is a fancy way\n            of saying \"none\": you have solved the exercise. (Hooray!)  On\n            the other hand, a list of axioms means you haven't fully solved\n            the exercise. (But see below regarding \"Allowed Axioms.\") If the\n            exercise name itself is in the list, that means you haven't\n            solved it; probably you have [Admitted] it.\n\t\t\n        - Third, you will see the maximum number of points in standard and\n            advanced versions of the assignment.  That number is based on\n            the number of stars in the non-optional exercises.\n\t\t\n        - Fourth, you will see a list of \"Allowed Axioms\".  These are\n            unproved theorems that your solution is permitted to depend\n            upon.  You'll probably see something about\n            [functional_extensionality] for this chapter; we'll cover what\n            that means in a later chapter.\n\t\t\n        - Finally, you will see a summary of whether you have solved each\n            exercise.  Note that summary does not include the critical\n            information of whether the type is ok (that is, whether you\n            accidentally changed the theorem statement): you have to look\n            above for that information.\n\t\t\n        Exercises that are manually graded will also show up in the\n        output.  But since they have to be graded by a human, the test\n        script won't be able to tell you much about them.  *)\n\t\t\n    (* 2022-08-08 17:13 *)\n\t\t", "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/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.6808738863720282}}
{"text": "Require Import String.\nRequire Import ZArith.\nDefinition Identifier := string.\nDefinition id_eq_dec := string_dec.\nInductive Term : Set :=\n  | Var : Identifier -> Term\n  | Int : Z -> Term\n  | Eq : Term -> Term -> Term\n  | Plus : Term -> Term -> Term\n  | Times : Term -> Term -> Term\n  | Minus : Term -> Term -> Term\n  | Choose : Identifier -> Term -> Term.\nDefinition extendEnv {Value} (env : Identifier -> Value) \n  (var : Identifier) (newValue : Value) : Identifier -> Value :=\n  fun id => if id_eq_dec id var then newValue else env id.\nRecord EpsilonLogic :=\n mkLogic {Value : Type;\n          vTrue : Value;\n          vFalse : Value;\n          trueAndFalseDistinct : vTrue <> vFalse;\n          eval : (Identifier -> Value) -> Term -> Value;\n          evalVar : forall env id, eval env (Var id) = env id;\n          evalIntConst :\n           forall env1 env2 i, eval env1 (Int i) = eval env2 (Int i);\n          evalIntInj :\n           forall env i j, i <> j -> eval env (Int i) <> eval env (Int j);\n          evalEqTrue :\n           forall env a b,\n           eval env a = eval env b <-> eval env (Eq a b) = vTrue;\n          evalEqFalse :\n           forall env a b,\n           eval env a <> eval env b <-> eval env (Eq a b) = vFalse;\n          evalChoose :\n           forall env x P,\n           (exists value, eval (extendEnv env x value) P = vTrue) ->\n           exists out, eval env (Eq (Choose x P) out) = vTrue;\n          evalChooseDet :\n           forall env x P Q,\n           eval env P = vTrue <-> eval env Q = vTrue ->\n           eval env (Choose x P) = eval env (Choose x Q)}.\nDefinition isTheorem (L : EpsilonLogic) (t : Term) :=\n  forall env, L.(eval) env t = L.(vTrue).\nFixpoint simplify (t : Term) : Term :=\n  match t with\n  | Var x => Var x\n  | Int i => Int i\n  | Eq a b => Eq (simplify a) (simplify b)\n  | Plus a b => Plus (simplify a) (simplify b)\n  | Times a b => Times (simplify a) (simplify b)\n  | Minus a b => Minus (simplify a) (simplify b)\n  | Choose x P => Choose x (simplify P)\n  end.\nTheorem simplify_correct :\n  forall (L : EpsilonLogic) (t : Term), isTheorem L (Eq t (simplify t)).\nProof.\n(unfold isTheorem).\n(induction t; intros; simpl in *).\n-\n(apply evalEqTrue).\nreflexivity.\n-\n(apply evalEqTrue).\nreflexivity.\n-\n(apply evalEqTrue).\nspecialize IHt1 with env.\nspecialize IHt2 with env.\n(apply evalEqTrue in IHt1).\n(apply evalEqTrue in IHt2).\nAdmitted.\n(* Auto-generated comment: Succeeded. *)\n\n", "meta": {"author": "uwplse", "repo": "analytics-data", "sha": "64d3fccac3a25230d1adb59fcf1aded3f375029a", "save_path": "github-repos/coq/uwplse-analytics-data", "path": "github-repos/coq/uwplse-analytics-data/analytics-data-64d3fccac3a25230d1adb59fcf1aded3f375029a/diffs-annotated-fixed-2/5/user-5-session-18.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6808233501839877}}
{"text": "Require Import Reals.\n\nOpen Scope R_scope.\n\nDefinition Real := R.\n\n(* declare variables in exp-flaring rule. *)\n(* \n   Hl02 is the acceleration of the trace of exp-flaring.\n   qieta is the constant of time.\n   Hd2 is the dropping acceleration.\n   deltaHl0 is the difference of H(the initial height) and Hxt(the hanging height).\n   K is the time that the height of helicopter drop to the hanging height.\n*)\nVariables Hl02 qieta Hd2 : Real.\n\nVariables deltaHl0 K : Real.\n\nDefinition tm1 := Hl02 - deltaHl0 / (qieta * qieta) .\nDefinition tm2 := Hd2 -  K * K / 2.\nDefinition tm3 := Hl02 - Hd2.\n\n(* assumptions of this deduction. *)\nAxiom e1 : tm1 = 0.\nAxiom e2 : tm2 = 0.\nAxiom e3 : tm3 = 0.\nAxiom e5 : 0 <= K * K.\nAxiom e6 : 0 < qieta * qieta.\nAxiom e7 : 0 <= K * K / 2.\nAxiom e8 : 0 <= sqrt (deltaHl0 / (qieta * qieta)).\nAxiom e9 : 0 <= deltaHl0 / (qieta * qieta).\n\nDefinition tm5 :=  K * K / 2.\nDefinition tm6 := Hd2.\nDefinition tm7 := Hl02.\n\n\nLemma eq0_eq : forall y z, y-z = 0 -> y = z.\nintros.\napply sym_eq.\napply Rminus_diag_uniq_sym.\nassumption.\nQed.\n\nLemma  tm5_eq_tm6 : tm5 = tm6.\napply sym_eq.\napply eq0_eq.\nunfold tm5;unfold tm6.\napply e2.\nQed.\n\nLemma  tm6_eq_tm7 : tm6 = tm7.\napply sym_eq.\napply eq0_eq.\nunfold tm6;unfold tm7.\napply e3.\nQed.\n\n\nLemma tm5_eq : tm5  = deltaHl0 /(qieta * qieta) .\napply eq0_eq.\nrewrite tm5_eq_tm6.\nrewrite tm6_eq_tm7.\napply e1.\nQed.\n\nLemma two_eq_two : INR 2 = 2.\nauto.\nQed.\n\nLemma zero_less_than_inr_two : (0 < INR 2).\napply lt_0_INR.\nauto.\nQed.\n\n(* real number 2 is not equal to real number 0. *)\nLemma zero_less_than_two : 0<2.\nrewrite <- two_eq_two.\napply zero_less_than_inr_two.\nQed.\n\nLemma l1 : sqrt (K * K) / sqrt 2 = sqrt(K*K / 2).\napply sym_eq.\napply sqrt_div.\napply e5.\napply zero_less_than_two.\nQed.\n\nLemma l2 : sqrt(deltaHl0) / sqrt(qieta * qieta) = sqrt( deltaHl0 / (qieta * qieta)).\napply sym_eq.\napply sqrt_div_alt.\napply e6.\nQed.\n\nLemma l3 : K * K / 2 = tm5.\nunfold tm5.\nring.\nQed.\n\nLemma l4 : K * K / 2 = deltaHl0 / (qieta * qieta).\nrewrite l3.\nrewrite tm5_eq.\nring.\nQed.\n\n(*\nLemma l5 : forall K, 0 <= K -> 0 <= K * K / 2.\nintros.\n*)\n\nTheorem final_result : 0 <= (deltaHl0) -> 0 <= K -> 0 <> qieta -> sqrt(K * K) / sqrt(2) = sqrt(deltaHl0) / sqrt(qieta * qieta).\nintros.\nrewrite l1.\nrewrite l2.\napply sqrt_lem_1.\n(*this step should from (0 <= K) reach (0 <= K * K / 2) *)\napply e7.\n(*\nthis step should from (0 <> qieta) reach \n(0 <= sqrt (deltaHl0 / (qieta * qieta))) \n*)\napply e8.\nrewrite l4.\napply sqrt_sqrt.\n(*this step should from (0 <= K) reach (0 <= K * K / 2) *)\napply e9.\nQed.\n", "meta": {"author": "darenme", "repo": "MyCoqScript", "sha": "cb88d115ec69ebf3d0b55d72c255a043ee3f143b", "save_path": "github-repos/coq/darenme-MyCoqScript", "path": "github-repos/coq/darenme-MyCoqScript/MyCoqScript-cb88d115ec69ebf3d0b55d72c255a043ee3f143b/helicopter_exp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6808233451822643}}
{"text": "Section Ejercicio1.\n\n\nVariable U  : Set.\nVariable A B: U -> Prop.\nVariable P Q: Prop.\nVariable R S: U -> U -> Prop.\n\nTheorem e11 : (forall x:U, A(x)) -> forall y:U, A(y).\nProof.\n  \nQed.\n\nTheorem e12 : (forall x y:U, (R x y)) -> forall x y:U, (R y x).\nProof.\n  \nQed.\n\n\nTheorem e13 : (forall x: U, ((A x)->(B x)))\n                        -> (forall y:U, (A y))\n                          -> (forall z:U, (B z)).\nProof.\n  \nQed.\n\n\nEnd Ejercicio1.\n\n\n\nSection Ejercicio2.\n\nVariable U  : Set.\nVariable A B: U -> Prop.\nVariable P Q: Prop.\nVariable R S: U -> U -> Prop.\n\n\nTheorem e21 : (forall x:U, ((A x)-> ~(forall x:U, ~ (A x)))).\nProof.\n  \nQed.\n\nTheorem e22 : (forall x y:U, ((R x y)))-> (forall x:U, (R x x)).\nProof.\n  \nQed.\n\nTheorem e23 : (forall x:U, ((P -> (A x))))\n                        -> (P -> (forall x: U, (A x))).\nProof.\n  \nQed.\n\n\nTheorem e24 : (forall x:U, ((A x) /\\ (B x)))\n                        -> (forall x:U, (A x))\n                          -> (forall x:U, (B x)).\nProof.\n  \nQed.\n\nEnd Ejercicio2.\n\n\n\nSection Ejercicio3.\n\nVariable U   : Set.\nVariable A B : U -> Prop.\nVariable P Q : Prop.\nVariable R S : U -> U -> Prop.\n\nDefinition H1 := forall x:U, (R x x).\nDefinition H2 := forall x y z:U, (R x y) /\\ (R x z) -> (R y z).\n\nTheorem e231: H1 /\\ H2 -> ... \nProof.\n  ...\nQed.\n\nDefinition Irreflexiva := ...\nDefinition Asimetrica := ...\n \nLemma e232 : Asimetrica -> Irreflexiva.\nProof.\n  ...\nQed.\n\nEnd Ejercicio3.\n\n\n\nSection Ejercicio4.\n\nVariable U : Set.\nVariable A : U->Prop.\nVariable R : U->U->Prop.\n\nTheorem e41: (exists x:U, exists y:U, (R x y)) -> exists y:U, exists x:U, (R x y).\nProof.\n  \nQed.\n\nTheorem e42: (forall x:U, A(x)) -> ~ exists x:U, ~ A(x).\nProof.\n  \nQed.\n\nTheorem e43: (exists x:U, ~(A x)) -> ~(forall x:U, (A x)).\nProof.\n  \nQed.\n\nEnd Ejercicio4.\n\n\n\nSection Ejercicio5.\n\nVariable nat      : Set.\nVariable S        : nat -> nat.\nVariable a b c    : nat.\nVariable odd even : nat -> Prop.\nVariable P Q      : nat -> Prop.\nVariable f        : nat -> nat.\n\nTheorem e51: forall x:nat, exists y:nat, (P(x)->P(y)).\nProof.\n  \nQed.\n\nTheorem e52: exists x:nat, (P x)\n                            -> (forall y:nat, (P y)->(Q y))\n                               -> (exists z:nat, (Q z)).\nProof.\n  \nQed.\n\n\nTheorem e53: even(a) -> (forall x:nat, (even(x)->odd (S(x)))) -> exists y: nat, odd(y).\nProof.\n  \nQed.\n\n\nTheorem e54: (forall x:nat, P(x) /\\ odd(x) ->even(f(x)))\n                            -> (forall x:nat, even(x)->odd(S(x)))\n                            -> even(a)\n                            -> P(S(a))\n                            -> exists z:nat, even(f(z)).\nProof.\n  \nQed.\n\nEnd Ejercicio5.\n\n\n\nSection Ejercicio6.\n\nVariable nat : Set.\nVariable S   : nat -> nat.\nVariable le  : nat -> nat -> Prop.\nVariable f   : nat -> nat.\nVariable P   : nat -> Prop.\n\nAxiom le_n: forall n:nat, (le n n).\nAxiom le_S: forall n m:nat, (le n m) -> (le n (S m)).\nAxiom monoticity: forall n m:nat, (le n m) -> (le (f n) (f m)).\n\n\nLemma le_x_Sx: forall x:nat, (le x (S x)).\nProof.\n  \nQed.\n\nLemma le_x_SSx: forall x:nat, (le x (S (S x))).\nProof.\n  \nQed.\n\nTheorem T1: forall a:nat, exists b:nat, (le (f a) b).\nProof.\n  \nQed.\n\nEnd Ejercicio6.\n\n\n\nSection Ejercicio7.\n\nVariable U   : Set.\nVariable A B : U -> Prop.\n\nTheorem e71: (forall x:U, ((A x) /\\ (B x)))\n                       -> (forall x:U, (A x)) /\\ (forall x:U, (B x)).\nProof.\n  \nQed.\n\nTheorem e72: (exists x:U, (A x \\/ B x))->(exists x:U, A x )\\/(exists x:U, B x).\nProof.\n  \nQed.\n\nTheorem e73: (forall x:U, A x) \\/ (forall y:U, B y) → forall z:U, A z \\/ B z.\nProof.\n  \nQed.\n\nEnd Ejercicio7.\n\n\nSection Ejercicio9.\nRequire Import Classical.\nVariables U : Set.\nVariables A : U -> Prop.\n\nLemma not_ex_not_forall: (~exists x :U, ~A x) -> (forall x:U, A x).\nProof.\n  \nQed.\n\nLemma not_forall_ex_not: (~forall x :U, A x) -> (exists x:U,  ~A x).\nProof.\n  \nQed.\n\nEnd Ejercicio9.\n\n\n\nSection Ejercicio10.\n\nVariable nat : Set.\nVariable  O  : nat.\nVariable  S  : nat -> nat.\n\nAxiom disc   : forall n:nat, ~O=(S n).\nAxiom inj    : forall n m:nat, (S n)=(S m) -> n=m.\nAxiom allNat : forall n: Nat, n = O \\/ exists m: nat, S m = n.\n\nVariable sum prod : nat->nat->nat.\n\nAxiom sum0   : forall n :nat, (sum n O)=n.\nAxiom sumS   : forall n m :nat, (sum n (S m))=(S (sum n m)).\nAxiom prod0  : forall n :nat, (prod n O)=O.\nAxiom prodS  : forall n m :nat, (prod n (S m))=(sum n (prod n m)).\n\nLemma L10_1: (sum (S O) (S O)) = (S (S O)).\nProof.\n  \nQed.\n\nLemma L10_2: forall n :nat, ~(O=n /\\ (exists m :nat, n = (S m))).\nProof.\n  \nQed.\n\nLemma prod_neutro: forall n :nat, (prod n (S O)) = n.\nProof.\n  \nQed.\n\nLemma diff: forall n:nat, ~(S (S n))=(S O).\nProof.\n  \nQed.\n\nLemma L10_3: forall n: nat, exists m: nat, prod n (S m) = sum n n. \nProof.\n  ...\nQed.\n\nLemma L10_4: forall m n: nat, n <> O -> sum m n <> O.  \nProof.\n  ...\nQed.\n\nLemma L10_5: forall m n: nat, sum m n = O -> m = O /\\ n = O.  \nProof.\n  ...\nQed.\n\n\nEnd Ejercicio10.\n\n\n\nSection Ejercicio11.\n\nVariable le : nat->nat->Prop.\nAxiom leinv: forall n m:nat, (le n m) -> n=O \\/\n      (exists p:nat, (exists q:nat, n=(S p)/\\ m=(S q) /\\ (le p q))).\n\nLemma notle_s_o: forall n:nat, ~(le (S n) O).\nProof.\n  \nQed.\n\nEnd Ejercicio11.\n", "meta": {"author": "elopez", "repo": "CFPTT", "sha": "5df066218d0acba5a009db498e6125d69865096a", "save_path": "github-repos/coq/elopez-CFPTT", "path": "github-repos/coq/elopez-CFPTT/CFPTT-5df066218d0acba5a009db498e6125d69865096a/práctica 2/plantilla p2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6807491110227439}}
{"text": "Require Import Arith.\nRequire Import Relations.\nRequire Import Lexicographic_Product.\n\n(** Library for reasoning about wellfounded relations *)\n\nSection LT_WF_REL.\n (* This Section is copied from the Coq library, which unfortunately uses\n Set instead of Type for Variable A, so just modified the one word. *)\n  Variable A : Type.\n  Variable R : A -> A -> Prop.\n\n  (* Relational form of inversion *)\n  Variable F : A -> nat -> Prop.\n  Definition inv_lt_rel x y := exists2 n, F x n & (forall m, F y m -> n < m).\n\n  Hypothesis F_compat : forall x y:A, R x y -> inv_lt_rel x y.\n  Remark acc_lt_rel : forall x:A, (exists n, F x n) -> Acc R x.\n  Proof.\n    intros x [n fxn]; generalize dependent x.\nRequire Import Image.\n    pattern n in |- *; apply lt_wf_ind; intros.\n    constructor; intros.\n    destruct (F_compat y x) as (x0,H1,H2); trivial.\n    apply (H x0); auto.\n  Qed.\n\n  Theorem well_founded_inv_lt_rel_compat : well_founded R.\n  Proof.\n    constructor; intros.\n    case (F_compat y a); trivial; intros.\n    apply acc_lt_rel; trivial.\n    exists x; trivial.\n  Qed.\n\nEnd LT_WF_REL.\n\nDefinition lex_pair {A B} (Ra: A -> A -> Prop) (Rb: B -> B -> Prop)\n            (x: A*B) (y: A*B) : Prop :=\n Ra (fst x) (fst y) \\/ (fst x = fst y /\\ Rb (snd x) (snd y)).\n\n\n(*\nLemma lex_pair_eqv:\n  forall A B Ra Rb,\n   lex_pair Ra Rb =\n   (fun x y =>\n   lexprod A (fun _ => B) Ra (fun _ => Rb)\n     (existT (fun _:A => B) (fst x) (snd x))\n     (existT (fun _:A => B) (fst y) (snd y))).\nProof.\n intros.\n apply Axioms.extensionality; intros [a b].\n apply Axioms.extensionality; intros [a' b'].\n simpl.\n apply Axioms.prop_ext; intuition.\n destruct H; simpl in *.\n left; auto.\n destruct H; subst a'. right; auto.\n inversion H; clear H; subst.\n left; simpl; auto.\n right; split; auto.\nQed.\n*)\n\nLemma well_founded_incl:\n  forall A (Rs Rt: A -> A -> Prop),\n   inclusion _ Rt Rs -> well_founded Rs -> well_founded Rt.\nProof.\n  unfold well_founded; intros.\n  specialize (H0 a).\n  induction H0; constructor; intros; auto.\nQed.\n\nLemma well_founded_image:\n  forall A B (f: A -> B) (Rb: B -> B -> Prop),\n    well_founded Rb ->\n    well_founded (fun x y => Rb (f x) (f y)).\nProof.\n  intros.\n intro a.\n specialize (H (f a)).\n remember (f a) as fa.\n revert a Heqfa; induction H; intros; constructor;  intros; auto.\n subst.\n eapply H0; eauto.\nQed.\n\nLemma well_founded_lex_pair:\n  forall A B (Ra: A -> A -> Prop) (Rb: B -> B -> Prop),\n  well_founded Ra -> well_founded Rb -> well_founded (lex_pair Ra Rb).\nProof.\n intros.\n apply well_founded_incl with (Rs :=  (fun x y =>\n   lexprod A (fun _ => B) Ra (fun _ => Rb)\n     (existT (fun _:A => B) (fst x) (snd x))\n     (existT (fun _:A => B) (fst y) (snd y)))).\n intros [a b] [a' b'] ?.\n inversion H1; clear H1; subst; simpl in *.\n left; auto. destruct H2; subst; right; auto.\n apply well_founded_image.\n apply wf_lexprod; auto.\nQed.\n\n\nLemma well_founded_trans:\n  forall A (Ra: A -> A -> Prop),\n    well_founded Ra <-> well_founded (clos_trans _ Ra).\nProof.\nintros; split; intros.\nunfold well_founded in *.\nintros.\nspecialize (H a).\ninduction H.\nconstructor; intros.\napply clos_trans_t1n in H1.\ninduction H1; auto.\nassert (Acc (clos_trans A Ra) y).\n2: destruct H3; apply H3; apply clos_t1n_trans; econstructor; eauto.\nclear - H0 H2.\nrevert H0; induction H2; intros.\nauto.\napply IHclos_trans_1n; auto.\nconstructor 1; auto.\nunfold well_founded in *.\nintros.\nspecialize (H a).\ninduction H.\nconstructor; intros; auto.\napply H0.\nconstructor 1 ;auto.\nQed.\n\n\nDefinition lexprodx {B A : Type} (f: A -> B) (R1: B -> B -> Prop)\n  (R2: B -> A -> A -> Prop)\n  (x y : A) : Prop :=\n     R1 (f x) (f y) \\/ f x = f y /\\ R2 (f x) x y.\n\nLemma lexprodx_eq: forall B A f R1 R2 x y,\n    lexprodx f R1 R2 x y <->\n    lexprod B (fun _ => A) R1 R2 (existT (fun _:B => A) (f x) x)\n               (existT (fun _:B => A) (f y) y).\nProof.\n intros.\n unfold lexprodx.\n intuition.\n left; auto.\n rewrite <- H. right. auto.\n inversion H; clear H; subst.\n left; auto.\n right; split; auto.\nQed.\n\nLemma well_founded_lexprodx: forall B A (f: A -> B) R1 R2,\n  well_founded R1 -> (forall n, well_founded (R2 n)) ->\n  well_founded (lexprodx f R1 R2).\nProof.\nintros.\n apply well_founded_incl with (fun x y => lexprod B (fun _ => A) R1 R2 (existT (fun _:B => A) (f x) x)\n               (existT (fun _:B => A) (f y) y)).\n intros ? ? ?. rewrite <- lexprodx_eq.  auto.\n apply well_founded_image with (f:= fun x => (existT (fun _ : B => A) (f x) x)).\n apply wf_lexprod; auto.\nQed.\n\n\n(* WARNING: Not sure simple_lexprod is useful! *)\nDefinition simple_lexprod {A: Type} (R1: A -> A -> Prop) (R2: A -> A -> Prop)\n            (x y: A) : Prop :=\n  R1 x y \\/ x=y /\\ R2 x y.\n\nLemma simple_lexprod_eq:\n  forall A R1 R2 x y,\n     @simple_lexprod A R1 R2 x y <->\n    lexprod A (fun _ => A) R1 (fun _ => R2)\n       (existT (fun _:A => A) x x) (existT (fun _:A => A) y y).\nProof.\nintros.\nunfold simple_lexprod.\nintuition.\nleft; auto.\nsubst; right; auto.\ninversion H; clear H; subst; auto.\nQed.\n\nLemma wellfounded_simple_lexprod:\n  forall A (R1: A -> A -> Prop) (R2: A -> A -> Prop),\n    well_founded R1 ->\n    well_founded R2 ->\n    well_founded (simple_lexprod R1 R2).\nProof.\n intros.\n apply well_founded_incl with\n   (fun x y => lexprod A (fun _ => A) R1 (fun _ => R2) (existT (fun _:A => A) x x)  (existT (fun _:A => A) y y)).\n intros ? ? ?. rewrite <- simple_lexprod_eq. auto.\n apply well_founded_image with (f:= fun x => existT (fun _:A => A) x x).\n apply wf_lexprod; auto.\nQed.\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/veristar/wellfounded.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6807491059827003}}
{"text": "Require Import GeoCoq.Tarski_dev.Ch12_parallel_inter_dec.\nRequire Import Morphisms.\nRequire Import GeoCoq.Axioms.hilbert_axioms.\nRequire Import GeoCoq.Axioms.parallel_postulates.\nRequire Import GeoCoq.Meta_theory.Parallel_postulates.tarski_playfair.\nRequire Import GeoCoq.Meta_theory.Parallel_postulates.SPP_ID.\nRequire Import GeoCoq.Meta_theory.Dimension_axioms.upper_dim_3.\nRequire Import GeoCoq.Meta_theory.Parallel_postulates.parallel_postulates.\n\nRequire Export GeoCoq.Utils.triples.\n\nSection T.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\n(** We need a notion of line. *)\n\nDefinition Line := @Couple Tpoint.\nDefinition Lin := build_couple Tpoint.\n\nDefinition IncidentL := fun A l => Col A (P1 l) (P2 l).\n\n(** * Group I Combination *)\n\n(** For every pair of distinct points there is a line containing them. *)\n\nLemma axiom_line_existence : forall A B, A<>B -> exists l, IncidentL A l /\\ IncidentL B l.\nProof.\nintros.\nexists (Lin A B H).\nunfold IncidentL.\nintuition.\nQed.\n\n(** We need a notion of equality over lines. *)\n\nDefinition EqL : relation Line := fun l m => forall X, IncidentL X l <-> IncidentL X m.\n\nInfix \"=l=\" := EqL (at level 70):type_scope.\n\nLemma incident_eq : forall A B l, forall H : A<>B,\n IncidentL A l -> IncidentL B l ->\n (Lin A B H) =l= l.\nProof.\nintros.\nunfold EqL.\nintros.\nunfold IncidentL in *.\nreplace (P1 (Lin A B H)) with A; trivial.\nreplace (P2 (Lin A B H)) with B; trivial.\nsplit;intro.\nassert (T:=Cond l).\nelim (eq_dec_points X B); intro.\nsubst X.\nauto.\nassert (Col (P1 l) A B).\napply col_transitivity_1 with (P2 l); Col.\nassert (Col (P2 l) A B).\napply (col_transitivity_2 (P1 l)); Col.\napply (col3 A B); Col.\n\nassert (U:=Cond l).\napply (col3 (P1 l) (P2 l)); Col.\nQed.\n\n(** Our equality is an equivalence relation. *)\n\nLemma eq_transitivity : forall l m n, l =l= m -> m =l= n -> l =l= n.\nProof.\nunfold EqL,IncidentL.\nintros.\nassert (T:=H X).\nassert (V:= H0 X).\nsplit;intro;intuition.\nQed.\n\nLemma eq_reflexivity : forall l, l =l= l.\nProof.\nintros.\nunfold EqL.\nintuition.\nQed.\n\nLemma eq_symmetry : forall l m, l =l= m -> m =l= l.\nProof.\nunfold EqL.\nintros.\nassert (T:=H X).\nintuition.\nQed.\n\nInstance EqL_Equiv : Equivalence EqL.\nProof.\nsplit.\nunfold Reflexive.\napply eq_reflexivity.\nunfold Symmetric.\napply eq_symmetry.\nunfold Transitive.\napply eq_transitivity.\nDefined.\n\n\n(** The equality is compatible with IncidentL *)\n\nLemma eq_incident : forall A l m, l =l= m ->\n (IncidentL A l <-> IncidentL A m).\nProof.\nintros.\nsplit;intros;\nunfold EqL in *;\nassert (T:= H A);\nintuition.\nQed.\n\nInstance incident_Proper (A:Tpoint) :\nProper (EqL ==>iff) (IncidentL A).\nProof.\nintros a b H .\napply eq_incident.\nassumption.\nDefined.\n\nLemma axiom_Incid_morphism :\n forall P l m, IncidentL P l -> EqL l m -> IncidentL P m.\nProof.\nintros.\ndestruct (eq_incident P l m H0).\nintuition.\nQed.\n\nLemma axiom_Incid_dec : forall P l, IncidentL P l \\/ ~IncidentL P l.\nProof.\nintros.\nunfold IncidentL.\napply col_dec.\nQed.\n\n(** There is only one line going through two points. *)\n\nLemma axiom_line_uniqueness : forall A B l m, A <> B ->\n IncidentL A l -> IncidentL B l -> IncidentL A m -> IncidentL B m ->\n l =l= m.\nProof.\nintros.\nassert ((Lin A B H) =l= l).\neapply incident_eq;assumption.\nassert ((Lin A B H) =l= m).\neapply incident_eq;assumption.\nrewrite <- H4.\nassumption.\nQed.\n\n(** Every line contains at least two points. *)\n\nLemma axiom_two_points_on_line : forall l,\n  { A : Tpoint & { B | IncidentL B l /\\ IncidentL A l /\\ A <> B}}.\nProof.\nintros.\nexists (P1 l).\nexists (P2 l).\nunfold IncidentL.\nrepeat split;Col.\nexact (Cond l).\nQed.\n\n(** Definition of the collinearity predicate.\n We say that three points are collinear if they belongs to the same line. *)\n\nDefinition Col_H := fun A B C =>\n  exists l, IncidentL A l /\\ IncidentL B l /\\ IncidentL C l.\n\n(** We show that the notion of collinearity we just defined is equivalent to the\n notion of collinearity of Tarski. *)\n\nLemma cols_coincide_1 : forall A B C, Col_H A B C -> Col A B C.\nProof.\nintros.\nunfold Col_H in H.\nDecompExAnd H l.\nunfold IncidentL in *.\nassert (T:=Cond l).\napply (col3 (P1 l) (P2 l)); Col.\nQed.\n\nLemma cols_coincide_2 : forall A B C, Col A B C -> Col_H A B C.\nProof.\nintros.\nunfold Col_H.\nelim (eq_dec_points A B); intro.\nsubst B.\nelim (eq_dec_points A C); intro.\nsubst C.\nassert (exists B, A<>B).\neapply another_point.\nDecompEx H0 B.\nexists (Lin A B H1).\nunfold IncidentL;intuition.\nexists (Lin A C H0).\nunfold IncidentL;intuition.\nexists (Lin A B H0).\nunfold IncidentL;intuition.\nQed.\n\nLemma cols_coincide : forall A B C, Col A B C <-> Col_H A B C.\nProof.\nintros.\nsplit.\napply cols_coincide_2.\napply cols_coincide_1.\nQed.\n\nLemma ncols_coincide : forall A B C, ~ Col A B C <-> ~ Col_H A B C.\nProof.\nintros.\nsplit; intros HNCol HCol; apply HNCol, cols_coincide, HCol.\nQed.\n\n(** There exists three non collinear points. *)\n\nLemma lower_dim' : PA <> PB /\\ PB <> PC /\\ PA <> PC /\\ ~ Col_H PA PB PC.\nProof.\nassert (HNCol : ~ Col PA PB PC) by (apply lower_dim).\nassert_diffs.\napply ncols_coincide in HNCol.\nrepeat split; auto.\nQed.\n\n(** We need a notion of plane. *)\n\nRecord Plane := Plan {M1; M2; M3; NCol : ~ Col_H M1 M2 M3}.\n\nDefinition IncidentP := fun A p => Coplanar (M1 p) (M2 p) (M3 p) A.\n\n(** For every triplet of non collinear points there is a plane containing them. *)\n\nLemma axiom_plane_existence : forall A B C, ~ Col_H A B C ->\n  exists p, IncidentP A p /\\ IncidentP B p /\\ IncidentP C p.\nProof.\nintros A B C HNCol.\nexists (Plan A B C HNCol).\nunfold IncidentP; simpl; repeat split; Cop.\nQed.\n\n(** We need a notion of equality over planes. *)\n\nDefinition EqP : relation Plane := fun p q => forall X, IncidentP X p <-> IncidentP X q.\n\nInfix \"=p=\" := EqP (at level 70):type_scope.\n\nLemma incidentp_eqp : forall A B C p, forall H : ~ Col_H A B C,\n IncidentP A p -> IncidentP B p -> IncidentP C p ->\n (Plan A B C H) =p= p.\nProof.\nintros A B C p HNCol HA HB HC X.\nunfold IncidentP in *; simpl.\nassert (Hp := NCol p).\napply ncols_coincide in Hp.\napply ncols_coincide in HNCol.\nsplit; intro; [apply coplanar_pseudo_trans with A B C; trivial|];\napply coplanar_pseudo_trans with (M1 p) (M2 p) (M3 p); Cop.\nQed.\n\n(** Our equality is an equivalence relation. *)\n\nLemma eqp_transitivity : forall p q r, p =p= q -> q =p= r -> p =p= r.\nProof.\nintros p q r H1 H2 X.\nrewrite (H1 X); apply H2.\nQed.\n\nLemma eqp_reflexivity : forall p, p =p= p.\nProof.\nintros.\nunfold EqP.\nintuition.\nQed.\n\nLemma eqp_symmetry : forall p q, p =p= q -> q =p= p.\nProof.\nunfold EqP.\nintros p q H X.\nassert (T := H X).\nintuition.\nQed.\n\n(** * Group II Order *)\nInstance EqP_Equiv : Equivalence EqP.\nProof.\nsplit.\nunfold Reflexive.\napply eqp_reflexivity.\nunfold Symmetric.\napply eqp_symmetry.\nunfold Transitive.\napply eqp_transitivity.\nDefined.\n\n\n(** The equality is compatible with IncidentL *)\n\nLemma eqp_incidentp : forall A p q, p =p= q ->\n (IncidentP A p <-> IncidentP A q).\nProof.\nintros A p q H.\nexact (H A).\nQed.\n\nInstance incidentp_Proper (A:Tpoint) :\nProper (EqP ==>iff) (IncidentP A).\nProof.\nintros a b H.\napply eqp_incidentp.\nassumption.\nDefined.\n\nLemma axiom_Incidp_morphism :\n forall M p q, IncidentP M p -> EqP p q -> IncidentP M q.\nProof.\nintros M p q Hp H.\ndestruct (eqp_incidentp M p q H).\nintuition.\nQed.\n\nLemma axiom_Incidp_dec : forall M p, IncidentP M p \\/ ~ IncidentP M p.\nProof.\nintros.\napply cop_dec.\nQed.\n\n(** There is only one plane going through three non collinear points. *)\n\nLemma axiom_plane_uniqueness : forall A B C p q, ~ Col_H A B C ->\n IncidentP A p -> IncidentP B p -> IncidentP C p ->\n IncidentP A q -> IncidentP B q -> IncidentP C q ->\n p =p= q.\nProof.\nintros A B C p q H; intros.\nassert (Heq : (Plan A B C H) =p= p).\napply incidentp_eqp;assumption.\nassert ((Plan A B C H) =p= q).\napply incidentp_eqp;assumption.\nrewrite <- Heq.\nassumption.\nQed.\n\n(** Every plane contains at least one point. *)\n\nLemma axiom_one_point_on_plane : forall p,\n  { A | IncidentP A p }.\nProof.\nintro p.\nexists (M1 p).\nunfold IncidentP; Cop.\nQed.\n\n(** Definition of a line belonging to a plane.\n  We say that a line belongs to a plane if every point of the line belongs to the plane. *)\n\nDefinition  IncidentLP := fun l p => forall A, IncidentL A l -> IncidentP A p.\n\n(** If two distinct points of a line belong to a plane, then the line belongs to the plane. *)\n\nLemma axiom_line_on_plane : forall A B l p, A <> B ->\n IncidentL A l -> IncidentL B l -> IncidentP A p -> IncidentP B p ->\n IncidentLP l p.\nProof.\nintros A B l p HAB HAl HBl HAp HBp X HXl.\ndestruct (ex_ncol_cop (M1 p) (M2 p) (M3 p) A B HAB) as [C [HCp HNCol]].\napply ncols_coincide in HNCol.\nassert (Heq : (Plan A B C HNCol) =p= p).\napply incidentp_eqp; auto.\nrewrite <- Heq.\nunfold IncidentP; simpl.\nexists X; left; split.\napply cols_coincide_1; exists l; repeat split; assumption.\nCol.\nQed.\n\n(** * Group II Order *)\n\n(** Definition of the Between predicate of Hilbert.\n    Note that it is different from the Between of Tarski.\n    The Between of Hilbert is strict. *)\n\nDefinition Between_H := fun A B C =>\n  Bet A B C /\\ A <> B /\\ B <> C /\\ A <> C.\n\nLemma axiom_between_col :\n forall A B C, Between_H A B C -> Col_H A B C.\nProof.\nintros.\nunfold Col_H, Between_H in *.\nDecompAndAll.\nexists (Lin A B H2).\nunfold IncidentL.\nintuition.\nQed.\n\nLemma axiom_between_diff :\n forall A B C, Between_H A B C -> A<>C.\nProof.\nintros.\nunfold Between_H in *.\nintuition.\nQed.\n\n(** If B is between A and C, it is also between C and A. *)\n\nLemma axiom_between_comm : forall A B C, Between_H A B C -> Between_H C B A.\nProof.\nunfold Between_H in |- *.\nintros.\nintuition.\nQed.\n\n\n\nLemma axiom_between_out :\n forall A B, A <> B -> exists C, Between_H A B C.\nProof.\nintros.\nprolong A B C A B.\nexists C.\nunfold Between_H.\nrepeat split;\nauto;\nintro;\ntreat_equalities;\ntauto.\nQed.\n\nLemma axiom_between_only_one :\n forall A B C,\n Between_H A B C -> ~ Between_H B C A.\nProof.\nunfold Between_H in |- *.\nintros.\nintro;\nspliter.\nassert (B=C) by\n (apply (between_equality B C A);Between).\nsolve [intuition].\nQed.\n\nLemma between_one : forall A B C,\n A<>B -> A<>C -> B<>C -> Col A B C ->\n Between_H A B C \\/ Between_H B C A \\/ Between_H B A C.\nProof.\nintros.\nunfold Col, Between_H in *.\ndestruct H2 as [|[|]]; [left|right..]; Between.\nQed.\n\n\nLemma axiom_between_one : forall A B C,\n A<>B -> A<>C -> B<>C -> Col_H A B C ->\n Between_H A B C \\/ Between_H B C A \\/ Between_H B A C.\nProof.\nintros.\napply between_one;try assumption.\napply cols_coincide_1.\nassumption.\nQed.\n\n(** Axiom of Pasch, (Hilbert version). *)\n\n(** First we define a predicate which means that the line l intersects the segment AB. *)\n\nDefinition cut := fun l A B =>\n  ~ IncidentL A l /\\ ~ IncidentL B l /\\ exists I, IncidentL I l /\\ Between_H A I B.\n\n(** We show that this definition is equivalent to the predicate TS of Tarski. *)\n\nLemma cut_two_sides : forall l A B, cut l A B <-> TS (P1 l) (P2 l) A B.\nProof.\nintros.\nunfold cut.\nunfold TS.\nsplit.\nintros.\nspliter.\nrepeat split; intuition.\nex_and H1 T.\nexists T.\nunfold IncidentL in H1.\nunfold Between_H in *.\nintuition.\n\nintros.\nspliter.\nex_and H1 T.\nunfold IncidentL.\nrepeat split; try assumption.\nexists T.\nsplit.\nassumption.\nunfold Between_H.\nrepeat split.\nassumption.\nintro.\nsubst.\ncontradiction.\nintro.\nsubst.\ncontradiction.\nintro.\ntreat_equalities.\ncontradiction.\nQed.\n\nLemma cop_plane_aux : forall A B C D, Coplanar A B C D -> A <> B ->\n  exists p, IncidentP A p /\\ IncidentP B p /\\ IncidentP C p /\\ IncidentP D p.\nProof.\n  intros A B C D HCop HAB.\n  destruct (col_dec A B C) as [|HNCol]; [destruct (col_dec A B D) as [|HNCol]|].\n  - destruct (not_col_exists A B HAB) as [E HNCol].\n    apply ncols_coincide in HNCol.\n    exists (Plan A B E HNCol).\n    unfold IncidentP; simpl; repeat split; Cop.\n  - apply ncols_coincide in HNCol.\n    exists (Plan A B D HNCol).\n    unfold IncidentP; simpl; repeat split; Cop.\n  - apply ncols_coincide in HNCol.\n    exists (Plan A B C HNCol).\n    unfold IncidentP; simpl; repeat split; Cop.\nQed.\n\nLemma cop_plane : forall A B C D, Coplanar A B C D ->\n  exists p, IncidentP A p /\\ IncidentP B p /\\ IncidentP C p /\\ IncidentP D p.\nProof.\n  intros A B C D HCop.\n  destruct (eq_dec_points A B) as [|HAB]; [destruct (eq_dec_points A C);\n    [destruct (eq_dec_points A D)|]|].\n  - destruct (another_point D) as [E].\n    destruct (cop_plane_aux D E E E) as [p []]; Cop.\n    subst; exists p; repeat split; assumption.\n  - destruct (cop_plane_aux A D B C) as [p]; Cop.\n    spliter; exists p; repeat split; assumption.\n  - destruct (cop_plane_aux A C B D) as [p]; Cop.\n    spliter; exists p; repeat split; assumption.\n  - apply (cop_plane_aux A B C D HCop HAB).\nQed.\n\nLemma plane_cop: forall A B C D p,\n  IncidentP A p -> IncidentP B p -> IncidentP C p -> IncidentP D p -> Coplanar A B C D.\nProof.\n  unfold IncidentP.\n  intros A B C D p HA HB HC HD.\n  assert (HNCol := NCol p).\n  apply ncols_coincide in HNCol.\n  apply coplanar_pseudo_trans with (M1 p) (M2 p) (M3 p); assumption.\nQed.\n\nLemma axiom_pasch : forall A B C l p, ~ Col_H A B C ->\n IncidentP A p -> IncidentP B p -> IncidentP C p -> IncidentLP l p -> ~ IncidentL C l ->\n cut l A B -> cut l A C \\/ cut l B C.\nProof.\nintros.\napply cut_two_sides in H5.\nassert(~Col A B C).\napply ncols_coincide.\nassumption.\n\nassert(HH:=H5).\nunfold TS in HH.\nspliter.\n\nunfold IncidentL in H4.\nassert (HCop : Coplanar (P1 l) (P2 l) A C).\napply plane_cop with p; trivial; apply H3; unfold IncidentL; simpl; Col.\n\nassert(HH:= cop__one_or_two_sides (P1 l)(P2 l) A C HCop H7 H4).\n\ninduction HH.\nleft.\napply <-cut_two_sides.\nassumption.\nright.\napply <-cut_two_sides.\napply l9_2.\neapply l9_8_2.\napply H5.\nassumption.\nQed.\n\nLemma Incid_line :\n forall P A B l, A<>B ->\n IncidentL A l -> IncidentL B l -> Col P A B -> IncidentL P l.\nProof.\nintros.\nunfold IncidentL in *.\ndestruct l as [C D HCD].\nsimpl in *.\nColR.\nQed.\n\n\n\n\n(** * Group IV Congruence *)\n\n(** The cong predicate of Hilbert is the same as the one of Tarski: *)\n\nDefinition outH := fun P A B => Between_H P A B \\/ Between_H P B A \\/ (P <> A /\\ A = B).\n\nLemma out_outH : forall P A B, Out P A B -> outH P A B.\nunfold Out.\nunfold outH.\nintros.\nspliter.\ninduction H1.\n\ninduction (eq_dec_points A B).\nright; right.\nsplit; auto.\nleft.\nunfold Between_H.\nrepeat split; auto.\n\n\ninduction (eq_dec_points A B).\nright; right.\nsplit; auto.\nright; left.\nunfold Between_H.\nrepeat split; auto.\nQed.\n\nLemma axiom_hcong_1_existence : forall A B A' P l,\n  A <> B -> A' <> P ->\n  IncidentL A' l -> IncidentL P l ->\n  exists B', IncidentL B' l /\\ outH A' P B' /\\ Cong A' B' A B.\nProof.\nintros; destruct (l6_11_existence A' A B P) as [B' [HOut HCong]]; auto.\nexists B'; repeat split; try apply out_outH, l6_6; auto; unfold IncidentL in *.\ndestruct l; simpl in *; ColR.\nQed.\n\nLemma axiom_hcong_1_uniqueness :\n forall A B l M A' B' A'' B'', A <> B -> IncidentL M l ->\n  IncidentL A' l -> IncidentL B' l ->\n  IncidentL A'' l -> IncidentL B'' l ->\n  Between_H A' M B' -> Cong M A' A B ->\n  Cong M B' A B -> Between_H A'' M B'' ->\n  Cong M A'' A B -> Cong M B'' A B ->\n  (A' = A'' /\\ B' = B'') \\/ (A' = B'' /\\ B' = A'').\nProof.\nunfold Between_H.\nunfold IncidentL.\nintros.\nspliter.\n\nassert(A' <> M /\\ A'' <> M /\\ B' <> M /\\ B'' <> M /\\ A' <> B' /\\ A'' <> B'').\nrepeat split; intro; treat_equalities; tauto.\nspliter.\n\ninduction(out_dec M A' A'').\nleft.\nassert(A' = A'').\neapply (l6_11_uniqueness M A B A''); try assumption.\napply out_trivial.\nassumption.\n\nsplit.\nassumption.\nsubst A''.\n\neapply (l6_11_uniqueness M A B B''); try assumption.\n\nunfold Out.\nrepeat split; try assumption.\neapply l5_2.\napply H18.\nassumption.\nassumption.\napply out_trivial.\nassumption.\n\nright.\napply not_out_bet in H23.\n\nassert(A' = B'').\neapply (l6_11_uniqueness M A B A'); try assumption.\napply out_trivial.\nassumption.\n\nunfold Out.\nrepeat split; try assumption.\n\neapply l5_2.\napply H18.\nassumption.\napply between_symmetry.\nassumption.\n\nsplit.\nassumption.\n\nsubst B''.\neapply (l6_11_uniqueness M A B B'); try assumption.\napply out_trivial.\nassumption.\nunfold Out.\nrepeat split; try assumption.\neapply l5_2.\napply H20.\napply between_symmetry.\nassumption.\nassumption.\neapply col3.\napply (Cond l).\nCol.\nCol.\nCol.\nQed.\n\n(** As a remark we also prove another version of this axiom as formalized in Isabelle by\nPhil Scott. *)\n\nDefinition same_side_scott := fun E A B => E <> A /\\ E <> B /\\ Col_H E A B /\\ ~ Between_H A E B.\n\nRemark axiom_hcong_scott:\n forall P Q A C, A <> C -> P <> Q ->\n  exists B, same_side_scott A B C  /\\ Cong P Q A B.\nProof.\nintros.\nunfold same_side_scott.\nassert (exists X : Tpoint, Out A X C /\\ Cong A X P Q).\napply l6_11_existence;auto.\ndecompose [ex and] H1;clear H1.\nexists x.\nrepeat split.\nunfold Out in H3.\nintuition.\nunfold Out in H3.\nintuition.\napply cols_coincide_2.\napply out_col;assumption.\n\n\nunfold Out in H3.\nunfold Between_H.\nintro.\ndecompose [and] H3;clear H3.\ndecompose [and] H1;clear H1.\nclear H8.\ndestruct H7.\nassert (A = x).\neapply between_equality;eauto.\nintuition.\nassert (A = C).\neapply between_equality;eauto.\napply between_symmetry.\nauto.\nintuition.\nCong.\nQed.\n\n(** We define when two segments do not intersect. *)\n\nDefinition disjoint := fun A B C D => ~ exists P, Between_H A P B /\\ Between_H C P D.\n\n(** Note that two disjoint segments may share one of their extremities. *)\n\nLemma col_disjoint_bet : forall A B C, Col_H A B C -> disjoint A B B C -> Bet A B C.\nProof.\nintros.\napply cols_coincide_1 in H.\nunfold disjoint in H0.\n\ninduction (eq_dec_points A B).\nsubst  B.\napply between_trivial2.\ninduction (eq_dec_points B C).\nsubst  C.\napply between_trivial.\n\nunfold Col in H.\ninduction H.\nassumption.\n\ninduction H.\napply False_ind.\napply H0.\nassert(exists M, Midpoint M B C) by(apply midpoint_existence).\nex_and H3 M.\nexists M.\nunfold Midpoint in H4.\nspliter.\nsplit.\nunfold Between_H.\nrepeat split.\napply between_symmetry.\neapply between_exchange4.\napply H3.\nassumption.\nintro.\ntreat_equalities.\n(*\napply between_symmetry in H.\napply between_equality in H.\ntreat_equalities.\n*)\ntauto.\n(*\napply between_symmetry.\nassumption.\n*)\nintro.\ntreat_equalities.\ntauto.\nassumption.\nunfold Between_H.\nrepeat split.\nassumption.\nintro.\ntreat_equalities.\ntauto.\nintro.\ntreat_equalities.\ntauto.\nassumption.\n\napply False_ind.\napply H0.\nassert(exists M, Midpoint M A B) by(apply midpoint_existence).\nex_and H3 M.\nexists M.\nunfold Midpoint in H4.\nspliter.\nsplit.\nunfold Between_H.\nrepeat split.\nassumption.\nintro.\ntreat_equalities.\ntauto.\nintro.\ntreat_equalities.\ntauto.\nassumption.\n\nunfold Between_H.\nrepeat split.\n\neapply between_exchange4.\napply between_symmetry.\napply H3.\napply between_symmetry.\nassumption.\nintro.\ntreat_equalities.\ntauto.\nintro.\ntreat_equalities.\nintuition.\nassumption.\nQed.\n\n\nLemma axiom_hcong_3 : forall A B C A' B' C',\n   Col_H A B C -> Col_H A' B' C' ->\n  disjoint A B B C -> disjoint A' B' B' C' ->\n  Cong A B A' B' -> Cong B C B' C' -> Cong A C A' C'.\nProof.\nintros.\nassert(Bet A B C).\neapply col_disjoint_bet.\nassumption.\nassumption.\n\nassert(Bet A' B' C').\neapply col_disjoint_bet.\nassumption.\nassumption.\neapply l2_11;eauto.\nQed.\n\nLemma exists_not_incident : forall A B : Tpoint, forall  HH : A <> B , exists C, ~ IncidentL C (Lin A B HH).\nProof.\nintros.\nunfold IncidentL.\nassert(HC:=not_col_exists A B HH).\nex_and HC C.\nexists C.\nintro.\napply H.\nsimpl in H0.\nCol.\nQed.\n\nDefinition same_side := fun A B l => exists P, cut l A P /\\ cut l B P.\n\n(** Same side predicate corresponds to OS of Tarski. *)\n\nLemma same_side_one_side : forall A B l, same_side A B l -> OS (P1 l) (P2 l) A B.\nProof.\nunfold same_side.\nintros.\ndestruct H as [P []].\napply cut_two_sides in H.\napply cut_two_sides in H0.\neapply l9_8_1.\napply H.\napply H0.\nQed.\n\n\n\nLemma one_side_same_side : forall A B l, OS (P1 l) (P2 l) A B -> same_side A B l.\nProof.\nintros.\nunfold same_side.\nunfold OS in H.\ndestruct H as [P []].\nexists P.\nunfold cut.\nunfold IncidentL.\nunfold TS in H.\nunfold TS in H0.\nspliter.\nrepeat split; auto.\nex_and H4 T.\nexists T.\nunfold Between_H.\nrepeat split; auto.\nintro.\nsubst T.\ncontradiction.\nintro.\nsubst T.\ncontradiction.\nintro.\nsubst P.\napply between_identity in H5.\nsubst T.\ncontradiction.\nex_and H2 T.\nexists T.\nunfold Between_H.\nrepeat split; auto.\nintro.\nsubst T.\ncontradiction.\nintro.\nsubst T.\ncontradiction.\nintro.\nsubst P.\napply between_identity in H5.\nsubst T.\ncontradiction.\nQed.\n\nDefinition same_side' := fun A B X Y =>\n  X <> Y /\\ forall l, IncidentL X l -> IncidentL Y l -> same_side A B l.\n\nLemma OS_distinct : forall P Q A B,\n  OS P Q A B -> P<>Q.\nProof.\nintros.\napply one_side_not_col123 in H.\nassert_diffs;assumption.\nQed.\n\n\nLemma OS_same_side' :\n forall P Q A B, OS P Q A B -> same_side' A B P Q.\nProof.\nintros.\nunfold same_side'.\nintros.\nsplit.\napply OS_distinct with A B;assumption.\nintros.\n\napply  one_side_same_side.\ndestruct l.\nunfold IncidentL in *.\nsimpl in *.\napply col2_os__os with P Q; try assumption; ColR.\nQed.\n\nLemma same_side_OS :\n forall P Q A B, same_side' P Q A B -> OS A B P Q.\nProof.\nintros.\nunfold same_side' in *.\ndestruct H.\ndestruct (axiom_line_existence A B H).\ndestruct H1.\nassert (T:=H0 x H1 H2).\nassert (U:=same_side_one_side P Q x T).\ndestruct x.\nunfold IncidentL in *.\nsimpl in *.\napply col2_os__os with P1 P2;Col.\nQed.\n\n(** This is equivalent to the out predicate of Tarski. *)\n\nLemma outH_out : forall P A B, outH P A B -> Out P A B.\nProof.\nunfold outH.\nunfold Out.\nintros.\ninduction H.\nunfold Between_H in H.\nspliter.\nrepeat split; auto.\ninduction H.\nunfold Between_H in H.\nspliter.\nrepeat split; auto.\nspliter.\nrepeat split.\nauto.\nsubst B.\nauto.\nsubst B.\nleft.\napply between_trivial.\nQed.\n\n(** The 2D version of the fourth congruence axiom **)\n\nLemma incident_col : forall M l, IncidentL M l -> Col M (P1 l)(P2 l).\nProof.\nunfold IncidentL.\nintros.\nassumption.\nQed.\n\nLemma col_incident : forall M l, Col M (P1 l)(P2 l) -> IncidentL M l.\nProof.\nunfold IncidentL.\nintros.\nassumption.\nQed.\n\nLemma Bet_Between_H : forall A B C,\n Bet A B C -> A<>B -> B<>C -> Between_H A B C.\nProof.\nintros.\nunfold Between_H.\nrepeat split;try assumption.\nintro.\nsubst.\ntreat_equalities.\nintuition.\nQed.\n\nLemma axiom_cong_5' : forall A B C A' B' C', ~ Col_H A B C -> ~ Col_H A' B' C' ->\n           Cong A B A' B' -> Cong A C A' C' -> CongA B A C B' A' C' -> CongA A B C A' B' C'.\nProof.\nintros A B C A' B' C'.\nintros.\nassert (T:=l11_49 B A C B' A' C').\nassert (~ Col A B C).\nintro.\napply cols_coincide_2 in H4.\nintuition.\nassert_diffs.\nintuition.\nQed.\n\n\nLemma axiom_hcong_4_existence :  forall A B C O X P,\n   ~ Col_H P O X -> ~ Col_H A B C ->\n  exists Y, CongA A B C X O Y  (* /\\ ~Col O X Y *) /\\ same_side' P Y O X.\nProof.\nintros.\nrewrite <- cols_coincide in H.\nrewrite <- cols_coincide in H0.\n\nassert(~Col X O P).\nintro.\napply H.\nCol.\nassert(HH:=angle_construction_1 A B C X O P H0 H1).\n\nex_and HH Y.\n\nexists Y.\nsplit.\nassumption.\napply OS_same_side'.\napply invert_one_side.\napply one_side_symmetry.\nassumption.\nQed.\n\nLemma same_side_trans :\n forall A B C l,\n  same_side A B l -> same_side B C l -> same_side A C l.\nProof.\nintros.\napply one_side_same_side.\napply same_side_one_side in H.\napply same_side_one_side in H0.\neapply one_side_transitivity.\napply H.\nassumption.\nQed.\n\nLemma same_side_sym :\n forall A B l,\n  same_side A B l -> same_side B A l.\nProof.\nintros.\napply one_side_same_side.\napply same_side_one_side in H.\napply one_side_symmetry.\nassumption.\nQed.\n\n\nLemma axiom_hcong_4_uniqueness :\n  forall A B C O P X Y Y', ~ Col_H P O X  -> ~ Col_H A B C -> CongA A B C X O Y -> CongA A B C X O Y' -> \n  same_side' P Y O X -> same_side' P Y' O X -> outH O Y Y'.\nProof.\nintros.\nrewrite <- cols_coincide in H.\nrewrite <- cols_coincide in H0.\nassert (T:CongA X O Y X O Y').\neapply conga_trans.\napply conga_sym.\napply H1.\nassumption.\n\napply conga_cop__or_out_ts in T.\ninduction T.\napply out_outH.\nassumption.\n\napply same_side_OS in H3.\napply same_side_OS in H4.\nexfalso.\nassert (OS O X Y Y').\napply one_side_transitivity with P.\napply one_side_symmetry.\nassumption.\nassumption.\napply invert_one_side in H6.\napply l9_9 in H5.\nintuition.\n\napply same_side_OS in H3.\napply same_side_OS in H4.\napply coplanar_trans_1 with P; Col; Cop.\nQed.\n\nLemma axiom_conga_comm : forall A B C,\n ~ Col_H A B C -> CongA A B C C B A.\nProof.\nintros.\nrewrite <- cols_coincide in H.\nassert_diffs.\napply conga_pseudo_refl;auto.\nQed.\n\nLemma axiom_congaH_outH_congaH :\n forall A B C D E F A' C' D' F' : Tpoint,\n  CongA A B C D E F ->\n  Between_H B A A' \\/ Between_H B A' A \\/ B <> A /\\ A = A' ->\n  Between_H B C C' \\/ Between_H B C' C \\/ B <> C /\\ C = C' ->\n  Between_H E D D' \\/ Between_H E D' D \\/ E <> D /\\ D = D' ->\n  Between_H E F F' \\/ Between_H E F' F \\/ E <> F /\\ F = F' ->\n  CongA A' B C' D' E F'.\nProof.\nintros.\napply out_conga with A C D F;auto using outH_out.\nQed.\n\nLemma axiom_conga_permlr:\nforall A B C D E F : Tpoint, CongA A B C D E F -> CongA C B A F E D.\nProof.\napply Ch11_angles.conga_comm.\nQed.\n\n(*\nLemma axiom_inter_dec : forall l m,\n  (exists P, IncidentL P l /\\ IncidentL P m) \\/ ~ (exists P, IncidentL P l /\\ IncidentL P m).\nProof.\nintros l m;\nelim (inter_dec (P1 l) (P2 l) (P1 m) (P2 m));\nintro; [left|right]; auto.\nQed.\n*)\n\nLemma axiom_conga_refl : forall A B C, ~ Col_H A B C -> CongA A B C A B C.\nProof.\nintros A B C H.\napply Ch11_angles.conga_refl; intro; subst; apply H; apply cols_coincide; Col.\nQed.\n\nEnd T.\n\nSection Tarski_neutral_to_Hilbert_neutral.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nInstance Hilbert_neutral_follows_from_Tarski_neutral : Hilbert_neutral_dimensionless.\nProof.\nexact (Build_Hilbert_neutral_dimensionless Tpoint Line Plane EqL EqL_Equiv EqP EqP_Equiv IncidentL\n       IncidentP axiom_Incid_morphism axiom_Incid_dec axiom_Incidp_morphism axiom_Incidp_dec\n       eq_dec_points axiom_line_existence axiom_line_uniqueness axiom_two_points_on_line PA\n       PB PC lower_dim' axiom_plane_existence axiom_one_point_on_plane axiom_plane_uniqueness\n       axiom_line_on_plane Between_H axiom_between_diff axiom_between_col axiom_between_comm\n       axiom_between_out axiom_between_only_one axiom_pasch Cong cong_right_commutativity\n       axiom_hcong_1_existence cong_inner_transitivity\n        axiom_hcong_3 CongA axiom_conga_refl axiom_conga_comm\n       axiom_conga_permlr axiom_congaH_outH_congaH axiom_hcong_4_existence\n       axiom_hcong_4_uniqueness axiom_cong_5').\nDefined.\n\nEnd Tarski_neutral_to_Hilbert_neutral.\n\nSection Tarski_neutral_2D_to_Hilbert_neutral_2D.\n\nContext `{T2D:Tarski_2D}.\n\nInstance Hilbert_2D_follows_from_Tarski_2D : Hilbert_neutral_2D Hilbert_neutral_follows_from_Tarski_neutral.\nProof.\nsplit.\nintros A B C l HNCol HNCl Hcut.\napply axiom_pasch with (Plan A B C HNCol); trivial;\n  unfold IncidentLP, IncidentP; intros; try (apply all_coplanar).\nDefined.\n\nEnd Tarski_neutral_2D_to_Hilbert_neutral_2D.\n\nSection Tarski_neutral_3D_to_Hilbert_neutral_3D.\n\nContext `{T3D:Tarski_3D}.\n\nLemma lower_dim_3' : {A : Tpoint & {B : Tpoint & {C : Tpoint & {D |\n  ~ exists p, IncidentP A p /\\ IncidentP B p /\\ IncidentP C p /\\ IncidentP D p}}}}.\nProof.\nexists S1, S2, S3, S4.\nintros [p]; spliter.\napply tarski_axioms.lower_dim_3, plane_cop with p; assumption.\nQed.\n\nInstance Hilbert_3D_follows_from_Tarski_3D : Hilbert_neutral_3D Hilbert_neutral_follows_from_Tarski_neutral.\nProof.\ndestruct lower_dim_3' as [A [B [C [D n]]]].\nexists A B C D; [|assumption].\nclear A B C D n.\nintros A p q HAp HAq.\ndestruct p as [P1 P2 P3 HP].\ndestruct q as [Q1 Q2 Q3 HQ].\nunfold IncidP in *; simpl in *; unfold IncidentP in *; simpl in *.\nassert (pi : plane_intersection_axiom).\ncut upper_dim_3_axiom.\napply upper_dim_3_equivalent_axioms; simpl; tauto.\nunfold upper_dim_3_axiom.\napply upper_dim_3.\napply pi; assumption.\nDefined.\n\nEnd Tarski_neutral_3D_to_Hilbert_neutral_3D.\n\nSection Tarski_Euclidean_to_Hilbert_Euclidean.\n\nContext `{TE:Tarski_euclidean}.\n\n(** * Group Parallels *)\n\nDefinition Para := fun l m =>\n  (~ exists X, IncidentL X l /\\ IncidentL X m) /\\ exists p, IncidentLP l p /\\ IncidentLP m p.\n\nLemma Para_Par : forall A B C D (HAB : A<>B) (HCD: C<>D),\n Para (Lin A B HAB) (Lin C D HCD) -> Par A B C D.\nProof.\nunfold Para, IncidentL, Par, Par_strict; simpl.\nintros.\ndestruct H as [HNI [p []]].\nleft.\nrepeat split;auto.\napply plane_cop with p; [apply H|apply H|apply H0..]; unfold IncidentL; simpl; Col.\nQed.\n\nLemma axiom_euclid_uniqueness :\n  forall l P m1 m2,\n  ~ IncidentL P l ->\n   Para l m1 -> IncidentL P m1 ->\n   Para l m2 -> IncidentL P m2 ->\n   EqL m1 m2.\nProof.\nintros.\ndestruct l as [A B HAB].\ndestruct m1 as [C D HCD].\ndestruct m2 as [C' D' HCD'].\nunfold IncidentL in *;simpl in *.\napply Para_Par in H0.\napply Para_Par in H2.\nelim (tarski_s_euclid_implies_playfair euclid A B C D C' D' P H0 H1 H2 H3);intros.\napply axiom_line_uniqueness with C' D';\nunfold IncidentL;simpl;Col.\nQed.\n\nInstance Hilbert_euclidean_follows_from_Tarski_euclidean :\n  Hilbert_euclidean Hilbert_neutral_follows_from_Tarski_neutral.\nProof.\nsplit.\napply axiom_euclid_uniqueness.\nDefined.\n\nInstance Hilbert_euclidean_ID_follows_from_Tarski_euclidean :\n  Hilbert_euclidean_ID Hilbert_euclidean_follows_from_Tarski_euclidean.\nProof.\nsplit.\nintros l m.\nassert (ID : decidability_of_intersection).\napply strong_parallel_postulate_implies_inter_dec.\ncut tarski_s_parallel_postulate.\napply equivalent_postulates_without_decidability_of_intersection_of_lines_bis; simpl; tauto.\nunfold tarski_s_parallel_postulate.\napply euclid.\ndestruct l as [L1 L2 HL].\ndestruct m as [M1 M2 HM].\nsimpl; unfold IncidentL; simpl.\napply ID.\nDefined.\n\nEnd Tarski_Euclidean_to_Hilbert_Euclidean.", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/GeoCoq/Meta_theory/Models/tarski_to_hilbert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6807490904302459}}
{"text": "(** This file provides a direct formalizatoin of Girard's paradox, as explained in Martin-Lof's 1972\n\"An intuitionistic theory of types\". It can serve as a test as to whether the version of Coq being\nused is (in the most obvious way) inconsistent. **)\n\nRequire Import UniMath.Foundations.All.\nRequire Export UniMath.Tactics.EnsureStructuredProofs.\n\n(* This section has an arbitrary type instead of False *)\nSection girard.\n\nVariable Flse : Type.\n\n(* an \"ordering without infinite descending chains\" (wf is for \"well-founded\") *)\nDefinition wf (T : Type) : Type\n  := ∑ lt : T -> T -> Type,\n            (∏ x y z: T, lt x y -> lt y z -> lt x z) ×\n            (∏ h : (nat -> T), (∏ n : nat, lt (h (S n)) (h n)) -> Flse).\n\n(* the type of such orderings *)\nDefinition wfs : Type := total2 wf.\n\n(* the underyling set *)\nDefinition uset (w : wfs) : Type := pr1 w.\n(* the underlying order *)\nDefinition uord (w : wfs) : uset w -> uset w -> Type := pr1 (pr2 w).\n(* the transitivity property *)\nDefinition trans (w : wfs) {x y z : uset w}\n  : pr1 (pr2 w) x y → pr1 (pr2 w) y z → pr1 (pr2 w) x z\n  := pr1 (pr2 (pr2 w)) x y z.\n(* the well-foundedness property *)\nDefinition wfp (w : wfs) :\n  (λ _ : ∏ x y z : pr1 w, pr1 (pr2 w) x y → pr1 (pr2 w) y z → pr1 (pr2 w) x z,\n                   ∏ h : nat → pr1 w, (∏ n : nat, pr1 (pr2 w) (h (S n)) (h n)) → Flse) (pr1 (pr2 (pr2 w)))\n  := pr2 (pr2 (pr2 w)).\n\n(* the order on wfs: an order-preserving function on underlying sets and an\n   element of the second set which dominates the image *)\nDefinition wfs_wf_uord (v : wfs) (w : wfs) : Type\n  := ∑ f : uset v -> uset w,\n           (∏ x y : uset v, (uord v) x y -> (uord w) (f x) (f y)) ×\n           (∑ y : uset w, ∏ (x: uset v), (uord w) (f x) y).\n\n(* the underlying function *)\nDefinition ufun {v : wfs} {w : wfs} (a : wfs_wf_uord v w) : uset v → uset w := pr1 a.\n(* the homomorpshim property *)\nDefinition homo {v : wfs} {w : wfs} (a : wfs_wf_uord v w)\n  : ∏ (x y : uset v), uord v x y → uord w (pr1 a x) (pr1 a y)\n  := pr1 (pr2 a).\n(* the dominating element *)\nDefinition domi {v : wfs} {w : wfs} (a : wfs_wf_uord v w) : uset w := pr1 (pr2 (pr2 a)).\n(* the relation comparing the dominating element to the various images *)\nDefinition domicom {v : wfs} {w : wfs} (a : wfs_wf_uord v w)\n  : (λ y : uset w, ∏ x : uset v, uord w (pr1 a x) y) (pr1 (pr2 (pr2 a)))\n  := pr2 (pr2 (pr2 a)).\n\n(* transitivty of the ordering on wfs *)\nDefinition wfs_wf_trans : forall x y z : wfs, wfs_wf_uord x y -> wfs_wf_uord y z -> wfs_wf_uord x z.\nProof.\n  intros x y z.\n  intros f g.\n  exists (fun a : uset x => (ufun g) ((ufun f) a)).\n  split.\n  + intros x0 y0.\n    intro x0y0.\n    exact (homo g _ _ (homo f _ _ x0y0)).\n  + exists (domi g).\n    intro x0.\n    set (y0 := ufun f x0).\n    set (ydom := domi f).\n    set (co := domicom f x0).\n    exact (trans z (homo g _ _ co) (domicom g (domi f))).\nDefined.\n\n(* the following three definitions and lemmas are for showing that wfs_wf_uord is well founded *)\n\n(* given a descending sequence f : nat -> wfs, map each f(n) to f(0) by composing all the maps *)\n\nDefinition wfs_wf_wfp_shift (f : nat -> wfs) (b : ∏ n : nat, wfs_wf_uord (f (S n)) (f n)) :\n  ∏ (n : nat), (uset (f n) -> uset (f 0)).\nProof.\n  intro n.\n  induction n.\n  - intro a; exact a.\n  - intro x.\n    exact (IHn (ufun (b n) x)).\nDefined.\n\n(* thus obtain a sequence in (f 0) *)\nDefinition wfs_wf_wfp_seq (f : nat -> wfs) (b : ∏ n : nat, wfs_wf_uord (f (S n)) (f n)) :\n  nat -> uset (f 0).\nProof.\n  intro n.\n  exact (wfs_wf_wfp_shift f b n (domi (b n))).\nDefined.\n\n(* obtain comparisons between the shifted elements *)\nDefinition wfs_wf_wfp_compshift (f : nat -> wfs) (b : ∏ n : nat, wfs_wf_uord (f (S n)) (f n)) :\n  ∏ (n : nat) {x y : uset (f n)},\n    uord (f n) x y -> uord (f 0) (wfs_wf_wfp_shift f b n x) (wfs_wf_wfp_shift f b n y).\nProof.\n  intros n.\n  induction n.\n  - intros x y p.\n    exact p.\n  - intros x y p.\n    exact (IHn _ _ (homo (b n) x y p)).\nQed.\n\n(* show that the resulting sequence on (f 0) is descending *)\nLemma wfs_wf_wfp_desc (f : nat -> wfs) (b : forall n : nat, wfs_wf_uord (f (S n)) (f n)) :\n  ∏ n : nat, uord (f 0) (wfs_wf_wfp_seq f b (S n)) (wfs_wf_wfp_seq f b n).\nProof.\n  intro n.\n  exact (wfs_wf_wfp_compshift f b n (domicom (b n) (domi (b (S n))))).\nDefined.\n\n(* the wf on wfs *)\nDefinition wfs_wf : wf wfs.\nProof.\n  exists wfs_wf_uord.\n  split.\n  - exact wfs_wf_trans.\n  - intro h.\n    intro b.\n    exact (wfp _ (wfs_wf_wfp_seq h b) (wfs_wf_wfp_desc  h b)).\nDefined.\n\n(* the wf on wfs as an element of wfs *)\nDefinition wfs_wf_t : wfs := tpair (fun T => wf T) wfs (wfs_wf).\n\n(* this definition and the following three lemmas show that wfs_wf has a maximal element *)\n\n(* function mapping each wf to the set of wfs (by taking inital segments) *)\nDefinition maxi_fun (w : wfs) : uset w -> wfs.\nProof.\n  intro x.\n  exists (∑ y : uset w, uord w y x).\n  exists (fun a b => uord w (pr1 a) (pr1 b)).\n  split.\n  - intros x0 y z p q.\n    exact (trans w p q).\n  - intro h.\n    intro b.\n    exact (wfp w (fun n => pr1 (h n)) b).\nDefined.\n\n(* maxi_fun preserves the order *)\nLemma maxi_homo (w : wfs) : ∏ (x y : uset w),\n    uord w x y -> wfs_wf_uord (maxi_fun w x) (maxi_fun w y).\nProof.\n  intros x y p.\n  exists (fun (z : uset (maxi_fun w x)) => tpair _ (pr1 z) (trans w (pr2 z) p)).\n  split.\n  - intros x0 y0 q.\n    exact q.\n  - exists (tpair _ x p).\n    intro x0.\n    exact (pr2 x0).\nDefined.\n\n(* w itself dominates the image of w under maxi_fun *)\nLemma maxidom (w : wfs) : ∏ (x : uset w), wfs_wf_uord (maxi_fun w x) w.\nProof.\n  intro x.\n  exists (fun (z : uset (maxi_fun w x)) => pr1 z).\n  split.\n  - intros x0 y p.\n    exact p.\n  - exists x.\n    intro x0.\n    exact (pr2 x0).\nDefined.\n\n(* wfs_wf_t is maximal with respect to wfs_wf *)\nLemma maxi (w : wfs) : wfs_wf_uord w wfs_wf_t.\nProof.\n  exists (maxi_fun w).\n  split.\n  - exact (maxi_homo w).\n  - exact (tpair _ _ (maxidom w)).\nDefined.\n\n(* in particular wfs_wf_t is greather than itself *)\nProposition whoa : uord wfs_wf_t wfs_wf_t wfs_wf_t.\nProof.\n  apply maxi.\nDefined.\n\n(* but wfs are irreflexive *)\nProposition irref (w : wfs) : ∏ (x : uset w), (uord w) x x -> Flse.\nProof.\n  intro x.\n  intro p.\n  exact (wfp w (fun n => x) (fun n => p)).\nDefined.\n\n(* therefore the world explodes *)\nProposition the_world_explodes : Flse.\nProof.\n  exact (irref wfs_wf_t wfs_wf_t whoa).\nDefined.\n\nEnd girard.\n\n(* especially if Flse=False *)\nProposition but_seriously_the_world_explodes : empty.\n  exact (the_world_explodes empty).\nDefined.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/Paradoxes/GirardsParadox.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.680622200522859}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra.\nRequire Import extra_mathcomp.\n\nImport Order.TTheory GRing.Theory Num.Theory.\n\nLocal Notation \"s `_ i\" := (nth 0 s i) : nat_scope.\n\n(* For n_1, ..., n_k, and n := n_1 + ... + n_k, the multinomial (n | n_1, ... n_k) is\nthe coefficient of the monomial x_1 ^ n_1 ... x_k ^n_k in the expansion of\n(x_1 + ... + x_k)^n. It can also be defined as n! /(n_1!... n_k!) or as the product\n(bin n_1 n_2) (bin (n_1 + n_2) n_2)... (bin n n_k) *)\n\n(* Shall we obtain this from a more computational friendly\n  definition? One day, may be, if needed. *)\nDefinition multinomial (l : seq nat) : nat :=\n \\prod_(0 <= i < size l) (binomial (\\sum_(0 <= j < i.+1) l`_j) l`_i).\n\nArguments multinomial l : simpl never.\n\n(* Notation under evaluation ... *)\nNotation \"''C' [ l ]\" := (multinomial l)\n  (at level 8, format \"''C' [ l ]\") : nat_scope.\n\n(* For instance I would like to avoid double brackets, like in: *)\nCheck 'C[[::]].\nCheck 'C[[:: 8]].\n\n(* Unlocking is needed for computation and for convertibility. *)\nExample foo : multinomial [::1;2] = 3.\nby rewrite /multinomial /binomial unlock.\nQed.\n\nLemma multi_nil : 'C[[::]] = 1.\nProof. by rewrite /multinomial big_nil. Qed.\n\nLemma multi_singl n : 'C[[:: n]] = 1.\nProof.\nby rewrite /multinomial; do 2! (rewrite !big_mkord /= big_ord1 /=); rewrite binn.\nQed.\n\nLemma multi_gt0 l : 'C[l] > 0.\nProof. by apply: prodn_gt0 => i; rewrite bin_gt0 big_nat_recr //= leq_addl. Qed.\n\nLemma multi_rcons n l :\n'C[rcons l n] = 'C[l] * 'C(\\sum_(j <- l) j + n, n).\nProof.\nrewrite [in LHS]/multinomial [in RHS](big_nth 0) size_rcons !big_nat_recr //=.\nhave -> : (rcons l n)`_(size l) = n by rewrite nth_rcons ltnn eqxx.\nhave aux k : 0 <= k < size l -> (rcons l n)`_k = l`_k.\n  by rewrite nth_rcons; case/andP=> _ ->.\nrewrite !big_nat (eq_bigr _ aux) -big_nat; congr (_ * _); rewrite /multinomial.\nrewrite !big_nat; apply: eq_bigr => i ?; rewrite aux // !big_nat; congr 'C(_, _).\nby apply: eq_bigr=> j /andP[le0j leji]; rewrite aux // le0j (leq_trans leji).\nQed.\n\nLemma multi_prod_fact l : 'C[l] * \\prod_(j <- l) j`! = (\\sum_(j <- l) j)`!.\nProof.\nelim/last_ind: l => [| l n ihl]; first by rewrite multi_nil !big_nil.\nset p := \\prod_(_ <- _) _; set s := \\sum_(_ <- _) _.\nrewrite multi_rcons mulnAC.\nhave aux : (rcons l n)`_(size l) = n by rewrite nth_rcons ltnn eqxx.\nhave -> : p = \\prod_(j <- l) j`! * n`! by rewrite /p -cats1 big_cat /= big_seq1.\nrewrite mulnA ihl.\nhave es : s = \\sum_(j <- l) j + n by rewrite /s -cats1 big_cat /= big_seq1.\nrewrite -es mulnC [X in _ * X = _]mulnC.\nhave -> : \\sum_(j <- l) j = s - n by rewrite es addnK.\nby rewrite bin_fact // es leq_addl.\nQed.\n\nNotation \"'BIG_op_F' op\" :=\n  (F in  \\big[op/_]_(i <- _ | _) F i)%pattern (at level 36).\n\nNotation \"'BIG_op_P' op\" :=\n  (P in  \\big[op/_]_(i <- _ | P i) _)%pattern (at level 36).\n\n\n(* For the sake of compatibility with hanson.\nNote that the sum and prod should be moved to a \\sum_(j <- l)_ shape. *)\nLemma eq_def_multiQ l :\n  ('C[l]%:Q =\n   (\\sum_(0 <= i < size l) l`_i)`!%:Q /\n   (\\prod_(0 <= i < size l) (l`_i)`!)%N%:Q)%R.\nProof.\nhave dn0 : ((\\prod_(i <- l) i `!)%N%:Q != 0)%R.\n  rewrite pnatr_eq0 -lt0n prodn_gt0 // => i; exact: fact_gt0.\nrewrite -(big_nth 0 xpredT) -(big_nth 0 xpredT id). (* booh *)\nby rewrite -multi_prod_fact !PoszM !rmorphM /= mulfK.\nQed.\n\n(* Because it is basically mulnK *)\nLemma whyIsThisNotProved (m d n : nat) : 0 < d -> m * d = n -> m = n %/ d.\nProof. by move=> d_gt0 <-; rewrite mulnK. Qed.\n\n(* Compatiblity again. *)\nLemma eq_def_multi1 (l : list nat) :\n'C[l] * \\prod_(0 <= i < size l) (l`_i)`! = (\\sum_(0 <= i < size l) l`_i)`!.\nProof.\nrewrite -(big_nth 0 xpredT) -(big_nth 0 xpredT id). (* booh *)\nexact: multi_prod_fact.\nQed.\n\nLocal Open Scope ring_scope.\n\nSection Monomials.\n\nContext  {R : unitRingType}.\n\n\nDefinition monomial (x : seq R) (e : seq nat) :=\n  \\prod_(xi <- zip x e) xi.1 ^ xi.2.\n\n\n(* Definition monomial {n : nat} (x : seq R) (e : seq 'I_n) := *)\n(*   \\prod_(xi <- zip x e) xi.1 ^ xi.2. *)\n\n\n(* Definition monomial {R : unitRingType} {n : nat} (x : seq R) (e : seq 'I_n) := *)\n(*   \\prod_(0 <= i < size x) (nth 0 x i) ^ (nth 0%N (map (@nat_of_ord n) e) i). *)\n\n\nLemma monom_nill e : monomial [::] e = 1.\nProof. by rewrite /monomial zip_nil_l big_nil. Qed.\n\nLemma monom_nilr (x : seq R) : monomial x [::] = 1.\nProof. by rewrite /monomial zip_nil_r big_nil. Qed.\n\nLemma monom_rcons (a : R) (x : seq R) i e :\n  size x = size e -> monomial (rcons x a) (rcons e i) = (monomial x e) * a ^ i.\nProof. by move => Hxe; rewrite /monomial !zip_rcons // big_rcons. Qed.\n\nEnd Monomials.\n\n\nDefinition tmap_val {n m} (t : n.-tuple 'I_m) : seq nat :=\n  [seq val j | j <- t].\n\nLemma tmap_val_rcons  {n m} (t : n.-tuple 'I_m) i :\n  tmap_val [tuple of rcons t i] = rcons (tmap_val t) i.\nProof. by rewrite /tmap_val map_rcons. Qed.\n\nSection GNewton.\n\nContext  {R : comUnitRingType}.\n\n\nLemma generalizedNewton (l : seq R) (n m : nat) (s := size l) :\n  (n <= m)%N ->\n  (\\sum_(x <- l) x) ^+ n =\n  \\sum_(t : s.-tuple 'I_m.+1 | (\\sum_(i <- t) i)%N == n)\n   ('C[tmap_val t])%:R * monomial l (tmap_val t).\nProof.\nrewrite {}/s; elim/last_ind: l n m => [|l a ihl] n m /=.\n- rewrite big_tuple0 big_nil big_tuple big_ord0 /= monom_nill mulr1 /= expr0n.\n  by rewrite multi_nil; case: n.\n- move=> leqnm; rewrite size_rcons big_rcons /= exprDn.\n  set s := size l.\n  pose tlast s (t : s.-tuple 'I_m.+1) := last ord0 t.\n  have -> P F :\n   \\sum_(t : s.+1.-tuple 'I_m.+1 | P t) F t =\n   \\sum_(j < m.+1) \\sum_(t | P t && (tlast _ t == j)) F t.\n     exact: partition_big.\n  pose F (i : nat) := (\\sum_(j <- l) j) ^+ (n - i) * a ^+ i *+ 'C(n, i).\n  have -> : \\sum_(i < n.+1) F i = \\sum_(i < m.+1 | (i < n.+1)%N) F i.\n    by apply: big_ord_widen; rewrite ltnS.\n  rewrite big_mkcond /=; apply: eq_bigr => i _; case: ltnP=> hni; last first.\n    rewrite /tlast big_pred0 // => [[]]; case/lastP => // t u stu /=.\n    rewrite last_rcons big_rcons /=.\n    by apply: contraTF hni; case/andP=> /eqP<- /eqP<-; rewrite -leqNgt leq_addl.\n  rewrite {}/F.\n  have /ihl -> : (n - i <= m)%N.\n    by apply: (leq_trans (leq_subr _ _)); apply: (leq_trans leqnm).\n  rewrite mulr_suml -sumrMnl.\n  pose tsum a (t : a.-tuple 'I_m.+1) b := ((\\sum_(j <- t) j) == b)%N.\n  have -> F :\n  \\sum_(t : s.+1.-tuple 'I_m.+1 | tsum _ t n && (tlast _ t == i)) F t =\n  \\sum_(t : s.-tuple 'I_m.+1    | tsum _ t (n - i)%N) F [tuple of (rcons t i)].\n    pose indx (t : s.-tuple 'I_m.+1) := [tuple of rcons t i].\n    pose indxV (t : s.+1.-tuple 'I_m.+1) := [tuple of rev (behead (rev t))].\n    rewrite [LHS](reindex indx) /= /tlast /tsum.\n       apply: eq_bigl => t; rewrite last_rcons eqxx andbT big_rcons /=.\n       apply/eqP/eqP=> [|->]; first exact: (canRL (addnK i)).\n       by rewrite subnK.\n    exists indxV => t ht; rewrite /indx /indxV /=; apply: val_inj => /=.\n      by rewrite rev_rcons revK.\n    move: ht; rewrite inE; case/andP=> _; case: t; case/lastP => //= ? j _.\n    by rewrite last_rcons => /eqP->; rewrite rev_rcons /= revK.\n  symmetry; apply: congr_big => //= u /eqP es /=.\n  rewrite tmap_val_rcons multi_rcons natrM mulrAC monom_rcons; last first.\n    by rewrite size_map size_tuple.\n  by rewrite /tmap_val big_map es exprnP mulr_natr -mulrA subnK.\nQed.\n\n\nEnd GNewton.\n\nSection MultinomialIneq.\n\nContext  {R : comUnitRingType}.\n\nLocal Open Scope nat_scope.\n\nLemma multinomial_ineq (l : seq nat) (p :=  \\prod_(j <- l) j ^ j) (s := \\sum_(j <- l) j) :\n  'C[l] * p <= s ^ s.\nProof.\n  rewrite -lez_nat -!natz natrX natrM natr_sum.\n  pose lz : seq int := [seq i%:R | i <- l].\n  have -> : (\\sum_(i <- l) i%:R = \\sum_(i <- lz) i)%R by rewrite big_map.\n  pose m := s; pose n := s.\n  have /generalizedNewton -> : n <= m by [].\n  have paux (i : 'I_(size l)) : nth 0 l i < m.+1.\n    rewrite ltnS /m /s.\n    have /(big_rem _) -> /= : (nth 0 l i) \\in l by rewrite mem_nth.\n    exact: leq_addr.\n  pose aux (i : 'I_(size l)) := Ordinal (paux i).\n  pose tl := mktuple aux.\n  have Heq : tmap_val tl = l.\n    suff Heq1 (i : 'I_(size l)) : nth 0 (tmap_val tl) i = nth 0 l i.\n      apply: (@eq_from_nth nat 0 _ _); rewrite size_map size_tuple // .\n      move => i Hisize.\n      suff -> : nth 0 (tmap_val tl) (Ordinal Hisize) = nth 0 l (Ordinal Hisize) by [].\n      exact: Heq1.\n    by rewrite (nth_map ord0 0) /tl ?size_tuple ?(nth_mktuple aux ord0 i).\n  rewrite /lz size_map; set P := BIG_P.\n  have /(bigD1 _) -> /= : P tl.\n    rewrite /P /n /s big_tuple big_tnth /=; apply/eqP/eq_bigr => i _.\n    by rewrite tnth_mktuple /aux /= (tnth_nth 0) in_tupleE.\n  suff {P} -> : (('C[l])%:R * p%:R =\n     ('C[tmap_val tl])%:R * monomial [seq i%:R | i <- l] (tmap_val tl) :> int)%R.\n  rewrite cpr_add; apply: sumr_ge0 => i _; apply: mulr_ge0.\n  - by rewrite ler0n.\n  - rewrite /monomial big_seq_cond.\n    apply: prodr_ge0 => j; rewrite andbT => /nth_index hj.\n    rewrite -(hj (1 : int, 0%N)) nth_zip /=; last first.\n      by rewrite !size_map size_tuple.\n    rewrite exprn_ge0 //.\n    set ll := (X in (0 <= nth _ X _)%R); set k := index _ _.\n    case: (ltnP k (size ll)) => [/mem_nth |] hk.\n      suff ll_pos x : x \\in ll -> (0 <= x)%R by apply: ll_pos.\n      rewrite /ll; case/mapP => u _ ->; exact: ler0n.\n    by rewrite nth_default.\n  congr (_ * _)%R.\n  - apply/eqP; rewrite eqr_nat.\n    by rewrite Heq.\n  - rewrite /monomial /p Heq natr_prod.\n    suff -> : zip [seq i%:R | i <- l] l = map (fun i => (Posz i,i)) l.\n      rewrite big_map.\n      by apply: eq_bigr => i _ /=; first by rewrite natrX -exprnP -natz.\n    apply: (@eq_from_nth _ (0%:R,0));rewrite size_zip !size_map minnn// => i Hi.\n    rewrite nth_zip ?size_map // ; rewrite (nth_map 0 (Posz 0)) // .\n    by rewrite (nth_map 0 (Posz 0,0)) // natz.\nQed.\n\nEnd MultinomialIneq.\n", "meta": {"author": "coq-community", "repo": "apery", "sha": "305046d98025d75ca426cc44283302963389f1dc", "save_path": "github-repos/coq/coq-community-apery", "path": "github-repos/coq/coq-community-apery/apery-305046d98025d75ca426cc44283302963389f1dc/theories/multinomial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6806221898523425}}
{"text": "Require Import Coq.Init.Prelude.\n\nFixpoint fnd (n : nat) : Prop :=\n  match n with\n  | O => True\n  | S n => True /\\ fnd n\n  end.\n\nFixpoint big_and (xs : list Prop) : Prop :=\n  match xs with\n  | nil => True\n  | cons x xs => and x (big_and xs)\n  end.\nFixpoint typeof_big_conj (xs : list Prop) (P : Prop) : Prop :=\n  match xs with\n  | nil => P\n  | cons x xs => x -> typeof_big_conj xs P\n  end.\nLemma apply_rconj_and xs (P Q : Prop) : P -> typeof_big_conj xs Q -> typeof_big_conj xs (P /\\ Q).\nProof. revert Q; revert P; induction xs; intros; cbn in *; eauto. Qed.\nLemma big_conj xs : typeof_big_conj xs (big_and xs).\nProof. induction xs. exact I. cbn. intros. apply apply_rconj_and; eauto. Qed.\n\nRequire Import Coq.Lists.List.\n\nGoal fnd 10000.\n  Time\n  let n := match goal with |- fnd ?n => n end in\n  let ls := eval cbv in (repeat True n) in\n  let pf := constr:(big_conj ls) in\n  let T := type of pf in\n  let T := eval cbv [typeof_big_conj big_and] in T in\n  refine (let H : T := pf in _).\n  Time clearbody H.\n  Time apply H; exact I.\nTime Qed.\n(*\nFinished transaction in 3.028 secs (2.946u,0.067s) (successful)\nFinished transaction in 0.001 secs (0.001u,0.s) (successful)\nFinished transaction in 21.168 secs (21.078u,0.017s) (successful)\nFinished transaction in 3.405 secs (3.397u,0.s) (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_and_10000_true.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6806221844105665}}
{"text": "Require Export Coq.Unicode.Utf8.\nRequire Export FSubProd.\n\n(******************************************************************************)\n(* Subtyping relation                                                         *)\n(******************************************************************************)\n\nInductive Sub (Γ: Env) : Ty → Ty → Prop :=\n  | SA_Top {S} (wf_S: wfTy (domainEnv Γ) S) :\n      Sub Γ S top\n  | SA_Refl_TVar {X} :\n      wfindex (domainEnv Γ) X → Sub Γ (tvar X) (tvar X)\n  | SA_Trans_TVar {X T U} :\n      lookup_etvar Γ X U → Sub Γ U T → Sub Γ (tvar X) T\n  | SA_Arrow {T1 T2 S1 S2} :\n      Sub Γ T1 S1 → Sub Γ S2 T2 → Sub Γ (tarr S1 S2) (tarr T1 T2)\n  | SA_All {T1 T2 S1 S2} :\n      Sub Γ T1 S1 → Sub (etvar Γ T1) S2 T2 → Sub Γ (tall S1 S2) (tall T1 T2)\n  | SA_Prod {T1 T2 S1 S2} :\n      Sub Γ S1 T1 → Sub Γ S2 T2 →\n      Sub Γ (tprod S1 S2) (tprod T1 T2).\n\n(******************************************************************************)\n(* Typing relation.                                                           *)\n(******************************************************************************)\n\nInductive PTyping (Γ: Env) : Pat → Ty → Env → Prop :=\n  | P_Var {T} (wT: wfTy (domainEnv Γ) T) :\n      PTyping Γ (pvar T) T (evar empty T)\n  | P_Prod {p1 T1 Δ1 p2 T2 Δ2} :\n      PTyping Γ p1 T1 Δ1 →\n      PTyping (appendEnv Γ Δ1) (weakenPat p2 (domainEnv Δ1))\n        (weakenTy T2 (domainEnv Δ1)) Δ2 →\n      PTyping Γ (pprod p1 p2) (tprod T1 T2) (appendEnv Δ1 Δ2).\n\nInductive Typing (Γ: Env) : Tm → Ty → Prop :=\n  | T_Var {y T} :\n      lookup_evar Γ y T → Typing Γ (var y) T\n  | T_Abs {t T1 T2} (wf_T1: wfTy (domainEnv Γ) T1) :\n      Typing (evar Γ T1) t T2 →\n      Typing Γ (abs T1 t) (tarr T1 T2)\n  | T_App {t1 t2 T11 T12} :\n      Typing Γ t1 (tarr T11 T12) → Typing Γ t2 T11 →\n      Typing Γ (app t1 t2) T12\n  | T_Tabs {t T1 T2} (wf_T1: wfTy (domainEnv Γ) T1) :\n      Typing (etvar Γ T1) t T2 →\n      Typing Γ (tabs T1 t) (tall T1 T2)\n  | T_Tapp {t1 T11 T12 T2} :\n      Typing Γ t1 (tall T11 T12) → Sub Γ T2 T11 →\n      Typing Γ (tapp t1 T2) (tsubstTy X0 T2 T12)\n  | T_Prod {t1 T1 t2 T2} :\n      Typing Γ t1 T1 → Typing Γ t2 T2 →\n      Typing Γ (prod t1 t2) (tprod T1 T2)\n  | T_Let {p t1 t2 T1 T2 Δ} :\n      Typing Γ t1 T1 → PTyping Γ p T1 Δ →\n      Typing (appendEnv Γ Δ) t2 (weakenTy T2 (domainEnv Δ)) →\n      Typing Γ (lett p t1 t2) T2\n  | T_Sub {t T1 T2} :\n      Typing Γ t T1 → Sub Γ T1 T2 →\n      Typing Γ t T2.\n", "meta": {"author": "skeuchel", "repo": "metatheory", "sha": "d0df292cbd764f8afeba088e1c9459f0a4298b47", "save_path": "github-repos/coq/skeuchel-metatheory", "path": "github-repos/coq/skeuchel-metatheory/metatheory-d0df292cbd764f8afeba088e1c9459f0a4298b47/fsubprod/DeclarationTyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.680622179555575}}
{"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(****************************************************************************)\n(*                                                                          *)\n(*                                                                          *)\n(*                Solange Coupet-Grimal & Line Jakubiec-Jamet               *)\n(*                                                                          *)\n(*                                                                          *)\n(*             Laboratoire d'Informatique Fondamentale de Marseille         *)\n(*                   CMI et Faculté des Sciences de Luminy                  *)\n(*                                                                          *)\n(*           e-mail:{Solange.Coupet,Line.Jakubiec}@lif.univ-mrs.fr          *)\n(*                                                                          *)\n(*                                                                          *)\n(*                            Developped in Coq v6                          *)\n(*                            Ported to Coq v7                              *)\n(*                            Translated to Coq v8                          *)\n(*                                                                          *)\n(*                             July 12nd 2005                               *)\n(*                                                                          *)\n(****************************************************************************)\n(*                            Lib_Div_Even_Odd.v                            *)\n(****************************************************************************)\n\n\nRequire Export Lib_Mult.\n\n(****************************** even/odd *********************************)\n\nInductive even (n : nat) : Prop :=\n    even_intro : forall q : nat, n = 2 * q -> even n.\n\nInductive odd (n : nat) : Prop :=\n    odd_intro : forall q : nat, n = 2 * q + 1 -> odd n.\n\n\n(************************* quotients and divisors ***********************)\n\nLemma no_zero_div :\n forall n m : nat, 0 < n -> forall q : nat, n = m * q -> 0 < q.\nsimple induction q.\nintro.\nabsurd (0 = n).\napply lt_O_neq; auto with arith.\nrewrite (mult_n_O m); auto with arith.\nauto with arith.\nQed.\n\n\n\nLemma lt_quotient2_n :\n forall n : nat, 0 < n -> forall q : nat, n = 2 * q -> q < n.\nintros.\nrewrite (plus_n_O q).\nrewrite H0.\nelim plus_mult.\napply plus_lt_compat_l.\napply (no_zero_div n 2 H q H0).\nQed. \nHint Immediate lt_quotient2_n.\n\n\n\nLemma less_div : forall n a b : nat, 0 < n -> n = a * b -> b <= n.\nintros.\nrewrite H0.\nelim (mult_O_le b a); auto with arith.\nintro.\nabsurd (n = 0).\nunfold not in |- *; intro.\nelim (lt_irrefl n).\npattern n at 1 in |- *.\nrewrite H2; auto with arith.\nrewrite H0.\nrewrite H1; auto with arith.\nQed.\n\n\nLemma even_or_odd : forall n : nat, {even n} + {odd n}.\nsimple induction n.\nleft; apply (even_intro 0 0); auto with arith.\nintros y hrec.\nelim hrec.\nintro eveny.\nright; elim eveny.\nintros q hy; apply (odd_intro (S y) q).\nelim hy.\nelim plus_n_Sm.\nauto.\nintro oddy; left.\nelim oddy.\nintros q hy; apply (even_intro (S y) (S q)).\nrewrite hy.\nrewrite plus_n_Sm.\nelim (mult_comm (S q) 2).\nelim (mult_comm q 2).\nelim plus_comm.\nauto.\nQed.\n\n\n\nLemma even_odd : forall a : nat, even a -> ~ odd a.\nunfold not in |- *; intros.\nelim H0; elim H.\nintros k1 evena k2 odda.\napply (le_Sn_n 1).\napply (less_div 1 (k1 - k2) 2); auto with arith.\nrewrite mult_comm.\nreplace (2 * (k1 - k2)) with (2 * k1 - 2 * k2).\nelim evena.\nrewrite odda.\nauto with arith.\nelim mult_comm.\nreplace (2 * k1) with (k1 * 2).\n2: apply mult_comm.\nreplace (2 * k2) with (k2 * 2).\n2: apply mult_comm.\n(*Rewrite (mult_minus_distr k1 k2 (S(S O))).*)\nelim (mult_comm 2 k1); elim (mult_comm 2 k2).\napply sym_equal; auto with arith.\nQed.\n\n\n\nLemma odd_even : forall a : nat, odd a -> ~ even a.\nunfold not in |- *; intros.\napply (even_odd a H0).\nauto with arith.\nQed.\n\n\n(********************** S,pred,plus,odd and even ************************)\n\nLemma plus_even_even : forall a b : nat, even a -> even b -> even (a + b).\nintros.\nelim H0; elim H.\nintros.\nrewrite H2; rewrite H1.\nelim (mult_plus_distr_left q q0 2).\napply (even_intro (2 * (q + q0)) (q + q0)).\nauto with arith.\nQed.\n\n\n\nLemma S_odd_even : forall a : nat, odd a -> even (S a).\nintros.\nelim H; intros.\nrewrite H0.\nrewrite (plus_n_Sm (2 * q) 1).\napply (plus_even_even (2 * q) 2).\napply (even_intro (2 * q) q); auto.\napply (even_intro 2 1).\nauto with arith.\nQed.\n\n\n\nLemma pred_odd_even : forall a : nat, odd a -> even (pred a).\nintros.\nelim H; intros.\nrewrite H0.\nelim (plus_n_Sm (2 * q) 0).\nelim (pred_Sn (2 * q + 0)).\nelim (plus_n_O (2 * q)).\napply (even_intro (2 * q) q); auto with arith.\nQed.\n\n\n\nLemma plus_even_odd : forall a b : nat, even a -> odd b -> odd (a + b).\nintros.\nelim H0; elim H; intros.\nrewrite H2; rewrite H1.\nrewrite (plus_assoc (2 * q) (2 * q0) 1).\nelim (mult_plus_distr_left q q0 2).\napply (odd_intro (2 * (q + q0) + 1) (q + q0)).\nauto with arith.\nQed.\nHint Immediate plus_even_odd.\n\n\n\nLemma plus_odd_even : forall a b : nat, odd a -> even b -> odd (a + b).\nintros.\nrewrite plus_comm.\nauto with arith.\nQed.\n\n\n\nLemma S_even_odd : forall a : nat, even a -> odd (S a).\nintros.\nelim H; intros.\nrewrite H0.\napply (odd_intro (S (2 * q)) q).\nelim (plus_n_Sm (2 * q) 0).\nauto with arith.\nQed.\n\n\n\nLemma plus_odd_odd : forall a b : nat, odd a -> odd b -> even (a + b).\nintros.\nelim H0; elim H; intros.\nrewrite H2; rewrite H1; intros.\nrewrite (plus_comm (2 * q0) 1).\nrewrite (plus_assoc (2 * q + 1) 1 (2 * q0)).\nrewrite (plus_assoc_reverse (2 * q) 1 1).\napply (plus_even_even (2 * q + (1 + 1)) (2 * q0)).\napply (plus_even_even (2 * q) (1 + 1)).\napply (even_intro (2 * q) q); auto with arith.\napply (even_intro (1 + 1) 1); auto with arith.\napply (even_intro (2 * q0) q0); auto.\nQed.\n\n\n(************************** mult, even and odd ***************************)\n\nLemma mult_even : forall a b : nat, even a -> even (a * b).\nintros.\nelim H.\nintros.\napply (even_intro (a * b) (q * b)).\nrewrite H0.\nauto with arith.\nQed.\n\n\n\nLemma mult_odd_odd : forall a b : nat, odd a -> odd b -> odd (a * b).\nintros.\nelim H0; intros.\nelim H; intros.\nclear H0; clear H.\nrewrite H2; rewrite H1.\nrewrite (mult_plus_distr_r (2 * q0) 1 (2 * q + 1)).\napply (plus_even_odd (2 * q0 * (2 * q + 1)) (1 * (2 * q + 1))).\napply (mult_even (2 * q0) (2 * q + 1)).\napply (even_intro (2 * q0) q0); auto.\napply (odd_intro (1 * (2 * q + 1)) q); auto with arith.\nQed.\n\n\n(************************** div, even and odd ****************************)\n\nDefinition div (d a : nat) := exists k : nat, a = d * k.\n\n\n\nLemma div_odd_even : forall n d : nat, div d (2 * n) -> odd d -> div d n.\nintros.\nelim H.\nintros.\ncut (even x).\nintro.\nelim H2.\nintros q evenx.\nunfold div in |- *.\nexists q.\napply (mult_reg_l_bis n (d * q) 2).\nauto with arith.\nrewrite H1.\nrewrite evenx.\nelim (mult_assoc_reverse 2 d q).\nrewrite (mult_comm 2 d).\nauto with arith.\nelim (even_or_odd x).\nauto with arith.\nintros.\nabsurd (even (d * x)).\napply odd_even.\napply mult_odd_odd; auto.\ncut (d * x = 2 * n); auto with arith.\nintro.\napply (even_intro (d * x) n).\nauto with arith.\nQed.\n\n\n\nLemma div_odd_odd : forall n : nat, odd n -> forall d : nat, div d n -> odd d.\nintros n oddn d divdn.\nelim divdn.\nintros.\n elim (even_or_odd d); auto.\nintros evend.\nabsurd (even n).\napply odd_even; auto with arith.\nrewrite H.\napply mult_even; auto with arith.\nQed.\n\n\n\nLemma div_plus : forall n m d : nat, div d n -> div d m -> div d (n + m).\nintros n m d divdn divdm.\nelim divdm; intros; elim divdn; intros.\nrewrite H0; rewrite H.\nelim mult_plus_distr_left.\nunfold div in |- *.\nexists (x0 + x); auto with arith.\nQed.\nHint Immediate div_plus.\n\n\n\nLemma div_minus : forall n m d : nat, div d n -> div d m -> div d (n - m).\nintros n m d divdn divdm.\nelim divdm; intros; elim divdn; intros.\nrewrite H0; rewrite H.\nelim (mult_minus_distr_left x0 x d).\nunfold div in |- *.\nexists (x0 - x); auto with arith.\nQed.\nHint Immediate div_minus.\n\n\n(************* Informative definitions of Even and Or ********************)\n\nInductive Even (n : nat) : Set :=\n    Even_intro : forall q : nat, n = 2 * q -> Even n.\n\nInductive Odd (n : nat) : Set :=\n    Odd_intro : forall q : nat, n = 2 * q + 1 -> Odd n.\n\n\n\nLemma Even_or_Odd : forall n : nat, Even n + Odd n.\nsimple induction n.\nleft; apply (Even_intro 0 0); auto with arith.\nintros y hrec.\nelim hrec.\nintro eveny.\nright; elim eveny.\nintros q hy; apply (Odd_intro (S y) q).\nelim hy.\nelim plus_n_Sm.\nauto with arith.\nintro oddy; left.\nelim oddy.\nintros q hy; apply (Even_intro (S y) (S q)).\nrewrite hy.\nrewrite plus_n_Sm.\nelim (mult_comm (S q) 2).\nelim (mult_comm q 2).\nelim plus_comm.\nauto with arith.\nQed.\n\n\nLemma Odd_odd : forall n : nat, Odd n -> odd n.\nintros.\nelim H.\nintros.\napply (odd_intro n q e).\nQed.\nHint Immediate Odd_odd.", "meta": {"author": "coq-contribs", "repo": "fairisle", "sha": "e36087a6b7e52ef3c6dcfdeba1298e8fde1260a0", "save_path": "github-repos/coq/coq-contribs-fairisle", "path": "github-repos/coq/coq-contribs-fairisle/fairisle-e36087a6b7e52ef3c6dcfdeba1298e8fde1260a0/Libraries/Lib_Arithmetic/Lib_Div_Even_Odd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6805866781158025}}
{"text": "(*\n  Copyright 2022 ZhengPu Shi\n  This file is part of CoqMatrix. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : Implementation with Dependent Pair\n  author    : ZhengPu Shi\n  date      : 2021.12\n *)\n\nRequire Export MatrixTheory.\nRequire Import DepPair.Matrix.\n\n\n(* ######################################################################### *)\n(** * Basic matrix theory implemented with Dependent Pair *)\n\nModule BasicMatrixTheoryDP (E : ElementType) <: BasicMatrixTheory E.\n\n  (** Basic library *)\n  Export BasicConfig TupleExt SetoidListListExt HierarchySetoid.\n\n  (* ==================================== *)\n  (** ** Matrix element type *)\n  Export E.\n\n  Infix \"==\" := (eqlistA Aeq) : list_scope.\n  Infix \"==\" := (eqlistA (eqlistA Aeq)) : dlist_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vec_scope.\n\n  Open Scope nat_scope.\n  Open Scope A_scope.\n  Open Scope vector_scope.\n  Open Scope mat_scope.\n  \n  (* ==================================== *)\n  (** ** Matrix type and basic operations *)\n\n  Definition mat r c := @mat A r c.\n\n  (** matrix equality *)\n  Definition meq {r c : nat} := @meq A Aeq r c.\n  Infix \"==\" := meq : mat_scope.\n\n  Lemma meq_equiv r c : Equivalence (@meq r c).\n  Proof.\n    apply meq_equiv.\n  Qed.\n\n  Global Existing Instance meq_equiv.\n\n  (** Get n-th element of a matrix *)  \n  Definition mnth {r c} (m : mat r c) (ri ci : nat) :=\n    @mnth A A0 r c m ri ci.\n\n  (** meq and mnth should satisfy this constraint *)\n  Lemma meq_iff_mnth : forall {r c : nat} (m1 m2 : mat r c),\n      m1 == m2 <-> (forall ri ci, ri < r -> ci < c -> (mnth m1 ri ci == mnth m2 ri ci)%A).\n  Proof.\n    intros. apply meq_iff_mnth.\n  Qed.\n\n  (** linear matrix arithmetic tactic for equation: split goal to every element *)\n  Ltac lma :=\n    cbv; repeat constructor;\n    try ring; try easy.\n  \n  (* ==================================== *)\n  (** ** Convert between list list and matrix *)\n\n  (** *** list list to mat *)\n  \n  Definition l2m {r c} (dl : list (list A)) : mat r c :=\n    l2m A0 dl r c.\n\n  (** l2m is a proper morphism *)\n  Lemma l2m_aeq_mor : forall r c, Proper (eqlistA (eqlistA Aeq) ==> meq) (@l2m r c).\n  Proof.\n    Admitted.\n\n  Global Existing Instance l2m_aeq_mor.\n\n  (* Another definition *)\n  Definition l2m_old {r c} (dl : list (list A)) : mat r c :=\n    mmake r c (fun x y => nth y (nth x dl []) A0).\n  \n  Lemma l2m_inj : forall {r c} (d1 d2 : list (list A)),\n      length d1 = r -> width d1 c -> \n      length d2 = r -> width d2 c -> \n      ~(d1 == d2)%dlist -> ~(@l2m r c d1 == l2m d2).\n  Proof.\n  Admitted.\n  \n  Lemma l2m_surj : forall {r c} (m : mat r c), \n      (exists d, l2m d == m).\n  Proof.\n  Admitted.\n\n\n  (** *** mat to list list *)\n  \n  Definition m2l {r c} (m : mat r c) : list (list A) :=\n    m2l m.\n\n  (** m2l is a proper morphism *)\n  Lemma m2l_aeq_mor : forall r c, Proper (meq ==> eqlistA (eqlistA Aeq)) (@m2l r c).\n  Proof.\n    Admitted.\n\n  Global Existing Instance m2l_aeq_mor.\n  \n  Lemma m2l_length : forall {r c} (m : mat r c), length (m2l m) = r.\n  Proof.\n    unfold m2l. induction r; intros; destruct m; simpl; auto.\n  Qed.\n\n  Global Hint Resolve m2l_length : mat.\n  \n  Lemma m2l_width : forall {r c} (m : mat r c), width (m2l m) c.\n  Proof.\n    unfold width, m2l.\n    induction r; intros; destruct m; simpl; auto; constructor; auto.\n    apply v2l_length.\n  Qed.\n\n  Global Hint Resolve m2l_width : mat.\n  \n  Lemma m2l_l2m_id : forall {r c} (dl : list (list A)) (H1 : length dl = r)\n                       (H2 : width dl c), (@m2l r c (l2m dl) == dl)%dlist.\n  Proof.\n    intros. apply m2l_l2m_id; auto.\n  Qed.\n  \n  Lemma l2m_m2l_id : forall {r c} (m : mat r c), l2m (m2l m) == m. \n  Proof.\n    intros. apply l2m_m2l_id; auto.\n  Qed.\n  \n  Lemma m2l_inj : forall {r c} (m1 m2 : mat r c),\n      ~(m1 == m2) -> ~(m2l m1 == m2l m2)%dlist.\n  Proof.\n  Admitted.\n  \n  Lemma m2l_surj : forall {r c} (d : list (list A)), \n      length d = r -> width d c -> \n      (exists m, @m2l r c m == d)%dlist.\n  Proof.\n  Admitted.\n  \n  (* ==================================== *)\n  (** ** Specific matrix *)\n\n  Definition mk_mat_1_1 (a11 : A) : mat 1 1 := [[a11]].\n\n  Definition mk_mat_3_1 (a1 a2 a3 : A) : mat 3 1 := [[a1];[a2];[a3]].\n  \n  Definition mk_mat_3_3 (a11 a12 a13 a21 a22 a23 a31 a32 a33 : A) : mat 3 3 \n    := [[a11;a12;a13];[a21;a22;a23];[a31;a32;a33]].\n\n  (* ==================================== *)\n  (** ** Convert between tuples and matrix *)\n  \n  (** tuple_3x3 -> mat_3x3 *)\n  Definition t2m_3x3 (t : @T_3x3 A) : mat 3 3.\n  Proof.\n    destruct t as ((t1,t2),t3).\n    destruct t1 as ((a11,a12),a13).\n    destruct t2 as ((a21,a22),a23).\n    destruct t3 as ((a31,a32),a33).\n    exact (mk_mat_3_3 a11 a12 a13 a21 a22 a23 a31 a32 a33).\n  Defined.\n  \n  (** mat_3x3 -> tuple_3x3, thatt is ((a11,a12,a13),(a21,a22,a23),(a31,a32,a33)) *)\n  Definition m2t_3x3 (m : mat 3 3) : @T_3x3 A.\n    set (dl := m2l m).\n    remember (hd [] dl) as l1.\n    remember (hd [] (tl dl)) as l2.\n    remember (hd [] (tl (tl dl))) as l3.\n    remember (hd A0 l1, hd A0 (tl l1), hd A0 (tl (tl l1))) as t1.\n    remember (hd A0 l2, hd A0 (tl l2), hd A0 (tl (tl l2))) as t2.\n    remember (hd A0 l3, hd A0 (tl l3), hd A0 (tl (tl l3))) as t3.\n    exact (t1, t2, t3).\n  Defined.\n  \n  (** m[0,0] : mat_1x1 -> A *)\n  Definition scalar_of_mat (m : mat 1 1) := mnth m 0 0.\n\n  (* ==================================== *)\n  (** ** Matrix transposition *)\n  \n  Definition mtrans {r c} (m : mat r c): mat c r :=\n    @mtrans A r c m.\n  \n  Global Notation \"m \\T\" := (mtrans m) : mat_scope.\n  \n  Lemma mtrans_trans : forall {r c} (m : mat r c), mtrans (mtrans m) == m.\n  Proof.\n    apply @mtrans_trans. apply Equiv_Aeq.\n  Qed.\n  \n  (* ==================================== *)\n  (** ** Mapping of matrix *)\n\n  (** Mapping of a matrix *)\n  Definition mmap {r c} (f : A -> A) (m : mat r c) : mat r c := mmap f m.\n  \n  Definition mmap2 {r c} (f: A -> A -> A) (m1 m2: mat r c) : mat r c := mmap2 f m1 m2.\n  \n  Lemma mmap2_comm : forall {r c} (f : A -> A -> A)\n                       (f_comm : forall a b : A, (f a b == f b a)%A)\n                       (m1 m2 : mat r c), \n      mmap2 f m1 m2 == mmap2 f m2 m1.\n  Proof.\n    intros. apply mmap2_comm. auto.\n  Qed.\n  \n  Lemma mmap2_assoc : forall {r c} (f : A -> A -> A)\n                        (f_assoc : forall a b c, (f (f a b) c == f a (f b c))%A)\n                        (m1 m2 m3 : mat r c), \n      mmap2 f (mmap2 f m1 m2) m3 == mmap2 f m1 (mmap2 f m2 m3).\n  Proof.\n    intros. apply mmap2_assoc. auto.\n  Qed.\n\nEnd BasicMatrixTheoryDP.\n\n\n(* ######################################################################### *)\n(** * Decidable matrix theory implemented with Dependent Pair *)\n\nModule DecidableMatrixTheoryDP (E : DecidableElementType) <: DecidableMatrixTheory E.\n\n  (* Export E. *)\n  Include BasicMatrixTheoryDP E.\n  \n  (** meq is decidable *)\n  Lemma meq_dec : forall {r c}, Decidable (meq (r:=r)(c:=c)).\n  Proof.\n    intros. apply veq_dec. apply veq_dec. apply Dec_Aeq.\n  Qed.\n\nEnd DecidableMatrixTheoryDP.\n\n\n(* ######################################################################### *)\n(** * Ring matrix theory implemented with Dependent Pair *)\n\nModule RingMatrixTheoryDP (E : RingElementType) <: RingMatrixTheory E.\n\n  (* Export E. *)\n  Include BasicMatrixTheoryDP E.\n\n  Add Ring ring_thy_inst : Ring_thy.\n\n  (** Zero matrix *)\n  Definition mat0 r c : mat r c := @mat0 A A0 r c.\n\n  (** Unit matrix *)\n  Definition mat1 n : mat n n := @mat1 A A0 A1 n.\n  \n  (** *** Addition of matrix *)\n  \n  Definition madd {r c} := @madd A Aadd r c.\n  Global Notation \"m1 + m2\" := (madd m1 m2) : mat_scope.\n\n  (** m1 + m2 = m2 + m1 *)\n  Lemma madd_comm : forall {r c} (m1 m2 : mat r c), m1 + m2 == m2 + m1.\n  Proof.\n    intros. apply madd_comm.\n  Qed.\n  \n  (** (m1 + m2) + m3 = m1 + (m2 + m3) *)\n  Lemma madd_assoc : forall {r c} (m1 m2 m3 : mat r c), (m1 + m2) + m3 == m1 + (m2 + m3).\n  Proof.\n    intros. apply madd_assoc.\n  Qed.\n  \n  (** 0 + m = m *)\n  Lemma madd_0_l : forall {r c} (m : mat r c), (mat0 r c) + m == m.\n  Proof.\n    intros. apply madd_0_l.\n  Qed.\n  \n  (** m + 0 = m *)\n  Lemma madd_0_r : forall {r c} (m : mat r c), m + (mat0 r c) == m.\n  Proof.\n    intros. apply madd_0_r.\n  Qed.\n\n  \n  (** l2v is a homomorphic mapping with respect to vadd *)\n  Notation l2v := (l2v (A0:=A0)).\n  Notation vadd := (vadd (Aadd:=Aadd)).\n  \n  Lemma l2v_vadd_homo : forall (n : nat) (l1 l2 : list A)\n    (H1 : length l1 = n) (H2 : length l2 = n),\n      (l2v (map2 Aadd l1 l2) n == vadd (l2v l1 n) (l2v l2 n))%vec.\n  Proof.\n    induction n; intros.\n    - rewrite length_zero_iff_nil in H1,H2. subst; simpl; auto.\n    - destruct l1,l2; try easy.\n      inversion H1. inversion H2. simpl. split; try easy.\n      rewrite H0. apply IHn; auto.\n  Qed.\n  \n  (** v2l is a homomorphic mapping with respect to vadd *)\n  (* Lemma v2l_vadd_homo : forall (n : nat) (v1 v2 : vec n), *)\n  (*   v2l (vadd Aadd v1 v2) = map2 Aadd (v2l v1) (v2l v2). *)\n  (* Proof. *)\n  (*   induction n; intros; destruct v1,v2; simpl; auto. f_equal; auto. *)\n  (* Qed. *)\n\n  (** l2m is a homomorphic mapping with respect to madd *)\n  Lemma l2m_madd_homo : forall (r c : nat) (dl1 dl2 : list (list A))\n    (H1 : length dl1 = r) (W1 : width dl1 c)\n    (H2 : length dl2 = r) (W2 : width dl2 c),\n    @l2m r c (dmap2 Aadd dl1 dl2) == (l2m dl1) + (l2m dl2).\n  Proof.\n    induction r; intros.\n    - rewrite length_zero_iff_nil in *. subst. simpl. auto.\n    - destruct dl1,dl2; simpl in *; try easy.\n      inv H1. inv H2. inv W1. inv W2. split.\n      + apply l2v_vadd_homo; auto.\n      + rewrite H0. apply IHr; auto.\n  Qed.\n  \n  (** m2l is a homomorphic mapping with respect to madd *)\n  (* Lemma m2l_madd_homo : forall (r c : nat) (m1 m2 : mat r c), *)\n  (*   m2l (madd m1 m2) = dmap2 Aadd (m2l m1) (m2l m2). *)\n  (* Proof. *)\n  (*   induction r; intros; destruct m1,m2; simpl; auto. f_equal; auto. *)\n  (*   apply v2l_vadd_homo. *)\n  (* Qed. *)\n  \n  \n  (** *** Opposite of matrix *)\n\n  Definition mopp {r c} (m : mat r c) : mat r c := @mopp A Aopp r c m.\n  Global Notation \"- m\" := (mopp m) : mat_scope.\n\n  (** - - m = m *)\n  Lemma mopp_opp : forall {r c} (m : mat r c), - - m == m.\n  Proof.\n    intros. apply mopp_mopp.\n  Qed.\n\n  (** m + (-m) = 0 *)\n  Lemma madd_opp : forall {r c} (m : mat r c), m + (-m) == mat0 r c.\n  Proof.\n    intros. apply msub_self.\n  Qed.\n  \n  \n  (** *** Subtraction of matrix *)\n  \n  Definition msub {r c} (m1 m2 : mat r c) : mat r c := @msub A Aadd Aopp r c m1 m2.\n  Global Notation \"m1 - m2\" := (msub m1 m2) : mat_scope.\n\n  (** m1 - m2 = - (m2 - m1) *)\n  Lemma msub_comm : forall {r c} (m1 m2 : mat r c), m1 - m2 == - (m2 - m1).\n  Proof.\n    intros. apply msub_comm.\n  Qed.\n  (** (m1 - m2) - m3 = m1 - (m2 + m3) *)\n  Lemma msub_assoc : forall {r c} (m1 m2 m3 : mat r c), (m1 - m2) - m3 == m1 - (m2 + m3).\n  Proof.\n    intros. apply msub_assoc.\n  Qed.\n\n  (** 0 - m = - m *)\n  Lemma msub_0_l : forall {r c} (m : mat r c), (mat0 r c) - m == - m.\n  Proof.\n    intros. apply msub_0_l.\n  Qed.\n  \n  (** m - 0 = m *)\n  Lemma msub_0_r : forall {r c} (m : mat r c), m - (mat0 r c) == m.\n  Proof.\n    intros. apply msub_0_r.\n  Qed.\n  \n  (** m - m = 0 *)\n  Lemma msub_self : forall {r c} (m : mat r c), m - m == (mat0 r c).\n  Proof.\n    intros. apply msub_self.\n  Qed.\n  \n  \n  (** *** Scalar multiplication of matrix *)\n\n  (** Left scalar multiplication of matrix *)\n  Definition mcmul {r c} (a : A) (m : mat r c) : mat r c :=\n    @mcmul A Amul r c a m.\n  Global Notation \"a c* m\" := (mcmul a m) : mat_scope.\n\n  (** Right scalar multiplication of matrix *)\n  Definition mmulc {r c} (m : mat r c) (a : A) : mat r c :=\n    @mmulc A Amul r c m a.\n  Global Notation \"m *c a\" := (mmulc m a) : mat_scope.\n\n  (** m * a = a * m *)\n  Lemma mmulc_eq_mcmul : forall {r c} (a : A) (m : mat r c), m *c a == a c* m.\n  Proof.\n    intros. apply mmulc_eq_mcmul.\n  Qed.\n  \n  (** a * (b * m) = (a * b) * m *)\n  Lemma mcmul_assoc : forall {r c} (a b : A) (m : mat r c), a c* (b c* m) == (a * b)%A c* m.\n  Proof.\n    intros. apply mcmul_assoc.\n  Qed.\n  \n  (** a * (b * m) = b * (a * m) *)\n  Lemma mcmul_perm : forall {r c} (a b : A) (m : mat r c), a c* (b c* m) == b c* (a c* m).\n  Proof.\n    intros. apply mcmul_perm.\n  Qed.\n  \n  (** a * (m1 + m2) = (a * m1) + (a * m2) *)\n  Lemma mcmul_add_distr_l : forall {r c} (a : A) (m1 m2 : mat r c),\n      a c* (m1 + m2) == (a c* m1) + (a c* m2).\n  Proof.\n    intros. apply mcmul_add_distr_l.\n  Qed.\n  \n  (** (a + b) * m = (a * m) + (b * m) *)\n  Lemma mcmul_add_distr_r : forall {r c} (a b : A) (m : mat r c),\n      (a + b)%A c* m == (a c* m) + (b c* m).\n  Proof.\n    intros. apply mcmul_add_distr_r.\n  Qed.\n  \n  (** 0 * m = 0 *)\n  Lemma mcmul_0_l : forall {r c} (m : mat r c), A0 c* m == mat0 r c.\n  Proof.\n    intros. apply mcmul_0_l.\n  Qed.\n  \n  (** 1 * m = m *)\n  Lemma mcmul_1_l : forall {r c} (m : mat r c), A1 c* m == m.\n  Proof.\n    intros. apply mcmul_1_l.\n  Qed.\n  \n  \n  (** *** Multiplication of matrix *)\n  Definition mmul {r c s} (m1 : mat r c) (m2 : mat c s) : mat r s :=\n    @mmul A Aadd A0 Amul r c s m1 m2.\n  Global Infix \"*\" := mmul : mat_scope.\n\n  (** m1 * (m2 + m3) = (m1 * m2) + (m1 * m3) *)\n  Lemma mmul_add_distr_l : forall {r c A} (m1 : mat r c) (m2 m3 : mat c A),\n      m1 * (m2 + m3) == m1 * m2 + m1 * m3.\n  Proof.\n    intros. apply mmul_add_distr_l.\n  Qed.\n  \n  (** (m1 + m2) * m3 = (m1 * m3) + (m2 * m3) *)\n  Lemma mmul_add_distr_r : forall {r c s} (m1 m2 : mat r c) (m3 : mat c s),\n      (m1 + m2) * m3 == (m1 * m3) + (m2 * m3).\n  Proof.\n    intros. apply mmul_add_distr_r.\n  Qed.\n  \n  (** (m1 * m2) * m3 = m1 * (m2 * m3) *)\n  Lemma mmul_assoc : forall {r c s A} (m1 : mat r c) (m2 : mat c s) (m3 : mat s A),\n      (m1 * m2) * m3 == m1 * (m2 * m3).\n  Proof.\n    intros. apply mmul_assoc.\n  Qed.\n  \n  (** mat0 * m = mat0 *)\n  Lemma mmul_0_l : forall {r c A} (m : mat c A), (mat0 r c) * m == mat0 r A.\n  Proof.\n    intros. apply mmul_0_l.\n  Qed.\n  \n  (** m * mat0 = mat0 *)\n  Lemma mmul_0_r : forall {r c A} (m : mat r c), m * (mat0 c A) == mat0 r A.\n  Proof.\n    intros. apply mmul_0_r.\n  Qed.\n  \n  (** mat1 * m = m *)\n  Lemma mmul_1_l : forall {r c} (m : mat r c), (mat1 r) * m == m.\n  Proof.\n    intros. apply mmul_1_l.\n  Qed.\n  \n  (** m * mat1 = m *)\n  Lemma mmul_1_r : forall {r c} (m : mat r c), m * (mat1 c) == m.\n  Proof.\n    intros. apply mmul_1_r.\n  Qed.\n  \n\nEnd RingMatrixTheoryDP.\n\n\n(* ######################################################################### *)\n(** * Decidable Field matrix theory implemented with Dependent Pair *)\n\nModule DecidableFieldMatrixTheoryDP (E : DecidableFieldElementType)\n<: DecidableFieldMatrixTheory E.\n\n  (* Export E. *)\n  Include RingMatrixTheoryDP E.\n  Module Export DecMT := DecidableMatrixTheoryDP E.\n\n  (** meq is decidable *)\n  Lemma meq_dec : forall (r c : nat), Decidable (meq (r:=r) (c:=c)).\n  Proof.\n    intros. apply meq_dec.\n  Qed.\n    \n  (** ** matrix theory *)\n  \nEnd DecidableFieldMatrixTheoryDP.\n", "meta": {"author": "zhengpushi", "repo": "CoqMatrix", "sha": "28fa5f96e38a07659cfd373e09b0e75c24c22bfd", "save_path": "github-repos/coq/zhengpushi-CoqMatrix", "path": "github-repos/coq/zhengpushi-CoqMatrix/CoqMatrix-28fa5f96e38a07659cfd373e09b0e75c24c22bfd/CoqMatrix/DepPair/MatrixTheoryDP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.6805866754584986}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nTheorem append_nil: forall (l: lst), append l Nil = l.\nProof.\n   induction l.\n   { simpl. f_equal. assumption. }\n   { simpl. reflexivity. }\nQed.\n\nTheorem append_assoc:\n   forall (l1 l2 l3: lst), append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\n   induction l1; induction l2; induction l3; try (simpl; reflexivity).\n   { simpl. rewrite <- IHl1. f_equal. }\n   { simpl. rewrite 2 append_nil. reflexivity. }\n   { simpl. rewrite append_nil.  reflexivity. }\n   { simpl. rewrite 2 append_nil. reflexivity. }\nQed.\n\nTheorem append_rev_cons:\n   forall (l1 l2: lst) (x: natural),\n   rev (append l1 (Cons x l2)) = append (rev l2) (Cons x (rev l1)).\nProof.\n   induction l1; induction l2; try (simpl; reflexivity).\n   { intro.  simpl.  rewrite IHl1.  simpl. lfind. \nAdmitted.\n\nTheorem rev_append: forall (l1 l2: lst), rev (append l1 l2) = append (rev l2) (rev l1).\nProof.\n   induction l1.\n   { induction l2.\n   { simpl. rewrite append_rev_cons.\n      rewrite <- 2 append_assoc.\n      f_equal. }\n   { simpl. rewrite append_nil. reflexivity. }\n   }\n   { intro. simpl. rewrite append_nil. reflexivity. }\nQed.\n\nTheorem rev_involutive : forall (x : lst), eq (rev (rev x)) x.\nProof.\n   induction x.\n   { simpl. rewrite rev_append. simpl. f_equal.\n   assumption. }\n   { simpl. reflexivity. }\nQed.\n\nTheorem theorem0 : forall (x : lst), eq (rev (append (rev x) Nil)) x.\nProof.\n   intro.\n   rewrite append_nil.\n   apply rev_involutive.\nQed.\n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/clam_lf_goal30_append_rev_cons_45_append_assoc/goal30.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6805866716144304}}
{"text": "(** Finite Multiset over Lists\n\nWe define an axiomatization of finite multiset through their relation with lists.\nEquality is an equivalence relation.\nAn implementation of the axioms is provided for every type\nby lists up to permutation. *)\n\nFrom Coq Require Import Relation_Definitions Morphisms List Permutation.\n\nSet Implicit Arguments.\nSet Default Proof Using \"Type\".\n\n\n(** * Axiomatization *)\n\n(** A finite multiset with elements in [A] is a type [M]\n    related with [list A] as follows: *)\nClass FinMultisetoid M A := {\n  meq : relation M;\n  mequiv : Equivalence meq;\n  empty : M;\n  add : A -> M -> M;\n  add_meq : Proper (eq ==> meq ==> meq) add;\n  elts : M -> list A;\n  elts_empty : elts empty = @nil A;\n  elts_add : forall a m, Permutation (elts (add a m)) (a :: elts m);\n  perm_meq : forall l1 l2, Permutation l1 l2 ->\n               meq (fold_right add empty l1) (fold_right add empty l2);\n  meq_perm : forall m1 m2, meq m1 m2 -> Permutation (elts m1) (elts m2);\n  retract_meq : forall m, meq (fold_right add empty (elts m)) m\n}.\n\n(** [Mst] and [Elt] define a finite multiset construction over a type [K]\n    if for any [A] in [K], [Mst A] is a finite multiset with elements [Elt A]. *)\nDefinition FMoidConstructor K Mst Elt :=\n  forall A : K, FinMultisetoid (Mst A) (Elt A).\n\n\n(** * Constructions and properties over finite multisets *)\n\nSection FMSet2List.\n\n  Variable M A : Type.\n  Variable fm : FinMultisetoid M A.\n\n  #[export] Instance mequivalence : Equivalence meq := mequiv.\n\n  Definition list2fm l := fold_right add empty l.\n\n  #[export] Instance list2fm_perm : Proper (@Permutation A ==> meq) list2fm := perm_meq.\n\n  #[export] Instance elts_perm' : Proper (meq ==> @Permutation A) elts := meq_perm.\n\n  Lemma list2fm_retract m : meq (list2fm (elts m)) m.\n  Proof. apply retract_meq. Qed.\n\n  Lemma list2fm_nil : list2fm nil = empty.\n  Proof. reflexivity. Qed.\n\n  Lemma list2fm_elt l1 l2 a :\n    meq (list2fm (l1 ++ a :: l2)) (add a (list2fm (l1 ++ l2))).\n  Proof.\n  symmetry.\n  change (add a (list2fm (l1 ++ l2)))\n    with (list2fm (a :: l1 ++ l2)).\n  apply perm_meq, Permutation_middle.\n  Qed.\n\n  Lemma list2fm_cons l a : meq (list2fm (a :: l)) (add a (list2fm l)).\n  Proof. now rewrite <- (app_nil_l (a :: l)), list2fm_elt. Qed.\n\n  Lemma elts_perm l : Permutation (elts (list2fm l)) l.\n  Proof.\n  induction l as [|a l IHl].\n  - now simpl; rewrite elts_empty.\n  - now simpl; rewrite elts_add, IHl.\n  Qed.\n\n  Lemma elts_eq_nil m : elts m = nil -> meq m empty.\n  Proof.\n  intros Heq.\n  now assert (Hr := retract_meq m); rewrite Heq in Hr; simpl in Hr; rewrite Hr.\n  Qed.\n\n  Lemma add_swap m a b : meq (add a (add b m)) (add b (add a m)).\n  Proof.\n  now rewrite <- list2fm_retract, ? elts_add, perm_swap,\n              <- 2 elts_add, list2fm_retract.\n  Qed.\n\n  Definition sum m1 m2 := list2fm (elts m1 ++ elts m2).\n\n  Lemma elts_sum m1 m2 : Permutation (elts (sum m1 m2)) (elts m1 ++ elts m2).\n  Proof. apply elts_perm. Qed.\n\n  Lemma sum_empty_left m : meq (sum empty m) m.\n  Proof. unfold sum; rewrite elts_empty; apply retract_meq. Qed.\n\n  Lemma sum_empty_right m : meq (sum m empty) m.\n  Proof. unfold sum; rewrite elts_empty, app_nil_r; apply retract_meq. Qed.\n\n  Lemma sum_comm m1 m2 : meq (sum m1 m2) (sum m2 m1).\n  Proof. now unfold sum; rewrite Permutation_app_comm. Qed.\n\n  Lemma sum_ass m1 m2 m3 : meq (sum (sum m1 m2) m3) (sum m1 (sum m2 m3)).\n  Proof.\n  unfold sum; apply perm_meq.\n  transitivity ((elts m1 ++ elts m2) ++ elts m3).\n  - apply Permutation_app_tail, elts_perm.\n  - rewrite <- app_assoc; symmetry.\n    apply Permutation_app_head, elts_perm.\n  Qed.\n\n  Lemma list2fm_app l1 l2 : meq (list2fm (l1 ++ l2)) (sum (list2fm l1) (list2fm l2)).\n  Proof.\n  unfold sum; apply perm_meq.\n  transitivity (elts (list2fm l1) ++ l2); symmetry.\n  - apply Permutation_app_tail, elts_perm.\n  - apply Permutation_app_head, elts_perm.\n  Qed.\n\n  #[export] Instance sum_meq : Proper (meq ==> meq ==> meq) sum.\n  Proof.\n  intros m1 m2 Heq m1' m2' Heq'; unfold sum.\n  apply meq_perm in Heq.\n  apply meq_perm in Heq'.\n  now apply perm_meq, Permutation_app.\n  Qed.\n\nEnd FMSet2List.\n\nArguments list2fm {_ _ _}  _.\nArguments list2fm_retract {_ _ _} _.\nArguments sum {_ _ _} _ _.\n\n\nSection Fmmap.\n\n  Variable M A N B: Type.\n  Variable fm : FinMultisetoid M A.\n  Variable fm' : FinMultisetoid N B.\n  Variable f : A -> B.\n\n  Definition fmmap (m : M) := list2fm (map f (elts m)).\n\n  #[export] Instance fmmap_meq : Proper (meq ==> meq) fmmap.\n  Proof.\n  intros l1 l2 Heq.\n  now apply perm_meq, Permutation_map, meq_perm.\n  Qed.\n\n  Lemma list2fm_map l : meq (list2fm (map f l)) (fmmap (list2fm l)).\n  Proof. symmetry; apply perm_meq, Permutation_map, elts_perm. Qed.\n\n  Lemma elts_fmmap m : Permutation (elts (fmmap m)) (map f (elts m)).\n  Proof.\n  rewrite <- (list2fm_retract m) at 1.\n  remember (elts m) as l eqn:Heql; clear m Heql; induction l as [|a l IHl].\n  - simpl; unfold fmmap; rewrite elts_empty; simpl.\n    now rewrite elts_empty.\n  - transitivity (map f (elts (list2fm (a :: l)))).\n    + apply elts_perm.\n    + apply Permutation_map, elts_perm.\n  Qed.\n\nEnd Fmmap.\n\nArguments fmmap {_ _ _ _ _ _} _ _.\n\n\n(** * Lists up to permutation as finite multisets *)\n\nLemma fold_id A l : fold_right (@cons A) nil l = l.\nProof. now induction l; simpl; auto; f_equal. Qed.\n\nFact FMoidConstr_list : FMoidConstructor list id.\nProof.\nintros A.\nsplit with (@Permutation A) (@nil A) (@cons A) id; auto.\n- apply Permutation_Equivalence.\n- intros a1 a2 Heq l1 l2 HP; subst.\n  now apply Permutation_cons.\n- now intros l1 l2 HP; rewrite 2 fold_id.\n- now intros m; rewrite fold_id.\nDefined.\n", "meta": {"author": "olaure01", "repo": "ollibs", "sha": "805f773d1ba83a97e35a1e973bf408daff3824ef", "save_path": "github-repos/coq/olaure01-ollibs", "path": "github-repos/coq/olaure01-ollibs/ollibs-805f773d1ba83a97e35a1e973bf408daff3824ef/fmsetoidlist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6805866651130582}}
{"text": "(*\n  Copyright 2022 ZhengPu Shi\n  This file is part of CoqMatrix. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : Homomorphism theory on matrix.\n  author    : ZhengPu Shi\n  date      : 2021.12\n*)\n\nRequire Export MatrixAll.\nRequire Export HomomorphismThy.\n\nRequire Import Lia.\nRequire Import List.\n\n\n(** * DR and DP is homomorphism *)\nModule Homo_DR_DP (E : RingElementType).\n\n  (** Instantialize the functor to module *)\n  Module Import MatrixAllInst := MatrixAll.RingMatrixTheory E.\n  \n  (* ====================================================== *)\n  (** ** DR and DP is homomorphism with respect to madd *)\n\n  (** Examples: prove properties of madd in DP with the help of DR *)\n\n  Example mdp_madd_comm : forall r c,\n    Commutative (@DR.madd r c) DR.meq -> Commutative (@DP.madd r c) DP.meq.\n  Proof.\n    intros r c H.\n    apply (homo_keep_comm (fa := @DR.madd r c) (Aeq:=DR.meq)); auto.\n    constructor. \n    exists dr2dp. split.\n    - apply hom_madd_dr2dp.\n    - split.\n      + apply dr2dp_surj.\n      + apply dr2dp_aeq_mor. \n  Qed.\n  \n  Example mdp_madd_assoc : forall r c,\n    Associative (@DR.madd r c) DR.meq -> Associative (@DP.madd r c) DP.meq.\n  Proof.\n    intros r c H.\n    apply (homo_keep_assoc (fa := @DR.madd r c) (Aeq:=DR.meq)); auto.\n    constructor.\n    exists dr2dp. split.\n    - apply hom_madd_dr2dp.\n    - split.\n      + apply dr2dp_surj.\n      + apply dr2dp_aeq_mor.\n  Qed.\n\n  \n  (** Examples: prove properties of madd in DR with the help of DP *)\n  \n  Example mdr_madd_comm : forall r c,\n    Commutative (@DP.madd r c) DP.meq -> Commutative (@DR.madd r c) DR.meq.\n  Proof.\n    intros r c H.\n    apply (homo_keep_comm (fa := @DP.madd r c) (Aeq:=DP.meq)); auto.\n    constructor.\n    exists dp2dr. split.\n    - apply hom_madd_dp2dr.\n    - split.\n      + apply dp2dr_surj.\n      + apply dp2dr_aeq_mor.\n  Qed.\n  \nEnd Homo_DR_DP.\n\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/MatrixHomo/MatrixHomomorphism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6805651355324076}}
{"text": "(** * INITIATION A COQ *)\n\n(**\nLe début de ce fichier a été présenté en cours.\nIl est demandé de le réviser à la maison et de le terminer\nen préparation du TD suivant.\n- Lire attentivement les commentaires explicatifs\n- sous emacs/Proof-general,\n  - pour avancer d'une étape, faire C-c C-n\n  - pour reculer, C-c C-p\n  - pour aller d'un coup à la position du curseur, C-c RET.\n  D'autres raccourcis sont disponibles, regarder les menus Proof-General et Coq.\n*)\n\n\n(** ** Généralités *)\n\n(** Coq est primitivement un langage de programmation particulier.\n    Comme OCaml, c'est un langage fonctionnel typé.\n    Son système de types est beaucoup plus riche que celui de OCaml,\n    ce qui permet en particulier d'énoncer des formules logiques,\n    et éventuellement de les démontrer.\n\n    Dans un premier temps, on se focalise sur l'aspect programmation,\n    et les formules logiques considérées sont de simples égalités.\n *)\n\n(** Un script Coq est une suite de déclarations de types, de valeurs,\n    (très souvent : des fonctions), d'énoncés de théorèmes suivis\n    de leur preuve.\n\n    On a également des requêtes pour obtenir des informations,\n    calculer des expressions.\n*)\n\n(** À RETENIR : EN COQ, TOUT FINIT PAR UN POINT '.' *)\n\n(** ** Types énumérés *)\n\n(** Le type qui s'écrirait en OCaml\ntype coulfeu =\n  | Vert\n  | Orange\n  | Rouge\n\nse définit en Coq presque de la même façon.\n*)\n\nInductive coulfeu : Set :=\n  | Vert : coulfeu\n  | Orange : coulfeu\n  | Rouge : coulfeu\n.\n\n(** Comme en OCaml, [blabla : machin] se lit \"[blabla] a pour type [machin]\".\n    Ainsi la déclaration précédente indique que [Vert], [Orange] et [Rouge]\n    sont de type coulfeu.\n    Par ailleurs, en Coq tout a un type ; la déclaration ci-dessus indique que\n    le type de [coulfeu] est [Set], cf. notes de cours.\n*)\n\n(** ** Définition d'une valeur fonctionnelle *)\n\nDefinition coul_suiv : coulfeu -> coulfeu :=\n  fun c =>\n    match c with\n    | Vert => Orange\n    | Orange => Rouge\n    | Rouge => Vert\n    end.\n\n(** La commande Check permet d'obtenir le type d'une expression.\n    Elle vérifie que l'expression est bien typée. *)\n\nCheck coul_suiv.\nCheck (coul_suiv Vert).\n\n(** La commande Eval permet de calculer une expression. *)\n\nEval compute in (coul_suiv Vert).\n\n(** Raccourci *)\nCompute (coul_suiv Vert).\n\n(** ** Premier théorème, tactiques cbn et reflexivity *)\n\nTheorem ex1_coul_suiv : coul_suiv (coul_suiv Vert) = Rouge.\nProof. cbn [coul_suiv]. reflexivity. Qed.\n\n(** Remarque : on peut énoncer une théorème à prouver au moyen d'autres\nmots-clé, notamment Lemma (pour un résultat auxiliaure) ou Example\n(pour un théorème très simple servant à tester le résultat d'une fonction\nsur une entrée particulière.\nCes mots-clé sont équivalents, le choix de l'un ou l'autre est affaire de\nconvention ou d'usage.\nIci on aurait donc plutôt utilisé  Example.\nExample ex1_coul_suiv : coul_suiv (coul_suiv Vert) = Rouge.\n*)\n\n\n(** Une *tactique* est une commande permettant de faire progresser une preuve *)\n\n(** On a utilisé ci-dessus les tactiques suivantes :\n    - cbn [nom_de_fonction] : évaluation (partielle) de [nom_de_fonction]\n    - reflexivity : reconnaissance que les deux membres de l'égalité\n                    à prouver sont identiques (preuve de x = x).\n *)\n\n(** ATTENTION À BIEN TERMINER PAR \"Qed.\" *)\n\n(** ** Variables *)\n\n(** Les preuves par réflexivité fonctionnent non seulement\n    entre des expressions constantes identiques, mais aussi\n    entre des expressions comportant des variables. *)\n\n(** On a la possibilité en Coq (mais pas en OCaml) de déclarer\n    des variables :\n    ce sont des noms dont on connaît simplement le type.\n    Il faut que ces noms soient déclarés dans une portée\n    (domaine de visibilité) définie par une section.\n*)\n\n(** Ouverture d'une section dans laquelle on va faire quelques\n    preuves par réflexivité. *)\n\nSection sec_refl.\n  Variable c : coulfeu.\n  (** Signification intuitive : \"soit [c] une [coulfeu] inconnue\". *)\n\n  Theorem th1_refl_simple : c = c.\n  (** Remarquer que le but contient un environnement comportant\n      l'hypothèse [c : coulfeu]. *)\n  Proof. reflexivity. Qed.\n\n  Check c.\n\n(** Fermeture de la section,\n    ce qui clôt la portée des variables, ici [c : coulfeu]. *)\nEnd sec_refl.\n\nFail Check c.\nFail Definition x := Vert + 2.\n\n(* -------------------------------------------------------------------  *)\n(** Vu jusqu'ici dans ls CM1 2020, en fait juste avant le End sec_refl. *)\n(* -------------------------------------------------------------------  *)\n\n(** ** Principe de Leibniz : tactique rewrite *)\n\nSection sec_reec.\n  Variable c : coulfeu.\n  Hypothesis crou : c = Rouge.\n  (** Signification intuitive, par analogie avec la ligne d'avant :\n      \"soit [crou] une preuve inconnue de [c = Rouge]\". *)\n\n  Theorem coul_suiv_Rouge : coul_suiv c = Vert.\n  Proof.\n    rewrite crou.\n    cbn [coul_suiv].\n    reflexivity.\n  Qed.\n\nEnd sec_reec.\n\n(** ** Raisonnement par cas : tactique destruct *)\n\nSection sec_cas.\n  Variable c : coulfeu.\n\n  Theorem th3_coul_suiv : coul_suiv (coul_suiv (coul_suiv c)) = c.\n  Proof.\n    (** reflexivity ne fonctionne pas. *)\n    Fail reflexivity.\n    (** Il faut raisonner par cas sur les trois valeurs de [c] possibles *)\n    (** Cela va donner lieu à trois sous-buts, un pour chaque cas. *)\n    destruct c as [ (*Vert*) | (*Orange*) | (*Rouge*) ].\n    - cbn [coul_suiv]. reflexivity.\n    - cbn [coul_suiv]. reflexivity.\n    - cbn [coul_suiv]. reflexivity.\n  Qed.\n\nEnd sec_cas.\n\n(** ** Raisonnement universel : tactique intro *)\n\n(** Il est possible d'énoncer des formules quantifiées universellement.\n    Par exemple : [forall c : coulfeu, c = c].\n *)\n\nTheorem th_refl_gen : forall c : coulfeu, c = c.\nProof.\n  (** Pour la démontrer, la première étape consiste à dire\n      \"soit [c0] une couleur arbitraire, démontrons [c0 = c0].\" *)\n  intro c0.\n  (** Remarquer que intro a introduit l'hypothèse [c0 : coulfeu]. *)\n  (** On a déjà vu que reflexivity fonctionne dans cette situation. *)\n  reflexivity.\nQed.\n\n(** La tactique intro sert également à démontrer une implication. *)\nTheorem th_crou_gen : forall c : coulfeu, c = Rouge -> coul_suiv c = Vert.\nProof.\n  intro c0.\n  (** Pour démontrer [c0 = Rouge -> coul_suiv c0 = Vert],\n      on suppose [c0 = Rouge]\n      et on doit alors prouver [coul_suiv c0 = Vert]\n      sous cette hypothèse supplémentaire ;\n      lorsque l'on introduit une hypothèse, on lui donne un nom. *)\n  intro c0rou.\n  (** Le raisonnement sous-jacent est :\n      soit c0rou une preuve arbitraire (inconnue) de [c0 = Rouge],\n      on peut s'en servir pour démontrer coul_suiv [c0 = Vert]. *)\n  rewrite c0rou. cbn [coul_suiv]. reflexivity.\nQed.\n\n(** Remarque : on est souvent amené à effectuer plusieurs introductions\n    successives. On emploie alors le raccourci intros (au pluriel).\n    Sur l'exemple précédent cela donne ceci : *)\nTheorem th_crou_gen_bis : forall c : coulfeu, c = Rouge -> coul_suiv c = Vert.\nProof.\n  intros c0 c0rou.\n  rewrite c0rou. cbn [coul_suiv]. reflexivity.\nQed.\n\n(** * Début du travail à faire à la maison *)\n\n(** *** Exercice: Variante du précédent avec section *)\n\nSection sec_variante_th_crou_gen.\n  Variable c : coulfeu.\n  Theorem th_crou_demi_gen : c = Rouge -> coul_suiv c = Vert.\n  Proof.\n    (** à compléter *)\n    intros.\n    rewrite H.\n    cbn [coul_suiv].\n    reflexivity.\nQed.\n\nEnd sec_variante_th_crou_gen.\n\n(** *** Exercice: Preuve par cas d'un théorème avec forall *)\n\nLemma suivsuivsuiv_id : forall c:coulfeu, coul_suiv (coul_suiv (coul_suiv c))=c.\nProof.\n    intros.\n    destruct c.\n    - cbn [coul_suiv]. reflexivity.\n    - cbn [coul_suiv]. reflexivity.\n    - cbn [coul_suiv]. reflexivity.\nQed.\n\n(** ** Type inductif et récurrence structurelle : arbres binaires tricolores *)\n\nInductive arbin : Set :=\n  | F : coulfeu -> arbin\n  | N : arbin -> arbin -> arbin.\n\n(**\nPour définir une fonction récursive (l'équivalent de let rec\nen OCaml) on utilise le mot clé [Fixpoint].\n *)\n\nFixpoint renva a : arbin :=\n  match a with\n  | F c => F c\n  | N g d => N (renva d) (renva g)\n  end.\n\n(** *** Exercice: prouver que renverser deux fois un arbre rend le même arbre *)\nTheorem renva_renva : forall a, renva (renva a) = a.\nProof.\n  intro a.\n  (** Tentative de raisonnement par cas sur a *)\n  (** Les noms mis dans chaque cas (c pour le premier, a2 a2 pour le second)\n      désignent les composantes des constructeurs respectivement F puis N *)\n  destruct a as [ (* F *) c\n                | (* N *) a1 a2 ].\n  - cbn [renva]. reflexivity.\n  - cbn [renva].\n    (** Il apparaît qu'un simple raisonnement par cas est insuffisant, *)\n    (** donc on arrete tout... *)\n Abort.\n\n(** ... et on recommence en raisonnant par récurrence structurelle *)\nTheorem renva_renva : forall a, renva (renva a) = a.\nProof.\n  intro a.\n  (** récurrence structurelle sur le type inductif arbin *)\n  (** Remarquer l'analogie avec l'utilisation de la tactique destruct :\n      les noms mis dans chaque cas (c pour le premier, a2 a2 pour le second)\n      désignent les composantes des constructeurs respectivement F puis N\n      mais en complément, on ajoute deux noms pour les hypothèses de récurrence,\n       Hrec_a1 pour celle sur a1 et Hrec_a2 pour celle sur a2 *)\n  induction a as [ (* F *) c\n                 | (* N *) a1 Hrec_a1 a2 Hrec_a2 ].\n  - cbn [renva]. reflexivity.\n  - cbn [renva]. rewrite Hrec_a1. rewrite Hrec_a2. reflexivity.\nQed.\n(** Fin du travail à faire à la maison. *)\n", "meta": {"author": "elegaanz", "repo": "info4-ltpf", "sha": "1c2802dc05157ac781e07147763d35491f7995a6", "save_path": "github-repos/coq/elegaanz-info4-ltpf", "path": "github-repos/coq/elegaanz-info4-ltpf/info4-ltpf-1c2802dc05157ac781e07147763d35491f7995a6/coq1_B_A_BA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.6805651081903225}}
{"text": "Require Import Notation.\nRequire Import GeneralTactics.\nRequire Import Axioms.\n\nCreate HintDb prop_simpl.\n\nTheorem and_idempotent : forall P: Prop,\n  (P /\\ P) = P.\nProof using.\n  intros *.\n  follows extensionality.\nQed.\nHint Rewrite and_idempotent : prop_simpl.\n\nTheorem or_idempotent : forall P: Prop,\n  (P \\/ P) = P.\nProof using.\n  intros *.\n  follows extensionality.\nQed.\nHint Rewrite or_idempotent : prop_simpl.\n\nTheorem and_inv : forall P: Prop,\n  (P /\\ ~P) = False.\nProof using.\n  intros *.\n  follows extensionality.\nQed.\nHint Rewrite and_inv : prop_simpl.\n\nTheorem or_inv : forall P: Prop,\n  (P \\/ ~P) = True.\nProof using.\n  intros *.\n  extensionality.\n  after split.\n  intro.\n  apply classic.\nQed.\nHint Rewrite or_inv : prop_simpl.\n\nTheorem and_id_left : forall P: Prop,\n  (True /\\ P) = P.\nProof using.\n  intros *.\n  follows extensionality.\nQed.\nHint Rewrite and_id_left : prop_simpl.\n\nTheorem and_id_right : forall P: Prop,\n  (P /\\ True) = P.\nProof using.\n  intros *.\n  follows extensionality.\nQed.\nHint Rewrite and_id_right : prop_simpl.\n\nTheorem or_id_left : forall P: Prop,\n  (False \\/ P) = P.\nProof using.\n  intros *.\n  follows extensionality.\nQed.\nHint Rewrite or_id_left : prop_simpl.\n\nTheorem or_id_right : forall P: Prop,\n  (P \\/ False) = P.\nProof using.\n  intros *.\n  follows extensionality.\nQed.\nHint Rewrite or_id_right : prop_simpl.\n\nTheorem or_true_left : forall P: Prop,\n  (True \\/ P) = True.\nProof using.\n  intros *.\n  follows extensionality.\nQed.\nHint Rewrite or_true_left : prop_simpl.\n\nTheorem or_true_right : forall P: Prop,\n  (P \\/ True) = True.\nProof using.\n  intros *.\n  follows extensionality.\nQed.\nHint Rewrite or_true_right : prop_simpl.\n\nTheorem and_false_left : forall P: Prop,\n  (False /\\ P) = False.\nProof using.\n  intros *.\n  follows extensionality.\nQed.\nHint Rewrite and_false_left : prop_simpl.\n\nTheorem and_false_right : forall P: Prop,\n  (P /\\ False) = False.\nProof using.\n  intros *.\n  follows extensionality.\nQed.\nHint Rewrite and_false_right : prop_simpl.\n\nTheorem impl_refl : forall P: Prop,\n  (P -> P) = True.\nProof using.\n  intros *.\n  follows extensionality.\nQed.\nHint Rewrite impl_refl : prop_simpl.\n\nTheorem impl_true_left : forall P: Prop,\n  (True -> P) = P.\nProof using.\n  intros *.\n  follows extensionality.\nQed.\nHint Rewrite impl_true_left : prop_simpl.\n\nTheorem impl_true_right : forall P: Prop,\n  (P -> True) = True.\nProof using.\n  intros *.\n  follows extensionality.\nQed.\nHint Rewrite impl_true_right : prop_simpl.\n \nTheorem impl_false_left : forall P: Prop,\n  (False -> P) = True.\nProof using.\n  intros *.\n  follows extensionality.\nQed.\nHint Rewrite impl_false_left : prop_simpl.\n\n\n(* Positivity rewrites *)\nHint Rewrite rew_not_not   : prop_simpl.\nHint Rewrite rew_not_and   : prop_simpl.\nHint Rewrite rew_not_or    : prop_simpl.\nHint Rewrite rew_not_all   : prop_simpl.\nHint Rewrite rew_not_ex    : prop_simpl.\nHint Rewrite rew_not_imply : prop_simpl.\n\n\n(* Agressive rewriting with UIP and propositional extensionality\n   Note, this is *very* experimental. In particular, `crush_eqs` \n   currently erases too much information at times\n*)\n\nTactic Notation \"simpl!\" :=\n  cbn;\n  repeat (progress crush_eqs; cbn);\n  autorewrite with prop_simpl.\n\nTactic Notation \"simpl!\" \"in\" hyp(H) :=\n  cbn in H;\n  repeat (progress crush_eqs; cbn in H);\n  autorewrite with prop_simpl in H.\n  \nTactic Notation \"simpl!\" \"in\" \"*\" :=\n  cbn in *;\n  repeat (progress crush_eqs; cbn in *);\n  autorewrite with prop_simpl in *.\n\n\n(* `with` adds rewriting rule *)\n\nTactic Notation \"simpl!\" \"with\" uconstr(rew) := \n  simpl!;\n  repeat (progress rewrite rew; progress simpl!).\n\nTactic Notation \"simpl!\" \"in\" hyp(H) \"with\" uconstr(rew) := \n  simpl! in H;\n  repeat (progress rewrite rew in H; progress simpl! in H).\n\nTactic Notation \"simpl!\" \"in\" \"*\" \"with\" uconstr(rew) := \n  simpl! in *;\n  repeat (progress rewrite rew in *; progress simpl! in *).\n", "meta": {"author": "ku-sldg", "repo": "CTL", "sha": "75bb188ae2689baeb28d34a789fe839871c240fe", "save_path": "github-repos/coq/ku-sldg-CTL", "path": "github-repos/coq/ku-sldg-CTL/CTL-75bb188ae2689baeb28d34a789fe839871c240fe/Glib/PropNormalize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.6805651061468753}}
{"text": "(* Exercise 47 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\nTheorem exercise_047 : A -> (A -> (B -> A)).\nProof.\nimp_i a1.\nimp_i a2.\nimp_i a3.\nhyp a1.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop047.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391706552536, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6804258644045084}}
{"text": "Require Import Coq.Vectors.Vector.\nRequire Import QArith.\nRequire Import Setoid.\n\n(*******************************************************************************************\n    Helpful definitions and proofs about Rationals (Q)\n *******************************************************************************************)\nDefinition Qge_bool (a b : Q) : bool := Qle_bool b a.\nDefinition Qlt_bool (a b : Q) : bool := andb (Qle_bool a b) (negb (Qeq_bool a b)).\nDefinition Qgt_bool (a b : Q) : bool := Qlt_bool b a.\n\nLemma Qsquare_nonneg : forall (a : Q),\n 0 <= a * a.\nProof.\n  intros a. unfold Qle. simpl. rewrite Zmult_1_r. apply Z.square_nonneg. Qed.\n\nLemma Qsquare_gt_0 : forall (a : Q),\n  (~a == 0) -> (a*a) > 0.\nProof.\n  intros. destruct a. unfold Qlt. simpl. rewrite Z.mul_1_r. unfold Qeq in H.\n  simpl in H. rewrite Z.mul_1_r in H. destruct Qnum. exfalso. apply H. reflexivity.\n  apply Z.mul_pos_pos; reflexivity. apply Z.mul_neg_neg; reflexivity. Qed.\n\nLemma Qopp_mult_distr_l : forall (a b : Q),\n  Qopp (a * b) == (Qopp a) * b.\nProof.\n  intros. unfold Qmult. simpl. unfold Qeq. simpl.\n  rewrite <- (Zopp_mult_distr_l (Qnum a) (Qnum b)). reflexivity.\nQed.\n\nLemma Qopp_mult_distr_r : forall (a b : Q),\n  Qopp (a * b) == a * (Qopp b).\nProof.\n  intros. unfold Qmult. simpl. unfold Qeq. simpl.\n  rewrite <- (Zopp_mult_distr_r (Qnum a) (Qnum b)). reflexivity.\nQed.\n\nLemma Qplus_diag_eq_mult_2 : forall (a : Q),\n  Qplus a a == Qmult (2#1) a.\nProof.\n  intros. unfold Qeq, Qmult, Qplus. simpl.\n  rewrite Zplus_diag_eq_mult_2. repeat rewrite <- Zmult_assoc.\n  rewrite (Zmult_assoc _ 2 _). rewrite (Zmult_comm _ 2).\n  repeat rewrite Zmult_assoc. rewrite (Zmult_comm _ 2).\n  repeat rewrite <- Zmult_assoc. rewrite (Zmult_assoc 2 _ _).\n  simpl. reflexivity. Qed.\n\nLemma Qle_neq_lt : forall (a b : Q),\n  a <= b -> ~ a == b -> a < b.\nProof.\n  intros. apply Qle_lteq in H. inversion H.\n  apply H1. exfalso. apply H0. apply H1. Qed.\n\n(*****************************************************************************************\n    Definitions and Fixpoints for operations on Qvecs\n    (Also includes Fixpoints/Computation on Training Data: list ((Qvec n)*bool))\n *****************************************************************************************)\n\n(** Hacking this to avoid changing everything. Always normalize/reduce after plus and mult **)\nDefinition Qplus (a b : Q) : Q := Qred (Qplus a b).\nInfix \"+\" := Qplus : Q_scope.\nDefinition Qmult (a b : Q) : Q := Qred (Qmult a b).\nInfix \"*\" := Qmult : Q_scope.\n\nDefinition Qvec := Vector.t Q.\nDefinition Qvec_plus {n:nat} (v1 v2 : Qvec n) := map2 Qplus v1 v2.\nDefinition Qvec_dot {n:nat} (v1 v2 : Qvec n) := fold_left Qplus 0 (map2 Qmult v1 v2).\nDefinition Qvec_normsq {n:nat} (v1 : Qvec n) := Qvec_dot v1 v1.\nDefinition Qvec_zero (n : nat) : Qvec n := const 0 n.\n\nDefinition class (i : Q) : bool := Qle_bool 0 i.\nDefinition correct_class (i : Q) (l : bool) : bool :=\n  andb (Bool.eqb l (class i)) (negb (Qeq_bool i 0)).\nDefinition Qvec_mult_class {n:nat} (l :bool) (f : Qvec n) :=\n  if l then f else map (Qmult (-1%Z#1)) f.\nDefinition Qvec_mult_scalar {n : nat} (s : Q) (f : Qvec n) := map (Qmult s) f.\nDefinition consb {n : nat} (v : Qvec n) := cons _ 1 _ v.\n\nFixpoint Qvec_sum_class {n : nat} (w : Qvec (S n)) (M : list ((Qvec n)*bool)) : Qvec (S n) :=\n  match M with\n  | List.nil => w\n  | List.cons (f, l) M' => Qvec_sum_class (Qvec_plus w (Qvec_mult_class l (consb f))) M'\n  end.\n\nFixpoint Qvec_sum {n : nat} (M : list ((Qvec n)*bool)) : Qvec (S n) :=\n  match M with\n  | List.nil => Qvec_zero (S n)\n  | List.cons (f, l) M' => Qvec_plus (Qvec_mult_class l (consb f)) (Qvec_sum M')\n  end.\n\nFixpoint min_element_product {n : nat} (w : Qvec (S n)) (T: list ((Qvec n)*bool)) : Q :=\n  match T with\n  | List.nil => 1 (* avoid divide by zero *)\n  | List.cons (f, l) List.nil => Qvec_dot w (Qvec_mult_class l (consb f))\n  | List.cons (f, l) T' =>\n      if (Qle_bool (Qvec_dot w (Qvec_mult_class l (consb f))) (min_element_product w T'))\n      then (Qvec_dot w (Qvec_mult_class l (consb f)))\n      else (min_element_product w T')\n  end.\n\nFixpoint max_element_normsq {n : nat} (T: list ((Qvec n)*bool)) : Q :=\n  match T with\n  | List.nil => 1\n  | List.cons (f, l) List.nil => (Qvec_normsq (consb f))\n  | List.cons (f, l) T' =>\n      if (Qge_bool (Qvec_normsq (consb f)) (max_element_normsq T'))\n      then (Qvec_normsq (consb f))\n      else (max_element_normsq T')\n  end.\n\nFixpoint Qvec_sum_normsq {n:nat} (L: list ((Qvec n)*bool)) : Q :=\n  match L with\n  | List.nil => 0\n  | List.cons (f, l) L' => Qplus (Qvec_normsq (consb f)) (Qvec_sum_normsq L')\n  end.\n\nFixpoint Qvec_sum_dot {n:nat} (w : Qvec (S n)) (L: list ((Qvec n)*bool)) : Q :=\n  match L with\n  | List.nil => 0\n  | List.cons (f, l) L' => Qplus (Qvec_dot w (Qvec_mult_class l (consb f))) (Qvec_sum_dot w L')\n  end.\n\nFixpoint Qvec_foil {n:nat} (w : Qvec (S n)) (L: list ((Qvec n)*bool)) : Q :=\n  match L with\n  | List.nil => 0\n  | List.cons (f, l) L' => Qplus (Qvec_dot w (Qvec_mult_class l (consb f)))\n                                 (Qvec_foil (Qvec_plus w (Qvec_mult_class l (consb f))) L')\n  end.\n\n (****************************************************************************************\n    Case Analysis for Vectors + Induction Principles for multiple vectors.\n  ****************************************************************************************)\nDefinition Vector_0_is_nil {A} (v : t A 0) : v = nil A :=\nmatch v with\n| nil _ => eq_refl\nend.\n\nDefinition Vector_S_is_cons {A} {n} (v: t A (S n)) : exists a, exists v0, v = cons A a n v0 :=\nmatch v as v' in t _ n1\n  return match n1 return t A n1 -> Prop with\n  |O => fun _ => True\n  |S n => fun v => exists a, exists v0, v = cons A a n v0 end v' with\n| nil _ => I\n| cons _ a _ v0 => ex_intro _ a (ex_intro _ v0 (refl_equal _))\nend.\n\nLemma Vector_S_is_cons' : forall {A : Type} {n : nat} (v : t A (S n)),\n  v = cons A (hd v) n (tl v).\nProof.\n  intros. assert (H := Vector_S_is_cons v). destruct H as [a [v' H]].\n  rewrite H. simpl. reflexivity. Qed.\n\nLemma mutual_induction : forall {A B: Type} (P : forall {n : nat}, t A n -> t B n -> Prop),\n  (P (nil A) (nil B)) -> (forall (h1 : A) (h2 : B) {n : nat} (t1 : t A n) (t2 : t B n),\n  (P t1 t2) -> (P (cons A h1 n t1) (cons B h2 n t2))) ->\n  forall {n : nat} (v1 : t A n) (v2 : t B n), P v1 v2.\nProof.\n  intros. induction n. rewrite (Vector_0_is_nil v1).\n  rewrite (Vector_0_is_nil v2). apply H.\n  assert (H1 := Vector_S_is_cons v1). assert (H2 := Vector_S_is_cons v2).\n  destruct H1 as [a [v1' H1]]. destruct H2 as [b [v2' H2]]. rewrite H1.\n  rewrite H2. apply H0. apply IHn. Qed.\n\nLemma triple_induction : forall {A B C: Type} (P : forall {n : nat}, t A n -> t B n -> t C n-> Prop),\n  (P (nil A) (nil B) (nil C)) ->\n  (forall (h1 : A) (h2 : B) (h3 : C) {n : nat} (t1 : t A n) (t2 : t B n) ( t3 : t C n),\n  (P t1 t2 t3) -> (P (cons A h1 n t1) (cons B h2 n t2) (cons C h3 n t3))) ->\n  forall {n : nat} (v1 : t A n) (v2 : t B n) (v3 : t C n), P v1 v2 v3.\nProof.\n  intros. induction n. rewrite (Vector_0_is_nil v1). rewrite (Vector_0_is_nil v2).\n  rewrite (Vector_0_is_nil v3). apply H. assert (H1 := Vector_S_is_cons v1).\n  assert (H2 := Vector_S_is_cons v2). assert (H3 := Vector_S_is_cons v3).\n  destruct H1 as [a [v1' H1]]. destruct H2 as [b [v2' H2]].\n  destruct H3 as [c [v3' H3]]. rewrite H1. rewrite H2. rewrite H3.\n  apply H0. apply IHn. Qed.\n\n(*****************************************************************************************\n                     Qvec_Eq. Rational Equality of Qvecs.\n *****************************************************************************************)\nInductive Qvec_Eq : forall {n : nat},(Qvec n)->(Qvec n)->Prop :=\n| QNil : Qvec_Eq (nil Q) (nil Q)\n| QCons: forall {n : nat} (v1 v2 : Qvec n) (h1 h2 : Q),\n         Qvec_Eq v1 v2 -> h1 == h2 -> Qvec_Eq (cons Q h1 n v1) (cons Q h2 n v2).\nNotation \"a === b\" := (Qvec_Eq a b) (at level 70).\n\nLemma Qvec_Eq_refl : forall {n : nat} (v : Qvec n),\n  v === v.\nProof.\n  intros. induction v. apply QNil.\n  apply (QCons _ _ _ _ IHv eq_refl). Qed.\n\nLemma Qvec_Eq_symm : forall {n : nat} (v1 v2 : Qvec n),\n  v1 === v2 -> v2 === v1.\nProof.\n  intros n v1 v2. set (P := fun {n : nat} (v1 v2 : Qvec n) => v1 === v2 -> v2 === v1).\n  change (P n v1 v2). apply mutual_induction; unfold P; clear P; intros.\n  apply QNil. inversion H0; subst. apply Eqdep_dec.inj_pair2_eq_dec in H3.\n  apply Eqdep_dec.inj_pair2_eq_dec in H6. subst. apply H in H5.\n  apply QCons. apply H5. symmetry. apply H7. apply eq_nat_dec. apply eq_nat_dec. Qed.\n\nLemma Qvec_Eq_trans : forall {n : nat} (v1 v2 v3 : Qvec n),\n  v1 === v2 -> v2 === v3 -> v1 === v3.\nProof.\n  intros n v1 v2 v3. set (P := fun {n : nat} (v1 v2 v3 : Qvec n) =>\n    v1 === v2 -> v2 === v3 -> v1 === v3). change (P n v1 v2 v3).\n  apply triple_induction; unfold P; clear P; intros; simpl. apply QNil.\n  inversion H0; subst. apply Eqdep_dec.inj_pair2_eq_dec in H4.\n  apply Eqdep_dec.inj_pair2_eq_dec in H7. subst. inversion H1; subst.\n  apply Eqdep_dec.inj_pair2_eq_dec in H4. apply Eqdep_dec.inj_pair2_eq_dec in H9.\n  subst. apply QCons. apply H in H6. apply H6. apply H7.\n  apply (Qeq_trans h1 h2 h3 H8 H10). apply eq_nat_dec. apply eq_nat_dec.\n  apply eq_nat_dec. apply eq_nat_dec. Qed.\n\nInstance Qvec_Setoid : forall {n : nat},\n  Equivalence (Qvec_Eq (n := n)).\nProof.\n  intros. split; red. apply Qvec_Eq_refl.\n  apply Qvec_Eq_symm. apply Qvec_Eq_trans. Qed.\n\nTheorem Qvec_Eq_dec : forall {n : nat} (v1 v2 : Qvec n),\n  {v1 === v2} + {~ v1 === v2}.\nProof.\n  intros. induction v1. rewrite (Vector_0_is_nil v2). left. apply QNil.\n  assert (H := Vector_S_is_cons' v2). rewrite H. assert (H0 := IHv1 (tl v2)).\n  inversion H0. assert (H2 := Qeq_dec h (hd v2)). inversion H2.\n  left. apply (QCons _ _ _ _ H1 H3). right. unfold not. intros.\n  apply H3. inversion H4. apply H11. right. unfold not. intros.\n  apply H1. inversion H2. apply Eqdep_dec.inj_pair2_eq_dec in H5. rewrite <- H5.\n  apply Eqdep_dec.inj_pair2_eq_dec in H8. rewrite <- H8. apply H7.\n  apply eq_nat_dec. apply eq_nat_dec. Qed.\n\nTheorem Qvec_not_eq_symm : forall {n : nat} (v1 v2 : Qvec n),\n  ~ v1 === v2 -> ~ v2 === v1.\nProof.\n  intros. unfold not. intros. apply H. apply (Qvec_Eq_symm _ _ H0). Qed.\n\n(***************** Setoid Compatibility Results *****************)\nInstance Qvec_plus_comp : forall {n : nat},\n  Proper (Qvec_Eq==>Qvec_Eq==>Qvec_Eq) (Qvec_plus (n := n)).\nProof.\n  intros. unfold Proper; unfold respectful. induction n; intros.\n  rewrite(Vector_0_is_nil x). rewrite (Vector_0_is_nil x0).\n  rewrite(Vector_0_is_nil y). rewrite (Vector_0_is_nil y0). reflexivity.\n  assert (Hx := Vector_S_is_cons x). assert (Hx0 := Vector_S_is_cons x0).\n  assert (Hy := Vector_S_is_cons y). assert (Hy0 := Vector_S_is_cons y0).\n  destruct Hx as [hx [x' Hx]]. destruct Hx0 as [hx0 [x0' Hx0]].\n  destruct Hy as [hy [y' Hy]]. destruct Hy0 as [hy0 [y0' Hy0]]. subst.\n  inversion H0. inversion H. subst. apply Eqdep_dec.inj_pair2_eq_dec in H3.\n  apply Eqdep_dec.inj_pair2_eq_dec in H6. apply Eqdep_dec.inj_pair2_eq_dec in H10.\n  apply Eqdep_dec.inj_pair2_eq_dec in H13. subst. assert (HH := IHn _ _ H12 _ _ H5).\n  simpl. apply QCons. apply HH. rewrite H14. rewrite H7. reflexivity.\n  apply eq_nat_dec. apply eq_nat_dec. apply eq_nat_dec. apply eq_nat_dec. Qed.\n\nLemma fold_left_add_unfold : forall {n : nat} (v1 v2 : Qvec n) (A : Q),\n (fold_left Qplus A (map2 Qmult v1 v2)) == (Qplus A (fold_left Qplus 0 (map2 Qmult v1 v2))).\nProof.\n  intros n v1 v2. set (P := fun {n : nat} (v1 v2 : Qvec n) => forall A : Q,\n  Qeq (fold_left Qplus A (map2 Qmult v1 v2)) (Qplus A (fold_left Qplus 0 (map2 Qmult v1 v2)))).\n  change (P n v1 v2). apply mutual_induction; unfold P; intros; clear P.\n  simpl. unfold Qplus; rewrite Qplus_0_r. symmetry. apply Qred_correct.\n  simpl. rewrite (H (A + h1 * h2)). rewrite (H (0 + h1*h2)).\n  unfold Qplus. rewrite Qplus_0_l. repeat rewrite Qred_correct. rewrite Qplus_assoc.\n  reflexivity. Qed.\n\nInstance Qvec_dot_comp : forall {n : nat},\n  Proper (Qvec_Eq==>Qvec_Eq==>Qeq) (Qvec_dot (n := n)).\nProof.\n  intros. unfold Proper, respectful; intros. induction n.\n  rewrite (Vector_0_is_nil x). rewrite (Vector_0_is_nil x0).\n  rewrite (Vector_0_is_nil y). rewrite (Vector_0_is_nil y0). reflexivity.\n  assert (Hx := Vector_S_is_cons x). assert (Hx0 := Vector_S_is_cons x0).\n  assert (Hy := Vector_S_is_cons y). assert (Hy0 := Vector_S_is_cons y0).\n  destruct Hx as [hx [x' Hx]]. destruct Hx0 as [hx0 [x0' Hx0]].\n  destruct Hy as [hy [y' Hy]]. destruct Hy0 as [hy0 [y0' Hy0]]. subst.\n  unfold Qvec_dot. simpl. rewrite fold_left_add_unfold. fold (Qvec_dot x' x0').\n  rewrite fold_left_add_unfold. fold (Qvec_dot y' y0'). repeat rewrite Qplus_0_l.\n  inversion H0. inversion H. subst. apply Eqdep_dec.inj_pair2_eq_dec in H3.\n  apply Eqdep_dec.inj_pair2_eq_dec in H6. apply Eqdep_dec.inj_pair2_eq_dec in H10.\n  apply Eqdep_dec.inj_pair2_eq_dec in H13. subst.\n  assert (HH := IHn _ _ H12 _ _ H5). rewrite H7. rewrite H14. rewrite HH. reflexivity.\n  apply eq_nat_dec. apply eq_nat_dec. apply eq_nat_dec. apply eq_nat_dec. Qed.\n\nInstance Qvec_normsq_comp : forall {n : nat},\n  Proper (Qvec_Eq==>Qeq) (Qvec_normsq (n := n)).\nProof.\n  intros. unfold Proper, respectful, Qvec_normsq; intros.\n  rewrite H. reflexivity. Qed.\n\nInstance Qvec_mult_class_comp : forall {n : nat},\n  Proper (eq==>Qvec_Eq==>Qvec_Eq) (Qvec_mult_class (n := n)).\nProof.\n  intros. unfold Proper, respectful. intros x y Hxy v1 v2.\n  set (P := fun {n : nat} (v1 v2 : Qvec n) => v1 === v2 ->\n  Qvec_mult_class x v1 === Qvec_mult_class y v2). change (P n v1 v2). apply mutual_induction;\n  unfold P; clear P; intros. rewrite Hxy. reflexivity. rewrite Hxy.\n  inversion H0; subst. apply Eqdep_dec.inj_pair2_eq_dec in H3.\n  apply Eqdep_dec.inj_pair2_eq_dec in H6. subst. apply H in H5. unfold Qvec_mult_class.\n  destruct y. apply H0. simpl. simpl in H5. apply QCons. apply H5. rewrite H7. reflexivity.\n  apply eq_nat_dec. apply eq_nat_dec. Qed.\n\nInstance consb_comp : forall {n : nat},\n  Proper (Qvec_Eq==>Qvec_Eq) (consb (n := n)).\nProof.\n  intros. unfold Proper, respectful; intros. unfold consb.\n  apply (QCons _ _ _ _ H eq_refl). Qed.\n\nInstance Qvec_sum_class_comp : forall {n : nat},\n  Proper (Qvec_Eq==>eq==>Qvec_Eq) (Qvec_sum_class (n := n)).\nProof.\n  intros. unfold Proper, respectful; intros x y Hxy a L HL; subst.\n  generalize dependent y. generalize dependent x. induction L; intros.\n  simpl. apply Hxy. destruct a as [f l]. simpl.\n  assert (H := Qvec_Eq_refl (Qvec_mult_class l (consb f))).\n  apply (Qvec_plus_comp x y Hxy) in H. apply (IHL _ _ H). Qed.\n\nInstance min_element_product_comp : forall {n : nat},\n  Proper (Qvec_Eq==>eq==>Qeq) (min_element_product (n := n)).\nProof.\n  intros. unfold Proper, respectful; intros x y Hxy a L HL; subst.\n  generalize dependent y. generalize dependent x. induction L; intros.\n  reflexivity. destruct a as [f l]. destruct L. simpl. rewrite Hxy.\n  reflexivity. unfold min_element_product. fold (min_element_product y (p :: L)).\n  fold (min_element_product x (p :: L)). assert (IHxy := IHL _ _ Hxy).\n  repeat rewrite IHxy. repeat rewrite Hxy.\n  destruct (Qle_bool (Qvec_dot y (Qvec_mult_class l (consb f))) (min_element_product y (p :: L))).\n  rewrite Hxy. reflexivity. apply IHxy. Qed.\n\nInstance Qvec_sum_dot_comp : forall {n : nat},\n  Proper (Qvec_Eq==>eq==>Qeq) (Qvec_sum_dot (n := n)).\nProof.\n  intros. unfold Proper, respectful; intros x y Hxy a L HL; subst; induction L; intros.\n  reflexivity. destruct a as [f l]. simpl. rewrite IHL. rewrite Hxy. reflexivity. Qed.\n\nInstance Qvec_foil_comp : forall {n : nat},\n  Proper (Qvec_Eq==>eq==>Qeq) (Qvec_foil (n := n)).\nProof.\n  intros. unfold Proper, respectful. intros x y H l L HL; subst. generalize dependent y.\n  generalize dependent x. induction L; intros. reflexivity. destruct a as [f l].\n  simpl. assert (H0 := Qvec_Eq_refl (Qvec_mult_class l (consb f))).\n  apply (Qvec_plus_comp x y H) in H0. apply IHL in H0. rewrite H0.\n  rewrite H. reflexivity. Qed.\n\n(****************************************************************************************\n    Proofs about Arithmetic on Qvec, Fixpoints/Computations on Qvecs / Training Data.\n ****************************************************************************************)\nLemma Qvec_normsq_nonneg : forall {n : nat} (f : Qvec n),\n 0 <= (Qvec_normsq f).\nProof.\n  intros. induction f; unfold Qvec_normsq, Qvec_dot. unfold Qle. reflexivity.\n  simpl. rewrite fold_left_add_unfold. fold (Qvec_dot f f). fold (Qvec_normsq f).\n  unfold Qplus, Qmult; repeat rewrite Qred_correct. rewrite Qplus_0_l.\n  apply (Qplus_le_compat 0 _ 0). apply Qsquare_nonneg. apply IHf. Qed.\n\nLemma Qvec_consb_gt_0 : forall {n : nat} (f : Qvec n),\n Qvec_normsq (consb f) > 0.\nProof.\n  intros n f. unfold Qvec_normsq. unfold Qvec_dot. unfold consb. simpl.\n  rewrite fold_left_add_unfold. assert (0 + 1 * 1 == 1). unfold Qmult, Qplus;\n  rewrite Qred_correct. simpl. apply Qplus_0_l. rewrite H; clear H.\n  fold (Qvec_dot f f). fold (Qvec_normsq f). rewrite <- Qplus_0_r.\n  unfold Qplus; rewrite Qred_correct. apply (Qplus_lt_le_compat 0 _ 0). reflexivity.\n  apply Qvec_normsq_nonneg. Qed.\n\nLemma Qvec_sum_normsq_nonneg : forall {n : nat} (L : list ((Qvec n)*bool)),\n  0 <= (Qvec_sum_normsq L).\nProof.\n  intros. induction L. unfold Qle. reflexivity.\n  destruct a as [f l]. simpl. assert (H := Qvec_normsq_nonneg (consb f)).\n  unfold Qplus; rewrite Qred_correct. apply (Qplus_le_compat 0 _ 0 _ H IHL). Qed.\n\nLemma Qvec_normsq_Qvec_0 : forall (n : nat),\n Qvec_normsq (Qvec_zero n) == 0.\nProof.\n  intros n. induction n; unfold Qvec_zero, Qvec_normsq, Qvec_dot. reflexivity.\n  simpl. apply IHn. Qed.\n\nLemma normsq_mult_neg_1_same : forall {n : nat} (f : Qvec n),\n  Qvec_normsq f == Qvec_normsq (map (Qmult (-1#1)) f).\nProof.\n  intros. induction f. simpl. reflexivity.\n  unfold Qvec_normsq, Qvec_dot. simpl. rewrite fold_left_add_unfold.\n  rewrite (fold_left_add_unfold _ _ (0 + _)). fold (Qvec_dot f f). fold (Qvec_normsq f).\n  fold (Qvec_dot (map (Qmult (-1#1)) f) (map (Qmult (-1#1)) f)).\n  fold (Qvec_normsq (map (Qmult (-1#1)) f)). repeat rewrite Qplus_0_l.\n  assert (Qopp 1 = (-1#1)). reflexivity. repeat rewrite <- H.\n  unfold Qmult, Qplus; repeat rewrite Qred_correct.\n  rewrite <- Qopp_mult_distr_l. repeat rewrite Qmult_1_l.\n  rewrite <- Qopp_mult_distr_l. rewrite <- Qopp_mult_distr_r. rewrite Qopp_involutive.\n  rewrite IHf. rewrite <- H. reflexivity. Qed.\n\nLemma Qvec_dot_mult_neg_1 : forall {n:nat} (v1 v2 : Qvec n),\n  Qvec_dot v1 (map (Qmult (-1#1)) v2) == Qmult (-1#1) (Qvec_dot v1 v2).\nProof.\n  intros n v1 v2. set (P := fun (n : nat) (v1 v2 : t Q n) =>\n  Qvec_dot v1 (map (Qmult (-1#1)) v2) == Qmult (-1#1) (Qvec_dot v1 v2)).\n  change (P n v1 v2). apply mutual_induction; unfold P; clear P.\n  { unfold Qvec_dot, Qmult, Qplus. simpl. reflexivity. }\n  intros. unfold Qvec_dot. simpl. rewrite fold_left_add_unfold.\n  rewrite (fold_left_add_unfold t1 t2 _). fold (Qvec_dot t1 t2).\n  unfold Qplus, Qmult; repeat rewrite Qred_correct. rewrite Qplus_0_l.\n  rewrite Qplus_0_l. assert (-1#1 = Qopp 1). reflexivity. rewrite H0.\n  rewrite <- Qopp_mult_distr_l. rewrite <- Qopp_mult_distr_r. rewrite Qmult_1_l.\n  rewrite <- Qopp_mult_distr_l. rewrite Qmult_1_l. rewrite Qopp_plus.\n  rewrite H0 in H. unfold Qmult, Qplus in H. repeat rewrite Qred_correct in H.\n  rewrite <- Qopp_mult_distr_l in H. rewrite Qmult_1_l in H.\n  rewrite <- H. unfold Qvec_dot. reflexivity. Qed.\n\nLemma Qvec_dot_add_sub_mult_eq : forall {n : nat} (v1 v2 v3 : Qvec n),\n  Qvec_dot v1 v2 == Qminus (Qvec_dot (Qvec_plus v1 v3) v2) (Qvec_dot v3 v2).\nProof.\n  intros. set (P := fun {n} (v1 v2 v3 : Qvec n) => Qvec_dot v1 v2 ==\n  Qminus (Qvec_dot (Qvec_plus v1 v3) v2) (Qvec_dot v3 v2)). change (P n v1 v2 v3).\n  apply triple_induction; unfold P; clear P; intros; unfold Qvec_dot.\n  { reflexivity. }\n  simpl. rewrite fold_left_add_unfold. fold (Qvec_dot t1 t2).\n  unfold Qplus, Qmult; repeat rewrite Qred_correct. rewrite Qplus_0_l.\n  rewrite fold_left_add_unfold. fold (Qvec_dot (Qvec_plus t1 t3) t2).\n  rewrite Qplus_0_l. rewrite fold_left_add_unfold. fold (Qvec_dot t3 t2).\n  rewrite Qplus_0_l. unfold Qminus, Qplus. repeat rewrite Qred_correct.\n  rewrite Qopp_plus. rewrite <- Qplus_assoc. rewrite (Qplus_comm (Qopp _) (Qopp _)).\n  rewrite (Qplus_assoc (Qvec_dot _ _) (Qopp _) (Qopp _)).\n  rewrite (Qplus_comm (_ _ _) (Qopp _)).\n  fold (Qminus (Qvec_dot (Qvec_plus t1 t3) t2) (Qvec_dot t3 t2)).\n  rewrite <- H. rewrite Qplus_assoc. rewrite Qmult_plus_distr_l.\n  repeat rewrite <- Qplus_assoc. rewrite (Qplus_assoc (_ h3 h2) _ _).\n  rewrite Qplus_opp_r. rewrite Qplus_0_l. reflexivity. Qed.\n\nLemma Qvec_normsq_cons : forall {n : nat} (h : Q) (t : Qvec n),\n  Qvec_normsq (cons Q h n t) == Qplus (Qmult h h) (Qvec_normsq t).\nProof.\n  intros. unfold Qvec_normsq, Qvec_dot. simpl. rewrite fold_left_add_unfold.\n  unfold Qplus, Qmult; repeat rewrite Qred_correct. rewrite Qplus_0_l. reflexivity. Qed.\n\nLemma Qvec_dot_cons : forall {n : nat} (h1 h2 : Q) (t1 t2 : Qvec n),\n  Qvec_dot (cons Q h1 n t1) (cons Q h2 n t2) == Qplus (Qmult h1 h2) (Qvec_dot t1 t2).\nProof.\n  intros. unfold Qvec_dot. simpl. rewrite fold_left_add_unfold.\n  unfold Qplus, Qmult; repeat rewrite Qred_correct. rewrite Qplus_0_l. reflexivity. Qed.\n\nLemma Qvec_normsq_plus : forall {n: nat} (v1 v2 : Qvec n),\n  Qvec_normsq (Qvec_plus v1 v2) == Qplus (Qplus (Qvec_normsq v1) (Qmult (2#1) (Qvec_dot v1 v2))) (Qvec_normsq v2).\nProof.\n  intros.  set (P := fun {n} (v1 v2 : Qvec n) => Qvec_normsq (Qvec_plus v1 v2) ==\n  Qplus (Qplus (Qvec_normsq v1) (Qmult (2#1) (Qvec_dot v1 v2))) (Qvec_normsq v2)).\n  change (P n v1 v2). apply mutual_induction; unfold P; intros. reflexivity.\n  unfold Qvec_plus. simpl. repeat rewrite Qvec_normsq_cons. rewrite Qvec_dot_cons.\n  fold (Qvec_plus t1 t2). unfold Qplus, Qmult; repeat rewrite Qred_correct.\n  rewrite (Qmult_plus_distr_r (2#1)). repeat rewrite <- Qplus_assoc.\n  rewrite (Qplus_assoc _  _ (Qvec_normsq t2)). rewrite (Qplus_comm (_ (2#1) (Qvec_dot t1 t2))).\n  rewrite (Qplus_assoc (Qvec_normsq t1)). rewrite (Qplus_comm (Qvec_normsq t1) _).\n  rewrite <- Qplus_assoc. repeat rewrite (Qplus_assoc (Qvec_normsq t1) _ _).\n  rewrite (Qplus_comm (Qvec_normsq t1)). repeat rewrite <- Qplus_assoc.\n  rewrite (Qplus_assoc (Qvec_normsq t1) _ _). unfold Qplus, Qmult in H;\n  repeat rewrite Qred_correct in H; rewrite <- H. repeat rewrite Qplus_assoc.\n  rewrite Qmult_plus_distr_l. repeat rewrite Qmult_plus_distr_r.\n  rewrite (Qmult_comm h2 h1). rewrite <- Qplus_diag_eq_mult_2.\n  repeat rewrite Qplus_assoc. reflexivity. Qed.\n\nLemma Qvec_dot_Qvec_zero_l : forall {n : nat} (v : Qvec n),\n  Qvec_dot (Qvec_zero n) v == 0.\nProof.\n  intros. induction v; unfold Qvec_dot. reflexivity.\n  simpl. rewrite fold_left_add_unfold. unfold Qplus, Qmult;\n  repeat rewrite Qred_correct; rewrite Qplus_0_l.\n  rewrite Qmult_0_l. rewrite Qplus_0_l. apply IHv. Qed.\n\nLemma Qvec_dot_Qvec_zero_r : forall {n : nat} (v : Qvec n),\n  Qvec_dot v (Qvec_zero n) == 0.\nProof.\n  intros. induction v; unfold Qvec_dot. reflexivity.\n  simpl. rewrite fold_left_add_unfold. unfold Qplus, Qmult;\n  repeat rewrite Qred_correct; rewrite Qplus_0_l.\n  rewrite Qmult_0_r. rewrite Qplus_0_l. apply IHv. Qed.\n\nLemma Qvec_plus_Qvec_zero : forall {n : nat} (v : Qvec n),\n  Qvec_plus (Qvec_zero n) v === v.\nProof.\n  intros. induction v; unfold Qvec_plus. reflexivity.\n  simpl. fold (Qvec_zero n). fold (Qvec_plus (Qvec_zero n) v).\n  apply QCons. apply IHv. unfold Qplus; rewrite Qred_correct;\n  apply Qplus_0_l. Qed.\n\nLemma Qvec_plus_Qvec_zero_r : forall {n : nat} (v : Qvec n),\n  Qvec_plus v (Qvec_zero n) === v.\nProof.\n  intros. induction v; unfold Qvec_plus. reflexivity.\n  simpl. fold (Qvec_zero n). fold (Qvec_plus v (Qvec_zero n)).\n  apply QCons. apply IHv. unfold Qplus; rewrite Qred_correct;\n  apply Qplus_0_r. Qed.\n\nLemma Qvec_dot_dist_l : forall {n : nat} (v1 v2 v3 : Qvec n),\n  Qvec_dot (Qvec_plus v1 v2) v3 == Qplus (Qvec_dot v1 v3) (Qvec_dot v2 v3).\nProof.\n  intros. set (P := fun {n} (v1 v2 v3 : Qvec n) =>\n  Qvec_dot (Qvec_plus v1 v2) v3 == Qplus (Qvec_dot v1 v3) (Qvec_dot v2 v3)).\n  change (P n v1 v2 v3). apply triple_induction; unfold P; intros. reflexivity.\n  simpl. repeat rewrite Qvec_dot_cons. rewrite H. unfold Qplus, Qmult;\n  repeat rewrite Qred_correct; rewrite Qmult_plus_distr_l.\n  repeat rewrite <- Qplus_assoc. rewrite (Qplus_assoc (Qvec_dot t1 t3) _ _).\n  rewrite (Qplus_comm (Qvec_dot t1 t3) (QArith_base.Qmult h2 h3)).\n  repeat rewrite Qplus_assoc. reflexivity. Qed.\n\nLemma Qvec_dot_dist_r : forall {n : nat} (v1 v2 v3 : Qvec n),\n  Qvec_dot v1 (Qvec_plus v2 v3) == Qplus (Qvec_dot v1 v2) (Qvec_dot v1 v3).\nProof.\n  intros. set (P := fun {n} (v1 v2 v3 : Qvec n) =>\n  Qvec_dot v1 (Qvec_plus v2 v3) == Qplus (Qvec_dot v1 v2) (Qvec_dot v1 v3)).\n  change (P n v1 v2 v3). apply triple_induction; unfold P; clear P; intros. reflexivity.\n  simpl. repeat rewrite Qvec_dot_cons. rewrite H. unfold Qplus, Qmult; repeat rewrite Qred_correct;\n  rewrite Qmult_plus_distr_r. repeat rewrite <- Qplus_assoc.\n  rewrite (Qplus_assoc (Qvec_dot t1 t2) _ _). rewrite (Qplus_comm (Qvec_dot t1 t2)\n  (QArith_base.Qmult h1 h3)). repeat rewrite Qplus_assoc. reflexivity. Qed.\n\nLemma Qvec_plus_shuffle : forall {n: nat} (v1 v2 v3 : Qvec n),\n  Qvec_plus (Qvec_plus v1 v2) v3 === Qvec_plus (Qvec_plus v1 v3) v2.\nProof.\n  intros. set (P := fun n (v1 v2 v3 : Qvec n) => \n  Qvec_plus (Qvec_plus v1 v2) v3 === Qvec_plus (Qvec_plus v1 v3) v2). change (P n v1 v2 v3).\n  apply triple_induction; unfold P; clear P; intros; simpl. apply QNil.\n  apply QCons. apply H. unfold Qplus; repeat rewrite Qred_correct;\n  rewrite <- Qplus_assoc. rewrite (Qplus_comm h2 h3). apply Qplus_assoc. Qed.\n\nLemma Qvec_plus_comm : forall {n : nat} (v1 v2 : Qvec n),\n  Qvec_plus v1 v2 === Qvec_plus v2 v1.\nProof.\n  intros. set (P := fun {n : nat} (v1 v2 : Qvec n) => Qvec_plus v1 v2 === Qvec_plus v2 v1).\n  change (P n v1 v2). apply mutual_induction; unfold P; clear P; intros; simpl. apply QNil.\n  apply QCons. apply H. unfold Qplus. rewrite Qplus_comm. reflexivity. Qed.\n\nLemma Qvec_foil_w_0 : forall {n : nat} (v1 v2 : Qvec (S n)) (L : list ((Qvec n)*bool)),\n  Qplus (Qvec_dot v1 (Qvec_sum L)) (Qvec_foil v2 L) == Qvec_foil (Qvec_plus v2 v1) L.\nProof.\n  intros; generalize dependent v1; generalize dependent v2; induction L; intros.\n  simpl. rewrite Qvec_dot_Qvec_zero_r. reflexivity. destruct a as [f l].\n  unfold Qvec_sum. fold (Qvec_sum L). unfold Qvec_foil.\n  fold (Qvec_foil (Qvec_plus v2 (Qvec_mult_class l (consb f)))).\n  fold (Qvec_foil (Qvec_plus (Qvec_plus v2 v1) (Qvec_mult_class l (consb f)))).\n  rewrite Qvec_dot_dist_r. unfold Qplus; repeat rewrite Qred_correct.\n  rewrite Qplus_assoc. assert (forall (A B C D : Q),\n  QArith_base.Qplus (QArith_base.Qplus (QArith_base.Qplus A B) C) D == \n  QArith_base.Qplus (QArith_base.Qplus A C) (QArith_base.Qplus B D)). intros.\n  repeat rewrite <- Qplus_assoc. rewrite (Qplus_assoc C B D). rewrite (Qplus_comm C B).\n  repeat rewrite <- Qplus_assoc. reflexivity.\n  rewrite H; clear H. assert (H := IHL (Qvec_plus v2 (Qvec_mult_class l (consb f))) v1).\n  unfold Qplus in H; repeat rewrite Qred_correct in H. rewrite H.\n  assert (H0 := Qvec_dot_dist_l v1 v2 (Qvec_mult_class l (consb f))).\n  unfold Qplus in H0; rewrite Qred_correct in H0. rewrite <- H0.\n  rewrite Qvec_plus_shuffle. rewrite Qvec_plus_comm. reflexivity. Qed.\n\nLemma Qvec_dot_sum_eq : forall {n : nat} (w : Qvec (S n)) (L : list ((Qvec n)*bool)),\n  Qvec_dot w (Qvec_sum L) == Qvec_sum_dot w L.\nProof.\n  intros. induction L. simpl.\n  rewrite Qvec_dot_Qvec_zero_r. apply Qeq_refl.\n  destruct a as [f l].\n  simpl. rewrite Qvec_dot_dist_r. rewrite IHL. reflexivity. Qed.\n\nLemma Qvec_foil_0_w : forall {n : nat} (v1 v2 : Qvec (S n)) (L : list ((Qvec n)*bool)),\n  Qvec_foil v1 L == Qminus (Qvec_foil (Qvec_plus v1 v2) L) (Qvec_sum_dot v2 L).\nProof.\n  intros. assert (H := Qvec_foil_w_0 v2 v1 L). rewrite <- (Qplus_inj_r _ _ (Qvec_sum_dot v2 L)).\n  unfold Qminus. rewrite <- Qplus_assoc. rewrite (Qplus_comm (Qopp _) _). rewrite Qplus_opp_r.\n  rewrite Qplus_0_r. rewrite <- H. rewrite Qvec_dot_sum_eq. unfold Qplus; rewrite Qred_correct.\n  apply Qplus_comm. Qed.\n\nLemma Qvec_normsq_eq_sum_normsq_foil : forall {n: nat} (L : list ((Qvec n)*bool)),\n  Qvec_normsq (Qvec_sum L) == Qplus (Qvec_sum_normsq L) (Qmult (2#1) (Qvec_foil (Qvec_zero (S n)) L)).\nProof.\n  intros. induction L. simpl. unfold Qplus, Qmult; rewrite Qred_correct.\n  rewrite Qmult_0_r. rewrite Qplus_0_l. apply Qvec_normsq_Qvec_0.\n  destruct a as [f l]. unfold Qvec_normsq, Qvec_sum. fold (Qvec_sum L).\n  unfold Qvec_sum_normsq. fold (Qvec_sum_normsq L). unfold Qvec_foil.\n  fold (Qvec_foil (Qvec_plus (Qvec_zero (S n)) (Qvec_mult_class l (consb f))) L).\n  fold (Qvec_normsq (Qvec_plus (Qvec_mult_class l (consb f)) (Qvec_sum L))).\n  rewrite Qvec_normsq_plus. assert (Qvec_normsq (Qvec_mult_class l (consb f)) == Qvec_normsq (consb f)).\n  destruct l. reflexivity. unfold Qvec_mult_class. rewrite <- normsq_mult_neg_1_same. reflexivity.\n  rewrite H; clear H. rewrite IHL. unfold Qplus, Qmult; repeat rewrite Qred_correct.\n  rewrite <- Qplus_assoc. rewrite (Qplus_assoc (QArith_base.Qmult (2#1) _) (Qvec_sum_normsq L) _).\n  rewrite (Qplus_comm (QArith_base.Qmult (2#1) _) (Qvec_sum_normsq L)). repeat rewrite <- Qplus_assoc.\n  rewrite Qvec_dot_Qvec_zero_l. repeat rewrite Qplus_0_l. rewrite <- Qmult_plus_distr_r.\n  assert (H := Qvec_foil_w_0 (Qvec_mult_class l (consb f)) (Qvec_zero (S n)) L).\n  unfold Qplus in H; rewrite Qred_correct in H. rewrite H. reflexivity. Qed.\n\nLemma Qvec_plus_assoc : forall {n : nat} (v1 v2 v3 : Qvec n),\n  Qvec_plus (Qvec_plus v1 v2) v3 === Qvec_plus v1 (Qvec_plus v2 v3).\nProof.\n  intros. set (P := fun n (v1 v2 v3 : Qvec n) => \n  Qvec_plus (Qvec_plus v1 v2) v3 === Qvec_plus v1 (Qvec_plus v2 v3)). change (P n v1 v2 v3).\n  apply triple_induction; unfold P; clear P; intros. reflexivity.\n  simpl. apply QCons. apply H. symmetry. unfold Qplus; repeat rewrite Qred_correct;\n  apply Qplus_assoc. Qed.\n\nLemma Qvec_foil_append : forall {n : nat} (L1 L2 : list ((Qvec n)*bool)) (v : Qvec (S n)),\n  Qvec_foil v (List.app L1 L2) == Qplus (Qvec_foil v L1) (Qvec_foil (Qvec_plus v (Qvec_sum L1)) L2).\nProof.\n  intros n L1. induction L1; intros. simpl. rewrite Qvec_plus_Qvec_zero_r. symmetry.\n  unfold Qplus; rewrite Qplus_0_l; apply Qred_correct.\n  destruct a as [f l]. simpl. rewrite IHL1. rewrite Qvec_plus_assoc.\n  unfold Qplus; repeat rewrite Qred_correct; rewrite Qplus_assoc. reflexivity. Qed.\n\nLemma Qvec_sum_sum_class : forall {n : nat} (w : Qvec (S n)) (L : list ((Qvec n)*bool)),\n  Qvec_plus w (Qvec_sum L) === Qvec_sum_class w L.\nProof.\n  intros. generalize dependent w; induction L; intros. simpl.\n  rewrite Qvec_plus_Qvec_zero_r. apply Qvec_Eq_refl.\n  destruct a as [f l]. simpl. rewrite <- Qvec_plus_assoc. apply IHL. Qed.\n\nLemma Qvec_sum_class_append : forall {n : nat} (w0: Qvec (S n)) (M1 M2: (list ((Qvec n)*bool))),\n  Qvec_sum_class (Qvec_sum_class w0 M1) M2 = Qvec_sum_class w0 (List.app M1 M2).\nProof.\n  intros n w0 M1. generalize dependent w0. induction M1; intros.\n  { reflexivity. } destruct a as [f l]. simpl. apply IHM1. Qed.\n\nLemma Qvec_dot_comm : forall {n : nat} (v1 v2 : Qvec n),\n  Qvec_dot v1 v2 == Qvec_dot v2 v1.\nProof.\n  intros. set (P := fun n (v1 v2 : Qvec n) => Qvec_dot v1 v2 == Qvec_dot v2 v1).\n  change (P n v1 v2). apply mutual_induction; unfold P; clear P; intros. reflexivity.\n  repeat (rewrite Zvec_dot_cons). repeat rewrite Qvec_dot_cons. rewrite H.\n  unfold Qmult; rewrite Qmult_comm. reflexivity. Qed.\n\nLemma Qvec_dot_Not_Qvec_zero : forall {n : nat} (v1 v2 : Qvec n),\n  (~ Qvec_dot v1 v2 == 0) -> (~ v1 === Qvec_zero n) /\\ (~ v2 === Qvec_zero n).\nProof.\n  intros. split. unfold not; intros. apply H. rewrite H0. apply Qvec_dot_Qvec_zero_l.\n  unfold not; intros. apply H. rewrite H0. apply Qvec_dot_Qvec_zero_r. Qed.\n\nLemma Qvec_cons_Not_Qvec_zero : forall {n : nat} (v1 : Qvec n) (h : Q),\n  (~ cons Q h n v1 === Qvec_zero (S n)) -> (~ h == 0) \\/ (~ v1 === Qvec_zero n).\nProof.\n  intros n v1; induction v1; intros. unfold Qvec_zero in H. simpl in H. left. unfold not.\n  intros. apply H. apply (QCons _ _ _ _ QNil H0). assert (H0 := Qeq_dec h0 0). destruct H0.\n  { right. unfold not. intros. apply H. unfold Qvec_zero, const. fold (const 0 (S n)).\n  fold (Qvec_zero (S n)). apply QCons. apply H0. apply q. } left. apply n0. Qed.\n\nLemma Qvec_normsq_Not_Qvec_Zero : forall {n : nat} (v1 : Qvec n),\n  (~ v1 === Qvec_zero n) -> Qvec_normsq v1 > 0.\nProof.\n  intros. induction v1. exfalso. apply H. reflexivity.\n  apply Qvec_cons_Not_Qvec_zero in H. inversion H. apply Qsquare_gt_0 in H0.\n  unfold Qvec_normsq. rewrite Qvec_dot_cons. fold (Qvec_normsq v1).\n  unfold Qplus, Qmult; repeat rewrite Qred_correct. rewrite <- Qplus_0_r.\n  apply (Qplus_lt_le_compat 0 _ 0 _ H0). apply Qvec_normsq_nonneg.\n  apply IHv1 in H0. unfold Qvec_normsq. rewrite Qvec_dot_cons.\n  fold (Qvec_normsq v1). unfold Qplus, Qmult; repeat rewrite Qred_correct.\n  rewrite Qplus_comm. apply (Qplus_lt_le_compat 0 _ 0 _ H0 (Qsquare_nonneg _)). Qed.\n\nLemma Qvec_sum_dot_append : forall {n : nat} (L1 L2 : list ((Qvec n)*bool)) (w : Qvec (S n)),\n  Qvec_sum_dot w (List.app L1 L2) == Qplus (Qvec_sum_dot w L1) (Qvec_sum_dot w L2).\nProof.\n  intros n L1; induction L1; intros. simpl. symmetry. unfold Qplus;\n  rewrite Qplus_0_l; apply Qred_correct.\n  destruct a as [f l]. simpl. rewrite IHL1. unfold Qplus; repeat rewrite Qred_correct. \n  repeat (rewrite Qplus_assoc). reflexivity. Qed.\n\nLemma Qfoil : forall (A B C D : Q),\n (A + B) * (C + D) == (A * C) + (A * D) + (B * C) + (B * D).\nProof.\n  intros. unfold Qplus, Qmult; repeat rewrite Qred_correct.\n  rewrite Qmult_plus_distr_l. repeat (rewrite Qmult_plus_distr_r).\n  apply Qplus_assoc. Qed.\n\nLemma CSHH : forall (A B : Q),\n  (A * B) + (A * B) <= (A * A) + (B * B).\nProof.\n  intros. assert ((A - B) * (A - B) == (QArith_base.Qplus (A * A) (B * B)) - (QArith_base.Qplus (A * B) (A * B))).\n  unfold Qminus. assert (H := Qfoil A (Qopp B) A (Qopp B)).\n  unfold Qplus in H; repeat rewrite Qred_correct in H. rewrite H. unfold Qmult; repeat rewrite Qred_correct.\n  repeat rewrite <- Qopp_mult_distr_r. repeat rewrite <- Qopp_mult_distr_l.\n  rewrite Qopp_involutive. repeat rewrite <- Qplus_assoc.\n  rewrite (Qplus_comm _ (_ B B)). rewrite (Qplus_assoc _ (_ B B) _). rewrite (Qplus_comm _ (_ B B)).\n  repeat rewrite <- Qplus_assoc. rewrite <- Qopp_plus. rewrite (Qmult_comm B A). reflexivity. \n  assert (0 <= (A - B) * (A - B)). unfold Qmult; rewrite Qred_correct. apply Qsquare_nonneg.\n  rewrite H in H0. apply (Qplus_le_l _ _ (A * B + A * B)) in H0. rewrite Qplus_0_l in H0.\n  unfold Qminus in H0. rewrite <- Qplus_assoc in H0.\n  rewrite (Qplus_comm _ (_ (A*B) (A*B))) in H0.\n  unfold Qplus in H0 at 2. rewrite Qred_correct in H0. rewrite Qplus_opp_r in H0.\n  rewrite Qplus_0_r in H0. unfold Qplus at 2. rewrite Qred_correct. apply H0. Qed.\n\n(* This is trivialy true if the parity of negatives is odd *)\nLemma Cauchy_Schwarz_helper': forall (A B C D : Q),\n  A*B*C*D + A*B*C*D <= A*A*D*D + B*B*C*C.\nProof.\n  intros. assert (forall (A B C D : Q), A*B*C*D == A*D*(B*C)). intros.\n  unfold Qplus, Qmult; repeat rewrite Qred_correct.\n  rewrite (Qmult_comm B0 C0). rewrite <- Qmult_assoc. rewrite <- Qmult_assoc.\n  rewrite (Qmult_comm B0 (_ C0 D0)). rewrite Qmult_assoc. rewrite (Qmult_comm C0 D0).\n  repeat rewrite Qmult_assoc. reflexivity. repeat rewrite H. apply CSHH. Qed.\n\nLemma Cauchy_Schwarz_helper : forall {n : nat} (v1 v2 : Qvec n) (A B : Q),\n  A*B*(Qvec_dot v1 v2) + A*B*(Qvec_dot v1 v2) <= A*A*(Qvec_normsq v2) + B*B*(Qvec_normsq v1).\nProof.\n  intros n v1 v2. set (P := fun n (v1 v2 : Qvec n) => forall (A B : Q),\n  A*B*(Qvec_dot v1 v2) + A*B*(Qvec_dot v1 v2) <= A*A*(Qvec_normsq v2) + B*B*(Qvec_normsq v1)).\n  change (P n v1 v2). apply mutual_induction; unfold P; clear P; intros.\n  unfold Qvec_normsq, Qvec_dot; simpl. unfold Qmult; repeat rewrite Qred_correct.\n  repeat rewrite Qmult_0_r. apply Qle_refl. repeat (rewrite Qvec_dot_cons). repeat (rewrite Qvec_normsq_cons).\n  unfold Qplus, Qmult; repeat rewrite Qred_correct.\n  repeat (rewrite Qmult_plus_distr_r). repeat (rewrite Qplus_assoc). repeat (rewrite Qmult_assoc).\n  assert (forall (A B C D : Q), (QArith_base.Qplus (QArith_base.Qplus (QArith_base.Qplus A B) C) D) == \n  (QArith_base.Qplus (QArith_base.Qplus A C) (QArith_base.Qplus B D))). intros.\n  repeat rewrite <- Qplus_assoc. rewrite (Qplus_assoc B0 C D). rewrite (Qplus_comm B0 C).\n  rewrite <- Qplus_assoc. reflexivity. unfold Qplus in H0. repeat rewrite H0; clear H0.\n  assert (H0 := Cauchy_Schwarz_helper' A B h1 h2). apply Qplus_le_compat.\n  unfold Qplus, Qmult in H0; repeat rewrite Qred_correct in H0; apply H0.\n  assert (H1 := H A B). unfold Qplus, Qmult in H1; repeat rewrite Qred_correct in H1; apply H1. Qed.\n\nLemma Cauchy_Schwarz_inequality : forall {n : nat} (v1 v2 : Qvec n),\n  (Qvec_dot v1 v2)*(Qvec_dot v1 v2) <= (Qvec_normsq v1)*(Qvec_normsq v2).\nProof.\n  intros. set (P := fun n (v1 v2 : Qvec n) =>\n  (Qvec_dot v1 v2)*(Qvec_dot v1 v2) <= (Qvec_normsq v1)*(Qvec_normsq v2)). change (P n v1 v2).\n  apply mutual_induction; unfold P; clear P; intros. apply Qle_refl.\n  repeat (rewrite Qvec_dot_cons). repeat (rewrite Qvec_normsq_cons). repeat (rewrite Qfoil).\n  unfold Qplus, Qmult; repeat rewrite Qred_correct.\n  rewrite <- Qmult_assoc. rewrite (Qmult_comm h2 (QArith_base.Qmult h1 h2)). repeat rewrite Qmult_assoc.\n  repeat rewrite <- Qplus_assoc. apply Qplus_le_r.\n  repeat rewrite Qplus_assoc. apply Qplus_le_compat.\n  { repeat rewrite <- Qmult_assoc. rewrite (Qmult_comm _ (QArith_base.Qmult h1 h2)).\n    rewrite (Qmult_comm _ (QArith_base.Qmult h2 h2)). repeat rewrite Qmult_assoc.\n    assert (H0 := Cauchy_Schwarz_helper t1 t2 h1 h2). unfold Qplus, Qmult in H0;\n    repeat rewrite Qred_correct in H0. apply H0.\n  } unfold Qmult in H; repeat rewrite Qred_correct in H; apply H. Qed.", "meta": {"author": "tm507211", "repo": "CoqPerceptron", "sha": "ce154b357c0cd6f072159d26c9b6c88f28c6af5b", "save_path": "github-repos/coq/tm507211-CoqPerceptron", "path": "github-repos/coq/tm507211-CoqPerceptron/CoqPerceptron-ce154b357c0cd6f072159d26c9b6c88f28c6af5b/QvecArith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6804258521839199}}
{"text": "Require Import Coq.Relations.Relation_Operators.\nRequire Import Relation_Operators.\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Wellfounded.Lexicographic_Product.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Omega.\n\n\nDefinition compose A (R S : relation A) : relation A :=\n  fun x y => exists z, R x z /\\ S z y.\n(*Heavily based on the Lex proofs from the CoLoR library. The main difference is that I need the \n  first relation to be on the second type in the tuple because of the order of the arguments in the\n  Haskell functions*)\nSection Lex.\n  Variables (A B : Type) (ltA eqA : relation A) (ltB : relation B).\n  Inductive lex : relation (B * A) :=\n  | lex1 a a' b b' : ltA a a' -> lex (b,a) (b',a')\n  | lex2 a a' b b' : eqA a a' -> ltB b b' -> lex (b,a) (b',a').\n  Variables (WF_gtA : well_founded ltA) (WF_gtB : well_founded ltB)\n    (eqA_trans : Transitive eqA) (Hcomp : forall x y : A, (exists z : A, eqA y z /\\ ltA x z) -> ltA x y)\n    (eqA_sym: Symmetric eqA).\n  \n   Lemma lex_Acc_eq : forall a b,\n    Acc lex (b,a) -> forall a', eqA a a' -> Acc lex (b,a').\n\n  Proof.\n    intros a b SN_ab a' eqaa'. inversion SN_ab. apply Acc_intro.\n    destruct y as (a'',b'). intro H'.\n    inversion H'; subst a'0 b'0 a0 b0; apply H.\n    apply lex1. apply Hcomp. exists a'. auto. \n    apply lex2. assert (eqA a' b'). eapply eqA_sym. assumption. \n    pose proof (eqA_trans _ _ _ eqaa' H0). apply eqA_sym. assumption. assumption.\n  Qed.\n\n  Lemma lex_Acc :\n    forall a, Acc ltA a -> forall b, Acc ltB b -> Acc lex (b, a).\n\n  Proof.\n    induction 1 as [a Ha1 Ha2]. induction 1 as [b Hb1 Hb2]. apply Acc_intro.\n    destruct y as (a'',b'). intro H. inversion H. subst a'' b'0. subst a0. subst a'. (* subst a'' b'0 a0 b0.*)\n    (* gtA a a' *)\n    apply Ha2. exact H1. apply WF_gtB. \n    (* eqA a a' /\\ gtB b b' *)\n    apply (@lex_Acc_eq a).\n    apply Hb2. assumption. apply eqA_sym. assumption.\n  Qed.\n\n  Lemma WF_lex : well_founded lex.\n\n  Proof.\n    unfold well_founded. destruct a as (a,b). apply lex_Acc. apply WF_gtA. apply WF_gtB.\n  Qed.\n\nEnd Lex.\n\nDefinition f_nat_lt {a} (f: a -> nat) x y := f x < f y.\n\nLemma f_nat_lt_acc: forall {a} (f: a -> nat) x n, f x <= n -> Acc (f_nat_lt f) x.\nProof.\n  intros. generalize dependent x. induction n; auto.\n  - intros. apply Acc_intro. intros. unfold f_nat_lt in *. omega.\n  - unfold f_nat_lt in *. intros. apply Acc_intro. intros. apply IHn. omega.\nQed.\n\nLemma f_nat_lt_wf: forall {a} (f: a -> nat), well_founded (f_nat_lt f).\nProof.\n  red. intro. intro. intro. eapply f_nat_lt_acc. eauto.\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/graph/theories/Lex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6804247665700233}}
{"text": "From Coq Require Import\n     Arith\n     Lia\n     List.\n\nFrom ExtLib Require Import\n     Monad\n     Traversable\n     Data.List.\n\nFrom ITree Require Import\n     ITree\n     ITreeFacts\n     Basics.Basics\n     Basics.Category\n     Basics.CategoryKleisli\n     Basics.CategoryKleisliFacts.\n\nImport Basics.Basics.Monads.\nImport ListNotations.\nImport ITreeNotations.\nLocal Open Scope itree_scope.\n\nSection SYNTAX.\n\n  Inductive typ :=\n  | Base\n  | Arr (s:typ) (t:typ).\n\n  Variable V : typ -> Type.  (* PHOAS variables *)\n  Inductive tm : typ -> Type :=\n  | Lit (n:nat) : tm Base\n  | Var : forall (t:typ), V t -> tm t\n  | App : forall t1 t2 (m1 : tm (Arr t1 t2)) (m2 : tm t1), tm t2\n  | Lam : forall t1 t2 (body : V t1 -> tm t2), tm (Arr t1 t2)\n  | Opr : forall (m1 : tm Base) (m2 : tm Base), tm Base\n  .\n\n  Fixpoint open_tm (G : list typ) (u:typ) : Type :=\n    match G with\n    | [] => tm u\n    | t::ts =>  V t -> (open_tm ts u)\n    end.\n\nEnd SYNTAX.\n\nDefinition Term (G : list typ) (u:typ) := forall (V : typ -> Type), open_tm V G u.\n\nArguments Lit {V}.\nArguments Var {V t}.\nArguments App {V t1 t2}.\nArguments Lam {V t1 t2}.\nArguments Opr {V}.\n\nSection DENOTATION.\n  Fixpoint denote_typ E (t:typ) : Type :=\n    match t with\n    | Base => nat\n    | Arr s t => (denote_typ E s) -> itree E (denote_typ E t)\n    end.\n\n  Fixpoint denotation_tm_typ E (V:typ -> Type) (G : list typ) (u:typ) :=\n    match G with\n    | [] => itree E (V u)\n    | t::ts => (V t) -> denotation_tm_typ E V ts u\n    end.\n\n  Fixpoint denote_closed_term {E} {u:typ} (m : tm (denote_typ E) u) : itree E (denote_typ E u) :=\n    match m with\n    | Lit n => Ret n\n    | Var x => Ret x\n    | App m1 m2 => f <- (denote_closed_term m1) ;;\n                  x <- (denote_closed_term m2) ;;\n                  ans <- f x ;;\n                  ret ans\n    | Lam body => ret (fun x => denote_closed_term (body x))\n    | Opr m1 m2 => x <- (denote_closed_term m1) ;;\n                  y <- (denote_closed_term m2) ;;\n                  Ret (x + y)\n    end.\n\n  Program Fixpoint denote_rec\n          (V:typ -> Type) E\n          (base : forall u (m : tm V u), itree E (V u))\n          (G: list typ) (u:typ) (m : open_tm V G u) : denotation_tm_typ E V G u :=\n    match G with\n    | [] => base u _\n    | t::ts => fun (x : V t) => denote_rec V E base ts u _\n    end.\n  Next Obligation.\n    simpl in m.\n    exact m.\n  Defined.\n  Next Obligation.\n    unfold Term in m.\n    simpl in m.\n    apply m in x.\n    exact x.\n  Defined.\n\n  Program Definition denote E (G : list typ) (u:typ) (m : Term G u)\n    : denotation_tm_typ E (denote_typ E) G u :=\n    denote_rec (denote_typ E) E (@denote_closed_term E) G u _.\n  Next Obligation.\n    unfold Term in m.\n    specialize (m (denote_typ E)).\n    exact m.\n  Defined.\n\nEnd DENOTATION.\n\n\nDefinition id_tm : Term [] (Arr Base Base) :=\n  fun V => Lam (fun x => Var x).\n\nDefinition example : Term [] Base :=\n  fun V => App (id_tm V) (Lit 3).\n\nLemma example_equiv E : (denote E [] Base example) ≈ Ret 3.\nProof.\n  cbn.\n  repeat rewrite bind_ret_l.\n  reflexivity.\nQed.\n\nDefinition twice : Term [] (Arr (Arr Base Base) (Arr Base Base)) :=\n  fun V => Lam (fun f => Lam (fun x => App (Var f) (App (Var f) (Var x)))).\n\nDefinition example2 : Term [] Base :=\n  fun V => App (App (twice V) (id_tm V)) (Lit 3).\n\nLemma big_example_equiv E : (denote E [] Base example2) ≈ Ret 3.\nProof.\n  cbn.\n  repeat rewrite bind_ret_l.\n  reflexivity.\nQed.\n\nDefinition add_2_tm : Term [] (Arr Base Base) :=\n  fun V => Lam (fun x => (Opr (Var x) (Lit 2))).\n\nDefinition example3 : Term [] Base :=\n  fun V => App (App (twice V) (add_2_tm V)) (Lit 3).\n\nLemma big_example2_equiv E : (denote E [] Base example3) ≈ Ret 7.\nProof.\n  cbn.\n  repeat rewrite bind_ret_l.\n  reflexivity.\nQed.\n\n", "meta": {"author": "DeepSpec", "repo": "InteractionTrees", "sha": "8e28e2ee08496c696e03916a22d93c39559a9715", "save_path": "github-repos/coq/DeepSpec-InteractionTrees", "path": "github-repos/coq/DeepSpec-InteractionTrees/InteractionTrees-8e28e2ee08496c696e03916a22d93c39559a9715/examples/STLC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6804247665700233}}
{"text": "Require Import HOASLib.\nRequire Import Composition.\n\nDefinition cnot10 (n : nat) : Box ((S (S n) ⨂ Qubit)%qc) ((S (S n) ⨂ Qubit)%qc) :=\n  box_ (tar,(ct,u)) ⇒ let_ (ct,tar) ← CNOT $ (ct,tar); (tar,(ct,u)).\n\nOpen Scope matrix_scope.\n\nFixpoint nket (n : nat) (st : Matrix 2 1) : Matrix (2^n) 1 :=\n  match n with\n  | 0 => I 1\n  | S n' => st ⊗ (nket n' st)\n  end.\n\nDefinition ghz_ket (n : nat) : Matrix (2^(S n)) 1 :=\n  1/ √2 .* (nket (S n) qubit0) .+ 1/ √2 .* nket (S n) qubit1.\n\nDefinition ghz_state (n : nat) : Density (2^(S n)) :=\n  outer_product (ghz_ket n) (ghz_ket n).\n\nRequire Import Symmetric.\nOpen Scope circ_scope.\n\nFixpoint ghz (n : nat) : Box ((S n) ⨂ One)%qc ((S n) ⨂ Qubit)%qc :=\n  match n with\n  | 0 => box_ (q,u) ⇒ let_ q ← _H $ init0 $ q; let_ u ← (); (q,u)\n  | S n' => (init0 ∥ ghz n') ;; (cnot10 n') \n  end.\n\nLemma typed_cnot10 :\n  forall n : nat, Typed_Box (cnot10 n).\nProof.\n  induction n; simpl; type_check.\nQed.\n\nLemma typed_ghz :\n  forall n : nat, Typed_Box (ghz n).\nProof.\n  induction n; simpl.\n  - type_check.\n  - assert (Typed_Box(cnot10 n)). apply typed_cnot10.\n    type_check.\nQed.\n\nLemma wf_nket :\n  forall (n : nat)(st : (Matrix 2 1)), WF_Matrix st -> WF_Matrix (nket n st).\nProof.\n  intros. induction n.\n  - simpl. apply WF_I1.\n  - simpl. apply WF_kron.\n    + rewrite <- plus_n_O. lia.\n    + lia.\n    + assumption.\n    + assumption.\nQed.\n\nRequire Import Denotation.\nOpen Scope matrix_scope.\n\n(* TODO: Move to Matrix.v *)\nDefinition notc : Matrix 4 4 :=\n  fun x y => match x, y with \n          | 0, 0 => C1\n          | 1, 3 => C1\n          | 2, 2 => C1\n          | 3, 1 => C1\n          | _, _ => C0\n          end.      \n\nLemma wf_notc : WF_Matrix notc.\nProof. show_wf. Qed.\n\nLemma wf_ghz :\n  forall n : nat, WF_Matrix (ghz_state n).\nProof.\n  intro.\n  unfold ghz_state.\n  apply WF_outer_product.\n  all : unfold ghz_ket;\n    apply WF_plus; apply WF_scale; apply wf_nket;\n      try apply WF_qubit0; try apply WF_qubit1.\nQed.\n\n#[export] Hint Resolve wf_ghz wf_nket wf_notc : wf_db.\n\nLemma ctrl_list_notc :\n  forall n : nat, \n    ctrl_list_to_unitary_r (repeat false n ++ [true]) σx = notc ⊗ I (2 ^ n).\nProof.\n  induction n.\n  - simpl.\n    rewrite kron_1_r.\n    solve_matrix.\n  - simpl. rewrite IHn.\n    assert (I (2 ^ n) ⊗ I 2 = I (2 ^ n + (2 ^ n + 0))).\n    { rewrite id_kron. rewrite <- plus_n_O.\n      replace (2^n*2)%nat with (2^n+2^n)%nat. reflexivity. lia. }\n    rewrite <- H.\n    assert ((length (repeat false n ++ [true])) = (S n)).\n    { rewrite app_length. simpl. rewrite repeat_length. lia. }\n    rewrite H0. \n    rewrite Nat.add_1_r. repeat rewrite <- plus_n_O.\n    replace (2^S(S n)+2^S (S n))%nat with (4*(2^n)*2)%nat.\n    replace (2^n+2^n)%nat with ((2^n)*2)%nat.\n    rewrite <- kron_assoc by auto with wf_db.\n    reflexivity.\n    lia.\n    unify_pows_two.\nQed.\n\nLocal Close Scope C_scope.\nLocal Close Scope R_scope.\nLemma cnot10_correct :\n  forall n ρ, WF_Matrix ρ -> \n    ⟦cnot10 n⟧ ρ = (notc ⊗ (I (2^n))) × ρ × (notc ⊗ (I (2^n)))†.\nProof.\n  intros. \n  induction n.\n  - matrix_denote.\n    simpl in *.\n    Msimpl.\n    solve_matrix.\n  - matrix_denote. \n    rewrite add_fresh_split.\n    simpl.\n    matrix_denote.\n    rewrite add_fresh_split. simpl. \n    repeat rewrite subst_var_no_gaps.\n    simpl.\n    unify_pows_two.\n    rewrite rev_repeat.\n    rewrite size_ntensor. simpl.\n    rewrite Nat.mul_1_r. \n    rewrite subst_pat_fresh.\n    rewrite swap_fresh_seq.\n    simpl.\n    rewrite size_ntensor. simpl.\n    rewrite Nat.mul_1_r.\n    repeat rewrite -> Nat.add_1_r.\n    assert(E : forall i j, i > j -> (map (fun z : nat * nat => if match snd z with\n                                                | 0 => true\n                                                | S _ => false\n                                      end then (fst z, j)%core else z) (combine (seq i n) (seq i n))) =\n               (combine (seq i n) (seq i n))).\n    clear. induction n. simpl. reflexivity. simpl.\n    intros. simpl. rewrite IHn by lia. destruct i; try lia. reflexivity.\n    rewrite E by lia. clear E.\n    assert(E : forall i, i > 1 -> (map (fun z : nat * nat => if match snd z with\n                                                | 1 => true\n                                                | _ => false\n                                      end then (fst z, 1)%core else z) (combine (seq i n) (seq i n))) =\n               (combine (seq i n) (seq i n))).\n    clear. induction n. simpl. reflexivity. simpl.\n    intros. simpl. rewrite IHn by lia. destruct i as [|[|]]; try lia. reflexivity.\n    rewrite E by lia. clear E.\n    assert(E : forall i, i > 2 -> (map (fun z : nat * nat => if match snd z with\n                                                | 2 => true\n                                                | _ => false\n                                      end then (fst z, 2)%core else z) (combine (seq i n) (seq i n))) =\n               (combine (seq i n) (seq i n))).\n    clear. induction n. simpl. reflexivity. simpl.\n    intros. simpl. rewrite IHn by lia. destruct i as [|[|[|]]]; try lia. reflexivity.\n    rewrite E by lia. clear E.\n\n    assert ((2 ^ S (S (S n)))%nat=(4 * 2 ^ S n)%nat). unify_pows_two.\n    assert ([false] = (repeat false 1)) by auto.\n    \n    repeat rewrite Mmult_1_r. repeat rewrite Mmult_1_l. Msimpl.\n    rewrite swap_list_aux_id.\n    replace (n+2) with (S (S n)) by lia.\n    rewrite Nat.sub_diag. rewrite id_kron. rewrite mult_1_r. rewrite Mmult_1_l.\n    rewrite id_adjoint_eq. rewrite Mmult_1_r.\n\n    rewrite H1. rewrite repeat_combine.\n    replace (n+1) with (S n) by lia.\n    replace (2^S (S (S n))) with (4*2^S n) by unify_pows_two. rewrite ctrl_list_notc. reflexivity.\n    \n    rewrite H0. apply WF_mult. apply WF_mult. \n    rewrite H1. rewrite repeat_combine. \n    replace (n+1) with (S n) by lia. rewrite ctrl_list_notc. apply WF_kron.\n    auto.  auto. show_wf. apply WF_I.\n    assumption.\n    \n    rewrite H1. rewrite repeat_combine. \n    replace (n+1) with (S n) by lia. rewrite ctrl_list_notc.\n    apply WF_adjoint. apply WF_kron. auto. auto.\n    show_wf. apply WF_I.\n    \n    rewrite H0. apply WF_mult. apply WF_mult.\n    rewrite H1. rewrite repeat_combine. \n    replace (n+1) with (S n) by lia. rewrite ctrl_list_notc.\n    apply WF_kron.\n    auto. auto. show_wf. apply WF_I.\n    assumption.\n    \n    rewrite H1. rewrite repeat_combine. \n    replace (n+1) with (S n) by lia.\n    rewrite ctrl_list_notc.\n    apply WF_adjoint.\n    apply WF_kron.\n    auto. auto.\n    show_wf.\n    apply WF_I.\n\n    all : try (rewrite swap_list_aux_id; apply WF_I).\n\n    repeat constructor.\n    rewrite fresh_state_ntensor.\n    rewrite app_length. simpl.\n    repeat apply lt_n_S. apply Nat.lt_0_succ.\n    \n    apply add_fresh_state_no_gaps.\n    repeat constructor.\n    rewrite fresh_state_ntensor.\n    rewrite app_length. simpl.\n    repeat apply lt_n_S. apply Nat.lt_0_succ.\n\n    apply add_fresh_state_no_gaps.\n    repeat constructor.\n\n    rewrite fresh_state_ntensor.\n    rewrite app_length.\n    simpl. apply Nat.lt_0_succ.\n\n    apply add_fresh_state_no_gaps.\n    repeat constructor.\nQed.\n\nLemma Mmult_outer_product :\n  forall (n : nat)  (k : (Matrix n 1)) (M : Matrix n n),\n    M × (outer_product k k) × M† = outer_product (M × k) (M × k).\nProof.\n  intros. \n  unfold outer_product.\n  rewrite Mmult_adjoint.\n  repeat rewrite Mmult_assoc. reflexivity.\nQed.\n\nLemma kron_product :\n  forall (m n : nat) (a : (Matrix m 1))(b : (Matrix n 1)),\n    (outer_product a a) ⊗ (outer_product b b) = outer_product (a ⊗ b) (a ⊗ b).\nProof.\n  intros. unfold outer_product.\n  rewrite <- kron_mixed_product.\n  rewrite <- kron_adjoint. reflexivity.\nQed.\n\nLemma outer_eq :\n  forall (n : nat)(a b : Matrix n 1),\n    a = b -> outer_product a a = outer_product b b.\nProof.\n  intros. rewrite H. reflexivity.\nQed.\n  \nLemma Mplus_eq :\n  forall (m n: nat)(a1 b1 a2 b2 : Matrix m n),\n    a1 = a2 -> b1 = b2 -> a1 .+ b1 = a2 .+ b2.\nProof.\n  intros. rewrite H. rewrite H0. reflexivity.\nQed.\n\nLemma Mscale_eq :\n  forall (m n: nat)(c : C) (u v : (Matrix m n)),\n    u = v -> c .* u = c .* v.\nProof.\n  intros. rewrite H. reflexivity.\nQed.\n\nLemma kron_eq :\n  forall (m n: nat)(u1 u2 : (Matrix m 1))(v1 v2 : (Matrix n 1)),\n    u1=u2 -> v1=v2 -> u1⊗v1=u2⊗v2.\nProof. \n  intros. rewrite H. rewrite H0. reflexivity.\nQed.\n\nLocal Open Scope C_scope.\nLocal Open Scope R_scope.\nTheorem ghz_correct :\n  forall n : nat, ⟦ghz n⟧ (I 1) = ghz_state n.\nProof.\n  induction n as [| n' IHn'].\n  - matrix_denote. Msimpl.\n    unfold ghz_state, outer_product, ghz_ket.\n    solve_matrix.\n  - simpl.\n    rewrite inSeq_correct.\n    + assert ((I 1) = (I (2^⟦One⟧)) ⊗ (I (2^⟦((S n') ⨂ One)%qc⟧))).\n      { Msimpl. rewrite size_ntensor. rewrite Nat.mul_0_r. reflexivity. }\n      unfold compose_super.\n      assert (⟦init0⟧ (I 1) = ∣0⟩⟨0∣).\n      { simpl. Msimpl. solve_matrix. }\n      assert (denote_box true (init0 ∥ ghz n') (I 1) = (denote_box true init0 (I (2^⟦One⟧))) ⊗ (denote_box true (ghz n') (I (2^⟦((S n') ⨂ One)%qc⟧)))).\n      {\n        rewrite -> H.\n        apply inPar_correct.\n        type_check.\n        apply typed_ghz.\n        simpl. apply WF_I1. \n        replace (2^⟦(S n' ⨂ One)%qc⟧)%nat with 1%nat by (simpl; rewrite -> size_ntensor; rewrite Nat.mul_0_r; auto).\n        apply WF_I1.\n      }\n      simpl in H1. rewrite -> H1.\n      assert (denote_box true init0 (I 1) = ∣0⟩⟨0∣).\n      { matrix_denote. solve_matrix. }\n      rewrite H2. simpl in IHn'.\n      repeat rewrite -> size_ntensor. rewrite Nat.mul_0_r. simpl. rewrite IHn'.\n      assert (⟦cnot10 n'⟧ (∣0⟩⟨0∣ ⊗ ghz_state n') = (notc ⊗ (I (2^n'))) × (∣0⟩⟨0∣ ⊗ ghz_state n') × (notc ⊗ (I (2^n')))† ).\n      { apply cnot10_correct. apply WF_kron.\n        simpl. repeat rewrite <- plus_n_O. repeat rewrite plus_assoc. reflexivity.\n        simpl. repeat rewrite <- plus_n_O. rewrite plus_assoc. reflexivity.\n        apply WF_braqubit0. apply wf_ghz.\n         }\n      simpl in H3. simpl. \n      assert ((size_wtype (n' ⨂ Qubit)%qc)=n').\n      { rewrite size_ntensor. simpl.  lia. }\n      simpl in H3. rewrite Nat.mul_1_r. simpl. rewrite -> H3.\n      unfold ghz_state, ghz_ket.\n      replace (∣0⟩⟨0∣) with (outer_product ∣0⟩ ∣0⟩) by (simpl; reflexivity).\n      rewrite -> kron_product.\n      replace ((2 * 2 ^ S n'))%nat with (4 * 2^n')%nat in * by (simpl; lia).\n      rewrite -> Mmult_outer_product.\n      rewrite kron_plus_distr_l.\n      simpl in *.\n      replace (2 ^ n' + (2 ^ n' + (2 ^ n' + (2 ^ n' + 0))))%nat with\n          (2 ^ n' + (2 ^ n' + 0) + (2 ^ n' + (2 ^ n' + 0) + 0))%nat by (repeat rewrite <- plus_n_O; repeat rewrite plus_assoc; reflexivity).\n      rewrite Mmult_plus_distr_l.\n      apply outer_eq.\n      apply Mplus_eq.\n      *\n        remember (nket n' ∣0⟩) as nk0.\n        assert ( (∣0⟩ ⊗ (1%R / √ 2 .* (∣0⟩ ⊗ nk0))) = 1%R / √ 2 .* (∣0⟩ ⊗ ((∣0⟩ ⊗ nk0)))).\n        { rewrite -> Mscale_kron_dist_r. reflexivity. }     \n        simpl in H5. rewrite -> H5.\n        (* simpl. *)\n        assert ((∣0⟩ ⊗ (∣0⟩ ⊗ nk0)) = (∣0⟩ ⊗ ∣0⟩) ⊗ nk0).\n        { rewrite -> kron_assoc; subst; auto with wf_db. }\n        simpl in H6. rewrite -> H6.\n        rewrite -> Mscale_mult_dist_r.\n        apply Mscale_eq.\n        assert (notc ⊗ I (2 ^ n') × (∣0⟩ ⊗ ∣0⟩ ⊗ nk0) = (notc × (∣0⟩⊗∣0⟩)) ⊗ ((I (2^n')) × nk0)).\n        { rewrite -> kron_mixed_product. reflexivity. }\n        simpl in H7. repeat rewrite <- plus_n_O in H7.\n        repeat rewrite <- plus_n_O.\n        replace (2 ^ n' + 2 ^ n' + (2 ^ n' + 2 ^ n'))%nat with (2 ^ n' + (2 ^ n' + (2 ^ n' + 2 ^ n')))%nat by (repeat rewrite plus_assoc; reflexivity).\n        rewrite -> H7.\n        apply kron_eq.\n        solve_matrix. \n        rewrite Mmult_1_l. reflexivity.\n        rewrite Heqnk0. apply wf_nket.\n        apply WF_qubit0.\n      *\n        remember (nket n' ∣1⟩) as nk1.\n        assert ( (∣0⟩ ⊗ (1%R / √ 2 .* (∣1⟩ ⊗ nk1))) = 1%R / √ 2 .* (∣0⟩ ⊗ ((∣1⟩ ⊗ nk1)))).\n        { rewrite -> Mscale_kron_dist_r. reflexivity. }     \n        simpl in H5. rewrite -> H5.\n        assert ((∣0⟩ ⊗ (∣1⟩ ⊗ nk1)) = (∣0⟩ ⊗ ∣1⟩) ⊗ nk1).\n        { rewrite -> kron_assoc; subst; auto with wf_db. }\n        simpl in H6. rewrite -> H6.\n        rewrite Mscale_mult_dist_r.\n        apply Mscale_eq.\n        assert (notc ⊗ I (2 ^ n') × (∣0⟩ ⊗ ∣1⟩ ⊗ nk1) = (notc × (∣0⟩⊗∣1⟩)) ⊗ ((I (2^n')) × nk1)).\n        { rewrite -> kron_mixed_product. reflexivity. }\n        simpl in H7.\n        repeat rewrite <- plus_n_O in H7.\n        repeat rewrite <- plus_n_O. \n        replace (2 ^ n' + 2 ^ n' + (2 ^ n' + 2 ^ n'))%nat with (2 ^ n' + (2 ^ n' + (2 ^ n' + 2 ^ n')))%nat by (repeat rewrite plus_assoc; reflexivity).\n        rewrite -> H7. \n        assert ((∣1⟩ ⊗ (∣1⟩ ⊗ nk1)) = (∣1⟩ ⊗ ∣1⟩) ⊗ nk1).\n        { rewrite -> kron_assoc; subst; auto with wf_db. }\n        replace (1 * 1)%nat with 1%nat in H8 by lia.\n        replace (2^n'+2^n')%nat with (2*2^n')%nat by lia.\n        rewrite -> H8.\n        apply kron_eq.\n        solve_matrix. \n        rewrite Mmult_1_l. reflexivity.\n        rewrite Heqnk1. apply wf_nket. \n        apply WF_qubit1.\n    + apply typed_cnot10.\n    + apply inPar_WT. type_check. apply typed_ghz.\nQed.\n", "meta": {"author": "inQWIRE", "repo": "QWIRE", "sha": "1b252a1b15e8c54262609f713a21b4016adb3b78", "save_path": "github-repos/coq/inQWIRE-QWIRE", "path": "github-repos/coq/inQWIRE-QWIRE/QWIRE-1b252a1b15e8c54262609f713a21b4016adb3b78/GHZ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6804247632656688}}
{"text": "Require Import Coq.ZArith.ZArith Coq.micromega.Lia.\n\nLocal Open Scope Z_scope.\nModule Z2Nat.\n  Definition inj_nonpos n : n <= 0 -> Z.to_nat n = 0%nat.\n  Proof.\n    destruct n; try reflexivity; lia.\n  Qed.\nEnd Z2Nat.\n\nModule Z.\n  Lemma pos_pow_nat_pos : forall x n,\n    Z.pos x ^ Z.of_nat n > 0.\n  Proof. intros; apply Z.lt_gt, Z.pow_pos_nonneg; lia. Qed.\n\n  Lemma pow_Z2N_Zpow : forall a n, 0 <= a ->\n                                   ((Z.to_nat a) ^ n = Z.to_nat (a ^ Z.of_nat n)%Z)%nat.\n  Proof.\n    intros a n H; induction n as [|n IHn]; try reflexivity.\n    rewrite Nat2Z.inj_succ.\n    rewrite Nat.pow_succ_r by apply le_0_n.\n    rewrite Z.pow_succ_r by apply Zle_0_nat.\n    rewrite IHn.\n    rewrite Z2Nat.inj_mul; auto using Z.pow_nonneg.\n  Qed.\n\n  Lemma pow_Zpow : forall a n : nat, Z.of_nat (a ^ n) = Z.of_nat a ^ Z.of_nat n.\n  Proof with auto using Zle_0_nat, Z.pow_nonneg.\n    intros; apply Z2Nat.inj...\n    rewrite <- pow_Z2N_Zpow, !Nat2Z.id...\n  Qed.\n  Hint Rewrite pow_Zpow : push_Zof_nat.\n  Hint Rewrite <- pow_Zpow : pull_Zof_nat.\n\n  Lemma Zpow_sub_1_nat_pow a v\n    : (Z.pos a^Z.of_nat v - 1 = Z.of_nat (Z.to_nat (Z.pos a)^v - 1))%Z.\n  Proof.\n    rewrite <- (Z2Nat.id (Z.pos a)) at 1 by lia.\n    change 2%Z with (Z.of_nat 2); change 1%Z with (Z.of_nat 1);\n      autorewrite with pull_Zof_nat.\n    rewrite Nat2Z.inj_sub\n      by (change 1%nat with (Z.to_nat (Z.pos a)^0)%nat; apply Nat.pow_le_mono_r; simpl; lia).\n    reflexivity.\n  Qed.\n  Hint Rewrite Zpow_sub_1_nat_pow : pull_Zof_nat.\n  Hint Rewrite <- Zpow_sub_1_nat_pow : push_Zof_nat.\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/Z2Nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6804247625498842}}
{"text": "Require Import set.\nRequire Import equiv.\nRequire Import equiv_symmetric.\nRequire Import equiv_transitive.\n\n(* obvious consequence of transitivity and symmetry *)\nProposition equiv_compatible: forall (a a' b b':set),\n  equiv a a' -> equiv b b' -> equiv a b -> equiv a' b'.\nProof.\n  intros a a' b b' Haa' Hbb' Hab.\n  apply equiv_transitive with (b:= b).\n  apply equiv_transitive with (b:= a).\n  apply equiv_symmetric. exact Haa'. exact Hab. exact Hbb'.\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/set2/equiv_compatible.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.7799929053683039, "lm_q1q2_score": 0.6804247580885282}}
{"text": "Require Import Basics.\nRequire Import Types.\nRequire Import HSet.\nRequire Import Algebra.Group.\n\nLocal Open Scope mc_mult_scope.\nGeneralizable Variables G H A B C N f g.\n\n(** * Subgroups *)\n\n(** The property of being a subgroup *)\nClass IsSubgroup (G H : Group) := {\n  issubgroup_incl :> GroupHomomorphism G H;\n  isinj_issubgroup_incl :> IsInjective issubgroup_incl;\n}.\n\n(* Subgroup inclusion is an embedding. *)\nGlobal Instance isembedding_issubgroup_incl `{!IsSubgroup G H}\n  : IsEmbedding (@issubgroup_incl G H _).\nProof.\n  apply isembedding_isinj_hset.\n  apply isinj_issubgroup_incl.\nDefined.\n\nDefinition issig_issubgroup G H : _ <~> IsSubgroup G H\n  := ltac:(issig).\n\n(** A subgroup of a group H is a group G which is a subgroup of H. *) \nClass Subgroup (H : Group) := {\n  subgroup_group :> Group;\n  subgroup_issubgroup :> IsSubgroup subgroup_group H;\n}.\n\nCoercion subgroup_group : Subgroup >-> Group.\n\nSection Cosets.\n\n  (** Left and right cosets give equivalence relations. *)\n\n  Context {G : Group} `{!IsSubgroup H G}.\n\n  (* The relation of being in a left coset represented by an element. *)\n  Definition in_cosetL : Relation G.\n  Proof.\n    intros x y.\n    refine (hfiber issubgroup_incl _).\n    exact (-x * y).\n  Defined.\n\n  (* The relation of being in a right coset represented by an element. *)\n  Definition in_cosetR : Relation G.\n  Proof.\n    intros x y.\n    refine (hfiber issubgroup_incl _).\n    exact (x * -y).\n  Defined.\n\n  (* These are props *)\n\n  Global Instance ishprop_in_cosetL : is_mere_relation G in_cosetL.\n  Proof.\n    exact _.\n  Defined.\n\n  Global Instance ishprop_in_cosetR : is_mere_relation G in_cosetR.\n  Proof.\n    exact _.\n  Defined.\n\n  (* Infact they are both equivalence relations. *)\n\n  Global Instance reflexive_in_cosetL : Reflexive in_cosetL.\n  Proof.\n    intro x; hnf.\n    exists mon_unit.\n    refine (_ @ _).\n    2: apply symmetry, left_inverse.\n    apply grp_homo_unit.\n  Defined.\n\n  Global Instance reflexive_in_cosetR : Reflexive in_cosetR.\n  Proof.\n    intro x; hnf.\n    exists mon_unit.\n    refine (_ @ _).\n    2: apply symmetry, right_inverse.\n    apply grp_homo_unit.\n  Defined.\n\n  Global Instance symmetric_in_cosetL : Symmetric in_cosetL.\n  Proof.\n    intros x y [h p]; hnf.\n    exists (-h).\n    refine (_ @ _).\n    1: apply grp_homo_inv.\n    apply moveR_equiv_M.\n    refine (p @ _).\n    symmetry.\n    refine (negate_sg_op _ _ @ _).\n    refine (ap (-x *.) _).\n    apply negate_involutive.\n  Defined.\n\n  Global Instance symmetric_in_cosetR : Symmetric in_cosetR.\n  Proof.\n    intros x y [h p]; hnf.\n    exists (-h).\n    refine (_ @ _).\n    1: apply grp_homo_inv.\n    apply moveR_equiv_M.\n    refine (p @ _).\n    symmetry.\n    refine (negate_sg_op _ _ @ _).\n    refine (ap (fun x => x *  -y) _).\n    apply negate_involutive.\n  Defined.\n\n  Global Instance transitive_in_cosetL : Transitive in_cosetL.\n  Proof.\n    intros x y z [h p] [h' q].\n    exists (h * h').\n    refine (grp_homo_op _ _ _ @ _).\n    destruct p^, q^.\n    rewrite <- simple_associativity.\n    apply ap.\n    rewrite simple_associativity.\n    refine (ap (fun x => x *  -z) _ @ _).\n    1: apply right_inverse.\n    apply left_identity.\n  Defined.\n\n  Global Instance transitive_in_cosetR : Transitive in_cosetR.\n  Proof.\n    intros x y z [h p] [h' q].\n    exists (h * h').\n    refine (grp_homo_op _ _ _ @ _).\n    destruct p^, q^.\n    rewrite <- simple_associativity.\n    apply ap.\n    rewrite simple_associativity.\n    refine (ap (fun x => x *  -z) _ @ _).\n    1: apply left_inverse.\n    apply left_identity.\n  Defined.\n\nEnd Cosets.\n\n(** Identities related to the left and right cosets. *)\n\nDefinition in_cosetL_unit {G : Group} `{!IsSubgroup N G}\n  : forall x y, in_cosetL (-x * y) mon_unit <~> in_cosetL x y.\nProof.\n  intros x y.\n  unfold in_cosetL.\n  rewrite negate_sg_op.\n  rewrite negate_involutive.\n  rewrite (right_identity (-y * x)).\n  change (in_cosetL y x <~> in_cosetL x y).\n  serapply equiv_iff_hprop;\n  by intro; symmetry.\nDefined.\n\nDefinition in_cosetR_unit {G : Group} `{!IsSubgroup N G}\n  : forall x y, in_cosetR (x * -y) mon_unit <~> in_cosetR x y.\nProof.\n  intros x y.\n  unfold in_cosetR.\n  rewrite negate_mon_unit.\n  rewrite (right_identity (x * -y)).\n  reflexivity.\nDefined.\n\n(** Symmetry is an equivalence. *)\nDefinition equiv_in_cosetL_symm {G : Group} `{!IsSubgroup N G}\n  : forall x y, in_cosetL x y <~> in_cosetL y x.\nProof.\n  intros x y.\n  serapply equiv_iff_hprop.\n  all: by intro.\nDefined.\n\nDefinition equiv_in_cosetR_symm {G : Group} `{!IsSubgroup N G}\n  : forall x y, in_cosetR x y <~> in_cosetR y x.\nProof.\n  intros x y.\n  serapply equiv_iff_hprop.\n  all: by intro.\nDefined.\n\n(* A subgroup is normal if being in a left coset is equivalent to being in a right coset represented by the same element. *)\nClass IsNormalSubgroup {G : Group} (N : Subgroup G) := {\n  isnormal {x y} : in_cosetL x y <~> in_cosetR x y;\n}.\n\n(* Inverses are then respected *)\nDefinition in_cosetL_inv {G : Group} `{!IsNormalSubgroup N}\n  : forall x y, in_cosetL (-x) (-y) <~> in_cosetL x y.\nProof.\n  intros x y.\n  refine (_ oE (in_cosetL_unit _ _)^-1).\n  refine (_ oE isnormal).\n  refine (_ oE in_cosetR_unit _ _).\n  refine (_ oE isnormal^-1).\n  by rewrite negate_involutive.\nDefined.\n\nDefinition in_cosetR_inv {G : Group} `{!IsNormalSubgroup N}\n  : forall x y, in_cosetR (-x) (-y) <~> in_cosetR x y.\nProof.\n  intros x y.\n  refine (_ oE (in_cosetR_unit _ _)^-1).\n  refine (_ oE isnormal^-1).\n  refine (_ oE in_cosetL_unit _ _).\n  refine (_ oE isnormal).\n  by rewrite negate_involutive.\nDefined.\n\n(* There is always another element of the normal subgroup allowing us to commute with an element of the group. *)\nDefinition normal_subgroup_swap {G : Group}\n  `{!IsNormalSubgroup N} (x : G) (h : N)\n  : exists h' : N, x * issubgroup_incl h = issubgroup_incl h' * x.\nProof.\n  assert (X : in_cosetL x (x * issubgroup_incl h)).\n  { exists h.\n    rewrite simple_associativity.\n    rewrite left_inverse.\n    symmetry.\n    apply left_identity. }\n  apply isnormal in X.\n  destruct X as [a p].\n  rewrite negate_sg_op in p.\n  rewrite simple_associativity in p.\n  eexists (-a).\n  symmetry.\n  rewrite grp_homo_inv.\n  apply (moveR_equiv_M (f := (- _ *.))).\n  cbn; rewrite negate_involutive.\n  rewrite simple_associativity.\n  apply (moveL_equiv_M (f := (fun x => x * _))).\n  apply (moveL_equiv_M (f := (fun x => x * _))).\n  symmetry.\n  assumption.\nDefined.\n\n(* This let's us prove that left and right coset relations are congruences. *)\nDefinition in_cosetL_cong {G : Group} `{!IsNormalSubgroup N}\n  : forall x x' y y', in_cosetL x y -> in_cosetL x' y' -> in_cosetL (x * x') (y * y').\nProof.\n  intros x x' y y' [a p] [b q].\n  eexists ?[c].\n  rewrite negate_sg_op.\n  rewrite <- simple_associativity.\n  rewrite (simple_associativity (-x) y).\n  rewrite <- p.\n  rewrite simple_associativity.\n  rewrite (normal_subgroup_swap _ a).2.\n  rewrite <- simple_associativity.\n  rewrite <- q.\n  apply grp_homo_op.\nDefined.\n\nDefinition in_cosetR_cong {G : Group} `{!IsNormalSubgroup N}\n  : forall x x' y y', in_cosetR x y -> in_cosetR x' y' -> in_cosetR (x * x') (y * y').\nProof.\n  intros x x' y y' [a p] [b q].\n  eexists ?[c].\n  rewrite negate_sg_op.\n  rewrite <- simple_associativity.\n  rewrite (simple_associativity x' (-y')).\n  rewrite <- q.\n  rewrite simple_associativity.\n  rewrite (normal_subgroup_swap _ b).2.\n  rewrite <- simple_associativity.\n  rewrite <- p.\n  apply grp_homo_op.\nDefined.\n\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/theories/Algebra/Subgroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6804247536271717}}
{"text": "\nFrom Undecidability.Shared.Libs.PSL Require Import FinTypes.\n\nFixpoint position {X : eqType} (x : X) (l : list X) : option (Fin.t (length l)).\nProof.\n  induction l.\n  - exact None.\n  - cbn. decide (a = x).\n    + exact (Some Fin.F1).\n    + destruct (position _ x l) as [res | ].\n      * exact (Some (Fin.FS res)). \n      * exact None.\nDefined.\n\nLemma position_in {X : eqType} (x : X) (l : list X) (H : x el l) : \n  { i | position x l = Some i}.\nProof.  \n    induction l; cbn in *.\n    - inv H.\n    - decide (a = x).\n        + eauto.\n        + destruct IHl as [i IH]. firstorder. rewrite IH. eauto.\nDefined. \n\nDefinition posIn {X : eqType} (x : X) (l : list X) (H : x el l) : Fin.t (length l).\nProof.\n    eapply position_in in H. destruct (position x l) as [i | ]. exact i.\n    abstract (exfalso; firstorder congruence).\nDefined.\n\nFixpoint getat {X : Type} (l : list X) (i : Fin.t (length l)) : X.\nProof.\n    destruct l.\n    - inv i.\n    - cbn in i. eapply (Fin.caseS' i (fun _ => X)).\n      + exact x.\n      + eapply getat.\nDefined.\n\nArguments getat {_} _ _.\n\nLemma getatIn {X : Type} (l : list X) (i : Fin.t (length l)) : \n    getat l i el l.\nProof.\n    induction l.\n    - inv i.\n    - cbn in *. eapply (Fin.caseS' i); cbn. eauto. eauto.\nQed.\n\nLemma getat_position {X : eqType} (x : X) l (H : x el l) :\ngetat l (proj1_sig (position_in H)) = x.\nProof.\ndestruct (position_in H) as [i H1]. cbn.\ninduction l; cbn in *. \n+ inv H1.\n+ decide (a = x).\n  * inv H1. cbn. reflexivity.\n  * destruct (position x l) eqn:E; inv H1.\n    cbn. eapply IHl. firstorder. reflexivity.\nQed.\n\nLemma finite_n (F : finType) :\n    { n & {f : F -> Fin.t n & { g : Fin.t n -> F | (forall i, f (g i) = i) /\\ forall x, g (f x) = x }}}.\nProof.\n    destruct F as (X & [l H]). cbn in *. \n    exists (length l).\n    assert (Hin : forall x, x el l). { intros x. eapply count_in_equiv. rewrite H. lia. }\n    exists (fun x => proj1_sig (position_in (Hin x))). exists (@getat _ l). split.\n    - intros i. destruct position_in. cbn.\n      specialize (H (getat l i)). clear - H e. \n      induction l.\n      + inv x.\n      + cbn in *. revert H e.\n        eapply (Fin.caseS' i). cbn.\n        * decide (a = a); congruence.\n        * cbn. intros. decide (getat l p = a).\n         -- decide (a = getat l p); try congruence. subst. inv e. inv H.\n            eapply countZero in H1 as []. eapply getatIn.\n         -- decide (a = getat l p); try congruence.\n            destruct position eqn:E; inv e. eapply IHl in E; congruence.\n    - intros. eapply getat_position.\nQed.\n    ", "meta": {"author": "uds-psl", "repo": "coq-synthetic-computability", "sha": "dc6eaeef99c76f4ff2903b8c07e2928622ee36ba", "save_path": "github-repos/coq/uds-psl-coq-synthetic-computability", "path": "github-repos/coq/uds-psl-coq-synthetic-computability/coq-synthetic-computability-dc6eaeef99c76f4ff2903b8c07e2928622ee36ba/Shared/FinTypeEquiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6803085911765551}}
{"text": "Require Import Utf8.\n\nSection Noniterability_of_induction.\n\nDefinition till (n : nat) (P : nat → Prop) := ∀ k, k<n → P k.\nDefinition prime (P : nat → Prop) (n : nat) := till n P → P n.\nDefinition univ (P: nat → Prop) := ∀ n, P n.\nNotation \"P '\" := (prime P) (at level 1).\n\nPrint \"<\". Print \"≤\".\n(* We see that ≤ is in fact basic relation in Coq's system\n   (least reflexive S-closed on the right)\n   and then < is defined from ≤ adding another S on the left.\n\n   For this induction we need the von Neumann's order (∈)\n   so we have to prove the equivalence of that with Coq's\n   definitions: first for ≤, and then for <. *)\n\nTheorem less_equal: ∀ m n, m ≤ S n → m ≤ n ∨ m = S n.\nProof.\n  intros m n hyp. inversion hyp as [eql|n' less' n'j].\n  - right. reflexivity.\n  - left. assumption.\nQed.\n\nTheorem less_succ: ∀ m n, m < S n → m < n ∨ m = n.\nProof.\n  unfold \"<\". intros m n hyp. apply less_equal in hyp.\n  destruct hyp as [first|second].\n  - left. assumption.\n  - right. injection second as [=eql]. assumption.\nQed.\n\nTheorem strong_induction: ∀ P, univ P ' → univ P.\nProof.\n  unfold univ. intros P hyp n. apply hyp.\n  induction n as [|n IH].\n  - unfold till. intros k contra. inversion contra.\n  - unfold till. intros k less.\n    apply less_succ in less as [less|eql].\n    * apply IH. assumption.\n    * subst. apply hyp. assumption.\nQed.\n\nTheorem Šika1: ∀ P n, P ' ' n ↔ P ' n.\nProof.\n  intros P n. split.\n  - intros hyp till_n. apply hyp.\n    + intros k less till_k. apply till_n. assumption.\n    + assumption.\n  - intros hyp till_n' till_n. apply hyp. assumption.\nQed.\n\nEnd Noniterability_of_induction.\n\n\nSection Geometry_Converses.\n\nVariable (S : Set) (F G : S → Prop).\n\nDefinition exist (F : S → Prop) := ∃ x, F x.\nDefinition unique (G : S → Prop) := ∀ x y, G x ∧ G y → x = y.\n\nTheorem Šika2: (∀ x, F x → G x) ∧ exist F ∧ unique G →\n                   ∀ x, F x ↔ G x.\n(* If every F is a G, and there are ≥1 Fs, and there are ≤1 Gs,\n   then every G is an F too. \n   In fact we can generalize 1→n, although it becomes even more\n   convoluted to express that using just logic:\n   if F ⇒ G and #F ≥ n ≥ #G, then F ⇔ G.\n   But ONLY FOR FINITE n: if F ⇒ G and #F ≥ ℵ₀ ≥ #G\n   then not necessarily F ⇔ G.\n   (Hilbert's hotel: for example, F x :⇔ x > 2, G x :⇔ x > 1) *)\nProof.\n  intros (onedirection & least1F & most1G) x. split.\n  - apply onedirection.\n  - intros Gx. destruct least1F as (x0 & Fx0).\n    replace x with x0.\n    + assumption.\n    + apply most1G. split.\n      * apply onedirection. assumption.\n      * assumption.\nQed.\n(* The whole mystery comes solely from the clumsiness of\n   first order logic to express counting quantifiers. *)\n\nEnd Geometry_Converses.\n\n\n(* Require Import Classical_Prop. *)\n\nSection Equality_Characterization.\n\nVariable X : Set.\n\nDefinition reflexive (J : X → X → Prop) := ∀ x, J x x.\n(* Leibniz property can be expressed relationally or functionally\n   - but they aren't equivalent, and don't give the same results!\n   (maybe codomain of f could be differently set up, or maybe J\n   itself could be expressed functionally, but I don't know how. *)\nDefinition fLeibniz (J : X → X → Prop) :=\n  ∀ (x y : X) (f : X → X), J x y → J (f x) (f y).\nDefinition rLeibniz (J : X → X → Prop) :=\n  ∀ (x y : X) (P : X → Prop), J x y → P x → P y.\nDefinition RL (J : X → X → Prop) := reflexive J ∧ rLeibniz J.\nDefinition trueEquality (x y : X) := x = y.\n\nExample rlj: RL trueEquality.\nProof. split.\n  - intros x. reflexivity.\n  - intros x y f xy. unfold trueEquality in xy.\n    subst. intros hyp. assumption.\nQed.\n\nExample flj: fLeibniz trueEquality.\nProof.\n  intros x y f xy. unfold trueEquality in xy. subst. reflexivity. Qed.\n\nProposition characterization: ∀ J, (RL J ↔ ∀ x y, J x y ↔ x = y).\n                    (* only extensionally: we can't say J = (=)! *)\nProof.\n  intros J. split; intros hyp.\n  - destruct hyp as (rj & lj). intros x y. split; intros xy.\n    + apply lj with x.\n      * assumption.\n      * reflexivity.\n    + subst. apply rj.\n  - split.\n    + intros x. apply hyp. reflexivity.\n    + intros x y P Jxy Px. apply hyp in Jxy. subst. assumption.\nQed.\n(* But the characterization doesn't hold for functional Leibniz\n   property. If X has at least 2 elements and J is universal,\n   it's obviously reflexive and fLeibniz, but it's not equality. *)\n\nEnd Equality_Characterization.\n\nSection Equivalence_Calculus.\n\n(* Šika proposes using ≡ as a base for defining propositional\n   logic, later adding ∨ to get a positive fragment and\n   yet later adding ¬ to get the whole thing. Axioms:\n   \n   Associativity of ≡ (so parentheses aren't needed:)\n   Commutativity of ≡: x≡y≡y≡x\n   Associativity of ∨\n   Commutativity of ∨\n   Idempotence of ∨\n   Distributivity of ∨ over ≡\n   \n   Half-distributivity of ¬ over ≡: ¬(x≡y)≡x≡¬y\n    => DNE ¬¬x≡x\n   Tertium non datur: x∨¬x\n*)\n\nVariable (B: Set) (ekviv: B → B → B).\nNotation \"x ≡ y\" := (ekviv x y) (left associativity, at level 90).\nDefinition true x := x = (x ≡ x). Coercion true : B >-> Sortclass.\n(* That means we can assert elements of B as propositions,\n   and proving x actually means proving \"true x\" (x = (x ≡ x)). *)\n\nAxiom eA: ∀ x y z, (x ≡ y ≡ z) ≡ (x ≡ (y ≡ z)).\nAxiom eS: ∀ x y, x ≡ y ≡ y ≡ x.\n\nLemma ejj: ∀ x y, x ≡ y ↔ x = y.\nProof.\n  apply characterization. split.\n  - intros x. unfold true. (* now what? *) admit.\n  - intros x y P xy px. (* even more hopeless *) admit.\nAdmitted.\n\n(* One minor problem with defining t as y≡y: we must first have y.\n   Bigger problem: To be able to rewrite using ≡, we must first\n   have fLeibniz property (with respect to itself). However, this\n   only follows from associativity _if_ you already can rewrite\n   (\"remove parentheses\"). It is circular after all. :-( *)\n\nDefinition associative {X: Set} (op: X → X → X) := ∀ x y z,\n  op x (op y z) = op (op x y) z.\n\nProposition eAj: associative ekviv.\nProof. intros x y z. symmetry. apply ejj. apply eA. Qed.\n\nProposition yyl1: ∀ x y, x ≡ ((y ≡ y) ≡ x).\nProof. intros x y. rewrite 2 eAj. apply eS. Qed.\n\nSection Properties_Operation_Relation.\n\nVariable (X: Set) (op: X → X → X).\nNotation \"x ○ y\" := (op x y) (at level 65).\nDefinition R x y := x ○ y = y.\nNotation \"x # y\" := (R x y) (at level 75).\n\nDefinition idempotent := ∀ x, x ○ x = x.\nProposition i2r: idempotent ↔ reflexive X R.\nProof. split; intros hyp x; apply hyp. Qed.\n\nDefinition absorbent t := ∀ x, x ○ t = t.\nDefinition maximal t := ∀ x, x # t.\nProposition a2m: ∀ t, absorbent t ↔ maximal t.\nProof. split; intros hyp x; apply hyp. Qed.\n\nDefinition transitive := ∀ x y z, x # y → y # z → x # z.\nProposition as2tr: associative op → transitive.\nProof.\n  intros assoc x y z xy yz. unfold \"#\" in *.\n  rewrite <- yz, assoc, xy. reflexivity.\nQed.\n(* Converse doesn't hold here: on {t,f}, define x○y:=¬y.\n   Then # is empty (x○y is never y) so trivially transitive,\n   but t○(t○t)=t○f=t and (t○t)○t=f○t=f, so ○ is not associative. *)\n\n(* Also: if ○ is commutative, then # is antisymmetric.\n   The converse doesn't hold; same counterexample. *)\n   \n(* Also, what distributes through ○, is monotone with respect to #.\n   Again, the same counterexample (with ∧ as additional operation)\n   shows that converse doesn't hold. *)\n\nEnd Properties_Operation_Relation.\n\n(* The mystery of quasidistributivity *)\n(* ---------------------------------- *)\n\n(* ∨ distributes over ≡, but ∧ doesn't.\n   There is a \"quasidistributivity\": ∧ distributes over ternary ≡!\n   Of course, then ∨ also distributes over ternary ≡ (which is\n   not surprising, since ternary ≡ is invariant to t↔f switch *)\n   \n(* | x  y     | is a square with \"even parity\".      | x  x∧y |\n   | z  x≡y≡z |                                 Also | y  x∨y | *)\n\n(* However, why does ∨ behave even better?\n   Of course, if we want symmetry swapping ∨ and ∧, we also have\n   to switch t↔f, and then binary ≡ becomes ⊻ (xor), but\n   ternary ≡ is preserved (see squares above)\n\n(* In | x y | there is an odd number of t and even number of f\n      | x≡y |   so we can't just swap them: we get x⊻y below *)\n\n(* And truly, ∧ distributes over ⊻: x∧(y⊻z) ≡ x∧y ⊻ x∧z.\n   But ≡ can be used for rewriting, since it's transitive!\n   Well, what does transitive mean? (x≡y)∧(y≡z)→(x≡z)\n   Dually, we get a contrapositive: (x⊻y)∨(y⊻z)←(x⊻z) which holds.\n\nAnd there is also a reason for extra-good property:\nin Z2 (a ring of two elements, even and odd numbers)\n* if we interpret t as even (0), and f as odd (1),\n  then ⊻ is addition (mod 2),\n  and ∧ is multiplication (mod 2 but irrelevant)\n  - so this is distributivity of multiplication over addition!\n    (this is well known, but the dual interpretation maybe isn't:)\n* if we interpret t as odd (1), and f as even (0),\n  then ≡ is addition (mod 2),\n  and ∨ is multiplication (mod 2 but irrelevant)\n  - so this is again distributivity of times over plus! :-)\nI think it solves the mystery. *)\n\n(* Šika: which axioms should be used for ≡ & ∧ ?\n  Yes, quasidistributivity, probably, but with ∧ there is another\n  natural choice for an axiom (that we don't have with ∨, again\n  since t is favored over f): x ∧ t ≡ x. I think it doesn't follow\n  from anything else, and it (at least a bit) restores the\n  \"disadvantage\" that ∧ has over ∨ regarding distributivity. *)\n\n(* ≡ and ∨ formalize exactly the positive fragment.\n   Normal forms: ≡-chains of very elementary disjunctions\n   (no negations, no repetition, order doesn't matter)\n   So with x and y we have ≡-chains of: x y x∨y, which are\n   (again, no repetition, order doesn't matter)\n   x    y    x∨y    x≡y    x≡x∨y    y≡x∨y    x≡y≡x∨y\n                             x←y       x→y       x∧y            *)\n(* Does tertium non datur follow from other axioms? No! → Python *)\n\n(* The simplest forms are (with ∨ as head) x∨¬x\n   and (with ≡ as head) x∨f≡x. They cannot be simplified further.\n   A 4-value countermodel shows it is not a consequence.\n   (Just for humoristic value, there is a 2-value model, where\n   ≡ and ∨ are interpreted as ordinary equivalence and disjunction\n   while ¬ is interpreted as identity (!). It satisfies all the\n   axioms except TND. *)", "meta": {"author": "vedgar", "repo": "LAP2021", "sha": "ca529c368ece915c31c9608c686813f654d2b3cf", "save_path": "github-repos/coq/vedgar-LAP2021", "path": "github-repos/coq/vedgar-LAP2021/LAP2021-ca529c368ece915c31c9608c686813f654d2b3cf/Šikaeng.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.6803009937845986}}
{"text": "Require Import Coq.ZArith.ZArith Coq.micromega.Lia.\nRequire Import Crypto.Util.ZUtil.Tactics.CompareToSgn.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Hints.ZArith.\nRequire Import Crypto.Util.ZUtil.Hints.PullPush.\nRequire Import Crypto.Util.ZUtil.ZSimplify.Core.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma div_mul' : forall a b : Z, b <> 0 -> (b * a) / b = a.\n  Proof. intros. rewrite Z.mul_comm. apply Z.div_mul; auto. Qed.\n  Hint Rewrite div_mul' using zutil_arith : zsimplify.\n\n  Local Ltac replace_to_const c :=\n    repeat match goal with\n           | [ H : ?x = ?x |- _ ] => clear H\n           | [ H : ?x = c, H' : context[?x] |- _ ] => rewrite H in H'\n           | [ H : c = ?x, H' : context[?x] |- _ ] => rewrite <- H in H'\n           | [ H : ?x = c |- context[?x] ] => rewrite H\n           | [ H : c = ?x |- context[?x] ] => rewrite <- H\n           end.\n\n  Lemma lt_div_0 n m : n / m < 0 <-> ((n < 0 < m \\/ m < 0 < n) /\\ 0 < -(n / m)).\n  Proof.\n    Z.compare_to_sgn; rewrite Z.sgn_opp; simpl.\n    pose proof (Zdiv_sgn n m) as H.\n    pose proof (Z.sgn_spec (n / m)) as H'.\n    repeat first [ progress intuition auto\n                 | progress simpl in *\n                 | congruence\n                 | lia\n                 | progress replace_to_const (-1)\n                 | progress replace_to_const 0\n                 | progress replace_to_const 1\n                 | match goal with\n                   | [ x : Z |- _ ] => destruct x\n                   end ].\n  Qed.\n\n  Lemma div_add' a b c : c <> 0 -> (a + c * b) / c = a / c + b.\n  Proof. intro; rewrite <- Z.div_add, (Z.mul_comm c); try lia. Qed.\n\n  Lemma div_add_l' a b c : b <> 0 -> (b * a + c) / b = a + c / b.\n  Proof. intro; rewrite <- Z.div_add_l, (Z.mul_comm b); lia. Qed.\n\n  Hint Rewrite div_add_l' div_add' using zutil_arith : zsimplify.\n\n  Lemma div_sub a b c : c <> 0 -> (a - b * c) / c = a / c - b.\n  Proof. intros; rewrite <- !Z.add_opp_r, <- Z.div_add by lia; apply f_equal2; lia. Qed.\n\n  Lemma div_sub' a b c : c <> 0 -> (a - c * b) / c = a / c - b.\n  Proof. intro; rewrite <- div_sub, (Z.mul_comm c); try lia. Qed.\n\n  Hint Rewrite div_sub div_sub' using zutil_arith : zsimplify.\n\n  Lemma div_add_sub_l a b c d : b <> 0 -> (a * b + c - d) / b = a + (c - d) / b.\n  Proof. rewrite <- Z.add_sub_assoc; apply Z.div_add_l. Qed.\n\n  Lemma div_add_sub_l' a b c d : b <> 0 -> (b * a + c - d) / b = a + (c - d) / b.\n  Proof. rewrite <- Z.add_sub_assoc; apply Z.div_add_l'. Qed.\n\n  Lemma div_add_sub a b c d : c <> 0 -> (a + b * c - d) / c = (a - d) / c + b.\n  Proof. rewrite (Z.add_comm _ (_ * _)), (Z.add_comm (_ / _)); apply Z.div_add_sub_l. Qed.\n\n  Lemma div_add_sub' a b c d : c <> 0 -> (a + c * b - d) / c = (a - d) / c + b.\n  Proof. rewrite (Z.add_comm _ (_ * _)), (Z.add_comm (_ / _)); apply Z.div_add_sub_l'. Qed.\n\n  Hint Rewrite Z.div_add_sub Z.div_add_sub' Z.div_add_sub_l Z.div_add_sub_l' using zutil_arith : zsimplify.\n\n  Lemma div_mul_skip a b k : 0 < b -> 0 < k -> a * b / k / b = a / k.\n  Proof.\n    intros; rewrite Z.div_div, (Z.mul_comm k), <- Z.div_div by lia.\n    autorewrite with zsimplify. reflexivity.\n  Qed.\n\n  Lemma div_mul_skip' a b k : 0 < b -> 0 < k -> b * a / k / b = a / k.\n  Proof.\n    intros; rewrite Z.div_div, (Z.mul_comm k), <- Z.div_div by lia.\n    autorewrite with zsimplify; reflexivity.\n  Qed.\n\n  Hint Rewrite Z.div_mul_skip Z.div_mul_skip' using zutil_arith : zsimplify.\n\n  Lemma div_mul_skip_pow base e0 e1 x y : 0 < y -> 0 < base -> 0 <= e1 <= e0 -> x * base^e0 / y / base^e1 = x * base^(e0 - e1) / y.\n  Proof.\n    intros.\n    assert (0 < base^e1) by auto with zarith.\n    replace (base^e0) with (base^(e0 - e1) * base^e1) by (autorewrite with pull_Zpow zsimplify; reflexivity).\n    rewrite !Z.mul_assoc.\n    autorewrite with zsimplify; lia.\n  Qed.\n  Hint Rewrite div_mul_skip_pow using zutil_arith : zsimplify.\n\n  Lemma div_mul_skip_pow' base e0 e1 x y : 0 < y -> 0 < base -> 0 <= e1 <= e0 -> base^e0 * x / y / base^e1 = base^(e0 - e1) * x / y.\n  Proof.\n    intros.\n    rewrite (Z.mul_comm (base^e0) x), div_mul_skip_pow by lia.\n    auto using f_equal2 with lia.\n  Qed.\n  Hint Rewrite div_mul_skip_pow' using zutil_arith : zsimplify.\n\n  Lemma div_le_mono_nonneg a b c : 0 <= c -> a <= b -> a / c <= b / c.\n  Proof.\n    destruct (Z_zerop c).\n    { subst; simpl; autorewrite with zsimplify; reflexivity. }\n    { intros; apply Z.div_le_mono; omega. }\n  Qed.\n  Hint Resolve div_le_mono_nonneg : zarith.\n\n  Lemma div_le_mono_pow_pos a b c e : a <= b -> a / Z.pos c ^ e <= b / Z.pos c ^ e.\n  Proof. auto with zarith. Qed.\n\n  Lemma div_nonneg a b : 0 <= a -> 0 <= b -> 0 <= a / b.\n  Proof.\n    destruct (Z_zerop b); subst; rewrite ?Zdiv_0_r; [ reflexivity | ].\n    intros; apply Z.div_pos; omega.\n  Qed.\n  Hint Resolve div_nonneg : zarith.\n\n  Lemma div_add_exact x y d : d <> 0 -> x mod d = 0 -> (x + y) / d = x / d + y / d.\n  Proof.\n    intros; rewrite (Z_div_exact_full_2 x d) at 1 by assumption.\n    rewrite Z.div_add_l' by assumption; lia.\n  Qed.\n  Hint Rewrite div_add_exact using zutil_arith : zsimplify.\n\n  Lemma div_sub_mod_exact a b : b <> 0 -> a / b = (a - a mod b) / b.\n  Proof.\n    intro.\n    rewrite (Z.div_mod a b) at 2 by lia.\n    autorewrite with zsimplify.\n    reflexivity.\n  Qed.\n\n  Lemma div_sub_mod_cond x y d\n    : d <> 0\n      -> (x - y) / d\n         = x / d + ((x mod d - y) / d).\n  Proof. clear.\n         intro.\n         replace (x - y) with ((x - x mod d) + (x mod d - y)) by lia.\n         rewrite Z.div_add_exact by (autorewrite with pull_Zmod zsimplify; auto).\n         rewrite <- Z.div_sub_mod_exact by lia; lia.\n  Qed.\n  Hint Resolve div_sub_mod_cond : zarith.\n\n  Lemma div_add_mod_cond_l : forall x y d, d <> 0 -> (x + y) / d = (x mod d + y) / d + x / d.\n  Proof.\n    intros. replace (x + y) with ((x - x mod d) + (x mod d + y)) by lia.\n    rewrite Z.div_add_exact by (autorewrite with pull_Zmod zsimplify; auto).\n    rewrite <- Z.div_sub_mod_exact by lia; lia.\n  Qed.\n\n  Lemma div_add_mod_cond_r : forall x y d, d <> 0 -> (x + y) / d = (x + y mod d) / d + y / d.\n  Proof.\n    intros. rewrite Z.add_comm, div_add_mod_cond_l by auto. repeat (f_equal; try ring).\n  Qed.\n\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/Div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.6803009775305144}}
{"text": "Require Export Subbases SeparatednessAxioms.\nFrom ZornsLemma Require Export Relation_Definitions_Implicit.\nFrom ZornsLemma Require Import EnsemblesTactics.\n\nSection OrderTopology.\n\nVariable X:Type.\nVariable R:relation X.\nHypothesis R_ord: order R.\n\nInductive order_topology_subbasis : Family X :=\n  | intro_lower_interval: forall x:X,\n    In order_topology_subbasis [ y:X | R y x /\\ y <> x ]\n  | intro_upper_interval: forall x:X,\n    In order_topology_subbasis [ y:X | R x y /\\ y <> x].\n\nDefinition OrderTopology : TopologicalSpace :=\n  Build_TopologicalSpace_from_subbasis X order_topology_subbasis.\n\nSection if_total_order.\n\nHypothesis R_total: forall x y:X, R x y \\/ R y x.\n\nLemma lower_closed_interval_closed: forall x:X,\n  closed [ y:X | R y x ] (X:=OrderTopology).\nProof.\nintro.\nred.\nmatch goal with |- open ?U => replace U with (interior U) end.\n{ apply interior_open. }\napply Extensionality_Ensembles; split.\n{ apply interior_deflationary. }\nintros y ?.\nred in H.\nred in H.\nassert (R x y).\n{ destruct (R_total x y); trivial.\n  now contradiction H. }\nexists [z:X | R x z /\\ z <> x];\n  constructor; split; trivial.\n- apply (Build_TopologicalSpace_from_subbasis_subbasis\n    _ order_topology_subbasis).\n  constructor.\n- red. intros z ?.\n  destruct H1.\n  destruct H1.\n  intro.\n  destruct H3.\n  contradiction H2.\n  now apply (ord_antisym R_ord).\n- intro.\n  contradiction H.\n  constructor.\n  now subst.\nQed.\n\nLemma upper_closed_interval_closed: forall x:X,\n  closed [y:X | R x y] (X:=OrderTopology).\nProof.\nintro.\nred.\nmatch goal with |- open ?U => replace U with (interior U) end.\n{ apply interior_open. }\napply Extensionality_Ensembles; split.\n{ apply interior_deflationary. }\nintros y ?.\nred in H.\nred in H.\nassert (R y x).\n{ destruct (R_total x y); trivial.\n  now contradiction H. }\nexists ([z:X | R z x /\\ z <> x]);\n  constructor; split; trivial.\n- apply (Build_TopologicalSpace_from_subbasis_subbasis\n    _ order_topology_subbasis).\n  constructor.\n- red; intros z ?.\n  destruct H1.\n  destruct H1.\n  intro.\n  destruct H3.\n  contradiction H2.\n  now apply (ord_antisym R_ord).\n- intro.\n  contradiction H.\n  constructor.\n  now subst.\nQed.\n\nLemma order_topology_Hausdorff: Hausdorff OrderTopology.\nProof.\nred.\nmatch goal with |- forall x y:point_set OrderTopology, ?P =>\n  cut (forall x y:point_set OrderTopology, R x y -> P)\n  end;\n  intros.\n- destruct (R_total x y).\n  { exact (H x y H1 H0). }\n  assert (y <> x) by auto.\n  destruct (H y x H1 H2) as [V [U [? [? [? []]]]]].\n  exists U, V.\n  repeat split; trivial.\n  transitivity (Intersection V U); trivial.\n  now extensionality_ensembles.\n- pose proof (Build_TopologicalSpace_from_subbasis_subbasis\n    _ order_topology_subbasis).\n  destruct (classic (exists z:X, R x z /\\ R z y /\\ z <> x /\\ z <> y)).\n  + destruct H2 as [z [? [? []]]].\n    exists ([w:X | R w z /\\ w <> z]),\n           ([w:X | R z w /\\ w <> z]).\n    repeat split; auto.\n    * apply H1.\n      constructor.\n    * apply H1.\n      constructor.\n    * extensionality_ensembles.\n      destruct H6, H7.\n      contradiction H8.\n      now apply (ord_antisym R_ord).\n  + exists ([w:X | R w y /\\ w <> y]),\n           ([w:X | R x w /\\ w <> x]).\n    repeat split; auto.\n    * apply H1.\n      constructor.\n    * apply H1.\n      constructor.\n    * extensionality_ensembles.\n      destruct H3, H4.\n      contradiction H2.\n      exists x0.\n      now repeat split.\nQed.\n\nEnd if_total_order.\n\nEnd OrderTopology.\n\nArguments OrderTopology {X}.\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/OrderTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.6802932004627099}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import Psatz.\n\nRequire Import kernel_numeric.\nRequire Import kernel_graph.\nRequire Import graph_examples.\nRequire Import graph_constructions.\n\nDefinition graph_complement (G : Graph) : Graph.\nProof.\n  refine {| V := (V G);\n            E := fun x y => x <> y  /\\ not(E G x y); \n         |}.\n  - intros x y.\n    destruct (Nat.eq_dec x y).\n    + right.\n      intro A.\n      destruct A.\n      auto.\n    + destruct (E_decidable G x y).\n      * right.\n        intro A.\n        destruct A.\n        auto.\n      * auto.\n  - intros x q A.\n    destruct A.\n    auto.\n  - intros x q y r.\n    pose (E_symmetric G).\n    intro A.\n    destruct A.\n    split; auto. (* spet primer ko auto zna omega pa ne*)\nQed.\n\nDefinition ordered_induced_subgraph (G : Graph) (n : nat) (p: n <= (V G)): Graph.\n(*Proof. (* kje je Proof. bolj smiselno? *)*)\n  refine {| V := n;\n            E := fun x y => E G x y; \n         |}.\n(* Tu bi sel tudi tukaj ampak kje drugje pa ne saj moti znak ; *)\nProof. \n  - apply (E_decidable G).\n  - intros x q.\n    apply (E_irreflexive G).\n    omega.\n  - intros x q y r.\n    apply E_symmetric; omega.\nQed.\n\n(* This definition is for reflexive edges only - must be normal graph. *)\nDefinition graph_equality (G1 : Graph) (G2 : Graph) :=\n  (V G1) = (V G2) /\\ (all x : (V G1), all y : x, (E G1 x y <-> E G2 x y)).\n\nDefinition graph_homomorphism (G1 G2 : Graph) (f : nat -> nat):=\n  (all x : (V G1), ((f x) < (V G2)))/\\ \n  (all x : (V G1), all y : x, (E G1 x y -> E G2 (f x) (f y))).\n\n(* graph_surjective_homeomorphism *)\nDefinition graph_epimorphism (G1 G2 : Graph) (f : nat -> nat):=\n  (all x : (V G1), ((f x) < (V G2))) /\\ \n  (all y : (V G2), some x : (V G1), ((f x) = y)) /\\ \n  (all x : (V G1), all y : x, (E G1 x y -> E G2 (f x) (f y))).\n(** \nto je sedaj definiran epimorfizm s pripadajoco funkcijo\nMogoce nekoc enako brez da podana funkcija. \nPotem uporabim obstaja f...\n**)\n\nDefinition graph_monomorphism (G1 G2 : Graph) (f : nat -> nat):=\n  (all x : (V G1), ((f x) < (V G2))) /\\ \n  (all x1 : (V G1), all x2 : (V G1), ((x1 <> x2) -> ((f x1) <> (f x2)))) /\\ \n  (all x : (V G1), all y : x, (E G1 x y -> E G2 (f x) (f y))).\n\nDefinition graph_monomorphism_back (G1 G2 : Graph) (f : nat -> nat):=\n  (all x : (V G1), ((f x) < (V G2))) /\\ \n  (all x1 : (V G1), all x2 : (V G1), ((x1 <> x2) -> ((f x1) <> (f x2)))) /\\ \n  (all x : (V G1), all y : x, (E G2 (f x) (f y) -> E G1 x y)).\n\nDefinition graph_izomorphismA (G1 G2 : Graph) (f : nat -> nat):=\n  (V G1) = (V G2) /\\ (graph_epimorphism G1 G2 f).\n\nDefinition graph_izomorphismB (G1 G2 : Graph) (f : nat -> nat):=\n  (V G1) = (V G2) /\\ (graph_monomorphism G1 G2 f).\n\nDefinition increasing_conected_graph (G : Graph) :=\n  (all x : (V G), some y : x, (E G x y)).\n\nDefinition conected_graphA (G : Graph) :=\n  (exists H : Graph , ((increasing_conected_graph H) /\\ \n   exists f : nat -> nat, (graph_epimorphism H G f))).\n\n(*\nSearch (~ (_ /\\ _) -> (_ \\/ _)).\nSearch (~(_ \\/ _) -> (_ /\\ _)).\n*)\n\n\n\n(*\nDefinition conected_graphB (G : Graph) :=\n  (exists H : Graph , ((increasing_conected_graph H) /\\ \n   exists f : nat -> nat, (graph_monomorphism_back G H f))).\n\nDefinition conected_graphC (G : Graph) :=\n  (exists H : Graph , ((increasing_conected_graph H) /\\ \n   exists f : nat -> nat, (graph_monomorphism_back \n    (graph_complement G) (graph_complement H) f))).\n*)\n\n      \n  \n\n\n\n\n\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/kernel_graph_extensions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.680293186614501}}
{"text": "Require Import Coq.Reals.Rdefinitions.\nRequire Import Coq.Reals.Ranalysis1.\nRequire Import Coq.Reals.Ranalysis4.\nRequire Import Coq.micromega.Psatz.\nRequire Import Coq.Reals.Rbasic_fun.\nRequire Import Coq.Reals.Rtrigo_def.\nRequire Import Coq.Reals.Reals.\nRequire Import SLogic.Tactics.\n\nDefinition strict_increasing_bound\n           (f : R -> R) (bound : R) : Prop :=\n  forall x y, (bound <= x < y -> f x < f y)%R.\n\nDefinition decreasing_bound\n           (f : R -> R) (bound : R) : Prop :=\n  forall x y, (bound <= x <= y -> f y <= f x)%R.\n\nDefinition K_fun (f : R -> R) : Prop :=\n  continuity f /\\ strict_increasing_bound f R0 /\\ f R0 = R0.\n\n(* I couldn't find a definition in the standard library\n   for the limit at infinity. *)\nDefinition limit_pos_inf (f : R -> R) (l : R) : Prop :=\n  forall epsilon, (epsilon > 0)%R ->\n    exists M, (M > 0)%R /\\\n      (forall x, x > M -> Rabs (f x - l) < epsilon)%R.\n\nDefinition unbounded (f : R -> R) : Prop :=\n  (forall N, N > 0 ->\n     exists M, (M > 0)%R /\\\n       forall x, x > M -> f(x) > N)%R.\n\nDefinition K_inf_fun (f : R -> R) : Prop :=\n  K_fun f /\\ unbounded f.\n\n(* This is not the same as the definition of L functions\n   from the Tabuada paper. In particular, we only require\n   that the function be decreasing, not strictly decreasing.\n   I think that if you require the function to be strictly\n   decreasing, then there are no KLD functions. Moreover,\n   I think that our definition of L function is the\n   standard one from control theory. *)\nDefinition L_fun (f : R -> R) : Prop :=\n  continuity f /\\ decreasing_bound f R0 /\\\n  limit_pos_inf f R0.\n\nDefinition KL_fun (f : R -> R -> R) : Prop :=\n  (forall t, (0 <= t)%R -> K_fun (fun c => f c t)) /\\\n  (forall c, (0 <= c)%R -> L_fun (fun t => f c t)).\n\nDefinition KLD_fun (f : R -> R -> R) : Prop :=\n  KL_fun f /\\\n  forall (c : R),\n    (0 <= c)%R ->\n    f c 0%R = c /\\\n    forall (s t : R),\n      (0 <= s)%R -> (0 <= t)%R ->\n      (f c (s + t) = f (f c s) t)%R.\n\n(* Now some useful properties of these functions. *)\n\nLemma K_fun_pos :\n  forall f, K_fun f ->\n            forall r, (0 <= r)%R ->\n                      (0 <= f r)%R.\nProof.\n  unfold K_fun, strict_increasing_bound. intros.\n  destruct H as [? [Hincr HR0]].\n  rewrite <- HR0. destruct H0.\n  { specialize (Hincr R0 r). psatzl R. }\n  { rewrite H0. psatzl R. }\nQed.\n\nLemma KL_fun_pos :\n  forall f, KL_fun f ->\n            forall r1 r2,\n              (0 <= r1)%R -> (0 <= r2)%R ->\n              (0 <= f r1 r2)%R.\nProof.\n  unfold KL_fun. intros.\n  destruct H as [HK ?].\n  specialize (HK r2 H1).\n  eapply K_fun_pos in HK; eauto.\nQed.\n\nLemma KLD_fun_pos :\n  forall f, KLD_fun f ->\n            forall r1 r2,\n              (0 <= r1)%R -> (0 <= r2)%R ->\n              (0 <= f r1 r2)%R.\nProof.\n  unfold KLD_fun. intros.\n  apply KL_fun_pos; tauto.\nQed.\n\nLemma KLD_fun_increasing_nonneg :\n  forall f,\n    KLD_fun f ->\n    forall t, (0 <= t)%R ->\n              strict_increasing_bound (fun x => f x t) R0.\nProof.\n  intros. unfold KLD_fun, KL_fun, K_fun in *.\n  intuition. specialize (H t).\n  specialize_arith_hyp H. tauto.\nQed.\n\nLemma KLD_fun_0 :\n  forall f,\n    KLD_fun f ->\n    forall t, (0 <= t)%R ->\n              f R0 t = R0.\nProof.\n  unfold KLD_fun, KL_fun, K_fun, L_fun. intros.\n  intuition.\n  (* This requires reasoning about infinite limits. *)\nAdmitted.\n\nLemma continuity_id :\n  continuity id.\nProof.\n  apply derivable_continuous; apply derivable_id.\nQed.\n\nLemma continuity_exp :\n  continuity exp.\nProof.\n  apply derivable_continuous; apply derivable_exp.\nQed.\n\n(* TODO: move *)\n(* Proves continuity facts of real-valued functions. *)\nLtac prove_continuity :=\n  repeat first [ apply continuity_plus |\n                 apply continuity_opp |\n                 apply continuity_minus |\n                 apply continuity_mult |\n                 solve [apply continuity_const; congruence] |\n                 apply continuity_scal |\n                 apply continuity_inv |\n                 apply continuity_div |\n                 apply continuity_id |\n                 apply continuity_exp |\n                 apply Ranalysis4.Rcontinuity_abs ].\n\nLemma Rabs_involutive :\n  forall r, Rabs (Rabs r) = Rabs r.\nProof.\n  intros. apply Rabs_pos_eq; apply Rabs_pos.\nQed.\n\nLocal Open Scope R_scope.\n\nLemma K_fun_id :\n  K_fun Ranalysis1.id.\nProof.\n  split.\n  { prove_continuity. }\n  { unfold strict_increasing_bound, Ranalysis1.id.\n    split; intros; psatzl R. }\nQed.\n\nLemma K_fun_mult :\n  forall f1 f2,\n    K_fun f1 -> K_fun f2 ->\n    K_fun (fun x => f1 x * f2 x).\nProof.\n  unfold K_fun; intros; split.\n  { prove_continuity; tauto. }\n  { unfold strict_increasing_bound in *. intuition.\n    pose proof (H0 x y). pose proof (H2 x y).\n    specialize_arith_hyp H3. specialize_arith_hyp H8.\n    specialize (H0 0 x). specialize (H2 0 x).\n    destruct H6.\n    { specialize_arith_hyp H0. specialize_arith_hyp H2.\n      psatz R. }\n    { subst. psatz R. } }\nQed.\n\nLemma K_fun_scale :\n  forall f c,\n    K_fun f -> 0 < c ->\n    K_fun (fun x => c * f x).\nProof.\n  unfold K_fun. intros. split.\n  { prove_continuity; tauto. }\n  { unfold strict_increasing_bound in *. intuition. }\nQed.\n\nLemma K_inf_fun_id :\n  K_inf_fun Ranalysis1.id.\nProof.\n  split.\n  { apply K_fun_id. }\n  { unfold unbounded, id. intros. eauto. }\nQed.\n\nLemma K_inf_fun_scale :\n  forall f c,\n    K_inf_fun f -> 0 < c ->\n    K_inf_fun (fun x => c * f x).\nProof.\n  unfold K_inf_fun. intros. split.\n  { apply K_fun_scale; tauto. }\n  { unfold unbounded in *. intros.\n    assert (/c > 0) by (apply Rinv_0_lt_compat; assumption).\n    assert (N / c > 0) by (unfold Rdiv; psatz R).\n    destruct H. specialize (H4 _ H3).\n    destruct H4. destruct H4.\n    exists x. split; auto. intros. specialize (H5 _ H6).\n    apply Rlt_gt. apply (Rmult_lt_reg_l (/c)); [ psatzl R | ].\n    rewrite <- Rmult_assoc. rewrite <- Rinv_l_sym; psatzl R. }\nQed.\n\nLemma KL_fun_abs_exp :\n  forall a,\n    0 < a ->\n    KL_fun (fun d t => Rabs d * exp (-t * a)).\nProof.\n  repeat split.\n  { prove_continuity. }\n  { unfold strict_increasing_bound. intros.\n    pose proof (Exp_prop.exp_pos (-t * a)).\n    repeat (rewrite Rabs_right;\n            [ | solve [psatzl R ] ]).\n    psatz R. }\n  { rewrite Rabs_R0. psatzl R. }\n  { prove_continuity.\n    apply continuity_comp with (f1:=fun x => -x * a)\n                                 (f2:=exp);\n      prove_continuity. }\n  { unfold decreasing_bound. intros.\n    destruct H1. destruct H2.\n    { pose proof (exp_increasing (-y * a) (-x * a)).\n      pose proof (Rabs_pos c).\n      assert (- y * a < - x * a) by psatz R.\n      pose proof (exp_pos (-y * a)).\n      intuition.\n    (* I don't understand\n             how this solves the goal. *) }\n    { subst. intuition. } }\n  { unfold limit_pos_inf. intros.\n    admit. (* Need some limit lemmas. *) }\nAdmitted.\n\nLemma KLD_fun_abs_exp :\n  forall a,\n    0 < a ->\n    KLD_fun (fun d t => Rabs d * exp (-t * a)).\nProof.\n  split.\n  { apply KL_fun_abs_exp; assumption. }\n  { repeat split.\n    { intros.\n      rewrite RIneq.Ropp_0. rewrite Rmult_0_l. rewrite exp_0.\n      rewrite RIneq.Rmult_1_r.\n      apply Rabs_pos_eq; assumption. }\n    { intros. rewrite RIneq.Ropp_plus_distr.\n      rewrite Rmult_plus_distr_r. rewrite Exp_prop.exp_plus.\n      rewrite Rabs_mult. rewrite Rabs_involutive.\n      rewrite Rabs_pos_eq with (x:=exp (-s * a));\n        [ | left; apply Exp_prop.exp_pos ].\n      psatzl R. } }\nQed.\n", "meta": {"author": "dricketts", "repo": "quadcopter", "sha": "62bb21915612a141e1ffabc73df3dc2d931c54ce", "save_path": "github-repos/coq/dricketts-quadcopter", "path": "github-repos/coq/dricketts-quadcopter/quadcopter-62bb21915612a141e1ffabc73df3dc2d931c54ce/shallow-logic/BoundingFunctions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6802684366423992}}
{"text": "(* \n  Autor(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\n(* * Halting problem for one counter machines CM1_HALT  *)\n\n(* \n  Problem(s):\n    One Counter Machine Halting (CM1_HALT)\n*)\n\nRequire Import List Nat.\n\nDefinition State : Set := nat.\n(* a configuration consists of a state and a counter value *)\nRecord Config : Set := mkConfig { state : State; value : nat }.\n\n(* an instruction (n, q) maps \n  a configuration (p, c) to (q, c * (n+2) / (n+1)) if c is divisible by (n+1)\n  and otherwise to (p+1, c) *)\nDefinition Instruction : Set := State * nat.\n\n(* an one counter machine is a list of instructions *)\nDefinition Cm1 : Set := list Instruction.\n\n(* one counter machine step function *)\nDefinition step (M: Cm1) (x: Config) : Config :=\n  match (value x), (nth_error M (state x)) with\n  | 0, _ => x (* halting configuration *)\n  | _, None => x (* halting configuration *)\n  | _, Some (p, n) => \n      match modulo (value x) (n+1) with\n      | 0 => {| state := p; value := ((value x) * (n+2)) / (n+1) |}\n      | _ => {| state := 1 + state x; value := value x |}\n      end\n  end.\n\n(* unfold step if the configuration is decomposed *)\nArguments step _ !x /.\n\n(* halting configuration property *)\nDefinition halting (M : Cm1) (x: Config) : Prop := step M x = x.\n\n(* One Counter Machine Halting Problem (with Denominators at most 4) *)\nDefinition CM1_HALT : { M : Cm1 | Forall (fun '(_, n) => n < 4) M } -> Prop :=\n  fun '(exist _ M _) => \n    exists n, halting M (Nat.iter n (step M) {| state := 0; value := 1 |}).\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/CM1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7577943603346811, "lm_q1q2_score": 0.6802684296579417}}
{"text": "Require Export P03.\n\n\n\nTheorem lookup_relate:\n  forall k t cts ,   Abs t cts -> lookup k t =  cts (int2Z k).\nProof.\n  intros.\n  induction H; try eauto.\n  simpl. unfold t_update. unfold combine.\n  (* There are a bunch of cases that compare between k0 and k.\n     In this situation, you can just stack destructs (or bdestruct in this problem)\n     and use 'try nia' to eliminate cases that are non-sense. *)\n  bdestruct (ltb k k0); bdestruct (int2Z k0 =? int2Z k);\n    bdestruct (int2Z k <? int2Z k0); bdestruct (ltb k0 k); try nia; eauto.\nQed.\n\n", "meta": {"author": "snu-sf-class", "repo": "sf201902", "sha": "68d5c0149d05c90e7ca45a5f5d75fb11f5b6b596", "save_path": "github-repos/coq/snu-sf-class-sf201902", "path": "github-repos/coq/snu-sf-class-sf201902/sf201902-68d5c0149d05c90e7ca45a5f5d75fb11f5b6b596/4-redblacktree-sol/P04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.841825655188238, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.6802517192673264}}
{"text": "Require Export GeoCoq.Axioms.tarski_axioms.\n\nSection Definitions.\n\nContext `{Tn:Tarski_neutral_dimensionless}.\n\n(** Definition 2.10. *)\n\nDefinition OFSC A B C D A' B' C' D' :=\n  Bet A B C /\\ Bet A' B' C' /\\\n  Cong A B A' B' /\\ Cong B C B' C' /\\\n  Cong A D A' D' /\\ Cong B D B' D'.\n\n(** Definition 3.8. *)\n\nDefinition Bet_4 A1 A2 A3 A4 :=\n   Bet A1 A2 A3 /\\ Bet A2 A3 A4 /\\ Bet A1 A3 A4 /\\ Bet A1 A2 A4.\n\n(** Definition 4.1. *)\n\nDefinition IFSC A B C D A' B' C' D' :=\n   Bet A B C /\\ Bet A' B' C' /\\\n   Cong A C A' C' /\\ Cong B C B' C' /\\\n   Cong A D A' D' /\\ Cong C D C' D'.\n\n(** Definition 4.4. *)\n\nDefinition Cong_3 A B C A' B' C' :=\n  Cong A B A' B' /\\ Cong A C A' C' /\\ Cong B C B' C'.\n\nDefinition Cong_4 P1 P2 P3 P4 Q1 Q2 Q3 Q4 :=\n  Cong P1 P2 Q1 Q2 /\\ Cong P1 P3 Q1 Q3 /\\ Cong P1 P4 Q1 Q4 /\\\n  Cong P2 P3 Q2 Q3 /\\ Cong P2 P4 Q2 Q4 /\\ Cong P3 P4 Q3 Q4.\n\nDefinition Cong_5 P1 P2 P3 P4 P5 Q1 Q2 Q3 Q4 Q5 :=\n  Cong P1 P2 Q1 Q2 /\\ Cong P1 P3 Q1 Q3 /\\\n  Cong P1 P4 Q1 Q4 /\\ Cong P1 P5 Q1 Q5 /\\\n  Cong P2 P3 Q2 Q3 /\\ Cong P2 P4 Q2 Q4 /\\ Cong P2 P5 Q2 Q5 /\\\n  Cong P3 P4 Q3 Q4 /\\ Cong P3 P5 Q3 Q5 /\\ Cong P4 P5 Q4 Q5.\n\n(** Definition 4.10. *)\n\nDefinition Col A B C := Bet A B C \\/ Bet B C A \\/ Bet C A B.\n\n(** Definition 4.15. *)\n\nDefinition FSC A B C D A' B' C' D' :=\n  Col A B C /\\ Cong_3 A B C A' B' C' /\\ Cong A D A' D' /\\ Cong B D B' D'.\n\n(** Definition 5.4. *)\n\nDefinition Le A B C D := exists E, Bet C E D /\\ Cong A B C E.\n\nDefinition Ge A B C D := Le C D A B.\n\n(** Definition 5.14. *)\n\nDefinition Lt A B C D := Le A B C D /\\ ~ Cong A B C D.\n\nDefinition Gt A B C D := Lt C D A B.\n\n(** Definition 6.1. *)\n\nDefinition Out P A B := A <> P /\\ B <> P /\\ (Bet P A B \\/ Bet P B A).\n\n(** Definition 6.22. *)\n\nDefinition Inter A1 A2 B1 B2 X :=\n B1 <> B2 /\\ (exists P, Col P B1 B2 /\\ ~ Col P A1 A2) /\\\n Col A1 A2 X /\\ Col B1 B2 X.\n\n(** Definition 7.1. *)\n\nDefinition Midpoint M A B := Bet A M B /\\ Cong A M M B.\n\n(** Definition 8.1. *)\n\nDefinition Per A B C := exists C', Midpoint B C C' /\\ Cong A C A C'.\n\n(** Definition 8.11. *)\n\nDefinition Perp_at X A B C D :=\n  A <> B /\\ C <> D /\\ Col X A B /\\ Col X C D /\\\n  forall U V, Col U A B -> Col V C D -> Per U X V.\n\n(** Definition 8.11. *)\n\nDefinition Perp A B C D := exists X, Perp_at X A B C D.\n\n(** Definition 9.1. *)\n\nDefinition TS A B P Q :=\n  ~ Col P A B /\\ ~ Col Q A B /\\ exists T, Col T A B /\\ Bet P T Q.\n\n(** Definition 9.7. *)\n\nDefinition OS A B P Q := exists R, TS A B P R /\\ TS A B Q R.\n\n(** Satz 9.33. *)\n\nDefinition Coplanar A B C D :=\n  exists X, (Col A B X /\\ Col C D X) \\/\n            (Col A C X /\\ Col B D X) \\/\n            (Col A D X /\\ Col B C X).\n\n(** Definition 9.37 *)\n\nDefinition TSP A B C P Q :=\n  ~ Coplanar A B C P /\\ ~ Coplanar A B C Q /\\ (exists T, Coplanar A B C T /\\ Bet P T Q).\n\n(** Definition 9.40 *)\n\nDefinition OSP A B C P Q :=\n  exists R, TSP A B C P R /\\ TSP A B C Q R.\n\n(** Definition 10.3. *)\n\nDefinition ReflectL P' P A B :=\n  (exists X, Midpoint X P P' /\\ Col A B X) /\\ (Perp A B P P' \\/ P = P').\n\nDefinition Reflect P' P A B :=\n (A <> B /\\ ReflectL P' P A B) \\/ (A = B /\\ Midpoint A P P').\n\nDefinition ReflectL_at M P' P A B :=\n  (Midpoint M P P' /\\ Col A B M) /\\ (Perp A B P P' \\/ P = P').\n\nDefinition Reflect_at M P' P A B :=\n (A <> B /\\ ReflectL_at M P' P A B) \\/ (A = B /\\ A = M /\\ Midpoint M P P').\n\n(** Definition 11.2. *)\n\nDefinition CongA A B C D E F :=\n  A <> B /\\ C <> B /\\ D <> E /\\ F <> E /\\\n  exists A', exists C', exists D', exists F',\n  Bet B A A' /\\ Cong A A' E D /\\\n  Bet B C C' /\\ Cong C C' E F /\\\n  Bet E D D' /\\ Cong D D' B A /\\\n  Bet E F F' /\\ Cong F F' B C /\\\n  Cong A' C' D' F'.\n\n(** Definition 11.23. *)\n\nDefinition InAngle P A B C :=\n  A <> B /\\ C <> B /\\ P <> B /\\ exists X, Bet A X C /\\ (X = B \\/ Out B X P).\n\n(** Definition 11.27. *)\n\nDefinition LeA A B C D E F := exists P, InAngle P D E F /\\ CongA A B C D E P.\n\nDefinition GeA A B C D E F := LeA D E F A B C.\n\n(** Definition 11.38. *)\n\nDefinition LtA A B C D E F := LeA A B C D E F /\\ ~ CongA A B C D E F.\n\nDefinition GtA A B C D E F := LtA D E F A B C.\n\n(** Definition 11.39. *)\n\nDefinition Acute A B C :=\n  exists A' B' C', Per A' B' C' /\\ LtA A B C A' B' C'.\n\n(** Definition 11.39. *)\n\nDefinition Obtuse A B C :=\n  exists A' B' C', Per A' B' C' /\\ LtA A' B' C' A B C.\n\n(** Definition 11.59. *)\n\nDefinition Orth_at X A B C U V :=\n  ~ Col A B C /\\ U <> V /\\ Coplanar A B C X /\\ Col U V X /\\\n  forall P Q, Coplanar A B C P -> Col U V Q -> Per P X Q.\n\nDefinition Orth A B C U V := exists X, Orth_at X A B C U V.\n\n(** Definition 12.2. *)\n\nDefinition Par_strict A B C D :=\n  Coplanar A B C D /\\ ~ exists X, Col X A B /\\ Col X C D.\n\n(** Definition 12.3. *)\n\nDefinition Par A B C D :=\n  Par_strict A B C D \\/ (A <> B /\\ C <> D /\\ Col A C D /\\ Col B C D).\n\n(** Definition 13.4. *)\n\nDefinition Q_Cong l := exists A B, forall X Y, Cong A B X Y <-> l X Y.\n\nDefinition Len A B l := Q_Cong l /\\ l A B.\n\nDefinition Q_Cong_Null l := Q_Cong l /\\ exists A, l A A.\n\nDefinition EqL (l1 l2 : Tpoint -> Tpoint -> Prop) :=\n  forall A B, l1 A B <-> l2 A B.\n\nDefinition Q_CongA a :=\n  exists A B C,\n    A <> B /\\ C <> B /\\ forall X Y Z, CongA A B C X Y Z <-> a X Y Z.\n\nDefinition Ang A B C a := Q_CongA a /\\ a A B C.\n\nDefinition Ang_Flat a := Q_CongA a /\\ forall A B C, a A B C -> Bet A B C.\n\nDefinition EqA (a1 a2 : Tpoint -> Tpoint -> Tpoint -> Prop) :=\n  forall A B C, a1 A B C <-> a2 A B C.\n\n(** Definition 13.9. *)\n\nDefinition Perp2 A B C D P :=\n  exists X Y, Col P X Y /\\ Perp X Y A B /\\ Perp X Y C D.\n\nDefinition Q_CongA_Acute a :=\n  exists A B C,\n    Acute A B C /\\ forall X Y Z, CongA A B C X Y Z <-> a X Y Z.\n\nDefinition Ang_Acute A B C a := Q_CongA_Acute a /\\ a A B C.\n\nDefinition Q_CongA_nNull a := Q_CongA a /\\ forall A B C, a A B C -> ~ Out B A C.\n\nDefinition Q_CongA_nFlat a := Q_CongA a /\\ forall A B C, a A B C -> ~ Bet A B C.\n\nDefinition Q_CongA_Null a := Q_CongA a /\\ forall A B C, a A B C -> Out B A C.\n\nDefinition Q_CongA_Null_Acute a :=\n  Q_CongA_Acute a /\\ forall A B C, a A B C -> Out B A C.\n\nDefinition is_null_anga' a :=\n  Q_CongA_Acute a /\\ exists A B C, a A B C /\\ Out B A C.\n\nDefinition Q_CongA_nNull_Acute a :=\n  Q_CongA_Acute a /\\ forall A B C, a A B C -> ~ Out B A C.\n\nDefinition Lcos lb lc a :=\n  Q_Cong lb /\\ Q_Cong lc /\\ Q_CongA_Acute a /\\\n  (exists A B C, (Per C B A /\\ lb A B /\\ lc A C /\\ a B A C)).\n\nDefinition Eq_Lcos la a lb b := exists lp, Lcos lp la a /\\ Lcos lp lb b.\n\nDefinition Lcos2 lp l a b := exists la, Lcos la l a /\\ Lcos lp la b.\n\nDefinition Eq_Lcos2 l1 a b l2 c d :=\n  exists lp, Lcos2 lp l1 a b /\\ Lcos2 lp l2 c d.\n\nDefinition Lcos3 lp l a b c :=\n  exists la lab, Lcos la l a /\\ Lcos lab la b /\\ Lcos lp lab c.\n\nDefinition Eq_Lcos3 l1 a b c l2 d e f :=\n  exists lp, Lcos3 lp l1 a b c /\\ Lcos3 lp l2 d e f.\n\n(** Definition 14.1. *)\n\nDefinition Ar1 O E A B C :=\n O <> E /\\ Col O E A /\\ Col O E B /\\ Col O E C.\n\nDefinition Ar2 O E E' A B C :=\n ~ Col O E E' /\\ Col O E A /\\ Col O E B /\\ Col O E C.\n\n(** Definition 14.2. *)\n\nDefinition Pj A B C D := Par A B C D \\/ C = D.\n\n(** Definition 14.3. *)\n\nDefinition Sum O E E' A B C :=\n Ar2 O E E' A B C /\\\n exists A' C',\n Pj E E' A  A' /\\ Col O E' A' /\\\n Pj O E  A' C' /\\\n Pj O E' B  C' /\\\n Pj E' E C' C.\n\nDefinition Proj P Q A B X Y :=\n  A <> B /\\ X <> Y /\\ ~Par A B X Y  /\\ Col A B Q /\\ (Par P Q X Y \\/ P = Q).\n\nDefinition Sump O E E' A B C :=\n Col O E A /\\ Col O E B /\\\n exists A' C' P',\n   Proj A A' O E' E E' /\\\n   Par O E A' P' /\\\n   Proj B C' A' P' O E' /\\\n   Proj C' C O E E E'.\n\n(** Definition 14.4. *)\n\nDefinition Prod O E E' A B C :=\n Ar2 O E E' A B C /\\\n exists B', Pj E E' B B' /\\ Col O E' B' /\\ Pj E' A B' C.\n\nDefinition Prodp O E E' A B C :=\n Col O E A /\\ Col O E B /\\\n exists B', Proj B B' O E' E E' /\\ Proj B' C O E A E'.\n\n(** Definition 14.8. *)\n\nDefinition Opp O E E' A B :=\n Sum O E E' B A O.\n\n(** Definition 14.38. *)\n\nDefinition Diff O E E' A B C :=\n  exists B', Opp O E E' B B' /\\ Sum O E E' A B' C.\n\nDefinition sum3 O E E' A B C S :=\n  exists AB, Sum O E E' A B AB /\\ Sum O E E' AB C S.\n\nDefinition Sum4 O E E' A B C D S :=\n  exists ABC, sum3 O E E' A B C ABC /\\ Sum O E E' ABC D S.\n\nDefinition sum22 O E E' A B C D S :=\n  exists AB CD, Sum O E E' A B AB /\\ Sum O E E' C D CD /\\ Sum O E E' AB CD S.\n\nDefinition Ar2_4 O E E' A B C D :=\n  ~ Col O E E' /\\ Col O E A /\\ Col O E B /\\ Col O E C /\\ Col O E D.\n\n(** Definition 14.34. *)\n\nDefinition Ps O E A := Out O A E.\n\nDefinition Ng O E A := A <> O /\\ E <> O /\\ Bet A O E .\n\n(** Definition 14.38. *)\n\nDefinition LtP O E E' A B := exists D, Diff O E E' B A D /\\ Ps O E D.\n\nDefinition LeP O E E' A B := LtP O E E' A B \\/ A = B.\n\nDefinition Length O E E' A B L :=\n O <> E /\\ Col O E L /\\ LeP O E E' O L /\\ Cong O L A B.\n\n(** Definition 15.1. *)\n\nDefinition Is_length O E E' A B L :=\n Length O E E' A B L \\/ (O = E /\\ O = L).\n\nDefinition Sumg O E E' A B C :=\n  Sum O E E' A B C \\/ (~ Ar2 O E E' A B B /\\ C = O).\n\nDefinition Prodg O E E' A B C :=\n  Prod O E E' A B C \\/ (~ Ar2 O E E' A B B /\\ C = O).\n\nDefinition PythRel O E E' A B C :=\n  Ar2 O E E' A B C /\\\n  ((O = B /\\ (A = C \\/ Opp O E E' A C)) \\/\n   exists B', Perp O B' O B /\\ Cong O B' O B /\\ Cong O C A B').\n\nDefinition SignEq O E A B := Ps O E A /\\ Ps O E B \\/ Ng O E A /\\ Ng O E B.\n\nDefinition LtPs O E E' A B := exists D, Ps O E D /\\ Sum O E E' A D B.\n\n(** Definition 16.1. *)\n(** We skip the case of dimension 1. *)\n\nDefinition Cs O E S U1 U2 :=\n   O <> E /\\ Cong O E S U1 /\\ Cong O E S U2 /\\ Per U1 S U2.\n\n\n(** Q is the orthogonal projection of P on the line AB. *)\n\nDefinition Projp P Q A B :=\n  A <> B /\\ ((Col A B Q /\\ Perp A B P Q) \\/ (Col A B P /\\ P = Q)).\n\n(** Definition 16.5. *)\n(** P is of coordinates (X,Y) in the grid SU1U2 using unit length OE. *)\n\nDefinition Cd O E S U1 U2 P X Y :=\n  Cs O E S U1 U2 /\\ Coplanar P S U1 U2 /\\\n  (exists PX, Projp P PX S U1 /\\ Cong_3 O E X S U1 PX) /\\\n  (exists PY, Projp P PY S U2 /\\ Cong_3 O E Y S U2 PY).\n\n\n(** Strict betweenness *)\n\nDefinition BetS A B C : Prop := Bet A B C /\\ A <> B /\\ B <> C.\n\n(** Definition of the sum of segments.\n    SumS A B C D E F means that AB + CD = EF. *)\n\nDefinition SumS A B C D E F := exists P Q R,\n  Bet P Q R /\\ Cong P Q A B /\\ Cong Q R C D /\\ Cong P R E F.\n\n(** PQ is the perpendicular bisector of segment AB *)\n\nDefinition Perp_bisect P Q A B := ReflectL A B P Q /\\ A <> B.\n\nDefinition Perp_bisect_bis P Q A B :=\n  exists I, Perp_at I P Q A B /\\ Midpoint I A B.\n\nDefinition Is_on_perp_bisect P A B := Cong A P P B.\n\n(** Definition of the sum of angles.\n    SumA A B C D E F G H I means that ABC + DEF = GHI. *)\n\nDefinition SumA A B C D E F G H I :=\n  exists J, CongA C B J D E F /\\ ~ OS B C A J /\\ Coplanar A B C J /\\ CongA A B J G H I.\n\n(** The SAMS predicate describes the fact that the sum of the two angles is \"at most straight\" *)\n\nDefinition SAMS A B C D E F :=\n  A <> B /\\ (Out E D F \\/ ~ Bet A B C) /\\\n  exists J, CongA C B J D E F /\\ ~ OS B C A J /\\ ~ TS A B C J /\\ Coplanar A B C J.\n\n(** Supplementary angles *)\n\nDefinition SuppA A B C D E F :=\n  A <> B /\\ exists A', Bet A B A' /\\ CongA D E F C B A'.\n\n(** Definition of the sum of the interior angles of a triangle.\n    TriSumA A B C D E F means that the sum of the angles of the triangle ABC\n    is equal to the angle DEF *)\n\nDefinition TriSumA A B C D E F :=\n  exists G H I, SumA A B C B C A G H I /\\ SumA G H I C A B D E F.\n\n(** The difference between a straight angle and the sum of the angles of the triangle ABC.\n    It is a non-oriented angle, so we can't discriminate between positive and negative difference *)\n\nDefinition Defect A B C D E F := exists G H I,\n  TriSumA A B C G H I /\\ SuppA G H I D E F.\n\n(** P is on the circle of center A going through B *)\n\nDefinition OnCircle P A B := Cong A P A B.\n\n(** P is inside or on the circle of center A going through B *)\n\nDefinition InCircle P A B := Le A P A B.\n\n(** P is outside or on the circle of center A going through B *)\n\nDefinition OutCircle P A B := Le A B A P.\n\n(** P is strictly inside the circle of center A going through B *)\n\nDefinition InCircleS P A B := Lt A P A B.\n\n(** P is strictly outside the circle of center A going through B *)\n\nDefinition OutCircleS P A B := Lt A B A P.\n\n(** The line segment AB is a diameter of the circle of center O going through P *)\n\nDefinition Diam A B O P := Bet A O B /\\ OnCircle A O P /\\ OnCircle B O P.\n\nDefinition EqC A B C D :=\n forall X, OnCircle X A B <-> OnCircle X C D.\n\n(** The circles of center A passing through B and\n                of center C passing through D intersect\n                in two distinct points P and Q. *)\n\nDefinition InterCCAt A B C D P Q :=\n  ~ EqC A B C D /\\\n  P<>Q /\\ OnCircle P C D /\\ OnCircle Q C D /\\ OnCircle P A B /\\ OnCircle Q A B.\n\n\n(** The circles of center A passing through B and\n                of center C passing through D\n                have two distinct intersections. *)\n\nDefinition InterCC A B C D :=\n exists P Q, InterCCAt A B C D P Q.\n\n(** The circles of center A passing through B and\n                of center C passing through D\n                are tangent. *)\n\nDefinition TangentCC A B C D := exists !X, OnCircle X A B /\\ OnCircle X C D.\n\n(** The line AB is tangent to the circle OP *)\n\nDefinition Tangent A B O P := exists !X, Col A B X /\\ OnCircle X O P.\n\nDefinition TangentAt A B O P T :=\n  Tangent A B O P /\\ Col A B T /\\ OnCircle T O P.\n\n(** The points A, B, C and D belong to a same circle *)\n\nDefinition Concyclic A B C D := Coplanar A B C D /\\\n  exists O P, OnCircle A O P /\\ OnCircle B O P /\\ OnCircle C O P /\\ OnCircle D O P.\n\n(** The points A, B, C and D are concyclic or lined up *)\n\nDefinition Concyclic_gen A B C D :=\n  Concyclic A B C D \\/ (Col A B C /\\ Col A B D /\\ Col A C D /\\ Col B C D).\n\n(** C is on the graduation based on [AB] *)\nInductive Grad : Tpoint -> Tpoint -> Tpoint -> Prop :=\n  | grad_init : forall A B, Grad A B B\n  | grad_stab : forall A B C C',\n                  Grad A B C ->\n                  Bet A C C' -> Cong A B C C' ->\n                  Grad A B C'.\n\nDefinition Reach A B C D := exists B', Grad A B B' /\\ Le C D A B'.\n\n(** There exists n such that AC = n times AB and DF = n times DE *)\nInductive Grad2 : Tpoint -> Tpoint -> Tpoint -> Tpoint -> Tpoint -> Tpoint ->\n                  Prop :=\n  | grad2_init : forall A B D E, Grad2 A B B D E E\n  | grad2_stab : forall A B C C' D E F F',\n                   Grad2 A B C D E F ->\n                   Bet A C C' -> Cong A B C C' ->\n                   Bet D F F' -> Cong D E F F' ->\n                   Grad2 A B C' D E F'.\n\n(** Graduation based on the powers of 2 *)\nInductive GradExp : Tpoint -> Tpoint -> Tpoint -> Prop :=\n  | gradexp_init : forall A B, GradExp A B B\n  | gradexp_stab : forall A B C C',\n                     GradExp A B C ->\n                     Bet A C C' -> Cong A C C C' ->\n                     GradExp A B C'.\n\nInductive GradExp2 : Tpoint -> Tpoint -> Tpoint -> Tpoint -> Tpoint -> Tpoint ->\n                     Prop :=\n  | gradexp2_init : forall A B D E, GradExp2 A B B D E E\n  | gradexp2_stab : forall A B C C' D E F F',\n                      GradExp2 A B C D E F ->\n                      Bet A C C' -> Cong A C C C' ->\n                      Bet D F F' -> Cong D F F F' ->\n                      GradExp2 A B C' D E F'.\n\n(** There exists n such that the angle DEF is congruent to n times the angle ABC *)\nInductive GradA : Tpoint -> Tpoint -> Tpoint -> Tpoint -> Tpoint -> Tpoint ->\n                  Prop :=\n  | grada_init : forall A B C D E F, CongA A B C D E F -> GradA A B C D E F\n  | grada_stab : forall A B C D E F G H I,\n                   GradA A B C D E F ->\n                   SAMS D E F A B C -> SumA D E F A B C G H I ->\n                   GradA A B C G H I.\n\n(** There exists n such that the angle DEF is congruent to 2^n times the angle ABC *)\nInductive GradAExp : Tpoint -> Tpoint -> Tpoint -> Tpoint -> Tpoint -> Tpoint ->\n                     Prop :=\n  | gradaexp_init : forall A B C D E F, CongA A B C D E F -> GradAExp A B C D E F\n  | gradaexp_stab : forall A B C D E F G H I,\n                      GradAExp A B C D E F ->\n                      SAMS D E F D E F -> SumA D E F D E F G H I ->\n                      GradAExp A B C G H I.\n\n(** Parallelogram *)\n\nDefinition Parallelogram_strict A B A' B' :=\n  TS A A' B B' /\\ Par A B A' B' /\\ Cong A B A' B'.\n\nDefinition Parallelogram_flat A B A' B' :=\n  Col A B A' /\\ Col A B B' /\\\n  Cong A B A' B' /\\ Cong A B' A' B /\\\n  (A <> A' \\/ B <> B').\n\nDefinition Parallelogram A B A' B' :=\n  Parallelogram_strict A B A' B' \\/ Parallelogram_flat A B A' B'.\n\nDefinition Plg A B C D :=\n  (A <> C \\/ B <> D) /\\ exists M, Midpoint M A C /\\ Midpoint M B D.\n\n(** Rhombus *)\n\nDefinition Rhombus A B C D := Plg A B C D /\\ Cong A B B C.\n\n(** Rectangle *)\n\nDefinition Rectangle A B C D := Plg A B C D /\\ Cong A C B D.\n\n(** Square *)\n\nDefinition Square A B C D := Rectangle A B C D /\\ Cong A B B C.\n\n(** Kite *)\n\nDefinition Kite A B C D := Cong B C C D /\\ Cong D A A B.\n\n(** Saccheri *)\n\nDefinition Saccheri A B C D :=\n  Per B A D /\\ Per A D C /\\ Cong A B C D /\\ OS A D B C.\n\n(** Lambert *)\n\nDefinition Lambert A B C D :=\n  A <> B /\\ B <> C /\\ C <> D /\\ A <> D /\\ Per B A D /\\ Per A D C /\\ Per A B C /\\ Coplanar A B C D.\n\n(** Vector *)\n\nDefinition EqV A B C D := Parallelogram A B D C \\/ A = B /\\ C = D.\n\nDefinition SumV A B C D E F := forall D', EqV C D B D' -> EqV A D' E F.\n\nDefinition SumV_exists A B C D E F := exists D', EqV B D' C D /\\ EqV A D' E F.\n\nDefinition Same_dir A B C D :=\n  A = B /\\ C = D \\/ exists D', Out C D D' /\\ EqV A B C D'.\n\nDefinition Opp_dir A B C D := Same_dir A B D C.\n\n(** Projections *)\n\nDefinition CongA_3 A B C A' B' C' :=\n  CongA A B C A' B' C' /\\ CongA B C A B' C' A' /\\ CongA C A B C' A' B'.\n\nEnd Definitions.", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Tarski_dev/Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.6802517056485854}}
{"text": "Require Import SetoidList.\nRequire OrderedType.\nRequire Import Orders.\n\n\n\n(** Some preliminary results  **)\nInstance not_symmetric (A : Type) (R: relation A) `{Symmetric A R} : Symmetric (fun x y => ~R x y).\nProof. intros ? ? Hnot HR. apply Hnot. symmetry. assumption. Qed.\n\nInstance InA_compat {A : Type} : Proper (subrelation ==> eq ==> eq ==> impl) (@InA A).\nProof.\nintros inA inB Hin. do 6 intro; subst. intro Hl. rewrite InA_alt in *.\ndestruct Hl as [? [? ?]]. eexists. split; eauto.\nQed.\n\nDefinition full_relation {A : Type} : relation A := fun x y : A => True.\n\n\n(** Conversion module between the two kinds of [OrderedType]. **)\nModule OTconvert (O : OrderedType) : OrderedType.OrderedType\n          with Definition t := O.t\n          with Definition eq := O.eq\n          with Definition lt := O.lt.\n  \n  Definition t := O.t.\n  Definition eq := O.eq.\n  Definition lt := O.lt.\n  \n  Definition eq_refl : forall x, eq x x := reflexivity.\n  Lemma eq_sym : forall x y : t, eq x y -> eq y x.\n  Proof. intros. now symmetry. Qed. \n  Lemma eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z.\n  Proof. intros. etransitivity; eassumption. Qed.\n\n  Lemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z.\n  Proof. intros. etransitivity; eassumption. Qed.\n  Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y.\n  Proof. intros ? ? Hlt Heq. rewrite Heq in Hlt. revert Hlt. apply StrictOrder_Irreflexive. Qed.\n\n  Lemma compare : forall x y : t, OrderedType.Compare lt eq x y.\n  Proof.\n  intros x y. assert (H :=  (O.compare_spec x y)).  destruct (O.compare x y).\n  - constructor 2. now inversion H.\n  - constructor 1. now inversion H.\n  - constructor 3. now inversion H.\n  Qed.\n  \n  Definition eq_dec := O.eq_dec.\nEnd OTconvert.\n", "meta": {"author": "coq-contribs", "repo": "dep-map", "sha": "c8a3df946a9e357284799b0ee40def47538bdc37", "save_path": "github-repos/coq/coq-contribs-dep-map", "path": "github-repos/coq/coq-contribs-dep-map/dep-map-c8a3df946a9e357284799b0ee40def47538bdc37/Coqlib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6802516902995657}}
{"text": "\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n\nFixpoint 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\n(* This is repeated, we have proven mult_assoc as part of other theorems *)\nTheorem theorem0 : forall (x : natural) (y : natural) (z : natural), eq (mult (mult x y) z) (mult x (mult y z)).\nProof.\nAdmitted.\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/goal73.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6802195006401488}}
{"text": "Require Export Logics.\nRequire Export Coq.Setoids.Setoid.\n\nLemma or_elim {A} :\n  A \\/ A <-> A.\nProof.\n  split => [aa | a].\n  induction aa.\n  done.\n  done. \n  by apply or_introl.\nQed.\n\n\n(* 4.1 An Axiom systems*)\n\nAxiom Class : Type.\nAxiom In : Class -> Class -> Prop.\nNotation \"x ∈ X\" := (In x X) (at level 50).\n\n\nAxiom Equal : forall X Y,\n  (forall Z, Z ∈ X <-> Z ∈ Y) <-> X = Y.\n\n\nDefinition Inclusion (X Y : Class) :=\n  forall Z, Z ∈ X -> Z ∈ Y.\nNotation \"X ⊂ Y\" := (Inclusion X Y)(at level 10).\n\n\nDefinition ProperInclusion (X Y : Class) :=\n  X ⊂ Y /\\ X <> Y.\nNotation \"X ⊆ Y\" := (ProperInclusion X Y) (at level 10). \n\n\n\nDefinition M X :=\n  exists Y , X ∈ Y.\n\nDefinition Pr X :=\n  ~ M X.\n\n\nAxiom Classify : (Class -> Prop) -> Class.\nNotation \"{| P |}\"  := (Classify P) (at level 0).\n\nAxiom in_cls :\n  forall P u, M u -> u ∈ ({|P|}) <-> P u.\n\nAxiom Empty : Class.\nNotation \"∅\" := (Empty).\n\nAxiom notin_empty :\n  forall x, M x -> ~ x ∈ ∅.\n    \nAxiom empty_set :\n  M ∅.\n\n \nDefinition Pair x y :=\n  {| fun u => u = x \\/ u = y |}.\n\nAxiom pair_set :\n  forall x y, M x -> M y -> M (Pair x y).\n\nTheorem in_pair x y u (u_ : M u):\n  u ∈ Pair x y <-> u = x \\/ u = y.\nProof.\n  rewrite in_cls => //.\nQed.\n\n\n\n\n\n", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "MK", "sha": "ac16a400fa4fcb4c7568d010ec8677defd0a5b94", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-MK", "path": "github-repos/coq/gaxiiiiiiiiiiii-MK/MK-ac16a400fa4fcb4c7568d010ec8677defd0a5b94/Axioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.6800174698349892}}
{"text": "(* We want a dependently typed recursive function.  The output type is itself\n  described by a recursive function. *)\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\n(* The difficult point is to describe the computation at each\n   recursive step, knowing that sometimes this computation deals with\n   boolean values, while at other times it deals with integer\n   values.  The trick is to discover that computations can actually\n   always be described by the same function as for the\n   pre-predecessor.\n\n   A dependently typed pattern-matching construct is need. *)\n\nRequire Import Bool.\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\n\n(* The function is then easy to describe.  We can use \"Compute\"\n   to check that its value is always as required. *)\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\n(** Tests :\n\nCompute (bool_nat_fun 6).\n\nCompute (bool_nat_fun 7).\n\nCompute (bool_nat_fun 9).\n\nCompute (bool_nat_fun 7 : bool).\n\nCompute (bool_nat_fun 6 : nat).\n\n*)\n\n\n\n(* Defining a function of this form was fun, but will it ever be\n   useful? *)\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/depfun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.6800174619235989}}
{"text": "Require Import IntuitionisticLogic.base.\nRequire Import IntuitionisticLogic.Wf.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Relations.Relation_Operators.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.Setoids.Setoid.\nLocal Open Scope IPC_scope.\n\nModule RelationDef.\nSection RelationDef.\n\nContext {A: Type}.\n\nSection Intersection.\n\nVariables R1 R2: relation A.\n\nDefinition intersection x y := R1 x y /\\ R2 x y.\n\nEnd Intersection.\n\nArguments union {A} R1 R2 x y /.\nArguments intersection R1 R2 x y /.\n\nVariables R eqA: relation A.\n\nClass Total: Prop :=\n  totality: forall x y, R x y \\/ R y x.\n\nClass StrictTotal: Prop :=\n  strict_totality: forall x y, R x y \\/ x = y \\/ R y x.\n\nClass StrictTotalViaEquiv: Prop :=\n  strict_totality_via_equiv: forall x y, R x y \\/ eqA x y \\/ R y x.\n\nClass Antisymmetric: Prop :=\n  antisymmetry: forall x y, R x y -> R y x -> x = y.\n\nClass AntisymViaEquiv: Prop :=\n  antisymmetry_via_equiv: forall x y, R x y -> R y x -> eqA x y.\n\nClass IrreflViaEquiv: Prop :=\n  irreflexivity_via_equiv: forall x y, eqA x y -> R x y -> False.\n\nClass WeakTotalOrder: Prop := {\n  WeakTotalOrder_Reflexive: Reflexive R;\n  WeakTotalOrder_Transitive: Transitive R;\n  WeakTotalOrder_Total: Total\n}.\n\nClass TotalOrder: Prop := {\n  TotalOrder_Reflexive: Reflexive R;\n  TotalOrder_Antisymmetric: Antisymmetric;\n  TotalOrder_Transitive: Transitive R;\n  TotalOrder_Total: Total\n}.\n\nClass StrictTotalOrder: Prop := {\n  StrictTotalOrder_Irreflexive: Irreflexive R;\n  StrictTotalOrder_Transitive: Transitive R;\n  StrictTotalOrder_StrictTotal: StrictTotal\n}.\n\nClass StrictTotalOrderViaEquiv: Prop := {\n  StrictTotalOrderViaEquiv_EqIsEquiv: Equivalence eqA;\n  StrictTotalOrderViaEquiv_IrreflViaEquiv: IrreflViaEquiv;\n  StrictTotalOrderViaEquiv_Transitive: Transitive R;\n  StrictTotalOrderViaEquiv_StrictTotal: StrictTotalViaEquiv\n}.\n\nClass StrictWellOrder: Prop := {\n  StrictWellOrder_StrictTotalOrder: StrictTotalOrder;\n  StrictWellOrder_WellFounded: well_founded R\n}.\n\nEnd RelationDef.\n\nLemma Irreflexive_is_IrreflViaEquiv:\n  forall {A} (R: relation A),\n  Irreflexive R <-> IrreflViaEquiv R eq.\nProof.\n  intros; split; intros; hnf in *; intros.\n  + subst.\n    apply H in H1; auto.\n  + specialize (H x x eq_refl).\n    exact H.\nQed.\n\nEnd RelationDef.\n\nImport RelationDef.\nArguments union {A} R1 R2 x y /.\nArguments intersection {A} R1 R2 x y /.\n\nModule StrictTotalOrderViaEquiv.\nSection StrictTotalOrderViaEquiv.\n\nVariable A: Type.\nVariables R eqA: relation A.\nVariable Order: StrictTotalOrderViaEquiv R eqA.\n\nLemma disjointed_3cases: forall x y,\n  (R x y /\\ ~ eqA x y /\\ ~ R y x) \\/\n  (~ R x y /\\ eqA x y /\\ ~ R y x) \\/\n  (~ R x y /\\ ~ eqA x y /\\ R y x).\nProof.\n  intros.\n  pose proof StrictTotalOrderViaEquiv_StrictTotal _ _ x y.\n  pose proof StrictTotalOrderViaEquiv_IrreflViaEquiv _ _ x y.\n  pose proof StrictTotalOrderViaEquiv_IrreflViaEquiv _ _ y x.\n  pose proof StrictTotalOrderViaEquiv_IrreflViaEquiv _ _ x x.\n  pose proof StrictTotalOrderViaEquiv_Transitive _ _ x y x.\n  inversion Order.\n  pose proof Equivalence_Reflexive x.\n  pose proof Equivalence_Symmetric x y.\n  pose proof Equivalence_Symmetric y x.\n  tauto.\nQed.\n  \nLemma LeftProperViaEquiv: forall x x0 y, eqA x x0 -> R x y -> R x0 y.\nProof.\n  intros.\n  pose proof disjointed_3cases x0 y.\n  pose proof disjointed_3cases x x0.\n  pose proof disjointed_3cases x y.\n  pose proof @Equivalence_Transitive _ eqA (StrictTotalOrderViaEquiv_EqIsEquiv _ _) x x0 y.\n  pose proof StrictTotalOrderViaEquiv_Transitive _ _ x y x0.\n  tauto.\nQed.  \n\nLemma RightProperViaEquiv: forall x y y0, eqA y0 y -> R x y -> R x y0.\nProof.\n  intros.\n  pose proof disjointed_3cases x y.\n  pose proof disjointed_3cases y0 y.\n  pose proof disjointed_3cases x y0.\n  pose proof @Equivalence_Transitive _ eqA (StrictTotalOrderViaEquiv_EqIsEquiv _ _) x y0 y.\n  pose proof StrictTotalOrderViaEquiv_Transitive _ _ y0 x y.\n  tauto.\nQed.\n\nInstance ProperViaEquiv: Proper (eqA ==> eqA ==> iff) R.\nProof.\n  intro; intros; intro; intros.\n  inversion Order.\n  pose proof Equivalence_Symmetric _ _  H.\n  pose proof Equivalence_Symmetric _ _  H0.\n  pose proof LeftProperViaEquiv x y x0 H.\n  pose proof LeftProperViaEquiv y x x0 H1.\n  pose proof RightProperViaEquiv y x0 y0 H2.\n  pose proof RightProperViaEquiv y y0 x0 H0.\n  tauto.\nQed.\n\nEnd StrictTotalOrderViaEquiv.\n\nTheorem StrictTotalOrder_is_StrictTotalOrderViaEquiv:\n  forall {A} (R: relation A), StrictTotalOrder R <-> StrictTotalOrderViaEquiv R eq.\nProof.\n  intros; split; intros; inversion H; constructor; auto.\n  + apply eq_equivalence.\n  + apply Irreflexive_is_IrreflViaEquiv; auto.\n  + apply Irreflexive_is_IrreflViaEquiv; auto.\nQed.\n  \nEnd StrictTotalOrderViaEquiv.\n\nSection Operators.\n\nVariable A: Type.\nVariable R1 R2 eqA: relation A.\n\nLemma intersection_Reflexive: Reflexive R1 -> Reflexive R2 -> Reflexive (intersection R1 R2).\nProof.\n  intros ? ? x.\n  split; apply reflexivity.\nQed.\n\nLemma intersection_Symmetric: Symmetric R1 -> Symmetric R2 -> Symmetric (intersection R1 R2).\nProof.\n  intros ? ? x y [? ?].\n  split; apply symmetry; auto.\nQed.\n\nLemma intersection_Transitive: Transitive R1 -> Transitive R2 -> Transitive (intersection R1 R2).\nProof.\n  intros ? ? x y z [? ?] [? ?].\n  split; eapply transitivity; eauto.\nQed.\n\nLemma union_IrreflViaEquiv: IrreflViaEquiv R1 eqA -> IrreflViaEquiv R2 eqA -> IrreflViaEquiv (union R1 R2) eqA.\nProof.\n  intros ? ? x y ? [? | ?].\n  + exact (H x y H1 H2).\n  + exact (H0 x y H1 H2).\nQed.\n\nTheorem intersection_Equivalence: Equivalence R1 -> Equivalence R2 -> Equivalence (intersection R1 R2).\nProof.\n  intros.\n  constructor.\n  + apply intersection_Reflexive; apply Equivalence_Reflexive.\n  + apply intersection_Symmetric; apply Equivalence_Symmetric.\n  + apply intersection_Transitive; apply Equivalence_Transitive.\nQed.\n\nEnd Operators.\n\nSection BiKeyOrder.\n\nVariable A: Type.\nVariable R1 R2 eqA1 eqA2: relation A.\n\nDefinition BiKey := union R1 (intersection eqA1 R2).\n\nTheorem BiKey_StrictTotalOrderViaEquiv:\n  StrictTotalOrderViaEquiv R1 eqA1 ->\n  StrictTotalOrderViaEquiv R2 eqA2 ->\n  StrictTotalOrderViaEquiv BiKey (intersection eqA1 eqA2).\nProof.\n  intros; unfold BiKey.\n  inversion H.\n  inversion H0.\n  constructor.\n  + apply intersection_Equivalence; auto.\n  + intros x y; simpl.\n    specialize (StrictTotalOrderViaEquiv_IrreflViaEquiv0 x y).\n    specialize (StrictTotalOrderViaEquiv_IrreflViaEquiv1 x y).\n    tauto.\n  + intros x y z [? | [? ?]] [? | [? ?]]; simpl.\n    - left. eapply StrictTotalOrderViaEquiv_Transitive0; eauto.\n    - left. eapply StrictTotalOrderViaEquiv.RightProperViaEquiv with (eqA := eqA1); eauto.\n      symmetry; auto.\n    - left. eapply StrictTotalOrderViaEquiv.LeftProperViaEquiv with (eqA := eqA1); eauto.\n      symmetry; auto.\n    - right; split.\n      * eapply transitivity; eauto.\n      * eapply transitivity; eauto.\n  + intros x y; simpl.\n    pose proof StrictTotalOrderViaEquiv.disjointed_3cases _ R1 _ _ x y.\n    pose proof StrictTotalOrderViaEquiv.disjointed_3cases _ R2 _ _ x y.\n    pose proof @symmetry _ eqA1 _ x y.\n    pose proof @symmetry _ eqA1 _ y x.\n    tauto.\nQed.\n\nLemma BiKey_StrictTotalOrder:\n  StrictTotalOrderViaEquiv R1 eqA1 ->\n  StrictTotalOrder R2 ->\n  StrictTotalOrder BiKey.\nProof.\nAdmitted.\n\nSection enumerate.\n\nVariable venv: Var_env.\nVariable lt_var: Var -> Var -> Prop.\nHypothesis Wf: well_founded lt_var.\nHypothesis TO: TotalOrder lt_var.\n\nFixpoint level (e: Term) : nat :=\n  match e with\n  | andp e1 e2 => max (level e1) (level e2) + 1\n  | orp e1 e2 => max (level e1) (level e2) + 1\n  | impp e1 e2 => max (level e1) (level e2) + 1\n  | falsep => 0\n  | varp _ => 0\n  end.\n\nFixpoint trivial_lt (e1 e2: Term): Prop :=\n  match e1, e2 with\n  | falsep, falsep => False\n  | falsep, _ => True\n  | _, falsep => False\n  | varp v1, varp v2 => lt_var v1 v2\n  | varp _, _ => True\n  | _, varp _ => False\n  | andp e11 e12, andp e21 e22 => trivial_lt e11 e21 \\/ (e11 = e21 /\\ trivial_lt e12 e22)\n  | andp _ _, _ => True\n  | _, andp _ _ => False\n  | orp e11 e12, orp e21 e22 => trivial_lt e11 e21 \\/ (e11 = e21 /\\ trivial_lt e12 e22)\n  | orp _ _, _ => True\n  | _, orp _ _ => False\n  | impp e11 e12, impp e21 e22 => trivial_lt e11 e21 \\/ (e11 = e21 /\\ trivial_lt e12 e22)\n  end.\n\nDefinition lt_Term (e1 e2: Term): Prop :=\n  (level e1 < level e2) \\/ (level e1 = level e2 /\\ trivial_lt e1 e2).\n\n\n\nDefinition \n", "meta": {"author": "QinxiangCao", "repo": "UnifySL", "sha": "cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d", "save_path": "github-repos/coq/QinxiangCao-UnifySL", "path": "github-repos/coq/QinxiangCao-UnifySL/UnifySL-cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d/unused_files/enumerate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6799981246999834}}
{"text": "\n\n\nRequire Import ZArith.\nFrom QuickChick Require Import QuickChick.\nFrom ExtLib Require Import Monad.\nFrom ExtLib.Data.Monads Require Import OptionMonad.\nImport QcNotation.\nImport MonadNotation.\nFrom Coq Require Import List.\nImport ListNotations.\n\n\nFrom RBT Require Import Impl Spec.\n\nOpen Scope Z_scope.\n\nFixpoint genTree (lo hi : Z) (c : Color)  (f: nat) (h : nat) : G (option Tree) \n:=\nif lo >? hi then ret None else\nmatch f with\n| S f' =>\n  match h, c with\n  | O, R => ret (Some E)\n  | O, B => oneOf [ ret (Some E)\n                        ; k <- choose (lo, hi) ;;\n                          v <- arbitrary ;;\n                          ret (Some (T R E k v E))]\n  | S h', R =>\n      let margin := (2^(2*(Z.of_nat h) - 1) - 1) in\n      if (lo + margin >? hi - margin) then  ret None else\n      c' <- ret B ;;\n      k <- choose (lo + margin, hi - margin) ;;\n      v <- arbitrary ;;\n      l <- genTree lo (k - 1)  B f' h' ;;\n      r <- genTree (k + 1) hi  B f' h' ;;\n       match l, r with\n      | Some tl, Some tr => ret (Some (T c' tl k v tr))\n      | _, _ => ret None\n      end\n          \n  | S h', B =>\n      let margin := (2^(2*(Z.of_nat h)) - 1) in\n      if (lo + margin >? hi - margin) then ret None else\n      c' <- arbitrary ;;\n      k <- choose (lo + margin, hi - margin) ;;\n      v <- arbitrary ;;\n      let h'' := match c' with R => h | B => h' end in\n      l <- genTree lo (k - 1) c' f' h'' ;;\n      r <- genTree (k + 1) hi c' f' h'' ;;\n      match l, r with\n      | Some tl, Some tr => ret (Some (T c' tl k v tr))\n      | _, _ => ret None\n      end\n  end\n| _ => ret None\nend.\n\nAxiom fuel : nat. Extract Constant fuel => \"10000\".\n\nGlobal Instance genTreeSized : GenSized (option Tree) :=\n{| arbitrarySized x := \n    let y := Nat.min x 2 in\n      genTree 0 (2^(Z.of_nat(y)*2)) R fuel y |}.\n\n\nDefinition gSized := \n    x <- choose (0, 3)%nat;;\n    genTree 0 (2^(Z.of_nat(x)*2)) R fuel x\n.\n\n(* --------------------- Tests --------------------- *)\n\nDefinition test_prop_InsertValid :=  \n    forAllMaybe gSized (fun t =>    \n    forAll arbitrary (fun k =>\n    forAll arbitrary (fun v =>\n        (prop_InsertValid t k v)))).\n\n(*! QuickChick test_prop_InsertValid. *)\n\nDefinition test_prop_DeleteValid :=  \n    forAllMaybe gSized (fun t =>    \n    forAll arbitrary (fun k =>\n        prop_DeleteValid t k)).\n\n(*! QuickChick test_prop_DeleteValid. *)\n\nDefinition test_prop_InsertPost :=  \n    forAllMaybe gSized (fun t =>    \n    forAll arbitrary (fun k =>\n    forAll arbitrary (fun k' =>\n     forAll arbitrary (fun v =>\n        prop_InsertPost t k k' v)))).\n\n(*! QuickChick test_prop_InsertPost. *)\n\nDefinition test_prop_DeletePost := \n    forAllMaybe gSized (fun t =>    \n    forAll arbitrary (fun k =>\n    forAll arbitrary (fun k' =>\n        prop_DeletePost t k k'))).\n\n(*! QuickChick test_prop_DeletePost. *)\n    \nDefinition test_prop_InsertModel :=  \n    forAllMaybe gSized (fun t =>    \n    forAll arbitrary (fun k =>\n    forAll arbitrary (fun v =>\n        prop_InsertModel t k v))).\n\n(*! QuickChick test_prop_InsertModel. *)\n    \nDefinition test_prop_DeleteModel :=  \n    forAllMaybe gSized (fun t =>    \n    forAll arbitrary (fun k =>\n            prop_DeleteModel t k)).\n\n(*! QuickChick test_prop_DeleteModel. *)\n\nDefinition test_prop_InsertInsert :=  \n    forAllMaybe gSized (fun t =>    \n    forAll arbitrary (fun k =>\n    forAll arbitrary (fun k' =>\n    forAll arbitrary (fun v =>\n    forAll arbitrary (fun v' =>     \n        prop_InsertInsert t k k' v v'))))).\n\n(*! QuickChick test_prop_InsertInsert. *)\n    \nDefinition test_prop_InsertDelete := \n    forAllMaybe gSized (fun t =>    \n    forAll arbitrary (fun k =>\n    forAll arbitrary (fun k' =>\n    forAll arbitrary (fun v =>\n        prop_InsertDelete t k k' v)))).\n\n(*! QuickChick test_prop_InsertDelete. *)\n    \nDefinition test_prop_DeleteInsert := \n    forAllMaybe gSized (fun t =>    \n    forAll arbitrary (fun k =>\n    forAll arbitrary (fun k' =>\n    forAll arbitrary (fun v' =>\n        prop_DeleteInsert t k k' v')))).\n\n(*! QuickChick test_prop_DeleteInsert. *)\n    \nDefinition test_prop_DeleteDelete :=  \n    forAllMaybe gSized (fun t =>    \n    forAll arbitrary (fun k =>\n    forAll arbitrary (fun k' =>\n        prop_DeleteDelete t k k'))).\n\n(*! QuickChick test_prop_DeleteDelete. *)\n", "meta": {"author": "jwshi21", "repo": "etna", "sha": "master", "save_path": "github-repos/coq/jwshi21-etna", "path": "github-repos/coq/jwshi21-etna/etna-main/workloads/Coq/RBT/Strategies/BespokeGenerator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6799251242796743}}
{"text": "Require Import List.\nExport ListNotations.\nRequire Export ZArith.\nRequire Import Init.Datatypes.\n\nInductive IPE: Type :=\n | zero_pe    \n | one_pe.\n\nInductive PE : Type := \n | i_pe      : IPE -> PE\n | u_pe      : PE.\n\nDefinition P : Type := list PE.\n\nFunction beq_ipe (i i' : IPE) : bool := \n  match i, i' with\n    | zero_pe, zero_pe => true\n    | one_pe, one_pe => true\n    | _, _ => false\n  end.\n\nFunction beq_pe (p p' : PE) : bool :=\n  match p, p' with\n    | i_pe x, i_pe y => beq_ipe x y\n    | u_pe, u_pe => true\n    | _, _ => false\n  end.\n\nFunction beq_path (p q : P) : bool := \n  match p, q with\n    | [], [] => true\n    | x :: p', y :: q' => andb (beq_pe x y) (beq_path p' q')\n    | _  , _ => false\n  end.\n", "meta": {"author": "briangmilnes", "repo": "CycloneCoqSemantics", "sha": "190c0fc57d5aebfde244efb06a119f108de7a150", "save_path": "github-repos/coq/briangmilnes-CycloneCoqSemantics", "path": "github-repos/coq/briangmilnes-CycloneCoqSemantics/CycloneCoqSemantics-190c0fc57d5aebfde244efb06a119f108de7a150/3/modules/InversionExperiment2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6799251086979476}}
{"text": " Fixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\nintros n. destruct n.\n- reflexivity.\n- reflexivity.\nQed.", "meta": {"author": "Asap7772", "repo": "coq_softwarefoundations", "sha": "a7a58d9f82aed0966d8a2fcd2fc3be1d4b7b1f0d", "save_path": "github-repos/coq/Asap7772-coq_softwarefoundations", "path": "github-repos/coq/Asap7772-coq_softwarefoundations/coq_softwarefoundations-a7a58d9f82aed0966d8a2fcd2fc3be1d4b7b1f0d/chapter1/zeronbeqplus1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6798971403850755}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\nInductive natural : Type :=   Zero : natural | Succ : natural -> natural .\n\nInductive lst : Type :=  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   - lfind. Admitted.\n\n", "meta": {"author": "ana-brendel", "repo": "coq-benchmarks", "sha": "78b9ca2993b0fb579d814ed17e63c6859e79681c", "save_path": "github-repos/coq/ana-brendel-coq-benchmarks", "path": "github-repos/coq/ana-brendel-coq-benchmarks/coq-benchmarks-78b9ca2993b0fb579d814ed17e63c6859e79681c/testing_results_initial/manual_testing/results/test51_goal34/lfind_goal34.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6798971310067492}}
{"text": "Require Import Pointed.\nRequire Import WildCat HFiber.\nRequire Import Truncations.\nRequire Import Algebra.Groups.\nRequire Import Homotopy.HomotopyGroup.\n\nLocal Open Scope pointed_scope.\nLocal Open Scope nat_scope.\n\n(** 8.8.1 *)\nDefinition isequiv_issurj_tr0_isequiv_ap\n           `{Univalence} {A B : Type} (f : A -> B)\n           {i  : IsSurjection (Trunc_functor 0 f)}\n           {ii : forall x y, IsEquiv (@ap _ _ f x y)}\n  : IsEquiv f.\nProof.\n  apply (equiv_isequiv_ap_isembedding f)^-1 in ii.\n  srapply isequiv_surj_emb.\n  srapply BuildIsSurjection.\n  cbn; intro b.\n  pose proof (@center _ (i (tr b))) as p.\n  revert p.\n  apply Trunc_functor.\n  apply sig_ind.\n  srapply Trunc_ind.\n  intros a p.\n  apply (equiv_path_Tr _ _)^-1 in p.\n  strip_truncations.\n  exists a.\n  exact p.\nDefined.\n\n(** 8.8.2 *)\nDefinition isequiv_isbij_tr0_isequiv_loops\n           `{Univalence} {A B : Type} (f : A -> B)\n           {i  : IsEquiv (Trunc_functor 0 f)}\n           {ii : forall x, IsEquiv (fmap loops (pmap_from_point f x)) }\n  : IsEquiv f.\nProof.\n  srapply (isequiv_issurj_tr0_isequiv_ap f).\n  intros x y.\n  apply isequiv_inhab_codomain.\n  intro p.\n  apply (ap (@tr 0 _)) in p.\n  apply (@equiv_inj _ _ _ i (tr x) (tr y)) in p.\n  apply (equiv_path_Tr _ _)^-1 in p.\n  strip_truncations.\n  destruct p.\n  cbn in ii.\n  snrapply (isequiv_homotopic _ (H:=ii x)).\n  exact (fun _ => concat_1p _ @ concat_p1 _).\nDefined.\n\n(** When the types are 0-connected and the map is pointed, just one [loops_functor] needs to be checked. *)\nDefinition isequiv_is0connected_isequiv_loops\n           `{Univalence} {A B : pType} `{IsConnected 0 A} `{IsConnected 0 B}\n           (f : A ->* B)\n           (e : IsEquiv (fmap loops f))\n  : IsEquiv f.\nProof.\n  apply isequiv_isbij_tr0_isequiv_loops.\n  (** The pi_0 condition is trivial because [A] and [B] are 0-connected. *)\n  1: apply isequiv_contr_contr.\n  (** Since [A] is 0-connected, it's enough to check the [loops_functor] condition for the basepoint. *)\n  rapply conn_point_elim.\n  (** The [loops_functor] condition for [pmap_from_point f _] is equivalent to the [loops_functor] condition for [f] with its given pointing. *)\n  srapply isequiv_homotopic'.\n  - exact (equiv_concat_lr (point_eq f) (point_eq f)^ oE (Build_Equiv _ _ _ e)).\n  - intro r.\n    simpl.\n    hott_simpl.\nDefined.\n\n(** Truncated Whitehead's principle (8.8.3) *)\nDefinition whiteheads_principle\n           {ua : Univalence} {A B : Type} {f : A -> B}\n           (n : trunc_index) {H0 : IsTrunc n A} {H1 : IsTrunc n B}\n           {i  : IsEquiv (Trunc_functor 0 f)}\n           {ii : forall (x : A) (k : nat), IsEquiv (fmap (Pi k.+1) (pmap_from_point f x)) }\n  : IsEquiv f.\nProof.\n  revert A B H0 H1 f i ii.\n  induction n as [|n IHn].\n  1: intros; apply isequiv_contr_contr.\n  intros A B H0 H1 f i ii.\n  nrefine (@isequiv_isbij_tr0_isequiv_loops ua _ _ f i _).\n  intro x.\n  nrefine (isequiv_homotopic (@ap _ _ f x x) _).\n  2:{intros p; cbn.\n     symmetry; exact (concat_1p _ @ concat_p1 _). }\n  pose proof (@istrunc_paths _ _ H0 x x) as h0.\n  pose proof (@istrunc_paths _ _ H1 (f x) (f x)) as h1.\n  nrefine (IHn (x=x) (f x=f x) h0 h1 (@ap _ _ f x x) _ _).\n  - pose proof (ii x 0) as h2.\n    unfold is0functor_pi in h2; cbn in h2.\n    refine (@isequiv_homotopic _ _ _ _ h2 _).\n    apply (O_functor_homotopy (Tr 0)); intros p.\n    exact (concat_1p _ @ concat_p1 _).\n  - intros p k; revert p.\n    assert (h3 : forall (y:A) (q:x=y),\n               IsEquiv (fmap (Pi k.+1) (pmap_from_point (@ap _ _ f x y) q))).\n    2:exact (h3 x).\n    intros y q. destruct q.\n    snrefine (isequiv_homotopic _ _).\n    1: exact (fmap (Pi k.+1) (fmap loops (pmap_from_point f x))).\n    2:{ rapply (fmap2 (Pi k.+1)); srefine (Build_pHomotopy _ _).\n        - intros p; cbn.\n          refine (concat_1p _ @ concat_p1 _).\n        - reflexivity. }\n    nrefine (isequiv_commsq _ _ _ _ (fmap_pi_loops k.+1 (pmap_from_point f x))).\n    2-3:refine (equiv_isequiv (pi_loops _ _)).\n    exact (ii x k.+1).\nDefined.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Homotopy/WhiteheadsPrinciple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6798971310067492}}
{"text": "(* This file is distributed under the terms of the MIT License, also\n   known as the X11 Licence.  A copy of this license is in the README\n   file that accompanied the original distribution of this file.\n\n   Based on code written by:\n     Brian Aydemir *)\n\nRequire Import Coq.Arith.Peano_dec.\nRequire Import Coq.Lists.SetoidList.\nRequire Import Coq.omega.Omega.\n\nRequire Import Metalib.CoqUniquenessTac.\n\n\n(* *********************************************************************** *)\n(** * Examples *)\n\n(** The examples go through more smoothly if we declare [eq_nat_dec]\n    as a hint. *)\n\nHint Resolve eq_nat_dec : eq_dec.\n\n\n(* *********************************************************************** *)\n(** ** Predicates on natural numbers *)\n\nScheme le_ind' := Induction for le Sort Prop.\n\nLemma le_unique : forall (x y : nat) (p q: x <= y), p = q.\nProof.\n  induction p using le_ind';\n  uniqueness 1;\n  assert False by omega; intuition.\n\nQed.\n\n\n(* ********************************************************************** *)\n(** ** Predicates on lists *)\n\n(** Uniqueness of proofs for predicates on lists often comes up when\n    discussing extensional equality on finite sets, as implemented by\n    the FSets library. *)\n\nSection Uniqueness_Of_SetoidList_Proofs.\n\n  Variable A : Type.\n  Variable R : A -> A -> Prop.\n\n  Hypothesis R_unique : forall (x y : A) (p q : R x y), p = q.\n  Hypothesis list_eq_dec : forall (xs ys : list A), {xs = ys} + {xs <> ys}.\n\n  Scheme lelistA_ind' := Induction for lelistA Sort Prop.\n  Scheme sort_ind'    := Induction for sort Sort Prop.\n  Scheme eqlistA_ind' := Induction for eqlistA Sort Prop.\n\n  Theorem lelistA_unique :\n    forall (x : A) (xs : list A) (p q : lelistA R x xs), p = q.\n  Proof. induction p using lelistA_ind'; uniqueness 1. Qed.\n\n  Theorem sort_unique :\n    forall (xs : list A) (p q : sort R xs), p = q.\n  Proof. induction p using sort_ind'; uniqueness 1. apply lelistA_unique. Qed.\n\n  Theorem eqlistA_unique :\n    forall (xs ys : list A) (p q : eqlistA R xs ys), p = q.\n  Proof. induction p using eqlistA_ind'; uniqueness 2. Qed.\n\nEnd Uniqueness_Of_SetoidList_Proofs.\n\n\n(* *********************************************************************** *)\n(** ** Vectors *)\n\n(** [uniqueness] can show that the only vector of length zero is the\n    empty vector.  This shows that the tactic is not restricted to\n    working only on [Prop]s. *)\n\nInductive vector (A : Type) : nat -> Type :=\n  | vnil : vector A 0\n  | vcons : forall (n : nat) (a : A), vector A n -> vector A (S n).\n\nTheorem vector_O_eq : forall (A : Type) (v : vector A 0),\n  v = vnil _.\nProof. intros. uniqueness 1. Qed.\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/Metalib/CoqUniquenessTacEx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321936479701, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.6798690595168478}}
{"text": "Inductive tree : Set :=\n  | empty : tree\n  | node : tree -> tree -> tree. (* Constructor that takes to subtrees and returns a tree *)\n\nPrint tree_ind.\n\nFixpoint size t := (* Returns the size of a tree *)\n  match t with\n    | empty => 0\n    | node t1 t2 => S (plus(size t1)(size t2))\n  end.\n\nFixpoint swap t := (* Swaps nodes in a tree with their subtrees ?*)\n  match t with\n    | empty => empty\n    | node t1 t2 => node (swap t1) (swap t2)\n  end.\n\nTheorem swap_size: forall t, size t = size (swap t).\n\nProof. intros t. induction t.\n  - auto. (* Tactic that will prove base cases IDK why *)\n  - simpl. f_equal. (* got rid of the successors *) rewrite <- IHt1. rewrite <- IHt2. reflexivity.\nQed.", "meta": {"author": "dschneck", "repo": "coq-code", "sha": "3f8455c41488d95b7295b03b078d8499c6dc0034", "save_path": "github-repos/coq/dschneck-coq-code", "path": "github-repos/coq/dschneck-coq-code/coq-code-3f8455c41488d95b7295b03b078d8499c6dc0034/tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.6798690460897886}}
{"text": "Inductive 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\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\nInfix \"&&\" := andb.\nInfix \"||\" := orb.\n\nLemma lem_bool : forall b:bool, b = true \\/ b = false.\nProof.\n    destruct b.\n        - left. reflexivity.\n        - right. reflexivity.\nQed.\n\n\nLemma negb_involutive : forall b:bool,\n    negb (negb b) = b.\nProof.\n    intros b. destruct b.\n    - reflexivity.\n    - reflexivity.\nQed.\n\n\nLemma andb_comm : forall b c:bool,\n    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\nLemma orb_comm : forall b c: bool,\n    orb b c = orb c b.\nProof.\n    destruct b, c.    \n    - reflexivity.\n    - reflexivity.\n    - reflexivity.\n    - reflexivity.\nQed.\n\n\n\nLemma andb_true_iff : forall b c:bool,\n    b && c = true <-> b = true /\\ c = true.\nProof.\n    intros b c. split.\n    - intros H. split. \n        + destruct b eqn: H'.\n            { reflexivity. }\n            { inversion H. }\n        + destruct c eqn: H'.\n            { reflexivity. }\n            { rewrite andb_comm in H. inversion H. }\n    - intros [H1 H2]. rewrite H1, H2. reflexivity.\nQed.\n\n\nLemma orb_true_iff : forall b c:bool,\n    b || c = true <-> b = true \\/ c = true.\nProof.\n    intros b c. split.\n    - intros H. destruct b eqn: H'.\n        + left. reflexivity.\n        + right. exact H.\n    - intros [H|H].\n        + rewrite H. reflexivity.\n        + rewrite H. rewrite orb_comm. reflexivity.\nQed.\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/sf/bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503682, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6798690441206798}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (lf2 : natural) (lf1 : natural)\n  : natural := plus Zero (plus Zero lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj43_coqofml_gOHdrE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6798667110429784}}
{"text": "(****************************************************************************\n\n Pullbacks and equivalences\n\n Content:\n 1. Any two pullbacks are equivalent\n 2. Objects equivalent to pullbacks are pullbacks themselves\n\n ****************************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.Bicategories.Core.Bicat.\nImport Bicat.Notations.\nRequire Import UniMath.Bicategories.Core.Invertible_2cells.\nRequire Import UniMath.Bicategories.Core.Univalence.\nRequire Import UniMath.Bicategories.Core.AdjointUnique.\nRequire Import UniMath.Bicategories.Core.EquivToAdjequiv.\nRequire Import UniMath.Bicategories.Core.BicategoryLaws.\nRequire Import UniMath.Bicategories.Core.Unitors.\nRequire Import UniMath.Bicategories.Core.TransportLaws.\nRequire Import UniMath.Bicategories.Morphisms.Adjunctions.\nRequire Import UniMath.Bicategories.Morphisms.Properties.ClosedUnderInvertibles.\nRequire Import UniMath.Bicategories.Limits.Pullbacks.\n\nLocal Open Scope cat.\n\n(**\n 1. Any two pullbacks are equivalent\n *)\nSection UmpMorEquiv.\n  Context {B : bicat}\n          {b₁ b₂ b₃ : B}\n          {f : b₁ --> b₃}\n          {g : b₂ --> b₃}\n          (cone₁ cone₂ : pb_cone f g)\n          (H₁ : has_pb_ump cone₁)\n          (H₂ : has_pb_ump cone₂).\n\n  Definition pb_ump_mor_left_adjoint_equivalence_unit_pr1\n    : id₁ cone₂ · pb_cone_pr1 cone₂\n      ==>\n      pr1 (pr1 H₁ cone₂) · pb_ump_mor H₂ cone₁ · pb_cone_pr1 cone₂\n    := lunitor _\n       • (pb_ump_mor_pr1 H₁ cone₂)^-1\n       • (_ ◃ (pb_ump_mor_pr1 H₂ cone₁)^-1)\n       • lassociator _ _ _.\n\n  Definition pb_ump_mor_left_adjoint_equivalence_unit_pr2\n    : id₁ cone₂ · pb_cone_pr2 cone₂\n      ==>\n      pr1 (pr1 H₁ cone₂) · pb_ump_mor H₂ cone₁ · pb_cone_pr2 cone₂\n    := lunitor _\n       • (pb_ump_mor_pr2 H₁ cone₂)^-1\n       • (_ ◃ (pb_ump_mor_pr2 H₂ cone₁)^-1)\n       • lassociator _ _ _.\n\n  Definition pb_ump_mor_left_adjoint_equivalence_unit_cell\n    : (_ ◃ pb_cone_cell cone₂)\n      • lassociator _ _ _\n      • (pb_ump_mor_left_adjoint_equivalence_unit_pr2 ▹ _)\n      • rassociator _ _ _\n      =\n      lassociator _ _ _\n      • (pb_ump_mor_left_adjoint_equivalence_unit_pr1 ▹ _)\n      • rassociator _ _ _\n      • (_ ◃ pb_cone_cell cone₂).\n  Proof.\n    unfold pb_ump_mor_left_adjoint_equivalence_unit_pr1.\n    unfold pb_ump_mor_left_adjoint_equivalence_unit_pr2.\n    rewrite <- !rwhisker_vcomp.\n    rewrite !vassocl.\n    etrans.\n    {\n      apply maponpaths.\n      rewrite !vassocr.\n      rewrite lunitor_triangle.\n      apply idpath.\n    }\n    etrans.\n    {\n      rewrite !vassocr.\n      rewrite vcomp_lunitor.\n      rewrite !vassocl.\n      apply idpath.\n    }\n    refine (!_).\n    etrans.\n    {\n      rewrite !vassocr.\n      rewrite lunitor_triangle.\n      rewrite !vassocl.\n      apply idpath.\n    }\n    apply maponpaths.\n    use (vcomp_rcancel (rassociator _ _ _)) ; [ is_iso | ].\n    rewrite !vassocl.\n    rewrite <- lwhisker_lwhisker_rassociator.\n    rewrite <- rassociator_rassociator.\n    refine (!_).\n    etrans.\n    {\n      do 3 apply maponpaths.\n      rewrite !vassocr.\n      rewrite rwhisker_vcomp.\n      rewrite lassociator_rassociator.\n      rewrite id2_rwhisker.\n      rewrite id2_left.\n      apply idpath.\n    }\n    refine (!_).\n    etrans.\n    {\n      do 2 apply maponpaths.\n      etrans.\n      {\n        apply maponpaths.\n        rewrite !vassocr.\n        rewrite <- rassociator_rassociator.\n        apply idpath.\n      }\n      rewrite !vassocr.\n      rewrite rwhisker_vcomp.\n      rewrite lassociator_rassociator.\n      rewrite id2_rwhisker.\n      rewrite id2_left.\n      rewrite !vassocl.\n      apply idpath.\n    }\n    rewrite (pb_ump_mor_cell H₂).\n    rewrite <- !lwhisker_vcomp.\n    rewrite !vassocr.\n    apply maponpaths_2.\n    rewrite !vassocl.\n    etrans.\n    {\n      do 3 apply maponpaths.\n      rewrite !vassocr.\n      rewrite lwhisker_vcomp.\n      rewrite rassociator_lassociator.\n      rewrite lwhisker_id2.\n      rewrite id2_left.\n      rewrite !vassocl.\n      apply idpath.\n    }\n    etrans.\n    {\n      apply maponpaths.\n      rewrite !vassocr.\n      rewrite <- rwhisker_lwhisker_rassociator.\n      rewrite !vassocl.\n      apply maponpaths.\n      rewrite !vassocr.\n      rewrite lwhisker_vcomp, rwhisker_vcomp.\n      rewrite vcomp_linv.\n      rewrite id2_rwhisker, lwhisker_id2.\n      rewrite id2_left.\n      apply idpath.\n    }\n    etrans.\n    {\n      do 2 apply maponpaths.\n      apply maponpaths_2.\n      exact (pb_ump_mor_cell H₁ cone₂).\n    }\n    etrans.\n    {\n      apply maponpaths.\n      rewrite !vassocr.\n      rewrite rassociator_lassociator.\n      rewrite id2_left.\n      apply idpath.\n    }\n    etrans.\n    {\n      rewrite !vassocr.\n      rewrite rwhisker_vcomp.\n      rewrite vcomp_linv.\n      rewrite id2_rwhisker.\n      rewrite id2_left.\n      rewrite !vassocl.\n      apply idpath.\n    }\n    do 2 apply maponpaths.\n    rewrite rwhisker_lwhisker_rassociator.\n    apply idpath.\n  Qed.\n\n  Definition pb_ump_mor_left_adjoint_equivalence_unit\n    : id₁ cone₂\n      ==>\n      pr1 (pr1 H₁ cone₂) · pb_ump_mor H₂ cone₁.\n  Proof.\n    use (pb_ump_cell H₂) ; cbn.\n    - exact pb_ump_mor_left_adjoint_equivalence_unit_pr1.\n    - exact pb_ump_mor_left_adjoint_equivalence_unit_pr2.\n    - exact pb_ump_mor_left_adjoint_equivalence_unit_cell.\n  Defined.\n\n  Definition pb_ump_mor_left_adjoint_equivalence_unit_inv2cell\n    : is_invertible_2cell pb_ump_mor_left_adjoint_equivalence_unit.\n  Proof.\n    use is_invertible_2cell_pb_ump_cell.\n    - unfold pb_ump_mor_left_adjoint_equivalence_unit_pr1.\n      is_iso.\n    - unfold pb_ump_mor_left_adjoint_equivalence_unit_pr2.\n      is_iso.\n  Defined.\nEnd UmpMorEquiv.\n\nDefinition pb_ump_mor_left_adjoint_equivalence\n           {B : bicat}\n           {b₁ b₂ b₃ : B}\n           {f : b₁ --> b₃}\n           {g : b₂ --> b₃}\n           (cone₁ cone₂ : pb_cone f g)\n           (H₁ : has_pb_ump cone₁)\n           (H₂ : has_pb_ump cone₂)\n  : left_adjoint_equivalence (pb_ump_mor H₁ cone₂).\nProof.\n  use equiv_to_adjequiv.\n  simple refine ((_ ,, (_ ,, _)) ,, (_ ,, _)).\n  - exact (pb_ump_mor H₂ cone₁).\n  - exact (pb_ump_mor_left_adjoint_equivalence_unit cone₁ cone₂ H₁ H₂).\n  - exact ((pb_ump_mor_left_adjoint_equivalence_unit_inv2cell cone₂ cone₁ H₂  H₁)^-1).\n  - apply pb_ump_mor_left_adjoint_equivalence_unit_inv2cell.\n  - apply is_invertible_2cell_inv.\nDefined.\n\n(**\n 2. Objects equivalent to pullbacks are pullbacks themselves\n *)\nSection IdEquivalenceToPB.\n  Context {B : bicat}\n          {b₁ b₂ b₃ : B}\n          {f : b₁ --> b₃}\n          {g : b₂ --> b₃}\n          {q : B}\n          {qpr1 qpr1' : q --> b₁}\n          {qpr2 qpr2' : q --> b₂}\n          (qγ : invertible_2cell (qpr1 · f) (qpr2 · g))\n          (qγ' : invertible_2cell (qpr1' · f) (qpr2' · g))\n          (H₂ : has_pb_ump (make_pb_cone q qpr1' qpr2' qγ'))\n          (lpr1 : invertible_2cell qpr1 qpr1')\n          (lpr2 : invertible_2cell qpr2 qpr2')\n          (lc : qγ • (lpr2 ▹ g) = (lpr1 ▹ f) • qγ').\n\n  Definition id_left_adjoint_equivalence_to_pb_ump_1\n    : pb_ump_1 (make_pb_cone q qpr1 qpr2 qγ).\n  Proof.\n    intro qc.\n    use make_pb_1cell.\n    - exact (pb_ump_mor H₂ qc).\n    - exact (comp_of_invertible_2cell\n               (lwhisker_of_invertible_2cell _ lpr1)\n               (pb_ump_mor_pr1 H₂ qc)).\n    - exact (comp_of_invertible_2cell\n               (lwhisker_of_invertible_2cell _ lpr2)\n               (pb_ump_mor_pr2 H₂ qc)).\n    - abstract\n        (cbn ;\n         use (vcomp_rcancel (_ ◃ (lpr2 ▹ g))) ;\n         [ is_iso ; apply property_from_invertible_2cell | ] ;\n         rewrite lwhisker_vcomp ;\n         rewrite lc ;\n         rewrite <- lwhisker_vcomp ;\n         refine (maponpaths (λ z, _ • z) (pb_ump_mor_cell H₂ qc) @ _) ;\n         cbn ;\n         rewrite !vassocr ;\n         rewrite rwhisker_lwhisker ;\n         rewrite !vassocl ;\n         apply maponpaths ;\n         rewrite <- rwhisker_vcomp ;\n         rewrite !vassocl ;\n         do 3 apply maponpaths ;\n         rewrite rwhisker_lwhisker_rassociator ;\n         rewrite !vassocr ;\n         apply maponpaths_2 ;\n         rewrite rwhisker_vcomp ;\n         rewrite !vassocl ;\n         rewrite lwhisker_vcomp ;\n         rewrite vcomp_linv ;\n         rewrite lwhisker_id2 ;\n         rewrite id2_right ;\n         apply idpath).\n  Defined.\n\n  Section UMP2.\n    Context {qc : B}\n            {φ ψ : qc --> q}\n            (α : φ · qpr1 ==> ψ · qpr1)\n            (β : φ · qpr2 ==> ψ · qpr2)\n            (p : (φ ◃ qγ) • lassociator _ _ _ • (β ▹ g) • rassociator _ _ _\n                 =\n                 lassociator _ _ _ • (α ▹ f) • rassociator _ _ _ • (ψ ◃ qγ)).\n\n    Lemma id_left_adjoint_equivalence_to_pb_ump_2_cell_eq\n      : (φ ◃ qγ')\n          • lassociator _ _ _\n          • (((φ ◃ lpr2 ^-1) • β • (ψ ◃ lpr2)) ▹ g)\n          • rassociator _ _ _\n        =\n        lassociator _ _ _\n        • (((φ ◃ lpr1 ^-1) • α • (ψ ◃ lpr1)) ▹ f)\n        • rassociator ψ qpr1' f\n        • (ψ ◃ qγ').\n    Proof.\n      rewrite <- !rwhisker_vcomp.\n      rewrite !vassocl.\n      refine (!_).\n      etrans.\n      {\n        rewrite !vassocr.\n        rewrite <- rwhisker_lwhisker.\n        rewrite !vassocl.\n        apply idpath.\n      }\n      use vcomp_move_R_pM ; [ is_iso | ] ; cbn.\n      refine (!_).\n      rewrite !vassocr.\n      rewrite lwhisker_vcomp.\n      rewrite <- lc.\n      rewrite <- lwhisker_vcomp.\n      rewrite !vassocl.\n      etrans.\n      {\n        apply maponpaths.\n        rewrite !vassocr.\n        rewrite rwhisker_lwhisker.\n        rewrite !vassocl.\n        apply maponpaths.\n        rewrite !vassocr.\n        rewrite rwhisker_vcomp.\n        rewrite lwhisker_vcomp.\n        rewrite vcomp_rinv.\n        rewrite lwhisker_id2.\n        rewrite id2_rwhisker.\n        rewrite id2_left.\n        rewrite !vassocl.\n        rewrite <- rwhisker_lwhisker_rassociator.\n        apply idpath.\n      }\n      rewrite !vassocr.\n      rewrite p.\n      rewrite !vassocl.\n      do 2 apply maponpaths.\n      rewrite lwhisker_vcomp.\n      rewrite lc.\n      rewrite <- lwhisker_vcomp.\n      rewrite !vassocr.\n      apply maponpaths_2.\n      rewrite rwhisker_lwhisker_rassociator.\n      apply idpath.\n    Qed.\n\n    Definition id_left_adjoint_equivalence_to_pb_ump_2_cell\n      : φ ==> ψ.\n    Proof.\n      use (pb_ump_cell H₂).\n      - exact ((_ ◃ lpr1^-1) • α • (_ ◃ lpr1)).\n      - exact ((_ ◃ lpr2^-1) • β • (_ ◃ lpr2)).\n      - exact id_left_adjoint_equivalence_to_pb_ump_2_cell_eq.\n    Defined.\n\n    Definition id_left_adjoint_equivalence_to_pb_ump_2_cell_pr1\n      : id_left_adjoint_equivalence_to_pb_ump_2_cell ▹ qpr1\n        =\n        α.\n    Proof.\n      unfold id_left_adjoint_equivalence_to_pb_ump_2_cell.\n      use (vcomp_lcancel (φ ◃ lpr1 ^-1)).\n      {\n        is_iso.\n      }\n      use (vcomp_rcancel (ψ ◃ lpr1)).\n      {\n        is_iso.\n        apply property_from_invertible_2cell.\n      }\n      rewrite <- vcomp_whisker.\n      etrans.\n      {\n        do 2 apply maponpaths_2.\n        apply (pb_ump_cell_pr1 H₂).\n      }\n      rewrite !vassocl.\n      rewrite lwhisker_vcomp.\n      rewrite vcomp_linv.\n      rewrite lwhisker_id2.\n      rewrite id2_right.\n      apply idpath.\n    Qed.\n\n    Definition id_left_adjoint_equivalence_to_pb_ump_2_cell_pr2\n      : id_left_adjoint_equivalence_to_pb_ump_2_cell ▹ qpr2\n        =\n        β.\n    Proof.\n      unfold id_left_adjoint_equivalence_to_pb_ump_2_cell.\n      use (vcomp_lcancel (φ ◃ lpr2 ^-1)).\n      {\n        is_iso.\n      }\n      use (vcomp_rcancel (ψ ◃ lpr2)).\n      {\n        is_iso.\n        apply property_from_invertible_2cell.\n      }\n      rewrite <- vcomp_whisker.\n      etrans.\n      {\n        do 2 apply maponpaths_2.\n        apply (pb_ump_cell_pr2 H₂).\n      }\n      rewrite !vassocl.\n      rewrite lwhisker_vcomp.\n      rewrite vcomp_linv.\n      rewrite lwhisker_id2.\n      rewrite id2_right.\n      apply idpath.\n    Qed.\n\n    Definition id_left_adjoint_equivalence_to_pb_ump_2_unique\n      : isaprop (∑ (γ : φ ==> ψ), γ ▹ qpr1 = α × γ ▹ qpr2 = β).\n    Proof.\n      use invproofirrelevance.\n      intros ζ₁ ζ₂.\n      use subtypePath.\n      {\n        intro.\n        apply isapropdirprod ; apply cellset_property.\n      }\n      use (pb_ump_eq H₂) ; cbn.\n      - exact ((_ ◃ lpr1^-1) • α • (_ ◃ lpr1)).\n      - exact ((_ ◃ lpr2^-1) • β • (_ ◃ lpr2)).\n      - exact id_left_adjoint_equivalence_to_pb_ump_2_cell_eq.\n      - rewrite !vassocl.\n        use vcomp_move_L_pM ; [ is_iso | ].\n        cbn.\n        rewrite <- vcomp_whisker.\n        apply maponpaths_2.\n        exact (pr12 ζ₁).\n      - rewrite !vassocl.\n        use vcomp_move_L_pM ; [ is_iso | ].\n        cbn.\n        rewrite <- vcomp_whisker.\n        apply maponpaths_2.\n        exact (pr22 ζ₁).\n      - rewrite !vassocl.\n        use vcomp_move_L_pM ; [ is_iso | ].\n        cbn.\n        rewrite <- vcomp_whisker.\n        apply maponpaths_2.\n        exact (pr12 ζ₂).\n      - rewrite !vassocl.\n        use vcomp_move_L_pM ; [ is_iso | ].\n        cbn.\n        rewrite <- vcomp_whisker.\n        apply maponpaths_2.\n        exact (pr22 ζ₂).\n    Qed.\n  End UMP2.\n\n  Definition id_left_adjoint_equivalence_to_pb_ump_2\n    : pb_ump_2 (make_pb_cone q qpr1 qpr2 qγ).\n  Proof.\n    intros qc φ ψ α β p.\n    use iscontraprop1.\n    - exact (id_left_adjoint_equivalence_to_pb_ump_2_unique _ _ p).\n    - simple refine (_ ,, _ ,, _).\n      + exact (id_left_adjoint_equivalence_to_pb_ump_2_cell _ _ p).\n      + exact (id_left_adjoint_equivalence_to_pb_ump_2_cell_pr1 _ _ p).\n      + exact (id_left_adjoint_equivalence_to_pb_ump_2_cell_pr2 _ _ p).\n  Defined.\n\n  Definition id_left_adjoint_equivalence_to_pb\n    : has_pb_ump (make_pb_cone q qpr1 qpr2 qγ).\n  Proof.\n    split.\n    - exact id_left_adjoint_equivalence_to_pb_ump_1.\n    - exact id_left_adjoint_equivalence_to_pb_ump_2.\n  Defined.\nEnd IdEquivalenceToPB.\n\nDefinition left_adjoint_equivalence_eq_to_pb\n           {B : bicat}\n           {b₁ b₂ b₃ : B}\n           {f : b₁ --> b₃}\n           {g : b₂ --> b₃}\n           (cone₁ cone₂ : pb_cone f g)\n           (H₂ : has_pb_ump cone₂)\n           (p : pr1 cone₁ = pr1 cone₂)\n           (qp1 : invertible_2cell\n                    (idtoiso_2_0 _ _ (!p) · pb_cone_pr1 cone₁)\n                    (pb_cone_pr1 cone₂))\n           (qp2 : invertible_2cell\n                    (idtoiso_2_0 _ _ (!p) · pb_cone_pr2 cone₁)\n                    (pb_cone_pr2 cone₂))\n           (path : (qp1^-1 ▹ f)\n                   • rassociator _ _ _\n                   • (_ ◃ pb_cone_cell cone₁)\n                   • lassociator _ _ _\n                   • (qp2 ▹ g)\n                   =\n                   pr1 (pb_cone_cell cone₂))\n  : has_pb_ump cone₁.\nProof.\n  induction cone₁ as [ q cone ].\n  induction cone as [ qp₁ cone ].\n  induction cone as [ qp₂ γ ].\n  induction cone₂ as [ q' cone ].\n  induction cone as [ qp₁' cone ].\n  induction cone as [ qp₂' γ' ].\n  cbn in *.\n  induction p ; cbn in *.\n  use (id_left_adjoint_equivalence_to_pb _ _ H₂).\n  - exact (comp_of_invertible_2cell (linvunitor_invertible_2cell _) qp1).\n  - exact (comp_of_invertible_2cell (linvunitor_invertible_2cell _) qp2).\n  - abstract\n      (cbn ;\n       use vcomp_move_L_pM ; [ is_iso ; apply property_from_invertible_2cell | ] ; cbn ;\n       refine (_ @ path) ;\n       rewrite <- !rwhisker_vcomp ;\n       rewrite !vassocl ;\n       apply maponpaths ;\n       rewrite !vassocr ;\n       apply maponpaths_2 ;\n       use vcomp_move_R_Mp ; [ is_iso | ] ; cbn ;\n       rewrite !vassocl ;\n       rewrite lunitor_triangle ;\n       rewrite vcomp_lunitor ;\n       rewrite !vassocr ;\n       apply maponpaths_2 ;\n       rewrite <- lunitor_triangle ;\n       rewrite !vassocr ;\n       rewrite rassociator_lassociator ;\n       rewrite id2_left ;\n       apply idpath).\nDefined.\n\nSection EquivalenceToPBHelp.\n  Context {B : bicat}\n          (HB_2_0 : is_univalent_2_0 B)\n          {b₁ b₂ b₃ : B}\n          {f : b₁ --> b₃}\n          {g : b₂ --> b₃}\n          (cone₁ cone₂ : pb_cone f g)\n          (H₂ : has_pb_ump cone₂)\n          (l : cone₁ --> cone₂)\n          (Hl : left_adjoint_equivalence l)\n          (r := left_adjoint_right_adjoint Hl)\n          (rpr1 : invertible_2cell\n                    (r · pb_cone_pr1 cone₁)\n                    (pb_cone_pr1 cone₂))\n          (rpr2 : invertible_2cell\n                    (r · pb_cone_pr2 cone₁)\n                    (pb_cone_pr2 cone₂))\n          (path : (r ◃ pb_cone_cell cone₁) • lassociator _ _ _ • (rpr2 ▹ g)\n                  =\n                  lassociator _ _ _ • (rpr1 ▹ f) • pr1 (pb_cone_cell cone₂)).\n\n  Local Definition help_inv2cell\n    : invertible_2cell\n        (idtoiso_2_0 _ _ (! isotoid_2_0 HB_2_0 (l,, Hl)))\n        r.\n  Proof.\n    apply idtoiso_2_1.\n    cbn.\n    rewrite idtoiso_2_0_inv.\n    rewrite idtoiso_2_0_isotoid_2_0.\n    apply idpath.\n  Qed.\n\n  Definition left_adjoint_equivalence_to_pb_help_pr1\n    : invertible_2cell\n        (idtoiso_2_0 _ _ (! isotoid_2_0 HB_2_0 (l,, Hl))\n         ·\n         pb_cone_pr1 cone₁)\n        (pb_cone_pr1 cone₂)\n    := comp_of_invertible_2cell\n         (rwhisker_of_invertible_2cell\n            _\n            help_inv2cell)\n         rpr1.\n\n  Definition left_adjoint_equivalence_to_pb_help_pr2\n    : invertible_2cell\n        (idtoiso_2_0 _ _ (! isotoid_2_0 HB_2_0 (l,, Hl))\n         ·\n         pb_cone_pr2 cone₁)\n        (pb_cone_pr2 cone₂)\n    := comp_of_invertible_2cell\n         (rwhisker_of_invertible_2cell\n            _\n            help_inv2cell)\n         rpr2.\n\n  Definition left_adjoint_equivalence_to_pb_help_path\n    : (left_adjoint_equivalence_to_pb_help_pr1^-1 ▹ f)\n      • rassociator _ _ _\n      • (_ ◃ pb_cone_cell cone₁)\n      • lassociator _ _ _\n      • (left_adjoint_equivalence_to_pb_help_pr2 ▹ g)\n      =\n      pr1 (pb_cone_cell cone₂).\n  Proof.\n    cbn.\n    rewrite !vassocl.\n    use vcomp_move_R_pM ; [ is_iso | ].\n    cbn.\n    rewrite <- !rwhisker_vcomp.\n    rewrite !vassocl.\n    etrans.\n    {\n      do 2 apply maponpaths.\n      rewrite !vassocr.\n      rewrite rwhisker_rwhisker.\n      rewrite !vassocl.\n      apply idpath.\n    }\n    etrans.\n    {\n      apply maponpaths.\n      rewrite !vassocr.\n      rewrite <- vcomp_whisker.\n      rewrite !vassocl.\n      apply idpath.\n    }\n    rewrite !vassocr.\n    rewrite <- rwhisker_rwhisker_alt.\n    rewrite !vassocl.\n    apply maponpaths.\n    use vcomp_move_R_pM ; [ is_iso | ].\n    rewrite !vassocr.\n    exact path.\n  Qed.\n\n  Definition left_adjoint_equivalence_to_pb_help\n    : has_pb_ump cone₁.\n  Proof.\n    use (left_adjoint_equivalence_eq_to_pb _ _ H₂).\n    - exact (isotoid_2_0 HB_2_0 (l ,, Hl)).\n    - exact left_adjoint_equivalence_to_pb_help_pr1.\n    - exact left_adjoint_equivalence_to_pb_help_pr2.\n    - exact left_adjoint_equivalence_to_pb_help_path.\n  Defined.\nEnd EquivalenceToPBHelp.\n\nSection LeftAdjointEquivalenceToPB.\n  Context {B : bicat}\n          (HB_2_0 : is_univalent_2_0 B)\n          {b₁ b₂ b₃ : B}\n          {f : b₁ --> b₃}\n          {g : b₂ --> b₃}\n          (cone₁ cone₂ : pb_cone f g)\n          (H₂ : has_pb_ump cone₂)\n          (l : cone₁ --> cone₂)\n          (Hl : left_adjoint_equivalence l)\n          (lpr1 : invertible_2cell\n                    (l · pb_cone_pr1 cone₂)\n                    (pb_cone_pr1 cone₁))\n          (lpr2 : invertible_2cell\n                    (l · pb_cone_pr2 cone₂)\n                    (pb_cone_pr2 cone₁))\n          (path : (_ ◃ pb_cone_cell cone₂) • lassociator _ _ _ • (lpr2 ▹ g)\n                  =\n                  lassociator _ _ _ • (lpr1 ▹ f) • pb_cone_cell cone₁).\n\n  Let r : cone₂ --> cone₁\n    := left_adjoint_right_adjoint Hl.\n  Let η : invertible_2cell (id₁ _) (l · r)\n    := left_equivalence_unit_iso Hl.\n  Let ε : invertible_2cell (r · l) (id₁ _)\n    := left_equivalence_counit_iso Hl.\n\n  Definition left_adjoint_equivalence_to_pb_pr1\n    : invertible_2cell\n        (r · pb_cone_pr1 cone₁)\n        (pb_cone_pr1 cone₂)\n    := comp_of_invertible_2cell\n         (lwhisker_of_invertible_2cell\n            _\n            (inv_of_invertible_2cell lpr1))\n         (comp_of_invertible_2cell\n            (lassociator_invertible_2cell _ _ _)\n            (comp_of_invertible_2cell\n               (rwhisker_of_invertible_2cell _ ε)\n               (lunitor_invertible_2cell _))).\n\n  Definition left_adjoint_equivalence_to_pb_pr2\n    : invertible_2cell\n        (r · pb_cone_pr2 cone₁)\n        (pb_cone_pr2 cone₂)\n    := comp_of_invertible_2cell\n         (lwhisker_of_invertible_2cell\n            _\n            (inv_of_invertible_2cell lpr2))\n         (comp_of_invertible_2cell\n            (lassociator_invertible_2cell _ _ _)\n            (comp_of_invertible_2cell\n               (rwhisker_of_invertible_2cell _ ε)\n               (lunitor_invertible_2cell _))).\n\n  Definition left_adjoint_equivalence_to_pb_eq\n    : (r ◃ pb_cone_cell cone₁)\n      • lassociator _ _ _\n      • (left_adjoint_equivalence_to_pb_pr2 ▹ g)\n      =\n      lassociator _ _ _\n      • (left_adjoint_equivalence_to_pb_pr1 ▹ f)\n      • pr1 (pb_cone_cell cone₂).\n  Proof.\n    cbn.\n    rewrite <- !rwhisker_vcomp.\n    rewrite !vassocl.\n    refine (!_).\n    etrans.\n    {\n      rewrite !vassocr.\n      rewrite <- rwhisker_lwhisker.\n      rewrite !vassocl.\n      apply idpath.\n    }\n    use vcomp_move_R_pM ; [ is_iso | ] ; cbn.\n    use (vcomp_lcancel (r ◃ lassociator _ _ _)) ; [ is_iso | ].\n    rewrite !vassocr.\n    rewrite lassociator_lassociator.\n    rewrite !lwhisker_vcomp.\n    rewrite <- path.\n    rewrite <- !lwhisker_vcomp.\n    rewrite !vassocl.\n    refine (!_).\n    etrans.\n    {\n      do 3 apply maponpaths.\n      rewrite !vassocr.\n      rewrite <- rwhisker_lwhisker.\n      apply idpath.\n    }\n    etrans.\n    {\n      apply maponpaths.\n      etrans.\n      {\n        apply maponpaths.\n        rewrite !vassocr.\n        rewrite lwhisker_vcomp.\n        rewrite rwhisker_vcomp.\n        rewrite vcomp_rinv.\n        rewrite id2_rwhisker.\n        rewrite lwhisker_id2.\n        rewrite id2_left.\n        apply idpath.\n      }\n      rewrite !vassocr.\n      rewrite lassociator_lassociator.\n      rewrite !vassocl.\n      apply maponpaths.\n      rewrite !vassocr.\n      rewrite rwhisker_rwhisker.\n      rewrite !vassocl.\n      apply idpath.\n    }\n    rewrite !vassocr.\n    rewrite lwhisker_lwhisker.\n    rewrite !vassocl.\n    apply maponpaths.\n    rewrite !vassocr.\n    rewrite <- vcomp_whisker.\n    rewrite rwhisker_rwhisker.\n    rewrite !vassocl.\n    apply maponpaths.\n    rewrite lunitor_triangle.\n    rewrite vcomp_lunitor.\n    rewrite !vassocr.\n    rewrite lunitor_triangle.\n    apply idpath.\n  Qed.\n\n  Definition left_adjoint_equivalence_to_pb\n    : has_pb_ump cone₁.\n  Proof.\n    use (left_adjoint_equivalence_to_pb_help HB_2_0 _ _ H₂ l Hl).\n    - exact left_adjoint_equivalence_to_pb_pr1.\n    - exact left_adjoint_equivalence_to_pb_pr2.\n    - exact left_adjoint_equivalence_to_pb_eq.\n  Defined.\nEnd LeftAdjointEquivalenceToPB.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/Bicategories/Limits/PullbackEquivalences.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6798667094986305}}
{"text": "Require Import Decidable.\n\n(* Entscheidbarkeit auf Typenlevel*)\nDefinition decT (T : Type) : Type := T + ( T -> False).\n\nDefinition eq_dec (T : Type) : Type := forall (x y :T), decidable (x = y).\nEval compute in ( eq_dec nat).\n", "meta": {"author": "margrit", "repo": "Code", "sha": "b3e89580b33732c23cdf4df8171d6c76ce9186e7", "save_path": "github-repos/coq/margrit-Code", "path": "github-repos/coq/margrit-Code/Code-b3e89580b33732c23cdf4df8171d6c76ce9186e7/Code/General.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6798667043549984}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := nil : Lst | cons : Nat -> Lst -> Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint mem (mem_arg0 : Nat) (mem_arg1 : Lst) : Prop\n:= match mem_arg0, mem_arg1 with\n    | x, nil => False\n    | x, cons y z => x = y \\/ mem x z\n    end.\n\nTheorem theorem0 : forall (x : Nat) (y : Lst) (z : Lst), mem x z -> mem x (append y z).\nProof.\n  intros.\n  induction y.\n  - auto.\n  - simpl. auto.\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal37.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6798666971564308}}
{"text": "Require Import Arith Omega.\nRequire Import Word.\nRequire Import WordAuto.\nRequire Import Psatz.\n\n(* TODO: move byte-specific lemmas *)\nRequire Import AsyncDisk.\nImport Valulen.\n\n(** The divup and roundup functions and associated theorems.\n    divup n sz performs n / sz, rounding up rather than down.\n    roundup n sz rounds n to the smallest multiple of sz >= n;\n     it is similar to the customary n / sz * sz, but uses divup instead of /.\n*)\n\nDefinition divup (n unitsz : nat) : nat := (n + unitsz - 1) / unitsz.\nDefinition roundup (n unitsz:nat) : nat := (divup n unitsz) * unitsz.\n\n  Lemma div_le_mul : forall n a b,\n    b > 0 -> a > 0 -> n / a <= n * b.\n  Proof.\n    intros.\n    destruct n.\n    destruct a; cbv; auto.\n    destruct a; try omega.\n    eapply le_trans.\n    apply div_le; auto.\n    rewrite Nat.mul_comm.\n    destruct (mult_O_le (S n) b); auto; omega.\n  Qed.\n\n  Lemma mul_div : forall a b,\n    a mod b = 0 ->\n    b > 0 ->\n    a / b * b = a.\n  Proof.\n    intros.\n    erewrite Nat.div_mod with (x := a) (y := b) by omega.\n    rewrite H, Nat.add_0_r.\n    setoid_rewrite Nat.mul_comm at 2.\n    rewrite Nat.div_mul by omega.\n    setoid_rewrite Nat.mul_comm at 2; auto.\n  Qed.\n\n  Lemma mod_le_r : forall a b, a mod b <= b.\n  Proof.\n    intros. case_eq b; intros. auto.\n    apply Nat.lt_le_incl, Nat.mod_upper_bound. omega.\n  Qed.\n\n  Lemma lt_add_lt_sub : forall a b c,\n    b <= a -> a < b + c -> a - b < c.\n  Proof.\n    intros; omega.\n  Qed.\n\n  Lemma lt_div_mul_add_le : forall a b c,\n    b > 0 -> a < c / b -> b + a * b <= c.\n  Proof.\n    intros.\n    apply lt_le_S in H0.\n    apply mult_le_compat_r with ( p := b ) in H0; auto.\n    rewrite Nat.add_comm, <- Nat.mul_succ_l.\n    eapply le_trans; eauto.\n    rewrite Nat.mul_comm.\n    apply Nat.mul_div_le; omega.\n  Qed.\n\n  Lemma lt_div_mul_lt : forall a b c,\n    b > 0 -> a < c / b -> a * b < c.\n  Proof.\n    intros.\n    apply lt_div_mul_add_le in H0; auto; omega.\n  Qed.\n\n  Lemma div_lt_mul_lt : forall a b c,\n    b > 0 -> a / b < c -> a < c * b.\n  Proof.\n    intros.\n    apply lt_le_S in H0.\n    apply mult_le_compat_r with ( p := b ) in H0; auto.\n    eapply lt_le_trans; [ | eauto ].\n    rewrite Nat.mul_comm.\n    apply Nat.mul_succ_div_gt; omega.\n  Qed.\n\n  Lemma sub_round_eq_mod : forall a b, b <> 0 -> a - a / b * b = a mod b.\n  Proof.\n    intros.\n    rewrite Nat.mod_eq, mult_comm; auto.\n  Qed.\n\n  Lemma mult_neq_0 : forall m n, m <> 0 -> n <> 0 -> m * n <> 0.\n  Proof.\n    intros. intuition.\n  Qed.\n\n  Lemma mul_ge_l : forall m n,\n    0 < m -> n <= n * m.\n  Proof.\n    intros.\n    rewrite mult_comm.\n    destruct (mult_O_le n m); solve [ omega | auto].\n  Qed.\n\n  Lemma mul_ge_r : forall m n,\n    0 < m -> n <= m * n.\n  Proof.\n    intros. rewrite mult_comm. apply mul_ge_l; auto.\n  Qed.\n\n  Lemma div_mul_le : forall a b : addr, a / b * b <= a.\n  Proof.\n    intros.\n    destruct (Nat.eq_dec b 0) as [H|H]; subst; try omega.\n    pose proof Nat.div_mod a b H.\n    rewrite mult_comm; omega.\n  Qed.\n\n  Lemma sub_sub_assoc : forall a b,\n    a >= b -> a - (a - b) = b.\n  Proof.\n    intros; omega.\n  Qed.\n\n  Lemma sub_mod_eq_round : forall a b, b <> 0 -> a - (a mod b) = a / b * b.\n  Proof.\n    intros.\n    rewrite <- sub_round_eq_mod at 1 by auto.\n    rewrite sub_sub_assoc; auto.\n    apply div_mul_le.\n  Qed.\n\n  Lemma roundup_ge: forall x sz,\n      sz > 0 ->\n      roundup x sz >= x.\n  Proof.\n    unfold roundup, divup; intros.\n    rewrite (Nat.div_mod x sz) at 1 by omega.\n    rewrite <- Nat.add_sub_assoc by omega.\n    rewrite <- plus_assoc.\n    rewrite (mult_comm sz).\n    rewrite Nat.div_add_l by omega.\n\n    case_eq (x mod sz); intros.\n    - rewrite (Nat.div_mod x sz) at 2 by omega.\n       nia.\n\n    - rewrite Nat.mul_add_distr_r.\n      replace (S n + (sz - 1)) with (sz + n) by omega.\n      replace (sz) with (1 * sz) at 3 by omega.\n      rewrite Nat.div_add_l by omega.\n      rewrite (Nat.div_mod x sz) at 2 by omega.\n      assert (x mod sz < sz).\n      apply Nat.mod_bound_pos; omega.\n      nia.\n  Qed.\n\n  Lemma roundup_ge_divisor : forall x sz, 0 < x -> roundup x sz >= sz.\n  Proof.\n    unfold roundup; intros.\n    case_eq sz; intros; subst; auto.\n    unfold ge.\n    rewrite <- mult_1_l at 1.\n    apply mult_le_compat; auto.\n    unfold divup.\n    apply Nat.div_str_pos; omega.\n  Qed.\n\n  Lemma divup_ok:\n    forall x,\n      divup x valubytes * valubytes >= x.\n  Proof.\n    intros.\n    apply roundup_ge.\n    rewrite valubytes_is; omega.\n  Qed.\n\n  Lemma divup_0:\n    forall x,\n    divup 0 x = 0.\n  Proof.\n    intros.\n    case_eq x; intros.\n    reflexivity.\n    apply Nat.div_small.\n    omega.\n  Qed.\n\n  Lemma roundup_0:\n    forall x,\n    roundup 0 x = 0.\n  Proof.\n    unfold roundup; intros.\n    rewrite divup_0. auto.\n  Qed.\n\n  Lemma divup_1: forall x,\n    divup x 1 = x.\n  Proof.\n    simpl; intros.\n    replace (x + 1 - 1) with x by omega.\n    pose proof (Nat.divmod_spec x 0 0 0 (Nat.le_refl 0)).\n    destruct (Nat.divmod x 0 0 0); simpl.\n    omega.\n  Qed.\n\n  Lemma divup_divup_eq:\n    forall x,\n      (divup ((divup x valubytes)*valubytes) valubytes) * valubytes =\n      (divup x valubytes) * valubytes.\n  Proof.\n    unfold divup; intros.\n    rewrite <- Nat.add_sub_assoc by ( rewrite valubytes_is; omega ).\n    rewrite Nat.div_add_l by ( rewrite valubytes_is; omega ).\n    rewrite Nat.mul_add_distr_r.\n    replace ((valubytes - 1) / valubytes * valubytes) with 0. omega.\n    rewrite valubytes_is.\n    compute.\n    auto.\n  Qed.\n\n  Lemma divup_lt_arg: forall x sz,\n    divup x sz <= x.\n  Proof.\n    intros.\n    case_eq sz; intros.\n    (* sz = 0 *)\n    simpl. omega.\n    case_eq x; intros.\n    (* x = 0 *)\n    rewrite divup_0; constructor.\n    unfold divup.\n    (* sz > 0, x > 0 *)\n    rewrite Nat.div_mod with (y := S n) by omega.\n    rewrite <- H.\n    rewrite <- H0.\n    apply le_trans with (sz * x / sz).\n    apply Nat.div_le_mono.\n    omega.\n    replace (sz) with (1 + (sz - 1)) at 2 by omega.\n    rewrite Nat.mul_add_distr_r.\n    rewrite Nat.mul_1_l.\n    replace (x + sz - 1) with (x + (sz - 1)).\n    apply plus_le_compat_l.\n    replace x with (n0 + 1) by omega.\n    rewrite Nat.mul_add_distr_l.\n    rewrite plus_comm.\n    rewrite Nat.mul_1_r.\n    apply le_plus_l.\n    omega.\n    rewrite mult_comm.\n    rewrite Nat.div_mul by omega.\n    apply Nat.eq_le_incl.\n    apply Nat.div_mod.\n    omega.\n  Qed.\n  \n  Lemma divup_ge : forall a b c,\n    b > 0 -> \n    c >= divup a b -> c * b >= a.\n  Proof.\n    intros.\n    apply le_trans with (m := divup a b * b).\n    apply roundup_ge; auto.\n    apply Nat.mul_le_mono_pos_r; auto.\n  Qed.\n\n  Lemma divup_mono: forall m n sz,\n    m <= n -> divup m sz <= divup n sz.\n  Proof.\n    intros.\n    case_eq sz; intros.\n    reflexivity.\n    apply Nat.div_le_mono.\n    auto.\n    omega.\n  Qed.\n\n  Lemma roundup_mono : forall m n sz,\n    m <= n -> roundup m sz <= roundup n sz.\n  Proof.\n    intros.\n    unfold roundup.\n    apply Nat.mul_le_mono_nonneg_r.\n    omega.\n    apply divup_mono; assumption.\n  Qed.\n\n  Definition divup' x m :=\n  match (x mod m) with\n  | O => x / m\n  | S _ => x / m + 1\n  end.\n\n  Theorem divup_eq_divup'_m_nonzero : forall x m,\n    m <> 0 ->\n    divup x m = divup' x m.\n  Proof.\n    intros.\n    unfold divup, divup'.\n    case_eq (x mod m); intros.\n    assert (Hxm := Nat.div_mod x m H).\n    rewrite H0 in Hxm.\n    symmetry.\n    apply Nat.div_unique with (m - 1).\n    omega.\n    omega.\n    assert (Hxm := Nat.div_mod x m H).\n    symmetry.\n    apply Nat.div_unique with (r := x mod m - 1).\n    apply lt_trans with (x mod m).\n    omega.\n    apply Nat.mod_upper_bound; assumption.\n    replace (x + m - 1) with (x + (m - 1)) by omega.\n    rewrite Hxm at 1.\n    rewrite Nat.mul_add_distr_l.\n    rewrite Nat.mul_1_r.\n    assert (x mod m + (m - 1) = m + (x mod m - 1)).\n    omega.\n    omega.\n  Qed.\n\n  Theorem divup_eq_divup' : forall x m,\n    divup x m = divup' x m.\n  Proof.\n    intros.\n    case_eq m; intros.\n    unfold divup, divup'.\n    reflexivity.\n    apply divup_eq_divup'_m_nonzero.\n    omega.\n  Qed.\n\n  Ltac divup_cases :=\n    rewrite divup_eq_divup';\n    match goal with\n    | [ |- context[divup' ?x ?m] ] =>\n      unfold divup';\n      case_eq (x mod m); intros\n    end.\n\n  Lemma divup_mul : forall x m,\n    m <> 0 ->\n    divup (x*m) m = x.\n  Proof.\n    intros.\n    rewrite divup_eq_divup'.\n    unfold divup'.\n    rewrite Nat.mod_mul by assumption.\n    apply Nat.div_mul.\n    assumption.\n  Qed.\n\n  Lemma divup_eq_div : forall a b, a mod b = 0 -> divup a b = a / b.\n  Proof.\n    intros.\n    rewrite divup_eq_divup'. unfold divup'.\n    destruct (a mod b); omega.\n  Qed.\n\n  Lemma div_le_divup : forall n sz,\n    n / sz <= divup n sz.\n  Proof.\n    intros.\n    destruct sz.\n    - simpl.\n      omega.\n    - unfold divup.\n      apply Nat.div_le_mono.\n      omega.\n      omega.\n  Qed.\n\n  Lemma div_lt_divup : forall m n sz,\n    sz <> 0 ->\n    m < n ->\n    m / sz < divup n sz.\n  Proof.\n    intros.\n    rewrite divup_eq_divup'.\n    unfold divup'.\n    case_eq (n mod sz); intros.\n    rewrite Nat.mul_lt_mono_pos_l with (p := sz) by omega.\n    replace (sz * (n / sz)) with n.\n    eapply le_lt_trans.\n    apply Nat.mul_div_le.\n    omega.\n    assumption.\n    apply Nat.div_exact; assumption.\n    apply le_lt_trans with (n / sz).\n    apply Nat.div_le_mono; omega.\n    omega.\n  Qed.\n\n  Lemma le_divup:\n    forall m n,\n      m <= n ->\n      divup m valubytes <= divup n valubytes.\n  Proof.\n    intros.\n    apply divup_mono; assumption.\n  Qed.\n\n  Lemma le_roundup:\n    forall m n,\n      m <= n ->\n      roundup m valubytes <= roundup n valubytes.\n  Proof.\n    unfold roundup, divup; intros.\n    apply Nat.mul_le_mono_r.\n    apply le_divup; assumption.\n  Qed.\n\n  (* slightly different from the one in Word.v *)\n  Lemma lt_minus':\n    forall a b c,\n      a < c -> a - b < c.\n  Proof.\n    intros.\n    omega.\n  Qed.\n\n  Lemma divup_goodSize:\n    forall (a: waddr),\n      goodSize addrlen (divup #a valubytes).\n  Proof.\n    assert (addrlen > 1) by ( unfold addrlen ; omega ).\n    generalize dependent addrlen.\n    intros.\n    unfold goodSize, divup.\n    apply Nat.div_lt_upper_bound.\n    rewrite valubytes_is; simpl valubytes_real; auto.\n    apply lt_minus'.\n    unfold addrlen.\n    rewrite valubytes_is; simpl valubytes_real.\n    replace (4096) with (pow2 12) by reflexivity.\n    rewrite <- pow2_add_mul.\n    replace (pow2 (12 + n)) with (pow2 (11 + n) + pow2 (11 + n)).\n    apply plus_lt_compat.\n    eapply lt_trans.\n    apply natToWord_goodSize.\n    apply pow2_inc; omega.\n    apply pow2_inc; omega.\n    replace (12 + n) with ((11 + n) + 1) by omega.\n    rewrite (pow2_add_mul (11+n) 1).\n    simpl (pow2 1).\n    omega.\n  Qed.\n\n  Lemma divup_sub_1 : forall n sz,\n    n >= sz -> sz <> 0 ->\n    divup (n - sz) sz = divup n sz - 1.\n  Proof.\n    unfold divup; intros; simpl.\n    replace (n - sz + sz) with n by lia.\n    replace (n + sz - 1) with (n - 1 + 1 * sz) by lia.\n    rewrite Nat.div_add by auto.\n    omega.\n  Qed.\n\n  Lemma divup_sub : forall i n sz,\n    n >= i * sz -> sz <> 0 ->\n    divup (n - i * sz) sz = divup n sz - i.\n  Proof.\n    induction i; intros; simpl.\n    repeat rewrite Nat.sub_0_r; auto.\n    replace (n - (sz + i * sz)) with ((n - sz) - (i * sz)) by nia.\n    rewrite IHi by nia.\n    rewrite divup_sub_1; nia.\n  Qed.\n\n  Lemma sub_mod_add_mod : forall a b,\n    b <> 0 -> b - a mod b + a mod b = b.\n  Proof.\n    intros.\n    pose proof (Nat.mod_upper_bound a b H).\n    omega.\n  Qed.\n\n  Lemma divup_mul_l : forall b c,\n    divup (c * b) b <= c.\n  Proof.\n    intros; destruct (Nat.eq_dec b 0); subst.\n    rewrite Nat.mul_0_r; rewrite divup_0; omega.\n    rewrite divup_mul; omega.\n  Qed.\n\n  Lemma divup_mul_r : forall b c,\n    divup (b * c) b <= c.\n  Proof.\n    intros; rewrite Nat.mul_comm; apply divup_mul_l.\n  Qed.\n\n  Lemma divup_le : forall a b c,\n    a <= b * c -> divup a b <= c.\n  Proof.\n    intros.\n    eapply le_trans.\n    apply divup_mono; eauto.\n    rewrite divup_mul_r; auto.\n  Qed.\n\n  Lemma divup_le_1 : forall a b,\n    a <= b -> divup a b <= 1.\n  Proof.\n    intros; apply divup_le; omega.\n  Qed.\n\n  Lemma divup_ge_1 : forall a b,\n   b <> 0 -> a >= b -> divup a b >= 1.\n  Proof.\n    intros; unfold divup.\n    replace (a + b - 1) with (a - 1 + 1 * b) by omega.\n    rewrite Nat.div_add by auto.\n    nia.\n  Qed.\n\n  Lemma divup_small : forall c n, 0 < c <= n -> divup c n = 1.\n  Proof.\n    intros.\n    assert (divup c n <= 1) by (apply divup_le_1; omega).\n    assert (c - 1 < n) by omega.\n    assert ((c - 1) / n < divup c n) by (apply div_lt_divup; omega).\n    assert ((c - 1) / n = 0) as HH by (apply Nat.div_small; auto); rewrite HH in *.\n    omega.\n  Qed.\n\n  Lemma divup_mul_ge : forall a b c,\n    b <> 0 -> a >= b * c -> divup a b >= c.\n  Proof.\n    intros.\n    eapply le_trans.\n    2: apply divup_mono; eauto.\n    rewrite Nat.mul_comm.\n    rewrite divup_mul; auto.\n  Qed.\n\n  Lemma divup_gt_0 : forall a b, 0 < a -> 0 < b -> divup a b > 0.\n  Proof.\n    intros.\n    apply Nat.div_str_pos; omega.\n  Qed.\n\n  Lemma mod_div_0 : forall a b,\n    (a mod b) / b = 0.\n  Proof.\n    intros.\n    destruct (Nat.eq_dec b 0); subst; simpl; auto.\n    rewrite Nat.div_small; auto.\n    apply Nat.mod_bound_pos; omega.\n  Qed.\n\n  Lemma div_add_distr_le : forall a b c,\n    a / c + b / c <= (a + b) / c.\n  Proof.\n    intros.\n    destruct (Nat.eq_dec c 0); subst; simpl; auto.\n    rewrite Nat.div_mod with (x := a) (y := c) by auto.\n    rewrite Nat.div_mod with (x := b) (y := c) by auto.\n    replace (c * (a / c) + a mod c + (c * (b / c) + b mod c)) with\n            (((a mod c + b mod c) + (b / c) * c) + (a / c) * c) by nia.\n    repeat rewrite Nat.div_add by auto.\n    setoid_rewrite Nat.add_comm at 2 3.\n    setoid_rewrite Nat.mul_comm.\n    repeat rewrite Nat.div_add by auto.\n    repeat rewrite mod_div_0.\n    repeat rewrite Nat.add_0_l.\n    omega.\n  Qed.\n\n\n  Lemma divup_add' : forall i n sz,\n    sz <> 0 -> n <> 0 ->\n    divup (n + sz * i) sz = divup n sz + i.\n  Proof.\n    induction i; intros; simpl.\n    rewrite Nat.add_0_r; rewrite Nat.mul_0_r; auto.\n    replace (n + (sz * S i)) with ((n + sz) + (sz * i)) by nia.\n    rewrite IHi by nia.\n    unfold divup.\n    replace (n + sz + sz - 1) with (n - 1 + 2 * sz) by nia.\n    replace (n + sz - 1) with (n - 1 + 1 * sz) by nia.\n    repeat rewrite Nat.div_add by auto.\n    omega.\n  Qed.\n  \n  Lemma divup_add : forall i n sz,\n    sz <> 0 -> divup (n + sz * i) sz = divup n sz + i.\n  Proof.\n    intros.\n    destruct (Nat.eq_dec n 0); subst.\n    rewrite divup_0; rewrite Nat.add_0_l; rewrite Nat.mul_comm.\n    rewrite divup_mul; omega.\n    apply divup_add'; auto.\n  Qed.\n\n  Lemma divup_n_mul_n_le : forall a n, n <> 0 -> a <= (divup a n) * n.\n  Proof.\n    intros.\n    destruct (addr_eq_dec a 0); subst; try lia.\n    eapply (Nat.div_mod a) in H as HH.\n    rewrite HH.\n    rewrite plus_comm.\n    rewrite divup_add by omega.\n    rewrite Nat.mul_add_distr_r.\n    destruct (addr_eq_dec (a mod n) 0) as [H'|H'].\n    rewrite H'.\n    rewrite mul_div; lia.\n    rewrite divup_small.\n    simpl. rewrite plus_0_r.\n    pose proof Nat.mod_upper_bound a n H.\n    rewrite mult_comm; omega.\n    split. omega.\n    apply Nat.lt_le_incl. apply Nat.mod_upper_bound.\n    omega.\n  Qed.\n\n  Lemma add_lt_upper_bound : forall a b c d,\n    a <= b -> c + b < d -> c + a < d.\n  Proof.\n    intros; omega.\n  Qed.\n\n  Lemma helper_sub_add_cancel : forall a b c,\n    a >= b -> b >= c ->\n    a - b + (b - c) = a - c.\n  Proof.\n    intros; omega.\n  Qed.\n\n  Lemma helper_add_sub_lt : forall a b c,\n    b > 0 -> a < c -> a + b - c < b.\n  Proof.\n    intros. omega.\n  Qed.\n\n  Lemma div_mul_lt : forall a b,\n    b <> 0 -> a mod b <> 0 -> a / b * b < a.\n  Proof.\n    intros.\n    rewrite Nat.div_mod with (x := a) (y := b) by auto.\n    setoid_rewrite Nat.mul_comm at 2.\n    repeat rewrite Nat.div_add_l by omega.\n    rewrite Nat.div_small with (a := (a mod b)).\n    rewrite Nat.add_0_r, Nat.mul_comm.\n    omega.\n    apply Nat.mod_upper_bound; omega.\n  Qed.\n\n  Theorem roundup_mult_mono : forall n a b, b <> 0 ->\n    Nat.divide a b -> roundup n a <= roundup n b.\n  Proof.\n    intros.\n    unfold Nat.divide in *.\n    destruct H0; subst.\n    destruct (addr_eq_dec x 0) as [|Hx]; subst; try omega.\n    destruct (addr_eq_dec n 0) as [|Hn]; subst.\n    repeat rewrite roundup_0; auto.\n    destruct (addr_eq_dec a 0) as [|Ha]; subst; [> rewrite mult_comm; auto |].\n    unfold roundup.\n    rewrite mult_assoc.\n    apply mult_le_compat_r.\n    unfold divup.\n    replace (n + a - 1) with ((1 * a) + (n - 1)) by omega.\n    replace (n + x * a - 1) with (1 * (x * a) + (n - 1)) by lia.\n    repeat rewrite Nat.div_add_l by auto.\n    replace (x * a) with (a * x) by (apply mult_comm).\n    rewrite <- Nat.div_div by auto.\n    remember ((n - 1) / a) as r.\n    apply Nat.div_mod with (x := r) in Hx as Hr.\n    rewrite plus_comm in Hr.\n    rewrite Hr at 1.\n    rewrite plus_assoc, mult_comm.\n    apply plus_le_compat_r.\n    eapply lt_le_trans; [> apply Nat.mod_upper_bound | ]; auto.\n  Qed.\n\n  Lemma min_roundup : forall a b z, roundup (min a b) z = min (roundup a z) (roundup b z).\n  Proof.\n    intros.\n    edestruct Min.min_spec as [ [HH Hmin]|[HH Hmin] ]; rewrite Hmin in *;\n    symmetry; (apply min_l || apply min_r);\n    apply roundup_mono; omega.\n  Qed.\n\n  Lemma roundup_mult : forall a b, roundup (a * b) a = a * b.\n  Proof.\n    unfold roundup; intros.\n    destruct (Nat.eq_dec a 0); subst; simpl; auto.\n    replace (a * b) with (b * a) by apply mult_comm.\n    destruct (Nat.eq_dec b 0); subst; simpl.\n    rewrite divup_0; auto.\n    rewrite divup_mul; auto.\n  Qed.\n\n  Lemma roundup_sub_lt : forall n sz,\n    sz > 0 -> roundup n sz - n < sz.\n  Proof.\n    unfold roundup; intros.\n    divup_cases.\n    replace (n / sz * sz) with n; try omega.\n    rewrite Nat.mul_comm.\n    rewrite Nat.div_exact; omega.\n    rewrite Nat.mul_add_distr_r, Nat.mul_1_l.\n\n    apply helper_add_sub_lt; auto.\n    apply div_mul_lt; omega.\n  Qed.\n\n  Lemma roundup_subt_divide : forall a b c, a < roundup b c -> Nat.divide c a ->\n    roundup (b - a) c = roundup b c - a.\n  Proof.\n    intros.\n    destruct H0 as [x H0].\n    destruct (Nat.eq_dec c 0); subst; unfold roundup; auto.\n    rewrite divup_sub; auto.\n    rewrite Nat.mul_sub_distr_r; auto.\n    unfold roundup in *.\n    rewrite <- Nat.mul_lt_mono_pos_r in H by omega.\n    unfold ge.\n    unfold divup in *.\n    apply lt_div_mul_add_le in H; omega.\n  Qed.\n\n  Lemma divup_add_small : forall m n k,\n    k > 0 -> n <= roundup m k - m ->\n    divup (m + n) k = divup m k.\n  Proof.\n    unfold roundup, divup; intros.\n    replace (m + n + k - 1) with ((m + k - 1) + n) by omega.\n    rewrite Nat.div_mod with (x := (m + k -1)) (y := k) by omega.\n    rewrite Nat.mul_comm.\n    rewrite <- Nat.add_assoc.\n    repeat rewrite Nat.div_add_l by omega.\n    f_equal.\n    repeat rewrite Nat.div_small; auto.\n    apply Nat.mod_upper_bound; omega.\n\n    eapply add_lt_upper_bound; eauto.\n    rewrite Nat.mod_eq by omega.\n    rewrite Nat.mul_comm.\n\n    destruct (le_gt_dec (m + k - 1) ((m + k - 1) / k * k)).\n    replace (m + k - 1 - (m + k - 1) / k * k ) with 0 by omega.\n    rewrite Nat.add_0_l.\n\n    apply roundup_sub_lt; auto.\n    rewrite helper_sub_add_cancel; try omega.\n    apply roundup_ge; auto.\n  Qed.\n\n  Lemma divup_divup: forall x sz,\n      sz > 0 ->\n      divup ((divup x sz) * sz) sz = divup x sz.\n  Proof.\n    unfold divup; intros.\n    rewrite <- Nat.add_sub_assoc by omega.\n    rewrite Nat.div_add_l by omega.\n    replace ((sz - 1) / sz) with 0. omega.\n    rewrite Nat.div_small; omega.\n  Qed.\n\n  Lemma roundup_roundup : forall n sz,\n    sz > 0 ->\n    roundup (roundup n sz) sz = roundup n sz.\n  Proof.\n    unfold roundup; intros.\n    rewrite divup_divup; auto.\n  Qed.\n\n  Lemma roundup_roundup_add : forall x n sz,\n    sz > 0 ->\n    roundup (roundup n sz + x) sz = roundup n sz + roundup x sz.\n  Proof.\n    unfold roundup; intros.\n    rewrite Nat.add_comm.\n    setoid_rewrite Nat.mul_comm at 2.\n    rewrite divup_add by omega.\n    lia.\n  Qed.\n\n  Lemma divup_same : forall x,\n    x <> 0 -> divup x x = 1.\n  Proof.\n    intros; erewrite <- divup_mul; eauto.\n    rewrite Nat.mul_1_l; auto.\n  Qed.\n\n  Lemma divup_gt : forall a b sz,\n    sz > 0 -> divup a sz > b -> a > b * sz.\n  Proof.\n    intros a b sz H.\n    divup_cases.\n    eapply Nat.mul_lt_mono_pos_r in H1; eauto.\n    replace (a / sz * sz) with a in H1; auto.\n    rewrite Nat.mul_comm.\n    apply Nat.div_exact; omega.\n\n    destruct b.\n    destruct (Nat.eq_dec a 0); subst.\n    contradict H0.\n    rewrite Nat.mod_0_l; omega.\n    omega.\n\n    rewrite Nat.add_1_r in H1.\n    apply lt_n_Sm_le in H1.\n    eapply Nat.mul_le_mono_pos_r in H1; eauto.\n    replace (a / sz * sz) with (a - a mod sz) in H1.\n    rewrite H0 in H1.\n    eapply Nat.le_lt_trans; eauto.\n    destruct (Nat.eq_dec a 0); subst.\n    contradict H0.\n    rewrite Nat.mod_0_l; omega.\n    omega.\n\n    rewrite Nat.mod_eq by omega.\n    setoid_rewrite Nat.mul_comm at 2.\n    apply sub_sub_assoc.\n    apply Nat.mul_div_le; omega.\n  Qed.\n\n  Definition divup_S x sz :=\n    match (x mod sz) with\n    | O => divup x sz + 1\n    | S _ => divup x sz\n    end.\n\n  Theorem divup_eq_divup_S : forall x sz,\n    sz <> 0 ->\n    divup (S x) sz = divup_S x sz.\n  Proof.\n    intros.\n    unfold divup, divup_S.\n    divup_cases;\n    replace (S x + sz - 1) with (x + 1 * sz) by omega;\n    rewrite Nat.div_add; auto.\n  Qed.\n\n\n  Lemma divup_add_gt : forall a b n sz,\n    sz > 0 -> a + divup b sz > n ->\n    a * sz + b > n * sz.\n  Proof.\n    induction a; intros; auto.\n    rewrite Nat.add_0_l in H0.\n    rewrite Nat.add_0_l.\n    apply divup_gt; auto.\n\n    replace (S a * sz + b) with (a * sz + (b + sz * 1)).\n    apply IHa; auto.\n    rewrite divup_add; omega.\n    rewrite Nat.mul_1_r.\n    rewrite Nat.mul_succ_l.\n    omega.\n  Qed.\n\n  Lemma roundup_le' : forall a b sz,\n    sz > 0 ->\n    a <= b * sz -> roundup a sz <= b * sz.\n  Proof.\n    intros.\n    apply (roundup_mono _ _ sz) in H0.\n    eapply le_trans; eauto.\n    unfold roundup.\n    apply Nat.mul_le_mono_pos_r; auto.\n    apply divup_mul_l.\n  Qed.\n\n  Lemma roundup_le : forall a b sz,\n    a <= b * sz -> roundup a sz <= b * sz.\n  Proof.\n    destruct sz; intros.\n    unfold roundup.\n    repeat rewrite Nat.mul_0_r; auto.\n    apply roundup_le'; auto; omega.\n  Qed.\n\n  Lemma roundup_min_r : forall a b,\n    b > 0 -> Nat.min ((divup a b) * b ) a = a.\n  Proof.\n    intros.\n    apply Nat.min_r.\n    apply roundup_ge; auto.\n  Qed.\n\n  Lemma divup_eq_div_plus_1 : forall a b, a mod b <> 0 -> divup a b = a / b + 1.\n  Proof.\n    intros.\n    divup_cases; omega.\n  Qed.\n\n  Lemma roundup_gt : forall a b, b <> 0 -> a mod b <> 0 -> a < roundup a b.\n  Proof.\n    intros.\n    unfold roundup.\n    rewrite divup_eq_div_plus_1 by auto.\n    rewrite Nat.mul_add_distr_r. rewrite mult_1_l.\n    rewrite Nat.div_mod with (x := a) (y := b) at 1 by auto.\n    rewrite mult_comm.\n    assert (a mod b < b) by (apply Nat.mod_upper_bound; auto). omega.\n  Qed.\n\n  Lemma roundup_eq : forall a n, n <> 0 -> a mod n <> 0 -> roundup a n = a + (n - a mod n).\n  Proof.\n    intros.\n    unfold roundup.\n    rewrite divup_eq_divup'. unfold divup'.\n    destruct (a mod n) as [|n'] eqn:HH; intuition.\n    replace (S n') with (a mod n) by omega.\n    rewrite Nat.div_mod with (x := a) (y := n) at 2 by auto.\n    rewrite <- plus_assoc.\n    rewrite <- le_plus_minus by (apply mod_le_r).\n    rewrite Nat.mul_add_distr_r. rewrite mult_comm. omega.\n  Qed.\n", "meta": {"author": "mit-pdos", "repo": "fscq", "sha": "2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0", "save_path": "github-repos/coq/mit-pdos-fscq", "path": "github-repos/coq/mit-pdos-fscq/fscq-2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0/src/Rounding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6798592473026859}}
{"text": "(**\n私家版：代数的構造とCoq\n「Magma の六角形」を実装してみる。\n\n@suharahiromichi\n\n2015_01_02\n2015_05_01\n*)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n(*\nGeneralizable All Variables.\n個別に宣言する。\n*)\nRequire Import ssreflect ssrbool ssrnat eqtype seq ssrfun.\n\n(**\n# Setoid\n *)\nClass setoid_equal (A : Type) := setoid_eq : A -> A -> Prop.\nInfix \"==\" := setoid_eq.\nClass Setoid (A : Type) (equal : setoid_equal A) : Prop :=\n  {\n    (* 同値関係（だけ） *)\n    prf_Setoid_ref :                        (* 反射律 *)\n      forall x : A, equal x x;\n    prf_Setoid_sym :                        (* 対象律 *)\n      forall x y : A, equal x y -> equal y x;\n    prf_Setoid_trans :                      (* 推移律 *)\n      forall x y z : A, equal x y -> equal y z -> equal x z\n  }.\n\nGeneralizable Variables A equal.\n\nClass magma_binop `{X : @Setoid A equal} := magma_op : A -> A -> A.\nInfix \"*\" := magma_op.\nClass Magma `{X : @Setoid A equal} (dot : magma_binop) : Prop :=\n  {\n    prf_binop : forall (x1 y1 x2 y2 : A),\n                  x1 == y1 -> x2 == y2 -> x1 * x2 == y1 * y2\n  }.\n\n(* ******************** *)\n(* ***** 性質 ********* *)\n(* ******************** *)\nGeneralizable Variables dot ST.\n\nClass Associative `{X : @Magma A equal ST dot} : Prop :=\n  associative : forall (x y z : A), (x * y) * z == x * (y * z).\n  \nClass LIdentical `{X : @Magma A equal ST dot} (e : A) : Prop :=\n  left_identical: forall x : A, e * x == x.\n\nClass RIdentical `{X : @Magma A equal ST dot} (e : A) : Prop :=\n  right_identical: forall x : A , x * e == x.\n\nClass Identical `{X : @Magma A equal ST dot} (e : A) : Prop :=\n  {\n    identical_l : LIdentical e;\n    identical_r : RIdentical e\n  }.\n\n(* divの引数を直感的な順番にした。 *)\nClass LDivisible `{X : @Magma A equal ST dot} (div : A -> A -> A) : Prop :=\n  left_divisible: forall (a b : A), (div b a) * a == b.\n\nClass RDivisible `{X : @Magma A equal ST dot} (div : A -> A -> A) : Prop :=\n  right_divisible: forall (a b : A), a * (div b a) == b.\n\nClass Divisible `{X : @Magma A equal ST dot} (divL divR : A -> A -> A) : Prop :=\n  {\n    divisible_l : LDivisible divL;\n    divisible_r : RDivisible divL\n  }.\n\n(* Invertible の定義を Monoid からMagmaに移動する。 *)\nClass LInvertible `{X : @Magma A equal ST dot}  (e : A) (inv : A -> A) : Prop :=\n  left_invertible: forall (x : A), (inv x) * x == e.\n  \nClass RInvertible `{X : @Magma A equal ST dot}  (e : A) (inv : A -> A) : Prop :=\n  right_invertible: forall (x : A), (inv x) * x == e.\n\nClass Invertible `{X : @Magma A equal ST dot}  (e : A) (inv : A -> A) : Prop :=\n  {\n    invertible_l :> LInvertible e inv;\n    invertible_r :> RInvertible e inv\n  }.\n\n(* ******************** *)\n(* bool 排他的論理和の群 *)\n(* ******************** *)\nCheck setoid_equal bool.\nInstance bool_equal : setoid_equal bool := eq.\nCheck false == true : Prop.\n\nCheck @Setoid bool bool_equal.\nProgram Instance bool_setoid : @Setoid bool bool_equal.\nNext Obligation.\n    by [].                                  (* bool_equal は reflextivity できる。 *)\nQed.\nNext Obligation.\n    by [].\nQed.\nNext Obligation.\n  by rewrite H H0.                          (* bool_equal は rewrite できる。 *)\nQed.\n\nCheck @magma_binop bool bool_equal bool_setoid.\nInstance bool_dot : @magma_binop bool bool_equal bool_setoid := xorb.\nEval compute in false * false.              (* false *)\nEval compute in false * true.               (* true *)\nEval compute in true * false.               (* true *)\nEval compute in true * true.                (* false *)\n\nCheck @Magma bool bool_equal bool_setoid bool_dot.\nProgram Instance bool_magma : @Magma bool eq bool_setoid xorb.\nNext Obligation.\n  by rewrite H H0.\nQed.\n\nSection Group_1.\n  Generalizable Variables divl divr one MG QG.\n\n  Check @Magma.\n  Check `(@Magma A equal ST dot).\n  Class qg_divop `{X : @Magma A equal ST dot} := qg_op : A -> A -> A.\n  Infix \"/\" := qg_op.\n  Class Quasigroup `{X : @Magma A equal ST dot} (divl divr : qg_divop) : Prop :=\n    {\n      divisible : Divisible divl divr\n    }.\n  \n  Check @Quasigroup.\n  Check `(@Quasigroup A equal ST dot MG divl divr).\n  Class lp_unitop `{X : @Quasigroup A equal ST dot MG divl divr} := lp_op : A.\n  Class Loop `{X : @Quasigroup A equal ST dot MG divl divr} (lp_unit : A) : Prop :=\n    {\n      lp_identical : Identical lp_unit      (* IdenticalはMagmaで定義している。 *)\n    }.\n  \n  Check @Loop.\n  Check `(@Loop A equal ST dot MG divl divr QG one).\n  Class Group_1 `{X : @Loop A equal ST dot MG divl divr QG one} : Prop :=\n    {\n        prf_group_1 : Associative\n    }.\n  \n  (* ******************** *)\n  (* bool 排他的論理和の群 *)\n  (* ******************** *)\n  Check @qg_divop bool bool_equal bool_setoid bool_dot bool_magma.\n  Instance bool_div : @qg_divop bool bool_equal bool_setoid bool_dot bool_magma := xorb.\n  Eval compute in false / false.              (* false *)\n  Eval compute in false / true.               (* true *)\n  Eval compute in true / false.               (* true *)\n  Eval compute in true / true.                (* false *)\n\n  Check @Quasigroup bool bool_equal bool_setoid bool_dot bool_magma bool_div bool_div.\n  Program Instance bool_qg : @Quasigroup bool bool_equal bool_setoid bool_dot bool_magma bool_div bool_div.\n  Next Obligation.\n  Proof.\n    apply Build_Divisible.\n    - rewrite /LDivisible.                  (* 左割算 *)\n      rewrite /bool_div.\n        by case; case.\n    - rewrite /RDivisible.                  (* 右割算 *)\n      rewrite /bool_div.\n        by case; case.\n  Qed.\n  \n  Check `(@lp_unitop bool eq ST xorb MG divl divr QG).\n  Check @lp_unitop bool bool_equal bool_setoid bool_dot bool_magma bool_div bool_div bool_qg.\n  Instance bool_unit : @lp_unitop bool bool_equal bool_setoid bool_dot bool_magma bool_div bool_div bool_qg := false.\n\n  Program Instance bool_loop : @Loop bool bool_equal bool_setoid bool_dot bool_magma bool_div bool_div bool_qg bool_unit.\n  Next Obligation.\n    apply Build_Identical.\n    - rewrite /LIdentical.                  (* 左単位元 *)\n        by case.\n    - rewrite /RIdentical.                  (* 右単位元 *)\n        by case.\n  Qed.\n\n  Check @Group_1 bool bool_equal bool_setoid bool_dot bool_magma bool_div bool_div bool_qg bool_unit bool_loop.\n  Program Instance bool_group_1 : @Group_1 bool bool_equal bool_setoid bool_dot bool_magma bool_div bool_div bool_qg bool_unit bool_loop.\n  Next Obligation.                          (* 結合則 *)\n  Proof.\n    rewrite /Associative.\n      by apply Bool.xorb_assoc_reverse.    \n  Qed.\nEnd Group_1.\n\nSection Group_2.\n  Generalizable Variables one MG SG.        (* MGは、Group_1 とは別なものになる。 *)\n\n  Check @Magma.\n  Class Semigroup `{X : @Magma A equal ST dot} : Prop :=\n    {\n      prf_semigroup : forall (x y z : A), (x * y) * z == x * (y * z)\n    }.\n  \n  Check @Semigroup.\n  Class Monoid `{X : @Semigroup A equal ST dot MG} (mon_unit : A) : Prop :=\n    {\n      mon_identical : Identical mon_unit    (* IdenticalはMagmaで定義している。 *)\n  }.\n  \n  Check @Monoid.\n  Class gp_invop `{X : @Monoid A equal ST dot MG SG one} := gp_op : A -> A.\n  (* Invertible の定義を Monoid からMagmaに移動する。 *)\n  Class Group_2 `{X : @Monoid A equal ST dot MG SG one} (inv : gp_invop) : Prop :=\n    {\n      invertible : Invertible one inv\n    }.\n  \n  (* ******************** *)\n  (* bool 排他的論理和の群 *)\n  (* ******************** *)\n  Check @Semigroup bool bool_equal bool_setoid bool_dot bool_magma.\n  Program Instance bool_sg : @Semigroup bool bool_equal bool_setoid bool_dot bool_magma.\n  Next Obligation.                          (* 結合則 *)\n  Proof.\n    rewrite /magma_op /bool_dot.\n    by rewrite Bool.xorb_assoc_reverse.\n  Qed.\n\n  Check Monoid bool_unit.\n  Check @Monoid bool bool_equal bool_setoid bool_dot bool_magma bool_sg bool_unit.\n  Program Instance bool_monoid : @Monoid bool bool_equal bool_setoid bool_dot bool_magma bool_sg bool_unit.\n  Next Obligation.\n    apply Build_Identical.\n    - rewrite /LIdentical.                  (* 左単位元 *)\n        by case.\n    - rewrite /RIdentical.                  (* 右単位元 *)\n        by case.\n  Qed.\n  Check bool_monoid : Monoid bool_unit.\n  \n  Check gp_invop.\n  Check @gp_invop bool bool_equal bool_setoid bool_dot bool_magma bool_sg bool_unit bool_monoid.\n  Instance bool_inv : @gp_invop bool bool_equal bool_setoid bool_dot bool_magma bool_sg bool_unit bool_monoid := id.\n\n  Check @Group_2 bool bool_equal bool_setoid bool_dot bool_magma bool_sg bool_unit bool_monoid bool_inv.\n  Program Instance bool_groop_2 : @Group_2 bool bool_equal bool_setoid bool_dot bool_magma bool_sg bool_unit bool_monoid bool_inv.\n  Next Obligation.\n    apply Build_Invertible.\n    - rewrite /LInvertible.                 (* 左逆元 *)\n      rewrite /bool_unit /bool_inv => x.\n      by case x.\n    - rewrite /RInvertible.                 (* 右逆元 *)\n      rewrite /bool_unit /bool_inv => x.\n      by case x.\n  Qed.\n  \n  (* 補足説明 *)\n  Check `(@Monoid bool bool_equal ST bool_dot MG SG bool_unit).\n  (* 一部を、Generalizable Variable にしてもよいが、証明している対象が違ってきているかもしれない。 *)\n  Program Instance bool_monoid' : `(@Monoid bool bool_equal ST bool_dot MG SG bool_unit).\n  Next Obligation.\n    apply Build_Identical.\n    - rewrite /LIdentical.                  (* 左単位元 *)\n        by case.\n    - rewrite /RIdentical.                  (* 右単位元 *)\n        by case.\n  Qed.\n  Check bool_monoid'. (* forall (ST : Setoid bool_equal) (MG : Magma bool_dot) (SG : Semigroup), Monoid bool_unit *)\n\n  Program Instance bool_groop_2' : Group_2 bool_inv. (* @がいらない場合もある。 *)\n  Next Obligation.\n    apply Build_Invertible.\n    - rewrite /LInvertible.                 (* 左逆元 *)\n      rewrite /bool_unit /bool_inv => x.\n        by case x.\n    - rewrite /RInvertible.                 (* 右逆元 *)\n      rewrite /bool_unit /bool_inv => x.\n        by case x.\n  Qed.\nEnd Group_2.\n\nSection Group_3.\n  Generalizable Variables inv divl divr one MG QG LP SG MON GP.\n  \n  Check @Group_1.\n  Check `(@Group_1 A equal ST dot MG divl divr QG one LP).\n  Class gp1_invop `{X : @Group_1 A equal ST dot MG divl divr QG one LP} := gp1_op : A -> A.\n  \n  Class inv_Group_1 `{@Group_1 A equal ST dot MG divl divr QG one LP} (inv : gp1_invop) : Prop :=\n    {\n      invertible' : Invertible one inv\n    }.\n  \n  Check `(@Group_2 A equal ST dot MG SG one MON inv).\n  Class gp2_divop `{@Group_2 A equal ST dot MG SG one MON inv} := gp2_op : A -> A -> A.\n  Infix \"/\" := gp2_op.\n  Class div_Group_2 `{@Group_2 A equal ST dot MG SG one MON inv} (divl divr : gp2_divop) : Prop :=\n    {\n      divisible' : Divisible divl divr\n    }.\n  \nEnd Group_3.\n  \n(**\n# 参考：\n    http://www.labri.fr/perso/casteran/CoqArt/TypeClassesTut/typeclassestut.pdf\n    http://mathink.net/program/coq_setoid.html\n    http://mathink.net/program/coq_map.html\n    http://mathink.net/program/coq_group.html\n    http://en.wikipedia.org/wiki/Magma_(algebra)\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/gitcrc/ssr_setoid_magma_group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995028, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6798592378322573}}
{"text": "Require Export Families.\nRequire Import EnsemblesSpec.\n\nLocal Unset Standard Proposition Elimination Names.\n\nRecord Filter (X:Type) : Type := {\n  filter_family: Family X;\n  filter_intersection: forall S1 S2:Ensemble X,\n    In filter_family S1 -> In filter_family S2 ->\n    In filter_family (Intersection S1 S2);\n  filter_upward_closed: forall S1 S2:Ensemble X,\n    In filter_family S1 -> Included S1 S2 ->\n    In filter_family S2;\n  filter_full: In filter_family Full_set;\n  filter_empty: ~ In filter_family Empty_set\n}.\n\nArguments filter_family [X].\n\nRecord filter_basis {X:Type} (F:Filter X) (B:Family X) : Prop := {\n  filter_basis_elements: Included B (filter_family F);\n  filter_basis_cond: forall S:Ensemble X,\n    In (filter_family F) S -> exists S':Ensemble X,\n    In B S' /\\ Included S' S\n}.\n\nRequire Import IndexedFamilies.\nRequire Import FiniteTypes.\n\nLemma filter_finite_indexed_intersection: forall {X:Type} (F:Filter X)\n  {A:Type} (S:IndexedFamily A X),\n  FiniteT A -> (forall a:A, In (filter_family F) (S a)) ->\n  In (filter_family F) (IndexedIntersection S).\nProof.\nintros.\ninduction H.\nrewrite empty_indexed_intersection.\napply filter_full.\nreplace (IndexedIntersection S) with\n  (Intersection (IndexedIntersection (fun a:T => S (Some a)))\n                (S None)).\napply filter_intersection.\napply IHFiniteT; auto.\napply H0.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H1.\ndestruct H1.\nconstructor.\ndestruct a; (apply H1 || apply H2).\ndestruct H1.\nconstructor; trivial.\nconstructor; auto.\n\ndestruct H1 as [g].\nreplace (IndexedIntersection S) with\n  (IndexedIntersection (fun x:X0 => S (f x))).\napply IHFiniteT; auto.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H3.\nconstructor.\nintros.\npose proof (H3 (g a)).\ncongruence.\ndestruct H3.\nconstructor.\nintro.\napply H3.\nQed.\n\nSection filter_from_basis.\n\nVariable X:Type.\nVariable B:Family X.\nHypothesis B_nonempty: Inhabited B.\nHypothesis B_empty: ~ In B Empty_set.\nHypothesis B_basis_cond: forall S1 S2:Ensemble X,\n  In B S1 -> In B S2 -> exists T:Ensemble X,\n  In B T /\\ Included T (Intersection S1 S2).\n\nDefinition Build_Filter_from_basis : Filter X.\nrefine (Build_Filter X [ S:Ensemble X | exists T:Ensemble X,\n                       In B T /\\ Included T S ] _ _ _ _).\nintros.\ndestruct H.\ndestruct H0.\ndestruct H as [T1 []].\ndestruct H0 as [T2 []].\ndestruct (B_basis_cond T1 T2 H H0) as [T' []].\nconstructor.\nexists T'; split; trivial.\nred; intros.\napply H4 in H5.\ndestruct H5.\nconstructor; auto.\n\nintros.\ndestruct H.\ndestruct H as [T []].\nconstructor.\nexists T; split; auto with sets.\n\nconstructor.\ndestruct B_nonempty as [T].\nexists T; split; trivial.\nred; intros; constructor.\nred; intro.\ndestruct H.\ndestruct H as [T []].\nassert (T = Empty_set).\napply Extensionality_Ensembles; split; auto with sets.\ndestruct H1.\ncontradiction B_empty.\nDefined.\n\nLemma filter_from_basis_basis: filter_basis Build_Filter_from_basis B.\nProof.\nconstructor.\nsimpl.\nred; intros S ?.\nconstructor.\nexists S; split; auto with sets.\nintros.\nsimpl in H.\ndestruct H.\nexact H.\nQed.\n\nEnd filter_from_basis.\n\nArguments Build_Filter_from_basis [X].\n\nRequire Import FiniteTypes.\nRequire Import IndexedFamilies.\n\nRecord filter_subbasis {X:Type} (F:Filter X) (B:Family X) : Prop := {\n  filter_subbasis_elements: Included B (filter_family F);\n  filter_subbasis_cond: forall S:Ensemble X,\n    In (filter_family F) S -> exists J:Type, FiniteT J /\\\n          exists T:J->Ensemble X,\n          (forall j:J, In B (T j)) /\\\n          Included (IndexedIntersection T) S\n}.\n\nSection filter_from_subbasis.\n\nVariable X:Type.\nVariable B:Family X.\nHypothesis B_subbasis_cond: forall (J:Type) (V:J->Ensemble X),\n  FiniteT J -> (forall j:J, In B (V j)) ->\n  Inhabited (IndexedIntersection V).\n\nRequire Import FiniteIntersections.\n\nDefinition Build_Filter_from_subbasis: Filter X.\nrefine (Build_Filter_from_basis (finite_intersections B) _ _ _).\nexists Full_set.\nconstructor.\nred; intro.\npose proof (finite_intersection_is_finite_indexed_intersection _ _ H).\ndestruct H0 as [J [? [V []]]].\nassert (Inhabited (IndexedIntersection V)).\napply B_subbasis_cond; trivial.\nrewrite <- H2 in H3.\ndestruct H3.\ndestruct H3.\n\nintros.\nexists (Intersection S1 S2); split; auto with sets.\nconstructor 3; trivial.\nDefined.\n\nLemma filter_from_subbasis_subbasis:\n  filter_subbasis Build_Filter_from_subbasis B.\nProof.\nassert (filter_basis Build_Filter_from_subbasis (finite_intersections B)).\napply filter_from_basis_basis.\ndestruct H.\nconstructor.\nassert (Included B (finite_intersections B)); auto with sets.\nred; intros.\nconstructor; trivial.\n\nintros.\ndestruct (filter_basis_cond0 S H) as [S' []].\npose proof (finite_intersection_is_finite_indexed_intersection\n  _ _ H0).\ndestruct H2 as [J [? [V []]]].\nexists J; split; trivial.\nexists V; split; trivial.\nrewrite <- H4; trivial.\nQed.\n\nEnd filter_from_subbasis.\n\nArguments Build_Filter_from_subbasis [X].\n\nDefinition ultrafilter {X:Type} (F:Filter X) : Prop :=\n  forall S:Ensemble X, In (filter_family F) S \\/\n                       In (filter_family F) (Ensembles.Complement S).\n\nRequire Import ZornsLemma.\n\nLemma ultrafilter_extension: forall {X:Type} (F:Filter X),\n  exists U:Filter X, Included (filter_family F) (filter_family U) /\\\n                     ultrafilter U.\nProof.\nintros.\npose (PO := { F':Filter X | Included (filter_family F) (filter_family F') }).\npose (PO_ord := fun (F1' F2':PO) =>\n  Included (filter_family (proj1_sig F1')) (filter_family (proj1_sig F2'))).\nassert (exists U:PO, premaximal PO_ord U).\napply ZornsLemmaForPreorders.\nconstructor.\nred; intro.\ndestruct x.\nred; simpl.\nauto with sets.\nred; intros.\ndestruct x; destruct y; destruct z.\nred in H; simpl in H.\nred in H0; simpl in H0.\nred; simpl.\nauto with sets.\n\nintros.\nRequire Import DecidableDec.\ndestruct (classic_dec (Inhabited S)) as [Hnonempty|Hempty].\nunshelve refine (let H0:=_ in let H1:=_ in let H2:=_ in let H3:=_ in\n  let ub:=Build_Filter X (IndexedUnion (fun F':{F':PO | In S F'} =>\n    filter_family (proj1_sig (proj1_sig F')))) H0 H1 H2 H3 in _);\n  [ | clearbody H0 | clearbody H0 H1 | clearbody H0 H1 H2 | clearbody H0 H1 H2 H3 ].\nintros.\ndestruct H0 as [F1'].\ndestruct H1 as [F2'].\ndestruct F1' as [[F1']].\ndestruct F2' as [[F2']].\nsimpl in H0.\nsimpl in H1.\ndestruct (H (exist _ F1' i) (exist _ F2' i1)); trivial.\nred in H2; simpl in H2.\napply H2 in H0.\nexists (exist _ (exist _ F2' i1)  i2).\nsimpl.\napply filter_intersection; trivial.\nred in H2; simpl in H2.\napply H2 in H1.\nexists (exist _ (exist _ F1' i) i0).\nsimpl.\napply filter_intersection; trivial.\n\nintros.\ndestruct H1 as [[[F1']]].\nsimpl in H1.\nexists (exist _ (exist _ F1' i) i0).\nsimpl.\napply filter_upward_closed with x; trivial.\ndestruct Hnonempty.\nexists (exist _ x H2).\nsimpl.\napply filter_full.\n\nred; intro.\ninversion_clear H3 as [F'].\ncontradict H4.\napply filter_empty.\n\nassert (Included (filter_family F) (filter_family ub)).\nsimpl.\nred; intros.\ndestruct Hnonempty.\nexists (exist _ x0 H5).\nsimpl.\ndestruct x0 as [F'].\nsimpl.\nauto.\n\nexists (exist _ ub H4).\nintros.\nred; simpl.\nred; intros.\nexists (exist _ y H5).\nsimpl.\ntrivial.\n\nassert (Included (filter_family F) (filter_family F)).\nauto with sets.\nexists (exist _ F H0).\nintros.\ncontradiction Hempty.\nexists y; trivial.\n\ndestruct H as [[U]].\nexists U; split; trivial.\nred; intros.\nclassical_right.\nassert (forall S':Ensemble X, In (filter_family U) S' ->\n  Inhabited (Intersection S' (Ensembles.Complement S))).\nintros.\napply NNPP; red; intro.\ncontradiction H0.\napply filter_upward_closed with S'; trivial.\nred; intros.\napply NNPP; red; intro.\ncontradiction H2.\nexists x.\nauto with sets.\n\nunshelve refine (let H2:=_ in let H3:=_ in let H4:=_ in\n  let Uext := Build_Filter_from_basis\n       (Im (filter_family U) (fun S':Ensemble X =>\n          Intersection S' (Ensembles.Complement S))) H2 H3 H4 in _).\nexists (Ensembles.Complement S).\nexists Full_set.\napply filter_full.\napply Extensionality_Ensembles; split; auto with sets.\nred; intros.\nconstructor; trivial; constructor.\nred; intro.\ninversion_clear H3 as [S'].\ndestruct (H1 S' H4) as [x].\nrewrite <- H5 in H3.\ndestruct H3.\n\nintros.\ndestruct H4.\ndestruct H5.\nexists (Intersection y y0).\nsplit; auto with sets.\nexists (Intersection x x0).\napply filter_intersection; trivial.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H8.\nrewrite H6 in H8; destruct H8.\nrewrite H7 in H9; destruct H9.\nconstructor; trivial; constructor; trivial.\ndestruct H8.\ndestruct H8.\nconstructor.\nrewrite H6; constructor; trivial.\nrewrite H7; constructor; trivial.\n\nassert (Included (filter_family U) (filter_family Uext)).\nred; intros.\napply filter_upward_closed with (Intersection x (Ensembles.Complement S)).\nassert (filter_basis Uext\n  (Im (filter_family U) (fun S':Ensemble X =>\n                        Intersection S' (Ensembles.Complement S)))).\napply filter_from_basis_basis.\ndestruct H6.\napply filter_basis_elements0.\nexists x; trivial.\nauto with sets.\nassert (Included (filter_family F) (filter_family Uext)).\nauto with sets.\n\nassert (PO_ord (exist _ U i) (exist _ Uext H6)).\nred.\nexact H5.\napply H in H7.\napply H7.\nchange (In (filter_family Uext) (Ensembles.Complement S)).\nassert (filter_basis Uext (Im (filter_family U)\n  (fun S':Ensemble X => Intersection S' (Ensembles.Complement S)))).\napply filter_from_basis_basis.\ndestruct H8.\napply filter_basis_elements0.\nexists Full_set.\napply filter_full.\napply Extensionality_Ensembles; split; auto with sets.\nred; intros.\nconstructor; trivial; constructor.\nQed.\n\nRequire Import InverseImage.\n\nDefinition filter_direct_image {X Y:Type} (f:X->Y) (F:Filter X) : Filter Y.\nrefine (Build_Filter Y\n  [ S:Ensemble Y | In (filter_family F) (inverse_image f S) ]\n  _ _ _ _).\nintros.\ndestruct H.\ndestruct H0.\nconstructor.\nrewrite inverse_image_intersection.\napply filter_intersection; trivial.\n\nintros.\ndestruct H.\nconstructor.\napply filter_upward_closed with (inverse_image f S1); auto with sets.\n\nconstructor.\nrewrite inverse_image_full.\napply filter_full.\n\nred; intro.\ndestruct H.\nrewrite inverse_image_empty in H.\nrevert H; apply filter_empty.\nDefined.\n\nSection filter_sum.\n\nVariable X:Type.\nVariable F G:Filter X.\nHypothesis F_G_compat: forall S T:Ensemble X,\n  In (filter_family F) S -> In (filter_family G) T ->\n  Inhabited (Intersection S T).\n\nDefinition filter_sum : Filter X.\nrefine (Build_Filter_from_basis\n  (Im [ p:(Ensemble X)*(Ensemble X) |\n        let (S,T):=p in In (filter_family F) S /\\\n                       In (filter_family G) T ]\n    (fun p:(Ensemble X)*(Ensemble X) => let (S,T):=p in\n       Intersection S T))\n  _ _ _).\nexists Full_set.\nexists ( (Full_set, Full_set) ).\nconstructor.\nsplit; apply filter_full.\napply Extensionality_Ensembles; split; red; intros.\nconstructor; constructor.\nconstructor.\n\nred; intro.\ninversion_clear H.\ndestruct x as [S T].\ndestruct H0.\ndestruct H.\nassert (Inhabited (Intersection S T)).\napply F_G_compat; trivial.\nrewrite <- H1 in H2.\ndestruct H2.\ndestruct H2.\nintros.\ndestruct H.\ndestruct x as [S1 T1].\ndestruct H0.\ndestruct H0.\ndestruct x as [S2 T2].\nexists (Intersection y y0).\nsplit; auto with sets.\ndestruct H0.\ndestruct H.\ndestruct H.\nexists ( (Intersection S1 S2, Intersection T1 T2) ).\nconstructor; split; apply filter_intersection; trivial.\nrewrite H1; rewrite H2.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H5.\ndestruct H5.\ndestruct H6.\nconstructor; constructor; trivial.\ndestruct H5.\ndestruct H5; destruct H6.\nconstructor; constructor; trivial.\nDefined.\n\nEnd filter_sum.\n\nArguments filter_sum [X].\n", "meta": {"author": "verimath", "repo": "topology", "sha": "9405aaf18d99c718769f1d2af8e030a902687837", "save_path": "github-repos/coq/verimath-topology", "path": "github-repos/coq/verimath-topology/topology-9405aaf18d99c718769f1d2af8e030a902687837/src/top/Filters.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.679859230976084}}
{"text": "Module Lecture1.\n  Require Import Arith.\n  Require Import List.\n\n  Definition AnIntegerExists : nat.\n  (* First prove by construction. Start with\n     Definition AnIntegerExists : nat := _.\n     and fill in the underscore. *)\n\n  Lemma AnIntegerExistsB : nat.\n  (* Then prove using tactics. Start with\n     \"Proof.\" and check out Coq's reports.\n     Tactics: `apply`, `intros`, `split`, `destruct`. *)\n\n\n  Definition Proj1 {A B:Prop} : A /\\ B -> A.\n\n  Lemma Proj1B {A B:Prop} : A /\\ B -> A.\n\n\n  (* Use `Locate`, `Check`, and `Print` to figure out\n     how <-> works. Start with `Locate \"_ <-> _\".` *)\n  Lemma ObjectivismB {A:Prop} : A <-> A.\n\n  Definition Objectivism {A:Prop} : A <-> A.\n\n\n  Lemma DistributeAnd {A B C:Prop} : \n    A /\\ (B \\/ C) -> (A /\\ B) \\/ (A /\\ C).\n\nEnd Lecture1.\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/l01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6798375116284001}}
{"text": "Require Import Arith.\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\n\nTheorem consLT : forall l1 n, (len l1) <= (len (Cons n l1)).\nProof.\n  intros. simpl. apply le_n_Sn.\nQed.\n\nTheorem appendLT : forall l1 l2, (len l1) <= (len (append l1 l2)).\nProof.\n    intros. induction l1.\n    - simpl. apply le_0_n.\n    - simpl. apply le_n_S. assumption.\nQed.\n\nTheorem appendLT2 : forall l1 l2, (len l2) <= (len (append l1 l2)).\nProof.\n    intros. induction l1.\n    - simpl. apply le_refl.\n    - simpl. apply Nat.le_le_succ_r. assumption.\nQed.\n\nLemma append_assoc: forall l1 l2 l3, append l1 (append l2 l3) = (append (append l1 l2) l3).\nAdmitted.\n\nLemma len_app_cons: forall l1 l2 n, len (append l1 (Cons n l2)) = S (len (append l1 l2)).\nAdmitted.\n\nTheorem appendLT3 : forall l1 l2, (len l1) <= (len (append (rev l1) l2)).\nProof.\n    induction l1.\n    - intros. simpl. apply le_0_n.\n    - intros. simpl. rewrite <- append_assoc. simpl. rewrite len_app_cons.\n      apply le_n_S. apply IHl1.\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/list_le.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6798375070057815}}
{"text": "\nRequire Import List Omega.\n\nRequire Import copy.\nRequire Import dither.\nRequire Import halting_defs.\nRequire Import shift.\nRequire Import shift_maxsource.\n\n(**************** WITNESS Machine ***************)\n\nDefinition witness :=\n  (app Copy\n  (app (shift HM     7)\n       (shift Dither (max_source HM 0 + 8)))).\n\n(*** Auxiliary properties for the 2nd path of Undecidability ***)\n\nLemma max_source_shift: forall M m n k,\n      m <= n ->\n      max_source (shift M m) (max_source M k + n) =\n      max_source M k + n.\ninduction M; intros.\n\nsimpl. reflexivity.\n\ndestruct a. destruct p. destruct p.\nsimpl. elim (le_gt_dec s0 k); intros.\nrewrite (gt_false s0 k).\nrewrite Nat.add_comm at 1.\nrewrite gt_false. apply IHM. assumption.\n\napply plus_le_compat.\nassert (k <= max_source M k). apply max_source_ge. omega.\nassumption. assumption.\n\nrewrite (gt_true s0 k).\nrewrite Nat.add_comm at 1.\nrewrite gt_false. apply IHM. assumption.\napply plus_le_compat. apply max_source_ge. assumption. assumption.\nQed.\n\nLemma maxsource_swap: forall M n a b,\n      max_source (cons a (cons b M)) n =\n      max_source (cons b (cons a M)) n.\nintros.\ndestruct a. destruct p. destruct p.\ndestruct b. destruct p. destruct p. simpl.\n\nelim (le_gt_dec s0 n); intros.\n\nrewrite gt_false.\nelim (le_gt_dec s3 n); intros.\n\nrewrite gt_false. reflexivity. assumption.\n\nrewrite gt_true. rewrite gt_false. reflexivity. omega.\nassumption. assumption.\n\nrewrite gt_true.\nelim (le_gt_dec s3 n); intros.\n\nrewrite gt_false. rewrite gt_false. reflexivity. assumption. omega.\n\nelim (le_gt_dec s3 s0); intros.\n\nrewrite gt_false. rewrite gt_true.\nassert (s3 < s0 \\/ s3 = s0). apply le_lt_or_eq. assumption.\nelim H; clear H a; intro.\n\nrewrite gt_true. reflexivity. assumption.\nrewrite H. rewrite gt_false. reflexivity.\nomega. assumption. assumption.\n\nrewrite gt_true. rewrite gt_true. rewrite gt_false. reflexivity.\nomega. assumption. assumption. assumption.\nQed.\n\nLemma max_source_1step: forall p a x q b M n,\n      max_source ((p, a, x, q) :: b :: M) n =\n      if gtstate p n then max_source (b :: M) p\n                     else max_source (b :: M) n.\nauto.\nQed.\n\nLemma maxsource_app_comm_item: forall M n a,\n      max_source (app M (cons a nil)) n = max_source (cons a M) n.\ninduction M; intros.\n\nsimpl. reflexivity.\n\nrewrite maxsource_swap.\ndestruct a. destruct p. destruct p.\n\nrewrite max_source_1step. simpl (max_source (((s0, s1, s, h) :: M) ++ a0 :: nil) n).\nelim (le_gt_dec s0 n); intros.\n\nrewrite gt_false. apply IHM. assumption.\n\nrewrite gt_true. apply IHM. assumption.\nQed.\n\nLemma maxsource_app_comm: forall M N n,\n      max_source (app M N) n = max_source (app N M) n.\ninduction M; intros.\n\nsimpl. rewrite <- app_nil_end. reflexivity.\n\nassert (N ++ a :: M = app (app N (cons a nil)) M).\nrewrite <- ass_app. rewrite <- app_comm_cons. auto.\nrewrite H; clear H. rewrite <- IHM.\n\nrewrite <- app_comm_cons. rewrite ass_app.\nrewrite <- maxsource_app_comm_item. reflexivity.\nQed.\n\nLemma max_source_HM_witness:\n      max_source witness 0 = max_source HM 0 + 9.\nsimpl.\nrewrite maxsource_app_comm.\nsimpl. rewrite (gt_true (max_source HM 0 + 8 + 0) 6).\nrewrite (gt_true (max_source HM 0 + 8 + 1) (max_source HM 0 + 8 + 0)).\nrewrite (gt_false (max_source HM 0 + 8 + 1) (max_source HM 0 + 8 + 1)).\n\nrewrite <- Nat.add_assoc. change (8+1) with 9.\n\napply max_source_shift. omega.\n\nomega. omega. omega.\nQed.\n", "meta": {"author": "asr", "repo": "tm-coinduction", "sha": "599083b74ffdf0c1032c5c2495fef9bf23a4058c", "save_path": "github-repos/coq/asr-tm-coinduction", "path": "github-repos/coq/asr-tm-coinduction/tm-coinduction-599083b74ffdf0c1032c5c2495fef9bf23a4058c/animation/halting/witness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6798375067981223}}
{"text": "Require Import ArithRing Div2 Bool Even Setoid Min List Aux Field VectorSpace Kn.\n\nSection Vect.\n\n(* This is our scalar space with its dimension *)\nVariable p : params.\n(* The operations for scalar have the expected properties *)\nHypothesis Hp : fparamsProp p.\n\nDeclare Scope g_scope.\nDelimit Scope g_scope with g.\nOpen Scope g_scope.\nOpen Scope vector_scope.\n\n(* We recover the usual mathematical notation *)\nDefinition K1 := K.\nNotation \"'K'\" := (K1 p) : g_scope.\nNotation \"'kn'\" := (kn p).\nNotation projk := (proj p).\n\nLtac Kfold n :=\n     change (Kn.add p n) with (addE (Kn.vn_eparams p n));\n     change (Kn.scal p n) with (scalE (Kn.vn_eparams p n));\n     change (Kn.genk p n 0%f) with (E0 (Kn.vn_eparams p n)).\n\n(* A vector is a full-binary tree of hight n *)\nFixpoint vect (n: nat): Set := \n  match n with O => K | S n1 => (vect n1 * vect n1)%type end.\n\n(* Equality over two trees: Equality on leaves *)\nFixpoint eq (n : nat) : vect n -> vect n -> bool :=\n  match n return (vect n -> vect n -> bool) with\n  | 0%nat => fun a b => (a ?= b)%f\n  | S n1 =>\n      fun l1 l2 =>\n      let (l3, l5) := l1 in\n      let (l4, l6) := l2 in \n      if eq n1 l3 l4 then eq n1 l5 l6 else false\n  end.\n\n(* Adding two trees: adding its leaves *)\nFixpoint add (n : nat) : vect n -> vect n -> vect n :=\n  match n return (vect n -> vect n -> vect n) with\n  | 0%nat => fun a b => (a + b)%f\n  | S n1 =>\n      fun l1 l2 =>\n      let (l3, l5) := l1 in\n      let (l4, l6) := l2 in (add n1 l3 l4, add n1 l5 l6)\n  end.\n\n(* Generate the constant k for the dimension n *)\nFixpoint genk (n: nat) (k: K) {struct n}: (vect n) :=\n   match n return vect n with 0%nat => k | n1.+1 => (genk n1 0%f, genk n1 k) end.\nNotation \" [ k ] \" := (genk _ k%f) (at level 9): g_scope.\nArguments genk _ _%field_scope.\n\n(* Multiplication by a scalar *)\nFixpoint scal (n : nat) (k: K) {struct n}: vect n -> vect n :=\n  match n return (vect n -> vect n) with\n  | 0%nat => fun a => (k * a)%f\n  | S n1 =>\n      fun l1 =>\n      let (l2, l3) := l1 in (scal n1 k l2, scal n1 k l3)\n  end.\n\nCanonical Structure vn_eparams (n: nat) :=\n  Build_eparams (vect n) K [0] (eq n) (add n) (scal n).\n\nDefinition fn n : vparamsProp (vn_eparams n).\napply Build_vparamsProp; auto.\n(* Equality *)\ninduction n as [| n IH]; simpl.\n  intros x y; apply eqK_dec; auto.\nintros (l3,l5) (l4, l6); simpl in IH; generalize (IH l3 l4); case eq.\n  generalize (IH l5 l6); case eq; intros HH1 HH2; subst; auto.\n  intros HH3; case HH1; injection HH3; auto.\nintros HH1 HH2; case HH1; injection HH2; auto.\n(* Addition is associative *)\ninduction n as [| n IH]; simpl.\n  intros x y z; rewrite (addK_assoc _ Hp); auto.\nintros (l3,l5) (l4, l6) (l7, l8); simpl in IH; rewrite !IH; auto.\n(* Addition is commutative *)\ninduction n as [| n IH]; simpl.\n  intros x y; rewrite (addK_com _ Hp); auto.\nintros (l3,l5) (l4, l6); simpl in IH; rewrite (IH l3), (IH l5); auto.\n(* 0 is  a left neutral element for + *)\ninduction n as [| n IH]; simpl.\n  intros x; rewrite (addK0l _ Hp); auto.\nintros (l1,l2); simpl in IH; rewrite IH, IH; auto.\n(* Multiplication by 0 *)\ninduction n as [| n IH]; simpl.\n  intros x; rewrite (multK0l _ Hp); auto.\nintros (l1, l2); simpl in IH; rewrite IH, IH; auto.\n(* Multiplication by 1 *)\ninduction n as [| n IH]; simpl.\n  intros x; rewrite (multK1l _ Hp); auto.\nintros (l1, l2); simpl in IH; rewrite IH, IH; auto.\n(* Left addition of the multiplication by a scalar *)\ninduction n as [| n IH]; simpl.\n  intros k x y; rewrite (add_multKl _ Hp); auto.\nintros k1 k2 (l1, l2); simpl in IH; rewrite IH, IH; auto.\n(* Right addition of the multiplication by a scalar *)\ninduction n as [| n IH]; simpl.\n  intros k x y; rewrite (add_multKr _ Hp); auto.\nintros k (l1, l3) (l2, l4); simpl in IH; rewrite IH, IH; auto.\n(* Composition of the multiplication by a scalar *)\ninduction n as [| n IH]; simpl.\n  intros x y z; rewrite (multK_assoc _ Hp); auto.\nintros k1 k2 (l1, l2); simpl in IH; rewrite IH, IH; auto.\nQed.\n\nHint Resolve fn : core.\n\nNotation \"1\" := ([1]): g_scope.\n\nLtac Vfold n :=\n     change (add n) with (addE (vn_eparams n));\n     change (scal n) with (scalE (vn_eparams n));\n     change (genk n 0) with (E0 (vn_eparams n)).\n\nHint Rewrite multK0l multK0r oppK0 addK0l addK0r \n             addE0r addE0l scalE0r scalE0l: GRm0.\n\nLtac Grm0 := autorewrite with GRm0; auto.\n\n(* Subtraction  *)\nFixpoint sub (n : nat) : vect n -> vect n -> vect n :=\n  match n return (vect n -> vect n -> vect n) with\n  | 0%nat => fun a b => (a + (- b))%f\n  | S n1 =>\n      fun v1 v2 =>\n      let (x1, y1) := v1 in\n      let (x2, y2) := v2 in (sub n1 x1 x2, sub n1 y1 y2)\n  end.\n\nNotation \"x - y\" := (sub _ x y): g_scope.\n\nLemma sub_add n (v1 v2: vect n) : v1 - v2 = v1 + (-(1)).* v2.\nProof.\ninduction n as [| n IH]; simpl; try Vfold n.\nrewrite <-opp_multKl, multK1l; auto.\ndestruct v1; destruct v2; rewrite !IH; auto.\nQed.\n\nLemma sub0l n (v: vect n) : 0 - v = (-(1)) .* v.\nProof. rewrite sub_add; Grm0. Qed.\n\nHint Rewrite sub0l: GRm0.\n\nLemma sub0r n (v: vect n) : v - 0 = v.\nProof. rewrite sub_add; Grm0. Qed.\n\nHint Rewrite sub0r: GRm0.\n\n(* Some properties of constants *)\nLemma injk n k1 k2 : [k1] = [k2] :> vect n -> k1 = k2.\nProof.\ninduction n as [| n IH]; simpl; auto.\nintros HH; injection HH; auto.\nQed.\n\nLemma oppk n k : [-k] = (-(1)).* [k] :> vect n.\nProof.\ninduction n as [| n IH]; simpl; try Vfold n.\nrewrite <- opp_multKl, multK1l; auto.\nrewrite scalE0r, IH; auto.\nQed.\n\nLemma genkE n k : [k] = k .* 1 :> vect n.\nProof.\ninduction n as [| n IH]; simpl; Krm1; try Vfold n.\nrewrite IH, scalE0r; auto.\nQed.\n\nLemma deck0 n (x: vect n):  x = 0 \\/ x <> 0.\nProof.\ninduction n as [| n IH]; simpl; auto.\ngeneralize (eqK_dec _ Hp x 0%f).\ncase eqK; auto.\ndestruct x as (x1, x2).\ncase (IH x1); auto; intros H1; subst.\ncase (IH x2); auto; intros H1; subst; auto.\nright; intro HH; case H1; injection HH; auto.\nright; intro HH; case H1; injection HH; auto.\nQed.\n\n(* Generate the p element of the base in dimension n *)\nFixpoint gen (n: nat) (p: nat) {struct n} : vect n :=\n  match n return vect n with 0 => 1%f | S n1 =>\n    match p with\n      0 => (genk n1 1%f, genk n1 0%f)\n    | S p1 =>  (genk n1 0%f, gen n1 p1) \n    end\n  end.\n\nNotation \"''e_' p\" := (gen _ p) (at level 8, format \"''e_' p\"): g_scope.\n\nLemma inj_e n p1 p2 : p1 < n -> p2 < n ->\n  'e_p1 = 'e_p2 :> vect n -> p1 = p2.\nProof.\ngeneralize p1 p2; clear p1 p2.\ninduction n as [| n IH]; auto.\nintros p1 p2 HH; contradict HH; auto with arith.\nintros [|p1]; intros [|p2]; simpl; auto;\n try (intros _ _ HH; injection HH; intros _ HH1;\n  case (one_diff_zero _ Hp); apply (injk n); auto).\nintros H1 H2 HH; injection HH; intros HH1.\nrewrite (IH p1 p2); auto with arith.\nQed.\n\n\n(* Get the constant part of a vector *)\nFixpoint const (n: nat): (vect n) -> K :=\n  match n return vect n -> K with \n  | O => fun a => a\n  | S n1 => fun l => let (l1,l2) := l in const n1 l2\n  end.\n\nNotation \"'C[ x ]\" := (const _ x).\n\nLemma const0 n : 'C[ 0: vect n ] = 0%f.\nProof. induction n as [| n IH]; simpl; auto. Qed.\n\nHint Rewrite const0: GRm0.\n\nLemma constk n k : 'C[[k]: vect n] = k.\nProof. induction n as [| n IH]; simpl; auto. Qed.\n\nLemma const_scal n k (x: vect n): 'C[k .* x] = (k * 'C[x])%f.\nProof.\ninduction n as [| n IH]; simpl; try Vfold n; auto.\ndestruct x; rewrite IH; auto.\nQed.\n\nLemma const_add n (x1 x2: vect n): 'C[x1 + x2] = ('C[x1] + 'C[x2])%f.\nProof.\ninduction n as [| n IH]; simpl; try Vfold n; auto.\ndestruct x1; destruct x2; rewrite IH; auto.\nQed.\n\n(* Equality to zero: Equality to zero on leaves *)\nFixpoint eq0 (n : nat) : vect n -> bool :=\n  match n return (vect n -> bool) with\n  | 0%nat => fun a => (a ?= 0)%f\n  | S n1 =>\n      fun l1 =>\n      let (l2, l3) := l1 in\n      if eq0 n1 l2 then eq0 n1 l3 else false\n  end.\n\nNotation \"x ?= 0\" := (eq0 _ x) (at level 70): g_scope.\n\n(* Equality to zero *)\nLemma eq0_dec n (x: vect n) : if x ?= 0 then x = 0 else x <> 0.\nProof.\ninduction n as [| n IH]; simpl.\n  apply eqK_dec; auto.\ndestruct x as [l1 l2]; generalize (IH l1); case eq0.\n  generalize (IH l2); case eq0; intros HH1 HH2; subst; auto.\n  intros HH3; case HH1; injection HH3; auto.\nintros HH1 HH2; case HH1; injection HH2; auto.\nQed.\n\nLemma eq0_spec n (x: vect n) : eq_Spec x 0 (x ?= 0).\nProof. generalize (eq0_dec n x); case eq0; intros; constructor; auto. Qed.\n\nLemma eq0I n : ((0: vect n) ?= 0) = true.\nProof.\ninduction n as [| n IH]; simpl.\ncase eqK_spec; auto.\nsimpl in IH; rewrite IH; auto.\nQed.\n\nLemma en_def n : 'e_n = 1 :> vect n.\nProof.\ninduction n as [| n IH]; simpl; auto.\nrewrite IH; auto.\nQed.\n\nLemma addk n k1 k2 : [k1] + [k2] = [k1 + k2] :> vect n.\nProof.\ninduction n as [|n IH]; simpl; auto; Vfold n.\nrewrite !IH; Vrm0.\nQed.\n\n(* scal is integral *)\nLemma scal_integral n k (x: vect n) : k .* x = 0 -> k = 0%f \\/ x = 0.\nProof.\ninduction n as [| n IH]; simpl.\n  intros; apply (multK_integral _ Hp k); auto.\ndestruct x; intros HH; injection HH; intros HH1 HH2.\ncase (IH _ _ HH1); case (IH _ _ HH2); auto.\nintros; right; apply f_equal2 with (f := @pair (vect n) (vect n)); auto.\nQed.\n\n(* Multiplication of a constant *)\nLemma scalk n k1 k2 : k1 .* [k2] = [k1 * k2] :> vect n.\nProof.\ninduction n as [| n IH]; simpl; auto.\ngeneralize IH; Vfold n; clear IH; intros IH.\nrewrite scalE0r, IH; auto.\nQed.\n\n(* Homogeneity *)\nFixpoint hom (n k : nat) {struct n} : vect n -> bool :=\n  match n return (vect n -> bool) with\n  | 0%nat => fun a => match k with O => true | S _ => a ?= 0 end\n  | S n1 =>\n      fun l1 =>\n       let (l2, l3) := l1 in\n       (match k with O => l2 ?= 0 | S k1 => hom n1 k1 l2 end) && hom n1 k l3\n  end.\n\nLemma homk0 n k : hom n k 0.\nProof.\ngeneralize k; clear k.\ninduction n as [|n IH]; simpl; auto.\n  intros [|k]; auto; rewrite eqKI; auto.\nintros [|k]; auto.\n  rewrite eq0I; simpl; auto.\nrewrite !IH; auto.\nQed.\n\nHint Resolve homk0 : core.\n\nLemma hom0K n k : hom n 0 [k].\nProof.\ninduction n as [|n IH]; simpl; auto.\ncase eq0_spec; auto.\nintros HH; case HH; auto.\nQed.\n\nHint Resolve hom0K : core.\n\nLemma const_hom n k x : hom n k x -> 0 < k -> 'C[x] = 0%f.\nProof.\ngeneralize k; clear k.\ninduction n as [|n IH]; intros [|k]; simpl; auto.\nintros _ H; contradict H; auto with arith.\ncase eqK_spec; auto; intros; discriminate.\nintros _ H; contradict H; auto with arith.\ndestruct x; rewrite andbP; intros (H1,H2) _.\napply (IH _ k.+1); auto with arith.\nQed.\n\nLemma hom0E n (x: vect n) : hom n 0 x -> x = ['C[x]].\nProof.\ninduction n as [| n IH]; simpl; auto.\ndestruct x; case eq0_spec; try (intros; discriminate).\nintros H H2; rewrite H, <-IH; auto.\nQed.\n\nLemma hom1e n i : i < n -> hom n 1 'e_i.\nProof.\ngeneralize i; clear i.\ninduction n as [|n IH]; simpl; auto.\n  intros k HH; contradict HH; auto with arith.\nintros [|k]; simpl; rewrite hom0K; intros HH.\napply homk0.\napply IH; auto with arith.\nQed.\n\nLemma homE n k1 k2 (x: vect n) : \n  hom n k1 x -> hom n k2 x -> k1 = k2 \\/ x = 0.\nProof.\nassert (aux: forall n k1 k2, hom n k1.+1 [k2] -> k2 = 0%f).\n  intros n1; elim n1; simpl; auto; clear n1.\n  intros _ k4; case eqK_spec; auto; intros; discriminate.\n  intros n1 IH k3 k4.\n  rewrite homk0; intros HH; apply (IH _ _ HH).\ngeneralize k1 k2 x; clear k1 k2 x.\nelim n; simpl; auto; clear n.\nintros [|k1] [|k2]; auto;\n  try (intros x; case eqK_spec; auto; intros; discriminate).\nintros n IH [|k1] [|k2] (x1, x2); auto.\ncase eq0_spec; try (intros; discriminate).\nrewrite !andbP; intros  H (_,H1) (_,H2).\ncase (IH _ _ _ H1 H2); intros; subst; auto.\ncase eq0_spec; try (intros; discriminate).\nrewrite !andbP; intros  H (_,H1) (_,H2).\ncase (IH _ _ _ H1 H2); intros; subst; auto.\nrewrite !andbP; intros  (H1,H2) (H3,H4).\ncase (IH _ _ _ H1 H3); intros; subst; auto.\ncase (IH _ _ _ H2 H4); intros; subst; auto.\nQed.\n\nLemma hom_lt n k v : n < k -> hom n k v -> v = 0.\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; intros [|k]; simpl; auto;\n  try (intros HH; contradict HH; auto with arith; fail).\ncase eqK_spec; auto; intros; discriminate.\ndestruct v as [x y]; intros H1; rewrite andbP; intros (H2, H3).\nrewrite (IH x k), (IH y k.+1); auto with arith.\nQed.\n\nLemma add_hom n k (x y: vect n) : \n  hom n k x -> hom n k y -> hom n k (x + y).\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; simpl; try (Vfold n).\n  intros k; case k; auto.\n  intros _; case eqK_spec; auto; intros Hx HH; try discriminate HH.\n  case eqK_spec; auto; intros Hy HH1; try discriminate HH1.\n  rewrite Hx; rewrite Hy; rewrite addK0l; auto.\n  rewrite eqKI; auto.\nintros [| k]; destruct x; destruct y; rewrite !andbP;\n  intros (H1, H2) (H3, H4); split; auto.\ngeneralize H1 H3; do 2 (case eq0_spec; try (intros; discriminate));\n  intros; subst; rewrite addE0l; auto.\nQed.\n\nHint Resolve add_hom : core.\n\nLemma scal_hom n k1 k2 (x: vect n) : \n  hom n k1 x -> hom n k1 (k2 .* x).\nProof.\ngeneralize k1; clear k1.\ninduction n as [| n IH]; simpl; try (Vfold n).\n  intros k1; case k1; auto.\n  intros _;  case eqK_spec; auto; intros Hx HH; try discriminate.\n  rewrite Hx; rewrite multK0r, eqKI; auto.\nintros [| k]; destruct x; rewrite !andbP; \n  intros (H1, H2); split; auto.\ngeneralize H1; case eq0_spec; try (intros; discriminate);\n  intros; subst; rewrite scalE0r, eq0I; auto.\nQed.\n\nHint Resolve scal_hom : core.\n\n(* Get homogeneity part *)\nFixpoint get_hom (n m : nat) {struct n} : vect n -> vect n :=\n  match n return (vect n -> vect n) with\n  | 0%nat => fun a => match m with O => a | S _ => 0 end\n  | S n1 =>\n      fun l1 =>\n       let (l2, l3) := l1 in\n       ((match m with O => [0] \n                 | S m1 => get_hom n1 m1 l2\n         end), get_hom n1 m l3)\n  end.\n\nLemma get_hom0 n m : get_hom n m [0] = [0].\nProof.\ngeneralize m; clear m; induction n as [|n IH]; \n  intros [|m]; simpl; auto; rewrite !IH; auto.\nQed.\n\nLemma get_homk0 n k: get_hom n 0 [k] = [k].\nProof.\ninduction n as [|n IH];  simpl; auto; rewrite !IH; auto.\nQed.\n\nLemma get_homkS n m k: get_hom n m.+1 [k] = [0].\nProof.\ninduction n as [|n IH];  simpl; auto; rewrite !IH, ?get_hom0; auto.\nQed.\n\nLemma get_hom_ei n m i :  i < n ->\n  get_hom n m 'e_i = match m with 1 => 'e_i | _ => [0] end.\nProof.\ngeneralize m i; clear m i; induction n as [|n IH].\nintros m i HH; contradict HH; auto with arith.\nintros [|[|m]] [|i] H; simpl; rewrite ?get_hom0; auto.\nrewrite IH; auto with arith.\nrewrite get_homk0; auto.\nrewrite !IH; auto with arith.\nrewrite get_homkS; auto.\nrewrite !IH; auto with arith.\nQed.\n\nLemma get_hom_scal n m k x : \n  get_hom n m (k .* x) = k .* get_hom n m x.\nProof.\ngeneralize m x; clear m x; induction n as [|n IH]; \n  intros [|m]; simpl; Krm0; intros [x y]; Vfold n; rewrite ?IH; Vrm0.\nQed.\n\nLemma get_hom_add n m x y : \n  get_hom n m (x + y) = get_hom n m x + get_hom n m y.\nProof.\ngeneralize m x y; clear m x y; induction n as [|n IH]; \n  intros [|m]; simpl; Krm0; intros [x1 x2] [y1 y2]; Vfold n; rewrite ?IH; Vrm0.\nQed.\n\nLemma get_hom_up n m x : n < m -> get_hom n m x = [0].\nProof.\ngeneralize m; clear m; induction n as [| n IH]; intros m Hnm.\ndestruct m; simpl; auto; contradict Hnm; auto with arith.\ndestruct m as [|m]; simpl; auto.\ncontradict Hnm; auto with arith.\ndestruct x as [x1 x2]; rewrite !IH; auto with arith.\nQed.\n\nFixpoint sum (n : nat) (f: (nat -> vect n)) (m : nat) {struct m} :\n    vect n :=\n  match m with\n  | 0%nat => f 0%nat\n  | S m1 => f m + sum n f m1\n  end.\n\nLemma sumEl n f m : \n  sum n f m.+1 = f 0%nat + sum n (fun m => f m.+1) m.\nProof.\ninduction m as [|m IH]; simpl; Vfold n.\nrewrite addE_com; auto.\nrewrite addE_swap with (x1 := f 0%nat); auto.\nrewrite <-IH; simpl; auto.\nQed.\n\nLemma sumEr n f m : sum n f m.+1 = f m.+1 + sum n f m.\nProof. simpl; auto. Qed.\n\nLemma sum_ext (n : nat) (f1 f2: (nat -> vect n)) (m : nat) :\n  sum n.+1 (fun m => (f1 m, f2 m)) m = (sum n f1 m, sum n f2 m).\nProof.\ninduction m as [|m IH]; simpl; auto.\nrewrite IH; auto.\nQed.\n\nLemma get_hom_sum n (x : vect n) :\n   x = sum n (fun m => get_hom n m x) n.\nProof.\ninduction n as [|n IH]; simpl; auto.\ndestruct x as [x y]; simpl.\nrewrite sum_ext.\nrewrite <-(IH y).\nchange (get_hom n n x) with\n       ((fun m : nat => match m with\n                      | 0 => [0]\n                      | m1.+1 => get_hom n m1 x\n                      end) n.+1).\nVfold n; rewrite <-sumEr, sumEl; Vrm0.\nrewrite <-IH, get_hom_up; Vrm0.\nQed.\n\nLemma hom_get_hom n (x : vect n) m : hom n m (get_hom n m x).\nProof.\ngeneralize m; induction n as [|n IH]; simpl; auto.\nintros []; auto.\nrewrite eqKI; auto.\nintros [|m1]; destruct x as [x1 x2].\nrewrite eq0I, IH; auto.\nrewrite !IH; auto.\nQed.\n\n(* First degre that is used to guess if a vector is homegene *)\nFixpoint first_deg (n : nat) {struct n} : vect n -> nat :=\n  match n return (vect n -> nat) with\n  | 0%nat => fun a => 0%nat\n  | S n1 =>\n      fun l1 =>\n      let (l2, l3) := l1 in\n      if l2 ?= 0 then first_deg n1 l3 else S (first_deg n1 l2)\n  end.\n\nLemma first_deg0 n : first_deg n 0 = 0%nat.\nProof.\ninduction n as [| n IH]; simpl; auto.\nrewrite eq0I; auto.\nQed.\n\nLemma first_deg0i n v : first_deg n v = 0%nat -> hom n 0 v.\nProof.\ninduction n as [| n IH]; simpl; auto.\ndestruct v.\ncase eq0_spec; intros H1 H2; simpl; auto.\ndiscriminate.\nQed.\n\nLemma hom_first_deg n k x : x <> 0 -> hom n k x -> first_deg n x = k.\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; intros [|k]; simpl; auto.\ncase eqK_spec; auto; try (intros; discriminate).\nintros H1 H2; case H2; auto.\ndestruct x; case eq0_spec; intros Hx Hy; subst; try (discriminate).\nrewrite andbP; intros (_, H1); apply IH; auto.\nintros H2; case Hy; subst; auto.\ntry (rewrite andbP; intros (H1,_); discriminate).\ndestruct x; rewrite andbP; case eq0_spec; intros Hx Hy (H1,H2).\napply IH; auto; intros H3; case Hy; subst; auto.\nrewrite (IH _ k); auto.\nQed.\n\n(* Lift a vector of dimension n into a vector of dimension n+1 whose\n   first component is 0 *)\nDefinition lift (n: nat) (v: vect n) : (vect n.+1) :=  ((0: vect n), v).\n\nNotation \" x ^'l \" := (lift _ x) (at level 9, format \"x ^'l\"): g_scope.\n\n(* Lift of generator of the base *)\nLemma gen_lift n i : 'e_i.+1 = 'e_i^'l :> vect n.+1.\nProof. auto. Qed.\n\n(* Lift on constant *)\nLemma lift_k n k : [k] = [k]^'l :> vect n.+1.\nProof. auto. Qed.\n\n(* Lift on add *)\nLemma lift_add n x y : (x + y)^'l = x^'l + y^'l :> vect n.+1.\nProof. unfold lift; simpl; Vfold n; rewrite addE0l; auto. Qed.\n\n(* Lift on scalar multiplication *)\nLemma lift_scal n (k: K) x :  (k .* x)^'l = k .* x^'l :> vect n.+1.\nProof. unfold lift; simpl; Vfold n; rewrite scalE0r; auto. Qed.\n\n(* Lift on the multiple product *)\nLemma lift_mprod (n: nat) (ks: list K) vs : ks *X* map (lift n) vs = \n  (ks *X* vs)^'l.\nProof.\ngeneralize vs; clear vs.\ninduction ks as [| k ks IH].\n  intros vs; rewrite !mprod0l; auto.\nintros [| v vs]; simpl; try rewrite mprod0r; auto.\nrewrite (mprod_S (vn_eparams n.+1)); auto.\nrewrite mprod_S; auto.\nrewrite IH, lift_add, lift_scal; auto.\nQed.\n\nLemma lift_cbl n l (x: vect n) :\n  cbl _ l x -> cbl _ (map (lift n) l) x^'l.\nProof.\nintros H; elim H; clear x H; auto.\napply cbl0.\nintros v Hv; apply cbl_in; apply in_map; auto.\nintros x y H1x H2x H1y H2y.\nrewrite lift_add; apply cbl_add; auto.\nintros k x H1x H2x.\nrewrite lift_scal; apply cbl_scal; auto.\nQed.\n\nLemma lift_inj n (x1 x2: vect n) : x1^'l = x2^'l -> x1 = x2.\nProof.\ndestruct n as [| n]; simpl; intros HH; injection HH; auto.\nQed.\n\n(* Dual lift*)\nDefinition dlift (n: nat) (v: vect n) : (vect n.+1) := (v,(0: vect n)).\n\nNotation \"x ^'dl\" := (dlift _ x) (at level 9, format \"x ^'dl\" ): g_scope.\n\nLemma dlift_add n x y : (x + y)^'dl = x^'dl + y^'dl :> vect n.+1.\nProof. unfold dlift; simpl; Vfold n; rewrite addE0l; auto. Qed.\n\nLemma dlift_scal n (k: K) x : (k .* x)^'dl = k .* x^'dl :> vect n.+1.\nProof. unfold dlift; simpl; Vfold n; rewrite scalE0r; auto. Qed.\n\nLemma dlift_mprod (n: nat) (ks: list K) vs :\n   ks *X* map (dlift n) vs = (ks *X* vs)^'dl.\nProof.\ngeneralize vs; clear vs.\ninduction ks as [| k ks IH].\n  intros vs; rewrite !mprod0l; auto.\nintros [| v vs]; simpl; try rewrite mprod0r; auto.\nrewrite (mprod_S (vn_eparams n.+1)); auto.\nrewrite mprod_S; auto.\nrewrite  IH, dlift_add, dlift_scal; auto.\nQed.\n\n(* Coordinates for k vector *)\nFixpoint proj (n: nat) k: (vect n) -> (list K) :=\n  match n return vect n -> list  K with \n  | O => fun a  =>\n          match k with | O => a::nil | _ => nil end\n  | S n1 => fun l => let (l1,l2) := l in \n          match k with | O => proj n1 k l2 | S k1 => \n           (proj n1 k1 l1 ++ proj n1 k l2)%list\n          end\n  end.\n\nLemma proj0 n x : proj n 0 x = 'C[x]:: nil.\nProof.\ninduction n as [| n IH]; simpl; auto.\ndestruct x; rewrite IH; auto.\nQed.\n\nLemma proj_hom0_eq n x y : \n  hom n 0 x -> hom n 0 y ->\n  nth 0 (proj n 0 x) 0%f = nth 0 (proj n 0 y) 0%f ->  x = y.\nProof.\ninduction n as [| n IH]; simpl; auto.\ndestruct x; destruct y.\ndo 2 (case eq0_spec; try (intros; discriminate)).\nintros; subst; apply f_equal2 with (f := @pair _ _); auto.\nQed.\n\nLemma proj_lt n m x : n < m -> proj n m x = nil.\nProof.\ngeneralize m; clear m.\ninduction n as [| n IH]; simpl; auto.\nintros [] H; auto; contradict H; auto with arith.\nintros [| m] H; destruct x; rewrite !IH; auto with arith.\nQed.\n\nLemma proj_homn_eq n x y : \n  hom n n x -> hom n n y ->\n  nth 0 (proj n n x) 0%f = nth 0 (proj n n y) 0%f ->  x = y.\nProof.\ninduction n as [| n IH]; simpl; auto.\ndestruct x; destruct y; rewrite !andbP; intros (H1,H2) (H3,H4).\nrewrite hom_lt with (2:= H2); auto with arith.\nrewrite hom_lt with (2:= H4); auto with arith.\nrewrite !(proj_lt n n.+1), <-!app_nil_end; auto with arith.\nintros H; rewrite (IH _ _ H1 H3); auto.\nQed.\n\nFixpoint all (n: nat): vect n :=\n  match n return vect n with\n  | 0 => 1\n  | S n1 => (all n1, 0: vect n1)\n  end.\n\nNotation \"'E'\" := (all _).\n \nLemma all_hom n : hom n n E.\nProof.\ninduction n as [| n IH]; simpl; auto.\nrewrite IH, homk0; auto.\nQed.\n\nHint Resolve all_hom : core.\n\n(* Base of k vector *)\nFixpoint base (n: nat) k:list (vect n) :=\n  match n return list (vect n) with \n  | O =>  match k with | O => 1%f::nil | _ => nil end\n  | S n1 => \n          match k with | O => \n                     map (lift n1) (base n1 k) | S k1 => \n           (map (dlift n1) (base n1 k1) ++ \n            map (lift n1) (base n1 k))%list\n          end\n  end.\n\nLemma proj_base_length n (x: vect n) k : \n  length (proj n k x) = length (base n k).\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; simpl.\nintros [| k]; auto.\nintros [| k]; destruct x; rewrite ?map_length; auto.\nrewrite !app_length, !map_length, !IH; auto.\nQed.\n\nLemma base0 n : base n 0 = 'e_n::nil.\nProof.\ninduction n as [| n IH]; simpl; rewrite ?IH; auto.\nQed.\n\nLemma base_lt_nil m n : m < n -> base m n = nil.\nProof.\ngeneralize n; clear n.\ninduction m as [| m IH]; intros [| n]; simpl; auto;\n  try (intros HH; contradict HH; auto with arith; fail).\nintros Hm; rewrite !IH; auto with arith.\nQed.\n\nLemma base_n n : base n n = all n::nil.\nProof.\ninduction n as [| n IH]; simpl; auto.\nrewrite IH, base_lt_nil; auto.\nQed.\n\nLemma base_length n k : length (base n k) = bin n k.\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; simpl base; intros [| k]; auto.\nrewrite base0; auto.\nrewrite app_length, !map_length, !IH, bin_def, Plus.plus_comm; auto.\nQed.\n\nLemma base_lift n k :  incl (map (lift n) (base n k)) (base n.+1 k).\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; intros [| k]; simpl; auto with datatypes.\nQed.\n\nLemma base_hom n k v : k <= n -> In v (base n k) -> hom n k v.\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; simpl; intros [| k]; auto.\nintros HH; contradict HH; auto with arith.\ndestruct v as [v1 v2].\nrewrite base0, en_def; simpl.\nintros _ [H1|[]]; injection H1; intros; subst.\nrewrite eq0I, hom0K; auto.\nintros HH; case (Lt.le_lt_or_eq k n); auto with arith; intros H1 H2; subst.\ncase (in_app_or _ _ _ H2); rewrite in_map_iff;\n  intros (v1, ([],Hv1)); simpl.\nrewrite IH, homk0; auto with arith.\nrewrite homk0, IH; auto with arith.\nrewrite base_n, base_lt_nil in H2; auto.\nsimpl in H2; case H2; intros []; simpl.\nrewrite all_hom, homk0; auto.\nQed.\n\nLemma proj_homk n (x: vect n) k : \n  hom n k x -> proj n k x *X* base n k = x.\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; simpl.\nintros [| k] Hx.\nrewrite (mprod_S (vn_eparams 0)); auto.\n    rewrite mprod0l, addE0r; auto.\n    simpl; rewrite multK1r; auto.\n  rewrite mprod0r.\ngeneralize Hx; case eqK_spec; auto.\nintros; discriminate.\nintros [|k ]; destruct x.\ncase eq0_spec; intros Hx Hx1; try discriminate; subst.\nrewrite lift_mprod, IH; auto.\nintros HH.\nrewrite (mprod_app (vn_eparams n.+1)); auto.\nrewrite  !lift_mprod, !dlift_mprod, !IH; auto.\nsimpl; Vfold n; rewrite addE0l, addE0r; auto.\ngeneralize HH; case hom; auto; intros; discriminate.\ngeneralize HH; case hom; auto; intros; discriminate.\nrewrite map_length, proj_base_length; auto.\nQed.\n\nLemma base_free n k : free _ (base n k).\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; simpl; auto.\nintros [|k] [|x [|]]; simpl; try (intros; discriminate); auto.\nrewrite (mprod_S (vn_eparams 0)); auto.\n  (* rewrite !mprod_S, !mprod0r, !addE0r; simpl; auto. *)\n  rewrite  !mprod0r, !addE0r; simpl; auto.\nrewrite multK1r; auto; intros _ HH k [HH1 | []]; subst; auto.\nintros _ _ k1 HH; case HH.\nintros [| k].\nrewrite base0; intros [| x []]; try (intros; discriminate); simpl.\nintros _.\nrewrite (mprod_S (vn_eparams n.+1)); auto.\nrewrite mprod0r; simpl; auto; Vfold n.\nrewrite en_def, scalE0r, addE0l, addE0r, scalk, multK1r; auto.\nintros HH; injection HH; intros HH1 k [HK | []]; subst.\napply injk with (1 := HH1); auto.\nintros l; rewrite app_length, !map_length.\nintros H1 H2 k1 Hk1.\ncase (list_split _ _ _ _ H1); intros l1 (l2, (Hl1, (Hl2, Hl3))); subst.\nrewrite mprod_app, lift_mprod, dlift_mprod in H2; try rewrite map_length; auto.\ninjection H2; Vfold n; rewrite addE0r, addE0l; auto; intros He1 He2.\ncase (in_app_or _ _ _ Hk1); intros H3.\napply (IH k l1); auto.\napply (IH k.+1 l2); auto.\nQed.\n\n(* Each generator is in the base *)\nLemma e_in_base1 n i : i < n -> In 'e_i (base n 1).\nProof.\ngeneralize i; clear i.\ninduction n as [| n IH].\n  intros p1 Hp1; absurd (p1 < 0); auto with arith.\nintros [| p1] Hp1; simpl; Vfold n; auto.\napply in_or_app; left; auto.\nchange (1: vect n, 0: vect n) with (dlift n (1)).\nrewrite base0, en_def; simpl; auto.\napply in_or_app; right; auto.\nchange (0: vect n, 'e_p1: vect n) with ('e_p1^'l:vect n.+1).\nrefine (in_map _ _ _ _);  auto with arith.\nQed.\n\n(* An element of the base is a generator *)\nLemma e_in_base1_ex n v : \n  In v (base n 1) -> exists p1, p1 < n /\\ v = 'e_p1.\nProof.\ninduction n as [| n IH]; intros HH.\n  inversion HH.\ndestruct v as [vv1 vv2].\ncase (in_app_or _ _ _ HH); rewrite in_map_iff;\n  intros (v, (Hv1, Hv2)); injection Hv1; intros H1 H2; subst; auto.\nexists 0%nat; split; auto with arith.\nrewrite base0, en_def in Hv2.\nsimpl in Hv2; case Hv2; intros HH1; subst; auto.\ncase HH1.\ncase (IH _ Hv2); auto; intros p1 (H1p1, H2p1).\nexists p1.+1; split; subst; auto with arith.\nQed.\n\n(* The length of the base is n *)\nLemma base1_length n : length (base n 1) = n.\nProof. rewrite base_length, bin_1; auto. Qed.\n\nLemma base1_S n:\n  base n.+1 1 = ('e_0: vect n.+1) :: map (lift n) (base n 1).\nProof. simpl; unfold dlift; simpl; rewrite base0, en_def; simpl; auto. Qed.\n\nLemma base_nil n k : n < k -> base n k = nil.\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; intros [| k] H; simpl; auto;\n  try (contradict H; auto with arith; fail).\nrewrite !IH; auto with arith.\nQed.\n\nLemma cbl1_hom1_equiv n (x: vect n) : cbl _ (base n 1) x <-> hom n 1 x.\nProof.\nsplit; intros Hx; elim Hx.\nrewrite homk0; auto.\nintros v Hv.\ncase (e_in_base1_ex _ _ Hv); intros i (Hi, Hei); subst.\napply hom1e; auto.\nintros y1 y2 _ Hy1 _ Hy2; apply add_hom; auto.\nintros k y _ Hy; apply scal_hom; auto.\nrewrite <- (proj_homk _ _ _ Hx).\napply mprod_cbl; auto.\nQed.\n\nLemma cblk_homk_equiv n k (x: vect n): cbl _ (base n k) x <-> hom n k x.\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; simpl; auto.\nintros [| k]; split; intros H; auto.\nreplace x with (x .* 1: vect 0).\napply cbl_scal.\nconstructor; auto with datatypes.\nrewrite scalk, multK1r; auto.\nelim H.\nrewrite eqKI; auto.\nintros v [].\nintros x1 y1 _; do 2 (case eqK_spec; auto; intros HH; subst; try (intros; discriminate)).\nVrm0; rewrite eqKI; auto.\nintros k1 x1 _; case eqK_spec; auto; intros HH HH1; subst; Vrm0;\n  try discriminate; rewrite eqKI; auto.\ngeneralize H; case eqK_spec; auto; intros; subst; try discriminate.\nconstructor.\nintros [| k]; destruct x as [x y]; split; intros HH.\ncase (cbl_map_inv _ _ (lift n) id id) with (5 := HH); auto.\nintros; apply (lift_add n).\nintros; apply (lift_scal n).\nintros x1 (H1x1, H2x1); injection H2x1; intros; subst.\nrewrite eq0I; simpl; rewrite <- IH; auto.\ngeneralize HH; case eq0_spec; try (intros; discriminate).\nintros H1 H2; subst.\napply cbl_map with (f := lift n) (g:= id); auto.\nintros; apply (lift_add n).\nintros; apply (lift_scal n).\nrewrite IH; auto.\nrewrite andbP; rewrite <-!IH.\ngeneralize HH; clear HH.\ngeneralize (base n k) (base n k.+1); intros l1 l2.\nassert (He: exists l3, l3 = (map\n (dlift n) l1 ++ map (lift n) l2)%list).\nexists (map (dlift n) l1 ++ map (lift n) l2)%list; auto.\nintros HH.\nchange (cbl (vn_eparams n) l1 (fst (x, y)) /\\ cbl (vn_eparams n) l2 (snd (x, y))).\ncase He; intros l3 Hl3; simpl in Hl3; rewrite <-Hl3 in HH; generalize Hl3.\nelim HH; clear HH Hl3.\nintros; split; constructor.\nsimpl; intros (x1, y1) H1 H2; subst.\ncase (in_app_or _ _ _ H1); rewrite in_map_iff; intros (v, (H1v, H2v));\n  injection H1v; intros; subst; split; constructor; auto.\nsimpl; intros (x1,x2) (y1, y2) Hx1 H1 H2 H3 H4; Vfold n.\nsplit; auto; simpl fst; simpl snd; apply cbl_add; auto.\ncase H1; auto.\ncase H3; auto.\ncase H1; auto.\ncase H3; auto.\nsimpl; intros k1 (x1, x2) Hx1 H1 H2.\nsplit; auto; simpl fst; simpl snd; apply cbl_scal; auto.\ncase H1; auto.\ncase H1; auto.\nrewrite andbP in HH; case HH; intros HH1 HH2.\nreplace (x,y) with (dlift n x + lift n y).\napply cbl_add.\napply cbl_incl with (l1 := map (dlift n) (base n k)); auto with datatypes.\napply cbl_map with (f := dlift n) (g:= id); auto.\nintros; apply (dlift_add n).\nintros; apply (dlift_scal n).\nrewrite IH; auto.\napply cbl_incl with (l1 := map (lift n) (base n k.+1)); auto with datatypes.\napply cbl_map with (f := lift n) (g:= id); auto.\nintros; apply (lift_add n).\nintros; apply (lift_scal n).\nrewrite IH; auto.\nsimpl; Vfold n; Vrm0; auto.\nQed.\n\nLemma cbl_base1_split n x :\n cbl _ (base n.+1 1) x -> exists k, exists y, cbl _ (base n 1) y /\\ x = ([k], y).\nProof.\nintros H; elim H; clear x H.\nexists (0%f); exists (0: vect n); split; auto; apply cbl0.\nintros v; rewrite base1_S; simpl In.\nintros [H1 | H1].\nexists (1%f: K); exists (0: vect n); split; auto; apply cbl0.\nrewrite in_map_iff in H1; case H1; intros y [H1y H2y].\nexists (0%f); exists y; split; auto.\napply cbl_in; auto.\nintros x y _ (k1,(y1, (H1y1, H2y1))) _ (k2,(y2, (H1y2, H2y2)));\n  subst x y.\nexists (k1 + k2)%f; exists (y1 + y2); split; auto.\napply cbl_add; auto.\nsimpl; Vfold n; rewrite addk; auto.\nintros k x _ (k1, (y, (H1y, H2y))); subst x.\nexists (k*k1)%f; exists ((k: K) .* y); split; auto.\napply cbl_scal; auto.\nsimpl; Vfold n; rewrite scalk; auto.\nQed.\n\nLemma cbl_base1_list_split n l:\n (forall x, In x l -> cbl _ (base n.+1 1) x) -> \n   exists lk, exists ly,\n    (forall i, In i lk -> (fst i) <> 0%f) /\\\n    (forall i, In i lk -> cbl _ (base n 1) (snd i)) /\\\n    (forall i, In i ly -> cbl _ (base n 1) i) /\\\n    perm l ((map (fun x => ([fst x],(snd x))) lk) ++ map (lift n) ly).\nProof.\ninduction l as [| a l1 IH]; auto.\nintros; exists (@nil (K * vect n)); exists (@nil (vect n)); repeat split.\nintros i HH; inversion HH.\nintros i HH; inversion HH.\nintros i HH; inversion HH.\nsimpl map; apply perm_id.\nintros Hi.\ncase IH; auto with datatypes.\nintros lk (ly, (H1ly, (H2ly, (H3ly, H4ly)))).\ncase (cbl_base1_split n a); auto with datatypes.\nintros k (y, (H1y, H2y)); subst a.\ngeneralize (eqK_dec _ Hp k 0%f); case eqK; intros Hk; try subst k.\nexists lk; exists (y::ly); repeat split; auto with datatypes.\nsimpl; intros i1 [Hi1 | Hi1]; try subst i1; auto.\napply perm_trans with \n  (2 := perm_cons_app _ y^'l (map (fun x => ([fst x], snd x)) lk)\n                 (map (lift n) ly)).\nsimpl; apply perm_skip; auto.\nexists ((k,y)::lk); exists ly; repeat split; auto with datatypes.\nsimpl; intros i1 [Hi1 | Hi1]; try subst i1; auto.\nsimpl; intros i1 [Hi1 | Hi1]; try subst i1; auto.\nsimpl; apply perm_skip; auto.\nQed.\n\n(* Ad-hoc inductive principe for vectors of degree k *)\nLemma hom_induct n k (P: vect n -> Prop) :\n  P 0 -> (forall v, In v (base n k) -> P v) ->\n     (forall v1 v2, P v1 -> P v2 -> P (v1 + v2)) ->\n     (forall k v, P v -> P (k .* v)) ->\n     (forall v, hom n k v -> P v).\nProof.\nintros H1 H2 H3 H4 v.\nrewrite <-cblk_homk_equiv; intros HH; elim HH; auto.\nQed.\n   \n(* Ad-hoc conjugate function in order to define the product *)\nFixpoint conj (n : nat) (b: bool) {struct n}: vect n -> vect n :=\n  match n return (vect n -> vect n) with\n  | 0%nat => fun a => if b then (- a)%f else a\n  | S n1 =>\n      fun l1 =>\n      let (l2, l3) := l1 in (conj n1 (negb b) l2, conj n1 b l3)\n  end.\n\nNotation \"x ^_ b\" := (conj _ b x)  (at level 30).\nNotation \"x ^_'t\" := (conj _ true x)  (at level 30).\nNotation \"x ^_'f\" := (conj _ false x)  (at level 30).\n\n(* Conjugate behave well with the sum *)\nLemma conj_add n b (x y: vect n) : (x + y) ^_ b = x ^_ b + y ^_ b.\nProof.\ngeneralize b; clear b.\ninduction n as [| n IH]; simpl.\n  intros []; auto; rewrite opp_addK; auto.\ndestruct x; destruct y; intros b; Vfold n.\nrewrite IH, IH; auto.\nQed.\n\n(* Conjugate is involutive *)\nLemma conj_invo n b (x: vect n) : x ^_ b ^_ b = x.\nProof.\ngeneralize b; clear b.\ninduction n as [| n IH]; simpl.\n  intros []; auto; rewrite opp_oppK; auto.\nintros vv; destruct x; rewrite !IH; auto.\nQed.\n\n(* Conjugate of 0 is 0 *)\nLemma conj0 n b : 0 ^_ b = (0 : vect n).\nProof.\ngeneralize b; clear b.\ninduction n as [| n IH]; simpl.\nintros []; auto; rewrite oppK0; auto.\nintros b; rewrite IH; rewrite IH; auto.\nQed.\n\nHint Rewrite conj0 : GRm0.\n\n(* Conjugate of k is -k *)\nLemma conjk n b k : [k] ^_ b=  if b then [-k] else ([k]: vect n).\nProof.\ninduction n as [| n IH]; simpl; try Vfold n; auto.\ndestruct b; auto; rewrite IH, conj0; auto.\nQed.\n\n(* removing negation *)\nLemma conj_neg n b (v: vect n) : v ^_ (negb b) = (-(1)) .*  (v ^_ b).\nProof.\ninduction n as [| n IH];simpl; auto.\ndestruct b; simpl; Krm1.\ndestruct v; Vfold n.\nrewrite negb_involutive, !IH, <-scal_multE; Krm1; rewrite scalE1; auto.\nQed.\n\n(* removing conj_true *)\nLemma conjt n (v: vect n) : v ^_'t = (-(1)) .*  (v ^_'f).\nProof. apply (conj_neg n false). Qed.\n\n(* Conjugate of a generator g is -g *)\nLemma conj_e n b i : i < n ->\n  'e_i ^_ b = if b then ('e_i: vect n) else (- (1)).* 'e_i.\nProof.\ngeneralize i; clear i.\ninduction n as [| n IH]; simpl; try (Vfold n).\n  intros i H; absurd (i < 0); auto with arith.\nintros [| i] H.\n  rewrite conj0, scalE0r, conjk; case b; auto.\n  rewrite scalk, multK1r; auto.\nrewrite IH; auto with arith.\nrewrite conj0, scalE0r; case b; auto.\nQed.\n\n(* Conjugate behaves well with scalar multiplication *)\nLemma conj_scal n b k (x: vect n) : (k .* x) ^_ b = k .* x ^_ b.\nProof.\ngeneralize b; clear b.\ninduction n as [| n IH]; simpl; try Vfold n.\n  intros []; auto; rewrite opp_multKr; auto.\nintros []; destruct x; rewrite IH, IH; auto.\nQed.\n\nLemma conj_hom n b k (x: vect n) : hom n k x -> hom n k (x ^_ b).\nProof.\ngeneralize b k; clear b k.\ninduction n as [| n IH]; simpl.\n  intros [|] [|k]; auto.\n  case eqK_spec; auto; intros HH HH1; try discriminate.\n  rewrite HH, oppK0, eqKI; auto.\nintros b [|k]; destruct x; rewrite !andbP; intros (H1, H2); split; auto.\ngeneralize H1; case eq0_spec; intros Hx1 HH; try discriminate.\n  rewrite Hx1, conj0, eq0I; auto.\nQed.\n\nHint Resolve conj_hom : core.\n\nLemma conjf_hom n k (M: vect n) : hom n k M -> M ^_'f = (- (1))^k .* M.\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH];simpl; auto; try Vfold n.\nintros [|k] H; simpl; Krm1.\ngeneralize H; case eqK_spec; try (intros; discriminate); auto.\nintros H1; rewrite H1; Krm0.\nintros [| k]; destruct M; rewrite andbP; intros (HM1, HM2);\n  rewrite conjt; simpl; Vfold n; Krm1.\ngeneralize HM1; case eq0_spec; try (intros; discriminate); auto.\nintros H1; rewrite H1, (IH _ _ HM2); simpl; Vfold n; Krm1.\nrewrite conj0; Vrm0.\nrewrite (IH _ _ HM1), (IH _ _ HM2).\nsimpl; Vfold n; rewrite <-!scal_multE; Krm1.\nQed.\n\nLemma conjt_hom n k (M: vect n) : hom n k M -> M ^_'t = (- (1))^k.+1 .* M.\nProof.\nintros HH; rewrite conjt, (conjf_hom n k); auto.\nsimpl; Vfold n; rewrite scal_multE; auto.\nQed.\n\nLemma conj_const n b (x: vect n) : 'C[x ^_ b] = if b then (-'C[x])%f else 'C[x].\nProof.\ngeneralize b; clear b.\ninduction n as [|n IH]; simpl; auto.\nintros []; destruct x; rewrite IH; auto.\nQed.                      \n\n(* We can swap add-hoc conjugate *)\nLemma conj_swap n b1 b2 (x: vect n) : x ^_ b2 ^_ b1 =  x ^_ b1 ^_ b2.\nProof.\ncase b1; case b2; rewrite ?conjt, ?conj_scal, !conj_invo; auto.\nQed.\n\n(* Conjugate of 0 is 0 *)\nLemma conj_all n b: (E  ^_ b) = \n   (if b then (-((-(1))^ n))%f else ((-(1))^ n)%f) .* E :> vect n.\nProof.\ngeneralize b; clear b.\ninduction n as [| n Hrec]; simpl; auto.\nintros b; Krm1.\nintros b; repeat rewrite Hrec;\n  case b; simpl; auto; rewrite conj0; Vfold n; Vrm0.\nrewrite <-opp_multK1l; Krm1.\nrewrite <-opp_multK1l; auto.\nQed.\n\n(* We are now ready to define our multiplication *)\nFixpoint join (n : nat) : vect n -> vect n -> vect n :=\n  match n return (vect n -> vect n -> vect n) with\n  | 0%nat => fun x y => (x * y)%f\n  | S n1 =>\n      fun x y =>\n      let (x1, x2) := x in\n      let (y1, y2) := y in (join n1 x1 y2 + join n1 (x2 ^_'f) y1, \n                             join n1 x2 y2)\n  end.\n\n(* Unicode u2228 *)\nNotation \"x '∨' y\" := (join _ x y) (at level 40, left associativity): type_scope.\n\n(* (k.x) \\/  y = k. (x \\/ y) *)\nLemma join_scall n k (x y : vect n) : k .* x ∨ y = k .* (x ∨ y).\nProof.\ninduction n as [| n IH]; simpl; try Vfold n.\nrewrite multK_assoc; auto.\ndestruct x; destruct y; rewrite scal_addEr, conj_scal, !IH; auto.\nQed.\n\nLemma join0 (v1 v2: vect 0) : v1 ∨ v2 = (v1 ∨ v2)%f.\nProof. auto. Qed.\n\n(* 0 \\/ x = 0 *)\nLemma join0l n (x : vect n) : 0 ∨ x = 0.\nProof.\ninduction n as [| n IH]; simpl; try Vfold n.\n  rewrite multK0l; auto.\ndestruct x; rewrite IH, conj0, IH; Vrm0.\nQed.\n\nHint Rewrite join0l : GRm0.\n\n(* x \\/ 0  = 0 *)\nLemma join0r n (x : vect n) : x ∨ 0 = 0.\nProof.\ninduction n as [| n IH]; simpl; try Vfold n.\n  rewrite multK0r; auto.\ndestruct x; rewrite !IH; Vrm0.\nQed.\n\nHint Rewrite join0r: GRm0.\n\nLemma joinkl n k (x : vect n) : [k] ∨ x = k .* x.\nProof.\ninduction n as [| n IH]; simpl; auto; Vfold n.\ndestruct x; rewrite IH, conjk, join0l, addE0l, IH; auto.\nQed.\n\n(* x ∨ 1 = 1 *)\nLemma joinkr n k (x : vect n) : x ∨ [k] = k .* x.\nProof.\ninduction n as [| n IH]; simpl; auto; try Vfold n.\nrewrite multK_com; auto.\ndestruct x; rewrite !IH, join0r, addE0r; auto.\nQed.\n\n(* 1 \\/ x  = x *)\nLemma join1l n (x : vect n) : 1 ∨ x = x.\nProof. rewrite joinkl, scalE1; auto. Qed.\n\n(* x \\/ 1 = 1 *)\nLemma join1r n (x : vect n) : x ∨ 1 = x.\nProof. intros; rewrite joinkr, scalE1; auto. Qed.\n\nLemma join_alll n (x: vect n) : all n ∨ x = 'C[x] .* all n.\nProof.\ninduction n as [| n IH]; simpl; try Vfold n.\nsimpl; rewrite multK_com; auto.\ndestruct x; rewrite conj0, !join0l, addE0r, IH; auto.\nsimpl; Vfold n; rewrite scalE0r; auto.\nQed.\n\nLemma join_allr n (x: vect n) : x ∨ all n = 'C[x] .* all n.\nProof.\ninduction n as [| n IH]; simpl; auto; Vfold n.\ndestruct x; rewrite !join0r, addE0l, IH; auto.\nsimpl; Vfold n; rewrite scalE0r, conj_const; auto.\nQed.\n\nLemma join_allhr k n x : hom n k x -> 0 < k -> x ∨ E = 0.\nProof.\nintros Hh Hl; rewrite join_allr, (const_hom n k), scalE0l; auto.\nQed.\n\nLemma join_allhl k n x : hom n k x -> 0 < k -> E ∨ x = 0.\nProof.\nintros Hh Hl; rewrite join_alll, (const_hom n k), scalE0l; auto.\nQed.\n\n(* x \\/ (k.y) = k. (x \\/ y) *)\nLemma join_scalr n k (x y : vect n) : x ∨ (k .* y) = k .* (x ∨ y).\nProof.\ninduction n as [| n IH]; simpl; try Vfold n.\n  rewrite (multK_com _ Hp x), (multK_com _ Hp x), \n                        multK_assoc; auto.\ndestruct x; destruct y; apply f_equal2 with (f := @pair _ _); auto.\nrewrite IH, IH, <- scal_addEr; auto.\nQed.\n\nLemma joink n k1 k2 : [k1] ∨ [k2] = [k1 * k2] :> vect n.\nProof. rewrite joinkl, <- scalk; auto. Qed.\n\nLemma join_e0 n (M : vect n.+1) : 'e_0 ∨ M = (snd M, [0]).\nProof.\ndestruct M; simpl; Vfold n.\nrewrite conj0, !join0l, joinkl, scalE1; Vrm0.\nQed.\n\nLemma join_ei n i (M : vect n.+1) : i < n ->\n  'e_i.+1 ∨ M =  ((-(1))%f .* ('e_i ∨ fst M), 'e_i ∨ snd M).\nProof.\nintros HH; destruct M; simpl; Vfold n.\nrewrite join0l, conj_e, join_scall; Vrm0.\nQed.\n\n(* g_i \\/ g_j + g_j \\/ g_i = 0 *)\nLemma join_es n i j : \n   i < n -> j < n -> 'e_ i ∨ 'e_ j + 'e_ j ∨ 'e_ i = (0: vect n).\nProof.\ngeneralize i j; clear i j.\ninduction n as [| n IH]; simpl; try Vfold n.\n  intros i j H; absurd (i < 0); auto with arith.\nintros [|i] [|j].\n   rewrite join0l, join0r, conj0, join0l, addE0r, addE0r; auto.\nintros H1 H2.\n   rewrite join0l, join0r, join1r, join1l, join0l, addE0l,\n           addE0r, join0r, addE0r, conj_e; simpl; auto with arith.\n   Vfold n; pattern (gen n j) at 1;  \n   replace (gen n j) with (1.* (gen n j)) by (rewrite scalE1; auto).\n   rewrite <- scal_addEl, oppKr, scalE0l; auto.\nintros H1 H2.\n   rewrite join0l, join0r, join1r, join1l, join0l, addE0l, addE0r,\n           join0r, addE0r, conj_e; simpl; auto with arith.\n   Vfold n; pattern (gen n i) at 2;  \n   replace (gen n i) with (1.* (gen n i)) by (rewrite scalE1; auto).\n   rewrite <- scal_addEl, oppKl, scalE0l; auto.\nintros H1 H2.\nrewrite join0l, join0r, IH; try rewrite join0l;\n  try rewrite join0r; try rewrite addE0l; try rewrite addE0l; auto with arith.\nQed.\n\n(* g_i \\/ g_i = 0 *)\nLemma join_e n i : i < n -> 'e_ i ∨ 'e_ i = (0 : vect n).\nProof.\ngeneralize i; clear i.\ninduction n as [| n IH]; simpl; try Vfold n.\n  intros i Hi; absurd (i < 0); auto with arith.\nintros [|i] Hi.\n rewrite join0l, join0r, addE0l, conj0, join0l; auto.\nrewrite IH, join0l, join0r, addE0l; auto with arith.\nQed.\n\n(* (x + y) \\/ z = (x \\/ z) + (y \\/ z) *)\nLemma join_addl n (x y z : vect n) : (x + y) ∨ z = x ∨ z + y ∨ z.\nProof.\ninduction n as [| n IH]; simpl; try Vfold n.\napply (add_multKl p); auto.\ndestruct x; destruct y; destruct z.\napply f_equal2 with (f := @pair _ _); rewrite IH; auto.\nrewrite conj_add, !addE_assoc; auto.\napply f_equal2 with (f := add n); auto.\nrewrite IH, addE_com, !addE_assoc; auto.\napply f_equal2 with (f := add n); auto.\nrewrite addE_com; auto.\nQed.\n\n(* z \\/ (x + y) = (z \\/ x) + (z \\/ y) *)\nLemma join_addr n (x y z : vect n) : z ∨ (x + y) = z ∨ x + z ∨ y.\nProof.\ninduction n as [| n IH]; simpl; try Vfold n.\nintros; apply (add_multKr p); auto.\ndestruct x; destruct y; destruct z.\napply f_equal2 with (f := @pair _ _); rewrite IH; auto.\nrewrite !addE_assoc; auto.\napply f_equal2 with (f := add n); auto.\nrewrite IH, addE_com,!addE_assoc; auto.\napply f_equal2 with (f := add n); auto.\nrewrite addE_com; auto.\nQed.\n\nLemma conjf_join n (x y: vect n) : (x ∨ y) ^_'f =  x ^_'f ∨ y ^_'f.\nProof.\ninduction n as [| n IH]; auto; simpl; Vfold n.\ndestruct x; destruct y.\nrewrite conj_add, IH, !conjt, !IH, conj_invo, !join_scall,\n        !join_scalr; auto.\nQed.\n\n(* We are now ready to prove associativity ! *)\nLemma join_assoc n (x y z : vect n) : x ∨ y ∨ z = x ∨ (y ∨ z).\nProof.\ninduction n as [| n IH]; simpl; try Vfold n.\nrewrite multK_assoc; auto.\ndestruct x; destruct y; destruct z.\napply f_equal2 with (f := @pair _ _).\n  2: rewrite IH; auto.\nrewrite join_addr, join_addl, !addE_assoc; auto.\nrepeat apply f_equal2 with (f := add n); auto.\nrewrite <- IH.\napply f_equal2 with (f := join n); auto.\nrewrite conjf_join; auto.\nQed. \n\n(* Anti-commutativity is stable by linear combination *)\nLemma cbl_join_com n (vs: list (vect n)) :\n  (forall x y, In x vs -> In y vs -> y ∨ x = (- (1)).* (x ∨ y)) ->\n  forall x y, cbl _ vs x -> cbl _ vs y -> y ∨ x = (- (1)).* (x ∨ y).\nProof.\nintros H x y Hx; elim Hx; clear x Hx.\nintros; rewrite join0l; rewrite join0r; rewrite scalE0r; auto.\nintros vx Hvx Hy; elim Hy; clear y Hy; auto.\nrewrite join0l, join0r, scalE0r; auto.\nintros x y Hx Hx1 Hy Hy1; rewrite join_addl, Hx1, Hy1, <- scal_addEr,\n                                  join_addr; auto.\nintros k x Hx Hx1.\n  rewrite join_scall, Hx1, <- scal_multE, join_scalr, <- scal_multE, multK_com; auto.\nintros x y1 Hx Hxrec Hy1 Hy1rec Hy.\nrewrite join_addr, Hxrec, Hy1rec; auto.\nrewrite <- scal_addEr, join_addl; auto.\nintros k x Hx Hxrec Hy.\nrewrite join_scalr, Hxrec, <- scal_multE, join_scall, <- scal_multE, multK_com; auto.\nQed.\n\n(* Anti-commutativity is true for the base *)\nLemma cbl_base_join_com n x y :\n cbl _ (base n 1) x -> cbl _ (base n 1) y ->  y ∨ x = (- (1)).* (x ∨ y).\nProof.\napply (cbl_join_com n).\nintros x1 y1 Hx Hy.\ncase (e_in_base1_ex _ _ Hx); intros i (Hi, Hi1).\ncase (e_in_base1_ex _ _ Hy); intros j (Hj, Hj1).\nrewrite Hi1; rewrite Hj1.\nrewrite <- (addE0l (vn_eparams n)); auto.\n rewrite <- (join_es n j i), addE_assoc, scal_addE0, addE0r; auto.\nQed.\n\n(* x*x = 0 is stable by linear combination *)\nLemma cbl_join_id n vs : \n  (forall x y, In x vs -> In y vs -> join n y x = (- (1)).* (x ∨ y)) ->\n  (forall x, In x vs -> x ∨ x = 0) -> forall x, cbl _ vs x -> x ∨ x = 0.\nProof.\nintros H H1 x Hx; elim Hx; clear x Hx; auto.\nintros; rewrite join0l; auto.\nintros x y Hx Hxrec Hy Hyrec.\nrewrite join_addr, join_addl, \n        join_addl, Hxrec, Hyrec, addE0l, addE0r; auto.\nrewrite (cbl_join_com _ _ H x), addE_com, scal_addE0;  auto.\nintros k x Hx IH; rewrite join_scall, join_scalr, IH, scalE0r, scalE0r; auto.\nQed.\n\n(* x*x = 0 is true for the base *)\nLemma cbl_base_join_id n x : cbl _ (base n 1) x -> x ∨ x = 0.\nProof.\nintros Hx; apply (cbl_join_id n (base n 1)); auto; clear x Hx.\nintros x y Hx Hy.\ncase (e_in_base1_ex _ _ Hx); intros i (Hi, Hi1).\ncase (e_in_base1_ex _ _ Hy); intros j (Hj, Hj1).\nrewrite Hi1; rewrite Hj1.\nrewrite <- (addE0l (vn_eparams n)), <- (join_es n j i), addE_assoc, scal_addE0, addE0r; auto.\nintros x Hx.\ncase (e_in_base1_ex _ _ Hx); intros i (Hi, Hi1).\nrewrite Hi1, join_e; auto.\nQed.\n\nLemma join_hom1_id n x : hom n 1 x -> x ∨ x = 0.\nProof.\nrewrite <-cbl1_hom1_equiv.\nintros; apply cbl_base_join_id; auto.\nQed.\n\n(* Lift for the production *)\nLemma lift_join n x y : lift n (x ∨ y) = lift n x ∨ lift n y.\nProof.\nunfold lift; simpl; try Vfold n.\nrewrite join0l, addE0l, join0r; auto.\nQed.\n\nLemma join_hom n k1 k2 (x y: vect n) : \n  hom n k1 x -> hom n k2 y -> hom n (k1 + k2) (x ∨ y).\nProof.\ngeneralize k1 k2; clear k1 k2.\ninduction n as [| n IH]; simpl; try Vfold n.\n  intros [|k1] [|k2]; simpl; auto.\n  intros _; case eqK_spec; auto; intros HH HH1; try discriminate.\n    rewrite HH, multK0r, eqKI; auto.\n  case eqK_spec; auto; intros HH HH1 _; try discriminate.\n    rewrite HH, multK0l, eqKI; auto.\n  intros _; case eqK_spec; auto; intros HH HH1; try discriminate.\n    rewrite HH, multK0r, eqKI; auto.\nintros [|k1] [|k2];\n    destruct x as [x1 x2]; destruct y as [y1 y2]; simpl; auto; Vfold n.\ncase eq0_spec; case eq0_spec; try (intros; discriminate);\n  intros HH1 HH2; subst.\n  rewrite join0l, join0r, addE0l, eq0I; auto; intros HH1 HH2.\n  rewrite (hom0E _ _ HH1), (hom0E _ _ HH2), joink, hom0K; auto.\ncase eq0_spec; try (intros; discriminate);\n  intros HH1 HH2 HH3; subst.\n  rewrite join0l, addE0l; auto.\n  generalize (IH x2 y1 0%nat k2.+1 HH2).\n  intros HH4.\n  rewrite (IH _ _ 0%nat k2); auto.\n  apply (IH _ _ 0%nat k2.+1); auto.\n  generalize HH3; case hom; auto; intros; discriminate.\n  generalize HH3; case hom; auto.\ncase eq0_spec; try (intros; discriminate);\n  intros HH1 HH2 HH3; subst.\n  rewrite join0r, addE0r, <- plus_n_O; auto.\n  pattern k1 at 1; rewrite (plus_n_O k1).\n  rewrite IH; auto.\n  rewrite  (plus_n_O k1.+1).\n  apply IH; auto.\n  generalize HH2; case hom; auto; intros; discriminate.\n  generalize HH2; case hom; auto; intros; discriminate.\nintros HH1 HH2.\nassert (Hx1: hom n k1 x1).\n  generalize HH1; case hom; auto.\nassert (Hx2: hom n k1.+1 x2).\n  generalize HH1; rewrite Hx1; auto.\nassert (Hy1: hom n k2 y1).\n  generalize HH2; case hom; auto.\nassert (Hy2: hom n k2.+1 y2).\n  generalize HH2; rewrite Hy1; auto.\nrewrite add_hom; auto.\napply (IH _ _ k1.+1 k2.+1); auto.\nrewrite <- Plus.plus_Snm_nSm.\napply IH; auto.\nQed.\n\nHint Resolve join_hom : core.\n\nLemma join_big n k1 k2 (x y : vect n) : \n  hom n k1 x -> hom n k2 y -> n < k1 + k2 -> x ∨ y = 0.\nProof. intros Hx Hy Hlt; apply hom_lt with (k1 + k2)%nat; auto. Qed.\n\nLemma const_join n (x y: vect n): 'C[x ∨ y] = ('C[x] * 'C[y])%f.\nProof.\ninduction n as [| n IH]; auto; simpl; try Vfold n.\ndestruct x; destruct y; simpl; auto.\nQed.\n\nLemma lift_decomp n (x y: vect n) : (x, y) = 'e_0 ∨ x^'l + y^'l.\nProof.  simpl; Vfold n; rewrite conj0, !join0l, !addE0r, addE0l, join1l; auto.\nQed.\n\n(* Base as product *)\nLemma base_in n k x: In x (base n k.+1) -> \n    exists i, exists y, x = 'e_i ∨ y /\\ In y (base n k). \nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; simpl.\nintros k [].\nintros [| k] HH; destruct x as [x1 x2].\ncase (in_app_or _ _ _ HH); rewrite in_map_iff;\n  intros (x, (H1x, H2x)); injection H1x; intros; subst.\nexists 0%nat; exists (lift n x1); simpl; split; Vfold n.\nrewrite join0l, join0r, join1l, addE0r; auto .\napply in_map; auto.\ncase (IH x2 0%nat); auto; intros i (y, (H1y, H2y)).\nexists (1 + i)%nat; exists (lift n y); simpl; split; Vfold n.\nrewrite join0l, join0r, addE0r, H1y; auto .\napply in_map; auto.\ncase (in_app_or _ _ _ HH); rewrite in_map_iff;\n  intros (x, (H1x, H2x)); injection H1x; intros; subst.\nexists 0%nat; exists (lift n x1); simpl; split; Vfold n.\nrewrite join0l, join0r, join1l, addE0r; auto .\napply in_or_app; right; apply in_map; auto.\ncase (IH x2 k.+1%nat); auto; intros i (y, (H1y, H2y)).\nexists (1 + i)%nat; exists (lift n y); simpl; split; Vfold n.\nrewrite join0l, join0r, addE0r, H1y; auto .\napply in_or_app; right; apply in_map; auto.\nQed.\n\n(* given a list of vectors produce the list of all products *)\nFixpoint all_prods (n: nat) (vs: list (vect n)) {struct vs} : list (vect n) :=\n  match vs with\n    nil => 1 :: nil\n  | v::vs1 => let vs1 := all_prods n vs1 in \n                (map (join n v) vs1 ++ vs1)%list\n  end.\n\n(* 1 is the only element of empty product *)\nLemma all_prods_nil n : all_prods n nil = 1 :: nil.\nProof. auto. Qed.\n\n(* Recursive definition of all products *)\nLemma all_prods_cons n v vs : \n  all_prods n (v :: vs) = (map (join n v) (all_prods n vs) ++ (all_prods n vs))%list.\nProof. auto. Qed.\n\n(* 1 is always in the list of all products *)\nLemma all_prods1 n vs : In (1) (all_prods n vs).\nProof. induction vs as [| v vs IH]; simpl; auto with datatypes. Qed.\n\n(* The initial vectors are in the list of all products *)\nLemma all_prods_id n vs : incl vs (all_prods n vs).\nProof.\ninduction vs as [| v vs IH]; intros x; simpl In; auto.\nintros [H1 | H1]; auto with datatypes.\napply in_or_app; left; rewrite <- H1.\npattern v at 1; rewrite <- (join1r n v); apply in_map.\napply all_prods1.\nQed.\n\n(* If n is the length of the list of vectors,\n      2^n is the length of the list of all products *)\nLemma all_prods_length n vs : \n  length (all_prods n vs) = exp 2 (length vs).\nProof.\ninduction vs as [| v vs IH]; simpl all_prods; auto.\nrewrite app_length; rewrite map_length; rewrite IH.\nsimpl length; rewrite expS; simpl; auto with arith.\nQed.\n\n(* Lift of all products *)\nLemma all_prods_lift n vs :\n  all_prods n.+1 (map (lift n) vs) = map (lift n) (all_prods n vs).\nProof.\ninduction vs as [| v vs IH].\nsimpl; auto.\nsimpl map; rewrite (all_prods_cons n.+1).\nchange (vect n * vect n)%type with (vect n.+1).\nrewrite map_app; rewrite IH.\napply f_equal2 with (f := @app (vect n.+1)); auto.\nelim all_prods; auto.\nintros a l IH1.\nassert (map_cons: forall (A B: Type) (f: A -> B) a l, \n                     map f (a:: l) = f a :: map f l); auto.\nrewrite !map_cons, IH1, lift_join; auto.\nQed.\n\nLemma all_prods_hom n vs :\n  (forall i, In i vs -> exists k, hom n k i) ->\n  (forall i, In i (all_prods n vs) -> exists k, hom n k i).\nProof.\ninduction vs as [| v vs IH]; simpl.\nintros _ i [[]|[]]; exists 0%nat; apply hom0K.\nintros H i Hi; case (in_app_or _ _ _ Hi); clear Hi; intros Hi.\nrewrite in_map_iff in Hi; case Hi; intros v1 (H1v,H2v); subst.\nassert (H1: forall i, In i vs -> exists k : nat, hom n k i); auto with datatypes.\ncase (H v); auto; intros k1 Hk1.\ncase (IH H1 v1); auto; intros k2 Hk2.\nexists (k1 + k2)%nat; auto.\napply IH; auto.\nQed.\n\n(* Turn a vector in a list of scalar to be used for multiple product *)\nFixpoint v2l (n: nat) : vect n -> list K :=\n  match n return vect n -> list K with\n    O => fun k => k :: nil\n  | S n1 => fun x => let (x1, x2) := x in\n                      (v2l n1 x1 ++ v2l n1 x2)%list\n  end.\n\n(* The length is 2^n *)\nLemma v2l_length n v : length (v2l n v) = exp 2 n.\nProof.\ninduction n as [| n IH]; auto.\nsimpl; destruct v; rewrite app_length; rewrite IH; rewrite IH.\ncase n; auto.\nQed.\n\n(* Every vector is a multiple product of all products of the base *)\nLemma mprod_2l n (v: vect n) :  v2l n v *X*  all_prods n (base n 1) = v.\nProof.\ninduction n as [| n IH].\nunfold mprod; simpl; rewrite multK1r; auto; rewrite addK0r; auto.\nassert (UUn := fn n); assert (UUsn := fn n.+1).\nsimpl vect; destruct v as [x1 x2].\nsimpl v2l; simpl base; rewrite base0, en_def; simpl app; unfold dlift.\n rewrite (all_prods_cons n.+1).\nrewrite mprod_app; auto.\n2: rewrite v2l_length, map_length, all_prods_length, map_length, \n   base_length; auto.\nrewrite (all_prods_lift n), (lift_mprod n), IH, map_map.\nreplace \n ((v2l n x1) *X*\n    (map (fun x : vect n => ((1: vect n, 0: vect n): vect n.+1) ∨ lift n x) (all_prods n (base n 1))))\nwith (x1, 0: vect n); auto.\nsimpl; Vfold n; rewrite addE0l, addE0r; auto.\nchange ((1: vect n, 0: vect n): vect n.+1) with ('e_0: vect n.+1).\nassert (H: forall l,\n  map (fun x : vect n =>  'e_0 ∨ (lift n x)) l =\n   map (fun x => (x, genk n 0)) l).\ninduction l as [| a l Hlrec]; simpl; Vfold n; auto.\napply f_equal2 with (f := @cons (vect n.+1)); auto.\nrewrite join1l, conj0, join0l, addE0r, join0l; auto.\nrewrite H; clear H.\nassert (H: forall l1 (l2: list (vect n)),\n  mprod (vn_eparams n.+1) l1 (map (fun x => (x, genk n 0)) l2) =\n  (mprod (vn_eparams n) l1 l2, genk n 0)).\ninduction l1 as [| a l1 Hlrec]; intros [| b l2]; auto.\nsimpl map; rewrite (mprod_S), Hlrec; auto.\nsimpl; Vfold n; rewrite scalE0r, addE0l, mprod_S; auto.\nrewrite H, IH; auto.\nrewrite bin_1; auto.\nQed.\n\n(* Every vector is a linear combination of all products of the base *)\nLemma cbl_all_prods n v : cbl _ (all_prods _ (base n 1)) v.\nProof. rewrite <- (mprod_2l n v); apply mprod_cbl; auto. Qed.\n\n(* All products of the base are free *)\nLemma all_prods_free n: free _ (all_prods _ (base n 1)).\nProof.\ninduction n as [| n IH]; intros ks.\nsimpl; case ks; try (intros; discriminate).\nintros k1 [| k2 l]; try (intros; discriminate); simpl.\nunfold mprod; simpl.\nrewrite multK1r; auto; rewrite addK0r; auto; intros _ H k.\nrewrite H; intros [H1 | H1]; auto; case H1.\nrewrite base1_S; simpl.\nrewrite app_length, map_length, (all_prods_lift n), map_length; intros Hk1.\ncase (list_split _ _ _ _ Hk1).\nintros l1 (l2, (Hl1, (Hl2, Hl3))).\nrewrite Hl1.\nunfold base, all_prods; fold base; fold all_prods.\nrewrite (mprod_app (vn_eparams n.+1)); auto.\n2: rewrite map_length, map_length; auto.\nrewrite map_map.\nassert (H1: forall l,\n  map (fun x : vect n => join n.+1 (gen n.+1 0) (lift n x)) l =\n   map (fun x => (x, genk n 0)) l).\ninduction l as [| a l Hlrec]; simpl; auto.\napply f_equal2 with (f := @cons (vect n.+1)); auto.\nVfold n; rewrite join1l, conj0, join0l, addE0r, join0l; auto.\nrewrite H1; clear H1.\nassert (H1: forall (l1: list K) (l2: list (vect n)),\n  mprod (vn_eparams n.+1) l1 (map (fun x => (x, genk n 0)) l2) =\n  (l1 *X* l2, genk n 0)).\nclear l1 l2 Hl1 Hl2 Hl3.\ninduction l1 as [| a l1 Hlrec]; intros [| b l2]; auto.\nsimpl; Vfold n.\nrewrite (mprod_S (vn_eparams n.+1)); auto.\nrewrite (mprod_S (vn_eparams n)); auto.\nrewrite Hlrec; auto.\nsimpl; Vfold n; rewrite scalE0r, addE0l; auto.\nrewrite H1, lift_mprod.\nsimpl; Vfold n; rewrite addE0l, addE0r; auto.\nintros HH; injection HH; clear HH; intros HH1 HH2 k Hk.\ncase (in_app_or _ _ _ Hk); intros Hl.\napply (IH l1); auto.\napply (IH l2); auto.\nQed.\n\n(* Ad-hoc inductive principes for vectors *)\nLemma vect_induct n (P: vect n -> Prop) :\n  P (1: vect n) -> (forall v, In v (base n 1) -> P v) ->\n     (forall v1 v2, P v1 -> P v2 -> P (v1 ∨ v2)) ->\n     (forall v1 v2, P v1 -> P v2 -> P (v1 + v2)) ->\n     (forall k v, P v -> P (k .* v)) ->\n     (forall v, P v).\nProof.\nintros H1 H2 H3 H4 H5 v.\ngeneralize (cbl_all_prods n v); intros HH; elim HH; auto; clear v HH.\ngeneralize (H5 0%f (1)); Vrm0.\ngeneralize (incl_refl (base n 1)).\ngeneralize (base n 1) at 1 3.\nintros l; induction l as [| a l IH]; simpl.\nintros _ v [H6|[]]; subst; auto.\nintros Hu1 v Ha.\nassert (Ht: incl l (base n 1)) by (intros u; auto with datatypes).\ncase (in_app_or _ _ _ Ha); intros Hb; auto with datatypes.\ngeneralize IH Hb; elim (all_prods n l); simpl; auto.\nintros a1 l1 IH1 H1i [H2i|H2i]; subst; auto with datatypes.\nQed.\n\nLemma vect_hom_induct n (P: vect n -> Prop) :\n  (forall k v, hom n k v -> P v) ->\n  (forall v1 v2, P v1 -> P v2 -> P (v1 + v2)) ->\n     (forall v, P v).\nProof.\nintros H1 H2 v.\nrewrite <-mprod_2l.\nassert (F1: forall i, In i (all_prods n (base n 1)) -> exists k, hom n k i).\napply all_prods_hom; intros i Hi; exists 1%nat.\nrewrite <-cbl1_hom1_equiv; constructor; auto.\ngeneralize (v2l n v); \n  induction (all_prods n (base n 1)) as [|a2 l2 IH]; simpl; auto.\nintros l; rewrite mprod0r; apply (H1 0%nat); apply homk0.\nintros [|a1 l1].\nrewrite mprod0l; apply (H1 0%nat); apply homk0.\nrewrite mprod_S; auto; apply H2; auto with datatypes.\ncase (F1 a2); auto with datatypes; intros k Hk.\napply (H1 k); auto.\nQed.\n   \n(* Iterated product of a list of vectors *)\nFixpoint joinl n (l: list (vect n)) := match l with\n| nil => 0\n| a::nil => a\n| a::l => a ∨ joinl n l\nend.\n\nLemma joinl0 n : joinl n nil = 0.\nProof. auto. Qed.\n\nHint Rewrite joinl0 : GRm0.\n\nLemma joinl1 n x : joinl n (x::nil) = x.\nProof. auto. Qed.\n\nLemma joinlS n x l : l <> nil -> joinl n (x::l) = x ∨ joinl n l.\nProof. destruct l; auto; intros []; auto. Qed.\n\nLemma joinl_scal n k (a: vect n) l : \n   joinl _ (k .* a::l) = k .* joinl _ (a::l).\nProof.\ncase (list_case _ l); intros Hl.\nrewrite Hl; simpl; Vfold n; auto.\nrewrite !joinlS, join_scall; auto.\nQed.\n\nLemma joinl_app n l1 l2 :\n  l1 <> nil -> l2 <> nil -> joinl n (l1 ++ l2)%list = joinl n l1 ∨ joinl n l2.\ninduction l1 as [| a1 l1 IH].\nintros H; case H; auto.\nintros _ Hl2.\ncase (list_case _ l1); intros; subst; simpl app; rewrite joinlS; auto.\nrewrite joinlS, IH, join_assoc; auto.\ndestruct l1; auto; try (intros; discriminate).\nQed.\n\nLemma joinl_base1_perm n l1 l2 :\n perm l1 l2 ->\n (forall x, In x l1 -> cbl _ (base n 1) x) ->\n  (joinl n l1 = joinl n l2) \\/ (joinl n l1 = (-(1)).* joinl n l2) .\nProof.\nintros H; elim H; simpl; auto; clear l1 l2 H; try Vfold n.\nintros a b [|c l] IH; right.\nrewrite <-cbl_base_join_com; auto.\nrewrite <-join_assoc, <-(join_assoc _ b), (cbl_base_join_com _ b),\n        !join_assoc, !join_scall;  auto with datatypes.\nrewrite join_assoc; auto.\nintros a [|a1 l1] [|b1 l2] Hl; auto.\nassert (HH:= perm_length _ _ _ Hl); discriminate.\nassert (HH:= perm_length _ _ _ Hl); discriminate.\nintros H1 H2; case H1; auto; intros H3; rewrite H3; auto.\nrewrite join_scalr; auto.\nintros l1 l2 l3 Hp1 HH1 Hp2 HH2 H1.\nassert (H2: forall x, In x l2 -> cbl _ (base n 1) x).\nintros x Hx; apply H1; auto.\napply perm_in with (1 := perm_sym _ _ _ Hp1); auto.\ncase HH1; auto; intros HH3; rewrite HH3; auto.\ncase HH2; auto; intros HH4; rewrite HH4; auto.\nleft.\nrewrite <- scal_multE, multK_m1_m1, scalE1; auto.\nQed.\n\nLemma joinl0_base1_perm n l1 l2 : perm l1 l2 ->\n (forall x, In x l1 -> cbl _ (base n 1) x) -> joinl n l1 = 0 -> joinl n l2 = 0.\nProof.\nintros H1 H2 H3; case (joinl_base1_perm n l1 l2); auto.\nintros HH; rewrite <-HH; auto.\nintros HH.\nrewrite <- (scalE0r _ (fn n) (-(1))%f), <- H3, HH,\n        <- scal_multE, multK_m1_m1, scalE1; auto.\nQed.\n\nLemma lift_joinl n l : lift n (joinl n l) = joinl n.+1 (map (lift n) l).\nProof.\nelim l; auto.\nintros a l1 IH; case (list_case _ l1); intros H1; subst; auto.\nsimpl map; rewrite ?joinl0, ?joinl1, ?joinlS; auto.\nrewrite lift_join, IH; auto.\ndestruct l1; simpl; try (intros; discriminate); case H1; auto.\nQed.\n\nLemma joinl_hom1 n l :\n (forall x, In x l -> hom n 1 x) -> hom n (length l) (joinl n l).\nProof.\nelim l; auto.\nintros; simpl; apply homk0.\nintros a l1 IH H1.\ncase (list_case _ l1); intros Hl1.\nsubst; simpl; auto with datatypes.\nrewrite joinlS; auto.\nchange (length (a::l1)) with (1 + length l1)%nat.\napply join_hom; auto with datatypes.\nQed.\n\nHint Resolve joinl_hom1 : core.\n\nLemma joinl_swap n (a b: vect n) l: \n cbl _ (base n 1) a ->  cbl _ (base n 1) b ->\n   joinl _ (a::b::l) = (-(1)).* joinl _ (b::a::l).\nProof.\nintros Ha Hb.\ncase (list_case _ l); intros Hl.\nrewrite Hl; simpl; Vfold n.\napply cbl_base_join_com; auto.\nrewrite !joinlS, <-join_assoc, (cbl_base_join_com n b),\n        !join_scall, !join_assoc; \n  try (intros; discriminate); auto.\nQed.\n\nLemma joinl_top n (a: vect n) l1 l2 : \n (forall i, In i (a :: l1) -> cbl _ (base n 1) i) ->\n   joinl _ (l1 ++ (a::l2)) = (-(1))^length l1 .* joinl _ (a:: (l1 ++ l2)%list).\nProof.\ninduction l1 as [| b l1 IH]; intros Hl2; auto.\nsimpl app; simpl expK; rewrite scalE1; auto.\nsimpl app; simpl expK;  \n  rewrite joinlS, IH, join_scalr, <-joinlS, multK_com,\n          scal_multE, joinl_swap; auto with datatypes.\nsimpl In; intros i [[]|Hi]; auto with datatypes.\nQed.\n\n\nLemma joinl_all n : 0 < n -> joinl n (base n 1) = E.\nProof.\ninduction n as [|n IH]; simpl; auto.\nintros H; contradict H; auto with arith.\ndestruct n as [|n].\nsimpl; auto.\nintros _.\nrewrite joinl_app, <-lift_joinl, IH; auto with arith.\nrewrite base0; simpl; Vfold n; Grm0.\nrewrite en_def, conjk, joinkl, scalE1; auto.\nrewrite base0; intros; discriminate.\nsimpl; rewrite base0; intros; discriminate.\nQed.\n\nDefinition is_vector n v := cbl _ (base n 1) v.\n\nDefinition is_vector_space n l := forall x, In x l -> is_vector n x.\n\nLemma joinl0_mprod n M : M <> nil -> is_vector_space n M ->\n   joinl n M = 0 ->\n   exists lk, exists i, length lk = length M /\\ In i lk /\\ i <> 0%f /\\ lk *X* M = 0.\nProof.\ngeneralize M; clear M.\ninduction n as [| n IH]; simpl.\nintros l Hd Hl Hp1.\nassert (forall a, In a l -> (a: vect 0) = 0).\nintros a H1; apply (cbl0_inv _ (fn 0)); apply Hl; auto.\n exists (map (fun x => (1%f)) l); exists (1%f); repeat split.\nrewrite map_length; auto.\ndestruct l; simpl; auto.\napply one_diff_zero; auto.\nclear Hd Hl Hp1; induction l as [|a l IH]; simpl; auto.\nrewrite  (mprod_S (vn_eparams 0)); auto.\nrewrite (H a); Vrm0; auto with datatypes.\nintros l Hl Hd Hprod; unfold is_vector in Hl.\ncase (cbl_base1_list_split n l); auto.\nintros lx (ly, (H1ly, (H2ly, (H3ly, H4ly)))).\nmatch type of H4ly with perm _ ?X => set (l1 := (X: list (vect n.+1))) in H4ly end.\nassert (Hl1: exists lk, exists i,\n    length lk = length l1 /\\ In i lk /\\ i <> 0%f /\\ lk *X* l1 = 0).\n2: case Hl1; intros lk (i, (H1i, (H2i, (H3i, H4i)))).\n2: assert (Hlk: length lk = length l).\n2: rewrite H1i; apply perm_length; apply perm_sym; auto.\n2: case (mprod_perm _ (fn n.+1) _ _ _ (perm_sym _ _ _  H4ly) H1i); intros lk2 (H1lk2, H2lk2).\n2: exists lk2; exists i; repeat split; auto.\n2: rewrite <- Hlk; apply perm_length; apply perm_sym; auto.\n2: apply perm_in with (1 := H1lk2); auto.\n2: rewrite <-H2lk2; auto.\nassert (HH: l1 <> nil).\ngeneralize (perm_length _ _ _ H4ly) Hl.\ncase l; case l1; auto; intros; discriminate.\nassert (HH1:= joinl0_base1_perm n.+1 _ _ H4ly Hd Hprod).\ngeneralize HH HH1; unfold l1; generalize (refl_equal (length lx)) ly H1ly H2ly H3ly.\npattern lx at -2; generalize (length lx); intros n1; generalize lx.\ninduction n1 as [| n1 IH1]; clear lx l1 l Hl Hd Hprod ly H1ly H2ly H3ly H4ly HH HH1. \n  intros [| a [| b lx]] HH ly H1ly H2ly H3ly H4ly H5ly.\n2: discriminate HH.\n2: discriminate HH.\ncase (list_case _ ly); intros Hly; subst.\ncase H4ly; auto.\ncase (IH ly); auto; clear HH.\ngeneralize H5ly; simpl; rewrite <-(lift_joinl n); intros HH; injection HH; auto.\nintros ly1 (i, (H1i, (H2i, (H3i, H4i)))).\nexists ly1; exists i; repeat split; simpl; auto.\nrewrite map_length; auto.\nrewrite (lift_mprod n); rewrite H4i; auto.\nintros [| a [| b lx]]; try (intros; discriminate).\nintros HH ly H1y H2y H3y H4y H5y; injection HH; intros; subst n1; clear HH.\ngeneralize H5y; simpl map.\ncase (list_case _ ly); intros Hly; subst.\nintros HH; injection HH; intros.\ncase (H1y a); auto with datatypes; auto.\napply injk with n; auto.\nrewrite joinl_app; auto; simpl; auto.\nrewrite <-(lift_joinl n); simpl; Vfold n.\nrewrite join0r, addE0r; auto.\nreplace (@fst (Field.K K) (vect n) a) with ((fst a  * 1)%f) by (rewrite multK1r; auto).\nrewrite <- scalk, join_scall, join1l; auto.\nintros HH; injection HH; clear HH; intros _ HH.\ncase (scal_integral _ _ _ HH); intros HH1.\ncase (H1y a); auto with datatypes.\ncase (IH ly); auto; try split.\nintros ly1 (i1, (H1i1, (H2i1, (H3i1, H4i1)))).\nexists (0%f::ly1); exists i1; repeat split; simpl; Vfold n; auto.\nrewrite map_length; simpl in H1i1; rewrite H1i1; auto.\nrewrite (mprod_S (vn_eparams n.+1)), scalE0l, addE0l; auto.\n\nrewrite (lift_mprod n), H4i1; auto.\nintros; discriminate.\ndestruct ly; try (intros; discriminate); case Hly; auto.\nintros Hl ly1 H1ly H2ly H3ly H4ly H5ly.\npose (x1 := fst a .* snd b + (- (fst b)).* snd a).\npose (mk_v:= fun x : K * vect n => ([fst x], snd x) : vect n.+1).\nassert (Hx1: lift n x1 = ((fst a) .* (mk_v b) + (- (fst b)).* mk_v a)).\n  unfold x1; simpl; Vfold n.\n  rewrite !scalk, addk, multK_com, <-opp_multKl, oppKr; auto.\nassert (Halx: length (a :: lx) = n1).\ngeneralize Hl; simpl; intros HH1; injection HH1; auto.\ncase (IH1 _ Halx (x1::ly1)); auto.\nsimpl; intros i [Hi | Hi]; try subst i; apply H1ly; auto with datatypes.\nsimpl; intros i [Hi | Hi]; try subst i; apply H2ly; auto with datatypes.\nsimpl; intros i [Hi | Hi]; try subst i; auto.\nunfold x1; apply cbl_add; apply cbl_scal; apply H2ly; auto with datatypes.\nintros HH; discriminate.\nsimpl map.\nassert (Hmk: forall b, mk_v b = (fst b) .* (gen n.+1 0) +\n                        lift n (snd b)).\n  intros (vv, bb); unfold mk_v; simpl; Vfold n.\n  rewrite addE0r, scalE0r, addE0l, scalk, multK1r; auto.\nassert (F1: cbl (vn_eparams n.+1) (base n.+1 1) (mk_v a)).\nrewrite Hmk.\napply cbl_add; try apply cbl_scal; auto with datatypes.\nconstructor; apply (e_in_base1 n.+1 0); auto with arith.\napply cbl_incl with (l1 := map (lift n) (base n 1)); simpl; auto with datatypes.\napply lift_cbl; auto with datatypes.\nassert (F2: cbl (vn_eparams n.+1) (base n.+1 1) (lift n x1)).\napply cbl_incl with (l1 := map (lift n) (base n 1)); simpl; auto with datatypes.\napply lift_cbl; auto with datatypes.\napply cbl_add; apply cbl_scal; auto with datatypes.\nrewrite joinl_top; auto.\nsimpl app; rewrite joinl_swap; auto.\nrewrite Hx1.\nassert (F3: forall a k1 k2 b l, cbl _ (base n.+1 1) a ->\n joinl n.+1 (a::(k1 .* b + k2 .* a)::l) = k1 .* joinl n.+1 (a::b ::l)).\nintros a1 k1 k2 a2 l H.\ncase (list_case _ l); intros Hll.\nsubst; apply trans_equal with  (a1 ∨ (k1 .* a2 + k2 .* a1)); auto.\nrewrite join_addr, !join_scalr, cbl_base_join_id; Vrm0.\nrewrite !joinlS; auto; try (intros; discriminate).\nrewrite <-join_assoc, join_addr, !join_scalr, cbl_base_join_id; Vrm0.\nrewrite join_scall, <-!join_assoc; auto.\nrewrite F3; auto.\ngeneralize H5ly; unfold mk_v; simpl; intros HH; rewrite HH; Vfold n; Vrm0.\nsimpl In; intros i [[]|[[]|H]]; auto.\nrewrite in_map_iff in H; case H.\nintros x [[] Hx].\ngeneralize (Hmk x); unfold mk_v; intros HH; rewrite HH.\napply cbl_add; try apply cbl_scal; auto with datatypes.\nconstructor; apply (e_in_base1 n.+1 0); auto with arith.\napply cbl_incl with (l1 := map (lift n) (base n 1)); simpl; auto with datatypes.\napply lift_cbl; auto with datatypes.\nsimpl map;\nintros ly2 (i2, (H1ly2, (H2ly2, (H3ly3, H3ly4)))).\ncase (length_split _ _ _ _ _ _ _ H1ly2).\nintros k1 (k2, (lk1, (lk2, (Hlk1, (Hlk2, Hlk3))))).\ngeneralize (eqK_dec _ Hp k2 0%f); case eqK; intros Hk2.\n*\nexists (k1::0%f::lk1++lk2)%list; exists i2; repeat split; auto.\ngeneralize Hlk2 Hlk3; simpl; clear Hlk2 Hlk3; intros Hlk2 Hlk3.\nrewrite !app_length, Hlk2, Hlk3; auto.\ngeneralize H2ly2; rewrite Hlk1; simpl.\nintros [HH | HH]; auto.\ncase (in_app_or  _ _ _ HH); auto with datatypes.\nsimpl; intros [HH1 | HH2]; try subst; auto with datatypes.\ngeneralize H3ly4; rewrite Hlk1, Hk2; simpl.\nrewrite !(mprod_S (vn_eparams n.+1)), !(mprod_app (vn_eparams n.+1)), !(mprod_S (vn_eparams n.+1)); auto.\nrewrite !scalE0l, !addE0l; auto.\nrewrite (scalE0l (vn_eparams n.+1)); auto. rewrite addE0l; auto. \n*\nexists ((k1+-(k2 * fst b))%f::(k2 * fst a)%f::lk1++lk2)%list; \n  exists (k2 * fst a)%f; repeat split; auto with datatypes.\ngeneralize Hlk2 Hlk3; simpl; clear Hlk2 Hlk3; intros Hlk2 Hlk3.\nrewrite !app_length, Hlk2, Hlk3; auto.\nintros HH; case (multK_integral _ Hp _ _ HH); intros HH1; auto with datatypes.\ncase (H1ly a); auto with datatypes.\nrewrite <- H3ly4; rewrite Hlk1; simpl.\nrewrite Hx1, !(mprod_S (vn_eparams n.+1)), !(mprod_app (vn_eparams n.+1)), !(mprod_S (vn_eparams n.+1)), !scal_addEr,\n        !scal_addEl, !addE_assoc; auto.\napply f_equal2 with (f := add n.+1); auto.\nrewrite addE_com,!addE_assoc, addE_com, !addE_assoc; auto.\napply f_equal2 with (f := add n.+1); auto.\napply sym_equal.\nrewrite addE_com, !addE_assoc, addE_com, !addE_assoc; auto.\napply f_equal2 with (f := add n.+1); auto.\napply sym_equal.\nrewrite addE_com, <-!scal_multE, opp_multKr; auto.\nQed.\n\nLemma cbl_joinl0_mprod n M x : is_vector_space n M ->  \n  cbl _ M x -> joinl n (x::M) = 0.\nProof.\nintros H1 H2; elim H2; clear x H2.\ndestruct M; auto; rewrite joinlS, join0l; auto; intros; discriminate.\nintros v.\ngeneralize H1; elim M; auto with datatypes.\nintros _ HH; case HH.\nintros a l1 IH Hc; simpl In; intros [H3 | H3]; try subst.\ncase (list_case _ l1); intros Hl1.\nrewrite Hl1; simpl; rewrite cbl_base_join_id; try apply Hc; auto with datatypes.\nrewrite !joinlS, <-join_assoc, cbl_base_join_id, join0l; try apply Hc; auto with datatypes.\nrewrite !joinlS; try (intros; discriminate).\n2: intros HH; subst; case H3.\nrewrite <-join_assoc, (cbl_base_join_com n a), join_scall,\n        join_assoc, <-joinlS; try apply Hc; auto with datatypes.\ngeneralize IH; simpl; intros HH; rewrite HH; Vfold n; auto.\nrewrite join0r; Vrm0.\nintros i Hi; apply Hc; auto with datatypes.\nintros HH; subst; case H3.\nintros x y _ Hx _ Hy.\ncase (list_case _ M); intros Hl; subst.\nsimpl in Hx,Hy |- *; Vfold n; rewrite Hx, Hy; Vrm0.\nrewrite joinlS, join_addl, <-!joinlS; Vrm0.\ngeneralize Hx Hy; simpl; intros Hx1 Hx2; rewrite Hx1, Hx2; Vfold n; Vrm0.\nintros k x Hc Hpr.\ncase (list_case _ M); intros Hl; subst.\ngeneralize Hpr; simpl; Vfold n; intros Hpr1.\nsimpl; Vfold n; rewrite Hpr1, scalE0r; auto.\nrewrite joinlS, join_scall, <-joinlS; auto.\ngeneralize Hpr; simpl; intros Hpr1; rewrite Hpr1; Vfold n; auto.\nrewrite scalE0r; auto.\nQed.\n\n(* M is decomposable and l is its decomposition *)\nDefinition decomposable n l M := is_vector_space n l /\\ M = joinl n l.\n\nLemma decomp_cbl n M l x : is_vector n x ->\n  decomposable n l M -> M <> 0 -> (x ∨ M = 0 <-> cbl _ l x). \nProof.\nintros Hx [Hn HM] Hdiff; subst; split; intros H1.\nassert (Hd: l <> nil) by (intros HH; case Hdiff; subst; auto).\ncase (joinl0_mprod n (x::l)); auto with datatypes.\nsimpl; intros x1 [Hx1 | Hx1]; subst; auto with datatypes.\nrewrite joinlS; auto; intros HH1; case Hdiff; rewrite HH1; auto.\nintros [| k lk] (i, (H1lk, (H2lk, (H3lk, H4lk)))); try discriminate.\ngeneralize (eqK_dec _ Hp k 0%f); case eqK; intros Hk; subst; auto.\ngeneralize H4lk.\nrewrite (mprod_S (vn_eparams n)); auto.\nrewrite (scalE0l (vn_eparams n)); auto.\nrewrite  addE0l; auto; intros HH.\nsimpl in H2lk; case H2lk; clear H2lk; intros H2lk; subst.\ncase H3lk; auto.\ncase Hdiff; injection H1lk.\ngeneralize l Hn Hd HH H2lk; clear l H4lk H1lk Hdiff H1 Hd Hn HH H2lk.\nelim lk; simpl; auto.\nintros l; case l; intros; try discriminate; auto.\nintros a l IH [| b l1] H1l1 H2l1.\ncase H2l1; auto.\ngeneralize (eqK_dec _ Hp a 0%f); case eqK; intros Ha; simpl in Ha.\nrewrite (mprod_S (vn_eparams n)), Ha, (scalE0l (vn_eparams n)), addE0l; auto.\nintros HH [HH1 | HH1]; try (case H3lk; auto; fail).\nintros HH2; injection HH2; clear HH2; intros HH2.\nrewrite joinlS.\nrewrite IH; auto with datatypes.\nrewrite join0r; auto.\nintros i1 Hi1; apply H1l1; auto with datatypes.\nintros HH3; subst.\ndestruct l; try discriminate; case HH1.\nintros HH3; subst.\ndestruct l; try discriminate; case HH1.\nintros HH1.\nassert (HxL: b = (-(a^-1)).* (l *X* l1)).\ngeneralize HH1; rewrite mprod_S; auto; intros HH.\nrewrite <- (addE0l _  (fn n) (l *X* l1)); rewrite <- (scal_addE0 _ (fn n) (a .* b)).\nrewrite (addE_com _ (fn n) (a.*b)); rewrite addE_assoc, HH, addE0r,\n         <-!scal_multE, <-!opp_multKr, <-!opp_multKl, multK1r, multK_com, invKl,\n         opp_oppK, scalE1; auto.\ngeneralize H1l1 IH HxL; case l; case l1; try (intros; discriminate);\n clear l l1 HxL HH1 H1l1 H2l1 IH.\nintros H1l1 IH.\nunfold mprod; simpl; Vfold n; rewrite scalE0r; auto; intros HH2; rewrite HH2.\nintros a1 l1 b1 l H2l1 IH HxL _ Hl.\napply (cbl_joinl0_mprod n (a1::l1)); auto with datatypes.\nintros i1; simpl; intros [[]|Hi]; apply H2l1; auto with datatypes.\nrewrite HxL; apply cbl_scal.\napply mprod_cbl; auto.\nassert (HxL: x = (-(k^-1)).* (lk *X* l)).\ngeneralize H4lk; rewrite mprod_S; auto; intros HH.\nrewrite <- (addE0l _ (fn n) (lk *X* l)), <- (scal_addE0 _  (fn n) (k .* x)).\nrewrite (addE_com _  (fn n) (k.*x)), addE_assoc, HH, addE0r,\n        <-!scal_multE, <-!opp_multKr, <-!opp_multKl,\n        multK1r, multK_com, invKl, opp_oppK, scalE1; auto.\nrewrite HxL; apply cbl_scal.\napply mprod_cbl; auto.\nrewrite <-joinlS; auto.\napply (cbl_joinl0_mprod n l x); auto.\nintros HH; case Hdiff; rewrite HH; auto.\nQed.\n\nLemma hom1_decomposable n x : hom n 1 x -> decomposable n (x::nil) x.\nProof.\nintros H; split; auto.\nintros y; simpl; intros [[]|[]]; red; rewrite cbl1_hom1_equiv; auto.\nQed.\n\nLemma decomp_hom n (l: list (vect n)) M : decomposable n l M -> hom n (length l) M.\nProof.\nintros (H1, H2); subst.\nassert (HH: forall a, In a l -> hom n 1 a).\nintros a Ha; rewrite <- cbl1_hom1_equiv; auto.\ngeneralize (H1 a Ha); auto.\nclear H1; induction l as [| a l1 IH].\nsimpl; apply hom0K.\ncase (list_case _ l1); intros H1.\nsubst; simpl; auto with datatypes.\nrewrite joinlS; auto.\nchange (length (a::l1)) with (1 + length l1)%nat; auto with datatypes.\nQed.\n\n(* The linear form is defined by its finger print on the base *)\n\nFixpoint contra (n : nat) {struct n}: kn n -> vect n -> vect n :=\n  match n return (kn n -> vect n -> vect n) with\n  | 0%nat => fun k a => 0\n  | S n1 =>\n      fun lf l1 =>\n      let (k, lf1) := lf in\n      let (l2, l3) := l1 in \n         ((- (1)).* (contra n1 lf1 l2),  (k : K) .* l2 + contra n1 lf1 l3)\n  end.\n\nNotation \"#< l , x ># \" := (contra _ l x) (format \"#< l ,  x >#\").\n\nLemma contraE n l (M : vect n.+1) :\n  #<l, M ># =\n      ((- (1))%f.* #< snd l, fst M>#,  (fst l : K) .* fst M + #<snd l, snd M>#).\nProof. destruct l; destruct M; auto. Qed.\n\nLemma contra0r n lf : #<lf, 0># = (0: vect n).\nProof.\ninduction n as [| n IH]; simpl; Grm0; Vfold n.\ndestruct lf; rewrite IH; Grm0.\nQed.\n\nHint Rewrite contra0r : GRm0.\n\nLemma contra0l n (x:vect n) : #<0, x># = 0.\nProof.\ninduction n as [|n IH]; simpl; auto.\ndestruct x.\nVfold n.\nVfold n; repeat rewrite IH; Grm0.\nrewrite (scalE0l (vn_eparams n)); auto.\nQed.\n\nLemma contrak n i lf : #<lf, [i]># = 0 :> vect n.\nProof.\ninduction n as [| n IH]; simpl; auto.\ndestruct lf; rewrite IH; Grm0.\nQed.\n\nLemma contra_e n i lf : i < n -> #<lf, 'e_i># = [projk _ i lf] :> vect n.\nProof.\ngeneralize i; clear i.\ninduction n as [| n IH]; intros i; simpl; auto; try Vfold n.\ndestruct lf; destruct i as [| i]; Grm0.\n  rewrite contrak; Grm0;  simpl; Vfold n; Grm0.\n  rewrite scalk, multK1r; auto.\nintros HH; assert (HH1: i < n); auto with arith.\nrewrite IH; simpl; auto.\nQed.\n\nLemma contra_scalr n k lf (x: vect n) : #< lf, k .* x ># = k .* #< lf , x >#.\nProof.\ninduction n as [| n IH]; simpl; auto; try Vfold n.\n  intros; rewrite multK0r; auto.\ndestruct lf; destruct x.\nrewrite IH, IH, scal_addEr, <-! scal_multE; auto.\nrepeat rewrite (fun x => (multK_com p x k)); auto.\nQed.\n\nLemma contra_addr n lf (x y: vect n) : #< lf, x + y ># = #< lf, x ># + #< lf,  y >#.\nProof.\ninduction n as [| n IH]; simpl; auto; try Vfold n.\n  intros; rewrite addK0r; auto.\ndestruct lf; destruct x; destruct y; rewrite !IH, !scal_addEr; auto.\napply f_equal2 with (f := @pair _ _); auto.\nrewrite <-! addE_assoc; try apply f_equal2 with (f := add n); auto.\nrewrite !addE_assoc; try apply f_equal2 with (f := add n); auto.\nrewrite addE_com; auto.\nQed.\n\nLemma contra_scall n (k : K) (x : kn n)  (M : vect n) :\n #< (scalE (Kn.vn_eparams p n) k x), M># = k .* #<x, M>#.\nProof.\ninduction n as [|n IH]; simpl; Krm0.\ndestruct x as [k1 x1]; destruct M as [M1 M2]; Vfold n; Kfold n.\nrewrite !IH, scal_addEr, <-!scal_multE, multK_com; auto.\nQed.\n\nLemma contra_addl n (x y : kn n) (M : vect n) :\n #< x + y, M ># =  #< x, M ># + #<y, M >#.\nProof.\ninduction n as [|n IH]; simpl; Krm0.\ndestruct x as [a x1]; destruct y as [b y1]; destruct M as [M1 M2].\nVfold n; Kfold n.\nrewrite !IH, scal_addEr, (scal_addEl (vn_eparams n)); auto.\napply f_equal2 with (f := @pair _ _); auto.\nrewrite !addE_assoc; auto.\napply f_equal2 with (f := addE _); auto.\nrewrite addE_swap; auto.\nQed.\n\nLemma contra_conj n lf b (x: vect n) : #< lf, x ^_ b ># = #< lf, x ># ^_ (negb b).\nProof.\ngeneralize b; clear b.\ninduction n as [| n IH]; simpl.\n  intros  [|]; try rewrite oppK0; auto.\ndestruct lf; intros b; destruct x; rewrite IH, IH; Vfold n.\nrewrite conj_add, conj_scal, conj_scal; auto.\nQed.\n\nLemma contra_hom n lf k M : hom n k.+1 M -> hom n k #<lf , M>#.\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; simpl; intros [|k1]; simpl; auto.\n rewrite eqKI; auto.\nintros H; destruct lf.\ndestruct M as [M1 M2]; try rewrite eq0I; rewrite ?homk0; auto.\nassert (Hm1: hom n 0 M1); [generalize H; case hom; auto | idtac].\nassert (Hm2: hom n 1 M2); [generalize H; repeat (case hom; auto) | clear H].\n  rewrite (hom0E _ _ Hm1); Vfold n.\n  rewrite contrak, scalE0r, eq0I,  add_hom; auto; apply scal_hom; apply hom0K; auto.\ndestruct lf; destruct M as [M1 M2]; intros H.\nassert (Hm1: hom n k1.+1 M1); [generalize H; case hom; auto | idtac].\nassert (Hm2: hom n k1.+2 M2); [generalize H; repeat (case hom; auto) | clear H]; auto.\nVfold n; rewrite scal_hom, add_hom; auto.\nQed.\n\nHint Resolve contra_hom : core.\n\nLemma contra_hom0 n lf M : hom n 0 M -> #<lf , M># = 0.\nProof. intros H; rewrite (hom0E _ _ H); apply contrak. Qed.\n\nLemma contra_id n lf (M: vect n) : #<lf, #< lf, M>#  ># = 0.\nProof.\ninduction n as [| n IH]; simpl; auto; Vfold n.\ndestruct lf; destruct M.\nrewrite !contra_addr, !contra_scalr, !IH, !scalE0r, addE0r,\n        <-scal_addEr, addE_com, scal_addE0, scalE0r; auto.\nQed.\n\nLemma contra_swap n lf1 lf2 (M: vect n) :\n  #<lf1, #< lf2, M>#  ># = (-(1)).*  #<lf2, #< lf1, M>#  >#.\nProof.\ninduction n as [| n IH]; simpl; auto; try Vfold n.\nrewrite multK0r; auto.\ndestruct lf1 as [k1 lf1]; destruct lf2 as [k2  lf2]; destruct M.\nrewrite !contra_scalr, !contra_addr, !(IH _ lf2), !contra_scalr,\n        !scal_addEr, !scalE_opp, !opp_oppK, !scalE1,\n        <-!scal_multE, <-!opp_multKl, !multK1l, addE_swap; auto.\nQed.\n\nFixpoint v2k (n : nat) : vect n -> kn n :=\n  match n return vect n -> kn n  with\n  | O => fun v : vect 0 => tt\n  | S n1  => fun v => let (v1,v2) := v in\n             ('C[v1], v2k n1 v2)\n  end.\n\nLemma contra_const n lf M : hom n 1 M -> \n  #<lf, M># = [(lf [.] v2k n M)%Kn].\nProof.\ninduction n as [| n IH]; simpl; Krm0.\ndestruct lf; destruct M as [M1 M2]; intros HM12.\nassert (HM1: hom n 0 M1) by (generalize HM12; case hom; auto).\nassert (HM2: hom n 1 M2) by (generalize HM12; rewrite HM1; case hom; auto).\nrewrite (hom0E _ _ HM1); Vfold n.\nrewrite contrak, scalE0r, IH; auto.\napply f_equal2 with (f := @pair _ _); auto.\nrewrite <-addk, <-joink, joinkl, <-!hom0E; simpl; auto.\nQed.\n\nLemma contra_join n lf k1 k2 M1 M2 : hom n k1 M1 -> hom n k2 M2 ->\n  #<lf, M1 ∨ M2># = #<lf, M1># ∨ M2 + ((- (1))^k1).* M1 ∨ #<lf, M2>#.\nProof.\ngeneralize lf k1 k2; clear lf k1 k2.\ninduction n as [| n IH]; simpl; auto; try Vfold n.\nintros lf [| k1] [| k2]; Grm0.\nintros [k lf] [| k1] [| k2]; destruct M2 as [M3 M4]; destruct M1 as [M1 M2]; \n  simpl expK; Grm0.\ncase eq0_spec; try (intros; discriminate); intros HH HM2; subst; Grm0.\ncase eq0_spec; try (intros; discriminate); intros HH HM3; subst; Grm0.\nassert (Hk24 := join_hom _ _ _ _ _ HM2 HM3).\nrewrite (hom0E _ _ Hk24), (hom0E _ _ HM2), (hom0E _ _ HM3), !contrak; Grm0.\ncase eq0_spec; try (intros; discriminate); intros HH HM2; subst; Grm0.\nrewrite (hom0E _ _ HM2).\nrepeat ((rewrite conjk || rewrite scalE1 || rewrite joinkl ||\n         rewrite contra_scalr || rewrite contrak); Grm0).\nrepeat ((rewrite scal_addEr || rewrite <- scal_multE); auto).\nrewrite multK_com, (multK_com _ Hp k); auto.\nintros HH.\ncase eq0_spec; try (intros; discriminate); intros HH1 HM3; subst; Grm0.\nrewrite (hom0E _ _ HM3).\nrepeat ((rewrite conjk || rewrite scalE1 || rewrite joinkl ||\n         rewrite joinkr ||rewrite contra_scalr || rewrite contrak); Grm0).\nrepeat ((rewrite scal_addEr || rewrite <- scal_multE); auto).\nrewrite multK_com, (multK_com _ Hp k); auto.\nintros HM1 HM2.\nassert (F1: hom n k1 M1) by (generalize HM1; case hom; auto).\nassert (F2: hom n k1.+1 M2) by (generalize HM1; case hom; auto; intros; discriminate).\nassert (F3: hom n k2 M3) by (generalize HM2; case hom; auto).\nassert (F4: hom n k2.+1 M4) by (generalize HM2; case hom; auto; intros; discriminate).\nclear HM1 HM2.\nrewrite !contra_addr, (conjf_hom n k1.+1 M2), join_scall, conj_add; auto.\nrepeat (rewrite conj_scal || rewrite contra_scalr || rewrite scal_addE_r); auto.\nrewrite (IH M1 M4  lf k1 k2.+1); auto; simpl expK.\nrewrite (IH M2 M3 lf k1.+1 k2); auto; simpl expK.\nrewrite (IH M2 M4 lf k1.+1 k2.+1); auto; simpl expK.\nrepeat (rewrite scal_addEr || rewrite join_addr || rewrite join_addl ||\n        rewrite join_scall || rewrite join_scalr); auto.\nrewrite (conjf_hom n k1 M1); auto.\nrewrite (conjf_hom n k1 #<lf, M2 >#); try apply contra_hom; auto.\nrewrite (conjf_hom n k1.+1 M2); auto; simpl expK; \n  rewrite !join_scall, <-!scal_multE; Krm1; auto.\napply f_equal2 with (f := @pair _ _).\napply sym_equal.\ndo 8 (rewrite ?addE_assoc; auto; \n  ((apply f_equal2 with (f := addE (vn_eparams n)); auto); [idtac])\n || rewrite addE_com; auto); rewrite multK_com; auto.\nrewrite addE_com, addE_assoc, <- scal_addEl, oppKr; Grm0.\nrepeat (rewrite ?addE_assoc; auto; \n  ((apply f_equal2 with (f := addE (vn_eparams n)); auto); [idtac])\n || rewrite addE_com; auto); rewrite multK_com; auto.\nQed.\n\n(* Anti-commutativity for homegeonous vectors, generalization of  cbl_base_prod_com  *)\nLemma join_hom_com n k1 k2 x y :\n hom n k1 x -> hom n k2 y ->  y ∨ x = ((- (1)) ^(k1 * k2)).* (x ∨ y).\nProof.\ngeneralize k1 k2; clear k1 k2.\ninduction n as [| n IH]; simpl; try Vfold n.\nintros [|k1] [|k2] Hk1 Hk2; simpl expK.\nrewrite multK1l, multK_com; auto.\ngeneralize Hk2; case eqK_spec; auto; intros; subst; Krm0; discriminate.\ngeneralize Hk1; case eqK_spec; auto; intros; subst; Krm0; discriminate.\ngeneralize Hk1; case eqK_spec; auto; intros; subst; Krm0; discriminate.\nintros [|k1] [|k2] Hk1 Hk2; simpl expK; \n  destruct x as [x1 x2]; destruct y as [y1 y2];\n  try (generalize Hk1; case eq0_spec; intros; subst; Grm0; try discriminate);\n  try (generalize Hk2; case eq0_spec; intros; subst; Grm0; try discriminate).\nrewrite (hom0E n x2), (hom0E n y2); auto; simpl; Vfold n.\nrewrite scalE1, !joink, multK_com; auto.\nrewrite (hom0E n x2), conjk, !joinkl, !joinkr, !scalE1; auto.\nrewrite (hom0E n y2), <-!mult_n_O, conjk, !joinkl, !joinkr, !scalE1; auto.\nassert (Hh1: hom n k1 x1) by (generalize Hk1; case hom; auto).\nassert (Hh2: hom n k1.+1 x2) by (generalize Hk1; case hom; intros; auto; discriminate).\nassert (Hh3: hom n k2 y1) by (generalize Hk2; case hom; auto).\nassert (Hh4: hom n k2.+1 y2) by (generalize Hk2; case hom; intros; auto; discriminate).\nrewrite (conjf_hom _ k2.+1), join_scall, (conjf_hom _ k1.+1), join_scall; auto.\napply f_equal2 with (f := @pair _ _).\nrewrite  addE_com, scal_addEr; auto.\napply f_equal2 with (f := add n).\nrewrite (IH _ _ k1 k2.+1); auto.\nsimpl expK; rewrite !expK_add, !scal_multE; auto.\nrewrite (IH _ _ k1.+1 k2); auto.\nsimpl expK; rewrite <-mult_n_Sm, !expK_add, <-!scal_multE; auto.\napply f_equal2 with (f := scal n); auto.\nrewrite (multK_com _ Hp (- (1))%f), !multK_assoc; auto.\nrewrite <- (multK_assoc _ Hp (- (1))%f), multK_m1_m1, multK1l, expK2m1, multK1r; auto.\nrewrite (IH _ _ k1.+1 k2.+1); auto.\nQed.\n\nLemma join_hom_odd n k x : (1+1 <> (0: K))%f -> hom n k x -> odd k -> x ∨ x = 0.\nProof.\nintros H2 Hx Hk.\ncase (scalE_integral _ (fn n) (1 + 1)%f (x ∨ x)); auto.\n2: intros; case H2; auto.\nrewrite scal_addEl, scalE1; auto.\npattern (x ∨ x) at 2; rewrite (join_hom_com n k k x x); auto.\nrewrite expKm1_odd, scal_addE0; auto.\napply odd_mult; auto.\nQed.\n\nLemma join_hom_id n k x : hom n k x -> odd k ->  x ∨ x = 0.\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; simpl; try Vfold n.\nintros [|k] Hk; simpl expK.\nintros HH; inversion HH.\ngeneralize Hk; case eqK_spec; intros; subst; Krm0; discriminate.\nintros [|k]; destruct x as [x y]; rewrite andbP; intros (Hk1,Hk2).\nintros HH; inversion HH.\nintros Ho; rewrite (IH _ k.+1); auto.\nrewrite conjf_hom with (k := S k); auto.\nrewrite expKm1_odd, join_scall, (join_hom_com n k k.+1 x y),\n        expKm1_even, scalE1, scal_addE0; auto.\napply even_mult_l.\napply odd_plus_even_inv_r with 1%nat; auto; repeat constructor; auto.\nQed.\n\nLemma is_vector_space_swap n x l :\n  is_vector_space n l -> In x l ->\n  exists l1, is_vector_space n (x::l1) /\\ joinl n l = joinl n (x::l1).\nProof.\ninduction l as [|y l IH].\nintros _ [].\nsimpl In; intros Hs [[] | Hxy].\nexists l; auto.\nassert (F1: is_vector_space n l).\nintros u Hu; apply Hs; auto with datatypes.\ncase (IH F1 Hxy); intros l1 (H1l1,H2l1).\nexists ((-(1)) .* y::l1); split.\nintros u; simpl; intros [Hu|[Hu|Hu]]; subst.\napply H1l1; auto with datatypes.\napply VectorSpace.cbl_scal; apply Hs; auto with datatypes.\napply H1l1; auto with datatypes.\nrewrite joinlS, H2l1.\ndestruct l1 as [|z l1].\nsimpl; Vfold n.\nrewrite join_hom_com with (k1 := 1%nat) (k2 := 1%nat).\nsimpl expK; Krm1; rewrite join_scalr; auto.\nrewrite <-cbl1_hom1_equiv; apply H1l1; auto with datatypes.\nrewrite <-cbl1_hom1_equiv; apply Hs; auto with datatypes.\nrewrite joinlS, <-join_assoc.\nrewrite join_hom_com with (k1 := 1%nat) (k2 := 1%nat) (x:= x).\nsimpl expK; Krm1; rewrite <-join_scalr, join_assoc; auto.\nrewrite <-cbl1_hom1_equiv; apply H1l1; auto with datatypes.\nrewrite <-cbl1_hom1_equiv; apply Hs; auto with datatypes.\nintros HH; discriminate.\ndestruct l as [|z l].\ncase Hxy.\nintros HH; discriminate.\nQed.\n\n(* This function will be only call with first vector is hom 1 *)\nFixpoint factor n: (vect n) -> (vect n) -> vect n :=\n  match n return vect n -> vect n -> vect n with\n  | O => fun x1 x2 => (x2 * x1^-1)%f\n  | S n1 =>\n        fun x1 x2 =>\n        let (x11, x12) := x1 in\n        let (x21, x22) := x2 in\n        if x12 ?= 0 then\n        (* if x<> 0 then x11 <> 0 *) \n        ((0: vect n1), ('C[x11]^-1).* x21: vect n1) else\n        let x32 := factor n1 x12 x22 in\n          (* We have x12 ∨ x32 = x22 *)\n             (* let x31 such that x12 /\\ x31 = x11 ∨ x32 - x21                            *)\n             (* (x11,x12) /\\ (x31,x32) = (x11 /\\ x32 - x12 /\\ x31, x12 /\\ x32) (x21, x22) *)\n             (factor n1 x12 (add n1 (('C[x11]) .* x32: vect n1) (scal n1 (-(1))%f  x21: vect n1))\n               , x32)\n   end.\n\nLemma factor0 n x : factor n x 0 = 0.\nProof.\ninduction n as [| n IH]; simpl; auto.\nrewrite multK0l; auto.\ndestruct x; case eq0_spec; intros Hx2; subst; Vfold n; Grm0.\nrewrite IH; Grm0; rewrite IH; auto.\nQed.\n\nLemma factor_scal n k x M : factor n x (k .* M) = k .* factor n x M.\nProof.\ninduction n as [| n IH]; simpl.\nrewrite multK_assoc; auto.\ndestruct x as [x1 x2]; destruct M as [M1 M2].\ncase eq0_spec; intros Hx2; subst; Vfold n; Grm0.\nrewrite <-!scal_multE, multK_com; auto.\napply f_equal2 with (f := @pair _ _); rewrite IH; auto.\napply sym_equal; rewrite <-IH.\nrewrite scal_addEr, !(scalE_swap _ (fn n) k); auto.\nQed.\n\nLemma factor_id n x : x <> 0 -> hom n 1 x -> factor n x x = 1.\nProof.\ninduction n as [| n IH]; simpl; auto; try Vfold n.\nintros H; case eqK_spec; intros; auto; case H; auto; discriminate.\nintros Hd; destruct x.\nrewrite !andbP; intros (Hx1, Hx2).\nrewrite (hom0E _ _ Hx1), !constk, !scalk, <-opp_multKl, multK1l; auto.\ncase eq0_spec; intros H1x2; subst.\nrewrite invKr; auto; intros Hk1; case Hd.\nrewrite (hom0E _ _ Hx1), Hk1; Grm0.\nrewrite IH, scalk, multK1r, addk, oppKr, factor0; auto.\nQed.\n\nLemma factor_hom0E n x1 x2 : x1 <> 0 ->  hom n 1 x1 -> hom n 0 x2 ->\n  factor n x1 (x1 ∨ x2) = x2.\nProof.\nintros Hx1 H1x1 Hx2.\nrewrite (hom0E _ _ Hx2), joinkr, factor_scal, factor_id, scalk, multK1r; auto.\nQed.\n\nLemma factor_factor n x1 x2 : hom n 1 x1 -> x1 <> 0 ->  \n  x1 ∨ x2 = 0 -> x2 = x1 ∨ factor n x1 x2.\nProof.\ninduction n as [| n IH]; simpl; auto; try Vfold n.\ncase eqK_spec; auto; try (intros; discriminate).\nintros H1 _ H2; case H2; auto.\ndestruct x2 as [x3 x4]; destruct x1 as [x1 x2].\nrewrite !andbP; intros (Hu1, Hu2) H3.\nrewrite (hom0E _ _ Hu1), constk; auto.\nrewrite !joinkl, (conjf_hom _ _ _ Hu2); simpl expK; rewrite multK1r; auto.\ncase eq0_spec; intros He2; subst.\nGrm0; intros HH; injection HH; clear HH; intros HH.\ncase (scalE_integral _ (fn n) _ _ HH); clear HH; intros HH; subst; auto.\ncase H3; rewrite (hom0E _ _ Hu1), HH; auto.\nrewrite joinkl, <- scal_multE, invKl, scalE1; Grm0; auto.\nintros HH; case H3; rewrite (hom0E _ _ Hu1), HH; auto.\nintros HH; injection HH; Vfold n; intros Hr1 Hr2.\nassert (H1: x2 ∨ factor n x2 x4 = x4).\nrewrite <-IH; auto.\napply f_equal2 with (f := @pair _ _); auto.\nrewrite joinkl, join_scall, <-IH, scal_addEr, <-addE_assoc,\n        scal_addE0, addE0l, <-scal_multE, multK_m1_m1, scalE1; auto.\nrewrite join_addr, !join_scalr, H1, <-join_scall; auto.\nQed.\n\nLemma factork n x k : x <> 0 -> hom n 1 x -> factor n x [k] = 0.\nProof.\ninduction n as [| n IH]; simpl.\nintros  H1 H2; case H1; generalize H2.\ncase eqK_spec; auto; intros; discriminate.\nintros Hx; destruct x; rewrite andbP; intros (H1,H2); Vfold n.\ncase eq0_spec; Grm0; intros H3.\nrewrite IH; Grm0.\nrewrite factor0; auto.\nQed.\n\nLemma factor0_hom0 n x1 x2 : x1 <> 0 -> hom n 1 x1 -> hom n 0 x2 -> \n  factor n x1 x2 = 0.\nProof.\nintros H1 H2 H3; rewrite (hom0E _ _ H3); apply factork; auto.\nQed.\n\nLemma factor_hom n k x1 x2 : x1 <> 0 -> x1 ∨ x2 = 0 -> \n  hom n 1 x1 -> hom n k.+1 x2 -> hom n k (factor n x1 x2).\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; intros k; simpl; auto; try Vfold n.\ncase eqK_spec; auto; try (intros; discriminate).\nintros H1 H2; case H2; auto.\nintros H Heq; destruct x2 as [x3 x4]; destruct x1 as [x1 x2];\n     rewrite !andbP; intros (Hu1,Hu2) (Hu3, Hu4).\ncase eq0_spec; intros Hx2; subst.\ndestruct k as [| k]; rewrite ?eq0I, ?homk0, scal_hom; auto.\n injection Heq; Vfold n; rewrite (hom0E _ _ Hu1).\nrewrite conjf_hom with (1 := Hu2); simpl expK; \n  rewrite multK1r, joinkl; auto.\nintros Heq1 Heq2.\nrewrite constk; auto.\nsimpl in x3.\nassert (Heq3: x2 ∨ ('C[x1] .* factor n x2 x4 + (- (1)).* (x3 : vect n)) = 0).\n  rewrite join_addr, !join_scalr, <-factor_factor, <-join_scall; auto.\ndestruct k as [| k]; rewrite andbP; split; auto.\nrewrite factor0_hom0; try rewrite eq0I; auto.\nQed.\n\nLemma factor_add n k x1 x2 x3 : x1 <> 0 ->\n  hom n 1 x1 -> hom n k.+1 x2 -> hom n k.+1 x3 ->\n  x1 ∨ x2 = 0 -> x1 ∨ x3 = 0 ->\n  factor n x1 (x2 + x3) = factor n x1 x2 + factor n x1 x3.\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; simpl; auto.\nintros k H; case eqK_spec; auto; intros H1 H2; case H; auto; discriminate.\nintros k; destruct x1 as [x11 x12]; destruct x2 as [y11 y12];\n  destruct x3 as [z11 z12]; rewrite !andbP; Vfold n.\nfold vect in x11, x12, y11, y12, z11, z12.\nintros H1 (H2,H3) (H4, H5) (H6, H7) HH1 HH2.\ninjection HH1; injection HH2; Vfold n; intros Eq1 Eq2 Eq3 Eq4; clear HH1 HH2.\nrewrite (hom0E _ _ H2), !constk.\ncase eq0_spec; intros Hex12; subst; Vfold n; Grm0.\nrewrite scal_addEr; auto.\nsimpl in y12.\nassert (Hf: \n  factor n x12 (y12 + z12) = factor n x12 y12 + factor n x12 z12).\n   apply IH with (k := k); auto.\napply f_equal2 with (f := @pair _ _); auto.\nrewrite Hf.\nassert (Heq: forall kk (xx yy zz tt: vect n),\n            (kk .* (xx + yy) + (-(1)).* (zz + tt) = \n            (kk .* xx + (-(1)).* zz) + (kk .* yy + (-(1)).* tt))).\nintros kk xx yy zz tt.\nrewrite !scal_addEr, !addE_assoc; auto.\napply f_equal2 with (f := add n); auto.\nrewrite addE_com, !addE_assoc; auto.\napply f_equal2 with (f := add n); auto.\nrewrite addE_com; auto.\nrewrite Heq; clear Heq.\ndestruct k as [| k].\nassert (Hv1: x12 ∨ ('C[x11] .* factor n x12 y12 + (- (1)).* y11) = 0).\n  rewrite join_addr, !join_scalr, <-factor_factor, <-join_scall; auto.\n  generalize Eq4; pattern x11 at 1; rewrite (hom0E _ _ H2), joinkl.\n  rewrite conjf_hom with (1 := H3); simpl expK;\n  rewrite multK1r; auto.\nassert (Hv2: x12 ∨ ('C[x11] .* factor n x12 z12 + (- (1)).* z11) = 0).\n  rewrite join_addr, !join_scalr, <-factor_factor, <-join_scall; auto.\n  generalize Eq2; pattern x11 at 1; rewrite (hom0E _ _ H2), joinkl.\n  rewrite conjf_hom with (1 := H3); simpl expK;\n  rewrite multK1r; auto.\nrewrite !factor0_hom0; Grm0;\n  apply add_hom; try apply scal_hom; try apply factor_hom; auto.\napply add_hom; try apply scal_hom; try apply factor_hom; auto.\napply add_hom; try apply scal_hom; try apply factor_hom; auto.\napply IH with (k := k); auto;\n  try apply add_hom; try apply scal_hom; \n  try apply factor_hom; auto.\nrewrite join_addr, !join_scalr, <-factor_factor, <-join_scall; auto.\ngeneralize Eq4; pattern x11 at 1; rewrite (hom0E _ _ H2), joinkl.\nrewrite conjf_hom with (1 := H3); simpl expK;\n  rewrite multK1r; auto.\nrewrite join_addr, !join_scalr, <-factor_factor, <-join_scall; auto.\ngeneralize Eq2; pattern x11 at 1; rewrite (hom0E _ _ H2), joinkl.\nrewrite conjf_hom with (1 := H3); simpl expK;\n  rewrite multK1r; auto.\nQed.\n\n(* Orthogonalité for factorisation, i.e. condition for factorisation to be idempotent *)\nFixpoint fortho n : (vect n) -> (vect n) -> bool :=\n  match n return vect n -> vect n -> bool with\n  | O => fun x1 x2 => false\n  | S n1 =>\n        fun x1 x2 =>\n        let (x11, x12) := x1 in\n        let (x21, x22) := x2 in\n        if x12 ?= 0 then x21 ?= 0 else  fortho n1 x12 x21 && fortho n1 x12 x22\n   end.\n\nLemma fortho0 n : 0 < n -> fortho n 0 0.\nProof.\nintros H; destruct n; simpl.\ncontradict H; auto with arith.\nrewrite !eq0I; auto.\nQed.\n\nLemma fortho_refl n x : fortho n x x -> x = 0.\nProof.\ninduction n as [|n IH]; simpl.\nintros H; discriminate.\ndestruct x; case eq0_spec.\ncase eq0_spec; intros; subst; auto; discriminate.\nintro Hx1; rewrite andbP; intros (Hx2x1, Hx1x2).\ncase Hx1; apply IH; auto.\nQed. \n\nLemma forthok n k1 k2 (v: vect n) : v <> 0 -> hom n k1.+1 v -> fortho n v [k2].\nProof.\ngeneralize k1 k2; clear k1 k2.\ninduction n as [| n IH]; simpl; auto; try Vfold n.\nintros _ _; case eqK_spec; auto; intros H1 H2; subst; auto; case H2; auto.\nintros k k1; destruct v; rewrite andbP; intros HH.\ncase eq0_spec; intros HH2; subst; auto.\nrewrite eq0I; auto.\nintros (H1, H2).\nrewrite (IH _ k), (IH _ k 0%f); auto.\nQed.\n\nLemma fortho_scal n k v1 v2 : fortho n v1 v2 -> fortho n v1 (k .* v2).\nProof.\ninduction n as [| n IH]; simpl; auto; try Vfold n.\ndestruct v1; destruct v2; case eq0_spec; auto.\ncase eq0_spec; auto; intros; subst; try discriminate; Grm0.\nrewrite eq0I; auto.\nrewrite andbP; intros Hy1 (Hr1, Hr2).\nrewrite !IH; auto.\nQed.\n\nLemma fortho_add n v1 v2 v3 : \n  fortho n v1 v2 -> fortho n v1 v3 -> fortho n v1 (v2 + v3).\nProof.\ninduction n as [| n IH]; simpl; auto; try Vfold n.\ndestruct v1; destruct v2; destruct v3.\ncase eq0_spec.\n  do 2 (case eq0_spec; auto; try (intros; discriminate));\n  intros; subst; Grm0.\n  rewrite eq0I; auto.\nrewrite andbP, andbP; intros Hy1 (H1, H2) (H3, H4).\nrewrite !IH; auto.\nQed.\n\nLemma fortho_conj n b v1 v2 : fortho n v1 v2 -> fortho n v1 (v2 ^_ b).\nProof.\ngeneralize b; clear b.\ninduction n as [| n IH]; simpl; auto; try Vfold n.\nintros b; destruct v1; destruct v2.\ncase eq0_spec.\n  case eq0_spec; auto; try (intros; discriminate);\n  intros; subst; Grm0.\n  rewrite eq0I; auto.\nrewrite andbP, andbP; intros Hy1 (H1, H2).\nrewrite !IH; auto.\nQed.\n\nLemma fortho_join n v1 v2 v3 : \n  fortho n v1 v2 -> fortho n v1 v3 -> fortho n v1 (v2 ∨ v3).\nProof.\ninduction n as [| n IH]; simpl; auto; Vfold n.\ndestruct v1; destruct v2; destruct v3.\ncase eq0_spec.\n  do 2 (case eq0_spec; auto; try (intros; discriminate));\n  intros; subst; Grm0.\n  rewrite eq0I; auto.\nrewrite andbP, andbP; intros Hy1 (H1, H2) (H3, H4).\nrewrite fortho_add, !IH; auto.\nrewrite IH; auto.\nrewrite fortho_conj; auto.\nQed.\n\nLemma fortho_joinl n k v l : v <> 0 -> hom n k.+1 v -> \n  (forall v1, In v1 l -> fortho n v v1) -> fortho n v (joinl n l).\nProof.\nintros Hv Hhv; induction l as [| a l IH]; simpl; try Vfold n; auto.\nintros; apply (forthok n k 0%f); auto.\nintros; destruct l; auto.\napply fortho_join; auto with datatypes.\nQed.\n\n(* Here we are *)\nLemma factor_ortho n x1 x2 : x1 <> 0 -> hom n 1 x1 -> \n    fortho n x1 x2 -> factor n x1 (x1 ∨ x2) = x2.\nProof.\ninduction n as [| n IH]; simpl; auto; try Vfold n.\nintros H1 H2; case H1; generalize H2; case eqK_spec; auto.\nintros; discriminate.\ndestruct x2 as [y1 y2]; destruct x1 as [x1 x2]; case eq0_spec.\nrewrite andbP; case eq0_spec; intros Hx2 Hy1 HH (HH1,HH2) Ht;\n  subst; Grm0; try discriminate.\npattern x1 at 2; rewrite (hom0E _ _ HH1).\nrewrite joinkl, <-scal_multE, invKr, scalE1; auto.\nintros HH3; case HH; rewrite (hom0E _ _ HH1), HH3; auto.\nrewrite andbP, andbP; intros Hy1 HH (HH1,HH2) (Ht1, Ht2); try discriminate.\nrewrite IH; auto.\npattern x1 at 2; rewrite (hom0E _ _ HH1).\nrewrite joinkl, scal_addEr, <-scal_multE,\n        <-addE_assoc, <-scal_addEl, <-opp_multKl, multK1l, oppKr;\n  Grm0.\nrewrite factor_scal, (conjf_hom _ _ _ HH2); simpl expK.\nrewrite multK1r, join_scall, factor_scal, IH, <-scal_multE,\n        multK_m1_m1, scalE1; auto.\nQed.\n\n(* Getting the canceling factor for fortho *)\nFixpoint fget n : (vect n) -> (vect n) -> K :=\n  match n return vect n -> vect n -> K with\n  | O => fun x1 x2 => 0%f\n  | S n1 =>\n        fun x1 x2 =>\n        let (x11, x12) := x1 in\n        let (x21, x22) := x2 in\n        if x12 ?= 0 then (('C[x11])^-1 * 'C[x21])%f else fget n1 x12 x22\n   end.\n\nLemma fget_scal n k x1 x2 : fget n x1 (k .* x2) = (k *  fget n x1 x2)%f.\nProof.\ninduction n as [| n IH]; simpl; auto; try Vfold n; Krm0.\ndestruct x1; destruct x2; case eq0_spec; auto.\nrewrite const_scal, <-!multK_assoc, (multK_com _ Hp k); auto.\nQed.\n\nLemma fortho_fget n x1 x2 : x1 <> 0 -> hom n 1 x1 -> hom n 1 x2 ->\n    fortho n x1 (x2 + (-(1) * fget n x1 x2)%f .* x1).\nProof.\ninduction n as [| n IH]; simpl; auto; try Vfold n.\ncase eqK_spec; auto; try (intros; discriminate).\nintros HH HH1; case HH1; auto.\ndestruct x2 as [y1 y2]; destruct x1 as [x1 x2].\nintros HH; rewrite !andbP; intros (H1, H2) (H3, H4).\npattern x1 at 2 4; rewrite (hom0E _ _ H1).\npattern y1 at 1 3; rewrite (hom0E _ _ H3).\ncase eq0_spec; intros H5; subst.\nrewrite !scalk, addk, (multK_com _ Hp ('C[x1]^-1)%f), !multK_assoc,\n        invKr, multK1r; Krm1.\nrewrite oppKr, eq0I; auto.\nintros HH1; case HH; rewrite (hom0E _ _ H1), HH1; auto.\nrewrite andbP; split.\napply fortho_add; try apply fortho_genk; auto.\nrepeat apply fortho_scal; auto.\napply forthok with 0%nat; auto.\nrepeat apply fortho_scal; auto.\napply forthok with 0%nat; auto.\napply IH; auto.\nQed.\n\nLemma joinl_addmult n (f: vect n -> vect n -> K) x l :\nhom n 1 x -> (forall i, In i l -> hom n 1 i) ->\nx ∨ joinl n l = x ∨ joinl n (map (fun y => (y + (f x y) .* x)) l).\nProof.\nintros Hk1 Hl; induction l as [| a l IH]; auto.\ncase (list_case _ l); intros Hll.\nsubst; simpl; Vfold n.\nrewrite join_addr, !join_scalr, join_hom1_id; Grm0.\nsimpl map; rewrite !joinlS; auto; Vfold n.\nrewrite <-!join_assoc, join_addr, !join_scalr, join_hom1_id; Grm0.\nrewrite (join_hom_com n 1 1 a x); auto with datatypes.\nrewrite !join_scall, !join_assoc, IH; auto with datatypes.\ndestruct l; auto; intros HH; discriminate.\nQed.\n\nLemma mprod_hom n k l1 l2 :\n  (forall i, In i l2 -> hom n k i) -> hom n k (l1 *X* l2).\nProof.\ngeneralize k l2; clear k l2.\ninduction l1 as [| a l1 IH].\nintros; rewrite mprod0l; apply homk0.\nintros k [| b l2] H; auto.\nrewrite mprod0r; apply homk0.\nrewrite mprod_S; auto with datatypes.\nQed.\n\nHint Resolve mprod_hom : core.\n\nDefinition is_decomposable n M := exists l, decomposable n l M.\n\nLemma joinl_factor n x M : x <> 0 -> hom n 1 x ->\n  is_decomposable n M -> x ∨ M = 0 ->\n    exists k, exists l, (forall v, In v l -> hom n 1 v) /\\ M = k .* joinl n (x::l).\nProof.\nintros Hx Hhx (l, Hl) HxM.\ncase (eqE_spec _ (fn n) M 0); intros HM.\nexists 0%f; exists (x::nil); split; Grm0.\nsimpl; intros v [Hv | []]; subst; auto.\nassert (Hv: is_vector n x).\nred; rewrite cbl1_hom1_equiv; auto.\nrewrite (decomp_cbl _ _ _ _ Hv Hl) in HxM; auto.\ncase cbl_mprod with (2 := HxM); auto.\nintros ll (H1ll, H2ll); subst.\ncase Hl; intros Hu1 HU2; subst.\nassert (Hu4: forall x, In x l -> hom n 1 x).\nintros x H1x; rewrite <-cbl1_hom1_equiv; auto.\napply Hu1; auto.\ngeneralize l H1ll Hx Hu4; elim ll; clear ll l Hx Hhx H1ll HxM Hl Hv Hu1 Hu4 HM.\nintros l Hl HH; case HH; auto.\nintros a ll IH [|b l] Hl H1 H2; try discriminate.\ncase (eqK_spec _ Hp a 0%f); intros H4; subst.\nrewrite mprod_S; Grm0.\ncase (IH l); auto with datatypes.\nintros HH; case H1; rewrite mprod_S, HH; Grm0.\nrewrite (scalE0l (vn_eparams n)); auto.\nintros k (l1, (H1l1, H2l1)).\nexists k%f; exists ((-(1)).* b::l1); split.\nsimpl; intros v [Hv|Hv]; subst; auto.\nVfold n; apply scal_hom; auto with datatypes.\nrewrite joinl_swap, joinlS, joinlS, H2l1.\nrewrite join_scall, <-(scal_multE _ (fn n) (-(1))%f); auto.\nrewrite multK_m1_m1, scalE1, join_scalr; auto.\nrewrite (scalE0l (vn_eparams n)); auto. rewrite (addE0l (vn_eparams n)); auto.\nintros HH; discriminate.\nintros HH; subst; destruct ll; try discriminate.\ncase H1; rewrite mprod_S; Grm0.\nrewrite (scalE0l (vn_eparams n)); auto.\napply cbl_trans with l; auto.\nintros; rewrite cbl1_hom1_equiv; auto with datatypes.\nrewrite (scalE0l (vn_eparams n)); auto.\nrewrite addE0l; auto.\napply mprod_cbl; auto.\napply cbl_scal.\nrewrite cbl1_hom1_equiv; auto with datatypes.\nexists (a^-1)%f; exists l; split; auto with datatypes.\ncase (list_case _ l); intros Hll.\nrewrite Hll; simpl; Vfold n; rewrite mprod_S, mprod0r; Grm0.\nrewrite <-scal_multE, invKr, scalE1; auto.\nrewrite mprod_S, !joinlS, join_addl, scal_addEr; auto.\nrewrite join_scall, <-scal_multE, invKr, scalE1; auto.\nreplace (ll *X* l ∨ joinl n l) with (0: vect n); Grm0.\ninjection Hl.\ngeneralize ll H2; elim l; clear l ll IH Hl H1 H2 Hll.\nintros; rewrite mprod0r; Grm0.\nintros a1 l1 IH ll H1 H2.\ndestruct ll as [| b1 ll].\nrewrite mprod0l; Grm0.\ncase (list_case _ l1); intros Hll1.\nrewrite Hll1; simpl; Vfold n; rewrite mprod_S, mprod0r; Grm0.\nrewrite join_scall, join_hom1_id; Grm0; auto with datatypes.\nrewrite mprod_S, joinlS, join_addl; auto.\nrewrite join_scall, <-join_assoc, join_hom1_id; Grm0; auto with datatypes.\nrewrite <- join_assoc.\nrewrite (join_hom_com n 1 1 a1 (ll *X* l1)); auto with datatypes.\nrewrite join_scall, join_assoc, <- IH; Grm0; auto.\nsimpl; intros x [Hx|Hx]; subst; auto with datatypes.\nQed.\n\nLemma decomposable_factor n k x M : x <> 0 -> hom n 1 x -> hom n k.+2 M ->\n  is_decomposable n M -> x ∨ M = 0 -> is_decomposable n (factor n x M).\nProof.\nintros Hx Hhx HhM HM HxM.\ncase (joinl_factor n x M); auto.\nintros k1 (l, (H1l, H2l)); subst; red.\ncase (list_case _ l); intros Hl.\nsubst; simpl joinl.\nrewrite factor_scal, factor_id; auto.\ncase (homE n 1 k.+2 (k1 .* x)); try (intros; discriminate); auto.\nintros HH1; case (scalE_integral _ (fn n) _ _ HH1); intros HH2; subst; Grm0.\nexists (x::x::nil).\nsplit.\nsimpl; intros x1 [H1| [H1 | H1]]; subst; red; rewrite cbl1_hom1_equiv; auto.\nsimpl joinl; rewrite join_hom1_id; auto.\ncase Hx; auto.\nrewrite joinlS, factor_scal; auto. \nrewrite (joinl_addmult n (fun x y => (-(1) * ((fget n x y)))%f)); auto.\ndestruct l as [| a l].\ncase Hl; auto. \nexists (map (fun y : vn_eparams n => y + (- (1) * fget n x y)%f .* x) (k1 .* a::l)).\nsplit; auto.\nsimpl map; intros x1; simpl In; Vfold n; intros [Hx1|Hx1]; auto with datatypes.\nred; rewrite cbl1_hom1_equiv, <-Hx1, add_hom; auto with datatypes.\nrewrite in_map_iff in Hx1; case Hx1; intros x2 ([], H2x2).\nred; rewrite cbl1_hom1_equiv, add_hom; auto with datatypes.\nsimpl map; Vfold n.\nrewrite factor_ortho; auto.\nrewrite <-joinl_scal, scal_addEr, scal_multE, scalE_swap, <-!scal_multE,\n        fget_scal, multK_assoc; auto.\napply fortho_joinl with 0%nat; auto.\nintros v2 Hv2; case in_inv with (1 := Hv2).\nintros Hv3; subst.\napply fortho_fget; auto with datatypes.\nrewrite in_map_iff; intros (v3, ([], H2v3)).\napply fortho_fget; auto with datatypes.\nQed.\n\n(* A factor of a special degre *)\nFixpoint one_factor (n: nat) k : vect n -> vect n :=\n  match n return vect n -> vect n with \n  | O => fun a  => a \n  | S n1 => fun l =>\n          match k with \n          | O => l\n          | S k1 => \n            let (l1,l2) := l in\n            let r := one_factor n1 k1 l1 in  \n            (0:vect n1, if r ?= 0 then one_factor n1 k l2 else r)\n          end\n  end.\n\nLemma one_factor0 n k : one_factor n k 0 = 0.\nProof.\ngeneralize k; induction n as [| n IH]; simpl; auto; clear k.\nintros k; case k; simpl; auto; intros n0; case eq0_spec; rewrite !IH; auto.\nQed.\n\nLemma one_factor_hom n k1 k2 (x: vect n) :\n k2 < k1 -> hom n k1 x -> hom n (k1 - k2) (one_factor n k2 x).\nProof.\ngeneralize k1 k2; clear k1 k2.\ninduction n as [| n IH]; simpl; auto.\nintros [|k1][|k2]; auto with arith.\nintros _ H; rewrite H; case minus; auto.\nintros [| k1] [|k2] Heq; destruct x; rewrite andbP; intros (Ho1,Ho2); auto.\ncontradict Heq; auto with arith.\ncontradict Heq; auto with arith.\nsimpl; rewrite Ho1, Ho2; auto.\ngeneralize (minus_match k2.+1 k1.+1); case_eq (k1.+1 - k2.+1)%nat.\nintros _ H1; contradict H1; auto with arith.\nintros n1 Hn1 _; rewrite <-Hn1.\ncase eq0_spec; intros H1; try (case eq0_spec; intros H2).\nrewrite homk0, IH; auto.\nrewrite homk0.\nsimpl; rewrite IH; auto with arith.\nQed.\n\nHint Resolve one_factor_hom : core.\n \nLemma one_factor_zero n k1 k2 (x: vect n) :\n k2 < k1 -> hom n k1 x -> one_factor n k2 x = 0 -> x = 0.\nProof.\ngeneralize k1 k2; clear k1 k2.\ninduction n as [| n IH]; simpl; auto.\nintros [|k1][|k2] Hk1k2; destruct x; auto;\n   try (contradict Hk1k2; auto with arith; fail).\nrewrite andbP; intros (Ho1,Ho2); auto.\nassert (Hl : k2 < k1) by auto with arith.\ncase eq0_spec; auto.\nintro Hv.\nrewrite (IH _ _ _  Hl Ho1 Hv).\nintros HH; injection HH; intros Hv0.\nrewrite (IH _ _ _  Hk1k2 Ho2 Hv0); auto.\nintros HH1 HH2; case HH1; injection HH2; auto.\nQed.\n\n(* Iterated contraction *)\n\nDefinition mcontra n (ll: list (kn n)) (x: vect n) :=\n  fold_left (fun x l => #<l,x>#) ll x.\n\nNotation \"#<< l , x >>#\" := (mcontra _ l x).\n\nLemma mcontra_nil n (x: vect n) : #<<nil, x>># = x.\nProof. simpl; auto. Qed.\n\nLemma mcontra_cons n (x: vect n) a l : #<<a::l, x>># = #<<l, #<a,x>#>>#.\nProof. simpl; auto. Qed.\n\nLemma mcontra_app n l1 l2 (M: vect n) :  \n  #<< l1 ++ l2, M>># = #<<l2, #<<l1, M>>#>>#.\nProof.\ngeneralize M; clear M.\ninduction l1 as [| l l1 IH]; simpl; intros; \n try rewrite IH; auto.\nQed.\n\nLemma mcontra0 n lfs : #<< lfs, 0 >># = (0: vect n).\nProof.\ninduction lfs as [| lf lfs IH]; simpl; auto.\nVfold n; rewrite contra0r, IH; auto.\nQed.\n\nHint Rewrite mcontra0: GRm0.\n\nLemma mcontra_id n a l (M: vect n) : #<< a::a::l, M>># = 0.\nProof. simpl; rewrite contra_id, mcontra0; auto. Qed.\n\nLemma mcontrak n lfs i : lfs <> nil -> #<< lfs, [i] >># = (0: vect n).\nProof.\ninduction lfs as [| lf lfs IH]; simpl; intros HH.\ncase HH; auto.\ndestruct lfs as [|lf1 lfs].\nrewrite mcontra_nil, contrak; auto.\nrewrite contrak, mcontra0; auto.\nQed.\n\nLemma mcontra_scal n k lfs (x: vect n) : #<< lfs, k .* x >># = k .* #<< lfs , x >>#.\nProof.\ngeneralize x; clear x.\ninduction lfs as [| lf lfs IH]; simpl; Vfold n; auto.\nintros; rewrite contra_scalr, IH; auto.\nQed.\n\nLemma mcontra_swap n a b l (M: vect n) :  \n  #<< a::b::l, M>># = (-(1)).*  #<<b::a::l, M>>#.\nProof.\nsimpl; Vfold n; rewrite contra_swap, mcontra_scal; auto.\nQed.\n\nLemma mcontra_add n lfs (x y: vect n) :\n  #<< lfs, x + y >># = #<< lfs, x >># + #<< lfs,  y >>#.\nProof.\ngeneralize x y; clear x y.\ninduction lfs as [| lf lfs IH]; simpl; intros; Vfold n; auto.\nrewrite contra_addr, IH; auto.\nQed.\n\nLemma mcontra_conj n lfs b (x: vect n) : \n  #<<lfs, x ^_ b >># = #<< lfs, x >># ^_ (iter negb (length lfs) b).\nProof.\ngeneralize b x; clear b x.\ninduction lfs as [| lf lfs IH]; simpl; Vfold n; intros b x; auto.\nrewrite contra_conj, IH.\napply f_equal2 with (f := conj n); auto.\nclear IH; induction (length lfs) as [| m IH]; simpl; auto.\nrewrite IH; auto.\nQed.\n\nLemma mcontra_hom n k (x: vect n) l :\n  hom n k x -> hom n (k - length l) #<<l, x>>#.\nProof.\ngeneralize k x; clear k x; induction l as [| a l IH];\n  intros k x Hx; simpl.\nrewrite <- Minus.minus_n_O; auto.\ndestruct k as [| k]; simpl.\nrewrite (hom0E _ _ Hx), contra_hom0; Grm0.\napply IH; auto.\nQed.\n\nHint Resolve mcontra_hom : core.\n\nLemma mcontra_hom0 n lfs M : lfs <> nil -> hom n 0 M -> #<<lfs , M>># = 0.\nProof.\nintros H H1; rewrite (hom0E _ _ H1); apply mcontrak; auto.\nQed.\n\nNotation liftk := (Kn.lift p).\n\nLemma lift_contra n lf1 x : #< liftk n lf1, lift n x ># = lift n #<lf1, x>#.\nProof.\ninduction n as [| n IH]; simpl; Krm0; auto.\ndestruct lf1; destruct x; Vfold n; Vrm0.\nrewrite contra0r; Vrm0.\nQed.\n\nLemma lift_mcontra n lfs1 x :\n  #<< map (liftk n) lfs1, lift n x >># = lift n #<<lfs1, x>>#.\nProof.\ngeneralize x; clear x.\ninduction lfs1 as [| lf lfs IH]; simpl; Vfold n; auto.\nintros x; simpl; Vfold n; Vrm0.\nrewrite contra0r; Vrm0.\napply (IH #<lf, x>#).\nQed.\n\nLemma mcontra_one_factor n k1 k2 (x: vect n) :\n  k2 < k1 -> hom n k1 x -> \n exists lfs, length lfs = k2 /\\ #<<lfs , x>># = one_factor n k2 x.\nProof.\ngeneralize k1 k2; clear k1 k2.\ninduction n as [| n IH]; simpl; auto.\nintros [| k1] k2 Hlt.\ncontradict Hlt; auto with arith.\ncase eqK_spec; auto; intros Hx; subst; try (intros; discriminate).\nexists (iter (cons tt) k2 nil); split; clear Hlt.\ninduction k2 as [| k2 IH1]; simpl; auto.\nrewrite mcontra0; auto.\nintros [| k1] k2 Hlt; destruct x.\ncontradict Hlt; auto with arith.\nrewrite andbP; intros (Hx1, Hx2).\n(*\ncase eq0_spec; intros H0x1; try (case eq0_spec; intros H1x2); subst.\nexists (iter (cons nil) k2 nil); split; clear Hlt.\ninduction k2 as [| k2 IH1]; simpl; auto.\nrewrite mcontra0; auto.\n*)\ndestruct k2 as [| k2].\nexists nil; auto.\ncase eq0_spec; intros H1x2.\ncase (IH _ _ _ Hlt Hx2); intros lf1.\nintros (Hlf1, H1lf1).\nexists (map (liftk n) lf1); split; auto.\nrewrite map_length; auto.\nrewrite one_factor_zero with (k1 := k1) (3 := H1x2); auto with arith.\ngeneralize lift_mcontra; unfold lift; intros HH1;\n rewrite HH1, H1lf1; auto.\ncase (IH _ _ _ (Lt.lt_S_n _ _ Hlt) Hx1).\nintros lfs1  (H1lfs1, H2lfs1).\nexists ((1%f, 0):: (map (liftk n) lfs1 : list (K * kn n))); simpl; Vfold n; split.\nrewrite map_length; auto.\nrewrite !contra0l, scalE1; Vrm0.\nrewrite <- H2lfs1.\napply (lift_mcontra n); auto.\nQed.\n\nInductive cbl n (l: list (vect n)): nat -> (vect n) -> Prop :=\n| cbl_in: forall v, In v l -> cbl n l 0%nat v\n| cbl_add: forall k x y, cbl n l k x -> cbl n l k y -> cbl n l k (x + y)\n| cbl_scal: forall k k1 x, cbl n l k x -> cbl n l k (k1 .* x)\n| cbl_join: forall k v x, In v l -> cbl n l k x -> cbl n l k.+1 (v ∨ x).\n\nLemma cbl_cons n (a: vect n) l k x : cbl n l k x -> cbl n (a::l) k x.\nProof.\nintros H; elim H; simpl; auto with arith;\n  intros; constructor; auto with datatypes.\nQed.\n\nLemma joinl_join n l (v: vect n) : \n  (forall x, In x l -> hom n 1 x) -> In v l -> v ∨ joinl n l = 0.\nProof.\nintros Hv Hivl; rewrite <-joinlS.\napply (cbl_joinl0_mprod n); auto.\nintros i Hi; red; rewrite cbl1_hom1_equiv; auto.\nconstructor; auto.\nintros Hl; subst; case Hivl.\nQed.\n\nLemma cbl_joinl n (l: list (vect n)) :\n  l <> nil -> (forall x, In x l -> hom n 1 x) -> cbl n l (pred (length l)) (joinl n l).\nProof.\ninduction l as [| a l IH]; auto.\nintros HH; case HH; auto.\nintros _ H1.\ndestruct l as [| b l].\nsimpl pred; rewrite joinl1; constructor; auto with datatypes.\nrewrite joinlS.\nchange (pred(length (a::b :: l))) with (1 + (pred (length (b :: l))))%nat.\nconstructor; auto with datatypes.\napply cbl_cons; apply IH; auto with datatypes.\nintros; discriminate.\nQed.\n\nLemma cbl_joinl0 n (l: list (vect n)) k x :\n  (forall x, In x l -> hom n 1 x) -> cbl n l k x -> x ∨ joinl n l = 0.\nProof.\nintros Hl HH; elim HH; clear x HH; auto.\nintros; apply joinl_join; auto.\nintros k1 x y Hx Hmx Hy Hmy.\n rewrite join_addl, Hmx, Hmy; Vrm0.\nintros k1 k2 x Hx Hmx; rewrite join_scall, Hmx; Vrm0.\nintros k1 v x Hl1 Hx Hmx.\nrewrite join_assoc, Hmx; Grm0.\nQed.\n\nLemma cbl_hom n (l: list (vect n)) k x :\n  (forall x, In x l -> hom n 1 x) -> cbl n l k x -> hom n k.+1 x.\nProof.\nintros Hl HH; elim HH; clear x HH; auto.\nintros k1 v x Hv Hvc Hmx; apply (join_hom n 1 k1.+1); auto.\nQed.\n\nLemma cbl_contra n (l: list (vect n)) lf k x :\n  (forall x, In x l -> hom n 1 x) -> cbl n l k.+1 x -> cbl n l k #<lf, x>#.\nProof.\nintros Hl; generalize k x; clear k x.\nassert (H: forall (k k1 : nat) (x : vect n), cbl n l k x -> \n                k = k1.+1 ->  cbl n l k1 #<lf, x >#).\nintros k k1 x HH; generalize k1; elim HH; clear x HH k; auto.\nintros; discriminate.\nintros k x y Hx IHx Hy IHy k2 Hk2; subst.\nrewrite contra_addr; apply cbl_add; auto.\nintros k k2 x Hx IHx k3 Hk3; subst.\nrewrite contra_scalr; apply cbl_scal; auto.\nintros k v x Hv Hx IHx k2 HH; injection HH; intros HH1; subst.\nassert (Hm1: hom n 1 v) by auto.\nassert (Hmx: hom n k2.+1 x) by (apply cbl_hom with l; auto).\nrewrite (contra_join n lf 1 k2.+1); auto.\napply cbl_add; auto.\nrewrite contra_const, joinkl; auto.\napply cbl_scal; auto.\nrewrite join_scall; apply cbl_scal; auto.\ndestruct k2 as [| k2].\nrewrite contra_const, joinkr; auto.\napply cbl_scal; auto.\napply cbl_in; auto.\napply cbl_join; auto.\nintros k x HH; apply H with k.+1; auto.\nQed.\n\nLemma cbl_mcontra n (l: list (vect n)) lfs k x :\n  length lfs <= k ->\n  (forall x, In x l -> hom n 1 x) -> cbl n l k x -> cbl n l (k - length lfs) #<<lfs, x>>#.\nProof.\nintros Hk HH; generalize k x Hk; clear k x Hk.\ninduction lfs as [| lf lfs IH]; simpl; intros [| k] x Hk;\n  try (contradict Hk; auto with arith; fail); simpl; auto.\nintros H1; apply IH; auto with arith.\ndestruct k as [| k]; apply cbl_contra; auto.\nQed.\n\nLemma decomp_one_factor_hom n (l: list (vect n)) M : l <> nil ->\n decomposable n l M -> hom n 1 (one_factor n (pred (length l)) M).\nProof.\nintros Hd H.\nassert (Hhm:= decomp_hom n l M H).\ncase H; intros H1 H2; subst; clear H.\nassert (Hl: pred (length l) < length l).\ndestruct l; simpl; auto with arith; case Hd; auto.\nassert (Hh: forall x, In x l -> hom n 1 x).\nintros a Ha; rewrite <- cbl1_hom1_equiv; auto.\napply H1; auto.\ncase (mcontra_one_factor n (length l) (pred (length l)) (joinl n l)); auto.\nintros ll (H1ll,H2ll); rewrite <-H2ll.\nreplace 1%nat with (length l - length ll)%nat.\napply mcontra_hom; auto.\nrewrite H1ll; destruct l; simpl length; auto with arith.\nintros; simpl length; simpl pred; \n  rewrite <- Minus.minus_Sn_m, <-Minus.minus_n_n; auto.\nQed.\n\nLemma decomp_one_factor0 n (l: list (vect n)) M :\n decomposable n l M -> one_factor n (pred (length l)) M = 0 -> M = 0.\nProof.\nintros H1 H2.\ncase (list_case _ l); intros H; subst.\ncase H1; simpl; auto.\napply one_factor_zero with (k1 := length l) (3 := H2); auto.\ndestruct l; simpl; auto with arith.\ncase H; auto.\napply decomp_hom; auto.\nQed.\n\nLemma decomp_one_factor_join n (l: list (vect n)) M :\n decomposable n l M -> one_factor n (pred (length l)) M ∨ M = 0.\nProof.\nintros H.\ncase (list_case _ l); intros Hl; subst.\ncase H; simpl; auto; intros _ H1; rewrite H1; Grm0.\nassert (Hhm:= decomp_hom n l M H).\ncase H; intros H1 H2; subst; clear H.\nassert (Hl1: pred (length l) < length l).\ndestruct l; simpl; auto with arith; case Hl; auto.\nassert (Hh: forall x, In x l -> hom n 1 x).\nintros a Ha; rewrite <- cbl1_hom1_equiv; auto.\napply H1; auto.\napply cbl_joinl0 with (k := 0%nat); auto.\ncase (mcontra_one_factor n (length l) (pred (length l)) (joinl n l)); auto.\nintros ll (H1ll,H2ll); rewrite <-H2ll.\nreplace 0%nat with (pred (length l) - length ll)%nat.\napply cbl_mcontra; try rewrite H1ll; auto with arith.\napply cbl_joinl; auto.\nrewrite H1ll; auto with arith.\nQed.\n\nFixpoint decomposek (n: nat) k (v: vect n) {struct k} : list (vect n) :=\n  match k with \n  | O => nil \n  | S O => v::nil \n  | S k1 => let v1 := one_factor n k1 v in\n            v1::decomposek n k1 (factor n v1 v)\n  end.\n\nLemma decomposekSS (n: nat) k (v: vect n) :\n  decomposek n k.+2 v =  \n    one_factor n k.+1 v::\n       decomposek n k.+1 (factor n (one_factor n k.+1 v) v).\nProof. auto. Qed.\n\nLemma decomposek_cor n k v : \nv <> 0 -> is_decomposable n v -> hom n k v -> decomposable n (decomposek n k v) v.\nProof.\ngeneralize v; clear v.\ninduction k as [|k IH].\nintros v Hv (l, Hl) H1.\ncase (homE n 0 (length l) v); auto.\napply decomp_hom; auto.\ndestruct l; simpl; auto; intros; discriminate.\nintros; subst; split; auto.\nintros i [].\nintros v Hv H1 H2; destruct k as [| k].\nrepeat split; try (intros; discriminate).\nsimpl; intros x [[]|[]].\nred; rewrite cbl1_hom1_equiv; auto.\ncase H1; intros l Hl.\nassert (F1: one_factor n k.+1 v ∨ v = 0).\nreplace k.+1 with (pred (length l)).\napply decomp_one_factor_join; auto.\ncase (homE n (length l) k.+2 v); auto.\napply decomp_hom; auto.\nintros HH1; rewrite HH1; auto.\nintros HH1; case Hv; auto.\nassert (F2: hom n 1 (one_factor n k.+1 v)).\nreplace 1%nat with (k.+2 - k.+1)%nat.\napply one_factor_hom; auto.\nrewrite <-Minus.minus_Sn_m, <-Minus.minus_n_n; auto with arith.\nassert (F3: v = one_factor n k.+1 v ∨ factor n (one_factor n k.+1 v) v).\nsimpl; apply factor_factor; auto.\nintros HH; case Hv; apply (one_factor_zero n k.+2 k.+1); auto.\ncase (IH (factor n (one_factor n k.+1 v) v)); auto.\nintros HH; case Hv; rewrite F3, HH; Grm0.\napply decomposable_factor with k; auto.\nintros HH; case Hv; rewrite F3, HH; Grm0.\napply factor_hom; auto.\nintros HH; case Hv; rewrite F3, HH; Grm0.\nintros Hr1 Hr2.\nrepeat split; try (intros; discriminate).\nintros x Hx; case (in_inv Hx); intros H1x.\nrewrite <-H1x.\nred; rewrite cbl1_hom1_equiv; auto.\napply Hr1; auto.\nrewrite decomposekSS, joinlS, <-Hr2; auto.\ndestruct k; simpl; intros; discriminate.\nQed.\n\nDefinition all_hom1 n l := fold_left (fun c x => c && hom n 1 x) l true.\n\nLemma all_hom1_cor n l :\n if all_hom1 n l then forall i, In i l -> hom n 1 i else \n     exists i, In i l /\\ ~ hom n 1 i.\nProof.\nunfold all_hom1.\nassert (F1: forall b,\n   if fold_left (fun c x => c && hom n 1 x) l b\n   then b /\\ forall i : vect n, In i l -> hom n 1 i\n   else ~b \\/ exists i, In i l /\\ ~ hom n 1 i).\ninduction l as [| a l IH]; simpl.\nintros []; auto.\nsplit; auto; intros i [].\nleft; intros; discriminate.\nintros b; generalize (IH (b && hom n 1 a)).\nmatch goal with |- context[fold_left ?X ?Y ?Z] =>\n  case (fold_left X Y Z); auto\nend; rewrite andbP.\nintros ((H1,H2),H3); split; auto.\nintros i [[]|Hi]; auto.\nintros [H1 | H1].\ncase_eq (hom n 1 a); intros Ha.\nleft; intros Hb; case H1; auto.\nright; exists a; split; auto; rewrite Ha.\nintros; discriminate.\ncase H1; intros i [H1i H2i]; right; exists i; split; auto.\ngeneralize (F1 true).\nmatch goal with |- context[fold_left ?X ?Y ?Z] =>\n  case (fold_left X Y Z); auto\nend. intros []; auto.  intros []; auto. contradict H; auto.\nQed.\n\nDefinition decompose n (v: vect n) : option (list (vect n)) := \n  let d := first_deg n v in\n  let l := decomposek n d v in\n  if all_hom1 n l then\n      if v ?= joinl n l then Some l else None\n  else None.\n\nLemma  decompose_cor n v : \n   match decompose n v with\n   | None => ~ is_decomposable n v\n   | Some l => decomposable n l v\n   end.\nProof.\nunfold decompose.\nmatch goal with |- context[all_hom1 ?X ?Y] =>\n  generalize (all_hom1_cor X Y); case (all_hom1 X Y);\n  intros Hi\nend.\ncase eqE_spec; auto.\nintros HH.\ncase (eqE_spec _ (fn n) v 0); intros Hv.\nrewrite Hv, first_deg0; simpl; split; auto.\nintros i [].\napply decomposek_cor; auto.\nexists (decomposek n (first_deg n v) v).\nsplit; auto.\nintros i H1i; red; rewrite cbl1_hom1_equiv; auto.\nassert (F1: hom n (length (decomposek n (first_deg n v) v)) v). \nrewrite HH at 3; apply (joinl_hom1 n); auto.\nrewrite hom_first_deg with (k := length (decomposek n (first_deg n v) v)); auto.\nintros H1 HH.\ncase HH; intros l Hl.\nassert (F1: v <> 0).\nintros H2; case H1.\nrewrite H2 at 2; rewrite first_deg0; auto.\nassert (F2: hom n (length l) v).\ncase Hl; intros H2 H3; rewrite H3.\napply (joinl_hom1 n); auto.\nintros; rewrite <-cbl1_hom1_equiv; auto.\napply H2; auto.\ncase (decomposek_cor n (length l) v); auto.\nintros; case H1; auto.\nrewrite hom_first_deg with (k := length l); auto.\nintros H1; case H1; intros l Hl.\nassert (F1: v <> 0).\nintros H2; case Hi; intros i.\nsubst; rewrite first_deg0; intros [[] _].\nassert (F2: hom n (length l) v).\ncase Hl; intros H2 H3; rewrite H3.\napply (joinl_hom1 n); auto.\nintros; rewrite <-cbl1_hom1_equiv; auto.\napply H2; auto.\ncase (decomposek_cor n (length l) v); auto.\nintros H2.\ncase Hi; intros i [H1i []].\nrewrite <-cbl1_hom1_equiv; auto.\napply H2; auto.\nrewrite <-(hom_first_deg n (length l) v); auto.\nQed.\n\n(* Grade definition *)\nDefinition grade n k x := hom n k x &&  \n  if decompose n x then true else false.\n\nLemma gradeE n k x : \n  grade n k x <->  hom n k x /\\\n                   exists l, x = joinl n l /\\\n                             (forall y, In y l -> hom n 1 y).\nProof.\nunfold grade.\ngeneralize (decompose_cor n x); case decompose; \n  rewrite andb_comm; simpl; auto.\nintros l (H1,H2); subst.\nassert (H4: forall x : vect n, In x l -> hom n 1 x).\nintros x H4; rewrite <-cbl1_hom1_equiv; apply H1; auto.\nsplit.\nintros H3; split; auto.\nexists l; split; auto.\nintros (HH,_); auto.\nintros HH; split.\nintros HH1; discriminate.\nintros (H1, (l, (H1l,H2l))).\ncase HH.\nexists l; split; auto.\nintros u Hu; red; rewrite cbl1_hom1_equiv; auto.\nQed.\n\nLemma grade0 n k : grade n k 0.\nProof.\nunfold grade; rewrite homk0.\ngeneralize (decompose_cor n 0); case decompose; auto.\nintros []; exists nil; split; auto.\nintros x1 [].\nQed.\n\nLemma grade0E n x : grade n 0 x -> x = 0.\nProof.\nrewrite gradeE.\nintros  (Hx, (l, (H1l, H2l))); subst.\ndestruct l as [|y l]; auto.\ncase (homE n (length (y::l)) 0 (joinl n (y::l))); auto.\nintros; discriminate.\nQed.\n\nLemma grade_hom n k x : grade n k x -> hom n k x.\nProof.\nunfold grade; rewrite andbP; intros (H,_); auto.\nQed.\n\nLemma grade1_hom n x : grade n 1 x = hom n 1 x.\nProof.\nunfold grade.\ncase_eq (hom n 1 x); auto.\nintros H.\ngeneralize (decompose_cor n x); case decompose; auto.\nintros []; exists (x::nil); split; auto.\nintros x1; simpl; intros [[]|[]].\nred; rewrite cbl1_hom1_equiv, H; auto.\nQed.\n\nLemma grade_scal n k1 k2 x : grade n k1 x -> grade n k1 (k2 .* x).\nProof.\nrewrite !gradeE; intros (Hx, (l, (H1l, H2l))).\ndestruct l as [| y l].\nrewrite H1l; simpl joinl; rewrite scalE0r, <-gradeE, grade0; auto.\nsplit; auto.\nexists (k2 .* y :: l); repeat split; auto.\nrewrite H1l; destruct l as [|z l]; auto.\nrewrite joinlS; try (intros HH; discriminate).\napply sym_equal; rewrite joinlS; try (intros HH; discriminate).\nrewrite join_scall; auto.\nsimpl; intros z [[] | Hz]; auto with datatypes.\napply scal_hom; auto with datatypes.\nQed.\n\nLemma grade_join n k1 k2 x y :\n   grade n k1 x -> grade n k2 y -> grade n (k1 + k2) (x ∨ y).\nProof.\nrewrite !gradeE.\nintros (Hx, (l1, (H1l1, H2l1))) (Hy, (l2, (H1l2, H2l2))).\nsplit; auto.\ndestruct l1 as [|x1 l1].\nrewrite H1l1; simpl joinl; exists nil; split; Grm0.\ndestruct l2 as [|x2 l2].\nrewrite H1l2; simpl joinl; exists nil; split; Grm0.\nexists ((x1::l1) ++ (x2::l2)); repeat split.\nrewrite H1l1, H1l2, joinl_app; auto; intros; discriminate.\nintros z Hz; case (in_app_or _ _ _ Hz); intros H1; auto.\nQed.\n\n(* Hodge Duality *)\nFixpoint dual n : vect n -> vect n :=\n  match n return vect n ->  vect n with\n  |    0 => fun a => a\n  | S n1 => fun v => let (x,y) := v in (dual n1 (y ^_'f), dual n1 x)\n  end.\nNotation \"'@ x \" := (dual _ x) (at level 9).\n\nLemma dual0 n : '@0 = 0 :> vect n.\nProof.\ninduction n as  [| n IH]; simpl dual; auto.\nVfold n; rewrite conj0,!IH; auto.\nQed.\n\nHint Rewrite dual0: GRm0.\n\nLemma dual0E n (x: vect n) : '@x = 0 -> x = 0.\nProof.\ninduction n as [| n IH]; simpl; auto.\ndestruct x as [x1 x2]; intros HH; injection HH; intros H1 H2.\nrewrite <-(conj_invo n false x2), (IH _ H1), (IH _ H2),\n       conj0; auto.\nQed.\n\nLemma dual_hom n k v : hom n k v -> hom n (n - k) '@v.\nProof.\ncase (Lt.le_or_lt k n).\n2: intros Hi Hh; rewrite (hom_lt _ _ _ Hi Hh), dual0, homk0; auto.\ngeneralize k v; induction n as  [| n IH]; simpl; auto; clear k v.\nintros [| k] (x,y) H; rewrite !andbP; intros (H1,H2).\nsplit; try apply conj_hom.\npattern n at 2; replace n with (n - 0)%nat; auto with arith.\ngeneralize H1; case eq0_spec; intros; [subst | discriminate].\nrewrite dual0, homk0; auto.\nassert (H3: k <= n); auto with arith.\ngeneralize (Minus.le_plus_minus _ _ H3).\ncase (n - k)%nat.\nrewrite Plus.plus_0_r; intros; subst.\nrewrite (hom_lt k k.+1 y), conj0, dual0, eq0I; auto with arith.\nsplit; auto.\nreplace 0%nat with (k - k)%nat; auto with arith.\nintros n1 Hn1; split; try apply conj_hom.\nreplace n1 with (n - S k)%nat; auto with arith.\napply IH; auto with arith.\nrewrite Hn1, <-Plus.plus_Snm_nSm; auto with arith.\nrewrite Hn1, <-Plus.plus_Snm_nSm; auto with arith.\nreplace n1.+1 with (n - k)%nat; auto with arith.\nrewrite Hn1, Minus.minus_plus; auto.\nQed.\n\nHint Resolve dual_hom : core.\n\nLemma dual_scal n k (v: vect n) : '@(k .* v) = k .* '@v.\nProof.\ninduction n as  [| n IH]; simpl; auto; Vfold n.\ndestruct v; rewrite !conj_scal,!IH; auto.\nQed.\n\nLemma dual_add n (v1 v2: vect n) : '@(v1 + v2) = '@v1 + '@v2.\nProof.\ninduction n as  [| n IH]; simpl; auto; Vfold n.\ndestruct v1; destruct v2; rewrite !conj_add, !IH; auto.\nQed.\n\nLemma dual_invo n k (v: vect n): hom n k v ->  '@('@v) = (-(1)) ^(k * n.+1) .* v.\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH]; simpl; try Vfold n.\nintros [| k]; auto; Krm1.\ncase eqK_spec; intros; subst; Vrm0; try discriminate.\nintros [|k]; destruct v.\nrewrite andbP; case eq0_spec; intros H1 (H2,H3); subst; try discriminate.\nrewrite !dual0, conj0; Vrm0.\nrewrite (conjf_hom _ _ _ H3), !dual_scal, (IH _ _ H3).\nsimpl expK; rewrite !scalE1, dual0; auto.\nrewrite andbP; intros (H1,H2).\nrewrite (conjf_hom _ _ _ H2), !dual_scal, (IH _ _ H2).\nassert (H3:= dual_hom _ _ _ H1).\nrewrite (conjf_hom _ _ _ H3), dual_scal, (IH _ _ H1).\napply f_equal2 with (f := @pair _ _); auto.\ncase (Lt.le_or_lt k n); intros Hkn.\n2: rewrite hom_lt with (2:= H1); Grm0.\nrewrite expKm1_sub, <-!scal_multE, <-!expK_add; auto.\nreplace ((k.+1 * n .+2)%nat) with (2 + (n + k + k * n.+1))%nat by ring.\nsimpl expK; Krm1.\nrewrite <-!scal_multE, <-!expK_add; auto.\nreplace (k.+1 + k.+1 * n.+1)%nat with (k.+1 * n .+2)%nat by ring; auto.\nQed.\n\nLemma dual_invoE n k (v: vect n) : hom n k v ->  v = ((-(1)) ^(k * n.+1)) .* '@('@v).\nProof.\nintros H; rewrite (dual_invo _ _ _ H), <-scal_multE, expK2m1, scalE1; auto.\nQed.\n\nLemma dual_all n : '@E = 1 :> vect n.\nProof.\ninduction n as [|n IH]; simpl; auto.\nrewrite IH, conj0, dual0; auto.\nQed.\n\nLemma dual1 n : '@1 =  E :> vect n.\nProof.\ninduction n as [|n IH]; simpl; Krm1.\nassert (F1: hom n 0 1) by apply hom0K.\nassert (F2: hom n n '@1).\n  generalize (dual_hom _ _ _ F1); rewrite <-Minus.minus_n_O; auto.\nrewrite (conjf_hom _ _ _ F1), dual_scal, IH, scalE1, dual0; auto.\nQed.\n\nLemma homn_ex n v : hom n n v -> exists k, v = '@[k].\nProof.\nrewrite <-cblk_homk_equiv.\nintros HH; elim HH; clear v HH.\nexists 0%f; rewrite dual0; auto.\nintros v Hv; exists 1%f.\nrewrite base_n in Hv; simpl in Hv; case Hv; auto; intros [].\nrewrite dual1; auto.\nintros x y _ [k1 Hk1] _ [k2 Hk2]; exists (k1 + k2)%f; subst.\nrewrite <-dual_add, addk; auto.\nintros k1 x _ [k2 Hk2]; exists (k1 * k2)%f; subst.\nrewrite <-dual_scal, scalk; auto.\nQed.\n\nLemma dual_base n k v :\n  In v (base n k) -> In '@v (base n (n - k)) \\/ In ((-(1)) .* '@v) (base n (n - k)).\nProof.\ncase (Lt.le_or_lt k n).\n2: intros H; rewrite base_lt_nil; auto; intros HH; inversion HH.\ngeneralize k; induction n as  [| n IH]; simpl; auto; clear k; try Vfold n.\nintros [| k] H; auto with arith.\nintros [| k] H; destruct v as [x y].\nrewrite base0; simpl; Vfold n.\nintros [H1 | []]; injection H1; intros; subst.\nrewrite dual0, en_def, conjk, dual1; Vrm0.\nleft; apply in_or_app; left; rewrite base_n; simpl; auto with datatypes.\nassert (H3: k <= n); auto with arith.\ngeneralize (Minus.le_plus_minus _ _ H3).\ncase (n - k)%nat.\nrewrite Plus.plus_0_r; intros Hn H1; subst.\nrewrite base_n, base_lt_nil in H1; auto with arith.\nsimpl in H1; case H1; [intros H2 | intros []].\ninjection H2; intros; subst.\nrewrite conj0, dual0, dual_all.\nleft.\nchange (0:vect k, 1: vect k) with (lift k 1).\napply in_map; rewrite base0, en_def; auto with datatypes.\nintros k1 Hk1 H1.\nassert (H4: k.+1 <= n); auto with arith.\n  rewrite Hk1, <-plus_n_Sm; auto with arith.\nreplace k1.+1 with (n - k)%nat.\n  2: rewrite Hk1, Minus.minus_plus; auto.\nreplace k1 with (n - k.+1)%nat.\n  2: rewrite Hk1, <-Plus.plus_Snm_nSm, Minus.minus_plus; auto.\ncase (in_app_or _ _ _ H1).\nrewrite in_map_iff; intros [u (H1u,H2u)].\ninjection H1u; intros Hv1 HV1; subst x y; rewrite conj0, dual0.\nVfold n; Vrm0.\ncase (IH _ _ H3 H2u); auto.\nintros Hin.\nassert (Hh := base_hom _ _ _  (Minus.le_minus _ _) Hin).\nleft; apply in_or_app; right; apply (in_map (lift n)); auto.\nright; apply in_or_app; right; apply (in_map (lift n)); simpl; auto.\nrewrite in_map_iff; intros [u (H1u,H2u)].\ninjection H1u; intros Hv1 HV1; subst x y.\nrewrite dual0.\nVfold n; Vrm0.\ncase (IH _ _ H4 H2u); auto; intros Hin;\n  rewrite (conjf_hom n k.+1); try apply base_hom; auto;\n  rewrite dual_scal;\n  case (even_or_odd (k.+1)); intros H2; simpl stype.\nrewrite expKm1_even with (2 := H2), scalE1; auto.\nleft; apply in_or_app; left; apply (in_map (dlift n)); auto.\nrewrite expKm1_odd with (2:= H2); auto.\nrewrite <-scal_multE, multK_m1_m1, scalE1; auto.\nright; apply in_or_app; left; apply (in_map (dlift n)); auto.\nrewrite expKm1_even with (2 := H2), scalE1; auto.\nright; apply in_or_app; left; apply (in_map (dlift n)); auto.\nrewrite expKm1_odd with (2 := H2); auto.\nleft; apply in_or_app; left; apply (in_map (dlift n)); auto.\nQed.\n\n(* Ad-hoc conjugate function in order to define the join *)\nFixpoint dconj (n : nat) (b: bool) {struct n} : vect n -> vect n :=\n  match n return (vect n -> vect n) with\n  | 0%nat => fun a => if b then (- a)%f else a\n  | S n1 =>\n      fun l1 =>\n      let (l2, l3) := l1 in (dconj n1 b l2, dconj n1 (negb b) l3)\n  end.\n\nNotation \"x ^d_ b\" := (dconj _ b x)  (at level 29, left associativity).\nNotation \"x ^d_'t\" := (dconj _ true x)  (at level 29, left associativity).\nNotation \"x ^d_'f\" := (dconj _ false x)  (at level 29, left associativity).\n\nLemma dconj0 n b : 0 ^d_ b = 0 :> vect n.\nProof.\ngeneralize b; clear b.\ninduction n as [| n IH]; simpl; auto.\nintros []; Krm0.\nintros []; rewrite !IH; auto.\nQed.\n\nHint Rewrite dconj0: GRm0.\n\nLemma dconj_all n b :\n       E ^d_ b = (if b then (-(1)) .* E else E) :> vect n.\nProof.\ngeneralize b; clear b.\ninduction n as [| n IH]; simpl; try Vfold n.\nintros []; Krm1.\nintros []; rewrite !IH; Grm0.\nQed.\n\nLemma dconj_scal n b k (x: vect n) : (k .* x)^d_ b = k .* x ^d_ b.\nProof.\ngeneralize b; clear b.\ninduction n as [| n IH]; simpl;auto.\nintros []; auto; intros; rewrite opp_multKr; auto.\nintros b; destruct x; Vfold n; rewrite !IH; auto.\nQed.\n\n(* Dual conjugate behave well with the sum *)\nLemma dconj_add n b (x y: vect n) : (x + y) ^d_ b = x ^d_ b + y ^d_ b.\nProof.\ngeneralize b; clear b.\ninduction n as [| n IH]; simpl.\n  intros b; case b; auto; rewrite opp_addK; auto.\nintros b; destruct x; destruct y; simpl in IH; rewrite IH, IH; auto.\nQed.\n\n(* Dual conjugate is involutive *)\nLemma dconj_invo n b (v: vect n) : v ^d_ b ^d_ b = v.\nProof.\ngeneralize b; clear b.\ninduction n as [| n IH]; simpl; auto.\nintros []; auto; rewrite opp_oppK; auto.\nintros b; destruct v; rewrite !IH; auto.\nQed.\n\nLemma dconj_neg n b (v: vect n) : v ^d_ (negb b) = (-(1)) .*  (v ^d_ b).\nProof.\ngeneralize b; clear b.\ninduction n as [| n IH];simpl; auto.\nintros []; simpl; Krm1.\nintros b; destruct v; Vfold n.\nrewrite negb_involutive, !IH, <-scal_multE; Krm1; rewrite scalE1; auto.\nQed.\n\nLemma dconjt n (v: vect n) : v ^d_'t = (-(1)) .*  (v ^d_'f).\nProof. rewrite <-dconj_neg; auto. Qed.\n\nLemma dconjf_hom n k (M: vect n) : \n  hom n k M -> M ^d_'f = (- (1))^(n + k) .* M.\nProof.\ngeneralize k; clear k.\ninduction n as [| n IH];simpl; auto; try Vfold n.\nintros [|k] H; simpl; Krm1.\ngeneralize H; case eqK_spec; intros; subst; Grm0; discriminate.\nintros [| k]; destruct M; rewrite andbP; intros (HM1, HM2);\n  rewrite dconjt; simpl; Vfold n; Krm1.\ngeneralize HM1; case eq0_spec; try (intros; discriminate); auto.\nintros H1; rewrite H1, (IH _ _ HM2); simpl; Vfold n; Krm1.\nrewrite dconj0, Plus.plus_0_r, <-scal_multE; Krm1; Vrm0.\nrewrite IH with (1 := HM1),IH with (1 := HM2); auto.\nrewrite <-scal_multE, <-plus_n_Sm; simpl expK; Krm1.\nQed.\n\nLemma dconjt_hom n k (M: vect n) : \n hom n k M -> M ^d_'t = (- (1))^(n + k).+1 .* M.\nProof.\nintros H1; rewrite dconjt, (dconjf_hom _ _ _ H1).\nrewrite <-scal_multE; auto.\nQed.\n\nLemma dconj_swap n b1 b2 (x: vect n) : x ^d_ b2 ^d_ b1 = x ^d_ b1 ^d_ b2.\nProof.\ngeneralize b1 b2; clear b1 b2.\ninduction n as [| n IH]; simpl; auto.\nintros [] []; auto.\nintros b1 b2; destruct x.\nrewrite (IH _ b2), (IH _ (negb b1)); auto.\nQed.\n\nLemma dconj_conj_swap n b1 b2 (x: vect n) : (x ^_ b2) ^d_  b1 = x ^d_ b1 ^_ b2.\nProof.\ngeneralize b1 b2; clear b1 b2.\ninduction n as [| n IH]; simpl; auto.\nintros [] []; auto.\nintros b1 b2; destruct x.\nrewrite (IH _ b1), (IH _ (negb b1)); auto.\nQed.\n\nLemma dconj_conj n b (x: vect n) : (x ^_ b) ^d_ b = (-(1))^n .* x.\nProof.\ngeneralize b; clear b.\ninduction n as [| n IH]; simpl; auto.\nintros []; Krm1.\nintros []; destruct x; simpl; Vfold n;\n  rewrite conjt, dconjt, dconj_scal, !IH, <-!scal_multE; auto.\nQed.\n\nLemma dconj_hom n b k (x: vect n) : hom n k x -> hom n k (x ^d_ b).\nProof.\ngeneralize b k; clear b k.\ninduction n as [| n IH]; simpl.\n  intros [|] [|k]; auto.\n  case eqK_spec; auto; intros HH HH1; try discriminate.\n  rewrite HH, oppK0, eqKI; auto.\nintros b [|k]; destruct x; rewrite !andbP; intros (H1, H2); split; auto.\ngeneralize H1; case eq0_spec; intros Hx1 HH; try discriminate.\n  rewrite Hx1, dconj0, eq0I; auto.\nQed.\n\nHint Resolve dconj_hom : core.\n\nLemma dconjf_joinl n (x y: vect n) : (x ∨ y) ^d_'f = x ^d_'f ∨ y ^_'f.\nProof.\ninduction n as [| n IH]; auto.\ndestruct x; destruct y; simpl; Vfold n.\nrewrite !dconjt, IH.\nrewrite dconj_add, !IH, !conjt, join_scall.\napply f_equal2 with (f := @pair _ _); auto.\napply f_equal2 with (f := addE (vn_eparams n)); auto.\nrewrite conj_scal, !join_scall, !join_scalr, <-scal_multE; Krm1.\nrewrite dconj_conj_swap, scalE1; auto.\nQed.\n\nLemma dconjf_joinr n (x y: vect n) : (x ∨ y) ^d_'f = x ^_'f ∨ y ^d_'f.\nProof.\ninduction n as [| n IH]; auto.\nsimpl vect.\ndestruct x; destruct y; simpl; Vfold n.\nrewrite !dconjt, IH.\nrewrite dconj_add, !IH, !conjt.\nrewrite !join_scall, !join_scalr, <-scal_multE; Krm1.\nrewrite scalE1; auto.\nQed.\n\nLemma conj_dual n b (x: vect n): '@(x ^_ b) = '@x ^d_ b.\nProof.\ngeneralize b; clear b.\ninduction n as [| n IH]; auto.\nsimpl; intros b; destruct x; rewrite !IH.\nrewrite dconj_swap; auto.\nQed.\n\nLemma dconj_dual n b (x: vect n) : '@(x ^d_ b) = '@x ^_ b.\nProof.\ngeneralize b; clear b.\ninduction n as [| n IH]; auto.\nsimpl; intros []; destruct x; \n  rewrite !IH, !conj_dual, IH, dconj_conj_swap; auto.\nQed.\n\nLemma dualk n k : '@([k]) = k .* E :> vect n.\nProof.\ninduction n as [| n IH]; simpl; auto.\nrewrite multK1r; auto.\nVfold n.\nrewrite dual0, scalE0r; auto.\nrewrite conj_dual, IH, dconj_scal, dconj_all; auto.\nQed.\n\nDefinition dconst n (x: vect n) := 'C['@x].\nNotation \"'dC[ x ]\" := (dconst _ x).\n\nLemma dconjk n b k :\n  [k] ^d_ b = (if b then [(-(1))^n.+1 * k] else [(-(1))^n * k]:vect n).\nProof.\ncase b; auto.\nrewrite dconjt_hom with (k := 0%nat), Plus.plus_0_r, scalk; auto.\nrewrite dconjf_hom with (k := 0%nat), Plus.plus_0_r, scalk; auto.\nQed.\n\nLemma dconj_const n b (x: vect n) :\n  'C[x ^d_ b] = (if b then ((-(1))^n.+1 * 'C[x])%f else ((-(1))^n * 'C[x])%f).\nProof.\ngeneralize b; clear b.\ninduction n as [|n IH]; simpl; auto.\nintros []; Krm1.\nintros []; destruct x; simpl negb; rewrite IH; Krm1.\nQed.                      \n\nLemma conj_dconst n b (x: vect n) :\n  'dC[x ^_ b] = (if b then ((-(1))^n.+1 * 'dC[x])%f else  ((-(1))^n * 'dC[x])%f).\nProof. unfold dconst; rewrite conj_dual, dconj_const; auto. Qed.\n\nLemma dconj_dconst n b (x: vect n) :\n  'dC[x ^d_ b] = (if b then (- 'dC[x])%f else  'dC[x]).\nProof. unfold dconst; rewrite dconj_dual, conj_const; auto. Qed.\n\nLemma projn n (x : vect n) : proj n n x = 'dC[x] :: nil.\nProof.\ninduction n as [| n IH]; simpl; auto.\ndestruct x; rewrite IH, proj_lt; auto.\nQed.\n\nLemma dconst_all n : 'dC[(E: vect n)] = 1%f .\nProof. unfold dconst; rewrite dual_all, constk; auto. Qed.\n\nLemma dconst0 n : 'dC[0:vect n] = 0%f.\nProof. unfold dconst; rewrite dual0, const0; auto. Qed.\n\nHint Rewrite dconst0: GRm0.\n\nLemma dconst_scal n k (x: vect n) : 'dC[k .* x] = (k * 'dC[x])%f.\nProof. unfold dconst; rewrite dual_scal, const_scal; auto. Qed.\n\nLemma dconst_add n (x1 x2 : vect n) : 'dC[x1 + x2] = ('dC[x1] + 'dC[x2])%f.\nProof. unfold dconst; rewrite dual_add, const_add; auto. Qed.\n\nLemma dconst_hom n k x : hom n k x -> n <> k -> 'dC[x] = 0%f.\nProof.\nintros H1 H2.\ncase (Lt.le_or_lt n k); intros H3.\ncase (Lt.le_lt_or_eq _ _ H3); intros H4; auto.\nrewrite hom_lt with (2 := H1), dconst0; auto.\ncase H2; auto.\nunfold dconst; apply const_hom with (k := (n - k)%nat).\napply dual_hom; auto.\napply Plus.plus_lt_reg_l with k.\nrewrite Plus.plus_0_r, <-Minus.le_plus_minus; auto with arith.\nQed.\n\nLemma homn_all n x : hom n n x -> x = 'dC[x] .* E.\nProof.\nunfold dconst.\ninduction n as [|n IH]; simpl; try Vfold n; Krm1.\ndestruct x; rewrite andbP; intros (Hx1,Hx2).\nrewrite <-(IH _ Hx1); Grm0.\nrewrite hom_lt with (2 := Hx2); Grm0.\nQed.\n\nLemma const_dual n (x: vect n) : 'C['@x] = 'dC[x].\nProof. auto. Qed.\n\nLemma dconst_dual n (x: vect n) : 'dC['@x] = 'C[x].\nProof.\nunfold dconst; induction n as [|n IH]; simpl; auto; Vfold n.\ndestruct x; rewrite IH, conj_const; auto.\nQed.\n\n(* Defining the meet *)\nFixpoint meet (n : nat) : vect n -> vect n -> vect n :=\n  match n return (vect n -> vect n -> vect n) with\n  | 0%nat => fun a b => (a * b)%f\n  | S n1 =>\n      fun v1 v2 => \n      let (x1, y1) := v1 in\n      let (x2, y2) := v2 in (meet n1 x1 x2,\n                                meet n1 x1 y2 +\n                                meet n1 y1 (x2 ^d_'f))\n  end.\n\n(* unicode 2227 *)\nNotation \"x '∧' y\" := (meet _ x y) (at level 45, left associativity).\n\nLemma meet0l n (x: vect n) : 0 ∧ x = 0.\nProof.\ninduction n as [| n IH]; simpl; try Vfold n; Krm0.\ndestruct x; rewrite !IH; Vrm0.\nQed.\n\nHint Rewrite meet0l: GRm0.\n\nLemma meet0r n (x: vect n) : x ∧ 0 = 0.\nProof.\ninduction n as [| n IH]; simpl; try Vfold n; Krm0.\ndestruct x; rewrite dconj0, !IH; Vrm0.\nQed.\n\nHint Rewrite meet0r: GRm0.\n\nLemma meet1l n (x: vect n) : 1 ∧ x = ['C['@x]].\nProof.\ninduction n as [| n IH]; simpl; try Vfold n; Krm1.\ndestruct x.\nrewrite !meet0l, addE0l, IH,dconj_dual, conj_const; auto.\nQed.\n\nLemma meet1r n (x: vect n) : x ∧ 1 = ['C['@x]].\nProof.\ninduction n as [| n IH]; simpl; try Vfold n; Krm1.\ndestruct x.\nrewrite !meet0r, dconj0, IH, meet0r, addE0r; auto.\nQed.\n\n(* (k.x) ∧ y = k. (x ∧ y) *)\nLemma meet_scall n k (x y : vect n) : k .* x ∧ y = k .* (x ∧ y).\nProof.\ninduction n as [| n IH]; simpl; try Vfold n;auto.\nrewrite multK_assoc; auto.\ndestruct x; destruct y.\nrewrite scal_addEr, !IH; auto.\nQed.\n\n(* x ∧ (k . y) = k. (x ∧ y) *)\nLemma meet_scalr n k (x y : vect n) : x ∧ k .* y = k .* (x ∧ y).\nProof.\ninduction n as [| n IH]; simpl; try Vfold n;auto.\nrewrite <-!multK_assoc, (multK_com _ Hp x); auto.\ndestruct x; destruct y.\nrewrite dconj_scal, scal_addEr, !IH; auto.\nQed.\n\nLemma meet0 (v1 v2 : vect 0) : v1 ∧ v2 = (v1 * v2)%f.\nProof. auto. Qed.\n\nLemma meetS n (x1 x2 y1 y2 : vect n) :\n ((x1,y1): vect n.+1) ∧ (x2,y2) = \n  (x1 ∧ x2, x1 ∧ y2 + y1 ∧ (x2 ^d_'f)).\nProof. auto. Qed.\n\nLemma dual_meet n (v1 v2 : vect n) : '@(v1 ∧ v2) = '@v1 ∨ '@v2.\nProof.\ninduction n as [| n IH]; auto.\ndestruct v1; destruct v2; rewrite meetS.\nsimpl; Vfold n.\nrewrite IH, conj_add, dual_add.\napply f_equal2 with (f := @pair _ _); auto.\nrewrite addE_com; auto; apply f_equal2 with (f := @addE (vn_eparams n)); auto.\nrewrite !conj_dual, IH, dconj_dual, dconjf_joinl, conj_invo; auto.\nrewrite !conj_dual, IH, dconjf_joinr; auto.\nQed.\n\nLemma conjf_meetl n (x y : vect n) : (x ∧ y) ^_'f = x ^_'f ∧ y ^d_'f.\nProof.\ninduction n as [| n IH]; auto.\ndestruct x; destruct y; rewrite !meetS.\nsimpl dconj; simpl conj; Vfold n; rewrite !conjt, meetS, !IH, meet_scall.\napply f_equal2 with (f := @pair _ _); auto.\nrewrite conj_add, !IH.\napply f_equal2 with (f := addE (vn_eparams n)); auto.\nrewrite dconjt, meet_scalr, meet_scall, <-scal_multE; Krm1.\nrewrite scalE1; auto.\nQed.\n\nLemma conjf_meetr n (x y : vect n) : (x ∧ y) ^_'f = x ^d_'f ∧ y ^_'f.\nProof.\ninduction n as [| n IH]; auto.\ndestruct x; destruct y; rewrite !meetS.\nsimpl dconj; simpl conj; Vfold n; rewrite !conjt, meetS, !IH, meet_scalr.\napply f_equal2 with (f := @pair _ _); auto.\nrewrite conj_add, !IH; apply f_equal2 with (f := addE (vn_eparams n)); auto.\nrewrite dconjt, dconj_scal, meet_scalr, meet_scall, <-scal_multE; Krm1.\nrewrite scalE1, dconj_conj_swap; auto.\nQed.\n\nLemma dconjf_meet n (x y : vect n) : (x ∧ y) ^d_'f = x ^d_'f ∧ y ^d_'f.\nProof.\ninduction n as [| n IH]; auto.\ndestruct x; destruct y; rewrite !meetS.\nsimpl dconj; rewrite meetS, !IH, !dconj_invo; Vfold n.\napply f_equal2 with (f := @pair _ _); auto.\nrewrite !dconjt, dconj_add, meet_scall, meet_scalr, <-scal_addEr; auto.\nrewrite !IH, dconj_invo; auto.\nQed.\n   \nLemma dconjf_meetd n (x y : vect n) : (x ∧ y) ^d_'f = x ^_'f ∧ y ^_'f.\nProof.\ninduction n as [| n IH]; auto.\ndestruct x; destruct y; rewrite !meetS.\nsimpl conj; simpl dconj; rewrite meetS, !conjt, !dconjt; Vfold n.\nrewrite IH, !meet_scall, !meet_scalr, <-!scal_multE, dconj_add; Krm1.\nrewrite scalE1; auto; apply f_equal2 with (f := @pair _ _); auto.\nrewrite !IH, !dconj_scal, meet_scalr, dconj_conj_swap, scal_addEr; auto.\nQed.\n\nLemma dconst_meet n (x y: vect n) : 'dC[x ∧ y] = ('dC[x] * 'dC[y])%f.\nProof. unfold dconst; rewrite dual_meet, const_join. auto. Qed.\n\nLemma dual_join n (v1 v2: vect n) : '@(v1 ∨ v2) = '@v1 ∧ '@v2.\nProof.\ninduction n as [| n IH]; auto.\nsimpl; Vfold n.\ndestruct v1; destruct v2.\napply f_equal2 with (f := @pair _ _); auto.\nrewrite conjf_join, IH; auto.\nrewrite dual_add, addE_com; auto; apply f_equal2 with (f := @addE (vn_eparams n)); auto.\nrewrite conj_dual, dconj_invo, IH; auto.\nQed.\n\n(* (x + y) ∧ z = (x ∧ z) + (y ∧ z) *)\nLemma meet_addl n (x y z : vect n) : (x + y) ∧ z = x ∧ z + y ∧ z.\nProof.\ninduction n as [| n IH]; simpl; try Vfold n.\nintros; apply (add_multKl p); auto.\ndestruct x; destruct y; destruct z.\napply f_equal2 with (f := @pair _ _); rewrite IH; auto.\nrewrite !addE_assoc; auto.\napply f_equal2 with (f := add n); auto.\nrewrite IH, addE_com, !addE_assoc; auto.\napply f_equal2 with (f := add n); auto.\nrewrite addE_com; auto.\nQed.\n\n(* z ∧ (x + y) = (z ∧ x) + (z ∧ y) *)\nLemma meet_addr n (x y z : vect n) : z ∧ (x + y) = z ∧ x + z ∧ y.\nProof.\ninduction n as [| n IH]; simpl; try Vfold n.\nintros; apply (add_multKr p); auto.\ndestruct x; destruct y; destruct z.\napply f_equal2 with (f := @pair _ _); rewrite IH; auto.\nrewrite !addE_assoc; auto.\napply f_equal2 with (f := add n); auto.\nrewrite dconj_add, IH, addE_com,!addE_assoc; auto.\napply f_equal2 with (f := add n); auto.\nrewrite addE_com; auto.\nQed.\n\nLemma meet_assoc n (x y z : vect n) : x ∧ y ∧ z = x ∧ (y ∧ z).\nProof.\ninduction n as [| n IH]; simpl; try Vfold n.\nintros; rewrite multK_assoc; auto.\ndestruct x; destruct y; destruct z.\napply f_equal2 with (f := @pair _ _).\nrewrite IH; auto.\nrewrite meet_addr, meet_addl, !addE_assoc; auto.\nrepeat apply f_equal2 with (f := add n); auto.\nrewrite dconjf_meet, IH; auto.\nQed. \n\nLemma meet_alll n (x: vect n) : all n ∧ x = x.\nProof.\ninduction n as [| n IH]; simpl; try Vfold n.\nintros; rewrite multK1l; auto.\ndestruct x; rewrite !IH, meet0l, addE0r; auto.\nQed.\n\nLemma meet_allr n (x: vect n) : x ∧ all n = x.\nProof.\ninduction n as [| n IH]; simpl; try Vfold n.\nrewrite multK1r; auto.\ndestruct x; rewrite !IH, meet0r, addE0l, dconj_all, IH; auto.\nQed.\n\n(* By duality *)\nLemma meet_small n k1 k2 (x y : vect n) : \n  hom n k1 x -> hom n k2 y -> k1 + k2 < n -> x ∧ y = 0.\nProof.\ngeneralize k1 k2; clear k1 k2.\ninduction n as [| n IH]; simpl; try Vfold n.\nintros k1 k2 _ _ HH; contradict HH; auto with arith.\nintros [|k1] [|k2]; destruct x as [x1 x2]; destruct y as [y1 y2].\ncase eq0_spec; auto; intros HH Hx2; subst; try discriminate.\ncase eq0_spec; auto; intros HH Hy; subst; try discriminate.\nGrm0.\ncase eq0_spec; auto; intros HH Hx2; subst; try discriminate.\nrewrite andbP; intros (Hy1,Hy2) H; rewrite (IH x2 _ 0%nat k2); Grm0.\nauto with arith.\nrewrite andbP; intros (Hx1,Hx2).\ncase eq0_spec; auto; intros HH Hy2 H; subst; try discriminate.\nrewrite (IH x1 y2 k1 0%nat); Grm0; auto with arith.\nrewrite !andbP; intros (Hx1,Hx2) (Hy1,H2) H.\nrewrite (IH _ _ k1 k2), (IH _ _ k1 k2.+1), (IH _ _ k1.+1 k2); \n      Grm0; auto with arith.\nrewrite <-plus_n_Sm in H; auto with arith.\napply Lt.lt_trans with (k1 + k2).+1; auto with arith.\nrewrite <-plus_n_Sm in H; auto with arith.\nQed.\n\n(* By duality *)\nLemma meet_hom n k1 k2 (x y : vect n) : \n  hom n k1 x -> hom n k2 y -> hom n (k1 + k2 - n) (x ∧ y).\nProof.\nintros Hx Hy.\ncase (Lt.le_or_lt k1 n); intros Hk1.\n2: rewrite hom_lt with (1 := Hk1)(2:= Hx); Grm0; apply homk0.\ncase (Lt.le_or_lt k2 n); intros Hk2.\n2: rewrite hom_lt with (1 := Hk2)(2:= Hy); Grm0; apply homk0.\ncase (Lt.le_or_lt n (k1 + k2)); intros Hk1k2.\n2: rewrite meet_small with (1 := Hx)(2:= Hy); Grm0.\nreplace (k1 + k2 - n)%nat with (n - ((n - k1) + (n - k2)))%nat; auto.\nrewrite dual_invoE with (1 := Hx), dual_invoE with (1 := Hy).\nrewrite meet_scall, meet_scalr, <-dual_join; auto 10.\nrewrite Minus.minus_plus_simpl_l_reverse with (p := (k1 + k2)%nat).\nrewrite (Plus.plus_comm k1), <-!Plus.plus_assoc, (Plus.plus_assoc k1).\nrewrite <-Minus.le_plus_minus, !Plus.plus_assoc; auto.\nrewrite !(Plus.plus_comm k2), <-!Plus.plus_assoc, <-Minus.le_plus_minus; auto.\nrewrite Plus.plus_assoc, (Plus.plus_comm (k1 + k2)); auto. \nrewrite <-Minus.minus_plus_simpl_l_reverse; auto.\nQed.\n\nHint Resolve meet_hom : core.\n\nLemma meetkl0 n k1 k2 x : hom n k1 x -> n <> k1 -> [k2] ∧ x = 0.\nProof.\nintros H1 H2.\ncase (Lt.le_or_lt k1 n); intros H3.\ncase (Lt.le_lt_or_eq _ _ H3); intros H4.\napply meet_small with (k1 := 0%nat) (k2 := k1); auto; apply hom0K.\ncase H2; auto.\nrewrite hom_lt with (2 := H1); auto; rewrite meet0r; auto.\nQed.\n\nLemma meetkl n k x : hom n n x -> [k] ∧ x = [k * 'dC[x]].\nProof.\nintros H.\npattern x at 1; rewrite (homn_all _ _ H); auto.\nrewrite meet_scalr, meet_allr, scalk, multK_com; auto.\nQed.\n\nLemma meetkr0 n k1 k2 x : hom n k1 x -> n <> k1 -> x ∧ [k2] = 0.\nProof.\nintros H1 H2.\ncase (Lt.le_or_lt k1 n); intros H3.\ncase (Lt.le_lt_or_eq _ _ H3); intros H4.\napply meet_small with (k1 := k1) (k2 := 0%nat); auto.\nrewrite Plus.plus_0_r; auto.\ncase H2; auto.\nrewrite hom_lt with (2 := H1); auto; rewrite meet0l; auto.\nQed.\n\nLemma meetkr n k x : hom n n x -> x ∧ [k] = ['dC[x] * k].\nProof.\nintros H.\npattern x at 1; rewrite (homn_all _ _ H); auto.\nrewrite meet_scall, meet_alll, scalk; auto.\nQed.\n\n\nLemma meet_hom_com n k1 k2 (x y : vect n) :\n  hom n k1 x ->\n  hom n k2 y -> y ∧ x = ((- (1))^((n + k1) * (n + k2))).* (x ∧ y).\nProof.\nintros Hx Hy.\ncase (Lt.le_or_lt k1 n); intros Hk1.\n2: rewrite hom_lt with (2 := Hx), meet0l, meet0r; Grm0.\ncase (Lt.le_or_lt k2 n); intros Hk2.\n2: rewrite hom_lt with (2 := Hy), meet0r, meet0l; Grm0.\nassert (Hdx := dual_hom _ _ _ Hx).\nassert (Hdy := dual_hom _ _ _ Hy).\nassert (Hxy := meet_hom _ _ _ _ _ Hx Hy).\nassert (Hyx := meet_hom _ _ _ _ _ Hy Hx).\nrewrite (dual_invoE _ _ _ Hyx), dual_meet, (join_hom_com _ _ _ _ _ Hdx Hdy),\n        dual_scal, <-dual_meet, (dual_invo _ _ _ Hxy).\nrewrite <-!scal_multE, <-!expK_add, (Plus.plus_comm k2); auto.\nreplace ((k1 + k2 - n) * n.+1 + (n - k1) * (n - k2) + (k1 + k2 - n) * n.+1)%nat\n  with (2 * ((k1 + k2 - n) * n.+1) + (n - k1) * (n - k2))%nat by ring.\nreplace ((n + k1) * (n + k2)) with \n        (2 * (2 * k1 *k2 + k1 * (n - k2) + k2 * (n - k1)) + (n - k1) * (n - k2))%nat.\nrewrite !expKm1_2E; auto.\npattern n at 5; rewrite (Minus.le_plus_minus _ _ Hk1).\npattern n at 6; rewrite (Minus.le_plus_minus _ _ Hk2); ring.\nQed.\n\nLemma meet_hom_id n k x : hom n k x -> odd (n - k) ->  x ∧ x = 0.\nProof.\nintros Hx Ho.\nassert (Hdx := dual_hom _ _ _ Hx).\nassert (Hxx := meet_hom _ _ _ _ _ Hx Hx).\nrewrite (dual_invoE _ _ _ Hxx), dual_meet.\nrewrite (join_hom_id _ _ _ Hdx), dual0; Vrm0.\nQed.\n\nLemma dual_join_compl n k v :\n  In v (base n k) -> (v ∨ '@v = all n) \\/ v ∨ '@v = (-(1)) .*  all n.\nProof.\ngeneralize k; clear k.\ninduction n as [|n IH]; simpl; try Vfold n.\nintros [|k]; simpl.\nintros [[]|[]]; rewrite multK1r; auto.\nintros [].\nintros [|k]; destruct v as [x y]; simpl dual.\nrewrite in_map_iff; intros [z (H1z,H2z)].\ninjection H1z; intros; subst; rewrite dual0; Grm0.\nrewrite (conjf_hom n 0), scalE1; simpl; Vfold n; Grm0.\n  case (IH y 0%nat); auto; intros Hu; rewrite Hu; auto.\nrewrite <-cblk_homk_equiv; constructor; auto.\nintros H1; case (in_app_or _ _ _ H1); rewrite in_map_iff; intros [z (H1z,H2z)].\ninjection H1z; intros; subst.\n  rewrite conj0, dual0; Grm0.\n  case (IH x k); auto; intros Hx; rewrite Hx; auto.\ninjection H1z; intros; subst; rewrite dual0; Grm0.\nrewrite conjf_hom with (k := S k).\ncase (even_or_odd k.+1); intros He.\nrewrite expKm1_even, scalE1; auto.\ncase (IH y k.+1); auto.\n intros Hy; rewrite Hy; auto.\nintros H; rewrite H; auto.\nrewrite expKm1_odd, join_scall; auto.\nrewrite dual_scal, join_scalr, <-scal_multE; Krm1; rewrite scalE1; auto.\ncase (IH y k.+1); auto; intros Hy; rewrite Hy; auto.\nrewrite <-cblk_homk_equiv; constructor; auto.\nQed.\n\nLemma join01E n x y : hom n 1 x -> hom n 1 y -> \n   x ∨ y = 0 -> exists k, x = k .* y \\/ y = k .* x.\nProof.\nintros H1 H2 H3.\ncase (eqE_spec _ (fn n) y 0); intros Hy; subst.\nexists 0%f; Grm0.\nrewrite <-cbl1_hom1_equiv in H1.\nrewrite (decomp_cbl n y (y::nil) x H1 (hom1_decomposable _ _ H2) Hy) in H3.\ncase cbl1 with (2 := H3); auto.\nintros k Hk; exists k; auto.\nQed. \n\nLemma homn_1 n k1 k2 x y : \n  hom n k1 x -> hom n k2 y -> n = (k1 + k2)%nat -> x ∧ y = 'dC[x ∨ y] .* 1.\nProof.\nunfold dconst; generalize k1 k2; clear k1 k2.\ninduction n as [|n IH]; simpl; try Vfold n.\nintros [|k1] [|k2]; Krm1.\nintros [|k1] [|k2]; destruct x as [x1 x2]; destruct y as [y1 y2].\nintros; discriminate.\ncase eq0_spec; intros HH Hx2; subst; try discriminate.\nrewrite !meet0l; Grm0.\nrewrite andbP; intros (Hy1,Hy2) HH; injection HH; intros HH1; subst.\nrewrite dconjf_hom with (1 := Hy1), conjf_hom with (1 := Hx2).\nrewrite expK_add, expK2m1; simpl expK; auto.\nrewrite !scalE1, (IH _ _ 0%nat k2); auto.\nrewrite andbP; intros (Hx1,Hx2).\ncase eq0_spec; intros HH Hy2; subst; try discriminate.\nintros HH; injection HH; intros HH1; subst.\nrewrite dconj0, !meet0r, IH with (1 := Hx1) (2 := Hy2); Grm0.\nrewrite !andbP; intros (Hx1,Hx2)( Hy1,Hy2) Hn; Grm0.\ninjection Hn; rewrite <-plus_n_Sm; clear Hn; intros Hn; subst.\nrewrite meet_small with (1:= Hx1) (2 := Hy1); auto with arith.\nrewrite (IH _ _ k1 k2.+1), (IH _ _ k1.+1 k2),\n        dual_add, const_add, scal_addEl; auto.\nrewrite dconjf_hom with (1 := Hy1), conjf_hom with (1 := Hx2).\nreplace ((k1 + k2).+1 + k2)%nat with (2 * k2 + k1.+1)%nat by ring.\nrewrite expKm1_2E, join_scall, join_scalr; auto.\nQed.\n\n(* One theorem of white  WHITE 1997 p882 and Barnabei Brini Rota p135 *) \nLemma join2_meetE n k1 k2 (x y : vect n) : \n  hom n k1 x -> hom n k2 y -> n <= k1 + k2 ->  x ∨ y = (x ∧ y) ∨ E.\nProof.\nintros Hx Hy Hn.\ncase (Lt.le_lt_or_eq _ _ Hn); clear Hn; intros Hn.\nrewrite (hom_lt n (k1 + k2) (x ∨ y)); auto.\nrewrite join_allhr with (k := (k1 + k2 - n)%nat); auto.\napply Plus.plus_lt_reg_l with n.\nrewrite Plus.plus_0_r, <-Minus.le_plus_minus; auto with arith.\nrewrite homn_1 with (3 := Hn), join_scall, join1l, <-homn_all; subst; auto.\nQed.\n\n(* Barnabei Brini Rota p136 *) \nLemma join_meet_swap n k1 k2 k3 (x y z : vect n) : \n   hom n k1 x -> hom n k2 y ->  hom n k3 z -> (k1 + k2 + k3 = n)%nat -> \n    x ∧ (y ∨ z) = (x ∨ y) ∧ z.\nProof.\nintros Hx Hy Hz Hn.\nrewrite homn_1 with (k1 := k1) (k2 := (k2 + k3)%nat); auto.\nrewrite homn_1 with (k1 := (k1 + k2)%nat) (k2 := k3); auto.\nrewrite join_assoc; auto.\nrewrite Plus.plus_assoc; auto.\nQed.\n\n(* Barnabei Brini Rota p136 *) \nLemma join3_meetE n k1 k2 (x y z : vect n) : \n  hom n n x -> hom n k1 y -> hom n k2 z ->  n <= k1 + k2 ->  \n  x ∧ (y ∨ z) = (x ∧ y ∧ z) ∨ E.\nProof.\nintros Hx Hy Hz Hn.\nrewrite homn_all with (1 := Hx), !meet_scall, !meet_alll; auto.\nrewrite join_scall, join2_meetE with (k1 := k1) (k2 := k2); auto.\nQed.\n\nLemma splitlr n k1 k2 x y z : hom n k1 x -> hom n 1 y ->  hom n k2 z ->\n  (x ∨ y) ∧ z = (-(1))^(n + (k1 + k2).+1) .* (x ∧ (y ∨ z)) +\n                         (x ∧ z) ∨ y.\nProof.\ngeneralize k1 k2; clear k1 k2.\ninduction n as [| n IH]; simpl; try Vfold n.\nintros [|k1] [|k2]; \n  case eqK_spec; intros; subst; Krm0; try discriminate.\nintros [|k1] [|k2]; destruct x as [x1 x2]; destruct y as [y1 y2];\n  destruct z as [z1 z2].\ncase eq0_spec; intros tmp Hx2; subst; try discriminate.\nrewrite andbP; intros (Hy1, Hy2).\ncase eq0_spec; intros tmp Hz2; subst; try discriminate.\nGrm0.\nrewrite (hom0E _ _ Hx2), (hom0E _ _ Hy1), (hom0E _ _ Hz2),\n        conjk; auto.\nrewrite dconjf_joinl, conjk, dconjk, !joinkr.\ncase (Peano_dec.dec_eq_nat n 0); intros Hn; subst; auto.\nsimpl; Krm1; rewrite !multK_assoc, multK_com, !multK_assoc; auto.\nrewrite !meet_small with (k1 := 0%nat) (k2 := 0%nat); Grm0;\n  try apply scal_hom; try apply hom0K; try (destruct n; auto with arith; fail).\ncase eq0_spec; intros tmp Hx2; subst; try discriminate.\nrewrite !andbP; intros (Hy1, Hy2) (Hz1, Hz2).\nrewrite (IH x2 y2 (z1^d_'f) 0%nat k2); auto.\nrewrite (hom0E _ _ Hx2), (hom0E _ _ Hy1), conjk; auto.\nGrm0.\nrewrite !joink, joinkr.\napply f_equal2 with (f := @pair _ _).\nrewrite conjf_meetl, dconj_invo, conjk, <-meet_scall, scalk, multK_com; auto.\nrewrite <-addE_assoc; auto.\napply f_equal2 with (f := add n); auto.\nsimpl minus.\nrewrite dconj_add, meet_addr, scal_addEr; auto.\napply f_equal2 with (f := add n); auto.\nrewrite dconjf_joinr, conjk, joinkl, meet_scalr, <-meet_scall, scalk; auto.\nrewrite multK_com, dconjf_hom with (1 := Hz2), meet_scalr, <-scal_multE; auto.\nrewrite multK_assoc, <-expK_add; auto.\nreplace (n + (0 + k2.+1).+1 + (n + k2.+1))%nat with (2 * (n + k2.+1) + 1)%nat by ring.\nrewrite expKm1_2E; simpl expK; Krm1; rewrite scalE1; auto.\nrewrite dconjf_joinr, conj_invo; auto.\nrewrite <-!plus_n_Sm; simpl expK; Krm1.\ncase eq0_spec; intros tmp; subst; try (intros; discriminate).\nrewrite andbP, andbP; intros (Hx1, Hx2) (Hy1, Hy2) Hz2.\nrewrite dconj0, !meet0r; Grm0.\napply f_equal2 with (f := @pair _ _).\nrewrite (hom0E _ _ Hy1), (hom0E _ _ Hz2), !joinkr; auto.\nrewrite scalk, multK_com, <-scalk, meet_scalr; auto.\nrewrite <-meet_scalr, scalk, multK_com with (x := 'C[z2]); auto.\nrewrite conjf_meetr, conjk, <-meet_scalr with (k := 'C[y1]), scalk; auto.\nrewrite dconjf_hom with (1 := Hx1), meet_scall, <-scal_addEl; auto.\nreplace (n + (k1.+1 + 0).+1)%nat with ((n + k1).+2)%nat by ring.\nsimpl expK; Krm1; rewrite oppKl; Grm0.\nrewrite meet_addl, IH with (1 := Hx1) (3 := Hz2); auto.\nrewrite addE_com, <-!addE_assoc; auto.\napply f_equal2 with (f := add n); auto.\nrewrite addE_com, scal_addEr; auto.\nrewrite (hom0E _ _ Hy1), (hom0E _ _ Hz2), !joinkr; auto.\napply f_equal2 with (f := add n); auto.\nreplace (n + (k1.+1 + 0).+1)%nat with ((n + (k1 + 0).+1).+1)%nat by ring.\nsimpl expK; Krm1.\nrewrite conjf_hom with (1 := Hx2), !meet_scall, dconj_scal, \n        dconjk, <-!meet_scalr, !scalk.\nrewrite multK_com with (x := 'C[y1]), multK_com with (x := 'C[z2]), <-!multK_assoc; auto.\nrewrite multK_assoc, multK_com with (x := 'C[z2]), <- multK_assoc; auto.\nKrm1; rewrite !opp_multKl, <-expKS, <-expK_add; auto.\nreplace ((n + (k1.+1 + 0).+1).+1 + n)%nat with (2 * (n.+1) + k1.+1)%nat by ring.\nrewrite expKm1_2E; auto.\nrewrite !andbP; intros (Hx1,Hx2) (Hy1,Hy2) (Hz1,Hz2).\napply f_equal2 with (f := @pair _ _).\nrewrite meet_addl.\nrewrite IH with (1 := Hx1) (3 := Hz1); auto.\nrewrite meet_addr, scal_addEr, !addE_assoc; auto.\napply sym_equal; rewrite addE_com; auto.\nrewrite !addE_assoc; auto;  apply f_equal2 with (f := add n); auto.\nrewrite conjf_hom with (1 := Hy2), join_scall, meet_scalr; auto.\nrewrite <-scal_multE; simpl expK; Krm1.\nreplace (n + (k1 + k2.+1) .+2)%nat with (2 * 1 + (n + (k1 + k2).+1))%nat by ring.\nrewrite expKm1_2E; auto.\napply f_equal2 with (f := add n); auto.\nrewrite conj_add, join_addl.\nrewrite !conjf_meetl, dconj_invo.\nrewrite (hom0E _ _ Hy1), !joinkr, !joinkl.\nrewrite meet_scalr, meet_scall.\nrewrite conjf_hom with (1 := Hx1).\nrewrite dconjf_hom with (1 := Hz2).\nrewrite addE_com, <-addE_assoc, meet_scalr, meet_scall, <-!scal_multE,\n        <-scal_addEl; auto.\nrewrite multK_com, !multK_assoc, <-add_multKr, <-expK_add; auto.\nreplace (n + (k1.+1 + k2.+1).+1)%nat with (2 * 1 + (n + k2.+1 + k1))%nat by ring.\nKrm1; rewrite expKm1_2E, oppKl; Grm0.\nrewrite meet_addl.\nrewrite IH with (1 := Hx1) (3 := Hz2); auto.\nrewrite !scal_addEr, !addE_assoc; auto.\napply f_equal2 with (f := add n); auto.\nreplace (n + (k1.+1 + k2.+1).+1)%nat with (n + (k1 + k2.+1).+1).+1 by ring.\nsimpl expK; Krm1.\napply sym_equal; rewrite addE_com, join_addl, !addE_assoc; auto.\napply f_equal2 with (f := add n); auto.\nrewrite IH with (1 := Hx2) (3 := dconj_hom _ _ _ _ Hz1); auto.\napply sym_equal; rewrite <-addE_assoc, addE_com; auto.\napply f_equal2 with (f := add n); auto.\nrewrite dconj_add, meet_addr, scal_addEr; auto.\napply f_equal2 with (f := add n); auto.\nrewrite (hom0E _ _ Hy1).\nrewrite joinkl,joinkr,dconj_scal, meet_scalr.\nrewrite conjf_hom with (1 := Hx2).\nrewrite dconjf_hom with (1 := Hz2).\nrewrite !meet_scall, !meet_scalr, <-!scal_multE; auto.\nrewrite !multK_assoc, !multK_com with (x := 'C[y1]), <-!multK_assoc; auto.\nKrm1; rewrite !opp_multKl, <-expKS, <-expK_add; auto.\nreplace ((n + (k1.+1 + k2.+1).+1).+1 + (n + k2.+1))% nat with\n        (2 * (n.+1 + k2.+1) + k1.+1)%nat by ring.\nrewrite expKm1_2E; auto.\napply f_equal2 with (f := scal n); auto.\nreplace (n + (k1.+1 + k2.+1).+1)%nat with (n + (k1.+1 + k2).+1).+1 by ring.\nsimpl expK; Krm1.\nrewrite dconjf_joinr, conj_invo; auto.\nQed.\n\nLemma splitll n k1 k2 x y z : hom n k1 x -> hom n 1 y ->  hom n k2 z ->\n  (y ∨ x) ∧ z = (-(1))^(n + k2.+1) .* ((x ∧ (y ∨ z)) - y ∨ (x ∧ z)).\nProof.\nintros Hx Hy Hz.\ncase (Lt.le_or_lt k1 n); intros Hk1.\n2: rewrite hom_lt with (2 := Hx), sub_add, !meet0l; Grm0; rewrite meet0l; auto.\ncase (Lt.le_or_lt k2 n); intros Hk2.\n2: rewrite hom_lt with (2 := Hz), sub_add, !meet0r; Grm0; rewrite meet0r; Grm0.\nrewrite join_hom_com with (2 := Hy) (1 := Hx), meet_scall,\n        splitlr with (k1 := k1) (k2 := k2); auto.\nrewrite sub_add, !scal_addEr, <-scal_multE, <-expK_add; auto.\napply f_equal2 with (f := add n); auto.\nreplace (k1 * 1 + (n + (k1 + k2).+1))%nat with (2 * k1 + (n + k2.+1))%nat by ring.\nrewrite expKm1_2E; auto.\ncase (Lt.le_or_lt n (k1 + k2)%nat); intros Hm1.\n2: rewrite meet_small with (k1 := k1) (k2 := k2); Grm0.\nassert (Hxz := meet_hom _ _ _ _ _ Hx Hz).\nrewrite join_hom_com with (1 := Hxz) (2 := Hy), !Mult.mult_1_r; auto.\nrewrite <-!scal_multE, expKm1_sub; auto.\nKrm1; rewrite  opp_multKl, <-expKS, <- expK_add; auto.\nreplace ((n + k2.+1).+1 +(k1 + k2 + n))%nat with\n        (2 * (n + k2.+1) + k1)%nat by ring.\nrewrite expKm1_2E; auto.\nQed.\n\nLemma splitrr n k1 k2 x y z : hom n k1 x -> hom n 1 y ->  hom n k2 z ->\n  z ∧ (x ∨ y) = (-(1))^(n + k2.+1) .* ((z ∨ y) ∧ x - (z ∧ x) ∨ y).\nProof.\nintros Hx Hy Hz.\nrewrite meet_hom_com with (k2 := k2) (k1 := (k1 + 1)%nat); auto.\nrewrite splitlr with (k1 := k1) (k2 := k2); auto.\nrewrite sub_add, !scal_addEr, <-!scal_multE; auto.\napply f_equal2 with (f := add n); auto.\nrewrite join_hom_com with (1 := Hz) (2 := Hy), !Mult.mult_1_r, meet_scalr,\n        <-scal_multE, <-expK_add; auto.\nrewrite meet_hom_com with (k1 := k1) (k2 := (k2 + 1)%nat) (x := x); auto.\nrewrite <-scal_multE, <-!expK_add; auto.\nreplace ((n + (k1 + 1)) * (n + k2) + (n + (k1 + k2).+1) + k2)%nat with\n        (2* k2 + (n + k2.+1 + (n + k1) * (n + (k2 + 1))))%nat by ring.\nrewrite !expKm1_2E; auto.\nrewrite meet_hom_com with (k1 := k1) (k2 := k2) (x := x); auto.\nKrm1; rewrite <-expKS, join_scall, <- scal_multE, <-expK_add; auto.\nreplace ((n + k2.+1).+1 + (n + k1) * (n + k2))%nat with\n        (2 * 1 + ((n + (k1 + 1)) * (n + k2)))%nat by ring.\nrewrite expKm1_2E; auto.\nQed.\n\nLemma splitrl n k1 k2 x y z : hom n k1 x -> hom n 1 y ->  hom n k2 z ->\n  z ∧ (y ∨ x) = (-(1))^(n + (k1 + k2).+1) .* (z ∨ y) ∧ x + y ∨ (z ∧ x).\nProof.\nintros Hx Hy Hz.\nrewrite meet_hom_com with (k2 := k2) (k1 := (1 + k1)%nat); auto.\nrewrite splitll with (k1 := k1) (k2 := k2); auto.\nrewrite sub_add, !scal_addEr, <-!scal_multE; auto.\napply f_equal2 with (f := add n); auto.\nrewrite join_hom_com with (1 := Hz) (2 := Hy), !Mult.mult_1_r, meet_scalr,\n        <-scal_multE, <-expK_add; auto.\nrewrite meet_hom_com with (k1 := k1) (k2 := (k2 + 1)%nat) (x := x); auto.\nrewrite meet_scalr, <-scal_multE, <-!expK_add; auto.\nreplace ((n + (1 + k1)) * (n + k2) + (n + k2.+1) + k2)%nat with\n        (2 * k2 + (n * n + n * k1 + n * k2 + 2 * n + k1 * k2 + k2 + 1))%nat by ring.\nreplace ((n + k1) * (n + (k2 + 1)) + (n + (k1 + k2).+1))%nat with\n        (2 * k1 + (n * n + n * k1 + n * k2 + 2 * n + k1 * k2 + k2 + 1))%nat by ring.\nrewrite !expKm1_2E; auto.\nrewrite meet_hom_com with (k1 := k1) (k2 := k2) (x := x); auto.\nKrm1; rewrite opp_multKl, <-expKS, join_scalr, <-!expK_add; auto.\nreplace (((n + (1 + k1)) * (n + k2)).+1 + (n + k2.+1))%nat with \n        (2 * (n + k2 + 1) + (n + k1) * (n + k2))%nat by ring.\nrewrite !expKm1_2E; auto.\nQed.\n\nLemma inter n k1 k2 x y z : hom n 1 x -> hom n k1 y ->  hom n k2 z ->\n  x ∨ y = 0 -> x ∨ z = 0 -> x ∨ (y ∧ z) = 0.\nProof.\nintros Hx Hy Hz Hxy Hxz.\ngeneralize  (splitll n k1 k2 y x z Hy Hx Hz).\nrewrite Hxy, Hxz; Grm0.\nrewrite <-scal_multE; Krm1; rewrite <-expKS; auto.\nintros H.\ncase (scalE_integral _ (fn n) _ _ (sym_equal H)); auto.\nintros HH; contradict HH; apply expKm1_n0; auto.\nQed.\n\nLemma join_meet_distrl n k1 k2 x y z :\n   hom n k1 x -> hom n 1 y ->  hom n k2 z ->\n    y ∨ (x ∧ z) = (-(1))^(n + k2) .* ((y ∨ x) ∧ z)  +  x ∧ (y ∨ z).\nProof.\nintros Hx Hy Hz.\nrewrite (splitll n k1 k2 x y z), sub_add, !scal_addEr; auto.\nrewrite <-!scal_multE, <-expK_add; Krm1; rewrite <-expKS; auto.\nreplace (n + k2 + (n + k2.+1))%nat with (2 * (n + k2) + 1)%nat by ring.\nrewrite expKm1_2E, !expKS, expKm1_2E, expKS; simpl expK; Krm1.\nrewrite addE_com, <-addE_assoc, scalE1, scal_addE0; Grm0.\nQed.\n\nLemma meet_join_distrl n k1 k2 x y z :\n  hom n k1 x -> hom n 1 y ->  hom n k2 z ->\n  '@y ∧ (x ∨ z) = (-(1))^k2 .* (('@y ∧ x) ∨ z)  +  x ∨ ('@y ∧ z).\nProof.\nintros Hx Hy Hz.\ncase (Lt.le_or_lt n 0); intros Hn.\ndestruct n.\nrewrite hom_lt with (2 := Hy); Grm0.\ncontradict Hn; auto with arith.\ncase (Lt.le_or_lt k1 n); intros Hk1.\n2: rewrite hom_lt with (2 := Hx); Grm0.\ncase (Lt.le_or_lt k2 n); intros Hk2.\n2: rewrite hom_lt with (2 := Hz); Grm0.\npattern x at 1; rewrite dual_invoE with (1 := Hx).\npattern z at 1; rewrite dual_invoE with (1 := Hz).\nrewrite !join_scalr, !join_scall, !meet_scalr.\nrewrite <-dual_meet, <-dual_join; auto.\nrewrite (join_meet_distrl n (n - k1) (n- k2) '@x y '@z); auto.\nrewrite dual_add, dual_scal, !dual_meet, !dual_join.\nrewrite <-scal_multE, scal_addEr, <-scal_multE, multK_com,\n        <-multK_assoc, !scal_multE; auto.\nrewrite <-join_scall, <-meet_scalr, <-dual_invoE; auto.\nrewrite <-join_scalr, <-dual_invoE; auto.\nrewrite addE_com; auto.\nrewrite <-join_scall, <-dual_invoE; auto.\nrewrite <-join_scalr, <-meet_scalr, <-dual_invoE; auto.\nrewrite addE_com; auto.\nrewrite expK_add, expKm1_sub, <-expK_add; auto.\nreplace (n + (n + k2))%nat with (2 * n + k2)%nat by ring.\nrewrite expKm1_2E; auto.\nQed.\n \nLemma grade_dual n k x : k < n -> grade n k x -> grade n (n - k) '@x.\nassert (dual_aux: forall n x l, hom n 1 x -> is_vector_space n l ->\n (forall y, In y l -> '@x ∧ y = 0) -> '@x ∧ joinl n l = 0).\nintros n1 x1 l Hx; induction l as [|y l IH]; simpl; Vfold n; Grm0.\nintros Hv Hr; destruct l as [|b l1]; auto.\nrewrite meet_join_distrl with (k1 := 1%nat) (k2 := length (b:: l1)); auto.\nrewrite Hr, IH; Grm0.\nintros u Hu; apply Hv; auto with datatypes.\nrewrite <-cbl1_hom1_equiv; apply Hv; auto with datatypes.\napply joinl_hom1; intros u Hu.\nrewrite <-cbl1_hom1_equiv; apply Hv; auto with datatypes.\nassert (dual_aux_rec: forall n x l, hom n 1 x -> is_vector_space n l ->\n '@x ∧ joinl n l = 0  \\/ (exists y, In y l /\\ '@x ∧ y <> 0)).\nintros n1 x1 l H1 H2.\ncase (list_dec _ (fun y => '@x1 ∧ y = 0) l); auto.\nintros y; case (eqE_spec _ (fn n1) ('@x1 ∧ y) 0); auto.\ngeneralize x; clear x.\ninduction k as [|k IH]; auto.\nintros x Hn Hx; rewrite (grade0E _ _ Hx); Grm0.\napply grade0.\nintros x Hn; rewrite !gradeE; intros (Hx, ([|a l], (H1l,H2l))); \n  subst; try discriminate; split; auto.\nexists nil; split; Grm0.\nassert (Hn1: 0 < n)\n   by (destruct n; auto with arith; contradict Hn; auto with arith).\nassert (Ha: hom n 1 a); auto with datatypes.\ncase (eqE_spec _ (fn n) (joinl n (a :: l)) 0); intros Hal.\nrewrite Hal; exists nil; split; Grm0; intros y [].\ncase (homE _  _ (length (a::l)) _ Hx).\napply joinl_hom1; auto.\n2: intros HH; rewrite HH; exists nil; Grm0.\n2: split; auto; intros y [].\nintros HH; injection HH; clear HH; intros Hk.\nassert (F1: exists l1, is_vector_space n l1 /\\ \n     '@(joinl n (a::l)) = '@a ∧ joinl n l1).\ndestruct l.\nexists (base n 1).\nsplit.\nintros u Hu; constructor; auto.\nrewrite joinl_all, meet_allr; auto with arith.\nassert (F1: grade n k  (joinl n (v::l))).\nrewrite gradeE; split.\nrewrite Hk; apply joinl_hom1; auto with datatypes.\nexists (v::l); split; auto with datatypes.\nassert (F2: k < n); auto with arith.\ngeneralize (IH _ F2 F1); rewrite gradeE; intros (_,(l1,(H1l1,H2l1))).\nexists l1; split.\nintros u Hu; red; rewrite cbl1_hom1_equiv; auto with datatypes.\nrewrite joinlS, dual_join, H1l1; auto.\nintros HH; discriminate.\ncase F1; intros l1 (H1l1,H2l1).\nrewrite H2l1.\ncase (dual_aux_rec n a l1); auto with datatypes.\nintros HH; rewrite HH.\nexists nil; split; auto; intros y [].\nintros (b, (H1b,H2b)).\nassert (Hb: hom n 1 b) by\n  (rewrite <-cbl1_hom1_equiv; apply H1l1; auto with datatypes).\ncase (is_vector_space_swap n b l1); auto.\nintros l2 (H1l2,H2l2); rewrite H2l2.\ndestruct l2 as [|c l2].\nassert (F2: hom n 0 '@(joinl n (a :: l))).\nrewrite H2l1, H2l2; simpl.\nreplace 0%nat with ((n - 1) + 1 - n)%nat; auto.\nrewrite Plus.plus_comm, <-Minus.le_plus_minus, <-Minus.minus_n_n; auto.\ncase (homE n n k.+1 (joinl n (a :: l))); auto.\nrewrite dual_invoE with (1 := Hx).\npattern n at 2; replace n with (n - 0)%nat; auto.\nrewrite <-Minus.minus_n_O; auto.\nintros; subst n; contradict Hn; auto with arith.\nintros H1a; case Hal; auto.\nassert (Hc: hom n 1 c) by\n  (rewrite <-cbl1_hom1_equiv; apply H1l2; auto with datatypes).\npose (f := fun x => 'C['@a ∧ x]).\nexists (((- (1)) ^ length (c :: l2) * f b) .* (c + (-(1) * f c * (f b)^-1) .* b) ::\n        map (fun x => x + (-(1) * f x * (f b)^-1) .* b) l2).\nsplit.\nassert (F2: forall y, hom n 1 y -> '@a ∧ y = ['C['@a ∧ y]]).\nintros y Hy; apply hom0E.\nreplace 0%nat with ((n - 1) + 1 - n)%nat; auto.\nrewrite Plus.plus_comm, <-Minus.le_plus_minus, <-Minus.minus_n_n; auto.\nreplace (joinl n (b :: c :: l2)) with\n      (joinl n (b::(c + (-(1) * f c * f b ^-1) .* b)::\n             map (fun x : vect n => x + (-(1) * f x * f b ^-1) .* b) l2)).\nrewrite joinlS; auto.\n2: intros HH; discriminate.\nrewrite (meet_join_distrl n 1 (length (c::l2))); auto.\nrewrite addE_com, dual_aux; Grm0.\nrewrite (F2 b); auto.\nrewrite joinkl, !joinl_scal, !scal_multE; auto.\nintros y Hy; case in_inv with (1 := Hy).\nintros; subst; auto.\nred; apply VectorSpace.cbl_add.\napply H1l2; auto with datatypes.\napply VectorSpace.cbl_scal; apply H1l2; auto with datatypes.\nrewrite in_map_iff; intros (u, (H1u,H2u)); subst.\nred; apply VectorSpace.cbl_add.\napply H1l2; auto with datatypes.\napply VectorSpace.cbl_scal.\napply H1l2; auto with datatypes.\nintros y Hy; case in_inv with (1 := Hy).\nintros HH; subst.\nrewrite meet_addr, !meet_scalr.\nrewrite (F2 c), (F2 b); auto.\nunfold f; rewrite !scalk, addk, !multK_assoc; auto.\nrewrite invKr, multK1r; Krm1.\nrewrite oppKr; auto.\nintros HH; case H2b; rewrite F2, HH; auto.\nrewrite in_map_iff; intros (u, (H1u,H2u)); subst.\nrewrite  meet_addr, !meet_scalr.\nrewrite (F2 u), (F2 b); auto.\nunfold f; rewrite !scalk, addk, !multK_assoc; auto.\nrewrite invKr, multK1r; Krm1.\nrewrite oppKr; auto.\nintros HH; case H2b; rewrite F2, HH; auto.\nrewrite <-cbl1_hom1_equiv; apply H1l2; auto with datatypes.\nreplace (length (c::l2)) with\n  (length (c + (-(1) * f c * f b ^-1) .* b\n      :: map (fun x : vect n => x + (-(1) * f x * f b ^-1) .* b) l2)).\napply joinl_hom1.\nintros y Hy; case in_inv with (1 := Hy).\nintros HH; subst; auto.\nrewrite in_map_iff; intros (u, (H1u,H2u)); subst.\napply add_hom; auto.\nrewrite <-cbl1_hom1_equiv; apply H1l2; auto with datatypes.\nsimpl; rewrite map_length; auto.\nrewrite joinlS.\napply sym_equal; rewrite joinlS.\nchange (c + (-(1) * f c * f b ^-1) .* b\n      :: map (fun x : vect n => x + (-(1) * f x * f b ^-1) .* b) l2) with\n       (map (fun x : vect n => x + (-(1) * f x * f b ^-1) .* b) (c::l2)).\napply joinl_addmult with (f:= fun b x: vect n => (-(1) * f x * f b ^-1)%f); auto.\nsimpl; intros i [[]|Hi]; auto.\nrewrite <-cbl1_hom1_equiv; apply H1l2; auto with datatypes.\nintros HH; discriminate.\nintros HH; discriminate.\nintros y Hy; case in_inv with (1 := Hy).\nintros; subst; auto.\nrewrite in_map_iff; intros (u, (H1u,H2u)); subst.\napply add_hom.\nrewrite <-cbl1_hom1_equiv; apply H1l2; auto with datatypes.\napply scal_hom.\nrewrite <-cbl1_hom1_equiv; apply H1l2; auto with datatypes.\nQed.\n\nLemma grade_meet n k1 k2 x y : n < k1 + k2 ->\n  grade n k1 x -> grade n k2 y -> grade n (k1 + k2 - n) (x ∧ y).\nProof.\nintros Hk1Hk2 Hx Hy.\nassert (Hmx: hom n k1 x) by (apply grade_hom; auto).\nassert (Hmy: hom n k2 y) by (apply grade_hom; auto).\ncase (Lt.le_or_lt k1 n); intros Hk1.\n2: rewrite hom_lt with (1 := Hk1)(2:= Hmx); Grm0; apply grade0.\ncase (Lt.le_lt_or_eq _ _ Hk1); intros H1k1; subst.\n2: rewrite homn_all with (1 := Hmx), meet_scall, meet_alll.\n2: apply grade_scal; rewrite Minus.minus_plus; auto with arith.\ncase (Lt.le_or_lt k2 n); intros Hk2.\n2: rewrite hom_lt with (1 := Hk2)(2:= Hmy); Grm0; apply grade0.\ncase (Lt.le_lt_or_eq _ _ Hk2); intros H1k2; subst.\n2: rewrite homn_all with (1 := Hmy), meet_scalr, meet_allr.\n2: apply grade_scal; rewrite Plus.plus_comm, Minus.minus_plus; auto with arith.\nreplace (k1 + k2 - n)%nat with (n - ((n - k1) + (n - k2)))%nat; auto.\nassert (F1: hom n (k1 + k2 - n) (x ∧ y)) by\n  (rewrite gradeE in Hx, Hy; case Hx; case Hy; auto).\nrewrite dual_invoE with (1 := F1).\napply grade_scal.\nrewrite dual_meet.\napply grade_dual; auto.\napply Plus.plus_lt_reg_l with k1.\nrewrite Plus.plus_assoc, <-Minus.le_plus_minus, Plus.plus_comm; auto.\napply Plus.plus_lt_compat_r.\napply Plus.plus_lt_reg_l with k2.\nrewrite <-Minus.le_plus_minus, Plus.plus_comm; auto.\napply grade_join; auto; apply grade_dual; auto.\nrewrite Minus.minus_plus_simpl_l_reverse with (p := (k1 + k2)%nat).\nrewrite (Plus.plus_comm k1), <-!Plus.plus_assoc, (Plus.plus_assoc k1).\nrewrite <-Minus.le_plus_minus, !Plus.plus_assoc; auto.\nrewrite !(Plus.plus_comm k2), <-!Plus.plus_assoc, <-Minus.le_plus_minus; auto.\nrewrite Plus.plus_assoc, (Plus.plus_comm (k1 + k2)); auto. \nrewrite <-Minus.minus_plus_simpl_l_reverse; auto.\nQed.\n\n(* Defining the natural injection of Kn in Gn *)\n\nDefinition Kn := kn p.\n\nFixpoint k2g (n: nat) {struct n} : kn n ->  vect n :=\n  match n return kn n -> vect n with \n    O => fun k => 0%f\n  | S n1 => fun v => let (k, v1) := v in ([k], k2g n1 v1)\n  end.\n\nNotation \"'v_ x\" := (k2g _ x) (at level 9). \nNotation \"'kn n\" := (vn_eparams p (pred n)) (at level 10).\n\nLemma k2g0 n : 'v_0 = 0 :> vect n.\nProof.\ninduction n as [|n IH]; simpl; auto.\nsimpl in IH; rewrite IH; auto.\nQed.\n\nLemma k2g_add n x y : 'v_(x + y) = 'v_x + 'v_y :> vect n. \nProof. \ninduction n as [|n IH]; simpl; Krm0.\ndestruct x as [k1 x]; destruct y as [k2 y]; simpl.\ngeneralize (IH x y); simpl; intros HH; rewrite HH.\nrewrite <-addk; Vfold n; Grm0.\nQed.\n\nLemma k2g_scal n k x : 'v_(k .* x) = (k: K) .* 'v_x :> vect n.\nProof.\ninduction n as [|n IH]; simpl; Krm0.\ndestruct x as [k1 x].\ngeneralize (IH k x); simpl; intros HH; rewrite HH.\nrewrite <-scalk; Vfold n; Grm0.\nQed.\n\nLemma k2g_unit n i : i < n -> 'v_('e_i)%Kn = 'e_i :> vect n.\nProof.\ngeneralize i; clear i.\ninduction n as [|n IH]; Krm0.\nintros i Hi; auto; contradict Hi; auto with arith.\nintros [|i] Hi; simpl;\n  rewrite ?k2g0; rewrite ?IH; auto with arith.\nQed.\n\nLemma k2g_hom n x : hom n 1 ('v_x).\nProof.\ninduction n as [|n IH]; Krm0.\nsimpl; rewrite eqKI; auto.\ndestruct x as [k x]; simpl.\nrewrite  hom0K; apply (IH x).\nQed.\n\nLemma hom1E n x : hom n 1 x -> exists y, x = 'v_y.\nProof.\ninduction n as [|n IH]; simpl; Krm0.\ncase eqK_spec; auto; intros; subst; try discriminate.\nexists tt; auto.\ndestruct x as [x1 x2].\nrewrite andbP; intros (Hx1, Hx2).\ncase (IH _ Hx2); intros y Hy.\nexists ('C[x1], y).\nrewrite <-(hom0E _ _ Hx1), <-Hy; auto.\nQed.\n\nLemma k2glift n x : 'v_(Kn.lift p n x) = ('v_x)^'l.\nProof. auto. Qed.\n\nLemma pscal_join n x y : 'v_x ∨ '@('v_y) =  ((x [.] y)%Kn:K) .* E :> vect n.\nProof.\ninduction n as [|n IH]; simpl; Krm0; Krm1.\ndestruct x as [k x]; destruct y as [h y]; Vfold n.\nVrm0.\nrewrite !dualk, !joinkl; simpl expK; Grm0; Krm1.\nrewrite !(conjf_hom _ _ _ (k2g_hom _ _)); simpl expK; Grm0; Krm1.\nrewrite dual_scal, !join_scall, !join_scalr, IH.\nrewrite <- scal_multE, (scal_addEl (vn_eparams n)); auto. rewrite <-!scal_multE; Krm1.\nrewrite (join_allhr _ _ _ (k2g_hom _ _)); Vrm0.\nQed.\n\nLemma pscal_meet n x y : 'v_x ∧ '@('v_y) =  ((x [.] y)%Kn:K) .* 1 :> vect n.\nProof.\ndestruct n as [|n].\nsimpl; Krm0.\nrewrite Kn.pscal_com, <-dual_all, <-dual_scal, <-pscal_join, dual_join; auto.\nrewrite dual_invo with (k := 1%nat).\n2: apply k2g_hom.\nrewrite meet_hom_com with (k2 := 1%nat) (k1 := (n.+1 - 1)%nat).\n2: apply dual_hom; apply k2g_hom.\n2: apply k2g_hom.\nrewrite meet_scalr.\nreplace ((n.+1 + (n.+1 - 1)) * (n.+1 + 1))%nat with \n        (2 * ((n.+1 -1) * n.+2) +  (1 * n .+2))%nat.\nrewrite expKm1_2E; auto.\nsimpl minus; rewrite <-Minus.minus_n_O.\nring.\nQed.\n\n(* This is 0 *)\nDefinition V0 := genk (dim p) 0.\n(* This is 1 *)\nDefinition V1 := genk (dim p) 1.\nDefinition Vect := vect p.\n(* This is the equality for our vectors *)\nDefinition Veq: Vect -> Vect -> bool := eq p.\n(* This is the addition for our vectors *)\nDefinition Vadd: Vect -> Vect -> Vect := add p.\n(* This is the multiplication for our vectors *)\nDefinition Vscal: K -> Vect -> Vect := scal (dim p).\n(* This is the generator of the base *)\nDefinition Vgen := gen p.\nDefinition Vgenk := genk p.\n(* This is the ad-hoc conjugate for our vectors (maybe useless) *)\nDefinition Vconj: bool -> Vect -> Vect := conj (dim p).\n(* This is the multiplication for our vectors *)\nDefinition Vjoin: Vect -> Vect -> Vect := join (dim p).\nDefinition Vmeet: Vect -> Vect -> Vect := meet (dim p).\nDefinition Vcontra: Kn -> Vect -> Vect := contra (dim p).\nDefinition Vdual: Vect -> Vect := dual (dim p).\nDefinition Vdecompose: Vect -> option (list Vect) := decompose (dim p).\nDefinition K2G: Kn -> Vect  := k2g p.\n\nDefinition v_eparams :=\n  Build_eparams Vect K V0 Veq Vadd Vscal.\n\nDefinition f: vparamsProp (Kn.v_eparams p) := (Kn.fn p Hp p).\n\nEnd Vect.\n\nDeclare Scope Gn_scope.\nDelimit Scope Gn_scope with Gn.\nNotation \" 'e_ p\" := (gen _  _ p) : Gn_scope.\nNotation \" [ k ] \" := (genk _ _ k) (at level 9) : Gn_scope.\n\nRequire Import QArith.\n\nOpen Scope Q_scope.\n\nDefinition Qparams (n:nat) := Build_params \n   n\n  (Build_fparams\n  Q \n  0%Q\n  1%Q\n Qeq_bool\n Qopp\n Qplus\n Qmult\n Qinv)\n.\n\nModule Ex2D.\n\n(* Q in 2 D *)\n\nLocal Definition p := Qparams 2.\n\nNotation \"[[ X: x , Y: y , X**Y: xy ]]\" :=  ((xy,x),(y,0)).\n\nDefinition X := (Vgen p 0).\nEval compute in X.\nDefinition Y := (Vgen p 1).\nEval compute in Y.\n\nNotation \"x '∨' y\" := (Vjoin p  x y) (at level 40, left associativity).\nNotation \"x + y\" := (Vadd p  x y).\nNotation \"k .* x\" := (Vscal p  k x).\nNotation \"x '∧' y\" := (Vmeet p  x y) (at level 40, left associativity).\nNotation \"'@  x\" := (Vdual p x) (at level 100).\n\nEval vm_compute in (X ∨ Y) ∧ (X ∨ Y).\n\nEval vm_compute in '@(X + Y).\n\nEval vm_compute in (X + Y) ∨ '@(X + Y).\n\nEnd Ex2D.\n\nModule Ex3D.\n\n(* Q in 3 D *)\n\nLocal Definition p := Qparams 3.\n\nNotation \"[[ X: x , Y: y ,  Z: z , X**Y: xy , Y**Z: yz  , X**Z: xz , X**Y**Z: xyz ]]\" :=\n  ((((xyz,xy),(xz,x)), ((yz,y),(z,0)))).\n\nDefinition X := (Vgen p 0).\nEval compute in X.\nDefinition Y := (Vgen p 1).\nEval compute in Y.\nDefinition Z := (Vgen p 2).\nEval compute in Z.\n\n\nNotation \"x '∨' y\" := (Vjoin p  x y) (at level 40, left associativity).\nNotation \"x + y\" := (Vadd p  x y).\nNotation \"k .* x\" := (Vscal p  k x).\nNotation \"x '∧' y\" := (Vmeet p  x y) (at level 40, left associativity).\nNotation \"'@  x\" := (Vdual p x) (at level 100).\n\nEval vm_compute in '@(Vgen p 3).\n\nEval vm_compute in (X ∨ Z) ∧ (Y ∨ Z).\n\nEval vm_compute in '@((X∨Y)∧ ( Z)).\n\nEval vm_compute in (X + Y) ∨ '@(X + Y).\n\n\nEval vm_compute in Vdecompose p ((X ∨ Y) ∧ (Y ∨ Z)).\n\nEval vm_compute in Vdecompose p ((X + Y) ∨ (X + Z)).\n\nEval vm_compute in Vdecompose p ((X + Y + Z) ∨ (X + Z) ∨ (X + Y)).\n\nEval vm_compute in Vdecompose p ((X + Y) ∨ (Y + Z)).\n\nEval vm_compute in (X + Y) ∨ (X + Z) + \n  (-1#1)%Q .* (((-1#1)%Q .* Y + Z) ∨ ((-1#1)%Q .* (X + Y))).\n\nEval vm_compute in ((-1#1)%Q .* Y + Z) ∨ (X + Y) ∨ (X + Z).\n\nEval vm_compute in (X ∨ Y ∨ Z) ∨ (X ∨ Y ∨ Z).\nEval vm_compute in (X + Y + Z) ∨ (X + Y + Z).\nEval vm_compute in Z ∨ Y ∨ X.\nEval vm_compute in X ∨ Z.\nEval vm_compute in Z ∨ X.\nEval vm_compute in X ∨ Y ∨ Z.\nEval vm_compute in Z ∨ X ∨ Y.\nEval vm_compute in Y ∨ X ∨ Z.\nEval vm_compute in Y ∨ X.\n\nEnd Ex3D.\n\n\nModule Ex4D.\n\n(* Q in 4 D *)\n\nLocal Definition p := Qparams 4.\n\nNotation \" '[[' 'X:' x ',' 'Y:' y ','  'Z:' z , 'T:' t ',' 'X**Y:' xy ',' 'X**Z:' xz ',' 'X**T:' xt ',' 'Y**Z:' yz ',' 'Y**T:' yt ',' 'Z**T:' zt ',' 'X**Y**Z:' xyz ',' 'X**Y**T:' xyt ',' 'X**Z**T:' xzt ',' 'Y**Z**T:' yzt ','  'X**Y**Z**T:' xyzt ','  'K:' vv  ']]'\" :=\n ((((xyzt, xyz), (xyt, xy)), ((xzt, xz), (xt, x))) , \n  (((yzt, yz), (yt, y)), ((zt,z), (t, vv)))).\n\nDefinition X := (Vgen p 0).\nEval compute in X.\nDefinition Y := (Vgen p 1).\nEval compute in Y.\nDefinition Z := (Vgen p 2).\nEval compute in Z.\nDefinition T := (Vgen p 3).\nEval compute in T.\n\nNotation \"x '∨' y\" := (Vjoin p  x y) (at level 40, left associativity).\nNotation \"x + y\" := (Vadd p  x y).\nNotation \"k .* x\" := (Vscal p  k x).\nNotation \"x '∧' y\" := (Vmeet p  x y) (at level 40, left associativity).\nNotation \"'@  x\" := (Vdual p x) (at level 100).\nNotation \"#< l , x ># \" := (Vcontra p l x).\n\nEval vm_compute in '@X.\n\nEval vm_compute in (X + Y) ∨ '@(X + Y).\n\nDefinition X' := (1, (0, (0, (0, tt)))).\nDefinition Y' := (0, (1, (0, (0, tt)))).\nDefinition Z' := (0, (0, (1, (0, tt)))).\nDefinition T' := (0, (0, (0, (1, tt)))).\n\n\nDefinition U := (X + Y) ∨ Z.\n\nEval vm_compute in U.\n\nDefinition fxy := #<Y', #< X', U ># >#.\nDefinition fxz := #<Z', #< X', U ># >#.\nDefinition fxt := #<T', #< X', U ># >#.\nDefinition fyz := #<Z', #< Y', U ># >#.\nDefinition fyt := #<T', #< Y', U ># >#.\nDefinition fzt := #<T', #< Z', U ># >#.\n\n\nEval vm_compute in fxy.\n\n\nEval vm_compute in #< Y', X>#.\n\n\nEval vm_compute in (X ∨ Y ∨ Z) ∨ (X ∨ Y ∨ Z).\n\nEval vm_compute in (X + Y + Z) ∨ (X + Y + Z).\nEval vm_compute in Z ∨ Y ∨ X.\nEval vm_compute in X ∨ Z.\nEval vm_compute in Z ∨ X.\nEval vm_compute in X ∨ Y ∨ Z.\nEval vm_compute in Z ∨ X ∨ Y.\nEval vm_compute in Y ∨ X ∨ Z.\nEval vm_compute in Y ∨ X.\nEval vm_compute in X ∨ T.\nEval vm_compute in T ∨ X.\n\nEval vm_compute in Vconj p false (Z ∨ T) ∨ (X ∨ Y).\n\nEval vm_compute in (X ∨ Y ∨ Z ∨ T) ∨ (X ∨ Y ∨ Z ∨ T).\n\nEnd Ex4D.\n\nModule Ex5D.\n\n(* Q in 5 D *)\n\nLocal Definition p := Qparams 5.\n\nNotation \" [[ X: x , Y: y ,  Z: z , T: t , U: u , X**Y: xy , X**Z: xz , X**T: xt , X**U: xu , Y**Z: yz , Y**T: yt , Y**U: yu , Z**T: zt , Z**U: zu , T**U: tu , X**Y**Z: xyz , X**Y**T: xyt , X**Y**U: xyu , X**Z**T: xzt , X**Z**U: xzu , X**T**U: xtu , Y**Z**T: yzt , Y**Z**U: yzu , Y**T**U: ytu , Z**T**U: ztu , X**Y**Z**T: xyzt , X**Y**Z**U: xyzu , X**Y**T**U: xytu , X**Z**T**U: xztu , Y**Z**T**U: yztu , X**Y**Z**T**U: xyztu , 'K:' vv ]]\" :=\n(\n ((((xyztu, xyzt), (xyzu, xyz)), ((xytu, xyt), (xyu, xy))) , \n  (((xztu, xzt), (xzu, xz)), ((xtu,xt), (xu, x)))),\n ((((yztu, yzt), (yzu, yz)), ((ytu, yt), (yu, y))) , \n  (((ztu, zt), (zu, z)), ((tu,t), (u, vv))))).\n\nDefinition X := (Vgen p 0).\nEval compute in X.\nDefinition Y := (Vgen p 1).\nEval compute in Y.\nDefinition Z := (Vgen p 2).\nEval compute in Z.\nDefinition T := (Vgen p 3).\nEval compute in T.\nDefinition U := (Vgen p 4).\nEval compute in U.\n\nNotation \"x '∨' y\" := (Vjoin p  x y) (at level 40, left associativity).\nNotation \"x + y\" := (Vadd p  x y).\nNotation \"k .* x\" := (Vscal p  k x).\nNotation \"x '∧' y\" := (Vmeet p  x y) (at level 40, left associativity).\nNotation \"'@  x\" := (Vdual p x) (at level 100).\n\nEval vm_compute in Vconj p false (T ∨ U) ∨ (X ∨ Y ∨ Z).\nEval vm_compute in Vconj p false (X ∨ Y ∨ Z ∨ T ∨ U).\n\nEnd Ex5D.\n\nModule Ex6D.\n\n(* Q in 6 D *)\n\nLocal Definition p := Qparams 6.\n\nDefinition X := (Vgen p 0).\nEval compute in X.\nDefinition Y := (Vgen p 1).\nEval compute in Y.\nDefinition Z := (Vgen p 2).\nEval compute in Z.\nDefinition T := (Vgen p 3).\nEval compute in T.\nDefinition U := (Vgen p 4).\nEval compute in U.\nDefinition K := (Vgen p 5).\nEval compute in K.\n\n\nNotation \"x '∨' y\" := (Vjoin p  x y) (at level 40, left associativity).\nNotation \"x + y\" := (Vadd p  x y).\nNotation \"k .* x\" := (Vscal p  k x).\nNotation \"x '∧' y\" := (Vmeet p  x y) (at level 40, left associativity).\nNotation \"'@  x\" := (Vdual p x) (at level 100).\n\nEval vm_compute in \n  ((X ∨ (Y ∨ Z ∨ T)) + (U ∨ K)) ∨\n  ((X ∨ (Y ∨ Z ∨ T)) + (U ∨ K)).\n\nEval vm_compute in Vconj p false (T ∨ U) ∨ (X ∨ Y ∨ Z).\nEval vm_compute in Vconj p false (X ∨ Y ∨ Z ∨ T ∨ U).\n\nEval vm_compute in\n  ((X ∨ T) + (Y ∨ Z)) ∨ ((X ∨ T) + (Y ∨ Z)).\n\nEnd Ex6D.\n\n", "meta": {"author": "olivierverdier", "repo": "GeometricAlgebra", "sha": "86105900b5c3e58e7b117f714037b173a9cdcc75", "save_path": "github-repos/coq/olivierverdier-GeometricAlgebra", "path": "github-repos/coq/olivierverdier-GeometricAlgebra/GeometricAlgebra-86105900b5c3e58e7b117f714037b173a9cdcc75/Grassmann.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6798375045906426}}
{"text": "(** * StlcProp: Properties of STLC *)\n\nRequire Import Maps.\nRequire Import Types.\nRequire Import Stlc.\nRequire Import Smallstep.\nModule STLCProp.\nImport STLC.\n\n(** In this chapter, we develop the fundamental theory of the Simply\n    Typed Lambda Calculus -- in particular, the type safety\n    theorem. *)\n\n(* ################################################################# *)\n(** * Canonical Forms *)\n\n(** As we saw for the simple calculus in the [Types] chapter, the\n    first step in establishing basic properties of reduction and types\n    is to identify the possible _canonical forms_ (i.e., well-typed\n    closed values) belonging to each type.  For [Bool], these are the boolean\n    values [ttrue] and [tfalse].  For arrow types, the canonical forms\n    are lambda-abstractions.  *)\n\nLemma canonical_forms_bool : forall t,\n  empty |- t \\in TBool ->\n  value t ->\n  (t = ttrue) \\/ (t = tfalse).\nProof.\n  intros t HT HVal.\n  inversion HVal; intros; subst; try inversion HT; auto.\nQed.\n\nLemma canonical_forms_fun : forall t T1 T2,\n  empty |- t \\in (TArrow T1 T2) ->\n  value t ->\n  exists x u, t = tabs x T1 u.\nProof.\n  intros t T1 T2 HT HVal.\n  inversion HVal; intros; subst; try inversion HT; subst; auto.\n  exists x0. exists t0.  auto.\nQed.\n\n(* ################################################################# *)\n(** * Progress *)\n\n(** As before, the _progress_ theorem tells us that closed, well-typed\n    terms are not stuck: either a well-typed term is a value, or it\n    can take a reduction step.  The proof is a relatively\n    straightforward extension of the progress proof we saw in the\n    [Types] chapter.  We'll give the proof in English first, then the\n    formal version. *)\n\nTheorem progress : forall t T,\n     empty |- t \\in T ->\n     value t \\/ exists t', t ==> t'.\n\n(** _Proof_: By induction on the derivation of [|- t \\in T].\n\n    - The last rule of the derivation cannot be [T_Var], since a\n      variable is never well typed in an empty context.\n\n    - The [T_True], [T_False], and [T_Abs] cases are trivial, since in\n      each of these cases we can see by inspecting the rule that [t]\n      is a value.\n\n    - If the last rule of the derivation is [T_App], then [t] has the\n      form [t1 t2] for som e[t1] and [t2], where we know that [t1] and\n      [t2] are also well typed in the empty context; in particular,\n      there exists a type [T2] such that [|- t1 \\in T2 -> T] and [|-\n      t2 \\in T2].  By the induction hypothesis, either [t1] is a value\n      or it can take a reduction step.\n\n        - If [t1] is a value, then consider [t2], which by the other\n          induction hypothesis must also either be a value or take a step.\n\n            - Suppose [t2] is a value.  Since [t1] is a value with an\n              arrow type, it must be a lambda abstraction; hence [t1\n              t2] can take a step by [ST_AppAbs].\n\n            - Otherwise, [t2] can take a step, and hence so can [t1\n              t2] by [ST_App2].\n\n        - If [t1] can take a step, then so can [t1 t2] by [ST_App1].\n\n    - If the last rule of the derivation is [T_If], then [t = if t1\n      then t2 else t3], where [t1] has type [Bool].  By the IH, [t1]\n      either is a value or takes a step.\n\n        - If [t1] is a value, then since it has type [Bool] it must be\n          either [true] or [false].  If it is [true], then [t] steps\n          to [t2]; otherwise it steps to [t3].\n\n        - Otherwise, [t1] takes a step, and therefore so does [t] (by\n          [ST_If]). *)\n\nProof with eauto.\n  intros t T Ht.\n  remember (@empty ty) as Gamma.\n  induction Ht; subst Gamma...\n  - (* T_Var *)\n    (* contradictory: variables cannot be typed in an\n       empty context *)\n    inversion H.\n\n  - (* T_App *)\n    (* [t] = [t1 t2].  Proceed by cases on whether [t1] is a\n       value or steps... *)\n    right. destruct IHHt1...\n    + (* t1 is a value *)\n      destruct IHHt2...\n      * (* t2 is also a value *)\n        assert (exists x0 t0, t1 = tabs x0 T11 t0).\n        eapply canonical_forms_fun; eauto.\n        destruct H1 as [x0 [t0 Heq]]. subst.\n        exists ([x0:=t2]t0)...\n\n      * (* t2 steps *)\n        inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...\n\n    + (* t1 steps *)\n      inversion H as [t1' Hstp]. exists (tapp t1' t2)...\n\n  - (* T_If *)\n    right. destruct IHHt1...\n\n    + (* t1 is a value *)\n      destruct (canonical_forms_bool t1); subst; eauto.\n\n    + (* t1 also steps *)\n      inversion H as [t1' Hstp]. exists (tif t1' t2 t3)...\nQed.\n\n(** **** Exercise: 3 stars, optional (progress_from_term_ind)  *)\n(** Show that progress can also be proved by induction on terms\n    instead of induction on typing derivations. *)\n\nTheorem progress' : forall t T,\n     empty |- t \\in T ->\n     value t \\/ exists t', t ==> t'.\nProof.\n  intros t.\n  induction t; intros T Ht; auto.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Preservation *)\n\n(** The other half of the type soundness property is the preservation\n    of types during reduction.  For this, we need to develop some\n    technical machinery for reasoning about variables and\n    substitution.  Working from top to bottom (from the high-level\n    property we are actually interested in to the lowest-level\n    technical lemmas that are needed by various cases of the more\n    interesting proofs), the story goes like this:\n\n      - The _preservation theorem_ is proved by induction on a typing\n        derivation, pretty much as we did in the [Types] chapter.  The\n        one case that is significantly different is the one for the\n        [ST_AppAbs] rule, whose definition uses the substitution\n        operation.  To see that this step preserves typing, we need to\n        know that the substitution itself does.  So we prove a...\n\n      - _substitution lemma_, stating that substituting a (closed)\n        term [s] for a variable [x] in a term [t] preserves the type\n        of [t].  The proof goes by induction on the form of [t] and\n        requires looking at all the different cases in the definition\n        of substitition.  This time, the tricky cases are the ones for\n        variables and for function abstractions.  In both cases, we\n        discover that we need to take a term [s] that has been shown\n        to be well-typed in some context [Gamma] and consider the same\n        term [s] in a slightly different context [Gamma'].  For this\n        we prove a...\n\n      - _context invariance_ lemma, showing that typing is preserved\n        under \"inessential changes\" to the context [Gamma] -- in\n        particular, changes that do not affect any of the free\n        variables of the term.  And finally, for this, we need a\n        careful definition of...\n\n      - the _free variables_ of a term -- i.e., those variables\n        mentioned in a term and not in the scope of an enclosing\n        function abstraction binding a variable of the same name.\n\n   To make Coq happy, we need to formalize the story in the opposite\n   order... *)\n\n(* ================================================================= *)\n(** ** Free Occurrences *)\n\n(** A variable [x] _appears free in_ a term _t_ if [t] contains some\n    occurrence of [x] that is not under an abstraction labeled [x].\n    For example:\n      - [y] appears free, but [x] does not, in [\\x:T->U. x y]\n      - both [x] and [y] appear free in [(\\x:T->U. x y) x]\n      - no variables appear free in [\\x:T->U. \\y:T. x y]\n\n    Formally: *)\n\nInductive appears_free_in : id -> tm -> Prop :=\n  | afi_var : forall x,\n      appears_free_in x (tvar x)\n  | afi_app1 : forall x t1 t2,\n      appears_free_in x t1 -> appears_free_in x (tapp t1 t2)\n  | afi_app2 : forall x t1 t2,\n      appears_free_in x t2 -> appears_free_in x (tapp t1 t2)\n  | afi_abs : forall x y T11 t12,\n      y <> x  ->\n      appears_free_in x t12 ->\n      appears_free_in x (tabs y T11 t12)\n  | afi_if1 : forall x t1 t2 t3,\n      appears_free_in x t1 ->\n      appears_free_in x (tif t1 t2 t3)\n  | afi_if2 : forall x t1 t2 t3,\n      appears_free_in x t2 ->\n      appears_free_in x (tif t1 t2 t3)\n  | afi_if3 : forall x t1 t2 t3,\n      appears_free_in x t3 ->\n      appears_free_in x (tif t1 t2 t3).\n\nHint Constructors appears_free_in.\n\n(** A term in which no variables appear free is said to be _closed_. *)\n\nDefinition closed (t:tm) :=\n  forall x, ~ appears_free_in x t.\n\n(** **** Exercise: 1 star (afi)  *)\n(** If the definition of [appears_free_in] is not crystal clear to\n    you, it is a good idea to take a piece of paper and write out the\n    rules in informal inference-rule notation.  (Although it is a\n    rather low-level, technical definition, understanding it is\n    crucial to understanding substitution and its properties, which\n    are really the crux of the lambda-calculus.) *)\n(** [] *)\n\n(* ================================================================= *)\n(** ** Substitution *)\n\n(** To prove that substitution preserves typing, we first need a\n    technical lemma connecting free variables and typing contexts: If\n    a variable [x] appears free in a term [t], and if we know [t] is\n    well typed in context [Gamma], then it must be the case that\n    [Gamma] assigns a type to [x]. *)\n\nLemma free_in_context : forall x t T Gamma,\n   appears_free_in x t ->\n   Gamma |- t \\in T ->\n   exists T', Gamma x = Some T'.\n\n(** _Proof_: We show, by induction on the proof that [x] appears\n      free in [t], that, for all contexts [Gamma], if [t] is well\n      typed under [Gamma], then [Gamma] assigns some type to [x].\n\n      - If the last rule used was [afi_var], then [t = x], and from\n        the assumption that [t] is well typed under [Gamma] we have\n        immediately that [Gamma] assigns a type to [x].\n\n      - If the last rule used was [afi_app1], then [t = t1 t2] and [x]\n        appears free in [t1].  Since [t] is well typed under [Gamma],\n        we can see from the typing rules that [t1] must also be, and\n        the IH then tells us that [Gamma] assigns [x] a type.\n\n      - Almost all the other cases are similar: [x] appears free in a\n        subterm of [t], and since [t] is well typed under [Gamma], we\n        know the subterm of [t] in which [x] appears is well typed\n        under [Gamma] as well, and the IH gives us exactly the\n        conclusion we want.\n\n      - The only remaining case is [afi_abs].  In this case [t =\n        \\y:T11.t12], and [x] appears free in [t12]; we also know that\n        [x] is different from [y].  The difference from the previous\n        cases is that whereas [t] is well typed under [Gamma], its\n        body [t12] is well typed under [(Gamma, y:T11)], so the IH\n        allows us to conclude that [x] is assigned some type by the\n        extended context [(Gamma, y:T11)].  To conclude that [Gamma]\n        assigns a type to [x], we appeal to lemma [update_neq], noting\n        that [x] and [y] are different variables. *)\n\nProof.\n  intros x t T Gamma H H0. generalize dependent Gamma.\n  generalize dependent T.\n  induction H;\n         intros; try solve [inversion H0; eauto].\n  - (* afi_abs *)\n    inversion H1; subst.\n    apply IHappears_free_in in H7.\n    rewrite update_neq in H7; assumption.\nQed.\n\n(** Next, we'll need the fact that any term [t] which is well typed in\n    the empty context is closed (it has no free variables). *)\n\n(** **** Exercise: 2 stars, optional (typable_empty__closed)  *)\nCorollary typable_empty__closed : forall t T,\n    empty |- t \\in T  ->\n    closed t.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Sometimes, when we have a proof [Gamma |- t : T], we will need to\n    replace [Gamma] by a different context [Gamma'].  When is it safe\n    to do this?  Intuitively, it must at least be the case that\n    [Gamma'] assigns the same types as [Gamma] to all the variables\n    that appear free in [t]. In fact, this is the only condition that\n    is needed. *)\n\nLemma context_invariance : forall Gamma Gamma' t T,\n     Gamma |- t \\in T  ->\n     (forall x, appears_free_in x t -> Gamma x = Gamma' x) ->\n     Gamma' |- t \\in T.\n\n(** _Proof_: By induction on the derivation of \n    [Gamma |- t \\in T].\n\n      - If the last rule in the derivation was [T_Var], then [t = x]\n        and [Gamma x = T].  By assumption, [Gamma' x = T] as well, and\n        hence [Gamma' |- t \\in T] by [T_Var].\n\n      - If the last rule was [T_Abs], then [t = \\y:T11. t12], with [T\n        = T11 -> T12] and [Gamma, y:T11 |- t12 \\in T12].  The\n        induction hypothesis is that, for any context [Gamma''], if\n        [Gamma, y:T11] and [Gamma''] assign the same types to all the\n        free variables in [t12], then [t12] has type [T12] under\n        [Gamma''].  Let [Gamma'] be a context which agrees with\n        [Gamma] on the free variables in [t]; we must show [Gamma' |-\n        \\y:T11. t12 \\in T11 -> T12].\n\n        By [T_Abs], it suffices to show that [Gamma', y:T11 |- t12 \\in\n        T12].  By the IH (setting [Gamma'' = Gamma', y:T11]), it\n        suffices to show that [Gamma, y:T11] and [Gamma', y:T11] agree\n        on all the variables that appear free in [t12].\n\n        Any variable occurring free in [t12] must be either [y] or\n        some other variable.  [Gamma, y:T11] and [Gamma', y:T11]\n        clearly agree on [y].  Otherwise, note that any variable other\n        than [y] that occurs free in [t12] also occurs free in [t =\n        \\y:T11. t12], and by assumption [Gamma] and [Gamma'] agree on\n        all such variables; hence so do [Gamma, y:T11] and [Gamma',\n        y:T11].\n\n      - If the last rule was [T_App], then [t = t1 t2], with [Gamma |-\n        t1 \\in T2 -> T] and [Gamma |- t2 \\in T2].  One induction\n        hypothesis states that for all contexts [Gamma'], if [Gamma']\n        agrees with [Gamma] on the free variables in [t1], then [t1]\n        has type [T2 -> T] under [Gamma']; there is a similar IH for\n        [t2].  We must show that [t1 t2] also has type [T] under\n        [Gamma'], given the assumption that [Gamma'] agrees with\n        [Gamma] on all the free variables in [t1 t2].  By [T_App], it\n        suffices to show that [t1] and [t2] each have the same type\n        under [Gamma'] as under [Gamma].  But all free variables in\n        [t1] are also free in [t1 t2], and similarly for [t2]; hence\n        the desired result follows from the induction hypotheses. *)\n\nProof with eauto.\n  intros.\n  generalize dependent Gamma'.\n  induction H; intros; auto.\n  - (* T_Var *)\n    apply T_Var. rewrite <- H0...\n  - (* T_Abs *)\n    apply T_Abs.\n    apply IHhas_type. intros x1 Hafi.\n    (* the only tricky step... the [Gamma'] we use to\n       instantiate is [update Gamma x T11] *)\n    unfold update. unfold t_update. destruct (beq_id x0 x1) eqn: Hx0x1...\n    rewrite beq_id_false_iff in Hx0x1. auto.\n  - (* T_App *)\n    apply T_App with T11...\nQed.\n\n(** Now we come to the conceptual heart of the proof that reduction\n    preserves types -- namely, the observation that _substitution_\n    preserves types.\n\n    Formally, the so-called _Substitution Lemma_ says this: Suppose we\n    have a term [t] with a free variable [x], and suppose we've been\n    able to assign a type [T] to [t] under the assumption that [x] has\n    some type [U].  Also, suppose that we have some other term [v] and\n    that we've shown that [v] has type [U].  Then, since [v] satisfies\n    the assumption we made about [x] when typing [t], we should be\n    able to substitute [v] for each of the occurrences of [x] in [t]\n    and obtain a new term that still has type [T]. *)\n\n(** _Lemma_: If [Gamma,x:U |- t \\in T] and [|- v \\in U], then [Gamma |-\n    [x:=v]t \\in T]. *)\n\nLemma substitution_preserves_typing : forall Gamma x U t v T,\n     update Gamma x U |- t \\in T ->\n     empty |- v \\in U   ->\n     Gamma |- [x:=v]t \\in T.\n\n(** One technical subtlety in the statement of the lemma is that\n    we assign [v] the type [U] in the _empty_ context -- in other\n    words, we assume [v] is closed.  This assumption considerably\n    simplifies the [T_Abs] case of the proof (compared to assuming\n    [Gamma |- v \\in U], which would be the other reasonable assumption\n    at this point) because the context invariance lemma then tells us\n    that [v] has type [U] in any context at all -- we don't have to\n    worry about free variables in [v] clashing with the variable being\n    introduced into the context by [T_Abs].\n\n    The substitution lemma can be viewed as a kind of \"commutation\"\n    property.  Intuitively, it says that substitution and typing can\n    be done in either order: we can either assign types to the terms\n    [t] and [v] separately (under suitable contexts) and then combine\n    them using substitution, or we can substitute first and then\n    assign a type to [ [x:=v] t ] -- the result is the same either\n    way.\n\n    _Proof_: We show, by induction on [t], that for all [T] and\n    [Gamma], if [Gamma,x:U |- t \\in T] and [|- v \\in U], then [Gamma\n    |- [x:=v]t \\in T].\n\n      - If [t] is a variable there are two cases to consider,\n        depending on whether [t] is [x] or some other variable.\n\n          - If [t = x], then from the fact that [Gamma, x:U |- x \\in\n            T] we conclude that [U = T].  We must show that [[x:=v]x =\n            v] has type [T] under [Gamma], given the assumption that\n            [v] has type [U = T] under the empty context.  This\n            follows from context invariance: if a closed term has type\n            [T] in the empty context, it has that type in any context.\n\n          - If [t] is some variable [y] that is not equal to [x], then\n            we need only note that [y] has the same type under [Gamma,\n            x:U] as under [Gamma].\n\n      - If [t] is an abstraction [\\y:T11. t12], then the IH tells us,\n        for all [Gamma'] and [T'], that if [Gamma',x:U |- t12 \\in T']\n        and [|- v \\in U], then [Gamma' |- [x:=v]t12 \\in T'].\n\n        The substitution in the conclusion behaves differently\n        depending on whether [x] and [y] are the same variable.\n\n        First, suppose [x = y].  Then, by the definition of\n        substitution, [[x:=v]t = t], so we just need to show [Gamma |-\n        t \\in T].  But we know [Gamma,x:U |- t : T], and, since [y]\n        does not appear free in [\\y:T11. t12], the context invariance\n        lemma yields [Gamma |- t \\in T].\n\n        Second, suppose [x <> y].  We know [Gamma,x:U,y:T11 |- t12 \\in\n        T12] by inversion of the typing relation, from which\n        [Gamma,y:T11,x:U |- t12 \\in T12] follows by the context\n        invariance lemma, so the IH applies, giving us [Gamma,y:T11 |-\n        [x:=v]t12 \\in T12].  By [T_Abs], [Gamma |- \\y:T11. [x:=v]t12\n        \\in T11->T12], and by the definition of substitution (noting\n        that [x <> y]), [Gamma |- \\y:T11. [x:=v]t12 \\in T11->T12] as\n        required.\n\n      - If [t] is an application [t1 t2], the result follows\n        straightforwardly from the definition of substitution and the\n        induction hypotheses.\n\n      - The remaining cases are similar to the application case.\n\n    One more technical note: This proof is a rare case where an\n    induction on terms, rather than typing derivations, yields a\n    simpler argument.  The reason for this is that the assumption\n    [update Gamma x U |- t \\in T] is not completely generic, in the\n    sense that one of the \"slots\" in the typing relation -- namely the\n    context -- is not just a variable, and this means that Coq's\n    native induction tactic does not give us the induction hypothesis\n    that we want.  It is possible to work around this, but the needed\n    generalization is a little tricky.  The term [t], on the other\n    hand, _is_ completely generic. *)\n\nProof with eauto.\n  intros Gamma x U t v T Ht Ht'.\n  generalize dependent Gamma. generalize dependent T.\n  induction t; intros T Gamma H;\n    (* in each case, we'll want to get at the derivation of H *)\n    inversion H; subst; simpl...\n  - (* tvar *)\n    rename i into y. destruct (beq_idP x y) as [Hxy|Hxy].\n    + (* x=y *)\n      subst.\n      rewrite update_eq in H2.\n      inversion H2; subst. clear H2.\n                  eapply context_invariance... intros x Hcontra.\n      destruct (free_in_context _ _ T empty Hcontra) as [T' HT']...\n      inversion HT'.\n    + (* x<>y *)\n      apply T_Var. rewrite update_neq in H2...\n  - (* tabs *)\n    rename i into y. apply T_Abs.\n    destruct (beq_idP x y) as [Hxy | Hxy].\n    + (* x=y *)\n      subst.\n      eapply context_invariance...\n      intros x Hafi. unfold update, t_update.\n      destruct (beq_id y x) eqn: Hyx...\n    + (* x<>y *)\n      apply IHt. eapply context_invariance...\n      intros z Hafi. unfold update, t_update.\n      destruct (beq_idP y z) as [Hyz | Hyz]; subst; trivial.\n      rewrite <- beq_id_false_iff in Hxy.\n      rewrite Hxy...\nQed.\n\n(* ================================================================= *)\n(** ** Main Theorem *)\n\n(** We now have the tools we need to prove preservation: if a closed\n    term [t] has type [T] and takes a step to [t'], then [t']\n    is also a closed term with type [T].  In other words, the small-step\n    reduction relation preserves types. *)\n\nTheorem preservation : forall t t' T,\n     empty |- t \\in T  ->\n     t ==> t'  ->\n     empty |- t' \\in T.\n\n(** _Proof_: By induction on the derivation of [|- t \\in T].\n\n    - We can immediately rule out [T_Var], [T_Abs], [T_True], and\n      [T_False] as the final rules in the derivation, since in each of\n      these cases [t] cannot take a step.\n\n    - If the last rule in the derivation was [T_App], then [t = t1\n      t2].  There are three cases to consider, one for each rule that\n      could have been used to show that [t1 t2] takes a step to [t'].\n\n        - If [t1 t2] takes a step by [ST_App1], with [t1] stepping to\n          [t1'], then by the IH [t1'] has the same type as [t1], and\n          hence [t1' t2] has the same type as [t1 t2].\n\n        - The [ST_App2] case is similar.\n\n        - If [t1 t2] takes a step by [ST_AppAbs], then [t1 =\n          \\x:T11.t12] and [t1 t2] steps to [[x:=t2]t12]; the\n          desired result now follows from the fact that substitution\n          preserves types.\n\n    - If the last rule in the derivation was [T_If], then [t = if t1\n      then t2 else t3], and there are again three cases depending on\n      how [t] steps.\n\n        - If [t] steps to [t2] or [t3], the result is immediate, since\n          [t2] and [t3] have the same type as [t].\n\n        - Otherwise, [t] steps by [ST_If], and the desired conclusion\n          follows directly from the induction hypothesis. *)\n\nProof with eauto.\n  remember (@empty ty) as Gamma.\n  intros t t' T HT. generalize dependent t'.\n  induction HT;\n       intros t' HE; subst Gamma; subst;\n       try solve [inversion HE; subst; auto].\n  - (* T_App *)\n    inversion HE; subst...\n    (* Most of the cases are immediate by induction,\n       and [eauto] takes care of them *)\n    + (* ST_AppAbs *)\n      apply substitution_preserves_typing with T11...\n      inversion HT1...\nQed.\n\n(** **** Exercise: 2 stars, recommended (subject_expansion_stlc)  *)\n(** An exercise in the [Types] chapter asked about the subject\n    expansion property for the simple language of arithmetic and\n    boolean expressions.  Does this property hold for STLC?  That is,\n    is it always the case that, if [t ==> t'] and [has_type t' T],\n    then [empty |- t \\in T]?  If so, prove it.  If not, give a\n    counter-example not involving conditionals.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(* ################################################################# *)\n(** * Type Soundness *)\n\n(** **** Exercise: 2 stars, optional (type_soundness)  *)\n(** Put progress and preservation together and show that a well-typed\n    term can _never_ reach a stuck state.  *)\n\nDefinition stuck (t:tm) : Prop :=\n  (normal_form step) t /\\ ~ value t.\n\nCorollary soundness : forall t t' T,\n  empty |- t \\in T ->\n  t ==>* t' ->\n  ~(stuck t').\nProof.\n  intros t t' T Hhas_type Hmulti. unfold stuck.\n  intros [Hnf Hnot_val]. unfold normal_form in Hnf.\n  induction Hmulti.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Uniqueness of Types *)\n\n(** **** Exercise: 3 stars (types_unique)  *)\n(** Another nice property of the STLC is that types are unique: a\n    given term (in a given context) has at most one type. *)\n(** Formalize this statement and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 1 star (progress_preservation_statement)  *)\n(** Without peeking at their statements above, write down the progress\n    and preservation theorems for the simply typed lambda-calculus. *)\n(** [] *)\n\n(** **** Exercise: 2 stars (stlc_variation1)  *)\n(** Suppose we add a new term [zap] with the following reduction rule\n\n                         ---------                  (ST_Zap)\n                         t ==> zap\n\nand the following typing rule:\n\n                      ----------------               (T_Zap)\n                      Gamma |- zap : T\n\n    Which of the following properties of the STLC remain true in\n    the presence of these rules?  For each property, write either\n    \"remains true\" or \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n[]\n*)\n\n(** **** Exercise: 2 stars (stlc_variation2)  *)\n(** Suppose instead that we add a new term [foo] with the following \n    reduction rules:\n\n                       -----------------                (ST_Foo1)\n                       (\\x:A. x) ==> foo\n\n                         ------------                   (ST_Foo2)\n                         foo ==> true\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n[]\n*)\n\n(** **** Exercise: 2 stars (stlc_variation3)  *)\n(** Suppose instead that we remove the rule [ST_App1] from the [step]\n    relation. Which of the following properties of the STLC remain\n    true in the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation4)  *)\n(** Suppose instead that we add the following new rule to the \n    reduction relation:\n\n            ----------------------------------        (ST_FunnyIfTrue)\n            (if true then t1 else t2) ==> true\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation5)  *)\n(** Suppose instead that we add the following new rule to the typing \n    relation:\n\n                 Gamma |- t1 \\in Bool->Bool->Bool\n                     Gamma |- t2 \\in Bool\n                 ------------------------------          (T_FunnyApp)\n                    Gamma |- t1 t2 \\in Bool\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation6)  *)\n(** Suppose instead that we add the following new rule to the typing \n    relation:\n\n                     Gamma |- t1 \\in Bool\n                     Gamma |- t2 \\in Bool\n                    ---------------------               (T_FunnyApp')\n                    Gamma |- t1 t2 \\in Bool\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation7)  *)\n(** Suppose we add the following new rule to the typing relation \n    of the STLC:\n\n                         ------------------- (T_FunnyAbs)\n                         |- \\x:Bool.t \\in Bool\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n[]\n*)\n\nEnd STLCProp.\n\n(* ================================================================= *)\n(** ** Exercise: STLC with Arithmetic *)\n\n(** To see how the STLC might function as the core of a real\n    programming language, let's extend it with a concrete base\n    type of numbers and some constants and primitive\n    operators. *)\n\nModule STLCArith.\n\n(** To types, we add a base type of natural numbers (and remove\n    booleans, for brevity). *)\n\nInductive ty : Type :=\n  | TArrow : ty -> ty -> ty\n  | TNat   : ty.\n\n(** To terms, we add natural number constants, along with\n    successor, predecessor, multiplication, and zero-testing. *)\n\nInductive tm : Type :=\n  | tvar : id -> tm\n  | tapp : tm -> tm -> tm\n  | tabs : id -> ty -> tm -> tm\n  | tnat  : nat -> tm\n  | tsucc : tm -> tm\n  | tpred : tm -> tm\n  | tmult : tm -> tm -> tm\n  | tif0  : tm -> tm -> tm -> tm.\n\n(** **** Exercise: 4 stars (stlc_arith)  *)\n(** Finish formalizing the definition and properties of the STLC extended\n    with arithmetic.  Specifically:\n\n    - Copy the whole development of STLC that we went through above (from\n      the definition of values through the Type Soundness theorem), and\n      paste it into the file at this point.\n\n    - Extend the definitions of the [subst] operation and the [step]\n      relation to include appropriate clauses for the arithmetic operators.\n\n    - Extend the proofs of all the properties (up to [soundness]) of\n      the original STLC to deal with the new syntactic forms.  Make\n      sure Coq accepts the whole file. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd STLCArith.\n\n(** $Date: 2016-07-13 12:41:41 -0400 (Wed, 13 Jul 2016) $ *)\n\n", "meta": {"author": "coqoon", "repo": "Software-Foundations", "sha": "a327b63aa8ff8543ae2cedee7a5960da05bbfaa7", "save_path": "github-repos/coq/coqoon-Software-Foundations", "path": "github-repos/coq/coqoon-Software-Foundations/Software-Foundations-a327b63aa8ff8543ae2cedee7a5960da05bbfaa7/Software Foundations/src/SF/StlcProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.679837499968024}}
{"text": "From Test Require Import tactic.\n\nSection FOFProblem.\n\nVariable Universe : Set.\nVariable UniverseElement : Universe.\n\nVariable par_ : Universe -> Universe -> Universe -> Universe -> Prop.\nVariable pG_ : Universe -> Universe -> Universe -> Universe -> Prop.\nVariable eF_ : Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Prop.\nVariable cong_3_ : Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Prop.\nVariable congA_ : Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Prop.\nVariable cong_ : Universe -> Universe -> Universe -> Universe -> Prop.\nVariable col_ : Universe -> Universe -> Universe -> Prop.\nVariable cR_ : Universe -> Universe -> Universe -> Universe -> Prop.\nVariable betS_ : Universe -> Universe -> Universe -> Prop.\n\n\nVariable defparallelogram_1 : (forall A B C D : Universe, (pG_ A B C D -> (par_ A B C D /\\ par_ A D B C))).\nVariable defparallelogram2_2 : (forall A B C D : Universe, ((par_ A B C D /\\ par_ A D B C) -> pG_ A B C D)).\nVariable lemma_parallelNC_3 : (forall A B C D : Universe, (par_ A B C D -> (~(col_ A B C) /\\ (~(col_ A C D) /\\ (~(col_ B C D) /\\ ~(col_ A B D)))))).\nVariable lemma_NCdistinct_4 : (forall A B C : Universe, (~(col_ A B C) -> (A <> B /\\ (B <> C /\\ (A <> C /\\ (B <> A /\\ (C <> B /\\ C <> A))))))).\nVariable proposition_34_5 : (forall A B C D : Universe, (pG_ A C D B -> (cong_ A B C D /\\ (cong_ A C B D /\\ (congA_ C A B B D C /\\ (congA_ A B D D C A /\\ cong_3_ C A B B D C)))))).\nVariable lemma_congruencesymmetric_6 : (forall A B C D : Universe, (cong_ B C A D -> cong_ A D B C)).\nVariable lemma_congruencetransitive_7 : (forall A B C D E F : Universe, ((cong_ A B C D /\\ cong_ C D E F) -> cong_ A B E F)).\nVariable lemma_parallelsymmetric_8 : (forall A B C D : Universe, (par_ A B C D -> par_ C D A B)).\nVariable lemma_collinearparallel2_9 : (forall A B C D E F : Universe, ((par_ A B C D /\\ (col_ C D E /\\ (col_ C D F /\\ E <> F))) -> par_ A B E F)).\nVariable lemma_crisscross_10 : (forall A B C D : Universe, ((par_ A C B D /\\ ~(cR_ A B C D)) -> cR_ A D B C)).\nVariable defcross_11 : (forall A B C D : Universe, (exists X : Universe, (cR_ A B C D -> (betS_ A X B /\\ betS_ C X D)))).\nVariable defcross2_12 : (forall A B C D X : Universe, ((betS_ A X B /\\ betS_ C X D) -> cR_ A B C D)).\nVariable axiom_betweennesssymmetry_13 : (forall A B C : Universe, (betS_ A B C -> betS_ C B A)).\nVariable proposition_33_14 : (forall A B C D M : Universe, ((par_ A B C D /\\ (cong_ A B C D /\\ (betS_ A M D /\\ betS_ B M C))) -> (par_ A C B D /\\ cong_ A C B D))).\nVariable lemma_parallelflip_15 : (forall A B C D : Universe, (par_ A B C D -> (par_ B A C D /\\ (par_ A B D C /\\ par_ B A D C)))).\nVariable proposition_35_16 : (forall A B C D E F : Universe, ((pG_ A B C D /\\ (pG_ E B C F /\\ (col_ A D E /\\ col_ A D F))) -> eF_ A B C D E B C F)).\nVariable lemma_collinear4_17 : (forall A B C D : Universe, ((col_ A B C /\\ (col_ A B D /\\ A <> B)) -> col_ B C D)).\nVariable lemma_collinearorder_18 : (forall A B C : Universe, (col_ A B C -> (col_ B A C /\\ (col_ B C A /\\ (col_ C A B /\\ (col_ A C B /\\ col_ C B A)))))).\nVariable lemma_inequalitysymmetric_19 : (forall A B : Universe, (A <> B -> B <> A)).\nVariable axiom_EFpermutation_20 : (forall A B C D Ca Cb Cc Cd : Universe, (eF_ A B C D Ca Cb Cc Cd -> (eF_ A B C D Cb Cc Cd Ca /\\ (eF_ A B C D Cd Cc Cb Ca /\\ (eF_ A B C D Cc Cd Ca Cb /\\ (eF_ A B C D Cb Ca Cd Cc /\\ (eF_ A B C D Cd Ca Cb Cc /\\ (eF_ A B C D Cc Cb Ca Cd /\\ eF_ A B C D Ca Cd Cc Cb)))))))).\nVariable axiom_EFsymmetric_21 : (forall A B C D Ca Cb Cc Cd : Universe, (eF_ A B C D Ca Cb Cc Cd -> eF_ Ca Cb Cc Cd A B C D)).\nVariable axiom_EFtransitive_22 : (forall A B C D P Q R S Ca Cb Cc Cd : Universe, ((eF_ A B C D Ca Cb Cc Cd /\\ eF_ Ca Cb Cc Cd P Q R S) -> eF_ A B C D P Q R S)).\nVariable lemma_congruenceflip_23 : (forall A B C D : Universe, (cong_ A B C D -> (cong_ B A D C /\\ (cong_ B A C D /\\ cong_ A B D C)))).\n\nTheorem proposition_36_24 : (forall A B C D E F G H : Universe, ((pG_ A B C D /\\ (pG_ E F G H /\\ (col_ A D E /\\ (col_ A D H /\\ (col_ B C F /\\ (col_ B C G /\\ cong_ B C F G)))))) -> eF_ A B C D E F G H)).\nProof.\n  time tac.\nQed.\n\nEnd FOFProblem.\n", "meta": {"author": "janicicpredrag", "repo": "Larus", "sha": "a095ca588fbb0e4a64a26d92946485bbf85e1e08", "save_path": "github-repos/coq/janicicpredrag-Larus", "path": "github-repos/coq/janicicpredrag-Larus/Larus-a095ca588fbb0e4a64a26d92946485bbf85e1e08/benchmarks/coq-problems/euclid/proposition_36.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6798374955530639}}
{"text": "(** Examples.Add : A Von Neumann adder.  *)\nRequire Import Common Core Front ZArith. \n\nFixpoint pow2 k := (match k with O => 1 | S p => pow2 p + pow2 p end)%nat.\n\nNotation \"[2^ n ]\" := (pow2 n). \n\n(** A divide and conquer adder (Von Neumann)  *)\nSection s. \n  \n  Variable V : type -> Type. \n  Open Scope Z_scope.  \n  Fixpoint add {Phi} n (x : expr V (Tint [2^ n])) (y : expr V (Tint [2^ n])) \n    :        action Phi V (Ttuple [Tbool; Tbool; Tint [2^ n]; Tint [2^ n]]) := \n    match n \n       return \n       expr V (Tint [2^ n]) -> \n       expr V (Tint [2^ n]) ->  \n       action Phi V (Ttuple [Tbool; Tbool; Tint [2^ n]; Tint [2^ n]])\n    with \n      | 0%nat => fun x y => \n                ret [tuple ((x = #i 1) || (y = #i 1)), (* propagate *)\n                     ((x = #i 1) && (y = #i 1)),       (* generate *)\n                     x + y,                            (* s *)\n                     x + y + #i 1 ]%expr               (* t *)\n      | S n => fun x y => \n                (\n                  do xL <~ low  x;\n                  do xH <~ high x; \n                  do yL <~ low  y; \n                  do yH <~ high y; \n                  do rL <- add n xL yL; \n                  do rH <- add n xH yH; \n                  do (pL, gL, sL, tL) <~ rL;\n                  do (pH, gH, sH, tH) <~ rH;\n                  do sH' <~ (Emux (gL) (tH) (sH))%expr;\n                  do tH' <~ (Emux (pL) (tH) (sH))%expr;\n                  do pH' <~ (gH || (pH && pL))%expr;\n                  do gH' <~ (gH || (pH && gL))%expr;\n                  ret [tuple pH', \n                       gH', \n                       combineLH sL sH', \n                       combineLH tL tH']\n                )                                     \n          end%expr%action x y.  \nEnd s. \n\nArguments Front.Close {Var} Phi {T U} c.\n\nDefinition generator n : Action ([Tinput (Tint [2^n]); Tinput (Tint [2^n])]%list) (Ttuple [ B; B; Int [2^n]; Int [2^n]])%list. \n  intros V. \n  apply (Front.Close ([Tinput (Tint [2^n])]%list)). \n  intros x.\n  apply (Front.Close ([]%list)).\n  intros y. \n  apply (add _ _ (Evar x) (Evar y)) . \nDefined.\n  ", "meta": {"author": "braibant", "repo": "Synthesis", "sha": "922982aaddb8a7a16101ff304c45d24a6265dc2e", "save_path": "github-repos/coq/braibant-Synthesis", "path": "github-repos/coq/braibant-Synthesis/Synthesis-922982aaddb8a7a16101ff304c45d24a6265dc2e/examples/Add.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6798234386418954}}
{"text": "From Test Require Import tactic.\n\nSection FOFProblem.\n\nVariable Universe : Set.\nVariable UniverseElement : Universe.\n\nVariable per_ : Universe -> Universe -> Universe -> Prop.\nVariable out_ : Universe -> Universe -> Universe -> Prop.\nVariable lt_ : Universe -> Universe -> Universe -> Universe -> Prop.\nVariable cong_ : Universe -> Universe -> Universe -> Universe -> Prop.\nVariable col_ : Universe -> Universe -> Universe -> Prop.\nVariable betS_ : Universe -> Universe -> Universe -> Prop.\n\n\nVariable lemma_rightangleNC_1 : (forall A B C : Universe, (per_ A B C -> ~(col_ A B C))).\nVariable lemma_NCdistinct_2 : (forall A B C : Universe, (~(col_ A B C) -> (A <> B /\\ (B <> C /\\ (A <> C /\\ (B <> A /\\ (C <> B /\\ C <> A))))))).\nVariable lemma_collinearorder_3 : (forall A B C : Universe, (col_ A B C -> (col_ B A C /\\ (col_ B C A /\\ (col_ C A B /\\ (col_ A C B /\\ col_ C B A)))))).\nVariable lemma_8_2_4 : (forall A B C : Universe, (per_ A B C -> per_ C B A)).\nVariable lemma_collinearright_5 : (forall A B C D : Universe, ((per_ A B D /\\ (col_ A B C /\\ C <> B)) -> per_ C B D)).\nVariable lemma_8_7_6 : (forall A B C : Universe, (per_ C B A -> ~(per_ A C B))).\nVariable lemma_collinear4_7 : (forall A B C D : Universe, ((col_ A B C /\\ (col_ A B D /\\ A <> B)) -> col_ B C D)).\nVariable lemma_inequalitysymmetric_8 : (forall A B : Universe, (A <> B -> B <> A)).\nVariable lemma_legsmallerhypotenuse_9 : (forall A B C : Universe, (per_ A B C -> (lt_ A B A C /\\ lt_ B C A C))).\nVariable cn_equalityreverse_10 : (forall A B : Universe, cong_ A B B A).\nVariable lemma_lessthancongruence2_11 : (forall A B C D E F : Universe, ((lt_ A B C D /\\ cong_ A B E F) -> lt_ E F C D)).\nVariable lemma_lessthantransitive_12 : (forall A B C D E F : Universe, ((lt_ A B C D /\\ lt_ C D E F) -> lt_ A B E F)).\nVariable axiom_betweennesssymmetry_13 : (forall A B C : Universe, (betS_ A B C -> betS_ C B A)).\nVariable cn_congruencereflexive_14 : (forall A B : Universe, cong_ A B A B).\nVariable deflessthan_15 : (forall A B C D : Universe, (exists X : Universe, (lt_ A B C D -> (betS_ C X D /\\ cong_ C X A B)))).\nVariable deflessthan2_16 : (forall A B C D X : Universe, ((betS_ C X D /\\ cong_ C X A B) -> lt_ A B C D)).\nVariable lemma_trichotomy2_17 : (forall A B C D : Universe, (lt_ A B C D -> ~(lt_ C D A B))).\nVariable defcollinear_18 : (forall A B C : Universe, (col_ A B C -> (A = B \\/ (A = C \\/ (B = C \\/ (betS_ B A C \\/ (betS_ A B C \\/ betS_ A C B))))))).\nVariable defcollinear2a_19 : (forall A B C : Universe, (A = B -> col_ A B C)).\nVariable defcollinear2b_20 : (forall A B C : Universe, (A = C -> col_ A B C)).\nVariable defcollinear2c_21 : (forall A B C : Universe, (B = C -> col_ A B C)).\nVariable defcollinear2d_22 : (forall A B C : Universe, (betS_ B A C -> col_ A B C)).\nVariable defcollinear2e_23 : (forall A B C : Universe, (betS_ A B C -> col_ A B C)).\nVariable defcollinear2f_24 : (forall A B C : Universe, (betS_ A C B -> col_ A B C)).\nVariable lemma_ray4_1_25 : (forall A B E : Universe, ((betS_ A E B /\\ A <> B) -> out_ A B E)).\nVariable lemma_ray4_2_26 : (forall A B E : Universe, ((E = B /\\ A <> B) -> out_ A B E)).\nVariable lemma_ray4_3_27 : (forall A B E : Universe, ((betS_ A B E /\\ A <> B) -> out_ A B E)).\nVariable lemma_ray5_28 : (forall A B C : Universe, (out_ A B C -> out_ A C B)).\nVariable lemma_tworays_29 : (forall A B C : Universe, ((out_ A B C /\\ out_ B A C) -> betS_ A C B)).\n\nTheorem lemma_altitudeofrighttriangle_30 : (forall A B C M Xp : Universe, ((per_ B A C /\\ (per_ A M Xp /\\ (col_ B C Xp /\\ col_ B C M))) -> betS_ B M C)).\nProof.\n  time tac.\nQed.\n\nEnd FOFProblem.\n", "meta": {"author": "janicicpredrag", "repo": "Larus", "sha": "a095ca588fbb0e4a64a26d92946485bbf85e1e08", "save_path": "github-repos/coq/janicicpredrag-Larus", "path": "github-repos/coq/janicicpredrag-Larus/Larus-a095ca588fbb0e4a64a26d92946485bbf85e1e08/benchmarks/coq-problems/euclid/lemma_altitudeofrighttriangle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6798234266955971}}
{"text": "Require Import Coq.Classes.RelationClasses.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Relations.Relation_Operators.\nRequire Import Coq.Setoids.Setoid.\nRequire Import DschingisKhan.Prelude.PreludeInit.\nRequire Import DschingisKhan.Prelude.PreludeMath.\nRequire Import DschingisKhan.Math.BasicPosetTheory.\n\nModule BasicGeneralTopology.\n\n  Import MathProps MathClasses BasicPosetTheory.\n\n  Create HintDb topology_hints.\n\n  Class Topology_axiom {A : Type} (isOpen : ensemble A -> Prop) : Prop :=\n    { full_isOpen\n      : isOpen full\n    ; unions_isOpen (Xs : ensemble (ensemble A))\n      (every_member_of_Xs_isOpen : forall X : ensemble A, << X_in_Xs : member X Xs >> -> isOpen X)\n      : isOpen (unions Xs)\n    ; intersection_isOpen (XL : ensemble A) (XR : ensemble A)\n      (XL_isOpen : isOpen XL)\n      (XR_isOpen : isOpen XR)\n      : isOpen (intersection XL XR)\n    ; isOpen_compatWith_eqProp (X : ensemble A) (X' : ensemble A)\n      (X_isOpen : isOpen X)\n      (X_eq_X' : X == X')\n      : isOpen X'\n    }\n  .\n\n  Class isTopologicalSpace (A : Type) : Type :=\n    { isOpen (O : ensemble A) : Prop\n    ; TopologicalSpace_obeysTopology_axiom :> Topology_axiom isOpen\n    }\n  .\n\n  Global Add Parametric Morphism {A : Type} (requiresTopology : isTopologicalSpace A) :\n    (isOpen (isTopologicalSpace := requiresTopology)) with signature (eqProp ==> iff)\n    as eqProp_lifts_isOpen.\n  Proof. iis; ii; eapply isOpen_compatWith_eqProp; eauto with *. Qed.\n\n  Lemma fullOpen {A : Type} {requiresTopology : isTopologicalSpace A}\n    : isOpen (@full A).\n  Proof. eapply full_isOpen; eauto. Qed.\n\n  Lemma unionsOpen {A : Type} {requiresTopology : isTopologicalSpace A} (Os : ensemble (ensemble A))\n    (every_member_of_Os_isOpen : forall O : ensemble A, member O Os -> isOpen O)\n    : isOpen (@unions A Os).\n  Proof. eapply unions_isOpen; eauto. Qed.\n\n  Lemma intersectionOpen {A : Type} {requiresTopology : isTopologicalSpace A} (O1 : ensemble A) (O2 : ensemble A)\n    (O1_isOpen : isOpen O1)\n    (O2_isOpen : isOpen O2)\n    : isOpen (@intersection A O1 O2).\n  Proof. eapply intersection_isOpen; eauto. Qed.\n\n  Lemma emptyOpen {A : Type} {requiresTopology : isTopologicalSpace A}\n    : isOpen (@empty A).\n  Proof.\n    eapply isOpen_compatWith_eqProp.\n    - eapply unions_isOpen with (Xs := empty). ii; desnw.\n      apply in_empty_iff in X_in_Xs. tauto.\n    - intros z. rewrite in_unions_iff. split.\n      + intros [X [z_in_X []]].\n      + intros [].\n  Qed.\n\n  Global Hint Resolve fullOpen unionsOpen intersectionOpen emptyOpen : topology_hints.\n\n  Definition isContinuousMap {dom : Type} {cod : Type} {dom_isTopology : isTopologicalSpace dom} {cod_isTopology : isTopologicalSpace cod} (f : dom -> cod) : Prop :=\n    forall Y : ensemble cod, << TGT_OPEN : isOpen Y >> -> << SRC_OPEN : isOpen (preimage f Y) >>\n  .\n\n  Section SUBTOPOLOGY.\n\n  Context {A : Type} (phi : A -> Prop).\n\n  Let Subspace : Type := @sig A phi.\n\n  Context {requiresTopology : isTopologicalSpace A}.\n\n  Definition isOpen_inSubspace (O_repr : ensemble Subspace) : Prop :=\n    exists O : ensemble A, isFilterReprOf phi O_repr O /\\ isOpen O\n  .\n\n  Local Hint Unfold isOpen_inSubspace : core.\n\n  Global Instance Subtopology\n    : Topology_axiom isOpen_inSubspace.\n  Proof with (now vm_compute in *; firstorder) || (eauto with *).\n    split.\n    - exists (full). split...\n    - ii. exists (unions (bind Xs (fun O_repr : ensemble Subspace => fun O : ensemble A => isFilterReprOf phi O_repr O /\\ isOpen O))). split... eapply unions_isOpen...\n    - intros X1 X2 [O1 [O1_repr O1_open]] [O2 [O2_repr O2_open]]. exists (intersection O1 O2). split...\n    - intros X X' [O [O_repr O_open]] X_eq_X'...\n  Qed.\n\n  End SUBTOPOLOGY.\n\n  Local Instance SubspaceTopology {A : Type} {requiresTopology : isTopologicalSpace A} (phi : A -> Prop) : isTopologicalSpace (@sig A phi) :=\n    { isOpen := @isOpen_inSubspace A phi requiresTopology\n    ; TopologicalSpace_obeysTopology_axiom := @Subtopology A phi requiresTopology\n    }\n  .\n\n  Lemma proj1_sig_isContinuousMap_fromSubspaceTopology {A : Type} {requiresTopology : isTopologicalSpace A} (X : ensemble A)\n    : isContinuousMap (dom := @sig A X) (cod := A) (@proj1_sig A X).\n  Proof with eauto with *. ii; desnw; unnw. exists (Y). split... eapply isFilterReprOf_iff... Qed.\n\nEnd BasicGeneralTopology.\n", "meta": {"author": "KiJeong-Lim", "repo": "DschingisKhan", "sha": "b2d663f5c705f9732d44adc2faf49709b6ddec07", "save_path": "github-repos/coq/KiJeong-Lim-DschingisKhan", "path": "github-repos/coq/KiJeong-Lim-DschingisKhan/DschingisKhan-b2d663f5c705f9732d44adc2faf49709b6ddec07/theories/Math/BasicGeneralTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.754914975839675, "lm_q1q2_score": 0.6798234136689043}}
{"text": "Require Import Nat.\nRequire Import PeanoNat.\n\nLtac inv H := inversion H; subst; clear H.\n(* destruct a match in a hypothesis *)\nLtac dmh := match goal with | H : context[match ?x with | _ => _ end] |- _ => destruct x eqn:?E end.\n(* destruct a match in the goal *)\nLtac dmg := match goal with | |- context[match ?x with | _ => _ end] => destruct x eqn:?E end.\nLtac dm := (first [dmh | dmg]); auto.\n\nLemma false_not_true : forall(b : bool),\n    b = false <-> not(b = true).\nProof.\n  intros b. split.\n  - intros H. destruct b.\n    + discriminate.\n    + unfold not. intros C. discriminate.\n  - intros H. destruct b.\n    + contradiction.\n    + reflexivity.\nQed.\n\nLtac inj_all :=\n  match goal with\n  | H:context [ (_, _) = (_, _) ] |- _\n    => injection H; intros; subst; clear H\n  | H:context [ Some _ = Some _ ] |- _\n    => injection H; intros; subst; clear H\n  end.\n\nLtac eqb_eq_all :=\n  match goal with\n  | H:context [ (_ =? _) = _ ] |- _ => try(rewrite false_not_true in H); rewrite Nat.eqb_eq in H\n  end.\n\nLtac ltb_lt_all :=\n  match goal with\n  | H:context [ (_ <? _) = _ ] |- _ => try(rewrite false_not_true in H); rewrite Nat.ltb_lt in H\n  end.\n", "meta": {"author": "egolf-cs", "repo": "vlg", "sha": "84f22921f9671cac506bef1b4887d73ecc74436d", "save_path": "github-repos/coq/egolf-cs-vlg", "path": "github-repos/coq/egolf-cs-vlg/vlg-84f22921f9671cac506bef1b4887d73ecc74436d/aux/ltac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.6797374733785767}}
{"text": "(* Code for Software Foundations, Chapter 6: Tactics: More Basic Tactics *)\n\nRequire Import Arith.\nRequire Import List.\nRequire Import Poly.\n\n(* silly_ex *)\n\nTheorem silly_ex :\n  (forall n, Nat.even n = true -> Nat.odd (S n) = true) -> Nat.even 3 = true -> Nat.odd 4 = true.\nProof.\n  intros h1 h2.\n  apply h1.\n  apply h2.\nQed.\n\n(* apply_exercise1 *)\n\nTheorem rev_exercise1 :\n  forall l l' : list nat, l = rev l' -> l' = rev l.\nProof.\n  intros l l'.\n  (* Theorem rev_involutive :\n    forall (X : Type) (l : list X), rev (rev l) = l. *)\n  pattern l.\n  rewrite <- rev_involutive.\n  intros h1.\n  rewrite h1.\n  rewrite rev_involutive.\n  reflexivity.\nQed.\n\n(* apply_rewrite *)\n\n(* The difference between \"rewrite\" and \"apply\":\n  + apply: match current goal with argument's inclusion, generate new\n    subgoals from it's hypotheses.\n  + rewrite: rewrite from equation. *)\n\n(* apply_with_exercise *)\n\nDefinition minus_two (n : nat) : nat :=\n  match n with\n    | O        => O\n    | S O      => O\n    | S (S n') => n'\n  end.\n\nTheorem trans_eq_exercise :\n  forall n m o p, m = minus_two o -> n + p = m -> n + p = minus_two o.\nProof.\n  intros n m o p h1 h2.\n  rewrite h2.\n  rewrite h1.\n  reflexivity.\nQed.\n\n(* inversion_exercise *)\n\nTheorem inversion_ex1 :\n  forall n m o : nat, n::m::nil = o::o::nil -> n::nil = m::nil.\nProof.\n  intros n m o.\n  inversion 1; reflexivity.\nQed.\n\nTheorem inversion_ex2 :\n  forall n m : nat, n::nil = m::nil -> n = m.\nProof.\n  intros n m.\n  inversion 1; reflexivity.\nQed.\n\nTheorem inversion_ex3 :\n  forall (X : Type) (x y z : X) (l j : list X), x :: y :: l = z :: j -> y :: l = x :: j -> x = y.\nProof.\n  intros X x y z l j.\n  inversion 1.\n  inversion 1.\n  reflexivity.\nQed.\n\nTheorem inversion_ex4 :\n  forall n : nat, S n = O -> 2 + 2 = 5.\nProof.\n  intros n.\n  inversion 1.\nQed.\n\nTheorem inversion_ex5 :\n  forall n m : nat, false = true -> n::nil = m::nil.\nProof.\n  intros n m.\n  inversion 1.\nQed.\n\nTheorem inversion_ex6 :\n  forall (X : Type) (x y z : X) (l j : list X), x::y::l = nil -> y::l = z::j -> x = z.\nProof.\n  intros X x y z l j.\n  inversion 1.\nQed.\n\n(* plus_n_n_injective *)\n\nTheorem plus_n_n_injective :\n  forall n m : nat, n + n = m + m -> n = m.\nProof.\n  induction n, m.\n  + simpl; reflexivity.\n  + simpl; inversion 1.\n  + simpl; inversion 1.\n  + intros h1.\n    simpl in h1.\n    apply Nat.succ_inj in h1.\n    pattern (n + S n) in h1; rewrite plus_comm in h1.\n    pattern (m + S m) in h1; rewrite plus_comm in h1.\n    simpl in h1.\n    apply Nat.succ_inj in h1.\n    apply eq_S.\n    apply IHn.\n    assumption.\nQed.\n\n(* beq_nat_true *)\n\nTheorem beq_nat_true :\n  forall n m, beq_nat n m = true -> n = m.\nProof.\n  induction n.\n  + induction m.\n    - simpl; reflexivity.\n    - simpl; inversion 1.\n  + induction m.\n    - simpl; inversion 1.\n    - intros h1.\n      simpl in h1.\n      apply IHn in h1.\n      rewrite h1; reflexivity.\nQed.\n\n(* gen_dep_practice *)\n\nTheorem nth_error_after_last :\n  forall (n : nat) (X : Type) (l : list X), length l = n -> nth_error l n = None.\nProof.\n  intros n X l.\n  (* NOTE: PAY attention to the order of \"generalize dependent\" and \"induction\".\n    WHY?\n    If use \"generalize\" after \"induction\", the hypothesis can be proved under\n    base condition still keeps it was after \"induction\", before \"generalize\".\n    But in an opposite manner, the conclusion under base condition will contain\n    the term introduced by \"generalize\". *)\n  generalize dependent n.\n  induction l.\n  + intros n h1.\n    rewrite <- h1.\n    reflexivity.\n  + intros n h1.\n    simpl in h1.\n    rewrite <- h1.\n    simpl; apply IHl; reflexivity.\nQed.\n\n(* app_length_cons *)\n\nTheorem app_length_cons :\n  forall (X : Type) (l1 l2 : list X) (x : X) (n : nat),\n    length (l1 ++ (x :: l2)) = n -> S (length (l1 ++ l2)) = n.\nProof.\n  intros X l1 l2 x n.\n  induction l1.\n  + simpl.\n    intros; assumption.\n  + simpl.\n    intros h1.\n    assert (length_app_succ : length (l1 ++ x :: l2) = S (length (l1 ++ l2))).\n    - rewrite List.app_length.\n      simpl.\n      rewrite <- plus_n_Sm.\n      rewrite List.app_length.\n      reflexivity.\n    - rewrite <- h1.\n      rewrite length_app_succ.\n      reflexivity.\nQed.\n\n(* app_length_twice *)\n\nTheorem app_length_twice :\n  forall (X : Type) (n : nat) (l : list X), length l = n -> length (l ++ l) = n + n.\nProof.\n  intros X n l h1.\n  rewrite List.app_length.\n  repeat rewrite h1.\n  reflexivity.\nQed.\n\nLemma app_length :\n  forall (X : Type) (l1 l2 : list X), length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros X l1 l2.\n  induction l1.\n  - simpl; reflexivity.\n  - simpl; rewrite IHl1; reflexivity.\nQed.\n\n(* double induction *)\nTheorem double_induction :\n  forall (P : nat -> nat -> Prop),\n    P O O -> (\n      forall m, P m O -> P (S m) O) -> (\n        forall n, P O n -> P O (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.\n  induction m.\n  + induction n.\n    - apply h1.\n    - apply h3; apply IHn.\n  + induction n.\n    - apply h2; apply (IHm O).\n    - apply h4.\n      apply IHm.\nQed.\n\n(* combine_split *)\n\nTheorem combine_split :\n  forall X Y (l : list (X * Y)) l1 l2, split l = (l1, l2) -> combine l1 l2 = l.\nProof.\n  induction l as [|(x, y) l'].\n  + intros l1 l2 h1.\n    simpl in h1.\n    inversion h1.\n    simpl; reflexivity.\n  + simpl.\n    destruct (split l') as [xs ys]. (* The KEY step! *)\n    intros l1 l2 h1.\n    inversion h1.\n    simpl.\n    rewrite IHl'; reflexivity.\nQed.\n\n(* destruct_eqn_practice *)\n\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool), f (f (f b)) = f b.\nProof.\n  intros f b.\n\n  assert(case_h1 : f true = true -> f false = true -> f (f (f b)) = f b).\n  intros h1 h2.\n  case b.\n  repeat rewrite h1; reflexivity.\n  rewrite h2; repeat rewrite h1; reflexivity.\n\n  assert(case_h2 : f true = true -> f false = false -> f (f (f b)) = f b).\n  intros h1 h2.\n  case b.\n  repeat rewrite h1; reflexivity.\n  repeat rewrite h2; reflexivity.\n\n  assert(case_h3 : f true = false -> f false = true -> f (f (f b)) = f b).\n  intros h1 h2.\n  case b.\n  rewrite h1; rewrite h2; rewrite h1; reflexivity.\n  rewrite h2; rewrite h1; rewrite h2; reflexivity.\n\n  assert(case_h4 : f true = false -> f false = false -> f (f (f b)) = f b).\n  intros h1 h2.\n  case b.\n  rewrite h1; repeat rewrite h2; reflexivity.\n  repeat rewrite h2; reflexivity.\n\n  destruct (f true).\n  + destruct (f false).\n    - apply case_h1; reflexivity.\n    - apply case_h2; reflexivity.\n  + destruct (f false).\n    - apply case_h3; reflexivity.\n    - apply case_h4; reflexivity.\nQed.\n\n(* beq_nat_sym *)\n\nTheorem beq_nat_sym :\n  forall n m, beq_nat n m = beq_nat m n.\nProof.\n  induction n, m.\n  + reflexivity.\n  + reflexivity.\n  + reflexivity.\n  + simpl; apply IHn.\nQed.\n\n(* beq_nat_trans *)\n\nTheorem beq_nat_trans :\n  forall n m p, beq_nat n m = true -> beq_nat m p = true -> beq_nat n p = true.\nProof.\n  induction n, m, p; try (simpl; reflexivity).\n  + trivial.\n  + trivial.\n  + trivial.\n  + inversion 1.\n  + trivial.\n  + simpl; apply IHn.\nQed.\n\n(* split_combine *)\n\nTheorem split_combine :\n  forall (X : Type) (l1 l2 : list X), length l1 = length l2 -> split (combine l1 l2) = (l1, l2).\nProof.\n  induction l1, l2.\n  + simpl; reflexivity.\n  + simpl; inversion 1.\n  + simpl; inversion 1.\n  + simpl.\n    intros h1.\n    apply eq_add_S in h1.\n    rewrite IHl1.\n    - reflexivity.\n    - assumption.\nQed.\n\n(* filter_exercise *)\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  induction l.\n  + inversion 1.\n  + intros lf h1.\n    simpl in h1.\n    (* destruct term \"eqn:naming_intro_pattern\" *)\n    destruct (test a) as [] _eqn:h2.\n    - inversion h1 as [eq_a_x].\n      rewrite eq_a_x in h2.\n      assumption.\n    - apply (IHl lf); assumption.\nQed.\n\n(* forall_exists_challenge *)\n\nFixpoint forallb {X : Type} (p : X -> bool) (l : list X) {struct l} : bool :=\n  match l with\n    | nil   => true\n    | x::xs => andb (p x) (forallb p xs)\n  end.\n\nFixpoint existsb {X : Type} (p : X -> bool) (l : list X) {struct l} : bool :=\n  match l with\n    | nil   => false\n    | x::xs => if p x then true else existsb p xs\n  end.\n\nDefinition existsb' {X : Type} (p : X -> bool) (l : list X) : bool :=\n  negb (forallb (fun x => negb (p x)) l).\n\nTheorem existsb_eq :\n  forall (X : Type) (p : X -> bool) (l : list X), existsb p l = existsb' p l.\nProof.\n  intros X p l.\n  unfold existsb'.\n  induction l.\n  + simpl; reflexivity.\n  + simpl.\n    destruct (p a) as [] eqn:pred_a.\n    simpl; reflexivity.\n    simpl; rewrite <- IHl; reflexivity.\nQed.\n\n\n", "meta": {"author": "sighingnow", "repo": "amazing-coq", "sha": "70acce0bac267f76f696b0f0a35865622b6a0ee8", "save_path": "github-repos/coq/sighingnow-amazing-coq", "path": "github-repos/coq/sighingnow-amazing-coq/amazing-coq-70acce0bac267f76f696b0f0a35865622b6a0ee8/software-foundations/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.6797374627105547}}
{"text": "Require Import Arith Bool List DepList.\n\nModule Tree_Idx.\n  Inductive tree (A : Type) : Type :=\n  | Leaf : A -> tree A\n  | Node : tree A -> tree A -> tree A.\n\n  Arguments Leaf {A} _.\n  Arguments Node {A} _ _.\n\n  Inductive Path {A} (a : A) : tree A -> Type :=\n  | Empty : Path a (Leaf a)\n  | Left : forall l r, Path a l -> Path a (Node l r)\n  | Right : forall l r, Path a r -> Path a (Node l r).\n\n  Inductive htree {A} B idx : Type :=\n  | Tf : (forall (a : A), Path a idx -> B a) -> htree B idx.\n\n  Definition map {A B C D idx}\n             (f : forall a, B a -> C a -> D a)\n             (t1 : htree B idx)\n             (t2 : htree C idx)\n    : htree D idx :=\n    match t1, t2 with\n    | Tf f1, Tf f2 => @Tf A D idx (fun a p => f a (f1 a p) (f2 a p))\n    end.\nEnd Tree_Idx.\n\nModule Tree_Rec.\n  Inductive tree (A : Type) : Type :=\n  | Leaf : A -> tree A\n  | Node : tree A -> tree A -> tree A.\n\n  Arguments Leaf {A} _.\n  Arguments Node {A} _ _.\n\n  Fixpoint htree {A} (B : A -> Type) (idx : tree A) : Type :=\n    match idx with\n    | Leaf a => B a\n    | Node l r => htree B l * htree B r\n    end%type.\n\n  Fixpoint Path {A : Type} a (idx : tree A) : Type :=\n    match idx with\n    | Leaf a' => a' = a\n    | Node l r => Path a l + Path a r\n    end%type.\n\n  Fixpoint get {A} B idx (t : htree B idx) {a : A} (p : Path a idx) : B a :=\n    match idx return htree B idx -> Path a idx -> B a with\n    | Node li ri => fun t p =>\n                      match t with\n                      | pair l r => match p with\n                                    | inl p' => get B li l p'\n                                    | inr p' => get B ri r p'\n                                    end\n                      end\n    | Leaf _ => fun t p =>\n                  match p with\n                  | eq_refl => t\n                  end\n    end t p.\n\n  Fixpoint map {A B C D} {idx : tree A}\n           (f : forall a, B a -> C a -> D a)\n           (t1 : htree B idx)\n           (t2 : htree C idx)\n    : htree D idx :=\n    match idx return htree B idx -> htree C idx -> htree D idx\n    with\n    | Leaf a => fun t1 t2 => f a t1 t2\n    | Node l r => fun t1 t2 => (map f (fst t1) (fst t2), map f (snd t1) (snd t2))\n    end t1 t2.\nEnd Tree_Rec.\n\nModule Tree_Ind.\n  Inductive tree (A : Type) : Type :=\n  | Leaf : A -> tree A\n  | Node : tree A -> tree A -> tree A.\n\n  Arguments Leaf {A} _.\n  Arguments Node {A} _ _.\n\n  Inductive htree {A : Type} (B : A -> Type) : tree A -> Type :=\n  | L : forall (a : A) (x : B a), htree B (Leaf a)\n  | N : forall (T1 T2 : tree A) (t1 : htree B T1) (t2 : htree B T2), htree B (Node T1 T2).\n\n  Arguments L {A} {B} {a}  _.\n  Arguments N {A} {B} {T1} {T2} _ _.\n\n  Inductive Path {A} (a : A) : tree A -> Type :=\n  | Empty : Path a (Leaf a)\n  | Left : forall l r, Path a l -> Path a (Node l r)\n  | Right : forall l r, Path a r -> Path a (Node l r).\n\n  Fixpoint get {A B idx a} (t : htree B idx) (p : Path a idx) : B a :=\n    match p in Path _ idx return @htree A B idx -> B a\n    with\n    | Empty => fun t =>\n                 match t in htree _ idx return match idx with\n                                               | Leaf a => B a\n                                               | Node _ _ => unit\n                                               end\n                 with\n                 | L _ x => x\n                 | N _ _ _ _ => tt\n                 end\n    | Left tl _ p' => fun t =>\n                        match t in htree _ idx return match idx with\n                                                      | Leaf _ => unit\n                                                      | Node tl _ => Path a tl -> B a\n                                                      end\n                        with\n                        | L _ _ => tt\n                        | N _ _ l _ => fun p' => get l p'\n                        end p'\n    | Right _ _ p' => fun t =>\n                        match t in htree _ idx return match idx with\n                                                      | Leaf _ => unit\n                                                      | Node _ tr => Path a tr -> B a\n                                                      end\n                        with\n                        | L _ _ => tt\n                        | N _ _ _ r => fun p' => get r p'\n                        end p'\n    end t.\n\n  Fixpoint map {A B C D} {idx : tree A}\n           (f : forall a, B a -> C a -> D a)\n           (t1 : htree B idx)\n           (t2 : htree C idx)\n    : htree D idx :=\n    match t1 in htree _ idx return htree C idx -> htree D idx\n    with\n    | L _ x => fun t2 =>\n                 match t2 in htree _ idx return match idx with\n                                                | Leaf a => B a -> htree D idx\n                                                | _ => unit\n                                                end\n                 with\n                 | L a y => fun x => L (f a x y)\n                 | _ => tt\n                 end x\n    | N tl tr l r => fun t2 =>\n                       match t2 in htree _ idx return match idx with\n                                                      | Leaf _ => unit\n                                                      | Node tl tr => htree B tl -> htree B tr -> htree D idx\n                                                      end\n                       with\n                       | L _ _ => tt\n                       | N _ _ l' r' => fun l r => N (map f l l') (map f r r')\n                       end l r\n    end t2.\nEnd Tree_Ind.\n\nModule Interpreter.\n  Inductive ty : Set :=\n  | Bool : ty\n  | Sum : ty -> ty -> ty.\n\n  Fixpoint denote (t : ty) : Set :=\n    match t with\n    | Bool => bool\n    | Sum t1 t2 => denote t1 + denote t2\n    end%type.\n\n  Definition var := nat.\n\n  Definition binding := prod var ty.\n\n  Definition bindings := list binding.\n\n  Inductive P : bindings -> ty -> Set :=\n  | PVar : forall T x, P (pair x T :: nil) T\n  | PConst : bool -> P nil Bool\n  | PLeft : forall bs T1 T2, P bs T1 -> P bs (Sum T1 T2)\n  | PRight : forall bs T1 T2, P bs T2 -> P bs (Sum T1 T2).\n\n  Definition Patterns (bs : list bindings) (T : ty) :=\n    hlist (fun b => P b T) bs.\n\n  Inductive Exp : bindings -> ty -> Set :=\n  | Var : forall bs T v, member (v, T) bs -> Exp bs T\n  | Const : forall bs, bool -> Exp bs Bool\n  | Left : forall bs T1 T2, Exp bs T1 -> Exp bs (Sum T1 T2)\n  | Right : forall bs T1 T2, Exp bs T2 -> Exp bs (Sum T1 T2)\n  | Case : forall bs T1 T2\n                  (pbs : list bindings)\n                  (patterns : Patterns pbs T1),\n      (forall b, member b pbs -> Exp (b ++ bs) T2)\n      -> Exp bs T2\n      -> Exp bs T1\n      -> Exp bs T2.\n\n  Definition PExps (bs : bindings) (pbs : list bindings) (T : ty) :=\n    hlist (fun b => Exp (b ++ bs) T) pbs.\n\n  Definition bindingType (b : binding) : Set :=\n    denote (snd b).\n\n  Definition Env (bs : bindings):=\n    hlist bindingType bs.\n\n  Fixpoint patternMatch {pbs T} (p : P pbs T) (v : denote T) {bs} (G : Env bs)\n    : option (Env (pbs ++ bs)) :=\n    match p in P pbs T return denote T -> Env bs -> option (Env (pbs ++ bs))\n    with\n    | PVar T x => fun v G => Some (@HCons binding bindingType (x, T) bs v G)\n    | PConst b => fun v G => if bool_dec b v then Some G else None\n    | PLeft _ _ _ p' => fun v G => match v with\n                                   | inl x => patternMatch p' x G\n                                   | _ => None\n                                   end\n    | PRight _ _ _ p' => fun v G => match v with\n                                    | inr x => patternMatch p' x G\n                                    | _ => None\n                                    end\n    end v G.\n\n  Definition Matched (bs : bindings) (pbs : list bindings) :=\n    fun b => prod (member b pbs) (Env (b ++ bs)).\n\n  Fixpoint matched {bs pbs T}\n           (patterns : Patterns pbs T)\n           (G : Env bs)\n           (v : denote T)\n    : option (sigT (Matched bs pbs)) :=\n    match patterns with\n    | HCons b pbs' p patterns' =>\n      match patternMatch p v G with\n      | Some G' => Some (existT _ b (@HFirst bindings b pbs', G'))\n      | None => match matched patterns' G v with\n                | Some (existT b (m, G'))\n                  => Some (existT _ b (HNext m, G'))\n                | None => None\n                end\n      end\n    | _ => None\n    end.\n\n  Fixpoint eval {T bs} (e : Exp bs T) (G : Env bs) {struct e} : denote T :=\n    match e in Exp bs T return Env bs -> denote T\n    with\n    | Var _ _ v m => fun G => hget G m\n    | Const _ b => fun _ => b\n    | Left _ _ _ e' => fun G => inl (eval e' G)\n    | Right _ _ _ e' => fun G => inr (eval e' G)\n    | Case bs T1 T2 pbs patterns exps def e' =>\n      fun G =>\n        match matched patterns G (eval e' G) with\n        | Some (existT b (m, G')) => eval (exps b m) G'\n        | None => eval def G\n        end\n    end G.\nEnd Interpreter.\n", "meta": {"author": "eldargab", "repo": "cpdt", "sha": "a7b41081e90e245014b4f4918c0a3837864bec56", "save_path": "github-repos/coq/eldargab-cpdt", "path": "github-repos/coq/eldargab-cpdt/cpdt-a7b41081e90e245014b4f4918c0a3837864bec56/DataStruct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6797251960127059}}
{"text": "Require Import Arith.\nRequire Import List.\nRequire Import ListSet.\n\nInductive Ty : Set := \n| Bas : nat -> Ty\n| Arr : Ty -> Ty -> Ty.\nNotation \"T ⇒ S\" := (Arr T S) (at level 30, right associativity).\n\nInductive Term : Set := \n| v : nat -> Term \n| ƛ : Ty -> Term -> Term\n| app : Term -> Term -> Term.\nNotation \"t · s\" := (app t s) (at level 20, left associativity).\n\nFixpoint Free (n : nat) (A : Set) : Set := \n  match n with \n    | O => A\n    | S n' => Term -> Free n' A\n  end.\n\nNotation \"[]\" := nil.\nNotation \"[ x ]\" := (cons x nil).\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) .. ).\n\nFixpoint idx (A : Set) (n : nat) (G : list A) : option A := \n  match G with \n    | [] => None\n    | (x::t) => match n with \n                  | O => Some x \n                  | S n' => idx A n' t\n                end\n  end.\nImplicit Arguments idx [A].\n\nDefinition Ctx := list Ty.\n\n(* Note : is \\colon, using TeX mode, and not : *)\nReserved Notation \"Γ ⊢ t @ A\" (at level 70, no associativity).\nInductive Derivation : Ctx -> Term -> Ty -> Set := \n| VarIntro : forall Γ n A, \n  idx n Γ = Some A -> \n  Γ ⊢ (v n) @ A\n| ImpIntro : forall Γ t A B,\n  A::Γ ⊢ t @ B ->\n  Γ ⊢ ƛ A t @ A ⇒ B\n| ImpElim : forall Γ f t A B, \n  Γ ⊢ f @ A ⇒ B -> \n  Γ ⊢ t @ A -> \n  Γ ⊢ f · t @ B\n where \"Γ ⊢ r @ A \" := (Derivation Γ r A) : type_scope.\n\nFixpoint shiftat (d : nat) (x : Term) {struct x} : Term := \n  match x with\n    | v m => if le_lt_dec d m then v (S m) else v m\n    | ƛ A t => ƛ A (shiftat (S d) t)\n    | r · s => (shiftat d r) · (shiftat d s)\n  end.\nDefinition shift := shiftat 0.\n\nDefinition sub : forall (t : Term) (n : nat) (u : Term), Term.\nProof.\n  refine \n    (fix sub (t : Term) (n : nat) (u : Term) := \n      match t with \n        | v m => match le_lt_dec n m with \n                   | left p => \n                     match eq_nat_dec n m with \n                       | left _ => u \n                       | right p' => \n                         (match m as m' return (m = m' -> Term) with\n                            | 0 => (fun p'' => False_rec _ _ )\n                            | S m' => (fun _ => v m')\n                          end) (refl_equal m)\n                     end\n                   | right _ => v m\n                 end\n        | ƛ A t => ƛ A (sub t (S n) (shift u))\n        | r · s => (sub r n u) · (sub s n u)\n      end) ; subst ; auto. \n  destruct n. apply le_n_O_eq in p. apply p'. reflexivity.\n  inversion p.\nDefined.\n\nLemma GammaClose : forall Γ a t A B, \n  A::Γ ⊢ t @ B -> [] ⊢ a @ A -> Γ ⊢ (sub t 0 a) @ B).\n\nLemma GammaClosure : forall Γ t A, \n  Γ ⊢ t @ A -> Free (length Γ) ([] ⊢ t @ A).\nProof. \n  induction Γ ; intros.\n\n  (* [] *) \n  simpl. auto.\n \n  (* a::Γ *)\n  simpl.\n  intros. \n  apply IHΓ. ", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/GammaClosure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6797251912215045}}
{"text": "Require Import Coq.Arith.EqNat.\nRequire Import Coq.Init.Nat.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Strings.String.\n\nRequire Import Hapsl.Bool.Bool.\nRequire Import Hapsl.Ascii.Equality.\n\n(* Returns true if one character is exactly one more than another, otherwise \n   returns false. *)\nDefinition consecutive_up (c1 c2 : ascii) : bool :=\n  eqb (nat_of_ascii c1) ((nat_of_ascii c2) - 1).\n\n(* Returns true if one character is exactly one less than another, otherwise \n   returns false. *)\nDefinition consecutive_down (c1 c2 : ascii) : bool :=\n  eqb (nat_of_ascii c1) ((nat_of_ascii c2) + 1).\n\n(* Returns the maximum number of times consecutive characters in a string \n   satisfy a function. *)\nFixpoint sequence_of (s : string) (f : ascii->ascii->bool) (a : nat) : nat :=\n  match s with\n  | EmptyString => a\n  | String c1 s1 => \n    match s1 with\n    | EmptyString => a\n    | String c2 s2 => \n      if f c1 c2 then\n        sequence_of s1 f (a + 1)\n      else\n        max a (sequence_of s1 f 0)\n    end\n  end.\n\n(* Returns the maximum number of times consecutive characters in a string are \n   one more than their predecessor. *)\nDefinition sequence_up (s : string) : nat :=\n  sequence_of s consecutive_up 0.\n\n(* Returns the maximum number of times consecutive characters in a string are \n   one less than their predecessor. *)\nDefinition sequence_down (s : string) : nat :=\n  sequence_of s consecutive_down 0.\n\n(* Returns the maximum number of times consecutive characters in a string are \n   the same as their predecessor. *)\nDefinition sequence_eq (s : string) : nat :=\n  sequence_of s beq_ascii 0.\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/Sequence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942232112239, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6797251889991518}}
{"text": "\nRequire Import Coq.funind.FunInd.\n\nDefinition iszero (n : nat) : bool :=\n  match n with\n  | O => true\n  | _ => false\n  end.\n\nFunctional Scheme iszero_ind := Induction for iszero Sort Prop.\n\nLemma toto : forall n : nat, n = 0 -> iszero n = true.\nintros x eg.\n functional induction iszero x; simpl.\ntrivial.\ninversion eg.\nQed.\n\n\nFunction ftest (n m : nat) : nat :=\n  match n with\n  | O => match m with\n         | O => 0\n         | _ => 1\n         end\n  | S p => 0\n  end.\n(* MS: FIXME: apparently can't define R_ftest_complete. Rest of the file goes through. *)\n\nLemma test1 : forall n m : nat, ftest n m <= 2.\nintros n m.\n functional induction ftest n m; auto.\nQed.\n\nLemma test2 : forall m n, ~ 2 = ftest n m.\nProof.\nintros n m;intro H.\nfunctional inversion H ftest.\nQed.\n\nLemma test3 : forall n m, ftest n m = 0 -> (n = 0 /\\ m = 0)  \\/ n <> 0.\nProof.\nfunctional inversion 1 ftest;auto.\nQed.\n\n\nRequire Import Arith.\nLemma test11 : forall m : nat, ftest 0 m <= 2.\nintros m.\n functional induction ftest 0 m.\nauto.\nauto.\nauto with *.\nQed.\n\nFunction lamfix (m n : nat) {struct n } : nat :=\n  match n with\n    | O => m\n    | S p => lamfix m p\n  end.\n\n(* Parameter v1 v2 : nat. *)\n\nLemma lamfix_lem : forall v1 v2 : nat, lamfix v1 v2 = v1.\nintros v1 v2.\n functional induction lamfix v1 v2.\ntrivial.\nassumption.\nDefined.\n\n\n\n(* polymorphic function *)\nRequire Import List.\n\nFunctional Scheme app_ind := Induction for app Sort Prop.\n\nLemma appnil : forall (A : Set) (l l' : list A), l' = nil -> l = l ++ l'.\nintros A l l'.\n functional induction app A l l';  intuition.\n rewrite <- H0; trivial.\nQed.\n\n\n\n\n\nRequire Export Arith.\n\n\nFunction trivfun (n : nat) : nat :=\n  match n with\n  | O => 0\n  | S m => trivfun m\n  end.\n\n\n(* essaie de parametre variables non locaux:*)\n\nParameter varessai : nat.\n\nLemma first_try : trivfun varessai = 0.\n functional induction trivfun varessai.\ntrivial.\nassumption.\nDefined.\n\n\n Functional Scheme triv_ind := Induction for trivfun Sort Prop.\n\nLemma bisrepetita : forall n' : nat, trivfun n' = 0.\nintros n'.\n functional induction trivfun n'.\ntrivial.\nassumption.\nQed.\n\n\n\n\n\n\n\nFunction iseven (n : nat) : bool :=\n  match n with\n  | O => true\n  | S (S m) => iseven m\n  | _ => false\n  end.\n\n\nFunction funex (n : nat) : nat :=\n  match iseven n with\n  | true => n\n  | false => match n with\n             | O => 0\n             | S r => funex r\n             end\n  end.\n\n\nFunction nat_equal_bool (n m : nat) {struct n} : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | _ => false\n         end\n  | S p => match m with\n           | O => false\n           | S q => nat_equal_bool p q\n           end\n  end.\n\n\nRequire Export Div2.\nRequire Import Nat.\nFunctional Scheme div2_ind := Induction for div2 Sort Prop.\nLemma div2_inf : forall n : nat, div2 n <= n.\nintros n.\n functional induction div2 n.\nauto.\nauto.\n\napply le_S.\napply le_n_S.\nexact IHn0.\nQed.\n\n(* reuse this lemma as a scheme:*)\n\nFunction nested_lam (n : nat) : nat -> nat :=\n  match n with\n  | O => fun m : nat => 0\n  | S n' => fun m : nat => m + nested_lam n' m\n  end.\n\n\nLemma nest : forall n m : nat, nested_lam n m = n * m.\nintros n m.\n functional induction nested_lam n m; simpl;auto.\nQed.\n\n\nFunction essai (x : nat) (p : nat * nat) {struct x} : nat :=\n  let (n, m) := (p: nat*nat) in\n  match n with\n  | O => 0\n  | S q => match x with\n           | O => 1\n           | S r => S (essai r (q, m))\n           end\n  end.\n\nLemma essai_essai :\n forall (x : nat) (p : nat * nat), let (n, m) := p in 0 < n -> 0 < essai x p.\nintros x p.\n functional induction essai x p; intros.\ninversion H.\nauto with arith.\n auto with arith.\nQed.\n\nFunction plus_x_not_five'' (n m : nat) {struct n} : nat :=\n  let x := nat_equal_bool m 5 in\n  let y := 0 in\n  match n with\n  | O => y\n  | S q =>\n      let recapp := plus_x_not_five'' q m in\n      match x with\n      | true => S recapp\n      | false => S recapp\n      end\n  end.\n\nLemma notplusfive'' : forall x y : nat, y = 5 -> plus_x_not_five'' x y = x.\nintros a b.\n functional induction plus_x_not_five'' a b; intros hyp; simpl; auto.\nQed.\n\nLemma iseq_eq : forall n m : nat, n = m -> nat_equal_bool n m = true.\nintros n m.\n functional induction nat_equal_bool n m; simpl; intros hyp; auto.\nrewrite <- hyp in y; simpl in y;tauto.\ninversion hyp.\nQed.\n\nLemma iseq_eq' : forall n m : nat, nat_equal_bool n m = true -> n = m.\nintros n m.\n functional induction nat_equal_bool n m; simpl; intros eg; auto.\ninversion eg.\ninversion eg.\nQed.\n\n\nInductive istrue : bool -> Prop :=\n    istrue0 : istrue true.\n\nFunctional Scheme add_ind := Induction for add Sort Prop.\n\nLemma inf_x_plusxy' : forall x y : nat, x <= x + y.\nintros n m.\n functional induction add n m; intros.\nauto with arith.\nauto with arith.\nQed.\n\n\nLemma inf_x_plusxy'' : forall x : nat, x <= x + 0.\nintros n.\nunfold plus.\n functional induction plus n 0; intros.\nauto with arith.\napply le_n_S.\nassumption.\nQed.\n\nLemma inf_x_plusxy''' : forall x : nat, x <= 0 + x.\nintros n.\n functional induction plus 0 n; intros; auto with arith.\nQed.\n\nFunction mod2 (n : nat) : nat :=\n  match n with\n  | O => 0\n  | S (S m) => S (mod2 m)\n  | _ => 0\n  end.\n\nLemma princ_mod2 : forall n : nat, mod2 n <= n.\nintros n.\n functional induction mod2 n; simpl; auto with arith.\nQed.\n\nFunction isfour (n : nat) : bool :=\n  match n with\n  | S (S (S (S O))) => true\n  | _ => false\n  end.\n\nFunction isononeorfour (n : nat) : bool :=\n  match n with\n  | S O => true\n  | S (S (S (S O))) => true\n  | _ => false\n  end.\n\nLemma toto'' : forall n : nat, istrue (isfour n) -> istrue (isononeorfour n).\nintros n.\n functional induction isononeorfour n; intros istr; simpl;\n inversion istr.\napply istrue0.\ndestruct n. inversion istr.\ndestruct n. tauto.\ndestruct n. inversion istr.\ndestruct n. inversion istr.\ndestruct n. tauto.\nsimpl in *. inversion H0.\nQed.\n\nLemma toto' : forall n m : nat, n = 4 -> istrue (isononeorfour n).\nintros n.\n functional induction isononeorfour n; intros m istr; inversion istr.\napply istrue0.\nrewrite H in y; simpl in y;tauto.\nQed.\n\nFunction ftest4 (n m : nat) : nat :=\n  match n with\n  | O => match m with\n         | O => 0\n         | S q => 1\n         end\n  | S p => match m with\n           | O => 0\n           | S r => 1\n           end\n  end.\n\nLemma test4 : forall n m : nat, ftest n m <= 2.\nintros n m.\n functional induction ftest n m; auto with arith.\nQed.\n\nLemma test4' : forall n m : nat, ftest4 (S n) m <= 2.\nintros n m.\nassert ({n0 | n0 = S n}).\nexists (S n);reflexivity.\ndestruct H as [n0 H1].\nrewrite <- H1;revert H1.\n functional induction ftest4 n0 m.\ninversion 1.\ninversion 1.\n\nauto with arith.\nauto with arith.\nQed.\n\nFunction ftest44 (x : nat * nat) (n m : nat) : nat :=\n  let (p, q) := (x: nat*nat) in\n  match n with\n  | O => match m with\n         | O => 0\n         | S q => 1\n         end\n  | S p => match m with\n           | O => 0\n           | S r => 1\n           end\n  end.\n\nLemma test44 :\n forall (pq : nat * nat) (n m o r s : nat), ftest44 pq n (S m) <= 2.\nintros pq n m o r s.\n functional induction ftest44 pq n (S m).\nauto with arith.\nauto with arith.\nauto with arith.\nauto with arith.\nQed.\n\nFunction ftest2 (n m : nat) {struct n} : nat :=\n  match n with\n  | O => match m with\n         | O => 0\n         | S q => 0\n         end\n  | S p => ftest2 p m\n  end.\n\nLemma test2' : forall n m : nat, ftest2 n m <= 2.\nintros n m.\n functional induction ftest2 n m; simpl; intros; auto.\nQed.\n\nFunction ftest3 (n m : nat) {struct n} : nat :=\n  match n with\n  | O => 0\n  | S p => match m with\n           | O => ftest3 p 0\n           | S r => 0\n           end\n  end.\n\nLemma test3' : forall n m : nat, ftest3 n m <= 2.\nintros n m.\n functional induction ftest3 n m.\nintros.\nauto.\nintros.\nauto.\nintros.\nsimpl.\nauto.\nQed.\n\nFunction ftest5 (n m : nat) {struct n} : nat :=\n  match n with\n  | O => 0\n  | S p => match m with\n           | O => ftest5 p 0\n           | S r => ftest5 p r\n           end\n  end.\n\nLemma test5 : forall n m : nat, ftest5 n m <= 2.\nintros n m.\n functional induction ftest5 n m.\nintros.\nauto.\nintros.\nauto.\nintros.\nsimpl.\nauto.\nQed.\n\nFunction ftest7 (n : nat) : nat :=\n  match ftest5 n 0 with\n  | O => 0\n  | S r => 0\n  end.\n\nLemma essai7 :\n forall (Hrec : forall n : nat, ftest5 n 0 = 0 -> ftest7 n <= 2)\n   (Hrec0 : forall n r : nat, ftest5 n 0 = S r -> ftest7 n <= 2)\n   (n : nat), ftest7 n <= 2.\nintros hyp1 hyp2 n.\n functional induction ftest7 n; auto.\nQed.\n\nFunction ftest6 (n m : nat) {struct n} : nat :=\n  match n with\n  | O => 0\n  | S p => match ftest5 p 0 with\n           | O => ftest6 p 0\n           | S r => ftest6 p r\n           end\n  end.\n\n\nLemma princ6 :\n (forall n m : nat, n = 0 -> ftest6 0 m <= 2) ->\n (forall n m p : nat,\n  ftest6 p 0 <= 2 -> ftest5 p 0 = 0 -> n = S p -> ftest6 (S p) m <= 2) ->\n (forall n m p r : nat,\n  ftest6 p r <= 2 -> ftest5 p 0 = S r -> n = S p -> ftest6 (S p) m <= 2) ->\n forall x y : nat, ftest6 x y <= 2.\nintros hyp1 hyp2 hyp3 n m.\ngeneralize hyp1 hyp2 hyp3.\nclear hyp1 hyp2 hyp3.\n functional induction ftest6 n m; auto.\nQed.\n\nLemma essai6 : forall n m : nat, ftest6 n m <= 2.\nintros n m.\n functional induction ftest6 n m; simpl; auto.\nQed.\n\n(* Some tests with modules *)\nModule M.\nFunction test_m (n:nat) : nat :=\n  match n with\n    | 0 => 0\n    | S n =>  S (S (test_m n))\n  end.\n\nLemma test_m_is_double :  forall n, div2 (test_m n) = n.\nProof.\nintros n.\nfunctional induction (test_m n).\nreflexivity.\nsimpl;rewrite IHn0;reflexivity.\nQed.\nEnd M.\n(* We redefine a new Function with the same name *)\nFunction test_m (n:nat) : nat :=\n  pred n.\n\nLemma test_m_is_pred : forall n, test_m n = pred n.\nProof.\nintro n.\nfunctional induction (test_m n). (* the test_m_ind to use is the last defined  saying that test_m = pred*)\nreflexivity.\nQed.\n\n(* Checks if the dot notation are correctly treated in infos *)\nLemma M_test_m_is_double : forall n, div2 (M.test_m n) = n.\nintro n.\n(* here we should apply M.test_m_ind *)\nfunctional induction (M.test_m n).\nreflexivity.\nsimpl;rewrite IHn0;reflexivity.\nQed.\n\nImport M.\n(* Now test_m is the one which defines double *)\n\nLemma test_m_is_double : forall n, div2 (M.test_m n) = n.\nintro n.\n(* here we should apply M.test_m_ind *)\nfunctional induction (test_m n).\nreflexivity.\nsimpl;rewrite IHn0;reflexivity.\nQed.\n\n\n\n\n\n\n\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/success/Funind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.6797134546695147}}
{"text": "Require Export Coq.Program.Tactics.\nRequire Export Coq.Setoids.Setoid.\nRequire Export Coq.Classes.Morphisms.\nRequire Export Coq.Arith.Arith_base.\nRequire Export Coq.Relations.Relations.\nRequire Export Coq.Lists.List.\n\nImport EqNotations.\nImport ListNotations.\n\n\n(***\n *** Ordered Types = Types with a PreOrder\n ***)\n\nRecord OType : Type :=\n  {\n    ot_Type :> Type;\n    ot_R : relation ot_Type;\n    ot_PreOrder : PreOrder ot_R\n  }.\n\nInstance OType_Reflexive (A:OType) : Reflexive (ot_R A).\nProof.\n  destruct A; auto with typeclass_instances.\nQed.\n\nInstance OType_Transitive (A:OType) : Transitive (ot_R A).\nProof.\n  destruct A; auto with typeclass_instances.\nQed.\n\n(* The equivalence relation for an OrderedType *)\nDefinition ot_equiv (A:OType) : relation A :=\n  fun x y => ot_R A x y /\\ ot_R A y x.\n\nInstance ot_equiv_Equivalence A : Equivalence (ot_equiv A).\nProof.\n  constructor; intro; intros.\n  { split; reflexivity. }\n  { destruct H; split; assumption. }\n  { destruct H; destruct H0; split; transitivity y; assumption. }\nQed.\n\n\n(***\n *** Commonly-Used Ordered Types\n ***)\n\n(* The ordered type of propositions *)\nProgram Definition OTProp : OType :=\n  {|\n    ot_Type := Prop;\n    ot_R := Basics.impl;\n  |}.\nNext Obligation.\n  constructor; auto with typeclass_instances.\nQed.\n\n(* The discrete ordered type, where things are only related to themselves *)\nProgram Definition OTdiscrete (A:Type) : OType :=\n  {|\n    ot_Type := A;\n    ot_R := eq;\n  |}.\n\n(* The only ordered type over unit is the discrete one *)\nDefinition OTunit : OType := OTdiscrete unit.\n\n(* The ordered type of natural numbers using <= *)\nProgram Definition OTnat : OType :=\n  {|\n    ot_Type := nat;\n    ot_R := le;\n  |}.\n\n(* Flip the ordering of an OType *)\nProgram Definition OTflip (A:OType) : OType :=\n  {|\n    ot_Type := ot_Type A;\n    ot_R := fun x y => ot_R A y x\n  |}.\nNext Obligation.\n  constructor.\n  { intro x. reflexivity. }\n  { intros x y z; transitivity y; assumption. }\nQed.\n\n(* The pointwise relation on pairs *)\nDefinition pairR {A B} (RA:relation A) (RB:relation B) : relation (A*B) :=\n  fun p1 p2 => RA (fst p1) (fst p2) /\\ RB (snd p1) (snd p2).\n\nInstance PreOrder_pairR A B RA RB\n         `(PreOrder A RA) `(PreOrder B RB) : PreOrder (pairR RA RB).\nProof.\n  constructor.\n  { intro p; split; reflexivity. }\n  { intros p1 p2 p3 R12 R23; destruct R12; destruct R23; split.\n    - transitivity (fst p2); assumption.\n    - transitivity (snd p2); assumption. }\nQed.\n\n(* The non-dependent product ordered type, where pairs are related pointwise *)\nDefinition OTpair (A B:OType) : OType :=\n  {|\n    ot_Type := ot_Type A * ot_Type B;\n    ot_R := pairR (ot_R A) (ot_R B);\n    ot_PreOrder := PreOrder_pairR A B _ _ (ot_PreOrder A) (ot_PreOrder B)\n  |}.\n\n(* The sort-of pointwise relation on sum types *)\nInductive sumR {A B} (RA:relation A) (RB:relation B) : A+B -> A+B -> Prop :=\n| sumR_inl a1 a2 : RA a1 a2 -> sumR RA RB (inl a1) (inl a2)\n| sumR_inr b1 b2 : RB b1 b2 -> sumR RA RB (inr b1) (inr b2).\n\nInstance PreOrder_sumR A B RA RB\n         `(PreOrder A RA) `(PreOrder B RB) : PreOrder (sumR RA RB).\nProof.\n  constructor.\n  { intro s; destruct s; constructor; reflexivity. }\n  { intros s1 s2 s3 R12 R23. destruct R12; inversion R23.\n    - constructor; transitivity a2; assumption.\n    - constructor; transitivity b2; assumption. }\nQed.\n\n(*\nDefinition sumR {A B} (RA:relation A) (RB:relation B) : relation (A+B) :=\n  fun sum1 sum2 =>\n    match sum1, sum2 with\n    | inl x, inl y => RA x y\n    | inl x, inr y => False\n    | inr x, inl y => False\n    | inr x, inr y => RB x y\n    end.\n\nInstance PreOrder_sumR A B RA RB\n         `(PreOrder A RA) `(PreOrder B RB) : PreOrder (sumR RA RB).\nProof.\n  constructor.\n  { intro s; destruct s; simpl; reflexivity. }\n  { intros s1 s2 s3 R12 R23.\n    destruct s1; destruct s2; destruct s3;\n      try (elimtype False; assumption); simpl.\n    - transitivity a0; assumption.\n    - transitivity b0; assumption. }\nQed.\n*)\n\n(* The non-dependent sum ordered type, where objects are only related if they\nare both \"left\"s or both \"right\"s *)\nDefinition OTsum (A B : OType) : OType :=\n  {|\n    ot_Type := ot_Type A + ot_Type B;\n    ot_R := sumR (ot_R A) (ot_R B);\n    ot_PreOrder := PreOrder_sumR _ _ _ _ (ot_PreOrder A) (ot_PreOrder B)\n  |}.\n\n\n(* NOTE: the following definition requires everything above to be polymorphic *)\n(* NOTE: The definition we choose for OTType is actually deep: instead of\nrequiring ot_Type A = ot_Type B, we could just require a coercion function from\not_Type A to ot_Type B, which would yield something more like HoTT... though\nmaybe it wouldn't work unless we assumed the HoTT axiom? As it is, we might need\nUIP to hold if we want to use the definition given here... *)\n(*\nProgram Definition OTType : OType :=\n  {|\n    ot_Type := OType;\n    ot_R := (fun A B =>\n               exists (e:ot_Type A = ot_Type B),\n                 forall (x y:A),\n                   ot_R A x y ->\n                   ot_R B (rew [fun A => A] e in x)\n                        (rew [fun A => A] e in y));\n  |}.\n*)\n\n\n(***\n *** The Ordered Type for Functions\n ***)\n\n(* The type of continuous, i.e. Proper, functions between ordered types *)\nRecord Pfun (A B:OType) :=\n  {\n    pfun_app : ot_Type A -> ot_Type B;\n    pfun_Proper : Proper (ot_R A ==> ot_R B) pfun_app\n  }.\n\nArguments pfun_app [_ _] _ _.\nArguments pfun_Proper [_ _] _ _ _ _.\n\n(* Infix \"@\" := pfun_app (at level 50). *)\n\n(* The non-dependent function ordered type *)\nDefinition OTarrow_R (A B : OType) : relation (Pfun A B) :=\n  fun f g =>\n    forall a1 a2, ot_R A a1 a2 -> ot_R B (pfun_app f a1) (pfun_app g a2).\n\nProgram Definition OTarrow (A B:OType) : OType :=\n  {|\n    ot_Type := Pfun A B;\n    ot_R := OTarrow_R A B;\n  |}.\nNext Obligation.\n  constructor.\n  { intros f; apply (pfun_Proper f). }\n  { intros f g h Rfg Rgh a1 a2 Ra. transitivity (pfun_app g a1).\n    - apply (Rfg a1 a1). reflexivity.\n    - apply Rgh; assumption. }\nQed.\n\n(* Curry a Pfun *)\nProgram Definition pfun_curry {A B C} (pfun : Pfun (OTpair A B) C)\n  : Pfun A (OTarrow B C) :=\n  {| pfun_app :=\n       fun a =>\n         {| pfun_app := fun b => pfun_app pfun (a,b);\n            pfun_Proper := _ |};\n     pfun_Proper := _ |}.\nNext Obligation.\nProof.\n  intros b1 b2 Rb. apply pfun_Proper.\n  split; [ reflexivity | assumption ].\nQed.\nNext Obligation.\nProof.\n  intros a1 a2 Ra b1 b2 Rb; simpl.\n  apply pfun_Proper; split; assumption.\nQed.\n\n(* Uncrry a Pfun *)\nProgram Definition pfun_uncurry {A B C} (pfun : Pfun A (OTarrow B C))\n  : Pfun (OTpair A B) C :=\n  {| pfun_app :=\n       fun ab => pfun_app (pfun_app pfun (fst ab)) (snd ab);\n     pfun_Proper := _ |}.\nNext Obligation.\nProof.\n  intros ab1 ab2 Rab. destruct Rab as [ Ra Rb ].\n  exact (pfun_Proper pfun (fst ab1) (fst ab2) Ra (snd ab1) (snd ab2) Rb).\nQed.\n\n(* Currying and uncurrying of pfuns form an adjunction *)\n(* FIXME: figure out the simplest way of stating this adjunction *)\n\n\n(* OTarrow is right adjoint to OTpair, meaning that (OTarrow (OTpair A B) C) is\nisomorphic to (OTarrow A (OTarrow B C)). The following is the first part of this\nisomorphism, mapping left-to-right. *)\n\n\n(* FIXME: could also do a forall type, but need the second type argument, B, to\nitself be proper, i.e., to be an element of OTarrow A OType. Would also need a\ndependent version of OTContext, below. *)\n\n\n(* pfun_app is always Proper *)\nInstance Proper_pfun_app A B :\n  Proper (ot_R (OTarrow A B) ==> ot_R A ==> ot_R B) (@pfun_app A B).\nProof.\n  intros f1 f2 Rf a1 a2 Ra. apply Rf; assumption.\nQed.\n\n(* pfun_app is always Proper w.r.t. ot_equiv *)\nInstance Proper_pfun_app_equiv A B :\n  Proper (ot_equiv (OTarrow A B) ==> ot_equiv A ==> ot_equiv B) (@pfun_app A B).\nProof.\n  intros f1 f2 Rf a1 a2 Ra; destruct Rf; destruct Ra.\n  split; apply Proper_pfun_app; assumption.\nQed.\n\n\n(***\n *** Building Proper Functions\n ***)\n\nClass ProperPair (A:OType) (x y:A) : Prop :=\n  proper_pair_pf : ot_R A x y.\n\nDefinition ot_Lambda {A B:OType} (f: A -> B)\n           {prp:forall x y, ProperPair A x y -> ProperPair B (f x) (f y)}\n  : OTarrow A B :=\n  {| pfun_app := f; pfun_Proper := prp |}.\n\nInstance ProperPair_refl (A:OType) (x:A) : ProperPair A x x.\nProof.\n  unfold ProperPair. reflexivity.\nQed.\n\nInstance ProperPair_pfun_app (A B:OType) (fl fr:OTarrow A B) argl argr\n         (prpf:ProperPair (OTarrow A B) fl fr)\n         (prpa:ProperPair A argl argr)\n : ProperPair B (pfun_app fl argl) (pfun_app fr argr).\nProof.\n  apply prpf; assumption.\nQed.\n\nInstance ProperPair_ot_lambda (A B:OType) (f g:A -> B) prpl prpr\n         (pf: forall x y, ProperPair A x y -> ProperPair B (f x) (g y)) :\n  ProperPair (OTarrow A B) (@ot_Lambda A B f prpl) (@ot_Lambda A B g prpr).\nProof.\n  intros xl xr Rx; apply pf; assumption.\nQed.\n\n\n(***\n *** Ordered Terms for Pair Operations\n ***)\n\nProgram Definition ofst {A B:OType} : OTarrow (OTpair A B) A :=\n  @ot_Lambda (OTpair A B) A fst _.\nNext Obligation.\n  destruct H. assumption.\nQed.\n\nProgram Definition osnd {A B:OType} : OTarrow (OTpair A B) B :=\n  @ot_Lambda (OTpair A B) _ snd _.\nNext Obligation.\n  destruct H. assumption.\nQed.\n\nProgram Definition opair {A B:OType} : OTarrow A (OTarrow B (OTpair A B)) :=\n  @ot_Lambda\n    A _\n    (fun x =>\n       @ot_Lambda\n         B (OTpair A B)\n         (fun y => pair x y)\n         _)\n    _.\nNext Obligation.\n  split; [ reflexivity | assumption ].\nQed.\nNext Obligation.\n  apply ProperPair_ot_lambda; intros. split; assumption.\nQed.\n\n\n(***\n *** Notations for Ordered Types\n ***)\n\nNotation \"A '-o>' B\" :=\n  (OTarrow A B) (right associativity, at level 99).\nNotation \"A '*o*' B\" :=\n  (OTpair A B) (left associativity, at level 40).\nNotation \"A '+o+' B\" :=\n  (OTsum A B) (left associativity, at level 50).\nNotation \"'~o~' A\" :=\n  (OTflip A) (right associativity, at level 35).\n\nNotation \"x <o= y\" :=\n  (ot_R _ x y) (no associativity, at level 70).\nNotation \"x =o= y\" :=\n  (ot_equiv _ x y) (no associativity, at level 70).\n\nNotation \"x @o@ y\" :=\n  (pfun_app x y) (left associativity, at level 20).\n\nNotation \"( x ,o, y )\" :=\n  (opair @o@ x @o@ y)\n    (no associativity, at level 0).\n\n(* FIXME: why don't these work?\nNotation \"'ofun' ( x : A ) =o> t\" :=\n  (@ot_Lambda A _ (fun x => t))\n    (at level 100, right associativity, x at level 99) : pterm_scope.\n\nNotation \"'ofun' x =o> t\" :=\n  (ot_Lambda (fun x => t))\n    (at level 100, right associativity, x at level 99) : pterm_scope.\n *)\n\nNotation ofun := ot_Lambda.\n\n\n(***\n *** Automation for Ordered Terms\n ***)\n\n(* Don't unfold ot_Lambda when simplifying  *)\nArguments ot_Lambda A B f prp : simpl never.\n\nInstance Proper_ot_R_ot_R A :\n  Proper (Basics.flip (ot_R A) ==> ot_R A ==> Basics.impl) (ot_R A).\nProof.\n  intros x1 x2 Rx y1 y2 Ry R.\n  transitivity x1; [ assumption | ]; transitivity y1; assumption.\nQed.\n\nInstance Proper_ot_equiv_ot_R A :\n  Proper (ot_equiv A ==> ot_equiv A ==> iff) (ot_R A).\nProof.\n  intros x1 x2 Rx y1 y2 Ry; destruct Rx; destruct Ry; split; intro R.\n  transitivity x1; [ assumption | ]; transitivity y1; assumption.\n  transitivity x2; [ assumption | ]; transitivity y2; assumption.\nQed.\n\nInstance Proper_ot_R_pfun_app A B :\n  Proper (ot_R (A -o> B) ==> ot_R A ==> ot_R B) (@pfun_app A B).\nProof.\n  intros f1 f2 Rf x1 x2 Rx. apply Rf; apply Rx.\nQed.\n\nInstance Proper_ot_R_pfun_app_partial A B f :\n  Proper (ot_R A ==> ot_R B) (@pfun_app A B f).\nProof.\n  apply pfun_Proper.\nQed.\n\n\nCreate HintDb OT.\n\n(* Split ot_equiv equalities into the left and right cases *)\nDefinition split_ot_equiv A (x y : ot_Type A)\n           (pf1: x <o= y) (pf2 : y <o= x) : x =o= y :=\n  conj pf1 pf2.\n\nHint Resolve split_ot_equiv : OT.\n\n(* Extensionality for ot_R *)\nDefinition ot_arrow_ext (A B:OType) (f1 f2 : A -o> B)\n           (pf:forall x y, x <o= y -> f1 @o@ x <o= f2 @o@ y) : f1 <o= f2 := pf.\n\nHint Resolve ot_arrow_ext : OT.\n\n(* Add the above rules to the OT rewrite set *)\n(* Hint Rewrite @mkOTerm_apply @ot_unlift_iso_OTForType_refl_id : OT. *)\n\n(* Eta-equality for pairs *)\nLemma ot_pair_eta (A B:OType) (x : A *o* B) :\n  @ot_equiv (A *o* B) (fst x , snd x) x.\n  split; split; reflexivity.\nQed.\n\nHint Rewrite ot_pair_eta : OT.\n\n(* Tactic to apply rewrites in the OT rewrite set *)\nLtac rewrite_OT := rewrite_strat (topdown (hints OT)).\n\n(* General tactic to try to prove theorems about ordered terms *)\n(*\nLtac prove_OT :=\n  repeat first [simpl_mkOTerm_refl | simpl_mkOTerm_apply];\n  try rewrite_OT;\n  lazymatch goal with\n  | |- ot_equiv _ _ _ => split\n  | |- _ => idtac\n  end.\n  (* repeat (apply ot_arrow_ext; intros). *)\n *)\n\n\n(***\n *** Examples of Ordered Terms\n ***)\n\nModule OTExamples.\n\nDefinition ex1 : OTProp -o> OTProp := ot_Lambda (fun p => p).\n(* Eval compute in (pfun_app ex1 : Prop -> Prop). *)\n\nDefinition ex2 {A} : (A -o> A) := ot_Lambda (fun p => p).\n(* Eval simpl in (fun A:OType => pfun_app (@ex2 A) : A -> A). *)\n\nDefinition ex3 {A} : (A -o> A -o> A) :=\n  ot_Lambda (fun p1 => ot_Lambda (fun p2 => p1)).\n(* Eval simpl in (fun (A:OType) x => pfun_app (pfun_app (@ex3 A) x)). *)\n\nDefinition ex4 {A B} : (A *o* B -o> A) := ot_Lambda (fun p => ofst @o@ p).\n(* Eval simpl in (fun (A B:OType) => pfun_app ex4 : A * B -> A). *)\n\nDefinition ex5 {A B} : A *o* B -o> B *o* A :=\n  ot_Lambda (fun p => (osnd @o@ p ,o, ofst @o@ p)).\n(* Eval simpl in (fun (A B:OType) => pfun_app ex5 : A *o* B -> B *o* A). *)\n\nDefinition ex6 {A B C} : A *o* B *o* C -o> C *o* A :=\n  ot_Lambda (fun triple => (osnd @o@ triple ,o, ofst @o@ (ofst @o@ triple))).\n\nDefinition ex7 {A B C} : (A *o* B -o> C) -o> C -o> A -o> B -o> C :=\n  ot_Lambda (fun (f:(A *o* B -o> C)) =>\n               ot_Lambda\n                 (fun (c:C) =>\n                    ot_Lambda\n                      (fun a =>\n                         ot_Lambda (fun b => f @o@ (a ,o, b))))).\n\nEnd OTExamples.\n", "meta": {"author": "eddywestbrook", "repo": "predicate-monads", "sha": "2e4ac28d8f5e4b3080bdde5dafdb106c569197d4", "save_path": "github-repos/coq/eddywestbrook-predicate-monads", "path": "github-repos/coq/eddywestbrook-predicate-monads/predicate-monads-2e4ac28d8f5e4b3080bdde5dafdb106c569197d4/theories/archival/Ordered7/OrderedType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.6797134529143617}}
{"text": "Require Import List Orders Nat.\nRequire Import Coq.Structures.OrdersFacts.\nRequire Import Coq.Sorting.Permutation.\nRequire Import Coq.Sorting.Sorted.\nRequire Import Sorticoq.SortedList.\nImport ListNotations.\n\nModule SelectionSort (Import O: UsualOrderedTypeFull').\n\nInclude (OrderedTypeFacts O).\n\nDefinition A := O.t.\n\nFixpoint SelectMin (l: list A) (d: A) : A :=\n  match l with\n  | [] => d\n  | h::t => let y := (SelectMin t h) in match (O.compare d y) with\n    | Lt => d\n    | _ => y\n    end\n  end.\n\nFixpoint delete (x: A) (l: list A) : list A :=\n  match l with\n  | [] => []\n  | h::t => match (O.compare x h) with\n    | Eq => t\n    | _ => h::(delete x t)\n    end\n  end.\n\nFixpoint SelectionSortHelp (l: list A) (n: nat) : list A :=\n  match l, n with\n  | [], _ => []\n  | _, 0 => l\n  | h::t, S n' => let y := (SelectMin t h) in\n    y::(SelectionSortHelp (delete y l) n')\n  end.\n\nDefinition SelectionSort (l: list A) :=\n  SelectionSortHelp l (length l).\n\nHint Constructors LocallySorted.\nHint Extern 1 (?x <= ?y) => apply le_lteq; OrderTac.order.\n\nLtac convert_compare :=\n  repeat match goal with\n  | H: compare ?x ?y = Lt |- _ => apply compare_lt_iff in H\n  | H: compare ?x ?y = Gt |- _ => apply compare_gt_iff in H\n  | H: compare ?x ?y = Eq |- _ => apply compare_eq in H\n  end.\n\nLemma le_trans: @transitive O.t le.\nProof.\n  unfold transitive.\n  intros. apply le_lteq in H. apply le_lteq in H0.\n  apply le_lteq. intuition; order.\nQed.\n\nLemma SelectMin_is_min: forall l a,\n  forall x, In x (a::l) -> (SelectMin l a) <= x.\nProof.\n  intro l; induction l; intros; simpl; auto.\n  - inversion H; auto. inversion H0.\n  - simpl in H. destruct H as [H | [H | H]];\n    remember (compare _ _) as c; symmetry in Heqc; destruct c; convert_compare;\n    subst; auto;\n    try match goal with\n    | |- SelectMin l ?x <= ?y => apply IHl\n    | H: ?x < ?y |- ?x <= ?z => apply (le_trans x y z)\n    end; simpl; auto; apply IHl; simpl; auto.\nQed.\n\nLtac do_compare :=\n  let C := fresh in let eqnC := fresh in remember (compare _ _) as C eqn:eqnC;\n  symmetry in eqnC; destruct C; convert_compare.\n\nLemma SelectMin_In: forall l a,\n  In (SelectMin l a) (a::l).\nProof.\n  intro l; induction l; simpl; auto.\n  intros; do_compare; auto.\n  simpl in IHl. auto.\nQed.\n\nLemma SelectMin_In2: forall l a,\n  (SelectMin l a) <> a ->\n  In (SelectMin l a) l.\nProof.\n  intros. assert (In (SelectMin l a) (a::l)) by apply SelectMin_In.\n  destruct H0. rewrite <- H0 in H. contradiction. exact H0.\nQed.\n\nLemma delete_length: forall l a,\n  In a l ->\n  S (length (delete a l)) = length l.\nProof.\n  intro l; induction l; simpl; intros; auto.\n  - contradiction.\n  - do_compare; auto; intuition; try order.\n  all: simpl; apply eq_S; apply IHl; assumption.\nQed.\n\nLemma delete_Permutation: forall l a,\n  In a l ->\n  Permutation l (a::delete a l).\nProof.\n  induction l; intros; simpl in *.\n  - contradiction.\n  - do_compare; intuition; subst; try order; auto.\n    all: transitivity (a::a0::delete a0 l); auto; apply perm_swap.\nQed.\n\nOpaque delete.\n\nLemma SelectionSort_Permutation_t: forall l n,\n  length l = n -> Permutation l (SelectionSort l).\nProof.\n  intros; generalize dependent l.\n  induction n; unfold SelectionSort; intros; auto.\n  - apply length_zero_iff_nil in H. subst. auto.\n  - destruct l eqn: E; simpl; auto.\n    assert (length (delete (SelectMin l0 a) (a::l0)) = length l0).\n      assert (Hy: In (SelectMin l0 a) (a::l0)) by apply SelectMin_In; simpl in Hy.\n      Transparent delete. simpl. do_compare; intuition; try order;\n      simpl; apply delete_length; assumption.\n    rewrite <- H0.\n    change (SelectionSortHelp ?l (length ?l)) with (SelectionSort l).\n    transitivity (SelectMin l0 a :: (delete (SelectMin l0 a) (a::l0))).\n    apply delete_Permutation. apply SelectMin_In.\n    constructor. apply IHn. rewrite H0. simpl in H. auto.\nQed.\n\nLemma SelectionSort_Permutation: forall l,\n  Permutation l (SelectionSort l).\nProof.\n  intros. apply (SelectionSort_Permutation_t l (length l)). reflexivity.\nQed.\n\nHint Extern 2 (Permutation (SelectionSort ?l) ?l) =>\n  apply Permutation_sym; apply SelectionSort_Permutation.\n\nLemma delete_length2: forall l a,\n  SelectMin l a <> a ->\n  length (a :: delete (SelectMin l a) l) = length l.\nProof.\n  intros. simpl; apply delete_length.\n  apply SelectMin_In2; assumption.\nQed.\n\nLemma In_delete: forall l a x,\n  In x (delete a l) -> In x l.\nProof.\n  induction l; simpl; auto; intros; do_compare; auto.\n  all: simpl in H; intuition; apply IHl in H0; auto.\nQed.\n\nLemma SelectionSort_LocallySorted_t: forall l n,\n  length l = n -> LocallySorted le (SelectionSort l).\nProof.\n  intros; generalize dependent l.\n  induction n; unfold SelectionSort; intros; simpl; auto.\n  + apply length_zero_iff_nil in H. subst; simpl; auto.\n  + destruct l. inversion H. simpl.\n  do_compare;\n  try assert (length (a::(delete (SelectMin l a) l)) = length l) by\n      (apply delete_length2; order);\n  repeat (match goal with\n  | |- context[SelectionSortHelp ?x (length ?x)] =>\n    change (SelectionSortHelp ?l (length ?l)) with (SelectionSort l)\n  | H: context[SelectionSortHelp ?x (length ?x)] |- _ =>\n    change (SelectionSortHelp ?l (length ?l)) with (SelectionSort l) in H\n  | |- LocallySorted le (SelectMin ?l ?x :: _) =>\n    apply LocallySorted_hd_relation; intros\n  | |- SelectMin ?l ?a <= ?x =>\n    apply SelectMin_is_min\n  | H: length ?x = length ?l |- context[length l] =>\n    rewrite <- H\n  | H: length ?x = length ?l |- _ =>\n    try match goal with\n    | H2: In ?t (SelectionSortHelp x (length l)) |- _ =>\n      rewrite <- H in H2\n    end\n  end; auto).\n  - apply Permutation_in with (l' := l) in H0; simpl; auto.\n  - apply Permutation_in with (l' := (a::delete (SelectMin l a) l)) in H2; simpl; auto.\n    simpl in H2; intuition. apply In_delete in H3. auto.\n  - apply IHn. rewrite H0. auto.\n  - apply Permutation_in with (l' := (a::delete (SelectMin l a) l)) in H2; simpl; auto.\n    simpl in H2; intuition. apply In_delete in H3. auto.\n  - apply IHn. rewrite H0. auto.\nQed.\n\nLemma SelectionSort_LocallySorted: forall l,\n  LocallySorted le (SelectionSort l).\nProof.\n  intros. apply SelectionSort_LocallySorted_t with (n:=length l). reflexivity.\nQed.\n\nLemma SelectionSort_is_sorting_algo:\n  is_sorting_algo le SelectionSort.\nProof.\n  unfold is_sorting_algo; intros; split.\n  - apply SelectionSort_Permutation.\n  - apply Sorted_LocallySorted_iff. apply SelectionSort_LocallySorted.\nQed.\n\nEnd SelectionSort.\n\n(**\n   An example\n*)\n\nRequire Import ZArith.\n\nModule Import ZSort := SelectionSort Z.\n\nExample SortingExample: [2%Z; 4%Z; 4%Z; 6%Z; 8%Z] =\n  (SelectionSort [4%Z; 2%Z; 8%Z; 4%Z; 6%Z]).\nProof.\n  compute. reflexivity.\nQed.", "meta": {"author": "holmuk", "repo": "Sorticoq", "sha": "ac115f2a80deb5c2db2a56ba6b7adfad043e84b5", "save_path": "github-repos/coq/holmuk-Sorticoq", "path": "github-repos/coq/holmuk-Sorticoq/Sorticoq-ac115f2a80deb5c2db2a56ba6b7adfad043e84b5/src/SelectionSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.6797134494040556}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Sorted lists                                                            *\n**************************************************************************)\n\nSet Implicit Arguments.\nGeneralizable Variables A B.\nRequire Import LibTactics LibLogic LibRelation LibWf LibList\n LibOrder LibNat.\n\n\n(* ********************************************************************** *)\n(** * Permutations of lists *)\n\nSection Permutation.\nVariable A : Type.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition *)\n\n(** We could define permutation in terms of multisets, \n    but this would impose additional constraints on the\n    type of elements. So instead, we use a definition\n    in terms of permutation of two inner segment of lists,\n    taking the reflexive-transitive closure. *)\n\nInductive permut_one : list A -> list A -> Prop :=\n  | permut_one_intro : forall l1 l2 l3 l4, \n      permut_one (l1++l2++l3++l4) (l1++l3++l2++l4).\n\nHint Constructors permut_one.\n\nDefinition permut := rtclosure permut_one.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties *)\n\n(** Permutation is an equivalence *)\n\nLemma permut_refl : forall l,\n  permut l l.\nProof using. intros. apply rtclosure_refl. Qed.\n\nLemma permut_sym : forall l1 l2,\n  permut l1 l2 -> permut l2 l1.\nProof using. \n  intros. induction H.\n  apply permut_refl.\n  applys rtclosure_last. apply IHrtclosure. inverts~ H.\nQed.\n\nLemma permut_trans : forall l2 l1 l3,\n  permut l1 l2 -> permut l2 l3 -> permut l1 l3.\nProof using. intros. apply* rtclosure_trans. Qed.\n\n(** Permutation is a congruence with respect to [++] and [::] *)\n\nLemma permut_flip : forall l1 l2,\n  permut (l1++l2) (l2++l1).\nProof using.\n  intros. lets: (permut_one_intro nil l1 l2 nil).\n  rew_app in *. apply~ rtclosure_once.\nQed.\n\nLemma permut_app_l : forall l1 l1' l2,\n  permut l1 l1' ->\n  permut (l1 ++ l2) (l1' ++ l2).\nProof using.\n  introv H. gen l2. induction H; intros.\n  apply permut_refl.\n  specializes IHrtclosure l2. inverts H.\n   rew_app in *. eapply permut_trans.\n   applys* rtclosure_step. apply permut_refl.\nQed.\n\nLemma permut_app_r : forall l1 l2 l2',\n  permut l2 l2' ->\n  permut (l1 ++ l2) (l1 ++ l2').\nProof using.\n  introv H. gen l1. induction H; intros.\n  apply permut_refl.\n  specializes IHrtclosure l1. inverts H.\n   rewrite <- app_assoc in *. eapply permut_trans. \n   applys* rtclosure_step. apply permut_refl.\nQed.\n\nLemma permut_app_lr : forall l1 l1' l2 l2',\n  permut l1 l1' -> permut l2 l2' ->\n  permut (l1 ++ l2) (l1' ++ l2').\nProof using.\n  intros. applys rtclosure_trans.\n  sapply* permut_app_l.\n  apply* permut_app_r.  \nQed.\n\nLemma permut_cons : forall x l1 l1',\n  permut l1 l1' ->\n  permut (x::l1) (x::l1').\nProof using.\n  intros. lets: (@permut_app_r (x::nil) _ _ H).\n  rew_app in *. auto.\nQed.\n\n(** Permutation are stable through list reversal *)\n\nLemma permut_rev : forall l,\n  permut l (rev l).\nProof using.\n  induction l. apply permut_refl. rew_rev.\n  lets: (@permut_flip (a::nil) (rev l)). rew_app in *.\n  apply~ (@permut_trans (a::rev l)). apply~ permut_cons. \nQed.\n\n(** Properties of elements are preserved by permutation *)\n\nLemma Forall_permut_one : forall (P:A->Prop) l1 l2, \n  Forall P l1 -> permut_one l1 l2 -> Forall P l2.\nProof using.\n  introv F Per. inverts Per.\n  lets F0 F345: (Forall_app_inv _ _ F).\n  lets F3 F45: (Forall_app_inv _ _ F345).  \n  lets F4 F5: (Forall_app_inv _ _ F45).\n  apply~ Forall_app. apply~ Forall_app. apply~ Forall_app.\nQed. \n\nLemma Forall_permut : forall (P:A->Prop) l1 l2, \n  Forall P l1 -> permut l1 l2 -> Forall P l2.\nProof using.\n  introv F1 Per. gen F1. induction Per.\n  auto. \n  autos* Forall_permut_one.\nQed. \n\nEnd Permutation.\n\nHint Resolve permut_refl permut_flip\n             permut_app_lr permut_cons.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Permutation tactic *)\n\nSection PermutationTactic.\nVariable A : Type.\nImplicit Types l : list A.\n\nLemma permut_get_1 : forall l1 l2,\n  permut (l1 ++ l2) (l1 ++ l2).\nProof using. intros. apply permut_refl. Qed.\nLemma permut_get_2 : forall l1 l2 l3,\n  permut (l1 ++ l2 ++ l3) (l2 ++ l1 ++ l3).\nProof using. \n  intros. apply rtclosure_once. \n  applys (@permut_one_intro _ nil l1 l2 l3). \nQed.\nLemma permut_get_3 : forall l1 l2 l3 l4,\n  permut (l1 ++ l2 ++ l3 ++ l4) (l2 ++ l3 ++ l1 ++ l4).\nProof using.\n  intros. do 2 rewrite <- (@app_assoc _ l2).\n  apply permut_get_2.\nQed.\nLemma permut_get_4 : forall l1 l2 l3 l4 l5,\n  permut (l1 ++ l2 ++ l3 ++ l4 ++ l5) \n         (l2 ++ l3 ++ l4 ++ l1 ++ l5).\nProof using.\n  intros. do 2 rewrite <- (@app_assoc _ l2).\n  apply permut_get_3.\nQed.\nLemma permut_get_5 : forall l1 l2 l3 l4 l5 l6,\n  permut (l1 ++ l2 ++ l3 ++ l4 ++ l5 ++ l6) \n         (l2 ++ l3 ++ l4 ++ l5 ++ l1 ++ l6).\nProof using.\n  intros. do 2 rewrite <- (@app_assoc _ l2).\n  apply permut_get_4.\nQed.\nLemma permut_get_6 : forall l1 l2 l3 l4 l5 l6 l7,\n  permut (l1 ++ l2 ++ l3 ++ l4 ++ l5 ++ l6 ++ l7) \n         (l2 ++ l3 ++ l4 ++ l5 ++ l6 ++ l1 ++ l7).\nProof using.\n  intros. do 2 rewrite <- (@app_assoc _ l2).\n  apply permut_get_5.\nQed.\n\nLemma permut_tactic_setup : forall l1 l2,\n  permut (nil ++ l1 ++ nil) (l2 ++ nil) -> permut l1 l2.\nProof using. intros. rew_list~ in H. Qed.\n\nLemma permut_tactic_keep : forall l1 l2 l3 l4,\n  permut ((l1 ++ l2) ++ l3) l4 ->\n  permut (l1 ++ (l2 ++ l3)) l4.\nProof using. intros. rew_list~ in H. Qed.\n\nLemma permut_tactic_simpl : forall l1 l2 l3 l4,\n  permut (l1 ++ l3) l4 ->\n  permut (l1 ++ (l2 ++ l3)) (l2 ++ l4).\nProof using.\n  intros. eapply permut_trans.\n  apply permut_get_2. apply~ permut_app_r.\nQed.\n\nLemma permut_tactic_trans : forall l1 l2 l3,\n  permut l3 l2 -> permut l1 l3 -> permut l1 l2.\nProof using. introv P1 P2. apply~ (permut_trans P2 P1). Qed.\n\nEnd PermutationTactic.\n\n\n(** [permut_prepare] applies to a goal of the form [permut l l']\n    and sets [l] and [l'] in the form [l1 ++ l2 ++ .. ++ nil],\n    (some of the lists [li] are put in the form [x::nil]). *)\n(* todo: improve so as to ensure no rewrite inside elements *)\n\nHint Rewrite app_assoc app_nil_l app_nil_r : permut_rew.\n\nLtac permut_lemma_get n :=\n  match nat_from_number n with\n  | 1 => constr:(permut_get_1)\n  | 2 => constr:(permut_get_2)\n  | 3 => constr:(permut_get_3)\n  | 4 => constr:(permut_get_4)\n  | 5 => constr:(permut_get_5) \n  end.\n\nLtac permut_isolate_cons :=\n  do 20 try (* todo : repeat *)\n    match goal with |- context [?x::?l] =>\n      match l with \n      | nil => fail 1\n      | _ => rewrite <- (@app_cons_one _ x l)\n      end \n    end.\n\nLtac permut_simpl_prepare :=\n   autorewrite with permut_rew;\n   permut_isolate_cons;\n   autorewrite with permut_rew;\n   apply permut_tactic_setup;\n   repeat rewrite app_assoc.\n\n\n(** [permut_simplify] simplifies a goal of the form \n    [permut l l'] where [l] and [l'] are lists built with \n    concatenation and consing, by cancelling syntactically \n    equal elements *)\n\nLtac permut_index_of l lcontainer :=\n  match constr:(lcontainer) with\n  | l ++ _ => constr:(1)\n  | _ ++ l ++ _ => constr:(2)\n  | _ ++ _ ++ l ++ _ => constr:(3)\n  | _ ++ _ ++ _ ++ l ++ _ => constr:(4)\n  | _ ++ _ ++ _ ++ _ ++ l ++ _ => constr:(5)\n  | _ ++ _ ++ _ ++ _ ++ _ ++ l ++ _ => constr:(6)\n  | _ => constr:(0) (* not found *)\n  end.\n\nLtac permut_simpl_once := \n  match goal with\n  | |- permut (_ ++ nil) _ => fail 1\n  | |- permut (_ ++ (?l ++ _)) ?l' => \n     match permut_index_of l l' with\n     | 0 => apply permut_tactic_keep\n     | ?n => let F := permut_lemma_get n in\n            eapply permut_tactic_trans; \n            [ apply F\n            | apply permut_tactic_simpl ]\n     end\n  end.\n\nLtac permut_simpl :=\n  permut_simpl_prepare;\n  repeat permut_simpl_once;\n  autorewrite with permut_rew;\n  try apply permut_refl.\n\n(* todo: permut rewrite *)\n\n\n(* ********************************************************************** *)\n(** * Sorted lists *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition *)\n\nSection Sorted.\nVariable A : Type.\nImplicit Types le : binary A.\n\nInductive sorted le : list A -> Prop :=\n  | sorted_nil : sorted le nil\n  | sorted_one : forall x, sorted le (x::nil)\n  | sorted_two : forall x y l, \n     sorted le (y::l) -> le x y ->\n     sorted le (x::y::l).\n\nDefinition rsorted le := sorted (flip le).\n\nDefinition head_of_le le x l :=\n  match l with\n  | nil => True\n  | h::_ => le x h\n  end.\n\nDefinition head_le le l1 l2 :=\n  match l1,l2 with\n  | _,nil => True\n  | nil,_ => True\n  | h1::_,h2::_ => le h1 h2\n  end.\n\nEnd Sorted.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties about sorted *)\n\nImplicit Arguments sorted [A].\nHint Unfold rsorted.\n\nSection SortedProperties.\nHint Constructors sorted.\n\nVariables (A : Type).\nVariable le : binary A.\nHint Resolve sorted_nil sorted_one.\n\nLemma sorted_inv : forall x l,\n  sorted le (x::l) -> head_of_le le x l /\\ sorted le l.\nProof using. introv H. inverts H; simpls~. Qed. \n\nLemma sorted_sub : forall x l,\n  sorted le (x::l) -> sorted le l.\nProof using. introv H. inverts~ H. Qed.\n\nLemma sorted_cons : forall l,\n  sorted le l -> forall x,\n  head_of_le le x l -> sorted le (x::l).\nProof using. introv S Hd. inverts~ S. Qed.\n\nLemma head_le_from_sorted : forall x l1 l2,\n  sorted le (x::l2) ->\n  head_le le l1 (x::l2) ->\n  head_le le (x::l1) l2.\nProof using.\n  intros. destruct l2; simpl. auto. inverts~ H.\nQed.\n\nLemma sorted_cons_head_of : forall x l,\n  sorted le (x::l) -> head_of_le le x l.\nProof using. introv H. inverts H; simpls~. Qed.\n\nLemma head_le_nil_l : forall l,\n  head_le le nil l.\nProof using. intros. unfolds. destruct~ l. Qed.\n\nLemma head_le_nil_r : forall l,\n  head_le le l nil.\nProof using. intros. unfolds. destruct~ l. Qed.\n\nLemma sorted_cons_head : forall l1 l2 x,\n  head_le le (x::l1) l2 -> \n  sorted le l2 ->\n  sorted le (x::l2).\nProof using. introv H S2. destruct l2. auto. apply~ sorted_cons. Qed.\n\nLemma head_le_flip : forall l1 l2,\n  head_le (flip le) l1 l2 = head_le le l2 l1.\nProof using. destruct l1; destruct l2; auto. Qed.\n\nLemma head_le_flip_1 : forall l1 l2,\n  head_le (flip le) l1 l2 -> head_le le l2 l1.\nProof using. intros. rewrite~ <- head_le_flip. Qed.\n\nLemma head_le_flip_2 : forall l1 l2,\n  head_le le l2 l1 -> head_le (flip le) l1 l2.\nProof using. intros. rewrite~ head_le_flip. Qed.\n\nLemma sorted_Forall_le : forall x l,\n  total_preorder le ->\n  head_of_le le x l -> sorted le l -> Forall (le x) l.\nProof using.\n  induction l; simpl; introv Tot LeH Sl. auto. constructor~.\n  lets: (sorted_sub Sl). constructor~. apply~ IHl.\n  destruct~ l; simpls~. inverts Sl. sapply* total_preorder_trans.\nQed.\n\nLemma head_of_le_Forall_le : forall x l,\n  Forall (le x) l -> head_of_le le x l.\nProof using. introv H. destruct l; simpls. auto. inverts~ H. Qed.\n\nLemma sorted_flip_flip : forall l,\n  sorted le l ->\n  sorted (flip (flip le)) l.\nProof using.\n  introv H. rewrite flip_flip. induction H.\n   constructor. constructor. apply~ sorted_cons.\nQed.\n\nEnd SortedProperties.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties about rsorted *)\n\nSection RSortedProperties.\nVariables (A : Type).\nVariable le : binary A.\nHint Resolve sorted_nil sorted_one.\nHint Constructors sorted.\n\nLemma rsorted_inv : forall x l,\n  rsorted le (x::l) -> head_of_le (flip le) x l /\\ rsorted le l.\nProof using. introv H. inverts H; simpls~. Qed. \n\nLemma head_le_from_rsorted : forall x l1 l2,\n  rsorted le (x::l2) ->\n  head_le (flip le) l1 (x::l2) ->\n  head_le (flip le) (x::l1) l2.\nProof using.\n  intros. destruct l2; simpl. auto. inverts~ H.\nQed.\n\nLemma rsorted_cons_head : forall l1 l2 x,\n  head_le (flip le) (x::l1) l2 -> \n  rsorted le l2 ->\n  rsorted le (x::l2).\nProof using. introv H S2. destruct~ l2. Qed.\n\nLemma sorted_app : forall l1 l2,\n  head_le le l1 l2 -> rsorted le l1 -> sorted le l2 -> \n  sorted le ((rev l1) ++ l2).\nProof using.\n  introv. gen l2. induction l1; introv Hd S1 S2; rew_rev. auto.\n  lets Hd1 S1': (rsorted_inv S1). clear S1.\n  apply IHl1. destruct~ l1. auto.\n  apply sorted_cons. auto. destruct~ l2.\nQed.\n\nEnd RSortedProperties.\n\nLemma rsorted_app : forall (A : Type) (le : binary A) l1 l2,\n  head_le le l2 l1 -> sorted le l1 -> rsorted le l2 -> \n  rsorted le ((rev l1) ++ l2).\nProof using.\n  unfold rsorted. intros. apply sorted_app.\n    rewrite~ head_le_flip.\n    unfolds. apply~ sorted_flip_flip.\n    auto.\nQed.\n\n\n(* ********************************************************************** *)\n(** * Sorting of a list *)\n\nSection Sorts.\nVariables (A : Type).\nImplicit Types le : binary A.\nHint Resolve sorted_nil sorted_one.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition *)\n\nDefinition sorts le l l' :=\n  permut l l' /\\ sorted le l'.\n\nDefinition rsorts le := sorts (flip le).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties *)\n\nLemma sorts_refl : forall le l,\n  sorted le l -> sorts le l l.\nProof using. split. apply permut_refl. auto. Qed.\n\nLemma rsorts_refl : forall le l,\n  rsorted le l -> rsorts le l l.\nProof using. intros. apply~ sorts_refl. Qed.\n\nLemma sorts_app_rev : forall le l1 l2,\n head_le le l1 l2 -> rsorted le l1 -> sorted le l2 ->\n sorts le (l1 ++ l2) (rev l1 ++ l2).\nProof using.\n  introv H S1 S2. split.\n  apply permut_app_l. apply permut_rev.\n  apply~ sorted_app. \nQed.\n\nLemma rsorts_app_rev : forall le l1 l2,\n head_le le l2 l1 -> sorted le l1 -> rsorted le l2 ->\n rsorts le (l1 ++ l2) (rev l1 ++ l2).\nProof using.\n  introv H S1 S2. split.\n  apply permut_app_l. apply permut_rev.\n  apply~ rsorted_app. \nQed.\n\nLemma sorts_permut : forall l1 l2 l' le,\n  sorts le l1 l' -> permut l2 l1 ->\n  sorts le l2 l'.\nProof using.\n  introv [P1 S1] Per. split~. \n  apply* (@permut_trans _ l1). \nQed.\n\nLemma rsorts_permut : forall l1 l2 l' le,\n  rsorts le l1 l' -> permut l2 l1 ->\n  rsorts le l2 l'.\nProof using. intros. apply~ (@sorts_permut l1). Qed.\n\nLemma sorts_cons : forall le l l' x,\n  sorts le l l' -> head_of_le le x l' ->\n  sorts le (x::l) (x::l').\nProof using.\n  introv [P S] Hd. split. \n  apply~ permut_cons. apply~ sorted_cons.\nQed.\n\nLemma sorts_2 : forall le l x1 x2,\n  permut l (x1::x2::nil) ->\n  le x1 x2 ->\n  sorts le l (x1::x2::nil).\nProof using.\n  intros. apply~ (@sorts_permut (x1::x2::nil)).\n  apply sorts_refl. apply sorted_cons.\n  apply sorted_one. simpls~.\nQed.\n\nLemma sorts_3 : forall le l x1 x2 x3,\n  permut l (x1::x2::x3::nil) ->\n  le x1 x2 -> le x2 x3 ->\n  sorts le l (x1::x2::x3::nil).\nProof using.\n  intros.\n   apply~ (@sorts_permut (x1::x2::x3::nil)).\n   apply sorts_refl. apply sorted_cons.\n   apply sorted_cons. apply sorted_one.\n   simpls~. simpls~.\nQed.\n\nLemma rsorts_2 : forall le l x1 x2,\n  permut l (x1::x2::nil) ->\n  le x2 x1 ->\n  rsorts le l (x1::x2::nil).\nProof using.\n  intros.\n   apply~ (@rsorts_permut (x1::x2::nil)).\n   apply rsorts_refl. applys sorted_cons.\n   apply sorted_one. unfold flip. simpls~.\nQed.\n\nLemma rsorts_3 : forall le l x1 x2 x3,\n  permut l (x1::x2::x3::nil) ->\n  le x2 x1 -> le x3 x2 ->\n  rsorts le l (x1::x2::x3::nil).\nProof using.\n  intros.\n   apply~ (@rsorts_permut (x1::x2::x3::nil)).\n   apply rsorts_refl. applys sorted_cons.\n   apply sorted_cons. apply sorted_one.\n   simpls~. simpls~.\nQed.\n\nLemma sorts_length_lt_2 : forall le l,\n  length l < 2 -> sorts le l l.\nProof using.\n  intros. apply sorts_refl. destruct~ l. \n  destruct~ l. rew_length in *. false. nat_math.\nQed.\n\nEnd Sorts.\n\n\n\n", "meta": {"author": "pleiad", "repo": "Refinements", "sha": "3a4d24329bdbb91b95a352b70db53f10cad094a1", "save_path": "github-repos/coq/pleiad-Refinements", "path": "github-repos/coq/pleiad-Refinements/Refinements-3a4d24329bdbb91b95a352b70db53f10cad094a1/TLC/LibListSorted.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.6797134493582477}}
{"text": "From Coq Require Export ssreflect.\nFrom stdpp Require Export base list relations.\n\nTactic Notation \"make_eq\" constr(t) \"as\" ident(x) ident(E) :=\n  set x := t ;\n  assert (t = x) as E by reflexivity ;\n  clearbody x.\n\nLemma take_cons {A : Type} (n : nat) (x : A) (xs : list A) :\n  (0 < n)%nat → take n (x :: xs) = x :: take (n-1)%nat xs.\nProof.\n  intros <- % Nat.succ_pred_pos. by rewrite /= - minus_n_O.\nQed.\n\nLemma drop_cons {A : Type} (n : nat) (x : A) (xs : list A) :\n  (0 < n)%nat → drop n (x :: xs) = drop (n-1)%nat xs.\nProof.\n  intros <- % Nat.succ_pred_pos. by rewrite /= - minus_n_O.\nQed.\n\nLemma nsteps_split `{R : relation A} m n x y :\n  nsteps R (m+n) x y →\n  ∃ (z : A), nsteps R m x z ∧ nsteps R n z y.\nProof.\n  revert x ; induction m as [ | m' IH ] ; intros x H.\n  - exists x. split ; [ constructor | assumption ].\n  - inversion H as [ (*…*) | sum' x_ z y_ Hxz Hzy Esum' Ex Ey ] ; clear dependent sum' x_ y_.\n    apply IH in Hzy as (ω & Hzω & Hωy).\n    exists ω. split ; first econstructor ; eassumption.\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/Base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6796789462241005}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint drop (drop_arg0 : natural) (drop_arg1 : lst) : lst\n           := match drop_arg0, drop_arg1 with\n              | x, Nil => Nil\n              | Zero, x => x\n              | Succ x, Cons y z => drop x z\n              end.\n\nTheorem drop_Nil: forall (x: natural), drop x Nil = Nil.\nProof.\n  induction x ; simpl; reflexivity.\nQed.\n\nTheorem drop_Cons: forall (x n: natural) (l: lst), drop (Succ x) (Cons n l) = drop x l.\n  induction l; induction x; simpl; reflexivity.\nQed.\n\nTheorem drop_Cons_assoc: forall (x1 x2 x3: natural) (l: lst),\n    drop x1 (drop x2 (Cons x3 l)) = drop x2 (drop x1 (Cons x3 l)).\nProof.\n  induction x1; induction x2; try (simpl; reflexivity).\n  + induction l.\n    * rewrite 2 drop_Cons. rewrite <- IHx1.\n      rewrite IHx2. rewrite 2 drop_Cons.\n      induction l.\n      - rewrite IHx1. reflexivity. \nlfind.  reflexivity.  \nAdmitted.\n\nTheorem drop_assoc : forall (x : natural) (y : natural) (z : lst), eq (drop x (drop y z)) (drop y (drop x z)).\nProof.\n  induction z.\n  + rewrite 2 drop_Cons_assoc. reflexivity. \n  + rewrite 3 drop_Nil. reflexivity. \nQed.\n\nTheorem theorem0 : forall (x : natural) (y : natural) (w : natural) (z : lst), eq (drop w (drop x (drop y z))) (drop y (drop x (drop w z))).\nProof.\n  intros.\n  rewrite (drop_assoc w x).\n  rewrite (drop_assoc w y).\n  rewrite (drop_assoc x y).\n  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/clam_lf_goal9_drop_Cons_assoc_36_drop_Nil/goal9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6796789445375124}}
{"text": "Require Import ZArith.\nRequire Import smart_common.\nRequire Import smart_bdd.\nRequire Import FMapPositive.\nRequire Import FunctionalExtensionality.\n\nInductive canonical: var -> bdd -> Prop :=\n  | Tcanonical : forall v, canonical v T\n  | Fcanonical : forall v, canonical v F\n  | Ncanonical :\n      forall v v', (v' < v)%positive ->\n      forall bt, canonical v' bt ->\n      forall bf, canonical v' bf ->\n      bt <> bf ->\n      canonical v (N v' bt bf).\n\nHint Constructors canonical.\n\nLemma bdd_interp_canonical_independent:\n  forall v b, canonical v b ->\n  forall x env,\n    bdd_interp b (PositiveMap.add v x env) = bdd_interp b env.\nProof.\n  intros v b Hcan.\n  remember v in |- *. assert (v <= v0)%positive by (subst; reflexivity). clear Heqv0.\n  generalize dependent v0.\n  induction Hcan; auto.\n  simpl; intros.\n  rewrite PositiveMap.gso by (zify; omega).\n  destruct (PositiveMap.find v' env) as [[]|].\n  - apply IHHcan1. zify; omega.\n  - apply IHHcan2. zify; omega.\n  - auto.\nQed.\n\nLemma bdd_canonical_aux1:\n  forall bt bf v,\n  forall b, canonical v b -> canonical v bt ->\n    (forall env, bdd_interp b env = bdd_interp (N v bt bf) env) ->\n    forall env, bdd_interp b env = bdd_interp bt env.\nProof.\n  intros.\n  specialize (H1 (PositiveMap.add v true env)). simpl in H1.\n  rewrite PositiveMap.gss, !bdd_interp_canonical_independent in H1; auto.\nQed.\n\nLocal Hint Resolve bdd_canonical_aux1.\n\nLemma bdd_canonical_aux2:\n  forall bt bf v,\n  forall b, canonical v b -> canonical v bf ->\n    (forall env, bdd_interp b env = bdd_interp (N v bt bf) env) ->\n    forall env, bdd_interp b env = bdd_interp bf env.\nProof.\n  intros.\n  specialize (H1 (PositiveMap.add v false env)). simpl in H1.\n  rewrite PositiveMap.gss, !bdd_interp_canonical_independent in H1; auto.\nQed.\n\nLocal Hint Resolve bdd_canonical_aux2.\n\nTheorem bdd_canonical:\n  forall a va, canonical va a ->\n  forall b vb, canonical vb b ->\n    (forall env, bdd_interp a env = bdd_interp b env) ->\n    a = b.\nProof.\n  induction 1; induction 1; subst; intro.\n  - reflexivity.\n  - specialize (H (PositiveMap.empty _)). discriminate.\n  - rewrite <- IHcanonical2, <- IHcanonical1 in H2 by eauto. tauto.\n  - specialize (H (PositiveMap.empty _)). discriminate.\n  - reflexivity.\n  - rewrite <- IHcanonical2, <- IHcanonical1 in H2 by eauto. tauto.\n  - erewrite IHcanonical2 with (b:=T), IHcanonical1 with (b:=T) in H2 by (eauto; symmetry; eauto). tauto.\n  - erewrite IHcanonical2 with (b:=F), IHcanonical1 with (b:=F) in H2 by (eauto; symmetry; eauto). tauto.\n  - destruct (Pos.compare_spec v' v'0).\n    + subst. f_equal.\n      * eapply IHcanonical1; eauto.\n        intro. specialize (H5 (PositiveMap.add v'0 true env)). simpl in H5.\n        erewrite PositiveMap.gss, !bdd_interp_canonical_independent in H5 by eauto. auto.\n      * eapply IHcanonical2; eauto.\n        intro. specialize (H5 (PositiveMap.add v'0 false env)). simpl in H5.\n        erewrite PositiveMap.gss, !bdd_interp_canonical_independent in H5 by eauto. auto.\n    + erewrite <- IHcanonical3, <- IHcanonical4 in H4 by (eauto; symmetry; eauto). tauto.\n    + erewrite IHcanonical2 with (b:=N v'0 bt0 bf0), IHcanonical1 with (b:=N v'0 bt0 bf0) in H2 by (eauto; symmetry; eauto). tauto.\n  Grab Existential Variables.\n  exact xH. exact xH. exact xH. exact xH.\nQed.\n\nLemma bdd_not_inj:\n  forall b1 b2, bdd_not b1 = bdd_not b2 -> b1 = b2.\nProof.\n  induction b1; induction b2; try reflexivity; try discriminate.\n  unfold bdd_not, memo_rec.\n  intro.\n  rewrite Fix_eq with (x:=N v0 b2_1 b2_2) in H. rewrite Fix_eq in H.\n  injection H. clear H. intros. subst.\n  f_equal; auto.\n  intros. replace g with f. easy. extensionality x'. extensionality p. auto.\n  intros. replace g with f. easy. extensionality x'. extensionality p. auto.\nQed.\n\nTheorem canonical_bdd_not:\n  forall v b, canonical v b -> canonical v (bdd_not b).\nProof.\n  induction 1; auto.\n  unfold bdd_not, memo_rec.\n  rewrite Fix_eq.\n  constructor; auto.\n  intro. apply bdd_not_inj in H3. tauto.\n  intros. replace g with f. easy. extensionality x'. extensionality p. auto.\nQed.\n\nLemma canonical_le:\n  forall v v' b, (v <= v')%positive ->\n    canonical v b ->\n    canonical v' b.\nProof.\n  destruct 2; constructor; auto.\n  zify; omega.\nQed.\n\nLemma canonical_N_check:\n  forall v bt bf,\n    canonical v bt ->\n    canonical v bf ->\n  forall v', (v < v')%positive ->\n    canonical v' (N_check v bt bf).\nProof.\n  unfold N_check. intros.\n  pose proof (bdd_eqb_iff bt bf).\n  destruct (bdd_eqb bt bf).\n  eapply canonical_le; eauto. zify; omega.\n  constructor; auto.\n  unfold not. rewrite <- H2. discriminate.\nQed.\n\nTheorem canonical_bdd_and:\n  forall b1 b2 v,\n    canonical v b1 ->\n    canonical v b2 ->\n    canonical v (bdd_and b1 b2).\nProof.\n  intros. revert b2 H0.\n  pose proof H. induction H; auto.\n  intros.\n  unfold bdd_and. unfold memo_rec.\n  rewrite Fix_eq;\n    try (intros; replace g with f; [easy|extensionality x'; extensionality p; auto]).\n  induction H4; auto.\n  unfold memo_rec.\n  rewrite Fix_eq;\n  try (intros; replace g with f; [easy|extensionality x'; extensionality p; auto]).\n  destruct (Pos.compare_spec v' v'0); eapply canonical_N_check; subst; auto.\nQed.\n\nTheorem canonical_bdd_or:\n  forall b1 b2 v,\n    canonical v b1 ->\n    canonical v b2 ->\n    canonical v (bdd_or b1 b2).\nProof.\n  intros. revert b2 H0.\n  pose proof H. induction H; auto.\n  intros.\n  unfold bdd_or. unfold memo_rec.\n  rewrite Fix_eq;\n    try (intros; replace g with f; [easy|extensionality x'; extensionality p; auto]).\n  induction H4; auto.\n  unfold memo_rec.\n  rewrite Fix_eq;\n    try (intros; replace g with f; [easy|extensionality x'; extensionality p; auto]).\n  destruct (Pos.compare_spec v' v'0); eapply canonical_N_check; subst; auto.\nQed.\n\nTheorem canonical_bdd_xor:\n  forall b1 b2 v,\n    canonical v b1 ->\n    canonical v b2 ->\n    canonical v (bdd_xor b1 b2).\nProof.\n  intros. revert b2 H0.\n  pose proof H. induction H; auto using canonical_bdd_not.\n  intros.\n  unfold bdd_xor, memo_rec.\n  rewrite Fix_eq;\n    try (intros; replace g with f; [easy|extensionality x'; extensionality p; auto]).\n  induction H4; auto.\n  unfold memo_rec.\n  rewrite Fix_eq;\n    try (intros; replace g with f; [easy|extensionality x'; extensionality p; auto]).\n  auto using canonical_bdd_not.\n  rewrite Fix_eq;\n    try (intros; replace g with f; [easy|extensionality x'; extensionality p; auto]).\n  destruct (Pos.compare_spec v' v'0); eapply canonical_N_check; subst; auto.\nQed.\n\n(* BDD ITE  *)\n\nTheorem canonical_bdd_ite:\n  forall b1 b2 b3,\n  forall v,\n    canonical v b1 ->\n    canonical v b2 ->\n    canonical v b3 ->\n    canonical v (bdd_ite b1 b2 b3).\nProof.\n  intros. revert b2 H0 b3 H1.\n  induction H; auto.\n  unfold bdd_ite, memo_rec.\n  rewrite Fix_eq;\n    try (intros; replace g with f; [easy|extensionality x'; extensionality p; auto]).\n  change (Fix (well_founded_ltof bdd bdd_size))\n  with (memo_rec (well_founded_ltof bdd bdd_size)) in *.\n  fold bdd_ite in *. unfold memo_rec.\n  intros b2 ?.\n  induction H3; auto;\n  rewrite Fix_eq;\n  try (intros; replace g with f; [easy|extensionality x'; extensionality p; auto]).\n  - intros.\n    induction H3;\n    rewrite Fix_eq;\n      try (intros; replace g with f; [easy|extensionality x'; extensionality p; auto]).\n    apply canonical_N_check; auto.\n    apply canonical_N_check; auto.\n    destruct (Pos.compare_spec v' v'0); subst; apply canonical_N_check; auto.\n  - intros.\n    induction H3;\n    rewrite Fix_eq;\n      try (intros; replace g with f; [easy|extensionality x'; extensionality p; auto]).\n    apply canonical_N_check; auto.\n    apply canonical_N_check; auto.\n    destruct (Pos.compare_spec v' v'0); subst; apply canonical_N_check; auto.\n  - intros.\n    match goal with |- context [match ?t with (_, _) => _ end] =>\n                    remember t\n    end.\n    destruct p as [[rect recf] v1].\n    assert (forall b, canonical v1 b -> canonical v1 (rect b)).\n    { destruct (Pos.compare_spec v' v'0); inversion Heqp; subst; clear Heqp; auto. }\n    assert (forall b, canonical v1 b -> canonical v1 (recf b)).\n    { destruct (Pos.compare_spec v' v'0); inversion Heqp; subst; clear Heqp; auto. }\n    assert (v1 < v)%positive.\n    { destruct (Pos.compare_spec v' v'0); inversion Heqp; subst; clear Heqp; auto. }\n    clear H H3.\n    induction H5;\n    rewrite Fix_eq;\n      try (intros; replace g with f; [easy|extensionality x'; extensionality p; auto]).\n    apply canonical_N_check; auto.\n    apply canonical_N_check; auto.\n    destruct (Pos.compare_spec v1 v'1); subst; apply canonical_N_check; auto.\nQed.\n", "meta": {"author": "braibant", "repo": "hash-consing-coq", "sha": "e7bdcb3d5e73d523e056e9e0703d5731f1a6cdf6", "save_path": "github-repos/coq/braibant-hash-consing-coq", "path": "github-repos/coq/braibant-hash-consing-coq/hash-consing-coq-e7bdcb3d5e73d523e056e9e0703d5731f1a6cdf6/smart/bdd_canonical.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6796789370920179}}
{"text": "Require Import List Permutation.\nRequire Import RelationClasses Morphisms.\nRequire Import Omega Lra Rbase.\nRequire Import Relation_Definitions Sorted.\n\nRequire Import LibUtils.\n\nImport ListNotations.\n\nSection Map.\n\n  Lemma removelast_map {A B : Type} (f:A->B) (l : list A) :\n    removelast (map f l) = map f (removelast l).\n  Proof.\n    induction l; simpl; trivial.\n    rewrite IHl.\n    destruct l; simpl; trivial.\n  Qed.\n\n  Lemma tl_map {A B : Type} (f:A->B) (l : list A) :\n    tl (map f l) = map f (tl l).\n  Proof.\n    destruct l; simpl; trivial.\n  Qed.\n\nEnd Map.\n\nSection Fold.\n  Context {A B C: Type}.\n\n  Lemma fold_right_map\n        (f:C -> A -> A) (g:B->C) (l:list B) (init:A) :\n    fold_right f init (map g l) = fold_right (fun a b => f (g a) b) init l.\n  Proof.\n    revert init.\n    induction l; simpl; trivial; intros.\n    rewrite IHl; trivial.\n  Qed.\n\nEnd Fold.\n\nLemma fold_right_assoc_abs {A} (f:A->A->A) (init:A) (l : list (list A))\n      (assoc:forall x y z : A, f x (f y z) = f (f x y) z) \n      (abs:forall x, f init x = x) :\n  fold_right f init (concat l) =\n  fold_right f init (map (fold_right f init) l).\nProof.\n  rewrite fold_right_map.\n  induction l; simpl; trivial.\n  rewrite fold_right_app.\n  rewrite <- IHl.\n  generalize (fold_right f init (concat l)); intros.\n  induction a; simpl.\n  - auto.\n  - rewrite IHa.\n    generalize (fold_right f init a1); intros.\n    now rewrite assoc.\nQed.\n\nLemma fold_right_plus_concat (l : list (list R)) :\n  fold_right Rplus R0 (concat l) =\n  fold_right Rplus R0 (map (fold_right Rplus R0) l).\nProof.\n  apply fold_right_assoc_abs; intros; lra.\nQed.\n\nLemma fold_right_plus_acc f acc l :\n  fold_right (fun (a : nat) (b : R) => f a + b)%R acc l =\n  (fold_right (fun (a : nat) (b : R) => f a + b)%R R0 l + acc)%R.\nProof.\n  induction l; simpl.\n  - lra.\n  - rewrite IHl; lra.\nQed.\n\nSection Seq.\n  \n  Lemma seq_shiftn {A:Type} (l:list A)  (n:nat) :\n    seq n (length l) = map (fun x => x + n)%nat (seq 0 (length l)).\n  Proof.\n    induction n; simpl.\n    - erewrite map_ext.\n      + erewrite map_id; trivial.\n      + intros; omega.\n    - rewrite <- seq_shift.\n      rewrite IHn.\n      rewrite map_map.\n      apply map_ext; intros.\n      omega.\n  Qed.\n\n  Lemma list_as_nthseq_start {A:Type} (l:list A) (d:A) (c:nat) : l = map (fun n => nth (n-c) l d) (seq c%nat (length l)).\n  Proof.\n    induction l; simpl; trivial.\n    rewrite <- seq_shift.\n    rewrite map_map.\n    simpl.\n    replace (c-c)%nat with 0%nat by omega.\n    rewrite IHl.\n    f_equal.\n    rewrite map_length.\n    rewrite seq_length.\n    apply map_ext_in; intros x inn.\n    apply in_seq in inn.\n    rewrite <- IHl.\n    destruct c.\n    - f_equal; omega.\n    - assert (x-c > 0)%nat by omega.\n      replace (x - S c)%nat with ((x - c) - 1)%nat by omega.\n      destruct (x-c)%nat.\n      + omega.\n      + f_equal; omega.\n  Qed.\n  \n  Lemma list_as_nthseq {A:Type} (l:list A) (d:A) : l = map (fun n => nth n l d) (seq 0%nat (length l)).\n  Proof.\n    rewrite (list_as_nthseq_start l d 0) at 1.\n    apply map_ext; intros.\n    f_equal; omega.\n  Qed.\n\n  Lemma seq_Sn s n : seq s (S n) = seq s n ++ [(s+n)]%nat.\n  Proof.\n    replace (S n) with (n + 1)%nat by omega.\n    rewrite seq_plus.\n    simpl; trivial.\n  Qed.\n\nLemma tl_seq n : tl (seq 0 n) = seq 1 (n-1).\nProof.\n  destruct n; simpl; trivial.\n  rewrite Nat.sub_0_r.\n  trivial.\nQed.\n\nLemma removelast_seq (n:nat) : removelast (seq 0 n) = seq 0 (n-1).\nProof.\n  induction n; simpl; trivial.\n  rewrite Nat.sub_0_r.\n  rewrite <- seq_shift.\n  rewrite removelast_map.\n  rewrite IHn.\n  repeat rewrite seq_shift.\n  destruct n; simpl; trivial.\n  rewrite Nat.sub_0_r.\n  trivial.\nQed.\n\nLemma seq_shiftn_map start len : seq start len = map (plus start) (seq 0 len).\nProof.\n  induction start; simpl.\n  - rewrite map_id; trivial.\n  - rewrite <- seq_shift.\n    rewrite IHstart.\n    rewrite map_map.\n    trivial.\nQed.\n\nEnd Seq.\n\nSection fp.\n\n  Lemma ForallOrdPairs_impl {A:Type} (R:A->A->Prop) (l:list A) (f:A->A) :\n    ForallOrdPairs R l ->\n    ForallOrdPairs (fun x y => R x y -> R (f x) (f y)) l ->\n    ForallOrdPairs R (map f l).\n  Proof.\n    induction l; intros FP; inversion FP; clear FP; subst; intros FP; simpl.\n    - constructor.\n    - inversion FP; clear FP; subst.\n      constructor.\n      + rewrite Forall_forall in *.\n        intros x inn.\n        apply in_map_iff in inn.\n        destruct inn as [xx [eqxx inxx]]; subst.\n        auto.\n      + intuition.\n  Qed.\n\n  Lemma ForallPairs_all {A:Type} (R:A->A->Prop) (l:list A) :\n    (forall x1 x2, R x1 x2) -> ForallPairs R l.\n  Proof.\n    firstorder.\n  Qed. \n\nEnd fp.\n\nLemma nth_tl {A} idx (l:list A) d : nth idx (tl l) d = nth (S idx) l d.\nProof.\n  destruct l; simpl; trivial.\n  destruct idx; trivial.\nQed.\n\nLemma nth_removelast_in {A} idx (l:list A) d :\n  idx < pred (length l) ->\n  nth idx (removelast l) d = nth idx l d.\nProof.\n  revert idx.\n  induction l; simpl; trivial; intros idx inn.\n  destruct l.\n  - destruct idx; simpl in *; omega.\n  - simpl in *.\n    destruct idx; trivial.\n    rewrite IHl by omega.\n    trivial.\nQed.\n\nLemma nth_last {A} (l:list A) d: nth (pred (length l)) l d = last l d.\nProof.\n  induction l; simpl; trivial.\n  destruct l; simpl in *; trivial.\nQed.\n\nLemma nth_hd {A} (l:list A) d: nth 0 l d = hd d l.\nProof.\n  destruct l; simpl in *; trivial.\nQed.\n\nLemma hd_app {A} (l1 l2:list A) d : l1 <> nil -> hd d (l1 ++ l2) = hd d l1.\nProof.\n  induction l1; simpl; congruence.\nQed.\n\nLemma last_rev {A} (l:list A) d : last l d = hd d (rev l).\nProof.\n  induction l; trivial.\n  simpl rev.\n  destruct l; trivial.\n  rewrite hd_app; trivial.\n  intros eqq.\n  apply (f_equal (@length A)) in eqq.\n  simpl in eqq.\n  rewrite app_length in eqq.\n  simpl in eqq.\n  omega.\nQed.\n\nLemma last_app {A} (l1 l2:list A) d : l2 <> nil -> last (l1 ++ l2) d = last l2 d.\nProof.\n  intros.\n  repeat rewrite last_rev.\n  rewrite rev_app_distr.\n  rewrite hd_app; trivial.\n  intro eqq; apply H.\n  apply (f_equal (@rev A)) in eqq.\n  rewrite rev_involutive in eqq.\n  trivial.\nQed.\n\nLemma last_cons {A} (x:A) l y : last (x::l) y = last l x.\nProof.\n  revert y.\n  induction l; simpl; trivial; intros.\n  destruct l; trivial.\n  simpl in *.\n  apply IHl.\nQed.\n\nLemma seq_last s n d :\n  (n > 0)%nat ->\n  last (seq s n) d = (s+n-1)%nat.\nProof.\n  intros.\n  destruct n.\n  - simpl; omega.\n  - rewrite seq_Sn.\n    rewrite last_app by congruence.\n    simpl.\n    omega.\nQed.\n\nLemma last_map {A B} (f:A->B) (l:list A) d : last (map f l) (f d) = f (last l d).\nProof.\n  induction l; simpl; trivial.\n  destruct l; simpl; trivial.\nQed.\n\nLemma map_nth_in {A B} (f:A->B) l d1 n d2 :\n  (n < length l)%nat ->\n  nth n (map f l) d1 = f (nth n l d2).\nProof.\n  revert n.\n  induction l; simpl.\n  - destruct n; omega.\n  - destruct n; trivial.\n    intros; eauto.\n    rewrite IHl; trivial; omega.\nQed.\n\nLemma map_nth_in_exists {A B} (f:A->B) l d1 n :\n  (n < length l)%nat ->\n  exists d2,\n  nth n (map f l) d1 = f (nth n l d2).\nProof.\n  revert n.\n  induction l; simpl.\n  - destruct n; omega.\n  - destruct n; trivial.\n    + intros; eauto.\n    + intros.\n      destruct (IHl n).\n      * omega.\n      * rewrite H0.\n        eauto.\nQed.\n\nLemma nth_in_default {A} (l:list A) d1 d2 n :\n  (n < length l)%nat ->\n  nth n l d1 = nth n l d2.\nProof.\n  revert n.\n  induction l; simpl.\n  - destruct n; omega.\n  - destruct n; trivial.\n    + intros; eauto.\n      rewrite (IHl n); trivial.\n      omega.\nQed.\n\nLemma Forall_app_iff {A} {P:A->Prop} {l1 l2} :\n  Forall P (l1 ++ l2) <->\n  Forall P l1 /\\ Forall P l2.\nProof.\n  repeat rewrite Forall_forall.\n  intuition.\n  apply in_app_iff in H.\n  intuition.\nQed.\n       \nLemma StronglySorted_app_inv {A} {R:relation A} {l1 l2} :\n  StronglySorted R (l1 ++ l2) ->\n  StronglySorted R l1 /\\ StronglySorted R l2.\nProof.\n  Hint Constructors StronglySorted : list.\n  revert l2.\n  induction l1; intros l2 ss; simpl in *.\n  - simpl in *; split; trivial with list.\n  - inversion ss; subst; clear ss.\n    destruct (IHl1 _ H1).\n    split; trivial.\n    constructor; trivial.\n    apply Forall_app_iff in H2.\n    tauto.\nQed.\n\nLemma StronglySorted_sub {A} (R1 R2:relation A) :\n    subrelation R1 R2 ->\n    forall l, StronglySorted R1 l -> StronglySorted R2 l.\nProof.\n  Hint Constructors StronglySorted : list.\n  intros sub.\n  induction l; simpl; intros ssl; trivial with list.\n  inversion ssl; clear ssl; subst.\n  simpl in *.\n  constructor.\n  - apply IHl; intuition.\n  - rewrite Forall_forall in *.\n    eauto.\nQed.\n  \nLemma StronglySorted_map_in {A B} (R1:relation A) (R2:relation B) (f:A->B) l :\n  (forall x y, In x l /\\ In y l -> R1 x y -> R2 (f x) (f y)) ->\n  StronglySorted R1 l -> StronglySorted R2 (map f l).\nProof.\n  Hint Constructors StronglySorted : list.\n  intros prop.\n  induction l; simpl; intros ssl; trivial with list.\n  inversion ssl; clear ssl; subst.\n  simpl in *.\n  constructor.\n  - apply IHl; intuition.\n  - rewrite Forall_forall in *.\n    intros x inn.\n    apply in_map_iff in inn.\n    destruct inn as [a' [eqq inn]].\n    subst; auto.\nQed.\n\nLemma StronglySorted_map {A B} (R1:relation A) (R2:relation B) (f:A->B) :\n  Proper (R1 ==> R2) f ->\n  forall l,\n    StronglySorted R1 l -> StronglySorted R2 (map f l).\nProof.\n  intros.\n  eapply StronglySorted_map_in; eauto.\nQed.\n\nLemma StronglySorted_compose {A B} R (f:A->B) (l:list A) :\n  StronglySorted R (map f l) <->\n  StronglySorted (fun x y => R (f x) (f y)) l.\nProof.\n  induction l; simpl.\n  - intuition.\n  - split; inversion 1; subst; constructor; intuition.\n    + now rewrite Forall_map in H3.\n    + now rewrite Forall_map.\nQed.\n\nLemma StronglySorted_break {A} R (l:list A) x :\n  StronglySorted R l ->\n  In x l ->\n  exists b c, l = b++x::c /\\ Forall (fun y => R y x) b /\\ Forall (R x) c.\nProof.\n  induction l; simpl; intros ss inn; [tauto | ].\n  invcs ss.\n  destruct inn.\n  - subst.\n    exists nil, l.\n    simpl.\n    intuition.\n  - destruct IHl as [b [c [p1 [p2 p3]]]]; trivial.\n    subst.\n    exists (a::b), c.\n    simpl; intuition.\n    constructor; trivial.\n    rewrite Forall_forall in H2.\n    specialize (H2 x).\n    rewrite in_app_iff in H2; simpl in H2.\n    eauto.\nQed.\n\nLemma StronglySorted_nth_lt {A} R (l:list A) idx1 idx2 d1 d2 :\n  StronglySorted R l ->\n  (idx2 < length l)%nat ->\n  (idx1 < idx2)%nat ->\n  R (nth idx1 l d1) (nth idx2 l d2).\nProof.\n  intros.\n  destruct (@nth_split _ idx1 l d1)\n           as [l1 [l2 [leqq l1len]]]\n  ; [ omega | ].\n  rewrite leqq in H.\n  apply StronglySorted_app_inv in H.\n  destruct H as [ _ ssl2].\n  inversion ssl2; clear ssl2; subst.\n  rewrite leqq in *.\n  rewrite app_length in H0.\n  simpl in H0.\n  revert H4.\n  generalize (nth (length l1) l d1).\n  clear l leqq.\n  intros a Fa.\n  rewrite Forall_forall in Fa.\n  apply Fa.\n  rewrite app_nth2 by omega.\n  simpl.\n  case_eq (idx2 - length l1); try omega.\n  intros.\n  apply nth_In.\n  omega.\nQed.\n\nLemma StronglySorted_nth_le {A} R (l:list A) idx1 idx2 d1 d2 :\n  reflexive _ R ->\n  StronglySorted R l ->\n  (idx2 < length l)%nat ->\n  (idx1 <= idx2)%nat ->\n  R (nth idx1 l d1) (nth idx2 l d2).\nProof.\n  intros refl ?? leq.\n  destruct leq.\n  - erewrite nth_in_default; try apply refl.\n    trivial.\n  - apply StronglySorted_nth_lt; trivial.\n    omega.\nQed.\n\nSection bucket.\n\n  Context {A:Type} {R:relation A} (R_dec : forall x y, {R x y} + {~ R x y}).\n\n  Fixpoint find_bucket (needle:A) (haystack:list A)\n    := match haystack with\n       | x::((y::_) as more) => if R_dec x needle\n                       then if R_dec needle y\n                            then Some (x,y)\n                            else find_bucket needle more\n                       else None\n       | _ => None\n       end.\n  \n  Lemma find_bucket_break {needle l a1 a2}:\n    find_bucket needle l = Some (a1, a2) ->\n      exists l1 l2,\n        l = l1 ++ [a1; a2] ++ l2.\n  Proof.\n    induction l; simpl; try discriminate.\n    destruct l; try discriminate.\n    destruct (R_dec a needle); try discriminate.\n    destruct (R_dec needle a0).\n    - inversion 1; subst.\n      exists nil, l.\n      reflexivity.\n    - intros HH.\n      destruct (IHl HH) as [l1 [l2 eqq]].\n      rewrite eqq.\n      exists (a::l1), l2.\n      reflexivity.\n  Qed.\n\n  Lemma middle_find_bucket needle l1 l2 a1 a2:\n    transitive _ R ->\n    antisymmetric _ R ->\n    StronglySorted R (l1++[a1]) ->\n    R a1 needle ->\n    R needle a2 ->\n    ~ R needle a1 ->\n    find_bucket needle (l1 ++ a1::a2::l2) = Some (a1, a2).\n  Proof.\n    intros trans antisymm.\n    intros sorted r1 r2 nr1.\n    revert sorted.\n    induction l1; intros sorted.\n    - simpl.\n      destruct (R_dec a1 needle); [ | tauto].\n      destruct (R_dec needle a2); [ | tauto].\n      trivial.\n    - simpl in *.\n      inversion sorted; clear sorted; subst.\n      specialize (IHl1 H1).\n      rewrite IHl1; trivial.\n      destruct (R_dec a needle).\n      + destruct l1; simpl.\n        * destruct (R_dec needle a1); tauto.\n        * destruct (R_dec needle a0); trivial.\n          elim nr1.\n          apply (trans _ a0); trivial.\n          inversion H1; clear H1; subst.\n          rewrite Forall_forall in H4.\n          apply H4.\n          rewrite in_app_iff.\n          simpl; tauto.\n      + rewrite Forall_forall in H2.\n        elim n.\n        apply (trans _ a1); trivial.\n        apply H2.\n        rewrite in_app_iff.\n        simpl; tauto.\n  Qed.\n                 \n  Lemma find_bucket_nth_finds needle l idx d1 d2:\n    transitive _ R ->\n    antisymmetric _ R ->\n    StronglySorted R l ->\n    S idx < length l ->\n    R (nth idx l d1) needle ->\n    R needle (nth (S idx) l d2) ->\n    ~ R needle (nth idx l d1) ->\n    find_bucket needle l = Some (nth idx l d1, nth (S idx) l d2).\n  Proof.\n    intros trans antisymm ss idx_bound.\n    assert (idx_bound':idx < length l) by omega.\n    destruct (nth_split l d1 idx_bound') as [l1 [l2 [eqq leneq]]].\n    revert eqq.\n    generalize (nth idx l d1); intros a1.\n    intros eqq r1 r2 nr1.\n    subst.\n    rewrite app_nth2 in * by omega.\n    replace ((S (length l1) - length l1)) with 1 in * by omega.\n    rewrite app_length in idx_bound.\n    simpl in *.\n    destruct l2; simpl in *; [ omega | ].\n    apply middle_find_bucket; trivial.\n    replace (l1 ++ a1 :: a :: l2) with ((l1 ++ a1::nil) ++ (a :: l2)) in ss.\n    - apply StronglySorted_app_inv in ss.\n      tauto.\n    - rewrite app_ass; simpl; trivial.\n  Qed.\n\n  Lemma find_bucket_needle_in needle l a1 a2:\n    find_bucket needle l = Some (a1, a2) ->\n    R a1 needle /\\ R needle a2.\n  Proof.\n    induction l; simpl; try discriminate.\n    destruct l; try discriminate.\n    destruct (R_dec a needle); try discriminate.\n    destruct (R_dec needle a0).\n    - inversion 1; subst.\n      tauto.\n    - intuition.\n  Qed.\n\n  Lemma find_bucket_bucket_in needle l a1 a2 d1 d2:\n    reflexive _ R ->\n    StronglySorted R l ->\n    find_bucket needle l = Some (a1, a2) ->\n    R (hd d1 l) a1 /\\ R a2 (last l d2).\n  Proof.\n    intros refl ssl eqq1.\n    destruct (find_bucket_break eqq1)\n      as [l1 [l2 eqq2]].\n    replace (l1 ++ [a1; a2] ++ l2) with ((l1 ++ a1::nil) ++ (a2::l2)) in eqq2.\n    - subst.\n      apply StronglySorted_app_inv in ssl.\n      destruct ssl as [ssl1 ssl2].\n      split.\n      + destruct l1; simpl.\n        * apply refl.\n        * inversion ssl1; subst.\n          rewrite Forall_forall in H2.\n          apply H2.\n          rewrite in_app_iff; simpl; tauto.\n      + inversion ssl2; clear ssl2; subst.\n        rewrite last_app by congruence.\n        rewrite Forall_forall in H2.\n        simpl.\n        destruct l2.\n        * apply refl.\n        * apply H2.\n          clear.\n          { revert a.\n            induction l2.\n            - simpl; tauto.\n            - simpl in *.\n              eauto.\n          } \n    - rewrite app_ass; simpl; reflexivity.\n  Qed.\n\n  Lemma find_bucket_bounded_le_exists a b l (needle:A) :\n    (forall x y, R x y \\/ R y x) ->\n    R a needle ->\n    R needle b ->\n    exists lower upper,\n    find_bucket needle (a::l++[b]) = Some (lower, upper).\n  Proof.\n    intros total r1 r2.\n    simpl.\n    destruct (R_dec a needle); [ | tauto].\n    induction l; simpl.\n    - destruct (R_dec needle b); [ | tauto].\n      eauto.\n    - destruct (IHl) as [lower [upper eqq]].\n      destruct (R_dec needle a0).\n      + eauto.\n      + clear IHl r.\n        { destruct (R_dec a0 needle).\n          - destruct l; simpl in *.\n            + destruct (R_dec needle b); simpl; eauto.\n            + destruct (R_dec needle a1); eauto.\n          - destruct (total needle a0); tauto.\n        } \n  Qed.\n\nEnd bucket.\n\nLemma StronglySorted_seq s n : StronglySorted lt (seq s n).\nProof.\n  revert s.\n  induction n; intros s; simpl.\n  - constructor.\n  - constructor; trivial.\n    rewrite Forall_forall; intros.\n    apply in_seq in H.\n    omega.\nQed.\n\nLemma length_S_tl {A : Type} (l : list A) :\n  l <> nil ->\n  length l = S (length (tl l)).\nProof.\n  intros.\n  destruct l; simpl; congruence.\nQed.\n\nLemma tl_length {A : Type} (l : list A) :\n  length (tl l) = pred (length l).\nProof.\n  intros.\n  destruct l; simpl; congruence.\nQed.\n\nLemma removelast_length {A : Type} (l : list A) :\n  length (removelast l) = pred (length l).\nProof.\n  induction l; trivial.\n  destruct l; trivial.\n  simpl in *.\n  rewrite IHl; trivial.\nQed.\n\nSection combining.\n\nLemma combine_nth_in {A B : Type} (l : list A) (l' : list B) (n : nat) (x : A) (y : B) :\n  n < min (length l) (length l') ->\n  nth n (combine l l') (x, y) = (nth n l x, nth n l' y).\nProof.\n  revert l' n.\n  induction l; simpl; intros l' n nlt.\n  - omega.\n  - destruct l'; simpl in *.\n    + omega.\n    + destruct n; simpl; trivial.\n      apply IHl.\n      omega.\nQed.\n\nLemma combine_map {A B C D:Type} (f:A->C) (g:B->D) (l1:list A) (l2:list B) :\n  combine (map f l1) (map g l2) = map (fun '(x,y) => (f x, g y)) (combine l1 l2).\nProof.\n  revert l2.\n  induction l1; intros l2; simpl; trivial.\n  destruct l2; simpl; trivial.\n  f_equal.\n  auto.\nQed.\n\nLemma combine_self {A:Type} (l:list A) :\n  combine l l = map (fun x => (x,x)) l.\nProof.\n  induction l; simpl; trivial.\n  f_equal; trivial.\nQed.\n\nLemma combine_nil_l {A B} (l:list B) : combine (@nil A) l = nil.\nProof.\n  reflexivity.\nQed.\n\nLemma combine_nil_r {A B} (l:list A) : combine l (@nil B) = nil.\nProof.\n  destruct l; trivial.\nQed.\n\nLemma combine_swap {A B} (l1:list A) (l2:list B) : combine l1 l2 = map (fun xy => (snd xy, fst xy)) (combine l2 l1).\nProof.\n  revert l2; induction l1; simpl; intros\n  ; destruct l2; simpl; trivial.\n  rewrite IHl1; trivial.\nQed.\n\nLemma combine_domain_eq {A B} (x:list A) (y:list B) :\n  length x = length y -> domain (combine x y) = x.\nProof.\n  revert y.\n  induction x; destruct y; simpl in *; intros\n  ; try easy.\n  inversion H.\n  rewrite IHx; trivial.\nQed.    \n\nLemma list_prod_map {A B C D:Type} (f:A->C) (g:B->D) (l1:list A) (l2:list B) :\n  list_prod (map f l1) (map g l2) = map (fun '(x,y) => (f x, g y)) (list_prod l1 l2).\nProof.\n  revert l2.\n  induction l1; intros l2; simpl; trivial.\n  rewrite map_app.\n  repeat rewrite map_map.\n  rewrite IHl1.\n  trivial.\nQed.\n\nLemma list_prod_nil_l {A B} (l:list B) : list_prod (@nil A) l = nil.\nProof.\n  reflexivity.\nQed.\n\nLemma list_prod_nil_r {A B} (l:list A) : list_prod l (@nil B) = nil.\nProof.\n  induction l; trivial.\nQed.\n\nLemma list_prod_cons2_pred {A B} (l1:list A) a (l2:list B) :\n  Permutation (list_prod l1 (a :: l2)) (map (fun x : A => (x, a)) l1 ++ list_prod l1 l2).\nProof.\n  revert a l2.\n  induction l1; simpl; intros.\n  - reflexivity.\n  - rewrite IHl1.\n    apply Permutation_cons; trivial.\n    repeat rewrite <- app_ass.\n    apply Permutation_app; [ | reflexivity ].\n    rewrite Permutation_app_swap.\n    reflexivity.\nQed.\n\nLemma list_prod_swap {A B} (l1:list A) (l2:list B) : Permutation (list_prod l1 l2) (map (fun xy => (snd xy, fst xy)) (list_prod l2 l1)).\nProof.\n  revert l1; induction l2; simpl; intros.\n  - rewrite list_prod_nil_r; simpl.\n    reflexivity.\n  - rewrite map_app.\n    rewrite <- IHl2.\n    rewrite map_map; simpl.\n    apply list_prod_cons2_pred.\nQed.\n\nInstance list_prod_perm_proper1 {A B} : Proper ((@Permutation A) ==> eq ==> (@Permutation (A*B))) (@list_prod A B).\nProof.\n  intros l1 l1' perm1 l2' l2 eqq; subst.\n  revert l1 l1' perm1.\n  apply Permutation_ind_bis; intros.\n  - reflexivity.\n  - simpl.\n    rewrite H0; reflexivity.\n  - simpl.\n    rewrite H0.\n    repeat rewrite <- app_ass.\n    apply Permutation_app; [ | reflexivity ].\n    rewrite Permutation_app_swap.\n    reflexivity.\n  - etransitivity; eauto.\nQed.\n\nGlobal Instance list_prod_perm_proper {A B} : Proper ((@Permutation A) ==> (@Permutation B) ==> (@Permutation (A*B))) (@list_prod A B).\nProof.\n  intros l1 l1' perm1 l2 l2' perm2.\n  transitivity (list_prod l1' l2).\n  - apply list_prod_perm_proper1; trivial.\n  - rewrite (list_prod_swap l1' l2).\n    rewrite (list_prod_swap l1' l2').\n    apply Permutation_map.\n    apply list_prod_perm_proper1; trivial.\nQed.\n\nLemma combine_incl_list_prod {A B} (l1:list A) (l2:list B) : incl (combine l1 l2) (list_prod l1 l2).\nProof.\n  intros [x y] inn.\n  apply in_prod_iff.\n  split.\n  - eapply in_combine_l; eauto.\n  - eapply in_combine_r; eauto.\nQed.\n\nEnd combining.\n\nDefinition adjacent_pairs {A:Type} (l:list A) := (combine l (tl l)).\n\nDefinition adjacent_pairs_alt {A:Type} (l:list A) := (combine (removelast l) (tl l)).\n\nLemma adjacent_pairs_alt_eq {A:Type} (l:list A) :\n  adjacent_pairs l = adjacent_pairs_alt l.\nProof.\n  unfold adjacent_pairs, adjacent_pairs_alt.\n  induction l; simpl; trivial.\n  destruct l; simpl in *; trivial.\n  f_equal.\n  trivial.\nQed.\n\nLemma adjacent_pairs_length {A:Type} (l:list A) : length (adjacent_pairs l) = pred (length l).\nProof.\n  unfold adjacent_pairs.\n  rewrite combine_length.\n  rewrite tl_length.\n  rewrite Nat.min_r; trivial.\n  omega.\nQed.\n\nLemma adjacent_pairs_nth_in {A:Type} n (l:list A) d1 d2 :\n  S n < length l ->\n  nth n (adjacent_pairs l) (d1,d2) = (nth n l d1, nth (S n) l d2).\nProof.\n  intros.\n  unfold adjacent_pairs.\n  rewrite combine_nth_in.\n  - rewrite nth_tl; trivial.\n  - rewrite tl_length.\n    rewrite Nat.min_r; omega.\nQed.\n\nLemma adjacent_pairs_map {A B:Type} (f:A->B) (l:list A) :\n  adjacent_pairs (map f l) = map (fun '(x,y) => (f x, f y)) (adjacent_pairs l).\nProof.\n  unfold adjacent_pairs.\n  rewrite tl_map, combine_map.\n  trivial.\nQed.\n\nLemma adjacent_pairs_seq s n :\n  adjacent_pairs (seq s n) = map (fun i => (i, S i)) (seq s (pred n)).\nProof.\n  unfold adjacent_pairs.\n  revert s.\n  induction n; simpl; intros s; trivial.\n  destruct n; simpl; trivial.\n  f_equal.\n  apply IHn.\nQed.\n", "meta": {"author": "CertRL", "repo": "CertRLanon", "sha": "ba50abfb13c9c49abda8ffaad23fe76dcd4bf6ec", "save_path": "github-repos/coq/CertRL-CertRLanon", "path": "github-repos/coq/CertRL-CertRLanon/CertRLanon-ba50abfb13c9c49abda8ffaad23fe76dcd4bf6ec/coq/utils/ListAdd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.8289388062084421, "lm_q1q2_score": 0.6796414030904236}}
{"text": "Require Import Basics.\nRequire Import Pos.Core.\n\nLocal Open Scope positive_scope.\n\n(** ** Specification of [succ] in term of [add] *)\n\nLemma pos_add_1_r p : p + 1 = pos_succ p.\nProof.\n  by destruct p.\nQed.\n\nLemma pos_add_1_l p : 1 + p = pos_succ p.\nProof.\n  by destruct p.\nQed.\n\n(** ** Specification of [add_carry] *)\n\nTheorem pos_add_carry_spec p q : pos_add_carry p q = pos_succ (p + q).\nProof.\n  revert q.\n  induction p; destruct q; simpl; by apply ap.\nQed.\n\n(** ** Commutativity *)\n\nTheorem pos_add_comm p q : p + q = q + p.\nProof.\n  revert q.\n  induction p; destruct q; simpl; apply ap; trivial.\n  rewrite 2 pos_add_carry_spec; by apply ap.\nQed.\n\n(** ** Permutation of [add] and [succ] *)\n\nTheorem pos_add_succ_r p q : p + pos_succ q = pos_succ (p + q).\nProof.\n  revert q.\n  induction p; destruct q; simpl; apply ap;\n   auto using pos_add_1_r; rewrite pos_add_carry_spec; auto.\nQed.\n\nTheorem pos_add_succ_l p q : pos_succ p + q = pos_succ (p + q).\nProof.\n  rewrite pos_add_comm, (pos_add_comm p). apply pos_add_succ_r.\nQed.\n\nDefinition pos_add_succ p q : p + pos_succ q = pos_succ p + q.\nProof.\n  by rewrite pos_add_succ_r, pos_add_succ_l.\nDefined.\n\nDefinition pos_add_carry_spec_l q r\n  : pos_add_carry q r = pos_succ q + r.\nProof.\n  by rewrite pos_add_carry_spec, pos_add_succ_l.\nQed.\n\nDefinition pos_add_carry_spec_r q r\n  : pos_add_carry q r = q + pos_succ r.\nProof.\n  by rewrite pos_add_carry_spec, pos_add_succ_r.\nDefined.\n\n(** ** No neutral elements for addition *)\nLemma pos_add_no_neutral p q : q + p <> p.\nProof.\n  revert q.\n  induction p as [ |p IHp|p IHp]; intros [ |q|q].\n  1,3: apply x0_neq_xH.\n  1: apply x1_neq_xH.\n  1,3: apply x1_neq_x0.\n  2,4: apply x0_neq_x1.\n  1,2: intro H; apply (IHp q).\n  1: apply x0_inj, H.\n  apply x1_inj, H.\nQed.\n\n(** * Injectivity of pos_succ *)\nLemma pos_succ_inj n m : pos_succ n = pos_succ m -> n = m.\nProof.\n  revert m.\n  induction n as [ | n x | n x]; induction m as [ | m y | m y].\n  + reflexivity.\n  + intro p.\n    destruct (x0_neq_x1 p).\n  + intro p.\n    simpl in p.\n    apply x0_inj in p.\n    destruct m.\n    1,3: destruct (xH_neq_x0 p).\n    destruct (xH_neq_x1 p).\n  + intro p.\n    destruct (x1_neq_x0 p).\n  + simpl.\n    intro p.\n    by apply ap, x1_inj.\n  + intro p.\n    destruct (x1_neq_x0 p).\n  + intro p.\n    cbn in p.\n    apply x0_inj in p.\n    destruct n.\n    1,3: destruct (x0_neq_xH p).\n    destruct (x1_neq_xH p).\n  + intro p.\n    cbn in p.\n    destruct (x0_neq_x1 p).\n  + intro p.\n    apply ap, x, x0_inj, p.\nDefined.\n\n(** ** Addition is associative *)\n\nTheorem pos_add_assoc p q r : p + (q + r) = p + q + r.\nProof.\n  revert q r.\n  induction p.\n  + intros [|q|q] [|r|r].\n    all: try reflexivity.\n    all: simpl.\n    1,2: by destruct r.\n    1,2: apply ap; symmetry.\n    1: apply pos_add_carry_spec.\n    1: apply pos_add_succ_l.\n    apply ap.\n    rewrite pos_add_succ_l.\n    apply pos_add_carry_spec.\n  + intros [|q|q] [|r|r].\n    all: try reflexivity.\n    all: cbn; apply ap.\n    3,4,6: apply IHp.\n    1: apply pos_add_1_r.\n    1: symmetry; apply pos_add_carry_spec_r.\n    1: apply pos_add_succ_r.\n    rewrite 2 pos_add_carry_spec_l.\n    rewrite <- pos_add_succ_r.\n    apply IHp.\n  + intros [|q|q] [|r|r].\n    all: cbn; apply ap.\n    1: apply pos_add_1_r.\n    1: apply pos_add_carry_spec_l.\n    1: apply pos_add_succ.\n    1: apply pos_add_carry_spec.\n    1: apply IHp.\n    2: symmetry; apply pos_add_carry_spec_r.\n    1,2: rewrite 2 pos_add_carry_spec, ?pos_add_succ_l.\n    1,2: apply ap, IHp.\n    rewrite ?pos_add_carry_spec_r.\n    rewrite pos_add_succ.\n    apply IHp.\nQed.\n\n(** ** One is neutral for multiplication *)\n\nLemma pos_mul_1_l p : 1 * p = p.\nProof.\n  reflexivity.\nQed.\n\nLemma pos_mul_1_r p : p * 1 = p.\nProof.\n  induction p; cbn; trivial; by apply ap.\nQed.\n\n(** pos_succ and doubling functions *)\n\nLemma pos_pred_double_succ n\n  : pos_pred_double (pos_succ n) = n~1.\nProof.\n  induction n as [|n|n nH].\n  all: trivial.\n  cbn; apply ap, nH.\nQed.\n\nLemma pos_succ_pred_double n\n  : pos_succ (pos_pred_double n) = n~0.\nProof.\n  induction n as [|n nH|n].\n  all: trivial.\n  cbn; apply ap, nH.\nQed.\n\n(** ** Iteration and pos_succ *)\nLemma pos_iter_succ_l {A} (f : A -> A) p a\n  : pos_iter f (pos_succ p) a = f (pos_iter f p a).\nProof.\n  unfold pos_iter.\n  by rewrite pos_peano_ind_beta_pos_succ.\nQed.\n\nLemma pos_iter_succ_r {A} (f : A -> A) p a\n  : pos_iter f (pos_succ p) a = pos_iter f p (f a).\nProof.\n  revert p f a.\n  serapply pos_peano_ind.\n  1: hnf; intros; trivial.\n  hnf; intros p q f a.\n  refine (_ @ _ @ _^).\n  1,3: unfold pos_iter;\n    by rewrite pos_peano_ind_beta_pos_succ.\n  apply ap.\n  apply q.\nQed.\n\n", "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/Pos/Spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.6796414015412255}}
{"text": "Require Import extensionality.\nRequire Import irrelevance.\nRequire Import Nat.\nRequire Import Max2.\n\n(********************************************************************************)\n(************************* Parial Order on 'option a' ***************************)\n(********************************************************************************)\n\nDefinition ole (a:Type) (x y:option a) : Prop :=\n    forall (v:a), x = Some v -> y = Some v.\n\nArguments ole {a} _ _.\n\nLemma ole_refl : forall (a:Type) (x:option a), ole x x.\nProof. intros a x v H. assumption. Qed.\n\nLemma ole_anti : forall (a:Type) (x y:option a),\n    ole x y -> ole y x -> x = y.\nProof.\n    unfold ole. intros a x y Hxy Hyx. destruct x as [v|], y as [w|].\n        - apply Hyx. reflexivity.\n        - symmetry. apply Hxy. reflexivity.\n        - apply Hyx. reflexivity.\n        - reflexivity.\nQed.\n\nLemma ole_trans : forall (a:Type) (x y z:option a),\n    ole x y -> ole y z -> ole x z.\nProof.\n    unfold ole. intros a x y z Hxy Hyz v H.\n    apply Hyz, Hxy. assumption.\nQed.\n\nDefinition ole' (a:Type) (x y:option a) : Prop :=\n    match x with\n    | None          => True\n    | Some v        =>\n        match y with\n        | None      => False\n        | Some w    => v = w\n        end\n    end.\n\nArguments ole' {a} _ _.\n\nLemma ole_equivalence : forall (a:Type) (x y:option a),\n    ole x y <-> ole' x y.\nProof.\n    intros a x y. unfold ole, ole'. destruct x as [v|], y as [w|]; split.    \n    - intros H. assert (Some w = Some v) as E.\n        { apply H. reflexivity. }\n        inversion E. reflexivity.\n    - intros H1. subst. intros v H. assumption.\n    - intros H. assert (None = Some v) as E.\n        { apply H. reflexivity. }\n        inversion E.\n    - intros H1. exfalso. assumption.\n    - intros H. apply I.\n    - intros H1 v H2. inversion H2.\n    - intros H. apply I.\n    - intros H1 v H2. assumption.\nQed.\n\n\n(********************************************************************************)\n(******************************* Monotone Maps **********************************)\n(********************************************************************************)\n\n(* Bad definition from cpdt                                                     *)\nDefinition monotone (a:Type) (f:nat -> option a) : Prop :=\n    forall (n:nat) (v:a), f n = Some v -> \n    forall (m:nat), n <= m -> f m = Some v.\n\nArguments monotone {a} _.\n\n\n(* Checking bad definition makes sense                                          *)\nLemma monotone_check : forall (a:Type) (f:nat -> option a),\n    monotone f <-> forall (n m:nat), n <= m -> ole (f n) (f m).\nProof.\n    intros a f. split; unfold monotone, ole; intros H.\n    - intros n m H1 v H2. apply H with n; assumption.\n    - intros n v H1 m H2. apply H with n; assumption.\nQed.\n\n\n\n(********************************************************************************)\n(******************************** Computations **********************************)\n(********************************************************************************)\n\n\n(* A computation is a monotone map                                              *)\nDefinition Computation (a:Type) : Type := { f:nat -> option a | monotone f }.\n\nDefinition eval (a:Type) (c:Computation a) (n:nat) : option a := proj1_sig c n.\n\nArguments eval {a}.\n\n(* Expresses the fact that computation k yields value v for input n             *)\nDefinition runTo (a:Type) (k:Computation a) (n:nat) (v:a) : Prop :=\n    eval k n = Some v.\n\nArguments runTo {a} _ _ _.\n\n(* Expresses the fact that computation k eventually yields v                    *) \nDefinition run (a:Type) (k:Computation a) (v:a) : Prop :=\n    exists (n:nat), runTo k n v.\n\nArguments run {a} _ _.\n\n(* We are defining a value with coq tactics. This value is essentially a tuple  *)\n(* where the second coordinate is a proof, so using tactics appears to be       *)\n(* making sense. Note that this proof is not opaque ('Defined' rather than      *)\n(* 'Qed'). Alternatively, we could have defined the proof separately as some    *)\n(* sort of lemma and defined the value 'bot' in the usual direct way by         *)\n(* referring to this lemma                                                      *)\n\nDefinition bot' (a:Type) : Computation a.\n    unfold Computation. exists (fun (_:nat) => None).\n    unfold monotone. intros n v H. inversion H.\nDefined.\n\nArguments bot' {a}.\n\n\nDefinition botf (a:Type) (n:nat) : option a := None.\n\nArguments botf {a} _.\n\nLemma botp : forall (a:Type), monotone (@botf a).\nProof.\n    unfold monotone, botf. intros a n v H. inversion H.\nQed.\n\nArguments botp {a}.\n\n(* A lot better I think, details of proof decoupled from computation logic      *)\nDefinition bot (a:Type) : Computation a :=\n    exist monotone botf botp.\n\nArguments bot {a}.\n\n(********************************************************************************)\n(************************ Equality between Computations *************************)\n(********************************************************************************)\n\nDefinition ceq (a:Type) (k1 k2:Computation a) : Prop :=\n    forall (n:nat), eval k1 n = eval k2 n.\n\nArguments ceq {a} _ _.\n\nNotation \"x == y\" := (ceq x y) (at level 90).\n\nLemma ceq_refl : forall (a:Type) (x:Computation a), x == x.\nProof.\n    intros a [f p] n. simpl. reflexivity.\nQed.\n\nLemma ceq_sym  : forall (a:Type) (x y:Computation a), \n    x == y -> y == x.\nProof.\n    intros a [f p] [g q] H n. simpl. symmetry. apply H.\nQed.\n\nLemma ceq_trans : forall (a:Type) (x y z:Computation a),\n    x == y -> y == z -> x == z.\nProof.\n    intros a [f p] [g q] [h r] Hxy Hyz n. simpl.\n    apply eq_trans with (g n).\n    - apply Hxy.\n    - apply Hyz.\nQed.\n\n\n(********************************************************************************)\n(**************************** Computation as Monad ******************************)\n(********************************************************************************)\n\n(* 'return' is a keyword in coq, so using 'pure' instead                        *)\nDefinition pure' (a:Type) : a -> Computation a.\n    intros v. \n    unfold Computation. exists (fun (_:nat) => Some v).\n    unfold monotone. intros n w H. inversion H. subst.\n    intros m H'. reflexivity.\nDefined.\n\nArguments pure' {a} _.\n\n(* computation is made explicit                                                 *)\nDefinition puref (a:Type)(x:a)(n:nat) : option a := Some x.\n\nArguments puref {a} _ _.\n\n(* statement of what it is we are proving is also clear                         *)\nLemma purep : forall (a:Type) (x:a), monotone (puref x).\nProof.\n    unfold monotone, puref. intros a x n v H m H'. \n    inversion H. subst. reflexivity.\nQed.\n\nArguments purep {a} _.\n\n(* wrapping up in a single function, no complexity here                         *)\nDefinition pure (a:Type)(x:a) : Computation a :=\n    exist monotone (puref x) (purep x).\n\nArguments pure {a} _.\n\n(* Checking 'pure' has the intended semantics                                   *)\nLemma run_pure : forall (a:Type) (v:a), run (pure v) v. \nProof.\n    intros a v. unfold run. exists 0. reflexivity.\nQed.\n\n\n(* Totally useless definition. computation logic and proof are coupled          *)\nDefinition bind'(a b:Type)(k:Computation a)(g:a -> Computation b):Computation b.\n    unfold Computation. \n    remember (fun (n:nat) =>\n        match eval k n with\n        |   Some va => proj1_sig (g va) n\n        |   None    => None\n        end) as gf eqn:GF.\n    exists gf.\n    unfold monotone. \n    intros n vb H m I.\n    destruct k as [f Mf]. simpl in GF. \n    unfold monotone in Mf.\n    rewrite GF in H. rewrite GF.\n    destruct (f n) as [va|] eqn:Fn.\n        - destruct (f m) as [va'|] eqn:Fm.\n            + assert (f m = Some va) as E. \n                { apply Mf with n; assumption. }\n              rewrite Fm in E. inversion E.\n              destruct (g va) as [g' Mg']. simpl. simpl in H.\n              unfold monotone in Mg'. apply Mg' with n; assumption.\n            + assert (f m = Some va) as E.\n                { apply Mf with n; assumption. }\n              rewrite Fm in E. inversion E.\n        - inversion H.\nDefined.\n\n\nArguments bind' {a} {b} _ _.\n\n(* computation logic of bind is plainly visible                                 *) \nDefinition bindf \n    (a b:Type)\n    (k:Computation a)\n    (g:a -> Computation b)\n    (n:nat)\n    :option b :=\n    match k with                    (* unpack computation k             *) \n    | exist _ f _ =>\n        match (f n) with            (* result of f after n cycles       *) \n        | None   => None            (* first computation fails          *)\n        | Some v =>                 (* first computation returns value  *)\n            match (g v) with        (* unpack second computation        *)\n            | exist _ h _ => h n    (* returns result after n cycles    *)\n            end\n        end\n    end.\n\nArguments bindf {a} {b} _ _ _.\n\n(* what we are proving is clear                                                 *)\nLemma bindp : forall (a b:Type) (k:Computation a) (g:a -> Computation b),\n    monotone (bindf k g).\nProof.\n    unfold monotone, bindf. intros a b [f p] g n v H m H'.\n    destruct (f n) as [x|] eqn:E.\n    - unfold monotone in p. rewrite (p n x).\n        + destruct (g x) as [h q]. unfold monotone in q. \n          apply q with n; assumption.\n        + assumption.\n        + assumption.\n    - inversion H.\nQed.\n\nArguments bindp {a} {b} _ _.\n\n(* packing adds no complexity                                                   *)\nDefinition bind (a b:Type) (k:Computation a) (g:a -> Computation b) \n    : Computation b := exist monotone (bindf k g) (bindp k g).\n\nArguments bind {a} {b}.\n\nNotation \"k >>= g\" := (bind k g) (at level 50, left associativity).\n\n(* checking bind has the intended semantics                                      *)\nLemma run_bind : forall (a b:Type) (k:Computation a) (h:a -> Computation b),\n    forall (x:a) (y:b), run k x -> run (h x) y -> run (k >>= h) y.\nProof.\n    intros a b [f p] h x y [n Hx] [m Hy].\n    destruct (h x) as [g q] eqn:H.\n    unfold runTo in Hx. simpl in Hx.\n    unfold runTo in Hy. simpl in Hy.\n    unfold monotone in p. unfold monotone in q.\n    unfold run. unfold runTo.\n    exists (max n m). unfold bind. simpl.\n    assert (f (max n m) = Some x) as E. \n        { apply p with n. assumption. apply n_le_max. }\n    rewrite E, H. simpl. apply q with m. \n        - assumption.\n        - apply m_le_max.\nQed.\n\n\n(********************************************************************************)\n(************************** Checking Monad Laws *********************************)\n(********************************************************************************)\n\nLemma left_identity : forall (a b:Type) (x:a) (h:a -> Computation b),\n    (pure x) >>= h == h x.\nProof. intros a b x h n. simpl. destruct (h x) as [f p]. reflexivity. Qed. \n\nLemma right_identity : forall (a:Type) (k:Computation a), \n    k >>= pure == k.\nProof. intros a [f p] n. simpl. destruct (f n) as [v|]; reflexivity. Qed. \n\nLemma associativity : forall (a b c:Type), \n    forall (k:Computation a) (f:a -> Computation b) (g:b -> Computation c),\n    k >>= f >>= g == k >>= (fun (x:a) => (f x) >>= g).\nProof.\n    intros a b c [k p] f g n. simpl. destruct (k n) as [v|].\n    - destruct (f v) as [h q]. reflexivity.\n    - reflexivity.\nQed.\n\n(********************************************************************************)\n(********************** Partial Order on Computations  **************************)\n(********************************************************************************)\n\nDefinition cle (a:Type) (x y:Computation a) : Prop :=\n    forall (n:nat), ole (eval x n) (eval y n).\n\nArguments cle {a} _ _.\n\nLemma cle_refl : forall (a:Type) (x:Computation a), cle x x.\nProof. intros a [f p] n. apply ole_refl. Qed.\n\n(* Assuming extensionality and proof irrelevance                                *)\nLemma cle_anti : forall (a:Type) (x y:Computation a),\n    cle x y -> cle y x -> x = y.\nProof.\n    unfold cle. intros a [f p] [g q]. simpl. intros H1 H2.\n    assert (f = g) as H.\n        { apply extensionality. intros n. apply ole_anti.\n          - apply H1. \n          - apply H2.\n        }\n    clear H1 H2. revert p q. subst. intros p q.\n    assert (p = q) as H. { apply irrelevance. } subst.\n    reflexivity.\nQed.\n\nLemma cle_trans : forall (a:Type) (x y z:Computation a), \n    cle x y -> cle y z -> cle x z.\nProof.\n    unfold cle. intros a [f p] [g q] [h r]. simpl. intros H1 H2 n.\n    apply ole_trans with (g n).\n        - apply H1.\n        - apply H2.\nQed.\n\nDefinition cle' (a:Type) (x y:Computation a) : Prop :=\n    forall (n:nat) (v:a), runTo x n v -> runTo y n v.\n\nArguments cle' {a} _ _.\n \nLemma cle_equivalence: forall (a:Type) (x y:Computation a),\n    cle x y <-> cle' x y.\nProof.\n    unfold cle, cle', ole, runTo. intros a x y. split; intros H; assumption.\nQed.\n\n\n(********************************************************************************)\n(************** Partial Order on Arrows 'a -> Computation b'  *******************)\n(********************************************************************************)\n\nDefinition cfle (a b:Type) (f g:a -> Computation b) : Prop :=\n    forall (x:a), cle (f x) (g x).\n\nArguments cfle {a} {b} _ _.\n\nLemma cfle_refl : forall (a b:Type) (f:a -> Computation b), cfle f f.\nProof.\n    unfold cfle. intros a b f x. apply cle_refl.\nQed.\n\nLemma cfle_anti : forall (a b:Type) (f g:a -> Computation b),\n    cfle f g -> cfle g f -> f = g.\nProof.\n    unfold cfle. intros a b f g H1 H2. apply extensionality.\n    intros x. apply cle_anti.\n        - apply H1.\n        - apply H2.\nQed.\n\nLemma cfle_trans : forall (a b:Type) (f g h:a -> Computation b),\n    cfle f g -> cfle g h -> cfle f h.\nProof.\n    unfold cfle. intros a b f g h H1 H2 x.\n    apply cle_trans with (g x).\n        - apply H1.\n        - apply H2.\nQed.\n\n(* 'slice at n', just a preorder though                                         *)\nDefinition cfle_n (a b:Type) (n:nat) (f g:a -> Computation b) : Prop :=\n    forall (x:a), ole (eval (f x) n) (eval (g x) n).\n\nArguments cfle_n {a} {b}.\n    \nLemma cfle_n_refl : forall (a b:Type) (n:nat) (f:a -> Computation b),\n    cfle_n n f f.\nProof. intros a b n f x. apply ole_refl. Qed.\n\n\nLemma cfle_n_trans : forall (a b:Type) (n:nat) (f g h:a -> Computation b),\n    cfle_n n f g -> cfle_n n g h -> cfle_n n f h.\nProof.\n    intros a b n f g h H1 H2 x. apply ole_trans with (eval (g x) n).\n        - apply H1.\n        - apply H2.\nQed.\n\n(********************************************************************************)\n(************************* Continuous Function on Arrows  ***********************)\n(********************************************************************************)\n\nDefinition continuous (a b: Type)(F:(a -> Computation b)->(a -> Computation b)):=\n    forall (f g:a -> Computation b)(n:nat), \n        cfle_n n f g  -> cfle_n n (F f) (F g). \n\nArguments continuous {a} {b}.\n\n(* This is a stronger property than just being monotone wr to cfle              *)\n\nLemma continuous_stronger : forall (a b:Type) \n    (F:(a -> Computation b)->(a -> Computation b)), continuous F ->\n        forall (f g:a -> Computation b), cfle f g -> cfle (F f) (F g).\nProof.\n    intros a b F C f g H x n. revert x. apply C. intros x. apply H. \nQed.\n\nDefinition Operator (a b:Type) : Type := \n    {F: (a -> Computation b) -> (a -> Computation b) | continuous F}.\n\n\nDefinition ap (a b:Type) (F:Operator a b) (f:a -> Computation b)\n    : a -> Computation b := proj1_sig F f.\n\nArguments ap {a} {b}.\n\nNotation \"F $ f\" :=(ap F f) (at level 60, right associativity).\n\n(********************************************************************************)\n(************************ The Fixed Point of an Operator  ***********************)\n(********************************************************************************)\n\nDefinition init (a b:Type) : a -> Computation b := (fun x => bot).\n\nArguments init {a} {b}.\n\nFixpoint iter (a b:Type) (F:Operator a b) (n:nat) : a -> Computation b :=\n    match n with\n    | 0     => init\n    | S n   => F $ (iter a b F n)\n    end.\n\nArguments iter {a} {b}.\n\nLemma iter_increasing_ : forall (a b:Type) (F:Operator a b) (n:nat),\n    cfle (iter F n) (iter F (S n)).\nProof.\n    intros a b [F p]. induction n as [|n IH].\n    - unfold cfle, iter, cle, init, ole, bot, ap, botf.\n      simpl. intros x n v H. inversion H.\n    - intros x m. simpl. revert x. apply p. intros x. apply IH.\nQed.\n\nLemma iter_increasing : forall (a b:Type) (F:Operator a b) (n m:nat),\n    n <= m -> cfle (iter F n) (iter F m).\nProof.\n    intros a b F n m H. induction H as [|m H IH].\n    - apply cfle_refl.\n    - apply cfle_trans with (iter F m).\n        + assumption.\n        + apply iter_increasing_.\nQed.\n\nDefinition Fixf (a b:Type) (F:Operator a b) (x:a) (n:nat) : option b :=\n    eval (iter F n x) n.  \n\nArguments Fixf {a} {b}.\n\nLemma Fixp : forall (a b:Type) (F:Operator a b) (x:a), monotone (Fixf F x).\nProof.\n    intros a b F x. apply monotone_check. intros n m H.\n    unfold Fixf. apply ole_trans with (proj1_sig (iter F n x) m).\n    - destruct (iter F n x) as [f p]. simpl. apply monotone_check; assumption.\n    - apply iter_increasing. assumption.\nQed.\n\nArguments Fixp {a} {b}.\n\n\nDefinition Fix (a b:Type) (F:Operator a b) (x:a) : Computation b :=\n    exist monotone (Fixf F x) (Fixp F x).\n\nArguments Fix {a} {b}.\n\n(* key lemma                                                                    *)\nLemma FFix_iter : forall (a b:Type) (F:Operator a b) (x:a) (n:nat),\n    eval ((F $ Fix F) x) n = eval (iter F (S n) x) n.\nProof.\n    intros a b F x n. \n    destruct F as [F' p] eqn:E. rewrite <- E.\n    unfold continuous, cfle_n in p.\n    remember (Fix F) as f eqn:E1.\n    remember (iter F n) as g eqn:E2.\n    assert (eval (F' f x) n = eval ((F $ f) x) n) as E3. \n        { unfold eval, ap. rewrite E. reflexivity. }\n    assert (eval (F' g x) n = eval (iter F (S n) x) n) as E4.\n        { unfold eval. rewrite E2. unfold iter, ap. rewrite E. reflexivity. }\n    assert (forall (x:a), eval (f x) n = eval (g x) n) as H.\n        { intros y. rewrite E1, E2. unfold Fix,Fixf, iter, eval. reflexivity. }\n    rewrite <- E3, <- E4.\n    apply ole_anti; apply p; intros y; rewrite H; apply ole_refl.\nQed.\n\n(* If computation F (Fix F) terminates @x, so will computation Fix F @x         *)\nLemma FFix_Fix : forall (a b:Type) (F:Operator a b) (x:a) (n:nat),\n    ole (eval ((F $ Fix F) x) n) (eval (Fix F x) (S n)).\nProof.\n    intros a b F x n. apply ole_trans with (eval (iter F (S n) x) n).\n    - rewrite FFix_iter. apply ole_refl.\n    - assert (eval (Fix F x) (S n) = eval (iter F (S n) x) (S n)) as E.\n        { reflexivity. }\n      rewrite E. destruct (iter F (S n) x) as [f p]. simpl.\n      apply monotone_check. \n        + assumption.\n        + apply le_S, le_n.\nQed.\n\n(* If computation Fix F terminates @x, so will computation F (Fix F) @x         *)\nLemma Fix_FFix : forall (a b:Type) (F:Operator a b) (x:a) (n:nat),\n    ole (eval (Fix F x) n) (eval ((F $ Fix F) x) n).\nProof.\n    intros a b F x n. rewrite FFix_iter. apply iter_increasing_.\nQed.\n\n\n(* checking Fix has the intended semantics  *)\n(* F (Fix F) terminates iff (Fix F) terminates, and both results equal          *)\nTheorem run_Fix : forall (a b:Type) (F:Operator a b) (x:a) (v:b),\n    run ((F $ Fix F) x) v <-> run (Fix F x) v.\nProof.\n    intros a b F x v. split; unfold run, runTo; intros [n H].\n    - exists (S n). apply FFix_Fix. assumption.\n    - exists n. apply Fix_FFix. 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/domain.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.6795902756511503}}
{"text": "Theorem 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. destruct c. \n+ intros H. reflexivity.\n+ intros H. rewrite H. reflexivity.\n- simpl. destruct c. \n+ intros H. rewrite H. reflexivity.\n+ intros H. reflexivity.\nQed.\n\n", "meta": {"author": "Asap7772", "repo": "coq_softwarefoundations", "sha": "a7a58d9f82aed0966d8a2fcd2fc3be1d4b7b1f0d", "save_path": "github-repos/coq/Asap7772-coq_softwarefoundations", "path": "github-repos/coq/Asap7772-coq_softwarefoundations/coq_softwarefoundations-a7a58d9f82aed0966d8a2fcd2fc3be1d4b7b1f0d/chapter1/andb eq orb alt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.6795902706876354}}
{"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\nRequire Import Exponentiation.\n\n(* Why3 goal *)\nNotation power := Zpower.\n\nLemma power_is_exponentiation :\n  forall x n, (0 <= n)%Z -> power x n = Exponentiation.power _ 1%Z Zmult x n.\nProof.\nintros x [|n|n] H.\neasy.\n2: now elim H.\nunfold Exponentiation.power, power, Zpower_pos.\nnow rewrite iter_nat_of_P.\nQed.\n\n(* Why3 goal *)\nLemma Power_0 :\nforall (x:Z), ((power x 0%Z) = 1%Z).\nProof.\nintros x.\napply refl_equal.\nQed.\n\n(* Why3 goal *)\nLemma Power_s :\nforall (x:Z) (n:Z),\n (0%Z <= n)%Z -> ((power x (n + 1%Z)%Z) = (x * (power x n))%Z).\nProof.\nintros x n h1.\nrewrite Zpower_exp.\nchange (power x 1) with (x * 1)%Z.\nring.\nnow apply Zle_ge.\neasy.\nQed.\n\n(* Why3 goal *)\nLemma Power_s_alt :\nforall (x:Z) (n:Z),\n (0%Z < n)%Z -> ((power x n) = (x * (power x (n - 1%Z)%Z))%Z).\nintros x n h1.\nrewrite <- Power_s.\nf_equal; auto with zarith.\nomega.\nQed.\n\n(* Why3 goal *)\nLemma Power_1 :\nforall (x:Z), ((power x 1%Z) = x).\nProof.\nexact Zmult_1_r.\nQed.\n\n(* Why3 goal *)\nLemma Power_sum :\nforall (x:Z) (n:Z) (m:Z),\n (0%Z <= n)%Z ->\n ((0%Z <= m)%Z -> ((power x (n + m)%Z) = ((power x n) * (power x m))%Z)).\nProof.\nintros x n m Hn Hm.\nnow apply Zpower_exp; apply Zle_ge.\nQed.\n\n(* Why3 goal *)\nLemma Power_mult :\nforall (x:Z) (n:Z) (m:Z),\n (0%Z <= n)%Z ->\n ((0%Z <= m)%Z -> ((power x (n * m)%Z) = (power (power x n) m))).\nProof.\nintros x n m Hn Hm.\nrewrite 3!power_is_exponentiation ; auto with zarith.\napply Power_mult ; auto with zarith.\nQed.\n\n(* Why3 goal *)\nLemma Power_comm1 :\nforall (x:Z) (y:Z),\n ((x * y)%Z = (y * x)%Z) ->\n forall (n:Z), (0%Z <= n)%Z -> (((power x n) * y)%Z = (y * (power x n))%Z).\nProof.\nintros x y h1 n h2.\nauto with zarith.\nQed.\n\n(* Why3 goal *)\nLemma Power_comm2 :\nforall (x:Z) (y:Z),\n ((x * y)%Z = (y * x)%Z) ->\n forall (n:Z),\n  (0%Z <= n)%Z -> ((power (x * y)%Z n) = ((power x n) * (power y n))%Z).\nProof.\nintros x y h1 n h2.\nrewrite 3!power_is_exponentiation ; auto with zarith.\napply Power_comm2 ; auto with zarith.\nQed.\n\n(* Why3 goal *)\nLemma Power_non_neg :\nforall (x:Z) (y:Z), ((0%Z <= x)%Z /\\ (0%Z <= y)%Z) -> (0%Z <= (power x y))%Z.\nintros x y (h1,h2).\nnow apply Z.pow_nonneg.\nQed.\n\nOpen Scope Z_scope.\n\n(* Why3 goal *)\nLemma Power_monotonic :\nforall (x:Z) (n:Z) (m:Z),\n ((0%Z < x)%Z /\\ ((0%Z <= n)%Z /\\ (n <= m)%Z)) ->\n ((power x n) <= (power x m))%Z.\nintros.\napply Z.pow_le_mono_r; auto with zarith.\nQed.\n\n", "meta": {"author": "florianschanda", "repo": "why3", "sha": "dc0d2720d58c6d130b9c3e1db820a07275a133eb", "save_path": "github-repos/coq/florianschanda-why3", "path": "github-repos/coq/florianschanda-why3/why3-dc0d2720d58c6d130b9c3e1db820a07275a133eb/lib/coq/int/Power.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145053, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6795902557970904}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\n\nSection HilbertSaxiom.\n\nVariables A B C : Prop.\n\nLemma HilbertS : (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\nmove=> hAiBiC hAiB hA.\nmove: hAiBiC.\napply.\n  by [].\nby apply: hAiB.\nQed.\n\nHypotheses (hAiBiC : A -> B -> C) (hAiB : A -> B) (hA : A).\n\nLemma HilbertS2 : C.\nProof.\napply: hAiBiC; first by apply: hA.\nexact: hAiB.\nQed.\n\nCheck (hAiB hA).\n\nLemma HilbertS3 : C.\nProof. by apply: hAiBiC; last exact: hAiB. Qed.\n\nLemma HilbertS4 : C.\nProof. exact:  (hAiBiC _ (hAiB _)). Qed.\n\nLemma HilbertS5 : C.\nProof. exact: hAiBiC (hAiB _). Qed.\n\nLemma HilbertS6 : C.\nProof. exact HilbertS5. Qed.\n\nEnd HilbertSaxiom.\n\n\n\nSection Symmetric_Conjunction_Disjunction.\n\nPrint bool.\n\nLemma andb_sym : forall A B : bool, A && B -> B && A.\nProof.\ncase.\n  by case.\nby [].\nQed.\n\nLemma andb_sym2 : forall A B : bool, A && B -> B && A.\nProof. by case; case. Qed.\n\nLemma andb_sym3 : forall A B : bool, A && B -> B && A.\nProof. by do 2! case. Qed.\n\nVariables (C D : Prop) (hC : C) (hD : D).\nCheck (and C D).\nPrint and.\nCheck conj.\nCheck (conj hC hD).\n\nLemma and_sym : forall A B : Prop, A /\\ B -> B /\\ A.\nProof. by move=> A1 B []. Qed.\n\nPrint or.\n\nCheck or_introl.\n\nLemma or_sym : forall A B : Prop, A \\/ B -> B \\/ A.\nProof. by move=> A B [hA | hB]; [apply: or_intror | apply: or_introl]. Qed.\n\nLemma or_sym2 : forall A B : bool, A \\/ B -> B \\/ A.\nProof. by move=> [] [] AorB; apply/orP; move/orP : AorB. Qed.\n\nEnd Symmetric_Conjunction_Disjunction.\n\n\n\nSection R_sym_trans.\n\nVariables (D : Type) (R : D -> D -> Prop).\n\nHypothesis R_sym : forall x y, R x y -> R y x.\n\nHypothesis R_trans : forall x y z, R x y -> R y z -> R x z.\n\nLemma refl_if : forall x : D, (exists y, R x y) -> R x x.\nProof.\nmove=> x [y Rxy].\nexact: R_trans (R_sym _ y _).\nQed.\n\nEnd R_sym_trans.\n\n\n\nSection Smullyan_drinker.\n\nVariables (D : Type) (P : D -> Prop).\nHypotheses (d : D) (EM : forall A, A \\/ ~A).\n\nLemma drinker : exists x, P x -> forall y, P y.\nProof.\n(* case: (EM (exists y, ~P y)) => [[y notPy]| nonotPy] *)\nhave [[y notPy]| nonotPy] := EM (exists y, ~P y); first by exists y.\nexists d => _ y; case: (EM (P y)) => // notPy.\nby case: nonotPy; exists y.\nQed.\n\nEnd Smullyan_drinker.\n\n\n\nSection Equality.\n\nVariable f : nat -> nat.\nHypothesis f00 : f 0 = 0.\n\nLemma fkk : forall k, k = 0 -> f k = k.\nProof. by move=> k k0; rewrite k0. Qed.\n\nLemma fkk2 : forall k, k = 0 -> f k = k.\nProof. by move=> k ->. Qed.\n\nVariable f10 : f 1 = f 0.\n\nLemma ff10 : f (f 1) = 0.\nProof. by rewrite f10 f00. Qed.\n\nVariables (D : eqType) (x y : D).\n\nLemma eq_prop_bool : x = y -> x == y.\nProof. by move/eqP. Qed.\n\nLemma eq_bool_prop : x == y -> x = y.\nProof. by move/eqP. Qed.\n\nEnd Equality.\n\n\n\nSection Using_Definition.\n\nVariable U : Type.\n\nDefinition set := U -> Prop.\n\nDefinition subset (A B : set) := forall x, A x -> B x.\n\nDefinition transitive (T : Type) (R : T -> T -> Prop) :=\n forall x y z, R x y -> R y z -> R x z.\n\nLemma subset_trans : transitive set subset.\nProof.\nrewrite /transitive /subset => x y z subxy subyz t xt.\nby apply: subyz; apply: subxy.\nQed.\n\nLemma subset_trans2 : transitive set subset.\nProof.\nmove=> x y z subxy subyz t.\nby move/subxy; move/subyz.\nQed.\n\nEnd Using_Definition.\n\n\nSection Basic_ssrnat.\n\n\nLemma three : S (S (S O)) = 3 /\\ 3 = 0.+1.+1.+1.\nProof. by []. Qed.\n\nLemma concrete_plus : plus 16 64 = 80.\nProof. (*simpl.*) by []. Qed.\n\nLemma concrete_addn : 16 + 64 = 80.\nProof. (*simpl.*)  by []. Qed.\n\nLemma concrete_le : le 1 3.\nProof. by apply: (Le.le_trans _ 2); apply: Le.le_n_Sn. Qed.\n\nLemma concrete_big_le : le 16 64.\nProof. by auto 47 with arith. Qed.\n\nLemma concrete_big_leq : 0 <= 51.\nProof. by []. Qed.\n\nLemma semi_concrete_leq : forall n m, n <= m -> 51 + n <= 51 + m.\nProof. by []. Qed.\n\nLemma concrete_arith : (50 < 100) && (3 + 4 < 3 * 4 <= 17 - 2).\nProof. by []. Qed.\n\nLemma plus_com : forall m1 n1, n1 + m1 = m1 + n1.\nProof.\nby elim=> [| n IHn m]; [elim | rewrite -[n.+1 + m]/(n + m).+1 -IHn; elim: m].\nQed.\n\nEnd Basic_ssrnat.\n\n\nSection Euclidean_division.\n\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nDefinition edivn_rec d := fix loop (m q : nat) {struct m} :=\n  if m - d is m'.+1 then loop m' q.+1 else (q, m).\n\nDefinition edivn m d := if d is d'.+1 then edivn_rec d' m 0 else (0, m).\n\nCoInductive edivn_spec (m d : nat) : nat * nat -> Type :=\n  EdivnSpec q r of m = q * d + r & (d > 0) ==> (r < d) : edivn_spec m d (q, r).\n\nLemma edivnP : forall m d, edivn_spec m d (edivn m d).\nProof.\nmove=> m [|d] //=; rewrite -{1}[m]/(0 * d.+1 + m).\nelim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //=; rewrite ltnS => le_mn.\nrewrite subn_if_gt; case: ltnP => // le_dm.\nrewrite -{1}(subnKC le_dm) -addSn addnA -mulSnr; apply: IHn.\napply: leq_trans le_mn; exact: leq_subr.\nQed.\n\nLemma edivn_eq : forall d q r, r < d -> edivn (q * d + r) d = (q, r).\nProof.\nmove=> d q r lt_rd; have d_gt0: 0 < d by exact: leq_trans lt_rd.\ncase: edivnP lt_rd => q' r'; rewrite d_gt0 /=.\nwlog: q q' r r' / q <= q' by case (ltnP q q'); last symmetry; eauto.\nrewrite leq_eqVlt; case: eqP => [-> _|_] /=; first by move/addnI->.\nrewrite -(leq_pmul2r d_gt0); move/leq_add=> Hqr Eqr _; move/Hqr {Hqr}.\nby rewrite addnS ltnNge mulSn -addnA Eqr addnCA addnA leq_addr.\nQed.\n\nCoInductive edivn_spec_right : nat -> nat -> nat * nat -> Type :=\n  EdivnSpec_right m d q r of m = q * d + r & (d > 0) ==> (r < d) :\n  edivn_spec_right m d (q, r).\n\nCoInductive edivn_spec_left (m d : nat)(qr : nat * nat) : Type :=\nEdivnSpec_left of m = (fst qr) * d + (snd qr) & (d > 0) ==> (snd qr < d) :\n   edivn_spec_left m d qr.\n\n\nLemma edivnP_left : forall m d, edivn_spec_left m d (edivn m d).\nProof.\nmove=> m [|d] //=; rewrite -{1}[m]/(0 * d.+1 + m).\nelim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //=; rewrite ltnS => le_mn.\nrewrite subn_if_gt; case: ltnP => // le_dm.\nrewrite -{1}(subnKC le_dm) -addSn addnA -mulSnr; apply: IHn.\napply: leq_trans le_mn; exact: leq_subr.\nQed.\n\nLemma edivnP_right : forall m d, edivn_spec_right m d (edivn m d).\nProof.\nmove=> m [|d] //=; rewrite -{1}[m]/(0 * d.+1 + m).\nelim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //=; rewrite ltnS => le_mn.\nrewrite subn_if_gt; case: ltnP => // le_dm.\nrewrite -{1}(subnKC le_dm) -addSn addnA -mulSnr; apply: IHn.\napply: leq_trans le_mn; exact: leq_subr.\nQed.\n\nLemma edivn_eq_right : forall d q r, r < d -> edivn (q * d + r) d = (q, r).\nProof.\nmove=> d q r lt_rd; have d_gt0: 0 < d by exact: leq_trans lt_rd.\nset m := q * d + r; have: m = q * d + r by [].\nset d' := d; have: d' = d by [].\ncase: (edivnP_right m d') => {m d'} m d' q' r' -> lt_r'd' d'd q'd'r'.\nmove: q'd'r' lt_r'd' lt_rd; rewrite d'd d_gt0 {d'd m} /=.\nwlog: q q' r r' / q <= q' by case (ltnP q q'); last symmetry; eauto.\nrewrite leq_eqVlt; case: eqP => [-> _|_] /=; first by move/addnI->.\nrewrite -(leq_pmul2r d_gt0); move/leq_add=> Hqr Eqr _; move/Hqr {Hqr}.\nby rewrite addnS ltnNge mulSn -addnA -Eqr addnCA addnA leq_addr.\nQed.\n\n\nLemma edivn_eq_left : forall d q r, r < d -> edivn (q * d + r) d = (q, r).\nProof.\nmove=> d q r lt_rd; have d_gt0: 0 < d by exact: leq_trans lt_rd.\ncase: (edivnP_left (q * d + r) d) lt_rd; rewrite d_gt0 /=.\nset q':= (edivn (q * d + r) d).1; set r':= (edivn (q * d + r) d).2.\nrewrite (surjective_pairing (edivn (q * d + r) d)) -/q' -/r'.\nwlog: q r q' r' / q <= q' by case (ltnP q q'); last symmetry; eauto.\nrewrite leq_eqVlt; case: eqP => [-> _|_] /=; first by move/addnI->.\nrewrite -(leq_pmul2r d_gt0); move/leq_add=> Hqr Eqr _; move/Hqr {Hqr}.\nby rewrite addnS ltnNge mulSn -addnA Eqr addnCA addnA leq_addr.\nQed.\n\n\nEnd Euclidean_division.", "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/doc/tutorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.6795213414451887}}
{"text": "\n\n\n(* -------------------------Description--------------------------------------\n\n   In this file we capture the notion of ordType. This type has\n   elements with decidable equality. This is almost same and inspired by\n   ssreflect library.  \n   We also connect natural numbers and booleans to this type by creating\n   canonical instances nat_eqType and bool_eqType. \n \n\n   Structure type: Type:=  Pack {\n                             E: Type;\n                             eqb: E-> E -> bool;\n                             eqP: forall x y, reflect (eq x y)(eqb x y) }.\n\n \n  Notation \"x == y\":= (@Decidable.eqb _ x y)(at level 70, no associativity).\n\n \n\n  Some important results are:\n  \n  Lemma eqP  (T:ordType)(x y:T): reflect (x=y)(eqb  x y). \n  Lemma nat_eqP (x y:nat): reflect (x=y)(Nat.eqb x y).\n\n  Canonical nat_eqType: eqType:=\n                              {| Decidable.E:= nat; Decidable.eqb:= Nat.eqb;\n                                  Decidable.eqP:= nat_eqP |}.\n\n  Lemma bool_eqP (x y:bool): reflect (x=y)(Bool.eqb x y). \n  \n  Canonical bool_eqType: eqType:= \n                             {| Decidable.E:= bool; Decidable.eqb:= Bool.eqb;\n                                  Decidable.eqP:= bool_eqP |}.\n\n  \n   ------------------------------------------------------------------------- *)\n\nFrom Coq Require Export ssreflect  ssrbool. \nRequire Export  GenReflect Lia.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule Decidable.\n  Structure type: Type:= Pack {\n                             E: Type;\n                             eqb: E-> E -> bool;\n                             eqP: forall x y, reflect (eq x y)(eqb x y) }.\n  Module Exports.\n    Coercion E : type >-> Sortclass.\n    Notation eqType:= type.\n    End Exports.\nEnd Decidable.\nExport Decidable.Exports.\n\nNotation \"x == y\":= (@Decidable.eqb _ x y)(at level 70, no associativity): bool_scope.\n\n\n\nLemma eqP  (T:eqType)(x y:T): reflect (x=y)(x == y). \nProof. apply Decidable.eqP. Qed.\n\n\nHint Resolve eqP: core.\n\nLemma eq_to_eqb (T:eqType)(x y:T): (x=y)-> (x == y).\nProof.  intro; apply /eqP; auto. Qed.\nLemma eqb_to_eq (T:eqType) (x y:T): (x == y)-> (x=y).\nProof. intro;apply /eqP; auto. Qed.\n\nHint Immediate eq_to_eqb eqb_to_eq: core.\n\nLemma eq_refl (T: eqType)(x:T): x == x.\nProof. apply /eqP; auto. Qed.\nLemma eq_symm (T: eqType)(x y:T): (x == y)=(y == x).\nProof. { case (x== y) eqn:H1; case ( y== x) eqn:H2;  try(auto).\n       { assert (H3: x=y). apply /eqP;auto.\n         rewrite H3 in H2; rewrite eq_refl in H2; inversion H2. }\n       { assert (H3: y= x). apply /eqP; auto.\n         rewrite H3 in H1; rewrite eq_refl in H1; inversion H1.  } } Qed.\n\nHint Resolve eq_refl eq_symm: core.\n\n(*--------- Natural numbers as an instance of eqType---------------------*)\n\nLemma nat_eqb_ref (x:nat): Nat.eqb x x = true.\nProof. induction x;simpl;auto. Qed.\nHint Resolve nat_eqb_ref:core.\n\nLemma nat_eqb_elim (x y:nat):  Nat.eqb x y -> x = y.\nProof. { revert y. induction x.\n       { intro y. case y. tauto. simpl; intros n H; inversion H. }\n       intro y. case y. simpl; intro H; inversion H. simpl. eauto. } Qed.\nHint Resolve nat_eqb_elim: core.\n\nLemma nat_eqb_intro (x y:nat): x=y -> Nat.eqb x y.\nProof. intro H. subst x. eauto. Qed.\nHint Resolve nat_eqb_intro: core.\n\nLemma nat_eqP (x y:nat): reflect (x=y)(Nat.eqb x y).\nProof. apply reflect_intro.  split; eauto. Qed. \nHint Resolve nat_eqP: core.\n\n\nCanonical nat_eqType: eqType:= {| Decidable.E:= nat; Decidable.eqb:= Nat.eqb;\n                                  Decidable.eqP:= nat_eqP |}.\n\n(*--------- Bool as an instance of eqType --------------------------------*)\nLemma bool_eqb_ref (x:bool): Bool.eqb x x = true.\nProof. destruct x; simpl; auto. Qed.\nHint Resolve bool_eqb_ref: core.\n\nLemma bool_eqb_elim (x y:bool): (Bool.eqb x y) -> x = y.\nProof. destruct x; destruct y; simpl; try (auto || tauto). Qed.\n\nLemma bool_eqb_intro (x y:bool): x = y -> (Bool.eqb x y).\nProof. intros; subst y; destruct x; simpl; auto. Qed.\n\nHint Immediate bool_eqb_elim bool_eqb_intro: core.\n\nLemma bool_eqP (x y:bool): reflect (x=y)(Bool.eqb x y).\nProof. apply reflect_intro.\n       split. apply bool_eqb_intro. apply bool_eqb_elim. Qed.\nHint Resolve bool_eqP: core.\n\nCanonical bool_eqType: eqType:= {| Decidable.E:= bool; Decidable.eqb:= Bool.eqb;\n                                  Decidable.eqP:= bool_eqP |}.\n\nLtac conflict_eq :=\n    match goal with\n    | H:  (?x == ?x)= false  |- _\n      => switch_in H; cut(False);[tauto |auto]\n    | H: ~(is_true (?x == ?x)) |- _\n      => cut(False);[tauto |auto]             \n    | H: ~ (?x = ?x) |- _\n      => cut(False);tauto\n    | H: (?x == ?y) = true, H1: ?x <> ?y |- _\n      => absurd (x = y);auto\n    | H:  is_true (?x == ?y), H1: ?x <> ?y |- _\n      => absurd (x = y);auto                     \n    | H: (?x == ?y) = true, H1: ?y <> ?x |- _\n      => absurd (y = x);[auto | (symmetry;auto)]\n    | H: is_true (?x == ?y), H1: ?y <> ?x |- _\n      => absurd (y = x);[auto | (symmetry;auto)]                     \n    | H: (?x == ?y) = false, H1: ?x = ?y |- _\n      => switch_in H; absurd (x=y); auto\n    | H: (?x == ?y) = false, H1: ?y = ?x |- _\n      => switch_in H; symmetry in H1; absurd (x=y); auto\n    end.\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/DecType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430520409024, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.6795213380256138}}
{"text": "Require Import Reals.\nRequire Import Interval.Tactic.\n\nGoal forall x, (1 < x <= 5)%R -> (2 > Rabs x)%R -> (2 <= x + 1 <= 3)%R.\nProof.\nintros x H1 H2.\ninterval with (i_prec 30).\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/bug-20201020.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308091776496, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6795147068249684}}
{"text": "(* \n  Author(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\n(** * Halting problem for one counter machines CM1_HALT  *)\n\n(* \n  Problem(s):\n    One Counter Machine Halting (CM1_HALT)\n*)\n\nRequire Import List Nat.\n\nDefinition State : Set := nat.\n(* a configuration consists of a state and a counter value *)\nRecord Config : Set := mkConfig { state : State; value : nat }.\n\n(* an instruction (n, q) maps \n  a configuration (p, c) to (q, c * (n+2) / (n+1)) if c is divisible by (n+1)\n  and otherwise to (p+1, c) *)\nDefinition Instruction : Set := State * nat.\n\n(* an one counter machine is a list of instructions *)\nDefinition Cm1 : Set := list Instruction.\n\n(* one counter machine step function *)\nDefinition step (M: Cm1) (x: Config) : Config :=\n  match (value x), (nth_error M (state x)) with\n  | 0, _ => x (* halting configuration *)\n  | _, None => x (* halting configuration *)\n  | _, Some (p, n) => \n      match modulo (value x) (n+1) with\n      | 0 => {| state := p; value := ((value x) * (n+2)) / (n+1) |}\n      | _ => {| state := 1 + state x; value := value x |}\n      end\n  end.\n\n(* unfold step if the configuration is decomposed *)\nArguments step _ !x /.\n\n(* halting configuration property *)\nDefinition halting (M : Cm1) (x: Config) : Prop := step M x = x.\n\n(* One Counter Machine Halting Problem (with Denominators at most 4) *)\nDefinition CM1_HALT : { M : Cm1 | Forall (fun '(_, n) => n < 4) M } -> Prop :=\n  fun '(exist _ M _) => \n    exists n, halting M (Nat.iter n (step M) {| state := 0; value := 1 |}).\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/CounterMachines/CM1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6794963849185466}}
{"text": "(* File: Trees.v  (last edited on 25/10/2000) (c) Klaus Weich  *)\n\nFrom Coq Require Import Le.\nFrom IPC Require Export My_Arith.\n\n\n(******   Tree stuff  ********************************************)\n\nSection Trees.\n\n\nVariable A : Set.\n\n\nInductive Tree : Set :=\n    node : A -> Forest -> Tree\nwith Forest : Set :=\n  | Nil_Forest : Forest\n  | Cons_Forest : Tree -> Forest -> Forest.\n\n\nFixpoint height_tree (t : Tree) : nat :=\n  match t with\n  | node a succs => S (height_forest succs)\n  end\n\n with height_forest (succs : Forest) : nat :=\n  match succs with\n  | Nil_Forest => 0\n  | Cons_Forest t0 succs => max (height_tree t0) (height_forest succs)\n  end.\n\n\n(*\nInductive Tree : Set :=\n| node : A -> (list Tree) -> Tree.\n\nFixpoint height_tree [t:Tree] : nat :=\n  Cases t of\n  | (node a succs) => (S (height_forest succs))\n  end\nwith height_forest[succs:(list Tree)] : nat :=\n  Cases succs of\n  | nil => O\n  | (cons t0 succs) => (max (height_tree t0) (height_forest succs))\n  end.\nDoes not work!!\n*)\n\n\nDefinition root (t : Tree) := match t with\n                              | node a _ => a\n                              end.\nDefinition successors (t : Tree) := match t with\n                                    | node _ succs => succs\n                                    end.\n\n\nInductive In_Forest (t0 : Tree) : Forest -> Prop :=\n  | in_forest_head :\n      forall succs : Forest, In_Forest t0 (Cons_Forest t0 succs)\n  | in_forest_tail :\n      forall (t1 : Tree) (succs : Forest),\n      In_Forest t0 succs -> In_Forest t0 (Cons_Forest t1 succs).\n\n\nLemma height_in_le :\n forall (t : Tree) (succs : Forest),\n In_Forest t succs -> height_tree t <= height_forest succs.\nintros t succs in_t.\nelim in_t; clear in_t succs.\n\nintros succs.\nsimpl in |- *.\napply le_n_max1.\n\nintros t1 succs in_t le_t.\napply Nat.le_trans with (height_forest succs).\nassumption.\nsimpl in |- *.\napply le_n_max2.\nQed.\n\n\nLemma My_Tree_ind :\n forall P : Tree -> Prop,\n (forall (a : A) (succs : Forest),\n  (forall t : Tree, In_Forest t succs -> P t) -> P (node a succs)) ->\n forall t : Tree, P t.\nintros P step.\ncut (forall (n : nat) (t : Tree), height_tree t <= n -> P t).\nintro claim.\nintro t.\napply claim with (height_tree t).\ntrivial.\nintros n; elim n; clear n.\n\nintros t; elim t; clear t.\nintros a succs u0.\nelimtype False.\ninversion_clear u0.\n\nintros n ih t.\nelim t; clear t.\nintros a succs u0.\napply step; clear step.\nintros t in_t.\napply ih; clear ih P.\napply le_S_n.\napply Nat.le_trans with (S (height_forest succs)).\napply le_n_S.\napply height_in_le; assumption.\nassumption.\nQed.\n\n\nLemma My_Tree_rec :\n forall P : Tree -> Set,\n (forall (a : A) (succs : Forest),\n  (forall t : Tree, In_Forest t succs -> P t) -> P (node a succs)) ->\n forall t : Tree, P t.\nintros P step.\ncut (forall (n : nat) (t : Tree), height_tree t <= n -> P t).\nintro claim.\nintro t.\napply claim with (height_tree t).\ntrivial.\nintros n; elim n; clear n.\n\nintros t; elim t; clear t.\nintros a succs u0.\nelimtype False.\ninversion_clear u0.\n\nintros n ih t.\nelim t; clear t.\nintros a succs u0.\napply step; clear step.\nintros t in_t.\napply ih; clear ih P.\napply le_S_n.\napply Nat.le_trans with (S (height_forest succs)).\napply le_n_S.\napply height_in_le; assumption.\nassumption.\nQed.\n\n\n(* Successor relation  *)\n\nInductive Successor : Tree -> Tree -> Prop :=\n  | successor_refl : forall t : Tree, Successor t t\n  | successor_trans :\n      forall t0 t1 : Tree,\n      In_Forest t1 (successors t0) ->\n      forall t2 : Tree, Successor t2 t1 -> Successor t2 t0.\n\n\nLemma succs_trans :\n forall t1 t2 : Tree,\n Successor t2 t1 -> forall t0 : Tree, Successor t1 t0 -> Successor t2 t0.\nintros t1 t2 u0 t0 u1.\ngeneralize u0; clear u0.\nelim u1; clear u1 t0 t1.\ntrivial.\n\nintros t0 t1 in_t1 t3 suc_t3_t1 ih suc_t2_t3.\napply (successor_trans t0 t1 in_t1 t2).\napply ih; assumption.\nQed.\n\n\nLemma succs_refl : forall t : Tree, Successor t t.\nintros.\napply successor_refl.\nQed.\n\n\n\nLemma Succs_Tree_ind :\n forall P : Tree -> Prop,\n (forall a : A, P (node a Nil_Forest)) ->\n (forall t0 t1 : Tree, Successor t0 t1 -> P t0 -> P t1) ->\n forall t : Tree, P t.\nintros P leaf step t.\napply My_Tree_ind.\nintros a succs; case succs; clear succs.\nintros.\napply leaf.\nintros t0 succs ih.\napply step with t0.\napply successor_trans with t0.\nsimpl in |- *.\napply in_forest_head.\napply successor_refl.\napply ih.\napply in_forest_head.\nQed.\n\n\n(* In_tree *)\n(* ------- *)\n\nInductive In_tree : A -> Tree -> Prop :=\n  | in_leave : forall (a : A) (succs : Forest), In_tree a (node a succs)\n  | in_succs :\n      forall (succs : Forest) (t : Tree),\n      In_Forest t succs ->\n      forall a : A, In_tree a t -> forall a' : A, In_tree a (node a' succs).\n\n\nLemma in_successor_in :\n forall (a : A) (t : Tree),\n In_tree a t -> forall t' : Tree, Successor t t' -> In_tree a t'.\nintros a t in_t t' suc.\ngeneralize in_t; clear in_t.\nelim suc; clear suc.\ntrivial.\nclear t t'.\nintros t0 t1 in_t1 t2 suc_t2 ih in_t2.\ngeneralize in_t1; clear in_t1.\nelim t0; clear t0.\nintros a' succs in_t1.\napply in_succs with (t := t1).\nassumption.\napply ih.\nassumption.\nQed.\n\n(********************************************************************)\n(*  Monotone Trees                                                  *)\n\nVariable I : Set.\nVariable P : A -> I -> Prop.\n\nInductive Is_Monotone_Tree : Tree -> Prop :=\n    is_monotone_tree_intro :\n      forall (a : A) (succs : Forest),\n      Is_Monotone_Forest a succs -> Is_Monotone_Tree (node a succs)\nwith Is_Monotone_Forest : A -> Forest -> Prop :=\n  | is_monotone_forest_nil : forall a : A, Is_Monotone_Forest a Nil_Forest\n  | is_monotone_forest_cons :\n      forall (a : A) (t : Tree) (succs : Forest),\n      (forall i : I, P a i -> P (root t) i) ->\n      Is_Monotone_Tree t ->\n      Is_Monotone_Forest a succs ->\n      Is_Monotone_Forest a (Cons_Forest t succs).\n\n\n\n\nLemma is_monotone_tree_successor :\n forall t : Tree,\n Is_Monotone_Tree t ->\n forall t0 : Tree, Successor t0 t -> Is_Monotone_Tree t0.\nintros t is_mon_t t0 suc_t0.\ngeneralize is_mon_t; clear is_mon_t.\nelim suc_t0; clear suc_t0 t0.\ntrivial.\nintros t0 t1 in_t1 t2 suc_t2 ih is_mon_t0.\napply ih; clear ih suc_t2 t2.\ngeneralize in_t1; clear in_t1.\ninversion_clear is_mon_t0.\nsimpl in |- *.\ngeneralize H; clear H.\nelim succs; clear succs.\nintros H in_t1.\ninversion_clear in_t1.\nintros t2 succs ih H in_t1.\ninversion_clear in_t1.\ninversion_clear H; assumption.\napply ih.\ninversion_clear H; assumption.\nassumption.\nQed.\n\n\nInductive Is_Monotone (t : Tree) : Prop :=\n    is_monotone_intro :\n      (forall t0 : Tree,\n       Successor t0 t ->\n       forall i : I,\n       P (root t0) i -> forall t1 : Tree, Successor t1 t0 -> P (root t1) i) ->\n      Is_Monotone t.\n\n\n\nLemma is_monotone_successor :\n forall T : Tree,\n Is_Monotone T -> forall t : Tree, Successor t T -> Is_Monotone t.\nintros T mon_T t suc_t.\napply is_monotone_intro.\nintros t0 suc_t0 i Pa t1 suc_1.\ninversion_clear mon_T.\napply H with t0.\napply succs_trans with t; assumption.\nassumption.\nassumption.\nQed.\n\n\nLemma is_monotone_tree_is_monotone :\n forall t : Tree, Is_Monotone_Tree t -> Is_Monotone t.\nintros t H.\napply is_monotone_intro.\nintros t0 suc_t0.\ngeneralize (is_monotone_tree_successor t H t0 suc_t0); clear H suc_t0 t.\nintros H i P0 t1 suc_t1.\ngeneralize P0; clear P0.\ngeneralize H; clear H.\nelim suc_t1; clear suc_t1 t0 t1.\ntrivial.\nintros t0 t1 in_t1 t2 suc_t2 ih H P0.\napply ih; clear ih.\napply is_monotone_tree_successor with t0.\nassumption.\napply successor_trans with t1.\nassumption.\napply successor_refl.\ngeneralize P0; clear P0.\ngeneralize in_t1; clear in_t1.\ninversion_clear H.\nsimpl in |- *.\nintros in_t1 Pa.\ngeneralize H0; clear H0.\ngeneralize in_t1; clear in_t1.\nelim succs; clear succs.\nintros in_t1 H0.\ninversion_clear in_t1.\nintros t3 succs ih in_t1 H0.\ninversion_clear in_t1.\ninversion_clear H0.\napply H; assumption.\napply ih.\nassumption.\ninversion_clear H0; assumption.\nQed.\n\n\nEnd Trees.\n", "meta": {"author": "coq-contribs", "repo": "ipc", "sha": "eab92b40792d59a991abfba2e2e6af6aa2d18031", "save_path": "github-repos/coq/coq-contribs-ipc", "path": "github-repos/coq/coq-contribs-ipc/ipc-eab92b40792d59a991abfba2e2e6af6aa2d18031/theories/Trees.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.7853085859124003, "lm_q1q2_score": 0.679467895327582}}
{"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(** 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, 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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Coq generates induction principles for every datatype defined with\n    [Inductive], including those that aren't recursive.  Although of\n    course we don't need induction to prove properties of\n    non-recursive datatypes, the idea of an induction principle still\n    makes sense for them: it gives a way to prove that a property\n    holds for all values of the type.\n\n    These generated principles follow a similar pattern. If we define\n    a type [t] with constructors [c1] ... [cn], Coq generates a\n    theorem with this shape:\n\n    t_ind : forall P : t -> Prop,\n              ... case for c1 ... ->\n              ... case for c2 ... -> ...\n              ... case for cn ... ->\n              forall n : t, P n\n\n    The specific shape of each case depends on the arguments to the\n    corresponding constructor.  Before trying to write down a general\n    rule, let's look at some more examples. First, an example where\n    the constructors take no arguments: *)\n\nInductive yesno : Type :=\n  | yes\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\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? \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, 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(** **** 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  (* FILL IN HERE *)\n.\n(** [] *)\n\n(* ################################################################# *)\n(** * Polymorphism *)\n\n(** Next, what about polymorphic datatypes?\n\n    The inductive definition of polymorphic lists\n\n      Inductive list (X:Type) : Type :=\n        | nil : list X\n        | cons : X -> list X -> list X.\n\n    is very similar to that of [natlist].  The main difference is\n    that, here, the whole definition is _parameterized_ on a set [X]:\n    that is, we are defining a _family_ of inductive types [list X],\n    one for each [X].  (Note that, wherever [list] appears in the body\n    of the declaration, it is always applied to the parameter [X].)\n    The induction principle is likewise parameterized on [X]:\n\n      list_ind :\n        forall (X : Type) (P : list X -> Prop),\n           P [] ->\n           (forall (x : X) (l : list X), P l -> P (x :: l)) ->\n           forall l : list X, P l\n\n    Note that the _whole_ induction principle is parameterized on\n    [X].  That is, [list_ind] can be thought of as a polymorphic\n    function that, when applied to a type [X], gives us back an\n    induction principle specialized to the type [list X]. *)\n\n(** **** Exercise: 1 star, standard, optional (tree)  \n\n    Write out the induction principle that Coq will generate for\n   the following datatype.  Compare your answer with what Coq\n   prints. *)\n\nInductive tree (X:Type) : Type :=\n  | leaf (x : X)\n  | node (t1 t2 : tree X).\nCheck tree_ind.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (mytype)  \n\n    Find an inductive definition that gives rise to the\n    following induction principle:\n\n      mytype_ind :\n        forall (X : Type) (P : mytype X -> Prop),\n            (forall x : X, P (constr1 X x)) ->\n            (forall n : nat, P (constr2 X n)) ->\n            (forall m : mytype X, P m ->\n               forall n : nat, P (constr3 X m n)) ->\n            forall m : mytype X, P m\n*) \n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (foo)  \n\n    Find an inductive definition that gives rise to the\n    following induction principle:\n\n      foo_ind :\n        forall (X Y : Type) (P : foo X Y -> Prop),\n             (forall x : X, P (bar X Y x)) ->\n             (forall y : Y, P (baz X Y y)) ->\n             (forall f1 : nat -> foo X Y,\n               (forall n : nat, P (f1 n)) -> P (quux X Y f1)) ->\n             forall f2 : foo X Y, P f2\n*) \n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (foo')  \n\n    Consider the following inductive definition: *)\n\nInductive foo' (X:Type) : Type :=\n  | C1 (l : list X) (f : foo' X)\n  | C2.\n\n(** What induction principle will Coq generate for [foo']?  Fill\n   in the blanks, then check your answer with Coq.)\n\n     foo'_ind :\n        forall (X : Type) (P : foo' X -> Prop),\n              (forall (l : list X) (f : foo' X),\n                    _______________________ ->\n                    _______________________   ) ->\n             ___________________________________________ ->\n             forall f : foo' X, ________________________\n*)\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Induction Hypotheses *)\n\n(** Where does the phrase \"induction hypothesis\" fit into this story?\n\n    The induction principle for numbers\n\n       forall P : nat -> Prop,\n            P 0  ->\n            (forall n : nat, P n -> P (S n))  ->\n            forall n : nat, P n\n\n   is a generic statement that holds for all propositions\n   [P] (or rather, strictly speaking, for all families of\n   propositions [P] indexed by a number [n]).  Each time we\n   use this principle, we are choosing [P] to be a particular\n   expression of type [nat->Prop].\n\n   We can make proofs by induction more explicit by giving\n   this expression a name.  For example, instead of stating\n   the theorem [mult_0_r] as \"[forall n, n * 0 = 0],\" we can\n   write it as \"[forall n, P_m0r n]\", where [P_m0r] is defined\n   as... *)\n\nDefinition P_m0r (n:nat) : Prop :=\n  n * 0 = 0.\n\n(** ... or equivalently: *)\n\nDefinition P_m0r' : nat->Prop :=\n  fun n => n * 0 = 0.\n\n(** Now it is easier to see where [P_m0r] appears in the proof. *)\n\nTheorem mult_0_r'' : forall n:nat,\n  P_m0r n.\nProof.\n  apply nat_ind.\n  - (* n = O *) reflexivity.\n  - (* n = S n' *)\n    (* Note the proof state at this point! *)\n    intros n IHn.\n    unfold P_m0r in IHn. unfold P_m0r. simpl. apply IHn. Qed.\n\n(** This extra naming step isn't something that we do in\n    normal proofs, but it is useful to do it explicitly for an example\n    or two, because it allows us to see exactly what the induction\n    hypothesis is.  If we prove [forall n, P_m0r n] by induction on\n    [n] (using either [induction] or [apply nat_ind]), we see that the\n    first subgoal requires us to prove [P_m0r 0] (\"[P] holds for\n    zero\"), while the second subgoal requires us to prove [forall n',\n    P_m0r n' -> P_m0r (S n')] (that is \"[P] holds of [S n'] if it\n    holds of [n']\" or, more elegantly, \"[P] is preserved by [S]\").\n    The _induction hypothesis_ is the premise of this latter\n    implication -- the assumption that [P] holds of [n'], which we are\n    allowed to use in proving that [P] holds for [S n']. *)\n\n(* ################################################################# *)\n(** * More on the [induction] Tactic *)\n\n(** The [induction] tactic actually does even more low-level\n    bookkeeping for us than we discussed above.\n\n    Recall the informal statement of the induction principle for\n    natural numbers:\n      - If [P n] is some proposition involving a natural number n, and\n        we want to show that P holds for _all_ numbers n, we can\n        reason like this:\n          - show that [P O] holds\n          - show that, if [P n'] holds, then so does [P (S n')]\n          - conclude that [P n] holds for all n.\n    So, when we begin a proof with [intros n] and then [induction n],\n    we are first telling Coq to consider a _particular_ [n] (by\n    introducing it into the context) and then telling it to prove\n    something about _all_ numbers (by using induction).\n\n    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    Rewrite both [plus_assoc'] and [plus_comm'] and their proofs in\n    the same style as [mult_0_r''] above -- that is, for each theorem,\n    give an explicit [Definition] of the proposition being proved by\n    induction, and state the theorem and proof in terms of this\n    defined proposition.  *)\n\n(* FILL IN HERE \n\n    [] *)\n\n(* ################################################################# *)\n(** * Induction Principles 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": "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/IndPrinciples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085758631159, "lm_q2_score": 0.8652240791017536, "lm_q1q2_score": 0.679467889361874}}
{"text": "Require Import ssreflect ssrbool eqtype ssrnat.\n\n(**\n# 第8回\n\nhttp://qnighy.github.io/coqex2014/ex6.html\n\n## 課題37 (種別:A / 締め切り : 2014/06/01)\n\n自然数の対の商集合として整数を定義する。下の証明の空欄を埋めよ。\nomega等を使ってもよい。\n*)\nRequire Import SetoidClass.\n\nRecord int :=\n  {\n    Ifst : nat;\n    Isnd : nat\n  }.\n\nLemma addn2r p m n : (m + p = n + p) -> (m = n).\nProof.\n  move/eqP => H.\n  apply/eqP.\n  by rewrite -(eqn_add2r p).\nQed.\n\nProgram Instance ISetoid : Setoid int :=\n  {|\n    equiv x y :=                            (* == *)\n      Ifst x + Isnd y = Ifst y + Isnd x\n  |}.\nNext Obligation.\nProof.\n  (* http://d.hatena.ne.jp/m-a-o/20110112 *)\n  apply Build_Equivalence.\n  by rewrite /Reflexive.\n  by rewrite /Symmetric.\n  rewrite /Transitive.\n  move=> x y z.\n  move=> Hxy Hyz.\n  apply (addn2r (Ifst y + Isnd y)).\n  rewrite !addnA.\n  rewrite [Ifst x + Isnd z + Ifst y + Isnd y]addnC.\n  rewrite [Ifst z + Isnd x + Ifst y + Isnd y]addnC.\n  rewrite !addnA.\n  rewrite [Isnd y + Ifst x]addnC.\n  rewrite [Isnd y + Ifst z]addnC.\n  rewrite Hxy.\n  rewrite -Hyz.\n  rewrite [Ifst y + Isnd z + Isnd x + Ifst y]addnC.\n  rewrite [Ifst y + Isnd z + Isnd x]addnC.\n  rewrite [Ifst y + Isnd z]addnC.\n  rewrite !addnA.\n  by [].\nQed.\n\nDefinition zero : int :=\n  {|\n    Ifst := 0;\n    Isnd := 0\n  |}.\n\nDefinition int_plus (x y : int) : int :=\n  {|\n    Ifst := Ifst x + Ifst y;\n    Isnd := Isnd x + Isnd y\n  |}.\n\nDefinition int_minus (x y : int) : int :=\n  {|\n    Ifst := Ifst x + Isnd y;\n    Isnd := Isnd x + Ifst y\n  |}.\n\nLemma int_sub_diag : forall x, int_minus x x == zero.\nProof.\n  move=> x.\n  by rewrite /= addn0 add0n addnC.\nQed.\n\n(* まず、int_minus_compatを証明せずに、下の2つの証明を実行して、\nどちらも失敗することを確認せよ。*)\n\nInstance int_plus_compat :\n  Proper (equiv ==> equiv ==> equiv) int_plus.\nProof.\n  unfold Proper.\n  unfold respectful.                        (* ==> *)\n  move=> x y Hxy x' y' Hx'y'.\n  rewrite /int_plus /=.\n\n  have Hxy2 : (Ifst x + Isnd y = Ifst y + Isnd x) by apply Hxy.\n  have Hx'y'2 : (Ifst x' + Isnd y' = Ifst y' + Isnd x') by apply Hx'y'.\n  \n  rewrite 2!addnA.\n  rewrite -[Ifst x + Ifst x' + Isnd y]addnA.\n  rewrite [Ifst x' + Isnd y]addnC.\n  rewrite addnA.\n  rewrite Hxy2.  \n  rewrite -[(Ifst y + Isnd x) + Ifst x' + Isnd y']addnA.\n  rewrite Hx'y'2.\n  rewrite addnA.\n  rewrite -[Ifst y + Isnd x + Ifst y']addnA.\n  rewrite [Isnd x + Ifst y']addnC.\n  rewrite addnA.\n  by [].\nQed.\n\nInstance int_minus_compat :\n  Proper (equiv ==> equiv ==> equiv) int_minus.\nProof.\n  unfold Proper.\n  unfold respectful.                        (* ==> *)\n  move=> x y Hxy x' y' Hx'y'.\n  rewrite /int_minus /=.\n\n  have Hxy2 : (Ifst x + Isnd y = Ifst y + Isnd x) by apply Hxy.\n  have Hx'y'2 : (Ifst x' + Isnd y' = Ifst y' + Isnd x') by apply Hx'y'.\n  \n  rewrite 2!addnA.\n  rewrite [Ifst x + Isnd x' + Isnd y]addnC.\n  rewrite [Ifst y + Isnd y' + Isnd x]addnC.\n  rewrite 2!addnA.\n  rewrite [Isnd y + Ifst x]addnC.\n  rewrite -addnA.\n  rewrite [Isnd x' + Ifst y']addnC.\n  rewrite [Isnd x + Ifst y]addnC.\n  rewrite -Hx'y'2.\n  rewrite -Hxy2.\n  rewrite -[(Ifst x + Isnd y) + Isnd y' + Ifst x']addnA.\n  rewrite [Isnd y' + Ifst x']addnC.\n  by [].\nQed.\n\nGoal forall x y, int_minus x (int_minus y y) == int_minus x zero.\nProof.\n  intros x y.\n  rewrite int_sub_diag.\n  reflexivity.\nQed.\n\nGoal forall x y, int_minus x (int_minus y y) == int_minus x zero.\nProof.\n  intros x y.\n  rewrite -!{1}int_sub_diag.                (* SSReflectのタクティカルも使える。 *)\n  reflexivity.\nQed.\n\nGoal forall x y, int_minus x (int_minus y y) == int_minus x zero.\nProof.\n  intros x y.\n  setoid_rewrite int_sub_diag.\n  reflexivity.\nQed.\n\n(**\n\nおまけ : ISetoidの定義においてProgram InstanceをInstanceに変更し、Next Obligation. を取り除\nいてもISetoidは定義できるが、続きがうまくいかなくなる。これは何故か？\n\nヒント\n\n通常のイコール (Coq.Init.Logic.eq) 以外の同値関係を入れたい場合、Setoidを使います。Setoidに\nよる書き換えは、通常rewriteで行えます。明示的にSetoidを使う場合は、setoid_rewriteを使います。\n\nSetoidによってreplaceを行いたい場合はsetoid_replaceを使えます。通常のイコールと違い、\nSetoidの同値関係を保存しない写像が存在する可能性があります。例えば、この問題におけるIfst関\n数はSetoidの同値関係を保存しません。Setoidによる書き換えを行うためには、それぞれの関数が同\n値関係を保存することを逐一証明する必要があります。\n\nRecordは単一のコンストラクタを持ち再帰的でない型を定義するのに使えるコマンドです。メンバを\n取り出す関数(この例ではIfst, Isnd)が自動的に定義されることや、{| ... |} という構文でRecord\n型の値を記述できるという利点があります。\n*)\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/ex2014/ex37.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6794678866326992}}
{"text": "Set 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 exercise8.\n\nModule AExp.\n\nInductive aexp : Type :=\n  | ANum (n : nat)\n  | APlus (a1 a2 : aexp)\n  | AMinus (a1 a2 : aexp)\n  | AMult (a1 a2 : aexp).\n\nInductive bexp : Type :=\n  | BTrue\n  | BFalse\n  | BEq (a1 a2 : aexp)\n  | BNeq (a1 a2 : aexp)\n  | BLe (a1 a2 : aexp)\n  | BGt (a1 a2 : aexp)\n  | BNot (b : bexp)\n  | BAnd (b1 b2 : 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\nCompute aeval (APlus (ANum 2) (ANum 2)). (* it evaluates to 4. *)\n\nFixpoint beval (b : bexp) : bool :=\n  match b with\n  | BTrue => true\n  | BFalse => false\n  | BEq a1 a2 => (aeval a1) =? (aeval a2)\n  | BNeq a1 a2 => negb ((aeval a1) =? (aeval a2))\n  | BLe a1 a2 => (aeval a1) <=? (aeval a2)\n  | BGt a1 a2 => negb ((aeval a1) <=? (aeval a2))\n  | BNot 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\nTheorem optimize_0plus_sound: forall a,\n  aeval (optimize_0plus a) = aeval a.\nProof.\n  intros. induction a.\n  - trivial.\n  - destruct a1; try destruct n; try destruct a2; simpl; auto.\n  - simpl. auto.\n  - simpl. auto.\nQed.\n\n(* Since the optimize_0plus transformation doesn't change the value of aexps, we should be able to apply\nit to all the aexps that appear in a bexp without changing the bexp's value. Write a function that\nperforms this transformation on bexps and prove it is sound. Use the tacticals we've just seen to make\nthe proof as short and elegant as possible. *)\nFixpoint optimize_0plus_b (b : bexp) : bexp :=\n  match b with\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  | _ => b\n  end.\n\nTheorem optimize_0plus_b_sound : forall b,\n  beval (optimize_0plus_b b) = beval b.\nProof.\n  intros. induction b; simpl; repeat rewrite optimize_0plus_sound; trivial.\n  - rewrite IHb. trivial.\n  - rewrite IHb1. rewrite IHb2. trivial.\nQed.\n\nLtac invert H := inversion H; subst; clear H.\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) ->\n      (e2 ==> n2) ->\n      (APlus e1 e2) ==> (n1 + n2)\n  | E_AMinus (e1 e2 : aexp) (n1 n2 : nat) :\n      (e1 ==> n1) ->\n      (e2 ==> n2) ->\n      (AMinus e1 e2) ==> (n1 - n2)\n  | E_AMult (e1 e2 : aexp) (n1 n2 : nat) :\n      (e1 ==> n1) ->\n      (e2 ==> n2) ->\n      (AMult e1 e2) ==> (n1 * n2)\n\n      where \"e '==>' n\" := (aevalR e n) : type_scope.\n\nTheorem aeval_iff_aevalR : forall a n,\n  (a ==> n) <-> aeval a = n.\nProof.\n  split; intros.\n  - induction H; simpl; auto.\n  - generalize dependent n.\n    induction a; simpl; intros; subst; constructor; \n    try apply IHa1; try apply IHa2; trivial.\nQed.\n\nReserved Notation \"e '==>b' b\" (at level 90, left associativity).\n\nInductive bevalR : bexp -> bool -> Prop :=\n  | E_BTrue : BTrue ==>b true\n  | E_BFalse : BFalse ==>b false\n  | E_BEq (e1 e2 : aexp) (n1 n2 : nat) :\n    e1 ==> n1 ->\n    e2 ==> n2 ->\n    (BEq e1 e2 ==>b n1 =? n2)\n  | E_BNeq (e1 e2 : aexp) (n1 n2 : nat) :\n    e1 ==> n1 ->\n    e2 ==> n2 ->\n    (BNeq e1 e2 ==>b negb (n1 =? n2))\n  | E_BLe (e1 e2 : aexp) (n1 n2 : nat) :\n    e1 ==> n1 ->\n    e2 ==> n2 ->\n    (BLe e1 e2 ==>b n1 <=? n2)\n  | E_BGt (e1 e2 : aexp) (n1 n2 : nat) :\n    e1 ==> n1 ->\n    e2 ==> n2 ->\n    (BGt e1 e2 ==>b negb (n1 <=? n2))\n  | E_BNot (e : bexp) (b : bool) :\n    e ==>b b ->\n    BNot e ==>b negb b\n  | E_BAnd (e1 e2 : bexp) (b1 b2 : bool) :\n    (e1 ==>b b1) ->\n    (e2 ==>b b2) ->\n    BAnd e1 e2 ==>b andb b1 b2\n\n  where \"e '==>b' b\" := (bevalR e b) : type_scope.\n\nLemma beval_iff_bevalR : forall b bv,\n  b ==>b bv <-> beval b = bv.\nProof.\n  split; intro.\n  - induction H; simpl; auto; try apply aeval_iff_aevalR in H, H0; try rewrite H, H0; trivial.\n    + rewrite IHbevalR. trivial.\n    + rewrite IHbevalR1, IHbevalR2. trivial.\n  - generalize dependent bv. \n    induction b; simpl; intros; subst; constructor; try apply aeval_iff_aevalR; trivial.\n    + apply IHb. trivial.\n    + apply IHb1. trivial.\n    + apply IHb2. trivial.\nQed.\n\nEnd AExp.\n\nDefinition state := total_map nat.\n\nInductive aexp : Type :=\n  | ANum (n : nat)\n  | AId (x : string) (* <--- NEW *)\n  | APlus (a1 a2 : aexp)\n  | AMinus (a1 a2 : aexp)\n  | AMult (a1 a2 : aexp).\n\nDefinition W : string := \"W\".\nDefinition X : string := \"X\".\nDefinition Y : string := \"Y\".\nDefinition Z : string := \"Z\".\n\nInductive bexp : Type :=\n  | BTrue\n  | BFalse\n  | BEq (a1 a2 : aexp)\n  | BNeq (a1 a2 : aexp)\n  | BLe (a1 a2 : aexp)\n  | BGt (a1 a2 : aexp)\n  | BNot (b : bexp)\n  | BAnd (b1 b2 : bexp).\n\nCoercion AId : string >-> aexp.\nCoercion ANum : nat >-> aexp.\n\nDeclare Custom Entry com.\nDeclare Scope com_scope.\nNotation \"<{ e }>\" := e (at level 0, e custom com at level 99) : com_scope.\nNotation \"( x )\" := x (in custom com, x at level 99) : com_scope.\nNotation \"x\" := x (in custom com at level 0, x constr at level 0) : com_scope.\nNotation \"f x .. y\" := (.. (f x) .. y)\n                  (in custom com at level 0, only parsing,\n                  f constr at level 0, x constr at level 9,\n                  y constr at level 9) : com_scope.\nNotation \"x + y\" := (APlus x y) (in custom com at level 50, left associativity).\nNotation \"x - y\" := (AMinus x y) (in custom com at level 50, left associativity).\nNotation \"x * y\" := (AMult x y) (in custom com at level 40, left associativity).\nNotation \"'true'\" := true (at level 1).\nNotation \"'true'\" := BTrue (in custom com at level 0).\nNotation \"'false'\" := false (at level 1).\nNotation \"'false'\" := BFalse (in custom com at level 0).\nNotation \"x <= y\" := (BLe x y) (in custom com at level 70, no associativity).\nNotation \"x > y\" := (BGt x y) (in custom com at level 70, no associativity).\nNotation \"x = y\" := (BEq x y) (in custom com at level 70, no associativity).\nNotation \"x <> y\" := (BNeq x y) (in custom com at level 70, no associativity).\nNotation \"x && y\" := (BAnd x y) (in custom com at level 80, left associativity).\nNotation \"'~' b\" := (BNot b) (in custom com at level 75, right associativity).\nOpen Scope com_scope.\n\n(* We can now write 3 + (X × 2) instead of APlus 3 (AMult X 2), and true && ~(X ≤ 4) instead of BAnd \ntrue (BNot (BLe X 4)). *)\n\nFixpoint aeval (st : state) (* <--- NEW *) (a : aexp) : nat :=\n  match a with\n  | ANum n => n\n  | AId x => st x (* <--- NEW *)\n  | <{a1 + a2}> => (aeval st a1) + (aeval st a2)\n  | <{a1 - a2}> => (aeval st a1) - (aeval st a2)\n  | <{a1 * a2}> => (aeval st a1) * (aeval st a2)\n  end.\n\nFixpoint beval (st : state) (* <--- NEW *) (b : bexp) : bool :=\n  match b with\n  | <{true}> => true\n  | <{false}> => false\n  | <{a1 = a2}> => (aeval st a1) =? (aeval st a2)\n  | <{a1 <> a2}> => negb ((aeval st a1) =? (aeval st a2))\n  | <{a1 <= a2}> => (aeval st a1) <=? (aeval st a2)\n  | <{a1 > a2}> => negb ((aeval st a1) <=? (aeval st a2))\n  | <{~ b1}> => negb (beval st b1)\n  | <{b1 && b2}> => andb (beval st b1) (beval st b2)\n  end.\n\nDefinition empty_st := (_ !-> 0).\n\n(* singleton state *)\nNotation \"x '!->' v\" := (x !-> v ; empty_st) (at level 100).\n\nInductive com : Type :=\n  | CSkip\n  | CAsgn (x : string) (a : aexp)\n  | CSeq (c1 c2 : com)\n  | CIf (b : bexp) (c1 c2 : com)\n  | CWhile (b : bexp) (c : com).\n\nNotation \"'skip'\" :=\n    CSkip (in custom com at level 0) : com_scope.\nNotation \"x := y\" :=\n    (CAsgn x y)\n       (in custom com at level 0, x constr at level 0,\n        y at level 85, no associativity) : com_scope.\nNotation \"x ; y\" :=\n    (CSeq x y)\n      (in custom com at level 90, right associativity) : com_scope.\nNotation \"'if' x 'then' y 'else' z 'end'\" :=\n    (CIf x y z)\n      (in custom com at level 89, x at level 99,\n       y at level 99, z at level 99) : com_scope.\nNotation \"'while' x 'do' y 'end'\" :=\n    (CWhile x y)\n       (in custom com at level 89, x at level 99, y at level 99) : com_scope.\n\nFixpoint ceval_fun_no_while (st : state) (c : com) : state :=\n  match c with\n    | <{ skip }> =>\n        st\n    | <{ x := a }> =>\n        (x !-> (aeval st a) ; st)\n    | <{ c1 ; c2 }> =>\n        let st' := ceval_fun_no_while st c1 in\n        ceval_fun_no_while st' c2\n    | <{ if b then c1 else c2 end}> =>\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(* Operational Semantics *)\nReserved Notation\n         \"st '=[' c ']=>' st'\"\n         (at level 40, c custom com at level 99,\n          st constr, st' constr at next level).\n\nInductive ceval : com -> state -> state -> Prop :=\n  | E_Skip : forall st,\n      st =[ skip ]=> st\n  | E_Asgn : forall st a n x,\n      aeval st a = n ->\n      st =[ x := a ]=> (x !-> n ; st)\n  | E_Seq : forall c1 c2 st st' st'',\n      st =[ c1 ]=> st' ->\n      st' =[ c2 ]=> st'' ->\n      st =[ c1 ; c2 ]=> st''\n  | E_IfTrue : forall st st' b c1 c2,\n      beval st b = true ->\n      st =[ c1 ]=> st' ->\n      st =[ if b then c1 else c2 end]=> st'\n  | E_IfFalse : forall st st' b c1 c2,\n      beval st b = false ->\n      st =[ c2 ]=> st' ->\n      st =[ if b then c1 else c2 end]=> st'\n  | E_WhileFalse : forall b st c,\n      beval st b = false ->\n      st =[ while b do c end ]=> st\n  | E_WhileTrue : forall st st' st'' b c,\n      beval st b = true ->\n      st =[ c ]=> st' ->\n      st' =[ while b do c end ]=> st'' ->\n      st =[ while b do c end ]=> st''\n\n  where \"st =[ c ]=> st'\" := (ceval c st st').\n\nExample ceval_example1:\n  empty_st =[\n     X := 2;\n     if (X <= 1)\n       then Y := 3\n       else Z := 4\n     end\n  ]=> (Z !-> 4 ; X !-> 2).\nProof.\n  apply E_Seq with (X !-> 2).\n  - apply E_Asgn. trivial.\n  - apply E_IfFalse.\n    + trivial.\n    + apply E_Asgn. trivial.\nQed.\n\nExample ceval_example2:\n  empty_st =[\n    X := 0;\n    Y := 1;\n    Z := 2\n  ]=> (Z !-> 2 ; Y !-> 1 ; X !-> 0).\nProof.\n  apply E_Seq with (X !-> 0).\n  - apply E_Asgn. trivial.\n  - apply E_Seq with (Y !-> 1; X !-> 0); (* Treat as a whole. *)\n  apply E_Asgn; trivial.\nQed.\n\nDefinition 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(* Write an Imp program that sums the numbers from 1 to X (inclusive: 1 + 2 + ... + X) in the variable Y.  *)\nDefinition pup_to_n : com :=\n  <{\n    Y := 0;\n    while X <> 0 do\n      Y := Y + X;\n      X := X - 1\n    end\n  }>.\n\nTheorem pup_to_2_ceval :\n  (X !-> 2) =[\n    pup_to_n\n  ]=> (X !-> 0 ; Y !-> 3 ; X !-> 1 ; Y !-> 2 ; Y !-> 0 ; X !-> 2). \n  (* can be treated as a reverse-ordered state list? *)\n  (* final, prev1, prev2, initial. *)\nProof.\n  unfold pup_to_n.\n  apply E_Seq with (Y !-> 0 ; X !-> 2).\n  - apply E_Asgn. trivial.\n  - apply E_WhileTrue with (X !-> 1 ; Y !-> 2 ; Y !-> 0 ; X !-> 2).\n    * trivial.\n    * apply E_Seq with (Y !-> 2; Y !-> 0; X !-> 2); apply E_Asgn; trivial.\n    * apply E_WhileTrue with (X !-> 0 ; Y !-> 3 ; X !-> 1 ; Y !-> 2 ; Y !-> 0 ; X !-> 2).\n      + trivial.\n      + apply E_Seq with (Y !-> 3 ; X !-> 1 ; Y !-> 2 ; Y !-> 0 ; X !-> 2); apply E_Asgn; trivial.\n      + apply E_WhileFalse. trivial.\nQed.\n\nTheorem ceval_deterministic : forall c st st1 st2,\n  st =[ c ]=> st1 ->\n  st =[ c ]=> st2 ->\n  st1 = st2.\nProof.\n  intros c st st1 st2 E1 E2.\n  generalize dependent st2.\n  induction E1; intros; inversion E2; subst.\n  - trivial.\n  - trivial.\n  - apply IHE1_2. apply IHE1_1 in H1. subst. apply H4.\n  - apply IHE1. apply H6.\n  - rewrite H in H5. discriminate.\n  - rewrite H in H5. discriminate.\n  - apply IHE1. apply H6.\n  - trivial.\n  - rewrite H in H2. discriminate.\n  - rewrite H in H4. discriminate.\n  - apply IHE1_2. apply IHE1_1 in H3. rewrite H3. apply H6.\nQed.\n\nDefinition plus2 : com :=\n  <{ X := X + 2 }>.\n\nTheorem plus2_spec: forall st n st',\n  st X = n ->\n  st =[ plus2 ]=> st' ->\n  st' X = n + 2.\nProof.\n  unfold plus2. intros. inversion H0. subst.\n  trivial.\nQed.\n\nDefinition XtimesYinZ : com :=\n  <{ Z := X * Y }>.\n\nTheorem XtimesYinZ_spec: forall st n1 n2 st',\n  st X = n1 ->\n  st Y = n2 ->\n  st =[ XtimesYinZ ]=> st' ->\n  st' Z = n1 * n2.\nProof.\n  unfold XtimesYinZ. intros.\n  inversion H1. subst.\n  trivial.\nQed.\n\nDefinition loop : com :=\n  <{ while true do\n       skip\n     end }>.\n\nTheorem loop_never_stops : forall st st',\n  ~(st =[ loop ]=> st').\nProof.\n  intros st st' contra. unfold loop in contra.\n  remember <{ while true do skip end }> as loopdef\n           eqn : Heqloopdef.\n  induction contra; try discriminate. \n  - inversion Heqloopdef. rewrite H1 in H. discriminate.\n  - inversion Heqloopdef. subst. apply IHcontra2. apply Heqloopdef.\nQed.\n\nFixpoint no_whiles (c : com) : bool :=\n  match c with\n  | <{ skip }> =>\n      true\n  | <{ _ := _ }> =>\n      true\n  | <{ c1 ; c2 }> =>\n      andb (no_whiles c1) (no_whiles c2)\n  | <{ if _ then ct else cf end }> =>\n      andb (no_whiles ct) (no_whiles cf)\n  | <{ while _ do _ end }> =>\n      false\n  end.\n\nInductive no_whilesR: com -> Prop :=\n  | R_skip : no_whilesR <{ skip }>\n  | R_asgn : forall lhs rhs, no_whilesR <{ lhs := rhs }>\n  | R_seq : forall c1 c2, no_whilesR c1 -> no_whilesR c2 -> no_whilesR <{ c1 ; c2 }>\n  | R_ifesle : forall exp c1 c2, no_whilesR c1 -> no_whilesR c2 -> no_whilesR <{ if exp then c1 else c2 end }>.\n\nTheorem no_whiles_eqv:\n  forall c, no_whiles c = true <-> no_whilesR c.\nProof.\n  split; intros.\n  - induction c.\n    + apply R_skip.\n    + apply R_asgn.\n    + inversion H. apply andb_true_iff in H1. destruct H1. apply R_seq. apply IHc1. auto. apply IHc2. auto.\n    + inversion H. apply andb_true_iff in H1. destruct H1. apply R_ifesle. apply IHc1. auto. apply IHc2. auto.\n    + inversion H.\n  - induction H; auto; simpl; apply andb_true_iff; split; auto.\nQed.\n\nTheorem no_whiles_terminating : forall st c,\n  no_whilesR c ->\n  exists st', st =[ c ]=> st'.\nProof.\n  intros. (* There is no meaning introducing st. *)\n  generalize dependent st. induction H; intros.\n  - exists st. apply E_Skip.\n  - exists (lhs !-> aeval st rhs; st). apply E_Asgn. trivial.\n  - destruct IHno_whilesR1 with st. destruct IHno_whilesR2 with x. (* fix some existing state. *)\n    exists x0. apply E_Seq with x; auto.\n  - destruct IHno_whilesR1 with st. destruct IHno_whilesR2 with st.\n    destruct (beval st exp) eqn : H'. (* destruct condition. *)\n    + exists x. apply E_IfTrue. apply H'. apply H1.\n    + exists x0. apply E_IfFalse. apply H'. apply H2.\nQed.\n\nInductive sinstr : Type :=\n| SPush (n : nat)\n| SLoad (x : string)\n| SPlus\n| SMinus\n| SMult.\n\n\nFixpoint s_execute (st : state) (stack : list nat)\n                   (prog : list sinstr)\n                 : list nat :=\n  match prog with\n  | [] => stack\n  | cons inst l' =>\n      match inst with\n      | SPush n => s_execute (st) (n :: stack)  (l')\n      | SLoad x => s_execute (st) ((aeval st (AId x)) :: stack) (l')\n      | SPlus => \n        match stack with\n        | n1 :: n2 :: l'' => s_execute (st) ((n2 + n1) :: l'') (l')\n        | _ => s_execute st stack l'\n        end\n      | SMinus => \n        match stack with\n        | n1 :: n2 :: l'' => s_execute (st) ((n2 - n1) :: l'') (l')\n        | _ => s_execute st stack l'\n        end\n      | SMult =>\n        match stack with\n        | n1 :: n2 :: l'' => s_execute (st) ((n2 * n1) :: l'') (l')\n        | _ => s_execute st stack l'\n        end\n      end\n  end.\n\nExample s_execute1 :\n     s_execute empty_st []\n       [SPush 5; SPush 3; SPush 1; SMinus]\n   = [2; 5].\nProof. trivial. Qed.\n\nExample s_execute2 :\n     s_execute (X !-> 3) [3;4]\n       [SPush 4; SLoad X; SMult; SPlus]\n   = [15; 4].\nProof. trivial. Qed.\n\nFixpoint s_compile (e : aexp) : list sinstr :=\n  match e with\n  | ANum n => [SPush n]\n  | AId x => [SLoad x]\n  | APlus exp1 exp2 => s_compile (exp1) ++ s_compile (exp2) ++ [SPlus]\n  | AMinus exp1 exp2 => s_compile (exp1) ++ s_compile (exp2) ++ [SMinus]\n  | AMult exp1 exp2 => s_compile (exp1) ++ s_compile (exp2) ++ [SMult]\n  end.\n\nExample s_compile1 :\n  s_compile <{ X - (2 * Y) }>\n  = [SLoad X; SPush 2; SLoad Y; SMult; SMinus].\nProof. trivial. Qed.\n\nTheorem execute_app : forall st p1 p2 stack,\n  s_execute st stack (p1 ++ p2) = s_execute st (s_execute st stack p1) p2.\nProof.\n  induction p1.\n  - trivial.\n  - induction a; intros.\n    + simpl. auto.\n    + simpl. auto.\n    + induction stack; simpl; auto; induction stack; simpl; auto.\n    + induction stack; simpl; auto; induction stack; simpl; auto.\n    + induction stack; simpl; auto; induction stack; simpl; auto.\nQed.\n\nLemma s_compile_correct_aux : forall st e stack,\n  s_execute st stack (s_compile e) = aeval st e :: stack.\nProof.\n  induction e; trivial; intros; simpl;\n  try (rewrite app_assoc; repeat rewrite execute_app; rewrite IHe1; rewrite IHe2; trivial).\nQed.\n\nTheorem s_compile_correct : forall (st : state) (e : aexp),\n  s_execute st [] (s_compile e) = [ aeval st e ].\nProof.\n  intros. rewrite s_compile_correct_aux. trivial.\nQed.\n\nFixpoint beval_sc (st : state) (* <--- NEW *) (b : bexp) : bool :=\n  match b with\n  | <{b1 && b2}> => if negb (beval_sc st b1) then false else beval_sc st b2\n  | _ => beval st b\n  end.\n\nTheorem beval_sc_is_beval : forall st b,\n  beval st b = beval_sc st b.\nProof.\n  induction b; trivial; simpl.\n  destruct (negb (beval_sc st b1)) eqn : H.\n  - apply negb_true_iff in H. rewrite H in IHb1. rewrite IHb1. trivial.\n  - apply negb_false_iff in H. rewrite H in IHb1. rewrite IHb1. trivial.\nQed.", "meta": {"author": "hiroki-chen", "repo": "Software-Foundations", "sha": "c60a50c490603fce3c2ecaa88976349004f7fc6f", "save_path": "github-repos/coq/hiroki-chen-Software-Foundations", "path": "github-repos/coq/hiroki-chen-Software-Foundations/Software-Foundations-c60a50c490603fce3c2ecaa88976349004f7fc6f/Vol1/Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.6794388115227334}}
{"text": "From Coq Require Export String.\n\nInductive bool : Type :=\n  | true\n  | false.\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\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.\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).\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.\nExample test_nandb1: (nandb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb2: (nandb false false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb3: (nandb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb4: (nandb true true) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  match b1 with\n  | false => false\n  | true => match b2 with\n            | false => false\n            | true => match b3 with\n                      | false => false\n                      | true => true\n                      end\n            end\n  end.\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\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\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).\nExample test_oddb1: oddb 1 = true.\nProof. simpl. reflexivity. Qed.\nExample test_oddb2: oddb 4 = false.\nProof. simpl. reflexivity. Qed.\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\nExample test_mult1: (mult 3 3) = 9.\nProof. simpl. reflexivity. Qed.\n\nFixpoint minus (n m:nat) : nat :=\n  match n, m with\n  | O , _ => O\n  | S _ , O => n\n  | S n', S m' => minus n' m'\n  end.\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 n (factorial n')\n  end.\nExample test_factorial1: (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. simpl. reflexivity. Qed.\n\nNotation \"x + y\" := (plus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x - y\" := (minus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x * y\" := (mult x y)\n                       (at level 40, left associativity)\n                       : nat_scope.\nCheck ((0 + 1) + 1) : nat.\n\nFixpoint eqb (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => eqb n' m'\n            end\n  end.\n\nFixpoint leb (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => leb n' m'\n      end\n  end.\n\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\nDefinition ltb (n m : nat) : bool :=\n  match eqb n m with\n  | true => false\n  | false => leb n m\n  end.\n\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\nExample test_ltb1: (ltb 2 2) = false.\nProof. reflexivity. Qed.\nExample test_ltb2: (ltb 2 4) = true.\nProof. reflexivity. Qed.\nExample test_ltb3: (ltb 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 H.\n  intros P.\n  rewrite H.\n  rewrite P.\n  reflexivity.\nQed.\n\nTheorem mult_n_1 : forall p : nat,\n  p * 1 = p.\nProof.\n    intros p.\n    rewrite <- mult_n_Sm.\n    rewrite <- mult_n_O.\n    simpl.\n    reflexivity.\nQed.\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.\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.\nQed.\n\nTheorem andb_commutative : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b eqn:Eb.\n  - destruct c eqn:Ec.\n    + reflexivity.\n    + reflexivity.\n  - destruct c eqn:Ec.\n    + reflexivity.\n    + reflexivity.\nQed.\n\nTheorem andb3_exchange :\n  forall b c d, andb (andb b c) d = andb (andb b d) c.\nProof.\n  intros b c d. destruct b eqn:Eb.\n  - destruct c eqn:Ec.\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\n  - destruct c eqn:Ec.\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\n    { destruct d eqn:Ed.\n      - reflexivity.\n      - reflexivity. }\nQed.\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n    intros b c. destruct b eqn: Eb.\n    - destruct c eqn: Ec.\n        + simpl. reflexivity.\n        + intro H. rewrite <- H. simpl. reflexivity.\n    - destruct c eqn: Ec.\n        + intro H. rewrite <- H. simpl. reflexivity.\n        + intro H. rewrite <- H. simpl. reflexivity.\nQed.\n\nTheorem plus_1_neq_0' : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  0 =? (n + 1) = false.\nProof.\n    intros [|n].\n    - simpl. 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\nTheorem identity_fn_applied_twice :\n  forall (f : bool -> bool),\n  (forall (x : bool), f x = x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n  intros f H.\n  destruct b eqn: Eb.\n  - rewrite H. rewrite H. reflexivity.\n  - rewrite H. rewrite H. reflexivity.\nQed.\n\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.\n  destruct b eqn: Eb.\n  - rewrite H. rewrite H. simpl. reflexivity.\n  - rewrite H. rewrite H. simpl. 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 eqn: Eb.\n  - destruct c eqn: Ec.\n    + simpl. reflexivity.\n    + simpl. rewrite <- Ec. rewrite <- Eb. intro H. rewrite -> H. reflexivity.\n  - destruct c eqn: Ec.\n    + simpl. rewrite <- Ec. rewrite <- Eb. intro H. rewrite -> H. reflexivity.\n    + simpl. reflexivity.\nQed.\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.\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.\nExample test_bin_incr1 : (incr (B1 Z)) = B0 (B1 Z).\nProof. simpl. reflexivity. Qed.\nExample test_bin_incr2 : (incr (B0 (B1 Z))) = B1 (B1 Z).\nProof. simpl. reflexivity. Qed.\nExample test_bin_incr3 : (incr (B1 (B1 Z))) = B0 (B0 (B1 Z)).\nProof. simpl. reflexivity. Qed.\nExample test_bin_incr4 : bin_to_nat (B0 (B1 Z)) = 2.\nProof. simpl. reflexivity. Qed.\nExample test_bin_incr5 :\n        bin_to_nat (incr (B1 Z)) = 1 + bin_to_nat (B1 Z).\nProof. simpl. reflexivity. Qed.\nExample test_bin_incr6 :\n        bin_to_nat (incr (incr (B1 Z))) = 2 + bin_to_nat (B1 Z).\nProof. simpl. reflexivity. Qed.", "meta": {"author": "pacyu", "repo": "Software-Foundations-Solutions", "sha": "432404d7135397bc02131604b18b3ec17f5f2f07", "save_path": "github-repos/coq/pacyu-Software-Foundations-Solutions", "path": "github-repos/coq/pacyu-Software-Foundations-Solutions/Software-Foundations-Solutions-432404d7135397bc02131604b18b3ec17f5f2f07/LF/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6794226137137228}}
{"text": "Require Import BenB.\n\n(* Domeinen *)\nVariables S: Set. (* Alle studenten van de RU. *)\nVariables V: Set. (* Alle vakken bij FNWI. *)\n\n(* Constanten *)\nVariable BB: V. (* Beweren en Bewijzen *)\nVariable WS: V. (* Wiskundige Structuren *)\nVariable FD: V. (* Formeel Denken *)\n\n(* Predikaten *)\nVariable GNR (* s v *): S -> V  -> Prop.\n  (* Student s gaat naar responsiecolleges van vak v. *)\n  (* Presentielijsten van die responsiecolleges bekijken. *)\n\nVariable HV (* s v *): S -> V -> Prop.\n  (* Student s haalt vak v. *)\n  (* Cijfer in Osiris opzoeken. *)\n\nTheorem ResponsieCollegesBBLonen:\n      (forall s:S, GNR s BB -> HV s BB)\n    /\\\n      (exists s:S, GNR s BB)\n  ->\n      (exists s:S, HV s BB)\n.\nProof.\nimp_i a1.\nexi_e (exists b:S, GNR b BB) b a2.\ncon_e2 (forall s:S, GNR s BB -> HV s BB).\nhyp a1.\nexi_i b.\nimp_e (GNR b BB).\nall_e (forall b:S, GNR b BB -> HV b BB) b.\ncon_e1 (exists s:S, GNR s BB).\nhyp a1.\nhyp a2.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak11/Taak11_responsiecolleges.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857831, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6794201327670925}}
{"text": "Require Export Logic.\n\nDefinition even (n : nat) : Prop :=\n  evenb n = true.\n\nTheorem even20 : even 20.\nProof. reflexivity. Qed.\nPrint even20.\n\nInductive ev : nat -> Prop :=\n| ev_O : ev 0\n| ev_SS : forall n,  ev n -> ev (S (S n)).\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  intros n. induction n.\n  Case \"n = O\". simpl. apply ev_O.\n  Case \"n = S n\". simpl. apply ev_SS. assumption.\nQed.\n\nInductive beautiful : nat -> Prop :=\n| b_0 : beautiful 0\n| b_3 : beautiful 3\n| b_5 : beautiful 5\n| b_sum n m : beautiful n -> beautiful m -> beautiful (n + m).\n\nTheorem three_is_beautiful : beautiful 3.\nProof. apply b_3. Qed.\n\nTheorem eight_is_beautiful : beautiful 8.\nProof.\n  apply b_sum with (n := 3) (m := 5). apply b_3. apply b_5.\nQed.\n\nTheorem beautiful_plus_eight n : beautiful n -> beautiful (8+n).\nProof.\n  intros H. apply b_sum with (n := 3) (m := 5 + n).\n  apply b_3. apply b_sum with (n := 5) (m := n). apply b_5.\n  assumption.\nQed.\n\nTheorem b_times2: forall n, beautiful n -> beautiful (2 * n).\nProof.\n  intros n. intros H. simpl. apply b_sum with (n := n) (m := (n + 0)).\n  assumption. SearchAbout (_ + 0 = _). rewrite NPeano.Nat.add_0_r.\n  assumption.\nQed.\n\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m * n).\nProof.\n  intros n m H. induction m.\n  Case \"m = O\". apply b_0.\n  Case \"m = S m\". simpl. apply b_sum with (n := n ) (m := m * n). assumption.\n  assumption.\nQed.\n(* This is best example of not following the nose *)\nPrint b_timesm.\n\nInductive gorgeous : nat -> Prop :=\n| g_0 : gorgeous 0\n| g_3 : forall n : nat, gorgeous n -> gorgeous (3 + n)\n| g_5 : forall n : nat, gorgeous n -> gorgeous (5 + n).\n\nTheorem gorgeous_plus13: forall n,\n  gorgeous n -> gorgeous (13+n).\nProof.\n  intros n H. apply g_5 with (n := 8 + n). apply g_5. apply g_3. assumption.\nQed.\n\nTheorem gorgeous__beautiful_FAILED : forall n,\n  gorgeous n -> beautiful n.\nProof.\n  intros n H. induction n.\n  Case \"n = O\". apply b_0.\n  Abort.\n\nTheorem gorgeous__beautiful : forall n,\n  gorgeous n -> beautiful n.\nProof.\n  intros n H. induction H.\n  Case \"H = b_0\". apply b_0.\n  Case \"H = b_3\". apply b_sum with (n := 3). apply b_3. assumption.\n  Case \"H = b_5\". apply b_sum with (n := 5). apply b_5. assumption.\nQed.\n\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n  intros n m Hn Hm. induction Hn.\n  Case \"g_0\". simpl. assumption.\n  Case \"g_3\". apply g_3 with (n := n + m). assumption.\n  Case \"g_5\". apply g_5 with (n := n + m). assumption.\nQed.\n\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n  intros n H. induction H.\n  Case \"b_0\". apply g_0.\n  Case \"b_3\". apply g_3. apply g_0.\n  Case \"b_5\". apply g_5. apply g_0.\n  Case \"b_sum\". apply gorgeous_sum. assumption. assumption.\nQed.\n\nLemma helper_g_times2 : forall x y z, x + (z + y)= z + x + y.\nProof.\n  intros x y z. induction x. \n  Case \"x = O\".\n    simpl. rewrite plus_0_r. reflexivity.\n  Case \"x = S x\".\n   assert ( H : z + S x = S x + z ).\n       apply plus_comm. \n       rewrite H. simpl. rewrite plus_assoc. reflexivity.\nQed.\n  \n  \nTheorem g_times2: forall n, gorgeous n -> gorgeous (2 * n).\nProof.\n   intros n H. simpl. induction H.\n   Case \"g_0\". simpl. apply g_0.\n   Case \"g_3\". apply g_3 with (n := n + (3 + n + 0)).\n   rewrite plus_0_r. rewrite helper_g_times2. apply g_3 with (n := n + n).\n   rewrite plus_0_r in IHgorgeous. assumption.\n   Case \"g_5\". apply g_5 with (n := n + (5 + n + 0)). rewrite helper_g_times2.\n   rewrite plus_0_r. rewrite plus_0_r in IHgorgeous. apply g_5 with (n := n + n).\n   assumption.\nQed.\nPrint g_times2.\n\nTheorem g_times2': forall n, gorgeous n -> gorgeous (2 * n).\nProof.\n  intros n H. apply beautiful__gorgeous with (n := 2 * n).\n  apply b_timesm.  apply  gorgeous__beautiful. assumption.\nQed.\n(* prevous proof is about moving gorgeous (2 * n ) => beautiful n \nand beautiful n to gorgeous n *)\n\n\nTheorem ev__even : forall n,\n  ev n -> even n.\nProof.\n  intros n H. induction H. unfold even. simpl. reflexivity.\n  unfold even. simpl. assumption.\nQed.\n\nTheorem l : forall n, ev n.\nProof.\n  induction n. apply ev_O.\n  Abort.\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof.\n  intros n m Hn Hm. induction Hn.\n  Case \"ev_O\". simpl. assumption.\n  Case \"ev_n\". simpl. apply ev_SS. assumption.\nQed.\n\nTheorem ev_minus2: forall n, ev n -> ev (pred (pred n)).\nProof.\n  intros n H. induction H. simpl. apply ev_O.\n  simpl. assumption.\nQed.\n\nTheorem ev_minus2': forall n, ev n -> ev (pred (pred n)).\nProof.\n  intros n H. inversion H. simpl. apply ev_O.\n  simpl. assumption.\nQed.\n\nTheorem ev_minus2'': forall n, ev n -> ev (pred (pred n)).\nProof.\n  intros n H. destruct H eqn: Ht. simpl. apply ev_O.\n  simpl. assumption.\nQed.\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n H. inversion H. assumption.\nQed.\n\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n H. apply SSev__even in H. apply SSev__even in H. assumption.\nQed.\n\nTheorem SSSSev__even' : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n H. inversion H. inversion H1. assumption.\nQed.\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros H. inversion H. inversion H1.\n  inversion H3.\nQed.\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros n m E1 E2. induction E2.\n  Case \"ev_O\". assumption.\n  Case \"ev_SS\". apply IHE2. simpl in E1. inversion E1. assumption.\nQed.\n\nTheorem ev_ev_even : forall n m,\n   ev n -> ev m -> ev (n + m).\nProof.\n  intros n m E1. induction E1. intros. simpl. assumption.\n  intros H. simpl. apply ev_SS. apply IHE1. assumption.\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 H1 H2.\n\n(*\n\n2 subgoals, subgoal 1 (ID 720)\n  \n  n : nat\n  m : nat\n  p : nat\n  H1 : ev (n + m)\n  H2 : ev (n + p)\n  ============================\n   ev m\n\nsubgoal 2 (ID 721) is:\n ev p\n\nI am not able to extact the any information from H1 and H2 so stuck \n *)\nAbort.\n\nInductive ev_list {X : Type} : list X -> Prop :=\n| el_nil : ev_list []\n| el_cc x y l : ev_list l -> ev_list ( x :: y :: l).\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  Case \"el_nil\". apply ev_O.\n  Case \"el_cc\". simpl. apply ev_SS. apply IHev_list.\nQed.\n\nLemma ev_length__ev_list:\n  forall X n, ev n -> forall (l : list X), n = length l -> ev_list l.\nProof.\n  intros X n H. induction H.\n  Case \"ev_O\".\n  {\n    induction l.\n    SCase \"[]\". intros. apply el_nil.\n    SCase \"Cons n l\". intros H. inversion H.\n  }\n  Case \"ev_SS\".\n  {\n    intros l H2. destruct l.\n    SCase \"[]\". inversion H2. destruct l.\n    SCase \"[x]\". inversion H2.\n    SCase \"{x :: y :: l]\". apply el_cc. apply IHev. inversion H2. reflexivity.\n  }\nQed.\n\nInductive pal {X : Type} : list X -> Prop :=\n| empty : pal []\n| oneelem : forall x,  pal [x]\n| manyelem : forall x l, pal l -> pal ( x :: l ++ [x]).\n\nTheorem snoc_list : forall (X : Type) (l : list X) (n : X),\n                          snoc l n = l ++ [n].\nProof.\n    induction l.\n    Case \"l = nil\". reflexivity.\n    Case \"l = cons n l\". simpl. intros n0. rewrite IHl. reflexivity.\nQed.\n\nTheorem app_assoc : forall  (X : Type) (l1 l2 l3 : list X),\n                        (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n    induction l1 as [ | n l'].\n    Case \"l1 = nil\". reflexivity.\n    Case \"l1 = cons n l'\".\n    simpl. intros l2 l3. rewrite IHl'. reflexivity.\nQed.\n\nTheorem pal_app_rev : forall (X : Type) (l : list X), pal (l ++ rev l).\nProof.\n  intros X l. induction l.\n  Case \"nil\". simpl. apply empty.\n  Case \"Cons n l\". simpl. rewrite snoc_list.\n  rewrite <- app_assoc. apply manyelem. assumption.\nQed.\n\nLemma rev_list : forall ( X : Type ) ( a : X ) ( l : list X ),\n  rev ( l ++ [a] ) = a :: rev l.\nProof.\n  intros X a l. induction l as [ | v' l'].\n  Case \"l = nil\".\n     reflexivity.\n  Case \"l = Cons v' l'\".\n    simpl. rewrite -> snoc_list. rewrite -> snoc_list.\n    rewrite IHl'. simpl. reflexivity.\nQed.\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  Case \"empty\". simpl. reflexivity.\n  Case \"oneelem\". simpl. reflexivity.\n  Case \"manyelem\". simpl. rewrite snoc_list. rewrite rev_list. simpl.\n  rewrite <- IHpal. reflexivity.\nQed.\n\nTheorem rev_pal : forall (X : Type) (l : list X),\n                    l = rev l -> pal l.\nProof.\n  intros X l H. destruct l.\n  Case \"nil\". apply empty. destruct l.\n  Case \"[x]\". apply oneelem.\n  Case \"x :: y :: l\". simpl in H. rewrite snoc_list in H. rewrite snoc_list in H.\n  rewrite app_assoc in H.\nAbort.\n\nInductive le : nat -> nat -> Prop :=\n| le_n n : le n n\n| le_S n m : le n m -> le n (S m).\n\n\nNotation \"m <= n\" := (le m n).\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  apply le_n.\nQed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  apply le_S. apply (le_S 3 4). apply (le_S 3 3). apply (le_n 3).\nQed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  intros H. inversion H. inversion H2.\nQed.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n, square_of n (n * n).\n\nTheorem square3 : square_of 3 9.\nProof.\n  apply sq.\nQed.\n\nInductive next_nat : nat -> nat -> Prop :=\n  nn : forall n, 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\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o H1 H2. induction H2.\n  assumption.\n  apply le_S. apply IHle. assumption.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros n. induction n. apply le_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 m H. induction H. apply le_n. apply le_S. assumption.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  intros n m.  generalize dependent n. induction m.\n  Case \"m = O\". intros n H. inversion H. apply le_n. inversion H2.\n  Case \"m = S m\". intros n H. inversion H.\n  apply le_n. apply le_S. apply IHm. apply H2.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros a b. generalize dependent a. induction b.\n  Case \"b = O\". simpl. intros a. rewrite plus_0_r. apply le_n.\n  Case \"b = S b\". intros a. SearchAbout ( _ + S _).\n  rewrite NPeano.Nat.add_succ_r. apply le_S. apply IHb.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n                    n1 + n2 < m -> n1 < m /\\ n2 < m.\nProof.\n  unfold lt. intros n1 n2 m H. split.\n  Case \"left\". inversion H.\nAbort.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  unfold lt. intros n m H. apply le_S. assumption.\nQed.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof.\n  intros n m H. generalize dependent m. induction n.\n  Case \"n = O\". intros m H. unfold ble_nat in H. induction m.\n  apply le_n. apply le_S. assumption.\n  Case \"n = S n\". intros m H. induction m. inversion H. simpl in H. apply IHn in H.\n  apply n_le_m__Sn_le_Sm in H. assumption.\nQed.\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n  intros n m H. generalize dependent n. induction m.\n  Case \"m = O\". intros n H. inversion H. reflexivity.\n  Case \"m = S m\".\n  {\n    induction n.\n    simpl. intros H. reflexivity.\n    simpl. intros H. apply IHm. apply Sn_le_Sm__n_le_m in H. assumption.\n  }\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 m o H1 H2. apply ble_nat_true in H1. apply ble_nat_true in H2.\n  apply le_ble_nat. generalize dependent H2. generalize dependent H1.\n  apply le_trans.\nQed.\n\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  unfold not. intros n m H1 H2. apply le_ble_nat in H2.\n  rewrite H1 in H2. inversion H2.\nQed.\n\nInductive sortedlist : list nat -> Prop :=\n| nilsorted : sortedlist []\n| onesorted : forall x, sortedlist [x]\n| morsorted : forall x y ys,\n                le x y -> sortedlist (y :: ys) -> sortedlist (x :: y :: ys).\n\nTheorem sorted : sortedlist [1; 2; 3].\nProof.\n  apply morsorted. apply le_S. apply le_n.\n  apply morsorted. apply le_S. apply le_n.\n  apply onesorted.\nQed.\n\nTheorem sorted_inv : forall (n : nat) (l : list nat),\n                       sortedlist (n :: l) -> sortedlist l.\nProof.\n  intros n l H. induction l.\n  Case \"l = []\". apply nilsorted.\n  Case \"Cons n l\". inversion H. assumption.\nQed.\n\nModule R.\n\n  Inductive R : nat -> nat -> nat -> Prop :=\n  | c1 : R 0 0 0\n  | c2 : forall m n o, R m n o -> R (S m) n (S o)\n  | c3 : forall m n o, R m n o -> R m (S n) (S o)\n  | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n  | c5 : forall m n o, R m n o -> R n m o.\n\n  (* R 1 1 2 is provalbe. c2 -> c3 -> c1 *)\n  Theorem provalber112 : R 1 1 2.\n  Proof.\n    apply c2. apply c3. apply c1.\n  Qed.\n\n  \n  Theorem provalber226 : R 2 2 6.\n  Proof.\n    apply c3. apply c3. apply c5.\n    apply c3. apply c3.\n  Abort.\nEnd R.\n\nInductive subseq {X : Type} : list X -> list X -> Prop :=\n| emptysubseq : forall l, subseq [] l\n| dropsubseq : forall x l1 l2, subseq l1 l2 -> subseq l1 (x :: l2)\n| keepsubseq : forall x l1 l2, subseq l1 l2 -> subseq (x :: l1) (x :: l2).\n\nExample subseqexample : subseq [1; 2; 3] [5; 6; 1; 9; 9; 2; 7; 3; 8].\nProof.\n  apply dropsubseq. apply dropsubseq. apply keepsubseq.\n  apply dropsubseq. apply dropsubseq. apply keepsubseq.\n  apply dropsubseq. apply keepsubseq. apply emptysubseq.\nQed.\n\nTheorem subseqreflexive : forall (X : Type) (l : list X), subseq l l.\nProof.\n  intros X l. induction l.\n  Case \"l = []\". apply emptysubseq.\n  Case \"l = x :: l\". apply keepsubseq. apply IHl.\nQed.\n\nLemma app_right : forall (X : Type) (l : list X), l ++ [] = l.\nProof.\n  intros X l. induction l.\n  Case \"l = []\". reflexivity.\n  Case \"l = Cons n l\".\n  {\n    simpl. rewrite IHl. reflexivity.\n  }\nQed.\n\nTheorem subseq_app : forall (X : Type) (l1 l2 l3 : list X),\n                       subseq l1 l2 -> subseq l1 (l2 ++ l3).\nProof.\n  intros X l1 l2 l3 H. induction H.\n  Case \"emptysubseq\". apply emptysubseq.\n  Case \"dropsubseq\". simpl. apply dropsubseq. assumption.\n  Case \"keepsubseq\". simpl. apply keepsubseq. assumption.\nQed.\n\nTheorem subseq_trans : forall (X : Type) (l1 l2 l3 : list X),\n                         subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof.\n  intros X l1 l2 l3 H1 H2. induction H1.\n  Case \"emptysubseq\". apply emptysubseq.\nAbort.\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\n(* first  provable. second third is not *)\n\nTheorem r210 : R 2 [1; 0].\nProof. apply c2. apply c2. apply c1. Qed.\nTheorem r11210 : R 1 [1;2;1;0].\nProof. Abort.\nTheorem r63210 : R 6 [3;2;1;0].\nProof. Abort.\n\nCheck (2 + 2 = 4).\nCheck (ble_nat 2 3 = false).\nCheck (beautiful 8).\nCheck (2 + 2 = 5).\nCheck (beautiful 4).\nTheorem plus_2_2_is_4 : 2 + 2 = 4.\nProof. compute. reflexivity. Qed.\n\nDefinition plus_fact : Prop := 2 + 2 = 4.\nCheck plus_fact.\n\nTheorem plus_fact_is_true : plus_fact.\nProof. unfold plus_fact. reflexivity. Qed.\n\nCheck (even 3).\nCheck (even 4).\nCheck even.\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\nDefinition teen : nat -> Prop := between 13 19.\nCheck teen.\n\nDefinition true_for_zero (P : nat -> Prop) : Prop := P 0.\n\nDefinition true_for_all_number (P : nat -> Prop) : Prop :=\n  forall n, P n.\n\nDefinition preserverd_by_S (P : nat -> Prop) : Prop :=\n  forall n, P n -> P (S n).\n\nDefinition natural_number_induction_valid : Prop :=\n  forall (P : nat -> Prop),\n    true_for_zero P -> preserverd_by_S P -> true_for_all_number P.\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun n => if evenb n then Peven n else Podd n.\n\nTheorem combine_odd_even_intro :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  intros Podd Peven n H1 H2.\n  unfold combine_odd_even. destruct (evenb n) eqn:Hev.\n  apply H2. unfold oddb. rewrite Hev. simpl. reflexivity.\n  apply H1. unfold oddb. rewrite Hev. simpl. 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. unfold oddb.\n  assert (forall n, negb (evenb n) = true -> evenb n = false).\n  {\n    intros n. destruct (evenb n) eqn:Hev.\n    Case \"true\". intros H. simpl in H. inversion H.\n    Case \"false\". simpl. intros H. reflexivity.\n  }\n  intros Podd Peven n H1 H2. apply H in H2. rewrite H2 in H1. 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  unfold combine_odd_even, oddb.\n  assert (forall n, negb (evenb n) = false -> evenb n = true).\n  {\n    intros n. destruct (evenb n) eqn: Hev.\n    Case \"true\". intros H. reflexivity.\n    Case \"false\". simpl. intros H. inversion H.\n  }\n  intros Podd Peven n H1 H2. apply H in H2. rewrite H2 in H1. assumption.\nQed.\n\n(* finished all the problems *)\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/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6794201115900323}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the 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 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, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nGlobal Set Automatic Coercions Import.\nGlobal Set Asymmetric Patterns.\nSet Implicit Arguments.\nUnset Strict Implicit.\n(** Title \"Sets, relations, maps\" *)\nSection Sets1.\nComments\n  \"Basically, algebraic structures are sets, in which we talk about elements, belonging, equality,\"\n  \"applications, equivalence relations, quotient sets, etc\".\nComments\n  \"Types in Coq are not well-suited to represent sets, because they cannot be quotiented\".\nComments \"We will define sets in Coq as types with an equivalence relation\".\nComments \"First, we need some definitions on binary relations on types:\".\nSection Relations.\nVariable E : Type.\n\nDefinition relation (E : Type) := E -> E -> Prop.\n\nDefinition app_rel (R : relation E) (x y : E) := R x y.\n\nDefinition reflexive (R : relation E) : Prop := forall x : E, app_rel R x x.\n\nDefinition symmetric (R : relation E) : Prop :=\n  forall x y : E, app_rel R x y -> app_rel R y x.\n\nDefinition transitive (R : relation E) : Prop :=\n  forall x y z : E, app_rel R x y -> app_rel R y z -> app_rel R x z.\nComments \"A partial equivalence on\" E\n  \" is a relation which is transitive and symmetric:\".\n\nDefinition partial_equivalence (R : relation E) : Prop :=\n  transitive R /\\ symmetric R.\nComments \"An equivalence relation is reflexive, symmetric and transitive:\".\n\nDefinition equivalence (R : relation E) : Prop :=\n  reflexive R /\\ partial_equivalence R.\nComments \"Some immediate properties:\".\n\nLemma equiv_refl : forall R : relation E, equivalence R -> reflexive R.\ncompute in |- *. tauto.\nQed.\n\nLemma equiv_sym : forall R : relation E, equivalence R -> symmetric R.\ncompute in |- *; tauto.\nQed.\n\nLemma equiv_trans : forall R : relation E, equivalence R -> transitive R.\ncompute in |- *; tauto.\nQed.\nEnd Relations.\nHint Unfold reflexive transitive symmetric partial_equivalence equivalence:\n  algebra.\nHint Resolve equiv_refl equiv_sym equiv_trans: algebra.\nComments \"Then we define a dedicated structure to represent sets:\".\n\nRecord Setoid : Type := \n  {Carrier :> Type; Equal : relation Carrier; Prf_equiv :> equivalence Equal}.\nHint Resolve Prf_equiv: algebra.\nComments\n  \"A set is then given by a type (for its elements), a binary relation\"\n  \"and a proof that this relation is an equivalence relation\".\nComments \"We will write\" (Equal x y)\n  \"for the equality of two elements of a set\".\n\nLemma Refl : forall (E : Setoid) (x : E), Equal x x.\nintros E; try assumption.\ncut (reflexive (Equal (s:=E))); auto with algebra.\nQed.\n\nLemma Sym : forall (E : Setoid) (x y : E), Equal x y -> Equal y x.\nintros E; try assumption.\ncut (symmetric (Equal (s:=E))); auto with algebra.\nQed.\n\nLemma Trans :\n forall (E : Setoid) (x y z : E), Equal x y -> Equal y z -> Equal x z.\nintros E; try assumption.\ncut (transitive (Equal (s:=E))); auto with algebra.\nQed.\nHint Resolve Refl: algebra.\nHint Immediate Sym: algebra.\nComments\n  \"Every type in Coq can be seen as a set, with the Leibnitz equality:\".\n\nLet eqT_equiv : forall A : Type, equivalence (eq (A:=A)).\nintros A; try assumption.\nred in |- *.\nsplit; [ try assumption | idtac ].\nred in |- *.\nunfold app_rel in |- *; auto with algebra.\nred in |- *.\nsplit; [ try assumption | idtac ].\nred in |- *.\nunfold app_rel in |- *; auto with algebra.\nintros x y z H' H'0; try assumption.\nrewrite H'; auto with algebra.\nred in |- *.\nunfold app_rel in |- *; auto with algebra.\nQed.\n\nDefinition Leibnitz_set (A : Type) : Setoid := Build_Setoid (eqT_equiv A).\n\nLemma Leibnitz_set_prop :\n forall (A : Type) (x y : Leibnitz_set A), Equal x y -> x = y.\nauto with algebra.\nQed.\n\nLemma Leibnitz_set_prop_rev :\n forall (A : Type) (x y : Leibnitz_set A), x = y -> Equal x y.\nauto with algebra.\nQed.\nSection Quotient1.\nComments\n  \"We can now define quotient sets, using equivalence relations on sets\".\nComments\n  \"A binary relation on a set is a binary relation on its carrier, which is compatible with equality:\".\nVariable E : Setoid.\n\nDefinition rel_compatible (R : relation E) : Prop :=\n  forall x x' y y' : E,\n  Equal x x' -> Equal y y' -> app_rel R x y -> app_rel R x' y'.\n\nRecord Relation : Type := \n  {Rel_fun :> relation E; Rel_compatible_prf : rel_compatible Rel_fun}.\n\nLemma Rel_comp :\n forall (R : Relation) (x x' y y' : E),\n Equal x x' -> Equal y y' -> app_rel R x y -> app_rel R x' y'.\nintros R; try assumption.\nexact (Rel_compatible_prf (r:=R)).\nQed.\nHint Resolve Rel_comp: algebra.\nVariable R : Relation.\nHypothesis R_equiv : equivalence R.\nSet Strict Implicit.\nUnset Implicit Arguments.\n\nDefinition quotient : Setoid := Build_Setoid R_equiv.\nSet Implicit Arguments.\nUnset Strict Implicit.\nEnd Quotient1.\nSection Maps1.\nComments\n  \"Maps between two sets are functions which are compatible with equalities:\".\nSection Maps1_1.\nVariable A B : Setoid.\n\nDefinition fun_compatible (f : A -> B) : Prop :=\n  forall x y : A, Equal x y -> Equal (f x) (f y).\n\nRecord Map : Type := \n  {Ap :> A -> B; Map_compatible_prf :> fun_compatible Ap:Prop}.\nComments \"Two maps are equal when they have the same values:\".\n\nDefinition Map_eq (f g : Map) : Prop := forall x : A, Equal (f x) (g x).\n\nLet Map_eq_equiv : equivalence Map_eq.\nred in |- *.\nsplit; [ try assumption | idtac ].\nred in |- *.\nunfold Map_eq, app_rel in |- *; simpl in |- *; auto with algebra.\nred in |- *.\nsplit; [ try assumption | idtac ].\nred in |- *.\nunfold Map_eq, app_rel in |- *; simpl in |- *; auto with algebra.\nintros x y z H' H'0 x0; try assumption.\napply Trans with (y x0); auto with algebra.\nred in |- *.\nunfold Map_eq, app_rel in |- *; simpl in |- *; auto with algebra.\nQed.\n\nDefinition MAP : Setoid := Build_Setoid Map_eq_equiv.\nComments \"We note\" (MAP A B) \"the set of maps between\" A \"and\" B.\nEnd Maps1_1.\nComments \"Some immediate properties of maps:\".\n\nLemma Ap_comp :\n forall (A B : Setoid) (f g : MAP A B) (x y : A),\n Equal x y -> Equal f g -> Equal (f x) (g y).\nintros A B f g x y H' H'0; try assumption.\napply Trans with (f y).\napply (Map_compatible_prf f); auto with algebra.\nsimpl in H'0.\nunfold Map_eq in H'0.\nauto with algebra.\nQed.\nHint Resolve Ap_comp: algebra.\n\nLemma map_ext :\n forall (A B : Setoid) (f g : MAP A B),\n (forall x : A, Equal (f x) (g x)) -> Equal f g.\nsimpl in |- *.\nunfold Map_eq in |- *.\nauto with algebra.\nQed.\nHint Resolve map_ext: algebra.\nSection Maps1_2.\nComments \"We define now injections, surjections and bijections.\".\nVariable A B : Setoid.\n\nDefinition injective (f : MAP A B) : Prop :=\n  forall x y : A, Equal (f x) (f y) -> Equal x y.\n\nDefinition surjective (f : MAP A B) : Prop :=\n  forall y : B, exists x : A, Equal y (f x).\n\nDefinition bijective (f : MAP A B) : Prop := injective f /\\ surjective f.\nEnd Maps1_2.\nComments \"These definitions are coherent with equality of maps:\".\n\nLemma injective_comp :\n forall (A B : Setoid) (f f' : MAP A B),\n injective f -> Equal f f' -> injective f'.\nunfold injective in |- *.\nintros A B f f' H' H'0 x y H'1; try assumption.\napply H'.\napply Trans with (Ap f' x); auto with algebra.\napply Trans with (Ap f' y); auto with algebra.\nQed.\n\nLemma surjective_comp :\n forall (A B : Setoid) (f f' : MAP A B),\n surjective f -> Equal f f' -> surjective f'.\nunfold surjective in |- *.\nintros A B f f' H' H'0 y; try assumption.\nelim (H' y); intros x E; try exact E.\nexists x; try assumption.\napply Trans with (Ap f x); auto with algebra.\nQed.\n\nLemma bijective_comp :\n forall (A B : Setoid) (f f' : MAP A B),\n bijective f -> Equal f f' -> bijective f'.\nunfold bijective in |- *.\nintros A B f f' H' H'0; try assumption.\nsplit; [ try assumption | idtac ].\nelim H'; intros H'1 H'2; try exact H'1; clear H'.\napply injective_comp with (f := f); auto with algebra.\nelim H'; intros H'1 H'2; try exact H'2; clear H'.\napply surjective_comp with (f := f); auto with algebra.\nQed.\nComments \"Trivialities:\".\n\nLemma bijective_injective :\n forall (A B : Setoid) (f : MAP A B), bijective f -> injective f.\nintros A B f H'; red in H'; auto with algebra.\nelim H'; auto with algebra.\nQed.\nHint Resolve bijective_injective: algebra.\n\nLemma bijective_surjective :\n forall (A B : Setoid) (f : MAP A B), bijective f -> surjective f.\nintros A B f H'; red in H'; auto with algebra.\nelim H'; auto with algebra.\nQed.\nHint Resolve bijective_surjective: algebra.\nSet Strict Implicit.\nUnset Implicit Arguments.\n\nDefinition surj_set_quo :\n  forall (E : Setoid) (R : Relation E) (p : equivalence R),\n  MAP E (quotient E R p).\nintros E R p; try assumption.\napply (Build_Map (A:=E) (B:=quotient E R p) (Ap:=fun x : E => x)).\ngeneralize p; clear p.\nelim R.\nintros Rel_fun' Rel_compatible_prf0 p; try assumption.\nred in |- *.\nred in Rel_compatible_prf0.\nintros x y H'; try assumption.\nsimpl in |- *.\nunfold app_rel in Rel_compatible_prf0.\napply Rel_compatible_prf0 with (x := x) (y := x); auto with algebra.\nelim p.\nintros H'0 H'1; try assumption.\nsimpl in H'0.\nred in H'0.\nunfold app_rel in H'0.\nauto with algebra.\nDefined.\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nLemma surj_set_quo_surjective :\n forall (E : Setoid) (R : Relation E) (p : equivalence R),\n surjective (surj_set_quo E R p).\nintros E R p; try assumption.\nred in |- *.\nintros y; exists y; try assumption.\nsimpl in |- *.\nelim p.\nintros H'; red in H'.\nunfold app_rel in H'.\nauto with algebra.\nQed.\nSection Maps1_3.\nComments \"We define the composition of maps:\".\nVariable E F G : Setoid.\nVariable g : MAP F G.\nVariable f : MAP E F.\nComments\n  \"First, we define the composition of the functions associated to two maps:\"\n  f \"and\" g.\n\nDefinition comp_map_fun (x : E) := g (f x).\nComments \"Then, we proof that the result is compatible with equality:\".\n\nLemma comp_map_fun_compatible : fun_compatible comp_map_fun.\nred in |- *.\nunfold comp_map_fun in |- *.\nauto with algebra.\nQed.\nComments \"With this result, we can build the composed map:\".\n\nDefinition comp_map_map : MAP E G := Build_Map comp_map_fun_compatible.\nEnd Maps1_3.\nComments \"We note\" (comp_map_map g f) \"the composition of\" g \"and\" f.\nComments \"Composition is compatible with equality of maps:\".\n\nLemma comp_map_comp :\n forall (A B C : Setoid) (f f' : MAP A B) (g g' : MAP B C),\n Equal f f' -> Equal g g' -> Equal (comp_map_map g f) (comp_map_map g' f').\nunfold comp_map_map in |- *; simpl in |- *.\nunfold Map_eq in |- *; simpl in |- *; auto with algebra.\nunfold comp_map_fun in |- *.\nauto with algebra.\nQed.\nHint Resolve comp_map_comp: algebra.\nComments \"Composition is associative:\".\n\nLemma comp_map_assoc :\n forall (A B C D : Setoid) (f : MAP A B) (g : MAP B C) (h : MAP C D),\n Equal (comp_map_map h (comp_map_map g f))\n   (comp_map_map (comp_map_map h g) f).\nunfold comp_map_map in |- *; simpl in |- *.\nunfold Map_eq in |- *; simpl in |- *; auto with algebra.\nQed.\nHint Resolve comp_map_assoc: algebra.\nComments \"We define now the identity map:\".\n\nDefinition Id : forall A : Setoid, MAP A A.\nintros A; try assumption.\napply (Build_Map (A:=A) (B:=A) (Ap:=fun x : A => x)).\nred in |- *.\nauto with algebra.\nDefined.\nComments \"Identity map is a unit element for composition:\".\n\nLemma Id_unit_r :\n forall (A B : Setoid) (f : MAP A B), Equal (comp_map_map f (Id A)) f.\nunfold comp_map_map in |- *; simpl in |- *.\nunfold Map_eq in |- *; simpl in |- *; auto with algebra.\nQed.\nHint Resolve Id_unit_r: algebra.\n\nLemma Id_unit_l :\n forall (A B : Setoid) (f : MAP A B), Equal (comp_map_map (Id B) f) f.\nunfold comp_map_map in |- *; simpl in |- *.\nunfold Map_eq in |- *; simpl in |- *; auto with algebra.\nQed.\nHint Resolve Id_unit_l: algebra.\n\nLemma Id_is_bijective : forall A : Setoid, bijective (Id A).\nintros A; red in |- *.\nsplit; [ red in |- * | idtac ].\nsimpl in |- *; auto with algebra.\nred in |- *.\nintros y; exists y; try assumption; auto with algebra.\nQed.\nHint Resolve Id_is_bijective: algebra.\nComments \"Some properties of composition:\".\n\nLemma comp_injective :\n forall (A B C : Setoid) (f : MAP A B) (g : MAP B C),\n injective (comp_map_map g f) -> injective f.\nunfold injective in |- *.\nintros A B C f g H' x y H'0; try assumption.\napply H'.\nunfold comp_map_map in |- *; simpl in |- *.\nunfold comp_map_fun in |- *.\nauto with algebra.\nQed.\nHint Resolve comp_injective: algebra.\n\nLemma comp_surjective :\n forall (A B C : Setoid) (f : MAP A B) (g : MAP B C),\n surjective (comp_map_map g f) -> surjective g.\nunfold surjective in |- *.\nintros A B C f g H' y; try assumption.\nelim (H' y); intros x E; try exact E.\nsimpl in E.\nunfold comp_map_fun in E.\nexists (Ap f x); try assumption; auto with algebra.\nQed.\n\nLemma comp_is_id_then_bijective :\n forall (A B : Setoid) (f : MAP A B) (g : MAP B A),\n Equal (comp_map_map g f) (Id A) ->\n Equal (comp_map_map f g) (Id B) -> bijective f.\nintros A B f g H' H'0; try assumption.\nunfold bijective in |- *.\nsplit; [ try assumption | idtac ].\napply comp_injective with A g; auto with algebra.\napply injective_comp with (f := Id A); auto with algebra.\napply comp_surjective with B g; auto with algebra.\napply surjective_comp with (f := Id B); auto with algebra.\nQed.\n\nLemma comp_is_id_then_injective :\n forall (A B : Setoid) (f : MAP A B) (g : MAP B A),\n Equal (comp_map_map g f) (Id A) -> injective f.\nintros A B f g H'; try assumption.\napply comp_injective with A g; auto with algebra.\napply injective_comp with (f := Id A); auto with algebra.\nQed.\n\nLemma comp_is_id_then_surjective :\n forall (A B : Setoid) (f : MAP A B) (g : MAP B A),\n Equal (comp_map_map f g) (Id B) -> surjective f.\nintros A B f g H'; try assumption.\napply comp_surjective with B g; auto with algebra.\napply surjective_comp with (f := Id B); auto with algebra.\nQed.\nEnd Maps1.\nEnd Sets1.\nHint Immediate Sym: algebra.\nHint Unfold reflexive transitive symmetric partial_equivalence equivalence:\n  algebra.\nHint Resolve equiv_refl equiv_sym equiv_trans Prf_equiv Refl Rel_comp Ap_comp\n  map_ext bijective_injective bijective_surjective surj_set_quo_surjective\n  comp_map_comp comp_map_assoc Id_unit_r Id_unit_l Id_is_bijective\n  comp_injective: algebra.\n", "meta": {"author": "coq-contribs", "repo": "algebra", "sha": "4006abe46420df0394e20f0fb19279f64bb8501e", "save_path": "github-repos/coq/coq-contribs-algebra", "path": "github-repos/coq/coq-contribs-algebra/algebra-4006abe46420df0394e20f0fb19279f64bb8501e/Sets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.6793533033840021}}
{"text": "(** * 6.822 Formal Reasoning About Programs, Spring 2022 - Pset 13 *)\n\nRequire Import Frap MessagesAndRefinement.\n\nModule Type S.\n\n  Inductive request :=\n  | GET (client_id key : nat).\n\n  Definition get_key (req : request) : nat :=\n    match req with\n    | GET _ key => key\n    end.\n\n  Inductive response :=\n  | FOUND (client_id key : nat) (value : nat)\n  | NOT_FOUND (client_id key : nat).\n\n  Definition request_handler (store : fmap nat nat) (source output : channel) : proc :=\n    ??source(req: request);\n    match req with\n    | GET client_id key =>\n      match store $? key with\n      | Some v => !!output(FOUND client_id key v); Done\n      | None => !!output(NOT_FOUND client_id key); Done\n      end\n    end.\n\n  Definition split_store (full_store even_store odd_store : fmap nat nat) : Prop :=\n    (forall k, k mod 2 = 0  -> even_store $? k = full_store $? k) /\\\n    (forall k, k mod 2 = 0  -> odd_store  $? k = None) /\\\n    (forall k, k mod 2 <> 0 -> even_store $? k = None) /\\\n    (forall k, k mod 2 <> 0 -> odd_store  $? k = full_store $? k).\n\n  Definition request_dispatcher (input forward_even forward_odd : channel) : proc :=\n    ??input(req: request);\n    if get_key req mod 2 ==n 0 then\n      !!forward_even(req); Done\n    else\n      !!forward_odd(req); Done.\n\n  Definition balanced_handler (even_store odd_store : fmap nat nat) (input output : channel) : proc :=\n    New[input; output](forward_even);\n    New[input; output; forward_even](forward_odd);\n    request_dispatcher input forward_even forward_odd\n    || (request_handler even_store forward_even output)\n    || (request_handler odd_store forward_odd output).\n\n  Definition correctness: Prop := forall full_store even_store odd_store input output,\n      split_store full_store even_store odd_store ->\n      input <> output ->\n      forall trace,\n        couldGenerate (balanced_handler even_store odd_store input output) trace ->\n        couldGenerate (request_handler full_store input output) trace.\n\n  (*[30%]*)\n  Parameter R_alias_for_grading : fmap nat nat -> fmap nat nat ->\n                                  fmap nat nat -> channel -> channel ->\n                                  proc -> proc -> Prop.\n\n  (*[70%]*)\n  Parameter balanced_handler_correct : correctness.\nEnd S.\n\n(*|\nHINTS: A few hints to help you if you get stuck on certain \n       problems in Pset 13.\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(*|\nHINT 1: First stage of simulation relation R\n============================================\n\nHere's the first case of our simulation relation R:\n\n| Stage0 :\n    NoDup [input; output] ->\n    R fs es os input output\n      (balanced_handler es os input output)\n      (request_handler fs input output)\n|*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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: Second stage of simulation relation R\n=============================================\n\nHere's the second case of our simulation relation R:\n\n| Stage1 : forall forward_even,\n    NoDup [input; output; forward_even] ->\n    R fs es os input output\n      (Block forward_even;\n       New [input; output; forward_even] (forward_odd);\n       request_dispatcher input forward_even forward_odd\n       || request_handler es forward_even output\n       || request_handler os forward_odd output)\n      (request_handler fs input output)\n|*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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: Order of invert\n=======================\n\nTo prove the simulation, you'll get to assume an lstepSilent (or an lstep with an action, in the second subgoal) as well as an R, and you'll have to invert both of them. Depending on which of the two you invert first, your proof might become shorter or longer.\n|*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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: Going from Stage0 to Stage1 in case of a silent step\n============================================================\n\nIn our solution, there's a case where we have to prove that when the implementation takes a silent step starting at what we called Stage0, then the specification can simulate this.\nOur goal looks as follows:\n\n  full_store, even_store, odd_store : fmap nat nat\n  input, output : nat\n  H : split_store full_store even_store odd_store\n  H0 : input = output -> False\n  pr1' : proc\n  H2 : lstepSilent (balanced_handler even_store odd_store input output) pr1'\n  H3 : NoDup [input; output]\n  ============================\n  exists pr2' : proc,\n    (lstepSilent) ^* (request_handler full_store input output) pr2' /\\\n    R full_store even_store odd_store input output pr1' pr2'\n\nAnd we prove it with the following code:\n\n    + (* After Stage0: generate fresh forward_even channel *)\n      invert H2. rename ch into forward_even.\n      eexists. split.\n      * eapply TrcRefl.\n      * eapply Stage1. lists.\n|*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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: Going from Stage0 to Stage1 in case of a non-silent step\n================================================================\n\nIn our solution, there's a case where we have to prove that when the implementation takes a non-silent step starting at what we called Stage0, then the specification can simulate this.\nOur goal looks as follows:\n\n  full_store, even_store, odd_store : fmap nat nat\n  input, output : nat\n  H : split_store full_store even_store odd_store\n  H0 : input = output -> False\n  a : action\n  pr1' : proc\n  H2 : lstep (balanced_handler even_store odd_store input output) (Action a) pr1'\n  H3 : NoDup [input; output]\n  ============================\n  exists pr2' pr2'' : proc,\n    (lstepSilent) ^* (request_handler full_store input output) pr2' /\\\n    lstep pr2' (Action a) pr2'' /\\ R full_store even_store odd_store input output pr1' pr2''\n\nThis is a contradiction, because H2 claims that balanced_handler takes a non-silent step, but the first step it takes is to execute a New, which is silent. So, all we have to do in this case is \"invert H2.\"\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/pset13_MessagePassing/Pset13Sig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.6793532880153283}}
{"text": "(******************************************************************************)\n(**)\n(******************************************************************************)\n(*         M1 \\oplus M2 == the zmodType given by pair_lmodType in ssralg.v    *)\n(*                         This is an implementation of the direct sum of two *)\n(*                         zmodTypes.                        *)\n(* \\bigoplus_(f in L) I == the lmodType built up iteratively, where L : seq S *)\n(*                         for S : eqType and I : S -> lmodType R             *)\n(*                         \\bigoplus_(f in nil) I is zmodNullType whilst      *)\n(*                         \\bigoplus_(f in a::L) I is                         *)\n(*                               (I a) \\oplus (\\bigoplus_(f in L) I)          *)\n(*                         This is an implementation of the direct sum of an  *)\n(*                         arbitrary number of zmodTypes. Note that L is not  *)\n(*                         a list of zmodTypes but of some eqType S, which    *)\n(*                         are 'converted' to zmodTypes by                    *)\n(*                           I : S -> zmodType.                               *)\n(*  \\bigoplus_(f : F) I == the zmodType equal to \\bigoplus_(f in (enum F)) I  *)\n(*        \\bigoplus_F I == equivalent to \\bigoplus_(f : F) I                  *)\n(*          \\bigoplus I == equivalent to \\bigoplus_(f : F) I                  *)\n(*                         where I : F -> zmodType                            *)\n(******************************************************************************)\n(* The following constructions and lemmas relate to M \\oplus N,               *)\n(* the direct sum of the pair of zmodTypes M and N                            *)\n(******************************************************************************)\n(*  \\proj1^(M,N)   == the additive projection from M \\oplus N to M            *)\n(*  \\proj2^(M,N)   == the additive projection from M \\oplus N to N            *)\n(*  \\incl1^(M,N)   == the additive inclusion from M to M \\oplus N             *)\n(*  \\incl2^(M,N)   == the additive inclusion from N to M \\oplus N             *)\n(*  incl1_injective  == a proof that \\incl1^(M,N) is injective                *)\n(*  incl2_injective  == a proof that \\incl2^(M,N) is injective                *)\n(*  proj1_incl1K     == a proof of \\proj1^(M,N) (\\incl1^(M,N) x) = x          *)\n(*  proj2_incl2K     == a proof of \\proj2^(M,N) (\\incl2^(M,N) x) = x          *)\n(*  proj1_incl20     == a proof of \\proj1^(M,N) (\\incl2^(M,N) x) = 0          *)\n(*  proj2_incl10     == a proof of \\proj2^(M,N) (\\incl1^(M,N) x) = 0          *)\n(*  incl_proj12_sum  == a proof that any x : M \\oplus N can be written        *)\n(*                         x = \\incl1^(M,N) (\\proj1^(M,N) x)                  *)\n(*                              + \\incl2^(M,N) (\\proj2^(M,N) x)               *)\n(*  incl_proj12_idem == a proof that rewriting with incl_proj12_sum is        *)\n(*                         idempotent                                         *)\n(******************************************************************************)\n(* Let M N M1 M2 N1 N2 : zmodType                                             *)\n(* We define construction for combining linear maps so to be compatible       *)\n(* with direct sums                                                           *)\n(******************************************************************************)\n(* Let f1 : {additive M1 -> N1} and f2 : {additive M2 -> N2}                  *)\n(* \\diagmap(f,g) == the additive map : M1 \\oplus M2 -> N1 \\oplus N2           *)\n(*                         given by \\diagmap(f,g) (x,y) = (f x, g y)          *)\n(******************************************************************************)\n(* Let f1 : {additive M1 -> N} and f2 : {additive M2 -> N}                    *)\n(* \\rowmap(f,g) == the additive map : M1 \\oplus M2 -> N                       *)\n(*                         given by \\rowmap(f,g) (x,y) = f x + g y            *)\n(******************************************************************************)\n(* Let f1 : {additive M -> N1} and f2 : {additive M -> N2}                    *)\n(* \\colmap(f,g) == the additive map : M -> N1 \\oplus N2                       *)\n(*                         given by \\colmap(f,g) x = (f x, g x)               *)\n(******************************************************************************)\n(* The following constructions and lemmas relate to \\bigoplus_(f : F) I,      *)\n(* the direct sum of the zmodTypes given by (I : F -> zmodType), and F is a   *)\n(* finite index set (i.e. a finType)                                          *)\n(******************************************************************************)\n(*  \\proj_f^(I)    == the additive projection from \\bigoplus I to (I f),      *)\n(*                 for f : F. This function is surjective                     *)\n(*  \\incl_f^(I)    == the additive inclusion from (I f) to \\bigoplus I,       *)\n(*                 for f : F. This function is injective                      *)\n(*  incl_injective == a proof that \\incl_f^(I) is injective for f : F         *)\n(*  proj_inclK     == a proof that \\incl_f^(I) and \\proj_f^(I) cancel         *)\n(*  proj_incl0     == a proof that \\incl_f^(I) and \\proj_(f')^(I) equals zero *)\n(*                    if f != f'                                              *)\n(*  incl_proj_sum  == rewrites element x : \\bigoplus I as                     *)\n(*                        \\sum_(f : F)\\incl_f^(I) (\\proj_f^(I) x)             *)\n(*  incl_proj_idem       ==  a proof that rewriting with incl_proj_sum is     *)\n(*                         idempotent                                         *)\n(******************************************************************************)\n(* The following constructions are used to split and unsplit the direct sum   *)\n(* of two direct sums, that is (\\bigoplus J) \\oplus (\\bigoplus K).            *)\n(* Doing this involves:                                                       *)\n(*  1) three index sets F, G and H,                                           *)\n(*  2) a function GH_F : G + H -> F, connecting the sum of G and H to F       *)\n(*  3) a proof enumB : enum F = map F_GH (enum sum_finType G H) which         *)\n(* establishes that GH_F is an 'isomorphism' of G + H and F as finTypes,      *)\n(* and the notations J = I \\o GH_F \\o inl and K = I \\o GH_F \\o inr.           *)\n(******************************************************************************)\n(*     split == a additive function from \\bigoplus I to                       *)\n(*                    (\\bigoplus J) \\oplus (\\bigoplus K)                      *)\n(*   unsplit == a additive function from (\\bigoplus J) \\oplus (\\bigoplus K)   *)\n(*                    to \\bigoplus I                                          *)\n(*  splitK   == a proof that split and unsplit cancel                         *)\n(*  unsplitK == a proof that unsplit and split cancel                         *)\n(******************************************************************************)\n(* DirectSum_UniversalProperty == *)\n(******************************************************************************)\n\nFrom Coq.Init Require Import Notations Datatypes.\nRequire Import Coq.Program.Tactics.\nFrom Coq.Logic Require Import FunctionalExtensionality.\nFrom mathcomp Require Import ssreflect ssrfun seq.\nFrom mathcomp Require Import eqtype fintype bigop.\n\nSet Warnings \"-parsing\". (* Some weird bug in ssrbool throws out parsing warnings*)\n  From mathcomp Require Import ssrbool ssrnat.\nSet Warnings \"parsing\".\n\nSet Warnings \"-ambiguous-paths\". (* Some weird bug in ssralg throws out coercion warnings*)\n    From mathcomp Require Import ssralg.\nSet Warnings \"ambiguous-paths\".\n\nRequire Import AbGroups Additives.\nOpen Scope ring_scope.\nSet Implicit Arguments.\nUnset Strict Implicit.\nInclude GRing.\n\nOpen Scope  zmod_scope.\n\nSection Helpers.\n  Variable (S : finType) (X : zmodType) (f : S*S -> X).\n  Lemma big_pair_diag_eq :\n    \\sum_(i : S*S | i.2 == i.1)f i\n      = \\sum_(i : S) f (i, i).\n  Proof.\n    have : forall (i : S) (_ : true), f (i, i) = \\sum_(j : S) if (j == i) then f (i, j) else 0\n    by move=>i _;\n    rewrite -big_mkcond (big_pred1 i).\n    move=> H; rewrite (eq_bigr _ H); clear H.\n    by rewrite pair_bigA -big_mkcond\n    (eq_bigr (fun i => f (i.1,i.2)) _)=>/=;\n      [|move=>i _; destruct i=>/=].\n  Qed.\nEnd Helpers.\n\n\nReserved Notation \"\\bigoplus_ i F\"\n(at level 36, F at level 36, i at level 50,\n  right associativity,\n        format \"'[' \\bigoplus_ i '/ ' F ']'\").\n\nReserved Notation \"\\bigoplus F\"\n(at level 36, F at level 36,\n  right associativity,\n        format \"'[' \\bigoplus F ']'\").\n\nReserved Notation \"\\bigoplus_ ( i : t ) F\"\n(at level 36, F at level 36, i at level 50,\n        format \"'[' \\bigoplus_ ( i : t ) '/ ' F ']'\").\n\nReserved Notation \"\\bigoplus_ ( i < n ) F\"\n(at level 36, F at level 36, i, n at level 50,\n        format \"'[' \\bigoplus_ ( i < n ) F ']'\").\n\nReserved Notation \"\\bigoplus_ ( i 'in' A ) F\"\n(at level 36, F at level 36, i, A at level 50,\n        format \"'[' \\bigoplus_ ( i 'in' A ) '/ ' F ']'\").\n\nReserved Notation \"\\proj^( I )_ f \"\n(at level 36, f at level 36, I at level 36,\n  format \"'[' \\proj^( I )_ f ']'\").\n\nReserved Notation \"\\inj^( I )_ f \"\n(at level 36, f at level 36, I at level 36,\n  format \"'[' \\inj^( I )_ f ']'\").\n\nReserved Notation \"\\proj_ f ^( I ) \"\n(at level 36, f at level 36, I at level 36,\n  format \"'[' \\proj_ f '^(' I ) ']'\").\n\nReserved Notation \"\\inj_ f ^( I )\"\n(at level 36, f at level 36, I at level 36,\n  format \"'[' \\inj_ f '^(' I ) ']'\").\n\n\nModule dsZmod.\n  Module Pair.\n    Section Def.\n      Variable (m1 m2 : zmodType).\n\n      Section Injection.\n        Definition inj1_raw := fun x : m1 => (x,zero m2) : pair_zmodType m1 m2.\n        Definition inj2_raw := fun x : m2 => (zero m1, x) : pair_zmodType m1 m2.\n\n        Lemma inj1_add : additive inj1_raw.\n        Proof. rewrite /inj1_raw/==>x y.\n          by symmetry; rewrite /(add _)/=/add_pair/=subr0. Qed.\n        Lemma inj2_add : additive inj2_raw.\n        Proof. rewrite /inj2_raw/==>x y.\n          by symmetry; rewrite /(add _)/=/add_pair/=subr0. Qed.\n\n        Lemma inj1_injective : injective inj1_raw.\n        Proof. by move=>x y H; inversion H. Qed.\n        Lemma inj2_injective : injective inj2_raw.\n        Proof. by move=>x y H; inversion H. Qed.\n\n        Definition inj1 := Additive inj1_add.\n        Definition inj2 := Additive inj2_add.\n\n        Lemma inj1_unraw x : inj1_raw x = inj1 x. Proof. by []. Qed.\n        Lemma inj2_unraw x : inj2_raw x = inj2 x. Proof. by []. Qed.\n      End Injection.\n\n      Section Projection.\n        Definition proj1_raw := fun x : pair_zmodType m1 m2 => x.1.\n        Definition proj2_raw := fun x : pair_zmodType m1 m2 => x.2.\n\n        Lemma proj1_add : additive proj1_raw.\n        Proof. rewrite /proj1_raw/==>x y; destruct x as [x1 x2], y as [y1 y2].\n          by rewrite /(add _)/=/add_pair. Qed.\n        Lemma proj2_add : additive proj2_raw.\n        Proof. rewrite /proj1_raw/==>x y; destruct x as [x1 x2], y as [y1 y2].\n          by rewrite /(add _)/=/add_pair. Qed.\n\n        Definition proj1 := Additive proj1_add.\n        Definition proj2 := Additive proj2_add.\n\n        Lemma proj1_unraw x : proj1_raw x = proj1 x. Proof. by []. Qed.\n        Lemma proj2_unraw x : proj2_raw x = proj2 x. Proof. by []. Qed.\n\n        Lemma proj1_inj1K x : proj1 (inj1 x) = x. Proof. by []. Qed.\n        Lemma proj2_inj2K x : proj2 (inj2 x) = x. Proof. by []. Qed.\n        Lemma proj1_inj20 x : proj1 (inj2 x) = 0. Proof. by []. Qed.\n        Lemma proj2_inj10 x : proj2 (inj1 x) = 0. Proof. by []. Qed.\n      End Projection.\n\n      Lemma inj_proj_sum x : x = inj1 (proj1 x) + inj2 (proj2 x).\n      Proof.\n        rewrite /inj1/proj1/inj2/proj2/(add _)/=\n         /add_pair addr0 add0r;\n        by destruct x.\n      Qed.\n    End Def.\n\n\n    Section Morphisms.\n      Section MorphismsToDS.\n        Variable (M N1 N2 : zmodType)\n          (f1 : {additive M -> N1}) (f2 : {additive M -> N2}).\n\n        Definition to_ds_raw : M -> (pair_zmodType N1 N2)\n          := fun x => (inj1 _ _ (f1 x)) + (inj2  _ _ (f2 x)).\n\n        Lemma to_ds_add : additive to_ds_raw.\n        Proof. rewrite/to_ds_raw=>x y.\n        by rewrite !raddfD !raddfN addrACA. Qed.\n        Definition to_ds : {additive M -> (pair_zmodType N1 N2)}\n          := Additive to_ds_add.\n\n      End MorphismsToDS.\n\n      Section MorphismsFromDS.\n        Variable (M1 M2 N : zmodType)\n          (f1 : {additive M1 -> N}) (f2 : {additive M2 -> N}).\n\n        Definition from_ds_raw : (pair_zmodType M1 M2) -> N\n          := fun x => (f1 (proj1 _ _ x)) + (f2 (proj2  _ _ x)).\n\n        Lemma from_ds_add : additive from_ds_raw.\n        Proof. rewrite/from_ds_raw=>x y.\n        by rewrite !raddfD !raddfN addrACA. Qed.\n\n        Definition from_ds : {additive (pair_zmodType M1 M2) -> N}\n          := Additive from_ds_add.\n\n      End MorphismsFromDS.\n\n      Section MorphismsDiag.\n        Variable (M1 M2 N1 N2 : zmodType)\n          (f1 : {additive M1 -> N1}) (f2 : {additive M2 -> N2}).\n\n        Definition diag_raw : (pair_zmodType M1 M2) -> (pair_zmodType N1 N2)\n          := fun x => (inj1 _ _ (f1 (proj1 _ _ x))) + (inj2 _ _ (f2 (proj2  _ _ x))).\n\n        Lemma diag_add : additive diag_raw.\n        Proof. rewrite/diag_raw=>x y.\n        by rewrite !raddfD !raddfN addrACA. Qed.\n\n        Definition diag : {additive (pair_zmodType M1 M2) -> (pair_zmodType N1 N2)}\n          := Additive diag_add.\n\n      End MorphismsDiag.\n\n      Section MorphismsDiagCompositions.\n        Variable (M1 M2 N1 N2 O1 O2 : zmodType)\n          (f1 : {additive M1 -> N1}) (f2 : {additive M2 -> N2})\n          (g1 : {additive N1 -> O1}) (g2 : {additive N2 -> O2}).\n\n        Lemma diag_id : diag (\\id_M1) (\\id_M2) = \\id_(pair_zmodType M1 M2).\n        Proof.\n          rewrite additive_eq.\n          apply functional_extensionality=>x/=.\n          by rewrite /diag_raw /addID.map -!(lock) -(inj_proj_sum x).\n        Qed.\n\n        Lemma diag_comp : (diag g1 g2) \\oAdd (diag f1 f2) = diag (g1 \\oAdd f1) (g2 \\oAdd f2).\n        Proof.\n          rewrite additive_eq.\n          apply functional_extensionality=>x.\n          rewrite -!addCompChain=>/=.\n          rewrite /diag_raw -!addCompChain=>/=.\n          by rewrite addr0 add0r.\n        Qed.\n\n      End MorphismsDiagCompositions.\n    End Morphisms.\n\n    Module Exports.\n      Notation zmodDSPairType := pair_zmodType.\n      Infix \"\\oplus\" := (pair_zmodType) (at level 35) : zmod_scope.\n      Notation \"\\diagmap( f , g )\" := (diag f g) (at level 35) : zmod_scope.\n      Notation \"\\rowmap( f , g )\" := (from_ds f g) (at level 35) : zmod_scope.\n      Notation \"\\colmap( f , g )\" := (to_ds f g) (at level 35) : zmod_scope.\n    End Exports.\n  End Pair.\n  Export Pair.Exports.\n\n\n\n  Module Seq.\n    Section Ring.\n      Section Environment.\n        Variable (T : eqType) (I : T -> zmodType).\n\n        Section Def.\n          Definition Nth := (fun L n => match (seq.nth None (map Some L) n) with\n          |Some t => I t\n          |None => zmodZeroType\n          end).\n\n          Fixpoint DS (L : seq T) : zmodType := match L with\n            |nil => zmodZeroType\n            |a'::L' => (I a') \\oplus (DS L')\n          end.\n        End Def.\n\n        Section Injection.\n        Fixpoint inj_raw (L : seq T) (n : nat) {struct n} :\n          Nth L n -> DS L\n        := match L as LL return Nth LL n -> DS LL with\n          |nil => fun _ => tt\n          |a::L' => match n as nn return Nth (a::L') nn -> DS (a::L') with\n            |0    => fun x => @Pair.inj1 (I a) (DS L') x\n            |S n' => fun x => @Pair.inj2 (I a) (DS L') ((@inj_raw L' n') x)\n            end\n          end.\n\n          Lemma inj_add (L : seq T) (n : nat) : additive (@inj_raw L n).\n          Proof. move: n; induction L.\n            induction n=>//.\n            move : L IHL; induction n=>// x y.\n            apply (@Pair.inj1_add (I a) (DS L)).\n            by rewrite /=-(@Pair.inj2_add (I a) (DS L)) (IHL n).\n          Qed.\n\n          Lemma inj_injective\n            (L : seq T) (n : nat) : injective (@inj_raw L n).\n          Proof. move: n; induction L=>//=.\n          { induction n; by move=> x y; destruct x, y. }\n            move: L IHL.\n            induction n=>/= x y H.\n            apply (@Pair.inj1_injective _ _ x y H).\n            apply (IHL n x y (@Pair.inj2_injective _ _ (@inj_raw L n x) (@inj_raw L n y) H)).\n          Qed.\n        End Injection.\n        Definition inj (L : seq T) (n : nat)\n          := Additive (@inj_add L n).\n\n        Section Projection.\n          Fixpoint proj_raw (L : seq T) (n : nat) {struct n} :\n          DS L -> Nth L n\n        := match L as LL return DS LL -> Nth LL n with\n          |nil => match n as nn return zmodZero.type -> Nth nil nn with\n            |0    => fun _ => tt\n            |S n' => fun _ => tt\n            end\n          |a::L' => match n as nn return DS (a::L') -> Nth (a::L') nn with\n            |0    => fun x => @Pair.proj1 (I a) (DS L') x\n            |S n' => fun x => (@proj_raw L' n') (@Pair.proj2 (I a) (DS L') x)\n            end\n          end.\n          \n          Lemma proj_add (L : seq T) (n : nat) : additive (@proj_raw L n).\n          Proof. move: n; induction L=>//=. induction n=>//.\n            move: L IHL; induction n=>//=; move=> x y.\n            by rewrite !Pair.proj2_unraw raddfD -(IHL n).\n          Qed.\n        End Projection.\n        Definition proj (L : seq T) (n : nat)\n          := Additive (@proj_add L n).\n\n        Section Results.\n          Section Lemmas.\n            Variable (L : seq T).    \n            Lemma nth_cons {a d} {n : nat} : seq.nth d (a::L) (S n) = seq.nth d L n.\n            Proof. by induction n. Qed.\n        \n            Lemma inj_cons n a x : @inj (a::L) (S n) x = Pair.inj2 (I a) _ (@inj L n x).\n            Proof. by []. Qed.\n        \n            Lemma proj_cons n a x : @proj (a::L) (S n) (Pair.inj2 (I a) _ x) = @proj L n x.\n            Proof. by []. Qed.\n\n            Lemma proj_inj_cons (n n' : nat) a x\n            : @proj (a::L) (n.+1) (@inj (a::L) (n'.+1) x) = @proj L n (@inj L n' x).\n            Proof. by []. Qed.\n          End Lemmas.\n          Variable (L : seq T).\n\n          (* The following two lemmas are used for cancellation *)\n          Lemma proj_injK_ofsize (n : 'I_(size L)) x : @proj L (nat_of_ord n) (@inj L (nat_of_ord n) x) = x.\n          Proof.\n            induction L=>//; destruct n as [n N]=>//.\n            induction n=>//; move:x; simpl (Ordinal N : nat)=>x.\n            rewrite -ltn_predRL in N.\n            by rewrite proj_inj_cons (IHl (Ordinal N)).\n          Qed.\n\n          Lemma proj_inj0_ofsize (n n' : 'I_(size L)) x : (nat_of_ord n) != n' -> @proj L n (@inj L n' x) = 0.\n          Proof.\n            induction L; destruct n as [n N], n' as [n' N']=>//.\n            simpl in x, IHl, N, N'=>H.\n            induction n.\n              apply (rwP negP) in H.\n              by induction n'=>/=; [contradiction H|].\n            induction n'=>//=.\n              by (have: proj l n 0 = 0 by rewrite raddf0).\n            clear IHn' IHn;\n            rewrite eqSS in H;\n            rewrite ltnS in N;\n            rewrite ltnS in N';\n            by apply (IHl (Ordinal N) (Ordinal N') x H).\n          Qed.\n          \n          (* The following two lemmas are the same as above but more versitile,\n          in that they don't require the index to be an ordinal of size L, simply\n          that they are naturals less than size L *)\n          Lemma proj_injK (n : nat) x (M : n < size L) : @proj L n (@inj L n x) = x.\n          Proof. apply (@proj_injK_ofsize (Ordinal M)). Qed.\n      \n          Lemma proj_inj0 m1 m2 (n : 'I_m1) (n' : 'I_m2) x (M1 : m1 <= (size L)) (M2 : m2 <= (size L))\n            : (nat_of_ord n) != n' -> @proj L n (@inj L n' x) = 0.\n          Proof. apply (@proj_inj0_ofsize (widen_ord M1 n) (widen_ord M2 n')). Qed.\n\n          (* this lemma expresses any element as a sum of projections *)\n          Lemma inj_proj_sum x : x = \\sum_(n < size L) inj L (nat_of_ord n) (@proj L (nat_of_ord n) x).\n          Proof.\n            induction L.\n            by rewrite /size big_ord0; case x.\n            destruct x as [Ia DSl].\n            by rewrite big_ord_recl {1}(IHl DSl)\n            (Pair.inj_proj_sum (Ia, _)) raddf_sum.\n          Qed.\n        End Results.\n\n        (* Given a direct sum indexed by a seq, we define a function to reform\n        the direct sum into the direct sum of two smaller direct sums. *)\n        Section Operations.\n          Variable (L1 L2 : seq T).\n          (*Tr = truncate, Ap = Append, R = right, L = left*)\n          Section L1.\n            Variable (n : 'I_(size L1)).\n            Lemma catTrR_eq : (Nth (L1 ++ L2) n) = (Nth L1 n).\n            Proof. destruct n as [n' H].\n            by rewrite/Nth map_cat nth_cat size_map H. Qed.\n\n            Definition catTrR : (Nth (L1 ++ L2) n) -> (Nth L1 n).\n            Proof. by rewrite catTrR_eq. Defined.\n\n            Definition catApR : (Nth L1 n) -> (Nth (L1 ++ L2) n).\n            Proof. by rewrite catTrR_eq. Defined.\n\n            Lemma catTrApR_add : additive catTrR /\\ additive catApR.\n            Proof. split; rewrite/catTrR/catApR=>x y; by destruct(catTrR_eq). Qed.\n\n            Lemma catApTrRK : cancel catTrR catApR /\\ cancel catApR catTrR.\n            Proof. split; rewrite/catApR/catTrR=>x; by destruct(catTrR_eq). Qed.\n\n            Definition catifyL1 : addIsomType (Nth (L1 ++ L2) n) (Nth L1 n)\n            := addIsomBuildPack catTrApR_add catApTrRK.\n          End L1.\n          Section L2.\n            Variable (n : 'I_(size L2)).\n        \n            Lemma catTrL_eq : (Nth (L1 ++ L2) (rshift (size L1) n)) = (Nth L2 n).\n            Proof. by simpl; rewrite/Nth map_cat nth_cat size_map\n            -{2}(addn0 (size L1)) ltn_add2l addnC addnK. Qed.\n\n            Definition catTrL : (Nth (L1 ++ L2) (rshift (size L1) n)) -> (Nth L2 n).\n            Proof.  by rewrite catTrL_eq. Defined.\n\n            Definition catApL : (Nth L2 n) -> (Nth (L1 ++ L2) (rshift (size L1) n)).\n            Proof. by rewrite catTrL_eq. Defined.\n\n            Lemma catTrApL_add : additive catTrL /\\ additive catApL.\n            Proof. split; rewrite/catTrL/catApL=>x y;by destruct (catTrL_eq). Qed.\n            \n            Lemma catApTrLK : cancel catTrL catApL /\\ cancel catApL catTrL.\n            Proof. split; rewrite/catApL/catTrL=>x; by destruct(catTrL_eq). Qed.\n\n            Definition catifyL2 : addIsomType (Nth (L1 ++ L2) (rshift (size L1) n)) (Nth L2 n)\n            := addIsomBuildPack catTrApL_add catApTrLK.\n          End L2.\n\n          Definition split_raw : DS (L1 ++ L2) -> DS L1 \\oplus DS L2\n            := fun x =>\n            (\\sum_(n < size L1)(inj L1 n \\oAdd catifyL1 n \\oAdd proj (L1 ++ L2) n ) x,\n            \\sum_(n < size L2)(inj L2 n \\oAdd catifyL2 n \\oAdd proj (L1 ++ L2) (rshift (size L1) n)) x).\n\n          Definition unsplit_raw : DS L1 \\oplus DS L2 -> DS (L1 ++ L2)\n          := fun x =>\n            \\sum_(n < size L1)((inj (L1 ++ L2) n                     \\oAdd inv(catifyL1 n) \\oAdd proj L1 n) x.1) +\n            \\sum_(n < size L2)((inj (L1 ++ L2) (rshift (size L1) n)  \\oAdd inv(catifyL2 n) \\oAdd proj L2 n) x.2).\n\n          Lemma split_add : additive split_raw.\n          Proof. rewrite/split_raw=>x y/=.\n            by rewrite (rwP eqP)/eq_op -(rwP andP) -!(rwP eqP)/=\n             -!sumrB !(eq_bigr _ (fun i _ => raddfB _ _ _)).\n          Qed.\n\n          Lemma unsplit_add : additive unsplit_raw.\n          Proof. rewrite/unsplit_raw=>x y/=.\n            rewrite !(eq_bigr _ (fun i _ => raddfB _ _ _)) !sumrB/=.\n            Admitted.\n\n          Definition split := Additive split_add.\n          Definition unsplit := Additive unsplit_add.\n\n          Lemma unsplitK : cancel split unsplit.\n          Proof. simpl; rewrite /unsplit_raw/split_raw=>x.\n            under eq_bigr do rewrite raddf_sum.\n            under eq_bigr do under eq_bigr do rewrite -!addCompChain.\n            under[\\sum_(_ < size L2) _] eq_bigr do rewrite raddf_sum.\n            under[\\sum_(_ < size L2) _] eq_bigr do under eq_bigr do rewrite -!addCompChain.\n            rewrite!pair_bigA.\n            rewrite (eq_bigr (fun p : 'I_(size L1)*'I_(size L1)\n            => if p.2 == p.1\n              then inj _ p.1 (proj _ p.1 x)\n              else 0 ) _).\n            rewrite (eq_bigr (fun p : 'I_(size L2)*'I_(size L2)\n              => if p.2 == p.1\n              then inj _ (rshift (size L1) p.2) (proj _ (rshift (size L1) p.2) x)\n              else 0 ) _).\n            by rewrite -!big_mkcond !big_pair_diag_eq {3}(@inj_proj_sum _ x)\n            size_cat (@big_split_ord _ _ _ (size L1) (size L2)).\n            by move=>p _; case (p.2 == p.1) as []eqn:E;\n            [apply (rwP eqP) in E; rewrite E proj_injK_ofsize (isomaK (catifyL2 p.1)) |\n            rewrite proj_inj0_ofsize; [rewrite !raddf0|\n              rewrite eq_sym/eq_op in E; simpl in E; rewrite E]].\n            by move=>p _; case (p.2 == p.1) as []eqn:E;\n            [ apply (rwP eqP) in E; rewrite E proj_injK_ofsize (isomaK (catifyL1 p.1))|\n            rewrite proj_inj0_ofsize; [rewrite !raddf0|\n              rewrite eq_sym/eq_op in E; simpl in E; rewrite E]].\n          Qed.\n\n          Lemma splitK : cancel unsplit split.\n          Proof. simpl; rewrite /unsplit_raw/split_raw=>x.\n          under eq_bigr do rewrite !raddfD.\n          under[\\sum_(n < _) ((_ \\oAdd _ \\oAdd proj _ (rshift _ n)) _)]\n            eq_bigr do rewrite !raddfD.\n\n          rewrite !big_split !(eq_bigr _ (fun i _ => raddf_sum _ _ _ _)) !pair_bigA.\n          rewrite (eq_bigr (fun p : 'I_(size L1)*'I_(size L1)\n          => if(p.2 == p.1)\n            then inj L1 p.1 (proj L1 p.1 x.1)\n            else 0) _).\n          rewrite (eq_bigr (fun p : 'I_(size L2)*'I_(size L2)\n          => if(p.2 == p.1)\n            then inj L2 p.2 (proj L2 p.2 x.2)\n            else 0) _).\n          {\n            destruct x as [x1 x2];\n            rewrite -!big_mkcond !big_pair_diag_eq\n            (eq_bigr (fun p : 'I_(size L1) => inj _ p (proj _ p x1)) _);[|by move].\n            rewrite (eq_bigr (fun p : 'I_(size L2) => inj _ p (proj _ p x2)) _); [| by []].\n            rewrite {4}(inj_proj_sum x1) {4}(inj_proj_sum x2) (rwP eqP) /eq_op -(rwP andP).\n            split; rewrite -subr_eq0.\n\n            rewrite {1}addrC addrA addNr add0r (eq_bigr (fun _ => 0) _).\n            rewrite big_const cardE /iter enumT;\n            induction(Finite.enum _)=>//=; by rewrite add0r.\n\n            move =>[[p1 H1] [p2 H2]] _;\n            rewrite -!addCompChain proj_inj0;[by rewrite !raddf0 |by rewrite size_cat leq_addr|by rewrite size_cat|];\n            rewrite -(rwP negP)/not -(rwP eqP)=>/=N;\n            by rewrite N -{2}(addn0 (size L1)) ltn_add2l in H1.\n\n            rewrite -addrA addrN addr0 (eq_bigr (fun _ => 0) _).\n            rewrite big_const cardE /iter enumT;\n            induction(Finite.enum _)=>//=; by rewrite add0r.\n\n            move =>[[p1 H1] [p2 H2]] _;\n            rewrite -!addCompChain proj_inj0;[by rewrite !raddf0 |by rewrite size_cat|by rewrite size_cat leq_addr|];\n            rewrite -(rwP negP)/not -(rwP eqP)=>/=N.\n            by rewrite -N -{2}(addn0 (size L1)) ltn_add2l in H2.\n          }\n          move=>p _; case(p.2 == p.1) as []eqn:E.\n          move/eqP in E; rewrite E -!addCompChain.\n          rewrite proj_injK; [by rewrite isomKa|].\n          destruct p as [[p1 H1] [p2 H2]].\n          by rewrite size_cat ltn_add2l.\n          rewrite -!addCompChain proj_inj0; [by rewrite !raddf0|by rewrite size_cat|by rewrite size_cat|].\n          rewrite /eq_op in E; simpl in E.\n          by rewrite /rshift eqn_add2l eq_sym E.\n\n          move=>p _; case(p.2 == p.1) as []eqn:E.\n          apply (rwP eqP) in E; rewrite -E -!addCompChain.\n          rewrite proj_injK; [by rewrite isomKa|].\n          destruct p as [[p1 H1] [p2 H2]]=>/=.\n          by rewrite size_cat addnC (ltn_addl _ H2).\n          rewrite -!addCompChain proj_inj0; [by rewrite !raddf0|by rewrite size_cat leq_addr|by rewrite size_cat leq_addr|].\n          rewrite /eq_op in E; simpl in E.\n          by rewrite eq_sym E.\n          Qed.\n        End Operations.\n      End Environment.\n      \n      Section Hom.\n        Variable (S T : eqType) (I : T -> zmodType) (T_S : S -> T).\n\n        Fixpoint homify_raw (L : seq S) : DS (I \\o T_S) L -> DS I (map T_S L)\n          := match L with\n          |nil => id\n          |a::l => fun x => (x.1 , homify_raw x.2)\n          end.\n        Fixpoint unhomify_raw (L : seq S) : DS I (map T_S L) -> DS (I \\o T_S) L\n          := match L with\n          |nil => id\n          |a::l => fun x => (x.1 , unhomify_raw x.2)\n          end.\n        \n        Variable (L : seq S).\n        Lemma homify_add : additive (@homify_raw L) /\\ additive (@unhomify_raw L).\n        Proof. split; induction L=>//=x y;\n          by rewrite IHl/homify_raw/unhomify_raw.\n        Qed.\n        Lemma homifyK : cancel (@homify_raw L) (@unhomify_raw L) /\\ cancel (@unhomify_raw L) (@homify_raw L).\n        Proof. split; induction L=>//=x; destruct x;\n          by rewrite IHl.\n        Qed.\n        Definition homify := addIsomBuildPack homify_add homifyK.\n      End Hom.\n\n      Section Bijection.\n        Variable (S T : eqType) (I : T -> zmodType)\n            (T_S : S -> T) (S_T : T -> S) (Inj : cancel S_T T_S).\n\n        Variable (L : seq T).\n        Definition mapify_raw : DS I (map T_S (map S_T L)) -> DS I L.\n        by rewrite mapK. Defined.\n        Definition unmapify_raw : DS I L -> DS I (map T_S (map S_T L)).\n        by rewrite mapK. Defined.\n        Lemma mapify_add : additive mapify_raw /\\ additive unmapify_raw.\n        Proof. split; by rewrite/mapify_raw/unmapify_raw; destruct mapK. Qed.\n        Lemma mapifyK : cancel mapify_raw unmapify_raw /\\ cancel unmapify_raw mapify_raw.\n        Proof. split; by rewrite/mapify_raw/unmapify_raw; destruct mapK. Qed.\n        Definition mapify := addIsomBuildPack mapify_add mapifyK.\n\n        Definition bijectify := addIsomConcat (homify I T_S (map S_T L)) mapify.\n      End Bijection.\n    End Ring.\n  End Seq.\n\n\n\n\n\n\n\n\n\n  Section General.\n    Section Def.\n      Variable (F : finType) (I : F -> zmodType).\n\n      Definition DS : zmodType := Seq.DS I (enum F).\n\n      Section Components.\n        Variable (f : F).\n\n        Lemma cardElt : nat_of_ord (enum_rank f) < size (enum F).\n        Proof. rewrite -cardE; apply ltn_ord. Qed.\n\n        Definition Ord := Ordinal cardElt.\n        Definition Nth := Seq.Nth I (enum F) Ord.\n\n        Section TypeConversion.\n          Lemma Nth_If_eq : Nth = I f.\n          Proof. by rewrite /Nth/Seq.Nth -codomE nth_codom enum_rankK. Qed.\n          Lemma If_Nth_eq : I f = Nth.\n          Proof. by rewrite Nth_If_eq. Qed.\n\n          Definition finify_raw : Nth -> I f := (fun fn : Nth\n            -> Nth => eq_rect_r (fun M : zmodType => Nth -> M)\n              fn If_Nth_eq) id.\n          Definition unfinify_raw : I f -> Nth := (fun fn : Nth\n            -> Nth => eq_rect_r (fun M : zmodType => M -> Nth)\n              fn If_Nth_eq) id.\n          Lemma finify_add : additive finify_raw /\\ additive unfinify_raw.\n          Proof. split; by rewrite /finify_raw/unfinify_raw=>x y; destruct If_Nth_eq. Qed.\n          Lemma finifyK : cancel finify_raw unfinify_raw /\\ cancel unfinify_raw finify_raw.\n          Proof. split; by rewrite/finify_raw/unfinify_raw; destruct If_Nth_eq. Qed.\n\n          Definition finify := addIsomBuildPack finify_add finifyK.\n\n        End TypeConversion.\n\n        Section Projection.\n          Definition proj_raw : DS -> I f\n          := finify \\oAdd (@Seq.proj F I (enum F) Ord).\n\n          Lemma proj_add : additive proj_raw.\n          Proof. rewrite/proj_raw=> x y; by rewrite !raddfB. Qed.\n\n          Definition proj : {additive DS -> I f} := Additive proj_add.\n        End Projection.\n\n        Section Injection.\n          Definition inj_raw : I f -> DS\n          := (@Seq.inj F I (enum F) Ord) \\oAdd inv(finify).\n\n          Lemma inj_add : additive inj_raw.\n          Proof. rewrite/inj_raw=> x y; by rewrite !raddfB. Qed.\n\n          Lemma inj_injective : injective inj_raw.\n          Proof. rewrite/inj_raw=>x y; rewrite -!addCompChain=>H.\n            apply Seq.inj_injective in H.\n            apply (congr1 finify) in H.\n            by rewrite !isomKa in H.\n          Qed.\n\n          Definition inj : {additive I f -> DS} := Additive inj_add.\n        End Injection.\n      End Components.\n\n      Section Results.\n        Lemma proj_injK (f : F) x : proj f (inj f x) = x.\n        Proof. by rewrite /proj_raw/inj_raw -!addCompChain\n          Seq.proj_injK; [rewrite -{2}(isomKf (finify f) x) | apply cardElt].\n        Qed.\n\n        Lemma proj_inj0 (f f' : F) x : f != f' -> @proj f (@inj f' x) = 0.\n        Proof.\n          rewrite-(rwP negP)/not -!addCompChain=>H.\n          case((nat_of_ord (enum_rank f) != enum_rank f')) as []eqn:E.\n          rewrite (@Seq.proj_inj0_ofsize _ _ _ (Ord f) (Ord f') _ E).\n          by rewrite raddf0.\n          assert (E' := contraFeq (fun B : enum_rank f != enum_rank f' => B) E).\n          apply enum_rank_inj in E'.\n          rewrite E' eq_refl in H.\n          by assert (H' := H is_true_true).\n        Qed.\n\n        Lemma inj_proj_sum x : x = \\sum_(f : F) inj f (proj f x).\n        Proof.\n          rewrite big_enum_val.\n          rewrite {1}(Seq.inj_proj_sum x) -!big_enum  -cardT.\n          refine (eq_bigr _ _).\n          move=> i _; rewrite /inj_raw/proj_raw/Seq.inj/Seq.proj\n          -!addCompChain (isomaK (finify _))/Ord=>/=.\n          by rewrite enum_valK.\n        Qed.\n\n        Lemma inj_proj_idem x : \\sum_(f : F) inj f (proj f (\\sum_(f : F) inj f (proj f x))) = \\sum_(f : F) inj f (proj f x).\n        Proof. by rewrite -inj_proj_sum. Qed.\n      End Results.\n    End Def.\n    Section Hom.\n(*      Variable (F G : finType) (I : F -> lmodType R) (J : G -> lmodType R)\n      (J = I \\o F_G)\n      (F_G : G -> F) (enumB : enum F = map F_G (enum G)).\n\n      Definition enumify_raw : Seq.DS I (map F_G (enum G)) -> DS I.\n      by rewrite /DS enumB. Defined.\n      Definition unenumify_raw : DS I -> Seq.DS I (map F_G (enum G)).\n      by rewrite /DS enumB. Defined.\n      Lemma enumify_lin : linear enumify_raw /\\ linear unenumify_raw.\n      Proof. split; rewrite /enumify_raw/unenumify_raw; by destruct enumB. Qed.\n      Lemma enumifyK : cancel enumify_raw unenumify_raw /\\ cancel unenumify_raw enumify_raw .\n      Proof. split; rewrite /enumify_raw/unenumify_raw; by destruct enumB. Qed.\n      Definition enumify := linIsomBuildPack enumify_lin enumifyK.\n\n      Definition homify : {linear DS (I \\o F_G) -> DS I}\n      := enumify \\oLin (@Seq.homify _ _ _ I F_G (enum G)).\n      Definition unhomify : {linear DS I -> DS (I \\o F_G)}\n      := inv(@Seq.homify _ _ _ I F_G (enum G)) \\oLin inv(enumify).*)\n    End Hom.\n    Section Bijection.\n    (*\n      Variable (F G : finType) (I : F -> lmodType R) (J : G -> lmodType R)\n        (F_G : G -> F) (G_F : F -> G)\n        (I_J : I = J \\o G_F) (J_I : J = I \\o F_G)\n        (Inj : cancel F_G G_F) (Surj : cancel G_F F_G) (enumB : enum F = map F_G (enum G)).\n\n\n        Definition mapify_raw : DS (I \\o S_T \\o T_S) -> DS I.\n        by rewrite mapK. Defined.      \n        Definition unmapify_raw : DS I L -> DS I (map T_S (map S_T L)).\n        by rewrite mapK. Defined.\n        Lemma mapify_lin : linear mapify_raw /\\ linear unmapify_raw.\n        Proof. split; by rewrite/mapify_raw/unmapify_raw; destruct mapK. Qed.\n        Lemma mapifyK : cancel mapify_raw unmapify_raw /\\ cancel unmapify_raw mapify_raw.\n        Proof. split; by rewrite/mapify_raw/unmapify_raw; destruct mapK. Qed.\n        Definition mapify := linIsomBuildPack mapify_lin mapifyK.\n\n        Definition bijectify := linIsomConcat (homify I T_S (map S_T L)) mapify.*)\n    End Bijection.\n\n    Section Operations.\n      Variable (F G : finType) (I : F + G -> zmodType).\n      Definition J : F -> zmodType := I \\o inl.\n      Definition K : G -> zmodType := I \\o inr.\n\n      Lemma sumify_eq : (enum (sum_finType F G)) = ((map inl (enum F)) ++ (map inr (enum G))).\n      Proof. by rewrite/DS enumT(unlock _)/=/sum_enum -!enumT. Qed.\n\n      Definition sumify_raw : DS I -> Seq.DS I ((map inl (enum F)) ++ (map inr (enum G))).\n      by rewrite /DS sumify_eq. Defined.\n      Definition unsumify_raw : Seq.DS I ((map inl (enum F)) ++ (map inr (enum G))) -> DS I.\n      by rewrite /DS sumify_eq. Defined.\n      \n      Lemma sumify_add : additive sumify_raw /\\ additive unsumify_raw.\n        Proof. split; rewrite/sumify_raw/unsumify_raw=>x y;\n        by destruct sumify_eq. Qed.\n      Lemma sumifyK : cancel sumify_raw unsumify_raw /\\ cancel unsumify_raw sumify_raw.\n        Proof. split; rewrite/sumify_raw/unsumify_raw=>x;\n        by destruct sumify_eq. Qed.\n\t    Definition sumify := addIsomBuildPack sumify_add sumifyK.\n      \n      Definition split : DS I -> DS J \\oplus DS K\n       := \\diagmap(inv(Seq.homify _ inl _), inv(Seq.homify _ inr _))\n\t\t\t      \\oAdd (Seq.split I _ _) \\oAdd sumify.\n\n      Definition unsplit : {additive DS J \\oplus DS K -> DS I}\n      := inv(sumify) \\oAdd (Seq.unsplit I _ _) \\oAdd\n          \\diagmap(Seq.homify _ inl _, Seq.homify _ inr _).\n\n      Lemma unsplitK : cancel split unsplit.\n      Proof. rewrite /unsplit/split=>x.\n        by rewrite -!addCompChain (addCompChain (\\diagmap(_,_)) (\\diagmap(_,_)))\n        Pair.diag_comp !addIsom.concatKa Pair.diag_id -addIDChain\n        Seq.unsplitK (isomaK sumify).\n      Qed.\n\n      Lemma splitK : cancel unsplit split.\n      Proof. rewrite /unsplit/split=>x.\n        by rewrite -!addCompChain isomKa Seq.splitK\n        (addCompChain (\\diagmap(_,_)) (\\diagmap(_,_)))\n        Pair.diag_comp !addIsom.concataK Pair.diag_id -addIDChain.\n      Qed.\n\n    End Operations.\n\n  End General.\n  Section Results.\n  Variable (M N : zmodType) (m : M) (n : N).\n  Lemma pair_eq_seq (F G : eqType) (f : F -> M) (g : G -> N)\n    (L1 : seq F) (L2 : seq G) :\n    \\sum_(i <- L1) (f i, 0)%R + \\sum_(i <- L2) (0, g i) == (m,n)\n    <-> (\\sum_(i <- L1) f i == m /\\ \\sum_(i <- L2) g i == n).\n  Proof. split; [move=> H|move=> [H1 H2]]. {\n    have:(\\sum_(i <- L1) (dsZmod.Pair.inj1 M N (f i)) + \\sum_(i <- L2) (dsZmod.Pair.inj2 M N (g i)) == (m, n))\n      by apply H .\n    rewrite -!raddf_sum/Pair.inj1/Pair.inj2/(@add _)/=\n     /add_pair add0r addr0 -(rwP eqP)=>H0;\n    by inversion H0.\n  }\n  move: H1 H2; rewrite -!(rwP eqP)=>H1 H2.\n  have:(\\sum_(i <- L1) (Pair.inj1 _ _  (f i)) == (m, @zero N))\n    by rewrite -raddf_sum/Pair.inj1 H1.\n  have:(\\sum_(i <- L2) (Pair.inj2 _ _ (g i)) == (@zero M, n))\n    by rewrite -raddf_sum/Pair.inj2 H2=>/=.\n  rewrite -!(rwP eqP)=>H H0.\n  have:(\\sum_(i <- L1) (dsZmod.Pair.inj1 _ _ (f i)) + \\sum_(i <- L2) (dsZmod.Pair.inj2 _ _ (g i)) == (m, n))\n    by rewrite H H0 {1}/(@add (pair_zmodType M N))/=\n    /add_pair add0r addr0.\n  by rewrite /Pair.inj1/Pair.inj2 -(rwP eqP).\n  Qed.\n\n    Lemma pair_eq (F G : finType) (f : F -> M) (g : G -> N) :\n    \\sum_i (f i, 0)%R + \\sum_i (0, g i) == (m,n)\n    <-> (\\sum_i f i == m /\\ \\sum_i g i == n).\n  Proof. by rewrite -big_enum/=pair_eq_seq big_enum/=. Qed.\n  End Results.\nEnd dsZmod.\n\nDefinition dsProj (F : finType) (I : F -> zmodType) (f : F) := @dsZmod.proj F I f.\nDefinition dsInj (F : finType) (I : F -> zmodType) (f : F) := @dsZmod.inj F I f.\n\n\n\n\nExport dsZmod.Pair.Exports.\nNotation \"\\bigoplus_ i F\" := (dsZmod.DS (fun i => F i)) : zmod_scope.\nNotation \"\\bigoplus F\" := (dsZmod.DS F) : zmod_scope.\nNotation \"\\bigoplus_ ( i : t ) F\" := (dsZmod.DS (fun i : t => F i)) : zmod_scope.\nNotation \"\\bigoplus_ ( i 'in' A ) F\" := (dsZmod.Seq.DS (filter F (fun i => i \\in A))) : zmod_scope.\nNotation \"\\proj^( I )_ f \" := (dsZmod.proj I f ) : zmod_scope.\nNotation \"\\inj^( I )_ f \" := (dsZmod.inj I f ) : zmod_scope.\nNotation \"\\proj_ f ^( I )\" := (dsZmod.proj I f ) : zmod_scope.\nNotation \"\\inj_ f ^( I )\" := (dsZmod.inj I f ) : zmod_scope.\n\nTheorem DirectSum_UniversalProperty (F : finType)\n  (I : F -> zmodType)\n    : forall (f : forall i : F, {additive \\bigoplus I -> (I i)}), \n      exists (g : forall i : F, {additive (I i) -> (I i)}),\n        forall i : F, f i \\oAdd \\inj_i^(I) = g i.\nProof. move=> f.\n  by refine(ex_intro _ (fun i => f i \\oAdd \\inj_i^(I)) _ ).\nQed.\n\nClose Scope  zmod_scope.\nClose Scope  ring_scope.", "meta": {"author": "Modularius", "repo": "MathcompFreeModules", "sha": "5731747c5bcbafe914687d44e74f112632f07ec7", "save_path": "github-repos/coq/Modularius-MathcompFreeModules", "path": "github-repos/coq/Modularius-MathcompFreeModules/MathcompFreeModules-5731747c5bcbafe914687d44e74f112632f07ec7/theories/AbGroups/DirectSumAbGroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6792886023505517}}
{"text": "(* \n  Author(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\n(* \n  Problem(s):\n    Simple Semi-unification (SSemiU)\n    Semi-unification (SemiU)\n    Right-uniform Two-Inequality Semi-unification (RU2SemiU)\n    Left-uniform Two-Inequality Semi-unification (LU2SemiU)\n*)\n\n(*\n  Literature:\n  [1] Andrej Dudenhefner. \"Undecidability of Semi-Unification on a Napkin\"\n      5th International Conference on Formal Structures for Computation and Deduction (FSCD 2020): 9:1-9:16\n      https://drops.dagstuhl.de/opus/volltexte/2020/12331\n*)\n\nRequire Import List.\n\n(* terms are built up from atoms and a binary term constructor arr *)\nInductive term : Set :=\n  | atom : nat -> term\n  | arr : term -> term -> term.\n\nDefinition valuation : Set := nat -> term.\n\n(* substitute atoms n of a term t by (f n) *)\nFixpoint substitute (f: valuation) (t: term) : term :=\n  match t with\n  | atom n => f n\n  | arr s t => arr (substitute f s) (substitute f t)\n  end.\n\n(* Simple Semi-unification Definition *)\n\n(* simple semi unification constraint\n  ((a, x), (y, b)) mechanizes the constraint (a|x|ϵ ≐ ϵ|y|b) *)\nDefinition constraint : Set := ((bool * nat) * (nat * bool)).\n\n(* constraint semantics, \n  (φ, ψ0, ψ1) models a|x|ϵ ≐ ϵ|y|b if ψa (φ (x)) = πb (φ (y)) *)\nDefinition models (φ ψ0 ψ1: valuation) : constraint -> Prop :=\n  fun '((a, x), (y, b)) => \n    match φ y with\n    | atom _ => False\n    | arr s t => (if b then t else s) = substitute (if a then ψ1 else ψ0) (φ x)\n    end.\n\n(* Simple Semi-unification *)\n(* are there substitutions (φ, ψ0, ψ1) that model each constraint? *)\nDefinition SSemiU (p : list constraint) := \n  exists (φ ψ0 ψ1: valuation), forall (c : constraint), In c p -> models φ ψ0 ψ1 c.\n\n\n(* Semi-unification Definition *)\n\n(* inequality: s ≤ t *)\nDefinition inequality : Set := (term * term).\n\n(* φ solves s ≤ t, if there is ψ such that ψ (φ (s)) = φ (s) *)\nDefinition solution (φ : valuation) : inequality -> Prop := \n  fun '(s, t) => exists (ψ : valuation), substitute ψ (substitute φ s) = substitute φ t.\n\n(* Semi-unification *)\n(* is there a substitution φ that solves all inequalities? *)\nDefinition SemiU (p: list inequality) := \n  exists (φ: valuation), forall (c: inequality), In c p -> solution φ c.\n\n(* Right-uniform Two-Inequality Semi-unification *)\n(* All right-hand sides of inequalities are identical, there are exactly two inequlities *)\nDefinition RU2SemiU : term * term * term -> Prop := \n  fun '(s0, s1, t) => exists (φ ψ0 ψ1: valuation), \n    substitute ψ0 (substitute φ s0) = substitute φ t /\\ substitute ψ1 (substitute φ s1) = substitute φ t.\n\n(* Left-uniform Two-Inequality Semi-unification *)\n(* All right-hand sides of inequalities are identical, there are exactly two inequlities *)\nDefinition LU2SemiU : term * term * term -> Prop := \n  fun '(s, t0, t1) => exists (φ ψ0 ψ1: valuation), \n    substitute ψ0 (substitute φ s) = substitute φ t0 /\\ substitute ψ1 (substitute φ s) = substitute φ t1.\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/SemiUnification/SemiU.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6792885962253468}}
{"text": "Require 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  inversion H.\n  ", "meta": {"author": "KeenS", "repo": "coqex", "sha": "325a48569d54a8925e41f757cbb4c3c74443c5a3", "save_path": "github-repos/coq/KeenS-coqex", "path": "github-repos/coq/KeenS-coqex/coqex-325a48569d54a8925e41f757cbb4c3c74443c5a3/3/12.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.896251378675949, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6791742451052937}}
{"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(** * positives: basic facts about binary positive numbers *)\n\nRequire Export BinNums.\nRequire Import comparisons.\n\n(** positives as a [cmpType] *)\n\nFixpoint eqb_pos i j := \n  match i,j with \n    | xH,xH => true\n    | xI i,xI j | xO i, xO j => eqb_pos i j\n    | _,_ => false\n  end.\n\nLemma eqb_pos_spec: forall i j, reflect (i=j) (eqb_pos i j).\nProof. induction i; intros [j|j|]; simpl; (try case IHi); constructor; congruence. Qed.\n\nFixpoint pos_compare i j := \n  match i,j with\n    | xH, xH => Eq\n    | xO i, xO j | xI i, xI j => pos_compare i j\n    | xH, _ => Lt\n    | _, xH => Gt\n    | xO _, _ => Lt \n    | _,_ => Gt\n  end.\n \nLemma pos_compare_spec: forall i j, compare_spec (i=j) (pos_compare i j).\nProof. induction i; destruct j; simpl; try case IHi; try constructor; congruence. Qed.\n\nCanonical Structure cmp_pos := mk_cmp _ eqb_pos_spec _ pos_compare_spec.\n\n\n(** positive maps (for making environments) *)\n(** we redefine such trees here rather than importing them from the standard library: \n   since we do not need any proof about them, this avoids us a heavy Require Import *)\nSection e.\nVariable A: Type.\nInductive sigma := sigma_empty | N(l: sigma)(o: option A)(r: sigma).\nFixpoint sigma_get default m i :=\n  match m with \n    | N l o r => \n      match i with\n        | xH => match o with None => default | Some a => a end\n        | xO i => sigma_get default l i\n        | xI i => sigma_get default r i\n      end\n    | _ => default\n  end.\nFixpoint sigma_add i v m :=\n    match m with\n    | sigma_empty =>\n        match i with\n        | xH => N sigma_empty (Some v) sigma_empty\n        | xO i => N (sigma_add i v sigma_empty) None sigma_empty\n        | xI i => N sigma_empty None (sigma_add i v sigma_empty)\n        end\n    | N l o r =>\n        match i with\n        | xH => N l (Some v) r\n        | xO i => N (sigma_add i v l) o r\n        | xI i => N l o (sigma_add i v r)\n        end\n    end.\nEnd e.\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/positives.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.6791372704560725}}
{"text": "\nRequire Export Coq.Lists.List.\nRequire Export Iron.Language.DelayedSimple.Tactics.Chargueraud.\n\n\n(********************************************************************)\n(* Forall Lemmas *)\n\nLemma Forall_inst\n :  forall {A B} a' xs (P: A -> B -> Prop)\n ,  Forall (fun x => forall a, P a x) xs\n -> Forall (fun x => P a' x) xs.\nProof.\n intros.\n induction xs.\n - auto.\n - eapply Forall_cons.\n   + inverts H. eapply H2.\n   + inverts H. eapply IHxs. assumption.\nQed.\n\n\nLemma Forall_mp\n :  forall {A} (P Q: A -> Prop)  xs\n ,  Forall (fun x => P x -> Q x) xs\n -> Forall (fun x => P x)        xs\n -> Forall (fun x => Q x)        xs.\nProof.\n intros.\n induction xs.\n - auto.\n - eapply Forall_cons.\n   + inverts H. inverts H0. auto.\n   + inverts H. inverts H0. auto.\nQed. \n\n\nLemma Forall_mp_const \n :  forall {A} P (Q: A -> Prop)  xs\n ,  P\n -> Forall (fun x => P -> Q x) xs\n -> Forall (fun x => Q x)      xs.\nProof.\n intros.\n induction H.\n - auto.\n - apply Forall_cons.\n   + auto.\n   + auto.\nQed.\n\n\nLemma Forall_map\n :  forall {A B}\n    (P: B -> Prop) (f: A -> B) (xs: list A)\n ,  Forall (fun x => P (f x)) xs\n -> Forall P (map f xs).\nProof.\n intros. induction xs.\n  apply Forall_nil.\n  inverts H. simpl. intuition.\nQed.\n\n\n(********************************************************************)\n(* Forall2 Lemmas *)\n\nLemma Forall2_mp\n :  forall {A B} (P Q: A -> B -> Prop)  aa bb\n ,  Forall2 (fun a b => P a b -> Q a b) aa bb\n -> Forall2 (fun a b => P a b)          aa bb\n -> Forall2 (fun a b => Q a b)          aa bb.\nProof.\n intros.\n induction H0.\n - auto.\n - inverts H.\n   apply Forall2_cons; auto.\nQed.\n\n\nLemma Forall2_map\n :  forall {A B C D}\n    (P:  B -> D -> Prop) (f:  A -> B) (g:  C -> D) \n    (xs: list A) (ys: list C)\n ,  Forall2 (fun x y => P (f x) (g y)) xs ys\n -> Forall2 P (map f xs) (map g ys).\nProof.\n intros.\n induction H.\n - simpl. auto.\n - simpl. apply Forall2_cons; auto. \nQed.\n\n\nLemma Forall2_map'\n :  forall {A B C D}\n    (P: B -> D -> Prop) (f:  A -> B) (g:  C -> D)\n    (xs: list A) (ys: list C)\n ,  Forall2 P (map f xs) (map g ys)\n -> Forall2 (fun x y => P (f x) (g y)) xs ys.\nProof.\n intros. gen ys.\n induction xs; intros.\n  induction ys; intros.\n   auto.\n   inverts H.\n   destruct ys.\n    inverts H.\n    simpl in H.\n    inverts H. eauto.\nQed.\n\n\n(********************************************************************)\n(* Convert Forall to Forall2 *)\nLemma Forall_Forall2_right\n :  forall  {A B C} \n    (P: B -> C -> Prop) \n    (f: A -> B) (g: A -> C) (aa: list A)\n ,  Forall  (fun b => forall c, P b c) (map f aa)\n -> Forall2 P (map f aa) (map g aa).\nProof.\n intros.\n induction aa.\n - simpl. auto.\n - simpl in *.\n   inverts H.\n   apply Forall2_cons.\n   auto. auto.\nQed.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Language/DelayedSimple/Data/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.6791372675840305}}
{"text": "(*|\n#################################################\nStuck on a simple proof about regular expressions\n#################################################\n\n:Link: https://stackoverflow.com/q/40796214\n|*)\n\n(*|\nQuestion\n********\n\nI'm trying to formalize some properties on regular expressions (REs)\nusing Coq. But, I've got some troubles to prove a rather simple\nproperty:\n\n    For all strings ``s``, if ``s`` is in the language of\n    ``(epsilon)*`` RE, then ``s = \"\"``, where ``epsilon`` and ``*``\n    denotes the empty string RE and Kleene star operation.\n\nThis seems to be an obvious application of induction / inversion\ntactics, but I couldn't make it work.\n\nThe minimal working code with the problematic lemma is in the\nfollowing `gist\n<https://gist.github.com/rodrigogribeiro/e8f6bde70b54c871f8c744a9b3570bb2>`__.\nAny tip on how should I proceed will be appreciated.\n\n**EDIT**: One of my tries was something like:\n\n.. coq:: none\n|*)\n\nSet Implicit Arguments.\n\nRequire Import Ascii String.\n\nInductive regex : Set :=\n| Emp : regex\n| Eps : regex\n| Chr : ascii -> regex\n| Cat : regex -> regex -> regex\n| Choice : regex -> regex -> regex\n| Star : regex -> regex.\n\nOpen Scope string_scope.\n\nNotation \"'#0'\" := Emp.\nNotation \"'#1'\" := Eps.\nNotation \"'$' c\" := (Chr c) (at level 40).\nNotation \"e '@' e1\" := (Cat e e1) (at level 15, left associativity).\nNotation \"e ':+:' e1\" := (Choice e e1) (at level 20, left associativity).\nNotation \"e '^*'\" := (Star e) (at level 40).\n\n(** Semantics of regular expressions *)\n\nReserved Notation \"s '<<-' e\" (at level 40).\n\nInductive in_regex : string -> regex -> Prop :=\n| InEps : \"\" <<- #1\n| InChr : forall c, (String c EmptyString) <<- ($ c)\n| InCat : forall e e' s s' s1,\n    s <<- e -> s' <<- e' -> s1 = s ++ s' -> s1 <<- (e @ e')\n| InLeft : forall s e e', s <<- e -> s <<- (e :+: e')\n| InRight : forall s' e e',  s' <<- e' -> s' <<- (e :+: e')\n| InStar : forall s e, s <<- (#1 :+: (e @ (e ^*))) -> s <<- (e ^*)\nwhere \"s '<<-' e\" := (in_regex s e).\n\nHint Constructors in_regex.\n\n(*||*)\n\nLemma star_lemma : forall s, s <<- (#1 ^*) -> s = \"\".\nProof.\n  intros s H. inversion_clear H. inversion_clear H0.\n  - now inversion_clear H.\n  - inversion_clear H.\n    inversion_clear H2. clear s.\n    inversion_clear H0. clear s0.\n    simpl.\n\n(*| that leave me with the following goal: |*)\n\n    Show. (* .unfold .messages *)\n\n(*|\nAt least to me, it appears that using induction would finish the\nproof, since I could use ``H1`` in induction hypothesis to finish the\nproof, but when I start the proof using\n|*)\n\n    Restart. (* .none *) intros s H. (* .none *)\n    induction H.\n\n(*| instead of |*)\n\n    Restart. (* .none *) intros s H. (* .none *)\n    inversion_clear H.\nAbort. (* .none *)\n\n(*|\nI got some (at least for me) senseless goals. In Idris / Agda, such\nproof just follows by pattern matching and recursion over the\nstructure of ``s <<- (#1 ^*\\ )``. My point is how to do such recursion\nin Coq.\n|*)\n\n(*|\nAnswer (Anton Trunov)\n*********************\n\nHere is one possible solution of the original problem:\n|*)\n\nLemma star_lemma : forall s, s <<- (#1 ^*) -> s = \"\".\nProof.\n  refine (fix star_lemma s prf {struct prf} : s = \"\" := _).\n  inversion_clear prf; subst.\n  inversion_clear H; subst.\n  - now inversion H0.\n  - inversion_clear H0; subst. inversion_clear H; subst.\n    rewrite (star_lemma s' H1).\n    reflexivity.\nQed.\n\n(*|\nThe main idea is to introduce a term in the context which will\nresemble the recursive call in a typical Idris proof. The approaches\nwith ``remember`` and ``dependent induction`` don't work well (without\nmodifications of ``in_regex``) because they introduce impossible to\nsatisfy equations as induction hypotheses' premises.\n\n*Note*: it can take a while to check this lemma (around 40 seconds on\nmy machine under Coq 8.5pl3). I think it's due to the fact that the\n``inversion`` tactic tends to generate big proof terms.\n\n----\n\n**A:** Nice! I really don't see how to prove it without using an\nhand-crafted fixpoint. Following your example, `I factored the proof\n<https://gist.github.com/gallais/58b42d5d9571ff0e6a432a9f40cf06c9>`__\nthrough a ``star_unfold`` lemma which says that if ``s <<- (e ^*\\ )``\nthen ``exists n, s <<- ntimes n e``. In the case of a full-blown\nlibrary, this should isolate the expensive check to ``star_unfold``\nalone given that later proofs can simply use induction on a natural\nnumber.\n\n**A:** Very good point! Please consider making your comment into an\nanswer -- I hear comments are not very reliable on SO. You could've\nalso used ``Nat.iter`` instead of ``ntimes`` to make the code shorter:\n``exists n, s <<- Nat.iter n (Cat e) #1.`` (But maybe it hurts\nreadability a bit).\n|*)\n\n(*|\nAnswer (eponier)\n****************\n\nThis problem has obsessed me for a week, and I have finally found a\nsolution that I find elegant.\n\nI had already read that when an induction principle does not fit your\nneeds, you can write and prove another one, more adapted to your\nproblem. That is what I have done in this case. What we would want is\nthe one obtained when using the more natural definition given in `this\nanswer <https://stackoverflow.com/a/40806050/5153939>`__. By doing\nthis, we can keep the same definition (if changing it implies too many\nchanges, for example) and reason about it more easily.\n\nHere is the proof of the induction principle (I use a section to\nspecify precisely the implicit arguments, since otherwise I observe\nstrange behaviours with them, but the section mechanism is not\nnecessary at all here).\n|*)\n\nReset star_lemma. (* .none *)\nSection induction_principle.\n\nContext (P : string -> regex -> Prop)\n  (H_InEps : P \"\" #1)\n  (H_InChr : forall c, P (String c \"\") ($ c))\n  (H_InCat : forall {e e' s s' s1}, s <<- e -> P s e -> s' <<- e' ->\n    P s' e' -> s1 = s ++ s' -> P s1 (e @ e'))\n  (H_InLeft : forall {s e e'}, s <<- e -> P s e -> P s (e :+: e'))\n  (H_InRight : forall {s' e e'}, s' <<- e' -> P s' e' -> P s' (e :+: e'))\n  (H_InStar_Eps : forall e, P \"\" (e ^*))\n  (H_InStar_Cat : forall {s1 s2 e}, s1 <<- e -> s2 <<- (e ^*) ->\n    P s1 e -> P s2 (e ^*) -> P (s1 ++ s2) (e ^*)).\n\nArguments H_InCat {_ _ _ _ _} _ _ _ _ _.\nArguments H_InLeft {_ _ _} _ _.\nArguments H_InRight {_ _ _} _ _.\nArguments H_InStar_Cat {_ _ _} _ _ _ _.\n\nDefinition in_regex_ind2 : forall (s : string) (r : regex), s <<- r -> P s r.\nProof\n  using H_InCat H_InChr H_InEps H_InLeft H_InRight H_InStar_Cat H_InStar_Eps.\n  refine (fix in_regex_ind2 {s r} prf {struct prf} : P s r :=\n    match prf with\n    | InEps => H_InEps\n    | InChr c => H_InChr c\n    | InCat prf1 prf2 eq1 =>\n        H_InCat prf1 (in_regex_ind2 prf1) prf2 (in_regex_ind2 prf2) eq1\n    | InLeft _ prf => H_InLeft prf (in_regex_ind2 prf)\n    | InRight _ prf => H_InRight prf (in_regex_ind2 prf)\n    | InStar prf => _\n    end).\n  inversion prf; subst.\n  - inversion H1. apply H_InStar_Eps.\n  - inversion H1; subst.\n    apply H_InStar_Cat; try assumption; apply in_regex_ind2; assumption.\nQed.\n\nEnd induction_principle.\n\n(*|\nAnd it turned out that the ``Qed`` of this proof was not instantaneous\n(probably due to ``inversion`` producing large terms as in `this\nanswer <https://stackoverflow.com/a/40807209/5153939>`__), but took\nless than 1s (maybe because the lemma is more abstract).\n\nThe ``star_lemma`` becomes nearly trivial to prove (as soon as we know\nthe ``remember`` trick), as with the natural definition.\n|*)\n\nLemma star_lemma : forall s, s <<- (#1 ^*) -> s = \"\".\nProof.\n  intros s H. remember (#1 ^*) as r.\n  induction H using in_regex_ind2; try discriminate.\n  - reflexivity.\n  - inversion Heqr; subst.\n    inversion H. rewrite IHin_regex2 by reflexivity. reflexivity.\nQed.\n\n(*|\nAnswer (Zimm i48)\n*****************\n\nI modified a bit the definition of your in_regex predicate:\n|*)\n\nReset in_regex. (* .none *)\nInductive in_regex : string -> regex -> Prop :=\n| InEps : \"\" <<- #1\n| InChr : forall c, (String c EmptyString) <<- ($ c)\n| InCat : forall e e' s s' s1,\n    s <<- e -> s' <<- e' -> s1 = s ++ s' -> s1 <<- (e @ e')\n| InLeft : forall s e e', s <<- e -> s <<- (e :+: e')\n| InRight : forall s' e e',  s' <<- e' -> s' <<- (e :+: e')\n| InStarLeft : forall e, \"\" <<- (e ^*)\n| InStarRight : forall s s' e, s <<- e -> s' <<- (e ^*) -> (s ++ s') <<- (e ^*)\nwhere \"s '<<-' e\" := (in_regex s e).\n\n(*| and could prove your lemma: |*)\n\nLemma star_lemma : forall s, s <<- (#1 ^*) -> s = \"\".\nProof.\n  intros s H.\n  remember (#1 ^*) as r.\n  induction H; inversion Heqr; clear Heqr; trivial.\n  subst e.\n  rewrite IHin_regex2; trivial.\n  inversion H; trivial.\nQed.\n\n(*|\nSome explanations are necessary.\n\n1. I did an induction on ``H``. The reasoning is: if I have a proof of\n   ``s <<- (#1 ^*\\ )`` then this proof must have the following form...\n2. The tactic `remember\n   <https://coq.inria.fr/refman/proof-engine/tactics.html#coq:tacv.remember>`__\n   create a new hypothesis ``Heqr`` which, combined with `inversion\n   <https://coq.inria.fr/refman/proof-engine/tactics.html#coq:tacn.inversion>`__\n   will help get rid of cases which cannot possibly give this proof\n   (in fact all the cases minus the ones where ``^*`` is in the\n   conclusion).\n3. Unfortunately, this path of reasoning does not work with the\n   definition you had for the ``in_regex`` predicate because it will\n   create an unsatisfiable condition to the induction hypothesis.\n   That's why I modified your inductive predicate as well.\n4. The modified inductive tries to give a more basic definition of\n   being in ``(e ^*\\ )``. Semantically, I think this is equivalent.\n\nI would be interested to read a proof on the original problem.\n\n----\n\n**A:** The proof of the original problem is `here\n<http://stackoverflow.com/a/40807209/2747511>`__ :).\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/stuck-on-a-simple-proof-about-regular-expressions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.6791372635676152}}
{"text": "\nRequire Import Omega.\n\n(* Submitted by Xavier Urbain 18 Jan 2002 *)\n\nLemma lem1 :\n forall x y : Z, (-5 < x < 5)%Z -> (-5 < y)%Z -> (-5 < x + y + 5)%Z.\nProof.\nintros x y.\n omega.\nQed.\n\n(* Proposed by Pierre Crégut *)\n\nLemma lem2 : forall x : Z, (x < 4)%Z -> (x > 2)%Z -> x = 3%Z.\nintro.\n omega.\nQed.\n\n(* Proposed by Jean-Christophe Filliâtre *)\n\nLemma lem3 : forall x y : Z, x = y -> (x + x)%Z = (y + y)%Z.\nProof.\nintros.\n omega.\nQed.\n\n(* Proposed by Jean-Christophe Filliâtre: confusion between an Omega *)\n(* internal variable and a section variable (June 2001) *)\n\nSection A.\nVariable x y : Z.\nHypothesis H : (x > y)%Z.\nLemma lem4 : (x > y)%Z.\n omega.\nQed.\nEnd A.\n\n(* Proposed by Yves Bertot: because a section var, L was wrongly renamed L0 *)\n(* May 2002 *)\n\nSection B.\nVariable R1 R2 S1 S2 H S : Z.\nHypothesis I : (R1 < 0)%Z -> R2 = (R1 + (2 * S1 - 1))%Z.\nHypothesis J : (R1 < 0)%Z -> S2 = (S1 - 1)%Z.\nHypothesis K : (R1 >= 0)%Z -> R2 = R1.\nHypothesis L : (R1 >= 0)%Z -> S2 = S1.\nHypothesis M : (H <= 2 * S)%Z.\nHypothesis N : (S < H)%Z.\nLemma lem5 : (H > 0)%Z.\n omega.\nQed.\nEnd B.\n\n(* From Nicolas Oury (bug #180): handling -> on Set (fixed Oct 2002) *)\nLemma lem6 :\n forall (A : Set) (i : Z), (i <= 0)%Z -> ((i <= 0)%Z -> A) -> (i <= 0)%Z.\nintros.\n omega.\nQed.\n\n(* Adapted from an example in Nijmegen/FTA/ftc/RefSeparating (Oct 2002) *)\nRequire Import Omega.\nSection C.\nParameter g : forall m : nat, m <> 0 -> Prop.\nParameter f : forall (m : nat) (H : m <> 0), g m H.\nVariable n : nat.\nVariable ap_n : n <> 0.\nLet delta := f n ap_n.\nLemma lem7 : n = n.\n omega.\nQed.\nEnd C.\n\n(* Problem of dependencies *)\nRequire Import Omega.\nLemma lem8 : forall H : 0 = 0 -> 0 = 0, H = H -> 0 = 0.\nintros;  omega.\nQed.\n\n(* Bug that what caused by the use of intro_using in Omega *)\nRequire Import Omega.\nLemma lem9 :\n forall p q : nat, ~ (p <= q /\\ p < q \\/ q <= p /\\ p < q) -> p < p \\/ p <= p.\nintros;  omega.\nQed.\n\n(* Check that the interpretation of mult on nat enforces its positivity *)\n(* Submitted by Hubert Thierry (bug #743) *)\n(* Postponed... problem with goals of the form \"(n*m=0)%nat -> (n*m=0)%Z\" *)\nLemma lem10 : forall n m:nat, le n (plus n (mult n m)).\nProof.\nintros; omega with *.\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/Omega.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143776, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.6791372500195745}}
{"text": "From mathcomp Require Import ssreflect.\n\nRequire Import collect_operator.\nRequire Import direct_product.\nRequire Import mapping.\nRequire Import mapping_space.\n\n(* 族:X_iは添字集合:Iから集合:Xへの写像である. X_i:I->X *)\n(* family X_i is alias of mapping indexing set I to set X *)\nDefinition TypeOfFamily (U V:Type) := U -> V.\nDefinition IndexedFamily {U V:Type} (map:TypeOfFamily U V) (I:Collection U) (X: Collection V) :=\n  forall i:U, i ∈ I -> exists Xi:V, Xi = map i /\\ Xi ∈ X.\n\n(* 族で添字に対応する要素が集合である場合,集合族と言う. 集合族は関数,写像 *)\n(* 添字集合の要素iからと集合の集合より紐付いた集合を取り出す関数 *)\nDefinition FamilyOfSetsWithFunction {U:Type} (map:U -> Collection U) (I:Collection U) (X: Collection (Collection U)) :=\n  IndexedFamily map I X.\n\nDefinition TypeOfGraphOfFamilyOfSets U := Collection (TypeOfOrderedPair (Collection U)).\n\n(* 族のGraphは添字集合と集合の直積の部分集合である *)\n(* Graph of family is subset of direct product of indexing set I to set X *)\n(* 集合族のGraph *)\nInductive GraphOfFamilyOfSets {U:Type} (map: TypeOfFamily U (Collection U)) (I:Collection U) (X: Collection (Collection U)) :\n  TypeOfGraphOfFamilyOfSets U :=\n| definition_of_graph_of_family_set:\n    forall Z:TypeOfOrderedPair (Collection U),\n      (exists i:U, exists x':Collection U, Z=<|{|i|},x'|> /\\ x' = map i /\\ i ∈ I /\\ x' ∈ X) ->\n      Z ∈ GraphOfFamilyOfSets map I X.\n\n(* 集合族から添字により集合を得ます *)\nDefinition PickIndexedSetByFamilyOfSets {U V:Type} (map:V -> Collection U) (i:V) : Collection U := map i.\n\n(* ⌞ Unicode: 231E BOTTOM LEFT CORNER *)\nNotation \"X_I ⌞ i\" := (PickIndexedSetByFamilyOfSets X_I i) (left associativity, at level 20).\n\n(* 部分集合族 *)\nDefinition FamilyOFSubsetsWithFunction {U:Type} (X_I:U -> Collection U) (I:Collection U) (X: Collection U) :=\n  forall i:U, i ∈ I ->  (X_I ⌞ i) ⊂ X /\\ exists X':Collection (Collection U), (X_I ⌞ i) ∈ X' /\\ FamilyOfSetsWithFunction X_I I X'.\n\nInductive BigCupOfFamilySet {U V:Type} (I:Collection V) (X_I: V -> Collection U): Collection U :=\n| intro_of_bigcup_of_family: forall x:U, (exists i:V, i ∈ I /\\ x ∈ (X_I ⌞ i)) -> x ∈ BigCupOfFamilySet I X_I.\n\nNotation \"⋃{ I , X_I }\" := (BigCupOfFamilySet I X_I).\n\nInductive BigCapOfFamilySet {U V:Type} (I:Collection V) (X_I: V -> Collection U) : Collection U :=\n| intro_of_bigcap_of_family: forall x: U, (forall i:V, i ∈ I -> x ∈ (X_I ⌞ i)) -> x ∈ BigCapOfFamilySet I X_I.\n\nNotation \"⋂{ I , X_I }\" := (BigCapOfFamilySet I X_I).\n\n(* 被覆 *)\nDefinition CoveringByFamilySet {U V:Type} (I:Collection V) (X:Collection U) (X_I:V->Collection U) := X ⊂ ⋃{ I , X_I }.\n\nSection FamilyCollection.\n  Variable U:Type.\n\n  (* 添字集合の要素iと集合族の要素は一意に決まる. *)\n  Theorem indexed_set_is_unique:\n    forall (X_I:TypeOfFamily U (Collection U)) (I:Collection U) (X': Collection (Collection U)),\n      FamilyOfSetsWithFunction X_I I X' ->\n      forall (i:U), i ∈ I -> exists! X_i:Collection U, X_I i = X_i.\n  Proof.\n    move => f_i I X' HF i HiI.\n    apply HF in HiI.\n    inversion HiI as [X_i].\n    inversion H.\n    exists X_i.\n    split.\n    apply sym_eq.\n    apply H0.\n    move => x' HF'.\n    rewrite -HF'.\n    trivial.\n  Qed.\n\n  (* 添字集合が空なら集合族の合併は空 *)\n  Theorem indexed_set_eq_empty_to_bigcup_eq_empty:\n    forall (X_I: TypeOfFamily U (Collection U)) (I:Collection U),\n      I = `Ø` ->\n      ⋃{ I , (fun i:U => X_I ⌞ i) } = `Ø`.\n  Proof.\n    move => X_I I HIE.\n    apply mutally_included_to_eq.\n    split => x H.\n    inversion H as [x0].\n    inversion H0 as [i0].\n    inversion H2.\n    rewrite HIE in H3.\n    apply DoubleNegativeElimination.\n    move => HxE.\n    move: H3.\n    apply noone_in_empty.\n    apply DoubleNegativeElimination.\n    move => HxE.\n    move: H.\n    apply noone_in_empty.\n  Qed.\n\n  (* 添字集合が空なら集合族の交わりは全体集合 *)\n  Theorem indexed_set_eq_empty_to_bigcap_eq_full:\n    forall (X_I: TypeOfFamily U (Collection U)) (I:Collection U),\n      I = `Ø` ->\n      ⋂{ I , (fun i:U => X_I ⌞ i) } = (FullCollection U).\n  Proof.\n    move => X_I I HIE.\n    apply mutally_included_to_eq.\n    split => x H.\n    apply intro_full_collection.\n    split => i HiI.\n    apply DoubleNegativeElimination => HXI.\n    rewrite HIE in HiI.\n    move: HiI.\n    apply noone_in_empty.\n  Qed.\n\n  (* 添字集合が空なら部分集合族の交わりはもとの集合の全体 *)\n  Theorem indexed_subset_eq_empty_to_bigcap_eq_full:\n    forall (X_I: TypeOfFamily U (Collection U)) (I:Collection U) (X:Collection U),\n    forall i:U, i ∈ I ->\n    I = `Ø` ->\n    ⋂{ I , (fun i:U => X_I ⌞ i) } = X.\n  Proof.\n    move => X_I I X i HiI HIE.\n    have L1: forall i:U, i ∉ I.\n    rewrite HIE.\n    apply noone_in_empty.\n    apply DoubleNegativeElimination => HnxX.\n    apply (L1 i).\n    apply HiI.\n  Qed.\n\n  Theorem LawOfDeMorganOfBigcup:\n    forall (X_I: TypeOfFamily U (Collection U)) (I:Collection U),\n      (⋃{ I , (fun i:U => X_I ⌞ i) })^c = ⋂{ I , (fun i:U => (X_I ⌞ i)^c) }.\n  Proof.\n    move => X_I I.\n    apply mutally_included_to_eq.\n    split => x H0.\n    split => i HiI HxnXi.\n    apply H0.\n    split.\n    exists i.\n    split.\n    apply HiI.\n    trivial.\n    move => HUc.\n    inversion HUc.\n    inversion H as [i [HiI HxXi]].\n    inversion H0.\n    apply H2 in HiI.\n    apply HiI.\n    trivial.\n  Qed.\n\n  Theorem LawOfDeMorganOfBigcap:\n    forall (X_I: TypeOfFamily U (Collection U)) (I:Collection U),\n      (⋂{ I , (fun i:U => X_I ⌞ i) })^c = ⋃{ I , (fun i:U => (X_I ⌞ i)^c) }.\n  Proof.\n    move => X_I I.\n    apply mutally_included_to_eq.\n    split => x H.\n    +apply notin_collect_iff_in_complement in H.\n     apply DoubleNegativeElimination => HnxX.\n     apply H.\n     split.\n     move => i HiI.\n     apply DoubleNegativeElimination => HnxXi.\n     apply HnxX.\n     split.\n     exists i.\n     split. trivial.\n     move => HxXi.\n     apply HnxXi.\n     trivial.\n    +move => HxCap.\n     inversion H.\n     inversion H0 as [i [HiI HnxX]].\n     apply HnxX.\n     inversion HxCap as [x1].\n     apply H2 in HiI.\n     trivial.\n  Qed.\n\n  (* 978-4-489-02249-4 P67 *)\n  Theorem a_set_includes_bigcup_of_sets_of_family_to_a_set_includes_element_of_sets_of_family:\n    forall (I Y:Collection U) (X_I: TypeOfFamily U (Collection U)),\n      ⋃{ I , (fun i:U => X_I ⌞ i) } ⊂ Y -> forall i:U, i ∈ I -> X_I ⌞ i ⊂ Y.\n  Proof.\n    move => I Y X_I H i HiI x HxXi.\n    apply H.\n    split.\n    exists i.\n    split; trivial.\n  Qed.\n\n  Theorem a_set_includes_element_of_sets_of_family_to_a_set_includes_bigcup_of_sets_of_family:\n    forall (I Y:Collection U) (X_I: TypeOfFamily U (Collection U)),\n    (forall i:U, i ∈ I -> X_I ⌞ i ⊂ Y) -> ⋃{ I , (fun i:U => X_I ⌞ i) } ⊂ Y.\n  Proof.\n    move => I Y X_I H x HxCup.\n    inversion HxCup.\n    inversion H0 as [i [H2 H3]].\n    apply H in H2.\n    apply H2.\n    trivial.\n  Qed.\n\n  Theorem a_set_includes_bigcup_of_sets_of_family_iff_a_set_includes_element_of_sets_of_family:\n    forall (I Y:Collection U) (X_I: TypeOfFamily U (Collection U)),\n      ⋃{ I , (fun i:U => X_I ⌞ i) } ⊂ Y <-> forall i:U, i ∈ I -> X_I ⌞ i ⊂ Y.\n  Proof.\n    move => I Y X_I.\n    rewrite /iff.\n    split;[apply a_set_includes_bigcup_of_sets_of_family_to_a_set_includes_element_of_sets_of_family|\n           apply a_set_includes_element_of_sets_of_family_to_a_set_includes_bigcup_of_sets_of_family].\n  Qed.\n\n  Theorem a_element_of_sets_of_family_includes_a_set_to_bigcap_of_sets_of_family_includes_a_set:\n    forall (I Y:Collection U) (X_I: TypeOfFamily U (Collection U)),\n      (forall i:U, i ∈ I -> Y ⊂ X_I ⌞ i) -> Y ⊂ ⋂{ I , (fun i:U => X_I ⌞ i) }.\n  Proof.\n    move => I Y X_I H x HxY.\n    split => i HiI.\n    apply H in HiI.\n    apply HiI.\n    assumption.\n  Qed.\n  \n\n  Theorem bigcap_of_sets_of_family_includes_a_set_to_a_element_of_sets_of_family_includes_a_set:\n    forall (I Y:Collection U) (X_I: TypeOfFamily U (Collection U)),\n      Y ⊂ ⋂{ I , (fun i:U => X_I ⌞ i) } -> forall i:U, i ∈ I -> Y ⊂ X_I ⌞ i.\n  Proof.\n    move => I Y X_I H i HiI x HxY.\n    apply H in HxY.\n    inversion HxY.\n    apply H0 in HiI.\n    assumption.\n  Qed.\n\n  Theorem a_element_of_sets_of_family_includes_a_set_iff_bigcap_of_sets_of_family_includes_a_set:\n    forall (I Y:Collection U) (X_I: TypeOfFamily U (Collection U)),\n      (forall i:U, i ∈ I -> Y ⊂ X_I ⌞ i) <-> Y ⊂ ⋂{ I , (fun i:U => X_I ⌞ i) }.\n  Proof.\n    move => I Y X_I.\n    rewrite /iff.\n    split;[apply a_element_of_sets_of_family_includes_a_set_to_bigcap_of_sets_of_family_includes_a_set|\n           apply bigcap_of_sets_of_family_includes_a_set_to_a_element_of_sets_of_family_includes_a_set].\n  Qed.\n\n  Theorem bigcup_union_of_sets_of_family_and_a_set_eq:\n    forall (I Y:Collection U) (X_I: TypeOfFamily U (Collection U)),\n      I <> `Ø` ->\n      ⋃{ I , (fun i:U => (X_I ⌞ i) ∪ Y) } = ⋃{ I , (fun i:U => (X_I ⌞ i)) } ∪ Y.\n  Proof.\n    move => I Y X_I HnIE.\n    apply mutally_included_to_eq.\n    split => x.\n    +move => H.\n     inversion H as [x0].\n     inversion H0 as [i].\n     inversion H2 as [HiI].\n     inversion H3.\n     left.\n     split.\n     exists i.\n     split; trivial.\n     right.\n     trivial.\n    +case => x0 H.\n     split.\n     inversion H.\n     inversion H0 as [i].\n     inversion H2.\n     exists i.\n     split.\n     trivial.\n     left.\n     trivial.\n     apply not_empty_collection_to_exists_element_in_collection in HnIE.\n     inversion HnIE as [i].\n     split.\n     exists i.\n     split;[trivial|right;trivial].\n    Qed.\n\n  (* 978-4-489-02249-4 P76 *)\n  Theorem union_bigcap_sets_of_family_and_a_set_eq:\n    forall (I Y:Collection U) (X_I: TypeOfFamily U (Collection U)),\n      ⋂{ I , (fun i:U => (X_I ⌞ i)) } ∪ Y = ⋂{ I , (fun i:U => (X_I ⌞ i) ∪ Y) }.\n  Proof.\n    move => I Y X_I.\n    apply mutally_included_to_eq.\n    split => x.\n    +case => x0 H.\n     ++split => i HiI.\n       left.\n       inversion H.\n       apply H0 in HiI.\n       trivial.\n     ++split => i HiI.\n       right.\n       trivial.\n    +case: (LawOfExcludedMiddle (x ∈ Y)) => HY H.\n     ++right.\n       trivial.\n       inversion H.\n     ++left.\n       split.\n       move => i HiI.\n       apply H0 in HiI.\n       inversion HiI.\n       apply H2.\n       apply DoubleNegativeElimination => Hn.\n       apply HY.\n       trivial.\n  Qed.\n\n  Theorem intersection_bigcap_sets_of_family_and_a_set_eq:\n    forall (I Y:Collection U) (X_I: TypeOfFamily U (Collection U)),\n      ⋃{ I , (fun i:U => (X_I ⌞ i)) } ∩ Y = ⋃{ I , (fun i:U => (X_I ⌞ i) ∩ Y) }.\n  Proof.\n    move => I Y X_I.\n    apply mutally_included_to_eq.\n    split => x H.\n    +split.\n    ++inversion H.\n      inversion H0.\n      inversion H3 as [i [HiI HxXi]].\n      exists i.\n      split; trivial.\n      split; trivial.\n    ++inversion H.\n      inversion H0 as [i [HiI HxXi]].\n      inversion HxXi.\n      split.\n      split.\n      exists i.\n      split;trivial.\n      trivial.\n  Qed.\n\nEnd FamilyCollection.\n", "meta": {"author": "seisyuu-hantatsushi", "repo": "implement_set_theory_in_coq", "sha": "49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c", "save_path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq", "path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq/implement_set_theory_in_coq-49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c/coq/sets_of_family.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6790596875539564}}
{"text": "Inductive SC(T:Type): Type :=\n| Value : T -> SC T\n| Unknown : SC T.\n\nInductive Stack(T:Type): Type :=\n| Empty : Stack T\n| Push:  T -> Stack T -> Stack T.\n(* For better readability I renamed Add constructor in Ex1.v to Push *)\n\n(* not_empty checks if the stack is empty or not by returning a Proposition*)\nDefinition not_empty(T:Type)(s:Stack T):Prop := s <> Empty T.\n\nDefinition isEmpty (T:Type)(s:Stack T) : bool :=\nmatch s with \n| Empty => true\n| Push _ _ => false\nend.\n\n\n(*pop and top are defined by doing the compile-time check that the stack is non empty *)\nDefinition pop(T:Type)(s:Stack T):not_empty T s -> Stack T := \nmatch s with \n| Empty => (fun proof: not_empty T s => (Empty T))\n| Push x r => (fun proof: not_empty T s => r )\nend.\n\nDefinition top(T:Type)(s:Stack T) : not_empty T s -> SC T :=\nmatch s with\n| Empty => (fun proof: not_empty T s => Unknown T)\n| Push x _ => (fun proof: not_empty T s => Value T x)\nend.\n\n(*post-conditions of push :\nSince the precondition of top is not_empty, it is used as an assumption here*)\nTheorem push_post_condition : forall t x xs, forall proof:not_empty t xs,(top t (Push t x xs))= (fun proof => Value t x).\n\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\n(*push invariant : all other elements should remain unchanged , pop( push x ts)=ts*) \n(*Since the precondition of pop is not_empty, it is used as an assumption here*)\n\nTheorem push_invariant : forall t x xs, forall proof:not_empty t xs, pop t (Push t x xs)=(fun proof =>xs).\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\n(* post condition of isEmpty: returns true if the stack is empty*)\n\n\nTheorem isEmpty_post_condition :forall t, isEmpty t (Empty t)= true.\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\n\nTheorem safe: forall (T:Type)(x y:T)(s:Stack T)(proof:not_empty T (Push T x s))(proof1:not_empty T (Push T y (Push T x s))),\n (s=Empty T)->(pop T ((pop T (Push T y (Push T x s))) proof1)) proof = Empty T.\nProof.\nintros.\nunfold pop.\nrewrite H.\nreflexivity.\nQed.\n\n(*\nDuring the second pop, the compile time check sees if the stack is empty or not.\nas the stack is empty at this point, it cant return the proof for the not_empty and \nthe program crashes.\n*)\nTheorem crash: forall (T:Type)(x:T)(s:Stack T)(proof:not_empty T (Push T x s))(proof1:not_empty T (Push T x (Push T x s))),((pop T ((pop T (Push T x s)) proof)) proof1) = Empty T.\nProof.\nAbort.\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/Exercise2/Ex3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.6790596867687717}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Functor.Main.\nRequire Import Cat.Cat.\nRequire Import Basic_Cons.Terminal.\nRequire Import Archetypal.Discr.Discr.\nRequire Import NatTrans.NatTrans NatTrans.NatIso.\n\n(** The unique functor to the terminal category. *)\nProgram Definition Functor_To_1_Cat (C' : Category) : (C' –≻ 1)%functor :=\n{|\n  FO := fun x => tt;\n  FA := fun a b f => tt;\n  F_id := fun _ => eq_refl;\n  F_compose := fun _ _ _ _ _ => eq_refl\n|}.\n\n(** Terminal category. *)\nProgram Instance Cat_Term : Terminal Cat :=\n{\n  terminal := 1%category;\n\n  t_morph := fun x => Functor_To_1_Cat x\n}.\n\nNext Obligation. (* t_morph_unique *)\nProof.\n  Func_eq_simpl;\n  FunExt;\n  match goal with\n    [|- ?A = ?B] =>\n    destruct A;\n      destruct B end;\n  trivial.\nQed.  \n\n(** A functor from terminal category maps all arrows (any arrow is just the identity)\nto the identity arrow. *)\nSection From_Term_Cat.\n  Context {C : Category} (F : (1 –≻ C)%functor).\n\n  Theorem From_Term_Cat : ∀ h, (F @_a tt tt h)%morphism = id.\n  Proof.\n    destruct h.\n    change tt with (id 1 tt).\n    apply F_id.\n  Qed.\n\nEnd From_Term_Cat.\n\n(** Any two functors from a category to the terminal categoy are naturally isomorphic. *)\nProgram Definition Functor_To_1_Cat_Iso\n        {C : Category}\n        (F F' : (C –≻ 1)%functor)\n  : (F ≃ F')%natiso :=\n{|\n  iso_morphism :=\n    {|\n      Trans := fun _ => tt\n    |};\n  inverse_morphism :=\n    {|\n      Trans := fun _ => tt\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/Cat/Cat_Terminal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6790596734115543}}
{"text": "Require Import List.\nRequire Import Arith.\n\nLtac caseEq f :=\n  generalize (refl_equal f); pattern f at -1; case f.\n\nInductive cmp : Set := Less : cmp | Equal : cmp | Greater : cmp.\n\nFixpoint three_way_compare (n m:nat) {struct n} : cmp :=\n  match n, m with\n  | O, O => Equal\n  | 0, S _ => Less\n  | S _, 0 => Greater\n  | S n', S m' => three_way_compare n' m'\n  end.\n\nFixpoint\n  update_primes (k:nat) (l: list (nat*nat)) {struct l} : list (nat*nat)*bool :=\n  match l with\n  | nil => (nil,false)\n  | (p,n)::tl => \n    let (l',b) := update_primes k tl in\n    match three_way_compare k n with\n    | Less => ((p, n)::l', b)\n    | Equal => ((p, n+p)::l', true)\n    | Greater => ((p, n+p)::l', b)\n    end\n  end.\n\nFixpoint prime_sieve (n:nat) : list (nat*nat) :=\n  match n with\n  | O => nil\n  | 1 => nil\n  | S k' => \n    let (l', b) := update_primes (S k')(prime_sieve k') in\n    if b then l' else ((S k', 2*S k')::l')\n  end.\n\nDefinition prime_fun (n:nat) : bool :=\n  match prime_sieve n with\n  | nil => false\n  | (p,q)::tl => \n    match three_way_compare p n with\n    | Equal => true\n    | _ => false\n    end\n  end.\n\n(* The rest of the file shows that we can prove interesting facts\n   about our function using only the notions that have been introduced \n   in the book up to chapter 6.  However, an expert user would rather\n   also rely on notions that are introduced later, like the inductive\n   properties found in chapter 8. *)\n \n\nDefinition divides (p n:nat) := exists q:nat, n = p*q.\n\nDefinition prime (n:nat) :=\n  (n<>0/\\n<>1)/\\~(exists k:nat, 1 < k < n /\\ divides k n).\n\nDefinition all_list(P:nat->nat->Prop) (l:list(nat*nat)):=\n forall (l1 l2:list(nat*nat))(p n:nat),\n   l = l1++(p, n)::l2 -> (P p n).\n\nDefinition all_first_less_than (k:nat) :=\n all_list (fun p n:nat => p < k).\n\nDefinition all_first_prime :=\n all_list (fun p n:nat => prime p).\n\nDefinition all_intervals (k:nat) :=\n all_list (fun p n:nat => n-p<k<=n).\n\nDefinition all_multiples :=\n all_list (fun p n:nat => exists q:nat, n=p*q).\n\nDefinition all_greater_than_one :=\n all_list (fun p n => 1 < p).\n\nDefinition all_prime_in_first (k:nat)(l:list (nat*nat)) :=\n forall n:nat, 0 < n < k -> prime n ->\n  (exists l1: list (nat*nat),\n    (exists l2: list (nat*nat),\n      (exists p: nat, l= l1++(n,p)::l2))).\n\n(* A theorem that should be in the general libraries. *)\n\nTheorem mult_lt_reg_l : \n  forall m n p, m * n < m * p -> n < p.\nProof.\n intros m n; elim n.\n intros p; case p.\n repeat (rewrite mult_comm; simpl); auto.\n auto with arith.\n intros n' Hrec p; case p.\n rewrite <- (mult_comm 0); simpl; intros Hlt; elim (lt_n_O (m*S n'));auto.\n intros p'; repeat rewrite <- mult_n_Sm.\n repeat rewrite <- (plus_comm m).\n intros Hlt; assert (Hlt' : m*n' < m* p').\n apply plus_lt_reg_l with m; auto.\n auto with arith.\nQed.\n\n\n(* Now come the proofs around three_way_compare. *)\n\nTheorem three_way_compare_Less1 :\n  forall n m:nat, three_way_compare n m = Less -> n < m.\nProof.\n intros n; elim n; simpl; auto with arith.\n intros m; case m; simpl; auto with arith.\n intros; discriminate.\n intros n0 Hrec m; case m; simpl; auto with arith.\n intros; discriminate.\nQed.\n\nTheorem three_way_compare_Less2 :\n  forall n m:nat, n < m -> three_way_compare n m = Less.\nProof.\n intros n; elim n; simpl.\n intros m; case m; simpl; auto.\n intros Hlt_absurd; elim (lt_irrefl 0); assumption.\n intros n0 Hrec m; case m; simpl; auto.\n intros Hlt_absurd; elim (lt_asym (S n0) 0); auto with arith.\n auto with arith.\nQed.\n\nTheorem three_way_compare_Equal1 :\n  forall n m:nat, three_way_compare n m = Equal -> n=m.\nProof.\n intros n; elim n.\n intros m; case m; simpl;auto.\n intros; discriminate.\n intros n0 Hrec m; case m; simpl; auto.\n intros; discriminate.\nQed.\n\nTheorem three_way_compare_Equal2 :\n  forall n, three_way_compare n n = Equal.\nProof.\n intros n; elim n; simpl; auto.\nQed.\n\nTheorem three_way_compare_Greater1 :\n  forall n m:nat, three_way_compare n m = Greater -> m < n.\nProof.\n intros n; elim n; simpl; auto with arith.\n intros m; case m; simpl; auto with arith.\n intros; discriminate.\n intros; discriminate.\n intros n0 Hrec m; case m; simpl; auto with arith.\nQed.\n\nTheorem three_way_compare_Greater2 :\n  forall n m:nat, m < n -> three_way_compare n m = Greater.\nProof.\n intros n; elim n; simpl.\n intros m; case m; simpl; auto.\n intros Hlt_absurd; elim (lt_irrefl 0); assumption.\n intros n0 Hlt_absurd; elim (lt_asym (S n0) 0); auto with arith.\n intros n0 Hrec m; case m; simpl; auto with arith.\nQed.\n\n(* A bunch of generic proofs about the all_list predicate. *)\n\nTheorem all_list_transmit :\n forall (P:nat->nat->Prop)(p:nat*nat)(l:list(nat*nat)),\n   all_list P (p::l)-> all_list P l.\nProof.\n intros P fst_elem l H l1 l2 p n Heq.\n unfold all_list in H.\n apply H with (fst_elem::l1) l2; rewrite Heq; auto.\nQed.\n\nTheorem all_list_add :\n forall (P:nat->nat->Prop)(l:list(nat*nat))(p n:nat),\n P p n -> all_list P l -> all_list P ((p,n)::l).\nProof.\n intros P l p n Hp Hal l1; case l1.\n intros l2 p' n' Heq; injection Heq; intros Hl Hn' Hp';\n rewrite <- Hn'; rewrite <- Hp'; auto.\n\n simpl; clear l1; intros fst_elem l1 l2 p' n' Heq; injection Heq;\n intros Hl Hfst; apply (Hal l1 l2); assumption.\nQed.\n\nTheorem absurd_decompose_list :\n forall (A:Set) (l1 l2:list A) (p:A), nil = l1++p::l2 -> False.\nProof.\n intros A l1; case l1; simpl; intros; discriminate.\nQed.\n\nTheorem all_list_nil :\n forall (P:nat->nat->Prop),\n  all_list P nil. \nProof.\n intros P l1 l2 p n Heq; elim (absurd_decompose_list _ _ _ _ Heq).\nQed. \n\n(* As corollaries, we get transmission theorems for the main predicates. *)\n\nTheorem all_intervals_transmit :\n forall (k:nat)(p:nat*nat)(l: list(nat*nat)),\n  all_intervals k (p::l) -> all_intervals k l.\nProof.\n intros k; exact (all_list_transmit (fun p n => n-p<k<=n)).\nQed.\n\nTheorem all_multiples_transmit :\n forall (p:nat*nat)(l: list(nat*nat)),\n  all_multiples (p::l) -> all_multiples l.\nProof.\n exact (all_list_transmit (fun p n => exists q:nat, n=p*q)).\nQed.\n\nTheorem all_greater_than_one_transmit :\n forall (p:nat*nat)(l: list(nat*nat)),\n  all_greater_than_one (p::l) -> all_greater_than_one l.\nProof.\n exact (all_list_transmit (fun p n => 1<p)).\nQed.\n\nTheorem all_first_prime_transmit :\n forall (p:nat*nat)(l:list(nat*nat)),\n  all_first_prime(p::l) -> all_first_prime l.\nProof.\n exact (all_list_transmit (fun p n => prime p)).\nQed.\n\nTheorem all_first_less_than_transmit :\n forall k (p:nat*nat)(l: list(nat*nat)),\n  all_first_less_than k (p::l) -> all_first_less_than k l.\nProof.\n intros k; exact (all_list_transmit (fun p n => p < k)).\nQed.\n\n(* Theorems about invariants in update_primes *)\nTheorem update_primes_all_list_invariant :\n forall (P:nat->nat->nat->Prop),\n (forall k p n:nat, k = n -> P k p n -> P k p (n+p))->\n (forall k p n:nat, n < k -> P k p n -> P k p (n+p))->\n forall (k:nat)(l l':list(nat*nat))(b:bool),\n  all_list (P k) l ->\n  update_primes k l = (l',b) -> all_list (P k) l'.\nProof.\n intros P Hp2 Hp3 k l; elim l.\n simpl; intros Hal l' b Hup; injection Hup; intros Hb Hl';\n rewrite <- Hl'; apply (all_list_nil (P k)).\n\n simpl; intros (p, n) l0 Hrec l' b Hal;\n caseEq (update_primes k l0); intros l'0 b0 Hup0.\n caseEq (three_way_compare k n); intros Htwc Hup; injection Hup;\n intros Hb Hl'; rewrite <- Hl';\n generalize (Hal nil l0 p n (refl_equal _)); intros HPkpn;\n generalize (Hrec l'0 b0 (all_list_transmit (P k) (p,n) l0 Hal) Hup0);\n intros Hal'; apply all_list_add; auto.\n\n apply Hp2;[apply three_way_compare_Equal1;auto| auto].\n apply Hp3;[apply three_way_compare_Greater1;auto| auto].\nQed.\n\n(* Now a few proofs about divides and prime *)\n\nTheorem divides_dec_aux : \n  forall k n p:nat, n <= k -> divides p n \\/ ~divides p n.\nProof.\n intros k; elim k.\n intros n p Hle; left; exists 0; rewrite mult_comm; simpl; \n symmetry; apply le_n_O_eq; auto.\n\n intros k' Hrec n p Hlt; elim (le_lt_or_eq n (S k')).\n auto with arith.\n\n intros Heq; rewrite Heq.\n case p.\n right; intros (q, Heq').\n discriminate Heq'.\n\n intros p'.\n caseEq (three_way_compare (S p') (S k')); intros Htwc.\n\n assert (S p' < S k').\n apply three_way_compare_Less1; auto.\n\n elim (Hrec (minus (S k') (S p')) (S p')).\n intros (q, Heq'); left; exists (S q).\n rewrite (le_plus_minus (S p') (S k')).\n rewrite Heq'.\n repeat rewrite (mult_comm (S p')).\n reflexivity.\n auto with arith.\n\n intros Hndiv; right; intros Hdiv.\n apply Hndiv.\n elim Hdiv.\n intros q; case q.\n rewrite mult_comm;  simpl; intros; discriminate.\n intros q' Heq'; exists q'.\n apply plus_reg_l with (S p').\n rewrite le_plus_minus_r.\n rewrite Heq'.\n rewrite plus_comm; rewrite mult_n_Sm; reflexivity.\n auto with arith.\n\n simpl.\n apply le_minus.\n\n assert (H:S p' = S k').\n apply three_way_compare_Equal1; auto.\n left; exists 1; rewrite H.\n auto with arith.\n\n assert (Hlt': S k' < S p').\n apply three_way_compare_Greater1; auto.\n right; intros Hdiv; elim Hdiv; intros q; case q.\n rewrite mult_comm; simpl; intros; discriminate.\n intros q' Heq'; elim (lt_not_le _ _ Hlt').\n rewrite Heq'.\n rewrite mult_comm; simpl; auto with arith.\n\n trivial.\nQed.\n\nTheorem eq_nat_or :\n forall n m:nat, n=m \\/ ~n=m.\nProof.\n intros n; elim n.\n intros m; case m.\n left; auto.\n right; auto.\n intros n' Hrec m; case m.\n right; auto with arith.\n intros m'; elim (Hrec m').\n left; auto with arith.\n right; auto with arith.\nQed.\n\nTheorem prime_dec_aux :\n forall n k:nat,\n  (n=0\\/n=1)\\/\n  (exists p:nat, 1<p<k /\\ (exists q:nat, n=p*q))\\/\n  ((n<>0/\\n<>1)/\\~(exists p:nat, 1<p<k/\\ (exists q:nat, n=p*q))).\nProof.\n intros n; elim (eq_nat_or n 1).\n auto.\n intros Hnneq1.\n elim (eq_nat_or n 0).\n auto.\n intros Hnneq0 k; elim k.\n right; right; split.\n auto.\n intros (p, ((_,Hlt0), (q, Heq))).\n elim (lt_n_O p); auto.\n intros k'; case k'.\n intros; right; right; split.\n auto.\n intros (p, ((Hpgt1, Hplt1),_)).\n elim (lt_irrefl 1); apply lt_trans with p;auto.\n intros k''; case k''.\n intros; right; right; split; auto; intros (p, ((Hpgt1, Hplt2),_)).\n elim (lt_irrefl p); apply le_lt_trans with 1; auto with arith.\n intros k''' Hrec; case (divides_dec_aux n n (S (S k'''))).\n auto with arith.\n intros Hdiv; right; left; exists (S (S k''')); repeat split; auto with arith.\n intros Hndiv; elim Hrec.\n auto.\n\n intros Hrec'; elim Hrec'.\n intros (p, ((Hpgt1, Hplt), Hex)); right; left; exists p; repeat split;\n   auto with arith.\n intros (_, Hnodiv); right; right; split; auto;\n   intros (p, ((Hpgt1, Hplt), Hex)).\n assert (Hple : p <= S (S k''')).\n auto with arith.\n elim (le_lt_or_eq _ _ Hple).\n intros Hplt'.\n elim Hnodiv; exists p; repeat split; auto with arith.\n intros Hpeq.\n elim Hndiv; rewrite <- Hpeq; exact Hex.\nQed.\n\nTheorem prime_dec :\n forall n:nat, (n=0\\/n=1)\\/(exists p:nat, 1<p<n /\\ (exists q:nat, n=p*q))\\/\n  prime n.\nProof.\n intros n; exact (prime_dec_aux n n).\nQed.\n\n\nTheorem div_by_prime_aux :\n forall k:nat, forall n:nat, n <= k ->\n 1 < n -> (exists p:nat, 1 < p < n /\\ (exists q : nat, n=p*q)) ->\n (exists p:nat, 1 < p < n /\\ (prime p) /\\ (exists q:nat, n=p*q)).\nProof.\n intros k; elim k.\n intros n Hle Hlt Hn.\n elim (lt_asym 1 0). \n apply lt_le_trans with n; assumption.\n auto with arith.\n intros k' Hrec n Hle Hlt Hn.\n elim (le_lt_or_eq n (S k')).\n intros Hle'; apply Hrec; auto with arith.\n\n elim Hn; intros p ((Hpgt1, Hpltn),(q,Heq)).\n intros HneqSk'.\n elim (prime_dec p).\n\n intros Hpeq0or1; elim Hpeq0or1.\n intros Hpeq0.\n rewrite Hpeq0 in Hpgt1; elim (lt_n_O 1); assumption.\n intros Hpeq1.\n rewrite Hpeq1 in Hpgt1; elim (lt_irrefl 1); assumption.\n intros Hpdec; elim Hpdec.\n intros Hexp.\n elim (Hrec p); auto with arith.\n intros p' ((Hp'gt1,Hp'ltp), (Hpr,(q', Heq'))).\n exists p'.\n split;[split|split]; auto with arith.\n apply lt_trans with p; auto with arith.\n exists (q' * q).\n rewrite mult_assoc.\n rewrite Heq; rewrite Heq'; trivial.\n\n unfold lt in Hpltn.\n rewrite HneqSk' in Hpltn; auto with arith.\n\n exists p;split;[split|split]; auto with arith.\n exists q; auto with arith.\n\n trivial.\nQed.\n\nTheorem div_by_prime :\n forall n:nat, 1 < n -> (exists p:nat, 1 < p < n /\\ (exists q : nat, n=p*q)) ->\n (exists p:nat, 1 < p < n /\\ (prime p) /\\ (exists q:nat, n=p*q)).\nProof.\n intros n; apply (div_by_prime_aux n n).\n auto with arith.\nQed.\n\n(* Now, theorems about update_primes. *)\n\nTheorem update_primes_true_aux :\n  forall (k:nat) (l1 l2 l3 l4: list(nat*nat))(b:bool),\n    update_primes k l1 = (l2, true) ->\n    update_primes k (l3++l1) = (l4, b) -> b=true.\nProof.\n intros k l1 l2 l3; elim l3.\n simpl; intros l4 b Heq1; rewrite Heq1; intros Heq2; injection Heq2; auto.\n\n simpl; intros (p,n) l; case (update_primes k (l++l1)).\n intros l4 b Hrec l4' b'; case (three_way_compare k n).\n intros Heq1 Heq2; injection Heq2.\n intros Heq3 Heq4; rewrite <- Heq3; apply Hrec with l4; auto.\n intros Heq1 Heq2; injection Heq2; auto.\n intros Heq1 Heq2; injection Heq2.\n intros Heq3 Heq4; rewrite <- Heq3; apply Hrec with l4; auto.\nQed.\n\nTheorem update_primes_true_imp_div :\n  forall (k:nat)(l: list (nat*nat)),\n    all_first_less_than k l ->\n    all_multiples l ->\n    all_greater_than_one l ->\n    forall l1, update_primes k l = (l1, true) ->\n      (exists p:nat, 1< p < k /\\ (exists q:nat, k = p*q)).\nProof.\n intros k l; elim l.\n simpl; intros; discriminate.\n intros (p,n) l0 Hrec Haf Ham Hal l1; simpl.\n caseEq (update_primes k l0).\n intros l2 b Hup; caseEq (three_way_compare k n).\n intros Htwc Heq; injection Heq; intros Hb Hl1.\n rewrite Hb in Hup; apply Hrec with l2.\n apply all_first_less_than_transmit with (p,n); auto.\n apply all_multiples_transmit with (p,n); auto.\n apply all_greater_than_one_transmit with (p,n); auto.\n auto.\n intros Htwc Heq; generalize (three_way_compare_Equal1 _ _ Htwc).\n intros Hk.\n exists p.\n split.\n split.\n unfold all_greater_than_one in Hal;\n  apply Hal with (nil (A:=nat*nat)) l0 n; auto.\n unfold all_first_less_than in Haf;\n  apply Haf with (nil (A:=nat*nat)) l0 n; auto.\n unfold all_multiples in Ham.\n rewrite Hk; apply Ham with (nil (A:=nat*nat)) l0; auto.\n intros Htwc Heq; injection Heq; intros Hb Hl1.\n rewrite Hb in Hup; apply Hrec with l2.\n apply all_first_less_than_transmit with (p,n); auto.\n apply all_multiples_transmit with (p,n); auto.\n apply all_greater_than_one_transmit with (p,n); auto.\n auto.\nQed.\n\nTheorem interval_eq :\n forall p q q', p*q'-p < p*q <= p*q' -> q=q'.\nProof.\n intros p; case p.\n simpl; intros q q' (Hlt, Hle); elim (lt_irrefl 0);assumption.\n\n intros p' q q' (Hlt, Hle).\n apply le_antisym.\n apply mult_S_le_reg_l with p'; auto.\n assert (Hlt' : (q' - 1)*S p' < S p' * q).\n rewrite mult_minus_distr_r.\n rewrite mult_1_l.\n rewrite (mult_comm q').\n assumption.\n rewrite (mult_comm (q' - 1)) in Hlt'.\n generalize (mult_lt_reg_l _ _ _ Hlt').\n case q'; simpl.\n auto with arith.\n intros n; rewrite <- minus_n_O.\n auto with arith.\nQed.\n\n\nTheorem update_primes_false_imp_prime :\n forall k l l1,\n   1 < k ->\n   all_multiples l ->\n   all_intervals k l ->\n   all_prime_in_first k l ->\n   update_primes k l = (l1,false) -> prime k.\nProof.\n intros k l l1 Hkgt1 Ham Hai Hap Heq.\n elim (prime_dec k); auto.\n intros Hkeq0or1;elim Hkeq0or1.\n intros Hkeq0.\n rewrite Hkeq0 in Hkgt1; elim (lt_n_O 1); assumption.\n intros Hkeq1; rewrite Hkeq1 in Hkgt1; elim (lt_irrefl 1); assumption.\n intros Hpdec; elim Hpdec.\n intros Hexdiv.\n generalize (div_by_prime _ Hkgt1 Hexdiv).\n  intros (p, ((Hpgt1,Hpltk), (Hpr, Hex))).\n elim (Hap p); auto.\n intros l'1 (l2, (n, Heq')).\n elim Hex; intros q Heq''. \n assert (Hint: n - p < k <= n).\n unfold all_intervals in Hai.\n apply Hai with l'1 l2. \n auto.\n assert (Hmult : (exists q':nat, n = p*q')).\n unfold all_multiples in Ham.\n apply Ham with l'1 l2.\n auto.\n elim Hmult; intros q' Heq3.\n assert (Heq4: q=q').\n\n apply interval_eq with p.\n rewrite <- Heq3.\n rewrite <- Heq''.\n assumption.\n\n cut (false = true).\n intros;discriminate.\n caseEq (update_primes k ((p,n)::l2)).\n intros l3 b Hup.\n generalize (update_primes_true_aux k ((p,n)::l2) l3 l'1 l1 false).\n intros H; apply H.\n generalize Hup.\n simpl.\n case (update_primes k l2).\n intros l5 b2.\n rewrite Heq''; rewrite Heq3; rewrite Heq4.\n rewrite three_way_compare_Equal2.\n intros Heq5; injection Heq5; intros Heq6 Heq7; rewrite Heq6;rewrite Heq7;\n auto with arith.\n rewrite <- Heq'.\n assumption.\n auto with arith.\n trivial.\n\nQed.\n\n(* We can now prove that all properties are invariant. *)\n\nTheorem update_primes_all_multiples :\n  forall k l l' b,\n    all_multiples l ->\n       update_primes k l = (l', b) -> all_multiples l'.\nProof.\n apply (update_primes_all_list_invariant (fun k p n => exists q:nat, n=p*q));\n try (intros k p n Hcomp (q, Heq);exists (S q);rewrite Heq;\n rewrite <- mult_n_Sm; reflexivity).\nQed.\n\n\nTheorem update_primes_all_first_less_than :\n forall k l l' b,\n all_first_less_than k l ->\n update_primes k l = (l',b) ->\n all_first_less_than k l'.\nProof.\n apply (update_primes_all_list_invariant (fun k p n => p < k)); auto.\nQed.\n\n\nTheorem update_primes_all_greater_than_one :\n forall k l l' b,\n  all_greater_than_one l ->\n  update_primes k l = (l',b) ->\n  all_greater_than_one l'.\nProof.\n apply (update_primes_all_list_invariant (fun k p n => 1 < p)); auto.\nQed.\n\nTheorem update_primes_all_first_prime :\n forall k l l' b,\n  all_first_prime l -> update_primes k l = (l',b) -> all_first_prime l'.\nProof.\n apply (update_primes_all_list_invariant (fun k p n => prime p)); auto.\nQed.\n\nTheorem update_primes_all_intervals :\n forall (k:nat)(l:list(nat*nat)),\n   all_intervals k l -> all_greater_than_one l ->\n   forall l' b, update_primes k l = (l',b) -> all_intervals (S k) l'.\nProof.\n intros k l; elim l.\n simpl; intros Hai Hal l' b Hup; injection Hup; intros Hb Hl'; rewrite <- Hl'.\n intros l1 l2 n p Heq; elim (absurd_decompose_list _ _ _ _ Heq).\n\n simpl; intros (p, n) l0 Hrec Hai Hal l' b;\n caseEq (update_primes k l0); intros l'0 b0 Hup0 Hup l1.\n case l1.\n\n unfold all_intervals in Hai.\n caseEq (three_way_compare k n); simpl; intros Htwc l2 p' n' Heq;\n rewrite Htwc in Hup; injection Hup; intros Hb Hl';\n rewrite <- Hl' in Heq; injection Heq; intros Hl2 Hn' Hp';\n rewrite <- Hp'; rewrite <- Hn';\n generalize (Hai nil l0 p n (refl_equal _));\n intros (Hlt, Hle);split; \n (generalize (three_way_compare_Less1 _ _ Htwc) ||\n  generalize (three_way_compare_Equal1 _ _ Htwc) ||\n  generalize (three_way_compare_Greater1 _ _ Htwc)); auto with arith.\n\n intros Heq2; rewrite Heq2; rewrite plus_comm; rewrite minus_plus;\n auto with arith.\n\n intros Heq2; rewrite Heq2; unfold all_greater_than_one in Hal;\n generalize (Hal nil l0 p n (refl_equal _)); intros Hpgt1.\n pattern n at 1; rewrite plus_n_O; rewrite plus_n_Sm;\n apply plus_le_compat; auto with arith.\n\n rewrite plus_comm; rewrite minus_plus; auto with arith.\n generalize (Hal nil l0 p n (refl_equal _)); intros Hpgt1.\n intros Hkltn; pattern k at 1; rewrite plus_n_O; rewrite plus_n_Sm;\n apply plus_le_compat; auto with arith.\n\n generalize (all_intervals_transmit _ _ _ Hai); intros Hai'.\n generalize (all_greater_than_one_transmit _ _ Hal); intros Hal'.\n\n simpl; clear l1; intros fst_elem l1 l2 p' n' Heq; generalize Hup;\n rewrite Heq.\n\n case (three_way_compare k n); intros Hup'; injection Hup'; \n intros Hb Hl' _; apply (Hrec Hai' Hal' l'0 b0 Hup0 l1 l2); assumption.\nQed.\n\nTheorem all_first_less_than_S :\n forall k l, all_first_less_than k l -> all_first_less_than (S k) l.\nProof.\n intros k l; elim l.\n intros Haf l1 l2 p n Heq; elim (absurd_decompose_list _ _ _ _ Heq).\n\n intros (p,n) l0 Hrec Haf l1.\n case l1.\n intros l2 p' n' Heq;\n generalize (Haf nil l2 p' n' Heq); intros Hpltk.\n auto with arith.\n\n simpl; clear l1; intros fst_elem l1 l2 p' n' Heq.\n injection Heq; intros; \n apply (Hrec (all_first_less_than_transmit _ _ _ Haf) l1 l2 p' n');\n assumption.\nQed.\n\nTheorem all_intervals_add :\n forall (l:list(nat*nat))(k p n:nat),\n  n-p < k <= n ->\n  all_intervals k l ->\n  all_intervals k ((p,n)::l).\nProof.\n intros l k p n Hint Hai l1; case l1.\n intros l2 p' n' Heq; injection Heq; intros Hl Hn' Hp';\n rewrite <- Hn'; rewrite <- Hp'; auto.\n\n  simpl; clear l1; intros fst_elem l1 l2 p' n' Heq; injection Heq;\n intros Hl Hfst; apply (Hai l1 l2); assumption.\nQed.\n\nTheorem all_first_prime_add :\n forall (l:list(nat*nat))(p n:nat),\n  prime p ->\n  all_first_prime l -> all_first_prime ((p,n)::l).\nProof.\n intros l p n Hlt Haf l1; case l1.\n intros l2 p' n' Heq; injection Heq; intros Hl Hn' Hp';\n rewrite <- Hp'; assumption.\n\n simpl; clear l1; intros fst_elem l1 l2 p' n' Heq; injection Heq;\n intros Hl Hfst; apply (Haf l1 l2 p' n' Hl).\nQed.\n\nTheorem all_multiples_add :\n forall l n p,\n  (exists q:nat, n=p*q)->\n  all_multiples l ->\n  all_multiples ((p,n)::l).\nProof.\n intros l n p Hdiv Ham l1; case l1.\n simpl; intros l2 p' n' Heq; injection Heq;\n intros Hl2 Hn' Hp'; rewrite <- Hn'; rewrite <- Hp';\n assumption.\n\n clear l1; simpl; intros fst_elem l1 l2 p' n' Heq; injection Heq;\n intros Hl Hfst; apply (Ham l1 l2); assumption.\nQed.\n\nTheorem all_greater_than_one_add :\n forall l n p,\n  1 < p -> all_greater_than_one l ->\n  all_greater_than_one ((p,n)::l).\nProof.\n intros l n p Hlt Hal  l1; case l1.\n simpl; intros l2 p' n' Heq; injection Heq;\n intros Hl2 Hn' Hp'; rewrite <- Hp';\n assumption.\n\n clear l1; simpl; intros fst_elem l1 l2 p' n' Heq; injection Heq;\n intros Hl Hfst; apply (Hal l1 l2 p' n'); assumption.\nQed.\n\nFixpoint same_first (l1 l2:list(nat*nat)) {struct l1} : bool :=\n  match l1, l2 with\n    nil, nil => true\n  | ((a, _)::l'1), ((b, _)::l'2) =>\n    match three_way_compare a b with\n    | Equal => same_first l'1 l'2\n    | _ => false\n    end\n  | _, _ => false\n  end.\n\nTheorem update_primes_same_first :\n forall k l l' b,\n   update_primes k l = (l', b) ->\n   forall l1 l2 p n,\n   l = l1++(p,n)::l2 -> \n   (exists l'1 : list(nat*nat),\n     (exists l'2 : list(nat*nat),\n       (exists n': nat,\n         l'=l'1++(p,n')::l'2))).\nProof.\n intros k l; elim l.\n intros l' b Hup l1 l2 p n Heq; elim (absurd_decompose_list _ _ _ _ Heq).\n\n intros (p,n) l0 Hrec l' b.\n simpl; caseEq (update_primes k l0); intros l'0 b0 Hup'.\n\n case (three_way_compare k n); intros Hup; injection Hup;\n intros Hb Hl'; intros l1; (case l1; [simpl; intros l2 p0 n0 Heq;\n injection Heq; intros Hl2 Hn0 Hp0; rewrite <- Hl'; rewrite <- Hp0;\n exists (nil (A:=nat*nat)); exists l'0 | \n clear l1; simpl; intros fst_elem l1 l2 p0 n0 Heq; injection Heq;\n intros Hl0 Hfst_elem; rewrite <- Hl';\n elim (Hrec l'0 b0 Hup' l1 l2 p0 n0 Hl0); intros l'1 (l'2, (n', Heq2));\n rewrite Heq2]).\n\n exists n; reflexivity.\n exists ((p,n)::l'1); exists l'2; exists n'; reflexivity.\n exists (n+p); reflexivity.\n exists ((p,n+p)::l'1); exists l'2; exists n'; reflexivity.\n exists (n+p); reflexivity.\n exists ((p,n+p)::l'1); exists l'2; exists n'; reflexivity.\nQed.\n\nTheorem update_primes_all_prime_in_first :\n forall k l l' b,\n  all_prime_in_first k l ->\n  update_primes k l = (l', b) ->\n  all_prime_in_first k l'.\nProof.\n intros k l l' b Hap Hup p Hplek Hpr.\n elim (Hap p Hplek Hpr); intros l'1 (l'2, (n', Heq)).\n apply (update_primes_same_first k l l' b Hup l'1 l'2 p n' Heq).\nQed.\n\n\nTheorem prime_sieve_invariant :\n forall k l,\n   prime_sieve (S k)=l ->\n   all_first_less_than (S (S k)) l /\\\n   all_first_prime l /\\\n   all_prime_in_first (S (S k)) l /\\\n   all_intervals (S (S k)) l /\\\n   all_multiples l /\\\n   all_greater_than_one l.\nProof.\nintros k; elim k.\n  simpl; intros l Hl; rewrite <- Hl; clear Hl l.\n  split;[idtac | split; [idtac | split;[idtac|split;[idtac|split]]]];\n    try (intros l1 l2 p n Heq; elim (absurd_decompose_list _ _ _ _ Heq)).\nintros n Hle1 ((Hnneq0, Hnneq1),_); elim Hnneq1.\nelim Hle1; intros; apply (le_antisym n 1); auto with arith.\n\nintros k' Hrec l Hps.\n change ((let (l', b) := \n   update_primes (S (S k')) (prime_sieve (S k')) in\n   if b then l' else (S (S k'), 2*S (S k'))::l') = l) in Hps.\ncaseEq (update_primes (S (S k')) (prime_sieve (S k'))); intros l' b Heq.\ngeneralize (Hrec (prime_sieve (S k'))); intros Hrec'.\nassert (Hal: all_first_less_than (S (S k')) l').\napply update_primes_all_first_less_than with (prime_sieve (S k')) b; auto.\nintuition.\nassert (Hafp: all_first_prime l').\napply update_primes_all_first_prime \n  with (S (S k')) (prime_sieve (S k')) b; auto.\nintuition.\nassert (Hapf: all_prime_in_first (S (S k')) l').\napply update_primes_all_prime_in_first with (prime_sieve (S k')) b; auto.\nintuition.\nassert (Hai : all_intervals (S (S (S k'))) l').\napply update_primes_all_intervals with (prime_sieve (S k')) b; auto.\nintuition.\nintuition.\nassert (Ham : all_multiples l').\napply update_primes_all_multiples \n  with (S (S k')) (prime_sieve (S k')) b; auto.\nintuition.\nassert (Ha1 : all_greater_than_one l').\napply update_primes_all_greater_than_one with (S (S k')) (prime_sieve (S k')) b; auto.\nintuition.\n\ncaseEq b; intros Heqb; rewrite Heqb in Heq; rewrite Heq in Hps.\nrewrite <- Hps.\nsplit;[idtac|split;[idtac|split;[idtac|split;[idtac|split;[idtac|idtac]]]]]; \n auto.\napply all_first_less_than_S; assumption.\nunfold all_prime_in_first.\nintros n Hint Hpr; unfold all_prime_in_first in Hapf; apply Hapf; auto.\nsplit.\nintuition.\nelim Hint.\nintros Hngt0 Hnlek.\nelim (le_lt_or_eq _ _ Hnlek).\nauto with arith; fail.\nintros Hn'; injection Hn'.\nintros Hn; rewrite Hn in Hpr; elim Hpr.\nintros _ Hnex; elim Hnex.\nunfold divides.\napply update_primes_true_imp_div with (prime_sieve (S k')) l'.\nintuition.\nintuition.\nintuition.\nauto.\n\nsplit.\n\nintros l1; case l1.\nsimpl; intros l2 p n; rewrite <- Hps; intros Heq2;injection Heq2.\nintros Hl2 Hn Hp; rewrite <- Hp; auto with arith.\nintros fst_elem l'1 l2 p n; simpl; rewrite <- Hps; intros Heq2;\ninjection Heq2; intros Hl' Hfst_elem.\nassert (Hal' : all_first_less_than (S (S (S k'))) l').\napply all_first_less_than_S; auto.\napply (Hal' l'1 l2 p n); auto.\n\nsplit.\nrewrite <- Hps; apply all_first_prime_add; auto.\napply update_primes_false_imp_prime with (prime_sieve (S k')) l';\n try tauto.\nauto with arith.\n\nsplit.\nrewrite <- Hps.\nintros n (Hpos, Hle) Hpr.\nelim (le_lt_or_eq _ _ Hle).\nintros Hlt; elim (Hapf n); auto with arith.\nintros l'1 (l'2, (p, Heq2));\nexists ((S (S k'), 2*S(S k'))::l'1); exists l'2; exists p.\nrewrite Heq2;reflexivity.\nintros Hn'; injection Hn'; intros Hn.\nexists (nil (A:=nat*nat)); exists l'; exists (2*S (S k')).\nrewrite Hn;reflexivity.\n\n\nsplit.\nrewrite <- Hps; apply all_intervals_add; auto with arith.\nsplit.\nsimpl.\nrewrite minus_plus.\nrewrite <- plus_n_O.\nauto with arith.\nsimpl.\nrepeat rewrite <- plus_n_Sm.\nauto with arith.\n\nsplit.\nrewrite <- Hps; apply all_multiples_add; auto with arith.\nexists 2; rewrite (mult_comm 2); reflexivity.\n\nrewrite <- Hps.\napply all_greater_than_one_add; auto with arith.\nQed.\n\nTheorem prime_fun_sound :\n forall k, prime_fun k = true -> prime k.\nProof.\n intros k0; case k0.\n simpl; intros; discriminate.\n intros k; unfold prime_fun.\n caseEq (prime_sieve (S k)).\n \n intros; discriminate.\n intros (p,n) l Heq; caseEq (three_way_compare p (S k));\n try(intros; discriminate; fail).\n intros Htwc _.\n \n assert (Hap:all_first_prime ((p,n)::l)).\n generalize (prime_sieve_invariant k ((p,n)::l) Heq); intuition.\n rewrite <- (three_way_compare_Equal1 _ _ Htwc).\n apply (Hap nil l p n); auto.\nQed.\n\nTheorem prime_fun_complete :\n forall k, prime k -> prime_fun k = true.\nProof.\n intros k; case k.\n intros ((Hneq0, Hneq1),Hnex); elim Hneq0; auto.\n intros k'; case k'.\n intros ((Hneq0, Hneq1),Hnex); elim Hneq1; auto.\n intros k'' ((_,_),Hnex).\n unfold prime_fun.\n\n assert (Hps: prime_sieve (S (S k'')) = \n              let (l',b) := (update_primes (S (S k'')) (prime_sieve (S k''))) \n              in\n              if b then l' else ((S (S k''), 2*S (S k''))::l')).\n auto.\n rewrite Hps.\n\n caseEq  (update_primes (S (S k'')) (prime_sieve (S k''))).\n intros l' b; case b; intros Hup.\n elim Hnex.\n unfold divides.\n generalize (prime_sieve_invariant k'' (prime_sieve (S k''))); intros Hinv.\n apply (update_primes_true_imp_div (S (S k'')) (prime_sieve (S k''))) with l';\n intuition.\n\n rewrite (three_way_compare_Equal2 (S (S k''))); 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/erato.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6790151623780823}}
{"text": "From mathcomp Require Import ssreflect.\nFrom Category.Base Require Import Logic Category Functor NatTran.\n\nProgram Definition DiscreteCat (A : Type) : Category :=\n  {|\n    Obj := A;\n    Hom := fun x y => x = y;\n  |}.\n\nLemma DiscreteCat_Hom_eq :\n  forall {A : Type},\n  forall {X Y : Obj (DiscreteCat A)},\n  forall (f g : Hom X Y), f = g.\nProof.\n  move => A X Y.\n  unfold Hom.\n  simpl.\n  move => f g.\n  exact: p_proof_irrelevance.\nQed.\n\nDefinition Cat0 := DiscreteCat False.\n\nDefinition Cat1 := DiscreteCat True.\nDefinition Cat1Obj : Obj Cat1 := I.\n\nLemma Cat1Obj_eq :\n  forall (X Y : Obj Cat1), X = Y.\nProof.\n  case.\n  case.\n  reflexivity.\nQed.\n\nLemma Cat1Hom_eq :\n  forall {X Y : Obj Cat1} (f g : Hom X Y), f = g.\nProof.\n  move => X Y f g.\n  exact: DiscreteCat_Hom_eq.\nQed.\n", "meta": {"author": "k27c8ff627uxz", "repo": "category_theory", "sha": "d5568b2ba04120a4f0e5bc7f2d61297c3cf42b9e", "save_path": "github-repos/coq/k27c8ff627uxz-category_theory", "path": "github-repos/coq/k27c8ff627uxz-category_theory/category_theory-d5568b2ba04120a4f0e5bc7f2d61297c3cf42b9e/src/Instances/DiscreteCat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6789639110929795}}
{"text": "Require Import Setoid ProofIrrelevance FunctionalExtensionality Ensembles.\nRequire Import Common Notations.\n\nSet Implicit Arguments.\n\n(**\n   An equivalence class is a non-empty set of all values\n   which are all equivalent to some particular value.\n*)\n\nLocal Ltac specialize_with tac fin_tac :=\n  match goal with\n    | [ x : ?T, H : forall _ : ?T, _ |- _ ] => specialize (H x); tac; specialize_with tac fin_tac\n    | _ => fin_tac\n  end.\n\nSection EquivalenceClass.\n  Variable value : Type.\n  Variable equiv : value -> value -> Prop.\n  (* [E] is an equivalence class if it is non-empty and if all it consists\n     of all values that are equivalent to some particular value.\n     Because the equivalence relation is transitive, we can encode\n     this without picking a representative element by requiring that\n     for every member of the class, the class consists of exactly the\n     values equivalent to that member. *)\n  Record EquivalenceClass := {\n    InClass : value -> Prop;\n\n    ClassInhabited : exists v, InClass v;\n\n    ClassEquivalent : relation value := equiv;\n    ClassEquivalent_refl : Reflexive ClassEquivalent;\n    ClassEquivalent_sym : Symmetric ClassEquivalent;\n    ClassEquivalent_trans : Transitive ClassEquivalent;\n\n    ClassElementsEquivalent : forall v, InClass v -> forall v', InClass v' -> ClassEquivalent v v';\n    ClassContainsEquivalent : forall v, InClass v -> forall v', ClassEquivalent v v' -> InClass v'\n  }.\nEnd EquivalenceClass.\n\nAdd Parametric Relation value equiv (E : @EquivalenceClass value equiv) : _ (ClassEquivalent E)\n  reflexivity proved by (@ClassEquivalent_refl _ _ _)\n  symmetry proved by (@ClassEquivalent_sym _ _ _)\n  transitivity proved by (@ClassEquivalent_trans _ _ _)\n    as ClassEquivalent_rel.\n\nAdd Parametric Morphism value equiv (E : @EquivalenceClass value equiv) : (InClass E)\n  with signature equiv ==> iff\n    as InClass_mor.\n  intros x y eqv; split; intro inc;\n    eapply ClassContainsEquivalent; eauto; try symmetry; eauto.\nQed.\n\nSection equiv.\n  Variable value : Type.\n  Variable equiv : value -> value -> Prop.\n\n  Hypothesis equiv_Equivalence : Equivalence equiv.\n\n  Local Add Parametric Relation : _ equiv\n    reflexivity proved by (Equivalence.equiv_reflexive _)\n    symmetry proved by (Equivalence.equiv_symmetric _)\n    transitivity proved by (Equivalence.equiv_transitive _)\n      as equiv_equiv_rel.\n\n  Local Infix \"~=\" := equiv (at level 70).\n\n  Local Ltac simpl_equiv := hnf; intros; trivial;\n    repeat match goal with\n             | _ => solve [ reflexivity ]\n             | _ => solve [ symmetry; trivial ]\n             | _ => solve [ etransitivity; eauto ]\n             | _ => solve [ symmetry; etransitivity; eauto ]\n             | _ => solve [ etransitivity; eauto; symmetry; eauto ]\n             | [ H : equiv _ _ -> False |- _ ] => contradict H; trivial\n             | [ H : ~ equiv _ _ |- _ ] => contradict H; trivial\n           end.\n\n  (* The equivalence [classOf] a particular [value] is defined by the proposition that\n     the elements are equivalent to that [value]. *)\n  Definition classOf (v : value) : EquivalenceClass equiv.\n    exists (fun v' => v ~= v');\n      abstract (\n        repeat esplit; unfold InClass in *;\n          simpl_equiv\n      ).\n  Defined.\n\n  Lemma classOf_refl : forall v, InClass (classOf v) v.\n    compute; intro; reflexivity.\n  Qed.\n\n  (* Two equivalence classes are the same if they share all values *)\n  Definition sameClass (C C' : EquivalenceClass equiv) := forall v, (InClass C v <-> InClass C' v).\n\n  Definition disjointClasses (C C' : EquivalenceClass equiv) := forall v, ~InClass C v \\/ ~InClass C' v.\n\n  Definition differentClasses (C C' : EquivalenceClass equiv) := exists v,\n    (InClass C v /\\ ~InClass C' v) \\/\n    (~InClass C v /\\ InClass C' v).\n\n  Definition notDisjointClasses (C C' : EquivalenceClass equiv) := exists v, InClass C v /\\ InClass C' v.\n\n  Definition notDisjointClasses' (C C' : EquivalenceClass equiv) := exists v v', InClass C v /\\ InClass C' v' /\\ equiv v v'.\n\n  Lemma sameClass_refl (C : EquivalenceClass equiv) : sameClass C C.\n    clear equiv_Equivalence; firstorder.\n  Qed.\n\n  Lemma sameClass_sym (C C' : EquivalenceClass equiv) : sameClass C C' -> sameClass C' C.\n    clear equiv_Equivalence; firstorder.\n  Qed.\n\n  Lemma sameClass_trans (C C' C'' : EquivalenceClass equiv) : sameClass C C' -> sameClass C' C'' -> sameClass C C''.\n    clear equiv_Equivalence; firstorder.\n  Qed.\n\n  Lemma sameClass_eq (C C' : EquivalenceClass equiv) : (sameClass C C') -> (C = C').\n    clear equiv_Equivalence; intro H.\n    cut (InClass C = InClass C');\n      destruct C, C'; simpl;\n        intros;\n          unfold sameClass in *;\n            subst;\n              split_iff;\n              f_equal; try apply proof_irrelevance;\n                apply Extensionality_Ensembles;\n                  hnf; split; hnf; simpl;\n                    firstorder.\n  Qed.\n\n  Lemma eq_sameClass (C C' : EquivalenceClass equiv) : C = C' -> sameClass C C'.\n    intro; subst; apply sameClass_refl.\n  Qed.\n\n  Global Add Parametric Morphism : classOf\n    with signature equiv ==> eq\n      as classOf_mor.\n    intros x y eqv;\n      apply sameClass_eq; compute in *; intros; split; intros; simpl_equiv.\n  Qed.\n\n  Lemma classOf_eq x y : classOf x = classOf y <-> equiv x y.\n    split; intro H; try apply classOf_mor; trivial.\n    pose (classOf_refl x).\n    pose (classOf_refl y).\n    rewrite H in *;\n      compute in *;\n        simpl_equiv.\n  Qed.\n\n  Lemma disjointClasses_differentClasses (C C' : EquivalenceClass equiv) : (disjointClasses C C') -> (differentClasses C C').\n    clear equiv_Equivalence; unfold differentClasses, disjointClasses; intro H.\n    pose (ClassInhabited C) as H'; destruct H' as [ x H' ].\n    exists x; specialize (H x); tauto.\n  Qed.\n\n  Lemma notDisjointClasses_sameClass (C C' : EquivalenceClass equiv) : (notDisjointClasses C C') -> (sameClass C C').\n    clear equiv_Equivalence; unfold notDisjointClasses, sameClass; intro H; destruct H as [ x [ H0 H1 ] ]; intro v; split; intros;\n      match goal with\n        | [ H0 : InClass ?C ?x, H1 : InClass ?C ?y |- InClass ?C' ?x ]\n          => let H := fresh in\n            assert (H : equiv x y) by (apply (ClassElementsEquivalent C); assumption);\n              rewrite H; assumption\n      end.\n  Qed.\n\n  Lemma notDisjointClasses_eq (C C' : EquivalenceClass equiv) : (notDisjointClasses C C') -> C = C'.\n    clear equiv_Equivalence; intro; apply sameClass_eq; apply notDisjointClasses_sameClass; assumption.\n  Qed.\n\n  Lemma EquivalenceClass_forall_equiv__eq (C C' : EquivalenceClass equiv) :\n    (forall v v', (InClass C v \\/ InClass C' v') -> (InClass C v /\\ InClass C' v' <-> equiv v v')) ->\n    C' = C.\n    clear equiv_Equivalence; intro H. apply sameClass_eq; unfold sameClass; intro v.\n    assert (equiv v v) by reflexivity; firstorder.\n  Qed.\n\n  Lemma EquivalenceClass_forall__eq (C C' : EquivalenceClass equiv) :\n    (forall v, InClass C v <-> InClass C' v) ->\n    C' = C.\n    clear equiv_Equivalence; intro H. apply sameClass_eq; unfold sameClass;\n    firstorder.\n  Qed.\nEnd equiv.\n\nAdd Parametric Relation value equiv : _ (@sameClass value equiv)\n  reflexivity proved by (@sameClass_refl _ _)\n  symmetry proved by (@sameClass_sym _ _)\n  transitivity proved by (@sameClass_trans _ _)\n    as sameClass_mor.\n\nSection InClass_classOf.\n  Variable value : Type.\n  Variable equiv : value -> value -> Prop.\n  Variable C : EquivalenceClass equiv.\n\n  Lemma InClass_classOf_eq eqv v : InClass C v -> C = classOf eqv v.\n    intro H.\n    apply sameClass_eq.\n    pose (classOf eqv v).\n    pose (classOf_refl eqv v).\n    pose (@ClassContainsEquivalent _ equiv).\n    pose (@ClassElementsEquivalent _ equiv).\n    specialize_all_ways.\n    intro; split; intro;\n      eauto.\n  Qed.\n\n  Let C_Equivalence : Equivalence equiv\n    := {| Equivalence_Reflexive := ClassEquivalent_refl C;\n          Equivalence_Symmetric := ClassEquivalent_sym C;\n          Equivalence_Transitive := ClassEquivalent_trans C |}.\n\n  Definition InClass_classOf_eq' : forall v, InClass C v -> C = classOf C_Equivalence v\n    := InClass_classOf_eq C_Equivalence.\nEnd InClass_classOf.\n\nLtac create_classOf_InClass :=\n  repeat match goal with\n           | [ H : InClass (@classOf ?v ?e ?eq ?val) _ |- _ ] => unique_pose (@classOf_refl v e eq val)\n           | [ |- InClass (@classOf ?v ?e ?eq ?val) _ ] => unique_pose (@classOf_refl v e eq val)\n         end.\n\nLtac replace_InClass := create_classOf_InClass;\n  repeat match goal with\n           | [ H : InClass ?C ?x, H' : InClass ?C ?x' |- _ ] => unique_pose (ClassElementsEquivalent C _ H _ H');\n             try (clear H' || clear H) (* try, in case both appear in the conclusion *)\n           | [ H : InClass ?C ?x |- InClass ?C ?x' ] => apply (ClassContainsEquivalent C x H x')\n           | [ |- exists v : ?T, @?G v ] =>\n             match G with\n               | appcontext[InClass ?C ?v] => fail 1 (* [?v] cannot be the same as [v] above, so we fail *)\n               | appcontext[InClass ?C _] => (* match an [InClass] expression that references a variable not scoped outside.\n                                                This is a kludge to get the correct InClass, which matches the [exists]. *)\n                 let v := fresh in let H := fresh in\n                   destruct (ClassInhabited C) as [ v H ]; exists v\n             end\n           | [ |- _ /\\ _ ] => split; intros; create_classOf_InClass\n         end.\n\nLtac InClass2classOf eqv :=\n  repeat match goal with\n           | [ H : InClass ?C ?x |- _ ] =>\n             apply (@InClass_classOf_eq _ _ C eqv _) in H\n         end.\n\nLtac InClass2classOf' :=\n  repeat match goal with\n           | [ H : InClass ?C ?x |- _ ] =>\n             apply (@InClass_classOf_eq' _ _ C _) in H\n         end.\n\nHint Extern 1 (@eq (EquivalenceClass _ _) _ _) => apply EquivalenceClass_forall__eq; replace_InClass.\n\nLtac clear_InClass' :=\n  repeat match goal with\n           | [ |- context[InClass] ] => fail 1\n           | [ H : InClass _ _ |- _ ] => clear H\n         end.\n\nLtac clear_InClass := replace_InClass; clear_InClass'.\n\nSection apply1.\n  Variable value0 : Type.\n  Variable equiv0 : value0 -> value0 -> Prop.\n\n  Variable value' : Type.\n  Variable equiv' : value' -> value' -> Prop.\n\n  Variable f : value0 -> value'.\n  Hypothesis f_mor : forall v v', equiv0 v v' -> equiv' (f v) (f v').\n  Variable E0 : EquivalenceClass equiv0.\n\n  Local Add Parametric Relation : _ equiv0\n    reflexivity proved by (ClassEquivalent_refl E0)\n    symmetry proved by (ClassEquivalent_sym E0)\n    transitivity proved by (ClassEquivalent_trans E0)\n      as apply_equiv_rel.\n\n  Hypothesis equiv'_Equivalence : Equivalence equiv'.\n\n  Local Add Parametric Relation : _ equiv'\n    reflexivity proved by (Equivalence.equiv_reflexive _)\n    symmetry proved by (Equivalence.equiv_symmetric _)\n    transitivity proved by (Equivalence.equiv_transitive _)\n      as apply_equiv'_rel.\n\n  Hint Resolve f_mor.\n\n  Definition apply_to_class : EquivalenceClass equiv'.\n    refine {| InClass := (fun v => exists v0, InClass E0 v0 /\\ equiv' v (f v0)) |};\n    intros;\n    abstract (solve [ reflexivity\n                    | abstract (symmetry; assumption)\n                    | abstract (etransitivity; eauto)\n                    | destruct (ClassInhabited E0) as [ v0 ]; exists (f v0); eexists; split; eauto; apply f_mor; reflexivity\n                    | destruct_hypotheses; repeat esplit; clear_InClass; repeat_subst_mor_of_type value'; try apply f_mor;\n                      solve [ reflexivity\n                            | assumption\n                            | abstract (etransitivity; eauto) ]\n                    ]).\n  Defined.\n\n  Lemma apply_to_class_f_inj : forall v, InClass E0 v -> InClass apply_to_class (f v).\n    compute; firstorder.\n  Qed.\n\n  Lemma apply_to_class_f_surj : forall v, InClass apply_to_class v -> exists v', equiv' v (f v') /\\ InClass E0 v'.\n    compute; firstorder.\n  Qed.\nEnd apply1.\n\nHint Resolve apply_to_class_f_inj.\n\nLemma apply_to_classOf value0 equiv0 equiv0_eqv value' equiv' equiv'_eqv f f_mor e0 :\n  @apply_to_class value0 equiv0 value' equiv' f f_mor\n  (@classOf _ _ equiv0_eqv e0)\n  equiv'_eqv\n  = @classOf _ _ equiv'_eqv (f e0).\nProof.\n  apply EquivalenceClass_forall__eq; intros; split; intros;\n    hnf in *; destruct_hypotheses; replace_InClass; repeat_subst_mor_of_type value'; eauto; reflexivity.\nQed.\n\nSection apply2.\n  Variable value0 : Type.\n  Variable equiv0 : value0 -> value0 -> Prop.\n\n  Variable value1 : Type.\n  Variable equiv1 : value1 -> value1 -> Prop.\n\n  Variable value' : Type.\n  Variable equiv' : value' -> value' -> Prop.\n\n  Hypothesis equiv'_Equivalence : Equivalence equiv'.\n\n  Local Add Parametric Relation : _ equiv'\n    reflexivity proved by (Equivalence.equiv_reflexive _)\n    symmetry proved by (Equivalence.equiv_symmetric _)\n    transitivity proved by (Equivalence.equiv_transitive _)\n      as apply2_equiv'_rel.\n\n  Variable f : value0 -> value1 -> value'.\n  Hypothesis f_mor : forall v0 v0', equiv0 v0 v0' -> forall v1 v1', equiv1 v1 v1' -> equiv' (f v0 v1) (f v0' v1').\n\n  Variable E0 : EquivalenceClass equiv0.\n  Variable E1 : EquivalenceClass equiv1.\n\n  Local Add Parametric Relation : _ equiv0\n    reflexivity proved by (@ClassEquivalent_refl _ _ E0)\n    symmetry proved by (@ClassEquivalent_sym _ _ E0)\n    transitivity proved by (@ClassEquivalent_trans _ _ E0)\n      as apply2_equiv0_rel.\n\n  Local Add Parametric Relation : _ equiv1\n    reflexivity proved by (@ClassEquivalent_refl _ _ E1)\n    symmetry proved by (@ClassEquivalent_sym _ _ E1)\n    transitivity proved by (@ClassEquivalent_trans _ _ E1)\n      as apply2_equiv1_rel.\n\n  Definition apply2_to_class : EquivalenceClass equiv'.\n    refine {| InClass := (fun v => exists v0 v1, InClass E0 v0 /\\ InClass E1 v1 /\\ equiv' v (f v0 v1)) |};\n      abstract (\n        intros;\n          solve [ reflexivity || (symmetry; assumption) || (etransitivity; eauto) ] ||\n            solve [\n              destruct (ClassInhabited E0) as [ v0 ], (ClassInhabited E1) as [ v1 ]; exists (f v0 v1); repeat esplit;\n              eauto; apply f_mor; reflexivity\n            ] ||\n            solve [\n              destruct_hypotheses; repeat esplit; clear_InClass; repeat_subst_mor_of_type value'; try apply f_mor;\n                reflexivity || assumption || etransitivity; eauto\n            ]\n    ).\n  Defined.\n\n  Lemma apply2_to_class_f_inj : forall v0 v1, InClass E0 v0 -> InClass E1 v1 -> InClass apply2_to_class (f v0 v1).\n    compute; firstorder.\n  Qed.\n\n  Lemma apply2_to_class_f_surj : forall v, InClass apply2_to_class v -> exists v0 v1, equiv' v (f v0 v1) /\\ InClass E0 v0 /\\ InClass E1 v1.\n    compute; firstorder.\n  Qed.\nEnd apply2.\n\nHint Resolve apply2_to_class_f_inj.\n\nLemma apply2_to_classOf\n  value0 equiv0 equiv0_eqv\n  value1 equiv1 equiv1_eqv\n  value' equiv' equiv'_eqv\n  f f_mor e0 e1 :\n  @apply2_to_class value0 equiv0 value1 equiv1 value' equiv'\n  equiv'_eqv\n  f f_mor\n  (@classOf _ _ equiv0_eqv e0)\n  (@classOf _ _ equiv1_eqv e1)\n  = @classOf _ _ equiv'_eqv (f e0 e1).\nProof.\n  apply EquivalenceClass_forall__eq; intros; split; intros;\n    hnf in *; destruct_hypotheses;\n      repeat (clear_InClass; eexists; repeat split);\n        clear_InClass;\n        repeat_subst_mor_of_type value';\n        hnf in *;\n          try apply f_mor;\n            eauto; reflexivity || (symmetry; assumption).\nQed.\n\nSection description.\n  (** Can be imported from Coq.Logic.ClassicalDescription,\n      Coq.Logic.ClassicalEpsilon, Coq.Logic.ConstructiveEpsilon,\n      Coq.Logic.Epsilon, Coq.Logic.IndefiniteDescription, or, for the\n      axiom, Coq.Logic.Description *)\n\n  Hypothesis constructive_definite_description :\n    forall (A : Type) (P : A->Prop),\n      (exists! x, P x) -> { x : A | P x }.\n\n  Variable T : Type.\n\n  Definition EquivalenceClass_eq_lift\n  : EquivalenceClass (@eq T) -> T.\n    intro x.\n    cut (exists! u, InClass x u).\n    - apply constructive_definite_description.\n    - destruct (ClassInhabited x) as [u H].\n      exists u.\n      abstract (\n          split; [ exact H\n                 | intros; apply (ClassElementsEquivalent x); assumption ]\n        ).\n  Defined.\n\n  Definition EquivalenceClass_eq_proj\n  : T -> EquivalenceClass (@eq T).\n    apply classOf; abstract typeclasses eauto.\n  Defined.\n\n  Lemma EquivalenceClass_eq_iso1\n  : forall x, EquivalenceClass_eq_lift (EquivalenceClass_eq_proj x) = x.\n    intros.\n    expand.\n    match goal with\n      | [ |- appcontext[match ?E with _ => _ end] ] => case E\n    end.\n    intros; subst; reflexivity.\n  Qed.\n\n  Lemma EquivalenceClass_eq_iso2\n  : forall x, EquivalenceClass_eq_proj (EquivalenceClass_eq_lift x) = x.\n    intros.\n    apply sameClass_eq; simpl.\n    split;\n      intros;\n      simpl in *;\n      subst;\n      hnf;\n      unfold EquivalenceClass_eq_lift;\n      repeat match goal with\n               | [ |- appcontext[match ?E with _ => _ end] ] => case E; simpl; intros\n             end;\n      subst;\n      intuition.\n    apply (ClassElementsEquivalent x); assumption.\n  Qed.\nEnd description.\n", "meta": {"author": "JasonGross", "repo": "ct4s", "sha": "fa17718be5c6f4fe25c447490f929f943a23f2fc", "save_path": "github-repos/coq/JasonGross-ct4s", "path": "github-repos/coq/JasonGross-ct4s/ct4s-fa17718be5c6f4fe25c447490f929f943a23f2fc/EquivalenceClass.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.6789610072611338}}
{"text": "(** * RIS.algebra : algebraic structures. *)\n(* Set Implicit Arguments. *)\n(* Unset Strict Implicit. *)\n(* Unset Printing Implicit Defensive. *)\n\nRequire Import tools.\n\n(** * Definitions *)\nSection algebra.\n  (** Let [A] be some type equipped with an equivalence relation [⩵] and a partial order [≦]. *)\n  Context {A : Type} {eqA: relation A}.\n  Context {equivA : @Equivalence A eqA}.\n\n  Infix \" ⩵ \" := eqA (at level 80).\n\n  (** We introduce some notations. *)\n  Class Un := un : A.\n  Notation \" 𝟭 \" := un.\n\n  Class Zero := zero : A.\n  Notation \" 𝟬 \" := zero.\n  \n  Class Product := prod : A -> A -> A.\n  Infix \" ⋅ \" := prod (at level 40).\n\n  Class ParProduct := par : A -> A -> A.\n  Infix \" ∥ \" := par (at level 42).\n\n  Class Join := join : A -> A -> A.\n  Infix \" ∪ \" := join (at level 45).\n\n  Class Star := star : A -> A.\n  Notation \" e ⋆ \" := (star e) (at level 35).\n\n  (** ** Basic properties *)\n  Class Associative (prod : A -> A -> A) :=\n    associative : (forall a b c : A, prod a (prod b c) ⩵ prod (prod a b) c).\n  Class Commutative (prod : A -> A -> A) :=\n    commutative : (forall a b : A, prod a b ⩵ prod b a).\n  Class Idempotent (prod : A -> A -> A) :=\n    idempotent : (forall a : A, prod a a ⩵ a).\n  Class Unit (prod : A -> A -> A) (unit : A) :=\n    {\n      left_unit : forall a : A, prod unit a ⩵ a;\n      right_unit : forall a : A, prod a unit ⩵ a\n    }.\n  Class Absorbing (prod : A -> A -> A) (z : A) :=\n    {\n      left_absorbing : forall a : A, prod z a ⩵ z;\n      right_absorbing : forall a : A, prod a z ⩵ z\n    }.\n\n  (** ** Basic structures *)\n  Class Monoid (prod : A -> A -> A) (unit : A) :=\n    {\n      mon_congr :> Proper (eqA ==> eqA ==> eqA) prod;\n      mon_assoc :> Associative prod;\n      mon_unit :> Unit prod unit;\n    }.\n\n  Class BiMonoid (prod : A -> A -> A) (par : A -> A -> A) (unit : A) :=\n    {\n      bimon_seq :> Monoid prod unit;\n      bimon_par :> Monoid par unit;\n      bimon_comm :> Commutative par\n    }.\n  \n  Class Semilattice (join : A -> A -> A) :=\n    {\n      lat_congr :> Proper (eqA ==> eqA ==> eqA) join;\n      lat_assoc :> Associative join;\n      lat_comm :> Commutative join;\n      lat_idem :> Idempotent join;\n    }.\n  \n  Class Lattice (m j : A -> A -> A) :=\n    {\n      lat_meet_congr :> Proper (eqA ==> eqA ==> eqA) m;\n      lat_meet_assoc :> Associative m;\n      lat_meet_comm :> Commutative m;\n      lat_join_congr :> Proper (eqA ==> eqA ==> eqA) j;\n      lat_join_assoc :> Associative j;\n      lat_join_comm :> Commutative j;\n      lat_join_meet : forall a b, j a (m a b) ⩵ a;\n      lat_meet_join : forall a b, m a (j a b) ⩵ a;\n    }.\n\n  Class SemiRing (prod add : A -> A -> A) (u z : A) :=\n    {\n      semiring_prod :> Monoid prod u;\n      semiring_add :> Monoid add z;\n      semiring_comm :> Commutative add;\n      semiring_zero :> Absorbing prod z;\n      semiring_left_distr : forall a b c, prod a (add b c) ⩵ add (prod a b) (prod a c);\n      semiring_right_distr : forall a b c, prod (add a b) c ⩵ add (prod a c) (prod b c);\n    }.\n\n  Class BiSemiRing (prod par add : A -> A -> A) (u z : A) :=\n    {\n      bisemiring_bimon :> BiMonoid prod par u;\n      bisemiring_add :> Monoid add z;\n      bisemiring_comm :> Commutative add;\n      bisemiring_zero_seq :> Absorbing prod z;\n      bisemiring_zero_par :> Absorbing par z;\n      bisemiring_left_distr : forall a b c, prod a (add b c) ⩵ add (prod a b) (prod a c);\n      bisemiring_right_distr : forall a b c, prod (add a b) c ⩵ add (prod a c) (prod b c);\n      bisemiring_par_distr : forall a b c, par a (add b c) ⩵ add (par a b) (par a c);\n    }.\n\n  (** ** Join semi-lattices *)\n  Section order.\n    Context {j : Join}.\n    Context {S : Semilattice join}.\n    \n    Definition leqA : relation A := (fun x y => y ⩵ x ∪ y).\n    Infix \" ≦ \" := leqA (at level 80).\n\n    Global Instance preA : PreOrder leqA.\n    Proof.\n      destruct S as [p ass comm id];unfold leqA.\n      split.\n      - intro x;symmetry;apply id.\n      - intros x y z e1 e2.\n        rewrite e2 at 2.\n        rewrite (ass x y z),<- e1.\n        apply e2.\n    Qed.\n\n    Global Instance partialA : PartialOrder eqA leqA.\n    Proof.\n      destruct S as [p ass comm id].\n      intros x y;unfold Basics.flip,leqA;split.\n      - intros E;split.\n        + rewrite E,(id y);reflexivity.\n        + rewrite E;symmetry;apply id.\n      - intros (E1&E2).\n        rewrite E1.\n        rewrite E2 at 1.\n        apply comm.\n    Qed.\n    \n    Lemma refactor e f g h : (e ∪ f) ∪ (g ∪ h) ⩵ (e ∪ g) ∪ (f ∪ h).\n    Proof.\n      rewrite (lat_assoc (e∪f) g h).\n      rewrite <- (lat_assoc e f g).\n      rewrite (@lat_comm _ S f g).\n      rewrite (lat_assoc e g f).\n      rewrite (lat_assoc (e∪g) f h).\n      reflexivity.\n    Qed.\n\n    Global Instance proper_join_inf : Proper (leqA ==> leqA ==> leqA) join.\n    Proof.\n      intros x y I x' y' I';unfold leqA in *.\n      rewrite I,I' at 1;apply refactor.\n    Qed.\n\n    Lemma inf_cup_left a b : a ≦ a ∪ b.\n    Proof. unfold leqA; rewrite (lat_assoc _ _ _),(lat_idem _);reflexivity. Qed.\n\n    Lemma inf_cup_right a b : b ≦ a ∪ b.\n    Proof. rewrite (lat_comm a b);apply inf_cup_left. Qed.\n\n    Lemma inf_join_inf a b c : a ≦ c -> b ≦ c -> a ∪ b ≦ c.\n    Proof. intros;rewrite <- (lat_idem c); apply proper_join_inf;assumption. Qed.\n\n    Context {z : Zero} {u : Unit join zero}.\n  \n    Lemma zero_minimal x : zero ≦ x.\n    Proof. unfold leqA;symmetry ;apply left_unit. Qed.\n\n  End order.\n      \n  Infix \" ≦ \" := leqA (at level 80).\n\n\n  (** ** Kleene algebra and Boolean algebra *)\n  Class KleeneAlgebra (j: Join) (p: Product) (z: Zero) (u:Un) (s:Star) :=\n    {\n      ka_star_congr :> Proper (eqA ==> eqA) star;\n      ka_semiring :> SemiRing prod join un zero;\n      ka_idem :> Idempotent join;\n      ka_star_unfold : forall a, 𝟭 ∪ a ⋅ a ⋆ ≦ a⋆ ;\n      ka_star_left_ind : forall a b, a ⋅ b ≦ b -> a ⋆ ⋅ b ≦ b;\n      ka_star_right_ind : forall a b, a ⋅ b ≦ a -> a ⋅ b ⋆ ≦ a;\n    }.\n\n  Class BiKleeneAlgebra\n        (j: Join) (seq: Product) (par : ParProduct) (z: Zero) (u:Un) (s:Star) :=\n    {\n      bika_star_congr :> Proper (eqA ==> eqA) star;\n      bika_semiring :> BiSemiRing prod par join un zero;\n      bika_idem :> Idempotent join;\n      bika_star_unfold : forall a, 𝟭 ∪ a ⋅ a ⋆ ≦ a⋆ ;\n      bika_star_left_ind : forall a b, a ⋅ b ≦ b -> a ⋆ ⋅ b ≦ b;\n      bika_star_right_ind : forall a b, a ⋅ b ≦ a -> a ⋅ b ⋆ ≦ a;\n    }.\n\n  Class BooleanAlgebra (t f : A) (n : A -> A) (c d: A -> A -> A) :=\n    {\n      proper_c :> Proper (eqA ==> eqA ==> eqA) c;\n      proper_d :> Proper (eqA ==> eqA ==> eqA) d;\n      proper_n :> Proper (eqA ==> eqA) n;\n      ba_conj_comm :> Commutative c;\n      ba_disj_comm :> Commutative d;\n      ba_true : forall a, c a t ⩵ a;\n      ba_false : forall a, d a f ⩵ a;\n      ba_conj_disj : forall x y z, c x (d y z) ⩵ d (c x y) (c x z);\n      ba_disj_conj : forall x y z, d x (c y z) ⩵ c (d x y) (d x z);\n      ba_neg_conj : forall a, c a (n a) ⩵ f;\n      ba_neg_disj : forall a, d a (n a) ⩵ t;\n    }.\n  \nEnd algebra.\nArguments Zero: clear implicits.\nArguments Un: clear implicits.\nArguments Product: clear implicits.\nArguments ParProduct: clear implicits.\nArguments Join: clear implicits.\nArguments Star: clear implicits.\nNotation \" 𝟭 \" := un.\nNotation \" 𝟬 \" := zero.\nInfix \" ⋅ \" := prod (at level 40).\nInfix \" ∥ \" := par (at level 42).\nInfix \" ∪ \" := join (at level 45).\nNotation \" e ⋆ \" := (star e) (at level 35).\n\nClass Box A := box : A -> A.\nNotation \" ▢ \" := box.\n\nArguments Monoid : clear implicits.\nArguments BiMonoid : clear implicits.\nArguments KleeneAlgebra : clear implicits.\nArguments KleeneAlgebra A eqA {j p z u s}.\nArguments SemiRing : clear implicits.\nArguments BiKleeneAlgebra : clear implicits.\nArguments BiKleeneAlgebra A eqA {j seq par z u s}.\nArguments BiSemiRing : clear implicits.\nArguments Semilattice : clear implicits.\nArguments BooleanAlgebra : clear implicits.\nArguments BooleanAlgebra {A} eqA t f n c d.\nArguments leqA : clear implicits.\nArguments leqA {A} eqA {j}.\n\n(** * Facts about boolean algebra *)\nSection booleanAlgebra.\n  Context {A : Type} {eqA: relation A}.\n  Context {equivA : @Equivalence A eqA}.\n\n  Infix \" ⩵ \" := eqA (at level 80).\n  Context {top bot : A} {neg : A -> A} {conj disj : A -> A -> A}.\n  Context `{BooleanAlgebra A eqA top bot neg conj disj}.\n\n  Notation \" ⊤ \" := top.\n  Notation \" ⊥ \" := bot.\n  Notation \" ¬ \" := neg.\n  Infix \" ∧ \" := conj (at level 40).\n  Infix \" ∨ \" := disj (at level 45).\n\n  (** When we defined boolean algebra before, we relied on\n  Huntington's 1904 axiomatization, which differs from the usual way\n  they are defined, but is much more concise. We now show that this\n  axiomatization indeed implies all the properties we expect of a\n  boolean algebra. The following subsection is a straightforward\n  adaptation of the proofs detailed on the wikipedia page of boolean\n  algebra: \n  #<a href=\"https://en.wikipedia.org/wiki/Boolean_algebra_(structure)##Axiomatics\">en.wikipedia.org/wiki/Boolean_algebra_(structure)</a>#.*)\n\n  (** ** Elementary properties *)\n  Lemma UId1 o : (forall x, x ∨ o ⩵ x) -> o ⩵ ⊥.\n  Proof.\n    intros hyp.\n    rewrite <- (ba_false o).\n    rewrite (ba_disj_comm _ _).\n    apply hyp.\n  Qed.\n  \n  Lemma Idm1 x : x ∨ x ⩵ x.\n  Proof.\n    rewrite <- (ba_true (x∨x)),<-(ba_neg_disj x).\n    rewrite <- ba_disj_conj,ba_neg_conj.\n    apply ba_false.\n  Qed.\n\n  Lemma Bnd1 x : x ∨ ⊤ ⩵ ⊤.\n  Proof.\n    rewrite <- (ba_true (x∨⊤)),(ba_conj_comm _ _).\n    rewrite <- (ba_neg_disj x) at 1.\n    rewrite <- ba_disj_conj,ba_true.\n    apply ba_neg_disj.\n  Qed.\n\n  Lemma Abs1 x y : x ∨ (x ∧ y) ⩵ x.\n  Proof.\n    rewrite <- (ba_true x) at 1.\n    rewrite <- ba_conj_disj,(ba_disj_comm _ _),Bnd1.\n    apply ba_true.\n  Qed.\n\n  Lemma UId2 o : (forall x, x ∧ o ⩵ x) -> o ⩵ ⊤.\n  Proof.\n    intros hyp.\n    rewrite <- (ba_true o).\n    rewrite (ba_conj_comm _ _).\n    apply hyp.\n  Qed.\n  \n  Lemma Idm2 x : x ∧ x ⩵ x.\n  Proof.\n    rewrite <- (ba_false (x∧x)),<-(ba_neg_conj x).\n    rewrite <- ba_conj_disj,ba_neg_disj.\n    apply ba_true.\n  Qed.\n\n  Lemma Bnd2 x : x ∧ ⊥ ⩵ ⊥.\n  Proof.\n    rewrite <- (ba_false (x∧⊥)),(ba_disj_comm _ _).\n    rewrite <- (ba_neg_conj x) at 1.\n    rewrite <- ba_conj_disj,ba_false.\n    apply ba_neg_conj.\n  Qed.\n\n  Lemma Abs2 x y : x ∧ (x ∨ y) ⩵ x.\n  Proof.\n    rewrite <- (ba_false x) at 1.\n    rewrite <- ba_disj_conj,(ba_conj_comm _ _),Bnd2.\n    apply ba_false.\n  Qed.\n  \n  Lemma UNg x x' : x ∨ x' ⩵ ⊤ -> x ∧ x' ⩵ ⊥ -> x' ⩵ ¬ x.\n  Proof.\n    intros h1 h2.\n    rewrite <- (ba_true x'),<-(ba_neg_disj x),ba_conj_disj,(ba_conj_comm x' _),(ba_conj_comm x' _).\n    rewrite h2.\n    rewrite <- (ba_neg_conj x),(ba_conj_comm _ _),<-ba_conj_disj.\n    rewrite h1.\n    apply ba_true.\n  Qed.\n\n  Lemma DNg x : ¬(¬ x) ⩵ x.\n  Proof.\n    symmetry;apply UNg.\n    - rewrite (ba_disj_comm _ _);apply ba_neg_disj.\n    - rewrite (ba_conj_comm _ _);apply ba_neg_conj.\n  Qed.\n\n  Lemma A1 x y : x ∨ (¬ x ∨ y) ⩵ ⊤.\n  Proof.\n    rewrite <- (ba_true (x∨_)),(ba_conj_comm _ _),<-(ba_neg_disj x).\n    rewrite <- ba_disj_conj.\n    rewrite Abs2;reflexivity.\n  Qed.\n\n  Lemma A2 x y : x ∧ (¬ x ∧ y) ⩵ ⊥.\n  Proof.\n    rewrite <- (ba_false (x∧_)),(ba_disj_comm _ _),<-(ba_neg_conj x).\n    rewrite <- ba_conj_disj.\n    rewrite Abs1;reflexivity.\n  Qed.\n\n  Lemma B1 x y : (x ∨ y)∨(¬x∧¬y)⩵⊤.\n  Proof.\n    rewrite ba_disj_conj.\n    rewrite (ba_disj_comm _ (¬x)), (ba_disj_comm _ (¬y)).\n    rewrite (ba_disj_comm x y) at 2.\n    rewrite <- (DNg x) at 2.\n    rewrite <- (DNg y) at 3.\n    repeat rewrite A1.\n    apply ba_true.\n  Qed.\n    \n  Lemma B2 x y : (x ∧ y)∧(¬x∨¬y)⩵⊥.\n  Proof.\n    rewrite ba_conj_disj.\n    rewrite (ba_conj_comm _ (¬x)), (ba_conj_comm _ (¬y)).\n    rewrite (ba_conj_comm x y) at 2.\n    rewrite <- (DNg x) at 2.\n    rewrite <- (DNg y) at 3.\n    repeat rewrite A2.\n    apply ba_false.\n  Qed.\n\n  Lemma C1 x y : (x ∨ y)∧ (¬x∧¬y)⩵⊥.\n  Proof.\n    rewrite (ba_conj_comm (x∨_) _),ba_conj_disj.\n    rewrite (ba_conj_comm _ x),(ba_conj_comm _ y).\n    rewrite (ba_conj_comm _ (¬y)) at 2.\n    repeat rewrite A2.\n    apply ba_false.\n  Qed.\n\n  Lemma C2 x y : (x ∧ y)∨ (¬x∨¬y)⩵⊤.\n  Proof.\n    rewrite (ba_disj_comm (x∧_) _),ba_disj_conj.\n    rewrite (ba_disj_comm _ x),(ba_disj_comm _ y).\n    rewrite (ba_disj_comm _ (¬y)) at 2.\n    repeat rewrite A1.\n    apply ba_true.\n  Qed.\n\n  Lemma DMg1 x y : ¬ (x∨y) ⩵ ¬ x ∧ ¬ y.\n  Proof.\n    symmetry;apply UNg.\n    - apply B1.\n    - apply C1.\n  Qed.\n\n  Lemma DMg2 x y : ¬ (x∧y) ⩵ ¬ x ∨ ¬ y.\n  Proof.\n    symmetry;apply UNg.\n    - apply C2.\n    - apply B2.\n  Qed.\n\n  Lemma D1 x y z : (x∨(y∨z))∨¬x⩵⊤.\n  Proof.\n    rewrite (ba_disj_comm _ (¬x)).\n    rewrite <- (DNg x) at 2.\n    apply A1.\n  Qed.\n\n  Lemma D2 x y z : (x∧(y∧z))∧¬x⩵⊥.\n  Proof.\n    rewrite (ba_conj_comm _ (¬x)).\n    rewrite <- (DNg x) at 2.\n    apply A2.\n  Qed.\n\n  Lemma E1 x y z : y∧(x∨(y∨z))⩵ y.\n  Proof.\n    rewrite ba_conj_disj,Abs2,(ba_disj_comm _).\n    apply Abs1.\n  Qed.\n\n  Lemma E2 x y z : y∨(x∧(y∧z))⩵ y.\n  Proof.\n    rewrite ba_disj_conj,Abs1,(ba_conj_comm _).\n    apply Abs2.\n  Qed.\n\n  Lemma F1 x y z : (x∨(y∨z))∨¬y ⩵ ⊤.\n  Proof.\n    rewrite (ba_disj_comm _ (¬ _)).\n    rewrite <- ba_true,(ba_conj_comm _ _),<-(ba_neg_disj y) at 1.\n    rewrite (ba_disj_comm y),<-ba_disj_conj,E1,(ba_disj_comm _ y).\n    apply ba_neg_disj.\n  Qed.\n\n  Lemma F2 x y z : (x∧(y∧z))∧¬y ⩵ ⊥.\n  Proof.\n    rewrite (ba_conj_comm _ (¬ _)).\n    rewrite <- ba_false,(ba_disj_comm _ _),<-(ba_neg_conj y) at 1.\n    rewrite (ba_conj_comm y),<-ba_conj_disj,E2,(ba_conj_comm _ y).\n    apply ba_neg_conj.\n  Qed.\n\n  Lemma G1 x y z : (x ∨(y∨z))∨¬z⩵⊤.\n  Proof. rewrite (ba_disj_comm y z);apply F1. Qed.\n\n  Lemma G2 x y z : (x ∧(y∧z))∧¬z⩵⊥.\n  Proof. rewrite (ba_conj_comm y z);apply F2. Qed.\n\n  Lemma H1 x y z : ¬ ((x∨y)∨z)∧x⩵⊥.\n  Proof.\n    rewrite DMg1,DMg1.\n    rewrite (ba_conj_comm _).\n    rewrite <- ba_false,(ba_disj_comm _).\n    rewrite <- (ba_neg_conj x) at 1.\n    rewrite <- ba_conj_disj,(ba_conj_comm _ (¬z)),E2.\n    apply ba_neg_conj.\n  Qed.\n\n  Lemma H2 x y z : ¬ ((x∧y)∧z)∨x⩵⊤.\n  Proof.\n    rewrite DMg2,DMg2.\n    rewrite (ba_disj_comm _).\n    rewrite <- ba_true,(ba_conj_comm _).\n    rewrite <- (ba_neg_disj x) at 1.\n    rewrite <- ba_disj_conj,(ba_disj_comm _ (¬z)),E1.\n    apply ba_neg_disj.\n  Qed.\n\n  Lemma I1 x y z : ¬ ((x∨y)∨z)∧y⩵⊥.\n  Proof. rewrite (ba_disj_comm x y);apply H1. Qed.\n\n  Lemma I2 x y z : ¬ ((x∧y)∧z)∨y⩵⊤.\n  Proof. rewrite (ba_conj_comm x y);apply H2. Qed.\n\n  Lemma J1 x y z : ¬((x∨y)∨z)∧z⩵⊥.\n  Proof. rewrite DMg1,(ba_conj_comm _),(ba_conj_comm (¬ _));apply A2. Qed.\n\n  Lemma J2 x y z : ¬((x∧y)∧z)∨z⩵⊤.\n  Proof. rewrite DMg2,(ba_disj_comm _),(ba_disj_comm (¬ _));apply A1. Qed.\n\n  Lemma K1 x y z : (x∨(y∨z))∨¬((x∨y)∨z)⩵⊤.\n  Proof.\n    repeat rewrite DMg1.\n    repeat rewrite ba_disj_conj.\n    rewrite D1,F1,G1.\n    repeat rewrite ba_true;reflexivity.\n  Qed.\n  \n  Lemma K2 x y z : (x∧(y∧z))∧¬((x∧y)∧z)⩵⊥.\n  Proof.\n    repeat rewrite DMg2.\n    repeat rewrite ba_conj_disj.\n    rewrite D2,F2,G2.\n    repeat rewrite ba_false;reflexivity.\n  Qed.\n  \n  Lemma L1 x y z : (x∨(y∨z))∧¬((x∨y)∨z) ⩵ ⊥.\n  Proof.\n    rewrite (ba_conj_comm _).\n    repeat rewrite ba_conj_disj.\n    rewrite H1,I1,J1.\n    repeat rewrite ba_false;reflexivity.\n  Qed.\n  \n  Lemma L2 x y z : (x∧(y∧z))∨¬((x∧y)∧z) ⩵ ⊤.\n  Proof.\n    rewrite (ba_disj_comm _).\n    repeat rewrite ba_disj_conj.\n    rewrite H2,I2,J2.\n    repeat rewrite ba_true;reflexivity.\n  Qed.\n\n  Lemma Ass1 x y z : x∨(y∨z)⩵(x∨y)∨z.\n  Proof.\n    rewrite <- (DNg ((x∨y)∨z));apply UNg.\n    - rewrite (ba_disj_comm _);apply K1.\n    - rewrite (ba_conj_comm _);apply L1.\n  Qed.\n\n  Lemma Ass2 x y z : x∧(y∧z)⩵(x∧y)∧z.\n  Proof.\n    rewrite <- (DNg ((x∧y)∧z));apply UNg.\n    - rewrite (ba_disj_comm _);apply L2.\n    - rewrite (ba_conj_comm _);apply K2.\n  Qed.\n\n  (** ** Boolean algebra as other structures*)\n  Global Instance BooleanAlgebra_Join_Lattice : @Lattice A eqA conj disj.\n  Proof.\n    split.\n    - apply H.\n    - intros x y z;apply Ass2.\n    - apply ba_conj_comm.\n    - apply H.\n    - intros x y z;apply Ass1.\n    - apply ba_disj_comm.\n    - apply Abs1.\n    - apply Abs2.\n  Qed.\n  \n  Global Instance BooleanAlgebra_Join_Semilattice : Semilattice A eqA disj.\n  Proof.\n    split.\n    - apply H.\n    - apply lat_join_assoc.\n    - apply lat_join_comm.\n    - intros a;apply Idm1.\n  Qed.\n\n  Global Instance BooleanAlgebra_Meet_Semilattice : Semilattice A eqA conj.\n  Proof.\n    split.\n    - apply H.\n    - apply lat_meet_assoc.\n    - apply lat_meet_comm.\n    - intros a;apply Idm2.\n  Qed.\n\n  Global Instance BooleanAlgebra_Meet_Monoid : @Monoid A eqA conj top.\n  Proof.\n    split.\n    - apply H.\n    - apply lat_meet_assoc.\n    - split.\n      + intro a;etransitivity;[apply lat_meet_comm|apply ba_true].\n      + apply ba_true.\n  Qed.\n\n  Global Instance BooleanAlgebra_Join_Monoid : @Monoid A eqA disj bot.\n  Proof.\n    split.\n    - apply H.\n    - apply lat_join_assoc.\n    - split.\n      + intro a;etransitivity;[apply lat_join_comm|apply ba_false].\n      + apply ba_false.\n  Qed.\n\n  Global Instance BooleanAlgebra_Semiring : SemiRing A eqA conj disj top bot.\n  Proof.\n    split.\n    - eapply BooleanAlgebra_Meet_Monoid;eassumption.\n    - eapply BooleanAlgebra_Join_Monoid;eassumption.\n    - apply lat_join_comm.\n    - split.\n      + intros a;rewrite (ba_conj_comm _);apply Bnd2.\n      + intros a;apply Bnd2.\n    - apply ba_conj_disj.\n    - intros x y z;rewrite (ba_conj_comm _),ba_conj_disj.\n      repeat rewrite (ba_conj_comm z);reflexivity.\n  Qed.\n\nEnd booleanAlgebra.\n(** * Sums *)\nSection sums.\n  Context {A : Type} {eqA: relation A}.\n  Context {equivA : @Equivalence A eqA}.\n  \n  Infix \" ⩵ \" := eqA (at level 80).\n  \n  Context {j: Join A}{z: Zero A}.\n  Context {j_mon : Monoid A eqA join zero}.\n  Context {j_comm : @Commutative A eqA join}.\n  Context {j_idem : @Idempotent A eqA join}.\n\n  Infix \" ≦ \" := (leqA eqA) (at level 80).\n  Instance semi_lat : Semilattice A eqA join.\n  Proof.\n    split;auto.\n    - apply mon_congr.\n    - apply mon_assoc.\n  Qed.\n  \n  Definition Σ l := fold_right (fun e f => join e f) zero l.\n\n  Lemma Σ_app L M : Σ L ∪ Σ M ⩵ Σ (L++M).\n  Proof.\n    induction L;simpl;[|rewrite <- IHL].\n    - apply left_unit.\n    - symmetry;apply mon_assoc.\n  Qed.\n      \n  Lemma Σ_incl L M : L ⊆ M -> Σ L ≦ Σ M.\n  Proof.\n    intro I;unfold leqA;rewrite Σ_app;revert M I;induction L;intros M I.\n    - reflexivity.\n    - simpl;rewrite <- IHL by (rewrite <- I;intro;simpl;tauto).\n      assert (Ia : a ∈ M) by (apply I;now left).\n      clear I L IHL.\n      induction M as [|e L].\n      + simpl in *;tauto.\n      + simpl;destruct Ia as [->|Ia];simpl.\n        * rewrite (mon_assoc _ _ _),(j_idem _);reflexivity.\n        * rewrite IHL at 1 by assumption.\n          rewrite (mon_assoc _ _ _),(j_comm e a),(mon_assoc _ _ _);reflexivity.\n  Qed.  \n  \n  Global Instance Σ_equivalent : Proper (@equivalent _ ==> eqA) Σ.\n  Proof.\n    intros l1 l2 E.\n    apply antisymmetry;apply Σ_incl;rewrite E;reflexivity.\n  Qed.\n\n  Lemma Σ_bigger e L : e ∈ L -> e ≦ Σ L.\n  Proof.\n     intro I;transitivity (Σ [e]).\n     - simpl;apply inf_cup_left.\n     - apply Σ_incl;intros ? [<-|F];simpl in *;tauto.\n  Qed.\n  \n  Lemma Σ_bounded e L : (forall f, f ∈ L -> f ≦ e) <-> Σ L ≦ e.\n  Proof.\n    split.\n    - induction L;simpl;intro I.\n      + apply zero_minimal.\n      + rewrite IHL by (intros ? ?;apply I;now right).\n        rewrite (I a) by now left.\n        rewrite (j_idem e);reflexivity.\n    - intros E f If.\n      rewrite <- E;apply Σ_bigger,If.\n  Qed.\nEnd sums.\n\n(** * Products *)\nSection prods.\n  Context {A : Type} {eqA: relation A}.\n  Context {equivA : @Equivalence A eqA}.\n  \n  Infix \" ⩵ \" := eqA (at level 80).\n  \n  Context {m : Product A}{u: Un A}.\n  Context {j_mon : Monoid A eqA prod un}.\n\n  Definition Π l := fold_right (fun e f => e ⋅ f) 𝟭 l.\n\n  Lemma Π_app L M : Π L ⋅ Π M ⩵ Π (L++M).\n  Proof.\n    induction L;simpl;[|rewrite <- IHL].\n    - apply left_unit.\n    - symmetry;apply mon_assoc.\n  Qed.\n\n  Fixpoint Power (β : A) n :=\n    match n with\n    | 0 => 𝟭\n    | S n => β ⋅ Power β n\n    end.\n  Infix \" ^ \" := Power.\n\n  Global Instance Power_proper :\n    Proper (eqA ==> eq ==> eqA) Power.\n  Proof.\n    intros a b E n _ <-;induction n;simpl.\n    - reflexivity.\n    - rewrite IHn,E;reflexivity.\n  Qed.\n\n  Lemma Power_last a n : a ^ (S n) ⩵ a ^ n ⋅ a.\n  Proof.\n    induction n;simpl.\n    - rewrite left_unit,right_unit;reflexivity.\n    - rewrite IHn,(mon_assoc _),IHn;reflexivity.\n  Qed.\n\n  Lemma Power_add a x y : a ^ (x + y) ⩵ a ^ x ⋅ a ^ y.\n  Proof.\n    induction x;simpl.\n    - rewrite left_unit;reflexivity.\n    - rewrite IHx;apply mon_assoc.\n  Qed.\nEnd prods.\nInfix \" ^ \" := Power.\n\n(** * Parallel Products *)\nSection parprods.\n  Context {A : Type} {eqA: relation A}.\n  Context {equivA : @Equivalence A eqA}.\n  \n  Infix \" ⩵ \" := eqA (at level 80).\n  \n  Context {m : ParProduct A}{u: Un A}.\n  Context {j_mon : Monoid A eqA par un}.\n\n  Definition ParΠ l := fold_right (fun e f => e ∥ f) 𝟭 l.\n  Notation \" ! \" := ParΠ.\n\n  Lemma ParΠ_app L M : ! L ∥ ! M ⩵ ! (L++M).\n  Proof.\n    induction L;simpl;[|rewrite <- IHL].\n    - apply left_unit.\n    - symmetry;apply mon_assoc.\n  Qed.\n      \nEnd parprods.\nNotation \" ! \" := ParΠ.\n\nSection idempotent_semirings.\n  Context {A : Type} {eqA: relation A}.\n  Context {equivA : @Equivalence A eqA}.\n  \n  Infix \" ⩵ \" := eqA (at level 80).\n  \n  Context {j: Join A}{p: Product A}{z: Zero A}{u:Un A}.\n  Context {sr: SemiRing A eqA prod join un zero}.\n  Context {idj: @Idempotent A eqA join}.\n\n  Infix \" ≦ \" := (leqA eqA) (at level 80).\n  \n  Global Instance proper_prod_inf : Proper (leqA eqA ==> leqA eqA ==> leqA eqA) prod.\n  Proof.\n    intros e f I e' f' I'.\n    unfold leqA in *.\n    rewrite I' at 1.\n    rewrite semiring_left_distr.\n    rewrite I at 1.\n    rewrite semiring_right_distr.\n    rewrite <- (mon_assoc _ _ _).\n    rewrite <- semiring_left_distr.\n    rewrite <- I'.\n    reflexivity.\n  Qed.\n  \n  Instance join_semilattice : Semilattice A eqA join.\n  Proof. split;apply sr||apply idj. Qed.\n  \n  Lemma Σ_distr_l e L : e ⋅ Σ L ⩵ Σ (map (prod e) L).\n  Proof.\n    induction L;simpl.\n    - apply right_absorbing.\n    - rewrite <- IHL,semiring_left_distr;reflexivity.\n  Qed.\n  \n  Lemma Σ_distr_r e L : Σ L ⋅ e ⩵ Σ (map (fun f => f ⋅ e) L).\n  Proof.\n    induction L;simpl.\n    - apply left_absorbing.\n    - rewrite <- IHL,semiring_right_distr;reflexivity.\n  Qed.\n\nEnd idempotent_semirings.\n\n\n(** * Kleene algebras *)\nSection ka_facts.\n  Context {A : Type} {eqA: relation A}.\n  Context {equivA : @Equivalence A eqA}.\n  \n  Infix \" ⩵ \" := eqA (at level 80).\n  \n  Context {j: Join A}{p: Product A}{z: Zero A}{u:Un A}{s:Star A}.\n  Context {ka: KleeneAlgebra A eqA}.\n\n  Infix \" ≦ \" := (leqA eqA) (at level 80).\n\n  Global Instance ka_join_semilattice : Semilattice A eqA join:= join_semilattice.\n  \n  Lemma ka_star_unfold_eq a : a⋆ ⩵ 𝟭 ∪ a ⋅ a ⋆.\n  Proof.\n    apply antisymmetry.\n    - etransitivity;[|apply ka_star_left_ind with (a0:=a)].\n      + rewrite (semiring_left_distr _ _ _). \n        rewrite right_unit. \n        apply inf_cup_left.\n      + rewrite (semiring_left_distr _ _ _).\n        rewrite right_unit.\n        apply inf_join_inf.\n        * rewrite <- inf_cup_right.\n          rewrite <- ka_star_unfold.\n          rewrite (semiring_left_distr _ _ _).\n          rewrite <- inf_cup_left.\n          rewrite right_unit.\n          reflexivity.\n        * rewrite <- ka_star_unfold at 2.\n          rewrite <- inf_cup_right.\n          rewrite (semiring_left_distr _ _ _).\n          rewrite <- inf_cup_right.\n          reflexivity.\n    - apply ka_star_unfold.\n  Qed.\n  \n  Lemma ka_star_dup a : a ⋆ ⋅ a ⋆ ⩵ a ⋆.\n  Proof.\n    apply antisymmetry.\n    - apply ka_star_left_ind.\n      rewrite ka_star_unfold_eq at 2.\n      apply inf_cup_right.\n    - rewrite ka_star_unfold_eq at 1.\n      apply inf_join_inf.\n      + rewrite ka_star_unfold_eq.\n        rewrite (semiring_left_distr _ _ _).\n        rewrite (semiring_right_distr _ _ _).\n        rewrite <- inf_cup_left.\n        rewrite <- inf_cup_left.\n        rewrite left_unit.\n        reflexivity.\n      + apply proper_prod_inf;[|reflexivity].\n        rewrite ka_star_unfold_eq.\n        rewrite <- inf_cup_right.\n        rewrite ka_star_unfold_eq.\n        rewrite (semiring_left_distr _ _ _).\n        rewrite <- inf_cup_left.\n        rewrite right_unit.\n        reflexivity.\n  Qed.\n\n  Lemma one_inf_star e : 𝟭 ≦ e⋆.\n  Proof. rewrite ka_star_unfold_eq;apply inf_cup_left. Qed.\n\n  Lemma star_incr e : e ≦ e⋆.\n  Proof. rewrite ka_star_unfold_eq, <- one_inf_star,right_unit;apply inf_cup_right. Qed.\n    \n  Global Instance proper_star_inf : Proper (leqA eqA ==> leqA eqA) star.\n  Proof.\n    intros e f I.\n    transitivity (e⋆⋅𝟭);[rewrite right_unit;reflexivity|].\n    rewrite (one_inf_star f).\n    apply ka_star_left_ind.\n    rewrite I,(star_incr f),ka_star_dup at 1;reflexivity.\n  Qed.\n  \n  Lemma ka_star_star a : a⋆ ⩵ (a ⋆)⋆.\n  Proof.\n    apply antisymmetry.\n    - apply proper_star_inf.\n      rewrite ka_star_unfold_eq.\n      rewrite <- inf_cup_right.\n      rewrite ka_star_unfold_eq.\n      rewrite (semiring_left_distr _ _ _).\n      rewrite right_unit.\n      apply inf_cup_left.\n    - rewrite ka_star_unfold_eq at 1.\n      apply inf_join_inf.\n      + rewrite ka_star_unfold_eq.\n        apply inf_cup_left.\n      + apply ka_star_right_ind.\n        rewrite ka_star_dup.\n        reflexivity.\n  Qed.        \n  \n  Lemma ka_star_unfold_right a : 𝟭 ∪ a⋆ ⋅ a ≦ a⋆.\n  Proof.\n    apply inf_join_inf.\n    - rewrite ka_star_unfold_eq.\n      apply inf_cup_left.\n    - rewrite <- ka_star_dup at 2.\n      apply proper_prod_inf.\n      + reflexivity.\n      + rewrite ka_star_unfold_eq,ka_star_unfold_eq.\n        rewrite semiring_left_distr,right_unit.\n        rewrite <- inf_cup_right.\n        apply inf_cup_left.\n  Qed.\n\n  Lemma star_join e f : (e ∪ f)⋆ ⩵ e ⋆ ∪ f⋆⋅(e⋅f⋆)⋆.\n  Proof.\n    apply antisymmetry.\n    - transitivity ((e ∪ f) ⋆ ⋅ un);[rewrite right_unit;reflexivity|].\n      transitivity ((e ∪ f) ⋆ ⋅ (e ⋆ ∪ f ⋆ ⋅ (e ⋅ f ⋆) ⋆)).\n      + apply proper_prod_inf;[reflexivity|].\n        etransitivity;[|apply inf_cup_left].\n        apply one_inf_star.\n      + apply ka_star_left_ind.\n        rewrite semiring_left_distr.\n        repeat rewrite semiring_right_distr.\n        repeat apply inf_join_inf.\n        * etransitivity;[|apply inf_cup_left].\n          rewrite (star_incr e) at 1.\n          rewrite ka_star_dup;reflexivity.\n        * etransitivity;[|apply inf_cup_right].\n          apply proper_prod_inf;[apply star_incr|].\n          rewrite <- (one_inf_star f),right_unit;reflexivity.\n        * etransitivity;[|apply inf_cup_right].\n          rewrite <- (one_inf_star f) at 3;rewrite left_unit.\n          rewrite <- (ka_star_dup (e⋅f⋆)) at 2.\n          rewrite <- (star_incr (e⋅f⋆)) at 2.\n          rewrite (mon_assoc _ _ _).\n          reflexivity.\n        * etransitivity;[|apply inf_cup_right].\n          rewrite (mon_assoc _ _ _).\n          apply proper_prod_inf;[|reflexivity].\n          rewrite (star_incr f) at 1;rewrite ka_star_dup;reflexivity.\n    - apply inf_join_inf.\n      + apply proper_star_inf,inf_cup_left.\n      + rewrite <- (ka_star_dup (e∪f)).\n        apply proper_prod_inf;[apply proper_star_inf,inf_cup_right|].\n        rewrite (ka_star_star (e∪f)).\n        apply proper_star_inf.\n        rewrite <- (ka_star_dup (e∪f)).\n        apply proper_prod_inf;[|apply proper_star_inf,inf_cup_right].\n        rewrite <- star_incr;apply inf_cup_left.\n  Qed.    \n\n  Lemma un_star : un⋆ ⩵ un.\n  Proof.\n    apply antisymmetry.\n    - transitivity (un⋆⋅un);[rewrite right_unit;reflexivity|].\n      apply ka_star_left_ind;rewrite left_unit;reflexivity.\n    - apply star_incr.\n  Qed.\n\n  Lemma star_switch_side e : e⋆⋅e ⩵ e⋅ e⋆.\n  Proof.\n    apply antisymmetry.\n    - transitivity (e⋆⋅e⋅e⋆).\n      + rewrite <- one_inf_star at 3.\n        rewrite right_unit;reflexivity.\n      + rewrite <- (mon_assoc _ _ _).\n        apply ka_star_left_ind.\n        rewrite (star_incr e) at 2.\n        rewrite ka_star_dup;reflexivity.\n    - transitivity (e⋆⋅e⋅e⋆).\n      + rewrite <- one_inf_star at 2.\n        rewrite left_unit;reflexivity.\n      + apply ka_star_right_ind.\n        rewrite (star_incr e) at 2.\n        rewrite ka_star_dup;reflexivity.\n  Qed.\n\n  Lemma ka_star_mid_split e : e⋆⋅e⋅e⋆ ≦ e⋆.\n  Proof.\n    etransitivity;[apply proper_prod_inf;[apply proper_prod_inf;\n                                          [reflexivity|apply star_incr]|reflexivity]|].\n    cut ((e ⋆ ⋅ e ⋆) ⋅ e ⋆ ⩵ e ⋆);[intros ->;reflexivity|].\n    repeat rewrite ka_star_dup;reflexivity.\n  Qed.\n\n  Lemma ka_zero_star :  𝟬 ⋆ ⩵ 𝟭.\n  Proof.\n    apply antisymmetry.\n    - transitivity (𝟬 ⋆ ⋅ 𝟭).\n      + rewrite right_unit;reflexivity.\n      + apply ka_star_left_ind.\n        rewrite left_absorbing;apply zero_minimal.\n    - apply one_inf_star.\n  Qed.\n\nEnd ka_facts.\n\nSection bisemiring_is_semiring.\n  Context {A} {eqA: relation A}.\n  Context {equivA : @Equivalence A eqA}.\n  Context {s p j : A -> A -> A} {u z : A}.\n  Context {bsr : BiSemiRing A eqA s p j u z}.\n  Lemma bisemiring_is_semiring : SemiRing A eqA s j u z.\n  Proof.\n    split.\n    - apply bimon_seq.\n    - apply bisemiring_add.\n    - apply bisemiring_comm.\n    - apply bisemiring_zero_seq.\n    - apply bisemiring_left_distr.\n    - apply bisemiring_right_distr.\n  Qed.\n  Lemma bisemiring_is_semiring_par : SemiRing A eqA p j u z.\n  Proof.\n    split.\n    - apply bimon_par.\n    - apply bisemiring_add.\n    - apply bisemiring_comm.\n    - apply bisemiring_zero_par.\n    - apply bisemiring_par_distr.\n    - intros.\n      rewrite (bimon_comm (j a b)),bisemiring_par_distr.\n      rewrite (bimon_comm c a), (bimon_comm c b).\n      reflexivity.\n  Qed.\nEnd bisemiring_is_semiring.\n\nSection bika_is_ka.\n  Context {A} {eqA: relation A}.\n  Context {equivA : @Equivalence A eqA}.\n  Context `{BiKleeneAlgebra A eqA}.\n  Lemma bika_is_ka : KleeneAlgebra A eqA.\n  Proof.\n    split.\n    - apply bika_star_congr.\n    - eapply bisemiring_is_semiring.\n      Unshelve.\n      + exact par.\n      + exact bika_semiring.\n    - apply bika_idem.\n    - apply H.\n    - apply H.\n    - apply H.\n  Qed.\nEnd bika_is_ka.\n\nSection powerset_biKA.\n  Context {A} {eqA: relation A}.\n  Context {equivA : @Equivalence A eqA}.\n  \n  Infix \" ⩵ \" := eqA (at level 80).\n  \n  Context `{Product A}`{ParProduct A}`{Un A}.\n  Context {bimon: BiMonoid A eqA prod par un}.\n\n  Definition SetBiKA := {f : A -> Prop | Proper (eqA ==> iff) f}.\n\n  Definition member u (a : SetBiKA) := (proj1_sig a u).\n  Infix \" ∊ \" := member (at level 80).\n\n  Global Instance SetBiKA_eq : SemEquiv SetBiKA :=\n    fun a b => forall u, u ∊ a <-> u ∊ b.\n  Global Instance SetBiKA_inf : SemSmaller SetBiKA :=\n    fun a b => forall u, u ∊ a -> u ∊ b.\n\n  Global Instance member_Proper : Proper (eqA ==> sequiv ==> iff) member.\n  Proof.\n    intros u v E a b E'.\n    transitivity (v ∊ a).\n    - apply (proj2_sig a),E.\n    - apply E'.\n  Qed.\n  \n  Global Instance SetBiKA_eq_equiv : Equivalence sequiv.\n  Proof.\n    split.\n    - intros (a,?) w;tauto.\n    - intros (a,?) (b,?) E w;symmetry;apply E.\n    - intros (a,?) (b,?) (c,?) E1 E2 w;rewrite (E1 _),(E2 _);reflexivity.\n  Qed.\n\n  Global Instance SetBiKA_inf_preorder : PreOrder ssmaller.\n  Proof.\n    split.\n    - intros a w;tauto.\n    - intros a b c E1 E2 w h;apply (E2 _),(E1 _),h.\n  Qed.\n  Global Instance SetBiKA_inf_partialorder : PartialOrder sequiv ssmaller.\n  Proof.\n    intros a b;unfold Basics.flip;split.\n    - intros E;split;intros w h;apply E,h.\n    - intros (h1&h2) w;split;[apply h1|apply h2].\n  Qed.\n\n  Lemma prod_internal (a b: SetBiKA) :\n    Proper (eqA ==> iff) (fun w => exists u1 u2, w ⩵ u1 ⋅ u2 /\\ u1 ∊ a /\\ u2 ∊ b).\n  Proof.\n    intros u1 u2 E;split;intros (v1&v2&E'&I1&I2);exists v1,v2;repeat split;auto.\n    - rewrite <-E;auto.\n    - rewrite E;auto.\n  Qed.\n  Lemma par_internal (a b: SetBiKA) :\n    Proper (eqA ==> iff) (fun w => exists u1 u2, w ⩵ u1 ∥ u2 /\\ u1 ∊ a /\\ u2 ∊ b).\n  Proof.\n    intros u1 u2 E;split;intros (v1&v2&E'&I1&I2);exists v1,v2;repeat split;auto.\n    - rewrite <-E;auto.\n    - rewrite E;auto.\n  Qed.\n  Lemma join_internal (a b: SetBiKA) :\n    Proper (eqA ==> iff) (fun w => w ∊ a \\/ w ∊ b).\n  Proof.\n    intros u v E.\n    destruct a as (a&Pa),b as (b&Pb);simpl.\n    rewrite (Pa _ _ E),(Pb _ _ E);reflexivity.\n  Qed.\n  Lemma un_internal : Proper (eqA ==> iff) (fun w => w ⩵ 𝟭).\n  Proof. intros u v E;rewrite E;reflexivity. Qed.\n    \n  Lemma zero_internal : Proper (eqA ==> iff) (fun _ => False).\n  Proof. intros ? ? ?;reflexivity. Qed.\n  \n  Global Instance SetBiKAProd : Product SetBiKA :=\n    fun a b =>\n      exist _ (fun w => exists u1 u2, w ⩵ u1 ⋅ u2 /\\ u1 ∊ a /\\ u2 ∊ b)\n            (prod_internal a b).\n\n  Global Instance SetBiKAPar : ParProduct SetBiKA :=\n    fun a b =>\n      exist _ (fun w => exists u1 u2, w ⩵ u1 ∥ u2 /\\ u1 ∊ a /\\ u2 ∊ b)\n            (par_internal a b).\n  \n  Global Instance SetBiKAJoin : Join SetBiKA :=\n    fun a b => exist _ (fun u => u ∊ a \\/ u ∊ b) (join_internal a b).\n  Global Instance SetBiKAUn : Un SetBiKA :=\n    exist _ (fun u => u ⩵ 𝟭) un_internal.\n  Global Instance SetBiKAZero : Zero SetBiKA :=\n    exist _ (fun _ => False) zero_internal.\n  \n  \n  Lemma star_internal a : Proper (eqA ==> iff) (fun u => exists n, u ∊ (a ^ n)).\n  Proof. intros u1 u2 E;split;intros (n&I);exists n;apply (proj2_sig (a^n) _ _ E),I. Qed.\n\n  Global Instance SetBiKAStar : Star SetBiKA :=\n    fun a => exist _ (fun u => exists n, u ∊ (a ^ n)) (star_internal a).\n\n  Global Instance SetBiKA_bisemiring : BiSemiRing SetBiKA sequiv prod par join un zero.\n  Proof.\n    split.\n    - split.\n      + split.\n        * intros (a,?) (b,?) E (a',?) (b',?) E' w;split.\n          -- intros (u1&u2&Eu&E1&E2);exists u1,u2.\n             apply E in E1;apply E' in E2;tauto.\n          -- intros (u1&u2&Eu&E1&E2);exists u1,u2.\n             apply E in E1;apply E' in E2;tauto.\n        * intros a b c w;split.\n          -- intros (u1&?&E1&I1&u2&u3&E2&I2&I3).\n             exists (u1⋅u2),u3;repeat split;auto.\n             ++ rewrite E1,E2;apply mon_assoc.\n             ++ exists u1,u2;repeat split;auto.\n                reflexivity.\n          -- intros (?&u3&E1&(u1&u2&E2&I1&I2)&I3).\n             exists u1,(u2⋅u3);repeat split;auto.\n             ++ rewrite E1,E2;symmetry;apply mon_assoc.\n             ++ exists u2,u3;repeat split;auto.\n                reflexivity.\n        * split;intros a w;split.\n          -- intros (u1&u2&E1&E2&I).\n             eapply (proj2_sig a);[|eauto].\n             rewrite E1,E2,left_unit;reflexivity.\n          -- intros I;exists 𝟭,w.\n             repeat split;auto.\n             ++ rewrite left_unit;reflexivity.\n             ++ simpl;reflexivity.\n          -- intros (u1&u2&E1&I&E2).\n             eapply (proj2_sig a);[|eauto].\n             rewrite E1,E2,right_unit;reflexivity.\n          -- intros I;exists w,(𝟭:A).\n             repeat split;auto.\n             ++ rewrite right_unit;reflexivity.\n             ++ simpl;reflexivity.\n      + split.\n        * intros a b E a' b' E' w;split.\n          -- intros (u1&u2&Eu&E1&E2);exists u1,u2.\n             apply E in E1;apply E' in E2;tauto.\n          -- intros (u1&u2&Eu&E1&E2);exists u1,u2.\n             apply E in E1;apply E' in E2;tauto.\n        * intros a b c w;split.\n          -- intros (u1&?&E1&I1&u2&u3&E2&I2&I3).\n             exists (u1∥u2),u3;repeat split;auto.\n             ++ rewrite E1,E2;apply mon_assoc.\n             ++ exists u1,u2;repeat split;auto.\n                reflexivity.\n          -- intros (?&u3&E1&(u1&u2&E2&I1&I2)&I3).\n             exists u1,(u2∥u3);repeat split;auto.\n             ++ rewrite E1,E2;symmetry;apply mon_assoc.\n             ++ exists u2,u3;repeat split;auto.\n                reflexivity.\n      * split;intros a w;split.\n          -- intros (u1&u2&E1&E2&I).\n             eapply (proj2_sig a);[|eauto].\n             rewrite E1,E2,left_unit;reflexivity.\n          -- intros I;exists 𝟭,w.\n             repeat split;auto.\n             ++ rewrite left_unit;reflexivity.\n             ++ simpl;reflexivity.\n          -- intros (u1&u2&E1&I&E2).\n             eapply (proj2_sig a);[|eauto].\n             rewrite E1,E2,right_unit;reflexivity.\n          -- intros I;exists w,(𝟭:A).\n             repeat split;auto.\n             ++ rewrite right_unit;reflexivity.\n             ++ simpl;reflexivity.\n      + intros a b w;split;intros (u1&u2&->&I1&I2);rewrite (bimon_comm _);exists u2,u1;\n          repeat split;auto||reflexivity.\n    - split.\n      + intros a b E a' b' E' w;split;intros [I|I];(left;apply E,I)||(right;apply E',I).\n      + intros a b c w;unfold join,SetBiKAJoin;simpl;tauto.\n      + split;intros a w;unfold join,SetBiKAJoin,zero,SetBiKAZero;simpl;tauto.\n    - intros a b w;unfold join,SetBiKAJoin;simpl;tauto.\n    - split;intros a w;unfold prod,SetBiKAProd,zero,SetBiKAZero;simpl;firstorder.\n    - split;intros a w;unfold par,SetBiKAPar,zero,SetBiKAZero;simpl;firstorder.\n    - intros a b c w;split.\n      + intros (u1&u2&->&I1&[I2|I2]);[left|right];exists u1,u2;repeat split;auto||reflexivity.\n      + intros [(u1&u2&->&I1&I2)|(u1&u2&->&I1&I2)];exists u1,u2;\n          repeat split;reflexivity||auto;[left|right];auto.\n    - intros a b c w;split.\n      + intros (u1&u2&->&[I1|I1]&I2);[left|right];exists u1,u2;repeat split;auto||reflexivity.\n      + intros [(u1&u2&->&I1&I2)|(u1&u2&->&I1&I2)];exists u1,u2;\n          repeat split;reflexivity||auto;[left|right];auto.\n    - intros a b c w;split.\n      + intros (u1&u2&->&I1&[I2|I2]);[left|right];exists u1,u2;repeat split;auto||reflexivity.\n      + intros [(u1&u2&->&I1&I2)|(u1&u2&->&I1&I2)];exists u1,u2;\n          repeat split;reflexivity||auto;[left|right];auto.\n  Qed.\n\n  \n  Global Instance SetBiKA_biKA : BiKleeneAlgebra SetBiKA sequiv.\n  Proof.\n    split.\n    - intros a b E w;split;intros (n&I);exists n.\n      + rewrite <- E;assumption.\n      + rewrite E;assumption.\n    - apply SetBiKA_bisemiring.\n    - intros a w;unfold join,SetBiKAJoin;simpl;tauto.\n    - intros a w;split;[intros I;right;auto|intros [I|I];[|apply I]].\n      destruct I as [->|(u1&u2&->&I1&n&I2)].\n      + exists 0;simpl;reflexivity.\n      + exists (S n),u1,u2;repeat split;auto||reflexivity.\n    - intros a b E w;split;[intros I;right;auto|intros [I|I];[|apply I]].\n      destruct I as (u1&u2&->&(n&I1)&I2).\n      revert u1 u2 I1 I2;induction n;intros u1 u2 I1 I2.\n      + rewrite I1,left_unit;auto.\n      + destruct I1 as (v1&v2&->&I1&I1').\n        rewrite <- (mon_assoc _).\n        apply E;left;exists v1,(v2⋅u2);repeat split;auto||reflexivity.\n    - intros a b E w;split;[intros I;right;auto|intros [I|I];[|apply I]].\n      destruct I as (u1&u2&->&I1&n&I2).\n      revert u1 u2 I1 I2;induction n;intros u1 u2 I1 I2.\n      + rewrite I2,right_unit;auto.\n      + rewrite Power_last in I2;destruct I2 as (v1&v2&->&I2&I2').\n        rewrite (mon_assoc _).\n        apply E;left;exists (u1⋅v1),v2;repeat split;auto||reflexivity.\n  Qed.\n\n  Lemma SetBiKA_inf_is_impl a b : leqA sequiv a b <-> a ≲ b.\n  Proof.\n    unfold leqA;split.\n    - intros -> w I;left;auto.\n    - intros I w;split.\n      + intro I';right;auto.\n      + intros [I'|I'].\n        * apply I,I'.\n        * auto.\n  Qed.\n\n  (** * Finite elements *)\n\n  Definition mem (L : list A) := fun x => exists y, y ∈ L /\\ y ⩵ x.\n  \n  Lemma list_internal L : Proper (eqA ==> iff) (mem L).\n  Proof.\n    intros x y E;split;intros (z&Iz&Ez);exists z;rewrite Ez at 2;rewrite E;\n      split;assumption||reflexivity.\n  Qed.\n      \n  Definition lift L : SetBiKA := exist _ (mem L) (list_internal L).\n\n  Notation \" ⟨ L ⟩ \" := (lift L).\n\n  Global Instance infLang : SemSmaller (list A) :=\n    fun L M => forall x, x ∈ L -> exists y, y ∈ M /\\ y ⩵ x.\n  \n  Global Instance eqLang : SemEquiv (list A) :=\n    fun L M => L ≲ M /\\ M ≲ L.\n  \n  Global Instance infLang_PreOrder : PreOrder ssmaller.\n  Proof.\n    split.\n    - intros L x I;exists x;split;assumption||reflexivity.\n    - intros L M N E1 E2 x I.\n      apply E1 in I as (y&I&E).\n      setoid_rewrite <-E.\n      apply E2,I.\n  Qed.\n  Global Instance eqLang_Equiv : Equivalence sequiv.\n  Proof.\n    repeat split.\n    - reflexivity.\n    - reflexivity.\n    - destruct H4;tauto.\n    - destruct H4;tauto.\n    - transitivity y;[apply H4|apply H5].\n    - transitivity y;[apply H5|apply H4].\n  Qed.\n  Global Instance infLang_PartialOrder : PartialOrder sequiv ssmaller.\n  Proof. repeat split;apply H4. Qed.\n\n  Lemma lift_iso l m : l ≃ m <-> ⟨l⟩ ≃ ⟨m⟩.\n  Proof.\n    split.\n    - intros (h1&h2);intro x;unfold member;simpl;unfold mem.\n      split;intros (y&Iy&Ey);setoid_rewrite <- Ey;[apply h1|apply h2];apply Iy.\n    - intros h;split;intros x Ix;apply h;exists x;split;assumption||reflexivity.\n  Qed.\n\n  Global Instance prod_list : Product (list A) := (@lift_prod A prod).\n  Global Instance par_list : ParProduct (list A) := (@lift_prod A par).\n  Global Instance join_list : Join (list A) := (@app A).\n  Global Instance unit_list : Un (list A) := [𝟭].\n  Global Instance zero_list : Zero (list A) := [].\n\n  Lemma prod_list_eq l m : ⟨l ⋅ m⟩ ≃ ⟨l⟩⋅⟨m⟩.\n  Proof.\n    intro a;split.\n    - intros (b&Ib&<-);unfold prod,prod_list in Ib.\n      apply lift_prod_spec in Ib as (b1&b2&Ib1&Ib2&->).\n      exists b1,b2;repeat split.\n      + reflexivity.\n      + exists b1;split;assumption||reflexivity.\n      + exists b2;split;assumption||reflexivity.\n    - intros (a1&a2&->&(b1&I1&<-)&b2&I2&<-).\n      exists (b1⋅b2);split;[apply lift_prod_spec;exists b1,b2;tauto|reflexivity].\n  Qed.\n      \n  Lemma par_list_eq l m : ⟨l ∥ m⟩ ≃ ⟨l⟩∥⟨m⟩.\n  Proof.\n    intro a;split.\n    - intros (b&Ib&<-);unfold par,par_list in Ib.\n      apply lift_prod_spec in Ib as (b1&b2&Ib1&Ib2&->).\n      exists b1,b2;repeat split.\n      + reflexivity.\n      + exists b1;split;assumption||reflexivity.\n      + exists b2;split;assumption||reflexivity.\n    - intros (a1&a2&->&(b1&I1&<-)&b2&I2&<-).\n      exists (b1∥b2);split;[apply lift_prod_spec;exists b1,b2;tauto|reflexivity].\n  Qed.\n\n  Lemma join_list_eq l m : ⟨l∪m⟩ ≃ ⟨l⟩∪⟨m⟩.\n  Proof.\n    intro a;split.\n    - intros (b&Ib&<-).\n      apply in_app_iff in Ib as [Ib|Ib];[left|right];exists b;split;assumption||reflexivity.\n    - intros [I|I];destruct I as (b&Ib&<-);exists b;split;try reflexivity;\n        apply in_app_iff;[left|right];assumption.\n  Qed.\n        \n  Lemma unit_list_eq : ⟨𝟭⟩ ≃ 𝟭.\n  Proof.\n    intro a;split.\n    - intros (b&[<-|F]&<-).\n      + simpl;reflexivity.\n      + simpl in F;tauto.\n    - intros ->;exists 𝟭;split;[left|];reflexivity.\n  Qed.\n\n  Lemma zero_list_eq : ⟨𝟬⟩ ≃ 𝟬.\n  Proof. intros a;split;simpl;unfold mem;simpl;firstorder. Qed.\n    \n  Global Instance ListBiSemiRing_bisemiring :\n    BiSemiRing (list A) sequiv prod par join un zero.\n  Proof.\n    split.\n    - split.\n      + split.\n        * intros x y E1 z t E2.\n          rewrite lift_iso in *;repeat rewrite prod_list_eq.\n          rewrite E1,E2;reflexivity.\n        * intros x y z.\n          rewrite lift_iso in *;repeat rewrite prod_list_eq.\n          apply mon_assoc.\n        * split;intro x;apply lift_iso;rewrite prod_list_eq,unit_list_eq.\n          -- apply left_unit.\n          -- apply right_unit.\n      + split.\n        * intros x y E1 z t E2.\n          rewrite lift_iso in *;repeat rewrite par_list_eq.\n          rewrite E1,E2;reflexivity.\n        * intros x y z.\n          rewrite lift_iso in *;repeat rewrite par_list_eq.\n          apply mon_assoc.\n        * split;intro x;apply lift_iso;rewrite par_list_eq,unit_list_eq.\n          -- apply left_unit.\n          -- apply right_unit.\n      + intros x y;rewrite lift_iso in *;repeat rewrite par_list_eq;apply bimon_comm.\n    - split.\n      * intros x y E1 z t E2.\n        rewrite lift_iso in *;repeat rewrite join_list_eq.\n        rewrite E1,E2;reflexivity.\n      * intros x y z.\n        rewrite lift_iso in *;repeat rewrite join_list_eq.\n        apply mon_assoc.\n      * split;intro x;apply lift_iso;rewrite join_list_eq,zero_list_eq.\n        -- apply left_unit.\n        -- apply right_unit.\n    - intros x y;apply lift_iso;repeat rewrite join_list_eq;apply bisemiring_comm.\n    - split;intro x;apply lift_iso;rewrite prod_list_eq,zero_list_eq.\n      + apply left_absorbing.\n      + apply right_absorbing.\n    - split;intro x;apply lift_iso;rewrite par_list_eq,zero_list_eq.\n      + apply left_absorbing.\n      + apply right_absorbing.\n    - intros x y z;apply lift_iso;repeat rewrite prod_list_eq||rewrite join_list_eq.\n      apply bisemiring_left_distr.\n    - intros x y z;apply lift_iso;repeat rewrite prod_list_eq||rewrite join_list_eq.\n      apply bisemiring_right_distr.\n    - intros x y z;apply lift_iso;repeat rewrite par_list_eq||rewrite join_list_eq.\n      apply bisemiring_par_distr.\n  Qed.\n  \n  Global Instance ListBiSemiRing_idempotent : @Idempotent _ sequiv join.\n  Proof. intros x;apply lift_iso;repeat rewrite join_list_eq;apply bika_idem. Qed.\n\nEnd powerset_biKA.\nArguments SetBiKA : clear implicits.\nInfix \" ∊ \" := member (at level 80).\n  \nSection morph.\n  \n  Context {A : Type} {eqA: relation A}.\n  Context {equivA : @Equivalence A eqA}.\n  \n  Infix \" =A \" := eqA (at level 80).\n  \n  Context {joinA: Join A}{seqA: Product A}{parA:ParProduct A}{zA: Zero A}{uA:Un A}\n          {sA:Star A}.\n  \n  Context {B : Type} {eqB: relation B}.\n  Context {equivB : @Equivalence B eqB}.\n  \n  Infix \" =B \" := eqB (at level 80).\n  \n  Context {joinB: Join B}{seqB: Product B}{parB:ParProduct B}{zB: Zero B}{uB:Un B}\n          {sB:Star B}.\n\n  Class biKA_morph (g : A -> B) :=\n    {\n      morph_eq : Proper (eqA ==> eqB) g;\n      morph_1 : g 𝟭 =B 𝟭;\n      morph_0 : g 𝟬 =B 𝟬;\n      morph_prod : forall b1 b2, g (b1 ⋅ b2) =B g b1 ⋅ g b2;\n      morph_par : forall b1 b2, g (b1 ∥ b2) =B g b1 ∥ g b2;\n      morph_join : forall b1 b2, g (b1 ∪ b2) =B g b1 ∪ g b2;\n      morph_star : forall b, g (b⋆) =B g b⋆;\n    }.\nEnd morph.\n\nArguments biKA_morph : clear implicits.\nArguments biKA_morph {A} eqA {joinA seqA parA zA uA sA B} eqB {joinB seqB parB zB uB sB} g.\n\n(* Section iso_biKA. *)\n(*   Context {A : Type} {eqA: relation A}. *)\n(*   Context {equivA : @Equivalence A eqA}. *)\n  \n(*   Infix \" =A \" := eqA (at level 80). *)\n  \n(*   Context {j: Join A}{seq: Product A}{par:ParProduct A}{z: Zero A}{u:Un A}{s:Star A}. *)\n(*   Context {biKA: BiKleeneAlgebra A eqA}. *)\n\n  \n(*   Context {B : Type} {eqB: relation B}. *)\n(*   Context {equivB : @Equivalence B eqB}. *)\n  \n(*   Infix \" =B \" := eqB (at level 80). *)\n  \n(*   Context {joinB: Join B}{seqB: Product B}{parB:ParProduct B}{zB: Zero B}{uB:Un B} *)\n(*           {sB:Star B}. *)\n\n(*   Context {f : A -> B} {g : B -> A}. *)\n(*   Hypothesis fg : forall b, f (g b) =B b. *)\n(*   Hypothesis gf : forall a, g (f a) =A a. *)\n  \n(*   Hypothesis g_morph : biKA_morph eqB eqA g. *)\n(*   Hypothesis f_morph : biKA_morph eqA eqB f. *)\n  \n(*   Theorem BiKA_B : BiKleeneAlgebra B eqB. *)\n(*   Proof. *)\n(*     split. *)\n(*     - intros b1 b2 E. *)\n(*       etransitivity;[|apply fg]. *)\n(*       etransitivity;[symmetry;apply fg|]. *)\n(*       apply morph_eq. *)\n(*       repeat rewrite morph_star. *)\n(*       apply morph_eq in E;rewrite E;reflexivity. *)\n(*     - repeat split. *)\n(*       + intros b1 b2 E1 b1' b2' E2. *)\n(*         etransitivity;[|apply fg]. *)\n(*         etransitivity;[symmetry;apply fg|]. *)\n(*         apply morph_eq. *)\n(*         repeat rewrite morph_prod. *)\n(*         apply morph_eq in E1;apply morph_eq in E2. *)\n(*         destruct biKA. *)\n(*         destruct bika_semiring0. *)\n(*         destruct bisemiring_bimon0. *)\n(*         destruct bimon_seq0. *)\n(*         apply mon_congr0;auto. *)\n(*       +  *)\n        \n(*         apply mon_congr. *)\n(*         reflexivity. *)\n        \n    \n\n        \n(* Lemma iso_biKA   : *)\n(*   () -> *)\n(*   (forall a, g (f a) eqA a) -> *)\n(*    -> *)\n(*   (forall b1 b2, . *)\n         \n         ", "meta": {"author": "monstrencage", "repo": "AtomicCKA", "sha": "3d6208f18f247db91d9fca7bcafd0c78b205dc52", "save_path": "github-repos/coq/monstrencage-AtomicCKA", "path": "github-repos/coq/monstrencage-AtomicCKA/AtomicCKA-3d6208f18f247db91d9fca7bcafd0c78b205dc52/algebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516187, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.6789610010052588}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\nRequire Export Coq.Lists.List.\nFrom VFA Require Import Perm.\n\n\n\nFixpoint select (x: nat) (l: list nat) : nat * list nat :=\nmatch l with\n|  nil => (x, nil)\n|  h::t => if x <=? h\nthen let (j, l') := select x t in (j, h::l')\nelse let (j,l') := select h t in (j, x::l')\nend.\n\n\n\n\n\n\n\nFixpoint selsort l n {struct n} :=\nmatch l, n with\n| x::r, S n' => let (y,r') := select x r\nin y :: selsort r' n'\n| nil, _ => nil\n| _::_, O => nil\nend.\n\n\n\nExample out_of_gas: selsort [3;1;4;1;5] 3 <> [1;1;3;4;5].\nProof. hammer_hook \"Selection\" \"Selection.out_of_gas\".\nsimpl.\nintro. inversion H.\nQed.\n\n\n\nExample too_much_gas: selsort [3;1;4;1;5] 10 = [1;1;3;4;5].\nProof. hammer_hook \"Selection\" \"Selection.too_much_gas\".\nsimpl.\nauto.\nQed.\n\n\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. hammer_hook \"Selection\" \"Selection.sort_pi\".\nunfold selection_sort.\nsimpl.\nreflexivity.\nQed.\n\n\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) :=\nforall al, Permutation al (f al) /\\ sorted (f al).\n\n\n\n\n\n\nDefinition selection_sort_correct : Prop :=\nis_a_sorting_algorithm selection_sort.\n\n\n\n\nLemma select_perm: forall x l,\nlet (y,r) := select x l in\nPermutation (x::l) (y::r).\nProof. hammer_hook \"Selection\" \"Selection.select_perm\".\n\n\n\nintros x l; revert x.\ninduction l; intros; simpl in *.\nAdmitted.\n\n\n\nLemma selsort_perm:\nforall n,\nforall l, length l = n -> Permutation l (selsort l n).\nProof. hammer_hook \"Selection\" \"Selection.selsort_perm\".\n\n\n\nAdmitted.\n\nTheorem selection_sort_perm:\nforall l, Permutation l (selection_sort l).\nProof. hammer_hook \"Selection\" \"Selection.selection_sort_perm\".\nAdmitted.\n\n\n\nLemma select_smallest_aux:\nforall x al y bl,\nForall (fun z => y <= z) bl ->\nselect x al = (y,bl) ->\ny <= x.\nProof. hammer_hook \"Selection\" \"Selection.select_smallest_aux\".\n\nAdmitted.\n\nTheorem select_smallest:\nforall x al y bl, select x al = (y,bl) ->\nForall (fun z => y <= z) bl.\nProof. hammer_hook \"Selection\" \"Selection.select_smallest\".\nintros x al; revert x; induction al; intros; simpl in *.\nadmit.\nbdestruct (x <=? a).\n*\ndestruct (select x al) eqn:?H.\nAdmitted.\n\n\n\nLemma selection_sort_sorted_aux:\nforall  y bl,\nsorted (selsort bl (length bl)) ->\nForall (fun z : nat => y <= z) bl ->\nsorted (y :: selsort bl (length bl)).\nProof. hammer_hook \"Selection\" \"Selection.selection_sort_sorted_aux\".\n\nAdmitted.\n\nTheorem selection_sort_sorted: forall al, sorted (selection_sort al).\nProof. hammer_hook \"Selection\" \"Selection.selection_sort_sorted\".\nintros.\nunfold selection_sort.\n\nAdmitted.\n\n\n\n\nTheorem selection_sort_is_correct: selection_sort_correct.\nProof. hammer_hook \"Selection\" \"Selection.selection_sort_is_correct\".\nsplit. apply selection_sort_perm. apply selection_sort_sorted.\nQed.\n\n\n\n\n\n\nRequire Import Recdef.\n\nFunction selsort' l {measure length l} :=\nmatch l with\n| x::r => let (y,r') := select x r\nin y :: selsort' r'\n| nil => nil\nend.\n\n\n\nProof.\nintros.\npose proof (select_perm x r).\nrewrite teq0 in H.\napply Permutation_length in H.\nsimpl in *; omega.\nDefined.\n\n\nLemma selsort'_perm:\nforall n,\nforall l, length l = n -> Permutation l (selsort' l).\nProof. hammer_hook \"Selection\" \"Selection.selsort'_perm\".\n\n\n\n\n\nAdmitted.\n\n\nEval compute in selsort' [3;1;4;1;5;9;2;6;5].\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/Selection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516187, "lm_q2_score": 0.8006920020959543, "lm_q1q2_score": 0.6789609929394179}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import Crypto.Arithmetic.MontgomeryReduction.Proofs. (* For MontgomeryReduction *)\nRequire Import Crypto.Util.Tactics.UniquePose.\nRequire Import Crypto.Util.Tuple Crypto.Util.Prod Crypto.Util.LetIn.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo.\nRequire Import Crypto.Util.ZUtil.Tactics.RewriteModSmall.\nRequire Import Crypto.Util.ZUtil.Log2.\nRequire Import Crypto.Util.ZUtil.AddGetCarry Crypto.Util.ZUtil.MulSplit.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.Tactics.SplitInContext.\nRequire Import Crypto.Util.ZUtil.Definitions.\nImport Coq.Lists.List ListNotations. Local Open Scope Z_scope.\n\nSection primitives.\n  Definition mulx (bitwidth : Z) := Eval cbv [Z.mul_split_at_bitwidth] in Z.mul_split_at_bitwidth bitwidth.\n  Definition addcarryx (bitwidth : Z) := Eval cbv [Z.add_with_get_carry Z.add_with_carry Z.get_carry] in Z.add_with_get_carry bitwidth.\n  Definition subborrowx (bitwidth : Z) := Eval cbv [Z.sub_with_get_borrow Z.sub_with_borrow Z.get_borrow Z.get_carry Z.add_with_carry] in Z.sub_with_get_borrow bitwidth.\n  Definition cmovznz (bitwidth : Z) (cond : Z) (z nz : Z)\n    := dlet t := (0 - Z.bneg (Z.bneg cond)) mod 2^bitwidth in Z.lor (Z.land (Z.value_barrier t) nz) (Z.land (Z.value_barrier (Z.lnot_modulo t (2^bitwidth))) z).\n  Definition cmovznz_by_mul (bitwidth : Z) (cond : Z) (z nz : Z)\n    := dlet t := cond * (2^bitwidth - 1) in Z.lor (Z.land (Z.value_barrier t) nz) (Z.land (Z.value_barrier (Z.lnot_modulo t (2^bitwidth))) z).\n\n  Lemma mulx_correct (bitwidth : Z)\n        (x y : Z)\n    : mulx bitwidth x y = ((x * y) mod 2^bitwidth, (x * y) / 2^bitwidth).\n  Proof using Type.\n    change mulx with Z.mul_split_at_bitwidth.\n    rewrite <- Z.mul_split_at_bitwidth_div, <- Z.mul_split_at_bitwidth_mod; eta_expand.\n    eta_expand; reflexivity.\n  Qed.\n\n  Lemma addcarryx_correct (bitwidth : Z)\n        (c x y : Z)\n    : addcarryx bitwidth c x y = ((c + x + y) mod 2^bitwidth, (c + x + y) / 2^bitwidth).\n  Proof using Type.\n    cbv [addcarryx Let_In]; reflexivity.\n  Qed.\n\n  Lemma subborrowx_correct (bitwidth : Z)\n        (b x y : Z)\n    : subborrowx bitwidth b x y = ((-b + x + -y) mod 2^bitwidth, -((-b + x + -y) / 2^bitwidth)).\n  Proof using Type.\n    cbv [subborrowx Let_In]; reflexivity.\n  Qed.\n\n  Lemma cmovznz_correct bitwidth cond z nz\n    : 0 <= z < 2^bitwidth\n      -> 0 <= nz < 2^bitwidth\n      -> cmovznz bitwidth cond z nz = Z.zselect cond z nz.\n  Proof using Type.\n    intros.\n    assert (0 < 2^bitwidth) by lia.\n    assert (0 <= bitwidth) by auto with zarith.\n    assert (0 < bitwidth -> 1 < 2^bitwidth) by auto with zarith.\n    pose proof Z.log2_lt_pow2_alt.\n    assert (bitwidth = 0 \\/ 0 < bitwidth) by lia.\n    repeat first [ progress cbv [cmovznz Z.zselect Z.bneg Let_In Z.lnot_modulo]\n                 | progress split_iff\n                 | progress subst\n                 | progress Z.ltb_to_lt\n                 | progress destruct_head'_or\n                 | congruence\n                 | lia\n                 | progress break_innermost_match_step\n                 | progress break_innermost_match_hyps_step\n                 | progress autorewrite with zsimplify_const in *\n                 | progress pull_Zmod\n                 | progress intros\n                 | rewrite !Z.sub_1_r, <- Z.ones_equiv, <- ?Z.sub_1_r\n                 | rewrite Z_mod_nz_opp_full by (Z.rewrite_mod_small; lia)\n                 | rewrite (Z.land_comm (Z.ones _))\n                 | rewrite Z.land_ones_low by auto with lia\n                 | progress Z.rewrite_mod_small ].\n  Qed.\n\n  Lemma cmovznz_by_mul_correct bitwidth cond z nz\n    : 0 <= cond < 2^1\n      -> 0 <= z < 2^bitwidth\n      -> 0 <= nz < 2^bitwidth\n      -> cmovznz_by_mul bitwidth cond z nz = Z.zselect cond z nz.\n  Proof using Type.\n    intros.\n    assert (0 < 2^bitwidth) by lia.\n    assert (0 <= bitwidth) by auto with zarith.\n    assert (0 < bitwidth -> 1 < 2^bitwidth) by auto with zarith.\n    pose proof Z.log2_lt_pow2_alt.\n    assert (bitwidth = 0 \\/ 0 < bitwidth) by lia.\n    assert (cond = 0 \\/ cond = 1) by lia.\n    repeat first [ progress cbv [cmovznz_by_mul Z.zselect Let_In Z.lnot_modulo Z.lnot Z.pred]\n                 | progress split_iff\n                 | progress subst\n                 | progress Z.ltb_to_lt\n                 | progress destruct_head'_or\n                 | congruence\n                 | lia\n                 | progress break_innermost_match_step\n                 | progress break_innermost_match_hyps_step\n                 | progress autorewrite with zsimplify_const in *\n                 | progress (push_Zmod; pull_Zmod)\n                 | progress intros\n                 | rewrite !Z.sub_1_r, <- Z.ones_equiv, <- ?Z.sub_1_r\n                 | rewrite Z_mod_nz_opp_full by (Z.rewrite_mod_small; lia)\n                 | rewrite (Z.land_comm (Z.ones _))\n                 | rewrite Z.land_ones_low by auto with lia\n                 | progress Z.rewrite_mod_small\n                 | replace (-Z.ones bitwidth + -1) with (-2^bitwidth) by (rewrite Z.ones_equiv, <- Z.sub_1_r; lia) ].\n  Qed.\nEnd primitives.\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/Arithmetic/Primitives.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.6789171060190606}}
{"text": "Require Import Coq.Init.Datatypes.\nRequire Import Coq.Program.Tactics.\nImport Coq.Init.Notations.\nNotation \"A -> B\" := (forall (_ : A), B) : type_scope.\nRequire Import univalence.\nRequire Import equivalences.\nRequire Import equivalencesDefinitions.\nRequire Import propositionsSets.\n\nSection prodStrictlyAssoc.\nSearch prod.\n\n(*  the proof of the following Lemma is at \n    the end of equivalences.v. *)\nDefinition halfAdjointEquivImpliesContractible {X Y:Type}\n  (f:X->Y):\n  HalfAdjointEquiv f -> IsContractibleMap f.\nProof.\nAdmitted.\n\nDefinition associator (X Y Z:Type):\n  (prod (prod X Y) Z) -> (prod X (prod Y Z)).\nProof.\n  intro. induction X0. induction a.\n  apply (a,(b0,b)).\nDefined.\n\nDefinition associatorInverse (X Y Z:Type):\n  (prod X (prod Y Z)) -> (prod (prod X Y) Z).\nProof.\n(* define the inverse to the associator here *)\nDefined.\n\nDefinition assocIsInv {X Y Z:Type} (v:(prod X (prod Y Z))):\n  Id (associator X Y Z (associatorInverse X Y Z v)) v.\nProof.\n(* your proof here *)\nDefined.\n\nDefinition assocIsInv2 {X Y Z:Type} (v:prod (prod X Y) Z):\n  Id (associatorInverse X Y Z (associator X Y Z v)) v.\nProof.\n(* your proof here *)\nDefined.\n\n\n\nDefinition associatorIsEquiv {X Y Z:Type}:\n  IsContractibleMap (associator X Y Z).\nProof.\n(* your proof here - use the fact that haequiv are contractible maps *)\nDefined.\n\nLemma productStrictlyAssoc {X Y Z:Type}:\n  Id (prod (prod X Y) Z) (prod X (prod Y Z)).\nProof.\n(* your proof here *)\nDefined.\n\nEnd prodStrictlyAssoc.", "meta": {"author": "mwpb", "repo": "introduction-univalence-coq", "sha": "106643b5aea0937740e5ea51993a21da117dca2a", "save_path": "github-repos/coq/mwpb-introduction-univalence-coq", "path": "github-repos/coq/mwpb-introduction-univalence-coq/introduction-univalence-coq-106643b5aea0937740e5ea51993a21da117dca2a/productStrictlyAssoc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242132, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6789171008826131}}
{"text": "Require Import CT.Category.\nRequire Import CT.Functor.\nRequire Import CT.Instance.Category.ProductCategory.\nRequire Import CT.Instance.Functor.Endofunctor.\n\n(** [F : AxB -> C]. _Bifunctors_ are functors from a product category to another\n    category. These (or rather their specialized form [ProductFunctor]) show up\n    as tensors in [MonoidalCategory] instances.\n*)\nProgram Definition Bifunctor (A B C : Category) := Functor (ProductCategory A B) C.\n\n(* TODO: Explain this better. *)\n(** Given two morphisms \\(f, g\\), do the \"right thing\" by applying them to\n    the first and second components on both ends of a morphism respectively,\n    thus lifting it into the codomain category of the given (implicit)\n    functor. *)\nDefinition bimap\n           {A B C : Category}\n           {F : Bifunctor A B C}\n           {a b : ob A}\n           {c d : ob B}\n           (f : mor a b)\n           (g : mor c d) :\n  mor (F_ob F (a, c)) (F_ob F (b, d)) :=\n  @F_mor (ProductCategory A B) C F (a, c) (b, d) (f, g).\n\n(* TODO: Write a bunch of theorems about bimap. *)", "meta": {"author": "relrod", "repo": "ct", "sha": "abd8b0067e219ee4867f7136bdf1b35885224cb4", "save_path": "github-repos/coq/relrod-ct", "path": "github-repos/coq/relrod-ct/ct-abd8b0067e219ee4867f7136bdf1b35885224cb4/CT/Instance/Functor/Bifunctor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6789170990597339}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Frederic Blanqui, 2008-08-08\n\nboolean functions on lists\n*)\n\nSet Implicit Arguments.\n\nFrom Coq Require Import Arith Lia.\nFrom CoLoR Require Import ListUtil BoolUtil EqUtil LogicUtil.\n\nSection S.\n\n  Variables (A : Type) (beq : A -> A -> bool)\n            (beq_ok : forall x y, beq x y = true <-> x = y).\n\n  Ltac case_beq := EqUtil.case_beq beq beq_ok.\n\n(***********************************************************************)\n(** boolean decidability of equality *)\n\n  Fixpoint beq_list (l m : list A) :=\n    match l, m with\n    | nil, nil => true\n    | x :: l', y :: m' => beq x y && beq_list l' m'\n    | _, _ => false\n    end.\n\n  Lemma beq_list_refl : forall l, beq_list l l = true.\n\n  Proof. induction l; simpl. refl. rewrite IHl, (beq_refl beq_ok). refl. Qed.\n\n  Lemma beq_list_ok : forall l m, beq_list l m = true <-> l = m.\n\n  Proof.\n    induction l; destruct m; simpl; split; intro; try (refl || discr).\n    destruct (andb_elim H). rewrite beq_ok in H0. subst a0.\n    rewrite IHl in H1. subst m. refl.\n    inversion H. subst a0. subst m. apply andb_intro.\n    rewrite beq_ok. refl. rewrite IHl. refl.\n  Qed.\n\n  (*REMARK: this lemma does not use beq_ok *)\n  Lemma beq_list_ok_in : forall l,\n      forall hyp : forall x, In x l -> forall y, beq x y = true <-> x = y,\n        forall m, beq_list l m = true <-> l = m.\n\n  Proof.\n    induction l; destruct m; split; intro; try (refl || discr).\n    inversion H. destruct (andb_elim H1).\n    assert (h : In a (a::l)). simpl. auto.\n    ded (hyp _ h a0). rewrite H3 in H0. subst a0.\n    apply tail_eq.\n    assert (hyp' : forall x, In x l -> forall y, beq x y = true <-> x=y).\n    intros x hx. apply hyp. simpl. auto.\n    destruct (andb_elim H1). ded (IHl hyp' m). rewrite H5 in H4. exact H4.\n    rewrite <- H. simpl. apply andb_intro.\n    assert (h : In a (a::l)). simpl. auto.\n    ded (hyp _ h a). rewrite H0. refl.\n    assert (hyp' : forall x, In x l -> forall y, beq x y = true <-> x=y).\n    intros x hx. apply hyp. simpl. auto.\n    ded (IHl hyp' l). rewrite H0. refl.\n  Qed.\n\n(***********************************************************************)\n(** membership *)\n\n  Fixpoint mem (x : A) (l : list A) : bool :=\n    match l with\n    | nil => false\n    | y :: m => beq x y || mem x m\n    end.\n\n  Lemma mem_ok x : forall l, mem x l = true <-> In x l.\n\n  Proof.\n    induction l; simpl; intros; auto. intuition. split; intro.\n    destruct (orb_true_elim H). rewrite beq_ok in e. subst. auto. intuition.\n    destruct H. subst. rewrite (beq_refl beq_ok). refl. intuition.\n  Qed.\n\n(***********************************************************************)\n(** inclusion *)\n\n  Fixpoint incl (l l' : list A) : bool :=\n    match l with\n    | nil => true\n    | y :: m => mem y l' && incl m l'\n    end.\n\n  Lemma incl_ok : forall l l', incl l l' = true <-> l [= l'.\n\n  Proof.\n    induction l; simpl; intros; auto. intuition. apply incl_nil. split; intro.\n    destruct (andb_elim H). rewrite mem_ok in H0. rewrite IHl in H1. intuition.\n    destruct (incl_cons_l H). rewrite <- mem_ok in H0. rewrite <- IHl in H1.\n    rewrite H0, H1. refl.\n  Qed.\n\n(***********************************************************************)\n(** position of an element in a list *)\n\n  Fixpoint position_aux (i : nat) (x : A) (l : list A) : option nat :=\n    match l with\n    | nil => None\n    | y :: m => if beq x y then Some i else position_aux (S i) x m\n    end.\n\n  Definition position := position_aux 0.\n\n  Lemma position_ko : forall x l, position x l = None <-> ~In x l.\n\n  Proof.\n    unfold position. cut (forall x l i, position_aux i x l = None <-> ~In x l).\n    auto. induction l; simpl; intros. intuition. case_beq x a.\n    intuition; discr. rewrite (beq_ko beq_ok) in H. ded (IHl (S i)). intuition.\n  Qed.\n\n  Lemma position_aux_plus x j k : forall l i,\n      position_aux i x l = Some k -> position_aux (i+j) x l = Some (k+j).\n\n  Proof.\n    induction l; simpl. discr. case_beq x a; intros. inversion H.\n    refl. assert (S(i+j) = S i+j). refl. rewrite H1. apply IHl. hyp.\n  Qed.\n\n  Lemma position_aux_S x k : forall l i,\n      position_aux i x l = Some k -> position_aux (S i) x l = Some (S k).\n\n  Proof.\n    induction l; simpl. discr. case_beq x a; intros. inversion H.\n    refl. apply IHl. hyp.\n  Qed.\n\n  Lemma position_aux_ok1 k x : forall l i,\n      position_aux i x l = Some k -> k >= i /\\ element_at l (k-i) = Some x.\n\n  Proof.\n    induction l; simpl. discr. case_beq x a. intros. inversion H.\n    rewrite <- minus_n_n. intuition. destruct l. simpl. discr. intros.\n    ded (IHl _ H0). assert (exists p', k - i = S p'). exists (k-i-1). lia.\n    destruct H2. rewrite H2. assert (k - S i = x0). lia. rewrite <- H3.\n    intuition.\n  Qed.\n\n  Lemma position_aux_ok2 i x : forall l k, element_at l k = Some x ->\n    exists k', k' <= k /\\ position_aux i x l = Some (i+k').\n\n  Proof.\n    induction l; simpl; intros. discr. case_beq x a.\n    exists 0. intuition. rewrite (beq_ko beq_ok) in H0. destruct k.\n    inversion H. subst. cong. destruct (IHl _ H). exists (S x0). intuition.\n    rewrite <- plus_Snm_nSm. simpl. apply position_aux_S. hyp.\n  Qed.\n\nEnd S.\n\nArguments mem_ok [A beq] _ _ _.\nArguments beq_list_ok [A beq] _ _ _.\nArguments beq_list_ok_in [A beq l] _ _.\nArguments incl_ok [A beq] _ _ _.\n\n(***********************************************************************)\n(** tactics *)\n\nLtac incl beq_ok :=\n  rewrite <- (incl_ok beq_ok); check_eq\n    || fail 10 \"list inclusion not satisfied\".\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Util/List/ListDec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.6788733096586063}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nSet Implicit Arguments.\nLocal Unset Intuition Negation Unfolding.\n\n\n\n\n\n\n\n\n\nSection ChoiceSchemes.\n\nVariables A B :Type.\n\nVariable P:A->Prop.\n\n\n\n\n\nDefinition RelationalChoice_on :=\nforall R:A->B->Prop,\n(forall x : A, exists y : B, R x y) ->\n(exists R' : A->B->Prop, subrelation R' R /\\ forall x, exists! y, R' x y).\n\n\n\n\n\nDefinition FunctionalChoice_on_rel (R:A->B->Prop) :=\n(forall x:A, exists y : B, R x y) ->\nexists f : A -> B, (forall x:A, R x (f x)).\n\nDefinition FunctionalChoice_on :=\nforall R:A->B->Prop,\n(forall x : A, exists y : B, R x y) ->\n(exists f : A->B, forall x : A, R x (f x)).\n\n\nDefinition DependentFunctionalChoice_on (A:Type) (B:A -> Type) :=\nforall R:forall x:A, B x -> Prop,\n(forall x:A, exists y : B x, R x y) ->\n(exists f : (forall x:A, B x), forall x:A, R x (f x)).\n\n\nDefinition InhabitedForallCommute_on (A : Type) (B : A -> Type) :=\n(forall x, inhabited (B x)) -> inhabited (forall x, B x).\n\n\n\nDefinition FunctionalDependentChoice_on :=\nforall (R:A->A->Prop),\n(forall x, exists y, R x y) -> forall x0,\n(exists f : nat -> A, f 0 = x0 /\\ forall n, R (f n) (f (S n))).\n\n\n\nDefinition FunctionalCountableChoice_on :=\nforall (R:nat->A->Prop),\n(forall n, exists y, R n y) ->\n(exists f : nat -> A, forall n, R n (f n)).\n\n\n\nDefinition FunctionalRelReification_on :=\nforall R:A->B->Prop,\n(forall x : A, exists! y : B, R x y) ->\n(exists f : A->B, forall x : A, R x (f x)).\n\n\nDefinition DependentFunctionalRelReification_on (A:Type) (B:A -> Type) :=\nforall (R:forall x:A, B x -> Prop),\n(forall x:A, exists! y : B x, R x y) ->\n(exists f : (forall x:A, B x), forall x:A, R x (f x)).\n\n\n\n\n\nRequire Import RelationClasses Logic.\n\nDefinition RepresentativeFunctionalChoice_on :=\nforall R:A->A->Prop,\n(Equivalence R) ->\n(exists f : A->A, forall x : A, (R x (f x)) /\\ forall x', R x x' -> f x = f x').\n\n\n\nDefinition SetoidFunctionalChoice_on :=\nforall R : A -> A -> Prop,\nforall T : A -> B -> Prop,\nEquivalence R ->\n(forall x x' y, R x x' -> T x y -> T x' y) ->\n(forall x, exists y, T x y) ->\nexists f : A -> B, forall x : A, T x (f x) /\\ (forall x' : A, R x x' -> f x = f x').\n\n\n\n\n\nDefinition GeneralizedSetoidFunctionalChoice_on :=\nforall R : A -> A -> Prop,\nforall S : B -> B -> Prop,\nforall T : A -> B -> Prop,\nEquivalence R ->\nEquivalence S ->\n(forall x x' y y', R x x' -> S y y' -> T x y -> T x' y') ->\n(forall x, exists y, T x y) ->\nexists f : A -> B,\nforall x : A, T x (f x) /\\ (forall x' : A, R x x' -> S (f x) (f x')).\n\n\n\nDefinition SimpleSetoidFunctionalChoice_on A B :=\nforall R : A -> A -> Prop,\nforall T : A -> B -> Prop,\nEquivalence R ->\n(forall x, exists y, forall x', R x x' -> T x' y) ->\nexists f : A -> B, forall x : A, T x (f x) /\\ (forall x' : A, R x x' -> f x = f x').\n\n\n\nDefinition ConstructiveIndefiniteDescription_on :=\nforall P:A->Prop,\n(exists x, P x) -> { x:A | P x }.\n\n\n\nDefinition ConstructiveDefiniteDescription_on :=\nforall P:A->Prop,\n(exists! x, P x) -> { x:A | P x }.\n\n\n\n\n\nDefinition GuardedRelationalChoice_on :=\nforall P : A->Prop, forall R : A->B->Prop,\n(forall x : A, P x -> exists y : B, R x y) ->\n(exists R' : A->B->Prop,\nsubrelation R' R /\\ forall x, P x -> exists! y, R' x y).\n\n\n\nDefinition GuardedFunctionalChoice_on :=\nforall P : A->Prop, forall R : A->B->Prop,\ninhabited B ->\n(forall x : A, P x -> exists y : B, R x y) ->\n(exists f : A->B, forall x, P x -> R x (f x)).\n\n\n\nDefinition GuardedFunctionalRelReification_on :=\nforall P : A->Prop, forall R : A->B->Prop,\ninhabited B ->\n(forall x : A, P x -> exists! y : B, R x y) ->\n(exists f : A->B, forall x : A, P x -> R x (f x)).\n\n\n\nDefinition OmniscientRelationalChoice_on :=\nforall R : A->B->Prop,\nexists R' : A->B->Prop,\nsubrelation R' R /\\ forall x : A, (exists y : B, R x y) -> exists! y, R' x y.\n\n\n\nDefinition OmniscientFunctionalChoice_on :=\nforall R : A->B->Prop,\ninhabited B ->\nexists f : A->B, forall x : A, (exists y : B, R x y) -> R x (f x).\n\n\n\nDefinition EpsilonStatement_on :=\nforall P:A->Prop,\ninhabited A -> { x:A | (exists x, P x) -> P x }.\n\n\n\nDefinition IotaStatement_on :=\nforall P:A->Prop,\ninhabited A -> { x:A | (exists! x, P x) -> P x }.\n\nEnd ChoiceSchemes.\n\n\n\nNotation RelationalChoice :=\n(forall A B : Type, RelationalChoice_on A B).\nNotation FunctionalChoice :=\n(forall A B : Type, FunctionalChoice_on A B).\nNotation DependentFunctionalChoice :=\n(forall A (B:A->Type), DependentFunctionalChoice_on B).\nNotation InhabitedForallCommute :=\n(forall A (B : A -> Type), InhabitedForallCommute_on B).\nNotation FunctionalDependentChoice :=\n(forall A : Type, FunctionalDependentChoice_on A).\nNotation FunctionalCountableChoice :=\n(forall A : Type, FunctionalCountableChoice_on A).\nNotation FunctionalChoiceOnInhabitedSet :=\n(forall A B : Type, inhabited B -> FunctionalChoice_on A B).\nNotation FunctionalRelReification :=\n(forall A B : Type, FunctionalRelReification_on A B).\nNotation DependentFunctionalRelReification :=\n(forall A (B:A->Type), DependentFunctionalRelReification_on B).\nNotation RepresentativeFunctionalChoice :=\n(forall A : Type, RepresentativeFunctionalChoice_on A).\nNotation SetoidFunctionalChoice :=\n(forall A  B: Type, SetoidFunctionalChoice_on A B).\nNotation GeneralizedSetoidFunctionalChoice :=\n(forall A B : Type, GeneralizedSetoidFunctionalChoice_on A B).\nNotation SimpleSetoidFunctionalChoice :=\n(forall A B : Type, SimpleSetoidFunctionalChoice_on A B).\n\nNotation GuardedRelationalChoice :=\n(forall A B : Type, GuardedRelationalChoice_on A B).\nNotation GuardedFunctionalChoice :=\n(forall A B : Type, GuardedFunctionalChoice_on A B).\nNotation GuardedFunctionalRelReification :=\n(forall A B : Type, GuardedFunctionalRelReification_on A B).\n\nNotation OmniscientRelationalChoice :=\n(forall A B : Type, OmniscientRelationalChoice_on A B).\nNotation OmniscientFunctionalChoice :=\n(forall A B : Type, OmniscientFunctionalChoice_on A B).\n\nNotation ConstructiveDefiniteDescription :=\n(forall A : Type, ConstructiveDefiniteDescription_on A).\nNotation ConstructiveIndefiniteDescription :=\n(forall A : Type, ConstructiveIndefiniteDescription_on A).\n\nNotation IotaStatement :=\n(forall A : Type, IotaStatement_on A).\nNotation EpsilonStatement :=\n(forall A : Type, EpsilonStatement_on A).\n\n\n\n\nDefinition ProofIrrelevance :=\nforall (A:Prop) (a1 a2:A), a1 = a2.\n\n\nDefinition IndependenceOfGeneralPremises :=\nforall (A:Type) (P:A -> Prop) (Q:Prop),\ninhabited A ->\n(Q -> exists x, P x) -> exists x, Q -> P x.\n\n\nDefinition SmallDrinker'sParadox :=\nforall (A:Type) (P:A -> Prop), inhabited A ->\nexists x, (exists x, P x) -> P x.\n\n\nDefinition ExcludedMiddle :=\nforall P:Prop, P \\/ ~ P.\n\n\n\n\nLocal Notation ExtensionalPropositionRepresentative :=\n(forall (A:Type),\nexists h : Prop -> Prop,\nforall P : Prop, (P <-> h P) /\\ forall Q, (P <-> Q) -> h P = h Q).\n\n\nLocal Notation ExtensionalPredicateRepresentative :=\n(forall (A:Type),\nexists h : (A->Prop) -> (A->Prop),\nforall (P : A -> Prop), (forall x, P x <-> h P x) /\\ forall Q, (forall x, P x <-> Q x) -> h P = h Q).\n\n\nLocal Notation ExtensionalFunctionRepresentative :=\n(forall (A B:Type),\nexists h : (A->B) -> (A->B),\nforall (f : A -> B), (forall x, f x = h f x) /\\ forall g, (forall x, f x = g x) -> h f = h g).\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nLemma functional_rel_reification_and_rel_choice_imp_fun_choice :\nforall A B : Type,\nFunctionalRelReification_on A B -> RelationalChoice_on A B -> FunctionalChoice_on A B.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.functional_rel_reification_and_rel_choice_imp_fun_choice\".  \nintros A B Descr RelCh R H.\ndestruct (RelCh R H) as (R',(HR'R,H0)).\ndestruct (Descr R') as (f,Hf).\nfirstorder.\nexists f; intro x.\ndestruct (H0 x) as (y,(HR'xy,Huniq)).\nrewrite <- (Huniq (f x) (Hf x)).\napply HR'R; assumption.\nQed.\n\nLemma fun_choice_imp_rel_choice :\nforall A B : Type, FunctionalChoice_on A B -> RelationalChoice_on A B.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.fun_choice_imp_rel_choice\".  \nintros A B FunCh R H.\ndestruct (FunCh R H) as (f,H0).\nexists (fun x y => f x = y).\nsplit.\nintros x y Heq; rewrite <- Heq; trivial.\nintro x; exists (f x); split.\nreflexivity.\ntrivial.\nQed.\n\nLemma fun_choice_imp_functional_rel_reification :\nforall A B : Type, FunctionalChoice_on A B -> FunctionalRelReification_on A B.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.fun_choice_imp_functional_rel_reification\".  \nintros A B FunCh R H.\ndestruct (FunCh R) as [f H0].\n\nintro x.\ndestruct (H x) as (y,(HRxy,_)).\nexists y; exact HRxy.\n\nexists f; exact H0.\nQed.\n\nCorollary fun_choice_iff_rel_choice_and_functional_rel_reification :\nforall A B : Type, FunctionalChoice_on A B <->\nRelationalChoice_on A B /\\ FunctionalRelReification_on A B.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.fun_choice_iff_rel_choice_and_functional_rel_reification\".  \nintros A B. split.\nintro H; split;\n[ exact (fun_choice_imp_rel_choice H)\n| exact (fun_choice_imp_functional_rel_reification H) ].\nintros [H H0]; exact (functional_rel_reification_and_rel_choice_imp_fun_choice H0 H).\nQed.\n\n\n\n\n\n\n\n\n\nLemma rel_choice_and_proof_irrel_imp_guarded_rel_choice :\nRelationalChoice -> ProofIrrelevance -> GuardedRelationalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.rel_choice_and_proof_irrel_imp_guarded_rel_choice\".  \nintros rel_choice proof_irrel.\nred; intros A B P R H.\ndestruct (rel_choice _ _ (fun (x:sigT P) (y:B) => R (projT1 x) y)) as (R',(HR'R,H0)).\nintros (x,HPx).\ndestruct (H x HPx) as (y,HRxy).\nexists y; exact HRxy.\nset (R'' := fun (x:A) (y:B) => exists H : P x, R' (existT P x H) y).\nexists R''; split.\nintros x y (HPx,HR'xy).\nchange x with (projT1 (existT P x HPx)); apply HR'R; exact HR'xy.\nintros x HPx.\ndestruct (H0 (existT P x HPx)) as (y,(HR'xy,Huniq)).\nexists y; split. exists HPx; exact HR'xy.\nintros y' (H'Px,HR'xy').\napply Huniq.\nrewrite proof_irrel with (a1 := HPx) (a2 := H'Px); exact HR'xy'.\nQed.\n\nLemma rel_choice_indep_of_general_premises_imp_guarded_rel_choice :\nforall A B : Type, inhabited B -> RelationalChoice_on A B ->\nIndependenceOfGeneralPremises -> GuardedRelationalChoice_on A B.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.rel_choice_indep_of_general_premises_imp_guarded_rel_choice\".  \nintros A B Inh AC_rel IndPrem P R H.\ndestruct (AC_rel (fun x y => P x -> R x y)) as (R',(HR'R,H0)).\nintro x. apply IndPrem. exact Inh. intro Hx.\napply H; assumption.\nexists (fun x y => P x /\\ R' x y).\nfirstorder.\nQed.\n\nLemma guarded_rel_choice_imp_rel_choice :\nforall A B : Type, GuardedRelationalChoice_on A B -> RelationalChoice_on A B.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.guarded_rel_choice_imp_rel_choice\".  \nintros A B GAC_rel R H.\ndestruct (GAC_rel (fun _ => True) R) as (R',(HR'R,H0)).\nfirstorder.\nexists R'; firstorder.\nQed.\n\nLemma subset_types_imp_guarded_rel_choice_iff_rel_choice :\nProofIrrelevance -> (GuardedRelationalChoice <-> RelationalChoice).\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.subset_types_imp_guarded_rel_choice_iff_rel_choice\".  \nintuition auto using\nguarded_rel_choice_imp_rel_choice,\nrel_choice_and_proof_irrel_imp_guarded_rel_choice.\nQed.\n\n\n\nCorollary guarded_iff_omniscient_rel_choice :\nGuardedRelationalChoice <-> OmniscientRelationalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.guarded_iff_omniscient_rel_choice\".  \nsplit.\nintros GAC_rel A B R.\napply (GAC_rel A B (fun x => exists y, R x y) R); auto.\nintros OAC_rel A B P R H.\ndestruct (OAC_rel A B R) as (f,Hf); exists f; firstorder.\nQed.\n\n\n\n\n\n\nLemma guarded_fun_choice_imp_indep_of_general_premises :\nGuardedFunctionalChoice -> IndependenceOfGeneralPremises.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.guarded_fun_choice_imp_indep_of_general_premises\".  \nintros GAC_fun A P Q Inh H.\ndestruct (GAC_fun unit A (fun _ => Q) (fun _ => P) Inh) as (f,Hf).\ntauto.\nexists (f tt); auto.\nQed.\n\n\nLemma guarded_fun_choice_imp_fun_choice :\nGuardedFunctionalChoice -> FunctionalChoiceOnInhabitedSet.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.guarded_fun_choice_imp_fun_choice\".  \nintros GAC_fun A B Inh R H.\ndestruct (GAC_fun A B (fun _ => True) R Inh) as (f,Hf).\nfirstorder.\nexists f; auto.\nQed.\n\nLemma fun_choice_and_indep_general_prem_imp_guarded_fun_choice :\nFunctionalChoiceOnInhabitedSet -> IndependenceOfGeneralPremises\n-> GuardedFunctionalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.fun_choice_and_indep_general_prem_imp_guarded_fun_choice\".  \nintros AC_fun IndPrem A B P R Inh H.\napply (AC_fun A B Inh (fun x y => P x -> R x y)).\nintro x; apply IndPrem; eauto.\nQed.\n\nCorollary fun_choice_and_indep_general_prem_iff_guarded_fun_choice :\nFunctionalChoiceOnInhabitedSet /\\ IndependenceOfGeneralPremises\n<-> GuardedFunctionalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.fun_choice_and_indep_general_prem_iff_guarded_fun_choice\".  \nintuition auto using\nguarded_fun_choice_imp_indep_of_general_premises,\nguarded_fun_choice_imp_fun_choice,\nfun_choice_and_indep_general_prem_imp_guarded_fun_choice.\nQed.\n\n\n\n\n\nLemma omniscient_fun_choice_imp_small_drinker :\nOmniscientFunctionalChoice -> SmallDrinker'sParadox.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.omniscient_fun_choice_imp_small_drinker\".  \nintros OAC_fun A P Inh.\ndestruct (OAC_fun unit A (fun _ => P)) as (f,Hf).\nauto.\nexists (f tt); firstorder.\nQed.\n\nLemma omniscient_fun_choice_imp_fun_choice :\nOmniscientFunctionalChoice -> FunctionalChoiceOnInhabitedSet.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.omniscient_fun_choice_imp_fun_choice\".  \nintros OAC_fun A B Inh R H.\ndestruct (OAC_fun A B R Inh) as (f,Hf).\nexists f; firstorder.\nQed.\n\nLemma fun_choice_and_small_drinker_imp_omniscient_fun_choice :\nFunctionalChoiceOnInhabitedSet -> SmallDrinker'sParadox\n-> OmniscientFunctionalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.fun_choice_and_small_drinker_imp_omniscient_fun_choice\".  \nintros AC_fun Drinker A B R Inh.\ndestruct (AC_fun A B Inh (fun x y => (exists y, R x y) -> R x y)) as (f,Hf).\nintro x; apply (Drinker B (R x) Inh).\nexists f; assumption.\nQed.\n\nCorollary fun_choice_and_small_drinker_iff_omniscient_fun_choice :\nFunctionalChoiceOnInhabitedSet /\\ SmallDrinker'sParadox\n<-> OmniscientFunctionalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.fun_choice_and_small_drinker_iff_omniscient_fun_choice\".  \nintuition auto using\nomniscient_fun_choice_imp_small_drinker,\nomniscient_fun_choice_imp_fun_choice,\nfun_choice_and_small_drinker_imp_omniscient_fun_choice.\nQed.\n\n\n\n\n\nTheorem guarded_iff_omniscient_fun_choice :\nGuardedFunctionalChoice <-> OmniscientFunctionalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.guarded_iff_omniscient_fun_choice\".  \nsplit.\nintros GAC_fun A B R Inh.\napply (GAC_fun A B (fun x => exists y, R x y) R); auto.\nintros OAC_fun A B P R Inh H.\ndestruct (OAC_fun A B R Inh) as (f,Hf).\nexists f; firstorder.\nQed.\n\n\n\n\n\n\nLemma iota_imp_constructive_definite_description :\nIotaStatement -> ConstructiveDefiniteDescription.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.iota_imp_constructive_definite_description\".  \nintros D_iota A P H.\ndestruct D_iota with (P:=P) as (x,H1).\ndestruct H; red in H; auto.\nexists x; apply H1; assumption.\nQed.\n\n\n\nLemma epsilon_imp_constructive_indefinite_description:\nEpsilonStatement -> ConstructiveIndefiniteDescription.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.epsilon_imp_constructive_indefinite_description\".  \nintros D_epsilon A P H.\ndestruct D_epsilon with (P:=P) as (x,H1).\ndestruct H; auto.\nexists x; apply H1; assumption.\nQed.\n\nLemma constructive_indefinite_description_and_small_drinker_imp_epsilon :\nSmallDrinker'sParadox -> ConstructiveIndefiniteDescription ->\nEpsilonStatement.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.constructive_indefinite_description_and_small_drinker_imp_epsilon\".  \nintros Drinkers D_epsilon A P Inh;\napply D_epsilon; apply Drinkers; assumption.\nQed.\n\nLemma epsilon_imp_small_drinker :\nEpsilonStatement -> SmallDrinker'sParadox.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.epsilon_imp_small_drinker\".  \nintros D_epsilon A P Inh; edestruct D_epsilon; eauto.\nQed.\n\nTheorem constructive_indefinite_description_and_small_drinker_iff_epsilon :\n(SmallDrinker'sParadox * ConstructiveIndefiniteDescription ->\nEpsilonStatement) *\n(EpsilonStatement ->\nSmallDrinker'sParadox * ConstructiveIndefiniteDescription).\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.constructive_indefinite_description_and_small_drinker_iff_epsilon\".  \nintuition auto using\nepsilon_imp_constructive_indefinite_description,\nconstructive_indefinite_description_and_small_drinker_imp_epsilon,\nepsilon_imp_small_drinker.\nQed.\n\n\n\n\n\n\nRequire Import Wf_nat.\nRequire Import Decidable.\n\nLemma classical_denumerable_description_imp_fun_choice :\nforall A:Type,\nFunctionalRelReification_on A nat ->\nforall R:A->nat->Prop,\n(forall x y, decidable (R x y)) -> FunctionalChoice_on_rel R.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.classical_denumerable_description_imp_fun_choice\".  \nintros A Descr.\nred; intros R Rdec H.\nset (R':= fun x y => R x y /\\ forall y', R x y' -> y <= y').\ndestruct (Descr R') as (f,Hf).\nintro x.\napply (dec_inh_nat_subset_has_unique_least_element (R x)).\napply Rdec.\napply (H x).\nexists f.\nintros x.\ndestruct (Hf x) as (Hfx,_).\nassumption.\nQed.\n\n\n\n\n\n\n\n\nTheorem dep_non_dep_functional_choice :\nDependentFunctionalChoice -> FunctionalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.dep_non_dep_functional_choice\".  \nintros AC_depfun A B R H.\ndestruct (AC_depfun A (fun _ => B) R H) as (f,Hf).\nexists f; trivial.\nQed.\n\n\n\nScheme and_indd := Induction for and Sort Prop.\nScheme eq_indd := Induction for eq Sort Prop.\n\nDefinition proj1_inf (A B:Prop) (p : A/\\B) :=\nlet (a,b) := p in a.\n\nTheorem non_dep_dep_functional_choice :\nFunctionalChoice -> DependentFunctionalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.non_dep_dep_functional_choice\".  \nintros AC_fun A B R H.\npose (B' := { x:A & B x }).\npose (R' := fun (x:A) (y:B') => projT1 y = x /\\ R (projT1 y) (projT2 y)).\ndestruct (AC_fun A B' R') as (f,Hf).\nintros x. destruct (H x) as (y,Hy).\nexists (existT (fun x => B x) x y). split; trivial.\nexists (fun x => eq_rect _ _ (projT2 (f x)) _ (proj1_inf (Hf x))).\nintro x; destruct (Hf x) as (Heq,HR) using and_indd.\ndestruct (f x); simpl in *.\ndestruct Heq using eq_indd; trivial.\nQed.\n\n\n\nTheorem functional_choice_to_inhabited_forall_commute :\nFunctionalChoice -> InhabitedForallCommute.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.functional_choice_to_inhabited_forall_commute\".  \nintros choose0 A B Hinhab.\npose proof (non_dep_dep_functional_choice choose0) as choose;clear choose0.\nassert (Hexists : forall x, exists _ : B x, True).\n{ intros x;apply inhabited_sig_to_exists.\nrefine (inhabited_covariant _ (Hinhab x)).\nintros y;exists y;exact I. }\napply choose in Hexists.\ndestruct Hexists as [f _].\nexact (inhabits f).\nQed.\n\nTheorem inhabited_forall_commute_to_functional_choice :\nInhabitedForallCommute -> FunctionalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.inhabited_forall_commute_to_functional_choice\".  \nintros choose A B R Hexists.\nassert (Hinhab : forall x, inhabited {y : B | R x y}).\n{ intros x;apply exists_to_inhabited_sig;trivial. }\napply choose in Hinhab. destruct Hinhab as [f].\nexists (fun x => proj1_sig (f x)).\nexact (fun x => proj2_sig (f x)).\nQed.\n\n\n\n\n\nTheorem dep_non_dep_functional_rel_reification :\nDependentFunctionalRelReification -> FunctionalRelReification.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.dep_non_dep_functional_rel_reification\".  \nintros DepFunReify A B R H.\ndestruct (DepFunReify A (fun _ => B) R H) as (f,Hf).\nexists f; trivial.\nQed.\n\n\n\nTheorem non_dep_dep_functional_rel_reification :\nFunctionalRelReification -> DependentFunctionalRelReification.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.non_dep_dep_functional_rel_reification\".  \nintros AC_fun A B R H.\npose (B' := { x:A & B x }).\npose (R' := fun (x:A) (y:B') => projT1 y = x /\\ R (projT1 y) (projT2 y)).\ndestruct (AC_fun A B' R') as (f,Hf).\nintros x. destruct (H x) as (y,(Hy,Huni)).\nexists (existT (fun x => B x) x y). repeat split; trivial.\nintros (x',y') (Heqx',Hy').\nsimpl in *.\ndestruct Heqx'.\nrewrite (Huni y'); trivial.\nexists (fun x => eq_rect _ _ (projT2 (f x)) _ (proj1_inf (Hf x))).\nintro x; destruct (Hf x) as (Heq,HR) using and_indd.\ndestruct (f x); simpl in *.\ndestruct Heq using eq_indd; trivial.\nQed.\n\nCorollary dep_iff_non_dep_functional_rel_reification :\nFunctionalRelReification <-> DependentFunctionalRelReification.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.dep_iff_non_dep_functional_rel_reification\".  \nintuition auto using\nnon_dep_dep_functional_rel_reification,\ndep_non_dep_functional_rel_reification.\nQed.\n\n\n\n\n\n\nLemma relative_non_contradiction_of_indefinite_descr :\nforall C:Prop, (ConstructiveIndefiniteDescription -> C)\n-> (FunctionalChoice -> C).\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.relative_non_contradiction_of_indefinite_descr\".  \nintros C H AC_fun.\nassert (AC_depfun := non_dep_dep_functional_choice AC_fun).\npose (A0 := { A:Type & { P:A->Prop & exists x, P x }}).\npose (B0 := fun x:A0 => projT1 x).\npose (R0 := fun x:A0 => fun y:B0 x => projT1 (projT2 x) y).\npose (H0 := fun x:A0 => projT2 (projT2 x)).\ndestruct (AC_depfun A0 B0 R0 H0) as (f, Hf).\napply H.\nintros A P H'.\nexists (f (existT _ A (existT _ P H'))).\npose (Hf' := Hf (existT _ A (existT _ P H'))).\nassumption.\nQed.\n\nLemma constructive_indefinite_descr_fun_choice :\nConstructiveIndefiniteDescription -> FunctionalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.constructive_indefinite_descr_fun_choice\".  \nintros IndefDescr A B R H.\nexists (fun x => proj1_sig (IndefDescr B (R x) (H x))).\nintro x.\napply (proj2_sig (IndefDescr B (R x) (H x))).\nQed.\n\n\n\nLemma relative_non_contradiction_of_definite_descr :\nforall C:Prop, (ConstructiveDefiniteDescription -> C)\n-> (FunctionalRelReification -> C).\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.relative_non_contradiction_of_definite_descr\".  \nintros C H FunReify.\nassert (DepFunReify := non_dep_dep_functional_rel_reification FunReify).\npose (A0 := { A:Type & { P:A->Prop & exists! x, P x }}).\npose (B0 := fun x:A0 => projT1 x).\npose (R0 := fun x:A0 => fun y:B0 x => projT1 (projT2 x) y).\npose (H0 := fun x:A0 => projT2 (projT2 x)).\ndestruct (DepFunReify A0 B0 R0 H0) as (f, Hf).\napply H.\nintros A P H'.\nexists (f (existT _ A (existT _ P H'))).\npose (Hf' := Hf (existT _ A (existT _ P H'))).\nassumption.\nQed.\n\nLemma constructive_definite_descr_fun_reification :\nConstructiveDefiniteDescription -> FunctionalRelReification.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.constructive_definite_descr_fun_reification\".  \nintros DefDescr A B R H.\nexists (fun x => proj1_sig (DefDescr B (R x) (H x))).\nintro x.\napply (proj2_sig (DefDescr B (R x) (H x))).\nQed.\n\n\n\n\n\n\n\n\n\n\nRequire Import Setoid.\n\nTheorem constructive_definite_descr_excluded_middle :\n(forall A : Type, ConstructiveDefiniteDescription_on A) ->\n(forall P:Prop, P \\/ ~ P) -> (forall P:Prop, {P} + {~ P}).\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.constructive_definite_descr_excluded_middle\".  \nintros Descr EM P.\npose (select := fun b:bool => if b then P else ~P).\nassert { b:bool | select b } as ([|],HP).\nred in Descr.\napply Descr.\nrewrite <- unique_existence; split.\ndestruct (EM P).\nexists true; trivial.\nexists false; trivial.\nintros [|] [|] H1 H2; simpl in *; reflexivity || contradiction.\nleft; trivial.\nright; trivial.\nQed.\n\nCorollary fun_reification_descr_computational_excluded_middle_in_prop_context :\nFunctionalRelReification ->\n(forall P:Prop, P \\/ ~ P) ->\nforall C:Prop, ((forall P:Prop, {P} + {~ P}) -> C) -> C.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.fun_reification_descr_computational_excluded_middle_in_prop_context\".  \nintros FunReify EM C H. intuition auto using\nconstructive_definite_descr_excluded_middle,\n(relative_non_contradiction_of_definite_descr (C:=C)).\nQed.\n\n\n\n\n\nRequire Import Arith.\n\nTheorem functional_choice_imp_functional_dependent_choice :\nFunctionalChoice -> FunctionalDependentChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.functional_choice_imp_functional_dependent_choice\".  \nintros FunChoice A R HRfun x0.\napply FunChoice in HRfun as (g,Rg).\nset (f:=fix f n := match n with 0 => x0 | S n' => g (f n') end).\nexists f; firstorder.\nQed.\n\nTheorem functional_dependent_choice_imp_functional_countable_choice :\nFunctionalDependentChoice -> FunctionalCountableChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.functional_dependent_choice_imp_functional_countable_choice\".  \nintros H A R H0.\nset (R' (p q:nat*A) := fst q = S (fst p) /\\ R (fst p) (snd q)).\ndestruct (H0 0) as (y0,Hy0).\ndestruct H with (R:=R') (x0:=(0,y0)) as (f,(Hf0,HfS)).\nintro x; destruct (H0 (fst x)) as (y,Hy).\nexists (S (fst x),y).\nred. auto.\nassert (Heq:forall n, fst (f n) = n).\ninduction n.\nrewrite Hf0; reflexivity.\nspecialize HfS with n; destruct HfS as (->,_); congruence.\nexists (fun n => snd (f (S n))).\nintro n'. specialize HfS with n'.\ndestruct HfS as (_,HR).\nrewrite Heq in HR.\nassumption.\nQed.\n\n\n\n\nRequire Import ClassicalFacts PropExtensionalityFacts.\n\n\n\n\nTheorem repr_fun_choice_imp_ext_prop_repr :\nRepresentativeFunctionalChoice -> ExtensionalPropositionRepresentative.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.repr_fun_choice_imp_ext_prop_repr\".  \nintros ReprFunChoice A.\npose (R P Q := P <-> Q).\nassert (Hequiv:Equivalence R) by (split; firstorder).\napply (ReprFunChoice _ R Hequiv).\nQed.\n\nTheorem repr_fun_choice_imp_ext_pred_repr :\nRepresentativeFunctionalChoice -> ExtensionalPredicateRepresentative.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.repr_fun_choice_imp_ext_pred_repr\".  \nintros ReprFunChoice A.\npose (R P Q := forall x : A, P x <-> Q x).\nassert (Hequiv:Equivalence R) by (split; firstorder).\napply (ReprFunChoice _ R Hequiv).\nQed.\n\nTheorem repr_fun_choice_imp_ext_function_repr :\nRepresentativeFunctionalChoice -> ExtensionalFunctionRepresentative.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.repr_fun_choice_imp_ext_function_repr\".  \nintros ReprFunChoice A B.\npose (R (f g : A -> B) := forall x : A, f x = g x).\nassert (Hequiv:Equivalence R).\n{ split; try easy. firstorder using eq_trans. }\napply (ReprFunChoice _ R Hequiv).\nQed.\n\n\n\nTheorem repr_fun_choice_imp_excluded_middle :\nRepresentativeFunctionalChoice -> ExcludedMiddle.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.repr_fun_choice_imp_excluded_middle\".  \nintros ReprFunChoice.\napply representative_boolean_partition_imp_excluded_middle, ReprFunChoice.\nQed.\n\nTheorem repr_fun_choice_imp_relational_choice :\nRepresentativeFunctionalChoice -> RelationalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.repr_fun_choice_imp_relational_choice\".  \nintros ReprFunChoice A B T Hexists.\npose (D := (A*B)%type).\npose (R (z z':D) :=\nlet x := fst z in\nlet x' := fst z' in\nlet y := snd z in\nlet y' := snd z' in\nx = x' /\\ (T x y -> y = y' \\/ T x y') /\\ (T x y' -> y = y' \\/ T x y)).\nassert (Hequiv : Equivalence R).\n{ split.\n- split. easy. firstorder.\n- intros (x,y) (x',y') (H1,(H2,H2')). split. easy. simpl fst in *. simpl snd in *.\nsubst x'. split; intro H.\n+ destruct (H2' H); firstorder.\n+ destruct (H2 H); firstorder.\n- intros (x,y) (x',y') (x'',y'') (H1,(H2,H2')) (H3,(H4,H4')).\nsimpl fst in *. simpl snd in *. subst x'' x'. split. easy. split; intro H.\n+ simpl fst in *. simpl snd in *. destruct (H2 H) as [<-|H0].\n* destruct (H4 H); firstorder.\n* destruct (H2' H0), (H4 H0); try subst y'; try subst y''; try firstorder.\n+ simpl fst in *. simpl snd in *. destruct (H4' H) as [<-|H0].\n* destruct (H2' H); firstorder.\n* destruct (H2' H0), (H4 H0); try subst y'; try subst y''; try firstorder. }\ndestruct (ReprFunChoice D R Hequiv) as (g,Hg).\nset (T' x y := T x y /\\ exists y', T x y' /\\ g (x,y') = (x,y)).\nexists T'. split.\n- intros x y (H,_); easy.\n- intro x. destruct (Hexists x) as (y,Hy).\nexists (snd (g (x,y))).\ndestruct (Hg (x,y)) as ((Heq1,(H',H'')),Hgxyuniq); clear Hg.\ndestruct (H' Hy) as [Heq2|Hgy]; clear H'.\n+ split. split.\n* rewrite <- Heq2. assumption.\n* exists y. destruct (g (x,y)) as (x',y'). simpl in Heq1, Heq2. subst; easy.\n* intros y' (Hy',(y'',(Hy'',Heq))).\nrewrite (Hgxyuniq (x,y'')), Heq. easy. split. easy.\nsplit; right; easy.\n+ split. split.\n* assumption.\n* exists y. destruct (g (x,y)) as (x',y'). simpl in Heq1. subst x'; easy.\n* intros y' (Hy',(y'',(Hy'',Heq))).\nrewrite (Hgxyuniq (x,y'')), Heq. easy. split. easy.\nsplit; right; easy.\nQed.\n\n\n\n\nTheorem gen_setoid_fun_choice_imp_setoid_fun_choice  :\nforall A B, GeneralizedSetoidFunctionalChoice_on A B -> SetoidFunctionalChoice_on A B.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.gen_setoid_fun_choice_imp_setoid_fun_choice\".  \nintros A B GenSetoidFunChoice R T Hequiv Hcompat Hex.\napply GenSetoidFunChoice; try easy.\napply eq_equivalence.\nintros * H <-. firstorder.\nQed.\n\nTheorem setoid_fun_choice_imp_gen_setoid_fun_choice :\nforall A B, SetoidFunctionalChoice_on A B -> GeneralizedSetoidFunctionalChoice_on A B.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.setoid_fun_choice_imp_gen_setoid_fun_choice\".  \nintros A B SetoidFunChoice R S T HequivR HequivS Hcompat Hex.\ndestruct SetoidFunChoice with (R:=R) (T:=T) as (f,Hf); try easy.\n{ intros; apply (Hcompat x x' y y); try easy. }\nexists f. intros x; specialize Hf with x as (Hf,Huniq). intuition. now erewrite Huniq.\nQed.\n\nCorollary setoid_fun_choice_iff_gen_setoid_fun_choice :\nforall A B, SetoidFunctionalChoice_on A B <-> GeneralizedSetoidFunctionalChoice_on A B.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.setoid_fun_choice_iff_gen_setoid_fun_choice\".  \nsplit; auto using gen_setoid_fun_choice_imp_setoid_fun_choice, setoid_fun_choice_imp_gen_setoid_fun_choice.\nQed.\n\nTheorem setoid_fun_choice_imp_simple_setoid_fun_choice  :\nforall A B, SetoidFunctionalChoice_on A B -> SimpleSetoidFunctionalChoice_on A B.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.setoid_fun_choice_imp_simple_setoid_fun_choice\".  \nintros A B SetoidFunChoice R T Hequiv Hexists.\npose (T' x y := forall x', R x x' -> T x' y).\nassert (Hcompat : forall (x x' : A) (y : B), R x x' -> T' x y -> T' x' y) by firstorder.\ndestruct (SetoidFunChoice R T' Hequiv Hcompat Hexists) as (f,Hf).\nexists f. firstorder.\nQed.\n\nTheorem simple_setoid_fun_choice_imp_setoid_fun_choice :\nforall A B, SimpleSetoidFunctionalChoice_on A B -> SetoidFunctionalChoice_on A B.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.simple_setoid_fun_choice_imp_setoid_fun_choice\".  \nintros A B SimpleSetoidFunChoice R T Hequiv Hcompat Hexists.\ndestruct (SimpleSetoidFunChoice R T Hequiv) as (f,Hf); firstorder.\nQed.\n\nCorollary setoid_fun_choice_iff_simple_setoid_fun_choice :\nforall A B, SetoidFunctionalChoice_on A B <-> SimpleSetoidFunctionalChoice_on A B.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.setoid_fun_choice_iff_simple_setoid_fun_choice\".  \nsplit; auto using simple_setoid_fun_choice_imp_setoid_fun_choice, setoid_fun_choice_imp_simple_setoid_fun_choice.\nQed.\n\n\n\n\nTheorem setoid_fun_choice_imp_fun_choice :\nforall A B, SetoidFunctionalChoice_on A B -> FunctionalChoice_on A B.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.setoid_fun_choice_imp_fun_choice\".  \nintros A B SetoidFunChoice T Hexists.\ndestruct SetoidFunChoice with (R:=@eq A) (T:=T) as (f,Hf).\n- apply eq_equivalence.\n- now intros * ->.\n- assumption.\n- exists f. firstorder.\nQed.\n\nCorollary setoid_fun_choice_imp_functional_rel_reification :\nforall A B, SetoidFunctionalChoice_on A B -> FunctionalRelReification_on A B.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.setoid_fun_choice_imp_functional_rel_reification\".  \nintros A B SetoidFunChoice.\napply fun_choice_imp_functional_rel_reification.\nnow apply setoid_fun_choice_imp_fun_choice.\nQed.\n\nTheorem setoid_fun_choice_imp_repr_fun_choice :\nSetoidFunctionalChoice -> RepresentativeFunctionalChoice .\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.setoid_fun_choice_imp_repr_fun_choice\".  \nintros SetoidFunChoice A R Hequiv.\napply SetoidFunChoice; firstorder.\nQed.\n\nTheorem functional_rel_reification_and_repr_fun_choice_imp_setoid_fun_choice :\nFunctionalRelReification -> RepresentativeFunctionalChoice -> SetoidFunctionalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.functional_rel_reification_and_repr_fun_choice_imp_setoid_fun_choice\".  \nintros FunRelReify ReprFunChoice A B R T Hequiv Hcompat Hexists.\nassert (FunChoice : FunctionalChoice).\n{ intros A' B'. apply functional_rel_reification_and_rel_choice_imp_fun_choice.\n- apply FunRelReify.\n- now apply repr_fun_choice_imp_relational_choice. }\ndestruct (FunChoice _ _ T Hexists) as (f,Hf).\ndestruct (ReprFunChoice A R Hequiv) as (g,Hg).\nexists (fun a => f (g a)).\nintro x. destruct (Hg x) as (Hgx,HRuniq).\nsplit.\n- eapply Hcompat. symmetry. apply Hgx. apply Hf.\n- intros y Hxy. f_equal. auto.\nQed.\n\nTheorem functional_rel_reification_and_repr_fun_choice_iff_setoid_fun_choice :\nFunctionalRelReification /\\ RepresentativeFunctionalChoice <-> SetoidFunctionalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.functional_rel_reification_and_repr_fun_choice_iff_setoid_fun_choice\".  \nsplit; intros.\n- now apply functional_rel_reification_and_repr_fun_choice_imp_setoid_fun_choice.\n- split.\n+ now intros A B; apply setoid_fun_choice_imp_functional_rel_reification.\n+ now apply setoid_fun_choice_imp_repr_fun_choice.\nQed.\n\n\n\n\n\n\nImport EqNotations.\n\n\n\n\n\nTheorem fun_choice_and_ext_functions_repr_and_excluded_middle_imp_setoid_fun_choice :\nFunctionalChoice -> ExtensionalFunctionRepresentative -> ExcludedMiddle -> RepresentativeFunctionalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.fun_choice_and_ext_functions_repr_and_excluded_middle_imp_setoid_fun_choice\".  \nintros FunChoice SetoidFunRepr EM A R (Hrefl,Hsym,Htrans).\nassert (H:forall P:Prop, exists b, b = true <-> P).\n{ intros P. destruct (EM P).\n- exists true; firstorder.\n- exists false; easy. }\ndestruct (FunChoice _ _ _ H) as (c,Hc).\npose (class_of a y := c (R a y)).\npose (isclass f := exists x:A, f x = true).\npose (class := {f:A -> bool | isclass f}).\npose (contains (c:class) (a:A) := proj1_sig c a = true).\ndestruct (FunChoice class A contains) as (f,Hf).\n- intros f. destruct (proj2_sig f) as (x,Hx).\nexists x. easy.\n- destruct (SetoidFunRepr A bool) as (h,Hh).\nassert (Hisclass:forall a, isclass (h (class_of a))).\n{ intro a. exists a. destruct (Hh (class_of a)) as (Ha,Huniqa).\nrewrite <- Ha. apply Hc. apply Hrefl. }\npose (f':= fun a => exist _ (h (class_of a)) (Hisclass a) : class).\nexists (fun a => f (f' a)).\nintros x. destruct (Hh (class_of x)) as (Hx,Huniqx). split.\n+ specialize Hf with (f' x). unfold contains in Hf. simpl in Hf. rewrite <- Hx in Hf. apply Hc. assumption.\n+ intros y Hxy.\nf_equal.\nassert (Heq1: h (class_of x) = h (class_of y)).\n{ apply Huniqx. intro z. unfold class_of.\ndestruct (c (R x z)) eqn:Hxz.\n- symmetry. apply Hc. apply -> Hc in Hxz. firstorder.\n- destruct (c (R y z)) eqn:Hyz.\n+ apply -> Hc in Hyz. rewrite <- Hxz. apply Hc. firstorder.\n+ easy. }\nassert (Heq2:rew Heq1 in Hisclass x = Hisclass y).\n{ apply proof_irrelevance_cci, EM. }\nunfold f'.\nrewrite <- Heq2.\nrewrite <- Heq1.\nreflexivity.\nQed.\n\nTheorem setoid_functional_choice_first_characterization :\nFunctionalChoice /\\ ExtensionalFunctionRepresentative /\\ ExcludedMiddle <-> SetoidFunctionalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.setoid_functional_choice_first_characterization\".  \nsplit.\n- intros (FunChoice & SetoidFunRepr & EM).\napply functional_rel_reification_and_repr_fun_choice_imp_setoid_fun_choice.\n+ intros A B. apply fun_choice_imp_functional_rel_reification, FunChoice.\n+ now apply fun_choice_and_ext_functions_repr_and_excluded_middle_imp_setoid_fun_choice.\n- intro SetoidFunChoice. repeat split.\n+ now intros A B; apply setoid_fun_choice_imp_fun_choice.\n+ apply repr_fun_choice_imp_ext_function_repr.\nnow apply setoid_fun_choice_imp_repr_fun_choice.\n+ apply repr_fun_choice_imp_excluded_middle.\nnow apply setoid_fun_choice_imp_repr_fun_choice.\nQed.\n\n\n\n\n\n\nTheorem fun_choice_and_ext_pred_ext_and_proof_irrel_imp_setoid_fun_choice :\nFunctionalChoice -> ExtensionalPredicateRepresentative -> ProofIrrelevance -> RepresentativeFunctionalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.fun_choice_and_ext_pred_ext_and_proof_irrel_imp_setoid_fun_choice\".  \nintros FunChoice PredExtRepr PI A R (Hrefl,Hsym,Htrans).\npose (isclass P := exists x:A, P x).\npose (class := {P:A -> Prop | isclass P}).\npose (contains (c:class) (a:A) := proj1_sig c a).\npose (class_of a := R a).\ndestruct (FunChoice class A contains) as (f,Hf).\n- intros c. apply proj2_sig.\n- destruct (PredExtRepr A) as (h,Hh).\nassert (Hisclass:forall a, isclass (h (class_of a))).\n{ intro a. exists a. destruct (Hh (class_of a)) as (Ha,Huniqa).\nrewrite <- Ha; apply Hrefl. }\npose (f':= fun a => exist _ (h (class_of a)) (Hisclass a) : class).\nexists (fun a => f (f' a)).\nintros x. destruct (Hh (class_of x)) as (Hx,Huniqx). split.\n+ specialize Hf with (f' x). simpl in Hf. rewrite <- Hx in Hf. assumption.\n+ intros y Hxy.\nf_equal.\nassert (Heq1: h (class_of x) = h (class_of y)).\n{ apply Huniqx. intro z. unfold class_of. firstorder. }\nassert (Heq2:rew Heq1 in Hisclass x = Hisclass y).\n{ apply PI. }\nunfold f'.\nrewrite <- Heq2.\nrewrite <- Heq1.\nreflexivity.\nQed.\n\nTheorem setoid_functional_choice_second_characterization :\nFunctionalChoice /\\ ExtensionalPredicateRepresentative /\\ ProofIrrelevance <-> SetoidFunctionalChoice.\nProof. hammer_hook \"ChoiceFacts\" \"ChoiceFacts.setoid_functional_choice_second_characterization\".  \nsplit.\n- intros (FunChoice & ExtPredRepr & PI).\napply functional_rel_reification_and_repr_fun_choice_imp_setoid_fun_choice.\n+ intros A B. now apply fun_choice_imp_functional_rel_reification.\n+ now apply fun_choice_and_ext_pred_ext_and_proof_irrel_imp_setoid_fun_choice.\n- intro SetoidFunChoice. repeat split.\n+ now intros A B; apply setoid_fun_choice_imp_fun_choice.\n+ apply repr_fun_choice_imp_ext_pred_repr.\nnow apply setoid_fun_choice_imp_repr_fun_choice.\n+ red. apply proof_irrelevance_cci.\napply repr_fun_choice_imp_excluded_middle.\nnow apply setoid_fun_choice_imp_repr_fun_choice.\nQed.\n\n\n\nNotation description_rel_choice_imp_funct_choice :=\nfunctional_rel_reification_and_rel_choice_imp_fun_choice (compat \"8.6\").\n\nNotation funct_choice_imp_rel_choice := fun_choice_imp_rel_choice (compat \"8.6\").\n\nNotation FunChoice_Equiv_RelChoice_and_ParamDefinDescr :=\nfun_choice_iff_rel_choice_and_functional_rel_reification (compat \"8.6\").\n\nNotation funct_choice_imp_description := fun_choice_imp_functional_rel_reification (compat \"8.6\").\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Logic/ChoiceFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6788328327610978}}
{"text": "Require Import List.\nImport ListNotations.\n\n(** *Bibliothèque standard *)\n\nPrint nat.\nLocate \"+\".\nPrint Nat.add.\nLocate \"*\".\nPrint Nat.mul.\n\nPrint list.\nLocate \"++\".\nPrint app.\n\nPrint True.\n\nPrint False.\n\nPrint or.\nLocate \"\\/\".\n\nPrint and.\nLocate \"/\\\".\n\nPrint not.\nLocate \"~\".\n\n(** *Logique : le tiers exclu *)\n\n(* Axiomes possibles pour la logique classique *)\n\nDefinition tiersExclu : Prop := forall P : Prop, P \\/ ~P. \nDefinition involutionNegation : Prop := forall P : Prop, ~~P -> P. \nDefinition implicationMaterielle : Prop := forall P Q : Prop, (P -> Q) -> (~P \\/ Q). \nDefinition reciproqueContraposition : Prop := forall P Q : Prop, (~Q -> ~P) -> (P -> Q). \n(* Indication pour la suite : si besoin, utiliser la tactique \"unfold\" pour déplier\n   la définition d'une des propositions précédentes. *)\n\n(* Réciproques valides *)\n\n(*\n  Indication :\n  - la négation *~P* est définie comme *P -> False*.            \n *)\nProposition reciproqueInvolutionNegation :\n  forall P : Prop, P -> ~~P.\nProof.\n  intros.\n  \n  simpl.\nAdmitted.\n\n(*\n  Indication :\n  - décomposer la disjonction en hypothèse,\n  - lorsque les hypothèses entrainent une contradiction,\n  utiliser la tactique exfalso.\n *)\nProposition reciproqueImplicationMaterielle :\n  forall P Q : Prop, (~P \\/ Q) -> P -> Q.\nProof.\nAdmitted.\n\nProposition contraposition :\n  forall P Q : Prop, (P -> Q) -> (~Q -> ~P).\nProof.\nAdmitted.\n\n(* Equivalence des axiomes *)\n\n(*\n  Indication :\n  - décomposer le tiers exclu appliqué à la proposition.\n *)\nProposition tiersExcluVersInvolutionNegation :\n  tiersExclu -> involutionNegation.\nProof.\nAdmitted.\n\n(*\n  Indication :\n  - appliquer l'involution de la négation à (P \\/ ~P),\n  - utiliser le fait que (~(P \\/ ~P)) entraine ~P,\n  - utiliser les tactiques \"left\" et \"right\" pour prouver une disjonction. \n *)\nProposition involutionNegationVersTiersExclu :\n  involutionNegation -> tiersExclu.\nProof.\nAdmitted.\n\n(*\n  Indication :\n  - décomposer la preuve de la disjonction (P \\/ ~P) obtenue en appliquant\n  le lemme involutionNegationVersTiersExclu à la proposition P.\n *)\nProposition involutionNegationVersImplicationMaterielle :\n  involutionNegation -> implicationMaterielle.\nProof.\nAdmitted.\n\nCheck or_comm.\n(*\n  Indication :\n  - utiliser la proposition or_comm exprimant la commutativité de la disjonction (or).\n *)\nProposition implicationMaterielleVersTiersExclu :\n  implicationMaterielle -> tiersExclu.\nProof.\nAdmitted.\n\n(*\n  Indication :\n  - utiliser deux propositions déjà montrées.\n *)\nProposition implicationMaterielleVersInvolutionNegation :\n  implicationMaterielle -> involutionNegation.\nProof.\nAdmitted.\n\n(*\n  Indication :\n  - utiliser l'involution de la négation.\n *)\nProposition implicationMaterielleVersReciproqueContraposition :\n  implicationMaterielle -> reciproqueContraposition.\nProof.\nAdmitted.\n\n(*\n  Indication :\n  - appliquer la réciproque de la contraposition à True et P.\n *)\nProposition reciproqueContrapositionVersInvolutionNegation :\n  reciproqueContraposition -> involutionNegation.\nProof.\nAdmitted.\n\n(** *Définitions inductives - La croissance de listes *)\n\nInductive EstCroissante : list nat -> Prop :=\n| videCroissante : EstCroissante []\n| singletonCroissante : forall a, EstCroissante [a]\n| consConsCroissante :\n    forall a b l, (a <= b)\n             -> EstCroissante (b :: l) -> EstCroissante( a :: b :: l).\n\n(*\n  --------- [precVide]\n  Prec m []\n  \n  (t : nat)  (r : list nat)  (m <= t)\n  ----------------------------------- [precCons]\n  Prec m (t :: r)\n *)\nInductive Prec(m : nat) : list nat -> Prop :=\n(* à modifier *)\n.\n\n\n(* à compléter\n   \n----------------- [videCroissante2]\n\n\n\n--------------------------------------------------------- [consCroissante2]\n\n *)\n\nInductive EstCroissante2 : list nat -> Prop :=\n(* à modifier *)\n.\n\n(*\n  Indication :\n  - procéder par induction sur la preuve de (EstCroissante2 l) ;\n  dans le cas d'une liste non vide, décomposer par cas la preuve\n  du prédicat Prec.\n *)\nProposition adequation_estCroissante2 : forall l,\n    EstCroissante2 l -> EstCroissante l.\nProof.\nAdmitted.\n\n(*\n  Indication :\n  - procéder par induction sur la preuve de (EstCroissante l).\n *)\nProposition completude_estCroissante2 : forall l,\n    EstCroissante l -> EstCroissante2 l.\nProof.\nAdmitted.\n\n(** *Définitions inductives - Facteurs d'une liste *)\n\nProposition associativite_concatenation :\n  forall T : Type,\n  forall l1 l2 l3 : list T,\n    l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\nProof.\nAdmitted.\n\n\n(* à compléter \n  \n------------------ [facteurPrefixe]\n\n\n\n-------------------------------- [facteurInterne]\n\n *)\n\nInductive Facteur{A : Type}(k : list A) : list A -> Prop :=\n| facteurPrefixe : forall l, Facteur k l (* à modifier *)\n| facteurInterne : forall l, Facteur k l. (* à modifier *)\n\n(*\n  Indication :\n  - procéder par induction sur la preuve de *Facteur k l*,\n  - pour prouver l'existence, utiliser la tactique \"exists w\", où w est le terme\n  montrant l'existence.\n *)\nLemma adequation_Facteur :\n  forall A, forall k l : list A, Facteur k l -> exists k' k'', k' ++ k ++ k'' = l.\nProof.\nAdmitted.  \n\n(*\n  Indication :\n  - utiliser directement les constructeurs de Facteur.\n *)\nLemma completude_Facteur :\n  forall A, forall k' k k'' l : list A, k' ++ k ++ k'' = l -> Facteur k l.\nProof.\nAdmitted.  \n\n(** *Entiers naturels - Des fonctions et des propositions utiles *)\n\n(* Addition et ordre *)\n\nLemma neutraliteDroite_addition :\n  forall n : nat, n = n + 0.\nProof.\nAdmitted.\n\nLemma sommeSuccesseurs :\n  forall n m : nat,\n    S n + S m = S (S (n + m)).\nProof.\nAdmitted.\n\n(*\n  Indication :\n  - procéder par induction sur la preuve de (n2 <= n3).\n *)\nProposition transitivite_le :\n  forall n1 n2 n3, n1 <= n2 -> n2 <= n3 -> n1 <= n3.\nProof.\nAdmitted.\n\nProposition zeroMin_le :\n  forall n, 0 <= n.\nProof.\nAdmitted.\n\nLemma successeurCroissant_le :\n  forall m n, m <= n -> S m <= S n.\nProof.\nAdmitted.\n\n(*\n  Indication :\n  - procéder par induction sur m,\n  - utiliser successeurCroissant_le.\n *)\nLemma compatibiliteAdditionGauche_le : \n  forall m n1 n2, n1 <= n2 -> (m + n1) <= (m + n2).\nProof.\nAdmitted.\n\n(*\n  Indication :\n  - procéder par induction sur la preuve de (m1 <= m2),\n  - utiliser compatibiliteAdditionGauche_le.\n *)\nProposition compatibiliteAddition_le :\n  forall m1 m2 n1 n2, m1 <= m2 -> n1 <= n2 -> (m1 + n1) <= (m2 + n2).\nProof.\nAdmitted.\n\n(*\n  Indication :\n  - utiliser compatibiliteAddition_le.\n *)\nProposition compatibiliteAddition_zeroMinDroite_le :\n  forall m1 m2 n, m1 <= m2 -> m1 <= (m2 + n).\nProof.\nAdmitted.\n\n(* Maximum et puissance *)\n\nFixpoint max(m n : nat) : nat.\n  exact (Nat.max m n). (* à modifier *)\nDefined.\n\n(*\n  Indication :\n  - procéder par induction sur m, avec une hypothèse de récurrence\n  quantifiée universellement sur n. \n *)\nProposition commutativite_max :\n  forall m n, max m n = max n m.\nProof.\nAdmitted.\n\nProposition idempotence_max :\n  forall n, n = max n n.\nProof.\nAdmitted.\n\n(*\n  Indication :\n  - procéder par induction sur m, avec une hypothèse de récurrence\n  quantifiée universellement sur n. \n *)\nProposition majorantGauche_max :\n  forall m n, m <= max m n.\nProof.\nAdmitted.\n\n(*\n  Indication :\n  - utiliser la commutativité.\n *)\nProposition majorantDroite_max :\n  forall m n, n <= max m n.\nProof.\nAdmitted.\n\nFixpoint puissance(m n : nat) : nat.\n  exact (Nat.pow m n). (* à modifier *)\nDefined.\n\n(*\n  Indication :\n  - procéder par induction sur la preuve de (n1 <= n2).\n *)\nProposition croissance_puissance :\n  forall (m n1 n2 : nat),\n    n1 <= n2 -> puissance (S m) n1 <= puissance (S m) n2.\nProof.\nAdmitted.\n\n(** *Arbres binaires - Un encadrement de la taille    *)\n\n(* à compléter\n\n-------  [arbreVide]\n\n\n\n-----------------------  [arbreCons]\n\n*)\n \nInductive Arbre(T : Type) : Type :=\n(* à modifier *)\n.\n\nProposition principeInductif_Arbre : \n  forall (T : Type) (P : Arbre T -> Prop),\n    (* à compléter *)\n    forall (a : Arbre T), P a.\nProof.\nAdmitted.\n\nFixpoint hauteur{T : Type}(a : Arbre T) : nat.\n  exact 0. (* à modifier *)\nDefined.\n\nFixpoint taille{T : Type}(a : Arbre T) : nat.\n  exact 0. (* à modifier *)\nDefined.\n\nDefinition unArbre : Arbre nat.\nAdmitted.\n\n\nExample hauteurArbre : hauteur (unArbre) = 3.\nAdmitted.\n\nExample tailleArbre : taille (unArbre) = 5.\nAdmitted.\n\n(*\n  Indication :\n  - procéder par induction sur l'arbre,\n  - utiliser les propositions démontrées sur les entiers naturels.\n *)\nProposition majorationTaille_Arbre :\n  forall T : Type,\n  forall a : Arbre T,\n    S (taille a) <= (puissance 2 (hauteur a)). \nProof.\nAdmitted.\n\n(*\n  Indication :\n  - décomposer la preuve de (inhabited T) en hypothèse \n  pour obtenir un élément de T,            \n  - procéder par induction sur n,\n  - utiliser les propositions démontrées sur les entiers naturels,\n  - pour prouver une conjonction, utiliser \"split\".\n *)\nPrint inhabited.\nProposition majorationOptimaleTaille_Arbre :\n  forall T : Type,\n    inhabited T ->\n    forall n : nat,\n    exists a : Arbre T,\n      hauteur a = n\n      /\\\n      S (taille a) = (puissance 2 (hauteur a)). \nProof.\nAdmitted.\n", "meta": {"author": "Naedri", "repo": "Coq-lessons", "sha": "de4a20047a4255f43fcf6486ea2733dd6d6afabe", "save_path": "github-repos/coq/Naedri-Coq-lessons", "path": "github-repos/coq/Naedri-Coq-lessons/Coq-lessons-de4a20047a4255f43fcf6486ea2733dd6d6afabe/Exam/coq_logic_sujet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6788328215563296}}
{"text": "\n(* Import in the following order to minimize trouble:\n   stdlib, old corn things, mathclasses, new corn things *)\n\nRequire Import Limit.\nRequire Import abstract_algebra orders additional_operations streams series.\n\n(*\nLemma forall_impl {A} (P Q: ∞ A → Prop) (H1:∀ t, P t → Q t) :\n ∀ t, ForAll P t → ForAll Q t.\nProof.\n cofix G. \n split.\n apply (H1 t). \n destruct H as [Ha _]. \n exact Ha.\n destruct H as [_ Hb].\n apply (G (tl t) Hb).\nQed.\n*)\n\n(** This section is about computing a generalized version of\n a geometric series.\n\n A geometric series has the form $s_{i+1} = r * s_i$ for some\n ratio $0 < r < 1$ (should we allow negative values for $a$\n the series will be alternating, however, we don't allow this).\n\n We impose a further positivity restriction on the elements\n of the series, $0 ≤ s_i$.\n\n*)\n\nSection geom_sum.\n\n(** We work abstractly of an ordered ring R *)\nContext `{FullPseudoSemiRingOrder R}.\n\n(** R is not automatically a SemiRing as this causes loops in\n   instance search. So we add it locally as this is needed for\n   rewrites, e.g. (1)\n*)\nInstance: SemiRing R := pseudo_srorder_semiring.\n\n(** A geometric series is a series with a constant ratio\n    between succesive terms. Here we parametrize by this ratio\n*)\nVariable r : R.\nHypothesis Hr : 0 < r < 1.\n\n\n(** A slightly stricter (positive) version of [GeometricSeries],\n  which specifies a slightly more general (less-than instead of\n  equality) version of a geometric series.\n*)\nDefinition ARGeometricSeries : ∞ R → Prop :=\n  ForAll (λ xs, 0 ≤ hd (tl xs) ≤ r * hd xs).\n\n\nSection properties.\n\nContext `(gs: ARGeometricSeries s).\n\n(** If [s] is a geometric series, then so is it's tail *)\nLemma gs_tl : ARGeometricSeries (tl s).\nProof.\n  apply ForAll_tl; now assumption.\nQed.\n\n(** Every element in a geometric series is positive *)\nLemma gs_positive : 0 ≤ hd s.\nProof.\n  destruct gs as [GS FA].\n  apply (maps.order_reflecting_pos (.*.) r); try tauto.\n  rewrite rings.mult_0_r.\n  transitivity (hd (tl s)); tauto.\nQed. \n\n(** A geometric series is always decreasing *)\nLemma gs_decreasing : hd (tl s) ≤ hd s.\nProof.\n  destruct gs.\n  apply (maps.order_reflecting_pos (.*.) r); try tauto.\n  transitivity (hd (tl s)); try tauto.\n  rewrite <- (rings.mult_1_l (hd (tl s))) at 2.\n  apply semirings.mult_le_compat; try solve [apply orders.lt_le; tauto].\n   tauto.\n  reflexivity. \nQed.\n\nNotation \"'x₀'\" := (hd s).\n\n(* if only...\n\n   Notation \"'xₙ₊1'\" := (Str_nth (n + 1) s).\n   Notation \"'xₙ'\"   := (Str_nth n s).\n*)\nRequire Import nat_pow.\n\nLemma helper n `{xs:∞A} : Str_nth (1 + n) xs ≡ hd (tl (Str_nth_tl n xs)).\nAdmitted.\n\n(* [peano_naturals.nat_induction] is a induction scheme that uses\n   type classed naturals. *)\n\nLemma gs_nth_rn n : Str_nth n s ≤ r^n * x₀.\nProof.\n  induction n using peano_naturals.nat_induction.\n   rewrite nat_pow_0, rings.mult_1_l; compute; reflexivity.\n  rewrite nat_pow_S.\n  apply (ForAll_Str_nth_tl n) in gs.\n  destruct gs as [[GS1 GS2] FA].\n  replace (hd (Str_nth_tl n s)) with (Str_nth n s) in GS2 by auto.\n  replace (hd (tl (Str_nth_tl n s))) with (Str_nth (1+n) s) in GS2.\n  transitivity (r * Str_nth n s); [assumption|].\n  rewrite <- associativity.\n  apply (maps.order_preserving_nonneg (.*.) r).\n   apply orders.lt_le. destruct Hr as [Ha Hb].\n  auto.\n  assumption.\n  apply helper.\nAdmitted.\n\nEnd properties.\n\n(** A geometric series is decreasing and non negative. *)\nLemma gs_dnn `(gs: ARGeometricSeries s) : DecreasingNonNegative s.\nProof.\n revert s gs.\n cofix FIX; intros s gs.\n constructor.\n  now split; auto using gs_positive, gs_tl, gs_decreasing.\n now apply FIX, gs_tl.\nQed.\n\nEnd geom_sum.", "meta": {"author": "coq-community", "repo": "corn", "sha": "cfbf6b297643935f0fe7e22d2b14b462bf7e3095", "save_path": "github-repos/coq/coq-community-corn", "path": "github-repos/coq/coq-community-corn/corn-cfbf6b297643935f0fe7e22d2b14b462bf7e3095/broken/abstract_gsum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6787806279701287}}
{"text": "Require Import Reals Interval.Tactic.\n\nGoal forall x, (-1 / 3 <= x - x <= 1 / 7)%R.\nProof.\nintros x.\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/bug-20150925.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6787676224425846}}
{"text": "Require Import Util CSet StableFresh Even.\nRequire Import InfiniteSubset SafeFirstInfiniteSubset Take TakeSet.\n\nSet Implicit Arguments.\n\nRecord inf_partition  X `{OrderedType X}  :=\n  { part_1 : inf_subset X;\n    part_2 : inf_subset X;\n    part_disj : forall x, part_1 x -> part_2 x -> False;\n    part_cover : forall x, part_1 x + part_2 x;\n  }.\n\nArguments inf_partition X {H}.\n\nLemma part_dich  X `{OrderedType X}  (p:inf_partition X) x\n  : (part_1 p x /\\ (part_2 p x -> False)) \\/ (part_2 p x /\\ (part_1 p x -> False)).\nProof.\n  destruct (part_cover p x);\n    pose proof (part_disj p x); cset_tac.\nQed.\n\nDefinition even_part : inf_partition nat.\nProof.\n  refine (Build_inf_partition even_inf_subset odd_inf_subset _ _).\n  - intros.\n    unfold even_inf_subset in H. simpl in H.\n    unfold odd_inf_subset in H0. simpl in H0.\n    unfold odd in H0. unfold negb in H0. cases in H0; eauto.\n  - intros.\n    unfold even_inf_subset, odd_inf_subset, odd, negb; simpl.\n    cases; eauto.\nDefined.\n\nDefinition even_part_pos : inf_partition positive.\nProof.\n  refine (Build_inf_partition even_inf_subset_pos odd_inf_subset_pos _ _).\n  - intros.\n    unfold even_inf_subset in H. simpl in H.\n    unfold odd_inf_subset in H0. simpl in H0.\n    unfold odd in H0. unfold negb in H0. cases in H0; eauto.\n  - intros.\n    unfold even_inf_subset, odd_inf_subset, odd, negb; simpl.\n    rewrite <- even_pos_fast_correct.\n    eapply even_or_odd.\nDefined.\n\nArguments even_part_pos : simpl never.\nArguments even_part : simpl never.\n\n(*\nRequire Import SafeFirst.\n\nLemma fresh_variable_always_exists_in_inf_subset X `{NaturalRepresentationSucc X}\n      `{@NaturalRepresentationMax X H H0}\n      (lv:set X) (p:inf_subset X) n\n: safe (fun x => x ∉ lv /\\ p x) n.\nProof.\n  - decide (_lt (SetInterface.fold max lv (ofNat 0)) n).\n    + decide (p n).\n      * econstructor. split; eauto.\n        intro. cset_tac'.\n        eapply (@fold_max_lt X _ _ _ _) in H5; eauto.\n        simpl in *. exfalso. nr. simpl in *. omega.\n        eapply (@fold_max_lt X _ _ _ _) in H5; eauto.\n        simpl in *. exfalso. nr. simpl in *. omega.\n      * edestruct (inf_subset_inf p n); dcr. cbn in *.\n        eapply (@safe_antitone _ _ _ _ _ _ _ x); eauto.\n        econstructor; split; eauto.\n        intro. cset_tac'.\n        eapply (@fold_max_lt X _ _ _ _) in H8; eauto.\n        simpl in *. exfalso. nr. simpl in *. omega.\n        eapply (@fold_max_lt X _ _ _ _) in H8; eauto.\n        simpl in *. exfalso. nr. simpl in *. omega.\n    + decide (p (succ (SetInterface.fold max lv (ofNat 0)))).\n      * eapply safe_antitone. eauto.\n        instantiate (1:=succ (SetInterface.fold max lv (ofNat 0))).\n        econstructor. split; eauto. intro.\n        cset_tac'.\n        eapply (@fold_max_lt X _ _ _ _) in H5; eauto.\n        simpl in *. exfalso. nr. simpl in *. omega.\n        eapply (@fold_max_lt X _ _ _ _) in H5; eauto.\n        simpl in *. exfalso. nr. simpl in *. omega.\n        simpl in *. nr. omega.\n      * edestruct (inf_subset_inf p (succ (fold max lv (ofNat 0))));\n          dcr.\n        eapply (@safe_antitone _ _ _ _ _ _ _ x).\n        econstructor; split; eauto.\n        cset_tac'.\n        eapply (@fold_max_lt X _ _ _ _) in H8; eauto.\n        simpl in *. exfalso. clear H6. nr. omega.\n        eapply (@fold_max_lt X _ _ _ _) in H8; eauto.\n        simpl in *. exfalso. clear H6. nr. omega.\n        simpl in *. clear H6. nr. omega.\n        Grab Existential Variables. eauto. eauto.\nQed.\n*)\n\n\nLemma fresh_variable_always_exists_in_inf_subset X `{OrderedType X}\n      (lv:set X) (p:inf_subset X) k\n  : forall n, cardinal lv <= n ->\n         SafeFirstInfiniteSubset.safe p (fun x => x ∉ lv /\\ p x) k.\nProof.\n  intros. general induction n.\n  - exploit (@cardinal_inv_1 _ _ _ _ lv); try omega; eauto.\n    econstructor. intros.\n    econstructor; intros.\n    exfalso. revert H3. destr_sig. cset_tac.\n  - econstructor; intros. clear H1.\n    decide ((proj1_sig (inf_subset_inf p k)) ∈ lv).\n    + econstructor; intros.\n      eapply safe_impl'.\n      eapply (IHn (lv \\ singleton (proj1_sig (inf_subset_inf p k))) p).\n      * rewrite cardinal_difference'; [|cset_tac].\n        rewrite singleton_cardinal. omega.\n      * revert i H1. repeat destr_sig. dcr. intros. cset_tac'.\n        -- rewrite <- H10 in *. clear H10 x1. clear_trivial_eqs. eauto.\n    + econstructor; intros.\n      exfalso. revert n0 H1.\n      destr_sig. cset_tac.\nQed.\n\nDefinition least_fresh_P X `{OrderedType X}\n           (p:inf_subset X) (lv:set X) : X.\n  refine (@safe_first X H p (fun x => x ∉ lv /\\ p x) _ (proj1_sig (inf_subset_least p)) _).\n  eapply fresh_variable_always_exists_in_inf_subset. reflexivity.\nDefined.\n\n(*Definition least_fresh_P' X `{OrderedType X}\n           (p:inf_subset X) (lv:set X) : X.\n  refine (@SafeFirstInfiniteSubset.safe_first X H p (fun x => x ∉ lv /\\ p x) _\n                                              (proj1_sig (inf_subset_least p)) _).\n  - eapply fresh_variable_always_exists_in_inf_subset; eauto.\nDefined.*)\n\nLemma least_fresh_P_full_spec X `{OrderedType X}\n      p (G:set X)\n  : least_fresh_P p G ∉ G\n    /\\ (forall m, p m ->  _lt m (least_fresh_P p G) -> m ∈ filter p G)\n    /\\ p (least_fresh_P p G).\nProof.\n  unfold least_fresh_P.\n  eapply safe_first_spec with\n  (I:= fun n => forall m, p m -> _lt m n -> m ∈ filter p G).\n  - intros. rewrite de_morgan_dec, <- in_dneg in H1.\n    destruct H1.\n    + decide (m === n); subst; eauto.\n      * cset_tac.\n      * exploit (H0 m); eauto.\n        revert H3. destr_sig; dcr; intros.\n        edestruct (H6 m); eauto.\n        cset_tac.\n    + decide (m === n); subst; eauto.\n      * exfalso. eapply H1. rewrite <- e. eauto.\n      * exploit (H0 m); eauto.\n        revert H3. destr_sig; dcr; intros.\n        edestruct (H6 m); eauto.\n        cset_tac.\n  - intros. cset_tac.\n  - intros. exfalso.\n    revert H1. destr_sig; dcr; intros.\n    edestruct (H2 m); eauto.\nQed.\n\nLemma least_fresh_P_ext  X `{OrderedType X} p (G G' : ⦃X⦄)\n  : G [=] G' -> least_fresh_P p G = least_fresh_P p G'.\nProof.\n  intros. unfold least_fresh_P; eauto.\n  eapply safe_first_ext. intros. rewrite H0. reflexivity.\nQed.\n\nLemma least_fresh_P_p X `{OrderedType X} (p:inf_subset X) G\n  : p (least_fresh_P p G).\nProof.\n  eapply least_fresh_P_full_spec.\nQed.\n\nDefinition stable_fresh_P  X `{OrderedType X} (isub:inf_subset X) : StableFresh X.\n  refine (Build_StableFresh (fun lv _ => least_fresh_P isub lv) _ _).\n  - intros. eapply least_fresh_P_full_spec.\n  - intros. eapply least_fresh_P_ext; eauto.\nDefined.\n\nLemma semantic_branch (P Q:Prop) `{Computable Q}\n  : P \\/ Q -> ((~ Q /\\ P) \\/ Q).\nProof.\n  decide Q; clear H; intros; intuition.\nQed.\n\nDefinition least_fresh_P_oracle X `{OrderedType X}\n           (p:inf_subset X) (lv:set X) (o:X->X) (x:X) :=\n  let y := o x in\n  if [p y /\\ y ∉ lv]\n  then y\n  else least_fresh_P p lv.\n\nDefinition least_fresh_part X `{OrderedType X} (p:inf_partition X) (o2:X -> X)\n           (G:set X) x :=\n  if part_1 p x then\n    least_fresh_P (part_1 p) G\n  else\n    least_fresh_P_oracle (part_2 p) G o2 x.\n\nLemma least_fresh_part_fresh X `{OrderedType X} p G x o2\n  : least_fresh_part p o2 G x ∉ G.\nProof.\n  unfold least_fresh_part; cases; eauto.\n  - eapply least_fresh_P_full_spec.\n  - unfold least_fresh_P_oracle. cases; dcr; eauto.\n    eapply least_fresh_P_full_spec.\nQed.\n\nLemma least_fresh_part_1 X `{OrderedType X} (p:inf_partition X) G x o2\n  : part_1 p x\n    -> part_1 p (least_fresh_part p o2 G x).\nProof.\n  unfold least_fresh_part; intros; cases.\n  eapply least_fresh_P_full_spec.\nQed.\n\nLemma least_fresh_part_2  X `{OrderedType X} (p:inf_partition X) G x o2\n  : part_2 p x\n    -> part_2 p (least_fresh_part p o2 G x).\nProof.\n  unfold least_fresh_part; intros. cases.\n  - exfalso. eapply (part_disj p); eauto.\n  - unfold least_fresh_P_oracle. cases; dcr; eauto.\n    eapply least_fresh_P_full_spec.\nQed.\n\n\nLemma least_fresh_part_p1 X `{OrderedType X}\n      (p:inf_partition X) G x o2\n  : part_1 p (least_fresh_part p o2 G x) -> part_1 p x.\nProof.\n  intros. edestruct part_cover; eauto.\n  eapply least_fresh_part_2 in i.\n  exfalso. eapply part_disj in H0; eauto.\nQed.\n\nLemma least_fresh_part_p2 X `{OrderedType X}\n      (p:inf_partition X) G x o2\n  : part_2 p (least_fresh_part p o2 G x) -> part_2 p x.\nProof.\n  intros. edestruct part_cover; eauto.\n  eapply least_fresh_part_1 in i.\n  exfalso. eapply part_disj in H0; eauto.\nQed.\n\nLemma least_fresh_part_ext  X `{OrderedType X} p (G G' : ⦃X⦄) x o2\n  : G [=] G' -> least_fresh_part p o2 G x = least_fresh_part p o2 G' x.\nProof.\n  intros. unfold least_fresh_part, least_fresh_P_oracle; repeat cases; eauto using least_fresh_P_ext.\n  exfalso. cset_tac.\n  exfalso. cset_tac.\nQed.\n\nDefinition stable_fresh_part  X `{OrderedType X} (p:inf_partition X) (o2:X->X) : StableFresh X.\n  refine (Build_StableFresh (least_fresh_part p o2) _ _).\n  - intros. eapply least_fresh_part_fresh.\n  - intros. eapply least_fresh_part_ext; eauto.\nDefined.\n\nLemma least_fresh_list_part_ext  X `{OrderedType X} p n G G' o2\n  : G [=] G'\n    -> fst (fresh_list_stable (stable_fresh_part p o2) G n)\n      = fst (fresh_list_stable (stable_fresh_part p o2) G' n).\nProof.\n  eapply fresh_list_stable_ext.\n  intros. eapply least_fresh_part_ext; eauto.\nQed.\n\nLemma fresh_list_stable_P_ext  X `{OrderedType X} p G L L'\n  : ❬L❭ = ❬L'❭\n    -> of_list (fst (fresh_list_stable (stable_fresh_P p) G L))\n              ⊆ of_list (fst (fresh_list_stable (stable_fresh_P p) G L')).\nProof.\n  intros. hnf; intros ? In.\n  general induction H0; simpl in *.\n  - cset_tac.\n  - revert In. repeat let_pair_case_eq; repeat simpl_pair_eqs; subst; simpl; eauto.\n    cset_tac.\nQed.\n\nLemma fresh_list_stable_P_ext_eq  X `{OrderedType X} p G L L'\n  : ❬L❭ = ❬L'❭\n    -> of_list (fst (fresh_list_stable (stable_fresh_P p) G L))\n              [=] of_list (fst (fresh_list_stable (stable_fresh_P p) G L')).\nProof.\n  split; intros.\n  - eapply fresh_list_stable_P_ext; eauto.\n  - eapply fresh_list_stable_P_ext; [symmetry|]; eauto.\nQed.\n\n\nLemma least_fresh_part_1_back  X `{OrderedType X} (p:inf_partition X) G x o2\n  : part_1 p (least_fresh_part p o2 G x ) -> part_1 p x.\nProof.\n  intros.\n  decide (part_1 p x); eauto.\n  destruct (part_cover p x); eauto.\n  eapply least_fresh_part_2 in i.\n  edestruct (part_disj p); eauto.\nQed.\n\nLemma least_fresh_part_2_back  X `{OrderedType X} (p:inf_partition X) G x o2\n  : part_2 p (least_fresh_part p o2 G x) -> part_2 p x.\nProof.\n  intros.\n  decide (part_2 p x); eauto.\n  destruct (part_cover p x); eauto.\n  eapply least_fresh_part_1 in i.\n  edestruct (part_disj p); eauto.\nQed.\n\nLemma cardinal_filter_part  X `{OrderedType X} p G Z o2\n      (UNIQ:NoDupA _eq Z)\n  : cardinal (filter (part_1 p)\n                     (of_list (fst (fresh_list_stable (stable_fresh_part p o2) G Z))))\n    = cardinal (filter (part_1 p) (of_list Z)).\nProof.\n  general induction Z; simpl.\n  - reflexivity.\n  -  repeat let_pair_case_eq; repeat simpl_pair_eqs; subst; simpl.\n    decide (part_1 p a).\n    + rewrite filter_add_in; eauto using least_fresh_part_1.\n      rewrite filter_add_in; eauto.\n      rewrite !add_cardinal_2; eauto.\n      * intro. inv UNIQ. cset_tac.\n      * exploit (fresh_list_stable_spec (stable_fresh_part p o2));\n        eauto using least_fresh_part_fresh.\n        cset_tac'.\n        eapply H0; cset_tac.\n    + rewrite filter_add_notin; eauto.\n      rewrite filter_add_notin; eauto.\n      eauto using least_fresh_part_1_back.\nQed.\n\nLemma cardinal_smaller  X `{OrderedType X}\n      p n (G:set X) (Z:list X) x o2\n      (GET:get Z n x) (P1:part_1 p x) (ND: NoDupA _eq Z)\n  : SetInterface.cardinal\n    (filter (part_1 p)\n       (of_list\n          (take n\n             (fst\n                (fresh_list_stable (stable_fresh_part p o2) G Z)))))\n    < SetInterface.cardinal (filter (part_1 p) (of_list Z)).\nProof.\n  general induction Z; simpl;\n    let_pair_case_eq; simpl_pair_eqs; subst; simpl; destruct n; simpl.\n  - inv GET.\n    + rewrite filter_incl; eauto. rewrite empty_cardinal.\n      rewrite filter_add_in; eauto.\n      rewrite add_cardinal_2. omega. inv ND.\n      rewrite filter_incl; eauto.\n  - inv GET.\n    + decide (part_1 p a).\n      * rewrite filter_add_in; eauto using least_fresh_part_1.\n        rewrite filter_add_in; eauto.\n        rewrite !add_cardinal_2.\n        -- eapply lt_n_S.\n           eapply IHZ; eauto.\n        -- rewrite filter_incl; eauto.\n        -- rewrite filter_incl, take_list_incl; eauto.\n           hnf; intro IN.\n           eapply fresh_list_stable_spec in IN. cset_tac.\n      * rewrite filter_add_notin; eauto using least_fresh_part_1.\n        rewrite filter_add_notin; eauto.\n        intro; eapply n0. eapply least_fresh_part_p1; eauto.\nQed.\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Infra/InfinitePartition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6787602137937863}}
{"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 Definitions.\n\nRequire Import utils pos vec. \nRequire Import subcode sss. \nRequire Import tiles_solvable bsm_defs bsm_pcp.\n\nFact tile_concat_itau ln lt : tile_concat ln lt = (itau1 lt (rev ln), itau2 lt (rev ln)).\nProof.\n  induction ln as [ | i ln IH ]; simpl; auto.\n  rewrite itau1_app, itau2_app; simpl.\n  unfold card, string; generalize (nth i lt ([] / [])); intros (a,b); rewrite IH.\n  repeat rewrite <- app_nil_end; auto.\nQed.\n\n(* tiles_solvable & iBPCP is the same predicate except that the existentially\n   quantified list is reversed *)\n\nTheorem tiles_solvable_iBPCP lt : tiles_solvable lt <-> iBPCP lt.\nProof.\n  split.\n  + intros (ln & H1 & H2 & H3).\n    rewrite tile_concat_itau in H3.\n    exists (rev ln). \n    rewrite <- Forall_forall.\n    repeat split; auto.\n    * apply Forall_rev; auto.\n    * contradict H1; rewrite <- (rev_involutive ln), H1; auto.\n  + intros (ln & H1 & H2 & H3).\n    exists (rev ln).\n    rewrite tile_concat_itau, rev_involutive.\n    repeat split; auto.\n    * contradict H2; rewrite <- (rev_involutive ln), H2; auto.\n    * apply Forall_rev, Forall_forall; auto.\nQed.\n\nLocal Notation \"P // s ->> t\" := (sss_compute (@bsm_sss _) P s t).\nLocal Notation \"P // s ~~> t\" := (sss_output (@bsm_sss _) P s t).\nLocal Notation \"P // s ↓\" := (sss_terminates (@bsm_sss _) P s). \n\nSection iBPCP_BSM_HALTING.\n\n  Let f (lt : list (card bool)) : BSM_PROBLEM.\n  Proof.\n    exists 4, 1, (pcp_bsm lt).\n    exact (vec_set_pos (fun _ => nil)).\n  Defined.\n\n  Goal forall x, | pcp_bsm x| >= 80.\n    intros; rewrite pcp_bsm_size; omega.\n  Qed.\n  \n  Theorem iBPCP_BSM_HALTING : iBPCP ⪯ BSM_HALTING.\n  Proof.\n    exists f.\n    intros lt.\n    rewrite <- tiles_solvable_iBPCP.\n    unfold BSM_HALTING; split.\n    * intros H.\n      apply pcp_bsm_sound with (v := vec_set_pos (fun _ => nil)) in H.\n      match type of H with  _ // _ ->> (?q,?w) => exists (q, w) end.\n      split; auto.\n      simpl; omega.\n    * intros ((q & w) & H).\n      apply pcp_bsm_complete in H; tauto.\n  Qed.\n\nEnd iBPCP_BSM_HALTING.\n\n", "meta": {"author": "uds-psl", "repo": "ill-undecidability", "sha": "0bfda1a33cb3411c8f2c0263e15d5c85c090721d", "save_path": "github-repos/coq/uds-psl-ill-undecidability", "path": "github-repos/coq/uds-psl-ill-undecidability/ill-undecidability-0bfda1a33cb3411c8f2c0263e15d5c85c090721d/coq/iBPCP_BSM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6787602085483385}}
{"text": "Theorem noncontradiction : forall P : Prop, P /\\ ~ P -> False.\nProof.\n  intros P pf_P_and_nP.\n  unfold not in pf_P_and_nP.\n  destruct pf_P_and_nP as (pf_P & pf_nP).\n  exact (pf_nP pf_P).\nQed.\n\nTheorem explosion : forall P : Prop, False -> P.\nProof.\n  intros P pf_False.\n  case pf_False.\nQed.", "meta": {"author": "Riib11", "repo": "Coq-Work", "sha": "e163edd331fd15549910f0fe0a361bc93ca951d7", "save_path": "github-repos/coq/Riib11-Coq-Work", "path": "github-repos/coq/Riib11-Coq-Work/Coq-Work-e163edd331fd15549910f0fe0a361bc93ca951d7/Practice/Contradiction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6787601957157726}}
{"text": "\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n\nFixpoint even (even_arg0 : natural) : bool\n           := match even_arg0 with\n              | Zero => true\n              | Succ n => negb (even n)\n              end.\n\nLemma lem: forall m n, even (plus m n) = negb (even (plus m (Succ n))).\nProof.\ninduction m.\n  - intros. simpl. rewrite <- IHm. reflexivity.\n  - intros. simpl. unfold negb. destruct (even n). reflexivity. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : natural), eq (even (plus x x)) true.\nProof.\ninduction x.\n- simpl. rewrite <- lem. assumption.\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/goal16.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6786653896613344}}
{"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(** ** Bitwise operations on nat *)\n\nRequire Import Arith Nat Omega List Bool Setoid.\nRequire Import utils_tac utils_list utils_nat bool_list gcd sums power_decomp.\n\nSet Implicit Arguments.\n\nLocal Notation power := (mscal mult 1).\nLocal Notation \"∑\" := (msum plus 0).\n\nLocal Reserved Notation \"x ≲ y\" (at level 70, no associativity).\n\n(* if n and m are written in binary, LSB first:\n       n = n0 n1 n2 ...\n       m = m0 m1 m2 ...\n    then n ≲ m means forall any i, n[i] <= m[i] *)\n\nInductive binary_le : nat -> nat -> Prop :=\n | in_ble_0 : forall n, 0 ≲ n\n | in_ble_1 : forall n m, rem n 2 <= rem m 2 -> div n 2 ≲ div m 2 -> n ≲ m\nwhere \"x ≲ y\" := (binary_le x y).\n\nLocal Infix \"≲\" := binary_le (at level 70, no associativity).\n\nFact binary_le_inv n m : n ≲ m -> n = 0 \\/ div n 2 ≲ div m 2 /\\ rem n 2 <= rem m 2.\nProof. inversion 1; auto. Qed.\n\nFact binary_le_refl x : x ≲ x.\nProof.\n  induction on x as IH with measure x.\n  destruct (eq_nat_dec x 0).\n  + subst; constructor.\n  + constructor 2; auto.\n    apply IH, div_by_p_lt; auto.\nQed.\n\nFact binary_le_le x y : x ≲ y -> x <= y.\nProof.\n  induction 1 as [ n | n m H1 H2 IH2 ]; try omega.\n  rewrite (div_rem_spec1 n 2), (div_rem_spec1 m 2); omega.\nQed.\n\nFact binary_le_zero_inv n : n ≲ 0 -> n = 0.\nProof. intros H; apply binary_le_le in H; omega. Qed.\n\nFact binary_le_zero n : 0 ≲ n.\nProof. constructor. Qed.\n\nHint Resolve binary_le_zero binary_le_refl.\n\nLocal Notation \"⟘\" := false.\nLocal Notation \"⟙\" := true.\n\nDefinition bool2nat x := \n  match x with \n    | ⟘ => 0 \n    | ⟙ => 1 \n  end.\n \nFact rem_2_bool2nat b n : rem (bool2nat b+2*n) 2 = bool2nat b.\nProof. \n  destruct b; unfold bool2nat.\n  + apply rem_2_fix_2.\n  + apply rem_2_fix_1.\nQed.\n\nFact div_2_bool2nat b n : div (bool2nat b+2*n) 2 = n.\nProof. \n  destruct b; unfold bool2nat.\n  + apply div_2_fix_2.\n  + apply div_2_fix_1.\nQed.\n\nDefinition nat2bool x := \n  match x with \n    | 0 => ⟘ \n    | _ => ⟙ \n  end.\n\nFact bool2nat2bool : forall x, x < 2 -> bool2nat (nat2bool x) = x.\nProof. intros [ | [ | ] ] ?; simpl; omega. Qed.\n\nFact nat2bool2nat : forall x, nat2bool (bool2nat x) = x.\nProof. intros []; auto. Qed.\n\nLocal Hint Resolve power2_gt_0.\n\nLocal Notation lb := (list bool).\n\nLocal Infix \"⪦\" := leb (at level 70, no associativity).\nLocal Infix \"⪯\" := lb_mask (at level 70, no associativity).\nLocal Infix \"≂\" := lb_mask_equiv (at level 70, no associativity).\nLocal Infix \"⟂\" := lb_ortho (at level 70, no associativity).\nLocal Infix \"↓\" := lb_meet (at level 40, left associativity).\nLocal Infix \"↑\" := lb_join (at level 41, left associativity).\n\nLocal Reserved Notation \"'⟦' l '⟧'\".\nLocal Reserved Notation \"'⟬' x '⟭'\".\n\n(* Section lb_nat. *)\n\n  Fixpoint lb_nat (l : lb) :=\n    match l with\n      | nil    => 0\n      | x :: l => bool2nat x + 2*⟦l⟧\n    end\n  where \"⟦ l ⟧\" := (lb_nat l).\n\n  Fact lb_nat_fix_0 : ⟦nil⟧ = 0.                      Proof. trivial. Qed.\n  Fact lb_nat_fix_1 l : ⟦⟘::l⟧ = 2*⟦l⟧.               Proof. trivial. Qed.\n  Fact lb_nat_fix_2 l : ⟦⟙::l⟧ = 1+2*⟦l⟧.             Proof. trivial. Qed.\n  Fact lb_nat_fix_3 x l : ⟦x::l⟧ = bool2nat x+2*⟦l⟧.  Proof. trivial. Qed.\n\n  Fact lb_nat_app l m : lb_nat (l++m) = lb_nat l + (power (length l) 2)*(lb_nat m).\n  Proof.\n    induction l as [ | x l IHl ].\n    + rewrite lb_nat_fix_0; simpl; omega.\n    + simpl app; do 2 rewrite lb_nat_fix_3.\n      simpl length; rewrite power_S.\n      rewrite IHl; ring.\n  Qed.\n\n  Fact lb_mask_binary_le l m : l ⪯ m -> ⟦l⟧ ≲ ⟦m⟧.\n  Proof.\n    induction 1 as [ l | l H1 IH1 | x y l m H1 H2 IH2 ].\n    - constructor 1.\n    - apply binary_le_zero_inv in IH1.\n      simpl; rewrite IH1; constructor.\n    - do 2 rewrite lb_nat_fix_3.\n      constructor 2.\n      * do 2 rewrite rem_2_bool2nat.\n        revert x y H1; intros [] []; simpl; auto; discriminate.\n      * do 2 rewrite div_2_bool2nat; auto.\n  Qed.\n\n  Section nat_lb_def.\n\n    Inductive g_nlb : nat -> lb -> Prop :=\n      | in_gnlb_0 : g_nlb 0 nil\n      | in_gnlb_1 : forall n l, n <> 0 -> rem n 2 = 0 -> g_nlb (div n 2) l -> g_nlb n (⟘::l)\n      | in_gnlb_2 : forall n l, n <> 0 -> rem n 2 = 1 -> g_nlb (div n 2) l -> g_nlb n (⟙::l).\n   \n    Fact g_nlb_fun n l1 l2 : g_nlb n l1 -> g_nlb n l2 -> l1 = l2.\n    Proof.\n      intros H1 H2; revert H1 l2 H2.\n      induction 1; inversion 1; auto; try omega; f_equal; auto.\n    Qed.\n\n    Let nat_lb_full n : { l | g_nlb n l }.\n    Proof.\n      induction on n as IHn with measure n.\n      destruct (eq_nat_dec n 0) as [ | Hn ].\n      + exists nil; subst; constructor.\n      + destruct (IHn (div n 2)) as (l & Hl).\n        * apply div_by_p_lt; omega.\n        * case_eq (rem n 2).\n          - intro; exists (⟘::l); constructor; auto.\n          - intro; exists (⟙::l); constructor; auto.\n            generalize (rem_2_lt n); omega.\n    Qed.\n\n    Definition nat_lb n := proj1_sig (nat_lb_full n).\n  \n    Fact nat_lb_spec n : g_nlb n (nat_lb n).\n    Proof. apply (proj2_sig (nat_lb_full _)). Qed.\n\n  End nat_lb_def.\n\n  Local Notation \"⟬ n ⟭\" := (nat_lb n).\n\n  Hint Resolve nat_lb_spec.\n\n  Fact nat_lb_fix_0 : ⟬ 0⟭ = nil.\n  Proof. apply g_nlb_fun with 0; auto; constructor. Qed.\n\n  Fact nat_lb_fix_1 n : n <> 0 -> ⟬ 2*n⟭ = ⟘::⟬ n⟭ .\n  Proof.\n    intros Hn. \n    apply g_nlb_fun with (2*n); auto.\n    constructor; auto; try omega.\n    + apply rem_2_fix_1.\n    + rewrite div_2_fix_1; auto.\n  Qed.\n\n  Fact nat_lb_fix_2 n : ⟬1+2*n⟭ = ⟙::⟬ n⟭ .\n  Proof.\n    apply g_nlb_fun with (1+2*n); auto.\n    constructor; auto; try omega.\n    + apply rem_2_fix_2.\n    + rewrite div_2_fix_2; auto.\n  Qed.\n\n  Fact nat_lb_1 : ⟬ 1⟭ = ⟙::nil.\n  Proof.\n    change 1 with (1+2*0).\n    rewrite nat_lb_fix_2, nat_lb_fix_0.\n    trivial.\n  Qed.\n\n  Fact lb_nat_lb n : ⟦⟬ n ⟭⟧ = n.\n  Proof.\n    induction on n as IHn with measure n.\n    destruct (eq_nat_dec n 0) as [ | Hn ].\n    + subst; rewrite nat_lb_fix_0; auto.\n    + destruct (euclid_2 n) as (q & [ Hq | Hq ]); subst n.\n      * rewrite nat_lb_fix_1; try omega.\n        rewrite lb_nat_fix_1; f_equal.\n        apply IHn; omega.\n      * rewrite nat_lb_fix_2; try omega.\n        rewrite lb_nat_fix_2; do 2 f_equal.\n        apply IHn; omega.\n  Qed.\n\n  Fact nat_lb_length x n : x < power n 2 -> length ⟬ x ⟭ <= n.\n  Proof.\n    revert x; induction n as [ | n IHn ]; intros x.\n    + rewrite power_0; intro; cutrewrite (x=0); try omega.\n      rewrite nat_lb_fix_0; simpl; omega.\n    + rewrite power_S.\n      destruct (euclid_2 x) as (y & [ H | H ]); intros Hx; subst.\n      * destruct y.\n        - simpl; rewrite nat_lb_fix_0;simpl; omega.\n        - rewrite nat_lb_fix_1; try omega.\n          simpl; apply le_n_S, IHn; omega.\n      * rewrite nat_lb_fix_2; simpl.\n        apply le_n_S, IHn; omega.\n  Qed.\n\n  Fact binary_le_lb_mask x y : x ≲ y -> ⟬ x ⟭ ⪯ ⟬ y ⟭ . \n  Proof.\n    induction 1 as [ n | n m H1 H2 IH2 ].\n    + rewrite nat_lb_fix_0; constructor.\n    + destruct (eq_nat_dec n 0) as [ Hn | Hn ].\n      - subst; rewrite nat_lb_fix_0; constructor.\n      - assert (n <= m) as Hmn.\n        { apply binary_le_le; constructor; auto. }\n        destruct (euclid_2_div n) as (G1 & [ G2 | G2 ] );\n        destruct (euclid_2_div m) as (G3 & [ G4 | G4 ] ); try omega.\n        * rewrite G1, G2, G3, G4, Nat.add_0_l, Nat.add_0_l.\n          do 2 (rewrite nat_lb_fix_1; [ | omega ]).\n          constructor; auto.\n        * rewrite G1, G2, G3, G4, Nat.add_0_l, nat_lb_fix_2.\n          rewrite nat_lb_fix_1; [ | omega ].\n          constructor; auto.\n        * rewrite G1, G2, G3, G4.\n          do 2 rewrite nat_lb_fix_2.\n          constructor; auto.\n  Qed.\n\n  Hint Resolve lb_mask_binary_le binary_le_lb_mask.\n\n  Section lb_mask_nat.\n\n    Let lb_mask_nat_1 l : ⟬ ⟦l⟧⟭  ⪯  l.\n    Proof.\n      induction l as [ | [|] l IHl ].\n      + rewrite lb_nat_fix_0, nat_lb_fix_0; constructor.\n      + rewrite lb_nat_fix_2, nat_lb_fix_2; constructor; auto.\n      + rewrite lb_nat_fix_1.\n        destruct (eq_nat_dec ⟦l⟧ 0) as [ Hl | Hl ]. \n        - rewrite Hl; simpl; rewrite nat_lb_fix_0; constructor.\n        - rewrite nat_lb_fix_1; auto; constructor; auto.\n    Qed.\n\n    Let lb_mask_nat_2 l : l ⪯  ⟬ ⟦l⟧⟭  .\n    Proof.\n      induction l as [ | [|] l IHl ].\n      + constructor.\n      + rewrite lb_nat_fix_2, nat_lb_fix_2; constructor; auto.\n      + rewrite lb_nat_fix_1.\n        destruct (eq_nat_dec ⟦l⟧ 0) as [ Hl | Hl ]. \n        - rewrite Hl; simpl; rewrite nat_lb_fix_0; constructor.\n          rewrite Hl, nat_lb_fix_0 in IHl; auto.\n        - rewrite nat_lb_fix_1; auto; constructor; auto.\n    Qed.\n\n    Fact lb_mask_nat l : ⟬ ⟦l⟧⟭ ≂ l.\n    Proof. split; auto. Qed.\n\n  End lb_mask_nat.\n\n  Definition nat_lb_nat := lb_mask_nat.\n\n  (* We have a correspondance *)\n\n  Lemma lb_mask_eq_binary_le l m : l ⪯ m <-> ⟦l⟧ ≲ ⟦m⟧.\n  Proof.\n    split; auto; intro.\n    rewrite <- (lb_mask_nat l), <- (lb_mask_nat m); auto.\n  Qed.\n\n  Lemma binary_le_eq_lb_mask x y : x ≲ y <-> ⟬ x⟭  ⪯ ⟬ y⟭ .\n  Proof.\n    split; auto.\n    intro; rewrite <- (lb_nat_lb x), <- (lb_nat_lb y); auto.\n  Qed.\n\n  Hint Resolve lb_mask_eq_binary_le binary_le_eq_lb_mask.\n\n  Fact binary_le_trans x y z : x ≲ y -> y ≲ z -> x ≲ z.\n  Proof.\n    do 3 rewrite binary_le_eq_lb_mask; apply lb_mask_trans.\n  Qed.\n\n  Fact lb_mask_equiv_equal l m : l ≂ m <-> ⟦l⟧ = ⟦m⟧.\n  Proof.\n    unfold lb_mask_equiv.\n    do 2 rewrite lb_mask_eq_binary_le; split.\n    + intros (? & ?); apply le_antisym; apply binary_le_le; auto.\n    + intros H; rewrite H; split; auto. \n  Qed.\n\n  Fact equal_lb_mask_equiv x y : x = y <-> ⟬ x⟭ ≂⟬ y⟭.\n  Proof.\n    rewrite lb_mask_equiv_equal, lb_nat_lb, lb_nat_lb; tauto.\n  Qed.\n\n  Local Notation lbeq := lb_mask_equiv (only parsing).\n\n  Add Parametric Morphism: (lb_nat) with signature (lbeq) ==> (eq) as lb_nat_eq.\n  Proof. apply lb_mask_equiv_equal. Qed.\n\n(*\n  Hint Resolve dio_rel_binomial dio_rel_remainder.\n\n  Section binary_le_dio.\n\n    Let ble_equiv x y : x ≲ y <-> exists b, b = binomial y x /\\ 1 = rem b 2.\n    Proof.\n      rewrite binary_le_binomial; split; eauto.\n      intros (? & ? & ?); subst; auto.\n    Qed.\n\n    Theorem binary_le_diophatine x y : \n             dio_expression x\n          -> dio_expression y\n          -> dio_rel (fun v => x v ≲ y v).\n    Proof.\n      intros. \n      apply dio_rel_equiv with (1 := fun v => ble_equiv (x v) (y v)).\n      dio_rel_auto.\n    Qed.\n\n  End binary_le_dio.\n\n  Definition lb_dio (R : (nat -> lb) -> Prop) := { f | forall v, df_pred f (fun n => ⟦v n⟧) <-> R v }.\n\n  Theorem lb_mask_diophantine x y : lb_dio (fun v => v x ⪯  v y).\n  Proof.\n    destruct (binary_le_diophatine (dio_expr_var x) (dio_expr_var y)) as (f & Hf).\n    exists f; intros v; rewrite Hf, lb_mask_eq_binary_le; tauto.\n  Qed.\n\n*)\n\n  Definition bool_add_with_rem a b c : bool * bool :=\n    match a, b, c with \n     | ⟘, ⟘, ⟘ => (⟘,⟘)\n     | ⟘, ⟘, ⟙ => (⟘,⟙)\n     | ⟘, ⟙, ⟘ => (⟘,⟙)\n     | ⟘, ⟙, ⟙ => (⟙,⟘)\n     | ⟙, ⟘, ⟘ => (⟘,⟙)\n     | ⟙, ⟘, ⟙ => (⟙,⟘)\n     | ⟙, ⟙, ⟘ => (⟙,⟘)\n     | ⟙, ⟙, ⟙ => (⟙,⟙)\n    end.\n\n  Notation bin_add := bool_add_with_rem.\n  \n  Fact bin_add_eq_00x x : bin_add ⟘ ⟘  x = (⟘,x).\n  Proof. destruct x; auto. Qed.\n\n  Fact bin_add_eq_0x0 x : bin_add ⟘ x ⟘  = (⟘,x).\n  Proof. destruct x; auto. Qed.\n\n  Fixpoint lb_succ a l :=\n    match l with\n      | nil  => a::nil\n      | x::l => let (r,z) := bin_add ⟘ a x in z::lb_succ r l\n    end.\n\n  Fact lb_succ_spec_0 l : ⟦lb_succ ⟘ l⟧ = ⟦l⟧.\n  Proof.\n    induction l as [ | [] ]; simpl; auto.\n  Qed.\n\n  Fact lb_succ_spec_1 l : ⟦lb_succ ⟙ l⟧ = S ⟦l⟧.\n  Proof.\n    induction l as [ | [] ]; auto.\n    + simpl lb_succ; rewrite lb_nat_fix_2.\n      rewrite lb_nat_fix_1, IHl; omega.\n    + simpl lb_succ; rewrite lb_nat_fix_2.\n      rewrite lb_nat_fix_1, lb_succ_spec_0; omega.\n  Qed.\n\n  Fact lb_succ_spec a l : ⟦lb_succ a l⟧ = bool2nat a + ⟦l⟧.\n  Proof.\n    destruct a.\n    + rewrite lb_succ_spec_1; auto.\n    + rewrite lb_succ_spec_0; auto.\n  Qed.\n\n  Fact lb_succ_bot l : lb_succ ⟘ l ≂ l.\n  Proof.\n    induction l as [ | x ]; simpl; auto.\n    + split; repeat constructor.\n    + destruct x; rewrite IHl; auto.\n  Qed.\n\n  Fixpoint lb_plus a l m :=\n    match l, m with\n      | nil,   m   => lb_succ a m\n      | l,    nil  => lb_succ a l\n      | x::l, y::m => let (r,z) := bin_add a x y in z::lb_plus r l m\n    end.\n\n  Fact lb_plus_fix_0 a l : lb_plus a nil l = lb_succ a l.\n  Proof. auto. Qed.\n\n  Fact lb_plus_fix_1 a l : lb_plus a l nil = lb_succ a l.\n  Proof. destruct l; auto. Qed.\n\n  Fact lb_plus_fix_2 a x y l m : lb_plus a (x::l) (y::m) = let (r,z) := bin_add a x y in z::lb_plus r l m.\n  Proof. auto. Qed.\n\n  Fact lb_plus_spec a l m : ⟦lb_plus a l m⟧ = bool2nat a + ⟦l⟧ + ⟦m⟧.\n  Proof.\n    revert a m; induction l as [ | x l IHl ]; intros a m.\n    + rewrite lb_plus_fix_0, lb_succ_spec, lb_nat_fix_0; omega.\n    + destruct m as [ | y m ].\n      * rewrite lb_plus_fix_1, lb_succ_spec, lb_nat_fix_0; omega.\n      * rewrite lb_plus_fix_2, lb_nat_fix_3, lb_nat_fix_3.\n        destruct a; destruct x; destruct y; simpl; rewrite IHl; simpl; omega.\n  Qed.\n\n  Local Infix \"⊕\" := (lb_plus ⟘ ) (at level 41, left associativity). \n\n  Fact lb_plus_spec_0 l m : ⟦l⊕m⟧ = ⟦l⟧ + ⟦m⟧.\n  Proof. rewrite lb_plus_spec; simpl; auto. Qed.\n\n  Add Parametric Morphism a: (lb_plus a) with signature (lbeq) ==> (lbeq) ==> (lbeq) as lb_plus_eq.\n  Proof.\n    intros x1 y1 E1 x2 y2 E2; revert E1 E2.\n    do 3 rewrite lb_mask_equiv_equal.\n    do 2 rewrite lb_plus_spec.\n    intros; f_equal; auto.\n  Qed.\n\n  Fact lb_ortho_plus l m : l ⟂ m <-> l ⪯ l⊕m.\n  Proof.\n    split.\n    + induction 1 as [ l | l | x y l m [ H1 | H1 ] H2 IH2 ].\n      * constructor. \n      * rewrite lb_plus_fix_1.\n        rewrite lb_mask_eq_binary_le, lb_succ_spec; simpl.\n        rewrite <- lb_mask_eq_binary_le; apply lb_mask_refl.\n      * rewrite lb_plus_fix_2.\n        subst x; rewrite bin_add_eq_00x.\n        destruct y; constructor; auto.\n      * rewrite lb_plus_fix_2.\n        subst y; rewrite bin_add_eq_0x0.\n        destruct x; constructor; auto.\n    + revert m; induction l as [ | x l IHl ].\n      * intros; constructor.\n      * intros [ | y m ] H.\n        - constructor.\n        - rewrite lb_plus_fix_2 in H.\n          destruct x; destruct y; simpl in H; try (apply lb_mask_inv_cons_cons in H; tauto);\n            apply lb_mask_inv_cons, proj2 in H; constructor; auto.\n  Qed.\n\n(*\n\n  Theorem lb_ortho_diophantine x y : lb_dio (fun v => v x ⟂ v y).\n  Proof.\n    destruct (@lb_mask_diophantine 0 1) as (f & Hf).\n    exists (df_subst (fun n => match n with 0 => de_var x | _ => de_add (de_var x) (de_var y) end) f).\n    intros v; rewrite df_pred_subst.\n    set (w z := match z with 0 => v x | _ => lb_plus ⟘  (v x) (v y) end).\n    rewrite df_pred_ext with (ω := fun n => ⟦ w n ⟧).\n    + rewrite Hf; unfold w; symmetry; apply lb_ortho_plus.\n    + intros [ | ]; simpl; auto.\n      rewrite lb_plus_spec_0; auto.\n  Qed.\n\n*)\n\n  Fact lb_ortho_plus_join x y : x ⟂ y -> x⊕y ≂ x↑y.\n  Proof.\n    induction 1 as [ m | l | x y l m H1 H2 IH2 ].\n    + rewrite lb_plus_fix_0, lb_join_right; apply lb_succ_bot.\n    + rewrite lb_plus_fix_1, lb_join_left; apply lb_succ_bot.\n    + rewrite lb_join_cons.\n      apply lb_mask_equiv_equal.\n      rewrite lb_plus_spec_0.\n      do 3 rewrite lb_nat_fix_3.\n      rewrite lb_mask_equiv_equal in IH2.\n      rewrite <- IH2.\n      rewrite lb_plus_spec_0.\n      destruct x; destruct y; simpl; try ring.\n      destruct H1; discriminate.\n  Qed.\n\n  Fact lb_ortho_plus_id a x y : a ⟂ x -> a ⟂ y -> x ⟂ y <-> (a⊕x)↓(a⊕y) ≂ a.\n  Proof.\n    intros H1 H2. \n    do 2 (rewrite lb_ortho_plus_join; auto). \n    rewrite <- lb_join_meet_distr, lb_ortho_meet_nil.\n    split.\n    + intros H3; rewrite H3, lb_join_left; auto.\n    + intros H3; apply lb_ortho_mask_nil with a.\n      * revert H1; apply lb_ortho_anti; auto.\n      * rewrite <- H3, lb_join_comm; auto.\n  Qed.\n\n  (* A purely Boolean algebraic proof *)\n\n  Fact lb_minus_plus a b : a ⪯ b -> exists x, b ≂ a⊕x /\\ a ⪯  a⊕x.\n  Proof.\n    intros H.\n    destruct lb_minus with (1 := H) as (x & H1 & H2).\n    exists x; rewrite lb_ortho_plus_join; auto.\n  Qed.\n\n  (* A diophantine representation of bitwise and *)\n \n  Theorem lb_meet_dio a b c : a ≂ b↓c <-> exists x y, b ≂ a⊕x /\\ c ≂ a⊕y /\\ a ⪯  a⊕x /\\ a ⪯  a⊕y /\\ x ⪯  x⊕y.\n  Proof.\n    split.\n    + intros H.\n      destruct (@lb_minus_plus a b) as (x & H1 & H2).\n      { rewrite H; auto. }\n      destruct (@lb_minus_plus a c) as (y & H3 & H4).\n      { rewrite H; auto. }\n      exists x, y; repeat (split; auto).\n      rewrite <- lb_ortho_plus in H2, H4 |- *.\n      rewrite lb_ortho_plus_join in H1, H3; auto.\n      apply lb_ortho_meet_nil. \n      apply lb_ortho_mask_nil with (a := a).\n      - revert H4; apply lb_ortho_anti; auto.\n      - rewrite H, H1, H3.\n        apply lb_meet_mono; auto.\n    + intros (x & y & H1 & H2 & H3 & H4 & H5).\n      rewrite <- lb_ortho_plus in H3, H4, H5.\n      rewrite H1, H2.\n      do 2 (rewrite lb_ortho_plus_join; auto).\n      rewrite <- lb_join_meet_distr. \n      rewrite lb_ortho_meet_nil in H5.\n      rewrite H5; rew lb.\n  Qed.\n\n  (* A diophantine representation of bitwise or *)\n\n  Fact lb_join_dio a b c : a ≂ b↑c <-> exists x, a ≂ b⊕x /\\ b ⪯  b⊕x /\\ x ⪯ c /\\ c ⪯ a.\n  Proof.\n    split. \n    + intros H. \n      destruct (@lb_minus_plus b a) as (x & H1 & H2).\n      { rewrite H; auto. }\n      exists x; repeat (split; auto).\n      2: rewrite H; auto.\n      rewrite <- lb_ortho_plus in H2.\n      rewrite  lb_ortho_plus_join in H1; auto.\n      rewrite lb_ortho_meet_nil in H2.\n      rewrite <- (lb_meet_join_idem x b), lb_join_comm.\n      rewrite <- H1, H, lb_meet_join_distr, (lb_meet_comm _ b), H2.\n      rew lb.\n    + intros (x & H1 & H2 & H3 & H4).\n      rewrite <- lb_ortho_plus in H2.\n      rewrite lb_ortho_plus_join in H1; auto.\n      rewrite lb_ortho_meet_nil in H2.\n      split.\n      * rewrite H1; apply lb_join_mono; auto.\n      * apply lb_join_spec; auto; rewrite H1; auto.\n  Qed.\n\n(* End lb_nat. *)\n\n  Fixpoint lb_bots n :=\n    match n with \n      | 0   => nil\n      | S n => ⟘ :: lb_bots n\n    end.\n      \n  Definition lb_shift n l := lb_bots n ++ l.\n\n  Fact lb_shift_0 l : lb_shift 0 l = l.\n  Proof. auto. Qed.\n\n  Fact lb_shift_S n l : lb_shift (S n) l = ⟘ :: lb_shift n l.\n  Proof. auto. Qed.\n\n  Fact lb_nat_shift n l : ⟦lb_shift n l⟧ = ⟦l⟧*power n 2.\n  Proof.\n    unfold lb_shift.\n    induction n as [ | n IHn ]; simpl lb_bots.\n    + rewrite power_0; simpl; ring.\n    + simpl app; rewrite lb_nat_fix_1, IHn, power_S; ring.\n  Qed.\n\n  Fact lb_shift_meet n l m : lb_shift n (l↓m) = (lb_shift n l)↓(lb_shift n m).\n  Proof.\n    induction n as [ | n IHn ].\n    + repeat rewrite lb_shift_0; auto.\n    + do 3 rewrite lb_shift_S.\n      rewrite lb_meet_cons; f_equal; auto.\n  Qed.\n\n  Fact lb_shift_join n l m : lb_shift n (l↑m) = (lb_shift n l)↑(lb_shift n m).\n  Proof.\n    induction n as [ | n IHn ].\n    + repeat rewrite lb_shift_0; auto.\n    + do 3 rewrite lb_shift_S.\n      rewrite lb_join_cons; f_equal; auto.\n  Qed.\n\n  Fact lb_shift_ortho n l m : length l <= n -> l ⟂ lb_shift n m.\n  Proof.\n    revert n.\n    induction l as [ | x l IHl ]; intros [ | n ]; simpl; auto; try omega.\n    intro; rewrite lb_shift_S; constructor; auto; apply IHl; omega.\n  Qed.\n\n  Fact lb_shift_ortho_meet n l m : length l <= n -> l ↓ lb_shift n m ≂ nil.\n  Proof.\n    intros; apply lb_ortho_meet_nil, lb_shift_ortho; auto.\n  Qed.\n\n  Fact nat_pow2_lb_shift n q : ⟬q*power n 2⟭ ≂ lb_shift n ⟬q⟭ .\n  Proof.  \n    apply lb_mask_equiv_equal.\n    rewrite lb_nat_lb, lb_nat_shift, lb_nat_lb; auto.\n  Qed.\n\n  Fact nat_euclid_pow2_lb n r q : r < power n 2 -> ⟬r+q*power n 2⟭ ≂ ⟬r⟭ ↑lb_shift n ⟬q⟭ .\n  Proof.\n    intros H.\n    apply lb_mask_equiv_equal.\n    rewrite lb_nat_lb.\n    rewrite <- lb_ortho_plus_join.\n    2: apply lb_shift_ortho, nat_lb_length; auto.\n    rewrite lb_plus_spec_0; f_equal.\n    + rewrite lb_nat_lb; auto.\n    + rewrite lb_nat_shift, lb_nat_lb; auto.\n  Qed.\n\n  Definition nat_meet n m := ⟦ ⟬n⟭↓⟬m⟭ ⟧.\n  Local Infix \"⇣\" := nat_meet (at level 40, left associativity).\n\n  Fact nat_meet_comm n m : n⇣m = m⇣n.\n  Proof.\n    apply lb_mask_equiv_equal.\n    rewrite lb_meet_comm; auto.\n  Qed.\n\n  Fact nat_meet_left n m : n⇣m ≲ n.\n  Proof.\n    apply binary_le_eq_lb_mask.\n    unfold nat_meet.\n    rewrite lb_mask_nat; auto.\n  Qed.\n\n  Fact nat_meet_right n m : n⇣m ≲ m.\n  Proof.\n    apply binary_le_eq_lb_mask.\n    unfold nat_meet.\n    rewrite lb_mask_nat; auto.\n  Qed.\n\n  Hint Resolve nat_meet_left nat_meet_right.\n\n  Fact binary_le_nat_meet n m : n ≲ m <-> n⇣m = n.\n  Proof.\n    rewrite equal_lb_mask_equiv.\n    rewrite binary_le_eq_lb_mask.\n    unfold nat_meet.\n    rewrite nat_lb_nat.\n    apply lb_mask_meet.\n  Qed.\n  \n  Theorem nat_meet_dio a b c : a = b⇣c <-> exists x y,  b = a+x\n                                                     /\\ c = a+y\n                                                     /\\ a ≲ a+x\n                                                     /\\ a ≲ a+y\n                                                     /\\ x ≲ x+y.\n  Proof.\n    unfold nat_meet.\n    rewrite equal_lb_mask_equiv, nat_lb_nat.\n    rewrite lb_meet_dio.\n    split; intros (x & y & H1 & H2 & H3 & H4 & H5).\n    + exists ⟦x⟧, ⟦y⟧.\n      revert H1 H2 H3 H4 H5.\n      repeat rewrite lb_mask_equiv_equal.\n      repeat rewrite lb_mask_eq_binary_le.\n      repeat rewrite lb_plus_spec_0.\n      repeat rewrite lb_nat_lb; auto.\n    + exists ⟬ x⟭, ⟬ y⟭ .\n      repeat rewrite lb_mask_equiv_equal.\n      repeat rewrite lb_mask_eq_binary_le.\n      rewrite H1, H2.\n      repeat rewrite lb_plus_spec_0.\n      repeat rewrite lb_nat_lb.\n      auto.\n  Qed.\n\n  (* This is how we compute the meet by division by powers of 2 *)\n\n  Lemma nat_meet_mult_power2 q x y : (x*power q 2) ⇣ (y*power q 2) \n                                    = (x⇣y)*power q 2.\n  Proof.\n    unfold nat_meet.\n    rewrite <- lb_nat_shift, lb_shift_meet.\n    apply lb_mask_equiv_equal.\n    do 2 rewrite nat_pow2_lb_shift; auto.\n  Qed.\n\n  Lemma nat_meet_euclid_power_2 q r1 d1 r2 d2 : \n           r1 < power q 2 \n        -> r2 < power q 2 \n        -> (r1+d1*power q 2) ⇣ (r2+d2*power q 2) \n         = (r1⇣r2) + (d1⇣d2)*power q 2.\n  Proof.\n    unfold nat_meet.\n    intros H1 H2.\n    do 2 (rewrite nat_euclid_pow2_lb; auto).\n    rewrite <- lb_nat_shift, <- lb_plus_spec_0.\n    apply lb_mask_equiv_equal.\n    rewrite lb_ortho_plus_join.\n    2: apply lb_shift_ortho, lb_meet_length_le; apply nat_lb_length; auto.\n    rewrite lb_shift_meet.\n    rewrite lb_meet_join_distr.\n    do 2 rewrite (lb_meet_comm (_↑_)).\n    do 2 rewrite lb_meet_join_distr.\n    rewrite lb_shift_ortho_meet; try (apply nat_lb_length; auto; fail).\n    rew lb. \n    rewrite (lb_meet_comm (lb_shift _ _)).\n    rewrite lb_shift_ortho_meet; try (apply nat_lb_length; auto; fail).\n    rew lb.\n    rewrite lb_meet_comm.\n    rewrite (lb_meet_comm (lb_shift _ _)); auto.\n  Qed.\n\n  Lemma nat_meet_euclid_2 r1 d1 r2 d2 : \n           r1 < 2 \n        -> r2 < 2 \n        -> (r1+2*d1) ⇣ (r2+2*d2) \n         = (r1⇣r2) + 2*(d1⇣d2).\n  Proof.\n    intros H1 H2.\n    do 3 rewrite (mult_comm 2).\n    apply nat_meet_euclid_power_2 with (q := 1); auto.\n  Qed.\n  \n  Fact nat_meet_0n n : 0⇣n = 0.\n  Proof.\n    apply equal_lb_mask_equiv.\n    unfold nat_meet.\n    rewrite nat_lb_fix_0; rew lb.\n    apply nat_lb_nat.\n  Qed.\n\n  Fact nat_meet_n0 n : n⇣0 = 0.\n  Proof. rewrite nat_meet_comm, nat_meet_0n; auto. Qed.\n\n  Fact nat_meet_idem n : n⇣n = n.\n  Proof. \n    apply equal_lb_mask_equiv.\n    unfold nat_meet.\n    rewrite nat_lb_nat, lb_meet_idem; auto.\n  Qed.\n\n  Hint Resolve nat_meet_0n nat_meet_n0 nat_meet_idem.\n\n  Fact nat_meet_assoc n m k : n⇣(m⇣k) = n⇣m⇣k.\n  Proof.\n    apply equal_lb_mask_equiv; unfold nat_meet.\n    repeat rewrite nat_lb_nat.\n    rewrite lb_meet_assoc; auto.\n  Qed.\n\n  Section nat_meet_power2_neq.\n\n    Let nat_meet_power2_lt x y : x < y -> (power x 2) ⇣ (power y 2) = 0. \n    Proof.\n      intros H.\n      replace (power x 2) with (power x 2 + 0*power y 2) by ring.\n      replace (power y 2) with (0 + 1*power y 2) at 2 by ring.\n      rewrite nat_meet_euclid_power_2.\n      + rewrite nat_meet_n0, nat_meet_0n; ring.\n      + apply power_smono_l; omega.\n      + apply power_ge_1; omega.\n    Qed.\n\n    Fact nat_meet_power2_neq x y : x <> y -> (power x 2) ⇣ (power y 2) = 0. \n    Proof.\n      intros H.\n      destruct (lt_eq_lt_dec x y) as [[]|]; try omega.\n      + apply nat_meet_power2_lt; auto.\n      + rewrite nat_meet_comm; apply nat_meet_power2_lt; auto.\n    Qed.\n\n  End nat_meet_power2_neq.\n\n  Fact nat_meet_12n n : 1⇣(2*n) = 0.\n  Proof.\n    replace 1 with (1+0*power 1 2) at 1 by auto.\n    replace (2*n) with (0+n*power 1 2) by (rewrite power_1; ring).\n    rewrite nat_meet_euclid_power_2; rewrite power_1; try omega.\n    rewrite nat_meet_0n, nat_meet_n0; auto.\n  Qed.\n\n  Fact nat_meet_12 : 1⇣2 = 0.\n  Proof. apply (nat_meet_12n 1). Qed.\n\n  Fact power_2_minus_1 n : power (S n) 2 - 1 = 1 + 2*(power n 2 - 1).\n  Proof.\n    rewrite power_S.\n    generalize (@power_ge_1 n 2); intros; omega.\n  Qed.\n\n  Fact power_2_minus_1_gt n x : x < power n 2 <-> x ≲ power n 2 - 1.\n  Proof.\n    split.\n    2: { intro Hx.\n         apply binary_le_le in Hx.\n         generalize (@power_ge_1 n 2); intros; omega. }\n    intros H1.\n    assert (x <= power n 2 -1) as H by omega; clear H1. \n    rewrite binary_le_nat_meet.\n    revert x H; induction n as [ | n IHn ]; intros x Hx.\n    + rewrite power_0 in Hx; cutrewrite (x=0); auto; omega.\n    + destruct (eq_nat_dec x 0) as [ H | H ].\n      - rewrite H; auto.\n      - destruct (euclid_2_div x) as (H1 & H2).\n        rewrite H1, power_2_minus_1.\n        rewrite nat_meet_euclid_2; try omega.\n        rewrite IHn.\n        * f_equal; destruct H2 as [ H2 | H2 ]; rewrite H2; auto.\n        * rewrite power_2_minus_1 in Hx; omega.\n  Qed.\n\n  Definition nat_join n m := ⟦ ⟬n⟭↑⟬m⟭ ⟧.\n  Local Infix \"⇡\" := nat_join (at level 50, left associativity).\n\n  Fact nat_join_comm n m : n⇡m = m⇡n.\n  Proof.\n    apply lb_mask_equiv_equal.\n    rewrite lb_join_comm; auto.\n  Qed.\n\n  Fact nat_join_left n m : n ≲ n⇡m.\n  Proof.\n    apply binary_le_eq_lb_mask.\n    unfold nat_join.\n    rewrite lb_mask_nat; auto.\n  Qed.\n\n  Fact nat_join_right n m : m ≲ n⇡m.\n  Proof.\n    apply binary_le_eq_lb_mask.\n    unfold nat_join.\n    rewrite lb_mask_nat; auto.\n  Qed.\n\n  Hint Resolve nat_join_left nat_join_right.\n\n  Fact nat_join_0n n : 0⇡n = n.\n  Proof.\n    apply equal_lb_mask_equiv.\n    unfold nat_join.\n    rewrite nat_lb_fix_0; rew lb.\n    apply nat_lb_nat.\n  Qed.\n\n  Fact nat_join_n0 n : n⇡0 = n.\n  Proof. rewrite nat_join_comm, nat_join_0n; auto. Qed.\n\n  Fact nat_join_idem n : n⇡n = n.\n  Proof. \n    apply equal_lb_mask_equiv.\n    unfold nat_join.\n    rewrite nat_lb_nat, lb_join_idem; auto.\n  Qed.\n\n  Fact nat_join_mono a b u v : a ≲ b -> u ≲ v -> a⇡u ≲ b⇡v.\n  Proof.\n    do 3 rewrite binary_le_eq_lb_mask; unfold nat_join.\n    do 2 rewrite nat_lb_nat.\n    apply lb_join_mono.\n  Qed.\n\n  Fact nat_join_assoc n m k : n⇡(m⇡k) = n⇡m⇡k.\n  Proof.\n    apply equal_lb_mask_equiv; unfold nat_join.\n    repeat rewrite nat_lb_nat.\n    rewrite lb_join_assoc; auto.\n  Qed.\n\n  Fact nat_join_meet_distr_l n m k : n⇡(m⇣k) = (n⇡m)⇣(n⇡k).\n  Proof.\n    apply equal_lb_mask_equiv.\n    unfold nat_join, nat_meet.\n    repeat rewrite nat_lb_nat.\n    rewrite lb_join_meet_distr; auto.\n  Qed.\n\n  Fact nat_meet_join_distr_l n m k : n⇣(m⇡k) = (n⇣m)⇡(n⇣k).\n  Proof.\n    apply equal_lb_mask_equiv.\n    unfold nat_join, nat_meet.\n    repeat rewrite nat_lb_nat.\n    rewrite lb_meet_join_distr; auto.\n  Qed.\n  \n  Hint Resolve nat_join_0n nat_join_n0 nat_join_assoc.\n\n  Lemma nat_join_monoid : monoid_theory nat_join 0.\n  Proof. split; auto. Qed.\n \n  Hint Resolve nat_join_monoid nat_join_mono.\n\n  Fact nat_meet_joins_distr_l m n f : m ⇣ msum nat_join 0 n f = msum nat_join 0 n (fun i => m ⇣ f i).\n  Proof.\n    revert m f; induction n as [ | n IHn ]; intros m f.\n    + do 2 rewrite msum_0; auto.\n    + do 2 rewrite msum_S.\n      rewrite nat_meet_join_distr_l, IHn; auto.\n  Qed.\n\n  Fact nat_join_binary_le n m k : n⇡m ≲ k <-> n ≲ k /\\ m ≲ k.\n  Proof.\n    split.\n    + intros H; split; apply binary_le_trans with (2 := H); auto.\n    + intros (H1 & H2). rewrite <- (nat_join_idem k); auto.\n  Qed. \n\n  Fact nat_joins_binary_le_left n f m : msum nat_join 0 n f ≲ m <-> forall i, i < n -> f i ≲ m.\n  Proof.\n    revert f; induction n as [ | n IHn ]; intros f.\n    + rewrite msum_0; split; auto; intros; omega.\n    + rewrite msum_S, nat_join_binary_le, IHn.\n      split.\n      * intros [H1 H2] [] ?; auto; apply H2; omega.\n      * intros H; split; intros; apply H; omega.\n  Qed.\n\n  Fact nat_joins_binary_le_right m n f : (exists i, i < n /\\ m ≲ f i) -> m ≲ msum nat_join 0 n f.\n  Proof.\n    intros (i & H1 & H2).\n    apply binary_le_trans with (1 := H2).\n    clear m H2.\n    revert f i H1; induction n as [ | n IHn ]; intros f [ | i ] Hi; try omega; rewrite msum_S; auto.\n    apply binary_le_trans with (2 := nat_join_right _ _).\n    apply (IHn (fun i => f (S i))); omega.\n  Qed.\n\n  Fact nat_joins_binary_le n m f g :\n           (forall i, i < n -> exists j, j < m /\\ f i ≲ g j)\n        -> msum nat_join 0 n f ≲ msum nat_join 0 m g.\n  Proof.\n    intros H.\n    rewrite nat_joins_binary_le_left.\n    intros i Hi; apply nat_joins_binary_le_right; auto.\n  Qed.\n\n  Fact nat_double_joins_binary_le n m f g : \n           (forall i j, j < i < n -> exists k, k < m /\\ f i j ≲ g k)\n        -> msum nat_join 0 n (fun i => msum nat_join 0 i (f i)) ≲ msum nat_join 0 m g.\n  Proof.\n    intros H.\n    rewrite nat_joins_binary_le_left.\n    intros; apply nat_joins_binary_le; auto.\n  Qed.\n\n  Fact binary_le_join_inv m a b : m ≲ a⇡b -> m = (m⇣a)⇡(m⇣b).\n  Proof.\n    rewrite binary_le_nat_meet, nat_meet_join_distr_l; auto.\n  Qed.\n\n  Fact binary_le_joins_inv m n f : m ≲ msum nat_join 0 n f\n                              -> { k : nat & { g : nat -> nat & { h | m = msum nat_join 0 k g\n                                                                   /\\ k <= n \n                                                                   /\\ (forall i, i < k -> g i <> 0 /\\ g i ≲ f (h i))  \n                                                                   /\\ (forall i, i < k -> h i < n)\n                                                                   /\\ (forall i j, i < j < k -> h i < h j) } } }.\n  Proof.\n    revert m f; induction n as [ | n IHn ]; intros m f H.\n    + rewrite msum_0 in H; apply binary_le_zero_inv in H.\n      subst; exists 0, (fun _ => 0), (fun _ => 0); split.\n      - rewrite msum_0; auto.\n      - split; [ | split; [ | split ] ]; intros; omega.\n    + rewrite msum_S in H.\n      apply binary_le_join_inv in H.\n      destruct (@IHn (m ⇣ msum nat_join 0 n (fun n => f (S n))) (fun n => f (S n)))\n        as (k & g & h & H1 & H0 & H2 & H3 & H4); auto.\n      rewrite H1 in H.\n      case_eq (m ⇣ f 0).\n      * intros E.\n        rewrite E, nat_join_0n in H.\n        exists k, g, (fun i => S (h i)); repeat (split; auto).\n        - intros i Hi; specialize (H3 _ Hi); omega.\n        - intros i j Hij; specialize (H4 _ _ Hij); omega.\n      * intros u Hu.\n        exists (S k), (fun i => match i with 0 => S u | S i => g i end),\n                      (fun i => match i with 0 => 0   | S i => S (h i) end); split; [  | split; [ | split; [ | split ] ] ].\n        - rewrite H, msum_S, <- Hu; auto.\n        - omega.\n        - intros [ | i ]; split; try omega. \n          ++ rewrite <- Hu; auto.\n          ++ apply H2; omega.\n          ++ apply H2; omega.\n        - intros [ | i ] Hi; try omega.\n          apply lt_S_n, H3 in Hi; omega.\n        - intros [ | i ] [ | j ] (G1 & G2); simpl; try omega.\n          apply lt_n_S, H4; omega.\n  Qed.\n\n  Fact binary_le_joins_inv' m n f : m ≲ msum nat_join 0 n f\n                              -> { g | m = msum nat_join 0 n g /\\ forall i, i < n -> g i ≲ f i }.  \n  Proof.\n    intros H; exists (fun i => m⇣f i); split.\n    2: intros; auto.\n    apply binary_le_nat_meet in H.\n    rewrite <- H at 1.\n    apply nat_meet_joins_distr_l.\n  Qed.\n\n  (* This is how we compute the meet by division by powers of 2 *)\n\n  Lemma nat_join_mult_power2 q x y : (x*power q 2) ⇡ (y*power q 2) \n                                    = (x⇡y)*power q 2.\n  Proof.\n    unfold nat_join.\n    rewrite <- lb_nat_shift, lb_shift_join.\n    apply lb_mask_equiv_equal.\n    do 2 rewrite nat_pow2_lb_shift; auto.\n  Qed.\n\n  Lemma binary_le_mult_power2_inv m x q : m ≲ x * power q 2 -> m <> 0 -> { y | m = y * power q 2 /\\ y <> 0 /\\ y ≲ x }.\n  Proof.\n    intros H1 H2.\n    destruct (@euclid m (power q 2)) as (d & r & H3 & H4).\n    + generalize (@power_ge_1 q 2); intros; omega.\n    + apply binary_le_nat_meet in H1.\n      rewrite plus_comm in H3.\n      rewrite H3, <- (Nat.add_0_l (x*_)) in H1.\n      rewrite nat_meet_euclid_power_2 in H1; auto.\n      rewrite nat_meet_n0 in H1.\n      rewrite (plus_comm r), (plus_comm 0) in H1.\n      apply div_rem_uniq in H1; auto.\n      2: generalize (@power_ge_1 q 2); intros; omega.\n      destruct H1 as (H0 & H1).\n      subst r; simpl in H3.\n      exists d; split; auto.\n      split.\n      - contradict H2; subst; auto.\n      - rewrite <- H0; auto.\n  Qed.\n \n  Lemma nat_join_euclid2 q r1 d1 r2 d2 : \n           r1 < power q 2 \n        -> r2 < power q 2 \n        -> (r1+d1*power q 2) ⇡ (r2+d2*power q 2) \n         = (r1⇡r2) + (d1⇡d2)*power q 2.\n  Proof.\n    unfold nat_join.\n    intros H1 H2.\n    do 2 (rewrite nat_euclid_pow2_lb; auto).\n    rewrite <- lb_nat_shift, <- lb_plus_spec_0.\n    apply lb_mask_equiv_equal.\n    rewrite lb_ortho_plus_join.\n    2: apply lb_shift_ortho, lb_join_length_le; apply nat_lb_length; auto.\n    rewrite lb_shift_join.\n    rewrite  lb_join_assoc, <- (lb_join_assoc ⟬ r1 ⟭).\n    rewrite (lb_join_comm _ ⟬ r2 ⟭).\n    repeat rewrite lb_join_assoc; auto.\n  Qed.\n\n  Fact nat_lb_plus n m : ⟬n+m⟭ ≂ ⟬n⟭⊕⟬m⟭.\n  Proof.\n    rewrite lb_mask_equiv_equal, lb_nat_lb, lb_plus_spec_0. \n    f_equal; symmetry; apply lb_nat_lb.\n  Qed.\n\n  Fact nat_ortho_plus_join n m : n⇣m = 0 -> n+m = n⇡m.\n  Proof.\n    do 2 rewrite equal_lb_mask_equiv.\n    unfold nat_meet, nat_join.\n    do 2 rewrite nat_lb_nat.\n    rewrite nat_lb_plus, nat_lb_fix_0.\n    rewrite <- lb_ortho_meet_nil.\n    apply lb_ortho_plus_join.\n  Qed.\n\n  Local Notation sum_powers := (fun r n f e => ∑ n (fun i => f i * power (e i) r)).\n\n  Fact sum_powers_bound r n f e :\n                 r <> 0\n              -> (forall i, i < n -> f i < r) \n              -> (forall i j, i < j -> e i < e j)\n              -> sum_powers r n f e < power (e n) r.\n  Proof.\n    intros Hr; revert f e.\n    induction n as [ | n IHn ]; intros f e Hf He.\n    + rewrite msum_0; apply power_ge_1; auto.\n    + rewrite msum_plus1; auto.\n      apply lt_le_trans with (power (S (e n)) r).\n      2: apply power_mono_l; try omega; apply He; auto.\n      rewrite power_S.\n      apply lt_le_trans with (1*power (e n) r + f n * power (e n) r).\n      * rewrite Nat.mul_1_l; apply plus_lt_le_compat; auto.\n      * rewrite <- Nat.mul_add_distr_r; apply mult_le_compat; auto.\n        apply Hf; auto.\n  Qed.\n\n  Fact sum_powers_euclid r n f e : (forall j, j < n -> e 1 <= e (S j))\n        -> sum_powers r (S n) f e = f 0 * power (e 0) r \n                                  + sum_powers r n (fun i => f (S i)) (fun i => e (S i) - e 1) * power (e 1) r.\n  Proof.\n    intros Hf; simpl; f_equal.\n    rewrite <- sum_0n_scal_r.\n    apply msum_ext.\n    intros i Hi.\n    rewrite <- mult_assoc; f_equal.\n    rewrite <- power_plus; f_equal.\n    generalize (Hf _ Hi); omega.\n  Qed.\n\n  Fact nat_meet_joins m n f : m⇣msum nat_join 0 n f = msum nat_join 0 n (fun i => m⇣f i).\n  Proof.\n    revert f; induction n as [ | n IHn ]; intros f.\n    + rewrite msum_0, msum_0, nat_meet_n0; auto.\n    + do 2 rewrite msum_S.\n      rewrite nat_meet_join_distr_l, IHn; auto.\n  Qed.\n\n  Fact nat_join_eq_0 n m : n⇡m = 0 <-> n = 0 /\\ m = 0.\n  Proof.\n    split.\n    + do 3 rewrite equal_lb_mask_equiv. \n      unfold nat_join; rewrite nat_lb_nat.\n      repeat rewrite nat_lb_fix_0.\n      apply lb_join_nil_eq.\n    + intros []; subst; apply nat_join_0n.\n  Qed.\n\n  Fact nat_ortho_joins_left m n f : m⇣msum nat_join 0 n f = 0 \n                           <-> forall i, i < n -> m⇣f i = 0.\n  Proof.\n    rewrite nat_meet_joins.\n    revert f; induction n as [ | n IHn ]; intros f.\n    + rewrite msum_0; split; auto; intros; omega.\n    + rewrite msum_S, nat_join_eq_0, IHn.\n      split.\n      * intros [ H1 H2 ] [ | i ] ?; auto; apply H2; omega.\n      * intros H; split; intros; apply H; omega.\n  Qed.\n\n  Fact nat_ortho_sum_join n f : (forall i j, i <> j -> i < n -> j < n -> f i ⇣ f j = 0)\n                             -> ∑ n f = msum nat_join 0 n f.\n  Proof.\n    revert f; induction n as [ | n IHn ]; intros f Hf.\n    + do 2 rewrite msum_0; auto.\n    + do 2 rewrite msum_S.\n      rewrite IHn.\n      apply nat_ortho_plus_join, nat_ortho_joins_left.\n      * intros; apply Hf; omega.\n      * intros; apply Hf; omega.\n  Qed.\n\n  Fact nat_ortho_joins m n f g : msum nat_join 0 m f ⇣ msum nat_join 0 n g = 0 \n                             <-> forall i j, i < m -> j < n -> f i ⇣ g j = 0.\n  Proof.\n    rewrite nat_ortho_joins_left.\n    split; intros H.\n    + intros i j H1 H2; specialize (H _ H2).\n      rewrite nat_meet_comm in H |- *.\n      rewrite nat_ortho_joins_left in H; auto.\n    + intros i Hi; rewrite nat_meet_comm, nat_ortho_joins_left.\n      intros j Hj; rewrite nat_meet_comm; auto.\n  Qed.\n\n  Local Notation \"⇧\" := (fun r n f e => msum nat_join 0 n (fun i => f i * power (e i) r)).\n\n  Section nat_meet_digits.\n\n    Variable (q : nat) (Hq : 0 < q) (r : nat) (Hr : r = power q 2).\n          \n    Implicit Types (f g : nat -> nat).\n\n    Let Hr' : 2 <= r.\n    Proof. rewrite Hr; apply (@power_mono_l 1 _ 2); omega. Qed.\n\n    Fact nat_meet_powers_eq i a b : (a*power i r)⇣(b*power i r) = (a⇣b)*power i r.\n    Proof. rewrite Hr, <- power_mult, nat_meet_mult_power2; auto. Qed.\n\n    Fact binary_power_split i a : { u : nat & { v | a = u⇡(v*power i r) /\\ forall k, u⇣(k*power i r) = 0 } }.\n    Proof.\n      destruct (@euclid a (power i r)) as (u & v & H1 & H2).\n      + generalize (@power_ge_1 i r); intros; omega.\n      + exists v, u.\n        assert (forall k, v ⇣ (k*power i r) = 0) as E.\n        { intros k; replace v with (v+0*power i r) by ring.\n          replace (k*power i r) with (0+k*power i r) by ring.\n          rewrite Hr, <- power_mult.\n          rewrite nat_meet_euclid_power_2, nat_meet_0n, nat_meet_n0; auto.\n          rewrite power_mult, <- Hr; auto. }\n        split; auto.\n        rewrite H1, plus_comm, nat_ortho_plus_join; auto.\n    Qed.\n        \n\n    Fact binary_le_power_inv i a b : a ≲ b * power i r -> { a' | a = a' * power i r /\\ a' ≲ b }.\n    Proof.\n      intros H.\n      destruct (binary_power_split i a) as (u & v & H1 & H2).\n      exists (v⇣b).\n      rewrite binary_le_nat_meet in H.\n      rewrite H1 in H at 1.\n      rewrite nat_meet_comm, nat_meet_join_distr_l in H.\n      rewrite (nat_meet_comm _ u), H2, nat_join_0n, nat_meet_comm in H.\n      rewrite Hr, <- power_mult,  nat_meet_mult_power2, power_mult, <- Hr in H.\n      split; auto.\n    Qed.\n  \n    Section nat_meet_powers_neq.\n\n      Let nat_meet_neq_powers i j a b : i < j -> a < r -> b < r -> (a*power i r)⇣(b*power j r) = 0.\n      Proof.\n        intros H1 Ha Hb.\n        replace (a*power i r) with (a*power i r + 0*power j r) by ring.\n        replace (b*power j r) with (0+b*power j r) by ring.\n        rewrite Hr, <- power_mult, <- power_mult.\n        rewrite  nat_meet_euclid_power_2.\n        + rewrite nat_meet_n0, nat_meet_0n; ring.\n        + do 2 rewrite power_mult; rewrite <- Hr.\n          apply lt_le_trans with (power (S i) r).\n          - rewrite power_S; apply mult_lt_compat_r; auto.\n            apply power_ge_1; omega.\n          - apply power_mono_l; omega.\n        + rewrite power_mult, <- Hr.\n          apply power_ge_1; omega.\n      Qed.\n\n      Fact nat_meet_powers_neq i j a b : i <> j -> a < r -> b < r -> (a*power i r)⇣(b*power j r) = 0.\n      Proof.\n        intros Hij Ha Hb.\n        destruct (lt_eq_lt_dec i j) as [ [] | ]; try omega.\n        + apply nat_meet_neq_powers; auto.\n        + rewrite nat_meet_comm.\n          apply nat_meet_neq_powers; auto.\n      Qed.\n \n    End nat_meet_powers_neq.\n\n    Fact sum_powers_ortho n f e : \n                 (forall i, i < n -> f i < r) \n              -> (forall i j, i < n -> j < n -> e i = e j -> i = j)\n              -> sum_powers r n f e = ⇧ r n f e.\n    Proof.\n      revert f e; induction n as [ | n IHn ]; intros f e H1 H2.\n      + do 2 rewrite msum_0; auto.\n      + rewrite msum_S.\n        rewrite IHn.\n        2: intros; apply H1; omega.\n        2: intros i j Hi Hj E; apply H2 in E; omega.\n        rewrite nat_ortho_plus_join.\n        * rewrite msum_S; auto.\n        * apply nat_ortho_joins_left.\n          intros i Hi.\n          apply nat_meet_powers_neq.\n          - intros E; apply H2 in E; omega.\n          - apply H1; omega.\n          - apply H1; omega.\n    Qed.\n\n    Section double_sum_powers_ortho.\n \n      Variable (n : nat) (f e : nat -> nat -> nat)\n               (Hf : forall i j, j < i < n -> f i j < r)\n               (He : forall i1 j1 i2 j2, j1 < i1 < n -> j2 < i2 < n -> e i1 j1 = e i2 j2 -> i1 = i2 /\\ j1 = j2).\n\n      Let dsmpo_1 i : i < n -> sum_powers r i (f i) (e i) = ⇧ r i (f i) (e i).\n      Proof.\n        intros Hi; apply sum_powers_ortho.\n        + intros; apply Hf; omega.\n        + intros ? ? ? ?; apply He; omega.\n      Qed.\n\n      Fact double_sum_powers_ortho : ∑ n (fun i => sum_powers r i (f i) (e i)) = msum nat_join 0 n (fun i => ⇧ r i (f i) (e i)).\n      Proof.\n        rewrite nat_ortho_sum_join.\n        + apply msum_ext; intros; apply dsmpo_1; auto.\n        + intros; do 2 (rewrite dsmpo_1; auto).\n          apply nat_ortho_joins.\n          intros; apply nat_meet_powers_neq; auto.\n          intros E; apply He in E; omega.\n      Qed.\n\n    End double_sum_powers_ortho.\n\n    Fact sinc_injective n f : (forall i j, i < j < n -> f i < f j) -> forall i j, i < n -> j < n -> f i = f j -> i = j.\n    Proof.\n      intros Hf i j Hi Hj E.\n      destruct (lt_eq_lt_dec i j) as [ [] | ]; auto.\n      + generalize (Hf i j); intros; omega.\n      + generalize (Hf j i); intros; omega.\n    Qed.\n\n    Hint Resolve sinc_injective.\n\n    Section binary_le_meet_sum_powers.\n\n      Variable (n : nat) (f g e : nat -> nat)\n               (Hf : forall i, i < n -> f i < r) \n               (Hg : forall i, i < n -> g i < r)\n               (He : forall i j, i < j < n -> e i < e j).\n\n      Fact meet_sum_powers : (sum_powers r n f e)⇣(sum_powers r n g e) \n                           = sum_powers r n (fun i => f i ⇣ g i) e.\n      Proof.\n        generalize (sinc_injective _ He); intros H0.\n        simpl; do 3 (rewrite sum_powers_ortho; auto).\n        rewrite nat_meet_joins.\n        + apply msum_ext.\n          intros i Hi; rewrite nat_meet_comm.\n          rewrite nat_meet_joins.\n          rewrite msum_only_one with (i := i); auto.\n          * rewrite nat_meet_comm, Hr, <- power_mult.\n            apply nat_meet_mult_power2.\n          * intros j G1 G2; apply nat_meet_powers_neq; auto.\n        + intros i Hi.\n          apply le_lt_trans with (2 := Hf Hi).\n          apply binary_le_le; auto.\n      Qed.\n\n      Fact binary_le_sum_powers : sum_powers r n f e ≲ sum_powers r n g e <-> forall i, i < n -> f i ≲ g i.\n      Proof.\n        rewrite binary_le_nat_meet, meet_sum_powers.\n        split. \n        + intros E i Hi.\n          apply binary_le_nat_meet.\n          apply power_decomp_unique with (5 := E); auto.\n          intros j Hj; apply le_lt_trans with (2 := Hf Hj).\n          apply binary_le_le; auto.\n        + intros H; apply msum_ext.\n          intros; f_equal; apply binary_le_nat_meet; auto.\n      Qed.\n          \n    End binary_le_meet_sum_powers.\n\n    Fact sum_power_binary_lt p n f a : \n            0 < p <= q\n         -> (forall i j, i < j < n -> f i < f j)\n         -> (forall i, i < n -> a i < power p 2)  -> ∑ n (fun i => a i * power (f i) r) \n                                                   ≲ (power p 2-1) * ∑ n (fun i => power (f i) r).\n    Proof.\n      intros H1 H2 H3.\n      generalize (sinc_injective _ H2); intros H4.\n      rewrite <- sum_0n_scal_l.\n      apply binary_le_nat_meet.\n      rewrite meet_sum_powers; auto.\n      2: intros i Hi; rewrite Hr; apply lt_le_trans with (1 := H3 _ Hi), power_mono_l; omega. \n      2: { rewrite Hr.\n           intros i Hi. \n           generalize (@power_ge_1 p 2); intro.\n           unfold lt.\n           cutrewrite (S (power p 2 -1) = power p 2); try omega. \n           apply power_mono_l; omega. }\n      apply msum_ext; intros i Hi; f_equal.\n      apply binary_le_nat_meet, power_2_minus_1_gt.\n      assert (a i < power p 2); try omega.\n      apply lt_le_trans with (1 := H3 _ Hi), power_mono_l; omega.\n    Qed.\n\n    Fact sum_powers_binary_le_inv n f e m :\n                 (forall i, i < n -> f i < r) \n              -> (forall i j, i < j < n -> e i < e j)\n              -> m ≲ sum_powers r n f e\n              -> { k : nat &\n                 { g : nat -> nat & \n                 { h |  m = sum_powers r k g (fun i => e (h i)) \n                     /\\ k <= n\n                     /\\ (forall i, i < k -> g i <> 0 /\\ g i ≲ f (h i))\n                     /\\ (forall i, i < k -> h i < n)\n                     /\\ (forall i j, i < j < k -> h i < h j) } } }.\n    Proof.\n      intros H1 H2 H3.\n      generalize (sinc_injective _ H2); intros H0.\n      simpl in H3; rewrite sum_powers_ortho in H3; auto.\n      apply binary_le_joins_inv in H3.\n      destruct H3 as (k & g & h & H4 & H10 & H5 & H6 & H7).\n      generalize (sinc_injective _ H7); intros H8.\n      assert (forall i, { a | i < k -> g i = a * power (e (h i)) r /\\ a <> 0 /\\ a ≲ f (h i) }) as H.\n      { intros i.\n        destruct (le_lt_dec k i) as [ H | H ].\n        * exists 0; intros; omega.\n        * destruct (H5 _ H) as (G1 & G2).\n          rewrite Hr, <- power_mult in G2.\n          apply binary_le_mult_power2_inv in G2; auto.\n          destruct G2 as (a & G2 & G3 & G4).\n          rewrite power_mult, <- Hr in G2.\n          exists a; auto. }\n      set (g' := fun i => proj1_sig (H i)).\n      assert (Hg' : forall i, i < k -> g i = g' i * power (e (h i)) r /\\ g' i <> 0 /\\ g' i ≲ f (h i)).\n      { intro i; apply (proj2_sig (H i)). }\n      generalize g' Hg'; clear H g' Hg'; intros g' Hg'.\n\n      exists k, g', h; split; [ | split; [ | split ] ]; auto.\n      - rewrite sum_powers_ortho, H4.\n        * apply msum_ext. intros; apply Hg'; auto.\n        * intros i Hi; apply le_lt_trans with (f (h i)).\n          + apply binary_le_le, Hg'; auto.\n          + apply H1, H6; auto.\n        * intros ? ? ? ? E; apply H0 in E; auto.\n      - intros; apply Hg'; auto.\n    Qed.\n\n    Fact binary_le_sum_powers_inv n f e m :\n                 (forall i, i < n -> f i < r) \n              -> (forall i j, i < j < n -> e i < e j)\n              -> m ≲ sum_powers r n f e\n              -> { g | m = sum_powers r n g e /\\ forall i, i < n -> g i ≲ f i }.\n    Proof.\n      intros H1 H2 H3.\n      generalize (sinc_injective _ H2); intros H0.\n      simpl in H3; rewrite sum_powers_ortho in H3; auto.\n      apply binary_le_joins_inv' in H3.\n      destruct H3 as (g & H3 & H4).\n      assert (forall i, i < n -> { h | g i = h * power (e i) r /\\ h ≲ f i }) as h_full.\n      { intros i Hi; apply binary_le_power_inv; auto. }\n      set (h := fun i => match le_lt_dec n i with left _ => 0 | right H => proj1_sig (h_full _ H) end).\n      assert (Hh : forall i, i < n ->  g i = h i * power (e i) r /\\ h i ≲ f i).\n      { intros i Hi; unfold h; destruct (le_lt_dec n i) as [ | H' ]; try omega.\n        apply (proj2_sig (h_full _ H')). }\n      generalize h Hh; clear h_full h Hh; intros h Hh.\n      exists h; split; auto.\n      + rewrite H3.\n        rewrite sum_powers_ortho; auto.\n        * apply msum_ext; intros; apply Hh; auto.\n        * intros i Hi; apply le_lt_trans with (2 := H1 _ Hi), binary_le_le, Hh; auto.\n      + intros; apply Hh; auto.\n    Qed.\n\n    Fact sum_power_binary_lt_inv p n f e m :\n            0 < p <= q\n         -> (forall i j, i < j < n -> f i < f j)\n         -> (forall i j, i < j < n -> e i < e j)\n         -> m ≲ (power p 2-1) * ∑ n (fun i => power (f i) r)\n         -> exists a, m = ∑ n (fun i => a i * power (f i) r) \n                   /\\ forall i, i < n -> a i < power p 2.\n    Proof.\n      intros H1 H2 H3 H4.\n      rewrite <- sum_0n_scal_l in H4.\n      apply binary_le_sum_powers_inv in H4; auto.\n      + destruct H4 as (a & H5 & H6).\n        exists a; split; auto.\n        intros i Hi; apply power_2_minus_1_gt; auto.\n      + intros i Hi.\n        apply lt_le_trans with (power p 2).\n        - generalize (@power_ge_1 p 2); intros; omega.\n        - rewrite Hr; apply power_mono_l; omega.\n    Qed.\n\n  End nat_meet_digits.\n\n    \n        \n       \n \n      \n\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/coq-library-undecidability/Shared/Libs/DLW/Utils/bool_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6786578351940442}}
{"text": "Inductive bool : Type :=\n  | true \n  | false. \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 andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  if negb b1 then false \n  else if negb b2 then false \n  else b3.\n\n\nCompute (1+1).\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\nCompute (1+1).", "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/andb3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.7690802264851918, "lm_q1q2_score": 0.6786578329015222}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.btauto.Btauto.\nRequire Import Crypto.Util.ZUtil.Notations.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Testbit.\nLocal Open Scope bool_scope. Local Open Scope Z_scope.\n\nModule Z.\n  Lemma land_lxor_distr_l : forall a b c, (Z.lxor a b) &' c = (Z.lxor (a &' c) b) &' c.\n  Proof. intros; apply Z.bits_inj; intro; autorewrite with Ztestbit; btauto. Qed.\n  Lemma land_lxor_distr_r : forall a b c, (Z.lxor a b) &' c = (Z.lxor a (b &' c)) &' c.\n  Proof. intros; apply Z.bits_inj; intro; autorewrite with Ztestbit; btauto. Qed.\n  Lemma land_lxor_distr_both : forall a b c, (Z.lxor a b) &' c = (Z.lxor (a &' c) (b &' c)) &' c.\n  Proof. intros; apply Z.bits_inj; intro; autorewrite with Ztestbit; btauto. 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/Lxor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6786537825836746}}
{"text": "Require Import Coq.Reals.Reals.\n\n\nClass Ord A : Type :=\n  {\n    (* Slightly more verbose than necessary *)\n    lt_ord : A -> A -> Prop;\n\n    (* Axioms *)\n    le_dec (x : A) (y : A) : {lt_ord x y \\/ x = y} + {lt_ord y x};\n    lt_trans (x y z : A) : lt_ord x y -> lt_ord y z -> lt_ord x z;\n  }.\n\n\nDelimit Scope Ord_scope with O.\nOpen Scope Ord_scope.\n\nInfix \"<\" := lt_ord : Ord_scope.\n\nDefinition le_ord {A} `{Ord A} x y : Prop := (x < y \\/ x = y)%O.\nInfix \"<=\" := le_ord : Ord_scope.\n\nDefinition gt_ord {A} `{Ord A} x y : Prop := (y < x)%O.\nInfix \">\" := gt_ord : Ord_scope.\n\nDefinition ge_ord {A} `{Ord A} x y : Prop := (x > y \\/ x = y)%O.\nInfix \">=\" := ge_ord : Ord_scope.\n\n\nNotation \"x <= y <= z\" := (x <= y /\\ y <= z) : Ord_scope.\nNotation \"x <= y < z\" := (x <= y /\\ y < z) : Ord_scope.\nNotation \"x < y < z\" := (x < y /\\ y < z) : Ord_scope.\nNotation \"x < y <= z\" := (x < y /\\ y <= z) : Ord_scope.\n\n\nTheorem nat_le_lt_dec :\n  forall x y,\n    {(x < y \\/ x = y)%nat} + {(y < x)%nat}.\nProof.\n  intros x y.\n  destruct (le_lt_dec x y); auto using le_lt_or_eq.\nQed.\n\n\nLocal Open Scope nat_scope.\nInstance ordNat : Ord nat :=\n  {|\n    lt_ord x y := x < y;\n    le_dec := nat_le_lt_dec;\n    lt_trans := Nat.lt_trans;\n  |}.\n\n\nLocal Open Scope R_scope.\nInstance ordReal : Ord R :=\n  {|\n    lt_ord x y := x < y;\n    le_dec x y := Rle_lt_dec x y;\n    lt_trans := Rlt_trans;\n  |}.\n\n\nLocal Open Scope Ord_scope.\n\n\nDefinition max {A} `{Ord A} x y : A :=\n  match le_dec x y with\n  | left _ => y\n  | right _ => x\n  end.\n\n\nTheorem max_lub_lt_iff :\n  forall {A} `{Ord A} (x y z : A),\n    max x y < z <-> (x < z) /\\ (y < z).\nProof.\n  intros A H x y z.\n  split; unfold max; destruct (le_dec x y) as [[Hlt | Heq] | Heq]; try tauto;\n  subst; eauto using lt_trans.\nQed.\n\n", "meta": {"author": "Chobbes", "repo": "Coqplexity", "sha": "0a914ce2a9f4a751925308c37ac165866453e3d2", "save_path": "github-repos/coq/Chobbes-Coqplexity", "path": "github-repos/coq/Chobbes-Coqplexity/Coqplexity-0a914ce2a9f4a751925308c37ac165866453e3d2/ord.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623015, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6786537662910769}}
{"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 base bar arity ramsey_paper.\n\nSet Implicit Arguments.\n\nLocal Notation \"A ⊆ B\" := (∀x, A x -> B x).\nLocal Notation \"A ∩ B\" := (fun z => A z /\\ B z).\nLocal Notation \"A ∪ B\" := (fun z => A z \\/ B z).\n\nLocal Notation \"R ⋅ x\" := (fun l => R (x::l)).\nLocal Notation \"R ↑ x\" := (fun l => R l \\/ R (x::l)).\n\n(** Symbols for copy/paste: ∩ ∪ ⊆ ⊇ ⊔ ⊓ ⊑ ≡  ⋅ ↑ ↓ ⇑ ⇓ ∀ ∃ *)\n\nSection list_lift.\n\n  Variable X : Type.\n  \n  Implicit Type (R S : list X -> Prop).\n  \n  Fact one_lift_mono R S : R ⊆ S -> forall x, R↑x ⊆ S↑x.\n  Proof. intros H x l; generalize (H l) (H (x::l)); tauto. Qed.\n\n  Hint Resolve one_lift_mono.\n\n  Fixpoint list_lift R l :=\n    match l with\n      | nil  => R\n      | x::l => (R⇑l)↑x\n    end\n  where \"R ⇑ l\" := (list_lift R l).\n\n  Fact list_lift_app R l m : R⇑(l++m) = R⇑m⇑l.\n  Proof. induction l; simpl; auto; rewrite IHl; auto. Qed.\n \n  Fact list_lift_mono R S : R ⊆ S -> forall l, R⇑l ⊆ S⇑l.\n  Proof.\n    intros H l; revert R S H; induction l; simpl; intros R S H; auto.\n    apply one_lift_mono, IHl; auto.\n  Qed.\n  \n  Fact list_lift_spec R l m : (R⇑l) m <-> ∃k, k <sl l /\\ R (rev k++m).\n  Proof.\n    revert m R.\n    induction l as [ | x l IHl ]; intros m R; simpl.\n    * split.\n      + exists nil; split; auto; constructor.\n      + intros (l & H1 & H2).\n        rewrite sl_nil_inv in H1; subst; auto.\n    * do 2 rewrite IHl; split.\n      + intros [ (k & H1 & H2) | (k & H1 & H2) ].\n        - exists k; split; auto; constructor; auto.\n        - exists (x::k); split.\n          ** constructor; auto.\n          ** simpl; rewrite app_ass; auto.\n      + intros (k & H1 & H2).\n        apply sublist_cons_inv_rt in H1.\n        destruct H1 as [ H1 | (k' & H1 & H3) ].\n        - left; exists k; auto.\n        - subst; right; exists k'; split; auto.\n          revert H2; simpl; rewrite app_ass; auto.\n  Qed.\n\nEnd list_lift.\n  \nArguments list_lift {X}.\nLocal Notation \"R ⇑ l\" := (list_lift R l).\n\nHint Resolve one_lift_mono list_lift_mono.\n\nSection AF.\n\n  Variable (X : Type).\n\n  Implicit Type (R S : list X -> Prop).\n\n  (** AF is an inductive characterization Almost Full *)\n\n  Inductive AF R : Prop := \n    | in_AF_0 : (∀x, R x)      -> AF R\n    | in_AF_1 : (∀x, AF (R↑x)) -> AF R.\n\n  Fact AF_mono R S : R ⊆ S -> AF R -> AF S.\n  Proof.\n    intros H1 H2; revert H2 S H1. \n    induction 1 as [ | R HR IHR ]; intros S HS; \n      [ constructor 1 | constructor 2 ]; auto.\n    intros x; apply (IHR x), one_lift_mono; auto. \n  Qed.\n\n  (* Almost Full is an instance of Ultimately Greatest (ie least for ⊇) *)\n\n  Local Fact AF_UL R : AF R <-> UF (fun R S => R ⊆ S) (fun R S => R ∪ S) \n                                     (fun _ => True) (fun a R => R⋅a) R.\n  Proof. \n    split; (induction 1 as [ ? H | ]; [ constructor 1 | constructor 2 ]; auto); \n      unfold lattice_eq in *; auto.\n    intros; apply H; auto.\n  Qed.\n  \n  (* This is Ramsey's theorem as in \"Stop When you are almost full\" but\n     proved using the generic lattice based proof of Coquand *)\n  \n  Theorem AF_Ramsey R S : Ar R -> Ar S -> AF R -> AF S -> AF (R∩S).\n  Proof.\n    rewrite Ar_US, Ar_US, AF_UL, AF_UL, AF_UL.\n    revert R S. \n    apply (@Ramsey_lattice) with (bot := fun _ => False); auto.\n    * split; auto; intros [] ? [|]; auto.\n    * split; auto; intros H; split; apply H; auto.\n    * tauto.\n    * tauto.\n  Qed.\n\n  (* This seems to be a good definition of good ?\n     Is there an equivalent inductive characterization ? \n     \n     It comes from list_lift_spec\n   *)\n  \n  Definition GOOD R l := ∀m, ∃k, k <sl l /\\ R (rev k++m).\n  \n  Fact GOOD_list_lift_eq R l : GOOD R l <-> ∀m, (R⇑l) m.\n  Proof. split; intros H m; apply list_lift_spec; auto. Qed.\n  \n  Fact GOOD_nil R : (∀l, R l) -> GOOD R nil.\n  Proof. rewrite GOOD_list_lift_eq; auto. Qed.\n  \n  Fact GOOD_snoc R x l : GOOD (R↑x) l -> GOOD R (l++x::nil).\n  Proof.\n    do 2 rewrite GOOD_list_lift_eq.\n    intros H1 m.\n    rewrite list_lift_app; apply H1.\n  Qed.\n  \n  Fact GOOD_mono R S : R ⊆ S -> GOOD R ⊆ GOOD S.\n  Proof.\n    intros H1 l H2 m; generalize (H2 m).\n    intros (k & H3 & H4); exists k; split; auto.\n  Qed.\n  \n  Fact GOOD_app R ll mm : GOOD (R⇑mm) ll -> GOOD R (ll ++ mm).\n  Proof.\n    revert R; induction mm as [ | x mm IHmm ] using list_snoc_ind; intros R; simpl.\n    * rewrite <- app_nil_end; auto.\n    * intros H.\n      rewrite <- app_ass.\n      apply GOOD_snoc, IHmm.\n      revert H; apply GOOD_mono.\n      rewrite list_lift_app; simpl; auto.\n  Qed. \n  \n  Fact GOOD_app_left R l m : GOOD R m -> GOOD R (l++m).\n  Proof.\n    intros H p.\n    destruct (H p) as (k & H1 & H2).\n    exists k; split; auto.\n    apply sl_trans with (1 := H1), sl_app_left.\n  Qed.\n\n  Fact GOOD_cons R x l : GOOD R l -> GOOD R (x::l).\n  Proof. apply GOOD_app_left with (l := _::nil). Qed.\n\n  Fact GOOD_app_right R l m : GOOD R l -> GOOD R (l++m).\n  Proof.\n    intros H p.\n    destruct (H p) as (k & H1 & H2).\n    exists k; split; auto.\n    apply sl_trans with (1 := H1), sl_app_right.\n  Qed.\n\n  Fact bar_GOOD_nil R : bar (GOOD R) nil <-> ∀l, bar (GOOD R) l.\n  Proof. apply bar_nil, GOOD_cons. Qed.\n\n  Section AF_bar_GOOD.\n\n    Let AF_bar_rec R : AF R -> ∀ l S, R ⊆ S⇑l -> bar (GOOD S) l.\n    Proof.\n      induction 1 as [ R HR | R HR IHR ]; intros l S HS.\n      * apply in_bar_0.\n        apply GOOD_app with (ll := nil), GOOD_mono with (1 := HS), GOOD_nil, HR.\n      * apply in_bar_1; intros x.\n        apply (IHR x (x::l)), one_lift_mono, HS.\n    Qed.\n  \n    Let bar_AF R l : bar (GOOD R) l -> AF (R⇑l).\n    Proof.\n      induction 1 as [ l Hl | l Hl IHl ].\n      * constructor 1; apply GOOD_list_lift_eq, Hl.\n      * constructor 2; apply IHl.\n    Qed.\n  \n    Theorem AF_bar_lift_eq R l : AF (R⇑l) <-> bar (GOOD R) l.\n    Proof.\n      split.\n      * intros H; apply AF_bar_rec with (1 := H); auto.\n      * apply bar_AF.\n    Qed.\n\n  End AF_bar_GOOD.\n\n  Inductive subseq : (nat -> X) -> list X -> Prop :=\n    | in_ss_0 : forall f, subseq f nil\n    | in_ss_1 : forall f l, subseq (fun n => f (S n)) l -> subseq f l\n    | in_ss_2 : forall f l, subseq (fun n => f (S n)) l -> subseq f (f 0::l).\n\n  Fact sl_subseq f l m : l <sl m -> subseq f m -> subseq f l.\n  Proof.\n    intros H1 H2; revert H2 l H1.\n    induction 1 as [ f | f m Hm IHm | f m Hm IHm ]; intros l Hl.\n    + apply sl_nil_inv in Hl; subst; constructor 1.\n    + constructor 2; auto.\n    + apply sublist_cons_inv_rt in Hl.\n      destruct Hl as [ Hl | (l' & -> & Hl) ].\n      * constructor 2; auto.\n      * constructor 3; auto.\n  Qed.\n\n  Fact pfx_subseq f n : subseq f (pfx f n).\n  Proof.\n    revert f; induction n; intros; simpl.\n     + constructor.\n     + constructor 3; auto.\n  Qed. \n\n  Fact subseq_pfx_eq f l : subseq f l <-> exists n, l <sl pfx f n.\n  Proof.\n    split.\n    + induction 1 as [ f | f l Hl IHl | f l Hl IHl ].\n      * exists 0; constructor.\n      * destruct IHl as (n & Hn).\n        exists (S n); simpl; constructor 3; auto.\n      * destruct IHl as (n & Hn).\n        exists (S n); simpl; constructor 2; auto.\n    + intros (n & Hn).\n      apply sl_subseq with (1 := Hn).\n      apply pfx_subseq.\n  Qed.\n\n  Fact bar_GOOD_seq R : bar (GOOD R) nil -> forall f, exists l, subseq f l /\\ GOOD R (rev l).\n  Proof.\n    intros H f.\n    apply bar_seq with (f := f) (n := 0) in H; auto.\n    destruct H as (k & _ & Hk); exists (rev (pfx_rev f k)); split; auto.\n    2: rewrite rev_involutive; auto.\n    clear Hk.\n    rewrite <- pfx_pfx_rev.\n    revert f; induction k as [ | k IHk ]; intros f; simpl.\n    + constructor.\n    + constructor 3; auto.\n  Qed.\n  \n  Corollary AF_bar_eq R : AF R <-> bar (GOOD R) nil.\n  Proof. apply AF_bar_lift_eq with (l := nil). Qed.\n\n  Fact AF_seq R f : AF R -> exists l, subseq f l /\\ GOOD R (rev l).\n  Proof.\n    intros H.\n    rewrite AF_bar_eq in H.\n    revert H f.\n    apply bar_GOOD_seq.\n  Qed.\n\n  Corollary bar_list_lift R l : bar (GOOD R) l <-> bar (GOOD (R⇑l)) nil.\n  Proof. rewrite <- AF_bar_lift_eq, AF_bar_eq; tauto. Qed.\n\n  (* For a strict kary relation, we have a simpler characterizatino of GOOD *)\n      \n  Theorem GOOD_kary_strict k R : \n      kary_strict k R -> ∀ll, GOOD R ll <-> ∃m, m <sl ll /\\ R (rev m) /\\ length m = k.\n  Proof.\n    rewrite kary_strict_spec; intros H ll; split.\n    * intros H1.\n      destruct (H1 nil) as (m & H2 & H3).\n      rewrite <- app_nil_end in H3.\n      rewrite H in H3.\n      destruct H3 as (l & r & H3 & H4 & H5).\n      exists (rev l).\n      rewrite rev_involutive, rev_length; repeat split; auto.\n      apply sl_trans with (2 := H2).\n      rewrite <- (rev_involutive m), H4.\n      apply sl_rev, sl_app_right.\n    * intros (m & H1 & H2 & H3) p.\n      exists m; split; auto.\n      apply H; exists (rev m), p.\n      rewrite rev_length; auto.\n  Qed.\n\n  Fact AF_seq_strict k R f : kary_strict k R -> AF R -> exists m, subseq f m /\\ R m /\\ length m = k.\n  Proof.\n    intros H1 H2.\n    apply AF_seq with (f := f) in H2.\n    destruct H2 as (l & H2 & H3).\n    rewrite GOOD_kary_strict with (1 := H1) in H3.\n    destruct H3 as (m & H3 & H4 & H5).\n    exists (rev m); rewrite rev_length; repeat split; auto.\n    revert H2; apply sl_subseq.\n    rewrite <- (rev_involutive l).\n    apply sl_rev; auto.\n  Qed.\n\n  Fact sl_pfx_cst (x : X) l n : l <sl pfx (fun _ => x) n -> Forall (eq x) l.\n  Proof.\n    revert l; induction n as [ | n IHn ]; intros l H.\n    + apply sl_nil_inv in H; subst; constructor.\n    + simpl in H.\n      apply sublist_cons_inv_rt in H.\n      destruct H as [ H | (l' & -> & H) ]; auto.\n  Qed.\n\n  (* There is ONLY ONE unary strict AF relation, up to extentionality of course *)\n\n  Fact AF_unary_strict R : kary_strict 1 R -> AF R -> forall l, R l <-> l <> nil.\n  Proof.\n    intros H1 H2.\n    assert (H3 : forall x, R (x::nil)).\n    { intros x.\n      destruct AF_seq_strict with (1 := H1) (2 := H2) (f := fun _ : nat => x)\n        as (m & H3 & H4 & H5).\n      rewrite subseq_pfx_eq in H3.\n      destruct H3 as (n & Hn).\n      destruct m as [ | u [ | ? ? ] ]; try discriminate.\n      assert (E : u = x).\n      { clear H4 H5.\n        apply sl_pfx_cst in Hn.\n        inversion Hn; auto. }\n      subst; auto. }\n    simpl in H1; destruct H1 as (H0 & H1).\n    intros [ | x l ].\n    + split; tauto.\n    + rewrite H1; split; auto; discriminate.\n  Qed.\n\n  Fact AF_unary R : kary 1 R -> AF R -> forall x, R (x::nil).\n  Proof.\n    intros H1 H2 x.\n    apply AF_seq with (f := fun _ => x) in H2.\n    destruct H2 as (l & H2 & H3).\n    simpl in H1.\n    red in H3.\n    destruct (H3 (x::nil)) as (k & H4 & H5); auto.\n    clear H3.\n    apply sl_rev in H4.\n    rewrite rev_involutive in H4.\n    revert H4 H5; generalize (rev k); clear k; intros k H4 H5.\n    destruct k as [ | y k ]; auto.\n    assert (Hy : y = x).\n    { apply sl_subseq with (1 := H4) in H2.\n      apply subseq_pfx_eq in H2.\n      destruct H2 as (n & H2).\n      apply sl_pfx_cst in H2.\n      inversion H2; auto. }\n    subst.\n    simpl in H5; apply H1 in H5; auto.\n  Qed.\n\nEnd AF.\n\n\n", "meta": {"author": "DmxLarchey", "repo": "Ramsey", "sha": "24510f63d4290149c4944fe68267d342345621ed", "save_path": "github-repos/coq/DmxLarchey-Ramsey", "path": "github-repos/coq/DmxLarchey-Ramsey/Ramsey-24510f63d4290149c4944fe68267d342345621ed/src/AF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6786537590500901}}
{"text": "(* SlopeMisc.v *)\n\nRequire Import Utf8.\nRequire Import QArith.\n\nRequire Import Slope_base.\nRequire Import Misc.\n\nTheorem Qcmp_eq : ∀ a, (a ?= a) = Eq.\nProof.\nintros a; apply Qeq_alt; reflexivity.\nQed.\n\nTheorem Qcmp_lt_gt : ∀ a b, (a ?= b) = Lt → (b ?= a) = Gt.\nProof.\nintros a b H; apply Qlt_alt in H; apply Qgt_alt; assumption.\nQed.\n\nTheorem Qcmp_gt_lt : ∀ a b, (a ?= b) = Gt → (b ?= a) = Lt.\nProof.\nintros a b H; apply Qgt_alt in H; apply Qlt_alt; assumption.\nQed.\n\nTheorem Qcmp_sym : ∀ a b c d,\n  (a ?= b) = (c ?= d)\n  → (b ?= a) = (d ?= c).\nProof.\nintros a b c d H.\nremember (a ?= b) as cmp.\nsymmetry in Heqcmp, H.\ndestruct cmp.\n apply Qeq_alt in Heqcmp.\n apply Qeq_alt in H.\n rewrite Heqcmp, H.\n do 2 rewrite Qcmp_eq.\n reflexivity.\n\n apply Qcmp_lt_gt in Heqcmp.\n apply Qcmp_lt_gt in H.\n rewrite <- H in Heqcmp; assumption.\n\n apply Qcmp_gt_lt in Heqcmp.\n apply Qcmp_gt_lt in H.\n rewrite <- H in Heqcmp; assumption.\nQed.\n\nTheorem slope_cmp_flatten : ∀ x₁ y₁ x₂ y₂ x₃ y₃ x₄ y₄,\n  x₁ < x₂\n  → x₃ < x₄\n    → (slope_expr (x₁, y₁) (x₂, y₂) ?= slope_expr (x₃, y₃) (x₄, y₄)) =\n      (y₂ * x₄ + y₁ * x₃ + y₃ * x₂ + y₄ * x₁ ?=\n       y₄ * x₂ + y₃ * x₁ + y₁ * x₄ + y₂ * x₃).\nProof.\nintros x₁ y₁ x₂ y₂ x₃ y₃ x₄ y₄ Hlt₁₂ Hlt₃₄.\nunfold slope_expr; simpl.\nrewrite Qcmp_shift_mult_r; [ idtac | apply Qlt_minus; assumption ].\nrewrite Qmult_div_swap.\nrewrite Qcmp_shift_mult_l; [ idtac | apply Qlt_minus; assumption ].\nrepeat rewrite Qmult_minus_distr_l.\nrepeat rewrite Qmult_minus_distr_r.\nrepeat rewrite Qminus_minus_assoc.\nrepeat rewrite <- Qplus_minus_swap.\nrepeat rewrite <- Qcmp_plus_minus_cmp_r.\nrepeat rewrite <- Qplus_minus_swap.\nrepeat rewrite <- Qplus_cmp_cmp_minus_r.\nreflexivity.\nQed.\n\n(* should use 'slope_cmp_flatten' like the other theorems, but pb with\n   conditions... *)\nTheorem slope_eq : ∀ x₁ y₁ x₂ y₂ x₃ y₃,\n  ¬x₁ == x₂\n  → ¬x₂ == x₃\n    → ¬x₃ == x₁\n      → slope_expr (x₁, y₁) (x₂, y₂) == slope_expr (x₁, y₁) (x₃, y₃)\n        → slope_expr (x₁, y₁) (x₂, y₂) == slope_expr (x₂, y₂) (x₃, y₃).\nProof.\nintros x₁ y₁ x₂ y₂ x₃ y₃ H₁₂ H₂₃ H₃₁ H.\nunfold slope_expr in H |-*.\napply Qeq_shift_mult_l in H.\n symmetry in H.\n rewrite Qmult_div_swap in H.\n apply Qeq_shift_mult_l in H.\n  apply Qeq_shift_div_l.\n   intros HH; apply H₁₂.\n   symmetry; apply Qminus_eq; assumption.\n\n   symmetry.\n   rewrite Qmult_div_swap.\n   apply Qeq_shift_div_l.\n    intros HH; apply H₂₃.\n    symmetry; apply Qminus_eq; assumption.\n\n    setoid_replace ((y₃ - y₁) * (x₂ - x₁)) with\n     (x₂ * y₃ - x₂ * y₁ - x₁ * y₃ + x₁ * y₁) in H by ring.\n    setoid_replace ((y₂ - y₁) * (x₃ - x₁)) with\n     (x₃ * y₂ - x₃ * y₁ - x₁ * y₂ + x₁ * y₁) in H by ring.\n    apply Qplus_inj_r in H.\n    setoid_replace ((y₃ - y₂) * (x₂ - x₁)) with\n     (x₁ * y₂ + x₂ * y₃ - x₁ * y₃ - x₂ * y₂) by ring.\n    setoid_replace ((y₂ - y₁) * (x₃ - x₂)) with\n     (x₂ * y₁ + x₃ * y₂ - x₃ * y₁ - x₂ * y₂) by ring.\n    unfold Qminus at 1.\n    unfold Qminus at 2.\n    apply Qplus_inj_r.\n    do 2 apply Qminus_eq_eq_plus_r in H.\n    do 4 rewrite <- Qplus_minus_swap in H.\n    symmetry in H.\n    do 2 apply Qminus_eq_eq_plus_r in H.\n    apply Qeq_plus_minus_eq_r.\n    rewrite <- Qplus_minus_swap.\n    symmetry.\n    apply Qeq_plus_minus_eq_r.\n    setoid_replace (x₂ * y₁ + x₃ * y₂ + x₁ * y₃) with\n     (x₃ * y₂ + x₁ * y₃ + x₂ * y₁) by ring.\n    rewrite H; ring.\n\n  intros HH; apply H₃₁.\n  apply Qminus_eq; assumption.\n\n intros HH; apply H₁₂.\n symmetry; apply Qminus_eq; assumption.\nQed.\n\nTheorem slope_cmp_norm₁₂₁₃ : ∀ x₁ y₁ x₂ y₂ x₃ y₃,\n  x₁ < x₂ < x₃\n  → (slope_expr (x₁, y₁) (x₂, y₂) ?= slope_expr (x₁, y₁) (x₃, y₃)) =\n    (x₁ * y₃ + x₂ * y₁ + x₃ * y₂ ?= x₁ * y₂ + x₂ * y₃ + x₃ * y₁).\nProof.\nintros x₁ y₁ x₂ y₂ x₃ y₃ (Hlt₁, Hlt₂).\nassert (x₁ < x₃) as Hlt₃ by (eapply Qlt_trans; eassumption).\nrewrite slope_cmp_flatten; [ idtac | assumption | assumption ].\nrewrite <- Qplus_assoc, Qplus_comm, Qplus_assoc.\nremember (y₁ * x₂ + y₃ * x₁ + y₂ * x₃ + y₁ * x₁) as t.\nrewrite <- Qplus_assoc, Qplus_comm, Qplus_assoc; subst t.\nrewrite <- Qplus_cmp_compat_r.\nsetoid_replace (y₁ * x₂ + y₃ * x₁ + y₂ * x₃) with\n (x₁ * y₃ + x₂ * y₁ + x₃ * y₂) by ring.\nsetoid_replace (y₁ * x₃ + y₂ * x₁ + y₃ * x₂) with\n (x₁ * y₂ + x₂ * y₃ + x₃ * y₁) by ring.\nreflexivity.\nQed.\n\nTheorem slope_cmp_norm₁₃₁₂ : ∀ x₁ y₁ x₂ y₂ x₃ y₃,\n  x₁ < x₂ < x₃\n  → (slope_expr (x₁, y₁) (x₃, y₃) ?= slope_expr (x₁, y₁) (x₂, y₂)) =\n    (x₁ * y₂ + x₂ * y₃ + x₃ * y₁ ?= x₁ * y₃ + x₂ * y₁ + x₃ * y₂).\nProof.\nintros; apply Qcmp_sym, slope_cmp_norm₁₂₁₃; assumption.\nQed.\n\nTheorem slope_cmp_norm₁₃₂₃ : ∀ x₁ y₁ x₂ y₂ x₃ y₃,\n  x₁ < x₂ < x₃\n  → (slope_expr (x₁, y₁) (x₃, y₃) ?= slope_expr (x₂, y₂) (x₃, y₃)) =\n    (x₁ * y₃ + x₂ * y₁ + x₃ * y₂ ?= x₁ * y₂ + x₂ * y₃ + x₃ * y₁).\nProof.\nintros x₁ y₁ x₂ y₂ x₃ y₃ (Hlt₁, Hlt₂).\nassert (x₁ < x₃) as Hlt₃ by (eapply Qlt_trans; eassumption).\nrewrite slope_cmp_flatten; [ idtac | assumption | assumption ].\nrepeat rewrite <- Qplus_assoc.\nrewrite <- Qplus_cmp_compat_l.\nrepeat rewrite Qplus_assoc.\nsetoid_replace (y₁ * x₂ + y₂ * x₃ + y₃ * x₁) with\n (x₁ * y₃ + x₂ * y₁ + x₃ * y₂) by ring.\nsetoid_replace (y₂ * x₁ + y₁ * x₃ + y₃ * x₂) with\n (x₁ * y₂ + x₂ * y₃ + x₃ * y₁) by ring.\nreflexivity.\nQed.\n\nTheorem slope_cmp_norm₂₃₁₃ : ∀ x₁ y₁ x₂ y₂ x₃ y₃,\n  x₁ < x₂ < x₃\n  → (slope_expr (x₂, y₂) (x₃, y₃) ?= slope_expr (x₁, y₁) (x₃, y₃)) =\n    (x₁ * y₂ + x₂ * y₃ + x₃ * y₁ ?= x₁ * y₃ + x₂ * y₁ + x₃ * y₂).\nProof.\nintros; apply Qcmp_sym, slope_cmp_norm₁₃₂₃; assumption.\nQed.\n\nTheorem slope_cmp₂ : ∀ pt₁ pt₂ pt₃,\n  fst pt₁ < fst pt₂ < fst pt₃\n  → (slope_expr pt₁ pt₃ ?= slope_expr pt₁ pt₂) =\n    (slope_expr pt₂ pt₃ ?= slope_expr pt₁ pt₃).\nProof.\nintros (x₁, y₁) (x₂, y₂) (x₃, y₃) (Hlt₁, Hlt₂).\nassert (x₁ < x₃) as Hlt₃ by (eapply Qlt_trans; eassumption).\nrewrite slope_cmp_norm₁₃₁₂; [ idtac | split; assumption ].\nrewrite slope_cmp_norm₂₃₁₃; [ idtac | split; assumption ].\nreflexivity.\nQed.\nTheorem slope_lt_1312_2313 : ∀ pt₁ pt₂ pt₃,\n  fst pt₁ < fst pt₂ < fst pt₃\n  → slope_expr pt₁ pt₃ < slope_expr pt₁ pt₂\n    → slope_expr pt₂ pt₃ < slope_expr pt₁ pt₃.\nProof.\nintros (x₁, y₁) (x₂, y₂) (x₃, y₃) Hlt H.\nrewrite Qlt_alt in H |- *; rewrite <- H.\nsymmetry; apply slope_cmp₂; assumption.\nQed.\n", "meta": {"author": "roglo", "repo": "puiseuxth", "sha": "5b1cdc4d42e3585f5fdd57431cc06a3ffcdc3fb5", "save_path": "github-repos/coq/roglo-puiseuxth", "path": "github-repos/coq/roglo-puiseuxth/puiseuxth-5b1cdc4d42e3585f5fdd57431cc06a3ffcdc3fb5/coq/SlopeMisc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6785963685874039}}
{"text": "(** * Types: Type Systems *)\n\nRequire Export Auto.\n\n(** Our next major topic is _type systems_ -- static program\n    analyses that classify expressions according to the \"shapes\" of\n    their results.  We'll begin with a typed version of a very simple\n    language with just booleans and numbers, to introduce the basic\n    ideas of types, typing rules, and the fundamental theorems about\n    type systems: _type preservation_ and _progress_.  Then we'll move\n    on to the _simply typed lambda-calculus_, which lives at the core\n    of every modern functional programming language (including\n    Coq). *)\n\n(* ###################################################################### *)\n(** * Typed Arithmetic Expressions *)\n\n(** To motivate the discussion of type systems, let's begin as\n    usual with an extremely simple toy language.  We want it to have\n    the potential for programs \"going wrong\" because of runtime type\n    errors, so we need something a tiny bit more complex than the\n    language of constants and addition that we used in chapter\n    [Smallstep]: a single kind of data (just numbers) is too simple,\n    but just two kinds (numbers and booleans) already gives us enough\n    material to tell an interesting story.\n\n    The language definition is completely routine.  The only thing to\n    notice is that we are _not_ using the [asnum]/[aslist] trick that\n    we used in chapter [HoareList] to make all the operations total by\n    forcibly coercing the arguments to [+] (for example) into numbers.\n    Instead, we simply let terms get stuck if they try to use an\n    operator with the wrong kind of operands: the [step] relation\n    doesn't relate them to anything. *)\n\n(* ###################################################################### *)\n(** ** Syntax *)\n\n(** Informally:\n    t ::= true\n        | false\n        | if t then t else t\n        | 0\n        | succ t\n        | pred t\n        | iszero t\n    Formally:\n*)\n\nInductive tm : Type :=\n  | ttrue : tm\n  | tfalse : tm\n  | tif : tm -> tm -> tm -> tm\n  | tzero : tm\n  | tsucc : tm -> tm\n  | tpred : tm -> tm\n  | tiszero : tm -> tm.\n\n(** _Values_ are [true], [false], and numeric values... *)\n\nInductive bvalue : tm -> Prop :=\n  | bv_true : bvalue ttrue\n  | bv_false : bvalue tfalse.\n\nInductive nvalue : tm -> Prop :=\n  | nv_zero : nvalue tzero\n  | nv_succ : forall t, nvalue t -> nvalue (tsucc t).\n\nDefinition value (t:tm) := bvalue t \\/ nvalue t.\n\nHint Constructors bvalue nvalue.\nHint Unfold value.  \nHint Unfold beq_id beq_nat extend.\n\n(* ###################################################################### *)\n(** ** Operational Semantics *)\n\n(** Informally: *)\n(**\n                    ------------------------------                  (ST_IfTrue)\n                    if true then t1 else t2 ==> t1\n\n                   -------------------------------                 (ST_IfFalse)\n                   if false then t1 else t2 ==> t2\n\n                              t1 ==> t1'\n                      -------------------------                         (ST_If)\n                      if t1 then t2 else t3 ==>\n                        if t1' then t2 else t3\n\n                              t1 ==> t1'\n                         --------------------                         (ST_Succ)\n                         succ t1 ==> succ t1'\n\n                             ------------                         (ST_PredZero)\n                             pred 0 ==> 0\n\n                           numeric value v1\n                        ---------------------                     (ST_PredSucc)\n                        pred (succ v1) ==> v1\n\n                              t1 ==> t1'\n                         --------------------                         (ST_Pred)\n                         pred t1 ==> pred t1'\n\n                          -----------------                     (ST_IszeroZero)\n                          iszero 0 ==> true\n\n                           numeric value v1\n                      --------------------------                (ST_IszeroSucc)\n                      iszero (succ v1) ==> false\n\n                              t1 ==> t1'\n                       ------------------------                     (ST_Iszero)\n                       iszero t1 ==> iszero t1'\n*)\n\n(** Formally: *)\n\nReserved Notation \"t1 '==>' t2\" (at level 40).\n\nInductive step : tm -> tm -> Prop :=\n  | ST_IfTrue : forall t1 t2,\n      (tif ttrue t1 t2) ==> t1\n  | ST_IfFalse : forall t1 t2,\n      (tif tfalse t1 t2) ==> t2\n  | ST_If : forall t1 t1' t2 t3,\n      t1 ==> t1' ->\n      (tif t1 t2 t3) ==> (tif t1' t2 t3)\n  | ST_Succ : forall t1 t1',\n      t1 ==> t1' ->\n      (tsucc t1) ==> (tsucc t1')\n  | ST_PredZero :\n      (tpred tzero) ==> tzero\n  | ST_PredSucc : forall t1,\n      nvalue t1 ->\n      (tpred (tsucc t1)) ==> t1\n  | ST_Pred : forall t1 t1',\n      t1 ==> t1' ->\n      (tpred t1) ==> (tpred t1')\n  | ST_IszeroZero :\n      (tiszero tzero) ==> ttrue\n  | ST_IszeroSucc : forall t1,\n       nvalue t1 ->\n      (tiszero (tsucc t1)) ==> tfalse\n  | ST_Iszero : forall t1 t1',\n      t1 ==> t1' ->\n      (tiszero t1) ==> (tiszero t1')\n\nwhere \"t1 '==>' t2\" := (step t1 t2).\n\nTactic Notation \"step_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"ST_IfTrue\" | Case_aux c \"ST_IfFalse\" | Case_aux c \"ST_If\" \n  | Case_aux c \"ST_Succ\" | Case_aux c \"ST_PredZero\"\n  | Case_aux c \"ST_PredSucc\" | Case_aux c \"ST_Pred\" \n  | Case_aux c \"ST_IszeroZero\" | Case_aux c \"ST_IszeroSucc\"\n  | Case_aux c \"ST_Iszero\" ].\n\nHint Constructors step.\n\n(** Notice that the [step] relation doesn't care about whether\n    expressions make global sense -- it just checks that the operation\n    in the _next_ reduction step is being applied to the right kinds\n    of operands.  \n\n    For example, the term [succ true] (i.e., [tsucc ttrue] in the\n    formal syntax) cannot take a step, but the almost as obviously\n    nonsensical term\n       succ (if true then true else true) \n    can take a step (once, before becoming stuck). *)\n\n(* ###################################################################### *)\n(** ** Normal Forms and Values *)\n\n(** The first interesting thing about the [step] relation in this\n    language is that the strong progress theorem from the Smallstep\n    chapter fails!  That is, there are terms that are normal\n    forms (they can't take a step) but not values (because we have not\n    included them in our definition of possible \"results of\n    evaluation\").  Such terms are _stuck_. *)\n\nNotation step_normal_form := (normal_form step).\n\nDefinition stuck (t:tm) : Prop :=\n  step_normal_form t /\\ ~ value t.\n\nHint Unfold stuck.\n\n(** **** Exercise: 2 stars (some_term_is_stuck) *)\nExample some_term_is_stuck :\n  exists t, stuck t.\nProof.\n  (* SOLUTION: *)\n  exists (tsucc tfalse).\n  unfold stuck. split.\n    Case \"normal form\".\n      unfold normal_form. intros contra. inversion contra as [t' Hstp].\n      solve by inversion 2.\n    Case \"not a value\".\n      intros H. solve by inversion 3.  Qed.\n(** [] *)\n\n(** However, although values and normal forms are not the same in this\n    language, the former set is included in the latter.  This is\n    important because it shows we did not accidentally define things\n    so that some value could still take a step. *)\n\n(** **** Exercise: 3 stars, advanced (value_is_nf) *)\n(** Hint: You will reach a point in this proof where you need to\n    use an induction to reason about a term that is known to be a\n    numeric value.  This induction can be performed either over the\n    term itself or over the evidence that it is a numeric value.  The\n    proof goes through in either case, but you will find that one way\n    is quite a bit shorter than the other.  For the sake of the\n    exercise, try to complete the proof both ways. *)\n\nLemma value_is_nf : forall t,\n  value t -> step_normal_form t.\nProof.\n  (* SOLUTION: *)\n  intros t H.\n  (* Here is the easier way: *)\n  unfold normal_form.\n  inversion H; clear H.\n  Case \"boolean value\". inversion H0.\n    SCase \"ttrue\". intros Contra. inversion Contra as [t' P]. \n      inversion P.\n    SCase \"tfalse\". intros Contra. inversion Contra as [t' P]. \n      inversion P.\n  Case \"numeric value\".\n    induction H0.\n    SCase \"nv_zero\". intros Contra. inversion Contra as [t' P]. \n      inversion P.\n    SCase \"nv_succ\". intros Contra. inversion Contra as [t' P]. \n      inversion P. subst. apply IHnvalue. \n      exists t1'. auto.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (step_deterministic) *)\n(** Using [value_is_nf], we can show that the [step] relation is\n    also deterministic... *)\n\nTheorem step_deterministic:\n  deterministic step.\nProof with eauto.\n  (* SOLUTION: *)\n  unfold deterministic. intros x y1 y2 Hy1 Hy2.\n  generalize dependent y2.\n  step_cases (induction Hy1) Case; \n        intros y2 Hy2; inversion Hy2; subst; auto; \n        try (solve by inversion).\n    Case \"ST_If\".\n      SCase \"Hy2 by ST_If\". f_equal... \n    Case \"ST_Succ\". \n      SCase \"Hy2 by ST_Succ\". f_equal... \n    Case \"ST_PredSucc\".\n      SCase \"Hy2 by ST_Pred\".\n        inversion H1; subst. \n        apply ex_falso_quodlibet.\n        apply value_is_nf with t1...\n    Case \"ST_Pred\".\n      SCase \"Hy2 by ST_PredSucc\". \n        inversion Hy1; subst.\n        apply ex_falso_quodlibet. \n        apply value_is_nf with y2... \n      SCase \"Hy2 by ST_Pred\". \n        f_equal... \n    Case \"ST_IszeroSucc\".\n      SCase \"Hy2 by ST_Iszero\". \n        inversion H1; subst.\n        apply ex_falso_quodlibet.\n        apply value_is_nf with t1...\n    Case \"ST_Iszero\".\n      SCase \"Hy2 by ST_IszeroSucc\". \n        inversion Hy1; subst.\n        apply ex_falso_quodlibet. \n        apply value_is_nf with t0...\n      SCase \"Hy2 by ST_Iszero\".\n        f_equal... Qed. \n(** [] *)\n\n\n\n(* ###################################################################### *)\n(** ** Typing *)\n\n(** The next critical observation about this language is that,\n    although there are stuck terms, they are all \"nonsensical\", mixing\n    booleans and numbers in a way that we don't even _want_ to have a\n    meaning.  We can easily exclude such ill-typed terms by defining a\n    _typing relation_ that relates terms to the types (either numeric\n    or boolean) of their final results.  *)\n\nInductive ty : Type := \n  | TBool : ty\n  | TNat : ty.\n\n(** In informal notation, the typing relation is often written\n    [|- t \\in T], pronounced \"[t] has type [T].\"  The [|-] symbol is\n    called a \"turnstile\".  (Below, we're going to see richer typing\n    relations where an additional \"context\" argument is written to the\n    left of the turnstile.  Here, the context is always empty.) *)\n(** \n                           ----------------                            (T_True)\n                           |- true \\in Bool\n\n                          -----------------                           (T_False)\n                          |- false \\in Bool\n\n             |- t1 \\in Bool    |- t2 \\in T    |- t3 \\in T\n             --------------------------------------------                (T_If)\n                    |- if t1 then t2 else t3 \\in T\n\n                             ------------                              (T_Zero)\n                             |- 0 \\in Nat\n                              \n                            |- t1 \\in Nat\n                          ------------------                           (T_Succ)\n                          |- succ t1 \\in Nat\n\n                            |- t1 \\in Nat\n                          ------------------                           (T_Pred)\n                          |- pred t1 \\in Nat\n\n                            |- t1 \\in Nat\n                        ---------------------                        (T_IsZero)\n                        |- iszero t1 \\in Bool\n*)\n\nReserved Notation \"'|-' t '\\in' T\" (at level 40).\n\nInductive has_type : tm -> ty -> Prop :=\n  | T_True : \n       |- ttrue \\in TBool\n  | T_False : \n       |- tfalse \\in TBool\n  | T_If : forall t1 t2 t3 T,\n       |- t1 \\in TBool ->\n       |- t2 \\in T ->\n       |- t3 \\in T ->\n       |- tif t1 t2 t3 \\in T\n  | T_Zero : \n       |- tzero \\in TNat\n  | T_Succ : forall t1,\n       |- t1 \\in TNat ->\n       |- tsucc t1 \\in TNat\n  | T_Pred : forall t1,\n       |- t1 \\in TNat ->\n       |- tpred t1 \\in TNat\n  | T_Iszero : forall t1,\n       |- t1 \\in TNat ->\n       |- tiszero t1 \\in TBool\n\nwhere \"'|-' t '\\in' T\" := (has_type t T).\n\nTactic Notation \"has_type_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"T_True\" | Case_aux c \"T_False\" | Case_aux c \"T_If\"\n  | Case_aux c \"T_Zero\" | Case_aux c \"T_Succ\" | Case_aux c \"T_Pred\"\n  | Case_aux c \"T_Iszero\" ].\n\nHint Constructors has_type.\n\n(* ###################################################################### *)\n(** *** Examples *)\n\n(** It's important to realize that the typing relation is a\n    _conservative_ (or _static_) approximation: it does not calculate\n    the type of the normal form of a term. *)\n\nExample has_type_1 : \n  |- tif tfalse tzero (tsucc tzero) \\in TNat.\nProof. \n  apply T_If. \n    apply T_False.\n    apply T_Zero.\n    apply T_Succ.\n      apply T_Zero.  \nQed.\n\n(** (Since we've included all the constructors of the typing relation\n    in the hint database, the [auto] tactic can actually find this\n    proof automatically.) *)\n\nExample has_type_not : \n  ~ (|- tif tfalse tzero ttrue \\in TBool).\nProof.\n  intros Contra. solve by inversion 2.  Qed.\n\n(** **** Exercise: 1 star, optional (succ_hastype_nat__hastype_nat) *)\nExample succ_hastype_nat__hastype_nat : forall t,\n  |- tsucc t \\in TNat ->\n  |- t \\in TNat.  \nProof.\n  (* SOLUTION: *)\n  intros t H. inversion H. subst. assumption.  Qed.\n(** [] *)\n\n(* ###################################################################### *)\n(** ** Progress *)\n\n(** The typing relation enjoys two critical properties.  The first is\n    that well-typed normal forms are values (i.e., not stuck). *)\n\nTheorem progress : forall t T,\n  |- t \\in T ->\n  value t \\/ exists t', t ==> t'.\n\n(** **** Exercise: 3 stars (finish_progress) *)\n(** Complete the formal proof of the [progress] property.  (Make sure\n    you understand the informal proof fragment in the following\n    exercise before starting -- this will save you a lot of time.) *)\n\nProof with auto.\n  intros t T HT.\n  has_type_cases (induction HT) Case...\n  (* The cases that were obviously values, like T_True and\n     T_False, were eliminated immediately by auto *)\n  Case \"T_If\".\n    right. inversion IHHT1; clear IHHT1.\n    SCase \"t1 is a value\". inversion H; clear H.\n      SSCase \"t1 is a bvalue\". inversion H0; clear H0.\n        SSSCase \"t1 is ttrue\".\n          exists t2...\n        SSSCase \"t1 is tfalse\". \n          exists t3...\n      SSCase \"t1 is an nvalue\".\n        solve by inversion 2.  (* on H and HT1 *)\n    SCase \"t1 can take a step\".\n      inversion H as [t1' H1].\n      exists (tif t1' t2 t3)...\n  (* SOLUTION: *)\n  Case \"T_Succ\". \n    inversion IHHT; clear IHHT.\n    SCase \"t1 is a value\". inversion H...\n      SSCase \"t1 is a bvalue\". solve by inversion 2.\n    SCase \"t1 can take a step\".\n      right. inversion H as [t1' H1]. \n      exists (tsucc t1')...\n  Case \"T_Pred\". \n    inversion IHHT; clear IHHT.\n    SCase \"t1 is a value\". inversion H; clear H.\n      SSCase \"t1 is a bvalue\". solve by inversion 2.\n      SSCase \"t1 is an nvalue\". right. \n        inversion H0; subst.\n        SSSCase \"t1 is zero\".\n          exists (tzero)... \n        SSSCase \"t1 is nonzero\".\n          exists t...\n    SCase \"t1 can take a step\".\n      right. inversion H as [t1' H1].\n      exists (tpred t1')...\n  Case \"T_Iszero\". \n    inversion IHHT; clear IHHT.\n    SCase \"t1 is a value\". inversion H; clear H.\n      SSCase \"t1 is a bvalue\". solve by inversion 2.\n      SSCase \"t1 is an nvalue\". right.\n        inversion H0; subst.\n        SSSCase \"t1 is zero\".\n          exists ttrue...\n        SSSCase \"t1 is nonzero\".\n          exists tfalse...\n    SCase \"t1 can take a step\". \n      right. inversion H as [t1' H1]. \n      exists (tiszero t1')...  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (finish_progress_informal) *)\n(** Complete the corresponding informal proof: *)\n\n(** _Theorem_: If [|- t \\in T], then either [t] is a value or else \n    [t ==> t'] for some [t']. *)\n\n(** _Proof_: By induction on a derivation of [|- t \\in T].\n\n      - If the last rule in the derivation is [T_If], then [t = if t1\n        then t2 else t3], with [|- t1 \\in Bool], [|- t2 \\in T] and [|- t3\n        \\in T].  By the IH, either [t1] is a value or else [t1] can step\n        to some [t1'].  \n\n            - If [t1] is a value, then it is either an [nvalue] or a\n              [bvalue].  But it cannot be an [nvalue], because we know\n              [|- t1 \\in Bool] and there are no rules assigning type\n              [Bool] to any term that could be an [nvalue].  So [t1]\n              is a [bvalue] -- i.e., it is either [true] or [false].\n              If [t1 = true], then [t] steps to [t2] by [ST_IfTrue],\n              while if [t1 = false], then [t] steps to [t3] by\n              [ST_IfFalse].  Either way, [t] can step, which is what\n              we wanted to show.\n\n            - If [t1] itself can take a step, then, by [ST_If], so can\n              [t].\n\n    (* SOLUTION: *)\n\n      - If the last rule in the derivation is [T_True], then [t =\n        true], which is a boolean value and hence a value.  The cases\n        for [T_False] and [T_Zero] are similar.\n\n      - If the last rule in the derivation is [T_Succ], then [t = succ\n        t1], with [|- t1 \\in Nat].  By the IH, either [t1] is a value or\n        else [t1] can step to some [t1'].\n\n            - If [t1] is a value, then it is either an [nvalue] or a\n              [bvalue].  But it cannot be an [bvalue], because we know\n              [|- t1 \\in Nat] and there are no rules assigning type\n              [Bool] to any term that could be a [bvalue].  So [t1] is\n              a [nvalue], and hence [t] is also an [nvalue] (and hence\n              a value) by [nv_succ].\n\n            - If [t1] can take a step, then by [ST_Succ], so can [t].\n\n      - If the last rule in the derivation is [T_Pred], then [t =\n        pred t1], with [|- t1 \\in Nat].   By the IH, either [t1] is a\n        value or else [t1] can step to some [t1'].\n\n            - If [t1] is a value, then (by the same argument as in the\n              previous case) it must be an [nvalue].  By inversion on\n              the [nvalue] judgement, there are two cases:\n \n                - If [t1 = zero], then [t] can take a step by\n                  [ST_PredZero].\n\n                - Otherwise, [t1 = succ t1'], with [t1'] an [nvalue].\n                  Hence [t] can again take a step, this time by\n                  [ST_PredSucc].\n\n            - Finally, if [t1] can take a step, then by [ST_Pred], so\n              can [t].\n\n      - If the last rule in the derivation is [T_IsZero], then [t =\n        iszero t1], with [|- t1 \\in Nat].  By the IH, either [t1] is a\n        value or else [t1] steps to some [t1'].\n\n            - If [t1] is a value, it must be an [nvalue], and there\n              are two cases to consider:\n\n                - If [t1 = zero], then [t] can take a step by\n                  [ST_IsZeroZero].\n\n                - Otherwise, [t1 = succ t1'] where [t1'] is an\n                  [nvalue].  Hence [t] can take a step by\n                  [ST_IsZeroSucc].\n\n            - If [t1] can take a step, then so can [t], by [ST_IsZero].\n      \n    []\n*)\n\n(** This is more interesting than the strong progress theorem that we\n    saw in the Smallstep chapter, where _all_ normal forms were\n    values.  Here, a term can be stuck, but only if it is ill\n    typed. *)\n\n(** **** Exercise: 1 star (step_review) *)\n(** Quick review.  Answer _true_ or _false_.  In this language...\n      - Every well-typed normal form is a value.\n\n            TRUE: This is the content of the progress theorem.\n      - Every value is a normal form.\n\n            TRUE: This can proved by induction on values.\n      - The single-step evaluation relation is\n        a partial function (i.e., it is deterministic).\n\n            TRUE: This is the determinism theorem.\n      - The single-step evaluation relation is a _total_ function.\n\n            FALSE: normal forms do not evaluate to anything + can get stuck.\n*)\n(** [] *)\n\n(* ###################################################################### *)\n(** ** Type Preservation *)\n\n(** The second critical property of typing is that, when a well-typed\n    term takes a step, the result is also a well-typed term.\n\n    This theorem is often called the _subject reduction_ property,\n    because it tells us what happens when the \"subject\" of the typing\n    relation is reduced.  This terminology comes from thinking of\n    typing statements as sentences, where the term is the subject and\n    the type is the predicate. *)\n\nTheorem preservation : forall t t' T,\n  |- t \\in T ->\n  t ==> t' ->\n  |- t' \\in T.\n\n(** **** Exercise: 2 stars (finish_preservation) *)\n(** Complete the formal proof of the [preservation] property.  (Again,\n    make sure you understand the informal proof fragment in the\n    following exercise first.) *)\n\nProof with auto.\n  intros t t' T HT HE.\n  generalize dependent t'.\n  has_type_cases (induction HT) Case; \n         (* every case needs to introduce a couple of things *)\n         intros t' HE; \n         (* and we can deal with several impossible\n            cases all at once *)\n         try (solve by inversion).\n    Case \"T_If\". inversion HE; subst.\n      SCase \"ST_IFTrue\". assumption.\n      SCase \"ST_IfFalse\". assumption.\n      SCase \"ST_If\". apply T_If; try assumption.\n        apply IHHT1; assumption.\n    (* SOLUTION: *)\n    Case \"T_Succ\". inversion HE; subst...\n    Case \"T_Pred\". inversion HE; subst...\n      SCase \"ST_PredSucc\". inversion HT...\n    Case \"T_Iszero\". inversion HE; subst...  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (finish_preservation_informal) *)\n(** Complete the following proof: *)\n\n(** _Theorem_: If [|- t \\in T] and [t ==> t'], then [|- t' \\in T]. *)\n\n(** _Proof_: By induction on a derivation of [|- t \\in T].\n\n      - If the last rule in the derivation is [T_If], then [t = if t1\n        then t2 else t3], with [|- t1 \\in Bool], [|- t2 \\in T] and [|- t3\n        \\in T].  \n\n        Inspecting the rules for the small-step reduction relation and\n        remembering that [t] has the form [if ...], we see that the\n        only ones that could have been used to prove [t ==> t'] are\n        [ST_IfTrue], [ST_IfFalse], or [ST_If].\n\n           - If the last rule was [ST_IfTrue], then [t' = t2].  But we\n             know that [|- t2 \\in T], so we are done.\n\n           - If the last rule was [ST_IfFalse], then [t' = t3].  But we\n             know that [|- t3 \\in T], so we are done.\n\n           - If the last rule was [ST_If], then [t' = if t1' then t2\n             else t3], where [t1 ==> t1'].  We know [|- t1 \\in Bool] so,\n             by the IH, [|- t1' \\in Bool].  The [T_If] rule then gives us\n             [|- if t1' then t2 else t3 \\in T], as required.\n\n    (* SOLUTION: *)\n\n      - If the last rule in the derivation were [T_True], then [t =\n        true].  However, [true] does not step to anything, so this\n        case cannot actually occur.\n\n      - Similarly, neither [T_False] nor [T_Zero] could not be the\n        final rule in the derivation.\n\n      - If the last rule in the derivation is [T_Succ], then [t = succ\n        t1] with [|- t1 \\in Nat] and [T = Nat]. The only rule which\n        could have been used to show that [t] steps is [ST_Succ], in\n        which case [t1] steps to some [t1'].  So, by the IH, [|- t1' \\in\n        Nat], and hence [t' = succ t1'] also has type [Nat] by\n        [T_Succ].\n\n      - If the last rule in the derivation is [T_Pred], then [t = pred\n        t1] with [|- t1 \\in Nat].  There are only three rules which could\n        have been the last rule in the derivation of [pred t1 ==> t'].\n\n          - If the last rule was [ST_PredZero], then [t' = zero] which\n            has type [Nat].\n\n          - If the last rule was [ST_PredSucc], then [t1 = succ t'];\n            by inversion on the fact that [|- t1 \\in Nat] it follows\n            that [|- t' \\in Nat] as well.\n\n          - If the last rule was [ST_Pred], then [t1] steps to some\n            [t1']; by the IH [|- t1' \\in Nat], and so [pred t1'] has\n            type [Nat] as well by [T_Pred].\n  \n      - If the last rule in the derivation is [T_IsZero], then [t =\n        iszero t1] with [|- t1 \\in Nat] and [T = Bool].  There are only\n        three rules which could have been the last rule in the\n        derivation of [iszero t1 ==> t'].\n \n          - If the last rule was [ST_IsZeroZero], then [t' = true]\n            which has type [Bool].\n\n          - If the last rule was [ST_IsZeroSucc], then [t' = false]\n            which has type [Bool].\n\n          - If the last rule was [ST_IsZero], then [t1] steps to some\n            [t1'].  By the IH, [|- t1' \\in Nat] as well, and hence [t' =\n            iszero t1'] has type [Bool] by [T_IsZero].\n\n    []\n*)\n\n(** **** Exercise: 3 stars (preservation_alternate_proof) *)\n(** Now prove the same property again by induction on the\n    _evaluation_ derivation instead of on the typing derivation.\n    Begin by carefully reading and thinking about the first few\n    lines of the above proof to make sure you understand what\n    each one is doing.  The set-up for this proof is similar, but\n    not exactly the same. *)\n\nTheorem preservation' : forall t t' T,\n  |- t \\in T ->\n  t ==> t' ->\n  |- t' \\in T.\nProof with eauto.\n  (* SOLUTION: *)\n  intros t t' T HT HE.\n  generalize dependent T.\n  step_cases (induction HE) Case;\n         (* in each case, invert the given typing derivation *)\n         intros T HT; inversion HT; subst; \n         (* deal with several easy or contradictory cases \n            all at once *)\n         try solve [assumption; solve by inversion]...\n    Case \"ST_PredSucc\". \n      inversion HT. subst. inversion H2. subst...  Qed.\n(** [] *)\n\n(* ###################################################################### *)\n(** ** Type Soundness *)\n\n(** Putting progress and preservation together, we can see that a\n    well-typed term can _never_ reach a stuck state.  *)\n\nDefinition multistep := (multi step).\nNotation \"t1 '==>*' t2\" := (multistep t1 t2) (at level 40).\n\nCorollary soundness : forall t t' T,\n  |- t \\in T -> \n  t ==>* t' ->\n  ~(stuck t').\nProof. \n  intros t t' T HT P. induction P; intros [R S].\n  destruct (progress x T HT); auto.   \n  apply IHP.  apply (preservation x y T HT H).\n  unfold stuck. split; auto.   Qed.\n\n(* ###################################################################### *)\n(** ** Additional Exercises *)\n\n(** **** Exercise: 2 stars (subject_expansion) *)\n(** Having seen the subject reduction property, it is reasonable to\n    wonder whether the opposity property -- subject _expansion_ --\n    also holds.  That is, is it always the case that, if [t ==> t']\n    and [|- t' \\in T], then [|- t \\in T]?  If so, prove it.  If\n    not, give a counter-example.  (You do not need to prove your\n    counter-example in Coq, but feel free to do so if you like.)\n\n    (* SOLUTION: *) \n       Subject expansion does not hold in this language (or most\n       interesting languages).  For example, [tif tfalse\n       ttrue tzero] is ill typed, but it evaluates to the\n       well-typed term [tzero].  \n    []\n*)\n\n\n\n\n(** **** Exercise: 2 stars (variation1) *)\n(** Suppose, that we add this new rule to the typing relation: \n      | T_SuccBool : forall t,\n           |- t \\in TBool ->\n           |- tsucc t \\in TBool\n   Which of the following properties remain true in the presence of\n   this rule?  For each one, write either \"remains true\" or\n   else \"becomes false.\" If a property becomes false, give a\n   counterexample.\n      - Determinism of [step]\n\n            Remains true\n      - Progress\n\n            Becomes false:  [tsucc ttrue] is well typed, but stuck.\n      - Preservation\n\n            Remains true            \n[]\n*)\n\n(** **** Exercise: 2 stars (variation2) *)\n(** Suppose, instead, that we add this new rule to the [step] relation: \n      | ST_Funny1 : forall t2 t3,\n           (tif ttrue t2 t3) ==> t3\n   Which of the above properties become false in the presence of\n   this rule?  For each one that does, give a counter-example.\n\n       - Determinism becomes false: [tif ttrue\n         tzero (tsucc tzero)] can now evaluate in one step\n         to either [tzero] or [tsucc tzero].\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (variation3) *)\n(** Suppose instead that we add this rule:\n      | ST_Funny2 : forall t1 t2 t2' t3,\n           t2 ==> t2' ->\n           (tif t1 t2 t3) ==> (tif t1 t2' t3)\n   Which of the above properties become false in the presence of\n   this rule?  For each one that does, give a counter-example.\n\n       - Determinism again becomes false: [tif\n         tfalse (tpred tzero) (tsucc tzero)] can now\n         evaluate in one step to either [tsucc tzero] or\n         [tif tfalse tzero (tsucc tzero)].  (There are\n         several other correct counter-examples.)\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (variation4) *)\n(** Suppose instead that we add this rule:\n      | ST_Funny3 : \n          (tpred tfalse) ==> (tpred (tpred tfalse))\n   Which of the above properties become false in the presence of\n   this rule?  For each one that does, give a counter-example.\n\n   All remain true\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (variation5) *)\n(** Suppose instead that we add this rule:\n   \n      | T_Funny4 : \n            |- tzero \\in TBool\n   ]]\n   Which of the above properties become false in the presence of\n   this rule?  For each one that does, give a counter-example.\n\n       - Progress becomes false: [tif tzero ttrue ttrue]\n         has type [TBool], is a normal form, and is not a\n         value.\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (variation6) *)\n(** Suppose instead that we add this rule:\n   \n      | T_Funny5 : \n            |- tpred tzero \\in TBool\n   ]]\n   Which of the above properties become false in the presence of\n   this rule?  For each one that does, give a counter-example.\n\n       - Preservation becomes false: [tpred tzero] has type\n         [TBool] and evaluates in one step to [tzero], which\n         does not have type [TBool].\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (more_variations) *)\n(** Make up some exercises of your own along the same lines as\n    the ones above.  Try to find ways of selectively breaking\n    properties -- i.e., ways of changing the definitions that\n    break just one of the properties and leave the others alone.\n    [] \n*)\n\n(** **** Exercise: 1 star (remove_predzero) *)\n(** The evaluation rule [E_PredZero] is a bit counter-intuitive: we\n    might feel that it makes more sense for the predecessor of zero to\n    be undefined, rather than being defined to be zero.  Can we\n    achieve this simply by removing the rule from the definition of\n    [step]?  Would doing so create any problems elsewhere? \n\n(* SOLUTION: *) \n    Yes, but doing this would break the progress property.\n    A better way would be to raise an exception in this case, but this\n    requires that we add exceptions to the language we're formalizing!\n[] *)\n\n(** **** Exercise: 4 stars, advanced (prog_pres_bigstep) *)\n(** Suppose our evaluation relation is defined in the big-step style.\n    What are the appropriate analogs of the progress and preservation\n    properties?\n\n(* SOLUTION: *) The type preservation property for the big-step\n    semantics is similar to the one we gave for the small-step\n    semantics: if a well-typed term evaluates to some final value,\n    then this value has the same type as the original term.  The proof\n    is similar to the one we gave.\n\n    The situation with the progress property is more interesting.  A\n    direct analog (if a term is well typed then it evaluates to some\n    other term) makes a much stronger claim than the progress theorem\n    we have given: it says that every well-typed term can be evaluated\n    to some final value---that is, that evaluation always terminates\n    on well-typed terms.  For arithmetic expressions, this happens to\n    be the case, but for more interesting languages (languages\n    involving general recursion, for example) it will often not be\n    true.  For such languages, we simply have no progress property in\n    the big-step style: in effect, there is no way to tell the\n    difference between reaching an error state and failing to\n    terminate.  This is one reason that language theorists generally\n    prefer the small-step style.\n[]\n*)\n\n(* $Date$ *)\n", "meta": {"author": "ysyshtc", "repo": "cis500", "sha": "c538fd552b09cbcf4a972fc3474d48d0c246e30d", "save_path": "github-repos/coq/ysyshtc-cis500", "path": "github-repos/coq/ysyshtc-cis500/cis500-c538fd552b09cbcf4a972fc3474d48d0c246e30d/Types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6785963580903018}}
{"text": "(************************************************************************)\n(*                                                                      *)\n(* Micromega: A reflexive tactic using the Positivstellensatz           *)\n(*                                                                      *)\n(*  Frédéric Besson (Irisa/Inria) 2006-2008                             *)\n(*                                                                      *)\n(************************************************************************)\n\nRequire Import Psatz.\nRequire Import QArith.\n\nLemma plus_minus : forall x y, \n  0 == x + y -> 0 ==  x -y -> 0 == x /\\ 0 == y.\nProof.\n  intros.\n  psatzl Q.\nQed.\n\n\n\n\n(* Other (simple) examples *)\nOpen Scope Q_scope.\n\nLemma binomial : forall x y:Q, ((x+y)^2 == x^2 + (2 # 1) *x*y + y^2).\nProof.\n  intros.\n  psatzl Q.\nQed.\n\n\nLemma hol_light19 : forall m n, (2 # 1) * m + n == (n + m) + m.\nProof.\n  intros ; psatzl Q.\nQed.\nOpen Scope Z_scope.\nOpen Scope Q_scope.\n\nLemma vcgen_25 : forall   \n  (n : Q)\n  (m : Q)\n  (jt : Q)\n  (j : Q)\n  (it : Q)\n  (i : Q)\n  (H0 : 1 * it + (-2 # 1) * i + (-1 # 1) == 0)\n  (H :  1 * jt + (-2 # 1) * j + (-1 # 1) == 0)\n  (H1 : 1 * n + (-10 # 1) = 0)\n  (H2 : 0 <= (-4028 # 1)  * i + (6222 # 1) * j + (705 # 1)  * m + (-16674 # 1))\n  (H3 : 0 <= (-418 # 1) * i + (651 # 1) * j + (94 # 1) * m + (-1866 # 1))\n  (H4 : 0 <= (-209 # 1) * i + (302 # 1) * j + (47 # 1) * m + (-839 # 1))\n  (H5 : 0 <= (-1 # 1) * i + 1 * j + (-1 # 1))\n  (H6 : 0 <= (-1 # 1) * j + 1 * m + (0 # 1))\n  (H7 : 0 <= (1 # 1) * j + (5 # 1) * m + (-27 # 1))\n  (H8 : 0 <= (2 # 1) * j + (-1 # 1) * m + (2 # 1))\n  (H9 : 0 <= (7 # 1) * j + (10 # 1) * m + (-74 # 1))\n  (H10 : 0 <= (18 # 1) * j + (-139 # 1) * m + (1188 # 1))\n  (H11 : 0 <= 1  * i + (0 # 1))\n  (H13 : 0 <= (121 # 1)  * i + (810 # 1)  * j + (-7465 # 1) * m + (64350 # 1)),\n  (( 1# 1) == (-2 # 1) * i + it).\nProof.\n  intros.\n  psatzl Q.\nQed.\n\nGoal forall x, -x^2 >= 0 -> x - 1 >= 0 -> False.\nProof.\n  intros.\n  psatz Q 2.\nQed.\n\nLemma motzkin' : forall x y, (x^2+y^2+1)*(x^2*y^4 + x^4*y^2 + 1 - (3 # 1) *x^2*y^2) >= 0.\nProof.\n  intros ; psatz Q.\nQed.\n\n\n\n", "meta": {"author": "coq-contribs", "repo": "micromega", "sha": "a70bf64b99462a77cd9181e3f2836bc1fed04593", "save_path": "github-repos/coq/coq-contribs-micromega", "path": "github-repos/coq/coq-contribs-micromega/micromega-a70bf64b99462a77cd9181e3f2836bc1fed04593/test/qexample.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6785963561249192}}
{"text": "Axiom todo : forall {A}, A.\n\n(* 2.1 Equality *)\n\nDefinition sym (A:Type) (x y:A) (e:x=y) : y = x := \n\teq_ind x (fun y0 => y0=x) eq_refl y e.\n\n\t\t\nDefinition trans (A:Type) (x y z:A) (e1:x=y) (e2:y=z) : x=z := \t\t\n\teq_ind y (fun z0 => x=z0) e1 z e2 .\n\nDefinition congr (A B:Type) (f:A->B) (x y:A) (e:x=y) : f x = f y := \n\teq_ind x (fun y0 => f x = f y0) eq_refl y e.\n\nPrint eq_rect.\n\n\n\nLemma dcongr (A:Type) (B:A->Type) (f:forall x:A, B x) (x y:A) (e:x=y) :\n  eq_rect x B (f x) y e = f y.\nProof.\ncase e.\nunfold eq_rect.\nreflexivity.\nQed.\n\n(* 3 Universes *)\n\n(* 4.1 *)\n\nCheck (forall (P:Prop),P).\nCheck (forall (P:Type),P).\nCheck (forall (PP:Prop->Prop), exists (P:Prop), PP P).\nFail Check (forall (PP:Type->Type), exists (P:Type), PP P).\n\nDefinition conj (A B:Prop) : Prop :=\n  forall Q:Prop, (A->B->Q) -> Q.\n\nDefinition conj_i (A B: Prop) (a:A) (b:B) : conj A B := \n\tfun Q (f:A->B->Q) => f a b.\n\nDefinition conj_e1 (A B:Prop) (p: conj A B) : A := \n\tp A (fun A B => A).\n\nDefinition conj_e2 (A B:Prop) (p: conj A B) : B := \n\tp B (fun A B => B).\n\nDefinition disj (A B:Prop) : Prop := \n\tforall Q:Prop, (A->Q) -> (B->Q) -> Q.\n\nDefinition disj_i1 (A B:Prop) (a:A) : disj A B := \n\tfun Q f f' => f a.\n\nDefinition disj_i2 (A B:Prop) (b:B) : disj A B := \n\tfun Q f f' => f' b.\n\t\nDefinition disj_e (A B:Prop) (p: disj A B) (Q:Prop) (f:A->Q) (f':B->Q) : Q := \n\tp Q f f'.\n\nDefinition ex (A:Type) (P: A -> Prop) : Type := \n\tforall Q:Prop, (forall x:A, P x -> Q) -> Q.\n\nDefinition ex_i (A :Type) (P: A -> Prop) (a:A) (b:P a) : ex A P  :=\n\tfun Q (f:forall x:A, P x -> Q) => f a b.\n\nDefinition ex_e (A:Type) (P:A->Prop) (p: ex A P) (Q:Prop) (f:forall (a:A) (b:P a), Q) : Q := \n\t p Q f.\n\nDefinition equ (A:Type) (a b:A) : Type := \n\tforall (P:A->Prop), P a -> P b.\n\nDefinition equ_refl (A:Type) (x:A) : equ A x x  :=\n\tfun P h => h\n\t.\n\nDefinition equ_ind : todo := todo.\n\nDefinition equ_sym : todo := todo.\nDefinition equ_trans : todo := todo.\n\nDefinition equ_congr : todo := todo.\n\n(* 4.2 *)\n\nDefinition bool : Prop :=\n  forall Q:Prop, Q->Q->Q.\n\nDefinition true : bool := todo.\nDefinition false : bool := todo.\n\nDefinition ifthenelse : todo := todo.\n\nDefinition band : todo := todo.\nLemma band_ff : todo.\nProof. apply todo. Qed.\nLemma band_ft : todo.\nProof. apply todo. Qed.\nLemma band_tf : todo.\nProof. apply todo. Qed.\nLemma band_tt : todo.\nProof. apply todo. Qed.\n\n(* 4.3 *)\n\nDefinition nat : Prop :=\n  forall Q:Prop, Q -> (Q->Q) -> Q.\n\nDefinition zero : nat := todo.\n\nDefinition succ (n:nat) : nat := todo.\n\n(* iterate n times successor on m *)\nDefinition plus (n m:nat) : nat := todo.\n\nDefinition mult (n m:nat) : nat := todo.\n\nEval compute in (mult (succ (succ zero)) (succ (succ (succ zero)))).\n\n(* 5. *)\n\nDefinition pnat : Type := todo.\n\nDefinition pzero : pnat := todo.\n\nDefinition psucc (n:pnat) : pnat := todo.", "meta": {"author": "sebastienPatte", "repo": "Coq", "sha": "1c031f13db8d7101ca356c23b36d560c0a194de1", "save_path": "github-repos/coq/sebastienPatte-Coq", "path": "github-repos/coq/sebastienPatte-Coq/Coq-1c031f13db8d7101ca356c23b36d560c0a194de1/PA/tp2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357632379241, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6785963554012666}}
{"text": "Inductive formula : Set :=\n| atom : nat -> formula\n| false_f : formula\n| or_f : formula -> formula -> formula\n| and_f : formula -> formula -> formula\n| implies_f : formula -> formula -> formula.\n\nInfix \"/\\f\" := and_f (at level 60, right associativity).\nInfix \"\\/f\" := or_f (at level 65, right associativity).\nInfix \"->f\" := implies_f (at level 70, right associativity).\n\n(* Some variable constants for convenience *)\nNotation X := (atom 0).\nNotation Y := (atom 1).\nNotation Z := (atom 2).\n\nInductive MID := bot | mid | top.\n\nDefinition sel {A} (m : MID) (x y z : A): A :=\n  match m with\n  | bot => x\n  | mid => y\n  | top => z\n  end.\n\nDefinition meet (m n : MID): MID :=\n  sel m (sel n bot bot bot)\n        (sel n bot mid mid)\n        (sel n bot mid top).\n\nDefinition join (m n : MID): MID :=\n  sel m (sel n bot mid top)\n        (sel n mid mid top)\n        (sel n top top top).\n\nDefinition impl (m n : MID): MID :=\n  sel m (sel n top top top)\n        (sel n bot top top)\n        (sel n bot mid top).\n\nDefinition map := nat -> MID.\n\nFixpoint valuation (c : formula) (m : map) : MID :=\n  match c with\n  | atom v => m v\n  | false_f => bot\n  | a \\/f b => join (valuation a m) (valuation b m)\n  | a /\\f b => meet (valuation a m) (valuation b m)\n  | a ->f b => impl (valuation a m) (valuation b m)\n  end.\n\nDefinition MID_valid (c : formula) := forall m, valuation c m = top.\n\nDefinition substitution := nat -> formula.\n\nFixpoint subst (c : formula) (s : substitution) : formula :=\n  match c with\n  | atom v => s v\n  | false_f => false_f\n  | a \\/f b => subst a s \\/f subst b s\n  | a /\\f b => subst a s /\\f subst b s\n  | a ->f b => subst a s ->f subst b s\n  end.\n\nInductive hilbert : formula -> Prop :=\n| app_h : forall a b, hilbert (a ->f b) -> hilbert a -> hilbert b\n| subst_h : forall a s, hilbert a -> hilbert (subst a s)\n| k_h : hilbert (X ->f Y ->f X)\n| s_h : hilbert ((X ->f Y ->f Z) ->f (X ->f Y) ->f (X ->f Z))\n| fst_h : hilbert (X /\\f Y ->f X)\n| snd_h : hilbert (X /\\f Y ->f Y)\n| pair_h : hilbert (X ->f Y ->f X /\\f Y)\n| inl_h : hilbert (X ->f X \\/f Y)\n| inr_h : hilbert (Y ->f X \\/f Y)\n| either_h : hilbert ((X ->f Z) ->f (Y ->f Z) ->f (X \\/f Y ->f Z))\n| absurd_h : hilbert (false_f ->f X).\n\nDefinition LEM := X \\/f (X ->f false_f).\n\nLemma hilbert_MID_sound : forall c, hilbert c -> MID_valid c.\nProof with (try easy).\n  fix HH 1.\n  intros.\n  unfold MID_valid.\n  induction H; intros.\n  destruct a, b...\n  all: simpl in *.\n  all: multimatch goal with\n  | H: forall m : map, _, H2: forall m : map, _ |- _ => pose proof (H m); pose proof (H2 m)\n  | H: forall m : map, _ |- _ => pose proof (H m)\n  | _ => idtac\n  end; try easy.\n  destruct (m n), (m n0)...\n  destruct (m n)...\n  all: multimatch goal with\n  | |- join ?U ?I = top => destruct (join U I)\n  | |- meet ?U ?I = top => destruct (meet U I)\n  | _ => idtac\n  end; try easy.\n  all: multimatch goal with\n  | [ u : nat |- _ ] => destruct (m u)\n  | [ |- impl (valuation ?b1 ?m) (valuation ?b2 ?m) = top ] => destruct (impl (valuation b1 m) (valuation b2 m))\n  | _ => idtac\n  end; try easy.\n  all: multimatch goal with\n  | [ |- impl (valuation ?b1 ?m) (valuation ?b2 ?m) = top ] => destruct (impl (valuation b1 m) (valuation b2 m))\n  | [ u : nat |- _ ] => destruct (m u)\n  | _ => idtac\n  end; try easy.\n  all: multimatch goal with\n  | H: join ?U ?I = top |- _ => destruct (join U I)\n  | H: meet ?U ?I = top |- _ => destruct (meet U I)\n  | [H: impl (valuation ?b1 ?m) (valuation ?b2 ?m) = top |- _ ] => destruct (impl (valuation b1 m) (valuation b2 m))\n  | _ => idtac\n  end; try easy.\n  all: multimatch goal with\n  | |- context [?m 2] => destruct (m 2)\n  | _ => idtac\n  end; try easy.\n  all: multimatch goal with\n  | |- context [?m 1] => destruct (m 1)\n  | _ => idtac\n  end; try easy.\n  all: multimatch goal with\n  | |- context [?m 0] => destruct (m 0)\n  | _ => idtac\n  end; try easy.\n\n  pose (mbot (n : nat) := valuation (s n) m).\n  pose proof (IHhilbert mbot).\n  clear -H1.\n  induction a; intros; try easy; simpl in *.\n  assert (valuation a1 mbot = top \\/ valuation a2 mbot = top).\n  destruct (valuation a1 mbot), (valuation a2 mbot); try auto.\n  destruct H.\n  rewrite (IHa1 ltac:(easy)).\n  destruct (valuation (subst a2 s) m); try easy.\n  rewrite (IHa2 ltac:(easy)).\n  destruct (valuation (subst a1 s) m); try easy.\n  destruct (valuation a1 mbot), (valuation a2 mbot); try easy.\n  rewrite (IHa1 eq_refl).\n  rewrite (IHa2 eq_refl).\n  reflexivity.\n\n\nLemma LEM_not_MID_valid : ~ MID_valid LEM.\nProof.\n  intros H.\n  unfold MID_valid, LEM in H.\n  specialize (H (fun n => mid)).\n  simpl in H.\n  easy.\nQed.\n\n\nTheorem hilbert_LEM_not_provable : ~ hilbert LEM.\nProof.\n  (* This should not need modifying *)\n  auto using LEM_not_MID_valid, hilbert_MID_sound.\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/lem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6785963534358838}}
{"text": "Require Import ssreflect ssrbool.\nRequire Export Lists.List.\nRequire Export GenReflect SetSpecs.\nRequire Export DecList.\nRequire Export DecSort.\nRequire Export mBidAsk.\nRequire Export Quantity.\nRequire Export mMatching.\nRequire Export MatchingAlter.\n\n\nSection Bound.\n\n\n(*-------------- buyers_above and sellers_above relationship and results------------------*)\n\n\n\nDefinition buyers_above (p: nat)(B: list Bid): list Bid :=\n  filter (fun x:Bid => Nat.leb p (bp x))  B.\n\nLemma buyers_above_elim (p:nat)(B: list Bid)(x:Bid):\n  In x (buyers_above p B)-> bp(x) >= p.\nProof. { unfold buyers_above. intros H. \n         induction B. \n         {  simpl in H. destruct H. } \n         {  simpl in H.  \n            destruct (Nat.leb p a) eqn: H1. \n            { simpl in H. destruct H. subst x. move /leP in H1. auto. \n            apply IHB in H. exact. }\n            { apply IHB in H. exact. }}} Qed.\n      \nLemma buyers_above_intro (p:nat)(B: list Bid)(x:Bid):\n ( In x B /\\ (Nat.leb p x)) -> In x (buyers_above p B).\nProof. { intros H. destruct H as [H1  H2].  \n         induction B. \n         { destruct H1. }\n         { simpl in H1. \n           destruct H1 as [H1a | H1b].\n           { subst x. simpl. destruct (Nat.leb p a) eqn: Hpa. auto.\n            apply IHB. eapply insert_elim2. apply insert_intro3.\n            auto. }\n           { apply IHB in H1b. simpl. destruct (Nat.leb p a) eqn: Hpa.\n             eauto. exact. }}} Qed.\n\nDefinition sellers_above (p: nat)(A: list Ask): list Ask :=\n  filter (fun x:Ask => Nat.leb p (sp x)) (A).\n\nLemma sellers_above_elim (p:nat)(A: list Ask)(x:Ask):\n  In x (sellers_above p A)-> sp(x) >= p.\nProof. { unfold sellers_above. intros H. \n         induction A. \n         {  simpl in H. destruct H. } \n         {  simpl in H.  \n            destruct (Nat.leb p a) eqn: H1. \n            { simpl in H. destruct H. subst x. move /leP in H1. auto. \n            apply IHA in H. exact. }\n            { apply IHA in H. exact. }}} Qed.\n            \nLemma sellers_above_intro (p:nat)(A: list Ask)(x:Ask):\n ( In x A /\\ Nat.leb p x ) -> In x (sellers_above p A).\nProof. { intros H. destruct H as [H1  H2].  \n         induction A. \n         { destruct H1. }\n         { simpl in H1. \n           destruct H1 as [H1a | H1b].\n           { subst x. simpl. destruct (Nat.leb p a) eqn: Hpa. auto. \n             apply IHA. eapply insert_elim2. apply insert_intro3.\n            auto. }\n           { apply IHA in H1b. simpl. destruct (Nat.leb p a) eqn: Hpa.\n             eauto. exact. }}} Qed.\n\nDefinition buyers_below (p: nat)(B: list Bid): list Bid :=\n  filter (fun x:Bid => Nat.ltb (bp x) p) (B).\n\nLemma buyers_below_intro (p:nat)(B: list Bid)(x:Bid):\n ( In x B /\\ Nat.ltb x p ) -> In x (buyers_below p B).\nProof. { intros H. destruct H as [H1  H2].  \n         induction B. \n         { destruct H1. }\n         { simpl in H1. \n           destruct H1 as [H1a | H1b].\n           { subst x. simpl. destruct (Nat.ltb a p) eqn: Hpa. auto. \n             apply IHB. eapply insert_elim2. apply insert_intro3.\n            auto. }\n           { apply IHB in H1b. simpl. destruct (Nat.ltb a p) eqn: Hpa.\n             eauto. exact. }}} Qed.\n\nLemma buyers_below_elim (p:nat)(B: list Bid)(x:Bid):\n  In x (buyers_below p B)-> bp(x) < p.\nProof.  { unfold sellers_above. intros H. \n         induction B. \n         {  simpl in H. destruct H. } \n         {  simpl in H.  \n            destruct (Nat.ltb a p) eqn: H1. \n            { simpl in H. destruct H. subst x. move /leP in H1. auto. \n            apply IHB in H. exact. }\n            { apply IHB in H. exact. }}} Qed.\n\nDefinition sellers_below (p: nat)(A: list Ask): list Ask :=\n  filter (fun x:Ask => Nat.leb (sp x) p) (A).\n\nLemma sellers_below_intro (p:nat)(A: list Ask)(x:Ask):\n ( In x A /\\ Nat.leb x p ) -> In x (sellers_below p A).\nProof. { intros H. destruct H as [H1  H2].  \n         induction A. \n         { destruct H1. }\n         { simpl in H1. \n           destruct H1 as [H1a | H1b].\n           { subst x. simpl. destruct (Nat.leb a p) eqn: Hpa. auto.\n             apply IHA. eapply insert_elim2. apply insert_intro3.\n            auto. }\n           { apply IHA in H1b. simpl. destruct (Nat.leb a p) eqn: Hpa.\n             eauto. exact. }}} Qed.\n\nLemma sellers_below_elim (p:nat)(A: list Ask)(x:Ask):\n  In x (sellers_below p A)-> sp(x) <= p.\nProof. { unfold sellers_below. intros H. \n         induction A. \n         {  simpl in H. destruct H. } \n         {  simpl in H.  \n            destruct (Nat.leb a p) eqn: H1. \n            { simpl in H. destruct H. subst x. move /leP in H1. auto. \n            apply IHA in H. exact. }\n            { apply IHA in H. exact. }}} Qed.\n\n\n(*#########Theorem in the paper###############*)\n\nLemma maching_buyer_right_plus_seller_left (B:list Bid)(A:list Ask):\nforall p M, (matching_in B A M) -> \nQM(M) <= QB(buyers_above p (bids_of M)) + QA(sellers_below p (asks_of M)).\nintros. induction M as [|m M']. simpl. auto.\nsimpl. assert(HM:matching_in B A (delete m (m::M'))).\n       eauto. simpl in HM. replace (m_eqb m m) with true in HM.\n       apply IHM' in HM.\n       assert(tq m <= bq (bid_of m)).\n       apply tqm_le_bqm with (M:=m::M')(B:=B)(A:=A).\n       auto. auto.\n       assert(tq m <= sq (ask_of m)).\n       apply tqm_le_sqm with (M:=m::M')(B:=B)(A:=A).\n       auto. auto.\n       destruct (Nat.leb p (bid_of m)) eqn: Hpb;\n       destruct (Nat.leb (ask_of m) p) eqn: Hpa.\n       all:simpl. all: (try lia).\n       { move /leP in Hpb. move /leP in Hpa.\n         assert(ask_of m <= bid_of m).\n         apply H. auto. lia.\n       } eauto.\nQed.\n\n(*Now we prove our main combinatorial result *) \n\n\n\nLemma buyers_above_nodup (B:list Bid) (Ndb: NoDup B) (p:nat):\nNoDup (buyers_above p B).\nProof. induction B. simpl. constructor. simpl. \ndestruct (Nat.leb p a) eqn: Hpa. assert (H0:~In a B).\neauto. assert (H1:~In a (buyers_above p B)). eauto. \nassert (H2: NoDup B). eauto. eapply IHB in H2. eauto.\nassert (H2: NoDup B). eauto. eapply IHB in H2. eauto. Qed.\n\nLemma sellers_below_nodup (A:list Ask) (Nda: NoDup A) (p:nat):\nNoDup (sellers_below p A).\nProof. induction A. simpl. constructor. simpl. \ndestruct (Nat.leb a p) eqn: Hpa. assert (H0:~In a A).\neauto. assert (H1:~In a (sellers_below p A)). eauto. \nassert (H2: NoDup A). eauto. eapply IHA in H2. eauto.\nassert (H2: NoDup A). eauto. eapply IHA in H2. eauto. Qed.\n\n\nDefinition Mbgep (p: nat)(M: list fill_type): list fill_type :=\n  filter (fun x:fill_type => Nat.leb p (bp (bid_of x))) M.\n\nDefinition Mbltp (p: nat)(M: list fill_type): list fill_type :=\n  filter (fun x:fill_type => Nat.ltb (bp (bid_of x)) p) M.\n\n\nLemma Mbgep_elim (p:nat)(M: list fill_type)(x:fill_type):\n  In x (Mbgep p M)-> (bp (bid_of x)) >= p.\nProof. { unfold Mbgep. intros H. \n         induction M. \n         {  simpl in H. destruct H. } \n         {  simpl in H.  \n            destruct (Nat.leb p (bid_of a)) eqn: H1. \n            { simpl in H. destruct H. subst x. move /leP in H1. auto. \n            apply IHM in H. exact. }\n            { apply IHM in H. exact. }}} Qed.\n      \nLemma Mbgep_intro (p:nat)(M: list fill_type)(x:fill_type):\n ( In x M /\\ (Nat.leb p (bid_of x))) -> In x (Mbgep p M).\nProof. { intros H. destruct H as [H1  H2].  \n         induction M. \n         { destruct H1. }\n         { simpl in H1. \n           destruct H1 as [H1a | H1b].\n           { subst x. simpl. destruct (Nat.leb p (bid_of a)) eqn: Hpa. auto.\n             elim H2.\n            apply IHM. eapply insert_elim2. apply insert_intro3.\n            auto. }\n           { apply IHM in H1b. simpl. destruct (Nat.leb p (bid_of a)) eqn: Hpa.\n             eauto. exact. }}} Qed.\n\nLemma Mbltp_elim (p:nat)(M: list fill_type)(x:fill_type):\n  In x (Mbltp p M)->  p> (bp (bid_of x)).\nProof. { unfold Mbltp. intros H. \n         induction M. \n         {  simpl in H. destruct H. } \n         {  simpl in H.  \n            destruct (Nat.ltb (bid_of a) p) eqn: H1. \n            { simpl in H. destruct H. subst x. move /leP in H1. auto. \n            apply IHM in H. exact. }\n            { apply IHM in H. exact. }}} Qed.\n\n\n      \nLemma Mbltp_intro (p:nat)(M: list fill_type)(x:fill_type):\n ( In x M /\\ (Nat.ltb (bid_of x) p)) -> In x (Mbltp p M).\nProof. { intros H. destruct H as [H1  H2].  \n         induction M. \n         { destruct H1. }\n         { simpl in H1. \n           destruct H1 as [H1a | H1b].\n           { subst x. simpl. destruct (Nat.ltb (bid_of a) p) eqn: Hpa. auto.\n             elim H2.\n            apply IHM. eapply insert_elim2. apply insert_intro3.\n            auto. }\n           { apply IHM in H1b. simpl. destruct (Nat.ltb (bid_of a) p) eqn: Hpa.\n             eauto. exact. }}} Qed.\n\n\nLemma Mbgep_bids_subsetBp (p:nat)(M: list fill_type)(B:list Bid):\nbids_of M [<=] B -> bids_of ((Mbgep p M)) [<=] (buyers_above p B).\nProof. intros. unfold \"[<=]\". intros. \nset (M1:=(Mbgep p M)). assert(exists x, In x M1/\\a=bid_of x).\neauto. destruct H1 as [m H1]. destruct H1. apply Mbgep_elim in H1 as H3.\nassert(In m M). eauto. assert(In (bid_of m) B). eauto. \nassert(In a (buyers_above p B)). apply buyers_above_intro.\nsubst. split. auto. apply /leP. lia. auto. Qed.\n\nLemma Mbgep_ttqb (p:nat)(M: list fill_type)(b:Bid):\nttqb ((Mbgep p M)) b <= ttqb M b.\nProof. induction M as [| m M']. simpl. auto.\nsimpl. \ndestruct (Nat.leb p (bid_of m)) eqn: Hpm;destruct (b_eqb b (bid_of m)) eqn:Hbm.\n{ simpl. rewrite Hbm. lia. }\n{ simpl. rewrite Hbm. lia. }\n{ lia. }\n{ lia. } Qed.\n\n\nLemma Mbltp_asks_subsetAp (p:nat)(M: list fill_type)(A:list Ask):\nAll_matchable M -> asks_of M [<=] A -> asks_of ((Mbltp p M)) [<=] (sellers_below p A).\nProof.\nintros. unfold \"[<=]\". intros. \nset (M1:=(Mbltp p M)). assert(exists x, In x M1/\\a=ask_of x).\neauto. destruct H2 as [m H2]. destruct H2. apply Mbltp_elim in H2 as H4.\nassert(In m M). eauto. assert(In (ask_of m) A). eauto. \nassert(In a (sellers_below p A)). apply sellers_below_intro.\nsubst. split. auto. apply /leP. \napply H in H5.\n lia. auto. Qed.\n\nLemma Mbltp_ttqa (p:nat)(M: list fill_type)(a:Ask):\nttqa ((Mbltp p M)) a <= ttqa M a.\nProof. induction M as [| m M']. simpl. auto.\nsimpl. \ndestruct (Nat.ltb (bid_of m) p) eqn: Hpm;destruct (a_eqb a (ask_of m)) eqn:Ham.\n{ simpl. rewrite Ham. lia. }\n{ simpl. rewrite Ham. lia. }\n{ lia. }\n{ lia. } Qed.\n\n\n\nLemma Mbgep_bound (p:nat)(M: list fill_type)(B:list Bid)(A:list Ask)\n(NDB:NoDup B):\nmatching_in B A M -> QM((Mbgep p M)) <= QB(buyers_above p B).\nProof.\nintros. rewrite <- QM_equal_QMb with (B:=(buyers_above p B)).\napply fill_size_vs_bid_size. apply buyers_above_nodup.\nauto. intros.\nassert(bids_of ((Mbgep p M)) [<=] (buyers_above p B)).\napply Mbgep_bids_subsetBp. apply H.\nassert(ttqb (Mbgep p M) b <= ttqb M b).\napply Mbgep_ttqb. cut(ttqb M b <= bq b).\nlia.\nassert(In b (bids_of M)\\/~In b (bids_of M)).\neauto. destruct H3.\napply H. auto. apply ttqb_elim in H3. lia.\napply buyers_above_nodup. auto. apply Mbgep_bids_subsetBp. apply H. \nQed.\n\nLemma Mbltp_bound (p:nat)(M: list fill_type)(B:list Bid)(A:list Ask)\n(NDA:NoDup A):\nmatching_in B A M -> QM((Mbltp p M)) <= QA(sellers_below p A).\nProof.\nintros. rewrite <- QM_equal_QMa with (A:=(sellers_below p A)).\napply fill_size_vs_ask_size. apply sellers_below_nodup. auto. intros.\nassert(asks_of ((Mbltp p M)) [<=] (sellers_below p A)).\napply Mbltp_asks_subsetAp. apply H. apply H. \nassert(ttqa (Mbltp p M) a <= ttqa M a).\napply Mbltp_ttqa. cut(ttqa M a <= sq a).\nlia.\nassert(In a (asks_of M)\\/~In a (asks_of M)).\neauto. destruct H3.\napply H. auto. apply ttqa_elim in H3. lia.\napply sellers_below_nodup. auto. apply Mbltp_asks_subsetAp. apply H. apply H.\nQed.\n\n\nLemma M_bound_volume (p:nat)(M: list fill_type):\nQM(M) = QM(Mbgep p M) + QM(Mbltp p M).\nProof. induction M. simpl. auto.\nsimpl. \ndestruct (Nat.leb p (bid_of a)) eqn:H1;destruct(Nat.ltb (bid_of a) p) eqn:H2.\n{ move /leP in H1. move /leP in H2. lia. }\n{ move /leP in H1. move /leP in H2. simpl. lia. }\n{ move /leP in H1. move /leP in H2. simpl. lia. }\n{ move /leP in H1. move /leP in H2. lia. } Qed.\n\n\nTheorem bound_on_M\n(M: list fill_type) (B:list Bid) (A:list Ask) (p:nat)\n(NDB: NoDup B)(NDA: NoDup A):\n(matching_in B A M) -> \nQM(M)<= QB(buyers_above p B) + QA(sellers_below p A).\nProof. intros. apply Mbgep_bound with (p:=p) in H as H1.\napply Mbltp_bound with (p:=p) in H as H2.\nassert(QM(M) = QM(Mbgep p M) + QM(Mbltp p M)). \napply M_bound_volume with (p:=p). lia. all:auto. Qed.\n\n\n\nEnd Bound.", "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/Bound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.678596347334161}}
{"text": "Require Export List.\nRequire Export Bool.\nRequire Export Lia.\nRequire Export Peano_dec.\n\nModule Classic.\n\n  Lemma axiom_of_choice (A : Set) (B : Set) :\n    forall phi : A -> B -> Prop,\n    (forall x : A, { y : B | phi x y }) ->\n    { f : A -> B | forall x : A, phi x (f x) }.\n  Proof.\n    intros phi.\n    intro H.\n    apply (exist (fun f : A -> B => forall x : A, phi x (f x)) (fun x : A => proj1_sig (H x))).\n    intros x.\n    unfold proj1_sig.\n    destruct (H x).\n    apply p.\n  Qed.\n\n  Axiom ex_middle : forall P : Prop, P \\/ ~P.\n\nEnd Classic.\n\nModule Ordering.\n\n  Inductive ordering : Set :=\n  | LT : ordering\n  | EQ : ordering\n  | GT : ordering\n  .\n\n  Fixpoint compareNats (lhs : nat) (rhs : nat) : ordering :=\n    match lhs, rhs with\n    | 0, 0 => EQ\n    | 0, S rhs' => LT\n    | S lhs', 0 => GT\n    | S lhs', S rhs' => compareNats lhs' rhs'\n    end\n  .\n\n  Lemma property_compareNats :\n    forall lhs rhs : nat,\n    (lhs < rhs /\\ compareNats lhs rhs = LT) \\/\n    (lhs = rhs /\\ compareNats lhs rhs = EQ) \\/\n    (lhs > rhs /\\ compareNats lhs rhs = GT).\n  Proof.\n    intros lhs.\n    induction lhs.\n    - destruct rhs.\n      * simpl.\n        tauto.\n      * simpl.\n        assert (0 < S rhs).\n          lia.\n        tauto.\n    - destruct rhs.\n      * simpl.\n        assert (S lhs > 0).\n          lia.\n        tauto.\n      * simpl.\n        assert\n          ( lhs < rhs /\\ compareNats lhs rhs = LT \\/\n            lhs = rhs /\\ compareNats lhs rhs = EQ \\/\n            lhs > rhs /\\ compareNats lhs rhs = GT\n          ).\n        apply (IHlhs rhs).\n        intuition.\n  Qed.\n\n  Theorem property_LT :\n    forall lhs rhs : nat,\n    LT = compareNats lhs rhs <-> lhs < rhs.\n  Proof.\n    intros lhs rhs.\n    assert\n      ( lhs < rhs /\\ compareNats lhs rhs = LT \\/\n        lhs = rhs /\\ compareNats lhs rhs = EQ \\/\n        lhs > rhs /\\ compareNats lhs rhs = GT\n      ).\n      apply (property_compareNats lhs rhs).\n    constructor.\n      intro.\n      intuition.\n      assert (LT = EQ).\n        rewrite <- H0 in H2.\n        apply H2.\n      discriminate H.\n      assert (LT = GT).\n        rewrite <- H0 in H2.\n        apply H2.\n      discriminate H.\n      intro.\n      assert (~lhs = rhs).\n        lia.\n      assert (~lhs > rhs).\n        lia.\n      intuition.\n  Qed.\n\n  Theorem property_EQ :\n    forall lhs rhs : nat,\n    EQ = compareNats lhs rhs <-> lhs = rhs.\n  Proof.\n    intros lhs rhs.\n    assert\n      ( lhs < rhs /\\ compareNats lhs rhs = LT \\/\n        lhs = rhs /\\ compareNats lhs rhs = EQ \\/\n        lhs > rhs /\\ compareNats lhs rhs = GT\n      ).\n      apply (property_compareNats lhs rhs).\n    constructor.\n      intro.\n      intuition.\n      assert (EQ = LT).\n        rewrite <- H0 in H2.\n        apply H2.\n      discriminate H1.\n      assert (EQ = GT).\n        rewrite <- H0 in H2.\n        apply H2.\n      discriminate H.\n      intro.\n      assert (~lhs < rhs).\n        lia.\n      assert (~lhs > rhs).\n        lia.\n      intuition.\n  Qed.\n\n  Theorem property_GT :\n    forall lhs rhs : nat,\n    GT = compareNats lhs rhs <-> lhs > rhs.\n  Proof.\n    intros lhs rhs.\n    assert\n      ( lhs < rhs /\\ compareNats lhs rhs = LT \\/\n        lhs = rhs /\\ compareNats lhs rhs = EQ \\/\n        lhs > rhs /\\ compareNats lhs rhs = GT\n      ).\n      apply (property_compareNats lhs rhs).\n    constructor.\n      intro.\n      intuition.\n      assert (GT = LT).\n        rewrite <- H0 in H2.\n        apply H2.\n      discriminate H1.\n      assert (GT = EQ).\n        rewrite <- H0 in H2.\n        apply H2.\n      discriminate H.\n      intro.\n      assert (~lhs < rhs).\n        lia.\n      assert (~lhs = rhs).\n        lia.\n      intuition.\n  Qed.\n\nEnd Ordering.\n\nModule ListTheory.\n\n  Section General.\n\n    Import ListNotations.\n\n    Variable A : Type.\n\n    Variable eq_A_dec : forall x y : A, {x = y} + {x <> y}.\n\n    Variable B : Type.\n\n    Fixpoint areAllDistinct (xs : list A) : Prop :=\n      match xs with\n      | [] => True\n      | x :: xs' => not (In x xs') /\\ areAllDistinct xs'\n      end\n    .\n\n    Lemma len_append :\n      forall (xs ys : list A),\n      length (xs ++ ys) = length xs + length ys.\n    Proof.\n      intros xs ys.\n      induction xs.\n      - simpl.\n        reflexivity.\n      - simpl.\n        lia.\n    Qed.\n\n    Lemma len_map :\n      forall f : A -> B,\n      forall xs : list A,\n      length xs = length (map f xs).\n    Proof.\n      intros f xs.\n      induction xs.\n      - simpl.\n        tauto.\n      - simpl.\n        lia.\n    Qed.\n\n    Lemma in_or_not_in :\n      forall xs : list A,\n      forall x : A,\n      In x xs \\/ ~ In x xs.\n    Proof.\n      intros xs.\n      induction xs.\n      simpl.\n      tauto.\n      simpl.\n      intro x.\n      destruct (eq_A_dec a x).\n      tauto.\n      destruct (IHxs x).\n      tauto.\n      tauto.\n    Qed.\n\n    Lemma in_append :\n      forall x : A,\n      forall (xs ys : list A),\n      In x (xs ++ ys) <-> (In x xs \\/ In x ys).\n    Proof.\n      intros x xs ys.\n      constructor.\n      - induction xs.\n        * simpl.\n          tauto.\n        * simpl.\n          tauto.\n      - intro.\n        induction xs.\n        * simpl.\n          destruct H.\n          + elimtype False.\n            apply H.\n          + apply H.\n        * simpl.\n          destruct H.\n          + destruct H.\n            apply (or_introl H).\n            apply or_intror.\n            tauto.\n          + tauto.\n    Qed.\n\n    Lemma in_map :\n      forall f : A -> B,\n      forall xs : list A,\n      forall x : A,\n      In x xs -> In (f x) (map f xs).\n    Proof.\n      intros f xs.\n      induction xs.\n      - simpl.\n        tauto.\n      - intros x.\n        simpl.\n        intro.\n        destruct H.\n        * subst.\n          tauto.\n        * apply (or_intror (IHxs x H)).\n    Qed.\n\n    Lemma in_middle :\n      forall (x y : A),\n      forall (xs ys : list A),\n      In x (xs ++ y :: ys) <-> (x = y \\/ In x (xs ++ ys)).\n    Proof.\n      intros x y xs ys.\n      induction xs.\n      - constructor.\n        * simpl.\n          intro.\n          destruct H.\n          apply or_introl.\n          auto.\n          tauto.\n        * simpl.\n          intro.\n          destruct H.\n          auto.\n          auto.\n      - constructor.\n        * simpl.\n          tauto.\n        * simpl.\n          tauto.\n    Qed.\n\n    Lemma in_map_in :\n      forall f : A -> B,\n      forall xs : list A,\n      forall y : B,\n      In y (map f xs) ->\n      exists x : A, y = f x /\\ In x xs.\n    Proof.\n      intros f xs.\n      induction xs.\n      - intros y.\n        simpl.\n        tauto.\n      - intros y.\n        simpl.\n        intro.\n        destruct H.\n        * exists a.\n          subst.\n          tauto.\n        * destruct (IHxs y H).\n          exists x.\n          tauto.\n    Qed.\n\n    Lemma in_map_inj :\n      forall f : A -> B,\n      (forall x1 x2 : A, f x1 = f x2 -> x1 = x2) ->\n      forall xs : list A,\n      forall x : A,\n      In (f x) (map f xs) -> In x xs.\n    Proof.\n      intros f.\n      intro.\n      intros xs.\n      induction xs.\n      - intros x.\n        simpl.\n        tauto.\n      - intros x.\n        simpl.\n        intro.\n        destruct H0.\n        * apply (or_introl (H a x H0)).\n        * apply (or_intror (IHxs x H0)).\n    Qed.\n\n    Lemma split_middle :\n      forall x : A,\n      forall xs : list A,\n      In x xs ->\n      exists ls : list A,\n      exists rs : list A,\n      xs = ls ++ x :: rs.\n    Proof.\n      intros x xs.\n      induction xs.\n      - simpl.\n        intro.\n        elimtype False.\n        apply H.\n      - intro.\n        destruct H.\n        * exists [].\n          exists xs.\n          subst.\n          simpl.\n          reflexivity.\n        * destruct (IHxs H) as [ls H0].\n          destruct (H0) as [rs].\n          exists (a :: ls).\n          exists rs.\n          subst.\n          simpl.\n          reflexivity.\n    Qed.\n\n    Theorem pigeon_hole :\n      forall (xs xs' : list A),\n      (forall x : A, In x xs -> In x xs') ->\n      length xs' < length xs ->\n      not (areAllDistinct xs).\n    Proof.\n      intros xs.\n      induction xs.\n      - intros xs'.\n        simpl.\n        intro.\n        lia.\n      - intros xs'.\n        simpl.\n        intro.\n        assert (H0 : exists ls : list A, exists rs : list A, xs' = ls ++ a :: rs).\n        apply (fun H0 : In a xs' => split_middle a xs' H0).\n        apply (H a).\n        simpl.\n        tauto.\n        destruct H0 as [ls H0].\n        destruct H0 as [rs H0].\n        subst.\n        assert (H0 : length (ls ++ a :: rs) = length ls + length (a :: rs)).\n        apply (len_append ls (a :: rs)).\n        subst.\n        rewrite H0.\n        simpl.\n        intro.\n        intro.\n        destruct H2.\n        apply (IHxs (ls ++ rs)).\n        * intros x.\n          intro.\n          apply (proj2 (in_append x ls rs)).\n          destruct (eq_A_dec a x).\n          + subst.\n            elimtype False.\n            apply (H2 H4).\n          + apply (proj1 (in_append x ls rs)).\n            assert (H6 : In x (ls ++ a :: rs)).\n            apply (H x (or_intror H4)).\n            assert (H7 : a = x \\/ In x (ls ++ rs)).\n            destruct (proj1 (in_middle x a ls rs)).\n            apply H6.\n            apply or_introl.\n            subst.\n            reflexivity.\n            apply or_intror.\n            apply H5.\n            destruct H7.\n            elimtype False.\n            apply (n H5).\n            apply H5.\n        * assert (H4 : length (ls ++ rs) = length ls + length rs).\n          apply (len_append ls rs).\n          lia.\n        * apply H3.\n    Qed.\n\n  End General.\n\n  Section Nat.\n\n    Import ListNotations.\n\n    Lemma enum_exists :\n      forall from : nat,\n      forall to : nat,\n      forall f_le_t : from <= to,\n      exists enum : list nat,\n      (from + length enum = to) /\\\n      (areAllDistinct nat enum) /\\\n      forall n : nat,\n      In n enum <->\n      (from <= n /\\ n < to)\n      .\n    Proof.\n      intros from to f_le_t.\n      induction f_le_t as [| to].\n      - exists [].\n        constructor.\n        simpl.\n        lia.\n        simpl.\n        constructor.\n        trivial.\n        intros n.\n        lia.\n      - destruct IHf_le_t as [enum H].\n        destruct H.\n        exists (to :: enum).\n        constructor.\n        simpl.\n        lia.\n        simpl.\n        destruct H0.\n        constructor.\n        constructor.\n        intro.\n        assert (from <= to < to).\n        apply (proj1 (H1 to) H2).\n        lia.\n        apply H0.\n        intros n.\n        constructor.\n        intro.\n        destruct H2.\n        subst.\n        lia.\n        assert (from <= n /\\ n < to).\n        apply (proj1 (H1 n) H2).\n        lia.\n        intro.\n        destruct (eq_nat_dec to n).\n        simpl.\n        tauto.\n        assert (from <= n /\\ n < to).\n        lia.\n        simpl.\n        apply or_intror.\n        apply (proj2 (H1 n) H3).\n    Qed.\n\n    Theorem pigeon_hole_nat :\n      forall size : nat,\n      forall ns : list nat,\n      (forall n : nat, In n ns <-> n < size) ->\n      areAllDistinct nat ns ->\n      length ns = size.\n    Proof.\n      intros size ns.\n      destruct (enum_exists 0 size) as [enum H].\n      lia.\n      intro.\n      intro.\n      assert (not (length ns > size)).\n      intro.\n      apply (pigeon_hole nat eq_nat_dec ns enum).\n      destruct H.\n      destruct H3.\n      intros n.\n      assert (n < size <-> 0 <= n < size).\n      lia.\n      intro.\n      apply (proj2 (H4 n)).\n      apply (proj1 H5).\n      apply (proj1 (H0 n) H6).\n      destruct H.\n      lia.\n      apply H1.\n      destruct H.\n      destruct H3.\n      assert (not (length ns < size)).\n      intro.\n      apply (pigeon_hole nat eq_nat_dec enum ns).\n      intros n.\n      assert (n < size <-> 0 <= n < size).\n      lia.\n      intro.\n      apply (proj2 (H0 n)).\n      apply (proj2 H6).\n      apply (proj1 (H4 n) H7).\n      lia.\n      apply H3.\n      lia.\n    Qed.\n\n  End Nat.\n\nEnd ListTheory.\n\nModule GraphTheory.\n\n  Record Graph : Type :=\n    { Vertex : Set\n    ; Edge : Vertex -> Vertex -> Prop\n    }\n  .\n\n  Section General.\n\n    Import ListNotations.\n\n    Import ListTheory.\n    \n    Variable g : Graph.\n  \n    Variable eq_gVertex_dec : forall v1 v2 : g.(Vertex), {v1 = v2} + {v1 <> v2}.\n\n    Inductive Path : list g.(Vertex) -> g.(Vertex) -> g.(Vertex) -> Prop :=\n    | PZ :\n      forall beg : g.(Vertex),\n      Path [beg] beg beg\n    | PS :\n      forall beg cur next : g.(Vertex),\n      forall visiteds : list g.(Vertex),\n      g.(Edge) cur next ->\n      not (In next visiteds) ->\n      Path visiteds beg cur ->\n      Path (next :: visiteds) beg next\n    .\n\n    Inductive Walk : list g.(Vertex) -> g.(Vertex) -> g.(Vertex) -> Prop :=\n    | WZ :\n      forall beg : g.(Vertex),\n      Walk [] beg beg\n    | WS :\n      forall trace : list g.(Vertex),\n      forall beg cur next : g.(Vertex),\n      g.(Edge) cur next ->\n      Walk trace beg cur ->\n      Walk (cur :: trace) beg next\n    .\n\n    Lemma subpath_exist :\n      forall visiteds : list g.(Vertex),\n      forall beg cur : g.(Vertex),\n      Path visiteds beg cur ->\n      forall prev : g.(Vertex),\n      In prev visiteds ->\n      exists visiteds' : list g.(Vertex),\n      Path visiteds' beg prev.\n    Proof.\n      intros visiteds beg cur.\n      intro.\n      induction H.\n      intros prev.\n      intro.\n      inversion H.\n      exists [beg].\n      subst.\n      apply PZ.\n      inversion H0.\n      intros prev.\n      intro.\n      inversion H2.\n      subst.\n      exists (prev :: visiteds).\n      apply (PS beg cur prev visiteds H H0 H1).\n      apply (IHPath prev H3).\n    Qed.\n\n    Theorem walk_implies_path :\n      forall trace : list g.(Vertex),\n      forall beg cur : g.(Vertex),\n      Walk trace beg cur ->\n      exists visiteds,\n      Path visiteds beg cur.\n    Proof.\n      intros trace beg cur.\n      intro.\n      induction H.\n      exists [beg].\n      apply (PZ beg).\n      destruct IHWalk as [visiteds].\n      destruct (in_or_not_in g.(Vertex) eq_gVertex_dec visiteds next).\n      apply (subpath_exist visiteds beg cur H1 next H2).\n      exists (next :: visiteds).\n      apply (PS beg cur next visiteds H H2 H1).\n    Qed.\n\n    Proposition visiteds_are_all_distinct :\n      forall visiteds : list g.(Vertex),\n      forall beg cur : g.(Vertex),\n      Path visiteds beg cur ->\n      areAllDistinct g.(Vertex) visiteds.\n    Proof.\n      intros visiteds beg cur.\n      intro.\n      induction H.\n      - subst.\n        simpl.\n        tauto.\n      - subst.\n        simpl.\n        tauto.\n    Qed.\n\n  End General.\n\n  Section Finite.\n\n    Import ListNotations.\n\n    Import ListTheory.\n\n    Variable g : Graph.\n  \n    Variable eq_gVertex_dec : forall v1 v2 : g.(Vertex), {v1 = v2} + {v1 <> v2}.\n\n    Variable size : nat.\n\n    Variable can_enum_vertices : (exists vertices : list g.(Vertex), areAllDistinct g.(Vertex) vertices /\\ length vertices = size /\\ (forall v : g.(Vertex), In v vertices)).\n\n    Proposition len_path_leq_size : \n      forall visiteds : list g.(Vertex),\n      forall beg cur : g.(Vertex),\n      Path g visiteds beg cur ->\n      length visiteds <= size.\n    Proof.\n      intros visiteds beg cur.\n      intro.\n      destruct can_enum_vertices as [vertices].\n      assert (not (length visiteds > size)).\n        intro.\n        destruct H0.\n        destruct H2.\n        apply (pigeon_hole g.(Vertex) eq_gVertex_dec visiteds vertices).\n          intros v.\n          intro.\n          apply (H3 v).\n          lia.\n          apply (visiteds_are_all_distinct g visiteds beg cur H).\n        lia.\n    Qed.\n\n  End Finite.\n\nEnd GraphTheory.\n\nModule ETC.\n\n  Fixpoint first_nat (p : nat -> bool) (n : nat) : nat :=\n    match n with\n    | 0 => 0\n    | S n' => if p (first_nat p n') then first_nat p n' else n\n    end\n  .\n\n  Theorem well_ordering_principle : \n    forall p : nat -> bool,\n    (exists n : nat, p n = true) ->\n    (exists m : nat, p m = true /\\ (forall i : nat, p i = true -> i >= m)).\n  Proof.\n    intros p.\n    assert (forall x : nat, p x = true -> p (first_nat p x) = true).\n      intros x.\n      induction x.\n      tauto.\n      simpl.\n      cut (let b := p (first_nat p x) in p (S x) = true -> p (if b then first_nat p x else S x) = true).\n        simpl.\n        tauto.\n      intros.\n      assert (b = true \\/ b = false).\n        destruct b.\n          tauto.\n          tauto.\n      destruct H0.\n      rewrite H0.\n      unfold b in H0.\n      apply H0.\n      rewrite H0.\n      apply H.\n    assert (forall x : nat, first_nat p x <= x).\n      intros x.\n      induction x.\n        simpl.\n        lia.\n        simpl.\n        cut (let b := p (first_nat p x) in (if b then first_nat p x else S x) <= S x).\n          simpl.\n          tauto.\n        intros.\n        assert (b = true \\/ b = false).\n          destruct b.\n            tauto.\n            tauto.\n        destruct H0.\n          rewrite H0.\n          lia.\n          rewrite H0.\n          lia.\n    assert (forall x : nat, p (first_nat p x) = true -> (forall y : nat, x < y -> first_nat p x = first_nat p y)).\n      intros x.\n      intro.\n      intros y.\n      intro.\n      induction H2.\n        simpl.\n        rewrite H1.\n        tauto.\n        simpl.\n        rewrite <- IHle.\n        rewrite H1.\n        tauto.\n    assert (forall x : nat, forall y : nat, p y = true -> first_nat p x <= y).\n      intros x.\n      intros y.\n      intro.\n      assert (x <= y \\/ x > y).\n        lia.\n      destruct H3.\n      assert (first_nat p x <= x <= y).\n        constructor.\n        apply (H0 x).\n        apply H3.\n        lia.\n      assert (p (first_nat p y) = true).\n        apply (H y).\n        assert (first_nat p x <= x).\n          apply (H0 x).\n          apply H2.\n      assert (first_nat p y = first_nat p x).\n        apply (H1 y).\n        apply H4.\n        lia.\n        rewrite <- H5.\n        apply (H0 y).\n    intro.\n    destruct H3.\n    exists (first_nat p x).\n    constructor.\n    apply (H x H3).\n    intros i.\n    intro.\n    assert (first_nat p x <= i).\n      apply (H2 x i H4).\n    lia.\n  Qed.\n\nEnd ETC.\n", "meta": {"author": "KiJeong-Lim", "repo": "proof", "sha": "d3d488c224ac310d4f591c7eb6233d112287f9b9", "save_path": "github-repos/coq/KiJeong-Lim-proof", "path": "github-repos/coq/KiJeong-Lim-proof/proof-d3d488c224ac310d4f591c7eb6233d112287f9b9/scratch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.7826624688140728, "lm_q1q2_score": 0.6785963429387819}}
{"text": "Require Export Relations Morphisms.\n\nRequire Import List.\nImport ListNotations.\n\nSet Primitive Projections.\nSet Implicit Arguments.\n\nLocal Notation negate P := (fun x => ~P x).\nLocal Notation conjoin P Q := (fun x => P x /\\ Q x).\nLocal Notation disjoin P Q := (fun x => P x \\/ Q x).\nLocal Notation const x := (fun _ => x).\nLocal Notation \"f ∘ g\" := (fun x => f (g x)) (at level 30).\n\nModule set.\n  Section Basics.\n\n    Variable V : Type.\n\n    Record t := of { spec : (V -> Prop) }.\n\n    Implicit Type a b c x y z : V.\n    Implicit Type A B C X Y Z : t.\n\n    Inductive elem x A : Prop := elem_ext : A.(spec) x -> elem x A.\n\n    Definition eq A B := forall x, elem x A <-> elem x B.\n\n    Definition subset A B := forall x, elem x A -> elem x B.\n\n    Property eq_refl : Reflexive eq.\n    Proof.\n      unfold eq; intros A x.\n      reflexivity.\n    Qed.\n\n    Property eq_sym : Symmetric eq.\n    Proof.\n      unfold eq; intros A B H1 x.\n      specialize (H1 x).\n      symmetry; assumption.\n    Qed.\n\n    Property eq_trans : Transitive eq.\n    Proof.\n      unfold  eq; intros A B C H1 H2 x.\n      specialize (H1 x); specialize (H2 x).\n      etransitivity; eassumption.\n    Qed.\n\n    Property subset_refl : Reflexive subset.\n    Proof. cbv; auto. Qed.\n    \n    Property subset_trans : Transitive subset.\n    Proof. cbv; auto. Qed.\n\n    Global Add Relation t eq\n      reflexivity proved by eq_refl\n      symmetry proved by eq_sym\n      transitivity proved by eq_trans\n    as eq_rel.\n\n    Global Add Relation t subset\n      reflexivity proved by subset_refl\n      transitivity proved by subset_trans\n    as subset_rel.\n\n    Property eq_subset A B : eq A B <-> subset A B /\\ subset B A.\n    Proof. cbv; do 2 split; apply H. Qed.\n\n    Global Add Morphism elem : elem_morphism.\n    Proof. intros x ? ? ?; revert x; assumption. Qed.\n\n    Global Add Morphism subset : subset_morphism.\n    Proof. \n      now_show (Proper (eq ==> eq ==> iff) subset).\n      unfold subset; solve_proper.\n    Qed.\n\n    Definition empty := of (fun x => False).\n\n    Definition full := of (fun x => True).\n\n    Definition union A B := of (disjoin A.(spec) B.(spec)).\n\n    Definition intersection A B := of (conjoin A.(spec) B.(spec)).\n\n    Definition complement A := of (negate A.(spec)).\n\n  End Basics.\n\nEnd set.\n\nNotation set := set.t.\n\nDeclare Scope set_scope.\nBind Scope set_scope with set.\nDelimit Scope set_scope with set.\n\nNotation \"x ∈ A\" := (set.elem x A) (at level 70, right associativity) : set_scope.\nNotation \"x ∉ A\" := (~set.elem x A) (at level 70, right associativity) : set_scope.\nNotation \"A ∋ x\" := (set.elem x A) (at level 71, left associativity, only parsing) : set_scope.\nNotation \"A ∌ x\" := (~set.elem x A) (at level 71, left associativity, only parsing) : set_scope.\nNotation \"A ⊆ B\" := (set.subset A B) (at level 70, right associativity) : set_scope.\nNotation \"A ⊈ B\" := (~set.subset A B) (at level 70, right associativity) : set_scope.\nNotation \"B ⊇ A\" := (set.subset A B) (at level 71, left associativity, only parsing) : set_scope.\nNotation \"B ⊉ A\" := (~set.subset A B) (at level 71, left associativity, only parsing) : set_scope.\nNotation \"A == B\" := (set.eq A B) (at level 70, no associativity) : set_scope.\nNotation \"A =/= B\" := (~set.eq A B) (at level 70, no associativity) : set_scope.\nNotation \"∅\" := (set.empty _) : set_scope.\nNotation \"[ X ]\" := (set.full X) : set_scope.\nNotation \"A ∪ B\" := (set.union A B) (at level 50, left associativity) : set_scope.\nNotation \"A ∩ B\" := (set.intersection A B) (at level 40, left associativity) : set_scope.\nNotation \"- A\" := (set.complement A) : set_scope.\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/BetterSets/Base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6785637161484709}}
{"text": "Add LoadPath \"D:\\sfsol\".\nRequire Export Types.\n\nModule STLC.\n\nInductive ty : Type :=\n  | TBool : ty\n  | TArrow : ty -> ty -> ty.\n\nInductive tm : Type :=\n  | tvar : id -> tm\n  | tapp : tm -> tm -> tm\n  | tabs : id -> ty -> tm -> tm\n  | ttrue : tm\n  | tfalse : tm\n  | tif : tm -> tm -> tm -> tm.\n\nTactic Notation \"t_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"tvar\" | Case_aux c \"tapp\"\n  | Case_aux c \"tabs\" | Case_aux c \"ttrue\"\n  | Case_aux c \"tfalse\" | Case_aux c \"tif\" ].\n\nDefinition x := (Id 0).\nDefinition y := (Id 1).\nDefinition z := (Id 2).\nHint Unfold x.\nHint Unfold y.\nHint Unfold z.\n\nNotation idB :=\n  (tabs x TBool (tvar x)).\n\nNotation idBB :=\n  (tabs x (TArrow TBool TBool) (tvar x)).\n\nNotation idBBBB :=\n  (tabs x (TArrow (TArrow TBool TBool)\n                      (TArrow TBool TBool))\n    (tvar x)).\n\nNotation k := (tabs x TBool (tabs y TBool (tvar x))).\n\nNotation notB := (tabs x TBool (tif (tvar x) tfalse ttrue)).\n\nInductive value : tm -> Prop :=\n  | v_abs : forall x T t,\n      value (tabs x T t)\n  | v_true :\n      value ttrue\n  | v_false :\n      value tfalse.\n\nHint Constructors value.\n\nReserved Notation \"'[' x ':=' s ']' t\" (at level 20).\n\nFixpoint subst (x:id) (s:tm) (t:tm) : tm :=\n  match t with\n  | tvar x' =>\n      if eq_id_dec x x' then s else t\n  | tabs x' T t1 =>\n      tabs x' T (if eq_id_dec x x' then t1 else ([x:=s] t1))\n  | tapp t1 t2 =>\n      tapp ([x:=s] t1) ([x:=s] t2)\n  | ttrue =>\n      ttrue\n  | tfalse =>\n      tfalse\n  | tif t1 t2 t3 =>\n      tif ([x:=s] t1) ([x:=s] t2) ([x:=s] t3)\n  end\n\nwhere \"'[' x ':=' s ']' t\" := (subst x s t).\n\nInductive substi (s:tm) (x:id) : tm -> tm -> Prop :=\n  | s_var1 :\n      substi s x (tvar x) s\n  | s_var2 : forall y, y<>x ->\n      substi s x (tvar y) (tvar y)\n  | s_tabs1 : forall t T,\n      substi s x (tabs x T t) (tabs x T t)\n  | s_tabs2 : forall y t T t', y<>x -> substi s x t t' ->\n      substi s x (tabs y T t) (tabs y T t')\n  | s_app : forall t1 t2 t1' t2', (substi s x t1 t1')->(substi s x t2 t2')->\n      substi s x (tapp t1 t2) (tapp t1' t2')\n  | s_true : substi s x ttrue ttrue\n  | s_false : substi s x tfalse tfalse\n  | s_tif : forall t1 t2 t3 t1' t2' t3', (substi s x t1 t1')->\n      (substi s x t2 t2')->(substi s x t3 t3')->\n      substi s x (tif t1 t2 t3) (tif t1' t2' t3').\n\nHint Constructors substi.\n\nTheorem substi_correct : forall s x t t',\n  [x:=s]t = t' <-> substi s x t t'.\nProof.\n  split; intros. generalize dependent t'.\n    induction t; intros; simpl in H; subst; eauto 10;\n      try destruct (eq_id_dec x0 i); subst;eauto.\n    induction H; simpl; subst; try rewrite eq_id; eauto; try rewrite neq_id; eauto.\n  Qed.\n\n\nReserved Notation \"t1 '==>' t2\" (at level 40).\n\nInductive step : tm -> tm -> Prop :=\n  | ST_AppAbs : forall x T t12 v2,\n         value v2 ->\n         (tapp (tabs x T t12) v2) ==> [x:=v2]t12\n  | ST_App1 : forall t1 t1' t2,\n         t1 ==> t1' ->\n         tapp t1 t2 ==> tapp t1' t2\n  | ST_App2 : forall v1 t2 t2',\n         value v1 ->\n         t2 ==> t2' ->\n         tapp v1 t2 ==> tapp v1 t2'\n  | ST_IfTrue : forall t1 t2,\n      (tif ttrue t1 t2) ==> t1\n  | ST_IfFalse : forall t1 t2,\n      (tif tfalse t1 t2) ==> t2\n  | ST_If : forall t1 t1' t2 t3,\n      t1 ==> t1' ->\n      (tif t1 t2 t3) ==> (tif t1' t2 t3)\n\nwhere \"t1 '==>' t2\" := (step t1 t2).\n\nTactic Notation \"step_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"ST_AppAbs\" | Case_aux c \"ST_App1\"\n  | Case_aux c \"ST_App2\" | Case_aux c \"ST_IfTrue\"\n  | Case_aux c \"ST_IfFalse\" | Case_aux c \"ST_If\" ].\n\nHint Constructors step.\n\nNotation multistep := (multi step).\nNotation \"t1 '==>*' t2\" := (multistep t1 t2) (at level 40).\n\nLemma step_example1 :\n  (tapp idBB idB) ==>* idB.\nProof.\n  eapply multi_step.\n    apply ST_AppAbs.\n    apply v_abs.\n  simpl.\n  apply multi_refl. Qed.\n\nLemma step_example2 :\n  (tapp idBB (tapp idBB idB)) ==>* idB.\nProof.\n  eapply multi_step.\n    apply ST_App2. auto.\n    apply ST_AppAbs. auto.\n  eapply multi_step.\n    apply ST_AppAbs. simpl. auto.\n  simpl. apply multi_refl. Qed.\n\nLemma step_example3 :\n  tapp (tapp idBB notB) ttrue ==>* tfalse.\nProof.\n  eapply multi_step.\n    apply ST_App1. apply ST_AppAbs. auto. simpl.\n  eapply multi_step.\n    apply ST_AppAbs. auto. simpl.\n  eapply multi_step.\n    apply ST_IfTrue. apply multi_refl. Qed.\n\nLemma step_example4 :\n  tapp idBB (tapp notB ttrue) ==>* tfalse.\nProof.\n  eapply multi_step.\n    apply ST_App2. auto.\n    apply ST_AppAbs. auto. simpl.\n  eapply multi_step.\n    apply ST_App2. auto.\n    apply ST_IfTrue.\n  eapply multi_step.\n    apply ST_AppAbs. auto. simpl.\n  apply multi_refl. Qed.\n\nLemma step_example1' :\n  (tapp idBB idB) ==>* idB.\nProof. normalize. Qed.\n\nLemma step_example2' :\n  (tapp idBB (tapp idBB idB)) ==>* idB.\nProof.\n  normalize.\nQed.\n\nLemma step_example3' :\n  tapp (tapp idBB notB) ttrue ==>* tfalse.\nProof. normalize. Qed.\n\nLemma step_example4' :\n  tapp idBB (tapp notB ttrue) ==>* tfalse.\nProof. normalize. Qed.\n\nLemma step_example5 :\n       (tapp (tapp idBBBB idBB) idB)\n  ==>* idB.\nProof.\n  eapply multi_step. eapply ST_App1. eapply ST_AppAbs. eauto.\n  simpl. eapply multi_step. eapply ST_AppAbs. eauto. simpl.\n  apply multi_refl. Qed.\n\nLemma step_example5' :\n       (tapp (tapp idBBBB idBB) idB)\n  ==>* idB.\nProof. normalize. Qed.\n\nModule PartialMap.\n\nDefinition partial_map (A:Type) := id -> option A.\n\nDefinition empty {A:Type} : partial_map A := (fun _ => None).\n\nDefinition extend {A:Type} (Γ : partial_map A) (x:id) (T : A) :=\n  fun x' => if eq_id_dec x x' then Some T else Γ x'.\n\nLemma extend_eq : forall A (ctxt: partial_map A) x T,\n  (extend ctxt x T) x = Some T.\nProof.\n  intros. unfold extend. rewrite eq_id. auto.\nQed.\n\nLemma extend_neq : forall A (ctxt: partial_map A) x1 T x2,\n  x2 <> x1 ->\n  (extend ctxt x2 T) x1 = ctxt x1.\nProof.\n  intros. unfold extend. rewrite neq_id; auto.\nQed.\n\nEnd PartialMap.\n\nDefinition context := partial_map ty.\n\nReserved Notation \"Gamma '|-' t '\\in' T\" (at level 40).\n\nInductive has_type : context -> tm -> ty -> Prop :=\n  | T_Var : forall Gamma x T,\n      Gamma x = Some T ->\n      Gamma |- tvar x \\in T\n  | T_Abs : forall Gamma x T11 T12 t12,\n      extend Gamma x T11 |- t12 \\in T12 ->\n      Gamma |- tabs x T11 t12 \\in TArrow T11 T12\n  | T_App : forall T11 T12 Gamma t1 t2,\n      Gamma |- t1 \\in TArrow T11 T12 ->\n      Gamma |- t2 \\in T11 ->\n      Gamma |- tapp t1 t2 \\in T12\n  | T_True : forall Gamma,\n       Gamma |- ttrue \\in TBool\n  | T_False : forall Gamma,\n       Gamma |- tfalse \\in TBool\n  | T_If : forall t1 t2 t3 T Gamma,\n       Gamma |- t1 \\in TBool ->\n       Gamma |- t2 \\in T ->\n       Gamma |- t3 \\in T ->\n       Gamma |- tif t1 t2 t3 \\in T\n\nwhere \"Gamma '|-' t '\\in' T\" := (has_type Gamma t T).\n\nTactic Notation \"has_type_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"T_Var\" | Case_aux c \"T_Abs\"\n  | Case_aux c \"T_App\" | Case_aux c \"T_True\"\n  | Case_aux c \"T_False\" | Case_aux c \"T_If\" ].\n\nHint Constructors has_type.\n\nExample typing_example_1 :\n  empty |- tabs x TBool (tvar x) \\in TArrow TBool TBool.\nProof.\n  apply T_Abs. apply T_Var. reflexivity. Qed.\n\nExample typing_example_1' :\n  empty |- tabs x TBool (tvar x) \\in TArrow TBool TBool.\nProof. auto. Qed.\n\nExample typing_example_2 :\n  empty |-\n    (tabs x TBool\n       (tabs y (TArrow TBool TBool)\n          (tapp (tvar y) (tapp (tvar y) (tvar x))))) \\in\n    (TArrow TBool (TArrow (TArrow TBool TBool) TBool)).\nProof with auto using extend_eq.\n  apply T_Abs.\n  apply T_Abs.\n  eapply T_App. apply T_Var...\n  eapply T_App. apply T_Var...\n  apply T_Var...\nQed.\n\nExample typing_example_2_full :\n  empty |-\n    (tabs x TBool\n       (tabs y (TArrow TBool TBool)\n          (tapp (tvar y) (tapp (tvar y) (tvar x))))) \\in\n    (TArrow TBool (TArrow (TArrow TBool TBool) TBool)).\nProof.\n  apply T_Abs.\n  apply T_Abs.\n  apply T_App with (TBool). apply T_Var. apply extend_eq.\n  apply T_App with (TBool). apply T_Var. apply extend_eq.\n  apply T_Var. apply extend_neq. destruct (eq_id_dec y x). inversion e. assumption.\n  Qed.\n\nExample typing_example_3 :\n  exists T,\n    empty |-\n      (tabs x (TArrow TBool TBool)\n         (tabs y (TArrow TBool TBool)\n            (tabs z TBool\n               (tapp (tvar y) (tapp (tvar x) (tvar z)))))) \\in\n      T.\nProof with auto.\n  exists (TArrow (TArrow TBool TBool) (TArrow (TArrow TBool TBool) (TArrow TBool TBool))).\n  apply T_Abs.\n  apply T_Abs.\n  apply T_Abs.\n  apply T_App with (TBool). apply T_Var...\n  apply T_App with (TBool). apply T_Var...\n  apply T_Var...\n  Qed.\n\nExample typing_nonexample_1 :\n  ~ exists T,\n      empty |-\n        (tabs x TBool\n            (tabs y TBool\n               (tapp (tvar x) (tvar y)))) \\in\n        T.\nProof.\n  intros Hc. inversion Hc.\n  inversion H. subst. clear H.\n  inversion H5. subst. clear H5.\n  inversion H4. subst. clear H4.\n  inversion H2. subst. clear H2.\n  inversion H5. subst. clear H5.\n  inversion H1. Qed.\n\nLemma TarrowUneq : forall T1 T2,\n  ~ (TArrow T1 T2 = T1).\nProof.\n  induction T1; intros T2 contra; inversion contra.\n  eapply IHT1_1. apply H0.\n  Qed.\n\nExample typing_nonexample_3 :\n  ~ (exists S, exists T,\n        empty |-\n          (tabs x S\n             (tapp (tvar x) (tvar x))) \\in\n          T).\nProof.\n  intros Hc. inversion Hc. inversion H.\n  inv H0. inv H6. inv H3. inv H2.\n  inv H5. inversion H2.\n  eapply TarrowUneq. apply H1.\n  Qed.\n\nEnd STLC.", "meta": {"author": "mmalone", "repo": "sfsol", "sha": "5888f4532a1ec1ababa21bef39e25eb26279f0e4", "save_path": "github-repos/coq/mmalone-sfsol", "path": "github-repos/coq/mmalone-sfsol/sfsol-5888f4532a1ec1ababa21bef39e25eb26279f0e4/Stlc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.6785614938645388}}
{"text": "Require Import Arith.\nRequire Import Lists.List.\nRequire Import Coq.Relations.Relations.\nRequire Coq.Vectors.Vector.\nImport Vector.VectorNotations.\nRequire Coq.Vectors.Fin.\nRequire Import Coq.Logic.Eqdep_dec.\nRequire Import Coq.Arith.Peano_dec.\nRequire Import Coq.Structures.Orders.\nRequire Import Program.\n\nHint Immediate eq_nat_dec.\n\nTactic Notation \"solve_by_inversion_step\" tactic(t) :=\n  match goal with\n    | H : _ |- _ => solve [ inversion H; subst; t ]\n  end\n    || fail \"because the goal is not solvable by inversion.\".\n\nTactic Notation \"solve\" \"by\" \"inversion\" \"1\" :=\n  solve_by_inversion_step idtac.\nTactic Notation \"solve\" \"by\" \"inversion\" \"2\" :=\n  solve_by_inversion_step (solve by inversion 1).\nTactic Notation \"solve\" \"by\" \"inversion\" \"3\" :=\n  solve_by_inversion_step (solve by inversion 2).\nTactic Notation \"solve\" \"by\" \"inversion\" :=\n  solve by inversion 1.\n\nTheorem Forall_app : forall A (R : A -> Prop) l1 l2,\n                       Forall R l1 -> Forall R l2 -> Forall R (l1 ++ l2).\nProof.\n  induction l1; simpl; intros.\n  auto.\n  inversion H; constructor; auto.\nQed.\n\nNotation \"'sigma' x .. y ',' p\" := (sigT (fun x => .. (sigT (fun y => p)) ..))\n                                     (at level 180, x binder, right associativity)\n                                   : type_scope.\n\nLemma fin_case :\n  forall n (P : Fin.t (S n) -> Type),\n    (P Fin.F1) ->\n    (forall x, P (Fin.FS x)) ->\n    (forall x, P x).\nProof.\n  intros.\n  refine (match x as x' in Fin.t n'\n                return forall pf : n' = S n,\n                         eq_rect n' Fin.t x' (S n) pf = x ->\n                         P x with\n            | Fin.F1 _ => _\n            | Fin.FS _ _ => _\n          end eq_refl _).\n  - intros.\n    inversion pf.\n    subst.\n    rewrite <- Eqdep_dec.eq_rect_eq_dec by apply eq_nat_dec.\n    auto.\n  - intros.\n    inversion pf.\n    subst.\n    rewrite <- Eqdep_dec.eq_rect_eq_dec by apply eq_nat_dec.\n    auto.\n  - rewrite <- Eqdep_dec.eq_rect_eq_dec by apply eq_nat_dec.\n    reflexivity.\nQed.\n\nLtac fin_dep_destruct v :=\n  pattern v; apply fin_case; clear v; intros.\n\nLtac finite :=\n  let rec finite' n x :=\n      match n with\n        | S ?n_ =>\n          let x' := fresh \"x\" in\n          pattern x; apply fin_case; [clear x | clear x; intros x'; finite' n_ x']\n        | O => pattern x; apply Fin.case0\n      end\n  in\n  match goal with\n    | [ |- forall (x : Fin.t ?n), _ ] =>\n      intros x; finite' n x\n  end.\n\nLemma eq_fin_dec : forall {n} (f f' : Fin.t n), {f = f'} + {f <> f'}.\nProof.\n  induction n; intros.\n  apply Fin.case0; auto.\n  fin_dep_destruct f; fin_dep_destruct f';\n  try (right; intro; solve by inversion).\n  left; auto.\n  specialize (IHn x x0).\n  destruct IHn.\n  left; f_equal; auto.\n  right. intro. inversion H. apply inj_pair2_eq_dec in H1. auto. auto.\nQed.\n\nHint Immediate eq_fin_dec.\n\nLemma eq_vector_dec_ind : forall {n A} (v v' : Vector.t A n), (forall i t, {v[@i] = t} + {v[@i] <> t}) -> {v = v'} + {v <> v'}.\nProof.\n  induction n; dependent destruction v; dependent destruction v'; intros.\n  left; auto.\n  assert (forall (i : Fin.t n) (t : A), {v[@i] = t} + {v[@i] <> t}).\n  intros.\n  specialize (X (Fin.FS i) t); auto.\n  specialize (IHn _ v v' X0).\n  specialize (X Fin.F1 h0); simpl in X.\n  destruct IHn; destruct X; subst;\n  try (left; auto; fail).\n  right; intro; inversion H; auto.\n  right; intro; inversion H; auto; apply inj_pair2_eq_dec in H1; auto.\n  right; intro; inversion H; auto; apply inj_pair2_eq_dec in H1; auto.\nQed.\n\nLemma eq_vector_dec : forall {n A} (P : forall (t t' : A), {t = t'} + {t <> t'}) (v v' : Vector.t A n), {v = v'} + {v <> v'}.\nProof.\n  intros. apply eq_vector_dec_ind.\n  intros. apply P.\nQed.\n\nHint Immediate eq_vector_dec.\n\nLtac simpl_exist :=\n  repeat (\n      repeat match goal with\n               | [ H : existT _ _ _ = existT _ _ _ |- _] =>\n                 (apply inj_pair2_eq_dec in H; [|eauto using eq_vector_dec; fail])\n               | [ H : existT _ _ _ = existT _ _ _, _ : existT _ _ _ = existT _ _ _ |- _] =>\n                 (apply inj_pair2_eq_dec in H; [|eauto using eq_vector_dec; fail])\n               | [ H : existT _ _ _ = existT _ _ _, _ : existT _ _ _ = existT _ _ _, _ : existT _ _ _ = existT _ _ _ |- _] =>\n                 (apply inj_pair2_eq_dec in H; [|eauto using eq_vector_dec; fail])\n             end;\n      subst; clear_dups\n    ).\n\nLemma lift_fin_inj : forall {n} m (i : Fin.t n) j,\n                       Fin.R m i = Fin.R m j -> i = j.\nProof.\n  induction m; intros; simpl in H; auto.\n  inversion H. apply inj_pair2_eq_dec in H1; eauto.\nQed.\n\nLemma vector_map_map : forall {n A B C} (f : B->C) (g:A->B) (v : Vector.t A n),\n                         Vector.map f (Vector.map g v) = Vector.map (fun x => f (g x)) v.\nProof.\n  induction v; auto.\n  simpl. f_equal. auto.\nQed.\n\nLemma vector_map_inj : forall {n A B} (f : A -> B) (v v' : Vector.t A n)\n                       (P : forall i t', f v[@i] = f t' -> v[@i] = t'),\n                         Vector.map f v = Vector.map f v' -> v = v'.\nProof.\n  induction v; intros; dependent destruction v'; auto.\n  intros. f_equal. \n  inversion H. specialize (P Fin.F1 h0). auto.\n  assert (forall (i : Fin.t n) (t' : A), f v[@i] = f t' -> v[@i] = t').\n  intros. specialize (P (Fin.FS i) t'). simpl in P. auto.\n  specialize (IHv v' H0).\n  inversion H. apply inj_pair2_eq_dec in H3; auto.\nQed.\n\nLemma fin_compare : forall {n}, Fin.t n -> Fin.t n -> comparison.\nProof.\n  intros n. induction n.\n  intros. apply Fin.case0; eauto.\n  intros x y. fin_dep_destruct x; fin_dep_destruct y.\n  apply Eq.\n  apply Lt.\n  apply Gt.\n  apply IHn; eauto.\nQed.\n\nFixpoint fin_subst {A n} (t : A) (x : Fin.t (S n)) (y : Fin.t (S n)) : A + Fin.t n :=\n  match n as n' return forall pf : n' = n, A + Fin.t n with\n    | O => fun _ => inl t\n    | S n' => fun pf =>\n                match x in Fin.t m return forall pf : m = S n,\n                                            A + Fin.t n with\n                  | Fin.F1 _ => fun pfx =>\n                                  match y in Fin.t m return forall pf : m = S n,\n                                                              A + Fin.t n with\n                                    | Fin.F1 _ => fun pfy => inl t\n                                    | Fin.FS m y => fun pfy => inr (eq_rect m Fin.t y _ (f_equal pred pfy))\n                                  end eq_refl\n                  | Fin.FS k x => fun pfx =>\n                                  match y in Fin.t m return forall pf : m = S n,\n                                                              A + Fin.t n with\n                                    | Fin.F1 _ => fun pfy => inr (eq_rect (S n') Fin.t Fin.F1 _ pf)\n                                    | Fin.FS m y => fun pfy =>\n                                                      match @fin_subst A n' t\n                                                                       (eq_rect k Fin.t x _ (eq_trans (f_equal pred pfx) (eq_sym pf)))\n                                                                       (eq_rect m Fin.t y _ (eq_trans (f_equal pred pfy) (eq_sym pf))) with\n                                                        | inl t => inl t\n                                                        | inr v => inr (eq_rect (S n') Fin.t (Fin.FS v) _ pf)\n                                                      end\n                                  end eq_refl\n                end eq_refl\n  end eq_refl.\n\nLemma fin_subst_eq : forall n A (t : A) (x : Fin.t (S n)), fin_subst t x x = inl t.\nProof with eauto.\n  induction n; intros; fin_dep_destruct x; simpl...\n  rewrite IHn...\nQed.\n\nFixpoint lift_fin_at {n} (i : Fin.t (S n)) (x : Fin.t n) : Fin.t (S n) :=\n  match i in Fin.t ni, x in Fin.t nx return forall pf : ni = S n,\n                                            forall pf' : nx = n,\n                                              Fin.t (S n)\n  with\n    | Fin.F1 _, x => fun _ _ => Fin.FS x\n    | Fin.FS _ i, Fin.F1 _ => fun _ _ => Fin.F1\n    | Fin.FS ni i, Fin.FS nx x =>\n      fun pf pf' =>\n        eq_rect (S (S nx)) Fin.t\n                (Fin.R 1 (lift_fin_at (eq_rect ni Fin.t i _ (eq_trans (f_equal pred pf) (eq_sym pf'))) x))\n                _ (f_equal S pf')\n  end eq_refl eq_refl.\n\nLemma lift_fin_at_inj : forall {n} (i : Fin.t (S n)) (x y : Fin.t n),\n                          lift_fin_at i x = lift_fin_at i y -> x = y.\nProof.\n  induction n; intros i x y; dependent destruction i; dependent destruction x; dependent destruction y; intros; inversion H; simpl_exist; eauto; f_equal; eauto.\nQed.\n\nHint Immediate lift_fin_at_inj.\n\nLemma fin_subst_neq : forall n A (t : A) (x y : Fin.t (S n)),\n                        x <> y -> exists v, fin_subst t x y = inr v /\\\n                                            lift_fin_at x v = y.\nProof with eauto.\n  induction n; dependent destruction x; dependent destruction y; intro;\n  try (exfalso; eauto; fail);\n  try (eapply Fin.case0; eauto; fail);\n  try (eexists; split; simpl; eauto; fail).\n  assert (x <> y); [intro; subst; apply H; auto|];\n  specialize (IHn _ t x y H0); destruct IHn; destruct_pairs;\n  eexists; simpl; rewrite H1; rewrite <- H2; split; eauto.\nQed.\n\nLemma eq_fin_subst : forall n A (t t' : A) (x y : Fin.t (S n)), fin_subst t x y = inl t' -> t = t'.\nProof with eauto.\n  dependent induction n; intros;\n  dependent destruction x; dependent destruction y;\n  try (inversion H; auto).\n  destruct (fin_subst t x y) eqn:H2; inversion H; inversion H1; subst...\nQed.\n\nLtac simpl_forall_list :=\n  repeat match goal with\n           | [ H : Forall _ ?l |- _ ] => is_list_constr l; inversion_clear H\n           | _ => idtac\n         end.\n\nModule Type TermDef.\n  Parameter symbol : Type.\n  Parameter eq_symbol_dec : forall (s s' : symbol), {s = s'} + {s <> s'}.\n  Hint Immediate eq_symbol_dec.\n  Parameter arity : symbol -> nat.\nEnd TermDef.\n\nModule Expr (T : TermDef).\n  Import T.\n  Export T.\n\n  Inductive term : nat -> Type :=\n  | t_var : forall {n}, Fin.t n -> term n\n  | t_term : forall {n} (s : symbol), Vector.t (term n) (arity s) -> term n\n  .\n  \n  Definition termRect :=\n      fun (P : forall n : nat, term n -> Type)\n          (f : forall (n : nat) (t : Fin.t n), P n (@t_var n t))\n          (f0 : forall (n : nat) (s : symbol) (t : Vector.t (term n) (arity s)),\n                  (forall i, P n (Vector.nth t i)) -> P n (t_term s t)) =>\n        fix F (n : nat) (t : term n) {struct t} : P n t :=\n    match t as t0 in (term n0) return (P n0 t0) with\n      | t_var n0 t0 => f n0 t0\n      | t_term n0 s t0 => f0 n0 s t0 (fun i => F n0 (Vector.nth t0 i))\n    end.\n\n  Theorem eq_term_dec : forall {n} (t t' : term n), {t = t'} + {t <> t'}.\n  Proof.\n    intro. induction t using termRect; intros;\n    destruct t'; try (right; intro; solve by inversion).\n    assert (H := eq_fin_dec t t0).\n    destruct H; subst.\n    left; auto.\n    right; intro; inversion H; simpl_exist; auto.\n    assert (H := eq_symbol_dec s s0).\n    destruct H; subst.\n    assert (H := eq_vector_dec_ind t t0 X).\n    destruct H; subst.\n    left; auto.\n    right; intro; inversion H; simpl_exist; auto.\n    right; intro; inversion H; simpl_exist; auto.\n  Qed.\n\n  Hint Immediate eq_term_dec.\n\n  Fixpoint lift_term {n} (t : term n) : term (S n) :=\n    match t with\n      | t_var _ j => t_var (Fin.R 1 j)\n      | t_term _ s ts => t_term s (Vector.map lift_term ts)\n    end.\n\n  Fixpoint lift_term_by {n} i (t : term n) : term (i + n) :=\n    match i with\n      | 0 => t\n      | S i => lift_term (lift_term_by i t)\n    end.\n\n  Theorem lift_term_inj : forall {n} (t t' : term n),\n                            lift_term t = lift_term t' -> t = t'.\n  Proof.\n    induction t using termRect; intros t' H0; destruct t';\n    simpl in H0; try (solve by inversion); inversion H0; simpl_exist; auto.    \n    apply vector_map_inj in H3; subst; auto.\n  Qed.\n\n  Hint Immediate lift_term_inj.\n\n  Inductive type : nat -> Type :=\n  | ty_term : forall {n : nat}, term n -> type n\n  | ty_arrow : forall {n : nat}, type n -> type n -> type n\n  | ty_forall : forall {n : nat}, type (S n) -> type n\n  | ty_exists : forall {n : nat}, type (S n) -> type n\n  | ty_bottom : forall {n : nat}, type n\n  | ty_copair : forall {n : nat}, type n -> type n -> type n\n  | ty_top : forall {n : nat}, type n\n  | ty_pair : forall {n : nat}, type n -> type n -> type n\n  .\n\n  Ltac lift_dec_eq :=\n    match goal with\n      | [ |- { ?a ?b = ?a ?b' } + { ?a ?b <> ?a ?b' } ] =>\n        let H := fresh \"H\" in\n        let H0 := fresh \"H\" in\n        assert (H : {b = b'} + {b <> b'});\n          [ auto\n          | destruct H;\n            [ left; subst; auto\n            | right; unfold not; intros H0; inversion H0; simpl_exist; auto\n            ]\n          ]\n      | [ |- { ?a ?b ?c = ?a ?b' ?c' } + { ?a ?b ?c <> ?a ?b' ?c' } ] =>\n        let H := fresh \"H\" in\n        let H0 := fresh \"H\" in\n        let H1 := fresh \"H\" in\n        assert (H : {b = b'} + {b <> b'});\n          [ auto\n          | assert (H0 : {c = c'} + {c <> c'});\n            [ auto\n            | destruct H;\n              [ destruct H0;\n                [ left; subst; auto\n                | right; unfold not; intros H1; inversion H1; simpl_exist; auto\n                ]\n              | right; unfold not; intros H1; inversion H1; simpl_exist; auto\n              ]\n            ]\n          ]\n      | [ |- { ?a ?b ?c ?d = ?a ?b' ?c' ?d' } + { ?a ?b ?c ?d <> ?a ?b' ?c' ?d' } ] =>\n        let H := fresh \"H\" in\n        let H0 := fresh \"H\" in\n        let H1 := fresh \"H\" in\n        let H2 := fresh \"H\" in\n        assert (H : {b = b'} + {b <> b'});\n          [ auto\n          | assert (H0 : {c = c'} + {c <> c'});\n            [ auto\n            | assert (H1 : {d = d'} + {d <> d'});\n              [ auto\n              | destruct H;\n                [ destruct H0;\n                  [ destruct H1;\n                    [ left; subst; auto\n                    | right; unfold not; intros H2; inversion H2; simpl_exist; auto\n                    ]\n                  | right; unfold not; intros H2; inversion H2; simpl_exist; auto\n                  ]\n                | right; unfold not; intros H2; inversion H2; simpl_exist; auto\n                ]\n              ]\n            ]\n          ]\n    end.\n\n  Theorem eq_type_dec : forall {n} (t t' : type n), {t = t'} + {t <> t'}.\n  Proof.\n    intro. induction t; destruct t';\n           try (right; intro; solve by inversion);\n           try (lift_dec_eq).\n  Qed.\n\n  Hint Immediate eq_type_dec.\n  \n  Fixpoint lift_type {n} (t : type n) : type (S n) :=\n  match t with\n    | ty_term _ t => ty_term (lift_term t)\n    | ty_arrow _ a b => ty_arrow (lift_type a) (lift_type b)\n    | ty_forall _ a => ty_forall (lift_type a)\n    | ty_exists _ a => ty_exists (lift_type a)\n    | ty_copair _ a b => ty_copair (lift_type a) (lift_type b)\n    | ty_bottom _ => ty_bottom\n    | ty_pair _ a b => ty_pair (lift_type a) (lift_type b)\n    | ty_top _ => ty_top\n  end.\n\n  Fixpoint lift_type_by {n} i (t : type n) : type (i + n) :=\n    match i with\n      | 0 => t\n      | S i => lift_type (lift_type_by i t)\n    end.\n\n  Theorem lift_type_inj : forall {n} (t t' : type n),\n                            lift_type t = lift_type t' -> t = t'.\n  Proof.\n    induction t; intros t' H; dependent destruction t'; inversion H; simpl_exist; f_equal; auto.\n  Qed.\n\n  Hint Immediate lift_type_inj.\n  \n  Fixpoint term_subst {n} (i : Fin.t (S n)) (t : term n) (u : term (S n)) : term n :=\n    match u as u' in term n' return forall pf : n' = S n,\n                                      term n\n    with\n      | t_var n' j => fun pf =>\n                       match fin_subst t i (eq_rect n' Fin.t j _ pf) with\n                         | inl t => t\n                         | inr v => t_var v\n                       end\n      | t_term n' s ts => fun pf => t_term s (Vector.map (term_subst i t)\n                                                         (eq_rect n' (fun i => Vector.t (term i) _) ts _ pf)\n                                             )\n    end eq_refl.\n\n  Fixpoint type_subst {n} (i : Fin.t (S n)) (t : term n) (u : type (S n)) : type n :=\n    match u as u' in type n' return forall pf : n' = S n,\n                                      type n\n    with\n      | ty_term n' a => fun pf => ty_term (term_subst i t (eq_rect n' term a _ pf))\n      | ty_arrow n' a b => fun pf => ty_arrow (type_subst i t (eq_rect n' type a _ pf)) (type_subst i t (eq_rect n' type b _ pf))\n      | ty_forall n' a => fun pf => ty_forall (type_subst (Fin.R 1 i) (lift_term t) (eq_rect (S n') type a _ (f_equal S pf)))\n      | ty_exists n' a => fun pf => ty_exists (type_subst (Fin.R 1 i) (lift_term t) (eq_rect (S n') type a _ (f_equal S pf)))\n      | ty_copair n' a b => fun pf => ty_copair (type_subst i t (eq_rect n' type a _ pf)) (type_subst i t (eq_rect n' type b _ pf))\n      | ty_bottom _ => fun pf => ty_bottom\n      | ty_pair n' a b => fun pf => ty_pair (type_subst i t (eq_rect n' type a _ pf)) (type_subst i t (eq_rect n' type b _ pf))\n      | ty_top _ => fun pf => ty_top\n    end eq_refl.\n\n    Inductive exp : nat -> nat -> Type :=\n    | e_var : forall {n m : nat}, Fin.t n -> exp n m\n    | e_app : forall {n m : nat}, exp n m -> exp n m -> exp n m\n    | e_forall : forall {n m : nat}, exp n (S m) -> exp n m\n    | e_exists : forall {n m : nat}, term m -> exp n m -> exp n m\n    | e_ecase : forall {n m : nat}, exp n m -> exp (S n) (S m) -> exp n m\n    | e_abs : forall {n m : nat}, exp (S n) m -> exp n m\n    | e_tapp : forall {n m : nat}, exp n m -> term m -> exp n m\n    | e_absurd : forall {n m}, exp n m -> exp n m\n    | e_copair1 : forall {n m}, exp n m -> exp n m\n    | e_copair2 : forall {n m}, exp n m -> exp n m\n    | e_case : forall {n m}, exp n m -> exp (S n) m -> exp (S n) m -> exp n m\n    | e_tt : forall {n m}, exp n m\n    | e_pair : forall {n m}, exp n m -> exp n m -> exp n m\n    | e_pair1 : forall {n m}, exp n m -> exp n m\n    | e_pair2 : forall {n m}, exp n m -> exp n m\n    .\n\n    Theorem eq_exp_dec : forall {n m} (e e' : exp n m), {e = e'} + {e <> e'}.\n    Proof.\n      intros n m. induction e; destruct e';\n                  try (right; intro; solve by inversion);\n                  try (lift_dec_eq).\n    Qed.\n    \n    Hint Immediate eq_exp_dec.\n  \n\n  Definition sub_exp {n m} (t : exp n m) : list (exp n m) :=\n  match t with\n    | e_var _ _ j => nil\n    | e_app _ _ a b => cons a (cons b nil)\n    | e_forall _ _ a => nil\n    | e_exists _ _ a b => nil\n    | e_ecase _ _ a b => nil\n    | e_abs _ _ a => nil\n    | e_tapp _ _ a b => nil\n    | e_absurd _ _ a => cons a nil\n    | e_copair1 _ _ a => cons a nil\n    | e_copair2 _ _ a => cons a nil\n    | e_case _ _ a b c => cons a nil\n    | e_tt _ _ => nil\n    | e_pair _ _ a b => cons a (cons b nil)\n    | e_pair1 _ _ a => cons a nil\n    | e_pair2 _ _ a => cons a nil\n  end.\n\n  Fixpoint lift_exp_at {n m} (i : Fin.t (S n)) (t : exp n m) : exp (S n) m :=\n    match t in exp n' m' return Fin.t (S n') -> exp (S n') m'\n    with\n    | e_var _ _ j => fun i => e_var (lift_fin_at i j)\n    | e_app _ _ a b => fun i => e_app (lift_exp_at i a) (lift_exp_at i b)\n    | e_forall _ _ a => fun i => e_forall (lift_exp_at i a)\n    | e_exists _ _ a b => fun i => e_exists a (lift_exp_at i b)\n    | e_ecase _ _ a b => fun i => e_ecase (lift_exp_at i a) (lift_exp_at (Fin.FS i) b)\n    | e_abs _ _ a => fun i => e_abs (lift_exp_at (Fin.FS i) a)\n    | e_tapp _ _ a b => fun i => e_tapp (lift_exp_at i a) b\n    | e_absurd _ _ a => fun i => e_absurd (lift_exp_at i a)\n    | e_copair1 _ _ a => fun i => e_copair1 (lift_exp_at i a)\n    | e_copair2 _ _ a => fun i => e_copair2 (lift_exp_at i a)\n    | e_case _ _ a b c => fun i => e_case (lift_exp_at i a) (lift_exp_at (Fin.FS i) b) (lift_exp_at (Fin.FS i) c)\n    | e_tt _ _ => fun i => e_tt\n    | e_pair _ _ a b => fun i => e_pair (lift_exp_at i a) (lift_exp_at i b)\n    | e_pair1 _ _ a => fun i => e_pair1 (lift_exp_at i a)\n    | e_pair2 _ _ a => fun i => e_pair2 (lift_exp_at i a)\n    end i.\n\n  Definition lift_exp_n {n m} := @lift_exp_at n m Fin.F1.\n  Hint Unfold lift_exp_n.\n  \n  Fixpoint lift_exp {n m} (t : exp n m) : exp n (S m) :=\n  match t with\n    | e_var _ _ j => e_var j\n    | e_app _ _ a b => e_app (lift_exp a) (lift_exp b)\n    | e_forall _ _ a => e_forall (lift_exp a)\n    | e_exists _ _ a b => e_exists (lift_term a) (lift_exp b)\n    | e_ecase _ _ a b => e_ecase (lift_exp a) (lift_exp b)\n    | e_abs _ _ a => e_abs (lift_exp a)\n    | e_tapp _ _ a b => e_tapp (lift_exp a) (lift_term b)\n    | e_absurd _ _ a => e_absurd (lift_exp a)\n    | e_copair1 _ _ a => e_copair1 (lift_exp a)\n    | e_copair2 _ _ a => e_copair2 (lift_exp a)\n    | e_case _ _ a b c => e_case (lift_exp a) (lift_exp b) (lift_exp c)\n    | e_tt _ _ => e_tt\n    | e_pair _ _ a b => e_pair (lift_exp a) (lift_exp b)\n    | e_pair1 _ _ a => e_pair1 (lift_exp a)\n    | e_pair2 _ _ a => e_pair2 (lift_exp a)\n  end.\n\n    Fixpoint exp_subst {n m} (i : Fin.t (S n)) (t : exp n m) (u : exp (S n) m) : exp n m :=\n      let eq_rect_exp {n m n' m'} (pf : n' = S n) (pf' : m' = m) x :=\n          eq_rect n' (fun i => exp i m) (eq_rect m' (fun i => exp n' i) x _ pf') _ pf\n      in\n      match u as u' in exp n' m' return forall pf : n' = S n,\n                                        forall pf' : m' = m,\n                                          exp n m\n      with\n        | e_var n' _ j => fun pf _ =>\n                            match fin_subst t i (eq_rect n' Fin.t j _ pf) with\n                              | inl t => t\n                              | inr v => e_var v\n                            end\n        | e_app _ _ a b => fun pf pf' => e_app (exp_subst i t (eq_rect_exp pf pf' a)) (exp_subst i t (eq_rect_exp pf pf' b))\n        | e_forall _ _ a => fun pf pf' => e_forall (exp_subst i (lift_exp t) (eq_rect_exp pf (f_equal S pf') a))\n        | e_exists _ m' a b => fun pf pf' => e_exists (eq_rect m' term a _ pf') (exp_subst i t (eq_rect_exp pf pf' b))\n        | e_ecase _ _ a b => fun pf pf' => e_ecase (exp_subst i t (eq_rect_exp pf pf' a)) (exp_subst (Fin.FS i) (lift_exp_n (lift_exp t)) (eq_rect_exp (f_equal S pf) (f_equal S pf') b))\n        | e_abs _ _ a => fun pf pf' => e_abs (exp_subst (Fin.FS i) (lift_exp_n t) (eq_rect_exp (f_equal S pf) pf' a))\n        | e_tapp _ _ a b => fun pf pf' => e_tapp (exp_subst i t (eq_rect_exp pf pf' a)) (eq_rect _ _ b _ pf')\n        | e_absurd _ _ a => fun pf pf' => e_absurd (exp_subst i t (eq_rect_exp pf pf' a))\n        | e_copair1 _ _ a => fun pf pf' => e_copair1 (exp_subst i t (eq_rect_exp pf pf' a))\n        | e_copair2 _ _ a => fun pf pf' => e_copair2 (exp_subst i t (eq_rect_exp pf pf' a))\n        | e_case _ _ a b c => fun pf pf' => e_case\n                                              (exp_subst i t (eq_rect_exp pf pf' a))\n                                              (exp_subst (Fin.FS i) (lift_exp_n t) (eq_rect_exp (f_equal S pf) pf' b))\n                                              (exp_subst (Fin.FS i) (lift_exp_n t) (eq_rect_exp (f_equal S pf) pf' c))\n        | e_tt _ _ => fun _ _ => e_tt\n        | e_pair _ _ a b => fun pf pf' => e_pair (exp_subst i t (eq_rect_exp pf pf' a)) (exp_subst i t (eq_rect_exp pf pf' b))\n        | e_pair1 _ _ a => fun pf pf' => e_pair1 (exp_subst i t (eq_rect_exp pf pf' a))\n        | e_pair2 _ _ a => fun pf pf' => e_pair2 (exp_subst i t (eq_rect_exp pf pf' a))\n      end eq_refl eq_refl.\n\n    Theorem exp_subst_eq : forall {n m} i (u : exp n m),\n                             exp_subst i u (e_var i) = u.\n    Proof.\n      intros. simpl. rewrite fin_subst_eq. auto.\n    Qed.\n\n    Reserved Notation \"a '===>' b\" (at level 60).\n\n    Fixpoint exp_subst_term {n m} (i : Fin.t (S m)) (t : term m) (u : exp n (S m)) : exp n m :=\n      let eq_rect_exp {n m n' m'} (pf : n' = n) (pf' : m' = S m) (x : exp n' m') :=\n          eq_rect n' (fun i => exp i (S m)) (eq_rect m' (fun i => exp n' i) x _ pf') _ pf\n      in\n      match u as u' in exp n' m' return forall pf : n' = n,\n                                        forall pf' : m' = S m,\n                                          exp n m\n      with\n        | e_var n' _ j => fun pf pf' => eq_rect n' (fun i => exp i m) (e_var j) _ pf\n        | e_app _ _ a b => fun pf pf' => e_app (exp_subst_term i t (eq_rect_exp pf pf' a)) (exp_subst_term i t (eq_rect_exp pf pf' b))\n        | e_forall _ _ a => fun pf pf' => e_forall (exp_subst_term (Fin.FS i) (lift_term t) (eq_rect_exp pf (f_equal S pf') a))\n        | e_exists _ m' a b => fun pf pf' => e_exists (term_subst i t (eq_rect m' term a _ pf')) (exp_subst_term i t (eq_rect_exp pf pf' b))\n        | e_ecase _ _ a b => fun pf pf' => e_ecase (exp_subst_term i t (eq_rect_exp pf pf' a)) (exp_subst_term (Fin.FS i) (lift_term t) (eq_rect_exp (f_equal S pf) (f_equal S pf') b))\n        | e_abs _ _ a => fun pf pf' => e_abs (exp_subst_term i t (eq_rect_exp (f_equal S pf) pf' a))\n        | e_tapp _ m' a b => fun pf pf' => e_tapp (exp_subst_term i t (eq_rect_exp pf pf' a)) (term_subst i t (eq_rect m' term b _ pf'))\n        | e_absurd _ _ a => fun pf pf' => e_absurd (exp_subst_term i t (eq_rect_exp pf pf' a))\n        | e_copair1 _ _ a => fun pf pf' => e_copair1 (exp_subst_term i t (eq_rect_exp pf pf' a))\n        | e_copair2 _ _ a => fun pf pf' => e_copair2 (exp_subst_term i t (eq_rect_exp pf pf' a))\n        | e_case _ _ a b c => fun pf pf' => e_case\n                                              (exp_subst_term i t (eq_rect_exp pf pf' a))\n                                              (exp_subst_term i t (eq_rect_exp (f_equal S pf) pf' b))\n                                              (exp_subst_term i t (eq_rect_exp (f_equal S pf) pf' c))\n        | e_tt _ _ => fun _ _ => e_tt\n        | e_pair _ _ a b => fun pf pf' => e_pair (exp_subst_term i t (eq_rect_exp pf pf' a)) (exp_subst_term i t (eq_rect_exp pf pf' b))\n        | e_pair1 _ _ a => fun pf pf' => e_pair1 (exp_subst_term i t (eq_rect_exp pf pf' a))\n        | e_pair2 _ _ a => fun pf pf' => e_pair2 (exp_subst_term i t (eq_rect_exp pf pf' a))\n      end eq_refl eq_refl.\n    \n    Reserved Notation \"a '===>' b\" (at level 60).\n\n    Inductive reduction : forall {n m}, exp n m -> exp n m -> Prop :=\n    | reduction_beta : forall n m (a : exp (S n) m) b, e_app (e_abs a) b ===> exp_subst Fin.F1 b a\n    | reduction_forall : forall n m (a : exp n (S m)) (b : term m), reduction (e_tapp (e_forall a) b) (exp_subst_term Fin.F1 b a)\n    | reduction_absurd : forall n m (a : exp n m) b, e_app (e_absurd a) b ===> e_absurd a\n    | reduction_ecase : forall n m t (a : exp n m) b, e_ecase (e_exists t a) b ===> exp_subst Fin.F1 a (exp_subst_term Fin.F1 t b)\n    | reduction_case1 : forall n m (a : exp n m) u v, e_case (e_copair1 a) u v ===> exp_subst Fin.F1 a u\n    | reduction_case2 : forall n m (a : exp n m) u v, e_case (e_copair2 a) u v ===> exp_subst Fin.F1 a v\n    | reduction_pair1 : forall n m (a : exp n m) b, e_pair1 (e_pair a b) ===> a\n    | reduction_pair2 : forall n m (a : exp n m) b, e_pair2 (e_pair a b) ===> b\n    | reduction_context_app_1 : forall n m (a : exp n m) b a', a ===> a' -> e_app a b ===> e_app a' b\n    | reduction_context_app_2 : forall n m (b : exp n m) a b', b ===> b' -> e_app a b ===> e_app a b'\n    | reduction_context_abs : forall n m (a : exp (S n) m) a', a ===> a' -> e_abs a ===> e_abs a'\n    | reduction_context_forall : forall n m (a : exp n (S m)) a', a ===> a' -> e_forall a ===> e_forall a'\n    | reduction_context_exists : forall n m (a : exp n m) a' t, a ===> a' -> e_exists t a ===> e_exists t a'\n    | reduction_context_ecase_1 : forall n m (a : exp n m) b a', a ===> a' -> e_ecase a b ===> e_ecase a' b\n    | reduction_context_ecase_2 : forall n m (a : exp n m) b b', b ===> b' -> e_ecase a b ===> e_ecase a b'\n    | reduction_context_tapp : forall n m (a : exp n m) a' t, a ===> a' -> e_tapp a t ===> e_tapp a' t\n    | reduction_context_absurd : forall n m (a : exp n m) a', a ===> a' -> e_absurd a ===> e_absurd a'\n    | reduction_context_case_1 : forall n m (a : exp n m) b c a', a ===> a' -> e_case a b c ===> e_case a' b c\n    | reduction_context_case_2 : forall n m (a : exp n m) b c b', b ===> b' -> e_case a b c ===> e_case a b' c\n    | reduction_context_case_3 : forall n m (a : exp n m) b c c', c ===> c' -> e_case a b c ===> e_case a b c'\n    | reduction_context_copair1 : forall n m (a : exp n m) a', a ===> a' -> e_copair1 a ===> e_copair1 a'\n    | reduction_context_copair2 : forall n m (a : exp n m) a', a ===> a' -> e_copair2 a ===> e_copair2 a'\n    | reduction_context_pair_1 : forall n m (a : exp n m) b a', a ===> a' -> e_pair a b ===> e_pair a' b\n    | reduction_context_pair_2 : forall n m (a : exp n m) b b', b ===> b' -> e_pair a b ===> e_pair a b'\n    | reduction_context_pair1 : forall n m (a : exp n m) a', a ===> a' -> e_pair1 a ===> e_pair1 a'\n    | reduction_context_pair2 : forall n m (a : exp n m) a', a ===> a' -> e_pair2 a ===> e_pair2 a'\n    (* | reduction_trans : forall n m (a : exp n m) b c, a ===> b -> b ===> c -> a ===> c *)\n    where \"a '===>' b\" := (@reduction _ _ a b)\n    .\n\n    Definition nf {n m} (e : exp n m) := forall e', e ===> e' -> False.\n\n    Theorem nf_sub_exp : forall {n m} (e : exp n m), nf e -> Forall nf (sub_exp e).\n    Proof.\n      unfold nf; intros.\n      destruct e; simpl; repeat constructor; intros e' He;\n      eapply H; try (constructor; eauto; fail).\n      eapply reduction_context_app_2; eauto.\n      eapply reduction_context_pair_2; eauto.\n    Qed.\n    \n    Inductive nfview : forall {n m}, exp n m -> Prop :=\n    | nfv_unknown : forall n m (e : exp n m) (ns : list (exp n m)),\n                      Forall nfview ns -> nfview_unknown e ->\n                      nfview (fold_right (fun a b => e_app b a) e ns)\n    | nfv_abs : forall n m (e : exp (S n) m),\n                  nfview e -> nfview (e_abs e)\n    | nfv_absurd : forall n m (e : exp n m),\n                  nfview e -> nfview (e_absurd e)\n    with nfview_unknown : forall {n m}, exp n m -> Prop :=\n         | nfv_var : forall n m (i : Fin.t n), @nfview_unknown _ m (e_var i)\n         | nfv_forall : forall n m (e : exp n (S m)),\n                          nfview e -> nfview_unknown (e_forall e)\n         | nfv_exists : forall n m t (e : exp n m),\n                          nfview e -> nfview_unknown (e_exists t e)\n         | nfv_ecase : forall n m (a : exp n m) (b : exp (S n) (S m)),\n                         (forall x y, a = e_exists x y -> False) ->\n                         nfview a -> nfview b -> nfview_unknown (e_ecase a b)\n         | nfv_tapp : forall n m (a : exp n m) t,\n                        (forall x, a = e_forall x -> False) ->\n                        nfview a -> nfview_unknown (e_tapp a t)\n         | nfv_copair1 : forall n m (a : exp n m),\n                           nfview a -> nfview_unknown (e_copair1 a)\n         | nfv_copair2 : forall n m (a : exp n m),\n                           nfview a -> nfview_unknown (e_copair2 a)\n         | nfv_case : forall n m (a : exp n m) b c,\n                        (forall x, a = e_copair1 x -> False) ->\n                        (forall x, a = e_copair2 x -> False) ->\n                        nfview a -> nfview b -> nfview c -> nfview_unknown (e_case a b c)\n         | nfv_tt : forall n m, @nfview_unknown n m e_tt\n         | nfv_pair : forall n m (a : exp n m) b,\n                        nfview a -> nfview b -> nfview_unknown (e_pair a b)\n         | nfv_pair1 : forall n m (a : exp n m),\n                         (forall x y, a = e_pair x y -> False) ->\n                         nfview a -> nfview_unknown (e_pair1 a)\n         | nfv_pair2 : forall n m (a : exp n m),\n                         (forall x y, a = e_pair x y -> False) ->\n                         nfview a -> nfview_unknown (e_pair2 a)\n    .\n    \n    Ltac nf_nfview_helper p := \n      match goal with\n        | [ IH : nf ?e -> nfview ?e |- nfview ?e ] =>\n          let e := fresh \"e\" in\n          let H := fresh \"H\" in\n          apply IH; intros e H; exfalso; eapply p; constructor (solve [eauto])\n      end.\n\n    Theorem nf_nfview : forall n m (e : exp n m), nf e -> nfview e.\n    Proof with eauto; try (constructor; eauto; fail).\n      intros n m e. set (e0 := e).\n      dependent induction e; intro p;\n      assert (A := nf_sub_exp e0 p); subst e0; simpl in A; simpl_forall_list;\n      repeat match goal with\n                 [ A : nf ?e -> nfview ?e, B : nf ?e |- _ ] => apply A in B\n             end;\n      try (apply nfv_unknown with (ns:=nil); eauto; constructor; eauto;\n           try (nf_nfview_helper p; fail);\n           try (intros; subst; eapply p; constructor);\n           fail);\n      try (constructor (solve [eauto; nf_nfview_helper p]); fail).\n      + destruct H; try (exfalso; eapply p; constructor; fail).\n        apply nfv_unknown with (e:=e) (ns:=cons e2 ns)...\n    Qed.\n\n    Theorem nfview_nf : forall n m (e : exp n m), (nfview e -> nf e) /\\ (nfview_unknown e -> nf e).\n    Proof with eauto.\n      intros n m e; set (e0 := e); dependent induction e;\n      (assert (S2 : nfview_unknown e0 -> nf e0);\n      [ subst e0; intro;\n        destruct_pairs;\n        try (intros e' H'; inversion H'; fail);\n        inversion H; simpl_exist; subst; eauto\n      | split; [|exact S2]; subst e0; intro;\n        destruct_pairs;\n        inversion H; simpl_exist; subst;\n        try (match goal with\n                 [ H : fold_right _ _ _ = _ |- _ ] => destruct ns; [ simpl in H; subst; auto\n                                                                   | solve by inversion\n                                                                   ]\n             end; fail)\n      ]); try (intros e' H'; inversion H'; simpl_exist; subst; eauto;\n               match goal with \n                 | [ H : nfview ?e -> nf ?e, _ : ?e ===> _ |- _ ] => unfold nf in H; eapply H; eauto\n               end; fail\n              ).\n      + destruct ns; simpl in H4; subst; [ solve by inversion |].\n        destruct ns; simpl in H4; inversion H4; simpl_exist; subst.\n        * simpl_forall_list.\n          intros e' H'; inversion H'; simpl_exist; subst.\n          inversion H8.\n          inversion H8.\n          unfold nf in H3; eapply H3; eauto.\n          unfold nf in H0; eapply H0; eauto.\n        * simpl_forall_list.\n          intros e' H'; inversion H'; simpl_exist; subst.\n          unfold nf in H2; eapply H2... apply nfv_unknown with (e:=e) (ns:=cons e3 ns)...\n          unfold nf in H0; eapply H0; eauto.\n    Qed.\n\n    Theorem nfview_app : forall {n m} (a b : exp n m), nfview (e_app a b) -> nfview a.\n    Proof.\n      intros.\n      apply nfview_nf in H.\n      apply nf_nfview. intro. intros. eapply H. eapply reduction_context_app_1. eauto.\n    Qed.\n      \nEnd Expr.\n\nModule Type TermCongruence (T : TermDef).\n  Module E := Expr(T).\n  Import E.\n  Export E.\n  Parameter cong : forall {n}, type n -> type n -> Prop.\nEnd TermCongruence.\n\nModule NJ (T : TermDef) (TC : TermCongruence(T)).\n  Import TC.\n  Export TC.\n  Reserved Notation \"x '≡' y\" (at level 40).\n\n  Inductive type_equiv : forall {n : nat}, relation (type n) :=\n  | te_context_var : forall {n} {i}, @ty_term n (t_var i) ≡ ty_term (t_var i)\n  | te_context_term : forall {n} {s : symbol} xs ys,\n                        (forall i, @ty_term n (Vector.nth xs i) ≡ ty_term (Vector.nth ys i)) ->\n                        ty_term (t_term s xs) ≡ ty_term (t_term s ys)\n  | te_context_arrow : forall {n} {x y z t : type n},\n                         x ≡ y ->\n                         z ≡ t ->\n                         ty_arrow x z ≡ ty_arrow y t\n  | te_context_forall : forall {n} {x y : type (S n)},\n                          x ≡ y ->\n                          ty_forall x ≡ ty_forall y\n  | te_context_exists : forall {n} {x y : type (S n)},\n                          x ≡ y ->\n                          ty_exists x ≡ ty_exists y\n  | te_context_bottom : forall {n}, @ty_bottom n ≡ ty_bottom\n  | te_context_copair : forall {n} {x y z t : type n},\n                         x ≡ y ->\n                         z ≡ t ->\n                         ty_copair x z ≡ ty_copair y t\n  | te_context_top : forall {n}, @ty_top n ≡ ty_top\n  | te_context_pair : forall {n} {x y z t : type n},\n                         x ≡ y ->\n                         z ≡ t ->\n                         ty_pair x z ≡ ty_pair y t\n  | te_sym : forall {n} {x y : type n}, x ≡ y -> y ≡ x\n  | te_trans : forall {n} {x y z : type n}, x ≡ y -> y ≡ z -> x ≡ z\n  | te_term : forall {n} {x y : type n},\n                cong x y -> x ≡ y\n  | te_subst : forall {n i t} {x y : type (S n)},\n                      x ≡ y -> type_subst i t x ≡ type_subst i t y\n  | te_lift : forall {n} {x y : type n},\n                x ≡ y -> lift_type x ≡ lift_type y\n  where \"x '≡' y\" := (type_equiv x y).\n  \n  Theorem te_refl : forall {n : nat} (x : type n), x ≡ x.\n  Proof.\n    assert (forall n (t : term n), ty_term t ≡ ty_term t).\n    induction t using termRect; constructor; eauto.\n    induction x; try (constructor; eauto; fail).\n  Qed.\n  \n  Definition liftΓ {n m} (Γ : Vector.t (type m) n) : Vector.t (type (S m)) n := Vector.map lift_type Γ.\n\n  Theorem liftΓ_inj : forall {n m} (Γ1 Γ2 : Vector.t (type m) n),\n                        liftΓ Γ1 = liftΓ Γ2 -> Γ1 = Γ2.\n  Proof.\n    induction Γ1; intros; dependent destruction Γ2; auto.\n    simpl in H. inversion H. f_equal; simpl_exist; auto.\n  Qed.\n\n  Hint Immediate liftΓ_inj.\n  \n  Reserved Notation \"Γ '⊢' t '∈' ty\" (at level 40).\n  \n  Inductive has_type : forall {n m : nat}, Vector.t (type m) n -> exp n m -> type m -> Prop :=\n  | p_var : forall {n m} {Γ : Vector.t (type m) n} i ty,\n              ty ≡ Vector.nth Γ i -> Γ ⊢ e_var i ∈ ty\n  | p_app : forall {n m} {Γ : Vector.t (type m) n} {u v s t ty},\n            Γ ⊢ u ∈ ty_arrow s t ->\n            Γ ⊢ v ∈ s ->\n            ty ≡ t -> Γ ⊢ e_app u v ∈ ty\n  | p_abs : forall {n m} {Γ : Vector.t (type m) n} {e t u ty},\n              (t :: Γ) ⊢ e ∈ u ->\n              ty ≡ ty_arrow t u -> Γ ⊢ e_abs e ∈ ty\n  | p_forall : forall {n m} {Γ : Vector.t (type m) n} {e u ty},\n                 (liftΓ Γ) ⊢ e ∈ u ->\n                 ty ≡ ty_forall u -> Γ ⊢ e_forall e ∈ ty\n  | p_exists : forall {n m} {Γ : Vector.t (type m) n} {t u p ty},\n                 Γ ⊢ u ∈ type_subst Fin.F1 t p ->\n                 ty ≡ ty_exists p -> Γ ⊢ e_exists t u ∈ ty\n  | p_ecase : forall {n m} {Γ : Vector.t (type m) n} {u v p q ty},\n                Γ ⊢ u ∈ ty_exists p ->\n                (p :: liftΓ Γ) ⊢ v ∈ lift_type q ->\n                ty ≡ q -> Γ ⊢ e_ecase u v ∈ ty\n  | p_copair1 : forall {n m} {Γ : Vector.t (type m) n} {u s t ty},\n                  Γ ⊢ u ∈ s ->\n                  ty ≡ ty_copair s t -> Γ ⊢ e_copair1 u ∈ ty\n  | p_copair2 : forall {n m} {Γ : Vector.t (type m) n} {v s t ty},\n                  Γ ⊢ v ∈ t ->\n                  ty ≡ ty_copair s t -> Γ ⊢ e_copair2 v ∈ ty\n  | p_case : forall {n m} {Γ : Vector.t (type m) n} {a b u v1 v2 t ty},\n               Γ ⊢ u ∈ ty_copair a b ->\n               (a :: Γ) ⊢ v1 ∈ t ->\n               (b :: Γ) ⊢ v2 ∈ t ->\n               ty ≡ t -> Γ ⊢ e_case u v1 v2 ∈ ty\n  | p_pair : forall {n m} {Γ : Vector.t (type m) n} {u v s t ty},\n               Γ ⊢ u ∈ s ->\n               Γ ⊢ v ∈ t ->\n               ty ≡ ty_pair s t -> Γ ⊢ e_pair u v ∈ ty\n  | p_pair1 : forall {n m} {Γ : Vector.t (type m) n} {u s t ty},\n                  Γ ⊢ u ∈ ty_pair s t ->\n                  ty ≡ s -> Γ ⊢ e_pair1 u ∈ ty\n  | p_pair2 : forall {n m} {Γ : Vector.t (type m) n} {u s t ty},\n                  Γ ⊢ u ∈ ty_pair s t ->\n                  ty ≡ t -> Γ ⊢ e_pair2 u ∈ ty\n  | p_absurd : forall {n m} {Γ : Vector.t (type m) n} {e t ty},\n                 Γ ⊢ e ∈ ty_bottom ->\n                 ty ≡ t -> Γ ⊢ e_absurd e ∈ ty\n  | p_tt : forall {n m} {Γ : Vector.t (type m) n} {ty},\n             ty ≡ ty_top -> Γ ⊢ e_tt ∈ ty\n               where \"Γ '⊢' t '∈' ty\" := (has_type Γ t ty).\n\n  Theorem p_equiv : forall {n m} Γ (e : exp n m) ty ty',\n                      Γ ⊢ e ∈ ty -> ty ≡ ty' -> Γ ⊢ e ∈ ty'.\n  Proof.\n    intros. inversion H; simpl_exist;\n    econstructor (solve [eauto; eapply te_trans; eauto; eapply te_sym; eauto]).\n  Qed.\n    \n  Definition is_typable {n m : nat} (e : exp n m) := sigma Γ ty, Γ ⊢ e ∈ ty.\n  Definition is_provable {n : nat} (ty : type n) := sigma {e : exp O n}, [] ⊢ e ∈ ty.\n  Definition is_provable_nf {n : nat} (ty : type n) := (sigma {e : exp O n}, nf e * ([] ⊢ e ∈ ty))%type.\n  \nEnd NJ.\n\nModule Ex1Term <: TermDef.\n  Inductive symbol_ :=\n  | s_zero\n  | s_succ\n  | s_plus\n  | s_equal\n  .\n\n  Definition symbol := symbol_.\n\n  Theorem eq_symbol_dec : forall (s s' : symbol), {s = s'} + {s <> s'}.\n  Proof.\n    decide equality.\n  Qed.\n    \n  Fixpoint arity s :=\n    match s with\n      | s_zero => 0\n      | s_succ => 1\n      | s_plus => 2\n      | s_equal => 2\n    end.\nEnd Ex1Term.\n\nModule Ex1Congruence <: TermCongruence(Ex1Term).\n  Module E := Expr(Ex1Term).\n  Import E.\n  Export E.\n  \n  Inductive cong_ {n} : relation (type n) :=\n  | c_0_l : forall {x}, cong_ (ty_term (t_term s_plus [t_term s_zero []; x])) (ty_term x)\n  | c_S_l : forall {x y}, cong_ (ty_term (t_term s_plus [t_term s_succ [x]; y])) (ty_term (t_term s_succ [t_term s_plus [x;  y]]))\n  | c_plus_sym : forall {x y}, cong_ (ty_term (t_term s_plus [x; y])) (ty_term (t_term s_plus [y; x]))\n  | c_equal_sym : forall {x y}, cong_ (ty_term (t_term s_equal [x; y])) (ty_term (t_term s_equal [y; x]))\n  | c_refl : forall {x}, cong_ (ty_term (t_term s_equal [x; x])) ty_top\n  | c_neq_0 : forall {x}, cong_ (ty_term (t_term s_equal [t_term s_succ [x]; t_term s_zero []])) ty_bottom\n  | c_S_inj : forall {x y}, cong_ (ty_term (t_term s_equal [t_term s_succ [x]; t_term s_succ [y]]))\n                                  (ty_term (t_term s_equal [x; y]))\n  .\n  Definition cong {n} := @cong_ n.\nEnd Ex1Congruence.\n\nModule Ex1NJ := NJ(Ex1Term)(Ex1Congruence).\n\nModule Q1.\n  Import Ex1NJ.\n\n  Fixpoint t_of_nat {m} n : term m :=\n    match n with\n      | 0 => t_term s_zero []\n      | S n => t_term s_succ [t_of_nat n]\n    end.\n\n  (* TODO : generate tactic by reflection from cong ? *)\n  (* TODO : generalize eapply te_context_term ? *)\n  Ltac simpl_equiv :=\n  autounfold;\n  let rec simpl_equiv' :=\n  match goal with\n    | [ |- ?x ≡ ?x ] => eapply te_refl\n    | [ |- ty_term (t_term s_succ [?x]) ≡ _ ] =>\n        let ty := type of x in\n        let x' := fresh \"x\" in\n        evar (x':ty); apply te_context_term with (ys:=[x']);\n        [subst x'; simpl; finite; simpl; simpl_equiv]\n    | [ |- ty_term (t_term s_plus [t_term s_zero []; _]) ≡ _ ] =>\n      eapply te_trans; [eapply te_term; [eapply c_0_l] | simpl_equiv ]\n    | [ |- ty_term (t_term s_plus [t_term s_succ [_]; _]) ≡ _ ] =>\n      eapply te_trans; [eapply te_term; [eapply c_S_l] | simpl_equiv ]\n    | [ |- ty_term (t_term s_equal [?x; ?y]) ≡ _ ] => eapply te_trans;[\n          let ty := type of x in\n          let x' := fresh \"x\" in\n          let y' := fresh \"y\" in\n          evar (x':ty); evar (y':ty); apply te_context_term with (ys:=[x'; y']);\n          [subst x'; subst y'; simpl; finite; [simpl; simpl_equiv | simpl; simpl_equiv]]\n        | match goal with\n            | [ |- ty_term (t_term s_equal [t_term s_succ _; t_term s_succ _]) ≡ _ ] =>\n              eapply te_trans; [ eapply te_term; [eapply c_S_inj] | simpl_equiv ]\n            | [ |- ty_term (t_term s_equal [?x; ?x]) ≡ _ ] =>\n              eapply te_trans; [ eapply te_term; [eapply c_refl] | simpl_equiv ]\n            | [ |- ty_term (t_term s_equal [t_term s_succ [_]; t_term s_zero []]) ≡ _ ] =>\n              eapply te_trans; [ eapply te_term; [eapply c_neq_0] | simpl_equiv ]\n            | _ => idtac\n          end\n        ]\n    | [ |- ty_arrow _ _ ≡ ty_arrow _ _ ] => eapply te_context_arrow; [ simpl_equiv | simpl_equiv ]\n    | [ |- ty_forall _ ≡ ty_forall _ ] => eapply te_context_forall; [ simpl_equiv ]\n    | _ => eapply te_refl\n    | _ => idtac\n  end in simpl_equiv' || (eapply te_sym; simpl_equiv').\n  \n  Theorem Q1a : is_provable (@ty_term 0 (t_term s_equal [t_term s_plus [t_of_nat 2; t_of_nat 3]; t_of_nat 5])).\n  Proof with eauto.\n    eexists e_tt.\n    constructor.\n    simpl_equiv.\n  Qed.\n  \n  Theorem Q1b : is_provable (@ty_forall 0 (ty_term (t_term s_equal [t_term s_plus [t_of_nat 2; t_var Fin.F1]; t_term s_plus [t_of_nat 1; t_term s_plus [t_of_nat 1; t_var Fin.F1]]]))).\n  Proof with eauto.\n    eexists (e_forall e_tt).\n    repeat (simpl_equiv || econstructor).\n  Qed.\n  \n  Theorem Q1c : is_provable (@ty_arrow 0 (ty_term (t_term s_equal [t_term s_plus [t_of_nat 1; t_of_nat 1]; t_term s_zero []])) (ty_term (t_term s_equal [t_term s_plus [t_of_nat 16; t_of_nat 64]; t_of_nat 42]))).\n  Proof with eauto.\n    eexists.\n    eapply p_abs; [eapply p_absurd;[apply p_var with (i:=Fin.F1)|]|].\n    simpl_equiv. simpl_equiv.\n    eapply te_context_arrow. simpl_equiv. eapply te_refl.\n  Qed.\n  \n  Theorem Q1d : is_provable (@ty_forall 0 (ty_arrow (ty_term (t_term s_equal [t_var Fin.F1; t_of_nat 2])) (ty_term (t_term s_equal [t_term s_plus [t_of_nat 1; t_var Fin.F1]; t_of_nat 3])))).\n  Proof with eauto.\n    eexists.\n    eapply p_forall;[eapply p_abs;[apply p_var with (i:=Fin.F1)|]|];\n    repeat simpl_equiv.\n  Qed.\n\nEnd Q1.\n\nModule Ex2Term <: TermDef.\n  Inductive symbol_ :=\n  | s_zero\n  | s_succ\n  | s_plus\n  | s_equal\n  | s_n\n  .\n  Definition symbol := symbol_.\n  Theorem eq_symbol_dec : forall (s s' : symbol), {s=s'}+{s<>s'}.\n  Proof. decide equality. Qed.\n  Fixpoint arity s :=\n    match s with\n      | s_zero => 0\n      | s_succ => 1\n      | s_plus => 2\n      | s_equal => 2\n      | s_n => 1\n    end.\nEnd Ex2Term.\n\nModule Ex2Congruence <: TermCongruence(Ex2Term).\n  Module E := Expr(Ex2Term).\n  Import E.\n  Export E.\n  \n  Inductive cong_ {n} : relation (type n) :=\n  | c_0_l : forall {x}, cong_ (ty_term (t_term s_plus [t_term s_zero []; x])) (ty_term x)\n  | c_S_l : forall {x y}, cong_ (ty_term (t_term s_plus [t_term s_succ [x]; y])) (ty_term (t_term s_succ [t_term s_plus [x;  y]]))\n  | c_plus_sym : forall {x y}, cong_ (ty_term (t_term s_plus [x; y])) (ty_term (t_term s_plus [y; x]))\n  | c_equal_sym : forall {x y}, cong_ (ty_term (t_term s_equal [x; y])) (ty_term (t_term s_equal [y; x]))\n  | c_refl : forall {x}, cong_ (ty_term (t_term s_equal [x; x])) ty_top\n  | c_neq_0 : forall {x}, cong_ (ty_term (t_term s_equal [t_term s_succ [x]; t_term s_zero []])) ty_bottom\n  | c_S_inj : forall {x y}, cong_ (ty_term (t_term s_equal [t_term s_succ [x]; t_term s_succ [y]]))\n                                  (ty_term (t_term s_equal [x; y]))\n  | c_n : forall {x},\n            cong_ (ty_term (t_term s_n [x]))\n                  (ty_copair\n                     (ty_term (t_term s_equal [x; t_term s_zero []]))\n                     (ty_exists (ty_pair\n                                   (ty_term (t_term s_equal [lift_term x; t_term s_succ [t_var Fin.F1]]))\n                                   (ty_term (t_term s_n [t_var Fin.F1]))\n                                )\n                     )\n                  )\n  .\n  \n  Definition cong {n} := @cong_ n.\nEnd Ex2Congruence.\n\nModule Ex2NJ := NJ(Ex2Term)(Ex2Congruence).\n\nModule Q2.\n  Import Ex2NJ.\n\n  Theorem Q2 : is_provable (@ty_forall 0 (ty_pair\n                                            (ty_arrow\n                                               (ty_term (t_term s_n [t_var Fin.F1]))\n                                               (ty_term (t_term s_n [t_term s_succ [t_var Fin.F1]]))\n                                            )\n                                            (ty_arrow\n                                               (ty_term (t_term s_n [t_term s_succ [t_var Fin.F1]]))\n                                               (ty_term (t_term s_n [t_var Fin.F1]))\n                                            )\n                                         )\n                           ).\n  Proof.\n    (* eexists. do 3 constructor; simpl. *)\n    (* + eapply p_equiv; [ eapply te_sym; eapply te_term; eapply c_n *)\n    (*                   | eapply p_copair2; eapply p_exists; eapply p_pair; simpl ]. *)\n    (*   eapply p_equiv; [ eapply te_sym; eapply te_term; eapply c_refl | eapply p_tt ]. *)\n    (*   eapply p_equiv; [ | eapply p_var with (i:=Fin.F1) ]. *)\n    (*   simpl; eapply te_refl. *)\n    (* + eapply p_case; [ eapply p_equiv; [| eapply p_var with (i:=Fin.F1) ] *)\n    (*                  |  *)\n    (*                  | eapply p_pair2; eapply p_ecase; [|] *)\n    (*                  ]; simpl. *)\n    (*   eapply te_term; eapply c_n. *)\n    (*   eapply p_absurd; eapply p_equiv; [| eapply p_var with (i:=Fin.F1) ]. simpl; eapply te_term; eapply c_neq_0. *)\n    (*   simpl. eapply p_equiv; [|eapply p_var with (i:=Fin.F1)]. simpl. eapply te_refl. *)\n    (*   simpl. eapply p_equiv; [|eapply p_var with (i:=Fin.F1)]. simpl. *)\n  Admitted.\n\nEnd Q2.\n\nModule Ex3Term <: TermDef.\n  Inductive symbol_ :=\n  | s_p\n  .\n  Definition symbol := symbol_.\n  Theorem eq_symbol_dec : forall (s s' : symbol), {s=s'}+{s<>s'}.\n  Proof. decide equality. Qed.\n  Fixpoint arity s :=\n    match s with\n      | s_p => 0\n    end.\nEnd Ex3Term.\n\nModule Ex3Congruence <: TermCongruence(Ex3Term).\n  Module E := Expr(Ex3Term).\n  Import E.\n  Export E.\n  \n  Inductive cong_ {n} : relation (type n) :=\n  | c_p : cong_ (ty_term (t_term s_p []))\n                (ty_arrow (ty_term (t_term s_p [])) ty_bottom)\n  .\n  \n  Definition cong {n} := @cong_ n.\nEnd Ex3Congruence.\n\nModule Ex3NJ := NJ(Ex3Term)(Ex3Congruence).\n\nModule Q3.\n  Import Ex3NJ.\n  \n  Theorem Q3 : @is_provable 0 ty_bottom.\n  Proof.\n    eexists.\n    eapply p_app; try eapply p_abs; try eapply p_app; try eapply p_var with (i:=Fin.F1);\n    simpl; try eapply te_refl.\n    eapply te_context_arrow; try apply te_refl.\n    eapply te_term. eapply c_p.\n    eapply te_term. eapply c_p.\n  Qed.\n    \nEnd Q3.\n\nModule Q4(T:TermDef)(TC:TermCongruence(T)).\n  Module NJ4 := NJ(T)(TC).\n  Import NJ4.\n  Export NJ4.\n\n  (* TODO : better name *)\n  Inductive weak_equiv {n} : type n -> type n -> Prop :=\n  | we_atom_l : forall i t, weak_equiv (ty_term (t_var i)) t\n  | we_atom_r : forall i t, weak_equiv t (ty_term (t_var i))\n  | we_term : forall s xs ys, weak_equiv (ty_term (t_term s xs)) (ty_term (t_term s ys))\n  | we_arrow : forall a b c d, weak_equiv (ty_arrow a b) (ty_arrow c d)\n  | we_forall : forall a b, weak_equiv (ty_forall a) (ty_forall b)\n  | we_exists : forall a b, weak_equiv (ty_exists a) (ty_exists b)\n  | we_bottom : weak_equiv ty_bottom ty_bottom\n  | we_copair : forall a b c d, weak_equiv (ty_copair a b) (ty_copair c d)\n  | we_top : weak_equiv ty_top ty_top\n  | we_pair : forall a b c d, weak_equiv (ty_pair a b) (ty_pair c d)\n  .\n\n  Definition sans_confusion := forall n p q, p ≡ q -> @weak_equiv n p q.\n\n  Ltac simpl_fold :=\n    repeat match goal with\n               [ H1 : context[fold_right _ _ nil] |- _ ] => simpl in H1; subst\n           end.\n\n  Ltac simpl_nf :=\n    match goal with\n      | [ H : nfview _ |- _ ] =>\n        inversion H; simpl_exist; subst;\n        try (solve by inversion);\n        match goal with\n            [ H0 : Forall nfview ?ns |- _ ] =>\n            destruct ns; simpl;\n            [ clear H H0\n            | solve by inversion\n            ]; simpl_fold\n        end\n      | [ H : nfview _ |- _ ] =>\n        inversion H; simpl_exist; subst;\n        [ match goal with\n              [ H0 : Forall nfview ?ns |- _ ] =>\n              destruct ns; simpl_fold; solve by inversion\n          end\n        |]\n      | [ H : nfview (e_app _ _) |- _ ] => apply nfview_app in H\n    end.\n\n  Ltac simpl_empty_nf :=\n    repeat match goal with\n             | [ H : ?x = ?x -> _ |- _ ] =>\n               let H0 := fresh \"H\" in\n               assert (H0 : x = x); [ reflexivity | specialize (H H0); clear H0 ]\n             | [ H : 1 = 0 -> _ |- _ ] => clear H\n             | [ H : 0 = 1 -> _ |- _ ] => clear H\n             | [ H : ?a, H0 : ?a -> ?b |- _ ] => specialize (H0 H)\n           end.\n  \n  (* Lemma empty_nf : sans_confusion -> *)\n  (*                  (forall n m Γ (e : exp n m) ty (P : Γ ⊢ e ∈ ty), *)\n  (*                     n = 0 -> m = 0 -> nfview e -> *)\n  (*                     (forall x, e <> e_absurd x) /\\ *)\n  (*                     (forall x y, e <> e_app x y) /\\ *)\n  (*                     (forall x y, e <> e_tapp x y) /\\ *)\n  (*                     (forall x, e <> e_pair1 x) /\\ *)\n  (*                     (forall x, e <> e_pair2 x) /\\ *)\n  (*                     (forall x y, e <> e_ecase x y) /\\ *)\n  (*                     (forall x y z, e <> e_case x y z) /\\ *)\n  (*                     ty <> ty_bottom *)\n  (*                  ). *)\n  (* Proof. *)\n  (*   Ltac solver := *)\n  (*     match goal with *)\n  (*       | [ H : sans_confusion, H0 : _ ≡ _ |- _ ] => *)\n  (*         (apply H in H0; try (inversion H0; simpl_exist; subst; *)\n  (*                              try (apply Fin.case0; trivial; fail); *)\n  (*                              try (unfold not; intro A; inversion A; fail); *)\n  (*                              fail)) *)\n  (*       | [ H0 : appcontext[?x = ?x -> False] |- _ ] => (eapply H0; eauto) *)\n  (*       | [ H0 : appcontext[?x _ = ?x _ -> False] |- _ ] => (eapply H0; eauto) *)\n  (*       | [ H0 : appcontext[?x _ _ = ?x _ _ -> False] |- _ ] => (eapply H0; eauto) *)\n  (*       | [ H0 : appcontext[?x _ _ _ = ?x _ _ _ -> False] |- _ ] => (eapply H0; eauto) *)\n  (*     end. *)\n\n  (*   intros H n m Γ e ty P. *)\n  (*   induction P; intros; subst; *)\n  (*   repeat constructor; *)\n  (*   try (intros; unfold not; intro A; inversion A; fail); *)\n  (*   try (apply Fin.case0; trivial; fail); *)\n  (*   solver; unfold not in *; *)\n  (*   try (exfalso; simpl_nf; try inversion H6; simpl_exist; *)\n  (*        simpl_empty_nf; destruct_pairs; *)\n  (*        match goal with *)\n  (*          | [ P : has_type Γ _ _ |- _ ] => *)\n  (*            inversion P; simpl_exist; *)\n  (*          try (apply Fin.case0; trivial; fail); *)\n  (*          repeat solver *)\n  (*        end; fail *)\n  (*       ); *)\n  (*   try ( exfalso; inversion H3; simpl_exist; subst; *)\n  (*         destruct ns; simpl_fold; *)\n  (*         [ inversion H6 *)\n  (*         | destruct ns; inversion H1; simpl_exist; subst; simpl_forall_list; *)\n  (*           apply nfview_app in H3; simpl_empty_nf; destruct_pairs; *)\n  (*           [ inversion H6; simpl_exist; subst; *)\n  (*             try (apply Fin.case0; auto; fail); *)\n  (*             try (inversion P1; simpl_exist; subst; try solver; fail); *)\n  (*             try solver *)\n  (*           | solver *)\n  (*           ] *)\n  (*         ]; fail). *)\n  (* Qed. *)\n\n  (* Theorem sans_confusion_coherent : sans_confusion -> *)\n  (*                                   forall (u : exp 0 0), nf u -> [] ⊢ u ∈ ty_bottom -> False. *)\n  (* Proof. *)\n  (*   intros H u nf p. *)\n  (*   apply nf_nfview in nf. *)\n  (*   assert (P := empty_nf H _ _ _ _ _ p). *)\n  (*   assert (0=0). reflexivity. *)\n  (*   specialize (P H0 H0 nf). *)\n  (*   destruct_pairs. *)\n  (*   apply H8; auto. *)\n  (* Qed. *)\n  \nEnd Q4.\n\nModule Q5(T:TermDef)(TC:TermCongruence(T)).\n  Module NJ5 := Q4(T)(TC).\n  Import NJ5.\n  Export NJ5.\n\n  Lemma vector_nth_map : forall {n A B} (f : A -> B) (v : Vector.t A n) i,\n                           (Vector.map f v)[@i] = f v[@i].\n  Proof.\n    intros. eapply Vector.nth_map; eauto.\n  Qed.\n  \n  Lemma vector_map_id : forall {n A} (v : Vector.t A n),\n                          v = Vector.map (fun x => x) v.\n  Proof.\n    dependent induction v; simpl; f_equal; auto.\n  Qed.\n\n  Lemma vector_map_sur {n A B} (f g : A -> B) (v : Vector.t A n) :\n    (forall i, f v[@i] = g v[@i]) ->\n    Vector.map f v = Vector.map g v.\n  Proof.\n    dependent induction v; intros; simpl; auto.\n    f_equal.\n    specialize (H Fin.F1). auto.\n    apply IHv; intros. specialize (H (Fin.FS i)). auto.\n  Qed.\n\n  Lemma term_subst_1_lift_term : forall {n} (t : term n) t',\n                                   term_subst Fin.F1 t (lift_term t') = t'.\n  Proof.\n    dependent induction t' using termRect.\n    destruct n; auto; apply Fin.case0; auto.\n    simpl; f_equal. rewrite (vector_map_id t0); repeat rewrite vector_map_map.\n    apply vector_map_sur. intros; eapply H.\n  Qed.\n    \n  Lemma lift_term_term_subst :\n    forall {n} i (t : term n) t',\n      term_subst (Fin.FS i) (lift_term t) (lift_term t') = lift_term (term_subst i t t').\n  Proof.\n    dependent induction t' using termRect.\n    destruct (eq_fin_dec i t0) eqn:H.\n    subst. simpl. repeat rewrite fin_subst_eq. trivial.\n    + simpl.\n      assert (H0 := fin_subst_neq _ _ (lift_term t) i t0 n0).\n      assert (H1 := fin_subst_neq _ _ t i t0 n0).\n      destruct H0; destruct H1; destruct_pairs. rewrite H0. rewrite H1. simpl. repeat f_equal.\n      rewrite <- H2 in H3. eauto.\n    + simpl. f_equal. repeat rewrite vector_map_map.\n      apply vector_map_sur. intros. eapply H. apply JMeq_refl.\n  Qed.\n  \n  Lemma lift_type_term_subst :\n    forall {n} i (t : term n) ty,\n      type_subst (Fin.FS i) (lift_term t) (lift_type ty) = lift_type (type_subst i t ty).\n  Proof.\n    dependent induction ty; simpl; f_equal; auto using lift_term_term_subst.\n  Qed.\n    \n  Lemma type_subst_1_lift_type : forall {n} (t : term n) t',\n                                   type_subst Fin.F1 t (lift_type t') = t'.\n  Proof.\n    dependent induction t'; simpl; f_equal; auto using term_subst_1_lift_term.\n    admit.\n    admit.\n  Qed.\n\n  Lemma liftΓ_term_subst :\n    forall {n m} i (t : term m) (Γ : Vector.t (type (S m)) n),\n      Vector.map (type_subst (Fin.FS i) (lift_term t)) (liftΓ Γ) = liftΓ (Vector.map (type_subst i t) Γ).\n  Proof.\n    intros. dependent induction Γ; simpl; f_equal; auto using lift_type_term_subst.\n  Qed.\n\n  Lemma term_subst_comm : forall {n} (t : term n) t' a i,\n                            term_subst Fin.F1 (term_subst i t t')\n                                       (term_subst (Fin.FS i) (lift_term t) a) =\n                            term_subst i t (term_subst Fin.F1 t' a).\n  Proof.\n    dependent induction a using termRect; intros.\n    + destruct (eq_fin_dec (Fin.FS i) t0) eqn:H; subst.\n      * simpl. repeat rewrite fin_subst_eq.\n        apply term_subst_1_lift_term.\n      * dependent destruction t0.\n        simpl. repeat rewrite fin_subst_eq. auto.\n        simpl. assert (i <> t0); [intro; subst; apply n0; auto|].\n        assert (H1 := fin_subst_neq _ _ (lift_term t) i t0 H0).\n        assert (H2 := fin_subst_neq _ _ t i t0 H0).\n        destruct H1; destruct H2; destruct_pairs. rewrite H1. rewrite H2.\n        rewrite <- H3 in H4. apply lift_fin_at_inj in H4. subst.\n        destruct n; eauto; apply Fin.case0; eauto.\n    + simpl. f_equal. repeat rewrite vector_map_map.\n      apply vector_map_sur; intros. eapply H; eauto.\n  Qed.\n        \n  Lemma type_subst_comm : forall {n} (t : term n) t' a i,\n                            type_subst Fin.F1 (term_subst i t t')\n                                       (type_subst (Fin.FS i) (lift_term t) a) =\n                            type_subst i t (type_subst Fin.F1 t' a).\n  Proof.\n    dependent induction a; intros; simpl; try (f_equal; eauto using term_subst_comm; fail).\n    (* lift_type needs to be replaced by lift_type_by, this is very difficult as n+m is not definitionally equal to m+n... *)\n    (* or free_variable relation ? *)\n    admit.\n    admit.\n  Qed.\n    \n  Theorem has_type_term_subst :\n    forall {n m} Γ (u : exp n (S m)) ty i t (P : Γ ⊢ u ∈ ty),\n      Vector.map (type_subst i t) Γ ⊢ exp_subst_term i t u ∈ type_subst i t ty.\n  Proof.\n    intros.\n    dependent induction P; simpl;\n    try (\n        repeat match goal with\n                 | [ H : (forall (_ : ?ty), _) |- _ ] =>\n                   let x := fresh \"x\" in\n                   evar (x : ty); specialize (H x);\n                 match goal with\n                   | [ x := ?a : ?b ~= ?c |- _ ] => unify b c; subst x\n                   | [ x := _ : _ |- _ ] => subst x\n                 end\n               end;\n        try (\n            simpl in *; econstructor; eauto using te_subst;\n            repeat match goal with\n                     | [ H : ?ty ≡ ?ty' |- _ ] =>\n                       match ty with\n                         | type_subst _ _ _ => fail\n                         | _ => eapply te_subst in H\n                       end\n                   end;\n            eauto using te_subst; fail)).\n    + econstructor. erewrite Vector.nth_map; eauto using te_subst.\n    + econstructor.\n      rewrite liftΓ_term_subst in IHP. eauto.\n      eapply te_subst in H. eapply H.\n    + econstructor. instantiate (1 := type_subst (Fin.FS i) (lift_term t) p).\n      rewrite type_subst_comm. eapply IHP.\n      eapply te_subst in H. eapply H.\n    + simpl in IHP2. rewrite liftΓ_term_subst in IHP2. rewrite lift_type_term_subst in IHP2.\n      econstructor; eauto using te_subst.\n      \n      Grab Existential Variables.\n      eauto. eauto. eauto. eauto. eauto.\n      eauto. eauto. eauto. eauto. eauto.\n      eauto. eauto. eauto. eauto. eauto.\n      eauto. eauto. eauto. eauto. eauto.\n      eauto. eauto. eauto. eauto.\n  Qed.\n\nEnd Q5.\n\nModule Q6(T:TermDef)(TC:TermCongruence(T)).\n  Module NJ6 := Q5(T)(TC).\n  Import NJ6.\n  Export NJ6.\n\n  Theorem admit {A} : A.\n  Proof. admit. Qed.\n\n  Fixpoint substΓ {n m} (i : Fin.t (S n)) (Γ : Vector.t (type m) (S n)) : Vector.t (type m) n\n    := match i in Fin.t n' return forall pf : n' = S n,\n                                    Vector.t (type m) n\n       with\n         | Fin.F1 _ => fun pf => Vector.tl Γ\n         | Fin.FS n' i => fun pf =>\n                            match n' as n'' return forall pf' : n'' = n',\n                                                     Vector.t (type m) n\n                            with\n                              | 0 => fun pf' => Fin.case0 (fun _ => Vector.t (type m) n) (eq_rect _ Fin.t i _ (eq_sym pf'))\n                              | S n'' => fun pf' => eq_rect (S n'') (Vector.t (type m))\n                                                      (Vector.hd Γ :: substΓ\n                                                                 (eq_rect n' Fin.t i _ (eq_sym pf'))\n                                                                 (eq_rect n (Vector.t (type m)) (Vector.tl Γ) _\n                                                                          (eq_trans (f_equal pred (eq_sym pf)) (eq_sym pf'))\n                                                                 )\n                                                      ) _ (eq_trans pf' (f_equal pred pf))\n                            end eq_refl\n       end eq_refl.\n\n  Lemma substΓ_extend : forall {n m} (Γ : Vector.t (type m) (S n)) ty i,\n                          ty :: substΓ i Γ = substΓ (Fin.FS i) (ty :: Γ).\n  Proof.\n    dependent induction Γ; intros; auto.\n  Qed.\n  \n  Lemma substΓ_lift : forall {n m} (Γ : Vector.t (type m) (S n)) i,\n                          liftΓ (substΓ i Γ) = substΓ i (liftΓ Γ).\n  Proof.\n    dependent induction Γ; intros;\n    dependent destruction i; auto.\n    destruct n; simpl.\n    apply Fin.case0; auto.\n    rewrite IHΓ; eauto.\n  Qed.\n\n  Lemma substΓ_index : forall {n m} (Γ : Vector.t (type m) (S n)) i i',\n                          (substΓ i Γ)[@i'] = Γ[@lift_fin_at i i'].\n  Proof.\n    intros.\n    dependent induction Γ; dependent destruction i; dependent destruction i'; intros; eauto.\n    specialize (IHΓ n Γ eq_refl JMeq_refl i i'); eauto.\n  Qed.\n\n  Lemma has_type_lift : forall {n m} Γ (e : exp n m) ty,\n                          Γ ⊢ e ∈ ty -> liftΓ Γ ⊢ lift_exp e ∈ lift_type ty.\n  Proof.\n    intros.\n    dependent induction H; \n      try (try econstructor;\n           unfold liftΓ; try rewrite vector_nth_map;\n           match goal with\n             | [ H : _ ≡ _ |- _ ] => apply te_lift in H\n           end;\n           eauto;\n           fail).\n    (* true ? *)\n    admit.\n  Qed.\n\n  \n  Lemma weakening_lemma : forall {n m} Γ (e : exp n m) ty i,\n                            substΓ i Γ ⊢ e ∈ ty -> Γ ⊢ lift_exp_at i e ∈ ty.\n  Proof.\n    intros.\n    dependent induction H; simpl;\n    try econstructor (solve [eauto]).\n    + rewrite substΓ_index in H.\n      econstructor; eauto.\n    + econstructor; eauto;\n      specialize (IHhas_type (t :: Γ) (Fin.FS i)); eauto.\n    + econstructor; eauto.\n      eapply (IHhas_type (liftΓ Γ) i);\n      rewrite substΓ_lift; eauto.\n    + econstructor; eauto.\n      eapply (IHhas_type2 (p :: liftΓ Γ) (Fin.FS i));\n      rewrite substΓ_lift; eauto.\n  Qed.\n      \n  Theorem substitution_lemma :\n    forall {n m} Γ v (e : exp (S n) m) ty i,\n      Γ ⊢ e ∈ ty -> substΓ i Γ ⊢ v ∈ Γ[@i] -> substΓ i Γ ⊢ exp_subst i v e ∈ ty.\n  Proof.\n    Ltac solver :=\n      repeat match goal with\n               | [ H : (forall (_ : ?ty), _) |- _ ] =>\n                 let x := fresh \"x\" in\n                 evar (x : ty); specialize (H x);\n                 match goal with\n                   | [ x := ?a : ?b = ?c |- _ ] => unify b c; subst x\n                   | [ x := ?a : ?b ~= ?c |- _ ] => unify b c; subst x\n                   | [ x := _ : _ |- _ ] => subst x\n                 end\n             end.\n    intros n m Γ v e ty i P.\n    dependent induction P; intros;\n    try (simpl; econstructor; try rewrite substΓ_lift; try rewrite substΓ_extend; eauto).\n    + destruct (eq_fin_dec i i0); subst.\n      rewrite exp_subst_eq; eapply p_equiv; eauto using te_sym.\n      assert (H1 := fin_subst_neq _ _ v _ _ n0).\n      destruct H1; destruct_pairs. simpl. rewrite H1.\n      econstructor. rewrite substΓ_index. subst. eauto.\n    + eapply IHP; eauto; eapply weakening_lemma; eauto.\n    + eapply IHP; eauto.\n      rewrite <- substΓ_lift; unfold liftΓ at 2; rewrite vector_nth_map.\n      eapply has_type_lift; eauto.\n    + eapply IHP2; eauto; simpl.\n      unfold liftΓ at 2; rewrite vector_nth_map.\n      eapply weakening_lemma; simpl.\n      rewrite <- substΓ_lift; eapply has_type_lift; eauto.\n    + eapply IHP2; eauto. eapply weakening_lemma; eauto.\n    + eapply IHP3; eauto. eapply weakening_lemma; eauto.\n  Qed.  \n\n  Lemma equivΓ_has_type : forall {n m} Γ Γ' (e : exp n m) ty,\n    (forall i, Γ[@i] ≡ Γ'[@i]) ->\n    Γ ⊢ e ∈ ty -> Γ' ⊢ e ∈ ty.\n  Proof with eauto using te_refl, te_lift, te_trans, te_sym.\n    intros. dependent induction H0;\n      try econstructor (solve [eauto using te_trans, te_refl, te_sym]).\n    + econstructor; eauto. eapply IHhas_type.\n      intro; dependent destruction i...\n    + econstructor; eauto. eapply IHhas_type. \n      intro. unfold liftΓ; repeat rewrite vector_nth_map...\n    + econstructor; eauto. eapply IHhas_type2. intro.\n      dependent destruction i...\n      unfold liftΓ; simpl; repeat rewrite vector_nth_map...\n    + econstructor; eauto.\n      * eapply IHhas_type2; intro; dependent destruction i...\n      * eapply IHhas_type3; intro; dependent destruction i...\n  Qed.\n        \n  Definition subject_reduction_hypothesis :=\n    (forall n a b, @ty_exists n a ≡ ty_exists b ->\n                   a ≡ b)\n    /\\ (forall n a b c d, @ty_arrow n a b ≡ ty_arrow c d ->\n                          a ≡ c /\\ b ≡ d)\n    /\\ (forall n a b c d, @ty_copair n a b ≡ ty_copair c d ->\n                          a ≡ c /\\ b ≡ d)\n    /\\ (forall n a b c d, @ty_pair n a b ≡ ty_pair c d ->\n                          a ≡ c /\\ b ≡ d).\n  \n  Theorem subject_reduction : subject_reduction_hypothesis ->\n                              forall {n m} Γ (e : exp n m) e' ty,\n                                Γ ⊢ e ∈ ty -> e ===> e' -> Γ ⊢ e' ∈ ty.\n  Proof with eauto using p_equiv, te_refl, te_lift, te_trans, te_sym.\n    intros H n m Γ e e' ty P; unfold subject_reduction_hypothesis in H; destruct_pairs.\n    generalize dependent e'.\n    induction P; intros e' R; inversion R; simpl_exist;\n    try (econstructor (solve [eauto using p_equiv, te_sym])).\n    + inversion P1; simpl_exist.\n      apply H0 in H10; destruct_pairs.\n      assert (HΓ : Γ = substΓ Fin.F1 (t0 :: Γ)); eauto; rewrite HΓ;\n      eapply substitution_lemma...\n    + inversion P1; simpl_exist. econstructor; eauto.\n    + inversion P1; simpl_exist.\n      assert (HΓ : Γ = substΓ Fin.F1 (type_subst Fin.F1 t p0 :: Γ)); eauto; rewrite HΓ.\n      eapply substitution_lemma...\n      assert (type_subst Fin.F1 t p0 :: Γ = Vector.map (type_subst Fin.F1 t) (p0 :: liftΓ Γ)); [|rewrite H4]. simpl. f_equal. rewrite (vector_map_id Γ) at 1. unfold liftΓ. rewrite vector_map_map. apply vector_map_sur. intro. rewrite type_subst_1_lift_type...\n      assert (ty = type_subst Fin.F1 t (lift_type ty)); [| rewrite H5].\n      rewrite type_subst_1_lift_type...\n      eapply has_type_term_subst; eapply p_equiv; eauto using te_sym, te_lift.\n      eapply equivΓ_has_type; eauto.\n      intro; dependent destruction i; simpl...\n    + inversion P1; simpl_exist.\n      apply H1 in H10; destruct_pairs.\n      assert (HΓ : Γ = substΓ Fin.F1 (a :: Γ)); eauto; rewrite HΓ;\n      eapply substitution_lemma...\n    + inversion P1; simpl_exist.\n      apply H1 in H10; destruct_pairs.\n      assert (HΓ : Γ = substΓ Fin.F1 (b :: Γ)); eauto; rewrite HΓ;\n      eapply substitution_lemma...\n    + inversion P; simpl_exist.\n      apply H2 in H12; destruct_pairs.\n      eauto using p_equiv, te_sym.\n    + inversion P; simpl_exist.\n      apply H2 in H12; destruct_pairs.\n      eauto using p_equiv, te_sym.\n  Qed.\n  \nEnd Q6.", "meta": {"author": "RafaelBocquet", "repo": "NJ", "sha": "2aba58ae5ac1fbd988defbcf674f90eecd77c93c", "save_path": "github-repos/coq/RafaelBocquet-NJ", "path": "github-repos/coq/RafaelBocquet-NJ/NJ-2aba58ae5ac1fbd988defbcf674f90eecd77c93c/NJ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.8080672204860317, "lm_q1q2_score": 0.6785614899636004}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\nLocal Set Warnings \"-notation-overridden\".\nFrom mathcomp Require Export seq eqtype ssrnat.\n\n\nTheorem fold_union :\n  forall (A: eqType) (l: seq A) f base P,\n    (forall acc a, P (f acc a) = P acc || P a) ->\n             P (foldl f base l) = P base || (has P l).\nProof.\n  move => A. elim => [ f base P HP /= | ]. by rewrite orbF.\n  move => a l Hind f base P HP. rewrite /= Hind => //.\n  by rewrite HP orbA.\nQed.\n\nTheorem fold_intersection :\n  forall (A: eqType) (l: seq A) f base P,\n    (forall acc a, P (f acc a) = P acc && P a) ->\n             P (foldl f base l) = (P base && all P l).\nProof.\n  move => A. elim => [ f base P HP |  ]; first by rewrite andbT.\n  move => a l Hind f base P HP. rewrite /= Hind => //.\n  by rewrite HP andbA.\nQed.\n\n\n\nTheorem sub_all_in: forall (T : eqType) (a1 a2 : pred T) (s: seq T),\n    subpred (T:=T) (fun x => (x \\in s) ==> a1 x) (fun x => (x \\in s) ==> a2 x) ->\n    all a1 s -> all a2 s.\nProof.\n  move => T a1 a2 s Hsubpred.\n  move => /allP HIn1. apply /allP => x Hx_in.\n  move => /(_ x) in Hsubpred. rewrite Hx_in in Hsubpred.\n  rewrite !implyTb in Hsubpred; auto.\nQed.\n\nTheorem zip_uniq :\n  forall (A B: eqType) (a: A) (b: B) (s1: seq A) (s2: seq B), uniq s1 -> uniq (zip s1 s2).\nProof.\n  move => A B a b s1 s2.\n  move => /uniqP Huniq.\n  apply /(uniqP (a,b)) => x y Hx Hy.\n  move => /(_ a x y) in Huniq.\n  rewrite /in_mem /= in Hx, Hy, Huniq.\n  move: (Hx) (Hy). rewrite !size_zip !leq_min => /andP[Hx1 Hx2] /andP[Hy1 Hy2].\n  move => /(_ Hx1 Hy1) in Huniq.\n  rewrite !nth_zip_cond Hx Hy. move => [H1 H2].\n    by auto.\nQed.\n\nTheorem index_uniq_zip :\n  forall (A B: eqType) (a: A) (b: B) (s1: seq A) (s2: seq B),\n    uniq s1 ->\n    (a, b) \\in (zip s1 s2) ->\n               index (a, b) (zip s1 s2) = index a s1.\nProof.\n  move => A B a b s1 s2 Huniq Hin.\n  move: (Hin) => Hin'.\n  apply (nth_index (a,b)) in Hin'. rewrite nth_zip_cond in Hin'.\n  rewrite -index_mem in Hin. rewrite Hin in Hin'.\n  case: Hin' => [Hin' _].\n  rewrite -[in X in _ = X]Hin'. rewrite index_uniq => //.\n  move: Hin. by rewrite size_zip leq_min => /andP[H1 H2].\nQed.\n\n\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/ssrseq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.6785614899636003}}
{"text": "Load lab9strongInduction.\nRequire Import Coq.omega.Omega.\n\nFixpoint redeemBars (n : nat) : nat :=\n match n with\n | 0 => 0\n | 1 => 0\n | 2 => 0\n | 3 => 0\n | 4 => 0\n | 5 => 0\n | 6 => 0\n | 7 => 0\n | 8 => 0\n | 9 => 0\n | S(S(S(S(S(S(S(S(S(S n as n'))))))))) => 1 + redeemBars n'\n end.\n\nEval compute in (redeemBars 9).\nEval compute in (redeemBars 10).\nEval compute in (redeemBars 17).\nEval compute in (redeemBars 18).\nEval compute in (redeemBars 19).\nEval compute in (redeemBars 27).\nEval compute in (redeemBars 28).\n\nFixpoint div9 (n : nat) : nat :=\n match n with\n | 0 => 0\n | 1 => 0\n | 2 => 0\n | 3 => 0\n | 4 => 0\n | 5 => 0\n | 6 => 0\n | 7 => 0\n | 8 => 0\n | S(S(S(S(S(S(S(S(S n)))))))) => 1 + div9 n\n end.\n\nTheorem result: forall n : nat, redeemBars(S n) = div9 n.\nProof.\ninduction n using strong_induction.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\ndestruct n.\nreflexivity.\n\nassert (n < S (S (S (S (S (S (S (S (S n))))))))).\nomega.\napply H in H0.\n\nchange (redeemBars (S (S (S (S (S (S (S (S (S (S n))))))))))) with (1 + redeemBars (S n)).\nchange (div9 (S (S (S (S (S (S (S (S (S n)))))))))) with (1 + div9 n).\n\nrewrite H0.\nreflexivity.\nQed.\n", "meta": {"author": "Toskah", "repo": "Coq", "sha": "956df87bfc60f2ae32b80851978d211f60768de0", "save_path": "github-repos/coq/Toskah-Coq", "path": "github-repos/coq/Toskah-Coq/Coq-956df87bfc60f2ae32b80851978d211f60768de0/lab11/lab11task2.COMPLETE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6785614854418122}}
{"text": "Welcome to Coq ciosx:/builds/workspace/coq-8.5pl3-macos,(detached from 2290dbb) (2290dbb9c95b63e693ced647731623e64297f5c8)\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 < Theorem plus_1_neq_0_firsttry : forall n : nat, beq_nat (n + 1) 0 = false.\n1 subgoal\n  \n  ============================\n  forall n : nat, beq_nat (n + 1) 0 = false\n\nplus_1_neq_0_firsttry < Proof.\n1 subgoal\n  \n  ============================\n  forall n : nat, beq_nat (n + 1) 0 = false\n\nplus_1_neq_0_firsttry < info_auto.\nDebug: (* info auto : *)\nDebug: idtac.\n1 subgoal\n  \n  ============================\n  forall n : nat, beq_nat (n + 1) 0 = false\n\nplus_1_neq_0_firsttry < intros n.\n1 subgoal\n  \n  n : nat\n  ============================\n  beq_nat (n + 1) 0 = false\n\nplus_1_neq_0_firsttry < simpl.\n1 subgoal\n  \n  n : nat\n  ============================\n  beq_nat (n + 1) 0 = false\n\nplus_1_neq_0_firsttry < destruct n as [| n'].\n2 subgoals\n  \n  ============================\n  beq_nat (0 + 1) 0 = false\n\nsubgoal 2 is:\n beq_nat (S n' + 1) 0 = false\n\nplus_1_neq_0_firsttry < reflexivity.\n1 subgoal\n  \n  n' : nat\n  ============================\n  beq_nat (S n' + 1) 0 = false\n\nplus_1_neq_0_firsttry < reflexivity.\nNo more subgoals.\n\nplus_1_neq_0_firsttry < Qed.\nProof.\ninfo_auto.\nintros n.\nsimpl.\ndestruct n as [| n'].\n reflexivity.\n\n reflexivity.\n\nQed.\nplus_1_neq_0_firsttry 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/basic016.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.6785614815604114}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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 := Succ y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj287_coqofml_3S3NY1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6785529082637948}}
{"text": "(**\nHere we define the basic notions of setoids.\n *)\nRequire Import prelude.all.\n\n(**\nProjections and builder functions of equivalence relations.\n*)\nDefinition make_eq_rel\n           {X : hSet}\n           (rel : hrel X)\n           (isrefl_rel : isrefl rel)\n           (issymm_rel : issymm rel)\n           (istrans_rel : istrans rel)\n  : eqrel X\n  := rel ,, ((istrans_rel ,, isrefl_rel) ,, issymm_rel).\n\nDeclare Scope setoid_scope.\nDelimit Scope setoid_scope with setoid.\nNotation \"'id' g\" := (eqrelrefl _ g) (at level 30) : setoid_scope.\nNotation \"! p\" := (eqrelsymm _ _ _ p) : setoid_scope.\nNotation \"p @ q\" := (eqreltrans _ _ _ _ p q) : setoid_scope.\n\n(**\nA setoid is just a pair of a set and an equivalence relation.\n *)\nDefinition setoid :=\n  ∑ (X : hSet), eqrel X.\n\n(**\nProjections and builder functions of setoids.\n *)\nDefinition make_setoid\n           {X : hSet}\n           (R : eqrel X)\n  : setoid\n  := X ,, R.\n\nCoercion carrier (X : setoid) : hSet := pr1 X.\n\nDefinition carrier_eq\n           (X : setoid)\n  : eqrel X\n  := pr2 X.\n\nNotation \"x ≡ y\" := (carrier_eq _ x y) (at level 70).\n\nDefinition isaprop_setoid_eq\n           {X : setoid}\n           (x y : X)\n  : isaprop (x ≡ y).\nProof.\n  apply (pr1 (carrier_eq X)).\nDefined.\n\nDefinition setoid_path\n           {X : setoid}\n           {x y : X}\n           (p : x = y)\n  : x ≡ y.\nProof.\n  induction p.\n  apply (id _)%setoid.\nDefined.\n\n(**\nLastly, we define setoid morphisms.\n *)\nDefinition setoid_morphism (X₁ X₂ : setoid)\n  := ∑ (f : X₁ → X₂), ∏ (x y : X₁), x ≡ y → f x ≡ f y.\n\n(**\nProjections and builder functions for setoid morphisms.\n *)\nDefinition make_setoid_morphism\n           {X₁ X₂ : setoid}\n           (f : X₁ → X₂)\n           (Rf : ∏ (x y : X₁), x ≡ y → f x ≡ f y)\n  : setoid_morphism X₁ X₂\n  := f ,, Rf.\n\nDefinition map_carrier\n           {X₁ X₂ : setoid}\n           (f : setoid_morphism X₁ X₂)\n  : X₁ → X₂\n  := pr1 f.\n\nCoercion map_carrier : setoid_morphism >-> Funclass.\n\nDefinition map_eq\n           {X₁ X₂ : setoid}\n           (f : setoid_morphism X₁ X₂)\n           {x y : X₁}\n  : x ≡ y → f x ≡ f y\n  := pr2 f x y.\n\n(**\nEquality principle for setoid morphisms.\n *)\nDefinition setoid_morphism_eq\n           {X₁ X₂ : setoid}\n           (f g : setoid_morphism X₁ X₂)\n           (e : ∏ (x : X₁), f x = g x)\n  : f = g.\nProof.\n  use subtypePath.\n  - intro.    \n    do 3 (apply impred ; intro).\n    apply isaprop_setoid_eq.\n  - apply funextsec.\n    exact e.\nDefined.\n\nDefinition isaset_setoid_morphism (X₁ X₂ : setoid)\n  : isaset(setoid_morphism X₁ X₂).\nProof.\n  use isaset_total2.\n  - apply isaset_set_fun_space.\n  - intros f ; cbn.\n    apply isasetaprop.\n    repeat (apply impred ; intro).\n    apply isaprop_setoid_eq.\nDefined.\n", "meta": {"author": "UniMath", "repo": "SetHITs", "sha": "512f3c76926f458a130786891c2e325e66afeb21", "save_path": "github-repos/coq/UniMath-SetHITs", "path": "github-repos/coq/UniMath-SetHITs/SetHITs-512f3c76926f458a130786891c2e325e66afeb21/code/setoids/base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587668, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.6784357690906384}}
{"text": "(***************************************************************************\n* Safety for Simply Typed Lambda Calculus (CBV) - Definitions              *\n* Brian Aydemir & Arthur Chargueraud, July 2007                            *\n***************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibLN.\nImplicit Types x : var.\n\n(** Grammar of types. *)\n\nInductive typ : Set :=\n  | typ_var   : var -> typ\n  | typ_arrow : typ -> typ -> typ.\n\n(** Grammar of pre-terms. *)\n\nInductive trm : Set :=\n  | trm_bvar : nat -> trm\n  | trm_fvar : var -> trm\n  | trm_abs  : trm -> trm\n  | trm_app  : trm -> trm -> trm.\n\n(** Opening up abstractions *)\n\nFixpoint open_rec (k : nat) (u : trm) (t : trm) {struct t} : trm :=\n  match t with\n  | trm_bvar i    => If k = i then u else (trm_bvar i)\n  | trm_fvar x    => trm_fvar x\n  | trm_abs t1    => trm_abs (open_rec (S k) u t1)\n  | trm_app t1 t2 => trm_app (open_rec k u t1) (open_rec k u t2)\n  end.\n\nDefinition open t u := open_rec 0 u t.\n\nNotation \"{ k ~> u } t\" := (open_rec k u t) (at level 67).\nNotation \"t ^^ u\" := (open t u) (at level 67).\nNotation \"t ^ x\" := (open t (trm_fvar x)).\n\n(** Terms are locally-closed pre-terms *)\n\nInductive term : trm -> Prop :=\n  | term_var : forall x,\n      term (trm_fvar x)\n  | term_abs : forall L t1,\n      (forall x, x \\notin L -> term (t1 ^ x)) ->\n      term (trm_abs t1)\n  | term_app : forall t1 t2,\n      term t1 ->\n      term t2 ->\n      term (trm_app t1 t2).\n\n(** Environment is an associative list mapping variables to types. *)\n\nDefinition env := LibEnv.env typ.\n\n(** Typing relation *)\n\nReserved Notation \"E |= t ~: T\" (at level 69).\n\nInductive typing : env -> trm -> typ -> Prop :=\n  | typing_var : forall E x T,\n      ok E ->\n      binds x T E ->\n      E |= (trm_fvar x) ~: T\n  | typing_abs : forall L E U T t1,\n      (forall x, x \\notin L ->\n        (E & x ~ U) |= t1 ^ x ~: T) ->\n      E |= (trm_abs t1) ~: (typ_arrow U T)\n  | typing_app : forall S T E t1 t2,\n      E |= t1 ~: (typ_arrow S T) ->\n      E |= t2 ~: S ->\n      E |= (trm_app t1 t2) ~: T\n\nwhere \"E |= t ~: T\" := (typing E t T).\n\n(** Definition of values (only abstractions are values) *)\n\nInductive value : trm -> Prop :=\n  | value_abs : forall t1,\n      term (trm_abs t1) -> value (trm_abs t1).\n\n(** Reduction relation - one step in call-by-value *)\n\nInductive red : trm -> trm -> Prop :=\n  | red_beta : forall t1 t2,\n      term (trm_abs t1) ->\n      value t2 ->\n      red (trm_app (trm_abs t1) t2) (t1 ^^ t2)\n  | red_app_1 : forall t1 t1' t2,\n      term t2 ->\n      red t1 t1' ->\n      red (trm_app t1 t2) (trm_app t1' t2)\n  | red_app_2 : forall t1 t2 t2',\n      value t1 ->\n      red t2 t2' ->\n      red (trm_app t1 t2) (trm_app t1 t2').\n\nNotation \"t --> t'\" := (red t t') (at level 68).\n\n(** Goal is to prove preservation and progress *)\n\nDefinition preservation := forall E t t' T,\n  E |= t ~: T ->\n  t --> t' ->\n  E |= t' ~: T.\n\nDefinition progress := forall t T,\n  empty |= t ~: T ->\n     value t\n  \\/ exists t', t --> t'.\n\n", "meta": {"author": "charguer", "repo": "formalmetacoq", "sha": "0f24ffe7416352c1a275671d8d857f8aa6a5bb39", "save_path": "github-repos/coq/charguer-formalmetacoq", "path": "github-repos/coq/charguer-formalmetacoq/formalmetacoq-0f24ffe7416352c1a275671d8d857f8aa6a5bb39/ln/STLC_Core_Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.6784357599903578}}
{"text": "Require Import Arith.\nRequire Import List.\nRequire Import Relations.\nRequire Import Wellfounded.\nRequire Import list_util.\n\n(* LP *)\nInductive Formula : Set :=\n|Var: nat -> Formula\n|Neg: Formula -> Formula\n|Imp: Formula -> Formula -> Formula\n.\n\nNotation \"# n\" := (Var n) (at level 80, no associativity) : LP_scope.\nNotation \"! f\" := (Neg f) (at level 82, no associativity) : LP_scope.\nNotation \"f ==> g\" := (Imp f g) (at level 85, right associativity) : LP_scope.\n\nOpen Scope LP_scope.\nFixpoint interpret (f:Formula) (a:nat->bool) := match f with |# n => a n | ! g => negb (interpret g a) | g ==> h => orb (negb (interpret g a)) (interpret h a) end.\n\nInductive LPAxiom: Formula -> Prop :=\n|LPA1 : forall f g, LPAxiom (f==>g==>f)\n|LPA2 : forall f g h, LPAxiom ((f==>g==>h)==>(f==>g)==>f==>h)\n|LPA3 : forall f g, LPAxiom ((!f==>!g)==>g==>f)\n.\nInductive LPTheorem : Formula -> Prop:=\n|LPAx: forall f, LPAxiom f -> LPTheorem f\n|LPImp: forall f g, LPTheorem (f==>g) -> LPTheorem f -> LPTheorem g\n.\nInductive LPInf (p:list Formula) : Formula -> Prop:=\n|LPIAx : forall f, LPAxiom f -> LPInf p f\n|LPIIn : forall f, In f p -> LPInf p f\n|LPIImp: forall f g, LPInf p (f==>g) -> LPInf p f -> LPInf p g\n.\nHint Constructors LPAxiom LPTheorem LPInf.\n\nTheorem LPTheorem_Inf: forall p f, LPTheorem f -> LPInf p f. Proof. intros. induction H; auto. apply LPIImp with f; auto. Qed.\nTheorem LPInf_Theorem: forall f, LPInf nil f -> LPTheorem f. Proof. intros. induction H; auto. inversion H. apply LPImp with f; auto. Qed.\nTheorem Inf_incl: forall f l m, incl l m -> LPInf l f -> LPInf m f. Proof. intros. induction H0; auto. apply LPIImp with f; auto. Qed.\nTheorem Inf_cons: forall f l p, LPInf l f -> LPInf (p::l) f. Proof. intros. apply Inf_incl with l; auto. Qed.\nTheorem imp_refl: forall l f, LPInf l (f==>f). Proof. intros. apply LPIImp with (f==>f==>f); auto. apply LPIImp with (f==>(f==>f)==>f); auto. Qed.\nTheorem imp_intro: forall l f g, LPInf l f -> LPInf l (g==>f). Proof. intros. apply LPIImp with f; auto. Qed.\nHint Resolve LPTheorem_Inf LPInf_Theorem Inf_incl Inf_cons imp_refl imp_intro.\n\nTheorem InfTh': forall p l m f, Add p l m -> LPInf m f -> LPInf l (p==>f). Proof. intros. induction H0; auto. apply Add_in with (x:=f) in H. apply H in H0. destruct H0; [subst p|]; auto. apply LPIImp with (p==>f); auto. apply LPIImp with (p==>f==>g); auto. Qed.\nTheorem InfTh: forall p l f, LPInf (p::l) f -> LPInf l (p==>f). Proof. intros. apply InfTh' with (p::l); auto. Qed.\nTheorem LPabsurd: forall p f g, LPInf p f -> LPInf p (!f) -> LPInf p g. Proof. intros. apply LPIImp with f; auto. apply LPIImp with (!g==>!f); auto. Qed.\nTheorem contra': forall l m f g, Add (!f) l m -> LPInf m g -> LPInf m (!g) -> LPInf l f. Proof. intros. apply LPIImp with (f==>f); auto. apply LPIImp with (!f==>!(f==>f)); auto. apply InfTh' with m; auto. apply LPabsurd with g; auto. Qed.\nTheorem contra: forall l f g, LPInf ((!f)::l) g -> LPInf ((!f)::l) (!g) -> LPInf l f. Proof. intros. apply contra' with ((!f)::l) g; auto. Qed.\nHint Resolve InfTh' InfTh LPabsurd contra' contra.\n\nTheorem neg_elim: forall p f, LPInf p (!(!f)) -> LPInf p f. Proof. intros. apply LPIImp with (f==>f); auto. apply LPIImp with (!f==>!(f==>f)); auto. apply LPIImp with (!(!(f==>f))==>!(!f)); auto. Qed.\nTheorem neg_intro: forall p f, LPInf p f -> LPInf p (!(!f)). Proof. intros. apply contra with f; auto. apply neg_elim; auto. Qed.\nTheorem imp_trans: forall p f g h, LPInf p (f==>g) -> LPInf p (g==>h) -> LPInf p (f==>h). Proof. intros. apply InfTh. apply LPIImp with g; auto. apply LPIImp with f; auto. Qed.\nHint Resolve neg_elim neg_intro imp_trans.\n\nTheorem neg_imp: forall p f g, LPInf p (f==>g) -> LPInf p (!f==>g) -> LPInf p g. Proof. intros. apply contra with f; apply LPIImp with (!g); auto. apply LPIImp with (!f==>!(!g)); auto. apply imp_trans with g; auto. apply LPIImp with (!(!f)==>!(!(g))); auto. apply imp_trans with f; auto. apply imp_trans with g; auto. Qed.\n\nDefinition LPand (f g:Formula) := !(f==>!g).\nDefinition LPor (f g:Formula) := !f==>g.\nNotation \"f &^ g\" := (LPand f g) (at level 83, left associativity) : LP_scope.\nNotation \"f |^ g\" := (LPor f g) (at level 84, left associativity) : LP_scope.\n\nTheorem or_intro1: forall p f g, LPInf p f -> LPInf p (f|^g). Proof. intros. apply InfTh. apply contra with f; auto. Qed.\nTheorem or_intro2: forall p f g, LPInf p g -> LPInf p (f|^g). Proof. intros. apply InfTh. auto. Qed.\nTheorem or_elim: forall p f g h, LPInf p (f==>h) -> LPInf p (g==>h) -> LPInf p (f|^g) -> LPInf p h. Proof. intros. apply neg_imp with f; auto. apply imp_trans with g; auto. Qed.\nTheorem and_intro: forall p f g, LPInf p f -> LPInf p g -> LPInf p (f&^g). Proof. intros. apply contra with g; auto. apply LPIImp with f; auto. Qed.\nTheorem and_elim1: forall p f g, LPInf p (f&^g) -> LPInf p f. Proof. intros. apply contra with (f==>!g); auto. apply InfTh. apply LPabsurd with f; auto. Qed.\nTheorem and_elim2: forall p f g, LPInf p (f&^g) -> LPInf p g. Proof. intros. apply contra with (f==>!g); auto. Qed.\nHint Resolve neg_imp or_intro1 or_intro2 or_elim and_intro and_elim1 and_elim2.\n\nTheorem deMorgan1: forall f g p, LPInf p (! f |^ ! g) -> LPInf p (!(f&^g)). Proof. intros. apply contra with f; auto. apply and_elim1 with g; auto. apply or_elim with (!f) (!g); auto. apply InfTh. apply LPabsurd with g; auto. apply and_elim2 with f; auto. Qed.\nTheorem deMorgan2: forall f g p, LPInf p (!f &^ !g) -> LPInf p (!(f|^g)). Proof. intros. apply contra with f; auto. apply or_elim with f g; auto. apply InfTh. apply LPabsurd with g; auto. apply and_elim2 with (!f); auto. apply and_elim1 with (!g); auto. Qed.\nTheorem deMorgan3: forall f g p, LPInf p (!(f|^g)) -> LPInf p (!f &^ !g). Proof. intros. apply and_intro; apply contra with (f|^g); auto. Qed.\nTheorem deMorgan4: forall f g p, LPInf p (!(f&^g)) -> LPInf p (!f |^ !g). Proof. intros. apply contra with (f &^ g); auto. apply LPIImp with (!(!f)&^!(!g)). apply InfTh. apply and_intro; apply neg_elim. apply and_elim1 with (!(!g)); auto. apply and_elim2 with (!(!f)); auto. apply deMorgan3; auto. Qed.\nHint Resolve deMorgan1 deMorgan2 deMorgan3 deMorgan4.\n\nDefinition Tautology f: Prop := forall a, interpret f a = true.\n\nInductive Vars: nat-> Formula ->Prop:=\n|VarV: forall n, Vars n (#n)\n|VarN: forall n f, Vars n f -> Vars n (!f)\n|VarI1: forall n f g, Vars n f -> Vars n (f==>g)\n|VarI2: forall n f g, Vars n g -> Vars n (f==>g)\n.\nHint Constructors Vars.\nDefinition vars' : forall f, {l| forall x, In x l<->Vars x f}. induction f. exists (n::nil). intros x; split; intros. destruct H. subst x; auto. destruct H. inversion H; auto. destruct IHf as [l H]. exists l. intros x. split; intros. apply VarN; apply H; auto. apply H. inversion H0; auto. destruct IHf1 as [l H]. destruct IHf2 as [m H1]. exists (l++m). intros. split; intros. apply in_app_or in H0. destruct H0. apply H in H0; auto. apply H1 in H0; auto. apply in_or_app. inversion H0; [left; apply H|right; apply H1]; auto. Defined.\nDefinition vars: forall f, {l|NoDup l & forall x, In x l<->Vars x f}. intros. destruct (vars' f) as [l H]. exists (nodup nat_eq_dec l). apply NoDup_nodup. intros. split; intros. apply nodup_In in H0. apply H; auto. apply nodup_In. apply H; auto. Defined.\n\nTheorem interpret_equiv: forall f a b, (forall n, Vars n f -> a n = b n) -> interpret f a = interpret f b. Proof. induction f; simpl; intros; auto. f_equal. apply IHf; auto. rewrite IHf1 with a b; auto. rewrite IHf2 with a b; auto. Qed.\nFixpoint assign_prep (l:list nat):= match l with nil => (fun _=>false, nil)::nil |n::m => map (fun p=>(fun x=>if nat_eq_dec x n then true else fst p x, (#n)::snd p)) (assign_prep m) ++ map (fun p=>(fst p, (! #n)::snd p)) (assign_prep m) end.\nTheorem assign_prep_spec1: forall l n p, In p (assign_prep l) -> In n l <-> In (# n) (snd p) \\/ In (! #n) (snd p). Proof. induction l; simpl; intros. destruct H. destruct p. simpl. split; intros. destruct H0. inversion H. subst l. destruct H0; destruct H0. destruct H.  apply in_app_or in H. destruct H; apply in_map_iff in H; destruct H as [y [H3 H4]]; subst p; simpl; split; intros. destruct H. subst a; auto. destruct (IHl n y); auto. apply H0 in H. destruct H; auto. destruct H. destruct H. inversion H; auto. right. destruct (IHl n y); auto. destruct H. inversion H. right. destruct (IHl n y); auto. destruct H. subst a; auto. destruct (IHl n y); auto. apply H0 in H. destruct H; auto. destruct H. destruct H. inversion H. right. destruct (IHl n y); auto. destruct H. inversion H; auto. right. destruct (IHl n y); auto. Qed.\nTheorem assign_prep_spec2: forall l n p, In p (assign_prep l) -> ~In n l -> fst p n=false. Proof. induction l; simpl; intros. destruct H. destruct p. destruct H. auto. destruct H. apply in_app_or in H. destruct H; apply in_map_iff in H; destruct H as [y [H1 H2]]; subst p; simpl. destruct (nat_eq_dec n a). contradict H0; auto. apply IHl; auto. apply IHl; auto. Qed.\nTheorem assign_prep_spec3: forall l n p, NoDup l -> In p (assign_prep l) -> In n l -> fst p n=true <-> In (# n) (snd p). Proof. intros l n p H. revert n p. induction H; intros. destruct H0. simpl in H1. apply in_app_or in H1. destruct H1; apply in_map_iff in H1; destruct H1 as [y [H3 H4]]; subst p; destruct H2; simpl. subst x; simpl. destruct (nat_eq_dec n n). split; intros; auto. contradict n0; auto. destruct (nat_eq_dec n x). subst x. split; intros; auto. split; intros; auto. right. apply IHNoDup; auto. apply IHNoDup; auto. destruct H2; auto. contradict n0; inversion H2; auto.\n  subst x. split; intros. rewrite assign_prep_spec2 with l n y in H1; auto. inversion H1. destruct H1. inversion H1. contradict H. destruct assign_prep_spec1 with l n y; auto. split; intros. right. apply IHNoDup; auto. destruct H2. inversion H2. apply IHNoDup; auto. Qed.\nTheorem assign_prep_spec4: forall l n p, NoDup l -> In p (assign_prep l) -> In n l -> fst p n=false <-> In (! # n) (snd p). Proof. intros l n p H. revert n p. induction H; intros. destruct H0. simpl in H1. apply in_app_or in H1. destruct H1; apply in_map_iff in H1; destruct H1 as [y [H3 H4]]; subst p; destruct H2; simpl. subst x; simpl. destruct (nat_eq_dec n n). split; intros; auto. inversion H1. destruct H1. inversion H1. contradict H. destruct (assign_prep_spec1) with l n y; auto. contradict n0; auto. destruct (nat_eq_dec n x). subst x. split; intros; auto. inversion H2. destruct H2. inversion H2. contradict H. destruct (assign_prep_spec1) with l n y; auto. split; intros; auto. right. apply IHNoDup; auto. destruct H2. inversion H2. apply IHNoDup; auto. subst x. split; intros; auto. apply assign_prep_spec2 with l; auto. split; intros. right. apply IHNoDup; auto. destruct H2. inversion H2.  subst x; contradiction. apply IHNoDup; auto. Qed.\nTheorem assign_prep_spec5: forall l a, NoDup l -> exists p, In p (assign_prep l) /\\ forall n, In n l->a n=fst p n. Proof. intros. induction H; simpl; intros. exists (fun _=>false, nil). split; auto. destruct (IHNoDup) as [[b r] [H1 H2]]. simpl in H2. remember (a x) as c. destruct c. exists (fun y=>if nat_eq_dec y x then true else b y, (#x)::r). split. apply in_or_app. left. apply in_map_iff. exists (b,r); auto. intros. simpl. destruct H3. subst x. destruct (nat_eq_dec n n); auto. contradict n0; auto. destruct (nat_eq_dec n x). subst x. auto. apply H2; auto. exists (b, (! #x)::r). split. apply in_or_app. right. apply in_map_iff. exists (b,r); auto. simpl. intros. destruct H3. subst x. rewrite <- Heqc. rewrite <- assign_prep_spec2 with l n (b,r); auto. auto. Qed.\n\nDefinition Tauto_dec: forall f, {Tautology f}+{~Tautology f}. intros. destruct (vars f) as [l H1 H2]. remember (find (fun p=>negb (interpret f (fst p))) (assign_prep l)). destruct o. right. intros C. symmetry in Heqo. apply find_some in Heqo. destruct Heqo. rewrite C in H0. inversion H0. symmetry in Heqo. left. intros a. destruct (assign_prep_spec5 l a) as [p [H3 H4]]; auto. apply find_none with (x:=p) in Heqo; auto. rewrite interpret_equiv with (b:=fst p); auto. destruct (interpret f (fst p)); auto. intros. apply H4. apply H2; auto. Defined.\nTheorem Theorem_Tauto: forall f, LPTheorem f -> Tautology f. Proof. intros. intros a. induction H. destruct H. simpl. destruct (interpret f a); simpl; auto. apply Bool.orb_true_r. simpl. destruct (interpret h a); destruct (interpret g a); destruct (interpret f a);simpl; auto.  simpl. destruct (interpret g a); destruct (interpret f a); simpl; auto. simpl in IHLPTheorem1. destruct (interpret g a); auto. contradict IHLPTheorem1. rewrite IHLPTheorem2. simpl. discriminate. Qed.\nTheorem interpretTh: forall f (a:nat->bool) l, (forall n, Vars n f->In (if a n then (#n) else (!(#n))) l) -> LPInf l (if (interpret f a) then f else (!(f))). Proof. intros. induction f; intros. simpl. auto. simpl. destruct (interpret f a); simpl; auto. simpl. destruct (interpret f2 a). rewrite Bool.orb_true_r. auto. destruct (interpret f1 a); simpl. apply contra with f2; auto. apply LPIImp with f1; auto. apply InfTh. apply LPabsurd with f1; auto. Qed.\nTheorem Tauto_Theorem: forall f, Tautology f -> LPTheorem f. Proof. intros. cut (forall m, (forall p, In p (assign_prep m) -> LPInf (snd p) f) -> LPTheorem f). intros. destruct (vars f) as [v H1 H2]. apply H0 with v. intros. replace f with (if interpret f (fst p) then f else (!f)). apply interpretTh. intros. remember (fst p n) as b. destruct b. apply assign_prep_spec3 with v; auto. apply H2; auto. apply assign_prep_spec4 with v; auto. apply H2; auto. replace (interpret f (fst p)) with true; auto.\n  induction m; simpl; intros. cut (LPInf (snd (fun _:nat=>false, nil)) f); intros; auto. apply IHm. intros. apply neg_imp with (#a); apply InfTh. replace ((#a)::snd p) with (snd (fun x=>if nat_eq_dec x a then true else fst p x, (#a)::snd p)); auto. apply H0. apply in_or_app. left. apply in_map_iff. exists p; auto. replace ((! # a)::snd p) with (snd (fst p, (! # a)::snd p)); auto. apply H0. apply in_or_app. right. apply in_map_iff. exists p; auto. Qed.\n\nDefinition Theorem_dec: forall f, {LPTheorem f}+{~LPTheorem f}. intros. destruct (Tauto_dec f); [left|right]. apply Tauto_Theorem; auto. contradict n. apply Theorem_Tauto; auto. Defined.\n", "meta": {"author": "ysfmssk", "repo": "coq", "sha": "07e0aa439df36339e3b6a27c3699a34f6eee4f8a", "save_path": "github-repos/coq/ysfmssk-coq", "path": "github-repos/coq/ysfmssk-coq/coq-07e0aa439df36339e3b6a27c3699a34f6eee4f8a/LP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.6784357599365312}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_Euclid4.\nRequire Export GeoCoq.Elements.OriginalProofs.proposition_14.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_righttogether : \n   forall A B C G, \n   Per G A B -> Per B A C -> TS G B A C ->\n   RT G A B B A C /\\ BetS G A C.\nProof.\nintros.\nassert (Per B A G) by (conclude lemma_8_2).\nassert (neq A G) by (conclude_def Per ).\nassert (neq G A) by (conclude lemma_inequalitysymmetric).\nlet Tf:=fresh in\nassert (Tf:exists D, (BetS G A D /\\ Cong A D G A)) by (conclude lemma_extension);destruct Tf as [D];spliter.\nassert (eq B B) by (conclude cn_equalityreflexive).\nassert (neq A B) by (conclude_def Per ).\nassert (Out A B B) by (conclude lemma_ray4).\nassert (Supp G A B B D) by (conclude_def Supp ).\nassert (nCol B A G) by (conclude_def TS ).\nassert (nCol G A B) by (forward_using lemma_NCorder).\nassert (CongA G A B G A B) by (conclude lemma_equalanglesreflexive).\nassert (Col G A D) by (conclude_def Col ).\nassert (neq A D) by (forward_using lemma_betweennotequal).\nassert (neq D A) by (conclude lemma_inequalitysymmetric).\nassert (Per D A B) by (conclude lemma_collinearright).\nassert (Per B A D) by (conclude lemma_8_2).\nassert (CongA B A C B A D) by (conclude lemma_Euclid4).\nassert (RT G A B B A C) by (conclude_def RT ).\nassert (TS C B A G) by (conclude lemma_oppositesidesymmetric).\nassert (BetS G A C) by (conclude proposition_14).\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_righttogether.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.6784357518294503}}
{"text": "(**\nDefinitions for deferred recursion\n*)\n\n(** The fixpoint axiom *)\n\n\nRequire Export HsToCoq.Err.\n\nAxiom deferredFix: forall {a r} `{Default r}, ((a -> r) -> (a -> r)) -> a -> r.\n\n(** Variants for differing arities *)\n\nDefinition deferredFix1 {a r} `{Default r} : ((a -> r) -> (a -> r)) -> a -> r\n  := deferredFix.\n\nDefinition curry : forall {a b r}, (((a * b) -> r) -> a -> b -> r)\n  := fun _ _ _ f x y => f (x, y).\n\nDefinition uncurry : forall {a b r}, ((a -> b -> r) -> (a * b) -> r)\n  := fun _ _ _ f '(x, y) => f x y.\n\nDefinition deferredFix2 {a b r} `{Default r} : ((a -> b -> r) -> (a -> b-> r)) -> a -> b -> r\n  := fun f => curry (deferredFix (fun g => uncurry (f (curry g)))).\n\nDefinition deferredFix3 {a b c r} `{Default r} : ((a -> b -> c -> r) -> (a -> b -> c -> r)) -> a -> b -> c -> r\n  := fun f => curry (deferredFix2 (fun g => uncurry (f (curry g)))).\n\nDefinition deferredFix4 {a b c d r} `{Default r} : ((a -> b -> c -> d -> r) -> (a -> b -> c -> d-> r)) -> a -> b -> c -> d -> r\n  := fun f => curry (deferredFix3 (fun g => uncurry (f (curry g)))).\n\n\n(** The fixpoint unrolling axiom *)\n\n\nDefinition recurses_on {a b} (P : a -> Prop) (R : a -> a -> Prop) (f : (a -> b) -> (a -> b)) :=\n  forall g h x, P x -> (forall y, P y ->  R y x -> g y = h y) -> f g x = f h x.\n\nAxiom deferredFix_eq_on: forall {a b} `{Default b} (f : (a -> b) -> (a -> b)) (P : a -> Prop) (R : a -> a -> Prop),\n   well_founded R -> recurses_on P R f ->\n   forall x, P x -> deferredFix f x = f (deferredFix f) x.\n", "meta": {"author": "plclub", "repo": "hs-to-coq", "sha": "e6401f6f054a2c1ff5e63a17ab8af2bcd5861c9c", "save_path": "github-repos/coq/plclub-hs-to-coq", "path": "github-repos/coq/plclub-hs-to-coq/hs-to-coq-e6401f6f054a2c1ff5e63a17ab8af2bcd5861c9c/examples/base-src/manual/HsToCoq/DeferredFix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.6784357478028232}}
{"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: Lt.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\n(** Theorems about [lt] in nat. [lt] is defined in library [Init/Peano.v] as:\n<<\nDefinition lt (n m:nat) := S n <= m.\nInfix \"<\" := lt : nat_scope.\n>>\n*)\n\nRequire Import Le.\nOpen Local Scope nat_scope.\n\nImplicit Types m n p : nat.\n\n(** * Irreflexivity *)\n\nTheorem lt_irrefl : forall n, ~ n < n.\nProof le_Sn_n.\nHint Resolve lt_irrefl: arith v62.\n\n(** * Relationship between [le] and [lt] *)\n\nTheorem lt_le_S : forall n m, n < m -> S n <= m.\nProof.\n  auto with arith.\nQed.\nHint Immediate lt_le_S: arith v62.\n\nTheorem lt_n_Sm_le : forall n m, n < S m -> n <= m.\nProof.\n  auto with arith.\nQed.\nHint Immediate lt_n_Sm_le: arith v62.\n\nTheorem le_lt_n_Sm : forall n m, n <= m -> n < S m.\nProof.\n  auto with arith.\nQed.\nHint Immediate le_lt_n_Sm: arith v62.\n\nTheorem le_not_lt : forall n m, n <= m -> ~ m < n.\nProof.\n  induction 1; auto with arith.\nQed.\n\nTheorem lt_not_le : forall n m, n < m -> ~ m <= n.\nProof.\n  red in |- *; intros n m Lt Le; exact (le_not_lt m n Le Lt).\nQed.\nHint Immediate le_not_lt lt_not_le: arith v62.\n\n(** * Asymmetry *)\n\nTheorem lt_asym : forall n m, n < m -> ~ m < n.\nProof.\n  induction 1; auto with arith.\nQed.\n\n(** * Order and successor *)\n\nTheorem lt_n_Sn : forall n, n < S n.\nProof.\n  auto with arith.\nQed.\nHint Resolve lt_n_Sn: arith v62.\n\nTheorem lt_S : forall n m, n < m -> n < S m.\nProof.\n  auto with arith.\nQed.\nHint Resolve lt_S: arith v62.\n\nTheorem lt_n_S : forall n m, n < m -> S n < S m.\nProof.\n  auto with arith.\nQed.\nHint Resolve lt_n_S: arith v62.\n\nTheorem lt_S_n : forall n m, S n < S m -> n < m.\nProof.\n  auto with arith.\nQed.\nHint Immediate lt_S_n: arith v62.\n\nTheorem lt_0_Sn : forall n, 0 < S n.\nProof.\n  auto with arith.\nQed.\nHint Resolve lt_0_Sn: arith v62.\n\nTheorem lt_n_O : forall n, ~ n < 0.\nProof le_Sn_O.\nHint Resolve lt_n_O: arith v62.\n\n(** * Predecessor *)\n\nLemma S_pred : forall n m, m < n -> n = S (pred n).\nProof.\ninduction 1; auto with arith.\nQed.\n\nLemma lt_pred : forall n m, S n < m -> n < pred m.\nProof.\ninduction 1; simpl in |- *; auto with arith.\nQed.\nHint Immediate lt_pred: arith v62.\n\nLemma lt_pred_n_n : forall n, 0 < n -> pred n < n.\ndestruct 1; simpl in |- *; auto with arith.\nQed.\nHint Resolve lt_pred_n_n: arith v62.\n\n(** * Transitivity properties *)\n\nTheorem lt_trans : forall n m p, n < m -> m < p -> n < p.\nProof.\n  induction 2; auto with arith.\nQed.\n\nTheorem lt_le_trans : forall n m p, n < m -> m <= p -> n < p.\nProof.\n  induction 2; auto with arith.\nQed.\n\nTheorem le_lt_trans : forall n m p, n <= m -> m < p -> n < p.\nProof.\n  induction 2; auto with arith.\nQed.\n\nHint Resolve lt_trans lt_le_trans le_lt_trans: arith v62.\n\n(** * Large = strict or equal *)\n\nTheorem le_lt_or_eq : forall n m, n <= m -> n < m \\/ n = m.\nProof.\n  induction 1; auto with arith.\nQed.\n\nTheorem le_lt_or_eq_iff : forall n m, n <= m <-> n < m \\/ n = m.\nProof.\n  split.\n  intros; apply le_lt_or_eq; auto.\n  destruct 1; subst; auto with arith.\nQed.\n\nTheorem lt_le_weak : forall n m, n < m -> n <= m.\nProof.\n  auto with arith.\nQed.\nHint Immediate lt_le_weak: arith v62.\n\n(** * Dichotomy *)\n\nTheorem le_or_lt : forall n m, n <= m \\/ m < n.\nProof.\n  intros n m; pattern n, m in |- *; apply nat_double_ind; auto with arith.\n  induction 1; auto with arith.\nQed.\n\nTheorem nat_total_order : forall n m, n <> m -> n < m \\/ m < n.\nProof.\n  intros m n diff.\n  elim (le_or_lt n m); [ intro H'0 | auto with arith ].\n  elim (le_lt_or_eq n m); auto with arith.\n  intro H'; elim diff; auto with arith.\nQed.\n\n(** * Comparison to 0 *)\n\nTheorem neq_0_lt : forall n, 0 <> n -> 0 < n.\nProof.\n  induction n; auto with arith.\n  intros; absurd (0 = 0); trivial with arith.\nQed.\nHint Immediate neq_0_lt: arith v62.\n\nTheorem lt_0_neq : forall n, 0 < n -> 0 <> n.\nProof.\n  induction 1; auto with arith.\nQed.\nHint Immediate lt_0_neq: arith v62.\n\n(* begin hide *)\nNotation lt_O_Sn := lt_0_Sn (only parsing).\nNotation neq_O_lt := neq_0_lt (only parsing).\nNotation lt_O_neq := lt_0_neq (only parsing).\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/Lt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.6784357477489966}}
{"text": "Require Import Coq.Sets.Ensembles.\nRequire Import Logic.GeneralLogic.KripkeModel.\nRequire Import Logic.SeparationLogic.Model.SeparationAlgebra.\n\nLocal Open Scope kripke_model.\nImport KripkeModelNotation_Intuitionistic.\n\nDefinition cut {worlds: Type} {J: Join worlds} (m: worlds) (P: worlds -> Prop) (n: worlds) : Prop :=\n  exists m', join m' n m /\\ P m'.\n\nDefinition greatest_cut {worlds: Type} {R: Relation worlds} {J: Join worlds} (m: worlds) (P: worlds -> Prop) (n: worlds) : Prop :=\n  cut m P n /\\ (forall n', cut m P n' -> n' <= n).\n\nDefinition Kdenote_precise {worlds: Type} {R: Relation worlds} {J: Join worlds} (P: Ensemble worlds): Prop :=\n  forall m n, cut m P n ->\n    exists n, greatest_cut m P n.\n\nRequire Import Logic.GeneralLogic.Base.\n\nLocal Open Scope logic_base.\nImport KripkeModelFamilyNotation.\n\nDefinition sem_precise\n        {L: Language}\n        {MD: Model}\n        {kMD: KripkeModel MD}\n        {M: Kmodel}\n        {R: Relation (Kworlds M)}\n        {J: Join (Kworlds M)}\n        {SM: Semantics L MD}\n        (x: expr): Prop :=\n  Kdenote_precise (Kdenotation M x).\n", "meta": {"author": "QinxiangCao", "repo": "UnifySL", "sha": "cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d", "save_path": "github-repos/coq/QinxiangCao-UnifySL", "path": "github-repos/coq/QinxiangCao-UnifySL/UnifySL-cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d/SeparationLogic/Semantics/SemanticsExtension.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895028, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6784305595135026}}
{"text": "\n\nRequire Export Ch10_Smallstep.\n\n\nInductive Sec : Type :=\n| L : Sec\n| H : Sec.\n\nInductive Ty : Type :=\n| an : RawTy -> Sec -> Ty\nwith RawTy : Type :=\n     | int : RawTy\n     | fn  : Ty -> Ty -> RawTy.\n\nScheme Ty_mut := Induction for Ty Sort Prop\nwith RawTy_ := Induction for RawTy Sort Prop.\n\nCheck (an int H).\nCheck (an int L).\nCheck (an (fn (an int L)(an int H)) L).\nCheck (an (fn (an int H)(an int H)) H).\nCheck (an (fn (an int H)(an (fn (an int H)(an int H)) H)) H).\nCheck (an (fn (an (fn (an int H)(an int H)) H)(an int L)) L).\n\n(*############subtyping#################*)\nInductive subsum_r : Sec -> Sec -> Prop :=\n| sub_refl: forall b : Sec, \n          subsum_r b b\n| sub_LH: subsum_r L H\n.\n\nLemma subsum_r_trans: forall a b c,\nsubsum_r a b ->\nsubsum_r b c ->\nsubsum_r a c.\nProof. intros. inversion H0. subst. inversion H1. subst.\n       apply sub_refl. apply sub_LH. destruct c. apply sub_refl.\n       apply sub_LH.\nQed.\n\nExample test_subsum_r_1:\nsubsum_r L L.\nProof. apply sub_refl. Qed.\nExample test_subsum_r_2:\nsubsum_r H H.\nProof. apply sub_refl. Qed.\nExample test_subsum_r_3:\nsubsum_r L H.\nProof. apply sub_LH. Qed.\n\n\nInductive subtyping : Ty -> Ty -> Prop :=\n| subt_int: forall b b',\n           subsum_r b b' -> \n           (an int b) < (an int b')\n| subt_fn: forall b b' T1 T1' T2 T2',\n           subsum_r b b' ->\n           T1' < T1 ->\n           T2 < T2' ->\n           (an (fn T1 T2) b) < (an (fn T1' T2') b')\nwhere \"t1  '<' t2\" := (subtyping t1 t2).\n\nLemma subtyping_refl: forall T,\nT < T.\nProof. apply (Ty_mut (fun T => T < T) (fun RT => forall b, (an RT b) < (an RT b))).\nintros. apply H0.\nintros. apply subt_int. apply sub_refl.\nintros. apply subt_fn. apply sub_refl. apply H0. apply H1. \nQed. \n       \n\nLemma subtyping_trans: forall y z x z',\nx < y -> z < x -> y < z' ->  z < z'.\nProof. intros.  generalize dependent z. generalize dependent z'. induction H0.\n       intros.\n       inversion H2. subst. inversion H1. subst. apply subt_int.  apply subsum_r_trans with (a:=b0)(b:=b)(c:=b')in H6.\n       apply subsum_r_trans with (a:=b0)(b:=b')(c:=b'0) in H6. apply H6. apply H4. apply H0. \n       intros. inversion H1. subst. inversion H2. subst. \n       apply subt_fn. apply subsum_r_trans with (a:=b0)(b:=b)(c:=b') in H7.\n       apply subsum_r_trans with (a:=b0)(b:=b')(c:=b'0) in H7. apply H7. apply H6. apply H0.\n       apply IHsubtyping1. apply H8. apply H11.\n       apply IHsubtyping2. apply H12. apply H9.\nQed.\n      \nExample apply_trans: forall x y z,\nx < y -> y < z -> x < z.\nProof. intros. apply subtyping_trans with (x:=y)(y:=y).  apply subtyping_refl.\n        apply H0. apply H1. Qed.      \n         \n(*####some tests of [subtyping]########*)     \nExample test_subtyping_1:\nsubtyping (an int L)(an int L).\nProof.  apply subt_int. apply sub_refl. Qed.\nExample test_subtyping_2:\n~subtyping (an int H)(an int L).\nProof. intros contra. inversion contra. subst. inversion H2. Qed.\nExample test_subtyping_3:\nsubtyping (an (fn (an int H)(an int L)) L)(an (fn (an int L)(an int H)) H).\nProof. apply subt_fn. apply sub_LH. apply subt_int. apply sub_LH. apply subt_int. apply sub_LH.\nQed.\nExample test_subtyping_4:\n~subtyping (an int L) (an (fn (an int H)(an int H)) H).\nProof. intros contra. inversion contra. Qed.\nExample test_subtyping_5:\n~subtyping (an (fn (an int L)(an int H)) H)(an int L).\nProof. intros contra. inversion contra. Qed.\nExample test_subtyping_6:\nsubtyping (an (fn (an int H)(an int L)) L)(an (fn (an int L)(an int L)) L).\nProof. apply subt_fn. apply sub_refl. apply subt_int.\n       apply sub_LH. apply subt_int. apply sub_refl. \n       Qed.\nExample test_subtyping_7:\nsubtyping (an int L)(an int H).\nProof. apply subt_int. apply sub_LH. Qed.\nExample test_subtyping_8:\nsubtyping (an (fn (an int H)(an int L)) L)(an (fn (an int H)(an int H)) H).\nProof. apply subt_fn. apply sub_LH. apply subt_int.\n       apply sub_refl. apply subt_int. apply sub_LH. \n       Qed.\nExample test_subtyping_9:\n~subtyping (an (fn(an int H)(an int H)) H)(an (fn(an int H)(an int L)) L).\nProof. intros contra. inversion contra. subst. inversion H4. Qed.\nExample test_subtyping_10:\n~subtyping (an (fn (an int L)(an int L)) L)(an (fn (an int H)(an int H)) H).\nProof. intros contra. inversion contra. subst. inversion H7. inversion H2. Qed. \nExample test_subtyping_11:\nsubtyping (an (fn (an int L)(an int L)) L)(an (fn (an int L)(an int L)) L).\nProof. apply subt_fn. apply sub_refl. apply subt_int.\n       apply sub_refl. apply subt_int. apply sub_refl. Qed.\n\n\n\n(*############typing context############*)\n\nDefinition context := id -> option Ty.\n\nDefinition empty_context : context := \n  fun _ => None.\n \nDefinition Cupdate (St : context) (X:id) (T : option Ty) : context :=\n  fun X' => if beq_id X X' then T else St X'.\n\n(*#######some useful theorems regarding [update]#########*)\nTheorem Cupdate_eq : forall T X St,\n  (Cupdate St X T) X = T.\nProof.\nintros. unfold Cupdate. rewrite<-beq_id_refl. reflexivity. \nQed.\nTheorem Cupdate_neq : forall X2 X1 T St,\n  beq_id X2 X1 = false ->\n  (Cupdate St X2 T) X1 = (St X1).\nProof.\nintros. unfold Cupdate. rewrite H0. reflexivity.\nQed.\nTheorem Cupdate_shadow : forall T1 T2 X1 X2 (f : context),\n   (Cupdate  (Cupdate f X2 T1) X2 T2) X1 = (Cupdate f X2 T2) X1.\nProof.\nintros. unfold Cupdate. destruct (beq_id X2 X1). reflexivity.\nreflexivity.\nQed.\nTheorem Cupdate_same : forall T1 X1 X2 (f : context),\n  f X1 = T1 ->\n  (Cupdate f X1 T1) X2 = f X2.\nProof.\nintros. unfold Cupdate. remember (beq_id X1 X2) as D. destruct D.\nCase (\"true\"). apply beq_id_eq in HeqD. subst. reflexivity.\nreflexivity.\nQed. \nTheorem Cupdate_permute : forall T1 T2 X1 X2 X3 f,\n  beq_id X2 X1 = false -> \n  (Cupdate (Cupdate f X2 T1) X1 T2) X3 = (Cupdate (Cupdate f X1 T2) X2 T1) X3.\nProof.\nintros. unfold Cupdate. remember (beq_id X1 X3) as D1. remember (beq_id X2 X3) as D2.\ndestruct D1.\nCase (\"D1=true\"). destruct D2.\n      SCase (\"D2=true\"). apply beq_id_false_not_eq in H0.  apply beq_id_eq in HeqD1.\n                         apply beq_id_eq in HeqD2. rewrite<-HeqD2 in HeqD1.\n                         unfold not in H0. symmetry in HeqD1. apply H0 in HeqD1.\n                         inversion HeqD1.\n      SCase (\"D2=false\"). reflexivity.\nCase (\"D1=false\"). destruct D2.\n      SCase (\"D2=true\"). reflexivity.\n      SCase (\"D2=false\"). reflexivity.\nQed.\n\nAxiom functional_extensionality : forall {X Y: Type} {f g : X -> Y},\n    (forall (x: X), f x = g x) ->  f = g.\n\nModule SecLang.\n\nInductive tm : Type :=\n| tvar  : id -> tm \n| tprot : Sec -> tm -> tm\n| tcon  : nat -> Sec -> tm\n| tabs  : id -> Ty -> tm -> Sec -> tm\n| tapp  : tm -> tm -> tm\n.\n\nCheck tvar (Id 0).\nCheck tcon 1 H.\nCheck tcon 2 L.\nCheck tabs (Id 0) (an int L) (tvar (Id 0)) H.\nCheck tabs (Id 1) (an (fn (an int H)(an int H)) L) (tvar (Id 1)) H.\nCheck tabs (Id 0) (an int H) (tabs (Id 1) (an int L) (tvar (Id 0)) H) H.\nCheck tapp (tabs (Id 0) (an int H) (tvar (Id 0)) H) (tcon 1 H).\nCheck tprot H (tcon 2 L).\nCheck tprot H (tabs (Id 0)(an int L)(tvar (Id 0)) L).\nCheck tprot H (tapp (tabs (Id 0)(an int L)(tvar (Id 0)) L)(tcon 1 L)).\nCheck tabs (Id 0)(an int L)(tprot H (tvar (Id 0))) L.\nCheck tapp (tabs (Id 0)(an int H)(tvar (Id 0)) H)(tprot H (tcon 2 L)).\nCheck tapp (tprot H (tabs (Id 0)(an int L)(tvar (Id 0)) L))(tcon 1 L).\n\n\nInductive value : tm -> Prop :=\n| v_c : forall b n,\n        value (tcon n b)\n| v_f : forall n T e b,\n        value (tabs (Id n) T e b).\n\n\n\n\nFixpoint subst (x:id) (s:tm) (t:tm): tm :=\n  match t with\n(*variables*)\n  | tvar x' => \n      if beq_id x x' then s  else t\n(*protects*)\n  | tprot b t' =>\n      tprot b (subst x s t')\n(*abstractions*)\n  | tabs x' T t1 b => \n      tabs x' T (if beq_id x x' then t1 else (subst x s t1)) b\n(*constants*)\n  | tcon n b => tcon n b\n(*applications*)\n  | tapp t1 t2 => \n      tapp (subst x s t1) (subst x s t2)\n  end.\nNotation \"'[' x ':=' s ']' t\" := (subst x s t) (at level 20).\n\n\n(*############tests of [subst]##############*)\nExample test_subst_1:\n[(Id 0) := (tabs (Id 0)(an int L)(tvar (Id 0)) L)] (tvar (Id 0)) \n= tabs (Id 0)(an int L)(tvar (Id 0)) L.\nProof. simpl. reflexivity. Qed.\nExample test_subst_2:\n[(Id 0) := tcon 1 H](tvar (Id 1)) = tvar (Id 1).\nProof. simpl. reflexivity. Qed.\nExample test_subst_3:\n[(Id 0) := (tcon 1 H)] (tabs (Id 1) (an int H) (tvar (Id 0)) H)\n= tabs (Id 1) (an int H) (tcon 1 H) H.\nProof. simpl. reflexivity. Qed.\nExample test_subst_4:\n[(Id 0) := (tcon 1 L)](tabs (Id 0)(an int L)(tvar (Id 0)) L)\n= tabs (Id 0)(an int L)(tvar (Id 0)) L.\nProof. simpl. reflexivity. Qed.\nExample test_subst_5:\n[(Id 0) := tcon 4 L] (tcon 1 H) = tcon 1 H.\nProof. simpl. reflexivity. Qed.\nExample test_subst_6:\n[(Id 0) := tcon 1 H] (tapp (tabs (Id 0) (an int H) (tvar (Id 0)) H)(tvar (Id 0)))\n= tapp (tabs (Id 0) (an int H) (tvar (Id 0)) H)(tcon 1 H).\nProof. simpl. reflexivity. Qed.\nExample test_subst_7:\n[(Id 0) := tcon 1 L](tprot H (tvar (Id 0))) = tprot H (tcon 1 L).\nProof. simpl. reflexivity. Qed.\nExample test_subst_8:\n[(Id 0) := tcon 1 H](tprot H (tcon 1 L)) = tprot H (tcon 1 L).\nProof. simpl. reflexivity. Qed.\nExample test_subst_9:\n[(Id 0) := tcon 1 L](tprot H (tabs (Id 1)(an int L)(tvar (Id 0)) L))\n= tprot H (tabs (Id 1)(an int L)(tcon 1 L) L).\nProof. simpl. reflexivity. Qed.\nExample test_subst_10:\n[(Id 0) := tcon 1 L](tabs (Id 1)(an int H)(tprot H (tvar (Id 0))) L)\n= tabs (Id 1)(an int H)(tprot H (tcon 1 L)) L.\nProof. simpl. reflexivity. Qed.\nExample test_subst_11:\n[(Id 0) := tcon 1 L](tapp (tabs (Id 0)(an int L)(tprot H (tvar (Id 0))) H)(tprot H (tvar (Id 0))))\n= tapp (tabs (Id 0)(an int L)(tprot H (tvar (Id 0))) H)(tprot H (tcon 1 L)).\nProof. simpl. reflexivity. Qed.\n\n\nInductive step : tm  -> tm  -> Prop :=\n\n| st_prot: forall b t t',\n  t ==> t' ->\n  tprot b t ==> tprot b t'\n| st_protL: forall v,\n  value v ->\n  tprot L v ==> v\n| st_protHf: forall x T e b,\n  tprot H (tabs x T e b) ==> tabs x T e H\n| st_protHc: forall n b,\n  tprot H (tcon n b) ==> tcon n H\n| st_appabs: forall x T e b v,\n  value v ->\n  tapp (tabs x T e b) v ==> tprot b ([x := v]e) \n| st_app1: forall t1 t1' t2,\n  t1  ==> t1'  ->\n  tapp t1 t2  ==> tapp t1' t2 \n| st_app2: forall v1 t2 t2',\n  value v1 ->\n  t2  ==> t2'  ->\n  tapp v1 t2  ==> tapp v1 t2' \n\nwhere \"t1  '==>' t2 \" := (step t1 t2).\n\nDefinition multistep := (multi step).\nNotation \"t1  '==>*' t2\" := (multistep t1 t2) \n  (at level 40).\n\n(*##############tests of [step]###########*)\nExample test_step_1:\ntapp (tabs (Id 0)(an int L)(tvar (Id 0)) H)(tcon 1 L) \n==>* tcon 1 H.\nProof. apply multi_step with (y:= tprot H ([(Id 0) := tcon 1 L](tvar (Id 0)))).\napply st_appabs. apply v_c. simpl. apply multi_step with (y:=tcon 1 H).\napply st_protHc. apply multi_refl.\nQed.\n\nExample test_step_2:\ntapp (\n      tapp \n           (tabs (Id 1)(an int L)(tabs (Id 0)(an int L)(tvar (Id 0)) L) H)\n           (tcon 1 L) \n     )\n     (\n      tapp \n           (tabs (Id 0)(an int L)(tvar (Id 0)) L)\n           (tcon 1 L)\n     ) \n==>* tcon 1 H.\nProof. apply multi_step with (y:=(tapp (tprot H ([(Id 1) := tcon 1 L](tabs (Id 0)(an int L)(tvar (Id 0)) L)))(tapp (tabs (Id 0)(an int L)(tvar (Id 0)) L)(tcon 1 L)))).\napply st_app1. apply st_appabs. apply v_c.\napply multi_step with (y:= (tapp (tabs (Id 0)(an int L)(tvar (Id 0)) H)(tapp (tabs (Id 0)(an int L)(tvar (Id 0)) L)(tcon 1 L)))).\napply st_app1. apply st_protHf. \napply multi_step with (y:= tapp (tabs (Id 0)(an int L)(tvar (Id 0)) H)(tprot L ([(Id 0) := tcon 1 L](tvar (Id 0))))). \napply st_app2. apply v_f. apply st_appabs. apply v_c.\napply multi_step with (y:= tapp (tabs (Id 0)(an int L)(tvar (Id 0)) H)(tcon 1 L)). apply st_app2. apply v_f.\napply st_protL. apply v_c. \napply multi_step with (y:= tprot H ([(Id 0) := tcon 1 L](tvar (Id 0)))). apply st_appabs. apply v_c.\napply multi_step with (y:= tcon 1 H). simpl. apply st_protHc. \napply multi_refl.\nQed.\nExample test_step_3:\ntapp (tabs (Id 1)(an int H)(tabs (Id 0)(an int L)(tvar (Id 0)) L) H)(tcon 1 H)\n==>* tabs (Id 0)(an int L)(tvar (Id 0)) H.\nProof. apply multi_step with (y:= tprot H ([(Id 1) := tcon 1 H](tabs (Id 0)(an int L)(tvar (Id 0)) L))).\napply st_appabs. apply v_c. \napply multi_step with (y:= tabs (Id 0)(an int L)(tvar (Id 0)) H). simpl. apply st_protHf.\napply multi_refl.\nQed.\nExample test_step_4:\ntapp (tabs (Id 0)(an (fn (an int L)(an int L)) L)(tvar (Id 0)) H)\n     (tabs (Id 0)(an int L)(tvar (Id 0)) L)\n==>* tabs (Id 0)(an int L)(tvar (Id 0)) H.\nProof. apply multi_step with (y:= tprot H ([(Id 0) := tabs (Id 0)(an int L)(tvar (Id 0)) L](tvar (Id 0)))).\napply st_appabs. apply v_f. apply multi_step with (y:= tabs (Id 0)(an int L)(tvar (Id 0)) H).\nsimpl. apply st_protHf. apply multi_refl.\nQed.\nExample test_step_5:\ntapp (tabs (Id 0)(an (fn (an int L) (an int L)) L)(tvar (Id 0)) H)\n     (tabs (Id 0) (an int L)(tvar (Id 1)) L) \n==>* tabs (Id 0)(an int L)(tvar (Id 1)) H.\nProof. apply multi_step with (y:= tprot H ([(Id 0) := tabs (Id 0)(an int L)(tvar (Id 1)) L ](tvar (Id 0)))).\napply st_appabs. apply v_f. \napply multi_step with (y:= tabs (Id 0)(an int L)(tvar (Id 1)) H). simpl. apply st_protHf. \napply multi_refl.\n Qed.\nExample test_step_6:\ntapp (tabs (Id 1)(an int H)(tprot H (tvar (Id 0))) L) (tcon  1 H) \n==> tprot L (tprot H (tvar (Id 0))).\nProof. apply st_appabs. apply v_c.\nQed.\nExample test_step_7:\ntapp (tabs (Id 0)(an int H)(tprot H (tvar (Id 0))) L) (tcon  1 H) \n==>* tcon 1 H.\nProof. apply multi_step with (y:= tprot L ([(Id 0) := tcon 1 H](tprot H (tvar (Id 0))))).\napply st_appabs. apply v_c. simpl.\napply multi_step with (y:= tprot L (tcon 1 H)). apply st_prot. apply st_protHc.\napply multi_step with (y:= tcon 1 H).  apply st_protL. apply v_c. \napply multi_refl.\n Qed.\nExample test_step_8:\ntapp (tabs (Id 0)(an int H)(tvar (Id 0)) H) (tprot H (tcon 1 L))\n==>* tcon 1 H.\nProof. apply multi_step with (y:= tapp (tabs (Id 0)(an int H)(tvar (Id 0)) H)(tcon 1 H)).\napply st_app2. apply v_f. apply st_protHc. \napply multi_step with (y:= tprot H ([(Id 0) := tcon 1 H](tvar (Id 0)))). apply st_appabs.\napply v_c. simpl. apply multi_step with (y:= tcon 1 H). apply st_protHc.\napply multi_refl.\nQed.\nExample test_step_9:\ntprot H (tapp (tabs (Id 0)(an int L)(tvar (Id 0)) L)(tcon 1 L))\n==>* tcon 1 H.\nProof. apply multi_step with (y:= tprot H (tprot L ([(Id 0) := tcon 1 L](tvar (Id 0))))).\napply st_prot. apply st_appabs. apply v_c. \napply multi_step with (y:= tprot H (tcon 1 L)). apply st_prot. simpl. apply st_protL. apply v_c.\napply multi_step with (y:= tcon 1 H). apply st_protHc.\napply multi_refl.\nQed.\nExample test_step_10:\n~ tprot H (tvar (Id 0)) ==> tcon 1 H.\nProof. intros contra. inversion contra.\nQed.\n\n(*####################Typing rules###########################*)\n(**\nIn what follows, we will specify the typing rules of the system.\nOne intuitive way of doing it is that we suppose that before reduction,\nwe have a \"typing context\" as follows,\ncontext := id -> option Ty \nwhich maps each variable to a type.\n\nWe have the following typing rules given a certain typing context\n\"Gamma\",\n\na. t_var\n Gamma (Id n) = T\n-------------------------------(t_var)\n Gamma |- tvar (Id n) : T \n\nb. t_prot\n Gamma | t : T\n-----------------------------------------(t_prot)\n Gamma |- tprot b t: join T b \nwhere [join] is a function whcih upon a security\nlabel [b] and a type [T] returns a type with the\nsecurity level at least as high as that of [T].\n\nc. t_con\n Gamma  |- (tcon n b) : an int b\n\nd. t_abs\n update Gamma x T1 |- e : T2\n------------------------------------(t_abs)\n Gamma |- tabs x T1 e b : an (fn T1 T2) b  \n\ne. t_app\n  Gamma |- t1 : Ann (fn T1 T2) b\n  Gamma |- t2 : T1\n----------------------------------(t_app)\n  Gamma |- tapp t1 t2 : join T2 b\n\n*)\n\n\n\n\n\n(*##########join#########*)\nDefinition join (T:Ty) (b:Sec): Ty :=\n match b with\n | L => T\n | H => match T with\n        | an R b => an R H\n        end\n end.\nExample test_join_1:\n join (an int L) H = an int H.\nProof. simpl. reflexivity. Qed.\nExample test_join_2:\n join (an (fn (an int L)(an int L)) L) H = an (fn (an int L)(an int L)) H.\nProof. simpl. reflexivity. Qed.\n\n(**\nNote:\nAdd sub-typing relation, referring to Lu's paper...\n*)\nInductive has_type : context  -> tm -> Ty -> Prop :=\n| t_var: forall Gamma n T,\n  Gamma (Id n) = Some T ->\n  has_type Gamma (tvar (Id n)) T\n| t_prot: forall Gamma t T T' b,\n  has_type Gamma t T ->\n  join T b = T' ->\n  has_type Gamma (tprot b t) T'\n| t_con: forall Gamma n b,\n  has_type Gamma (tcon n b) (an int b)\n| t_abs: forall Gamma T1 T2 b e x,\n  has_type (Cupdate Gamma x (Some T1)) e T2 ->\n  has_type Gamma (tabs x T1 e b) (an (fn T1 T2) b)\n| t_app: forall Gamma T1 T2 T2' b t1 t2,\n  has_type Gamma t1 (an (fn T1 T2) b) ->\n  has_type Gamma t2 T1 ->\n  join T2 b = T2' ->\n  has_type Gamma (tapp t1 t2) T2'\n| t_sub: forall Gamma t T T',\n  has_type Gamma t T ->\n  T < T' ->\n  has_type Gamma t T'.\n\n(*#######inversions of [has_type]##########*)\n(*some auxiliary lemmas*)\n \n(*end*)\n(*inversion of [has_type Gamma (tvar x) T]*)\nLemma inversion_tvar: forall Gamma x T,\nhas_type Gamma (tvar x) T ->\nexists T0, (Gamma x = Some T0)/\\(T0 < T).\nProof. intros. remember (tvar x) as t. induction H0.\ninversion Heqt. subst. exists T. split. apply H0. apply subtyping_refl.\nsubst. inversion Heqt. inversion Heqt. inversion Heqt. inversion Heqt.\napply IHhas_type in Heqt. inversion Heqt. exists x0. split. inversion H2.\napply H3. inversion H2. apply subtyping_trans with (x:=T)(y:=T). apply subtyping_refl.\napply H4. apply H1.\nQed.\n\n(*inversion of [has_type Gamma (tabs x T1 e b) T]*)\n(**     \nLemma inversion_tabs: forall Gamma x T1 T e b,\nhas_type Gamma (tabs x T1 e b) T ->\n(exists T1', exists T2', exists b', \nhas_type (Cupdate Gamma x (Some T1)) e T2'/\\(T1' < T1)/\\(subsum_r b b')/\\((an (fn T1' T2') b')< T)).\nProof. intros. remember (tabs x T1 e b) as t. induction H0. inversion Heqt. inversion Heqt. inversion Heqt.\ninversion Heqt. subst. exists T1. exists T2. exists b. split. apply H0. split. apply subtyping_refl.\nsplit. apply sub_refl. apply subtyping_refl. inversion Heqt.\napply IHhas_type in Heqt. inversion Heqt. exists x0. inversion H2. exists x1. inversion H3. exists x2. inversion H4.\nsplit. apply H5. inversion H6. split. apply H7. split. inversion H8. apply H9.\napply subtyping_trans with (x:=T)(y:=T). apply subtyping_refl. inversion H8. apply H10. apply H1.\nQed.\n\nLemma well_typed_tabs: forall Gamma x T1 e b T,\nhas_type Gamma (tabs x T1 e b) T ->\nexists T1', exists T2', exists b', exists T2, \n(has_type Gamma (tabs x T1 e b) (an (fn T1 T2') b))/\\\n(an (fn T1' T2) b' < T)/\\(T1' < T1)/\\(T2'<T2)/\\(subsum_r b b').\nProof.  intros. remember (tabs x T1 e b) as t. induction H0. inversion Heqt.\n        inversion Heqt. inversion Heqt. inversion Heqt. subst. exists T1. exists T2. exists b.\n        exists T2. split. apply t_abs. apply H0.\n        split. apply subtyping_refl. split. apply subtyping_refl. split. apply subtyping_refl. apply sub_refl.\n        inversion Heqt. apply IHhas_type in Heqt. inversion Heqt. inversion H2. inversion H3. inversion H4.\n        inversion H5. exists x0. exists x1. exists x2. exists x3. \n        split. apply  H6. inversion H7. split. apply subtyping_trans with (x:=T)(y:=T).\n        apply subtyping_refl. apply H8. apply H1. apply H9. \nQed.\n*)\nLemma inversion_tabs: forall Gamma x T1 T e b,\nhas_type Gamma (tabs x T1 e b) T ->\nexists T1', exists T2, exists T2', exists b',\n(has_type Gamma (tabs x T1 e b) (an (fn T1 T2) b)) /\\\n(has_type (Cupdate Gamma x (Some T1)) e T2) /\\\n(T1'<T1)/\\(T2<T2')/\\(subsum_r b b')/\\((an (fn T1' T2') b') < T).\nProof. intros. remember (tabs x T1 e b) as t. induction H0. inversion Heqt. inversion Heqt. inversion Heqt.\ninversion Heqt. subst. exists T1. exists T2. exists T2. exists b. split. apply t_abs with (b:=b) in H0. apply H0.\nsplit. apply H0. split. apply subtyping_refl. split. apply subtyping_refl. split. apply sub_refl. apply subtyping_refl.\ninversion Heqt.  apply IHhas_type in Heqt. inversion Heqt. exists x0. inversion H2. exists x1. inversion H3. exists x2.\ninversion H4. exists x3. inversion H5. split. apply H6. inversion H7. split. apply H8. split. inversion H9. apply H10.\nsplit. inversion H9. inversion H11. apply H12. split. inversion H9. inversion H11. inversion H13. apply H14. inversion H9.\ninversion H11. inversion H13. apply subtyping_trans with (x:=T)(y:=T). apply subtyping_refl. apply H15. apply H1.\nQed.\nLemma inversion_tprot: forall Gamma t T b,\nhas_type Gamma (tprot b t) T ->\nexists T', exists T'', (join T' b < T) /\\(has_type Gamma t T'')/\\(T'' < T').\nProof. intros. remember (tprot b t) as e. induction H0. subst. inversion Heqe.\n       inversion Heqe. subst. exists T. exists T. split. apply subtyping_refl.\n       split. apply H0. apply subtyping_refl. inversion Heqe. inversion Heqe.  inversion Heqe.\n       apply IHhas_type in Heqe. inversion Heqe. inversion H2. inversion H3. exists x. exists x0. \n       inversion H5. split. apply subtyping_trans with (x:=T)(y:=T). apply subtyping_refl.\n       apply H4. apply H1. apply H5.\nQed.\n(*inversion of [has_type Gamma (tcon n b) T]*)\n\nLemma inversion_tcon: forall Gamma T n b,\nhas_type Gamma (tcon n b) T ->\nexists T', exists T'', exists b', (T' = an int b)/\\(T'' = an int b')/\\(subsum_r b b')/\\(T'' < T).\nProof. intros. remember (tcon n b) as t. induction H0.\ninversion Heqt. inversion Heqt. inversion Heqt. subst. exists (an int b). exists (an int b).\nexists b. split. reflexivity. split. reflexivity. split. apply sub_refl. apply subtyping_refl.\ninversion Heqt. inversion Heqt.  apply IHhas_type in Heqt. inversion Heqt. exists x. inversion H2.\nexists x0. inversion H3. exists x1. \ninversion H4. split. apply H5. inversion H6. split. apply H7. inversion H8. split. apply H9. \napply subtyping_trans with (x:=T)(y:=T). apply subtyping_refl. apply H10. apply H1.\nQed.\n\n(*inversion of [has_type Gamma (tapp t1 t2) T]*)\nLemma inversion_tapp: forall Gamma t1 t2 T2,\nhas_type Gamma (tapp t1 t2) T2 ->\nexists T1', exists T2', exists b', exists T1'', exists T1''', exists T2'', exists b'',\nhas_type Gamma t1 (an (fn T1' T2') b')/\\((an (fn T1' T2') b')<(an (fn T1'' T2'') b''))/\\\n(has_type Gamma t2 T1''')/\\(T1''' < T1'') /\\\n((join T2'' b'') < T2).\nProof. intros. remember (tapp t1 t2) as t. induction H0.\ninversion Heqt. inversion Heqt. inversion Heqt. inversion Heqt. inversion Heqt. subst. exists T1.\nexists T2. exists b. exists T1. exists T1. exists T2. exists b.\nsplit. apply H0_. split. apply subtyping_refl. split. apply H0_0. split. apply subtyping_refl. \napply subtyping_refl.\n apply IHhas_type in Heqt. inversion Heqt. exists x. inversion H2.\nexists x0. inversion H3. exists x1. inversion H4. exists x2. inversion H5. exists x3. inversion H6. exists x4.\ninversion H7. exists x5. inversion H8.  split. apply H9. inversion H10. split. apply H11. inversion H12.\nsplit. apply H13. inversion H14. split. apply H15. apply subtyping_trans with (x:=T)(y:=T).\napply subtyping_refl. apply H16. apply H1. Qed.\n\n\n\n(*#######some examples of well-typed expressions#############*)\nExample has_type_1:\n has_type (Cupdate empty_context (Id 0) (Some (an int L))) \n          (tapp (tabs (Id 0)(an int L)(tvar (Id 0)) H)(tvar (Id 0)))\n          (an int H).\nProof. apply t_app with (T1:=an int L)(T2:=an int L)(b:=H).\napply t_abs. apply t_var. apply Cupdate_eq.\napply t_var. apply Cupdate_eq. reflexivity.\nQed.\nExample has_type_2:\n has_type empty_context (tapp (tabs (Id 0)(an int L)(tvar (Id 0)) H)(tcon 1 L)) (an int H).\nProof. apply t_app with (T1:=an int L)(T2:=an int L)(b:=H).\napply t_abs. apply t_var. apply Cupdate_eq. apply t_con.\nreflexivity. Qed.\nExample has_type_3:\n has_type (Cupdate empty_context (Id 0)(Some (an int H)))\n          (tvar (Id 0))\n          (an int H).\nProof. apply t_var. apply Cupdate_eq. Qed.\nExample has_type_4:\n has_type (Cupdate empty_context (Id 0)(Some (an int L)))\n          (tprot H (tvar (Id 0)))\n          (an int H).\nProof. apply t_prot with (T:= an int L). apply t_var. apply Cupdate_eq.\nreflexivity. Qed.\nExample has_type_5:\n has_type empty_context\n         (tapp (\n      tapp \n           (tabs (Id 1)(an int L)(tabs (Id 0)(an int L)(tvar (Id 0)) L) H)\n           (tcon 1 L) \n     )\n     (\n      tapp \n           (tabs (Id 0)(an int L)(tvar (Id 0)) L)\n           (tcon 1 L)\n     ))\n     (an int H).\nProof. apply t_app with (T1:=an int L)(T2:=an int L)(b:=H).\napply t_app with (T1:=an int L)(T2:=an (fn (an int L)(an int L)) L)(b:=H).\napply t_abs. apply t_abs. apply t_var. apply Cupdate_eq. apply t_con. reflexivity.\napply t_app with (T1:=an int L)(T2:=an int L)(b:=L). apply t_abs.\napply t_var. apply Cupdate_eq. apply t_con. reflexivity. reflexivity.\nQed.\nExample has_type_6:\n has_type empty_context\n          (tapp (tabs (Id 1)(an int H)(tabs (Id 0)(an int L)(tvar (Id 0)) L) H)(tcon 1 H))\n          (an (fn (an int L)(an int L)) H).\nProof. apply t_app with (T1:=an int H)(T2:=an (fn (an int L)(an int L)) L)(b:=H).\napply t_abs. apply t_abs. apply t_var. apply Cupdate_eq. apply t_con. reflexivity.\nQed.\nExample has_type_7:\n has_type (Cupdate empty_context (Id 0) (Some (an int L)))\n          (tapp (tabs (Id 1)(an int H)(tprot H (tvar (Id 0))) L)(tcon 1 H))\n          (an int H).\nProof. apply t_app with (T1:=an int H)(T2:=an int H)(b:=L).\napply t_abs. apply t_prot with (T:=an int L). apply t_var. \nassert (A:  beq_id (Id 0) (Id 1) = false ). reflexivity. \napply Cupdate_permute with (f:=empty_context)(T1:=Some (an int L))(T2:=Some (an int H))(X3:=(Id 0)) in A.\nrewrite->A. apply Cupdate_eq. reflexivity. apply t_con. reflexivity.\nQed.\nExample has_type_8:\n has_type empty_context\n          (tapp (tabs (Id 0)(an int L)(tprot H (tvar (Id 0))) L)(tcon 1 L))\n          (an int H).\nProof. apply t_app with (T1:=an int L)(T2:= an int H)(b:=L).\napply t_abs. apply t_prot with (T:=an int L). apply t_var.\n apply Cupdate_eq. reflexivity.\napply t_con. reflexivity. Qed.\nExample has_type_9:\nhas_type empty_context (tabs (Id 0)(an int L)(tprot H (tvar (Id 0))) L) (an (fn (an int L)(an int H)) L).\nProof. apply t_abs. apply t_prot with (T:=an int L). apply t_var. apply Cupdate_eq. reflexivity.\nQed.\nExample has_type_10:\nhas_type empty_context (tapp (tabs (Id 0)(an int H)(tvar (Id 0)) L)(tprot H (tcon 1 L)))(an int H).\nProof. apply t_app with (T1:=an int H)(T2:=an int H)(b:= L). apply t_abs. apply t_var. apply Cupdate_eq.\napply t_prot with (T:= an int L). apply t_con. reflexivity. reflexivity.\nQed.\nExample has_type_11:\nhas_type empty_context (tapp (tabs (Id 0)(an int H)(tcon 1 L) H)(tcon 1 L)) (an int H).\nProof. apply t_app with (T1:=an int H)(T2:=an int L)(b:=H). apply t_abs. apply t_con.\n       apply t_sub with (T:=an int L). apply t_con. apply subt_int. apply sub_LH. reflexivity.     \nQed.\nExample has_type_12:\nhas_type empty_context (tabs (Id 0)(an int H)(tcon 1 L) L)(an (fn (an int L)(an int H)) H).\nProof. apply t_sub with (T:=an (fn (an int H)(an int L)) L). apply t_abs. apply t_con.\n       apply subt_fn. apply sub_LH. apply subt_int. apply sub_LH. apply subt_int. apply sub_LH.\nQed.\nExample has_type_13:\nhas_type empty_context (tcon 1 L) (an int H).\nProof. apply t_sub with (T:=an int L). apply t_con. apply subt_int. apply sub_LH.\nQed.\nExample has_type_14:\nhas_type empty_context (tapp (tabs (Id 0)(an int H)(tcon 1 L) H)(tcon 1 L))(an int H).\nProof. apply t_app with (T1:=an int L)(T2:=an int L)(b:=H). apply t_sub with (T:=an (fn (an int H)(an int L)) H).\n       apply t_abs. apply t_con. apply subt_fn. apply sub_refl. apply subt_int. apply sub_LH. apply subt_int.\n       apply sub_refl. apply t_con. reflexivity.\nQed.\nExample has_type_15:\nhas_type empty_context (tapp (tabs (Id 0)(an int L)(tvar (Id 0)) H)(tcon 1 L)) (an int H).\nProof. apply t_app with (T1:=an int L)(T2:=an int H)(b:=H). apply t_abs. apply t_sub with (T:=an int L). apply t_var.\n       apply Cupdate_eq. apply subt_int. apply sub_LH. apply t_con. reflexivity. Qed.    \n\nExample has_type_16:forall Gamma b n,\nhas_type Gamma (tcon n b) (an int b).\nProof. intros. apply t_con. Qed.\n\n\n\n(*############some counter examples##########*)\n\n\n\n(**\nCase 1: undefined or ill-defined free variables\n*)\nExample has_type_i:\n ~has_type empty_context\n           (tvar (Id 0))\n           (an int L).\nProof. intros contra. apply inversion_tvar in contra. inversion contra.\n       inversion H0. inversion H1.\nQed.\nExample has_type_i':\n~has_type (Cupdate empty_context (Id 0) (Some (an int H)))\n         (tvar (Id 0))\n         (an (fn (an int L)(an int L)) H).\nProof. intros contra. apply inversion_tvar in contra. inversion contra.\n       rewrite->Cupdate_eq in H0. inversion H0. inversion H2. subst.\n       inversion H1. Qed.\n(**\nCase 2: ill-typed abstractions whose body contains undefined\n        free variables\n*)\nExample has_type_j:\n~has_type empty_context\n          (tabs (Id 0) (an int L)(tvar  (Id 1)) H)\n          (an (fn (an int L)(an int L)) H).\nProof. intros contra. apply inversion_tabs in contra. inversion contra.\n       inversion H0. inversion H1.  inversion H2. inversion H3. inversion H5.\n       apply inversion_tvar in H6. inversion H6. inversion H8. assert (beq_id (Id 0)(Id 1) = false).\n       apply not_eq_beq_id_false. intros contra'. inversion contra'.\n       apply Cupdate_neq with (T:=Some (an int L))(St:=empty_context) in H11.\n       rewrite->H11 in H9. inversion H9. Qed.\n\nExample has_type_j':\n~has_type (Cupdate empty_context (Id 1)(Some (an int L))) \n          (tabs (Id 0)(an int L)(tvar (Id 2)) L)\n          (an (fn (an int L)(an int H)) L).\nProof. intros contra. apply inversion_tabs in contra. inversion contra.\n       inversion H0. inversion H1. inversion H2. inversion H3. inversion H5.\n       apply inversion_tvar in H6. inversion H6. \n       assert (beq_id (Id 0)(Id 2) = false). apply not_eq_beq_id_false.\n       intros contra'. inversion contra'. apply Cupdate_neq with (T:=Some (an int L))(St:=Cupdate empty_context (Id 1)(Some (an int L))) in H9.\n       inversion H8.\n       rewrite->H9 in H10. assert (beq_id (Id 1)(Id 2)=false). apply not_eq_beq_id_false.\n       intros contra'. inversion contra'.\n       apply Cupdate_neq with (T:=Some (an int L))(St:=empty_context) in H12. rewrite->H12 in H10. \n       inversion H10.\nQed.\n(**\nCase 3: ill-typed abstraction whose type is not a function type\n*)\nExample has_type_j'':\n~has_type empty_context (tabs (Id 0)(an int H)(tvar (Id 1)) H) (an int H).\nProof. intros contra. inversion contra. subst. apply inversion_tabs in H0.\n       inversion H0. inversion H2. inversion H3. inversion H4. inversion H5.\n       inversion H7. inversion H9. inversion H11. inversion H13. destruct T. destruct r. inversion H15.\n       inversion H1.\nQed.\nExample has_type_j''':\n~has_type  empty_context \n          (tabs (Id 0)(an int L)(tvar (Id 0)) H) (an int H).\nProof. intros contra. inversion contra. subst. apply inversion_tabs in H0.\n       inversion H0. inversion H2. inversion H3. inversion H4. inversion H5.\n       inversion H7. inversion H9. inversion H11. inversion H13. destruct T. destruct r.\n       inversion H15. inversion H1.\nQed. \n(**\nCase 4: ill-defined protects\n*) \nExample has_type_k:\n~has_type empty_context (tprot H (tvar (Id 0))) (an int H).\nProof. intros contra. apply inversion_tprot in contra.\n       inversion contra. inversion H0. inversion H1. inversion H3.\n       apply inversion_tvar in H4.\n       inversion H4. inversion H6. inversion H7. Qed.\nExample has_type_k':\n~has_type empty_context (tprot H (tabs (Id 0)(an int H)(tvar (Id 1)) L))\n          (an (fn (an int H)(an int H)) H).\nProof. intros contra. apply inversion_tprot in contra. inversion contra.\n       inversion H0. inversion H1. inversion H3. \n       apply inversion_tabs in H4. inversion H4. inversion H6. inversion H7.\n       inversion H8. inversion H9. inversion H11. apply inversion_tvar in H12. \n        inversion H12. inversion H14.\n        assert (beq_id (Id 0)(Id 1) = false). apply not_eq_beq_id_false.\n       intros contra'. inversion contra'. apply Cupdate_neq with (T:=Some (an int H))(St:=empty_context) in H17.\n       rewrite->H17 in H15. inversion H15. Qed. \nExample has_type_k'':\n~has_type (Cupdate empty_context (Id 0)(Some (an int L))) (tprot H (tabs (Id 0)(an int L)(tvar (Id 0)) L))\n          (an int H).\nProof. intros contra. apply inversion_tprot in contra. inversion contra.\n      inversion H0. inversion H1. inversion H3.\n      apply inversion_tabs in H4. inversion H4. inversion H6. inversion H7.\n      inversion H8. inversion H9. inversion H11. inversion H13. inversion H15.\n      inversion H17. \n      destruct x0. destruct r. inversion H19. destruct x. destruct r.\n      inversion H5. simpl in H2. inversion H2.\nQed.\nExample has_type_k''':\n~has_type empty_context (tprot H (tcon 1 L)) (an int L).\nProof. intros contra. apply inversion_tprot in contra. inversion contra.\ninversion H0. inversion H1. inversion H3. \ndestruct x. destruct r.  simpl in H2. inversion H2. inversion H8. \nsimpl in H2. inversion H2.\nQed.\n(**\nCase 5: ill-typed constants\n*)\nExample has_type_l:\n~has_type empty_context (tprot H (tcon 1 L)) (an int L).\nProof. intros contra. apply inversion_tprot in contra. inversion contra.\ninversion H0. inversion H1. inversion H3. destruct x. destruct r.\nsimpl in H2. inversion H2. inversion H8. simpl in H2. inversion H2.\nQed.\nExample has_type_l':forall Gamma n,\n~has_type Gamma (tcon n H) (an int L).\nProof. intros. intros contra. apply inversion_tcon in contra.\ninversion contra. inversion H0. inversion H1. inversion H2. \ninversion H4. inversion H6. inversion H7. subst. inversion H8.\ninversion H9. Qed.\nExample has_type_l'':forall Gamma n b,\n~has_type Gamma (tcon n b) (an (fn (an int L)(an int L)) L).\nProof. intros. intros contra. apply inversion_tcon in contra.\ninversion contra. inversion H0. inversion H1. inversion H2.\ninversion H4. inversion H6. subst. inversion H8. Qed.\n(**\nCase 6: ill-matched applications\n*)\nExample has_type_m:\n~has_type empty_context\n          (tapp (tabs (Id 0)(an int L)(tcon 2 L) H)(tcon 1 H))\n          (an int H).\nProof. intros contra. apply inversion_tapp in contra. inversion contra.\ninversion H0. inversion H1. inversion H2. inversion H3. inversion H4.\ninversion H5. inversion H6. apply inversion_tabs in H7. inversion H7.\ninversion H9. inversion H10. inversion H11. inversion H12. inversion H14.\ninversion H16. inversion H18. inversion H20. inversion H22. subst. destruct x6.\ndestruct r. destruct s. destruct x. destruct r. destruct s. subst.\ndestruct x2. destruct r. destruct s. inversion H8. inversion H24. inversion H26.\napply inversion_tcon in H25. inversion H25. inversion H32. inversion H33. inversion H34.\ninversion H36. inversion H38. subst. inversion H39. subst. destruct x3. destruct r. destruct s.\ninversion H40. inversion H41. inversion H28. inversion H41. inversion H40.\ninversion H8. inversion H23. inversion H35. inversion H39. inversion H8.\ninversion H23. inversion H35. inversion H30. inversion H25. inversion H30.\ninversion H17. inversion H25. inversion H17.\nQed.\n \n\nExample has_type_m':\n~has_type empty_context\n         (tapp (tabs (Id 0)(an int L)(tvar (Id 0)) L)(tprot H (tcon 1 L)))\n          (an int L).\nProof. intros contra. apply inversion_tapp in contra. inversion contra. inversion H0.\n       inversion H1. inversion H2. inversion H3. inversion H4. inversion H5. inversion\n       H6. inversion H8. inversion H10. apply inversion_tabs in H7. apply inversion_tprot in H11.\n       inversion H11. inversion H13. inversion H14. inversion H16. \n       apply inversion_tcon in H17. inversion H17. inversion H19. inversion H20. inversion H21. \n       inversion H23. subst. inversion H21. inversion H24. subst. inversion H27. \n       inversion H29. subst. inversion H18. subst. \n       inversion H7. inversion H30. inversion H33. inversion H34. inversion H35. inversion H37. inversion H39.\n       inversion H41. inversion H43. \n       destruct x6. destruct r. destruct s. destruct x. destruct r. destruct s. \n       destruct x2. destruct r. destruct s. inversion H12. destruct x3. destruct r. destruct s. simpl in H15.\n       inversion H15. inversion H50. inversion H46. inversion H50. inversion H46. inversion H9. inversion H53.\n       inversion H57. inversion H9. inversion H53. inversion H45. inversion H53. inversion H57. inversion H45.\n       inversion H53. inversion H40. inversion H48. inversion H40.\nQed.\n\n\n\n(**\nCase 7: false applications\n*)\nExample has_type_m'':\n~has_type empty_context\n          (tapp (tcon 1 H)(tcon 2 L))\n          (an int L).\nProof. intros contra. apply inversion_tapp in contra. inversion contra. inversion H0.\n       inversion H1. inversion H2. inversion H3. inversion H4. inversion H5. inversion H6.\n       apply inversion_tcon in H7. inversion H7. inversion H9. inversion H10. inversion H11.\n       inversion H13. subst. inversion H11. inversion H14. inversion H17. inversion H19.        \nQed.\n\n\n(*######Properties########*)\n(**\nThere are two important type safety properties we want to investigate,\na.Progress\n forall Gamma T t t' st, \n has_type Gamma t T ->\n value t \\/ exists t', t / st ==> t' / st\nThat is well-typed terms never get stuck\n\nb. type preservation\n forall Gamma t t' st T,\n has_type Gamma t T ->\n t / st ==> t' / st ->\n has_type Gamma t' T\n  \n*)\n(*############type preserversion############*)\n\n\n(*#################auxiliary theorems##########*)\n(*##########s_p_t_1##############*)\n(*Firstly we use the following proposition to describe free variables*)\nInductive free_var : id -> tm -> Prop :=\n| e_tvar : forall x,\n      free_var x (tvar x)\n| e_tprot : forall x b t,\n      free_var x t ->\n      free_var x (tprot b t)\n| e_tapp1 : forall x e1 e2,\n      free_var x e1 ->\n      free_var x (tapp e1 e2)\n| e_tapp2 : forall x e1 e2,\n      free_var x e2 ->\n      free_var x (tapp e1 e2)\n| e_tabs : forall x y e T b,\n      y <> x ->\n      free_var x e ->\n      free_var x (tabs y T e b).\n\n(*some examples*)\nExample test_free_var_1:\nfree_var (Id 0) (tvar (Id 0)).\nProof. apply e_tvar. Qed.\nExample test_free_var_2:\nfree_var (Id 0) (tvar (Id 0)).\nProof. apply e_tvar. Qed.\nExample test_free_var_3:\nfree_var (Id 1) (tapp (tabs (Id 0)(an int L)(tvar (Id 0)) L)(tvar (Id 1))) .\nProof. apply e_tapp2. apply e_tvar. Qed.\nExample test_free_var_4:\nfree_var (Id 1)(tabs (Id 0)(an int L)(tvar (Id 1)) L).\nProof. apply e_tabs. intros contra. inversion contra. apply e_tvar. Qed.\nExample test_free_var_5:\nfree_var (Id 0) (tprot H (tvar (Id 0))).\nProof. apply e_tprot. apply e_tvar. Qed.\nExample test_free_var_6:\nfree_var (Id 0) (tprot H (tapp (tabs (Id 0)(an int L)(tvar (Id 0)) L)(tvar (Id 0)))).\nProof. apply e_tprot. apply e_tapp2. apply e_tvar. Qed.\nExample test_free_var_7:\nfree_var (Id 1) (tapp (tabs (Id 0)(an int L)(tvar (Id 1)) L)(tprot H (tcon 1 L))).\nProof. apply e_tapp1. apply e_tabs. intros contra. inversion contra. apply e_tvar.\nQed.\nExample test_free_var_8:\nforall x n b, ~free_var x (tcon n b).\nProof. intros. intros contra. inversion contra. Qed.\nExample test_free_var_9:\nforall x T e b,~free_var x (tabs x T e b).\nProof. intros. intros contra. inversion contra. subst. apply H3. reflexivity.\nQed.\nExample test_free_var_10:\nforall x n b b', ~free_var x (tprot b (tcon n b')).\nProof. intros. intros contra. inversion contra. subst. inversion H2.\nQed.\n(*some auxiliary lemmas*)\nTheorem beq_id_eq : forall i1 i2,\n  true = beq_id i1 i2 -> i1 = i2.\nProof. \nintros. unfold beq_id in H0. destruct i1. destruct i2. symmetry in H0.\napply beq_nat_true in H0. subst. reflexivity.\nQed.  \nTheorem not_eq_beq_id_false : forall i1 i2,\n  i1 <> i2 -> beq_id i1 i2 = false.\nProof. \nintros. unfold beq_id. destruct i1. destruct i2.  apply beq_nat_false_iff.\nintros C. apply H0. subst. reflexivity.\nQed.\nTheorem beq_id_refl : forall X,\n  true = beq_id X X.\nProof.\n  intros. destruct X.\n  apply beq_nat_refl.  Qed.\n(*end*)\n(*####any_term_typable_under_empty context is closed####*)\nLemma term_typable_empty_closed_1:forall x t T Gamma,\nfree_var x t ->\nhas_type Gamma t T ->\nexists T',Gamma x = Some T'.\nProof. intros. generalize dependent T. generalize dependent Gamma.\ninduction H0. \nCase (\"tvar\").\nintros. apply inversion_tvar in H1. inversion H1. inversion H0.\n        exists x0. apply H2.\nCase (\"tprot\"). \nintros. apply inversion_tprot in H1. inversion H1. inversion H2.\n        inversion H3. inversion H5. \n        apply IHfree_var in H6. inversion H6. exists x2. apply H8.\nCase (\"tapp1\").\nintros.  apply inversion_tapp in H1. inversion H1. inversion H2.\ninversion H3. inversion H4. inversion H5. inversion H6. inversion H7.\ninversion H8. apply IHfree_var in H9. inversion H9. exists x7.\napply H11.\nCase (\"tapp2\").\nintros. apply inversion_tapp in H1. inversion H1. inversion H2.\ninversion H3. inversion H4. inversion H5. inversion H6. inversion H7.\ninversion H8. inversion H10. inversion H12. apply IHfree_var in H13.\ninversion H13. exists x7. apply H15.\nCase (\"tabs\").\nintros.  apply inversion_tabs in H2. inversion H2. inversion H3. inversion H4.\ninversion H5. inversion H6. inversion H8. apply IHfree_var in H9. inversion H9. \napply not_eq_beq_id_false in H0. apply Cupdate_neq with (T:=Some T)(St:=Gamma)in H0.\nrewrite->H0 in H11. exists x4. apply H11.\nQed.\n\nCorollary term_typable_empty_closed: forall t T,\nhas_type empty_context t T ->\nforall x, ~free_var x t.\nProof. intros t. induction t.\nCase (\"tvar\").\nintros. intros contra. apply inversion_tvar in H0. inversion H0. inversion H1.\n        inversion H2.\nCase (\"tprot\"). \nintros. apply inversion_tprot in H0. inversion H0. inversion H1. inversion H2.\n        inversion H4.  apply IHt with (x:=x)in H5.\n        intros contra. inversion contra. subst. apply H5 in H9. inversion H9.\nCase (\"tcon\").\nintros. intros contra. inversion contra.\nCase (\"tabs\").\nintros. apply inversion_tabs in H0. inversion H0. inversion H1. inversion H2. inversion H3.\n        inversion H4. inversion H6.\n        intros contra. inversion contra.  subst. \n        apply term_typable_empty_closed_1 with (T:=x1)(Gamma:=Cupdate empty_context i (Some t))in H15.\n        inversion H15. apply not_eq_beq_id_false in H12. apply Cupdate_neq with (T:=Some t)(St:=empty_context)in H12.\n        rewrite->H12 in H9. inversion H9. apply H7.\nCase (\"tapp\").\nintros. apply inversion_tapp in H0. inversion H0. inversion H1. inversion H2. inversion H3.\n      inversion H4. inversion H5. inversion H6. inversion H7. inversion H9. inversion H11.\n      apply IHt1 with (x:=x)in H8. apply IHt2 with(x:=x) in H12. intros contra. inversion contra. \n      subst. apply H8 in H16. inversion H16. subst. apply H12 in H16. inversion H16.\nQed.\n\n\nCorollary change_context: forall Gamma Gamma' t T,\nhas_type Gamma t T ->\n(forall x, free_var x t -> Gamma x = Gamma' x) ->\nhas_type Gamma' t T.\nProof.\nintros. generalize dependent Gamma'. induction H0.\nCase (\"t_var\").\nintros. apply t_var. rewrite<-H0. symmetry. apply H1.\napply e_tvar.\nCase (\"t_prot\").\nintros. apply t_prot with (T:=T). apply IHhas_type. intros. apply H2.\napply e_tprot. apply H3. apply H1.\nCase (\"t_con\").\nintros. apply t_con.\nCase (\"t_abs\").\nintros. apply t_abs. apply IHhas_type. intros. remember (beq_id x x0) as BB.\n        destruct BB.  apply beq_id_eq in HeqBB. rewrite->HeqBB. rewrite->Cupdate_eq.\n        rewrite->Cupdate_eq. reflexivity. inversion HeqBB. symmetry in H4.\n        apply Cupdate_neq with (T:=Some T1)(St:=Gamma) in H4. rewrite->H4.\n        inversion HeqBB. symmetry in H5. apply Cupdate_neq with (T:=Some T1)(St:=Gamma') in H5.\n        rewrite->H5. clear H4. clear H5. apply H1. apply e_tabs. intros contra. rewrite->contra in HeqBB.\n        rewrite<-beq_id_refl in HeqBB. inversion HeqBB. apply H2.\nCase (\"t_app\").\nintros. apply t_app with (T1:=T1)(T2:=T2)(b:=b). apply IHhas_type1. intros. apply H1. apply e_tapp1.\n        apply H2. apply IHhas_type2. intros. apply H1. apply e_tapp2. apply H2.\n        apply H0.\nCase (\"t_sub\").\nintros. apply t_sub with (T:=T). apply IHhas_type. apply H2. apply H1.\nQed.\n\nTheorem s_p_t_1: forall t Gamma T,\nhas_type empty_context t T ->\nhas_type Gamma t T.\nProof. intros. apply change_context with (Gamma':=Gamma)in H0.\n      apply H0. intros. apply term_typable_empty_closed with (x:=x)in H0.\n      apply H0 in H1.  inversion H1.\nQed.\n\n(*################s_p_t_1################*)\nTheorem substitution_preserves_typing: forall Gamma x t2 T1 T2 e,\nhas_type empty_context t2 T1 ->\nhas_type (Cupdate Gamma x (Some T1)) e T2 ->\nhas_type Gamma ([x := t2]e) T2.\nProof. intros. generalize dependent Gamma. generalize dependent x.\ngeneralize dependent t2. generalize dependent T1. generalize dependent\nT2. induction e.\nCase (\"tvar\").\nintros. apply inversion_tvar in H1. inversion H1. inversion H2. \nremember (beq_id x i) as BB.\ndestruct BB. apply beq_id_eq in HeqBB. rewrite->HeqBB in H3.\nrewrite->Cupdate_eq in H3. inversion H3. subst. simpl. rewrite<-beq_id_refl.\napply s_p_t_1. apply t_sub with (T:=x0). apply H0. apply H4.\nsymmetry in HeqBB. simpl. rewrite->HeqBB. destruct i. apply t_sub with (T:=x0).\n apply t_var. apply Cupdate_neq with (T:=Some T1)(St:=Gamma)in HeqBB.\nrewrite->HeqBB in H3. apply H3. apply H4.\nCase (\"tprot\").\nintros. simpl. apply inversion_tprot in H1. inversion H1. inversion H2. inversion H3.\ninversion H5.  apply t_sub with (T:=join x0 s). apply t_prot with (T:=x0) .  apply IHe with (T1:=T1).\napply H0. apply t_sub with (T:=x1). apply H6. apply H7. reflexivity. apply H4. \nCase (\"tcon\").\nintros. simpl. apply inversion_tcon in H1. inversion H1. inversion H2. inversion H3. inversion H4. inversion H6.\ninversion H8. subst. destruct T2. destruct r. inversion H10. subst. apply t_sub with (T:=an int s). apply t_con.\napply subt_int. apply subsum_r_trans with (b:=x2). apply H9. apply H11. inversion H10.\nCase (\"tabs\").\n\nintros. simpl. remember (beq_id x i) as BB. destruct BB. apply inversion_tabs in H1. \ninversion H1. inversion H2. inversion H3. inversion H4. inversion H5. inversion H7. \ninversion H9. inversion H11. inversion H13. destruct T2. destruct r. inversion H15. apply t_sub with (T:=an (fn t0 t1) x3).\napply t_sub with (T:=an (fn t0 t1) s). apply t_sub with (T:=an (fn x0 t1) s). apply t_sub with (T:=an (fn t t1) s).\n\napply t_abs.  apply t_sub with (T:=x2). apply t_sub with (T:=x1). apply beq_id_eq in HeqBB. rewrite->HeqBB in H8.\nassert (Cupdate Gamma i (Some t) = Cupdate (Cupdate Gamma i (Some T1)) i (Some t)).\napply functional_extensionality. intros. remember (beq_id i x4) as CC. destruct CC.\napply beq_id_eq in HeqCC. rewrite->HeqCC. rewrite->Cupdate_eq.\nrewrite->Cupdate_eq. reflexivity. symmetry in HeqCC. inversion HeqCC. inversion HeqCC.\napply Cupdate_neq with (T:= Some t)(St:=Gamma ) in HeqCC. rewrite->HeqCC. \napply Cupdate_neq with (T:= Some t)(St:=Cupdate Gamma i (Some T1)) in H17.\nrewrite->H17. apply Cupdate_neq with (T:=Some T1)(St:=Gamma) in H18. rewrite->H18.\nreflexivity. rewrite->H16. apply H8. apply H12. inversion H15. subst. apply H24.\napply subt_fn. apply sub_refl. apply H10. apply subtyping_refl.\ninversion H15. subst. apply subt_fn. apply sub_refl. apply H23. apply subtyping_refl. apply subt_fn.\napply H14. apply subtyping_refl. apply subtyping_refl. inversion H15. subst. apply subt_fn. apply H20.\napply subtyping_refl. apply subtyping_refl.\napply inversion_tabs in H1. inversion H1. inversion H2. inversion H3. inversion H4. inversion H5.\ninversion H7. inversion H9. inversion H11. inversion H13.  apply t_sub with (T:=an (fn x0 x2) x3). apply t_sub with (T:=an (fn x0 x1) x3).\napply t_sub with (T:=an (fn t x1) x3). apply t_sub with (T:=an (fn t x1) s). apply t_abs. apply IHe with (T1:=T1).  apply H0.\n\nassert (Cupdate (Cupdate Gamma x (Some T1)) i (Some t) = Cupdate (Cupdate Gamma i (Some t)) x (Some T1)).\napply functional_extensionality. intros. remember (beq_id x x4) as AA.\nremember (beq_id i x4) as BB. destruct AA. destruct BB. apply beq_id_eq in HeqAA.\napply beq_id_eq in HeqBB0. rewrite->HeqAA in HeqBB. rewrite->HeqBB0 in HeqBB.\nrewrite<-beq_id_refl in HeqBB. inversion HeqBB. apply beq_id_eq in HeqAA. rewrite->HeqAA.\nrewrite->Cupdate_eq. rewrite->HeqAA in HeqBB. symmetry in HeqBB. apply Cupdate_permute with (T1:=Some T1)(T2:=Some t)(X3:=x4)(f:=Gamma) in HeqBB.\nrewrite->HeqBB. rewrite->Cupdate_eq. reflexivity. destruct BB. apply beq_id_eq in HeqBB0. rewrite->HeqBB0. rewrite->Cupdate_eq.\nsymmetry in HeqAA. apply Cupdate_permute with (T1:=Some T1)(T2:=Some t)(X3:=x4)(f:=Gamma) in HeqAA.\nrewrite<-HeqAA. rewrite->Cupdate_eq. reflexivity. symmetry in HeqBB0. inversion HeqBB0.\napply Cupdate_neq with (T:=Some t)(St:=Cupdate Gamma x (Some T1))in HeqBB0.\nrewrite->HeqBB0. symmetry in HeqAA. inversion HeqAA.\n apply Cupdate_neq with (T:=Some T1)(St:=Gamma) in HeqAA.\nrewrite->HeqAA. apply Cupdate_neq with (T:=Some T1)(St:=Cupdate Gamma i (Some t)) in H18.\nrewrite->H18. apply Cupdate_neq with (T:=Some t)(St:=Gamma) in H17. rewrite->H17. reflexivity.\nrewrite<-H16. apply H8. \napply subt_fn. apply H14. apply subtyping_refl. apply subtyping_refl.\napply subt_fn. apply sub_refl. apply H10. apply subtyping_refl.  apply subt_fn.\napply sub_refl. apply subtyping_refl. apply H12. apply H15. \nCase (\"tapp\").\nintros. simpl. apply inversion_tapp in H1. inversion H1. inversion H2. inversion H3. inversion H4. inversion H5.\ninversion H6. inversion H7. inversion H8. inversion H10. inversion H12. \napply t_sub with (T:=join x5 x6).\n apply t_app with (T1:=x3)(T2:=x5)(b:=x6).\napply IHe1 with (T1:=T1). apply H0. apply t_sub with (T:= an (fn x0 x1) x2). apply H9. apply H11.\napply IHe2 with (T1:=T1). apply H0. apply t_sub with (T:=x4). apply H13. inversion H14. apply H15.\nreflexivity. inversion H14. apply H16.\nQed.\n\n\n(*#######################end###################*)\nLemma subtyping_join:forall T b' b,\nsubsum_r b' b ->\njoin T b' < join T b.\nProof. intros. inversion H0. apply subtyping_refl. destruct T. simpl.\ndestruct r. destruct s. apply subt_int. apply sub_LH. apply subtyping_refl.\ndestruct s. apply subt_fn. apply sub_LH. apply subtyping_refl. apply subtyping_refl.\napply subtyping_refl. Qed.\nTheorem preservation: forall t t' T,\nhas_type empty_context t T ->\nt ==> t' ->\nhas_type empty_context t' T.\nProof. intros. generalize dependent t'. remember (@empty_context) as context.\n induction H0.\nCase (\"t_var\"). intros. inversion H1.  \nCase (\"t_prot\"). intros. inversion H2. subst. apply t_prot with (T:=T).\n                 apply IHhas_type in H6. apply H6. reflexivity. reflexivity. \n                 subst. simpl. apply H0. subst.\n                 apply inversion_tabs in H0. inversion H0. inversion H1. inversion H3.\n                 inversion H4. inversion H5. inversion H7. inversion H9. inversion H11. inversion H13.\n                 apply t_sub with (T:=join (an (fn x0 x2) x3) H). simpl. apply t_sub with (T:=an (fn T0 x2) H). \n                  apply t_abs. apply t_sub with (T:=x1). apply H8. apply H12. apply subt_fn. apply sub_refl. apply H10.\n                  apply subtyping_refl. destruct T. destruct r. simpl. inversion H15. simpl. apply subt_fn. apply sub_refl.\n                 inversion H15. subst. apply H23. inversion H15. subst. apply H24.\n                 subst. apply inversion_tcon in H0. inversion H0. inversion H1. inversion H3. inversion H4. inversion H6. subst.\n                 inversion H4. inversion H7. inversion H10. inversion H12. subst. simpl. apply t_con.\nCase (\"t_con\"). intros. inversion H1.\nCase (\"t_abs\"). intros. inversion H1.\nCase (\"t_app\"). intros. inversion H1. \n                subst. apply inversion_tabs in H0_.  inversion H0_. inversion H0. inversion H2. inversion H3.\n                inversion H4. inversion H7. inversion H9. inversion H11. inversion H13.\n                apply t_sub with (T:=join T2 x3). apply t_sub with (T:=join T2 b0). \n                apply t_prot with (T:=T2).\n                apply substitution_preserves_typing with (T1:=T). \n                apply t_sub with (T:= x0). apply t_sub with (T:=T1).\n                apply H0_0. inversion H15. subst. apply H23. apply H10. apply t_sub with (T:=x2). apply t_sub with (T:=x1).\n                apply H8. apply H12. inversion H15. subst. apply H24. reflexivity. apply subtyping_join. apply H14. apply subtyping_join.\n                inversion H15. subst. apply H20. \n                subst. apply t_app with (T1:=T1)(T2:=T2)(b:=b).\n                apply IHhas_type1 with (t':=t1')in H5. apply H5.\n                reflexivity. apply H0_0. reflexivity. subst.\n                apply t_app with (T1:=T1)(T2:=T2)(b:=b). apply H0_.\n                apply IHhas_type2 with (t':=t2') in H6. apply H6.\n                reflexivity. reflexivity.\nCase (\"t_sub\"). subst. intros. apply t_sub with (T:=T).\n                apply IHhas_type. reflexivity. apply H2. apply H1.\nQed.\n\nTheorem type_uniqueness:forall T t t',\n        has_type empty_context t T ->\n        t ==>*t' ->\n        has_type empty_context t' T.\nProof. intros. induction H1. apply H0. apply IHmulti.\n       apply preservation with (t':=y)in H0. apply H0. \n       apply H1. Qed.\n(*###########end##########*)\n(*#########progress#########*)\nTheorem progress: forall t T,\nhas_type empty_context t T ->\nvalue t \\/ (exists t', t ==> t').\nProof. intros. remember (@empty_context) as context. induction H0.\nCase (\"t_var\"). \n                subst. inversion H0.\nCase (\"t_prot\").\n                right. subst. assert (A: empty_context = empty_context). reflexivity.\n                apply IHhas_type in A. inversion A. inversion H1. subst. destruct b.\n                exists (tcon n b0). apply st_protL. apply v_c. exists (tcon n H).\n                apply st_protHc. subst. destruct b. exists (tabs (Id n) T0 e b0).\n                apply st_protL. apply v_f. exists (tabs (Id n) T0 e H). apply st_protHf.\n                inversion H1. exists (tprot b x). apply st_prot. apply H2.\nCase (\"t_con\").\n                left. apply v_c.\nCase (\"t_abs\").\n                left. destruct x. apply v_f.\nCase (\"t_app\").\n                right. subst.  assert (A: empty_context = empty_context). reflexivity.\n                assert (B: empty_context = empty_context). apply A. apply IHhas_type1 in A.\n                apply IHhas_type2 in B. inversion A. inversion B. inversion H0. subst.\n                inversion H1. subst. apply inversion_tcon in H0_.  inversion H0_. inversion H2.\n                inversion H3. inversion H4. inversion H6. inversion H8. rewrite->H7 in H10. inversion H10.\n                apply inversion_tcon in H0_. inversion H0_. inversion H3. inversion H4. inversion H5. inversion H7.\n                inversion H9. rewrite->H8 in H11. inversion H11.\n                inversion H1.\n                subst. exists (tprot b0 ([(Id n) := tcon n0 b1](e))). apply st_appabs. apply v_c.\n                subst. exists (tprot b0 ([(Id n):= tabs (Id n0) T0 e0 b1](e))). apply st_appabs.\n                apply v_f. inversion H1. exists (tapp t1 x). apply st_app2. apply H0. apply H2.\n                inversion H0. exists (tapp x t2). apply st_app1. apply H1.\nCase (\"t_sub\"). subst. apply IHhas_type. reflexivity.\n                \nQed.\n(*##########determinism#########*)\nTheorem determinism: forall t t' t'',\nt ==> t'  ->\nt ==> t'' ->\nt' = t''.\nProof. intros t. induction t.\nCase (\"tvar\").\n             intros. inversion H0.\nCase (\"tprot\").\n             intros. inversion H0. subst.  inversion H1. subst.\n             apply IHt with (t':=t')(t'':=t'0)in H6. subst. reflexivity.\n             apply H5. subst. inversion H6. subst. inversion H5. subst.\n             inversion H5. subst. inversion H5. subst. inversion H5.\n             subst. inversion H1. subst. inversion H0. subst.\n             apply IHt with (t':=t'1)(t'':=t'0) in H7. subst. reflexivity.\n             apply H6. subst. inversion H5. subst. inversion H6. subst. inversion H6.\n             reflexivity. subst. inversion H1. subst. inversion H5. reflexivity. subst.\n             inversion H1. inversion H5. reflexivity.\nCase (\"tcon\").\n             intros. inversion H0.\nCase (\"tabs\"). \n             intros. inversion H0.\nCase (\"tapp\"). \n             intros. inversion H0. inversion H1. subst. inversion H6. subst. reflexivity.\n             subst. inversion H9. subst. inversion H5. subst. inversion H10. subst.\n             inversion H10. subst. inversion H1. subst. inversion H5. subst.\n             apply IHt1 with (t':=t1')(t'':=t1'0) in H5. subst. reflexivity. apply H6.\n             subst. inversion H4. subst. inversion H5. subst.  inversion H5. subst.\n             inversion H1. subst. subst. inversion H7. subst. inversion H6. subst.\n             inversion H6. subst. inversion H4. subst. inversion H7. subst. inversion H7.\n             subst. apply IHt2 with (t':=t2')(t'':=t2'0) in H6. subst. reflexivity.\n             apply H8. \nQed.\n(*############soundness############*)\nCorollary soundness : forall t t' T,\n  has_type empty_context t T -> \n  t ==>* t' ->\n ~((~exists t, t' ==> t)/\\(~ value t')).\nProof.\nintros. remember (@empty_context) as context.  \ngeneralize dependent T. induction H1.\nCase (\"multi_step\").\n     intros. subst. intros contra. inversion contra.\n     apply progress in H0. inversion H0.\n     SCase (\"left\"). apply H2 in H3. inversion H3.\n     SCase (\"right\"). apply contra in H3. inversion H3.\nCase (\"multi_ref\"). subst. intros. apply IHmulti with (T:=T).\n     apply preservation with (t':=y)in H2.  apply H2. \n     apply H0.\nQed.\n\n(*##########################*)\n\nEnd SecLang.\n\nModule LowLang.\n\nInductive tm : Type :=\n|tvar : id -> tm\n|tcon : nat -> tm\n|tabs : id -> Ty -> tm -> tm\n|tapp : tm -> tm -> tm\n(**\ntH is used to replace all high security\nterms. It can have any high security type\n*)\n|tH   : tm.\n\nInductive value : tm -> Prop :=\n| v_c : forall n,\n       value (tcon n)\n| v_f : forall n T e,\n       value (tabs (Id n) T e)\n| v_H : value tH.\n\nFixpoint subst (x:id) (s:tm) (t:tm): tm :=\n  match t with\n(*variables*)\n  | tvar x' => \n      if beq_id x x' then s  else t\n(*abstractions*)\n  | tabs x' T t1  => \n      tabs x' T (if beq_id x x' then t1 else (subst x s t1)) \n(*constants*)\n  | tcon n  => tcon n \n(*applications*)\n  | tapp t1 t2 => \n      tapp (subst x s t1) (subst x s t2)\n(*high security term replacement*)\n  | tH => \n      tH\n  end.\nNotation \"'[' x ':=' s ']' t\" := (subst x s t) (at level 20).\n\nInductive step : tm  -> tm  -> Prop :=\n| st_Happ: forall v,\n  value v ->\n  tapp tH v ==> tH\n| st_appabs: forall x T e v,\n  value v ->\n  tapp (tabs x T e) v ==>  [x := v]e \n| st_app1: forall t1 t1' t2,\n  t1  ==> t1'  ->\n  tapp t1 t2  ==> tapp t1' t2 \n| st_app2: forall v1 t2 t2',\n  value v1 ->\n  t2  ==> t2'  ->\n  tapp v1 t2  ==> tapp v1 t2' \n\nwhere \"t1  '==>' t2 \" := (step t1 t2).\n\nDefinition multistep := (multi step).\nNotation \"t1  '==>*' t2\" := (multistep t1 t2) \n  (at level 40).\n\nDefinition join (T:Ty) (b:Sec): Ty :=\n match b with\n | L => T\n | H => match T with\n        | an R b => an R H\n        end\n end.\n\nInductive has_type : context  -> tm -> Ty -> Prop :=\n| t_H: forall Gamma rt,\n  has_type Gamma tH (an rt H)\n| t_var: forall Gamma n T,\n  Gamma (Id n) = Some T ->\n  has_type Gamma (tvar (Id n)) T\n| t_con: forall Gamma n,\n  has_type Gamma (tcon n) (an int L)\n| t_abs: forall Gamma T1 T2 e x,\n  has_type (Cupdate Gamma x (Some T1)) e T2 ->\n  has_type Gamma (tabs x T1 e) (an (fn T1 T2) L)\n| t_app: forall Gamma T1 T2 T2' t1 t2 b,\n  has_type Gamma t1 (an (fn T1 T2) b) ->\n  has_type Gamma t2 T1 ->\n  T2' = join T2 b ->\n  has_type Gamma (tapp t1 t2) T2'\n| t_sub: forall Gamma t T T',\n  has_type Gamma t T ->\n  T < T' ->\n  has_type Gamma t T'.\n(**\nNote the [t_sub] in [LowLang] is necessary,\nconsider the following application:\ntapp (tabs (Id 0)(an int H)(tvar (Id 0)))(tcon 1) \nwhich an application of an abstraction with high level input to \na low level constant. \nSince there is no obvious reason why this should not disallowed,\nwe have to introduce \"subtyping\" into [LowLang]\n*)\n(*#######inversions of [has_type]##########*)\n(*inversion of [has_type Gamma (tvar x) T]*)\nLemma inversion_tvar: forall Gamma x T,\nhas_type Gamma (tvar x) T ->\nexists T0, (Gamma x = Some T0)/\\(T0 < T).\nProof. intros. remember (tvar x) as t. induction H0.\ninversion Heqt. inversion Heqt. subst. exists T. split. \napply H0. apply subtyping_refl.\ninversion Heqt. inversion Heqt. inversion Heqt. apply IHhas_type in Heqt.\ninversion Heqt. exists x0. split. inversion H2. apply H3. inversion H2.\napply subtyping_trans with (x:=T)(y:=T). apply subtyping_refl. apply H4.\napply H1.\nQed.\n\n(*inversion of [has_type Gamma (tabs x T1 e b) T]*)\nLemma inversion_tabs: forall Gamma x T1 T e,\nhas_type Gamma (tabs x T1 e) T ->\nexists T1', exists T2, exists T2', exists b',\n(has_type Gamma (tabs x T1 e) (an (fn T1 T2) L)) /\\\n(has_type (Cupdate Gamma x (Some T1)) e T2) /\\\n(T1'<T1)/\\(T2<T2')/\\(subsum_r L b')/\\((an (fn T1' T2') b') < T).\nProof. intros. remember (tabs x T1 e) as t. induction H0. inversion Heqt. inversion Heqt. inversion Heqt.\ninversion Heqt. subst. exists T1. exists T2. exists T2. exists L. split. apply t_abs in H0. apply H0.\nsplit. apply H0. split. apply subtyping_refl. split. apply subtyping_refl. split. apply sub_refl. apply subtyping_refl.\ninversion Heqt.  apply IHhas_type in Heqt. inversion Heqt. exists x0. inversion H2. exists x1. inversion H3. exists x2.\ninversion H4. exists x3. inversion H5. split. apply H6. inversion H7. split. apply H8. split. inversion H9. apply H10.\nsplit. inversion H9. inversion H11. apply H12. split. inversion H9. inversion H11. inversion H13. apply H14. inversion H9.\ninversion H11. inversion H13. apply subtyping_trans with (x:=T)(y:=T). apply subtyping_refl. apply H15. apply H1.\nQed.\n\n(*inversion of [has_type Gamma (tcon n b) T]*)\n\nLemma inversion_tcon: forall Gamma T n,\nhas_type Gamma (tcon n) T ->\nexists T', exists T'', exists b', (T' = an int L)/\\(T'' = an int b')/\\(subsum_r L b')/\\(T'' < T).\nProof. intros. remember (tcon n) as t. induction H0.\ninversion Heqt. inversion Heqt. inversion Heqt. subst. exists (an int L). exists (an int L).\nexists L. split. reflexivity. split. reflexivity. split. apply sub_refl. apply subtyping_refl.\ninversion Heqt. inversion Heqt.  apply IHhas_type in Heqt. inversion Heqt. exists x. inversion H2.\nexists x0. inversion H3. exists x1. \ninversion H4. split. apply H5. inversion H6. split. apply H7. inversion H8. split. apply H9. \napply subtyping_trans with (x:=T)(y:=T). apply subtyping_refl. apply H10. apply H1.\nQed.\n(*inversion of [has_type Gamma tH T]*)\nLemma inversion_tH:forall Gamma T,\nhas_type Gamma tH T ->\nexists r,\n(an r H) < T.\nProof. intros. remember tH as t. induction H0. exists rt. apply subtyping_refl.\ninversion Heqt. inversion Heqt. inversion Heqt. inversion Heqt. apply IHhas_type in Heqt.\ninversion Heqt. exists x. apply subtyping_trans with (x:=T)(y:=T). apply subtyping_refl.\napply H2. apply H1. Qed.\n(*inversion of [has_type Gamma (tapp t1 t2) T]*)\nLemma inversion_tapp: forall Gamma t1 t2 T2,\nhas_type Gamma (tapp t1 t2) T2 ->\nexists T1', exists T2', exists b', exists T1'', exists T1''', exists T2'', exists b'',\nhas_type Gamma t1 (an (fn T1' T2') b')/\\((an (fn T1' T2') b')<(an (fn T1'' T2'') b''))/\\\n(has_type Gamma t2 T1''')/\\(T1''' < T1'') /\\\n((join T2'' b'') < T2).\nProof. intros. remember (tapp t1 t2) as t. induction H0.\ninversion Heqt. inversion Heqt. inversion Heqt. inversion Heqt. inversion Heqt. subst. exists T1.\nexists T2. exists b. exists T1. exists T1. exists T2. exists b.\nsplit. apply H0_. split. apply subtyping_refl. split. apply H0_0. split. apply subtyping_refl. \napply subtyping_refl.\n apply IHhas_type in Heqt. inversion Heqt. exists x. inversion H2.\nexists x0. inversion H3. exists x1. inversion H4. exists x2. inversion H5. exists x3. inversion H6. exists x4.\ninversion H7. exists x5. inversion H8.  split. apply H9. inversion H10. split. apply H11. inversion H12.\nsplit. apply H13. inversion H14. split. apply H15. apply subtyping_trans with (x:=T)(y:=T).\napply subtyping_refl. apply H16. apply H1. Qed.\n\n\n\n(*some examples*)\nExample test_has_type_1:\nhas_type empty_context (tabs (Id 0)(an int L)(tH)) (an (fn (an int L)(an int H)) L).\nProof. apply t_abs. apply t_H. Qed.\nExample test_has_type_2:\nhas_type empty_context (tabs (Id 0)(an int L)(tcon 4)) (an (fn (an int L)(an int H)) H).\nProof. apply t_sub with (T:=an (fn (an int L)(an int L)) H). apply t_sub with (T:=an (fn (an int L)(an int L)) L).\napply t_abs. apply t_con. apply subt_fn. apply sub_LH. apply subtyping_refl. apply subtyping_refl.\napply subt_fn. apply sub_refl. apply subtyping_refl. apply subt_int. apply sub_LH.\nQed.\nExample test_has_type_3:\nhas_type (Cupdate empty_context (Id 0) (Some (an int L))) (tvar (Id 0)) (an int H).\nProof. apply t_sub with (T:=an int L). apply t_var. rewrite->Cupdate_eq. reflexivity.\napply subt_int. apply sub_LH. Qed.\nExample test_has_type_4:\nhas_type (Cupdate empty_context (Id 0) (Some(an (fn (an int H)(an int L)) L)))\n         (tvar (Id 0)) (an (fn (an int L)(an int H)) H).\nProof. apply t_sub with (T:=an (fn (an int H)(an int L)) L). apply t_var. rewrite->Cupdate_eq. reflexivity.\napply subt_fn. apply sub_LH. apply subt_int. apply sub_LH. apply subt_int. apply sub_LH.\nQed.\nExample test_has_type_5:\nhas_type empty_context (tcon 1) (an int H).\nProof. apply t_sub with (T:=an int L). apply t_con. apply subt_int. apply sub_LH.\nQed.\nExample test_has_type_6:\nhas_type empty_context (tapp (tabs(Id 0)(an int H)(tvar (Id 0)))(tcon 1)) (an int H).\napply t_app with (T1:=an int H)(T2:=an int H)(b:=L).\napply t_abs. apply t_var. rewrite->Cupdate_eq. reflexivity. apply t_sub with (T:=an int L).\napply t_con. apply subt_int. apply sub_LH. reflexivity. Qed.\nExample test_has_type_7:\nhas_type empty_context (tapp (tabs (Id 0)(an int H)(tvar (Id 0)))(tcon 1))(an int H).\nProof. apply t_app with (T1:=an int L)(T2:=an int H)(b:=L). apply t_sub with (T:=an (fn (an int H)(an int H)) L).\napply t_abs. apply t_var. rewrite->Cupdate_eq. reflexivity. apply subt_fn. apply sub_refl. apply subt_int. apply sub_LH.\napply subtyping_refl. apply t_con. reflexivity. Qed.\nExample test_has_type_8:\nhas_type empty_context (tapp (tabs (Id 0)(an int L)(tvar (Id 0)))(tcon 1)) (an int H).\nProof. apply t_app with (T1:=an int L)(T2:=an int L)(b:=H). apply t_sub with (T:=an (fn (an int L)(an int L)) L).\napply t_abs. apply t_var. rewrite->Cupdate_eq. reflexivity. apply subt_fn. apply sub_LH. apply subtyping_refl.\napply subtyping_refl. apply t_con. reflexivity. Qed.\nExample test_has_type_9:\nhas_type empty_context (tapp (tabs (Id 0)(an int H)(tvar (Id 0))) tH)(an int H).\nProof. apply t_app with (T1:=an int H)(T2:=an int H)(b:=L). \napply t_abs. apply t_var. rewrite->Cupdate_eq. reflexivity. apply t_H. reflexivity. Qed.\nExample test_has_type_10:\nhas_type (Cupdate empty_context (Id 0)(Some (an int H)))(tvar (Id 0))(an int H).\nProof. apply t_var. rewrite->Cupdate_eq. reflexivity. Qed.\nExample test_has_type_11:\nhas_type empty_context (tabs (Id 0)(an int H)(tvar (Id 0))) (an (fn (an int H)(an int H)) L).\nProof. apply t_abs. apply t_var. rewrite->Cupdate_eq. reflexivity.\nQed.\nExample test_has_type_12:\nhas_type empty_context (tapp tH (tcon 1)) (an int H).\nProof. apply t_app with (T1:=an int L)(T2:=an int L)(b:=H). apply t_H. apply t_con.\nreflexivity. Qed.\nExample test_has_type_13:\nhas_type (Cupdate empty_context (Id 0) (Some (an (fn (an int H)(an int L)) L))) (tapp (tvar (Id 0))(tcon 1))(an int H).\nProof. apply t_app with (T1:=an int L)(T2:=an int L)(b:=H).\n       apply t_sub with (T:=an (fn (an int H)(an int L)) L).\n       apply t_var. rewrite->Cupdate_eq. reflexivity. apply subt_fn. apply sub_LH.\n       apply subt_int. apply sub_LH. apply subtyping_refl. apply t_con.\n       reflexivity. Qed.\nExample test_has_type_14:\nhas_type (Cupdate empty_context (Id 0) (Some (an (fn (an int H)(an int L)) L))) (tapp (tvar (Id 0))(tcon 1)) (an int L).\nProof. apply t_app with (T1:=an int H)(T2:=an int L)(b:=L). apply t_var. rewrite->Cupdate_eq.\nreflexivity. apply t_sub with (T:=an int L). apply t_con. apply subt_int. apply sub_LH. reflexivity.\nQed.\n       \nExample test_has_type_15:\nhas_type empty_context (tapp (tapp tH (tcon 1))(tcon 2)) (an int H).\nProof. apply t_app with (T1:=an int L)(T2:=an int L)(b:=H). \napply t_app with (T1:=an int L)(T2:=an (fn (an int L)(an int L)) L)(b:=H).\napply t_H. apply t_con. reflexivity. apply t_con. reflexivity.\nQed.\n(*some counter examples*)\n(*undefined variables*)\nExample test_has_type_16:\n~has_type empty_context (tvar (Id 0)) (an int L).\nProof. intros contra. apply inversion_tvar in contra. inversion contra.\ninversion H0. inversion H1. Qed.\nExample test_has_type_17:\n~has_type (Cupdate empty_context (Id 1)(Some (an int L))) (tvar (Id 0)) (an int L).\nProof. intros contra. apply inversion_tvar in contra. inversion contra.\nremember (beq_id (Id 1)(Id 0)) as BB. destruct BB. apply beq_id_eq in HeqBB. inversion HeqBB.\nsymmetry in HeqBB. apply Cupdate_neq with (T:=Some (an int L))(St:=empty_context) in HeqBB.\ninversion H0. rewrite->HeqBB in H1. inversion H1. Qed.\n(*abstractions with undefined variables*)\nExample test_has_type_18:\n~has_type empty_context (tabs (Id 0)(an int H)(tvar (Id 1))) (an (fn (an int H)(an int L)) L).\nProof. intros contra. apply inversion_tabs in contra. inversion contra. inversion H0. inversion H1.\ninversion H2. inversion H3. inversion H5. apply inversion_tvar in H6. inversion H6. inversion H8.\nremember (beq_id (Id 0)(Id 1)) as BB. destruct BB. apply beq_id_eq in HeqBB. inversion HeqBB.\nsymmetry in HeqBB. apply Cupdate_neq with (T:=Some (an int H))(St:=empty_context) in HeqBB. rewrite->HeqBB in H9.\ninversion H9. Qed.\n(*ill-typed abstractions*)\nExample test_has_type_19:\n~has_type empty_context (tabs (Id 0)(an int L)(tvar (Id 0))) (an (fn (an int H)(an int H)) H).\nProof. intros contra. apply inversion_tabs in contra. inversion contra. inversion H0. inversion H1.\ninversion H2. inversion H3. inversion H5.  inversion H7. inversion H9. inversion H11. destruct x.\ndestruct r. destruct s. inversion H13. subst. inversion H21. inversion H16. inversion H8. inversion H16.\ninversion H8. Qed.\nExample test_has_type_20:\n~has_type empty_context (tabs (Id 0)(an int H)(tvar (Id 0)))(an (fn (an int L)(an int L)) H).\nProof. intros contra. apply inversion_tabs in contra. inversion contra. inversion H0. inversion H1. inversion H2.\ninversion H3. inversion H5. inversion H7. inversion H9. inversion H11. apply inversion_tvar in H6. inversion H6.\ninversion H14. rewrite->Cupdate_eq in H15. inversion H15. subst. assert (an int H < x1). apply subtyping_trans with (x:=x0)(y:=x0).\napply subtyping_refl. apply H16. apply H10. destruct x1. destruct r. destruct s. inversion H17. inversion H20. inversion H13. subst.\ninversion H26. inversion H20. inversion H17. Qed.\nExample test_has_type_21:\n~has_type empty_context (tabs (Id 0)(an int L)(tvar (Id 0)))(an int L).\nProof. intros contra. apply inversion_tabs in contra. inversion contra.\ninversion H0. inversion H1. inversion H2. inversion H3. inversion H5.\ninversion H7. inversion H9. inversion H11. inversion H13. Qed.\n(*ill-typed constants*)\nExample test_has_type_22:\n~has_type empty_context (tcon 1) (an (fn (an int L)(an int L)) L).\nProof. intros contra. apply inversion_tcon in contra. inversion contra. inversion H0. inversion H1. inversion H2.\ninversion H4. inversion H6. rewrite->H5 in H8. inversion H8. Qed.\n(*ill-typed tH*)\nExample test_has_type_23:\n~has_type empty_context tH (an int L).\nProof. intros contra. apply inversion_tH in contra. inversion contra. destruct x.\ninversion H0. inversion H3. inversion H0. Qed.\n(*ill-matched applications*)\nExample test_has_type_24:\n~has_type empty_context (tapp (tabs (Id 0)(an int L)(tvar (Id 0))) tH) (an int H).\nProof. intros contra. apply inversion_tapp in contra. inversion contra. inversion H0.\n       inversion H1. inversion H2. inversion H3. inversion H4. inversion H5. inversion H6.\n       inversion H8. inversion H10. inversion H12. apply inversion_tH in H11. inversion H11.\n       assert (an x6 H < x2). apply subtyping_trans with (x:=x3)(y:=x3). apply subtyping_refl.\n       apply H15. apply H13. destruct x2. destruct r. destruct s. inversion H16. inversion H18.\n       apply inversion_tabs in H7. inversion H7. inversion H17. inversion H18. inversion H19.\n       inversion H20. inversion H22. inversion H24. inversion H26. inversion H28. destruct x2.\n       destruct r. destruct s. destruct x.  destruct r. destruct s. inversion H9. inversion H38.\n       inversion H42. inversion H30. inversion H38. inversion H42. inversion H30. inversion H38.\n       inversion H25. inversion H33. inversion H25.   apply inversion_tabs in H7.\n       inversion H7. inversion H17. inversion H18. inversion H19. inversion H20. inversion H22.\n       inversion H24. inversion H26. inversion H28. destruct x2. destruct r. destruct s0. destruct x.\n       destruct r. destruct s0. inversion H9. inversion H38. inversion H30. inversion H38. inversion H42.\n       inversion H30. inversion H38. inversion H25. inversion H33. inversion H25.\nQed.\nExample test_has_type_25:\n~has_type empty_context (tapp (tabs (Id 0)(an int L)(tcon 1))(tabs (Id 0)(an int L)(tvar (Id 0))))(an int L).\nProof. intros contra. apply inversion_tapp in contra. inversion contra. inversion H0. inversion H1. inversion H2.\ninversion H3. inversion H4. inversion H5. inversion H6. inversion H8. inversion H10. inversion H12. \napply inversion_tabs in H7. apply inversion_tabs in H11. inversion H7. inversion H15. inversion H16. inversion H17.\ninversion H18. inversion H20. inversion H22. inversion H24. inversion H26. destruct x6. destruct r. destruct s.\ndestruct x. destruct r. destruct s. destruct x2. destruct r. destruct s. inversion H11. inversion H29. inversion H30.\ninversion H31. inversion H32. inversion H34. inversion H36. inversion H38. inversion H40. destruct x3. destruct r. \ninversion H42.  inversion H13. inversion H9. inversion H36. inversion H40. inversion H9. inversion H36. inversion H28.\ninversion H36. inversion H40. inversion H28. inversion H36. inversion H23. inversion H31. inversion H23.\nQed.\n(*false-applications*)\nExample test_has_type_26:\n~has_type empty_context (tapp (tcon 1)(tcon 2)) (an int L).\nProof. intros contra. apply inversion_tapp in contra.  inversion contra. inversion H0. inversion H1. inversion H2.\ninversion H3. inversion H4. inversion H5. inversion H6. apply inversion_tcon in H7.\ninversion H7. inversion H9. inversion H10. inversion H11.  inversion H13. inversion H15. rewrite->H14 in H17.\ninversion H17.\nQed.\n(*properties of the language*)\n(*preservation*)\nAxiom functional_extensionality : forall {X Y: Type} {f g : X -> Y},\n    (forall (x: X), f x = g x) ->  f = g.\n(*########################################*)\n(*##########s_p_t_1##############*)\n(*Firstly we use the following proposition to describe free variables*)\nInductive free_var : id -> tm -> Prop :=\n| e_tvar : forall x,\n      free_var x (tvar x)\n| e_tapp1 : forall x e1 e2,\n      free_var x e1 ->\n      free_var x (tapp e1 e2)\n| e_tapp2 : forall x e1 e2,\n      free_var x e2 ->\n      free_var x (tapp e1 e2)\n| e_tabs : forall x y e T,\n      y <> x ->\n      free_var x e ->\n      free_var x (tabs y T e).\n\n(*some examples*)\nExample test_free_var_1:\nfree_var (Id 0) (tvar (Id 0)).\nProof. apply e_tvar. Qed.\nExample test_free_var_2:\nfree_var (Id 1) (tapp (tabs (Id 0)(an int L)(tvar (Id 0)))(tvar (Id 1))) .\nProof. apply e_tapp2. apply e_tvar. Qed.\nExample test_free_var_3:\nfree_var (Id 1)(tabs (Id 0)(an int L)(tvar (Id 1))).\nProof. apply e_tabs. intros contra. inversion contra. apply e_tvar. Qed.\nExample test_free_var_4:\nfree_var (Id 0) (tapp (tabs (Id 0)(an int L)(tvar (Id 0)))(tvar (Id 0))).\nProof. apply e_tapp2. apply e_tvar. Qed.\nExample test_free_var_5:\nfree_var (Id 1) (tapp (tabs (Id 0)(an int L)(tvar (Id 1)))(tcon 1)).\nProof. apply e_tapp1. apply e_tabs. intros contra. inversion contra. apply e_tvar.\nQed.\nExample test_free_var_6:\nforall x n, ~free_var x (tcon n).\nProof. intros. intros contra. inversion contra. Qed.\nExample test_free_var_7:\nforall x,~free_var x tH.\nProof. intros. intros contra. inversion contra. Qed.\nExample test_free_var_8:\nforall x T e,~free_var x (tabs x T e).\nProof. intros. intros contra. inversion contra. subst. apply H3. reflexivity.\nQed.\n(*some auxiliary lemmas*)\nTheorem beq_id_eq : forall i1 i2,\n  true = beq_id i1 i2 -> i1 = i2.\nProof. \nintros. unfold beq_id in H0. destruct i1. destruct i2. symmetry in H0.\napply beq_nat_true in H0. subst. reflexivity.\nQed.  \nTheorem not_eq_beq_id_false : forall i1 i2,\n  i1 <> i2 -> beq_id i1 i2 = false.\nProof. \nintros. unfold beq_id. destruct i1. destruct i2.  apply beq_nat_false_iff.\nintros C. apply H0. subst. reflexivity.\nQed.\nTheorem beq_id_refl : forall X,\n  true = beq_id X X.\nProof.\n  intros. destruct X.\n  apply beq_nat_refl.  Qed.\n(*end*)\n(*####any_term_typable_under_empty context is closed####*)\nLemma term_typable_empty_closed_1:forall x t T Gamma,\nfree_var x t ->\nhas_type Gamma t T ->\nexists T',Gamma x = Some T'.\nProof. intros. generalize dependent T. generalize dependent Gamma.\ninduction H0.\nCase (\"e_tvar\"). \nintros. apply inversion_tvar in H1. inversion H1. inversion H0.\n        exists x0. apply H2.\nCase (\"e_tapp1\").\nintros.  apply inversion_tapp in H1. inversion H1. inversion H2. inversion H3. \n         inversion H4. inversion H5. inversion H6. inversion H7. inversion H8.\n        apply IHfree_var with (T:=an (fn x0 x1) x2). apply H9.\nCase (\"e_tapp2\").\nintros. apply inversion_tapp in H1. inversion H1. inversion H2. inversion H3. inversion H4.\n        inversion H5. inversion H6. inversion H7. inversion H8. inversion H10. inversion H12.\n        apply IHfree_var with (T:=x4). apply H13. \nCase (\"e_tabs\").\nintros.  apply inversion_tabs in H2. inversion H2. inversion H3. inversion H4. inversion H5. inversion H6.\n         inversion H8. apply IHfree_var in H9. inversion H9. exists x4. \napply not_eq_beq_id_false in H0. apply Cupdate_neq with (T:=Some T)(St:=Gamma)in H0.\nrewrite->H0 in H11. apply H11.\nQed.\n\n\nCorollary term_typable_empty_closed: forall t T,\nhas_type empty_context t T ->\nforall x, ~free_var x t.\nProof. intros t. induction t.\nCase (\"tvar\").\nintros. intros contra. apply inversion_tvar in H0. inversion H0.\n        inversion H1. inversion H2.\nCase (\"tcon\").\nintros. intros contra. inversion contra.\nCase (\"tabs\").\nintros. apply inversion_tabs in H0. inversion H0. inversion H1. inversion H2. inversion H3. inversion H4.\n        inversion H6. intros contra. inversion contra.  subst. \n        apply term_typable_empty_closed_1 with (T:=x1)(Gamma:=Cupdate empty_context i (Some t))in H14.\n        inversion H14. apply not_eq_beq_id_false in H12. apply Cupdate_neq with (T:=Some t)(St:=empty_context)in H12.\n        rewrite->H12 in H9. inversion H9. apply H7.\nCase (\"tapp\").\nintros. intros contra. apply inversion_tapp in H0. inversion H0. inversion H1. inversion H2. inversion H3. inversion H4.\n        inversion H5. inversion H6. inversion H7. inversion H9. inversion H11.\n        inversion contra. subst.  apply IHt1 with (x:=x)in H8. apply H8 in H16.\n        inversion H16. subst. apply IHt2 with (x:=x) in H12. apply H12 in H16. inversion H16.\nCase (\"tH\").\nintros. intros contra. inversion contra.\nQed.\n\n\nCorollary change_context: forall Gamma Gamma' t T,\nhas_type Gamma t T ->\n(forall x, free_var x t -> Gamma x = Gamma' x) ->\nhas_type Gamma' t T.\nProof.\nintros. generalize dependent Gamma'. induction H0.\nCase (\"t_H\").\nintros. apply t_H.\nCase (\"t_var\").\nintros. apply t_var. rewrite<-H0. symmetry. apply H1.\napply e_tvar.\nCase (\"t_con\"). \nintros. apply t_con.\nCase (\"t_abs\").\nintros. apply t_abs. apply IHhas_type. intros. remember (beq_id x x0) as BB.\n        destruct BB.  apply beq_id_eq in HeqBB. rewrite->HeqBB. rewrite->Cupdate_eq.\n        rewrite->Cupdate_eq. reflexivity. inversion HeqBB. symmetry in H4.\n        apply Cupdate_neq with (T:=Some T1)(St:=Gamma) in H4. rewrite->H4.\n        inversion HeqBB. symmetry in H5. apply Cupdate_neq with (T:=Some T1)(St:=Gamma') in H5.\n        rewrite->H5. clear H4. clear H5. apply H1. apply e_tabs. intros contra. rewrite->contra in HeqBB.\n        rewrite<-beq_id_refl in HeqBB. inversion HeqBB. apply H2.\nCase (\"t_app\").\nintros. apply t_app with (T1:=T1)(T2:=T2)(b:=b). apply IHhas_type1. intros. apply H1. apply e_tapp1.\n        apply H2. apply IHhas_type2. intros. apply H1. apply e_tapp2. apply H2. apply H0.\nCase (\"t_sub\"). \nintros. apply t_sub with (T:=T). apply IHhas_type. apply H2. apply H1. \nQed.\n\nTheorem s_p_t_1: forall t Gamma T,\nhas_type empty_context t T ->\nhas_type Gamma t T.\nProof. intros. apply change_context with (Gamma':=Gamma)in H0.\n      apply H0. intros. apply term_typable_empty_closed with (x:=x)in H0.\n      apply H0 in H1.  inversion H1.\nQed.\n\n(*################s_p_t_1################*)\nTheorem substitution_preserves_typing: forall Gamma x t2 T1 T2 e,\nhas_type empty_context t2 T1 ->\nhas_type (Cupdate Gamma x (Some T1)) e T2 ->\nhas_type Gamma ([x := t2]e) T2.\nProof. intros. generalize dependent Gamma. generalize dependent x.\ngeneralize dependent t2. generalize dependent T1. generalize dependent\nT2. induction e.\nCase (\"tvar\").\nintros. apply inversion_tvar in H1. inversion H1. inversion H2.\nsimpl. remember (beq_id x i) as BB.\ndestruct BB. apply beq_id_eq in HeqBB. rewrite->HeqBB in H3.\nrewrite->Cupdate_eq in H3. inversion H3. subst. apply t_sub with (T:=x0).\n apply s_p_t_1. apply H0. apply H4.\nsymmetry in HeqBB. apply Cupdate_neq with (T:=Some T1)(St:=Gamma)in HeqBB.\nrewrite->HeqBB in H3. destruct i. apply t_sub with (T:=x0). apply t_var. apply H3.\napply H4. \nCase (\"tcon\").\nintros. simpl. apply inversion_tcon in H1. inversion H1. inversion H2. inversion H3. inversion H4.\ninversion H6. inversion H8. rewrite->H7 in H10. destruct T2. destruct r. destruct s. apply t_con.\napply t_sub with (T:=an int L). apply t_con. apply subt_int. apply sub_LH. inversion H10.\nCase (\"tabs\").\nintros. simpl. remember (beq_id x i) as BB. destruct BB. apply inversion_tabs in H1.\ninversion H1. inversion H2. inversion H3. inversion H4. inversion H5. inversion H7.\ninversion H9. inversion H11. inversion H13. destruct T2. destruct r. inversion H15.\nassert (t0 < t). apply subtyping_trans with (x:=x0)(y:=x0). apply subtyping_refl. inversion H15. apply H23.\napply H10. apply t_sub with (T:=an (fn t t1) s).  destruct s. apply t_abs.\napply beq_id_eq in HeqBB. rewrite->HeqBB in H8.\nassert (Cupdate Gamma i (Some t) = Cupdate (Cupdate Gamma i (Some T1)) i (Some t)).\napply functional_extensionality. intros. remember (beq_id i x4) as CC. destruct CC.\napply beq_id_eq in HeqCC. rewrite->HeqCC. rewrite->Cupdate_eq.\nrewrite->Cupdate_eq. reflexivity. symmetry in HeqCC. inversion HeqCC. inversion HeqCC.\napply Cupdate_neq with (T:= Some t)(St:=Gamma ) in HeqCC. rewrite->HeqCC. \napply Cupdate_neq with (T:= Some t)(St:=Cupdate Gamma i (Some T1)) in H18.\nrewrite->H18. apply Cupdate_neq with (T:=Some T1)(St:=Gamma) in H19. rewrite->H19.\nreflexivity. rewrite->H17. apply t_sub with (T:=x2). apply t_sub with (T:=x1).\n apply H8. apply H12. inversion H15. apply H26. apply t_sub with (T:=an (fn t t1) L).\n apply t_abs. apply beq_id_eq in HeqBB. rewrite->HeqBB in H8.\nassert (Cupdate Gamma i (Some t) = Cupdate (Cupdate Gamma i (Some T1)) i (Some t)).\napply functional_extensionality. intros. remember (beq_id i x4) as CC. destruct CC.\napply beq_id_eq in HeqCC. rewrite->HeqCC. rewrite->Cupdate_eq.\nrewrite->Cupdate_eq. reflexivity. symmetry in HeqCC. inversion HeqCC. inversion HeqCC.\napply Cupdate_neq with (T:= Some t)(St:=Gamma ) in HeqCC. rewrite->HeqCC. \napply Cupdate_neq with (T:= Some t)(St:=Cupdate Gamma i (Some T1)) in H18.\nrewrite->H18. apply Cupdate_neq with (T:=Some T1)(St:=Gamma) in H19. rewrite->H19.\nreflexivity. rewrite->H17. assert (x1 < t1). apply subtyping_trans with (x:=x2)(y:=x2).\napply subtyping_refl. apply H12. inversion H15. apply H26. apply t_sub with (T:=x1).\napply H8. apply H18. apply subt_fn. apply sub_LH. apply subtyping_refl. apply subtyping_refl.\napply subt_fn. apply sub_refl. apply H16. apply subtyping_refl. \n\napply inversion_tabs in H1. inversion H1. inversion H2. inversion H3. inversion H4. inversion H5.\ninversion H7. inversion H9. inversion H11. inversion H13. destruct T2. destruct r. destruct s.\ninversion H15. inversion H15. destruct s. assert (t0<t). apply subtyping_trans with (x:=x0)(y:=x0).\napply subtyping_refl. inversion H15. apply H23. apply H10. apply t_sub with (T:=an (fn t t1) L).\napply t_abs.\napply IHe with (T1:=T1).  apply H0. assert (x1<t1). apply subtyping_trans with (x:=x2)(y:=x2).\napply subtyping_refl. apply H12. inversion H15. apply H25. apply t_sub with (T:=x1).\nassert (Cupdate (Cupdate Gamma x (Some T1)) i (Some t) = Cupdate (Cupdate Gamma i (Some t)) x (Some T1)).\napply functional_extensionality. intros. remember (beq_id x x4) as AA.\nremember (beq_id i x4) as BB. destruct AA. destruct BB. apply beq_id_eq in HeqAA.\napply beq_id_eq in HeqBB0. rewrite->HeqAA in HeqBB. rewrite->HeqBB0 in HeqBB.\nrewrite<-beq_id_refl in HeqBB. inversion HeqBB. apply beq_id_eq in HeqAA. rewrite->HeqAA.\nrewrite->Cupdate_eq. rewrite->HeqAA in HeqBB. symmetry in HeqBB. apply Cupdate_permute with (T1:=Some T1)(T2:=Some t)(X3:=x4)(f:=Gamma) in HeqBB.\nrewrite->HeqBB. rewrite->Cupdate_eq. reflexivity. destruct BB. apply beq_id_eq in HeqBB0. rewrite->HeqBB0. rewrite->Cupdate_eq.\nsymmetry in HeqAA. apply Cupdate_permute with (T1:=Some T1)(T2:=Some t)(X3:=x4)(f:=Gamma) in HeqAA.\nrewrite<-HeqAA. rewrite->Cupdate_eq. reflexivity. symmetry in HeqBB0. inversion HeqBB0.\napply Cupdate_neq with (T:=Some t)(St:=Cupdate Gamma x (Some T1))in HeqBB0.\nrewrite->HeqBB0. symmetry in HeqAA. inversion HeqAA.\n apply Cupdate_neq with (T:=Some T1)(St:=Gamma) in HeqAA.\nrewrite->HeqAA. apply Cupdate_neq with (T:=Some T1)(St:=Cupdate Gamma i (Some t)) in H20.\nrewrite->H20. apply Cupdate_neq with (T:=Some t)(St:=Gamma) in H19. rewrite->H19. reflexivity.\nrewrite<-H18. apply H8. apply H17. apply subt_fn. apply sub_refl. apply H16. apply subtyping_refl.\n\napply t_sub with (T:=an (fn t0 t1) L). assert (t0<t). apply subtyping_trans with (x:=x0)(y:=x0).\napply subtyping_refl. inversion H15. apply H23. apply H10. apply t_sub with (T:=an (fn t t1) L).\napply t_abs.\napply IHe with (T1:=T1).  apply H0. assert (x1<t1). apply subtyping_trans with (x:=x2)(y:=x2).\napply subtyping_refl. apply H12. inversion H15. apply H25. apply t_sub with (T:=x1).\nassert (Cupdate (Cupdate Gamma x (Some T1)) i (Some t) = Cupdate (Cupdate Gamma i (Some t)) x (Some T1)).\napply functional_extensionality. intros. remember (beq_id x x4) as AA.\nremember (beq_id i x4) as BB. destruct AA. destruct BB. apply beq_id_eq in HeqAA.\napply beq_id_eq in HeqBB0. rewrite->HeqAA in HeqBB. rewrite->HeqBB0 in HeqBB.\nrewrite<-beq_id_refl in HeqBB. inversion HeqBB. apply beq_id_eq in HeqAA. rewrite->HeqAA.\nrewrite->Cupdate_eq. rewrite->HeqAA in HeqBB. symmetry in HeqBB. apply Cupdate_permute with (T1:=Some T1)(T2:=Some t)(X3:=x4)(f:=Gamma) in HeqBB.\nrewrite->HeqBB. rewrite->Cupdate_eq. reflexivity. destruct BB. apply beq_id_eq in HeqBB0. rewrite->HeqBB0. rewrite->Cupdate_eq.\nsymmetry in HeqAA. apply Cupdate_permute with (T1:=Some T1)(T2:=Some t)(X3:=x4)(f:=Gamma) in HeqAA.\nrewrite<-HeqAA. rewrite->Cupdate_eq. reflexivity. symmetry in HeqBB0. inversion HeqBB0.\napply Cupdate_neq with (T:=Some t)(St:=Cupdate Gamma x (Some T1))in HeqBB0.\nrewrite->HeqBB0. symmetry in HeqAA. inversion HeqAA.\n apply Cupdate_neq with (T:=Some T1)(St:=Gamma) in HeqAA.\nrewrite->HeqAA. apply Cupdate_neq with (T:=Some T1)(St:=Cupdate Gamma i (Some t)) in H20.\nrewrite->H20. apply Cupdate_neq with (T:=Some t)(St:=Gamma) in H19. rewrite->H19. reflexivity.\nrewrite<-H18. apply H8. apply H17. apply subt_fn. apply sub_refl. apply H16. apply subtyping_refl.\napply subt_fn. apply sub_LH. apply subtyping_refl. apply subtyping_refl.\nCase (\"tapp\").\nintros. simpl. apply inversion_tapp in H1. inversion H1. inversion H2. inversion H3. inversion H4. inversion H5. inversion H6. inversion H7.\ninversion H8. inversion H10. inversion H12. inversion H14.  \napply t_sub with (T:=join x5 x6).\napply t_app with (T1:=x3)(T2:=x5)(b:=x6).\napply IHe1 with (T1:=T1). apply H0. apply t_sub with (T:=an (fn x3 x5) x2).\napply t_sub with (T:=an (fn x0 x5) x2). apply t_sub with (T:=an (fn x0 x1) x2).\napply H9. apply subt_fn. apply sub_refl. apply subtyping_refl. inversion H11. apply H25.\napply subt_fn. apply sub_refl. inversion H11. apply H24. apply subtyping_refl. apply subt_fn.\ninversion H11. apply H21. apply subtyping_refl. apply subtyping_refl.  \napply IHe2 with (T1:=T1). apply H0. apply t_sub with (T:=x4). apply H13. apply H15.\nreflexivity. apply H16. \nCase (\"tH\").\nintros. simpl. apply inversion_tH in H1. inversion H1.\napply t_sub with (T:=an x0 H). apply t_H. apply H2.\nQed.\n(*#######################end###################*)\nLemma subtyping_join:forall T b' b,\nsubsum_r b' b ->\njoin T b' < join T b.\nProof. intros. inversion H0. apply subtyping_refl. destruct T. simpl.\ndestruct r. destruct s. apply subt_int. apply sub_LH. apply subtyping_refl.\ndestruct s. apply subt_fn. apply sub_LH. apply subtyping_refl. apply subtyping_refl.\napply subtyping_refl. Qed.\nTheorem preservation: forall t t' T,\nhas_type empty_context t T ->\nt ==> t' ->\nhas_type empty_context t' T.\nProof. intros. generalize dependent t'. remember (@empty_context) as context.\n induction H0.\nCase (\"t_H\"). intros. inversion H1.\nCase (\"t_var\"). intros. inversion H1.      \nCase (\"t_con\"). intros. inversion H1.\nCase (\"t_abs\"). intros. inversion H1.\nCase (\"t_app\").  intros. inversion H1. subst. apply inversion_tH in H0_. \n                inversion H0_. destruct b. inversion H0. inversion H7.\n                destruct T2. simpl. apply t_H.\n                subst. \n                apply substitution_preserves_typing with (T1:=T).\n                apply inversion_tabs in H0_. inversion H0_.\n                inversion H0. inversion H2. inversion H3. inversion H4.\n                inversion H7. inversion H9. inversion H11. inversion H13.\n                assert (T1<T). apply subtyping_trans with (x:=x0)(y:=x0).\n                apply subtyping_refl. inversion H15. apply H23. apply H10.\n                apply t_sub with (T:=T1). apply H0_0. apply H16.\n                apply inversion_tabs in H0_. inversion H0_.\n                inversion H0. inversion H2. inversion H3. inversion H4.\n                inversion H7. inversion H9. inversion H11. inversion H13.\n                destruct b. simpl. assert (x1<T2). apply subtyping_trans with (x:=x2)(y:=x2).\n                apply subtyping_refl. apply H12. inversion H15. apply H24. apply t_sub with (T:=x1).\n                apply H8. apply H16. apply t_sub with (T:=join T2 L). simpl.\n                assert (x1<T2). apply subtyping_trans with (x:=x2)(y:=x2). apply subtyping_refl.\n                apply H12. inversion H15. apply H24. apply t_sub with (T:=x1).\n                apply H8. apply H16. apply subtyping_join. apply sub_LH.\n                subst. \n                apply t_app with (T1:=T1)(T2:=T2)(b:=b).\n                apply IHhas_type1 with (t':=t1')in H5. apply H5.\n                reflexivity. apply H0_0. reflexivity.  subst.\n                apply t_app with (T1:=T1)(T2:=T2)(b:=b). apply H0_.\n                apply IHhas_type2 with (t':=t2') in H6. apply H6.\n                reflexivity. reflexivity.\nCase (\"t_sub\"). subst. intros. apply t_sub with (T:=T). apply IHhas_type. reflexivity.\n                apply H2. apply H1. \nQed.\n(*###########end##########*)\n(*#########progress#########*)\nTheorem progress: forall t T,\nhas_type empty_context t T ->\nvalue t \\/ (exists t', t ==> t').\nProof. intros. remember (@empty_context) as context. induction H0.\nCase (\"t_H\").\n                left. apply v_H.\nCase (\"t_var\"). \n                subst. inversion H0.\nCase (\"t_con\").\n                left. apply v_c.\nCase (\"t_abs\").\n                left. destruct x. apply v_f.\nCase (\"t_app\").\n                right. subst. assert (A: empty_context = empty_context). reflexivity.\n                assert (B: empty_context = empty_context). apply A. apply IHhas_type1 in A.\n                apply IHhas_type2 in B. inversion A. inversion B. inversion H0. subst.\n                inversion H1. subst. apply inversion_tcon in H0_. inversion H0_. inversion H2.\n                inversion H3. inversion H4. inversion H6. inversion H8. rewrite->H7 in H10.\n                inversion H10. \n                subst. \n                apply inversion_tcon in H0_. inversion H0_. inversion H2. inversion H3.\n                inversion H4. inversion H6. inversion H8. rewrite->H7 in H10. inversion H10.\n                subst. \n                apply inversion_tcon in H0_. inversion H0_. inversion H2. inversion H3.\n                inversion H4. inversion H6. inversion H8. rewrite->H7 in H10. inversion H10.\n                subst.\n                exists ([(Id n) := t2]e). apply st_appabs. apply H1.\n                subst. exists tH. apply st_Happ. apply H1.\n                inversion H1. exists (tapp t1 x). apply st_app2. apply H0. apply H2.\n                inversion H0. exists (tapp x t2). apply st_app1. apply H1.\nCase (\"t_sub\"). subst. apply IHhas_type. reflexivity.\nQed.\n(*##########determinism#########*)\nTheorem determinism: forall t t' t'',\nt ==> t'  ->\nt ==> t'' ->\nt' = t''.\nProof. intros t. induction t.\nCase (\"tvar\").\n             intros. inversion H0. \nCase (\"tcon\").\n             intros. inversion H0.\nCase (\"tabs\"). \n             intros. inversion H0.\nCase (\"tapp\"). \n             intros. inversion H0. inversion H1. subst. inversion H6. subst. reflexivity.\n             subst. inversion H9. subst. inversion H5. subst. inversion H6. inversion H6.\n             inversion H6. subst. inversion H9. subst. inversion H5. subst. inversion H10.\n             subst. inversion H10. subst. inversion H10. subst. inversion H1. subst.\n             reflexivity. inversion H6. subst. inversion H5. subst. inversion H7. subst.\n             inversion H7. subst. inversion H7. subst. inversion H1. subst. inversion H5.\n             subst. inversion H5. subst. \n             apply IHt1 with (t':=t1')(t'':=t1'0) in H5. subst. reflexivity. apply H6.\n             subst. inversion H4. subst. inversion H5. subst.  inversion H5. subst.\n             inversion H5. subst. inversion H1. subst. inversion H7. subst.\n             inversion H6. subst. inversion H6. inversion H7. subst. inversion H6.\n             subst. inversion H6. subst. inversion H6. subst. inversion H7. subst. inversion H6.\n             subst. inversion H6. subst. inversion H6. subst. inversion H4. subst. inversion H7.\n             subst. inversion H7. subst. inversion H7. subst.\n            apply IHt2 with (t':=t2')(t'':=t2'0) in H6. subst. reflexivity.\n             apply H8.\nCase (\"tH\").\n             intros. inversion H0. \nQed.\n\nTheorem determinism_extended:forall e v v',\nLowLang.value v  ->\nLowLang.value v' ->\nmulti LowLang.step e v  ->\nmulti LowLang.step e v' ->\nv = v'.\nProof. intros. generalize dependent v'. induction H2.\nintros. inversion H0. subst. inversion H3. reflexivity. inversion H2. subst.\ninversion H3. reflexivity. inversion H2. subst. inversion H3. reflexivity.\ninversion H2.\nintros. apply IHmulti. apply H0. apply H3. inversion H4. subst. inversion H3. subst.\ninversion H1. subst. inversion H1. subst. inversion H1. subst. apply determinism with (t':=y0)in H1.\nsubst. apply H6. apply H5. Qed.\n\n(*############soundness############*) \nCorollary soundness : forall t t' T,\n  has_type empty_context t T -> \n  t ==>* t' ->\n ~((~exists t, t' ==> t)/\\(~ value t')).\nProof.\nintros. remember (@empty_context) as context.  \ngeneralize dependent T. induction H1.\nCase (\"multi_step\").\n     intros. subst. intros contra. inversion contra.\n     apply progress in H0. inversion H0.\n     SCase (\"left\"). apply H2 in H3. inversion H3.\n     SCase (\"right\"). apply contra in H3. inversion H3.\nCase (\"multi_ref\"). subst. intros. apply IHmulti with (T:=T).\n     apply preservation with (t':=y)in H2.  apply H2. \n     apply H0.\nQed.\n\n(*some additional lemmas for later use*)\nLemma multi_step_app1: forall t1 t1' t2,\nt1 ==>* t1' ->\ntapp t1 t2 ==>* tapp t1' t2.\nProof. intros. generalize dependent t2. induction H0.\nCase (\"multi_refl\"). intros. apply multi_refl.\nCase (\"multi_step\"). intros. assert (tapp x t2 ==> tapp y t2). \n                     apply st_app1. apply H0. specialize (IHmulti t2).\n                     apply multi_step with (tapp y t2). apply H2. apply IHmulti.\nQed. \n\nLemma multi_step_app2: forall v1 t2 t2',\nvalue v1 ->\nt2 ==>* t2' ->\ntapp v1 t2 ==>* tapp v1 t2'.\nProof. intros. generalize dependent v1. induction H1.\nCase (\"multi_refl\"). intros. apply multi_refl.\nCase (\"multi_step\"). intros. assert (tapp v1 x ==> tapp v1 y). apply st_app2. apply H2.\n                     apply H0. apply IHmulti in H2. apply multi_step with (tapp v1 y).\n                     apply H3. apply H2.\nQed.\n(*##########################*)\nEnd LowLang.\n\nModule Correspondence.\n\nFixpoint project (e : SecLang.tm) : LowLang.tm :=\nmatch e with\n(*variables*)\n| SecLang.tvar x => LowLang.tvar x\n(*constants*)\n| SecLang.tcon n L => LowLang.tcon n\n| SecLang.tcon n H => LowLang.tH\n(*protects*)\n(*| SecLang.tprot L e' => LowLang.tprot (project e')*)\n(**\nNote that [project (tprot L e')] should not return [tprot (project e')],for the\ncorrespondance between [SecLang.step] and [LowLang.step] breaks down,\nin [SecLang],\ntapp(tabs x T e L) v ==> tprot L ([x:=v]e)\nyet the following reduction relation is not defined in [LowLang]\ntapp(tabs x T (project e))(project v) ==>* tprot (project ([x:=v]e))\ninstead we should have,\ntapp (tabs x T (project e))(project v) ==>* [x:=project v](project e).\n\nThis is the main reason why \"the project of a low protection should not yield another protection\".\nIt leads to the consideration that [tprot] should be completely removed from [LowLang].\n*)\n(**\nAlso note that the above change also leads to \nsome modification of the auxiliary lemmas specified by Lu\n*)\n| SecLang.tprot L e' => project e'\n| SecLang.tprot H e' => LowLang.tH\n(*abstractions*)\n| SecLang.tabs x T e L => LowLang.tabs x T (project e) \n| SecLang.tabs x T e H => LowLang.tH\n(*applications*)\n| SecLang.tapp t1 t2 => LowLang.tapp (project t1)(project t2)\nend.\n\nLemma corresp_typing: forall Gamma e T,\n      SecLang.has_type Gamma e T ->\n      LowLang.has_type Gamma (project e) T.\n(**\nIntuition,\na. suppose we have a term in [SecLang] of [H], then by [project],\n   [project e] is equal to [tH] which can be typed freely in [LowLang]\nb. suppose it is of [L] instead, the typing rule in [LowLang] is not\n   different from that in [SecLang] regarding low security terms\nQed. \n*)\nProof. intros. induction H0.\nCase (\"t_var\").\n             simpl. apply LowLang.t_var. apply H0.\nCase (\"t_prot\").\n             subst. destruct b. simpl. apply IHhas_type. simpl.\n             destruct T. apply LowLang.t_H.\nCase (\"t_con\"). destruct b. simpl. apply LowLang.t_con. simpl. apply LowLang.t_H.\nCase (\"t_abs\").\n             destruct b. simpl. apply LowLang.t_abs. apply IHhas_type.\n             simpl. apply LowLang.t_H.\nCase (\"t_app\").\n             subst. simpl. apply LowLang.t_app with (T1:=T1)(T2:=T2)(b:=b).\n             apply IHhas_type1. apply IHhas_type2. reflexivity.\nCase (\"t_sub\"). apply LowLang.t_sub with (T:=T). apply IHhas_type.\n             apply H1.\nQed.\n\n\nLemma project_value:forall v,\nSecLang.value v ->\nLowLang.value (project v).\nProof. intros. inversion H0.\nsubst. destruct b. simpl. apply LowLang.v_c. simpl. apply LowLang.v_H.\nsubst. destruct b. simpl. apply LowLang.v_f. simpl. apply LowLang.v_H. Qed.\n\n\nLemma project_subst:forall x v e,\nSecLang.value v ->\nLowLang.subst x (project v)(project e) = project (SecLang.subst x v e).\nProof. intros. generalize dependent x. generalize dependent v. induction e.\nCase (\"tvar\"). intros. simpl. remember (beq_id x i) as B. destruct B. reflexivity.\n              simpl. reflexivity. \nCase (\"tprot\"). intros. simpl. destruct s. apply IHe. apply H0. simpl. reflexivity.\nCase (\"tcon\"). intros. simpl. destruct s. simpl. reflexivity. simpl. reflexivity.\nCase (\"tabs\"). intros. simpl. destruct s. remember (beq_id x i) as B. destruct B.\n               apply beq_id_eq in HeqB. subst. simpl. rewrite<-beq_id_refl. reflexivity.\n               simpl. rewrite<-HeqB. apply IHe with (x:=x) in H0. rewrite->H0. reflexivity.\n               simpl. reflexivity.\nCase (\"tapp\"). intros. simpl. assert (SecLang.value v). apply H0. apply IHe1 with (x:=x) in H0.\n               apply IHe2 with (x:=x) in H1. rewrite->H0. rewrite->H1. \n               reflexivity.\nQed.\n\n\n\nLemma corresp_step : forall t t',\nSecLang.step t t' ->\nmulti LowLang.step (project t)(project t').\nProof. intros. induction H0.\n(**\nIntuition,\na. according to [st_Happ] and [st_apabs] in [LowLang],\n   we do not protect the result of the application with\n   the label of the function being applied and as a consequence\n   the typing rule w.r.t. [LowLang] is simpler and there are less\n   steps regarding [st_appabs]\nb. consider the following case,\nin [SecLang],\ntprot H (tcon n L) ==> tcon n H\nwhile,\nproject (tprot H (tcon n L)) = tH = project (tcon n H)\nthus we have,\nin [LowLang],\ntH ==>* tH\n*)\nCase (\"prot\").\n                destruct b. simpl. apply IHstep.\n                simpl. apply multi_refl.\nCase (\"protL\").\n                simpl. apply multi_refl.\nCase (\"protHf\").\n                simpl. apply multi_refl.\nCase (\"protHc\").\n                simpl. apply multi_refl.\nCase (\"appabs\").\n                destruct b. simpl.  \n                apply multi_step with (y:= LowLang.subst x (project v)(project e)).\n                apply LowLang.st_appabs. destruct v. inversion H0. inversion H0. simpl.\n                destruct s. apply LowLang.v_c. apply LowLang.v_H. simpl. destruct s.\n                destruct i. apply LowLang.v_f. apply LowLang.v_H. inversion H0.\n                apply project_subst with (x:=x)(e:=e)in H0. rewrite->H0. apply multi_refl.\n                simpl. apply multi_step with (y:=LowLang.tH). apply LowLang.st_Happ.\n                destruct v. inversion H0. inversion H0. simpl. destruct s. apply LowLang.v_c.\n                apply LowLang.v_H. destruct s. simpl. destruct i. apply LowLang.v_f. simpl.\n                apply LowLang.v_H. inversion H0. apply multi_refl.\nCase (\"app1\"). \n                simpl. apply LowLang.multi_step_app1 with (t2:=project t2)in IHstep.\n                apply IHstep.\nCase (\"app2\"). \n                simpl. apply LowLang.multi_step_app2 with (v1:=project v1)in IHstep.\n                apply IHstep. destruct v1. inversion H0. inversion H0. destruct s. simpl. apply LowLang.v_c.\n                simpl. apply LowLang.v_H. simpl. destruct s. destruct i. apply LowLang.v_f. apply LowLang.v_H.\n                inversion H0.\nQed.\n\n\nLemma corresp_eval:forall e v,\nSecLang.value v ->\nmulti SecLang.step e v ->\nmulti LowLang.step (project e)(project v).\nProof. intros. induction H1. apply multi_refl.\n       apply corresp_step in H1. apply multi_trans with (y:=project y).\n       apply H1. apply IHmulti. apply H0.\nQed.\n\n(*security level of a term is different from that of its type*)\nLemma LowLang_high_term:forall v rt,\nLowLang.value v ->\nLowLang.has_type empty_context v (an rt H) ->\n~LowLang.has_type empty_context v (an rt L) ->\nv = LowLang.tH.\nProof.\nintros. inversion H0.\nCase (\"tcon\"). subst. apply LowLang.inversion_tcon in H1. inversion H1. inversion H3.\n               inversion H4. inversion H5. inversion H7. inversion H9. rewrite->H8 in H11.\n               destruct rt. assert (LowLang.has_type empty_context (LowLang.tcon n)(an int L)).\n               apply LowLang.t_con. apply H2 in H12. inversion H12. inversion H11.\nCase (\"tabs\"). subst. apply LowLang.inversion_tabs in H1. inversion H1. inversion H3. inversion H4.\n               inversion H5. inversion H6. inversion H8. inversion H10. inversion H12. inversion H14.\n               destruct rt. inversion H16. assert (LowLang.has_type empty_context (LowLang.tabs (Id n) T e)(an (fn t t0) L)).\n               assert (x0<t0). apply subtyping_trans with (x:=x1)(y:=x1). apply subtyping_refl. apply H13. inversion H16. apply H25.\n               apply LowLang.t_sub with (T:=an (fn t x0) L). assert (t<T). apply subtyping_trans with (x:=x)(y:=x). apply subtyping_refl.\n               inversion H16. apply H25. apply H11. apply LowLang.t_sub with (T:=an (fn T x0) L). apply H7. apply subt_fn. apply sub_refl.\n               apply H18. apply subtyping_refl. apply subt_fn. apply sub_refl. apply subtyping_refl. apply H17. apply H2 in H17. inversion H17.\nCase (\"tH\"). reflexivity.\nQed.\n\nCorollary NI_LowLang:forall e x v1 v2 rt,\nLowLang.value v1 ->\nLowLang.value v2 ->\nLowLang.has_type empty_context v1 (an rt H) ->\nLowLang.has_type empty_context v2 (an rt H) ->\n~LowLang.has_type empty_context v1 (an rt L) ->\n~LowLang.has_type empty_context v2 (an rt L) ->\nLowLang.has_type (Cupdate empty_context x (Some (an rt H))) e (an int L) ->\nLowLang.subst x v1 e = LowLang.subst x v2 e.\nProof. intros. apply LowLang_high_term with (rt:=rt) in H0. subst.\n       apply LowLang_high_term with (rt:=rt) in H1. subst. reflexivity.\n       apply H3. apply H5. apply H2. apply H4.\nQed.\n\n\nLemma LowLang_canonical_low_int:forall v,\nLowLang.value v ->\nLowLang.has_type empty_context v (an int L) ->\nexists n, v = LowLang.tcon n.\nProof. intros. inversion H0.\nCase (\"tcon\"). subst. exists n. reflexivity.\nCase (\"tabs\"). subst. apply LowLang.inversion_tabs in H1. inversion H1.\n               inversion H2. inversion H3. inversion H4. inversion H5.\n               inversion H7. inversion H9. inversion H11. inversion H13.\n               inversion H15.\nCase (\"tH\"). subst. apply LowLang.inversion_tH in H1. inversion H1. inversion H2.\n             inversion H4.\nQed.           \n\nLemma corresp_project_int:forall e n,\nSecLang.value e ->\nproject e =LowLang.tcon n ->\ne = SecLang.tcon n L.\nProof. intros. inversion H0.\nCase (\"tcon\"). subst. destruct b. simpl in H1. inversion H1. \n               reflexivity. simpl in H1. inversion H1.\nCase (\"tabs\"). subst. simpl in H1. destruct b. inversion H1.\n               inversion H1.\nQed.\n\nDefinition return_sec (t : SecLang.tm) : option Sec :=\nmatch t with\n|SecLang.tcon n L =>Some L\n|SecLang.tcon n H =>Some H\n|SecLang.tabs x T e L =>Some L\n|SecLang.tabs x T e H =>Some H\n|SecLang.tprot b e =>None\n|SecLang.tvar x =>None\n|SecLang.tapp t1 t2 =>None\nend.\n\nTheorem NI:forall x e v1 v2 w1 w2 rt,\nSecLang.value v1 ->\nSecLang.value v2 ->\nSecLang.value w1 ->\nSecLang.value w2 ->\nSecLang.has_type empty_context v1 (an rt H) ->\nSecLang.has_type empty_context v2 (an rt H) ->\nreturn_sec v1 = Some H ->\nreturn_sec v2 = Some H ->\nSecLang.has_type (Cupdate empty_context x (Some (an rt H))) e (an int L) ->\nmulti SecLang.step (SecLang.subst x v1 e) w1 ->\nmulti SecLang.step (SecLang.subst x v2 e) w2 ->\nw1 = w2.\nProof. \n(**\nStep_one: \nprove,\n      project (subst x v1 e) = project (subst x v2 e)\nNote that by [project_subst], the above goal canbe rearranged as follows,\n      subst x (project v1)(project e) = subst x (project v2)(project e)\nand by [NI_LowLang] we need the following to prove the goal,\na. value (project v1)\n   value (project v2)\nb. has_type empty_context (project v1)(an rt H)   \n   has_type empty_context (project v2)(an rt H)\nC. ~has_type empty_context (project v1) (an rt L)\n   ~has_type empty_context (project v2) (an rt L)\nd. has_type (Cupdate empty_context x (Some (an rt H))) (project e) (an int L).    \n*)             \nintros.\nassert (SecLang.has_type empty_context v1 (an rt H)). apply H4.\nassert (SecLang.has_type empty_context v2 (an rt H)). apply H5.\nassert (SecLang.has_type empty_context v1 (an rt H)). apply H4.\nassert (SecLang.has_type empty_context v2 (an rt H)). apply H5.\n apply corresp_typing in H4. apply corresp_typing in H5. \nassert (SecLang.has_type (Cupdate empty_context x (Some (an rt H))) e (an int L)).\napply H8.\nassert (SecLang.has_type (Cupdate empty_context x (Some (an rt H))) e (an int L)).\napply H8.\n apply corresp_typing in H8.\nassert (~LowLang.has_type empty_context (project v1) (an rt L)). intros contra.\ndestruct v1. simpl in H6. inversion H6. simpl in H6. inversion H6. destruct s.\nsimpl in H6. inversion H6. simpl in contra. apply LowLang.inversion_tH in contra.\ninversion contra. inversion H17. inversion H19. inversion H22. destruct s. simpl in H6.\ninversion H6. simpl in contra. apply LowLang.inversion_tH in contra. inversion contra.\ninversion H17. inversion H19. inversion H22. simpl in H6. inversion H6.\nassert (~LowLang.has_type empty_context (project v2) (an rt L)). intros contra.\ndestruct v2. simpl in H7. inversion H7. simpl in H7. inversion H7. destruct s. simpl in H7.\ninversion H7. simpl in contra. apply LowLang.inversion_tH in contra. inversion contra. inversion H18.\ninversion H20. inversion H23. destruct s. simpl in H7. inversion H7. simpl in contra. apply LowLang.inversion_tH in contra.\ninversion contra. inversion H18. inversion H20. inversion H23. simpl in H7. inversion H7.\nassert (SecLang.value v1). apply H0. assert (SecLang.value v2). apply H1.\napply project_value in H0. apply project_value in H1.\napply NI_LowLang with (e:=project e)(x:=x)(v1:=project v1)(v2:=project v2)(rt:=rt) in H0.\nassert (LowLang.subst x (project v1)(project e) = project (SecLang.subst x v1 e)). apply project_subst. apply H19.\nassert (LowLang.subst x (project v2)(project e) = project (SecLang.subst x v2 e)). apply project_subst. apply H20.\nrewrite->H0 in H21. rewrite->H21 in H22. \n(**now we have,\nproject (SecLang.subst x v1 e) = project (SecLang.subst x v2 e)\nmulti LowLang.step (project (SecLang.subst x v1 e))(project w1)\nmulti LowLang.step (project (SecLang.subst x v2 e))(project w2)\n*)\n\n(**\nStep two:\nshow that project w1 =project w2 by determinism in [LowLang]\n*)\nassert (SecLang.value w1). apply H2. assert (SecLang.value w2). apply H3.\nassert (SecLang.value w1). apply H2. assert (SecLang.value w2). apply H3.\nassert (SecLang.value w1). apply H2. assert (SecLang.value w2). apply H3.\napply corresp_eval with (e:=SecLang.subst x v1 e)in H2.\napply corresp_eval with (e:=SecLang.subst x v2 e)in H3.\napply project_value in H19. apply project_value in H20. rewrite->H22 in H2.\napply project_value in H23.\napply LowLang.determinism_extended with (e:=project (SecLang.subst x v2 e))(v:=project w1)(v':=project w2)in H23.\n(**\nStep three:\nshow that firstly \nexists n1, exists n2,\nproject w1 = tcon n1 and project w2 = ton n2\n*)\n\napply SecLang.substitution_preserves_typing with (Gamma:=empty_context)(x:=x)(T2:=an int L)(e:=e)in H11.\napply SecLang.type_uniqueness with (t':=w1)in H11. apply corresp_typing in H11. apply project_value in H25.\napply LowLang_canonical_low_int in H25. inversion H25. apply corresp_project_int with (n:=x0)in H27.\nrewrite->H27. \napply SecLang.substitution_preserves_typing with (Gamma:=empty_context)(x:=x)(T2:=an int L)(e:=e)in H12.\napply SecLang.type_uniqueness with (t':=w2)in H12. apply corresp_typing in H12. apply project_value in H24.\napply LowLang_canonical_low_int in H24. inversion H24. apply corresp_project_int with (n:=x1)in H28.\nrewrite->H28. \nrewrite->H27 in H23. rewrite->H28 in H23. simpl in H23. inversion H23. reflexivity.\napply H30. apply H12. apply H10. apply H15. apply H29. apply H11. apply H9. \napply H15. apply project_value. apply H24. apply H2.  apply H3. apply H10. apply H9.\napply H1. apply H4. apply H5. apply H17. apply H18.  apply H8.\nQed. \n\n\n\nEnd Correspondence.\n\n", "meta": {"author": "peterthiemann", "repo": "LJGS", "sha": "e3c56f724a69c45cdf435035e53450c3b2483270", "save_path": "github-repos/coq/peterthiemann-LJGS", "path": "github-repos/coq/peterthiemann-LJGS/LJGS-e3c56f724a69c45cdf435035e53450c3b2483270/security_typing_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6783700709576392}}
{"text": "(* * Peano Arithmetic *)\n(* ** Axioms of PA, excluding induction *)\nRequire Export Undecidability.FOL.Syntax.Core.\nRequire Export Undecidability.FOL.Arithmetics.Signature.\nRequire Import Undecidability.FOL.Syntax.Facts.\nImport Vector.VectorNotations.\nRequire Import List.\nImport FullSyntax.\nExport FullSyntax.\n\n#[global] Existing Instance falsity_on.\n\nDefinition ax_add_zero :=  ∀  (zero ⊕ $0 == $0).\nDefinition ax_add_rec :=   ∀∀ ((σ $0) ⊕ $1 == σ ($0 ⊕ $1)).\nDefinition ax_mult_zero := ∀  (zero ⊗ $0 == zero).\nDefinition ax_mult_rec :=  ∀∀ (σ $1 ⊗ $0 == $0 ⊕ $1 ⊗ $0).\n\n(* Fragment only containing the defining equations for addition and multiplication. *)\nDefinition FA := ax_add_zero :: ax_add_rec :: ax_mult_zero :: ax_mult_rec :: nil.\n\n(* Equality axioms for the PA signature *)\n\nDefinition ax_refl :=  ∀   $0 == $0.\nDefinition ax_sym :=   ∀∀  $1 == $0 → $0 == $1.\nDefinition ax_trans := ∀∀∀ $2 == $1 → $1 == $0 → $2 == $0.\n\nDefinition ax_succ_congr := ∀∀ $0 == $1 → σ $0 == σ $1.\nDefinition ax_add_congr := ∀∀∀∀ $0 == $1 → $2 == $3 → $0 ⊕ $2 == $1 ⊕ $3.\nDefinition ax_mult_congr := ∀∀∀∀ $0 == $1 → $2 == $3 → $0 ⊗ $2 == $1 ⊗ $3.\n\nDefinition EQ :=\n  ax_refl :: ax_sym :: ax_trans :: ax_succ_congr :: ax_add_congr :: ax_mult_congr :: nil.\n\nDefinition FAeq :=\n  EQ ++ FA.\n\n\n(* Defines numerals i.e. a corresponding term for every natural number *)\nFixpoint μ n :=  match n with\n                   O => zero\n                 | S x => σ (μ x)\n                 end.\nDefinition num := μ.\n  \nLemma num_subst k ρ : (num k)`[ρ] = num k.\nProof.\n  induction k; cbn; congruence.\nQed.\n\nLemma num_bound n k : bounded_t k (num n).\nProof.\n  induction n; cbn; constructor.\n  - intros t []%Vectors.In_nil.\n  - now intros t [-> | []%Vectors.In_nil]%vec_cons_inv.\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/FOL/Arithmetics/FA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6783700517982838}}
{"text": "Require Export ZArith.\nRequire Export Arith.\n\n\nFixpoint check_range (v:Z)(r:nat)(sr:Z){struct r} : bool :=\n  match r with\n    O => true\n  | S r' =>\n    match (v mod sr)%Z with\n      Z0 => false\n    | _ => check_range v r' (Zpred sr)\n    end\n  end.\n\nDefinition check_primality (n:nat) :=\n  check_range (Z_of_nat n)(pred (pred n))(Z_of_nat (pred n)).\n\nTheorem verif_divide :\n    forall m p:nat, 0 < m -> 0 < p ->\n    (exists q:nat, m = q*p) -> (Z_of_nat m mod Z_of_nat p = 0)%Z.\nProof.\n intros m p Hltm Hltp (q, Heq); rewrite Heq.\n rewrite inj_mult.\n replace (Z_of_nat q * Z_of_nat p)%Z with (0 + Z_of_nat q * Z_of_nat p)%Z;\n    try ring.\n rewrite Z_mod_plus; auto.\n omega.\nQed.\n\nTheorem divisor_smaller :\n    forall m p:nat, 0 < m -> forall q:nat, m = q*p -> q <= m.\nProof.\n intros m p Hlt; case p.\n -  intros q Heq; rewrite Heq in Hlt; rewrite mult_comm in Hlt.\n     elim (lt_irrefl 0);exact Hlt.\n -  intros p' q; case q.\n    +  intros Heq; rewrite Heq in Hlt.\n       elim (lt_irrefl _ Hlt).\n    + intros q' Heq; rewrite Heq.\n      rewrite mult_comm; simpl; auto with arith.\nQed.\n\nTheorem Zabs_nat_0 : forall x:Z, Zabs_nat x = 0 -> (x = 0)%Z.\nProof.\n intros x; case x.\n -  simpl; auto.\n -  intros p Heq; elim (lt_irrefl 0).\n    pattern 0 at 2; rewrite <- Heq.\n    simpl; apply lt_O_nat_of_P.\n -  intros p Heq; elim (lt_irrefl 0).\n    pattern 0 at 2; rewrite <- Heq.\n    simpl; apply lt_O_nat_of_P.\nQed.\n\nTheorem Z_to_nat_and_back :\n forall x:Z, (0 <= x)%Z -> (Z_of_nat (Zabs_nat x))=x.\nProof.\n intros x; case x.\n - reflexivity. \n -  intros p Hd; elim p.\n   +  unfold Zabs_nat; intros p' Hrec; rewrite nat_of_P_xI.\n      rewrite inj_S,  inj_mult,  Zpos_xI.\n      unfold Zsucc; rewrite Hrec;  simpl; auto.\n   +  unfold Zabs_nat; intros p' Hrec; rewrite nat_of_P_xO.\n      rewrite inj_mult,  Zpos_xO.\n      unfold Zsucc; rewrite Hrec; simpl; auto.\n   +  simpl; auto.\n \n -  intros p' Hd; elim Hd;auto.\nQed.\n\nTheorem  check_range_correct :\n  forall (v:Z)(r:nat)(rz:Z),\n  (0 < v)%Z -> Z_of_nat (S r) = rz -> check_range v r rz = true ->\n  ~(exists k:nat, k <= S r /\\ k <> 1 /\\ \n                       (exists q:nat, Zabs_nat v = q*k)).\nProof.\n intros v r; elim r.\n -  intros rz Hlt H1 H2 Hex; case Hex; intros k; case k.\n   +  intros (Hle, (Hne1, (q, Heq))).\n      rewrite mult_comm in Heq; simpl in Heq.\n      rewrite (Zabs_nat_0 _ Heq) in Hlt.\n      elim (Zlt_irrefl 0); assumption.\n \n   + intros k' (Hle, (Hne1, (q, Heq))).\n     inversion Hle.\n     *  assert (H':k'=0) by  assumption.\n        rewrite H' in Hne1; elim Hne1;auto.\n     *  assert (H': S k' <= 0) by  assumption.\n        inversion H'.\n\n -  intros r' Hrec rz Hlt H1 H2 Hex; case Hex; intros k; case k.\n    intros (Hle, (Hne1, (q, Heq))).\n    rewrite mult_comm in Heq; simpl in Heq.\n    rewrite (Zabs_nat_0 _ Heq) in Hlt.\n    elim (Zlt_irrefl 0); assumption.\n    intros k' (Hle, (Hne1, (q, Heq))).\n    inversion Hle.\n    rewrite <- H1 in H2. \n    rewrite <- (Z_to_nat_and_back v) in H2.\n    assert (Hmod:(Z_of_nat (Zabs_nat v) mod Z_of_nat (S (S r')) = 0)%Z).\n    +  apply verif_divide.\n       replace 0 with (Zabs_nat 0%Z).\n       apply Zabs_nat_lt.\n       omega.\n       simpl; auto.\n       auto with arith.\n       exists q.\n       assert (H': k' = S r') by  assumption.\n       rewrite <- H'.\n       assumption.\n    +  unfold check_range in H2.\n       rewrite Hmod in H2.\n       discriminate H2.\n      + omega.\n      + unfold check_range in H2; fold check_range in H2.\n        case_eq ((v mod rz)%Z).\n        *  intros Heqmod; rewrite Heqmod in H2; discriminate H2.\n        *  intros pmod Heqmod; rewrite Heqmod in H2;  elim (Hrec (Zpred rz) Hlt).\n           rewrite <- H1; repeat rewrite inj_S;  rewrite <- Zpred_succ; auto. \n          assumption.\n          exists (S k'); repeat split;auto.\n          exists q; assumption.\n\n        * intros p Hmod; elim (Z_mod_lt v rz).\n          rewrite Hmod; unfold Zle; simpl; intros Hle'; elim Hle';auto.\n          rewrite <- H1; rewrite inj_S; unfold Zsucc; generalize (Zle_0_nat (S r')).\n          intros; omega.\nQed.\n\nTheorem nat_of_P_Psucc : \n forall p:positive, nat_of_P (Psucc p) = S (nat_of_P p).\nProof.\n intros p; elim p.\n - simpl; intros p'; rewrite nat_of_P_xO.\n   intros Heq; rewrite Heq.\n   rewrite nat_of_P_xI; ring.\n- intros p' Heq; simpl; rewrite nat_of_P_xI; rewrite nat_of_P_xO;auto.\n-  auto.\nQed.\n\nTheorem nat_to_Z_and_back:\n forall n:nat, Zabs_nat (Z_of_nat n) = n.\nProof.\n intros n; elim n.\n -  auto.\n - intros n'; simpl; case n'.\n  +  simpl; auto.\n  +  intros n''; simpl; rewrite nat_of_P_Psucc; intros Heq; rewrite Heq; auto.\nQed.\n\nTheorem check_correct :\n  forall p:nat, 0 < p -> check_primality p = true ->\n  ~(exists k:nat, k <> 1 /\\ k <> p /\\ (exists q:nat, p = q*k)).\nProof.\n unfold lt; intros p Hle; elim Hle.\n -  intros Hcp (k, (Hne1, (Hne1bis, (q, Heq)))); rewrite mult_comm in Heq.\n    assert (Hle' : k < 1).\n    +  elim (le_lt_or_eq k 1); try(intuition; fail).\n       apply divisor_smaller with (2:= Heq); auto.\n    +  case_eq k.\n       *  intros Heq'; rewrite Heq' in Heq; simpl in Heq; discriminate Heq.\n       *  intros; omega.\n -  intros p' Hlep' Hrec; unfold check_primality.\n    assert (H':(exists p'':nat, p' = (S p''))).\n   +  inversion Hlep'.  \n      *     exists 0; auto.\n      *  eapply ex_intro;eauto.\n   +  elim H'; intros p'' Hp''; rewrite Hp''.\n      repeat rewrite <- pred_Sn.\n      intros Hcr Hex;  elim check_range_correct with (3:= Hcr).\n     *  rewrite inj_S; generalize (Zle_0_nat (S p'')).\n        intros; omega.\n     *  auto.\n     *  elim Hex; intros k (Hne1, (HneSSp'', (q, Heq))); exists k.\n       split.\n       assert (HkleSSp'': k <= S (S p'')).\n       apply (divisor_smaller (S (S p'')) q); auto with arith.\n       rewrite mult_comm; assumption.\n       omega.\n       split.\n       assumption.\n       exists q; now  rewrite nat_to_Z_and_back.\nQed.\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch16_proof_by_reflection/SRC/verif_divide.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6783700442646394}}
{"text": "Require Import Coq.Program.Equality.\n\nInductive List (A: Type) : nat -> Type :=\n  | Nil : List A 0\n  | Cons : forall n: nat,  A -> List A n -> List A (S n).\n\nArguments Nil {A}.\nArguments Cons {A n}.\n\nDefinition len {A: Type} {n: nat} (l: List A n) : nat := n.\n\nTheorem len_ok : forall A: Type, forall n : nat, forall l : List A n, forall a : A, S (len l) = len (Cons a l).\nProof.\n  intros. cbv. trivial.\nQed.\n\nTheorem o_means_empty : forall A: Type, forall l: List A O, l = Nil.\nProof.\n  intros A l. dependent destruction l. trivial.\nQed.\n\nInductive UList (A: Type) : Type :=\n  | UNil : UList A\n  | UCons : forall l : UList, forall a : A, Unique a l -> UList A\nwith Unique {A : Type} (a: A) (l : UList A) : Prop :=\n  | UniqNil : Unique l a\n  | UniqCons : forall h : A, forall l : UList A, Unique l -> h <> a -> Unique a (UCons l h).\n\n\nInductive SEvenList (A: Type) (ord : A -> A -> bool) :=\n  | SEvenNil : SEvenList A ord\n  | SEvenCons : forall a: A, forall l : SOddList A ord,\n       l = SOddCons h t -> ord a h = true -> SEvenList A ord\nwith SOddList (A: Type) (ord : A -> A -> bool) :Type :=\n  | SOddCons : forall a : A, forall l : SEvenList A ord,\n      (l = SEvenNil A ord \\/ (l = SEvenCons h t /\\ ord a h = true)) -> SOddList A ord.\n", "meta": {"author": "speederking07", "repo": "magisterka", "sha": "602d1e328ac4a396c282e241744d129573a65381", "save_path": "github-repos/coq/speederking07-magisterka", "path": "github-repos/coq/speederking07-magisterka/magisterka-602d1e328ac4a396c282e241744d129573a65381/backup/dependent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6783566651776464}}
{"text": "From mathcomp Require Import ssreflect seq ssrfun ssrbool ssrnat.\nFrom mf Require Import all_mf.\nRequire Import pointwise reals pseudo_metrics.\nRequire Import Reals Psatz Classical ChoiceFacts Morphisms ProofIrrelevance ProofIrrelevanceFacts.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope pseudometric_scope.\nLocal Open Scope R_scope.\n\nSection PseudoMetricSpaces.\n  Class PseudoMetricSpace :=\n    {carrier:> Type;\n     distance: carrier * carrier -> R;\n     pseudo_metric: distance \\is_pseudometric_on carrier}.\n\n  Coercion carrier: PseudoMetricSpace >-> Sortclass.\n\n  Global Instance pm (M: PseudoMetricSpace): distance \\is_pseudometric.\n  Proof. exact/pseudo_metric. Qed.\n  Notation d := distance.\n\n  Context (M: PseudoMetricSpace).\n  Implicit Types (x y z: M).\n    \n  Lemma dst_le x y z r r' q: d(x,z) <= r -> d(z,y) <= r' -> r + r' <= q -> d(x,y) <= q.\n  Proof. by apply dst_le. Qed.\n\n  Lemma le_dst x y z r r' q: r + r' <= q -> d(x,z) <= r -> d(z,y) <= r' -> d(x,y) <= q.\n  Proof. by apply le_dst. Qed.\n\n  Lemma dst_lt x y z r r' q: d(x,z) <= r -> d(z,y) <= r' -> r + r' < q -> d(x,y) < q.\n  Proof. by apply dst_lt. Qed.\nEnd PseudoMetricSpaces.\nNotation d := distance.\n\nNotation limit := (limit d).\nNotation \"xn ~> x\" := (limit xn x) (at level 23): pseudometric_scope.\nNotation \"x \\limit_of xn\" := (xn ~> x) (at level 23): pseudometric_scope.\nNotation \"x \\is_limit_of xn\" := (xn ~> x) (at level 23): pseudometric_scope.\nSection limits.\n  Context (M: PseudoMetricSpace).\n  Implicit Types (x y z: M).\n  \n  Lemma lim_dst xn x y: x \\limit_of xn -> y \\limit_of xn  -> d(x,y) = 0.\n  Proof. by apply lim_dst. Qed.\n\n  Lemma lim_cnst x: x \\limit_of (cnst x).\n  Proof. by apply lim_cnst. Qed.\n  \n  Lemma lim_tpmn xn x: x \\limit_of xn <->\n    (forall n, exists N, forall m, (N <= m)%nat -> d(x,xn m) <= /2 ^ n).\n  Proof. by apply lim_tpmn. Qed.\n\n  Lemma dst0_tpmn x y: d(x,y) = 0 <-> (forall n, d(x,y) <= / 2 ^ n).\n  Proof. by apply dst0_tpmn. Qed.\nEnd limits.\n\nNotation \"A \\dense_subset\" := (A \\dense_subset_wrt d) (at level 35): pseudometric_scope.\nNotation \"A \\is_dense_subset\":= (A \\dense_subset) (at level 35): pseudometric_scope.\nNotation \"xn \\dense\" := (xn \\dense_wrt d) (at level 35): pseudometric_scope.\nNotation \"xn \\is_dense\" := (xn \\dense) (at level 35): pseudometric_scope.\nNotation \"xn \\dense_sequence\" := (xn \\dense) (at level 35): pseudometric_scope.\nNotation \"xn \\is_dense_sequence\" := (xn \\dense) (at level 35): pseudometric_scope.\nNotation closure A := (closure d A).\nSection density.\n  Context (M: PseudoMetricSpace).\n  \n  Lemma dns_tpmn (A: subset M):\n    A \\is_dense_subset <-> forall x n, exists y, y \\from A /\\ d(x,y) <= /2^n.\n  Proof. exact/dns_tpmn. Qed.  \n  \n  Lemma dseq_dns (xn: sequence_in M):\n    xn \\is_dense <-> (codom (F2MF xn)) \\is_dense_subset. \n  Proof. exact/dseq_dns. Qed.\n\n  Lemma dseq_tpmn (xn: sequence_in M):\n    xn \\is_dense <-> forall x n, exists k, d(x,xn k) <= /2^n.\n  Proof. exact/dseq_tpmn. Qed.\n  \n  Lemma subs_clos A: A \\is_subset_of closure A.\n  Proof. by apply subs_clos. Qed.\n\n  Lemma dns_clos A: A \\is_dense_subset <-> closure A === All.\n  Proof. exact/dns_clos. Qed.\nEnd density.\n\nNotation Cauchy_sequences:= (Cauchy_sequences d).  \nNotation \"xn \\Cauchy\" := (xn \\Cauchy_wrt d) (at level 45): pseudometric_scope.\nNotation \"xn \\Cauchy_sequence\" := (xn \\Cauchy) (at level 45): pseudometric_scope.\nNotation \"xn \\is_Cauchy\" := (xn \\Cauchy) (at level 45): pseudometric_scope.\nNotation \"xn \\is_Cauchy_sequence\" := (xn \\Cauchy) (at level 45): pseudometric_scope.\nNotation complete M := (@complete M d).\nNotation \"M \\is_complete\" := (complete M) (at level 45): metric_scope.\nSection Cauchy_sequences.\n  Context (M: PseudoMetricSpace).\n  Implicit Types (x y z: M) (xn yn: sequence_in M).\n  \n  Lemma lim_cchy: dom limit \\is_subset_of Cauchy_sequences.\n  Proof. by apply lim_cchy. Qed.  \n      \n  Lemma cchy_tpmn xn: xn \\Cauchy <->\n    (forall k, exists N, forall n m,\n            (N <= n <= m)%nat -> d (xn n, xn m) <= /2^k).\n  Proof. by apply cchy_tpmn. Qed.\n\n  Lemma lim_evb xn mu (x: M): x \\limit_of xn -> eventually_big mu -> limit (xn \\o_f mu) x.\n  Proof. exact/lim_evb. Qed.\n  \n  Lemma cchy_evb xn mu: xn \\Cauchy -> eventually_big mu -> (xn \\o_f mu) \\Cauchy.\n  Proof. exact/cchy_evb. Qed.\nEnd Cauchy_sequences.\n\nSection efficient_convergence.\n  Context (M: PseudoMetricSpace).\n  Local Notation fast_Cauchy_sequences := (fast_Cauchy_sequences d).\n  Local Notation \"xn \\fast_Cauchy\" := (xn \\is_fast_Cauchy_sequence_wrt d) (at level 35).\n  Local Notation efficient_limit := (efficient_limit d).\n  \n  Lemma fchy_cchy: fast_Cauchy_sequences \\is_subset_of Cauchy_sequences.\n  Proof. exact/fchy_cchy. Qed.\n  \n  Lemma lim_eff_spec: efficient_limit =~= limit|_(fast_Cauchy_sequences).\n  Proof. exact lim_eff_spec. Qed.\n    \n  Lemma lim_eff_lim : limit \\extends efficient_limit.\n  Proof. exact lim_eff_lim. Qed.\n\n  Lemma fchy_lim_eff: complete M ->\n    fast_Cauchy_sequences === dom efficient_limit.\n  Proof. exact fchy_lim_eff. Qed.\n\n  Lemma lim_eff_dst xn x y: efficient_limit xn x -> efficient_limit xn y -> d(x, y) = 0.\n  Proof. by apply lim_eff_dst. Qed.\n\n  Lemma lim_tight_lim_eff: limit \\tightens efficient_limit.\n  Proof. exact lim_tight_lim_eff. Qed.\n\n  Lemma cchy_eff_suff xn:\n    (forall n m, (n <= m)%nat -> d (xn n, xn m) <= /2^n + /2^m) -> xn \\fast_Cauchy.\n  Proof. by apply cchy_eff_suff. Qed.\nEnd efficient_convergence.\nNotation fast_Cauchy_sequences := (fast_Cauchy_sequences d).  \nNotation \"xn \\fast_Cauchy\" := (xn \\fast_Cauchy_wrt d) (at level 45): pseudometric_scope.\nNotation \"xn \\fast_Cauchy_sequence\" := (xn \\fast_Cauchy) (at level 45): pseudometric_scope.\nNotation \"xn \\is_fast_Cauchy_sequence\" := (xn \\fast_Cauchy) (at level 45): pseudometric_scope.\nNotation efficient_limit:= (efficient_limit d).\nNotation \"x \\efficient_limit_of xn\" := (efficient_limit xn x) (at level 45): pseudometric_scope.\n\nSection continuity.\n  Context (M M': PseudoMetricSpace).\n  Context (f: M -> M').\n  Implicit Types (x y: M) (xn yn: sequence_in M).\n  Local Notation continuous_in x := (continuity_point d d f x).\n  Local Notation continuous := (f \\continuous_wrt d \\and d).\n  Local Notation continuity_points := (continuity_points d d f).\n  Local Notation sequential_continuity_points := (sequential_continuity_points d d f).\n  Local Notation sequentially_continuous := (f \\sequentially_continuous_wrt d \\and d).\n\n  Lemma cntp_tpmn x:\n    continuous_in x <-> forall n, exists m, forall x', d (x, x') <= /2^m -> d (f x, f x') <= /2^n.\n  Proof. exact/cntp_tpmn. Qed.\n  \n  Lemma cont_tpmn:\n    continuous <-> forall x n, exists m, forall x', d (x, x') <= /2^m -> d (f x, f x') <= /2^n.\n  Proof. exact/cont_tpmn. Qed.\n  \n  Lemma cntp_all: continuous <-> continuity_points === All.\n  Proof. exact/cntp_all. Qed.\n\n  Lemma scntp_all: sequentially_continuous <-> sequential_continuity_points === All.\n  Proof. exact/scntp_all. Qed.\n\n  Lemma cntp_scntp: continuity_points \\is_subset_of sequential_continuity_points.\n  Proof. exact/cntp_scntp. Qed.\n  \n  Lemma cont_scnt: continuous -> sequentially_continuous.\n  Proof. exact/cont_scnt. Qed.\nEnd continuity.\nNotation \"f \\continuous_in x\" :=\n  (continuity_point d d  f x) (at level 35): pseudo_metric_scope.\nNotation continuity_points:= (continuity_points d d).\nNotation \"f \\continuous\" := (continuous d d f) (at level 2): pseudo_metric_scope.\nNotation \"f \\is_continuous\" := (f \\continuous_wrt d \\and d) (at level 2): pseudo_metric_scope.\nNotation sequential_continuity_points := (sequential_continuity_points d d).\nNotation \"f \\sequentially_continuous_in x\" :=\n  (sequential_continuity_point d d f x) (at level 40): pseudo_metric_scope.\nNotation \"f \\sequentially_continuous\" :=\n  (f \\sequentially_continuous_wrt d \\and d) (at level 40): pseudo_metric_scope.\nNotation \"f \\is_sequentially_continuous\" :=\n  (f \\sequentially_continuous_wrt d \\and d) (at level 40): pseudo_metric_scope.\n\nDelimit Scope pseudo_metric_scope with pmetric.\nSection subspaces.\n  Context (M: PseudoMetricSpace).\n\n  Global Instance subspace (A: subset M): PseudoMetricSpace.\n    exists {x | x \\from A} (fun xy => d (sval xy.1, sval xy.2)).\n    split; first by move => x y; apply dst_pos.\n    - by move => x y; apply dst_sym.\n    - by move => x; apply dstxx.\n    by move => x y z; apply dst_trngl.\n  Defined.\nEnd subspaces.\n", "meta": {"author": "FlorianSteinberg", "repo": "metric", "sha": "b34f29091173ffe079b4d4b6eab21061b81a930c", "save_path": "github-repos/coq/FlorianSteinberg-metric", "path": "github-repos/coq/FlorianSteinberg-metric/metric-b34f29091173ffe079b4d4b6eab21061b81a930c/pseudo_metric_spaces.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6783566586160068}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) (lf2 : natural)\n  : natural := plus Zero lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj164_coqofml_7l40R9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6782556993095915}}
{"text": "Require Import OrderedType.\nRequire Import OrderedTypeEx.\n\nModule Type PairOrderedType_Type (O1 O2:OrderedType).\n\n Module MO1:=OrderedTypeFacts(O1).\n Module MO2:=OrderedTypeFacts(O2).\n\n Definition t := prod O1.t O2.t.\n\n Definition eq x y := O1.eq (fst x) (fst y) /\\ O2.eq (snd x) (snd y).\n\n Definition lt x y :=\n    O1.lt (fst x) (fst y) \\/\n    (O1.eq (fst x) (fst y) /\\ O2.lt (snd x) (snd y)).\n\n Parameter eq_refl : forall x : t, eq x x.\n \n Parameter eq_sym : forall x y : t, eq x y -> eq y x.\n\n Parameter eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z.\n\n Parameter lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z.\n\n Parameter 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\n Parameter eq_dec : forall x y : t, {eq x y} + {~ eq x y}.\n\nEnd PairOrderedType_Type.", "meta": {"author": "doerrie", "repo": "confinement-proof", "sha": "db7bfb3522990d0820de64f13baa97b67e694c44", "save_path": "github-repos/coq/doerrie-confinement-proof", "path": "github-repos/coq/doerrie-confinement-proof/confinement-proof-db7bfb3522990d0820de64f13baa97b67e694c44/PairOrderedType_Type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6782556903318027}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_collinear4.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_rayimpliescollinear : \n   forall A B C, \n   Out A B C ->\n   Col A B C.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists J, (BetS J A C /\\ BetS J A B)) by (conclude_def Out );destruct Tf as [J];spliter.\nassert (neq J A) by (forward_using lemma_betweennotequal).\nassert (Col J A B) by (conclude_def Col ).\nassert (Col J A C) by (conclude_def Col ).\nassert (Col A B C) by (conclude lemma_collinear4).\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_rayimpliescollinear.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.6782018556524764}}
{"text": "(*\n   雪江明彦「代数学1群論入門」日本評論社\n   本文に沿って、coqにて展開する。\n   \n   2011_03_19 Sectionを使い、群に共通の定義をまとめて定義した。\n   2011_03_20 Ltac でtacticsをまとめた。\n   *)\n\n\nRequire Import Setoid.                      (* rewrite at *)\n\n\nSection Group.\n  Variable G : Set.\n  (* 演算子 *)\n  Variable App : G -> G -> G.\n  Infix \"**\" := App (at level 61, left associativity).\n  (* 定義 2.1.1 (1) *) (* 単位元 *)\n  Variable E : G.\n  (* 定義 2.1.1 (2) *) (* 逆元 *)\n  Variable Inv : G -> G.\n  \n  (* 定義 2.1.1 (1) *) (* 単位元 *)\n  Axiom identity_r :\n    forall x, x ** E = x.\n  Axiom identity_l :\n    forall x, E ** x = x.\n  \n  (* 定義 2.1.1 (2) *) (* 逆元 *)\n  Axiom inverse_r :\n    forall x, x ** (Inv x) = E.\n  Axiom inverse_l :\n    forall x, (Inv x) ** x = E.\n  \n  (* 定義 2.1.1 (3) *) (* 結合則 *)\n  Axiom associative_law :\n    forall x y z, x ** (y ** z) = (x ** y) ** z.\n  \n  Theorem right_law : \n    forall a b x, a = b -> a ** x = b ** x.\n  Proof. \n    intros a b x H. \n    rewrite H.\n    reflexivity.\n  Qed.\n  Theorem left_law : \n    forall a b x, a = b -> x ** a = x ** b.\n  Proof. \n    intros a b x H. \n    rewrite H.\n    reflexivity.\n  Qed.\n  (* 暗黙の裏公理。両辺にxを掛ける *)\n  (*Axiom right_law :\n    forall a b x, a = b -> a ** x = b ** x.\n  Axiom left_law :\n    forall a b x, a = b -> x ** a = x ** b.\n  *)\n  \n  (* 例題 2.1.7 *)\n  Goal forall x y z w : G,\n    x ** ((y ** z) ** w) = (x ** y) ** (z ** w).\n  Proof.\n    intros.\n    rewrite <- associative_law.\n    rewrite associative_law.\n    reflexivity.\n  Qed.\n\n\n  Ltac insert_inv_l B A :=                  (* B の左に (Inv A) ** A を掛ける *)\n    rewrite <- (identity_l B);\n      rewrite <- (inverse_l A).\n  \n  Ltac insert_inv_r B A :=                  (* B の右に A ** (Inv A) を掛ける *)\n    rewrite <- (identity_r B);\n      rewrite <- (inverse_r A).\n  \n  (* 命題 2.1.8 (1) *) (* 簡約法則 *)\n  Theorem reduce_law_l :\n    forall a b c : G, a ** b = a ** c -> b = c.\n  Proof.\n    intros.\n    insert_inv_l b a.\n    insert_inv_l c a.\n    rewrite <- associative_law.\n    rewrite <- associative_law.\n    eapply (left_law _ _ (Inv a)).\n    apply H.\n  Qed.\n  \n  Theorem reduce_law_r :\n    forall b c a : G, b ** a = c ** a -> b = c.\n  Proof.\n    intros.\n    insert_inv_r b a.\n    insert_inv_r c a.\n    rewrite associative_law.\n    rewrite associative_law.\n    eapply (right_law _ _ (Inv a)).\n    apply H.\n  Qed.\n  \n  (*\n     b = Inv a ** c\n     --------------\n     a ** b = c\n     *)\n  Ltac r_to_l A :=\n    eapply (reduce_law_l A _ _);\n      repeat (rewrite associative_law);\n        try (rewrite inverse_r);            (* rewrite (inverse_r a). *)\n          try (rewrite inverse_l);          (* 実行されないかも *)\n            try (rewrite identity_l).       (* rewrite (identity_l c). *)\n  \n  (*\n     a = c ** Inv b\n     --------------\n     a ** b = c\n     *)\n  Ltac l_to_r B :=\n    eapply (reduce_law_r _ _ B);\n      repeat (rewrite <- associative_law);\n        try (rewrite inverse_l);            (* rewrite (inverse_l b). *)\n          try (rewrite inverse_r);          (* 実行されないかも *)\n            try (rewrite identity_r).       (* rewrite (identity_r c). *)\n\n\n  (* 命題 2.1.8 (2) *)\n  Goal forall a b c,\n    a ** b = c -> b = (Inv a) ** c.\n  Proof.\n    intros.\n    r_to_l a.\n    apply H.\n  Qed.\n  \n  Goal forall a b c,\n    a ** b = c -> a = c ** (Inv b).\n  Proof.\n    intros.\n    l_to_r b.\n    apply H.\n  Qed.\n  \n  (* 例題 2.1.9 *)\n  Goal forall x y z,\n    x ** (Inv y) ** z ** x ** y ** x = E ->\n    z = y ** (Inv x) ** (Inv x) ** (Inv y) ** (Inv x).\n  Proof.\n    intros.\n    r_to_l (Inv y).\n    (*\n       eapply (reduce_law_l (Inv y) _ _).\n       repeat rewrite associative_law.\n       rewrite inverse_l.\n       rewrite identity_l.\n       *)\n    r_to_l x.\n    (*\n       eapply (reduce_law_l x _ _).\n       repeat rewrite associative_law.\n       rewrite inverse_r.\n       rewrite identity_l.\n       *)\n    l_to_r x.\n    (*\n       eapply (reduce_law_r _ _ x).\n       repeat rewrite <- associative_law.\n       rewrite inverse_l.\n       rewrite identity_r.\n       *)\n    l_to_r y.\n    (*\n       eapply (reduce_law_r _ _ y).\n       repeat rewrite <- associative_law.\n       rewrite inverse_l.\n       rewrite identity_r.\n       *)\n    l_to_r x.\n    (*\n       eapply (reduce_law_r _ _ x).\n       repeat rewrite <- associative_law.\n       rewrite inverse_l.\n       *)    \n    repeat rewrite associative_law.\n    apply H.\n  Qed.\n  \n  (* 命題 2.1.10 (1) *) (* 単位元の唯一性 *)\n  Theorem identity_uniqueness :\n    forall x E',\n      E' ** x = x -> E' = E.\n  Proof.\n    intros.\n    eapply (reduce_law_r _ _ x).\n    rewrite (identity_l x).\n    apply H.\n  Qed.\n  \n  (* 命題 2.1.10 (2) *) (* 逆元の一意性 *)\n  Goal forall b b',\n    b ** b' = E -> b' = Inv b.\n  Proof.\n    intros.\n    eapply (reduce_law_l b _ _).\n    rewrite inverse_r.\n    apply H.\n  Qed.\n  \n  (* 命題 2.1.10 (3) *)\n  Theorem inv_inv:\n    forall a b,\n      (Inv b) ** (Inv a) = Inv (a ** b).\n  Proof.\n    assert (forall a b, (Inv b) ** (Inv a) ** a ** b = E).\n    intros.\n    r_to_l b.\n    (*\n       apply (reduce_law_l b _ _).\n       repeat rewrite associative_law.\n       rewrite inverse_r.\n       rewrite identity_l.\n       *)\n    rewrite identity_r.\n    r_to_l a.\n    (*\n       apply (reduce_law_l a _ _).\n       repeat rewrite associative_law.\n       rewrite inverse_r.\n       rewrite identity_l.\n       *)\n    reflexivity.\n    (* END assert *)\n    \n    intros.\n    apply (reduce_law_r _ _ (a ** b)).\n    rewrite (inverse_l (a ** b)).\n    repeat rewrite associative_law.\n    eapply H.\n  Qed.\n  \n  (* 命題 2.1.10 (4) *)\n  Axiom inverse_inverse :\n    forall x, Inv (Inv x) = x.\nEnd Group.\n\n\n(* 群 G *)\nVariable G : Set.\n(* 演算子 *)\nVariable AppG : G -> G -> G.\nInfix \"**\" := AppG (at level 61, left associativity).\n(* 定義 2.1.1 (1) *) (* 単位元 *)\nVariable EG : G.\n(* 定義 2.1.1 (2) *) (* 逆元 *)\nVariable InvG : G -> G.\n(* 公理や定理 *)\nLet identity_g_r := identity_r G AppG EG.\nLet identity_g_l := identity_l G AppG EG.\nCheck identity_g_l.\nLet inverse_g_r := inverse_r G AppG EG InvG.\nLet inverse_g_l := inverse_l G AppG EG InvG.\nCheck inverse_g_l.\nLet associative_g_law := associative_law G AppG.\nLet right_law_g := right_law G AppG.\nLet left_law_g := left_law G AppG.\nLet reduce_law_g_r :=  reduce_law_r G AppG EG InvG.\nLet reduce_law_g_l :=  reduce_law_l G AppG EG InvG.\nCheck reduce_law_g_l.\nLet inv_inv_g := inv_inv G AppG EG InvG.\n\n\n(* 群 H *)\nVariable H : Set.\nVariable AppH : H -> H -> H.\nInfix \"++\" := AppH (at level 61, left associativity).\nVariable EH : H.\nVariable InvH : H -> H.\nLet identity_h_r := identity_r H AppH EH.\nLet identity_h_l := identity_l H AppH EH.\nCheck identity_h_l.\nLet inverse_h_r := inverse_r H AppH EH InvH.\nLet inverse_h_l := inverse_l H AppH EH InvH.\nCheck inverse_h_l.\nLet associative_h_law := associative_law H AppH.\nLet right_law_h := right_law H AppH.\nLet left_law_h := left_law H AppH.\nLet reduce_law_h_r :=  reduce_law_r H AppH EH InvH.\nLet reduce_law_h_l :=  reduce_law_l H AppH EH InvH.\n\n\n(* phi : G -> H が群の準同型写像 *)\nVariable phi : G -> H.\n\n\nAxiom homomorphism_phi :\n  forall a b : G, phi (a ** b) = (phi a) ++ (phi b).\n\n\n(* 命題 2.5.2 *)\n(* 全単射写像 phi : G -> H が群の準同型写像なら、GとHは同型である *)\n\n\n(* phi が全単射なら、phi は単射である。 *)\nAxiom injective_phi :\n  forall a b, (phi a) = (phi b) -> a = b.\n\n\n(* phi が全単射なら、逆写像 psi が存在する *)\nVariable psi : H -> G.\nAxiom inverse_phi :\n  forall x, phi (psi x) = x.\n\n\n(* 逆写像 psi は準同型写像である。 *)\nLemma t_2_5_2 :\n  forall x y,\n    (psi x) ** (psi y) = psi (x ++ y).\nProof.\n  intros.\n  apply injective_phi.\n  rewrite inverse_phi.\n  rewrite homomorphism_phi.\n  rewrite inverse_phi.\n  rewrite inverse_phi.\n  reflexivity.\nQed.\n(*\n   題意から、phi : G -> H は準同型写像である。\n   Lemma t_2_5_2から、phiの逆写像 psi : H -> G は準同型写像である。\n   写像とその逆写像の両方が準同型写像であるので、G と H は同型である。\n   *)\n\n\nTheorem homomorphism_phi_identity :\n  phi EG = EH.\nProof.\n  eapply (reduce_law_h_r _ _ (phi EG)).\n  rewrite identity_h_l.\n  rewrite <- homomorphism_phi.\n  rewrite identity_g_l.\n  reflexivity.\nQed.\n\n\n(* 命題 2.5.3 (2) *)\nTheorem homomorphism_phi_inverse :\n  forall x, phi (InvG x) = InvH (phi x).\nProof.\n  intros.\n  eapply (reduce_law_h_r _ _ (phi x)).\n  rewrite inverse_h_l.\n  rewrite <- homomorphism_phi.\n  rewrite inverse_g_l.\n  apply homomorphism_phi_identity.\nQed.\n\n\n(* Img(phi) = {(phi x) | x : G} は、Hの(部分)群である *)\nGoal forall x y, exists z,\n  (phi x) ++ (phi y) = phi z.\nProof.\n  intros.\n  exists (x ** y).\n  rewrite <- homomorphism_phi.\n  reflexivity.\nQed.\n\n\nGoal forall x, exists y,\n  InvH (phi x) = phi y.\nProof.\n  intros.\n  exists (InvG x).\n  rewrite <- homomorphism_phi_inverse.\n  reflexivity.\nQed.\n\n\n(* 恒等写像は、準同型写像である *)\nVariable IdG : G -> G.\nAxiom Identity_function : forall a, a = IdG a.\n\n\nGoal forall x y : G, (IdG x) ** (IdG y) = IdG (x ** y).\nProof.\n  intros.\n  repeat (rewrite <- Identity_function).\n  reflexivity.\nQed.\n\n\n(* 群GからGへの同型写像をGの自己同型写像とよぶ。その集合をAut(G)で表す。\n   恒等写像は同型写像であるから、自己同型写像である。IdG∈Aut(G)。\n   同型写像と同型写像の合成の演算を @@ とおく。\n   自己同型写像は @@ に対して閉じている（同型でなくても閉じているから）。\n   自己同型写像の集合 Aut(G) は、IdG を単位元とした群である。\n*)\n\n\n(* 命題 2.5.17 *)\n(* Tht : G -> Aut(G) を下記のとおり定義する。\n   （g∈Gに対して、(Tht g)∈Aut(G)である）\n   任意のgが固定されたとき、(Tht g)は、群Gの自己同型写像であることを示す。\n   *)\n\n\nVariable Tht : G -> (G -> G).               (* G -> Aut(G) *)\nAxiom define_tht :\n  forall g h : G, Tht g h = g ** h ** (InvG g).\n\n\nLemma p2_5_17 : forall g h1 h2 : G,\n  Tht g (h1 ** h2) = (Tht g h1) ** (Tht g h2).\nProof.\n  intros.\n  repeat (rewrite define_tht).\n  repeat (rewrite associative_g_law).\n  rewrite <- associative_g_law at 1.\n  (* rewriteはできるところはすべてrewriteするので、最初のところだけに限定する。 *)\n  rewrite <- (identity_g_l (h2 ** InvG g)).  \n  rewrite <- (inverse_g_l g).\n  repeat (rewrite associative_g_law).\n  reflexivity.\nQed.\n\n\n(* 命題 2.5.22 *)\n(* Tht : G -> Aut(G) を上記のとおり定義する。\n   （g∈Gに対して、(Tht g)∈Aut(G)である）\n   Thtは、群Gから群Aut(G)への準同型写像であることを示す。\n   ただし、群Aut(G)の積は、写像の合成（以下のDot）で定義する。\n*)\n\n\nVariable Dot : (G -> G) -> (G -> G) -> (G -> G).\nInfix \"@@\" := Dot (at level 51, right associativity).\nAxiom define_dot :\n  forall f g : G -> G,\n    forall x : G, (f @@ g) x = f (g x).\n\n\nLemma p2_5_22 : forall g1 g2 h : G,\n  ((Tht g1) @@ (Tht g2)) h = Tht (g1 ** g2) h.\nProof.\n  intros.\n  rewrite define_dot.\n  repeat (rewrite define_tht).\n  rewrite <- inv_inv_g.\n  repeat (rewrite associative_g_law).\n  reflexivity.\nQed.\n\n\n(* END *)", "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/algebra/yukie_group_theory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.6782018458310757}}
{"text": "Section Ejercicio3.\nVariable A B C: Set.\n\nEnd Ejercicio3.\n\n\nSection Ejercicio4.\nVariable A: Set.\n\nDefinition id := ....\n\nTheorem e4 : forall x:A, ...\nProof.\n\nQed.\n\nEnd Ejercicio4.\n\n\nSection Ejercicio5.\n\n(* 5.1 *)\nDefinition opI (A : Set) (x : A) := x.\n\nDefinition opK ...\n\nDefinition opS ...\n\n(* 5.2 *)\n(* Para formalizar el siguiente lema, determine los tipos ?1 ... ?8 adecuados *)\nLemma e52 : forall A B : Set, opS ?1 ?2 ?3 (opK ?4 ?5) (opK ?6 ?7) = opI ?8.\nProof.\n\nQed.\n\nEnd Ejercicio5.\n\n\nSection Ejercicio6.\nDefinition N := forall X : Set, X -> (X -> X) -> X.\nDefinition Zero (X : Set) (o : X) (f : X -> X) := o.\nDefinition Uno  (X : Set) (o : X) (f : X -> X) := f (Zero X o f).\n\n(* 6.1 *)\nDefinition Dos  ...\n\n(* 6.2 *)\nDefinition Succ ...\n\nLemma succUno : Succ Uno = Dos.\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 suma1: (Uno ++ Zero) = Uno.\nProof.\n\nQed.\n\nLemma suma2: (Uno ++ Uno) = Dos.\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 : (Uno ** Zero) = Zero.\nProof.\n\nQed.\n\nLemma prod2: (Uno ** Dos) = Dos.\nProof.\n\nQed.\n\nEnd Ejercicio6.\n\n\nSection Ejercicio7.\n(* 7.1 *)\nDefinition Bool := ...\nDefinition t    := ...\nDefinition f    := ...\n\n(* 7.2 *)\nDefinition If ...\n\n(* 7.3 *)\nDefinition Not ...\n\nLemma CorrecNot : (Not t) = f /\\ (Not f) = t.\nProof.\n\nQed.\n\n(* 7.4 *)\nDefinition And ...\n\nDefinition And' ...\n\n(* 7.5 *)\nInfix \"&\" := ...\n\nLemma CorrecAnd : (t & t) = t /\\ (f & t) = f /\\ (t & f) = f.\nProof.\n\nQed.\n\nEnd Ejercicio7.\n\n\n\n(* Ejercicio8 *)\n\nSection ArrayNat.\nParameter ArrayNat : forall n:nat, Set.\nParameter empty    : ArrayNat 0.\nParameter add      : forall n:nat, nat -> ArrayNat n -> ArrayNat (n + 1).\n\n(* 8.1 *)\n\n(* 8.2 *)\n\n(* 8.3 *)\nParameter Concat : ...\n\n(* 8.4 *)\nParameter Zip : ...\n\n(* 8.5 *)\n\n(* 8.6 *)\nParameter Array' : ...\nParameter empty' : ...\nParameter add'   : ...\nParameter Zip'   : ...\n\n(* 8.7 *)\nParameter ArrayBool : ...\n\nEnd ArrayNat.\n\n\nSection Ejercicio9.\n...\nEnd Ejercicio9.\n\n\nSection Ejercicio10.\n\nParameter Array : Set -> nat -> Set.\nParameter emptyA : forall X : Set, Array X 0.\nParameter addA : forall (X : Set) (n : nat), X -> Array X n -> Array X (S n).\n\nParameter Matrix : Set -> nat -> Set.\nParameter emptyM : ...\nParameter addM : ...\n\nDefinition M1 := ... (* matriz de una columna *)\nDefinition M2 := ... (* matriz de dos columnas *) \nDefinition M3 := ... (* matriz de tres columnas *)\n\nCheck M3.\n\nEnd Ejercicio10.\n\n\nSection Ejercicio11.\n...\nEnd Ejercicio11.\n\n\nSection Ejercicio12.\n...\nEnd Ejercicio12.\n\n\nSection Ejercicio13.\nVariable A B C: Set.\n\nLemma e13_1 : (A -> B -> C) -> B -> A -> C.\nProof.\n\nQed.\n\nLemma e13_2 : (A -> B) -> (B -> C) -> A -> C.\nProof.\n\nQed.\n\nLemma e13_3 : (A -> B -> C) -> (B -> A) -> B -> C.\nProof.\n\nQed.\n\nEnd Ejercicio13.\n\n\n\nSection Ejercicio14.\nVariable A B C: Prop.\n\nLemma Ej314_1 : (A -> B -> C) -> A -> (A -> C) -> B -> C.\nProof.\n  intros f a g b.\n        ...\nQed.\n\nLemma Ej314_2 : A -> ~ ~ A.\nProof.\n  unfold not.\n  intros.\n     ...\nQed.\n\nLemma Ej314_3 : (A -> B -> C) -> A -> B -> C.\nProof.\n     ...\nQed.\n\nLemma Ej314_4 : (A -> B) -> ~ (A /\\ ~ B).\nProof.\n  unfold not.\n  intros.\n  elim H0; intros.\n     ...\nQed.\n\nEnd Ejercicio14.\n\n\n\nSection Ejercicio15.\n\nVariable U : Set.\nVariable e : U.\nVariable A B : U -> Prop.\nVariable P : Prop.\nVariable R : U -> U -> Prop.\n\nLemma Ej315_1 : (forall x : U, A x -> B x) -> (forall x : U, A x) ->\nforall x : U, B x.\nProof.\n  intros.\n   ...\nQed.\n\nLemma Ej315_2 : forall x : U, A x -> ~ (forall x : U, ~ A x).\nProof.\n  unfold not.\n  intros.\n  ...\nQed.\n\nLemma Ej315_3 : (forall x : U, P -> A x) -> P -> forall x : U, A x.\nProof.\n    ...\nQed.\n\nLemma Ej315_4 : (forall x y : U, R x y) -> forall x : U, R x x.\nProof.\n     ...\nQed.\n\nLemma Ej315_5 : (forall x y: U, R x y -> R y x) ->\n                 forall z : U, R e z -> R z e.\nProof.\n     ...\nQed.\n\nEnd Ejercicio15.\n", "meta": {"author": "elopez", "repo": "CFPTT", "sha": "5df066218d0acba5a009db498e6125d69865096a", "save_path": "github-repos/coq/elopez-CFPTT", "path": "github-repos/coq/elopez-CFPTT/CFPTT-5df066218d0acba5a009db498e6125d69865096a/práctica 3/plantilla p3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.6782018414013196}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq path fintype.\n\n(******************************************************************************)\n(* This file develops the theory of finite graphs represented by an \"edge\"    *)\n(* relation over a finType T; this mainly amounts to the theory of the        *)\n(* transitive closure of such relations.                                      *)\n(*   For g : T -> seq T, e : rel T and f : T -> T we define:                  *)\n(*         grel g == the adjacency relation y \\in g x of the graph g.         *)\n(*       rgraph e == the graph (x |-> enum (e x)) of the relation e.          *)\n(*    dfs g n v x == the list of points traversed by a depth-first search of  *)\n(*                   the g, at depth n, starting from x, and avoiding v.      *)\n(* dfs_path g v x y <-> there is a path from x to y in g \\ v.                 *)\n(*      connect e == the transitive closure of e (computed by dfs).           *)\n(*  connect_sym e <-> connect e is symmetric, hence an equivalence relation.  *)\n(*       root e x == a representative of connect e x, which is the component  *)\n(*                   of x in the transitive closure of e.                     *)\n(*        roots e == the codomain predicate of root e.                        *)\n(*     n_comp e a == the number of e-connected components of a, when a is     *)\n(*                   e-closed and connect e is symmetric.                     *)\n(*                   equivalence classes of connect e if connect_sym e holds. *)\n(*     closed e a == the collective predicate a is e-invariant.               *)\n(*    closure e a == the e-closure of a (the image of a under connect e).     *)\n(* rel_adjunction h e e' a <-> in the e-closed domain a, h is the left part   *)\n(*                   of an adjunction from e to another relation e'.          *)\n(*     fconnect f == connect (frel f), i.e., \"connected under f iteration\".   *)\n(*      froot f x == root (frel f) x, the root of the orbit of x under f.     *)\n(*       froots f == roots (frel f) == orbit representatives for f.           *)\n(*      orbit f x == lists the f-orbit of x.                                  *)\n(*   findex f x y == index of y in the f-orbit of x.                          *)\n(*      order f x == size (cardinal) of the f-orbit of x.                     *)\n(*  order_set f n == elements of f-order n.                                   *)\n(*         finv f == the inverse of f, if f is injective.                     *)\n(*                := finv f x := iter (order x).-1 f x.                       *)\n(*      fcard f a == number of orbits of f in a, provided a is f-invariant    *)\n(*                   f is one-to-one.                                         *)\n(*    fclosed f a == the collective predicate a is f-invariant.               *)\n(*   fclosure f a == the closure of a under f iteration.                      *)\n(* fun_adjunction == rel_adjunction (frel f).                                 *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nDefinition grel (T : eqType) (g : T -> seq T) := [rel x y | y \\in g x].\n\n(* Decidable connectivity in finite types.                                  *)\nSection Connect.\n\nVariable T : finType.\n\nSection Dfs.\n\nVariable g : T -> seq T.\nImplicit Type v w a : seq T.\n\nFixpoint dfs n v x :=\n  if x \\in v then v else\n  if n is n'.+1 then foldl (dfs n') (x :: v) (g x) else v.\n\nLemma subset_dfs n v a : v \\subset foldl (dfs n) v a.\nProof.\nelim: n a v => [|n IHn]; first by elim=> //= *; rewrite if_same.\nelim=> //= x a IHa v; apply: subset_trans {IHa}(IHa _); case: ifP => // _.\nby apply: subset_trans (IHn _ _); apply/subsetP=> y; exact: predU1r.\nQed.\n\nInductive dfs_path v x y : Prop :=\n  DfsPath p of path (grel g) x p & y = last x p & [disjoint x :: p & v].\n\nLemma dfs_pathP n x y v :\n  #|T| <= #|v| + n -> y \\notin v -> reflect (dfs_path v x y) (y \\in dfs n v x).\nProof.\nhave dfs_id w z: z \\notin w -> dfs_path w z z.\n  by exists [::]; rewrite ?disjoint_has //= orbF.\nelim: n => [|n IHn] /= in x y v * => le_v'_n not_vy.\n  rewrite addn0 (geq_leqif (subset_leqif_card (subset_predT _))) in le_v'_n.\n  by rewrite predT_subset in not_vy.\nhave [v_x | not_vx] := ifPn.\n  by rewrite (negPf not_vy); right=> [] [p _ _]; rewrite disjoint_has /= v_x.\nset v1 := x :: v; set a := g x; have sub_dfs := subsetP (subset_dfs n _ _).\nhave [-> | neq_yx] := eqVneq y x.\n  by rewrite sub_dfs ?mem_head //; left; exact: dfs_id.\napply: (@equivP (exists2 x1, x1 \\in a & dfs_path v1 x1 y)); last first.\n  split=> {IHn} [[x1 a_x1 [p g_p p_y]] | [p /shortenP[]]].\n    rewrite disjoint_has has_sym /= has_sym /= => /norP[_ not_pv].\n    by exists (x1 :: p); rewrite /= ?a_x1 // disjoint_has negb_or not_vx.\n  case=> [_ _ _ eq_yx | x1 p1 /=]; first by case/eqP: neq_yx.\n  case/andP=> a_x1 g_p1 /andP[not_p1x _] /subsetP p_p1 p1y not_pv.\n  exists x1 => //; exists p1 => //.\n  rewrite disjoint_sym disjoint_cons not_p1x disjoint_sym.\n  by move: not_pv; rewrite disjoint_cons => /andP[_ /disjoint_trans->].\nhave{neq_yx not_vy}: y \\notin v1 by exact/norP.\nhave{le_v'_n not_vx}: #|T| <= #|v1| + n by rewrite cardU1 not_vx addSnnS.\nelim: {x v}a v1 => [|x a IHa] v /= le_v'_n not_vy.\n  by rewrite (negPf not_vy); right=> [] [].\nset v2 := dfs n v x; have v2v: v \\subset v2 := subset_dfs n v [:: x].\nhave [v2y | not_v2y] := boolP (y \\in v2).\n  by rewrite sub_dfs //; left; exists x; [exact: mem_head | exact: IHn].\napply: {IHa}(equivP (IHa _ _ not_v2y)).\n  by rewrite (leq_trans le_v'_n) // leq_add2r subset_leq_card.\nsplit=> [] [x1 a_x1 [p g_p p_y not_pv]].\n  exists x1; [exact: predU1r | exists p => //].\n  by rewrite disjoint_sym (disjoint_trans v2v) // disjoint_sym.\nsuffices not_p1v2: [disjoint x1 :: p & v2].\n  case/predU1P: a_x1 => [def_x1 | ]; last by exists x1; last exists p.\n  case/pred0Pn: not_p1v2; exists x; rewrite /= def_x1 mem_head /=.\n  suffices not_vx: x \\notin v by apply/IHn; last exact: dfs_id.\n  by move: not_pv; rewrite disjoint_cons def_x1 => /andP[].\napply: contraR not_v2y => /pred0Pn[x2 /andP[/= p_x2 v2x2]].\ncase/splitPl: p_x2 p_y g_p not_pv => p0 p2 p0x2.\nrewrite last_cat cat_path -cat_cons lastI cat_rcons {}p0x2 => p2y /andP[_ g_p2].\nrewrite disjoint_cat disjoint_cons => /and3P[{p0}_ not_vx2 not_p2v].\nhave{not_vx2 v2x2} [p1 g_p1 p1_x2 not_p1v] := IHn _ _ v le_v'_n not_vx2 v2x2.\napply/IHn=> //; exists (p1 ++ p2); rewrite ?cat_path ?last_cat -?p1_x2 ?g_p1 //.\nby rewrite -cat_cons disjoint_cat not_p1v.\nQed.\n\nLemma dfsP x y :\n  reflect (exists2 p, path (grel g) x p & y = last x p) (y \\in dfs #|T| [::] x).\nProof.\napply: (iffP (dfs_pathP _ _ _)); rewrite ?card0 // => [] [p]; exists p => //.\nby rewrite disjoint_sym disjoint0.\nQed.\n\nEnd Dfs.\n\nVariable e : rel T.\n\nDefinition rgraph x := enum (e x).\n\nLemma rgraphK : grel rgraph =2 e.\nProof. by move=> x y; rewrite /= mem_enum. Qed.\n\nDefinition connect : rel T := fun x y => y \\in dfs rgraph #|T| [::] x.\nCanonical connect_app_pred x := ApplicativePred (connect x).\n\nLemma connectP x y :\n  reflect (exists2 p, path e x p & y = last x p) (connect x y).\nProof.\napply: (equivP (dfsP _ x y)).\nby split=> [] [p e_p ->]; exists p => //; rewrite (eq_path rgraphK) in e_p *.\nQed.\n\nLemma connect_trans : transitive connect.\nProof.\nmove=> x y z /connectP[p e_p ->] /connectP[q e_q ->]; apply/connectP.\nby exists (p ++ q); rewrite ?cat_path ?e_p ?last_cat.\nQed.\n\nLemma connect0 x : connect x x.\nProof. by apply/connectP; exists [::]. Qed.\n\nLemma eq_connect0 x y : x = y -> connect x y.\nProof. move->; exact: connect0. Qed.\n\nLemma connect1 x y : e x y -> connect x y.\nProof. by move=> e_xy; apply/connectP; exists [:: y]; rewrite /= ?e_xy. Qed.\n\nLemma path_connect x p : path e x p -> subpred (mem (x :: p)) (connect x).\nProof.\nmove=> e_p y p_y; case/splitPl: p / p_y e_p => p q <-.\nby rewrite cat_path => /andP[e_p _]; apply/connectP; exists p.\nQed.\n\nDefinition root x := odflt x (pick (connect x)).\n\nDefinition roots : pred T := fun x => root x == x.\nCanonical roots_pred := ApplicativePred roots.\n\nDefinition n_comp_mem (m_a : mem_pred T) := #|predI roots m_a|.\n\nLemma connect_root x : connect x (root x).\nProof. by rewrite /root; case: pickP; rewrite ?connect0. Qed.\n\nDefinition connect_sym := symmetric connect.\n\nHypothesis sym_e : connect_sym.\n\nLemma same_connect : left_transitive connect.\nProof. exact: sym_left_transitive connect_trans. Qed.\n\nLemma same_connect_r : right_transitive connect.\nProof. exact: sym_right_transitive connect_trans. Qed.\n\nLemma same_connect1 x y : e x y -> connect x =1 connect y.\nProof. by move/connect1; exact: same_connect. Qed.\n\nLemma same_connect1r x y : e x y -> connect^~ x =1 connect^~ y.\nProof. by move/connect1; exact: same_connect_r. Qed.\n\nLemma rootP x y : reflect (root x = root y) (connect x y).\nProof.\napply: (iffP idP) => e_xy.\n  by rewrite /root -(eq_pick (same_connect e_xy)); case: pickP e_xy => // ->.\nby apply: (connect_trans (connect_root x)); rewrite e_xy sym_e connect_root.\nQed.\n\nLemma root_root x : root (root x) = root x.\nProof. exact/esym/rootP/connect_root. Qed.\n\nLemma roots_root x : roots (root x).\nProof. exact/eqP/root_root. Qed.\n\nLemma root_connect x y : (root x == root y) = connect x y.\nProof. exact: sameP eqP (rootP x y). Qed.\n\nDefinition closed_mem m_a := forall x y, e x y -> in_mem x m_a = in_mem y m_a.\n\nDefinition closure_mem m_a : pred T :=\n  fun x => ~~ disjoint (mem (connect x)) m_a.\n\nEnd Connect.\n\nHint Resolve connect0.\n\nNotation n_comp e a := (n_comp_mem e (mem a)).\nNotation closed e a := (closed_mem e (mem a)).\nNotation closure e a := (closure_mem e (mem a)).\n\nPrenex Implicits connect root roots.\n\nImplicit Arguments dfsP [T g x y].\nImplicit Arguments connectP [T e x y].\nImplicit Arguments rootP [T e x y].\n\nNotation fconnect f := (connect (coerced_frel f)).\nNotation froot f := (root (coerced_frel f)).\nNotation froots f := (roots (coerced_frel f)).\nNotation fcard_mem f := (n_comp_mem (coerced_frel f)).\nNotation fcard f a := (fcard_mem f (mem a)).\nNotation fclosed f a := (closed (coerced_frel f) a).\nNotation fclosure f a := (closure (coerced_frel f) a).\n\nSection EqConnect.\n\nVariable T : finType.\nImplicit Types (e : rel T) (a : pred T).\n\nLemma connect_sub e e' :\n  subrel e (connect e') -> subrel (connect e) (connect e').\nProof.\nmove=> e'e x _ /connectP[p e_p ->]; elim: p x e_p => //= y p IHp x /andP[exy].\nby move/IHp; apply: connect_trans; exact: e'e.\nQed.\n\nLemma relU_sym e e' :\n  connect_sym e -> connect_sym e' -> connect_sym (relU e e').\nProof.\nmove=> sym_e sym_e'; apply: symmetric_from_pre => x _ /connectP[p e_p ->].\nelim: p x e_p => //= y p IHp x /andP[e_xy /IHp{IHp}/connect_trans]; apply.\ncase/orP: e_xy => /connect1; rewrite (sym_e, sym_e');\n  by apply: connect_sub y x => x y e_xy; rewrite connect1 //= e_xy ?orbT.\nQed.\n\nLemma eq_connect e e' : e =2 e' -> connect e =2 connect e'.\nProof.\nmove=> eq_e x y; apply/connectP/connectP=> [] [p e_p ->];\n  by exists p; rewrite // (eq_path eq_e) in e_p *.\nQed.\n\nLemma eq_n_comp e e' : connect e =2 connect e' -> n_comp_mem e =1 n_comp_mem e'.\nProof.\nmove=> eq_e [a]; apply: eq_card => x /=.\nby rewrite !inE /= /roots /root /= (eq_pick (eq_e x)).\nQed.\n\nLemma eq_n_comp_r {e} a a' : a =i a' -> n_comp e a = n_comp e a'.\nProof. by move=> eq_a; apply: eq_card => x; rewrite inE /= eq_a. Qed.\n\nLemma n_compC a e : n_comp e T = n_comp e a + n_comp e [predC a].\nProof.\nrewrite /n_comp_mem (eq_card (fun _ => andbT _)) -(cardID a); congr (_ + _).\nby apply: eq_card => x; rewrite !inE andbC.\nQed.\n\nLemma eq_root e e' : e =2 e' -> root e =1 root e'.\nProof. by move=> eq_e x; rewrite /root (eq_pick (eq_connect eq_e x)). Qed.\n\nLemma eq_roots e e' : e =2 e' -> roots e =1 roots e'.\nProof. by move=> eq_e x; rewrite /roots (eq_root eq_e). Qed.\n\nEnd EqConnect.\n\nSection Closure.\n\nVariables (T : finType) (e : rel T).\nHypothesis sym_e : connect_sym e.\nImplicit Type a : pred T.\n\nLemma same_connect_rev : connect e =2 connect (fun x y => e y x).\nProof.\nsuff crev e': subrel (connect (fun x : T => e'^~ x)) (fun x => (connect e')^~x).\n  by move=> x y; rewrite sym_e; apply/idP/idP; exact: crev.\nmove=> x y /connectP[p e_p p_y]; apply/connectP.\nexists (rev (belast x p)); first by rewrite p_y rev_path.\nby rewrite -(last_cons x) -rev_rcons p_y -lastI rev_cons last_rcons.\nQed.\n\nLemma intro_closed a : (forall x y, e x y -> x \\in a -> y \\in a) -> closed e a.\nProof.\nmove=> cl_a x y e_xy; apply/idP/idP=> [|a_y]; first exact: cl_a.\nhave{x e_xy} /connectP[p e_p ->]: connect e y x by rewrite sym_e connect1.\nby elim: p y a_y e_p => //= y p IHp x a_x /andP[/cl_a/(_ a_x)]; exact: IHp.\nQed.\n\nLemma closed_connect a :\n  closed e a -> forall x y, connect e x y -> (x \\in a) = (y \\in a).\nProof.\nmove=> cl_a x _ /connectP[p e_p ->].\nby elim: p x e_p => //= y p IHp x /andP[/cl_a->]; exact: IHp.\nQed.\n\nLemma connect_closed x : closed e (connect e x).\nProof. by move=> y z /connect1/same_connect_r; exact. Qed.\n\nLemma predC_closed a : closed e a -> closed e [predC a].\nProof. by move=> cl_a x y /cl_a; rewrite !inE => ->. Qed.\n\nLemma closure_closed a : closed e (closure e a).\nProof.\napply: intro_closed => x y /connect1 e_xy; congr (~~ _).\nby apply: eq_disjoint; exact: same_connect.\nQed.\n\nLemma mem_closure a : {subset a <= closure e a}.\nProof. by move=> x a_x; apply/existsP; exists x; rewrite !inE connect0. Qed.\n\nLemma subset_closure a : a \\subset closure e a.\nProof. by apply/subsetP; exact: mem_closure. Qed.\n\nLemma n_comp_closure2 x y :\n  n_comp e (closure e (pred2 x y)) = (~~ connect e x y).+1.\nProof.\nrewrite -(root_connect sym_e) -card2; apply: eq_card => z.\napply/idP/idP=> [/andP[/eqP {2}<- /pred0Pn[t /andP[/= ezt exyt]]] |].\n  by case/pred2P: exyt => <-; rewrite (rootP sym_e ezt) !inE eqxx ?orbT.\nby case/pred2P=> ->; rewrite !inE roots_root //; apply/existsP;\n  [exists x | exists y]; rewrite !inE eqxx ?orbT sym_e connect_root.\nQed.\n\nLemma n_comp_connect x : n_comp e (connect e x) = 1.\nProof.\nrewrite -(card1 (root e x)); apply: eq_card => y.\napply/andP/eqP => [[/eqP r_y /rootP-> //] | ->] /=.\nby rewrite inE connect_root roots_root.\nQed.\n\nEnd Closure.\n\nSection Orbit.\n\nVariables (T : finType) (f : T -> T).\n\nDefinition order x := #|fconnect f x|.\n\nDefinition orbit x := traject f x (order x).\n\nDefinition findex x y := index y (orbit x).\n\nDefinition finv x := iter (order x).-1 f x.\n\nLemma fconnect_iter n x : fconnect f x (iter n f x).\nProof.\napply/connectP.\nby exists (traject f (f x) n); [ exact: fpath_traject | rewrite last_traject ].\nQed.\n\nLemma fconnect1 x : fconnect f x (f x).\nProof. exact: (fconnect_iter 1). Qed.\n\nLemma fconnect_finv x : fconnect f x (finv x).\nProof. exact: fconnect_iter. Qed.\n\nLemma orderSpred x : (order x).-1.+1 = order x.\nProof. by rewrite /order (cardD1 x) [_ x _]connect0. Qed.\n\nLemma size_orbit x : size (orbit x) = order x.\nProof. exact: size_traject. Qed.\n\nLemma looping_order x : looping f x (order x).\nProof.\napply: contraFT (ltnn (order x)); rewrite -looping_uniq => /card_uniqP.\nrewrite size_traject => <-; apply: subset_leq_card.\nby apply/subsetP=> _ /trajectP[i _ ->]; exact: fconnect_iter.\nQed.\n\nLemma fconnect_orbit x y : fconnect f x y = (y \\in orbit x).\nProof.\napply/idP/idP=> [/connectP[_ /fpathP[m ->] ->] | /trajectP[i _ ->]].\n  by rewrite last_traject; exact/loopingP/looping_order.\nexact: fconnect_iter.\nQed.\n\nLemma orbit_uniq x : uniq (orbit x).\nProof.\nrewrite /orbit -orderSpred looping_uniq; set n := (order x).-1.\napply: contraFN (ltnn n) => /trajectP[i lt_i_n eq_fnx_fix].\nrewrite {1}/n orderSpred /order -(size_traject f x n).\napply: (leq_trans (subset_leq_card _) (card_size _)); apply/subsetP=> z.\nrewrite inE fconnect_orbit => /trajectP[j le_jn ->{z}].\nrewrite -orderSpred -/n ltnS leq_eqVlt in le_jn.\nby apply/trajectP; case/predU1P: le_jn => [->|]; [exists i | exists j].\nQed.\n\nLemma findex_max x y : fconnect f x y -> findex x y < order x.\nProof. by rewrite [_ y]fconnect_orbit -index_mem size_orbit. Qed.\n\nLemma findex_iter x i : i < order x -> findex x (iter i f x) = i.\nProof.\nmove=> lt_ix; rewrite -(nth_traject f lt_ix) /findex index_uniq ?orbit_uniq //.\nby rewrite size_orbit.\nQed.\n\nLemma iter_findex x y : fconnect f x y -> iter (findex x y) f x = y.\nProof.\nrewrite [_ y]fconnect_orbit => fxy; pose i := index y (orbit x).\nhave lt_ix: i < order x by rewrite -size_orbit index_mem.\nby rewrite -(nth_traject f lt_ix) nth_index.\nQed.\n\nLemma findex0 x : findex x x = 0.\nProof. by rewrite /findex /orbit -orderSpred /= eqxx. Qed.\n\nLemma fconnect_invariant (T' : eqType) (k : T -> T') :\n  invariant f k =1 xpredT -> forall x y, fconnect f x y -> k x = k y.\nProof.\nmove=> eq_k_f x y /iter_findex <-; elim: {y}(findex x y) => //= n ->.\nby rewrite (eqP (eq_k_f _)).\nQed.\n\nSection Loop.\n\nVariable p : seq T.\nHypotheses (f_p : fcycle f p) (Up : uniq p).\nVariable x : T.\nHypothesis p_x : x \\in p.\n\n(* This lemma does not depend on Up : (uniq p) *)\nLemma fconnect_cycle y : fconnect f x y = (y \\in p).\nProof.\nhave [i q def_p] := rot_to p_x; rewrite -(mem_rot i p) def_p.\nhave{i def_p} /andP[/eqP q_x f_q]: (f (last x q) == x) && fpath f x q.\n  by have:= f_p; rewrite -(rot_cycle i) def_p (cycle_path x).\napply/idP/idP=> [/connectP[_ /fpathP[j ->] ->] | ]; last exact: path_connect.\ncase/fpathP: f_q q_x => n ->; rewrite !last_traject -iterS => def_x.\nby apply: (@loopingP _ f x n.+1); rewrite /looping def_x /= mem_head.\nQed.\n\nLemma order_cycle : order x = size p.\nProof. by rewrite -(card_uniqP Up); exact (eq_card fconnect_cycle). Qed.\n\nLemma orbit_rot_cycle : {i : nat | orbit x = rot i p}.\nProof.\nhave [i q def_p] := rot_to p_x; exists i.\nrewrite /orbit order_cycle -(size_rot i) def_p.\nsuffices /fpathP[j ->]: fpath f x q by rewrite /= size_traject.\nby move: f_p; rewrite -(rot_cycle i) def_p (cycle_path x); case/andP.\nQed.\n\nEnd Loop.\n\nHypothesis injf : injective f.\n\nLemma f_finv : cancel finv f.\nProof.\nmove=> x; move: (looping_order x) (orbit_uniq x).\nrewrite /looping /orbit -orderSpred looping_uniq /= /looping; set n := _.-1.\ncase/predU1P=> // /trajectP[i lt_i_n]; rewrite -iterSr => /= /injf ->.\nby case/trajectP; exists i.\nQed.\n\nLemma finv_f : cancel f finv.\nProof. exact (inj_can_sym f_finv injf). Qed.\n\nLemma fin_inj_bij : bijective f.\nProof. exists finv; [ exact finv_f | exact f_finv ]. Qed.\n\nLemma finv_bij : bijective finv.\nProof. exists f; [ exact f_finv | exact finv_f ]. Qed.\n\nLemma finv_inj : injective finv.\nProof. exact (can_inj f_finv). Qed.\n\nLemma fconnect_sym x y : fconnect f x y = fconnect f y x.\nProof.\nsuff{x y} Sf x y: fconnect f x y -> fconnect f y x by apply/idP/idP; auto.\ncase/connectP=> p f_p -> {y}; elim: p x f_p => //= y p IHp x.\nrewrite -{2}(finv_f x) => /andP[/eqP-> /IHp/connect_trans-> //].\nexact: fconnect_finv.\nQed.\nLet symf := fconnect_sym.\n\nLemma iter_order x : iter (order x) f x = x.\nProof. by rewrite -orderSpred iterS; exact (f_finv x). Qed.\n\nLemma iter_finv n x : n <= order x -> iter n finv x = iter (order x - n) f x.\nProof.\nrewrite -{2}[x]iter_order => /subnKC {1}<-; move: (_ - n) => m.\nby rewrite iter_add; elim: n => // n {2}<-; rewrite iterSr /= finv_f.\nQed.\n\nLemma cycle_orbit x : fcycle f (orbit x).\nProof.\nrewrite /orbit -orderSpred (cycle_path x) /= last_traject -/(finv x).\nby rewrite fpath_traject f_finv andbT /=.\nQed.\n\nLemma fpath_finv x p : fpath finv x p = fpath f (last x p) (rev (belast x p)).\nProof.\nelim: p x => //= y p IHp x; rewrite rev_cons rcons_path -{}IHp andbC /=.\nrewrite (canF_eq finv_f) eq_sym; congr (_ && (_ == _)).\nby case: p => //= z p; rewrite rev_cons last_rcons.\nQed.\n\nLemma same_fconnect_finv : fconnect finv =2 fconnect f.\nProof.\nmove=> x y; rewrite (same_connect_rev symf); apply: {x y}eq_connect => x y /=.\nby rewrite (canF_eq finv_f) eq_sym.\nQed.\n\nLemma fcard_finv : fcard_mem finv =1 fcard_mem f.\nProof. exact: eq_n_comp same_fconnect_finv. Qed.\n\nDefinition order_set n : pred T := [pred x | order x == n].\n\nLemma fcard_order_set n (a : pred T) :\n  a \\subset order_set n -> fclosed f a -> fcard f a * n = #|a|.\nProof.\nmove=> a_n cl_a; rewrite /n_comp_mem; set b := [predI froots f & a].\nsymmetry; transitivity #|preim (froot f) b|.\n  apply: eq_card => x; rewrite !inE (roots_root fconnect_sym).\n  by rewrite -(closed_connect cl_a (connect_root _ x)).\nhave{cl_a a_n} (x): b x -> froot f x = x /\\ order x = n.\n  by case/andP=> /eqP-> /(subsetP a_n)/eqnP->.\nelim: {a b}#|b| {1 3 4}b (eqxx #|b|) => [|m IHm] b def_m f_b.\n  by rewrite eq_card0 // => x; exact: (pred0P def_m).\nhave [x b_x | b0] := pickP b; last by rewrite (eq_card0 b0) in def_m.\nhave [r_x ox_n] := f_b x b_x; rewrite (cardD1 x) [x \\in b]b_x eqSS in def_m.\nrewrite mulSn -{1}ox_n -(IHm _ def_m) => [|_ /andP[_ /f_b //]].\nrewrite -(cardID (fconnect f x)); congr (_ + _); apply: eq_card => y.\n  by apply: andb_idl => /= fxy; rewrite !inE -(rootP symf fxy) r_x.\nby congr (~~ _ && _); rewrite /= /in_mem /= symf -(root_connect symf) r_x.\nQed.\n\nLemma fclosed1 (a : pred T) : fclosed f a -> forall x, (x \\in a) = (f x \\in a).\nProof. by move=> cl_a x; exact: cl_a (eqxx _). Qed.\n\nLemma same_fconnect1 x : fconnect f x =1 fconnect f (f x).\nProof. by apply: same_connect1 => /=. Qed.\n\nLemma same_fconnect1_r x y : fconnect f x y = fconnect f x (f y).\nProof. by apply: same_connect1r x => /=. Qed.\n\nEnd Orbit.\n\nPrenex Implicits order orbit findex finv order_set.\n\nSection FconnectId.\n\nVariable T : finType.\n\nLemma fconnect_id (x : T) : fconnect id x =1 xpred1 x.\nProof. by move=> y; rewrite (@fconnect_cycle _ _ [:: x]) //= ?inE ?eqxx. Qed.\n\nLemma order_id (x : T) : order id x = 1.\nProof. by rewrite /order (eq_card (fconnect_id x)) card1. Qed.\n\nLemma orbit_id (x : T) : orbit id x = [:: x].\nProof. by rewrite /orbit order_id. Qed.\n\nLemma froots_id (x : T) : froots id x.\nProof. by rewrite /roots -fconnect_id connect_root. Qed.\n\nLemma froot_id (x : T) : froot id x = x.\nProof. by apply/eqP; exact: froots_id. Qed.\n\nLemma fcard_id (a : pred T) : fcard id a = #|a|.\nProof. by apply: eq_card => x; rewrite inE froots_id. Qed.\n\nEnd FconnectId.\n\nSection FconnectEq.\n\nVariables (T : finType) (f f' : T -> T).\n\nLemma finv_eq_can : cancel f f' -> finv f =1 f'.\nProof.\nmove=> fK; exact: (bij_can_eq (fin_inj_bij (can_inj fK)) (finv_f (can_inj fK))).\nQed.\n\nHypothesis eq_f : f =1 f'.\nLet eq_rf := eq_frel eq_f.\n\nLemma eq_fconnect : fconnect f =2 fconnect f'.\nProof. exact: eq_connect eq_rf. Qed.\n\nLemma eq_fcard : fcard_mem f =1 fcard_mem f'.\nProof. exact: eq_n_comp eq_fconnect. Qed.\n\nLemma eq_finv : finv f =1 finv f'.\nProof.\nby move=> x; rewrite /finv /order (eq_card (eq_fconnect x)) (eq_iter eq_f).\nQed.\n\nLemma eq_froot : froot f =1 froot f'.\nProof. exact: eq_root eq_rf. Qed.\n\nLemma eq_froots : froots f =1 froots f'.\nProof. exact: eq_roots eq_rf. Qed.\n\nEnd FconnectEq.\n\nSection FinvEq.\n\nVariables (T : finType) (f : T -> T).\nHypothesis injf : injective f.\n\nLemma finv_inv : finv (finv f) =1 f.\nProof. exact: (finv_eq_can (f_finv injf)). Qed.\n\nLemma order_finv : order (finv f) =1 order f.\nProof. by move=> x; exact: eq_card (same_fconnect_finv injf x). Qed.\n\nLemma order_set_finv n : order_set (finv f) n =i order_set f n.\nProof. by move=> x; rewrite !inE order_finv. Qed.\n\nEnd FinvEq.\n\nSection RelAdjunction.\n\nVariables (T T' : finType) (h : T' -> T) (e : rel T) (e' : rel T').\nHypotheses (sym_e : connect_sym e) (sym_e' : connect_sym e').\n\nRecord rel_adjunction_mem m_a := RelAdjunction {\n  rel_unit x : in_mem x m_a -> {x' : T' | connect e x (h x')};\n  rel_functor x' y' :\n    in_mem (h x') m_a -> connect e' x' y' = connect e (h x') (h y')\n}.\n\nVariable a : pred T.\nHypothesis cl_a : closed e a.\n\nLocal Notation rel_adjunction := (rel_adjunction_mem (mem a)).\n\nLemma intro_adjunction (h' : forall x, x \\in a -> T') :\n   (forall x a_x,\n      [/\\ connect e x (h (h' x a_x))\n        & forall y a_y, e x y -> connect e' (h' x a_x) (h' y a_y)]) ->\n   (forall x' a_x,\n      [/\\ connect e' x' (h' (h x') a_x)\n        & forall y', e' x' y' -> connect e (h x') (h y')]) ->\n  rel_adjunction.\nProof.\nmove=> Aee' Ae'e; split=> [y a_y | x' z' a_x].\n  by exists (h' y a_y); case/Aee': (a_y).\napply/idP/idP=> [/connectP[p e'p ->{z'}] | /connectP[p e_p p_z']].\n  elim: p x' a_x e'p => //= y' p IHp x' a_x.\n  case: (Ae'e x' a_x) => _ Ae'x /andP[/Ae'x e_xy /IHp e_yz] {Ae'x}.\n  by apply: connect_trans (e_yz _); rewrite // -(closed_connect cl_a e_xy).\ncase: (Ae'e x' a_x) => /connect_trans-> //.\nelim: p {x'}(h x') p_z' a_x e_p => /= [|y p IHp] x p_z' a_x.\n  by rewrite -p_z' in a_x *; case: (Ae'e _ a_x); rewrite sym_e'.\ncase/andP=> e_xy /(IHp _ p_z') e'yz; have a_y: y \\in a by rewrite -(cl_a e_xy).\nby apply: connect_trans (e'yz a_y); case: (Aee' _ a_x) => _ ->.\nQed.\n\nLemma strict_adjunction :\n    injective h -> a \\subset codom h -> rel_base h e e' [predC a] ->\n  rel_adjunction.\nProof.\nmove=> /= injh h_a a_ee'; pose h' x Hx := iinv (subsetP h_a x Hx).\napply: (@intro_adjunction h') => [x a_x | x' a_x].\n  rewrite f_iinv connect0; split=> // y a_y e_xy.\n  by rewrite connect1 // -a_ee' !f_iinv ?negbK.\nrewrite [h' _ _]iinv_f //; split=> // y' e'xy.\nby rewrite connect1 // a_ee' ?negbK.\nQed.\n\nLet ccl_a := closed_connect cl_a.\n\nLemma adjunction_closed : rel_adjunction -> closed e' [preim h of a].\nProof.\ncase=> _ Ae'e; apply: intro_closed => // x' y' /connect1 e'xy a_x.\nby rewrite Ae'e // in e'xy; rewrite !inE -(ccl_a e'xy).\nQed.\n\nLemma adjunction_n_comp :\n  rel_adjunction -> n_comp e a = n_comp e' [preim h of a].\nProof.\ncase=> Aee' Ae'e.\nhave inj_h: {in predI (roots e') [preim h of a] &, injective (root e \\o h)}.\n  move=> x' y' /andP[/eqP r_x' /= a_x'] /andP[/eqP r_y' _] /(rootP sym_e).\n  by rewrite -Ae'e // => /(rootP sym_e'); rewrite r_x' r_y'.\nrewrite /n_comp_mem -(card_in_image inj_h); apply: eq_card => x.\napply/andP/imageP=> [[/eqP rx a_x] | [x' /andP[/eqP r_x' a_x'] ->]]; last first.\n  by rewrite /= -(ccl_a (connect_root _ _)) roots_root.\nhave [y' e_xy]:= Aee' x a_x; pose x' := root e' y'.\nhave ay': h y' \\in a by rewrite -(ccl_a e_xy).\nhave e_yx: connect e (h y') (h x') by rewrite -Ae'e ?connect_root.\nexists x'; first by rewrite inE /= -(ccl_a e_yx) ?roots_root.\nby rewrite /= -(rootP sym_e e_yx) -(rootP sym_e e_xy).\nQed.\n\nEnd RelAdjunction.\n\nNotation rel_adjunction h e e' a := (rel_adjunction_mem h e e' (mem a)).\nNotation \"@ 'rel_adjunction' T T' h e e' a\" :=\n  (@rel_adjunction_mem T T' h e e' (mem a))\n  (at level 10, T, T', h, e, e', a at level 8, only parsing) : type_scope.\nNotation fun_adjunction h f f' a := (rel_adjunction h (frel f) (frel f') a).\nNotation \"@ 'fun_adjunction' T T' h f f' a\" :=\n  (@rel_adjunction T T' h (frel f) (frel f') a)\n  (at level 10, T, T', h, f, f', a at level 8, only parsing) : type_scope.\n\nImplicit Arguments intro_adjunction [T T' h e e' a].\nImplicit Arguments adjunction_n_comp [T T' e e' a].\n\nUnset Implicit Arguments.\n\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/ssreflect/attic/ssreflect1.4_v8.3/theories/fingraph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.6782018409001231}}
{"text": "(**\n「Coq/SSReflect/MathCompによる定理証明」第5章で導入された公理について\n========================\n\n@suharahiromichi\n\n2020/12/26\n *)\n\n(**\n# はじめに\n\n文献 [1.] （以下、テキストと呼びます）の第5章では集合形式化について説明されています。\nそこでは、ふたつの公理が導入されています。\n\n5章の冒頭に記載されているとおり、形式化の方法は一通りではないため、\n別な公理や公理を導入しないで済ますことができないか、考えてたいと思います。\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# 集合の形式化（復習）\n\n型 M の要素である元 x が、型Mの要素全体を母集合とする集合 A に属することを、\nM型を引数とする命題型P （すなわち M -> Prop) の型をもつ命題によってあらわす\n（テキストのことばでいうと「形式化」することにします。\n\nなお、型Mは任意な型とします。あとで制限することになるので、注意しておいてください。\n*)\n\nDefinition mySet (M : Type) := M -> Prop.\nDefinition belong {M : Type} (A : mySet M) (x : M) : Prop := A x.\nNotation \"x ∈ A\" := (belong A x) (at level 11).\n\nDefinition myEmptySet {M : Type} : mySet M := fun (_ : M) => False.\nDefinition myMotherSet {M : Type} : mySet M := fun (_ : M) => True.\n\nDefinition mySub {M : Type} := fun (A B : mySet M) => forall (x : M), x ∈ A -> x ∈ B.\nNotation \"A ⊂ B\" := (mySub A B) (at level 11).\nDefinition eqmySet {M : Type} (A B : mySet M) := (A ⊂ B) /\\ (B ⊂ A).\n\nDefinition myComplement {M : Type} (A : mySet M) : mySet M := fun (x : M) => ~(A x).\nNotation \"A ^c\" := (myComplement A) (at level 11).\n\nDefinition myCup {M : Type} (A B : mySet M) : mySet M := fun (x : M) => x ∈ A \\/ x ∈ B.\nNotation \"A ∪ B\" := (myCup A B) (at level 11).\n\n(**\n# CSMの第5章の公理\n\n上記の集合の形式化の定義には問題がふたつあります。（要補足）\n\n- 元xが集合Aに含まれることは言えても、含まれないと言えるとは限らない。\n\nこれは、Coqが採用する直観主義論理の立場から、命題が証明できればそれが真だといえます。\nしかし、命題が証明できないと言い切ることができない（場合がある）ため、\n偽であるとの証明ができない（できるとは限らない）からです。\n\n- 集合AがBに含まれ、かつ、BがAに含まれることから、集合AとBが等しいことを証明できない。\n\nこれは、Coqの等号``=``は、ライプニッツの等式といって、\nその型の(Inductiveな)定義に遡って「同じに見える」場合に限り成立します。\n\n例 ``1 + 1 = 2`` は、``S (S O) = S (S O)``\n\nこの場合、集合AとBが等しいこと ``(A ⊂ B) /\\ (B ⊂ A)``\nは集合の帰納的な定義に基づくものでないため ``A = B`` というこができません。\n\n結果として、テキストの本文にあるように、\n「補集合の補集合がもとの集合になること」の証明ができません。\nテキストではふたつの公理を導入することで解決しています。\nここでは、それぞれを「公理 1」「公理 2」と呼ぶことにします。\n*)\n\n(**\n## (公理 1.) axiom_mySet\n\nテキストの第5章に沿って、\n「元xが集合Aに含まれるか、含まれないかのどちらかである」を公理として導入します。\n *)\n\nAxiom axiom_mySet : forall (M : Type) (A : mySet M), forall (x : M), x ∈ A \\/ ~(x ∈ A).\n\n(**\n## (公理 2.) axiom_ExteqmySet\n\nテキストの第5章に沿って、集合AとBが等しいことを、\n集合AがBに含まれ、かつ、BがAに含まれることとして定義します。\n *)\n\nAxiom axiom_ExteqmySet : forall {M : Type} (A B : mySet M), eqmySet A B -> A = B.\n\n(**\n## 補集合の補集合の証明\n*)\nSection Test1.\n  Variable M : Type.                        (* 注意してください。 *)\n\n  Lemma cc_cancel (A : mySet M) : (A^c)^c = A.\n  Proof.\n    apply: axiom_ExteqmySet.\n    split; rewrite /myComplement => x H;\n      by case: (axiom_mySet A x) => HxA.\n  Qed.\n  \n  Lemma myUnionCompMother (A : mySet M) : A ∪ (A^c) = myMotherSet.\n  Proof.\n    apply: axiom_ExteqmySet.\n    split=> [x | x H] //=.\n    case: (axiom_mySet A x); by [left | right].\n  Qed.\nEnd Test1.\n\n(**\n# (公理 1.)について\n\n## 排中律\n\n(公理 1.)は排中律を使えば証明できます。\n*)\nSection ExMid.\n  Variable M : Type.                        (* 注意してください。 *)\n  \n  Axiom ExMid : forall (P : Prop), P \\/ ~ P. (* 排中律 *)\n  \n  Lemma axiom_mySet'' : forall (A : mySet M),\n      forall (x : M), x ∈ A \\/ ~(x ∈ A).\n  Proof.\n    move=> A x.\n      by apply: ExMid.\n  Qed.\nEnd ExMid.\n\n(*\n## morita_hmさんの公理 ``refl_mySet``\n\nProofCafe において @morita_hm さんから別の公理が提案されました。より単純な、\n\n``reflect (A x) true``\n\nから、(公理 1.)を導くものです。\n*)\n\nSection Morita.\n  Variable M : Type.                        (* 注意してください。 *)\n  \n  Axiom refl_mySet : forall (A : mySet M) (x : M), reflect (A x) true.\n  \n  Lemma axiom_mySet' : forall (A : mySet M),\n      forall (x : M), x ∈ A \\/ ~(x ∈ A).\n  Proof.\n    rewrite /belong => A x.\n      by case: (refl_mySet A x); [left | right].\n    Undo.\n    move: (@refl_mySet A x) => Hr. (* ここで refl_mySet に M A x を与えている。 *)\n    case: Hr.\n    - by left.\n    - by right.\n  Qed.\n  \n(**\nここで実際に証明しているのは、次の命題であることが解ります。\n*)\n  Goal forall (A : mySet M) (x : M),\n      reflect (A x) true -> x ∈ A \\/ ~(x ∈ A).\n  Proof.\n    move=> A x.\n    by case; [left | right].\n  Qed.\nEnd Morita.\n\n(**\n## 別の説明\n\n公理 ``refl_mySet`` は、かたちを変えた排中律であり、\n排中律を経由して(公理 1.)を証明していることになります。これを以下で説明します。\n*)\n\n(**\n文献[2.] p.101 にあるとおり、``reflect P b`` は、\n\n- 命題(Prop型の) P がTrueであると証明できるとき、 bool型の命題が真(true)である。\n\n- 命題(Prop型の) P がFalseであると証明できるとき、bool型の命題が偽(false)である。\n\nと場合分けできることを示します。\n*)\nSection Test2.\n  \n  Lemma A_ref (P : Prop) : P -> reflect P true.\n  Proof.\n    move=> H.\n      by apply: ReflectT.\n  Qed.\n  \n  Lemma notA_ref (P : Prop) : ~ P -> reflect P false.\n  Proof.\n    move=> H.\n      by apply: ReflectF.\n  Qed.\n\n(**\n場合分けができ、また、bool型の命題 true が false であるとは、false のことですから、\n``reflect P true`` から排中律を導くことができます。\n*)\n  Lemma refl_exmid (P : Prop): reflect P true -> P \\/ ~ P.\n  Proof.\n    case=> Hr.\n    - by left.\n    - by right.\n  Qed.\nEnd Test2.\n\n(**\n## 依存和の使用\n\nかたちを変えた排中律としては、依存和があります。\n命題 P が P または ~ P のどちらかに決定可能である、\nということから排中律が求められます。\n*) \n\nSection Depend.\n  \n  Lemma dec_exmid (P : Prop) : {P} + {~ P} -> P \\/ ~ P.\n  Proof.\n    case=> Hd.\n    - by left.\n    - by right.\n  Qed.\n\nEnd Depend.\n\n(**\n## finType の場合\n\nテキストの 5.5節にあるように、\n母集合にあたる型 M を任意の型から、有限型 (finType) に制限することでも、\n(公理 1.)を不要にすることもできます。\n *)\n\nSection FinType.\n  Variable M : finType.             (* これまでは ``M : Type`` だった。 *)\n  \n(**\nなぜなら、有限型（母集合が有限）ならば、元が集合に含まれるかどうかを決定する命題を\n定義することができるからです。\n\nこのような命題はbool型の値をとるようにすると扱いやすいので、pA であらわします。\nそして、bool述語 pA が x で成り立つときことを\nMathCompの演算子 \\in を使って ``x \\in pA`` とあらわします。\n\n- pA は ``pred M`` 型となっていますが、これは ``M -> bool`` のことです（深い意味は無い）。\n\n- ``x \\in pA`` を ``pA x`` に置き換えても（ここでは）同じです。\nただし、単純な構文糖衣ではないので、つねに同じであるわけではありません。\n以下の説明も参照してください。\n\nhttps://github.com/suharahiromichi/coq/blob/master/csm/csm_4_1_ssrbool.v\n*)\n\n(**\n``pA : pred M`` が ``P : mySet M`` で形式化された集合の定で使えるように、\n変換する関数 p2S を定義します。\nなお、テキストで定義されている構文糖衣 ``\\{ x 'in' pA \\}`` は使わないことにしました。\nすなわち `` \\{ x in M \\}`` は ``p2S M`` のことで x に意味はありません。\n*)  \n  Definition p2S (pA : pred M) : mySet M :=\n    fun (x : M) => if x \\in pA then True else False.\n\n  Lemma Mother_predT : myMotherSet = p2S M.\n  Proof. by []. Qed.\n\n  Lemma myFinBelongP (x : M) (pA : pred M) : reflect (x ∈ p2S pA) (x \\in pA).\n  Proof.\n    rewrite /belong /p2S.\n    apply/(iffP idP) => H1.\n    - by rewrite H1.\n    - by case H : (x \\in pA); last rewrite H in H1.\n  Qed.  \n\n(**\n「元xが集合Aに含まれるか、含まれないかのどちらかである」ことを(公理 1.)を使わずに、\n定理として導くことができます。\n*)\n\n  Lemma fin_mySet (pA : pred M) (x : M) : x \\in pA \\/ ~(x \\in pA).\n  Proof.\n    case: (myFinBelongP x pA); by [left | right].\n  Qed.\n\n(**\n実際の集合の証明では、``M : Type, P : mySet M``\nを ``M : finType, pA : pred M`` に変更する必要があります。\n*)\n  Lemma Mother_Sub (pA : pred M) :\n    myMotherSet ⊂ p2S pA -> forall x, x ∈ p2S pA.\n  Proof.\n    rewrite Mother_predT.                   (* 省略可能 *)\n    move=> H x.\n    Check H x : x ∈ p2S M -> x ∈ p2S pA.\n    apply: (H x).\n    done.\n  Qed.\n  \n  Lemma transitive_Sub (pA pB pC : pred M) :\n    pA ⊂ pB -> pB ⊂ pC -> pA ⊂ pC.\n  Proof.\n    move=> HAB HBC t HtA.\n      by auto.\n  Qed.\n\n(**\naxiom_mySet ではなく、fin_mySet を使って証明することができます。\nすなわち(公理 1.)を使用せずに証明できたことになります。\n*)  \n  Lemma cc_cancel' (pA : pred M) : (pA^c)^c = pA.\n  Proof.\n    apply: axiom_ExteqmySet.\n    split; rewrite /myComplement => x H;\n      by case: (fin_mySet pA x) => HxA.\n  Qed.\n\n  Lemma myUnionCompMother' (pA : pred M) : pA ∪ (pA^c) = myMotherSet.\n  Proof.\n    apply: axiom_ExteqmySet.\n    split=> [x | x H] //=.\n    case: (fin_mySet pA x); by [left | right].\n  Qed.\nEnd FinType.\n\nSection 具体的なfinType.\n  \n  Definition p0 := @Ordinal 5 0 is_true_true.\n  Check p2S 'I_5 : mySet 'I_5.  \n\n  Goal p0 ∈ p2S 'I_5.\n  Proof. by []. Qed.\n\nEnd 具体的なfinType.\n\n(**\n## mySet を bool型であらわす場合\n\nそもそも ``mySet M`` を bool型の ``pred M`` であらわすことで、(公理 1.)は不要になります。\nbelongがbool述語となるので、公理なしで決定性が保証されるからです。以下を参照してください。\n\nhttps://github.com/suharahiromichi/coq/blob/master/csm/csm_5_set_theory_class.v\n\n（ご注意。ファイル名に意味はありません）\n *)\n\n(**\n# 公理 2. について\n\nこれは、外延性の公理です。\n*)\n\nSection Test3.\n  Variable M : finType.                     (* 注意してください。 *)\n\n  Definition myMotherSet' : mySet M := fun (_ : M) => true.\n  \n  Lemma cc_cancel'' (pA : pred M) : (pA^c)^c =1 pA.\n  Proof.\n    move=> x.\n    rewrite /myComplement.\n    (* Goal : (~ ~ pA x) = pA x *)\n  Admitted.\n\n  Lemma myUnionCompMother'' (pA : pred M) : (pA ∪ (pA^c)) =1 myMotherSet'.\n  Proof.\n    move=> x.\n    case: (fin_mySet pA x).\n    move/myFinBelongP=> H.\n    rewrite /myCup /myComplement /myMotherSet'.\n  Admitted.\n  \nEnd Test3.\n\n(**\n# 文献\n\n[1.] 萩原学 アフェルト・レナルド、「Coq/SSReflect/MathCompによる定理証明」、森北出版\n\n[2.] Mathematical Components (MathComp Book) https://math-comp.github.io\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/csm/csm_5_set_theory_axiom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825635346563, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.6782018372019077}}
{"text": "Require Import Toy.FP.usl.interface.\nRequire Import Toy.FP.usl.implementation.\nRequire Import ZArith.\nRequire Import QArith.\nImport T.\nOpen Scope Z.\n\nDefinition mapsto (p : addr) (z : Z) : Assertion := fun st => exists q, snd st p = Some (q, z).\nDefinition mapsto' (p : addr) (q : Q) (z : Z) : Assertion := fun st => snd st p = Some (q, z).\nDefinition exp {A : Type} (P : A -> Assertion) : Assertion := fun st => exists a, P a st.\nDefinition NULL : addr := -1.\n\nFixpoint listrep (p : Z) (l : list Z) (q1 q2 : Q) : Assertion :=\n  match l with\n\t  | nil => fun _ => p = NULL \n\t  | cons x l' => sepcon (mapsto' p q1 x) (exp (fun t => sepcon (mapsto' (p + 1) q2 t) (listrep t l' q1 q2)))\n  end.\n\t", "meta": {"author": "TaoYC0904", "repo": "Toy-Language-Address", "sha": "cabf1d8ef0fd11dd5bf4d61b2df2322a296f710c", "save_path": "github-repos/coq/TaoYC0904-Toy-Language-Address", "path": "github-repos/coq/TaoYC0904-Toy-Language-Address/Toy-Language-Address-cabf1d8ef0fd11dd5bf4d61b2df2322a296f710c/2-FP/listrev.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6780933712090644}}
{"text": "Require Import Basis .\n\n(** 戦術を使う。 *)\nDeclare ML Module \"ltac_plugin\" .\nSet Default Proof Mode \"Classic\" .\n\n\nArguments paths : clear implicits .\nArguments idpath : clear implicits .\nArguments paths_elim : clear implicits .\nArguments paths_elim_nop : clear implicits .\n\nDefinition book_1_12_2_a\n  {A : Type} {P : forall a a', paths A a a' -> Type}\n  (case_idpath : forall a, P a a (idpath A a))\n  (a a' : A) (x : paths A a a') : P a a' x .\nProof.\n revert a' x .\n refine (paths_elim A a (P a) _) .\n exact (case_idpath a) .\nDefined.\n\nDefinition book_1_12_2_b\n  (A : Type) (a : A) (P : forall a', paths A a a' -> Type)\n  (case_idpath : P a (idpath A a))\n  (a' : A) (x : paths A a a') : P a' x .\nProof.\n revert a a' x P case_idpath .\n refine (paths_elim_nop A ?[ex_P] _) .\n refine (fun a P h => _) .\n exact h .\nDefined.\n\n(* transport *)\nDefinition exerise_1_8_lemma_1\n  (A : Type) (P : A -> Type)\n  (x y : A) (p : paths A x y)\n  (u : P x) : P y .\nProof.\n revert x y p u .\n refine (paths_elim_nop A (fun x y _ => P x -> P y) _) .\n exact (fun z v => v) .\nDefined.\n\n(* path_based_paths *)\nDefinition exerise_1_8_lemma_2\n  (X : Type) (x : X) (p : dsum (paths X x))\n  : paths (dsum (paths X x)) (dpair x (idpath X x)) p .\nProof.\n revert p .\n refine (dsum_elim _) .\n revert x .\n refine (paths_elim_nop X ?[ex_P] _) .\n exact (fun z => idpath (dsum (paths X z)) (dpair z (idpath X z))) .\nDefined.\n\nDefinition exerise_1_8\n  (A : Type) (a : A) (P : forall a', paths A a a' -> Type)\n  (case_idpath : P a (idpath A a))\n  (a' : A) (x : paths A a a') : P a' x .\nProof.\n pose (Q := fun h => P (dfst h) (dsnd h)) .\n pose (h := dpair a (idpath A a)) .\n pose (h' := dpair a' x) .\n change (Q h) in case_idpath .\n change (Q h') .\n refine (exerise_1_8_lemma_1 (dsum (paths A a)) Q h h' _ case_idpath) .\n change (paths (dsum (paths A a)) (dpair a (idpath A a)) h') .\n exact (exerise_1_8_lemma_2 A a h') .\nDefined.\n", "meta": {"author": "Hexirp", "repo": "seityou", "sha": "ba816a97a2299dec3be1a4823e71166dfaaf5637", "save_path": "github-repos/coq/Hexirp-seityou", "path": "github-repos/coq/Hexirp-seityou/seityou-ba816a97a2299dec3be1a4823e71166dfaaf5637/theories/HoTTBook.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.6780916997321766}}
{"text": "Require Import Arith List ZArith.\n\nInductive season : Set := Spring | Summer | Fall | Winter.\n\nTheorem bool_equal : forall (b:bool), b=true\\/b=false.\n  apply bool_ind;\n  [apply or_introl|apply or_intror];\n  apply refl_equal.\nQed.\n\nInductive month : Set := \n  January|\n  February|\n  March|\n  April|\n  May|\n  June|\n  July|\n  August|\n  September|\n  October|\n  November|\n  December.\n\nDefinition season_of_month m :=\n  (month_rec \n    (fun _:month => season) \n    Winter\n    Winter\n    Winter\n    Spring\n    Spring\n    Spring\n    Summer\n    Summer\n    Summer\n    Fall\n    Fall\n    Fall) m.\n\nDefinition season_of_month' m :=\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 => Winter\n  | November => Winter\n  | December => Winter\n  end.\n\nDefinition bool_not( b : bool ) := if b then false else true.\nDefinition bool_or( l r : bool ) := if l then true else r.\nDefinition bool_and( l r : bool ) := if l then r else false.\nDefinition bool_eq( l r : bool ) := if l then r else bool_not r.\nDefinition bool_xor( l r : bool ) := bool_not (bool_eq l r).\n\nTheorem bool_xor_not_eq : \n  forall b1 b2 : bool, (bool_xor b1 b2) = (bool_not (bool_eq b1 b2)).\n  trivial.\nQed.\n\nTheorem bool_not_and : \n  forall b1 b2 : bool,\n    (bool_not (bool_and b1 b2)) =\n    (bool_or (bool_not b1) (bool_not b2)).\n  case b1, b2;auto.\nQed.\n\nTheorem bool_not_not : forall b : bool, (bool_not (bool_not b))=b.\n  intros.\n  case b;auto.\nQed.\n\nTheorem bool_tex : forall b : bool, (bool_or b (bool_not b))=true.\n  intros.\n  case b;auto.\nQed.\n\nTheorem bool_eq_reflect : forall b1 b2 : bool, (bool_eq b1 b2)=true -> b1=b2.\n  intros.\n  case b1, b2;auto.\nQed.\n\nTheorem bool_eq_reflect2 : forall b1 b2 : bool, \n  b1 = b2 ->\n    (bool_eq b1 b2) = true.\n  intros.\n  case b1, b2;auto.\nQed.\n\nTheorem bool_not_or : forall b1 b2 : bool,\n  (bool_not (bool_or b1 b2)) = (bool_and (bool_not b1) (bool_not b2)).\n  intros.\n  case b1, b2;auto.\nQed.\n\nTheorem bool_distr:  forall b1 b2 b3:bool,\n  (bool_or (bool_and b1 b3) (bool_and b2 b3)) = (bool_and (bool_or b1 b2) b3).\n  intros.\n  case b1, b2, b3;auto.\nQed.\n\nRecord plane : Set := point {abscissa : Z; ordinate : Z}.\n\nDefinition absolute p :=\n  match p with\n  | Z0 => Z0\n  | Zneg x => Zpos x\n  | Zpos x => Zneg x\n  end.\n\nOpen Scope Z_scope.\n\nDefinition manhatten l r := \n  absolute ((abscissa l) - (abscissa r)) + \n  absolute ((ordinate l) - (ordinate r)).\n\nClose Scope Z_scope.\n\nInductive vehicle : Set :=\n  bicycle : nat -> vehicle|\n  motorized : nat -> nat -> vehicle.\n\nDefinition number_of_seats v : nat :=\n  vehicle_rec (fun _ => nat) (fun x => x) (fun x _ => x) v.\n\nDefinition is_January v : bool :=\n  month_rec\n    (fun _ => bool) \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    v.\n\nGoal true <> false.\n  unfold not.\n  intros.\n  change((fun b : bool => if b then False else True)true).\n  rewrite H.\n  trivial.\nQed.\n\nRecord RatPlus : Set := mkRat\n  {top : nat; bottom : nat; bottom_condition : bottom <> 0}.\n\nDefinition r0 : RatPlus.\n  apply (mkRat 1 2).\n  auto.\nDefined.\n\nDefinition r1 : RatPlus.\n  apply (mkRat 2 4).\n  auto.\nDefined.\n\nDefinition eq_RatPlus : Prop := forall r r':RatPlus,\n  top r * bottom r' = top r' * bottom r -> r = r'.\n\nGoal eq_RatPlus -> False.\n  unfold eq_RatPlus.\n  intros.\n  assert(r0=r1).\n  apply H.\n  simpl.\n  reflexivity.\n  discriminate H0.\nQed.\n\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 None => None \n    | Some y => Some (y + 2)\n    end.\n\n  Lemma g_domain : forall n, P (n+2) <-> g n <> None.\n    intros;\n    case(f_domain (n + 2));\n    intros H1 H2;\n    unfold g;\n    split;\n    [\n      remember (f (n + 2)) as o;\n      destruct o;\n      intros;\n      [\n        discriminate |\n        \n        apply H1;\n        assumption\n      ]|\n      \n      remember (f (n + 2)) as o;\n      destruct o;\n      intros;\n      apply H2;\n      discriminate||assumption\n    ].\n  Qed.\n \nEnd partial_functions.\n\nDefinition lt3 n :=\n  match n with\n  | O => true\n  | S O => true\n  | _ => false\n  end.\n\nFixpoint plus' l r {struct r}:=\n  match r with\n  | O => l\n  | S x => S (plus' l x)\n  end.\n\nGoal forall x y, plus' x y = x + y.\n  induction y.\n  auto with arith.\n  simpl.\n  rewrite IHy.\n  auto with arith.\nQed.\n\nOpen Scope Z_scope.\n\nFixpoint accumulate( begin time : nat )( f : nat -> Z ) : Z := \n  match time with\n  | O => 0\n  | S x => (f begin) + accumulate (S begin) x f\n  end.\n\nEval compute in accumulate 0 10 (fun x => Z_of_nat (x * x)).\n\nFixpoint two_power x := match x with |O => 1 |S x => 2 * (two_power x) end.\n\nClose Scope Z_scope.\n\nDefinition _1000 := xO (xO (xO (xI (xO (xI (xI (xI (xI (xH))))))))).\n\nDefinition _1024 := xO (xO (xO (xO (xO (xO (xO (xO (xO (xO xH))))))))).\n\nDefinition _25 := xI (xO (xO (xI xH))).\n\nDefinition _512 := xO (xO (xO (xO (xO (xO (xO (xO (xO xH)))))))).\n\nDefinition is_even n := match n with | xO _ => true | _ => false end.\n\nDefinition div_2 n := \n  match n with\n  | xO x => Zpos x\n  | xI x => Zpos x\n  | xH => Z0 end.\n\nDefinition div_4 n :=\n  match div_2 n with\n  | Z0 => Z0\n  | Zpos x => div_2 x\n  | Zneg x => div_2 x\n  end.\n\nInductive bool' : Set := \n  true'|\n  false'|\n  and' : bool' -> bool' -> bool'|\n  or' : bool' -> bool' -> bool'|\n  not : bool' -> bool'.\n\nFixpoint bool'_denote b :=\n  match b with\n  | true' => true\n  | false' => false\n  | and' l r => bool_and (bool'_denote l) (bool'_denote r)\n  | or' l r => bool_or (bool'_denote l) (bool'_denote r)\n  | not x => bool_not (bool'_denote x)\n  end.\n\nInductive F := one | N : F -> F | D : F -> F.\n\nFixpoint fraction f :=\n  match f with\n  | one => (1,1)\n  | N x => let (a,b) := fraction x in (a+b,b)\n  | D x => let (a,b) := fraction x in (a,a+b)\n  end.\n\nInductive Z_btree : Set :=\n| Z_leaf : Z_btree \n| Z_bnode : Z->Z_btree->Z_btree->Z_btree.\n\nFixpoint has_occurence find t :=\n  match t with\n  | Z_leaf => false\n  | Z_bnode num l r =>\n      bool_or\n        (Zeq_bool num find)\n        (bool_or\n          (has_occurence find l)\n          (has_occurence find r))\n  end.\n\nOpen Scope Z_scope.\n\nFixpoint power( x : Z )( y : nat ):=\n  match y with\n  | O => 1\n  | S y' => x * (power x y')\n  end.\n\nClose Scope Z_scope.\n\nFixpoint discrete_log p : nat :=\n  match p with\n  | xH => 0\n  | xI p' => S (discrete_log p')\n  | xO p' => S (discrete_log p')\nend.\n\nInductive Z_fbtree : Set :=\n| Z_fleaf : Z_fbtree \n| Z_fnode : Z  -> (bool -> Z_fbtree) -> Z_fbtree.\n\nFixpoint fzero_present t :=\n  match t with\n  | Z_fleaf => false\n  | Z_fnode num f => \n      bool_or (Zeq_bool num 0) \n        (bool_or (fzero_present (f true)) (fzero_present (f false)))\n  end.\n\nInductive Z_inf_branch_tree : Set :=\n| Z_inf_leaf : Z_inf_branch_tree\n| Z_inf_node : Z->(nat->Z_inf_branch_tree)->Z_inf_branch_tree.\n\nFixpoint zero_reachable t i :=\n  match t with \n  | Z_inf_leaf => false\n  | Z_inf_node num func =>\n      bool_or\n        (Zeq_bool num 0)\n        ((fix reachable (z : nat) :=\n          bool_or\n            (zero_reachable (func z) i)\n            match z with\n            | O => false\n            | S x => (reachable x)\n            end) i)\n  end.\n\nTheorem plus_n_O : forall n, n+0 =n.\n  intros.\n  elim n.\n  reflexivity.\n  intros.\n  simpl.\n  rewrite H.\n  reflexivity.\nQed.\n\nFixpoint f1 (t : Z_btree) : Z_fbtree :=\n  match t with\n  | Z_leaf => Z_fleaf\n  | Z_bnode num l r => Z_fnode num (fun b => if b then f1 l else f1 r)\n  end.\n\nFixpoint f2 (t : Z_fbtree) : Z_btree :=\n  match t with\n  | Z_fleaf => Z_leaf\n  | Z_fnode num func => Z_bnode num (f2 (func true)) (f2 (func false))\n  end.\n\nTheorem f2_f1 : forall t: Z_btree, f2 (f1 t) = t.\n  induction t.\n  reflexivity.\n  simpl.\n  rewrite IHt1.\n  rewrite IHt2.\n  reflexivity.\nQed.\n\nTheorem f1_f2 :\n  (forall (A B:Set) (f g: A -> B),\n    (forall a, f a = g a) -> f = g )->\n      (forall t: Z_fbtree, f1 (f2 t) = t).\n  induction t.\n  reflexivity.\n  simpl.\n  f_equal.\n  apply H.\n  destruct a;\n  apply H0.\nQed.\n\nFixpoint mult2 (n:nat) : nat :=\n  match n with\n    O => O\n  | (S p) => (S (S (mult2 p)))\n  end.\n\nGoal forall n, n + n = mult2 n.\n  induction n.\n  reflexivity.\n  rewrite <- plus_Snm_nSm.\n  simpl.\n  rewrite IHn.\n  reflexivity.\nQed.\n\nFixpoint sum_n (n:nat) : nat :=\n  match n with\n  | O => O \n  | (S p) => (plus (S p) (sum_n p))\n  end.\n\nGoal forall n, 2*(sum_n n) = n * (n+1).\n  induction n.\n  reflexivity.\n  unfold sum_n.\n  fold sum_n.\n  rewrite mult_plus_distr_l.\n  rewrite IHn.\n  simpl.\n  f_equal.\n  rewrite plus_n_O.\n  rewrite mult_succ_r.\n  rewrite mult_plus_distr_l.\n  rewrite plus_assoc_reverse.\n  rewrite plus_assoc_reverse.\n  f_equal.\n  simpl.\n  f_equal.\n  rewrite plus_comm.\n  reflexivity.\nQed.\n\nGoal forall n, n <= sum_n n.\n  induction n.\n  reflexivity.\n  simpl.\n  apply le_n_S.\n  apply le_plus_l.\nQed.\n\nFixpoint first_n(A : Type)(n : nat)(l : list A) :=\n  match n with\n  | O => nil\n  | S x => \n      match l with\n      | nil => nil\n      | e :: next => e :: first_n A x next\n      end\n  end.\n\nFixpoint generate begin time : list nat :=\n  match time with\n  | O => nil\n  | S x => begin :: generate (S begin) x\n  end.\n\nFixpoint nth_option (A:Set)(n:nat)(l:list A) {struct l}\n  : 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  | n, nil => None\n  end.\n\nLemma nth_length : \n  forall (A:Set)(n:nat)(l:list A),\n    nth_option _ n l = None <-> length l <= n.\n  induction n;\n  [\n    destruct l;\n    simpl;\n    split;\n    discriminate 1||auto;\n    inversion 1|\n    intros;\n    destruct l;\n    [\n      split;\n      auto with arith|\n      \n      simpl;\n      split;\n      case (IHn l);\n      auto with arith\n    ]\n  ].\nQed.\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, lr) := split A B l' in (a :: ll, b :: lr)\n  end.\n\nFixpoint combine (A B : Set)(ll : list A)(lr : list B) : list (A * B) := \n  match (ll, lr) with\n  | (l :: ll', r :: lr') => (l, r) :: (combine A B ll' lr')\n  | (_, _) => nil\n  end.\n\nGoal forall (A B : Set)(l : list (A * B)), \n  let ( l1,l2) :=  (split _ _ l) in combine _ _ l1 l2 = l.\n  induction l.\n  reflexivity.\n  simpl.\n  destruct (split A B l).\n  destruct a.\n  destruct IHl.\n  reflexivity.\nQed.\n\nInductive btree(T : Set) : Set :=\n  leaf : btree T | bnode : T->btree T->btree T->btree T.\n\nFixpoint to_b_tree_Z(t : Z_btree) : btree Z :=\n  match t with\n  | Z_leaf => leaf Z\n  | Z_bnode z l r => bnode Z z (to_b_tree_Z l) (to_b_tree_Z r)\n  end.\n\nFixpoint to_Z_btree(t : btree Z) : Z_btree :=\n  match t with\n  | leaf => Z_leaf\n  | bnode z l r => Z_bnode z (to_Z_btree l) (to_Z_btree r)\n  end.\n\nGoal forall t, to_Z_btree (to_b_tree_Z t) = t.\n  induction t.\n  reflexivity.\n  simpl.\n  rewrite IHt1.\n  rewrite IHt2.\n  reflexivity.\nQed.\n\nGoal forall t, to_b_tree_Z (to_Z_btree t) = t.\n  induction t.\n  reflexivity.\n  simpl.\n  rewrite IHt1.\n  rewrite IHt2.\n  reflexivity.\nQed.\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\nDefinition first_of_htree\n  (A : Set) (n : nat) (v : htree A n) (t : htree A (S n)) : htree A n :=\n    match t in (htree _ n0) return (htree A (pred n0) -> htree A (pred n0)) with\n    | hleaf _ => fun v' : htree A 0 => v'\n    | hnode p _ t1 _ => fun _ : htree A p => t1\n    end v.\n\nTheorem injection_first_htree:\n  forall (n : nat) (t1 t2 t3 t4 : htree nat n),\n    hnode nat n O t1 t2 = hnode nat n O 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\nFixpoint make_htree (n:nat): htree Z n :=\n  match n return htree Z n with\n    0 => hleaf Z 0%Z\n  | S p => hnode Z p 0%Z (make_htree p) (make_htree p)\n  end.\n\nInductive binary_word : nat -> Set :=\n  tail : binary_word 0\n| push : forall n : nat, bool -> binary_word n -> binary_word (S n).\n\nFixpoint word_con (nl nr : nat) (wl : binary_word nl) (wr : binary_word nr) : binary_word (nl + nr) := \n  match wl in binary_word ln return binary_word (ln + nr) with\n  | tail => wr\n  | push l b w => push (l + nr) b (word_con l nr w wr)\n  end.\n\nFixpoint binary_word_or (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    | tail => (fun x => x)\n    | push ll lb lw => \n        (fun wr' : binary_word (S ll) => match wr' with\n        | tail => (fun p : False => wr')\n        | push rl rb rw => \n            (fun p : ll = rl => \n              push\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\nTheorem all_equal : forall x y : Empty_set, x = y.\n  destruct x.\nQed.\n\nTheorem all_diff : forall x y : Empty_set, x <> y.\n  destruct x.\nQed.\n", "meta": {"author": "DKXXXL", "repo": "CoqArt", "sha": "ae8f577a618aeb7182c4478642a9d5ce4b289b46", "save_path": "github-repos/coq/DKXXXL-CoqArt", "path": "github-repos/coq/DKXXXL-CoqArt/CoqArt-ae8f577a618aeb7182c4478642a9d5ce4b289b46/Chapter6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.678091697615621}}
{"text": "From Coq Require Import ssreflect ssrbool ssrfun.\nFrom mathcomp Require Import eqtype order seq path.\nFrom favssr Require Import bintree bst.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport Order.POrderTheory.\nImport Order.TotalTheory.\nOpen Scope order_scope.\n\nModule ASetM.\nStructure ASetM (T : eqType): Type :=\n  make {tp :> Type;\n        empty : tp;\n        insert : T -> tp -> tp;\n        delete : T -> tp -> tp;\n        isin : tp -> T -> bool;\n\n        abs : tp -> pred T;\n        invar : tp -> bool;\n\n        _ : invar empty;\n        _ : abs empty =i pred0;\n\n        _ : forall x s, invar s -> invar (insert x s);\n        _ : forall x s, invar s ->\n              abs (insert x s) =i [predU1 x & abs s];\n\n        _ : forall x s, invar s -> invar (delete x s);\n        _ : forall x s, invar s ->\n              abs (delete x s) =i [predD1 abs s & x];\n\n        _ : forall s, invar s -> isin s =i abs s\n        }.\nEnd ASetM.\n\nSection Specification.\nContext {disp : unit} {T : orderType disp}.\n\nCorollary inorder_empty_pred : inorder (@Leaf T) =i pred0.\nProof. by []. Qed.\n\nCorollary inorder_insert_pred x (t : tree T) :\n  bst t ->\n  inorder (insert x t) =i [predU1 x & inorder t].\nProof.\nmove=>H z; move/perm_mem: (inorder_insert x H)=>/(_ z)->.\nrewrite inE; case: ifP=>//=.\nby case: eqP=>//->->.\nQed.\n\nCorollary inorder_delete_pred x (t : tree T) :\n  bst t ->\n  inorder (delete x t) =i [predD1 inorder t & x].\nProof.\nmove=>H z; move/perm_mem: (inorder_delete x H)=>/(_ z)->.\nby rewrite mem_filter; rewrite !inE /=.\nQed.\n\n(* direct proofs for unbalanced trees work *)\nDefinition UASetM :=\n  @ASetM.make _ (tree T)\n    leaf insert delete isin\n    (pred_of_seq \\o inorder) bst\n    bst_empty inorder_empty_pred\n    bst_insert inorder_insert_pred\n    bst_delete inorder_delete_pred\n    inorder_isin.\n\nCorollary emp_pred0 : (@nil T) =i pred0.\nProof. by []. Qed.\n\nCorollary inorder_ins_list_pred (x : T) xs :\n  sorted <%O xs ->\n  ins_list x xs =i [predU1 x & xs].\nProof.\nmove=>H z; move/perm_mem: (inorder_ins_list x H)=>/(_ z)->.\nrewrite !inE /=; case: ifP=>//=.\nby case: eqP=>//->->.\nQed.\n\nCorollary inorder_del_list_pred (x : T) xs :\n  sorted <%O xs ->\n  del_list x xs =i [predD1 xs & x].\nProof.\nmove=>H z; move/perm_mem: (inorder_del_list x H)=>/(_ z)->.\nby rewrite mem_filter; rewrite !inE /=.\nQed.\n\n(* sorted lists implement sets *)\nDefinition LASetM :=\n  @ASetM.make _ (seq T)\n    [::] ins_list del_list (fun xs s => s \\in xs)\n    (pred_of_seq \\o id) (sorted <%O)\n    erefl emp_pred0\n    ins_list_sorted inorder_ins_list_pred\n    del_list_sorted inorder_del_list_pred\n    (fun _ _ _ => erefl).\n\nCorollary bst_list_empty : bst_list (@Leaf T).\nProof. by []. Qed.\n\nCorollary bst_list_insert x (t : tree T) :\n  bst_list t -> bst_list (insert x t).\nProof.\nmove=>H; rewrite /bst_list inorder_insert_list //.\nby apply: ins_list_sorted.\nQed.\n\nCorollary inorder_insert_list_set x (t : tree T) :\n  bst_list t ->\n  inorder (insert x t) =i [predU1 x & inorder t].\nProof.\nrewrite /bst_list => Hn.\nrewrite inorder_insert_list //.\nby apply: inorder_ins_list_pred.\nQed.\n\nCorollary bst_list_delete x (t : tree T) :\n  bst_list t -> bst_list (delete x t).\nProof.\nmove=>H; rewrite /bst_list inorder_delete_list //.\nby apply: del_list_sorted.\nQed.\n\nCorollary inorder_delete_list_set x (t : tree T) :\n  bst_list t ->\n  inorder (delete x t) =i [predD1 inorder t & x].\nProof.\nrewrite /bst_list => Hn.\nrewrite inorder_delete_list //.\nby apply: inorder_del_list_pred.\nQed.\n\n(* unbalanced trees via sorted lists implement sets *)\nDefinition ULASetM :=\n  @ASetM.make _ (tree T)\n    leaf insert delete isin\n    (pred_of_seq \\o inorder) bst_list\n    bst_list_empty inorder_empty_pred\n    bst_list_insert inorder_insert_list_set\n    bst_list_delete inorder_delete_list_set\n    inorder_isin_list.\n\nEnd Specification.\n\nModule Map.\nStructure Map (K : eqType) (V : Type) : Type :=\n  make {tp :> Type;\n        empty : tp;\n        update : K -> V -> tp -> tp;\n        delete : K -> tp -> tp;\n        lookup : tp -> K -> option V;\n\n        invar : tp -> bool;\n\n        _ : invar empty;\n        _ : lookup empty =1 fun => None;\n\n        _ : forall k v s, invar s -> invar (update k v s);\n        _ : forall k v s, invar s ->\n            lookup (update k v s) =1 [eta (lookup s) with k |-> Some v];\n\n        _ : forall k s, invar s -> invar (delete k s);\n        _ : forall k s, invar s ->\n            lookup (delete k s) =1 [eta (lookup s) with k |-> None]\n        }.\nEnd Map.\n\n(* Exercise 6.1 *)\n\nModule ASetI.\nStructure ASetI (T : eqType): Type :=\n  make {tp :> Type;\n        empty : tp;\n        insert : T -> tp -> tp;\n        delete : T -> tp -> tp;\n        isin : tp -> T -> bool;\n\n        (* FIXME *)\n\n        }.\nEnd ASetI.\n\n(* Exercise 6.3 *)\n\nSection MapUnbalanced.\nContext {disp : unit} {K : orderType disp} {V : Type}.\n\nNotation kvtree := (tree (K*V)).\n\n(* FIXME *)\n\nEnd MapUnbalanced.\n", "meta": {"author": "clayrat", "repo": "fav-ssr", "sha": "ec672bc001f6ace70cfc971990631371263b40f1", "save_path": "github-repos/coq/clayrat-fav-ssr", "path": "github-repos/coq/clayrat-fav-ssr/fav-ssr-ec672bc001f6ace70cfc971990631371263b40f1/src/adt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6780916926247427}}
{"text": "Require BigO.Util.Admitted.\nRequire Import MathClasses.interfaces.abstract_algebra.\nRequire Import MathClasses.interfaces.orders.\nRequire Import MathClasses.orders.dec_fields.\nRequire Import MathClasses.orders.semirings.\n\nSection NoOrder.\n  Context `{DecField K}.\n  Context `{!FullPseudoSemiRingOrder Kle Klt}.\n  Lemma plus_le : forall x y z : K, 0 < x -> 0 < y -> x + y ≤ z -> x ≤ z.\n    intros x y z zero_lt_x zero_lt_y x_plus_y.\n    destruct (decompose_le x_plus_y) as [a Hyp].\n    destruct Hyp as [zero_le_a z_eq].\n\n    apply (compose_le x z (y + a)).\n    {\n      setoid_replace 0 with (0 + 0) by (now rewrite left_identity).\n      apply (plus_le_compat 0 _ 0 _); try assumption.\n      now apply lt_le.\n    }\n    {\n      now rewrite associativity.\n    }\n  Qed.\nEnd NoOrder.\n\nSection DecFieldLemmas.\n  Context `{DecField K}.\n  Context `{!FullPseudoSemiRingOrder Kle Klt}.\n  Context `{!TotalOrder Kle}.\n\n  Lemma zero_ne_one : (0 : K) ≠ (1 : K).\n    unfold not.\n    intros zero_eq_1.\n\n    assert (Hyp : PropHolds (strong_setoids.default_apart 1 0)) by\n      (exact (@decfield_nontrivial K Ae Aplus Amult Azero Aone Anegate Adec_recip H)).\n    unfold PropHolds in Hyp.\n    assert (Hyp' : PropHolds (1 ≠ 0)).\n    {\n      unfold PropHolds.\n      apply trivial_apart.\n      exact Hyp.\n    }\n    unfold PropHolds in Hyp'.\n    unfold not in Hyp'.\n    apply Hyp'.\n    now symmetry.\n  Qed.\n\n  Lemma zero_lt_one_dec : (0 : K) < (1 : K).\n    assert (one_is_less_than_the_other : 0 < 1 \\/ 1 < 0) by\n      (apply apart_total_lt; apply zero_ne_one).\n    assert (one_not_lt_zero : ¬ 1 < 0).\n    {\n      apply le_not_lt_flip.\n      exact Admitted.zero_le_one_dec.\n    }\n    unfold not in one_not_lt_zero.\n    case one_is_less_than_the_other.\n    {\n      trivial.\n    }\n    {\n      intros Hyp.\n      apply one_not_lt_zero in Hyp.\n      inversion Hyp.\n    }\n  Qed.\n\n  Lemma dec_recip_inverse_reverse : forall x : K, x ≠ 0 -> (/ x) * x = 1.\n    intros x.\n    rewrite commutativity.\n    apply dec_recip_inverse.\n  Qed.\n\n  Lemma dec_recip_inverse_ge_0 : forall x : K, 0 < x -> (/ x) * x = 1.\n    intros x x_gt_0.\n    apply dec_recip_inverse_reverse.\n    now apply lt_ne_flip.\n  Qed.\n\n  Lemma order_preserving_mult_le : forall a b c : K, 0 < c -> a ≤ b -> c * a ≤ c * b.\n    intros a b c c_ge_0 a_le_b.\n    now apply (order_preserving ((.*.) c) a b).\n  Qed.\n\n  Lemma order_preserving_mult : forall x : K, 0 < x -> OrderPreserving (mult x).\n    intros x x_ge_0.\n    repeat (split; try apply _).\n    intros a b.\n    intros a_leq_b.\n    now apply order_preserving_mult_le.\n  Qed.\n\n  Lemma order_preserving_mult_lt : forall a b c : K, 0 < c -> a < b -> c * a < c * b.\n    intros a b c c_gt_0 a_lt_b.\n    now apply (strictly_order_preserving ((.*.) c) a b).\n  Qed.\n\n  Require Import Coq.setoid_ring.Ring.\n  (* this is definitely in math-classes *)\n  Add Ring R: (MathClasses.theory.rings.stdlib_ring_theory K).\n  Lemma mult_pos_gt_0 : forall x y : K, 0 < x -> 0 < y -> 0 < x * y.\n    intros x y x_ge_0 y_ge_0.\n    assert (Hyp : x * 0 = 0) by ring.\n    rewrite <- Hyp.\n    apply order_preserving_mult_lt; assumption.\n  Qed.\nEnd DecFieldLemmas.", "meta": {"author": "langston-barrett", "repo": "coq-big-o", "sha": "8042cc068b02574ac94de469a55a9f89268616c3", "save_path": "github-repos/coq/langston-barrett-coq-big-o", "path": "github-repos/coq/langston-barrett-coq-big-o/coq-big-o-8042cc068b02574ac94de469a55a9f89268616c3/src/Util/DecField.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6780754925745869}}
{"text": "Require Import rt.util.all.\nRequire Import rt.model.basic.task rt.model.basic.job rt.model.basic.task_arrival\n               rt.model.basic.schedule.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.\n\n(* Definition of response-time bound and some simple lemmas. *)\nModule ResponseTime.\n\n  Import Schedule SporadicTaskset SporadicTaskArrival.\n  \n  Section ResponseTimeBound.\n\n    Context {sporadic_task: eqType}.\n    Context {Job: eqType}.\n    Context {arr_seq: arrival_sequence Job}.\n    Variable job_cost: Job -> time.\n    Variable job_task: Job -> sporadic_task.\n\n    (* Given a task ...*)\n    Variable tsk: sporadic_task.\n\n    (* ... and a particular schedule, ...*)\n    Context {num_cpus : nat}.\n    Variable sched: schedule num_cpus arr_seq.\n\n    (* ... R is a response-time bound of tsk in this schedule ... *)\n    Variable R: time.\n\n    Let job_has_completed_by := completed job_cost sched.\n\n    (* ... iff any job j of tsk in this arrival sequence has\n       completed by (job_arrival j + R). *)\n    Definition is_response_time_bound_of_task :=\n      forall (j: JobIn arr_seq),\n        job_task j = tsk ->\n        job_has_completed_by j (job_arrival j + R).\n        \n  End ResponseTimeBound.\n\n  Section BasicLemmas.\n\n    Context {sporadic_task: eqType}.\n    Context {Job: eqType}.\n    Variable job_cost: Job -> time.\n    Variable job_task: Job -> sporadic_task.\n\n    Context {arr_seq: arrival_sequence Job}.\n    \n    (* Consider any valid schedule... *)\n    Context {num_cpus : nat}.\n    Variable sched: schedule num_cpus arr_seq.\n\n    Let job_has_completed_by := completed job_cost sched.\n\n    (* ... where jobs dont execute after completion. *)\n    Hypothesis H_completed_jobs_dont_execute:\n      completed_jobs_dont_execute job_cost sched.\n\n    Section SpecificJob.\n\n      (* Then, for any job j ...*)\n      Variable j: JobIn arr_seq.\n      \n      (* ...with response-time bound R in this schedule, ... *)\n      Variable R: time.\n      Hypothesis response_time_bound:\n        job_has_completed_by j (job_arrival j + R). \n\n      (* the service received by j at any time t' after its response time is 0. *)\n      Lemma service_after_job_rt_zero :\n        forall t',\n          t' >= job_arrival j + R ->\n          service_at sched j t' = 0.\n      Proof.\n        rename response_time_bound into RT,\n               H_completed_jobs_dont_execute into EXEC; ins.\n        unfold is_response_time_bound_of_task, completed,\n               completed_jobs_dont_execute in *.\n        apply/eqP; rewrite -leqn0.\n        rewrite <- leq_add2l with (p := job_cost j).\n        move: RT => /eqP RT; rewrite -{1}RT addn0.\n        apply leq_trans with (n := service sched j t'.+1);\n          last by apply EXEC.\n        unfold service; rewrite -> big_cat_nat with\n                                   (p := t'.+1) (n := job_arrival j + R);\n            [rewrite leq_add2l /= | by ins | by apply ltnW].\n          by rewrite big_nat_recr // /=; apply leq_addl.\n      Qed.\n\n      (* The same applies for the cumulative service of job j. *)\n      Lemma cumulative_service_after_job_rt_zero :\n        forall t' t'',\n          t' >= job_arrival j + R ->\n          \\sum_(t' <= t < t'') service_at sched j t = 0.\n      Proof.\n        ins; apply/eqP; rewrite -leqn0.\n        rewrite big_nat_cond; rewrite -> eq_bigr with (F2 := fun i => 0);\n          first by rewrite big_const_seq iter_addn mul0n addn0 leqnn.\n        intro i; rewrite andbT; move => /andP [LE _].\n        by rewrite service_after_job_rt_zero;\n          [by ins | by apply leq_trans with (n := t')].\n      Qed.\n      \n    End SpecificJob.\n    \n    Section AllJobs.\n\n      (* Consider any task tsk ...*)\n      Variable tsk: sporadic_task.\n\n      (* ... for which a response-time bound R is known. *)\n      Variable R: time.\n      Hypothesis response_time_bound:\n        is_response_time_bound_of_task job_cost job_task tsk sched R.\n\n      (* Then, for any job j of this task, ...*)\n      Variable j: JobIn arr_seq.\n      Hypothesis H_job_of_task: job_task j = tsk.\n\n      (* the service received by job j at any time t' after the response time is 0. *)\n      Lemma service_after_task_rt_zero :\n        forall t',\n          t' >= job_arrival j + R ->\n          service_at sched j t' = 0.\n      Proof.\n        by ins; apply service_after_job_rt_zero with (R := R); [apply response_time_bound |].\n      Qed.\n\n      (* The same applies for the cumulative service of job j. *)\n      Lemma cumulative_service_after_task_rt_zero :\n        forall t' t'',\n          t' >= job_arrival j + R ->\n          \\sum_(t' <= t < t'') service_at sched j t = 0.\n      Proof.\n        by ins; apply cumulative_service_after_job_rt_zero with (R := R);\n          first by apply response_time_bound. \n      Qed.\n      \n    End AllJobs.\n\n  End BasicLemmas.\n    \nEnd ResponseTime.", "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/model/basic/response_time.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.678075488733104}}
{"text": "(**\n  Ciro Iván García López\n  Tesis de Maestría\n  Session Type Systems Verification\n  Unam - 2021\n*)\nFrom Tmcod Require Import Defs_Proposition.\nFrom Tmcod Require Import Defs_Tactics.\n\n\n(**\n  The dual operation is idempotent.\n*)\nProposition Doble_Duality_ULLT  : \nforall A : Proposition , \n(A^⊥)^⊥ = A. \nProof.\n  StructuralInduction A.\n  \nQed.\n#[global]\nHint Resolve Doble_Duality_ULLT : Piull.\n\n\n(**\n  The definition of the linear implication is well defined.\n*)\nProposition Dual_Implication_Tensor : \nforall A B : Proposition , \n((A −∘ B)^⊥) = (A ⊗ (B^⊥)).\nProof.\n  intros.\n  unfold ULLT_IMP.\n  simpl.\n  rewrite -> (Doble_Duality_ULLT A).\n  reflexivity.\nQed.\n#[global]\nHint Resolve Dual_Implication_Tensor : Piull.\n\n\n(**\n  Relation between duals, tensor and linear implication.\n  The proof follows fron the definitions.\n*)\nProposition Dual_Tensor_Implication :  \nforall A B : Proposition, \n((A ⊗ B )^⊥) = (A −∘ (B^⊥)).\nProof.\n  auto with Piull.\nQed.\n#[global]\nHint Resolve Dual_Implication_Tensor : Piull.\n\n\n(**\n  The linar implication respect the idempotent property of the tensor.\n  The proof follows from the definitions.\n*)\nProposition Doble_Dual_Implication : \nforall A B : Proposition, \n(((A −∘ B)^⊥)^⊥) = (A −∘ B).\nProof.\n  auto with Piull.\nQed.\n#[global]\nHint Resolve Dual_Implication_Tensor : Piull.\n\n\n\n(**\n*)\nTheorem Decid_Propositions :\nforall (A B : Proposition),\nA = B \\/ A <> B.\nProof.\n  intro.\n  induction A.\n  + destruct B; OrSearch.\n  + destruct B; OrSearch.\n  + destruct B; try OrSearch.\n    specialize (IHA1 B1).\n    specialize (IHA2 B2).\n    destruct IHA1.\n    - destruct IHA2.\n      * subst. Piauto.\n      * right.\n        unfold not.\n        intros.\n        apply H0.\n        inversions H1.\n        Piauto.\n    - right.\n      unfold not.\n      intros.\n      apply H.\n      inversions H0.\n      Piauto.\n  + destruct B; try OrSearch.\n    specialize (IHA1 B1).\n    specialize (IHA2 B2).\n    destruct IHA1.\n    - destruct IHA2.\n      * subst. Piauto.\n      * right.\n        unfold not.\n        intros.\n        apply H0.\n        inversions H1.\n        Piauto.\n    - right.\n      unfold not.\n      intros.\n      apply H.\n      inversions H0.\n      Piauto.\n  + destruct B; try OrSearch.\n    specialize (IHA B).\n    destruct IHA.\n    - rewrite H.\n      OrSearch.\n    - right.\n      unfold not.\n      intros.\n      apply H.\n      inversions H0.\n      Piauto.\n  + destruct B; try OrSearch.\n    specialize (IHA B).\n    destruct IHA.\n    - rewrite H.\n      OrSearch.\n    - right.\n      unfold not.\n      intros.\n      apply H.\n      inversions H0.\n      Piauto.\nQed.\n#[global]\nHint Resolve Decid_Propositions : Piull.\n\n\n(**\n*)\nProposition Dual_inv : \nforall A B : Proposition , \n(A^⊥)= (B^⊥) -> A = B.\nProof.\n  intros.\n  assert ( Ha : (A ^⊥)^⊥ = A); Piauto.\n  rewrite H in Ha.\n  rewrite Doble_Duality_ULLT in Ha.\n  Piauto.\nQed.\n#[global]\nHint Resolve Dual_inv : Piull.\n\n\n\n\n\n", "meta": {"author": "cigarcial", "repo": "Tmcod", "sha": "ca6c9c454521360020f5f668b1752d18013d786f", "save_path": "github-repos/coq/cigarcial-Tmcod", "path": "github-repos/coq/cigarcial-Tmcod/Tmcod-ca6c9c454521360020f5f668b1752d18013d786f/Props_Propositions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6780664349294869}}
{"text": "Require Import util.\nRequire Import Fourier.\nRequire Export flow.\nSet Implicit Arguments.\nOpen Local Scope R_scope.\n\nRequire Import Coq.Reals.Reals.\n\nSection function_properties.\n\n  Variable f: R -> R.\n\n  Definition strongly_increasing: Prop :=\n    forall x x', x < x' -> f x < f x'.\n  Definition strongly_decreasing: Prop :=\n    forall x x', x < x' -> f x' < f x.\n\n  Lemma mildly_increasing:\n    strongly_increasing -> forall x x', x <= x' -> f x <= f x'.\n  Proof with auto with real.\n    intros.\n    destruct H0...\n    subst...\n  Qed.\n\n  Lemma mildly_decreasing:\n    strongly_decreasing -> forall x x', x <= x' -> f x' <= f x.\n  Proof with auto with real.\n    intros.\n    destruct H0...\n    subst...\n  Qed.\n\n  Lemma strongly_increasing_rev: strongly_increasing -> forall x x', f x < f x' -> x < x'.\n  Proof with auto with real.\n    unfold strongly_increasing.\n    intros.\n    destruct (Rlt_le_dec x x')...\n    destruct (Rle_lt_or_eq_dec x' x r).\n      elimtype False...\n      apply (Rlt_asym _ _  H0)...\n    subst.\n    elimtype False.\n    apply (Rlt_irrefl _ H0).\n  Qed.\n\n  Lemma strongly_decreasing_rev: strongly_decreasing -> forall x x', f x < f x' -> x' < x.\n  Proof with auto with real.\n    unfold strongly_decreasing.\n    intros.\n    destruct (Rlt_le_dec x x').\n      elimtype False...\n      apply (Rlt_asym _ _  H0)...\n    destruct (Rle_lt_or_eq_dec x' x r)...\n    subst.\n    elimtype False.\n    apply (Rlt_irrefl _ H0).\n  Qed.\n\n  Definition monotonic: Set := { strongly_increasing } + { strongly_decreasing }.\n\n  Lemma mono_eq: monotonic -> forall x x', f x = f x' <-> x = x'.\n  Proof with auto.\n    split.\n      intros.\n      destruct (Rle_lt_dec x x').\n        destruct r...\n        elimtype False.\n        destruct H; set (s _ _ H1); rewrite H0 in r; apply Rlt_irrefl with (f x')...\n      elimtype False.\n      destruct H; set (s _ _ r); rewrite H0 in r0; apply Rlt_irrefl with (f x')...\n    intros. subst...\n  Qed.\n\nEnd function_properties.\n\nSection single_inverses.\n\n  Variable f: Flow R.\n\n  Definition mono: Set :=\n    { forall x, strongly_increasing (f x) } +\n    { forall x, strongly_decreasing (f x) }.\n\n  Variable fmono: mono.\n\n  Lemma purify_mono: forall x, monotonic (f x).\n  Proof.\n    intros.\n    unfold monotonic.\n    destruct fmono; set (s x); [left | right]; assumption.\n  Qed.\n\n  Definition mle (x x': R): Prop := if fmono then x <= x' else x' <= x.\n  Definition mlt (x x': R): Prop := if fmono then x < x' else x' < x.\n\n  Lemma mle_refl x: mle x x.\n  Proof. unfold mle. destruct fmono; simpl; auto with real. Qed.\n\n  Lemma mle_trans x y z: mle x y -> mle y z -> mle x z.\n  Proof.\n    unfold mle.\n    destruct fmono; simpl; intros; apply Rle_trans with y; assumption.\n  Qed.\n\n  Lemma mlt_le x x': mlt x x' -> mle x x'.\n  Proof. unfold mlt, mle. destruct fmono; simpl; auto with real. Qed.\n\n  Lemma mle_lt_or_eq_dec x x':\n    mle x x' -> { mlt x x' } + { x = x' }.\n  Proof with auto with real.\n    unfold mle, mlt.\n    destruct fmono; simpl; intros.\n      apply Rle_lt_or_eq_dec...\n    destruct (Rle_lt_or_eq_dec _ _ H)...\n  Qed.\n\n  Lemma mono_opp v t t': t' <= t -> mle (f v t') (f v t).\n  Proof with auto with real.\n    unfold mle.\n    destruct fmono.\n      intros.\n      set (s v).\n      unfold strongly_increasing in s0.\n      destruct H...\n      subst...\n    intros.\n    set (s v).\n    unfold strongly_increasing in s0.\n    destruct H...\n    subst...\n  Qed.\n\n  Variables\n    (inv: R -> R -> Time)\n    (inv_correct: forall x x', f x (inv x x') = x').\n\n  Definition f_eq x t t': f x t = f x t' <-> t = t'\n    := mono_eq (purify_mono x) t t'.\n\n  Lemma inv_correct' x t: inv x (f x t) = t.\n  Proof.\n    intros.\n    destruct (f_eq x (inv x (f x t)) t).\n    clear H0. apply H.\n    rewrite inv_correct. reflexivity.\n  Qed.\n\n\n  Lemma inv_plus x y z: inv x z = inv x y + inv y z.\n  Proof with auto.\n    intros. destruct (f_eq x (inv x z) (inv x y + inv y z)).\n    clear H0. apply H.\n    rewrite flow_additive...\n    repeat rewrite inv_correct...\n  Qed.\n\n  Lemma inv_refl x: inv x x = 0.\n  Proof with auto.\n    intros. destruct (f_eq x (inv x x) 0).\n    clear H0. apply H.\n    repeat rewrite inv_correct...\n    rewrite flow_zero...\n  Qed.\n\n  Lemma f_lt x t t': mlt (f x t) (f x t') -> t < t'.\n  Proof with auto with real.\n    unfold mlt.\n    destruct fmono; intros.\n      apply strongly_increasing_rev with (f x)...\n    apply strongly_decreasing_rev with (f x)...\n  Qed.\n\n  Lemma f_le x t t': mle (f x t) (f x t') -> t <= t'.\n  Proof with auto with real.\n    unfold mle.\n    intros.\n    set (f_lt x t t'). clearbody r.\n    unfold mlt in r.\n    destruct fmono; destruct H.\n          apply Rlt_le...\n        right. destruct (f_eq x t t')...\n      apply Rlt_le...\n    right. destruct (f_eq x t t')...\n  Qed.\n\n  Lemma inv_lt_right a x x': inv a x < inv a x' <-> mlt x x'.\n  Proof with auto.\n    unfold mlt.\n    split; intros.\n      replace x with (f a (inv a x))...\n      replace x' with (f a (inv a x'))...\n      destruct fmono; apply s...\n    set f_lt. clearbody r.\n    unfold mlt in r.\n    destruct fmono; apply r with a; repeat rewrite inv_correct...\n  Qed.\n\n  Lemma inv_pos x x': 0 < inv x x' <-> mlt x x'.\n  Proof with auto with real.\n    unfold mlt.\n    split; intros.\n      set f_lt. clearbody r.\n      intros.\n      replace x with (f x 0)...\n        replace x' with (f x (inv x x'))...\n        destruct fmono; apply s...\n      rewrite flow_zero...\n    rewrite <- inv_refl with x.\n    destruct (inv_lt_right x x x')...\n  Qed.\n\n  Lemma inv_very_correct t x: inv (f x t) x = -t.\n  Proof with auto with real.\n    intros.\n    assert (inv x x = 0).\n      apply inv_refl.\n    rewrite (inv_plus x (f x t) x) in H.\n    rewrite inv_correct' in H.\n    replace (-t) with (0-t)...\n    rewrite <- H.\n    unfold Rminus.\n    rewrite Rplus_comm.\n    rewrite <- Rplus_assoc.\n    rewrite Rplus_opp_l...\n  Qed.\n\n  Lemma inv_inv x y: inv x y = - inv y x.\n  Proof with auto with real.\n    intros.\n    set (inv_very_correct (inv y x) y).\n    rewrite inv_correct in e...\n  Qed.\n\n  Lemma inv_uniq_0 x x': inv x x' = - inv 0 x + inv 0 x'.\n  Proof.\n    intros.\n    rewrite (inv_plus x 0 x').\n    rewrite (inv_inv x 0).\n    auto with real.\n  Qed.\n    (* hm, this shows that inv is uniquely determined by the values it\n      takes with 0 as first argument. perhaps the reason we don't\n      just take inv as a unary function is that it is problematic\n      for flow functions with singularities at 0? *)\n\n  Lemma inv_le a x x': mle x x' -> inv a x <= inv a x'.\n  Proof with auto.\n    intros.\n    set f_le. clearbody r.\n    apply r with a.\n    do 2 rewrite inv_correct...\n  Qed.\n\n  Lemma inv_nonneg x x': 0 <= inv x x' <-> mle x x'.\n  Proof with auto with real.\n    unfold mle.\n    split; intros.\n      set f_le. clearbody r.\n      intros.\n      replace x with (f x 0)...\n        replace x' with (f x (inv x x'))...\n        apply mono_opp...\n      apply flow_zero.\n    rewrite <- inv_refl with x.\n    apply inv_le...\n  Qed.\n\n  Lemma inv_zero x x': inv x x' = 0 <-> x = x'.\n  Proof with auto.\n    split; intros.\n      replace x' with (f x (inv x x'))...\n      rewrite H.\n      rewrite flow_zero...\n    subst.\n    rewrite inv_refl...\n  Qed.\n\n  Lemma f_lt_left x x' t: x < x' <-> f x t < f x' t.\n  Proof with auto with real.\n    split.\n      intros.\n      replace x' with (f x (inv x x'))...\n      rewrite <- flow_additive...\n      destruct (inv_pos x x').\n      destruct (inv_pos x' x).\n      unfold mlt in *.\n      destruct fmono.\n        apply s.\n        set (H1 H).\n        fourier.\n      apply s.\n      rewrite inv_inv.\n      set (H3 H).\n      fourier.\n    set f_lt. set inv_pos. clearbody r i.\n    unfold mlt in r, i.\n    destruct fmono; intros.\n      replace (f x' t) with (f (f x (inv x x')) t) in H...\n        rewrite <- flow_additive in H...\n        set (r _ _ _ H).\n        assert (0 < inv x x') by fourier.\n        destruct (i x x').\n        apply H1...\n      rewrite inv_correct...\n    replace (f x t) with (f (f x' (inv x' x)) t) in H...\n      rewrite <- flow_additive in H...\n      set (r _ _ _ H).\n      assert (0 < inv x' x) by fourier.\n      destruct (i x' x).\n      apply H1...\n    rewrite inv_correct...\n  Qed.\n\n  Lemma f_eq_left x x' t: f x t = f x' t <-> x = x'.\n  Proof with auto with real.\n    intros.\n    split; intros.\n      intros.\n      destruct (Rlt_le_dec x x').\n        elimtype False.\n        destruct (f_lt_left x x' t).\n        set (H0 r).\n        rewrite H in r0.\n        apply (Rlt_asym _ _ r0)...\n      destruct (Rle_lt_or_eq_dec _ _ r)...\n      elimtype False.\n      destruct (f_lt_left x' x t).\n      set (H0 r0).\n      rewrite H in r1.\n      apply (Rlt_asym _ _ r1)...\n    subst...\n  Qed.\n\n  Lemma f_le_left x x' t: x <= x' <-> f x t <= f x' t.\n  Proof with auto with real.\n    intros.\n    destruct (f_lt_left x x' t).\n    split; intro.\n      destruct H1...\n      subst...\n    destruct H1.\n      destruct (f_lt_left x x' t)...\n    replace x' with x...\n    destruct (f_eq_left x x' t)...\n  Qed.\n\n  Lemma inv_lt_left a x x': mlt x x' <-> inv x' a < inv x a.\n  Proof with auto with real.\n    unfold mlt.\n    intros.\n    rewrite (inv_inv x' a).\n    rewrite (inv_inv x a).\n    destruct (inv_lt_right a x x').\n    split...\n    intros.\n    apply H...\n  Qed.\n\n  Lemma inv_le_left a x x': mle x x' -> inv x' a <= inv x a.\n  Proof with auto with real.\n    unfold mle. intros.\n    destruct (inv_lt_left a x x').\n    unfold mlt in *.\n    destruct fmono; intros; destruct H; subst...\n  Qed.\n\n  Lemma inv_eq_right a x x': inv a x = inv a x' <-> x = x'.\n  Proof with auto with real.\n    split.\n      intros.\n      replace x with (f a (inv a x))...\n      replace x' with (f a (inv a x'))...\n    intros...\n  Qed.\n\n  Lemma inv_le_right a x x': inv a x <= inv a x' <-> mle x x'.\n  Proof with auto with real.\n    intros.\n    destruct (inv_lt_right a x x').\n    split; intro.\n      destruct H1.\n        apply mlt_le...\n      rewrite (conj_fst (inv_eq_right a x x') H1).\n      apply mle_refl.\n    destruct (mle_lt_or_eq_dec _ _ H1)...\n    subst...\n  Qed.\n\n  Lemma mle_flow t x: 0 <= t -> mle x (f x t).\n  Proof with auto.\n    intros.\n    apply mle_trans with (f x 0).\n      rewrite flow_zero...\n      apply mle_refl.\n    apply mono_opp...\n  Qed.\n\nEnd single_inverses.\n", "meta": {"author": "Eelis", "repo": "hybrid", "sha": "2065074beeca682de60d3e6e31dff9f16cc3a7ef", "save_path": "github-repos/coq/Eelis-hybrid", "path": "github-repos/coq/Eelis-hybrid/hybrid-2065074beeca682de60d3e6e31dff9f16cc3a7ef/old-nonconstructive/monotonic_flow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6780664264251283}}
{"text": "(****************************************************************************\n                                                                             \n          IEEE754  :  Digit                                                  \n                                                                             \n          Laurent Thery                                                      \n                                                                             \n  *****************************************************************************\n  Gives the number of digits necessary to write a number in a given base *)\nRequire Export ZArithRing.\nRequire Export Omega.\nRequire Export Faux.\nSection Pdigit.\n(* n is the base *)\nVariable n : Z.\n(* and it is greater or equal to 2 *)\nHypothesis nMoreThan1 : (1 < n)%Z.\n \nLet nMoreThanOne := Zlt_1_O _ (Zlt_le_weak _ _ nMoreThan1).\nHint Resolve nMoreThanOne: zarith.\n \nTheorem Zpower_nat_less : forall q : nat, (0 < Zpower_nat n q)%Z.\nintros q; elim q; simpl in |- *;\nauto with zarith.\nQed.\nHint Resolve Zpower_nat_less: zarith.\n \nTheorem Zpower_nat_monotone_S :\n forall p : nat, (Zpower_nat n p < Zpower_nat n (S p))%Z.\nintros p; rewrite <- (Zmult_1_l (Zpower_nat n p)); replace (S p) with (1 + p);\n [ rewrite Zpower_nat_is_exp | auto with zarith ].\nrewrite Zpower_nat_1; auto with zarith.\napply Zmult_gt_0_lt_compat_r; auto with zarith.\napply Zlt_gt; auto with zarith.\nQed.\n \nTheorem Zpower_nat_monotone_lt :\n forall p q : nat, p < q -> (Zpower_nat n p < Zpower_nat n q)%Z.\nintros p q H'; elim H'; simpl in |- *; auto.\napply Zpower_nat_monotone_S.\nintros m H H0; apply Zlt_trans with (1 := H0).\napply Zpower_nat_monotone_S.\nQed.\nHint Resolve Zpower_nat_monotone_lt: zarith.\n \nTheorem Zpower_nat_anti_monotone_lt :\n forall p q : nat, (Zpower_nat n p < Zpower_nat n q)%Z -> p < q.\nintros p q H'.\ncase (le_or_lt q p); auto; (intros H'1; generalize H'; case H'1).\nintros H'0; Contradict H'0; auto with zarith.\nintros m H'0 H'2; Contradict H'2; auto with zarith.\nQed.\n \nTheorem Zpower_nat_monotone_le :\n forall p q : nat, p <= q -> (Zpower_nat n p <= Zpower_nat n q)%Z.\nintros p q H'; case (le_lt_or_eq _ _ H'); auto with zarith.\nintros H1; rewrite H1; auto with zarith.\nQed.\n \nTheorem Zpower_nat_anti_monotone_le :\n forall p q : nat, (Zpower_nat n p <= Zpower_nat n q)%Z -> p <= q.\nintros p q H'; case (le_or_lt p q); intros H'0; auto with arith.\nContradict H'; auto with zarith.\nQed.\n \nTheorem Zpower_nat_anti_eq :\n forall p q : nat, Zpower_nat n p = Zpower_nat n q -> p = q.\nintros p q H'; apply le_antisym; apply Zpower_nat_anti_monotone_le;\n rewrite H'; auto with zarith.\nQed.\n(* To compute the number of digits structurally, we suppose that\n   we know already an upper bound q. So we start from q down\n   to 0 to find the bigger exponent r such that n^(r-1) < v *)\n \nFixpoint digitAux (v r : Z) (q : positive) {struct q} : nat :=\n  match q with\n  | xH => 0\n  | xI q' =>\n      match (n * r)%Z with\n      | r' =>\n          match (r ?= v)%Z with\n          | Datatypes.Gt => 0\n          | _ => S (digitAux v r' q')\n          end\n      end\n  | xO q' =>\n      match (n * r)%Z with\n      | r' =>\n          match (r ?= v)%Z with\n          | Datatypes.Gt => 0\n          | _ => S (digitAux v r' q')\n          end\n      end\n  end.\n(* As we know that log_n q < log_2 q we can define our function digit*)\n \nDefinition digit (q : Z) :=\n  match q with\n  | Z0 => 0\n  | Zpos q' => digitAux (Zabs q) 1 (xO q')\n  | Zneg q' => digitAux (Zabs q) 1 (xO q')\n  end.\nHint Unfold digit.\n \nTheorem digitAux1 :\n forall p r, (Zpower_nat n (S p) * r)%Z = (Zpower_nat n p * (n * r))%Z.\nintros p r; replace (S p) with (1 + p);\n [ rewrite Zpower_nat_is_exp | auto with arith ].\nrewrite Zpower_nat_1; ring.\nQed.\n \nTheorem Zcompare_correct :\n forall p q : Z,\n match (p ?= q)%Z with\n | Datatypes.Gt => (q < p)%Z\n | Datatypes.Lt => (p < q)%Z\n | Datatypes.Eq => p = q\n end.\nintros p q; unfold Zlt in |- *; generalize (Zcompare_EGAL p q);\n (CaseEq (p ?= q)%Z; simpl in |- *; auto).\nintros H H0; case (Zcompare_Gt_Lt_antisym p q); auto.\nQed.\n \nTheorem digitAuxLess :\n forall (v r : Z) (q : positive),\n match digitAux v r q with\n | S r' => (Zpower_nat n r' * r <= v)%Z\n | O => True\n end.\nintros v r q; generalize r; elim q; clear r q; simpl in |- *; auto.\nintros q' Rec r; generalize (Zcompare_correct r v); case (r ?= v)%Z; auto.\nintros H1; generalize (Rec (n * r)%Z); case (digitAux v (n * r) q').\nintros; rewrite H1; rewrite Zpower_nat_O; auto with zarith.\nintros r'; rewrite digitAux1; auto.\nintros H1; generalize (Rec (n * r)%Z); case (digitAux v (n * r) q').\nintros; rewrite Zpower_nat_O; auto with zarith.\napply Zle_trans with (m := r); auto with zarith.\nintros r'; rewrite digitAux1; auto.\nintros q' Rec r; generalize (Zcompare_correct r v); case (r ?= v)%Z; auto.\nintros H1; generalize (Rec (n * r)%Z); case (digitAux v (n * r) q').\nintros; rewrite H1; rewrite Zpower_nat_O; auto with zarith.\nintros r'; rewrite digitAux1; auto.\nintros H1; generalize (Rec (n * r)%Z); case (digitAux v (n * r) q').\nintros; rewrite Zpower_nat_O; auto with zarith.\napply Zle_trans with (m := r); auto with zarith.\nintros r'; rewrite digitAux1; auto.\nQed.\n(* digit is correct (first part) *)\n \nTheorem digitLess :\n forall q : Z, q <> 0%Z -> (Zpower_nat n (pred (digit q)) <= Zabs q)%Z.\nintros q; case q.\nintros H; Contradict H; auto with zarith.\nintros p H; unfold digit in |- *;\n generalize (digitAuxLess (Zabs (Zpos p)) 1 (xO p));\n case (digitAux (Zabs (Zpos p)) 1 (xO p)); simpl in |- *; \n auto with zarith.\nintros p H; unfold digit in |- *;\n generalize (digitAuxLess (Zabs (Zneg p)) 1 (xO p));\n case (digitAux (Zabs (Zneg p)) 1 (xO p)); simpl in |- *; \n auto with zarith.\nQed.\nHint Resolve digitLess: zarith.\nHint Resolve Zmult_gt_0_lt_compat_r Zmult_gt_0_lt_compat_l: zarith.\n \nFixpoint pos_length (p : positive) : nat :=\n  match p with\n  | xH => 0\n  | xO p' => S (pos_length p')\n  | xI p' => S (pos_length p')\n  end.\n \nTheorem digitAuxMore :\n forall (v r : Z) (q : positive),\n (0 < r)%Z ->\n (v < Zpower_nat n (pos_length q) * r)%Z ->\n (v < Zpower_nat n (digitAux v r q) * r)%Z.\nintros v r q; generalize r; elim q; clear r q; simpl in |- *.\nintros p Rec r Hr; generalize (Zcompare_correct r v); case (r ?= v)%Z; auto.\nintros H1 H2; rewrite <- H1.\napply Zle_lt_trans with (Zpower_nat n 0 * r)%Z; auto with zarith arith.\nrewrite Zpower_nat_O; rewrite Zmult_1_l; auto with zarith.\nintros H1 H2; rewrite digitAux1.\napply Rec.\napply Zlt_mult_ZERO; auto with zarith.\nrewrite <- digitAux1; auto.\nrewrite Zpower_nat_O; rewrite Zmult_1_l; auto with zarith.\nintros p Rec r Hr; generalize (Zcompare_correct r v); case (r ?= v)%Z; auto.\nintros H1 H2; rewrite <- H1.\napply Zle_lt_trans with (Zpower_nat n 0 * r)%Z; auto with zarith arith.\nrewrite Zpower_nat_O; rewrite Zmult_1_l; auto with zarith.\nintros H1 H2; rewrite digitAux1.\napply Rec.\napply Zlt_mult_ZERO; auto with zarith.\nrewrite <- digitAux1; auto.\nrewrite Zpower_nat_O; rewrite Zmult_1_l; auto with zarith.\nauto.\nQed.\n \nTheorem pos_length_pow :\n forall p : positive, (Zpos p < Zpower_nat n (S (pos_length p)))%Z.\nintros p; elim p; simpl in |- *; auto.\nintros p0 H; rewrite Zpos_xI.\napply Zlt_le_trans with (2 * (n * Zpower_nat n (pos_length p0)))%Z;\nauto with zarith.\nintros p0 H; rewrite Zpos_xO.\napply Zlt_le_trans with (2 * (n * Zpower_nat n (pos_length p0)))%Z;\nauto with zarith.\nauto with zarith.\nQed.\n(* digit is correct (second part) *)\n \nTheorem digitMore : forall q : Z, (Zabs q < Zpower_nat n (digit q))%Z.\nintros q; case q.\neasy.\nintros q'; rewrite <- (Zmult_1_r (Zpower_nat n (digit (Zpos q')))).\nunfold digit in |- *; apply digitAuxMore; auto with zarith.\nrewrite Zmult_1_r.\nsimpl in |- *; apply pos_length_pow.\nintros q'; rewrite <- (Zmult_1_r (Zpower_nat n (digit (Zneg q')))).\nunfold digit in |- *; apply digitAuxMore; auto with zarith.\nrewrite Zmult_1_r.\nsimpl in |- *; apply pos_length_pow.\nQed.\nHint Resolve digitMore: zarith.\n(* if we find an r such that n^(r-1) =< q < n^r \n   then r is the number of digits *)\n \nTheorem digitInv :\n forall (q : Z) (r : nat),\n (Zpower_nat n (pred r) <= Zabs q)%Z ->\n (Zabs q < Zpower_nat n r)%Z -> digit q = r.\nintros q r H' H'0; case (le_or_lt (digit q) r).\nintros H'1; case (le_lt_or_eq _ _ H'1); auto; intros H'2.\nabsurd (Zabs q < Zpower_nat n (digit q))%Z; auto with zarith.\napply Zle_not_lt; auto with zarith.\napply Zle_trans with (m := Zpower_nat n (pred r)); auto with zarith.\napply Zpower_nat_monotone_le.\ngeneralize H'2; case r; auto with arith.\nintros H'1.\nabsurd (Zpower_nat n (pred (digit q)) <= Zabs q)%Z; auto with zarith.\napply Zlt_not_le; auto with zarith.\napply Zlt_le_trans with (m := Zpower_nat n r); auto.\napply Zpower_nat_monotone_le.\ngeneralize H'1; case (digit q); auto with arith.\napply digitLess; auto with zarith.\ngeneralize H'1; case q; unfold digit in |- *; intros tmp; intros; red in |- *;\n intros; try discriminate; Contradict tmp; auto with arith.\nQed.\n \nTheorem digitO : digit 0 = 0.\nunfold digit in |- *; simpl in |- *; auto with arith.\nQed.\n \nTheorem digit1 : digit 1 = 1.\nunfold digit in |- *; simpl in |- *; auto.\nQed.\n(* digit is monotone *)\n \nTheorem digit_monotone :\n forall p q : Z, (Zabs p <= Zabs q)%Z -> digit p <= digit q.\nintros p q H; case (le_or_lt (digit p) (digit q)); auto; intros H1;\n Contradict H.\napply Zlt_not_le.\ncut (p <> 0%Z); [ intros H2 | idtac ].\napply Zlt_le_trans with (2 := digitLess p H2).\ncut (digit q <= pred (digit p)); [ intros H3 | idtac ].\napply Zlt_le_trans with (2 := Zpower_nat_monotone_le _ _ H3);\n auto with zarith.\ngeneralize H1; case (digit p); simpl in |- *; auto with arith.\ngeneralize H1; case p; simpl in |- *; intros tmp; intros; red in |- *; intros;\n try discriminate; Contradict tmp; auto with arith.\nQed.\nHint Resolve digit_monotone: arith.\n(* if the number is not null so is the number of digits *)\n \nTheorem digitNotZero : forall q : Z, q <> 0%Z -> 0 < digit q.\nintros q H'.\napply lt_le_trans with (m := digit 1); auto with zarith.\napply digit_monotone.\ngeneralize H'; case q; simpl in |- *; auto with zarith; intros q'; case q';\n simpl in |- *; auto with zarith arith; intros; red in |- *; \n simpl in |- *; red in |- *; intros; discriminate.\nQed.\nHint Resolve Zlt_gt: zarith.\n \nTheorem digitAdd :\n forall (q : Z) (r : nat),\n q <> 0%Z -> digit (q * Zpower_nat n r) = digit q + r.\nintros q r H0.\napply digitInv.\nreplace (pred (digit q + r)) with (pred (digit q) + r).\nrewrite Zpower_nat_is_exp; rewrite Zabs_Zmult;\n rewrite (fun x => Zabs_eq (Zpower_nat n x)); auto with zarith arith.\ngeneralize (digitNotZero _ H0); case (digit q); auto with arith.\nintros H'; Contradict H'; auto with arith.\nrewrite Zpower_nat_is_exp; rewrite Zabs_Zmult;\n rewrite (fun x => Zabs_eq (Zpower_nat n x)); auto with zarith arith.\nQed.\n \nTheorem digit_minus1 : forall p : nat, digit (Zpower_nat n p - 1) = p.\nintros p; case p; auto.\nintros n0; apply digitInv; auto.\nrewrite Zabs_eq.\ncut (Zpower_nat n (pred (S n0)) < Zpower_nat n (S n0))%Z; auto with zarith.\ncut (0 < Zpower_nat n (S n0))%Z; auto with zarith.\nrewrite Zabs_eq; auto with zarith.\nQed.\n \nTheorem digit_bound :\n forall (x y z : Z) (n : nat),\n (Zabs x <= Zabs y)%Z ->\n (Zabs y <= Zabs z)%Z -> digit x = n -> digit z = n -> digit y = n.\nintros x y z n0 H' H'0 H'1 H'2; apply le_antisym.\nrewrite <- H'2; auto with arith.\nrewrite <- H'1; auto with arith.\nQed.\n \nTheorem digit_abs : forall p : Z, digit (Zabs p) = digit p.\nintros p; case p; simpl in |- *; auto.\nQed.\n(* Strict comparison on the number of digits gives comparison on the numbers *)\n \nTheorem digit_anti_monotone_lt :\n (1 < n)%Z -> forall p q : Z, digit p < digit q -> (Zabs p < Zabs q)%Z.\nintros H' p q H'0.\ncase (Zle_or_lt (Zabs q) (Zabs p)); auto; intros H'1.\nContradict H'0.\ncase (Zle_lt_or_eq _ _ H'1); intros H'2.\napply le_not_lt; auto with arith.\nrewrite <- (digit_abs p); rewrite <- (digit_abs q); rewrite H'2;\n auto with arith.\nQed.\nEnd Pdigit.\nHint Resolve Zpower_nat_less: zarith.\nHint Resolve Zpower_nat_monotone_lt: zarith.\nHint Resolve Zpower_nat_monotone_le: zarith.\nHint Unfold digit.\nHint Resolve digitLess: zarith.\nHint Resolve digitMore: zarith.\nHint Resolve digit_monotone: arith.", "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/Digit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6780664221729487}}
{"text": "Definition N := 2.\n\nInductive tree : Type :=\n| Leaf : tree\n| Node : nat -> tree -> tree -> tree.\n\nFixpoint binary_tree c n :=\n  match n with\n  | 0 => Leaf\n  | S n =>\n    let t := binary_tree c n in\n    Node c t t\n  end.\n\nDefinition t0 := Eval vm_compute in binary_tree 0 N.\nDefinition t1 := Eval vm_compute in binary_tree 1 N.\n", "meta": {"author": "eponier", "repo": "compare-eq", "sha": "cc2da184e747d0ad6ada8597e1ebf03377e413e2", "save_path": "github-repos/coq/eponier-compare-eq", "path": "github-repos/coq/eponier-compare-eq/compare-eq-cc2da184e747d0ad6ada8597e1ebf03377e413e2/equality_test/2/type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6780664215306482}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import msl.Coqlib2.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Import floyd.sublist.\n\n(* from verif_revarray.v *)\n\nDefinition flip_between {A} lo hi (contents: list A) :=\n  firstn (Z.to_nat lo) (rev contents)\n  ++ firstn (Z.to_nat (hi-lo)) (skipn (Z.to_nat lo) contents)\n  ++ skipn (Z.to_nat hi) (rev contents).\n\nLemma flip_fact_0: forall {A} size (contents: list A),\n  Zlength contents = size ->\n  contents = flip_between 0 (size - 0) contents.\nProof.\n  intros.\n  assert (length contents = Z.to_nat size).\n    apply Nat2Z.inj. rewrite <- Zlength_correct, Z2Nat.id; auto.\n    subst; rewrite Zlength_correct; omega.\n  unfold flip_between.\n  rewrite !Z.sub_0_r. change (Z.to_nat 0) with O; simpl. rewrite <- H0.\n  rewrite skipn_short.\n  rewrite <- app_nil_end.\n  rewrite firstn_exact_length. auto.\n  rewrite rev_length. omega.\nQed.\n\nLemma flip_fact_1: forall A size (contents: list A) j,\n  Zlength contents = size ->\n  0 <= j ->\n  size - j - 1 <= j <= size - j ->\n  flip_between j (size - j) contents = rev contents.\nProof.\n  intros.\n  assert (length contents = Z.to_nat size).\n    apply Nat2Z.inj. rewrite <- Zlength_correct, Z2Nat.id; auto.\n    subst; rewrite Zlength_correct; omega.\n  unfold flip_between.\n  symmetry.\n  rewrite <- (firstn_skipn (Z.to_nat j)) at 1.\n  f_equal.\n  replace (Z.to_nat (size-j)) with (Z.to_nat j + Z.to_nat (size-j-j))%nat\n    by (rewrite <- Z2Nat.inj_add by omega; f_equal; omega).\n  rewrite <- skipn_skipn.\n  rewrite <- (firstn_skipn (Z.to_nat (size-j-j)) (skipn (Z.to_nat j) (rev contents))) at 1.\n  f_equal.\n  rewrite firstn_skipn_rev.\nFocus 2.\nrewrite H2.\napply Nat2Z.inj_le.\nrewrite Nat2Z.inj_add by omega.\nrewrite !Z2Nat.id by omega.\nomega.\n  rewrite len_le_1_rev.\n  f_equal. f_equal. f_equal.\n  rewrite <- Z2Nat.inj_add by omega. rewrite H2.\n  rewrite <- Z2Nat.inj_sub by omega. f_equal; omega.\n  rewrite firstn_length, min_l.\n  change 1%nat with (Z.to_nat 1). apply Z2Nat.inj_le; omega.\n  rewrite skipn_length.  rewrite H2.\n  rewrite <- Z2Nat.inj_sub by omega. apply Z2Nat.inj_le; omega.\nQed.\n\nLemma Zlength_flip_between:\n forall A i j (al: list A),\n 0 <= i  -> i<=j -> j <= Zlength al ->\n Zlength (flip_between i j al) = Zlength al.\nProof.\nintros.\nunfold flip_between.\nrewrite !Zlength_app, !Zlength_firstn, !Zlength_skipn, !Zlength_rev.\nforget (Zlength al) as n.\nrewrite (Z.max_comm 0 i).\nrewrite (Z.max_l i 0) by omega.\nrewrite (Z.max_comm 0 j).\nrewrite (Z.max_l j 0) by omega.\nrewrite (Z.max_comm 0 (j-i)).\nrewrite (Z.max_l (j-i) 0) by omega.\nrewrite (Z.max_comm 0 (n-i)).\nrewrite (Z.max_l (n-i) 0) by omega.\nrewrite Z.max_r by omega.\nrewrite (Z.min_l i n) by omega.\nrewrite Z.min_l by omega.\nomega.\nQed.\n\nLemma flip_fact_3:\n forall A (al: list A) (d: A) j size,\n  size = Zlength al ->\n  0 <= j < size - j - 1 ->\nfirstn (Z.to_nat j)\n  (firstn (Z.to_nat (size - j - 1)) (flip_between j (size - j) al) ++\n   firstn (Z.to_nat 1) (skipn (Z.to_nat j) (flip_between j (size - j) al)) ++\n   skipn (Z.to_nat (size - j - 1 + 1)) (flip_between j (size - j) al)) ++\nfirstn (Z.to_nat 1)\n  (skipn (Z.to_nat (size - j - 1)) al) ++\nskipn (Z.to_nat (j + 1))\n  (firstn (Z.to_nat (size - j - 1)) (flip_between j (size - j) al) ++\n   firstn (Z.to_nat 1) (skipn (Z.to_nat j) (flip_between j (size - j) al)) ++\n   skipn (Z.to_nat (size - j - 1 + 1)) (flip_between j (size - j) al)) =\nflip_between (Z.succ j) (size - Z.succ j) al.\nProof.\nintros.\nassert (Zlength (rev al) = size) by (rewrite Zlength_rev; omega).\nunfold flip_between.\nrewrite Zfirstn_app1.\nFocus 2. {\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite !Zlength_app.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite !Zlength_skipn.\nrewrite (Z.max_r 0 j) by omega.\nrewrite (Z.max_r 0 (size-j)) by omega.\nrewrite Z.max_r by omega.\nrewrite Z.max_r by omega.\nrewrite (Z.min_l j) by omega.\nrewrite (Z.min_l (size-j-j)) by omega.\nrewrite Z.min_l by omega.\nomega.\n} Unfocus.\nrewrite Zfirstn_app2\n by (rewrite Zlength_firstn, Z.max_r by omega;\n      rewrite Z.min_l by omega; omega).\nrewrite Zfirstn_app1\n by (rewrite Zlength_firstn, Z.max_r by omega;\n      rewrite Z.min_l by omega; omega).\nrewrite Zfirstn_firstn by omega.\nrewrite Zskipn_app1.\nFocus 2. {\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_rev.\nrewrite !Zlength_app.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Z.min_l by omega.\nrewrite Zlength_firstn.\nrewrite (Z.min_l j (Zlength al)) by omega.\nrewrite Z.max_r by omega.\nrewrite Zlength_app.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_skipn.\nrewrite (Z.max_r 0 j)  by omega.\nrewrite (Z.max_r 0 ) by omega.\nrewrite (Z.min_l  (size-j-j)) by omega.\nrewrite Zlength_skipn.\nrewrite (Z.max_r 0 (size-j)) by omega.\nrewrite Z.max_r by omega.\nrewrite Z.min_l by omega.\nomega.\n} Unfocus.\nrewrite Zskipn_app2\n by (rewrite Zlength_firstn, Z.max_r by omega;\n       rewrite Z.min_l by omega; omega).\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Z.min_l by omega.\nrewrite Zfirstn_app1.\nFocus 2. {\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_skipn, (Z.max_r 0 j) by omega.\nrewrite Z.max_r by omega.\nrewrite Z.min_l by omega. omega.\n} Unfocus.\nrewrite Zfirstn_firstn by omega.\nrewrite Zskipn_app2\n by (rewrite Zlength_firstn, Z.max_r by omega;\n       rewrite Z.min_l by omega; omega).\nrewrite Zskipn_app1.\nFocus 2. {\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Z.min_l by omega.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_skipn, (Z.max_r 0 j) by omega.\nrewrite Z.max_r by omega.\nrewrite Z.min_l by omega. omega.\n} Unfocus.\nrewrite Zfirstn_app1.\nFocus 2. {\nrewrite !Zlength_skipn, !Zlength_firstn.\nrewrite (Z.max_r 0 j) by omega.\nrewrite (Z.min_l j) by omega.\nrewrite Zlength_skipn.\nrewrite (Z.max_r 0 j) by omega.\nrewrite (Z.max_r 0 (Zlength al - j)) by omega.\nrewrite (Z.max_l 0 (j-j)) by omega.\nrewrite (Z.max_r 0 (size-j-j)) by omega.\nrewrite Z.min_l by omega.\nrewrite Z.max_r by omega.\nomega.\n} Unfocus.\nrewrite Zskipn_app2.\nFocus 2. {\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite (Z.min_l j) by omega.\nomega.\n} Unfocus.\nrewrite Zskipn_app2.\nFocus 2. {\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite (Z.min_l j) by omega.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_skipn, (Z.max_r 0 j) by omega.\nrewrite Z.max_r by omega.\nrewrite Z.min_l by omega.\nomega.\n} Unfocus.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_skipn, (Z.max_r 0 j) by omega.\nrewrite Z.max_r by omega.\nrewrite Z.min_l by omega.\nrewrite Z.min_l by omega.\nrewrite Zskipn_skipn by omega.\nrewrite !Zskipn_firstn by omega.\nrewrite !Z.sub_diag.\nrewrite Z.sub_0_r.\nrewrite !Zskipn_skipn by omega.\nrewrite Zfirstn_firstn by omega.\nrewrite <- app_ass.\nf_equal.\nrewrite <- (firstn_skipn (Z.to_nat j) (rev al)) at 2.\nrewrite Zfirstn_app2\n  by (rewrite Zlength_firstn, Z.max_r by omega;\n        rewrite Z.min_l by omega; omega).\nrewrite Zlength_firstn, Z.max_r by omega;\nrewrite Z.min_l by omega.\nreplace (Z.succ j - j) with 1 by omega.\nf_equal.\nrewrite app_nil_end.\nrewrite app_nil_end at 1.\nrewrite <- Znth_cons with (d0:=d) by omega.\nrewrite <- Znth_cons with (d0:=d) by omega.\nf_equal.\nrewrite Znth_rev by omega.\nf_equal. omega.\nreplace (size - j - 1 - j - (j + 1 - j))\n  with (size- Z.succ j- Z.succ j) by omega.\nreplace (j+(j+1-j)) with (j+1) by omega.\nf_equal.\nrewrite Z.add_0_r.\nrewrite <- (firstn_skipn (Z.to_nat 1) (skipn (Z.to_nat (size- Z.succ j)) (rev al))).\nrewrite Zskipn_skipn by omega.\nf_equal.\nrewrite app_nil_end.\nrewrite app_nil_end at 1.\nrewrite <- Znth_cons with (d0:=d) by omega.\nrewrite <- Znth_cons with (d0:=d) by omega.\nf_equal.\nrewrite Znth_rev by omega.\nf_equal.\nomega.\nf_equal.\nf_equal.\nomega.\nQed.\n\nLemma flip_fact_2:\n  forall {A} (al: list A) size j d,\n Zlength al = size ->\n  j < size - j - 1 ->\n   0 <= j ->\n  Znth (size - j - 1) al d =\n  Znth (size - j - 1) (flip_between j (size - j) al) d.\nProof.\nintros.\nunfold flip_between.\nrewrite app_Znth2\n by (rewrite Zlength_firstn, Z.max_r by omega;\n      rewrite Zlength_rev, Z.min_l by omega; omega).\nrewrite Zlength_firstn, Z.max_r by omega;\nrewrite Zlength_rev, Z.min_l by omega.\nrewrite app_Znth1.\nFocus 2. {\nrewrite Zlength_firstn, Z.max_r by omega;\nrewrite Zlength_skipn by omega.\nrewrite (Z.max_r 0 j) by omega.\nrewrite Z.max_r by omega.\nrewrite Z.min_l by omega.\nomega. } Unfocus.\nrewrite Znth_firstn by omega.\nrewrite Znth_skipn by omega.\nf_equal; omega.\nQed.\n\nRequire Import msl.shares.\nRequire Import veric.shares.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.common.Values.\nRequire Import compcert.cfrontend.Ctypes.\nRequire Import veric.expr.\n\nLemma verif_sumarray_example1:\nforall (sh : share) (contents : list int) (size : Z) (a : val),\nreadable_share sh ->\n0 <= size <= Int.max_signed ->\nis_pointer_or_null a ->\n@Zlength val (@map int val Vint contents) = size ->\n0 <= 0 /\\\n(0 <= size /\\ True) /\\\na = a /\\\nVint (Int.repr 0) = Vint (Int.repr 0) /\\\nVint (Int.repr size) = Vint (Int.repr size) /\\\nVint Int.zero = Vint (Int.repr 0) /\\ True.\nAbort.\n\nLemma verif_sumarray_example2:\nforall (sh : share) (contents : list int) (size : Z) (a : val),\nforall (sh : share) (contents : list int) (size a1 : Z) (a : val),\nreadable_share sh ->\n0 <= size <= Int.max_signed ->\na1 < size ->\n0 <= a1 <= size ->\nis_pointer_or_null a ->\nZlength (map Vint contents) = size ->\nis_int I32 Signed (Znth a1 (map Vint contents) Vundef).\nAbort.\n\nRequire Import compcert.exportclight.Clightdefs.\n\nLemma verif_sumarray_example3:\nforall (sum_int: list int -> int) (sh : share) (contents : list int) (size a1 : Z) (a : val) (x s : int),\n(forall (contents0 : list int) (i : Z) (x0 : int),\n Znth i (map Vint contents0) Vundef = Vint x0 ->\n 0 <= i ->\n sum_int (sublist 0 (Z.succ i) contents0) =\n Int.add (sum_int (sublist 0 i contents0)) x0) ->\nreadable_share sh ->\n0 <= size <= Int.max_signed ->\na1 < size ->\n0 <= a1 <= size ->\nis_pointer_or_null a ->\nforce_val\n  (sem_add_default tint tint (Vint (sum_int (sublist 0 a1 contents)))\n     (Znth a1 (map Vint contents) Vundef)) = Vint s ->\nZnth a1 (map Vint contents) Vundef = Vint x ->\nZlength (map Vint contents) = size ->\n0 <= Z.succ a1 /\\\n(Z.succ a1 <= size /\\ True) /\\\na = a /\\\nVint (Int.repr (Z.succ a1)) = Vint (Int.repr (a1 + 1)) /\\\nVint (Int.repr size) = Vint (Int.repr size) /\\\nVint (sum_int (sublist 0 (Z.succ a1) contents)) = Vint s /\\ True.\nAbort.\n\n\nRequire Import veric.Clight_lemmas.  (* just for nullval? *)\n\nLemma verif_reverse_example1:\nforall (sum_int: list int -> int) (sh : share) (contents cts : list int) (t0 t_old t : val) (h : int),\nreadable_share sh ->\nisptr t0 ->\nt0 = t_old ->\nis_pointer_or_null t ->\nis_pointer_or_null t ->\n(t = nullval <-> map Vint cts = []) ->\nt = t /\\\nVint (Int.sub (sum_int contents) (sum_int cts)) =\nVint (Int.add (Int.sub (sum_int contents) (Int.add h (sum_int cts))) h) /\\\nTrue.\nAbort.\n\nLemma verif_reverse_example2:\nforall (sh : share) (contents cts1 : list val) (w h : val) (r : list val)\n  (w_ t_ : val),\nwritable_share sh ->\ncontents = rev cts1 ++ h :: r ->\nis_pointer_or_null t_ ->\nis_pointer_or_null w_ ->\nisptr w_ ->\nis_pointer_or_null t_ ->\nis_pointer_or_null t_ ->\n(t_ = nullval <-> r = []) ->\nis_pointer_or_null w ->\n(w = nullval <-> cts1 = []) ->\ncontents = (rev cts1 ++ [h]) ++ r /\\ True /\\ w_ = w_ /\\ t_ = t_ /\\ True.\nAbort.\n\n\n\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/floyd/smt_test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6780664215306482}}
{"text": "Require Import geometry2D.\nRequire Import Vector.\nRequire Import fastReals.misc.\nRequire Import MCInstances.\nRequire Import fastReals.interface.\n\nOpen Scope mc_scope.\n\n\nLemma Min_plusl: ∀ a b c : ℝ, min (c + a) (c + b) =  c + min a b.\nProof.\n  intros.\n  rewrite (plus_comm c).\n  rewrite (plus_comm c).\n  setoid_rewrite Min_plus.\n  rewrite (plus_comm c).\n  reflexivity.\nQed.\n\nLemma Max_plusl: ∀ a b c : ℝ, max (c + a) (c + b) =  c + max a b.\nProof.\n  intros.\n  rewrite (plus_comm c).\n  rewrite (plus_comm c).\n  setoid_rewrite max_plus.\n  rewrite (plus_comm c).\n  reflexivity.\nQed.\n\nLemma minCartSum : forall c a b : Cart2D IR,\n  minCart (c+a) (c+b) = c + minCart a b.\nProof.\n  intros. unfold minCart. simpl.\n  rewrite Min_plusl.\n  rewrite Min_plusl.\n  split; reflexivity.\nQed.\n\nLemma maxCartSum : forall c a b : Cart2D IR,\n  maxCart (c+a) (c+b) = c + maxCart a b.\nProof.\n  intros. unfold maxCart. simpl.\n  rewrite Max_plusl.\n  rewrite Max_plusl.\n  split; reflexivity.\nQed.\n\nGlobal Instance ProperMinCart : \n  Proper (equiv ==> equiv  ==> equiv) (@minCart IR _).\nProof.\n  intros ? ? h1  ? ? h2.\n  destruct h1. destruct h2.\n  split; simpl; apply Max_AbsIR.Min_wd_unfolded; tauto.\nQed.\n\nGlobal Instance ProperMaxCart : \n  Proper (equiv ==> equiv  ==> equiv) (@maxCart IR _).\nProof.\n  intros ? ? h1  ? ? h2.\n  destruct h1. destruct h2.\n  split; simpl; apply Max_AbsIR.Max_wd_unfolded; tauto.\nQed.\n\nGlobal Instance AssociativeMinIR : `{Associative  (@min IR _)}.\n  intros ? ? ?. apply MinAssoc.\nQed.\n\nGlobal Instance AssociativeMaxIR : `{Associative  (@max IR _)}.\n  intros ? ? ?. apply MaxAssoc.\nQed.\n\nGlobal Instance AssociativeMinCart `{MinClass R} `{Associative _ (@min R _)}: \n  Associative  (@minCart R _).\nProof.\n  intros ? ? ?. split; simpl;\n  apply simple_associativity.\nQed.\n\nGlobal Instance AssociativeMaxCart `{MaxClass R} `{Associative _ (@max R _)}: \n  Associative  (@maxCart R _).\nProof.\n  intros ? ? ?. split; simpl;\n  apply simple_associativity.\nQed.\n\nGlobal Instance CommutativeMinIR : `{Commutative  (@min IR _)}.\n  intros ? ?. apply Min_comm.\nQed.\n\nGlobal Instance CommutativeMaxIR : `{Commutative  (@max IR _)}.\n  intros ? ?. apply Max_comm.\nQed.\n\nGlobal Instance CommutativeMinCart `{MinClass R} `{Commutative _ _ (@min R _)}: \n  Commutative  (@minCart R _).\nProof.\n  intros ? ?. split; simpl;\n  apply commutativity.\nQed.\n\nGlobal Instance CommutativeMaxCart `{MaxClass R} `{Commutative _ _ (@max R _)}: \n  Commutative  (@maxCart R _).\nProof.\n  intros ? ?. split; simpl;\n  apply commutativity.\nQed.\n\nHint Unfold cos CosClassIR sin SinClassIR min MinClassIR max MaxClassIR: IRMC.\n\nRequire Import IRTrig.\nLemma unitVecNonNeg : forall θ, 0 ≤ θ ≤ (½ * π)\n  -> 0 ≤ unitVec θ.\nProof.\n  intros ? hh.\n  pose proof (less_leEq ℝ [0] Pi pos_Pi) as h.\n  apply nonneg_div_two' in h.\n  autounfold with IRMC in hh.\n  unfold Zero_instance_IR in hh.\n  destruct hh as [x y]. \n  rewrite PiBy2DesugarIR in y.\n  pose proof MinusPiBy2Le0.\n  split; simpl;\n  [apply Cos_nonneg | apply Sin_nonneg]; eauto 3 with CoRN.\nQed.\n\n  Lemma unitVec90Minus :  ∀ θ:IR, \n    unitVec (½ * π - θ) = {|X:= sin θ; Y:= cos θ|}.\n  Proof using.\n    intros ?. split; simpl;\n    autounfold with IRMC.\n    -  rewrite PiBy2DesugarIR.\n      apply Cos_HalfPi_minus.\n    - rewrite PiBy2DesugarIR.\n      apply Sin_HalfPi_minus.\n  Qed.\n\nLocal Opaque Sin.\nLocal Opaque Cos.\n\n  Lemma unitVecMinus90 :  ∀ θ:IR, \n    unitVec (θ - ½ * π) = {|X:= sin θ; Y:=- cos θ|}.\n  Proof using.\n    intros ?. unfold EquivCart, unitVec.\n    autounfold with IRMC. simpl.\n    rewrite <- Cos_inv.\n    setoid_rewrite minusInvR.\n    rewrite <- (cg_inv_inv _ (Sin (θ [+] [--] (½ [*] π)))).\n    rewrite <- Sin_inv.\n    setoid_rewrite minusInvR.\n    split.\n    - rewrite PiBy2DesugarIR.\n      apply Cos_HalfPi_minus.\n    - rewrite PiBy2DesugarIR.\n      apply cg_inv_wd.\n      apply Sin_HalfPi_minus.\n  Qed.\n\n\nLemma unitVecMinDistr :  forall θ a b:IR, 0 ≤ θ ≤ (½ * π)\n  ->\n  minCart ((unitVec θ) * 'a) ((unitVec θ) * 'b)\n     = (unitVec θ) * '(min a b).\nProof.\n  intros ? ? ? hh.\n  apply unitVecNonNeg in hh. unfold unitVec in hh.\n  destruct hh as [x y]. simpl in x, y. \n  unfold minCart. split; simpl;\n  autounfold with IRMC;\n  rewrite MinMultLeft; try reflexivity; try assumption.\nQed.\n\n\nLemma unitVecMaxDistr :  forall θ a b:IR, 0 ≤ θ ≤ (½ * π)\n  ->\n  maxCart ((unitVec θ) * 'a) ((unitVec θ) * 'b)\n     = (unitVec θ) * '(max a b).\nProof.\n  intros ? ? ? hh.\n  apply unitVecNonNeg in hh. unfold unitVec in hh.\n  destruct hh as [x y]. simpl in x, y. \n  unfold maxCart. split; simpl;\n  autounfold with IRMC;\n  rewrite MaxMultLeft; try reflexivity; try assumption.\nQed.\n\nLemma minCart_leEq_lft: ∀ x y : Cart2D ℝ, \n  minCart x y ≤ x.\nProof using .\n  intros ? ?.\n  split; apply Min_leEq_lft.\nQed.\n\nLemma minCart_leEq_rht: ∀ x y : Cart2D ℝ, \n  minCart x y ≤ y.\nProof using .\n  intros ? ?. rewrite commutativity.\n  apply minCart_leEq_lft.\nQed.\n\nLemma lft_leEq_maxCart: ∀ x y : Cart2D ℝ, \n  x ≤ maxCart x y.\nProof using .\n  intros ? ?.\n  split; apply lft_leEq_Max.\nQed.\n\nLemma rht_leEq_maxCart: ∀ x y : Cart2D ℝ, \n  y ≤ maxCart x y.\nProof using .\n  intros ? ?. rewrite commutativity.\n  apply lft_leEq_maxCart.\nQed.\n\nLemma leEq_minCart : ∀ x y z : Cart2D ℝ, \n  z ≤ x → z ≤ y → z ≤ minCart x y.\nProof using .\n  intros ? ? ? Hab Hbc.\n  destruct Hab, Hbc.\n  split; apply leEq_Min; assumption.\nQed.\n\nLemma maxCart_leEq : ∀ x y z : Cart2D ℝ, \n  x ≤ z → y ≤ z → maxCart x y ≤ z.\nProof using .\n  intros ? ? ? Hab Hbc.\n  destruct Hab, Hbc.\n  split; apply Max_leEq; assumption.\nQed.\n\n  \nHint Resolve minCart_leEq_lft\nminCart_leEq_rht\nlft_leEq_maxCart\nrht_leEq_maxCart\nleEq_minCart\nmaxCart_leEq\n : MinMaxCart.\n\nLemma boundingUnionIff: forall (a b c : Line2D IR),\n  boundingUnion a b ⊆ c\n  <-> (a ⊆ c /\\ b ⊆ c).\nProof using .\n  intros. unfold boundingUnion, le, LeAsSubset.\n  simpl. split; intro hh.\n  - repnd. split; split;\n    eapply (@transitivity (Cart2D ℝ) le _);\n    try apply hhl;\n    try apply hhr;\n    eauto using\n      minCart_leEq_lft,\n      minCart_leEq_rht,\n      lft_leEq_maxCart,\n      rht_leEq_maxCart.\n  - repnd. split; eauto using \n      leEq_minCart, maxCart_leEq.\nQed.\n\nGlobal Instance CommBoundingUnion `{e:Equiv R} `{m:MinClass R}\n`{M: MaxClass R} `{@Commutative R e R min} `{@Commutative R e R max}:\n  Commutative boundingUnion.\nProof using.\n  unfold BoundingRectangle. intros ? ?. split; simpl.\n  - apply CommutativeMinCart.\n  - apply CommutativeMaxCart.\nQed.\n\nLemma boundingUnionPlus : forall (a b c: Line2D IR),\n  boundingUnion (b + a) (b + c)\n  = b + (boundingUnion a c).\nProof using.\n  intros ? ? ?.\n  unfold boundingUnion.\n  simpl.\n  rewrite minCartSum.\n  rewrite maxCartSum.\n  reflexivity.\nQed.\n\nLemma  boundingUnionLeft:\n  ∀ a b: Line2D ℝ, a ⊆ boundingUnion a b.\nProof.\n  intros ? ?. unfold boundingUnion;\n  split; simpl; eauto using minCart_leEq_lft,\n    lft_leEq_maxCart.\nQed.\n\nLemma  boundingUnionRight:\n  ∀ a b: Line2D ℝ, b ⊆ boundingUnion a b.\nProof.\n  intros. rewrite commutativity.\n  apply boundingUnionLeft.\nQed.\n\nGlobal Instance ProperboundingUnion:\n Proper (equiv ==> equiv ==> equiv) \n (@boundingUnion IR _ _).\nProof.\n  intros ? ? H1 ? ? H2.\n  unfold boundingUnion.\n  rewrite H1, H2. reflexivity.\nQed.\n\nLtac remCart2D c1min :=\n  match goal with\n    [|- context [{|\n            X :=?x ; Y :=?y|} ]] \n         => remember ({|\n            X :=x ; Y :=y|}) as c1min\n    end.\n\nRequire Import MCMisc.tactics.\nLtac simpRemCart2D c1min Heqc1min :=\n  match goal with\n    [|- context [{|\n            X :=?x ; Y :=?y|} ]] \n         => mcremember ({|\n            X :=x ; Y :=y|}) c1min Heqc1min;\n          ring_simplify x in Heqc1min; \n          ring_simplify y in Heqc1min\n    end.\n\nDefinition unitVecT `{SinClass R} `{CosClass R} (t:R) := transpose (unitVec t).\n\nDefinition flipAngle (c:Polar2D IR) : Polar2D IR:=\n{| rad := rad c ; θ:= ½ * π -θ c|}.\n\n\nLemma minCartIsLeft : forall (a b : Cart2D IR),\n  a ≤ b\n  -> minCart a b = a.\nProof using.\n  intros ? ? Hle.\n  destruct Hle.\n  split; simpl; apply leEq_imp_Min_is_lft; assumption.\nQed.\n\nLemma maxCartIsRight : forall (a b : Cart2D IR),\n  a ≤ b\n  -> maxCart a b = b.\nProof using.\n  intros ? ? Hle.\n  destruct Hle.\n  split; simpl; apply leEq_imp_Max_is_rht; assumption.\nQed.\n\nRequire Import MCMisc.rings.\n\n  Local Notation ConfineRect := (Line2D).\n  Local Notation minxy := (lstart).\n  Local Notation maxxy := (lend).\n\nLemma unionWithNonNegDisplacement : forall (a: ConfineRect IR) (d : Cart2D IR),\n  0 ≤ d\n  -> boundingUnion a (a+'d)\n    = {| minxy := lstart a ; maxxy := lend a + d |}.\nProof using.\n  intros ? ? Hle.\n  split; simpl.\n  - rewrite minCartIsLeft; auto.\n    rewrite commutativity.\n    apply RingLeProp1. assumption.\n  - rewrite maxCartIsRight; auto.\n    rewrite commutativity.\n    apply RingLeProp1. assumption.\nQed.\n\nRequire Import MathClasses.interfaces.vectorspace.\n\nRequire Import IRMisc.LegacyIRRing.\n\nRequire Import CartIR.\n(* Move *)\nLemma FFT2 : forall (θ:IR),\n(Cos θ * Cos θ + Sin θ * Sin θ) = 1.\nProof using.\n  intro.\n  rewrite <- (FFT θ).\n  simpl.\n  IRring.\nQed.\n\nRequire Import fastReals.interface.\n\nLemma FFT3 : forall (θ:IR),\ncos θ * cos θ  = 1 - sin θ * sin θ.\nProof using.\n  intro.\n  rewrite <- (FFT θ).\n  simpl.\n  IRring.\nQed.\n\nDefinition negY `{One A}`{Negate A} : Cart2D A:= \n{|X:=1;Y:=-1|}.\n\nRequire Import geometry2D.\nLemma unitVNegate :\n  forall (β : IR), unitVec (- β) = negY * unitVec β.\nProof using.\n  intros.\n  split; simpl.\n  - rewrite mult_1_l. apply Cos_inv.\n  - rewrite <- negate_mult_distr_l.\n    rewrite mult_1_l. apply Sin_inv.\nQed.\n\n\n\nLemma rotateAxisInvSimpl :\nforall (p : Cart2D IR) (θ:IR),\n(rotateAxis (-θ) p) =   \n  {| X := X p * cos θ - Y p * sin θ;\n    Y := Y p * cos θ + X p * sin θ\n  |}.\nProof using.\n  intros ? ?.  unfold rotateAxis. simpl.\n  unfold inprod, InProductCart2D.\n  split; simpl; \n  autounfold with IRMC;\n  rewrite Cos_inv;\n  rewrite Sin_inv; ring.\nQed.  \n  \nLemma rotateAxisInvertibleIR :\nforall (p : Cart2D IR) (θ:IR),\n(rotateAxis (-θ)) ((rotateAxis θ) p) = p.\nProof using.\n  intros ? ?. rewrite rotateAxisInvSimpl.\n  unfold rotateAxis, inprod, InProductCart2D.\n  split; simpl;\n  autounfold with IRMC;\n  ring_simplify.\n  - setoid_rewrite <- (mult_1_r (X p)) at 3.\n    rewrite <- (FFT θ).\n    simpl. IRring.\n  - setoid_rewrite <- (mult_1_r (Y p)) at 3.\n    rewrite <- (FFT θ).\n    simpl. IRring.\nQed.\n\nLemma nflipAsTranspose  `{Ring R} : forall (p : Cart2D R),\n  nflip p = negY * transpose p.\nProof using.\n  intros ?.\n  split; simpl.\n  - symmetry. apply mult_1_l.\n  - rewrite <- negate_mult_distr_l.\n    rewrite mult_1_l. reflexivity.\nQed.\n\nLemma nflipNegY `{Ring R} : forall (p : Cart2D R),\n  nflip (negY * p) =  - transpose p.\nProof using.\n  intros ?.\n  split; simpl.\n  - rewrite <- negate_mult_distr_l.\n    rewrite mult_1_l. reflexivity.\n  - symmetry. rewrite mult_1_l. reflexivity.\nQed.\n\n\nLemma multDotLeft `{Ring A}:\n  ∀ (a:A) (b c : Cart2D A), a * (⟨ b, c ⟩) = ⟨ ' a * b, c ⟩.\nProof using.\n  intros. unfold inprod, InProductCart2D.\n  simpl.\n  do 2 rewrite <- (@simple_associativity _ _ mult _ _).\n  rewrite <- plus_mult_distr_l.\n  reflexivity.\nQed.\n\nLemma  QNormSqrPosX : forall (q : Cart2D Q),\n  0 < X q\n  -> 0 < normSqr q.\nProof using.\n  intros ? Hlt. unfold normSqr.\n  pose proof Qpower.Qsqr_nonneg (Y q) as H1.\n  simpl in H1.\n  pose proof (@Q.Qmult_lt_0_compat _ _  Hlt Hlt).\n  autounfold with QMC.\n  lra.\nQed.\n\nLemma  QNormSqrPosY : forall (q : Cart2D Q),\n  0 < Y q\n  -> 0 < normSqr q.\nProof using.\n  intros ? Hlt. unfold normSqr.\n  pose proof Qpower.Qsqr_nonneg (X q) as H1.\n  simpl in H1.\n  pose proof (@Q.Qmult_lt_0_compat _ _  Hlt Hlt).\n  autounfold with QMC.\n  lra.\nQed.\n\n\nDefinition totalSpaceX (c : ConfineRect IR) :IR :=\n  X (maxxy c) - X (minxy c).\n\nRequire Import MathClasses.interfaces.functors.\n\n(* pointwise Norm *)\nDefinition pNorm `{NormSpace A A} (r: Rigid2DState A) :=\n  sfmap CanonicalNotations.norm r.\n \n\n", "meta": {"author": "aa755", "repo": "ROSCoq", "sha": "bb71cdf642fce1ab2f129c833db7a6c358965313", "save_path": "github-repos/coq/aa755-ROSCoq", "path": "github-repos/coq/aa755-ROSCoq/ROSCoq-bb71cdf642fce1ab2f129c833db7a6c358965313/src/geometry2DProps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6780664208883475}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Crypto.Util.ZRange.\nRequire Import Crypto.Util.ZRange.Operations.\nRequire Import Crypto.Util.ZRange.BasicLemmas.\nRequire Import Crypto.Util.ZRange.CornersMonotoneBounds.\nRequire Import Crypto.Util.ZRange.LandLorBounds.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Morphisms.\nRequire Import Crypto.Util.ZUtil.CC.\nRequire Import Crypto.Util.Notations.\n\nModule ZRange.\n  Local Ltac t :=\n    lazymatch goal with\n    | [ |- is_bounded_by_bool (?f _) (ZRange.two_corners ?f _) = true ]\n      => apply (@ZRange.monotoneb_two_corners_gen f)\n    | [ |- is_bounded_by_bool (?f _ _) (ZRange.four_corners ?f _ _) = true ]\n      => apply (@ZRange.monotoneb_four_corners_gen f)\n    | [ |- is_bounded_by_bool (?f _ _) (ZRange.four_corners_and_zero ?f _ _) = true ]\n      => apply (@ZRange.monotoneb_four_corners_and_zero_gen f)\n    end;\n    eauto with zarith;\n    repeat match goal with\n           | [ |- forall x : Z, _ ] => let x := fresh \"x\" in intro x; destruct x\n           end;\n    eauto with zarith.\n\n  Lemma is_bounded_by_bool_log2\n        x x_bs\n        (Hboundedx : is_bounded_by_bool x x_bs = true)\n  : is_bounded_by_bool (Z.log2 x) (ZRange.log2 x_bs) = true.\n  Proof. t. Qed.\n\n  Lemma is_bounded_by_bool_log2_up\n        x x_bs\n        (Hboundedx : is_bounded_by_bool x x_bs = true)\n  : is_bounded_by_bool (Z.log2_up x) (ZRange.log2_up x_bs) = true.\n  Proof. t. Qed.\n\n  Lemma is_bounded_by_bool_add\n        x x_bs y y_bs\n        (Hboundedx : is_bounded_by_bool x x_bs = true)\n        (Hboundedy : is_bounded_by_bool y y_bs = true)\n  : is_bounded_by_bool (Z.add x y) (ZRange.add x_bs y_bs) = true.\n  Proof. t. Qed.\n\n  Lemma is_bounded_by_bool_sub\n        x x_bs y y_bs\n        (Hboundedx : is_bounded_by_bool x x_bs = true)\n        (Hboundedy : is_bounded_by_bool y y_bs = true)\n  : is_bounded_by_bool (Z.sub x y) (ZRange.sub x_bs y_bs) = true.\n  Proof. t. Qed.\n\n  Lemma is_bounded_by_bool_mul\n        x x_bs y y_bs\n        (Hboundedx : is_bounded_by_bool x x_bs = true)\n        (Hboundedy : is_bounded_by_bool y y_bs = true)\n  : is_bounded_by_bool (Z.mul x y) (ZRange.mul x_bs y_bs) = true.\n  Proof. t. Qed.\n\n  Lemma is_bounded_by_bool_div\n        x x_bs y y_bs\n        (Hboundedx : is_bounded_by_bool x x_bs = true)\n        (Hboundedy : is_bounded_by_bool y y_bs = true)\n  : is_bounded_by_bool (Z.div x y) (ZRange.div x_bs y_bs) = true.\n  Proof. t. Qed.\n\n  Lemma is_bounded_by_bool_shiftr\n        x x_bs y y_bs\n        (Hboundedx : is_bounded_by_bool x x_bs = true)\n        (Hboundedy : is_bounded_by_bool y y_bs = true)\n  : is_bounded_by_bool (Z.shiftr x y) (ZRange.shiftr x_bs y_bs) = true.\n  Proof. t. Qed.\n\n  Lemma is_bounded_by_bool_shiftl\n        x x_bs y y_bs\n        (Hboundedx : is_bounded_by_bool x x_bs = true)\n        (Hboundedy : is_bounded_by_bool y y_bs = true)\n  : is_bounded_by_bool (Z.shiftl x y) (ZRange.shiftl x_bs y_bs) = true.\n  Proof. t. Qed.\n\n  Lemma is_bounded_by_bool_cc_m\n        s x x_bs\n        (Hboundedx : is_bounded_by_bool x x_bs = true)\n  : is_bounded_by_bool (Z.cc_m s x) (ZRange.cc_m s x_bs) = true.\n  Proof. t. Qed.\n\n  Lemma is_bounded_by_bool_land\n        x x_bs y y_bs\n        (Hboundedx : is_bounded_by_bool x x_bs = true)\n        (Hboundedy : is_bounded_by_bool y y_bs = true)\n  : is_bounded_by_bool (Z.land x y) (ZRange.land x_bs y_bs) = true.\n  Proof. now apply ZRange.is_bounded_by_bool_land_bounds. Qed.\n\n  Lemma is_bounded_by_bool_lor\n        x x_bs y y_bs\n        (Hboundedx : is_bounded_by_bool x x_bs = true)\n        (Hboundedy : is_bounded_by_bool y y_bs = true)\n  : is_bounded_by_bool (Z.lor x y) (ZRange.lor x_bs y_bs) = true.\n  Proof. now apply ZRange.is_bounded_by_bool_lor_bounds. Qed.\nEnd ZRange.\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/ZRange/OperationsBounds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894548800271, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6780664123839886}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import bigop ssralg poly polydiv.\n\n(******************************************************************************)\n(*   A proof that algebraically closed field enjoy quantifier elimination,    *)\n(*   as described in                                                          *)\n(*   ``A formal quantifier elimination for algebraically closed fields'',     *)\n(*    proceedings of Calculemus 2010, by Cyril Cohen and Assia Mahboubi       *)\n(*                                                                            *)\n(* This file constructs an instance of quantifier elimination mixin,          *)\n(* (see the ssralg library) from the theory of polynomials with coefficients  *)\n(* is an algebraically closed field (see the polydiv library).                *)\n(*                                                                            *)\n(* This file hence deals with the transformation of formulae part, which we   *)\n(* address by implementing one CPS style formula transformer per effective    *)\n(* operation involved in the proof of quantifier elimination. See the paper   *)\n(* for more details.                                                          *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.\nLocal Open Scope ring_scope.\n\nImport Pdiv.Ring.\nImport PreClosedField.\n\nSection ClosedFieldQE.\n\nVariable F : Field.type.\n\nVariable axiom : ClosedField.axiom F.\n\nNotation fF := (formula F).\nNotation qf f := (qf_form f && rformula f).\n\nDefinition polyF := seq (term F).\n\nFixpoint eval_poly (e : seq F) pf := \n  if pf is c::q then (eval_poly e q)*'X + (eval e c)%:P else 0.\n\nDefinition rpoly (p : polyF) := all (@rterm F) p.\n\nFixpoint sizeT (k : nat -> fF) (p : polyF) :=\n  if p is c::q then \n    sizeT (fun n => \n      if n is m.+1 then k m.+2 else \n        GRing.If (c == 0) (k 0%N) (k 1%N)) q \n   else k O%N.\n\n\nLemma sizeTP (k : nat -> formula F) (pf : polyF) (e : seq F) : \n  qf_eval e (sizeT k pf) = qf_eval e (k (size (eval_poly e pf))).\nProof.\nelim: pf e k; first by move=> *; rewrite size_poly0.\nmove=> c qf Pqf e k; rewrite Pqf.\nrewrite size_MXaddC -(size_poly_eq0 (eval_poly _ _)).\nby case: (size (eval_poly e qf))=> //=; case: eqP; rewrite // orbF.\nQed.\n\nLemma sizeT_qf (k : nat -> formula F) (p : polyF) : \n  (forall n, qf (k n)) -> rpoly p -> qf (sizeT k p).\nProof.\nelim: p k => /= [|c q ihp] k kP rp; first exact: kP.\ncase/andP: rp=> rc rq.\napply: ihp; rewrite ?rq //; case=> [|n]; last exact: kP.\nhave [/andP[qf0 rf0] /andP[qf1 rf1]] := (kP 0, kP 1)%N.\nby rewrite If_form_qf ?If_form_rf //= andbT.\nQed.\n\nDefinition isnull (k : bool -> fF) (p : polyF) :=\n  sizeT (fun n => k (n == 0%N)) p.\n\nLemma isnullP (k : bool -> formula F) (p : polyF) (e : seq F) :\n  qf_eval e (isnull k p) = qf_eval e (k (eval_poly e p == 0)).\nProof. by rewrite sizeTP size_poly_eq0. Qed.\n\nLemma isnull_qf (k : bool -> formula F) (p : polyF) :\n  (forall b, qf (k b)) -> rpoly p -> qf (isnull k p).\nProof. by move=> *; apply: sizeT_qf. Qed.\n\nDefinition lt_sizeT (k : bool -> fF) (p q : polyF) : fF :=\n  sizeT (fun n => sizeT (fun m => k (n<m)) q) p.\n\nDefinition lift (p : {poly F}) := let: q := p in map Const q.\n\nLemma eval_lift (e : seq F) (p : {poly F}) : eval_poly e (lift p) = p.\nProof.\nelim/poly_ind: p => [|p c]; first by rewrite /lift polyseq0.\nrewrite -cons_poly_def /lift polyseq_cons /nilp.\ncase pn0: (_ == _) => /=; last by move->; rewrite -cons_poly_def.\nmove=> _; rewrite polyseqC.\ncase c0: (_==_)=> /=.\n  move: pn0; rewrite (eqP c0) size_poly_eq0; move/eqP->. \n  by apply:val_inj=> /=; rewrite polyseq_cons // polyseq0.\nby rewrite mul0r add0r; apply:val_inj=> /=; rewrite polyseq_cons // /nilp pn0.\nQed.\n\nFixpoint lead_coefT (k : term F -> fF) p :=  \n  if p is c::q then \n    lead_coefT (fun l => GRing.If (l == 0) (k c) (k l)) q \n  else k (Const 0).\n\nLemma lead_coefTP (k : term F -> formula F) :\n (forall x e, qf_eval e (k x) = qf_eval e (k (Const (eval e x)))) ->\n  forall (p : polyF) (e : seq F),\n  qf_eval e (lead_coefT k p) = qf_eval e (k (Const (lead_coef (eval_poly e p)))).\nProof.\nmove=> Pk p e; elim: p k Pk => /= [*|a p' Pp' k Pk]; first by rewrite lead_coef0.\nrewrite Pp'; last by move=> *; rewrite //= -Pk.\nrewrite GRing.eval_If /= lead_coef_eq0.\ncase p'0: (_ == _); first by rewrite (eqP p'0) mul0r add0r lead_coefC -Pk.\nrewrite lead_coefDl ?lead_coefMX // polyseqC size_mul ?p'0 //; last first.\n  by rewrite -size_poly_eq0 size_polyX.\nrewrite size_polyX addnC /=; case: (_ == _)=> //=.\nby rewrite ltnS lt0n size_poly_eq0 p'0.\nQed.\n\nLemma lead_coefT_qf (k : term F -> formula F) (p : polyF) :\n (forall c, rterm c -> qf (k c)) -> rpoly p -> qf (lead_coefT k p).\nProof.\nelim: p k => /= [|c q ihp] k kP rp; first exact: kP.\nmove: rp; case/andP=> rc rq; apply: ihp; rewrite ?rq // => l rl.\nhave [/andP[qfc rfc] /andP[qfl rfl]] := (kP c rc, kP l rl).\nby rewrite If_form_qf ?If_form_rf //= andbT.\nQed.\n\nFixpoint amulXnT (a : term F) (n : nat) : polyF :=\n  if n is n'.+1 then (Const 0) :: (amulXnT a n') else [::a].\n\nLemma eval_amulXnT  (a : term F) (n : nat) (e : seq F) :\n  eval_poly e (amulXnT a n) = (eval e a)%:P * 'X^n.\nProof.\nelim: n=> [|n] /=; first by rewrite expr0 mulr1 mul0r add0r.\nby move->; rewrite addr0 -mulrA -exprSr.\nQed.\n\nLemma ramulXnT: forall a n, rterm a -> rpoly (amulXnT a n).\nProof. by move=> a n; elim: n a=> [a /= -> //|n ihn a ra]; apply: ihn. Qed.\n\nFixpoint sumpT (p q : polyF) :=\n  if p is a::p' then\n    if q is b::q' then (Add a b)::(sumpT p' q')\n      else p\n    else q.\n\nLemma eval_sumpT (p q : polyF) (e : seq F) :\n  eval_poly e (sumpT p q) = (eval_poly e p) + (eval_poly e q).\nProof.\nelim: p q => [|a p Hp] q /=; first by rewrite add0r.\ncase: q => [|b q] /=; first by rewrite addr0.\nrewrite Hp mulrDl -!addrA; congr (_+_); rewrite polyC_add addrC -addrA.\nby congr (_+_); rewrite addrC.\nQed.\n\nLemma rsumpT (p q : polyF) : rpoly p -> rpoly q -> rpoly (sumpT p q).\nProof.\nelim: p q=> [|a p ihp] q rp rq //; move: rp; case/andP=> ra rp.\ncase: q rq => [|b q]; rewrite /= ?ra ?rp //=.\nby case/andP=> -> rq //=; apply: ihp.\nQed.\n\nFixpoint mulpT (p q : polyF) :=\n  if p is a :: p' then sumpT (map (Mul a) q) (Const 0::(mulpT p' q)) else [::].\n\nLemma eval_mulpT (p q : polyF) (e : seq F) :\n  eval_poly e (mulpT p q) = (eval_poly e p) * (eval_poly e q).\nProof.\nelim: p q=> [|a p Hp] q /=; first by rewrite mul0r.\nrewrite eval_sumpT /= Hp addr0 mulrDl addrC mulrAC; congr (_+_).\nelim: q=> [|b q Hq] /=; first by rewrite mulr0.\nby rewrite Hq polyC_mul mulrDr mulrA.\nQed.\n\nLemma rpoly_map_mul (t : term F) (p : polyF) (rt : rterm t) : \n  rpoly (map (Mul t) p) = rpoly p.\nProof. \nby rewrite /rpoly all_map /= (@eq_all _ _ (@rterm _)) // => x; rewrite /= rt.\nQed.\n\nLemma rmulpT (p q : polyF) : rpoly p -> rpoly q -> rpoly (mulpT p q). \nProof.\nelim: p q=> [|a p ihp] q rp rq //=; move: rp; case/andP=> ra rp /=.\napply: rsumpT; last exact: ihp.\nby rewrite rpoly_map_mul.\nQed.\n\nDefinition opppT := map (Mul (@Const F (-1))).\n\nLemma eval_opppT (p : polyF) (e : seq F) : \n eval_poly e (opppT p) = - eval_poly e p.\nProof.\nby elim: p; rewrite /= ?oppr0 // => ? ? ->; rewrite !mulNr opprD polyC_opp mul1r.\nQed.\n\nDefinition natmulpT n := map (Mul (@NatConst F n)).\n\nLemma eval_natmulpT  (p : polyF) (n : nat) (e : seq F) :\n  eval_poly e (natmulpT n p) = (eval_poly e p) *+ n.\nProof.\nelim: p; rewrite //= ?mul0rn // => c p ->.\nrewrite mulrnDl mulr_natl polyC_muln; congr (_+_). \nby rewrite -mulr_natl mulrAC -mulrA mulr_natl mulrC.\nQed.\n\nFixpoint redivp_rec_loopT (q : polyF) sq cq (k : nat * polyF * polyF -> fF)\n  (c : nat) (qq r : polyF) (n : nat) {struct n}:=\n  sizeT (fun sr => \n    if sr < sq then k (c, qq, r) else \n      lead_coefT (fun lr =>\n        let m := amulXnT lr (sr - sq) in\n        let qq1 := sumpT (mulpT qq [::cq]) m in\n        let r1 := sumpT (mulpT r ([::cq])) (opppT (mulpT m q)) in\n        if n is n1.+1 then redivp_rec_loopT q sq cq k c.+1 qq1 r1 n1\n        else k (c.+1, qq1, r1)\n      ) r\n  ) r.\n  \nFixpoint redivp_rec_loop (q : {poly F}) sq cq \n   (k : nat) (qq r : {poly F})(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 redivp_rec_loop q sq cq k.+1 qq1 r1 n1 else\n        (k.+1, qq1, r1).\n\nLemma redivp_rec_loopTP (k : nat * polyF * polyF -> formula F) : \n  (forall c qq r e,  qf_eval e (k (c,qq,r)) \n    = qf_eval e (k (c, lift (eval_poly e qq), lift (eval_poly e r))))\n  -> forall q sq cq c qq r n e \n    (d := redivp_rec_loop (eval_poly e q) sq (eval e cq)\n      c (eval_poly e qq) (eval_poly e r) n),\n    qf_eval e (redivp_rec_loopT q sq cq k c qq r n) \n    = qf_eval e (k (d.1.1, lift d.1.2, lift d.2)).\nProof.\nmove=> Pk q sq cq c qq r n e /=.\nelim: n c qq r k Pk e => [|n Pn] c qq r k Pk e; rewrite sizeTP.\n  case ltrq : (_ < _); first by rewrite /= ltrq /= -Pk.\n  rewrite lead_coefTP => [|a p]; rewrite Pk.\n    rewrite ?(eval_mulpT,eval_amulXnT,eval_sumpT,eval_opppT) //=. \n    by rewrite ltrq //= mul_polyC ?(mul0r,add0r).\n  by symmetry; rewrite Pk ?(eval_mulpT,eval_amulXnT,eval_sumpT, eval_opppT).\ncase ltrq : (_<_); first by rewrite /= ltrq Pk.\nrewrite lead_coefTP.\n  rewrite Pn ?(eval_mulpT,eval_amulXnT,eval_sumpT,eval_opppT) //=. \n  by rewrite ltrq //= mul_polyC ?(mul0r,add0r).\nrewrite -/redivp_rec_loopT => x e'.\nrewrite Pn; last by move=>*; rewrite Pk. \nsymmetry; rewrite Pn; last by move=>*; rewrite Pk.\nrewrite Pk ?(eval_lift,eval_mulpT,eval_amulXnT,eval_sumpT,eval_opppT).\nby rewrite mul_polyC ?(mul0r,add0r).\nQed.\n\nLemma redivp_rec_loopT_qf (q : polyF) (sq : nat) (cq : term F)\n (k : nat * polyF * polyF -> formula F) (c : nat) (qq r : polyF) (n : nat) :\n  (forall r, [&& rpoly r.1.2 & rpoly r.2] -> qf (k r)) ->\n  rpoly q -> rterm cq -> rpoly qq -> rpoly r ->\n    qf (redivp_rec_loopT q sq cq k c qq r n).\nProof.\nelim: n q sq cq k c qq r => [|n ihn] q sq cq k c qq r kP rq rcq rqq rr.\n  apply: sizeT_qf=> // n; case: (_ < _); first by apply: kP; rewrite // rqq rr.\n  apply: lead_coefT_qf=> // l rl; apply: kP. \n  by rewrite /= ?(rsumpT,rmulpT,ramulXnT,rpoly_map_mul) //= rcq.\napply: sizeT_qf=> // m; case: (_ < _); first by apply: kP => //=; rewrite rqq rr.\napply: lead_coefT_qf=> // l rl; apply: ihn; rewrite //= ?rcq //.\n  by rewrite ?(rsumpT,rmulpT,ramulXnT,rpoly_map_mul) //= rcq.\nby rewrite ?(rsumpT,rmulpT,ramulXnT,rpoly_map_mul) //= rcq.\nQed.\n\nDefinition redivpT (p : polyF) (k : nat * polyF * polyF -> fF) \n                   (q : polyF) : fF :=\n  isnull (fun b =>\n    if b then k (0%N, [::Const 0], p) else\n      sizeT (fun sq =>\n        sizeT (fun sp =>\n          lead_coefT (fun lq =>\n            redivp_rec_loopT q sq lq k 0 [::Const 0] p sp\n          ) q\n        ) p\n      ) q\n  ) q.\n\nLemma redivp_rec_loopP  (q : {poly F}) (c : nat) (qq r : {poly F}) (n : nat) :\n  redivp_rec q c qq r n = redivp_rec_loop q (size q) (lead_coef q) c qq r n.\nProof. by elim: n c qq r => [| n Pn] c qq r //=; rewrite Pn. Qed. \n\nLemma redivpTP (k : nat * polyF * polyF -> formula F) :\n  (forall c qq r e,  \n     qf_eval e (k (c,qq,r)) = \n     qf_eval e (k (c, lift (eval_poly e qq), lift (eval_poly e r)))) ->\n  forall p q e (d := redivp (eval_poly e p) (eval_poly e q)),\n    qf_eval e (redivpT p k q) = qf_eval e (k (d.1.1, lift d.1.2, lift d.2)).\nProof.\nmove=> Pk p q e /=; rewrite isnullP unlock.\ncase q0 : (_ == _); first by rewrite Pk /= mul0r add0r polyC0.\nrewrite !sizeTP lead_coefTP /=; last by move=> *; rewrite !redivp_rec_loopTP.\nrewrite redivp_rec_loopTP /=; last by move=> *; rewrite Pk.\nby rewrite mul0r add0r polyC0 redivp_rec_loopP.\nQed.\n\nLemma redivpT_qf (p : polyF) (k : nat * polyF * polyF -> formula F) (q : polyF) :\n  (forall r, [&& rpoly r.1.2 & rpoly r.2] -> qf (k r)) ->\n   rpoly p -> rpoly q -> qf (redivpT p k q).\nProof.\nmove=> kP rp rq; rewrite /redivpT; apply: isnull_qf=> // [[]]; first exact: kP.\napply: sizeT_qf => // sq; apply: sizeT_qf=> // sp.\nby apply: lead_coefT_qf=> // lq rlq; apply: redivp_rec_loopT_qf.\nQed.\n\nDefinition rmodpT (p : polyF) (k : polyF -> fF) (q : polyF) : fF :=\n  redivpT p (fun d => k d.2) q.\nDefinition rdivpT (p : polyF) (k:polyF -> fF) (q : polyF) : fF :=\n  redivpT p (fun d => k d.1.2) q.\nDefinition rscalpT (p : polyF) (k: nat -> fF) (q : polyF) : fF :=\n  redivpT p (fun d => k d.1.1) q.\nDefinition rdvdpT (p : polyF) (k:bool -> fF) (q : polyF) : fF :=\n  rmodpT p (isnull k) q.\n\nFixpoint rgcdp_loop n (pp qq : {poly F}) {struct n} :=\n  if rmodp pp qq == 0 then qq \n    else if n is n1.+1 then rgcdp_loop n1 qq (rmodp pp qq)\n         else rmodp pp qq.\n\nFixpoint rgcdp_loopT (pp : polyF) (k : polyF -> formula F) n (qq : polyF) :=\n  rmodpT pp (isnull \n    (fun b => if b then (k qq) \n              else (if n is n1.+1 \n                    then rmodpT pp (rgcdp_loopT qq k n1) qq \n                    else rmodpT pp k qq)\n    )\n            ) qq.\n\nLemma rgcdp_loopP (k : polyF -> formula F) :\n  (forall p e, qf_eval e (k p) = qf_eval e (k (lift (eval_poly e p)))) ->\n  forall n p q e, \n    qf_eval e (rgcdp_loopT p k n q) = \n    qf_eval e (k (lift (rgcdp_loop n (eval_poly e p) (eval_poly e q)))).\nProof.\nmove=> Pk n p q e.\nelim: n p q e => /= [| m Pm] p q e.\n  rewrite redivpTP; last by move=>*; rewrite !isnullP eval_lift.\n  rewrite isnullP eval_lift; case: (_ == 0); first by rewrite Pk.\n  by rewrite redivpTP; last by move=>*; rewrite Pk.\nrewrite redivpTP; last by move=>*; rewrite !isnullP eval_lift.\nrewrite isnullP eval_lift; case: (_ == 0); first by rewrite Pk.\nby rewrite redivpTP; move=>*; rewrite ?Pm !eval_lift.\nQed.\n\nLemma rgcdp_loopT_qf (p : polyF) (k : polyF -> formula F) (q : polyF) (n : nat) :\n  (forall r, rpoly r -> qf (k r)) -> \n  rpoly p -> rpoly q -> qf (rgcdp_loopT p k n q).\nelim: n p k q => [|n ihn] p k q kP rp rq.\n  apply: redivpT_qf=> // r; case/andP=> _ rr.\n  apply: isnull_qf=> // [[]]; first exact: kP.\n  by apply: redivpT_qf=> // r'; case/andP=> _ rr'; apply: kP.\napply: redivpT_qf=> // r; case/andP=> _ rr.\napply: isnull_qf=> // [[]]; first exact: kP.\nby apply: redivpT_qf=> // r'; case/andP=> _ rr'; apply: ihn.\nQed.\n   \nDefinition rgcdpT (p : polyF) k (q : polyF) : fF :=\n  let aux p1 k q1 := isnull \n    (fun b => if b \n      then (k q1) \n      else (sizeT (fun n => (rgcdp_loopT p1 k n q1)) p1)) p1\n    in (lt_sizeT (fun b => if b then (aux q k p) else (aux p k q)) p q). \n\nLemma rgcdpTP (k : seq (term F) -> formula F) :\n  (forall p e, qf_eval e (k p) = qf_eval e (k (lift (eval_poly e p)))) ->\n   forall p q e, qf_eval e (rgcdpT p k q) = \n                 qf_eval e (k (lift (rgcdp (eval_poly e p) (eval_poly e q)))).\nProof.\nmove=> Pk p q e; rewrite /rgcdpT !sizeTP; case lqp: (_ < _).  \n  rewrite isnullP; case q0: (_ == _); first by rewrite Pk (eqP q0) rgcdp0.\n  rewrite sizeTP rgcdp_loopP => [|e' p']; last by rewrite Pk. \n  by rewrite /rgcdp lqp q0.\nrewrite isnullP; case p0: (_ == _); first by rewrite Pk (eqP p0) rgcd0p.\nrewrite sizeTP rgcdp_loopP => [|e' p']; last by rewrite Pk.\nby rewrite /rgcdp lqp p0.\nQed.\n\nLemma rgcdpT_qf  (p : polyF) (k : polyF -> formula F) (q : polyF) :\n  (forall r, rpoly r -> qf (k r)) -> rpoly p -> rpoly q -> qf (rgcdpT p k q).\nProof.\nmove=> kP rp rq; apply: sizeT_qf=> // n; apply: sizeT_qf=> // m.\nby case:(_ < _); \n   apply: isnull_qf=> //; case; do ?apply: kP=> //;\n   apply: sizeT_qf=> // n'; apply: rgcdp_loopT_qf.\nQed.\n\nFixpoint rgcdpTs k (ps : seq polyF) : fF :=\n  if ps is p::pr then rgcdpTs (rgcdpT p k) pr else k [::Const 0].\n\nLemma rgcdpTsP (k : polyF -> formula F) : \n  (forall p e, qf_eval e (k p) = qf_eval e (k (lift (eval_poly e p)))) ->\n  forall ps e, \n    qf_eval e (rgcdpTs k ps) = \n    qf_eval e (k (lift (\\big[@rgcdp _/0%:P]_(i <- ps)(eval_poly e i)))).\nProof.\nmove=> Pk ps e.\nelim: ps k Pk; first by move=> p Pk; rewrite /= big_nil Pk /= mul0r add0r.\nmove=> p ps Pps /= k Pk /=; rewrite big_cons Pps => [|p' e'].\n  by rewrite rgcdpTP // eval_lift.\nby rewrite !rgcdpTP // Pk !eval_lift .\nQed.\n\nDefinition rseq_poly ps := all rpoly ps.\n\nLemma rgcdpTs_qf (k : polyF -> formula F) (ps : seq polyF) :\n  (forall r, rpoly r -> qf (k r)) -> rseq_poly ps -> qf (rgcdpTs k ps).\nProof.\nelim: ps k=> [|c p ihp] k kP rps=> /=; first exact: kP.\nby move: rps; case/andP=> rc rp; apply: ihp=> // r rr; apply: rgcdpT_qf.\nQed.\n\nFixpoint rgdcop_recT (q : polyF) k  (p : polyF) n :=\n  if n is m.+1 then\n    rgcdpT p (sizeT (fun sd =>\n      if sd == 1%N then k p\n      else rgcdpT p (rdivpT p (fun r => rgdcop_recT q k r m)) q\n    )) q\n  else isnull (fun b => k [::Const b%:R]) q.\n\n\nLemma rgdcop_recTP (k : polyF -> formula F) : \n  (forall p e, qf_eval e (k p) = qf_eval e (k (lift (eval_poly e p))))\n  -> forall p q n e, qf_eval e (rgdcop_recT p k q n) \n    = qf_eval e (k (lift (rgdcop_rec (eval_poly e p) (eval_poly e q) n))).\nProof.\nmove=> Pk p q n e.\nelim: n k Pk p q e => [|n Pn] k Pk p q e /=.\n  rewrite isnullP /=.\n  by case: (_ == _); rewrite Pk /= mul0r add0r ?(polyC0, polyC1).\nrewrite rgcdpTP ?sizeTP ?eval_lift //.\n  rewrite /rcoprimep; case se : (_==_); rewrite Pk //.\n  do ?[rewrite (rgcdpTP,Pn,eval_lift,redivpTP) | move=> * //=].\nby do ?[rewrite (sizeTP,eval_lift) | move=> * //=].\nQed.\n\nLemma rgdcop_recT_qf (p : polyF) (k : polyF -> formula F) (q : polyF) (n : nat) :\n (forall r, rpoly r -> qf (k r)) -> \n rpoly p -> rpoly q -> qf (rgdcop_recT p k q n).\nProof.\nelim: n p k q => [|n ihn] p k q kP rp rq /=.\napply: isnull_qf=> //; first by case; rewrite kP.\napply: rgcdpT_qf=> // g rg; apply: sizeT_qf=> // n'.\ncase: (_ == _); first exact: kP.\napply: rgcdpT_qf=> // g' rg'; apply: redivpT_qf=> // r; case/andP=> rr _.\nexact: ihn.\nQed.\n\nDefinition rgdcopT q k p := sizeT (rgdcop_recT q k p) p.\n\nLemma rgdcopTP (k : polyF -> formula F) : \n  (forall p e, qf_eval e (k p) = qf_eval e (k (lift (eval_poly e p)))) ->\n  forall p q e, qf_eval e (rgdcopT p k q) =\n                qf_eval e (k (lift (rgdcop (eval_poly e p) (eval_poly e q)))).\nProof. by move=> *; rewrite sizeTP rgdcop_recTP 1?Pk. Qed.\n\nLemma rgdcopT_qf (p : polyF) (k : polyF -> formula F) (q : polyF) :\n  (forall r, rpoly r -> qf (k r)) -> rpoly p -> rpoly q -> qf (rgdcopT p k q).\nProof. \nby move=> kP rp rq; apply: sizeT_qf => // n; apply: rgdcop_recT_qf.\nQed.\n\n\nDefinition ex_elim_seq (ps : seq polyF) (q : polyF) :=\n  (rgcdpTs (rgdcopT q (sizeT (fun n => Bool (n != 1%N)))) ps).\n\nLemma ex_elim_seqP (ps : seq polyF) (q : polyF) (e : seq F) :\n  let gp := (\\big[@rgcdp _/0%:P]_(p <- ps)(eval_poly e p)) in\n  qf_eval e (ex_elim_seq ps q) = (size (rgdcop (eval_poly e q) gp) != 1%N).\nProof.\nby do ![rewrite (rgcdpTsP,rgdcopTP,sizeTP,eval_lift) //= | move=> * //=].\nQed.\n\nLemma ex_elim_seq_qf  (ps : seq polyF) (q : polyF) :\n  rseq_poly ps -> rpoly q -> qf (ex_elim_seq ps q).\nProof.\nmove=> rps rq; apply: rgcdpTs_qf=> // g rg; apply: rgdcopT_qf=> // d rd.\nexact : sizeT_qf.\nQed.\n\nFixpoint abstrX (i : nat) (t : term F) :=\n  match t with\n    | (Var n) => if n == i then [::Const 0; Const 1] else [::t]\n    | (Opp x) => opppT (abstrX i x)\n    | (Add x y) => sumpT (abstrX i x) (abstrX i y)\n    | (Mul x y) => mulpT (abstrX i x) (abstrX i y)\n    | (NatMul x n) => natmulpT n (abstrX i x)\n    | (Exp x n) => let ax := (abstrX i x) in\n      iter n (mulpT ax) [::Const 1]\n    | _ => [::t]\n  end.\n\nLemma abstrXP  (i : nat) (t : term F) (e : seq F) (x : F) :\n  rterm t -> (eval_poly e (abstrX i t)).[x] = eval (set_nth 0 e i x) t.\nProof.\nelim: t => [n | r | n | t tP s sP | t tP | t tP n | t tP s sP | t tP | t tP n] h.\n- move=> /=; case ni: (_ == _); \n    rewrite //= ?(mul0r,add0r,addr0,polyC1,mul1r,hornerX,hornerC);\n    by rewrite // nth_set_nth /= ni.\n- by rewrite /= mul0r add0r hornerC.\n- by rewrite /= mul0r add0r hornerC.\n- by case/andP: h => *; rewrite /= eval_sumpT hornerD tP ?sP. \n- by rewrite /= eval_opppT hornerN tP.\n- by rewrite /= eval_natmulpT hornerMn tP.\n- by case/andP: h => *; rewrite /= eval_mulpT hornerM tP ?sP.\n- by []. \n- elim: n h => [|n ihn] rt; first by rewrite /= expr0 mul0r add0r hornerC.\n  by rewrite /= eval_mulpT exprSr hornerM ihn // mulrC tP.\nQed.\n\nLemma rabstrX (i : nat) (t : term F) : rterm t -> rpoly (abstrX i t).\nProof.\nelim: t; do ?[ by move=> * //=; do ?case: (_ == _)].\n- move=> t irt s irs /=; case/andP=> rt rs.\n  by apply: rsumpT; rewrite ?irt ?irs //.\n- by move=> t irt /= rt; rewrite rpoly_map_mul ?irt //.\n- by move=> t irt /= n rt; rewrite rpoly_map_mul ?irt //.\n- move=> t irt s irs /=; case/andP=> rt rs.\n  by apply: rmulpT; rewrite ?irt ?irs //.\n- move=> t irt /= n rt; move: (irt rt)=> {rt} rt; elim: n => [|n ihn] //=.\n  exact: rmulpT.\nQed.\n\nImplicit Types tx ty : term F.\n\nLemma abstrX_mulM (i : nat) : {morph abstrX i : x y / Mul x y >-> mulpT x y}.\nProof. done. Qed.\n\nLemma abstrX1 (i : nat) : abstrX i (Const 1) = [::Const 1].\nProof. done. Qed.\n\nLemma eval_poly_mulM e : {morph eval_poly e : x y / mulpT x y >-> mul x y}.\nProof. by move=> x y; rewrite eval_mulpT. Qed.\n\nLemma eval_poly1 e : eval_poly e [::Const 1] = 1.\nProof. by rewrite /= mul0r add0r. Qed.\n\nNotation abstrX_bigmul := (big_morph _ (abstrX_mulM _) (abstrX1 _)).\nNotation eval_bigmul := (big_morph _ (eval_poly_mulM _) (eval_poly1 _)).\nNotation bigmap_id := (big_map _ (fun _ => true) id).\n\nLemma rseq_poly_map (x : nat) (ts : seq (term F)) :\n  all (@rterm _) ts ->  rseq_poly (map (abstrX x) ts).\nProof.\nby elim: ts => //= t ts iht; case/andP=> rt rts; rewrite rabstrX // iht.\nQed.\n\nDefinition ex_elim (x : nat) (pqs : seq (term F) * seq (term F)) :=\n  ex_elim_seq (map (abstrX x) pqs.1) \n  (abstrX x (\\big[Mul/Const 1]_(q <- pqs.2) q)).\n \nLemma ex_elim_qf (x : nat) (pqs : seq (term F) * seq (term F)) : \n  dnf_rterm pqs -> qf (ex_elim x pqs).\ncase: pqs => ps qs; case/andP=> /= rps rqs.\napply: ex_elim_seq_qf; first exact: rseq_poly_map.\napply: rabstrX=> /=.\nelim: qs rqs=> [|t ts iht] //=; first by rewrite big_nil.\nby case/andP=> rt rts; rewrite big_cons /= rt /= iht.\nQed.\n\nLemma holds_conj : forall e i x ps, all (@rterm _) ps ->\n  (holds (set_nth 0 e i x) (foldr (fun t : term F => And (t == 0)) True ps)\n  <-> all ((@root _)^~ x) (map (eval_poly e \\o abstrX i) ps)).\nProof.\nmove=> e i x; elim=> [|p ps ihps] //=.\ncase/andP=> rp rps; rewrite rootE abstrXP //.\nconstructor; first by case=> -> hps; rewrite eqxx /=; apply/ihps.\nby case/andP; move/eqP=> -> psr; split=> //; apply/ihps. \nQed.\n\nLemma holds_conjn (e : seq F) (i : nat) (x : F) (ps : seq (term F)) :\n  all (@rterm _) ps ->\n  (holds (set_nth 0 e i x) (foldr (fun t : term F => And (t != 0)) True ps) <-> \n  all (fun p => ~~root p x) (map (eval_poly e \\o abstrX i) ps)).\nProof.\nelim: ps => [|p ps ihps] //=.\ncase/andP=> rp rps; rewrite rootE abstrXP //.\nconstructor; first by case=> /eqP-> hps /=; apply/ihps.\nby case/andP=> pr psr; split; first apply/eqP=> //; apply/ihps. \nQed.\n\nLemma holds_ex_elim : GRing.valid_QE_proj ex_elim.\nProof.\nmove=> i [ps qs] /= e; case/andP=> /= rps rqs.\nrewrite ex_elim_seqP big_map.\nhave -> : \\big[@rgcdp _/0%:P]_(j <- ps) eval_poly e (abstrX i j) =\n          \\big[@rgcdp _/0%:P]_(j <- (map (eval_poly e) (map (abstrX i) (ps)))) j.\n  by rewrite !big_map.\nrewrite -!map_comp.\n  have aux I (l : seq I) (P : I -> {poly F}) :\n    \\big[(@gcdp F)/0]_(j <- l) P j %= \\big[(@rgcdp F)/0]_(j <- l) P j.\n    elim: l => [| u l ihl] /=; first by rewrite !big_nil eqpxx.\n    rewrite !big_cons; move: ihl; move/(eqp_gcdr (P u)) => h.\n    by apply: eqp_trans h _; rewrite eqp_sym; apply: eqp_rgcd_gcd.\ncase g0: (\\big[(@rgcdp F)/0%:P]_(j <- map (eval_poly e \\o abstrX i) ps) j == 0).\n  rewrite (eqP g0) rgdcop0.\n  case m0 : (_ == 0)=> //=; rewrite ?(size_poly1,size_poly0) //=.\n    rewrite abstrX_bigmul eval_bigmul -bigmap_id in m0.\n    constructor=> [[x] // []] //.\n    case=> _; move/holds_conjn=> hc; move/hc:rqs.\n    by rewrite -root_bigmul //= (eqP m0) root0.\n  constructor; move/negP:m0; move/negP=>m0.\n  case: (closed_nonrootP axiom _ m0) => x {m0}.\n  rewrite abstrX_bigmul eval_bigmul -bigmap_id root_bigmul=> m0.\n  exists x; do 2?constructor=> //; last by apply/holds_conjn.\n  apply/holds_conj; rewrite //= -root_biggcd.\n  by rewrite (eqp_root (aux _ _ _ )) (eqP g0) root0.\napply:(iffP (closed_rootP axiom _)); case=> x Px; exists x; move:Px => //=.\n  rewrite (eqp_root (eqp_rgdco_gdco _ _)) root_gdco ?g0 //.\n  rewrite -(eqp_root (aux _ _ _ )) root_biggcd  abstrX_bigmul eval_bigmul.\n  rewrite -bigmap_id root_bigmul; case/andP=> psr qsr.\n  do 2?constructor; first by apply/holds_conj.\n  by apply/holds_conjn.\nrewrite (eqp_root (eqp_rgdco_gdco _ _)) root_gdco ?g0 // -(eqp_root (aux _ _ _)).\nrewrite root_biggcd abstrX_bigmul eval_bigmul -bigmap_id.\nrewrite root_bigmul=> [[] // [hps hqs]]; apply/andP.\nconstructor; first by apply/holds_conj.\nby apply/holds_conjn.\nQed.\n\nLemma wf_ex_elim : GRing.wf_QE_proj ex_elim.\nProof. by move=> i bc /= rbc; apply: ex_elim_qf. Qed.\n\nDefinition closed_fields_QEMixin := \n  QEdecFieldMixin wf_ex_elim holds_ex_elim.\n\nEnd ClosedFieldQE.\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/theories/closed_field.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.67802885417622}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import LambekSyntax.\n\nFixpoint pullMultLeft (X: formula) (x: str) :=\n  match x with\n  | [] => X\n  | X' :: x' => pullMultLeft (X ° X') x'\n  end.\n\nFixpoint pullMultRight (X : formula) (x : str) :=\n  match x with\n  | [] => X\n  | (X'::x') => X ° (pullMultRight X' x')\n  end.\n\nLemma pullMultLeftSplit X x A:\n  pullMultLeft X (x ++ [A]) = pullMultLeft X x ° A.\nProof.\n  generalize dependent X.\n  induction x as [| X' x].\n  - auto.\n  - intros X. simpl.\n    apply (IHx (X ° X')).\nQed.\n", "meta": {"author": "gogabr", "repo": "lambekMikulas", "sha": "12f2cf11fe3e4dc65cf6ba8fb5a331c42198fbd3", "save_path": "github-repos/coq/gogabr-lambekMikulas", "path": "github-repos/coq/gogabr-lambekMikulas/lambekMikulas-12f2cf11fe3e4dc65cf6ba8fb5a331c42198fbd3/src/SyntaxOps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6780288443171402}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *         Copyright INRIA, CNRS and contributors             *)\n(* <O___,, * (see version control and CREDITS file for authors & dates) *)\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 Notations Logic Datatypes.\nRequire Decimal Hexadecimal Number.\nLocal Open Scope nat_scope.\n\n(**********************************************************************)\n(** * Peano natural numbers, definitions of operations *)\n(**********************************************************************)\n\n(** This file is meant to be used as a whole module,\n    without importing it, leading to qualified definitions\n    (e.g. Nat.pred) *)\n\nDefinition t := nat.\n\n(** ** Constants *)\n\nLocal Notation \"0\" := O.\nLocal Notation \"1\" := (S O).\nLocal Notation \"2\" := (S (S O)).\n\nDefinition zero := 0.\nDefinition one := 1.\nDefinition two := 2.\n\n(** ** Basic operations *)\n\nDefinition succ := S.\n\nDefinition pred n :=\n  match n with\n    | 0 => n\n    | S u => u\n  end.\n\nRegister pred as num.nat.pred.\n\nFixpoint add n m :=\n  match n with\n  | 0 => m\n  | S p => S (p + m)\n  end\n\nwhere \"n + m\" := (add n m) : nat_scope.\n\nRegister add as num.nat.add.\n\nDefinition double n := n + n.\n\nFixpoint mul n m :=\n  match n with\n  | 0 => 0\n  | S p => m + p * m\n  end\n\nwhere \"n * m\" := (mul n m) : nat_scope.\n\nRegister mul as num.nat.mul.\n\n(** Truncated subtraction: [n-m] is [0] if [n<=m] *)\n\nFixpoint sub n m :=\n  match n, m with\n  | S k, S l => k - l\n  | _, _ => n\n  end\n\nwhere \"n - m\" := (sub n m) : nat_scope.\n\nRegister sub as num.nat.sub.\n\n(** ** Comparisons *)\n\nFixpoint eqb n m : bool :=\n  match n, m with\n    | 0, 0 => true\n    | 0, S _ => false\n    | S _, 0 => false\n    | S n', S m' => eqb n' m'\n  end.\n\nFixpoint leb n m : bool :=\n  match n, m with\n    | 0, _ => true\n    | _, 0 => false\n    | S n', S m' => leb n' m'\n  end.\n\nDefinition ltb n m := leb (S n) m.\n\nInfix \"=?\" := eqb (at level 70) : nat_scope.\nInfix \"<=?\" := leb (at level 70) : nat_scope.\nInfix \"<?\" := ltb (at level 70) : nat_scope.\n\nFixpoint compare n m : comparison :=\n  match n, m with\n   | 0, 0 => Eq\n   | 0, S _ => Lt\n   | S _, 0 => Gt\n   | S n', S m' => compare n' m'\n  end.\n\nInfix \"?=\" := compare (at level 70) : nat_scope.\n\n(** ** Minimum, maximum *)\n\nFixpoint max n m :=\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\nFixpoint min n m :=\n  match n, m with\n    | 0, _ => 0\n    | S n', 0 => 0\n    | S n', S m' => S (min n' m')\n  end.\n\n(** ** Parity tests *)\n\nFixpoint even n : bool :=\n  match n with\n    | 0 => true\n    | 1 => false\n    | S (S n') => even n'\n  end.\n\nDefinition odd n := negb (even n).\n\n(** ** Power *)\n\nFixpoint pow n m :=\n  match m with\n    | 0 => 1\n    | S m => n * (n^m)\n  end\n\nwhere \"n ^ m\" := (pow n m) : nat_scope.\n\n(** ** Tail-recursive versions of [add] and [mul] *)\n\nFixpoint tail_add n m :=\n  match n with\n    | O => m\n    | S n => tail_add n (S m)\n  end.\n\n(** [tail_addmul r n m] is [r + n * m]. *)\n\nFixpoint tail_addmul r n m :=\n  match n with\n    | O => r\n    | S n => tail_addmul (tail_add m r) n m\n  end.\n\nDefinition tail_mul n m := tail_addmul 0 n m.\n\n(** ** Conversion with a decimal representation for printing/parsing *)\n\nLocal Notation ten := (S (S (S (S (S (S (S (S (S (S O)))))))))).\n\nFixpoint of_uint_acc (d:Decimal.uint)(acc:nat) :=\n  match d with\n  | Decimal.Nil => acc\n  | Decimal.D0 d => of_uint_acc d (tail_mul ten acc)\n  | Decimal.D1 d => of_uint_acc d (S (tail_mul ten acc))\n  | Decimal.D2 d => of_uint_acc d (S (S (tail_mul ten acc)))\n  | Decimal.D3 d => of_uint_acc d (S (S (S (tail_mul ten acc))))\n  | Decimal.D4 d => of_uint_acc d (S (S (S (S (tail_mul ten acc)))))\n  | Decimal.D5 d => of_uint_acc d (S (S (S (S (S (tail_mul ten acc))))))\n  | Decimal.D6 d => of_uint_acc d (S (S (S (S (S (S (tail_mul ten acc)))))))\n  | Decimal.D7 d => of_uint_acc d (S (S (S (S (S (S (S (tail_mul ten acc))))))))\n  | Decimal.D8 d => of_uint_acc d (S (S (S (S (S (S (S (S (tail_mul ten acc)))))))))\n  | Decimal.D9 d => of_uint_acc d (S (S (S (S (S (S (S (S (S (tail_mul ten acc))))))))))\n  end.\n\nDefinition of_uint (d:Decimal.uint) := of_uint_acc d O.\n\nLocal Notation sixteen := (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S O)))))))))))))))).\n\nFixpoint of_hex_uint_acc (d:Hexadecimal.uint)(acc:nat) :=\n  match d with\n  | Hexadecimal.Nil => acc\n  | Hexadecimal.D0 d => of_hex_uint_acc d (tail_mul sixteen acc)\n  | Hexadecimal.D1 d => of_hex_uint_acc d (S (tail_mul sixteen acc))\n  | Hexadecimal.D2 d => of_hex_uint_acc d (S (S (tail_mul sixteen acc)))\n  | Hexadecimal.D3 d => of_hex_uint_acc d (S (S (S (tail_mul sixteen acc))))\n  | Hexadecimal.D4 d => of_hex_uint_acc d (S (S (S (S (tail_mul sixteen acc)))))\n  | Hexadecimal.D5 d => of_hex_uint_acc d (S (S (S (S (S (tail_mul sixteen acc))))))\n  | Hexadecimal.D6 d => of_hex_uint_acc d (S (S (S (S (S (S (tail_mul sixteen acc)))))))\n  | Hexadecimal.D7 d => of_hex_uint_acc d (S (S (S (S (S (S (S (tail_mul sixteen acc))))))))\n  | Hexadecimal.D8 d => of_hex_uint_acc d (S (S (S (S (S (S (S (S (tail_mul sixteen acc)))))))))\n  | Hexadecimal.D9 d => of_hex_uint_acc d (S (S (S (S (S (S (S (S (S (tail_mul sixteen acc))))))))))\n  | Hexadecimal.Da d => of_hex_uint_acc d (S (S (S (S (S (S (S (S (S (S (tail_mul sixteen acc)))))))))))\n  | Hexadecimal.Db d => of_hex_uint_acc d (S (S (S (S (S (S (S (S (S (S (S (tail_mul sixteen acc))))))))))))\n  | Hexadecimal.Dc d => of_hex_uint_acc d (S (S (S (S (S (S (S (S (S (S (S (S (tail_mul sixteen acc)))))))))))))\n  | Hexadecimal.Dd d => of_hex_uint_acc d (S (S (S (S (S (S (S (S (S (S (S (S (S (tail_mul sixteen acc))))))))))))))\n  | Hexadecimal.De d => of_hex_uint_acc d (S (S (S (S (S (S (S (S (S (S (S (S (S (S (tail_mul sixteen acc)))))))))))))))\n  | Hexadecimal.Df d => of_hex_uint_acc d (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (tail_mul sixteen acc))))))))))))))))\n  end.\n\nDefinition of_hex_uint (d:Hexadecimal.uint) := of_hex_uint_acc d O.\n\nDefinition of_num_uint (d:Number.uint) :=\n  match d with\n  | Number.UIntDecimal d => of_uint d\n  | Number.UIntHexadecimal d => of_hex_uint d\n  end.\n\nFixpoint to_little_uint n acc :=\n  match n with\n  | O => acc\n  | S n => to_little_uint n (Decimal.Little.succ acc)\n  end.\n\nDefinition to_uint n :=\n  Decimal.rev (to_little_uint n Decimal.zero).\n\nFixpoint to_little_hex_uint n acc :=\n  match n with\n  | O => acc\n  | S n => to_little_hex_uint n (Hexadecimal.Little.succ acc)\n  end.\n\nDefinition to_hex_uint n :=\n  Hexadecimal.rev (to_little_hex_uint n Hexadecimal.zero).\n\nDefinition to_num_uint n := Number.UIntDecimal (to_uint n).\n\nDefinition to_num_hex_uint n := Number.UIntHexadecimal (to_hex_uint n).\n\nDefinition of_int (d:Decimal.int) : option nat :=\n  match Decimal.norm d with\n    | Decimal.Pos u => Some (of_uint u)\n    | _ => None\n  end.\n\nDefinition of_hex_int (d:Hexadecimal.int) : option nat :=\n  match Hexadecimal.norm d with\n    | Hexadecimal.Pos u => Some (of_hex_uint u)\n    | _ => None\n  end.\n\nDefinition of_num_int (d:Number.int) : option nat :=\n  match d with\n  | Number.IntDecimal d => of_int d\n  | Number.IntHexadecimal d => of_hex_int d\n  end.\n\nDefinition to_int n := Decimal.Pos (to_uint n).\n\nDefinition to_hex_int n := Hexadecimal.Pos (to_hex_uint n).\n\nDefinition to_num_int n := Number.IntDecimal (to_int n).\n\n(** ** Euclidean division *)\n\n(** This division is linear and tail-recursive.\n    In [divmod], [y] is the predecessor of the actual divisor,\n    and [u] is [y] minus the real remainder\n*)\n\nFixpoint divmod x y q u :=\n  match x with\n    | 0 => (q,u)\n    | S x' => match u with\n                | 0 => divmod x' y (S q) y\n                | S u' => divmod x' y q u'\n              end\n  end.\n\nDefinition div x y :=\n  match y with\n    | 0 => y\n    | S y' => fst (divmod x y' 0 y')\n  end.\n\nDefinition modulo x y :=\n  match y with\n    | 0 => x\n    | S y' => y' - snd (divmod x y' 0 y')\n  end.\n\nInfix \"/\" := div : nat_scope.\nInfix \"mod\" := modulo (at level 40, no associativity) : nat_scope.\n\n\n(** ** Greatest common divisor *)\n\n(** We use Euclid algorithm, which is normally not structural,\n    but Coq is now clever enough to accept this (behind modulo\n    there is a subtraction, which now preserves being a subterm)\n*)\n\nFixpoint gcd a b :=\n  match a with\n   | O => b\n   | S a' => gcd (b mod (S a')) (S a')\n  end.\n\n(** ** Square *)\n\nDefinition square n := n * n.\n\n(** ** Square root *)\n\n(** The following square root function is linear (and tail-recursive).\n  With Peano representation, we can't do better. For faster algorithm,\n  see Psqrt/Zsqrt/Nsqrt...\n\n  We search the square root of n = k + p^2 + (q - r)\n  with q = 2p and 0<=r<=q. We start with p=q=r=0, hence\n  looking for the square root of n = k. Then we progressively\n  decrease k and r. When k = S k' and r=0, it means we can use (S p)\n  as new sqrt candidate, since (S k')+p^2+2p = k'+(S p)^2.\n  When k reaches 0, we have found the biggest p^2 square contained\n  in n, hence the square root of n is p.\n*)\n\nFixpoint sqrt_iter k p q r :=\n  match k with\n    | O => p\n    | S k' => match r with\n                | O => sqrt_iter k' (S p) (S (S q)) (S (S q))\n                | S r' => sqrt_iter k' p q r'\n              end\n  end.\n\nDefinition sqrt n := sqrt_iter n 0 0 0.\n\n(** ** Log2 *)\n\n(** This base-2 logarithm is linear and tail-recursive.\n\n  In [log2_iter], we maintain the logarithm [p] of the counter [q],\n  while [r] is the distance between [q] and the next power of 2,\n  more precisely [q + S r = 2^(S p)] and [r<2^p]. At each\n  recursive call, [q] goes up while [r] goes down. When [r]\n  is 0, we know that [q] has almost reached a power of 2,\n  and we increase [p] at the next call, while resetting [r]\n  to [q].\n\n  Graphically (numbers are [q], stars are [r]) :\n\n<<\n                    10\n                  9\n                8\n              7   *\n            6       *\n          5           ...\n        4\n      3   *\n    2       *\n  1   *       *\n0   *   *       *\n>>\n\n  We stop when [k], the global downward counter reaches 0.\n  At that moment, [q] is the number we're considering (since\n  [k+q] is invariant), and [p] its logarithm.\n*)\n\nFixpoint log2_iter k p q r :=\n  match k with\n    | O => p\n    | S k' => match r with\n                | O => log2_iter k' (S p) (S q) q\n                | S r' => log2_iter k' p (S q) r'\n              end\n  end.\n\nDefinition log2 n := log2_iter (pred n) 0 1 0.\n\n(** Iterator on natural numbers *)\n\nDefinition iter (n:nat) {A} (f:A->A) (x:A) : A :=\n nat_rect (fun _ => A) x (fun _ => f) n.\n\n(** Bitwise operations *)\n\n(** We provide here some bitwise operations for unary numbers.\n  Some might be really naive, they are just there for fulfilling\n  the same interface as other for natural representations. As\n  soon as binary representations such as NArith are available,\n  it is clearly better to convert to/from them and use their ops.\n*)\n\nFixpoint div2 n :=\n  match n with\n  | 0 => 0\n  | S 0 => 0\n  | S (S n') => S (div2 n')\n  end.\n\nFixpoint testbit a n : bool :=\n match n with\n   | 0 => odd a\n   | S n => testbit (div2 a) n\n end.\n\nDefinition shiftl a := nat_rect _ a (fun _ => double).\nDefinition shiftr a := nat_rect _ a (fun _ => div2).\n\nFixpoint bitwise (op:bool->bool->bool) n a b :=\n match n with\n  | 0 => 0\n  | S n' =>\n    (if op (odd a) (odd b) then 1 else 0) +\n    2*(bitwise op n' (div2 a) (div2 b))\n end.\n\nDefinition land a b := bitwise andb a a b.\nDefinition lor a b := bitwise orb (max a b) a b.\nDefinition ldiff a b := bitwise (fun b b' => andb b (negb b')) a a b.\nDefinition lxor a b := bitwise xorb (max a b) a b.\n", "meta": {"author": "jsarracino", "repo": "mirrorsolve", "sha": "74fc7790b21952d4f27ea70545b0038f298915b0", "save_path": "github-repos/coq/jsarracino-mirrorsolve", "path": "github-repos/coq/jsarracino-mirrorsolve/mirrorsolve-74fc7790b21952d4f27ea70545b0038f298915b0/tests/case-studies/Nat/Nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6780288328802494}}
{"text": "From Nom Require Export Atom Group Swap.\n\n(** *Permutation *)\nDeclare Scope perm_scope.\nDelimit Scope perm_scope with perm.\n\nNotation Perm := (list (Atom * Atom)).\n(* Definition Perm := list (Atom * Atom). *)\n\nDefinition perm_act_atom (p: Perm) c: Atom :=\n  fold_left (fun w q => swap (fst q) (snd q) w) p c.\n\nSection PermEquiv.\n  Definition perm_equiv (p q: Perm): Prop :=\n    forall x, perm_act_atom p x ≡ perm_act_atom q x.\n  Local Hint Unfold perm_equiv: core.\n\n  Global Program Instance PermEquivRefl: Reflexive perm_equiv.\n  Global Program Instance PermEquivSymm: Symmetric perm_equiv.\n  Global Program Instance PermEquivTrans: Transitive perm_equiv.\n  Next Obligation. unfold perm_equiv in *; intros; eapply eq_trans; eauto. Qed.\n  Global Instance PermEquiv: Equiv Perm. exact perm_equiv. Defined.\n  Global Program Instance PermSetoid: Setoid Perm.\n  Next Obligation. split; typeclasses eauto. Qed.\nEnd PermEquiv.\nArguments PermEquiv p q/.\nArguments perm_equiv /.\n\nSection PermActProperties.\n  Lemma perm_act_atom_concat (p: Perm): forall q x,\n    perm_act_atom (p ++ q) x ≡ perm_act_atom q (perm_act_atom p x).\n  Proof with (auto). induction p; intros; simpl... Qed.\n\n  Lemma perm_act_atom_rev_left1 (p: Perm):\n    forall x, perm_act_atom p (perm_act_atom (rev p) x) ≡ x.\n  Proof with (auto).\n    induction p; intros; simpl...\n    rewrite perm_act_atom_concat; simpl; rewrite swap_involutive...\n  Qed.\n\n  Lemma perm_act_atom_rev_left (p: Perm) x:\n    perm_act_atom (rev p ++ p) x ≡ x.\n  Proof. rewrite perm_act_atom_concat; apply perm_act_atom_rev_left1. Qed.\n\n  Lemma perm_act_atom_rev_right1 (p: Perm):\n    forall x, perm_act_atom (rev p) (perm_act_atom p x) ≡ x.\n  Proof with auto.\n    induction p; intros; simpl...\n    rewrite perm_act_atom_concat; simpl; rewrite IHp;\n      apply swap_involutive.\n  Qed.\n\n  Lemma perm_act_atom_rev_right (p: Perm) x:\n    perm_act_atom (p ++ rev p) x ≡ x.\n  Proof. rewrite perm_act_atom_concat; apply perm_act_atom_rev_right1. Qed.\n\n  Lemma perm_act_atom_rev_equiv (p q: Perm):\n    p = q -> (rev p) = (rev q).\n  Proof with auto.\n    intros H x; transitivity (perm_act_atom (rev q ++ p ++ rev p) x);\n      repeat rewrite perm_act_atom_concat.\n    - rewrite H, perm_act_atom_rev_left1...\n    - rewrite perm_act_atom_rev_right1...\n  Qed.\nEnd PermActProperties.\n\n(** *Perm additive group  *)\nRequire Import Properties.\n\nInstance perm_unit: Neutral Perm. exact (@nil (Atom * Atom)). Defined.\nInstance perm_op: Binop Perm. exact (@app (Atom * Atom)). Defined.\nInstance perm_inv: Negate Perm. exact (@rev (Atom * Atom)). Defined.\nArguments perm_unit /.\nArguments perm_op /.\nArguments perm_inv /.\n\nProgram Instance: Associative perm_op.\nNext Obligation. rewrite app_assoc; auto. Qed.\nProgram Instance: RightIdentity perm_op perm_unit.\nNext Obligation. rewrite app_nil_r; auto. Qed.\nProgram Instance: LeftInverse perm_op perm_inv perm_unit.\nNext Obligation. unfold equiv; simpl; intros; rewrite perm_act_atom_rev_left; auto. Qed.\nProgram Instance: RightInverse perm_op perm_inv perm_unit.\nNext Obligation. unfold equiv; simpl; intros; rewrite perm_act_atom_rev_right; auto. Qed.\nProgram Instance: LeftIdentity perm_op perm_unit.\n\nProgram Instance PermGroup: @Group Perm PermEquiv perm_unit perm_inv perm_op :=\n  { g_setoid := PermSetoid }.\nNext Obligation. (* perm_op preserve perm_equiv *)\n  intros ? ? HE1 ? ? HE2; unfold equiv,\"+\" in *; simpl in *; intros;\n    repeat rewrite perm_act_atom_concat; rewrite HE1,HE2; reflexivity.\nQed.\nNext Obligation. (* perm_neg preserve perm_equiv *)\n  intros ? ? HE; unfold negate,equiv in *; simpl in *; intros;\n    apply perm_act_atom_rev_equiv; auto.\nQed.\n", "meta": {"author": "fasapa", "repo": "nominalsets", "sha": "2a2ef1b3cd17b1c06d95e473c0b750b359fd3e3d", "save_path": "github-repos/coq/fasapa-nominalsets", "path": "github-repos/coq/fasapa-nominalsets/nominalsets-2a2ef1b3cd17b1c06d95e473c0b750b359fd3e3d/theories/Permutation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6780288328802494}}
{"text": "(* ---------------------------------------------------------------------\n   This file contains definitions and proof scripts related to \n   (i) closure operations for context-free grammars, \n   (ii) context-free grammars simplification \n   (iii) context-free grammar Chomsky normalization and \n   (iv) pumping lemma for context-free languages.\n   \n   More information can be found in the paper \"Formalization of the\n   Pumping Lemma for Context-Free Languages\", submitted to JFR.\n   \n   Marcus Vinícius Midena Ramos\n   mvmramos@gmail.com\n   --------------------------------------------------------------------- *)\n\nRequire Import List.\nRequire Import Ring.\nRequire Import Omega.\nRequire Import NPeano.\n\nRequire Import misc_arith.\nRequire Import misc_list.\nRequire Import cfg.\nRequire Import cfl.\nRequire Import inaccessible.\nRequire Import useless.\nRequire Import unitrules.\nRequire Import emptyrules.\nRequire Import simplification.\nRequire Import trees.\nRequire Import allrules.\nRequire Import chomsky.\nRequire Import pigeon.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport ListNotations.\nOpen Scope list_scope.\n\n(* --------------------------------------------------------------------- *)\n(* PUMPING LEMMA                                                         *)\n(* --------------------------------------------------------------------- *)\n\nSection Pumping.\n\nVariable non_terminal terminal: Type.\nNotation sentence:= (list terminal).\n\nLemma pumping_aux:\nforall g: cfg _ _,\nforall t1 t2: btree (non_terminal' non_terminal terminal) _,\nforall n: _,\nforall c1 c2: list bool,\nforall v x: sentence,\nbtree_decompose t1 c1 = Some (v, t2, x) ->\nbtree_cnf g t1 ->\nbroot t1 = n ->\nbcode t1 (c1 ++ c2) ->\nc1 <> [] ->\nbroot t2 = n ->\nbcode t2 c2 ->\n(forall i: nat,\n exists t': btree _ _,\n btree_cnf g t' /\\\n broot t' = n /\\\n btree_decompose t' (iter c1 i) = Some (iter v i, t2, iter x i) /\\\n bcode t' (iter c1 i ++ c2) /\\\n get_nt_btree (iter c1 i) t' = Some n).\nProof.\ninduction i.\n- exists t2.\n  simpl.\n  split.\n  + apply btree_cnf_subtree with (t2:= t2) in H0.\n    * exact H0.\n    * {\n      apply btree_decompose_subtree_bcode in H.\n      - apply subtree_bcode_subtree in H. \n        exact H.\n      - exact H3.\n      }\n  + split.\n    * exact H4.\n    * {\n      split.\n      - rewrite btree_decompose_empty. \n        reflexivity.\n      - split. \n        + exact H5.\n        + destruct t2.\n          * simpl in H4.\n            subst.\n            reflexivity.\n          * simpl in H4.\n            subst.\n            reflexivity.\n      }\n- destruct IHi as [t' [H10 [H11 [H12 [H13 H14]]]]].\n  assert (H15: exists t'': btree _ _, btree_subst t' t1 (iter c1 i) = Some t'').\n    {\n    apply bcode_btree_subst with (c2:= c2).\n    exact H13.\n    }\n  destruct H15 as [t'' H15].\n  exists t''.\n  split. \n  + apply btree_subst_preserves_cnf with (g:= g) (c1':= c2) in H15.\n    * exact H15. \n    * exact H10. \n    * exact H13. \n    * exact H0.\n    * congruence. \n  + split. \n    * {\n      apply btree_subst_preserves_broot_v1 in H15.\n      - congruence.\n      - congruence.\n      }\n    * {\n      split. \n      - apply btree_subst_decompose with (t2:= t2) (x:= iter v i) (y:= iter x i) in H15.\n        + simpl. \n          repeat rewrite iter_comm.\n          replace (iter x i ++ x) with (x ++ iter x i).\n          * {\n            apply btree_decompose_combine with (t1:= t1).\n            - exact H15.\n            - exact H.\n            }\n          * rewrite iter_comm.\n            reflexivity.\n        + exact H12.\n      - split.\n        + apply btree_subst_bcode with (c1':= c2) (c2:= c1 ++ c2) in H15.\n          * simpl. \n            rewrite iter_comm. \n            rewrite <- app_assoc. \n            exact H15. \n          * exact H13. \n          * exact H2.\n        + simpl.\n            rewrite iter_comm.\n            {\n            apply btree_subst_get_nt with (c1':= c2) (c2:= c1) (c2':= c2) (n:= n) in H15.\n            - exact H15.\n            - exact H13.\n            - exact H2.\n            - apply btree_decompose_get_nt in H. \n              congruence. \n            }\n      }\nQed.\n\nEnd Pumping.\n\nSection Pumping_2.\n\nVariable terminal: Type.\nNotation sentence:= (list terminal).\n\nTheorem pumping_lemma:\nforall l: lang terminal,\n(contains_empty l \\/ ~ contains_empty l) /\\ (contains_non_empty l \\/ ~ contains_non_empty l) ->\ncfl l ->\nexists n: nat, \nforall s: sentence, \nl s -> \nlength s >= n ->\nexists u v w x y: sentence, \ns = u ++ v ++ w ++ x ++ y /\\\nlength (v ++ x) >= 1 /\\\nlength (u ++ y) >= 1 /\\\nlength (v ++ w ++ x) <= n /\\\nforall i: nat, l (u ++ (iter v i) ++ w ++ (iter x i) ++ y).\nProof.\nintros l H1 H2.\ninversion H2 as [non_terminal H3].\nclear H2.\ndestruct H3 as [g H3].\n(* Find g' in CNF *)\nassert (H2: exists g': cfg (chomsky.non_terminal' (emptyrules.non_terminal' non_terminal) terminal) terminal, (g_equiv g' g) /\\ (is_cnf g' \\/ is_cnf_with_empty_rule g') /\\ start_symbol_not_in_rhs g').\n  {\n  apply g_cnf_exists.\n  destruct H1 as [H1 H2].\n  split.\n  - destruct H1 as [H1 | H1].\n    + left.\n      specialize (H3 []).\n      destruct H3 as [H3 _].\n      apply H3.\n      exact H1.\n    + right.\n      intros H4.\n      apply H1.\n      specialize (H3 []).\n      destruct H3 as [_ H3].\n      apply H3.\n      exact H4.\n  - destruct H2 as [H2 | H2].\n    + left.\n      destruct H2 as [w [H2 H4]].\n      specialize (H3 w).\n      destruct H3 as [H3 _].\n      exists w.\n      split.\n      * apply H3.\n        exact H2.\n      * exact H4.\n    + right.\n      intros H4.\n      apply H2.\n      destruct H4 as [w [H4 H5]].\n      specialize (H3 w).\n      destruct H3 as [_ H3].\n      exists w.\n      split.\n      * apply H3.\n        exact H4.\n      * exact H5.\n  }\ndestruct H2 as [g' [H2 H4]].\n(* Change g for g' *)\napply lang_eq_change_g with (non_terminal':= chomsky.non_terminal' (emptyrules.non_terminal' non_terminal) terminal) (g':= g') in H3.\n- assert (H3':= H3).\n  assert (H3copy:= H3).\n  destruct (rules_finite g') as [n' [ntl' [tl' H5]]].\n  assert (H5':= H5).\n  (* exists n *)\n  exists (2 ^ (length ntl')).\n  intros s H6 H7.\n  specialize (H3 s). \n  destruct H3 as [H3 _].\n  specialize (H3 H6).\n  assert (H6':= H6).\n  unfold lang_of_g in H3.\n  destruct H4 as [H4 H4'].  \n  assert (H4copy:= H4).\n  unfold produces, generates in H3.\n  (* Find btree *)\n  apply derives_g_cnf_equiv_btree_v4 with (n:= start_symbol g') (s:= s) in H4.\n  + destruct H4 as [t [H4 [H8 H9]]].\n    clear g H1 H2 H3 H5 H6.\n    apply length_ge with (t:= t) in H7.\n    assert (HHH:= H7).      \n    * (* Find bpath *)\n      {\n      apply btree_exists_bpath with (ntl:= ntl') in H7.\n      - destruct H7 as [z [H20 [H21 [m [r [t0 [H22 [H23 [H24 H25]]]]]]]]].\n        assert (H26: forall s, In s r -> In s (map inl ntl')).\n          {\n          intros s0 H27.\n          specialize (H25 s0).\n          apply H25.\n          apply in_or_app.\n          right.\n          exact H27.\n          }\n        clear H25.\n        assert (H27: exists r': list (non_terminal' (emptyrules.non_terminal' non_terminal) terminal), r = map inl r').\n          {\n          exists (get_As _ _ r).\n          apply get_As_correct.\n          intros e H28.\n          specialize (H26 e H28).\n          apply in_split in H26.\n          destruct H26 as [l1 [l2 H26]].\n          symmetry in H26.\n          apply map_expand in H26.\n          destruct H26 as [s1' [s2' [_ [_ H26]]]].\n          symmetry in H26. \n          change (e :: l2) with ([e] ++ l2) in H26.\n          apply map_expand in H26.\n          destruct H26 as [s1'0 [s2'0 [_ [H26 _]]]].\n          destruct s1'0.\n          - simpl in H26.\n            inversion H26. \n          - simpl in H26.\n            inversion H26.\n            exists n.\n            reflexivity.\n          }\n        destruct H27 as [r' H27].\n        assert (H28: length r' = length r).\n          {\n          rewrite H27.\n          rewrite map_length.\n          reflexivity.\n          }\n        assert (H24':= H24).\n        rewrite <- H28 in H24.\n        rewrite H27 in H26.\n        assert (H29: forall n: non_terminal' (emptyrules.non_terminal' non_terminal) terminal, In n r' -> In n ntl').\n          {\n          intros n H99.\n          assert (H29: In (inl n) (map (@inl _ terminal) r')).\n            {\n            apply in_map.\n            exact H99.\n            }\n          specialize (H26 (inl n) H29).\n          apply in_split in H26.\n          destruct H26 as [l1 [l2 H26]].\n          symmetry in H26.\n          apply map_expand in H26.\n          destruct H26 as [s1' [s2' [H40 [H41 H42]]]].\n          symmetry in H42.\n          change (inl n :: l2) with ([inl n] ++ l2) in H42.\n          apply map_expand in H42.\n          destruct H42 as [s1'0 [s2'0 [H42 [H43 H44]]]].\n          destruct s1'0.\n          - simpl in H43.\n            inversion H43.\n          - simpl in H43.\n            inversion H43.\n            subst.\n            apply in_or_app.\n            right.\n            simpl.\n            left.\n            reflexivity.\n          }\n        apply pigeon in H29. \n        + destruct H29 as [n [r1' [r2' [r3' H29]]]].\n          rewrite H29 in H27.\n          repeat rewrite map_app in H27.\n          (* Prepare path *)\n          assert (Hpath:= H22).\n          rewrite H27 in Hpath.\n          repeat rewrite <- app_assoc in Hpath.\n          assert (H20copy:= H20). \n          rewrite Hpath in H20copy.\n          apply bpath_insert_head in H20copy.\n          * destruct H20copy as [p12' H20copy].\n            rewrite app_assoc in Hpath.\n            rewrite <- H20copy in Hpath.\n            rewrite <- app_assoc in Hpath.\n            (* Find subtrees and u, v, w, x, y *)\n            apply bpath_exists_bcode in H20.\n            destruct H20 as [c [H100 H101]].\n            rewrite Hpath in H101.\n            rewrite app_assoc in H101.\n            assert (H101copy:= H101).\n            {\n            apply bcode_split in H101.\n            - destruct H101 as [c1 [c2 [H101 [H102 [t1 [u [y [H104 [H105 H106]]]]]]]]].\n              assert (H105copy:= H105).\n              assert (Ht:= H105).\n              apply btree_decompose_bfrontier in H105.\n              destruct H105 as [Ht_a Ht_b].\n              assert (Hc1: c1 <> []).\n                {\n                simpl in H102.\n                assert (length c1 > 0) by omega.\n                apply length_not_zero in H.\n                apply not_eq_sym.\n                exact H.\n                }\n              specialize (Ht_b Hc1).\n              assert (Ht_c: subtree_bcode t t1 c1).\n                {\n                apply btree_decompose_subtree_bcode in H105copy.\n                - exact H105copy.\n                - exact Hc1.\n                }\n              rewrite app_assoc in H104.\n              assert (H104copy:= H104).\n              apply bcode_split in H104.\n              + destruct H104 as [c3 [c4 [H104 [H107 [t2 [v [x [H109 [H110 H111]]]]]]]]].\n                assert (H110copy:= H110).\n                assert (Ht1:= H110).\n                apply btree_decompose_bfrontier in H110.\n                destruct H110 as [Ht1_a Ht1_b].\n                assert (Hc3: c3 <> []).\n                  {\n                  simpl in H107.\n                  assert (length c3 > 0) by omega.\n                  apply length_not_zero in H.\n                  apply not_eq_sym.\n                  exact H.\n                  }\n                specialize (Ht1_b Hc3).\n                assert (Ht1_c: subtree_bcode t1 t2 c3).\n                  {\n                  apply btree_decompose_subtree_bcode in H110copy.\n                  - exact H110copy.\n                  - exact Hc3.\n                  }\n                remember (bfrontier t2) as w.\n                (* Find roots *)\n                assert (Hroot_t1: broot t1 = n).\n                  {\n                  apply bpath_bcode_split in H104copy.\n                  destruct H104copy as [H104copy _].\n                  apply bpath_broot with (d:= inl (broot t1)) in H104copy.\n                  simpl in H104copy.\n                  inversion H104copy.\n                  reflexivity.\n                  }\n                assert (Hroot_t2: broot t2 = n).\n                  {\n                  apply bpath_bcode_split in H109.\n                  destruct H109 as [H109 _].\n                  apply bpath_broot with (d:= inl (broot t2)) in H109.\n                  simpl in H109.\n                  inversion H109.\n                  reflexivity.\n                  }\n                (* Find heights *)\n                remember (length ntl') as k.\n                assert (H114: bheight t1 <= k + 1 /\\ bheight t1 >= 2).\n                  {\n                  split.\n                  - rewrite H106.\n                    rewrite H27 in H24'.\n                    repeat rewrite app_length in H24'.\n                    repeat rewrite app_length.\n                    simpl in H24'.\n                    simpl.\n                    omega.\n                  - rewrite H106.\n                    rewrite H27 in H24'.\n                    repeat rewrite app_length in H24'.\n                    repeat rewrite app_length.\n                    simpl in H24'.\n                    simpl.\n                    omega.\n                  }\n                assert (H115: bheight t2 <= k /\\ bheight t2 >= 1).\n                  {\n                  split.\n                  - rewrite H111.\n                    rewrite H27 in H24'.\n                    repeat rewrite app_length in H24'.\n                    repeat rewrite app_length.\n                    simpl in H24'.\n                    simpl.\n                    omega.\n                  - rewrite H111.\n                    rewrite H27 in H24'.\n                    repeat rewrite app_length in H24'.\n                    repeat rewrite app_length.\n                    simpl in H24'.\n                    simpl.\n                    omega.\n                  }\n                (* Exists u, v, w, x, y *)\n                exists u, v, w, x, y.\n                split.\n                * (* s = u ++ v ++ w ++ x ++ y *)\n                  rewrite <- H9.\n                  rewrite Ht_a.\n                  rewrite Ht1_a.\n                  repeat rewrite <- app_assoc.\n                  reflexivity.\n                * {\n                  split.\n                  - (* length (v ++ x) >= 1 *)\n                    apply length_not_zero_inv in Ht1_b.\n                    omega.\n                  - split.\n                    + (* length (u ++ y) >= 1 *)\n                      apply length_not_zero_inv in Ht_b.\n                      omega.                      \n                    + split.\n                      * (* length (v ++ w ++ x) <= 2 ^ k *)\n                        destruct H114 as [H114 H116].\n                        apply bheight_le in H114.\n                        rewrite Ht1_a in H114.\n                        {\n                        replace (k + 1 - 1) with k in H114.\n                        - exact H114. \n                        - omega.\n                        }\n                      * (* uv^iwx^iy *)\n                        intros i.\n                        assert (Ht': exists t': btree _ _, \n                                     btree_cnf g' t' /\\\n                                     broot t' = n /\\\n                                     btree_decompose t' (iter c3 i) = Some (iter v i, t2, iter x i) /\\\n                                     bcode t' (iter c3 i ++ c4) /\\\n                                     get_nt_btree (iter c3 i) t' = Some n).\n                          {\n                          apply pumping_aux with (g:= g') (t1:= t1) (t2:= t2) (n:= n) (c1:= c3) (c2:= c4) (v:= v) (x:= x) (i:= i).\n                          - exact Ht1. \n                          - apply subtree_bcode_subtree in Ht_c.\n                            apply btree_cnf_subtree with (g:= g') in Ht_c.\n                            + exact Ht_c.\n                            + exact H4.\n                          - exact Hroot_t1.\n                          - rewrite <- H104.\n                            apply bpath_bcode_split in H104copy. \n                            apply H104copy.\n                          - exact Hc3.\n                          - congruence.\n                          - apply bpath_bcode_split in H109.\n                            apply H109.\n                          }\n                        destruct Ht' as [t' [Ht'_1 [Ht'_2 [Ht'_3 Ht'_4]]]].\n                        assert (Ht'': exists t'': btree _ _, btree_subst t t' c1 = Some t'').\n                          {\n                          rewrite H101 in H100.\n                          apply bcode_btree_subst with (t2:= t') in H100.\n                          destruct H100 as [t'' H100].\n                          exists t''.\n                          exact H100.\n                          }\n                        destruct Ht'' as [t'' Ht''].\n                        assert (Ht''_1: broot t'' = start_symbol g').\n                          {\n                          apply btree_subst_preserves_broot_v2 in Ht''. \n                          - congruence. \n                          - exact Hc1.\n                          }\n                        assert (Ht''_2: bfrontier t'' = u ++ iter v i ++ w ++ iter x i ++ y).\n                          {\n                          apply btree_subst_bfrontier with (t2:= t1) (x:= u) (y:= y) in Ht''.\n                          - apply btree_decompose_bfrontier in Ht'_3.\n                            destruct Ht'_3 as [Ht'_3 _].\n                            rewrite Ht'_3 in Ht''.\n                            rewrite Heqw.\n                            repeat rewrite <- app_assoc in Ht''.\n                            exact Ht''.\n                          - exact Ht_c.\n                          - exact Ht. \n                          }\n                        assert (Ht''_3: btree_cnf g' t'').\n                          {\n                          apply btree_subst_preserves_cnf with (g:= g') (c1':= c3 ++ c4) in Ht''.\n                          - exact Ht''.\n                          - exact H4.\n                          - rewrite <- H104.\n                            rewrite <- H101.\n                            exact H100.\n                          - exact Ht'_1.\n                          - apply btree_decompose_get_nt in Ht.\n                            congruence.\n                          }\n                        {\n                        apply btree_equiv_produces_g_cnf in Ht''_3.\n                        - unfold lang_eq in H3'.\n                          specialize (H3' (u ++ iter v i ++ w ++ iter x i ++ y)).\n                          destruct H3' as [_ H3'].\n                          unfold lang_of_g in H3'.\n                          apply H3'.\n                          rewrite <- Ht''_2.\n                          exact Ht''_3.\n                        - congruence.\n                        }\n                  }\n              + rewrite app_length.\n                simpl.\n                omega.\n              + repeat rewrite app_length.\n                simpl.\n                omega.\n              + rewrite H106.\n                repeat rewrite app_length.\n                reflexivity.\n            - rewrite app_length.\n              simpl.\n              omega.\n            - repeat rewrite app_length.\n              simpl.\n              omega.\n            - rewrite Hpath in H21.\n              repeat rewrite app_length in H21.\n              repeat rewrite app_length.\n              omega.\n            }\n          * rewrite H8.\n            {\n            apply start_symbol_only_once with (g:= g') (t:= t) (p1:= m ++ map inl r1') (p2:= map inl r2') (p3:= map inl r3' ++ [inr t0]).\n            - exact H4'.\n            - exact H4.\n            - repeat rewrite <- app_assoc. \n              exact H20copy.\n            }\n        + apply (nt_eqdec g').\n        + rewrite H28.\n          exact H24'.\n      - apply cnf_bnts with (g:= g') (n:= n') (tl:= tl').\n        + exact H5'.\n        + exact H4.\n      }\n    * exact H9.\n  + assert (Hntl': 2 ^ length ntl' > 0).\n      {\n      apply pow_2_gt_0.\n      }\n    assert (Hs: length s > 0) by omega.\n    apply length_not_zero in Hs.\n    apply not_eq_sym.\n    exact Hs.\n  + exact H4'.\n  + exact H3.\n- exact H2.\nQed.\n\nTheorem pumping_lemma_v2:\nforall l: lang terminal,\n(contains_empty l \\/ ~ contains_empty l) /\\ (contains_non_empty l \\/ ~ contains_non_empty l) ->\ncfl l ->\nexists n: nat, \nforall s: sentence, \nl s -> \nlength s >= n ->\nexists u v w x y: sentence, \ns = u ++ v ++ w ++ x ++ y /\\\nlength (v ++ x) >= 1 /\\\nlength (v ++ w ++ x) <= (n - 1) * 2 /\\\nforall i: nat, l (u ++ (iter v i) ++ w ++ (iter x i) ++ y).\nProof.\nintros l H1 H2.\ninversion H2 as [non_terminal H3].\nclear H2.\ndestruct H3 as [g H3].\n(* Find g' in CNF *)\nassert (H2: exists g': cfg (chomsky.non_terminal' (emptyrules.non_terminal' non_terminal) terminal) terminal, (g_equiv g' g) /\\ (is_cnf g' \\/ is_cnf_with_empty_rule g') /\\ start_symbol_not_in_rhs g').\n  {\n  apply g_cnf_exists.\n  destruct H1 as [H1 H2].\n  split.\n  - destruct H1 as [H1 | H1].\n    + left.\n      specialize (H3 []).\n      destruct H3 as [H3 _].\n      apply H3.\n      exact H1.\n    + right.\n      intros H4.\n      apply H1.\n      specialize (H3 []).\n      destruct H3 as [_ H3].\n      apply H3.\n      exact H4.\n  - destruct H2 as [H2 | H2].\n    + left.\n      destruct H2 as [w [H2 H4]].\n      specialize (H3 w).\n      destruct H3 as [H3 _].\n      exists w.\n      split.\n      * apply H3.\n        exact H2.\n      * exact H4.\n    + right.\n      intros H4.\n      apply H2.\n      destruct H4 as [w [H4 H5]].\n      specialize (H3 w).\n      destruct H3 as [_ H3].\n      exists w.\n      split.\n      * apply H3.\n        exact H4.\n      * exact H5.\n  }\ndestruct H2 as [g' [H2 H4]].\n(* Change g for g' *)\napply lang_eq_change_g with (non_terminal':= chomsky.non_terminal' (emptyrules.non_terminal' non_terminal) terminal) (g':= g') in H3.\n- assert (H3':= H3).\n  assert (H3copy:= H3).\n  destruct (rules_finite g') as [n' [ntl' [tl' H5]]].\n  assert (H5':= H5).\n  assert (H5'':= H5).\n  (* exists n *)\n  exists (2 ^ ((length ntl') - 1) + 1).\n  intros s H6 H7.\n  specialize (H3 s). \n  destruct H3 as [H3 _].\n  specialize (H3 H6).\n  assert (H6':= H6).\n  unfold lang_of_g in H3.\n  destruct H4 as [H4 H4'].  \n  assert (H4copy:= H4).\n  unfold produces, generates in H3.\n  (* Find btree *)\n  apply derives_g_cnf_equiv_btree_v4 with (n:= start_symbol g') (s:= s) in H4.\n  + destruct H4 as [t [H4 [H8 H9]]].\n    clear g H1 H2 H3 H5 H6.\n    apply length_ge_v2 with (t:= t) in H7.\n    assert (HHH:= H7).      \n    * (* Find bpath *)\n      {\n      apply btree_exists_bpath with (ntl:= ntl') in H7.\n      - destruct H7 as [z [H20 [H21 [m [r [t0 [H22 [H23 [H24 H25]]]]]]]]].\n        assert (H26: forall s, In s r -> In s (map inl ntl')).\n          {\n          intros s0 H27.\n          specialize (H25 s0).\n          apply H25.\n          apply in_or_app.\n          right.\n          exact H27.\n          }\n        clear H25.\n        assert (H27: exists r': list (non_terminal' (emptyrules.non_terminal' non_terminal) terminal), r = map inl r').\n          {\n          exists (get_As _ _ r).\n          apply get_As_correct.\n          intros e H28.\n          specialize (H26 e H28).\n          apply in_split in H26.\n          destruct H26 as [l1 [l2 H26]].\n          symmetry in H26.\n          apply map_expand in H26.\n          destruct H26 as [s1' [s2' [_ [_ H26]]]].\n          symmetry in H26. \n          change (e :: l2) with ([e] ++ l2) in H26.\n          apply map_expand in H26.\n          destruct H26 as [s1'0 [s2'0 [_ [H26 _]]]].\n          destruct s1'0.\n          - simpl in H26.\n            inversion H26. \n          - simpl in H26.\n            inversion H26.\n            exists n.\n            reflexivity.\n          }\n        destruct H27 as [r' H27].\n        assert (H28: length r' = length r).\n          {\n          rewrite H27.\n          rewrite map_length.\n          reflexivity.\n          }\n        assert (H24':= H24).\n        rewrite <- H28 in H24.\n        rewrite H27 in H26.\n        assert (H29: forall n: non_terminal' (emptyrules.non_terminal' non_terminal) terminal, In n r' -> In n ntl').\n          {\n          intros n H99.\n          assert (H29: In (inl n) (map (@inl _ terminal) r')).\n            {\n            apply in_map.\n            exact H99.\n            }\n          specialize (H26 (inl n) H29).\n          apply in_split in H26.\n          destruct H26 as [l1 [l2 H26]].\n          symmetry in H26.\n          apply map_expand in H26.\n          destruct H26 as [s1' [s2' [H40 [H41 H42]]]].\n          symmetry in H42.\n          change (inl n :: l2) with ([inl n] ++ l2) in H42.\n          apply map_expand in H42.\n          destruct H42 as [s1'0 [s2'0 [H42 [H43 H44]]]].\n          destruct s1'0.\n          - simpl in H43.\n            inversion H43.\n          - simpl in H43.\n            inversion H43.\n            subst.\n            apply in_or_app.\n            right.\n            simpl.\n            left.\n            reflexivity.\n          }\n        apply pigeon in H29.\n        + destruct H29 as [n [r1' [r2' [r3' H29]]]].\n          rewrite H29 in H27.\n          repeat rewrite map_app in H27.\n          (* Prepare path *)\n          assert (Hpath:= H22).\n          rewrite H27 in Hpath.\n          repeat rewrite <- app_assoc in Hpath.\n          assert (H20copy:= H20). \n          rewrite Hpath in H20copy.\n          apply bpath_insert_head in H20copy.\n          * destruct H20copy as [p12' H20copy].\n            rewrite app_assoc in Hpath.\n            rewrite <- H20copy in Hpath.\n            rewrite <- app_assoc in Hpath.\n            (* Find subtrees and u, v, w, x, y *)\n            apply bpath_exists_bcode in H20.\n            destruct H20 as [c [H100 H101]].\n            rewrite Hpath in H101.\n            rewrite app_assoc in H101.\n            assert (H101copy:= H101).\n            {\n            apply bcode_split in H101.\n            - destruct H101 as [c1 [c2 [H101 [H102 [t1 [u [y [H104 [H105 H106]]]]]]]]].\n              assert (H105copy:= H105).\n              assert (Ht:= H105).\n              apply btree_decompose_bfrontier in H105.\n              destruct H105 as [Ht_a Ht_b].\n              assert (Hc1: c1 <> []).\n                {\n                simpl in H102.\n                assert (length c1 > 0) by omega.\n                apply length_not_zero in H.\n                apply not_eq_sym.\n                exact H.\n                }\n              specialize (Ht_b Hc1).\n              assert (Ht_c: subtree_bcode t t1 c1).\n                {\n                apply btree_decompose_subtree_bcode in H105copy.\n                - exact H105copy.\n                - exact Hc1.\n                }\n              rewrite app_assoc in H104.\n              assert (H104copy:= H104).\n              apply bcode_split in H104.\n              + destruct H104 as [c3 [c4 [H104 [H107 [t2 [v [x [H109 [H110 H111]]]]]]]]].\n                assert (H110copy:= H110).\n                assert (Ht1:= H110).\n                apply btree_decompose_bfrontier in H110.\n                destruct H110 as [Ht1_a Ht1_b].\n                assert (Hc3: c3 <> []).\n                  {\n                  simpl in H107.\n                  assert (length c3 > 0) by omega.\n                  apply length_not_zero in H.\n                  apply not_eq_sym.\n                  exact H.\n                  }\n                specialize (Ht1_b Hc3).\n                assert (Ht1_c: subtree_bcode t1 t2 c3).\n                  {\n                  apply btree_decompose_subtree_bcode in H110copy.\n                  - exact H110copy.\n                  - exact Hc3.\n                  }\n                remember (bfrontier t2) as w.\n                (* Find roots *)\n                assert (Hroot_t1: broot t1 = n).\n                  {\n                  apply bpath_bcode_split in H104copy.\n                  destruct H104copy as [H104copy _].\n                  apply bpath_broot with (d:= inl (broot t1)) in H104copy.\n                  simpl in H104copy.\n                  inversion H104copy.\n                  reflexivity.\n                  }\n                assert (Hroot_t2: broot t2 = n).\n                  {\n                  apply bpath_bcode_split in H109.\n                  destruct H109 as [H109 _].\n                  apply bpath_broot with (d:= inl (broot t2)) in H109.\n                  simpl in H109.\n                  inversion H109.\n                  reflexivity.\n                  }\n                (* Find heights *)\n                remember (length ntl') as k.\n                assert (H114: bheight t1 <= k + 1 /\\ bheight t1 >= 2).\n                  {\n                  split.\n                  - rewrite H106.\n                    rewrite H27 in H24'.\n                    repeat rewrite app_length in H24'.\n                    repeat rewrite app_length.\n                    simpl in H24'.\n                    simpl.\n                    omega.\n                  - rewrite H106.\n                    rewrite H27 in H24'.\n                    repeat rewrite app_length in H24'.\n                    repeat rewrite app_length.\n                    simpl in H24'.\n                    simpl.\n                    omega.\n                  }\n                assert (H115: bheight t2 <= k /\\ bheight t2 >= 1).\n                  {\n                  split.\n                  - rewrite H111.\n                    rewrite H27 in H24'.\n                    repeat rewrite app_length in H24'.\n                    repeat rewrite app_length.\n                    simpl in H24'.\n                    simpl.\n                    omega.\n                  - rewrite H111.\n                    rewrite H27 in H24'.\n                    repeat rewrite app_length in H24'.\n                    repeat rewrite app_length.\n                    simpl in H24'.\n                    simpl.\n                    omega.\n                  }\n                (* Exists u, v, w, x, y *)\n                exists u, v, w, x, y.\n                split.\n                * (* s = u ++ v ++ w ++ x ++ y *)\n                  rewrite <- H9.\n                  rewrite Ht_a.\n                  rewrite Ht1_a.\n                  repeat rewrite <- app_assoc.\n                  reflexivity.\n                * {\n                  split.\n                  - (* length (v ++ x) >= 1 *)\n                    apply length_not_zero_inv in Ht1_b.\n                    omega.\n                  - split.\n                    + (* length (v ++ w ++ x) <= 2 ^ k *)\n                      destruct H114 as [H114 H116].\n                      apply bheight_le in H114.\n                      rewrite Ht1_a in H114.\n                      replace (k + 1 - 1) with k in H114.\n                      * {\n                        replace ((2 ^ (k - 1) + 1 - 1) * 2) with (2 ^ k).\n                        - exact H114.\n                        - replace (2 ^ (k - 1) + 1 - 1) with (2 ^ (k - 1)).\n                          + replace k with (k - 1 + 1) at 1. \n                            * rewrite Nat.pow_add_r.\n                              simpl. \n                              reflexivity. \n                            * omega. \n                          + omega.\n                        }\n                      * omega. \n                    + (* uv^iwx^iy *)\n                      intros i.\n                      assert (Ht': exists t': btree _ _, \n                                   btree_cnf g' t' /\\\n                                   broot t' = n /\\\n                                   btree_decompose t' (iter c3 i) = Some (iter v i, t2, iter x i) /\\\n                                   bcode t' (iter c3 i ++ c4) /\\\n                                   get_nt_btree (iter c3 i) t' = Some n).\n                        {\n                        apply pumping_aux with (g:= g') (t1:= t1) (t2:= t2) (n:= n) (c1:= c3) (c2:= c4) (v:= v) (x:= x) (i:= i).\n                        - exact Ht1. \n                        - apply subtree_bcode_subtree in Ht_c.\n                          apply btree_cnf_subtree with (g:= g') in Ht_c.\n                          + exact Ht_c.\n                          + exact H4.\n                        - exact Hroot_t1.\n                        - rewrite <- H104.\n                          apply bpath_bcode_split in H104copy. \n                          apply H104copy.\n                        - exact Hc3.\n                        - congruence.\n                        - apply bpath_bcode_split in H109.\n                          apply H109.\n                        }\n                      destruct Ht' as [t' [Ht'_1 [Ht'_2 [Ht'_3 Ht'_4]]]].\n                      assert (Ht'': exists t'': btree _ _, btree_subst t t' c1 = Some t'').\n                        {\n                        rewrite H101 in H100.\n                        apply bcode_btree_subst with (t2:= t') in H100.\n                        destruct H100 as [t'' H100].\n                        exists t''.\n                        exact H100.\n                        }\n                      destruct Ht'' as [t'' Ht''].\n                      assert (Ht''_1: broot t'' = start_symbol g').\n                        {\n                        apply btree_subst_preserves_broot_v2 in Ht''. \n                        - congruence. \n                        - exact Hc1.\n                        }\n                      assert (Ht''_2: bfrontier t'' = u ++ iter v i ++ w ++ iter x i ++ y).\n                        {\n                        apply btree_subst_bfrontier with (t2:= t1) (x:= u) (y:= y) in Ht''.\n                        - apply btree_decompose_bfrontier in Ht'_3.\n                          destruct Ht'_3 as [Ht'_3 _].\n                          rewrite Ht'_3 in Ht''.\n                          rewrite Heqw.\n                          repeat rewrite <- app_assoc in Ht''.\n                          exact Ht''.\n                        - exact Ht_c.\n                        - exact Ht. \n                        }\n                      assert (Ht''_3: btree_cnf g' t'').\n                        {\n                        apply btree_subst_preserves_cnf with (g:= g') (c1':= c3 ++ c4) in Ht''.\n                        - exact Ht''.\n                        - exact H4.\n                        - rewrite <- H104.\n                          rewrite <- H101.\n                          exact H100.\n                        - exact Ht'_1.\n                        - apply btree_decompose_get_nt in Ht.\n                          congruence.\n                        }\n                      apply btree_equiv_produces_g_cnf in Ht''_3.\n                      * unfold lang_eq in H3'.\n                        specialize (H3' (u ++ iter v i ++ w ++ iter x i ++ y)).\n                        destruct H3' as [_ H3'].\n                        unfold lang_of_g in H3'.\n                        apply H3'.\n                        rewrite <- Ht''_2.\n                        exact Ht''_3.\n                      * congruence.\n                  }\n              + rewrite app_length.\n                simpl.\n                omega.\n              + repeat rewrite app_length.\n                simpl.\n                omega.\n              + rewrite H106.\n                repeat rewrite app_length.\n                reflexivity.\n            - rewrite app_length.\n              simpl.\n              omega.\n            - repeat rewrite app_length.\n              simpl.\n              omega.\n            - rewrite Hpath in H21.\n              repeat rewrite app_length in H21.\n              repeat rewrite app_length.\n              omega.\n            }\n          * rewrite H8.\n            {\n            apply start_symbol_only_once with (g:= g') (t:= t) (p1:= m ++ map inl r1') (p2:= map inl r2') (p3:= map inl r3' ++ [inr t0]).\n            - exact H4'.\n            - exact H4.\n            - repeat rewrite <- app_assoc. \n              exact H20copy.\n            }\n        + apply (nt_eqdec g').\n        + rewrite H28.\n          exact H24'.\n      - apply cnf_bnts with (g:= g') (n:= n') (tl:= tl').\n        + exact H5'.\n        + exact H4.\n      }\n    * destruct H5'' as [H5'' _].\n      apply in_split in H5''.\n      destruct H5'' as [l1 [l2 H5'']].\n      rewrite H5''.\n      rewrite app_length.\n      change (start_symbol g' :: l2) with ([start_symbol g'] ++ l2).\n      rewrite app_length.\n      simpl.\n      omega.\n    * exact H9.\n  + assert (Hntl': 2 ^ length ntl' > 0).\n      {\n      apply pow_2_gt_0.\n      }\n    assert (Hs: length s > 0) by omega.\n    apply length_not_zero in Hs.\n    apply not_eq_sym.\n    exact Hs.\n  + exact H4'.\n  + exact H3.\n- exact H2.\nQed.\n\nEnd Pumping_2.\n", "meta": {"author": "mvmramos", "repo": "pumping", "sha": "d8e2db890a4eb2c25bb0ef8efffa1d83031619f9", "save_path": "github-repos/coq/mvmramos-pumping", "path": "github-repos/coq/mvmramos-pumping/pumping-d8e2db890a4eb2c25bb0ef8efffa1d83031619f9/pumping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.7853085758631158, "lm_q1q2_score": 0.678028827359403}}
{"text": "Require Import rt.util.all.\nRequire Import rt.model.arrival.basic.task rt.model.arrival.basic.job rt.model.priority.\nRequire Import rt.model.schedule.global.workload.\nRequire Import rt.model.schedule.global.basic.schedule.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.\n\nModule Interference.\n\n  Import Schedule ScheduleOfSporadicTask Priority Workload.\n\n  Section InterferenceDefs.\n\n    Context {sporadic_task: eqType}.\n    Context {Job: eqType}.\n    Variable job_arrival: Job -> time.\n    Variable job_cost: Job -> time.\n    Variable job_task: Job -> sporadic_task.\n\n    (* Assume any job arrival sequence...*)\n    Variable arr_seq: arrival_sequence Job.\n\n    (* ... and any schedule. *)\n    Context {num_cpus: nat}.\n    Variable sched: schedule Job num_cpus.\n\n    (* Consider any job j that incurs interference. *)\n    Variable j: Job.\n\n    (* Recall the definition of backlogged (pending and not scheduled). *)\n    Let job_is_backlogged (t: time) :=\n      backlogged job_arrival job_cost sched j t.\n\n    (* First, we define total interference. *)\n    Section TotalInterference.\n      \n      (* The total interference incurred by job j during [t1, t2) is the\n         cumulative time in which j is backlogged in this interval. *)\n      Definition total_interference (t1 t2: time) :=\n        \\sum_(t1 <= t < t2) job_is_backlogged t.\n\n    End TotalInterference.\n\n    (* Next, we define job interference. *)    \n    Section JobInterference.\n\n      (* Let job_other be a job that interferes with j. *)\n      Variable job_other: Job.\n\n      (* The interference caused by job_other during [t1, t2) is the cumulative\n         time in which j is backlogged while job_other is scheduled. *)\n      Definition job_interference (t1 t2: time) :=\n        \\sum_(t1 <= t < t2)\n          \\sum_(cpu < num_cpus)\n            (job_is_backlogged t && scheduled_on sched job_other cpu t).\n\n    End JobInterference.\n\n    (* Next, we define task interference. *)\n    Section TaskInterference.\n\n      (* In order to define task interference, consider any interfering task tsk_other. *)\n      Variable tsk_other: sporadic_task.\n      \n      (* The interference caused by tsk during [t1, t2) is the cumulative time\n         in which j is backlogged while tsk is scheduled. *)\n      Definition task_interference (t1 t2: time) :=\n        \\sum_(t1 <= t < t2)\n          \\sum_(cpu < num_cpus)\n            (job_is_backlogged t &&\n            task_scheduled_on job_task sched tsk_other cpu t).\n\n    End TaskInterference.\n\n    (* Next, we define an approximation of the total interference based on\n       each per-task interference. *)\n    Section TaskInterferenceJobList.\n\n      Variable tsk_other: sporadic_task.\n\n      Definition task_interference_joblist (t1 t2: time) :=\n        \\sum_(j <- jobs_scheduled_between sched t1 t2 | job_task j == tsk_other)\n         job_interference j t1 t2.\n\n    End TaskInterferenceJobList.\n\n    (* Now we prove some basic lemmas about interference. *)\n    Section BasicLemmas.\n\n      (* First, we show that the total interference cannot be larger than the interval length. *)\n      Lemma total_interference_le_delta :\n        forall t1 t2,\n          total_interference t1 t2 <= t2 - t1.\n      Proof.\n        unfold total_interference; intros t1 t2.\n        apply leq_trans with (n := \\sum_(t1 <= t < t2) 1);\n          first by apply leq_sum; ins; apply leq_b1.\n        by rewrite big_const_nat iter_addn mul1n addn0 leqnn.\n      Qed.\n\n      (* Next, we show that job interference is bounded by the service of the interfering job. *)\n      Lemma job_interference_le_service :\n        forall j_other t1 t2,\n          job_interference j_other t1 t2 <= service_during sched j_other t1 t2.\n      Proof.\n        intros j_other t1 t2; unfold job_interference, service_during.\n        apply leq_sum; intros t _.\n        unfold service_at; rewrite [\\sum_(_ < _ | scheduled_on _ _ _  _)_]big_mkcond.\n        apply leq_sum; intros cpu _.\n        destruct (job_is_backlogged t); [rewrite andTb | by rewrite andFb].\n        by destruct (scheduled_on sched j_other cpu t).\n      Qed.\n      \n      (* We also prove that task interference is bounded by the workload of the interfering task. *)\n      Lemma task_interference_le_workload :\n        forall tsk t1 t2,\n          task_interference tsk t1 t2 <= workload job_task sched tsk t1 t2.\n      Proof.\n        unfold task_interference, workload; intros tsk t1 t2.\n        apply leq_sum; intros t _.\n        apply leq_sum; intros cpu _.\n        destruct (job_is_backlogged t); [rewrite andTb | by rewrite andFb].\n        unfold task_scheduled_on, service_of_task.\n        by destruct (sched cpu t).\n      Qed.\n\n    End BasicLemmas.\n\n    (* Now we prove some bounds on interference for sequential jobs. *)\n    Section InterferenceSequentialJobs.\n\n      (* If jobs are sequential, ... *)\n      Hypothesis H_sequential_jobs: sequential_jobs sched.\n    \n      (* ... then the interference incurred by a job in an interval\n         of length delta is at most delta. *)\n      Lemma job_interference_le_delta :\n        forall j_other t1 delta,\n          job_interference j_other t1 (t1 + delta) <= delta.\n      Proof.\n        rename H_sequential_jobs into SEQ.\n        unfold job_interference, sequential_jobs in *.\n        intros j_other t1 delta.\n        apply leq_trans with (n := \\sum_(t1 <= t < t1 + delta) 1);\n          last by rewrite big_const_nat iter_addn mul1n addn0 addKn leqnn.\n        apply leq_sum; intros t _.\n        destruct ([exists cpu, scheduled_on sched j_other cpu t]) eqn:EX.\n        {\n          move: EX => /existsP [cpu SCHED].\n          rewrite (bigD1 cpu) // /=.\n          rewrite big_mkcond (eq_bigr (fun x => 0)) /=;\n            first by simpl_sum_const; rewrite leq_b1.\n          intros cpu' _; des_if_goal; last by done.\n          destruct (scheduled_on sched j_other cpu' t) eqn:SCHED'; last by rewrite andbF.\n          move: SCHED SCHED' => /eqP SCHED /eqP SCHED'.\n          by specialize (SEQ j_other t cpu cpu' SCHED SCHED'); rewrite SEQ in Heq.\n        }\n        {\n          apply negbT in EX; rewrite negb_exists in EX.\n          move: EX => /forallP EX.\n          rewrite (eq_bigr (fun x => 0)); first by simpl_sum_const.\n          by intros cpu _; specialize (EX cpu); apply negbTE in EX; rewrite EX andbF.\n        }\n      Qed.\n\n    End InterferenceSequentialJobs.\n\n    (* Next, we show that the cumulative per-task interference bounds the total\n       interference. *)\n    Section BoundUsingPerJobInterference.\n      \n      Lemma interference_le_interference_joblist :\n        forall tsk t1 t2,\n          task_interference tsk t1 t2 <= task_interference_joblist tsk t1 t2.\n      Proof.\n        intros tsk t1 t2.\n        unfold task_interference, task_interference_joblist, job_interference, job_is_backlogged.\n        rewrite [\\sum_(_ <- _ sched _ _ | _) _]exchange_big /=.\n        rewrite big_nat_cond [\\sum_(_ <= _ < _ | true) _]big_nat_cond.\n        apply leq_sum; move => t /andP [LEt _].\n        rewrite exchange_big /=.\n        apply leq_sum; intros cpu _.\n        destruct (backlogged job_arrival job_cost sched j t) eqn:BACK;      \n          last by rewrite andFb (eq_bigr (fun x => 0));\n            first by rewrite big_const_seq iter_addn mul0n addn0.\n        rewrite andTb.\n        destruct (task_scheduled_on job_task sched tsk cpu t) eqn:SCHED; last by done.\n        unfold scheduled_on, task_scheduled_on in *.\n        destruct (sched cpu t) as [j' |] eqn:SOME; last by done.\n        rewrite big_mkcond /= (bigD1_seq j') /=; last by apply undup_uniq.\n        {\n          by rewrite SCHED eq_refl.\n        }\n        {\n          unfold jobs_scheduled_between.\n          rewrite mem_undup; apply mem_bigcat_nat with (j := t); first by done.\n          apply mem_bigcat_ord with (j := cpu); first by apply ltn_ord.\n          by unfold make_sequence; rewrite SOME mem_seq1 eq_refl.\n        }\n      Qed.\n        \n    End BoundUsingPerJobInterference.\n    \n  End InterferenceDefs.\n\nEnd Interference.", "meta": {"author": "cd-public", "repo": "rt-proofs", "sha": "ebef0b65460fe009c51f638fe2b459f16a6d1dd5", "save_path": "github-repos/coq/cd-public-rt-proofs", "path": "github-repos/coq/cd-public-rt-proofs/rt-proofs-ebef0b65460fe009c51f638fe2b459f16a6d1dd5/model/schedule/global/basic/interference.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6780048825761376}}
{"text": "Require Import Ensembles ssrfun Description Relations_1 IndefiniteDescription\n  Classical_Prop.\n\nArguments In {U} _ _.\nArguments Included {U} _ _.\nArguments Same_set {U}.\nArguments Equivalence {U}.\n\nModule base.\n\nSection definition.\n\nDefinition map {A B : Type} (f : A -> B) (X : Ensemble A) (Y : Ensemble B) :=\n  forall x, In X x -> exists y, In Y y /\\ f x = y.\n\nDefinition injective1 {A B : Type} (f : A -> B) (X : Ensemble A) (Y : Ensemble B) :=\n  map f X Y /\\ forall a b, a <> b -> f a <> f b.\n\nDefinition injective2 {A B : Type} (f : A -> B) (X : Ensemble A) (Y : Ensemble B) :=\n  map f X Y /\\ forall a b, f a = f b -> a = b.\n\nDefinition surjective {A B : Type} (f : A -> B) (X : Ensemble A) (Y : Ensemble B) :=\n  map f X Y /\\ forall b, exists a, f a = b.\n\nDefinition bijective {A B : Type} (f : A -> B) (X : Ensemble A) (Y : Ensemble B) :=\n  surjective f X Y /\\ injective2 f X Y.\n\nInductive invertible {X Y:Type} (f:X->Y) : Prop :=\n  | intro_invertible: forall g:Y->X,\n  (forall x:X, g (f x) = x) -> (forall y:Y, f (g y) = y) ->\n  invertible f.\n\nDefinition operation {A B D : Type} (f : A -> B -> D) \n  (X : Ensemble A) (Y : Ensemble B) (Z : Ensemble D) :=\n  forall x y, In X x -> In Y y -> exists z, In Z z /\\ f x y = z.\n\nDefinition one_operation {A : Type} (f : A -> A) (X Y : Ensemble A) := \n  map f X Y.\n\nDefinition binary_operation {A : Type} (f : A -> A -> A) (X : Ensemble A) := \n  operation f X X X.\n\n(* 同态映射 *)\nDefinition homomorphism_map {A B : Type} (X : Ensemble A) (Y : Ensemble B) \n  (f : A -> A -> A) (g : B -> B -> B) (h : A -> B) :=\n  binary_operation f X /\\ binary_operation g Y /\\ map h X Y /\\ \n  forall a b, h (f a b) = g (h a) (h b).\n\n(* 同态满射 *)\nDefinition homomorphism {A B : Type} (X : Ensemble A) (Y : Ensemble B) \n  (f : A -> A -> A) (g : B -> B -> B) (h : A -> B) :=\n  binary_operation f X /\\ binary_operation g Y /\\ surjective h X Y /\\ \n  forall a b, h (f a b) = g (h a) (h b).\n\n(* 同构 *)\nDefinition isomorphism {A B : Type} (X : Ensemble A) (Y : Ensemble B) \n  (f : A -> A -> A) (g : B -> B -> B) (h : A -> B) :=\n  binary_operation f X /\\ binary_operation g Y /\\ bijective h X Y /\\ \n  forall a b, h (f a b) = g (h a) (h b).\n\nDefinition exists_solution {A : Type} (f : A -> A -> A) (X : Ensemble A) :=\n  forall a b, (exists x, f a x = b) /\\ (exists y,f y a = b). \n\n(* A不为空 *)\nDefinition notEmpty {A : Type} (X : Ensemble A) := \n  exists a, In X a.\n\nLemma injec {A B : Type} (f : A -> B) (X : Ensemble A) (Y : Ensemble B) :\n  injective1 f X Y <-> injective2 f X Y.\nProof.\n  split; intros.\n  - destruct H. split; auto; intros.\n    generalize (classic (a = b)); intros.\n    destruct H2; auto. apply H0 in H2; auto.\n    contradiction.\n  - destruct H. split; auto.\nQed. \n\n(* 可证 *)\nLemma logic_pro : forall (P Q : Prop), (P -> Q) -> (~ Q -> ~ P).\nProof.\n  intros; auto.\nQed.\n\nEnd definition.\n\nSection base_law.\n\nRecord assoc_law {A : Type} (X : Ensemble A) : Type := Assoc {\n  add :> A -> A -> A; (* 代数运算 *)\n  _ : binary_operation add X;\n  _ : associative add; (* 加法满足结合律 *)\n  _ : notEmpty X;\n}.\n\nEnd base_law.\n\nEnd base.\n\nExport base.\n\n\n", "meta": {"author": "Wangdake25", "repo": "Coq", "sha": "9affcd8a2699e31b818890ce46b65cfdca2c52c2", "save_path": "github-repos/coq/Wangdake25-Coq", "path": "github-repos/coq/Wangdake25-Coq/Coq-9affcd8a2699e31b818890ce46b65cfdca2c52c2/base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6779569036568809}}
{"text": "Load \"Tactics4_Constructions.v\".\n\nSection BOLYAI.\n\n(* Quels que soient les points A B C *)\n(* si A B et C ne sont pas colineaires *)\n(* alors on sait construire un cercle gamma *)\n(* tel que A soit sur gamma et B soit sur gamma et C soit sur gamma. *)\n\nTheorem Bolyai : forall A B C : Point,\n~ Collinear A B C ->\n{gamma : Circle | OnCircle gamma A /\\ OnCircle gamma B /\\ OnCircle gamma C}.\nProof.\n(* Soient A B C trois points, *)\n(* Soit H l'hypothese A , B et C non colineaires, *)\nintros.\n(* Soit d1 la mediatrice du segment [A,B], *)\nsetMidLine A B ipattern:d1.\n(* Soit d2 la mediatrice du segment [B,C], *)\nsetMidLine B C ipattern:d2.\n(* En utilisant les droites (AB) et (BC) il vient d1 et d2 sont secantes, *)\nfrom (Ruler A B H0, Ruler B C H4) (SecantLines d1 d2).\n(* Soit E le point d'intesection de d1 et d2, *)\nsetInterLines d1 d2 ipattern:E.\n(* Soit gamma le cercle de centre E et de rayon EB, *)\nsetCircle E E B ipattern:gamma.\n(* gamma repond a la question, *)\nanswerIs gamma.\n(* de l'hypothese H1 : pour tout point M, si M est sur d1, les distances MA et MB sont egales, il vient les distances EA et EB sont egales, *)\n from H1 (Distance E A = Distance E B).\n(* de l'hypothese H5 : pour tout point M, si M est sur d2, les distances MB et MC sont egales, il vient les distances EB et EC sont egales, *)\n from H5 (Distance E B = Distance E C).\nQed.\n\nEnd BOLYAI.\n", "meta": {"author": "coq-contribs", "repo": "euclidean-geometry", "sha": "06838851a5924918d98e5a9c07ffa84021e13af7", "save_path": "github-repos/coq/coq-contribs-euclidean-geometry", "path": "github-repos/coq/coq-contribs-euclidean-geometry/euclidean-geometry-06838851a5924918d98e5a9c07ffa84021e13af7/Bolyai.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6779552356916665}}
{"text": "Inductive T : Type :=\n  | Tbool\n  | Tarrow : T -> T -> T. \n\nSection t. \n\n  Variable V : T -> Type. \n  Inductive term : T -> Type :=\n  | Var : forall t, V t -> term t\n  | Abs : forall a b, (V a -> term b) -> term (Tarrow a b)\n  | App : forall a b, term (Tarrow a b) -> term a -> term b. \nEnd t.  \n\nDefinition Term t := forall V, term V t. \n\nArguments Abs {V a b} _. \nArguments Var {V t} _. \nExample K a b : Term (Tarrow a (Tarrow b a))  := fun V => Abs (fun x => Abs (fun y => Var x)). ", "meta": {"author": "braibant", "repo": "Synthesis", "sha": "922982aaddb8a7a16101ff304c45d24a6265dc2e", "save_path": "github-repos/coq/braibant-Synthesis", "path": "github-repos/coq/braibant-Synthesis/Synthesis-922982aaddb8a7a16101ff304c45d24a6265dc2e/talks/coq-2012/phoas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6779219985582136}}
{"text": "(*** Predicates on a list ***)\n\nRequire Import Arith.\nRequire Import Bool.\nRequire Import List.\nRequire Import Ott.ott_list_base.\nRequire Import Ott.ott_list_core.\nRequire Import Ott.ott_list_takedrop.\n\n\n\nSection List_predicate_inductive.\n(* Properties of [Forall_list] and [Exists_list] *)\n\nVariables A : Type.\nImplicit Types x : A.\nImplicit Types xs l : list A.\nImplicit Types p : A -> bool.\nImplicit Types P : A -> Prop.\nSet Implicit Arguments.\n\nLemma not_Exists_list_nil : forall P, ~(Exists_list P nil).\nProof. intros P H; inversion H. Qed.\nHint Resolve not_Exists_list_nil : core.\n\nLemma Forall_list_dec :\n  forall P (dec : forall x, {P x} + {~P x}) l,\n    {Forall_list P l} + {~Forall_list P l}.\nProof.\n  induction l; simpl in * . solve [auto].\n  destruct (dec a); [destruct IHl | idtac]; auto;\n    right; intro; inversion_clear H; tauto.\nQed.\n\nLemma Exists_list_dec :\n  forall P (dec : forall x, {P x} + {~P x}) l,\n    {Exists_list P l} + {~Exists_list P l}.\nProof.\n  induction l; simpl in * . solve [auto].\n  destruct (dec a); [idtac | destruct IHl]; auto;\n    right; intro; inversion_clear H; tauto.\nQed.\n\nLemma Forall_Exists_list_dec :\n  forall P Q (dec : forall x, {P x} + {Q x}) l,\n    {Forall_list P l} + {Exists_list Q l}.\nProof.\n  induction l; simpl in * . solve [auto].\n  destruct (dec a); destruct IHl; auto.\nQed.\n\nLemma Forall_list_In :\n  forall P x l, In x l -> Forall_list P l -> P x.\nProof.\n  induction l; intros; simpl in *; destruct H;\n    inversion H0; subst; auto.\nQed.\n\nLemma In_Forall_list :\n  forall P l, (forall x, In x l -> P x) -> Forall_list P l.\nProof.\n  induction l; constructor; firstorder.\nQed.\n\nLemma exists_In_Exists_list :\n  forall P l, Exists_list P l -> exists x, In x l /\\ P x.\nProof.\n  induction 1.\n  exists x; simpl; tauto.\n  elim IHExists_list; intros. exists x0; simpl; tauto.\nQed.\n\nLemma Forall_list_app_left :\n  forall P l l', Forall_list P (l++l') -> Forall_list P l.\nProof.\n  intros; induction l; simpl in * . auto.\n  inversion_clear H. auto.\nQed.\nLemma Forall_list_app_right :\n  forall P l l', Forall_list P (l++l') -> Forall_list P l'.\nProof.\n  induction l; intros. auto. inversion_clear H; auto.\nQed.\nLemma app_Forall_list :\n  forall P l l', Forall_list P l -> Forall_list P l' -> Forall_list P (l++l').\nProof.\n  intros; induction l; simpl in * . assumption.\n  inversion_clear H. auto.\nQed.\nHint Resolve app_Forall_list Forall_list_app_left Forall_list_app_right : core.\n\nLemma Exists_list_app_or :\n  forall P l l', Exists_list P (l++l') ->\n    Exists_list P l \\/ Exists_list P l'.\nProof.\n  intros; induction l; simpl in * . solve [auto].\n  inversion_clear H. solve [auto].\n  destruct (IHl H0); solve [auto].\nQed.\nLemma app_Exists_list_left :\n  forall P l l', Exists_list P l -> Exists_list P (l++l').\nProof.\n  intros; induction l; inversion_clear H; simpl; auto.\nQed.\nLemma app_Exists_list_right :\n  forall P l l', Exists_list P l' -> Exists_list P (l++l').\nProof.\n  intros; induction l; simpl; auto.\nQed.\nHint Resolve Exists_list_app_or app_Exists_list_left app_Exists_list_right : core.\n\nLemma rev_Forall_list :\n  forall P l, Forall_list P l -> Forall_list P (rev l).\nProof. induction 1; simpl; auto. Qed.\nLemma rev_Exists_list :\n  forall P l, Exists_list P l -> Exists_list P (rev l).\nProof. induction 1; simpl; auto. Qed.\nLemma Forall_list_rev :\n  forall P l, Forall_list P (rev l) -> Forall_list P l.\nProof.\n  intros. rewrite <- (rev_involutive l). apply rev_Forall_list; assumption.\nQed.\nLemma Exists_list_rev :\n  forall P l, Exists_list P (rev l) -> Exists_list P l.\nProof.\n  intros. rewrite <- (rev_involutive l). apply rev_Exists_list; assumption.\nQed.\n\nLemma take_Forall_list :\n  forall P n l, Forall_list P l -> Forall_list P (take n l).\nProof.\n  intros; generalize dependent n; induction l; intros;\n    inversion_clear H; destruct n; simpl; auto.\nQed.\nLemma drop_Forall_list :\n  forall P n l, Forall_list P l -> Forall_list P (drop n l).\nProof.\n  intros; generalize dependent n; induction l; intros;\n    inversion_clear H; destruct n; simpl; auto.\nQed.\nLemma Forall_list_take_drop :\n  forall P n l,\n    Forall_list P (take n l) -> Forall_list P (drop n l) -> Forall_list P l.\nProof. intros; rewrite <- (take_app_drop l n); auto. Qed.\n\nLemma take_drop_Exists_list :\n  forall P n l, Exists_list P l ->\n    Exists_list P (take n l) \\/ Exists_list P (drop n l).\nProof. intros; rewrite <- (take_app_drop l n) in H; auto. Qed.\nLemma Exists_list_take :\n  forall P n l, Exists_list P (take n l) -> Exists_list P l.\nProof. intros; rewrite <- (take_app_drop l n); auto. Qed.\nLemma Exists_list_drop :\n  forall P n l, Exists_list P (drop n l) -> Exists_list P l.\nProof. intros; rewrite <- (take_app_drop l n); auto. Qed.\n\nLemma Forall_list_implies :\n  forall (P Q:A->Prop) xs,\n    (forall x, In x xs -> P x -> Q x) ->\n    Forall_list P xs -> Forall_list Q xs.\nProof. induction 2; firstorder. Qed.\nLemma Exists_list_implies :\n  forall (P Q:A->Prop) xs,\n    (forall x, In x xs -> P x -> Q x) ->\n    Exists_list P xs -> Exists_list Q xs.\nProof. induction 2; firstorder. Qed.\n\nEnd List_predicate_inductive.\n\nHint Resolve not_Exists_list_nil : lists.\nHint Resolve In_Forall_list : lists.\nHint Resolve Forall_list_app_left Forall_list_app_right : lists.\nHint Resolve app_Forall_list Exists_list_app_or : lists.\nHint Resolve app_Exists_list_left app_Exists_list_right : lists.\nHint Resolve rev_Forall_list rev_Exists_list : lists.\nHint Resolve Forall_list_rev Exists_list_rev : lists.\nHint Resolve take_Forall_list drop_Forall_list Forall_list_take_drop\n             take_drop_Exists_list Exists_list_take Exists_list_drop\n             : take_drop.\nHint Resolve Forall_list_implies Exists_list_implies : lists.\n\n\n\nSection List_predicate_fold.\n(* Properties of [forall_list] and [exists_list] *)\n\nVariables A : Type.\nImplicit Types x : A.\nImplicit Types xs l : list A.\nImplicit Types p : A -> bool.\nImplicit Types P : A -> Prop.\nSet Implicit Arguments.\n\nLemma forall_list_eq_fold_left_map :\n  forall p l,\n    forall_list p l = fold_left andb (map p l) true.\nProof.\n  unfold forall_list; intros. generalize true.\n  induction l; intros; simpl in * . reflexivity.\n  rewrite IHl. reflexivity.\nQed.\nLemma forall_list_eq_fold_right_map :\n  forall p l,\n    forall_list p l = fold_right andb true (map p l).\nProof.\n  intros. rewrite forall_list_eq_fold_left_map.\n  apply fold_symmetric; auto with bool.\nQed.\nLemma forall_list_eq_fold_left :\n  forall p l,\n    forall_list p l = fold_left (fun b z => b && p z) l true.\nProof. auto. Qed.\nLemma forall_list_eq_fold_right :\n  forall p l,\n    forall_list p l = fold_right (fun z b => b && p z) true l.\nProof.\n  intros; rewrite forall_list_eq_fold_right_map.\n  induction l; simpl. reflexivity. rewrite IHl. auto with bool.\nQed.\n\nLemma exists_list_eq_fold_left_map :\n  forall p l,\n    exists_list p l = fold_left orb (map p l) false.\nProof.\n  unfold exists_list; intros. generalize false.\n  induction l; intros; simpl in * . reflexivity.\n  rewrite IHl. reflexivity.\nQed.\nLemma exists_list_eq_fold_right_map :\n  forall p l,\n    exists_list p l = fold_right orb false (map p l).\nProof.\n  intros. rewrite exists_list_eq_fold_left_map.\n  apply fold_symmetric; auto with bool.\nQed.\nLemma exists_list_eq_fold_left :\n  forall p l,\n    exists_list p l = fold_left (fun b z => b || p z) l false.\nProof. auto. Qed.\nLemma exists_list_eq_fold_right :\n  forall p l,\n    exists_list p l = fold_right (fun z b => b || p z) false l.\nProof.\n  intros; rewrite exists_list_eq_fold_right_map.\n  induction l; simpl. reflexivity. rewrite IHl. auto with bool.\nQed.\n\nLemma forall_list_extensionality :\n  forall p p' l, (forall x, p x = p' x) -> forall_list p l = forall_list p' l.\nProof.\n  intros; repeat rewrite forall_list_eq_fold_right.\n  induction l; simpl. reflexivity. rewrite IHl; rewrite H. reflexivity.\nQed.\n\nLemma exists_list_extensionality :\n  forall p p' l, (forall x, p x = p' x) -> exists_list p l = exists_list p' l.\nProof.\n  intros; repeat rewrite exists_list_eq_fold_right.\n  induction l; simpl. reflexivity. rewrite IHl; rewrite H. reflexivity.\nQed.\n\nEnd List_predicate_fold.\n\n\n\nSection List_predicate_relationship.\n\nVariables A : Type.\nImplicit Types x : A.\nImplicit Types xs l : list A.\nImplicit Types p : A -> bool.\nImplicit Types P : A -> Prop.\nSet Implicit Arguments.\n\n(* TODO: lemmas relating Forall_list and forall_list, Exists_list\n   and exists_list, forall_list and exists_list. *)\n\nLemma Forall_if_implies_if_forall :\n  forall P p l,\n    Forall_list (fun z => if p z then P z else ~P z) l ->\n    if forall_list p l then Forall_list P l else ~Forall_list P l.\nProof.\n  intros; rewrite forall_list_eq_fold_right.\n  induction H; simpl in * . apply Forall_nil.\n  destruct (fold_right (fun (z : A) (b : bool) => b && p z) true l).\n  destruct (p x); simpl. apply Forall_cons; assumption.\n  intro No; inversion No; tauto.\n  simpl; intro No; inversion No; tauto.\nQed.\n\nEnd List_predicate_relationship.\n\n\n\n(*** More about maps ***)\n\nSection List_predicate_map.\n\nVariables A B C : Type.\nImplicit Types x : A.\nImplicit Types y : B.\nImplicit Types z : C.\nImplicit Types xs l : list A.\nImplicit Types ys : list B.\nImplicit Types zs : list C.\nImplicit Types f : A -> B.\nImplicit Types g : B -> C.\nImplicit Types P : A -> Prop.\nImplicit Types Q : B -> Prop.\nImplicit Types R : C -> Prop.\nImplicit Types m n : nat.\nSet Implicit Arguments.\n\nLemma map_take :\n  forall f l n, map f (take n l) = take n (map f l).\nProof.\n  intros. generalize dependent n; induction l; intros.\n  destruct n; reflexivity.\n  destruct n. reflexivity. simpl; rewrite IHl; reflexivity.\nQed.\n\nLemma map_drop :\n  forall f l n, map f (drop n l) = drop n (map f l).\nProof.\n  intros. generalize dependent n; induction l; intros.\n  destruct n; reflexivity.\n  destruct n. reflexivity. simpl; rewrite IHl; reflexivity.\nQed.\n\nLemma Forall_list_implies_map :\n  forall P Q f l,\n    (forall x, P x -> Q (f x)) ->\n    Forall_list P l -> Forall_list Q (map f l).\nProof. induction 2; simpl; auto with lists. Qed.\nLemma Exists_list_implies_map :\n  forall P Q f l,\n    (forall x, P x -> Q (f x)) ->\n    Exists_list P l -> Exists_list Q (map f l).\nProof. induction 2; simpl; auto with lists. Qed.\n\nLemma Forall_list_map_implies :\n  forall P Q f l,\n    (forall x, Q (f x) -> P x) ->\n    Forall_list Q (map f l) -> Forall_list P l.\nProof.\n  intros. induction l; simpl in * . apply Forall_nil.\n  inversion_clear H0. auto with lists.\nQed.\nLemma Exists_list_map_implies :\n  forall P Q f l,\n    (forall x, Q (f x) -> P x) ->\n    Exists_list Q (map f l) -> Exists_list P l.\nProof.\n  intros. induction l; simpl in *;\n    inversion_clear H0; auto with lists.\nQed.\n\nLemma Forall_list_map_intro :\n  forall Q f l,\n    Forall_list (fun x => Q (f x)) l -> Forall_list Q (map f l).\nProof. induction 1; simpl; auto with lists. Qed.\nLemma Exists_list_map_intro :\n  forall Q f l,\n    Exists_list (fun x => Q (f x)) l -> Exists_list Q (map f l).\nProof. induction 1; simpl; auto with lists. Qed.\n\nLemma Forall_list_map_elim :\n  forall Q f l,\n    Forall_list Q (map f l) -> Forall_list (fun x => Q (f x)) l.\nProof.\n  intros. induction l; simpl in * . apply Forall_nil.\n  inversion_clear H. auto with lists.\nQed.\nLemma Exists_list_map_elim :\n  forall Q f l,\n    Exists_list Q (map f l) -> Exists_list (fun x => Q (f x)) l.\nProof.\n  intros. induction l; simpl in *;\n    inversion_clear H; auto with lists.\nQed.\n\nEnd List_predicate_map.\n\nHint Rewrite map_take map_drop : take_drop.\nHint Resolve Forall_list_implies_map Exists_list_implies_map : lists.\nHint Resolve Forall_list_map_implies Exists_list_map_implies : lists.\nHint Resolve Forall_list_map_intro Exists_list_map_intro : lists.\nHint Resolve Forall_list_map_elim Exists_list_map_elim : lists.\n\n(* Simplify hypotheses and goals involving [Forall_list]. Simplifications\n   involve rewriting [Forall_list ?P ?l] into equivalent statements\n   where [?l] is simpler. Recognised ``complex'' constructors for [?l]\n   are [nil], [cons], [app], [map], [rev]. In the goal, only\n   simplifications that do not solve or split the goal are considered.\n *)\nLtac simplify_Forall_list :=\n  let tmp := fresh \"tmp\" in (\n    repeat match goal with\n             | H : Forall_list ?P nil |- _ => clear H\n             | H : Forall_list ?P (cons ?a ?l) |- _ =>\n               inversion_clear H;\n               match goal with H':_ |- _ => rename H' into H end\n             | H : Forall_list ?P (app ?l0 ?l1) |- _ =>\n               rename H into tmp;\n               assert (H := Forall_list_app_right l0 l1 tmp);\n               generalize H; clear H;\n               assert (H := Forall_list_app_left l0 l1 tmp);\n               intro; match goal with H':_ |- _ =>\n                        move H' after tmp; simpl in H'\n                      end;\n               move H after tmp; clear tmp; simpl in H\n             | H : Forall_list ?P (map ?f ?l) |- _ =>\n               (*apply Forall_list_map_elim in H*) (*>=V8.1 only*)\n               rename H into tmp;\n               assert (H := Forall_list_map_elim f l tmp);\n               move H after tmp; clear tmp; simpl in H\n             | H : Forall_list ?P (rev ?l) |- _ =>\n               rename H into tmp;\n               assert (tmp := Forall_list_rev l H);\n               move H after tmp; clear tmp; simpl in H\n           end;\n    repeat ((apply Forall_list_map_intro ||\n             apply rev_Forall_list\n            ); simpl)\n  ).\n\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_predicate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.67786364689955}}
{"text": "(** * D4: Arytmetyka Peano *)\n\n(* begin hide *)\n\n(*\nTODO: opisać silnię, współczynniki dwumianowe, sumy szeregów\nTODO: opisać charakteryzowanie wzorów rekurencyjnych\n*)\n\n(* end hide *)\n\n(** Poniższe zadania mają służyć utrwaleniu zdobytej dotychczas wiedzy na\n    temat prostej rekursji i indukcji. Większość powinna być robialna po\n    przeczytaniu rozdziału o konstruktorach rekurencyjnych, ale niczego nie\n    gwarantuję.\n\n    Celem zadań jest rozwinięcie arytmetyki do takiego poziomu, żeby można\n    było tego używać gdzie indziej w jakotakim stopniu. Niektóre zadania\n    mogą pokrywać się z zadaniami obecnymi w tekście, a niektóre być może\n    nawet z przykładami. Staraj się nie podglądać.\n\n    Nazwy twierdzeń nie muszą pokrywać się z tymi z biblioteki standardowej,\n    choć starałem się, żeby tak było. *)\n\nRequire Import Recdef.\nRequire Import Setoid.\n\nRequire Div2 ZArith.\n\nModule MyNat.\n\n(** * Podstawy *)\n\n(** ** Definicja i notacje *)\n\n(** Zdefiniuj liczby naturalne. *)\n\n(* begin hide *)\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n(* end hide *)\n\nNotation \"0\" := O.\nNotation \"1\" := (S 0).\nNotation \"2\" := (S (S 0)).\n\n(** ** [0] i [S] *)\n\n(** Udowodnij właściwości zera i następnika. *)\n\nLemma neq_0_Sn :\n  forall n : nat, 0 <> S n.\n(* begin hide *)\nProof.\n  do 2 intro. inversion H.\nQed.\n(* end hide *)\n\nLemma neq_n_Sn :\n  forall n : nat, n <> S n.\n(* begin hide *)\nProof.\n  induction n as [| n'].\n    apply neq_0_Sn.\n    intro. apply IHn'. inversion H. assumption.\nQed.\n(* end hide *)\n\nLemma not_eq_S :\n  forall n m : nat, n <> m -> S n <> S m.\n(* begin hide *)\nProof.\n  intros; intro. apply H. inversion H0. trivial.\nQed.\n(* end hide *)\n\nLemma S_injective :\n  forall n m : nat, S n = S m -> n = m.\n(* begin hide *)\nProof.\n  inversion 1. trivial.\nQed.\n(* end hide *)\n\n(** ** Poprzednik *)\n\n(** Zdefiniuj funkcję zwracającą poprzednik danej liczby naturalnej.\n    Poprzednikiem [0] jest [0]. *)\n\n(* begin hide *)\nDefinition pred (n : nat) : nat :=\nmatch n with\n| 0 => 0\n| S n' => n'\nend.\n(* end hide *)\n\nLemma pred_0 : pred 0 = 0.\n(* begin hide *)\nProof.\n  trivial.\nQed.\n(* end hide *)\n\nLemma pred_S :\n  forall n : nat, pred (S n) = n.\n(* begin hide *)\nProof.\n  trivial.\nQed.\n(* end hide *)\n\n(** * Proste działania *)\n\n(** ** Dodawanie *)\n\n(** Zdefiniuj dodawanie (rekurencyjnie po pierwszym argumencie) i\n    udowodnij jego właściwości. *)\n\n(* begin hide *)\nFixpoint add (n m : nat) : nat :=\nmatch n with\n| 0 => m\n| S n' => S (add n' m)\nend.\n(* end hide *)\n\nLemma add_0_l :\n  forall n : nat, add 0 n = n.\n(* begin hide *)\nProof.\n  intro. cbn. trivial.\nQed.\n(* end hide *)\n\nLemma add_0_r :\n  forall n : nat, add n 0 = n.\n(* begin hide *)\nProof.\n  intro. induction n as [| n'].\n    trivial.\n    cbn. f_equal. assumption.\nQed.\n(* end hide *)\n\nLemma add_S_l :\n  forall n m : nat, add (S n) m = S (add n m).\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn; trivial.\nQed.\n(* end hide *)\n\nLemma add_S_r :\n  forall n m : nat, add n (S m) = S (add n m).\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn; intro.\n    trivial.\n    rewrite IHn'. trivial.\nQed.\n(* end hide *)\n\nLemma add_assoc :\n  forall a b c : nat,\n    add a (add b c) = add (add a b) c.\n(* begin hide *)\nProof.\n  induction a as [| a']; cbn.\n    trivial.\n    intros. rewrite IHa'. trivial.\nQed.\n(* end hide *)\n\nLemma add_comm :\n  forall n m : nat, add n m = add m n.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn; intros.\n    rewrite add_0_r. trivial.\n    induction m as [| m']; cbn.\n      rewrite add_0_r. trivial.\n      rewrite IHn'. rewrite <- IHm'. cbn. rewrite IHn'.\n        trivial.\nQed.\n(* end hide *)\n\nLemma add_no_absorbing_l :\n  ~ exists a : nat, forall n : nat, add a n = a.\n(* begin hide *)\nProof.\n  intro. destruct H as [a H]. specialize (H (S 0)).\n  rewrite add_comm in H. cbn in H. induction a as [| a'].\n    inversion H.\n    apply IHa'. inversion H. assumption.\nQed.\n(* end hide *)\n\nLemma add_no_absorbing_r :\n  ~ exists a : nat, forall n : nat, add n a = a.\n(* begin hide *)\nProof.\n  intro. destruct H as [a H]. specialize (H (S 0)).\n  rewrite add_comm in H. cbn in H. induction a as [| a'].\n    inversion H.\n    apply IHa'. rewrite add_comm in *. cbn in *.\n      inversion H. assumption.\nQed.\n(* end hide *)\n\nLemma add_no_inverse_l :\n  ~ forall n : nat, exists i : nat, add i n = 0.\n(* begin hide *)\nProof.\n  intro. destruct (H (S 0)) as [i H']. rewrite add_comm in H'.\n  inversion H'.\nQed.\n(* end hide *)\n\nLemma add_no_inverse_r :\n  ~ forall n : nat, exists i : nat, add n i = 0.\n(* begin hide *)\nProof.\n  intro. destruct (H (S 0)) as [i H']. inversion H'.\nQed.\n(* end hide *)\n\nLemma add_no_inverse_l_strong :\n  forall n i : nat, n <> 0 -> add i n <> 0.\n(* begin hide *)\nProof.\n  destruct i; cbn; intros.\n    assumption.\n    inversion 1.\nQed.\n(* end hide *)\n\nLemma add_no_inverse_r_strong :\n  forall n i : nat, n <> 0 -> add n i <> 0.\n(* begin hide *)\nProof.\n  intros. rewrite add_comm. apply add_no_inverse_l_strong. assumption.\nQed.\n(* end hide *)\n\n(** ** Alternatywne definicje dodawania *)\n\n(** Udowodnij, że poniższe alternatywne metody zdefiniowania dodawania\n    rzeczywiście definiują dodawanie. *)\n\nFixpoint add' (n m : nat) : nat :=\nmatch m with\n| 0 => n\n| S m' => S (add' n m')\nend.\n\nLemma add'_is_add :\n  forall n m : nat, add' n m = add n m.\n(* begin hide *)\nProof.\n  intros n m. generalize dependent n.\n  induction m as [| m']; cbn; intros.\n    rewrite add_0_r. trivial.\n    rewrite IHm'. rewrite (add_comm n (S m')). cbn.\n      rewrite add_comm. trivial.\nQed.\n(* end hide *)\n\nFixpoint add'' (n m : nat) : nat :=\nmatch n with\n| 0 => m\n| S n' => add'' n' (S m)\nend.\n\nLemma add''_is_add :\n  forall n m : nat, add'' n m = add n m.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn.\n    reflexivity.\n    intro. rewrite IHn', add_comm. cbn. rewrite add_comm. reflexivity.\nQed.\n(* end hide *)\n\nFixpoint add''' (n m : nat) : nat :=\nmatch m with\n| 0 => n\n| S m' => add''' (S n) m'\nend.\n\nLemma add'''_is_add :\n  forall n m : nat, add''' n m = add n m.\n(* begin hide *)\nProof.\n  intros n m. generalize dependent n.\n  induction m as [| m']; cbn; intros.\n    rewrite add_0_r. reflexivity.\n    rewrite IHm'. cbn. rewrite (add_comm n (S _)). cbn.\n      rewrite add_comm. reflexivity.\nQed.\n(* end hide *)\n\n(** ** Odejmowanie *)\n\n(** Zdefiniuj odejmowanie i udowodnij jego właściwości. *)\n\n(* begin hide *)\nFixpoint sub (n m : nat) : nat :=\nmatch n, m with\n| 0, _ => 0\n| _, 0 => n\n| S n', S m' => sub n' m'\nend.\n(* end hide *)\n\nLemma sub_1_r :\n  forall n : nat, sub n 1 = pred n.\n(* begin hide *)\nProof.\n  repeat (destruct n; cbn; trivial).\nQed.\n(* end hide *)\n\nLemma sub_0_l :\n  forall n : nat, sub 0 n = 0.\n(* begin hide *)\nProof.\n  cbn. trivial.\nQed.\n(* end hide *)\n\nLemma sub_0_r :\n  forall n : nat, sub n 0 = n.\n(* begin hide *)\nProof.\n  destruct n; trivial.\nQed.\n(* end hide *)\n\nLemma sub_S_S :\n  forall n m : nat,\n    sub (S n) (S m) = sub n m.\n(* begin hide *)\nProof.\n  cbn. trivial.\nQed.\n(* end hide *)\n\nLemma sub_diag:\n  forall n : nat, sub n n = 0.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn; trivial.\nQed.\n(* end hide *)\n\nLemma sub_add_l :\n  forall n m : nat,\n    sub (add n m) n = m.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn.\n    apply sub_0_r.\n    apply IHn'.\nQed.\n(* end hide *)\n\nLemma sub_add_l' :\n  forall n m : nat,\n    sub (add n m) m = n.\n(* begin hide *)\nProof.\n  intros. rewrite add_comm. apply sub_add_l.\nQed.\n(* end hide *)\n\nLemma sub_add_r :\n  forall a b c : nat,\n    sub a (add b c) = sub (sub a b) c.\n(* begin hide *)\nProof.\n  induction a as [| a']; cbn; intros; [easy |].\n  destruct b as [| b']; cbn.\n  - now destruct c; cbn.\n  - now rewrite IHa'.\nQed.\n(* end hide *)\n\nLemma sub_exchange :\n  forall a b c : nat,\n    sub (sub a b) c = sub (sub a c) b.\n(* begin hide *)\nProof.\n  intros a b. generalize dependent a. induction b as [| b'].\n    intros. repeat rewrite sub_0_r. trivial.\n    intros a c. generalize dependent a. induction c as [| c'].\n      intro. repeat rewrite sub_0_r. trivial.\n      destruct a as [| a'].\n        cbn. trivial.\n        cbn in *. rewrite <- IHc'. rewrite IHb'. destruct a'; cbn.\n          trivial.\n          rewrite IHb'. trivial.\nRestart.\n  now intros; rewrite <- sub_add_r, add_comm, sub_add_r.\nQed.\n(* end hide *)\n\nLemma sub_not_assoc :\n  ~ forall a b c : nat,\n      sub a (sub b c) = sub (sub a b) c.\n(* begin hide *)\nProof.\n  intro. specialize (H 1 1 1). cbn in H. inversion H.\nQed.\n(* end hide *)\n\nLemma sub_not_comm :\n  ~ forall n m : nat,\n      sub n m = sub m n.\n(* begin hide *)\nProof.\n  intro. specialize (H 1 0). cbn in H. inversion H.\nQed.\n(* end hide *)\n\nLemma sub_comm_char :\n  forall n m : nat,\n    sub n m = sub m n -> n = m.\n(* begin hide *)\nProof.\n  induction n as [| n']; intros [| m'] Heq; cbn in *; [easy | inversion Heq.. |].\n  now f_equal; apply IHn'.\nQed.\n(* end hide *)\n\n(** ** Odejmowanie v2 *)\n\nFixpoint sub' (n m : nat) : nat :=\nmatch m with\n| 0    => n\n| S m' => pred (sub' n m')\nend.\n\nLemma sub'_1_r :\n  forall n : nat, sub' n 1 = pred n.\n(* begin hide *)\nProof.\n  reflexivity.\nQed.\n(* end hide *)\n\nLemma sub'_pred_l :\n  forall n m : nat,\n    sub' (pred n) m = pred (sub' n m).\n(* begin hide *)\nProof.\n  induction m as [| m']; cbn.\n    reflexivity.\n    rewrite IHm'. reflexivity.\nQed.\n(* end hide *)\n\nLemma sub'_0_l :\n  forall n : nat,\n    sub' 0 n = 0.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn.\n    reflexivity.\n    rewrite IHn'. cbn. reflexivity.\nQed.\n(* end hide *)\n\nLemma sub'_0_r :\n  forall n : nat,\n    sub' n 0 = n.\n(* begin hide *)\nProof.\n  reflexivity.\nQed.\n(* end hide *)\n\nLemma sub'_S_S :\n  forall n m : nat,\n    sub' (S n) (S m) = sub' n m.\n(* begin hide *)\nProof.\n  induction m as [| m']; cbn.\n    reflexivity.\n    rewrite <- IHm'. cbn. reflexivity.\nQed.\n(* end hide *)\n\nLemma pred_sub'_S :\n  forall n m : nat,\n    pred (sub' (S n) m) = sub' n m.\n(* begin hide *)\nProof.\n  induction m as [| m']; cbn.\n    reflexivity.\n    rewrite IHm'. reflexivity.\nQed.\n\n(* end hide *)\nLemma sub'_diag :\n  forall n : nat,\n    sub' n n = 0.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn.\n    reflexivity.\n    rewrite pred_sub'_S, IHn'. reflexivity.\nQed.\n(* end hide *)\n\nLemma sub'_add_l :\n  forall n m : nat,\n    sub' (add n m) n = m.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn.\n    reflexivity.\n    intro. rewrite pred_sub'_S. apply IHn'.\nQed.\n(* end hide *)\n\nLemma sub'_add_l' :\n  forall n m : nat,\n    sub' (add n m) m = n.\n(* begin hide *)\nProof.\n  intros. rewrite add_comm. apply sub'_add_l.\nQed.\n(* end hide *)\n\nLemma sub'_add_r :\n  forall a b c : nat,\n    sub' a (add b c) = sub' (sub' a b) c.\n(* begin hide *)\nProof.\n  induction b as [| b']; cbn; intros.\n    reflexivity.\n    rewrite IHb', sub'_pred_l. reflexivity.\nQed.\n(* end hide *)\n\nLemma sub'_exchange :\n  forall a b c : nat,\n    sub' (sub' a b) c = sub' (sub' a c) b.\n(* begin hide *)\nProof.\n  induction b as [| b']; cbn.\n    reflexivity.\n    intro. rewrite sub'_pred_l, IHb'. reflexivity.\nRestart.\n  now intros; rewrite <- sub'_add_r, add_comm, sub'_add_r.\nQed.\n(* end hide *)\n\nLemma sub'_not_assoc :\n  ~ forall a b c : nat,\n      sub' a (sub' b c) = sub' (sub' a b) c.\n(* begin hide *)\nProof.\n  intro. specialize (H 1 1 1). cbn in H. inversion H.\nQed.\n(* end hide *)\n\nLemma sub'_not_comm :\n  ~ forall n m : nat,\n      sub' n m = sub' m n.\n(* begin hide *)\nProof.\n  intro. specialize (H 1 0). cbn in H. inversion H.\nQed.\n(* end hide *)\n\n(** ** Mnożenie *)\n\n(** Zdefiniuj mnożenie i udowodnij jego właściwości. *)\n\n(* begin hide *)\nFixpoint mul (n m : nat) : nat :=\nmatch n with\n| 0 => 0\n| S n' => add m (mul n' m)\nend.\n(* end hide *)\n\nLemma mul_0_l :\n  forall n : nat,\n    mul 0 n = 0.\n(* begin hide *)\nProof.\n  cbn. reflexivity.\nQed.\n(* end hide *)\n\nLemma mul_0_r :\n  forall n : nat,\n    mul n 0 = 0.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn.\n    reflexivity.\n    assumption.\nRestart.\n  induction n; trivial.\nQed.\n(* end hide *)\n\nLemma mul_1_l :\n  forall n : nat,\n    mul 1 n = n.\n(* begin hide *)\nProof.\n  destruct n as [| n'].\n    cbn. trivial.\n    cbn. rewrite add_0_r. trivial.\nRestart.\n  destruct n; cbn; try rewrite add_0_r; trivial.\nQed.\n(* end hide*)\n\nLemma mul_1_r :\n  forall n : nat,\n    mul n 1 = n.\n(* begin hide *)\nProof.\n  induction n.\n    cbn. trivial.\n    cbn. rewrite IHn. trivial.\nRestart.\n  induction n; cbn; try rewrite IHn; trivial.\nQed.\n(* end hide *)\n\nLemma mul_comm :\n  forall n m : nat,\n    mul n m = mul m n.\n(* begin hide *)\nProof.\n  induction n as [| n']; intro.\n    rewrite mul_0_l, mul_0_r. trivial.\n    induction m as [| m'].\n      rewrite mul_0_l, mul_0_r. trivial.\n      cbn in *. rewrite IHn', <- IHm', IHn'. cbn.\n        do 2 rewrite add_assoc. rewrite (add_comm n' m'). trivial.\nQed.\n(* begin hide *)\n\nLemma mul_add_r :\n  forall a b c : nat,\n    mul a (add b c) = add (mul a b) (mul a c).\n(* begin hide *)\nProof.\n  induction a as [| a']; cbn; trivial.\n  intros. rewrite IHa'. repeat rewrite add_assoc.\n  f_equal. repeat rewrite <- add_assoc. f_equal.\n  apply add_comm.\nQed.\n(* end hide *)\n\nLemma mul_add_l :\n  forall a b c : nat,\n    mul (add a b) c = add (mul a c) (mul b c).\n(* begin hide *)\nProof.\n  intros. rewrite mul_comm. rewrite mul_add_r.\n  f_equal; apply mul_comm.\nQed.\n(* end hide *)\n\nLemma mul_sub_r :\n  forall a b c : nat,\n    mul a (sub b c) = sub (mul a b) (mul a c).\n(* begin hide *)\nProof.\n  induction a as [| a']; cbn; trivial.\n  induction b as [| b'].\n    intros. repeat rewrite mul_0_r. cbn. trivial.\n    induction c as [| c'].\n      rewrite mul_0_r. cbn. trivial.\n      cbn. rewrite (mul_comm a' (S b')). cbn.\n        rewrite (mul_comm a' (S c')). cbn.\n        rewrite IHb'. repeat rewrite sub_add_r.\n        f_equal. 2: apply mul_comm.\n        replace (add b' (add a' _)) with (add a' (add b' (mul b' a'))).\n          rewrite sub_exchange. rewrite sub_add_l.\n            rewrite mul_comm. trivial.\n          repeat rewrite add_assoc. rewrite (add_comm a' b'). trivial.\nQed.\n(* end hide *)\n\nLemma mul_sub_l :\n  forall a b c : nat,\n    mul (sub a b) c = sub (mul a c) (mul b c).\n(* begin hide *)\nProof.\n  intros. rewrite mul_comm. rewrite mul_sub_r.\n  f_equal; apply mul_comm.\nQed.\n(* end hide *)\n\nLemma mul_assoc :\n  forall a b c : nat,\n    mul a (mul b c) = mul (mul a b) c.\n(* begin hide *)\nProof.\n  induction a as [| a']; cbn; trivial.\n  intros. rewrite mul_add_l.\n  rewrite IHa'. trivial.\nQed.\n(* end hide *)\n\nLemma mul_no_inverse_l :\n  ~ forall n : nat, exists i : nat, mul i n = 1.\n(* begin hide *)\nProof.\n  intro. destruct (H (S 1)) as [i H']. rewrite mul_comm in H'.\n  cbn in H'. rewrite add_0_r in H'. destruct i.\n    inversion H'.\n    cbn in H'. rewrite add_comm in H'. cbn in H'. inversion H'.\nQed.\n(* end hide *)\n\nLemma mul_no_inverse_r :\n  ~ forall n : nat, exists i : nat, mul n i = 1.\n(* begin hide *)\nProof.\n  intro. destruct (H (S 1)) as [i H']. cbn in H'.\n  rewrite add_0_r in H'. destruct i.\n    inversion H'.\n    cbn in H'. rewrite add_comm in H'. cbn in H'. inversion H'.\nQed.\n(* end hide *)\n\nLemma mul_no_inverse_l_strong :\n  forall n i : nat, n <> 1 -> mul i n <> 1.\n(* begin hide *)\nProof.\n  induction i; cbn; intros.\n    inversion 1.\n    destruct n as [| [| n']]; cbn.\n      rewrite mul_0_r. assumption.\n      contradiction H. reflexivity.\n      inversion 1.\nQed.\n(* end hide *)\n\nLemma mul_no_inverse_r_strong :\n  forall n i : nat, n <> 1 -> mul n i <> 1.\n(* begin hide *)\nProof.\n  intros. rewrite mul_comm.\n  apply mul_no_inverse_l_strong. assumption.\nQed.\n(* end hide *)\n\nLemma mul_2_l :\n  forall n : nat, mul 2 n = add n n.\n(* begin hide *)\nProof.\n  intro. cbn. rewrite add_0_r. trivial.\nQed.\n(* end hide *)\n\n(** ** Potęgowanie *)\n\n(** Zdefiniuj potęgowanie i udowodnij jego właściwości. *)\n\n(* begin hide *)\nFixpoint pow (n m : nat) : nat :=\nmatch m with\n| 0 => 1\n| S m' => mul n (pow n m')\nend.\n(* end hide *)\n\nLemma pow_0_r :\n  forall n : nat,\n    pow n 0 = 1.\n(* begin hide *)\nProof. reflexivity. Qed.\n(* end hide *)\n\nLemma pow_0_l :\n  forall n : nat,\n    pow 0 (S n) = 0.\n(* begin hide *)\nProof.\n  destruct n; cbn; reflexivity.\nQed.\n(* end hide *)\n\nLemma pow_1_l :\n  forall n : nat,\n    pow 1 n = 1.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn; try rewrite add_0_r; trivial.\nQed.\n(* end hide *)\n\nLemma pow_1_r :\n  forall n : nat,\n    pow n 1 = n.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn; try rewrite mul_1_r; trivial.\nQed.\n(* end hide *)\n\nLemma pow_no_neutr_l :\n  ~ exists e : nat, forall n : nat, pow e n = n.\n(* begin hide *)\nProof.\n  destruct 1 as [e H]. specialize (H 0). cbn in H. inversion H.\nQed.\n(* end hide *)\n\nLemma pow_no_absorbing_r :\n  ~ exists a : nat, forall n : nat, pow n a = a.\n(* begin hide *)\nProof.\n  destruct 1 as [a H]. destruct a;\n  [specialize (H 1) | specialize (H 0)]; inversion H.\nQed.\n(* end hide *)\n\nLemma pow_add :\n  forall a b c : nat,\n    pow a (add b c) = mul (pow a b) (pow a c).\n(* begin hide *)\nProof.\n  induction b as [| b']; induction c as [| c']; cbn.\n    reflexivity.\n    rewrite add_0_r. reflexivity.\n    rewrite add_0_r, mul_1_r. reflexivity.\n    rewrite IHb'. cbn. rewrite !mul_assoc. reflexivity.\nQed.\n(* end hide *)\n\nLemma pow_mul_l :\n  forall a b c : nat,\n    pow (mul a b) c = mul (pow a c) (pow b c).\n(* begin hide *)\nProof.\n  induction c as [| c']; cbn.\n    trivial.\n    rewrite IHc'. repeat rewrite mul_assoc. f_equal.\n      repeat rewrite <- mul_assoc. f_equal. apply mul_comm.\nQed.\n(* end hide *)\n\nLemma pow_pow_l :\n  forall a b c : nat,\n    pow (pow a b) c = pow a (mul b c).\n(* begin hide *)\nProof.\n  induction c as [| c']; cbn.\n    rewrite mul_0_r. cbn. trivial.\n    rewrite IHc', (mul_comm b (S c')). cbn.\n      rewrite <- pow_add. rewrite mul_comm. trivial.\nQed.\n(* end hide *)\n\n(** * Porządek *)\n\n(** ** Porządek [<=] *)\n\n(** Zdefiniuj relację \"mniejszy lub równy\" i udowodnij jej właściwości. *)\n\n(* begin hide *)\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(* end hide *)\n\nNotation \"n <= m\" := (le n m).\n\nLemma le_0_l :\n  forall n : nat, 0 <= n.\n(* begin hide *)\nProof.\n  induction n as [| n'].\n    apply le_n.\n    apply le_S. assumption.\nQed.\n(* end hide *)\n\nLemma le_n_Sm :\n  forall n m : nat, n <= m -> n <= S m.\n(* begin hide *)\nProof.\n  apply le_S.\nQed.\n(* end hide *)\n\nLemma le_Sn_m :\n  forall n m : nat, S n <= m -> n <= m.\n(* begin hide *)\nProof.\n  induction m as [| m'].\n    inversion 1.\n    intros. inversion H.\n      apply le_S, le_n.\n      apply le_S, IHm'. assumption.\nQed.\n(* end hide *)\n\nLemma le_n_S :\n  forall n m : nat, n <= m -> S n <= S m.\n(* begin hide *)\nProof.\n  induction 1.\n    apply le_n.\n    apply le_S. assumption.\nQed.\n(* end hide *)\n\nLemma le_S_n :\n  forall n m : nat, S n <= S m -> n <= m.\n(* begin hide *)\nProof.\n  intros n m. generalize dependent n. induction m as [| m'].\n    intros. inversion H.\n      apply le_n.\n      inversion H1.\n    inversion 1.\n      apply le_n.\n      apply le_S. apply IHm'. assumption.\nQed.\n(* end hide *)\n\nLemma le_Sn_n :\n  forall n : nat, ~ S n <= n.\n(* begin hide *)\nProof.\n  induction n as [| n']; intro.\n    inversion H.\n    apply IHn'. apply le_S_n. assumption.\nQed.\n(* end hide *)\n\nLemma le_refl :\n  forall n : nat, n <= n.\n(* begin hide *)\nProof.\n  apply le_n.\nQed.\n(* end hide *)\n\nLemma le_trans :\n  forall a b c : nat,\n    a <= b -> b <= c -> a <= c.\n(* begin hide *)\nProof.\n  induction 1.\n    trivial.\n    intro. apply IHle. apply le_Sn_m. assumption.\nQed.\n(* end hide *)\n\nLemma le_antisym :\n  forall n m : nat,\n    n <= m -> m <= n -> n = m.\n(* begin hide *)\nProof.\n  induction n as [| n'].\n    inversion 2. trivial.\n    induction m as [| m'].\n      inversion 1.\n      intros. f_equal. apply IHn'; apply le_S_n; assumption.\nQed.\n(* end hide *)\n\nLemma le_pred :\n  forall n : nat, pred n <= n.\n(* begin hide *)\nProof.\n  destruct n; cbn; repeat constructor.\nQed.\n(* end hide *)\n\nLemma le_n_pred :\n  forall n m : nat,\n    n <= m -> pred n <= pred m.\n(* begin hide *)\nProof.\n  inversion 1.\n    constructor.\n    cbn. apply le_trans with n.\n      apply le_pred.\n      assumption.\nQed.\n(* end hide *)\n\nLemma no_le_pred_n :\n  ~ forall n m : nat,\n      pred n <= pred m -> n <= m.\n(* begin hide *)\nProof.\n  intro. specialize (H 1 0 (le_n 0)). inversion H.\nQed.\n(* end hide *)\n\nLemma le_add_l :\n  forall a b c : nat,\n    b <= c -> add a b <= add a c.\n(* begin hide *)\nProof.\n  induction a as [| a']; cbn.\n    trivial.\n    intros. apply le_n_S. apply IHa'. assumption.\nQed.\n(* end hide *)\n\nLemma le_add_r :\n  forall a b c : nat,\n    a <= b -> add a c <= add b c.\n(* begin hide *)\nProof.\n  intros. rewrite (add_comm a c), (add_comm b c).\n  apply le_add_l. assumption.\nQed.\n(* end hide *)\n\nLemma le_add :\n  forall a b c d : nat,\n    a <= b -> c <= d -> add a c <= add b d.\n(* begin hide *)\nProof.\n  induction 1.\n    apply le_add_l.\n    intros. cbn. apply le_S. apply IHle. assumption.\nQed.\n(* end hide *)\n\nLemma le_sub_S_S :\n  forall n m : nat,\n    sub n (S m) <= sub n m.\n(* begin hide *)\nProof.\n  induction n as [| n'].\n    cbn. constructor.\n    destruct m; cbn.\n      rewrite sub_0_r. do 2 constructor.\n      apply IHn'.\nQed.\n(* end hide *)\n\nLemma le_sub_l :\n  forall a b c : nat,\n    b <= c -> sub a c <= sub a b.\n(* begin hide *)\nProof.\n  induction 1.\n    constructor.\n    apply le_trans with (sub a m).\n      apply le_sub_S_S.\n      assumption.\nQed.\n(* end hide *)\n\nLemma le_sub_r :\n  forall a b c : nat,\n    a <= b -> sub a c <= sub b c.\n(* begin hide *)\nProof.\n  intros a b c. generalize dependent a. generalize dependent b.\n  induction c as [| c'].\n    intros. do 2 rewrite sub_0_r. trivial.\n    destruct a, b; cbn; intro; trivial.\n      apply le_0_l.\n      inversion H.\n      apply IHc'. apply le_S_n. assumption.\nQed.\n(* end hide *)\n\nLemma le_mul_l :\n  forall a b c : nat,\n    b <= c -> mul a b <= mul a c.\n(* begin hide *)\nProof.\n  induction a as [| a']; cbn.\n    constructor.\n    intros. apply le_add.\n      assumption.\n      apply IHa'. assumption.\nQed.\n(* end hide *)\n\nLemma le_mul_r :\n  forall a b c : nat,\n    a <= b -> mul a c <= mul b c.\n(* begin hide *)\nProof.\n  intros. rewrite (mul_comm a c), (mul_comm b c).\n  apply le_mul_l. assumption.\nQed.\n(* end hide *)\n\nLemma le_mul :\n  forall a b c d : nat,\n    a <= b -> c <= d -> mul a c <= mul b d.\n(* begin hide *)\nProof.\n  induction 1; cbn; intro.\n    apply le_mul_l. assumption.\n    change (mul a c) with (add 0 (mul a c)). apply le_add.\n      apply le_0_l.\n      apply IHle. assumption.\nQed.\n(* end hide *)\n\nLemma le_add_exists :\n  forall n m : nat,\n    n <= m -> exists k : nat, add n k = m.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn.\n    intros. exists m. trivial.\n    intros. destruct (IHn' m) as [k Hk].\n      apply le_Sn_m in H. assumption.\n      destruct k; cbn.\n        rewrite add_0_r in Hk. subst. cut False.\n          inversion 1.\n          apply (le_Sn_n m). assumption.\n        exists k. rewrite add_comm in Hk. cbn in Hk.\n          rewrite add_comm. assumption.\nQed.\n(* end hide *)\n\nLemma le_pow_l :\n  forall a b c : nat,\n    a <> 0 -> b <= c -> pow a b <= pow a c.\n(* begin hide *)\nProof.\n  induction 2.\n    constructor.\n    destruct a; cbn.\n      contradiction H. trivial.\n      change (pow (S a) b) with (add 0 (pow (S a) b)).\n        rewrite (add_comm (pow (S a) m) _). apply le_add.\n          apply le_0_l.\n          assumption.\nQed.\n(* end hide *)\n\nLemma le_pow_r :\n  forall a b c : nat,\n    a <= b -> pow a c <= pow b c.\n(* begin hide *)\nProof.\n  induction c as [| c']; cbn.\n    constructor.\n    intro. apply le_mul; auto.\nQed.\n(* end hide *)\n\nLemma sub'_0 :\n  forall n m : nat,\n    sub' n m = 0 -> n <= m.\n(* begin hide *)\nProof.\n  intros n m. revert n.\n  induction m as [| m']; cbn; intros.\n    rewrite H. constructor.\n    destruct n as [| n']; cbn.\n      apply le_0_l.\n      apply le_n_S, IHm'. rewrite pred_sub'_S in H. assumption.\nQed.\n(* end hide *)\n\nLemma sub'_S_l :\n  forall n m : nat,\n    m <= n -> sub' (S n) m = S (sub' n m).\n(* begin hide *)\nProof.\n  induction m as [| m']; cbn; intros.\n    reflexivity.\n    rewrite IHm'.\n      cbn. destruct (sub' n m') eqn: Heq.\n        apply sub'_0 in Heq. edestruct le_Sn_n. eapply le_trans.\n          exact H.\n          assumption.\n        cbn. reflexivity.\n      eapply le_trans with (S m').\n        do 2 constructor.\n        assumption.\nQed.\n(* end hide *)\n\nLemma le_sub'_l :\n  forall n m : nat,\n    sub' n m <= n.\n(* begin hide *)\nProof.\n  induction m as [| m']; cbn.\n    constructor.\n    apply le_trans with (sub' n m').\n      apply le_pred.\n      assumption.\nQed.\n(* end hide *)\n\nLemma sub'_inv :\n  forall n m : nat,\n    m <= n -> sub' n (sub' n m) = m.\n(* begin hide *)\nProof.\n  intros n m. revert n.\n  induction m as [| m']; intros.\n    rewrite sub'_0_r, sub'_diag. reflexivity.\n    induction n as [| n'].\n      inversion H.\n      cbn. rewrite pred_sub'_S, sub'_S_l, IHm'.\n        reflexivity.\n        apply le_S_n. assumption.\n        apply le_sub'_l.\nQed.\n(* end hide *)\n\n(** ** Porządek [<] *)\n\nDefinition lt (n m : nat) : Prop := S n <= m.\n\nNotation \"n < m\" := (lt n m).\n\nLemma lt_irrefl :\n  forall n : nat, ~ n < n.\n(* begin hide *)\nProof.\n  unfold lt, not; intros. apply le_Sn_n in H. assumption.\nQed.\n(* end hide *)\n\nLemma lt_trans :\n  forall a b c : nat, a < b -> b < c -> a < c.\n(* begin hide *)\nProof.\n  unfold lt; intros. destruct b.\n    inversion H.\n    destruct c as [| [| c']].\n      inversion H0.\n      inversion H0. inversion H2.\n      apply le_S_n in H0. constructor. eapply le_trans; eauto.\nQed.\n(* end hide *)\n\nLemma lt_asym :\n  forall n m : nat, n < m -> ~ m < n.\n(* begin hide *)\nProof.\n  unfold lt, not; intros. cut (S n <= n).\n    intro. apply le_Sn_n in H1. assumption.\n    apply le_trans with m.\n      assumption.\n      apply le_Sn_m. assumption.\nQed.\n(* end hide *)\n\n(** ** Minimum i maksimum *)\n\n(** Zdefiniuj operacje brania minimum i maksimum z dwóch liczb naturalnych\n    oraz udowodnij ich właściwości. *)\n\n(* begin hide *)\nFixpoint min (n m : nat) : nat :=\nmatch n, m with\n| 0, _ => 0\n| _, 0 => 0\n| S n', S m' => S (min n' m')\nend.\n\nFixpoint max (n m : nat) : nat :=\nmatch n, m with\n| 0, _ => m\n| _, 0 => n\n| S n', S m' => S (max n' m')\nend.\n(* end hide *)\n\nLemma min_0_l :\n  forall n : nat, min 0 n = 0.\n(* begin hide *)\nProof. reflexivity. Qed.\n(* end hide *)\n\nLemma min_0_r :\n  forall n : nat, min n 0 = 0.\n(* begin hide *)\nProof.\n  destruct n; cbn; reflexivity.\nQed.\n(* end hide *)\n\nLemma max_0_l :\n  forall n : nat, max 0 n = n.\n(* begin hide *)\nProof. reflexivity. Qed.\n(* end hide *)\n\nLemma max_0_r :\n  forall n : nat, max n 0 = n.\n(* begin hide *)\nProof.\n  destruct n; cbn; reflexivity.\nQed.\n(* end hide *)\n\nLemma min_le :\n  forall n m : nat, n <= m -> min n m = n.\n(* begin hide *)\nProof.\n  induction n as [| n'].\n    trivial.\n    destruct m as [| m'].\n      inversion 1.\n      intro. cbn. f_equal. apply IHn'. apply le_S_n. assumption.\nQed.\n(* end hide *)\n\nLemma max_le :\n  forall n m : nat, n <= m -> max n m = m.\n(* begin hide *)\nProof.\n  induction n as [| n'].\n    trivial.\n    destruct m as [| m'].\n      inversion 1.\n      intro. cbn. f_equal. apply IHn'. apply le_S_n. assumption.\nQed.\n(* end hide *)\n\nLemma min_assoc :\n  forall a b c : nat,\n    min a (min b c) = min (min a b) c.\n(* begin hide *)\nProof.\n  induction a as [| a'].\n    trivial.\n    destruct b, c; auto. cbn. rewrite IHa'. trivial.\nQed.\n(* end hide *)\n\nLemma max_assoc :\n  forall a b c : nat,\n    max a (max b c) = max (max a b) c.\n(* begin hide *)\nProof.\n  induction a as [| a'].\n    trivial.\n    destruct b, c; auto. cbn. rewrite IHa'. trivial.\nQed.\n(* end hide *)\n\nLemma min_comm :\n  forall n m : nat, min n m = min m n.\n(* begin hide *)\nProof.\n  induction n as [| n']; destruct m; cbn; try rewrite IHn'; trivial.\nQed.\n(* end hide *)\n\nLemma max_comm :\n  forall n m : nat, max n m = max m n.\n(* begin hide *)\nProof.\n  induction n as [| n']; destruct m; cbn; try rewrite IHn'; trivial.\nQed.\n(* end hide *)\n\nLemma min_refl :\n  forall n : nat, min n n = n.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn; try rewrite IHn'; trivial.\nQed.\n(* end hide *)\n\nLemma max_refl :\n  forall n : nat, max n n = n.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn; try rewrite IHn'; trivial.\nQed.\n(* end hide *)\n\nLemma min_no_neutr_l :\n  ~ exists e : nat, forall n : nat, min e n = n.\n(* begin hide *)\nProof.\n  intro. destruct H as [e H]. specialize (H (S e)).\n  induction e.\n    inversion H.\n    cbn in H. inversion H. apply IHe. assumption.\nQed.\n(* end hide *)\n\nLemma min_no_neutr_r :\n  ~ exists e : nat, forall n : nat, min n e = n.\n(* begin hide *)\nProof.\n  intro. apply min_no_neutr_l. destruct H as [e H].\n  exists e. intro. rewrite min_comm. apply H.\nQed.\n(* end hide *)\n\nLemma max_no_absorbing_l :\n  ~ exists a : nat, forall n : nat, max a n = a.\n(* begin hide *)\nProof.\n  intro. destruct H as [a H]. specialize (H (S a)).\n  induction a; inversion H. apply IHa. assumption.\nQed.\n(* end hide *)\n\nLemma max_no_absorbing_r :\n  ~ exists a : nat, forall n : nat, max n a = a.\n(* begin hide *)\nProof.\n  intro. destruct H as [a H]. apply max_no_absorbing_l.\n  exists a. intro. rewrite max_comm. apply H.\nQed.\n(* end hide *)\n\nLemma is_it_true :\n  (forall n m : nat, min (S n) m = S (min n m)) \\/\n  (~ forall n m : nat, min (S n) m = S (min n m)).\n(* begin hide *)\nProof.\n  right. intro. specialize (H 0 0). cbn in H. inversion H.\nQed.\n(* end hide *)\n\n(** * Rozstrzygalność *)\n\n(** ** Rozstrzygalność porządku *)\n\n(** Zdefiniuj funkcję [leb], która sprawdza, czy [n <= m]. *)\n\n(* begin hide *)\nFixpoint leb (n m : nat) : bool :=\nmatch n, m with\n| 0, _ => true\n| _, 0 => false\n| S n', S m' => leb n' m'\nend.\n(* end hide *)\n\nLemma leb_n :\n  forall n : nat,\n    leb n n = true.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn; trivial.\nQed.\n(* end hide *)\n\nLemma leb_spec :\n  forall n m : nat,\n    n <= m <-> leb n m = true.\n(* begin hide *)\nProof.\n  split; generalize dependent m.\n    induction n as [| n'].\n      cbn. trivial.\n      destruct m; cbn; intro.\n        inversion H.\n        apply IHn'. apply le_S_n. assumption.\n    induction n as [| n']; intros.\n      apply le_0_l.\n      destruct m; cbn.\n        cbn in H. inversion H.\n        cbn in H. apply le_n_S. apply IHn'. assumption.\nRestart.\n  split; generalize dependent m; induction n as [| n']; destruct m;\n  cbn; trivial; try (inversion 1; fail); intro.\n    apply IHn'. apply le_S_n. assumption.\n    apply le_n.\n    apply le_0_l.\n    apply le_n_S. apply IHn'. assumption.\nQed.\n(* end hide *)\n\n(** ** Rozstrzygalność równości *)\n\n(** Zdefiniuj funkcję [eqb], która sprawdza, czy [n = m]. *)\n\n(* begin hide *)\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(* end hide *)\n\nLemma eqb_spec :\n  forall n m : nat,\n    n = m <-> eqb n m = true.\n(* begin hide *)\nProof.\n  split; generalize dependent m; generalize dependent n.\n    destruct 1. induction n; auto.\n    induction n as [| n']; destruct m as [| m']; cbn; inversion 1; auto.\n      f_equal. apply IHn'. assumption.\nQed.\n(* end hide *)\n\n(** * Dzielenie i podzielność *)\n\n(** ** Dzielenie przez 2 *)\n\n(** Pokaż, że indukcję na liczbach naturalnych można robić \"co 2\".\n    Wskazówka: taktyk można używać nie tylko do dowodzenia. Przypomnij\n    sobie, że taktyki to programy, które generują dowody, zaś dowody\n    są programami. Dzięki temu nic nie stoi na przeszkodzie, aby\n    taktyki interpretować jako programy, które piszą inne programy.\n    I rzeczywiście — w Coqu możemy używać taktyk do definiowania\n    dowolnych termów. W niektórych przypadkach jest to bardzo częsta\n    praktyka. *)\n\nFixpoint nat_ind_2\n  (P : nat -> Prop) (H0 : P 0) (H1 : P 1)\n  (HSS : forall n : nat, P n -> P (S (S n))) (n : nat) : P n.\n(* begin hide *)\nProof.\n  destruct n.\n    apply H0.\n    destruct n.\n      apply H1.\n      apply HSS. apply nat_ind_2; auto.\nQed.\n(* end hide *)\n\n(** Zdefiniuj dzielenie całkowitoliczbowe przez [2] oraz funkcję obliczającą\n    resztę z dzielenia przez [2]. *)\n\n(* begin hide *)\nFixpoint div2 (n : nat) : nat :=\nmatch n with\n| 0 => 0\n| 1 => 0\n| S (S n') => S (div2 n')\nend.\n\nFixpoint mod2 (n : nat) : nat :=\nmatch n with\n| 0 => 0\n| 1 => 1\n| S (S n') => mod2 n'\nend.\n(* end hide *)\n\nLemma div2_even :\n  forall n : nat, div2 (mul 2 n) = n.\n(* begin hide *)\nProof.\n  apply nat_ind_2; cbn; intros; trivial.\n  rewrite add_0_r in *. rewrite ?add_S_r. cbn. rewrite H. trivial.\nQed.\n(* end hide *)\n\nLemma div2_odd :\n  forall n : nat, div2 (S (mul 2 n)) = n.\n(* begin hide *)\nProof.\n  apply nat_ind_2; cbn; intros; trivial.\n  rewrite add_0_r in *. rewrite ?add_S_r. cbn. rewrite H. trivial.\nQed.\n(* end hide *)\n\nLemma mod2_even :\n  forall n : nat, mod2 (mul 2 n) = 0.\n(* begin hide *)\nProof.\n  apply nat_ind_2; cbn; intros; trivial.\n  rewrite add_0_r, ?add_S_r in *. cbn. rewrite H. trivial.\nQed.\n(* end hide *)\n\nLemma mod2_odd :\n  forall n : nat, mod2 (S (mul 2 n)) = 1.\n(* begin hide *)\nProof.\n  apply nat_ind_2; cbn; intros; trivial.\n  rewrite add_0_r, ?add_S_r in *. cbn. rewrite H. trivial.\nQed.\n(* end hide *)\n\nLemma div2_mod2_spec :\n  forall n : nat, add (mul 2 (div2 n)) (mod2 n) = n.\n(* begin hide *)\nProof.\n  apply nat_ind_2; cbn; intros; trivial.\n  rewrite add_0_r in *. rewrite add_S_r. cbn. rewrite H. trivial.\nQed.\n(* end hide *)\n\nLemma div2_le :\n  forall n : nat, div2 n <= n.\n(* begin hide *)\nProof.\n  apply nat_ind_2; cbn; intros; trivial; try (repeat constructor; fail).\n  apply le_n_S. constructor. assumption.\nQed.\n(* end hide *)\n\nLemma div2_pres_le :\n  forall n m : nat, n <= m -> div2 n <= div2 m.\n(* begin hide *)\nProof.\n  induction n using nat_ind_2; cbn; intros; try apply le_0_l.\n  destruct m as [| [| m']]; cbn.\n    inversion H. \n    inversion H. inversion H1.\n    apply le_n_S, IHn. do 2 apply le_S_n. assumption.\nQed.  \n(* end hide *)\n\nLemma mod2_le :\n  forall n : nat, mod2 n <= n.\n(* begin hide *)\nProof.\n  apply nat_ind_2; cbn; intros; trivial; repeat constructor; assumption.\nQed.\n(* end hide *)\n\nLemma mod2_not_pres_e :\n  exists n m : nat, n <= m /\\ mod2 m <= mod2 n.\n(* begin hide *)\nProof.\n  exists (S (S (S 0))), (S (S (S (S 0)))). cbn.\n  split; repeat constructor.\nQed.\n(* end hide *)\n\nLemma div2_lt :\n  forall n : nat,\n    0 <> n -> div2 n < n.\n(* begin hide *)\nProof.\n  induction n using nat_ind_2; cbn; intros.\n    contradiction H. reflexivity.\n    apply le_n.\n    unfold lt in *. destruct n as [| n'].\n      cbn. apply le_n.\n      specialize (IHn ltac:(inversion 1)). apply le_n_S.\n        apply le_trans with (S n').\n          assumption.\n          apply le_S, le_n.\nQed.\n(* end hide *)\n\n(** ** Podzielność *)\n\nModule divides.\n\nDefinition divides (k n : nat) : Prop :=\n  exists m : nat, mul k m = n.\n\nNotation \"k | n\" := (divides k n) (at level 40).\n\n(** [k] dzieli [n] jeżeli [n] jest wielokrotnością [k]. Udowodnij podstawowe\n    właściwości tej relacji. *)\n\nLemma divides_0 :\n  forall n : nat, n | 0.\n(* begin hide *)\nProof.\n  intro. red. exists 0. apply mul_0_r.\nQed.\n(* end hide *)\n\nLemma not_divides_0 :\n  forall n : nat, n <> 0 -> ~ 0 | n.\n(* begin hide *)\nProof.\n  unfold not, divides; intros. destruct H0 as [m Hm].\n  rewrite mul_0_l in Hm. congruence.\nQed.\n(* end hide *)\n\nLemma divides_1 :\n  forall n : nat, 1 | n.\n(* begin hide *)\nProof.\n  intro. red. exists n. apply mul_1_l.\nQed.\n(* end hide *)\n\nLemma divides_refl :\n  forall n : nat, n | n.\n(* begin hide *)\nProof.\n  intro. red. exists 1. apply mul_1_r.\nQed.\n(* end hide *)\n\nLemma divides_trans :\n  forall k n m : nat, k | n -> n | m -> k | m.\n(* begin hide *)\nProof.\n  unfold divides; intros.\n  destruct H as [c1 H1], H0 as [c2 H2].\n  exists (mul c1 c2). rewrite mul_assoc. rewrite H1, H2. trivial.\nQed.\n(* end hide *)\n\nLemma divides_add :\n  forall k n m : nat, k | n -> k | m -> k | add n m.\n(* begin hide *)\nProof.\n  unfold divides; intros.\n  destruct H as [c1 H1], H0 as [c2 H2].\n  exists (add c1 c2). rewrite mul_add_r. rewrite H1, H2. trivial.\nQed.\n(* end hide *)\n\nLemma divides_mul_l :\n  forall k n m : nat, k | n -> k | mul n m.\n(* begin hide *)\nProof.\n  unfold divides. destruct 1 as [c H].\n  exists (mul c m). rewrite mul_assoc. rewrite H. trivial.\nQed.\n(* end hide *)\n\nLemma divides_mul_r :\n  forall k n m : nat, k | m -> k | mul n m.\n(* begin hide *)\nProof.\n  intros. rewrite mul_comm. apply divides_mul_l. assumption.\nQed.\n(* end hide *)\n\nLemma divides_le :\n  ~ forall k n : nat, k | n -> k <= n.\n(* begin hide *)\nProof.\n  intro. cut (1 <= 0).\n    inversion 1.\n    apply H. red. exists 0. cbn. reflexivity.\nQed.\n(* end hide *)\n\n(* begin hide *)\nDefinition prime (p : nat) : Prop :=\n  forall k : nat, k | p -> k = 1 \\/ k = p.\n\nLemma double_not_prime :\n  forall n : nat,\n    n <> 1 -> ~ prime (mul 2 n).\nProof.\n  unfold prime, not; intros.\n  destruct (H0 2).\n    red. exists n. reflexivity.\n    inversion H1.\n    destruct n as [| [| n']]; inversion H1.\n      apply H. reflexivity.\n      rewrite add_comm in H3. inversion H3.\nQed.\n(* end hide *)\n\nEnd divides.\n\n(** * Silnia *)\n\n(** Zdefiniuj silnię.\n\n    Przykład:\n    [fac 5 = 1 * 2 * 3 * 4 * 5 = 120]\n\n*)\n\n(* begin hide *)\nFixpoint fac (n : nat) : nat :=\nmatch n with\n| 0 => 1\n| S n' => mul n (fac n')\nend.\n(* end hide *)\n\nLemma le_1_fac :\n  forall n : nat, 1 <= fac n.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn.\n    constructor.\n    replace 1 with (add 1 0).\n      apply le_add.\n        assumption.\n        apply le_0_l.\n      apply add_comm.\nQed.\n(* end hide *)\n\nLemma le_lin_fac :\n  forall n : nat, n <= fac n.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn.\n    apply le_0_l.\n    replace (S n') with (add 1 n') by reflexivity.\n      apply le_add.\n        apply le_1_fac.\n        replace n' with (mul n' 1) at 1.\n          apply le_mul.\n            apply le_n.\n            apply le_1_fac.\n          apply mul_1_r.\nQed.\n(* end hide *)\n\nFixpoint pow2 (n : nat) : nat :=\nmatch n with\n| 0 => 1\n| S n' => mul 2 (pow2 n')\nend.\n\nNotation \"4\" := (S (S (S (S 0)))).\n\nLemma le_exp_fac :\n  forall n : nat, 4 <= n -> pow2 n <= fac n.\n(* begin hide *)\nProof.\n  induction 1; cbn.\n    repeat constructor.\n    rewrite add_0_r. apply le_add.\n      assumption.\n      replace (pow2 m) with (mul 1 (pow2 m)).\n        apply le_mul.\n          apply le_trans with 4; auto. repeat constructor.\n          assumption.\n        apply mul_1_l.\nQed.\n(* end hide *)\n\n(** * Współczynnik dwumianowy (TODO) *)\n\n(** Zdefiniuj współczynnik dwumianowy. Jeżeli nie wiesz co to, to dobrze:\n    będziesz miał więcej zabawy. W skrócie [binom n k] to ilość podzbiorów\n    zbioru [n] elementowego, którego mają [k] elementów. *)\n\n(* begin hide *)\nFunction binom (n k : nat) : nat :=\nmatch n, k with\n| 0, 0 => 1\n| 0, _ => 0\n| _, 0 => 1\n| S n', S k' => add (binom n' k') (binom n' k)\nend.\n(* TODO: być może przedefiniować współczynnik dwumianowy na bardziej ludzki *)\n(* end hide *)\n\nFixpoint double (n : nat) : nat :=\nmatch n with\n| 0 => 0\n| S n' => S (S (double n'))\nend.\n\nLemma binom_0_r :\n  forall n : nat, binom n 0 = 1.\n(* begin hide *)\nProof.\n  destruct n; cbn; reflexivity.\nQed.\n(* end hide *)\n\nLemma binom_0_l :\n  forall n : nat, binom 0 (S n) = 0.\n(* begin hide *)\nProof.\n  reflexivity.\nQed.\n(* end hide *)\n\nLemma binom_1_r :\n  forall n : nat, binom n 1 = n.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn.\n    reflexivity.\n    rewrite IHn', binom_0_r. cbn. reflexivity.\nQed.\n(* end hide *)\n\nLemma binom_gt :\n  forall n k : nat, n < k -> binom n k = 0.\n(* begin hide *)\nProof.\n  induction n as [| n'];\n  destruct k as [| k']; cbn;\n  try (inversion 1; trivial; fail); intro.\n  rewrite !IHn'.\n    reflexivity.\n    apply lt_trans with (S n').\n      apply le_n.\n      assumption.\n      apply le_S_n. assumption.\nQed.\n(* end hide *)\n\nLemma binom_diag :\n  forall n : nat, binom n n = 1.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn.\n    reflexivity.\n    rewrite IHn', binom_gt.\n      reflexivity.\n      constructor.\nQed.\n(* end hide *)\n\nLemma binom_sym :\n  forall n k : nat,\n    k <= n -> binom n k = binom n (sub' n k).\n(* begin hide *)\nProof.\n  intros n k. revert n.\n  induction k as [| k']; cbn; intros.\n    rewrite binom_0_r, binom_diag. reflexivity.\n    induction n as [| n']; cbn.\n      inversion H.\n      rewrite pred_sub'_S. destruct (sub' n' k') eqn: Heq.\n        rewrite IHk', Heq, binom_0_r, binom_gt.\n          reflexivity.\n          apply sub'_0 in Heq. apply le_n_S. assumption.\n          apply le_S_n. assumption.\n        apply le_S_n in H. inversion H; subst; try rename m into n'.\n          rewrite sub'_diag in Heq. inversion Heq.\n          rewrite add_comm, IHn', IHk', Heq.\n            reflexivity.\n            assumption.\n            apply le_n_S. assumption.\nQed.\n(* end hide *)\n\nLemma sub_sub' :\n  forall n m : nat,\n    sub n m = sub' n m.\n(* begin hide *)\nProof.\n  induction n as [| n'];\n  destruct  m as [| m'];\n  cbn.\n    reflexivity.\n    rewrite sub'_0_l. cbn. reflexivity.\n    reflexivity.\n    rewrite IHn', pred_sub'_S. reflexivity.\nQed.\n(* end hide *)\n\nLemma binom_sym' :\n  forall n k : nat,\n    k <= n -> binom n k = binom n (sub n k).\n(* begin hide *)\nProof.\n  intros.\n  rewrite sub_sub'.\n  apply binom_sym.\n  assumption.\nQed.\n(* end hide *)\n\nFunction binom' (n k : nat) : nat :=\nmatch k with\n| 0    => 1\n| S k' =>\n  match n with\n  | 0    => 0\n  | S n' => add (binom' n' k') (binom' n' k)\n  end\nend.\n\nLemma binom_S_S :\n  forall n k : nat,\n    mul (S k) (binom (S n) (S k)) = mul (S n) (binom n k).\n(* begin hide *)\nProof.\n  intros.\n  functional induction binom n k;\n  cbn.\n    admit.\nAdmitted.\n(* end hide *)\n\nLemma binom_spec :\n  forall n k : nat,\n    k <= n -> mul (fac k) (mul (fac (sub' n k)) (binom n k)) = fac n.\n(* begin hide *)\nProof.\n  induction n as [| n'].\n    inversion 1; subst. cbn. reflexivity.\n    destruct k as [| k'].\n      intro. cbn. rewrite add_0_r, mul_1_r. reflexivity.\n      {\n        intros. cbn [sub']. rewrite pred_sub'_S. cbn [fac].\n        replace (mul (mul (S k') _) _) with\n                (mul (mul (S k') (binom (S n') (S k'))) (mul (fac k') (fac (sub' n' k')))).\n          rewrite binom_S_S. replace (mul (mul _ _) _) with\n                                     (mul (S n') (mul (fac k') (mul (fac (sub' n' k')) (binom n' k')))).\n            rewrite IHn'.\n              reflexivity.\n              apply le_S_n. assumption.\n            rewrite <- !mul_assoc. f_equal. rewrite (mul_comm (fac _)).\n              rewrite <- !mul_assoc, mul_comm, <- !mul_assoc. reflexivity.\n          rewrite <- !mul_assoc. f_equal. rewrite (mul_comm (binom _ _)).\n              rewrite <- !mul_assoc, mul_comm, <- !mul_assoc. reflexivity.\n      }\nQed.\n(* end hide *)\n\n(* begin hide *)\nModule MyDiv2. (* TODO: szybkie mnożenie *)\n\nImport Div2 ZArith.\n\nFixpoint evenb (n : nat) : bool :=\nmatch n with\n| 0 => true\n| 1 => false\n| S (S n') => evenb n'\nend.\n\n(*\nFixpoint quickMul (fuel n m : nat) : nat :=\nmatch fuel with\n| 0 => 0\n| S fuel' =>\n  match n with\n  | 0 => 0\n  | _ =>\n    let res := quickMul fuel' (div2 n) m in\n      if evenb n then add res res else add (add m res) res\n  end\nend.\n\nTime Eval compute in 430 * 110.\nTime Eval compute in quickMul 1000 430 110.\n\nFunction qm (n m : nat) {measure id n} : nat :=\nmatch n with\n| 0 => 0\n| _ =>\n  let r := qm (div2 n) m in\n    if evenb n then 2 * r else m + 2 * r\nend.\nProof.\nAbort.\n\n*)\nEnd MyDiv2.\n(* end hide *)\n\n(** * Wzory rekurencyjne (TODO) *)\n\n(** * Sumy szeregów (TODO) *)\n\n(** Udowodnij, że [2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1].\n    Zaimplementuj w tym celu celu funkcję [f], która oblicza lewą\n    stronę tego równania, a następnie pokaż, że [f n = 2^(n + 1) - 1]\n    dla dowolnego [n : nat]. *)\n\n(* begin hide *)\nFixpoint twos (n : nat) : nat :=\nmatch n with\n| 0 => pow2 0\n| S n' => add (twos n') (pow2 n)\nend.\n(* end hide *)\n\nLemma twos_spec :\n  forall n : nat, twos n = sub (pow2 (S n)) 1.\n(* begin hide *)\nProof.\n  induction n as [| n']; cbn.\n    reflexivity.\n    rewrite IHn'. cbn. rewrite !add_0_r.\n      generalize dependent (add (pow2 n') (pow2 n')). destruct n.\n        reflexivity.\n        cbn. rewrite !sub_0_r. reflexivity.\nQed.\n(* end hide *)\n\n(* begin hide *)\n(* TODO: dziwna indukcja (ale o co tu miało chodzić?) *)\n(* end hide *)\n\nEnd MyNat.\n\n(** * Dyskretny pierwiastek kwadratowy (TODO) *)\n\n(* begin hide *)\n\n(** TODO: dyskretny pierwiastek kwadratowy *)\n\nRequire Import Lia Arith.\n\nLemma root : forall n : nat, {r : nat | r * r <= n < (S r) * (S r)}.\nProof.\n  induction n as [| n'].\n    exists 0. cbn; split.\n      trivial.\n      apply le_n.\n    destruct IHn' as [r [H1 H2]].\n    destruct (le_lt_dec ((S r) * (S r)) (S n')).\n      exists (S r). cbn; split.\n        cbn in l. assumption.\n        cbn in *. rewrite <- Nat.succ_lt_mono.\n        repeat match goal with\n        | H : context [?x + S ?y] |- _ =>\n          rewrite (add_comm x (S y)) in H; cbn in H\n        | H : context [?x * S ?y] |- _ =>\n          rewrite (mul_comm x (S y)) in H; cbn in H\n        | |- context [?x + S ?y] => rewrite (add_comm x (S y)); cbn\n        | |- context [?x * S ?y] => rewrite (mul_comm x (S y)); cbn\n        end. lia.\n      exists r. cbn; split.\n        apply Nat.le_trans with n'.\n          assumption.\n          apply le_S. apply le_n.\n        cbn in l. assumption.\nDefined.\n\nDefinition root' (n : nat) : nat.\nProof.\n  destruct (root n). exact x.\nDefined.\n\nEval compute in root' 24.\n\nFixpoint div4 (n : nat) : nat :=\nmatch n with\n| 0 => 0\n| 1 => 0\n| 2 => 0\n| 3 => 0\n| S (S (S (S n'))) => S (div4 n')\nend.\n\nFixpoint nat_ind_4 (P : nat -> Prop) (H0 : P 0) (H1 : P 1) (H2 : P 2) (H3 : P 3)\n    (H4 : forall n : nat, P n -> P (S (S (S (S n))))) (n : nat) : P n.\nProof.\n  destruct n.\n    exact H0.\n    destruct n.\n    exact H1.\n      destruct n.\n        exact H2.\n        destruct n.\n          exact H3.\n          apply H4. apply nat_ind_4; assumption.\nDefined.\n\nFixpoint nat_ind_3 (P : nat -> Prop) (H0 : P 0) (H1 : P 1) (H2 : P 2)\n    (H3 : forall n : nat, P n -> P (S (S (S n)))) (n : nat) : P n.\nProof.\n  destruct n.\n    exact H0.\n    destruct n.\n    exact H1.\n      destruct n.\n        exact H2.\n        apply H3. apply nat_ind_3; assumption.\nDefined.\n\nRequire Import Init.Wf.\n\nLemma div4_lemma : forall n : nat,\n    S (div4 n) < S (S (S (S n))).\nProof.\n  induction n using nat_ind_4; cbn; lia.\nQed.\n\nLemma nat_ind_div4 (P : nat -> Type) (H0 : P 0)\n    (Hdiv : forall n : nat, P (div4 n) -> P n) (n : nat) : P n.\nProof.\n  apply (Fix lt_wf P). intros.\n  destruct x.\n    apply H0.\n    destruct x.\n      apply Hdiv. cbn. apply H0.\n      destruct x.\n        apply Hdiv. cbn. apply H0.\n        destruct x.\n          apply Hdiv. cbn. apply H0.\n          apply Hdiv. cbn. apply X. apply div4_lemma.\nDefined.\n\nLtac nat_cbn := repeat\nmatch goal with\n| H : context [?x + S ?y] |- _ =>\n    rewrite (Nat.add_comm x (S y)) in H; cbn in H\n| H : context [?x * S ?y] |- _ =>\n  rewrite (Nat.mul_comm x (S y)) in H; cbn in H\n| |- context [?x + S ?y] => rewrite (Nat.add_comm x (S y)); cbn\n| |- context [?x * S ?y] => rewrite (Nat.mul_comm x (S y)); cbn\nend;\nrepeat rewrite Nat.add_0_r.\n\n(* end hide *)\n\n(** * Zadania *)\n\n(** **** Ćwiczenie (przeszukiwanko) *)\n\nSection reverse.\n\nContext\n  (f : nat -> nat)\n  (Hzero : f 0 = 0)\n  (Hincreasing : forall m n, m < n -> f m < f n).\n\n(** Udowodnij, że przy powyższych założeniach dla każdego [y : nat] istnieje [x : nat]\n    takie, że [f x <= y <= f (S x)]. Zdefiniuj w tym celu funkcję [g : nat -> nat] i\n    udowodnij, że spełnia ona specyfikację. *)\n\n(* begin hide *)\n\n(** **** Rozwiązanie *)\n\n(** Definicja jest prosta:\n    - jeżeli [y] to [0], to zwróć [0]\n    - jeżeli [x] który znaleźliśmy dla [y - 1] jest dalej ok, to zwróć [x]\n    - w przeciwnym wypadku zwróć [x + 1] *)\n\nFixpoint g (y : nat) : nat :=\nmatch y with\n| 0 => 0\n| S y' =>\n  let x := g y' in\n    if Nat.ltb y (f (S x))\n    then x\n    else S x\nend.\n\n(** Dowód też jest prosty i ma taki sam kształt jak definicja funkcji [g]. *)\nLemma g_correct : forall y (x := g y), f x <= y < f (S x).\nProof.\n  induction y as [| y']; simpl.\n  - split.\n    + rewrite Hzero. apply le_n.\n    + rewrite <- Hzero at 1. apply Hincreasing. lia.\n  - destruct (Nat.ltb_spec (S y') (f (S (g y')))).\n    + split.\n      * destruct IHy'. lia.\n      * assumption.\n    + split.\n      * assumption.\n      * destruct IHy'. assert (f (S (g y')) < f (S (S (g y')))).\n        -- apply Hincreasing. lia.\n        -- lia.\nQed.\n\n(** Uwaga: komenda [Function] nie upraszcza powyższego dowodu ani trochę. *)\n\n(* end hide *)\n\nEnd reverse.", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/book/D4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189134878876, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.6778636415343287}}
{"text": "(** * Geometric series definition and proof of convergence. *)\n\n(** Divergent series are the devil, and it is a shame to base on them\n    any demonstration whatsoever. (Niels Henrik Abel, 1826)\n    (https://www.math.ucdavis.edu/~hunter/intro_analysis_pdf/ch4.pdf) *)\n\nSet Implicit Arguments.\n\nFrom Coq Require Import\n  Lia\n  Lra\n  Reals\n.\n\nLocal Open Scope R_scope.\n\nFrom zar Require Import\n  cpo\n  eR\n  order\n  tactics\n.\n\nFixpoint geometric_series (a r : eR) (n : nat) : eR :=\n  match n with\n  | O => 0\n  | S n' => geometric_series a r n' + a * r ^ n'\n  end.\n\nLemma eRmult_infty_inv a b :\n  a * b = infty ->\n  a = infty \\/ b = infty.\nProof. intro Hab; destruct a, b; inv Hab; auto. Qed.\n\nLemma eRpow_infty_inv r i :\n  r ^ i = infty ->\n  r = infty.\nProof.\n  revert r; induction i; simpl; intros r Hr.\n  - inv Hr.\n  - apply eRmult_infty_inv in Hr; destruct Hr; auto.\nQed.\n\nLemma geometric_series_sum (r : eR) (n : nat) :\n  r < 1 ->\n  geometric_series 1 r n = (1 - r ^ n) / (1 - r).\nProof.\n  revert r; induction n; intros r Hr; simpl.\n  { rewrite eRminus_cancel; eRauto. }\n  rewrite eRmult_1_l.\n  rewrite IHn; auto; clear IHn.\n  replace ((1 - r ^ n) / (1 - r) + r ^ n) with\n    ((1 - r ^ n) / (1 - r) + ((1 - r) * r ^ n) / (1 - r)).\n  2: { rewrite eRmult_div_cancel; eRauto; intro HC.\n       symmetry in HC; apply eRminus_eq_plus in HC; eRauto.\n       rewrite eRplus_0_r in HC; subst.\n       inv Hr; lra. }\n  rewrite eRplus_combine_fract; f_equal.\n  rewrite eRmult_minus_distr_r.\n  2: { intro HC; apply eRpow_infty_inv in HC; subst; inv Hr. }\n  rewrite eRmult_1_l.\n  rewrite eRplus_minus_assoc.\n  2: { intro HC; apply eRpow_infty_inv in HC; subst; inv Hr. }\n  2: { eRauto. }\n  f_equal.\n  rewrite <- eRminus_assoc.\n  { eRauto. }\n  { apply eRpow_le_1; eRauto. }\n  { reflexivity. }\n  { intro HC; apply eRpow_infty_inv in HC; subst; inv Hr. }\nQed.\n\nLemma eRpow_pow a r n r1 r2 :\n  er a r ^ n = er r1 r2 ->\n  (a ^ n)%R = r1.\nProof.\n  revert a r r1 r2; induction n; simpl; intros a r r1 r2 H.\n  { inv H; reflexivity. }\n  unfold eRmult in H.\n  destruct (er a r ^ n) eqn:Har.\n  - inv H; erewrite IHn; eauto.\n  - apply eRpow_infty_inv in Har; inv Har.\nQed.\n\nLemma pow_seq_converges (a : eR) :\n  a < 1 ->\n  converges (eRpow a) 0.\nProof.\n  intros Ha eps Heps.\n  destruct a as [a|].\n  2: { inv Ha. }\n  inv Ha.\n  destruct (Req_dec a 0); subst.\n  - exists (S O); intros n Hn.\n    unfold diff. simpl.\n    destruct n; simpl; try lia.\n    + rewrite eRmult_0_l'; simpl; destr.\n      2: { exfalso; lra. }\n      destruct eps; constructor; inv Heps; lra.\n  - assert (Hr: R.converges_R (R.pow_sequence a) 0%R).\n    { apply R.pow_sequence_converges'; lra. }\n    unfold R.converges_R in Hr.\n    destruct eps as [eps|].\n    2: { exists O; intros n Hn.\n         unfold diff; simpl.\n         destruct (er a r ^ n) eqn:Hrn.\n         - destr; constructor.\n         - apply eRpow_infty_inv in Hrn; inv Hrn. }\n    inv Heps.\n    specialize (Hr eps H3).\n    destruct Hr as [n0 Hr].\n    exists n0; intros n Hn; specialize (Hr n Hn).\n    unfold R.pow_sequence in Hr.\n    unfold diff.\n    rewrite Rabs_minus_sym in Hr.\n    rewrite Rminus_0_r in Hr.\n    destruct (er a r ^ n) eqn:Hrn; simpl.\n    + destr.\n      * constructor.\n        rewrite Rabs_pos_eq in Hr.\n        2: { apply pow_le; lra. }\n        rewrite Rminus_0_r.\n        eapply Rle_lt_trans.\n        2: { apply Hr. }\n        apply eRpow_pow in Hrn; lra.\n      * constructor; lra.\n    + apply eRpow_infty_inv in Hrn; inv Hrn.\nQed.\n\nLemma infimum_0_minus_supremum (a : eR) (f : nat -> eR) :\n  dec_chain f ->\n  upper_bound a f ->\n  infimum 0 f ->\n  supremum a (fun i => a - f i).\nProof.\n  intros Hch Ha H0; split.\n  - intro; eRauto.\n  - intros x Hx; simpl.\n    unfold upper_bound in Hx; simpl in Hx.\n    destruct H0 as [Hlb Hglb]; simpl in *.\n    assert (Haxf: lower_bound (a - x) f).\n    { intro i; simpl.\n      apply eRplus_le_minus.\n      rewrite eRplus_comm.\n      apply eRminus_le_plus; auto. }\n    apply Hglb in Haxf.\n    apply eRminus_le_plus in Haxf; rewrite eRplus_0_l in Haxf; auto.\nQed.\n\nLemma geometric_series_supremum_1 (r : eR) :\n  r < 1 ->\n  supremum (1 / (1 - r)) (geometric_series 1 r).\nProof.\n  intro Hr.\n  replace (geometric_series 1 r) with (fun n => (1 - r ^ n) / (1 - r)).\n  2: { ext i; rewrite geometric_series_sum; auto. }\n  replace (fun n : nat => (1 - r ^ n) / (1 - r)) with\n    (fun n : nat => 1 / (1 - r) - r ^ n / (1 - r)).\n  2: { ext i; rewrite eRdiv_minus_distr; eRauto.\n       intro HC. symmetry in HC; apply eRminus_eq_plus in HC; eRauto.\n       rewrite eRplus_0_r in HC; subst.\n       inv Hr; lra. }\n  apply infimum_0_minus_supremum.\n  { intro i; simpl.\n    unfold eRdiv.\n    rewrite eRmult_assoc.\n    apply eRmult_le_1_le; eRauto. }\n  { intro i; simpl.\n    apply eRle_div.\n    apply eRpow_le_1; eRauto. }\n  replace (fun i : nat => r ^ i / (1 - r)) with\n    (fun i : nat => / (1 - r) * r ^ i).\n  2: { ext i; rewrite eRmult_comm; reflexivity. }\n  replace 0 with (/ (1 - r) * 0) by eRauto.\n  apply infimum_scalar.\n  { unfold eRinv, eRminus; simpl.\n    destruct r as [r|]; simpl; inv Hr.\n    destruct (Rle_dec r 1); simpl.\n    - destr.\n      + lra.\n      + intro HC; inv HC.\n    - lra. }\n  { apply converges_infimum.\n    - intro i; simpl.\n      apply eRmult_le_1_le; eRauto.\n    - intro i; intro HC; apply eRpow_infty_inv in HC; subst; inv Hr.\n    - apply pow_seq_converges; auto. }\nQed.\n\nLemma geometric_series_scalar a r  i:\n  geometric_series a r i = a * geometric_series 1 r i.\nProof.\n  revert a r; induction i; intros a r; simpl.\n  { eRauto. }\n  rewrite IHi, eRmult_1_l, eRmult_plus_distr_l; reflexivity.\nQed.\n\nLemma geometric_series_supremum (a r : eR) :\n  r < 1 ->\n  supremum (a / (1 - r)) (geometric_series a r).\nProof.\n  intro Hr.\n  replace (geometric_series a r) with (fun i => a * geometric_series 1 r i).\n  2: { ext i; rewrite <- geometric_series_scalar; reflexivity. }\n  unfold eRdiv.\n  apply supremum_scalar.\n  replace (/ (1 - r)) with (1 / (1 - r)) by eRauto.\n  apply geometric_series_supremum_1; auto.\nQed.\n\nCorollary geometric_series_sup (a r : eR) :\n  r < 1 ->\n  sup (geometric_series a r) = a / (1 - r).\nProof.\n  intro Hr; apply equ_eR, supremum_sup, geometric_series_supremum; auto.\nQed.\n", "meta": {"author": "bagnalla", "repo": "zar", "sha": "ec7ef01ac4c2cf2c1b2b59a921a92f05cc2f1f51", "save_path": "github-repos/coq/bagnalla-zar", "path": "github-repos/coq/bagnalla-zar/zar-ec7ef01ac4c2cf2c1b2b59a921a92f05cc2f1f51/geometric_series.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.6778636308038856}}
{"text": "\nParameter (Y : Type).\nAxiom Y_eq_dec : forall (x y : Y), {x = y} + {~x = y}.\nParameter (ordre : Y -> Y -> Prop).\nAxiom total_ordre : forall (x y : Y), {ordre x y} + {ordre y x}.\nHypothesis ordre_refl : forall y, ordre y y.\nHypothesis ordre_sym : forall x y, ordre x y /\\ ordre y x -> x = y.\nHypothesis ordre_trans : forall x y z, ordre x y -> ordre y z -> ordre x z.\n(*just some variables names to facilitate the definition of lhs and rhs*)\nVariable (x : Y).\nVariable (y : Y).\nVariable (z : Y).\n\n\nInductive est_dans : Y -> list Y -> Prop :=\n|construct: forall (x : Y) (l : list Y), est_dans x (cons x l) \n|propag : forall (x y : Y) (l : list Y),  est_dans x l -> est_dans x (cons y l).\n\nInductive sans_doublon :list Y -> Prop :=\n|cas_base_sd: sans_doublon nil\n|cas_cons_sd : forall (l : list Y) (x : Y), sans_doublon l -> ~(est_dans x l) -> sans_doublon (cons x l).\n\nCheck ordre.\n\nInductive triee : list Y -> Prop :=\n|cas_nil_tri : triee nil\n|cas_x_tri : forall (x : Y), triee (cons x nil)\n|cas_cons_tri : forall (x y: Y)(l : list Y), triee (x :: l) -> ordre y x  -> triee (cons y (cons x l )).\nRequire Import QArith.\n\nFixpoint calcul (phi : Y -> Q) (l  : list Y) : Q := match l with \n|nil => 0%Q\n|cons x q => phi x + calcul phi q\nend.\n\nFixpoint inserer (x : Y) (l : list Y) : list Y := \nmatch l with \n|nil => cons x nil\n|cons y q => match (Y_eq_dec x y) with \n             |left _ => l \n             |right _ => match (total_ordre x y) with \n                        |left _ => cons x (cons y q)\n                        |right _ => cons y (inserer x q)\n                      end\n             end\nend.\n\nFixpoint union (l l' : list Y) : list Y :=\nmatch l with \n|nil => l'\n|cons y q => union q (inserer y l')\nend.\n\nRecord ensemble_fini :=\n{ensemble :>  list Y ; \nis_a_set : sans_doublon ensemble ; \nis_sorted : triee ensemble }.\n\nLemma tri_logique : forall (l : list Y) (x y : Y), \ntriee (cons x l) -> est_dans y l -> ordre x y.\nProof.\nintros.\ninduction l.\ninversion H0. \ndestruct (Y_eq_dec y0 a).\ninversion H.\nrewrite e.\nauto.\napply IHl. \ninversion H.\ninversion H3.\napply cas_x_tri.\napply cas_cons_tri.\nauto.\napply ordre_trans with (y := a).\nauto.\nauto.\ninversion H0.\nassert (False).\napply n.\nauto.\ninversion H2.\nauto.\nQed.\n\nPrint tri_logique.\n\nLemma tri_cons_tri : forall (l : list Y) (a : Y), \ntriee (cons a l) -> triee l.\nProof.\nintros.\ninduction l.\napply cas_nil_tri.\ninversion H.\nauto.\nQed.\n\n\nLemma tri_not_inside : forall (l : list Y) (a x0: Y) , \ntriee (cons a l) -> x0 <> a -> ordre x0 a -> ~(est_dans x0 l).\nProof.\nintros.\ninversion H.\nintro.\ninversion H2.\nrewrite <- H3 in H.\nintro.\nassert ({ordre x1 x0} + {ordre x0 x1}).\napply total_ordre.\ndestruct H7.\napply H0.\napply ordre_sym.\nsplit.\nauto.\napply ordre_trans with (y := x1).\nauto.\nauto.\nassert ({x0 = x1}+ {x0 <> x1}).\napply Y_eq_dec.\ndestruct H7.\napply H0.\napply ordre_sym.\nsplit.\nauto.\nrewrite e.\nauto.\ninversion H6.\napply n.\nauto.\napply H0.\napply ordre_sym.\nsplit.\nauto.\napply ordre_trans with (y := x1).\nauto.\napply tri_logique with (l := l0).\nauto.\nauto.\nQed.\n\nLemma insertion_preserves_inside : forall (l : list Y) (a x0 :Y), \nest_dans a l -> est_dans a (inserer x0 l).\nProof.\nintros.\ninduction l.\ninversion H.\nsimpl.\ndestruct (Y_eq_dec x0 a0).\nauto.\ndestruct (total_ordre x0 a0).\napply propag.\nauto.\ndestruct (Y_eq_dec a a0).\nrewrite e.\napply construct.\napply propag.\napply IHl.\ninversion H.\nassert (False).\napply n0.\nauto.\ninversion H1.\nauto.\nQed.\n\nLemma insertion_alr_min : forall (l : list Y) (a : Y), \n(forall (x : Y), est_dans x l -> ordre a x) -> ~est_dans a l-> (inserer a l = cons a l).\nProof.\nintros.\ninduction l.\nsimpl.\nreflexivity.\nsimpl.\ndestruct (Y_eq_dec a a0).\nexfalso.\napply H0.\nrewrite e.\napply construct.\ndestruct (total_ordre a a0).\nreflexivity.\nexfalso.\napply n.\napply ordre_sym.\nsplit.\napply H.\napply construct.\nauto.\nQed.\n\nLemma insertion_conserves_inside : forall (l : list Y) (a x0 :Y), \nest_dans a (inserer x0 l) /\\x0 <> a -> est_dans a l.\nProof.\nintros.\ninduction l.\ninversion H.\nsimpl.\nsimpl in H0.\ninversion H0.\nassert (False).\napply H1.\nsymmetry ; auto.\ninversion H3.\nauto.\ndestruct (Y_eq_dec a a0).\nrewrite e.\napply construct.\napply propag.\napply IHl.\nsplit.\nsimpl in H.\ndestruct (Y_eq_dec x0 a0).\ndestruct H.\ninversion H.\nassert (False).\napply n.\nauto.\ninversion H2.\napply insertion_preserves_inside.\nauto.\ndestruct (total_ordre x0 a0).\ndestruct H.\ninversion H.\nassert (False).\napply H0.\nsymmetry.\nauto.\ninversion H2.\ninversion H3.\nassert (False).\napply n.\nsymmetry.\nauto.\ninversion H6.\napply insertion_preserves_inside.\nauto.\ndestruct H.\ninversion H.\nassert (False).\napply n.\nsymmetry.\nauto.\ninversion H2.\nauto.\ndestruct H.\nauto.\nQed.\n\n\nLemma insertion_preserves_doublon : forall (l : list Y)(x0 a : Y),\nsans_doublon (cons a l) -> x0 <> a -> ((est_dans a (inserer x0 l)) -> False).\nProof.\nintros.\ninduction l.\nsimpl in H1.\ninversion H1.\napply H0.\napply symmetry.\nauto.\ninversion H4.\nsimpl in H1.\ndestruct (Y_eq_dec x0 a0).\ninversion H1.\ninversion H.\napply H8.\nrewrite H4.\napply construct.\napply IHl.\ninversion H.\napply cas_cons_sd.\ninversion H8.\nauto.\nintro. \napply H9.\nauto.\napply insertion_preserves_inside.\nauto.\ndestruct (total_ordre x0 a0).\napply IHl.\ninversion H.\ninversion H4.\napply cas_cons_sd.\nauto.\nintro.\napply H5.\napply propag.\nauto.\nassert (False).\napply IHl.\ninversion H.\ninversion H4.\napply cas_cons_sd.\nauto.\nintro.\napply H5.\napply propag.\nauto.\napply insertion_preserves_inside.\ninversion H1.\nassert (False).\napply H0.\nauto.\ninversion H3.\ninversion H4.\ninversion H.\nassert (False).\napply H12.\nrewrite H8.\napply construct.\ninversion H13.\nauto.\ninversion H2.\napply IHl.\ninversion H.\ninversion H4.\nauto.\napply cas_cons_sd.\nauto.\nintro.\napply H5.\napply propag.\nauto.\ninversion H1.\ninversion H.\nassert (False).\napply H8.\nrewrite H4.\napply construct.\ninversion H9.\nauto.\nQed.\n\nLemma sans_doublon_inserer : forall (l : list Y) (x : Y), \ntriee l -> sans_doublon l -> sans_doublon (inserer x l).\nProof.\nintros.\ninduction l.\nsimpl.\napply cas_cons_sd.\nauto.\nintro.\ninversion H1.\nsimpl.\ndestruct (Y_eq_dec x0 a).\nexact H0.\ndestruct (total_ordre x0 a).\napply cas_cons_sd.\nexact H0.\napply tri_not_inside with (a := a).\napply cas_cons_tri.\nauto.\napply ordre_refl.\nauto.\nauto.\napply cas_cons_sd.\napply IHl.\ninversion H.\napply cas_nil_tri.\nauto.\ninversion H0.\nauto.\nassert (est_dans a (inserer x0 l) -> False).\napply insertion_preserves_doublon with (x0 := x0) (a := a) (l := l).\nauto.\nauto.\nauto.\nQed.\n\nLemma insertion_preserves_tri : forall (l : list Y)(a : Y), \nsans_doublon l -> triee l -> triee (inserer a l).\nProof.\nintros.\ngeneralize dependent a.\ninduction l.\nintros.\nsimpl.\napply cas_x_tri.\nintros.\nsimpl.\ndestruct (Y_eq_dec a0 a).\nauto.\ndestruct (total_ordre a0 a).\napply cas_cons_tri.\nauto.\nauto.\nassert (triee (inserer a0 l)).\napply IHl.\ninversion H.\nauto.\ninversion H0.\nauto.\napply cas_nil_tri.\nauto.\ndestruct l.\nsimpl.\napply cas_cons_tri.\nauto.\nauto.\nsimpl.\nsimpl in H1.\ndestruct (Y_eq_dec a0 y0).\nauto.\ndestruct (total_ordre a0 y0).\napply cas_cons_tri.\napply cas_cons_tri.\ninversion H0.\nauto.\nauto.\nauto.\napply cas_cons_tri.\nauto.\nauto.\ninversion H0.\nauto.\nQed.\n\nLemma sans_doublon_union : forall (l l' : list Y), \nsans_doublon l -> triee l -> sans_doublon l' -> triee l' -> sans_doublon (union l l').\nProof.\nintros.\ngeneralize dependent l'.\ninduction l.\nsimpl.\nintros.\nauto.\nintros.\nsimpl.\napply IHl with (l' := inserer a l').\ninversion H.\nauto.\ninduction l'.\ninversion H0.\nauto.\nauto.\napply IHl'.\ninversion H1.\nauto.\ninversion H2.\napply cas_nil_tri.\nauto.\napply sans_doublon_inserer.\nauto.\nauto.\napply insertion_preserves_tri.\nauto.\nauto.\nQed.\n\nLemma sorted_union : forall (l l' : list Y), \nsans_doublon l -> triee l -> sans_doublon l' -> triee l' -> triee (union l l').\nProof.\nintros.\ngeneralize dependent l'.\ninduction l.\nintros.\nsimpl.\nauto.\nintros.\nsimpl.\napply IHl with (l' := inserer a l').\ninversion H.\nauto.\ninversion H0.\nauto.\napply cas_nil_tri.\nauto.\napply sans_doublon_inserer.\nauto.\nauto.\napply insertion_preserves_tri.\nauto.\nauto.\nQed.\n\nLemma union_not_null : forall (l l' :list Y), \nl <> nil -> l' <> nil -> union l l' <> nil.\nProof.\nintros.\ngeneralize dependent l'.\ninduction l.\nintros.\nintro.\nsimpl in H1.\napply H0.\nauto.\nintros.\nsimpl.\ndestruct l.\nsimpl.\nintro.\ndestruct l'.\nsimpl in H1.\ninversion H1.\nsimpl in H1.\ndestruct(Y_eq_dec a y0).\ninversion H1.\ndestruct (total_ordre a y0).\ninversion H1.\ninversion H1.\nsimpl.\napply IHl with (l' := inserer a l').\nintro.\ninversion H1.\nintro.\ndestruct l'.\nsimpl in H1.\ninversion H1.\nsimpl in H1.\ndestruct(Y_eq_dec a y1).\ninversion H1.\ndestruct (total_ordre a y1).\ninversion H1.\ninversion H1.\nQed.\n\nLemma est_dedans_bien : forall (l : list Y) (a : Y), \nest_dans a (inserer a l).\nProof.\nintros.\ninduction l.\nsimpl.\napply construct.\nsimpl.\ndestruct (Y_eq_dec a a0).\nrewrite e.\napply construct.\ndestruct (total_ordre a a0).\napply construct.\napply propag.\nauto.\nQed.\n\n\n\nLemma transmission_gauche : forall (l l' : list Y) (a : Y), \nest_dans a l -> est_dans a (union l l').\nProof.\nintros.\ngeneralize dependent l'.\ninduction l.\nintro.\ninduction l'.\nintros.\ninversion H.\nsimpl in IHl'.\nsimpl.\napply propag.\nauto.\nintro.\ninversion H.\nsimpl.\nAdmitted.\n\n\nLemma transmission_droite : forall (l l' : list Y) (a : Y), \nest_dans a l -> est_dans a (union l' l).\nProof.\nAdmitted.\n\nLemma est_dans_already : forall (l : list Y) (a a0 : Y), \na <> a0 -> est_dans a (inserer a0 l) -> est_dans a l.\nProof.\nintros.\ninduction l.\nsimpl in H0.\ninversion H0.\nassert (False).\napply H.\nauto.\ninversion H2.\ninversion H3.\nsimpl in H0.\ndestruct (Y_eq_dec a0 a1).\napply propag.\napply IHl.\ninversion H0.\nassert (False).\napply H.\nrewrite H3.\napply symmetry.\nauto.\ninversion H2.\napply insertion_preserves_inside.\nauto.\ndestruct (Y_eq_dec a a1).\nrewrite e.\napply construct.\napply propag.\ndestruct (total_ordre a0 a1).\ninversion H0.\nassert (False).\napply H.\nauto.\ninversion H2.\ninversion H3.\nassert (False).\napply n0.\nauto.\ninversion H6.\nauto.\ninversion H0.\nassert (False).\napply n0.\nauto.\ninversion H2.\napply IHl.\nauto.\nQed.\n\nLemma transmission_inverse : forall (l l' : list Y) (a :Y), \nest_dans a (union l l') -> est_dans a l \\/ est_dans a l'.\nProof.\nintros.\ngeneralize dependent l'.\ninduction l.\nintros.\nsimpl in H.\nright.\nauto.\nintros.\nsimpl in H.\nassert (est_dans a l \\/ est_dans a (inserer a0 l')).\napply IHl.\nauto.\ndestruct H0.\nleft.\napply propag.\nauto.\ndestruct (Y_eq_dec a a0).\nrewrite e.\nleft.\napply construct.\nright.\napply est_dans_already with (a := a) (a0 := a0).\nauto.\nauto.\nQed.\n\nLemma transmission_not : forall (l l' : list Y) (a : Y), \n~est_dans a (union l l') -> ~est_dans a l /\\ ~est_dans a l'.\nProof.\nintros.\ninduction l.\nsplit.\nintro.\ninversion H0.\nsimpl in H.\nauto.\nsplit.\nintro.\napply H.\napply transmission_gauche.\nauto.\nintro.\napply H.\nsimpl.\nassert (est_dans a l' -> est_dans a (inserer a0 l')).\napply (insertion_preserves_inside).\napply H1 in H0.\napply transmission_droite.\nauto.\nQed.\n\nDefinition union_finite (A B : ensemble_fini) : ensemble_fini.\nProof.\nsplit with (union A B).\napply sans_doublon_union.\napply is_a_set.\napply is_sorted.\napply is_a_set.\napply is_sorted.\napply sorted_union.\napply is_a_set.\napply is_sorted.\napply is_a_set.\napply is_sorted.\nDefined.\n\nLemma union_preserves_both : forall (x : Y) (l l' : list Y), \nest_dans x (union l l') -> est_dans x l \\/ est_dans x l'.\nProof.\nintros. \ngeneralize dependent l'.\ninduction l.\nintros.\ninduction l'.\nsimpl in H.\ninversion H.\nsimpl in H.\nsimpl in IHl'.\nright.\nauto.\nintros.\nsimpl in H.\ndestruct (Y_eq_dec x0 a).\nleft.\nrewrite e.\napply construct.\nassert (est_dans x0 l \\/ est_dans x0 (inserer a l')).\napply IHl.\nauto.\ndestruct H0.\nleft.\napply propag.\nauto.\nright.\napply insertion_conserves_inside with (x0 := a) (a := x0).\nsplit.\nauto.\nintro.\napply n. \nsymmetry.\nauto.\nQed.\n\nLemma est_dans_dec : forall (x: Y) (l : list Y), {est_dans x l} + {~est_dans x l}.\nProof.\nintros.\ninduction l.\nright.\nintro.\ninversion H.\ndestruct IHl.\nleft.\napply propag.\nauto.\ndestruct (Y_eq_dec x0 a).\nleft.\nrewrite e.\napply construct.\nright.\nintro.\ninversion H.\napply n0.\nauto.\napply n.\nauto.\nQed.\n\nLemma equiv_tri : forall (l : list Y) (x : Y), \n(forall (z : Y), est_dans z l -> ordre x z) -> triee l -> triee (cons x l).\nProof.\nintros.\ninduction l.\napply cas_x_tri.\napply cas_cons_tri.\nauto.\napply H.\napply construct.\nQed.\n\n\nDefinition singleton (x : Y) : ensemble_fini.\nProof.\nsplit with (cons x nil).\napply cas_cons_sd.\napply cas_base_sd.\nintro.\ninversion H.\napply cas_x_tri.\nDefined.\n\n\n", "meta": {"author": "slechenne-dev", "repo": "Stage-CoQ", "sha": "1ee91236a452ceb07f7693adf40b16e8bad2e61c", "save_path": "github-repos/coq/slechenne-dev-Stage-CoQ", "path": "github-repos/coq/slechenne-dev-Stage-CoQ/Stage-CoQ-1ee91236a452ceb07f7693adf40b16e8bad2e61c/LS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6778631599313955}}
{"text": "Require Import XR_Rmin.\nRequire Import XR_Rle_dec.\n\nLocal Open Scope R_scope.\n\nLemma Rmin_r : forall x y:R, Rmin x y <= y.\nProof.\n  intros x y.\n  unfold Rmin.\n  destruct (Rle_dec x y) as [ hminl | hminr ].\n  { exact hminl. }\n  {\n    right.\n    reflexivity.\n  }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rmin_r.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527944504228, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.6778631500321057}}
{"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.\nRequire Import Coq.omega.Omega.\nImport ListNotations.\nRequire Import maps.\n\n(**Module AExp.\nInductive aexp : Type :=\n  | ANum : nat -> aexp\n  | APlus : aexp -> aexp -> aexp\n  | AMinus : aexp -> aexp -> aexp\n  | AMult : aexp -> aexp -> aexp.\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. simpl.\nreflexivity. 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 => leb (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 =>\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,\n  aeval (optimize_0plus a) = aeval a.\nProof.\nintros. induction a.\n- simpl. reflexivity.\n- destruct a1.\n + destruct n.\n   * simpl. apply IHa2.\n   * simpl. rewrite IHa2. trivial.\n + simpl. simpl in IHa1. rewrite IHa1. rewrite IHa2. trivial.\n + simpl. simpl in IHa1. rewrite IHa1. rewrite IHa2. trivial.\n + simpl. simpl in IHa1. rewrite IHa1. rewrite IHa2. trivial.\n- simpl. rewrite IHa1. rewrite IHa2. trivial.\n- simpl. rewrite IHa1. rewrite IHa2. trivial.\nQed.\n\nTheorem silly1 : forall ae, aeval ae = aeval ae.\nProof. try reflexivity. (* this just does reflexivity *) Qed.\nTheorem silly2 : forall (P : Prop), P -> P.\nProof.\n  intros P HP.\n  try reflexivity. (* just reflexivity would have failed *)\n  apply HP. (* we can still finish the proof in some other way *)\nQed.\n\nLemma foo : forall n, leb 0 n = true.\nProof.\n  intros.\n  destruct n.\n    (* Leaves two subgoals, which are discharged identically...  *)\n    - (* n=0 *) simpl. reflexivity.\n    - (* n=Sn' *) simpl. reflexivity.\nQed.\n\nLemma foo' : forall n, leb 0 n = true.\nProof.\n  intros.\n  (* destruct the current goal *)\n  destruct n;\n  (* then simpl each resulting subgoal *)\n  simpl;\n  (* and do reflexivity on each resulting subgoal *)\n  reflexivity.\nQed.\n\nTheorem optimize_0plus_sound': forall a,\n  aeval (optimize_0plus a) = aeval a.\nProof.\n  intros a.\n  induction a;\n    try (simpl; rewrite IHa1; rewrite IHa2; reflexivity).\n  - (* ANum *) reflexivity.\n  - (* APlus *)\n    destruct a1;try (simpl; simpl in IHa1; rewrite IHa1;\n           rewrite IHa2; reflexivity).\n    + (* a1 = ANum n *) destruct n;\n      simpl; rewrite IHa2; reflexivity. Qed.\n\nTheorem In10 : In 10 [1;2;3;4;5;6;7;8;9;10].\nProof.\nrepeat simpl.\nrepeat (try (left; reflexivity); right).\nQed.\n\nFixpoint optimize_0plus_b (b : bexp) : bexp :=\nmatch 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.\n  intro 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\nTheorem optimize_0plus_b_sound' : forall b,\n  beval (optimize_0plus_b b) = beval b.\nProof.\nAdmitted.\n\nTactic Notation \"simpl_and_try\" tactic(c) :=\n  simpl;\n  try c.\n\nExample silly_presburger_example : forall m n o p,\n  m + n <= n + o /\\ o + 3 = p + 3 ->\n  m <= p.\nProof.\n  intros. omega.\nQed.\n\nModule aevalR_first_try.\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).\nNotation \"e '\\\\' n\"\n         := (aevalR e n)\n            (at level 50, left associativity)\n         : type_scope.\nEnd aevalR_first_try.\n\nReserved Notation \"e '\\\\' n\" (at level 50, left associativity).\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)\n\n  where \"e '\\\\' n\" := (aevalR e n) : type_scope.\n\n\n\nFixpoint ble_nat ( n1 n2 : nat) : bool :=\nmatch n1 with\n| O => match n2 with \n     | O => true \n     | S n2' => true\n     end\n| S n1' => match n2 with\n    | O => false \n    | S n2' => ble_nat n1' n2'\n    end\nend.\n\nReserved Notation \"e '||' n\" (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 n1 n2, \naevalR a1 n1 -> aevalR a2 n2 -> BEq a1 a2 || beq_nat n1 n2\n| E_BLe : forall a1 a2 n1 n2, \naevalR a1 n1 -> aevalR a2 n2 -> BLe a1 a2 || ble_nat n1 n2\n| E_BNot : forall b p, b || p -> BNot b || negb p\n| E_BAnd : forall b1 b2 p1 p2,\nb1 || p1 -> b2 || p2 -> BAnd b1 b2 || andb p1 p2\n\nwhere \"e '||' n\" := (bevalR e n) : type_scope.\n\nTheorem aeval_iff_aevalR : forall a n,\n  (a \\\\ n) <-> aeval a = n.\nProof.\nsplit.\n- intros. induction H;simpl.\n  +  trivial.\n  + rewrite IHaevalR1. rewrite IHaevalR2. trivial. \n  + rewrite IHaevalR1. rewrite IHaevalR2. trivial.\n  + rewrite IHaevalR1. rewrite IHaevalR2. trivial. \n- intros. generalize dependent n. induction a;\n  simpl; intros; subst.\n  + apply E_ANum.\n  + apply E_APlus. apply IHa1. reflexivity. apply IHa2. reflexivity.\n  + apply E_AMinus. apply IHa1. reflexivity. \n    apply IHa2. reflexivity. \n  + apply E_AMult. apply IHa1. reflexivity. apply IHa2. reflexivity.\nQed.\n\nLemma beval_iff_bevalR : forall b bv,\n  bevalR b bv <-> beval b = bv.\nProof.\nintros.\nsplit.\n- intros. induction H;simpl.\n  + reflexivity.\n  + reflexivity.\n  + induction H; simpl; induction H0; simpl;\ntry (reflexivity). generalize dependent n.\nAdmitted.\n**)\nDefinition state := total_map nat.\n\nInductive aexp : Type :=\n  | ANum : nat -> aexp\n  | AId : string -> aexp (* <----- NEW *)\n  | APlus : aexp -> aexp -> aexp\n  | AMinus : aexp -> aexp -> aexp\n  | AMult : aexp -> aexp -> aexp.\n\nDefinition W : string := \"W\".\nDefinition X : string := \"X\".\nDefinition Y : string := \"Y\".\nDefinition Z : string := \"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\nCoercion AId : string >-> aexp.\nCoercion ANum : nat >-> aexp.\nDefinition bool_to_bexp (b: bool) : bexp :=\n  if b then BTrue else BFalse.\nCoercion bool_to_bexp : bool >-> bexp.\n\nBind Scope aexp_scope with aexp.\nInfix \"+\" := APlus : aexp_scope.\nInfix \"-\" := AMinus : aexp_scope.\nInfix \"*\" := AMult : aexp_scope.\nBind Scope bexp_scope with bexp.\nInfix \"<=\" := BLe : bexp_scope.\nInfix \"=\" := BEq : bexp_scope.\nInfix \"&&\" := BAnd : bexp_scope.\nNotation \"'!' b\" := (BNot b) (at level 60) : bexp_scope.\n\nFixpoint aeval (st : state) (a : aexp) : nat :=\n  match a with\n  | ANum n => n\n  | AId x => st x (* <----- NEW *)\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 => 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\nNotation \"{ a !-> x }\" := \n  (t_update { !-> 0 } a x) (at level 0).\nNotation \"{ a !-> x ; b !-> y }\" := \n  (t_update ({ a !-> x }) b y) (at level 0).\nNotation \"{ a !-> x ; b !-> y ; c !-> z }\" := \n  (t_update ({ a !-> x ; b !-> y }) c z) (at level 0).\nNotation \"{ a !-> x ; b !-> y ; c !-> z ; d !-> t }\" := \n    (t_update ({ a !-> x ; b !-> y ; c !-> z }) d t) (at level 0).\nNotation \"{ 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).\nNotation \"{ 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\nInductive com : Type :=\n  | CSkip : com\n  | CAss : string -> aexp -> com\n  | CSeq : com -> com -> com\n  | CIf : bexp -> com -> com -> com\n  | CWhile : bexp -> com -> com.\n\nBind Scope com_scope with com.\nNotation \"'SKIP'\" :=\n   CSkip : com_scope.\nNotation \"x '::=' a\" :=\n  (CAss x a) (at level 60) : com_scope.\nNotation \"c1 ;; c2\" :=\n  (CSeq c1 c2) (at level 80, right associativity) : com_scope.\nNotation \"'WHILE' b 'DO' c 'END'\" :=\n  (CWhile b c) (at level 80, right associativity) : com_scope.\nNotation \"'IFB' c1 'THEN' c2 'ELSE' c3 'FI'\" :=\n  (CIf c1 c2 c3) (at level 80, right associativity) : com_scope.\n\nOpen Scope com_scope.\n\nDefinition 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\nDefinition plus2 : com :=\n  X ::= X + 2.\nDefinition XtimesYinZ : com :=\n  Z ::= X * Y.\nDefinition subtract_slowly_body : com :=\n  Z ::= Z - 1 ;;\n  X ::= X - 1.\n\nDefinition subtract_slowly : com :=\n  WHILE ! (X = 0) DO\n    subtract_slowly_body\n  END.\nDefinition subtract_3_from_5_slowly : com :=\n  X ::= 3 ;;\n  Z ::= 5 ;;\n  subtract_slowly.\n\nDefinition loop : com :=\n  WHILE true DO\n    SKIP\n  END.\n\nFixpoint 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\nReserved Notation \"c1 '/' st '\\\\' st'\"\n                  (at level 40, st at level 39).\nInductive ceval : com -> state -> state -> Prop :=\n  | E_Skip : forall st,\n      SKIP / st \\\\ st\n  | E_Ass : forall st a1 n x,\n      aeval st a1 = n ->\n      (x ::= a1) / st \\\\ 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\n  where \"c1 '/' st '\\\\' st'\" := (ceval c1 st st').\n\nExample 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 }.\nProof.\napply E_Seq with { X !-> 2 }.\n  -\n    apply E_Ass. reflexivity.\n  -\n    apply E_IfFalse. simpl.\n      reflexivity.\n      apply E_Ass. simpl. reflexivity. Qed.\n\nExample ceval_example2:\n  (X ::= 0;; Y ::= 1;; Z ::= 2) / { !-> 0 } \\\\\n  { X !-> 0 ; Y !-> 1 ; Z !-> 2 }.\nProof.\napply E_Seq with { X !-> 0}.\napply E_Ass. reflexivity.\napply E_Seq with { X !-> 0;Y !-> 1}.\napply E_Ass. reflexivity.\napply E_Ass. reflexivity.\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.\ninversion Heval. subst. clear Heval. simpl.\n  apply t_update_eq. Qed.\n\nDefinition empty_st := fun (_ : string) => 0.\n(** do the advanced exercise **)\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/imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.8198933447152498, "lm_q1q2_score": 0.6778155049571576}}
{"text": "Module NatList.\n  Inductive natprod : Type :=\n    pair : nat -> nat -> natprod.\n\n  Definition fst (p : natprod) : nat :=\n    match p with\n      | pair x y => x\n    end.\n\n  Definition snd (p : natprod) : nat :=\n    match p with\n      | pair x y => y\n    end.\n\n  Notation \"( x , y )\" := (pair x y).\n\n  Definition swap_pair (p : natprod) : natprod :=\n    match p with\n      | (x,y) => (y,x)\n    end.\n\n  Theorem surjective_paring' : forall (n m : nat),\n                                 (n, m) = (fst (n,m), snd(n,m)).\n  Proof.\n    reflexivity.\n  Qed.\n\n  Theorem surjective_pairing_stuck : forall (p : natprod),\n                                       p = (fst p, snd p).\n  Proof.\n    intros p.\n    destruct p.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Theorem snd_fst_is_swap : forall (p :natprod),\n                              (snd p, fst p) = swap_pair p.\n  Proof.\n    intros p.\n    destruct p. simpl.\n    reflexivity.\n  Qed.\n\n  Inductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\n  Definition l_123 := cons 1 (cons 2 (cons 3 nil)).\n\n  Notation \"x :: l\" := (cons x l) (at level 60, right associativity).\n  Notation \"[ ]\" := nil.\n  Notation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n\n  Fixpoint repeat (n count : nat) : natlist :=\n    match count with\n      | O => nil\n      | S count' => n :: (repeat n count')\n    end.\n\n  Fixpoint length (l: natlist) : nat :=\n    match l with\n      | nil => 0\n      | l :: t => S (length t)\n    end.\n\n  Fixpoint app (l1 l2: natlist) : natlist :=\n    match l1 with\n      | nil => l2\n      | h :: t => h :: (app t l2)\n    end.\n\n  Notation \"x ++ y\" := (app x y) (right associativity, at level 60).\n\n  Example test_app1: [1,2,3] ++ [4,5] = [1,2,3,4,5].\n  Proof. reflexivity. Qed.\n  Example test_app2: nil ++ [4,5] =[4,5].\n  Proof. reflexivity. Qed.\n  Example test_app3: [1,2,3] ++ nil = [1,2,3].\n  Proof. reflexivity. Qed.\n\n  Definition hd (default:nat) (l:natlist) : nat :=\n    match l with\n      | nil => default\n      | h :: t => h\n    end.\n\n  Definition tail (l: natlist) : natlist :=\n    match l with\n      | nil => nil\n      | h :: t => t\n    end.\n\n  Fixpoint nonzeros (l: natlist) : natlist :=\n    match l with\n      | nil => nil\n      | 0 :: tl => nonzeros tl\n      | hd :: tl => hd :: nonzeros tl\n    end.\n  Example test_nonzeros: nonzeros [0,1,0,2,3,0,0] = [1,2,3].\n  Proof. reflexivity. Qed.\n\n  Fixpoint even (n : nat) : bool :=\n    match n with\n      | O => true\n      | S n' => negb (even n')\n    end.\n\n  Fixpoint odd (n : nat) : bool :=\n    negb (even n).\n\n  Fixpoint oddmembers (l: natlist) : natlist :=\n    match l with\n      | nil => nil\n      | hd :: tl => match odd hd with\n                      | false => oddmembers tl\n                      | true => hd :: oddmembers tl\n                    end\n    end.\n\n  Example test_oddmembers: oddmembers [0,1,0,2,3,0,0] = [1,3].\n  Proof. reflexivity. Qed.\n\n  Fixpoint countoddmembers (l:natlist) : nat :=\n    match l with\n      | nil => O\n      | hd :: tl => match odd hd with\n                      | false => countoddmembers tl\n                      | true  => 1 + (countoddmembers tl)\n                    end\n    end.\n\n  Example test_countoddmembers1: countoddmembers [1,0,3,1,4,5] = 4.\n  Proof. reflexivity. Qed.\n  Example test_countoddmembers2: countoddmembers [0,2,4] = 0.\n  Proof. reflexivity. Qed.\n  Example test_countoddmembers3: countoddmembers nil = 0.\n  Proof. reflexivity. Qed.\n\n  Fixpoint alternate (l1 l2: natlist) :natlist :=\n    match l1, l2 with\n      | nil, l2' => l2'\n      | l1', nil => l1'\n      | hd1 :: tl1, hd2 :: tl2  => hd1 :: hd2 :: (alternate tl1 tl2)\n    end.\n\n  Example test_alternate1: alternate [1,2,3] [4,5,6] = [1,4,2,5,3,6].\n  Proof. reflexivity. Qed.\n  Example test_alternate2: alternate [1] [4,5,6] = [1,4,5,6].\n  Proof. reflexivity. Qed.\n  Example test_alternate3: alternate [1,2,3] [4] = [1,4,2,3].\n  Proof. reflexivity. Qed.\n  Example test_alternate4: alternate [] [20,30] = [20,30].\n  Proof. reflexivity. Qed.\n\n  Definition bag := natlist.\n\n  Fixpoint neq (n m: nat): bool :=\n    match n, m with\n      | O, O      => true\n      | O, _      => false\n      | _, O      => false\n      | S n', S m' => neq n' m'\n    end.\n\n  Fixpoint count (v: nat) (s: bag) : nat :=\n    match s with\n      | nil => 0\n      | hd :: tl => match neq hd v with\n                      | true  => 1 + (count v tl)\n                      | false => (count v tl)\n                    end\n    end.\n\n  Example test_count1: count 1 [1,2,3,1,4,1] = 3.\n  Proof. reflexivity. Qed.\n  Example test_count2: count 6 [1,2,3,1,4,1] = 0.\n  Proof. reflexivity. Qed.\n\n  Definition sum : bag -> bag -> bag := app.\n\n  Example test_sum1: count 1 (sum [1,2,3] [1,4,1]) = 3.\n  Proof. reflexivity. Qed.\n\n  Definition add (v: nat) (s: bag): bag := v :: s.\n\n  Example test_add1: count 1 (add 1 [1,4,1]) = 3.\n  Proof. reflexivity. Qed.\n  Example test_add2: count 5 (add 1 [1,4,1]) = 0.\n  Proof. reflexivity. Qed.\n\n  Fixpoint nge (n m: nat) :=\n    match n, m with\n      | O, O => true\n      | S _, O => true\n      | O, S _ => false\n      | S n', S m' => nge n' m'\n    end.\n  \n\n  Definition member (v: nat) (s: bag) : bool := nge (count v s) 1.\n\n  Example test_member1: member 1 [1,4,1] = true.\n  Proof. reflexivity. Qed.\n  Example test_member2: member 2 [1,4,1] = false.\n  Proof. reflexivity. Qed.\n\n  Fixpoint remove_one (v: nat) (s: bag) : bag :=\n    match s with\n      | nil => nil\n      | hd :: tl => match neq v hd with\n                      | true  => tl\n                      | false => hd :: remove_one v tl\n                    end\n    end.\n\n  Example test_remove_one1: count 5 (remove_one 5 [2,1,5,4,1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_one2: count 5 (remove_one 5 [2,1,4,1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_one3: count 4 (remove_one 5 [2,1,4,5,1,4]) = 2.\n  Proof. reflexivity. Qed.\n  Example test_remove_one4:\n    count 5 (remove_one 5 [2,1,5,4,5,1,4]) = 1.\n  Proof. reflexivity. Qed.\n\n  Fixpoint remove_all (v: nat) (s: bag) :bag :=\n    match s with\n      | nil => nil\n      | hd :: tl => match neq v hd with\n                      | true  => remove_all v tl\n                      | false => hd :: remove_all v tl\n                    end\n    end.\n\n  Example test_remove_all1: count 5 (remove_all 5 [2,1,5,4,1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_all2: count 5 (remove_all 5 [2,1,4,1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_all3: count 4 (remove_all 5 [2,1,4,5,1,4]) = 2.\n  Proof. reflexivity. Qed.\n  Example test_remove_all4: count 5 (remove_all 5 [2,1,5,4,5,1,4,5,1,4]) = 0.\n  Proof. reflexivity. Qed.\n\n  Fixpoint subset (s1: bag) (s2: bag) :bool :=\n    match  s1, s2 with\n      | nil, _  => true\n      | _ , nil => false\n      | s1', hd :: tl => subset (remove_one hd s1') tl\n    end.\n\n  Example test_subset1: subset [1,2] [2,1,4,1] = true.\n  Proof. reflexivity. Qed.\n  Example test_subset2: subset [1,2,2] [2,1,4,1] = false.\n  Proof. reflexivity. Qed.\n\n  Theorem nil_app : forall l:natlist,\n                      [] ++ l = l.\n  Proof. reflexivity. Qed.\n\n  Theorem tl_length_pred : forall l: natlist,\n                             pred (length l) = length (tail l).\n  Proof.\n    intros l. destruct l as [| n l'].\n    reflexivity.\n    reflexivity.\n  Qed.\n\n  Theorem app_ass: forall l1 l2 l3 : natlist,\n                     (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\n  Proof.\n    intros l1 l2 l3. induction l1 as [| n l1'].\n    + reflexivity.\n    + simpl. rewrite IHl1'. reflexivity.\n  Qed.\n\n  Theorem app_length : forall l1 l2: natlist,\n                         length (l1 ++ l2) = (length l1) + (length l2).\n  Proof.\n    intros l1 l2.\n    induction l1 as [| n l1'].\n    + reflexivity.\n    + simpl. rewrite IHl1'. reflexivity.\n  Qed.\n\n  Fixpoint snoc (l: natlist) (v: nat) :natlist :=\n    match l with\n      | nil => [v]\n      | h :: t => h :: (snoc t v)\n    end.\n\n  Fixpoint rev (l: natlist) : natlist :=\n    match l with\n      | nil => nil\n      | h :: t => snoc (rev t) h\n    end.\n\n  Example test_rev1: rev [1,2,3] = [3,2,1].\n  Proof. reflexivity. Qed.\n  Example test_rev2: rev nil = nil.\n  Proof. reflexivity. Qed.\n\n  Theorem length_snoc: forall n : nat, forall l: natlist,\n                         length (snoc l n) = S (length l).\n  Proof.\n    intros n l.\n    induction l as [| m l'].\n    + reflexivity.\n    + simpl. rewrite IHl'. reflexivity.\n  Qed.      \n\n  Theorem rev_length_first: forall l :natlist,\n                              length (rev l) = length l.\n  Proof.\n    intros l. induction l as [| n l'].\n    + simpl. reflexivity.\n    + simpl. rewrite length_snoc. rewrite IHl'. reflexivity.\n  Qed.\n\n  Theorem app_nil_end: forall l : natlist,\n                         l ++ [] = l.\n  Proof.\n    intros l.\n    induction l.\n    + reflexivity.\n    + simpl. rewrite IHl. reflexivity.\n  Qed.\n\n  Lemma snoc_rev: forall l: natlist, forall n: nat, rev (snoc l n) = n :: (rev l).\n  Proof.\n    intros l n.\n    induction l.\n    + reflexivity.\n    + simpl.\n      rewrite IHl.\n      reflexivity.\n  Qed.\n\n  Theorem rev_involutive : forall l : natlist,\n                             rev (rev l) = l.\n  Proof.\n    intros l.\n    induction l.\n    + reflexivity.\n    + simpl.\n      rewrite snoc_rev.\n      rewrite IHl.\n      reflexivity.\n  Qed.\n\n  Theorem rev_snoc: forall l: natlist, forall n: nat,\n                      snoc (rev l) n = rev (n :: l).\n  Proof.\n    intros l n.\n    induction l.\n    + reflexivity.\n    + reflexivity.\n  Qed.\n\n  Lemma snoc_app: forall n: nat, forall l1 l2: natlist,\n                    l1 ++ snoc l2 n = snoc (l1 ++ l2) n.\n  Proof.\n    intros n l1 l2.\n    induction l1.\n    + reflexivity.\n    + simpl. rewrite IHl1. reflexivity.\n  Qed.\n\n  Theorem distr_rev: forall l1 l2: natlist,\n                       rev (l1 ++ l2) = (rev l2) ++ (rev l1).\n  Proof.\n    intros l1 l2.\n    induction l1.\n    + induction l2.\n    - reflexivity.\n    - simpl. rewrite app_nil_end. reflexivity.\n      + simpl.\n        rewrite IHl1.\n        rewrite snoc_app.\n        reflexivity.\n  Qed.\n\n  Theorem app_ass4: forall l1 l2 l3 l4: natlist,\n                      l1 ++ (l2 ++ l3 ++ l4) = ((l1 ++ l2) ++ l3) ++ l4.\n  Proof.\n    intros l1 l2 l3 l4.\n    rewrite app_ass.\n    rewrite app_ass.\n    reflexivity.\n\n    Theorem snoc_append: forall (l: natlist) (n: nat),\n                           snoc l n = l ++ [n].\n    Proof.\n      intros l n.\n      induction l.\n      + reflexivity.\n      + simpl. rewrite IHl. reflexivity.\n    Qed.\n\n    Lemma nonzeros_length: forall l1 l2: natlist,\n                             nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\n    Proof.\n      intros l1 l2.\n      induction l1.\n      + reflexivity.\n      + simpl. rewrite IHl1.\n        induction l2.\n      - simpl. rewrite app_nil_end.\n        destruct n.\n        * rewrite app_nil_end. reflexivity.\n        * rewrite app_nil_end. reflexivity.\n      - simpl. destruct n.\n        *  reflexivity.\n        * simpl. reflexivity.\n    Qed.\n\n    Theorem nil_rev: rev [] = [].\n    Proof.\n      reflexivity.\n    Qed.\n\n    Inductive natoption: Type :=\n    | Some : nat -> natoption\n    | None : natoption.\n\n    Fixpoint index (n: nat) (l:natlist): natoption :=\n      match l with\n        | nil => None\n        | a :: l' => match neq n 0 with\n                       | true => Some a\n                       | false => index (pred n) l'\n                     end\n      end.\n\n    Example test_index1 : index 0 [4,5,6,7] = Some 4.\n    Proof. reflexivity. Qed.\n    Example test_index2 : index 3 [4,5,6,7] = Some 7.\n    Proof. reflexivity. Qed.\n    Example test_index3 : index 10 [4,5,6,7] = None.\n    Proof. reflexivity. Qed.\n\n    Definition option_elim (o : natoption) (d: nat): nat :=\n      match o with\n        | Some n' => n'\n        | None => d\n      end.\n\n    Definition hd_opt (l: natlist): natoption :=\n      match l with\n        | nil => None\n        | a :: _ => Some a\n      end.\n\n    Example test_hd_opt1 : hd_opt [] = None.\n    Proof. reflexivity. Qed.\n    Example test_hd_opt2 : hd_opt [1] = Some 1.\n    Proof. reflexivity. Qed.\n    Example test_hd_opt3 : hd_opt [5,6] = Some 5.\n    Proof. reflexivity. Qed.\n\n    Theorem option_elim_hd: forall (l: natlist) (default: nat),\n                              hd default l = option_elim (hd_opt l) default.\n    Proof.\n      intros l default.\n      destruct l.\n      + simpl. reflexivity.\n      + simpl. reflexivity.\n    Qed.\n\n    Fixpoint beq (n m: nat): bool:=\n      match n, m with\n        | O, O => true\n        | S n', S m' => beq n' m'\n        | _ ,_ => false\n      end.\n\n    Fixpoint beq_natlist (l1 l2: natlist): bool :=\n      match l1, l2 with\n        | nil, nil => true\n        | a::l1', b::l2' => match beq a b with\n                              | true => beq_natlist l1' l2'\n                              | false => false\n                            end\n        |  _, _ => false\n      end.\n\n    Example test_beq_natlist1 : (beq_natlist nil nil = true).\n    Proof. reflexivity. Qed.\n    Example test_beq_natlist2 : beq_natlist [1,2,3] [1,2,3] = true.\n    Proof. reflexivity. Qed.\n    Example test_beq_natlist3 : beq_natlist [1,2,3] [1,2,4] = false.\n    Proof. reflexivity. Qed.\n\n    Theorem beq_natlist_refl: forall l: natlist,\n                                true = beq_natlist l l.\n    Proof.\n      intros l.\n      induction l.\n      + reflexivity.\n      + simpl. rewrite IHl.\n        induction n.\n      - simpl. reflexivity.\n      - simpl. rewrite <- IHn. reflexivity.\n    Qed.\n\n    Theorem silly1: forall (n m o p: nat),\n                      n = m ->\n                      [n, o] = [n, p] ->\n                      [n, o] = [m, p].\n    Proof.\n      intros n m o p eq1 eq2.\n      rewrite <- eq1.\n      apply eq2.\n    Qed.\n\n    Theorem 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].\n    Proof.\n      intros n m o p eq1 eq2.\n      apply eq2. apply eq1.\n    Qed.\n\n    Theorem silly_ex:\n      (forall n, even n = true -> odd (S n) = true) ->\n      even 3 = true ->\n      odd 4 = true.\n    Proof.\n      intros.\n      apply H.\n      apply H0.\n    Qed.\n\n    Theorem silly3: forall (n: nat),\n                      true = neq n 5 ->\n                      neq (S (S n)) 7 = true.\n    Proof.\n      intros n H.\n      symmetry.\n      apply H.\n    Qed.\n\n    Theorem rev_exercise1: forall (l l': natlist),\n                             l = rev l' ->\n                             l' = rev l.\n    Proof.\n      intros l l' H.\n      symmetry.\n      rewrite H.\n      apply rev_involutive.\n    Qed.\n\n    Theorem rev_ass': forall l1 l2 l3: natlist,\n                        (l1 ++ l2) ++ l3 = l1 ++ l2 ++ l3.\n      intros l1.\n      induction l1.\n      + reflexivity.\n      + intros l2 l3.\n        simpl.\n        assert(H: (l1++l2)++l3 = l1++l2++l3).\n        apply IHl1.\n        rewrite H.\n        reflexivity.\n    Qed.\n\n    Definition beq_nat (n m: nat): bool := neq n m.\n\n    Theorem beq_nat_sym: forall (n m: nat),\n                           beq_nat n m = beq_nat m n.\n    Proof.\n      intros n. induction n as [| n'].\n      + destruct m. reflexivity.\n        simpl. reflexivity.\n      +  destruct m.\n      - simpl. reflexivity.\n      - simpl. apply IHn'.\n    Qed.\n  Qed.\nEnd NatList.", "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/list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.677815495999293}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL B FREE SOFTWARE LICENSE AGREEMENT           *)\n(**************************************************************)\n\nFrom Coq\n  Require Import Arith Lia List.\n\n(** For lists *)\n\nArguments In {_}.\nArguments app {_}.\n\n#[global] Infix \"∈\" := In (at level 70, no associativity).\n#[global] Notation \"⌊ l ⌋\" := (length l) (at level 0, l at level 200, format \"⌊ l ⌋\").\n\n#[global] Notation \"P '⊆₁' Q\" := (forall x, P x -> Q x) (at level 70, no associativity, format \"P  ⊆₁  Q\").\n#[global] Notation \"P '⊆₂' Q\" := (forall x y, P x y -> Q x y) (at level 70, no associativity, format \"P  ⊆₂  Q\").\n\n#[global] Notation \"P '∪₁' Q\" := (fun x => P x \\/ Q x) (at level 1, no associativity, format \"P ∪₁ Q\").\n#[global] Notation \"P '∪₂' Q\" := (fun x y => P x y \\/ Q x y) (at level 1, no associativity, format \"P ∪₂ Q\").\n#[global] Notation \"P '∩₁' Q\" := (fun x => P x /\\ Q x) (at level 1, no associativity, format \"P ∩₁ Q\").\n#[global] Notation \"P '∩₂' Q\" := (fun x y => P x y /\\ Q x y) (at level 1, no associativity, format \"P ∩₂ Q\").\n\n#[global] Notation \"Q '∘' P\" := (fun x z => exists y, P x y /\\ Q y z) (at level 1, left associativity, format \"Q ∘ P\").\n\n(** We use lia to avoid incompatibilities between Coq <= 8.15.2 and Coq >= 8.16 \n    DLW: I know this is a like a tank to crush a fly but it is more compatible\n         than the other options *)\nDefinition plus_assoc n m p : n + (m + p) = n + m + p.      Proof. lia. Qed.\nDefinition le_plus_l n m : n <= n + m.                      Proof. lia. Qed.\nDefinition le_plus_r n m : m <= n + m.                      Proof. lia. Qed.\nDefinition le_trans n m p : n <= m -> m <= p -> n <= p.     Proof. lia. Qed.\nDefinition lt_le_trans n m p : n <= m -> m <= p -> n <= p.  Proof. lia. Qed.\nDefinition lt_0_Sn n : 0 < S n.                             Proof. lia. Qed.\nDefinition lt_n_S n m : n < m -> S n < S m.                 Proof. lia. Qed.\nDefinition lt_S_n n m : S n < S m -> n < m.                 Proof. lia. Qed.\n\n\n", "meta": {"author": "DmxLarchey", "repo": "Kruskal-Trees", "sha": "3118293d44b79655eea068a77ea5ea010211f8b4", "save_path": "github-repos/coq/DmxLarchey-Kruskal-Trees", "path": "github-repos/coq/DmxLarchey-Kruskal-Trees/Kruskal-Trees-3118293d44b79655eea068a77ea5ea010211f8b4/theories/notations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401362, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.6778154923610525}}
{"text": "Require Import String Omega Morph.\n\n(* Name indices are [nat]s *)\nDefinition index := nat.\n\n(* Shift up all indices greater than or equal to [i] *)\nFixpoint shift_idx (i : index) (j : index) : index :=\n  match i with\n  | 0 => S j\n  | S i =>\n    match j with\n    | 0 => 0\n    | S j => S (shift_idx i j)\n    end\n  end.\n\nLemma rw_shift_idx_ge i j :\n  i <= j ->\n  shift_idx i j = S j.\nProof.\n  generalize dependent j.\n  induction i; destruct j; intros; try easy.\n  cbn; auto with arith.\nQed.\n\nLemma rw_shift_idx_lt i j :\n  S j <= i ->\n  shift_idx i j = j.\nProof.\n  generalize dependent j.\n  induction i; destruct j; intros; try easy.\n  cbn; auto with arith.\nQed.\n\nLemma rw_shift_idx_same i :\n  shift_idx i i = S i.\nProof.\n  apply rw_shift_idx_ge; auto.\nQed.\n\n(* Partial inverse of [shift_idx]. Returns [None] iff [i = j]. *)\nFixpoint inverse_shift_idx i j :=\n  match i with\n  | 0 =>\n    match j with\n    | 0 => None\n    | S j => Some j\n    end\n  | S i =>\n    match j with\n    | 0 => Some 0\n    | S j =>\n      match inverse_shift_idx i j with\n      | None => None\n      | Some j' => Some (S j')\n      end\n    end\n  end.\n\nLemma rw_inverse_shift_idx_eq i j :\n  i = j ->\n  inverse_shift_idx i j = None.\nProof.\n  intros <-.\n  induction i; try easy; cbn.\n  rewrite IHi; easy.\nQed.\n\nLemma rw_inverse_shift_idx_lt i j :\n  S j <= i ->\n  inverse_shift_idx i j = Some j.\nProof.\n  generalize dependent j.\n  induction i; destruct j; intros Heq; try easy; cbn.\n  rewrite IHi; auto with arith.\nQed.\n\nLemma rw_inverse_shift_idx_gt i j :\n  S i <= j ->\n  inverse_shift_idx i j = Some (pred j).\nProof.\n  generalize dependent j.\n  induction i; destruct j; intros Heq; try easy; cbn.\n  rewrite IHi; f_equal; omega.\nQed.\n\nLemma rw_inverse_shift_idx_same i :\n  inverse_shift_idx i i = None.\nProof.\n  apply rw_inverse_shift_idx_eq; easy.\nQed.\n\n(* Tactics for handling the above operations *)\n\nArguments shift_idx !i !j.\nArguments inverse_shift_idx !i !j.\n\n(* Rewrite [shift_idx]s, [unshift_idx]s and [inverse_shift_idx]s where\n   the order of the parameters can be determined by the omega tactic *)\nLtac simpl_idxs :=\n  repeat progress\n    (match goal with\n     | |- context [shift_idx ?i ?j] =>\n       first\n         [ rewrite (rw_shift_idx_ge i j) by omega\n         | rewrite (rw_shift_idx_lt i j) by omega ]\n     | |- context [inverse_shift_idx ?i ?j] =>\n       first\n         [ rewrite (rw_inverse_shift_idx_eq i j) by omega\n         | rewrite (rw_inverse_shift_idx_lt i j) by omega\n         | rewrite (rw_inverse_shift_idx_gt i j) by omega ]\n     end; cbn).\n\n(* Case split on the order of the parameters, then simplify any\n   [shift_idx]s and [inverse_shift_idx]s affected by the\n   ordering. *)\nLtac case_order i j :=\n  destruct (Compare_dec.lt_eq_lt_dec i j) as [[|]|];\n  simpl_idxs.\n\n(* Inverses *)\n\nLemma rw_inverse_shift_idx_shift_idx i j :\n  inverse_shift_idx i (shift_idx i j) = Some j.\nProof.\n  case_order i j; easy.\nQed.\n\nLemma rw_shift_idx_inverse_shift_idx {i j} :\n  option_map (shift_idx i) (inverse_shift_idx i j)\n  = if Nat.eq_dec i j then None else Some j.\nProof.\n  case_order i j;\n    destruct (Nat.eq_dec i j); f_equal; try omega.\nQed.\n\n(* Comparison for free name indices *)\n\nInductive index_comparison (i : index) : index -> Set :=\n| same_idx : index_comparison i i\n| diff_idx j : index_comparison i (shift_idx i j).\n\nFixpoint compare_idx (i : index)\n  : forall j, index_comparison i j :=\n  match i with\n  | 0 => fun j =>\n    match j with\n    | 0 => same_idx _\n    | S j => diff_idx _ j\n    end\n  | S i => fun j =>\n    match j with\n    | 0 => diff_idx _ 0\n    | S j =>\n      match compare_idx i j with\n      | same_idx _ => same_idx _\n      | diff_idx _ j' => diff_idx _ (S j')\n      end\n    end\n  end.\n\nLemma rw_compare_idx_same :\n  forall i, compare_idx i i = same_idx i.\nProof. induction i; cbn; try rewrite IHi; easy. Qed.\n\nLemma rw_compare_idx_shift :\n  forall i j, compare_idx i (shift_idx i j) = diff_idx i j.\nProof. induction i; destruct j; cbn; try rewrite IHi; easy. Qed.\n\nHint Rewrite @rw_shift_idx_same @rw_inverse_shift_idx_same\n     @rw_inverse_shift_idx_shift_idx @rw_shift_idx_inverse_shift_idx\n     @rw_compare_idx_same @rw_compare_idx_shift\n  : rw_idxs.\n\nArguments shift_idx : simpl never.\nArguments inverse_shift_idx : simpl never.\n\n(* Free names are a pair of a string and an index *)\n\nSet Primitive Projections.\nRecord name := mkname { n_string : string; n_index : index }.\nAdd Printing Constructor name.\nUnset Primitive Projections.\n\nDefinition name_of_string s := mkname s 0.\nCoercion name_of_string : string >-> name.\nBind Scope string_scope with name.\n\nLemma name_dec (a : name) (b : name) :\n  {a = b} + {a <> b}.\nProof.\n  destruct (string_dec (n_string a) (n_string b)).\n  - destruct (Nat.eq_dec (n_index a) (n_index b)).\n    + left; destruct a, b; cbn in *; subst; easy.\n    + right; intro; subst; contradiction.\n  - right; intro; subst; contradiction.\nQed.\n\nDefinition indistinct_names a b :=\n  n_string a = n_string b.\n\nDefinition distinct_names a b :=\n  not (indistinct_names a b).\n\nLemma distinct_names_dec a b :\n  { distinct_names a b } + { indistinct_names a b }.\nProof.\n  destruct (string_dec (n_string a) (n_string b)).\n  - right; easy.\n  - left; easy.\nQed.\n\nLemma distinct_names_same a :\n  ~ (distinct_names a a).\nProof.\n  intro Hd.\n  unfold distinct_names, indistinct_names in Hd.\n  easy.\nQed.\n\nLemma distinct_names_symmetric {a b} :\n  distinct_names a b ->\n  distinct_names b a.\nProof.\n  unfold distinct_names; intuition.\nQed.\n  \n(* Shift the index of a name up by one *)\nDefinition succ_name (a : name) :=\n  mkname (n_string a) (S (n_index a)).\n\n(* Shift up all names with the same string as [a] and an index\n   greater than or equal to [a]'s *)\nDefinition shift_name (a : name) (b : name) :=\n  mkname (n_string b)\n   (if string_dec (n_string a) (n_string b) then\n      shift_idx (n_index a) (n_index b)\n    else\n      n_index b).\nArguments shift_name !a !b.\n\nLemma rw_shift_name_distinct a b :\n  distinct_names a b ->\n  shift_name a b = b.\nProof.\n  unfold shift_name.\n  destruct (string_dec (n_string a) (n_string b)); easy.  \nQed.\n\nLemma rw_shift_name_indistinct a b :\n  indistinct_names a b ->\n  shift_name a b\n  = mkname (n_string b) (shift_idx (n_index a) (n_index b)).\nProof.\n  unfold shift_name.\n  destruct (string_dec (n_string a) (n_string b)); easy.\nQed.\n\nLemma rw_shift_name_same a :\n  shift_name a a = succ_name a.\nProof.\n  rewrite rw_shift_name_indistinct by easy.\n  rewrite rw_shift_idx_same; easy.\nQed.\n\n(* Partial inverse of [shift_name]. Returns [None] iff [b = a]. *)\nDefinition inverse_shift_name (a : name) (b : name) :=\n  if string_dec (n_string a) (n_string b) then\n    option_map (mkname (n_string b))\n      (inverse_shift_idx (n_index a) (n_index b))\n  else\n    Some b.\n\nLemma rw_inverse_shift_name_distinct a b :\n  distinct_names a b ->\n  inverse_shift_name a b = Some b.\nProof.\n  unfold inverse_shift_name.\n  destruct (string_dec (n_string a) (n_string b)); easy.\nQed.\n\nLemma rw_inverse_shift_name_indistinct a b :\n  indistinct_names a b ->\n  inverse_shift_name a b\n  = option_map (mkname (n_string b))\n      (inverse_shift_idx (n_index a) (n_index b)).\nProof.\n  unfold inverse_shift_name.\n  destruct (string_dec (n_string a) (n_string b)); easy.\nQed.\n\nLemma rw_inverse_shift_name_same a :\n  inverse_shift_name a a = None.\nProof.\n  rewrite rw_inverse_shift_name_indistinct by easy.\n  rewrite rw_inverse_shift_idx_same; easy.\nQed.\n\n(* Rewrite [shift_idx]s, [unshift_idx]s and [inverse_shift_idx]s where\n   the order of the parameters can be determined by the omega tactic *)\nLtac simpl_names :=\n  repeat progress\n    (match goal with\n     | |- context [shift_name ?a ?b] =>\n       first\n         [ rewrite (rw_shift_name_distinct a b) by easy\n         | rewrite (rw_shift_name_indistinct a b) by easy ]\n     | |- context [inverse_shift_name ?a ?b] =>\n       first\n         [ rewrite (rw_inverse_shift_name_distinct a b) by easy\n         | rewrite (rw_inverse_shift_name_indistinct a b) by easy ]\n     end; cbn).\n\n(* Case split on the strings of the parameters, then simplify any\n   [shift_names]s and [inverse_shift_names]s affected by the\n   ordering. *)\nLtac case_strings a b :=\n  destruct (distinct_names_dec a b);\n  simpl_names.\n\n(* Inverses *)\n\nLemma rw_inverse_shift_name_shift_name a b :\n  inverse_shift_name a (shift_name a b) = Some b.\nProof.\n  case_strings a b; autorewrite with rw_idxs; easy.\nQed.\n\nLemma rw_shift_name_inverse_shift_name a b :\n  option_map (shift_name a) (inverse_shift_name a b)\n  = if distinct_names_dec a b then Some b\n    else if Nat.eq_dec (n_index a) (n_index b) then None\n    else Some b.\nProof.\n  case_strings a b; try easy;\n    case_order (n_index a) (n_index b);\n    simpl_names; simpl_idxs;\n      try replace (S (pred (n_index b))) with (n_index b) by omega;\n      destruct (Nat.eq_dec (n_index a) (n_index b)); try omega; easy.\nQed.    \n\nHint Rewrite @rw_shift_name_same @rw_inverse_shift_name_same\n     @rw_inverse_shift_name_shift_name\n  : rw_names.\n\n(* Renaming operation on names *)\n\nDefinition rename_name a b c :=\n  match inverse_shift_name b c with\n  | Some c' => shift_name a c'\n  | None => a\n  end.\n\nArguments rename_name !a !b !c.\n\nLemma rw_rename_name_distinct a b c :\n  distinct_names a c ->\n  rename_name b a c = shift_name b c.\nProof.\n  intros.\n  unfold rename_name.\n  rewrite (rw_inverse_shift_name_distinct a c) by easy.\n  easy.\nQed.\n\nLemma rw_rename_name_both_distinct a b c :\n  distinct_names a c ->\n  distinct_names b c ->\n  rename_name b a c = c.\nProof.\n  intros.\n  rewrite (rw_rename_name_distinct a b c) by easy.\n  rewrite (rw_shift_name_distinct b c) by easy.\n  easy.\nQed.\n\nLemma rw_rename_name_same a b : rename_name b a a = b.\nProof.\n  unfold rename_name.\n  autorewrite with rw_names; easy.\nQed.\n\nLemma rw_rename_name_shift_name a b c :\n  rename_name b a (shift_name a c) = shift_name b c.\nProof.\n  unfold rename_name.\n  autorewrite with rw_names; easy.\nQed.\n\nLemma rw_rename_name_rename_name a b c d :\n  rename_name b a (rename_name a c d)\n  = rename_name b c d.\nProof.\n  unfold rename_name.\n  case_strings c d;\n    case_order (n_index c) (n_index d);\n    autorewrite with rw_names; easy.\nQed.\n\nHint Rewrite @rw_rename_name_same @rw_rename_name_shift_name\n     @rw_rename_name_rename_name\n  : rw_names.\n\n(* Comparison for free names *)\n\nInductive name_comparison (a : name) : name -> Set :=\n| same_name : name_comparison a a\n| diff_name b : name_comparison a (shift_name a b).\n\nLemma compare_names a b : name_comparison a b.\nProof.\n  destruct a as [an ai], b as [bn bi]; cbn.\n  remember (string_dec an bn) as Hdec.\n  destruct Hdec; subst.\n  - destruct (compare_idx ai bi) as [|j].\n    + apply same_name.\n    + replace (mkname bn (shift_idx ai j))\n        with (shift_name (mkname bn ai) (mkname bn j));\n        try apply diff_name.\n      unfold shift_name, n_string.\n      rewrite <- HeqHdec; easy.      \n  - replace (mkname bn bi)\n        with (shift_name (mkname an ai) (mkname bn bi));\n      try apply diff_name.\n    unfold shift_name, n_string.\n    rewrite <- HeqHdec; easy.\nQed.\n\n(* Bound variables are represented by a level *)\n\nDefinition Zero := Empty_set.\n\nInductive Succ {S : Set} : Set := l0 | lS (s : S).\n\nFixpoint level (V : nat) : Set :=\n  match V with\n  | 0 => Zero\n  | S V => @Succ (level V)\n  end.\nArguments level !V.\n\n(* Variables are either free names or bound levels *)\n\nInductive var {V : nat} :=\n| free (name : name)\n| bound (l : level V).\n\n(* The core operations acting on variables *)\n\nDefinition wkv {V} (v : @var V) : @var (S V) :=\n  match v with\n  | free n => free n\n  | bound l => @bound (S V) (lS l)\n  end.\n\nDefinition openv a {V} (v : @var (S V)) : @var V :=\n  match v with\n  | free n => free (shift_name a n)\n  | bound l0 => free a\n  | bound (lS l) => @bound V l\n  end.\n\nDefinition closev a {V} (v : @var V) : @var (S V) :=\n  match v with\n  | free n =>\n    match inverse_shift_name a n with\n    | Some n' => free n'\n    | None => @bound (S V) l0\n    end\n  | bound l => @bound (S V) (lS l)\n  end.\n\nDefinition bindv {V} (v : @var (S V)) : option (@var V) :=\n  match v with\n  | free n => Some (free n)\n  | bound l0 => None\n  | bound (lS l) => Some (@bound V l)\n  end.\n\n(* We don't want to reduce the operations if it just exposes\n   the inner match. ([wkv] has no inner matches) *)\n\nArguments openv : simpl nomatch.\nArguments closev : simpl nomatch.\nArguments bindv : simpl nomatch.\n\n(* Add reductions for [closev]. The other operations reduce\n   directly by cbn. *)\n\nLemma rw_closev_shift a b :\n  forall {V}, @closev a V (free (shift_name a b)) = free b.\nProof.\n  unfold closev; autorewrite with rw_names; easy.\nQed.\n\nLemma rw_closev_same a :\n  forall {V}, @closev a V (free a) =\n    @bound (S V) (@l0 (level V)).\nProof.\n  unfold closev; autorewrite with rw_names; easy.\nQed.\n\nHint Rewrite @rw_closev_shift @rw_closev_same : rw_vars.\n\n(* Open and close on the same variable are inverses. Weaken\n   is a right inverse of bind. *)\n\nLemma rw_openv_closev a {V} (v : @var V) :\n  openv a (closev a v) = v.\nProof.\n  destruct v as [n|l]; cbn; try easy.\n  destruct (compare_names a n); autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_closev_openv a {V} (v : @var (S V)) :\n  closev a (openv a v) = v.\nProof.\n  destruct v as [n|[|l]]; cbn;\n    autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_bindv_wkv {V} (v : @var V) :\n  bindv (wkv v) = Some v.\nProof. destruct v; easy. Qed.\n\nHint Rewrite @rw_closev_openv @rw_openv_closev @rw_bindv_wkv\n  : rw_vars.\n\n(* [openv] and [closev] on distinct names *)\nLemma closev_distinct {a b} (Hd : distinct_names a b) {V} :\n  closev a (@free V b) = free b.\nProof.\n  unfold closev.\n  rewrite (rw_inverse_shift_name_distinct a b) by easy.\n  easy.\nQed.\n\nLemma openv_distinct {a b} (Hd : distinct_names a b) {V} :\n  openv a (@free (S V) b) = free b.\nProof.\n  unfold openv.\n  rewrite (rw_shift_name_distinct a b) by easy.\n  easy.\nQed.\n\n(* Combined operations *)\n\nDefinition shiftv a {V} v := @openv a V (wkv v).\nDefinition renv a b {V} v := @openv a V (closev b v).\nDefinition substv a {V} v := @bindv V (closev a v).\n\n(* We want [shiftv] to reduce whenever [v] is a\n   constructor, since [wkv] will always reduce in\n   such cases. *)\nArguments shiftv a {V} !v.\n\n(* Add reductions for [renv] and [substv] based on the\n   similar reductions for [closev] *)\n\nLemma rw_renv_free a b c :\n  forall {V}, @renv b a V (free c) =\n    free (rename_name b a c).\nProof.\n  intros; unfold renv.\n  destruct (compare_names a c);\n    autorewrite with rw_names rw_vars; easy.\nQed.\n\nLemma rw_substv_shift a c :\n  forall {V}, @substv a V (free (shift_name a c)) =\n              Some (free c).\nProof.\n  intros; unfold substv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_substv_same a :\n  forall {V}, @substv a V (free a) = None.\nProof.\n  intros; unfold substv; autorewrite with rw_vars; easy.\nQed.\n\nHint Rewrite @rw_renv_free @rw_substv_shift @rw_substv_same\n  : rw_vars.\n\n(* Combined operation reductions based on identities *)\n\nLemma rw_closev_shiftv a {V} (v : @var V) :\n  closev a (shiftv a v) = wkv v.\nProof.\n  unfold shiftv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_closev_renv a b {V} (v : @var V) :\n  closev a (renv a b v) = closev b v.\nProof.\n  unfold renv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_renv_same a {V} (v : @var V) :\n  renv a a v = v.\nProof.\n  unfold renv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_renv_openv a b {V} (v : @var (S V)) :\n  renv b a (openv a v) = openv b v.\nProof.\n  unfold renv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_renv_shiftv a b {V} (v : @var V) :\n  renv b a (shiftv a v) = shiftv b v.\nProof.\n  unfold renv, shiftv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_renv_renv a b c {V} (v : @var V) :\n  renv b a (renv a c v) = renv b c v.\nProof.\n  unfold renv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_substv_renv a b {V} (v : @var V) :\n  substv a (renv a b v) = substv b v.\nProof.\n  unfold renv, substv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_substv_shiftv a {V} (v : @var V) :\n  substv a (shiftv a v) = Some v.\nProof.\n  unfold shiftv, substv; autorewrite with rw_vars; easy.\nQed.\n\nHint Rewrite @rw_closev_shiftv @rw_closev_renv @rw_renv_same\n     @rw_renv_openv @rw_renv_shiftv @rw_renv_renv\n     @rw_substv_renv @rw_substv_shiftv\n  : rw_vars.\n\n(* Fold combined operations *)\n\nLemma rw_shiftv_fold a {V} (v : @var V) :\n  openv a (wkv v) = shiftv a v.\nProof. easy. Qed.\nLemma rw_renv_fold a b {V} (v : @var V) :\n  openv b (closev a v) = renv b a v.\nProof. easy. Qed.\nLemma rw_substv_fold a {V} (v : @var V) :\n  bindv (closev a v) = substv a v.\nProof. easy. Qed.\n\nHint Rewrite @rw_shiftv_fold @rw_renv_fold @rw_substv_fold\n  : rw_vars.\n\n(* Combined operations on distinct names *)\n\nLemma shiftv_distinct {a b} (Hd : distinct_names a b) {V} :\n  shiftv a (@free V b) = free b.\nProof.\n  cbn; rewrite (rw_shift_name_distinct a b) by easy; easy.\nQed.\n\nLemma renv_distinct {a b c} (Hd : distinct_names a c) {V} :\n  renv b a (@free V c) = free (shift_name b c).\nProof.\n  autorewrite with rw_vars.\n  rewrite (rw_rename_name_distinct a b c) by easy; easy.\nQed.\n\nLemma renv_both_distinct {a b c}\n      (Hd1 : distinct_names a c) (Hd2 : distinct_names b c) {V} :\n  renv b a (@free V c) = free c.\nProof.\n  autorewrite with rw_vars.\n  rewrite (rw_rename_name_both_distinct a b c) by easy; easy.\nQed.\n\nLemma substv_distinct {a b} (Hd : distinct_names a b) {V} :\n  substv a (@free V b) = Some (free b).\nProof.\n  unfold substv; rewrite (closev_distinct Hd); easy.\nQed.\n\n(* [wkv] commutes with [shiftv] and [renv]. We generally\n   try to move [wkv] leftwards but carefully to avoid\n   breaking confluence. *)\n\nLemma swap_shiftv_wkv a {V} (v : @var V) :\n  shiftv a (wkv v) = wkv (shiftv a v).\nProof. destruct v; easy. Qed.\n\nLemma swap_renv_wkv a b {V} (v : @var V) :\n  renv a b (wkv v) = wkv (renv a b v).\nProof. \n  destruct v; cbn; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_bindv_shiftv_wkv a {V} (v : @var V) :\n  bindv (shiftv a (wkv v)) = Some (shiftv a v).\nProof.\n  rewrite swap_shiftv_wkv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_bindv_renv_wkv a b {V} (v : @var V) :\n  bindv (renv a b (wkv v)) = Some (renv a b v).\nProof.\n  rewrite swap_renv_wkv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_openv_shiftv_wkv a b {V} (v : @var V) :\n  openv a (shiftv b (wkv v)) = shiftv a (shiftv b v).\nProof.\n  rewrite swap_shiftv_wkv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_openv_renv_wkv a b c {V} (v : @var V) :\n  openv a (renv b c (wkv v)) = shiftv a (renv b c v).\nProof.\n  rewrite swap_renv_wkv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_closev_wkv_shiftv a {V} (v : @var V) :\n  closev a (wkv (shiftv a v)) = wkv (wkv v).\nProof.\n  rewrite <- swap_shiftv_wkv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_renv_wkv_shiftv a b {V} (v : @var V) :\n  renv b a (wkv (shiftv a v)) = wkv (shiftv b v).\nProof.\n  rewrite swap_renv_wkv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_substv_wkv_shiftv a {V} (v : @var V) :\n  substv a (wkv (shiftv a v)) = Some (wkv v).\nProof.\n  rewrite <- swap_shiftv_wkv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_closev_wkv_renv a b {V} (v : @var V) :\n  closev a (wkv (renv a b v)) = closev b (wkv v).\nProof.\n  rewrite <- swap_renv_wkv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_renv_wkv_renv a b c {V} (v : @var V) :\n  renv b a (wkv (renv a c v)) = wkv (renv b c v).\nProof.\n  rewrite swap_renv_wkv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_substv_wkv_renv a b {V} (v : @var V) :\n  substv a (wkv (renv a b v)) = substv b (wkv v).\nProof.\n  rewrite <- swap_renv_wkv; autorewrite with rw_vars; easy.\nQed.\n\nLemma rw_shiftv_shiftv_wkv a b {V} (v : @var V) :\n  shiftv a (shiftv b (wkv v)) = shiftv a (wkv (shiftv b v)).\nProof.\n  rewrite swap_shiftv_wkv; easy.\nQed.\n\nLemma rw_renv_shiftv_wkv a b c {V} (v : @var V) :\n  renv b a (shiftv c (wkv v)) = renv b a (wkv (shiftv c v)).\nProof.\n  rewrite swap_shiftv_wkv; easy.\nQed.\n\nLemma rw_renv_renv_wkv a b c d {V} (v : @var V) :\n  renv b a (renv c d (wkv v)) = renv b a (wkv (renv c d v)).\nProof.\n  rewrite swap_renv_wkv; easy.\nQed.\n\nHint Rewrite @rw_bindv_shiftv_wkv @rw_bindv_renv_wkv\n     @rw_openv_shiftv_wkv @rw_openv_renv_wkv\n     @rw_closev_wkv_shiftv @rw_renv_wkv_shiftv\n     @rw_substv_wkv_shiftv @rw_closev_wkv_renv\n     @rw_renv_wkv_renv @rw_substv_wkv_renv\n     @rw_shiftv_shiftv_wkv @rw_renv_shiftv_wkv\n     @rw_renv_renv_wkv\n  : rw_vars.\n\n(* Comparison of vars *)\n\nInductive var_comparison (a : name) {V} : @var V -> Set :=\n| samev : var_comparison a (@free V a)\n| diffv v : var_comparison a (shiftv a v).\n\nDefinition compare_vars a {V} (v : @var V)\n  : var_comparison a v.\n  destruct v as [b|l].\n  destruct (compare_names a b).\n  - constructor.\n  - change (free (shift_name a b))\n      with (shiftv a (@free V b)).\n    constructor.\n  - change (bound l) with (shiftv a (bound l)).\n    constructor.\nQed.\n\n(* Comparison with [bound l0] *)\n\nInductive l0_comparison {V} : @var (S V) -> Set :=\n| samel0 : l0_comparison (@bound (S V) (@l0 (level V)))\n| diffl0 v : l0_comparison (wkv v).\n\nDefinition compare_l0 {V} (v : @var (S V)) : l0_comparison v.\nProof.\n  destruct v as [a|[|l]].\n  - change (@free (S V) a)\n      with (@wkv V (free a)); constructor.\n  - constructor.\n  - change (@bound (S V) (lS l))\n      with (@wkv V (bound l)); constructor.\nQed.\n\n(* A couple of useful commuting lemmas *)\n\nLemma swap_shiftv_shiftv_distinct {a b} (Hd : distinct_names a b)\n      {V} (v : @var V) :\n  shiftv a (shiftv b v) = shiftv b (shiftv a v).\nProof.\n  destruct v as [c|l]; cbn; try easy.\n  case_strings b c; try easy.\n  rewrite (rw_shift_name_distinct a c).\n  - rewrite (rw_shift_name_distinct a _);\n      replace (n_string c) with (n_string b); easy.\n  - unfold distinct_names, indistinct_names.\n    replace (n_string c) with (n_string b); easy.\nQed.\n\nLemma swap_shift_close {a b} (Hd : distinct_names b a)\n      {V} (v : @var V) :\n  closev a (shiftv b v) = shiftv b (closev a v).\nProof.\n  destruct (compare_vars a v).\n  - rewrite shiftv_distinct by easy.\n    autorewrite with rw_vars rw_names.\n    easy.\n  - rewrite swap_shiftv_shiftv_distinct by easy.\n    autorewrite with rw_vars rw_names.\n    rewrite swap_shiftv_wkv; easy.\nQed.\n\nDefinition swap_bound {V} (v : @var (S (S V))) : @var (S (S V)) :=\n  match v with\n  | free a => free a\n  | bound l =>\n    @bound (S (S V))\n    (match l with\n     | l0 => lS l0\n     | lS l0 => l0\n     | lS (lS v) => lS (lS v)\n     end)\n  end.\n\nLemma swap_close_close {x y}\n      (Hd : distinct_names x y) {V} {v : @var V} :\n  closev x (closev y v) = swap_bound (closev y (closev x v)).\nProof.\n  destruct (compare_vars y v); autorewrite with rw_vars; cbn.\n  - replace (free y) with (shiftv x (@free V y)).\n    + autorewrite with rw_vars; easy.\n    + rewrite (shiftv_distinct Hd); easy.\n  - rewrite swap_shift_close\n      by auto using distinct_names_symmetric.\n    autorewrite with rw_vars.\n    destruct v as [n|l]; cbn; try easy.\n    destruct (compare_names x n);\n      autorewrite with rw_vars; easy.\nQed.\n\n(* Algebra of operations on [var 0] *)\nInductive renaming {trm : Set} :=\n| r_id\n| r_comp (r : renaming) (s : renaming)\n| r_shift (b : name) (r : renaming)\n| r_rename (b : name) (r : renaming) (a : name)\n| r_subst (t : trm) (r : renaming) (a : name).\n\nDeclare Scope ren_scope.\nNotation \"r1 ; r2\" := (r_comp r1 r2)\n  (at level 57, right associativity) : ren_scope.\nNotation \"r ,, ^ a\" := (r_shift a r)\n  (at level 47, left associativity) : ren_scope.\nNotation \"r ,, a <- b\" := (r_rename a r b)\n  (at level 47, left associativity, a at next level) : ren_scope.\nNotation \"r ,, u // a\" := (r_subst u r a)\n  (at level 47, left associativity, u at next level) : ren_scope.\nNotation \"^ a\" := (r_shift a r_id)\n  (at level 47, left associativity) : ren_scope.\nNotation \"a <- b\" := (r_rename a r_id b)\n  (at level 47, left associativity) : ren_scope.\nNotation \"u // a\" := (r_subst u r_id a)\n  (at level 47, left associativity) : ren_scope.\nNotation \"r ,, a\" := (r_rename a r a)\n  (at level 47, left associativity) : ren_scope.\n\nDelimit Scope ren_scope with ren.\n\nFixpoint total {trm : Set} (r : @renaming trm) : Prop :=\n  match r with\n  | r_id => True\n  | r_comp r s => total r /\\ total s\n  | r_shift b r => total r\n  | r_rename b r a => total r\n  | r_subst u r a => False\n  end.\n\nDefinition proj1 {A B : Prop} (H : A /\\ B) := let (a, _) := H in a.\nDefinition proj2 {A B : Prop} (H : A /\\ B) := let (_, b) := H in b.\n\nFixpoint applyt {trm : Set} (r : @renaming trm) :\n  forall (rn : total r), morph (@var) 0 (@var) 0 :=\n  match r with\n  | r_id =>\n    fun _ _ v => v\n  | r_comp r s =>\n    fun rn V v => applyt r (proj1 rn) V (applyt s (proj2 rn) V v)\n  | r_shift b r =>\n    fun rn V v => openv b (applyt r rn (S V) (wkv v))\n  | r_rename b r a =>\n    fun rn V v => openv b (applyt r rn (S V) (closev a v))\n  | r_subst _ _ _ => False_rec _\n  end.\n\nArguments applyt {trm} !r rn {V} t /.\n\nLemma rw_applyt_bound trm (r : @renaming trm) rn :\n  forall {V} (v : level V),\n    applyt r rn (bound v) = bound v.\nProof.\n  induction r; try destruct rn; cbn; intros; auto;\n    repeat match goal with [ H : _ |- _ ] => rewrite H; clear H end;\n    cbn; easy.\nQed.\n\nHint Rewrite @rw_applyt_bound : rw_names.\n\nLemma rw_applyt_wkv :\n  forall trm (r : @renaming trm) (rn : total r) {V} (v : @var V),\n    applyt r rn (wkv v) = wkv (applyt r rn v).\nProof.\n  induction r; cbn; intuition.\n  - rewrite IHr2, IHr1; reflexivity.\n  - repeat rewrite IHr.\n    autorewrite with rw_vars.\n    rewrite <- swap_shiftv_wkv; reflexivity.\n  - destruct (compare_vars a v).\n    + autorewrite with rw_vars rw_names; reflexivity.\n    + autorewrite with rw_vars.\n      repeat rewrite IHr.\n      autorewrite with rw_vars.\n      rewrite <- swap_shiftv_wkv; reflexivity.\nQed.\n\nHint Rewrite @rw_applyt_wkv : rw_names.\n\nLemma rw_applyt_wkv_free trm (r : @renaming trm) rn {a V} :\n  applyt r rn (@free (S V) a) = wkv (applyt r rn (@free V a)).\nProof.\n  change (@free (S V) a) with (wkv (@free V a)).\n  apply rw_applyt_wkv.\nQed.\n\nHint Rewrite @rw_applyt_wkv_free : rw_names.\n\n", "meta": {"author": "lpw25", "repo": "shifted-names", "sha": "14bb7fcdbd6bf558d51c33a084b8981ef5368773", "save_path": "github-repos/coq/lpw25-shifted-names", "path": "github-repos/coq/lpw25-shifted-names/shifted-names-14bb7fcdbd6bf558d51c33a084b8981ef5368773/src/Var.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6777944446935439}}
{"text": "Require Coq.Init.Datatypes.\nImport Coq.Init.Notations.\nNotation \"A -> B\" := (forall (_ : A), B) : type_scope.\n\nSection inductionExamples.\n\n  Inductive ThreeElementSet:=\n  |zero\n  |one\n  |two.\n\n  Inductive PairOrTriple:=\n  |pair (x y:ThreeElementSet)\n  |triple (x y z:ThreeElementSet).\n\n  Inductive Lst:=\n  |nil\n  |cons (x:ThreeElementSet) (l:Lst).\n\nEnd inductionExamples.\n\nSection functionExamples.\n\n  Definition plusOneModThree (X:ThreeElementSet):\n    ThreeElementSet.\n  Proof.\n    induction X.\n    - apply one.\n    - apply two.\n    - apply zero.\n  Defined.\n\n  Definition constantAtZero (X:ThreeElementSet):\n    ThreeElementSet.\n  Proof.\n    apply zero.\n  Defined.\n\n  Definition plusTwoModThree (X:ThreeElementSet):\n    ThreeElementSet.\n  Proof.\n    induction X.\n    - apply two.\n    - apply zero.\n    - apply one.\n  Defined.\n\n  Definition roundToPair (p:PairOrTriple):\n    PairOrTriple.\n  Proof.\n    induction p.\n    - apply (pair x y).\n    - apply (pair x y).\n  Defined.\n\n  Fixpoint append (l m:Lst):\n    Lst.\n  Proof.\n    destruct l.\n    - apply m.\n    - apply (cons x (append l m)).\n  Defined.\n\nEnd functionExamples.\n\nSection inductionExercises.\n\n  Inductive FourElementSet:=\n  (* define four element set *).\n  \n  Inductive Nat:=\n  (* define natural number induction *).\n\nEnd inductionExercises.\n\nSection functionExercises.\n\n  Definition constantAtZero4 (x:FourElementSet):\n    FourElementSet.\n  Proof.\n    (* define the function x|->0*)\n  Defined.\n\n  Definition doubleModThree (x:ThreeElementSet):\n    ThreeElementSet.\n  Proof.\n    (* define the function x|->2x (mod 3)*)\n  Defined.\n\n  Definition fourModThree (x:FourElementSet):\n    ThreeElementSet.\n  Proof.\n    (* define the function x|->x( mod 3) \n       that lands in ThreeElementSet *)\n  Defined.\n\n  Fixpoint length (l:Lst):\n    Nat.\n  Proof.\n    (* return the length of l *)\n  Defined.\n\nEnd functionExercises.\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "mwpb", "repo": "introduction-univalence-coq", "sha": "106643b5aea0937740e5ea51993a21da117dca2a", "save_path": "github-repos/coq/mwpb-introduction-univalence-coq", "path": "github-repos/coq/mwpb-introduction-univalence-coq/introduction-univalence-coq-106643b5aea0937740e5ea51993a21da117dca2a/inductionAndFunctions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545425, "lm_q2_score": 0.8031737916455819, "lm_q1q2_score": 0.6777944292698691}}
{"text": "Add LoadPath \"C:\\Projects\\Coq\".\n\nRequire Export Induction.\nRequire Export Case.\n\nModule NatList.\n\nInductive natprod :=\n  | pair : nat -> nat -> natprod.\n\nDefinition fst a :=\n  match a with\n  | pair a _ => a\n  end.\n\nDefinition snd v :=\n  match v with\n  | pair _ b => b\n  end.\n\nEval compute in fst (pair 2 3).\n\nNotation \"( x , y )\" := (pair x y).\n\nEval compute in fst(2, 3).\n\nDefinition fst' p :=\n  match p with\n  | (x, _) => x\n  end.\n\nDefinition snd' p :=\n  match p with\n  | (_, y) => y\n  end.\n\nDefinition swap_pair v :=\n  match v with\n  | (x, y) => (y, x)\n  end.\n\nTheorem surjective_pairing':\n  forall n m, (n, m) = (fst (n, m), snd (n, m)).\nProof.\n  reflexivity.\nQed.\n\nTheorem surjective_pairing_stuck:\n  forall p, p = (fst p, snd p).\nProof.\n  destruct p.\n  reflexivity.\nQed.\n\nTheorem snd_fst_is_swap:\n  forall p, (snd p, fst p) = swap_pair p.\n\n  destruct p.\n  reflexivity.\nQed.\n  \nTheorem fst_swap_is_snd:\n  forall p, fst (swap_pair p) = snd p.\ndestruct p.\nreflexivity.\nQed.\n\nInductive natlist :=\n  | nil\n  | cons: nat -> natlist -> natlist.\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint repeat n count :=\n  match count with\n  | O => nil\n  | S count' => n :: repeat n count'\n  end.\n\nEval compute in repeat 9 10.\n\nFixpoint length l :=\n  match l with\n  | nil => O\n  | _ :: rest => S (length rest)\n  end.\n\nFixpoint app l1 l2 :=\n  match l1 with\n  | [] => l2\n  | x::rest => x :: app rest l2\n  end.\n\nEval compute in app [1;2;3] (repeat 9 10).\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 l :=\n  match l with\n  | [] => default\n  | h :: _ => h\n  end.\n\nDefinition tl l :=\n  match l with\n  | [] => []\n  | _ :: t => t\n  end.\n\nFixpoint nonzeros l :=\n  match l with\n  | [] => []\n  | 0 :: rest => nonzeros rest\n  | x :: rest => x :: nonzeros rest\n  end.\n\nFixpoint oddmembers l :=\n  match l with\n  | [] => []\n  | n :: rest =>\n    if oddb n then\n      n :: oddmembers rest\n    else\n      oddmembers rest\n  end.\n\nDefinition countoddmembers l :=\n  length (oddmembers l).\n\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nreflexivity. Qed.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\nreflexivity. Qed.\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\nreflexivity. Qed.\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\nreflexivity. Qed.\nExample test_countoddmembers3: countoddmembers nil = 0.\nreflexivity. Qed.\n\nFixpoint alternate l1 l2 :=\n  match l1, l2 with\n  | [], l\n  | l, [] => l\n  | x :: xs, y :: ys => x :: y :: alternate xs ys\n  end.\n\nExample test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nreflexivity. Qed.\nExample test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].\nreflexivity. Qed.\nExample test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].\nreflexivity. Qed.\nExample test_alternate4: alternate [] [20;30] = [20;30].\nreflexivity. Qed.\n\nDefinition bag := natlist.\n\nFixpoint count v s :=\n  match s with\n  | [] => O\n  | x :: xs =>\n    if beq_nat v x then\n      S (count v xs)\n    else\n      count v xs\n  end.\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nreflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nreflexivity. Qed.\n\nDefinition sum : bag -> bag -> bag := app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nreflexivity. Qed.\n\nDefinition add v s : bag := v :: s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nreflexivity. Qed.\n\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nreflexivity. Qed.\n\nDefinition member v (s: bag) :=\n  ble_nat 1 (count v s).\n\nExample test_member1: member 1 [1;4;1] = true.\nreflexivity. Qed.\n\nExample test_member2: member 2 [1;4;1] = false.\nreflexivity. Qed.\n\nFixpoint remove_one v s : bag :=\n  match s with\n  | [] => []\n  | x :: xs =>\n    if beq_nat x v\n    then xs\n    else x :: remove_one v xs\n  end.\n\nExample test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nreflexivity. Qed.\nExample test_remove_one2: count 5 (remove_one 5 [2;1;4;1]) = 0.\nreflexivity. Qed.\nExample test_remove_one3: count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nreflexivity. Qed.\nExample test_remove_one_4: count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nreflexivity. Qed.\n\nFixpoint remove_all v (s: bag) :=\n  match s with\n  | [] => []\n  | x :: xs =>\n    if beq_nat x v\n    then remove_all v xs\n    else x :: remove_all v xs\n  end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nreflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nreflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nreflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nreflexivity. Qed.\n\nFixpoint subset (s1: bag) (s2: bag) :=\n  match s1 with\n  | [] => true\n  | x :: xs =>\n    if member x s2\n    then subset xs (remove_one x s2)\n    else false\n  end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nreflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nreflexivity. Qed.\n\nTheorem beq_nat_refl:\n  forall n, beq_nat n n = true.\ninduction n. reflexivity. simpl. rewrite -> IHn. reflexivity. Qed.\n\nTheorem add_count:\n  forall n s, count n (add n s) = S (count n s).\nProof.\n  intros.\n  induction s as [|s'].\n  simpl.\n  rewrite -> beq_nat_refl.\n  reflexivity.\n  simpl.\n  rewrite -> beq_nat_refl.\n  reflexivity.\nQed.\n\nTheorem nil_app:\n  forall l, [] ++ l = l.\nreflexivity. Qed.\n\nTheorem tl_length_pred:\n  forall l, pred (length l) = length (tl l).\nProof.\n  destruct l as [|n l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    reflexivity.\nQed.\n\nTheorem app_ass:\n  forall l1 l2 l3, (l1 ++ l2) ++ l3 = l1 ++ l2 ++ l3.\nProof.\n  intros.\n  induction l1 as [|n l1'].\n  Case \"l1 = []\".\n    reflexivity.\n  Case \"l1 = n :: l1'\".\n    simpl. rewrite -> IHl1'.\n    reflexivity.\nQed.\n\nTheorem app_length:\n  forall l1 l2, length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros.\n  induction l1 as [|n l1'].\n  Case \"l1 = []\".\n    reflexivity.\n  Case \"l1 = n :: l1'\".\n    simpl. rewrite -> IHl1'.\n    reflexivity.\nQed.\n\nFixpoint snoc l v :=\n  match l with\n  | [] => [v]\n  | h :: t => h :: snoc t v\n  end.\n\nFixpoint rev l :=\n  match l with\n  | [] => []\n  | h :: t => snoc (rev t) h\n  end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nreflexivity. Qed.\nExample test_rve2: rev [] = [].\nreflexivity. Qed.\n\nTheorem rev_length_firsttry:\n  forall l, length (rev l) = length l.\nProof.\n  intro.\n  induction l as [| n l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    simpl.\n    rewrite <- IHl'.\nAbort.\n\nTheorem length_snoc:\n  forall n l, length (snoc l n) = S (length l).\nProof.\n  intros.\n  induction l as [|n' l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = n' :: l'\".\n    simpl.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem rev_length:\n  forall l, length (rev l) = length l.\nProof.\n  intro.\n  induction l as [|n l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    simpl.\n    rewrite -> length_snoc.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem app_nil_end:\n  forall l, l ++ [] = l.\nProof.\n  intro.\n  induction l as [|n l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    simpl.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem app_ass4:\n  forall l1 l2 l3 l4, l1 ++ l2 ++ l3 ++ l4 = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros.\n  rewrite -> app_ass.\n  rewrite -> app_ass.\n  reflexivity.\nQed.\n\nTheorem snoc_append:\n  forall l n, snoc l n = l ++ [n].\nProof.\n  intros.\n  induction l as [|n' l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = n' :: l'\".\n    simpl.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem distr_rev:\n  forall l1 l2, rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros.\n  induction l1 as [|n l1'].\n  Case \"l1 = []\".\n    simpl.\n    rewrite -> app_nil_end.\n    reflexivity.\n  Case \"l1 = n :: l1'\".\n    simpl.\n    rewrite -> IHl1'.\n    rewrite -> snoc_append.\n    rewrite -> snoc_append.\n    rewrite -> app_ass.\n    reflexivity.\nQed.\n\nLemma nonzeros_app:\n  forall l1 l2, nonzeros (l1 ++ l2) = nonzeros l1 ++ nonzeros l2.\nProof.\n  intros.\n  induction l1 as [|n l1'].\n  Case \"l1 = []\".\n    reflexivity.\n  Case \"l1 = n :: l1'\".\n    destruct n as [|n'].\n    SCase \"n = 0\".\n      simpl.\n      rewrite -> IHl1'.\n      reflexivity.\n    SCase \"n = S n'\".\n      simpl.\n      rewrite -> IHl1'.\n      reflexivity.\nQed.\n\nTheorem snoc_pow:\n  forall n m l, cons n (snoc l m) = n :: l ++ [m].\nProof.\n  intros.\n  rewrite -> snoc_append.\n  reflexivity.\nQed.\n\nTheorem count_member_nonzero:\n  forall (s: bag), ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n  intro.\n  reflexivity.\nQed.\n\nTheorem ble_n_Sn:\n  forall n, ble_nat n (S n) = true.\nProof.\n  intro n.\n  induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\nTheorem remove_decreases_count:\n  forall (s: bag),\n    ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  intro s.\n  induction s as [|n s'].\n  Case \"s = []\".\n    reflexivity.\n  Case \"s = n :: s'\".\n    destruct n as [|n'].\n    simpl.\n    rewrite -> ble_n_Sn.\n    reflexivity.\n    simpl.\n    rewrite -> IHs'.\n    reflexivity.\nQed.\n\nTheorem count_distr:\n  forall n l1 l2, count n (sum l1 l2) = count n l1 + count n l2.\nProof.\n  intros.\n  induction l1 as [|n' l1'].\n  Case \"l1 = []\".\n    reflexivity.\n  Case \"l1 = n' :: l1'\".\n    replace (sum (n' :: l1') l2) with (n' :: sum l1' l2).\n    simpl.\n    rewrite -> IHl1'.\n    destruct (beq_nat n n').\n    reflexivity.\n    reflexivity.\n    reflexivity.\nQed.\n\nTheorem rev_involutive:\n  forall l, rev (rev l) = l.\nProof.\n  intro l.\n  induction l as [|n l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    simpl.\n    rewrite -> snoc_append.\n    rewrite -> distr_rev.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem rev_injective:\n  forall l1 l2, rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2.\n  intro H.\n  induction l1 as [|n l1'].\n  Case \"l1 = []\".\n    replace l2 with (rev (rev l2)).\n    rewrite <- H.\n    reflexivity.\n    rewrite -> rev_involutive.\n    reflexivity.\n  Case \"l1 = n :: l1'\".\n    replace (n :: l1') with (rev (rev (n :: l1'))).\n    rewrite <- rev_involutive.\n    rewrite -> H.\n    reflexivity.\n    rewrite -> rev_involutive.\n    reflexivity.\nQed.\n\nTheorem rev_injective_easy:\n  forall l1 l2, rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros.\n  replace l1 with (rev (rev l1)).\n  replace l2 with (rev (rev l2)).\n  rewrite -> H.\n  reflexivity.\n  rewrite -> rev_involutive.\n  reflexivity.\n  rewrite -> rev_involutive.\n  reflexivity.\nQed.\n\nTheorem rev_injective_easier:\n  forall l1 l2, rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros.\n  replace l1 with (rev (rev l1)).\n  rewrite -> H.\n  rewrite -> rev_involutive.\n  reflexivity.\n  rewrite -> rev_involutive.\n  reflexivity.\nQed.\n\nTheorem rev_injective_easiest:\n  forall l1 l2, rev l1 = rev l2 -> l1 = l2.\nintros.\n  rewrite <- rev_involutive.\n  rewrite <- H.\n  rewrite -> rev_involutive.\n  reflexivity.\nQed.\n\n(*\nIt would seem I skipped writing rev_involutive on first reading\nand thus only came up with the idea of solving that first when\ngoing through my first solution to rev_injective. As you can see\nI took down a heavy path on my first go which took multiple attempts\nto get to the simplest solution. Yet it might be possible that my\nfirst solution (using involution anyway) could be easier than the\nso call hard way.\n*)\n\nInductive natoption :=\n  | Some: nat -> natoption\n  | None.\n\nFixpoint index_bad n l :=\n  match l with\n  | [] => 43\n  | a :: l' =>\n    if beq_nat n 0\n    then a\n    else index_bad (pred n) l'\n  end.\n\nFixpoint index n l :=\n  match n, l with\n  | _, [] => None\n  | 0, a :: l' => Some a\n  | S n', _ :: l' => index n' l'\n  end.\n\nExample test_index1: index 0 [4;5;6;7] = Some 4.\nreflexivity. Qed.\nExample test_index2: index 3 [4;5;6;7] = Some 7.\nreflexivity. Qed.\nExample test_index3: index 10 [1;2;3] = None.\nreflexivity. Qed.\n\nDefinition option_elim d o :=\n  match o with\n  | Some v => v\n  | None => d\n  end.\n\nDefinition hd_opt l :=\n  match l with\n  | [] => None\n  | x :: _ => Some x\n  end.\n\nExample test_hd_opt1: hd_opt [] = None.\nreflexivity. Qed.\nExample test_hd_opt2: hd_opt [1] = Some 1.\nreflexivity. Qed.\nExample test_hd_opt3: hd_opt [5;6] = Some 5.\nreflexivity. Qed.\n\nTheorem option_elim_hd:\n  forall l default, hd default l = option_elim default (hd_opt l).\nProof.\n  intros.\n  destruct l.\n  reflexivity.\n  reflexivity.\nQed.\n\nFixpoint beq_natlist l1 l2 :=\n  match l1, l2 with\n  | [], [] => true\n  | [], _ | _, [] => false\n  | a :: l1', b :: l2' =>\n     andb (beq_nat a b) (beq_natlist l1' l2')\n  end.\n\nExample test_beq_natlist1: beq_natlist nil [] = true.\nreflexivity. Qed.\nExample test_beq_natlist2: beq_natlist [1;2;3] [1;2;3] = true.\nreflexivity. Qed.\nExample test_beq_natlist3: beq_natlist [1;2;3] [1;2;4] = false.\nreflexivity. Qed.\n\nTheorem beq_natlist_refl:\n  forall l, true = beq_natlist l l.\nProof.\n  intro l.\n  induction l as [|n l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    simpl. rewrite -> IHl'.\n    rewrite -> beq_nat_refl.\n    reflexivity.\nQed.\n\nModule Dictionary.\n\nInductive dict :=\n  | empty\n  | record: nat -> nat -> dict -> dict.\n\nDefinition insert k v d := record k v d.\n\nFixpoint find k d :=\n  match d with\n  | empty => None\n  | record k' v d' =>\n    if beq_nat k k'\n    then Some v\n    else find k d'\n  end.\n\nTheorem dictionary_invariant1':\n  forall d k v, find k (insert k v d) = Some v.\nProof.\n  intros.\n  simpl.\n  rewrite -> beq_nat_refl.\n  reflexivity.\nQed.\n\nTheorem dictionary_invarian2':\n  forall d m n o,\n    beq_nat m n = false -> find m d = find m (insert n o d).\nProof.\n  intros.\n  simpl.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nEnd Dictionary.\n\nEnd NatList.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.8438951045175642, "lm_q1q2_score": 0.6777944268706572}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Binary relations                                                        *\n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibTactics LibLogic LibBool LibLogic LibProd LibSum.\nRequire Export LibOperation.\n\n\n(* ********************************************************************** *)\n(** * Generalities on binary relations *)\n\nDefinition binary (A : Type) := A -> A -> Prop.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inhabited *)\n\nInstance binary_inhab : forall A, Inhab (binary A).\nProof using. intros. apply (prove_Inhab (fun _ _ => True)). Qed.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Extensionality *)\n\nLemma binary_extensional : forall A (R1 R2:binary A),\n  (forall x y, R1 x y <-> R2 x y) -> R1 = R2.\nProof using. intros_all. apply~ prop_ext_2. Qed.\n\nInstance binary_extensional_inst : forall A, Extensional (binary A).\nProof using. intros. apply (Build_Extensional _ (@binary_extensional A)). Defined.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties *)\n\nSection Properties.\nVariables (A:Type).\nImplicit Types x y z : A.\nImplicit Types R : binary A.\n\n(** Reflexivity, irreflexivity, transitivity, symmetry, totality, definedness, functionality *)\n\nDefinition refl R := \n  forall x, R x x.\nDefinition irrefl R := \n  forall x, ~ (R x x).\nDefinition trans R := \n  forall y x z, R x y -> R y z -> R x z.\nDefinition sym R := \n  forall x y, R x y -> R y x.\nDefinition asym R := \n  forall x y, R x y -> ~ R y x.\nDefinition total R :=\n  forall x y, R x y \\/ R y x.\nDefinition defined R :=\n  forall x, exists y, R x y.\n  (* I would have liked to call this [total R], but this already\n     means something else... *)\nDefinition functional R :=\n  forall x y z, R x y -> R x z -> y = z.\n\n(** Antisymmetry with respect to an equivalence relation, \n    antisymmetry with respect to Leibnitz equality,\n     i.e. [forall x y, R x y -> R y x -> x = y] *)\n\nDefinition antisym_wrt (E:binary A) R :=\n  forall x y, R x y -> R y x -> E x y.\nDefinition antisym := \n  antisym_wrt (@eq A).\n\n(** Inclusion between relations *)\n\nDefinition incl R1 R2 :=\n  forall x y, R1 x y -> R2 x y.\n\n(** Equality between relations *)\n\n(* TODO move further down in the file *)\n(* TODO already called binary_extensional above? *)\nLemma rel_eq_intro : forall R1 R2,\n  (forall x y, R1 x y <-> R2 x y) -> R1 = R2.\nProof using. intros. extens*. Qed.\n\nLemma rel_eq_elim : forall R1 R2,\n  R1 = R2 -> (forall x y, R1 x y <-> R2 x y).\nProof using. intros. subst*. Qed.\n\nEnd Properties.\n\n\n(** Inclusion between a function and a relation. *)\n(* TODO: maybe use longer name? *)\n\nDefinition incl_fr A B (f : A -> B) (R : A -> B -> Prop) :=\n  forall x, R x (f x).\nDefinition incl_rf A B (R : A -> B -> Prop) (f : A -> B) :=\n  forall x y, R x y -> y = f x.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Constructions *)\n\nSection Constructions.\nVariable (A : Type).\nImplicit Types R : binary A.\nImplicit Types x y z : A.\n\n(** The empty relation *)\n\nDefinition empty : binary A :=\n  fun x y => False.\n\n(** Swap (i.e. symmetric, converse, or transpose) of a relation *)\n \nDefinition flip R : binary A := \n  fun x y => R y x.\n\n(** Complement of a relation *)\n \nDefinition compl R : binary A := \n  fun x y => ~ R y x.\n\n(** Union of two relations *)\n\nDefinition union R1 R2 : binary A :=\n  fun x y => R1 x y \\/ R2 x y.\n\n(** Strict order associated with an order, wrt Leibnitz' equality *)\n\nDefinition strict R : binary A :=\n  fun x y => R x y /\\ x <> y.\n\n(** Large order associated with an order, wrt Leibnitz' equality *)\n\nDefinition large R : binary A :=\n  fun x y => R x y \\/ x = y.\n\nEnd Constructions.\n\n(** Inverse image *)\n\nDefinition inverse_image (A B:Type) (R:binary B) (f:A->B) : binary A :=\n  fun x y => R (f x) (f y).\n\n(** Composition of two relations, usually written [R1; R2]. *)\n\nDefinition sequence (A B C:Type) (R1:A->B->Prop) (R2:B->C->Prop) : A->C->Prop :=\n  fun x z => exists y, R1 x y /\\ R2 y z.\n\n(** Pointwise product *)\n\nDefinition prod2 (A1 A2:Type) \n (R1:binary A1) (R2:binary A2) : binary (A1*A2) :=\n  fun p1 p2 : A1*A2 => match p1,p2 with (x1,x2),(y1,y2) => \n    R1 x1 y1 /\\ R2 x2 y2 end.\n\nDefinition prod3 (A1 A2 A3:Type) \n (R1:binary A1) (R2:binary A2) (R3:binary A3) \n : binary (A1*A2*A3) := \n  prod2 (prod2 R1 R2) R3.\n\nDefinition prod4 (A1 A2 A3 A4:Type) \n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4) \n : binary (A1*A2*A3*A4) := \n  prod2 (prod3 R1 R2 R3) R4.\n\nTactic Notation \"unfold_prod\" :=\n  unfold prod4, prod3, prod2.\n\nTactic Notation \"unfolds_prod\" :=\n  unfold prod4, prod3, prod2 in *.\n\n(** Lexicographical order *)\n\nDefinition lexico2 {A1 A2} (R1:binary A1) (R2:binary A2)\n  : binary (A1*A2) :=\n  fun p1 p2 : A1*A2 => let (x1,x2) := p1 in let (y1,y2) := p2 in\n  (R1 x1 y1) \\/ (x1 = y1) /\\ (R2 x2 y2).\n\nDefinition lexico3 {A1 A2 A3} \n (R1:binary A1) (R2:binary A2) (R3:binary A3) : binary (A1*A2*A3) :=\n  lexico2 (lexico2 R1 R2) R3.\n\nDefinition lexico4 {A1 A2 A3 A4}\n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4) \n : binary (A1*A2*A3*A4) :=\n  lexico2 (lexico3 R1 R2 R3) R4.\n\nTactic Notation \"unfold_lexico\" :=\n  unfold lexico4, lexico3, lexico2.\n\nTactic Notation \"unfolds_lexico\" :=\n  unfold lexico4, lexico3, lexico2 in *.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of constructions *)\n\nSection ConstructionsProp.\nVariable (A : Type).\nImplicit Types R : binary A.\nImplicit Types x y z : A.\n\nLemma refl_elim : forall x y R,\n  refl R -> x = y -> R x y.\nProof using. intros_all. subst~. Qed.\n\nLemma sym_elim : forall x y R,\n  sym R -> R x y -> R y x.\nProof using. introv Sy R1. apply* Sy. Qed.\n\nLemma antisym_elim : forall x y R,\n  antisym R -> R x y -> R y x -> x <> y -> False.\nProof using. intros_all*. Qed.\n\nLemma irrefl_neq : forall R,\n  irrefl R -> \n  forall x y, R x y -> x <> y. \nProof using. introv H P E. subst. apply* H. Qed.\n\nLemma irrefl_elim : forall R,\n  irrefl R -> \n  forall x, R x x -> False. \nProof using. introv H P. apply* H. Qed.\n\nLemma sym_to_eq : forall R,\n  sym R -> \n  forall x y, R x y = R y x.\nProof using. introv H. intros. apply prop_ext. split; apply H. Qed.\n\nLemma sym_flip : forall R,\n  sym R -> flip R = R.\nProof using. intros. unfold flip. apply* prop_ext_2. Qed.\n\nLemma trans_strict : forall R,\n  trans R -> antisym R -> trans (strict R).\nProof using. \n  introv T S. unfold strict. introv [H1 H2] [H3 H4]. split. \n    apply* T.\n    intros K. subst. apply H2. apply~ S.\nQed.\n\nLemma flip_flip : forall R, \n  flip (flip R) = R.\nProof using. intros. apply* prop_ext_2. Qed.\n\nLemma flip_refl : forall R,\n  refl R -> refl (flip R).\nProof using. intros_all. unfolds flip. auto. Qed.\n\nLemma flip_trans : forall R,\n  trans R -> trans (flip R).\nProof using. intros_all. unfolds flip. eauto. Qed.\n\nLemma flip_antisym : forall R,\n  antisym R -> antisym (flip R).\nProof using. intros_all. unfolds flip. auto. Qed.\n\nLemma flip_asym : forall R,\n  asym R -> asym (flip R).\nProof using. intros_all. unfolds flip. apply* H. Qed.\n\nLemma flip_total : forall R,\n  total R -> total (flip R).\nProof using. intros_all. unfolds flip. auto. Qed.\n\nLemma flip_strict : forall R,\n  flip (strict R) = strict (flip R).\nProof using. intros. unfold flip, strict. apply* prop_ext_2. Qed.\n\nLemma flip_large : forall R,\n  flip (large R) = large (flip R).\nProof using. intros. unfold flip, large. apply* prop_ext_2. Qed.\n\nLemma large_refl : forall R,\n  refl (large R).\nProof using. unfold large. intros_all~. Qed.\n\nLemma large_trans : forall R,\n  trans R -> trans (large R).\nProof using. unfold large. introv Tr [H1|E1] [H2|E2]; subst*. Qed.\n\nLemma large_antisym : forall R,\n  antisym R -> antisym (large R).\nProof using. introv T. introv H1 H2. (* todo: bug introv *)\n  unfolds large. destruct H1; destruct H2; auto. Qed.\n\nLemma large_total : forall R,\n  total R -> total (large R).\nProof using. unfold large. intros_all~. destruct* (H x y). Qed.\n\nLemma strict_large : forall R,\n  irrefl R -> strict (large R) = R.\nProof using.\n  intros. unfold large, strict. apply prop_ext_2.\n  intros_all. split; intros K.\n  autos*.\n  split. left*. apply* irrefl_neq. \nQed.\n\nLemma large_strict : forall R,\n  refl R -> large (strict R) = R.\nProof using. \n  intros. unfold large, strict. apply prop_ext_2. \n  intros_all. split; intros K.\n  destruct K. autos*. subst*.\n  destruct (classic (x1 = x2)). subst. right*. left*.\n  (* todo: cases *)\nQed.\n\nLemma double_incl : forall R1 R2,\n  incl R1 R2 -> incl R2 R1 -> R1 = R2.\nProof using. unfolds incl. intros. apply* prop_ext_2. Qed. \n\nLemma rel_incl_trans : forall R1 R2 R3,\n  incl R1 R2 -> incl R2 R3 -> incl R1 R3.\nProof using.\n  unfold incl. eauto.\nQed.\n\nLemma flip_injective : injective (@flip A).\nProof using.\n  intros R1 R2 E. apply prop_ext_2. intros x y.\n  unfolds flip. rewrite* (func_same_2 y x E).\nQed.\n\nLemma eq_by_flip_l : forall R1 R2,\n  R1 = flip R2 -> flip R1 = R2.\nProof using. intros. apply flip_injective. rewrite~ flip_flip. Qed.\n\nLemma eq_by_flip_r : forall R1 R2,\n  flip R1 = R2 -> R1 = flip R2.\nProof using. intros. apply flip_injective. rewrite~ flip_flip. Qed.\n\n(* TODO: do we really need this extensional version? *)\n\nLemma flip_flip_applied : forall R x y, \n  (flip (flip R)) x y = R x y.\nProof using. auto. Qed.\n\nEnd ConstructionsProp.\n\nLemma trans_elim : forall A (y x z : A) R,\n  trans R -> R x y -> R y z -> R x z.\nProof using. introv Tr R1 R2. apply* Tr. Qed.\n\nLemma trans_sym : forall A (y x z : A) R,\n  trans R -> sym R -> R z y -> R y x -> R x z.\nProof using. introv Tr Sy R1 R2. apply* Tr. Qed.\n\nLemma trans_sym_1 : forall A (y x z : A) R,\n  trans R -> sym R -> R y x -> R y z -> R x z.\nProof using. introv Tr Sy R1 R2. apply* Tr. Qed.\n\nLemma trans_sym_2 : forall A (y x z : A) R,\n  trans R -> sym R -> R x y -> R z y -> R x z.\nProof using. introv Tr Sy R1 R2. apply* Tr. Qed.\n\nImplicit Arguments trans_elim [A x z R].\nImplicit Arguments trans_sym [A x z R].\nImplicit Arguments trans_sym_1 [A x z R].\nImplicit Arguments trans_sym_2 [A x z R].\n\n(** Other forms of transitivity *)\n\nLemma large_strict_trans : forall A y x z (R:binary A),\n  trans R -> large R x y -> R y z -> R x z.\nProof using. introv T [E|H] H'; subst*. Qed.\n\nLemma strict_large_trans : forall A y x z (R:binary A),\n  trans R -> R x y -> large R y z -> R x z.\nProof using. introv T H [E|H']; subst*. Qed.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties about [functional] *)\n\n(* A relation [R] is functional if and only if [flip R] composed\n   with [R] is a subset of the diagonal relation [eq]. *)\n\nLemma functional_characterization : forall A (R : binary A),\n  functional R <->\n  incl (sequence (flip R) R) eq.\nProof using.\n  unfold functional, incl, sequence, flip.\n  split.\n    introv ? [ ? [ ? ? ]]. eauto.\n    eauto.\nQed.\n\n(* The empty relation is functional. *)\n\nLemma functional_empty : forall A,\n  functional (@empty A).\nProof using.\n  unfold empty. repeat intro. tauto.\nQed.\n\n(* TODO: a tactic \"functional_exploit R\" that looks for two distinct\n   assumptions in the goal of the form [R ?x ?y] and produces [functional R]\n   as subgoal. *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties about [union] *)\n\n(* TODO: rename lemmas *)\n\nLemma prove_rel_union_left : forall A (R1 R2 : binary A) x y,\n  R1 x y ->\n  union R1 R2 x y.\nProof using.\n  unfold union. eauto.\nQed.\n\nLemma prove_rel_union_right : forall A (R1 R2 : binary A) x y,\n  R2 x y ->\n  union R1 R2 x y.\nProof using.\n  unfold union. eauto.\nQed.\n\nLemma union_covariant : forall A (R1 R2 S1 S2 : binary A),\n  incl R1 S1 ->\n  incl R2 S2 ->\n  incl (union R1 R2) (union S1 S2).\nProof using.\n  unfold incl, union. intuition eauto.\nQed.\n\nLemma union_refl_left : forall A (R S : binary A),\n  refl R ->\n  refl (union R S).\nProof using.\n  unfold refl, union. eauto.\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of inclusion *)\n\n(* TODO change hypothesis names in proofs *)\n(* TODO decide whether to use a tactic exploit functional *)\n\n(* TODO there is something by the same name in [LibBag]. *)\nLemma incl_refl : forall A (R:binary A), incl R R.\nProof using. unfolds incl. auto. Qed.\n\nHint Resolve incl_refl. \n\nLemma lexico2_incl : forall A1 A2\n (R1 R1':binary A1) (R2 R2':binary A2),\n  incl R1 R1' -> incl R2 R2' -> incl (lexico2 R1 R2) (lexico2 R1' R2').\nProof using. \n  introv I1 I2. intros [x1 x2] [y1 y2] [H1|[H1 H2]].\n  left~. subst. right~.\nQed.\n\n(* If [R] is defined, [S] is functional, and [R] is a subset of [S],\n   then [R] equals [S]. In that case, [R] and [S] represent the graph\n   of a total function. *)\n\nLemma defined_incl_functional:\n  forall (A : Type) (R S : binary A),\n  defined R ->\n  functional S ->\n  incl R S ->\n  R = S.\nProof using.\n  introv hdef hfun hincl. eapply binary_extensional. intros v w. split; intros H; eauto.\n  forwards [ w' M1 ]: hdef v.\n  forwards M2: hincl. eauto.\n  forwards: hfun H M2. subst*.\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inclusion between a function and a relation. *)\n\n(* If the relation [R] is functional and if [f] is included in [R],\n   then [R] is included in [f], i.e., they coincide. *)\n\n(* TODO: currently limited to the case where B = A, but it shouldn't be *)\n\nLemma incl_fr_functional:\n  forall A (f : A -> A) (R : A -> A -> Prop),\n  incl_fr f R ->\n  functional R ->\n  incl_rf R f.\nProof using.\n  introv h1 h2. intros a b H. forwards M: h1 a. forwards*: h2 H M.\nQed.\n\n(* Note: [incl_fr f R] implies [defined R]\n         [incl_rf R f] implies [functional R] *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of lexicographical composition *)\n\nSection LexicoApp.\nVariables (A1 A2 A3 A4:Type). \nVariables (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4). \n\nLemma lexico2_app_1 : forall x1 x2 y1 y2,\n  R1 x1 y1 -> \n  lexico2 R1 R2 (x1,x2) (y1,y2).\nProof using. intros. left~. Qed.\n\nLemma lexico2_app_2 : forall x1 x2 y1 y2,\n  x1 = y1 -> R2 x2 y2 -> \n  lexico2 R1 R2 (x1,x2) (y1,y2).\nProof using. intros. right~. Qed.\n\nLemma lexico3_app_1 : forall x1 x2 x3 y1 y2 y3,\n  R1 x1 y1 -> \n  lexico3 R1 R2 R3 (x1,x2,x3) (y1,y2,y3).\nProof using. intros. left. left~. Qed.\n\nLemma lexico3_app_2 : forall x1 x2 x3 y1 y2 y3,\n  x1 = y1 -> R2 x2 y2 -> \n  lexico3 R1 R2 R3 (x1,x2,x3) (y1,y2,y3).\nProof using. intro. left. right~. Qed.\n\nLemma lexico3_app_3 : forall x1 x2 x3 y1 y2 y3,\n  x1 = y1 -> x2 = y2 -> R3 x3 y3 -> \n  lexico3 R1 R2 R3 (x1,x2,x3) (y1,y2,y3).\nProof using. intros. right~. Qed.\n\nLemma lexico4_app_1 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  R1 x1 y1 -> \n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof using. intros. left. left. left~. Qed.\n\nLemma lexico4_app_2 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  x1 = y1 -> R2 x2 y2 -> \n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof using. intros. left. left. right~. Qed.\n\nLemma lexico4_app_3 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  x1 = y1 -> x2 = y2 -> R3 x3 y3 -> \n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof using. intros. left. right~. Qed.\n\nLemma lexico4_app_4 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  x1 = y1 -> x2 = y2 -> x3 = y3 -> R4 x4 y4 -> \n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof using. intros. right~. Qed.\n\nEnd LexicoApp.\n\n(** Transitivity *)\n\nLemma lexico2_trans : forall A1 A2 \n (R1:binary A1) (R2:binary A2),\n  trans R1 -> trans R2 -> trans (lexico2 R1 R2).\nProof using.\n  introv Tr1 Tr2. intros [x1 x2] [y1 y2] [z1 z2] Rxy Ryz.\n  simpls. destruct Rxy as [L1|[Eq1 L1]]; \n   destruct Ryz as [M2|[Eq2 M2]]; subst*.\nQed.\n\nLemma lexico3_trans : forall A1 A2 A3 \n (R1:binary A1) (R2:binary A2) (R3:binary A3),\n  trans R1 -> trans R2 -> trans R3 -> trans (lexico3 R1 R2 R3).\nProof using.\n  introv Tr1 Tr2 Tr3. applys~ lexico2_trans. applys~ lexico2_trans.\nQed.\n\nLemma lexico4_trans : forall A1 A2 A3 A4 \n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4),\n  trans R1 -> trans R2 -> trans R3 -> trans R4 -> trans (lexico4 R1 R2 R3 R4).\nProof using.\n  introv Tr1 Tr2 Tr3. applys~ lexico3_trans. applys~ lexico2_trans.\nQed.\n\n\n\n(* ********************************************************************** *)\n(** * Equivalence relations *)\n\nRecord equiv A (R:binary A) :=\n { equiv_refl : refl R;\n   equiv_sym : sym R;\n   equiv_trans : trans R }. \n\n(** Equality is an equivalence *)\n\nLemma eq_equiv : forall A, equiv (@eq A).\nProof using. intros. constructor; intros_all; subst~. Qed.\n\nHint Resolve eq_equiv.\n\n(** Symmetric of an equivalence is an equivalence *)\n\nLemma flip_equiv : forall A (E:binary A),\n  equiv E -> equiv (flip E).\nProof using.\n  introv Equi. unfold flip. constructor; intros_all; \n    dintuition eauto.\nQed.\n\n(** Product of two equivalences is an equivalence *)\n\nLemma prod2_equiv : forall A1 A2 (E1:binary A1) (E2:binary A2),\n  equiv E1 -> equiv E2 -> equiv (prod2 E1 E2).\nProof using.\n  introv Equi1 Equi2. constructor.\n  intros [x1 x2]. simpl. dintuition.\n  intros [x1 x2] [y1 y2]. simpl. dintuition.\n  intros [x1 x2] [y1 y2] [z1 z2]. simpl. dintuition eauto.\nQed.\n(* NEWCOQ: clean above *)\n\n(* todo: other arities of Prod *)\n\n\n(**************************************************************************)\n(* * Closures *)\n\n(* TODO: eliminate the use of the section variable R *)\n\nSection Closures.\nVariables (A : Type) (R : binary A).\n\n(* ---------------------------------------------------------------------- *)\n(** ** Constructions *)\n\n(** Reflexive-transitive closure ( R* ) *)\n\nInductive rtclosure : binary A :=\n  | rtclosure_refl : forall x,\n      rtclosure x x\n  | rtclosure_step : forall y x z,\n      R x y -> rtclosure y z -> rtclosure x z.\n\n(** Transitive closure ( R+ ) *)\n\nInductive tclosure : binary A :=\n  | tclosure_intro : forall x y z,\n     R x y -> rtclosure y z -> tclosure x z.\n\n(** Another definition of transitive closure ( R+ ) *)\n\nInductive tclosure' : binary A :=\n  | tclosure'_step : forall x y,  \n     R x y -> tclosure' x y\n  | tclosure'_trans : forall y x z,\n     tclosure' x y -> tclosure' y z -> tclosure' x z.\n\n(** Symmetric-transitive closure *)\n\nInductive stclosure (A:Type) (R:binary A) : binary A :=\n  | stclosure_step : forall x y,\n      R x y -> stclosure R x y\n  | stclosure_sym : forall x y, \n      stclosure R x y -> stclosure R y x\n  | stclosure_trans : forall y x z,\n      stclosure R x y -> stclosure R y z -> stclosure R x z.\n\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties *)\n\nHint Constructors tclosure rtclosure equiv.\n\nLemma rtclosure_once : forall x y,\n  R x y -> rtclosure x y.\nProof using. autos*. Qed.\n\nHint Resolve rtclosure_once.\n\nLemma rtclosure_trans : trans rtclosure.  \nProof using. introv R1 R2. induction* R1. Qed.\n\nLemma rtclosure_last : forall y x z,\n  rtclosure x y -> R y z -> rtclosure x z.\nProof using. introv R1 R2. induction* R1. Qed.\n\nHint Resolve rtclosure_trans.\n\nLemma tclosure_once : forall x y,\n  R x y -> tclosure x y.  \nProof using. eauto. Qed.\n\nLemma tclosure_rtclosure : forall x y,\n  tclosure x y -> rtclosure x y.  \nProof using. intros. destruct* H. Qed.\n\nHint Resolve tclosure_once tclosure_rtclosure.\n\nLemma tclosure_rtclosure_step : forall x y z,\n  rtclosure x y -> R y z -> tclosure x z.\nProof using. intros. induction* H. Qed.\n\nLemma tclosure_step_rtclosure : forall x y z,\n  R x y -> rtclosure y z -> tclosure x z.\nProof using. intros. gen x. induction* H0. Qed.\n\nLemma tclosure_step_tclosure : forall x y z,\n  R x y -> tclosure y z -> tclosure x z.\nProof using. intros. inverts* H0. Qed.\n\nHint Resolve tclosure_rtclosure_step tclosure_step_rtclosure.\n\nLemma tclosure_rtclosure_tclosure : forall y x z,\n  rtclosure x y -> tclosure y z -> tclosure x z.  \nProof using. intros. gen z. induction* H. Qed.\n\nLemma tclosure_tclosure_rtclosure : forall y x z,\n  tclosure x y -> rtclosure y z -> tclosure x z.  \nProof using. intros. induction* H. Qed. \n\nLemma tclosure_trans : trans tclosure.\nProof using. intros_all. autos* tclosure_tclosure_rtclosure. Qed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Induction *)\n\n(** Star induction principle with transitivity hypothesis *)\n\nLemma rtclosure_ind_trans : forall (P : A -> A -> Prop),\n  (forall x : A, P x x) ->\n  (forall x y : A, R x y -> P x y) ->\n  (forall y x z : A, rtclosure x y -> P x y -> rtclosure y z -> P y z -> P x z) ->\n  forall x y : A, rtclosure x y -> P x y.\nProof using.\n  introv Hrefl Hstep Htrans S. induction S.\n  auto. apply~ (@Htrans y).\nQed.\n\n(** Star induction principle with steps at the end *)\n\nLemma rtclosure_ind_right : forall (P : A -> A -> Prop),\n  (forall x : A, P x x) ->\n  (forall y x z : A, rtclosure x y -> P x y -> R y z -> P x z) ->\n  forall x y : A, rtclosure x y -> P x y.\nProof using.\n  introv Hrefl Hlast. apply rtclosure_ind_trans. \n  auto.\n  intros. apply~ (Hlast x).\n  introv S1 P1 S2 _. gen x. induction S2; introv S1 P1.\n     auto.\n     apply IHS2. eauto. apply~ (Hlast x). \nQed.\n\nEnd Closures.\n\n(** Star induction principle with transitivity hypothesis *)\n\nLemma tclosure_ind_trans : forall A (R:binary A) (P : A -> A -> Prop),\n  (forall x y : A, R x y -> P x y) ->\n  (forall y x z : A, tclosure R x y -> P x y -> tclosure R y z -> P y z -> P x z) ->\n  forall x y : A, tclosure R x y -> P x y.\nProof using.\n  Hint Resolve tclosure_once.\n  introv Hstep Htrans S. inverts S as HR S. gen x. induction S; introv HR.\n    autos*.\n    applys* Htrans. constructors*.\nQed.\n\nHint Resolve rtclosure_refl rtclosure_step rtclosure_once : rtclosure.\n(* TODO: should rename and complete the [closure] database *)\n(* TODO: should not need to re-export the following version *)\n\nLemma incl_tclosure_self : forall A (R:binary A), \n   incl R (tclosure R).\nProof using. unfolds incl. intros. apply~ tclosure_once. Qed.\nHint Resolve incl_tclosure_self. \n\n(* TODO: sort and complete the following *)\n\nHint Resolve stclosure_step stclosure_sym stclosure_trans.\n\nLemma stclosure_le : forall A (R1 R2 : binary A),\n  incl R1 R2 -> incl (stclosure R1) (stclosure R2).\nProof using. unfolds incl. introv Le H. induction* H. Qed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Additional definitions *)\n\n(* TODO: move above once section has been eliminated *)\n(* A theory of [rstclosure]. *)\n\nInductive rstclosure (A : Type) (R : binary A) : binary A :=\n  | rstclosure_step : forall x y,\n      R x y -> rstclosure R x y\n  | rstclosure_refl : forall x,\n      rstclosure R x x\n  | rstclosure_sym : forall x y, \n      rstclosure R x y -> rstclosure R y x\n  | rstclosure_trans : forall y x z,\n      rstclosure R x y -> rstclosure R y z -> rstclosure R x z.\n\n(** Symmetric closure *)\n\nDefinition sclosure (A:Type) (R:binary A) : binary A :=\n  fun x y => R x y \\/ R y x.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Hints *)\n\nHint Constructors tclosure : tclosure.\nHint Constructors rstclosure : rstclosure.\nHint Constructors stclosure : stclosure.\nHint Unfold sclosure : sclosure.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Additional properties *)\n\n(* TODO: check name of lemmas below, and sort lemmas *)\n\nLemma rtclosure_refl_contrapositive : forall A (R : binary A) x y,\n  ~ rtclosure R x y ->\n  x <> y.\nProof using.\n  intros. intro. subst. eauto using rtclosure_refl.\nQed.\n\nLemma rtclosure_rstclosure : forall A (R : binary A) x y,\n  rtclosure R x y -> rstclosure R x y.\nProof using.\n  induction 1; eauto with rstclosure.\nQed.\n\nLemma stclosure_rstclosure : forall A (R : binary A) x y,\n  stclosure R x y -> rstclosure R x y.\nProof using.\n  induction 1; eauto with rstclosure.\nQed.\n\nLemma stclosure_is_rstclosure : forall A (R : binary A),\n  refl R ->\n  stclosure R = rstclosure R.\nProof using.\n  intros. eapply binary_extensional. intros x y.\n  split; eauto using stclosure_rstclosure.\n  gen x y. induction 1; eauto with stclosure.\nQed.\n\nLemma refl_rstclosure : forall A (R : binary A),\n  refl (rstclosure R).\nProof using.\n  unfold refl. eauto with rstclosure.\nQed.\n\nLemma rstclosure_covariant : forall A (R S : binary A),\n  incl R S ->\n  incl (rstclosure R) (rstclosure S).\nProof using.\n  unfold incl. induction 2; eauto with rstclosure.\nQed.\n\nLemma rstclosure_inflationary: forall A (R : binary A),\n  incl R (rstclosure R).\nProof using.\n  unfold incl. eauto with rstclosure.\nQed.\n\nLemma prove_rstclosure_incl : forall A (R S : binary A),\n  incl R (rstclosure S) ->\n  incl (rstclosure R) (rstclosure S).\nProof using.\n  unfold incl. induction 2; eauto with rstclosure.\nQed.\n\nLemma rstclosure_union : forall A (R S : binary A),\n  incl (union (rstclosure R) (rstclosure S))\n       (rstclosure (union R S)).\nProof using.\n  unfold incl, union. intros ? ? ? x y H. \n  destruct H; gen x y;\n  induction 1; eauto with rstclosure.\nQed.\n\n\nLemma sym_sclosure : forall A (R : binary A),\n  sym (sclosure R).\nProof using.\n  unfold sym, sclosure. tauto.\nQed.\n\nLemma sclosure_is_a_closure_operator : forall A (R1 R2 : binary A),\n  incl R1 (sclosure R2) ->\n  incl (sclosure R1) (sclosure R2).\nProof using.\n  unfold sclosure, incl. introv h. introv H.\n  destruct H.\n  { eauto. }\n  { forwards M: h. eauto. destruct M; tauto. }\nQed.\n\nLemma sclosure_covariant : forall A (R1 R2 : binary A),\n  incl R1 R2 ->\n  incl (sclosure R1) (sclosure R2).\nProof using.\n  unfold sclosure, incl. introv M H. destruct H; eauto.\nQed.\n\nLemma rtclosure_covariant : forall A (R1 R2 : binary A),\n  incl R1 R2 ->\n  incl (rtclosure R1) (rtclosure R2).\nProof using.\n  unfold incl. induction 2; eauto with rtclosure.\nQed.\n\nLemma tclosure_covariant : forall A (R1 R2 : binary A),\n  incl R1 R2 ->\n  incl (tclosure R1) (tclosure R2).\nProof using.\n  unfold incl. inversion 2; subst. econstructor.\n  eauto.\n  eapply rtclosure_covariant; eauto.\nQed.\n\nLemma tclosure_last : forall A (R : binary A) y x z,\n  tclosure R x y -> R y z -> tclosure R x z.\nProof using.\n  inversion 1; intros; subst.\n  eauto using rtclosure_last with tclosure.\nQed.\n\n(* If a relation is symmetric, then so is its transitive closure. *)\n\nLemma sym_rtclosure : forall A (R : binary A),\n  sym R ->\n  sym (rtclosure R).\nProof using.\n  unfold sym. induction 2; eauto using rtclosure_last with rtclosure.\nQed.\n\nLemma sym_tclosure : forall A (R : binary A),\n  sym R ->\n  sym (tclosure R).\nProof using.\n  unfold sym. inversion 2; subst. \n  eapply tclosure_rtclosure_step.\n  eapply sym_rtclosure; eauto.\n  eauto.\nQed.\n\nLemma sclosure_incl_stclosure : forall A (R : binary A),\n  incl (sclosure R) (stclosure R).\nProof using.\n  unfold incl. inversion 1; eauto with stclosure.\nQed.\n\nLemma tclosure_incl_stclosure : forall A (R1 R2 : binary A),\n  incl R1 (stclosure R2) ->\n  incl (tclosure R1) (stclosure R2).\nProof using.\n  introv H M. induction M using tclosure_ind_trans.\n  applys* H.\n  applys* stclosure_trans.\nQed.\n\nLemma stclosure_is_tclosure_sclosure : forall A (R : binary A),\n  stclosure R = tclosure (sclosure R).\nProof using.\n  extens. intros x y. split.\n  { gen x y. induction 1.\n    { eauto with tclosure sclosure rtclosure. }\n    { eapply sym_tclosure. eapply sym_sclosure. eauto. }\n    { eapply tclosure_trans; eauto. }\n  }\n  { intros.\n    eapply tclosure_incl_stclosure; [ | eassumption ].\n    eapply sclosure_incl_stclosure. }\nQed.", "meta": {"author": "pleiad", "repo": "Refinements", "sha": "3a4d24329bdbb91b95a352b70db53f10cad094a1", "save_path": "github-repos/coq/pleiad-Refinements", "path": "github-repos/coq/pleiad-Refinements/Refinements-3a4d24329bdbb91b95a352b70db53f10cad094a1/TLC/LibRelation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388040954684, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.6777192140817763}}
{"text": "(** * Basics: Functional Programming in Coq *)\n \n(* This library definition is included here temporarily \n   for backward compatibility with Coq 8.3.  \n   Please ignore. *)\n(* Definition admit {T: Type} : T.  Admitted. *)\n\n(* ###################################################################### *)\n(** * Introduction *)\n\n(** The functional programming style brings programming closer to\n    mathematics: If a procedure or method has no side effects, then\n    pretty much all you need to understand about it is how it maps\n    inputs to outputs -- that is, you can think of its behavior as\n    just computing a mathematical function.  This is one reason for\n    the word \"functional\" in \"functional programming.\"  This direct\n    connection between programs and simple mathematical objects\n    supports both sound informal reasoning and formal proofs of\n    correctness.\n\n    The other sense in which functional programming is \"functional\" is\n    that it emphasizes the use of functions (or methods) as\n    _first-class_ values -- i.e., values that can be passed as\n    arguments to other functions, returned as results, stored in data\n    structures, etc.  The recognition that functions can be treated as\n    data in this way enables a host of useful idioms, as we will see.\n\n    Other common features of functional languages include _algebraic\n    data types_ and _pattern matching_, which make it easy to construct\n    and manipulate rich data structures, and sophisticated\n    _polymorphic type systems_ that support abstraction and code\n    reuse.  Coq shares all of these features.\n*)\n\n\n(* ###################################################################### *)\n(** * Enumerated Types *)\n\n(** One unusual aspect of Coq is that its set of built-in\n    features is _extremely_ small.  For example, instead of providing\n    the usual palette of atomic data types (booleans, integers,\n    strings, etc.), Coq offers an extremely powerful mechanism for\n    defining new data types from scratch -- so powerful that all these\n    familiar types arise as instances.  \n\n    Naturally, the Coq distribution comes with an extensive standard\n    library providing definitions of booleans, numbers, and many\n    common data structures like lists and hash tables.  But there is\n    nothing magic or primitive about these library definitions: they\n    are ordinary user code.\n\n    To see how this works, let's start with a very simple example. *)\n\n(* ###################################################################### *)\n(** ** Days of the Week *)\n\n(** The following declaration tells Coq that we are defining\n    a new set of data values -- a _type_. *)\n\nInductive day : Type :=\n  | monday : day\n  | tuesday : day\n  | wednesday : day\n  | thursday : day\n  | friday : day\n  | saturday : day\n  | sunday : day.\n\n(** The type is called [day], and its members are [monday],\n    [tuesday], etc.  The second through eighth lines of the definition\n    can be read \"[monday] is a [day], [tuesday] is a [day], etc.\"\n\n    Having defined [day], we can write functions that operate on\n    days. *)\n\nDefinition next_weekday (d:day) : day :=\n  match d with\n  | monday    => tuesday\n  | tuesday   => wednesday\n  | wednesday => thursday\n  | thursday  => friday\n  | friday    => monday\n  | saturday  => monday\n  | sunday    => monday\n  end.\n\n(** One thing to note is that the argument and return types of\n    this function are explicitly declared.  Like most functional\n    programming languages, Coq can often work out these types even if\n    they are not given explicitly -- i.e., it performs some _type\n    inference_ -- but we'll always include them to make reading\n    easier. *)\n\n(** Having defined a function, we should check that it works on\n    some examples.  There are actually three different ways to do this\n    in Coq.  First, we can use the command [Eval compute] to evaluate a\n    compound expression involving [next_weekday].  *)\n\nEval compute in (next_weekday friday).\n   (* ==> monday : day *)\nEval compute in (next_weekday (next_weekday saturday)).\n   (* ==> tuesday : day *)\n\n(** If you have a computer handy, now would be an excellent\n    moment to fire up the Coq interpreter under your favorite IDE --\n    either CoqIde or Proof General -- and try this for yourself.  Load\n    this file ([Basics.v]) from the book's accompanying Coq sources,\n    find the above example, submit it to Coq, and observe the\n    result. *)\n\n(** The keyword [compute] tells Coq precisely how to\n    evaluate the expression we give it.  For the moment, [compute] is\n    the only one we'll need; later on we'll see some alternatives that\n    are sometimes useful. *)\n\n(** Second, we can record what we _expect_ the result to be in\n    the form of a Coq example: *)\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\n(** This declaration does two things: it makes an\n    assertion (that the second weekday after [saturday] is [tuesday]),\n    and it gives the assertion a name that can be used to refer to it\n    later. *)\n(** Having made the assertion, we can also ask Coq to verify it,\n    like this: *)\n\nProof. simpl. reflexivity.  Qed.\n\n\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 a [Definition], a\n    program in some other, more conventional, programming\n    language (OCaml, Scheme, or Haskell) with a high-performance\n    compiler.  This facility is very interesting, since it gives us a\n    way to construct _fully certified_ programs in mainstream\n    languages.  Indeed, this is one of the main uses for which Coq was\n    developed.  We'll come back to this topic in later chapters.\n    More information can also be found in the Coq'Art book by Bertot\n    and Casteran, as well as the Coq reference manual. *)\n\n\n(* ###################################################################### *)\n(** ** Booleans *)\n\n(** In a similar way, we can define the type [bool] of booleans,\n    with members [true] and [false]. *)\n\nInductive bool : Type :=\n  | true : bool\n  | false : bool.\n\n(** Although we are rolling our own booleans here for the sake\n    of building up everything from scratch, Coq does, of course,\n    provide a default implementation of the booleans in its standard\n    library, together with a multitude of useful functions and\n    lemmas.  (Take a look at [Coq.Init.Datatypes] in the Coq library\n    documentation if you're interested.)  Whenever possible, we'll\n    name our own definitions and theorems so that they exactly\n    coincide with the ones in the standard library. *)\n\n(** Functions over booleans can be defined in the same way as\n    above: *)\n\nDefinition negb (b:bool) : bool := \n  match b with\n  | true => false\n  | false => true\n  end.\n\nDefinition andb (b1:bool) (b2:bool) : bool := \n  match b1 with \n  | true => b2 \n  | false => false\n  end.\n\nDefinition orb (b1:bool) (b2:bool) : bool := \n  match b1 with \n  | true => true\n  | false => b2\n  end.\n\n(** The last two illustrate the syntax for multi-argument\n    function definitions. *)\n\n(** The following four \"unit tests\" constitute a complete\n    specification -- a truth table -- for the [orb] function: *)\n\nExample test_orb1:  (orb true  false) = true. \nProof. 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\n(** (Note that we've dropped the [simpl] in the proofs.  It's not\n    actually needed because [reflexivity] will automatically perform\n    simplification.) *)\n\n(** _A note on notation_: We use square brackets to delimit\n    fragments of Coq code in comments in .v files; this convention,\n    also used by the [coqdoc] documentation tool, keeps them visually\n    separate from the surrounding text.  In the html version of the\n    files, these pieces of text appear in a [different font]. *)\n\n(** The values [Admitted] and [admit] can be used to fill\n    a hole in an incomplete definition or proof.  We'll use them in the\n    following exercises.  In general, your job in the exercises is \n    to replace [admit] or [Admitted] with real definitions or proofs. *)\n\n(** **** Exercise: 1 star (nandb) *)\n(** Complete the definition of the following function, then make\n    sure that the [Example] assertions below can each be verified by\n    Coq.  *)\n\n(** This function should return [true] if either or both of\n    its inputs are [false]. *)\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n    | true => negb b2\n    | false => true\n  end.\n\n(** Remove \"[Admitted.]\" and fill in each proof with \n    \"[Proof. reflexivity. Qed.]\" *)\n\nExample test_nandb1:               (nandb true false) = true.\nProof. reflexivity. Qed.\nExample test_nandb2:               (nandb false false) = true.\nProof. reflexivity. Qed.\nExample test_nandb3:               (nandb false true) = true.\nProof. reflexivity. Qed.\nExample test_nandb4:               (nandb true true) = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star (andb3) *)\n(** Do the same for the [andb3] function below. This function should\n    return [true] when all of its inputs are [true], and [false]\n    otherwise. *)\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  match b1 with\n    | true => andb b2 b3\n    | false => false\n  end.\n\nExample test_andb31:                 (andb3 true true true) = true.\nProof. 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(** [] *)\n\n(* ###################################################################### *)\n(** ** Function Types *)\n\n(** The [Check] command causes Coq to print the type of an\n    expression.  For example, the type of [negb true] is [bool]. *)\n\nCheck true.\n(* ===> true : bool *)\nCheck (negb true).\n(* ===> negb true : bool *)\n\n(** Functions like [negb] itself are also data values, just like\n    [true] and [false].  Their types are called _function types_, and\n    they are written with arrows. *)\n\nCheck negb.\n(* ===> negb : bool -> bool *)\n\n(** The type of [negb], written [bool -> bool] and pronounced\n    \"[bool] arrow [bool],\" can be read, \"Given an input of type\n    [bool], this function produces an output of type [bool].\"\n    Similarly, the type of [andb], written [bool -> bool -> bool], can\n    be read, \"Given two inputs, both of type [bool], this function\n    produces an output of type [bool].\" *)\n\n(* ###################################################################### *)\n(** ** Numbers *)\n\n(** _Technical digression_: Coq provides a fairly sophisticated\n    _module system_, to aid in organizing large developments.  In this\n    course we won't need most of its features, but one is useful: If\n    we enclose a collection of declarations between [Module X] and\n    [End X] markers, then, in the remainder of the file after the\n    [End], these definitions will be referred to by names like [X.foo]\n    instead of just [foo].  Here, we use this feature to introduce the\n    definition of the type [nat] in an inner module so that it does\n    not shadow the one from the standard library. *)\n\nModule Playground1.\n\n(** The types we have defined so far are examples of \"enumerated\n    types\": their definitions explicitly enumerate a finite set of\n    elements.  A more interesting way of defining a type is to give a\n    collection of \"inductive rules\" describing its elements.  For\n    example, we can define the natural numbers as follows: *)\n\nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\n(** The clauses of this definition can be read: \n      - [O] is a natural number (note that this is the letter \"[O],\" not\n        the numeral \"[0]\").\n      - [S] is a \"constructor\" that takes a natural number and yields\n        another one -- that is, if [n] is a natural number, then [S n]\n        is too.\n\n    Let's look at this in a little more detail.  \n\n    Every inductively defined set ([day], [nat], [bool], etc.) is\n    actually a set of _expressions_.  The definition of [nat] says how\n    expressions in the set [nat] can be constructed:\n\n    - the expression [O] belongs to the set [nat]; \n    - if [n] is an expression belonging to the set [nat], then [S n]\n      is also an expression belonging to the set [nat]; and\n    - expressions formed in these two ways are the only ones belonging\n      to the set [nat].\n\n    The same rules apply for our definitions of [day] and [bool]. The\n    annotations we used for their constructors are analogous to the\n    one for the [O] constructor, and indicate that each of those\n    constructors doesn't take any arguments. *)\n\n(** These three conditions are the precise force of the\n    [Inductive] declaration.  They imply that the expression [O], the\n    expression [S O], the expression [S (S O)], the expression\n    [S (S (S O))], and so on all belong to the set [nat], while other\n    expressions like [true], [andb true false], and [S (S false)] do\n    not.\n\n    We can write simple functions that pattern match on natural\n    numbers just as we did above -- for example, 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 Playground1.\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n    | O => O\n    | S O => O\n    | S (S n') => n'\n  end.\n\n(** Because natural numbers are such a pervasive form of data,\n    Coq provides a tiny bit of built-in magic for parsing and printing\n    them: ordinary arabic numerals can be used as an alternative to\n    the \"unary\" notation defined by the constructors [S] and [O].  Coq\n    prints numbers in arabic form by default: *)\n\nCheck (S (S (S (S O)))).\nEval simpl in (minustwo 4).\n\n(** The constructor [S] has the type [nat -> nat], just like the\n    functions [minustwo] and [pred]: *)\n\nCheck S.\nCheck pred.\nCheck minustwo.\n\n(** These are all things that can be applied to a number to yield a\n    number.  However, there is a fundamental difference: functions\n    like [pred] and [minustwo] come with _computation rules_ -- e.g.,\n    the definition of [pred] says that [pred 2] can be simplified to\n    [1] -- while the definition of [S] has no such behavior attached.\n    Although it is like a function in the sense that it can be applied\n    to an argument, it does not _do_ anything at all! *)\n\n(** For most function definitions over numbers, pure pattern\n    matching is not enough: we also need recursion.  For example, to\n    check that a number [n] is even, we may need to recursively check\n    whether [n-2] is even.  To write such functions, we use the\n    keyword [Fixpoint]. *)\n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | O        => true\n  | S O      => false\n  | S (S n') => evenb n'\n  end.\n\n(** We can define [oddb] by a similar [Fixpoint] declaration, but here\n    is a simpler definition that will be a bit easier to work with: *)\n\nDefinition oddb (n:nat) : bool   :=   negb (evenb n).\n\nExample test_oddb1:    (oddb (S O)) = true.\nProof. reflexivity.  Qed.\nExample test_oddb2:    (oddb (S (S (S (S O))))) = false.\nProof. reflexivity.  Qed.\n\n(** Naturally, we can also define multi-argument functions by\n    recursion.  (Once again, we use a module to avoid polluting the\n    namespace.) *)\n\nModule Playground2.\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\n(** Adding three to two now gives us five, as we'd expect. *)\n\nEval simpl in (plus (S (S (S O))) (S (S O))).\n\n(** The simplification that Coq performs to reach this conclusion can\n    be visualized as follows: *)\n\n(*  [plus (S (S (S O))) (S (S O))]    \n==> [S (plus (S (S O)) (S (S O)))] by the second clause of the [match]\n==> [S (S (plus (S O) (S (S O))))] by the second clause of the [match]\n==> [S (S (S (plus O (S (S O)))))] by the second clause of the [match]\n==> [S (S (S (S (S O))))]          by the first clause of the [match]\n*)\n\n(** As a notational convenience, if two or more arguments have\n    the same type, they can be written together.  In the following\n    definition, [(n m : nat)] means just the same as if we had written\n    [(n : nat) (m : nat)]. *)\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\n\nExample test_mult1: (mult 3 3) = 9.\nProof. reflexivity.  Qed.\n\n(** You can match two expressions at once by putting a comma\n    between them: *)\n\nFixpoint minus (n m:nat) : nat :=\n  match n, m with\n  | O   , _    => O\n  | S _ , O    => n\n  | S n', S m' => minus n' m'\n  end.\n\n(** The _ in the first line is a _wildcard pattern_.  Writing _ in a\n    pattern is the same as writing some variable that doesn't get used\n    on the right-hand side.  This avoids the need to invent a bogus\n    variable name. *)\n\nEnd Playground2.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n    | O => S O\n    | S p => mult base (exp base p)\n  end.\n\n(** **** Exercise: 1 star (factorial) *)\n(** Recall the standard factorial function:\n<<\n    factorial(0)  =  1 \n    factorial(n)  =  n * factorial(n-1)     (if n>0)\n>>\n    Translate this into Coq. *)\n\nFixpoint factorial (n:nat) : nat := \n  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(** [] *)\n\n(** We can make numerical expressions a little easier to read and\n    write by introducing \"notations\" for addition, multiplication, and\n    subtraction. *)\n\nNotation \"x + y\" := (plus x y)  \n                       (at level 50, left associativity) \n                       : nat_scope.\nNotation \"x - y\" := (minus x y)  \n                       (at level 50, left associativity) \n                       : nat_scope.\nNotation \"x * y\" := (mult x y)  \n                       (at level 40, left associativity) \n                       : nat_scope.\n\nCheck ((0 + 1) + 1).\n\n(** (The [level], [associativity], and [nat_scope] annotations\n   control how these notations are treated by Coq's parser.  The\n   details are not important, but interested readers can refer to the\n   \"More on Notation\" subsection in the \"Optional Material\" section at\n   the end of this chapter.) *)\n\n(** Note that these do not change the definitions we've already\n    made: they are simply instructions to the Coq parser to accept [x\n    + y] in place of [plus x y] and, conversely, to the Coq\n    pretty-printer to display [plus x y] as [x + y]. *)\n\n(** When we say that Coq comes with nothing built-in, we really\n    mean it: even equality testing for numbers is a user-defined\n    operation! *)\n(** The [beq_nat] function tests [nat]ural numbers for [eq]uality,\n    yielding a [b]oolean.  Note the use of nested [match]es (we could\n    also have used a simultaneous match, as we did in [minus].)  *)\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\n(** Similarly, the [ble_nat] function tests [nat]ural numbers for\n    [l]ess-or-[e]qual, yielding a [b]oolean. *)\n\nFixpoint ble_nat (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => ble_nat n' m'\n      end\n  end.\n\nExample test_ble_nat1:             (ble_nat 2 2) = true.\nProof. 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\n(** **** Exercise: 2 stars (blt_nat) *)\n(** The [blt_nat] function tests [nat]ural numbers for [l]ess-[t]han,\n    yielding a [b]oolean.  Instead of making up a new [Fixpoint] for\n    this one, define it in terms of a previously defined function.  \n    \n    Note: If you have trouble with the [simpl] tactic, try using\n    [compute], which is like [simpl] on steroids.  However, there is a\n    simple, elegant solution for which [simpl] suffices. *)\n\nDefinition blt_nat (n m : nat) : bool :=\n  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(** [] *)\n\n(* ###################################################################### *)\n(** * Proof by Simplification *)\n\n(** Now that we've defined a few datatypes and functions, let's\n    turn to the question of how to state and prove properties of their\n    behavior.  Actually, in a sense, we've already started doing this:\n    each [Example] in the previous sections makes a precise claim\n    about the behavior of some function on some particular inputs.\n    The proofs of these claims were always the same: use [reflexivity] \n    to check that both sides of the [=] simplify to identical values. \n\n    (By the way, it will be useful later to know that\n    [reflexivity] actually does somewhat more than [simpl] -- for\n    example, it tries \"unfolding\" defined terms, replacing them with\n    their right-hand sides.  The reason for this difference is that,\n    when reflexivity succeeds, the whole goal is finished and we don't\n    need to look at whatever expanded expressions [reflexivity] has\n    found; by contrast, [simpl] is used in situations where we may\n    have to read and understand the new goal, so we would not want it\n    blindly expanding definitions.) \n\n    The same sort of \"proof by simplification\" can be used to prove\n    more interesting properties as well.  For example, the fact that\n    [0] is a \"neutral element\" for [+] on the left can be proved\n    just by observing that [0 + n] reduces to [n] no matter what\n    [n] is, a 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. reflexivity.  Qed.\n\n\n(** (_Note_: You may notice that the above statement looks\n    different in the original source file and the final html output. In Coq\n    files, we write the [forall] universal quantifier using the\n    \"_forall_\" reserved identifier. This gets printed as an\n    upside-down \"A\", the familiar symbol used in logic.)  *)\n\n(** The form of this theorem and proof are almost exactly the\n    same as the examples above; there are just a few differences.\n\n    First, we've used the keyword keyword [Theorem] instead of\n    [Example].  Indeed, the latter difference is purely a matter of\n    style; the keywords [Example] and [Theorem] (and a few others,\n    including [Lemma], [Fact], and [Remark]) mean exactly the same\n    thing to Coq.\n\n    Secondly, 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 \"OK, suppose [n] is some arbitrary 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 tell Coq how it should check the correctness of some\n    claim we are making.  We will see several more tactics in the rest\n    of this lecture, and yet more in future lectures. *)\n\n\n(** Step through these proofs in Coq and notice how the goal and\n    context change. *)\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n. \nProof.\n  intros n. reflexivity.  Qed.\n\nTheorem mult_0_l : forall n:nat, 0 * n = 0.\nProof.\n  intros n. reflexivity.  Qed.\n\n(** The [_l] suffix in the names of these theorems is\n    pronounced \"on the left.\" *)\n\n\n(* ###################################################################### *)\n(** * Proof by Rewriting *)\n\n(** Here is a slightly more interesting theorem: *)\n\nTheorem plus_id_example : forall n m:nat,\n  n = m -> \n  n + n = m + m.\n\n(** Instead of making a completely universal claim about all numbers\n    [n] and [m], this theorem talks about a more specialized property\n    that only holds when [n = m].  The arrow symbol is pronounced\n    \"implies.\"\n\n    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  intros n m.   (* move both quantifiers into the context *)\n  intros H.     (* move the hypothesis into the context *)\n  rewrite -> H. (* Rewrite the goal using the hypothesis *)\n  reflexivity.  Qed.\n\n(** The first line of the proof moves the universally quantified\n    variables [n] and [m] into the context.  The second moves the\n    hypothesis [n = m] into the context and gives it the (arbitrary)\n    name [H].  The third tells Coq to rewrite the current goal ([n + n\n    = m + m]) by replacing the left side of the equality hypothesis\n    [H] with the right side.\n\n    (The arrow symbol in the [rewrite] has nothing to do with\n    implication: it tells Coq to apply the rewrite from left to right.\n    To rewrite from right to left, you can use [rewrite <-].  Try\n    making this change in the above proof and see what difference it\n    makes in Coq's behavior.) *)\n\n(** **** Exercise: 1 star (plus_id_exercise) *)\n(** Remove \"[Admitted.]\" and fill in the proof. *)\n\nTheorem plus_id_exercise : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o.\n  intros H J.\n  rewrite -> H.\n  rewrite <- J.\n  reflexivity. Qed.\n(** [] *)\n\n(** As we've seen in earlier examples, the [Admitted] command\n    tells Coq that we want to skip trying to prove this theorem and\n    just accept it as a given.  This can be useful for developing\n    longer proofs, since we can state subsidiary facts that we believe\n    will be useful for making some larger argument, use [Admitted] to\n    accept them on faith for the moment, and continue thinking about\n    the larger argument until we are sure it makes sense; then we can\n    go back and fill in the proofs we skipped.  Be careful, though:\n    every time you say [Admitted] (or [admit]) you are leaving a door\n    open for total nonsense to enter Coq's nice, rigorous, formally\n    checked world! *)\n\n(** We can also use the [rewrite] tactic with a previously proved\n    theorem instead of a hypothesis from the context. *)\n\nTheorem mult_0_plus : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity.  Qed.\n\n(** **** Exercise: 2 stars (mult_S_1) *)\nTheorem mult_S_1 : forall n m : nat,\n  m = S n -> \n  m * (1 + n) = m * m.\nProof.\n  intros n m.\n  intros H.\n  rewrite -> plus_1_l.\n  rewrite <- H.\n  reflexivity. Qed.\n(** [] *)\n\n\n\n(* ###################################################################### *)\n(** * Proof by Case Analysis *) \n\n(** Of course, not everything can be proved by simple\n    calculation: In general, unknown, hypothetical values (arbitrary\n    numbers, booleans, lists, etc.) can block the calculation.  \n    For example, if we try to prove the following fact using the \n    [simpl] tactic as above, we get stuck. *)\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n. \n  simpl.  (* does nothing! *)\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    What we need is to be able to consider the possible forms of [n]\n    separately.  If [n] is [O], then we can calculate the final result\n    of [beq_nat (n + 1) 0] and check that it is, indeed, [false].\n    And if [n = S n'] for some [n'], then, although we don't know\n    exactly what number [n + 1] yields, we can calculate that, at\n    least, it will begin with one [S], and this is enough to calculate\n    that, again, [beq_nat (n + 1) 0] will yield [false].\n\n    The tactic that tells Coq to consider, separately, the cases where\n    [n = O] and where [n = S n'] is called [destruct]. *)\n\nTheorem plus_1_neq_0 : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n. destruct n as [| n'].\n    reflexivity.\n    reflexivity.  Qed.\n\n(** The [destruct] generates _two_ subgoals, which we must then\n    prove, separately, in order to get Coq to accept the theorem as\n    proved.  (No special command is needed for moving from one subgoal\n    to the other.  When the first subgoal has been proved, it just\n    disappears and we are left with the other \"in focus.\")  In this\n    proof, each of the subgoals is easily proved by a single use of\n    [reflexivity].\n\n    The annotation \"[as [| n']]\" is called an _intro pattern_.  It\n    tells Coq what variable names to introduce in each subgoal.  In\n    general, what goes between the square brackets is a _list_ of\n    lists of names, separated by [|].  Here, the first component is\n    empty, since the [O] constructor is nullary (it doesn't carry any\n    data).  The second component gives a single name, [n'], since [S]\n    is a unary constructor.\n\n    The [destruct] tactic can be used with any inductively defined\n    datatype.  For example, we use it here to prove that boolean\n    negation is involutive -- i.e., that negation is its own\n    inverse. *)\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b.\n    reflexivity.\n    reflexivity.  Qed.\n\n(** Note that the [destruct] here has no [as] clause because\n    none of the subcases of the [destruct] need to bind any variables,\n    so there is no need to specify any names.  (We could also have\n    written [as [|]], or [as []].)  In fact, we can omit the [as]\n    clause from _any_ [destruct] and Coq will fill in variable names\n    automatically.  Although this is convenient, it is arguably bad\n    style, since Coq often makes confusing choices of names when left\n    to its own devices. *)\n\n(** **** Exercise: 1 star (zero_nbeq_plus_1) *)\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros n. destruct n as [| n'].\n  reflexivity. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################################### *)\n(** * More Exercises *)\n\n(** **** Exercise: 2 stars (boolean functions) *)\n(** Use the tactics you have learned so far to prove the following \n    theorem about boolean functions. *)\n\nTheorem identity_fn_applied_twice : \n  forall (f : bool -> bool), \n  (forall (x : bool), f x = x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n  intros f. intros H. intros b.\n  rewrite -> H. rewrite -> H.\n  reflexivity. 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 = x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n  intros f. intros H. intros b.\n  rewrite -> H. rewrite -> H.\n  reflexivity. Qed.\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.) *)\n\nLemma andb_orb_dual :\n  forall (a : bool), (andb true a = orb false a).\nProof.\n  intros a. destruct a.\n  reflexivity. reflexivity. Qed.\n\nTheorem andb_eq_orb : \n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  intros a b.\n  destruct a.\n  rewrite -> andb_orb_dual. simpl.\n  intros H. rewrite -> H. reflexivity.\n  rewrite <- andb_orb_dual. simpl.\n  intros H. rewrite <- H. reflexivity.\n  Qed.\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] from class,\n    Inductive nat : Type :=\n      | O : nat\n      | S : nat -> nat.\n    says nothing about what [O] and [S] \"mean.\"  It just says \"[O] is\n    in the set called [nat], and if [n] is in the set then so is [S\n    n].\"  The interpretation of [O] as zero and [S] as successor/plus\n    one comes from the way that we _use_ [nat] values, by writing\n    functions to do things with them, proving things about them, and\n    so on.  Your definition of [bin] should be correspondingly simple;\n    it is the functions you will write next that will give it\n    mathematical meaning.)\n\n    (b) Next, write an increment function for binary numbers, and a\n        function to convert binary numbers to unary numbers.\n\n    (c) Write some unit tests for your increment and binary-to-unary\n        functions. Notice that incrementing a binary number and\n        then converting it to unary should yield the same result as first\n        converting it to unary and then incrementing. \n*)\n\n(* a) *)\n\nInductive bin : Type :=\n  | Z : bin\n  | D : bin -> bin\n  | N : bin -> bin.\n    \n(* b *)\n\nDefinition inc (n : bin) : bin :=\n  match n with\n    | Z => N Z\n    | D Z => Z\n    | D (D n') => N (D (D n'))\n    | D (N n') => N (D n')\n    | N Z => D (N Z)\n    | N (D n') => D (N n')\n    | N (N _) => Z (* shouldn't ever happen *)\n  end.\n\nFixpoint bin2nat (n : bin) : nat :=\n  match n with\n    | Z => O\n    | D n' => plus (bin2nat n') (bin2nat n')\n    | N n' => S (bin2nat n')\n  end.\n\nExample inc_equiv1 :\n  (S (S (S (S (S O))))) = bin2nat (inc (D (D (N Z)))).\nProof. reflexivity. Qed.\n\nExample inc_equiv2 :\n  (S (S (S (S (S (S O)))))) = bin2nat (inc (N (D (D (N Z))))).\nProof. reflexivity. Qed.\n\n  \n(** [] *)\n\n(* ###################################################################### *)\n(** * Optional Material *)\n\n(** ** More on Notation *)\n\nNotation \"x + y\" := (plus x y)  \n                       (at level 50, left associativity) \n                       : nat_scope.\nNotation \"x * y\" := (mult x y)  \n                       (at level 40, left associativity) \n                       : nat_scope.\n\n(** For each notation-symbol in Coq we can specify its _precedence level_\n    and its _associativity_. The precedence level n can be specified by the\n    keywords [at level n] and it is helpful to disambiguate\n    expressions containing different symbols. The associativity is helpful\n    to disambiguate expressions containing more occurrences of the same \n    symbol. For example, the parameters specified above for [+] and [*]\n    say that the expression [1+2*3*4] is a shorthand for the expression\n    [(1+((2*3)*4))]. Coq uses precedence levels from 0 to 100, and \n    _left_, _right_, or _no_ associativity.\n\n    Each notation-symbol in Coq is also active in a _notation scope_.  \n    Coq tries to guess what scope you mean, so when you write [S(O*O)] \n    it guesses [nat_scope], but when you write the cartesian\n    product (tuple) type [bool*bool] it guesses [type_scope].\n    Occasionally you have to help it out with percent-notation by\n    writing [(x*y)%nat], and sometimes in Coq's feedback to you it\n    will use [%nat] to indicate what scope a notation is in.\n\n    Notation scopes also apply to numeral notation (3,4,5, etc.), so you\n    may sometimes see [0%nat] which means [O], or [0%Z] which means the\n    Integer zero.\n*)\n\n(** ** [Fixpoint]s and Structural Recursion *)\n\nFixpoint plus' (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus' n' m)\n  end.\n\n(** When Coq checks this definition, it notes that [plus'] is\n    \"decreasing on 1st argument.\"  What this means is that we are\n    performing a _structural recursion_ over the argument [n] -- i.e.,\n    that we make recursive calls only on strictly smaller values of\n    [n].  This implies that all calls to [plus'] will eventually\n    terminate.  Coq demands that some argument of _every_ [Fixpoint]\n    definition is \"decreasing\".\n    \n    This requirement is a fundamental feature of Coq's design: In\n    particular, it guarantees that every function that can be defined\n    in Coq will terminate on all inputs.  However, because Coq's\n    \"decreasing analysis\" is not very sophisticated, it is sometimes\n    necessary to write functions in slightly unnatural ways. *)\n\n(** **** Exercise: 2 stars, optional (decreasing) *)\n(** To get a concrete sense of this, find a way to write a sensible\n    [Fixpoint] definition (of a simple function on numbers, say) that\n    _does_ terminate on all inputs, but that Coq will _not_ accept\n    because of this restriction. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n\n", "meta": {"author": "mkmks", "repo": "sf", "sha": "fec87d3b43222f2c0e05ecc929274c4ecf6b3a38", "save_path": "github-repos/coq/mkmks-sf", "path": "github-repos/coq/mkmks-sf/sf-fec87d3b43222f2c0e05ecc929274c4ecf6b3a38/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.817574471748733, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.6777192135079455}}
{"text": "(*Konrad Paziewski*)\n(*kp306410@students.mimuw.edu.pl*)\n(*Programowanie z typami zależnymi i dowodzenie twierdzeń 2015*)\n(*Zadanie 1*)\nRequire Import Utf8.\nRequire Import Arith.\nRequire Import CpdtTactics.\n\n(* a *)\nDefinition var := nat.\n\n(* b *)\nInductive exp : Set :=\n  | Var : var -> exp\n  | Const : nat -> exp\n  | Add : exp -> exp -> exp\n  | MakePair : exp -> exp -> exp\n  | Fst : exp -> exp\n  | Snd : exp -> exp.\n\n(* c *)\nInductive cmd : Set :=\n  | Return : exp -> cmd\n  | Assignment : var -> exp -> cmd -> cmd.\n\n(* d *)\nInductive val : Set :=\n  | Nat : nat -> val\n  | Pair : val -> val -> val.\n\n(* e *)\nDefinition map (T:Type) := var -> T.\nDefinition varAssignment := map val.\n\nDefinition insert T (v:var) (t:T) (m : map T) : map T := \n  fun vr => if eq_nat_dec v vr then t else m vr.\n\n\n(* f *)\nFixpoint eval (e : exp) (va : varAssignment) (r:val) : Prop := \n  match e, r with\n  | Var v, _ => eq (va v) r\n  | Const n, Nat rn => eq_nat n rn\n  | Add el er, Nat rn =>  ∃ vl vr : nat, (eq_nat (plus vl vr) rn /\\ eval el va (Nat vl) /\\ eval er va (Nat vr))  \n  | MakePair el er, Pair vl vr => eval el va vl /\\ eval er va vr\n  | Fst e, _ => ∃ vr:val, eval e va (Pair r vr)\n  | Snd e, _ => ∃ vl:val, eval e va (Pair vl r)\n  | _, _ => False\nend.\n\n(* g *)\nFixpoint run (c:cmd) (va : varAssignment) (r:val) : Prop :=\n  match c with\n  | Assignment v e next => ∃ ve:val, eval e va ve /\\ run next (insert val v ve va) r\n  | Return e => eval e va r\nend.\n\n(* h *)\nInductive type : Set :=\n  | NatType : type\n  | PairType : type -> type -> type.\n\nDefinition varTypings := map type.\n\nFixpoint valType (v:val) : type :=\n  match v with\n  | Nat _ => NatType\n  | Pair l r => PairType (valType l) (valType r)\nend.\n\nFixpoint expType (e:exp) (vt:varTypings) (r:type) : Prop :=\n  match e, r with\n  | Var v, _ => eq (vt v) r\n  | Const _, NatType => True\n  | Add el er, NatType =>  expType el vt NatType /\\ expType er vt NatType\n  | MakePair el er, PairType tl tr => expType el vt tl /\\ expType er vt tr\n  | Fst e, _ => ∃ tr:type, expType e vt (PairType r tr)\n  | Snd e, _ => ∃ tl:type, expType e vt (PairType tl r)\n  | _, _ => False\nend.\n\nFixpoint cmdType (c:cmd) (vt : varTypings) (r:type) : Prop :=\n  match c with\n  | Assignment v e next => ∃ et:type, expType e vt et /\\ cmdType next (insert type v et vt) r\n  | Return e => expType e vt r\nend.\n\n(* j *)\nDefinition varsType (va : varAssignment) (vt : varTypings) : Prop :=\n  ∀ v : var, eq (valType (va v)) (vt v).\n\n(* k *)\nLemma expCorrect: ∀ va: varAssignment, ∀ vt: varTypings, varsType va vt -> \n         ∀ e : exp, ∀ t: type, (expType e vt t -> ∃ v, eval e va v /\\ eq (valType v) t).\ninduction e; crush.\n(* Var _ *)\nexists (va v); crush.\n\n(*Const n*)\nexists (Nat n); destruct t; crush.\n\n(*Add _ _ *)\ndestruct t; crush.\nassert (N1: ∃ v : val, eval e2 va v ∧ valType v = NatType).\ncrush.\ndestruct N1.\ndestruct x; crush.\n\nassert (N2: ∃ v : val, eval e1 va v ∧ valType v = NatType).\ncrush.\ndestruct N2.\ndestruct x; crush.\n\nexists (Nat (n0 + n)).\ncrush.\nexists n0.\nexists n.\ncrush.\n\n(*MakePair _ _*)\ndestruct t; crush.\nassert (N1: ∃ v : val, eval e2 va v ∧ valType v = t2).\ncrush.\ndestruct N1.\n\nassert (N2: ∃ v : val, eval e1 va v ∧ valType v = t1).\ncrush.\ndestruct N2.\n\nexists (Pair x0 x).\ncrush.\n\n(*Left*)\nassert (N: ∃ v : val, eval e va v ∧ valType v = (PairType t x)).\ncrush.\ndestruct N; crush.\ndestruct x0; crush.\nexists x0_1.\ncrush.\nexists x0_2.\ncrush.\n\n(*Right*)\nassert (N: ∃ v : val, eval e va v ∧ valType v = (PairType x t)).\ncrush.\ndestruct N; crush.\ndestruct x0; crush.\nexists x0_2.\ncrush.\nexists x0_1.\ncrush.\nQed.\n\n(* l *)\nLemma insertCorrect : ∀ va: varAssignment, ∀ vt: varTypings, varsType va vt ->\n   ∀ v : val, ∀ x : var, varsType (insert val x v va) (insert type x (valType v) vt). \ncrush.\nunfold varsType.\ncrush.\nunfold insert.\nsimpl.\ndestruct (eq_nat_dec); crush.\nQed.\n\nLemma cmdCorrect' : ∀ c: cmd, ∀ va: varAssignment, ∀ vt: varTypings, varsType va vt -> \n   ∀ t: type, (cmdType c vt t -> ∃ v, run c va v /\\ eq (valType v) t).\ninduction c; crush.\n(* Return *)\napply (expCorrect va vt); crush.\n(* Assignment *)\nassert (N : ∃ ve, eval e va ve /\\ eq (valType ve) x).\napply (expCorrect va vt); crush.\ndestruct N.\nassert (M: varsType (insert val v x0 va) (insert type v (valType x0) vt)).\napply (insertCorrect va vt); crush.\nassert (P : ∃ v0 : val, run c (insert val v x0 va) v0 ∧ valType v0 = t).\napply (IHc (insert val v x0 va) (insert type v (valType x0) vt)); crush.\ndestruct P.\nexists x1.\ncrush.\nexists x0.\ncrush.\nQed.\n\nLemma cmdCorrect: ∀ va: varAssignment, ∀ vt: varTypings, varsType va vt -> \n   ∀ c: cmd, ∀ t: type, (cmdType c vt t -> ∃ v, run c va v /\\ eq (valType v) t).\ncrush.\napply (cmdCorrect' c va vt); crush.\nQed.", "meta": {"author": "konradxyz", "repo": "coq", "sha": "d0e0ffc0026fab96166ecc9758807c1e2cea8ada", "save_path": "github-repos/coq/konradxyz-coq", "path": "github-repos/coq/konradxyz-coq/coq-d0e0ffc0026fab96166ecc9758807c1e2cea8ada/zal1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388125473628, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.677719208095873}}
{"text": "Require Import CoRN.model.totalorder.QposMinMax.\nRequire Import\n Unicode.Utf8\n Setoid Arith List Program Permutation metric2.Classified\n CSetoids CPoly_ApZero CPoly_Degree\n CRArith CRArith_alg Qmetric Qring CReals Ranges\n stdlib_omissions.Pair stdlib_omissions.Q\n list_separates SetoidPermutation CRings.\nRequire MathClasses.implementations.ne_list.\nImport CRing_Homomorphisms.coercions.\nImport ne_list.notations ne_list.coercions.\n\nSet Automatic Introduction.\n\nCoercion Vector.to_list: Vector.t >-> list.\n\nLocal Open Scope CR_scope.\n\nLocal Notation Σ := cm_Sum.\nLocal Notation Π := cr_Product.\n\nSection continuous_vector_operations.\n\n  Context `{MetricSpaceClass X} (n: nat).\n\n  Definition uncurry_Vector_cons: X * Vector.t X n → Vector.t X (S n)\n    := λ p, Vector.cons _ (fst p) _ (snd p).\n\n  Global Instance Vector_cons_mu: UniformlyContinuous_mu uncurry_Vector_cons := { uc_mu := Qpos2QposInf }.\n\nEnd continuous_vector_operations.\n\n\nSection contents.\n\n  Notation QPoint := (Q * CR)%type.\n  Notation CRPoint := (CR * CR)%type.\n\n  (** Definition of the Newton polynomial: *)\n\n  Fixpoint divdiff_l (a: QPoint) (xs: list QPoint) {struct xs} : CR :=\n    match xs with\n    | nil => snd a\n    | cons b l => (divdiff_l a l - divdiff_l b l) * ' / (fst a - fst b)\n    end.\n\n  Definition divdiff (l: ne_list QPoint): CR := divdiff_l (ne_list.head l) (ne_list.tail l).\n\n  Lemma divdiff_e (l: ne_list QPoint):\n    divdiff l = \n      match l with\n      | ne_list.one a => snd a\n      | a ::: ne_list.one b => (snd a - snd b) * ' / (fst a - fst b)\n      | a ::: b ::: l =>\n         (divdiff (ne_list.cons a l) - divdiff (ne_list.cons b l)) * ' / (fst a - fst b)\n      end.\n  Proof. induction l as [|?[|]]; auto. Qed.\n\n  Definition divdiff_ind {T} (P: ne_list T → Prop)\n    (Pone: ∀ p, P (ne_list.one p))\n    (Ptwo: ∀ p q, P (p ::: ne_list.one q))\n    (Pmore: ∀ a b l, P (a ::: l) → P (b ::: l) → P (a ::: b ::: l)):\n    forall l, P l.\n  Proof with simpl; auto.\n   cut (forall t h, P (ne_list.from_list h t)).\n    intros. rewrite (ne_list.decomp_eq l)...\n   induction t...\n   destruct t; simpl...\n   intros. apply Pmore; apply IHt.\n  Qed.\n\n  Opaque CR.\n\n  Lemma divdiff_sum (xs: ne_list (Q * (CR * CR))):\n    divdiff (ne_list.map (second fst) xs) + divdiff (ne_list.map (second snd) xs) ==\n    divdiff (ne_list.map (second (λ x: CR * CR, fst x + snd x)) xs).\n  Proof with auto.\n   induction xs using divdiff_ind; do 3 rewrite divdiff_e; simpl in *.\n     reflexivity.\n    generalize (' (/ (fst p - fst q))). intro. simpl. ring.\n   generalize (' (/ (fst a - fst b))).  intro. simpl.\n   rewrite <- IHxs, <- IHxs0.\n   simpl. ring.\n  Qed.\n\n  Lemma divdiff_scalar_mult (c: CR) (xs: ne_list QPoint):\n    c * divdiff xs == divdiff (ne_list.map (second (CRmult c)) xs).\n  Proof with auto.\n   induction xs using divdiff_ind; simpl.\n     reflexivity.\n    change ((c * ((snd p - snd q) * ' (/ (fst p - fst q)))) == (c * snd p - c * snd q) * ' (/ (fst p - fst q))).\n    set (/ (fst p - fst q)). ring.\n   rewrite divdiff_e.\n   set (' (/ (fst a - fst b))).\n   transitivity ((c * divdiff (a ::: xs) - c * divdiff (b ::: xs)) * m). ring.\n   rewrite IHxs, IHxs0.\n   symmetry. rewrite divdiff_e.\n   simpl. fold m. ring.\n  Qed.\n\n  Lemma divdiff_product (xs: ne_list (Q * (CR * CR))):\n      divdiff (ne_list.map (second (λ x: CR * CR, fst x * snd x)) xs) ==\n      @cm_Sum CRasCMonoid (map (λ p, divdiff (ne_list.map (second fst) (fst p)) * divdiff (ne_list.map (second snd) (snd p)))\n        (zip (ne_list.tails xs) (ne_list.inits xs))).\n  Proof with simpl in *; auto.\n   intros.\n   induction xs using divdiff_ind.\n     unfold divdiff... ring.\n    unfold divdiff... set (' (/ (fst p - fst q))). ring.\n   rewrite divdiff_e.\n   set (λ p : ne_list (Q and CR and CR) and ne_list (Q and CR and CR),\n       divdiff (ne_list.map (second fst) (fst p)) * divdiff (ne_list.map (second snd) (snd p))) as s in *.\n   simpl in *.\n   rewrite IHxs, IHxs0.\n   repeat rewrite ne_list.list_map.\n   repeat rewrite zip_map_snd.\n   repeat rewrite map_map_comp.\n   generalize (zip (ne_list.tails xs) (ne_list.inits xs)). intro.\n   set (s0 := ' (/ (fst a - fst b))).\n   transitivity ((s (a ::: xs, ne_list.one a) - s (b ::: xs, ne_list.one b)) * s0 +\n     (@Σ CRasCMonoid (map (s ∘ second (ne_list.cons a))%prg l) - @Σ CRasCMonoid (map (s ∘ second (ne_list.cons b))%prg l)) * s0)...\n    ring.\n   setoid_replace ((s (a ::: xs, ne_list.one a) - s (b ::: xs, ne_list.one b)) * s0)\n     with (s (a ::: b ::: xs, ne_list.one a) + (s (b ::: xs, a ::: ne_list.one b))).\n    setoid_replace ((@Σ CRasCMonoid (map (s ∘ second (ne_list.cons a))%prg l) - @Σ CRasCMonoid (map (s ∘ second (ne_list.cons b))%prg l)) * s0)\n      with (@Σ CRasCMonoid (map (s ∘ second (ne_list.cons a) ∘ second (ne_list.cons b))%prg l))...\n     ring.\n    induction l... ring.\n    rewrite <- IHl.\n    unfold Basics.compose at 1 3 5 6...\n    subst s...\n    rewrite (divdiff_e (second snd a ::: second snd b ::: ne_list.map (second snd) (snd a0)))...\n    fold s0. ring.\n   subst s...\n   unfold divdiff at 2 4 6...\n   rewrite (divdiff_e (second fst a ::: second fst b ::: ne_list.map (second fst) xs)).\n   generalize (divdiff (second fst a ::: ne_list.map (second fst) xs)). intro.\n   generalize (divdiff (second fst b ::: ne_list.map (second fst) xs)). intro.\n   rewrite divdiff_e...\n   fold s0. ring.\n  Qed.\n\n  Lemma divdiff_chain (f : Q ->CR) (x y u v: Q): \n   let l:=(x,u):::ne_list.one (y,v) in\n   let sndl:=(ne_list.map snd l) in\n   ¬(u-v == 0)%Q ->\n   (divdiff (ne_list.map (second f ) l)) == \n   (divdiff (ne_zip sndl (ne_list.map f sndl))) * (divdiff (ne_list.map (second inject_Q_CR) l)).\n  Proof with auto;simpl.\n  intros. do 3 rewrite divdiff_e...\n  (* want a combination of ring and a rewrite database for inject_Q ? *)  \n  set (s:=f u - f v). set (t:='(/ (x - y))). \n  rewrite CRminus_Qminus. set (a:=(u-v)%Q).\n  transitivity (s * ' (/ (a) * (a))%Q * t).\n  rewrite <- (Qmult_comm a).\n  rewrite Qmult_inv_r... ring.\n  rewrite <- (@CRmult_Qmult (/a) a). set (' (/a)). ring.\n  Qed.\n\n  Let an (xs: ne_list QPoint): cpoly CRasCRing :=\n    (polyconst CRasCRing (divdiff xs))\n      [*] Π (map (fun x => @cpoly_linear_fun' CRasCRing (' (- fst x)%Q) [1]) (tl xs)).\n\n  Section with_qpoints.\n\n    Variable qpoints: ne_list QPoint.\n\n    Definition N: cpoly CRasCRing := Σ (map an (ne_list.tails qpoints)).\n\n    (** Degree: *)\n\n    Let an_degree (xs: ne_list QPoint): degree_le (length (tl xs)) (an xs).\n    Proof with auto.\n     intros.\n     unfold an.\n     replace (length (tl xs)) with (0 + length (tl xs))%nat by reflexivity.\n     apply degree_le_mult.\n      apply degree_le_c_.\n      replace (length (tl xs))\n        with (length (map (fun x => @cpoly_linear_fun' CRasCRing (' (-fst x)%Q) [1]) (tl xs)) * 1)%nat.\n      apply degree_le_Product.\n      intros.\n      apply in_map_iff in H.\n      destruct H.\n      destruct H.\n      rewrite <- H.\n      apply degree_le_cpoly_linear_inv.\n      apply (degree_le_c_ CRasCRing [1]).\n     ring_simplify.\n     rewrite map_length.\n     destruct xs; reflexivity.\n    Qed.\n\n    Lemma degree: degree_le (length (tl qpoints)) N.\n    Proof with auto.\n     intros.\n     unfold N.\n     apply degree_le_Sum.\n     intros.\n     apply in_map_iff in H.\n     destruct H as [x [H H0]].\n     subst p.\n     apply degree_le_mon with (length (tl x)).\n      pose proof (ne_list.tails_are_shorter qpoints x H0).\n      destruct x, qpoints; auto with arith.\n     apply an_degree.\n    Qed.\n\n    (** Applying this polynomial gives what you'd expect: *)\n\n    Definition an_applied (x: Q) (txs: ne_list QPoint) : CR\n      := divdiff txs * ' @cr_Product Q_as_CRing (map (Qminus x ∘ fst)%prg (tail txs)).\n\n    Definition applied (x: Q) := @Σ CRasCMonoid (map (an_applied x) (ne_list.tails qpoints)).\n\n    Lemma apply x: (N ! ' x) [=] applied x.\n    Proof.\n     unfold N, applied, an, an_applied.\n     rewrite cm_Sum_apply, map_map.\n     apply (@cm_Sum_eq CRasCMonoid).\n     intro.\n     autorewrite with apply.\n     apply mult_wd. reflexivity.\n     rewrite inject_Q_product.\n     rewrite cr_Product_apply.\n     do 2 rewrite map_map.\n     apply (@cm_Sum_eq (Build_multCMonoid CRasCRing)).\n     intro.\n     unfold Basics.compose.\n     rewrite <- CRminus_Qminus.\n     change ((' (- fst x1)%Q + ' x * (1 + ' x * 0)) == (' x - ' fst x1)).\n     ring.\n    Qed.\n\n  End with_qpoints.\n\n  (** Next, some lemmas leading up to the proof that the polynomial does\n   indeed interpolate the given points: *)\n\n  Let applied_cons (y: Q) (x: QPoint) (xs: ne_list QPoint):\n    applied (x ::: xs) y = an_applied y (x ::: xs) + applied xs y.\n  Proof. reflexivity. Qed.\n\n  Let N_cons (x: QPoint) (xs: ne_list QPoint):\n    N (x ::: xs) = an (x ::: xs) [+] N xs.\n  Proof. reflexivity. Qed.\n\n  Lemma an_applied_0 (t: QPoint) (x: Q) (xs: ne_list QPoint):\n    In x (map fst xs) -> an_applied x (t ::: xs) == 0.\n  Proof with auto.\n   intros. unfold an_applied.\n   simpl @tl.\n   rewrite (@cr_Product_0 Q_as_CRing (x - x))%Q.\n     change (divdiff (t ::: xs) * 0 == 0).\n     apply (cring_mult_zero CRasCRing).\n    change (x - x == 0)%Q. ring.\n   unfold Basics.compose.\n   rewrite <- map_map.\n   apply in_map...\n  Qed.\n\n  Lemma applied_head (x y: QPoint) (xs: ne_list QPoint):\n    Qred (fst x) <> Qred (fst y) ->\n    applied (x ::: y ::: xs) (fst x) [=] applied (x ::: xs) (fst x).\n  Proof with auto.\n   intro E.\n   repeat rewrite applied_cons.\n   cut (an_applied (fst x) (x ::: y ::: xs) + (an_applied (fst x) (y ::: xs)) == an_applied (fst x) (x ::: xs)).\n    intro H. rewrite <- H.\n    change (an_applied (fst x) (x ::: y ::: xs) + (an_applied (fst x) (y ::: xs) + applied xs (fst x)) ==\n      an_applied (fst x) (x ::: y ::: xs)+an_applied (fst x) (y ::: xs) + applied xs (fst x))%CR.\n    ring.\n   change ((divdiff_l x xs - divdiff_l y xs) * ' (/ (fst x - fst y)) * \n     ' (Qminus (fst x) (fst y) * @cr_Product Q_as_CRing (map (Qminus (fst x) ∘ fst)%prg xs))%Q+\n     divdiff_l y xs * ' @cr_Product Q_as_CRing (map (Qminus (fst x) ∘ fst)%prg xs) ==\n     divdiff_l x xs * ' @cr_Product Q_as_CRing (map (Qminus (fst x) ∘ fst)%prg xs)).\n   generalize (@cr_Product Q_as_CRing (map (Qminus (fst x) ∘ fst)%prg xs)).\n   intros.\n   rewrite CRmult_assoc.\n   change ((((divdiff_l x xs - divdiff_l y xs)*(' (/ (fst x - fst y))%Q*' ((fst x - fst y)*s)%Q) + divdiff_l y xs * ' s)) == divdiff_l x xs*' s)%CR.\n   rewrite CRmult_Qmult.\n   setoid_replace ((/ (fst x - fst y) * ((fst x - fst y) * s)))%Q with s.\n    ring.\n   rewrite Qmult_assoc.\n   change ((/ (fst x - fst y) * (fst x - fst y) * s)==s)%Q.\n   field. intro.\n   apply -> Q.Qminus_eq in H.\n   apply E.\n   apply Qred_complete...\n  Qed.\n\n  Section again_with_qpoints.\n\n    Variables (qpoints: ne_list QPoint) (H: QNoDup (map fst qpoints)).\n\n    Let crpoints := ne_list.map (first inject_Q_CR) qpoints.\n\n    Lemma interpolates: @interpolates CRasCField crpoints (N qpoints).\n    Proof with simpl; auto.\n     unfold interpolates.\n     unfold crpoints.\n     rewrite ne_list.list_map.\n     intros xy H0.\n     destruct (proj1 (in_map_iff _ _ _) H0) as [[x y] [? B]]. clear H0.\n     subst xy.\n     unfold first. simpl @fst. simpl @snd.\n     rewrite apply.\n     revert x y B.\n     induction qpoints using ne_list.two_level_rect.\n       intros u v [? | []]. subst x. change (v * 1 + 0 == v)%CR. ring.\n      intros.\n      rewrite applied_cons.\n      change (((snd x - snd y) * ' (/ (fst x - fst y)) * ' ((x0 - fst y) * 1)%Q + (snd y * 1 + 0)) == y0)%CR.\n      rewrite Qmult_1_r.\n      destruct B.\n       subst.\n       rewrite CRmult_assoc.\n       change ((y0 - snd y)*(' (/ (x0 - fst y))* '(x0 - fst y)%Q) + (snd y * 1 + 0)==y0)%CR.\n       rewrite CRmult_Qmult.\n       setoid_replace  (/ (x0 - fst y) * (x0 - fst y))%Q with 1%Q. ring.\n       simpl. field. intro.\n       apply -> Q.Qminus_eq in H0.\n       inversion_clear H.\n       apply H1.\n       simpl.\n       left.\n       apply Q.Proper_instance_0. (* For some reason using [rewrite] here is crazy slow. Todo: Investigate. *)\n       symmetry.\n       assumption.\n      destruct H0.\n       subst.\n       simpl @fst. simpl @snd.\n       rewrite (proj2 (Q.Qminus_eq x0 x0)).\n        rewrite (cring_mult_zero CRasCRing).\n        change (0 + (y0 * 1 + 0) == y0)%CR. ring.\n       reflexivity.\n      exfalso...\n     clear qpoints.\n     simpl @In.\n     intros x0 y0 [H1 | H1].\n      subst.\n      rewrite applied_head.\n       apply H0...\n       inversion_clear H.\n       unfold QNoDup.  simpl.\n       apply NoDup_cons. intuition.\n       inversion_clear H2. intuition.\n      intro. inversion_clear H. apply H2. simpl in H1. rewrite H1...\n     rewrite applied_cons.\n     assert (QNoDup (map fst (y :: l))).\n      inversion_clear H...\n     rewrite (H0 y H2 x0 y0).\n      rewrite an_applied_0...\n       change (0 + y0 == y0). ring.\n      destruct H1. subst...\n      right...\n      apply (in_map fst l (x0, y0))...\n     destruct H1...\n    Qed. (* Todo: Clean up more. *)\n\n    Lemma interpolates_economically: @interpolates_economically CRasCField crpoints (N qpoints).\n    Proof.\n     split. apply interpolates.\n     unfold crpoints.\n     rewrite ne_list.list_map, tl_map, map_length.\n     apply degree.\n    Qed.\n\n    (** Uniqueness of interpolating polynomials of minimal degree now lets us\n     prove some things about any such polynomial based on what we know about\n     this Newton polynomial: *)\n\n    Lemma coincides_with_polynomial_interpolators (p: cpoly CRasCRing):\n      @CPoly_ApZero.interpolates_economically CRasCField crpoints p →\n      N qpoints [=] p.\n    Proof with auto.\n     apply (@interpolation_unique CRasCField crpoints).\n      unfold crpoints. rewrite ne_list.list_map, map_fst_map_first.\n      apply (CNoDup_map _ inject_Q_CR).\n      apply CNoDup_weak with Qap...\n       intros. apply Qap_CRap...\n      apply QNoDup_CNoDup_Qap...\n     apply interpolates_economically.\n    Qed.\n\n    Lemma N_leading_coefficient: nth_coeff (length (tl qpoints)) (N qpoints) == divdiff qpoints.\n    Proof with try ring.\n     destruct qpoints.\n      change (divdiff (ne_list.one p) * 1 + 0 == divdiff (ne_list.one p))...\n     simpl @length.\n     rewrite N_cons.\n     rewrite nth_coeff_plus.\n     rewrite (degree l (length l)).\n      2: destruct l; simpl; auto.\n     change (nth_coeff (length l) (an (p ::: l))+0==divdiff (p ::: l)). (* to change [+] into + *)\n     ring_simplify.\n     unfold an.\n     rewrite nth_coeff_c_mult_p.\n     simpl tl.\n     set (f := fun x: Q and CR => @cpoly_linear_fun' CRasCRing (' (- fst x)%Q) [1]).\n     replace (length l) with (length (map f l) * 1)%nat.\n      rewrite lead_coeff_product_1.\n       change (divdiff (p ::: l)*1 == divdiff (p ::: l))... (* to change [*] into * *)\n      intros q. rewrite in_map_iff. intros [x [[] B]].\n      split. reflexivity.\n      apply degree_le_cpoly_linear_inv.\n      apply (degree_le_c_ CRasCRing [1]).\n     rewrite map_length...\n    Qed.\n\n    (** So now we know that the divided difference is the leading coefficient of /any/\n    economically interpolating polynomial: *)\n\n    Lemma leading_coefficient (p: cpoly CRasCRing):\n      @CPoly_ApZero.interpolates_economically CRasCField crpoints p →\n      nth_coeff (length (tl qpoints)) p == divdiff qpoints.\n    Proof with auto.\n     intros.\n     rewrite <- coincides_with_polynomial_interpolators...\n     apply N_leading_coefficient.\n    Qed.\n\n  End again_with_qpoints.\n\nFixpoint ne_list_zip {X Y} (xs: ne_list X) (ys: ne_list Y): ne_list (X * Y) :=\n  match xs, ys with\n  | ne_list.cons x xs', ne_list.cons y ys' => ne_list.cons (x, y) (ne_list_zip xs' ys')\n  | _, _ => ne_list.one (ne_list.head xs, ne_list.head ys)\n  end.\n\nDefinition Q01 := sig (λ x: Q, 0 <= x <= 1).\nDefinition Range (T: Type) := prod T T.\nClass Container (Elem C: Type) := In: C → Elem → Prop.\nHint Unfold In.\nNotation \"x ∈ y\" := (In y x) (at level 40).\nNotation \"(∈ y )\" := (In y) (at level 40).\nNotation \"x ∉ y\" := (In y x → False) (at level 40).\nInstance in_QRange: Container Q (Range Q) := λ r x, fst r <= x <= snd r. \nArguments proj1_sig {A P}.\nProgram Instance in_sig_QRange (P: Q → Prop): Container (sig P) (Range (sig P)) := λ r x, fst r <= x <= snd r. \nDefinition B01: Ball Q Qpos := (1#2, (1#2)%Qpos).\n  Section divdiff_as_repeated_integral.\n\n    Context\n      (n: nat) (points: Vector.t Q (S n))\n      (lo hi: Q).\n\n    Definition lohi (q: Q): Prop := lo <= q <= hi.\n    Definition Qbp: Type := sig lohi.\n\n(*    Context \n      (points_lohi: Vector.Forall lohi points)\n      (upper: CR)\n      (nth_deriv: Q → CR (*sig (λ x: CR, x <= upper)*))\n        `{!UniformlyContinuous_mu nth_deriv}\n        `{!UniformlyContinuous nth_deriv}\n          (* Todo: This should be replaced with some \"n times differentiable\" requirement on a subject function. *)\n      (integrate: Range Q01 * UCFunction Q01 CR → CR)\n        `{!UniformlyContinuous_mu integrate}\n        `{!UniformlyContinuous integrate}.\n          (* Todo: The integration function should not be a parameter. We should just use SimpleIntegration's implementation. *)\n*)\n(*\nRequire Import CRabs.\nImport QnonNeg.notations.\nDefinition ZeroRangeToBall (q: QnonNeg.T): Ball Q QnonNeg.T := (0, ((1#2) * q)%Qnn).\n    Variable integrate_on_01:\n      ∀ (u: QnonNeg.T) (f: sig (contains (ZeroRangeToBall u)) → CR) c,\n        (∀ x, CRabs (f x) <= c) →\n        CRabs (integrate _ f) <= c.\n*)\n    Opaque Qmult Qplus Qminus.\n       (* Without these, instance resolution gets a little too enthusiastic and breaks these operations open when\n       looking for PointFree instances below. It's actually kinda neat that it can put these in PointFree form though. *)\n\n\n    Notation SomeWeights n := ((*sig (λ ts:*) Vector.t Q01 n (*, cm_Sum (map proj1_sig ts) <= 1)%Q*)).\n    Notation Weights := ((*sig (λ ts:*) Vector.t Q01 (S n) (*, cm_Sum (map proj1_sig ts) == 1)%Q*)).\n\n    (** apply_weights: *)\n\n    Obligation Tactic := idtac.\n\n    (** \"inner\", the function of n weights: *)\n    (* Next up is \"reduce\", which *)\n  End divdiff_as_repeated_integral.\n\nEnd contents.\n", "meta": {"author": "coq-community", "repo": "corn", "sha": "cfbf6b297643935f0fe7e22d2b14b462bf7e3095", "save_path": "github-repos/coq/coq-community-corn", "path": "github-repos/coq/coq-community-corn/corn-cfbf6b297643935f0fe7e22d2b14b462bf7e3095/algebra/CPoly_Newton.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6776836238850112}}
{"text": "(** * AbstractWalk.v: An example of probabilistic termination\n      Related to Vacid0 example of Maze construction\n*)\n\n(* begin hide *)\nAdd Rec LoadPath \"../src\" as ALEA.\nRequire Export DistrTactic.\nSet Implicit Arguments.\nOpen Local Scope U_scope.\nOpen Local Scope O_scope.\n(* end hide *)\n\nSection Walk.\n\n(** ** Abstraction of maze scheme\n\n  If the process is not terminated then a random value is chosen in\n  Data, under a certain condition on input and the data, the process\n  is iterated on the same input, otherwise the input is changed.  The\n  change in the input decreases it strictly and the probability to stay \n  with the same input is bounded by k<1, then the process terminates.  \n\n<< let rec iter u =\n  if finished u then output u \n  else let d = dData in \n       if cond u d then iter u else iter (step d u) \n>> \n*)\n\nVariable Data Input Result: Type.\n\nVariable dData : distr Data.\n\n(** Termination is taken using a measure on integer but could be generalized\n    to an arbitrary well-founded ordering *)\n\nVariable size : Input -> nat.\nVariable finished : Input -> bool.\nAxiom finished_size : forall u, size u = O -> finished u = true.\n\nVariable output : Input -> Result.\nVariable cond : Input -> Data -> bool.\nVariable step : Input -> Data -> Input.\n\n(** When the process is not terminated, the probability to stay in the same state \n    is bounded by k<1 *)\n\nVariable k : U.\nHypothesis knot1 : k < 1.\nHypothesis d_true_bounded \n    : forall x, finished x = false -> mu dData (fun d => B2U (cond x d)) <= k.\n\n(** The random choice of data terminates *)\n\nHypothesis d_term : mu dData (fun d => 1) == 1.\n\n(** Hypothesis that the size decreases, when a step is taken *)\n\nHypothesis size_step : forall (u:Input) (x:Data), \n   finished u = false -> cond u x = false -> (size (step u x) < size u)%nat.\n\n\nLemma d_if_bound : \n   forall x,  finished x = false -> forall a b, a <= b -> \n    k * a + [1-]k * b \n <= mu dData (fun d => B2U (cond x d)) * a \n  + mu dData (fun d => NB2U (cond x d)) * b.\nintros; \nrewrite (bary_le_compat (mu dData (fun d => B2U (cond x d))) k a b); \nauto.\napply Uplus_le_compat; auto.\napply Umult_le_compat; auto.\nrewrite <- mu_one_inv; auto.\nunfold finv; rsimplmu.\ncase (cond x x0); simpl; auto.\nSave.\n\nInstance iter_mon : \n    monotonic \n   (fun (f:Input -> distr Result) (u:Input) => \n        if (finished u) then Munit (output u)\n        else (Mlet dData \n               (fun d => if (cond u d) then (f u) else (f (step u d))))).\nred; intros; intro u.\ncase (finished u); auto.\napply Mlet_le_compat; auto; intro d; auto.\ncase (cond u d); auto.\nSave.\n\nLemma mu_if : forall A (b:bool) (dt de : distr A) (f:MF A),\n              mu (if b then dt else de) f = if b then (mu dt f) else (mu de f).\ndestruct b; auto.\nSave.\n\nDefinition Fiter : (Input -> distr Result) -m> (Input -> distr Result)\n:= mon  (fun (f:Input -> distr Result) (u:Input) => \n        fif (finished u) (Munit (output u))\n        (Mlet dData \n             (fun d => fif (cond u d) (f u) (f (step u d))))).\n\nLemma Fiter_simpl : forall f u, \n   Fiter f u = fif (finished u) (Munit (output u))\n        (Mlet dData \n             (fun d => fif (cond u d) (f u) (f (step u d)))).\ntrivial.\nSave.\n\nLemma Fiter_cont : continuous Fiter. \nintros h u.\nrewrite Fiter_simpl.\nrewrite fcpo_lub_simpl.\nsetoid_rewrite (fcpo_lub_simpl h).\nsetoid_rewrite fif_continuous2.\nrewrite Mlet_lub_fun_le_right.\nrewrite (fif_continuous_right (finished u) (Munit (output u))).\nrewrite fcpo_lub_simpl; apply lub_le_compat; intro n; auto.\nSave.\n\nDefinition iter : Input -> distr Result := Mfix Fiter.\n\nLemma iter_eq : forall u:Input,\n      iter u == fif (finished u) (Munit (output u))\n                (Mlet dData (fun d => fif (cond u d) (iter u) (iter (step u d)))).\nexact (Mfix_eq Fiter_cont).\nSave.\nHint Resolve iter_eq.\n\n(** ** Building the invariant sequence\n\n  [x] is the size of the input and [n] the number of iterations: \n\n      [pw x 0 = 0]\n      [pw 0 n = 1]\n      [pw (x+1) (n+1) = k (pw (x+1) n) + (1-k) (pw x n)]\n   \n*)\n\nFixpoint pw_ (x n : nat) : U := \n  match n with O => 0 \n            | (S n) => match x with \n                         O => 1\n                     | S y => k * pw_ x n + ([1-] k) * pw_ y n \n                       end\n  end.\n\nLemma pw_decrS_x : forall n x, pw_ (S x) n <= pw_ x n.\ninduction n; simpl; intros; auto.\ndestruct x; auto.\nSave.\nHint Resolve pw_decrS_x.\n\nLemma pw_decr_x : forall n x y, (x <= y)%nat -> pw_ y n <= pw_ x n.\ninduction 1; simpl; intros; auto.\ntransitivity (pw_ m n); auto.\nSave.\nHint Resolve pw_decr_x.\n\nLemma pw_incr : forall x n, pw_ x n <= pw_ x (S n).\nsimpl; intros.\ncase x; auto.\nSave.\n\nHint Resolve pw_incr.\n\nDefinition pw : nat -> nat -m> U \n    := fun x => fnatO_intro (pw_ x) (pw_incr x).\n\nLemma pw_pw_ : forall x n, pw x n = pw_ x n.\ntrivial.\nSave.\n\nLemma pw_simpl : forall x n, pw x n = \n    match n with O => 0 \n             | (S n) => match x with \n                          O => 1\n                        | S y => k * pw x n + ([1-] k) * pw y n\n                        end\n    end.\ndestruct n; auto.\nSave.\n\nLemma pwS_simpl : forall x n, pw (S x) (S n) = k * pw (S x) n + [1-]k * (pw x n).\ntrivial.\nSave.\n\n\nLemma lim_pw_one : forall x, lub (pw x) == 1.\ninduction x.\napply Uge_one_eq.\ntransitivity (pw O (S O)); auto.\napply Umult_simpl_one with k; auto.\ntransitivity (mlub (seq_lift_left (pw (S x)) (S 0))).\ntransitivity (k * lub (pw (S x)) + [1-] k * lub (pw x)).\nrewrite IHx; auto.\ndo 2 rewrite <- lub_eq_mult.\nrewrite <- lub_eq_plus.\napply mlub_le_compat; intro n; auto.\nrewrite <- mlub_lift_left; trivial.\nSave.\n\n\nLemma iter_term : forall u, 1 <= mu (iter u) (fun r => 1).\nassert (okfun (fun x : Input => lub (pw (size x))) (Mfix Fiter) (fun a b => 1)).\napply fixrule; auto.\nunfold okfun,ok; intros.\nrewrite Fiter_simpl.\ncase_eq (size x); intros.\nrewrite finished_size; auto.\ncase_eq (finished x); auto.\nintro fx; rewrite pwS_simpl; intros.\nsimpl @fif.\nrewrite Mlet_simpl.\nrewrite (d_if_bound fx).\ntransitivity \n (mu dData\n   (fplus\n   (fun x0 : Data => B2U (cond x x0) * (mu (f x) (fun _ => 1)))\n   (fun x0 => NB2U (cond x x0) * (mu (f (step x x0)) (fun _ => 1))))).\nrewrite (mu_stable_plus dData).\napply Uplus_le_compat; auto.\ndo 4 simplmu.\nrewrite <- H0; rewrite <- H; auto.\ntransitivity (mu dData\n  (fun x0 : Data =>\n   NB2U (cond x x0) *(pw n i))); auto.\nrewrite Umult_sym; rewrite <- (mu_stable_mult dData (pw n i)).\nunfold fmult; simplmu; auto.\napply mu_le_compat; auto; intro x0.\ncase_eq (cond x x0); unfold NB2U; auto.\nrepeat Usimpl.\nintro; rewrite <- H.\nassert (size (step x x0) <= n)%nat; auto.\nassert (S (size (step x x0)) <= S n)%nat; auto.\nrewrite <- H0; apply size_step; auto.\nomega.\nrepeat rewrite pw_pw_; auto.\nred; intros; intro d.\ntransitivity (B2U (cond x d)); auto.\ntransitivity ([1-](NB2U (cond x d))); try simplmu; auto.\ncase (cond x d); auto.\n(* unfold finv; rsimplmu; auto.*)\napply mu_le_compat; intro d; unfold fplus; auto.\ncase (cond x d); simpl; auto.\napply (pw_decrS_x i n).\nintro u; rewrite <- (lim_pw_one (size u)) at 1.\nexact (H u).\nSave.\n\nEnd Walk.\n", "meta": {"author": "hivert", "repo": "Coq-HookLength", "sha": "f9f044a6defdeea7db48d8fe38735c32129cd928", "save_path": "github-repos/coq/hivert-Coq-HookLength", "path": "github-repos/coq/hivert-Coq-HookLength/Coq-HookLength-f9f044a6defdeea7db48d8fe38735c32129cd928/ALEA/examples/AbstractWalk.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6776787205207762}}
{"text": "(** Formal Reasoning About Programs <http://adam.chlipala.net/frap/>\n  * Chapter 5: Transition Systems\n  * Author: Adam Chlipala\n  * License: https://creativecommons.org/licenses/by-nc-nd/4.0/ *)\n\nRequire Import Frap.\n\nSet Implicit Arguments.\n(* This command will treat type arguments to functions as implicit, like in\n * Haskell or ML. *)\n\n\n(* Here's a classic recursive, functional program for factorial. *)\nFixpoint fact (n : nat) : nat :=\n  match n with\n  | O => 1\n  | S n' => fact n' * S n'\n  end.\n\n(* But let's reformulate factorial relationally, as an example to explore\n * treatment of inductive relations in Coq.  First, these are the states of our\n * state machine. *)\nInductive fact_state :=\n| AnswerIs (answer : nat)\n| WithAccumulator (input accumulator : nat).\n\n(* This *predicate* captures which states are starting states.\n * Before the main colon of [Inductive], we list *parameters*, which stay fixed\n * throughout recursive invocations of a predicate (though this definition does\n * not use recursion).  After the colon, we give a type that expresses which\n * additional arguments exist, followed by [Prop] for \"proposition.\"\n * Putting this inductive definition in [Prop] is what marks at as a predicate.\n * Our prior definitions have implicitly been in [Set], the normal universe\n * of mathematical objects. *)\nInductive fact_init (original_input : nat) : fact_state -> Prop :=\n| FactInit : fact_init original_input (WithAccumulator original_input 1).\n\n(** And here are the states where we declare execution complete. *)\nInductive fact_final : fact_state -> Prop :=\n| FactFinal : forall ans, fact_final (AnswerIs ans).\n\n(** The most important part: the relation to step between states *)\nInductive fact_step : fact_state -> fact_state -> Prop :=\n| FactDone : forall acc,\n  fact_step (WithAccumulator O acc) (AnswerIs acc)\n| FactStep : forall n acc,\n  fact_step (WithAccumulator (S n) acc) (WithAccumulator n (acc * S n)).\n\n(* We care about more than just single steps.  We want to run factorial to\n * completion, for which it is handy to define a general relation of\n * *transitive-reflexive closure*, like so. *)\nInductive trc {A} (R : A -> A -> Prop) : A -> A -> Prop :=\n| TrcRefl : forall x, trc R x x\n| TrcFront : forall x y z,\n  R x y\n  -> trc R y z\n  -> trc R x z.\n\n(* Ironically, this definition is not obviously transitive!\n * Let's prove transitivity as a lemma. *)\nTheorem trc_trans : forall {A} (R : A -> A -> Prop) x y, trc R x y\n  -> forall z, trc R y z\n    -> trc R x z.\nProof.\n  induct 1; simplify.\n  (* Note how we pass a *number* to [induct], to ask for induction on\n   * *the first hypothesis in the theorem statement*. *)\n\n  assumption.\n  (* [assumption]: prove a conclusion that matches some hypothesis exactly. *)\n\n  eapply TrcFront.\n  (* [eapply H]: like [apply], but works when it is not obvious how to\n   *   instantiate the quantifiers of theorem/hypothesis [H].  Instead,\n   *   placeholders are inserted for those quantifiers, to be determined\n   *   later. *)\n  eassumption.\n  (* [eassumption]: prove a conclusion that matches some hypothesis, when we\n   *   choose the right clever instantiation of placeholders.  Those placehoders\n   *   are then replaced everywhere with their new values. *)\n  apply IHtrc.\n  assumption.\n  (* [assumption]: like [eassumption], but never figures out placeholder\n   *   values. *)\nQed.\n\n(* Transitive-reflexive closure is so common that it deserves a shorthand notation! *)\nNotation \"R ^*\" := (trc R) (at level 0).\n\n(* Now let's use it to execute the factorial program. *)\nExample factorial_3 : fact_step^* (WithAccumulator 3 1) (AnswerIs 6).\nProof.\n  eapply TrcFront.\n  apply FactStep.\n  simplify.\n  eapply TrcFront.\n  apply FactStep.\n  simplify.\n  eapply TrcFront.\n  apply FactStep.\n  simplify.\n  eapply TrcFront.\n  apply FactDone.\n  apply TrcRefl.\nQed.\n\n(* That was exhausting yet uninformative.  We can use a different tactic to blow\n * through such obvious proof trees. *)\nExample factorial_3_auto : fact_step^* (WithAccumulator 3 1) (AnswerIs 6).\nProof.\n  repeat econstructor.\n  (* [econstructor]: tries all declared rules of the predicate in the\n   *   conclusion, attempting each with [eapply] until one works. *)\n\n  (* Note that here [econstructor] is doing double duty, applying the rules of\n   * both [trc] and [fact_step]. *)\nQed.\n\n(* It will be useful to give state machines more first-class status, as\n * *transition systems*, formalized by this record type.  It has one type\n * parameter, [state], which records the type of states. *)\nRecord trsys state := {\n  Initial : state -> Prop;\n  Step : state -> state -> Prop\n}.\n(* Probably it's intuitively clear what a record type must be.\n * See usage examples below to fill in more of the details.\n * Note that [state] is a polymorphic type parameter. *)\n\n(* The example of our factorial program: *)\nDefinition factorial_sys (original_input : nat) : trsys fact_state := {|\n  Initial := fact_init original_input;\n  Step := fact_step\n|}.\n\n(* A useful general notion for transition systems: reachable states *)\nInductive reachable {state} (sys : trsys state) (st : state) : Prop :=\n| Reachable : forall st0,\n  sys.(Initial) st0\n  -> sys.(Step)^* st0 st\n  -> reachable sys st.\n\n(* To prove that our state machine is correct, we rely on the crucial technique\n * of *invariants*.  What is an invariant?  Here's a general definition, in\n * terms of an arbitrary transition system. *)\nDefinition invariantFor {state} (sys : trsys state) (invariant : state -> Prop) :=\n  forall s, sys.(Initial) s\n            -> forall s', sys.(Step)^* s s'\n                          -> invariant s'.\n(* That is, when we begin in an initial state and take any number of steps, the\n * place we wind up always satisfies the invariant. *)\n\n(* Here's a simple lemma to help us apply an invariant usefully,\n * really just restating the definition. *)\nLemma use_invariant' : forall {state} (sys : trsys state)\n  (invariant : state -> Prop) s s',\n  invariantFor sys invariant\n  -> sys.(Initial) s\n  -> sys.(Step)^* s s'\n  -> invariant s'.\nProof.\n  unfold invariantFor.\n  simplify.\n  eapply H.\n  eassumption.\n  assumption.\nQed.\n\nTheorem use_invariant : forall {state} (sys : trsys state)\n  (invariant : state -> Prop) s,\n  invariantFor sys invariant\n  -> reachable sys s\n  -> invariant s.\nProof.\n  simplify.\n  invert H0.\n  eapply use_invariant'.\n  eassumption.\n  eassumption.\n  assumption.\nQed.\n\n(* What's the most fundamental way to establish an invariant?  Induction! *)\nLemma invariant_induction' : forall {state} (sys : trsys state)\n  (invariant : state -> Prop),\n  (forall s, invariant s -> forall s', sys.(Step) s s' -> invariant s')\n  -> forall s s', sys.(Step)^* s s'\n     -> invariant s\n     -> invariant s'.\nProof.\n  induct 2; propositional.\n  (* [propositional]: simplify the goal according to the rules of propositional\n   *   logic. *)\n\n  apply IHtrc.\n  eapply H.\n  eassumption.\n  assumption.\nQed.\n\nTheorem invariant_induction : forall {state} (sys : trsys state)\n  (invariant : state -> Prop),\n  (forall s, sys.(Initial) s -> invariant s)\n  -> (forall s, invariant s -> forall s', sys.(Step) s s' -> invariant s')\n  -> invariantFor sys invariant.\nProof.\n  unfold invariantFor; intros.\n  eapply invariant_induction'.\n  eassumption.\n  eassumption.\n  apply H.\n  assumption.\nQed.\n\n(* That's enough abstract results for now.  Let's apply them to our example.\n * Here's a good invariant for factorial, parameterized on the original input\n * to the program. *)\nDefinition fact_invariant (original_input : nat) (st : fact_state) : Prop :=\n  match st with\n  | AnswerIs ans => fact original_input = ans\n  | WithAccumulator n acc => fact original_input = fact n * acc\n  end.\n\n(* We can use [invariant_induction] to prove that it really is a good\n * invariant. *)\nTheorem fact_invariant_ok : forall original_input,\n  invariantFor (factorial_sys original_input) (fact_invariant original_input).\nProof.\n  simplify.\n  apply invariant_induction; simplify.\n\n  (* Step 1: invariant holds at the start. (base case) *)\n  (* We have a hypothesis establishing [fact_init original_input s].\n   * By inspecting the definition of [fact_init], we can draw conclusions about\n   * what [s] must be.  The [invert] tactic formalizes that intuition,\n   * replacing a hypothesis with certain \"obvious inferences\" from the original.\n   * In general, when multiple different rules may have been used to conclude a\n   * fact, [invert] may generate one new subgoal per eligible rule, but here the\n   * predicate is only defined with one rule. *)\n  invert H.\n  (* We magically learn [s = WithAccumulator original_input 1]! *)\n  simplify.\n  ring.\n\n  (* Step 2: steps preserve the invariant. (induction step) *)\n  invert H0.\n  (* This time, [invert] is used on a predicate with two rules, neither of which\n   * can be ruled out for this case, so we get two subgoals from one. *)\n\n  simplify.\n  linear_arithmetic.\n\n  simplify.\n  rewrite H.\n  ring.\nQed.\n\n(* Therefore, every reachable state satisfies this invariant. *)\nTheorem fact_invariant_always : forall original_input s,\n  reachable (factorial_sys original_input) s\n  -> fact_invariant original_input s.\nProof.\n  simplify.\n  eapply use_invariant.\n  apply fact_invariant_ok.\n  assumption.\nQed.\n\n(* Therefore, any final state has the right answer! *)\nLemma fact_ok' : forall original_input s,\n  fact_final s\n  -> fact_invariant original_input s\n  -> s = AnswerIs (fact original_input).\nProof.\n  invert 1; simplify; equality.\nQed.\n\nTheorem fact_ok : forall original_input s,\n  reachable (factorial_sys original_input) s\n  -> fact_final s\n  -> s = AnswerIs (fact original_input).\nProof.\n  simplify.\n  apply fact_ok'.\n  assumption.\n  apply fact_invariant_always.\n  assumption.\nQed.\n\n\n(** * A simple example of another program as a state transition system *)\n\n(* We'll formalize this pseudocode for one thread of a concurrent, shared-memory program.\n  lock();\n  local = global;\n  global = local + 1;\n  unlock();\n*)\n\n(* This inductive state effectively encodes all possible combinations of two\n * kinds of *local*state* in a thread:\n * - program counter\n * - values of local variables that may be read eventually *)\nInductive increment_program :=\n| Lock\n| Read\n| Write (local : nat)\n| Unlock\n| Done.\n\n(* Next, a type for state shared between threads. *)\nRecord inc_state := {\n  Locked : bool; (* Does a thread hold the lock? *)\n  Global : nat   (* A shared counter *)\n}.\n\n(* The combined state, from one thread's perspective, using a general\n * definition. *)\nRecord threaded_state shared private := {\n  Shared : shared;\n  Private : private\n}.\n\nDefinition increment_state := threaded_state inc_state increment_program.\n\n(* Now a routine definition of the three key relations of a transition system.\n * The most interesting logic surrounds saving the counter value in the local\n * state after reading. *)\n\nInductive increment_init : increment_state -> Prop :=\n| IncInit :\n  increment_init {| Shared := {| Locked := false; Global := O |};\n                    Private := Lock |}.\n\nInductive increment_step : increment_state -> increment_state -> Prop :=\n| IncLock : forall g,\n  increment_step {| Shared := {| Locked := false; Global := g |};\n                    Private := Lock |}\n                 {| Shared := {| Locked := true; Global := g |};\n                    Private := Read |}\n| IncRead : forall l g,\n  increment_step {| Shared := {| Locked := l; Global := g |};\n                    Private := Read |}\n                 {| Shared := {| Locked := l; Global := g |};\n                    Private := Write g |}\n| IncWrite : forall l g v,\n  increment_step {| Shared := {| Locked := l; Global := g |};\n                    Private := Write v |}\n                 {| Shared := {| Locked := l; Global := S v |};\n                    Private := Unlock |}\n| IncUnlock : forall l g,\n  increment_step {| Shared := {| Locked := l; Global := g |};\n                    Private := Unlock |}\n                 {| Shared := {| Locked := false; Global := g |};\n                    Private := Done |}.\n\nDefinition increment_sys := {|\n  Initial := increment_init;\n  Step := increment_step\n|}.\n\n\n(** * Running transition systems in parallel *)\n\n(* That last example system is a cop-out: it only runs a single thread.  We want\n * to run several threads in parallel, sharing the global state.  Here's how we\n * can do it for just two threads.  The key idea is that, while in the new\n * system the type of shared state remains the same, we take the Cartesian\n * product of the sets of private state. *)\n\nInductive parallel1 shared private1 private2\n  (init1 : threaded_state shared private1 -> Prop)\n  (init2 : threaded_state shared private2 -> Prop)\n  : threaded_state shared (private1 * private2) -> Prop :=\n| Pinit : forall sh pr1 pr2,\n  init1 {| Shared := sh; Private := pr1 |}\n  -> init2 {| Shared := sh; Private := pr2 |}\n  -> parallel1 init1 init2 {| Shared := sh; Private := (pr1, pr2) |}.\n\nInductive parallel2 shared private1 private2\n          (step1 : threaded_state shared private1 -> threaded_state shared private1 -> Prop)\n          (step2 : threaded_state shared private2 -> threaded_state shared private2 -> Prop)\n          : threaded_state shared (private1 * private2)\n            -> threaded_state shared (private1 * private2) -> Prop :=\n| Pstep1 : forall sh pr1 pr2 sh' pr1',\n  (* First thread gets to run. *)\n  step1 {| Shared := sh; Private := pr1 |} {| Shared := sh'; Private := pr1' |}\n  -> parallel2 step1 step2 {| Shared := sh; Private := (pr1, pr2) |}\n               {| Shared := sh'; Private := (pr1', pr2) |}\n| Pstep2 : forall sh pr1 pr2 sh' pr2',\n  (* Second thread gets to run. *)\n  step2 {| Shared := sh; Private := pr2 |} {| Shared := sh'; Private := pr2' |}\n  -> parallel2 step1 step2 {| Shared := sh; Private := (pr1, pr2) |}\n               {| Shared := sh'; Private := (pr1, pr2') |}.\n\nDefinition parallel shared private1 private2\n           (sys1 : trsys (threaded_state shared private1))\n           (sys2 : trsys (threaded_state shared private2)) := {|\n  Initial := parallel1 sys1.(Initial) sys2.(Initial);\n  Step := parallel2 sys1.(Step) sys2.(Step)\n|}.\n\n(* Example: composing two threads of the kind we formalized earlier *)\nDefinition increment2_sys := parallel increment_sys increment_sys.\n\n(* Let's prove that the counter is always 2 when the composed program terminates. *)\n\n(* First big idea: the program counter of a thread tells us how much it has\n * added to the shared counter so far. *)\nDefinition contribution_from (pr : increment_program) : nat :=\n  match pr with\n  | Unlock => 1\n  | Done => 1\n  | _ => 0\n  end.\n\n(* Second big idea: the program counter also tells us whether a thread holds the lock. *)\nDefinition has_lock (pr : increment_program) : bool :=\n  match pr with\n  | Read => true\n  | Write _ => true\n  | Unlock => true\n  | _ => false\n  end.\n\n(* Now we see that the shared state is a function of the two program counters,\n * as follows. *)\nDefinition shared_from_private (pr1 pr2 : increment_program) :=\n  {| Locked := has_lock pr1 || has_lock pr2;\n     Global := contribution_from pr1 + contribution_from pr2 |}.\n\n(* We also need a condition to formalize compatibility between program counters,\n * e.g. that they shouldn't both be in the critical section at once. *)\nDefinition instruction_ok (self other : increment_program) :=\n  match self with\n  | Lock => True\n  | Read => has_lock other = false\n  | Write n => has_lock other = false /\\ n = contribution_from other\n  | Unlock => has_lock other = false\n  | Done => True\n  end.\n\n(** Now we have the ingredients to state the invariant. *)\nInductive increment2_invariant :\n  threaded_state inc_state (increment_program * increment_program) -> Prop :=\n| Inc2Inv : forall pr1 pr2,\n  instruction_ok pr1 pr2\n  -> instruction_ok pr2 pr1\n  -> increment2_invariant {| Shared := shared_from_private pr1 pr2; Private := (pr1, pr2) |}.\n\n(** It's convenient to prove this alternative equality-based \"constructor\" for the invariant. *)\nLemma Inc2Inv' : forall sh pr1 pr2,\n  sh = shared_from_private pr1 pr2\n  -> instruction_ok pr1 pr2\n  -> instruction_ok pr2 pr1\n  -> increment2_invariant {| Shared := sh; Private := (pr1, pr2) |}.\nProof.\n  intros.\n  rewrite H.\n  apply Inc2Inv; assumption.\nQed.\n\n(* Now, to show it really is an invariant. *)\nTheorem increment2_invariant_ok : invariantFor increment2_sys increment2_invariant.\nProof.\n  apply invariant_induction; simplify.\n\n  invert H.\n  invert H0.\n  invert H1.\n  apply Inc2Inv'.\n\n  unfold shared_from_private.\n  simplify.\n  equality.\n\n  simplify.\n  propositional.\n\n  simplify.\n  propositional.\n\n  invert H.\n  invert H0.\n\n  invert H6; simplify.\n\n  cases pr2; simplify.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\n\n  equality.\n  (* Note that [equality] derives a contradiction from [false = true]! *)\n  equality.\n  equality.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\n\n  cases pr2; simplify.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\n\n  equality.\n  equality.\n  equality.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\n\n  cases pr2; simplify.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\n\n  equality.\n  equality.\n  equality.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\n\n  cases pr2; simplify.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\n\n  equality.\n  equality.\n  equality.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\n\n\n  invert H6.\n\n  cases pr1; simplify.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\n\n  equality.\n  (* Note that [equality] derives a contradiction from [false = true]! *)\n  equality.\n  equality.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\n\n  cases pr1; simplify.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\n\n  equality.\n  (* Note that [equality] derives a contradiction from [false = true]! *)\n  equality.\n  equality.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\n\n  cases pr1; simplify.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\n\n  equality.\n  (* Note that [equality] derives a contradiction from [false = true]! *)\n  equality.\n  equality.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\n\n  cases pr1; simplify.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\n\n  equality.\n  (* Note that [equality] derives a contradiction from [false = true]! *)\n  equality.\n  equality.\n\n  apply Inc2Inv'; unfold shared_from_private; simplify.\n  equality.\n  equality.\n  equality.\nQed.\n\n(* We can remove the repetitive proving with a more automated proof script,\n * whose details are beyond the scope of this book, but which may be interesting\n * anyway! *)\nTheorem increment2_invariant_ok_snazzy : invariantFor increment2_sys increment2_invariant.\nProof.\n  apply invariant_induction; simplify;\n  repeat match goal with\n         | [ H : increment2_invariant _ |- _ ] => invert H\n         | [ H : parallel1 _ _ _ |- _ ] => invert H\n         | [ H : increment_init _ |- _ ] => invert H\n         | [ H : parallel2 _ _ _ _ |- _ ] => invert H\n         | [ H : increment_step _ _ |- _ ] => invert H\n         | [ pr : increment_program |- _ ] => cases pr; simplify\n         end; try equality;\n  apply Inc2Inv'; unfold shared_from_private; simplify; equality.\nQed.\n\n(* Now, to prove our final result about the two incrementing threads, let's use\n * a more general fact, about when one invariant implies another. *)\nTheorem invariant_weaken : forall {state} (sys : trsys state)\n  (invariant1 invariant2 : state -> Prop),\n  invariantFor sys invariant1\n  -> (forall s, invariant1 s -> invariant2 s)\n  -> invariantFor sys invariant2.\nProof.\n  unfold invariantFor; simplify.\n  apply H0.\n  eapply H.\n  eassumption.\n  assumption.\nQed.\n\n(* Here's another, much weaker invariant, corresponding exactly to the overall\n * correctness property we want to establish for this system. *)\nDefinition increment2_right_answer\n  (s : threaded_state inc_state (increment_program * increment_program)) :=\n  s.(Private) = (Done, Done)\n  -> s.(Shared).(Global) = 2.\n\n(** Now we can prove that the system only runs to happy states. *)\nTheorem increment2_sys_correct : forall s,\n  reachable increment2_sys s\n  -> increment2_right_answer s.\nProof.\n  simplify.\n  eapply use_invariant.\n  apply invariant_weaken with (invariant1 := increment2_invariant).\n  (* Note the use of a [with] clause to specify a quantified variable's\n   * value. *)\n\n  apply increment2_invariant_ok.\n\n  simplify.\n  invert H0.\n  unfold increment2_right_answer; simplify.\n  invert H0.\n  (* Here we use inversion on an equality, to derive more primitive\n   * equalities. *)\n  simplify.\n  equality.\n\n  assumption.\nQed.\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/TransitionSystems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6776786975328368}}
{"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\n(** * MSetFullAVL : some complements to MSetAVL\n\n   - Functor [AvlProofs] proves that trees of [MSetAVL] are not only\n   binary search trees, but moreover well-balanced ones. This is done\n   by proving that the operations in [MSetAVL.Ops] preserve the balancing.\n\n   - We propose two functors [IntMake] and [Make] similar to the ones\n   of [MSetAVL], except that the two invariants (bst and avl)\n   are maintained instead of only the first one.\n\n   - Functor [OcamlOps] contains variants of [union], [subset],\n   [compare] and [equal] that are faithful to the original ocaml codes,\n   while the versions in MSetAVL have been adapted to perform only\n   structural recursive code.\n*)\n\nRequire Import ZArith Int ROmega MSetInterface MSetAVL NPeano.\nRequire Import FunInd.\n\nModule AvlProofs (Import I:Int)(X:OrderedType).\nInclude MSetAVL.MakeRaw I X.\nModule Import II := MoreInt I.\nLocal Open Scope pair_scope.\nLocal Open Scope Int_scope.\n\nLtac omega_max := i2z_refl; romega with Z.\nLtac mysubst :=\n match goal with\n   | E : _=_ |- _ => rewrite E in *; clear E; mysubst\n   | _ => idtac\n end.\n\n(** * AVL trees *)\n\n(** [avl s] : [s] is a properly balanced AVL tree,\n    i.e. for any node the heights of the two children\n    differ by at most 2 *)\n\nInductive avl : tree -> Prop :=\n  | RBLeaf : avl Leaf\n  | RBNode : forall x l r h, avl l -> avl r ->\n      -(2) <= height l - height r <= 2 ->\n      h = max (height l) (height r) + 1 ->\n      avl (Node h l x r).\n\nClass Avl (t:tree) : Prop := mkAvl : avl t.\n\nInstance avl_Avl s (Hs : avl s) : Avl s := Hs.\n\n(** * Automation and dedicated tactics *)\n\nLocal Hint Constructors avl.\n\n(** A tactic for cleaning hypothesis after use of functional induction. *)\n\nLtac clearf :=\n match goal with\n  | H : (@Logic.eq (sumbool _ _) _ _) |- _ => clear H; clearf\n  | H : (_ =? _) = true |- _ => rewrite II.eqb_eq in H; clearf\n  | H : (_ <? _) = true |- _ => rewrite II.ltb_lt in H; clearf\n  | H : (_ <=? _) = true |- _ => rewrite II.leb_le in H; clearf\n  | H : (_ =? _) = false |- _ => rewrite II.eqb_neq in H; clearf\n  | H : (_ <? _) = false |- _ => rewrite II.ltb_nlt in H; clearf\n  | H : (_ <=? _) = false |- _ => rewrite II.leb_nle in H; clearf\n  | _ => idtac\n end.\n\nLtac avl2Avl := change avl with Avl in *.\nLtac Avl2avl := change Avl with avl in *.\nLtac inv_avl := Avl2avl; invtree avl; avl2Avl.\n(* Similar, but non-recursive *)\nLtac inv_avl' :=\n  match goal with H : Avl (Node _ _ _ _) |- _ =>\n    inversion_clear H; avl2Avl\n  end.\n\n(** Tactics about [avl] *)\n\nLemma height_non_negative : forall s `{Avl s}, height s >= 0.\nProof.\n induction s; simpl; intros; auto with zarith.\n inv_avl; intuition; omega_max.\nQed.\n\n(** When [H:Avl r], typing [avl_nn H] adds [height r >= 0] *)\n\nLtac avl_nn H :=\n  let nz := fresh \"nz\" in assert (nz := @height_non_negative _ H).\n\n(* Repeat the previous tactic, clearing the [Avl _] hyps *)\n\nLtac avl_nns :=\n  match goal with\n     | H:Avl _ |- _ => avl_nn H; clear H; avl_nns\n     | _ => idtac\n  end.\n\n(** Results about [height] *)\n\nLemma height_0 : forall s `{Avl s}, height s = 0 -> s = Leaf.\nProof.\n destruct 1; avl2Avl; intuition; simpl in *.\n avl_nns. simpl in *; exfalso; omega_max.\nQed.\n\n(** Results about [avl] *)\n\nLemma avl_node :\n forall x l r `{Avl l, Avl r},\n -(2) <= height l - height r <= 2 ->\n Avl (Node (max (height l) (height r) + 1) l x r).\nProof.\n  auto_tc.\nQed.\nHint Resolve avl_node.\n\n(** * AVL trees have indeed logarithmic depth *)\n\nModule LogDepth.\n\nLocal Open Scope nat_scope.\n\n(** The minimal cardinal of an AVL tree of a given height.\n    NB: this minimal cardinal is optimal, i.e. for any height,\n    we could build an AVL tree of this cardinal. *)\n\nFixpoint mincard n :=\n match n with\n | O => O\n | 1 => 1\n | 2 => 2\n | S (S (S n) as p) => S (mincard n + mincard p)\n end.\n\n(** First, some basic properties of [mincard] *)\n\nLemma mincard_eqn n :\n mincard (S (S (S n))) = S (mincard n + mincard (2+n)).\nProof.\n reflexivity.\nQed.\n\nLemma mincard_incr n : mincard n < mincard (S n).\nProof.\n induction n using lt_wf_ind.\n do 3 (destruct n; auto).\n rewrite 2 mincard_eqn.\n apply -> Nat.succ_lt_mono.\n apply Nat.add_lt_mono; eauto.\nQed.\n\nLemma mincard_lt_mono n m : n < m -> mincard n < mincard m.\nProof.\n induction m; inversion_clear 1.\n - apply mincard_incr.\n - transitivity (mincard m); auto using mincard_incr.\nQed.\n\nLemma mincard_le_mono n m : n <= m -> mincard n <= mincard m.\nProof.\n induction 1; auto.\n transitivity (mincard m); auto using mincard_incr with arith.\nQed.\n\nLemma mincard_bound n m : m <= 2+n ->\n mincard (S m) <= S (mincard n + mincard m).\nProof.\n intros H.\n destruct m as [|[|m]].\n - simpl. auto with arith.\n - simpl. auto with arith.\n - rewrite mincard_eqn.\n   apply -> Nat.succ_le_mono.\n   apply Nat.add_le_mono; eauto.\n   apply mincard_le_mono; omega.\nQed.\n\n(** [mincard] has an exponential behavior *)\n\nLemma mincard_twice n : 2 * mincard n < mincard (2+n).\nProof.\n induction n as [n IH] using lt_wf_ind.\n do 3 (destruct n; [simpl; auto with arith|]).\n change (2 + S (S (S n))) with (S (S (S (2+n)))).\n rewrite 2 mincard_eqn.\n generalize (IH n) (IH (2+n)). omega.\nQed.\n\nLemma mincard_even n : n<>0 -> 2^n <= mincard (2*n).\nProof.\n induction n.\n - now destruct 1.\n - intros _.\n   destruct (Nat.eq_dec n 0).\n   * subst; simpl; auto.\n   * rewrite Nat.pow_succ_r', Nat.mul_succ_r, Nat.add_comm.\n     transitivity (2 * mincard (2*n)).\n     + apply Nat.mul_le_mono_l; auto.\n     + apply Nat.lt_le_incl. apply mincard_twice.\nQed.\n\nLemma mincard_odd n : 2^n <= mincard (2*n+1).\nProof.\n destruct (Nat.eq_dec n 0).\n - subst; auto.\n - transitivity (mincard (2*n)).\n   * now apply mincard_even.\n   * apply mincard_le_mono. omega.\nQed.\n\nLemma mincard_log n : n <= 2 * Nat.log2 (mincard n) + 1.\nProof.\n rewrite (Nat.div2_odd n).\n set (m := Nat.div2 n); clearbody m.\n destruct (Nat.odd n); simpl Nat.b2n; rewrite ?Nat.add_0_r; clear n.\n + apply Nat.add_le_mono_r, Nat.mul_le_mono_l.\n   apply Nat.log2_le_pow2.\n   apply (mincard_lt_mono 0); auto with arith.\n   apply mincard_odd.\n + destruct (Nat.eq_dec m 0); [subst; simpl; auto|].\n   transitivity (2*Nat.log2 (mincard (2*m))); [|omega].\n   apply Nat.mul_le_mono_l.\n   apply Nat.log2_le_pow2.\n   apply (mincard_lt_mono 0); omega.\n   now apply mincard_even.\nQed.\n\n(** We now prove that [mincard] gives indeed a lower bound\n    of the cardinal of AVL trees. *)\n\nLemma maxdepth_heigth s : Avl s ->\n Z.of_nat (maxdepth s) = i2z (height s).\nProof.\n induction 1.\n simpl. omega_max.\n simpl maxdepth. simpl height. subst h.\n rewrite Nat2Z.inj_succ, Nat2Z.inj_max. omega_max.\nQed.\n\nLemma mincard_maxdepth s :\n Avl s -> mincard (maxdepth s) <= cardinal s.\nProof.\n induction 1.\n - simpl; auto.\n - simpl maxdepth. simpl cardinal. subst h.\n   destruct (Nat.max_spec (maxdepth l) (maxdepth r)) as [(U,->)|(U,->)].\n   * rewrite mincard_bound.\n     apply -> Nat.succ_le_mono.\n     apply Nat.add_le_mono; eauto.\n     apply Nat2Z.inj_le. rewrite Nat2Z.inj_add.\n     rewrite 2 maxdepth_heigth by auto. simpl Z.of_nat.\n     i2z. omega.\n   * rewrite Nat.add_comm, mincard_bound.\n     apply -> Nat.succ_le_mono.\n     apply Nat.add_le_mono; eauto.\n     apply Nat2Z.inj_le. rewrite Nat2Z.inj_add.\n     rewrite 2 maxdepth_heigth by auto. simpl Z.of_nat.\n     i2z. omega.\nQed.\n\n(** We can now prove that the depth of an AVL tree is\n    logarithmic in its size. *)\n\nLemma maxdepth_upperbound s : Avl s ->\n maxdepth s <= 2 * Nat.log2 (cardinal s) + 1.\nProof.\n intros.\n transitivity (2 * Nat.log2 (mincard (maxdepth s)) + 1).\n apply mincard_log.\n apply Nat.add_le_mono_r, Nat.mul_le_mono_l, Nat.log2_le_mono.\n now apply mincard_maxdepth.\nQed.\n\nLemma maxdepth_lowerbound s : s<>Leaf ->\n Nat.log2 (cardinal s) < maxdepth s.\nProof.\n apply maxdepth_log_cardinal.\nQed.\n\nEnd LogDepth.\n\n(** * The AVL invariant is preserved by set operations *)\n\n(** empty *)\n\nInstance empty_avl : Avl empty.\nProof.\n auto_tc.\nQed.\n\n(** singleton *)\n\nInstance singleton_avl (x:elt) : Avl (singleton x).\nProof.\n unfold singleton. constructor; auto; simpl; omega_max.\nQed.\n\n(** create *)\n\nLemma create_avl :\n forall l x r `{Avl l, Avl r},\n   -(2) <= height l - height r <= 2 ->\n   Avl (create l x r).\nProof.\n unfold create; auto.\nQed.\n\nLemma create_height :\n forall l x r `{Avl l, Avl r},\n   -(2) <= height l - height r <= 2 ->\n   height (create l x r) = max (height l) (height r) + 1.\nProof.\n unfold create; auto.\nQed.\n\n(** bal *)\n\nLtac when f :=\n match goal with |- context [f] => idtac | _ => fail end.\n\nLemma bal_avl :\n  forall l x r `{Avl l, Avl r},\n    -(3) <= height l - height r <= 3 ->\n    Avl (bal l x r).\nProof.\n intros l x r; functional induction bal l x r; intros; clearf;\n inv_avl; simpl in *; try (when assert_false; avl_nns);\n repeat apply create_avl; simpl in *; auto; omega_max.\nQed.\n\nLemma bal_height_1 :\n  forall l x r `{Avl l, Avl r},\n    -(3) <= height l - height r <= 3 ->\n    0 <= height (bal l x r) - max (height l) (height r) <= 1.\nProof.\n intros l x r; functional induction bal l x r; intros; clearf;\n inv_avl; avl_nns; simpl in *; omega_max.\nQed.\n\nLemma bal_height_2 :\n forall l x r `{Avl l, Avl r},\n   -(2) <= height l - height r <= 2 ->\n   height (bal l x r) == max (height l) (height r) +1.\nProof.\n intros l x r; functional induction bal l x r; intros; clearf;\n inv_avl; simpl in *; omega_max.\nQed.\n\nLtac omega_bal := match goal with\n  | _:Avl ?l, _:Avl ?r |- context [ bal ?l ?x ?r ] =>\n     generalize (bal_height_1 l x r) (bal_height_2 l x r);\n     omega_max\n  end.\n\n(** add *)\n\nLemma add_avl_1 : forall s x `{Avl s},\n Avl (add x s) /\\ 0 <= height (add x s) - height s <= 1.\nProof.\n induct s x; inv_avl.\n - intuition; try constructor; simpl; auto; omega_max.\n - (* Eq *)\n   simpl. intuition; omega_max.\n - (* Lt *)\n   destruct (IHl x); trivial.\n   split.\n   * apply bal_avl; trivial; omega_max.\n   * omega_bal.\n - (* Gt *)\n   destruct (IHr x); trivial.\n   split.\n   * apply bal_avl; trivial; omega_max.\n   * omega_bal.\nQed.\n\nInstance add_avl s x `{Avl s} : Avl (add x s).\nProof.\n now destruct (add_avl_1 s x).\nQed.\n\n(** join *)\n\nLtac remtree t s :=\n match t with Node ?h _ _ _ =>\n  assert (height t = h) by trivial;\n  set (s := t) in *; clearbody s\n end.\n\nLemma join_avl_1 : forall l x r `{Avl l, Avl r},\n Avl (join l x r) /\\\n 0<= height (join l x r) - max (height l) (height r) <= 1.\nProof.\n join_tac; clearf.\n\n - simpl. destruct (add_avl_1 r x). split; trivial.\n   avl_nns; omega_max.\n\n - remtree (Node lh ll lx lr) l.\n   split; auto_tc.\n   destruct (add_avl_1 l x).\n   simpl. avl_nns; omega_max.\n\n - remtree (Node rh rl rx rr) r.\n   inv_avl.\n   destruct (Hlr x r); trivial; clear Hrl Hlr.\n   set (j := join lr x r) in *; clearbody j.\n   simpl.\n   assert (-(3) <= height ll - height j <= 3) by omega_max.\n   split.\n   * apply bal_avl; trivial.\n   * omega_bal.\n\n - remtree (Node lh ll lx lr) l.\n   inv_avl.\n   destruct Hrl; trivial; clear Hlr.\n   set (j := join l x rl) in *; clearbody j.\n   simpl.\n   assert (-(3) <= height j - height rr <= 3) by omega_max.\n   split.\n   * apply bal_avl; trivial.\n   * omega_bal.\n\n - clear Hrl Hlr.\n   remtree (Node lh ll lx lr) l.\n   remtree (Node rh rl rx rr) r.\n   assert (-(2) <= height l - height r <= 2) by omega_max.\n   split.\n   * apply create_avl; trivial.\n   * rewrite create_height; trivial; omega_max.\nQed.\n\nInstance join_avl l x r `{Avl l, Avl r} : Avl (join l x r).\nProof.\n now destruct (join_avl_1 l x r).\nQed.\n\n(** remove_min *)\n\nLemma remove_min_avl_1 : forall l x r h `{Avl (Node h l x r)},\n Avl (remove_min l x r)#1 /\\\n 0 <= height (Node h l x r) - height (remove_min l x r)#1 <= 1.\nProof.\n intros l x r; functional induction (remove_min l x r);\n subst; simpl in *; intros.\n - inv_avl; simpl in *; split; auto. avl_nns; omega_max.\n - mysubst. inv_avl'; simpl in *.\n   edestruct IHp; clear IHp; [eauto|].\n   split.\n   * apply bal_avl; trivial; omega_max.\n   * omega_bal.\nQed.\n\nInstance remove_min_avl l x r h `{Avl (Node h l x r)} :\n  Avl (remove_min l x r)#1.\nProof.\n now destruct (remove_min_avl_1 l x r h).\nQed.\n\n(** merge *)\n\nLemma merge_avl_1 : forall s1 s2 `{Avl s1, Avl s2},\n -(2) <= height s1 - height s2 <= 2 ->\n Avl (merge s1 s2) /\\\n 0<= height (merge s1 s2) - max (height s1) (height s2) <=1.\nProof.\n intros s1 s2; functional induction (merge s1 s2); intros;\n try (factornode s1).\n - simpl; split; auto; avl_nns; omega_max.\n - simpl; split; auto; avl_nns; simpl in *; omega_max.\n - generalize (@remove_min_avl_1 l2 x2 r2 _ _).\n   mysubst. destruct 1; simpl in *.\n   split.\n   * apply bal_avl; trivial. simpl; omega_max.\n   * omega_bal.\nQed.\n\nLemma merge_avl s1 s2 `{Avl s1, Avl s2} :\n  -(2) <= height s1 - height s2 <= 2 -> Avl (merge s1 s2).\nProof.\n intros; now destruct (merge_avl_1 s1 s2).\nQed.\n\n\n(** remove *)\n\nLemma remove_avl_1 : forall s x `{Avl s},\n Avl (remove x s) /\\ 0 <= height s - height (remove x s) <= 1.\nProof.\n induct s x; inv_avl.\n - intuition; omega_max.\n - (* Eq *)\n   generalize (merge_avl_1 l r).\n   intuition omega_max.\n - (* Lt *)\n   destruct (IHl x); trivial.\n   split.\n   * apply bal_avl; trivial; omega_max.\n   * omega_bal.\n - (* Gt *)\n   destruct (IHr x); trivial.\n   split.\n   * apply bal_avl; trivial; omega_max.\n   * omega_bal.\nQed.\n\nInstance remove_avl s x `{Avl s} : Avl (remove x s).\nProof.\n now destruct (remove_avl_1 s x).\nQed.\n\n(** concat *)\n\nInstance concat_avl s1 s2 `{Avl s1, Avl s2} : Avl (concat s1 s2).\nProof.\n functional induction (concat s1 s2); auto.\n apply join_avl; auto.\n generalize (remove_min_avl l2 x2 r2 _). now mysubst.\nQed.\n\n(** split *)\n\nFunctional Scheme split_ind := Induction for split Sort Prop.\n\nLemma split_avl : forall s x `{Avl s},\n  Avl (split x s)#l /\\ Avl (split x s)#r.\nProof.\n intros s x. functional induction (split x s); simpl; auto.\n - intros. inv_avl; auto.\n - mysubst; simpl in *; inversion_clear 1; intuition.\n - mysubst; simpl in *; inversion_clear 1; intuition.\nQed.\n\n(** inter *)\n\nLtac split_tac x1 :=\n let s2 := fresh \"s2\" in\n auto; factornode s2; generalize (split_avl s2 x1);\n mysubst; simpl; destruct 1; inv_avl; auto_tc.\n\nInstance inter_avl s1 s2 `{Avl s1, Avl s2} : Avl (inter s1 s2).\nProof.\n functional induction inter s1 s2; split_tac x1.\nQed.\n\n(** diff *)\n\nInstance diff_avl s1 s2 `{Avl s1, Avl s2} : Avl (diff s1 s2).\nProof.\n functional induction diff s1 s2; split_tac x1.\nQed.\n\n(** union *)\n\nInstance union_avl s1 s2 `{Avl s1, Avl s2} : Avl (union s1 s2).\nProof.\n functional induction union s1 s2; split_tac x1.\nQed.\n\n(** filter *)\n\nInstance filter_avl f s `{Avl s} : Avl (filter f s).\nProof.\n induction s; simpl; auto. inv_avl. destruct (f _); auto_tc.\nQed.\n\n(** partition *)\n\nInstance partition_avl_1 f s `{Avl s} : Avl (partition f s)#1.\nProof.\n induction s; simpl; auto. inv_avl.\n destruct (partition f s1), (partition f s2), (f _); simpl; auto_tc.\nQed.\n\nInstance partition_avl_2 f s `{Avl s} : Avl (partition f s)#2.\nProof.\n induction s; simpl; auto. inv_avl.\n destruct (partition f s1), (partition f s2), (f _); simpl; auto_tc.\nQed.\n\nEnd AvlProofs.\n\n\n(** * Encapsulation\n\n   We can implement [S] with balanced binary search trees.\n   When compared to [MSetAVL], we maintain here two invariants\n   (bst and avl) instead of only bst, which is enough for fulfilling\n   the MSet interface.\n*)\n\nModule IntMake (I:Int)(X: OrderedType) <: S with Module E := X.\n\n Module E := X.\n Module Import Raw := AvlProofs I X.\n\n Record t_ := Mkt\n   { this :> tree;\n     is_bst : Ok this;\n     is_avl : Avl this }.\n Arguments Mkt this {is_bst} {is_avl}.\n\n Definition t := t_.\n Definition elt := E.t.\n\n Existing Instance is_bst.\n Existing Instance is_avl.\n Existing Class bst.\n Existing Class avl.\n\n (** Functions *)\n\n Definition mem (x:elt)(s:t) : bool := mem x s.\n Definition empty : t := Mkt empty.\n Definition is_empty (s:t) : bool := is_empty s.\n Definition singleton (x:elt) : t := Mkt (singleton x).\n Definition add (x:elt)(s:t) : t := Mkt (add x s).\n Definition remove (x:elt)(s:t) : t := Mkt (remove x s).\n Definition inter (s s':t) : t := Mkt (inter s s').\n Definition union (s s':t) : t := Mkt (union s s').\n Definition diff (s s':t) : t := Mkt (diff s s').\n Definition elements (s:t) : list elt := elements s.\n Definition min_elt (s:t) : option elt := min_elt s.\n Definition max_elt (s:t) : option elt := max_elt s.\n Definition choose (s:t) : option elt := choose s.\n Definition fold {B : Type} (f : elt -> B -> B) (s:t) : B -> B := fold f s.\n Definition cardinal (s:t) : nat := cardinal s.\n Definition filter (f : elt -> bool) (s:t) : t := Mkt (filter f s).\n Definition for_all (f : elt -> bool) (s:t) : bool := for_all f s.\n Definition exists_ (f : elt -> bool) (s:t) : bool := exists_ f s.\n Definition partition (f : elt -> bool) (s:t) : t * t :=\n   let p := partition f s in (Mkt (fst p), Mkt (snd p)).\n\n Definition equal (s s':t) : bool := equal s s'.\n Definition subset (s s':t) : bool := subset s s'.\n\n Definition compare (s s':t) := compare s s'.\n\n (** Predicates *)\n\n Definition In (x : elt) (s : t) : Prop := In x s.\n Definition Equal (s s':t) : Prop := forall a : elt, In a s <-> In a s'.\n Definition Subset (s s':t) : Prop := forall a : elt, In a s -> In a s'.\n Definition Empty (s:t) : Prop := forall a : elt, ~ In a s.\n Definition For_all (P : elt -> Prop) (s:t) : Prop := forall x, In x s -> P x.\n Definition Exists (P : elt -> Prop) (s:t) : Prop := exists x, In x s /\\ P x.\n\n Instance In_compat : Proper (E.eq==>Logic.eq==>iff) In.\n Proof. repeat red. intros; apply In_compat; congruence. Qed.\n\n Definition eq (s s':t) : Prop := Equal s s'.\n Definition lt (s s':t) : Prop := lt s s'.\n\n Instance eq_equiv : Equivalence eq.\n Proof. firstorder. Qed.\n\n Definition eq_dec : forall (s s':t), { eq s s' }+{ ~eq s s' }.\n Proof.\n  intros (s,Bs,As) (s',Bs',As').\n  change ({Raw.Equal s s'}+{~Raw.Equal s s'}).\n  destruct (Raw.equal s s') as [ ] eqn:H; [left|right];\n   rewrite <- equal_spec; congruence.\n Defined.\n\n Instance lt_strorder : StrictOrder lt.\n Proof. constructor ; unfold lt; red.\n   unfold complement. red. intros. apply (irreflexivity H).\n   intros. transitivity y; auto.\n Qed.\n\n Instance lt_compat : Proper (eq==>eq==>iff) lt.\n Proof.\n repeat red. unfold eq, lt.\n intros (s1,B1,A1) (s2,B2,A2) E (s1',B1',A1') (s2',B2',A2') E'; simpl.\n change (Raw.eq s1 s2) in E.\n change (Raw.eq s1' s2') in E'.\n rewrite E,E'; intuition.\n Qed.\n\n (* Specs *)\n\n Section Specs.\n Variable s s' s'': t.\n Variable x y : elt.\n Variable f : elt -> bool.\n Notation compatb := (Proper (E.eq==>Logic.eq)) (only parsing).\n\n Lemma mem_spec : mem x s = true <-> In x s.\n Proof. exact (@mem_spec _ _ _). Qed.\n Lemma equal_spec : equal s s' = true <-> Equal s s'.\n Proof. exact (@equal_spec _ _ _ _). Qed.\n Lemma subset_spec : subset s s' = true <-> Subset s s'.\n Proof. exact (@subset_spec _ _ _ _). Qed.\n Lemma empty_spec : Empty empty.\n Proof. exact empty_spec. Qed.\n Lemma is_empty_spec : is_empty s = true <-> Empty s.\n Proof. exact (@is_empty_spec _). Qed.\n Lemma add_spec : In y (add x s) <-> E.eq y x \\/ In y s.\n Proof. exact (@add_spec _ _ _ _). Qed.\n Lemma remove_spec : In y (remove x s) <-> In y s /\\ ~E.eq y x.\n Proof. exact (@remove_spec _ _ _ _). Qed.\n Lemma singleton_spec : In y (singleton x) <-> E.eq y x.\n Proof. exact (@singleton_spec _ _). Qed.\n Lemma union_spec : In x (union s s') <-> In x s \\/ In x s'.\n Proof. exact (@union_spec _ _ _ _ _). Qed.\n Lemma inter_spec : In x (inter s s') <-> In x s /\\ In x s'.\n Proof. exact (@inter_spec _ _ _ _ _). Qed.\n Lemma diff_spec : In x (diff s s') <-> In x s /\\ ~In x s'.\n Proof. exact (@diff_spec _ _ _ _ _). Qed.\n Lemma fold_spec : forall (A : Type) (i : A) (f : elt -> A -> A),\n     fold f s i = fold_left (fun a e => f e a) (elements s) i.\n Proof. exact (@fold_spec _). Qed.\n Lemma cardinal_spec : cardinal s = length (elements s).\n Proof. exact (@cardinal_spec s _). Qed.\n Lemma filter_spec : compatb f ->\n   (In x (filter f s) <-> In x s /\\ f x = true).\n Proof. exact (@filter_spec _ _ _). Qed.\n Lemma for_all_spec : compatb f ->\n   (for_all f s = true <-> For_all (fun x => f x = true) s).\n Proof. exact (@for_all_spec _ _). Qed.\n Lemma exists_spec : compatb f ->\n   (exists_ f s = true <-> Exists (fun x => f x = true) s).\n Proof. exact (@exists_spec _ _). Qed.\n Lemma partition_spec1 : compatb f -> Equal (fst (partition f s)) (filter f s).\n Proof. exact (@partition_spec1 _ _). Qed.\n Lemma partition_spec2 : compatb f ->\n   Equal (snd (partition f s)) (filter (fun x => negb (f x)) s).\n Proof. exact (@partition_spec2 _ _). Qed.\n Lemma elements_spec1 : InA E.eq x (elements s) <-> In x s.\n Proof. exact (@elements_spec1 _ _). Qed.\n Lemma elements_spec2w : NoDupA E.eq (elements s).\n Proof. exact (@elements_spec2w _ _). Qed.\n Lemma choose_spec1 : choose s = Some x -> In x s.\n Proof. exact (@choose_spec1 _ _). Qed.\n Lemma choose_spec2 : choose s = None -> Empty s.\n Proof. exact (@choose_spec2 _). Qed.\n\n Lemma compare_spec : CompSpec eq lt s s' (compare s s').\n Proof. unfold compare; destruct (@compare_spec s s' _ _); auto. Qed.\n Lemma elements_spec2 : sort X.lt (elements s).\n Proof. exact (@elements_spec2 _ _). Qed.\n Lemma min_elt_spec1 : min_elt s = Some x -> In x s.\n Proof. exact (@min_elt_spec1 _ _). Qed.\n Lemma min_elt_spec2 : min_elt s = Some x -> In y s -> ~ X.lt y x.\n Proof. exact (@min_elt_spec2 _ _ _ _). Qed.\n Lemma min_elt_spec3 : min_elt s = None -> Empty s.\n Proof. exact (@min_elt_spec3 _). Qed.\n Lemma max_elt_spec1 : max_elt s = Some x -> In x s.\n Proof. exact (@max_elt_spec1 _ _). Qed.\n Lemma max_elt_spec2 : max_elt s = Some x -> In y s -> ~ X.lt x y.\n Proof. exact (@max_elt_spec2 _ _ _ _). Qed.\n Lemma max_elt_spec3 : max_elt s = None -> Empty s.\n Proof. exact (@max_elt_spec3 _). Qed.\n Lemma choose_spec3 :\n    choose s = Some x -> choose s' = Some y -> Equal s s' -> X.eq x y.\n  Proof. exact (@choose_spec3 _ _ _ _ _ _). Qed.\n\nEnd Specs.\nEnd IntMake.\n\n(* For concrete use inside Coq, we propose an instantiation of [Int] by [Z]. *)\n\nModule Make (X: OrderedType) <: S with Module E := X\n :=IntMake(Z_as_Int)(X).\n\n\n\nRequire Import Recdef.\n\nModule OcamlOps (Import I:Int)(X:OrderedType).\nModule Import Raw := AvlProofs I X.\nImport II.\nLocal Open Scope pair_scope.\nLocal Open Scope nat_scope.\nLocal Hint Resolve MX.eq_refl MX.eq_trans MX.lt_trans @ok.\nLocal Hint Immediate MX.eq_sym.\nLocal Hint Unfold In lt_tree gt_tree.\nLocal Hint Constructors InT bst.\nLocal Hint Unfold Ok.\nLocal Hint Resolve lt_leaf gt_leaf lt_tree_node gt_tree_node.\n\nLtac avl_nn' h :=\n  let t := type of h in\n  match type of t with\n   | Prop => avl_nn h\n   | _ => match goal with H : Avl h |- _ => avl_nn H end\n  end.\n\n(** Properties of cardinal *)\n\nLemma bal_cardinal : forall l x r,\n cardinal (bal l x r) = S (cardinal l + cardinal r).\nProof.\n intros l x r; functional induction bal l x r; intros; clearf;\n simpl; auto with arith; romega with *.\nQed.\n\nLemma add_cardinal : forall x s,\n cardinal (add x s) <= S (cardinal s).\nProof.\n induct s x; simpl; auto with arith;\n rewrite bal_cardinal; romega with *.\nQed.\n\nLemma join_cardinal : forall l x r,\n cardinal (join l x r) <= S (cardinal l + cardinal r).\nProof.\n join_tac; clearf; auto with arith.\n - simpl; apply add_cardinal.\n - simpl; destruct X.compare; simpl.\n   * auto with arith.\n   * generalize (bal_cardinal (add x ll) lx lr) (add_cardinal x ll);\n     romega with *.\n   * generalize (bal_cardinal ll lx (add x lr)) (add_cardinal x lr);\n     romega with *.\n - generalize (bal_cardinal ll lx (join lr x (Node rh rl rx rr)))\n  (Hlr x (Node rh rl rx rr)); simpl; romega with *.\n - simpl (S _) in *; generalize (bal_cardinal (join (Node lh ll lx lr) x rl) rx rr).\n   romega with *.\nQed.\n\nLemma split_cardinal_1 : forall x s,\n (cardinal (split x s)#l <= cardinal s)%nat.\nProof.\n intros x s; functional induction split x s; simpl; auto.\n - romega with *.\n - rewrite e1 in IHt0; simpl in *.\n   romega with *.\n - rewrite e1 in IHt0; simpl in *.\n   generalize (@join_cardinal l y rl); romega with *.\nQed.\n\nLemma split_cardinal_2 : forall x s,\n (cardinal (split x s)#r <= cardinal s)%nat.\nProof.\n intros x s; functional induction split x s; simpl; auto.\n - romega with *.\n - rewrite e1 in IHt0; simpl in *.\n   generalize (@join_cardinal rl y r); romega with *.\n - rewrite e1 in IHt0; simpl in *; romega with *.\nQed.\n\n(** * [ocaml_union], an union faithful to the original ocaml code *)\n\nDefinition cardinal2 (s:t*t) := (cardinal s#1 + cardinal s#2)%nat.\n\nLtac ocaml_union_tac :=\n intros; unfold cardinal2; simpl fst in *; simpl snd in *;\n match goal with H: split ?x ?s = _ |- _ =>\n  generalize (split_cardinal_1 x s) (split_cardinal_2 x s);\n  rewrite H; simpl; romega with *\n end.\n\nFunction ocaml_union (s : t * t) { measure cardinal2 s } : t  :=\n match s with\n  | (Leaf, Leaf) => s#2\n  | (Leaf, Node _ _ _ _) => s#2\n  | (Node _ _ _ _, Leaf) => s#1\n  | (Node h1 l1 x1 r1, Node h2 l2 x2 r2) =>\n        if ge_lt_dec h1 h2 then\n          if eq_dec h2 1%I then add x2 s#1 else\n          let (l2',_,r2') := split x1 s#2 in\n             join (ocaml_union (l1,l2')) x1 (ocaml_union (r1,r2'))\n        else\n          if eq_dec h1 1%I then add x1 s#2 else\n          let (l1',_,r1') := split x2 s#1 in\n             join (ocaml_union (l1',l2)) x2 (ocaml_union (r1',r2))\n end.\nProof.\nabstract ocaml_union_tac.\nabstract ocaml_union_tac.\nabstract ocaml_union_tac.\nabstract ocaml_union_tac.\nDefined.\n\nLemma ocaml_union_in : forall s y,\n Ok s#1 -> Avl s#1 -> Ok s#2 -> Avl s#2 ->\n (InT y (ocaml_union s) <-> InT y s#1 \\/ InT y s#2).\nProof.\n intros s; functional induction ocaml_union s; intros y B1 A1 B2 A2;\n  simpl (@fst) in *; simpl (@snd) in *; try clear e0 e1.\n - intuition_in.\n - intuition_in. \n - intuition_in. \n - (* add x2 s#1 *)\n   inv_avl.\n   rewrite (height_0 l2) by (avl_nn' l2; omega_max).\n   rewrite (height_0 r2) by (avl_nn' r2; omega_max).\n   rewrite add_spec; intuition_in.\n - (* join (union (l1,l2')) x1 (union (r1,r2')) *)\n   clear _x _x0. factornode s2.\n   generalize\n    (split_avl s2 x1) (@split_ok s2 x1 B2)\n    (@split_spec1 s2 x1 y B2) (@split_spec2 s2 x1 y B2).\n   rewrite e2; simpl.\n   destruct 1; destruct 1; inv_avl; invtree Ok.\n   rewrite join_spec, IHt0, IHt1; auto.\n   do 2 (intro Eq; rewrite Eq; clear Eq).\n   destruct (X.compare_spec y x1); intuition_in.\n - (* add x1 s#2 *)\n   inv_avl.\n   rewrite (height_0 l1) by (avl_nn' l1; omega_max).\n   rewrite (height_0 r1) by (avl_nn' r1; omega_max).\n   rewrite add_spec; auto; intuition_in.\n - (* join (union (l1',l2)) x1 (union (r1',r2)) *)\n   clear _x _x0. factornode s1.\n   generalize\n    (split_avl s1 x2) (@split_ok s1 x2 B1)\n    (@split_spec1 s1 x2 y B1) (@split_spec2 s1 x2 y B1).\n   rewrite e2; simpl.\n   destruct 1; destruct 1; inv_avl; invtree Ok.\n   rewrite join_spec, IHt0, IHt1; auto.\n   do 2 (intro Eq; rewrite Eq; clear Eq).\n   destruct (X.compare_spec y x2); intuition_in.\nQed.\n\nLemma ocaml_union_bst : forall s,\n Ok s#1 -> Avl s#1 -> Ok s#2 -> Avl s#2 -> Ok (ocaml_union s).\nProof.\n intros s; functional induction ocaml_union s; intros B1 A1 B2 A2;\n  simpl @fst in *; simpl @snd in *; try clear e0 e1;\n  try apply add_ok; auto.\n - (* join (union (l1,l2')) x1 (union (r1,r2')) *)\n clear _x _x0; factornode s2.\n generalize (split_avl s2 x1) (@split_ok _ x1 B2)\n  (@split_spec1 s2 x1)(@split_spec2 s2 x1).\n rewrite e2; simpl.\n destruct 1; destruct 1; intros.\n invtree Ok; inv_avl.\n apply join_ok; auto.\n intro y; rewrite ocaml_union_in, H3; intuition_in.\n intro y; rewrite ocaml_union_in, H4; intuition_in.\n - (* join (union (l1',l2)) x1 (union (r1',r2)) *)\n clear _x _x0; factornode s1.\n generalize (split_avl s1 x2) (@split_ok _ x2 B1)\n  (@split_spec1 s1 x2)(@split_spec2 s1 x2).\n rewrite e2; simpl.\n destruct 1; destruct 1; intros.\n invtree Ok; inv_avl.\n apply join_ok; auto.\n intro y; rewrite ocaml_union_in, H3; intuition_in.\n intro y; rewrite ocaml_union_in, H4; intuition_in.\nQed.\n\nLemma ocaml_union_avl : forall s,\n Avl s#1 -> Avl s#2 -> Avl (ocaml_union s).\nProof.\n intros s; functional induction ocaml_union s;\n  simpl @fst in *; simpl @snd in *; auto_tc.\n intros A1 A2; generalize (@split_avl _ x1 A2); rewrite e2; simpl.\n inv_avl; destruct 1; auto_tc.\n intros A1 A2; generalize (@split_avl _ x2 A1); rewrite e2; simpl.\n inv_avl; destruct 1; auto_tc.\nQed.\n\nLemma ocaml_union_alt : forall s, Ok s#1 -> Avl s#1 -> Ok s#2 -> Avl s#2 ->\n Equal (ocaml_union s) (union s#1 s#2).\nProof.\n red; intros; rewrite ocaml_union_in, union_spec; simpl; intuition.\nQed.\n\n\n(** * [ocaml_subset], a subset faithful to the original ocaml code *)\n\nFunction ocaml_subset (s:t*t) { measure cardinal2 s } : bool :=\n match s with\n  | (Leaf, _) => true\n  | (Node _ _ _ _, Leaf) => false\n  | (Node _ l1 x1 r1, Node _ l2 x2 r2) =>\n     match X.compare x1 x2 with\n      | Eq => ocaml_subset (l1,l2) && ocaml_subset (r1,r2)\n      | Lt => ocaml_subset (Node 0%I l1 x1 Leaf, l2) && ocaml_subset (r1,s#2)\n      | Gt => ocaml_subset (Node 0%I Leaf x1 r1, r2) && ocaml_subset (l1,s#2)\n     end\n end.\n\nProof.\n intros; unfold cardinal2; simpl; abstract romega with *.\n intros; unfold cardinal2; simpl; abstract romega with *.\n intros; unfold cardinal2; simpl; abstract romega with *.\n intros; unfold cardinal2; simpl; abstract romega with *.\n intros; unfold cardinal2; simpl; abstract romega with *.\n intros; unfold cardinal2; simpl; abstract romega with *.\nDefined.\n\nLtac ocaml_subset_tac :=\n simpl in *; invtree Ok; rewrite andb_true_iff;\n match goal with _ : X.compare ?x1 ?x2 = _ |- _ =>\n  destruct (X.compare_spec x1 x2); try discriminate\n end;\n repeat\n  (match goal with H : context [ocaml_subset] |- _ => rewrite H; clear H end);\n unfold Subset; intuition_in;\n match goal with\n  | H : forall a, InT a _ -> InT a ?s |- InT ?a _ =>\n    assert (InT a s) by auto; intuition_in; order\n  | _ => apply IsRoot; order\n end.\n\nLemma ocaml_subset_12 : forall s,\n Ok s#1 -> Ok s#2 ->\n (ocaml_subset s = true <-> Subset s#1 s#2).\nProof.\n intros s; functional induction ocaml_subset s; simpl; intros B1 B2.\n - intuition.\n   red; auto; inversion 1.\n - split; intros; try discriminate.\n   assert (H': In _x1 Leaf) by auto; inversion H'.\n - ocaml_subset_tac.\n - ocaml_subset_tac.\n - ocaml_subset_tac.\nQed.\n\nLemma ocaml_subset_alt : forall s, Ok s#1 -> Ok s#2 ->\n ocaml_subset s = subset s#1 s#2.\nProof.\n intros.\n generalize (ocaml_subset_12 _ H H0). rewrite <- subset_spec by auto.\n destruct ocaml_subset; destruct subset; intuition.\nQed.\n\n\n\n(** [ocaml_compare], a compare faithful to the original ocaml code *)\n\n(** termination of [compare_aux] *)\n\nFixpoint cardinal_e e := match e with\n  | End => 0\n  | More _ s r => S (cardinal s + cardinal_e r)\n end.\n\nLemma cons_cardinal_e : forall s e,\n cardinal_e (cons s e) = cardinal s + cardinal_e e.\nProof.\n induction s; simpl; intros; auto.\n rewrite IHs1; simpl; rewrite <- plus_n_Sm; auto with arith.\nQed.\n\nDefinition cardinal_e_2 e := cardinal_e e#1 + cardinal_e e#2.\n\nFunction ocaml_compare_aux\n (e:enumeration*enumeration) { measure cardinal_e_2 e } : comparison :=\n match e with\n | (End,End) => Eq\n | (End,More _ _ _) => Lt\n | (More _ _ _, End) => Gt\n | (More x1 r1 e1, More x2 r2 e2) =>\n       match X.compare x1 x2 with\n        | Eq => ocaml_compare_aux (cons r1 e1, cons r2 e2)\n        | Lt => Lt\n        | Gt => Gt\n       end\n end.\n\nProof.\nintros; unfold cardinal_e_2; simpl;\nabstract (do 2 rewrite cons_cardinal_e; romega with * ).\nDefined.\n\nDefinition ocaml_compare s1 s2 :=\n ocaml_compare_aux (cons s1 End, cons s2 End).\n\nLocal Hint Constructors L.lt_list.\n\nLemma ocaml_compare_aux_Cmp : forall e,\n Cmp (ocaml_compare_aux e) (flatten_e e#1) (flatten_e e#2).\nProof.\n intros e; functional induction ocaml_compare_aux e; simpl; intros;\n  try constructor; auto;\n  try destruct (X.compare_spec x1 x2); try discriminate; auto.\n reflexivity.\n apply L.cons_CompSpec; trivial. now rewrite <- !cons_1.\nQed.\n\nLemma ocaml_compare_Cmp : forall s1 s2,\n Cmp (ocaml_compare s1 s2) (elements s1) (elements s2).\nProof.\n unfold ocaml_compare; intros.\n assert (H1:=cons_1 s1 End).\n assert (H2:=cons_1 s2 End).\n simpl in *; rewrite <- app_nil_end in *; rewrite <-H1,<-H2.\n apply (@ocaml_compare_aux_Cmp (cons s1 End, cons s2 End)).\nQed.\n\nLemma ocaml_compare_alt : forall s1 s2, Ok s1 -> Ok s2 ->\n ocaml_compare s1 s2 = compare s1 s2.\nProof.\n intros s1 s2 B1 B2.\n generalize (ocaml_compare_Cmp s1 s2)(compare_Cmp s1 s2).\n destruct ocaml_compare; destruct compare; auto; intros; exfalso;\n inversion_clear H; inversion_clear H0; rewrite <- ?eq_Leq in *;\n repeat match goal with\n  | H : L.lt (elements ?s1) (elements ?s2) |- _ =>\n    assert (lt s1 s2) by (exists s1; exists s2; intuition); clear H\n end.\n rewrite H1 in H0. now apply StrictOrder_Irreflexive with s2.\n rewrite H1 in H0. now apply StrictOrder_Irreflexive with s2.\n rewrite H in H0. now apply StrictOrder_Irreflexive with s2.\n apply StrictOrder_Irreflexive with s2. now transitivity s1.\n rewrite H in H0. now apply StrictOrder_Irreflexive with s2.\n apply StrictOrder_Irreflexive with s2. now transitivity s1.\nQed.\n\n\n(** * Equality test *)\n\nDefinition ocaml_equal s1 s2 : bool :=\n match ocaml_compare s1 s2 with\n  | Eq => true\n  | _ => false\n end.\n\nLemma ocaml_equal_alt : forall s1 s2, Ok s1 -> Ok s2 ->\n ocaml_equal s1 s2 = equal s1 s2.\nProof.\nintros; unfold ocaml_equal, equal; rewrite ocaml_compare_alt; auto.\nQed.\n\nLemma ocaml_equal_1 : forall s1 s2, Ok s1 -> Ok s2 ->\n Equal s1 s2 -> ocaml_equal s1 s2 = true.\nProof.\nintros. rewrite ocaml_equal_alt; trivial. now apply equal_spec.\nQed.\n\nLemma ocaml_equal_2 : forall s1 s2,\n ocaml_equal s1 s2 = true -> Equal s1 s2.\nProof.\nunfold ocaml_equal; intros s1 s2 E.\ngeneralize (ocaml_compare_Cmp s1 s2);\n destruct ocaml_compare; auto; try discriminate.\ninversion 1. now apply eq_Leq.\nQed.\n\nEnd OcamlOps.\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/MSetFullAVL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430353105599, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.6775748112804043}}
{"text": "Require Import Setoid.\nRequire Import Lia.\n\nAxiom double_neg : forall P, P <-> ~~P.\nLemma fold_not : forall (P: Prop), (P -> False) <-> ~P. intuition auto. Defined.\nAxiom forall_exists_duality1 : forall {T} (P: T -> Prop), ~ (exists x, P x) <-> (forall x, ~ P x).\nAxiom forall_exists_duality2 : forall {T} (P: T -> Prop), ~ (forall x, P x) <-> (exists x, ~ P x).\nAxiom DeMorgan1 : forall (P Q : Prop), ~(P /\\ Q) <-> (~P \\/ ~Q).\nAxiom DeMorgan2 : forall (P Q : Prop), ~(P \\/ Q) <-> (~P /\\ ~Q).\n\nLtac classical := \n  repeat match goal with\n  | [ H : context[_ -> False] |- _ ] => rewrite (fold_not) in H (* sometimes intuition leaves us with negations like this. *)\n  | [ H : context[~(~ _)]|- _ ] => rewrite <-double_neg in H\n  | [ H : _ |- _ ] => rewrite DeMorgan1 in H\n  | [ H : _ |- _ ] => rewrite DeMorgan2 in H\n  | [ H: _ |- _] => erewrite forall_exists_duality1 in H\n  | [ H: _ |- _] => erewrite forall_exists_duality2 in H\n  | [ H : _ |- context[_ -> False] ] => rewrite (fold_not) (* sometimes intuition leaves us with negations like this. *)\n  | [ H : _ |- context[~(~ _)] ] => rewrite <-double_neg\n  | [ H : _ |- _ ] => rewrite DeMorgan1\n  | [ H : _ |- _ ] => rewrite DeMorgan2\n  | [ H: _ |- _] => erewrite forall_exists_duality1\n  | [ H: _ |- _] => erewrite forall_exists_duality2\n  end; try solve [intuition auto].  \n\nSection LTLdef. \n  Context {T: Type}.\n  Inductive LTL : Type :=\n  injp_ltl : (T -> Prop) -> LTL\n  | false_ltl : LTL\n  | true_ltl : LTL\n  | imp_ltl : LTL -> LTL -> LTL\n  | until_ltl : LTL -> LTL -> LTL\n  | next_ltl : LTL -> LTL.\n  Definition TemInt : Type := nat -> T.\n  Notation \"φ U- ψ\" := (until_ltl φ ψ) (at level 10).\n  Definition from (k: nat): TemInt -> TemInt :=\n      fun ζ n =>\n        ζ (n+k).\n  Notation \"ζ ^^ k\" := (from k ζ) (at level 10).\n\n  Reserved Notation \"ζ ⊨ φ\" (at level 50, no associativity).\n  Fixpoint models (φ : LTL) (ζ : TemInt) {struct φ}: Prop :=\n      match φ with\n      | injp_ltl p =>\n        p (ζ 0)\n      | imp_ltl ψ π =>\n        (~(ζ ⊨ ψ) \\/ (ζ ⊨ π))\n      | next_ltl ψ =>\n        (from 1 ζ) ⊨ ψ\n      | until_ltl ψ π =>\n        (exists (i:nat),\n          ζ ^^ i ⊨ π\n          /\\ (forall j, j < i -> ζ ^^ j ⊨ ψ))\n      | false_ltl =>\n        False\n      | true_ltl =>\n        True\n      end\n  where \"ζ ⊨ φ\" := (models φ ζ).\n\n  Definition not_ltl (φ : LTL) : LTL := imp_ltl φ false_ltl.\n  Definition ev_ltl (φ : LTL): LTL := true_ltl U- φ.\n  Definition always_ltl (φ : LTL): LTL := not_ltl (ev_ltl (not_ltl φ)).\n  Definition and_ltl (ϕ ψ : LTL) : LTL := not_ltl (imp_ltl ϕ (not_ltl ψ)).\n\n\n  Theorem and_good : forall ζ ϕ ψ, ζ ⊨ ϕ /\\ ζ ⊨ ψ <-> ζ ⊨ (and_ltl ϕ ψ).\n  Proof.\n    intros.\n    split.\n    { (* fwd *)\n      intro.\n      unfold  and_ltl,not_ltl.\n      cbn.\n      left.\n      intro.\n      repeat destruct H0; destruct H; auto.\n    }\n    {\n      intro.\n      split.\n      {\n        inversion H;\n        cbn in H0;\n        intuition auto;\n        classical.\n      }\n      {\n        inversion H; cbn in *; intuition auto; classical.\n      }\n    }\n  Defined.\n\n  Lemma ltl_not_good : forall ζ φ, ~ ζ ⊨ φ <-> ζ ⊨ (not_ltl φ).  \n    Proof.\n      (* Very lightly modified from a proof generated by GPT-3/copilot. *)  \n      intros.\n      split.\n      { \n        intro H.\n        unfold not_ltl.\n        lazy.\n        left.\n        intro.\n        repeat destruct H0; destruct H; auto.\n      }\n      {\n        intro.\n        inversion H; cbn in *; intuition auto; classical.\n      }\n    Defined.\n\n  Theorem always_iff_loop_inv : forall (φ : LTL) (ζ : TemInt), \n    ζ ⊨ (always_ltl φ) \n    <-> (exists (i : nat), \n          (forall k, k >= i -> ζ ^^ k ⊨ φ -> ζ ^^ (k+1) ⊨ φ) /\\ (forall (j : nat), j <= i -> ζ ^^ j ⊨ φ)).\n  Proof.\n    intros.\n    split.\n    { \n      intros H.\n      exists 0.\n      split; intros.\n      {\n        simpl in H.\n        classical.\n        destruct H; try solve [intuition auto].\n        specialize (H (k+1)).\n        classical.\n        repeat destruct H; solve [intuition auto].\n      } \n      {\n        inversion H0.\n        simpl in H.\n        classical.\n        destruct H; try solve [intuition auto].\n        specialize (H 0).\n        classical.\n        repeat destruct H; try solve [intuition auto].\n      }\n    } \n    {\n     intros H.  \n     left.\n     simpl.\n     destruct H as [i [Hpres Hinit]].\n     simpl.\n     repeat (progress classical || intro).\n     left.\n     split; [|solve[intuition auto]].\n     Require Import Coq.Arith.Compare_dec.\n     pose proof (lt_eq_lt_dec x i) as Hcompxi.\n     repeat match goal with\n            | [ H : context[{_} + {_}] |- _] => destruct H as [H | H]\n            end; try solve [eapply Hinit;lia].\n     {\n      assert (Hstronger : forall n, ζ ^^ (i+n) ⊨ φ).\n      {\n        induction n.\n        { \n          unshelve erewrite (_ : i + 0 = i). lia.\n          eapply Hinit.\n          auto.\n        }\n        { \n          unshelve erewrite (_ : i + S n = (i + n) + 1). lia.\n          eapply Hpres.\n          lia.\n          auto.\n        }\n      }\n      remember (x - i) as diff.\n      unshelve erewrite (_ : x = i + diff); try solve[lia].\n      auto.\n     }\n    }\nDefined.\nEnd LTLdef.\n\nRecord Mealy : Type := mkMealy {\n                           Σ : Type\n                         ; Q : Type\n                         ; δ : Q -> Σ -> Q * Σ\n                         ; Q₀ : Q\n                         }.\n\nFixpoint MealyTrace' (M : Mealy) (I : nat -> Σ M) (n : nat) {struct n}: (Q M) * (Σ M) :=\n    match n with\n    | 0 => (δ M) (Q₀ M) (I 0)\n    | S n' => let (Q', _) := MealyTrace' M I n' in\n             (δ M) Q' (I n)\n    end.\n\nDefinition MealyTrace (M : Mealy) (I : nat -> Σ M) : @TemInt (Q M * Σ M) :=\n    fun n => MealyTrace' M I n.", "meta": {"author": "jaykru", "repo": "mc-coq", "sha": "3a147aaa27ec7c0ff3b067fc7a27806f10aff8d7", "save_path": "github-repos/coq/jaykru-mc-coq", "path": "github-repos/coq/jaykru-mc-coq/mc-coq-3a147aaa27ec7c0ff3b067fc7a27806f10aff8d7/mc2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6774336935820097}}
{"text": "From Coq Require Import Ring.\nFrom stdpp Require Import base.\nFrom BY Require Export Hierarchy.Definitions.\nFrom BY.Hierarchy Require Import Group AbelianGroup Monoid.\n\nSection Ring.\n  Local Open Scope ring_scope.\n\n  Class Ring A `{Equiv A, Op1 A, Op2 A, Id1 A, Id2 A, Inv1 A} :=\n    {\n      ring_ab_grp :> @AbelianGroup _ _ (+) 0 (-);\n      ring_mon :> @Monoid _ _ [*] 1;\n      ring_distr_l :> LeftDistr (≡) [*] (+);\n      ring_distr_r :> RightDistr (≡) [*] (+)\n    }.\n\n  Class RingCongruence `{Ring A} (rel : relation A) :=\n    {\n      ring_cong_equiv :> Equivalence rel;\n      ring_cong_op1_proper :> Proper (rel ==> rel ==> rel) (+);\n      ring_cong_op2_proper :> Proper (rel ==> rel ==> rel) [*];\n      ring_cong_inv_proper :> Proper (rel ==> rel) (-)\n    }.\n\n  Context\n    `{Ring A}.\n  Local Instance : @Group A _ (+) 0 (-). sub_class_tac. Qed.\n\n  (* Instance : @AbelianGroup A _ (+) 0 (-) := _. *)\n\n  (* split. *)\n  (* repeat split; try apply _; try exact _. exact _. *)\n\n  (* Global Instance mul_1_r : @RightId _ _ ring_op 1 := right_identity. *)\n  (* Global Instance mul_1_l : @LeftIdentity _ _ ring_op 1 := left_identity. *)\n\n  (* Global Instance mul_assoc : @Associative _ ring_op := associative. *)\n\n  (* Global Instance mul_add_distr_l : LeftDistributive := left_distributive. *)\n  (* Global Instance mul_add_distr_r : RightDistributive := right_distributive. *)\n\n  Lemma mul_0_r : forall x : A, x * 0 ≡ 0.\n  Proof.\n    intros.\n    setoid_replace (x * 0) with (x * 0 + 0) by (symmetry; apply (right_id 0 (+))).\n    setoid_replace 0 with (x * 0 - x * 0) at 3 by (symmetry; apply (right_inv 0 (-) (+))).\n    setoid_rewrite (assoc (+)).\n    setoid_rewrite <- (left_distr [*] (+)).\n    setoid_rewrite (left_id 0 (+)).\n    apply (right_inv 0 (-) (+)).\n  Qed.\n\n  Lemma mul_0_l : forall x, 0 * x ≡ 0.\n  Proof.\n    intros.\n    setoid_replace (0 * x) with (0 * x + 0) by (symmetry; apply (right_id 0 (+))).\n    setoid_replace 0 with (0 * x - 0 * x) at 3 by (symmetry; apply (right_inv 0 (-) (+))).\n    setoid_rewrite (assoc (+)).\n    setoid_rewrite <- (right_distr [*] (+)).\n    setoid_rewrite (left_id 0 (+)).\n    apply (right_inv 0 (-) (+)).\n  Qed.\n\n  Definition ring_opp_unique_l : forall x y : A, y + x ≡ 0 -> y ≡ - x := grp_inv_unique_l.\n\n  Lemma opp_mul_l : forall x y, - (x * y) ≡ - x * y.\n  Proof.\n    intros. symmetry.\n    apply ring_opp_unique_l.\n    rewrite <- (right_distr [*] (+)).\n    setoid_rewrite (left_inv 0 (-) (+)).\n    apply mul_0_l.\n  Qed.\n\n  Lemma opp_mul_r : forall x y, - (x * y) ≡ x * - y.\n  Proof.\n    intros. symmetry.\n    apply ring_opp_unique_l.\n    rewrite <- (left_distr [*] (+)).\n    setoid_rewrite (left_inv 0 (-) (+)).\n    apply mul_0_r.\n  Qed.\n\nEnd Ring.\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/Hierarchy/Ring.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6774336842534766}}
{"text": "(** * Tactics: More Basic Tactics *)\n\n(** This chapter introduces several additional proof strategies\n    and tactics that allow us to begin proving more interesting\n    properties of functional programs.  We will see:\n\n    - how to use auxiliary lemmas in both \"forward-style\" and\n      \"backward-style\" proofs;\n    - how to reason about data constructors (in particular, how to use\n      the fact that they are injective and disjoint);\n    - how to strengthen an induction hypothesis (and when such\n      strengthening is required); and\n    - more details on how to reason by case analysis. *)\n\nRequire Export Poly.\n\n(* ################################################################# *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    _exactly_ the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n\n(** Here, we could finish with \"[rewrite -> eq2.  reflexivity.]\" as we\n    have done several times before.  We can achieve the same effect in\n    a single step by using the [apply] tactic instead: *)\n\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** You may find it instructive to experiment with this proof\n    and see if there is a way to complete it using just [rewrite]\n    instead of [apply]. *)\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] that binds some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex)  *)\n(** Complete the following proof without using [simpl]. *)\n\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 3 = true ->\n     oddb 4 = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal exactly -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  simpl.\n\n(** Here we cannot use [apply] directly, but we can use the [symmetry]\n    tactic, which switches the left and right sides of an equality in\n    the goal. *)\n\n  symmetry.\n  simpl. (* (This [simpl] is optional, since [apply] will perform\n            simplification first, if needed.) *)\n  apply H.  Qed.\n\n(** **** Exercise: 3 stars (apply_exercise1)  *)\n(** (_Hint_: You can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [SearchAbout] is\n    your friend.) *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (apply_rewrite)  *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  What are the situations where both can usefully be\n    applied?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(* ################################################################# *)\n(** * The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might like to pull it out\n    as a lemma recording, once and for all, the fact that equality is\n    transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to prove the above\n    example.  However, to do this we need a slight refinement of the\n    [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n\n(** If we simply tell Coq [apply trans_eq] at this point, it can\n    tell (by matching the goal against the conclusion of the lemma)\n    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and\n    [o] with [[e,f]].  However, the matching process doesn't determine\n    an instantiation for [m]: we have to supply one explicitly by\n    adding [with (m:=[c,d])] to the invocation of [apply]. *)\n\n  apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2.   Qed.\n\n(** Actually, we usually don't have to include the name [m] in\n    the [with] clause; Coq is often smart enough to figure out which\n    instantiation we're giving. We could instead write: [apply\n    trans_eq with [c;d]]. *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * The [inversion] Tactic *)\n\n(** Recall the definition of natural numbers:\n\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n\n    It is obvious from this definition that every number has one of\n    two forms: either it is the constructor [O] or it is built by\n    applying the constructor [S] to another number.  But there is more\n    here than meets the eye: implicit in the definition (and in our\n    informal understanding of how datatype declarations work in other\n    programming languages) are two more facts:\n\n    - The constructor [S] is _injective_.  That is, if [S n = S m], it\n      must be the case that [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n]. \n\n    Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor\n    is injective and [nil] is different from every non-empty list.\n    For booleans, [true] and [false] are different.  (Since neither\n    [true] nor [false] take any arguments, their injectivity is not \n    interesting.)  And so on. *)\n\n(** Coq provides a tactic called [inversion] that allows us to\n    exploit these principles in proofs. To see how to use it, let's\n    show explicitly that the [S] constructor is injective: *)\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n\n(** By writing [inversion H] at this point, we are asking Coq to\n    generate all equations that it can infer from [H] as additional\n    hypotheses, replacing variables in the goal as it goes. In the\n    present example, this amounts to adding a new hypothesis [H1 : n =\n    m] and replacing [n] by [m] in the goal. *)\n\n  inversion H.\n  reflexivity.  \nQed.\n\n(** Here's a more interesting example that shows how multiple\n    equations can be derived at once. *)\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity. Qed.\n\n(** We can name the equations that [inversion] generates with an \n    [as ...] clause: *)\n\nTheorem inversion_ex2 : forall (n m : nat),\n  [n] = [m] ->\n  n = m.\nProof.\n  intros n m H. inversion H as [Hnm]. reflexivity.  Qed.\n\n(** **** Exercise: 1 star (inversion_ex3)  *)\nExample inversion_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** When used on a hypothesis involving an equality between\n    _different_ constructors (e.g., [S n = O]), [inversion] solves the\n    goal immediately.  Consider the following proof: *)\n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  intros n.\n\n(** We can proceed by case analysis on [n]. The first case is\n    trivial. *)\n\n  destruct n as [| n'].\n  - (* n = 0 *)\n    intros H. reflexivity.\n\n(** However, the second one doesn't look so simple: assuming\n    [beq_nat 0 (S n') = true], we must show [S n' = 0], but the latter\n    clearly contradictory!  The way forward lies in the assumption.\n    After simplifying the goal state, we see that [beq_nat 0 (S n') =\n    true] has become [false = true]: *)\n\n  - (* n = S n' *)\n    simpl.\n\n(** If we use [inversion] on this hypothesis, Coq notices that\n    the subgoal we are working on is impossible, and therefore removes\n    it from further consideration. *)\n\n    intros H. inversion H. Qed.\n\n(** This is an instance of a logical principle known as the _principle\n    of explosion_, which asserts that a contradictory hypothesis\n    entails anything, even false things! *)\n\nTheorem inversion_ex4 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem inversion_ex5 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. inversion contra. Qed.\n\n(** If you find the principle of explosion confusing, remember\n    that these proofs are not actually showing that the conclusion of\n    the statement holds.  Rather, they are arguing that, if the\n    nonsensical situation described by the premise did somehow arise,\n    then the nonsensical conclusion would follow.  We'll explore the\n    principle of explosion of more detail in the next chapter. *)\n\n(** **** Exercise: 1 star (inversion_ex6)  *)\nExample inversion_ex6 : forall (X : Type)\n                          (x y z : X) (l j : list X),\n  x :: y :: l = [] ->\n  y :: l = z :: j ->\n  x = z.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** To summarize this discussion, suppose [H] is a hypothesis in the\n    context or a previously proven lemma of the form\n\n        c a1 a2 ... an = d b1 b2 ... bm\n\n    for some constructors [c] and [d] and arguments [a1 ... an] and\n    [b1 ... bm].  Then [inversion H] has the following effect:\n\n    - If [c] and [d] are the same constructor, then, by the\n      injectivity of this constructor, we know that [a1 = b1], [a2 =\n      b2], etc.  The [inversion H] adds these facts to the context and\n      tries to use them to rewrite the goal.\n\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory, and the current goal doesn't have to be\n      considered at all.  In this case, [inversion H] marks the\n      current goal as completed and pops it off the goal stack. *)\n\n(** The injectivity of constructors allows us to reason that\n    [forall (n m : nat), S n = S m -> n = m].  The converse of this\n    implication is an instance of a more general fact about both\n    constructors and functions, which we will find useful in a few\n    places below: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic [simpl in H] performs simplification in\n    the hypothesis named [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     beq_nat (S n) (S m) = b  ->\n     beq_nat n m = b.\nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, [apply L in H] matches some conditional statement\n    [L] (of the form [L1 -> L2], say) against a hypothesis [H] in the\n    context.  However, unlike ordinary [apply] (which rewrites a goal\n    matching [L2] into a subgoal [L1]), [apply L in H] matches [H]\n    against [L1] and, if successful, replaces it with [L2].\n\n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\": from [L1 -> L2] and a hypothesis matching [L1], it\n    produces a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\": it says that if we know [L1->L2] and we are\n    trying to prove [L2], it suffices to prove [L1].\n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\nTheorem silly3' : forall (n : nat),\n  (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->\n  true = beq_nat n 5  ->\n  true = beq_nat (S (S n)) 7.\nProof.\n  intros n eq H.\n  symmetry in H. apply eq in H. symmetry in H.\n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, idiomatic use of Coq tends to favor backward reasoning,\n    but in some situations the forward style can be easier to think\n    about.  *)\n\n(** **** Exercise: 3 stars, recommended (plus_n_n_injective)  *)\n(** Practice using \"in\" variants in this exercise.  (Hint: use\n    [plus_n_Sm].) *)\n\nTheorem plus_n_n_injective : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Varying the Induction Hypothesis *)\n\n(** Sometimes it is important to control the exact form of the\n    induction hypothesis when carrying out inductive proofs in Coq.\n    In particular, we need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose\n    we want to show that the [double] function is injective -- i.e.,\n    that it maps different arguments to different results:\n\n    Theorem double_injective: forall n m, \n      double n = double m -> n = m.\n\n    The way we _start_ this proof is a bit delicate: if we begin with\n\n      intros n. induction n.\n\n    all is well.  But if we begin it with\n\n      intros n m. induction n.\n\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  - (* n = O *) simpl. intros eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n  - (* n = S n' *) intros eq. destruct m as [| m'].\n    + (* m = O *) inversion eq.\n    + (* m = S m' *) apply f_equal.\n\n(** At this point, the induction hypothesis, [IHn'], does _not_ give us\n    [n' = m'] -- there is an extra [S] in the way -- so the goal is\n    not provable. *)\n\n      Abort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context --\n    intuitively, we have told Coq, \"Let's consider some particular [n]\n    and [m]...\" and we now have to prove that, if [double n = double\n    m] for _these particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove, for\n    _all_ [n], that the proposition\n\n      - [P n] = \"if [double n = double m], then [n = m]\"\n\n    holds, by showing\n\n      - [P O]\n\n         (i.e., \"if [double O = double m] then [O = m]\") and\n\n      - [P n -> P (S n)]\n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: it says that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help at all with proving\n    [R]!  (If we tried to prove [R] from [Q], we would start with\n    something like \"Suppose [double (S n) = 10]...\" but then we'd be\n    stuck: knowing that [double (S n)] is [10] tells us nothing about\n    whether [double n] is [10], so [Q] is useless.) *)\n\n(** Trying to carry out this proof by induction on [n] when [m] is\n    already in the context doesn't work because we are then trying to\n    prove a relation involving _every_ [n] but just a _single_ [m]. *)\n\n(** The successful proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  - (* n = O *) simpl. intros m eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n\n  - (* n = S n' *) simpl.\n\n(** Notice that both the goal and the induction hypothesis are\n    different this time: the goal asks us to prove something more\n    general (i.e., to prove the statement for _every_ [m]), but the IH\n    is correspondingly more flexible, allowing us to choose any [m] we\n    like when we apply the IH. *)\n\n    intros m eq.\n\n(** Now we've chosen a particular [m] and introduced the assumption\n    that [double n = double m].  Since we are doing a case analysis on\n    [n], we also need a case analysis on [m] to keep the two \"in sync.\" *)\n\n    destruct m as [| m'].\n    + (* m = O *) simpl.\n\n(** The 0 case is trivial: *)\n\n      inversion eq.\n\n    + (* m = S m' *)\n      apply f_equal.\n\n(** At this point, since we are in the second branch of the [destruct\n    m], the [m'] mentioned in the context is the predecessor of the\n    [m] we started out talking about.  Since we are also in the [S]\n    branch of the induction, this is perfect: if we instantiate the\n    generic [m] in the IH with the current [m'] (this instantiation is\n    performed automatically by the [apply] in the next step), then\n    [IHn'] gives us exactly what we need to finish the proof. *)\n\n      apply IHn'. inversion eq. reflexivity. Qed.\n\n(** What you should take away from all this is that we need to be\n    careful about using induction to try to prove something too\n    specific: To prove a property of [n] and [m] by induction on [n],\n    it is sometimes important to leave [m] generic. *)\n\n(** The following exercise requires the same pattern. *)\n\n(** **** Exercise: 2 stars (beq_nat_true)  *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (beq_nat_true_informal)  *)\n(** Give a careful informal proof of [beq_nat_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** The strategy of doing fewer [intros] before an [induction] to\n    obtain a more general IH doesn't always work by itself; sometimes\n    some _rearrangement_ of quantified variables is needed.  Suppose,\n    for example, that we wanted to prove [double_injective] by\n    induction on [m] instead of [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  - (* m = O *) simpl. intros eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *) apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (If we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce [n]\n    for us!)  *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    works, but it's not nice: We don't want to have to twist the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them!  Rather we want to state them in the clearest and\n    most natural way. *)\n\n(** What we can do instead is to first introduce all the quantified\n    variables and then _re-generalize_ one or more of them,\n    selectively taking variables out of the context and putting them\n    back at the beginning of the goal.  The [generalize dependent]\n    tactic does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m.\n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros n eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *) apply f_equal.\n      apply IHm'. inversion eq. reflexivity. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n    _Theorem_: For any nats [n] and [m], if [double n = double m], then\n      [n = m].\n\n    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n      any [n], if [double n = double m] then [n = m].\n\n      - First, suppose [m = 0], and suppose [n] is a number such\n        that [double n = double m].  We must show that [n = 0].\n\n        Since [m = 0], by the definition of [double] we have [double n =\n        0].  There are two cases to consider for [n].  If [n = 0] we are\n        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']\n        for some [n'], we derive a contradiction: by the definition of\n        [double], we can calculate [double n = S (S (double n'))], but\n        this contradicts the assumption that [double n = 0].\n\n      - Second, suppose [m = S m'] and that [n] is again a number such\n        that [double n = double m].  We must show that [n = S m'], with\n        the induction hypothesis that for every number [s], if [double s =\n        double m'] then [s = m'].\n\n        By the fact that [m = S m'] and the definition of [double], we\n        have [double n = S (S (double m'))].  There are two cases to\n        consider for [n].\n\n        If [n = 0], then by definition [double n = 0], a contradiction.\n\n        Thus, we may assume that [n = S n'] for some [n'], and again by\n        the definition of [double] we have [S (S (double n')) =\n        S (S (double m'))], which implies by inversion that [double n' =\n        double m'].  Instantiating the induction hypothesis with [n'] thus\n        allows us to conclude that [n' = m'], and it follows immediately\n        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just\n        what we wanted to show. [] *)\n\n(** Before we close this section and move on to some exercises,\n    let's digress briefly and use [beq_nat_true] to prove a similar\n    property of identifiers that we'll need in later chapters: *) \n\nTheorem beq_id_true : forall x y,\n  beq_id x y = true -> x = y.\nProof.\n  intros [m] [n]. simpl. intros H.\n  assert (H' : m = n). { apply beq_nat_true. apply H. }\n  rewrite H'. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, recommended (gen_dep_practice)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     nth_error l n = None.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ################################################################# *)\n(** * Unfolding Definitions *)\n\n(** It sometimes happens that we need to manually unfold a Definition\n    so that we can manipulate its right-hand side.  For example, if we\n    define... *)\n\nDefinition square n := n * n.\n\n(** ... and try to prove a simple fact about [square]... *)\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\n  simpl.\n\n(** ... we get stuck: [simpl] doesn't simplify anything at this point,\n    and since we haven't proved any other facts about [square], there\n    is nothing we can [apply] or [rewrite] with.\n\n    To make progress, we can manually [unfold] the definition of\n    [square]: *)\n\n  unfold square.\n\n(** Now we have plenty to work with: both sides of the equality are\n    expressions involving multiplication, and we have lots of facts\n    about multiplication at our disposal.  In particular, we know that\n    it is commutative and associative, and from these facts it is not\n    hard to finish the proof. *)\n  \n  rewrite mult_assoc.\n  assert (H : n * m * n = n * n * m).\n  { rewrite mult_comm. apply mult_assoc. }\n  rewrite H. rewrite mult_assoc. reflexivity.\nQed.\n\n(** At this point, a deeper discussion of unfolding and simplification\n    is in order.\n\n    You may already have observed that tactics like [simpl],\n    [reflexivity], and [apply] will often unfold the definitions of\n    functions automatically when this allows them to make progress.  For\n    example, if we define [foo m] to be the constant [5]... *)\n\nDefinition foo (x: nat) := 5.\n\n(** then the [simpl] in the following proof (or the [reflexivity], if\n    we omit the [simpl]) will unfold [foo m] to [(fun x => 5) m] and\n    then further simplify this expression to just [5]. *)\n\nFact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.\nProof.\n  intros m.\n  simpl.\n  reflexivity.\nQed.\n\n(** However, this automatic unfolding is rather conservative.  For\n    example, if we define a slightly more complicated function\n    involving a pattern match... *)\n\nDefinition bar x :=\n  match x with\n  | O => 5\n  | S _ => 5\n  end.\n\n(** ...then the analogous proof will get stuck: *)\n\nFact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  simpl. (* Does nothing! *)\nAbort.\n\n(** The reason that [simpl] doesn't make progress here is that it\n    notices that, after tentatively unfolding [bar m], it is left with\n    a match whose scrutinee, [m], is a variable, so the [match] cannot\n    be simplified further.  (It is not smart enough to notice that the\n    two branches of the [match] are identical.)  So it gives up on\n    unfolding [bar m] and leaves it alone.  Similarly, tentatively\n    unfolding [bar (m+1)] leaves a [match] whose scrutinee is a\n    function application (that, itself, cannot be simplified, even\n    after unfolding the definition of [+]), so [simpl] leaves it\n    alone.\n\n    At this point, there are two ways to make progress.  One is to use\n    [destruct m] to break the proof into two cases, each focusing on a\n    more concrete choice of [m] ([O] vs [S _]).  In each case, the\n    [match] inside of [bar] can now make progress, and the proof is\n    easy to complete. *)\n\nFact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  destruct m.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(** This approach works, but it depends on our recognizing that the\n    [match] hidden inside [bar] is what was preventing us from making\n    progress.\n\n    A more straightforward way to make progress is to explicitly tell\n    Coq to unfold [bar]. *)\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n\n(** Now it is apparent that we are stuck on the [match] expressions on\n    both sides of the [=], and we can use [destruct] to finish the\n    proof without thinking too hard. *)\n\n  destruct m.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where [destruct] is used to\n    perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (beq_nat n 3).\n    - (* beq_nat n 3 = true *) reflexivity.\n    - (* beq_nat n 3 = false *) destruct (beq_nat n 5).\n      + (* beq_nat n 5 = true *) reflexivity.\n      + (* beq_nat n 5 = false *) reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (beq_nat n 3) then ... else ...].  But either\n    [n] is equal to [3] or it isn't, so we can use [destruct (beq_nat\n    n 3)] to let us reason about the two cases.\n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c]. *)\n\n(** **** Exercise: 3 stars, optional (combine_split)  *)\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** However, [destruct]ing compound expressions requires a bit of\n    care, as such [destruct]s can sometimes erase information we need\n    to complete a proof. *)\n(** For example, suppose we define a function [sillyfun1] like\n    this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** Now suppose that we want to convince Coq of the (rather\n    obvious) fact that [sillyfun1 n] yields [true] only when [n] is\n    odd.  By analogy with the proofs we did with [sillyfun] above, it\n    is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAbort.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution performed by [destruct] is too brutal -- it threw\n    away every occurrence of [beq_nat n 3], but we need to keep some\n    memory of this expression and how it was destructed, because we\n    need to be able to reason that, since [beq_nat n 3 = true] in this\n    branch of the case analysis, it must be that [n = 3], from which\n    it follows that [n] is odd.\n\n    What we would really like is to substitute away all existing\n    occurences of [beq_nat n 3], but at the same time add an equation\n    to the context that records which case we are in.  The [eqn:]\n    qualifier allows us to introduce such an equation, giving it a\n    name that we choose. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got\n     stuck above, except that the context contains an extra\n     equality assumption, which is exactly what we need to\n     make progress. *)\n    - (* e3 = true *) apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    - (* e3 = false *)\n     (* When we come to the second equality test in the body\n        of the function we are reasoning about, we can use\n        [eqn:] again in the same way, allow us to finish the\n        proof. *)\n      destruct (beq_nat n 5) eqn:Heqe5.\n        + (* e5 = true *)\n          apply beq_nat_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + (* e5 = false *) inversion eq.  Qed.\n\n(** **** Exercise: 2 stars (destruct_eqn_practice)  *)\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Review *)\n\n(** We've now seen many of Coq's most fundamental tactics.  We'll\n    introduce a few more in the coming chapters, and later on we'll\n    see some more powerful _automation_ tactics that make Coq help us\n    with low-level details.  But basically we've got what we need to\n    get work done.\n\n    Here are the ones we've seen:\n\n      - [intros]: move hypotheses/variables from goal to context\n\n      - [reflexivity]: finish the proof (when the goal looks like [e =\n        e])\n\n      - [apply]: prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: apply a hypothesis, lemma, or constructor to\n        a hypothesis in the context (forward reasoning)\n\n      - [apply... with...]: explicitly specify values for variables\n        that cannot be determined by pattern matching\n\n      - [simpl]: simplify computations in the goal\n\n      - [simpl in H]: ... or a hypothesis\n\n      - [rewrite]: use an equality hypothesis (or lemma) to rewrite\n        the goal\n\n      - [rewrite ... in H]: ... or a hypothesis\n\n      - [symmetry]: changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]: changes a hypothesis of the form [t=u] into\n        [u=t]\n\n      - [unfold]: replace a defined constant by its right-hand side in\n        the goal\n\n      - [unfold... in H]: ... or a hypothesis\n\n      - [destruct... as...]: case analysis on values of inductively\n        defined types\n\n      - [destruct... eqn:...]: specify the name of an equation to be\n        added to the context, recording the result of the case\n        analysis\n\n      - [induction... as...]: induction on values of inductively\n        defined types\n\n      - [inversion]: reason by injectivity and distinctness of\n        constructors\n\n      - [assert (H: e)] (or [assert (e) as H]): introduce a \"local\n        lemma\" [e] and call it [H]\n\n      - [generalize dependent x]: move the variable [x] (and anything\n        else that depends on it) from the context back to an explicit\n        hypothesis in the goal formula *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (beq_nat_sym)  *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Proof:\n   (* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine)  *)\n(** We proved, in an exercise above, that for all lists of pairs,\n    [combine] is the inverse of [split].  How would you formalize the\n    statement that [split] is the inverse of [combine]?  When is this\n    property true?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?) *)\n\nDefinition split_combine_statement : Prop \n  (* (\"[: Prop]\" means that we are giving a name to a \n     logical proposition here.) *)\n  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.\n\nTheorem split_combine : split_combine_statement.\nProof.\n(* FILL IN HERE *) Admitted.\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise)  *)\n(** This one is a bit challenging.  Pay attention to the form of your\n    induction hypothesis. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge)  *)\n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n\n      forallb evenb [0;2;4;5] = false\n\n      forallb (beq_nat 5) [] = true\n\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n\n      existsb (beq_nat 5) [0;2;3;6] = false\n\n      existsb (andb true) [true;true;false] = true\n\n      existsb oddb [1;0;0;0;0;3] = true\n\n      existsb evenb [] = false\n\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n\n    Finally, prove a theorem [existsb_existsb'] stating that\n    [existsb'] and [existsb] have the same behavior. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** $Date: 2016-09-20 23:50:11 +0900 (2016年09月20日 (火)) $ *)\n\n\n", "meta": {"author": "hkrsnd", "repo": "coq", "sha": "199cec72dd10c5b08b32f4bd14679a1b544d758f", "save_path": "github-repos/coq/hkrsnd-coq", "path": "github-repos/coq/hkrsnd-coq/coq-199cec72dd10c5b08b32f4bd14679a1b544d758f/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936484231889, "lm_q2_score": 0.8840392756357327, "lm_q1q2_score": 0.6774336818762987}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) : natural := plus Zero lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_90_mult_zero/goal33conj53_coqofml_GkKLGp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.677433681840263}}
{"text": "Require Import prosa.classic.util.all.\nRequire Import prosa.classic.model.arrival.basic.task prosa.classic.model.arrival.basic.job prosa.classic.model.arrival.basic.task_arrival.\nRequire Import prosa.classic.model.schedule.global.basic.schedule.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.\n\n(* Definition of response-time bound and some simple lemmas. *)\nModule ResponseTime.\n\n  Import Schedule SporadicTaskset TaskArrival.\n  \n  Section ResponseTimeBound.\n\n    Context {sporadic_task: eqType}.\n    Context {Job: eqType}.\n    Variable job_arrival: Job -> time.\n    Variable job_cost: Job -> time.\n    Variable job_task: Job -> sporadic_task.\n\n    (* Consider any job arrival sequence... *)\n    Variable arr_seq: arrival_sequence Job.\n\n    (* ...and any multiprocessor schedule of these jobs. *)\n    Context {num_cpus : nat}.\n    Variable sched: schedule Job num_cpus.\n\n    (* For simplicity, let's define some local names.*)\n    Let job_has_completed_by := completed job_cost sched.\n\n    Section Definitions.\n      \n      (* Given a task tsk...*)\n      Variable tsk: sporadic_task.\n\n      (* ... we say that R is a response-time bound of tsk in this schedule ... *)\n      Variable R: time.\n\n      (* ... iff any job j of tsk in this arrival sequence has completed by (job_arrival j + R). *)\n      Definition is_response_time_bound_of_task :=\n        forall j,\n          arrives_in arr_seq j ->\n          job_task j = tsk ->\n          job_has_completed_by j (job_arrival j + R).\n\n    End Definitions.\n    \n    Section BasicLemmas.\n\n      (* Assume that jobs dont execute after completion. *)\n      Hypothesis H_completed_jobs_dont_execute:\n        completed_jobs_dont_execute job_cost sched.\n\n      Section SpecificJob.\n\n        (* Then, for any job j ...*)\n        Variable j: Job.\n        Hypothesis H_j_arrives: arrives_in arr_seq j.\n\n        (* ...with response-time bound R in this schedule, ... *)\n        Variable R: time.\n        Hypothesis response_time_bound:\n          job_has_completed_by j (job_arrival j + R). \n\n        (* ...the service received by j at any time t' after its response time is 0. *)\n        Lemma service_after_job_rt_zero :\n          forall t',\n            t' >= job_arrival j + R ->\n            service_at sched j t' = 0.\n        Proof.\n          rename response_time_bound into RT,\n                 H_completed_jobs_dont_execute into EXEC; ins.\n          unfold is_response_time_bound_of_task, completed,\n                 completed_jobs_dont_execute in *.\n          apply/eqP; rewrite -leqn0.\n          eapply completion_monotonic in RT; eauto 2.\n          apply completed_implies_not_scheduled in RT; eauto 2.\n            by move: RT; rewrite not_scheduled_no_service; move => /eqP RT; rewrite RT.\n        Qed.\n\n        (* The same applies for the cumulative service of job j. *)\n        Lemma cumulative_service_after_job_rt_zero :\n          forall t' t'',\n            t' >= job_arrival j + R ->\n            \\sum_(t' <= t < t'') service_at sched j t = 0.\n        Proof.\n          ins; apply/eqP; rewrite -leqn0.\n          rewrite big_nat_cond; rewrite -> eq_bigr with (F2 := fun i => 0);\n            first by rewrite big_const_seq iter_addn mul0n addn0 leqnn.\n          intro i; rewrite andbT; move => /andP [LE _].\n          by rewrite service_after_job_rt_zero;\n            [by ins | by apply leq_trans with (n := t')].\n        Qed.\n\n      End SpecificJob.\n\n      Section AllJobs.\n\n        (* Consider any task tsk ...*)\n        Variable tsk: sporadic_task.\n\n        (* ... for which a response-time bound R is known. *)\n        Variable R: time.\n        Hypothesis response_time_bound:\n          is_response_time_bound_of_task tsk R.\n\n        (* Then, for any job j of this task, ...*)\n        Variable j: Job.\n        Hypothesis H_j_arrives: arrives_in arr_seq j.\n        Hypothesis H_job_of_task: job_task j = tsk.\n\n        (* ...the service received by job j at any time t' after the response time is 0. *)\n        Lemma service_after_task_rt_zero :\n          forall t',\n            t' >= job_arrival j + R ->\n            service_at sched j t' = 0.\n        Proof.\n          by ins; apply service_after_job_rt_zero with (R := R); [apply response_time_bound |].\n        Qed.\n\n        (* The same applies for the cumulative service of job j. *)\n        Lemma cumulative_service_after_task_rt_zero :\n          forall t' t'',\n            t' >= job_arrival j + R ->\n            \\sum_(t' <= t < t'') service_at sched j t = 0.\n        Proof.\n          by ins; apply cumulative_service_after_job_rt_zero with (R := R);\n            first by apply response_time_bound. \n        Qed.\n\n      End AllJobs.\n\n    End BasicLemmas.\n\n  End ResponseTimeBound.\n\nEnd ResponseTime.", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/classic/model/schedule/global/response_time.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6774036372726362}}
{"text": "(*****************************************************************\n\n Colimits in self enriched categories\n\n We construct colimits in self enriched categories. Copowers in\n the self enriched category come from the tensor in the monoidal\n category.\n\n To show how the construction of colimits works, we show how to\n construct an initial object in the self-enriched category Suppose\n that `V` is a symmetric monoidal closed category and let `x` be\n an initial object in `V`. We want to show that `x` also is an\n initial object in the enriched sense. This means that for all\n objects `y`, we must show that `x ⊸ y` is terminal in `V`. So,\n we must show that for every `w` the type `w --> x ⊸ y` is\n contractible.\n\n Since `⊸` is right adjoint to `⊗`, the types `w --> x ⊸ y` and\n `w ⊗ x --> y` are equivalent. As such, it suffices to show that\n `w ⊗ x --> y` is contractible. This is equivalent to `w ⊗ x`\n being an initial object, so it suffices to show that `w ⊗ x` is\n initial. Since `V` is monoidal closed, we know that the functor\n `x ↦ w ⊗ x` is a left adjoint, and thus it preserves initial\n objects. Since `x` is initial, we also get that `w ⊗ x` is\n initial, so we conclude that `V` has an initial object in the\n enriched sense.\n\n Contents\n 1. Initial objects\n 2. Binary coproducts\n 3. Coequalizers\n 4. Copowers\n 5. Type indexed coproducts\n\n *****************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Adjunctions.Core.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Enrichment.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Examples.SelfEnriched.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Colimits.EnrichedInitial.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Colimits.EnrichedBinaryCoproducts.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Colimits.EnrichedCoproducts.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Colimits.EnrichedCoequalizers.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Colimits.EnrichedCopowers.\nRequire Import UniMath.CategoryTheory.Monoidal.WhiskeredBifunctors.\nRequire Import UniMath.CategoryTheory.Monoidal.Categories.\nRequire Import UniMath.CategoryTheory.Monoidal.Structure.Symmetric.\nRequire Import UniMath.CategoryTheory.Monoidal.Structure.Closed.\nRequire Import UniMath.CategoryTheory.limits.Preservation.\nRequire Import UniMath.CategoryTheory.limits.initial.\nRequire Import UniMath.CategoryTheory.limits.bincoproducts.\nRequire Import UniMath.CategoryTheory.limits.coproducts.\nRequire Import UniMath.CategoryTheory.limits.coequalizers.\nRequire Import UniMath.CategoryTheory.limits.terminal.\nRequire Import UniMath.CategoryTheory.limits.binproducts.\nRequire Import UniMath.CategoryTheory.limits.equalizers.\n\nLocal Open Scope cat.\nLocal Open Scope moncat.\nImport MonoidalNotations.\n\nSection SelfEnrichmentColimits.\n  Context (V : sym_mon_closed_cat).\n\n  (**\n   1. Initial objects\n   *)\n  Definition self_enrichment_initial\n             (v : Initial V)\n    : initial_enriched (self_enrichment V).\n  Proof.\n    refine (pr1 v ,, _).\n    intros x y ; cbn.\n    use (iscontrweqb (internal_hom_equiv _ _ _)).\n    exact (left_adjoint_preserves_initial\n             _\n             (sym_mon_closed_left_tensor_left_adjoint V y)\n             _\n             (pr2 v)\n             x).\n  Defined.\n\n  (**\n   2. Binary coproducts\n   *)\n  Section SelfEnrichedCoproduct.\n    Context {x y : V}\n            (c : BinCoproduct x y).\n\n    Let ι₁ : I_{V} --> x ⊸ c\n      := enriched_from_arr\n           (self_enrichment V)\n           (BinCoproductIn1 c).\n\n    Let ι₂ : I_{V} --> y ⊸ c\n      := enriched_from_arr\n           (self_enrichment V)\n           (BinCoproductIn2 c).\n\n    Definition make_self_enriched_binary_coprod_cocone\n      : enriched_binary_coprod_cocone (self_enrichment V) x y.\n    Proof.\n      use make_enriched_binary_coprod_cocone.\n      - exact c.\n      - exact ι₁.\n      - exact ι₂.\n    Defined.\n\n    Definition self_enriched_is_binary_coprod_paths_weq\n               {w z : V}\n               (f : z --> x ⊸ w)\n               (g : z --> y ⊸ w)\n               (fg : z --> c ⊸ w)\n      : (fg · precomp_arr (self_enrichment V) w (internal_to_arr ι₁) = f\n         ×\n         fg · precomp_arr (self_enrichment V) w (internal_to_arr ι₂) = g)\n        ≃\n        (identity z #⊗ BinCoproductIn1 c · (fg #⊗ identity c · internal_eval c w)\n         =\n         f #⊗ identity x · internal_eval x w)\n        ×\n        (identity z #⊗ BinCoproductIn2 c · (fg #⊗ identity c · internal_eval c w)\n         =\n         g #⊗ identity y · internal_eval y w).\n    Proof.\n      use weqimplimpl.\n      - intros pq.\n        split.\n        + rewrite !assoc.\n          rewrite <- tensor_split.\n          pose (p := pr1 pq) ; cbn in p.\n          rewrite self_enrichment_precomp in p.\n          rewrite <- p.\n          rewrite tensor_comp_r_id_r.\n          rewrite !assoc'.\n          rewrite internal_beta.\n          rewrite !assoc.\n          rewrite <- tensor_split'.\n          apply maponpaths_2.\n          apply maponpaths.\n          rewrite internal_to_from_arr.\n          apply idpath.\n        + rewrite !assoc.\n          rewrite <- tensor_split.\n          pose (p := pr2 pq) ; cbn in p.\n          rewrite self_enrichment_precomp in p.\n          rewrite <- p.\n          rewrite tensor_comp_r_id_r.\n          rewrite !assoc'.\n          rewrite internal_beta.\n          rewrite !assoc.\n          rewrite <- tensor_split'.\n          apply maponpaths_2.\n          apply maponpaths.\n          rewrite internal_to_from_arr.\n          apply idpath.\n      - intros pq.\n        split.\n        + pose (p := pr1 pq).\n          rewrite !assoc in p.\n          rewrite <- tensor_split in p.\n          use internal_funext.\n          intros a h.\n          rewrite tensor_comp_r_id_r.\n          rewrite self_enrichment_precomp.\n          rewrite !assoc'.\n          rewrite internal_beta.\n          rewrite (tensor_split f h).\n          rewrite !assoc'.\n          rewrite <- p.\n          rewrite !assoc.\n          apply maponpaths_2.\n          rewrite <- !tensor_comp_mor.\n          rewrite id_left, id_right.\n          do 2 apply maponpaths.\n          cbn.\n          apply internal_to_from_arr.\n        + pose (p := pr2 pq) ; cbn in p.\n          rewrite !assoc in p.\n          rewrite <- tensor_split in p.\n          use internal_funext.\n          intros a h.\n          rewrite tensor_comp_r_id_r.\n          rewrite self_enrichment_precomp.\n          rewrite !assoc'.\n          rewrite internal_beta.\n          rewrite (tensor_split g h).\n          rewrite !assoc'.\n          rewrite <- p.\n          rewrite !assoc.\n          apply maponpaths_2.\n          rewrite <- !tensor_comp_mor.\n          rewrite id_left, id_right.\n          do 2 apply maponpaths.\n          cbn.\n          apply internal_to_from_arr.\n      - apply isapropdirprod ; apply homset_property.\n      - apply isapropdirprod ; apply homset_property.\n    Qed.\n\n    Definition self_enriched_is_binary_coprod_weq\n               {w z : V}\n               (f : z --> x ⊸ w)\n               (g : z --> y ⊸ w)\n      : (∑ (fg : z --> c ⊸ w),\n         fg · precomp_arr (self_enrichment V) w (internal_to_arr ι₁) = f\n         ×\n         fg · precomp_arr (self_enrichment V) w (internal_to_arr ι₂) = g)\n        ≃\n        (∑ (fg : z ⊗ c --> w),\n         identity z #⊗ BinCoproductIn1 c · fg = f #⊗ identity x · internal_eval x w\n         ×\n         identity z #⊗ BinCoproductIn2 c · fg = g #⊗ identity y · internal_eval y w).\n    Proof.\n      use weqtotal2.\n      - exact (internal_hom_equiv z c w).\n      - exact (self_enriched_is_binary_coprod_paths_weq f g).\n    Defined.\n\n    Definition self_enriched_is_binary_coprod\n      : is_binary_coprod_enriched\n          (self_enrichment V)\n          x y\n          make_self_enriched_binary_coprod_cocone.\n    Proof.\n      intros w z f g.\n      use (iscontrweqb (self_enriched_is_binary_coprod_weq f g)).\n      apply (left_adjoint_preserves_bincoproduct\n               _\n               (sym_mon_closed_left_tensor_left_adjoint V z)\n               _ _ _ _ _\n               (pr2 c)).\n    Defined.\n  End SelfEnrichedCoproduct.\n\n  Definition self_enrichment_binary_coproducts\n             (coprodV : BinCoproducts V)\n    : enrichment_binary_coprod (self_enrichment V)\n    := λ x y,\n       make_self_enriched_binary_coprod_cocone (coprodV x y)\n       ,,\n       self_enriched_is_binary_coprod (coprodV x y).\n\n  (**\n   3. Coequalizers\n   *)\n  Section SelfEnrichmentCoequalizer.\n    Context {x y : V}\n            {f g : x --> y}\n            (c : Coequalizer f g).\n\n    Let e : y --> c := CoequalizerArrow c.\n\n    Definition make_self_enriched_coequalizer_cocone\n      : enriched_coequalizer_cocone (self_enrichment V) f g.\n    Proof.\n      use make_enriched_coequalizer_cocone.\n      - exact c.\n      - exact (enriched_from_arr (self_enrichment V) e).\n      - abstract\n          (cbn ;\n           rewrite !internal_to_from_arr ;\n           exact (CoequalizerEqAr c)).\n    Defined.\n\n    Definition self_enriched_is_coequalizer_path_weq\n               {w z : V}\n               (h : z --> y ⊸ w)\n               (φ : z --> c ⊸ w)\n      : (φ · precomp_arr (self_enrichment V) w (internal_to_arr (internal_from_arr e))\n         =\n         h)\n        ≃\n        (identity z #⊗ CoequalizerArrow c · (φ #⊗ identity c · internal_eval c w)\n         =\n         h #⊗ identity y · internal_eval y w).\n    Proof.\n      use weqimplimpl.\n      - intro p.\n        rewrite self_enrichment_precomp in p.\n        rewrite <- p.\n        rewrite tensor_comp_id_r.\n        rewrite !assoc'.\n        rewrite internal_beta.\n        rewrite internal_to_from_arr.\n        rewrite !assoc.\n        rewrite <- tensor_split.\n        rewrite <- tensor_split'.\n        apply idpath.\n      - intro p.\n        use internal_funext.\n        intros a k.\n        rewrite !assoc in p.\n        rewrite <- tensor_split in p.\n        rewrite self_enrichment_precomp.\n        rewrite tensor_comp_r_id_r.\n        rewrite !assoc'.\n        rewrite internal_beta.\n        rewrite internal_to_from_arr.\n        rewrite (tensor_split h k).\n        rewrite !assoc'.\n        rewrite <- p.\n        rewrite !assoc.\n        rewrite <- !tensor_comp_mor.\n        rewrite id_right.\n        rewrite id_left.\n        apply idpath.\n      - apply homset_property.\n      - apply homset_property.\n    Qed.\n\n    Definition self_enriched_is_coequalizer_weq\n               {w z : V}\n               (h : z --> y ⊸ w)\n               (r : h · precomp_arr (self_enrichment V) w f\n                    =\n                    h · precomp_arr (self_enrichment V) w g)\n      : (∑ (φ : z --> c ⊸ w),\n         φ · precomp_arr (self_enrichment V) w (internal_to_arr (internal_from_arr e)) = h)\n        ≃\n        (∑ (φ : z ⊗ c --> w),\n         identity z #⊗ CoequalizerArrow c · φ = h #⊗ identity _ · internal_eval y w).\n    Proof.\n      use weqtotal2.\n      - exact (internal_hom_equiv z c w).\n      - exact (self_enriched_is_coequalizer_path_weq h).\n    Defined.\n\n    Definition make_self_enriched_is_coequalizer\n      : is_coequalizer_enriched\n          (self_enrichment V)\n          f g\n          make_self_enriched_coequalizer_cocone.\n    Proof.\n      intros w z h r.\n      use (iscontrweqb (self_enriched_is_coequalizer_weq h r)).\n      refine (left_adjoint_preserves_coequalizer\n                _\n                (sym_mon_closed_left_tensor_left_adjoint V z)\n                _ _ _ _ _ _ _ _\n                (pr22 c)\n                _ _ _).\n      - cbn.\n        rewrite <- !tensor_comp_id_l.\n        apply maponpaths.\n        apply CoequalizerEqAr.\n      - abstract\n          (cbn ;\n           pose (maponpaths (λ z, z #⊗ identity _ · internal_eval _ _) r)\n             as r' ;\n           cbn in r' ;\n           rewrite !self_enrichment_precomp in r' ;\n           rewrite !tensor_comp_id_r in r' ;\n           rewrite !assoc' in r' ;\n           rewrite !internal_beta in r' ;\n           rewrite !assoc in r' ;\n           rewrite <- !tensor_split' in r' ;\n           rewrite !assoc ;\n           rewrite <- !tensor_split ;\n           exact r').\n    Defined.\n  End SelfEnrichmentCoequalizer.\n\n  Definition self_enrichment_coequalizers\n             (coeqV : Coequalizers V)\n    : enrichment_coequalizers (self_enrichment V)\n    := λ x y f g,\n       make_self_enriched_coequalizer_cocone (coeqV x y f g)\n       ,,\n       make_self_enriched_is_coequalizer (coeqV x y f g).\n\n  (**\n   4. Copowers\n   *)\n  Section SelfEnrichmentCopower.\n    Context (v₁ v₂ : V).\n\n    Definition self_enrichment_copower_cocone\n      : copower_cocone (self_enrichment V) v₁ v₂.\n    Proof.\n      use make_copower_cocone.\n      - exact (v₁ ⊗ v₂).\n      - exact (internal_pair v₁ v₂).\n    Defined.\n\n    Proposition self_enrichment_is_copower_eq_1\n                (w : V)\n      : is_copower_enriched_map\n          (self_enrichment V)\n          v₁ v₂\n          self_enrichment_copower_cocone\n          w\n        · internal_uncurry v₁ v₂ w\n        =\n        identity _.\n    Proof.\n      cbn.\n      use internal_funext.\n      intros a h.\n      rewrite tensor_comp_r_id_r.\n      rewrite !assoc'.\n      unfold internal_uncurry.\n      rewrite internal_beta.\n      unfold is_copower_enriched_map.\n      rewrite tensor_split.\n      rewrite <- tensor_id_id.\n      etrans.\n      {\n        rewrite !assoc'.\n        apply maponpaths.\n        rewrite !assoc.\n        rewrite tensor_rassociator.\n        rewrite !assoc'.\n        apply maponpaths.\n        rewrite !assoc.\n        rewrite <- tensor_comp_id_r.\n        rewrite internal_beta ; cbn.\n        rewrite tensor_comp_id_r.\n        rewrite !assoc'.\n        unfold internal_comp.\n        rewrite internal_beta.\n        rewrite !assoc.\n        rewrite tensor_lassociator.\n        rewrite !assoc'.\n        apply maponpaths.\n        rewrite !assoc.\n        rewrite <- tensor_comp_id_l.\n        unfold internal_pair.\n        rewrite internal_beta.\n        rewrite tensor_id_id.\n        apply id_left.\n      }\n      rewrite !assoc.\n      apply maponpaths_2.\n      rewrite !assoc'.\n      rewrite mon_rassociator_lassociator.\n      apply id_right.\n    Qed.\n\n    Proposition self_enrichment_is_copower_eq_2\n                (w : V)\n      : internal_uncurry v₁ v₂ w\n        · is_copower_enriched_map\n            (self_enrichment V)\n            v₁ v₂\n            self_enrichment_copower_cocone\n            w\n        =\n        identity _.\n    Proof.\n      use internal_funext ; cbn.\n      intros a₁ h₁.\n      rewrite tensor_comp_r_id_r.\n      rewrite !assoc'.\n      unfold is_copower_enriched_map ; cbn.\n      rewrite internal_beta.\n      use internal_funext ; cbn.\n      intros a₂ h₂.\n      rewrite !tensor_comp_r_id_r.\n      rewrite !assoc'.\n      unfold internal_comp.\n      rewrite internal_beta.\n      etrans.\n      {\n        apply maponpaths.\n        rewrite !assoc.\n        rewrite tensor_lassociator.\n        rewrite !assoc'.\n        apply maponpaths.\n        rewrite !assoc.\n        rewrite <- tensor_comp_id_l.\n        unfold internal_pair.\n        rewrite internal_beta.\n        rewrite tensor_id_id.\n        apply id_left.\n      }\n      rewrite !assoc.\n      rewrite tensor_lassociator.\n      rewrite !assoc'.\n      etrans.\n      {\n        apply maponpaths.\n        rewrite tensor_split.\n        rewrite !assoc'.\n        unfold internal_uncurry.\n        rewrite internal_beta.\n        rewrite !assoc.\n        rewrite tensor_rassociator.\n        rewrite !assoc'.\n        apply idpath.\n      }\n      rewrite !assoc.\n      rewrite mon_lassociator_rassociator.\n      rewrite id_left.\n      apply idpath.\n    Qed.\n\n    Definition self_enrichment_is_copower\n      : is_copower_enriched\n          (self_enrichment V)\n          v₁ v₂\n          self_enrichment_copower_cocone.\n    Proof.\n      use make_is_copower_enriched.\n      - exact (λ w, internal_uncurry v₁ v₂ w).\n      - exact self_enrichment_is_copower_eq_1.\n      - exact self_enrichment_is_copower_eq_2.\n    Defined.\n  End SelfEnrichmentCopower.\n\n  Definition self_enrichment_copowers\n    : enrichment_copower (self_enrichment V)\n    := λ v₁ v₂,\n       self_enrichment_copower_cocone v₁ v₂\n       ,,\n       self_enrichment_is_copower v₁ v₂.\n\n  (**\n   5. Type indexed coproducts\n   *)\n  Section SelfEnrichmentTypeCoproduct.\n    Context {J : UU}\n            {D : J → V}\n            (coprod : Coproduct J V D).\n\n    Let ι : ∏ (j : J), I_{V} --> D j ⊸ coprod\n      := λ j,\n         enriched_from_arr\n           (self_enrichment V)\n           (CoproductIn _ _ coprod j).\n\n    Definition self_enriched_coprod_cocone\n      : enriched_coprod_cocone (self_enrichment V) D.\n    Proof.\n      use make_enriched_coprod_cocone.\n      - exact coprod.\n      - exact ι.\n    Defined.\n\n    Definition self_enriched_is_coprod_weq_path\n               {w z : V}\n               (f : ∏ (j : J), z --> D j ⊸ w)\n               (fs : z --> coprod ⊸ w)\n               (j : J)\n      : (fs · precomp_arr\n                (self_enrichment V)\n                w\n                (internal_to_arr (internal_from_arr (CoproductIn J V coprod j)))\n         =\n         f j)\n        ≃\n        (identity z #⊗ CoproductIn J V coprod j\n         · (fs #⊗ identity coprod · internal_eval coprod w)\n         =\n         f j #⊗ identity (D j) · internal_eval (D j) w).\n    Proof.\n      rewrite internal_to_from_arr.\n      rewrite self_enrichment_precomp.\n      rewrite !assoc.\n      rewrite <- tensor_split.\n      use weqimplimpl.\n      - intro p.\n        pose (maponpaths (λ z, z #⊗ identity _ · internal_eval _ _) p) as q.\n        cbn in q.\n        rewrite tensor_comp_id_r in q.\n        rewrite !assoc' in q.\n        rewrite internal_beta in q.\n        rewrite !assoc in q.\n        rewrite <- tensor_split' in q.\n        exact q.\n      - intro p.\n        use internal_funext.\n        intros a h.\n        rewrite tensor_comp_r_id_r.\n        rewrite !assoc'.\n        rewrite internal_beta.\n        rewrite !assoc.\n        rewrite (tensor_split fs h).\n        rewrite (tensor_split (f j) h).\n        rewrite !assoc'.\n        apply maponpaths.\n        rewrite !assoc.\n        rewrite <- tensor_split'.\n        exact p.\n      - apply homset_property.\n      - apply homset_property.\n    Qed.\n\n    Definition self_enriched_is_coprod_weq\n               {w z : V}\n               (f : ∏ (j : J), z --> D j ⊸ w)\n      : (∑ (fs : z --> coprod ⊸ w),\n         ∏ (j : J),\n         fs · precomp_arr (self_enrichment V) w (internal_to_arr (ι j)) = f j)\n        ≃\n        (∑ (fs : z ⊗ coprod --> w),\n         ∏ (j : J),\n         identity z #⊗ CoproductIn _ _ coprod j · fs\n         =\n         f j #⊗ identity _ · internal_eval (D j) w).\n    Proof.\n      use weqtotal2.\n      - exact (internal_hom_equiv z coprod w).\n      - intro fs ; cbn -[ι].\n        use weqonsecfibers.\n        intro j.\n        apply self_enriched_is_coprod_weq_path.\n    Defined.\n\n    Definition self_enriched_is_coprod\n      : is_coprod_enriched (self_enrichment V) D self_enriched_coprod_cocone.\n    Proof.\n      intros w z f.\n      use (iscontrweqb (self_enriched_is_coprod_weq f)).\n      apply (left_adjoint_preserves_coproduct\n               _\n               (sym_mon_closed_left_tensor_left_adjoint V z)\n                _ _ _ _\n               (pr2 coprod)).\n    Defined.\n  End SelfEnrichmentTypeCoproduct.\n\n  Definition self_enrichment_coprod\n             (J : UU)\n             (HV : Coproducts J V)\n    : enrichment_coprod (self_enrichment V) J\n    := λ D,\n       self_enriched_coprod_cocone (HV D)\n       ,,\n       self_enriched_is_coprod (HV D).\nEnd SelfEnrichmentColimits.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/CategoryTheory/EnrichedCats/Colimits/Examples/SelfEnrichedColimits.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6774036281000572}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_samesidesymmetric.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_planeseparation.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_samenotopposite : \n   forall A B C D, \n   OS A B C D ->\n   ~ TS A C D B.\nProof.\nintros.\nassert (OS B A C D) by (forward_using lemma_samesidesymmetric).\nassert (~ TS A C D B).\n {\n intro.\n assert (TS B C D B) by (conclude lemma_planeseparation).\n let Tf:=fresh in\n assert (Tf:exists M, BetS B M B) by (conclude_def TS );destruct Tf as [M];spliter.\n assert (~ BetS B M B) by (conclude axiom_betweennessidentity).\n contradict.\n }\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_samenotopposite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6774036207294493}}
{"text": "(** Calculation of a compiler for the call-by-name lambda calculus +\narithmetic. *)\n\nRequire Import List.\nRequire Import ListIndex.\nRequire Import Tactics.\n\n(** * Syntax *)\n\nInductive Expr : Set := \n| Val : nat -> Expr \n| Add : Expr -> Expr -> Expr\n| Var : nat -> Expr\n| Abs : Expr -> Expr\n| App : Expr -> Expr -> Expr.\n\n(** * Semantics *)\n\n(** We start with the evaluator for this language, which is taken from\nAger et al. \"A functional correspondence between evaluators and\nabstract machines\" (we use Haskell syntax to describe the evaluator):\n<<\ntype Env   = [Thunk]\ndata Thunk = Thunk (() -> Value)\ndata Value = Num Int | Clo (Thunk -> Value)\n\n\neval :: Expr -> Env -> Value\neval (Val n)   e = Num n\neval (Add x y) e = case eval x e of\n                     Num n -> case eval y e of\n                                Num m -> Num (n + m)\neval (Var i)   e = case e !! i of\n                     Thunk t -> t ()\neval (Abs x)   e = Clo (\\t -> eval x (t : e))\neval (App x y) e = case eval x e of\n                     Clo f -> f (Thunk (\\_ -> eval y e))\n>>\nAfter defunctionalisation and translation into relational form we\nobtain the semantics below.  *)\n\nInductive Thunk : Set  :=\n  | thunk : Expr -> list Thunk -> Thunk.\n\nDefinition Env : Set := list Thunk.\n\nInductive Value : Set :=\n| Num : nat -> Value\n| Clo : Expr -> Env -> Value.\n\nReserved Notation \"x ⇓[ e ] y\" (at level 80, no associativity).\n\nInductive eval : Expr -> Env -> Value -> Prop :=\n| eval_val e n : Val n ⇓[e] Num n\n| eval_add e x y m n : x ⇓[e] Num m -> y ⇓[e] Num n -> Add x y ⇓[e] Num (m + n)\n| eval_var e e' x i v : nth e i = Some (thunk x e') -> x ⇓[e'] v -> Var i ⇓[e] v\n| eval_abs e x : Abs x ⇓[e] Clo x e\n| eval_app e e' x x' x'' y  : x ⇓[e] Clo x' e' -> x' ⇓[thunk y e :: e'] x'' -> App x y ⇓[e] x''\nwhere \"x ⇓[ e ] y\" := (eval x e y).\n\n(** * Compiler *)\n\nInductive Code : Set :=\n| PUSH : nat -> Code -> Code\n| ADD : Code -> Code\n| RET : Code\n| LOOKUP : nat -> Code -> Code\n| APP : Code -> Code -> Code\n| ABS : Code -> Code -> Code\n| HALT : Code.\n\nFixpoint comp' (e : Expr) (c : Code) : Code :=\n  match e with\n    | Val n => PUSH n c\n    | Add x y => comp' x (comp' y (ADD c))\n    | Var i => LOOKUP i c\n    | App x y => comp' x (APP (comp' y RET) c)\n    | Abs x => ABS (comp' x RET) c\n  end.\n\nDefinition comp (e : Expr) : Code := comp' e HALT.\n\n(** * Virtual Machine *)\n\nInductive Thunk' : Set  :=\n  | thunk' : Code -> list Thunk' -> Thunk'.\n\nDefinition Env' : Set := list Thunk'.\n\nInductive Value' : Set :=\n| Num' : nat -> Value'\n| Clo' : Code -> Env' -> Value'.\n\n\nInductive Elem : Set :=\n| VAL : Value' -> Elem \n| CLO : Code -> Env' -> Elem\n.\nDefinition Stack : Set := list Elem.\n\nInductive Conf : Set := \n| conf : Code -> Stack -> Env' -> Conf.\n\nNotation \"⟨ x , y , e ⟩\" := (conf x y e).\n\nReserved Notation \"x ==> y\" (at level 80, no associativity).\nInductive VM : Conf -> Conf -> Prop :=\n| vm_push n c s e :  ⟨PUSH n c, s, e⟩ ==> ⟨c, VAL (Num' n) :: s, e⟩\n| vm_add c m n s e : ⟨ADD c, VAL (Num' n) :: VAL (Num' m) :: s, e⟩\n                       ==> ⟨c, VAL (Num'(m + n)) :: s, e⟩\n| vm_ret v c e e' s  : ⟨RET, VAL v :: CLO c e :: s, e'⟩ ==> ⟨c, VAL v :: s, e⟩\n| vm_lookup e e' i c c' s : nth e i = Some (thunk' c' e') -> ⟨LOOKUP i c, s, e ⟩ ==> ⟨c', CLO c e :: s, e' ⟩\n| vm_app c c' c'' e e' s : ⟨APP c' c, VAL (Clo' c'' e') :: s, e⟩\n                           ==> ⟨c'', CLO c e :: s, thunk' c' e :: e'⟩\n| vm_abs c c' s e : ⟨ABS c' c, s, e ⟩ ==> ⟨c, VAL (Clo' c' e) :: s, e ⟩\nwhere \"x ==> y\" := (VM x y).\n\n(** Conversion functions from semantics to VM *)\n\nFixpoint convT (t : Thunk) : Thunk' :=\n  match t with\n    | thunk x e => thunk' (comp' x RET) (map convT e)\n  end.\n\nDefinition convE : Env -> Env' := map convT.\n\nDefinition convV (v : Value) : Value' :=\n  match v with\n    | Num n => Num' n\n    | Clo x e => Clo' (comp' x RET) (convE e)\n  end.\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 p e r c s : p ⇓[e] r -> ⟨comp' p c, s, convE e⟩ \n                                 =>> ⟨c , VAL (convV r) :: s, convE e⟩.\n\n(** Setup the induction proof *)\n\nProof.\n  intros.\n  generalize dependent c.\n  generalize dependent s.\n  induction H;intros.\n\n(** Calculation of the compiler *)\n\n(** - [Val n ⇓[e] Num n]: *)\n\n  begin\n  ⟨c, VAL (Num' n) :: s, convE e⟩.\n  <== { apply vm_push }\n  ⟨PUSH n c, s, convE e⟩.\n  [].\n\n(** - [Add x y ⇓[e] Num (m + n)]: *)\n\n  begin\n    ⟨c, VAL (Num' (m + n)) :: s, convE e ⟩.\n  <== { apply vm_add }\n    ⟨ADD c, VAL (Num' n) :: VAL (Num' m) :: s, convE e⟩. \n  <<= { apply IHeval2 }\n  ⟨comp' y (ADD c), VAL (Num' m) :: s, convE e⟩.\n  <<= { apply IHeval1 }\n  ⟨comp' x (comp' y (ADD c)), s, convE e⟩.\n  [].\n\n(** - [Var i ⇓[e] v]: *)\n\n  begin\n    ⟨c, VAL (convV v) :: s, convE e ⟩.\n  <== {apply vm_ret}\n    ⟨RET, VAL (convV v) :: CLO c (convE e) :: s, convE e'⟩.\n  <<= {apply IHeval}\n    ⟨comp' x RET, CLO c (convE e) :: s, convE e'⟩.\n  <== {apply vm_lookup; unfold convE; rewrite nth_map}\n    ⟨LOOKUP i c, s, convE e ⟩.\n  [].\n\n(** - [Abs x ⇓[e] Clo x e]: *)\n\n  begin\n    ⟨c, VAL (Clo' (comp' x RET) (convE e)) :: s, convE e ⟩.\n  <== { apply vm_abs }\n    ⟨ABS (comp' x RET) c, s, convE e ⟩.\n  [].\n  \n(** - [App x y ⇓[e] x'']: *)\n\n  begin\n    ⟨c, VAL (convV x'') :: s, convE e ⟩.\n  <== { apply vm_ret }\n    ⟨RET, VAL (convV x'') :: CLO c (convE e) :: s, convE (thunk y e :: e') ⟩.\n  <<= { apply IHeval2 }\n    ⟨comp' x' RET, CLO c (convE e) :: s, convE (thunk y e :: e') ⟩.\n  = {reflexivity}\n    ⟨comp' x' RET, CLO c (convE e) :: s, thunk' (comp' y RET) (convE e) :: convE e' ⟩.\n  <== { apply vm_app }\n    ⟨APP (comp' y RET) c, VAL (Clo' (comp' x' RET) (convE e')) :: s, convE e ⟩.\n  = { reflexivity }\n    ⟨APP (comp' y RET) c, VAL (convV (Clo x' e')) :: s, convE e ⟩.\n  <<= { apply IHeval1 }\n    ⟨comp' x (APP (comp' y RET) c), s, convE e ⟩.\n  [].\nQed.\n    \n(** * Soundness *)\n\nLemma determ_vm : determ VM.\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 p s C : terminates p -> ⟨comp p, s, nil⟩ =>>! C -> \n                          exists r, C = ⟨HALT , VAL (convV r) :: s, nil⟩ /\\ p ⇓[nil] r.\nProof.\n  unfold terminates. intros. destruct H as [r T].\n  \n  pose (spec p nil r HALT s) as H'. exists r. split. pose (determ_trc determ_vm) as D.\n  unfold determ in D. eapply D. eassumption. split. auto. intro. destruct H. \n  inversion H. assumption.\nQed.\n\n  \n", "meta": {"author": "pa-ba", "repo": "calc-comp", "sha": "337a5b89dfb8ceb9e2724e5911519a60d14a4f99", "save_path": "github-repos/coq/pa-ba-calc-comp", "path": "github-repos/coq/pa-ba-calc-comp/calc-comp-337a5b89dfb8ceb9e2724e5911519a60d14a4f99/LambdaCBName.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.6773823249016122}}
{"text": "Require Import CPidgin.Data.List.\nRequire Import CPidgin.Data.Maybe.\nRequire Import CPidgin.Data.Monoid.\nRequire Import CPidgin.Data.Semigroup.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import PeanoNat.\n\nModule ListTheorems.\n\nImport Maybe.\nImport Monoid.\nImport List.\nImport Semigroup.\n\n(* head of [] returns Nothing. *)\nLemma list_head_nil_none:\n    forall (A : Type),\n        head ([] : List A) = Nothing.\nProof.\n    intros.\n    unfold head.\n    trivial.\nQed.\n\n(* head of x :: xs returns x. *)\nLemma list_head_cons:\n    forall (A : Type) (x : A) (xs : List A),\n        head (x :: xs) = Just x.\nProof.\n    intros.\n    unfold head.\n    trivial.\nQed.\n\n(* tail of [] is []. *)\nLemma list_tail_nil:\n    forall (A : Type),\n        tail ([] : List A) = [].\nProof.\n    intros.\n    unfold tail.\n    trivial.\nQed.\n\n(* tail of x :: xs is xs. *)\nLemma list_tail_cons:\n    forall (A : Type) (x : A) (xs : List A),\n        tail (x :: xs) = xs.\nProof.\n    intros.\n    unfold tail.\n    trivial.\nQed.\n\n(* helper to create a duplicate list of a given size. *)\nFixpoint dupList {A : Type} (n : nat) (m : A) (ls : List A) : List A :=\n    match n with\n        | 0 => ls\n        | S n' => m :: dupList n' m ls\n    end.\n\n(* proof that we can unroll drop by 1. *)\nLemma list_drop_unroll:\n    forall (A : Type) (n : nat) (x : A) (xs : List A),\n        drop (S n) (x :: xs) = drop n xs.\nProof.\n    intros.\n    unfold drop.\n    trivial.\nQed.\n\n(* proof that we can unroll dupList by 1. *)\nLemma list_dupList_unroll:\n    forall (A : Type) (n : nat) (x : A) (xs : List A),\n        dupList (S n) x xs = x :: dupList n x xs.\nProof.\n    intros.\n    unfold dupList.\n    trivial.\nQed.\n\n(* proof that drop n drops n values from a list. *)\nLemma list_drop:\n    forall (A : Type) (n : nat) (x : A) (xs : List A),\n        drop n (dupList n x xs) = xs.\nProof.\n    intros.\n    induction n.\n    1: {\n        unfold drop.\n        unfold dupList.\n        trivial.\n    }\n    1: {\n        rewrite list_dupList_unroll.\n        rewrite list_drop_unroll.\n        rewrite IHn.\n        trivial.\n    }\nQed.\n\n(* Proof that we can unroll length by one. *)\nLemma list_length_unroll:\n    forall (A : Type) (l : List A) (m : A),\n        length (m :: l) = S (length l).\nProof.\n    intros.\n    unfold length.\n    trivial.\nQed.\n\n(* Proof that append and cons are commutative. *)\nLemma list_append_cons_commute:\n    forall (A : Type) (l1 l2 : List A) (m : A),\n        (m :: l1) ++ l2 = m :: (l1 ++ l2).\nProof.\n    intros.\n    unfold append.\n    trivial.\nQed.\n\n(* Proof that succ is associative wrt addition. *)\nLemma nat_succ_plus_assoc:\n    forall (n1 n2 : nat),\n        S (n1 + n2) = S n1 + n2.\nProof.\n    intros.\n    unfold plus.\n    trivial.\nQed.\n\n(* Proof that the length of two lists appended is the same as their lengths\n   added. *)\nLemma list_length_append:\n    forall (A : Type) (l1 l2 : List A),\n        length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n    intros.\n    induction l1.\n    1: {\n        unfold append.\n        unfold length.\n        trivial.\n    }\n    1: {\n        rewrite list_append_cons_commute.\n        rewrite list_length_unroll.\n        rewrite list_length_unroll.\n        rewrite IHl1.\n        rewrite nat_succ_plus_assoc.\n        trivial.\n    }\nQed.\n\n(* Proof that dropping the length of a list results in an empty list. *)\nLemma list_drop_length_empty:\n    forall (A : Type) (l : List A),\n        drop (length l) l = [].\nProof.\n    intros.\n    induction l.\n    1: {\n        unfold length.\n        unfold drop.\n        trivial.\n    }\n    1: {\n        rewrite list_length_unroll.\n        rewrite list_drop_unroll.\n        rewrite IHl.\n        trivial.\n    }\nQed.\n\n(* Proof that we can append two lists, drop the first list, and get the second\n   list. *)\nLemma list_drop_append_length:\n    forall (A : Type) (l1 l2 : List A),\n        drop (length l1) (l1 ++ l2) = l2.\nProof.\n    intros.\n    induction l1.\n    1: {\n        unfold length.\n        unfold drop.\n        unfold append.\n        trivial.\n    }\n    1: {\n        rewrite list_length_unroll.\n        rewrite list_append_cons_commute.\n        rewrite list_drop_unroll.\n        rewrite IHl1.\n        trivial.\n    }\nQed.\n\n(* Proof that we can unroll take. *)\nLemma list_take_unroll:\n    forall (A : Type) (l : List A) (m : A) (n : nat),\n        take (S n) (m :: l) = m :: take n l.\nProof.\n    intros.\n    unfold take.\n    trivial.\nQed.\n\n(* Proof that taking the length from a list is that list. *)\nLemma list_take_length:\n    forall (A : Type) (l : List A),\n        take (length l) l = l.\nProof.\n    intros.\n    induction l.\n    1: {\n        unfold length.\n        unfold take.\n        trivial.\n    }\n    1: {\n        rewrite list_length_unroll.\n        rewrite list_take_unroll.\n        rewrite IHl.\n        trivial.\n    }\nQed.\n\n(* Proof that we can take the first list from apending two lists. *)\nLemma list_append_take:\n    forall (A : Type) (l1 l2 : List A),\n        take (length l1) (l1 ++ l2) = l1.\nProof.\n    intros.\n    induction l1.\n    1: {\n        unfold length.\n        unfold append.\n        unfold take.\n        trivial.\n    }\n    1: {\n        rewrite list_append_cons_commute.\n        rewrite list_length_unroll.\n        rewrite list_take_unroll.\n        rewrite IHl1.\n        trivial.\n    }\nQed.\n\n(* Proof that we can unroll nth. *)\nDefinition list_nth_unroll:\n    forall (A : Type) (n : nat) (l : List A) (m : A),\n        nth (S n) (m :: l) = nth n l.\nProof.\n    intros.\n    unfold nth.\n    rewrite list_drop_unroll.\n    destruct n.\n    unfold drop.\n    trivial.\n    trivial.\nQed.\n\n(* Proof that we can take the nth item from an arbitrary list. *)\nDefinition list_nth_append_concat:\n    forall (A : Type) (l1 l2 : List A) (m : A),\n        nth (length l1) (l1 ++ (m :: l2)) = Just m.\nProof.\n    intros.\n    unfold nth.\n    destruct l1.\n    unfold length.\n    unfold append.\n    unfold head.\n    trivial.\n    rewrite list_length_unroll.\n    rewrite list_append_cons_commute.\n    rewrite list_drop_unroll.\n    rewrite list_drop_append_length.\n    unfold head.\n    trivial.\nQed.\n\n(* Proof that we can unroll removeNth by one. *)\nLemma list_remove_nth_unroll:\n    forall (A : Type) (n : nat) (l : List A) (m : A),\n        removeNth (S n) (m :: l) = m :: removeNth n l.\nProof.\n    intros.\n    unfold removeNth.\n    trivial.\nQed.\n\n(* Proof that we can remove an element from a list. *)\nLemma list_remove_nth:\n    forall (A : Type) (l1 l2 : List A) (m : A),\n        removeNth (length l1) (l1 ++ (m :: l2)) = l1 ++ l2.\nProof.\n    intros.\n    induction l1.\n    unfold length.\n    unfold removeNth.\n    unfold tail.\n    unfold append.\n    trivial.\n    rewrite list_length_unroll.\n    rewrite list_append_cons_commute.\n    rewrite list_append_cons_commute.\n    rewrite list_remove_nth_unroll.\n    rewrite IHl1.\n    trivial.\nQed.\n\n(* Proof that removing the nth element from an empty list returns the empty\n   list. *)\nLemma list_remove_nth_empty:\n    forall (A : Type) (n : nat),\n        removeNth n ([] : List A) = [].\nProof.\n    intros.\n    unfold removeNth.\n    destruct n.\n    unfold tail.\n    trivial.\n    trivial.\nQed.\n\n(* Proof that a list can be destructed as a left append of an empty list and\n   itself. *)\nLemma list_empty_left_append:\n    forall (A : Type) (l : List A),\n        l = [] ++ l.\nProof.\n    intros.\n    unfold append.\n    trivial.\nQed.\n\n(* Proof that a list can be destructed as a right append of an empty list and\n   itself. *)\nLemma list_empty_right_append:\n    forall (A : Type) (l : List A),\n        l = l ++ [].\nProof.\n    intros.\n    induction l.\n    unfold append.\n    trivial.\n    rewrite list_append_cons_commute.\n    rewrite <- IHl.\n    trivial.\nQed.\n\n(* Proof that list append follows the Semigroup Associativity Law. *)\nLemma list_append_semigroup_associativity:\n    forall (A : Type) (x y z : List A),\n        (x <o> y) <o> z = x <o> (y <o> z).\nProof.\n    intros.\n    unfold op.\n    unfold listSemigroup.\n    unfold append.\n    induction x.\n    induction y.\n    induction z.\n    trivial.\n    trivial.\n    trivial.\n    rewrite IHx.\n    trivial.\nQed.\n\n(* Proof that the list append monoid has a left identity. *)\nLemma list_append_monoid_left_identity:\n    forall (A : Type) (x : List A),\n        mempty <o> x = x.\nProof.\n    intros.\n    unfold mempty.\n    unfold listMonoid.\n    unfold op.\n    unfold listSemigroup.\n    unfold append.\n    trivial.\nQed.\n\n(* Proof that the list append monoid has a right identity. *)\nLemma list_append_monoid_right_identity:\n    forall (A : Type) (x : List A),\n        x <o> mempty = x.\nProof.\n    intros.\n    unfold mempty.\n    unfold listMonoid.\n    unfold op.\n    unfold listSemigroup.\n    unfold append.\n    induction x.\n    trivial.\n    rewrite IHx.\n    trivial.\nQed.\n\nEnd ListTheorems.\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/ListTheorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245828938678, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.6773823204739295}}
{"text": "Check (forall A:Set, A -> A).\n\nDefinition id (A:Set) (a:A) : A := a.\n\nCheck (forall A B:Set, (A -> A -> B) -> A -> B).\n\nDefinition diag (A B:Set) (f:A -> A -> B) (a:A) : B := f a a.\n\n\nCheck (forall A B C:Set, (A -> B -> C) -> B -> A -> C).\n \nDefinition permute (A B C:Set) (f:A -> B -> C) (b:B) (a:A) : C := f a b.\n\nRequire Import ZArith.\n\nCheck (forall A:Set, (nat -> A) -> Z -> A).\n\nDefinition f_nat_Z (A:Set) (f:nat -> A) (z:Z) : A := f (Zabs_nat z).\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/depprod/SRC/polymorph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88720460564669, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.6773663065872623}}
{"text": "Require Import Reals.\nRequire Import Field Psatz.\nFrom mathcomp Require Import all_ssreflect.\n\nSection Edwards.\n\n(* First create a field *)\nVariable K : Set.\n\nVariables kO kI : K.\nNotation \"0\" := kO.\nNotation \"1\" := kI.\n\nHypothesis one_not_zero: 1 <> 0.\n\nVariable kplus kmul ksub kdiv : K -> K -> K.\nNotation \"x + y\" := (kplus x y). \nNotation \"x * y \" := (kmul x y). \nNotation \"x - y \" := (ksub x y).\nNotation \"x / y\" := (kdiv x y).\n\nVariables kopp kinv :  K -> K.\nNotation \"- x\" := (kopp x).\nNotation \"/ x\" := (kinv x). \n\n(* Test to zero *)\nVariable is_zero: K -> bool.\n\nHypothesis is_zero_correct : forall k, is_zero k = true <-> k = 0.\n \n(* It is a field *)  \nVariable Kfth :  field_theory kO kI kplus kmul ksub kopp kdiv kinv (@eq K).\n\n(* Trick to get the power function *)\nFixpoint pow (k: K) (n: nat) :=\n match n with O => 1 | 1%nat => k | S n1 => k * pow k n1 end.\n\nNotation \"x ^ y\" := (pow x y).\n\nLemma pow_S k n : k ^ (S n) = k * k ^ n.\nProof.\ncase: n => //=.\nby rewrite Kfth.(F_R).(Rmul_comm) Kfth.(F_R).(Rmul_1_l).\nQed.\n\nLet Mkmul := rmul_ext3_Proper (Eq_ext kplus kmul kopp).\n\nLemma Kpower_theory : \n  Ring_theory.power_theory 1 kmul (eq (A:=K)) BinNat.nat_of_N pow.\nProof.\nconstructor => r [|] //=.\nelim/BinPos.Pind => // n H.\nrewrite Pnat.nat_of_P_succ_morphism pow_S.\nrewrite (Ring_theory.pow_pos_succ (Eqsth K) Mkmul) ?H //.\nexact Kfth.(F_R).(Rmul_assoc).\nQed.\n\nLtac iskpow_coef t :=\n  match t with\n  | (S ?x) => iskpow_coef x\n  | O => true\n  | _ => false\n  end.\n\nLtac kpow_tac t :=\n match iskpow_coef t with\n | true => constr:(BinNat.N_of_nat t)\n | _ => constr:(NotConstant)\n end.\n\nAdd Field Kfth : Kfth (power_tac Kpower_theory [kpow_tac]).\n\nLemma Kmult_integral x y : x * y = 0 -> x = 0 \\/ y = 0.\nProof.\nmove=> H.\ncase: (is_zero x) (is_zero_correct x) => [[H1 _]|[_ H1]].\n  by left; apply: H1.\nright.\napply: trans_equal (_ : (/x) * (x * y) = _); try field.\n  by move=> /H1.\nrewrite H; ring.\nQed.\n\nLemma Kdiv_0_l x : 0 / x = 0.\nProof. rewrite (Fdiv_def Kfth); ring. Qed.\n\nLemma Kdiv_eq_0_compat_r x y : x = 0 -> x / y = 0.\nProof. rewrite (Fdiv_def Kfth)=>->; ring. Qed.\n\n(* We can now start the elliptic part *)\n\nVariables cs d : K.\n\nDefinition c := cs * cs.\n\n(* not a non-zero square *)\nDefinition ns v := forall x, v = x * x -> v = 0.\n\nLemma nsD v y : ns v -> 1 - v * y * y <> 0.\nProof.\nmove=> H.\nhave := is_zero_correct v.\ncase: is_zero => // [[-> // _]|[_ H1] H2].\n  contradict one_not_zero.\n  by rewrite -one_not_zero; ring.\nhave H0 : v * y * y = 1.\n  rewrite (_ : 1 = 1 - 0); last by ring.\n  by rewrite -H2; ring.\nhave H3 : y <> 0.\n  move=> H3; rewrite H3 in H0.\n  case: one_not_zero.\n  by rewrite -H0; ring.\nsuff : false = true by [].\napply/H1/(H (1 / y)).\nby field[H0].\nQed.\n\nHypothesis ns_d : ns d.\n\n(* A point *)\nNotation point := (K * K)%type.\n\nImplicit Types p q : point.\n\nDefinition dx p q := 1 - d * p.1 * p.2 * q.1 * q.2.\n\nLemma dxC p q : dx p q = dx q p.\nProof. rewrite /dx; ring. Qed.\n\nDefinition dy p q := 1 + d * p.1 * p.2 * q.1 * q.2.\n\nLemma dyC p q : dy p q = dy q p.\nProof. rewrite /dy; ring. Qed.\n\nDefinition dd p q :=\n  1 - d * d * p.1 * p.1 * p.2 * p.2 * \n              q.1 * q.1 * q.2 * q.2.\n\nLemma ddE p q : dd p q = dx p q * dy p q.\nProof. rewrite /dd /dx /dy; ring. Qed.\n\nLemma ddC p q : dd p q = dd q p.\nProof. rewrite !ddE dxC dyC; ring. Qed.\n\nDefinition add p q : point :=\n (/(dx p q) * (p.1 * q.1 - c * p.2 * q.2),\n  /(dy p q) * (p.1 * q.2 + q.1 * p.2)).\n\nInfix \"++\" := add.\n\n(* Adding is commutative *)\nLemma addC p q : p ++ q = q ++ p.\nProof. rewrite /add dxC dyC; congr (_, _); ring. Qed.\n\nDefinition d0 : point := (1, 0).\n\nLemma add0C p : d0 ++ p = p.\nProof.\ncase: p => x y.\nby rewrite /add /dx /dy /=; congr (_, _); field.\nQed.\n\nDefinition on p :=\n  d * p.1 * p.1 * p.2 * p.2 = p.1 * p.1 + c * p.2 * p.2 - 1.\n\n(* 0 is on the curve *)\nLemma on0 : on d0.\nProof. rewrite /on /d0 /=; ring. Qed.\n\n(* Opposite *)\nDefinition opp p : point := (p.1,-p.2).\n\nNotation \"-- x\" := (opp x) (at level 10).\n\n(* The opposite is on the curve *)\nLemma on_opp p : on p -> on (-- p).\nProof.\ncase: p => x y; rewrite /on /= => H; ring[H].\nQed.\n\n(* If we are on the curve, we can divide by dd *)\nLemma on_dd p q : on p -> on q -> dd p q <> 0.\nProof.\ncase: p => x1 y1; case: q => x2 y2.\nhave F x : 1 - x = 0 -> x = 1.\n  move=> H.\n  replace 1 with (1 - x + x) by ring.\n  by rewrite H; ring.\npose r := (1 - c * d * y1 * y1 * y2 * y2) *\n          (1 - d * y1 * y1 * x2 * x2).\nrewrite /on /dd /= => H1 H2 /F H3.\nhave /Kmult_integral[H|H] : r = 0.\n- rewrite /r.\n(* here we mimic a grobner computation *)\n  ring_simplify [H1 H2] in H3.\n  set u := _ * c ^ 2 in H3.\n  have: u = u - 1 + 1 by ring.\n  rewrite -[in u - _]H3 => H4; ring_simplify in H4; rewrite /u in H4.\n  ring_simplify[H1 H2].\n  ring_simplify[H4].\n  ring_simplify[H1 H2].\n  ring[H4].\n- case (nsD _ (cs * y1 * y2) ns_d).\n  by rewrite -H /c; ring.\ncase (nsD _ (y1 * x2) ns_d).\nby rewrite -H /c; ring.\nTime Qed.\n\n(* If we are on the curve, we can divide by dx *)\nLemma on_dx p q : on p -> on q -> dx p q <> 0.\nProof.\nintros H1 H2 H.\ncase (on_dd _ _ H1 H2).\nrewrite ddE; ring[H].\nQed.\n\n(* If we are on the curve, we can divide by dy *)\nLemma on_dy p q : on p -> on q -> dy p q <> 0.\nProof.\nintros H1 H2 H.\ncase (on_dd _ _ H1 H2).\nrewrite ddE; ring[H].\nQed.\n\n(* Adding the opposite give 0 *)\nLemma addnK p : on p -> p ++ -- p = d0.\nProof.\nintro H1.\nhave H2 := on_opp _ H1.\nmove: {H2}H1 (on_dx _ _ H1 H2) (on_dy _ _ H1 H2).\ncase: p => x y.\nrewrite  /on /add /dx /dy /= => H1 H2 H3.\nby congr (_, _); field[H1].\nQed.\n\n(* Adding two elements of the curve gives an element of the curve *)\nLemma on_add p q : on p -> on q -> on (p ++ q).\nProof.\nmove=> H1 H2.\nmove: H1 H2 (on_dx _ _ H1 H2) (on_dy _ _ H1 H2).\ncase: p => x1 y1; case: q => x2 y2.\nrewrite /on /= /dx /dy /= => H1 H2 H3 H4.\nfield_simplify => //.\ncongr (_ / _).\nring [H1 H2].\nTime Qed.\n\n(* Adding is associative *)\nLemma add_assoc p q r :\n   on p -> on q -> on r -> (p ++ q) ++ r = p ++ (q ++ r).\nProof.\nmove=> H1 H2 H3.\nmove: H1 H2 H3 (on_dx _ _ H1 H2) (on_dy _ _ H1 H2) \n               (on_dx _ _ H2 H3) (on_dy _ _ H2 H3)\n               (on_dx _ _  H1 (on_add _ _ H2 H3))\n               (on_dy _ _  H1 (on_add _ _ H2 H3))\n               (on_dx _ _  (on_add _ _ H1 H2) H3)\n               (on_dy _ _  (on_add _ _ H1 H2) H3).\ncase: p => x1 y1; case: q => x2 y2; case: r => x3 y3.\nrewrite /add /on /= /dx /dy /= => H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11.\ncongr (_,_).\n  field[H1 H2 H3]; repeat split => //.\n    contradict H8; field_simplify; last by split.\n    apply: Kdiv_eq_0_compat_r.\n    by rewrite -H8; ring.\n  contradict H10; field_simplify; last by split.\n  apply: Kdiv_eq_0_compat_r.\n  by rewrite -H10; ring.\nTime field[H1 H2 H3]=> //.\nrepeat split => //.\n  contradict H9; field_simplify; last by split.\n  apply: Kdiv_eq_0_compat_r.\n  by rewrite -H9; ring.\ncontradict H11; field_simplify; last by split; auto.\napply: Kdiv_eq_0_compat_r.\nrewrite -H11; ring.\nTime Qed.\n\nEnd Edwards.\n\n", "meta": {"author": "thery", "repo": "EdwardsEllipticCurve", "sha": "b72bfbf4cf910ed8efc36c9540e5e76fc8643e45", "save_path": "github-repos/coq/thery-EdwardsEllipticCurve", "path": "github-repos/coq/thery-EdwardsEllipticCurve/EdwardsEllipticCurve-b72bfbf4cf910ed8efc36c9540e5e76fc8643e45/Edwards.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6773663024743459}}
{"text": "Require Import EqNat.\nRequire Import List.\nRequire Import ListSet.\nRequire Import PropLogic.\n\nImport ListNotations.\n\n(* define when two assign. agree on the atomic formulas *)\nInductive in_assignment: atomic -> assignment -> Prop :=\n| in1 : forall a tv,\n          in_assignment a [(a, tv)]\n| in2 : forall a b c,\n          in_assignment a b -> in_assignment a (c::b).\n\nInductive suitable_2 : formula -> assignment -> Prop :=\n| s1 : forall atm a b, \n         in_assignment atm a -> suitable_2 (Atom atm) a -> suitable_2 (Atom atm) (b::a)\n| s2 : forall f a b,\n         suitable_2 f a -> suitable_2 (Negation f) a -> suitable_2 (Negation f) (b::a)\n| s3 : forall f g a b,\n         suitable_2 f a /\\ suitable_2 g a -> suitable_2 (Disjunction f g) a -> suitable_2 (Disjunction f g) (b::a).\n\n(*   s1 : forall (a : assignment)  (atm : atomic), *)\n(*          in_assignment atm a -> suitable_2 (Atom atm) a *)\n(* | s2 : forall f a b, *)\n(*          suitable_2 f a -> suitable_2 f (b::a). *)\n(* | s2 : forall f a, *)\n(*          suitable_2 f a -> suitable_2 (Negation f) a *)\n(* | s3 : forall f g a, *)\n(*          suitable_2 f a -> suitable_2 g a -> suitable_2 (Disjunction f g) a. *)\n\nInductive agree : assignment -> assignment -> list atomic -> Prop :=\n  a1 : forall a b,\n         agree a b []\n| a2 : forall a b c d,\n         agree a b c -> in_assignment d a /\\ in_assignment d b -> agree a b (d::c).\n\nFixpoint atomicfs (f : formula) : list atomic :=\n  match f with\n    | Atom atm => [atm]\n    | Negation f' => atomicfs f'\n    | Disjunction f' g => atomicfs f' ++ atomicfs g\n  end.\n\nLemma all_formulae_have_atoms: forall F,\n                                 atomicfs F <> [].\nProof. \n  unfold not.\n  induction F; try (intros; inversion H).\n  apply IHF.\n  apply H1.\n  apply app_eq_nil in H1.\n  inversion H1.\n  generalize H0.\n  apply IHF1.\nQed.\n\nLemma empty_assignment_not_suitable: forall F,\n                                       suitable_2 F [] -> False.\nProof. \n  intros.\n  inversion H.\nQed.  \n\nLemma suitable_atomic_bidirectional: forall a atm,\n                                       suitable_2 (Atom atm) a -> in_assignment atm a.\n  induction atm.\n  intros.\n  inversion H.\n  apply in2.\n  apply H1.\nQed.\n\nLemma atoms_negation_invariant: forall F,\n                                  atomicfs F = atomicfs (Negation F).\nProof. \n  induction F; simpl; reflexivity.\nQed.\n\nLemma atoms_disjunction_invariant: forall F G,\n                                     atomicfs F ++ atomicfs G = atomicfs (Disjunction F G).\nProof. \n  induction F; destruct G; simpl; reflexivity.\nQed.\n\nLemma negation_suitable_invariant: forall F a,\n                                     suitable_2 F a <-> suitable_2 (Negation F) a.\nProof. \n  induction F.\n  split; intros.\n  induction a0.\n  inversion H.\n  apply s2.\nAdmitted.\n\nLemma suitable_invariant_under_assignment_aug: forall F a b,\n                                                 suitable_2 F a -> suitable_2 F (b::a).\nProof. \n  induction a.\n  intros.\n  inversion H.\n  intros.\n  induction F; intros; simpl.\n  apply s1. \n  apply suitable_atomic_bidirectional in H.\n  apply H.\n  apply H.\n  apply s2.\n  apply negation_suitable_invariant.\n  apply H.\n  apply H.\n  inversion H.\n  apply s3.\n  split; inversion H2.\n  generalize H5.\n  apply IHF1.\n  generalize H6.\n  apply IHF2.\n  \n\nLemma suitable_assignment_contains_all_atoms: forall F a atm,\n                                                suitable_2 F a -> In atm (atomicfs F) -> in_assignment atm a.\nProof.\n  induction F.\n  intros.\n  apply suitable_atomic_bidirectional.\n  unfold atomicfs in H0.\n  inversion H0.\n  rewrite H1 in H.\n  apply H.\n  inversion H1. \n  intros.\n  simpl in H0.\n  induction a.\n  inversion H.\n  generalize H0.  \n  apply negation_suitable_invariant in H.\n  generalize H.\n  apply IHF.\n  intros.\n  inversion H.\n  simpl in H0.\n  apply in_app_or in H0.\n  inversion H0.\n  generalize H6.\n  inversion H3.\n  \n\nLemma suitable_extract : forall a F atm,\n                           suitable_2 F a -> (In atm (atomicfs F)) -> in_assignment atm a.\nProof. \n  intros.\n  induction F.\n  apply suitable_atomic_bidirectional in H.\n  simpl in H0.\n  inversion H0.\n  rewrite <- H1.\n  apply H.\n  inversion H1.\n  apply IHF.\n\n\nTheorem hw1_prob3 : forall a b F,\n                      (suitable F a) /\\ (suitable F b) /\\ agree a b (atomicfs F) -> ((eval_formula F a) = (eval_formula F b)).  \nProof. \n  intros; induction F.\n", "meta": {"author": "etosch", "repo": "logic", "sha": "40e1f1c26bd89fed3a814d90166995cc44568ef5", "save_path": "github-repos/coq/etosch-logic", "path": "github-repos/coq/etosch-logic/logic-40e1f1c26bd89fed3a814d90166995cc44568ef5/src/hw1_prob3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.677366302033241}}
{"text": "Theorem ex1: forall p q r : Prop,\n             (p -> q) -> (((p -> r) -> q) -> q).\nProof.\n  Require Import Classical.\n  intros. apply NNPP. intro.\n  apply H1. apply H0. intro.\n  apply NNPP. intro. apply H1.\n  apply (H H2).\nQed.\n\nTheorem ex2: forall p q r s : Prop,\n             ((p -> q) -> r) -> ((r -> p) -> (s -> p)).\nProof.\n  Require Import Classical.\n  intros. apply NNPP. intro. apply H2.\n  apply H0. apply H. intro. contradiction.\nQed.\n\nTheorem ex3: forall p q r s : Prop,\n             ((p -> r) -> (s -> p)) -> \n             (((r -> q) -> p) -> (s -> p)).\nProof.\n  Require Import Classical.\n  intros. apply NNPP. intro. apply H2.\n  apply H0. intro. apply NNPP. intro. apply H2.\n  apply H. intro. assumption. assumption.\nQed.\n\nTheorem ex4: forall p q r s : Prop,\n             ((r -> q) -> (s -> p)) -> \n             ((r -> p) -> (s -> p)).\nProof.\n  Require Import Classical.\n  intros. apply NNPP. intro. apply H2.\n  apply H. intro. apply NNPP. intro.\n  apply H2. apply (H0 H3).\n  assumption.\nQed.\n\nTheorem ex5: forall p q r s : Prop,\n             (((r -> p) -> p) -> (s -> p))\n             -> (((p -> q) -> r) -> (s -> p)).\nProof.\n  Require Import Classical.\n  intros. apply NNPP. intro. apply H2.\n  apply H. intro. apply H3. apply H0.\n  intro. contradiction. assumption.\nQed.\n\nTheorem ex6: forall p q r : Prop,\n             (((p -> r) -> q) -> q) -> \n             ((q -> r) -> (p -> r)).\nProof.\n  Require Import Classical.\n  intros. apply NNPP. intro. apply H2.\n  apply H0. apply H. intro.\n  pose proof (H3 H1) as H4. contradiction.\nQed.\n\nTheorem ex7: forall p s : Prop,\n             ((p -> s) -> p) -> ((s -> p) -> p) -> p.\nProof.\n  Require Import Classical.\n  intros. apply NNPP. intro. apply H1. apply H0.\n  intro. apply H. intro. (*contradiction.*) \n  assumption. \nQed.\n\nTheorem ex8: forall a b c : Prop,\n             ((a -> b) -> c) -> ((a -> c) -> c).\nProof.\n  Require Import Classical.\n  intros. apply NNPP. intro. apply H1.\n  apply H. intro. apply NNPP. intro. apply H1.\n  apply (H0 H2).\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/Ex2_Church.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6773558995699299}}
{"text": "Require Export Relation.\n\n\n\nTheorem composition_assoc {f g h : Rel} :\n    h ○ (g ○ f) = (h ○ g) ○ f.\nProof.\n  apply Extensionality => ad.\n  repeat rewrite composition.\n  split => [H | H].\n  + induction H as [a]; induction H as [c]; induction H as [d].\n    induction H as [adad]; induction H as [ac_gf cd_h].\n    apply composition in ac_gf.\n    induction ac_gf as [x]; induction H as [b]; induction H as [z].\n    induction H as [ac_xz]; induction H as [ab_f bc_g].\n    apply eq_OrderPair in ac_xz; induction ac_xz; subst x z.\n    exists a; exists b; exists d.\n    apply (conj adad).\n    apply (conj ab_f).\n    apply composition.\n    exists b; exists c; exists d.\n    split.\n    - done.\n    - apply (conj bc_g cd_h).\n  + induction H as [a]; induction H as [b]; induction H as [d].\n    induction H as [ad_ad]; induction H as [ab_f bd_hg].\n    apply composition in bd_hg.\n    induction bd_hg as [b_]; induction H as [c]; induction H as [d_].\n    induction H as [bd_bd]; induction H as [bc_g cd_h].\n    apply eq_OrderPair in bd_bd; induction bd_bd; subst b_ d_.\n    exists a; exists c; exists d.\n    apply (conj ad_ad).\n    split.\n    - rewrite composition.\n      exists a; exists b; exists c.\n      done.\n    - done.\nQed.\n\nTheorem composition_dom {f g A B C : set} :\n      f | A → B -> g | B → C -> Dom (g ○ f) = Dom f.\nProof.\n  intros fAB gBC.\n  induction fAB as [funcf fAB].\n  induction fAB as [domf_A ranf_B].\n  induction gBC as [funcg gBC].\n  induction gBC as [domg_B rang_C].\n  apply Extensionality => a.\n  split => [H | H].\n  + apply dom in H.\n    induction H as [c].\n    apply composition in H.\n    induction H as [a_]; induction H as [b]; induction H as [c_].\n    induction H as [acac]; induction H as [ab_f bc_g].\n    apply eq_OrderPair in acac; induction acac; subst a_ c_.\n    apply dom.\n    by exists b.\n  + apply dom in H as H0.\n    induction H0 as [b ab_f] .\n    specialize (ranf_B b).\n    move: ranf_B; rewrite ran => ranf_B.\n    assert (exists a, (<|a,b|>) ∈ f).\n    by exists a.\n    specialize (ranf_B H0) as bB  .\n    clear H0 ranf_B.\n    rewrite <- domg_B in bB.\n    apply dom in bB.\n    induction bB as [c bc_g].\n    apply dom.\n    exists c.\n    rewrite composition.\n    by exists a; exists b; exists c.\nQed.    \n\nTheorem composition_ran {f g A B C : set} :\n      f | A → B -> g | B → C -> Ran (g ○ f) ⊂ (Ran g).\nProof.\n  intros fAB gBC c H.\n  induction fAB as [domf_A ranf_B].\n  induction gBC as [domg_B rang_C].\n  apply ran in H.\n  induction H as [a H].\n  apply composition in H.\n  induction H as [a_]; induction H as [b]; induction H as [c_].\n  induction H as [acac]; induction H as [ab_f bc_g].\n  apply eq_OrderPair in acac; induction acac; subst a_ c_.\n  apply ran.\n  by exists b.\nQed.\n\nTheorem composition_func {f g : set} :\n  func f -> func g -> func (g ○ f).\nProof.\n  intros funcf funcg.\n  intros x H.\n  apply dom in H.\n  induction H as [z H].\n  assert (xz_gf : (<|x,z|> ∈ (g ○ f))) by done.\n  apply composition in H.\n  induction H as [x_]; induction H as [y]; induction H as [z_].\n  induction H as [xyxy]; induction H as [xy_f yz_g].\n  apply eq_OrderPair in xyxy; induction xyxy; subst x_ z_.\n  exists z.\n  apply (conj xz_gf).\n  intros z_ H.\n\n  assert (x_domf : x ∈ (Dom f)).\n  apply dom.\n  by exists y.\n  specialize (funcf x x_domf).\n  induction funcf as [y0 Hf].\n  induction Hf as [xy0f Hf].\n\n  assert (y_domg : y ∈ (Dom g)).\n  apply dom.\n  by exists z.\n  specialize (funcg y y_domg).\n  induction funcg as [z0 Hg].\n  induction Hg as [yz0g Hg].\n\n  apply composition in H.\n  induction H as [x1]; induction H as [y1]; induction H as [z1].\n  induction H as [xzxz]; induction H as [xyf yzg].\n  apply eq_OrderPair in xzxz; induction xzxz; subst x1 z1.\n  apply (Hg z) in yz_g.\n  apply (Hf y1) in xyf.\n  apply (Hf y) in xy_f.\n  subst y0 y1 z0.\n  by apply (Hg z_) in yzg.\nQed.  \n\n\n\nTheorem composition_map {f g A B C : set} :\n     f | A → B -> g | B → C -> g ○ f | A → C.\nProof.\n  intros fAB gBC.\n  inversion fAB as [funcf fAB_].\n  induction  fAB_ as [domf_A ranf_B].\n  inversion gBC as [funcg gBC_].\n  induction gBC_ as [domf_B ranf_C].\n  apply (conj (composition_func funcf funcg)).\n  split.\n  + rewrite <- domf_A.\n    apply (composition_dom fAB gBC).\n  + intros c H.\n    apply ran in H.\n    induction H as [a H]     .\n    apply composition in H.\n    induction H as [a_]; induction H as [b]; induction H as [c_].\n    induction H as [acac]; induction H as [ab_f bc_g].\n    apply eq_OrderPair in acac; induction acac; subst a_ c_.\n    specialize (ranf_C c).\n    move:ranf_C ; rewrite ran => H.\n    by apply (H (ex_intro (fun b => (<| b, c |>) ∈ g) b bc_g)).\nQed.\n\nTheorem dom_reverse {f : set} :\n    Dom (Reverse f) = Ran f.\nProof.\n  apply Extensionality => x.\n  rewrite dom; rewrite ran.\n  split => [H | H].\n  + induction H as [y xy_f'] .\n    apply (reverse f) in xy_f'.\n    by exists y.\n  + induction H as [y yx_f].\n    exists y.\n    by apply (reverse f).\nQed.\n\nTheorem ran_reverse {f : set} :\n    Ran (Reverse f) = Dom f.\nProof.\n  apply Extensionality => x.\n  rewrite dom; rewrite ran.\n  split => [H | H].\n  + induction H as [y yx_f'] .\n    apply (reverse f) in yx_f'.\n    by exists y.\n  + induction H as [y xy_f] .\n    exists y.\n    by apply (reverse f).\nQed.  \n\n\n\nTheorem reverse_bijection (f A B : set) :\n  Bijection f A B <-> f | A → B /\\ Reverse f | B → A.\nProof.    \n  split => [H | H].  \n  + induction H as [fAB H].\n    induction H as [ranf_B inj].\n    induction fAB as [funcf fAB].\n    induction fAB as [domf_A ranfB].\n    split.\n    - apply (conj funcf) .\n      apply (conj domf_A ranfB).\n    - split.\n      * intros b b_ranf.\n        rewrite dom_reverse in b_ranf.\n        apply ran in b_ranf.\n        induction b_ranf as [a abf] .\n        exists a.\n        split.\n        by apply reverse.\n        intros a_ ab_f.\n        apply (reverse f) in ab_f.\n        apply inj.\n        apply (eq_value funcf) in abf.\n        apply (eq_value funcf) in ab_f.\n        by subst b.\n      * rewrite dom_reverse.\n        rewrite ran_reverse.\n        apply (conj ranf_B)         .\n        by rewrite domf_A.\n  + induction H as [fAB f'BA] .\n    induction fAB as [funcf fAB].\n    induction fAB as [domf_A ranfB].    \n    induction f'BA as [funcf' H].\n    induction H as [ranf_B domfA].\n    rewrite dom_reverse in ranf_B.\n    rewrite ran_reverse in domfA.\n    split.\n    - apply (conj funcf) .\n      apply (conj domf_A ranfB).\n    - apply (conj ranf_B) .\n      intros a a_ H.\n      specialize (funcf' (Value f a)).\n      assert (H1 : (Value f a) ∈ (Dom (Reverse f))).\n      rewrite dom_reverse.\n      apply ran.\n      exists a.\n      apply (value f a funcf).\n      apply funcf' in H1.\n      induction H1 as [a0 H1].\n      induction H1 as [_ H1].\n      specialize (value f a funcf) as abf.\n      specialize (value f a_ funcf) as a_bf.\n      rewrite <- H in a_bf.\n      rewrite <- reverse in abf.\n      rewrite <- reverse in a_bf.\n      apply (H1 a) in abf.\n      apply (H1 a_) in a_bf.\n      by subst a0.\nQed.\n\nTheorem reverse_ {R : set} :\n  forall u, u ∈ (Reverse R) <-> exists x y, u = <|y,x|> /\\ <|x,y|> ∈ R.\nProof.\n  intros u.\n  split => [H | H].\n  + apply class in H.\n    apply H.\n  + inversion H as [x H0]; induction H0 as [y].\n    induction H0 as [y_yx xy_R].\n    apply class.\n    split.\n    - apply product.\n      exists y; exists x.\n      split.\n      apply ran.\n      by exists x.\n      split.\n      apply dom.\n      by exists y.\n      done.\n    - by exists x; exists y.\nQed.       \n\n\n\n\nTheorem reverse_composition {f g : set} :\n  Reverse (g ○ f) = (Reverse f) ○ (Reverse g).\nProof.\n  apply Extensionality => u.\n  rewrite composition.\n  rewrite reverse_.\n  split => [H | H].\n  + induction H as [x]; induction H as [z] .\n    induction H as [u_yx xy_gf].\n    apply composition in xy_gf.\n    induction xy_gf as [x_]; induction H as [y]; induction H as [z_].\n    induction H as [xzxz]; induction  H as [xy_f yz_g].\n    apply eq_OrderPair in xzxz; induction xzxz; subst x_ z_.\n    exists z; exists y; exists x.\n    by repeat rewrite reverse.\n  + induction H as [x]; induction H as [y]; induction H as [z].\n    move: H.  repeat rewrite reverse.  intro H.\n    induction H as [u_xz]; induction H as [yx_g zy_f].\n    exists z; exists x.\n    apply (conj u_xz).\n    apply composition.\n    by exists z; exists y; exists x.\nQed.\n\nTheorem domran {f x y} :\n    <|x,y|> ∈ f -> x ∈ (Dom f) /\\ y ∈ (Ran f).\nProof.\n  intro H.\n  split.\n  by apply dom; exists y.\n  by apply ran; exists x.\nQed.  \n\nTheorem value_composition  {f g A B C : set} :\n  f | A → B -> g | B → C -> forall x, Value g (Value f x)  = Value (g ○ f)x.\nProof.\n  intros fAB gBC x.\n\n  induction fAB as [funcf  Hf].\n  induction Hf as [domf_A ranf_B].\n  specialize (value f x funcf) as xfx_f.\n  specialize (domran xfx_f) as dom_ran.\n  induction dom_ran as [x_domf fx_ranf].\n  specialize (funcf x x_domf) as Hf.\n  induction Hf as [y0 Hf].\n  induction Hf as [xy0_f Hf].\n  specialize (Hf (Value f x) xfx_f) as Hf'.\n  subst y0.\n  specialize (ranf_B (Value f x) fx_ranf).\n\n  induction gBC as [funcg  Hg].\n  induction Hg as [domf_B ranf_C].\n  rewrite <- domf_B in ranf_B.\n  specialize (funcg (Value f x) ranf_B) as Hz.\n  induction Hz as [z0 Hz].\n  induction Hz as [fxy_g Hz].\n  specialize (value g (Value f x) funcg) as fxgfx_g.\n  specialize (Hz (Value g (Value f x)) fxgfx_g) as Hz'.\n  subst z0.\n\n  specialize (value (g ○ f) x (composition_func funcf funcg)) as H.\n  apply composition in H.\n  induction H as [x0]; induction H as [y]; induction H as [z].\n  induction H as [xzxz H]; induction H as [xy_f yz_g].\n  apply eq_OrderPair in xzxz; induction xzxz; subst x0 z.\n  apply (Hf y) in xy_f.\n  subst y.\n  by apply Hz.\nQed.\n\n  \n\n\n\nTheorem composition_injection {f g A B C} :\n    Injection f A B -> Injection g B C -> Injection (g ○ f) A C.\nProof.\n  intros injfAB injgBC.\n  induction injfAB as [fAB injf].\n  induction injgBC as [gBC injg].\n  specialize (value_composition fAB gBC) as H0.\n  split.\n  + apply (composition_map fAB gBC).\n  + intros x x' H.\n    apply injf.\n    apply injg.\n    rewrite (H0 x).\n    rewrite (H0 x').\n    done.\nQed.   \n\nTheorem composition_surjection {f g A B C} :\n    Surjection f A B -> Surjection g B C -> Surjection (g ○ f) A C.\nProof.\n  intros Hf Hg.\n  induction Hf as [fAB ranf_B].\n  induction Hg as [gBC rang_C].\n  split.\n  + apply (composition_map fAB gBC).\n  + apply Extensionality => c.\n    rewrite ran.\n    split => [H | H].\n    - induction H as [a H].\n      apply composition in H.\n      induction H as [a0]; induction H as [b]; induction H as [c0].\n      induction H as [acac]; induction H as [ab_f bc_g].\n      apply eq_OrderPair in acac; induction acac; subst a0 c0.\n      apply domran in bc_g.\n      induction bc_g.\n      by subst C.\n    - rewrite <- rang_C in H.\n      apply ran in H.\n      induction H as [b bc_g].\n      apply domran in bc_g as dom_ran.\n      induction dom_ran as [b_domg _].      \n      induction gBC as [_ Hg].\n      induction Hg as [domg_B _].\n      subst B.\n      rewrite domg_B in b_domg.\n      apply ran in b_domg.\n      induction b_domg as [a ab_f].\n      exists a.\n      apply composition.\n      by exists a; exists b; exists c.\nQed.\n\nTheorem image_subset {f A B P1 P2 : set} \n  {P1_A : P1 ⊂ A} {P2_A : P2 ⊂ A} {fAB : f | A → B}:\n  P1 ⊂ P2 -> Image f P1 ⊂ (Image f P2).\nProof.    \n  intros H b a_fP1.\n  apply image in a_fP1.\n  induction a_fP1 as [a H1].\n  induction H1 as [a_P1 ab_f].\n  specialize (H a a_P1).\n  rewrite image.\n  by exists a.\nQed.  \n\nTheorem image_cup \n  {f A B P1 P2 : set} {fAB : f | A → B}\n  {P1_A : P1 ⊂ A} {P2_A : P2 ⊂ A} {P1P2 : P1 ⊂ P2} :\n  Image f (P1 ∪ P2) = (Image f P1) ∪ (Image f P2).\nProof.\n  apply Extensionality => b.  \n  rewrite cup.\n  repeat rewrite image.\n  split => [H | H].\n  + induction H as [a].\n    induction H as [a_P1P2 ab_f].\n    apply cup in a_P1P2.\n    induction a_P1P2 as [a_P1 | a_P2].\n    - by apply or_introl; exists a.\n    - by apply or_intror; exists a.\n  + induction H as [H | H].\n    - induction H as [a]; induction H as [aP abf].\n      exists a.\n      rewrite cup.\n      apply (conj (or_introl aP) abf).\n    - induction H as [a]; induction H as [aP abf].\n      exists a.\n      rewrite cup.\n      apply (conj (or_intror aP) abf).\nQed.\n\nTheorem image_cap \n  {f A B P1 P2 : set} {fAB : f | A → B}\n  {P1_A : P1 ⊂ A} {P2_A : P2 ⊂ A} {P1P2 : P1 ⊂ P2} :\n  Image f (P1 ∩ P2) ⊂ ((Image f P1) ∩ (Image f P2)).\nProof.\n  intros b.\n  rewrite cap.\n  repeat rewrite image.\n  intro H.\n  induction H as [a]; induction H as [aP1P2 abf].\n  apply cap in aP1P2; induction aP1P2 as [aP1 aP2].\n  split.\n  + by exists a.\n  + by exists a.\nQed.\n\nTheorem image_diff \n  {f A B P : set} {fAB : f | A → B} {P_A : P ⊂ A} :\n  ((Image f A) // (Image f P)) ⊂ (Image f (A // P)).\nProof.\n  intro b.\n  rewrite diff.\n  repeat rewrite image.\n  intro H.\n  induction H as [L R].\n  induction L as [a]; induction H as [aA abf].\n  move : R; rewrite <- allnot_notexists; intro H.\n  specialize (H a).\n  apply DeMorgan_notand in H.\n  induction H as [not_aP | not_abf].\n  - exists a.\n    split.\n    * by apply diff.\n    * done.\n  - case (not_abf abf).\nQed.\n\n\n\n\n\nTheorem eqclass_refl {R : Rel} {A : set}  (H : equivalence R A) :\n    forall a, a ∈ A -> a ∈ (eqClass H a).\nProof.\n  intros a aA.\n  apply eqclass.\n  induction H as [H _].\n  by specialize (H a aA).\nQed.\n\n\n\nTheorem eqclass_eq {R A : set} (H : equivalence R A) :\n  forall a b, a ∈ A -> b ∈ A -> <|a,b|> ∈ R <-> eqClass H a = eqClass H b.\nProof.\n  intros a b aA bA.\n  inversion H as [refl_ H0].\n  induction H0 as [sym_ trans_].\n  split => [H0 | H0].\n  + apply Extensionality => i.\n    repeat rewrite eqclass.\n    split => [H1 | H1].\n    - induction H1 as [iA ai_R].\n      apply (conj iA).\n      apply (sym_ a b aA bA) in H0.\n      apply (trans_ b a i bA aA iA H0 ai_R).\n    - induction H1 as [iA ai_R].\n      apply (conj iA).\n      apply (trans_ a b i aA bA iA H0 ai_R).\n  + specialize (eqclass_refl H a aA) as H1.    \n    rewrite H0 in H1.\n    apply eqclass in H1.\n    induction H1 as [_ H1].\n    by apply (sym_ b a bA aA ) in H1.\nQed.\n\nTheorem eqclass_contra {R A : set} {H : equivalence R A} :\n    forall a b, a ∈ A -> b ∈ A ->\n    eqClass H a <> eqClass H b -> (eqClass H a ∩ (eqClass H b)) = ∅.\nProof.\n  intros a b aA bA H0.\n  apply Extensionality => i.\n  rewrite cap.\n  repeat rewrite eqclass.\n  split => [H1 | H1].\n  + induction H1 as [l r] .\n    induction l as [iA ai_R].\n    induction r as [_ bi_R].\n    inversion H as [refl_ H2].\n    induction H2 as [sym_ trans_].\n    apply (sym_ b i bA iA) in bi_R.\n    specialize (trans_ a i b aA iA bA ai_R bi_R).\n    apply (eqclass_eq H a b aA bA ) in trans_.\n    case (H0 trans_).\n  + specialize (empty i) as H2.\n    case (H2 H1).\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", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "sets", "sha": "4db587e90349f1c8786dae9ffd14f56535512e07", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-sets", "path": "github-repos/coq/gaxiiiiiiiiiiii-sets/sets-4db587e90349f1c8786dae9ffd14f56535512e07/Relations_Theorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.67735588609769}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_betweennotequal.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_inequalitysymmetric.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_ondiameter : \n   forall D F K M N P Q, \n   CI K F P Q -> Cong F D P Q -> Cong F M P Q -> BetS D F M -> BetS D N M ->\n   InCirc N K.\nProof.\nintros.\nassert (neq D F) by (forward_using lemma_betweennotequal).\nassert (neq F D) by (conclude lemma_inequalitysymmetric).\nassert (~ ~ (BetS D N F \\/ BetS F N M \\/ eq F N)).\n {\n intro.\n assert (~ BetS D F N).\n  {\n  intro.\n  assert (BetS F N M) by (conclude lemma_3_6a).\n  contradict.\n  }\n assert (eq F N) by (conclude axiom_connectivity).\n contradict.\n }\nassert (Cong F N F N) by (conclude cn_congruencereflexive).\nassert (InCirc N K).\nby cases on (BetS D N F \\/ BetS F N M \\/ eq F N).\n{\n assert (BetS F N D) by (conclude axiom_betweennesssymmetry).\n assert (InCirc N K) by (conclude_def InCirc ).\n close.\n }\n{\n assert (InCirc N K) by (conclude_def InCirc ).\n close.\n }\n{\n assert (eq N F) by (conclude lemma_equalitysymmetric).\n assert (InCirc N K) by (conclude_def InCirc ).\n close.\n }\n(* cases *)\nclose.\nUnshelve.\nexact M.\nexact M.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_ondiameter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.6773558733178933}}
{"text": "From mathcomp Require Import all_ssreflect all_fingroup all_algebra all_solvable.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nOpen Scope ring_scope.\nImport GRing.Theory.\n\nLemma mulmxP (K : fieldType) (m n : nat) (A B : 'M[K]_(m, n)) :\n  reflect (forall u : 'rV__, u *m A = u *m B) (A == B).\nProof.\napply: (iffP eqP) => [-> //|eqAB].\napply: (@row_full_inj _ _ _ _ 1%:M); first by rewrite row_full_unit unitmx1.\nby apply/row_matrixP => i; rewrite !row_mul eqAB.\nQed.\n\nSection lfunP.\nVariable (F : fieldType).\nContext {uT vT : vectType F}.\nLocal Notation m := (\\dim {:uT}).\nLocal Notation n := (\\dim {:vT}).\n\nLemma span_lfunP (U : seq uT) (phi psi : 'Hom(uT,vT)) :\n  {in <<U>>%VS, phi =1 psi} <-> {in U, phi =1 psi}.\nProof.\nsplit=> eq_phi_psi u uU; first by rewrite eq_phi_psi ?memv_span.\nrewrite [u](@coord_span _ _ _ (in_tuple U))// !linear_sum/=.\nby apply: eq_bigr=> i _; rewrite !linearZ/= eq_phi_psi// ?mem_nth.\nQed.\n\nLemma fullv_lfunP (U : seq uT) (phi psi : 'Hom(uT,vT)) : <<U>>%VS = fullv ->\n  phi = psi <-> {in U, phi =1 psi}.\nProof.\nby move=> Uf; split=> [->//|/span_lfunP]; rewrite Uf=> /(_ _ (memvf _))-/lfunP.\nQed.\nEnd lfunP.\n\nModule passmx.\nSection passmx.\nVariable (F : fieldType).\n\nSection vecmx.\nContext {vT : vectType F}.\nLocal Notation n := (\\dim {:vT}).\n\nVariables (e : n.-tuple vT).\n\nDefinition rowmxof (v : vT) := \\row_i coord e i v.\nLemma rowmxof_linear : linear rowmxof.\nProof. by move=> x v1 v2; apply/rowP=> i; rewrite !mxE linearP. Qed.\nCanonical rowmxof_is_linear := Linear rowmxof_linear.\n\nLemma coord_rowof i v : coord e i v = rowmxof v 0 i.\nProof. by rewrite !mxE. Qed.\n\nDefinition vecof (v : 'rV_n) := \\sum_i v 0 i *: e`_i.\n\nLemma vecof_delta i : vecof (delta_mx 0 i) = e`_i.\nProof.\nrewrite /vecof (bigD1 i)//= mxE !eqxx scale1r big1 ?addr0// => j neq_ji.\nby rewrite mxE (negPf neq_ji) andbF scale0r.\nQed.\n\nLemma vecof_linear : linear vecof.\nProof.\nmove=> x v1 v2; rewrite linear_sum -big_split/=.\nby apply: eq_bigr => i _/=; rewrite !mxE scalerDl scalerA.\nQed.\nCanonical vecof_is_linear := Linear vecof_linear.\n\nVariable e_basis : basis_of {:vT} e.\n\nLemma rowmxofK : cancel rowmxof vecof.\nProof.\nmove=> v; rewrite [v in RHS](coord_basis e_basis) ?memvf//.\nby apply: eq_bigr => i; rewrite !mxE.\nQed.\n\nLemma vecofK : cancel vecof rowmxof.\nProof.\nmove=> v; apply/rowP=> i; rewrite !(lfunE, mxE).\nby rewrite coord_sum_free ?(basis_free e_basis).\nQed.\n\nLemma rowmxofE (i : 'I_n) : rowmxof e`_i = delta_mx 0 i.\nProof.\napply/rowP=> k; rewrite !mxE.\nby rewrite eqxx coord_free ?(basis_free e_basis)// eq_sym.\nQed.\n\nLemma coord_vecof i v : coord e i (vecof v) = v 0 i.\nProof. by rewrite coord_rowof vecofK. Qed.\n\nLemma rowmxof_eq0 v : (rowmxof v == 0) = (v == 0).\nProof. by rewrite -(inj_eq (can_inj vecofK)) rowmxofK linear0. Qed.\n\nLemma vecof_eq0 v : (vecof v == 0) = (v == 0).\nProof. by rewrite -(inj_eq (can_inj rowmxofK)) vecofK linear0. Qed.\n\nEnd vecmx.\n\nSection hommx.\nContext {uT vT : vectType F}.\nLocal Notation m := (\\dim {:uT}).\nLocal Notation n := (\\dim {:vT}).\n\nVariables (e : m.-tuple uT) (f : n.-tuple vT).\n\nDefinition mxof (h : 'Hom(uT, vT)) := lin1_mx (rowmxof f \\o h \\o vecof e).\n\nLemma mxof_linear : linear mxof.\nProof.\nmove=> x h1 h2; apply/matrixP=> i j; do !rewrite ?lfunE/= ?mxE.\nby rewrite linearP.\nQed.\nCanonical mxof_is_linear := Linear mxof_linear.\n\nDefinition funmx (M : 'M[F]_(m, n)) u := vecof f (rowmxof e u *m M).\n\nLemma funmx_is_linear M : linear (funmx M).\nProof.\nby rewrite /funmx => x u v; rewrite linearP mulmxDl -scalemxAl linearP.\nQed.\nCanonical funmx_linear M := Linear (funmx_is_linear M).\n\nDefinition hommx M : 'Hom(uT, vT) := linfun (funmx M).\n\nLemma hommx_linear : linear hommx.\nProof.\nrewrite /hommx; move=> x A B; apply/lfunP=> u; do !rewrite lfunE/=.\nby rewrite /funmx mulmxDr -scalemxAr linearP.\nQed.\nCanonical hommx_is_linear := Linear hommx_linear.\n\nHypothesis e_basis: basis_of {:uT} e.\nHypothesis f_basis: basis_of {:vT} f.\n\nLemma mxofK : cancel mxof hommx.\nProof.\nby move=> h; apply/lfunP=> u; rewrite lfunE/= /funmx mul_rV_lin1/= !rowmxofK.\nQed.\n\nLemma hommxK : cancel hommx mxof.\nProof.\nmove=> M; apply/matrixP => i j; rewrite !mxE/= lfunE/=.\nby rewrite /funmx vecofK// -rowE coord_vecof// mxE.\nQed.\n\nLemma mul_mxof phi u : u *m mxof phi = rowmxof f (phi (vecof e u)).\nProof. by rewrite mul_rV_lin1/=. Qed.\n\nLemma hommxE M u : hommx M u = vecof f (rowmxof e u *m M).\nProof. by rewrite -[M in RHS]hommxK mul_mxof !rowmxofK//. Qed.\n\nLemma rowmxof_mul M u : rowmxof e u *m M = rowmxof f (hommx M u).\nProof. by rewrite hommxE vecofK. Qed.\n\nLemma hom_vecof (phi : 'Hom(uT, vT)) u :\n   phi (vecof e u) = vecof f (u *m mxof phi).\nProof. by rewrite mul_mxof rowmxofK. Qed.\n\nLemma rowmxof_app (phi : 'Hom(uT, vT)) u :\n  rowmxof f (phi u) = rowmxof e u *m mxof phi.\nProof. by rewrite mul_mxof !rowmxofK. Qed.\n\nLemma vecof_mul M u : vecof f (u *m M) = hommx M (vecof e u).\nProof. by rewrite hommxE vecofK. Qed.\n\nLemma mxof_eq0 phi : (mxof phi == 0) = (phi == 0).\nProof. by rewrite -(inj_eq (can_inj hommxK)) mxofK linear0. Qed.\n\nLemma hommx_eq0 M : (hommx M == 0) = (M == 0).\nProof. by rewrite -(inj_eq (can_inj mxofK)) hommxK linear0. Qed.\n\nEnd hommx.\n\nSection hommx_comp.\n\nContext {uT vT wT : vectType F}.\nLocal Notation m := (\\dim {:uT}).\nLocal Notation n := (\\dim {:vT}).\nLocal Notation p := (\\dim {:wT}).\n\nVariables (e : m.-tuple uT) (f : n.-tuple vT) (g : p.-tuple wT).\nHypothesis e_basis: basis_of {:uT} e.\nHypothesis f_basis: basis_of {:vT} f.\nHypothesis g_basis: basis_of {:wT} g.\n\nLemma mxof_comp (phi : 'Hom(uT, vT)) (psi : 'Hom(vT, wT)) :\n  mxof e g (psi \\o phi)%VF = mxof e f phi *m mxof f g psi.\nProof.\napply/matrixP => i k; rewrite !(mxE, comp_lfunE, lfunE) /=.\nrewrite [phi _](coord_basis f_basis) ?memvf// 2!linear_sum/=.\nby apply: eq_bigr => j _ /=; rewrite !mxE !linearZ/= !vecof_delta.\nQed.\n\nLemma hommx_mul (A : 'M_(m,n)) (B : 'M_(n, p)) :\n  hommx e g (A *m B) = (hommx f g B \\o hommx e f A)%VF.\nProof.\nby apply: (can_inj (mxofK e_basis g_basis)); rewrite mxof_comp !hommxK.\nQed.\n\nEnd hommx_comp.\n\nSection vsms.\n\nContext {vT : vectType F}.\nLocal Notation n := (\\dim {:vT}).\n\nVariables (e : n.-tuple vT).\n\nDefinition msof (V : {vspace vT}) : 'M_n := mxof e e (projv V).\n(* alternative *)\n(* (\\sum_(v <- vbasis V) <<rowmxof e v>>)%MS. *)\n\nDefinition vsof (M : 'M[F]_n) := limg (hommx e e M).\n(* alternative *)\n(* <<[seq vecof e (row i M) | i : 'I_n]>>%VS. *)\n\n\nLemma mxof1 : free e -> mxof e e \\1 = 1%:M.\nProof.\nby move=> eF; apply/matrixP=> i j; rewrite !mxE vecof_delta lfunE coord_free.\nQed.\n\nHypothesis e_basis: basis_of {:vT} e.\n\nLemma hommx1 : hommx e e 1%:M = \\1%VF.\nProof. by rewrite -mxof1 ?(basis_free e_basis)// mxofK. Qed.\n\nLemma msofK : cancel msof vsof.\nProof. by rewrite /msof /vsof; move=> V; rewrite mxofK// limg_proj. Qed.\n\nLemma mem_vecof u (V : {vspace vT}) : (vecof e u \\in V) = (u <= msof V)%MS.\nProof.\napply/idP/submxP=> [|[v ->{u}]]; last by rewrite -hom_vecof// memv_proj.\nrewrite -[V in X in X -> _]msofK => /memv_imgP[v _].\nby move=> /(canRL (vecofK _)) ->//; rewrite -rowmxof_mul//; eexists.\nQed.\n\nLemma rowmxof_sub u M : (rowmxof e u <= M)%MS = (u \\in vsof M).\nProof.\napply/submxP/memv_imgP => [[v /(canRL (rowmxofK _)) ->//]|[v _ ->]]{u}.\n  by exists (vecof e v); rewrite ?memvf// -vecof_mul.\nby exists (rowmxof e v); rewrite -rowmxof_mul.\nQed.\n\nLemma vsof_sub M V : (vsof M <= V)%VS = (M <= msof V)%MS.\nProof.\napply/subvP/rV_subP => [MsubV _/submxP[u ->]|VsubM _/memv_imgP[u _ ->]].\n  by rewrite -mem_vecof MsubV// -rowmxof_sub vecofK// submxMl.\nby rewrite -[V]msofK -rowmxof_sub VsubM// -rowmxof_mul// submxMl.\nQed.\n\nLemma msof_sub V M : (msof V <= M)%MS = (V <= vsof M)%VS.\nProof.\napply/rV_subP/subvP => [VsubM v vV|MsubV _/submxP[u ->]].\n  by rewrite -rowmxof_sub VsubM// -mem_vecof rowmxofK.\nby rewrite mul_mxof rowmxof_sub MsubV// memv_proj.\nQed.\n\nLemma vsofK M : (msof (vsof M) == M)%MS.\nProof. by rewrite msof_sub -vsof_sub subvv. Qed.\n\nLemma sub_msof : {mono msof : V V' / (V <= V')%VS >-> (V <= V')%MS}.\nProof. by move=> V V'; rewrite msof_sub msofK. Qed.\n\nLemma sub_vsof : {mono vsof : M M' / (M <= M')%MS >-> (M <= M')%VS}.\nProof. by move=> M M'; rewrite vsof_sub (eqmxP (vsofK _)). Qed.\n\nLemma msof0 : msof 0 = 0.\nProof.\napply/eqP; rewrite -submx0; apply/rV_subP => v.\nby rewrite -mem_vecof memv0 vecof_eq0// => /eqP->; rewrite sub0mx.\nQed.\n\nLemma vsof0 : vsof 0 = 0%VS.\nProof. by apply/vspaceP=> v; rewrite memv0 -rowmxof_sub submx0 rowmxof_eq0. Qed.\n\nLemma msof_eq0 V : (msof V == 0) = (V == 0%VS).\nProof. by rewrite -(inj_eq (can_inj msofK)) msof0. Qed.\n\nLemma vsof_eq0 M : (vsof M == 0%VS) = (M == 0).\nProof.\nrewrite (sameP eqP eqmx0P) -!(eqmxP (vsofK M)) (sameP eqmx0P eqP) -msof0.\nby rewrite (inj_eq (can_inj msofK)).\nQed.\n\nEnd vsms.\n\nSection eigen.\n\nContext {uT : vectType F}.\n\nDefinition leigenspace (phi : 'End(uT)) a := lker (phi - a *: \\1%VF).\nDefinition leigenvalue phi a := leigenspace phi a != 0%VS.\n\nLocal Notation m := (\\dim {:uT}).\nVariables (e : m.-tuple uT).\nHypothesis e_basis: basis_of {:uT} e.\nLet e_free := basis_free e_basis.\n\nLemma lker_ker phi : lker phi = vsof e (kermx (mxof e e phi)).\nProof.\napply/vspaceP => v; rewrite memv_ker -rowmxof_sub// (sameP sub_kermxP eqP).\nby rewrite -rowmxof_app// rowmxof_eq0.\nQed.\n\nLemma limgE phi : limg phi = vsof e (mxof e e phi).\nProof.\napply/vspaceP => v; rewrite -rowmxof_sub//.\napply/memv_imgP/submxP => [[u _ ->]|[u /(canRL (rowmxofK _)) ->//]].\n  by exists (rowmxof e u); rewrite -rowmxof_app.\nby exists (vecof e u); rewrite ?memvf// -hom_vecof.\nQed.\n\nLemma leigenspaceE f a :\n   leigenspace f a = vsof e (eigenspace (mxof e e f) a).\nProof.\nby rewrite /leigenspace /eigenspace lker_ker linearB linearZ/= mxof1// scalemx1.\nQed.\n\nEnd eigen.\nEnd passmx.\nEnd passmx.\n", "meta": {"author": "math-comp", "repo": "Abel", "sha": "94499667cc4464f7748a2fd909e628a8f86a998e", "save_path": "github-repos/coq/math-comp-Abel", "path": "github-repos/coq/math-comp-Abel/Abel-94499667cc4464f7748a2fd909e628a8f86a998e/theories/xmathcomp/mxextra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.6773558725622881}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.euclidean_tactics.\nRequire Import ProofCheckingEuclid.lemma_betweennotequal.\nRequire Import ProofCheckingEuclid.lemma_collinear_ABC_ABD_BCD.\nRequire Import ProofCheckingEuclid.lemma_collinearorder.\nRequire Import ProofCheckingEuclid.lemma_inequalitysymmetric.\nRequire Import ProofCheckingEuclid.lemma_s_ncol_n_col.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_s_intersecting_triangles_ncol_ADE :\n\tforall A B D E F,\n\tTriangle A B D ->\n\tTriangle B A E ->\n\tBetS A F D ->\n\tBetS B F E ->\n\tnCol A D E.\nProof.\n\tintros A B D E F.\n\tintros Triangle_ABD.\n\tintros Triangle_BAE.\n\tintros BetS_A_F_D.\n\tintros BetS_B_F_E.\n\n\tassert (nCol_A_B_D := Triangle_ABD).\n\tunfold Triangle in nCol_A_B_D.\n\n\tassert (nCol_B_A_E := Triangle_BAE).\n\tunfold Triangle in nCol_B_A_E.\n\n\tdestruct Triangle_ABD as (_ & neq_A_D & _ & _ & _ & _).\n\tdestruct Triangle_BAE as (_ & _ & neq_A_E & _ & _ & _).\n\tpose proof (lemma_s_ncol_n_col _ _ _ nCol_A_B_D) as n_Col_A_B_D.\n\tpose proof (lemma_s_ncol_n_col _ _ _ nCol_B_A_E) as n_Col_B_A_E.\n\n\tpose proof (lemma_betweennotequal _ _ _ BetS_A_F_D) as (neq_F_D & _ & _).\n\tpose proof (lemma_betweennotequal _ _ _ BetS_B_F_E) as (neq_F_E & _ & _).\n\tpose proof (lemma_inequalitysymmetric _ _ neq_A_D) as neq_D_A.\n\n\tassert (Col A F D) as Col_A_F_D by (unfold Col; one_of_disjunct BetS_A_F_D).\n\tassert (Col B F E) as Col_B_F_E by (unfold Col; one_of_disjunct BetS_B_F_E).\n\tpose proof (lemma_collinearorder _ _ _ Col_A_F_D) as (_ & Col_F_D_A & Col_D_A_F & _ & _).\n\tpose proof (lemma_collinearorder _ _ _ Col_B_F_E) as (_ & Col_F_E_B & _ & _ & _).\n\n\tassert (~ eq D E) as neq_D_E.\n\t{\n\t\tintros eq_D_E.\n\n\t\tassert (Col F D B) as Col_F_D_B by (rewrite eq_D_E; exact Col_F_E_B).\n\t\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_F_D_A Col_F_D_B neq_F_D) as Col_D_A_B.\n\t\tpose proof (lemma_collinearorder _ _ _ Col_D_A_B) as (_ & Col_A_B_D & _ & _ & _).\n\n\t\tcontradict Col_A_B_D.\n\t\texact n_Col_A_B_D.\n\t}\n\n\tassert (~ BetS A D E) as nBetS_A_D_E.\n\t{\n\t\tintros BetS_A_D_E.\n\n\t\tassert (Col A D E) as Col_A_D_E by (unfold Col; one_of_disjunct BetS_A_D_E).\n\t\tpose proof (lemma_collinearorder _ _ _ Col_A_D_E) as (Col_D_A_E & _ & _ & _ & _).\n\n\t\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_D_A_E Col_D_A_F neq_D_A) as Col_A_E_F.\n\t\tpose proof (lemma_collinearorder _ _ _ Col_A_E_F) as (_ & _ & _ & _ & Col_F_E_A).\n\t\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_F_E_A Col_F_E_B neq_F_E) as Col_E_A_B.\n\t\tpose proof (lemma_collinearorder _ _ _ Col_E_A_B) as (_ & _ & _ & _ & Col_B_A_E).\n\n\t\tcontradict Col_B_A_E.\n\t\texact n_Col_B_A_E.\n\t}\n\n\tassert (~ BetS A E D) as nBetS_A_E_D.\n\t{\n\t\tintros BetS_A_E_D.\n\t\tassert (Col A E D) as Col_A_E_D by (unfold Col; one_of_disjunct BetS_A_E_D).\n\n\t\tpose proof (lemma_collinearorder _ _ _ Col_A_E_D) as (_ & _ & Col_D_A_E & _ & _).\n\n\t\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_D_A_E Col_D_A_F neq_D_A) as Col_A_E_F.\n\t\tpose proof (lemma_collinearorder _ _ _ Col_A_E_F) as (_ & _ & _ & _ & Col_F_E_A).\n\t\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_F_E_A Col_F_E_B neq_F_E) as Col_E_A_B.\n\t\tpose proof (lemma_collinearorder _ _ _ Col_E_A_B) as (_ & _ & _ & _ & Col_B_A_E).\n\n\t\tcontradict Col_B_A_E.\n\t\texact n_Col_B_A_E.\n\t}\n\n\tassert (~ BetS D A E) as nBetS_D_A_E.\n\t{\n\t\tintros BetS_D_A_E.\n\n\t\tassert (Col D A E) as Col_D_A_E by (unfold Col; one_of_disjunct BetS_D_A_E).\n\n\t\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_D_A_E Col_D_A_F neq_D_A) as Col_A_E_F.\n\t\tpose proof (lemma_collinearorder _ _ _ Col_A_E_F) as (_ & _ & _ & _ & Col_F_E_A).\n\t\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_F_E_A Col_F_E_B neq_F_E) as Col_E_A_B.\n\t\tpose proof (lemma_collinearorder _ _ _ Col_E_A_B) as (_ & _ & _ & _ & Col_B_A_E).\n\n\t\tcontradict Col_B_A_E.\n\t\texact n_Col_B_A_E.\n\t}\n\n\tunfold nCol.\n\trepeat split.\n\texact neq_A_D.\n\texact neq_A_E.\n\texact neq_D_E.\n\texact nBetS_A_D_E.\n\texact nBetS_A_E_D.\n\texact nBetS_D_A_E.\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_intersecting_triangles_ncol_ADE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.6773393560411178}}
{"text": "(** * Merge:  Merge Sort, With Specification and Proof of Correctness*)\n\nRequire Import Le Lt Gt Decidable PeanoNat Recdef.\nFrom Coq Require Import Recdef.  (* needed for [Function] feature *)\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\nNotation  \"a >=? b\" := (Nat.leb b a)\n                          (at level 70) : nat_scope.\nNotation  \"a >? b\"  := (Nat.ltb b a)\n                         (at level 70) : nat_scope.\n\n\nLemma eqb_reflect : forall x y, reflect (x = y) (x =? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.eqb_eq.\nQed.\n\nLemma ltb_reflect : forall x y, reflect (x < y) (x <? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.ltb_lt.\nQed.\n\nLemma leb_reflect : forall x y, reflect (x <= y) (x <=? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.leb_le.\nQed.\n\nLtac bdestruct X :=\n  let H := fresh in let e := fresh \"e\" in\n   evar (e: Prop);\n   assert (H: reflect e X); subst e;\n    [eauto with bdestruct\n    | destruct H as [H|H];\n      [ | try first [apply not_lt in H | apply not_le in H]]].\n\n\nHint Resolve ltb_reflect leb_reflect eqb_reflect : bdestruct.\n\nLtac inv H := inversion H; clear H; subst.\n\nInductive sorted: list nat -> Set :=\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(** Mergesort is a well-known sorting algorithm, normally presented\n    as an imperative algorithm on arrays, that has worst-case\n    O(n log n) execution time and requires O(n) auxiliary space.\n\n    The basic idea is simple: we divide the data to be sorted into two\n    halves, recursively sort each of them, and then\n    merge together the (sorted) results from each half:\n\n    [[\n    mergesort xs =\n      split xs into ys,zs;\n      ys' = mergesort ys;\n      zs' = mergesort zs;\n      return (merge ys' zs')\n    ]]\n\n    (As usual, if you are unfamiliar with mergesort see Wikipedia or\n    your favorite algorithms textbook.)\n\n    Mergesort on lists works essentially the same way: we split the\n    original list into two halves, recursively sort each sublist,\n    and then merge the two sublists together again.  The only \n    difference, compared to the imperative algorithm, is that splitting\n    the list takes O(n) rather than O(1) time; however, that \n    does not affect the asymptotic cost, since the merge step already\n    takes O(n) anyhow. \n*)\n\n(* ================================================================= *)\n(** ** Split and its properties *)\n\n(** Let us try to write down the Gallina code for mergesort.\n    The first step is to write a splitting function. There are\n    several ways to do this, since the exact splitting method does\n    not matter as long as the results are (roughly) equal in size.\n    For example, if we know the length of the list, we could use that to split\n    at the half-way point. But here is an attractive alternative, which simply\n    alternates assigning the elements into left and right sublists:\n*)     \n\nFixpoint split {X:Type} (l:list X) : (list X * list X) :=\n  match l with\n  | [] => ([],[])\n  | [x] => ([x],[])\n  | x1::x2::l' =>\n    let (l1,l2) := split l' in\n    (x1::l1,x2::l2)\n  end.\n\n(** Note: For generality, we made this function polymorphic, since the\n    type of the values in the list is irrelevant to the splitting process. \n\n    While this function is straightforward to define, it can be a bit challenging\n    to work with.  Let's try to prove the following lemma, which is obviously true:\n*)\n\nLemma split_len_first_try: forall {X} (l:list X) (l1 l2: list X),\n    split l = (l1,l2) ->\n    length l1 <= length l /\\\n    length l2 <= length l.\nProof.\n  induction l; intros. \n  - inv H. simpl. lia. \n  - destruct l as [| x l'].\n    + inv H. \n      split; simpl; auto.\n    + inv H. destruct (split l') as [l1' l2'] eqn:E. inv H1. \n      (* We're stuck! The IH talks about [split (x::l')] but we\n         only know aobut [split (a::x::l')]. *)\nAbort.\n\n(** The problem here is that the standard induction principle for lists\n    requires us to show that the property being proved follows for      \n    any non-empty list if it holds for the tail of that list.\n    What we want here is a \"two-step\" induction principle, that instead requires\n    us to show that the property being proved follows for a list of\n    length at least two, if it holds for the tail of the tail of that list.\n    Formally: \n*)\n\nDefinition list_ind2_principle:=\n    forall (A : Type) (P : list A -> Prop),\n      P [] ->\n      (forall (a:A), P [a]) ->\n      (forall (a b : A) (l : list A), P l -> P (a :: b :: l)) ->\n      forall l : list A, P l.\n\n(** If we assume the correctness of this \"non-standard\" induction principle, \n    our [split_len] proof is easy, using a form of the [induction] tactic \n    that lets us specify the induction principle to use: \n*)\n\nLemma split_len': list_ind2_principle -> \n    forall {X} (l:list X) (l1 l2: list X),\n    split l = (l1,l2) ->\n    length l1 <= length l /\\\n    length l2 <= length l.\nProof.\n  unfold list_ind2_principle; intro IP.\n  induction l using IP; intros.\n  - inv H. lia.\n  - inv H. simpl; lia.\n  - inv H. destruct (split l) as [l1' l2']. inv H1. \n    simpl. \n    destruct (IHl l1' l2') as [P1 P2]; auto; lia.\nQed.\n\n(** We still need to prove [list_ind2_principle].  There are several\n    ways to do this, but one direct way is to write an explicit proof\n    term, thus: *)\n\nDefinition list_ind2 :\n  forall (A : Type) (P : list A -> Prop),\n      P [] ->\n      (forall (a:A), P [a]) ->\n      (forall (a b : A) (l : list A), P l -> P (a :: b :: l)) ->\n      forall l : list A, P l :=\n  fun (A : Type)\n      (P : list A -> Prop)\n      (H : P [])\n      (H0 : forall a : A, P [a])\n      (H1 : forall (a b : A) (l : list A), P l -> P (a :: b :: l))  => \n    fix IH (l : list A) :  P l :=\n    match l with\n    | [] => H\n    | [x] => H0 x\n    | x::y::l' => H1 x y l' (IH l')\n    end.\n\n(** Here, the [fix] keyword defines a local recursive function [IH]\n    of type [forall l:list A, P l], which is returned as the overall value of\n    [list_ind2]. As usual, this function must be obviously terminating \n    to Coq (which it is because the recursive call is on a sublist [l'] \n    of the original argument [l]) and the [match] must be exhaustive over\n    all possible lists (which it evidently is). \n*)\n\n(** With our induction principle in hand, we can finally prove \n    [split_len] free and clear: \n*)\n\nLemma split_len: forall {X} (l:list X) (l1 l2: list X),\n    split l = (l1,l2) ->\n    length l1 <= length l /\\\n    length l2 <= length l.\nProof.\n apply (@split_len' list_ind2).\nQed.\n\n(** **** Exercise: 3 stars, standard (split_perm) *)\n\n(** Here's another fact about [split] that we will find useful later on.  \n*)\n\n\nLemma split_perm : forall {X:Type} (l l1 l2: list X),\n    split l = (l1,l2) -> Permutation l (l1 ++ l2).\nProof.\n  induction l as [| x | x1 x2 l1' IHl'] using list_ind2; intros.\n  inv H. simpl. auto.\n  inv H. simpl. auto.\n  inv H.\n  destruct (split l1').\n  inv H1.\n  assert (Permutation l1' (l ++ l0)) .\n  apply (IHl' l l0 ) . auto.\n  simpl.   econstructor.\n  assert (Permutation (x2 :: l1') (x2 :: (l ++ l0))).\n  econstructor. auto.\n  econstructor. apply H0. clear H0.\n  assert (Permutation (x2 :: l ++ l0) (x2 :: l0 ++ l)).\n  econstructor.    apply Permutation_app_comm.\n  econstructor. apply H0.\n  assert ((x2 :: l0 ++ l) = ((x2 :: l0) ++ l )) .\n  auto.\n  rewrite H1.\n  apply Permutation_app_comm.\nQed.\n\n\n\n\n(* ================================================================= *)\n(** ** Defining Merge *)\n\n(** Next, we need a [merge] function, which takes two\n    sorted lists (of naturals) and returns their sorted result.\n    This would seem easy to write:\n\n    [[\n    Fixpoint merge l1 l2 :=\n      match l1, l2 with\n      | [], _ => l2\n      | _, [] => l1\n      | a1::l1', a2::l2' =>\n          if a1 <=? a2 then a1 :: merge l1' l2 else a2 :: merge l1 l2'\n      end.\n    ]]\n\n    But Coq will reject this definition with the message:\n\n    [[\n    Error: Cannot guess decreasing argument of fix.\n    ]]\n\n    Coq insists the every [Fixpoint] definition be structurally recursive\n    on some specified argument, meaning that at each recursive call the\n    callee is passed a value that is a sub-term of the caller's argument value.\n    This check guarantees that every [Fixpoint] is actually terminating.\n\n    It is fairly obvious that this function is in fact terminating, because\n    at each call, either [l1] or [l2] is passed the tail of its original value.\n    But unfortunately, [Fixpoint] recursive calls must always decrease on\n    a _single fixed_ argument -- and neither [l1] nor [l2] will do. (That's\n    why Coq couldn't guess the one to use.)  We might reasonably wish\n    that Coq was a little smarter, but it isn't.\n\n    There are a number of ways to get around the problem of convincing\n    Coq that a function is actually terminating when the \"natural\" [Fixpoint]\n    doesn't work. In this case, a little creativity (or a peek at the Coq\n    library) might lead us to the following definition:\n*)\n\nFixpoint merge l1 l2  {struct l1} :=\n  let fix merge_aux l2 :=\n  match l1, l2 with\n  | [], _ => l2\n  | _, [] => l1\n  | a1::l1', a2::l2' =>\n      if a1 <=? a2 then a1 :: merge l1' l2 else a2 :: merge_aux l2'\n  end\n  in merge_aux l2.\n\n(** Coq accepts the outer definition because it is structurally\n    decreasing on [l1] (we specify that with the [{struct l1}] annotation,\n    although Coq would have guessed this even if we didn't write it), \n    and it accepts the inner definition because it is structurally recursive \n    on its (sole) argument. (Note that [let fix ... in ... end] is just a \n    mechanism for  defining a local recursive function.)  \n\n    This definition will turn out to work pretty well; the only irritation \n    is that simplification will show the definition of [merge_aux], as\n    illustrated by the following examples. \n\n    First, let's remind ourselves that Coq desugars a [match] over multiple \n    arguments into a nested sequence of matches: \n*)\n\nPrint merge.\n\n(** ==> (after a little renaming for clarity)\n\n    [[\n    fix merge (l1 l2 : list nat) {struct l1} : list nat :=\n      let\n        fix merge_aux (l2 : list nat) : list nat :=\n          match l1 with\n          | [] => l2\n          | a1 :: l1' =>\n              match l2 with\n              | [] => l1\n              | a2 :: l2' =>\n                  if a1 <=? a2 then a1 :: merge l1' l2 else a2 :: merge_aux l2'\n              end\n          end in\n      merge_aux l2.\n    ]]\n*)\n\n(** Let's prove the following simple lemmas about [merge]: \n*)\n\nLemma merge2 : forall (x1 x2:nat) r1 r2,\n    x1 <= x2 ->\n    merge (x1::r1) (x2::r2) =\n    x1::merge r1 (x2::r2).\nProof.\n  intros.\n  simpl. (* This blows up in an unpleasant way, but we can\n      still make some sense of it.  Look at the\n      [(fix merge_aux ...)] term. It represents the\n      the local function [merge_aux] after the value of the\n      free variable [l1] has been substituted by [x1::r1],\n      the match over [l1] has been simplified to its\n      second arm (the non-empty case) and [x1] and [r1] have\n      been substituted for the pattern variables [a1] and [l1']. \n      The entire [fix] is applied to [r2], but Coq won't attempt\n      any further simplification until the structure of [r2] \n      is known. *)\n  bdestruct (x1 <=? x2).\n  - auto.\n  - (* Since [H] and [H0] are contradictory, this case follows by [lia].\n       But (ignoring that for the moment), note that we can get further \n       simplification to occur if we give some structure to [l2]: *)\n    simpl. (* does nothing *)\n    destruct r2; simpl.  (* makes some progress *)\n    + lia.\n    + lia. \nQed.  \n\nLemma merge_nil_l : forall l, merge [] l = l. \nProof.\n  intros. simpl.\n  (* Once again, we see a version of [merge_aux] specialized to\n  the value [l1 = nil]. Now we see only the first arm (the\n  empty case) of the [match] expression, which simply returns [l2];\n  in other words, here the [fix] is just the identity function. \n  And once again, the [fix] is applied to [l].  Irritatingly,\n  Coq _still_ refuses to perform the application unless [l]\n  is destructured first (even though the answer is always [l]). *)\n  destruct l.\n  - auto.\n  - auto. \nQed.\n\n(** Morals: \n\n    (1) Even though the proof state involving local recursive\n        functions can can be hard to read, persevere!\n\n    (2) If Coq won't simplify an \"obvious\" application, try destructing\n        the argument.\n\n    We will defer stating and proving other properties of [merge] until later.\n*)\n\n(* ================================================================= *)\n(** ** Defining Mergesort *)\n\n(** Finally, we need to define the main mergesort function itself.\n    Once again, we might hope to write something simple like this:\n\n    [[\n    Fixpoint mergesort (l: list nat) :  list nat :=\n       let (l1,l2) := split l in\n       merge (mergesort l1) (mergesort l2).\n    ]]\n\n    Since this function has only one argument, Coq guesses that it is\n    intended to be structurally decreasing, but still \n    rejects the definition, this time with the complaint:\n\n    [[\n    Recursive call to mergesort has principal argument equal to \n    \"l1\" instead of a subterm of \"l\".\n    ]]\n\n    Again, the problem is that Coq has no way to know that [l1] and [l2]\n    are \"smaller\" than [l].  And this time, it is hard to complain that\n    Coq is being stupid, since the fact that [split] returns smaller\n    lists than it is passed is nontrivial.\n\n    In fact, it isn't true! Consider the behavior of [split] on \n    empty or singleton lists...  This is case where Coq's totality\n    requirements can actually help us correct the definition of \n    our code.  What we really want to write is something more like:\n\n    [[\n    Fixpoint mergesort (l: list nat) :  list nat :=\n        match l with\n        | [] => []\n        | [x] => [x]\n        | _ => let (l1,l2) := split l in merge (mergesort l1) (mergesort l2).\n    ]]\n\n    Now this function really is terminating!  But Coq still won't let us\n    write it with a [Fixpoint].  Instead, we need to use a mechanism \n    (there are several available) for defining functions that accommodates\n    an explicit way to show that the function only calls itself on smaller\n    arguments.   We will use the [Function] command:\n*)\n\nFunction mergesort (l: list nat) {measure length l} :  list nat :=\n  match l with\n  | [] => []\n  | [x] => [x]\n  | _ => let (l1,l2) := split l in\n         merge (mergesort l1) (mergesort l2)\n  end.\n\n(** [Function] is similar to [Fixpoint], but it lets us specify \n    an explicit _measure_ on the function arguments. \n    The annotation [{measure length l}] says that the function \n    [length] applied to argument [l] serves as a decreasing measure.  \n    After processing this definition, Coq enters proof mode and demands \n    proofs that each recursive call is indeed on a shorter list. \n    Happily, we proved that fact already. \n*)\n\nProof.\n  - (* recursive call on l1 *)\n    intros.\n    simpl in *. destruct (split l1) as [l1' l2'] eqn:E. inv teq1. simpl. \n    destruct (split_len _ _ _ E).\n    lia.\n  - (* recursive call on l2 *)\n    intros.\n    simpl in *. destruct (split l1) as [l1' l2'] eqn:E. inv teq1. simpl. \n    destruct (split_len _ _ _ E).\n    lia.\nDefined.\n\n(** Notice that the [Proof] must end with the keyword [Defined] rather\n    than [Qed]; if we don't do this, we won't be able to actually \n    compute with [mergesort]. \n\n    Defining [mergesort] with [Function] rather than [Fixpoint] causes\n    the automatic generation of some useful auxiliary definitions that we \n    will need when working with it. \n    First, we get a lemma [mergesort_equation], which performs a one-level\n    unfolding of the function. *)\n\nCheck mergesort_equation.\n \n(** ==> \n\n    [[\n    mergesort_equation\n     : forall l : list nat,\n       mergesort l =\n       match l with\n       | [] => []\n       | [x] => [x]\n       | x :: _ :: _ =>\n           let (l2, l3) := split l in merge (mergesort l2) (mergesort l3)\n       end\n    ]]\n\n    We should always use [apply mergesort_equation]\n    to simplify a call to [mergesort] rather than trying to [unfold] or [simpl]\n    it, which will lead to ugly or mysterious results.\n\n    Second, we get an induction principle [mergesort_ind]; performing\n    induction using this principle can be much easier than trying to\n    use list induction over the argument [l].  \n*)\n\nCheck mergesort_ind.\n\n(** ==>   \n    [[\n    mergesort_ind\n     : forall P : list nat -> list nat -> Prop,\n       (forall l : list nat, l = [] -> P [] []) ->\n       (forall (l : list nat) (x : nat), l = [x] -> P [x] [x]) ->\n       (forall l _x : list nat,\n        l = _x ->\n        match _x with\n        | _ :: _ :: _ => True\n        | _ => False\n        end ->\n        forall l1 l2 : list nat,\n        split l = (l1, l2) ->\n        P l1 (mergesort l1) ->\n        P l2 (mergesort l2) -> P _x (merge (mergesort l1) (mergesort l2))) ->\n        forall l : list nat, P l (mergesort l)\n    ]]\n*)\n\n(* ================================================================= *)\n(** ** Correctness: Sortedness *)\n\n(** As with insertion sort, our goal is to prove that mergesort produces\n    a sorted list that is a permutation of the original list, i.e. to prove\n    \n    [[\n    is_a_sorting_algorithm mergesort\n    ]] \n  \n    We will start by showing that [mergesort] produces a sorted list.  The key \n    lemma is to show that [merge] of two sorted lists produces a sorted list.\n    It is perhaps easiest to break out a sub-lemma first:\n*)\n\n(** **** Exercise: 2 stars, standard (sorted_merge1) *)\nLemma sorted_merge1 : forall x x1 l1 x2 l2,\n    x <= x1 -> x <= x2 -> \n    sorted (merge (x1::l1) (x2::l2)) ->\n    sorted (x :: merge (x1::l1) (x2::l2)).\nProof.\n  firstorder.\n  simpl in *.\n  bdestruct (x2 >=? x1 ); constructor; try lia; auto.\nQed.\n\nLemma sorted_merge2 : forall x l1 l2 ,\n    sorted (x :: l1) ->\n    sorted (x :: l2) ->\n    sorted (merge l1 l2) ->\n    sorted (x :: merge l1 l2).\nProof.\ndestruct l1; intros.\nrewrite (merge_nil_l l2) in *.\nauto.\ndestruct l2.\nsimpl in *.\nauto.\napply sorted_merge1.\ninv H. auto.\ninv H0. auto.\nauto.\nQed.\n\nLemma sorted_inv : forall x l , sorted (x :: l) -> sorted l.\nProof.\n  intros.\n  induction l.\n  constructor.\n  inv H.\n  auto.\nQed.\n\nLemma merge_nil_r : forall l , merge l [] = l .\n  Proof.\ninduction l.\nsimpl.    easy.\nsimpl.\neasy.\nQed.\n\n\n(** **** Exercise: 4 stars, standard (sorted_merge) *)\nLemma sorted_merge (l1 l2 : list nat): sorted l1 ->\n                                    sorted l2 ->\n                                    sorted (merge l1 l2) .\nProof.\n  generalize (lt_n_Sn (length l1 + length l2)).\n  remember (S (length l1 + length l2)).\n  clear Heqn.\n  generalize l1.\n  generalize l2.\n  induction n; intros.\n  lia.\n\n  destruct l3.\n  rewrite (merge_nil_l l0).\n  easy.\n  destruct l0.\n  simpl. easy.\n\n  simpl.\n  bdestruct (n1 >=? n0).\n\n  apply sorted_merge2.\n  easy.\n  econstructor.\n  easy.\n  easy.\n  apply IHn.\n  simpl in *.\n  lia.\n  eapply sorted_inv.\n  apply H0.\n  easy.\n\n  assert (sorted (n1 :: merge (n0 :: l3) l0)).\n  apply sorted_merge2.\n  econstructor.\n  lia. easy. easy.\n\n  apply IHn.\n  simpl in *.\n  lia.\n  easy.\n  eapply sorted_inv.\n  apply H1.\n  assumption.\n  \nQed.\n\n\n\n(** **** Exercise: 2 stars, standard (mergesort_sorts) *)\nLemma mergesort_sorts : forall l, sorted (mergesort l).\nProof.\n  intro.\n  functional induction (mergesort l).\n  constructor. constructor.\n  apply sorted_merge; auto.\nQed.  \n\n\n\n(* ================================================================= *)\n(** ** Correctness: Permutation *)\n\n(** Finally, we must show that [mergesort] returns a permutation of its input.\n\n    As usual, the key lemma is for [merge]. \n\n    Incidentally, you are welcome to import the alternative characterizations\n    of permutations as multisets given in [Multiset] or [BagPerm] \n    and use that instead of [Permutation] if you think it will be easier. \n    (I'm not sure!)\n*)\n\n\n(** **** Exercise: 3 stars, advanced (merge_perm) *)\nLemma merge_perm: forall (l1 l2: list nat),\n    Permutation (l1 ++ l2) (merge l1 l2).\nProof.\n    (* Hint: A nested induction on [l2] is required. *)\n  induction l1.\n  intros. rewrite (merge_nil_l l2).\n  simpl in *.\n  auto.\n  induction l2.\n  simpl.\n  assert (a :: l1 ++ [] = a :: l1).\n  f_equal.\n  apply app_nil_r.\n  rewrite H.\n  auto.\n  simpl.\n  bdestruct (a0 >=? a).\n  simpl.\n  econstructor.\n  apply IHl1.\n  assert  (Permutation ((a :: l1) ++ a0 :: l2) ((a0 :: l2) ++ a :: l1)).\n  apply Permutation_app_comm.\n  assert ((a :: l1 ++ a0 :: l2) = ((a :: l1) ++ a0 :: l2)).\n  auto.\n  rewrite H1.\n  econstructor.\n  apply H0.\n  simpl.\n  econstructor.\n  econstructor.\n  apply Permutation_app_comm.\n  exact IHl2.\nQed.\n\n  \n\n(** **** Exercise: 3 stars, advanced (mergesort_perm) *)\nLemma mergesort_perm: forall l, Permutation l (mergesort l).\nProof.\n  intros.\n  functional induction (mergesort l).\n    auto.\n    auto.\n    econstructor.\n    apply (split_perm l l1 l2 e0).\n    assert (Permutation (l1 ++ l2) ((mergesort l1) ++ (mergesort l2))).\n    apply Permutation_app.\n    auto. auto.\n    econstructor.\n    apply H.\n    apply merge_perm.\nQed.\n\n(*\n(** Putting it all together: *)\n\nTheorem mergesort_correct:\n  is_a_sorting_algorithm mergesort.\nProof.\n  split.\n  apply mergesort_perm.\n  apply mergesort_sorts.\nQed.\n*)\n(** $Date$ *)\n\n(* 2021-08-11 15:15 *)\n", "meta": {"author": "lengyijun", "repo": "MergeSort", "sha": "6338b5407322ab3d7bd5ef880079d6c26a6bb8be", "save_path": "github-repos/coq/lengyijun-MergeSort", "path": "github-repos/coq/lengyijun-MergeSort/MergeSort-6338b5407322ab3d7bd5ef880079d6c26a6bb8be/coq/length-induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424411924673, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6773393509196239}}
{"text": "Generalizable All Variables.\n\nReserved Notation \"a ~> b\" (at level 70, right associativity).\nReserved Notation \"g << f\" (at level 45).\nReserved Notation \"G <<< F\" (at level 45).\n\n(*** =============== Categories =============== ***)\n\n(****************** Definition 3.1 ******************)\nClass Category :=\n  {\n    (* The quadruple *)\n    Ob    :  Type;\n    hom   :  Ob -> Ob -> Type\n             where \"a ~> b\" := (hom a b);\n    id    :  `(hom a a);\n    comp  :  forall a b c, (hom a b) -> (hom b c) -> (hom a c)\n             where \"g << f\" := (comp _ _ _ f g);\n\n    (* Constraints *)\n    assoc :  forall a b c d (f: a~>b) (g: b~>c) (h: c~>d),\n             h << (g << f) = (h << g) << f;\n    id_l  :  forall `(f: a~>b), f << id a = f;\n    id_r  :  forall `(f: a~>b), id b << f = f\n  }.\n\nNotation \"a ~> b\"        := (@hom _ a b)  :category_scope.\nNotation \"g << f\"        := (comp _ _ _ f g)  :category_scope.\n\nOpen Scope category_scope.\n\nLemma juggle1 :\n  forall `{_:Category}`(f:a~>b)`(g:b~>c)`(h:c~>d)`(k:d~>e),\n    k << (h << (g << f)) = k << (h << g) << f.\nProof.\n  intros; repeat rewrite -> assoc; reflexivity.\nQed.\n\nLemma juggle2 :\n  forall `{_:Category}`(f:a~>b)`(g:b~>c)`(h:c~>d)`(k:d~>e),\n    ((k << h) << g) << f = k << (h << g) << f.\nProof.\n  intros; repeat rewrite -> assoc; reflexivity.\nQed.\n\nLemma juggle3 :\n  forall `{_:Category}`(f:a~>b)`(g:b~>c)`(h:c~>d)`(k:d~>e),\n    (k << h) << (g << f) = k << (h << g) << f.\nProof.\n  intros; repeat rewrite -> assoc; reflexivity.\nQed.\n\n(****************** Remark 3.2 ******************)\nDefinition dom `(C: Category) (a b: Ob) (_ : a ~> b)\n  := a.\n\nDefinition cod `(C: Category) (a b: Ob) (_ : a ~> b)\n  := b.\n\n(****************** Example 3.3 ******************)\nInstance catSet : Category :=\n  {\n    Ob   := Type;\n    hom  := fun a b => a -> b;\n    id   := fun a x => x;\n    comp := fun a b c (f: a -> b) (g: b -> c) x => g (f x)\n  }.\nProof.\n  trivial.\n  trivial.\n  trivial.\nDefined.\n\nInductive EmptyMor : Type := .\nClass IdentityMor (A: Type) : Type :=\n  {\n    im_f := fun x: A => x\n  }.\n\n(*** =============== The Duality Principle =============== ***)\n\n(****************** Definition 3.5 ******************)\nDefinition dual `(C: Category) : Category.\nProof.\n  apply (Build_Category)\n  with (Ob := Ob)\n       (hom := (fun a b => b ~> a))\n       (id := id)\n       (comp := fun a b c f g => comp c b a g f).\n  - symmetry; apply assoc.\n  - intros; apply id_r.\n  - intros; apply id_l.\nDefined.\n\n(****************** Remark 3.7 ******************)\nLemma double_dual : forall `(C: Category), (dual (dual C)) = C.\nProof.\n  Admitted.\n\n(* TODO: How can we formalize the duality principle? *)\n\n(*** =============== Isomorphism =============== ***)\n\n(****************** Definition 3.8 ******************)\nClass Inversion `{C: Category} `(f: a~>b) g : Prop :=\n  {\n    inv_comp1 : g << f = id a;\n    inv_comp2 : f << g = id b\n  }.\n\nClass Isomorphism `{C: Category} `(f: a ~> b) : Prop :=\n  {\n    iso_comp1: exists g, Inversion f g\n  }.\n\n(****************** Proposition 3.10 ******************)\nTheorem morph_equal :\n  forall `(_: Category) `(f: a ~> b) (g h: b ~> a),\n    g << f = id a -> f << h = id b -> g = h.\nProof.\n  intros C a b f g h Hfg Hhf.\n  rewrite <- id_r.\n  rewrite <- Hfg.\n  rewrite <- assoc.\n  rewrite -> Hhf.\n  rewrite -> id_l.\n  reflexivity.\nQed.\n\n(****************** Corollary 3.11 ******************)\nTheorem inv_unique :\n  forall `(_: Category) `(f: a ~> b) g h,\n    Inversion f g -> Inversion f h -> g = h.\nProof.\n  intros C a b f g h Hgf Hhf.\n  apply (morph_equal _ f).\n  - destruct Hgf; assumption.\n  - destruct Hhf; assumption.\nQed.\n\n(****************** Proposition 3.14 ******************)\nLemma inv_symm :\n  forall `(_: Category) `(f: a ~> b) g,\n    Inversion f g -> Inversion g f.\nProof.\n  intros C a b f g Hfg.\n  apply Build_Inversion; destruct Hfg; assumption.\nQed.\n\nLemma double_inv :\n  forall `(_: Category) `(f: a ~> b) g h,\n    Inversion f g -> Inversion g h -> f = h.\nProof.\n  intros C a b f g h Hfg Hgh.\n  apply (morph_equal _ g).\n  - destruct Hfg; assumption.\n  - destruct Hgh; assumption.\nQed.\n\nTheorem iso_inv :\n  forall `(_: Category) `(f: a ~> b) g,\n    Isomorphism f -> Inversion f g -> Isomorphism g.\nProof.\n  intros C a b f g Hf Hfg.\n  apply Build_Isomorphism.\n  exists f.\n  apply inv_symm; assumption.\nQed.\n\nTheorem inv_comp :\n  forall `(_: Category) `(f: a ~> b) `(g: b ~> c) f' g',\n    Inversion f f' ->\n    Inversion g g' ->\n    Inversion (g << f) (f' << g').\nProof.\n  intros C a b f c g f' g' Hf Hg.\n  destruct Hf; destruct Hg.\n  apply Build_Inversion.\n  - rewrite -> juggle3; rewrite -> inv_comp5.\n    rewrite -> id_l; assumption.\n  - rewrite -> juggle3; rewrite -> inv_comp4.\n    rewrite -> id_l; assumption.\nQed.\n\nTheorem iso_comp :\n  forall `(_: Category) `(f: a ~> b) `(g: b ~> c),\n    Isomorphism f -> Isomorphism g -> Isomorphism (g << f).\nProof.\n  intros C a b f c g Hf Hg.\n  apply Build_Isomorphism.\n  destruct Hf as [comp_f]; destruct Hg as [comp_g].\n  destruct comp_f; destruct comp_g.\n  exists (x << x0).\n  apply inv_comp; assumption.\nQed.\n\n(****************** Definition 3.15 ******************)\nClass Isomorphic `{c: Category} (a b: Ob) : Prop :=\n  {\n    iso_ex : exists f: a ~> b, Isomorphism f\n  }.\n", "meta": {"author": "eternalNight", "repo": "coq-category", "sha": "dd7eabc725ac3c7264e7f67ae619632a2c92961d", "save_path": "github-repos/coq/eternalNight-coq-category", "path": "github-repos/coq/eternalNight-coq-category/coq-category-dd7eabc725ac3c7264e7f67ae619632a2c92961d/ch03_1_categories.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245618, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.677339344699924}}
{"text": "(*|\n############################################################################\nCoq ``leb`` (``<=?``) does not give me an hypothesis after case or induction\n############################################################################\n\n:Link: https://stackoverflow.com/q/66709518\n|*)\n\n(*|\nQuestion\n********\n\nI have simplified my situation to the following piece of code,\nhopefully this makes it easier to understand.\n\nI would like to prove the following Lemma:\n|*)\n\nRequire Import Arith.\nLemma example: forall a b,\n    if a <=? b then a <= b else a > b.\n\n(*| Doing the following step in the proof |*)\n\nProof.\n  intros.\n\n(*| Gives me the result |*)\n\n  Show. (* .unfold .messages *)\n\n(*|\nIt seems trivial that either ``a`` is smaller than or equal to ``b``,\nin which case I could prove ``a<=b``. In the other case that ``b`` is\nlarger than ``a`` I could prove that ``a>b``.\n\nI've tried to prove this with ``induction (a <=? b)`` or ``case (a <=?\nb)`` but both give me the following result.\n|*)\n\n  induction (a <=? b). (* .unfold *)\nAbort. (* .none *)\n\n(*|\nNow I have no way to prove these goals. I expected to gain an\nhypothesis such as ``H: a <= b`` and ``H: a > b`` in the second case.\nThis way, I would be able to prove my goals.\n\nCould anybody tell me how I could this issue of the non-appearing\nhypothesis?\n\nEdit: The whole lemma can be proven as follows:\n|*)\n\nRequire Import Arith.\nLemma example: forall a b,\n    if a <=? b then a <= b else a > b.\nProof.\n  intros.\n  case (Nat.leb_spec a b); intuition.\nQed.\n\n(*|\nAnswer\n******\n\nTo do the case distinction that you are looking for you can use\n|*)\n\nLemma leb_spec x y : BoolSpec (x <= y) (y < x) (x <=? y).\n\n(*|\nThe type ``BoolSpec`` embodies exactly what you are trying to do: if\n``(x <=? y)`` is *the boolean* ``true``, then *the proposition* ``x <=\ny`` is true, and if ``(x <=? y)`` is ``false`` then ``y < x`` is true.\nThus, ``Nat.leb_spec`` embodies the specification of the function ``x\n<=? y``, as its name suggests.\n\nNow using ``case (Nat.leb_spec a b)`` does exactly what you were\ntrying to do with ``case (a <=? b)``: it gives you two subgoals, one\nwhere ``x <=? y`` is replaced by ``true`` and you have ``x <= y`` as\nan extra hypothesis, and the other where ``x <=? y`` is replaced by\n``false`` and you have ``y < x`` as an hypothesis instead. The fact\nthat you case distinction was on a term of type ``BoolSpec`` rather\nthan simply ``bool`` did the trick.\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-leb-does-not-give-me-an-hypothesis-after-case-or-induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.6773393357399093}}
{"text": "From Coq Require Import List.\nFrom StructTact Require Import StructTactics ListTactics.\nImport ListNotations.\n\nFixpoint before_all {A : Type} (x : A) y l : Prop :=\n  match l with\n    | [] => True\n    | a :: l' => \n      ~ In x l' \\/ \n      (y <> a /\\ before_all x y l')\n  end.\n\nSection before_all.\n  Variable A : Type.\n\n  Lemma before_all_head_not_in :\n    forall l (x y : A),\n      x <> y ->\n      before_all x y (y :: l) ->\n      ~ In x l.\n  Proof using.\n    intros.\n    simpl in *.\n    break_or_hyp; auto.\n    break_and. auto.\n  Qed.\n\n  Lemma before_all_neq_append : \n  forall l (x y a : A),\n    a <> x ->\n    before_all x y l ->\n    before_all x y (l ++ [a]).\n  Proof using.\n  induction l.\n  - intros; left; auto.\n  - intros;\n    simpl in *.\n    break_or_hyp.\n    * left.\n      intro H_in.\n      do_in_app.\n      break_or_hyp; auto.\n      simpl in *.\n      break_or_hyp; auto.\n    * break_and.\n      right.\n      split; auto.\n  Qed.\n\n  Lemma before_all_not_in_1 :\n    forall l (x y : A),\n      ~ In x l ->\n      before_all x y l.\n  Proof using.\n    intros.\n    destruct l; simpl in *; auto.\n  Qed.\n\n  Lemma before_all_not_in_2 :\n    forall l (x y : A),\n      ~ In y l ->\n      before_all x y l.\n  Proof using.\n    induction l.\n    - intros. simpl in *. auto.\n    - intros. simpl in *.\n      assert (H_neq: y <> a); auto.\n      assert (H_in: ~ In y l); auto.\n   Qed.\nEnd before_all.\n", "meta": {"author": "uwplse", "repo": "StructTact", "sha": "2f2ff253be29bb09f36cab96d036419b18a95b00", "save_path": "github-repos/coq/uwplse-StructTact", "path": "github-repos/coq/uwplse-StructTact/StructTact-2f2ff253be29bb09f36cab96d036419b18a95b00/theories/BeforeAll.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245617, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.6773393326300594}}
{"text": "Inductive listn : nat -> Set :=\n  | niln : listn 0\n  | consn : forall n : nat, nat -> listn n -> listn (S n).\n\nDefinition length1 (n : nat) (l : listn n) :=\n  match l with\n  | consn n _ (consn m _ _) => S (S m)\n  | consn n _ _ => 1\n  | _ => 0\n  end.\n\nFail Type\n  (fun (n : nat) (l : listn n) =>\n   match n return nat with\n   | O => 0\n   | S n => match l return nat with\n            | niln => 1\n            | l' => length1 (S n) l'\n            end\n   end).\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/failure/Case7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.6773152755565206}}
{"text": "Require Export HRwgt.\nRequire Export Setoid.\n\nModule mHRwspec (N:Num_w).\n\nImport N.\nModule Export GG := mHRwgt(N).\n\nLemma Padd : forall x y, P x -> P y -> P (x + y).\nunfold P; intros x y Hx Hy.\nelim Hx; intros nx Hnx.\nelim Hy; intros ny Hny.\nexists (nx+ny).\nsplit.\neapply ANS2a.\nintuition.\nintuition.\nsplit.\nsetoid_replace 0 with (0+0) by ring; apply lt_plus; solve [intuition].\neapply le_trans.\neapply abs_triang.\nrewrite mult_comm.\nsetoid_replace (w * (nx+ny) ) with (w*nx + w*ny) by ring.\napply le_plus.\nrewrite mult_comm.\nintuition.\nrewrite mult_comm.\nintuition.\nQed.\n\nDefinition HRwplus (x y: HRw) : HRw := \nmatch x with exist _ xx Hxx =>\nmatch y with exist _ yy Hyy => \nexist P (xx + yy) (Padd xx yy Hxx Hyy)\nend end.\n\n(* using the property that 0=1-1 and ANSx axioms *)\nLemma lim0 : lim 0.\nProof.\nintros.\nsetoid_replace 0 with (plusA 1 (oppA 1)) by ring.\napply ANS2a.\napply ANS1.\napply ANS4.\nexists 1.\nsplit.\napply ANS1.\nrewrite abs_neg_val.\nsetoid_replace (- - (1)) with 1 by ring.\nrewrite abs_pos_val.\napply le_refl.\napply lt_le.\napply lt_0_1.\napply le_plus_inv with (z:=1).\nsetoid_replace (- (1) + 1) with 0 by ring.\nsetoid_replace (0+1) with 1 by ring.\napply lt_le.\napply lt_0_1.\nQed.\n\nLemma Popp : forall x, P x -> P (- x).\nProof.\nunfold P; intros x Hx.\nelim Hx; clear Hx; intros nx (Hlimx, (Hle0nx, Hnxw)).\nexists nx.\nsplit.\nsolve [auto].\nsplit.\nsolve [auto].\napply le_trans with (|x|).\nrewrite abs_minus.\napply le_refl.\nassumption.\nQed.\n\nDefinition HRwopp (x: HRw) : HRw :=\nmatch x with exist _ xx Hxx =>\nexist P (- xx) (Popp xx Hxx)\nend. \n\nDefinition HRwminus (x y : HRw) : HRw := HRwplus x (HRwopp y).\n\nLemma Pprod : forall x y, P x -> P y -> P (( x * y) / w).\nProof.\nunfold P; intros x y Hx Hy.\nelim Hx; intros nx Hnx.\nelim Hy; intros ny Hny.\nexists (nx * (ny+1)).\nsplit.\napply ANS2b.\nintuition.\napply ANS2a; solve [intuition| apply ANS1].\nsplit.\napply mult_pos.\nsolve [intuition].\nsetoid_replace 0 with (0+0) by ring.\napply lt_plus.\nsolve [intuition].\napply lt_0_1.\nrewrite <- (div_idg ( nx * (ny+1) * w) w).\n(* branches here *)\napply le_mult_inv with w.\napply Aw.\nrewrite <- (abs_pos_val w) at 1.\nrewrite <- abs_prod.\nrewrite div_mod2.\nrewrite div_idg.\napply le_trans with (|x * y| + | - (x * y %% w) |).\napply abs_triang.\nsetoid_replace (w* (nx * (ny+1) * w)) with ((w* (nx * ny * w))+w*w*nx) by ring.\napply le_plus.\nsetoid_replace (w * (nx * ny * w)) with ((nx*w)*(ny*w)) by ring.\nrewrite abs_prod.\napply mult_le.\napply abs_pos.\nintuition.\napply abs_pos.\nintuition.\n\napply le_trans with w.\nrewrite abs_minus.\napply lt_le; apply div_mod3.\napply Aw.\nsetoid_replace w with (w*1) at 1 by ring.\nrewrite <- mult_assoc.\napply le_mult.\napply lt_le; apply Aw.\nsetoid_replace 1 with (0+1) by ring.\napply lt_le_2.\napply mult_pos.\napply Aw.\nsolve [intuition].\napply Aw.\nleft; apply Aw.\napply lt_le; apply Aw.\napply Aw.\nQed.\n\nDefinition HRwmult (x y: HRw) : HRw := \nmatch x with exist _ xx Hxx =>\nmatch y with exist _ yy Hyy => \nexist P ((xx * yy) / w) (Pprod xx yy Hxx Hyy)\nend end.\n\nDefinition HRwdiff (x y : HRw) : Prop := x [>] y \\/ y [>] x.\n\nLemma HRwdiff0_diff0_spec_or : forall a : A, forall Ha : P a, \n  HRwdiff (exist (fun x : A => P x) a Ha) HRw0 ->  0<a\\/a<0.\nProof.\nintros; unfold HRwdiff in H; destruct H.\nunfold HRw0, HRwgt in H.\nleft.\ndestruct H.\ndestruct H as [H1 [H2 H3]].\nring_simplify in H3.\napply lt_mult_inv with x.\nassumption.\napply lt_le_trans with w.\nring_simplify.\napply Aw.\nassumption.\nright.\nunfold HRw0, HRwgt in H.\ndestruct H.\ndestruct H as [H1 [H2 H3]].\nring_simplify in H3.\napply lt_mult_inv2 with (-x).\napply lt_plus_inv with x.\nring_simplify.\nassumption.\napply lt_le_trans with w.\nring_simplify.\napply Aw.\nassumption.\nQed.\n\nLemma HRwdiff0_diff0_spec2 : forall x, (exists n:A, lim n /\\ 0 < n /\\  w <= n*|x|) ->  |x|<>0.\nProof.\nintros.\nelim H.\nintros n (Hlim,(Hlt,Hw)).\nintro.\nrewrite H0 in *.\neapply (le_lt_False w).\nrewrite mult_absorb in *.\neassumption.\napply Aw.\nQed.\n\nLemma HRwdiff0_diff0_spec : forall x, (exists n:A, lim n /\\ 0 < n /\\  w <= n*|x|) ->  ~(|x|==0).\nProof.\nintros.\nelim H.\nintros n (Hlim,(Hlt,Hw)).\nintro.\nrewrite H0 in *.\neapply (le_lt_False w).\nrewrite mult_absorb in *.\neassumption.\napply Aw.\nQed.\n\nLemma Pdiv : forall x ,  HRwdiff x HRw0 -> P ((w * w ) /(proj1_sig x)).\nProof.\nintros z Hz.\nset (x:=(proj1_sig z)).\nassert (Hx:(exists n:A, lim n /\\ 0 < n /\\  w <= n*|x|)).\nunfold x; clear x.\nrevert Hz; case z.\nintros xx Hxx H_HRwdiff.\nelim H_HRwdiff.\nsimpl.\nintros.\nelim H; intros x (Hlim, (Hlt, Hw)).\nsetoid_replace (xx + -0) with xx in Hw by ring.\nexists x; intuition.\nassert (Habs:|xx|==xx).\napply abs_pos_val.\nassert (0 <= x* xx).\napply le_trans with (y:=w).\napply lt_le; apply Aw.\nassumption.\napply le_mult_inv with (x:=x).\nassumption.\nsetoid_replace (x*0) with 0 by ring.\nassumption.\nrewrite Habs.\nassumption.\nsimpl.\nintros.\nelim H; intros x (Hlim, (Hlt, Hw)).\nrewrite plus_neutral in Hw.\nexists x; intuition.\n\nassert (Habs:|xx|==-xx).\napply abs_neg_val.\nassert (0 <= x* -xx).\napply le_trans with (y:=w).\napply lt_le; apply Aw.\nassumption.\napply le_mult_inv with (x:=x).\nassumption.\nsetoid_replace (x*0) with 0 by ring.\napply le_plus_inv with (z:=x* -xx).\nsetoid_replace (x * xx + x * - xx) with 0 by ring.\nsetoid_replace (0 + x * - xx) with (x* -xx) by ring.\nassumption.\nrewrite Habs.\nassumption.\n\ndestruct z; simpl in *; subst x.\nunfold P.\nassert (0<x0\\/x0<0).\napply (HRwdiff0_diff0_spec_or x0 p Hz).\ndestruct H.\n\nelim Hx; intros n Hn.\nexists (n+1).\nsplit.\napply ANS2a; solve [intuition | apply ANS1].\nsplit.\nsetoid_replace 0 with (0+0) by ring; apply lt_plus; solve [intuition | apply lt_0_1].\napply le_mult_inv with x0.\nassumption.\nrewrite <- (abs_pos_val x0) at 1.\nrewrite <- abs_prod.\nrewrite div_mod2.\napply le_trans with (| w * w| + | - (w* w %% x0)|).\napply abs_triang.\nrewrite (abs_pos_val x0) in Hn.\nsetoid_replace (x0 * ((n +1) * w)) with (x0 * (n * w) + x0* w) by ring.\napply le_plus.\nrewrite abs_prod.\nrewrite abs_pos_val.\nsetoid_replace (x0*(n*w)) with (w * (n*x0)) by ring.\napply le_mult.\napply lt_le; apply Aw.\nsolve [intuition].\napply lt_le; apply Aw.\napply le_trans with x0.\nrewrite abs_minus.\napply lt_le; apply div_mod3.\nassumption.\nsetoid_replace x0 with (x0*1) at 1 by ring.\napply le_mult.\napply lt_le; assumption.\nsetoid_replace 1 with (0+1) by ring.\napply lt_le_2.\napply Aw.\napply lt_le; assumption.\nleft; assumption.\napply lt_le; assumption.\n\nelim Hx; intros n Hn.\nexists (n+1).\nsplit.\napply ANS2a; solve [intuition | apply ANS1].\nsplit.\nsetoid_replace 0 with (0+0) by ring; apply lt_plus; solve [intuition | apply lt_0_1].\nrewrite abs_neg_val in Hn.\napply le_mult_inv2 with x0.\nassumption.\nsetoid_replace (x0 * (|w * w / x0 |)) with (- ((-x0) * (|w * w / x0 |))) by ring.\nrewrite <- (abs_neg_val x0) at 1.\nrewrite <- (abs_prod x0).\nrewrite div_mod2.\napply le_plus_inv with ((|w * w + - (w * w %% x0) |) + - x0 * ((n + 1) * w)).\nring_simplify; unfold minusA.\napply le_trans with (| w * w| + | - (w* w %% x0)|).\napply abs_triang.\napply le_plus.\nrewrite abs_prod.\nrewrite abs_pos_val.\nsetoid_replace (- x0*n*w) with (w * (n* - x0)) by ring.\napply le_mult.\napply lt_le; apply Aw.\nsolve [intuition].\napply lt_le; apply Aw.\napply le_trans with (-x0).\nrewrite abs_minus.\napply le_trans with (|x0|).\napply div_mod3_abs.\nright; assumption.\nrewrite abs_neg_val.\napply le_refl.\napply lt_le; assumption.\nsetoid_replace (-x0) with ((-x0)*1) by ring.\nsetoid_replace (- (x0* w)) with (-x0 * w) by ring.\napply le_mult.\napply le_plus_inv with x0; ring_simplify; apply lt_le; assumption.\nsetoid_replace 1 with (0+1) by ring.\napply lt_le_2.\napply Aw.\nright; assumption.\napply lt_le; assumption.\napply lt_le; assumption.\nQed.\n\nDefinition HRwinv (x : HRw) (H: HRwdiff x HRw0) : HRw := \nexist P ((w * w ) / (proj1_sig x)) (Pdiv x H).\n\nNotation \"x [+] y \" := (HRwplus  x y) (at level 40).\nNotation \"x [*] y \" := (HRwmult  x y)(at level 35).\n\nNotation \"[0]\" := HRw0.\nNotation \"[1]\" := HRw1.\n\nNotation \"-w x\" := (HRwopp x) (at level 30).\nNotation \"x [=] y\" := (HRwequal x y) (at level 80).\n\n(* example : \nLemma f: forall x y z, x +w -w y *w z [=] x +w (y *w z).\n*)\n\nDefinition HRw2 : HRw := [1] [+] [1].\nNotation \"[2]\" := HRw2.\nDefinition HRw3 : HRw := [2] [+] [1].\nNotation \"[3]\" := HRw3.\nEnd mHRwspec.\n", "meta": {"author": "magaud", "repo": "HR", "sha": "18ef55bf254bffed6af7c6024986665924e770e4", "save_path": "github-repos/coq/magaud-HR", "path": "github-repos/coq/magaud-HR/HR-18ef55bf254bffed6af7c6024986665924e770e4/HRw_spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6772747695521224}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\nInductive natural : Type :=   Zero : natural | Succ : natural -> natural .\n\nInductive lst : Type :=  Nil : lst | Cons : natural -> lst -> lst .\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) : natural\n           := match mult_arg0, mult_arg1 with\n              | Zero, n => Zero\n              | Succ n, m => plus (mult n m) m\n              end.\n\nFixpoint qmult (qmult_arg0 : natural) (qmult_arg1 : natural) (qmult_arg2 : natural) : natural\n           := match qmult_arg0, qmult_arg1, qmult_arg2 with\n              | Zero, n, m => m\n              | Succ n, m, p => qmult n m (plus p m)\n              end.\n\nLemma plus_succ : forall (x y : natural), plus x (Succ y) = Succ (plus x y).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_assoc : forall (x y z : natural), plus (plus x y) z = plus x (plus y z).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_zero : forall (x : natural), plus x Zero = x.\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_commut : forall (x y : natural), plus x y = plus y x.\nProof.\n   intros.\n   induction x.\n   - rewrite plus_zero. reflexivity.\n   - simpl. rewrite plus_succ. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_qmult : forall (x y z a : natural), plus (qmult x y z) a = qmult x y (plus z a).\nProof.\n   intro.\n   induction x.\n   - reflexivity.\n   - intros. simpl. rewrite IHx. rewrite plus_assoc. lfind. Admitted.\n\n", "meta": {"author": "ana-brendel", "repo": "coq-benchmarks", "sha": "78b9ca2993b0fb579d814ed17e63c6859e79681c", "save_path": "github-repos/coq/ana-brendel-coq-benchmarks", "path": "github-repos/coq/ana-brendel-coq-benchmarks/coq-benchmarks-78b9ca2993b0fb579d814ed17e63c6859e79681c/modifications/quickchick_fails/test49_goal34/lfind_goal34.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6772747550547187}}
{"text": "Module Demo.\n  Inductive ex {X: Type} (p: X -> Prop) : Prop := E (x:X) (a: p x).\n\n  (* X implicit for ex and E *)\n\n  Definition match_ex {X: Type} (p: X -> Prop) (Z: Prop)\n    : ex p -> (forall x, p x -> Z) -> Z\n    := fun a e => match a with E _ x b => e x b end.\n\n  Lemma deMorgan X (p: X -> Prop) :\n    ~ ex (fun x => p x) <-> forall x, ~ p x.\n  Proof.\n    split.\n    - intros f x a.\n      apply f.\n      exact (E p x a).   (* note eta conversion *)\n    - intros f a.\n      apply (match_ex p False a).\n      exact f.\n    Show Proof.\n  Qed.\nEnd Demo.\n\nLocate \"exists\".\nPrint ex.\n\nLemma deMorgan X (p: X -> Prop) :\n  ~ (exists x, p x) <-> forall x, ~ p x.\nProof.\n  split.\n  - intros f x a. apply f. exists x. exact a.\n  - intros f [x a]. exact (f x a).\n    Show Proof.\nQed.\n\nGoal forall X (p: X -> Prop),\n    ~ (exists x, p x) <-> forall x, ~ p x.\nProof.\n  refine (fun X p => conj (fun f x a => _) (fun f b => _)).\n  - refine (f (ex_intro p x a)).\n  - refine (match b with ex_intro _ x a => f x a end).\n  Show Proof.\nQed.\n\nTheorem Barber X (p: X -> X -> Prop) :\n  ~ (exists x, forall y, p x y <-> ~ p y y).\nProof.\n  intros [x H]. specialize (H x). tauto.\nQed.\n\n(** Lawvere *)\n\nFact negb_no_fp :\n  ~ exists x, negb x = x.\nProof.\n  intros [[|] H]; discriminate.  \nQed.\n\nFact not_no_fp :\n  ~ exists P: Prop, (~P) = P.\nProof.\n  intros [P H].\n  enough (H1: ~(P <-> P)).\n  - tauto.\n  -  pattern P at 2. rewrite <-H. tauto.\nQed.\n\nDefinition surjective {X Y} (f: X -> Y) :=\n  forall y, exists x, f x = y.\n\nTheorem Lawvere X Y (f: X -> X -> Y) (g: Y -> Y) :\n  surjective f -> exists y, g y = y.\nProof.\n  intros H.\n  specialize (H (fun x => g (f x x))) as [x H].\n  apply (f_equal (fun f => f x)) in H.\n  exists (f x x).\n  easy.\nQed.\n\nCorollary Lawvere_bool X :\n  ~ exists f: X -> X -> bool, surjective f.\nProof.\n  intros [f H].\n  apply negb_no_fp.\n  revert H. apply Lawvere.\nQed.\n\nCorollary Lawvere_Prop X :\n  ~ exists f: X -> X -> Prop, surjective f.\nProof.\n  intros [f H].\n  apply not_no_fp.\n  revert H. apply Lawvere.\nQed.\n\n(** Exercise: Equational proof of not_no_fp, tricky *)\n\nCorollary not_no_fp' X :\n  (~X) <> X.\nProof.\n  intros H.\n  pose (id:= fun a: False => a).\n  enough (exists a, id a = a) as [[] _].\n  enough (exists f: X -> X -> False, surjective f) as [f H1].\n  - revert H1. apply Lawvere.\n  - pattern (X -> False). rewrite H.\n    exists (fun x => x). intros x. exists x. reflexivity.\nQed.\n", "meta": {"author": "uds-psl", "repo": "MPCTT", "sha": "8ab02bcad069d29105794e2a8fe03b07dcecb86e", "save_path": "github-repos/coq/uds-psl-MPCTT", "path": "github-repos/coq/uds-psl-MPCTT/MPCTT-8ab02bcad069d29105794e2a8fe03b07dcecb86e/coq/exquant.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6772747504495257}}
{"text": "From Coq Require Import ZArith Znumtheory Lia Psatz List Bool.\nFrom Coqtail Require Import Ztools Zeqm Zlittle_fermat Zpow Zprime.\n\n(** This file defines the Rabin Miller primality test, first as a\ntheorem, then as a boolean function.\n\nWe prove it is sound, in that it returns true when p is prime.\n\nWe prove it is complete below some bounds with sufficient sets of\nwitnesses:\n\n- below 2048 for the set {2}\n- below 10000 for the set {2,3}\n- below 1373653 for the set {2,3}\n\nThe last item can be checked but it takes a lot of time. Without\nparallelism, it is even worse, and enabling parallelism for all files\nmakes compiling most other files more slowly, so we removed this\nexhaustive check.\n*)\n\nTheorem square_roots_of_unity (x p : Z) :\n  prime p ->\n  x ^ 2 ≡ 1 [p] ->\n  x ≡ 1 [p] \\/ x ≡ -1 [p].\nProof.\n  intros pp.\n  rewrite !eqm_divide.\n  replace (x ^ 2 - 1) with ((x - 1) * (x + 1)) by lia.\n  now intros H % prime_mult.\n  all: apply prime_not_0, pp.\nQed.\n\nLemma miller_rabin_step (p a r d : Z) :\n  prime p ->\n  0 <= d ->\n  0 <= r ->\n  a ^ (2 ^ (r + 1) * d) ≡ 1 [p] ->\n  a ^ (2 ^ r * d) ≡ 1 [p] \\/\n  a ^ (2 ^ r * d) ≡ - 1 [p].\nProof.\n  intros pp Hd Hr H.\n  apply square_roots_of_unity; auto.\n  rewrite eqm_divide in *; try apply prime_not_0, pp.\n  enough ((a ^ (2 ^ r * d)) ^ 2 = a ^ (2 ^ (r + 1) * d)) by congruence.\n  assert (2 ^ (r + 1) * d = (2 ^ r * d) * 2) as ->\n      by now rewrite Z.pow_add_r; lia || auto.\n  rewrite (Z.pow_mul_r _ _ 2). easy.\n  pose proof Z.pow_nonneg 2 r ltac:(lia). lia. lia.\nQed.\n\nLemma miller_rabin_step' (p a r d : Z) :\n  prime p ->\n  0 <= d ->\n  1 <= r ->\n  a ^ (2 ^ r * d) ≡ 1 [p] ->\n  a ^ (2 ^ (r - 1) * d) ≡ 1 [p] \\/\n  a ^ (2 ^ (r - 1) * d) ≡ - 1 [p].\nProof.\n  intros pp d0 r1 e.\n  apply miller_rabin_step; auto; try lia.\n  exact_eq e. do 4 f_equal. lia.\nQed.\n\nLemma factoring_out_prime p x :\n  prime p -> 0 < x -> exists k y, x = p ^ k * y /\\ ~(p | y) /\\ 0 <= k.\nProof.\n  intros pp xz. generalize xz.\n  refine (Z_lt_induction\n            (fun x => 0 < x -> exists k y : Z, x = p ^ k * y /\\ ~ (p | y) /\\ 0 <= k)\n            _ x ltac:(lia)).\n  clear x xz; intros x IHx xz.\n  destruct (Zdivide_dec p x) as [ px | ? ].\n  2:{ exists 0, x. split. rewrite Z.pow_0_r. lia. split. auto. lia. }\n  pose proof prime_ge_2 p pp as p3.\n  assert (0 < x / p). {\n    apply Z.div_str_pos. split. lia.\n    eapply Z.divide_pos_le; eauto.\n  }\n  destruct (IHx (x / p)) as (k & y & e & py & kz).\n  - split. apply Z.div_pos; lia. apply Z.div_lt; lia.\n  - auto.\n  - exists (1 + k), y. split; auto.\n    assert (k < 0 \\/ 0 <= k) as [|] by lia.\n    + rewrite Z.pow_neg_r in e; auto. lia.\n    + rewrite Z.pow_add_r; try lia.\n      rewrite <-Z.mul_assoc, <-e.\n      replace (p ^ 1) with p by lia.\n      apply Z_div_exact_2. lia.\n      apply Zdivide_mod, px.\n    + split; auto. lia.\nQed.\n\nLemma factoring_out_prime_at_least_once p x :\n  prime p -> 0 < x -> (p | x) -> exists k y, x = p ^ k * y /\\ ~(p | y) /\\ 1 <= k.\nProof.\n  intros pp xz px.\n  destruct (factoring_out_prime p x pp xz) as (k & y & -> & py & kz).\n  exists k, y; intuition.\n  enough (k <> 0) by lia.\n  intros ->.\n  apply py. exact_eq px. f_equal.\n  lia.\nQed.\n\nLemma Even_div x : Z.Even x <-> (2 | x).\nProof.\n  split; intros [k]; exists k; lia.\nQed.\n\nLemma Odd_div x : Z.Odd x <-> ~(2 | x).\nProof.\n  split.\n  - intros [k ->] [l e]. lia.\n  - intros d. destruct (Z.Even_or_Odd x) as [ [k ->] | ]; auto.\n    destruct d. exists k; lia.\nQed.\n\nLemma Even_not_Odd x : Z.Even x <-> ~Z.Odd x.\nProof.\n  rewrite Even_div, Odd_div.\n  destruct (Zdivide_dec 2 x); tauto.\nQed.\n\nLemma Odd_not_Even x : Z.Odd x <-> ~Z.Even x.\nProof.\n  rewrite Even_div, Odd_div.\n  destruct (Zdivide_dec 2 x); tauto.\nQed.\n\nTheorem miller_rabin_criterion (p : Z) :\n  p > 2 ->\n  prime p ->\n  exists s d : Z,\n    0 < s /\\\n    0 < d /\\\n    Z.Odd d /\\\n    p - 1 = 2 ^ s * d /\\\n    forall a,\n      0 < a < p ->\n      a ^ d ≡ 1 [p] \\/\n      exists r, 0 <= r < s /\\ a ^ (2 ^ r * d) ≡ -1 [p].\nProof.\n  intros p3 pp.\n  pose proof primes_are_often_odd p ltac:(lia) pp as op.\n  destruct (factoring_out_prime_at_least_once 2 (p - 1))\n    as (s & d & psd & d2 & s1).\n  - apply prime_2.\n  - lia.\n  - destruct op as (k & ->). exists k. lia.\n  - assert (0 < d). {\n      enough (~d = 0 /\\ ~d < 0) by lia. split; intros d0.\n      - apply d2. exists 0. lia.\n      - enough (2 ^ s * d < 0) by lia. apply Z.mul_pos_neg. 2:lia.\n        apply Z.pow_pos_nonneg; lia.\n    }\n    exists s, d. repeat split; try lia.\n    + apply Odd_div, d2.\n    + intros a zap.\n      pose proof Fermat's_little_theorem_Z_pZ p a pp zap as f.\n      rewrite psd in f. clear psd.\n      apply eqm_divide in f; try now apply prime_not_0.\n      change (a ^ (2 ^ s * d) ≡ 1 [p]) in f.\n      (* main recurrence *)\n      assert (s0 : 0 <= s) by lia.\n      revert s s0 s1 f.\n      match goal with\n        |- forall s, 0 <= s -> ?G =>\n        apply (Z.right_induction (fun s => G))\n      end.\n      intros ? ? ->; tauto.\n      lia.\n      intros s s0 IHs s0_ asp.\n      apply miller_rabin_step in asp; lia || auto.\n      destruct asp as [e | e].\n      * destruct (Z.eq_dec s 0) as [-> | s1].\n        -- left. exact_eq e. repeat f_equal. lia.\n        -- destruct (IHs ltac:(lia) e) as [ ? | (r & lr & E)]; auto.\n           right. exists r. split; lia || auto.\n      * right. exists s. split; lia || auto.\nQed.\n\n(* There will be pseudoprimes for many sets of [a]. The deterministic\n variant, of running time ~O(log^4), uses the bound 2ln(p) which\n relies on the generalized Riemann hypothesis. Maybe more useful would\n be to prove that the set {2,3,5,7,11} suffices for p<=10^14. *)\n\n(* First step to implement the primality test: remove the null bits *)\n\nFixpoint remove_twos (x : positive) : (nat * positive) :=\n  match x with\n  | xO p => let (k, d) := remove_twos p in (S k, d)\n  | _ => (O, x)\n  end.\n\nLemma Odd_xI x : Z.Odd (Z.pos x~1).\nProof.\n  exists (Z.pos x). auto.\nQed.\n\nLemma remove_twos_spec x k d :\n  remove_twos x = (k, d) <->\n  Zpos x = 2 ^ (Z.of_nat k) * Zpos d /\\ Z.Odd (Zpos d).\nProof.\n  revert k d; induction x; intros k d; split.\n  - intros [=<-<-]. simpl; split; auto. apply Odd_xI.\n  - intros [e _]. simpl.\n    assert (k = O) as ->. {\n      destruct k. easy. exfalso.\n      eapply Odd_not_Even. eapply (Odd_xI x).\n      rewrite e. rewrite <-Zpower_nat_Z. exists (Zpower_nat 2 k * Z.pos d).\n      change (Zpower_nat 2 (S k)) with (2 * Zpower_nat 2 k).\n      lia.\n    }\n    change (2 ^ Z.of_nat 0) with 1 in e.\n    f_equal. lia.\n  - simpl. destruct (remove_twos x) as (k_, d_).\n    intros [=<-->]. rename k_ into k.\n    specialize (IHx k d). apply proj1 in IHx. spec IHx by auto.\n    destruct IHx as [e od]. split; auto.\n    rewrite <-Zpower_nat_Z in *.\n    change (Zpower_nat 2 (S k)) with (2 * Zpower_nat 2 k).\n    lia.\n  - simpl. destruct (remove_twos x) as (k_, d_).\n    specialize (IHx k_ d_). apply proj1 in IHx.\n    destruct IHx as [ex hd_]; auto.\n    change (Z.pos x~0) with (2 * Z.pos x).\n    rewrite ex.\n    intros [ex' hd].\n    assert (k <= k_ \\/ k > S k_ \\/ k = S k_)%nat as [lk | [lk | ->]] by lia.\n    + enough (Z.Even (Z.pos d)) by now apply Odd_not_Even in hd.\n      exists (2 ^ Z.of_nat (k_ - k) * Z.pos d_).\n      rewrite <-(Z.mul_cancel_l _ _ (2 ^ Z.of_nat k)). 2:lia.\n      rewrite <-ex'. replace k_ with (k + (k_ - k))%nat at 1 by lia.\n      rewrite <-!Zpower_nat_Z, Zpower_nat_is_exp. lia.\n    + enough (Z.Even (Z.pos d_)) by now apply Odd_not_Even in hd_.\n      exists (2 ^ Z.of_nat (k - k_ - 2) * Z.pos d).\n      rewrite <-(Z.mul_cancel_l _ _ (2 * 2 ^ Z.of_nat k_)). 2:lia.\n      rewrite <-!Zpower_nat_Z in *.\n      transitivity (Zpower_nat 2 k_ * Zpower_nat 2 (k - k_ - 2) * 4 * Z.pos d).\n      2: lia.\n      change 4 with (Zpower_nat 2 2).\n      rewrite Z.mul_assoc in ex'. rewrite ex'.\n      rewrite <-2Zpower_nat_is_exp.\n      repeat f_equal. lia.\n    + enough (d_ = d) by congruence.\n      rewrite <-!Zpower_nat_Z in *.\n      change (Zpower_nat 2 (S k_)) with (2 * Zpower_nat 2 k_) in ex'.\n      enough (Z.pos d_ = Z.pos d) by congruence.\n      rewrite <-(Z.mul_cancel_l _ _ (2 * Zpower_nat 2 k_)). lia. lia.\n  - simpl. intros [=<-<-]. intuition. exists 0; lia.\n  - intros (ek, od).\n    assert (k = O). {\n      destruct k; auto.\n      pose proof Z.pow_le_mono_r 2 1 (Z.of_nat (S k)) ltac:(lia) ltac:(lia).\n      nia.\n    }\n    simpl. subst. f_equal.\n    enough (Z.pos d = 1) by congruence.\n    auto.\nQed.\n\nDefinition eqmb (m a b : Z) : bool := a mod m =? b mod m.\n\nLemma eqmb_true_iff m a b : eqmb m a b = true <-> a ≡ b [m].\nProof.\n  apply Z.eqb_eq.\nQed.\n\nImport ListNotations.\n\nDefinition miller_rabin (l : list Z) (n : Z) : bool :=\n  if n <? 2 then false else\n    if n =? 2 then true else\n      Z.odd n &&\n      let (s, d) := remove_twos (Z.to_pos (n - 1)) in\n      forallb\n        (fun a =>\n           implb\n             ((0 <? a) && (a <? n))\n             ((pow_mod n a (Zpos d) =? 1)\n                  || existsb\n                      (fun r => pow_mod n a (2 ^ r * Zpos d) =? n - 1)\n                      (Zseq 0 s))) l.\n\nLemma pow_mod_help m a b : 1 < m -> (pow_mod m a b =? 1) = (eqmb m (a ^ b) 1).\nProof.\n  intros hm.\n  rewrite pow_mod_spec. unfold eqmb.\n  f_equal.\n  rewrite Zmod_1_l; auto.\nQed.\n\nLemma Zmod_m1_l a : 0 < a -> (-1) mod a = a - 1.\nProof.\n  intros ha.\n  destruct (Z.eq_dec a 1) as [-> | a1]. reflexivity.\n  transitivity ((a - 1) mod a).\n  - rewrite Zminus_mod, Z_mod_same, Zmod_1_l. reflexivity. lia. lia.\n  - apply Z.mod_small. lia.\nQed.\n\nLemma pow_mod_help' m a b : 0 < m -> (pow_mod m a b =? m - 1) = (eqmb m (a ^ b) (- 1)).\nProof.\n  intros hm.\n  rewrite pow_mod_spec. unfold eqmb.\n  f_equal.\n  rewrite Zmod_m1_l; auto.\nQed.\n\nLemma miller_rabin_sound l n : miller_rabin l n = false -> ~prime n.\nProof.\n  intros c pn.\n  enough (miller_rabin l n = true) by congruence; clear c.\n  unfold miller_rabin.\n\n  destruct (n <? 2) eqn:n1.\n  { apply Z.ltb_lt in n1. apply prime_ge_2 in pn. lia. }\n\n  destruct (n =? 2) eqn:n2; auto.\n  apply Z.eqb_neq in n2. apply Z.ltb_ge in n1.\n  assert (bn : n > 2) by lia. clear n1 n2.\n\n  rewrite andb_true_iff, Z.odd_spec.\n  split. apply primes_are_often_odd; auto; lia.\n\n  apply miller_rabin_criterion in pn; auto.\n  destruct pn as (s & d & zs & zd & od & e & crit).\n\n  destruct (remove_twos _) as (s_, d_) eqn:esd.\n  assert (e' : remove_twos (Z.to_pos (n - 1)) = (Z.to_nat s, Z.to_pos d)).\n  {\n    apply remove_twos_spec; split.\n    - exact_eq e; repeat f_equal.\n      + rewrite Z2Pos.id; lia.\n      + rewrite Z2Nat.id; lia.\n      + rewrite Z2Pos.id; lia.\n    - exact_eq od; f_equal.\n      rewrite Z2Pos.id; lia.\n  }\n  rewrite esd in e'. injection e' as -> ->.\n  rewrite Z2Pos.id; auto.\n\n  rewrite forallb_forall.\n  intros a al.\n  destruct (_ <? _) eqn:za. apply Z.ltb_lt in za. 2:reflexivity.\n  destruct (_ <? _) eqn:an. apply Z.ltb_lt in an. 2:reflexivity.\n  specialize (crit a ltac:(lia)).\n  change (implb (true && true) ?b) with b.\n  rewrite pow_mod_help; try lia.\n  rewrite orb_true_iff, existsb_exists, eqmb_true_iff.\n  destruct crit as [?|(r & rs & er)]. now left.\n  right. exists r.\n  rewrite pow_mod_help'; try lia.\n  rewrite eqmb_true_iff, in_Zseq.\n  split. lia. exact_eq er; repeat f_equal.\nQed.\n\nLemma miller_rabin_more_tests l l' :\n  (forall x, In x l -> In x l') -> forall n, implb (miller_rabin l' n) (miller_rabin l n) = true.\nProof.\n  intros s n.\n  unfold miller_rabin in *.\n  destruct (_ <? _). reflexivity.\n  destruct (_ =? _). reflexivity.\n  destruct (Z.odd _). 2: reflexivity.\n  destruct (remove_twos _).\n  rewrite 2andb_true_l.\n  assert (a : forall a b, (a = true -> b = true) -> implb a b = true)\n    by now intros [|] [|]; try discriminate || tauto. apply a.\n  rewrite 2forallb_forall. eauto.\nQed.\n\n(* It is faster to just use \"primeb\", it seems:\n\nDefinition primes (n : Z) := filter primeb (Zseq 1 (Z.to_nat n)).\nDefinition primesmr l (n : Z) := filter (miller_rabin l) (Zseq 1 (Z.to_nat n)).\n\nTime Eval vm_compute in primes 10000. (* 3s sec *)\nTime Eval vm_compute in primesmr [2; 3] 10000. (* 6 sec *)\n*)\n\n(** Re-using work to try an accelerate the computation *)\n\nFixpoint mainloop n s x :=\n  match s with\n  | O => false\n  | S s => (x =? n - 1) || mainloop n s ((x * x) mod n)\n  end.\n\nLemma mainloop_spec n a d s x :\n  x = pow_mod n a (Z.pos d) ->\n  mainloop n s x =\n  existsb\n    (fun r => pow_mod n a (2 ^ r * Z.pos d) =? n - 1)\n    (Zseq 0 s).\nProof.\n  replace (Z.pos d) with (2 ^ 0 * Z.pos d) at 1 by lia.\n  generalize (Z.le_refl 0).\n  generalize 0 at 2 3 4 as offset.\n  revert d x.\n  induction s. reflexivity.\n  intros d x offset oz ex.\n  change (Zseq offset (S s)) with (offset :: Zseq (1 + offset) s).\n  change (existsb ?f (?a :: ?l)) with (f a || existsb f l).\n  simpl mainloop.\n  f_equal. rewrite ex; auto.\n  apply IHs. lia.\n  replace (x * x) with (x ^ 2) by lia.\n  rewrite ex.\n  rewrite 2pow_mod_spec.\n  rewrite <-Zpow_mod. f_equal.\n  rewrite <-!Z.pow_mul_r.\n  rewrite Z.pow_add_r.\n  f_equal. lia.\n  lia.\n  lia.\n  apply Z.mul_nonneg_nonneg; try lia; try (apply Z.pow_nonneg; lia).\n  lia.\nQed.\n\nDefinition miller_rabin' (l : list Z) (n : Z) : bool :=\n  if n <? 2 then false else\n    if n =? 2 then true else\n      Z.odd n &&\n      let (s, d) := remove_twos (Z.to_pos (n - 1)) in\n      forallb\n        (fun a =>\n           implb\n             ((0 <? a) && (a <? n))\n             (let x := pow_mod n a (Zpos d) in\n              (x =? 1) ||\n              mainloop n s x)) l.\n\nLemma forallb_ext {A} (f g : A -> bool) l :\n  (forall a, f a = g a) -> forallb f l = forallb g l.\nProof.\n  intros e; induction l; simpl; congruence.\nQed.\n\nLemma implb_true_l: forall b : bool, implb true b = b. now intros []. Qed.\nLemma implb_true_r: forall b : bool, implb b true = true. now intros []. Qed.\nLemma implb_false_l: forall b : bool, implb false b = true. now intros []. Qed.\nLemma implb_false_r: forall b : bool, implb b false = negb b. now intros []. Qed.\n\nDefinition miller_rabin'_spec l n : miller_rabin' l n = miller_rabin l n.\nProof.\n  unfold miller_rabin.\n  unfold miller_rabin'.\n  destruct (n <? 2); auto.\n  destruct (n =? 2); auto.\n  destruct (Z.odd _); auto.\n  rewrite 2 andb_true_l.\n  destruct (remove_twos _) as (s, d).\n  apply forallb_ext; intros a.\n  destruct (_ && _); auto.\n  rewrite 2 implb_true_l.\n  f_equal.\n  now apply mainloop_spec.\nQed.\n\n(* Some benchmarking.\n\nmiller_rabin' is a bit faster, but not by much. If primeb (sqrt\nalgorithm) is still faster on small numbers, it does get surpassed by\nthe miller_rabin' above about 10000. miller_rabin also gets faster\nthan primeb only after about 80000.\n\nTime Eval vm_compute in length (filter  primeb                (Zseq 1 (Z.to_nat 10000))). (* 3 secs *)\nTime Eval vm_compute in length (filter (miller_rabin  [2; 3]) (Zseq 1 (Z.to_nat 10000))). (* 6 secs *)\nTime Eval vm_compute in length (filter (miller_rabin' [2; 3]) (Zseq 1 (Z.to_nat 10000))). (* 4 secs *)\n\nTime Eval vm_compute in length (filter  primeb                (Zseq 1 (Z.to_nat 20000))). (* 10.4 secs *)\nTime Eval vm_compute in length (filter (miller_rabin  [2; 3]) (Zseq 1 (Z.to_nat 20000))). (* 21.1 secs *)\nTime Eval vm_compute in length (filter (miller_rabin' [2; 3]) (Zseq 1 (Z.to_nat 20000))). (* 10.1 secs *)\n\nTime Eval vm_compute in length (filter  primeb                (Zseq 1 (Z.to_nat 40000))). (* 41.3 secs *)\nTime Eval vm_compute in length (filter (miller_rabin  [2; 3]) (Zseq 1 (Z.to_nat 40000))). (* 54.6 secs *)\nTime Eval vm_compute in length (filter (miller_rabin' [2; 3]) (Zseq 1 (Z.to_nat 40000))). (* 26.6 secs *)\n\nTime Eval vm_compute in length (filter  primeb                (Zseq 1 (Z.to_nat 80000))). (* 132 sec *)\nTime Eval vm_compute in length (filter (miller_rabin  [2; 3]) (Zseq 1 (Z.to_nat 80000))). (* 125 sec *)\nTime Eval vm_compute in length (filter (miller_rabin' [2; 3]) (Zseq 1 (Z.to_nat 80000))). (* 68 sec *)\n\nother simple ideas for improvement:\n- use positive instead of Z (maybe there is a lot of going back and forth)\n- replace \"x mod m\" with \"if x < m then x else x mod m\" (seem unlikely)\n- use 64 bits integers\n*)\n\n\n(** Checking that Miller-Rabin is sufficient below some bounds *)\n\nDefinition MR_at l n := if miller_rabin l n then primeb n else true.\nDefinition MR_range l a b := forallb (MR_at l) (Zseq a (Z.to_nat (b - a + 1))).\n\nLemma iff_intro {A} (P Q : A -> Prop) : (forall a, P a <-> Q a) -> (forall a, P a) <-> (forall a, Q a).\nProof.\n  firstorder.\nQed.\n\nLemma iff_intro_Prop (P Q P' Q' : Prop) : (P <-> Q) -> (P -> Q -> (P' <-> Q')) -> ((P -> P') <-> (Q -> Q')).\nProof.\n  firstorder.\nQed.\n\nLemma MR_range_spec l a b : MR_range l a b = true <-> (forall n : Z, a <= n <= b -> miller_rabin l n = primeb n).\nProof.\n  unfold MR_range.\n  rewrite forallb_forall.\n  apply iff_intro; intros x.\n  apply iff_intro_Prop. rewrite in_Zseq; lia.\n  intros _ bx.\n  unfold MR_at in *.\n  destruct (miller_rabin l x) eqn:e. split; auto.\n  destruct (primeb x) eqn:p; split; auto.\n  apply miller_rabin_sound in e.\n  now apply primeb_prime in p.\nQed.\n\nLemma MR_range_empty l a b : a > b -> MR_range l a b = true.\nProof.\n  intros ab.\n  unfold MR_range.\n  replace (Z.to_nat _) with O by lia.\n  easy.\nQed.\n\nLemma MR_range_spec_0 l b : MR_range l 0 b = true -> forall n : Z, n <= b -> miller_rabin l n = primeb n.\nProof.\n  intros h n nb.\n  pose proof proj1 (MR_range_spec _ _ _) h n as m.\n  destruct (n <? 2) eqn:n2.\n  - unfold miller_rabin in *. rewrite n2 in *.\n    destruct (primeb n) eqn:pn; auto.\n    apply Z.ltb_lt in n2. apply primeb_prime, prime_ge_2 in pn. lia.\n  - apply Z.ltb_ge in n2. apply m. lia.\nQed.\n\nLemma MR_range_spec_2 l b : MR_range l 2 b = true -> forall n : Z, n <= b -> miller_rabin l n = primeb n.\nProof.\n  intros h n nb.\n  pose proof proj1 (MR_range_spec _ _ _) h n as m.\n  destruct (n <? 2) eqn:n2.\n  - unfold miller_rabin in *. rewrite n2 in *.\n    destruct (primeb n) eqn:pn; auto.\n    apply Z.ltb_lt in n2. apply primeb_prime, prime_ge_2 in pn. lia.\n  - apply Z.ltb_ge in n2. tauto.\nQed.\n\n(** Below 2047, it is enough to check a=2 *)\n\nLemma miller_rabin_2 n : n <= 2046 -> miller_rabin [2] n = primeb n.\nProof.\n  apply MR_range_spec_2.\n  vm_compute. (* 0.3 seconds *)\n  reflexivity.\nQed.\n\nLemma first_miller_rabin_2_pseudo_prime :\n  miller_rabin [2]    2047 = true /\\\n  miller_rabin [2; 3] 2047 = false /\\\n  primeb              2047 = false.\nProof.\n  (*now native_compute.*)\n  now vm_compute.\nQed.\n\n(** Below 1373653, it is enough to check a=3, but we check for <= 10000 *)\n\nLemma miller_rabin_2_3 n : n <= 10000 -> miller_rabin [2; 3] n = primeb n.\nProof.\n  apply MR_range_spec_2.\n  (*Time native_compute.*) (* 1.6 secs *)\n  Time vm_compute.\n  reflexivity.\nTime Qed. (* 1.6 secs *)\n\nLemma first_miller_rabin_2_3_pseudo_prime :\n  miller_rabin [2; 3]    1373653 = true /\\\n  miller_rabin [2; 3; 5] 1373653 = false /\\\n  primeb                 1373653 = false.\nProof.\n  (*now native_compute.*)\n  now vm_compute.\nQed.\n", "meta": {"author": "coq-community", "repo": "coqtail-math", "sha": "be26e1a6a52f2e13e0779c68aba685ddfb4f0535", "save_path": "github-repos/coq/coq-community-coqtail-math", "path": "github-repos/coq/coq-community-coqtail-math/coqtail-math-be26e1a6a52f2e13e0779c68aba685ddfb4f0535/Arith/MillerRabin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.677274750108613}}
{"text": "From CoqAlgs Require Export Base.\n\nSet Implicit Arguments.\n\n(* Formulas. [not f] will be represented as [fImpl f fFalse] and\n   [f1 <-> f2] as [fAnd (fImpl f1 f2) (fImpl f2 f1)]. *)\nInductive formula : Type :=\n    | fFalse : formula\n    | fTrue : formula\n    | fVar : nat -> formula\n    | fAnd : formula -> formula -> formula\n    | fOr : formula -> formula -> formula\n    | fImpl : formula -> formula -> formula.\n\nFixpoint formulaDenote (env : Env Prop) (f : formula) : Prop :=\nmatch f with\n    | fFalse => False\n    | fTrue => True\n    | fVar i => holds i env\n    | fAnd f1 f2 => formulaDenote env f1 /\\ formulaDenote env f2\n    | fOr f1 f2 => formulaDenote env f1 \\/ formulaDenote env f2\n    | fImpl f1 f2 => formulaDenote env f1 -> formulaDenote env f2\nend.\n\nFunction simplifyFormula (f : formula) : formula :=\nmatch f with\n    | fFalse => fFalse\n    | fTrue => fTrue\n    | fVar P => fVar P\n    | fAnd f1 f2 =>\n        match simplifyFormula f1, simplifyFormula f2 with\n            | fOr f11 f12, f2' => fOr (fAnd f11 f2') (fAnd f12 f2')\n            | f1', fOr f21 f22 => fOr (fAnd f1' f21) (fAnd f1' f22)\n            | fFalse, _ => fFalse\n            | _, fFalse => fFalse\n            | fTrue, f2' => f2'\n            | f1', fTrue => f1'\n            | f1', f2' => fAnd f1' f2'\n        end\n    | fOr f1 f2 =>\n        match simplifyFormula f1, simplifyFormula f2 with\n            | fAnd f11 f12, f2' => fAnd (fOr f11 f2') (fOr f12 f2')\n            | f1', fAnd f21 f22 => fAnd (fOr f1' f21) (fOr f1' f22)\n            | fFalse, f2' => f2'\n            | f1', fFalse => f1'\n            | fTrue, _ => fTrue\n            | _, fTrue => fTrue\n            | f1', f2' => fOr f1' f2'\n        end\n    | fImpl f1 f2 =>\n        match simplifyFormula f1 with\n            | fFalse => fTrue\n            | fTrue => f2\n            | fAnd f11 f12 => fImpl f11 (fImpl f12 f2)\n            | fOr f11 f12 => fAnd (fImpl f11 f2) (fImpl f12 f2)\n            | f1' => fImpl f1' f2\n        end\nend.\n\nTheorem simplifyFormula_correct :\n  forall (f : formula) (env : Env Prop),\n    formulaDenote env (simplifyFormula f) <-> formulaDenote env f.\nProof.\n  intros. functional induction simplifyFormula f; cbn.\n  all:\n  repeat match goal with\n      | e : simplifyFormula ?f = _,\n        IH : formulaDenote _ (simplifyFormula ?f) <-> _ |- _ =>\n        rewrite <- IH, e; cbn\n  end; try (tauto; fail).\nQed.\n\nDefinition solveHypothesis (env : Env Prop) :\n  forall (proofs : Proofs) (hyp f : formula)\n    (cont : forall proofs : Proofs,\n      solution (allTrue env proofs -> formulaDenote env f)),\n        solution (allTrue env proofs -> formulaDenote env hyp ->\n          formulaDenote env f).\nProof.\n  refine (\n  fix solve\n    (proofs : Proofs) (hyp f : formula)\n      (cont : forall proofs : Proofs,\n        solution (allTrue env proofs -> formulaDenote env f)) :\n          solution (allTrue env proofs -> formulaDenote env hyp ->\n            formulaDenote env f) :=\n  match hyp with\n      | fFalse => Yes\n      | fTrue => Reduce (cont proofs)\n      | fVar i => Reduce (cont (i :: proofs))\n      | fAnd f1 f2 =>\n          Reduce (solve proofs f1 (fImpl f2 f)\n                        (fun proofs' => Reduce (cont proofs')))\n      | fOr f1 f2 =>\n          solve proofs f1 f cont &&&\n          solve proofs f2 f cont\n      | _ => No\n  end).\n  all: cbn in *; try tauto.\nDefined.\n\nDefinition solveGoal (env : Env Prop)\n  : forall (proofs : Proofs) (f : formula),\n      solution (allTrue env proofs -> formulaDenote env f).\nProof.\n  refine (\n  fix solve\n    (proofs : Proofs) (f : formula)\n      : solution (allTrue env proofs -> formulaDenote env f) :=\n  match f with\n      | fFalse => No\n      | fTrue => Yes\n      | fVar i =>\n          match in_dec Nat.eq_dec i proofs with\n              | left _ => Yes\n              | right _ => No\n          end\n      | fAnd f1 f2 => solve proofs f1 &&& solve proofs f2\n      | fOr f1 f2 => solve proofs f1 ||| solve proofs f2\n      | fImpl f1 f2 =>\n          solveHypothesis env proofs f1 f2\n            (fun proofs' => solve proofs' f2)\n  end).\n  all: cbn; try tauto.\n    intro. apply find_spec with proofs; assumption.\nDefined.\n\nDefinition solveFormula (env : Env Prop) (f : formula)\n  : solution (formulaDenote env f).\nProof.\n  refine (Reduce (solveGoal env [] f)). apply f0. cbn. trivial.\nDefined.\n\nTheorem solveFormula_correct :\n  forall (env : Env Prop) (f : formula),\n    (exists p : formulaDenote env f, solveFormula env f = Yes' p) ->\n      formulaDenote env f.\nProof.\n  intros. destruct H. assumption.\nQed.\n\nLtac allVarsFormula xs P :=\nmatch P with\n    | ~ ?P' => allVarsFormula xs P'\n    | ?P1 /\\ ?P2 =>\n        let xs' := allVarsFormula xs P2 in allVarsFormula xs' P1\n    | ?P1 \\/ ?P2 =>\n        let xs' := allVarsFormula xs P2 in allVarsFormula xs' P1\n    | ?P1 -> ?P2 =>\n        let xs' := allVarsFormula xs P2 in allVarsFormula xs' P1\n    | ?P1 <-> ?P2 =>\n        let xs' := allVarsFormula xs P2 in allVarsFormula xs' P1\n    | _ => addToList P xs\nend.\n\nLtac reifyFormula xs P :=\nmatch P with\n    | False => constr:(fFalse)\n    | True => constr:(fTrue)\n    | ~ ?P' =>\n        let e := reifyFormula xs P' in constr:(fImpl e fFalse)\n    | ?P1 /\\ ?P2 =>\n        let e1 := reifyFormula xs P1 in\n        let e2 := reifyFormula xs P2 in constr:(fAnd e1 e2)\n    | ?P1 \\/ ?P2 =>\n        let e1 := reifyFormula xs P1 in\n        let e2 := reifyFormula xs P2 in constr:(fOr e1 e2)\n    | ?P1 -> ?P2 =>\n        let e1 := reifyFormula xs P1 in\n        let e2 := reifyFormula xs P2 in constr:(fImpl e1 e2)\n    | ?P1 <-> ?P2 =>\n        let e1 := reifyFormula xs P1 in\n        let e2 := reifyFormula xs P2 in\n          constr:(fAnd (fImpl e1 e2) (fImpl e2 e1))\n    | _ =>\n        let i := lookup P xs in constr:(fVar i)\nend.\n\nLtac reflectFormula :=\nmatch goal with\n    |- ?P =>\n        let xs := allVarsFormula constr:(@nil Prop) P in\n        let f := reifyFormula xs P in\n          change (formulaDenote xs f);\n          rewrite <- simplifyFormula_correct; cbn\nend.\n\nLtac solveGoal' :=\nmatch goal with\n    |- ?P =>\n        let xs := allVarsFormula constr:(@nil Prop) P in\n        let f := reifyFormula xs P in change (formulaDenote xs f);\n          rewrite <- simplifyFormula_correct; cbn;\n          try apply (unwrap (solveFormula xs (simplifyFormula f)))\nend.\n\nLtac solveGoal := solveGoal'; fail.", "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/Reflection/Formula.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6772747433712798}}
{"text": "Require Import List.\nImport ListNotations.\n\n(** Relations **)\n\n(* A relation over a type `A` is a function `A -> A -> Prop` *)\nDefinition relation (A: Type) : Type := A -> A -> Prop.\n\nDefinition equivalent_relations {A: Type} (r1 r2: relation A) :=\n  forall x y, r1 x y <-> r2 x y.\n\nNotation \"r1 == r2\" := (equivalent_relations r1 r2) (at level 30).\n\nDefinition compose {A: Type} (r1 r2: relation A): relation A :=\n  fun x y => (exists z, r1 x z /\\ r2 z y).\n\nNotation \"r1 ** r2\" := (compose r1 r2) (at level 20).\n\n(* destruct existentials in context *)\nLtac destruct_exists :=\n  match goal with\n  | H: exists x, _ |- _ => let freshX := fresh x in destruct H as [ freshX ]\n  end.\n\nLemma compose_assoc:\n  forall A (r1 r2 r3: relation A),\n    r1 ** (r2 ** r3) == (r1 ** r2) ** r3.\nProof.\n  intros. \n  unfold compose. unfold equivalent_relations. split.\n    + intros. destruct H. destruct H. destruct H0. destruct H0. exists x1. split. \n      - exists x0. split.\n        * apply H.\n        * apply H0.\n      - apply H1.\n    + intros. destruct H. destruct H. destruct H. destruct H. exists x1. split.\n      - apply H.\n      - exists x0. split.\n        * apply H1.\n        * apply H0.\nQed.\n\nFixpoint rel_pow {A: Type} (r: relation A) (n: nat): relation A :=\n  match n with\n  | 0 => fun a1 a2 => a1 = a2\n  | S n => compose r (rel_pow r n)\n  end.\n\nNotation \"r ^^ n\" := (rel_pow r n) (at level 15).\n\nFixpoint is_path {A: Type} (r: relation A) (x: A) (p: list A) (y: A): Prop :=\n  match p with\n  | [] => x = y\n  | z :: zs => r x z /\\ is_path r z zs y\n  end.\n\nLemma path_to_power: forall A (r: relation A) (p: list A) (y x: A),\n    is_path r x p y -> (r ^^ (length p)) x y.\nProof.\n   induction p. \n    + intros. simpl. simpl in H. apply H.\n    + simpl. intros. unfold compose. destruct H.  exists a.  split.\n      - apply H.\n      - pose proof IHp y a. apply H1. apply H0. \nQed.\n\nLemma is_path_cons:\n  forall A (r: relation A) (x y z: A) (p: list A),\n    r x y ->\n    is_path r y p z ->\n    is_path r x (y :: p) z.\nProof.\n  intros. simpl. split.\n    + apply H.\n    + apply H0.\nQed.\n\nLemma power_to_path:\n  forall A (r: relation A) (n: nat) (x y: A),\n    (r ^^ n) x y ->\n    exists p: list A, is_path r x p y /\\ length p = n.\nProof.\n  induction n. \n    + intros. simpl in H. exists []. simpl. split. \n      - apply H.\n      - trivial. \n    + intros. simpl. unfold compose. intuition. destruct H. \n      destruct H. pose proof is_path_cons A r. pose proof IHn x0 y. destruct H2.\n      - apply H0.\n      - inversion H2. exists (x0::x1). simpl. split.\n        * simpl. split.\n          ++ apply H.\n          ++ apply H3.\n        * rewrite H4. trivial.\nQed.\n\n\nLemma path_compose:\n  forall (A: Type) (r: relation A) (p1 p2: list A) (x y z: A),\n    is_path r x p1 y ->\n    is_path r y p2 z ->\n    is_path r x (p1 ++ p2) z.\nProof.\n  induction p1. induction p2.\n  - simpl. intros. simpl in H. rewrite H. unfold is_path in H0. rewrite H0. reflexivity.\n  - simpl. intros. simpl in H. simpl in H0. rewrite H. apply H0.\n  - simpl. intros. simpl in H. destruct H. split.\n    + apply H.\n    + pose proof IHp1 p2 a y z. apply H2.\n      * apply H1.\n      * apply H0.\nQed.\n\nLemma power_compose:\n  forall A (r : relation A) (n1 n2: nat),\n    (r ^^ n1) ** (r ^^ n2) == r ^^ (n1 + n2).\nProof.\n  induction n1.\n    + intros. simpl. unfold compose. split.\n      * intros. inversion H. destruct H0. rewrite <- H0 in H1. apply H1.\n      * intros. exists x. split.\n        - trivial.\n        - apply H.\n    + intros. simpl. unfold equivalent_relations. intros. \n        \n        pose proof compose_assoc A r (r^^n1) (r^^n2) as useless1. \n        unfold equivalent_relations in useless1.\n        pose proof IHn1 n2 as useless2. \n        unfold equivalent_relations in useless2. \n\n        pose proof useless1 x y as H1. destruct H1 as (H11, H12).\n        split.\n        - intros. inversion H. unfold compose in H0; destruct H0. inversion H0. unfold compose. exists x1. split.\n          * destruct H2. apply H2.\n          * pose proof useless2 x1 y as H3; destruct H3 as (H31, H32). apply H31. unfold compose. exists x0. split.\n            ** destruct H2. apply H3.\n            ** apply H1.\n        - intros. apply H11. unfold compose. inversion H; destruct H0. exists x0. split.\n          * apply H0.\n          * pose proof useless2 x0 y. destruct H2. apply H3 in H2. \n            ** unfold compose in H2. inversion H2. exists x1. apply H4.\n            **  apply H3. apply H1.\nQed.\n\n(* `star r` is the reflexive and transitive closure of the relation `R` *)\nDefinition star { A } (r : relation A): A -> A -> Prop :=\n  fun x y => (exists n, (r ^^ n) x y).\n\n(* The reflexive and transitive closure of a relation is reflexive *)\nLemma star_refl:\n  forall A (r: relation A) x,\n    star r x x.\nProof.\n  intros. unfold star. exists 0. simpl. trivial.\nQed.\n\n(* The reflexive and transitive closure of a relation is transitive *)\nLemma star_trans:\n  forall A (r : relation A) x y z,\n    star r x y ->\n    star r y z ->\n    star r x z.\nProof.\n  unfold star. intros. inversion H. inversion H0. exists (x0+x1). pose proof power_compose.\n  pose proof H3 A r x0 x1. unfold equivalent_relations in H4. pose proof H4 x z. destruct H5.\n  apply H5. unfold compose. exists y. split.\n    * apply H1.\n    * apply H2.\nQed.\n\n(* The transitive closure of a relation \"contains\" the relation *)\nLemma star_step:\n  forall A (r: relation A) x y,\n    r x y ->\n    star r x y.\nProof.\n  intros. unfold star. exists 1. simpl. unfold compose. exists y. split.\n    + apply H.\n    + trivial.\nQed.\n\n\nLemma star_1n:\n  forall A (r: relation A) x y z,\n    r x y ->\n    star r y z ->\n    star r x z.\nProof.\n  intros.\n  inversion H0.\n  unfold star. exists (S x0). simpl. unfold compose. exists y. split.\n    + apply H.\n    + apply H1. \nQed.\n\n\n(** Transition Systems and Reachability **)\n\n(* A transition system with states `Q` and alphabet `A` is a pair with:                *)\n(* - An `initial` function of type `Q -> Prop` that says which states are initial      *)\n(* - A function `r` of type `Q -> A -> Q -> Prop` such that `r q1 a q2` holds when the *)\n(*   transition system has a transition from state `q1` to `q2` labelled by `a`        *)\nRecord Transition_System (Q A : Type) := new_Transition_System {\n  initial : Q -> Prop;\n  r : Q -> A -> Q -> Prop\n}.\n\nArguments initial { Q A }.\nArguments r { Q A }.\nArguments new_Transition_System { Q A }.\n\n\n(* Example *)\nDefinition ex_Q := nat.\nInductive ex_A := inc (n : nat) | dec (n : nat).\n\nDefinition ex_Counter_1 := {|\n  initial := fun q => q = 0;\n  r := fun q1 a q2 => match a with\n               | inc 1 => q2 = q1 + 1\n               | dec 1 => q2 = q1 - 1\n               | _ => False\n               end\n  |}.\n\nDefinition ex_Counter_n := {|\n  initial := fun q => q = 0;\n  r := fun q1 a q2 => match a with\n               | inc n => q2 = q1 + n\n               | dec n => q2 = q1 - n\n               end\n  |}.\n\nNotation \"ts |- q1 ~ a '~>' q2\" := (r ts q1 a q2) (at level 20).\nNotation \"ts |- q1 '~>' q2\" := (exists a, ts |- q1 ~a~> q2) (at level 20).\nNotation \"ts |- q1 '~>*' q2\" := (star (fun p q => ts |- p ~> q) q1 q2) (at level 20).\nNotation \"ts |- q1 '~>^' n q2\" := (((fun p q => ts |- p ~> q) ^^ n) q1 q2) (at level 20, n at level 1).\n\nDefinition reachable { Q A } (ts : Transition_System Q A) (q: Q) : Prop :=\n  exists q_i, initial ts q_i  /\\  ts |- q_i ~>* q.\n\n\n(** Traces of Transition Systems **)\n\n(* A trace an a starting state `start` and sequences of states and labels *)\nRecord Trace (Q A : Type) := new_Trace {\n  start: Q;\n  states : list Q;\n  labels : list A\n}.\n\nArguments start { Q A }.\nArguments states { Q A }.\nArguments labels { Q A }.\nArguments new_Trace { Q A }.\n\nDefinition in_trace { Q A } q (tr : Trace Q A) : Prop :=\n  q = start tr \\/ In q (states tr).\n\n(* `is_trace_aux ts q0 xs` holds when there are transition in `ts`   *)\n(* starting from (not necessarily initial) state `q0`, going through *)\n(* the states in `qs` and with labels in `xs`                        *)\nFixpoint is_trace_aux { Q A } (ts : Transition_System Q A)\n  (q0 : Q) (qs : list Q) (xs : list A) : Prop :=\n  match qs, xs with\n  | nil, nil => True\n  | q :: qs', x :: xs' => r ts q0 x q /\\ is_trace_aux ts q qs' xs'\n  | _, _ => False\n  end.\n\n(* A `trace` of `ts` starts with an initial state and then has valid transitions *)\nDefinition is_trace { Q A } (ts: Transition_System Q A) (tr: Trace Q A) : Prop :=\n  is_trace_aux ts (start tr) (states tr) (labels tr) /\\\n  initial ts (start tr).\n\nLemma is_trace_aux_nil:\n  forall Q A (ts : Transition_System Q A) q, is_trace_aux ts q nil nil.\nProof.\n  intros.\n  unfold is_trace_aux. \n  trivial.\nQed.\n\n(* A trace can be extended from the front with another transition *)\nLemma is_trace_aux_cons:\n  forall A Q (ts : Transition_System Q A) q1 q2 qs x xs,\n    ts |- q1 ~x~> q2 ->\n    is_trace_aux ts q2 qs xs ->\n    is_trace_aux ts q1 (q2 :: qs) (x :: xs).\nProof.\n  induction qs.\n    + intros. unfold is_trace_aux. split.\n      - apply H.\n      - trivial.\n    + intros. simpl. split. \n      * apply H.\n      * trivial.\nQed.\n\nLemma super_lemma_1 : \n  forall A Q (ts : Transition_System Q A) q   (states_l: list Q) (labels_l: list A) (start_s: Q) ,\n    is_trace_aux ts start_s states_l labels_l ->\n    In q states_l ->\n    ts |- start_s ~>* q.\nProof.\n   induction states_l.\n    + intros. contradiction.\n    + intros. destruct labels_l.\n      - simpl in H. contradiction.\n      - inversion H0.\n        * subst. simpl in H. destruct H. unfold star. exists 1. simpl. unfold compose. exists q. split.\n          ++ exists a0. apply H.\n          ++ reflexivity.\n        * unshelve epose proof IHstates_l labels_l a _ H1. \n          ++ inversion H. apply H3.\n          ++ simpl in H. destruct H. eauto using star_1n .\nQed.\n\n\n(** Equivalence between reachability and traces **)\n\n(* All the states `q` that appear in the states of a trace are reachable *)\nLemma in_trace_reachable:\n  forall A Q (ts : Transition_System Q A) (tr : Trace Q A) q,\n    is_trace ts tr ->\n    in_trace q tr ->\n    reachable ts q.\nProof.\n  intros.\n  unfold reachable.\n  exists (start tr). inversion H. inversion H0; subst.\n    + eauto using star_refl.\n    + eauto using super_lemma_1.\nQed.\n\nLemma super_lemma_2:\n  forall A Q (ts : Transition_System Q A) q (start_s: Q),\n    ts |- start_s ~>* q ->\n      exists states_l labels_l,\n        is_trace_aux ts start_s states_l labels_l /\\ (In q states_l \\/ start_s = q).\nProof.\n  intros. destruct H. generalize dependent start_s. generalize dependent q. induction x.\n  + exists (@nil Q). exists (@nil A). inversion H. unfold rel_pow. destruct H. split.\n                                                                               - unfold is_trace_aux. trivial.\n                                                                               - simpl. right. trivial.\n  + intros.\n    inversion H.\n    inversion H0.\n    pose proof IHx q x0.\n    apply H3 in H2.\n    destruct H2.\n    destruct H2.\n    destruct H2.\n    destruct H0.\n    destruct H0.\n    exists (cons x0 x1).\n    exists (cons x3 x2).\n    destruct H4.\n    - split.\n      -- simpl. split.\n                --- apply H0.\n                ---  apply H2.\n      -- left. unfold In. right. apply H4.\n   - simpl. split. split.\n            -- apply H0.\n            -- apply H2.\n            -- left. left. apply H4.\nQed.\n\n(* Conversely, if a state `q` is reachable, there exists a trace containing it *)\nLemma reachable_in_trace:\n  forall A Q (ts : Transition_System Q A) q,\n    reachable ts q ->\n    exists tr,\n      is_trace ts tr /\\\n      in_trace q tr.\nProof.\n  intros.\n  inversion H. destruct H0. inversion H1.\n  unfold is_trace. unfold in_trace. simpl. pose proof super_lemma_2 A Q ts q x. \n  unshelve epose proof H3 _.\n    * trivial.\n    * inversion H4. inversion H5. \n      exists {|\n        start := x;\n        states := x1;\n        labels := x2\n      |}. simpl. split.\n      - inversion H6; eauto.\n      - inversion H6. inversion H8.\n                      right. apply H9.\n                      left. subst. reflexivity.\nQed.\n\n\n(** Simulation Relations **)\n\nDefinition simulates { QC QA A }\n  (tsc : Transition_System QC A) (tsa : Transition_System QA A) (R : QC -> QA -> Prop) :=\n\n  (forall qc, initial tsc qc -> exists qa, R qc qa /\\ initial tsa qa) /\\\n  (forall qc1 a qc2 qa1, tsc |- qc1 ~a~> qc2 -> R qc1 qa1 -> exists qa2, R qc2 qa2 /\\ tsa |- qa1 ~a~> qa2).\n\n(* The counter with `inc 1` and `dec 1` simulates the counter with `inc n` and `dec n`. *)\n(* The relation used to show the simulation is the diagonal or identity relation.       *)\nLemma simulates_counter_1_n: simulates ex_Counter_1 ex_Counter_n (fun qc qa => True).\nProof.\n  unfold simulates. split. \n    * intros. exists qc. split.\n      - trivial.\n      - trivial.\n    * intros. unfold ex_Counter_n. simpl. unfold ex_Counter_1 in H; simpl in H. destruct a.\n      destruct n.\n      + contradiction.\n      + destruct n. simpl.\n        - exists (qa1 + 1). split.\n          -- trivial.\n          -- trivial.\n        - contradiction.\n      + destruct n.\n        - contradiction.\n        - exists (qa1 - S n). split.\n          -- trivial.\n          -- reflexivity.\nQed.\n\n(* If a transition system `tsc` simulates a transition system `tsa`, then for every trace of *)\n(* `tsc`, there exists a trace of `tsa` with the same labels.                                *)\nLemma simulates_inclusion_observable:\n  forall QC QA A (tsc : Transition_System QC A) (tsa : Transition_System QA A) (R : QC -> QA -> Prop) trc,\n    simulates tsc tsa R ->\n    is_trace tsc trc ->\n    exists tra,\n      is_trace tsa tra /\\\n      labels trc = labels tra.\nProof.\n  intros. inversion H. inversion H0.\nAdmitted.\n", "meta": {"author": "danielementary", "repo": "FormalVerification-Labs", "sha": "993e30919388dda478d80573a437d2d8a87cb4dd", "save_path": "github-repos/coq/danielementary-FormalVerification-Labs", "path": "github-repos/coq/danielementary-FormalVerification-Labs/FormalVerification-Labs-993e30919388dda478d80573a437d2d8a87cb4dd/Lab4/Relations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695836, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.677274740898227}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Import NZAxioms NZBase.\n\nModule Type NZAddProp (Import NZ : NZAxiomsSig')(Import NZBase : NZBaseProp NZ).\n\nHint Rewrite\npred_succ add_0_l add_succ_l mul_0_l mul_succ_l sub_0_r sub_succ_r : nz.\nHint Rewrite one_succ two_succ : nz'.\nLtac nzsimpl := autorewrite with nz.\nLtac nzsimpl' := autorewrite with nz nz'.\n\nTheorem add_0_r : forall n, n + 0 == n.\nProof. hammer_hook \"NZAdd\" \"NZAdd.NZAddProp.add_0_r\".  \nnzinduct n. now nzsimpl.\nintro. nzsimpl. now rewrite succ_inj_wd.\nQed.\n\nTheorem add_succ_r : forall n m, n + S m == S (n + m).\nProof. hammer_hook \"NZAdd\" \"NZAdd.NZAddProp.add_succ_r\".  \nintros n m; nzinduct n. now nzsimpl.\nintro. nzsimpl. now rewrite succ_inj_wd.\nQed.\n\nTheorem add_succ_comm : forall n m, S n + m == n + S m.\nProof. hammer_hook \"NZAdd\" \"NZAdd.NZAddProp.add_succ_comm\".  \nintros n m. now rewrite add_succ_r, add_succ_l.\nQed.\n\nHint Rewrite add_0_r add_succ_r : nz.\n\nTheorem add_comm : forall n m, n + m == m + n.\nProof. hammer_hook \"NZAdd\" \"NZAdd.NZAddProp.add_comm\".  \nintros n m; nzinduct n. now nzsimpl.\nintro. nzsimpl. now rewrite succ_inj_wd.\nQed.\n\nTheorem add_1_l : forall n, 1 + n == S n.\nProof. hammer_hook \"NZAdd\" \"NZAdd.NZAddProp.add_1_l\".  \nintro n; now nzsimpl'.\nQed.\n\nTheorem add_1_r : forall n, n + 1 == S n.\nProof. hammer_hook \"NZAdd\" \"NZAdd.NZAddProp.add_1_r\".  \nintro n; now nzsimpl'.\nQed.\n\nHint Rewrite add_1_l add_1_r : nz.\n\nTheorem add_assoc : forall n m p, n + (m + p) == (n + m) + p.\nProof. hammer_hook \"NZAdd\" \"NZAdd.NZAddProp.add_assoc\".  \nintros n m p; nzinduct n. now nzsimpl.\nintro. nzsimpl. now rewrite succ_inj_wd.\nQed.\n\nTheorem add_cancel_l : forall n m p, p + n == p + m <-> n == m.\nProof. hammer_hook \"NZAdd\" \"NZAdd.NZAddProp.add_cancel_l\".  \nintros n m p; nzinduct p. now nzsimpl.\nintro p. nzsimpl. now rewrite succ_inj_wd.\nQed.\n\nTheorem add_cancel_r : forall n m p, n + p == m + p <-> n == m.\nProof. hammer_hook \"NZAdd\" \"NZAdd.NZAddProp.add_cancel_r\".  \nintros n m p. rewrite (add_comm n p), (add_comm m p). apply add_cancel_l.\nQed.\n\nTheorem add_shuffle0 : forall n m p, n+m+p == n+p+m.\nProof. hammer_hook \"NZAdd\" \"NZAdd.NZAddProp.add_shuffle0\".  \nintros n m p. rewrite <- 2 add_assoc, add_cancel_l. apply add_comm.\nQed.\n\nTheorem add_shuffle1 : forall n m p q, (n + m) + (p + q) == (n + p) + (m + q).\nProof. hammer_hook \"NZAdd\" \"NZAdd.NZAddProp.add_shuffle1\".  \nintros n m p q. rewrite 2 add_assoc, add_cancel_r. apply add_shuffle0.\nQed.\n\nTheorem add_shuffle2 : forall n m p q, (n + m) + (p + q) == (n + q) + (m + p).\nProof. hammer_hook \"NZAdd\" \"NZAdd.NZAddProp.add_shuffle2\".  \nintros n m p q. rewrite (add_comm p). apply add_shuffle1.\nQed.\n\nTheorem add_shuffle3 : forall n m p, n + (m + p) == m + (n + p).\nProof. hammer_hook \"NZAdd\" \"NZAdd.NZAddProp.add_shuffle3\".  \nintros n m p. now rewrite add_comm, <- add_assoc, (add_comm p).\nQed.\n\nTheorem sub_1_r : forall n, n - 1 == P n.\nProof. hammer_hook \"NZAdd\" \"NZAdd.NZAddProp.sub_1_r\".  \nintro n; now nzsimpl'.\nQed.\n\nHint Rewrite sub_1_r : nz.\n\nEnd NZAddProp.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Numbers/NatInt/NZAdd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.793105953629227, "lm_q1q2_score": 0.67724328824592}}
{"text": "(** Adapted from \"Elements of Set Theory\" Chapter 5 **)\n(** Coq coding by choukh, July 2020 **)\n\nRequire Export ZFC.Elements.EST5_5.\n\n(*** EST第五章6：实数绝对值，非负实数乘法，正实数乘法逆元 ***)\n\n(** 实数绝对值 **)\nDefinition RealAbs : set → set := λ x, x ∪ -x.\nNotation \"| r |\" := (RealAbs r) : Real_scope.\n\nLemma realAbs_nonNeg_id : ∀ x, realNonNeg x → |x| = x.\nProof with neauto.\n  intros x [Hpos|H0].\n  - assert (Hx: x ∈ ℝ) by (apply binRelE2 in Hpos as [_ []]; auto).\n    apply realPos_rat0 in Hpos as H0...\n    ext q Hq; revgoals.\n    apply BUnionI1... apply BUnionE in Hq as []...\n    apply SepE in H as [Hq [s [Hs [Hlt H]]]].\n    eapply realE2_1 in H; revgoals... apply ratAddInv_ran...\n    apply ratPos_neg in H. rewrite ratAddInv_double in H...\n    assert (Hnq: ratNeg q) by (eapply ratLt_trans; eauto).\n    eapply realE2; revgoals...\n  - subst. ext q Hq.\n    + apply BUnionE in Hq as []... rewrite realAddInv_0 in H...\n    + apply BUnionI1...\nQed.\n\nLemma realAbs_unsigned_nonNeg : ∀x ∈ ℝ, |x| = x → realNonNeg x.\nProof with neauto.\n  intros x Hx Heq. apply realLe... intros q Hq.\n  apply SepE in Hq as [Hq Hlt]. rewrite <- Heq.\n  destruct (classic (Rat 0 ∈ x)).\n  - apply BUnionI1. eapply realE2; revgoals...\n  - apply BUnionI2. apply SepI... exists (Rat 0).\n    split... split... rewrite ratAddInv_0...\nQed.\n\nLemma realAbs_nonPos_flip : ∀ x, realNonPos x → |x| = -x.\nProof with neauto.\n  intros x [Hneg|Heq].\n  - assert (Hx: x ∈ ℝ) by (apply binRelE2 in Hneg as []; auto).\n    apply realNeg_pos in Hneg as Hpos.\n    apply realPos_rat0 in Hpos as H0; [|apply realAddInv_ran; auto].\n    ext q Hq; revgoals.\n    apply BUnionI2... apply BUnionE in Hq as [Hqx|]...\n    assert (Hq: q ∈ ℚ) by (apply (real_sub_rat x Hx); auto).\n    apply SepI... apply SepE in H0 as [_ [s [Hs [Hlt Hout]]]].\n    exists s. split... split... eapply ratLt_trans...\n    eapply realE2_1... intros H. apply realPos_rat0 in H...\n    eapply realLt_irrefl. eapply realLt_trans...\n  - subst. ext q Hq.\n    + apply BUnionE in Hq as []... rewrite realAddInv_0...\n    + apply BUnionI2...\nQed.\n\nLemma realAbs_flip_nonPos : ∀x ∈ ℝ, |x| = -x → realNonPos x.\nProof with neauto.\n  intros x Hx Heq. apply realLe_addInv'...\n  rewrite realAddInv_0. apply realLe... apply realAddInv_ran...\n  intros q Hq. apply SepE in Hq as [Hq Hlt]. rewrite <- Heq.\n  destruct (classic (Rat 0 ∈ x)).\n  - apply BUnionI1. eapply realE2; revgoals...\n  - apply BUnionI2. apply SepI... exists (Rat 0).\n    split... split... rewrite ratAddInv_0...\nQed.\n\nLemma realAbs_eq_0 : ∀x ∈ ℝ, |x| = Real 0 → x = Real 0.\nProof with nauto.\n  intros x Hx H0. destruct (classic (realNonNeg x))...\n  rewrite (realAbs_nonNeg_id _ H) in H0...\n  apply realNeg_not_nonNeg in H...\n  apply realNeg_nonPos in H...\n  rewrite (realAbs_nonPos_flip _ H) in H0.\n  assert (--x = -Real 0) by congruence.\n  rewrite realAddInv_double, realAddInv_0 in H1...\nQed.\n\nLemma realAbs_unsigned : ∀x ∈ ℝ, | -x | = |x|.\nProof with auto.\n  intros x Hx.\n  assert (Hx': -x ∈ ℝ) by (apply realAddInv_ran; auto).\n  destruct (classic (realNonNeg (-x))).\n  - rewrite (realAbs_nonNeg_id _ H).\n    apply realNonNeg_nonPos in H...\n    rewrite realAddInv_double in H...\n    rewrite (realAbs_nonPos_flip _ H)...\n  - apply realNeg_not_nonNeg in H...\n    apply realNeg_nonPos in H...\n    rewrite (realAbs_nonPos_flip _ H), realAddInv_double...\n    apply realNonPos_nonNeg in H... rewrite realAddInv_double in H...\n    rewrite (realAbs_nonNeg_id _ H)...\nQed.\n\nLemma realAbs_ran : ∀x ∈ ℝ, |x| ∈ ℝ.\nProof with auto.\n  intros x Hx. destruct (classic (realNonNeg x)).\n  - apply realAbs_nonNeg_id in H. rewrite H...\n  - apply realNeg_not_nonNeg in H...\n    apply realNeg_nonPos in H...\n    apply realAbs_nonPos_flip in H. rewrite H...\n    apply realAddInv_ran...\nQed.\n\nTheorem realAbs_nonNeg : ∀x ∈ ℝ, realNonNeg (|x|).\nProof with neauto.\n  intros x Hx. destruct (classic (realNonNeg x)).\n  - rewrite (realAbs_nonNeg_id _ H)...\n  - apply realNeg_not_nonNeg in H...\n    apply realNeg_nonPos in H...\n    apply realAbs_nonPos_flip in H as Heq. rewrite Heq.\n    apply realNonPos_nonNeg...\nQed.\n\nLemma realPos_ratPos : ∀x ∈ ℝ,\n  realPos x → ∃q ∈ ℚ, q ∈ x ∧ ratPos q.\nProof with auto.\n  intros x Hx Hpx. apply realE3... apply realPos_rat0...\nQed.\n\nLemma realPos_ratNonNeg : ∀x ∈ ℝ,\n  realPos x → ∃q ∈ x, ratNonNeg q.\nProof with auto.\n  intros x Hx Hpx. exists (Rat 0). split...\n  apply realPos_rat0... right...\nQed.\n\nLemma realNonPos_ratNeg : ∀x ∈ ℝ,\n  realNonPos x → ∃q ∈ x, ratNeg q.\nProof with nauto.\n  intros x Hx Hnpx. apply realLe in Hnpx...\n  apply realE0 in Hx as [r [Hrq Hrx]].\n  exists r. split... apply Hnpx in Hrx.\n  apply SepE in Hrx as [_ Hnr]...\nQed.\n\nLemma realNonPos_ratNonPos : ∀x ∈ ℝ,\n  realNonPos x → ∃q ∈ x, ratNonPos q.\nProof with nauto.\n  intros x Hx Hnpx.\n  apply realNonPos_ratNeg in Hnpx as [q [Hqx Hnq]]...\n  exists q. split... left...\nQed.\n\nLemma realE1'_ratPos : ∀x ∈ ℝ, realNonNeg x →\n  ∃r ∈ ℚ, (∀q ∈ x, q <𝐪 r) ∧ ratPos r.\nProof with neauto.\n  intros x Hx Hnnx. assert (Hx' := Hx).\n  apply realE1 in Hx' as [r [Hrq Hrx]].\n  exists (r + Rat 1)%q. split... apply ratAdd_ran... split.\n  intros q Hq. apply (real_sub_rat _ Hx) in Hq as Hqq.\n  assert (Hlt: r <𝐪 (r + Rat 1)%q). {\n    rewrite <- (ratAdd_0_r r) at 1...\n    apply ratAdd_preserve_lt'... apply ratPos_sn.\n  }\n  eapply ratLt_trans; revgoals. apply Hlt. eapply realE2_1...\n  cut (ratNonNeg r). intros [Hpr|H0].\n  unfold ratPos. rewrite <- (ratAdd_0_r (Rat 0))...\n  apply ratAdd_preserve_lt_trans... apply ratPos_sn.\n  subst. rewrite ratAdd_0_l... destruct Hnnx. \n  - left. apply realPos_rat0 in H... eapply realE2_1...\n  - subst. destruct (classic (r = Rat 0))... right...\n    apply ratLt_connected in H as []...\n    exfalso. apply Hrx. apply SepI... left...\nQed.\n\n(** 非负实数乘法 **)\nDefinition RealNonNegMul : set → set → set := λ x y,\n  let P := {p ∊ x × y | ratNonNeg (π1 p) ∧ ratNonNeg (π2 p)} in\n  Real 0 ∪ {(π1 p ⋅ π2 p)%q | p ∊ P}.\nNotation \"x ⋅₊ y\" := (RealNonNegMul x y) (at level 45) : Real_scope.\n\nLemma realNonNegMulI0 : ∀ x y ∈ ℝ, ∀ s, ratNeg s → s ∈ x ⋅₊ y.\nProof with auto.\n  intros x Hx y Hy s Hps. apply BUnionI1.\n  apply SepI... apply ratNeg_rat...\nQed.\n\nLemma realNonNegMulI1 : ∀ x y ∈ ℝ, ∀q ∈ x, ∀r ∈ y,\n  ratNonNeg q → ratNonNeg r → (q ⋅ r)%q ∈ x ⋅₊ y.\nProof with auto.\n  intros x Hx y Hy q Hqx r Hry Hnnq Hnnr.\n  apply BUnionI2. apply ReplAx.\n  exists <q, r>. split; zfc_simple. apply SepI.\n  apply CPrdI... zfc_simple. split...\nQed.\n\nLemma realNonNegMulE : ∀ x y ∈ ℝ, ∀s ∈ x ⋅₊ y, s ∈ Real 0 ∨\n  ∃q ∈ ℚ, ∃r ∈ ℚ, (q ∈ x ∧ r ∈ y) ∧\n    (ratNonNeg q ∧ ratNonNeg r) ∧ s = (q ⋅ r)%q.\nProof with auto.\n  intros x Hx y Hy s Hs.\n  apply BUnionE in Hs as []... right.\n  apply ReplAx in H as [p [Hp Hs]].\n  apply SepE in Hp as [Hp [H1 H2]].\n  apply CPrdE1 in Hp as [q [Hq [r [Hr Hp]]]].\n  subst. zfc_simple.\n  exists q. split... apply (real_sub_rat _ Hx)...\n  exists r. split... apply (real_sub_rat _ Hy)...\nQed.\n\nLemma realNonNegMul_sub_rat : ∀ x y ∈ ℝ, x ⋅₊ y ∈ 𝒫 ℚ.\nProof with auto.\n  intros x Hx y Hy. apply PowerAx. intros s Hs.\n  apply realNonNegMulE in Hs as []... apply SepE1 in H...\n  destruct H as [q [Hq [r [Hr [_ [_ Heq]]]]]].\n  subst. apply ratMul_ran...\nQed.\n\nClose Scope Real_scope.\nOpen Scope Rat_scope.\n\nLemma realNonNegMul_ran : ∀ x y ∈ ℝ,\n  realNonNeg x → realNonNeg y → (x ⋅₊ y)%r ∈ ℝ.\nProof with neauto.\n  intros x Hxr y Hyr Hnnx Hnny.\n  apply SepI. apply realNonNegMul_sub_rat... repeat split.\n  - apply EmptyNI. destruct (classic (x = Real 0 ∨ y = Real 0)).\n    + destruct H.\n      * assert (Hnpx: realNonPos x) by (right; auto).\n        apply realNonPos_ratNeg in Hnpx as [q [Hqy Hnq]]...\n        exists q. apply realNonNegMulI0...\n      * assert (Hnpy: realNonPos y) by (right; auto).\n        apply realNonPos_ratNeg in Hnpy as [r [Hrx Hnr]]...\n        exists r. apply realNonNegMulI0...\n    + apply not_or_and in H as [Hx0 Hy0].\n      destruct Hnnx; destruct Hnny; [clear Hx0 Hy0|exfalso; auto..].\n      apply realPos_ratNonNeg in H as [q [Hq Hnnq]]...\n      apply realPos_ratNonNeg in H0 as [r [Hr Hnnr]]...\n      exists (q ⋅ r). apply realNonNegMulI1...  \n  - assert (Hx' := Hxr). assert (Hy' := Hyr).\n    apply realE1'_ratPos in Hx' as [q [Hq [H1 Hpq]]]...\n    apply realE1'_ratPos in Hy' as [r [Hr [H2 Hpr]]]...\n    assert (Hqr : q ⋅ r ∈ ℚ) by (apply ratMul_ran; auto).\n    apply ExtNI. exists (q ⋅ r). split... intros H.\n    apply (ratLt_irrefl (q ⋅ r))...\n    cut (∀p ∈ (x ⋅₊ y)%r, p <𝐪 q ⋅ r). intros Hlt. apply Hlt...\n    intros p Hp. apply realNonNegMulE in Hp as []...\n    + apply SepE in H0 as [_ H0].\n      eapply ratLt_trans. apply H0.\n      apply ratMul_pos_prd...\n    + destruct H0 as [s [Hsq [t [Htq [[Hs Ht] [[Hnns Hnnt] Heq]]]]]].\n      subst. apply H1 in Hs. apply H2 in Ht.\n      destruct Hnnt as [Hpt|H0].\n      eapply ratMul_preserve_lt_trans...\n      subst. rewrite ratMul_0_r_r... apply ratMul_pos_prd...\n  - intros p Hp q Hq Hqxy Hlt.\n    apply realNonNegMulE in Hqxy as []; auto; [|\n      destruct (classic (ratNeg p)) as [|Hnnp]]; auto; [| |\n        destruct H as [s [Hsq [t [Htq [[Hs Ht]\n          [[[Hps|H0] Hnnt] Heq]]]]]]; revgoals]; subst.\n    + apply realNonNegMulI0...\n      apply SepE in H as [_ H0]. eapply ratLt_trans...\n    + apply realNonNegMulI0...\n    + apply realNonNegMulI0...\n      rewrite ratMul_0_l in Hlt...\n    + assert (Hsq': s ∈ ℚ'). {\n        apply nzRatI0... apply rat_neq_0...\n      }\n      assert (Hrsq: s⁻¹ ∈ ℚ). {\n        apply nzRatE1. apply ratMulInv_ran...\n      }\n      assert (Hprs: ratPos s⁻¹) by (apply ratPos_mulInv; auto).\n      assert (Heq: p = s ⋅ (p / s)). {\n        rewrite (ratMul_comm p), <- ratMul_assoc,\n        ratMulInv_annih, ratMul_1_l...\n      }\n      assert (Hlt': p / s <𝐪 t). {\n        rewrite <- (ratMul_1_r t), <- (ratMulInv_annih s),\n          <- ratMul_assoc... apply ratMul_preserve_lt...\n        apply ratMul_ran... rewrite ratMul_comm...\n      }\n      rewrite Heq. apply realNonNegMulI1...\n      eapply realE2; revgoals... apply ratMul_ran... left...\n      apply ratNonNeg_not_neg in Hnnp as []...\n      left. apply ratMul_pos_prd...\n      right. subst. rewrite ratMul_0_l...\n  - intros p Hp. apply realNonNegMulE in Hp as []...\n    + apply SepE in H as [Hpq Hp0]. \n      assert (Hpd2q: p / Rat 2 ∈ ℚ) by (apply ratMul_ran; nauto).\n      assert (Hnpq: - p ∈ ℚ) by (apply ratAddInv_ran; auto).\n      exists (p / Rat 2). split.\n      * apply realNonNegMulI0... unfold ratNeg.\n        rewrite <- (ratMul_1_r (Rat 0)),\n          <- (ratMulInv_annih (Rat 2)), <- ratMul_assoc, ratMul_0_l...\n        apply ratMul_preserve_lt...\n      * apply ratLt_addInv... rewrite <- (ratMul_1_r (-p)),\n          <- ratMul_addInv_l, ratMul_comm, (ratMul_comm (-p))...\n        apply ratMul_preserve_lt...\n        apply ratNeg_pos... apply ratLt_r2_1.\n    + destruct H as [s [Hsq [t [Htq [[Hs Ht] [[Hnns Hnnt] Heq]]]]]].\n      apply realE3 in Hs as [q [Hqq [Hqx H1]]]...\n      apply realE3 in Ht as [r [Hrq [Hry H2]]]...\n      assert (Hpq: ratPos q). {\n        destruct Hnns. eapply ratLt_trans... subst...\n      }\n      assert (Hpr: ratPos r). {\n        destruct Hnnt. eapply ratLt_trans.\n        apply H. apply H2. subst...\n      }\n      exists (q ⋅ r). split. apply realNonNegMulI1...\n      left... left... destruct Hnnt; revgoals; subst.\n      * rewrite ratMul_0_r_r... apply ratMul_pos_prd...\n      * apply ratMul_preserve_lt_trans...\nQed.\n\nClose Scope Rat_scope.\nOpen Scope Real_scope.\n\nLemma realNonNegMul_comm : ∀ x y ∈ ℝ,\n  realNonNeg x → realNonNeg y → x ⋅₊ y = y ⋅₊ x.\nProof with auto.\n  intros x Hx y Hy Hnnx Hnny.\n  ext p Hp.\n  - assert (Hpq: p ∈ ℚ). {\n      apply real_sub_rat in Hp... apply realNonNegMul_ran...\n    }\n    apply realNonNegMulE in Hp as []; auto; [|\n      destruct (classic (ratNeg p)) as [|Hnnp]]...\n    + apply BUnionI1...\n    + apply realNonNegMulI0...\n    + destruct H as [s [Hsq [t [Htq [[Hs Ht] [[Hnns Hnnt] Heq]]]]]].\n      rewrite Heq, ratMul_comm... apply realNonNegMulI1...\n  - assert (Hpq: p ∈ ℚ). {\n      apply real_sub_rat in Hp... apply realNonNegMul_ran...\n    }\n    apply realNonNegMulE in Hp as []; auto; [|\n      destruct (classic (ratNeg p)) as [|Hnnp]]...\n    + apply BUnionI1...\n    + apply realNonNegMulI0...\n    + destruct H as [s [Hsq [t [Htq [[Hs Ht] [[Hnns Hnnt] Heq]]]]]].\n      rewrite Heq, ratMul_comm... apply realNonNegMulI1...\nQed.\n\nLemma realNonNegMul_0_r_r : ∀x ∈ ℝ, x ⋅₊ Real 0 = Real 0.\nProof with nauto.\n  intros x Hx. ext p Hp.\n  - apply realNonNegMulE in Hp as []... exfalso.\n    destruct H as [_ [_ [t [_ [[_ Ht] [[_ Hnnt] _]]]]]].\n    apply SepE in Ht as [Htq Hnt].\n    apply ratNonNeg_not_neg in Hnnt...\n  - apply BUnionI1...\nQed.\n\nLemma realNonNegMul_0_l : ∀x ∈ ℝ, Real 0 ⋅₊ x = Real 0.\nProof with nauto.\n  intros x Hx. ext p Hp.\n  - apply realNonNegMulE in Hp as []... exfalso.\n    destruct H as [q [_ [_ [_ [[Hq _] [[Hnnq _] _]]]]]].\n    apply SepE in Hq as [Hqq Hnq].\n    apply ratNonNeg_not_neg in Hnnq...\n  - apply BUnionI1...\nQed.\n\nLemma realNonNegMul_preserve_le : ∀ x y z ∈ ℝ,\n  realNonNeg x → realNonNeg y → realPos z → \n  x ≤ y → x ⋅₊ z ≤ y ⋅₊ z.\nProof with eauto.\n  intros x Hx y Hy z Hz Hnnx Hnny Hpz Hle.\n  apply realPos_nonNeg in Hpz as Hnnz...\n  apply realLeE in Hle. apply realLeI.\n  apply realNonNegMul_ran... apply realNonNegMul_ran...\n  intros p Hp. apply realNonNegMulE in Hp as []...\n  - apply BUnionI1...\n  - destruct H as [q [_ [r [_ [[Hq Hr] [[Hnnq Hnnr] Heq]]]]]].\n    destruct Hnny as [Hpy|Hy0].\n    + rewrite Heq. apply realNonNegMulI1...\n    + exfalso. subst. apply Hle in Hq.\n      apply SepE in Hq as [Hq Hq0].\n      apply ratNonNeg_not_neg in Hnnq...\nQed.\n\nLemma realNonNegMul_nonNeg_prd : ∀ x y ∈ ℝ,\n  realNonNeg x → realNonNeg y → realNonNeg (x ⋅₊ y).\nProof with nauto.\n  intros x Hxr y Hyr Hnnx Hnny.\n  destruct Hnny as [Hpy|Hy0].\n  - unfold realNonNeg. rewrite <- (realNonNegMul_0_l y)...\n    apply realNonNegMul_preserve_le... right...\n  - subst. rewrite realNonNegMul_0_r_r... right...\nQed.\n\nLemma realNonNegMul_pos_prd : ∀ x y ∈ ℝ,\n  realPos x → realPos y → realPos (x ⋅₊ y).\nProof with nauto.\n  intros x Hxr y Hyr Hpx Hpy. apply realPos_rat0.\n  apply realNonNegMul_ran; auto; apply realPos_nonNeg...\n  rewrite <- (ratMul_0_l (Rat 0))... apply realNonNegMulI1...\n  apply realPos_rat0... apply realPos_rat0... right... right...\nQed.\n\nLemma realNonNegMul_assoc : ∀ x y z ∈ ℝ,\n  realNonNeg x → realNonNeg y → realNonNeg z →\n  (x ⋅₊ y) ⋅₊ z = x ⋅₊ (y ⋅₊ z).\nProof with auto.\n  intros x Hx y Hy z Hz Hnnx Hnny Hnnz.\n  assert (Hxyr: x ⋅₊ y ∈ ℝ) by (apply realNonNegMul_ran; auto).\n  assert (Hyzr: y ⋅₊ z ∈ ℝ) by (apply realNonNegMul_ran; auto).\n  ext p Hp.\n  - assert (Hpq: p ∈ ℚ). {\n      apply real_sub_rat in Hp... apply realNonNegMul_ran...\n      apply realNonNegMul_nonNeg_prd...\n    }\n    apply realNonNegMulE in Hp as []... apply BUnionI1...\n    destruct H as [q [_ [t [Htq [[Hq Ht] [[Hnnq Hnnt] Hpeq]]]]]].\n    apply realNonNegMulE in Hq as []...\n    + exfalso. apply SepE in H as [Hqq Hnq].\n      apply ratNonNeg_not_neg in Hnnq...\n    + destruct H as [r [Hrq [s [Hsq [[Hr Hs] [[Hnnr Hnns] Hqeq]]]]]].\n      assert (Hnnst: ratNonNeg (s ⋅ t)%q)\n        by (apply ratMul_nonNeg_prd; auto).\n      subst. rewrite ratMul_assoc...\n      apply realNonNegMulI1... apply realNonNegMulI1...\n  - assert (Hpq: p ∈ ℚ). {\n      apply real_sub_rat in Hp... apply realNonNegMul_ran...\n      apply realNonNegMul_nonNeg_prd...\n    }\n    apply realNonNegMulE in Hp as []... apply BUnionI1...\n    destruct H as [q [Hqq [t [_ [[Hq Ht] [[Hnnq Hnnt] Hpeq]]]]]].\n    apply realNonNegMulE in Ht as []...\n    + exfalso. apply SepE in H as [Htq Hnt].\n      apply ratNonNeg_not_neg in Hnnt...\n    + destruct H as [r [Hrq [s [Hsq [[Hr Hs] [[Hnnr Hnns] Hteq]]]]]].\n      assert (Hnnqr: ratNonNeg (q ⋅ r)%q)\n        by (apply ratMul_nonNeg_prd; auto).\n      subst. rewrite <- ratMul_assoc...\n      apply realNonNegMulI1... apply realNonNegMulI1...\nQed.\n\nLemma realAddE_nonNeg : ∀ x y ∈ ℝ, ∀q ∈ ℚ,\n  realPos x → realPos y → ratNonNeg q → q ∈ x + y →\n  ∃ r s ∈ ℚ, (r ∈ x ∧ s ∈ y) ∧\n    (ratNonNeg r ∧ ratNonNeg s) ∧ (r + s)%q = q.\nProof with neauto.\n  intros x Hx y Hy q Hqq Hpx Hpy Hnnq Hq.\n  apply ReplAx in Hq as [t [Ht Heq]]. apply CPrdE1 in Ht\n    as [r [Hr [s [Hs Ht]]]]. subst. zfc_simple.\n  assert (Hrq: r ∈ ℚ) by (eapply real_sub_rat; revgoals; eauto).\n  assert (Hsq: s ∈ ℚ) by (eapply real_sub_rat; revgoals; eauto).\n  destruct (classic (ratNeg r)); destruct (classic (ratNeg s)).\n  - exfalso. apply ratNonNeg_not_neg in Hnnq...\n    apply Hnnq. apply ratAdd_neg_sum...\n  - exists (Rat 0). split... exists (r + s)%q. repeat split...\n    + apply realPos_rat0...\n    + cut ((r + s)%q <𝐪 s). intros Hlt. eapply realE2; revgoals...\n      rewrite <- (ratAdd_0_l s) at 2... apply ratAdd_preserve_lt...\n    + right... + rewrite ratAdd_0_l...\n  - exists (r + s)%q. split... exists (Rat 0). repeat split...\n    + cut ((r + s)%q <𝐪 r). intros Hlt. eapply realE2; revgoals...\n      rewrite <- (ratAdd_0_r r) at 2... apply ratAdd_preserve_lt'...\n    + apply realPos_rat0...\n    + right... + rewrite ratAdd_0_r...\n  - apply ratNonNeg_not_neg in H... apply ratNonNeg_not_neg in H0...\n    exists r. split... exists s. split...\nQed.\n\nLemma realNonNegMul_distr : ∀ x y z ∈ ℝ,\n  realNonNeg x → realNonNeg y → realNonNeg z →\n  x ⋅₊ (y + z) = x ⋅₊ y + x ⋅₊ z.\nProof with nauto.\n  intros x Hx y Hy z Hz Hnnx Hnny Hnnz.\n  assert (Hxyr: x ⋅₊ y ∈ ℝ) by (apply realNonNegMul_ran; auto).\n  assert (Hxzr: x ⋅₊ z ∈ ℝ) by (apply realNonNegMul_ran; auto).\n  assert (Hsumr: y + z ∈ ℝ) by (apply realAdd_ran; auto).\n  ext p Hp.\n  - apply realNonNegMulE in Hp as []...\n    + cut (Real 0 ⊆ x ⋅₊ y + x ⋅₊ z). intros Hsub. apply Hsub...\n      apply realLe... apply realAdd_ran...\n      apply realAdd_nonNeg_sum; auto;\n      apply realNonNegMul_nonNeg_prd...\n    + destruct H as [q [Hqq [t [Htq [[Hq Ht] [[Hnnq Hnnt] Hpeq]]]]]].\n      destruct Hnny; destruct Hnnz; subst.\n      * apply realAddE_nonNeg in Ht\n          as [r [Hrq [s [Hsq [[Hr Hs] [[Hnnr Hnns] Heq]]]]]]...\n        subst. rewrite ratMul_distr... apply realAddI2...\n        apply realNonNegMulI1... apply realNonNegMulI1...\n      * rewrite realAdd_0_r in Ht...\n        rewrite realNonNegMul_0_r_r, realAdd_0_r...\n        apply realNonNegMulI1...\n      * rewrite realAdd_0_l in Ht...\n        rewrite realNonNegMul_0_r_r, realAdd_0_l...\n        apply realNonNegMulI1...\n      * exfalso. apply ratNonNeg_not_neg in Hnnt... apply Hnnt.\n        rewrite realAdd_0_r in Ht... apply SepE2 in Ht...\n  - destruct Hnnx as [Hpx|]; revgoals; [|\n      destruct (classic (y = Real 0 ∨ z = Real 0)); [\n        destruct H |\n        apply not_or_and in H as [Hy0 Hz0];\n        destruct Hnny as [Hpy|]; destruct Hnnz as [Hpz|];\n          [clear Hy0 Hz0|exfalso; auto..]\n    ]]; subst.\n    + rewrite realNonNegMul_0_l... rewrite realNonNegMul_0_l,\n        realNonNegMul_0_l, realAdd_0_r in Hp...\n    + rewrite realAdd_0_l...\n      rewrite realNonNegMul_0_r_r, realAdd_0_l in Hp...\n    + rewrite realAdd_0_r...\n      rewrite realNonNegMul_0_r_r, realAdd_0_r in Hp...\n    + assert (Hpq: p ∈ ℚ). {\n        apply real_sub_rat in Hp... apply realAdd_ran...\n      }\n      destruct (classic (ratNeg p)) as [|Hnnp]. apply realNonNegMulI0...\n      apply ratNonNeg_not_neg in Hnnp...\n      apply realAddE_nonNeg in Hp\n        as [q [Hqq [r [Hrq [[Hq Hr] [_ Heq]]]]]];\n        auto; [|apply realNonNegMul_pos_prd; auto..].\n      Close Scope Real_scope.\n      Open Scope Rat_scope.\n      apply realNonNegMulE in Hq as [Hq|Hq];\n      apply realNonNegMulE in Hr as [Hr|Hr]...\n      * exfalso. subst. apply ratNonNeg_not_neg in Hnnp...\n        apply Hnnp. apply ratAdd_neg_sum...\n        apply SepE2 in Hq... apply SepE2 in Hr...\n      * destruct Hr as [s [Hsq [t [Htq [[Hs Ht] [[Hnns Hnnt] Hreq]]]]]].\n        destruct Hnns; revgoals; subst.\n        rewrite (ratMul_0_l t), ratAdd_0_r... apply BUnionI1...\n        assert (Hs': s ∈ ℚ'). {\n          apply nzRatI0... apply rat_neq_0...\n        }\n        assert (Hrsq: s⁻¹ ∈ ℚ). {\n          apply nzRatE1. apply ratMulInv_ran...\n        }\n        assert (Hqsq: q/s ∈ ℚ) by (apply ratMul_ran; auto).\n        assert (Hqs0: q/s <𝐪 Rat 0). {\n          rewrite ratMul_comm... apply ratMul_neg_prd...\n          apply ratPos_mulInv... apply SepE2 in Hq...\n        }\n        assert (Hnnsum: ratNonNeg (q/s + t)). {\n          unfold ratNonNeg.\n          rewrite <- (ratMul_1_r t), <- (ratMulInv_annih s),\n            <- (ratMul_assoc t Htq s Hsq (s⁻¹)),\n            (ratMul_comm t Htq s Hsq),\n            <- ratMul_distr', <- (ratMul_0_l s⁻¹); [|auto..].\n          apply ratMul_preserve_le... apply ratPos_mulInv...\n        }\n        replace (q + s ⋅ t) with (s ⋅ (q/s + t)).\n        apply realNonNegMulI1... apply realAddI2...\n        eapply realE2; revgoals; [eauto|nauto..]. apply realPos_rat0... left...\n        rewrite ratMul_distr, (ratMul_comm q Hqq s⁻¹ Hrsq),\n          <- (ratMul_assoc s Hsq s⁻¹ Hrsq q Hqq),\n          (ratMulInv_annih s), (ratMul_1_l q); [|auto..]...\n      * destruct Hq as [s [Hsq [t [Htq [[Hs Ht] [[Hnns Hnnt] Hqeq]]]]]].\n        destruct Hnns; revgoals; subst.\n        rewrite (ratMul_0_l t), ratAdd_0_l... apply BUnionI1...\n        assert (Hs': s ∈ ℚ'). {\n          apply nzRatI0... apply rat_neq_0...\n        }\n        assert (Hrsq: s⁻¹ ∈ ℚ). {\n          apply nzRatE1. apply ratMulInv_ran...\n        }\n        assert (Hrdsq: r/s ∈ ℚ) by (apply ratMul_ran; auto).\n        assert (Hrs0: r/s <𝐪 Rat 0). {\n          rewrite ratMul_comm... apply ratMul_neg_prd...\n          apply ratPos_mulInv... apply SepE2 in Hr...\n        }\n        assert (Hnnsum: ratNonNeg (t + r/s)). {\n          unfold ratNonNeg.\n          rewrite <- (ratMul_1_r t), <- (ratMulInv_annih s),\n            <- (ratMul_assoc t Htq s Hsq s⁻¹ Hrsq),\n            (ratMul_comm t Htq s Hsq),\n            <- ratMul_distr', <- (ratMul_0_l s⁻¹); [|auto..].\n          apply ratMul_preserve_le; nauto. apply ratPos_mulInv... \n        }\n        replace (s ⋅ t + r) with (s ⋅ (t + r/s)).\n        apply realNonNegMulI1... apply realAddI2...\n        eapply realE2; revgoals; [eauto|nauto..].\n        apply realPos_rat0... left...\n        rewrite ratMul_distr, (ratMul_comm r Hrq s⁻¹ Hrsq),\n          <- (ratMul_assoc s Hsq s⁻¹ Hrsq r Hrq),\n          (ratMulInv_annih s), (ratMul_1_l r); [|auto..]...\n      * destruct Hq as [s [Hsq [t [Htq [[Hs Ht] [[Hnns Hnnt] Hqeq]]]]]].\n        destruct Hr as [u [Huq [v [Hvq [[Hu Hv] [[Hnnu Hnnv] Hreq]]]]]].\n        destruct Hnns as [Hps|]; revgoals; subst. {\n          rewrite (ratMul_0_l t), ratAdd_0_l; [|auto..].\n          apply realNonNegMulI1... rewrite <- (ratAdd_0_l v)...\n          apply realAddI2... apply realPos_rat0...\n        }\n        destruct Hnnt as [Hpt|]; revgoals; subst. {\n          rewrite (ratMul_0_r_r s), ratAdd_0_l; [|auto..].\n          apply realNonNegMulI1... rewrite <- (ratAdd_0_l v)...\n          apply realAddI2...\n        }\n        destruct Hnnu as [Hpu|]; revgoals; subst. {\n          rewrite (ratMul_0_l v), ratAdd_0_r; [|auto..].\n          apply realNonNegMulI1... rewrite <- (ratAdd_0_r t)...\n          apply realAddI2... apply realPos_rat0... left... left...\n        }\n        destruct Hnnv as [Hpv|]; revgoals; subst. {\n          rewrite (ratMul_0_r_r u), ratAdd_0_r; [|auto..].\n          apply realNonNegMulI1... rewrite <- (ratAdd_0_r t)...\n          apply realAddI2... left... left...\n        }\n        destruct (classic (s = u)). {\n          subst. rewrite <- ratMul_distr...\n          apply realNonNegMulI1... apply realAddI2... left...\n          apply ratAdd_nonNeg_sum... left... left...\n        }\n        apply ratLt_connected in H as [Hsu|Hus]... {\n          assert (Hu': u ∈ ℚ'). {\n            apply nzRatI0... apply rat_neq_0...\n          }\n          assert (Hruq: u⁻¹ ∈ ℚ). {\n            apply nzRatE1. apply ratMulInv_ran...\n          }\n          assert (Hpru: ratPos u⁻¹) by (apply ratPos_mulInv; auto).\n          assert (Hsuq: s/u ∈ ℚ) by (apply ratMul_ran; auto).\n          assert (Hsu1: s/u <𝐪 Rat 1). {\n            rewrite <- (ratMulInv_annih u)...\n            apply ratMul_preserve_lt...\n          }\n          assert (Hlt: (s/u) ⋅ t <𝐪 t). {\n            rewrite <- (ratMul_1_l t) at 2...\n            apply ratMul_preserve_lt...\n          }\n          assert (Hsutq: (s/u) ⋅ t ∈ ℚ) by (apply ratMul_ran; auto).\n          assert (Hnnsum: ratNonNeg ((s/u) ⋅ t + v)). {\n            left. apply ratAdd_pos_sum...\n            apply ratMul_pos_prd... apply ratMul_pos_prd...\n          }\n          replace (s⋅t + u⋅v) with (u⋅((s/u)⋅t + v)).\n          apply realNonNegMulI1... apply realAddI2...\n          eapply realE2; revgoals; [eauto|nauto..]. left...\n          rewrite ratMul_distr,\n            <- (ratMul_assoc u Huq (s/u) Hsuq t Htq),\n            (ratMul_comm s Hsq u⁻¹ Hruq),\n            <- (ratMul_assoc u Huq u⁻¹ Hruq s Hsq),\n            (ratMulInv_annih u), (ratMul_1_l s);\n            try apply ratMul_ran...\n        } {\n          assert (Hs': s ∈ ℚ'). {\n            apply nzRatI0... apply rat_neq_0...\n          }\n          assert (Hrsq: s⁻¹ ∈ ℚ). {\n            apply nzRatE1. apply ratMulInv_ran...\n          }\n          assert (Hprs: ratPos s⁻¹) by (apply ratPos_mulInv; auto).\n          assert (Husq: u/s ∈ ℚ) by (apply ratMul_ran; auto).\n          assert (Hus1: u/s <𝐪 Rat 1). {\n            rewrite <- (ratMulInv_annih s)...\n            apply ratMul_preserve_lt...\n          }\n          assert (Hlt: (u/s) ⋅ v <𝐪 v). {\n            rewrite <- (ratMul_1_l v) at 2...\n            apply ratMul_preserve_lt...\n          }\n          assert (Hustq: (u/s) ⋅ v ∈ ℚ) by (apply ratMul_ran; auto).\n          assert (Hnnsum: ratNonNeg (t + (u/s) ⋅ v)). {\n            left. apply ratAdd_pos_sum...\n            apply ratMul_pos_prd... apply ratMul_pos_prd...\n          }\n          replace (s⋅t + u⋅v) with (s⋅(t + (u/s)⋅v)).\n          apply realNonNegMulI1... apply realAddI2...\n          eapply realE2; revgoals; [eauto|nauto..]. left...\n          rewrite ratMul_distr,\n            <- (ratMul_assoc s Hsq (u/s) Husq v Hvq),\n            (ratMul_comm u Huq s⁻¹ Hrsq),\n            <- (ratMul_assoc s Hsq s⁻¹ Hrsq u Huq),\n            (ratMulInv_annih s), (ratMul_1_l u);\n            try apply ratMul_ran...\n        }\nQed.\n\nClose Scope Rat_scope.\nOpen Scope Real_scope.\n\nLemma realNonNegMul_distr' : ∀ x y z ∈ ℝ,\n  realNonNeg x → realNonNeg y → realNonNeg z → realNonNeg (y - z) →\n  x ⋅₊ (y - z) = x ⋅₊ y - x ⋅₊ z.\nProof with neauto.\n  intros x Hx y Hy z Hz Hnnx Hnny Hnnz Hd.\n  assert (Hnzr: -z ∈ ℝ) by (apply realAddInv_ran; auto).\n  assert (Hxzr: x ⋅₊ z ∈ ℝ) by (apply realNonNegMul_ran; auto).\n  assert (Hxyr: x ⋅₊ y ∈ ℝ) by (apply realNonNegMul_ran; auto).\n  assert (Hnxzr: -(x ⋅₊ z) ∈ ℝ) by (apply realAddInv_ran; auto).\n  assert (Hdr: y - z ∈ ℝ) by (apply realAdd_ran; auto).\n  assert (Hxdr: x ⋅₊ (y - z) ∈ ℝ) by (apply realNonNegMul_ran; auto).\n  assert (Hdistr: x ⋅₊ y - x ⋅₊ z ∈ ℝ) by (apply realAdd_ran; auto).\n  apply (realAdd_cancel _ Hxdr _ Hdistr _ Hxzr).\n  rewrite <- realNonNegMul_distr,\n    realAdd_assoc, (realAdd_comm (-z)),\n    realAddInv_annih, realAdd_0_r,\n    realAdd_assoc, (realAdd_comm (-(x ⋅₊ z))),\n    realAddInv_annih, realAdd_0_r...\nQed.\n\nClose Scope Real_scope.\nOpen Scope Rat_scope.\n\nLemma realNonNegMul_1_r : ∀x ∈ ℝ,\n  realNonNeg x → (x ⋅₊ Real 1)%r  = x.\nProof with neauto.\n  intros x Hx Hnnx.\n  ext p Hp.\n  - apply realNonNegMulE in Hp as []...\n    + destruct Hnnx as [Hpx|]; [|subst; auto].\n      apply SepE in H as [Hpq Hlt].\n      eapply realE2; revgoals... apply realPos_rat0...\n    + destruct H as [q [Hqq [r [Hrq [[Hq Hr] [[Hnnq Hnnr] Heq]]]]]].\n      destruct Hnnq as [Hpq|Hq0]; revgoals; subst.\n      rewrite ratMul_0_l... eapply realE2; revgoals...\n      rewrite <- (ratMul_1_r q) at 2... apply ratMul_preserve_lt'...\n      apply SepE2 in Hr... apply ratMul_ran...\n  - destruct (classic (ratNeg p)). apply realNonNegMulI0...\n    assert (Hpq: p ∈ ℚ) by (eapply real_sub_rat; eauto).\n    apply ratNonNeg_not_neg in H...\n    apply realE3 in Hp as [q [Hqq [Hq Hlt]]]...\n    assert (Hpoq: ratPos q). {\n      destruct H. eapply ratLt_trans... subst...\n    }\n    assert (Hprq: ratPos q⁻¹)\n      by (apply ratPos_mulInv; auto).\n    assert (Hqq': q ∈ ℚ'). {\n      apply nzRatI0... apply rat_neq_0...\n    }\n    assert (Hrqq: q⁻¹ ∈ ℚ). {\n      apply nzRatE1. apply ratMulInv_ran...\n    }\n    replace p with (q ⋅ (p/q)).\n    apply realNonNegMulI1... apply SepI.\n    apply ratMul_ran... rewrite <- (ratMulInv_annih q)...\n    apply ratMul_preserve_lt... left...\n    apply ratMul_nonNeg_prd... left...\n    rewrite (ratMul_comm p), <- ratMul_assoc,\n      ratMulInv_annih, ratMul_1_l...\nQed.\n\nLemma realNonNegMul_1_l : ∀x ∈ ℝ,\n  realNonNeg x → (Real 1 ⋅₊ x)%r  = x.\nProof with nauto.\n  intros x Hx Hnnx.\n  rewrite realNonNegMul_comm, realNonNegMul_1_r...\n  left. apply realPos_sn.\nQed.\n\nClose Scope Rat_scope.\nOpen Scope Real_scope.\n\n(* 正实数乘法逆元 *)\nDefinition RealPosMulInv : set → set := λ x,\n  {r ∊ ℚ | ∃s ∈ ℚ, s ∉ x ∧ (r ⋅ s)%q <𝐪 Rat 1}.\nNotation \"x ⁻¹⁺\" := (RealPosMulInv x) (at level 9) : Real_scope.\n\nLemma realPosMulInv_sub_rat : ∀x ∈ ℝ, x⁻¹⁺ ∈ 𝒫 ℚ.\nProof with auto.\n  intros x Hx. apply PowerAx. intros q Hq.\n  unfold RealPosMulInv in Hq. apply SepE1 in Hq...\nQed.\n\nClose Scope Real_scope.\nOpen Scope Rat_scope.\n\nLemma ratLt_mulInv': ∀ q r ∈ ℚ, ratPos r → q <𝐪 r⁻¹ ↔ q ⋅ r <𝐪 Rat 1.\nProof with auto.\n  intros q Hq r Hr Hpr.\n  assert (Hr': r ∈ ℚ'). { apply nzRatI0... apply rat_neq_0... }\n  assert (Hrr: r⁻¹ ∈ ℚ). { apply nzRatE1. apply ratMulInv_ran... }\n  split; intros.\n  - rewrite <- (ratMulInv_annih r), ratMul_comm...\n    apply ratMul_preserve_lt'...\n  - rewrite <- (ratMulInv_annih r), ratMul_comm in H...\n    apply ratMul_preserve_lt' in H...\nQed.\n\nLemma realPosMulInv_ran : ∀x ∈ ℝ, realPos x → (x⁻¹⁺)%r ∈ ℝ.\nProof with neauto.\n  intros x Hx Hpx. apply SepI.\n  apply realPosMulInv_sub_rat...\n  apply realPos_rat0 in Hpx... repeat split...\n  - destruct (classic (x ≤ Real 1)%r).\n    + apply realLe in H as Hsub... \n      pose proof (realE3 _ Hx _ Hpx) as [q [Hqq [Hqx H0q]]].\n      pose proof (realE3 _ Hx _ Hqx) as [r [Hrq [Hrx Hqr]]].\n      apply Hsub in Hqx as Hq1. apply SepE in Hq1 as [_ Hq1].\n      apply Hsub in Hrx as Hr1. apply SepE in Hr1 as [_ Hr1].\n      assert (Hpr: ratPos r) by (eapply ratLt_trans; eauto).\n      apply ratLt_mulInv in Hr1... rewrite ratMulInv_1 in Hr1.\n      assert (Hr': r ∈ ℚ'). { apply nzRatI0... apply rat_neq_0... }\n      assert (Hrr: r⁻¹ ∈ ℚ). { apply nzRatE1. apply ratMulInv_ran... }\n      assert (H1x: Rat 1 ∉ x) by (apply realLt_realn'; auto).\n      assert (Hrrx: r⁻¹ ∉ x) by (apply (realE2_2 _ Hx (Rat 1)); nauto).\n      apply EmptyNI. exists q. apply SepI... exists (r⁻¹).\n      repeat split... rewrite <- (ratMulInv_annih r)...\n      apply ratMul_preserve_lt... apply ratPos_mulInv...\n    + apply not_or_and in H as [].\n      apply realLt_connected in H0 as []...\n      apply realLt_realn in H0 as H1x...\n      pose proof (realE1 _ Hx) as [q [Hqq Hqx]].\n      pose proof (rat_archimedean _ Hqq) as [r [Hrq Hqr]].\n      assert (H1q: Rat 1 <𝐪 q) by (eapply realE2_1; neauto).\n      assert (H1r: Rat 1 <𝐪 r) by (eapply ratLt_trans; eauto).\n      assert (Hpr: ratPos r). {\n        eapply ratLt_trans; revgoals. apply H1r. apply ratPos_sn.\n      }\n      assert (Hr': r ∈ ℚ'). { apply nzRatI0... apply rat_neq_0... }\n      assert (Hrr: r⁻¹ ∈ ℚ). { apply nzRatE1. apply ratMulInv_ran... }\n      apply ratLt_mulInv in H1r as Hr1... rewrite ratMulInv_1 in Hr1.\n      apply EmptyNI. exists (r⁻¹). apply SepI... exists q.\n      repeat split... rewrite <- (ratMulInv_annih r), ratMul_comm...\n      apply ratMul_preserve_lt... apply ratPos_mulInv...\n  - pose proof (realE3 _ Hx _ Hpx) as [q [Hqq [Hqx H0q]]].\n    assert (Hq': q ∈ ℚ'). { apply nzRatI0... apply rat_neq_0... }\n    assert (Hrq: q⁻¹ ∈ ℚ). { apply nzRatE1. apply ratMulInv_ran... }\n    apply ExtNI. exists (q⁻¹). split... intros Hrqrx.\n    apply SepE in Hrqrx as [_ [s [Hsq [Hsx Hlt]]]].\n    rewrite <- (ratMulInv_annih q), ratMul_comm in Hlt...\n    apply ratMul_preserve_lt in Hlt; auto; [|apply ratPos_mulInv]...\n    apply Hsx. eapply realE2; revgoals...\n  - intros p Hpq q Hqq Hp Hlt.\n    apply SepE in Hp as [_ [r [Hrq [Hrx Hr1]]]].\n    assert (Hpr: ratPos r) by (eapply realE2_1; neauto).\n    apply SepI... exists r. repeat split...\n    apply ratLt_mulInv' in Hr1...\n    apply ratLt_mulInv'... eapply ratLt_trans...\n  - intros p Hp. apply SepE in Hp as [Hpq [r [Hrq [Hrx Hpr1]]]].\n    assert (Hpr: ratPos r) by (eapply realE2_1; neauto).\n    assert (Hr': r ∈ ℚ'). { apply nzRatI0... apply rat_neq_0... }\n    assert (Hrr: r⁻¹ ∈ ℚ). { apply nzRatE1. apply ratMulInv_ran... }\n    destruct (classic (ratNonPos p)) as [Hnpp|Hpp].\n    + apply ratPos_mulInv in Hpr as Hprr.\n      apply rat_dense in Hprr as [q [Hqq [Hq1 Hq2]]]...\n      exists q. split. apply SepI... exists r. repeat split...\n      apply ratLt_mulInv'... destruct Hnpp.\n      eapply ratLt_trans... subst...\n    + apply ratPos_not_nonPos in Hpp...\n      destruct (classic (p <𝐪 Rat 1)) as [Hp1|H1p];\n      destruct (classic (r <𝐪 Rat 1)) as [Hr1|H1r].\n      * exists (Rat 1). split... apply SepI...\n        exists r. repeat split... rewrite ratMul_1_l...\n      * apply ratLt_mulInv' in Hpr1...\n        apply rat_dense in Hpr1 as [q [Hqq [Hq1 Hq2]]]...\n        exists q. split... apply SepI... exists r. repeat split...\n        destruct (classic (r = Rat 1)).\n        subst. rewrite ratMulInv_1 in Hq2. rewrite ratMul_1_r...\n        apply ratLt_connected in H as []...\n        exfalso... apply ratLt_mulInv'...\n      * apply ratLt_mulInv' in Hpr1...\n        apply rat_dense in Hpr1 as [q [Hqq [Hq1 Hq2]]]...\n        exists q. split... apply SepI... exists r. repeat split...\n        apply ratLt_mulInv'...\n      * exfalso. apply H1p. destruct (classic (r = Rat 1)).\n        subst. rewrite ratMul_1_r in Hpr1...\n        apply ratLt_connected in H as []... exfalso...\n        apply ratLt_mulInv in H... rewrite ratMulInv_1 in H.\n        apply ratLt_mulInv' in Hpr1... eapply ratLt_trans...\nQed.\n\nLemma ex5_19' : ∀x ∈ ℝ, ∀p ∈ ℚ, realPos x → Rat 1 <𝐪 p →\n  ∃q ∈ ℚ, ratPos q ∧ q ∈ x ∧ p ⋅ q ∉ x.\nProof with nauto.\n  intros x Hx p Hp Hpx H1p. apply realPos_rat0 in Hpx...\n  pose proof (realE3 _ Hx _ Hpx) as [r [Hr [Hrx Hpr]]].\n  set (p - Rat 1) as p'.\n  set (p' ⋅ r / Rat 3) as s.\n  assert (Hp': p' ∈ ℚ) by (apply ratAdd_ran; nauto).\n  assert (Hs: s ∈ ℚ). {\n    apply ratMul_ran. apply ratMul_ran... nauto.\n  }\n  assert (Hpp': ratPos p'). {\n    unfold ratPos. rewrite <- (ratAddInv_annih (Rat 1))...\n    apply ratAdd_preserve_lt...\n  }\n  assert (Hps: ratPos s). {\n    apply ratMul_pos_prd. apply ratMul_ran... nauto.\n    apply ratMul_pos_prd... nauto.\n  }\n  pose proof (ex5_19 _ Hx _ Hs Hps) as [t [Ht [Htx Hleft]]].\n  destruct (classic (r / Rat 3 <𝐪 t)).\n  - assert (Hnt: -t ∈ ℚ) by (apply ratAddInv_ran; auto).\n    assert (Hst: s + t ∈ ℚ) by (apply ratAdd_ran; auto).\n    assert (Hpt: p ⋅ t ∈ ℚ) by (apply ratMul_ran; auto).\n    cut (s + t <𝐪 p ⋅ t). intros Hlt.\n    * exists t. repeat split; [auto| |auto|].\n      eapply ratLt_trans; revgoals; [eauto|apply ratMul_pos_prd]...\n      eapply realE2_2; revgoals; [apply Hlt|..]; assumption.\n    * eapply ratAdd_preserve_lt; swap 1 3; [apply Hnt|auto..|].\n      rewrite ratAdd_assoc, ratAddInv_annih, ratAdd_0_r; [|auto..].\n      rewrite <- (ratMul_1_l t) at 2; [|auto..].\n      rewrite <- ratMul_addInv_l, <- ratMul_distr'; [|nauto..].\n      unfold s. rewrite ratMul_assoc; [|nauto..]. subst p'.\n      apply ratMul_preserve_lt'; [apply ratMul_ran|..]...\n  - exists (r / Rat 2). repeat split.\n    + apply ratMul_ran... + apply ratMul_pos_prd...\n    + cut (r / Rat 2 <𝐪 r). intros Hlt.\n      * eapply realE2; swap 1 5; [apply Hlt| |auto..].\n        apply ratMul_ran... \n      * rewrite ratMul_comm... rewrite <- (ratMul_1_l r) at 2.\n        apply ratMul_preserve_lt... apply ratLt_r2_1. auto.\n    + cut (s + t <𝐪 p ⋅ (r / Rat 2)). intros Hlt.\n      * eapply realE2_2; swap 1 5; [apply Hlt|..|auto|auto].\n        apply ratAdd_ran... apply ratMul_ran; [auto|apply ratMul_ran]...\n      * assert (H1: r / Rat 3 ∈ ℚ) by (apply ratMul_ran; nauto).\n        assert (H2: -(r / Rat 3) ∈ ℚ) by (apply ratAddInv_ran; nauto).\n        assert (H3: p ⋅ r ∈ ℚ) by (apply ratMul_ran; auto).\n        assert (H4: p ⋅ r / Rat 3 ∈ ℚ) by (apply ratMul_ran; nauto).\n        assert (H5: - Rat 1 ∈ ℚ) by nauto.\n        assert (H6: - Rat 1 + p ∈ ℚ) by (apply ratAdd_ran; auto).\n        rewrite ratAdd_comm; [|auto..]. unfold s, p'.\n        rewrite (ratAdd_comm p Hp (-Rat 1)),\n          (ratMul_assoc (-Rat 1 + p) H6 r Hr (Rat 3)⁻¹),\n          (ratMul_distr' (r / Rat 3) H1 (-Rat 1) H5 p Hp),\n          <- (ratMul_assoc (-Rat 1) H5 r Hr (Rat 3)⁻¹),\n          <- (ratMul_assoc p Hp r Hr (Rat 3)⁻¹),\n          <- (ratMul_assoc p Hp r Hr (Rat 2)⁻¹),\n          (ratMul_addInv_l (Rat 1) (rat_n 1) r), (ratMul_1_l r),\n          (ratMul_addInv_l r Hr (Rat 3)⁻¹),\n          <- (ratAdd_assoc t Ht (-(r/Rat 3)) H2 (p⋅r/Rat 3));\n          clear H5 H6; [|nauto..].\n        replace (p⋅r/Rat 2) with (p⋅r / Rat 6 + p⋅r / Rat 3). {\n          apply ratAdd_preserve_lt. apply ratAdd_ran...\n          repeat apply ratMul_ran... repeat apply ratMul_ran...\n          cut (ratPos (p⋅r / Rat 6)). intros Hp6.\n          - destruct (classic (t = r / Rat 3)).\n            + subst. rewrite ratAddInv_annih; assumption.\n            + eapply ratLt_trans; revgoals. apply Hp6.\n              apply ratLt_connected in H0 as []; [|exfalso|auto..]...\n              rewrite <- (ratAddInv_annih (r/Rat 3)); [|auto].\n              apply ratAdd_preserve_lt...\n          - apply ratMul_pos_prd; [auto|nauto|..|nauto].\n            apply ratMul_pos_prd... eapply ratLt_trans.\n            apply ratPos_sn. apply H1p. \n        } {\n          rewrite <- ratMul_distr...\n          cut ((Rat 6)⁻¹ + (Rat 3)⁻¹ = (Rat 2)⁻¹). congruence.\n          apply ratAdd_r6_r3_r2.\n        }\nQed.\n\nTheorem realPosMulInv_annih : ∀x ∈ ℝ,\n  realPos x → (x ⋅₊ x⁻¹⁺)%r = Real 1.\nProof with neauto.\n  intros x Hx Hposx.\n  assert (Hx': (x⁻¹⁺)%r ∈ ℝ) by (apply realPosMulInv_ran; auto).\n  ext p Hp.\n  - apply realNonNegMulE in Hp as [Hp0|Hp]...\n    + apply SepE in Hp0 as [Hpq Hp0]. apply SepI...\n      eapply ratLt_trans... apply ratPos_sn.\n    + destruct Hp as [q [Hqq [r [Hrq [[Hq Hr] [[Hnnq Hnnr] Heq]]]]]].\n      subst p. apply SepI. apply ratMul_ran...\n      destruct Hnnq; destruct Hnnr; revgoals; subst.\n      * rewrite ratMul_0_l... apply ratPos_sn.\n      * rewrite ratMul_0_l... apply ratPos_sn.\n      * rewrite ratMul_0_r_r... apply ratPos_sn.\n      * apply SepE in Hr as [_ [s [Hsq [Hsx Hlt]]]].\n        assert (Hqs: q <𝐪 s) by (eapply realE2_1; revgoals; eauto).\n        assert (Hps: ratPos s) by (eapply ratLt_trans; revgoals; eauto).\n        rewrite ratMul_comm in Hlt... apply ratLt_mulInv' in Hlt...\n        apply ratLt_mulInv'... eapply ratLt_trans...\n  - apply SepE in Hp as [Hpq Hp1].\n    destruct (classic (p = Rat 0)). {\n      apply realPos_rat0 in Hposx...\n      subst p. rewrite <- (ratMul_0_l (Rat 0))...\n      apply realNonNegMulI1; auto; [|right..]...\n      pose proof (realE1 _ Hx) as [q [Hqq Hqx]].\n      apply SepI... exists q. repeat split... rewrite ratMul_0_l...\n    }\n    apply ratLt_connected in H as [Hnp|Hpp]... {\n      eapply realNonNegMulI0...\n    }\n    assert (Hpq': p ∈ ℚ'). { apply nzRatI0... apply rat_neq_0... }\n    assert (Hrpq: p⁻¹ ∈ ℚ). { apply nzRatE1. apply ratMulInv_ran... }\n    assert (Hprp: ratPos p⁻¹) by (apply ratPos_mulInv; auto).\n    apply ratLt_mulInv in Hp1... rewrite ratMulInv_1 in Hp1.\n    pose proof (ex5_19' _ Hx _ Hrpq Hposx Hp1) as [q [Hqq [Hposq [Hqx Hs]]]].\n    pose proof (realE3 _ Hx _ Hqx) as [r [Hrq [Hrx Hqr]]].\n    assert (Hposr: ratPos r) by (eapply ratLt_trans; eauto).\n    assert (Hrq': r ∈ ℚ'). { apply nzRatI0... apply rat_neq_0... }\n    assert (Hrrq: r⁻¹ ∈ ℚ). { apply nzRatE1. apply ratMulInv_ran... }\n    assert (Hsq: q / p ∈ ℚ) by (apply ratMul_ran; auto).\n    assert (Htq: p / r ∈ ℚ) by (apply ratMul_ran; auto).\n    assert (Hpt: ratPos (p / r)). {\n      apply ratMul_pos_prd... apply ratPos_mulInv...\n    }\n    rewrite <- (ratMul_1_l p), <- (ratMulInv_annih r),\n      ratMul_assoc, (ratMul_comm (r⁻¹))...\n    apply realNonNegMulI1; auto; revgoals; [left|left|]...\n    apply SepI. apply ratMul_ran... exists (q / p). repeat split...\n    rewrite ratMul_comm... rewrite (ratMul_comm (p / r))...\n    apply ratLt_mulInv'... rewrite ratMulInv_quot...\n    apply ratMul_preserve_lt...\nQed.\n\nLemma realPos_posMulInv : ∀x ∈ ℝ, realPos x → realPos (x⁻¹⁺)%r.\nProof with neauto.\n  intros x Hx Hpx. apply realPos_rat0 in Hpx as H0x...\n  apply binRelI... apply realPosMulInv_ran...\n  pose proof (realE1 _ Hx) as [q [Hqq Hqx]]. \n  assert (Hposq: ratPos q) by (eapply realE2_1; neauto). split.\n  - intros p Hp. apply SepE in Hp as [Hpq Hnp].\n    apply SepI... exists q. repeat split... eapply ratLt_trans.\n    rewrite ratMul_comm... apply ratMul_neg_prd... apply ratPos_sn.\n  - pose proof (rat_archimedean _ Hqq) as [r [Hrq Hqr]].\n    assert (Hposr: ratPos r) by (eapply ratLt_trans; eauto).\n    assert (Hr': r ∈ ℚ'). { apply nzRatI0... apply rat_neq_0... }\n    assert (Hrr: r⁻¹ ∈ ℚ). { apply nzRatE1. apply ratMulInv_ran... }\n    assert (Hposrr: ratPos r⁻¹) by (apply ratPos_mulInv; auto).\n    cut (r⁻¹ ∈ (x⁻¹⁺)%r). intros Hrqrx.\n    intros H. rewrite <- H in Hrqrx.\n    apply SepE in Hrqrx as [_ Hnrr].\n    eapply ratLt_irrefl. eapply ratLt_trans...\n    apply SepI... exists q. repeat split... rewrite ratMul_comm...\n    apply ratLt_mulInv'... rewrite ratMulInv_double...\nQed.\n\nClose Scope Rat_scope.\nOpen Scope Real_scope.\n\nLemma realPosMulInv_double : ∀x ∈ ℝ, realPos x → x⁻¹⁺⁻¹⁺ = x.\nProof with auto.\n  intros x Hx Hpx.\n  assert (Hr: x⁻¹⁺ ∈ ℝ) by (apply realPosMulInv_ran; auto).\n  assert (Hpr: realPos x⁻¹⁺) by (apply realPos_posMulInv; auto).\n  assert (Hrr: x⁻¹⁺⁻¹⁺ ∈ ℝ) by (apply realPosMulInv_ran; auto).\n  assert (Hprr: realPos x⁻¹⁺⁻¹⁺) by (apply realPos_posMulInv; auto).\n  rewrite <- (realNonNegMul_1_r (x⁻¹⁺⁻¹⁺)), <- (realPosMulInv_annih x),\n    realNonNegMul_comm, realNonNegMul_assoc, realPosMulInv_annih,\n    realNonNegMul_1_r; try left...\n  apply realNonNegMul_ran; try left...\n  apply realNonNegMul_pos_prd...\nQed.\n", "meta": {"author": "choukh", "repo": "Set-Theory", "sha": "5677d0d9cc3814adfb9bc1286a826f9d620fcc2e", "save_path": "github-repos/coq/choukh-Set-Theory", "path": "github-repos/coq/choukh-Set-Theory/Set-Theory-5677d0d9cc3814adfb9bc1286a826f9d620fcc2e/Elements/EST5_6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985636, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.6772432814882127}}
{"text": "Require Import Lia.\nRequire Import ZArith.\nRequire Import PLF.LibTactics.\nRequire Import CoqTactical.SimplMatch.\nRequire Import CoqRefinements.Tactics.\nRequire Import CoqRefinements.Types.\nRequire Import Program.Utils. (* for 'dec' *)\n\nOpen Scope Z_scope.\n\n\n\n\n\n\n(* Refined Int Functions *)\nDefinition add {P Q} (m:Int P)  (n:Int Q) :=\nexist _ (` m + ` n) eq_refl\n: Int (fun v => v = ` m + ` n).\n\nDefinition sub {P Q} (m:Int P) (n:Int Q) :=\n  exist _ (` m - ` n) eq_refl\n: Int (fun v => v = ` m - ` n).\n\n\nDefinition mul {P Q} (m:Int P) (n:Int Q) :=\n  exist _ (` m * ` n) eq_refl\n:Int (fun v => v = ` m * ` n).\n\n\nDefinition eq_p {P Q} (m:Int P) (n:Int Q) :=\n  (Z.eqb (` m) (` n)):bool.\n\nDefinition neq_p {P Q} (m:Int P) (n:Int Q) :=\n  negb (Z.eqb (` m) (` n)):bool.\n\nDefinition leq_p {P Q} (m:Int P) (n:Int Q) :=\n Z.leb (` m) (` n).\n\nDefinition geq_p {P Q} (m:Int P) (n:Int Q) :=\n Z.geb (` m) (` n).\n\nDefinition lt_p {P Q} (m:Int P) (n:Int Q) :=\n Z.ltb (` m) (` n).\n\nDefinition gt_p {P Q} (m:Int P) (n:Int Q) :=\nZ.gtb (` m) (` n).\n\nDefinition eq {P Q} (m:Int P) (n:Int Q) :=\n  exist _ (eq_p m n) eq_refl\n:@Bool ( eq_p m n).\n\nCheck Z.eqb.\n\nDefinition neq {P Q} (m:Int P) (n:Int Q) :=\n  exist _ (neq_p m n) eq_refl\n:@Bool (neq_p m n).\n\nDefinition leq {P Q} (m:Int P) (n:Int Q) :=\n  exist _ (leq_p m n) eq_refl\n:@Bool ( leq_p m n).\n\nDefinition geq {P Q} (m:Int P) (n:Int Q) :=\nexist _ (geq_p m n) eq_refl\n:@Bool ( geq_p m n).\n\nDefinition lt {P Q} (m:Int P) (n:Int Q) :=\n  exist _ (lt_p m n) eq_refl\n:@Bool ( lt_p m n).\n\nDefinition gt {P Q} (m:Int P) (n:Int Q) :=\n  exist _ (gt_p m n) eq_refl\n:@Bool ( gt_p m n).\n\n\n(* TESTS *)\nDefinition ge5_ge0 (n:{v:Z| v>=5}) : {v:Z| v>=0}. upcast n. Defined.\n\nDefinition add_nats_nat (m n:Nat):Nat.\ninfer (add m n).\nDefined.\n\n\nNotation refl := (fun v => v = v).\n\nNotation rInt := (Int refl).\nDefinition max (x y: rInt) :=\n  match dec(` x >? ` y) with\n  | left e => ltac:(infer x)\n  | right e => ltac: (infer y)\n  end  : {v:Z | v>= ` x /\\ v >= ` y}.\n\nDefinition abs (x:rInt) :=\n  match dec (` x >=? 0) with\n  | left e => ltac:(infer x)\n  | right e => ltac:(infer (sub (triv 0) x))\n  end\n: {v:Z | v>= 0 /\\  v >= (` x) }.\nRequire Import ssreflect.\n\nDefinition sub_5_4_nat: {v:Z | v<>0}. upcast (sub (triv 5) (triv 4)). Defined.\n\nDefinition mul_nats_nat (m n:Nat):Nat.\ninfer (mul m n).\nDefined.\n\nDefinition gem1_ltm1_nat (m:{v:Z| v>= -1}) (H: ` m > -1): Nat. exists (`m). lia. Defined.\n\n", "meta": {"author": "lykmast", "repo": "coq-refinements", "sha": "0ec3cbfdcf9d26c14b2781d632d33d256938c765", "save_path": "github-repos/coq/lykmast-coq-refinements", "path": "github-repos/coq/lykmast-coq-refinements/coq-refinements-0ec3cbfdcf9d26c14b2781d632d33d256938c765/theories/Prelude.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6772097332335127}}
{"text": "Require Export TopologicalSpaces.\nRequire Export Nets.\nRequire Export FilterLimits.\nRequire Export Continuity.\n\nDefinition compact (X:TopologicalSpace) :=\n  forall C:Family (point_set X),\n    (forall U:Ensemble (point_set X), In C U -> open U) ->\n    FamilyUnion C = Full_set ->\n    exists C':Family (point_set X),\n      Finite _ C' /\\ Included C' C /\\\n      FamilyUnion C' = Full_set.\n\nLemma compactness_on_indexed_covers:\n  forall (X:TopologicalSpace) (A:Type) (C:IndexedFamily A (point_set X)),\n    compact X ->\n    (forall a:A, open (C a)) -> IndexedUnion C = Full_set ->\n  exists A':Ensemble A, Finite _ A' /\\\n    IndexedUnion (fun a':{a':A | In A' a'} => C (proj1_sig a')) = Full_set.\nProof.\nintros.\npose (cover := ImageFamily C).\ndestruct (H cover) as [subcover].\nintros.\ndestruct H2.\nrewrite H3; apply H0.\nunfold cover; rewrite <- indexed_to_family_union; trivial.\ndestruct H2 as [? []].\ndestruct (finite_choice _ _\n  (fun (U:{U:Ensemble (point_set X) | In subcover U}) (a:A) =>\n      proj1_sig U = C a)) as [choice_fun].\napply Finite_ens_type; trivial.\ndestruct x as [U].\nsimpl.\napply H3 in i.\ndestruct i.\nexists x; trivial.\n\nexists (Im Full_set choice_fun).\nsplit.\napply FiniteT_img.\napply Finite_ens_type; trivial.\nintros; apply classic.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nrewrite <- H4 in H6.\ndestruct H6.\nassert (In (Im Full_set choice_fun) (choice_fun (exist _ S H6))).\nexists (exist _ S H6).\nconstructor.\ntrivial.\nexists (exist _ (choice_fun (exist _ S H6)) H8).\nsimpl.\nrewrite <- H5.\nsimpl.\ntrivial.\nQed.\n\nLemma compact_finite_nonempty_closed_intersection:\n  forall X:TopologicalSpace, compact X ->\n  forall F:Family (point_set X),\n    (forall G:Ensemble (point_set X), In F G -> closed G) ->\n    (forall F':Family (point_set X), Finite _ F' -> Included F' F ->\n     Inhabited (FamilyIntersection F')) ->\n    Inhabited (FamilyIntersection F).\nProof.\nintros.\napply NNPP; red; intro.\npose (C := [ U:Ensemble (point_set X) | In F (Complement U) ]).\nrefine (let H3:=(H C _ _) in _).\nintros.\ndestruct H3.\napply H0 in H3.\napply closed_complement_open; trivial.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\napply NNPP; red; intro.\ncontradiction H2.\nexists x.\nconstructor.\nintros.\napply NNPP; red; intro.\ncontradiction H4.\nexists (Complement S).\nconstructor.\nrewrite Complement_Complement; trivial.\nexact H6.\n\ndestruct H3 as [C' [? [? ?]]].\npose (F' := [G : Ensemble (point_set X) | In C' (Complement G)]).\nrefine (let H6 := (H1 F' _ _) in _).\nassert (F' = Im C' Complement).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H6.\nexists (Complement x); trivial.\nsymmetry; apply Complement_Complement.\ndestruct H6.\nconstructor.\nrewrite H7; rewrite Complement_Complement; trivial.\nrewrite H6; apply finite_image.\nassumption.\n\nred; intros.\ndestruct H6.\napply H4 in H6.\ndestruct H6.\nrewrite Complement_Complement in H6; trivial.\n\ndestruct H6 as [x0].\ndestruct H6.\nassert (In (FamilyUnion C') x).\nrewrite H5; constructor.\ndestruct H7.\nassert (In (Complement S) x).\napply H6.\nconstructor.\nrewrite Complement_Complement; trivial.\ncontradiction H9.\nQed.\n\nLemma finite_nonempty_closed_intersection_impl_compact:\n  forall X:TopologicalSpace,\n  (forall F:Family (point_set X),\n    (forall G:Ensemble (point_set X), In F G -> closed G) ->\n    (forall F':Family (point_set X), Finite _ F' -> Included F' F ->\n     Inhabited (FamilyIntersection F')) ->\n    Inhabited (FamilyIntersection F)) ->\n  compact X.\nProof.\nintros.\nred; intros.\napply NNPP; red; intro.\npose (F := [ G:Ensemble (point_set X) | In C (Complement G) ]).\nrefine (let H3 := (H F _ _) in _).\nintros.\ndestruct H3.\napply H0; trivial.\nintros.\napply NNPP; red; intro.\ncontradiction H2.\nexists [ U:Ensemble (point_set X) | In F' (Complement U) ].\nrepeat split.\nassert ([U:Ensemble (point_set X) | In F' (Complement U)] =\n  Im F' Complement).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H6.\nexists (Complement x); trivial.\nsymmetry; apply Complement_Complement.\nconstructor.\ndestruct H6.\nrewrite H7; rewrite Complement_Complement; trivial.\nrewrite H6; apply finite_image; trivial.\n\nred; intros.\ndestruct H6.\napply H4 in H6.\ndestruct H6.\nrewrite Complement_Complement in H6; trivial.\n\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\napply NNPP; red; intro.\ncontradiction H5.\nexists x.\nconstructor.\nintros.\napply NNPP; red; intro.\ncontradiction H7.\nexists (Complement S).\nconstructor.\nrewrite Complement_Complement; trivial.\nexact H9.\n\ndestruct H3.\nassert (In (FamilyUnion C) x).\nrewrite H1; constructor.\ndestruct H4.\nassert (In (Complement S) x).\ndestruct H3.\napply H3.\nconstructor.\nrewrite Complement_Complement; trivial.\ncontradiction H6.\nQed.\n\nLemma compact_impl_filter_cluster_point:\n  forall X:TopologicalSpace, compact X ->\n    forall F:Filter (point_set X), exists x0:point_set X,\n    filter_cluster_point F x0.\nProof.\nintros.\npose proof (compact_finite_nonempty_closed_intersection\n  _ H [ G:Ensemble (point_set X) | In (filter_family F) G /\\\n                                   closed G ]) as [x0].\nintros.\ndestruct H0 as [[]]; trivial.\nintros.\nassert (closed (FamilyIntersection F')).\napply closed_family_intersection.\nintros.\napply H1 in H2.\ndestruct H2 as [[]]; trivial.\nassert (In (filter_family F) (FamilyIntersection F')).\nclear H2.\ninduction H0.\nrewrite empty_family_intersection.\napply filter_full.\nreplace (FamilyIntersection (Add A x)) with\n  (Intersection (FamilyIntersection A) x).\napply filter_intersection.\napply IHFinite.\nauto with sets.\nassert (In (Add A x) x) by (right; constructor).\napply H1 in H3.\ndestruct H3 as [[]]; trivial.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H3.\nconstructor.\nintros.\ndestruct H5.\ndestruct H3.\napply H3; trivial.\ndestruct H5; trivial.\ndestruct H3.\nconstructor.\nconstructor; intros.\napply H3.\nauto with sets.\napply H3.\nauto with sets.\napply NNPP; intro.\ncontradiction (filter_empty _ F).\nreplace (@Empty_set (point_set X)) with (FamilyIntersection F'); trivial.\napply Extensionality_Ensembles; split; red; intros.\ncontradiction H4.\nexists x; trivial.\ndestruct H5.\n\nexists x0.\nred; intros.\ndestruct H0.\napply H0.\nconstructor.\nsplit.\napply filter_upward_closed with S; trivial.\napply closure_inflationary.\napply closure_closed.\nQed.\n\nLemma filter_cluster_point_impl_compact:\n  forall X:TopologicalSpace,\n    (forall F:Filter (point_set X), exists x0:point_set X,\n      filter_cluster_point F x0) -> compact X.\nProof.\nintros.\napply finite_nonempty_closed_intersection_impl_compact.\nintros.\nlet H:=fresh in\n  refine (let H:=_ in let filt := Build_Filter_from_subbasis F H in _).\nintros.\nrewrite indexed_to_family_intersection.\napply H1.\napply FiniteT_img; trivial.\nintros; apply classic.\nred; intros.\ndestruct H4.\nrewrite H5; apply H3.\nassert (filter_subbasis filt F) by apply filter_from_subbasis_subbasis.\ndestruct (H filt) as [x0].\nexists x0.\nconstructor; intros.\nassert (closed S) by (apply H0; trivial).\nassert (In (filter_family filt) S).\napply (filter_subbasis_elements _ _ H3); trivial.\npose proof (H4 _ H7).\nrewrite closure_fixes_closed in H8; trivial.\nQed.\n\nLemma ultrafilter_limit_impl_compact:\n  forall X:TopologicalSpace,\n    (forall U:Filter (point_set X), ultrafilter U ->\n      exists x0:point_set X, filter_limit U x0) -> compact X.\nProof.\nintros.\napply filter_cluster_point_impl_compact.\nintros.\ndestruct (ultrafilter_extension F) as [U].\ndestruct H0.\ndestruct (H _ H1) as [x0].\nexists x0.\nred; intros.\napply filter_limit_is_cluster_point in H2.\napply H0 in H3.\napply H2; trivial.\nQed.\n\nLemma compact_impl_net_cluster_point:\n  forall X:TopologicalSpace, compact X ->\n    forall (I:DirectedSet) (x:Net I X), inhabited (DS_set I) ->\n    exists x0:point_set X, net_cluster_point x x0.\nProof.\nRequire Import FiltersAndNets.\nintros.\ndestruct (compact_impl_filter_cluster_point\n  _ H (tail_filter x H0)) as [x0].\nexists x0.\napply tail_filter_cluster_point_impl_net_cluster_point with H0.\napply H1.\nQed.\n\nLemma net_cluster_point_impl_compact: forall X:TopologicalSpace,\n  (forall (I:DirectedSet) (x:Net I X), inhabited (DS_set I) ->\n    exists x0:point_set X, net_cluster_point x x0) ->\n  compact X.\nProof.\nintros.\napply filter_cluster_point_impl_compact.\nintros.\ndestruct (H _ (filter_to_net _ F)) as [x0].\ncut (inhabited (point_set X)).\nintro.\ndestruct H0 as [x].\nexists.\nsimpl.\napply Build_filter_to_net_DS_set with Full_set x.\napply filter_full.\nconstructor.\napply NNPP; intro.\ncontradiction (filter_empty _ F).\nreplace (@Empty_set (point_set X)) with (@Full_set (point_set X)).\napply filter_full.\napply Extensionality_Ensembles; split; red; intros.\ncontradiction H0.\nexists; exact x.\ndestruct H1.\n\nexists x0.\napply filter_to_net_cluster_point_impl_filter_cluster_point.\ntrivial.\nQed.\n\nRequire Export SeparatednessAxioms.\nRequire Export SubspaceTopology.\n\nLemma compact_closed: forall (X:TopologicalSpace)\n  (S:Ensemble (point_set X)), Hausdorff X ->\n  compact (SubspaceTopology S) -> closed S.\nProof.\nintros.\ndestruct (classic (Inhabited S)).\nassert (closure S = S).\napply Extensionality_Ensembles; split.\nred; intros.\ndestruct (net_limits_determine_topology _ _ H2) as [I0 [y []]].\npose (yS (i:DS_set I0) := exist (fun x:point_set X => In S x) (y i) (H3 i)).\nassert (inhabited (point_set (SubspaceTopology S))).\ndestruct H1.\nexists.\nexists x0; trivial.\nassert (inhabited (DS_set I0)) as HinhI0.\nred in H4.\ndestruct (H4 Full_set) as [i0]; auto with topology.\nconstructor.\npose proof (compact_impl_net_cluster_point\n  (SubspaceTopology S) H0 _ yS HinhI0).\ndestruct H6 as [[x0]].\napply net_cluster_point_impl_subnet_converges in H6.\ndestruct H6 as [J [y' []]].\ndestruct H6.\nassert (net_limit (fun j:DS_set J => y (h j)) x0).\napply continuous_func_preserves_net_limits with\n  (f:=subspace_inc S) (Y:=X) in H7.\nsimpl in H7.\nassumption.\napply continuous_func_continuous_everywhere.\napply subspace_inc_continuous.\nassert (net_limit (fun j:DS_set J => y (h j)) x).\napply subnet_limit with I0 y; trivial.\nconstructor; trivial.\nassert (x = x0).\nexact (Hausdorff_impl_net_limit_unique _ H _ _ H10 H9).\nrewrite H11; trivial.\ndestruct (H4 Full_set).\napply open_full.\nconstructor.\nexists; exact x1.\ndestruct H1.\n\napply closure_inflationary.\nrewrite <- H2; apply closure_closed.\n\nred.\nassert (Complement S = Full_set).\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nred; intro.\ncontradiction H1; exists x; trivial.\nrewrite H2; apply open_full.\nQed.\n\nLemma closed_compact: forall (X:TopologicalSpace) (S:Ensemble (point_set X)),\n  compact X -> closed S -> compact (SubspaceTopology S).\nProof.\nintros.\napply net_cluster_point_impl_compact.\nintros.\ndestruct (compact_impl_net_cluster_point _ H\n  _ (fun i:DS_set I => subspace_inc _ (x i))) as [x0].\ntrivial.\nassert (In S x0).\nrewrite <- (closure_fixes_closed S); trivial.\napply net_cluster_point_in_closure with\n  (2:=H2).\ndestruct H1 as [i0].\nexists i0.\nintros.\ndestruct (x j).\nsimpl.\ntrivial.\nexists (exist _ x0 H3).\nred; intros.\nred; intros.\ndestruct (subspace_topology_topology _ _ _ H4) as [V []].\nrewrite H7 in H5.\ndestruct H5.\nsimpl in H5.\ndestruct (H2 V H6 H5 i) as [j []]; trivial.\nexists j; split; trivial.\nrewrite H7.\nconstructor.\ntrivial.\nQed.\n\nLemma compact_image: forall {X Y:TopologicalSpace}\n  (f:point_set X->point_set Y),\n  compact X -> continuous f -> surjective f -> compact Y.\nProof.\nintros.\nred; intros.\npose (B := fun U:{U:Ensemble (point_set Y) | In C U} =>\n           inverse_image f (proj1_sig U)).\ndestruct (compactness_on_indexed_covers _ _ B H) as [subcover].\ndestruct a as [U].\nunfold B; simpl.\napply H0.\napply H2; trivial.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nassert (In (FamilyUnion C) (f x)).\nrewrite H3; constructor.\ninversion_clear H5 as [V].\nexists (exist _ V H6).\nunfold B; simpl.\nconstructor; trivial.\ndestruct H4.\n\nexists (Im subcover (@proj1_sig _ (fun U:Ensemble (point_set Y) => In C U))).\nrepeat split.\napply finite_image; trivial.\nred; intros V ?.\ndestruct H6 as [[U]].\nsimpl in H7.\ncongruence.\napply Extensionality_Ensembles; split; red; intros y ?.\nconstructor.\ndestruct (H1 y) as [x].\nassert (In (IndexedUnion\n  (fun a':{a' | In subcover a'} => B (proj1_sig a'))) x).\nrewrite H5; constructor.\ndestruct H8 as [[[U]]].\nexists U.\nsimpl in H8.\nexists (exist _ U i); trivial.\nunfold B in H8; simpl in H8.\ndestruct H8.\ncongruence.\nQed.\n\nLemma compact_Hausdorff_impl_normal_sep: forall X:TopologicalSpace,\n  compact X -> Hausdorff X -> normal_sep X.\nProof.\nintros.\nassert (T3_sep X).\nRequire Import ClassicalChoice.\ndestruct (choice (fun (xy:{xy:point_set X * point_set X |\n                  let (x,y):=xy in x <> y})\n  (UV:Ensemble (point_set X) * Ensemble (point_set X)) =>\n  match xy with | exist (x,y) i =>\n    let (U,V):=UV in\n  open U /\\ open V /\\ In U x /\\ In V y /\\ Intersection U V = Empty_set\n  end)) as\n[choice_fun].\ndestruct x as [[x y] i].\ndestruct (H0 _ _ i) as [U [V]].\nexists (U, V); trivial.\n\npose (choice_fun_U := fun (x y:point_set X)\n  (Hineq:x<>y) => fst (choice_fun (exist _ (x,y) Hineq))).\npose (choice_fun_V := fun (x y:point_set X)\n  (Hineq:x<>y) => snd (choice_fun (exist _ (x,y) Hineq))).\nassert (forall (x y:point_set X) (Hineq:x<>y),\n  open (choice_fun_U x y Hineq) /\\\n  open (choice_fun_V x y Hineq) /\\\n  In (choice_fun_U x y Hineq) x /\\\n  In (choice_fun_V x y Hineq) y /\\\n  Intersection (choice_fun_U x y Hineq) (choice_fun_V x y Hineq) = Empty_set).\nintros.\nunfold choice_fun_U; unfold choice_fun_V.\npose proof (H1 (exist _ (x,y) Hineq)).\ndestruct (choice_fun (exist _ (x,y) Hineq)).\nexact H2.\nclearbody choice_fun_U choice_fun_V; clear choice_fun H1.\n\nsplit.\napply Hausdorff_impl_T1_sep; trivial.\nintros.\npose proof (closed_compact _ _ H H1).\nassert (forall y:point_set X, In F y -> x <> y).\nintros.\ncongruence.\npose (cover := fun (y:point_set (SubspaceTopology F)) =>\n  let (y,i):=y in inverse_image (subspace_inc F)\n                     (choice_fun_V x y (H5 y i))).\ndestruct (compactness_on_indexed_covers _ _ cover H4) as [subcover].\ndestruct a as [y i].\napply subspace_inc_continuous.\napply H2.\napply Extensionality_Ensembles; split; red; intros y ?.\nconstructor.\nexists y.\ndestruct y as [y i].\nsimpl.\nconstructor.\nsimpl.\napply H2.\ndestruct H6.\n\nexists (IndexedIntersection\n  (fun y:{y:point_set (SubspaceTopology F) | In subcover y} =>\n    let (y,_):=y in let (y,i):=y in choice_fun_U x y (H5 y i))).\nexists (IndexedUnion\n  (fun y:{y:point_set (SubspaceTopology F) | In subcover y} =>\n    let (y,_):=y in let (y,i):=y in choice_fun_V x y (H5 y i))).\nrepeat split.\napply open_finite_indexed_intersection.\napply Finite_ens_type; trivial.\ndestruct a as [[y]].\napply H2.\napply open_indexed_union.\ndestruct a as [[y]].\napply H2.\ndestruct a as [[y]].\napply H2.\nred; intros y ?.\nassert (In (IndexedUnion\n  (fun y:{y:point_set (SubspaceTopology F) | In subcover y} =>\n    cover (proj1_sig y))) (exist _ y H8)).\nrewrite H7; constructor.\nremember (exist (In F) y H8) as ysig.\ndestruct H9 as [[y']].\nrewrite Heqysig in H9; clear x0 Heqysig.\nsimpl in H9.\ndestruct y' as [y'].\nsimpl in H9.\ndestruct H9.\nsimpl in H9.\nexists (exist _ (exist _ y' i0) i).\ntrivial.\n\napply Extensionality_Ensembles; split; auto with sets; red; intros y ?.\ndestruct H8.\ndestruct H8.\ndestruct H9.\npose proof (H8 a).\ndestruct a as [[y]].\nreplace (@Empty_set (point_set X)) with\n  (Intersection (choice_fun_U x y (H5 y i))\n                (choice_fun_V x y (H5 y i))).\nconstructor; trivial.\napply H2.\n\ndestruct (choice (fun (xF:{p:point_set X * Ensemble (point_set X) |\n                        let (x,F):=p in closed F /\\ ~ In F x})\n  (UV:Ensemble (point_set X) * Ensemble (point_set X)) =>\n  let (p,i):=xF in let (x,F):=p in\n  let (U,V):=UV in\n  open U /\\ open V /\\ In U x /\\ Included F V /\\\n  Intersection U V = Empty_set)) as [choice_fun].\ndestruct x as [[x F] []].\ndestruct H1.\ndestruct (H4 x F H2 H3) as [U [V]].\nexists (U,V); trivial.\n\npose (choice_fun_U := fun (x:point_set X) (F:Ensemble (point_set X))\n  (HC:closed F) (Hni:~ In F x) =>\n  fst (choice_fun (exist _ (x,F) (conj HC Hni)))).\npose (choice_fun_V := fun (x:point_set X) (F:Ensemble (point_set X))\n  (HC:closed F) (Hni:~ In F x) =>\n  snd (choice_fun (exist _ (x,F) (conj HC Hni)))).\nassert (forall (x:point_set X) (F:Ensemble (point_set X))\n  (HC:closed F) (Hni:~ In F x),\n  open (choice_fun_U x F HC Hni) /\\\n  open (choice_fun_V x F HC Hni) /\\\n  In (choice_fun_U x F HC Hni) x /\\\n  Included F (choice_fun_V x F HC Hni) /\\\n  Intersection (choice_fun_U x F HC Hni) (choice_fun_V x F HC Hni) =\n     Empty_set).\nintros.\npose proof (H2 (exist _ (x,F) (conj HC Hni))).\nunfold choice_fun_U; unfold choice_fun_V;\n  destruct (choice_fun (exist _ (x,F) (conj HC Hni))); trivial.\nclearbody choice_fun_U choice_fun_V; clear choice_fun H2.\nsplit.\napply H1.\nintros.\npose proof (closed_compact _ _ H H2).\nassert (forall x:point_set X, In F x -> ~ In G x).\nintros.\nintro.\nabsurd (In Empty_set x).\nred; destruct 1.\nrewrite <- H5; split; trivial.\n\npose (cover := fun x:point_set (SubspaceTopology F) =>\n  let (x,i):=x in inverse_image (subspace_inc F)\n                   (choice_fun_U x G H4 (H7 x i))).\ndestruct (compactness_on_indexed_covers _ _ cover H6) as [subcover].\ndestruct a as [x i].\napply subspace_inc_continuous.\napply H3.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nexists x.\ndestruct x.\nsimpl cover.\nconstructor.\nsimpl.\napply H3.\ndestruct H8.\n\nexists (IndexedUnion\n  (fun x:{x:point_set (SubspaceTopology F) | In subcover x} =>\n     let (x,i):=proj1_sig x in choice_fun_U x G H4 (H7 x i))).\nexists (IndexedIntersection\n  (fun x:{x:point_set (SubspaceTopology F) | In subcover x} =>\n     let (x,i):=proj1_sig x in choice_fun_V x G H4 (H7 x i))).\nrepeat split.\napply open_indexed_union.\ndestruct a as [[x]].\nsimpl.\napply H3.\napply open_finite_indexed_intersection.\napply Finite_ens_type; trivial.\ndestruct a as [[x]].\nsimpl.\napply H3.\nintros x ?.\nassert (In (@Full_set (point_set (SubspaceTopology F))) (exist _ x H10))\n  by constructor.\nrewrite <- H9 in H11.\nremember (exist _ x H10) as xsig.\ndestruct H11.\ndestruct a as [x'].\ndestruct x' as [x'].\nrewrite Heqxsig in H11; clear x0 Heqxsig.\nsimpl in H11.\ndestruct H11.\nsimpl in H11.\nexists (exist _ (exist _ x' i0) i).\nsimpl.\ntrivial.\ndestruct a as [x'].\nsimpl.\ndestruct x' as [x'].\nassert (Included G (choice_fun_V x' G H4 (H7 x' i0))) by apply H3.\nauto.\n\napply Extensionality_Ensembles; split; auto with sets; red; intros.\ndestruct H10.\ndestruct H10.\ndestruct H11.\npose proof (H11 a).\ndestruct a as [[x']].\nsimpl in H12.\nsimpl in H10.\nreplace (@Empty_set (point_set X)) with (Intersection\n  (choice_fun_U x' G H4 (H7 x' i))\n  (choice_fun_V x' G H4 (H7 x' i))).\nconstructor; trivial.\napply H3.\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/Compactness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6772097252310885}}
{"text": "(* Copyright 2012-2015 by Adam Petcher.\t\t\t\t*\n * Use of this source code is governed by the license described\t*\n * in the LICENSE file at the root of the source tree.\t\t*)\n(* Definitions and theory of natural numbers that is useful in cryptographi proofs. *)\n\nSet Implicit Arguments.\n\nRequire Export Arith.\nRequire Export Omega.\nRequire Export Arith.Div2.\nRequire Export Coq.Numbers.Natural.Peano.NPeano. \nRequire Import Coq.NArith.BinNat.\n\nLemma mult_same_r : forall n1 n2 n3,\n  n3 > 0 ->\n  n1 * n3 = n2 * n3 ->\n  n1 = n2.\n  \n  induction n1; destruct n2; intuition; simpl in *.\n  remember (n2 * n3) as x.\n  omega.\n  remember (n1 * n3) as x.\n  omega.\n  \n  f_equal.\n  eapply IHn1; eauto.\n  \n  eapply plus_reg_l. eauto.\nQed.\n\nLemma mult_same_l : forall n3 n1 n2,\n  n3 > 0 ->\n  n3 * n1 = n3 * n2 ->\n  n1 = n2.\n  \n  intuition.\n  eapply mult_same_r; eauto.\n  rewrite mult_comm.\n  rewrite (mult_comm n2 n3).\n  trivial.\nQed.\n\nLemma mult_gt_0 : forall n1 n2,\n  n1 > 0 ->\n  n2 > 0 ->\n  n1 * n2 > 0.\n  destruct n1; intuition; simpl in *.\n  remember (n1 * n2) as x.\n  omega.\nQed.\n\nLemma minus_eq_compat : forall n1 n2 n3 n4,\n  n1 = n2 ->\n  n3 = n4 ->\n  n1 - n3 = n2 - n4.\n  \n  intuition.\nQed.\n\nLemma plus_eq_compat : forall n1 n2 n3 n4,\n  n1 = n2 ->\n  n3 = n4 ->\n  n1 + n3 = n2 + n4.\n  \n  intuition.\nQed.\n\nLemma minus_diag_eq : forall n1 n2,\n  n1 = n2 ->\n  n1 - n2 = 0.\n  \n  intuition.\nQed.\n\nLemma le_eq : forall n1 n2,\n  n1 = n2 ->\n  n1 <= n2.\n  \n  intuition.\nQed.\n\nLemma minus_add_assoc : forall n1 n2 n3,\n  (n3 <= n2)%nat ->\n  (n1 + (n2 - n3) = n1 + n2 - n3)%nat.\n  \n  intuition.\nQed.\n\n\n\n\nClass nz (a : nat) := {\n  agz : a > 0\n}.\n\nInstance nz_nat : forall (n : nat), nz (S n).\nintuition.\neconstructor.\nomega.\nDefined.\n\nDefinition posnat := {n : nat | n > 0}.\n\nDefinition posnatToNat(p : posnat) :=\n  match p with\n    | exist _ n _ => n\n  end.\n\nInductive posnatEq : posnat -> posnat -> Prop :=\n  | posnatEq_intro : \n    forall (n1 n2 : nat) pf1 pf2,\n      n1 = n2 ->\n      posnatEq (exist _ n1 pf1) (exist _ n2 pf2).\n\nDefinition posnatMult(p1 p2 : posnat) : posnat :=\n    match (p1, p2) with\n      | (exist _ n1 pf1, exist _ n2 pf2) =>\n        (exist (fun n => n > 0) (n1 * n2) (mult_gt_0 pf1 pf2))\n    end.\n\nLemma posnatMult_comm : forall p1 p2,\n  (posnatEq (posnatMult p1 p2) (posnatMult p2 p1)).\n\n  intuition.\n  unfold posnatMult.\n  destruct p1; destruct p2.\n  econstructor.\n  apply mult_comm.\nQed.  \n\nCoercion posnatToNat : posnat >-> nat.\n\nLemma posnat_pos : forall (p : posnat),\n  p > 0.\n  \n  intuition.\n  destruct p.\n  unfold posnatToNat.\n  trivial.\nQed.\n\nInstance nz_posnat : forall (p : posnat),\n  nz p.\n\nintuition.\neconstructor.\neapply posnat_pos.\n\nQed.\n\nDefinition natToPosnat(n : nat)(pf : nz n) :=\n  (exist (fun x => x > 0) n agz).\n\nNotation \"'pos' x\" := (@natToPosnat x _) (at level 40).\n\nFixpoint expnat n1 n2 :=\n  match n2 with\n    | 0 => 1\n    | S n2' =>\n      n1 * (expnat n1 n2')\n  end.\n\nTheorem expnat_pos : forall x n,\n  x > 0 ->\n  expnat x n > 0.\n  \n  induction n; intuition; simpl in *.\n  remember (x * expnat x n) as y.\n  assert (y <> 0); try omega.\n  intuition; subst.\n  apply mult_is_O in H1.\n  destruct H1; omega.\n\nQed.\n\nLemma div2_le : forall n,\n  le (div2 n) n.\n  \n  intuition.\n\n  eapply PeanoNat.Nat.div2_decr.\n  omega.\n  \nQed.\n\nLemma div2_ge_double : forall n, \n  n >= (div2 n) + (div2 n).\n  \n  intuition.\n  destruct (Even.even_odd_dec n).\n  \n  rewrite (even_double n) at 1.\n  unfold double.\n  omega.\n  trivial.\n  rewrite (odd_double n) at 1.\n  unfold double.\n  omega.\n  trivial.\nQed.\n\nLocal Open Scope N_scope.\nDefinition modNat (n : nat)(p : posnat) : nat :=\n  N.to_nat ((N.of_nat n) mod (N.of_nat p)).\n\nLemma modNat_plus : forall n1 n2 p,\n    (modNat (n1 + n2) p = modNat ((modNat n1 p) + n2) p)%nat.\n  \n  unfold modNat.\n\n  intuition.\n  rewrite Nnat.Nat2N.inj_add.\n\n  rewrite <- N.add_mod_idemp_l.\n  f_equal.\n  rewrite <- (Nnat.Nat2N.id n2) at 2.\n  rewrite Nnat.Nat2N.inj_add.\n  repeat rewrite Nnat.N2Nat.id.\n  trivial.\n\n  destruct p.\n  simpl.\n  \n  destruct x;\n  simpl.\n  omega.\n  \n  Lemma Npos_nz : forall p, \n    Npos p <> N0.\n\n    destruct p; intuition; simpl in *.\n    inversion H.\n    inversion H.\n    inversion H.\n  Qed.\n\n  apply Npos_nz.\n\nQed.\n\n\nLemma modNat_arg_eq : forall (p : posnat),\n  modNat p p = O.\n\n  intuition.\n  unfold modNat.\n  rewrite N.mod_same.\n  trivial.\n  unfold N.of_nat, posnatToNat.\n  destruct p.\n  destruct x.\n  omega.\n  apply Npos_nz.\n\nQed.\n\nLemma of_nat_ge_0 : forall n,\n  0 <= N.of_nat n.\n\n  intuition.\n  unfold N.of_nat.\n  destruct n.\n  intuition.\n\n  simpl.\n  unfold N.le.\n  case_eq ((0 ?= N.pos (Pos.of_succ_nat n))); intuition;\n    try discriminate.\nQed.\n\nLemma of_posnat_gt_0 : forall (p : posnat),\n  0 < N.of_nat p.\n\n  intuition.\n  unfold N.of_nat, posnatToNat.\n  destruct p.\n  destruct x.\n  omega.\n  destruct x; intuition; simpl in *.\n  \n  case_eq (N.compare 0 1)%N; intuition.\n  inversion H.\n  inversion H.\n\n  case_eq (N.compare 0 (N.pos (Pos.succ (Pos.of_succ_nat x))))%N; intuition.\n  inversion H.\n  inversion H.\nQed.\n\nLemma modNat_lt : forall x p, (modNat x p < p)%nat.\n\n  intuition.\n  unfold modNat.\n  assert (N.of_nat x mod N.of_nat p < N.of_nat p)%N.\n  apply N.mod_bound_pos.\n  apply of_nat_ge_0.\n  apply of_posnat_gt_0.\n\n  specialize (Nnat.N2Nat.inj_compare); intuition.\n  rewrite <- (Nnat.Nat2N.id p) at 2.\n  apply nat_compare_lt.\n  rewrite <- H0.\n  apply N.compare_lt_iff.\n  trivial.\n\nQed.\n\nLemma modNat_eq : forall (n : posnat) x, (x < n -> modNat x n = x)%nat.\n  \n  intuition.\n  unfold modNat.\n  rewrite N.mod_small.\n  apply Nnat.Nat2N.id.\n  specialize (Nnat.N2Nat.inj_compare); intuition.\n  specialize (N.compare_lt_iff (N.of_nat x) (N.of_nat n)); intuition.\n  apply H2.\n  rewrite H0.\n  repeat rewrite Nnat.Nat2N.id.\n  apply nat_compare_lt.\n  trivial.\nQed.\n\nDefinition modNatAddInverse (n : nat)(p : posnat) :=\n  (p - (modNat n p))%nat.\n\nLemma modNatAddInverse_correct_gen : forall x y p,\n  modNat x p = modNat y p ->\n  modNat (x + modNatAddInverse y p) p = O.\n  \n  intuition.\n  unfold modNatAddInverse.\n  rewrite <- H.\n  rewrite modNat_plus.\n  rewrite minus_add_assoc.\n  rewrite (plus_comm).\n  rewrite <- minus_add_assoc.\n  rewrite minus_diag.\n  rewrite plus_0_r.\n  apply modNat_arg_eq.\n  \n  trivial.\n  \n  assert (modNat x p < p)%nat.\n  apply modNat_lt.\n  omega.\n  \nQed.\n\nLemma modNatAddInverse_correct : forall n p,\n    modNat (n + modNatAddInverse n p) p = O.\n\n  intuition.\n  eapply modNatAddInverse_correct_gen.\n  trivial.\n  \nQed.\n\nLemma modNat_correct : forall x (p : posnat),\n  exists k, (x = k * p + modNat x p)%nat.\n\n  intuition.\n  unfold modNat in *.\n  assert (p > 0)%nat.\n  eapply posnat_pos.\n  assert (posnatToNat p <> 0)%nat.\n  omega.\n  assert (N.of_nat p <> 0%N).\n  intuition.\n  eapply H0.\n  \n  rewrite <- Nnat.Nat2N.id.\n  rewrite <- (Nnat.Nat2N.id p).\n  f_equal.\n  trivial.\n\n  exists (N.to_nat (N.of_nat x / N.of_nat p)).\n  rewrite N.mod_eq; trivial.\n\n  rewrite <- (Nnat.Nat2N.id p) at 2.\n  rewrite <- Nnat.N2Nat.inj_mul.\n  rewrite <- Nnat.N2Nat.inj_add.\n  rewrite N.mul_comm.\n  remember (N.of_nat p * (N.of_nat x / N.of_nat p)) as z.\n  rewrite N.add_sub_assoc.\n  rewrite N.add_comm.\n  rewrite N.add_sub.\n  rewrite Nnat.Nat2N.id.\n  trivial.\n\n  subst.  \n  eapply N.mul_div_le.\n  trivial.\nQed.\n\nLemma modNat_divides : forall x p,\n  modNat x p = O ->\n  exists k, (x = k * p)%nat.\n\n  intuition.\n  destruct (modNat_correct x p).\n  rewrite H in H0.\n  econstructor.\n  rewrite plus_0_r in H0.\n  eauto.\nQed.\n\n\nLocal Open Scope nat_scope.\nLemma modNatAddInverse_sum_0 : forall x y p,\n  modNat (x + (modNatAddInverse y p)) p = O ->\n  modNat x p = modNat y p.\n  \n  intuition.\n  \n  assert (modNat x p < p).\n  eapply modNat_lt.\n  assert (modNat y p < p).\n  eapply modNat_lt.\n  \n  rewrite modNat_plus in H.\n  unfold modNatAddInverse in *.\n  rewrite minus_add_assoc in H; intuition.\n  rewrite plus_comm in H.\n  \n  apply modNat_divides in H.\n  destruct H.\n  \n  remember (modNat x p) as a.\n  remember (modNat y p) as b.\n  assert (p + a >= p).\n  omega.\n  assert (p + a < 2 * p)%nat.\n  omega.\n  assert (p + a - b < 2 * p).\n  omega.\n  assert (p + a - b > 0).\n  omega.\n  \n  assert (x0 * p > 0).\n  omega.\n  assert (x0 * p < 2 * p).\n  omega.\n  \n  destruct x0.\n  omega.\n  destruct x0.\n  \n  simpl in H.\n  rewrite plus_0_r in H.\n  omega.\n  \n  assert (p > 0).\n  eapply posnat_pos.\n  simpl in H7.\n  remember (x0 * p)%nat as c.\n  omega.\nQed.\n\nLemma modNat_correct_if : forall x y z (p : posnat),\n  x * p + y = z ->\n  modNat z p = modNat y p.\n  \n  induction x; intuition; simpl in *.\n  subst.\n  trivial.\n  \n  assert (x * p + (y + p) = z).\n  omega.\n  apply IHx in H0.\n  \n  rewrite H0.\n  rewrite plus_comm.\n  rewrite modNat_plus.\n  rewrite modNat_arg_eq.\n  rewrite plus_0_l.\n  trivial.\nQed.\n\nLemma modNat_mult : forall x (p : posnat),\n  modNat (x * p) p = 0.\n  \n  induction x; intuition; simpl in *.\n  rewrite modNat_plus.\n  rewrite modNat_arg_eq.\n  rewrite plus_0_l.\n  eauto.\n  \nQed.\n\nLemma modNat_add_same_l : forall x y z p,\n  modNat (x + y) p = modNat (x + z) p ->\n  modNat y p = modNat z p.\n  \n  induction x; intuition; simpl in *.\n  assert (S (x + y) = x + S y).\n  omega.\n  rewrite H0 in H.\n  clear H0.\n  assert (S (x + z) = x + S z).\n  omega.\n  rewrite H0 in H.\n  clear H0.\n  apply IHx in H.\n  \n  destruct (modNat_correct (S y) p).\n  destruct (modNat_correct (S z) p).\n  rewrite H in H0.\n  \n  assert (S y - x0 * p = modNat (S z) p).\n  omega.\n  assert (S z - x1 * p = modNat (S z) p).\n  omega.\n  rewrite <- H2 in H3.\n  \n  assert (z - x1 * p = y - x0 * p).\n  omega.\n  \n  assert (x1 * p + y = x0 * p + z).\n  omega.\n  \n  apply modNat_correct_if in H5.\n  rewrite modNat_plus in H5.\n  \n  rewrite modNat_mult in H5.\n  rewrite plus_0_l in H5.\n  auto.\n  \nQed.\n\nLemma modNat_add_same_r : forall x y z p,\n  modNat (y + x) p = modNat (z + x) p ->\n  modNat y p = modNat z p.\n  \n  intuition.\n  eapply (modNat_add_same_l x y z).\n  rewrite plus_comm.\n  rewrite H.\n  rewrite plus_comm.\n  trivial.\nQed.\n\nLemma expnat_base_S : forall n k,\n  ((expnat k n) + n * (expnat k (pred n)) <= expnat (S k) n)%nat.\n\n  induction n; intuition.\n  simpl in *.\n  eapply le_trans.\n  Focus 2.\n  eapply plus_le_compat.\n  eapply IHn.\n  eapply mult_le_compat.\n  eapply le_refl.\n  eapply IHn.\n\n  rewrite mult_plus_distr_l.\n  repeat rewrite mult_assoc.\n  repeat rewrite plus_assoc.\n  eapply plus_le_compat.\n  rewrite plus_comm.\n  eapply plus_le_compat.\n  rewrite <- (plus_0_r (expnat k n)) at 1.\n  eapply plus_le_compat. \n  omega.\n  intuition.\n  intuition.\n\n  rewrite (mult_comm k n).\n  rewrite <- (mult_assoc n).\n  destruct n; simpl; intuition.\nQed.\n\nLemma expnat_base_S_same : forall n,\n  n > 0 ->\n  (2 * (expnat n n) <= expnat (S n) n)%nat.\n\n  intuition.\n  simpl in *.\n  rewrite plus_0_r.\n  eapply le_trans.\n  Focus 2.\n  eapply expnat_base_S.\n  destruct n; simpl.\n  omega.\n  intuition.\nQed.\n\nLemma sqrt_le_lin_gen : forall a b,\n  (a <= b ->\n    Nat.sqrt a <= b)%nat.\n  \n  intuition.\n  eapply le_trans.\n  eapply Nat.sqrt_le_lin.\n  trivial.\nQed.\n\nLemma div2_le_mono : forall n1 n2,\n  (n1 <= n2 -> \n    div2 n1 <= div2 n2)%nat.\n  \n  induction n1; intuition.\n  destruct n2.\n  omega.\n  destruct (Even.even_odd_dec n1).\n  destruct (Even.even_odd_dec n2).\n  repeat rewrite <- even_div2; trivial.\n  eapply IHn1.\n  omega.\n  \n  rewrite <- even_div2; trivial.\n  rewrite <- odd_div2; trivial.\n  econstructor.\n  eapply IHn1.\n  omega.\n  \n  destruct (Even.even_odd_dec n2).\n  destruct (lt_dec n1 n2).\n  assert (n1 <= (S n2))%nat.\n  omega.\n  destruct n2.\n  omega.\n  rewrite <- odd_div2; trivial.\n  rewrite <- even_div2.\n  rewrite <- odd_div2.\n  eapply le_n_S.\n  eapply IHn1.\n  omega.\n  inversion e.\n  trivial.\n  trivial.\n  assert (n1 = n2).\n  omega.\n  subst.\n  exfalso.\n  eapply Even.not_even_and_odd; eauto.\n  \n  rewrite <- odd_div2; trivial.\n  rewrite <- odd_div2; trivial.\n  eapply le_n_S.\n  eapply IHn1.\n  omega.\n  \nQed.\n\nLemma div2_ge : forall n n',\n  n >= n' ->\n  forall x,\n    (n' = 2 * x)%nat ->\n    div2 n >= x.\n  \n  induction 1; intuition; subst; simpl in *.\n  specialize (div2_double x); intuition; simpl in *.\n  rewrite H.\n  omega.\n  \n  destruct m.\n  omega.\n  destruct (Even.even_odd_dec m).\n  rewrite even_div2.\n  assert (div2 (S m) >= x).\n  eapply IHle.\n  trivial.\n  omega.\n  trivial.\n  \n  rewrite odd_div2.\n  \n  eapply IHle.\n  trivial.\n  trivial.\nQed.\n\nInstance expnat_nz : forall k n (p : nz n),\n  nz (expnat n k).\n\nintuition.\n\ninduction k; intuition; simpl in *.\neconstructor.\nomega.\neconstructor.\nedestruct IHk; eauto.\ndestruct p.\neapply mult_gt_0; intuition.\n\nQed.\n  \nLemma expnat_2_ge_1 : forall n,\n  (1 <= expnat 2 n)%nat.\n\n  induction n; intuition; simpl in *.\n  omega.\nQed.\n\nLemma le_expnat_2 : forall n,\n  (n <= expnat 2 n)%nat.\n\n  induction n; intuition; simpl in *.\n  rewrite plus_0_r.\n  assert (S n = 1 + n)%nat.\n  omega.\n  rewrite H.\n  eapply plus_le_compat.\n  eapply expnat_2_ge_1.\n  trivial.\n  \nQed.\n\nLemma expnat_1 : forall k,\n  expnat 1%nat k = 1%nat.\n\n  induction k; intuition; simpl in *.\n  rewrite plus_0_r.\n  trivial.\n\nQed.\n\nTheorem expnat_base_le : \n  forall k n1 n2,\n    n1 <= n2 ->\n    expnat n1 k <=\n    expnat n2 k.\n  \n  induction k; intuition; simpl in *.\n  eapply mult_le_compat; intuition.\n  \nQed.\n\nTheorem expnat_double_le : \n  forall k n,\n    n >= 2 ->\n    expnat n (S k) >= 2 * expnat n k.\n\n  induction k; intuition; simpl in *.\n  omega.\n  rewrite plus_0_r.\n  rewrite <- mult_plus_distr_l.\n  eapply mult_le_compat.\n  trivial.\n  rewrite <- plus_0_r at 1.\n  rewrite <- plus_assoc.\n  eapply IHk.\n  trivial.\nQed.\n\nTheorem nat_half_plus : \n  forall x, \n    x > 1 ->\n    exists a b,\n      a > 0 /\\ b <= 1 /\\ x = 2 * a + b.\n  \n  induction x; intuition; simpl in *.\n  omega.\n  \n  destruct (eq_nat_dec x 1); subst.\n  exists 1.\n  exists 0.\n  intuition; omega.\n  \n  edestruct (IHx).\n  omega.\n  destruct H0.\n  intuition.\n  destruct x1.\n  rewrite plus_0_r in H3.\n  exists x0.\n  exists 1.\n  subst.\n  intuition; omega.\n  \n  exists (S x0).\n  exists 0.\n  subst.\n  intuition.\n            \nQed.\n\nTheorem log2_div2 : \n  forall x y,\n    S y = Nat.log2 x ->\n    Nat.log2 (div2 x) = y.\n  \n  intuition.\n  specialize (Nat.log2_double); intuition.\n  \n  destruct (@nat_half_plus x).\n  eapply Nat.log2_lt_cancel.\n  rewrite Nat.log2_1.\n  omega.\n  destruct H1.\n  intuition.\n  subst.\n  destruct x1.\n  rewrite plus_0_r in *.\n  rewrite div2_double.\n  rewrite H0 in H.\n  omega.\n  omega.\n  \n  destruct x1.\n  \n  rewrite plus_comm.\n  rewrite div2_double_plus_one.\n  \n  rewrite Nat.log2_succ_double in H.\n  omega.\n  omega.\n  \n  omega.\n  \nQed.\n\nLemma log2_0 : \n  Nat.log2 0 = 0.\n  trivial.\nQed.\n\nTheorem expnat_0 : \n  forall k,\n    k > 0 ->\n    expnat 0 k = 0.\n  \n  induction k; intuition; simpl in *.\n  \nQed.\n\nTheorem expnat_plus : \n  forall k1 k2 n,\n    expnat n (k1 + k2) = expnat n k1 * expnat n k2.\n  \n  induction k1; simpl in *; intuition.\n  rewrite IHk1.\n  rewrite mult_assoc.\n  trivial.\n  \nQed.\n\nTheorem expnat_ge_1 :\n  forall k n,\n    n > 0 ->\n    1 <= expnat n k.\n  \n  induction k; intuition; simpl in *.\n  rewrite <- mult_1_r at 1.\n  eapply mult_le_compat.\n  omega.\n  eauto.\nQed.\n\n\nTheorem expnat_exp_le : \n  forall n2 n4 n,\n    (n2 > 0 \\/ n > 0) ->\n    n2 <= n4 ->\n    expnat n n2 <= expnat n n4.\n  \n  induction n2; destruct n4; simpl in *; intuition.\n  rewrite <- mult_1_l at 1.\n  eapply mult_le_compat.\n  omega.\n  eapply expnat_ge_1; trivial.\n  \n  destruct (eq_nat_dec n 0); subst.\n  simpl; intuition.\n  eapply mult_le_compat; intuition.\n  \nQed.\n\nLemma mult_lt_compat : \n  forall a b c d,\n    a < b ->\n    c < d ->\n    a * c < b * d.\n  \n  intuition.\n  eapply le_lt_trans.\n  eapply mult_le_compat.\n  assert (a <= b).\n  omega.\n  eapply H1.\n  eapply le_refl.\n  eapply mult_lt_compat_l.\n  trivial.\n  omega.\nQed.\n\nTheorem orb_same_eq_if : \n  forall a b c,\n    (a = false -> b = c) ->\n    orb a b = orb a c.\n  \n  intuition.\n  destruct a; trivial; intuition.\n     \nQed.", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/fcf/StdNat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.677209721215989}}
{"text": "(*************** Verify that Ah_inverse is a normal matrix *****************)\n\nRequire Import Reals Psatz Omega.\nRequire Import Coquelicot.Hierarchy.\nRequire Import linear_algebra.\nRequire Import Ah_inverse.\n\n\nLemma inverse_is_normal (a b:R): forall (N:nat), \n  Mmult (inverse_A N a b ) (mat_transpose N (inverse_A N a b )) = \n  Mmult (mat_transpose N (inverse_A N a b )) (inverse_A N a b ).\nProof.\nintros.\napply (is_normal_mat N (inverse_A N a b )).\nunfold symmetric_mat.\nunfold mat_transpose. unfold inverse_A. apply mk_matrix_ext.\nintros.\nassert (coeff_mat 0\n        (mk_matrix N N\n           (fun i0 j0 : nat =>\n            if i0 <=? j0\n            then 1 / a * (-1) ^ (i0 + j0) * (Mk i0 (b / a) * Mk (N - j0 - 1) (b / a) * / Mk N (b / a))\n            else 1 / a * (-1) ^ (i0 + j0) * (Mk j0 (b / a) * Mk (N - i0 - 1) (b / a)) * / Mk N (b / a))) j i= \n            (fun i0 j0 : nat =>\n            if i0 <=? j0\n            then 1 / a * (-1) ^ (i0 + j0) * (Mk i0 (b / a) * Mk (N - j0 - 1) (b / a) * / Mk N (b / a))\n            else 1 / a * (-1) ^ (i0 + j0) * (Mk j0 (b / a) * Mk (N - i0 - 1) (b / a)) * / Mk N (b / a)) j i).\n{ apply (coeff_mat_bij 0  (fun i0 j0 : nat =>\n            if i0 <=? j0\n            then 1 / a * (-1) ^ (i0 + j0) * (Mk i0 (b / a) * Mk (N - j0 - 1) (b / a) * / Mk N (b / a))\n            else 1 / a * (-1) ^ (i0 + j0) * (Mk j0 (b / a) * Mk (N - i0 - 1) (b / a)) * / Mk N (b / a)) j i).\n  omega. omega. \n} rewrite H1. \nassert ( i=j \\/ (i<j)%nat \\/ (i>j)%nat). { omega. } \ndestruct H2.\n+ rewrite H2. assert (j <=? j=true). \n  { apply leb_correct. omega. } \n  rewrite H3. reflexivity.\n+ destruct H2.\n  assert (i <=? j=true). { apply leb_correct. omega. } rewrite H3.\n  assert (j <=? i=false). { apply leb_correct_conv. omega. } rewrite H4. \n  assert ((i + j)%nat=(j + i)%nat ). { omega. } rewrite H5. nra.\n+ assert ( i <=? j=false). { apply leb_correct_conv. omega. } rewrite H3. \n  assert (j <=? i=true). { apply leb_correct. omega. } rewrite H4.\n  assert ((i + j)%nat=(j + i)%nat ). { omega. } rewrite H5. nra.\nQed.\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/inverse_Ah_is_normal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.6772028833697641}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) : natural := plus lf2 Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj15_coqofml_0JlnZ8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.6772028789415525}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) : natural := Succ (plus Zero lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj62_coqofml_SNnSEo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6772028749157301}}
{"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.R_sqrt.\nRequire Reals.Rbasic_fun.\nRequire Reals.Rtrigo_def.\nRequire Reals.Rtrigo1.\nRequire Reals.Ratan.\nRequire BuiltIn.\nRequire real.Real.\nRequire real.Abs.\nRequire real.Square.\n\nRequire Import Reals.\n\n(* Why3 comment *)\n(* cos is replaced with (Reals.Rtrigo_def.cos x) by the coq driver *)\n\n(* Why3 comment *)\n(* sin is replaced with (Reals.Rtrigo_def.sin x) by the coq driver *)\n\n(* Why3 goal *)\nLemma Pythagorean_identity :\nforall (x:R),\n (((Reals.RIneq.Rsqr (Reals.Rtrigo_def.cos x)) + (Reals.RIneq.Rsqr (Reals.Rtrigo_def.sin x)))%R = 1%R).\nProof.\nintros x.\nrewrite Rplus_comm.\napply sin2_cos2.\nQed.\n\n(* Why3 goal *)\nLemma Cos_le_one :\nforall (x:R), ((Reals.Rbasic_fun.Rabs (Reals.Rtrigo_def.cos x)) <= 1%R)%R.\nProof.\nintros x.\napply Abs.Abs_le.\napply COS_bound.\nQed.\n\n(* Why3 goal *)\nLemma Sin_le_one :\nforall (x:R), ((Reals.Rbasic_fun.Rabs (Reals.Rtrigo_def.sin x)) <= 1%R)%R.\nProof.\nintros x.\napply Abs.Abs_le.\napply SIN_bound.\nQed.\n\n(* Why3 goal *)\nLemma Cos_0 :\n((Reals.Rtrigo_def.cos 0%R) = 1%R).\nProof.\napply cos_0.\nQed.\n\n(* Why3 goal *)\nLemma Sin_0 :\n((Reals.Rtrigo_def.sin 0%R) = 0%R).\nProof.\napply sin_0.\nQed.\n\n(* Why3 comment *)\n(* pi is replaced with Reals.Rtrigo1.PI by the coq driver *)\n\n(* Why3 goal *)\nLemma Pi_double_precision_bounds :\n((7074237752028440 / 2251799813685248)%R < Reals.Rtrigo1.PI)%R\n/\\ (Reals.Rtrigo1.PI < (7074237752028441 / 2251799813685248)%R)%R.\nProof.\nreplace PI with (4 * (PI / 4))%R by field.\nrewrite <- atan_1.\nadmit. (* to avoid a dependency on CoqInterval *)\n(*\nRequire Import Interval_tactic.\nsplit ; interval with (i_prec 55). \n*)\nAdmitted.\n\n(* Why3 goal *)\nLemma Cos_pi :\n((Reals.Rtrigo_def.cos Reals.Rtrigo1.PI) = (-1%R)%R).\nProof.\napply cos_PI.\nQed.\n\n(* Why3 goal *)\nLemma Sin_pi :\n((Reals.Rtrigo_def.sin Reals.Rtrigo1.PI) = 0%R).\nProof.\napply sin_PI.\nQed.\n\n(* Why3 goal *)\nLemma Cos_pi2 :\n((Reals.Rtrigo_def.cos ((05 / 10)%R * Reals.Rtrigo1.PI)%R) = 0%R).\nProof.\nreplace (5 / 10 * PI)%R with (PI / 2)%R by field.\napply cos_PI2.\nQed.\n\n(* Why3 goal *)\nLemma Sin_pi2 :\n((Reals.Rtrigo_def.sin ((05 / 10)%R * Reals.Rtrigo1.PI)%R) = 1%R).\nProof.\nreplace (5 / 10 * PI)%R with (PI / 2)%R by field.\napply sin_PI2.\nQed.\n\n(* Why3 goal *)\nLemma Cos_plus_pi :\nforall (x:R),\n ((Reals.Rtrigo_def.cos (x + Reals.Rtrigo1.PI)%R) = (-(Reals.Rtrigo_def.cos x))%R).\nProof.\nintros x.\napply neg_cos.\nQed.\n\n(* Why3 goal *)\nLemma Sin_plus_pi :\nforall (x:R),\n ((Reals.Rtrigo_def.sin (x + Reals.Rtrigo1.PI)%R) = (-(Reals.Rtrigo_def.sin x))%R).\nProof.\nintros x.\napply neg_sin.\nQed.\n\n(* Why3 goal *)\nLemma Cos_plus_pi2 :\nforall (x:R),\n ((Reals.Rtrigo_def.cos (x + ((05 / 10)%R * Reals.Rtrigo1.PI)%R)%R) = (-(Reals.Rtrigo_def.sin x))%R).\nProof.\nintros x.\nrewrite cos_sin.\nreplace (PI / 2 + (x + 5 / 10 * PI))%R with (x + PI)%R by field.\napply neg_sin.\nQed.\n\n(* Why3 goal *)\nLemma Sin_plus_pi2 :\nforall (x:R),\n ((Reals.Rtrigo_def.sin (x + ((05 / 10)%R * Reals.Rtrigo1.PI)%R)%R) = (Reals.Rtrigo_def.cos x)).\nProof.\nintros x.\nrewrite cos_sin.\napply f_equal.\nfield.\nQed.\n\n(* Why3 goal *)\nLemma Cos_neg :\nforall (x:R), ((Reals.Rtrigo_def.cos (-x)%R) = (Reals.Rtrigo_def.cos x)).\nProof.\nintros x.\napply cos_neg.\nQed.\n\n(* Why3 goal *)\nLemma Sin_neg :\nforall (x:R), ((Reals.Rtrigo_def.sin (-x)%R) = (-(Reals.Rtrigo_def.sin x))%R).\nProof.\nintros x.\napply sin_neg.\nQed.\n\n(* Why3 goal *)\nLemma Cos_sum :\nforall (x:R) (y:R),\n ((Reals.Rtrigo_def.cos (x + y)%R) = (((Reals.Rtrigo_def.cos x) * (Reals.Rtrigo_def.cos y))%R - ((Reals.Rtrigo_def.sin x) * (Reals.Rtrigo_def.sin y))%R)%R).\nProof.\nintros x y.\napply cos_plus.\nQed.\n\n(* Why3 goal *)\nLemma Sin_sum :\nforall (x:R) (y:R),\n ((Reals.Rtrigo_def.sin (x + y)%R) = (((Reals.Rtrigo_def.sin x) * (Reals.Rtrigo_def.cos y))%R + ((Reals.Rtrigo_def.cos x) * (Reals.Rtrigo_def.sin y))%R)%R).\nProof.\nintros x y.\napply sin_plus.\nQed.\n\n(* Why3 goal *)\nLemma tan_def :\n  forall (x:R),\n   ((Reals.Rtrigo1.tan x) = ((Reals.Rtrigo_def.sin x) / (Reals.Rtrigo_def.cos x))%R).\nProof.\nintros x.\napply eq_refl.\nQed.\n\n(* Why3 comment *)\n(* atan is replaced with (Reals.Ratan.atan x) by the coq driver *)\n\n(* Why3 goal *)\nLemma Tan_atan :\nforall (x:R), ((Reals.Rtrigo1.tan (Reals.Ratan.atan x)) = x).\nProof.\nintros x.\napply atan_right_inv.\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/Trigonometry.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.6772028745133409}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq div.\nFrom mathcomp Require Import fintype tuple finfun bigop fingroup perm.\nFrom mathcomp Require Import ssralg zmodp matrix mxalgebra poly polydiv.\n\n(******************************************************************************)\n(*   This file provides basic support for formal computation with matrices,   *)\n(* mainly results combining matrices and univariate polynomials, such as the  *)\n(* Cayley-Hamilton theorem; it also contains an extension of the first order  *)\n(* representation of algebra introduced in ssralg (GRing.term/formula).       *)\n(*      rVpoly v == the little-endian decoding of the row vector v as a       *)\n(*                  polynomial p = \\sum_i (v 0 i)%:P * 'X^i.                  *)\n(*     poly_rV p == the partial inverse to rVpoly, for polynomials of degree  *)\n(*                  less than d to 'rV_d (d is inferred from the context).    *)\n(* Sylvester_mx p q == the Sylvester matrix of p and q.                       *)\n(* resultant p q == the resultant of p and q, i.e., \\det (Sylvester_mx p q).  *)\n(*   horner_mx A == the morphism from {poly R} to 'M_n (n of the form n'.+1)  *)\n(*                  mapping a (scalar) polynomial p to the value of its       *)\n(*                  scalar matrix interpretation at A (this is an instance of *)\n(*                  the generic horner_morph construct defined in poly).      *)\n(* powers_mx A d == the d x (n ^ 2) matrix whose rows are the mxvec encodings *)\n(*                  of the first d powers of A (n of the form n'.+1). Thus,   *)\n(*                  vec_mx (v *m powers_mx A d) = horner_mx A (rVpoly v).     *)\n(*   char_poly A  == the characteristic polynomial of A.                      *)\n(* char_poly_mx A == a matrix whose determinant is char_poly A.               *)\n(*  companionmx p == a matrix whose char_poly is p                            *)\n(*   mxminpoly A  == the minimal polynomial of A, i.e., the smallest monic    *)\n(*                   polynomial that annihilates A (A must be nontrivial).    *)\n(* degree_mxminpoly A == the (positive) degree of mxminpoly A.                *)\n(* mx_inv_horner A == the inverse of horner_mx A for polynomials of degree    *)\n(*                  smaller than degree_mxminpoly A.                          *)\n(*  integralOver RtoK u <-> u is in the integral closure of the image of R    *)\n(*                  under RtoK : R -> K, i.e. u is a root of the image of a   *)\n(*                  monic polynomial in R.                                    *)\n(*  algebraicOver FtoE u <-> u : E is algebraic over E; it is a root of the   *)\n(*                  image of a nonzero polynomial under FtoE; as F must be a  *)\n(*                  fieldType, this is equivalent to integralOver FtoE u.     *)\n(*  integralRange RtoK <-> the integral closure of the image of R contains    *)\n(*                  all of K (:= forall u, integralOver RtoK u).              *)\n(* This toolkit for building formal matrix expressions is packaged in the     *)\n(* MatrixFormula submodule, and comprises the following:                      *)\n(*     eval_mx e == GRing.eval lifted to matrices (:= map_mx (GRing.eval e)). *)\n(*     mx_term A == GRing.Const lifted to matrices.                           *)\n(* mulmx_term A B == the formal product of two matrices of terms.             *)\n(* mxrank_form m A == a GRing.formula asserting that the interpretation of    *)\n(*                  the term matrix A has rank m.                             *)\n(* submx_form A B == a GRing.formula asserting that the row space of the      *)\n(*                  interpretation of the term matrix A is included in the    *)\n(*                  row space of the interpretation of B.                     *)\n(*   seq_of_rV v == the seq corresponding to a row vector.                    *)\n(*     row_env e == the flattening of a tensored environment e : seq 'rV_d.   *)\n(* row_var F d k == the term vector of width d such that for e : seq 'rV[F]_d *)\n(*                  we have eval e 'X_k = eval_mx (row_env e) (row_var d k).  *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory.\nImport Monoid.Theory.\n\nLocal Open Scope ring_scope.\n\nImport Pdiv.Idomain.\n(* Row vector <-> bounded degree polynomial bijection *)\nSection RowPoly.\n\nVariables (R : ringType) (d : nat).\nImplicit Types u v : 'rV[R]_d.\nImplicit Types p q : {poly R}.\n\nDefinition rVpoly v := \\poly_(k < d) (if insub k is Some i then v 0 i else 0).\nDefinition poly_rV p := \\row_(i < d) p`_i.\n\nLemma coef_rVpoly v k : (rVpoly v)`_k = if insub k is Some i then v 0 i else 0.\nProof. by rewrite coef_poly; case: insubP => [i ->|]; rewrite ?if_same. Qed.\n\nLemma coef_rVpoly_ord v (i : 'I_d) : (rVpoly v)`_i = v 0 i.\nProof. by rewrite coef_rVpoly valK. Qed.\n\nLemma rVpoly_delta i : rVpoly (delta_mx 0 i) = 'X^i.\nProof.\napply/polyP=> j; rewrite coef_rVpoly coefXn.\ncase: insubP => [k _ <- | j_ge_d]; first by rewrite mxE.\nby case: eqP j_ge_d => // ->; rewrite ltn_ord.\nQed.\n\nLemma rVpolyK : cancel rVpoly poly_rV.\nProof. by move=> u; apply/rowP=> i; rewrite mxE coef_rVpoly_ord. Qed.\n\nLemma poly_rV_K p : size p <= d -> rVpoly (poly_rV p) = p.\nProof.\nmove=> le_p_d; apply/polyP=> k; rewrite coef_rVpoly.\ncase: insubP => [i _ <- | ]; first by rewrite mxE.\nby rewrite -ltnNge => le_d_l; rewrite nth_default ?(leq_trans le_p_d).\nQed.\n\nLemma poly_rV_is_linear : linear poly_rV.\nProof. by move=> a p q; apply/rowP=> i; rewrite !mxE coefD coefZ. Qed.\nCanonical poly_rV_additive := Additive poly_rV_is_linear.\nCanonical poly_rV_linear := Linear poly_rV_is_linear.\n\nLemma rVpoly_is_linear : linear rVpoly.\nProof.\nmove=> a u v; apply/polyP=> k; rewrite coefD coefZ !coef_rVpoly.\nby case: insubP => [i _ _ | _]; rewrite ?mxE // mulr0 addr0.\nQed.\nCanonical rVpoly_additive := Additive rVpoly_is_linear.\nCanonical rVpoly_linear := Linear rVpoly_is_linear.\n\nEnd RowPoly.\n\nPrenex Implicits rVpoly rVpolyK.\nArguments poly_rV {R d}.\nArguments poly_rV_K {R d} [p] le_p_d.\n\nSection Resultant.\n\nVariables (R : ringType) (p q : {poly R}).\n\nLet dS := ((size q).-1 + (size p).-1)%N.\nLocal Notation band r := (lin1_mx (poly_rV \\o r \\o* rVpoly)).\n\nDefinition Sylvester_mx : 'M[R]_dS := col_mx (band p) (band q).\n\nLemma Sylvester_mxE (i j : 'I_dS) :\n  let S_ r k := r`_(j - k) *+ (k <= j) in\n  Sylvester_mx i j = match split i with inl k => S_ p k | inr k => S_ q k end.\nProof.\nmove=> S_; rewrite mxE; case: {i}(split i) => i; rewrite !mxE /=;\n  by rewrite rVpoly_delta coefXnM ltnNge if_neg -mulrb.\nQed.\n\nDefinition resultant := \\det Sylvester_mx.\n\nEnd Resultant.\n\nPrenex Implicits Sylvester_mx resultant.\n\nLemma resultant_in_ideal (R : comRingType) (p q : {poly R}) :\n    size p > 1 -> size q > 1 ->\n  {uv : {poly R} * {poly R} | size uv.1 < size q /\\ size uv.2 < size p\n  & (resultant p q)%:P = uv.1 * p + uv.2 * q}.\nProof.\nmove=> p_nc q_nc; pose dp := (size p).-1; pose dq := (size q).-1.\npose S := Sylvester_mx p q; pose dS := (dq + dp)%N.\nhave dS_gt0: dS > 0 by rewrite /dS /dq -(subnKC q_nc).\npose j0 := Ordinal dS_gt0.\npose Ss0 := col_mx (p *: \\col_(i < dq) 'X^i) (q *: \\col_(i < dp) 'X^i).\npose Ss := \\matrix_(i, j) (if j == j0 then Ss0 i 0 else (S i j)%:P).\npose u ds s := \\sum_(i < ds) cofactor Ss (s i) j0 * 'X^i.\nexists (u _ (lshift dp), u _ ((rshift dq) _)).\n  suffices sz_u ds s: ds > 1 -> size (u ds.-1 s) < ds by rewrite !sz_u.\n  move/ltn_predK=> {2}<-; apply: leq_trans (size_sum _ _ _) _.\n  apply/bigmax_leqP=> i _.\n  have ->: cofactor Ss (s i) j0 = (cofactor S (s i) j0)%:P.\n    rewrite rmorphM rmorph_sign -det_map_mx; congr (_ * \\det _).\n    by apply/matrixP=> i' j'; rewrite !mxE.\n  apply: leq_trans (size_mul_leq _ _) (leq_trans _ (valP i)).\n  by rewrite size_polyC size_polyXn addnS /= -add1n leq_add2r leq_b1.\ntransitivity (\\det Ss); last first.\n  rewrite (expand_det_col Ss j0) big_split_ord !big_distrl /=.\n  by congr (_ + _); apply: eq_bigr => i _;\n    rewrite mxE eqxx (col_mxEu, col_mxEd) !mxE mulrC mulrA mulrAC.\npose S_ j1 := map_mx polyC (\\matrix_(i, j) S i (if j == j0 then j1 else j)).\npose Ss0_ i dj := \\poly_(j < dj) S i (insubd j0 j).\npose Ss_ dj := \\matrix_(i, j) (if j == j0 then Ss0_ i dj else (S i j)%:P).\nhave{Ss u} ->: Ss = Ss_ dS.\n  apply/matrixP=> i j; rewrite mxE [in X in _ = X]mxE; case: (j == j0) => {j}//.\n  apply/polyP=> k; rewrite coef_poly Sylvester_mxE mxE.\n  have [k_ge_dS | k_lt_dS] := leqP dS k.\n    case: (split i) => {i}i; rewrite !mxE coefMXn;\n    case: ifP => // /negbT; rewrite -ltnNge ltnS => hi.\n      apply: (leq_sizeP _ _ (leqnn (size p))); rewrite -(ltn_predK p_nc).\n      by rewrite ltn_subRL (leq_trans _ k_ge_dS) // ltn_add2r.\n    - apply: (leq_sizeP _ _ (leqnn (size q))); rewrite -(ltn_predK q_nc).\n      by rewrite ltn_subRL (leq_trans _ k_ge_dS) // addnC ltn_add2l.\n  by rewrite insubdK //; case: (split i) => {i}i;\n     rewrite !mxE coefMXn; case: leqP.\ncase: (ubnPgeq dS) (dS_gt0); elim=> // dj IHj ltjS _; pose j1 := Ordinal ltjS.\npose rj0T (A : 'M[{poly R}]_dS) := row j0 A^T.\nhave: rj0T (Ss_ dj.+1) = 'X^dj *: rj0T (S_ j1) + 1 *: rj0T (Ss_ dj).\n  apply/rowP=> i; apply/polyP=> k; rewrite scale1r !(Sylvester_mxE, mxE) eqxx.\n  rewrite coefD coefXnM coefC !coef_poly ltnS subn_eq0 ltn_neqAle andbC.\n  case: (leqP k dj) => [k_le_dj | k_gt_dj] /=; last by rewrite addr0.\n  rewrite Sylvester_mxE insubdK; last exact: leq_ltn_trans (ltjS).\n  by case: eqP => [-> | _]; rewrite (addr0, add0r).\nrewrite -det_tr => /determinant_multilinear->;\n  try by apply/matrixP=> i j; rewrite !mxE eq_sym (negPf (neq_lift _ _)).\nhave [dj0 | dj_gt0] := posnP dj; rewrite ?dj0 !mul1r.\n  rewrite !det_tr det_map_mx addrC (expand_det_col _ j0) big1 => [|i _].\n    rewrite add0r; congr (\\det _)%:P.\n    apply/matrixP=> i j; rewrite [in X in _ = X]mxE; case: eqP => // ->.\n    by congr (S i _); apply: val_inj.\n  by rewrite mxE /= [Ss0_ _ _]poly_def big_ord0 mul0r.\nhave /determinant_alternate->: j1 != j0 by rewrite -val_eqE -lt0n.\n  by rewrite mulr0 add0r det_tr IHj // ltnW.\nby move=> i; rewrite !mxE if_same.\nQed.\n\nLemma resultant_eq0 (R : idomainType) (p q : {poly R}) :\n  (resultant p q == 0) = (size (gcdp p q) > 1).\nProof.\nhave dvdpp := dvdpp; set r := gcdp p q.\npose dp := (size p).-1; pose dq := (size q).-1.\nhave /andP[r_p r_q]: (r %| p) && (r %| q) by rewrite -dvdp_gcd.\napply/det0P/idP=> [[uv nz_uv] | r_nonC].\n  have [p0 _ | p_nz] := eqVneq p 0.\n    have: dq + dp > 0.\n      rewrite lt0n; apply: contraNneq nz_uv => dqp0.\n      by rewrite dqp0 in uv *; rewrite [uv]thinmx0.\n    by rewrite /dp /dq /r p0 size_poly0 addn0 gcd0p -subn1 subn_gt0.\n  do [rewrite -[uv]hsubmxK -{1}row_mx0 mul_row_col !mul_rV_lin1 /=] in nz_uv *.\n  set u := rVpoly _; set v := rVpoly _; pose m := gcdp (v * p) (v * q).\n  have lt_vp: size v < size p by rewrite (polySpred p_nz) ltnS size_poly.\n  move/(congr1 rVpoly)/eqP; rewrite -linearD linear0 poly_rV_K; last first.\n    rewrite (leq_trans (size_add _ _)) // geq_max.\n    rewrite !(leq_trans (size_mul_leq _ _)) // -subn1 leq_subLR.\n      by rewrite addnC addnA leq_add ?leqSpred ?size_poly.\n    by rewrite addnCA leq_add ?leqSpred ?size_poly.\n  rewrite addrC addr_eq0 => /eqP vq_up.\n  have nz_v: v != 0.\n    apply: contraNneq nz_uv => v0; apply/eqP.\n    congr row_mx; apply: (can_inj rVpolyK); rewrite linear0 // -/u.\n    by apply: contra_eq vq_up; rewrite v0 mul0r -addr_eq0 add0r => /mulf_neq0->.\n  have r_nz: r != 0 := dvdpN0 r_p p_nz.\n  have /dvdpP [[c w] /= nz_c wv]: v %| m by rewrite dvdp_gcd !dvdp_mulr.\n  have m_wd d: m %| v * d -> w %| d.\n    case/dvdpP=> [[k f]] /= nz_k /(congr1 ( *:%R c)).\n    rewrite mulrC scalerA scalerAl scalerAr wv mulrA => /(mulIf nz_v)def_fw.\n    by apply/dvdpP; exists (c * k, f); rewrite //= mulf_neq0.\n  have w_r: w %| r by rewrite dvdp_gcd !m_wd ?dvdp_gcdl ?dvdp_gcdr.\n  have w_nz: w != 0 := dvdpN0 w_r r_nz.\n  have p_m: p %| m  by rewrite dvdp_gcd vq_up -mulNr !dvdp_mull.\n  rewrite (leq_trans _ (dvdp_leq r_nz w_r)) // -(ltn_add2l (size v)).\n  rewrite addnC -ltn_subRL subn1 -size_mul // mulrC -wv size_scale //.\n  rewrite (leq_trans lt_vp) // dvdp_leq // -size_poly_eq0.\n  by rewrite -(size_scale _ nz_c) size_poly_eq0 wv mulf_neq0.\nhave [[c p'] /= nz_c p'r] := dvdpP _ _ r_p.\nhave [[k q'] /= nz_k q'r] := dvdpP _ _ r_q.\nhave def_r := subnKC r_nonC; have r_nz: r != 0 by rewrite -size_poly_eq0 -def_r.\nhave le_p'_dp: size p' <= dp.\n  have [-> | nz_p'] := eqVneq p' 0; first by rewrite size_poly0.\n  by rewrite /dp -(size_scale p nz_c) p'r size_mul // addnC -def_r leq_addl.\nhave le_q'_dq: size q' <= dq.\n  have [-> | nz_q'] := eqVneq q' 0; first by rewrite size_poly0.\n  by rewrite /dq -(size_scale q nz_k) q'r size_mul // addnC -def_r leq_addl.\nexists (row_mx (- c *: poly_rV q') (k *: poly_rV p')).\n  apply: contraNneq r_nz; rewrite -row_mx0; case/eq_row_mx=> q0 p0.\n  have{p0} p0: p = 0.\n    apply/eqP; rewrite -size_poly_eq0 -(size_scale p nz_c) p'r.\n    rewrite -(size_scale _ nz_k) scalerAl -(poly_rV_K le_p'_dp) -linearZ p0.\n    by rewrite linear0 mul0r size_poly0.\n  rewrite /r p0 gcd0p -size_poly_eq0 -(size_scale q nz_k) q'r.\n  rewrite -(size_scale _ nz_c) scalerAl -(poly_rV_K le_q'_dq) -linearZ.\n  by rewrite -[c]opprK scaleNr q0 !linear0 mul0r size_poly0.\nrewrite mul_row_col scaleNr mulNmx !mul_rV_lin1 /= !linearZ /= !poly_rV_K //.\nby rewrite !scalerCA p'r q'r mulrCA addNr.\nQed.\n\nSection HornerMx.\n\nVariables (R : comRingType) (n' : nat).\nLocal Notation n := n'.+1.\nVariable A : 'M[R]_n.\nImplicit Types p q : {poly R}.\n\nDefinition horner_mx := horner_morph (fun a => scalar_mx_comm a A).\nCanonical horner_mx_additive := [additive of horner_mx].\nCanonical horner_mx_rmorphism := [rmorphism of horner_mx].\n\nLemma horner_mx_C a : horner_mx a%:P = a%:M.\nProof. exact: horner_morphC. Qed.\n\nLemma horner_mx_X : horner_mx 'X = A. Proof. exact: horner_morphX. Qed.\n\nLemma horner_mxZ : scalable horner_mx.\nProof.\nmove=> a p /=; rewrite -mul_polyC rmorphM /=.\nby rewrite horner_mx_C [_ * _]mul_scalar_mx.\nQed.\n\nCanonical horner_mx_linear := AddLinear horner_mxZ.\nCanonical horner_mx_lrmorphism := [lrmorphism of horner_mx].\n\nDefinition powers_mx d := \\matrix_(i < d) mxvec (A ^+ i).\n\nLemma horner_rVpoly m (u : 'rV_m) :\n  horner_mx (rVpoly u) = vec_mx (u *m powers_mx m).\nProof.\nrewrite mulmx_sum_row linear_sum [rVpoly u]poly_def rmorph_sum.\napply: eq_bigr => i _.\nby rewrite valK !linearZ rmorphX /= horner_mx_X rowK /= mxvecK.\nQed.\n\nEnd HornerMx.\n\nPrenex Implicits horner_mx powers_mx.\n\nSection CharPoly.\n\nVariables (R : ringType) (n : nat) (A : 'M[R]_n).\nImplicit Types p q : {poly R}.\n\nDefinition char_poly_mx := 'X%:M - map_mx (@polyC R) A.\nDefinition char_poly := \\det char_poly_mx.\n\nLet diagA := [seq A i i | i <- index_enum _ & true].\nLet size_diagA : size diagA = n.\nProof. by rewrite -[n]card_ord size_map; have [e _ _ []] := big_enumP. Qed.\n\nLet split_diagA :\n  exists2 q, \\prod_(x <- diagA) ('X - x%:P) + q = char_poly & size q <= n.-1.\nProof.\nrewrite [char_poly](bigD1 1%g) //=; set q := \\sum_(s | _) _; exists q.\n  congr (_ + _); rewrite odd_perm1 mul1r big_map big_filter /=.\n  by apply: eq_bigr => i _; rewrite !mxE perm1 eqxx.\napply: leq_trans {q}(size_sum _ _ _) _; apply/bigmax_leqP=> s nt_s.\nhave{nt_s} [i nfix_i]: exists i, s i != i.\n  apply/existsP; rewrite -negb_forall; apply: contra nt_s => s_1.\n  by apply/eqP; apply/permP=> i; apply/eqP; rewrite perm1 (forallP s_1).\napply: leq_trans (_ : #|[pred j | s j == j]|.+1 <= n.-1).\n  rewrite -sum1_card (@big_mkcond nat) /= size_Msign.\n  apply: (big_ind2 (fun p m => size p <= m.+1)) => [| p mp q mq IHp IHq | j _].\n  - by rewrite size_poly1.\n  - apply: leq_trans (size_mul_leq _ _) _.\n    by rewrite -subn1 -addnS leq_subLR addnA leq_add.\n  rewrite !mxE eq_sym !inE; case: (s j == j); first by rewrite polyseqXsubC.\n  by rewrite sub0r size_opp size_polyC leq_b1.\nrewrite -[n in n.-1]card_ord -(cardC (pred2 (s i) i)) card2 nfix_i !ltnS.\napply: subset_leq_card; apply/subsetP=> j; move/(_ =P j)=> fix_j.\nrewrite !inE -{1}fix_j (inj_eq perm_inj) orbb.\nby apply: contraNneq nfix_i => <-; rewrite fix_j.\nQed.\n\nLemma size_char_poly : size char_poly = n.+1.\nProof.\nhave [q <- lt_q_n] := split_diagA; have le_q_n := leq_trans lt_q_n (leq_pred n).\nby rewrite size_addl size_prod_XsubC size_diagA.\nQed.\n\nLemma char_poly_monic : char_poly \\is monic.\nProof.\nrewrite monicE -(monicP (monic_prod_XsubC diagA xpredT id)).\nrewrite !lead_coefE size_char_poly.\nhave [q <- lt_q_n] := split_diagA; have le_q_n := leq_trans lt_q_n (leq_pred n).\nby rewrite size_prod_XsubC size_diagA coefD (nth_default 0 le_q_n) addr0.\nQed.\n\nLemma char_poly_trace : n > 0 -> char_poly`_n.-1 = - \\tr A.\nProof.\nmove=> n_gt0; have [q <- lt_q_n] := split_diagA; set p := \\prod_(x <- _) _.\nrewrite coefD {q lt_q_n}(nth_default 0 lt_q_n) addr0.\nhave{n_gt0} ->: p`_n.-1 = ('X * p)`_n by rewrite coefXM eqn0Ngt n_gt0.\nhave ->: \\tr A = \\sum_(x <- diagA) x by rewrite big_map big_filter.\nrewrite -size_diagA {}/p; elim: diagA => [|x d IHd].\n  by rewrite !big_nil mulr1 coefX oppr0.\nrewrite !big_cons coefXM mulrBl coefB IHd opprD addrC; congr (- _ + _).\nrewrite mul_polyC coefZ [size _]/= -(size_prod_XsubC _ id) -lead_coefE.\nby rewrite (monicP _) ?monic_prod_XsubC ?mulr1.\nQed.\n\nLemma char_poly_det : char_poly`_0 = (- 1) ^+ n * \\det A.\nProof.\nrewrite big_distrr coef_sum [0%N]lock /=; apply: eq_bigr => s _.\nrewrite -{1}rmorphN -rmorphX mul_polyC coefZ /=.\nrewrite mulrA -exprD addnC exprD -mulrA -lock; congr (_ * _).\ntransitivity (\\prod_(i < n) - A i (s i)); last by rewrite prodrN card_ord.\nelim: (index_enum _) => [|i e IHe]; rewrite !(big_nil, big_cons) ?coef1 //.\nby rewrite coefM big_ord1 IHe !mxE coefB coefC coefMn coefX mul0rn sub0r.\nQed.\n\nEnd CharPoly.\n\nPrenex Implicits char_poly_mx char_poly.\n\nLemma mx_poly_ring_isom (R : ringType) n' (n := n'.+1) :\n  exists phi : {rmorphism 'M[{poly R}]_n -> {poly 'M[R]_n}},\n  [/\\ bijective phi,\n      forall p, phi p%:M = map_poly scalar_mx p,\n      forall A, phi (map_mx polyC A) = A%:P\n    & forall A i j k, (phi A)`_k i j = (A i j)`_k].\nProof.\nset M_RX := 'M[{poly R}]_n; set MR_X := ({poly 'M[R]_n}).\npose Msize (A : M_RX) := \\max_i \\max_j size (A i j).\npose phi (A : M_RX) := \\poly_(k < Msize A) \\matrix_(i, j) (A i j)`_k.\nhave coef_phi A i j k: (phi A)`_k i j = (A i j)`_k.\n  rewrite coef_poly; case: (ltnP k _) => le_m_k; rewrite mxE // nth_default //.\n  by apply: leq_trans (leq_trans (leq_bigmax i) le_m_k); apply: (leq_bigmax j).\nhave phi_is_rmorphism : rmorphism phi.\n  do 2?[split=> [A B|]]; apply/polyP=> k; apply/matrixP=> i j; last 1 first.\n  - rewrite coef_phi mxE coefMn !coefC.\n    by case: (k == _); rewrite ?mxE ?mul0rn.\n  - by rewrite !(coef_phi, mxE, coefD, coefN).\n  rewrite !coef_phi !mxE !coefM summxE coef_sum.\n  pose F k1 k2 := (A i k1)`_k2 * (B k1 j)`_(k - k2).\n  transitivity (\\sum_k1 \\sum_(k2 < k.+1) F k1 k2); rewrite {}/F.\n    by apply: eq_bigr=> k1 _; rewrite coefM.\n  rewrite exchange_big /=; apply: eq_bigr => k2 _.\n  by rewrite mxE; apply: eq_bigr => k1 _; rewrite !coef_phi.\nhave bij_phi: bijective phi.\n  exists (fun P : MR_X => \\matrix_(i, j) \\poly_(k < size P) P`_k i j) => [A|P].\n    apply/matrixP=> i j; rewrite mxE; apply/polyP=> k.\n    rewrite coef_poly -coef_phi.\n    by case: leqP => // P_le_k; rewrite nth_default ?mxE.\n  apply/polyP=> k; apply/matrixP=> i j; rewrite coef_phi mxE coef_poly.\n  by case: leqP => // P_le_k; rewrite nth_default ?mxE.\nexists (RMorphism phi_is_rmorphism).\nsplit=> // [p | A]; apply/polyP=> k; apply/matrixP=> i j.\n  by rewrite coef_phi coef_map !mxE coefMn.\nby rewrite coef_phi !mxE !coefC; case k; last rewrite /= mxE.\nQed.\n\nTheorem Cayley_Hamilton (R : comRingType) n' (A : 'M[R]_n'.+1) :\n  horner_mx A (char_poly A) = 0.\nProof.\nhave [phi [_ phiZ phiC _]] := mx_poly_ring_isom R n'.\napply/rootP/factor_theorem; rewrite -phiZ -mul_adj_mx rmorphM.\nby move: (phi _) => q; exists q; rewrite rmorphB phiC phiZ map_polyX.\nQed.\n\nLemma eigenvalue_root_char (F : fieldType) n (A : 'M[F]_n) a :\n  eigenvalue A a = root (char_poly A) a.\nProof.\ntransitivity (\\det (a%:M - A) == 0).\n  apply/eigenvalueP/det0P=> [[v Av_av v_nz] | [v v_nz Av_av]]; exists v => //.\n    by rewrite mulmxBr Av_av mul_mx_scalar subrr.\n  by apply/eqP; rewrite -mul_mx_scalar eq_sym -subr_eq0 -mulmxBr Av_av.\ncongr (_ == 0); rewrite horner_sum; apply: eq_bigr => s _.\nrewrite hornerM horner_exp !hornerE; congr (_ * _).\nrewrite (big_morph _ (fun p q => hornerM p q a) (hornerC 1 a)).\nby apply: eq_bigr => i _; rewrite !mxE !(hornerE, hornerMn).\nQed.\n\nDefinition companionmx {R : ringType} (p : seq R) (d := (size p).-1) :=\n  \\matrix_(i < d, j < d)\n    if (i == d.-1 :> nat) then - p`_j else (i.+1 == j :> nat)%:R.\n\nLemma companionmxK {R : comRingType} (p : {poly R}) :\n   p \\is monic -> char_poly (companionmx p) = p.\nProof.\npose D n : 'M[{poly R}]_n := \\matrix_(i, j)\n   ('X *+ (i == j.+1 :> nat) - ((i == j)%:R)%:P).\nhave detD n : \\det (D n) = (-1) ^+ n.\n  elim: n => [|n IHn]; first by rewrite det_mx00.\n  rewrite (expand_det_row _ ord0) big_ord_recl !mxE /= sub0r.\n  rewrite big1 ?addr0; last by move=> i _; rewrite !mxE /= subrr mul0r.\n  rewrite /cofactor mul1r [X in \\det X](_ : _ = D _) ?IHn ?exprS//.\n  by apply/matrixP=> i j; rewrite !mxE /= /bump !add1n eqSS.\nelim/poly_ind: p => [|p c IHp].\n  by rewrite monicE lead_coef0 eq_sym oner_eq0.\nhave [->|p_neq0] := eqVneq p 0.\n  rewrite mul0r add0r monicE lead_coefC => /eqP->.\n  by rewrite /companionmx /char_poly size_poly1 det_mx00.\nrewrite monicE lead_coefDl ?lead_coefMX => [p_monic|]; last first.\n  rewrite size_polyC size_mulX ?polyX_eq0// ltnS.\n  by rewrite (leq_trans (leq_b1 _)) ?size_poly_gt0.\nrewrite -[in RHS]IHp // /companionmx size_MXaddC (negPf p_neq0) /=.\nrewrite /char_poly polySpred //.\nhave [->|spV1_gt0] := posnP (size p).-1.\n  rewrite [X in \\det X]mx11_scalar det_scalar1 !mxE ?eqxx det_mx00.\n  by rewrite mul1r -horner_coef0 hornerMXaddC mulr0 add0r rmorphN opprK.\nrewrite (expand_det_col _ ord0) /= -[(size p).-1]prednK //.\nrewrite big_ord_recr big_ord_recl/= big1 ?add0r //=; last first.\n  move=> i _; rewrite !mxE -val_eqE /= /bump leq0n add1n eqSS.\n  by rewrite ltn_eqF ?subrr ?mul0r.\nrewrite !mxE ?subnn -horner_coef0 /= hornerMXaddC.\nrewrite !(eqxx, mulr0, add0r, addr0, subr0, rmorphN, opprK)/=.\nrewrite mulrC /cofactor; congr (_ * 'X + _).\n  rewrite /cofactor -signr_odd odd_add addbb mul1r; congr (\\det _).\n  apply/matrixP => i j; rewrite !mxE -val_eqE coefD coefMX coefC.\n  by rewrite /= /bump /= !add1n !eqSS addr0.\nrewrite /cofactor [X in \\det X](_ : _ = D _).\n  by rewrite detD /= addn0 -signr_odd -signr_addb addbb mulr1.\napply/matrixP=> i j; rewrite !mxE -!val_eqE /= /bump /=.\nby rewrite leqNgt ltn_ord add0n add1n [_ == _.-2.+1]ltn_eqF.\nQed.\n\nLemma mulmx_delta_companion (R : ringType) (p : seq R)\n  (i: 'I_(size p).-1) (i_small : i.+1 < (size p).-1):\n  delta_mx 0 i *m companionmx p = delta_mx 0 (Ordinal i_small) :> 'rV__.\nProof.\napply/rowP => j; rewrite !mxE (bigD1 i) //= ?(=^~val_eqE, mxE) /= eqxx mul1r.\nrewrite ltn_eqF ?big1 ?addr0 1?eq_sym //; last first.\n  by rewrite -ltnS prednK // (leq_trans  _ i_small).\nby move=> k /negPf ki_eqF; rewrite !mxE eqxx ki_eqF mul0r.\nQed.\n\nSection MinPoly.\n\nVariables (F : fieldType) (n' : nat).\nLocal Notation n := n'.+1.\nVariable A : 'M[F]_n.\nImplicit Types p q : {poly F}.\n\nFact degree_mxminpoly_proof : exists d, \\rank (powers_mx A d.+1) <= d.\nProof. by exists (n ^ 2)%N; rewrite rank_leq_col. Qed.\nDefinition degree_mxminpoly := ex_minn degree_mxminpoly_proof.\nLocal Notation d := degree_mxminpoly.\nLocal Notation Ad := (powers_mx A d).\n\nLemma mxminpoly_nonconstant : d > 0.\nProof.\nrewrite /d; case: ex_minnP; case=> //; rewrite leqn0 mxrank_eq0; move/eqP.\nmove/row_matrixP; move/(_ 0); move/eqP; rewrite rowK row0 mxvec_eq0.\nby rewrite -mxrank_eq0 mxrank1.\nQed.\n\nLemma minpoly_mx1 : (1%:M \\in Ad)%MS.\nProof.\nby apply: (eq_row_sub (Ordinal mxminpoly_nonconstant)); rewrite rowK.\nQed.\n\nLemma minpoly_mx_free : row_free Ad.\nProof.\nhave:= mxminpoly_nonconstant; rewrite /d; case: ex_minnP; case=> // d' _.\nmove/(_ d'); move/implyP; rewrite ltnn implybF -ltnS ltn_neqAle.\nby rewrite rank_leq_row andbT negbK.\nQed.\n\nLemma horner_mx_mem p : (horner_mx A p \\in Ad)%MS.\nProof.\nelim/poly_ind: p => [|p a IHp]; first by rewrite rmorph0 // linear0 sub0mx.\nrewrite rmorphD rmorphM /= horner_mx_C horner_mx_X.\nrewrite addrC -scalemx1 linearP /= -(mul_vec_lin (mulmxr_linear _ A)).\ncase/submxP: IHp => u ->{p}.\nhave: (powers_mx A (1 + d) <= Ad)%MS.\n  rewrite -(geq_leqif (mxrank_leqif_sup _)).\n    by rewrite (eqnP minpoly_mx_free) /d; case: ex_minnP.\n  rewrite addnC; apply/row_subP=> i.\n  by apply: eq_row_sub (lshift 1 i) _; rewrite !rowK.\napply: submx_trans; rewrite addmx_sub ?scalemx_sub //.\n  by apply: (eq_row_sub 0); rewrite rowK.\nrewrite -mulmxA mulmx_sub {u}//; apply/row_subP=> i.\nrewrite row_mul rowK mul_vec_lin /= mulmxE -exprSr.\nby apply: (eq_row_sub (rshift 1 i)); rewrite rowK.\nQed.\n\nDefinition mx_inv_horner B := rVpoly (mxvec B *m pinvmx Ad).\n\nLemma mx_inv_horner0 :  mx_inv_horner 0 = 0.\nProof. by rewrite /mx_inv_horner !(linear0, mul0mx). Qed.\n\nLemma mx_inv_hornerK B : (B \\in Ad)%MS -> horner_mx A (mx_inv_horner B) = B.\nProof. by move=> sBAd; rewrite horner_rVpoly mulmxKpV ?mxvecK. Qed.\n\nLemma minpoly_mxM B C : (B \\in Ad -> C \\in Ad -> B * C \\in Ad)%MS.\nProof.\nmove=> AdB AdC; rewrite -(mx_inv_hornerK AdB) -(mx_inv_hornerK AdC).\nby rewrite -rmorphM ?horner_mx_mem.\nQed.\n\nLemma minpoly_mx_ring : mxring Ad.\nProof.\napply/andP; split; first by apply/mulsmx_subP; apply: minpoly_mxM.\napply/mxring_idP; exists 1%:M; split=> *; rewrite ?mulmx1 ?mul1mx //.\n  by rewrite -mxrank_eq0 mxrank1.\nexact: minpoly_mx1.\nQed.\n\nDefinition mxminpoly := 'X^d - mx_inv_horner (A ^+ d).\nLocal Notation p_A := mxminpoly.\n\nLemma size_mxminpoly : size p_A = d.+1.\nProof. by rewrite size_addl ?size_polyXn // size_opp ltnS size_poly. Qed.\n\nLemma mxminpoly_monic : p_A \\is monic.\nProof.\nrewrite monicE /lead_coef size_mxminpoly coefB coefXn eqxx /=.\nby rewrite nth_default ?size_poly // subr0.\nQed.\n\nLemma size_mod_mxminpoly p : size (p %% p_A) <= d.\nProof.\nby rewrite -ltnS -size_mxminpoly ltn_modp // -size_poly_eq0 size_mxminpoly.\nQed.\n\nLemma mx_root_minpoly : horner_mx A p_A = 0.\nProof.\nrewrite rmorphB -{3}(horner_mx_X A) -rmorphX /=.\nby rewrite mx_inv_hornerK ?subrr ?horner_mx_mem.\nQed.\n\nLemma horner_rVpolyK (u : 'rV_d) :\n  mx_inv_horner (horner_mx A (rVpoly u)) = rVpoly u.\nProof.\ncongr rVpoly; rewrite horner_rVpoly vec_mxK.\nby apply: (row_free_inj minpoly_mx_free); rewrite mulmxKpV ?submxMl.\nQed.\n\nLemma horner_mxK p : mx_inv_horner (horner_mx A p) = p %% p_A.\nProof.\nrewrite {1}(Pdiv.IdomainMonic.divp_eq mxminpoly_monic p) rmorphD rmorphM /=.\nrewrite mx_root_minpoly mulr0 add0r.\nby rewrite -(poly_rV_K (size_mod_mxminpoly _)) horner_rVpolyK.\nQed.\n\nLemma mxminpoly_min p : horner_mx A p = 0 -> p_A %| p.\nProof. by move=> pA0; rewrite /dvdp -horner_mxK pA0 mx_inv_horner0. Qed.\n\nLemma horner_rVpoly_inj : injective (horner_mx A \\o rVpoly : 'rV_d -> 'M_n).\nProof.\napply: can_inj (poly_rV \\o mx_inv_horner) _ => u /=.\nby rewrite horner_rVpolyK rVpolyK.\nQed.\n\nLemma mxminpoly_linear_is_scalar : (d <= 1) = is_scalar_mx A.\nProof.\nhave scalP := has_non_scalar_mxP minpoly_mx1.\nrewrite leqNgt -(eqnP minpoly_mx_free); apply/scalP/idP=> [|[[B]]].\n  case scalA: (is_scalar_mx A); [by right | left].\n  by exists A; rewrite ?scalA // -{1}(horner_mx_X A) horner_mx_mem.\nmove/mx_inv_hornerK=> <- nsB; case/is_scalar_mxP=> a defA; case/negP: nsB.\nmove: {B}(_ B); apply: poly_ind => [|p c].\n  by rewrite rmorph0 ?mx0_is_scalar.\nrewrite rmorphD ?rmorphM /= horner_mx_X defA; case/is_scalar_mxP=> b ->.\nby rewrite -rmorphM horner_mx_C -rmorphD /= scalar_mx_is_scalar.\nQed.\n\nLemma mxminpoly_dvd_char : p_A %| char_poly A.\nProof. by apply: mxminpoly_min; apply: Cayley_Hamilton. Qed.\n\nLemma eigenvalue_root_min a : eigenvalue A a = root p_A a.\nProof.\napply/idP/idP=> Aa; last first.\n  rewrite eigenvalue_root_char !root_factor_theorem in Aa *.\n  exact: dvdp_trans Aa mxminpoly_dvd_char.\nhave{Aa} [v Av_av v_nz] := eigenvalueP Aa.\napply: contraR v_nz => pa_nz; rewrite -{pa_nz}(eqmx_eq0 (eqmx_scale _ pa_nz)).\napply/eqP; rewrite -(mulmx0 _ v) -mx_root_minpoly.\nelim/poly_ind: p_A => [|p c IHp].\n  by rewrite rmorph0 horner0 scale0r mulmx0.\nrewrite !hornerE rmorphD rmorphM /= horner_mx_X horner_mx_C scalerDl.\nby rewrite -scalerA mulmxDr mul_mx_scalar mulmxA -IHp -scalemxAl Av_av.\nQed.\n\nEnd MinPoly.\n\nPrenex Implicits degree_mxminpoly mxminpoly mx_inv_horner.\n\nArguments mx_inv_hornerK {F n' A} [B] AnB.\nArguments horner_rVpoly_inj {F n' A} [u1 u2] eq_u12A : rename.\n          \n(* Parametricity. *)\nSection MapRingMatrix.\n\nVariables (aR rR : ringType) (f : {rmorphism aR -> rR}).\nLocal Notation \"A ^f\" := (map_mx (GRing.RMorphism.apply f) A) : ring_scope.\nLocal Notation fp := (map_poly (GRing.RMorphism.apply f)).\nVariables (d n : nat) (A : 'M[aR]_n).\n\nLemma map_rVpoly (u : 'rV_d) : fp (rVpoly u) = rVpoly u^f.\nProof.\napply/polyP=> k; rewrite coef_map !coef_rVpoly.\nby case: (insub k) => [i|]; rewrite /=  ?rmorph0 // mxE.\nQed.\n\nLemma map_poly_rV p : (poly_rV p)^f = poly_rV (fp p) :> 'rV_d.\nProof. by apply/rowP=> j; rewrite !mxE coef_map. Qed.\n\nLemma map_char_poly_mx : map_mx fp (char_poly_mx A) = char_poly_mx A^f.\nProof.\nrewrite raddfB /= map_scalar_mx /= map_polyX; congr (_ - _).\nby apply/matrixP=> i j; rewrite !mxE map_polyC.\nQed.\n\nLemma map_char_poly : fp (char_poly A) = char_poly A^f.\nProof. by rewrite -det_map_mx map_char_poly_mx. Qed.\n\nEnd MapRingMatrix.\n\nSection MapResultant.\n\nLemma map_resultant (aR rR : ringType) (f : {rmorphism {poly aR} -> rR}) p q :\n    f (lead_coef p) != 0 -> f (lead_coef q) != 0 ->\n  f (resultant p q)= resultant (map_poly f p) (map_poly f q).\nProof.\nmove=> nz_fp nz_fq; rewrite /resultant /Sylvester_mx !size_map_poly_id0 //.\nrewrite -det_map_mx /= map_col_mx; congr (\\det (col_mx _ _));\n  by apply: map_lin1_mx => v; rewrite map_poly_rV rmorphM /= map_rVpoly.\nQed.\n\nEnd MapResultant.\n\nSection MapComRing.\n\nVariables (aR rR : comRingType) (f : {rmorphism aR -> rR}).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\nLocal Notation fp := (map_poly f).\nVariables (n' : nat) (A : 'M[aR]_n'.+1).\n\nLemma map_powers_mx e : (powers_mx A e)^f = powers_mx A^f e.\nProof. by apply/row_matrixP=> i; rewrite -map_row !rowK map_mxvec rmorphX. Qed.\n\nLemma map_horner_mx p : (horner_mx A p)^f = horner_mx A^f (fp p).\nProof.\nrewrite -[p](poly_rV_K (leqnn _)) map_rVpoly.\nby rewrite !horner_rVpoly map_vec_mx map_mxM map_powers_mx.\nQed.\n\nEnd MapComRing.\n\nSection MapField.\n\nVariables (aF rF : fieldType) (f : {rmorphism aF -> rF}).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\nLocal Notation fp := (map_poly f).\nVariables (n' : nat) (A : 'M[aF]_n'.+1) (p : {poly aF}).\n\nLemma map_mx_companion (e := congr1 predn (size_map_poly _ _)) :\n  (companionmx p)^f = castmx (e, e) (companionmx (fp p)).\nProof.\napply/matrixP => i j; rewrite !(castmxE, mxE) /= (fun_if f).\nby rewrite rmorphN coef_map size_map_poly rmorph_nat.\nQed.\n\nLemma companion_map_poly (e := esym (congr1 predn (size_map_poly _ _))) :\n  companionmx (fp p) = castmx (e, e) (companionmx p)^f.\nProof. by rewrite map_mx_companion castmx_comp castmx_id. Qed.\n\nLemma degree_mxminpoly_map : degree_mxminpoly A^f = degree_mxminpoly A.\nProof. by apply: eq_ex_minn => e; rewrite -map_powers_mx mxrank_map. Qed.\n\nLemma mxminpoly_map : mxminpoly A^f = fp (mxminpoly A).\nProof.\nrewrite rmorphB; congr (_ - _).\n  by rewrite /= map_polyXn degree_mxminpoly_map.\nrewrite degree_mxminpoly_map -rmorphX /=.\napply/polyP=> i; rewrite coef_map //= !coef_rVpoly degree_mxminpoly_map.\ncase/insub: i => [i|]; last by rewrite rmorph0.\nby rewrite -map_powers_mx -map_pinvmx // -map_mxvec -map_mxM // mxE.\nQed.\n\nLemma map_mx_inv_horner u : fp (mx_inv_horner A u) = mx_inv_horner A^f u^f.\nProof.\nrewrite map_rVpoly map_mxM map_mxvec map_pinvmx map_powers_mx.\nby rewrite /mx_inv_horner degree_mxminpoly_map.\nQed.\n\nEnd MapField.\n\nSection IntegralOverRing.\n\nDefinition integralOver (R K : ringType) (RtoK : R -> K) (z : K) :=\n  exists2 p, p \\is monic & root (map_poly RtoK p) z.\n\nDefinition integralRange R K RtoK := forall z, @integralOver R K RtoK z.\n\nVariables (B R K : ringType) (BtoR : B -> R) (RtoK : {rmorphism R -> K}).\n\nLemma integral_rmorph x :\n  integralOver BtoR x -> integralOver (RtoK \\o BtoR) (RtoK x).\nProof. by case=> p; exists p; rewrite // map_poly_comp rmorph_root. Qed.\n\nLemma integral_id x : integralOver RtoK (RtoK x).\nProof. by exists ('X - x%:P); rewrite ?monicXsubC ?rmorph_root ?root_XsubC. Qed.\n\nLemma integral_nat n : integralOver RtoK n%:R.\nProof. by rewrite -(rmorph_nat RtoK); apply: integral_id. Qed.\n\nLemma integral0 : integralOver RtoK 0. Proof. exact: (integral_nat 0). Qed.\n\nLemma integral1 : integralOver RtoK 1. Proof. exact: (integral_nat 1). Qed.\n\nLemma integral_poly (p : {poly K}) :\n  (forall i, integralOver RtoK p`_i) <-> {in p : seq K, integralRange RtoK}.\nProof.\nsplit=> intRp => [_ /(nthP 0)[i _ <-] // | i]; rewrite -[p]coefK coef_poly.\nby case: ifP => [ltip | _]; [apply/intRp/mem_nth | apply: integral0].\nQed.\n\nEnd IntegralOverRing.\n\nSection IntegralOverComRing.\n\nVariables (R K : comRingType) (RtoK : {rmorphism R -> K}).\n\nLemma integral_horner_root w (p q : {poly K}) :\n    p \\is monic -> root p w ->\n    {in p : seq K, integralRange RtoK} -> {in q : seq K, integralRange RtoK} ->\n  integralOver RtoK q.[w].\nProof.\nmove=> mon_p pw0 intRp intRq.\npose memR y := exists x, y = RtoK x.\nhave memRid x: memR (RtoK x) by exists x.\nhave memR_nat n: memR n%:R by rewrite -(rmorph_nat RtoK).\nhave [memR0 memR1]: memR 0 * memR 1 := (memR_nat 0%N, memR_nat 1%N).\nhave memRN1: memR (- 1) by exists (- 1); rewrite rmorphN1.\npose rVin (E : K -> Prop) n (a : 'rV[K]_n) := forall i, E (a 0 i).\npose pXin (E : K -> Prop) (r : {poly K}) := forall i, E r`_i.\npose memM E n (X : 'rV_n) y := exists a, rVin E n a /\\ y = (a *m X^T) 0 0.\npose finM E S := exists n, exists X, forall y, memM E n X y <-> S y.\nhave tensorM E n1 n2 X Y: finM E (memM (memM E n2 Y) n1 X).\n  exists (n1 * n2)%N, (mxvec (X^T *m Y)) => y.\n  split=> [[a [Ea Dy]] | [a1 [/fin_all_exists[a /all_and2[Ea Da1]] ->]]].\n    exists (Y *m (vec_mx a)^T); split=> [i|].\n      exists (row i (vec_mx a)); split=> [j|]; first by rewrite !mxE; apply: Ea.\n      by rewrite -row_mul -{1}[Y]trmxK -trmx_mul !mxE.\n    by rewrite -[Y]trmxK -!trmx_mul mulmxA -mxvec_dotmul trmx_mul trmxK vec_mxK.\n  exists (mxvec (\\matrix_i a i)); split.\n    by case/mxvec_indexP=> i j; rewrite mxvecE mxE; apply: Ea.\n  rewrite -[mxvec _]trmxK -trmx_mul mxvec_dotmul -mulmxA trmx_mul !mxE.\n  apply: eq_bigr => i _; rewrite Da1 !mxE; congr (_ * _).\n  by apply: eq_bigr => j _; rewrite !mxE.\nsuffices [m [X [[u [_ Du]] idealM]]]: exists m,\n  exists X, let M := memM memR m X in M 1 /\\ forall y, M y -> M (q.[w] * y).\n- do [set M := memM _ m X; move: q.[w] => z] in idealM *.\n  have MX i: M (X 0 i).\n    by exists (delta_mx 0 i); split=> [j|]; rewrite -?rowE !mxE.\n  have /fin_all_exists[a /all_and2[Fa Da1]] i := idealM _ (MX i).\n  have /fin_all_exists[r Dr] i := fin_all_exists (Fa i).\n  pose A := \\matrix_(i, j) r j i; pose B := z%:M - map_mx RtoK A.\n  have XB0: X *m B = 0.\n    apply/eqP; rewrite mulmxBr mul_mx_scalar subr_eq0; apply/eqP/rowP=> i.\n    by rewrite !mxE Da1 mxE; apply: eq_bigr=> j _; rewrite !mxE mulrC Dr.\n  exists (char_poly A); first exact: char_poly_monic.\n  have: (\\det B *: (u *m X^T)) 0 0 == 0.\n    rewrite scalemxAr -linearZ -mul_mx_scalar -mul_mx_adj mulmxA XB0 /=.\n    by rewrite mul0mx trmx0 mulmx0 mxE.\n  rewrite mxE -Du mulr1 rootE -horner_evalE -!det_map_mx; congr (\\det _ == 0).\n  rewrite !raddfB /= !map_scalar_mx /= map_polyX horner_evalE hornerX.\n  by apply/matrixP=> i j; rewrite !mxE map_polyC /horner_eval hornerC.\npose gen1 x E y := exists2 r, pXin E r & y = r.[x]; pose gen := foldr gen1 memR.\nhave gen1S (E : K -> Prop) x y: E 0 -> E y -> gen1 x E y.\n  by exists y%:P => [i|]; rewrite ?hornerC ?coefC //; case: ifP.\nhave genR S y: memR y -> gen S y.\n  by elim: S => //= x S IH in y * => /IH; apply: gen1S; apply: IH.\nhave gen0 := genR _ 0 memR0; have gen_1 := genR _ 1 memR1.\nhave{gen1S} genS S y: y \\in S -> gen S y.\n  elim: S => //= x S IH /predU1P[-> | /IH//]; last exact: gen1S.\n  by exists 'X => [i|]; rewrite ?hornerX // coefX; apply: genR.\npose propD (R : K -> Prop) := forall x y, R x -> R y -> R (x + y).\nhave memRD: propD memR.\n  by move=> _ _ [a ->] [b ->]; exists (a + b); rewrite rmorphD.\nhave genD S: propD (gen S).\n  elim: S => //= x S IH _ _ [r1 Sr1 ->] [r2 Sr2 ->]; rewrite -hornerD.\n  by exists (r1 + r2) => // i; rewrite coefD; apply: IH.\nhave gen_sum S := big_ind _ (gen0 S) (genD S).\npose propM (R : K -> Prop) := forall x y, R x -> R y -> R (x * y).\nhave memRM: propM memR.\n  by move=> _ _ [a ->] [b ->]; exists (a * b); rewrite rmorphM.\nhave genM S: propM (gen S).\n  elim: S => //= x S IH _ _ [r1 Sr1 ->] [r2 Sr2 ->]; rewrite -hornerM.\n  by exists (r1 * r2) => // i; rewrite coefM; apply: gen_sum => j _; apply: IH.\nhave gen_horner S r y: pXin (gen S) r -> gen S y -> gen S r.[y].\n  move=> Sq Sy; rewrite horner_coef; apply: gen_sum => [[i _] /= _].\n  by elim: {2}i => [|n IHn]; rewrite ?mulr1 // exprSr mulrA; apply: genM.\npose S := w :: q ++ p; suffices [m [X defX]]: finM memR (gen S).\n  exists m, X => M; split=> [|y /defX Xy]; first exact/defX.\n  apply/defX/genM => //; apply: gen_horner => // [i|]; last exact/genS/mem_head.\n  rewrite -[q]coefK coef_poly; case: ifP => // lt_i_q.\n  by apply: genS; rewrite inE mem_cat mem_nth ?orbT.\npose intR R y := exists r, [/\\ r \\is monic, root r y & pXin R r].\npose fix genI s := if s is y :: s1 then intR (gen s1) y /\\ genI s1 else True.\nhave{mon_p pw0 intRp intRq}: genI S.\n  split; set S1 := _ ++ _; first exists p.\n    split=> // i; rewrite -[p]coefK coef_poly; case: ifP => // lt_i_p.\n    by apply: genS; rewrite mem_cat orbC mem_nth.\n  set S2 := S1; have: all (mem S1) S2 by apply/allP.\n  elim: S2 => //= y S2 IH /andP[S1y S12]; split; last exact: IH.\n  have{q S S1 IH S1y S12 intRp intRq} [q mon_q qx0]: integralOver RtoK y.\n    by move: S1y; rewrite mem_cat => /orP[]; [apply: intRq | apply: intRp].\n  exists (map_poly RtoK q); split=> // [|i]; first exact: monic_map.\n  by rewrite coef_map /=; apply: genR.\nelim: {w p q}S => /= [_|x S IH [[p [mon_p px0 Sp]] /IH{IH}[m2 [X2 defS]]]].\n  exists 1%N, 1 => y; split=> [[a [Fa ->]] | Fy].\n    by rewrite tr_scalar_mx mulmx1; apply: Fa.\n  by exists y%:M; split=> [i|]; rewrite 1?ord1 ?tr_scalar_mx ?mulmx1 mxE.\npose m1 := (size p).-1; pose X1 := \\row_(i < m1) x ^+ i.\nhave [m [X defM]] := tensorM memR m1 m2 X1 X2; set M := memM _ _ _ in defM.\nexists m, X => y; rewrite -/M; split=> [/defM[a [M2a]] | [q Sq]] -> {y}.\n  exists (rVpoly a) => [i|].\n    by rewrite coef_rVpoly; case/insub: i => // i; apply/defS/M2a.\n  rewrite mxE (horner_coef_wide _ (size_poly _ _)) -/(rVpoly a).\n  by apply: eq_bigr => i _; rewrite coef_rVpoly_ord !mxE.\nhave M_0: M 0 by exists 0; split=> [i|]; rewrite ?mul0mx mxE.\nhave M_D: propD M.\n  move=> _ _ [a [Fa ->]] [b [Fb ->]]; exists (a + b).\n  by rewrite mulmxDl !mxE; split=> // i; rewrite mxE; apply: memRD.\nhave{M_0 M_D} Msum := big_ind _ M_0 M_D.\nrewrite horner_coef; apply: (Msum) => i _; case: i q`_i {Sq}(Sq i) => /=.\nelim: {q}(size q) => // n IHn i i_le_n y Sy.\nhave [i_lt_m1 | m1_le_i] := ltnP i m1.\n  apply/defM; exists (y *: delta_mx 0 (Ordinal i_lt_m1)); split=> [j|].\n    by apply/defS; rewrite !mxE /= mulr_natr; case: eqP.\n  by rewrite -scalemxAl -rowE !mxE.\nrewrite -(subnK m1_le_i) exprD -[x ^+ m1]subr0 -(rootP px0) horner_coef.\nrewrite polySpred ?monic_neq0 // -/m1 big_ord_recr /= -lead_coefE.\nrewrite opprD addrC (monicP mon_p) mul1r subrK !mulrN -mulNr !mulr_sumr.\napply: Msum => j _; rewrite mulrA mulrACA -exprD; apply: IHn.\n  by rewrite -addnS addnC addnBA // leq_subLR leq_add.\nby rewrite -mulN1r; do 2!apply: (genM) => //; apply: genR.\nQed.\n\nLemma integral_root_monic u p :\n    p \\is monic -> root p u -> {in p : seq K, integralRange RtoK} ->\n  integralOver RtoK u.\nProof.\nmove=> mon_p pu0 intRp; rewrite -[u]hornerX.\napply: integral_horner_root mon_p pu0 intRp _.\nby apply/integral_poly => i; rewrite coefX; apply: integral_nat.\nQed.\n\nHint Resolve (integral0 RtoK) (integral1 RtoK) (@monicXsubC K) : core.\n\nLet XsubC0 (u : K) : root ('X - u%:P) u. Proof. by rewrite root_XsubC. Qed.\nLet intR_XsubC u :\n  integralOver RtoK (- u) -> {in 'X - u%:P : seq K, integralRange RtoK}.\nProof. by move=> intRu v; rewrite polyseqXsubC !inE => /pred2P[]->. Qed.\n\nLemma integral_opp u : integralOver RtoK u -> integralOver RtoK (- u).\nProof. by rewrite -{1}[u]opprK => /intR_XsubC/integral_root_monic; apply. Qed.\n\nLemma integral_horner (p : {poly K}) u :\n    {in p : seq K, integralRange RtoK} -> integralOver RtoK u ->\n  integralOver RtoK p.[u].\nProof. by move=> ? /integral_opp/intR_XsubC/integral_horner_root; apply. Qed.\n\nLemma integral_sub u v :\n  integralOver RtoK u -> integralOver RtoK v -> integralOver RtoK (u - v).\nProof.\nmove=> intRu /integral_opp/intR_XsubC/integral_horner/(_ intRu).\nby rewrite !hornerE.\nQed.\n\nLemma integral_add u v :\n  integralOver RtoK u -> integralOver RtoK v -> integralOver RtoK (u + v).\nProof. by rewrite -{2}[v]opprK => intRu /integral_opp; apply: integral_sub. Qed.\n\nLemma integral_mul u v :\n  integralOver RtoK u -> integralOver RtoK v -> integralOver RtoK (u * v).\nProof.\nrewrite -{2}[v]hornerX -hornerZ => intRu; apply: integral_horner.\nby apply/integral_poly=> i; rewrite coefZ coefX mulr_natr mulrb; case: ifP.\nQed.\n\nEnd IntegralOverComRing.\n\nSection IntegralOverField.\n\nVariables (F E : fieldType) (FtoE : {rmorphism F -> E}).\n\nDefinition algebraicOver (fFtoE : F -> E) u :=\n  exists2 p, p != 0 & root (map_poly fFtoE p) u.\n\nNotation mk_mon p := ((lead_coef p)^-1 *: p).\n\nLemma integral_algebraic u : algebraicOver FtoE u <-> integralOver FtoE u.\nProof.\nsplit=> [] [p p_nz pu0]; last by exists p; rewrite ?monic_neq0.\nexists (mk_mon p); first by rewrite monicE lead_coefZ mulVf ?lead_coef_eq0.\nby rewrite linearZ rootE hornerZ (rootP pu0) mulr0.\nQed.\n\nLemma algebraic_id a : algebraicOver FtoE (FtoE a).\nProof. exact/integral_algebraic/integral_id. Qed.\n\nLemma algebraic0 : algebraicOver FtoE 0.\nProof. exact/integral_algebraic/integral0. Qed.\n\nLemma algebraic1 : algebraicOver FtoE 1.\nProof. exact/integral_algebraic/integral1. Qed.\n\nLemma algebraic_opp x : algebraicOver FtoE x -> algebraicOver FtoE (- x).\nProof. by move/integral_algebraic/integral_opp/integral_algebraic. Qed.\n\nLemma algebraic_add x y :\n  algebraicOver FtoE x -> algebraicOver FtoE y -> algebraicOver FtoE (x + y).\nProof.\nmove/integral_algebraic=> intFx /integral_algebraic intFy.\nexact/integral_algebraic/integral_add.\nQed.\n\nLemma algebraic_sub x y :\n  algebraicOver FtoE x -> algebraicOver FtoE y -> algebraicOver FtoE (x - y).\nProof. by move=> algFx /algebraic_opp; apply: algebraic_add. Qed.\n\nLemma algebraic_mul x y :\n  algebraicOver FtoE x -> algebraicOver FtoE y -> algebraicOver FtoE (x * y).\nProof.\nmove/integral_algebraic=> intFx /integral_algebraic intFy.\nexact/integral_algebraic/integral_mul.\nQed.\n\nLemma algebraic_inv u : algebraicOver FtoE u -> algebraicOver FtoE u^-1.\nProof.\nhave [-> | /expf_neq0 nz_u_n] := eqVneq u 0; first by rewrite invr0.\ncase=> p nz_p pu0; exists (Poly (rev p)).\n  apply/eqP=> /polyP/(_ 0%N); rewrite coef_Poly coef0 nth_rev ?size_poly_gt0 //.\n  by apply/eqP; rewrite subn1 lead_coef_eq0.\napply/eqP/(mulfI (nz_u_n (size p).-1)); rewrite mulr0 -(rootP pu0).\nrewrite (@horner_coef_wide _ (size p)); last first.\n  by rewrite size_map_poly -(size_rev p) size_Poly.\nrewrite horner_coef mulr_sumr size_map_poly.\nrewrite [rhs in _ = rhs](reindex_inj rev_ord_inj) /=.\napply: eq_bigr => i _; rewrite !coef_map coef_Poly nth_rev // mulrCA.\nby congr (_ * _); rewrite -{1}(subnKC (valP i)) addSn addnC exprD exprVn ?mulfK.\nQed.\n\nLemma algebraic_div x y :\n  algebraicOver FtoE x -> algebraicOver FtoE y -> algebraicOver FtoE (x / y).\nProof. by move=> algFx /algebraic_inv; apply: algebraic_mul. Qed.\n\nLemma integral_inv x : integralOver FtoE x -> integralOver FtoE x^-1.\nProof. by move/integral_algebraic/algebraic_inv/integral_algebraic. Qed.\n\nLemma integral_div x y :\n  integralOver FtoE x -> integralOver FtoE y -> integralOver FtoE (x / y).\nProof. by move=> algFx /integral_inv; apply: integral_mul. Qed.\n\nLemma integral_root p u :\n    p != 0 -> root p u -> {in p : seq E, integralRange FtoE} ->\n  integralOver FtoE u.\nProof.\nmove=> nz_p pu0 algFp.\nhave mon_p1: mk_mon p \\is monic.\n  by rewrite monicE lead_coefZ mulVf ?lead_coef_eq0.\nhave p1u0: root (mk_mon p) u by rewrite rootE hornerZ (rootP pu0) mulr0.\napply: integral_root_monic mon_p1 p1u0 _ => _ /(nthP 0)[i ltip <-].\nrewrite coefZ mulrC; rewrite size_scale ?invr_eq0 ?lead_coef_eq0 // in ltip.\nby apply: integral_div; apply/algFp/mem_nth; rewrite -?polySpred.\nQed.\n\nEnd IntegralOverField.\n\n(* Lifting term, formula, envs and eval to matrices. Wlog, and for the sake  *)\n(* of simplicity, we only lift (tensor) envs to row vectors; we can always   *)\n(* use mxvec/vec_mx to store and retrieve matrices.                          *)\n(* We don't provide definitions for addition, subtraction, scaling, etc,     *)\n(* because they have simple matrix expressions.                              *)\nModule MatrixFormula.\n\nSection MatrixFormula.\n\nVariable F : fieldType.\n\nLocal Notation False := GRing.False.\nLocal Notation True := GRing.True.\nLocal Notation And := GRing.And (only parsing).\nLocal Notation Add := GRing.Add (only parsing).\nLocal Notation Bool b := (GRing.Bool b%bool).\nLocal Notation term := (GRing.term F).\nLocal Notation form := (GRing.formula F).\nLocal Notation eval := GRing.eval.\nLocal Notation holds := GRing.holds.\nLocal Notation qf_form := GRing.qf_form.\nLocal Notation qf_eval := GRing.qf_eval.\n\nDefinition eval_mx (e : seq F) := @map_mx term F (eval e).\n\nDefinition mx_term := @map_mx F term GRing.Const.\n\nLemma eval_mx_term e m n (A : 'M_(m, n)) : eval_mx e (mx_term A) = A.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nDefinition mulmx_term m n p (A : 'M[term]_(m, n)) (B : 'M_(n, p)) :=\n  \\matrix_(i, k) (\\big[Add/0]_j (A i j * B j k))%T.\n\nLemma eval_mulmx e m n p (A : 'M[term]_(m, n)) (B : 'M_(n, p)) :\n  eval_mx e (mulmx_term A B) = eval_mx e A *m eval_mx e B.\nProof.\napply/matrixP=> i k; rewrite !mxE /= ((big_morph (eval e)) 0 +%R) //=.\nby apply: eq_bigr => j _; rewrite /= !mxE.\nQed.\n\nLocal Notation morphAnd f := ((big_morph f) true andb).\n\nLet Schur m n (A : 'M[term]_(1 + m, 1 + n)) (a := A 0 0) :=\n  \\matrix_(i, j) (drsubmx A i j - a^-1 * dlsubmx A i 0%R * ursubmx A 0%R j)%T.\n\nFixpoint mxrank_form (r m n : nat) : 'M_(m, n) -> form :=\n  match m, n return 'M_(m, n) -> form with\n  | m'.+1, n'.+1 => fun A : 'M_(1 + m', 1 + n') =>\n    let nzA k := A k.1 k.2 != 0 in\n    let xSchur k := Schur (xrow k.1 0%R (xcol k.2 0%R A)) in\n    let recf k := Bool (r > 0) /\\ mxrank_form r.-1 (xSchur k) in\n    GRing.Pick nzA recf (Bool (r == 0%N))\n  | _, _ => fun _ => Bool (r == 0%N)\n  end%T.\n\nLemma mxrank_form_qf r m n (A : 'M_(m, n)) : qf_form (mxrank_form r A).\nProof.\nby elim: m r n A => [|m IHm] r [|n] A //=; rewrite GRing.Pick_form_qf /=.\nQed.\n\nLemma eval_mxrank e r m n (A : 'M_(m, n)) :\n  qf_eval e (mxrank_form r A) = (\\rank (eval_mx e A) == r).\nProof.\nelim: m r n A => [|m IHm] r [|n] A /=; try by case r.\nrewrite GRing.eval_Pick /mxrank unlock /=; set pf := fun _ => _.\nrewrite -(@eq_pick _ pf) => [|k]; rewrite {}/pf ?mxE // eq_sym.\ncase: pick => [[i j]|] //=; set B := _ - _; have:= mxrankE B.\ncase: (Gaussian_elimination B) r => [[_ _] _] [|r] //= <-; rewrite {}IHm eqSS.\nby congr (\\rank _ == r); apply/matrixP=> k l; rewrite !(mxE, big_ord1) !tpermR.\nQed.\n\nLemma eval_vec_mx e m n (u : 'rV_(m * n)) :\n  eval_mx e (vec_mx u) = vec_mx (eval_mx e u).\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma eval_mxvec e m n (A : 'M_(m, n)) :\n  eval_mx e (mxvec A) = mxvec (eval_mx e A).\nProof. by rewrite -{2}[A]mxvecK eval_vec_mx vec_mxK. Qed.\n\nSection Subsetmx.\n\nVariables (m1 m2 n : nat) (A : 'M[term]_(m1, n)) (B : 'M[term]_(m2, n)).\n\nDefinition submx_form :=\n  \\big[And/True]_(r < n.+1) (mxrank_form r (col_mx A B) ==> mxrank_form r B)%T.\n\nLemma eval_col_mx e :\n  eval_mx e (col_mx A B) = col_mx (eval_mx e A) (eval_mx e B).\nProof. by apply/matrixP=> i j; do 2![rewrite !mxE //; case: split => ?]. Qed.\n\nLemma submx_form_qf : qf_form submx_form.\nProof.\nby rewrite (morphAnd (@qf_form _)) ?big1 //= => r _; rewrite !mxrank_form_qf.\nQed.\n\nLemma eval_submx e : qf_eval e submx_form = (eval_mx e A <= eval_mx e B)%MS.\nProof.\nrewrite (morphAnd (qf_eval e)) //= big_andE /=.\napply/forallP/idP=> /= [|sAB d]; last first.\n  rewrite !eval_mxrank eval_col_mx -addsmxE; apply/implyP=> /eqP <-.\n  by rewrite mxrank_leqif_sup ?addsmxSr // addsmx_sub sAB /=.\nmove/(_ (inord (\\rank (eval_mx e (col_mx A B))))).\nrewrite inordK ?ltnS ?rank_leq_col // !eval_mxrank eqxx /= eval_col_mx.\nby rewrite -addsmxE mxrank_leqif_sup ?addsmxSr // addsmx_sub; case/andP.\nQed.\n\nEnd Subsetmx.\n\nSection Env.\n\nVariable d : nat.\n\nDefinition seq_of_rV (v : 'rV_d) : seq F := fgraph [ffun i => v 0 i].\n\nLemma size_seq_of_rV v : size (seq_of_rV v) = d.\nProof. by rewrite tuple.size_tuple card_ord. Qed.\n\nLemma nth_seq_of_rV x0 v (i : 'I_d) : nth x0 (seq_of_rV v) i = v 0 i.\nProof. by rewrite nth_fgraph_ord ffunE. Qed.\n\nDefinition row_var k : 'rV[term]_d := \\row_i ('X_(k * d + i))%T.\n\nDefinition row_env (e : seq 'rV_d) := flatten (map seq_of_rV e).\n\nLemma nth_row_env e k (i : 'I_d) : (row_env e)`_(k * d + i) = e`_k 0 i.\nProof.\nelim: e k => [|v e IHe] k; first by rewrite !nth_nil mxE.\nrewrite /row_env /= nth_cat size_seq_of_rV.\ncase: k => [|k]; first by rewrite (valP i) nth_seq_of_rV.\nby rewrite mulSn -addnA -if_neg -leqNgt leq_addr addKn IHe.\nQed.\n\nLemma eval_row_var e k : eval_mx (row_env e) (row_var k) = e`_k :> 'rV_d.\nProof. by apply/rowP=> i; rewrite !mxE /= nth_row_env. Qed.\n\nDefinition Exists_row_form k (f : form) :=\n  foldr GRing.Exists f (codom (fun i : 'I_d => k * d + i)%N).\n\nLemma Exists_rowP e k f :\n  d > 0 ->\n   ((exists v : 'rV[F]_d, holds (row_env (set_nth 0 e k v)) f)\n      <-> holds (row_env e) (Exists_row_form k f)).\nProof.\nmove=> d_gt0; pose i_ j := Ordinal (ltn_pmod j d_gt0).\nhave d_eq j: (j = j %/ d * d + i_ j)%N := divn_eq j d.\nsplit=> [[v f_v] | ]; last case/GRing.foldExistsP=> e' ee' f_e'.\n  apply/GRing.foldExistsP; exists (row_env (set_nth 0 e k v)) => {f f_v}// j.\n  rewrite [j]d_eq !nth_row_env nth_set_nth /=; case: eqP => // ->.\n  by case/imageP; exists (i_ j).\nexists (\\row_i e'`_(k * d + i)); apply: eq_holds f_e' => j /=.\nmove/(_ j): ee'; rewrite [j]d_eq !nth_row_env nth_set_nth /=.\ncase: eqP => [-> | ne_j_k -> //]; first by rewrite mxE.\napply/mapP=> [[r lt_r_d]]; rewrite -d_eq => def_j; case: ne_j_k.\nby rewrite def_j divnMDl // divn_small ?addn0.\nQed.\n\nEnd Env.\n\nEnd MatrixFormula.\n\nEnd MatrixFormula.\n", "meta": {"author": "gares", "repo": "mathcomp", "sha": "f4ea1abac523107baf16e3cf528752b22ad8fdb5", "save_path": "github-repos/coq/gares-mathcomp", "path": "github-repos/coq/gares-mathcomp/mathcomp-f4ea1abac523107baf16e3cf528752b22ad8fdb5/mathcomp/algebra/mxpoly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6771862219208029}}
{"text": "\nDefinition tautology : forall P : Prop, P -> P\n  := fun P x => x.\n\n\nDefinition Modus_tollens : forall P Q : Prop, ~Q /\\ (P -> Q) -> ~P\n  := (fun (P Q : Prop) (H : (Q -> False) /\\ (P -> Q)) (H0 : P) =>\n match H with\n | conj H1 H2 => H1 (H2 H0)\n end).\n\nDefinition Disjunctive_syllogism : forall P Q : Prop, (P \\/ Q) -> ~P -> Q\n  := (fun (P Q : Prop) (H : P \\/ Q) (H0 : P -> False) =>\n match H with\n | or_introl H1 => match H0 H1 return Q with\n                   end\n | or_intror H1 => H1\n end).\n\nDefinition tautology_on_Set : forall A : Set, A -> A\n  := (fun (A : Set) (H : A) => H).\n\nDefinition Modus_tollens_on_Set : forall A B : Set, (B -> Empty_set) * (A -> B) -> (A -> Empty_set)\n  := (fun (A B : Set) (H : (B -> Empty_set) * (A -> B)) (H0 : A) =>\n let (e, b) := H in e (b H0)).\n\nDefinition Disjunctive_syllogism_on_Set : forall A B : Set, (A + B) -> (A -> Empty_set) -> B\n  := (fun (A B : Set) (H : A + B) (H0 : A -> Empty_set) =>\n match H with\n | inl a => match H0 a return B with\n            end\n | inr b => b\n end).\n", "meta": {"author": "odanado", "repo": "coq", "sha": "6524eb11b64fc6703af806e94b5405279d099ef2", "save_path": "github-repos/coq/odanado-coq", "path": "github-repos/coq/odanado-coq/coq-6524eb11b64fc6703af806e94b5405279d099ef2/coqex2014/4/kadai4_16.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561135, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6771822879268006}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria.                       *)\n(* You may distribute this file under the terms of the CeCILL-B license *)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq div choice fintype.\nRequire Import finfun bigop prime binomial ssralg finset fingroup finalg.\nRequire Import perm zmodp.\n\n(******************************************************************************)\n(* Basic concrete linear algebra : definition of type for matrices, and all   *)\n(* basic matrix operations including determinant, trace and support for block *)\n(* decomposition. Matrices are represented by a row-major list of their       *)\n(* coefficients but this implementation is hidden by three levels of wrappers *)\n(* (Matrix/Finfun/Tuple) so the matrix type should be treated as abstract and *)\n(* handled using only the operations described below:                         *)\n(*   'M[R]_(m, n) == the type of m rows by n columns matrices with            *)\n(*   'M_(m, n)       coefficients in R; the [R] is optional and is usually    *)\n(*                   omitted.                                                 *)\n(*  'M[R]_n, 'M_n == the type of n x n square matrices.                       *)\n(* 'rV[R]_n, 'rV_n == the type of 1 x n row vectors.                          *)\n(* 'cV[R]_n, 'cV_n == the type of n x 1 column vectors.                       *)\n(*  \\matrix_(i < m, j < n) Expr(i, j) ==                                      *)\n(*                   the m x n matrix with general coefficient Expr(i, j),    *)\n(*                   with i : 'I_m and j : 'I_n. the < m bound can be omitted *)\n(*                   if it is equal to n, though usually both bounds are      *)\n(*                   omitted as they can be inferred from the context.        *)\n(*  \\row_(j < n) Expr(j), \\col_(i < m) Expr(i)                                *)\n(*                   the row / column vectors with general term Expr; the     *)\n(*                   parentheses can be omitted along with the bound.         *)\n(* \\matrix_(i < m) RowExpr(i) ==                                              *)\n(*                   the m x n matrix with row i given by RowExpr(i) : 'rV_n. *)\n(*          A i j == the coefficient of matrix A : 'M_(m, n) in column j of   *)\n(*                   row i, where i : 'I_m, and j : 'I_n (via the coercion    *)\n(*                   fun_of_matrix : matrix >-> Funclass).                    *)\n(*     const_mx a == the constant matrix whose entries are all a (dimensions  *)\n(*                   should be determined by context).                        *)\n(*     map_mx f A == the pointwise image of A by f, i.e., the matrix Af       *)\n(*                   congruent to A with Af i j = f (A i j) for all i and j.  *)\n(*            A^T == the matrix transpose of A.                               *)\n(*        row i A == the i'th row of A (this is a row vector).                *)\n(*        col j A == the j'th column of A (a column vector).                  *)\n(*       row' i A == A with the i'th row spliced out.                         *)\n(*       col' i A == A with the j'th column spliced out.                      *)\n(*   xrow i1 i2 A == A with rows i1 and i2 interchanged.                      *)\n(*   xcol j1 j2 A == A with columns j1 and j2 interchanged.                   *)\n(*   row_perm s A == A : 'M_(m, n) with rows permuted by s : 'S_m.            *)\n(*   col_perm s A == A : 'M_(m, n) with columns permuted by s : 'S_n.         *)\n(*   row_mx Al Ar == the row block matrix <Al Ar> obtained by contatenating   *)\n(*                   two matrices Al and Ar of the same height.               *)\n(*   col_mx Au Ad == the column block matrix / Au \\ (Au and Ad must have the  *)\n(*                   same width).            \\ Ad /                           *)\n(* block_mx Aul Aur Adl Adr == the block matrix / Aul Aur \\                   *)\n(*                                              \\ Adl Adr /                   *)\n(*   [l|r]submx A == the left/right submatrices of a row block matrix A.      *)\n(*                   Note that the type of A, 'M_(m, n1 + n2) indicates how A *)\n(*                   should be decomposed.                                    *)\n(*   [u|d]submx A == the up/down submatrices of a column block matrix A.      *)\n(* [u|d][l|r]submx A == the upper left, etc submatrices of a block matrix A.  *)\n(* castmx eq_mn A == A : 'M_(m, n) cast to 'M_(m', n') using the equation     *)\n(*                   pair eq_mn : (m = m') * (n = n'). This is the usual      *)\n(*                   workaround for the syntactic limitations of dependent    *)\n(*                   types in Coq, and can be used to introduce a block       *)\n(*                   decomposition. It simplifies to A when eq_mn is the      *)\n(*                   pair (erefl m, erefl n) (using rewrite /castmx /=).      *)\n(* conform_mx B A == A if A and B have the same dimensions, else B.           *)\n(*        mxvec A == a row vector of width m * n holding all the entries of   *)\n(*                   the m x n matrix A.                                      *)\n(* mxvec_index i j == the index of A i j in mxvec A.                          *)\n(*       vec_mx v == the inverse of mxvec, reshaping a vector of width m * n  *)\n(*                   back into into an m x n rectangular matrix.              *)\n(* In 'M[R]_(m, n), R can be any type, but 'M[R]_(m, n) inherits the eqType,  *)\n(* choiceType, countType, finType, zmodType structures of R; 'M[R]_(m, n)     *)\n(* also has a natural lmodType R structure when R has a ringType structure.   *)\n(* Because the type of matrices specifies their dimension, only non-trivial   *)\n(* square matrices (of type 'M[R]_n.+1) can inherit the ring structure of R;  *)\n(* indeed they then have an algebra structure (lalgType R, or algType R if R  *)\n(* is a comRingType, or even unitAlgType if R is a comUnitRingType).          *)\n(*   We thus provide separate syntax for the general matrix multiplication,   *)\n(* and other operations for matrices over a ringType R:                       *)\n(*         A *m B == the matrix product of A and B; the width of A must be    *)\n(*                   equal to the height of B.                                *)\n(*           a%:M == the scalar matrix with a's on the main diagonal; in      *)\n(*                   particular 1%:M denotes the identity matrix, and is is   *)\n(*                   equal to 1%R when n is of the form n'.+1 (e.g., n >= 1). *)\n(* is_scalar_mx A <=> A is a scalar matrix (A = a%:M for some A).             *)\n(*      diag_mx d == the diagonal matrix whose main diagonal is d : 'rV_n.    *)\n(*   delta_mx i j == the matrix with a 1 in row i, column j and 0 elsewhere.  *)\n(*       pid_mx r == the partial identity matrix with 1s only on the r first  *)\n(*                   coefficients of the main diagonal; the dimensions of     *)\n(*                   pid_mx r are determined by the context, and pid_mx r can *)\n(*                   be rectangular.                                          *)\n(*     copid_mx r == the complement to 1%:M of pid_mx r: a square diagonal    *)\n(*                   matrix with 1s on all but the first r coefficients on    *)\n(*                   its main diagonal.                                       *)\n(*      perm_mx s == the n x n permutation matrix for s : 'S_n.               *)\n(* tperm_mx i1 i2 == the permutation matrix that exchanges i1 i2 : 'I_n.      *)\n(*   is_perm_mx A == A is a permutation matrix.                               *)\n(*     lift0_mx A == the 1 + n square matrix block_mx 1 0 0 A when A : 'M_n.  *)\n(*          \\tr A == the trace of a square matrix A.                          *)\n(*         \\det A == the determinant of A, using the Leibnitz formula.        *)\n(* cofactor i j A == the i, j cofactor of A (the signed i, j minor of A),     *)\n(*         \\adj A == the adjugate matrix of A (\\adj A i j = cofactor j i A).  *)\n(*   A \\in unitmx == A is invertible (R must be a comUnitRingType).           *)\n(*        invmx A == the inverse matrix of A if A \\in unitmx A, otherwise A.  *)\n(* The following operations provide a correspondance between linear functions *)\n(* and matrices:                                                              *)\n(*     lin1_mx f == the m x n matrix that emulates via right product          *)\n(*                  a (linear) function f : 'rV_m -> 'rV_n on ROW VECTORS     *)\n(*      lin_mx f == the (m1 * n1) x (m2 * n2) matrix that emulates, via the   *)\n(*                  right multiplication on the mxvec encodings, a linear     *)\n(*                  function f : 'M_(m1, n1) -> 'M_(m2, n2)                   *)\n(* lin_mul_row u := lin1_mx (mulmx u \\o vec_mx) (applies a row-encoded        *)\n(*                  function to the row-vector u).                            *)\n(*       mulmx A == partially applied matrix multiplication (mulmx A B is     *)\n(*                  displayed as A *m B), with, for A : 'M_(m, n), a          *)\n(*                  canonical {linear 'M_(n, p) -> 'M(m, p}} structure.       *)\n(*      mulmxr A == self-simplifying right-hand matrix multiplication, i.e.,  *)\n(*                  mulmxr A B simplifies to B *m A, with, for A : 'M_(n, p), *)\n(*                  a canonical {linear 'M_(m, n) -> 'M(m, p}} structure.     *)\n(*   lin_mulmx A := lin_mx (mulmx A).                                         *)\n(*  lin_mulmxr A := lin_mx (mulmxr A).                                        *)\n(* We also extend any finType structure of R to 'M[R]_(m, n), and define:     *)\n(*     {'GL_n[R]} == the finGroupType of units of 'M[R]_n.-1.+1.              *)\n(*      'GL_n[R]  == the general linear group of all matrices in {'GL_n(R)}.  *)\n(*      'GL_n(p)  == 'GL_n['F_p], the general linear group of a prime field.  *)\n(*       GLval u  == the coercion of u : {'GL_n(R)} to a matrix.              *)\n(*   In addition to the lemmas relevant to these definitions, this file also  *)\n(* proves several classic results, including :                                *)\n(* - The determinant is a multilinear alternate form.                         *)\n(* - The Laplace determinant expansion formulas: expand_det_[row|col].        *)\n(* - The Cramer rule : mul_mx_adj & mul_adj_mx.                               *)\n(* Finally, as an example of the use of block products, we program and prove  *)\n(* the correctness of a classical linear algebra algorithm:                   *)\n(*    cormenLUP A == the triangular decomposition (L, U, P) of a nontrivial   *)\n(*                   square matrix A into a lower triagular matrix L with 1s  *)\n(*                   on the main diagonal, an upper matrix U, and a           *)\n(*                   permutation matrix P, such that P * A = L * U.           *)\n(* This is example only; we use a different, more precise algorithm to        *)\n(* develop the theory of matrix ranks and row spaces in mxalgebra.v           *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GroupScope.\nImport GRing.Theory.\nOpen Local Scope ring_scope.\n\nReserved Notation \"''M_' n\"     (at level 8, n at level 2, format \"''M_' n\").\nReserved Notation \"''rV_' n\"    (at level 8, n at level 2, format \"''rV_' n\").\nReserved Notation \"''cV_' n\"    (at level 8, n at level 2, format \"''cV_' n\").\nReserved Notation \"''M_' ( n )\" (at level 8, only parsing).\nReserved Notation \"''M_' ( m , n )\" (at level 8, format \"''M_' ( m ,  n )\").\nReserved Notation \"''M[' R ]_ n\"    (at level 8, n at level 2, only parsing).\nReserved Notation \"''rV[' R ]_ n\"   (at level 8, n at level 2, only parsing).\nReserved Notation \"''cV[' R ]_ n\"   (at level 8, n at level 2, only parsing).\nReserved Notation \"''M[' R ]_ ( n )\"     (at level 8, only parsing).\nReserved Notation \"''M[' R ]_ ( m , n )\" (at level 8, only parsing).\n\nReserved Notation \"\\matrix_ i E\" \n  (at level 36, E at level 36, i at level 2,\n   format \"\\matrix_ i  E\").\nReserved Notation \"\\matrix_ ( i < n ) E\"\n  (at level 36, E at level 36, i, n at level 50, only parsing).\nReserved Notation \"\\matrix_ ( i , j ) E\"\n  (at level 36, E at level 36, i, j at level 50,\n   format \"\\matrix_ ( i ,  j )  E\").\nReserved Notation \"\\matrix[ k ]_ ( i , j ) E\"\n  (at level 36, E at level 36, i, j at level 50,\n   format \"\\matrix[ k ]_ ( i ,  j )  E\").\nReserved Notation \"\\matrix_ ( i < m , j < n ) E\"\n  (at level 36, E at level 36, i, m, j, n at level 50, only parsing).\nReserved Notation \"\\matrix_ ( i , j < n ) E\"\n  (at level 36, E at level 36, i, j, n at level 50, only parsing).\nReserved Notation \"\\row_ j E\"\n  (at level 36, E at level 36, j at level 2,\n   format \"\\row_ j  E\").\nReserved Notation \"\\row_ ( j < n ) E\"\n  (at level 36, E at level 36, j, n at level 50, only parsing).\nReserved Notation \"\\col_ j E\"\n  (at level 36, E at level 36, j at level 2,\n   format \"\\col_ j  E\").\nReserved Notation \"\\col_ ( j < n ) E\"\n  (at level 36, E at level 36, j, n at level 50, only parsing).\n\nReserved Notation \"x %:M\"   (at level 8, format \"x %:M\").\nReserved Notation \"A *m B\" (at level 40, left associativity, format \"A  *m  B\").\nReserved Notation \"A ^T\"    (at level 8, format \"A ^T\").\nReserved Notation \"\\tr A\"   (at level 10, A at level 8, format \"\\tr  A\").\nReserved Notation \"\\det A\"  (at level 10, A at level 8, format \"\\det  A\").\nReserved Notation \"\\adj A\"  (at level 10, A at level 8, format \"\\adj  A\").\n\nNotation Local simp := (Monoid.Theory.simpm, oppr0).\n\n(*****************************************************************************)\n(****************************Type Definition**********************************)\n(*****************************************************************************)\n\nSection MatrixDef.\n\nVariable R : Type.\nVariables m n : nat.\n\n(* Basic linear algebra (matrices).                                       *)\n(* We use dependent types (ordinals) for the indices so that ranges are   *)\n(* mostly inferred automatically                                          *)\n\nInductive matrix : predArgType := Matrix of {ffun 'I_m * 'I_n -> R}.\n\nDefinition mx_val A := let: Matrix g := A in g.\n\nCanonical matrix_subType := Eval hnf in [newType for mx_val].\n\nFact matrix_key : unit. Proof. by []. Qed.\nDefinition matrix_of_fun_def F := Matrix [ffun ij => F ij.1 ij.2].\nDefinition matrix_of_fun k := locked_with k matrix_of_fun_def.\nCanonical matrix_unlockable k := [unlockable fun matrix_of_fun k].\n\nDefinition fun_of_matrix A (i : 'I_m) (j : 'I_n) := mx_val A (i, j).\n\nCoercion fun_of_matrix : matrix >-> Funclass.\n\nLemma mxE k F : matrix_of_fun k F =2 F.\nProof. by move=> i j; rewrite unlock /fun_of_matrix /= ffunE. Qed.\n\nLemma matrixP (A B : matrix) : A =2 B <-> A = B.\nProof.\nrewrite /fun_of_matrix; split=> [/= eqAB | -> //].\nby apply/val_inj/ffunP=> [[i j]]; exact: eqAB.\nQed.\n\nEnd MatrixDef.\n\nBind Scope ring_scope with matrix.\n\nNotation \"''M[' R ]_ ( m , n )\" := (matrix R m n) (only parsing): type_scope.\nNotation \"''rV[' R ]_ n\" := 'M[R]_(1, n) (only parsing) : type_scope.\nNotation \"''cV[' R ]_ n\" := 'M[R]_(n, 1) (only parsing) : type_scope.\nNotation \"''M[' R ]_ n\" := 'M[R]_(n, n) (only parsing) : type_scope.\nNotation \"''M[' R ]_ ( n )\" := 'M[R]_n (only parsing) : type_scope.\nNotation \"''M_' ( m , n )\" := 'M[_]_(m, n) : type_scope.\nNotation \"''rV_' n\" := 'M_(1, n) : type_scope.\nNotation \"''cV_' n\" := 'M_(n, 1) : type_scope.\nNotation \"''M_' n\" := 'M_(n, n) : type_scope.\nNotation \"''M_' ( n )\" := 'M_n (only parsing) : type_scope.\n\nNotation \"\\matrix[ k ]_ ( i , j ) E\" := (matrix_of_fun k (fun i j => E))\n  (at level 36, E at level 36, i, j at level 50): ring_scope.\n\nNotation \"\\matrix_ ( i < m , j < n ) E\" :=\n  (@matrix_of_fun _ m n matrix_key (fun i j => E)) (only parsing) : ring_scope.\n\nNotation \"\\matrix_ ( i , j < n ) E\" :=\n  (\\matrix_(i < n, j < n) E) (only parsing) : ring_scope.\n\nNotation \"\\matrix_ ( i , j ) E\" := (\\matrix_(i < _, j < _) E) : ring_scope.\n\nNotation \"\\matrix_ ( i < m ) E\" :=\n  (\\matrix_(i < m, j < _) @fun_of_matrix _ 1 _ E 0 j)\n  (only parsing) : ring_scope.\nNotation \"\\matrix_ i E\" := (\\matrix_(i < _) E) : ring_scope.\n\nNotation \"\\col_ ( i < n ) E\" := (@matrix_of_fun _ n 1 matrix_key (fun i _ => E))\n  (only parsing) : ring_scope.\nNotation \"\\col_ i E\" := (\\col_(i < _) E) : ring_scope.\n\nNotation \"\\row_ ( j < n ) E\" := (@matrix_of_fun _ 1 n matrix_key (fun _ j => E))\n  (only parsing) : ring_scope.\nNotation \"\\row_ j E\" := (\\row_(j < _) E) : ring_scope.\n\nDefinition matrix_eqMixin (R : eqType) m n :=\n  Eval hnf in [eqMixin of 'M[R]_(m, n) by <:].\nCanonical matrix_eqType (R : eqType) m n:=\n  Eval hnf in EqType 'M[R]_(m, n) (matrix_eqMixin R m n).\nDefinition matrix_choiceMixin (R : choiceType) m n :=\n  [choiceMixin of 'M[R]_(m, n) by <:].\nCanonical matrix_choiceType (R : choiceType) m n :=\n  Eval hnf in ChoiceType 'M[R]_(m, n) (matrix_choiceMixin R m n).\nDefinition matrix_countMixin (R : countType) m n :=\n  [countMixin of 'M[R]_(m, n) by <:].\nCanonical matrix_countType (R : countType) m n :=\n  Eval hnf in CountType 'M[R]_(m, n) (matrix_countMixin R m n).\nCanonical matrix_subCountType (R : countType) m n :=\n  Eval hnf in [subCountType of 'M[R]_(m, n)].\nDefinition matrix_finMixin (R : finType) m n :=\n  [finMixin of 'M[R]_(m, n) by <:].\nCanonical matrix_finType (R : finType) m n :=\n  Eval hnf in FinType 'M[R]_(m, n) (matrix_finMixin R m n).\nCanonical matrix_subFinType (R : finType) m n :=\n  Eval hnf in [subFinType of 'M[R]_(m, n)].\n\nLemma card_matrix (F : finType) m n : (#|{: 'M[F]_(m, n)}| = #|F| ^ (m * n))%N.\nProof. by rewrite card_sub card_ffun card_prod !card_ord. Qed.\n\n(*****************************************************************************)\n(****** Matrix structural operations (transpose, permutation, blocks) ********)\n(*****************************************************************************)\n\nSection MatrixStructural.\n\nVariable R : Type.\n\n(* Constant matrix *)\nFact const_mx_key : unit. Proof. by []. Qed.\nDefinition const_mx m n a : 'M[R]_(m, n) := \\matrix[const_mx_key]_(i, j) a.\nImplicit Arguments const_mx [[m] [n]].\n\nSection FixedDim.\n(* Definitions and properties for which we can work with fixed dimensions. *)\n\nVariables m n : nat.\nImplicit Type A : 'M[R]_(m, n).\n\n(* Reshape a matrix, to accomodate the block functions for instance. *)\nDefinition castmx m' n' (eq_mn : (m = m') * (n = n')) A : 'M_(m', n') :=\n  let: erefl in _ = m' := eq_mn.1 return 'M_(m', n') in\n  let: erefl in _ = n' := eq_mn.2 return 'M_(m, n') in A.\n\nDefinition conform_mx m' n' B A :=\n  match m =P m', n =P n' with\n  | ReflectT eq_m, ReflectT eq_n => castmx (eq_m, eq_n) A\n  | _, _ => B\n  end.\n\n(* Transpose a matrix *)\nFact trmx_key : unit. Proof. by []. Qed.\nDefinition trmx A := \\matrix[trmx_key]_(i, j) A j i.\n\n(* Permute a matrix vertically (rows) or horizontally (columns) *)\nFact row_perm_key : unit. Proof. by []. Qed.\nDefinition row_perm (s : 'S_m) A := \\matrix[row_perm_key]_(i, j) A (s i) j.\nFact col_perm_key : unit. Proof. by []. Qed.\nDefinition col_perm (s : 'S_n) A := \\matrix[col_perm_key]_(i, j) A i (s j).\n\n(* Exchange two rows/columns of a matrix *)\nDefinition xrow i1 i2 := row_perm (tperm i1 i2).\nDefinition xcol j1 j2 := col_perm (tperm j1 j2).\n\n(* Row/Column sub matrices of a matrix *)\nDefinition row i0 A := \\row_j A i0 j.\nDefinition col j0 A := \\col_i A i j0.\n\n(* Removing a row/column from a matrix *)\nDefinition row' i0 A := \\matrix_(i, j) A (lift i0 i) j.\nDefinition col' j0 A := \\matrix_(i, j) A i (lift j0 j).\n\nLemma castmx_const m' n' (eq_mn : (m = m') * (n = n')) a :\n  castmx eq_mn (const_mx a) = const_mx a.\nProof. by case: eq_mn; case: m' /; case: n' /. Qed.\n\nLemma trmx_const a : trmx (const_mx a) = const_mx a.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma row_perm_const s a : row_perm s (const_mx a) = const_mx a.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma col_perm_const s a : col_perm s (const_mx a) = const_mx a.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma xrow_const i1 i2 a : xrow i1 i2 (const_mx a) = const_mx a.\nProof. exact: row_perm_const. Qed.\n\nLemma xcol_const j1 j2 a : xcol j1 j2 (const_mx a) = const_mx a.\nProof. exact: col_perm_const. Qed.\n\nLemma rowP (u v : 'rV[R]_n) : u 0 =1 v 0 <-> u = v.\nProof. by split=> [eq_uv | -> //]; apply/matrixP=> i; rewrite ord1. Qed.\n\nLemma rowK u_ i0 : row i0 (\\matrix_i u_ i) = u_ i0.\nProof. by apply/rowP=> i'; rewrite !mxE. Qed.\n\nLemma row_matrixP A B : (forall i, row i A = row i B) <-> A = B.\nProof.\nsplit=> [eqAB | -> //]; apply/matrixP=> i j.\nby move/rowP/(_ j): (eqAB i); rewrite !mxE.\nQed.\n\nLemma colP (u v : 'cV[R]_m) : u^~ 0 =1 v^~ 0 <-> u = v.\nProof. by split=> [eq_uv | -> //]; apply/matrixP=> i j; rewrite ord1. Qed.\n\nLemma row_const i0 a : row i0 (const_mx a) = const_mx a.\nProof. by apply/rowP=> j; rewrite !mxE. Qed.\n\nLemma col_const j0 a : col j0 (const_mx a) = const_mx a.\nProof. by apply/colP=> i; rewrite !mxE. Qed.\n\nLemma row'_const i0 a : row' i0 (const_mx a) = const_mx a.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma col'_const j0 a : col' j0 (const_mx a) = const_mx a.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma col_perm1 A : col_perm 1 A = A.\nProof. by apply/matrixP=> i j; rewrite mxE perm1. Qed.\n\nLemma row_perm1 A : row_perm 1 A = A.\nProof. by apply/matrixP=> i j; rewrite mxE perm1. Qed.\n\nLemma col_permM s t A : col_perm (s * t) A = col_perm s (col_perm t A).\nProof. by apply/matrixP=> i j; rewrite !mxE permM. Qed.\n\nLemma row_permM s t A : row_perm (s * t) A = row_perm s (row_perm t A).\nProof. by apply/matrixP=> i j; rewrite !mxE permM. Qed.\n\nLemma col_row_permC s t A :\n  col_perm s (row_perm t A) = row_perm t (col_perm s A).\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nEnd FixedDim.\n\nLocal Notation \"A ^T\" := (trmx A) : ring_scope.\n\nLemma castmx_id m n erefl_mn (A : 'M_(m, n)) : castmx erefl_mn A = A.\nProof. by case: erefl_mn => e_m e_n; rewrite [e_m]eq_axiomK [e_n]eq_axiomK. Qed.\n\nLemma castmx_comp m1 n1 m2 n2 m3 n3 (eq_m1 : m1 = m2) (eq_n1 : n1 = n2)\n                                    (eq_m2 : m2 = m3) (eq_n2 : n2 = n3) A :\n  castmx (eq_m2, eq_n2) (castmx (eq_m1, eq_n1) A)\n    = castmx (etrans eq_m1 eq_m2, etrans eq_n1 eq_n2) A.\nProof.\nby case: m2 / eq_m1 eq_m2; case: m3 /; case: n2 / eq_n1 eq_n2; case: n3 /.\nQed.\n\nLemma castmxK m1 n1 m2 n2 (eq_m : m1 = m2) (eq_n : n1 = n2) :\n  cancel (castmx (eq_m, eq_n)) (castmx (esym eq_m, esym eq_n)).\nProof. by case: m2 / eq_m; case: n2 / eq_n. Qed.\n\nLemma castmxKV m1 n1 m2 n2 (eq_m : m1 = m2) (eq_n : n1 = n2) :\n  cancel (castmx (esym eq_m, esym eq_n)) (castmx (eq_m, eq_n)).\nProof. by case: m2 / eq_m; case: n2 / eq_n. Qed.\n\n(* This can be use to reverse an equation that involves a cast. *)\nLemma castmx_sym m1 n1 m2 n2 (eq_m : m1 = m2) (eq_n : n1 = n2) A1 A2 :\n  A1 = castmx (eq_m, eq_n) A2 -> A2 = castmx (esym eq_m, esym eq_n) A1.\nProof. by move/(canLR (castmxK _ _)). Qed.\n\nLemma castmxE m1 n1 m2 n2 (eq_mn : (m1 = m2) * (n1 = n2)) A i j :\n  castmx eq_mn A i j =\n     A (cast_ord (esym eq_mn.1) i) (cast_ord (esym eq_mn.2) j).\nProof.\nby do [case: eq_mn; case: m2 /; case: n2 /] in A i j *; rewrite !cast_ord_id.\nQed.\n\nLemma conform_mx_id m n (B A : 'M_(m, n)) : conform_mx B A = A.\nProof. by rewrite /conform_mx; do 2!case: eqP => // *; rewrite castmx_id. Qed.\n\nLemma nonconform_mx m m' n n' (B : 'M_(m', n')) (A : 'M_(m, n)) :\n  (m != m') || (n != n') -> conform_mx B A = B.\nProof. by rewrite /conform_mx; do 2!case: eqP. Qed.\n\nLemma conform_castmx m1 n1 m2 n2 m3 n3\n                     (e_mn : (m2 = m3) * (n2 = n3)) (B : 'M_(m1, n1)) A :\n  conform_mx B (castmx e_mn A) = conform_mx B A.\nProof. by do [case: e_mn; case: m3 /; case: n3 /] in A *. Qed.\n\nLemma trmxK m n : cancel (@trmx m n) (@trmx n m).\nProof. by move=> A; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma trmx_inj m n : injective (@trmx m n).\nProof. exact: can_inj (@trmxK m n). Qed.\n\nLemma trmx_cast m1 n1 m2 n2 (eq_mn : (m1 = m2) * (n1 = n2)) A :\n  (castmx eq_mn A)^T = castmx (eq_mn.2, eq_mn.1) A^T.\nProof.\nby case: eq_mn => eq_m eq_n; apply/matrixP=> i j; rewrite !(mxE, castmxE).\nQed.\n\nLemma tr_row_perm m n s (A : 'M_(m, n)) : (row_perm s A)^T = col_perm s A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_col_perm m n s (A : 'M_(m, n)) : (col_perm s A)^T = row_perm s A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_xrow m n i1 i2 (A : 'M_(m, n)) : (xrow i1 i2 A)^T = xcol i1 i2 A^T.\nProof. exact: tr_row_perm. Qed.\n\nLemma tr_xcol m n j1 j2 (A : 'M_(m, n)) : (xcol j1 j2 A)^T = xrow j1 j2 A^T.\nProof. exact: tr_col_perm. Qed.\n\nLemma row_id n i (V : 'rV_n) : row i V = V.\nProof. by apply/rowP=> j; rewrite mxE [i]ord1. Qed.\n\nLemma col_id n j (V : 'cV_n) : col j V = V.\nProof. by apply/colP=> i; rewrite mxE [j]ord1. Qed.\n\nLemma row_eq m1 m2 n i1 i2 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  row i1 A1 = row i2 A2 -> A1 i1 =1 A2 i2.\nProof. by move/rowP=> eqA12 j; have:= eqA12 j; rewrite !mxE. Qed.\n\nLemma col_eq m n1 n2 j1 j2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  col j1 A1 = col j2 A2 -> A1^~ j1 =1 A2^~ j2.\nProof. by move/colP=> eqA12 i; have:= eqA12 i; rewrite !mxE. Qed.\n\nLemma row'_eq m n i0 (A B : 'M_(m, n)) :\n  row' i0 A = row' i0 B -> {in predC1 i0, A =2 B}.\nProof.\nmove/matrixP=> eqAB' i; rewrite !inE eq_sym; case/unlift_some=> i' -> _ j.\nby have:= eqAB' i' j; rewrite !mxE.\nQed.\n\nLemma col'_eq m n j0 (A B : 'M_(m, n)) :\n  col' j0 A = col' j0 B -> forall i, {in predC1 j0, A i =1 B i}.\nProof.\nmove/matrixP=> eqAB' i j; rewrite !inE eq_sym; case/unlift_some=> j' -> _.\nby have:= eqAB' i j'; rewrite !mxE.\nQed.\n\nLemma tr_row m n i0 (A : 'M_(m, n)) : (row i0 A)^T = col i0 A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_row' m n i0 (A : 'M_(m, n)) : (row' i0 A)^T = col' i0 A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_col m n j0 (A : 'M_(m, n)) : (col j0 A)^T = row j0 A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_col' m n j0 (A : 'M_(m, n)) : (col' j0 A)^T = row' j0 A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLtac split_mxE := apply/matrixP=> i j; do ![rewrite mxE | case: split => ?].\n\nSection CutPaste.\n\nVariables m m1 m2 n n1 n2 : nat.\n\n(* Concatenating two matrices, in either direction. *)\n\nFact row_mx_key : unit. Proof. by []. Qed.\nDefinition row_mx (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) : 'M[R]_(m, n1 + n2) :=\n  \\matrix[row_mx_key]_(i, j)\n     match split j with inl j1 => A1 i j1 | inr j2 => A2 i j2 end.\n\nFact col_mx_key : unit. Proof. by []. Qed.\nDefinition col_mx (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) : 'M[R]_(m1 + m2, n) :=\n  \\matrix[col_mx_key]_(i, j)\n     match split i with inl i1 => A1 i1 j | inr i2 => A2 i2 j end.\n\n(* Left/Right | Up/Down submatrices of a rows | columns matrix.   *)\n(* The shape of the (dependent) width parameters of the type of A *)\n(* determines which submatrix is selected.                        *)\n\nFact lsubmx_key : unit. Proof. by []. Qed.\nDefinition lsubmx (A : 'M[R]_(m, n1 + n2)) :=\n  \\matrix[lsubmx_key]_(i, j) A i (lshift n2 j).\n\nFact rsubmx_key : unit. Proof. by []. Qed.\nDefinition rsubmx (A : 'M[R]_(m, n1 + n2)) :=\n  \\matrix[rsubmx_key]_(i, j) A i (rshift n1 j).\n\nFact usubmx_key : unit. Proof. by []. Qed.\nDefinition usubmx (A : 'M[R]_(m1 + m2, n)) :=\n  \\matrix[usubmx_key]_(i, j) A (lshift m2 i) j.\n\nFact dsubmx_key : unit. Proof. by []. Qed.\nDefinition dsubmx (A : 'M[R]_(m1 + m2, n)) :=\n  \\matrix[dsubmx_key]_(i, j) A (rshift m1 i) j.\n\nLemma row_mxEl A1 A2 i j : row_mx A1 A2 i (lshift n2 j) = A1 i j.\nProof. by rewrite mxE (unsplitK (inl _ _)). Qed.\n\nLemma row_mxKl A1 A2 : lsubmx (row_mx A1 A2) = A1.\nProof. by apply/matrixP=> i j; rewrite mxE row_mxEl. Qed.\n\nLemma row_mxEr A1 A2 i j : row_mx A1 A2 i (rshift n1 j) = A2 i j.\nProof. by rewrite mxE (unsplitK (inr _ _)). Qed.\n\nLemma row_mxKr A1 A2 : rsubmx (row_mx A1 A2) = A2.\nProof. by apply/matrixP=> i j; rewrite mxE row_mxEr. Qed.\n\nLemma hsubmxK A : row_mx (lsubmx A) (rsubmx A) = A.\nProof.\napply/matrixP=> i j; rewrite !mxE.\ncase: splitP => k Dk //=; rewrite !mxE //=; congr (A _ _); exact: val_inj.\nQed.\n\nLemma col_mxEu A1 A2 i j : col_mx A1 A2 (lshift m2 i) j = A1 i j.\nProof. by rewrite mxE (unsplitK (inl _ _)). Qed.\n\nLemma col_mxKu A1 A2 : usubmx (col_mx A1 A2) = A1.\nProof. by apply/matrixP=> i j; rewrite mxE col_mxEu. Qed.\n\nLemma col_mxEd A1 A2 i j : col_mx A1 A2 (rshift m1 i) j = A2 i j.\nProof. by rewrite mxE (unsplitK (inr _ _)). Qed.\n\nLemma col_mxKd A1 A2 : dsubmx (col_mx A1 A2) = A2.\nProof. by apply/matrixP=> i j; rewrite mxE col_mxEd. Qed.\n\nLemma eq_row_mx A1 A2 B1 B2 : row_mx A1 A2 = row_mx B1 B2 -> A1 = B1 /\\ A2 = B2.\nProof.\nmove=> eqAB; move: (congr1 lsubmx eqAB) (congr1 rsubmx eqAB).\nby rewrite !(row_mxKl, row_mxKr).\nQed.\n\nLemma eq_col_mx A1 A2 B1 B2 : col_mx A1 A2 = col_mx B1 B2 -> A1 = B1 /\\ A2 = B2.\nProof.\nmove=> eqAB; move: (congr1 usubmx eqAB) (congr1 dsubmx eqAB).\nby rewrite !(col_mxKu, col_mxKd).\nQed.\n\nLemma row_mx_const a : row_mx (const_mx a) (const_mx a) = const_mx a.\nProof. by split_mxE. Qed.\n\nLemma col_mx_const a : col_mx (const_mx a) (const_mx a) = const_mx a.\nProof. by split_mxE. Qed.\n\nEnd CutPaste.\n\nLemma trmx_lsub m n1 n2 (A : 'M_(m, n1 + n2)) : (lsubmx A)^T = usubmx A^T.\nProof. by split_mxE. Qed.\n\nLemma trmx_rsub m n1 n2 (A : 'M_(m, n1 + n2)) : (rsubmx A)^T = dsubmx A^T.\nProof. by split_mxE. Qed.\n\nLemma tr_row_mx m n1 n2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  (row_mx A1 A2)^T = col_mx A1^T A2^T.\nProof. by split_mxE. Qed.\n\nLemma tr_col_mx m1 m2 n (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  (col_mx A1 A2)^T = row_mx A1^T A2^T.\nProof. by split_mxE. Qed.\n\nLemma trmx_usub m1 m2 n (A : 'M_(m1 + m2, n)) : (usubmx A)^T = lsubmx A^T.\nProof. by split_mxE. Qed.\n\nLemma trmx_dsub m1 m2 n (A : 'M_(m1 + m2, n)) : (dsubmx A)^T = rsubmx A^T.\nProof. by split_mxE. Qed.\n\nLemma vsubmxK m1 m2 n (A : 'M_(m1 + m2, n)) : col_mx (usubmx A) (dsubmx A) = A.\nProof. by apply: trmx_inj; rewrite tr_col_mx trmx_usub trmx_dsub hsubmxK. Qed.\n\nLemma cast_row_mx m m' n1 n2 (eq_m : m = m') A1 A2 :\n  castmx (eq_m, erefl _) (row_mx A1 A2)\n    = row_mx (castmx (eq_m, erefl n1) A1) (castmx (eq_m, erefl n2) A2).\nProof. by case: m' / eq_m. Qed.\n\nLemma cast_col_mx m1 m2 n n' (eq_n : n = n') A1 A2 :\n  castmx (erefl _, eq_n) (col_mx A1 A2)\n    = col_mx (castmx (erefl m1, eq_n) A1) (castmx (erefl m2, eq_n) A2).\nProof. by case: n' / eq_n. Qed.\n\n(* This lemma has Prenex Implicits to help RL rewrititng with castmx_sym. *)\nLemma row_mxA m n1 n2 n3 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) (A3 : 'M_(m, n3)) :\n  let cast := (erefl m, esym (addnA n1 n2 n3)) in\n  row_mx A1 (row_mx A2 A3) = castmx cast (row_mx (row_mx A1 A2) A3).\nProof.\napply: (canRL (castmxKV _ _)); apply/matrixP=> i j.\nrewrite castmxE !mxE cast_ord_id; case: splitP => j1 /= def_j.\n  have: (j < n1 + n2) && (j < n1) by rewrite def_j lshift_subproof /=.\n  by move: def_j; do 2![case: splitP => // ? ->; rewrite ?mxE] => /ord_inj->.\ncase: splitP def_j => j2 ->{j} def_j; rewrite !mxE.\n  have: ~~ (j2 < n1) by rewrite -leqNgt def_j leq_addr.\n  have: j1 < n2 by rewrite -(ltn_add2l n1) -def_j.\n  by move: def_j; do 2![case: splitP => // ? ->] => /addnI/val_inj->.\nhave: ~~ (j1 < n2) by rewrite -leqNgt -(leq_add2l n1) -def_j leq_addr.\nby case: splitP def_j => // ? ->; rewrite addnA => /addnI/val_inj->.\nQed.\nDefinition row_mxAx := row_mxA. (* bypass Prenex Implicits. *)\n\n(* This lemma has Prenex Implicits to help RL rewrititng with castmx_sym. *)\nLemma col_mxA m1 m2 m3 n (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) (A3 : 'M_(m3, n)) :\n  let cast := (esym (addnA m1 m2 m3), erefl n) in\n  col_mx A1 (col_mx A2 A3) = castmx cast (col_mx (col_mx A1 A2) A3).\nProof. by apply: trmx_inj; rewrite trmx_cast !tr_col_mx -row_mxA. Qed.\nDefinition col_mxAx := col_mxA. (* bypass Prenex Implicits. *)\n\nLemma row_row_mx m n1 n2 i0 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  row i0 (row_mx A1 A2) = row_mx (row i0 A1) (row i0 A2).\nProof.\nby apply/matrixP=> i j; rewrite !mxE; case: (split j) => j'; rewrite mxE.\nQed.\n\nLemma col_col_mx m1 m2 n j0 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  col j0 (col_mx A1 A2) = col_mx (col j0 A1) (col j0 A2).\nProof. by apply: trmx_inj; rewrite !(tr_col, tr_col_mx, row_row_mx). Qed.\n\nLemma row'_row_mx m n1 n2 i0 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  row' i0 (row_mx A1 A2) = row_mx (row' i0 A1) (row' i0 A2).\nProof.\nby apply/matrixP=> i j; rewrite !mxE; case: (split j) => j'; rewrite mxE.\nQed.\n\nLemma col'_col_mx m1 m2 n j0 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  col' j0 (col_mx A1 A2) = col_mx (col' j0 A1) (col' j0 A2).\nProof. by apply: trmx_inj; rewrite !(tr_col', tr_col_mx, row'_row_mx). Qed.\n\nLemma colKl m n1 n2 j1 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  col (lshift n2 j1) (row_mx A1 A2) = col j1 A1.\nProof. by apply/matrixP=> i j; rewrite !(row_mxEl, mxE). Qed.\n\nLemma colKr m n1 n2 j2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  col (rshift n1 j2) (row_mx A1 A2) = col j2 A2.\nProof. by apply/matrixP=> i j; rewrite !(row_mxEr, mxE). Qed.\n\nLemma rowKu m1 m2 n i1 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  row (lshift m2 i1) (col_mx A1 A2) = row i1 A1.\nProof. by apply/matrixP=> i j; rewrite !(col_mxEu, mxE). Qed.\n\nLemma rowKd m1 m2 n i2 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  row (rshift m1 i2) (col_mx A1 A2) = row i2 A2.\nProof. by apply/matrixP=> i j; rewrite !(col_mxEd, mxE). Qed.\n\nLemma col'Kl m n1 n2 j1 (A1 : 'M_(m, n1.+1)) (A2 : 'M_(m, n2)) :\n  col' (lshift n2 j1) (row_mx A1 A2) = row_mx (col' j1 A1) A2.\nProof.\napply/matrixP=> i /= j; symmetry; rewrite 2!mxE.\ncase: splitP => j' def_j'.\n  rewrite mxE -(row_mxEl _ A2); congr (row_mx _ _ _); apply: ord_inj.\n  by rewrite /= def_j'.\nrewrite -(row_mxEr A1); congr (row_mx _ _ _); apply: ord_inj => /=.\nby rewrite /bump def_j' -ltnS -addSn ltn_addr.\nQed.\n\nLemma row'Ku m1 m2 n i1 (A1 : 'M_(m1.+1, n)) (A2 : 'M_(m2, n)) :\n  row' (lshift m2 i1) (@col_mx m1.+1 m2 n A1 A2) = col_mx (row' i1 A1) A2.\nProof.\nby apply: trmx_inj; rewrite tr_col_mx !(@tr_row' _.+1) (@tr_col_mx _.+1) col'Kl.\nQed.\n\nLemma mx'_cast m n : 'I_n -> (m + n.-1)%N = (m + n).-1.\nProof. by case=> j /ltn_predK <-; rewrite addnS. Qed.\n\nLemma col'Kr m n1 n2 j2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  col' (rshift n1 j2) (@row_mx m n1 n2 A1 A2)\n    = castmx (erefl m, mx'_cast n1 j2) (row_mx A1 (col' j2 A2)).\nProof.\napply/matrixP=> i j; symmetry; rewrite castmxE mxE cast_ord_id.\ncase: splitP => j' /= def_j.\n  rewrite mxE -(row_mxEl _ A2); congr (row_mx _ _ _); apply: ord_inj.\n  by rewrite /= def_j /bump leqNgt ltn_addr.\nrewrite 2!mxE -(row_mxEr A1); congr (row_mx _ _ _ _); apply: ord_inj.\nby rewrite /= def_j /bump leq_add2l addnCA.\nQed.\n\nLemma row'Kd m1 m2 n i2 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  row' (rshift m1 i2) (col_mx A1 A2)\n    = castmx (mx'_cast m1 i2, erefl n) (col_mx A1 (row' i2 A2)).\nProof. by apply: trmx_inj; rewrite trmx_cast !(tr_row', tr_col_mx) col'Kr. Qed.\n\nSection Block.\n\nVariables m1 m2 n1 n2 : nat.\n\n(* Building a block matrix from 4 matrices :               *)\n(*  up left, up right, down left and down right components *)\n\nDefinition block_mx Aul Aur Adl Adr : 'M_(m1 + m2, n1 + n2) :=\n  col_mx (row_mx Aul Aur) (row_mx Adl Adr).\n\nLemma eq_block_mx Aul Aur Adl Adr Bul Bur Bdl Bdr :\n block_mx Aul Aur Adl Adr = block_mx Bul Bur Bdl Bdr ->\n  [/\\ Aul = Bul, Aur = Bur, Adl = Bdl & Adr = Bdr].\nProof. by case/eq_col_mx; do 2!case/eq_row_mx=> -> ->. Qed.\n\nLemma block_mx_const a :\n  block_mx (const_mx a) (const_mx a) (const_mx a) (const_mx a) = const_mx a.\nProof. by split_mxE. Qed.\n\nSection CutBlock.\n\nVariable A : matrix R (m1 + m2) (n1 + n2).\n\nDefinition ulsubmx := lsubmx (usubmx A).\nDefinition ursubmx := rsubmx (usubmx A).\nDefinition dlsubmx := lsubmx (dsubmx A).\nDefinition drsubmx := rsubmx (dsubmx A).\n\nLemma submxK : block_mx ulsubmx ursubmx dlsubmx drsubmx = A.\nProof. by rewrite /block_mx !hsubmxK vsubmxK. Qed.\n\nEnd CutBlock.\n\nSection CatBlock.\n\nVariables (Aul : 'M[R]_(m1, n1)) (Aur : 'M[R]_(m1, n2)).\nVariables (Adl : 'M[R]_(m2, n1)) (Adr : 'M[R]_(m2, n2)).\n\nLet A := block_mx Aul Aur Adl Adr.\n\nLemma block_mxEul i j : A (lshift m2 i) (lshift n2 j) = Aul i j.\nProof. by rewrite col_mxEu row_mxEl. Qed.\nLemma block_mxKul : ulsubmx A = Aul.\nProof. by rewrite /ulsubmx col_mxKu row_mxKl. Qed.\n\nLemma block_mxEur i j : A (lshift m2 i) (rshift n1 j) = Aur i j.\nProof. by rewrite col_mxEu row_mxEr. Qed.\nLemma block_mxKur : ursubmx A = Aur.\nProof. by rewrite /ursubmx col_mxKu row_mxKr. Qed.\n\nLemma block_mxEdl i j : A (rshift m1 i) (lshift n2 j) = Adl i j.\nProof. by rewrite col_mxEd row_mxEl. Qed.\nLemma block_mxKdl : dlsubmx A = Adl.\nProof. by rewrite /dlsubmx col_mxKd row_mxKl. Qed.\n\nLemma block_mxEdr i j : A (rshift m1 i) (rshift n1 j) = Adr i j.\nProof. by rewrite col_mxEd row_mxEr. Qed.\nLemma block_mxKdr : drsubmx A = Adr.\nProof. by rewrite /drsubmx col_mxKd row_mxKr. Qed.\n\nLemma block_mxEv : A = col_mx (row_mx Aul Aur) (row_mx Adl Adr).\nProof. by []. Qed.\n\nEnd CatBlock.\n\nEnd Block.\n\nSection TrCutBlock.\n\nVariables m1 m2 n1 n2 : nat.\nVariable A : 'M[R]_(m1 + m2, n1 + n2).\n\nLemma trmx_ulsub : (ulsubmx A)^T = ulsubmx A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma trmx_ursub : (ursubmx A)^T = dlsubmx A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma trmx_dlsub : (dlsubmx A)^T = ursubmx A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma trmx_drsub : (drsubmx A)^T = drsubmx A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nEnd TrCutBlock.\n\nSection TrBlock.\nVariables m1 m2 n1 n2 : nat.\nVariables (Aul : 'M[R]_(m1, n1)) (Aur : 'M[R]_(m1, n2)).\nVariables (Adl : 'M[R]_(m2, n1)) (Adr : 'M[R]_(m2, n2)).\n\nLemma tr_block_mx :\n (block_mx Aul Aur Adl Adr)^T = block_mx Aul^T Adl^T Aur^T Adr^T.\nProof.\nrewrite -[_^T]submxK -trmx_ulsub -trmx_ursub -trmx_dlsub -trmx_drsub.\nby rewrite block_mxKul block_mxKur block_mxKdl block_mxKdr.\nQed.\n\nLemma block_mxEh :\n  block_mx Aul Aur Adl Adr = row_mx (col_mx Aul Adl) (col_mx Aur Adr).\nProof. by apply: trmx_inj; rewrite tr_block_mx tr_row_mx 2!tr_col_mx. Qed.\nEnd TrBlock.\n\n(* This lemma has Prenex Implicits to help RL rewrititng with castmx_sym. *)\nLemma block_mxA m1 m2 m3 n1 n2 n3\n   (A11 : 'M_(m1, n1)) (A12 : 'M_(m1, n2)) (A13 : 'M_(m1, n3))\n   (A21 : 'M_(m2, n1)) (A22 : 'M_(m2, n2)) (A23 : 'M_(m2, n3))\n   (A31 : 'M_(m3, n1)) (A32 : 'M_(m3, n2)) (A33 : 'M_(m3, n3)) :\n  let cast := (esym (addnA m1 m2 m3), esym (addnA n1 n2 n3)) in\n  let row1 := row_mx A12 A13 in let col1 := col_mx A21 A31 in\n  let row3 := row_mx A31 A32 in let col3 := col_mx A13 A23 in\n  block_mx A11 row1 col1 (block_mx A22 A23 A32 A33)\n    = castmx cast (block_mx (block_mx A11 A12 A21 A22) col3 row3 A33).\nProof.\nrewrite /= block_mxEh !col_mxA -cast_row_mx -block_mxEv -block_mxEh.\nrewrite block_mxEv block_mxEh !row_mxA -cast_col_mx -block_mxEh -block_mxEv.\nby rewrite castmx_comp etrans_id.\nQed.\nDefinition block_mxAx := block_mxA. (* Bypass Prenex Implicits *)\n\n(* Bijections mxvec : 'M_(m, n) <----> 'rV_(m * n) : vec_mx *)\nSection VecMatrix.\n\nVariables m n : nat.\n\nLemma mxvec_cast : #|{:'I_m * 'I_n}| = (m * n)%N. \nProof. by rewrite card_prod !card_ord. Qed.\n\nDefinition mxvec_index (i : 'I_m) (j : 'I_n) :=\n  cast_ord mxvec_cast (enum_rank (i, j)).\n\nCoInductive is_mxvec_index : 'I_(m * n) -> Type :=\n  IsMxvecIndex i j : is_mxvec_index (mxvec_index i j).\n\nLemma mxvec_indexP k : is_mxvec_index k.\nProof.\nrewrite -[k](cast_ordK (esym mxvec_cast)) esymK.\nby rewrite -[_ k]enum_valK; case: (enum_val _).\nQed.\n\nCoercion pair_of_mxvec_index k (i_k : is_mxvec_index k) :=\n  let: IsMxvecIndex i j := i_k in (i, j).\n\nDefinition mxvec (A : 'M[R]_(m, n)) :=\n  castmx (erefl _, mxvec_cast) (\\row_k A (enum_val k).1 (enum_val k).2).\n\nFact vec_mx_key : unit. Proof. by []. Qed.\nDefinition vec_mx (u : 'rV[R]_(m * n)) :=\n  \\matrix[vec_mx_key]_(i, j) u 0 (mxvec_index i j).\n\nLemma mxvecE A i j : mxvec A 0 (mxvec_index i j) = A i j.\nProof. by rewrite castmxE mxE cast_ordK enum_rankK. Qed.\n\nLemma mxvecK : cancel mxvec vec_mx.\nProof. by move=> A; apply/matrixP=> i j; rewrite mxE mxvecE. Qed.\n\nLemma vec_mxK : cancel vec_mx mxvec.\nProof.\nby move=> u; apply/rowP=> k; case/mxvec_indexP: k => i j; rewrite mxvecE mxE.\nQed.\n\nLemma curry_mxvec_bij : {on 'I_(m * n), bijective (prod_curry mxvec_index)}.\nProof.\nexists (enum_val \\o cast_ord (esym mxvec_cast)) => [[i j] _ | k _] /=.\n  by rewrite cast_ordK enum_rankK.\nby case/mxvec_indexP: k => i j /=; rewrite cast_ordK enum_rankK.\nQed.\n\nEnd VecMatrix.\n\nEnd MatrixStructural.\n\nImplicit Arguments const_mx [R m n].\nImplicit Arguments row_mxA [R m n1 n2 n3 A1 A2 A3].\nImplicit Arguments col_mxA [R m1 m2 m3 n A1 A2 A3].\nImplicit Arguments block_mxA\n  [R m1 m2 m3 n1 n2 n3 A11 A12 A13 A21 A22 A23 A31 A32 A33].\nPrenex Implicits const_mx castmx trmx lsubmx rsubmx usubmx dsubmx row_mx col_mx.\nPrenex Implicits block_mx ulsubmx ursubmx dlsubmx drsubmx.\nPrenex Implicits row_mxA col_mxA block_mxA.\nPrenex Implicits mxvec vec_mx mxvec_indexP mxvecK vec_mxK.\n\nNotation \"A ^T\" := (trmx A) : ring_scope.\n\n(* Matrix parametricity. *)\nSection MapMatrix.\n\nVariables (aT rT : Type) (f : aT -> rT).\n\nFact map_mx_key : unit. Proof. by []. Qed.\nDefinition map_mx m n (A : 'M_(m, n)) := \\matrix[map_mx_key]_(i, j) f (A i j).\n\nNotation \"A ^f\" := (map_mx A) : ring_scope.\n\nSection OneMatrix.\n\nVariables (m n : nat) (A : 'M[aT]_(m, n)).\n\nLemma map_trmx : A^f^T = A^T^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_const_mx a : (const_mx a)^f = const_mx (f a) :> 'M_(m, n).\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_row i : (row i A)^f = row i A^f.\nProof. by apply/rowP=> j; rewrite !mxE. Qed.\n\nLemma map_col j : (col j A)^f = col j A^f.\nProof. by apply/colP=> i; rewrite !mxE. Qed.\n\nLemma map_row' i0 : (row' i0 A)^f = row' i0 A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_col' j0 : (col' j0 A)^f = col' j0 A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_row_perm s : (row_perm s A)^f = row_perm s A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_col_perm s : (col_perm s A)^f = col_perm s A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_xrow i1 i2 : (xrow i1 i2 A)^f = xrow i1 i2 A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_xcol j1 j2 : (xcol j1 j2 A)^f = xcol j1 j2 A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_castmx m' n' c : (castmx c A)^f = castmx c A^f :> 'M_(m', n').\nProof. by apply/matrixP=> i j; rewrite !(castmxE, mxE). Qed.\n\nLemma map_conform_mx m' n' (B : 'M_(m', n')) :\n  (conform_mx B A)^f = conform_mx B^f A^f.\nProof.\nmove: B; have [[<- <-] B|] := eqVneq (m, n) (m', n'). \n  by rewrite !conform_mx_id.\nby rewrite negb_and => neq_mn B; rewrite !nonconform_mx.\nQed.\n\nLemma map_mxvec : (mxvec A)^f = mxvec A^f.\nProof. by apply/rowP=> i; rewrite !(castmxE, mxE). Qed.\n\nLemma map_vec_mx (v : 'rV_(m * n)) : (vec_mx v)^f = vec_mx v^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nEnd OneMatrix.\n\nSection Block.\n\nVariables m1 m2 n1 n2 : nat.\nVariables (Aul : 'M[aT]_(m1, n1)) (Aur : 'M[aT]_(m1, n2)).\nVariables (Adl : 'M[aT]_(m2, n1)) (Adr : 'M[aT]_(m2, n2)).\nVariables (Bh : 'M[aT]_(m1, n1 + n2)) (Bv : 'M[aT]_(m1 + m2, n1)).\nVariable B : 'M[aT]_(m1 + m2, n1 + n2).\n\nLemma map_row_mx : (row_mx Aul Aur)^f = row_mx Aul^f Aur^f.\nProof. by apply/matrixP=> i j; do 2![rewrite !mxE //; case: split => ?]. Qed.\n\nLemma map_col_mx : (col_mx Aul Adl)^f = col_mx Aul^f Adl^f.\nProof. by apply/matrixP=> i j; do 2![rewrite !mxE //; case: split => ?]. Qed.\n\nLemma map_block_mx :\n  (block_mx Aul Aur Adl Adr)^f = block_mx Aul^f Aur^f Adl^f Adr^f.\nProof. by apply/matrixP=> i j; do 3![rewrite !mxE //; case: split => ?]. Qed.\n\nLemma map_lsubmx : (lsubmx Bh)^f = lsubmx Bh^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_rsubmx : (rsubmx Bh)^f = rsubmx Bh^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_usubmx : (usubmx Bv)^f = usubmx Bv^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_dsubmx : (dsubmx Bv)^f = dsubmx Bv^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_ulsubmx : (ulsubmx B)^f = ulsubmx B^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_ursubmx : (ursubmx B)^f = ursubmx B^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_dlsubmx : (dlsubmx B)^f = dlsubmx B^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_drsubmx : (drsubmx B)^f = drsubmx B^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nEnd Block.\n\nEnd MapMatrix.\n\n(*****************************************************************************)\n(********************* Matrix Zmodule (additive) structure *******************)\n(*****************************************************************************)\n\nSection MatrixZmodule.\n\nVariable V : zmodType.\n\nSection FixedDim.\n\nVariables m n : nat.\nImplicit Types A B : 'M[V]_(m, n).\n\nFact oppmx_key : unit. Proof. by []. Qed.\nFact addmx_key : unit. Proof. by []. Qed.\nDefinition oppmx A := \\matrix[oppmx_key]_(i, j) (- A i j).\nDefinition addmx A B := \\matrix[addmx_key]_(i, j) (A i j + B i j).\n(* In principle, diag_mx and scalar_mx could be defined here, but since they *)\n(* only make sense with the graded ring operations, we defer them to the     *)\n(* next section.                                                             *)\n\nLemma addmxA : associative addmx.\nProof. by move=> A B C; apply/matrixP=> i j; rewrite !mxE addrA. Qed.\n\nLemma addmxC : commutative addmx.\nProof. by move=> A B; apply/matrixP=> i j; rewrite !mxE addrC. Qed.\n\nLemma add0mx : left_id (const_mx 0) addmx.\nProof. by move=> A; apply/matrixP=> i j; rewrite !mxE add0r. Qed.\n\nLemma addNmx : left_inverse (const_mx 0) oppmx addmx.\nProof. by move=> A; apply/matrixP=> i j; rewrite !mxE addNr. Qed.\n\nDefinition matrix_zmodMixin := ZmodMixin addmxA addmxC add0mx addNmx.\n\nCanonical matrix_zmodType := Eval hnf in ZmodType 'M[V]_(m, n) matrix_zmodMixin.\n\nLemma mulmxnE A d i j : (A *+ d) i j = A i j *+ d.\nProof. by elim: d => [|d IHd]; rewrite ?mulrS mxE ?IHd. Qed.\n\nLemma summxE I r (P : pred I) (E : I -> 'M_(m, n)) i j :\n  (\\sum_(k <- r | P k) E k) i j = \\sum_(k <- r | P k) E k i j.\nProof. by apply: (big_morph (fun A => A i j)) => [A B|]; rewrite mxE. Qed.\n\nLemma const_mx_is_additive : additive const_mx.\nProof. by move=> a b; apply/matrixP=> i j; rewrite !mxE. Qed.\nCanonical const_mx_additive := Additive const_mx_is_additive.\n\nEnd FixedDim.\n\nSection Additive.\n\nVariables (m n p q : nat) (f : 'I_p -> 'I_q -> 'I_m) (g : 'I_p -> 'I_q -> 'I_n).\n\nDefinition swizzle_mx k (A : 'M[V]_(m, n)) :=\n  \\matrix[k]_(i, j) A (f i j) (g i j).\n\nLemma swizzle_mx_is_additive k : additive (swizzle_mx k).\nProof. by move=> A B; apply/matrixP=> i j; rewrite !mxE. Qed.\nCanonical swizzle_mx_additive k := Additive (swizzle_mx_is_additive k).\n\nEnd Additive.\n\nLocal Notation SwizzleAdd op := [additive of op as swizzle_mx _ _ _].\n\nCanonical trmx_additive m n := SwizzleAdd (@trmx V m n).\nCanonical row_additive m n i := SwizzleAdd (@row V m n i).\nCanonical col_additive m n j := SwizzleAdd (@col V m n j).\nCanonical row'_additive m n i := SwizzleAdd (@row' V m n i).\nCanonical col'_additive m n j := SwizzleAdd (@col' V m n j).\nCanonical row_perm_additive m n s := SwizzleAdd (@row_perm V m n s).\nCanonical col_perm_additive m n s := SwizzleAdd (@col_perm V m n s).\nCanonical xrow_additive m n i1 i2 := SwizzleAdd (@xrow V m n i1 i2).\nCanonical xcol_additive m n j1 j2 := SwizzleAdd (@xcol V m n j1 j2).\nCanonical lsubmx_additive m n1 n2 := SwizzleAdd (@lsubmx V m n1 n2).\nCanonical rsubmx_additive m n1 n2 := SwizzleAdd (@rsubmx V m n1 n2).\nCanonical usubmx_additive m1 m2 n := SwizzleAdd (@usubmx V m1 m2 n).\nCanonical dsubmx_additive m1 m2 n := SwizzleAdd (@dsubmx V m1 m2 n).\nCanonical vec_mx_additive m n := SwizzleAdd (@vec_mx V m n).\nCanonical mxvec_additive m n :=\n  Additive (can2_additive (@vec_mxK V m n) mxvecK).\n\nLemma flatmx0 n : all_equal_to (0 : 'M_(0, n)).\nProof. by move=> A; apply/matrixP=> [] []. Qed.\n\nLemma thinmx0 n : all_equal_to (0 : 'M_(n, 0)).\nProof. by move=> A; apply/matrixP=> i []. Qed.\n\nLemma trmx0 m n : (0 : 'M_(m, n))^T = 0.\nProof. exact: trmx_const. Qed.\n\nLemma row0 m n i0 : row i0 (0 : 'M_(m, n)) = 0.\nProof. exact: row_const. Qed.\n\nLemma col0 m n j0 : col j0 (0 : 'M_(m, n)) = 0.\nProof. exact: col_const. Qed.\n\nLemma mxvec_eq0 m n (A : 'M_(m, n)) : (mxvec A == 0) = (A == 0).\nProof. by rewrite (can2_eq mxvecK vec_mxK) raddf0. Qed.\n\nLemma vec_mx_eq0 m n (v : 'rV_(m * n)) : (vec_mx v == 0) = (v == 0).\nProof. by rewrite (can2_eq vec_mxK mxvecK) raddf0. Qed.\n\nLemma row_mx0 m n1 n2 : row_mx 0 0 = 0 :> 'M_(m, n1 + n2).\nProof. exact: row_mx_const. Qed.\n\nLemma col_mx0 m1 m2 n : col_mx 0 0 = 0 :> 'M_(m1 + m2, n).\nProof. exact: col_mx_const. Qed.\n\nLemma block_mx0 m1 m2 n1 n2 : block_mx 0 0 0 0 = 0 :> 'M_(m1 + m2, n1 + n2).\nProof. exact: block_mx_const. Qed.\n\nLtac split_mxE := apply/matrixP=> i j; do ![rewrite mxE | case: split => ?].\n\nLemma opp_row_mx m n1 n2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  - row_mx A1 A2 = row_mx (- A1) (- A2).\nProof. by split_mxE. Qed.\n\nLemma opp_col_mx m1 m2 n (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  - col_mx A1 A2 = col_mx (- A1) (- A2).\nProof. by split_mxE. Qed.\n\nLemma opp_block_mx m1 m2 n1 n2 (Aul : 'M_(m1, n1)) Aur Adl (Adr : 'M_(m2, n2)) :\n  - block_mx Aul Aur Adl Adr = block_mx (- Aul) (- Aur) (- Adl) (- Adr).\nProof. by rewrite opp_col_mx !opp_row_mx. Qed.\n\nLemma add_row_mx m n1 n2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) B1 B2 :\n  row_mx A1 A2 + row_mx B1 B2 = row_mx (A1 + B1) (A2 + B2).\nProof. by split_mxE. Qed.\n\nLemma add_col_mx m1 m2 n (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) B1 B2 :\n  col_mx A1 A2 + col_mx B1 B2 = col_mx (A1 + B1) (A2 + B2).\nProof. by split_mxE. Qed.\n\nLemma add_block_mx m1 m2 n1 n2 (Aul : 'M_(m1, n1)) Aur Adl (Adr : 'M_(m2, n2))\n                   Bul Bur Bdl Bdr :\n  let A := block_mx Aul Aur Adl Adr in let B := block_mx Bul Bur Bdl Bdr in\n  A + B = block_mx (Aul + Bul) (Aur + Bur) (Adl + Bdl) (Adr + Bdr).\nProof. by rewrite /= add_col_mx !add_row_mx. Qed.\n\nDefinition nz_row m n (A : 'M_(m, n)) :=\n  oapp (fun i => row i A) 0 [pick i | row i A != 0].\n\nLemma nz_row_eq0 m n (A : 'M_(m, n)) : (nz_row A == 0) = (A == 0).\nProof.\nrewrite /nz_row; symmetry; case: pickP => [i /= nzAi | Ai0].\n  by rewrite (negbTE nzAi); apply: contraTF nzAi => /eqP->; rewrite row0 eqxx.\nby rewrite eqxx; apply/eqP/row_matrixP=> i; move/eqP: (Ai0 i) ->; rewrite row0. \nQed.\n\nEnd MatrixZmodule.\n\nSection FinZmodMatrix.\nVariables (V : finZmodType) (m n : nat).\nLocal Notation MV := 'M[V]_(m, n).\n\nCanonical matrix_finZmodType := Eval hnf in [finZmodType of MV].\nCanonical matrix_baseFinGroupType :=\n  Eval hnf in [baseFinGroupType of MV for +%R].\nCanonical matrix_finGroupType := Eval hnf in [finGroupType of MV for +%R].\nEnd FinZmodMatrix.\n\n(* Parametricity over the additive structure. *)\nSection MapZmodMatrix.\n\nVariables (aR rR : zmodType) (f : {additive aR -> rR}) (m n : nat).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\nImplicit Type A : 'M[aR]_(m, n).\n\nLemma map_mx0 : 0^f = 0 :> 'M_(m, n).\nProof. by rewrite map_const_mx raddf0. Qed.\n\nLemma map_mxN A : (- A)^f = - A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE raddfN. Qed.\n\nLemma map_mxD A B : (A + B)^f = A^f + B^f.\nProof. by apply/matrixP=> i j; rewrite !mxE raddfD. Qed.\n\nLemma map_mx_sub A B : (A - B)^f = A^f - B^f.\nProof. by rewrite map_mxD map_mxN. Qed.\n\nDefinition map_mx_sum := big_morph _ map_mxD map_mx0.\n\nCanonical map_mx_additive := Additive map_mx_sub.\n\nEnd MapZmodMatrix.\n\n(*****************************************************************************)\n(*********** Matrix ring module, graded ring, and ring structures ************)\n(*****************************************************************************)\n\nSection MatrixAlgebra.\n\nVariable R : ringType.\n\nSection RingModule.\n\n(* The ring module/vector space structure *)\n\nVariables m n : nat.\nImplicit Types A B : 'M[R]_(m, n).\n\nFact scalemx_key : unit. Proof. by []. Qed.\nDefinition scalemx x A := \\matrix[scalemx_key]_(i, j) (x * A i j).\n\n(* Basis *)\nFact delta_mx_key : unit. Proof. by []. Qed.\nDefinition delta_mx i0 j0 : 'M[R]_(m, n) :=\n  \\matrix[delta_mx_key]_(i, j) ((i == i0) && (j == j0))%:R.\n\nLocal Notation \"x *m: A\" := (scalemx x A) (at level 40) : ring_scope.\n\nLemma scale1mx A : 1 *m: A = A.\nProof. by apply/matrixP=> i j; rewrite !mxE mul1r. Qed.\n\nLemma scalemxDl A x y : (x + y) *m: A = x *m: A + y *m: A.\nProof. by apply/matrixP=> i j; rewrite !mxE mulrDl. Qed.\n\nLemma scalemxDr x A B : x *m: (A + B) = x *m: A + x *m: B.\nProof. by apply/matrixP=> i j; rewrite !mxE mulrDr. Qed.\n\nLemma scalemxA x y A : x *m: (y *m: A) = (x * y) *m: A.\nProof. by apply/matrixP=> i j; rewrite !mxE mulrA. Qed.\n\nDefinition matrix_lmodMixin := \n  LmodMixin scalemxA scale1mx scalemxDr scalemxDl.\n\nCanonical matrix_lmodType :=\n  Eval hnf in LmodType R 'M[R]_(m, n) matrix_lmodMixin.\n\nLemma scalemx_const a b : a *: const_mx b = const_mx (a * b).\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma matrix_sum_delta A :\n  A = \\sum_(i < m) \\sum_(j < n) A i j *: delta_mx i j.\nProof.\napply/matrixP=> i j.\nrewrite summxE (bigD1 i) // summxE (bigD1 j) //= !mxE !eqxx mulr1.\nrewrite !big1 ?addr0 //= => [i' | j']; rewrite eq_sym => /negbTE diff.\n  by rewrite summxE big1 // => j' _; rewrite !mxE diff mulr0.\nby rewrite !mxE eqxx diff mulr0.\nQed.\n\nEnd RingModule.\n\nSection StructuralLinear.\n\nLemma swizzle_mx_is_scalable m n p q f g k :\n  scalable (@swizzle_mx R m n p q f g k).\nProof. by move=> a A; apply/matrixP=> i j; rewrite !mxE. Qed.\nCanonical swizzle_mx_scalable m n p q f g k :=\n  AddLinear (@swizzle_mx_is_scalable m n p q f g k).\n\nLocal Notation SwizzleLin op := [linear of op as swizzle_mx _ _ _].\n\nCanonical trmx_linear m n := SwizzleLin (@trmx R m n).\nCanonical row_linear m n i := SwizzleLin (@row R m n i).\nCanonical col_linear m n j := SwizzleLin (@col R m n j).\nCanonical row'_linear m n i := SwizzleLin (@row' R m n i).\nCanonical col'_linear m n j := SwizzleLin (@col' R m n j).\nCanonical row_perm_linear m n s := SwizzleLin (@row_perm R m n s).\nCanonical col_perm_linear m n s := SwizzleLin (@col_perm R m n s).\nCanonical xrow_linear m n i1 i2 := SwizzleLin (@xrow R m n i1 i2).\nCanonical xcol_linear m n j1 j2 := SwizzleLin (@xcol R m n j1 j2).\nCanonical lsubmx_linear m n1 n2 := SwizzleLin (@lsubmx R m n1 n2).\nCanonical rsubmx_linear m n1 n2 := SwizzleLin (@rsubmx R m n1 n2).\nCanonical usubmx_linear m1 m2 n := SwizzleLin (@usubmx R m1 m2 n).\nCanonical dsubmx_linear m1 m2 n := SwizzleLin (@dsubmx R m1 m2 n).\nCanonical vec_mx_linear m n := SwizzleLin (@vec_mx R m n).\nDefinition mxvec_is_linear m n := can2_linear (@vec_mxK R m n) mxvecK.\nCanonical mxvec_linear m n := AddLinear (@mxvec_is_linear m n).\n\nEnd StructuralLinear.\n\nLemma trmx_delta m n i j : (delta_mx i j)^T = delta_mx j i :> 'M[R]_(n, m).\nProof. by apply/matrixP=> i' j'; rewrite !mxE andbC. Qed.\n\nLemma row_sum_delta n (u : 'rV_n) : u = \\sum_(j < n) u 0 j *: delta_mx 0 j.\nProof. by rewrite {1}[u]matrix_sum_delta big_ord1. Qed.\n\nLemma delta_mx_lshift m n1 n2 i j :\n  delta_mx i (lshift n2 j) = row_mx (delta_mx i j) 0 :> 'M_(m, n1 + n2).\nProof.\napply/matrixP=> i' j'; rewrite !mxE -(can_eq (@splitK _ _)).\nby rewrite (unsplitK (inl _ _)); case: split => ?; rewrite mxE ?andbF.\nQed.\n\nLemma delta_mx_rshift m n1 n2 i j :\n  delta_mx i (rshift n1 j) = row_mx 0 (delta_mx i j) :> 'M_(m, n1 + n2).\nProof.\napply/matrixP=> i' j'; rewrite !mxE -(can_eq (@splitK _ _)).\nby rewrite (unsplitK (inr _ _)); case: split => ?; rewrite mxE ?andbF.\nQed.\n\nLemma delta_mx_ushift m1 m2 n i j :\n  delta_mx (lshift m2 i) j = col_mx (delta_mx i j) 0 :> 'M_(m1 + m2, n).\nProof.\napply/matrixP=> i' j'; rewrite !mxE -(can_eq (@splitK _ _)).\nby rewrite (unsplitK (inl _ _)); case: split => ?; rewrite mxE.\nQed.\n\nLemma delta_mx_dshift m1 m2 n i j :\n  delta_mx (rshift m1 i) j = col_mx 0 (delta_mx i j) :> 'M_(m1 + m2, n).\nProof.\napply/matrixP=> i' j'; rewrite !mxE -(can_eq (@splitK _ _)).\nby rewrite (unsplitK (inr _ _)); case: split => ?; rewrite mxE.\nQed.\n\nLemma vec_mx_delta m n i j :\n  vec_mx (delta_mx 0 (mxvec_index i j)) = delta_mx i j :> 'M_(m, n).\nProof.\nby apply/matrixP=> i' j'; rewrite !mxE /= [_ == _](inj_eq enum_rank_inj).\nQed.\n\nLemma mxvec_delta m n i j :\n  mxvec (delta_mx i j) = delta_mx 0 (mxvec_index i j) :> 'rV_(m * n).\nProof. by rewrite -vec_mx_delta vec_mxK. Qed.\n\nLtac split_mxE := apply/matrixP=> i j; do ![rewrite mxE | case: split => ?].\n\nLemma scale_row_mx m n1 n2 a (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  a *: row_mx A1 A2 = row_mx (a *: A1) (a *: A2).\nProof. by split_mxE. Qed.\n\nLemma scale_col_mx m1 m2 n a (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  a *: col_mx A1 A2 = col_mx (a *: A1) (a *: A2).\nProof. by split_mxE. Qed.\n\nLemma scale_block_mx m1 m2 n1 n2 a (Aul : 'M_(m1, n1)) (Aur : 'M_(m1, n2))\n                                   (Adl : 'M_(m2, n1)) (Adr : 'M_(m2, n2)) :\n  a *: block_mx Aul Aur Adl Adr\n     = block_mx (a *: Aul) (a *: Aur) (a *: Adl) (a *: Adr).\nProof. by rewrite scale_col_mx !scale_row_mx. Qed.\n\n(* Diagonal matrices *)\n\nFact diag_mx_key : unit. Proof. by []. Qed.\nDefinition diag_mx n (d : 'rV[R]_n) :=\n  \\matrix[diag_mx_key]_(i, j) (d 0 i *+ (i == j)).\n\nLemma tr_diag_mx n (d : 'rV_n) : (diag_mx d)^T = diag_mx d.\nProof. by apply/matrixP=> i j; rewrite !mxE eq_sym; case: eqP => // ->. Qed.\n\nLemma diag_mx_is_linear n : linear (@diag_mx n).\nProof.\nby move=> a A B; apply/matrixP=> i j; rewrite !mxE mulrnAr mulrnDl.\nQed.\nCanonical diag_mx_additive n := Additive (@diag_mx_is_linear n).\nCanonical diag_mx_linear n := Linear (@diag_mx_is_linear n).\n\nLemma diag_mx_sum_delta n (d : 'rV_n) :\n  diag_mx d = \\sum_i d 0 i *: delta_mx i i.\nProof.\napply/matrixP=> i j; rewrite summxE (bigD1 i) //= !mxE eqxx /=.\nrewrite eq_sym mulr_natr big1 ?addr0 // => i' ne_i'i.\nby rewrite !mxE eq_sym (negbTE ne_i'i) mulr0.\nQed.\n\n(* Scalar matrix : a diagonal matrix with a constant on the diagonal *)\nSection ScalarMx.\n\nVariable n : nat.\n\nFact scalar_mx_key : unit. Proof. by []. Qed.\nDefinition scalar_mx x : 'M[R]_n :=\n  \\matrix[scalar_mx_key]_(i , j) (x *+ (i == j)).\nNotation \"x %:M\" := (scalar_mx x) : ring_scope.\n\nLemma diag_const_mx a : diag_mx (const_mx a) = a%:M :> 'M_n.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_scalar_mx a : (a%:M)^T = a%:M.\nProof. by apply/matrixP=> i j; rewrite !mxE eq_sym. Qed.\n\nLemma trmx1 : (1%:M)^T = 1%:M. Proof. exact: tr_scalar_mx. Qed.\n\nLemma scalar_mx_is_additive : additive scalar_mx.\nProof. by move=> a b; rewrite -!diag_const_mx !raddfB. Qed.\nCanonical scalar_mx_additive := Additive scalar_mx_is_additive.\n\nLemma scale_scalar_mx a1 a2 : a1 *: a2%:M = (a1 * a2)%:M :> 'M_n.\nProof. by apply/matrixP=> i j; rewrite !mxE mulrnAr. Qed.\n\nLemma scalemx1 a : a *: 1%:M = a%:M.\nProof. by rewrite scale_scalar_mx mulr1. Qed.\n\nLemma scalar_mx_sum_delta a : a%:M = \\sum_i a *: delta_mx i i.\nProof.\nby rewrite -diag_const_mx diag_mx_sum_delta; apply: eq_bigr => i _; rewrite mxE.\nQed.\n\nLemma mx1_sum_delta : 1%:M = \\sum_i delta_mx i i.\nProof. by rewrite [1%:M]scalar_mx_sum_delta -scaler_sumr scale1r. Qed.\n\nLemma row1 i : row i 1%:M = delta_mx 0 i.\nProof. by apply/rowP=> j; rewrite !mxE eq_sym. Qed.\n\nDefinition is_scalar_mx (A : 'M[R]_n) :=\n  if insub 0%N is Some i then A == (A i i)%:M else true.\n\nLemma is_scalar_mxP A : reflect (exists a, A = a%:M) (is_scalar_mx A).\nProof.\nrewrite /is_scalar_mx; case: insubP => [i _ _ | ].\n  by apply: (iffP eqP) => [|[a ->]]; [exists (A i i) | rewrite mxE eqxx].\nrewrite -eqn0Ngt => /eqP n0; left; exists 0.\nby rewrite raddf0; rewrite n0 in A *; rewrite [A]flatmx0.\nQed.\n\nLemma scalar_mx_is_scalar a : is_scalar_mx a%:M.\nProof. by apply/is_scalar_mxP; exists a. Qed.\n\nLemma mx0_is_scalar : is_scalar_mx 0.\nProof. by apply/is_scalar_mxP; exists 0; rewrite raddf0. Qed.\n\nEnd ScalarMx.\n\nNotation \"x %:M\" := (scalar_mx _ x) : ring_scope.\n\nLemma mx11_scalar (A : 'M_1) : A = (A 0 0)%:M.\nProof. by apply/rowP=> j; rewrite ord1 mxE. Qed.\n\nLemma scalar_mx_block n1 n2 a : a%:M = block_mx a%:M 0 0 a%:M :> 'M_(n1 + n2).\nProof.\napply/matrixP=> i j; rewrite !mxE -val_eqE /=.\nby do 2![case: splitP => ? ->; rewrite !mxE];\n  rewrite ?eqn_add2l // -?(eq_sym (n1 + _)%N) eqn_leq leqNgt lshift_subproof.\nQed.\n\n(* Matrix multiplication using bigops. *)\nFact mulmx_key : unit. Proof. by []. Qed.\nDefinition mulmx {m n p} (A : 'M_(m, n)) (B : 'M_(n, p)) : 'M[R]_(m, p) :=\n  \\matrix[mulmx_key]_(i, k) \\sum_j (A i j * B j k).\n\nLocal Notation \"A *m B\" := (mulmx A B) : ring_scope.\n\nLemma mulmxA m n p q (A : 'M_(m, n)) (B : 'M_(n, p)) (C : 'M_(p, q)) :\n  A *m (B *m C) = A *m B *m C.\nProof.\napply/matrixP=> i l; rewrite !mxE.\ntransitivity (\\sum_j (\\sum_k (A i j * (B j k * C k l)))).\n  by apply: eq_bigr => j _; rewrite mxE big_distrr.\nrewrite exchange_big; apply: eq_bigr => j _; rewrite mxE big_distrl /=.\nby apply: eq_bigr => k _; rewrite mulrA.\nQed.\n\nLemma mul0mx m n p (A : 'M_(n, p)) : 0 *m A = 0 :> 'M_(m, p).\nProof.\nby apply/matrixP=> i k; rewrite !mxE big1 //= => j _; rewrite mxE mul0r.\nQed.\n\nLemma mulmx0 m n p (A : 'M_(m, n)) : A *m 0 = 0 :> 'M_(m, p).\nProof.\nby apply/matrixP=> i k; rewrite !mxE big1 // => j _; rewrite mxE mulr0.\nQed.\n\nLemma mulmxN m n p (A : 'M_(m, n)) (B : 'M_(n, p)) : A *m (- B) = - (A *m B).\nProof.\napply/matrixP=> i k; rewrite !mxE -sumrN.\nby apply: eq_bigr => j _; rewrite mxE mulrN.\nQed.\n\nLemma mulNmx m n p (A : 'M_(m, n)) (B : 'M_(n, p)) : - A *m B = - (A *m B).\nProof.\napply/matrixP=> i k; rewrite !mxE -sumrN.\nby apply: eq_bigr => j _; rewrite mxE mulNr.\nQed.\n\nLemma mulmxDl m n p (A1 A2 : 'M_(m, n)) (B : 'M_(n, p)) :\n  (A1 + A2) *m B = A1 *m B + A2 *m B.\nProof.\napply/matrixP=> i k; rewrite !mxE -big_split /=.\nby apply: eq_bigr => j _; rewrite !mxE -mulrDl.\nQed.\n\nLemma mulmxDr m n p (A : 'M_(m, n)) (B1 B2 : 'M_(n, p)) :\n  A *m (B1 + B2) = A *m B1 + A *m B2.\nProof.\napply/matrixP=> i k; rewrite !mxE -big_split /=.\nby apply: eq_bigr => j _; rewrite mxE mulrDr.\nQed.\n\nLemma mulmxBl m n p (A1 A2 : 'M_(m, n)) (B : 'M_(n, p)) :\n  (A1 - A2) *m B = A1 *m B - A2 *m B.\nProof. by rewrite mulmxDl mulNmx. Qed.\n\nLemma mulmxBr m n p (A : 'M_(m, n)) (B1 B2 : 'M_(n, p)) :\n  A *m (B1 - B2) = A *m B1 - A *m B2.\nProof. by rewrite mulmxDr mulmxN. Qed.\n\nLemma mulmx_suml m n p (A : 'M_(n, p)) I r P (B_ : I -> 'M_(m, n)) :\n   (\\sum_(i <- r | P i) B_ i) *m A = \\sum_(i <- r | P i) B_ i *m A.\nProof.\nby apply: (big_morph (mulmx^~ A)) => [B C|]; rewrite ?mul0mx ?mulmxDl.\nQed.\n\nLemma mulmx_sumr m n p (A : 'M_(m, n)) I r P (B_ : I -> 'M_(n, p)) :\n   A *m (\\sum_(i <- r | P i) B_ i) = \\sum_(i <- r | P i) A *m B_ i.\nProof.\nby apply: (big_morph (mulmx A)) => [B C|]; rewrite ?mulmx0 ?mulmxDr.\nQed.\n\nLemma scalemxAl m n p a (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  a *: (A *m B) = (a *: A) *m B.\nProof.\napply/matrixP=> i k; rewrite !mxE big_distrr /=.\nby apply: eq_bigr => j _; rewrite mulrA mxE.\nQed.\n(* Right scaling associativity requires a commutative ring *)\n\nLemma rowE m n i (A : 'M_(m, n)) : row i A = delta_mx 0 i *m A.\nProof.\napply/rowP=> j; rewrite !mxE (bigD1 i) //= mxE !eqxx mul1r.\nby rewrite big1 ?addr0 // => i' ne_i'i; rewrite mxE /= (negbTE ne_i'i) mul0r.\nQed.\n\nLemma row_mul m n p (i : 'I_m) A (B : 'M_(n, p)) :\n  row i (A *m B) = row i A *m B.\nProof. by rewrite !rowE mulmxA. Qed.\n\nLemma mulmx_sum_row m n (u : 'rV_m) (A : 'M_(m, n)) :\n  u *m A = \\sum_i u 0 i *: row i A.\nProof.\nby apply/rowP=> j; rewrite mxE summxE; apply: eq_bigr => i _; rewrite !mxE.\nQed.\n\nLemma mul_delta_mx_cond m n p (j1 j2 : 'I_n) (i1 : 'I_m) (k2 : 'I_p) :\n  delta_mx i1 j1 *m delta_mx j2 k2 = delta_mx i1 k2 *+ (j1 == j2).\nProof.\napply/matrixP=> i k; rewrite !mxE (bigD1 j1) //=.\nrewrite mulmxnE !mxE !eqxx andbT -natrM -mulrnA !mulnb !andbA andbAC.\nby rewrite big1 ?addr0 // => j; rewrite !mxE andbC -natrM; move/negbTE->.\nQed.\n\nLemma mul_delta_mx m n p (j : 'I_n) (i : 'I_m) (k : 'I_p) :\n  delta_mx i j *m delta_mx j k = delta_mx i k.\nProof. by rewrite mul_delta_mx_cond eqxx. Qed.\n\nLemma mul_delta_mx_0 m n p (j1 j2 : 'I_n) (i1 : 'I_m) (k2 : 'I_p) :\n  j1 != j2 -> delta_mx i1 j1 *m delta_mx j2 k2 = 0.\nProof. by rewrite mul_delta_mx_cond => /negbTE->. Qed.\n\nLemma mul_diag_mx m n d (A : 'M_(m, n)) :\n  diag_mx d *m A = \\matrix_(i, j) (d 0 i * A i j).\nProof.\napply/matrixP=> i j; rewrite !mxE (bigD1 i) //= mxE eqxx big1 ?addr0 // => i'.\nby rewrite mxE eq_sym mulrnAl => /negbTE->.\nQed.\n\nLemma mul_mx_diag m n (A : 'M_(m, n)) d :\n  A *m diag_mx d = \\matrix_(i, j) (A i j * d 0 j).\nProof.\napply/matrixP=> i j; rewrite !mxE (bigD1 j) //= mxE eqxx big1 ?addr0 // => i'.\nby rewrite mxE eq_sym mulrnAr; move/negbTE->.\nQed.\n\nLemma mulmx_diag n (d e : 'rV_n) :\n  diag_mx d *m diag_mx e = diag_mx (\\row_j (d 0 j * e 0 j)).\nProof. by apply/matrixP=> i j; rewrite mul_diag_mx !mxE mulrnAr. Qed.\n\nLemma mul_scalar_mx m n a (A : 'M_(m, n)) : a%:M *m A = a *: A.\nProof.\nby rewrite -diag_const_mx mul_diag_mx; apply/matrixP=> i j; rewrite !mxE.\nQed.\n\nLemma scalar_mxM n a b : (a * b)%:M = a%:M *m b%:M :> 'M_n.\nProof. by rewrite mul_scalar_mx scale_scalar_mx. Qed.\n\nLemma mul1mx m n (A : 'M_(m, n)) : 1%:M *m A = A.\nProof. by rewrite mul_scalar_mx scale1r. Qed.\n\nLemma mulmx1 m n (A : 'M_(m, n)) : A *m 1%:M = A.\nProof.\nrewrite -diag_const_mx mul_mx_diag.\nby apply/matrixP=> i j; rewrite !mxE mulr1.\nQed.\n\nLemma mul_col_perm m n p s (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  col_perm s A *m B = A *m row_perm s^-1 B.\nProof.\napply/matrixP=> i k; rewrite !mxE (reindex_inj (@perm_inj _ s^-1)).\nby apply: eq_bigr => j _ /=; rewrite !mxE permKV.\nQed.\n\nLemma mul_row_perm m n p s (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  A *m row_perm s B = col_perm s^-1 A *m B.\nProof. by rewrite mul_col_perm invgK. Qed.\n\nLemma mul_xcol m n p j1 j2 (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  xcol j1 j2 A *m B = A *m xrow j1 j2 B.\nProof. by rewrite mul_col_perm tpermV. Qed.\n\n(* Permutation matrix *)\n\nDefinition perm_mx n s : 'M_n := row_perm s 1%:M.\n\nDefinition tperm_mx n i1 i2 : 'M_n := perm_mx (tperm i1 i2).\n\nLemma col_permE m n s (A : 'M_(m, n)) : col_perm s A = A *m perm_mx s^-1.\nProof. by rewrite mul_row_perm mulmx1 invgK. Qed.\n\nLemma row_permE m n s (A : 'M_(m, n)) : row_perm s A = perm_mx s *m A.\nProof.\nby rewrite -[perm_mx _]mul1mx mul_row_perm mulmx1 -mul_row_perm mul1mx.\nQed.\n\nLemma xcolE m n j1 j2 (A : 'M_(m, n)) : xcol j1 j2 A = A *m tperm_mx j1 j2.\nProof. by rewrite /xcol col_permE tpermV. Qed.\n\nLemma xrowE m n i1 i2 (A : 'M_(m, n)) : xrow i1 i2 A = tperm_mx i1 i2 *m A.\nProof. exact: row_permE. Qed.\n\nLemma tr_perm_mx n (s : 'S_n) : (perm_mx s)^T = perm_mx s^-1.\nProof. by rewrite -[_^T]mulmx1 tr_row_perm mul_col_perm trmx1 mul1mx. Qed.\n\nLemma tr_tperm_mx n i1 i2 : (tperm_mx i1 i2)^T = tperm_mx i1 i2 :> 'M_n.\nProof. by rewrite tr_perm_mx tpermV. Qed.\n\nLemma perm_mx1 n : perm_mx 1 = 1%:M :> 'M_n.\nProof. exact: row_perm1. Qed.\n\nLemma perm_mxM n (s t : 'S_n) : perm_mx (s * t) = perm_mx s *m perm_mx t.\nProof. by rewrite -row_permE -row_permM. Qed.\n\nDefinition is_perm_mx n (A : 'M_n) := [exists s, A == perm_mx s].\n\nLemma is_perm_mxP n (A : 'M_n) :\n  reflect (exists s, A = perm_mx s) (is_perm_mx A).\nProof. by apply: (iffP existsP) => [] [s /eqP]; exists s. Qed.\n\nLemma perm_mx_is_perm n (s : 'S_n) : is_perm_mx (perm_mx s).\nProof. by apply/is_perm_mxP; exists s. Qed.\n\nLemma is_perm_mx1 n : is_perm_mx (1%:M : 'M_n).\nProof. by rewrite -perm_mx1 perm_mx_is_perm. Qed.\n\nLemma is_perm_mxMl n (A B : 'M_n) :\n  is_perm_mx A -> is_perm_mx (A *m B) = is_perm_mx B.\nProof.\ncase/is_perm_mxP=> s ->.\napply/is_perm_mxP/is_perm_mxP=> [[t def_t] | [t ->]]; last first.\n  by exists (s * t)%g; rewrite perm_mxM.\nexists (s^-1 * t)%g.\nby rewrite perm_mxM -def_t -!row_permE -row_permM mulVg row_perm1.\nQed.\n\nLemma is_perm_mx_tr n (A : 'M_n) : is_perm_mx A^T = is_perm_mx A.\nProof.\napply/is_perm_mxP/is_perm_mxP=> [[t def_t] | [t ->]]; exists t^-1%g.\n  by rewrite -tr_perm_mx -def_t trmxK.\nby rewrite tr_perm_mx.\nQed.\n\nLemma is_perm_mxMr n (A B : 'M_n) :\n  is_perm_mx B -> is_perm_mx (A *m B) = is_perm_mx A.\nProof.\ncase/is_perm_mxP=> s ->.\nrewrite -[s]invgK -col_permE -is_perm_mx_tr tr_col_perm row_permE.\nby rewrite is_perm_mxMl (perm_mx_is_perm, is_perm_mx_tr).\nQed.\n\n(* Partial identity matrix (used in rank decomposition). *)\n\nFact pid_mx_key : unit. Proof. by []. Qed.\nDefinition pid_mx {m n} r : 'M[R]_(m, n) :=\n  \\matrix[pid_mx_key]_(i, j) ((i == j :> nat) && (i < r))%:R.\n\nLemma pid_mx_0 m n : pid_mx 0 = 0 :> 'M_(m, n).\nProof. by apply/matrixP=> i j; rewrite !mxE andbF. Qed.\n\nLemma pid_mx_1 r : pid_mx r = 1%:M :> 'M_r.\nProof. by apply/matrixP=> i j; rewrite !mxE ltn_ord andbT. Qed.\n\nLemma pid_mx_row n r : pid_mx r = row_mx 1%:M 0 :> 'M_(r, r + n).\nProof.\napply/matrixP=> i j; rewrite !mxE ltn_ord andbT.\ncase: splitP => j' ->; rewrite !mxE // .\nby rewrite eqn_leq andbC leqNgt lshift_subproof.\nQed.\n\nLemma pid_mx_col m r : pid_mx r = col_mx 1%:M 0 :> 'M_(r + m, r).\nProof.\napply/matrixP=> i j; rewrite !mxE andbC.\nby case: splitP => i' ->; rewrite !mxE // eq_sym.\nQed.\n\nLemma pid_mx_block m n r : pid_mx r = block_mx 1%:M 0 0 0 :> 'M_(r + m, r + n).\nProof.\napply/matrixP=> i j; rewrite !mxE row_mx0 andbC.\ncase: splitP => i' ->; rewrite !mxE //; case: splitP => j' ->; rewrite !mxE //=.\nby rewrite eqn_leq andbC leqNgt lshift_subproof.\nQed.\n\nLemma tr_pid_mx m n r : (pid_mx r)^T = pid_mx r :> 'M_(n, m).\nProof. by apply/matrixP=> i j; rewrite !mxE eq_sym; case: eqP => // ->. Qed.\n\nLemma pid_mx_minv m n r : pid_mx (minn m r) = pid_mx r :> 'M_(m, n).\nProof. by apply/matrixP=> i j; rewrite !mxE leq_min ltn_ord. Qed.\n \nLemma pid_mx_minh m n r : pid_mx (minn n r) = pid_mx r :> 'M_(m, n).\nProof. by apply: trmx_inj; rewrite !tr_pid_mx pid_mx_minv. Qed.\n\nLemma mul_pid_mx m n p q r :\n  (pid_mx q : 'M_(m, n)) *m (pid_mx r : 'M_(n, p)) = pid_mx (minn n (minn q r)).\nProof.\napply/matrixP=> i k; rewrite !mxE !leq_min.\nhave [le_n_i | lt_i_n] := leqP n i. \n  rewrite andbF big1 // => j _.\n  by rewrite -pid_mx_minh !mxE leq_min ltnNge le_n_i andbF mul0r.\nrewrite (bigD1 (Ordinal lt_i_n)) //= big1 ?addr0 => [|j].\n  by rewrite !mxE eqxx /= -natrM mulnb andbCA.\nby rewrite -val_eqE /= !mxE eq_sym -natrM => /negbTE->.\nQed.\n\nLemma pid_mx_id m n p r :\n  r <= n -> (pid_mx r : 'M_(m, n)) *m (pid_mx r : 'M_(n, p)) = pid_mx r.\nProof. by move=> le_r_n; rewrite mul_pid_mx minnn (minn_idPr _). Qed.\n\nDefinition copid_mx {n} r : 'M_n := 1%:M - pid_mx r.\n\nLemma mul_copid_mx_pid m n r :\n  r <= m -> copid_mx r *m pid_mx r = 0 :> 'M_(m, n).\nProof. by move=> le_r_m; rewrite mulmxBl mul1mx pid_mx_id ?subrr. Qed.\n\nLemma mul_pid_mx_copid m n r :\n  r <= n -> pid_mx r *m copid_mx r = 0 :> 'M_(m, n).\nProof. by move=> le_r_n; rewrite mulmxBr mulmx1 pid_mx_id ?subrr. Qed.\n\nLemma copid_mx_id n r :\n  r <= n -> copid_mx r *m copid_mx r = copid_mx r :> 'M_n.\nProof.\nby move=> le_r_n; rewrite mulmxBl mul1mx mul_pid_mx_copid // oppr0 addr0.\nQed.\n\n(* Block products; we cover all 1 x 2, 2 x 1, and 2 x 2 block products. *)\nLemma mul_mx_row m n p1 p2 (A : 'M_(m, n)) (Bl : 'M_(n, p1)) (Br : 'M_(n, p2)) :\n  A *m row_mx Bl Br = row_mx (A *m Bl) (A *m Br).\nProof.\napply/matrixP=> i k; rewrite !mxE.\nby case defk: (split k); rewrite mxE; apply: eq_bigr => j _; rewrite mxE defk.\nQed.\n\nLemma mul_col_mx m1 m2 n p (Au : 'M_(m1, n)) (Ad : 'M_(m2, n)) (B : 'M_(n, p)) :\n  col_mx Au Ad *m B = col_mx (Au *m B) (Ad *m B).\nProof.\napply/matrixP=> i k; rewrite !mxE.\nby case defi: (split i); rewrite mxE; apply: eq_bigr => j _; rewrite mxE defi.\nQed.\n\nLemma mul_row_col m n1 n2 p (Al : 'M_(m, n1)) (Ar : 'M_(m, n2))\n                            (Bu : 'M_(n1, p)) (Bd : 'M_(n2, p)) :\n  row_mx Al Ar *m col_mx Bu Bd = Al *m Bu + Ar *m Bd.\nProof.\napply/matrixP=> i k; rewrite !mxE big_split_ord /=.\ncongr (_ + _); apply: eq_bigr => j _; first by rewrite row_mxEl col_mxEu.\nby rewrite row_mxEr col_mxEd.\nQed.\n\nLemma mul_col_row m1 m2 n p1 p2 (Au : 'M_(m1, n)) (Ad : 'M_(m2, n))\n                                (Bl : 'M_(n, p1)) (Br : 'M_(n, p2)) :\n  col_mx Au Ad *m row_mx Bl Br\n     = block_mx (Au *m Bl) (Au *m Br) (Ad *m Bl) (Ad *m Br).\nProof. by rewrite mul_col_mx !mul_mx_row. Qed.\n\nLemma mul_row_block m n1 n2 p1 p2 (Al : 'M_(m, n1)) (Ar : 'M_(m, n2))\n                                  (Bul : 'M_(n1, p1)) (Bur : 'M_(n1, p2))\n                                  (Bdl : 'M_(n2, p1)) (Bdr : 'M_(n2, p2)) :\n  row_mx Al Ar *m block_mx Bul Bur Bdl Bdr\n   = row_mx (Al *m Bul + Ar *m Bdl) (Al *m Bur + Ar *m Bdr).\nProof. by rewrite block_mxEh mul_mx_row !mul_row_col. Qed.\n\nLemma mul_block_col m1 m2 n1 n2 p (Aul : 'M_(m1, n1)) (Aur : 'M_(m1, n2))\n                                  (Adl : 'M_(m2, n1)) (Adr : 'M_(m2, n2))\n                                  (Bu : 'M_(n1, p)) (Bd : 'M_(n2, p)) :\n  block_mx Aul Aur Adl Adr *m col_mx Bu Bd\n   = col_mx (Aul *m Bu + Aur *m Bd) (Adl *m Bu + Adr *m Bd).\nProof. by rewrite mul_col_mx !mul_row_col. Qed.\n\nLemma mulmx_block m1 m2 n1 n2 p1 p2 (Aul : 'M_(m1, n1)) (Aur : 'M_(m1, n2))\n                                    (Adl : 'M_(m2, n1)) (Adr : 'M_(m2, n2))\n                                    (Bul : 'M_(n1, p1)) (Bur : 'M_(n1, p2))\n                                    (Bdl : 'M_(n2, p1)) (Bdr : 'M_(n2, p2)) :\n  block_mx Aul Aur Adl Adr *m block_mx Bul Bur Bdl Bdr\n    = block_mx (Aul *m Bul + Aur *m Bdl) (Aul *m Bur + Aur *m Bdr)\n               (Adl *m Bul + Adr *m Bdl) (Adl *m Bur + Adr *m Bdr).\nProof. by rewrite mul_col_mx !mul_row_block. Qed.\n\n(* Correspondance between matrices and linear function on row vectors. *) \nSection LinRowVector.\n\nVariables m n : nat.\n\nFact lin1_mx_key : unit. Proof. by []. Qed.\nDefinition lin1_mx (f : 'rV[R]_m -> 'rV[R]_n) :=\n  \\matrix[lin1_mx_key]_(i, j) f (delta_mx 0 i) 0 j.\n\nVariable f : {linear 'rV[R]_m -> 'rV[R]_n}.\n\nLemma mul_rV_lin1 u : u *m lin1_mx f = f u.\nProof.\nrewrite {2}[u]matrix_sum_delta big_ord1 linear_sum; apply/rowP=> i.\nby rewrite mxE summxE; apply: eq_bigr => j _; rewrite linearZ !mxE.\nQed.\n\nEnd LinRowVector.\n\n(* Correspondance between matrices and linear function on matrices. *) \nSection LinMatrix.\n\nVariables m1 n1 m2 n2 : nat.\n\nDefinition lin_mx (f : 'M[R]_(m1, n1) -> 'M[R]_(m2, n2)) :=\n  lin1_mx (mxvec \\o f \\o vec_mx).\n\nVariable f : {linear 'M[R]_(m1, n1) -> 'M[R]_(m2, n2)}.\n\nLemma mul_rV_lin u : u *m lin_mx f = mxvec (f (vec_mx u)).\nProof. exact: mul_rV_lin1. Qed.\n\nLemma mul_vec_lin A : mxvec A *m lin_mx f = mxvec (f A).\nProof. by rewrite mul_rV_lin mxvecK. Qed.\n\nLemma mx_rV_lin u : vec_mx (u *m lin_mx f) = f (vec_mx u).\nProof. by rewrite mul_rV_lin mxvecK. Qed.\n\nLemma mx_vec_lin A : vec_mx (mxvec A *m lin_mx f) = f A.\nProof. by rewrite mul_rV_lin !mxvecK. Qed.\n\nEnd LinMatrix.\n\nCanonical mulmx_additive m n p A := Additive (@mulmxBr m n p A).\n\nSection Mulmxr.\n\nVariables m n p : nat.\nImplicit Type A : 'M[R]_(m, n).\nImplicit Type B : 'M[R]_(n, p).\n\nDefinition mulmxr_head t B A := let: tt := t in A *m B.\nLocal Notation mulmxr := (mulmxr_head tt).\n\nDefinition lin_mulmxr B := lin_mx (mulmxr B).\n\nLemma mulmxr_is_linear B : linear (mulmxr B).\nProof. by move=> a A1 A2; rewrite /= mulmxDl scalemxAl. Qed.\nCanonical mulmxr_additive B := Additive (mulmxr_is_linear B).\nCanonical mulmxr_linear B := Linear (mulmxr_is_linear B).\n\nLemma lin_mulmxr_is_linear : linear lin_mulmxr.\nProof.\nmove=> a A B; apply/row_matrixP; case/mxvec_indexP=> i j.\nrewrite linearP /= !rowE !mul_rV_lin /= vec_mx_delta -linearP mulmxDr.\ncongr (mxvec (_ + _)); apply/row_matrixP=> k.\nrewrite linearZ /= !row_mul rowE mul_delta_mx_cond.\nby case: (k == i); [rewrite -!rowE linearZ | rewrite !mul0mx raddf0]. \nQed.\nCanonical lin_mulmxr_additive := Additive lin_mulmxr_is_linear.\nCanonical lin_mulmxr_linear := Linear lin_mulmxr_is_linear.\n\nEnd Mulmxr.\n\n(* The trace. *)\nSection Trace.\n\nVariable n : nat.\n\nDefinition mxtrace (A : 'M[R]_n) := \\sum_i A i i.\nLocal Notation \"'\\tr' A\" := (mxtrace A) : ring_scope.\n\nLemma mxtrace_tr A : \\tr A^T = \\tr A.\nProof. by apply: eq_bigr=> i _; rewrite mxE. Qed.\n\nLemma mxtrace_is_scalar : scalar mxtrace.\nProof.\nmove=> a A B; rewrite mulr_sumr -big_split /=; apply: eq_bigr=> i _.\nby rewrite !mxE.\nQed.\nCanonical mxtrace_additive := Additive mxtrace_is_scalar.\nCanonical mxtrace_linear := Linear mxtrace_is_scalar.\n\nLemma mxtrace0 : \\tr 0 = 0. Proof. exact: raddf0. Qed.\nLemma mxtraceD A B : \\tr (A + B) = \\tr A + \\tr B. Proof. exact: raddfD. Qed.\nLemma mxtraceZ a A : \\tr (a *: A) = a * \\tr A. Proof. exact: scalarZ. Qed.\n\nLemma mxtrace_diag D : \\tr (diag_mx D) = \\sum_j D 0 j.\nProof. by apply: eq_bigr => j _; rewrite mxE eqxx. Qed.\n\nLemma mxtrace_scalar a : \\tr a%:M = a *+ n.\nProof.\nrewrite -diag_const_mx mxtrace_diag.\nby rewrite (eq_bigr _ (fun j _ => mxE _ _ 0 j)) sumr_const card_ord.\nQed.\n\nLemma mxtrace1 : \\tr 1%:M = n%:R. Proof. exact: mxtrace_scalar. Qed.\n\nEnd Trace.\nLocal Notation \"'\\tr' A\" := (mxtrace A) : ring_scope.\n\nLemma trace_mx11 (A : 'M_1) : \\tr A = A 0 0.\nProof. by rewrite {1}[A]mx11_scalar mxtrace_scalar. Qed.\n\nLemma mxtrace_block n1 n2 (Aul : 'M_n1) Aur Adl (Adr : 'M_n2) :\n  \\tr (block_mx Aul Aur Adl Adr) = \\tr Aul + \\tr Adr.\nProof.\nrewrite /(\\tr _) big_split_ord /=.\nby congr (_ + _); apply: eq_bigr => i _; rewrite (block_mxEul, block_mxEdr).\nQed.\n\n(* The matrix ring structure requires a strutural condition (dimension of the *)\n(* form n.+1) to statisfy the nontriviality condition we have imposed.        *)\nSection MatrixRing.\n\nVariable n' : nat.\nLocal Notation n := n'.+1.\n\nLemma matrix_nonzero1 : 1%:M != 0 :> 'M_n.\nProof. by apply/eqP=> /matrixP/(_ 0 0)/eqP; rewrite !mxE oner_eq0. Qed.\n\nDefinition matrix_ringMixin :=\n  RingMixin (@mulmxA n n n n) (@mul1mx n n) (@mulmx1 n n)\n            (@mulmxDl n n n) (@mulmxDr n n n) matrix_nonzero1.\n\nCanonical matrix_ringType := Eval hnf in RingType 'M[R]_n matrix_ringMixin.\nCanonical matrix_lAlgType := Eval hnf in LalgType R 'M[R]_n (@scalemxAl n n n).\n\nLemma mulmxE : mulmx = *%R. Proof. by []. Qed.\nLemma idmxE : 1%:M = 1 :> 'M_n. Proof. by []. Qed.\n\nLemma scalar_mx_is_multiplicative : multiplicative (@scalar_mx n).\nProof. by split=> //; exact: scalar_mxM. Qed.\nCanonical scalar_mx_rmorphism := AddRMorphism scalar_mx_is_multiplicative.\n\nEnd MatrixRing.\n\nSection LiftPerm.\n\n(* Block expresssion of a lifted permutation matrix, for the Cormen LUP. *)\n\nVariable n : nat.\n\n(* These could be in zmodp, but that would introduce a dependency on perm. *)\n\nDefinition lift0_perm s : 'S_n.+1 := lift_perm 0 0 s.\n\nLemma lift0_perm0 s : lift0_perm s 0 = 0.\nProof. exact: lift_perm_id. Qed.\n\nLemma lift0_perm_lift s k' :\n  lift0_perm s (lift 0 k') = lift (0 : 'I_n.+1) (s k').\nProof. exact: lift_perm_lift. Qed.\n\nLemma lift0_permK s : cancel (lift0_perm s) (lift0_perm s^-1).\nProof. by move=> i; rewrite /lift0_perm -lift_permV permK. Qed.\n\nLemma lift0_perm_eq0 s i : (lift0_perm s i == 0) = (i == 0).\nProof. by rewrite (canF_eq (lift0_permK s)) lift0_perm0. Qed.\n\n(* Block expresssion of a lifted permutation matrix *)\n\nDefinition lift0_mx A : 'M_(1 + n) := block_mx 1 0 0 A.\n\nLemma lift0_mx_perm s : lift0_mx (perm_mx s) = perm_mx (lift0_perm s).\nProof.\napply/matrixP=> /= i j; rewrite !mxE split1 /=; case: unliftP => [i'|] -> /=.\n  rewrite lift0_perm_lift !mxE split1 /=.\n  by case: unliftP => [j'|] ->; rewrite ?(inj_eq (@lift_inj _ _)) /= !mxE.\nrewrite lift0_perm0 !mxE split1 /=.\nby case: unliftP => [j'|] ->; rewrite /= mxE.\nQed.\n\nLemma lift0_mx_is_perm s : is_perm_mx (lift0_mx (perm_mx s)).\nProof. by rewrite lift0_mx_perm perm_mx_is_perm. Qed.\n\nEnd LiftPerm.\n\n(* Determinants and adjugates are defined here, but most of their properties *)\n(* only hold for matrices over a commutative ring, so their theory is        *)\n(* deferred to that section.                                                 *)\n\n(* The determinant, in one line with the Leibniz Formula *)\nDefinition determinant n (A : 'M_n) : R :=\n  \\sum_(s : 'S_n) (-1) ^+ s * \\prod_i A i (s i).\n\n(* The cofactor of a matrix on the indexes i and j *)\nDefinition cofactor n A (i j : 'I_n) : R :=\n  (-1) ^+ (i + j) * determinant (row' i (col' j A)).\n\n(* The adjugate matrix : defined as the transpose of the matrix of cofactors *)\nFact adjugate_key : unit. Proof. by []. Qed.\nDefinition adjugate n (A : 'M_n) := \\matrix[adjugate_key]_(i, j) cofactor A j i.\n\nEnd MatrixAlgebra.\n\nImplicit Arguments delta_mx [R m n].\nImplicit Arguments scalar_mx [R n].\nImplicit Arguments perm_mx [R n].\nImplicit Arguments tperm_mx [R n].\nImplicit Arguments pid_mx [R m n].\nImplicit Arguments copid_mx [R n].\nImplicit Arguments lin_mulmxr [R m n p].\nPrenex Implicits delta_mx diag_mx scalar_mx is_scalar_mx perm_mx tperm_mx.\nPrenex Implicits pid_mx copid_mx mulmx lin_mulmxr.\nPrenex Implicits mxtrace determinant cofactor adjugate.\n\nImplicit Arguments is_scalar_mxP [R n A].\nImplicit Arguments mul_delta_mx [R m n p].\nPrenex Implicits mul_delta_mx.\n\nNotation \"a %:M\" := (scalar_mx a) : ring_scope.\nNotation \"A *m B\" := (mulmx A B) : ring_scope.\nNotation mulmxr := (mulmxr_head tt).\nNotation \"\\tr A\" := (mxtrace A) : ring_scope.\nNotation \"'\\det' A\" := (determinant A) : ring_scope.\nNotation \"'\\adj' A\" := (adjugate A) : ring_scope.\n\n(* Non-commutative transpose requires multiplication in the converse ring.   *)\nLemma trmx_mul_rev (R : ringType) m n p (A : 'M[R]_(m, n)) (B : 'M[R]_(n, p)) :\n  (A *m B)^T = (B : 'M[R^c]_(n, p))^T *m (A : 'M[R^c]_(m, n))^T.\nProof.\nby apply/matrixP=> k i; rewrite !mxE; apply: eq_bigr => j _; rewrite !mxE.\nQed.\n\nCanonical matrix_finRingType (R : finRingType) n' :=\n  Eval hnf in [finRingType of 'M[R]_n'.+1].\n\n(* Parametricity over the algebra structure. *)\nSection MapRingMatrix.\n\nVariables (aR rR : ringType) (f : {rmorphism aR -> rR}).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\n\nSection FixedSize.\n\nVariables m n p : nat.\nImplicit Type A : 'M[aR]_(m, n).\n\nLemma map_mxZ a A : (a *: A)^f = f a *: A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE rmorphM. Qed.\n\nLemma map_mxM A B : (A *m B)^f = A^f *m B^f :> 'M_(m, p).\nProof.\napply/matrixP=> i k; rewrite !mxE rmorph_sum //.\nby apply: eq_bigr => j; rewrite !mxE rmorphM.\nQed.\n\nLemma map_delta_mx i j : (delta_mx i j)^f = delta_mx i j :> 'M_(m, n).\nProof. by apply/matrixP=> i' j'; rewrite !mxE rmorph_nat. Qed.\n\nLemma map_diag_mx d : (diag_mx d)^f = diag_mx d^f :> 'M_n.\nProof. by apply/matrixP=> i j; rewrite !mxE rmorphMn. Qed.\n\nLemma map_scalar_mx a : a%:M^f = (f a)%:M :> 'M_n.\nProof. by apply/matrixP=> i j; rewrite !mxE rmorphMn. Qed.\n\nLemma map_mx1 : 1%:M^f = 1%:M :> 'M_n.\nProof. by rewrite map_scalar_mx rmorph1. Qed.\n\nLemma map_perm_mx (s : 'S_n) : (perm_mx s)^f = perm_mx s.\nProof. by apply/matrixP=> i j; rewrite !mxE rmorph_nat. Qed.\n\nLemma map_tperm_mx (i1 i2 : 'I_n) : (tperm_mx i1 i2)^f = tperm_mx i1 i2.\nProof. exact: map_perm_mx. Qed.\n\nLemma map_pid_mx r : (pid_mx r)^f = pid_mx r :> 'M_(m, n).\nProof. by apply/matrixP=> i j; rewrite !mxE rmorph_nat. Qed.\n\nLemma trace_map_mx (A : 'M_n) : \\tr A^f = f (\\tr A).\nProof. by rewrite rmorph_sum; apply: eq_bigr => i _; rewrite mxE. Qed.\n\nLemma det_map_mx n' (A : 'M_n') : \\det A^f = f (\\det A).\nProof.\nrewrite rmorph_sum //; apply: eq_bigr => s _.\nrewrite rmorphM rmorph_sign rmorph_prod; congr (_ * _).\nby apply: eq_bigr => i _; rewrite mxE.\nQed.\n\nLemma cofactor_map_mx (A : 'M_n) i j : cofactor A^f i j = f (cofactor A i j).\nProof. by rewrite rmorphM rmorph_sign -det_map_mx map_row' map_col'. Qed.\n\nLemma map_mx_adj (A : 'M_n) : (\\adj A)^f = \\adj A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE cofactor_map_mx. Qed.\n\nEnd FixedSize.\n\nLemma map_copid_mx n r : (copid_mx r)^f = copid_mx r :> 'M_n.\nProof. by rewrite map_mx_sub map_mx1 map_pid_mx. Qed.\n\nLemma map_mx_is_multiplicative n' (n := n'.+1) :\n  multiplicative ((map_mx f) n n).\nProof. by split; [exact: map_mxM | exact: map_mx1]. Qed.\n\nCanonical map_mx_rmorphism n' := AddRMorphism (map_mx_is_multiplicative n').\n\nLemma map_lin1_mx m n (g : 'rV_m -> 'rV_n) gf :\n  (forall v, (g v)^f = gf v^f) -> (lin1_mx g)^f = lin1_mx gf.\nProof.\nby move=> def_gf; apply/matrixP=> i j; rewrite !mxE -map_delta_mx -def_gf mxE.\nQed.\n\nLemma map_lin_mx m1 n1 m2 n2 (g : 'M_(m1, n1) -> 'M_(m2, n2)) gf : \n  (forall A, (g A)^f = gf A^f) -> (lin_mx g)^f = lin_mx gf.\nProof.\nmove=> def_gf; apply: map_lin1_mx => A /=.\nby rewrite map_mxvec def_gf map_vec_mx.\nQed.\n\nEnd MapRingMatrix.\n\nSection ComMatrix.\n(* Lemmas for matrices with coefficients in a commutative ring *)\nVariable R : comRingType.\n\nSection AssocLeft.\n\nVariables m n p : nat.\nImplicit Type A : 'M[R]_(m, n).\nImplicit Type B : 'M[R]_(n, p).\n\nLemma trmx_mul A B : (A *m B)^T = B^T *m A^T.\nProof.\nrewrite trmx_mul_rev; apply/matrixP=> k i; rewrite !mxE.\nby apply: eq_bigr => j _; rewrite mulrC.\nQed.\n\nLemma scalemxAr a A B : a *: (A *m B) = A *m (a *: B).\nProof. by apply: trmx_inj; rewrite trmx_mul !linearZ /= trmx_mul scalemxAl. Qed.\n\nLemma mulmx_is_scalable A : scalable (@mulmx _ m n p A).\nProof. by move=> a B; rewrite scalemxAr. Qed.\nCanonical mulmx_linear A := AddLinear (mulmx_is_scalable A).\n\nDefinition lin_mulmx A : 'M[R]_(n * p, m * p) := lin_mx (mulmx A).\n\nLemma lin_mulmx_is_linear : linear lin_mulmx.\nProof.\nmove=> a A B; apply/row_matrixP=> i; rewrite linearP /= !rowE !mul_rV_lin /=.\nby rewrite [_ *m _](linearP (mulmxr_linear _ _)) linearP.\nQed.\nCanonical lin_mulmx_additive := Additive lin_mulmx_is_linear.\nCanonical lin_mulmx_linear := Linear lin_mulmx_is_linear.\n\nEnd AssocLeft.\n\nSection LinMulRow.\n\nVariables m n : nat.\n\nDefinition lin_mul_row u : 'M[R]_(m * n, n) := lin1_mx (mulmx u \\o vec_mx).\n\nLemma lin_mul_row_is_linear : linear lin_mul_row.\nProof.\nmove=> a u v; apply/row_matrixP=> i; rewrite linearP /= !rowE !mul_rV_lin1 /=.\nby rewrite [_ *m _](linearP (mulmxr_linear _ _)).\nQed.\nCanonical lin_mul_row_additive := Additive lin_mul_row_is_linear.\nCanonical lin_mul_row_linear := Linear lin_mul_row_is_linear.\n\nLemma mul_vec_lin_row A u : mxvec A *m lin_mul_row u = u *m A.\nProof. by rewrite mul_rV_lin1 /= mxvecK. Qed.\n\nEnd LinMulRow.\n\nLemma mxvec_dotmul m n (A : 'M[R]_(m, n)) u v :\n  mxvec (u^T *m v) *m (mxvec A)^T = u *m A *m v^T.\nProof.\ntransitivity (\\sum_i \\sum_j (u 0 i * A i j *: row j v^T)).\n  apply/rowP=> i; rewrite {i}ord1 mxE (reindex _ (curry_mxvec_bij _ _)) /=.\n  rewrite pair_bigA summxE; apply: eq_bigr => [[i j]] /= _.\n  by rewrite !mxE !mxvecE mxE big_ord1 mxE mulrAC.\nrewrite mulmx_sum_row exchange_big; apply: eq_bigr => j _ /=.\nby rewrite mxE -scaler_suml.\nQed.\n\nSection MatrixAlgType.\n\nVariable n' : nat.\nLocal Notation n := n'.+1.\n\nCanonical matrix_algType :=\n  Eval hnf in AlgType R 'M[R]_n (fun k => scalemxAr k).\n\nEnd MatrixAlgType.\n\nLemma diag_mxC n (d e : 'rV[R]_n) :\n  diag_mx d *m diag_mx e = diag_mx e *m diag_mx d.\nProof.\nby rewrite !mulmx_diag; congr (diag_mx _); apply/rowP=> i; rewrite !mxE mulrC.\nQed.\n\nLemma diag_mx_comm n' (d e : 'rV[R]_n'.+1) : GRing.comm (diag_mx d) (diag_mx e).\nProof. exact: diag_mxC. Qed.\n\nLemma scalar_mxC m n a (A : 'M[R]_(m, n)) : A *m a%:M = a%:M *m A.\nProof.\nby apply: trmx_inj; rewrite trmx_mul tr_scalar_mx !mul_scalar_mx linearZ.\nQed.\n\nLemma scalar_mx_comm n' a (A : 'M[R]_n'.+1) : GRing.comm A a%:M.\nProof. exact: scalar_mxC. Qed.\n\nLemma mul_mx_scalar m n a (A : 'M[R]_(m, n)) : A *m a%:M = a *: A.\nProof. by rewrite scalar_mxC mul_scalar_mx. Qed.\n\nLemma mxtrace_mulC m n (A : 'M[R]_(m, n)) (B : 'M_(n, m)) :\n  \\tr (A *m B) = \\tr (B *m A).\nProof.\ntransitivity (\\sum_i \\sum_j A i j * B j i).\n  by apply: eq_bigr => i _; rewrite mxE.\nrewrite exchange_big; apply: eq_bigr => i _ /=; rewrite mxE.\napply: eq_bigr => j _; exact: mulrC.\nQed.\n\n(* The theory of determinants *)\n\nLemma determinant_multilinear n (A B C : 'M[R]_n) i0 b c :\n    row i0 A = b *: row i0 B + c *: row i0 C ->\n    row' i0 B = row' i0 A ->\n    row' i0 C = row' i0 A ->\n  \\det A = b * \\det B + c * \\det C.\nProof.\nrewrite -[_ + _](row_id 0); move/row_eq=> ABC.\nmove/row'_eq=> BA; move/row'_eq=> CA.\nrewrite !big_distrr -big_split; apply: eq_bigr => s _ /=.\nrewrite -!(mulrCA (_ ^+s)) -mulrDr; congr (_ * _).\nrewrite !(bigD1 i0 (_ : predT i0)) //= {}ABC !mxE mulrDl !mulrA.\nby congr (_ * _ + _ * _); apply: eq_bigr => i i0i; rewrite ?BA ?CA.\nQed.\n\nLemma determinant_alternate n (A : 'M[R]_n) i1 i2 :\n  i1 != i2 -> A i1 =1 A i2 -> \\det A = 0.\nProof.\nmove=> neq_i12 eqA12; pose t := tperm i1 i2.\nhave oddMt s: (t * s)%g = ~~ s :> bool by rewrite odd_permM odd_tperm neq_i12.\nrewrite [\\det A](bigID (@odd_perm _)) /=.\napply: canLR (subrK _) _; rewrite add0r -sumrN.\nrewrite (reindex_inj (mulgI t)); apply: eq_big => //= s.\nrewrite oddMt => /negPf->; rewrite mulN1r mul1r; congr (- _).\nrewrite (reindex_inj (@perm_inj _ t)); apply: eq_bigr => /= i _.\nby rewrite permM tpermK /t; case: tpermP => // ->; rewrite eqA12.\nQed.\n\nLemma det_tr n (A : 'M[R]_n) : \\det A^T = \\det A.\nProof.\nrewrite [\\det A^T](reindex_inj (@invg_inj _)) /=.\napply: eq_bigr => s _ /=; rewrite !odd_permV (reindex_inj (@perm_inj _ s)) /=.\nby congr (_ * _); apply: eq_bigr => i _; rewrite mxE permK.\nQed.\n\nLemma det_perm n (s : 'S_n) : \\det (perm_mx s) = (-1) ^+ s :> R.\nProof.\nrewrite [\\det _](bigD1 s) //= big1 => [|i _]; last by rewrite /= !mxE eqxx.\nrewrite mulr1 big1 ?addr0 => //= t Dst.\ncase: (pickP (fun i => s i != t i)) => [i ist | Est].\n  by rewrite (bigD1 i) // mulrCA /= !mxE (negbTE ist) mul0r.\nby case/eqP: Dst; apply/permP => i; move/eqP: (Est i).\nQed.\n\nLemma det1 n : \\det (1%:M : 'M[R]_n) = 1.\nProof. by rewrite -perm_mx1 det_perm odd_perm1. Qed.\n\nLemma det_mx00 (A : 'M[R]_0) : \\det A = 1.\nProof. by rewrite flatmx0 -(flatmx0 1%:M) det1. Qed.\n\nLemma detZ n a (A : 'M[R]_n) : \\det (a *: A) = a ^+ n * \\det A.\nProof.\nrewrite big_distrr /=; apply: eq_bigr => s _; rewrite mulrCA; congr (_ * _).\nrewrite -[n in a ^+ n]card_ord -prodr_const -big_split /=.\nby apply: eq_bigr=> i _; rewrite mxE.\nQed.\n\nLemma det0 n' : \\det (0 : 'M[R]_n'.+1) = 0.\nProof. by rewrite -(scale0r 0) detZ exprS !mul0r. Qed.\n\nLemma det_scalar n a : \\det (a%:M : 'M[R]_n) = a ^+ n.\nProof. by rewrite -{1}(mulr1 a) -scale_scalar_mx detZ det1 mulr1. Qed.\n\nLemma det_scalar1 a : \\det (a%:M : 'M[R]_1) = a.\nProof. exact: det_scalar. Qed.\n\nLemma det_mulmx n (A B : 'M[R]_n) : \\det (A *m B) = \\det A * \\det B.\nProof.\nrewrite big_distrl /=.\npose F := ('I_n ^ n)%type; pose AB s i j := A i j * B j (s i).\ntransitivity (\\sum_(f : F) \\sum_(s : 'S_n) (-1) ^+ s * \\prod_i AB s i (f i)).\n  rewrite exchange_big; apply: eq_bigr => /= s _; rewrite -big_distrr /=.\n  congr (_ * _); rewrite -(bigA_distr_bigA (AB s)) /=.\n  by apply: eq_bigr => x _; rewrite mxE.\nrewrite (bigID (fun f : F => injectiveb f)) /= addrC big1 ?add0r => [|f Uf].\n  rewrite (reindex (@pval _)) /=; last first.\n    pose in_Sn := insubd (1%g : 'S_n).\n    by exists in_Sn => /= f Uf; first apply: val_inj; exact: insubdK.\n  apply: eq_big => /= [s | s _]; rewrite ?(valP s) // big_distrr /=.\n  rewrite (reindex_inj (mulgI s)); apply: eq_bigr => t _ /=.\n  rewrite big_split /= mulrA mulrCA mulrA mulrCA mulrA.\n  rewrite -signr_addb odd_permM !pvalE; congr (_ * _); symmetry.\n  by rewrite (reindex_inj (@perm_inj _ s)); apply: eq_bigr => i; rewrite permM.\ntransitivity (\\det (\\matrix_(i, j) B (f i) j) * \\prod_i A i (f i)).\n  rewrite mulrC big_distrr /=; apply: eq_bigr => s _.\n  rewrite mulrCA big_split //=; congr (_ * (_ * _)).\n  by apply: eq_bigr => x _; rewrite mxE.\ncase/injectivePn: Uf => i1 [i2 Di12 Ef12].\nby rewrite (determinant_alternate Di12) ?simp //= => j; rewrite !mxE Ef12.\nQed.\n\nLemma detM n' (A B : 'M[R]_n'.+1) : \\det (A * B) = \\det A * \\det B.\nProof. exact: det_mulmx. Qed.\n\nLemma det_diag n (d : 'rV[R]_n) : \\det (diag_mx d) = \\prod_i d 0 i.\nProof.\nrewrite /(\\det _) (bigD1 1%g) //= addrC big1 => [|p p1].\n  by rewrite add0r odd_perm1 mul1r; apply: eq_bigr => i; rewrite perm1 mxE eqxx.\nhave{p1}: ~~ perm_on set0 p.\n  apply: contra p1; move/subsetP=> p1; apply/eqP; apply/permP=> i.\n  by rewrite perm1; apply/eqP; apply/idPn; move/p1; rewrite inE.\ncase/subsetPn=> i; rewrite !inE eq_sym; move/negbTE=> p_i _.\nby rewrite (bigD1 i) //= mulrCA mxE p_i mul0r.\nQed.\n\n(* Laplace expansion lemma *)\nLemma expand_cofactor n (A : 'M[R]_n) i j :\n  cofactor A i j =\n    \\sum_(s : 'S_n | s i == j) (-1) ^+ s * \\prod_(k | i != k) A k (s k).\nProof.\ncase: n A i j => [|n] A i0 j0; first by case: i0.\nrewrite (reindex (lift_perm i0 j0)); last first.\n  pose ulsf i (s : 'S_n.+1) k := odflt k (unlift (s i) (s (lift i k))).\n  have ulsfK i (s : 'S_n.+1) k: lift (s i) (ulsf i s k) = s (lift i k).\n    rewrite /ulsf; have:= neq_lift i k.\n    by rewrite -(inj_eq (@perm_inj _ s)) => /unlift_some[] ? ? ->.\n  have inj_ulsf: injective (ulsf i0 _).\n    move=> s; apply: can_inj (ulsf (s i0) s^-1%g) _ => k'.\n    by rewrite {1}/ulsf ulsfK !permK liftK.\n  exists (fun s => perm (inj_ulsf s)) => [s _ | s].\n    by apply/permP=> k'; rewrite permE /ulsf lift_perm_lift lift_perm_id liftK.\n  move/(s _ =P _) => si0; apply/permP=> k.\n  case: (unliftP i0 k) => [k'|] ->; rewrite ?lift_perm_id //.\n  by rewrite lift_perm_lift -si0 permE ulsfK.\nrewrite /cofactor big_distrr /=.\napply: eq_big => [s | s _]; first by rewrite lift_perm_id eqxx.\nrewrite -signr_odd mulrA -signr_addb odd_add -odd_lift_perm; congr (_ * _).\ncase: (pickP 'I_n) => [k0 _ | n0]; last first.\n  by rewrite !big1 // => [j /unlift_some[i] | i _]; have:= n0 i.\nrewrite (reindex (lift i0)).\n  by apply: eq_big => [k | k _] /=; rewrite ?neq_lift // !mxE lift_perm_lift.\nexists (fun k => odflt k0 (unlift i0 k)) => k; first by rewrite liftK.\nby case/unlift_some=> k' -> ->.\nQed.\n\nLemma expand_det_row n (A : 'M[R]_n) i0 :\n  \\det A = \\sum_j A i0 j * cofactor A i0 j.\nProof.\nrewrite /(\\det A) (partition_big (fun s : 'S_n => s i0) predT) //=.\napply: eq_bigr => j0 _; rewrite expand_cofactor big_distrr /=.\napply: eq_bigr => s /eqP Dsi0.\nrewrite mulrCA (bigID (pred1 i0)) /= big_pred1_eq Dsi0; congr (_ * (_ * _)).\nby apply: eq_bigl => i; rewrite eq_sym.\nQed.\n\nLemma cofactor_tr n (A : 'M[R]_n) i j : cofactor A^T i j = cofactor A j i.\nProof.\nrewrite /cofactor addnC; congr (_ * _).\nrewrite -tr_row' -tr_col' det_tr; congr (\\det _).\nby apply/matrixP=> ? ?; rewrite !mxE.\nQed.\n\nLemma cofactorZ n a (A : 'M[R]_n) i j : \n  cofactor (a *: A) i j = a ^+ n.-1 * cofactor A i j.\nProof. by rewrite {1}/cofactor !linearZ detZ mulrCA mulrA. Qed.\n\nLemma expand_det_col n (A : 'M[R]_n) j0 :\n  \\det A = \\sum_i (A i j0 * cofactor A i j0).\nProof.\nrewrite -det_tr (expand_det_row _ j0).\nby apply: eq_bigr => i _; rewrite cofactor_tr mxE.\nQed.\n\nLemma trmx_adj n (A : 'M[R]_n) : (\\adj A)^T = \\adj A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE cofactor_tr. Qed.\n\nLemma adjZ n a (A : 'M[R]_n) : \\adj (a *: A) = a^+n.-1 *: \\adj A.\nProof. by apply/matrixP=> i j; rewrite !mxE cofactorZ. Qed.\n\n(* Cramer Rule : adjugate on the left *)\nLemma mul_mx_adj n (A : 'M[R]_n) : A *m \\adj A = (\\det A)%:M.\nProof.\napply/matrixP=> i1 i2; rewrite !mxE; case Di: (i1 == i2).\n  rewrite (eqP Di) (expand_det_row _ i2) //=.\n  by apply: eq_bigr => j _; congr (_ * _); rewrite mxE.\npose B := \\matrix_(i, j) (if i == i2 then A i1 j else A i j).\nhave EBi12: B i1 =1 B i2 by move=> j; rewrite /= !mxE Di eq_refl.\nrewrite -[_ *+ _](determinant_alternate (negbT Di) EBi12) (expand_det_row _ i2).\napply: eq_bigr => j _; rewrite !mxE eq_refl; congr (_ * (_ * _)).\napply: eq_bigr => s _; congr (_ * _); apply: eq_bigr => i _.\nby rewrite !mxE eq_sym -if_neg neq_lift.\nQed.\n\n(* Cramer rule : adjugate on the right *)\nLemma mul_adj_mx n (A : 'M[R]_n) : \\adj A *m A = (\\det A)%:M.\nProof.\nby apply: trmx_inj; rewrite trmx_mul trmx_adj mul_mx_adj det_tr tr_scalar_mx.\nQed.\n\nLemma adj1 n : \\adj (1%:M) = 1%:M :> 'M[R]_n.\nProof. by rewrite -{2}(det1 n) -mul_adj_mx mulmx1. Qed.\n\n(* Left inverses are right inverses. *)\nLemma mulmx1C n (A B : 'M[R]_n) : A *m B = 1%:M -> B *m A = 1%:M.\nProof.\nmove=> AB1; pose A' := \\det B *: \\adj A.\nsuffices kA: A' *m A = 1%:M by rewrite -[B]mul1mx -kA -(mulmxA A') AB1 mulmx1.\nby rewrite -scalemxAl mul_adj_mx scale_scalar_mx mulrC -det_mulmx AB1 det1.\nQed.\n\n(* Only tall matrices have inverses. *)\nLemma mulmx1_min m n (A : 'M[R]_(m, n)) B : A *m B = 1%:M -> m <= n.\nProof.\nmove=> AB1; rewrite leqNgt; apply/negP=> /subnKC; rewrite addSnnS.\nmove: (_ - _)%N => m' def_m; move: AB1; rewrite -{m}def_m in A B *.\nrewrite -(vsubmxK A) -(hsubmxK B) mul_col_row scalar_mx_block.\ncase/eq_block_mx=> /mulmx1C BlAu1 AuBr0 _ => /eqP/idPn[].\nby rewrite -[_ B]mul1mx -BlAu1 -mulmxA AuBr0 !mulmx0 eq_sym oner_neq0.\nQed.\n\nLemma det_ublock n1 n2 Aul (Aur : 'M[R]_(n1, n2)) Adr :\n  \\det (block_mx Aul Aur 0 Adr) = \\det Aul * \\det Adr.\nProof.\nelim: n1 => [|n1 IHn1] in Aul Aur *.\n  have ->: Aul = 1%:M by apply/matrixP=> i [].\n  rewrite det1 mul1r; congr (\\det _); apply/matrixP=> i j.\n  by do 2![rewrite !mxE; case: splitP => [[]|k] //=; move/val_inj=> <- {k}].\nrewrite (expand_det_col _ (lshift n2 0)) big_split_ord /=.\nrewrite addrC big1 1?simp => [|i _]; last by rewrite block_mxEdl mxE simp.\nrewrite (expand_det_col _ 0) big_distrl /=; apply eq_bigr=> i _.\nrewrite block_mxEul -!mulrA; do 2!congr (_ * _).\nby rewrite col'_col_mx !col'Kl raddf0 row'Ku row'_row_mx IHn1.\nQed.\n\nLemma det_lblock n1 n2 Aul (Adl : 'M[R]_(n2, n1)) Adr :\n  \\det (block_mx Aul 0 Adl Adr) = \\det Aul * \\det Adr.\nProof. by rewrite -det_tr tr_block_mx trmx0 det_ublock !det_tr. Qed.\n\nEnd ComMatrix.\n\nImplicit Arguments lin_mul_row [R m n].\nImplicit Arguments lin_mulmx [R m n p].\nPrenex Implicits lin_mul_row lin_mulmx.\n\n(*****************************************************************************)\n(********************** Matrix unit ring and inverse matrices ****************)\n(*****************************************************************************)\n\nSection MatrixInv.\n\nVariables R : comUnitRingType.\n\nSection Defs.\n\nVariable n : nat.\nImplicit Type A : 'M[R]_n.\n\nDefinition unitmx : pred 'M[R]_n := fun A => \\det A \\is a GRing.unit.\nDefinition invmx A := if A \\in unitmx then (\\det A)^-1 *: \\adj A else A.\n\nLemma unitmxE A : (A \\in unitmx) = (\\det A \\is a GRing.unit).\nProof. by []. Qed.\n\nLemma unitmx1 : 1%:M \\in unitmx. Proof. by rewrite unitmxE det1 unitr1. Qed.\n\nLemma unitmx_perm s : perm_mx s \\in unitmx.\nProof. by rewrite unitmxE det_perm unitrX ?unitrN ?unitr1. Qed.\n\nLemma unitmx_tr A : (A^T \\in unitmx) = (A \\in unitmx).\nProof. by rewrite unitmxE det_tr. Qed.\n\nLemma unitmxZ a A : a \\is a GRing.unit -> (a *: A \\in unitmx) = (A \\in unitmx).\nProof. by move=> Ua; rewrite !unitmxE detZ unitrM unitrX. Qed.\n\nLemma invmx1 : invmx 1%:M = 1%:M.\nProof. by rewrite /invmx det1 invr1 scale1r adj1 if_same. Qed.\n\nLemma invmxZ a A : a *: A \\in unitmx -> invmx (a *: A) = a^-1 *: invmx A.\nProof.\nrewrite /invmx !unitmxE detZ unitrM => /andP[Ua U_A].\nrewrite Ua U_A adjZ !scalerA invrM {U_A}//=.\ncase: (posnP n) A => [-> | n_gt0] A; first by rewrite flatmx0 [_ *: _]flatmx0.\nrewrite unitrX_pos // in Ua; rewrite -[_ * _](mulrK Ua) mulrC -!mulrA.\nby rewrite -exprSr prednK // !mulrA divrK ?unitrX.\nQed.\n\nLemma invmx_scalar a : invmx (a%:M) = a^-1%:M.\nProof.\ncase Ua: (a%:M \\in unitmx).\n  by rewrite -scalemx1 in Ua *; rewrite invmxZ // invmx1 scalemx1.\nrewrite /invmx Ua; have [->|n_gt0] := posnP n; first by rewrite ![_%:M]flatmx0.\nby rewrite unitmxE det_scalar unitrX_pos // in Ua; rewrite invr_out ?Ua.\nQed.\n\nLemma mulVmx : {in unitmx, left_inverse 1%:M invmx mulmx}.\nProof.\nby move=> A nsA; rewrite /invmx nsA -scalemxAl mul_adj_mx scale_scalar_mx mulVr.\nQed.\n\nLemma mulmxV : {in unitmx, right_inverse 1%:M invmx mulmx}.\nProof.\nby move=> A nsA; rewrite /invmx nsA -scalemxAr mul_mx_adj scale_scalar_mx mulVr.\nQed.\n\nLemma mulKmx m : {in unitmx, @left_loop _ 'M_(n, m) invmx mulmx}.\nProof. by move=> A uA /= B; rewrite mulmxA mulVmx ?mul1mx. Qed.\n\nLemma mulKVmx m : {in unitmx, @rev_left_loop _ 'M_(n, m) invmx mulmx}.\nProof. by move=> A uA /= B; rewrite mulmxA mulmxV ?mul1mx. Qed.\n\nLemma mulmxK m : {in unitmx, @right_loop 'M_(m, n) _ invmx mulmx}.\nProof. by move=> A uA /= B; rewrite -mulmxA mulmxV ?mulmx1. Qed.\n\nLemma mulmxKV m : {in unitmx, @rev_right_loop 'M_(m, n) _ invmx mulmx}.\nProof. by move=> A uA /= B; rewrite -mulmxA mulVmx ?mulmx1. Qed.\n\nLemma det_inv A : \\det (invmx A) = (\\det A)^-1.\nProof.\ncase uA: (A \\in unitmx); last by rewrite /invmx uA invr_out ?negbT.\nby apply: (mulrI uA); rewrite -det_mulmx mulmxV ?divrr ?det1.\nQed.\n\nLemma unitmx_inv A : (invmx A \\in unitmx) = (A \\in unitmx).\nProof. by rewrite !unitmxE det_inv unitrV. Qed.\n\nLemma unitmx_mul A B : (A *m B \\in unitmx) = (A \\in unitmx) && (B \\in unitmx).\nProof. by rewrite -unitrM -det_mulmx. Qed.\n\nLemma trmx_inv (A : 'M_n) : (invmx A)^T = invmx (A^T).\nProof. by rewrite (fun_if trmx) linearZ /= trmx_adj -unitmx_tr -det_tr. Qed.\n\nLemma invmxK : involutive invmx.\nProof.\nmove=> A; case uA : (A \\in unitmx); last by rewrite /invmx !uA.\nby apply: (can_inj (mulKVmx uA)); rewrite mulVmx // mulmxV ?unitmx_inv.\nQed.\n\nLemma mulmx1_unit A B : A *m B = 1%:M -> A \\in unitmx /\\ B \\in unitmx.\nProof. by move=> AB1; apply/andP; rewrite -unitmx_mul AB1 unitmx1. Qed.\n\nLemma intro_unitmx A B : B *m A = 1%:M /\\ A *m B = 1%:M -> unitmx A.\nProof. by case=> _ /mulmx1_unit[]. Qed.\n\nLemma invmx_out : {in [predC unitmx], invmx =1 id}.\nProof. by move=> A; rewrite inE /= /invmx -if_neg => ->. Qed.\n\nEnd Defs.\n\nVariable n' : nat.\nLocal Notation n := n'.+1.\n\nDefinition matrix_unitRingMixin :=\n  UnitRingMixin (@mulVmx n) (@mulmxV n) (@intro_unitmx n) (@invmx_out n).\nCanonical matrix_unitRing :=\n  Eval hnf in UnitRingType 'M[R]_n matrix_unitRingMixin.\nCanonical matrix_unitAlg := Eval hnf in [unitAlgType R of 'M[R]_n].\n\n(* Lemmas requiring that the coefficients are in a unit ring *)\n\nLemma detV (A : 'M_n) : \\det A^-1 = (\\det A)^-1.\nProof. exact: det_inv. Qed.\n\nLemma unitr_trmx (A : 'M_n) : (A^T  \\is a GRing.unit) = (A \\is a GRing.unit).\nProof. exact: unitmx_tr. Qed.\n\nLemma trmxV (A : 'M_n) : A^-1^T = (A^T)^-1.\nProof. exact: trmx_inv. Qed.\n\nLemma perm_mxV (s : 'S_n) : perm_mx s^-1 = (perm_mx s)^-1.\nProof.\nrewrite -[_^-1]mul1r; apply: (canRL (mulmxK (unitmx_perm s))).\nby rewrite -perm_mxM mulVg perm_mx1.\nQed.\n\nLemma is_perm_mxV (A : 'M_n) : is_perm_mx A^-1 = is_perm_mx A.\nProof.\napply/is_perm_mxP/is_perm_mxP=> [] [s defA]; exists s^-1%g.\n  by rewrite -(invrK A) defA perm_mxV.\nby rewrite defA perm_mxV.\nQed.\n\nEnd MatrixInv.\n\nPrenex Implicits unitmx invmx.\n\n(* Finite inversible matrices and the general linear group. *)\nSection FinUnitMatrix.\n\nVariables (n : nat) (R : finComUnitRingType).\n\nCanonical matrix_finUnitRingType n' :=\n  Eval hnf in [finUnitRingType of 'M[R]_n'.+1].\n\nDefinition GLtype of phant R := {unit 'M[R]_n.-1.+1}.\n\nCoercion GLval ph (u : GLtype ph) : 'M[R]_n.-1.+1 :=\n  let: FinRing.Unit A _ := u in A.\n\nEnd FinUnitMatrix.\n\nBind Scope group_scope with GLtype.\nArguments Scope GLval [nat_scope _ _ group_scope].\nPrenex Implicits GLval.\n\nNotation \"{ ''GL_' n [ R ] }\" := (GLtype n (Phant R))\n  (at level 0, n at level 2, format \"{ ''GL_' n [ R ] }\") : type_scope.\nNotation \"{ ''GL_' n ( p ) }\" := {'GL_n['F_p]}\n  (at level 0, n at level 2, p at level 10,\n    format \"{ ''GL_' n ( p ) }\") : type_scope.\n\nSection GL_unit.\n\nVariables (n : nat) (R : finComUnitRingType).\n\nCanonical GL_subType := [subType of {'GL_n[R]} for GLval].\nDefinition GL_eqMixin := Eval hnf in [eqMixin of {'GL_n[R]} by <:].\nCanonical GL_eqType := Eval hnf in EqType {'GL_n[R]} GL_eqMixin.\nCanonical GL_choiceType := Eval hnf in [choiceType of {'GL_n[R]}].\nCanonical GL_countType := Eval hnf in [countType of {'GL_n[R]}].\nCanonical GL_subCountType := Eval hnf in [subCountType of {'GL_n[R]}].\nCanonical GL_finType := Eval hnf in [finType of {'GL_n[R]}].\nCanonical GL_subFinType := Eval hnf in [subFinType of {'GL_n[R]}].\nCanonical GL_baseFinGroupType := Eval hnf in [baseFinGroupType of {'GL_n[R]}].\nCanonical GL_finGroupType := Eval hnf in [finGroupType of {'GL_n[R]}].\nDefinition GLgroup of phant R := [set: {'GL_n[R]}].\nCanonical GLgroup_group ph := Eval hnf in [group of GLgroup ph].\n\nImplicit Types u v : {'GL_n[R]}.\n\nLemma GL_1E : GLval 1 = 1. Proof. by []. Qed.\nLemma GL_VE u : GLval u^-1 = (GLval u)^-1. Proof. by []. Qed.\nLemma GL_VxE u : GLval u^-1 = invmx u. Proof. by []. Qed.\nLemma GL_ME u v : GLval (u * v) = GLval u * GLval v. Proof. by []. Qed.\nLemma GL_MxE u v : GLval (u * v) = u *m v. Proof. by []. Qed.\nLemma GL_unit u : GLval u \\is a GRing.unit. Proof. exact: valP. Qed.\nLemma GL_unitmx u : val u \\in unitmx. Proof. exact: GL_unit. Qed.\n\nLemma GL_det u : \\det u != 0.\nProof.\nby apply: contraL (GL_unitmx u); rewrite unitmxE => /eqP->; rewrite unitr0.\nQed.\n\nEnd GL_unit.\n\nNotation \"''GL_' n [ R ]\" := (GLgroup n (Phant R))\n  (at level 8, n at level 2, format \"''GL_' n [ R ]\") : group_scope.\nNotation \"''GL_' n ( p )\" := 'GL_n['F_p]\n  (at level 8, n at level 2, p at level 10,\n   format \"''GL_' n ( p )\") : group_scope.\nNotation \"''GL_' n [ R ]\" := (GLgroup_group n (Phant R)) : Group_scope.\nNotation \"''GL_' n ( p )\" := (GLgroup_group n (Phant 'F_p)) : Group_scope.\n\n(*****************************************************************************)\n(********************** Matrices over a domain *******************************)\n(*****************************************************************************)\n\nSection MatrixDomain.\n\nVariable R : idomainType.\n\nLemma scalemx_eq0 m n a (A : 'M[R]_(m, n)) :\n  (a *: A == 0) = (a == 0) || (A == 0).\nProof.\ncase nz_a: (a == 0) / eqP => [-> | _]; first by rewrite scale0r eqxx.\napply/eqP/eqP=> [aA0 | ->]; last exact: scaler0.\napply/matrixP=> i j; apply/eqP; move/matrixP/(_ i j)/eqP: aA0.\nby rewrite !mxE mulf_eq0 nz_a.\nQed.\n\nLemma scalemx_inj m n a :\n  a != 0 -> injective ( *:%R a : 'M[R]_(m, n) -> 'M[R]_(m, n)).\nProof.\nmove=> nz_a A B eq_aAB; apply: contraNeq nz_a.\nrewrite -[A == B]subr_eq0 -[a == 0]orbF => /negPf<-.\nby rewrite -scalemx_eq0 linearB subr_eq0 /= eq_aAB.\nQed.\n\nLemma det0P n (A : 'M[R]_n) :\n  reflect (exists2 v : 'rV[R]_n, v != 0 & v *m A = 0) (\\det A == 0).\nProof.\napply: (iffP eqP) => [detA0 | [v n0v vA0]]; last first.\n  apply: contraNeq n0v => nz_detA; rewrite -(inj_eq (scalemx_inj nz_detA)).\n  by rewrite scaler0 -mul_mx_scalar -mul_mx_adj mulmxA vA0 mul0mx.\nelim: n => [|n IHn] in A detA0 *.\n  by case/idP: (oner_eq0 R); rewrite -detA0 [A]thinmx0 -(thinmx0 1%:M) det1.\nhave [{detA0}A'0 | nzA'] := eqVneq (row 0 (\\adj A)) 0; last first.\n  exists (row 0 (\\adj A)) => //; rewrite rowE -mulmxA mul_adj_mx detA0.\n  by rewrite mul_mx_scalar scale0r.\npose A' := col' 0 A; pose vA := col 0 A.\nhave defA: A = row_mx vA A'.\n  apply/matrixP=> i j; rewrite !mxE.\n  case: splitP => j' def_j; rewrite mxE; congr (A i _); apply: val_inj => //=.\n  by rewrite def_j [j']ord1.\nhave{IHn} w_ j : exists w : 'rV_n.+1, [/\\ w != 0, w 0 j = 0 & w *m A' = 0].\n  have [|wj nzwj wjA'0] := IHn (row' j A').\n    by apply/eqP; move/rowP/(_ j)/eqP: A'0; rewrite !mxE mulf_eq0 signr_eq0.\n  exists (\\row_k oapp (wj 0) 0 (unlift j k)).\n  rewrite !mxE unlift_none -wjA'0; split=> //.\n    apply: contraNneq nzwj => w0; apply/eqP/rowP=> k'.\n    by move/rowP/(_ (lift j k')): w0; rewrite !mxE liftK.\n  apply/rowP=> k; rewrite !mxE (bigD1 j) //= mxE unlift_none mul0r add0r.\n  rewrite (reindex_onto (lift j) (odflt k \\o unlift j)) /= => [|k'].\n    by apply: eq_big => k'; rewrite ?mxE liftK eq_sym neq_lift eqxx.\n  by rewrite eq_sym; case/unlift_some=> ? ? ->.\nhave [w0 [nz_w0 w00_0 w0A']] := w_ 0; pose a0 := (w0 *m vA) 0 0.\nhave [j {nz_w0}/= nz_w0j | w00] := pickP [pred j | w0 0 j != 0]; last first.\n  by case/eqP: nz_w0; apply/rowP=> j; rewrite mxE; move/eqP: (w00 j).\nhave{w_} [wj [nz_wj wj0_0 wjA']] := w_ j; pose aj := (wj *m vA) 0 0.\nhave [aj0 | nz_aj] := eqVneq aj 0.\n  exists wj => //; rewrite defA (@mul_mx_row _ _ _ 1) [_ *m _]mx11_scalar -/aj.\n  by rewrite aj0 raddf0 wjA' row_mx0.\nexists (aj *: w0 - a0 *: wj).\n  apply: contraNneq nz_aj; move/rowP/(_ j)/eqP; rewrite !mxE wj0_0 mulr0 subr0.\n  by rewrite mulf_eq0 (negPf nz_w0j) orbF.\nrewrite defA (@mul_mx_row _ _ _ 1) !mulmxBl -!scalemxAl w0A' wjA' !linear0.\nby rewrite -mul_mx_scalar -mul_scalar_mx -!mx11_scalar subrr addr0 row_mx0.\nQed.\n\nEnd MatrixDomain.\n\nImplicit Arguments det0P [R n A].\n\n(* Parametricity at the field level (mx_is_scalar, unit and inverse are only *)\n(* mapped at this level).                                                    *)\nSection MapFieldMatrix.\n\nVariables (aF : fieldType) (rF : comUnitRingType) (f : {rmorphism aF -> rF}).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\n\nLemma map_mx_inj m n : injective ((map_mx f) m n).\nProof.\nmove=> A B eq_AB; apply/matrixP=> i j.\nby move/matrixP/(_ i j): eq_AB; rewrite !mxE; exact: fmorph_inj.\nQed.\n\nLemma map_mx_is_scalar n (A : 'M_n) : is_scalar_mx A^f = is_scalar_mx A.\nProof.\nrewrite /is_scalar_mx; case: (insub _) => // i.\nby rewrite mxE -map_scalar_mx inj_eq //; exact: map_mx_inj.\nQed.\n\nLemma map_unitmx n (A : 'M_n) : (A^f \\in unitmx) = (A \\in unitmx).\nProof. by rewrite unitmxE det_map_mx // fmorph_unit // -unitfE. Qed.\n\nLemma map_mx_unit n' (A : 'M_n'.+1) :\n  (A^f \\is a GRing.unit) = (A \\is a GRing.unit).\nProof. exact: map_unitmx. Qed.\n\nLemma map_invmx n (A : 'M_n) : (invmx A)^f = invmx A^f.\nProof.\nrewrite /invmx map_unitmx (fun_if ((map_mx f) n n)).\nby rewrite map_mxZ map_mx_adj det_map_mx fmorphV. \nQed.\n\nLemma map_mx_inv n' (A : 'M_n'.+1) : A^-1^f = A^f^-1.\nProof. exact: map_invmx. Qed.\n  \nLemma map_mx_eq0 m n (A : 'M_(m, n)) : (A^f == 0) = (A == 0).\nProof. by rewrite -(inj_eq (@map_mx_inj m n)) raddf0. Qed.\n\nEnd MapFieldMatrix.\n\n(*****************************************************************************)\n(****************************** LUP decomposion ******************************)\n(*****************************************************************************)\n\nSection CormenLUP.\n\nVariable F : fieldType.\n\n(* Decomposition of the matrix A to P A = L U with *)\n(*   - P a permutation matrix                      *)\n(*   - L a unipotent lower triangular matrix       *)\n(*   - U an upper triangular matrix                *)\n\nFixpoint cormen_lup {n} :=\n  match n return let M := 'M[F]_n.+1 in M -> M * M * M with\n  | 0 => fun A => (1, 1, A)\n  | _.+1 => fun A =>\n    let k := odflt 0 [pick k | A k 0 != 0] in\n    let A1 : 'M_(1 + _) := xrow 0 k A in\n    let P1 : 'M_(1 + _) := tperm_mx 0 k in\n    let Schur := ((A k 0)^-1 *: dlsubmx A1) *m ursubmx A1 in\n    let: (P2, L2, U2) := cormen_lup (drsubmx A1 - Schur) in\n    let P := block_mx 1 0 0 P2 *m P1 in\n    let L := block_mx 1 0 ((A k 0)^-1 *: (P2 *m dlsubmx A1)) L2 in\n    let U := block_mx (ulsubmx A1) (ursubmx A1) 0 U2 in\n    (P, L, U)\n  end.\n\nLemma cormen_lup_perm n (A : 'M_n.+1) : is_perm_mx (cormen_lup A).1.1.\nProof.\nelim: n => [|n IHn] /= in A *; first exact: is_perm_mx1.\nset A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/=.\nrewrite (is_perm_mxMr _ (perm_mx_is_perm _ _)).\ncase/is_perm_mxP => s ->; exact: lift0_mx_is_perm.\nQed.\n\nLemma cormen_lup_correct n (A : 'M_n.+1) :\n  let: (P, L, U) := cormen_lup A in P * A = L * U.\nProof.\nelim: n => [|n IHn] /= in A *; first by rewrite !mul1r.\nset k := odflt _ _; set A1 : 'M_(1 + _) := xrow _ _ _.\nset A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P' L' U']] /= IHn.\nrewrite -mulrA -!mulmxE -xrowE -/A1 /= -[n.+2]/(1 + n.+1)%N -{1}(submxK A1).\nrewrite !mulmx_block !mul0mx !mulmx0 !add0r !addr0 !mul1mx -{L' U'}[L' *m _]IHn.\nrewrite -scalemxAl !scalemxAr -!mulmxA addrC -mulrDr {A'}subrK.\ncongr (block_mx _ _ (_ *m _) _).\nrewrite [_ *: _]mx11_scalar !mxE lshift0 tpermL {}/A1 {}/k.\ncase: pickP => /= [k nzAk0 | no_k]; first by rewrite mulVf ?mulmx1.\nrewrite (_ : dlsubmx _ = 0) ?mul0mx //; apply/colP=> i.\nby rewrite !mxE lshift0 (elimNf eqP (no_k _)).\nQed.\n\nLemma cormen_lup_detL n (A : 'M_n.+1) : \\det (cormen_lup A).1.2 = 1.\nProof.\nelim: n => [|n IHn] /= in A *; first by rewrite det1.\nset A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/= detL.\nby rewrite (@det_lblock _ 1) det1 mul1r.\nQed.\n\nLemma cormen_lup_lower n A (i j : 'I_n.+1) :\n  i <= j -> (cormen_lup A).1.2 i j = (i == j)%:R.\nProof.\nelim: n => [|n IHn] /= in A i j *; first by rewrite [i]ord1 [j]ord1 mxE.\nset A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/= Ll.\nrewrite !mxE split1; case: unliftP => [i'|] -> /=; rewrite !mxE split1.\n  by case: unliftP => [j'|] -> //; exact: Ll.\nby case: unliftP => [j'|] ->; rewrite /= mxE.\nQed.\n\nLemma cormen_lup_upper n A (i j : 'I_n.+1) :\n  j < i -> (cormen_lup A).2 i j = 0 :> F.\nProof.\nelim: n => [|n IHn] /= in A i j *; first by rewrite [i]ord1.\nset A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/= Uu.\nrewrite !mxE split1; case: unliftP => [i'|] -> //=; rewrite !mxE split1.\nby case: unliftP => [j'|] ->; [exact: Uu | rewrite /= mxE].\nQed.\n\nEnd CormenLUP.\n", "meta": {"author": "beta-ziliani", "repo": "ssreflect-1.4", "sha": "2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571", "save_path": "github-repos/coq/beta-ziliani-ssreflect-1.4", "path": "github-repos/coq/beta-ziliani-ssreflect-1.4/ssreflect-1.4-2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571/theories/matrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6771784351456822}}
{"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 Relations Wellfounded.\n\nRequire Import tacs acc_utils rel_utils list_utils finite good_base.\n\nSet Implicit Arguments.\n\nSection trees.\n\n  Variable (X : Type).\n\n  (* we do not want the too weak Coq generated induction principles *)\n\n  Unset Elimination Schemes.\n\n  Inductive tree : Type := in_tree : X -> list tree -> tree.\n\n  Set Elimination Schemes.\n\n  Definition tree_root t := match t with in_tree x _ => x end.\n  Definition tree_sons t := match t with in_tree _ l => l end.\n\n  Fact tree_root_sons_eq t : t = in_tree (tree_root t) (tree_sons t).\n  Proof. destruct t; auto. Qed.\n  \n  (* the immediate subtree relation *)\n  \n  Definition imsub_tree s t := match t with in_tree _ ll => In s ll end.\n  \n  Infix \"<ist\" := imsub_tree (at level 70).\n  \n  Fact imsub_tree_fix s t : s <ist t <-> exists x ll, In s ll /\\ t = in_tree x ll.\n  Proof.\n    split.\n    destruct t as [ x ll ]; exists x, ll; auto.\n    intros (x & ll & H1 & ?); subst; auto.\n  Qed.\n  \n  (* The immediate subtree relation is well founded *)\n  \n  Lemma imsub_tree_wf : well_founded imsub_tree.\n  Proof.\n    refine (fix loop t :=\n      match t with\n        | in_tree x ll => Acc_intro _ _\n      end); simpl; clear x t.\n    induction ll as [ | x ll IH ].\n    intros _ [].\n    intros ? [ [] | ].\n    apply loop.\n    apply IH; auto.\n  Qed.\n\n  (* let us define our own induction principles *)\n\n  Section tree_rect.\n\n    Variable P : tree -> Type.\n    Hypothesis f : forall a ll, (forall x, In x ll -> P x) -> P (in_tree a ll).\n\n    Let f' : forall t, (forall x, x <ist t -> P x) -> P t.\n    Proof.\n      intros []; apply f.\n    Defined.\n\n    Definition tree_rect t : P t.\n    Proof.\n      apply Fix with (1 := imsub_tree_wf), f'.\n    Defined.\n\n    Section tree_rect_fix.\n    \n      Variable E : forall t, P t -> P t -> Prop.\n\n      Hypothesis f_ext : forall a ll f1 f2, (forall x Hx, E (f1 x Hx) (f2 x Hx)) -> E (f a ll f1) (f a ll f2).\n\n      Fact tree_rect_fix a ll : E (tree_rect (in_tree a ll)) (f a ll (fun t _ => tree_rect t)).\n      Proof.\n        unfold tree_rect, Fix.\n        rewrite <- Fix_F_eq; unfold f'.\n        apply f_ext; intros; apply Fix_F_ext.\n        intros [] ? ?; apply f_ext.\n      Qed.\n      \n    End tree_rect_fix.\n    \n    Section tree_rect_fix_eq.\n\n      Hypothesis f_ext : forall a ll f1 f2, (forall x Hx, f1 x Hx = f2 x Hx) -> f a ll f1 = f a ll f2.\n      \n      (* Coq recursive type-checking does not allow such a definition \n         but it is possible to prove this identity\n      *)\n      \n      Fact tree_rect_fix_eq a ll : tree_rect (in_tree a ll) = f a ll (fun t _ => tree_rect t).\n      Proof.\n        apply tree_rect_fix with (E := fun _ => @eq _); simpl; auto.\n      Qed.\n      \n    End tree_rect_fix_eq.\n\n  End tree_rect.\n  \n  Definition tree_rec (P : tree -> Set)  := tree_rect P.\n  Definition tree_ind (P : tree -> Prop) := tree_rect P.\n\n  Section tree_recursion.\n\n    (* the particular case when the output type does not depend on the tree *)\n\n    Variables (Y : Type) (f : X -> list tree -> list Y -> Y).    \n  \n    Definition tree_recursion : tree -> Y.\n    Proof.\n      apply tree_rect.\n      intros x ll IH.\n      apply (f x ll (list_In_map _ IH)).\n    Defined.\n    \n    (* In that case, extensionnality is for free *)\n\n    Fact tree_recursion_fix x ll : tree_recursion (in_tree x ll) = f x ll (map tree_recursion ll).\n    Proof.\n      unfold tree_recursion at 1.\n      rewrite tree_rect_fix with (E := fun _ => eq).\n      f_equal; apply list_In_map_eq_map.\n      clear x ll; intros x ll g h H; simpl.\n      f_equal; apply list_In_map_ext, H.\n    Qed.\n  \n  End tree_recursion.\n\n  Section tree_eq_dec.\n\n    Hypothesis eqX_dec : forall x y : X, { x = y } + { x <> y }.\n    \n    Theorem tree_eq_dec (t1 t2 : tree) : { t1 = t2 } + { t1 <> t2 }.\n    Proof.\n      revert t2; induction t1 as [ x ll IH ]; intros [ y mm ].\n      destruct (eqX_dec x y) as [ H1 | H1 ].\n      destruct (@list_eq_dec _ ll mm) as [ | C ].\n      intros; apply IH; auto.\n      subst; left; auto.\n      right; contradict C; injection C; auto.\n      right; contradict H1; injection H1; auto.\n    Qed.\n\n  End tree_eq_dec.\n\n  Definition tree_size : tree -> nat.\n  Proof.\n    induction 1 as [ _ _ ll ] using tree_recursion.\n    apply (S (lsum ll)).\n  Defined.\n\n  Fact tree_size_fix x ll : tree_size (in_tree x ll) = S (lsum (map tree_size ll)).\n  Proof.\n    apply tree_recursion_fix.\n  Qed.\n\n  Definition tree_ht : tree -> nat.\n  Proof.\n    induction 1 as [ _ _ IH ] using tree_recursion.\n    apply (S (lmax IH)).\n  Defined.\n  \n  Fact tree_ht_fix x ll : tree_ht (in_tree x ll) = S (lmax (map tree_ht ll)).\n  Proof.\n    apply tree_recursion_fix.\n  Qed.\n  \n  Fact tree_ht_0 t : 0 < tree_ht t.\n  Proof.\n    destruct t; rewrite tree_ht_fix; omega.\n  Qed.\n  \n  Definition tree_sum_ht : tree -> nat.\n  Proof.\n    induction 1 as [ x ll IH ] using tree_recursion.\n    apply (tree_ht (in_tree x ll) + lsum IH).\n  Defined.\n  \n  Fact tree_sum_ht_fix x ll : tree_sum_ht (in_tree x ll)\n                            = tree_ht (in_tree x ll)\n                            + lsum (map tree_sum_ht ll).\n  Proof.\n    apply tree_recursion_fix.\n  Qed.\n  \n  Fact tree_ht_find x ll : ll <> nil -> { t | In t ll /\\ tree_ht (in_tree x ll) = S (tree_ht t) }.\n  Proof.\n    intros H.\n    destruct (lmax_map_inv tree_ht H) as (t & H1 & H2).\n    exists t; rewrite tree_ht_fix, H2; auto.\n  Qed.\n\n  (* this is the subtree relation, aka inclusion *)   \n\n  Reserved Notation \"x '<st' y\" (at level 70, no associativity).\n\n  Inductive sub_tree : tree -> tree -> Prop :=\n    | in_subtree_0 : forall t, t <st t\n    | in_subtree_1 : forall s t x ll, In t ll -> s <st t -> s <st in_tree x ll \n  where \"x <st y\" := (sub_tree x y).\n\n  Fact sub_tree_ht s t : s <st t -> tree_ht s <= tree_ht t.\n  Proof.\n    induction 1 as [ | s t x ll H1 H2 H3 ]; auto.\n    rewrite tree_ht_fix.\n    apply le_trans with (1 := H3).\n    apply le_trans with (2 := le_n_Sn _).\n    apply lmax_In.\n    apply in_map_iff.\n    exists t; auto.\n  Qed.    \n\n  (* this is the strict subtree relation *)\n\n  Reserved Notation \"x '<<st' y\" (at level 70, no associativity).\n\n  Inductive ssub_tree : tree -> tree -> Prop :=\n    | in_ssubtree_0 : forall s   x ll, In s ll -> s <<st in_tree x ll\n    | in_ssubtree_1 : forall s t x ll, In t ll -> s <<st t -> s <<st in_tree x ll \n  where \"x <<st y\" := (ssub_tree x y).\n\n  Fact in_subtree_0' s t : s = t -> s <st t.\n  Proof. intro; subst; constructor. Qed.\n  \n  Fact imsub_ssub_tree s t : s <ist t -> s <<st t.\n  Proof.\n    rewrite imsub_tree_fix.\n    intros (x & ll & H1 & H2); subst.\n    constructor 1; auto.\n  Qed.\n  \n  Fact ssub_sub_tree s t : s <<st t -> s <st t.\n  Proof.\n    induction 1 as [ s | s t ].\n    constructor 2 with s; auto.\n    constructor 1.\n    constructor 2 with t; auto.\n  Qed.\n  \n  Fact ssub_tree_trans r s t : r <<st s -> s <<st t -> r <<st t.\n  Proof.\n    intro; induction 1 as [ s | ? t ]; auto.\n    constructor 2 with s; auto.\n    constructor 2 with t; auto.\n  Qed.\n\n  Fact ssub_imsub_tree : ssub_tree ~eq2 clos_trans _ imsub_tree.\n  Proof.\n    split; intros s t.\n\n    induction 1 as [ s x ll | s t x ll H1 H2 H3 ].\n    constructor 1; auto.\n    constructor 2 with (1 := H3).\n    constructor 1; auto.\n    \n    induction 1 as [ | ? s ].\n    apply imsub_ssub_tree; auto.\n    apply ssub_tree_trans with s; auto.\n  Qed.\n  \n  Fact ssub_tree_wf : well_founded ssub_tree.\n  Proof.\n    generalize imsub_tree_wf; intros H.\n    apply wf_clos_trans in H.\n    revert H; apply wf_incl.\n    intros ? ?; apply ssub_imsub_tree.\n  Qed.\n\n  Fact sub_tree_refl s : s <st s.\n  Proof.\n    constructor 1.\n  Qed.\n\n  Fact sub_tree_trans r s t : r <st s -> s <st t -> r <st t.\n  Proof.\n    intro; induction 1 as [ | ? t ]; auto.\n    constructor 2 with t; auto.\n  Qed.\n\n  Fact ssub_tree_inv_left s t : s <<st t <-> exists s', s <ist s' /\\ s' <st t.\n  Proof.\n    split.\n    \n    induction 1 as [ s x ll | s t x ll H1 H2 (s' & H3 & H4) ].\n    exists (in_tree x ll); split; auto.\n    constructor 1.\n    exists s'; split; auto.\n    constructor 2 with t; auto.\n    \n    intros (s' & H1 & H2).\n    revert s H1.\n    induction H2 as [ s' | s' t x ll H1 H2 H3 ].\n    intro; apply imsub_ssub_tree.\n    intros s Hs.\n    constructor 2 with t; auto.\n  Qed.\n\n  Fact ssub_tree_inv_right s t : s <<st t <-> exists s', s <st s' /\\ s' <ist t.\n  Proof.\n    split.\n\n    intros H.\n    apply ssub_imsub_tree in H.\n    apply clos_trans_tn1_iff in H.\n    induction H as [ | t u H1 H2 (s' & H3 & H4) ].\n    exists s; split; auto; constructor.\n    exists t; split; auto.\n    apply sub_tree_trans with (1 := H3).\n    apply ssub_sub_tree, imsub_ssub_tree, H4.\n    \n    destruct t as [ x ll ]; simpl.\n    intros (s' & H1 & H2); subst.\n    revert x ll H2.\n    induction H1 as [ s | s t x ll H1 H2 IH ]; intros y ll' H3.\n    constructor 1; auto.\n    constructor 2 with (in_tree x ll); auto.\n  Qed.\n  \n  Fact ssub_tree_inv s x ll : s <<st in_tree x ll <-> exists t, s <st t /\\ In t ll.\n  Proof.\n    rewrite ssub_tree_inv_right; simpl; split; auto.\n  Qed.\n\n  Fact sub_ssub_tree_trans r s t : r <st s -> s <<st t -> r <<st t.\n  Proof.\n    intros H1 H2.\n    rewrite ssub_tree_inv_right in H2.\n    destruct H2 as (s' & H2 & H3).\n    rewrite ssub_tree_inv_right.\n    exists s'; split; auto.\n    apply sub_tree_trans with (1 := H1); auto.\n  Qed.\n  \n  Fact ssub_sub_tree_trans r s t : r <<st s -> s <st t -> r <<st t.\n  Proof.\n    intros H1 H2.\n    rewrite ssub_tree_inv_left in H1.\n    destruct H1 as (s' & H1 & H3).\n    rewrite ssub_tree_inv_left.\n    exists s'; split; auto.\n    apply sub_tree_trans with (1 := H3); auto.\n  Qed.\n\n  Fact sub_tree_inv s t : s <st t <-> s = t \\/ s <<st t.\n  Proof.\n    split.\n\n    induction 1 as [ | s t x ll H1 H2 [ H3 | H3 ]]; subst; auto; right.\n    constructor 1; auto.\n    constructor 2 with t; auto.\n    \n    intros [ H | H ].\n    subst; constructor.\n    apply ssub_sub_tree; auto.\n  Qed.\n\n  Fact sub_in_tree_inv s x ll : s <st in_tree x ll -> s = in_tree x ll \\/ exists t, s <st t /\\ In t ll.\n  Proof.\n    intros H.\n    apply sub_tree_inv in H.\n    destruct H as [ H | H ]; auto; right.\n    apply ssub_tree_inv_right in H; auto.\n  Qed.\n\n  Definition tree_leaf t : { x | in_tree x nil <st t }.\n  Proof.\n    induction t as [ x [ | t ll ] IH ] using tree_rect.\n    \n    exists x; constructor 1.\n    destruct (IH t) as (y & Hy).\n    left; auto.\n    exists y; constructor 2 with t; simpl; auto.\n  Qed.\n\n  Section sub_trees.\n\n    Definition sub_trees : tree -> list tree.\n    Proof.\n      induction 1 as [ a ll IH ] using tree_recursion.\n      apply cons.\n      apply (in_tree a ll).\n      apply list_flatten, IH.\n    Defined.\n\n    Fact sub_trees_fix x ll : sub_trees (in_tree x ll) = in_tree x ll::list_flatten (map sub_trees ll).\n    Proof.\n      apply tree_recursion_fix.\n    Qed.\n    \n    Fact sub_trees_sub_tree_eq t x : In x (sub_trees t) <-> x <st t.\n    Proof.\n      split.\n\n      revert x.\n      induction t as [ y ll IH ]; intros x Hx.\n      rewrite sub_trees_fix in Hx.\n      simpl In in Hx.\n      destruct Hx as [ Hx | Hx ].\n      subst x; constructor 1.\n      rewrite list_flatten_spec in Hx.\n      destruct Hx as (mm & H1 & H2).\n      apply in_map_iff in H2.\n      destruct H2 as (t & H2 & H3); subst mm.\n      constructor 2 with t; auto.\n      \n      induction 1 as [ [ x ll ] | s t x ll H1 H2 H3 ]; rewrite sub_trees_fix.\n      left; auto.\n      right.\n      apply list_flatten_spec.\n      exists (sub_trees t); split; auto.\n      apply in_map_iff.\n      exists t; auto.\n    Qed.\n\n  End sub_trees.\n\n  (* finite quantification over the nodes of trees *)\n\n  Section tree_fall_exst.\n\n    Variable P : X -> list tree -> Prop.\n\n    Definition tree_fall (t : tree) : Prop.\n    Proof.\n      induction t as [ a ll IH ].\n      exact (P a ll /\\ forall x Hx, IH x Hx).\n    Defined.\n\n   (* this is how we would like tree_fall to be recursively defined but this would\n       not be well-formed in Coq\n    *)\n\n    Fact tree_fall_fix x ll : tree_fall (in_tree x ll) <-> P x ll /\\ forall t, In t ll -> tree_fall t. \n    Proof.\n      unfold tree_fall at 1.\n      rewrite tree_rect_fix \n        with (E := fun _ A B => A <-> B);\n        firstorder.\n    Qed.\n \n    Section tree_fall_rect.\n  \n      Variable (Q : tree -> Type).\n  \n      Hypothesis HQ : forall x ll, tree_fall (in_tree x ll) -> (forall t, In t ll -> Q t) -> Q (in_tree x ll).\n  \n      Theorem tree_fall_rect t : tree_fall t -> Q t.\n      Proof.\n        induction t as [ x ll IH ]; intros H.\n        apply HQ; auto.\n        rewrite tree_fall_fix in H; destruct H; auto.\n      Qed.\n\n    End tree_fall_rect.\n    \n    Definition tree_fall_rec (Q : tree -> Set) := @tree_fall_rect Q.\n    Definition tree_fall_ind (Q : tree -> Prop) := @tree_fall_rect Q.\n\n    Fact tree_fall_sub_tree t : tree_fall t <-> forall x ll, in_tree x ll <st t -> P x ll.\n    Proof.\n      split.\n\n      induction t as [ x ll IH ]; intros Ht.\n      rewrite tree_fall_fix in Ht.\n      destruct Ht as [ Hx Hll ].\n      intros y mm H1.\n      apply sub_in_tree_inv in H1.\n      destruct H1 as [ H1 | (t & H1 & H2) ].\n      injection H1; clear H1; intros; subst; auto.\n      apply IH with t; auto.\n      \n      induction t as [ x ll IH ]; intros Ht.\n      rewrite tree_fall_fix; split.\n      apply Ht; constructor 1.\n      intros u Hu; apply IH; auto.\n      intros y mm Hmm; apply Ht.\n      constructor 2 with u; auto.\n    Qed.\n\n    Definition tree_exst (t : tree) : Prop.\n    Proof.\n      induction t as [ a ll IH ].\n      exact (P a ll \\/ exists x Hx, IH x Hx).\n    Defined.\n\n    Let disj_eq_prop (A B B' : Prop) : (B <-> B') -> (A \\/ B <-> A \\/ B').\n    Proof. tauto. Qed.\n\n    Fact tree_exst_fix x ll : tree_exst (in_tree x ll) <-> P x ll \\/ exists t, In t ll /\\ tree_exst t. \n    Proof.\n      unfold tree_exst at 1.\n      rewrite tree_rect_fix \n        with (E := fun _ A B => A <-> B).\n      apply disj_eq_prop.\n      split; intros (y & ? & ?); exists y; split; auto.\n      intros; apply disj_eq_prop.\n      split; intros (y & Hy & ?); exists y, Hy; apply H; auto.\n    Qed.\n\n    Fact tree_exst_sub_tree t : tree_exst t <-> exists x ll, in_tree x ll <st t /\\ P x ll.\n    Proof.\n      split.\n\n      induction t as [ x ll IH ]; intros Ht.\n      rewrite tree_exst_fix in Ht.\n      destruct Ht as [ Ht | (t & H1 & H2) ].\n      exists x, ll; split; auto; constructor.\n      destruct (IH _ H1 H2) as (y & mm & H3 & H4).\n      exists y, mm; split; auto.\n      constructor 2 with t; auto.\n      \n      intros (x & ll & H1 & H2); revert x ll H1 H2.\n      induction t as [ x ll IH ]; intros y mm H1 H2.\n      rewrite tree_exst_fix.\n      apply sub_in_tree_inv in H1.\n      destruct H1 as [ H1 | (t & H1 & H3) ].\n      left; injection H1; intros; subst; auto.\n      right; exists t; split; auto.\n      apply IH with (2 := H1); auto.\n    Qed.\n\n    Fact sub_tree_fall t1 t2 : t1 <st t2 -> tree_fall t2 -> tree_fall t1.\n    Proof.\n      induction 1; auto.\n      rewrite tree_fall_fix.\n      intros (? & ?); auto.\n    Qed.\n\n    Fact sub_tree_exst t1 t2 : t1 <st t2 -> tree_exst t1 -> tree_exst t2.\n    Proof.\n      induction 1 as [ | ? t ]; auto.\n      rewrite tree_exst_fix.\n      right; exists t; auto.\n    Qed.\n\n  End tree_fall_exst.\n\n  Fact tree_fall_inc (P Q : _ -> _ -> Prop) : P inc2 Q -> tree_fall P inc1 tree_fall Q.\n  Proof.\n    intros H t; induction t as [ x ll IH ].\n    repeat rewrite tree_fall_fix.\n    intros []; split; auto.\n  Qed.\n\n  Fact tree_exst_inc (P Q : _ -> _ -> Prop) : P inc2 Q -> tree_exst P inc1 tree_exst Q.\n  Proof.\n    intros H t; induction t as [ x ll IH ].\n    repeat rewrite tree_exst_fix.\n    intros [| (t & ? & ?)]; [ left | right ]; auto; exists t; auto.\n  Qed. \n\n  Section tree_fall_exst_dec.\n\n    Variable (P Q : X -> list tree -> Prop).\n\n    Hypothesis PQ_incomp : forall x ll, P x ll -> Q x ll -> False.\n    \n    Fact tree_fall_exst_incomp t : tree_fall P t -> tree_exst Q t -> False.\n    Proof.\n      induction t as [ x ll IH ].\n      rewrite tree_fall_fix, tree_exst_fix.\n      intros [ H1 H2 ] [ H3 | (t & H3 & H4) ].\n      \n      apply PQ_incomp with (1 := H1); auto.\n      apply IH with (1 := H3); auto.\n    Qed.      \n\n    Hypothesis PQ_dec : forall x ll, { P x ll } + { Q x ll }.    \n    \n    Fact tree_fall_exst_dec t : { tree_fall P t } + { tree_exst Q t }.\n    Proof.\n      induction t as [ x ll IH ].\n      destruct (list_choose_rec (tree_exst Q) (tree_fall P) ll) as [ (t & H1 & H2) | H1 ].\n      intros z Hz; specialize (IH _ Hz); tauto.\n      \n      right.\n      apply tree_exst_fix.\n      right; exists t; auto.\n      \n      destruct (PQ_dec x ll) as [ | H2 ].\n      \n      left; apply tree_fall_fix; auto.\n      \n      right.\n      apply tree_exst_fix.\n      left; auto.\n    Qed.\n    \n  End tree_fall_exst_dec.\n\n  Section tree_fall_dec.\n  \n    Variable (P : X -> list tree -> Prop).\n\n    Hypothesis PQ_dec : forall x ll, { P x ll } + { ~ P x ll }.\n    \n    Fact tree_fall_dec t : { tree_fall P t } + { ~ tree_fall P t }.\n    Proof.\n      destruct (tree_fall_exst_dec _ _ PQ_dec t) as [ | C ].\n      tauto.\n      right; intros H.\n      apply tree_fall_exst_incomp with (2 := H) (3 := C).\n      intros; tauto.\n    Qed.\n    \n    Fact tree_exst_dec t : { tree_exst P t } + { ~ tree_exst P t }.\n    Proof.\n      destruct (tree_fall_exst_dec (fun x ll => ~ P x ll) P) with (t := t) as [ C | ].\n      intros x ll; specialize (PQ_dec x ll); tauto.\n      right; intros H.\n      apply tree_fall_exst_incomp with (2 := C) (3 := H).\n      intros; tauto.\n      left; auto.\n    Qed.\n\n  End tree_fall_dec.\n\nEnd trees.\n\nInfix \"<st\" := (@sub_tree _) (at level 70, no associativity).\nInfix \"<<st\" := (@ssub_tree _) (at level 70, no associativity).\nInfix \"<ist\" := (@imsub_tree _) (at level 70, no associativity).\n    \nSection tree_branch.\n\n  Variable X : Type.\n\n  Inductive tree_branch : tree X -> list X -> Prop :=\n    | in_tb0 : forall t, tree_branch t nil\n    | in_tb1 : forall x, tree_branch (in_tree x nil) (x::nil)\n    | in_tb2 : forall b x ll s, In s ll -> tree_branch s b -> tree_branch (in_tree x ll) (x::b).\n\n  Fact tree_branch_inv t b : tree_branch t b \n                          -> b = nil\n                          \\/ tree_sons t = nil /\\ b = tree_root t::nil\n                          \\/ exists b' x ll s,\n                                t = in_tree x ll\n                             /\\ b = x::b'\n                             /\\ In s ll\n                             /\\ tree_branch s b'.\n  Proof.\n    intros [ | x | b' x ll s ]; auto.\n    do 2 right; exists b', x, ll, s; auto.\n  Qed.\n\n  Fact tree_branch_cons_inv x ll y b : tree_branch (in_tree x ll) (y::b)\n                                    -> x = y \n                                    /\\  (ll = nil /\\ b = nil \n                                      \\/ exists s, In s ll /\\ tree_branch s b).\n  Proof.\n    intros H.\n    apply tree_branch_inv in H.\n    destruct H as [ H | [ (H1 & H2) | (b' & z & m & s & H1 & H2 & H3 & H4) ] ].\n    discriminate H.\n    simpl in H1, H2.\n    injection H2; clear H2; intros ? ?; subst y b ll; auto.\n    injection H1; clear H1; intros ? ?; subst z m.\n    injection H2; clear H2; intros ? ?; subst y b'.\n    split; auto; right.\n    exists s; auto.\n  Qed.\n  \n  Definition tree_branch_list : tree X -> list (list X).\n  Proof.\n    apply tree_recursion.\n    intros x [ | y ll ] lb.\n    exact (nil::(x::nil)::nil).\n    exact (nil::map (cons x) (concat lb)).\n  Defined.\n  \n  Fact tree_branch_list_fix0 x : tree_branch_list (in_tree x nil) = nil::(x::nil)::nil.\n  Proof.\n    apply tree_recursion_fix.\n  Qed.\n  \n  Fact tree_branch_list_fix1 x ll : ll <> nil -> tree_branch_list (in_tree x ll) = nil::map (cons x) (flat_map tree_branch_list ll).\n  Proof.\n    destruct ll as [ | y ll ].\n    intros []; reflexivity.\n    intros _.\n    unfold tree_branch_list at 1.\n    rewrite tree_recursion_fix.\n    do 2 f_equal.\n    symmetry; apply flat_map_concat_map.\n  Qed.\n  \n  Fact tree_branch_list_nil t : In nil (tree_branch_list t).\n  Proof.\n    destruct t as [ x [ | y ll ] ].\n    rewrite tree_branch_list_fix0; left; auto.\n    rewrite tree_branch_list_fix1; try discriminate; left; auto.\n  Qed.\n  \n  Fact tree_branch_list_eq t b : tree_branch t b <-> In b (tree_branch_list t).\n  Proof.\n    split.\n    \n    induction 1 as [ | x | b x ll s H1 H2 IH2 ].\n    apply tree_branch_list_nil.\n    rewrite tree_branch_list_fix0; right; left; auto.\n    destruct ll.\n    destruct H1.\n    rewrite tree_branch_list_fix1; try discriminate.\n    right; apply in_map_iff.\n    exists b; split; auto.\n    apply in_flat_map.\n    exists s; auto.\n    \n    revert b; induction t as [ x [ | y ll ] IH ]; intros b.\n    rewrite tree_branch_list_fix0.\n    intros [ [] | [ [] | [] ] ].\n    constructor 1.\n    constructor 2.\n    rewrite tree_branch_list_fix1; try discriminate.\n    intros [ [] | H ].\n    constructor 1.\n    apply in_map_iff in H.\n    destruct H as (b' & ? & H); subst b.\n    apply in_flat_map in H.\n    destruct H as (t & ? & ?).\n    constructor 3 with t; auto.\n  Qed.\n  \n  Fact tree_branch_finite_t t : finite_t (tree_branch t).\n  Proof.\n    exists (tree_branch_list t); symmetry; apply tree_branch_list_eq.\n  Qed.\n\n  Fact tree_branch_root t x l : tree_branch t (x::l) -> tree_root t = x.\n  Proof.\n    intros H.\n    apply tree_branch_inv in H.\n    destruct H as [ H | [ (H1 & H2) | (b & y & m & s & H1 & H2 & H3 & H4) ] ].\n    discriminate H.\n    injection H2; auto.\n    subst t; simpl.\n    injection H2; auto.\n  Qed.\n  \n  (* Every branch is smaller than the height of the tree *)\n\n  Fact tree_branch_length_ht t b : tree_branch t b -> length b <= tree_ht t.\n  Proof.\n    induction 1 as [ | x | b x ll s H1 H2 IH2 ].\n    destruct t; rewrite tree_ht_fix; simpl; omega.\n    rewrite tree_ht_fix; simpl; omega.\n    rewrite tree_ht_fix; simpl; apply le_n_S.\n    apply le_trans with (1 := IH2).\n    apply lmax_In, in_map_iff.\n    exists s; auto.\n  Qed.\n  \n  (* and there is a computable branch which has exactly the height if the tree *)\n  \n  Fact tree_ht_branch t : { b | tree_branch t b /\\ length b = tree_ht t }.\n  Proof.\n    induction t as [ x [ | y ll ] IH ].\n    \n    exists (x::nil); simpl; split; auto.\n    constructor 2; auto.\n    rewrite tree_ht_fix; auto.\n    \n    destruct (@tree_ht_find _ x (y::ll)) as (t & H1 & H2).\n    discriminate.\n    destruct (IH _ H1) as (b & H3 & H4).\n    exists (x::b); split.\n    constructor 3 with t; auto.\n    rewrite H2; simpl; f_equal; auto.\n  Qed.\n  \n  (* Hence n-bounded trees can be characterized by the length of their branches *)\n\n  Fact branch_length_tree_ht t n : (forall b, tree_branch t b -> length b <= n) <-> tree_ht t <= n.\n  Proof.\n    split.\n    intros H.\n    destruct (tree_ht_branch t) as (b & H1 & H2).\n    apply H in H1.\n    rewrite <- H2; auto.\n    intros H1 b H2.\n    apply le_trans with (2 := H1).\n    apply tree_branch_length_ht; auto.\n  Qed.\n\n  Fact tree_search t l m : tree_branch t (l++m) -> exists t', tree_branch t' m /\\ t' <st t.\n  Proof.\n    revert t; induction l as [ | x l IH ]; intros t.\n    exists t; split; auto; constructor 1.\n    intros H; simpl in H.\n    apply tree_branch_inv in H.\n    destruct H as [ H | [ (H1 & H2) | (b & y & mm & s & H1 & H2 & H3 & H4) ] ].\n    discriminate H.\n    injection H2; clear H2; intros H2 H3.\n    destruct l; try discriminate H2.\n    destruct m; try discriminate H2.\n    exists t; split.\n    constructor 1.\n    constructor 1.\n    injection H2; clear H2; intros H2 ?; subst y b.\n    apply IH in H4.\n    destruct H4 as (t' & H4 & H5).\n    exists t'; split; auto.\n    subst t; constructor 2 with s; auto.\n  Qed.\n  \n  Fact tree_split_search t l x r : \n       tree_branch t (l++x::r) -> \n            r = nil /\\ in_tree x nil <st t\n         \\/ exists t' tx, tree_branch t' r /\\ In t' tx /\\ in_tree x tx <st t.\n  Proof.\n    intros Ht.\n    apply tree_search in Ht.\n    destruct Ht as ([ y tx ] & H1 & H2).\n    apply tree_branch_cons_inv in H1.\n    destruct H1 as (? & [ (H5 & H7) | (t' & H5 & H7) ]); subst y.\n    left; subst; auto.\n    right; exists t', tx; auto.\n  Qed. \n\n  Definition bounded_tree n (t : tree X) := tree_ht t <= n.\n  \n  Fact bounded_tree_O : forall t, ~ bounded_tree 0 t.\n  Proof.\n    intros [ x ll ]; unfold bounded_tree; rewrite tree_ht_fix; omega.\n  Qed.\n  \n  Fact bounded_tree_S n t : bounded_tree (S n) t <-> Forall (bounded_tree n) (tree_sons t).\n  Proof.\n    destruct t as [ x ll ]; simpl.\n    unfold bounded_tree; rewrite tree_ht_fix.\n    split.  \n  \n    intros H.\n    apply le_S_n in H.\n    induction ll as [ | y ll IH ]; simpl in H; constructor.\n    apply le_trans with (2 := H), le_max_l.\n    apply IH, le_trans with (2 := H), le_max_r.\n    \n    intros H; apply le_n_S.\n    induction H as [ | y ll IH ]; simpl.\n    omega.\n    apply max_lub; auto.\n  Qed.\n\nEnd tree_branch.\n\nSection tree_irredundant.\n\n  Variables (X : Type) (R : X -> X -> Prop).\n  \n  Hypothesis Rdec : forall x y, { R x y } + { ~ R x y }.\n\n  (* Irredundant tree : no branch is good for R *)\n  \n  Definition tree_irred t := forall b, tree_branch t b -> bad R (rev b).\n  \n  Definition tree_good_or_irred t : { b | tree_branch t b /\\ good R (rev b) } + { tree_irred t }.\n  Proof.\n    destruct (finite_t_decide (fun l => bad R (rev l)) (fun l => good R (rev l)) (tree_branch_finite_t t)); auto.\n    intros x _; destruct (good_bad_dec _ Rdec (rev x)); auto.\n  Qed.\n  \n  Definition tree_irred_dec t : { tree_irred t } + { ~ tree_irred t }.\n  Proof.\n    destruct (tree_good_or_irred t) as [ (b & H1 & H2) | ]; auto.\n    right; intros H.\n    specialize (H _ H1).\n    apply good_bad_False with (1 := H2); auto.\n  Qed.\n\nEnd tree_irredundant.\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/tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6771784307594872}}
{"text": "Require Import FinTypes.\n\n(** * Definition of prod as finType *)\n\nLemma ProdCount (T1 T2: eqType) (A: list T1) (B: list T2) (a:T1) (b:T2)  :\n  count (prodLists A B) (a,b) =  count A a * count B b .\nProof.\n  induction A.\n  - reflexivity.\n  - cbn. rewrite <- countSplit. decide (a = a0) as [E | E].\n    + cbn. f_equal. subst a0. apply countMap. eauto.\n    + rewrite <- plus_O_n. f_equal. now apply countMapZero. eauto.\nQed.\n\nLemma prod_enum_ok (T1 T2: finType) (x: T1 * T2):\n  count (prodLists (elem T1) (elem T2)) x = 1.\nProof.\n  destruct x as [x y]. rewrite ProdCount. unfold elem.\n  now repeat rewrite enum_ok.\nQed.\n\nInstance finTypeC_Prod (F1 F2: finType) : finTypeC (EqType (F1 * F2)).\nProof.\n  econstructor.  apply prod_enum_ok.\nDefined.\n\n(** * Definition of option as finType *)\n\n(** Wrapping elements in \"Some\" does not change the number of occurences in a list *)\nLemma SomeElement (X: eqType) (A: list X) x:\n  count (toOptionList A) (Some x) = count A x .\nProof.\n  unfold toOptionList. simpl. dec; try congruence.\n  induction A.\n  + tauto.  \n  + simpl. dec; congruence.\nQed.\n\n(** A list produced by toOptionList contains None exactly once *)\nLemma NoneElement (X: eqType) (A: list X) :\n  count (toOptionList A) None = 1.\nProof.\n  unfold toOptionList. simpl. dec; try congruence. f_equal.\n  induction A.\n  - reflexivity.\n  - simpl; dec; congruence.    \nQed.\n\nLemma option_enum_ok (T: finType) x :\n  count (toOptionList (elem T)) x = 1.\nProof.\n  destruct x.\n  + rewrite SomeElement. apply enum_ok.\n  + apply NoneElement.\nQed.\n\nInstance  finTypeC_Option(F: finType): finTypeC (EqType (option F)).\nProof.\n  eapply FinTypeC.  apply option_enum_ok.\nDefined.\n\n(** * Definition of sum as finType *)\n\n(** The sum of two nats can only be 1 if one of them is 1 and the other one is 0 *)\nLemma proveOne m n: m = 1 /\\ n = 0 \\/ n = 1 /\\ m = 0 -> m + n = 1.\nProof.\n  omega.\nQed.\n\nLemma sum_enum_ok (X: finType) (Y: finType) x :\n  count (toSumList1 Y (elem X) ++ toSumList2 X (elem Y)) x = 1.\nProof.\n  rewrite <- countSplit. apply proveOne. destruct x.\n  - left. split; cbn.\n    + rewrite toSumList1_count. apply enum_ok.\n    + apply toSumList2_missing.\n  - right. split; cbn.\n    + rewrite toSumList2_count. apply enum_ok.\n    + apply toSumList1_missing.\nQed.\n\n(** Instance declaration for sum types for  the type class *)\nInstance finTypeC_sum (X Y: finType) : finTypeC (EqType ( X + Y)).\nProof.\n  eapply FinTypeC. apply sum_enum_ok.\nDefined.\n\n(* Some hints to make the typeclass inference work *)\n\nHint Extern 4 (finTypeC (EqType (_ * _))) => eapply finTypeC_Prod : typeclass_instances.\nHint Extern 4 (finTypeC (EqType (_ + _))) => eapply finTypeC_sum : typeclass_instances.\nHint Extern 4 (finTypeC (EqType (option _))) => eapply finTypeC_Option : typeclass_instances.\n", "meta": {"author": "uds-psl", "repo": "base-library", "sha": "d9f3b8abf379d4c12049dd25c8d1fdf1973dab48", "save_path": "github-repos/coq/uds-psl-base-library", "path": "github-repos/coq/uds-psl-base-library/base-library-d9f3b8abf379d4c12049dd25c8d1fdf1973dab48/FiniteTypes/CompoundFinTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6771784297057246}}
{"text": "(*****************************************************************************)\n(*                                                                           *)\n(*  Lemmas.v                                                                 *)\n(*                                                                           *)\n(*  This file establishes identities between array operations.               *)\n(*                                                                           *)\n(*  While the identities proven here can be useful for transforming complex  *)\n(*  expressions built from array operations, they also serve the purpose of  *)\n(*  verifying that the definitions of array operations behave as expected.   *)\n(*  This is particularly relevant for the operations that have less trivial  *)\n(*  definitions, i.e. 'split', 'append', 'foldl' and 'foldr'.                *)\n(*                                                                           *)\n(*****************************************************************************)\n\n\nRequire Import FunctionalExtensionality.\nRequire Import Program.Equality.\n\nRequire Import TensorIR.Equations.Shallow.Domain.\nRequire Import TensorIR.Equations.Shallow.Vectors.\nRequire Import TensorIR.Arrays.Array.\nRequire Import TensorIR.Arrays.Operations.\n\nImport VectorNotations.\n\n\n\nLemma map_compose {a b c : Type} {r : nat} {sh : NVect r} : \n  forall (f : a -> b) (g : b -> c) (x : Array sh a),\n  (map g) ((map f) x) = map (fun z => g (f z)) x.\nProof.\n  intuition.\nQed.\n\n\nLemma map_reshape {a b : Type} {r s : nat} {sh : NVect r} {sh' : NVect s} :\n  forall (f : a -> b) (rs : DomainT sh' -> DomainT sh) (x : Array sh a),\n    map f (reshape rs x) = reshape rs (map f x).\nProof.\n  intuition.\nQed.\n\n\nLemma split_append {a : Type} {r : nat} {sh : NVect r} {m n : nat} :\n  forall (x : Array (m::sh) a) (y : Array (n::sh) a),\n    split (append x y) = (x, y).\nProof.\n  intuition.\n  apply injective_projections;\n    apply functional_extensionality; simpl; intuition;\n    rewrite sep_join; auto.\nQed.\n\n\nLemma append_split {a : Type} {r : nat} {sh : NVect r} {m n : nat} :\n  forall (x : Array (m+n::sh) a),\n    let (y0,y1) := split x in append y0 y1 = x.\nProof.\n  intro x.\n  unfold split, append; apply functional_extensionality; intuition.\n  destruct x0 as (i0,i').\n  pose proof (join_sep i0) as H.\n  destruct (sep i0); rewrite <- H; auto.\nQed.\n\n\nLemma split_map_append {a b : Type} {r : nat} {sh : NVect r} {m n : nat} :\n  forall (f : a -> b) (x : Array (m+n::sh) a),\n    let (y0,y1) := split x in\n    append (map f y0) (map f y1) = map f x.\nProof with auto.\n  intuition.\n  pose proof (@append_split b r sh m n (map f x)) as H.\n  rewrite <- H.\n  apply functional_extensionality...\nQed.\n\n\nLemma split_0_empty {a : Type} {r : nat} {sh : NVect r} {n : nat} :\n  forall (x : Array (0+n::sh) a),\n    fst (split x) = empty sh.\nProof.\n  intro x.\n  apply functional_extensionality; intro i.\n  destruct i. inversion f.\nQed.\n\n\nLemma append_head_behead {a : Type} {r : nat} {sh : NVect r} :\n  forall (k : nat) (x : Array (S k::sh) a),\n    append (prop 0 (head x)) (behead x) = x.\nProof.\n  intros; apply functional_extensionality;\n    destruct x0 as (i0,i');\n    dependent destruction i0; auto.\nQed.\n\n\nLemma head_append {a : Type} {r : nat} {sh : NVect r} :\n  forall (m n : nat) (x : Array (S m::sh) a) (y : Array (n::sh) a),\n    head (append x y) = head x.\nProof.\n  intros; apply functional_extensionality; auto.\nQed.\n\n\nLemma append_head_append_behead {a : Type} {r : nat} {sh : NVect r} :\n  forall (m n : nat) (x : Array (S m::sh) a) (y : Array (n::sh) a),\n  append x y = append (prop 0 (head x)) (append (behead x) y).\nProof.\n  intros.\n  apply functional_extensionality; intro i.\n  destruct i as (i0,i').\n  dependent destruction i0... simpl. unfold head. reflexivity.\n  simpl. destruct (sep i0); auto.\nQed.\n\n\nLemma foldl_step {a : Type} {m : nat} {r : nat} {sh : NVect r} :\n  forall (f : Array sh a -> Array sh a -> Array sh a),\n    (forall u v w, f (f u v) w = f u (f v w)) ->\n      forall (i u : Array sh a) (v : Array (m::sh) a),\n        foldl f (f u i) v = f u (foldl f i v).\nProof with auto.\n  induction m; intros f assoc; auto.\n  + intuition.\n    unfold foldl at 2. fold (@foldl). rewrite IHm...\n    unfold foldl at 1. fold (@foldl). rewrite IHm...\nQed.\n\n\nLemma fold_lr {a : Type} {m : nat} {r : nat} {sh : NVect r} :\n  forall (f : Array sh a -> Array sh a -> Array sh a),\n    (forall u v w, f (f u v) w = f u (f v w)) ->\n      forall (init : Array sh a), (forall u, f u init = f init u) ->\n        forall (x : Array (m::sh) a), foldl f init x = foldr f init x.\nProof with auto.\n  induction m; intros f assoc init comm x; auto.\n  + simpl.\n    rewrite <- IHm...\n    unfold foldl. fold (@foldl).\n    rewrite <- comm.\n    rewrite foldl_step...\nQed.\n", "meta": {"author": "normanrink", "repo": "TensorIR", "sha": "00ec2cec5b818f01f5f92ec192eb5c866455cdf0", "save_path": "github-repos/coq/normanrink-TensorIR", "path": "github-repos/coq/normanrink-TensorIR/TensorIR-00ec2cec5b818f01f5f92ec192eb5c866455cdf0/arrays/Lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6771784253195298}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2019       *)\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.\nRequire Import NZAdd NZOrder ZAdd NZBase.\nRequire Import GenericMinMax ZMaxMin.\n\n\n(** * Euclidean Division for integers, Euclid convention\n    We use here the \"usual\" formulation of the Euclid Theorem\n    [forall a b, b<>0 -> exists r q, a = b*q+r /\\ 0 <= r < |b| ]\n    The outcome of the modulo function is hence always positive.\n    This corresponds to convention \"E\" in the following paper:\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    See files [ZDivTrunc] and [ZDivFloor] for others conventions.\n    We simply extend NZDiv with a bound for modulo that holds\n    regardless of the sign of a and b. This new specification\n    subsume mod_bound_pos, which nonetheless stays there for\n    subtyping. Note also that ZAxiomSig now already contain\n    a div and a modulo (that follow the Floor convention).\n    We just ignore them here.\n*)\n\nModule Type EuclidSpec (Import A : ZAxiomsSig')(Import B : DivMod A).\n Axiom mod_always_pos : forall a b, b ~= 0 -> 0 <= B.modulo a b < abs b.\nEnd EuclidSpec.\n\nModule Type ZEuclid (Z:ZAxiomsSig) := NZDiv.NZDiv Z <+ EuclidSpec Z.\n\nModule ZEuclidProp\n (Import A : ZAxiomsSig')\n (Import B : ZMulOrderProp A)\n (Import C : ZSgnAbsProp A B)\n (Import D : ZEuclid A).\n\n (** We put notations in a scope, to avoid warnings about\n     redefinitions of notations *)\n(* Declare Scope euclid. *)\n Infix \"/\" := D.div : euclid.\n Infix \"mod\" := D.modulo : euclid.\n Local Open Scope euclid.\n\n Module Import Private_NZDiv := Nop <+ NZDivProp A D B.\n\n(** Another formulation of the main equation *)\n\nLemma mod_eq :\n forall a b, b~=0 -> a mod b == a - b*(a/b).\nProof.\nintros.\nrewrite <- add_move_l.\nsymmetry. now apply div_mod.\nQed.\n\nLtac pos_or_neg a :=\n let LT := fresh \"LT\" in\n let LE := fresh \"LE\" in\n destruct (le_gt_cases 0 a) as [LE|LT]; [|rewrite <- opp_pos_neg in LT].\n\n(** Uniqueness theorems *)\n\nTheorem div_mod_unique : forall b q1 q2 r1 r2 : t,\n  0<=r1<abs b -> 0<=r2<abs b ->\n  b*q1+r1 == b*q2+r2 -> q1 == q2 /\\ r1 == r2.\nProof.\nintros b q1 q2 r1 r2 Hr1 Hr2 EQ.\npos_or_neg b.\nrewrite abs_eq in * by trivial.\napply div_mod_unique with b; trivial.\nrewrite abs_neq' in * by auto using lt_le_incl.\nrewrite eq_sym_iff. apply div_mod_unique with (-b); trivial.\nrewrite 2 mul_opp_l.\nrewrite add_move_l, sub_opp_r.\nrewrite <-add_assoc.\nsymmetry. rewrite add_move_l, sub_opp_r.\nnow rewrite (add_comm r2), (add_comm r1).\nQed.\n\nTheorem div_unique:\n forall a b q r, 0<=r<abs b -> a == b*q + r -> q == a/b.\nProof.\nintros a b q r Hr EQ.\nassert (Hb : b~=0).\n pos_or_neg b.\n rewrite abs_eq in Hr; intuition; order.\n rewrite <- opp_0, eq_opp_r. rewrite abs_neq' in Hr; intuition; order.\ndestruct (div_mod_unique b q (a/b) r (a mod b)); trivial.\nnow apply mod_always_pos.\nnow rewrite <- div_mod.\nQed.\n\nTheorem mod_unique:\n forall a b q r, 0<=r<abs b -> a == b*q + r -> r == a mod b.\nProof.\nintros a b q r Hr EQ.\nassert (Hb : b~=0).\n pos_or_neg b.\n rewrite abs_eq in Hr; intuition; order.\n rewrite <- opp_0, eq_opp_r. rewrite abs_neq' in Hr; intuition; order.\ndestruct (div_mod_unique b q (a/b) r (a mod b)); trivial.\nnow apply mod_always_pos.\nnow rewrite <- div_mod.\nQed.\n\n(** Sign rules *)\n\nLemma div_opp_r : forall a b, b~=0 -> a/(-b) == -(a/b).\nProof.\nintros. symmetry.\napply div_unique with (a mod b).\nrewrite abs_opp; now apply mod_always_pos.\nrewrite mul_opp_opp; now apply div_mod.\nQed.\n\nLemma mod_opp_r : forall a b, b~=0 -> a mod (-b) == a mod b.\nProof.\nintros. symmetry.\napply mod_unique with (-(a/b)).\nrewrite abs_opp; now apply mod_always_pos.\nrewrite mul_opp_opp; now apply div_mod.\nQed.\n\nLemma div_opp_l_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a)/b == -(a/b).\nProof.\nintros a b Hb Hab. symmetry.\napply div_unique with (-(a mod b)).\nrewrite Hab, opp_0. split; [order|].\npos_or_neg b; [rewrite abs_eq | rewrite abs_neq']; order.\nnow rewrite mul_opp_r, <-opp_add_distr, <-div_mod.\nQed.\n\nLemma div_opp_l_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a)/b == -(a/b)-sgn b.\nProof.\nintros a b Hb Hab. symmetry.\napply div_unique with (abs b -(a mod b)).\nrewrite lt_sub_lt_add_l.\nrewrite <- le_add_le_sub_l. nzsimpl.\nrewrite <- (add_0_l (abs b)) at 2.\nrewrite <- add_lt_mono_r.\ndestruct (mod_always_pos a b); intuition order.\nrewrite <- 2 add_opp_r, mul_add_distr_l, 2 mul_opp_r.\nrewrite sgn_abs.\nrewrite add_shuffle2, add_opp_diag_l; nzsimpl.\nrewrite <-opp_add_distr, <-div_mod; order.\nQed.\n\nLemma mod_opp_l_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a) mod b == 0.\nProof.\nintros a b Hb Hab. symmetry.\napply mod_unique with (-(a/b)).\nsplit; [order|now rewrite abs_pos].\nnow rewrite <-opp_0, <-Hab, mul_opp_r, <-opp_add_distr, <-div_mod.\nQed.\n\nLemma mod_opp_l_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a) mod b == abs b - (a mod b).\nProof.\nintros a b Hb Hab. symmetry.\napply mod_unique with (-(a/b)-sgn b).\nrewrite lt_sub_lt_add_l.\nrewrite <- le_add_le_sub_l. nzsimpl.\nrewrite <- (add_0_l (abs b)) at 2.\nrewrite <- add_lt_mono_r.\ndestruct (mod_always_pos a b); intuition order.\nrewrite <- 2 add_opp_r, mul_add_distr_l, 2 mul_opp_r.\nrewrite sgn_abs.\nrewrite add_shuffle2, add_opp_diag_l; nzsimpl.\nrewrite <-opp_add_distr, <-div_mod; order.\nQed.\n\nLemma div_opp_opp_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a)/(-b) == a/b.\nProof.\nintros. now rewrite div_opp_r, div_opp_l_z, opp_involutive.\nQed.\n\nLemma div_opp_opp_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a)/(-b) == a/b + sgn(b).\nProof.\nintros. rewrite div_opp_r, div_opp_l_nz by trivial.\nnow rewrite opp_sub_distr, opp_involutive.\nQed.\n\nLemma mod_opp_opp_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a) mod (-b) == 0.\nProof.\nintros. now rewrite mod_opp_r, mod_opp_l_z.\nQed.\n\nLemma mod_opp_opp_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a) mod (-b) == abs b - a mod b.\nProof.\nintros. now rewrite mod_opp_r, mod_opp_l_nz.\nQed.\n\n(** A division by itself returns 1 *)\n\nLemma div_same : forall a, a~=0 -> a/a == 1.\nProof.\nintros. symmetry. apply div_unique with 0.\nsplit; [order|now rewrite abs_pos].\nnow nzsimpl.\nQed.\n\nLemma mod_same : forall a, a~=0 -> a mod a == 0.\nProof.\nintros.\nrewrite mod_eq, div_same by trivial. nzsimpl. apply sub_diag.\nQed.\n\n(** A division of a small number by a bigger one yields zero. *)\n\nTheorem div_small: forall a b, 0<=a<b -> a/b == 0.\nProof. exact div_small. Qed.\n\n(** Same situation, in term of modulo: *)\n\nTheorem mod_small: forall a b, 0<=a<b -> a mod b == a.\nProof. exact mod_small. Qed.\n\n(** * Basic values of divisions and modulo. *)\n\nLemma div_0_l: forall a, a~=0 -> 0/a == 0.\nProof.\nintros. pos_or_neg a. apply div_0_l; order.\napply opp_inj. rewrite <- div_opp_r, opp_0 by trivial. now apply div_0_l.\nQed.\n\nLemma mod_0_l: forall a, a~=0 -> 0 mod a == 0.\nProof.\nintros; rewrite mod_eq, div_0_l; now nzsimpl.\nQed.\n\nLemma div_1_r: forall a, a/1 == a.\nProof.\nintros. symmetry. apply div_unique with 0.\nassert (H:=lt_0_1); rewrite abs_pos; intuition; order.\nnow nzsimpl.\nQed.\n\nLemma mod_1_r: forall a, a mod 1 == 0.\nProof.\nintros. rewrite mod_eq, div_1_r; nzsimpl; auto using sub_diag.\napply neq_sym, lt_neq; apply lt_0_1.\nQed.\n\nLemma div_1_l: forall a, 1<a -> 1/a == 0.\nProof. exact div_1_l. Qed.\n\nLemma mod_1_l: forall a, 1<a -> 1 mod a == 1.\nProof. exact mod_1_l. Qed.\n\nLemma div_mul : forall a b, b~=0 -> (a*b)/b == a.\nProof.\nintros. symmetry. apply div_unique with 0.\nsplit; [order|now rewrite abs_pos].\nnzsimpl; apply mul_comm.\nQed.\n\nLemma mod_mul : forall a b, b~=0 -> (a*b) mod b == 0.\nProof.\nintros. rewrite mod_eq, div_mul by trivial. rewrite mul_comm; apply sub_diag.\nQed.\n\nTheorem div_unique_exact a b q: b~=0 -> a == b*q -> q == a/b.\nProof.\n intros Hb H. rewrite H, mul_comm. symmetry. now apply div_mul.\nQed.\n\n(** * Order results about mod and div *)\n\n(** A modulo cannot grow beyond its starting point. *)\n\nTheorem mod_le: forall a b, 0<=a -> b~=0 -> a mod b <= a.\nProof.\nintros. pos_or_neg b. apply mod_le; order.\nrewrite <- mod_opp_r by trivial. apply mod_le; order.\nQed.\n\nTheorem div_pos : forall a b, 0<=a -> 0<b -> 0<= a/b.\nProof. exact div_pos. Qed.\n\nLemma div_str_pos : forall a b, 0<b<=a -> 0 < a/b.\nProof. exact div_str_pos. Qed.\n\nLemma div_small_iff : forall a b, b~=0 -> (a/b==0 <-> 0<=a<abs b).\nProof.\nintros a b Hb.\nsplit.\nintros EQ.\nrewrite (div_mod a b Hb), EQ; nzsimpl.\nnow apply mod_always_pos.\nintros. pos_or_neg b.\napply div_small.\nnow rewrite <- (abs_eq b).\napply opp_inj; rewrite opp_0, <- div_opp_r by trivial.\napply div_small.\nrewrite <- (abs_neq' b) by order. trivial.\nQed.\n\nLemma mod_small_iff : forall a b, b~=0 -> (a mod b == a <-> 0<=a<abs b).\nProof.\nintros.\nrewrite <- div_small_iff, mod_eq by trivial.\nrewrite sub_move_r, <- (add_0_r a) at 1. rewrite add_cancel_l.\nrewrite eq_sym_iff, eq_mul_0. tauto.\nQed.\n\n(** As soon as the divisor is strictly greater than 1,\n    the division is strictly decreasing. *)\n\nLemma div_lt : forall a b, 0<a -> 1<b -> a/b < a.\nProof. exact div_lt. Qed.\n\n(** [le] is compatible with a positive division. *)\n\nLemma div_le_mono : forall a b c, 0<c -> a<=b -> a/c <= b/c.\nProof.\nintros a b c Hc Hab.\nrewrite lt_eq_cases in Hab. destruct Hab as [LT|EQ];\n [|rewrite EQ; order].\nrewrite <- lt_succ_r.\nrewrite (mul_lt_mono_pos_l c) by order.\nnzsimpl.\nrewrite (add_lt_mono_r _ _ (a mod c)).\nrewrite <- div_mod by order.\napply lt_le_trans with b; trivial.\nrewrite (div_mod b c) at 1 by order.\nrewrite <- add_assoc, <- add_le_mono_l.\napply le_trans with (c+0).\nnzsimpl; destruct (mod_always_pos b c); try order.\nrewrite abs_eq in *; order.\nrewrite <- add_le_mono_l. destruct (mod_always_pos a c); order.\nQed.\n\n(** In this convention, [div] performs Rounding-Toward-Bottom\n    when divisor is positive, and Rounding-Toward-Top otherwise.\n    Since we cannot speak of rational values here, we express this\n    fact by multiplying back by [b], and this leads to a nice\n    unique statement.\n*)\n\nLemma mul_div_le : forall a b, b~=0 -> b*(a/b) <= a.\nProof.\nintros.\nrewrite (div_mod a b) at 2; trivial.\nrewrite <- (add_0_r (b*(a/b))) at 1.\nrewrite <- add_le_mono_l.\nnow destruct (mod_always_pos a b).\nQed.\n\n(** Giving a reversed bound is slightly more complex *)\n\nLemma mul_succ_div_gt: forall a b, 0<b -> a < b*(S (a/b)).\nProof.\nintros.\nnzsimpl.\nrewrite (div_mod a b) at 1; try order.\nrewrite <- add_lt_mono_l.\ndestruct (mod_always_pos a b). order.\nrewrite abs_eq in *; order.\nQed.\n\nLemma mul_pred_div_gt: forall a b, b<0 -> a < b*(P (a/b)).\nProof.\nintros a b Hb.\nrewrite mul_pred_r, <- add_opp_r.\nrewrite (div_mod a b) at 1; try order.\nrewrite <- add_lt_mono_l.\ndestruct (mod_always_pos a b). order.\nrewrite <- opp_pos_neg in Hb. rewrite abs_neq' in *; order.\nQed.\n\n(** NB: The three previous properties could be used as\n    specifications for [div]. *)\n\n(** Inequality [mul_div_le] is exact iff the modulo is zero. *)\n\nLemma div_exact : forall a b, b~=0 -> (a == b*(a/b) <-> a mod b == 0).\nProof.\nintros.\nrewrite (div_mod a b) at 1; try order.\nrewrite <- (add_0_r (b*(a/b))) at 2.\napply add_cancel_l.\nQed.\n\n(** Some additional inequalities about div. *)\n\nTheorem div_lt_upper_bound:\n  forall a b q, 0<b -> a < b*q -> a/b < q.\nProof.\nintros.\nrewrite (mul_lt_mono_pos_l b) by trivial.\napply le_lt_trans with a; trivial.\napply mul_div_le; order.\nQed.\n\nTheorem div_le_upper_bound:\n  forall a b q, 0<b -> a <= b*q -> a/b <= q.\nProof.\nintros.\nrewrite <- (div_mul q b) by order.\napply div_le_mono; trivial. now rewrite mul_comm.\nQed.\n\nTheorem div_le_lower_bound:\n  forall a b q, 0<b -> b*q <= a -> q <= a/b.\nProof.\nintros.\nrewrite <- (div_mul q b) by order.\napply div_le_mono; trivial. now rewrite mul_comm.\nQed.\n\n(** A division respects opposite monotonicity for the divisor *)\n\nLemma div_le_compat_l: forall p q r, 0<=p -> 0<q<=r -> p/r <= p/q.\nProof. exact div_le_compat_l. Qed.\n\n(** * Relations between usual operations and mod and div *)\n\nLemma mod_add : forall a b c, c~=0 ->\n (a + b * c) mod c == a mod c.\nProof.\nintros.\nsymmetry.\napply mod_unique with (a/c+b); trivial.\nnow apply mod_always_pos.\nrewrite mul_add_distr_l, add_shuffle0, <- div_mod by order.\nnow rewrite mul_comm.\nQed.\n\nLemma div_add : forall a b c, c~=0 ->\n (a + b * c) / c == a / c + b.\nProof.\nintros.\napply (mul_cancel_l _ _ c); try order.\napply (add_cancel_r _ _ ((a+b*c) mod c)).\nrewrite <- div_mod, mod_add by order.\nrewrite mul_add_distr_l, add_shuffle0, <- div_mod by order.\nnow rewrite mul_comm.\nQed.\n\nLemma div_add_l: forall a b c, b~=0 ->\n (a * b + c) / b == a + c / b.\nProof.\n intros a b c. rewrite (add_comm _ c), (add_comm a).\n now apply div_add.\nQed.\n\n(** Cancellations. *)\n\n(** With the current convention, the following isn't always true\n    when [c<0]: [-3*-1 / -2*-1 = 3/2 = 1] while [-3/-2 = 2] *)\n\nLemma div_mul_cancel_r : forall a b c, b~=0 -> 0<c ->\n (a*c)/(b*c) == a/b.\nProof.\nintros.\nsymmetry.\napply div_unique with ((a mod b)*c).\n(* ineqs *)\nrewrite abs_mul, (abs_eq c) by order.\nrewrite <-(mul_0_l c), <-mul_lt_mono_pos_r, <-mul_le_mono_pos_r by trivial.\nnow apply mod_always_pos.\n(* equation *)\nrewrite (div_mod a b) at 1 by order.\nrewrite mul_add_distr_r.\nrewrite add_cancel_r.\nrewrite <- 2 mul_assoc. now rewrite (mul_comm c).\nQed.\n\nLemma div_mul_cancel_l : forall a b c, b~=0 -> 0<c ->\n (c*a)/(c*b) == a/b.\nProof.\nintros. rewrite !(mul_comm c); now apply div_mul_cancel_r.\nQed.\n\nLemma mul_mod_distr_l: forall a b c, b~=0 -> 0<c ->\n  (c*a) mod (c*b) == c * (a mod b).\nProof.\nintros.\nrewrite <- (add_cancel_l _ _ ((c*b)* ((c*a)/(c*b)))).\nrewrite <- div_mod.\nrewrite div_mul_cancel_l by trivial.\nrewrite <- mul_assoc, <- mul_add_distr_l, mul_cancel_l by order.\napply div_mod; order.\nrewrite <- neq_mul_0; intuition; order.\nQed.\n\nLemma mul_mod_distr_r: forall a b c, b~=0 -> 0<c ->\n  (a*c) mod (b*c) == (a mod b) * c.\nProof.\n intros. rewrite !(mul_comm _ c); now rewrite mul_mod_distr_l.\nQed.\n\n\n(** Operations modulo. *)\n\nTheorem mod_mod: forall a n, n~=0 ->\n (a mod n) mod n == a mod n.\nProof.\nintros. rewrite mod_small_iff by trivial.\nnow apply mod_always_pos.\nQed.\n\nLemma mul_mod_idemp_l : forall a b n, n~=0 ->\n ((a mod n)*b) mod n == (a*b) mod n.\nProof.\n intros a b n Hn. symmetry.\n rewrite (div_mod a n) at 1 by order.\n rewrite add_comm, (mul_comm n), (mul_comm _ b).\n rewrite mul_add_distr_l, mul_assoc.\n rewrite mod_add by trivial.\n now rewrite mul_comm.\nQed.\n\nLemma mul_mod_idemp_r : forall a b n, n~=0 ->\n (a*(b mod n)) mod n == (a*b) mod n.\nProof.\n intros. rewrite !(mul_comm a). now apply mul_mod_idemp_l.\nQed.\n\nTheorem mul_mod: forall a b n, n~=0 ->\n (a * b) mod n == ((a mod n) * (b mod n)) mod n.\nProof.\n intros. now rewrite mul_mod_idemp_l, mul_mod_idemp_r.\nQed.\n\nLemma add_mod_idemp_l : forall a b n, n~=0 ->\n ((a mod n)+b) mod n == (a+b) mod n.\nProof.\n intros a b n Hn. symmetry.\n rewrite (div_mod a n) at 1 by order.\n rewrite <- add_assoc, add_comm, mul_comm.\n now rewrite mod_add.\nQed.\n\nLemma add_mod_idemp_r : forall a b n, n~=0 ->\n (a+(b mod n)) mod n == (a+b) mod n.\nProof.\n intros. rewrite !(add_comm a). now apply add_mod_idemp_l.\nQed.\n\nTheorem add_mod: forall a b n, n~=0 ->\n (a+b) mod n == (a mod n + b mod n) mod n.\nProof.\n intros. now rewrite add_mod_idemp_l, add_mod_idemp_r.\nQed.\n\n(** With the current convention, the following result isn't always\n    true with a negative intermediate divisor. For instance\n    [ 3/(-2)/(-2) = 1 <> 0 = 3 / (-2*-2) ] and\n    [ 3/(-2)/2 = -1 <> 0 = 3 / (-2*2) ]. *)\n\nLemma div_div : forall a b c, 0<b -> c~=0 ->\n (a/b)/c == a/(b*c).\nProof.\n intros a b c Hb Hc.\n apply div_unique with (b*((a/b) mod c) + a mod b).\n (* begin 0<= ... <abs(b*c) *)\n rewrite abs_mul.\n destruct (mod_always_pos (a/b) c), (mod_always_pos a b); try order.\n split.\n apply add_nonneg_nonneg; trivial.\n apply mul_nonneg_nonneg; order.\n apply lt_le_trans with (b*((a/b) mod c) + abs b).\n now rewrite <- add_lt_mono_l.\n rewrite (abs_eq b) by order.\n now rewrite <- mul_succ_r, <- mul_le_mono_pos_l, le_succ_l.\n (* end 0<= ... < abs(b*c) *)\n rewrite (div_mod a b) at 1 by order.\n rewrite add_assoc, add_cancel_r.\n rewrite <- mul_assoc, <- mul_add_distr_l, mul_cancel_l by order.\n apply div_mod; order.\nQed.\n\n(** Similarly, the following result doesn't always hold when [b<0].\n    For instance [3 mod (-2*-2)) = 3] while\n    [3 mod (-2) + (-2)*((3/-2) mod -2) = -1]. *)\n\nLemma mod_mul_r : forall a b c, 0<b -> c~=0 ->\n a mod (b*c) == a mod b + b*((a/b) mod c).\nProof.\n intros a b c Hb Hc.\n apply add_cancel_l with (b*c*(a/(b*c))).\n rewrite <- div_mod by (apply neq_mul_0; split; order).\n rewrite <- div_div by trivial.\n rewrite add_assoc, add_shuffle0, <- mul_assoc, <- mul_add_distr_l.\n rewrite <- div_mod by order.\n apply div_mod; order.\nQed.\n\nLemma mod_div: forall a b, b~=0 ->\n a mod b / b == 0.\nProof.\n intros a b Hb.\n rewrite div_small_iff by assumption.\n auto using mod_always_pos.\nQed.\n\n(** A last inequality: *)\n\nTheorem div_mul_le:\n forall a b c, 0<=a -> 0<b -> 0<=c -> c*(a/b) <= (c*a)/b.\nProof. exact div_mul_le. Qed.\n\n(** mod is related to divisibility *)\n\nLemma mod_divides : forall a b, b~=0 ->\n (a mod b == 0 <-> (b|a)).\nProof.\nintros a b Hb. split.\nintros Hab. exists (a/b). rewrite mul_comm.\n rewrite (div_mod a b Hb) at 1. rewrite Hab; now nzsimpl.\nintros (c,Hc). rewrite Hc. now apply mod_mul.\nQed.\n\n(********* Lemmas from GenericMinMax that I can't import for some reason? ******)\nLemma max_comm : forall n m, (max n m) == (max m n).\nProof.\nAdmitted.\n\nLemma min_comm n m : min n m == min m n.\nProof.\nAdmitted.\n\nLemma max_le_iff n m p : p <= max n m <-> p <= n \\/ p <= m.\nProof.\nAdmitted.\n\nLemma min_le n m p : min n m <= p -> n <= p \\/ m <= p.\nProof.\nAdmitted.\n\nLemma min_le_iff n m p : min n m <= p <-> n <= p \\/ m <= p.\nProof.\nAdmitted.\n\n(********* Helpful lemmas ************)\n\nLemma lt_neq_ooo : forall n m, n < m -> m ~= n.\nProof.\n  intros.\n  cut (n ~= m).\n  apply neq_sym.\n  apply lt_neq.\n  assumption.\nQed.\n\nLemma neg_div_antimonotone : forall a b c, c < 0 -> a <= b -> a/c >= b/c.\nProof.\n  intros.\n  rewrite <- opp_involutive with (n := c) at 1.\n  rewrite div_opp_r.\n  rewrite le_ngt.\n  rewrite <- opp_involutive with (n := c) at 1.\n  rewrite div_opp_r.\n  rewrite nlt_ge.\n  rewrite <- opp_le_mono.\n  apply div_le_mono.\n  apply opp_pos_neg.\n  assumption.\n  assumption.\n  apply lt_neq_ooo.\n  apply opp_pos_neg.\n  assumption.\n  apply lt_neq_ooo.\n  apply opp_pos_neg.\n  assumption.\nQed.\n\nLemma max_proper : forall x y z, x == y -> (max x z) == (max y z).\nProof.\n  intros.\n  cut (x <= z \\/ x > z).\n  intros.\n  destruct H0.\n  rewrite max_r.\n  cut (y <= z).\n  intros.\n  rewrite max_r.\n  reflexivity.\n  assumption.\n  rewrite <- H.\n  assumption.\n  assumption.\n  (cut (z <= x)).\n  intros.\n  rewrite max_l.\n  (cut (z <= y)).\n  intros.\n  rewrite max_l.\n  assumption.\n  assumption.\n  rewrite <- H.\n  assumption.\n  assumption.\n  apply lt_le_incl.\n  assumption.\n  apply le_gt_cases.\nQed.\n\nLemma min_proper : forall x y z, x == y -> (min x z) == (min y z).\nProof.\n  intros.\n  cut (x <= z \\/ x > z).\n  intros.\n  destruct H0.\n  rewrite min_l.\n  cut (y <= z).\n  intros.\n  rewrite min_l.\n  rewrite H.\n  reflexivity.\n  assumption.\n  rewrite <- H.\n  assumption.\n  assumption.\n  cut (z <= x).\n  intros.\n  rewrite min_r.\n  cut (z <= y).\n  intros.\n  rewrite min_r.\n  reflexivity.\n  assumption.\n  rewrite <- H.\n  assumption.\n  assumption.\n  apply lt_le_incl.\n  assumption.\n  apply le_gt_cases.\nQed.\n\nLemma div_nonzero : forall a b, a ~= 0 -> b ~= 0 -> a mod b == 0 -> a/b ~= 0.\nProof.\n  intros.\n  cut (a == b*(a/b)).\n  intros.\n  rewrite <- mul_cancel_l with (p := b).\n  rewrite <- H2.\n  rewrite mul_0_r.\n  assumption.\n  assumption.\n  apply div_exact.\n  assumption.\n  assumption.\nQed.\n\n(********* PROOFS OF REWRITE RULES ***********)\n\n(********* Z3 RETURNS UNKNOWN **********)\n\n(********* SIMPLIFY_ADD ************)\n\n(* ;; Before: (((_0 + c0) / c1) + c2) After : ((_0 + fold((c0 + (c1 * c2)))) / c1);; Pred  : 1 *)\n(* rewrite((x + c0)/c1 + c2, (x + fold(c0 + c1*c2))/c1) *)\nLemma addline109 : forall x c0 c1 c2, c1 ~= 0 -> (x + c0) / c1 + c2 == (x + (c0 + c1 * c2)) / c1.\nProof.\n  intros.\n  rewrite <- div_add with (a := (x + c0)).\n  rewrite add_assoc.\n  rewrite mul_comm.\n  reflexivity.\n  assumption.\nQed.\n\n(* ;; Before: ((_0 + ((_1 + c0) / c1)) + c2) After : (_0 + ((_1 + fold((c0 + (c1 * c2)))) / c1));; Pred  : 1 *)\n(* rewrite((x + (y + c0)/c1) + c2, x + (y + fold(c0 + c1*c2))/c1) *)\nLemma addline110 : forall x y c0 c1 c2, c1 ~= 0 -> x + (y + c0) / c1 + c2 == x + (y + (c0 + c1 * c2)) / c1.\nProof.\n  intros.\n  rewrite <- add_assoc.\n  rewrite addline109.\n  reflexivity.\n  assumption.\nQed.\n\n(* ;; Before: ((((_1 + c0) / c1) + _0) + c2) After : (_0 + ((_1 + fold((c0 + (c1 * c2)))) / c1));; Pred  : 1 *)\n(* rewrite(((y + c0)/c1 + x) + c2, x + (y + fold(c0 + c1*c2))/c1) *)\nLemma addline111 : forall x y c0 c1 c2, c1 ~= 0 -> (y + c0) / c1 + x + c2 == x + (y + c0 + c1 * c2) / c1.\nProof.\n  intros.\n  rewrite add_comm with (m := x).\n  rewrite <- add_assoc with (n := y).\n  apply addline110.\n  assumption.\nQed.\n\n(* ;; Before: (((c0 - _0) / c1) + c2) After : ((fold((c0 + (c1 * c2))) - _0) / c1);; Pred  : ((c0 != 0) && (c1 != 0)) *)\n(* rewrite((c0 - x)/c1 + c2, (fold(c0 + c1*c2) - x)/c1, c0 != 0 && c1 != 0) *)\nLemma addline112 : forall x c0 c1 c2, c0 ~= 0 -> c1 ~= 0 -> (c0 - x) / c1 + c2 == ((c0 + c1 * c2) - x) / c1.\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite addline109.\n  rewrite add_comm with (n := - x).\n  rewrite add_assoc.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\nQed.\n\n(* ;; Before: (_0 + ((_0 + _1) / c0)) After : (((fold((c0 + 1)) * _0) + _1) / c0);; Pred  : 1 *)\n(* rewrite(x + (x + y)/c0, (fold(c0 + 1)*x + y)/c0) *)\nLemma addline113 : forall x y c0, c0 ~= 0 -> x + (x + y) / c0 == ((c0 + 1) * x + y) / c0.\nProof.\n  intros.\n  rewrite <- div_add_l with (a := x) (b := c0).\n  rewrite add_assoc.\n  rewrite <- mul_1_r with (n := x) at 2.\n  rewrite mul_comm.\n  rewrite mul_comm with (n := x) (m := 1).\n  rewrite <- mul_add_distr_r.\n  reflexivity.\n  assumption.\nQed.\n\n(* ;; Before: (_0 + ((_1 + _0) / c0)) After : (((fold((c0 + 1)) * _0) + _1) / c0);; Pred  : 1 *)\n(* rewrite(x + (y + x)/c0, (fold(c0 + 1)*x + y)/c0) *)\nLemma addline114 : forall x y c0, c0 ~= 0 -> x + (y + x) / c0 == ((c0 + 1) * x + y) / c0.\nProof.\n  intros.\n  rewrite add_comm with (n := y) (m := x).\n  apply addline113.\n  assumption.\nQed.\n\n(* ;; Before: (_0 + ((_1 - _0) / c0)) After : (((fold((c0 - 1)) * _0) + _1) / c0);; Pred  : 1 *)\n(* rewrite(x + (y - x)/c0, (fold(c0 - 1)*x + y)/c0) *)\nLemma addline115 : forall x y c0, c0 ~= 0 -> x + (y - x) / c0 == ((c0 - 1) * x + y) / c0.\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite <- div_add_l with (a := x) (b := c0).\n  rewrite add_comm with (n := y) (m := -x).\n  rewrite <- mul_1_r with (n := -x).\n  rewrite mul_opp_comm.\n  rewrite mul_comm.\n  rewrite mul_comm with (n := x) (m := -1).\n  rewrite add_assoc.\n  rewrite <- mul_add_distr_r.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\nQed.\n\n(* ;; Before: (_0 + ((_0 - _1) / c0)) After : (((fold((c0 + 1)) * _0) - _1) / c0);; Pred  : 1 *)\n(* rewrite(x + (x - y)/c0, (fold(c0 + 1)*x - y)/c0) *)\nLemma addline116 : forall x y c0, c0 ~= 0 -> x + (x - y) / c0 == ((c0 + 1) * x - y)/c0.\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite addline113.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 - _1) / c0) + _0) After : (((fold((c0 + 1)) * _0) - _1) / c0);; Pred  : 1 *)\n(* rewrite((x - y)/c0 + x, (fold(c0 + 1)*x - y)/c0) *)\nLemma addline117 : forall x y c0, c0 ~= 0 -> (x - y) / c0 + x == ((c0 + 1)*x - y) / c0.\nProof.\n  intros.\n  rewrite add_comm.\n  apply addline116.\n  assumption.\nQed.\n\n(* ;; Before: (((_1 - _0) / c0) + _0) After : ((_1 + (fold((c0 - 1)) * _0)) / c0);; Pred  : 1 *)\n(* rewrite((y - x)/c0 + x, (y + fold(c0 - 1)*x)/c0) *)\nLemma addline118 : forall x y c0, c0 ~= 0 -> (y - x) / c0 + x == (y + (c0 - 1) * x) / c0.\nProof.\n  intros.\n  rewrite add_comm.\n  rewrite addline115.\n  rewrite add_comm.\n  reflexivity.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 + _1) / c0) + _0) After : (((fold((c0 + 1)) * _0) + _1) / c0);; Pred  : 1 *)\n(* rewrite((x + y)/c0 + x, (fold(c0 + 1)*x + y)/c0) *)\nLemma addline119 : forall x y c0, c0 ~= 0 -> (x + y) / c0 + x == ((c0 + 1) * x + y) / c0.\nProof.\n  intros.\n  rewrite add_comm.\n  apply addline113.\n  assumption.\nQed.\n\n(* ;; Before: (((_1 + _0) / c0) + _0) After : ((_1 + (fold((c0 + 1)) * _0)) / c0);; Pred  : 1 *)\n(* rewrite((y + x)/c0 + x, (y + fold(c0 + 1)*x)/c0) *)\nLemma addline120 : forall x y c0, c0 ~= 0 -> (y + x) / c0 + x == (y + (c0 + 1) * x) / c0.\nProof.\n  intros.\n  rewrite add_comm.\n  rewrite addline114.\n  rewrite add_comm.\n  reflexivity.\n  assumption.\nQed.\n\n(********* SIMPLIFY_DIV ************)\n\n(* rewrite((x / c0 + c1) / c2, (x + fold(c1 * c0)) / fold(c0 * c2),   c0 > 0 && c2 > 0 && !overflows(c0 * c2) && !overflows(c0 * c1)) *)\nLemma divline119 : forall x c0 c1 c2, c0 > 0 -> c2 > 0 -> ((x / c0) + c1) / c2 == (x + (c1 * c0)) / (c0 * c2).\nProof.\n  intros x c0 c1 c2 H0 H1.\n  rewrite <- div_add.\n  rewrite div_div.\n  reflexivity.\n  assumption.\n  apply neq_sym.\n  apply lt_neq.\n  assumption.\n  apply neq_sym.\n  apply lt_neq.\n  assumption.\nQed.\n\n(* rewrite((x * c0) / c1, x / fold(c1 / c0),                          c1 % c0 == 0 && c0 > 0 && c1 / c0 != 0) *)\nLemma divline120 : forall x c0 c1, c0 > 0 -> c1/c0 ~= 0 -> c1 mod c0 == 0 -> (x*c0)/c1 == x/(c1/c0).\nProof.\n  intros x c0 c1 H0 H1.\n  rewrite <- div_exact with (a := c1) (b := c0).\n  intros.\n  rewrite H at 1.\n  rewrite mul_comm.\n  rewrite div_mul_cancel_l.\n  reflexivity.\n  assumption.\n  assumption.\n  cut (0 ~= c0).\n  cut (0 < c0).\n  intros.\n  apply neq_sym.\n  assumption.\n  assumption.\n  apply lt_neq.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 * c0) + _1) / c1) After : ((_1 / c1) + (_0 * fold((c0 / c1))));; Pred  : (((c0 % c1) == 0) && (c1 > 0)) *)\n(* rewrite((x * c0 + y) / c1, y / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline124 : forall x y c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (x * c0 + y)/c1 == y/c1 + x*(c0/c1).\nProof.\n  intros x y c0 c1 H.\n  rewrite add_comm at 1.\n  rewrite <- div_exact with (b := c1).\n  intro H0.\n  rewrite H0 at 1.\n  rewrite mul_assoc.\n  rewrite mul_comm at 1.\n  rewrite mul_assoc.\n  rewrite div_add.\n  rewrite mul_comm at 1.\n  reflexivity.\n  apply neq_sym.\n  apply lt_neq.\n  assumption.\n  apply neq_sym.\n  apply lt_neq.\n  assumption.\nQed.\n\n(* rewrite((x * c0 - y) / c1, (-y) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline125 : forall x y c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (x * c0 - y)/c1 == (-y)/c1 + x * (c0/c1).\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  apply divline124.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: ((_1 + (_0 * c0)) / c1) After : ((_1 / c1) + (_0 * fold((c0 / c1))));; Pred  : (((c0 % c1) == 0) && (c1 > 0)) *)\n(* rewrite((y + x * c0) / c1, y / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline126 : forall x y c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (y + x * c0)/c1 == y/c1 + x*(c0/c1).\nProof.\n  intros.\n  rewrite add_comm at 1.\n  apply divline124.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: ((_1 - (_0 * c0)) / c1) After : ((_1 / c1) - (_0 * fold((c0 / c1))));; Pred  : (((c0 % c1) == 0) && (c1 > 0)) *)\n(* rewrite((y - x * c0) / c1, y / c1 - x * fold(c0 / c1),             c0 % c1 == 0 && c1 > 0) *)\nLemma divline127 : forall x y c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (y - x*c0)/c1 == y/c1 - x*(c0/c1).\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite <- mul_opp_l.\n  rewrite divline126.\n  rewrite mul_opp_l.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite(((x * c0 + y) + z) / c1, (y + z) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline129 : forall x y z c0 c1, c1 > 0 -> c0 mod c1 == 0 -> ((x * c0 + y) + z)/c1 == (y + z)/c1 + x*(c0/c1).\nProof.\n  intros.\n  rewrite <- add_assoc.\n  apply divline124.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite(((x * c0 - y) + z) / c1, (z - y) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline130 : forall x y z c0 c1, c1 > 0 -> c0 mod c1 == 0 -> ((x*c0 - y) + z)/c1 == (z - y)/c1 + x*(c0/c1).\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite <- add_assoc.\n  rewrite add_comm with (m := z).\n  rewrite add_opp_r.\n  apply divline124.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite(((x * c0 + y) - z) / c1, (y - z) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline131 : forall x y z c0 c1, c1 > 0 -> c0 mod c1 == 0 -> ((x*c0 + y) - z)/c1 == (y - z)/c1 + x*(c0/c1).\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite divline129.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite(((x * c0 - y) - z) / c1, (-y - z) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline132 : forall x y z c0 c1, c1 > 0 -> c0 mod c1 == 0 -> ((x*c0 - y) -z)/c1 == (-y -z)/c1 + x*(c0/c1).\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite <- add_opp_r.\n  rewrite divline129.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite(((y + x * c0) + z) / c1, (y + z) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline134 : forall x y z c0 c1, c1 >0 -> c0 mod c1 == 0 -> ((y + x * c0) + z)/c1 == (y + z)/c1 + x*(c0/c1).\nProof.\n  intros.\n  rewrite add_comm with (n := y).\n  rewrite <- add_assoc.\n  apply divline124.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite(((y + x * c0) - z) / c1, (y - z) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline135 : forall x y z c0 c1, c1 > 0 -> c0 mod c1 == 0 -> ((y + x * c0) - z)/c1 == (y - z)/c1 + x * (c0/c1).\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite divline134.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite(((y - x * c0) - z) / c1, (y - z) / c1 - x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline136 : forall x y z c0 c1, c1 > 0 -> c0 mod c1 == 0 -> ((y - x * c0) - z)/c1 == (y - z)/c1 - x*(c0/c1).\nProof.\n  intros.\n  rewrite <- add_opp_r with (n := y).\n  rewrite <- mul_opp_l.\n  rewrite divline135.\n  rewrite mul_opp_l.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite(((y - x * c0) + z) / c1, (y + z) / c1 - x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline137 : forall x y z c0 c1, c1 > 0 -> c0 mod c1 == 0 -> ((y - x*c0) + z)/c1 == (y+z)/c1 - x*(c0/c1).\nProof.\n  intros.\n  rewrite <- add_opp_r at 1.\n  rewrite <- mul_opp_l.\n  rewrite divline134.\n  rewrite mul_opp_l.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite((z + (x * c0 + y)) / c1, (z + y) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline139 : forall x y z c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (z + (x*c0 + y))/c1 == (z + y)/c1 + x*(c0/c1).\nProof.\n  intros.\n  rewrite add_assoc.\n  apply divline134.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite((z + (x * c0 - y)) / c1, (z - y) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline140 : forall x y z c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (z + (x*c0 - y))/c1 == (z - y)/c1 + x*(c0/c1).\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite add_assoc.\n  rewrite add_opp_r.\n  apply divline135.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite((z - (x * c0 - y)) / c1, (z + y) / c1 - x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline141 : forall x y z c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (z - (x*c0 - y))/c1 == (z + y)/c1 - x*(c0/c1).\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite opp_sub_distr.\n  rewrite <- mul_opp_l.\n  rewrite add_assoc.\n  rewrite mul_opp_l.\n  rewrite add_opp_r.\n  apply divline137.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite((z - (x * c0 + y)) / c1, (z - y) / c1 - x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline142 : forall x y z c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (z - (x * c0 + y))/c1 == (z - y)/c1 - x*(c0/c1).\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite opp_add_distr.\n  rewrite <- mul_opp_l.\n  rewrite divline139.\n  rewrite add_opp_r.\n  rewrite mul_opp_l.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite((z + (y + x * c0)) / c1, (z + y) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline144 : forall x y z c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (z + (y + x*c0))/c1 == (z + y)/c1 + x*(c0/c1).\nProof.\n  intros.\n  rewrite add_comm with (n := y).\n  apply divline139.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite((z - (y + x * c0)) / c1, (z - y) / c1 - x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline145 : forall x y z c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (z - (y + x * c0))/c1 == (z - y)/c1 - x*(c0/c1).\nProof.\n  intros.\n  rewrite add_comm with (n := y).\n  apply divline142.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite((z + (y - x * c0)) / c1, (z + y) / c1 - x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline146 : forall x y z c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (z + (y - x*c0))/c1 == (z + y)/c1 - x*(c0/c1).\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite <- mul_opp_l.\n  rewrite add_comm with (n := y).\n  rewrite divline139.\n  rewrite mul_opp_l.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite((z - (y - x * c0)) / c1, (z - y) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline147 : forall x y z c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (z - (y - x*c0))/c1 == (z - y)/c1 + x*(c0/c1).\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite <- add_opp_r.\n  rewrite <- mul_opp_l.\n  rewrite opp_add_distr.\n  rewrite add_comm with (n := -y).\n  rewrite <- mul_opp_l.\n  rewrite opp_involutive.\n  rewrite divline139.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite((((x * c0 + y) + z) + w) / c1, (y + z + w) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline150 : forall x y z w c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (x * c0 + y + z + w)/c1 == (y + z + w)/c1 + x*(c0/c1).\nProof.\n  intros.\n  rewrite <- add_assoc.\n  rewrite <- add_assoc.\n  rewrite add_assoc with (n := y).\n  apply divline124.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite((((y + x * c0) + z) + w) / c1, (y + z + w) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline151 : forall x y z w c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (((y + x * c0) + z) + w)/c1 == (y + z + w)/c1 + x*(c0/c1).\nProof.\n  intros.\n  rewrite add_comm with (n := y).\n  apply divline150.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite(((z + (x * c0 + y)) + w) / c1, (y + z + w) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline152 : forall x y z w c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (z + (x * c0 + y) + w)/c1 == (y + z + w)/c1 + x *(c0/c1).\nProof.\n  intros.\n  rewrite add_comm with (n := z).\n  apply divline150.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite(((z + (y + x * c0)) + w) / c1, (y + z + w) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline153 : forall x y z w c0 c1, c1 > 0 -> c0 mod c1 == 0 -> ((z + (y + x * c0)) + w) / c1 == (y + z + w) / c1 + x * (c0 / c1).\nProof.\n  intros.\n  rewrite add_comm with (n := y).\n  apply divline152.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite(((z + (y + x * c0)) + w) / c1, (y + z + w) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline154 : forall x y z w c0 c1, c1 > 0 -> c0 mod c1 == 0 -> ((z + (y + x * c0)) + w) / c1 == (y + z + w) / c1 + x * (c0 / c1).\nProof.\n  intros.\n  rewrite add_comm with (n := y).\n  rewrite add_comm with (n := z).\n  apply divline150.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite((w + ((y + x * c0) + z)) / c1, (y + z + w) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline155 : forall x y z w c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (w + ((y + x * c0) + z)) / c1 == (y + z + w) / c1 + x * (c0 / c1).\nProof.\n  intros.\n  rewrite add_comm.\n  rewrite add_comm with (n := y).\n  apply divline150.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite((w + (z + (x * c0 + y))) / c1, (y + z + w) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline156 : forall x y z w c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (w + (z + (x * c0 + y))) / c1 == (y + z + w) / c1 + x * (c0 / c1).\nProof.\n  intros.\n  rewrite add_comm with (n := z).\n  rewrite add_comm.\n  apply divline150.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite((w + (z + (y + x * c0))) / c1, (y + z + w) / c1 + x * fold(c0 / c1), c0 % c1 == 0 && c1 > 0) *)\nLemma divline157 : forall x y z w c0 c1, c1 > 0 -> c0 mod c1 == 0 -> (w + (z + (y + x * c0))) / c1 == (y + z + w) / c1 + x * (c0 / c1).\nProof.\n  intros.\n  rewrite add_comm with (n := y).\n  rewrite add_comm with (n := z).\n  rewrite add_comm with (n := w).\n  apply divline150.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite((x + c0) / c1, x / c1 + fold(c0 / c1), c0 % c1 == 0) *)\nLemma divline159 : forall x c0 c1, c1 ~= 0 -> c0 mod c1 == 0 -> (x + c0)/c1 == x/c1 + c0/c1.\nProof.\n  intros x c0 c1 H.\n  rewrite <- div_exact with (b := c1).\n  intro H0.\n  rewrite H0 at 1.\n  rewrite mul_comm at 1.\n  rewrite div_add.\n  reflexivity.\n  assumption.\n  assumption.\nQed.\n\n(* rewrite((x + y)/x, y/x + 1) *)\nLemma divline160 : forall x y, x ~= 0 -> (x + y)/x == (y/x + 1).\nProof.\n  intros.\n  rewrite <- mul_1_l with (n := x) at 1.\n  rewrite div_add_l.\n  rewrite add_comm at 1.\n  reflexivity.\n  assumption.\nQed.\n\n(* rewrite((y + x)/x, y/x + 1) *)\nLemma divline1161 : forall x y, x ~=  0 -> (y + x)/x == (y/x + 1).\nProof.\n  intros.\n  rewrite add_comm at 1.\n  apply divline160.\n  assumption.\nQed.\n\n(* rewrite((x - y)/x, (-y)/x + 1) *)\nLemma divline162 : forall x y, x ~= 0 -> (x - y)/x == ((-y)/x + 1).\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  apply divline160.\n  assumption.\nQed.\n\n(* rewrite((y - x)/x, y/x - 1) *)\nLemma divline163 : forall x y, x ~= 0 -> (y - x)/x == y/x - 1.\nProof.\n  intros.\n  rewrite <- mul_1_l with (n := x) at 1.\n  rewrite <- add_opp_r.\n  rewrite <- mul_opp_l.\n  rewrite div_add.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\nQed.\n\n(* rewrite(((x + y) + z)/x, (y + z)/x + 1) *)\nLemma divline164 : forall x y z, x ~= 0 -> (x + y + z)/x == (y + z)/x + 1.\nProof.\n  intros.\n  rewrite <- mul_1_l with (n := x) at 1.\n  rewrite <- add_assoc.\n  rewrite div_add_l.\n  rewrite add_comm at 1.\n  reflexivity.\n  assumption.\nQed.\n\n(* rewrite(((y + x) + z)/x, (y + z)/x + 1) *)\nLemma divline165 : forall x y z, x ~= 0 -> ((y + x) + z)/x == (y + z)/x + 1.\nProof.\n  intros.\n  rewrite <- add_assoc.\n  rewrite add_comm with (n := x).\n  rewrite add_assoc.\n  rewrite <- mul_1_l with (n := x) at 1.\n  rewrite div_add.\n  reflexivity.\n  assumption.\nQed.\n\n(* rewrite((z + (y + x))/x, (z + y)/x + 1) *)\nLemma divline167 : forall x y z, x ~= 0 -> (z + (y + x))/ x == (z + y)/x + 1.\nProof.\n  intros.\n  rewrite add_comm.\n  rewrite add_comm with (n := z).\n  apply divline165.\n  assumption.\nQed.\n\n(* rewrite((x*y + z)/x, y + z/x) *)\nLemma divline170 : forall x y z, x ~= 0 -> (x * y + z)/x == (y + z/x).\nProof.\n  intros.\n  rewrite mul_comm at 1.\n  rewrite div_add_l.\n  reflexivity.\n  assumption.\nQed.\n\n(* rewrite((y*x + z)/x, y + z/x) *)\nLemma divline171 : forall x y z, x ~= 0 -> (y * x + z)/x == (y + z/x).\nProof.\n  intros.\n  rewrite mul_comm at 1.\n  apply divline170.\n  assumption.\nQed.\n\n(* ;; Before: ((_2 + (_0 * _1)) / _0) After : ((_2 / _0) + _1);; Pred  : 1 *)\n(* rewrite((z + x*y)/x, z/x + y) *)\nLemma divline172 : forall x y z, x ~= 0 -> (z + x * y)/x == z/x + y.\nProof.\n  intros.\n  rewrite add_comm at 1.\n  rewrite divline170.\n  rewrite add_comm at 1.\n  reflexivity.\n  assumption.\nQed.\n\n(* ;; Before: ((_2 + (_1 * _0)) / _0) After : ((_2 / _0) + _1);; Pred  : 1 *)\n(* rewrite((z + y*x)/x, z/x + y) *)\nLemma divline173 : forall x y z, x ~= 0 -> (z + y*x)/x == z/x + y.\nProof.\n  intros.\n  rewrite mul_comm.\n  apply divline172.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 * _1) - _2) / _0) After : (_1 + (-_2 / _0));; Pred  : 1 *)\n(* rewrite((x*y - z)/x, y + (-z)/x) *)\nLemma divline174 : forall x y z, x ~= 0 -> (x*y - z)/x == (y + (-z)/x).\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite mul_comm.\n  rewrite div_add_l.\n  reflexivity.\n  assumption.\nQed.\n\n(* rewrite((y*x - z)/x, y + (-z)/x) *)\nLemma divline175 : forall x y z, x ~= 0 -> (y*x - z)/x == y + (-z)/x.\nProof.\n  intros.\n  rewrite mul_comm.\n  apply divline174.\n  assumption.\nQed.\n\n(* ;; Before: ((_2 - (_0 * _1)) / _0) After : ((_2 / _0) - _1);; Pred  : 1 *)\n(* rewrite((z - x*y)/x, z/x - y) *)\nLemma divline176 : forall x y z, x ~= 0 -> (z - x*y)/x == z/x - y.\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite <- mul_opp_r.\n  rewrite mul_comm.\n  rewrite div_add.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\nQed.\n\n(* rewrite((z - y*x)/x, z/x - y) *)\nLemma divline177 : forall x y z, x ~= 0 -> (z - y*x)/x == (z/x - y).\nProof.\n  intros.\n  rewrite mul_comm.\n  apply divline176.\n  assumption.\nQed.\n\n\n(* ;; Before: (ramp(_0, c0) / broadcast(c1)) After : ramp((_0 / c1), fold((c0 / c1)), 1);; Pred  : ((c0 % c1) == 0) *)\n(* rewrite(ramp(x, c0) / broadcast(c1), ramp(x / c1, fold(c0 / c1), lanes), c0 % c1 == 0) *)\n(* for convenient rewrite c0 as c2*c1 *)\nLemma divline180 : forall x c2 c1 lanes, c1 ~= 0 -> c2*c1 mod c1 == 0 -> (x + c2*c1*lanes)/c1 == x/c1 + ((c2*c1)/c1)*lanes.\nProof.\n  intros.\n  rewrite mul_comm with (n := c2).\n  rewrite <- mul_assoc.\n  rewrite mul_comm.\n  rewrite div_add.\n  rewrite <- mul_1_r with (n := c1) at 4.\n  rewrite div_mul_cancel_l.\n  rewrite div_1_r.\n  reflexivity.\n  auto.\n  intuition.\n  rewrite mul_1_l.\nAdmitted.\n\n(* ;; Before: (((_0 * c0) + c1) / c2) After : ((_0 + fold((c1 / c0))) / fold((c2 / c0)));; Pred  : (((c2 > 0) && (c0 > 0)) && ((c2 % c0) == 0)) *)\n(* rewrite((x * c0 + c1) / c2, (x + fold(c1 / c0)) / fold(c2 / c0), c2 > 0 && c0 > 0 && c2 % c0 == 0) *)\nLemma divline187 : forall x c0 c1 c2, c2 > 0 -> c0 > 0 -> c2 mod c0 == 0 -> (x * c0 + c1)/c2 == (x + (c1/c0))/(c2/c0).\nProof.\n  intros.\n  cut (c2 == c0*(c2/c0)).\n  intros.\n  rewrite H2.\n  rewrite <- div_div.\n  rewrite div_add_l.\n  rewrite <- H2.\n  reflexivity.\n  apply lt_neq_ooo.\n  assumption.\n  assumption.\n  apply div_nonzero.\n  apply lt_neq_ooo.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  assumption.\n  apply div_exact.\n  apply lt_neq_ooo.\n  assumption.\n  assumption.\nQed.\n\nLemma divline187alt : forall x c0 c1 c2, c2/c0 ~= 0 -> c2 > 0 -> c0 > 0 -> c2 mod c0 == 0 -> c1 mod c0 == 0 -> \n(x * c0 + c1)/c2 == (x + (c1/c0))/(c2/c0).\nProof.\n  intros x c0 c1 c2 H0 H2 H3 H4.\n  rewrite <- div_exact with (a := c1).\n  intros H5.\n  cut (c2 mod c0 == 0).\n  rewrite <- div_exact with (a := c2).\n  intros H6.\n  rewrite H5 at 1.\n  rewrite H6 at 1.\n  rewrite mul_comm.\n  rewrite <- mul_add_distr_l.\n  rewrite div_mul_cancel_l.\n  reflexivity.\n  assumption.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\nQed.\n\nLemma divline187alt2 : forall x c0 c1 c2, c2/c0 ~= 0 -> c2 ~= 0 -> c0 > 0 -> c2 mod c0 == 0 -> c1 mod c0 == 0 ->\n(x * c0 + c1)/c2 == (x + (c1/c0))/(c2/c0).\nProof.\n  intros x c0 c1 c2 H0 H1 H2 H3.\n  rewrite <- div_exact with (a := c1).\n  intros H4.\n  cut (c2 mod c0 == 0).\n  rewrite <- div_exact with (a := c2).\n  intros H5.\n  rewrite H4 at 1.\n  rewrite H5 at 1.\n  rewrite mul_comm.\n  rewrite <- mul_add_distr_l.\n  rewrite div_mul_cancel_l.\n  reflexivity.\n  assumption.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\nQed.\n\n(* rewrite((x * c0 + c1) / c2, x * fold(c0 / c2) + fold(c1 / c2), c2 > 0 && c0 % c2 == 0) *)\nLemma divline190 : forall x c0 c1 c2, c2 > 0 -> c0 mod c2 == 0 -> (x * c0 + c1)/c2 == x*(c0/c2) + c1/c2.\nProof.\n  intros x c0 c1 c2 H.\n  rewrite <- div_exact with (b := c2).\n  intro H0.\n  rewrite H0 at 1.\n  rewrite mul_comm with (n := c2).\n  rewrite mul_assoc.\n  rewrite div_add_l.\n  reflexivity.\n  apply neq_sym.\n  apply lt_neq.\n  assumption.\n  apply neq_sym.\n  apply lt_neq.\n  assumption.\nQed.\n\n\n\n(********* SIMPLIFY_LT ************)\n\n(* ;; Before: ((_0 * c0) < c1) After : (_0 < fold((((c1 + c0) - 1) / c0)));; Pred  : (c0 > 0) *)\n(* rewrite(x * c0 < c1, x < fold((c1 + c0 - 1) / c0), c0 > 0) *)\nLemma ltline140 : forall x c0 c1, c0 > 0 -> (x * c0) < c1 -> x < (c1 + c0 - 1)/c0.\nProof.\nAdmitted.\n(* proved true in z3 *)\n(*\n  intros.\n  cut (x <= c1/c0).\n  intros.\n  cut (x < (c1 + 0)/c0).\n  intros.\n  cut ((c1 + 0)/c0 <= (c1 + c0 - 1)/c0).\n  intros.\n  apply lt_le_trans with (n := x) (m := (c1 + 0)/c0) (p := (c1 + c0 - 1)/c0).\n  assumption.\n  assumption.\n  cut (c1 + 0 <= (c1 + c0 - 1)).\n  intros.\n  apply div_le_mono.\n  assumption.\n  assumption.\n  rewrite <- add_sub_assoc.\n  cut (0 <= c0 - 1).\n  intros.\n  apply add_le_mono_l.\n  assumption.\n  rewrite lt_le_pred in H.\n  rewrite succ_le_mono in H.\n  rewrite <- one_succ in H.\n  rewrite succ_pred in H.\n  rewrite add_le_mono_r with (p := -1) in H.\n  rewrite add_opp_r in H.\n  rewrite sub_diag in H.\n  rewrite add_opp_r in H.\n  assumption.\n  rewrite add_0_r.\n  cut (x ~= c1/c0).\n  intros.\n  rewrite le_neq.\n  auto.\n  \n  assumption.\n\n  rewrite mul_lt_mono_pos_r with (p := c0) in H0.\n  apply lt_asymm in H1.\n  discriminate.\n  apply lt_le_incl in H0.\n\n  rewrite div_mul in H0.\n  rewrite div_le_mono\n\n  cut (c0 * (c1/c0) <= c1).\n  intros.\n\n\n\n  rewrite <- nlt_succ_r in H.\n  rewrite nlt_ge in H.\n  apply lt_le_incl in H0.\n  rewrite mul_comm in H0.\n  apply div_le_lower_bound in H0.\n  cut (c0 == 1 \\/ c0 > 1).\n  intros.\n  destruct H1.\n  rewrite H1 at 1.\n  rewrite <- add_sub_assoc.\n  rewrite sub_diag.\n  rewrite add_0_r.\n  unfold H.\n  cut (c1/c0 <= (c1 + c0 - 1)/c0).\n  intros.\n  apply le_trans.\n*)\n\n(* ;; Before: (c1 < (_0 * c0)) After : (fold((c1 / c0)) < _0);; Pred  : (c0 > 0) *)\n(* rewrite(c1 < x * c0, fold(c1 / c0) < x, c0 > 0) *)\nLemma ltline142 : forall x c0 c1, c0 > 0 -> c1 < (x * c0) -> (c1 / c0) < x.\nProof.\n intros x c0 c1 H.\n  rewrite mul_lt_mono_pos_l with (n := c1/c0) (m := x) (p := c0).\n  cut (c0 * (c1/c0) <= c1).\n  rewrite mul_comm with (n := x) (m := c0).\n  apply le_lt_trans.\n  apply mul_div_le.\n  apply lt_neq_ooo.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: ((_0 / c0) < c1) After : (_0 < (c1 * c0));; Pred  : (c0 > 0) *)\n(* rewrite(x / c0 < c1, x < c1 * c0, c0 > 0) *)\nLemma ltline145 : forall x c0 c1, c0 > 0 -> (x mod c0 == 0) -> (x/c0) < c1 -> x < c1*c0.\nProof.\n  intros.\n  rewrite <- le_succ_l in H1.\n  cut (c0 * S (x/c0) <= c0 * c1).\n  intros.\n  cut (x < c0 * S (x/c0)).\n  intros.\n  apply lt_le_trans with (m := c0 * S (x / c0)).\n  assumption.\n  cut (c1 * c0 == c0 * c1).\n  intros.\n  rewrite H4.\n  assumption.\n  apply mul_comm.\n  apply mul_succ_div_gt.\n  assumption.\n  apply mul_le_mono_pos_l.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: ((_0 * c0) < ((_1 * c0) + c1)) After : (_0 < (_1 + fold((((c1 + c0) - 1) / c0))));; Pred  : (c0 > 0) *)\n(* rewrite(x * c0 < y * c0 + c1, x < y + fold((c1 + c0 - 1)/c0), c0 > 0) *)\nLemma ltline226 : forall x y c0 c1, c0 > 0 -> x * c0 < y * c0 + c1 -> x < y + ((c1 + c0) - 1)/c0.\nProof.\nAdmitted.\n(* this is true but x < y + c1/c0 is a tighter bound. see c0 = 2, c1 = 1 *)\n\n\n(* ;; Before: (((_0 * c0) + c1) < (_1 * c0)) After : ((_0 + fold((c1 / c0))) < _1);; Pred  : (c0 > 0) *)\n(* rewrite(x * c0 + c1 < y * c0, x + fold(c1/c0) < y, c0 > 0) *)\nLemma ltline227 : forall x y c0 c1, c0 > 0 -> x * c0 + c1 < y * c0 -> x + c1 / c0 < y.\nProof.\n  intros x y c0 c1 H0.\n  cut (c0 * (c1/c0) <= c1).\n  rewrite add_le_mono_l with (p := x*c0).\n  intros H1 H2.\n  cut (x * c0 + c0 * (c1 / c0) < y * c0).\n  Focus 2.\n  apply le_lt_trans with (n := x*c0 + c0*(c1/c0)) (m := x*c0 + c1) (p := y * c0).\n  assumption.\n  assumption.\n  rewrite mul_comm with (n := x) (m := c0).\n  rewrite <- mul_add_distr_l.\n  rewrite mul_comm with (n := y) (m := c0).\n  rewrite <- mul_lt_mono_pos_l.\n  auto.\n  assumption.\n  apply mul_div_le.\n  apply lt_neq_ooo.\n  assumption.\nQed.\n\n\n(* ;; Before: (((_0 + c1) / c0) < ((_0 + c2) / c0)) After : 0;; Pred  : ((c0 > 0) && (c1 >= c2)) *)\n(* rewrite((x + c1)/c0 < (x + c2)/c0, false, c0 > 0 && c1 >= c2) *)\nLemma ltline289 : forall x c0 c1 c2, c0 > 0 -> c1 >= c2 -> ~((x + c1) / c0 < (x + c2) / c0).\nProof.\n  intros.\n  rewrite nlt_ge.\n  apply div_le_mono.\n  assumption.\n  apply add_le_mono_l.\n  assumption.\nQed.\n\n(* ;; Before: ((_0 / c0) < ((_0 + c2) / c0)) After : 0;; Pred  : ((c0 > 0) && (0 >= c2)) *)\n(* rewrite(x/c0 < (x + c2)/c0, false, c0 > 0 && 0 >= c2) *)\nLemma ltline292 : forall x c0 c2, c0 > 0 -> 0 >= c2 -> ~ (x/c0 < (x + c2)/c0).\nProof.\n  intros.\n  rewrite <- le_ngt.\n  rewrite <- add_0_r with (n := x) at 2.\n  cut (x + c2 <= x + 0).\n  apply div_le_mono.\n  assumption.\n  apply add_le_mono_l.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 + c1) / c0) < (_0 / c0)) After : 0;; Pred  : ((c0 > 0) && (c1 >= 0)) *)\n(* rewrite((x + c1)/c0 < x/c0, false, c0 > 0 && c1 >= 0) *)\nLemma ltline295 : forall x c0 c1, c0 > 0 -> c1 >= 0 -> ~((x + c1) / c0 < x / c0).\nProof.\n  intros.\n  rewrite <- le_ngt.\n  rewrite <- add_0_r with (n := x) at 1.\n  cut (x + 0 <= x + c1).\n  apply div_le_mono.\n  assumption.\n  apply add_le_mono_l.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 + c1) / c0) < ((_0 / c0) + c2)) After : 0;; Pred  : ((c0 > 0) && (c1 >= (c2 * c0))) *)\n(* rewrite((x + c1)/c0 < x/c0 + c2, false, c0 > 0 && c1 >= c2 * c0) *)\nLemma ltline299 : forall x c0 c1 c2, c0 > 0 -> c1 >= c2 * c0 -> ~((x + c1) / c0 < x / c0 + c2).\nProof.\n  intros.\n  rewrite <- le_ngt.\n  rewrite <- div_add.\n  apply div_le_mono.\n  assumption.\n  apply add_le_mono_l.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 + c1) / c0) < (min((_0 / c0), _1) + c2)) After : 0;; Pred  : ((c0 > 0) && (c1 >= (c2 * c0))) *)\n(* rewrite((x + c1)/c0 < (min(x/c0, y) + c2), false, c0 > 0 && c1 >= c2 * c0) *)\nLemma ltline303 : forall x y c0 c1 c2, c0 > 0 -> c1 >= (c2 * c0) -> ~((x + c1) / c0 < (min (x / c0) y) + c2).\nProof.\n  intros.\n  rewrite <- le_ngt.\n  rewrite le_add_le_sub_r.\n  rewrite min_le_iff.\n  cut (x / c0 <= (x + c1) / c0 - c2).\n  auto.\n  rewrite <- le_add_le_sub_r.\n  rewrite <- div_add.\n  apply div_le_mono.\n  assumption.\n  apply add_le_mono_l.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 + c1) / c0) < min(((_0 + c2) / c0), _1)) After : 0;; Pred  : ((c0 > 0) && (c1 >= c2)) *)\n(* rewrite((x + c1)/c0 < min((x + c2)/c0, y), false, c0 > 0 && c1 >= c2) *)\nLemma ltline305 : forall x y c0 c1 c2, c0 > 0 -> c1 >= c2 -> ~((x + c1) / c0 < (min ((x + c2) / c0) y)).\nProof.\n  intros.\n  rewrite <- le_ngt.\n  rewrite min_le_iff.\n  cut ((x + c2) / c0 <= (x + c1) / c0).\n  auto.\n  apply div_le_mono.\n  assumption.\n  apply add_le_mono_l.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 + c1) / c0) < min((_0 / c0), _1)) After : 0;; Pred  : ((c0 > 0) && (c1 >= 0)) *)\n(* rewrite((x + c1)/c0 < min(x/c0, y), false, c0 > 0 && c1 >= 0) *)\nLemma ltline307 : forall x y c0 c1, c0 > 0 -> c1 >= 0 -> ~((x + c1) / c0 < (min (x / c0) y)).\nProof.\n  intros.\n  rewrite <- le_ngt.\n  cut (x/c0 <= (x + c1)/c0).\n  intros.\n  rewrite min_le_iff.\n  auto.\n  rewrite <- add_0_r with (n := x) at 1.\n  apply div_le_mono.\n  assumption.\n  apply add_le_mono_l.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 + c1) / c0) < (min(_1, (_0 / c0)) + c2)) After : 0;; Pred  : ((c0 > 0) && (c1 >= (c2 * c0))) *)\n(* rewrite((x + c1)/c0 < (min(y, x/c0) + c2), false, c0 > 0 && c1 >= c2 * c0) *)\nLemma ltline310 : forall x y c0 c1 c2, c0 > 0 -> c1 >= c2 * c0 -> ~((x + c1) / c0 < (min y (x / c0)) + c2).\nProof.\n  intros.\n  rewrite min_comm.\n  apply ltline303.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 + c1) / c0) < min(_1, ((_0 + c2) / c0))) After : 0;; Pred  : ((c0 > 0) && (c1 >= c2)) *)\n(* rewrite((x + c1)/c0 < min(y, (x + c2)/c0), false, c0 > 0 && c1 >= c2) *)\nLemma ltline312 : forall x y c0 c1 c2, c0 > 0 -> c1 >= c2 -> ~((x + c1) / c0 < (min y ((x + c2)/c0))).\nProof.\n  intros.\n  rewrite min_comm.\n  apply ltline305.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 + c1) / c0) < min(_1, (_0 / c0))) After : 0;; Pred  : ((c0 > 0) && (c1 >= 0)) *)\n(* rewrite((x + c1)/c0 < min(y, x/c0), false, c0 > 0 && c1 >= 0) *)\nLemma ltline314 : forall x y c0 c1, c0 > 0 -> c1 >= 0 -> ~((x + c1) / c0 < (min y (x / c0))).\nProof.\n  intros.\n  rewrite min_comm.\n  apply ltline307.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: (max(((_0 + c2) / c0), _1) < ((_0 + c1) / c0)) After : 0;; Pred  : ((c0 > 0) && (c2 >= c1)) *)\n(* rewrite(max((x + c2)/c0, y) < (x + c1)/c0, false, c0 > 0 && c2 >= c1) *)\nLemma ltline317 : forall x y c0 c1 c2, c0 > 0 -> c2 >= c1 -> ~((max ((x + c2)/c0) y) < (x + c1) / c0).\nProof.\n  intros.\n  rewrite <- le_ngt.\n  rewrite max_le_iff.\n  cut ((x + c1) / c0 <= (x + c2) / c0).\n  auto.\n  apply div_le_mono.\n  assumption.\n  apply add_le_mono_l.\n  assumption.\nQed.\n\n(* ;; Before: (max((_0 / c0), _1) < ((_0 + c1) / c0)) After : 0;; Pred  : ((c0 > 0) && (0 >= c1)) *)\n(* rewrite(max(x/c0, y) < (x + c1)/c0, false, c0 > 0 && 0 >= c1) *)\nLemma ltline319 : forall x y c0 c1, c0 > 0 -> 0 >= c1 -> ~((max (x / c0) y) < (x + c1) / c0).\nProof.\n  intros.\n  rewrite <- le_ngt.\n  rewrite max_le_iff.\n  cut ((x + c1)/c0 <= x/c0).\n  auto.\n  rewrite <- add_0_r with (n := x) at 2.\n  apply div_le_mono.\n  assumption.\n  apply add_le_mono_l.\n  assumption.\nQed.\n\n(* ;; Before: (max(_1, ((_0 + c2) / c0)) < ((_0 + c1) / c0)) After : 0;; Pred  : ((c0 > 0) && (c2 >= c1)) *)\n(* rewrite(max(y, (x + c2)/c0) < (x + c1)/c0, false, c0 > 0 && c2 >= c1) *)\nLemma ltline321 : forall x y c0 c1 c2, c0 > 0 -> c2 >= c1 -> ~((max y ((x + c2)/c0)) < (x + c1) / c0).\nProof.\n  intros.\n  rewrite max_comm.\n  apply ltline317.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: (max(_1, (_0 / c0)) < ((_0 + c1) / c0)) After : 0;; Pred  : ((c0 > 0) && (0 >= c1)) *)\n(* rewrite(max(y, x/c0) < (x + c1)/c0, false, c0 > 0 && 0 >= c1) *)\nLemma ltline323 : forall x y c0 c1, c0 > 0 -> 0 >= c1 -> ~((max y (x/c0)) < (x + c1)/c0).\nProof.\n  intros.\n  rewrite max_comm.\n  apply ltline319.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: (max(((_0 + c2) / c0), _1) < ((_0 / c0) + c1)) After : 0;; Pred  : ((c0 > 0) && (c2 >= (c1 * c0))) *)\n(* rewrite(max((x + c2)/c0, y) < x/c0 + c1, false, c0 > 0 && c2 >= c1 * c0) *)\nLemma ltline327 : forall x y c0 c1 c2, c0 > 0 -> c2 >= (c1 * c0) -> ~((max ((x + c2) / c0) y) < ((x / c0) + c1)).\nProof.\n  intros.\n  rewrite <- le_ngt.\n  rewrite max_le_iff.\n  cut (x / c0 + c1 <= (x + c2) / c0).\n  auto.\n  rewrite <- div_add.\n  apply div_le_mono.\n  assumption.\n  apply add_le_mono_l.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\nQed.\n\n(* ;; Before: (max(_1, ((_0 + c2) / c0)) < ((_0 / c0) + c1)) After : 0;; Pred  : ((c0 > 0) && (c2 >= (c1 * c0))) *)\n(* rewrite(max(y, (x + c2)/c0) < x/c0 + c1, false, c0 > 0 && c2 >= c1 * c0) *)\nLemma ltline329 : forall x y c0 c1 c2, c0 > 0 -> c2 >= c1 * c0 -> ~((max y ((x + c2)/c0)) < x/c0 + c1).\nProof.\n  intros.\n  rewrite max_comm.\n  apply ltline327.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: ((_0 / c0) < min(((_0 + c2) / c0), _1)) After : 0;; Pred  : ((c0 > 0) && (c2 < 0)) *)\n(* rewrite(x/c0 < min((x + c2)/c0, y), false, c0 > 0 && c2 < 0) *)\nLemma ltline333 : forall x y c0 c2, c0 > 0 -> c2 < 0 -> ~(x/c0 < (min ((x + c2)/c0) y)).\nProof.\n  intros.\n  rewrite <- le_ngt.\n  rewrite <- add_0_r with (n := x) at 2.\n  cut ((x + c2) / c0 <= (x + 0)/c0).\n  intros.\n  rewrite min_le_iff with (n := (x+c2)/c0) (m := y) (p := (x + 0)/c0).\n  auto.\n  rewrite add_0_r.\n  rewrite le_ngt.\n  apply ltline292.\n  assumption.\n  apply lt_le_incl.\n  assumption.\nQed.\n\n(* ;; Before: ((_0 / c0) < min(_1, ((_0 + c2) / c0))) After : 0;; Pred  : ((c0 > 0) && (c2 < 0)) *)\n(* rewrite(x/c0 < min(y, (x + c2)/c0), false, c0 > 0 && c2 < 0) *)\nLemma ltline335 : forall x y c0 c2, c0 > 0 -> c2 < 0 -> ~(x/c0 < (min y ((x + c2)/c0))).\nProof.\n  intros.\n  rewrite min_comm.\n  apply ltline333.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: (max(((_0 + c2) / c0), _1) < (_0 / c0)) After : 0;; Pred  : ((c0 > 0) && (c2 >= 0)) *)\n(* rewrite(max((x + c2)/c0, y) < x/c0, false, c0 > 0 && c2 >= 0) *)\nLemma ltline337 : forall x y c0 c2, c0 > 0 -> c2 >= 0 -> ~((max ((x + c2) / c0) y) < (x / c0)).\nProof.\n  intros.\n  rewrite <- le_ngt.\n  rewrite max_le_iff.\n  cut (x/c0 <= (x + c2)/c0).\n  intros.\n  auto.\n  rewrite le_ngt.\n  apply ltline295.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: (max(_1, ((_0 + c2) / c0)) < (_0 / c0)) After : 0;; Pred  : ((c0 > 0) && (c2 >= 0)) *)\n(* rewrite(max(y, (x + c2)/c0) < x/c0, false, c0 > 0 && c2 >= 0) *)\nLemma ltline339 : forall x y c0 c2, c0 > 0 -> c2 >= 0 -> ~((max y ((x + c2)/c0)) < x/c0).\nProof.\n  intros.\n  rewrite max_comm.\n  apply ltline337.\n  assumption.\n  assumption.\nQed.\n\n(********* SIMPLIFY_MAX ************)\n\n(* ;; Before: max((_0 / c0), (_1 / c0)) After : (max(_0, _1) / c0);; Pred  : (c0 > 0) *)\n(* rewrite(max(x / c0, y / c0), max(x, y) / c0, c0 > 0) *)\nLemma maxline233 : forall x y c0, c0 > 0 -> (max (x/c0) (y/c0)) == (max x y)/c0.\nProof.\n  intros.\n  cut (y <= x \\/ x <= y).\n  intros.\n  destruct H0.\n  rewrite max_l with (x := x) (y := y).\n  cut (y/c0 <= x/c0).\n  intros.\n  rewrite max_l.\n  reflexivity.\n  assumption.\n  apply div_le_mono.\n  assumption.\n  assumption.\n  assumption.\n  rewrite max_comm with (n := x) (m := y).\n  rewrite max_l with (x := y) (y := x).\n  cut (x/c0 <= y/c0).\n  intros.\n  rewrite max_comm.\n  rewrite max_l.\n  reflexivity.\n  assumption.\n  apply div_le_mono.\n  assumption.\n  assumption.\n  assumption.\n  apply le_ge_cases.\nQed.\n\n(* ;; Before: max((_0 / c0), (_1 / c0)) After : (min(_0, _1) / c0);; Pred  : (c0 < 0) *)\n(* rewrite(max(x / c0, y / c0), min(x, y) / c0, c0 < 0) *)\nLemma maxline234 : forall x y c0, c0 < 0 -> (max (x/c0) (y/c0)) == (min x y)/c0.\nProof.\n  intros.\n  cut (x <= y \\/ y <= x).\n  intros.\n  destruct H0.\n  cut (x/c0 >= y/c0).\n  intros.\n  rewrite max_l.\n  rewrite min_l.\n  reflexivity.\n  assumption.\n  apply neg_div_antimonotone.\n  assumption.\n  assumption.\n  apply neg_div_antimonotone.\n  assumption.\n  assumption.\n  cut (y/c0 >= x/c0).\n  intros.\n  rewrite max_r.\n  rewrite min_r.\n  reflexivity.\n  assumption.\n  assumption.\n  apply neg_div_antimonotone.\n  assumption.\n  assumption.\n  apply le_ge_cases.\nQed.\n\n(* ;; Before: max((_0 / c0), ((_1 / c0) + c1)) After : (max(_0, (_1 + fold((c1 * c0)))) / c0);; Pred  : ((c0 > 0) && !(overflows((c1 * c0)))) *)\n(* rewrite(max(x / c0, y / c0 + c1), max(x, y + fold(c1 * c0)) / c0, c0 > 0 && !overflows(c1 * c0)) *)\nLemma maxline241 : forall x y c0 c1, c0 > 0 -> (max (x/c0) ((y/c0) + c1)) == ((max x (y + c1 * c0)) / c0).\nProof.\n  intros.\n  cut (y/c0 + c1 == (y + c1 * c0)/c0).\n  intros.\n  cut ((max (x / c0) (y / c0 + c1)) == (max (x/c0) ((y + c1 * c0) / c0) )).\n  intros.\n  rewrite H1.\n  apply maxline233 with (x := x) (y := (y + c1 * c0)) (c0 := c0).\n  assumption.\n  rewrite max_comm.\n  cut ((max (y / c0 + c1) (x / c0)) == (max ((y + c1 * c0)/c0) (x / c0))).\n  intros.\n  rewrite H1.\n  rewrite max_comm.\n  reflexivity.\n  apply max_proper.\n  assumption.\n  apply eq_sym.\n  apply div_add.\n  apply lt_neq_ooo.\n  assumption.\nQed.\n(* ;; Before: max((_0 / c0), ((_1 / c0) + c1)) After : (min(_0, (_1 + fold((c1 * c0)))) / c0);; Pred  : ((c0 < 0) && !(overflows((c1 * c0)))) *)\n(* rewrite(max(x / c0, y / c0 + c1), min(x, y + fold(c1 * c0)) / c0, c0 < 0 && !overflows(c1 * c0)) *)\nLemma maxline242 : forall x y c0 c1, c0 < 0 -> (max (x / c0) (y / c0 + c1)) == (min x (y + c1 * c0)) / c0.\nProof.\n  intros.\n  cut (y/c0 + c1 == (y + c1 * c0)/c0).\n  intros.\n  rewrite max_comm.\n  cut ((max (y/c0 + c1) (x/c0)) == (max ((y + c1 * c0)/c0) (x/c0))).\n  intros.\n  rewrite H1.\n  rewrite max_comm.\n  apply maxline234.\n  assumption.\n  apply max_proper.\n  assumption.\n  apply eq_sym.\n  apply div_add.\n  apply neq_sym.\n  apply lt_neq_ooo.\n  assumption.\nQed.\n\n(********* SIMPLIFY_MIN ************)\n\n(* ;; Before: min((_0 / c0), (_1 / c0)) After : (min(_0, _1) / c0);; Pred  : (c0 > 0) *)\n(* rewrite(min(x / c0, y / c0), min(x, y) / c0, c0 > 0) *)\nLemma minline236 : forall x y c0, c0 > 0 -> (min (x / c0) (y / c0)) == (min x y) / c0.\nProof.\n  intros.\n  cut (y <= x \\/ x <= y).\n  intros.\n  destruct H0.\n  cut (y/c0 <= x/c0).\n  intros.\n  rewrite min_r.\n  rewrite min_r.\n  reflexivity.\n  assumption.\n  assumption.\n  apply div_le_mono.\n  assumption.\n  assumption.\n  cut (x/c0 <= y/c0).\n  intros.\n  rewrite min_l.\n  rewrite min_l.\n  reflexivity.\n  assumption.\n  assumption.\n  apply div_le_mono.\n  assumption.\n  assumption.\n  apply le_ge_cases.\nQed.\n\n(* ;; Before: min((_0 / c0), (_1 / c0)) After : (max(_0, _1) / c0);; Pred  : (c0 < 0) *)\n(* rewrite(min(x / c0, y / c0), max(x, y) / c0, c0 < 0) *)\nLemma minline237 : forall x y c0, c0 < 0 -> (min (x / c0) (y / c0)) == (max x y) / c0.\nProof.\n  intros.\n  cut (x <= y \\/ y <= x).\n  intros.\n  destruct H0.\n  cut (x/c0 >= y/c0).\n  intros.\n  rewrite max_r.\n  rewrite min_r.\n  reflexivity.\n  assumption.\n  assumption.\n  apply neg_div_antimonotone.\n  assumption.\n  assumption.\n  cut (y/c0 >= x/c0).\n  intros.\n  rewrite max_l.\n  rewrite min_l.\n  reflexivity.\n  assumption.\n  assumption.\n  apply neg_div_antimonotone.\n  assumption.\n  assumption.\n  apply le_ge_cases.\nQed.\n\n(* ;; Before: min((_0 / c0), ((_1 / c0) + c1)) After : (min(_0, (_1 + fold((c1 * c0)))) / c0);; Pred  : ((c0 > 0) && !(overflows((c1 * c0)))) *)\n(* rewrite(min(x / c0, y / c0 + c1), min(x, y + fold(c1 * c0)) / c0, c0 > 0 && !overflows(c1 * c0)) *)\nLemma minline244 : forall x y c0 c1, c0 > 0 -> (min (x / c0) (y / c0 + c1)) == (min x (y + c1 * c0)) / c0.\nProof.\n  intros.\n  cut (y/c0 + c1 == (y + c1 * c0)/c0).\n  intros.\n  cut ((min (x/c0) (y/c0 + c1)) == (min (x/c0) ((y + c1 * c0)/c0))).\n  intros.\n  rewrite H1.\n  apply minline236.\n  assumption.\n  rewrite min_comm.\n  cut ((min (y/c0 + c1) (x/c0)) == (min ((y + c1 * c0) / c0) (x/c0))).\n  intros.\n  rewrite H1.\n  rewrite min_comm.\n  reflexivity.\n  apply min_proper.\n  assumption.\n  apply eq_sym.\n  apply div_add.\n  apply lt_neq_ooo.\n  assumption.\nQed.\n\n(* ;; Before: min((_0 / c0), ((_1 / c0) + c1)) After : (max(_0, (_1 + fold((c1 * c0)))) / c0);; Pred  : ((c0 < 0) && !(overflows((c1 * c0)))) *)\n(* rewrite(min(x / c0, y / c0 + c1), max(x, y + fold(c1 * c0)) / c0, c0 < 0 && !overflows(c1 * c0)) *)\nLemma minline245 : forall x y c0 c1, c0 < 0 -> (min (x / c0) (y / c0 + c1)) == (max x (y + c1 * c0)) / c0.\nProof.\n  intros.\n  cut (y/c0 + c1 == (y + c1 * c0)/c0).\n  intros.\n  rewrite max_comm.\n  cut ((min (x/c0) (y/c0 + c1)) == (min ((y + c1 * c0)/c0) (x/c0))).\n  intros.\n  rewrite H1.\n  rewrite max_comm.\n  rewrite min_comm.\n  apply minline237.\n  assumption.\n  rewrite min_comm.\n  apply min_proper.\n  assumption.\n  apply eq_sym.\n  apply div_add.\n  apply neq_sym.\n  apply lt_neq_ooo.\n  assumption.\nQed.\n\n\n(********* SIMPLIFY_MOD ************)\n\n(* ;; Before: ((_0 * c0) % c1) After : ((_0 * fold((c0 % c1))) % c1);; Pred  : ((c1 > 0) && ((c0 >= c1) || (c0 < 0))) *)\n(* rewrite((x * c0) % c1, (x * fold(c0 % c1)) % c1, c1 > 0 && (c0 >= c1 || c0 < 0)) *)\nLemma modline67 : forall x c0 c1, c1 > 0 -> (c0 >= c1 \\/ c0 < 0) -> (x * c0) mod c1 == (x * (c0 mod c1)) mod c1.\nProof.\n  intros.\n  rewrite <- mul_mod_idemp_r.\n  reflexivity.\n  apply lt_neq_ooo.\n  assumption.\nQed.\n(* only required predicate is c1 ~= 0 *)\n\n(* ;; Before: ((_0 + c0) % c1) After : ((_0 + fold((c0 % c1))) % c1);; Pred  : ((c1 > 0) && ((c0 >= c1) || (c0 < 0))) *)\n(* rewrite((x + c0) % c1, (x + fold(c0 % c1)) % c1, c1 > 0 && (c0 >= c1 || c0 < 0)) *)\nLemma modline68 : forall x c0 c1, c1 > 0 -> (c0 >= c1 \\/ c0 < 0) -> (x + c0) mod c1 == (x + (c0 mod c1)) mod c1.\nProof.\n  intros.\n  rewrite <- add_mod_idemp_r.\n  reflexivity.\n  apply lt_neq_ooo.\n  assumption.\nQed.\n\n(* ;; Before: ((_0 * c0) % c1) After : ((_0 % fold((c1 / c0))) * c0);; Pred  : ((c0 > 0) && ((c1 % c0) == 0)) *)\n(* rewrite((x * c0) % c1, (x % fold(c1/c0)) * c0, c0 > 0 && c1 % c0 == 0) *)\nLemma modline69 : forall x c0 c1, c0 > 0 -> c1 ~= 0 -> c1 mod c0 == 0 -> (x * c0) mod c1 == (x mod (c1/c0))*c0.\nProof.\n  intros.\n  rewrite <- mul_mod_distr_r.\n  cut (c1 == c0 * (c1/c0)).\n  intros.\n  rewrite mul_comm with (n := c1/c0).\n  rewrite <- H2.\n  reflexivity.\n  apply div_exact.\n  apply lt_neq_ooo.\n  assumption.\n  assumption.\n  rewrite <- mul_cancel_l with (p := c0).\n  cut (c1 == c0 * (c1/c0)).\n  intros.\n  rewrite <- H2.\n  rewrite mul_0_r.\n  assumption.\n  apply div_exact.\n  apply lt_neq_ooo.\n  assumption.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 * c0) + _1) % c1) After : (_1 % c1);; Pred  : ((c0 % c1) == 0) *)\n(* rewrite((x * c0 + y) % c1, y % c1, c0 % c1 == 0) *)\nLemma modline70 : forall x y c0 c1, c1 ~= 0 -> c0 mod c1 == 0 -> (x * c0 + y) mod c1 == y mod c1.\nProof.\n  intros.\n  rewrite <- add_mod_idemp_l.\n  rewrite mul_mod.\n  rewrite H0.\n  rewrite mul_0_r.\n  rewrite mod_0_l.\n  rewrite add_0_l.\n  reflexivity.\n  assumption.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: ((_1 + (_0 * c0)) % c1) After : (_1 % c1);; Pred  : ((c0 % c1) == 0) *)\n(* rewrite((y + x * c0) % c1, y % c1, c0 % c1 == 0) *)\nLemma modline71 : forall x y c0 c1, c1 ~= 0 -> c0 mod c1 == 0 -> (y + x*c0) mod c1 == y mod c1.\nProof.\n  intros.\n  rewrite add_comm.\n  apply modline70.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 * c0) - _1) % c1) After : (-_1 % c1);; Pred  : ((c0 % c1) == 0) *)\n(* rewrite((x * c0 - y) % c1, (-y) % c1, c0 % c1 == 0) *)\nLemma modline72 : forall x y c0 c1, c1 ~= 0 -> c0 mod c1 == 0 -> (x*c0 - y) mod c1 == (- y) mod c1.\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite modline70.\n  reflexivity.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: ((_1 - (_0 * c0)) % c1) After : (_1 % c1);; Pred  : ((c0 % c1) == 0) *)\n(* rewrite((y - x * c0) % c1, y % c1, c0 % c1 == 0) *)\nLemma modline73 : forall x y c0 c1, c1 ~= 0 -> c0 mod c1 == 0 -> (y - x*c0) mod c1 == y mod c1.\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite <- mul_opp_l.\n  rewrite modline71 with (x := - x).\n  reflexivity.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: (ramp(_0, c0) % broadcast(c1)) After : (broadcast(_0, 1) % c1);; Pred  : ((c0 % c1) == 0) *)\n(* rewrite(ramp(x, c0) % broadcast(c1), broadcast(x, lanes) % c1, c0 % c1 == 0) *)\nLemma modline76 : forall x c0 c1 lanes, c1 ~= 0 -> c0 mod c1 == 0 -> (x + c0 * lanes) mod c1 == x mod c1.\nProof.\n  intros.\n  rewrite mul_comm.\n  apply modline71.\n  assumption.\n  assumption.\nQed.\n\n(* ;; Before: (ramp((_0 + c0), c2) % broadcast(c1)) After : (ramp((_0 + fold((c0 % c1))), fold((c2 % c1)), 1) % c1);; Pred  : ((c1 > 0) && ((c0 >= c1) || (c0 < 0))) *)\n(* rewrite(ramp(x + c0, c2) % broadcast(c1), (ramp(x + fold(c0 % c1), fold(c2 % c1), lanes) % c1), c1 > 0 && (c0 >= c1 || c0 < 0)) *)\nLemma modline81 : forall x c0 c1 c2 lanes, c1 > 0 -> (c0 >= c1 \\/ c0 < 0) -> \n(x + c0 + c2 * lanes) mod c1 == (x + (c0 mod c1) + (c2 mod c1)*lanes) mod c1.\nProof.\n  intros.\n  rewrite <- add_mod_idemp_l.\n  rewrite <- add_mod_idemp_r.\n  rewrite <- mul_mod_idemp_l.\n  rewrite <- add_mod_idemp_r with (b := c0).\n  rewrite add_mod_idemp_r.\n  rewrite add_mod_idemp_l.\n  reflexivity.\n  apply lt_neq_ooo.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\nQed.\n(* only predicate needed is c1 ~= 0 *)\n\n(* ;; Before: (ramp(((_0 * c0) + _1), c2) % broadcast(c1)) After : (ramp(_1, fold((c2 % c1)), 1) % c1);; Pred  : ((c0 % c1) == 0) *)\n(* rewrite(ramp(x * c0 + y, c2) % broadcast(c1), ramp(y, fold(c2 % c1), lanes) % c1, c0 % c1 == 0) *)\nLemma modline82 : forall x y c0 c1 c2 lanes, c1 ~= 0 -> c0 mod c1 == 0 -> (x*c0 + y + c2 * lanes) mod c1 == (y + (c2 mod c1)*lanes) mod c1.\nProof.\n  intros.\n  rewrite <- add_mod_idemp_l.\n  rewrite modline70.\n  rewrite <- add_mod_idemp_r.\n  rewrite <- mul_mod_idemp_l.\n  rewrite add_mod_idemp_l.\n  rewrite add_mod_idemp_r.\n  reflexivity.\n  assumption.\n  assumption.\n  assumption.\n  assumption.\n  assumption.\n  assumption.\n  assumption.\nQed.\n\n\n(* ;; Before: (ramp((_1 + (_0 * c0)), c2) % broadcast(c1)) After : (ramp(_1, fold((c2 % c1)), 1) % c1);; Pred  : ((c0 % c1) == 0) *)\n(* rewrite(ramp(y + x * c0, c2) % broadcast(c1), ramp(y, fold(c2 % c1), lanes) % c1, c0 % c1 == 0) *)\nLemma modline83 : forall x y c0 c1 c2 lanes, c1 ~= 0 -> c0 mod c1 == 0 -> (y + x*c0 + c2*lanes) mod c1 == (y + (c2 mod c1)*lanes) mod c1.\nProof.\n  intros.\n  rewrite add_comm with (n := y).\n  apply modline82.\n  assumption.\n  assumption.\nQed.\n\n\n\n(********* SIMPLIFY_SUB ************)\n\n(* ;; Before: (c0 - ((c1 - _0) / c2)) After : ((fold(((((c0 * c2) - c1) + c2) - 1)) + _0) / c2);; Pred  : (c2 > 0) *)\n(* rewrite(c0 - (c1 - x)/c2, (fold(c0*c2 - c1 + c2 - 1) + x)/c2, c2 > 0) *)\nLemma subline250 : forall x c0 c1 c2, c2 > 0 -> c0 - (c1 - x)/c2 == (c0*c2 - c1 + c2 - 1 + x)/c2.\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite <- div_opp_r.\n  rewrite <- add_opp_r with (n := c1).\n  rewrite add_comm with (n := c1) (m := - x).\n  rewrite <- opp_sub_distr.\nAdmitted.\n\n\n(* ;; Before: (c0 - ((_0 + c1) / c2)) After : ((fold(((((c0 * c2) - c1) + c2) - 1)) - _0) / c2);; Pred  : (c2 > 0) *)\n(* rewrite(c0 - (x + c1)/c2, (fold(c0*c2 - c1 + c2 - 1) - x)/c2, c2 > 0) *)\nLemma subline251 : forall x c0 c1 c2, c0 - (x + c1)/c2 == (c0*c2 - c1 + c2 - 1 - x)/c2.\nProof.\nAdmitted.\n\n(* ;; Before: (_0 - ((_0 + _1) / c0)) After : ((((_0 * fold((c0 - 1))) - _1) + fold((c0 - 1))) / c0);; Pred  : (c0 > 0) *)\n(* rewrite(x - (x + y)/c0, (x*fold(c0 - 1) - y + fold(c0 - 1))/c0, c0 > 0) *)\nLemma subline252 : forall x y c0, c0 > 0 -> x - (x + y)/c0 == (x*(c0 - 1) - y + (c0 - 1))/c0.\nProof.\nAdmitted.\n\n(* ;; Before: (_0 - ((_0 - _1) / c0)) After : ((((_0 * fold((c0 - 1))) + _1) + fold((c0 - 1))) / c0);; Pred  : (c0 > 0) *)\n(* rewrite(x - (x - y)/c0, (x*fold(c0 - 1) + y + fold(c0 - 1))/c0, c0 > 0) *)\nLemma subline253 : forall x y c0, c0 > 0 -> x - (x - y)/c0 == (x*(c0 - 1) + y + (c0 - 1))/c0.\nProof.\nAdmitted.\n\n(* ;; Before: (_0 - ((_1 + _0) / c0)) After : ((((_0 * fold((c0 - 1))) - _1) + fold((c0 - 1))) / c0);; Pred  : (c0 > 0) *)\n(* rewrite(x - (y + x)/c0, (x*fold(c0 - 1) - y + fold(c0 - 1))/c0, c0 > 0) *)\nLemma subline254 : forall x y c0, c0 > 0 -> x - (y + x)/c0 == (x*(c0 - 1) - y + (c0 - 1))/c0.\nProof.\nAdmitted.\n\n(* ;; Before: (_0 - ((_1 - _0) / c0)) After : ((((_0 * fold((c0 + 1))) - _1) + fold((c0 - 1))) / c0);; Pred  : (c0 > 0) *)\n(* rewrite(x - (y - x)/c0, (x*fold(c0 + 1) - y + fold(c0 - 1))/c0, c0 > 0) *)\nLemma subline255 : forall x y c0, c0 > 0 -> x - (y - x)/c0 == ((x * (c0 - 1) + y) + (c0 - 1))/c0.\nProof.\nAdmitted.\n\n(* ;; Before: (((_0 + _1) / c0) - _0) After : (((_0 * fold((1 - c0))) + _1) / c0);; Pred  : 1 *)\n(* rewrite((x + y)/c0 - x, (x*fold(1 - c0) + y)/c0) *)\nLemma subline256 : forall x y c0, c0 ~= 0 -> (x + y)/c0 - x == (x*(1 - c0) + y)/c0.\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite <- div_add with (b := (- x)).\n  rewrite <- add_assoc.\n  rewrite add_comm with (n := y).\n  rewrite add_assoc.\n  rewrite <- mul_1_r with (n := x) at 1.\n  rewrite mul_opp_comm.\n  rewrite <- mul_add_distr_l.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\nQed.\n\n(* ;; Before: (((_1 + _0) / c0) - _0) After : ((_1 + (_0 * fold((1 - c0)))) / c0);; Pred  : 1 *)\n(* rewrite((y + x)/c0 - x, (y + x*fold(1 - c0))/c0) *)\nLemma subline257 : forall x y c0, c0 ~= 0 -> (y + x)/c0 - x == (y + x*(1 - c0))/c0.\nProof.\n  intros.\n  rewrite add_comm.\n  rewrite add_comm with (m := (x * (1 - c0))).\n  apply subline256.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 - _1) / c0) - _0) After : (((_0 * fold((1 - c0))) - _1) / c0);; Pred  : 1 *)\n(* rewrite((x - y)/c0 - x, (x*fold(1 - c0) - y)/c0) *)\nLemma subline258 : forall x y c0, c0 ~= 0 ->(x - y)/c0 - x == (x*(1 - c0) - y)/c0.\nProof.\n  intros.\n  rewrite <- add_opp_r with (n := x) (m := y).\n  rewrite <- add_opp_r with (n := (x * (1 - c0))).\n  apply subline256.\n  assumption.\nQed.\n\n(* ;; Before: (((_1 - _0) / c0) - _0) After : ((_1 - (_0 * fold((1 + c0)))) / c0);; Pred  : 1 *)\n(* rewrite((y - x)/c0 - x, (y - x*fold(1 + c0))/c0) *)\nLemma subline259 : forall x y c0, c0 ~= 0 -> (y - x)/c0 - x == (y - x*(1 + c0))/c0.\nProof.\n  intros.\n  rewrite <- add_opp_r with (n := y) (m := x).\n  rewrite <- add_opp_r with (n := (y + - x) / c0).\n  rewrite addline120.\n  rewrite add_comm with (n := c0).\n  rewrite mul_comm.\n  rewrite mul_opp_l.\n  rewrite add_opp_r.\n  reflexivity.\n  assumption.\nQed.\n\nLemma lt_div_small : forall a b, 0 < a < b -> a/b == 0.\nProof.\n  intros.\n  cut (0 <= a < b).\n  intros.\n  apply div_small.\n  assumption.\n  destruct H.\n  apply lt_le_incl in H.\n  auto.\nQed.\n\n(* ;; Before: ((((_0 + c0) / c1) * c1) - _0) After : (-_0 % c1);; Pred  : ((c1 > 0) && ((c0 + 1) == c1)) *)\n(* rewrite(((x + c0)/c1)*c1 - x, (-x) % c1, c1 > 0 && c0 + 1 == c1) *)\nLemma subline263 : forall x c0 c1 q r, 0<=r<abs c1 -> x == (c1 * q) + r -> c1 > 0 -> c0 + 1 == c1 -> ((x + c0)/c1) * c1 - x == (- x) mod c1.\nProof.\n  intros.\n  cut (x mod c1 == 0 \\/ x mod c1 ~= 0).\n  intros.\n  destruct H3.\n  rewrite mod_opp_l_z.\n  rewrite add_move_r in H2.\n  rewrite H2.\n  rewrite H0.\n  cut (r == (x mod c1)).\n  intros.\n  rewrite H4.\n  rewrite H3.\n  rewrite add_0_r.\n  rewrite mul_comm with (n := c1) (m := q).\n  rewrite div_add_l.\n  cut ((c1 - 1)/c1 == 0).\n  intros.\n  rewrite H5.\n  rewrite add_0_r.\n  rewrite sub_diag.\n  reflexivity.\n  cut (0 <= c1 - 1).\n  cut (c1 - 1 < c1).\n  intros.\n  rewrite div_small.\n  reflexivity.\n  auto.\n  rewrite sub_1_r.\n  apply lt_pred_l.\n  rewrite sub_1_r.\n  apply lt_le_pred.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  apply mod_unique in H0.\n  assumption.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  assumption.\n(* case in which x mod c1 ~= 0 *)\n  rewrite mod_opp_l_nz.\n  cut (abs c1 == c1).\n  intros.\n  rewrite H4.\n  rewrite mod_eq.\n  rewrite <- add_opp_r with (n := c1).\n  rewrite opp_sub_distr with (n := x) (m := c1 * (x/c1)).\n  rewrite add_comm with (n := -x).\n  rewrite add_assoc.\n  rewrite <- add_opp_r.\n  rewrite add_cancel_r.\n  rewrite <- mul_1_r with (n := c1) at 3.\n  rewrite <- mul_add_distr_l.\n  rewrite mul_comm.\n  rewrite mul_cancel_l.\n  apply eq_sym in H2.\n  rewrite <- sub_move_r in H2.\n  rewrite <- H2.\n  rewrite <- add_opp_r.\n  rewrite add_comm with (n := c1) (m := -1).\n  rewrite add_assoc.\n  rewrite <- mul_1_l with (n := c1) at 1.\n  rewrite div_add.\n  rewrite add_comm.\n  rewrite add_cancel_l.\n  rewrite H0.\n  rewrite <- add_assoc.\n  rewrite mul_comm.\n  rewrite div_add_l.\n  rewrite div_add_l.\n  rewrite add_cancel_l.\n  cut (r < c1).\n  intros.\n  rewrite div_small.\n  rewrite lt_div_small.\n  reflexivity.\n  apply mod_unique in H0.\n  rewrite <- H0 in H3.\n  destruct H.\n  cut (0 < r).\n  intros.\n  auto.\n  apply le_neq.\n  apply neq_sym in H3.\n  auto.\n  assumption.\n  destruct H.\n  apply mod_unique in H0.\n  rewrite <- H0 in H3.\n  cut (0 < r).\n  intros.\n  auto.\n  rewrite lt_le_pred in H7.\n  cut (P r == r + -1).\n  intros.\n  rewrite H8 in H7.\n  cut (P r < c1).\n  intros.\n  rewrite H8 in H9.\n  auto.\n  apply lt_lt_pred.\n  assumption.\n  apply succ_inj_wd.\n  rewrite succ_pred.\n  rewrite <- add_succ_r.\n  rewrite succ_m1.\n  rewrite add_0_r.\n  reflexivity.\n  apply le_neq.\n  Search \"neq\".\n  cut (0 ~= r).\n  intros.\n  auto.\n  apply neq_sym.\n  assumption.\n  auto.\n  apply lt_le_incl in H1.\n  rewrite <- abs_eq with (n := c1).\n  destruct H.\n  assumption.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  apply lt_le_incl in H1.\n  apply abs_eq.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  assumption.\n  auto.\n  apply eq_decidable.\nQed.\n\n(* ;; Before (((_0 + _1) / c0) - ((_0 + c1) / c0)) After : ((((_0 + fold((c1 % c0))) % c0) + (_1 - c1)) / c0);; Pred  : (c0 > 0) *)\n(* rewrite((x + y)/c0 - (x + c1)/c0, (((x + fold(c1 % c0)) % c0) + (y - c1))/c0, c0 > 0) *)\nLemma subline273 : forall x y c0 c1, c0 > 0 -> (x + y)/c0 - (x + c1)/c0 == (((x + (c1 mod c0)) mod c0) + y - c1)/c0.\nProof.\n  intros.\n  rewrite mod_eq with (a := c1) (b := c0).\n  rewrite mod_eq.\n  rewrite add_sub_assoc with (n := x) (m := c1) (p := c0 * (c1/c0)).\n  rewrite <- add_opp_r with (m := c1).\n  rewrite <- add_opp_r with (m := c0 * ((x + c1 - c0 * (c1 / c0)) / c0)).\n  rewrite <- add_assoc.\n  rewrite add_shuffle0.\n  rewrite <- mul_opp_r.\n  rewrite <- add_opp_r with (m := c0 * (c1 / c0)).\n  rewrite <- mul_opp_r.\n  rewrite mul_comm.\n  rewrite div_add.\n  rewrite mul_comm with (m := - ((x + c1) / c0 + - (c1 / c0))).\n  rewrite div_add.\n  rewrite add_shuffle0.\n  rewrite div_add.\n  rewrite add_shuffle1.\n  rewrite add_opp_r with (n := c1) (m := c1).\n  rewrite sub_diag.\n  rewrite add_0_r.\n  rewrite opp_add_distr.\n  rewrite opp_involutive.\n  rewrite add_shuffle1.\n  rewrite add_comm with (n := -(c1/c0)).\n  rewrite add_opp_r.\n  rewrite add_opp_r.\n  rewrite sub_diag.\n  rewrite add_0_r.\n  reflexivity.\n  apply lt_neq_ooo.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\n  apply lt_neq_ooo.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 + c1) / c0) - ((_0 + _1) / c0)) After : (((fold(((c0 + c1) - 1)) - _1) - ((_0 + fold((c1 % c0))) % c0)) / c0);; Pred  : (c0 > 0) *)\n(* rewrite((x + c1)/c0 - (x + y)/c0, ((fold(c0 + c1 - 1) - y) - ((x + fold(c1 % c0)) % c0))/c0, c0 > 0) *)\nLemma subline274 : forall x y c0 c1, c0 > 0 -> (x + c1)/c0 - (x + y)/c0 == ((c0 + c1 - 1) - y - (x + (c1 mod c0)) mod c0) / c0.\nProof.\nAdmitted.\n\n(* ;; Before: (((_0 - _1) / c0) - ((_0 + c1) / c0)) After : (((((_0 + fold((c1 % c0))) % c0) - _1) - c1) / c0);; Pred  : (c0 > 0) *)\n(* rewrite((x - y)/c0 - (x + c1)/c0, (((x + fold(c1 % c0)) % c0) - y - c1)/c0, c0 > 0) *)\nLemma subline275 : forall x y c0 c1, c0 > 0 -> (x - y)/c0 - (x + c1)/c0 == (((x + (c1 mod c0)) mod c0) - y - c1)/c0.\nProof.\n  intros.\n  rewrite <- add_opp_r with (n := x) (m := y).\n  rewrite <- add_opp_r with (m := y).\n  apply subline273.\n  assumption.\nQed.\n\n(* ;; Before: (((_0 + c1) / c0) - ((_0 - _1) / c0)) After : (((_1 + fold(((c0 + c1) - 1))) - ((_0 + fold((c1 % c0))) % c0)) / c0);; Pred  : (c0 > 0) *)\n(* rewrite((x + c1)/c0 - (x - y)/c0, ((y + fold(c0 + c1 - 1)) - ((x + fold(c1 % c0)) % c0))/c0, c0 > 0) *)\nLemma subline276 : forall x y c0 c1, c0 > 0 -> (x + c1)/c0 - (x - y)/c0 == (y + c0 + c1 - 1 - (x + (c1 mod c0) mod c0))/c0.\nProof.\nAdmitted.\n\n(* ;; Before: ((_0 / c0) - ((_0 + _1) / c0)) After : (((fold((c0 - 1)) - _1) - (_0 % c0)) / c0);; Pred  : (c0 > 0) *)\n(* rewrite(x/c0 - (x + y)/c0, ((fold(c0 - 1) - y) - (x % c0))/c0, c0 > 0) *)\nLemma subline277 : forall x y c0, c0 > 0 -> x/c0 - (x + y)/c0 == (((c0 - 1) - y) - (x mod c0))/c0.\nProof.\n  intros.\nAdmitted.\n\n(* ;; Before: (((_0 + _1) / c0) - (_0 / c0)) After : (((_0 % c0) + _1) / c0);; Pred  : (c0 > 0) *)\n(* rewrite((x + y)/c0 - x/c0, ((x % c0) + y)/c0, c0 > 0) *)\nLemma subline278 : forall x y c0, c0 > 0 -> (x + y)/c0 - x/c0 == ((x mod c0) + y)/c0.\nProof.\n  intros.\n  rewrite mod_eq.\n  cut (x - c0*(x/c0) == x + -(c0*(x/c0))).\n  intros.\n  rewrite H0.\n  rewrite <- mul_opp_r.\n  rewrite add_shuffle0.\n  rewrite mul_comm.\n  rewrite div_add.\n  rewrite add_opp_r.\n  reflexivity.\n  apply lt_neq_ooo.\n  assumption.\n  rewrite add_opp_r.\n  reflexivity.\n  apply lt_neq_ooo.\n  assumption.\nQed.\n\n(* ;; Before: ((_0 / c0) - ((_0 - _1) / c0)) After : (((_1 + fold((c0 - 1))) - (_0 % c0)) / c0);; Pred  : (c0 > 0) *)\n(* rewrite(x/c0 - (x - y)/c0, ((y + fold(c0 - 1)) - (x % c0))/c0, c0 > 0) *)\nLemma subline279 : forall x y c0, c0 > 0 -> x/c0 - (x - y)/c0 == (y + (c0 - 1) - (x mod c0))/c0.\nProof.\n  intros.\n  rewrite mod_eq.\n  cut (x - c0*(x/c0) == x + -(c0*(x/c0))).\n  intros.\n  rewrite H0.\n  rewrite <- add_opp_r with (n := y + (c0 - 1)).\n  rewrite opp_add_distr.\n  rewrite opp_involutive.\n  rewrite add_assoc.\n  rewrite mul_comm.\n  rewrite div_add.\n  rewrite add_shuffle0.\n  rewrite add_comm with (n := y) (m := -x).\n  rewrite add_comm with (m := x/c0).\n  \n\n(* ;; Before: (((_0 - _1) / c0) - (_0 / c0)) After : (((_0 % c0) - _1) / c0);; Pred  : (c0 > 0) *)\n(* rewrite((x - y)/c0 - x/c0, ((x % c0) - y)/c0, c0 > 0)) *)\nLemma subline280 : forall x y c0, c0 > 0 -> (x - y)/c0 - x/c0 == ((x mod c0) - y)/c0.\nProof.\n  intros.\n  rewrite <- add_opp_r.\n  rewrite <- add_opp_r.\n  rewrite <- add_opp_r.\n  rewrite add_opp_r with (m := x/c0).\n  apply subline278.\n  assumption.\nQed.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nEnd ZEuclidProp.", "meta": {"author": "jn80842", "repo": "coq4halidetrs", "sha": "d1199da56592342fd76ebfa0d0ce63741d2d6e01", "save_path": "github-repos/coq/jn80842-coq4halidetrs", "path": "github-repos/coq/jn80842-coq4halidetrs/coq4halidetrs-d1199da56592342fd76ebfa0d0ce63741d2d6e01/rules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6771784242657669}}
{"text": "Require Import List Bool ZArith Permutation.\nRequire Import Wellfounded Morphisms.\nRequire Import Lia.\nImport ListNotations.\n\n(* already done in\n   https://github.com/math-comp/Coq-Combi/blob/master/theories/Combi/Dyckword.v *)\n\nFrom BasicCombinatorics Require Import Even Binomial.\n\n(* putting this in Set gives us a\n   \"Case analysis on sort Set is not allowed for inductive definition ex.\"\n*)\nInductive Dyck: word -> Prop :=\n| Dyck_nil: Dyck nil\n| Dyck_shift: forall w, Dyck w -> Dyck (true::w++[false])\n| Dyck_app: forall w1, Dyck w1 -> forall w2, Dyck w2 -> Dyck (w1 ++ w2).\n\nSection level.\nOpen Scope Z.\n\nFixpoint level w :=\nmatch w with\n| nil => 0\n| true::w => (level w) + 1\n| false::w => (level w) - 1\nend.\n\nLemma level_app w1 w2:\n  level (w1 ++ w2) = (level w1) + (level w2).\nProof.\n  induction w1.\n  - reflexivity.\n  - rewrite <- app_comm_cons. destruct a; cbn; lia.\nQed.\n\nLemma level_permutation:\n  Proper (@Permutation bool ==> eq) level.\nProof.\n  intros w w' H. induction H.\n  - reflexivity.\n  - cbn. rewrite IHPermutation. reflexivity.\n  - cbn. destruct x,y; lia.\n  - congruence.\nQed.\n\nCorollary level_ends a w b:\n  level (a::w++[b]) = level [a;b] + level w.\nProof.\n  rewrite <- level_app. apply level_permutation.\n  apply perm_skip. symmetry. apply Permutation_cons_append.\nQed.\n\nCoercion Z.of_nat : nat >-> Z.\n\nLemma level_count w:\n   level w = #true w - #false w.\nProof.\n  induction w.\n  - reflexivity.\n  - destruct a; cbn -[Z.of_nat]; lia.\nQed.\n\nCorollary level_count_le_iff w:\n  0 <= level w <-> (#false w <= #true w)%nat.\nProof. rewrite level_count. lia. Qed.\n\nCorollary level_count_eq_iff w:\n  level w = 0 <-> (#false w = #true w)%nat.\nProof. rewrite level_count. lia. Qed.\n\nLemma level_firstn_false:\n  forall n, -1 <= level (firstn n [false]).\nProof.\n  intro n. destruct n.\n  - cbn. lia.\n  - cbn. rewrite firstn_nil. reflexivity.\nQed.\n\nLemma dyck_level_firstn w:\n  Dyck w -> forall n, 0 <= level (firstn n w).\nProof.\n  intros D. induction D; intro n.\n  - rewrite firstn_nil. reflexivity.\n  - destruct n; [reflexivity|].\n    cbn. rewrite firstn_app, level_app.\n    pose (level_firstn_false (n - length w)). specialize (IHD n). lia.\n  - rewrite firstn_app, level_app.\n    specialize (IHD1 n). specialize (IHD2 (n - length w1)%nat). lia.\nQed.\n\nLemma dyck_level_zero w:\n  Dyck w -> level w = 0.\nProof.\n  intros D. induction D.\n  - reflexivity.\n  - rewrite level_ends. assumption.\n  - rewrite level_app, IHD1, IHD2. reflexivity.\nQed.\n\nLemma level_zero_even w:\n  level w = 0 -> Even w.\nProof.\n  intros H. apply count_eq_even.\n  rewrite level_count in H. lia.\nQed.\n\nLemma list_nil_decidable {A: Type} (l: list A):\n  {l = nil} + {l <> nil}.\nProof.\n  destruct l.\n  - left. reflexivity.\n  - right. discriminate.\nQed.\n\nLemma firstn_add_skipn {A: Type} (l: list A) (n m : nat):\n  firstn (n+m)%nat l = firstn n l ++ (firstn m (skipn n l)).\nProof. (* possibly can be done much shorter *)\n  destruct (Nat.le_decidable n (length l)) as [H|H].\n  - rewrite <- (firstn_skipn n l), firstn_app at 1.\n    rewrite firstn_length. rewrite min_l by assumption.\n    replace (n + m - n)%nat with m by auto with arith.\n    rewrite firstn_firstn. rewrite min_r by apply Nat.le_add_r.\n    reflexivity.\n  - apply Nat.nle_gt, Nat.lt_le_incl in H.\n    rewrite !firstn_all2, skipn_all2 by lia.\n    rewrite firstn_nil, app_nil_r. reflexivity.\nQed.\n\nSection level_zero_at.\n(* first time we return to ground level *)\nDefinition level_zero_at w n :=\n  (0 < n)%nat /\\ level (firstn n w) = 0.\n\nVariable w : word.\nHypothesis Hnil: w <> nil.\nHypothesis Hzero: level w = 0.\n\nLemma level_zero_at_length:\n  level_zero_at w (length w).\nProof.\n  split.\n  + apply Nat.neq_0_lt_0. intro H.\n    apply Hnil,length_zero_iff_nil. assumption.\n  + rewrite firstn_all. assumption.\nQed.\n\nLemma level_zero_at_least:\n  has_unique_least_element le (level_zero_at w).\nProof.\n  apply dec_inh_nat_subset_has_unique_least_element.\n  - intro n. apply Decidable.dec_and.\n    + apply Nat.lt_decidable.\n    + apply Z.eq_decidable.\n  - exists (length w). apply level_zero_at_length.\nQed.\n\nEnd level_zero_at.\n\nLemma level_firstn_dyck w:\n  level w = 0 ->\n  (forall n, (n < length w)%nat -> 0 <= level (firstn n w)) ->\n  Dyck w.\nProof.\n  (* strong induction over w *)\n  induction w as [w IH]\n  using (well_founded_induction ((wf_inverse_image _ _ _ (@length _)) lt_wf)).\n  (* consider first n where (firstn n w) returns to ground *)\n  intros H0 H1.\n  destruct (list_nil_decidable w) as [->|Hnil]; [constructor|].\n  destruct (level_zero_at_least w Hnil H0) as [n [[[Hn0 Hn] n_min] n_uniq]].\n  clear n_uniq.\n  (* is it the very end? *)\n  destruct (lt_eq_lt_dec n (length w)) as [[H|H]|H].\n  - (*no: w if of form Dyck_app *)\n    rewrite <- (firstn_skipn n). apply Dyck_app.\n    + apply IH; clear IH.\n      * rewrite firstn_length_le; auto with arith.\n      * assumption.\n      * intros k Hk. rewrite firstn_firstn. apply H1. lia.\n    + apply IH; clear IH.\n      * rewrite skipn_length. lia.\n      * rewrite <- (firstn_skipn n w), level_app, Hn in H0. assumption.\n      * intros k Hk. specialize (H1 (n + k)%nat).\n        rewrite firstn_add_skipn, level_app, Hn in H1. apply H1.\n        rewrite skipn_length in Hk. lia.\n  - (*yes: w is of the form Dyck_nil or Dyck_shift *)\n    subst n.\n    apply level_zero_even in H0 as HEven. destruct HEven as [|w' H2 a b].\n    + exact Dyck_nil.\n    + assert (a = true) as ->. {\n        destruct a; [reflexivity|exfalso].\n        specialize (H1 1%nat). cut (0 <= -1).\n        - lia.\n        - apply H1. rewrite length_cons_ends. auto with arith.\n      }\n      assert (b = false) as ->. {\n        destruct b; [exfalso|reflexivity]. clear - H0 H1.\n        rewrite level_ends in H0.\n        replace (level [true; true]) with 2 in H0 by reflexivity.\n\n        specialize (H1 (1 + length w' + 0)%nat). cbn in H1.\n        rewrite firstn_app_2, firstn_O, app_nil_r in H1.\n        cut (0 <= level w' + 1).\n        - lia.\n        - apply H1. rewrite app_length. auto with arith.\n      }\n      rewrite level_ends in H0.\n      apply Dyck_shift. apply IH; clear IH.\n      * rewrite length_cons_ends. repeat constructor.\n      * exact H0.\n      * intros k H.\n        destruct (Z.le_decidable 0 (level (firstn k w'))); [assumption|exfalso].\n        (* we went to the bottom at k, in contradiction to minimality n *)\n        assert (level_zero_at (true::w'++[false]) (S k)). {\n          split; [apply Nat.lt_0_succ|]. apply Z.le_antisymm.\n          - clear -H H3. cbn. rewrite firstn_app.\n            replace (k - length w')%nat with 0%nat by lia.\n            rewrite firstn_O, app_nil_r. lia.\n          - apply H1. clear -H. rewrite length_cons_ends. lia.\n        }\n        specialize (n_min (S k) H4). clear -H n_min.\n        rewrite length_cons_ends in n_min. lia.\n  - exfalso.\n    specialize (n_min (length w) (level_zero_at_length w Hnil H0)). lia.\nQed.\nEnd level.\n\nTheorem dyck_firstn_iff w:\n  Dyck w <->\n  (#false w = #true w) /\\\n  forall n, n < length w -> #false (firstn n w) <= #true (firstn n w).\nProof.\n  split; intro H.\n  - split.\n    + apply level_count_eq_iff, dyck_level_zero. assumption.\n    + intros n Hn. apply level_count_le_iff, dyck_level_firstn. assumption.\n  - destruct H as [H1 H2]. apply level_firstn_dyck.\n    + apply level_count_eq_iff. assumption.\n    + intros n Hn. apply level_count_le_iff, H2, Hn.\nQed.\n\nRequire Import FunInd Recdef.\n\nFixpoint dycks_aux fuel (n: nat) {struct fuel}: list word :=\nmatch fuel with\n| 0 => [ nil ]\n| S fuel =>\nmatch n with\n| 0 => [ nil ]\n| S n =>\n  flat_map\n  (fun k =>\n    map (fun '(v,w) => (true::v++[false])++w)\n    (list_prod (dycks_aux fuel k) (dycks_aux fuel (n-k))))\n  (seq 0 (S n))\nend\nend.\n\nDefinition dycks n := dycks_aux n n.\n\nLemma dycks_correct n:\n  forall w, In w (dycks n) -> Dyck w.\nProof.\n  induction n as [n IH] using (well_founded_induction lt_wf).\n  intros w H. destruct n.\n  - apply In_singleton in H. subst w. constructor.\n  - cbn -[flat_map seq app] in H.\n    apply in_flat_map in H as [k [Hk%in_seq H]].\n    apply in_map_iff in H as [[v' w'] [<- H%in_prod_iff]]. destruct H.\n    constructor; [constructor|].\n    + apply (IH k).\n      * destruct Hk. assumption.\n      * \nAbort.\n\nLemma dyck_factorize w:\n  w <> nil -> Dyck w ->\n  exists ! w1 w2, Dyck w1 /\\ Dyck w2 /\\ w = true::w1++[false]++w2.\nProof.\n  intros Hnil D. specialize (dyck_level_zero w D) as H0.\n  destruct (level_zero_at_least w Hnil H0) as [n [[[Hn0 Hn] n_min] n_uniq]].\n  remember ... destruct (level_zero_even _ Hn).\nAbort.\n", "meta": {"author": "haansn08", "repo": "coq-basic-combinatorics", "sha": "391e280605c2127142bc2cec20c0b874034d936a", "save_path": "github-repos/coq/haansn08-coq-basic-combinatorics", "path": "github-repos/coq/haansn08-coq-basic-combinatorics/coq-basic-combinatorics-391e280605c2127142bc2cec20c0b874034d936a/theories/Dyck.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017535, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6771784138271608}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\nRequire Import NAxioms NSub NZDiv.\n\n\n\nModule Type NDivProp (Import N : NAxiomsSig')(Import NP : NSubProp N).\n\n\nModule Import Private_NZDiv := Nop <+ NZDivProp N N NP.\n\nLtac auto' := try rewrite <- neq_0_lt_0; auto using le_0_l.\n\n\n\nLemma mod_upper_bound : forall a b, b ~= 0 -> a mod b < b.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mod_upper_bound\".   intros. apply mod_bound_pos; auto'. Qed.\n\n\n\nLemma mod_eq :\nforall a b, b~=0 -> a mod b == a - b*(a/b).\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mod_eq\".  \nintros.\nsymmetry. apply add_sub_eq_l. symmetry.\nnow apply div_mod.\nQed.\n\n\n\nTheorem div_mod_unique :\nforall b q1 q2 r1 r2, r1<b -> r2<b ->\nb*q1+r1 == b*q2+r2 -> q1 == q2 /\\ r1 == r2.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_mod_unique\".   intros. apply div_mod_unique with b; auto'. Qed.\n\nTheorem div_unique:\nforall a b q r, r<b -> a == b*q + r -> q == a/b.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_unique\".   intros; apply div_unique with r; auto'. Qed.\n\nTheorem mod_unique:\nforall a b q r, r<b -> a == b*q + r -> r == a mod b.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mod_unique\".   intros. apply mod_unique with q; auto'. Qed.\n\nTheorem div_unique_exact: forall a b q, b~=0 -> a == b*q -> q == a/b.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_unique_exact\".   intros. apply div_unique_exact; auto'. Qed.\n\n\n\nLemma div_same : forall a, a~=0 -> a/a == 1.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_same\".   intros. apply div_same; auto'. Qed.\n\nLemma mod_same : forall a, a~=0 -> a mod a == 0.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mod_same\".   intros. apply mod_same; auto'. Qed.\n\n\n\nTheorem div_small: forall a b, a<b -> a/b == 0.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_small\".   intros. apply div_small; auto'. Qed.\n\n\n\nTheorem mod_small: forall a b, a<b -> a mod b == a.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mod_small\".   intros. apply mod_small; auto'. Qed.\n\n\n\nLemma div_0_l: forall a, a~=0 -> 0/a == 0.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_0_l\".   intros. apply div_0_l; auto'. Qed.\n\nLemma mod_0_l: forall a, a~=0 -> 0 mod a == 0.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mod_0_l\".   intros. apply mod_0_l; auto'. Qed.\n\nLemma div_1_r: forall a, a/1 == a.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_1_r\".   intros. apply div_1_r; auto'. Qed.\n\nLemma mod_1_r: forall a, a mod 1 == 0.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mod_1_r\".   intros. apply mod_1_r; auto'. Qed.\n\nLemma div_1_l: forall a, 1<a -> 1/a == 0.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_1_l\".   exact div_1_l. Qed.\n\nLemma mod_1_l: forall a, 1<a -> 1 mod a == 1.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mod_1_l\".   exact mod_1_l. Qed.\n\nLemma div_mul : forall a b, b~=0 -> (a*b)/b == a.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_mul\".   intros. apply div_mul; auto'. Qed.\n\nLemma mod_mul : forall a b, b~=0 -> (a*b) mod b == 0.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mod_mul\".   intros. apply mod_mul; auto'. Qed.\n\n\n\n\n\n\nTheorem mod_le: forall a b, b~=0 -> a mod b <= a.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mod_le\".   intros. apply mod_le; auto'. Qed.\n\nLemma div_str_pos : forall a b, 0<b<=a -> 0 < a/b.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_str_pos\".   exact div_str_pos. Qed.\n\nLemma div_small_iff : forall a b, b~=0 -> (a/b==0 <-> a<b).\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_small_iff\".   intros. apply div_small_iff; auto'. Qed.\n\nLemma mod_small_iff : forall a b, b~=0 -> (a mod b == a <-> a<b).\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mod_small_iff\".   intros. apply mod_small_iff; auto'. Qed.\n\nLemma div_str_pos_iff : forall a b, b~=0 -> (0<a/b <-> b<=a).\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_str_pos_iff\".   intros. apply div_str_pos_iff; auto'. Qed.\n\n\n\n\nLemma div_lt : forall a b, 0<a -> 1<b -> a/b < a.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_lt\".   exact div_lt. Qed.\n\n\n\nLemma div_le_mono : forall a b c, c~=0 -> a<=b -> a/c <= b/c.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_le_mono\".   intros. apply div_le_mono; auto'. Qed.\n\nLemma mul_div_le : forall a b, b~=0 -> b*(a/b) <= a.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mul_div_le\".   intros. apply mul_div_le; auto'. Qed.\n\nLemma mul_succ_div_gt: forall a b, b~=0 -> a < b*(S (a/b)).\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mul_succ_div_gt\".   intros; apply mul_succ_div_gt; auto'. Qed.\n\n\n\nLemma div_exact : forall a b, b~=0 -> (a == b*(a/b) <-> a mod b == 0).\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_exact\".   intros. apply div_exact; auto'. Qed.\n\n\n\nTheorem div_lt_upper_bound:\nforall a b q, b~=0 -> a < b*q -> a/b < q.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_lt_upper_bound\".   intros. apply div_lt_upper_bound; auto'. Qed.\n\nTheorem div_le_upper_bound:\nforall a b q, b~=0 -> a <= b*q -> a/b <= q.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_le_upper_bound\".   intros; apply div_le_upper_bound; auto'. Qed.\n\nTheorem div_le_lower_bound:\nforall a b q, b~=0 -> b*q <= a -> q <= a/b.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_le_lower_bound\".   intros; apply div_le_lower_bound; auto'. Qed.\n\n\n\nLemma div_le_compat_l: forall p q r, 0<q<=r -> p/r <= p/q.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_le_compat_l\".   intros. apply div_le_compat_l. auto'. auto. Qed.\n\n\n\nLemma mod_add : forall a b c, c~=0 ->\n(a + b * c) mod c == a mod c.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mod_add\".   intros. apply mod_add; auto'. Qed.\n\nLemma div_add : forall a b c, c~=0 ->\n(a + b * c) / c == a / c + b.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_add\".   intros. apply div_add; auto'. Qed.\n\nLemma div_add_l: forall a b c, b~=0 ->\n(a * b + c) / b == a + c / b.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_add_l\".   intros. apply div_add_l; auto'. Qed.\n\n\n\nLemma div_mul_cancel_r : forall a b c, b~=0 -> c~=0 ->\n(a*c)/(b*c) == a/b.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_mul_cancel_r\".   intros. apply div_mul_cancel_r; auto'. Qed.\n\nLemma div_mul_cancel_l : forall a b c, b~=0 -> c~=0 ->\n(c*a)/(c*b) == a/b.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_mul_cancel_l\".   intros. apply div_mul_cancel_l; auto'. Qed.\n\nLemma mul_mod_distr_r: forall a b c, b~=0 -> c~=0 ->\n(a*c) mod (b*c) == (a mod b) * c.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mul_mod_distr_r\".   intros. apply mul_mod_distr_r; auto'. Qed.\n\nLemma mul_mod_distr_l: forall a b c, b~=0 -> c~=0 ->\n(c*a) mod (c*b) == c * (a mod b).\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mul_mod_distr_l\".   intros. apply mul_mod_distr_l; auto'. Qed.\n\n\n\nTheorem mod_mod: forall a n, n~=0 ->\n(a mod n) mod n == a mod n.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mod_mod\".   intros. apply mod_mod; auto'. Qed.\n\nLemma mul_mod_idemp_l : forall a b n, n~=0 ->\n((a mod n)*b) mod n == (a*b) mod n.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mul_mod_idemp_l\".   intros. apply mul_mod_idemp_l; auto'. Qed.\n\nLemma mul_mod_idemp_r : forall a b n, n~=0 ->\n(a*(b mod n)) mod n == (a*b) mod n.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mul_mod_idemp_r\".   intros. apply mul_mod_idemp_r; auto'. Qed.\n\nTheorem mul_mod: forall a b n, n~=0 ->\n(a * b) mod n == ((a mod n) * (b mod n)) mod n.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mul_mod\".   intros. apply mul_mod; auto'. Qed.\n\nLemma add_mod_idemp_l : forall a b n, n~=0 ->\n((a mod n)+b) mod n == (a+b) mod n.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.add_mod_idemp_l\".   intros. apply add_mod_idemp_l; auto'. Qed.\n\nLemma add_mod_idemp_r : forall a b n, n~=0 ->\n(a+(b mod n)) mod n == (a+b) mod n.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.add_mod_idemp_r\".   intros. apply add_mod_idemp_r; auto'. Qed.\n\nTheorem add_mod: forall a b n, n~=0 ->\n(a+b) mod n == (a mod n + b mod n) mod n.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.add_mod\".   intros. apply add_mod; auto'. Qed.\n\nLemma div_div : forall a b c, b~=0 -> c~=0 ->\n(a/b)/c == a/(b*c).\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_div\".   intros. apply div_div; auto'. Qed.\n\nLemma mod_mul_r : forall a b c, b~=0 -> c~=0 ->\na mod (b*c) == a mod b + b*((a/b) mod c).\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mod_mul_r\".   intros. apply mod_mul_r; auto'. Qed.\n\n\n\nTheorem div_mul_le:\nforall a b c, b~=0 -> c*(a/b) <= (c*a)/b.\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.div_mul_le\".   intros. apply div_mul_le; auto'. Qed.\n\n\n\nLemma mod_divides : forall a b, b~=0 ->\n(a mod b == 0 <-> exists c, a == b*c).\nProof. hammer_hook \"NDiv\" \"NDiv.NDivProp.mod_divides\".   intros. apply mod_divides; auto'. Qed.\n\nEnd NDivProp.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Numbers/Natural/Abstract/NDiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6771784111071821}}
{"text": "Require Import Morphisms.\nImport ProperNotations.\nRequire Import SetoidClass.\nRequire notation.\n\nModule Make(Import M: notation.T).\n\nRecord Category: Type := \n mk_Category \n {\n     obj : Type;\n     arrow: obj -> obj -> Type;\n     identity : forall a, arrow a a;\n     comp : forall {a b c}, (arrow a b) -> (arrow b c) -> (arrow a c);\n     assoc : forall {a b c d} (f : arrow b a) (g : arrow c b) (h : arrow d c), comp h (comp g f) = comp (comp h g) f;\n     identity_f: forall {a b} (f: arrow b a), comp (@identity b) f = f;\n     f_identity: forall {a b} (f: arrow b a), comp f (@identity a) = f \n  }.\nCheck obj.\nCheck arrow.\n\nNotation \" x 'o' y \" := (comp _ x y) (at level 40, left associativity). \n\nDefinition Product_Category (catC catD: Category) : Category.\nProof. \n  refine (@mk_Category \n           (obj catC * obj catD)%type\n           (fun a b => (arrow catC (fst a) (fst b) * arrow catD (snd a) (snd b))%type)\n           (fun a => (identity catC (fst a), identity catD (snd a)))\n           (fun a b c f2 f1 => (fst f2 o fst f1, snd f2 o snd f1))\n           _ _ _\n         ). \n  intros. setoid_rewrite <- assoc. reflexivity. \n  intros. simpl. specialize (@identity_f catC (fst a) (fst b) (fst f)). intros. rewrite H.\n  intros. simpl. specialize (@identity_f catD (snd a) (snd b) (snd f)). intros. rewrite H0.\n    destruct f. simpl. reflexivity.\n  intros. simpl. specialize (@f_identity catC (fst a) (fst b) (fst f)). intros. rewrite H.\n  intros. simpl. specialize (@f_identity catD (snd a) (snd b) (snd f)). intros. rewrite H0.\n    destruct f. simpl. reflexivity.\nDefined.\nCheck Product_Category.\n\nDefinition Dual_Category (catC: Category) : Category.\nProof. \n  refine (@mk_Category \n           (obj catC)%type\n           (fun a b => (arrow catC b a %type))\n           (fun a => (@identity catC a))\n           (fun a b c f1 f2 => f2 o f1)\n           _ _ _ \n         ). \n  intros. setoid_rewrite <- assoc. reflexivity.\n  intros.  specialize (@f_identity catC b a f). intros. exact H.\n  intros.  specialize (@identity_f catC b a f). intros. exact H. \nDefined. \nCheck Dual_Category.\n\n(*\nClass Category2 (Obj : Type) (Arrow: Obj -> Obj -> Type) : Type := \n {\n     obj2 := Obj;\n     arrow2 := Arrow; \n     identity2 : forall a, arrow2 a a;\n     comp2 : forall {a b c}, (arrow2 a b) -> (arrow2 b c) -> (arrow2 a c);\n     assoc2 : forall {a b c d} (f : arrow2 b a) (g : arrow2 c b) (h : arrow2 d c), comp2 h (comp2 g f) = comp2 (comp2 h g) f\n  }.\n\nCoercion obj2 : Category2 >-> Sortclass.\nCheck comp2.\n\n\nNotation \" x 'O' y \" := (comp2 x y) (at level 40, left associativity).\n\nGeneralizable All Variables.\n\nDefinition Dual_Category2 `(catC: Category2 objC arrowC) : Category2 objC (fun x y => arrowC y x).\nrefine (@Build_Category2 objC\n                              (fun x y => arrow2 y x) \n                              (fun a => (@identity2 obj2 arrow2 catC a))\n                              (fun a b c f g => g O f)\n                             _).\nintros. rewrite <- assoc2. reflexivity. Defined.\nCheck Dual_Category2.\n*)\n\nEnd Make.", "meta": {"author": "ekiciburak", "repo": "monads", "sha": "6e4de9f06d52f05fd4172d41a6c2db6d9239223d", "save_path": "github-repos/coq/ekiciburak-monads", "path": "github-repos/coq/ekiciburak-monads/monads-6e4de9f06d52f05fd4172d41a6c2db6d9239223d/src/categories.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476385, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6771596107719028}}
{"text": "\n(**************************************************************************)\n(**  Mechanised Framework for Local Interactions & Distributed Algorithms   \n                                                                            \n     T. Balabonski, P. Courtieu, L. Rieg, X. Urbain                         \n                                                                            \n     PACTOLE project                                                        \n                                                                            \n     This file is distributed under the terms of the CeCILL-C licence     *)\n(**************************************************************************)\n\n\n(**************************************************************************)\n(* Author : Mathis Bouverot-Dupuis (June 2022).\n\n * This file implements an algorithm to GATHER all robots in the plane (R²). \n * The algorithm assumes there are no byzantine robots,\n * and works in a FLEXIBLE and ASYNCHRONOUS setting. \n\n * The algorithm is as follows : all robots go towards the 'weber point' of \n * the configuration.\n * The algorithm works on initial configurations where the weber point is unique.\n * Thanks to a property of the weber point (see the thesis of Zohir Bouzid, \n * corollary 3.1.1), it remains unique and at the same place throughout the whole execution. *)\n(**************************************************************************)\n\n\nRequire Import Bool.\nRequire Import Arith.Div2.\nRequire Import Lia Field.\nRequire Import Rbase Rbasic_fun R_sqrt Rtrigo_def.\nRequire Import List.\nRequire Import SetoidList.\nRequire Import Relations.\nRequire Import RelationPairs.\nRequire Import Morphisms.\nRequire Import Psatz.\nRequire Import Inverse_Image.\nRequire Import FunInd.\nRequire Import FMapFacts.\n\n(* Helping typeclass resolution avoid infinite loops. *)\nTypeclasses eauto := (bfs).\n\n(* Pactole basic definitions *)\nRequire Export Pactole.Setting.\n(* Specific to R^2 topology *)\nRequire Import Pactole.Spaces.RealMetricSpace.\nRequire Import Pactole.Spaces.R2.\n(* Specific to gathering *)\nRequire Pactole.CaseStudies.Gathering.WithMultiplicity.\nRequire Import Pactole.CaseStudies.Gathering.Definitions.\n(* Specific to multiplicity *)\nRequire Import Pactole.Observations.MultisetObservation.\n(* Specific to flexibility *)\nRequire Import Pactole.Models.Flexible.\n(* Specific to settings with no Byzantine robots *)\nRequire Import Pactole.Models.NoByzantine.\n(* Utility lemmas. *)\nRequire Import Pactole.CaseStudies.Gathering.InR2.Weber.Utils.\n(* Specific to definition and properties of the weber point. *)\nRequire Import Pactole.CaseStudies.Gathering.InR2.Weber.Weber_point.\n\n(* User defined *)\nImport Permutation.\nImport Datatypes.\n\n\nSet Implicit Arguments.\nClose Scope R_scope.\nClose Scope VectorSpace_scope.\n\n\nSection Gathering.\nLocal Existing Instances dist_sum_compat.\n\n(* We assume the existence of a function that calculates a weber point of a collection\n * (even when the weber point is not unique).\n * This is a very strong assumption : such a function may not exist in closed form, \n * and the Weber point can only be approximated. *)\nAxiom weber_calc : list R2 -> R2.\nAxiom weber_calc_correct : forall ps, Weber ps (weber_calc ps).\n(* We also suppose this function doesn't depend on the order of the points. \n* This is probably not necessary (we can show that it holds when the points aren't colinear) \n* but simplifies the proof a bit. *)\nAxiom weber_calc_compat : Proper (PermutationA equiv ==> equiv) weber_calc.\nLocal Existing Instance weber_calc_compat.\n  \n(* The number of robots *)\nVariables n : nat.\nHypothesis lt_0n : 0 < n.\n\n(* There are no byzantine robots. *)\nLocal Instance N : Names := Robots n 0.\nLocal Instance NoByz : NoByzantine.\nProof using . now split. Qed.\n\nLemma list_in_length_n0 {A : Type} x (l : list A) : List.In x l -> length l <> 0.\nProof using . intros Hin. induction l as [|y l IH] ; cbn ; auto. Qed.\n\nLemma byz_impl_false : B -> False.\nProof using . \nintros b. assert (Hbyz := In_Bnames b). \napply list_in_length_n0 in Hbyz. \nrewrite Bnames_length in Hbyz.\ncbn in Hbyz. intuition.\nQed.\n\n(* Use this tactic to solve any goal\n * provided there is a byzantine robot as a hypothesis. *)\nLtac byz_exfalso :=\n  match goal with \n  | b : ?B |- _ => exfalso ; apply (byz_impl_false b)\n  end.\n\n(* Since all robots are good robots, we can define a function\n * from identifiers to good identifiers. *)\nDefinition unpack_good (id : ident) : G :=\n  match id with \n  | Good g => g \n  | Byz _ => ltac:(byz_exfalso)\n  end.\n\nLemma good_unpack_good id : Good (unpack_good id) == id.\nProof using . unfold unpack_good. destruct_match ; [auto | byz_exfalso]. Qed.\n\nLemma unpack_good_good g : unpack_good (Good g) = g.\nProof using . reflexivity. Qed.  \n\n(* The robots are in the plane (R^2). *)\nLocal Instance Loc : Location := make_Location R2.\nLocal Instance LocVS : RealVectorSpace location := R2_VS.\nLocal Instance LocES : EuclideanSpace location := R2_ES.\n\n(* - This is what represents a robot's state.\n * The first location is the robot's start position (where it performed its last 'compute').\n * The second location is the robot's destination (what the robogram computed).\n * The ratio indicates how far the robot has moved along the straight path\n * from start to destination.\n * - The robogram doesn't have access to all of this information : \n * when we create an observation, this state gets reduced to \n * only the current position of the robot.\n * - I would have prefered to use a path instead of a (start, destination) pair,\n * but we need an EqDec instance on [info]. *)\nDefinition info := ((location * location) * ratio)%type.\n\nLocal Instance info_Setoid : Setoid info := \n  prod_Setoid (prod_Setoid location_Setoid location_Setoid) ratio_Setoid.\nLocal Instance info_EqDec : EqDec info_Setoid := \n  prod_EqDec (prod_EqDec location_EqDec location_EqDec) ratio_EqDec.\n\nLocal Instance St : State info.\nsimple refine {|\n  get_location := fun '(start, dest, r) => straight_path start dest r ; \n  state_Setoid := info_Setoid ;\n  state_EqDec := info_EqDec ;\n  precondition f := sigT (fun sim : similarity location => Bijection.section sim == f) ; \n  lift f := fun '(start, dest, r) => ((projT1 f) start, (projT1 f) dest, r) \n|} ; autoclass.\nProof using .\n+ abstract (intros H [[start dest] r] ; reflexivity).\n+ abstract (intros [f [sim Hf]] [[start dest] r] ; cbn -[equiv straight_path] ;\n            rewrite <-Hf ; apply straight_path_similarity).\n+ abstract (intros [[s d] r] [[s' d'] r'] [[Hs Hd] Hr] ; \n            cbn -[equiv location] in * |- ; now rewrite Hs, Hd, Hr).\n+ abstract (intros [f Hf] [g Hg] ; cbn -[equiv] ; intros Hfg [[s d] r] [[s' d'] r'] [[Hs Hd] Hr] ;\n            cbn -[equiv location] in * |- ; repeat split ; cbn -[equiv] ; auto).\nDefined.\n\nDefinition get_start (i : info) := let '(s, _, _) := i in s.\n\nLocal Instance get_start_compat : Proper (equiv ==> equiv) get_start.\nProof using . intros [[? ?] ? ] [[? ?] ?] [[H _] _]. cbn -[equiv] in *. now rewrite H. Qed.\n\nDefinition get_destination (i : info) := let '(_, d, _) := i in d.\n\nLocal Instance get_destination_compat : Proper (equiv ==> equiv) get_destination.\nProof using . intros [[? ?] ? ] [[? ?] ?] [[_ H] _]. cbn -[equiv] in *. now rewrite H. Qed.\n\n(* Refolding typeclass instances *)\nLtac foldR2 :=\n  change R2 with location in * ;\n  change R2_Setoid with location_Setoid in * ;\n  change R2_EqDec with location_EqDec in * ;\n  change R2_VS with LocVS in * ;\n  change R2_ES with LocES in * ;\n  change info_Setoid with state_Setoid in * ;\n  change info_EqDec with state_EqDec in *.\n\n(* Robots choose their destination.\n * They will move to this destination along a straight path. *)\nLocal Instance RobotC : robot_choice location := \n  { robot_choice_Setoid := location_Setoid }.\n\n(* Robots view the other robots' positions up to a similarity. *)\nLocal Instance FrameC : frame_choice (similarity location) := FrameChoiceSimilarity.\n(* The demon doesn't perform any other choice for activated robots. *)\nLocal Instance UpdateC : update_choice unit := NoChoice.\n(* The demon chooses how far to move inactive robots towards their destination. \n * The ratio chosen by the demon is ADDED to the ratio stored in the robot state\n * (the result is clamped at 1 of course). *)\nLocal Instance InactiveC : inactive_choice ratio := { inactive_choice_Setoid := ratio_Setoid }.\n\n(* In a flexible setting, delta is the minimum distance that robots\n * are allowed to move before being reactivated. *)\nVariables delta : R.\nHypothesis delta_g0 : (0 < delta)%R.\n\n(* This is the property that must be verified in a flexible setting. *)\nDefinition flex_da_prop da := \n  forall id (config : configuration), activate da id = true -> \n    get_location (config id) == get_destination (config id) \\/ \n    (delta <= dist (get_start (config id)) (get_location (config id)))%R.\n\n(* We are in a flexible and semi-synchronous setting. *)\nLocal Instance UpdateF : update_function location (similarity location) unit.\nsimple refine {| \n  update config g _ target _ := (get_location (config (Good g)), target, ratio_0)\n|} ; autoclass.\nProof using .\nintros c c' Hc g g' Hg _ _ _ t t' Ht _ _ _.\nassert (H : c (Good g) == c' (Good g')) by now rewrite Hg, Hc.\ndestruct (c (Good g)) as [[start dest] r].\ndestruct (c' (Good g')) as [[start' dest'] r'].\ndestruct H as [[Hstart Hdest] Hr]. cbn -[equiv] in Hstart, Hdest, Hr.\nrepeat split ; cbn -[equiv get_location] ; auto.\nfoldR2. apply get_location_compat. now repeat split ; cbn -[equiv].\nDefined.\n\n\nLocal Instance InactiveF : inactive_function ratio.\nsimple refine {| inactive config id r_demon := \n  let '(start, dest, r) := config id in (start, dest, add_ratio r r_demon) \n|} ; autoclass.\nProof using . \nintros c c' Hc i i' Hi rd rd' Hrd.\nassert (H : c i == c' i') by now rewrite Hi, Hc.\ndestruct (c i) as [[start dest] r].\ndestruct (c' i') as [[start' dest'] r'].\ndestruct H as [[Hstart Hdest] Hr]. cbn -[equiv] in Hstart, Hdest, Hr.\nrepeat split ; cbn -[equiv] ; auto.\nf_equiv ; auto.\nDefined.\n\n(* This is a shorthand for the list of positions of robots in a configuration. *)\nDefinition pos_list (config : configuration) : list location := \n  List.map get_location (config_list config).\n\n(* The support of a multiset, but elements are repeated \n * a number of times equal to their multiplicity. \n * This is needed to convert an observation from multiset to list format, \n * so that we can use functions such as [weber_calc]. *)\nDefinition multi_support {A} `{EqDec A} (s : multiset A) :=\n  List.flat_map (fun '(x, mx) => alls x mx) (elements s).\n\nLocal Instance multi_support_compat {A} `{EqDec A} : Proper (equiv ==> PermutationA equiv) (@multi_support A _ _).\nProof using . \nintros s s' Hss'. unfold multi_support. f_equiv.\n+ intros [x mx] [y my] Hxy. inv Hxy. simpl in H0, H1. now rewrite H0, H1.\n+ now apply elements_compat.\nQed.\n\n(* The main algorithm : just move towards the weber point\n * (in a straight line) until all robots are gathered.\n * Note that [obs] describes the positions of the robots in the \n * LOCAL frame of reference. *)\nDefinition gatherW_pgm obs : location := \n  weber_calc (multi_support obs).\n\nLocal Instance gatherW_pgm_compat : Proper (equiv ==> equiv) gatherW_pgm.\nProof using . intros ? ? H. unfold gatherW_pgm. now rewrite H. Qed. \n\nDefinition gatherW : robogram := {| pgm := gatherW_pgm |}.\n\nLemma multi_support_add {A : Type} `{EqDec A} s x k : ~ In x s -> k > 0 ->\n  PermutationA equiv (multi_support (add x k s)) (alls x k ++ multi_support s).\nProof using . \nintros Hin Hk. unfold multi_support. \ntransitivity (flat_map (fun '(x0, mx) => alls x0 mx) ((x, k) :: elements s)).\n+ f_equiv.\n  - intros [a ka] [b kb] [H0 H1]. cbn in H0, H1. now rewrite H0, H1.\n  - apply elements_add_out ; auto.\n+ now cbn -[elements].\nQed.\n\nLemma multi_support_countA {A : Type} `{eq_dec : EqDec A} s x :\n  countA_occ equiv eq_dec x (multi_support s) == s[x]. \nProof using .\npattern s. apply MMultisetFacts.ind.\n+ intros m m' Hm. f_equiv. \n  - apply countA_occ_compat ; autoclass. now rewrite Hm.\n  - now rewrite Hm.\n+ intros m x' n' Hin Hn IH. rewrite add_spec, multi_support_add, countA_occ_app by auto.\n  destruct_match.\n  - now rewrite <-e, countA_occ_alls_in, Nat.add_comm, IH ; autoclass.\n  - now rewrite countA_occ_alls_out, IH, Nat.add_0_l ; auto.  \n+ now reflexivity.\nQed.\n\n(* This is the main result about multi_support. *)\n(* RMK : typeclass instance inference seems to be EXTREMELY slow in this proof.\n * Thankfully I found that the 'change' tactic is fast here. *)\nLemma multi_support_config (config : configuration) (id : ident) : \n  @PermutationA location equiv \n    (@multi_support location _ _ (obs_from_config config (config id))) \n    (pos_list config).\nProof using . \npose (l := pos_list config). fold l.\nchange (obs_from_config config (config id)) with (make_multiset l).\napply PermutationA_countA_occ. intros x. rewrite multi_support_countA. now apply make_multiset_spec.\nQed. \n\nCorollary multi_support_map f config id : \n  Proper (equiv ==> equiv) (projT1 f) ->\n  PermutationA (@equiv location _) \n    (@multi_support location _ _ (obs_from_config (map_config (lift f) config) (lift f (config id))))\n    (List.map (fun x => (projT1 f) (get_location x)) (config_list config)).\nProof using .  \nintros H. destruct f as [f Pf].\nchange (lift (existT precondition f Pf) (config id)) with (map_config (lift (existT precondition f Pf)) config id).\nrewrite multi_support_config. unfold pos_list. rewrite config_list_map, map_map.\n+ apply eqlistA_PermutationA. f_equiv. intros [[s d] r] [[s' d'] r'] Hsdr. inv Hsdr.\n  cbn -[equiv straight_path]. destruct Pf as [sim Hsim]. rewrite <-Hsim. apply straight_path_similarity.\n+ intros [[s d] r] [[s' d'] r'] [[Hs Hd] Hr]. cbn -[equiv] in H, Hs, Hd, Hr |- *. \n  repeat split ; cbn -[equiv] ; auto.\nQed.\n\nLemma lift_update_swap da config1 config2 g target :\n  @equiv info _\n    (lift (existT precondition (frame_choice_bijection (change_frame da config1 g ⁻¹))\n                               (precondition_satisfied_inv da config1 g))\n          (update config2\n           g (change_frame da config1 g) target (choose_update da config2 g target)))\n    (update (map_config (lift (existT precondition (frame_choice_bijection (change_frame da config1 g ⁻¹))\n                                      (precondition_satisfied_inv da config1 g)))\n                        config2)\n            g Similarity.id\n            ((frame_choice_bijection (change_frame da config1 g ⁻¹)) target)\n            (choose_update da config2 g target)).\nProof using .\npose (sim := change_frame da config1 g). fold sim.\ncbn -[inverse equiv straight_path]. destruct (config2 (Good g)) as [[start dest] r].\nnow rewrite straight_path_similarity.\nQed.\n\n(* Simplify the [round] function and express it in the global frame of reference.\n * This simplification only works when the weber point is unique.\n * All the proofs below use this simplified version. *)\nLemma round_simplify da config w : \n  similarity_da_prop da ->\n  OnlyWeber (pos_list config) w ->\n  exists r : ident -> ratio,\n  round gatherW da config == \n  fun id => if activate da id \n            then (get_location (config id), w, ratio_0)\n            else inactive config id (r id).\nProof using . \nintros Hsim [Hw HwU]. eexists ?[r]. intros id. unfold round. \ndestruct_match ; [|reflexivity].\ndestruct_match ; [|byz_exfalso].\ncbn -[inverse equiv lift precondition frame_choice_bijection config_list origin update get_location].\nrewrite (lift_update_swap da config _ g). \npose (f := existT precondition\n  (change_frame da config g)\n  (precondition_satisfied da config g)). \npose (f_inv := existT precondition\n  ((change_frame da config g) ⁻¹)\n  (precondition_satisfied_inv da config g)).\npose (obs := obs_from_config (map_config (lift f) config) (lift f (config (Good g)))).\nchange_LHS (update \n  (map_config (lift f_inv) (map_config (lift f) config)) g Similarity.id\n  (frame_choice_bijection (change_frame da config g ⁻¹)\n    (gatherW_pgm obs))\n  (choose_update da\n    (map_config (lift f) config) g (gatherW_pgm obs))).\nassert (Hcancel : map_config (lift f_inv) (map_config (lift f) config) == config).\n{ intros id. cbn -[equiv]. destruct (config id) as [[start dest] r]. now rewrite 2 Bijection.retraction_section. }\nrewrite Hcancel.\nassert (Proper (equiv ==> equiv) (projT1 f)) as f_compat.\n{ unfold f ; cbn -[equiv]. intros x y Hxy ; now rewrite Hxy. }\nunfold gatherW_pgm.\npose (sim := change_frame da config g). foldR2. fold sim.\nassert (Hw_sim : OnlyWeber (List.map sim (pos_list config)) (sim w)).\n{\n  split ; [now apply weber_similarity|]. \n  intros w' Hw'. rewrite <-(Bijection.section_retraction sim w') in Hw' |- *. \n  f_equiv. apply HwU. now rewrite <-weber_similarity in Hw'.\n}\nassert (Hweb : weber_calc (multi_support obs) == sim w).\n{\n  unfold obs. rewrite multi_support_map by auto. unfold f. cbn -[equiv config_list get_location].\n  foldR2. fold sim. rewrite <-map_map. change (List.map get_location (config_list config)) with (pos_list config).\n  apply Hw_sim, weber_calc_correct.\n}\nrewrite Hweb. cbn -[equiv config_list straight_path get_location].\nrewrite Bijection.retraction_section. reflexivity.\nQed.\n\n(* This is the property : all robots stay where they are. \n * This is what should be verified in the initial configuration. *)\nDefinition config_stay (config : configuration) : Prop := \n  forall id, let '(start, dest, _) := config id in dest == start.\n\nLocal Instance config_stay_compat : Proper (equiv ==> iff) config_stay.\nProof using . \nintros c c' Hc. unfold config_stay. \nassert (H : forall id, c id == c' id) by (intros id ; now specialize (Hc id)).\nsplit ; intros H1 id ; specialize (H1 id) ; specialize (H id) ;\n  destruct (c id) as [[s d] r] ; destruct (c' id) as [[s' d'] r'] ;\n  destruct H as [[Hs Hd] _] ; cbn -[equiv] in Hs, Hd.\n+ now rewrite <-Hs, <-Hd.\n+ now rewrite Hs, Hd.    \nQed.\n\n(* This is the property : all robots stay where they are OR \n * go towards point p. *)\nDefinition config_stay_or_go (config : configuration) p : Prop := \n  forall id, let '(start, dest, _) := config id in dest == start \\/ dest == p.\n\nLocal Instance config_stay_or_go_compat : Proper (equiv ==> equiv ==> iff) config_stay_or_go.\nProof using . \nintros c c' Hc p p' Hp. unfold config_stay_or_go. \nassert (H : forall id, c id == c' id) by (intros id ; now specialize (Hc id)).\nsplit ; intros H1 id ; specialize (H1 id) ; specialize (H id) ;\n  destruct (c id) as [[s d] r] ; destruct (c' id) as [[s' d'] r'] ;\n  destruct H as [[Hs Hd] _] ; cbn -[equiv] in Hs, Hd ; case H1 as [Hstay | Hgo].\n+ left. now rewrite <-Hs, <-Hd.\n+ right. now rewrite <-Hd, <-Hp.\n+ left. now rewrite Hs, Hd.\n+ right. now rewrite Hd, Hp.      \nQed.\n  \nLemma config_stay_impl_config_stg config :\n  config_stay config -> forall p, config_stay_or_go config p.\nProof using .\nunfold config_stay, config_stay_or_go. intros Hstay p i. specialize (Hstay i). \ndestruct (config i) as [[start dest] _]. now left.\nQed.\n\n(* This would have been much more pleasant to do with mathcomp's tuples. *)\nLemma config_list_InA_combine x x' c c' : \n  InA equiv (x, x') (combine (config_list c) (config_list c')) <-> \n  exists id, x == c id /\\ x' == c' id.\nProof using lt_0n.\nassert (g0 : G).\n{ change G with (fin n). apply (exist _ 0). lia. }\nsplit.\n+ intros Hin.\n  apply (@InA_nth (info * info) equiv (c (Good g0), c' (Good g0))) in Hin.\n  destruct Hin as [i [[y y'] [Hi [Hxy Hi']]]]. \n  rewrite combine_nth in Hi' by now repeat rewrite config_list_length. \n  inv Hi'. inv Hxy ; cbn -[equiv config_list] in * |-.\n  setoid_rewrite H. setoid_rewrite H0.\n  assert (i < n) as Hin.\n  { \n    eapply Nat.lt_le_trans ; [exact Hi|]. rewrite combine_length.\n    repeat rewrite config_list_length. rewrite Nat.min_id. cbn. lia. \n  }\n  pose (g := exist (fun x => x < n) i Hin).\n  change (fin n) with G in *. exists (Good g).\n  split ; rewrite config_list_spec, map_nth ; f_equiv ; unfold names ;\n    rewrite app_nth1, map_nth by (now rewrite map_length, Gnames_length) ;\n    f_equiv ; cbn ; change G with (fin n) ; apply nth_enum.  \n+ intros [[g|b] [Hx Hx']] ; [|byz_exfalso]. \n  assert (H : (x, x') == nth (proj1_sig g) (combine (config_list c) (config_list c')) (c (Good g0), c' (Good g0))).\n  { \n    rewrite combine_nth by now repeat rewrite config_list_length.\n    destruct g as [g Hg].\n    repeat rewrite config_list_spec, map_nth. unfold names.\n    repeat rewrite app_nth1, map_nth by now rewrite map_length, Gnames_length.\n    split ; cbn -[equiv].\n    * rewrite Hx. repeat f_equiv. change G with (fin n). erewrite nth_enum. reflexivity.\n    * rewrite Hx'. repeat f_equiv. change G with (fin n). erewrite nth_enum. reflexivity.\n  }\n  rewrite H. apply nth_InA ; autoclass. rewrite combine_length. repeat rewrite config_list_length.\n  rewrite Nat.min_id. cbn. destruct g. cbn. lia.\nQed.\n\nLemma pos_list_InA_combine x x' c c' : \n  InA equiv (x, x') (combine (pos_list c) (pos_list c')) <-> \n  exists id, x == get_location (c id) /\\ x' == get_location (c' id).\nProof using lt_0n.\nunfold pos_list. rewrite combine_map. rewrite (@InA_map_iff _ _ equiv equiv) ; autoclass.\n+ split.\n  - intros [[y y'] [[Hx Hx'] Hin]]. cbn -[equiv get_location] in Hx, Hx'.\n    rewrite config_list_InA_combine in Hin. destruct Hin as [id [Hy Hy']].\n    exists id. rewrite <-Hy, <-Hy', Hx, Hx'. auto.\n  - intros [id [Hx Hx']].\n    exists (c id, c' id). rewrite <-Hx, Hx'. split ; [auto|].\n    rewrite config_list_InA_combine. exists id. auto.\n+ intros [? ?] [? ?] [H1 H2]. cbn -[equiv] in H1, H2. split ; cbn -[equiv get_location].\n  - now rewrite H1.\n  - now rewrite H2.\nQed. \n\nLemma pos_list_InA x c : \n  InA equiv x (pos_list c) <-> exists id, x == get_location (c id).\nProof using . \nunfold pos_list. rewrite (@InA_map_iff _ _ equiv equiv) ; autoclass.\n+ split.\n  - intros [y [Hx Hin]]. foldR2. rewrite config_list_InA in Hin.\n    destruct Hin as [id Hy]. exists id. now rewrite <-Hx, <-Hy.   \n  - intros [id Hx]. exists (c id). rewrite <-Hx. split ; [auto|].\n    foldR2. rewrite config_list_InA. exists id. auto. \n+ foldR2. apply get_location_compat.\nQed. \n\n    \n(* This is the main invariant : the robots are alway headed towards the unique weber point. *)\nDefinition invariant w config : Prop := \n  config_stay_or_go config w /\\ OnlyWeber (pos_list config) w. \n\nLocal Instance invariant_compat : Proper (equiv ==> equiv ==> iff) invariant.\nProof using . intros w w' Hw c c' Hc. unfold invariant. now rewrite Hc, Hw. Qed. \n\n(* A technical lemma used to prove the fact that the configuration always\n * contracts towards the weber point. *)\nLemma segment_progress a b r1 r2 : \n  segment b (straight_path a b r1) (straight_path a b (add_ratio r1 r2)).\nProof using .\nassert (Hr1 := ratio_bounds r1).\nassert (Hr2 := ratio_bounds r2).  \nunfold add_ratio. case (Rle_dec R1 (r1 + r2)) as [Hle | HNle].\n+ rewrite straight_path_1. apply segment_start.\n+ change R1 with 1%R in HNle. cbn -[mul opp RealVectorSpace.add].\n unfold segment. exists (r2 / (1 - r1))%R. split.\n - split ; [apply Rdiv_le_0_compat | apply Rdiv_le_1] ; lra.\n - apply mul_reg_l with (1 - r1)%R ; [lra|].\n   repeat rewrite (mul_distr_add (1 - r1)). repeat rewrite mul_morph.\n   unfold Rdiv. rewrite <-Rmult_assoc, Rinv_r_simpl_m by lra.\n   rewrite Rmult_minus_distr_l, Rmult_1_r, <-Rmult_assoc, Rinv_r_simpl_m by lra.\n   assert (H : (a + r1 * (b - a) == r1 * b + (1 - r1) * a)%VS).\n   { unfold Rminus. rewrite mul_distr_add, <-add_morph, mul_1, 2 RealVectorSpace.add_assoc.\n     rewrite minus_morph, mul_opp. f_equiv. rewrite RealVectorSpace.add_comm. reflexivity. }\n   rewrite H, (RealVectorSpace.add_comm ((1 - r1) * a)), 2 mul_distr_add.\n   rewrite <-RealVectorSpace.add_assoc, (RealVectorSpace.add_assoc (r2 * b)). f_equiv.\n   * rewrite mul_morph, add_morph. f_equiv. lra.\n   * rewrite mul_opp, <-minus_morph, add_morph, mul_morph. f_equiv. lra. \nQed.\n\n(* The invariant is preserved. *)\nLemma round_preserves_invariant config da w : similarity_da_prop da -> \n  invariant w config -> invariant w (round gatherW da config).\nProof using lt_0n.\nunfold invariant. intros Hsim [Hstg Hweb]. destruct (round_simplify config Hsim Hweb) as [r Hround].\nsplit.\n+ rewrite Hround. intros i. destruct_match ; [now right|].\n  specialize (Hstg i). cbn -[equiv]. now destruct (config i) as [[s d] _].   \n+ revert Hweb. apply weber_contract_unique. unfold contract. \n  rewrite Forall2_Forall, Forall_forall by (now unfold pos_list ; repeat rewrite map_length, config_list_length).\n  intros [x x'] Hin. apply (@In_InA _ equiv) in Hin ; autoclass.\n  rewrite pos_list_InA_combine in Hin. destruct Hin as [id [Hx Hx']].\n  rewrite Hx, Hx', (Hround id).\n  destruct_match.\n  (* Activated robots don't move. *)\n  * destruct (config id) as [[s d] ri]. cbn -[straight_path RealVectorSpace.add opp].\n    rewrite straight_path_0. apply segment_end.\n  (* Inactive robots move along a straight line towards w. *)\n  * cbn -[straight_path mul opp RealVectorSpace.add]. \n    specialize (Hstg id). destruct (config id) as [[s d] ri].\n    case Hstg as [Hstay | Hgo].\n    --rewrite Hstay, 2 straight_path_same. apply segment_end.\n    --rewrite Hgo. apply segment_progress.\nQed.\n\n(* If the robots are gathered at the weber point, they don't move. *)\nLemma round_preserves_gathered config da w : \n  similarity_da_prop da -> invariant w config ->\n  gathered_at w config -> gathered_at w (round gatherW da config).\nProof using .\nintros Hsim [Hstg Hweb] Hgather g. destruct (round_simplify config Hsim Hweb) as [r Hround].\nrewrite (Hround (Good g)). destruct_match.\n+ rewrite Hgather. cbn -[equiv straight_path]. now rewrite straight_path_same.\n+ cbn -[equiv straight_path]. specialize (Hstg (Good g)). specialize (Hgather g). \n  destruct (config (Good g)) as [[s d] rg]. cbn -[straight_path equiv] in Hgather.\n  case Hstg as [Hstay | Hgo].\n  - rewrite Hstay in *. now rewrite straight_path_same in *.\n  - rewrite Hgo in *. rewrite straight_path_end in Hgather.\n    case Hgather as [Hsw | Hrg].\n    * now rewrite Hsw, straight_path_same.\n    * unfold add_ratio. destruct_match.\n      ++ now rewrite straight_path_1.\n      ++exfalso. change R1 with 1%R in *. rewrite Hrg in *. \n        generalize (ratio_bounds (r (Good g))). lra.\nQed.\n    \nLemma gathered_over config d w : \n  Stream.forever (Stream.instant similarity_da_prop) d -> \n  invariant w config -> \n  gathered_at w config -> \n  Gather w (execute gatherW d config).\nProof using lt_0n. \nrevert config d.\ncofix Hind. intros config d Hsim Hinv Hgather. constructor.\n+ cbn. exact Hgather.\n+ cbn. apply Hind.\n  - apply Hsim.\n  - now apply round_preserves_invariant ; [apply Hsim|].\n  - now apply round_preserves_gathered ; [apply Hsim| |].\nQed.   \n\n(* We say that a robot is looping when its start and destination points are equal. *)\nDefinition is_looping (robot : info) : bool := \n  if get_start robot =?= get_destination robot then true else false.\n\nLocal Instance is_looping_compat : Proper (equiv ==> eq) is_looping. \nProof using . intros [[? ?] ?] [[? ?] ?] [[H1 H2] _]. cbn -[equiv] in *. now rewrite H1, H2. Qed.     \n\nLemma is_looping_ratio start dest r1 r2 : \n  is_looping (start, dest, r1) = is_looping (start, dest, r2).\nProof using . now unfold is_looping. Qed. \n\n(* Boolean function to test whether a robot is on a point. *)\nDefinition is_on x (robot : info) : bool :=\n  if get_location robot =?= x then true else false.\n\nLocal Instance is_on_compat : Proper (equiv ==> equiv ==> eq) is_on.\nProof using . \nintros ? ? H1 ? ? H2. unfold is_on. \nrepeat destruct_match ; rewrite H1, H2 in * ; intuition. \nQed.\n\nDefinition BtoR : bool -> R := fun b => if b then 1%R else 0%R.\n\n(* This measure counts how many robots are [not on the weber point] and [looping]. *)\nDefinition measure_loop_nonweb config : R :=\n  let w := weber_calc (pos_list config) in\n  list_sum (List.map \n    (fun r => BtoR (is_looping r && negb (is_on w r))) \n    (config_list config)).\n\n(* This measure counts how many robots are not [looping on the weber point]. *)\nDefinition measure_loop_web config : R :=\n  let w := weber_calc (pos_list config) in\n  list_sum (List.map \n    (fun r => BtoR (negb (is_looping r && is_on w r)))\n    (config_list config)).\n\n(* This measure counts the total distance from the weber point to \n * the last update position of each robot. \n * RMK : this is NOT the distance from the weber point to the \n * current position of each robot. *)\nDefinition measure_dist config : R := \n  dist_sum \n    (List.map get_start (config_list config)) \n    (weber_calc (pos_list config)).\n\n(* The resulting measure is well-founded, and decreases whenever a robot is activated. *)\nDefinition measure config : R := \n  measure_loop_nonweb config + measure_loop_web config + measure_dist config.\n\nLocal Instance measure_compat : Proper (equiv ==> equiv) measure.\nProof using . \nintros c c' Hc. unfold measure.\nf_equiv ; [f_equiv|].\n+ unfold measure_loop_nonweb. apply list_sum_compat, eqlistA_PermutationA. \n  f_equiv ; [| now rewrite Hc].\n  intros i i' Hi. now rewrite Hi, Hc.\n+ unfold measure_loop_web. apply list_sum_compat, eqlistA_PermutationA. \n  f_equiv ; [| now rewrite Hc].\n  intros i i' Hi. now rewrite Hi, Hc.\n+ unfold measure_dist. f_equiv ; [|now rewrite Hc]. apply eqlistA_PermutationA. \n  apply map_eqlistA_compat with equiv ; autoclass.\n  now rewrite Hc.\nQed.\n\n(* The measure is trivially non-negative. *)\nLemma measure_nonneg config : (0 <= measure config)%R.\nProof using .\nunfold measure. repeat apply Rplus_le_le_0_compat.\n+ apply list_sum_ge_0. rewrite Forall_map, Forall_forall.\n  intros x _. unfold BtoR. destruct_match ; lra.\n+ apply list_sum_ge_0. rewrite Forall_map, Forall_forall.\n  intros x _. unfold BtoR. destruct_match ; lra.\n+ unfold measure_dist. apply list_sum_ge_0. rewrite Forall_map, Forall_forall.\n  intros x _. apply dist_nonneg.   \nQed.\n\nSection MeasureDecreaseLemmas.\nVariables (config : configuration) (da : demonic_action) (w : location).\nHypothesis (Hsim : similarity_da_prop da).\nHypothesis (Hinv : invariant w config).\n\nLemma HRinv : invariant w (round gatherW da config).\nProof using Hinv Hsim lt_0n. now apply round_preserves_invariant. Qed. \n\nLemma HRw : w == weber_calc (pos_list (round gatherW da config)).\nProof using Hinv Hsim lt_0n.\nsymmetry. apply HRinv, weber_calc_correct. \nQed.\n\nLemma Hw : w == weber_calc (pos_list config).\nProof using Hinv Hsim. \nsymmetry. apply Hinv, weber_calc_correct. \nQed. \n\nLemma BtoR_le b1 b2 : (b1 = true -> b2 = true) <-> (BtoR b1 <= BtoR b2)%R.\nProof using . unfold BtoR. repeat destruct_match ; lra. Qed.\n\nLemma BtoR_le_1 b1 b2 : (b1 = false /\\ b2 = true) <-> (BtoR b1 <= BtoR b2 - 1)%R.\nProof using . unfold BtoR. repeat destruct_match ; lra. Qed.\n\nLemma weber_dist_decreases id :\n  (dist w (get_start (round gatherW da config id)) <= dist w (get_start (config id)))%R.\nProof using Hinv Hsim. \ndestruct Hinv as [Hstg Hweb].\ndestruct (round_simplify config Hsim Hweb) as [r Hround].\nrewrite (Hround id). destruct_match. \n+ cbn -[dist straight_path]. specialize (Hstg id).\n  destruct (config id) as [[s d] ri]. cbn [get_start].\n  case Hstg as [Hstay | Hgo].\n  - rewrite Hstay, straight_path_same. reflexivity.\n  - rewrite Hgo. rewrite straight_path_dist_end, dist_sym. \n    rewrite <-Rmult_1_l. apply Rmult_le_compat_r ; [apply dist_nonneg|].\n    generalize (ratio_bounds ri). lra.\n+ cbn -[dist straight_path]. destruct (config id) as [[s d] ri]. cbn [get_start]. reflexivity.\nQed.\n\nLemma weber_dist_decreases_strong id :\n  activate da id = true -> \n  get_destination (config id) == w ->\n  get_location (config id) =/= w ->\n  flex_da_prop da ->\n  (dist w (get_start (round gatherW da config id)) <= dist w (get_start (config id)) - delta)%R.\nProof using Hinv Hsim.\nintros Hact Hdest Hloc Hflex. specialize (Hflex id config Hact).\ndestruct Hinv as [Hstg Hweb].\ndestruct (round_simplify config Hsim Hweb) as [r Hround]. rewrite (Hround id). \nfoldR2. change FrameChoiceSimilarity with FrameC in *. destruct_match_eq H ; [|intuition]. \ncbn -[dist straight_path]. specialize (Hstg id).\ndestruct (config id) as [[s d] ri]. cbn -[dist equiv straight_path] in Hdest, Hloc, Hflex |- *.\ncase Hstg as [Hstay | Hgo].\n+ exfalso. rewrite Hstay, straight_path_same in *. intuition.\n+ rewrite Hgo in *. case Hflex as [Hreached | Hdelta] ; [intuition|].\n  transitivity (dist w s - dist s (straight_path s w ri))%R.\n  - rewrite straight_path_dist_end, straight_path_dist_start, <-(Rmult_1_l (dist w s)), dist_sym.\n    rewrite <-Rmult_minus_distr_r. reflexivity.\n  - unfold Rminus. apply Rplus_le_compat_l, Ropp_le_contravar. exact Hdelta.\nQed.\n  \nLemma measure_dist_decreases : \n  (measure_dist (round gatherW da config) <= measure_dist config)%R.\nProof using Hinv Hsim lt_0n. \napply list_sum_le. rewrite Forall2_Forall by (now repeat rewrite map_length ; repeat rewrite config_list_length).\nrewrite combine_map, Forall_map, Forall_forall.\nintros [x' x] Hin. apply (@In_InA _ equiv) in Hin ; autoclass.\nrewrite combine_map, (@InA_map_iff _ _ equiv equiv) in Hin ; autoclass.\n+ destruct Hin as [[y' y] [[Hy' Hy] Hin]]. cbn -[equiv] in Hy, Hy'.\n  rewrite config_list_InA_combine in Hin. destruct Hin as [id [Hx' Hx]].\n  rewrite <-Hw, <-HRw, <-Hy, <-Hy', Hx, Hx'. apply weber_dist_decreases ; auto.\n+ intros [? ?] [? ?] [H1 H2]. now rewrite H1, H2.\nQed.\n\nLemma contra_bool b1 b2 : (b2 = true -> b1 = true) -> (negb b1 = true -> negb b2 = true).\nProof using . case b1 ; case b2 ; intuition. Qed.\n\nLemma loop_web_decreases id : \n  (BtoR (negb (is_looping (round gatherW da config id) && is_on w (round gatherW da config id))) <=  \n  BtoR (negb (is_looping (config id) && is_on w (config id))))%R.\nProof using Hinv Hsim. \ndestruct Hinv as [Hstg Hweb]. specialize (Hstg id).\napply BtoR_le. apply contra_bool. rewrite 2 andb_true_iff. intros [Hloop Hon]. revert Hloop Hon.\ndestruct (round_simplify config Hsim Hweb) as [r Hround]. rewrite (Hround id).\ndestruct_match.\n+ unfold is_looping, is_on. cbn -[straight_path equiv_dec].\n  destruct (config id) as [[s d] ri]. cbn [get_start get_destination].\n  rewrite straight_path_0. intuition.\n+ unfold is_looping, is_on. cbn -[straight_path equiv_dec]. \n  destruct (config id) as [[s d] ri]. cbn [get_start get_destination].\n  repeat (case ifP_sumbool ; try now intuition).\n  intros H1 H2 Hsd. exfalso. revert H1 H2. rewrite Hsd, 2 straight_path_same.\n  now intuition.\nQed.\n\nLemma loop_web_decreases_strong id :\n  activate da id = true -> \n  get_location (config id) == w -> \n  get_start (config id) =/= w ->\n  (BtoR (negb (is_looping (round gatherW da config id) && is_on w (round gatherW da config id))) <=  \n  BtoR (negb (is_looping (config id) && is_on w (config id))) - 1)%R.\nProof using Hinv Hsim.\ndestruct Hinv as [Hstg Hweb]. specialize (Hstg id).\nintros Hact Hloc Hstart. apply BtoR_le_1. \nrewrite negb_true_iff, negb_false_iff, andb_true_iff, andb_false_iff.\ndestruct (round_simplify config Hsim Hweb) as [r Hround]. rewrite (Hround id).\nfoldR2. change FrameChoiceSimilarity with FrameC.\nrevert Hact. case ifP_bool ; [intros Hact _ | discriminate].\nrevert Hloc Hstart. unfold is_looping, is_on. cbn -[straight_path equiv equiv_dec].\ndestruct (config id) as [[s d] ri]. cbn [get_start get_destination].\ncase Hstg as [Hstay | Hgo].\n+ rewrite Hstay. repeat rewrite straight_path_same. intuition.\n+ rewrite Hgo. rewrite straight_path_0. intros -> Hsw.\n  repeat (case ifP_sumbool ; try now intuition).\nQed.\n\nLemma measure_loop_web_decreases : \n  (measure_loop_web (round gatherW da config) <= measure_loop_web config)%R.\nProof using Hinv Hsim lt_0n. \napply list_sum_le. rewrite Forall2_Forall by (now repeat rewrite map_length ; repeat rewrite config_list_length).\nrewrite combine_map, Forall_map, Forall_forall.\nintros [x' x] Hin. apply (@In_InA _ equiv) in Hin ; autoclass.\nrewrite config_list_InA_combine in Hin. destruct Hin as [id [Hx' Hx]].\nrewrite <-Hw, <-HRw, Hx, Hx'. apply loop_web_decreases ; auto.\nQed.\n\nLemma loop_nonweb_decreases id :\n  (BtoR (is_looping (round gatherW da config id) && negb (is_on w (round gatherW da config id))) <=\n  BtoR (is_looping (config id) && negb (is_on w (config id))))%R.\nProof using Hinv Hsim.\ndestruct Hinv as [Hstg Hweb]. specialize (Hstg id).\napply BtoR_le. rewrite 2 andb_true_iff, 2 negb_true_iff.\nintros [Hloop Hon]. revert Hloop Hon.\ndestruct (round_simplify config Hsim Hweb) as [r Hround]. rewrite (Hround id).\ndestruct_match.\n+ unfold is_looping, is_on. cbn -[straight_path equiv_dec].\n  destruct (config id) as [[s d] ri]. cbn [get_start get_destination].\n  rewrite straight_path_0. intros ->. intuition.\n+ unfold is_looping, is_on. cbn -[straight_path equiv_dec].\n  destruct (config id) as [[s d] ri]. cbn [get_start get_destination].\n  case ifP_sumbool ; case ifP_sumbool ; try discriminate.\n  intros H1 Hsd _ _. split ; [intuition|]. revert H1. rewrite Hsd, 2 straight_path_same.\n  case ifP_sumbool ; intuition.\nQed.\n\nLemma loop_nonweb_decreases_strong id :\n  activate da id = true -> \n  get_destination (config id) =/= w -> \n  (BtoR (is_looping (round gatherW da config id) && negb (is_on w (round gatherW da config id))) <=\n  BtoR (is_looping (config id) && negb (is_on w (config id))) - 1)%R.\nProof using Hinv Hsim. \ndestruct Hinv as [Hstg Hweb]. specialize (Hstg id).\nintros Hact Hdest. apply BtoR_le_1. \nrewrite andb_true_iff, andb_false_iff, negb_false_iff, negb_true_iff.\ndestruct (round_simplify config Hsim Hweb) as [r Hround]. rewrite (Hround id).\nfoldR2. change FrameChoiceSimilarity with FrameC. \nrevert Hact. case ifP_bool ; [|discriminate].\nrevert Hdest. unfold is_looping, is_on. cbn -[straight_path equiv equiv_dec].\ndestruct (config id) as [[s d] ri]. cbn [get_start get_destination].\nrewrite straight_path_0. \ncase Hstg as [Hstay | Hgo].\n+ rewrite Hstay. repeat rewrite straight_path_same. repeat destruct_match ; intuition.\n+ intuition.\nQed.\n\nLemma measure_loop_nonweb_decreases : \n  (measure_loop_nonweb (round gatherW da config) <= measure_loop_nonweb config)%R.\nProof using Hinv Hsim lt_0n. \napply list_sum_le. rewrite Forall2_Forall by (now repeat rewrite map_length ; repeat rewrite config_list_length).\nrewrite combine_map, Forall_map, Forall_forall.\nintros [x' x] Hin. apply (@In_InA _ equiv) in Hin ; autoclass.\nrewrite config_list_InA_combine in Hin. destruct Hin as [id [Hx' Hx]].\nrewrite <-Hw, <-HRw, Hx, Hx'. apply loop_nonweb_decreases ; auto.\nQed.\n\nEnd MeasureDecreaseLemmas.\n    \nLemma In_InA_is_leibniz {A : Type} (eqA : relation A) x l : \n  (forall x y, eqA x y <-> x = y) -> (InA eqA x l <-> List.In x l).\nProof using . \nintros H. induction l as [|y l IH].\n+ cbn. split ; [intros Hnil ; inv Hnil | intuition].\n+ cbn. split.\n  - intros HinA. rewrite InA_cons in HinA. destruct HinA as [Heq | HinA].\n    * left. symmetry. now rewrite <-H.\n    * right. now rewrite <-IH.\n  - intros [Heq | Hin].\n    * apply InA_cons_hd. now rewrite H.\n    * apply InA_cons_tl. now rewrite IH.\nQed.\n\nLemma round_decrease_measure config da w :\n  similarity_da_prop da ->\n  invariant w config ->\n    (measure (round gatherW da config) <= measure config)%R. \nProof using lt_0n.\nintros Hsim Hinv.\nunfold measure. repeat apply Rplus_le_compat.\n+ apply measure_loop_nonweb_decreases with w ; auto.\n+ apply measure_loop_web_decreases with w ; auto.\n+ apply measure_dist_decreases with w ; auto.\nQed. \n \nLemma Rplus_le_compat3_1 x y z x' y' z' eps : \n  (x <= x' - eps)%R -> (y <= y')%R -> (z <= z')%R -> (x + y + z <= x' + y' + z' - eps)%R.\nProof using . lra. Qed.\n\nLemma Rplus_le_compat3_2 x y z x' y' z' eps : \n  (x <= x')%R -> (y <= y' - eps)%R -> (z <= z')%R -> (x + y + z <= x' + y' + z' - eps)%R.\nProof using . lra. Qed.\n\nLemma Rplus_le_compat3_3 x y z x' y' z' eps : \n  (x <= x')%R -> (y <= y')%R -> (z <= z' - eps)%R -> (x + y + z <= x' + y' + z' - eps)%R.\nProof using . lra. Qed. \n\n\n(* If a robot that is not [looping on the weber point] is activated, \n * the measure strictly decreases. *)\nLemma round_decreases_measure_strong config da w : \n  similarity_da_prop da -> \n  flex_da_prop da ->\n  invariant w config -> \n  (exists id, activate da id = true /\\ is_looping (config id) && is_on w (config id) = false) -> \n    (measure (round gatherW da config) <= measure config - Rmin delta 1)%R.\nProof using lt_0n. \nintros Hsim Hflex Hinv [id [Hact Hnlw]].\nassert (H := Hinv). destruct H as [Hstg Hweb]. specialize (Hstg id). \nassert (HRw : w == weber_calc (pos_list (round gatherW da config))).\n{ symmetry. apply (round_preserves_invariant Hsim Hinv). apply weber_calc_correct. }\nassert (Hw : w == weber_calc (pos_list config)).\n{ symmetry. apply Hinv. apply weber_calc_correct. }\nrewrite andb_false_iff in Hnlw. \ncase (Sumbool.sumbool_of_bool (is_looping (config id))) as [Hloop | HNloop]. \n+ destruct Hnlw as [HNloop | HNon] ; [now rewrite Hloop in HNloop |].\n  transitivity (measure config - 1)%R ; [|generalize (Rmin_r delta 1%R) ; lra].\n  apply Rplus_le_compat3_1 ; [| eapply measure_loop_web_decreases ; eauto | eapply measure_dist_decreases ; eauto].\n  apply list_sum_le_eps ; rewrite <-Hw, <-HRw.\n  * rewrite Forall2_Forall, combine_map, Forall_map, Forall_forall \n      by now repeat rewrite map_length, config_list_length.\n    intros [x' x] Hin. apply (@In_InA _ equiv) in Hin ; autoclass.\n    rewrite config_list_InA_combine in Hin. destruct Hin as [id' [-> ->]].\n    now apply loop_nonweb_decreases.\n  * pose (f := fun r0 => BtoR (is_looping r0 && negb (is_on w r0))). fold f. \n    rewrite Exists_exists, combine_map.\n    setoid_rewrite <-(@In_InA_is_leibniz _ equiv) ; autoclass.\n    setoid_rewrite (@InA_map_iff _ _ equiv equiv) ; autoclass.\n    ++eexists (?[x], ?[x']). \n      split. \n      --exists (round gatherW da config id, config id). split ; [reflexivity|].\n        rewrite config_list_InA_combine. now exists id.\n      --unfold f. apply loop_nonweb_decreases_strong ; auto.\n        destruct (config id) as [[s d] ri]. revert HNon Hloop. unfold is_on, is_looping.\n        case ifP_sumbool ; case ifP_sumbool ; try discriminate.\n        cbn -[equiv straight_path]. intros ->. now rewrite straight_path_same.\n    ++intros [? ?] [? ?] [H1 H2]. unfold f. rewrite H1, H2. reflexivity.\n    ++intros [? ?] [? ?]. split ; auto.\n+ unfold is_looping in HNloop. destruct (config id) as [[s d] r] eqn:Econfig. simpl in HNloop.\n  case (s =?= d) as [Hsd | Hsd] ; [exfalso ; revert HNloop ; destruct_match ; intuition |].\n  case Hstg as [Hstay | Hgo] ; [intuition|]. clear HNloop.\n  case (get_location (config id) =?= w) as [HReached | HNreached].\n  - transitivity (measure config - 1)%R ; [|generalize (Rmin_r delta 1%R) ; lra].\n    apply Rplus_le_compat3_2 ; [eapply measure_loop_nonweb_decreases ; eauto | | eapply measure_dist_decreases ; eauto].\n    apply list_sum_le_eps ; rewrite <-Hw, <-HRw.\n    * rewrite Forall2_Forall, combine_map, Forall_map, Forall_forall \n        by now repeat rewrite map_length, config_list_length.\n      intros [x' x] Hin. apply (@In_InA _ equiv) in Hin ; autoclass.\n      rewrite config_list_InA_combine in Hin. destruct Hin as [id' [-> ->]].\n      now apply loop_web_decreases.\n    * pose (f := fun r0 => BtoR (negb (is_looping r0 && is_on w r0))). fold f. \n      rewrite Exists_exists, combine_map.\n      setoid_rewrite <-(@In_InA_is_leibniz _ equiv) ; autoclass.\n      setoid_rewrite (@InA_map_iff _ _ equiv equiv) ; autoclass.\n      ++eexists (?[x], ?[x']). \n        split. \n        --exists (round gatherW da config id, config id). split ; [reflexivity|].\n          rewrite config_list_InA_combine. now exists id.\n        --unfold f. apply loop_web_decreases_strong ; auto. now rewrite Econfig, <-Hgo.\n      ++intros [? ?] [? ?] [H1 H2]. unfold f. rewrite H1, H2. reflexivity.\n      ++intros [? ?] [? ?] ; split ; auto.\n  - transitivity (measure config - delta)%R ; [|generalize (Rmin_l delta 1%R) ; lra].\n    apply Rplus_le_compat3_3 ; [eapply measure_loop_nonweb_decreases ; eauto | eapply measure_loop_web_decreases ; eauto |].\n    apply list_sum_le_eps ; rewrite <-Hw, <-HRw.\n    * rewrite Forall2_Forall, 2 map_map, combine_map, Forall_map, Forall_forall \n        by now repeat rewrite map_map, map_length, config_list_length.\n      intros [x' x] Hin. apply (@In_InA _ equiv) in Hin ; autoclass.\n      rewrite config_list_InA_combine in Hin. destruct Hin as [id' [-> ->]].\n      now apply weber_dist_decreases.\n    * rewrite 2 map_map, Exists_exists, combine_map.\n      setoid_rewrite <-(@In_InA_is_leibniz _ equiv) ; autoclass.\n      setoid_rewrite (@InA_map_iff _ _ equiv equiv) ; autoclass.\n      ++eexists (?[x], ?[x']). \n        split. \n        --exists (round gatherW da config id, config id). split ; [reflexivity|].\n          rewrite config_list_InA_combine. now exists id.\n        --apply weber_dist_decreases_strong ; auto. now rewrite Econfig, <-Hgo.\n      ++intros [? ?] [? ?] [H1 H2]. rewrite H1, H2. reflexivity.\n      ++intros [? ?] [? ?] ; split ; auto.  \nQed.\n\n(* This inductive proposition counts how many turns are left before\n * a robot that isn't [looping on w] is activated.\n * This is analoguous to FirstMove in the SSYNC case. *)\nInductive FirstActivNLW w : demon -> configuration -> Prop :=\n  | FirstActivNLW_Now : forall d config id, \n    activate (Stream.hd d) id = true -> is_looping (config id) && is_on w (config id) = false -> \n      FirstActivNLW w d config\n  | FirstActivNLW_Later : forall d config,\n    FirstActivNLW w (Stream.tl d) (round gatherW (Stream.hd d) config) -> \n      FirstActivNLW w d config. \n    \n(* If the robots aren't gathered yet, there exists a robot that isn't [looping on w]. *)\nLemma exists_non_webloop config w : \n  ~gathered_at w config ->\n  invariant w config -> \n  exists id, is_looping (config id) && is_on w (config id) = false.\nProof using lt_0n. \nintros HNgather Hinv.\nassert (H := Forall_dec (fun id => is_looping (config id) && is_on w (config id) = true)).\nfeed H ; [intros id ; case (is_looping (config id) && is_on w (config id)) ; intuition |].\ncase (H names) as [HT | HF] ; clear H.\n+ exfalso. apply HNgather. unfold gathered_at. \n  rewrite Forall_forall in HT. intros g.\n  specialize (HT (Good g)). feed HT ; [apply In_names |].\n  rewrite andb_true_iff in HT. destruct HT as [_ Hon].\n  revert Hon. unfold is_on. case ifP_sumbool ; try discriminate. auto. \n+ rewrite <-Exists_Forall_neg, Exists_exists in HF.\n  - destruct HF as [id [_ Hnwl]]. apply not_true_is_false in Hnwl. \n    now exists id.\n  - intros id. tauto.\nQed.\n\n(* Fairness entails that if the robots aren't gathered yet, \n * then a robot that isn't [looping on w] will eventually be activated. *)\nLemma non_webloop_will_activate config d w :\n  Stream.forever (Stream.instant similarity_da_prop) d ->\n  Fair d ->\n  ~gathered_at w config ->    \n  invariant w config -> \n  FirstActivNLW w d config.\nProof using lt_0n.\nintros Hsim Hfair HNgather Hinv.\ndestruct (exists_non_webloop HNgather Hinv) as [id Hnwl].\ndestruct Hfair as [Hlocallyfair Hfair]. specialize (Hlocallyfair id).\nclear HNgather. generalize dependent config.\ninduction Hlocallyfair as [d Hact | d HNact Hlater IH].\n+ intros config Hinv Hnwl.\n  apply FirstActivNLW_Now with id ; auto.\n+ intros config Hinv Hnwl.\n  apply FirstActivNLW_Later, IH.\n  - apply Hsim.\n  - apply Hfair.\n  - apply round_preserves_invariant ; [apply Hsim | apply Hinv].\n  - destruct Hsim as [Hsim_hd Hsim_tl]. \n    destruct Hinv as [Hstg Hweb].\n    destruct (round_simplify config Hsim_hd Hweb) as [r Hround].\n    rewrite (Hround id). destruct_match_eq Hact ; \n      [foldR2 ; rewrite Hact in HNact ; discriminate |].\n    cbn. destruct (config id) as [[start dest] ri].\n    rewrite andb_false_iff in Hnwl |- *.\n    rewrite (is_looping_ratio _ _ _ ri).\n    case Hnwl as [HNloop | HNon] ; [now left |].\n    case (start =?= dest) as [Hloop | HNloop] ; [right | left].\n    * revert HNon. cbn in Hloop. rewrite Hloop. unfold is_on. \n      cbn -[straight_path]. now rewrite 2 straight_path_same.\n    * unfold is_looping. destruct_match ; intuition.\nQed. \n\n(* This is the well founded relation we will perform induction on. *)\nDefinition lt_config eps c c' := \n  (0 <= measure c <= measure c' - eps)%R. \n\nLocal Instance lt_config_compat : Proper (equiv ==> equiv ==> equiv ==> iff) lt_config.\nProof using . intros e e' He c1 c1' Hc1 c2 c2' Hc2. unfold lt_config. now rewrite He, Hc1, Hc2. Qed.\n\n(* We proove this using the well-foundedness of lt on nat. *)\nLemma lt_config_wf eps : (eps > 0)%R -> well_founded (lt_config eps).\nProof using . \nintros Heps. unfold well_founded. intros c.\npose (f := fun x : R => Z.to_nat (up (x / eps))).\nremember (f (measure c)) as k. generalize dependent c. \npattern k. apply (well_founded_ind lt_wf). clear k.\nintros k IH c Hk. apply Acc_intro. intros c' Hc'. apply IH with (f (measure c')) ; auto.\nrewrite Hk ; unfold f ; unfold lt_config in Hc'.\nrewrite <-Z2Nat.inj_lt.\n+ apply Zup_lt. unfold Rdiv. rewrite <-(Rinv_r eps) by lra. \n  rewrite <-Rmult_minus_distr_r. apply Rmult_le_compat_r ; intuition.\n+ apply up_le_0_compat, Rdiv_le_0_compat ; intuition. \n+ apply up_le_0_compat, Rdiv_le_0_compat ; intuition.\n  transitivity eps ; intuition. \n  apply (Rplus_le_reg_r (- eps)). rewrite Rplus_opp_r. etransitivity ; eauto.\nQed.\n\n\n(* Notice that [invariant w config] is in the assumptions : \n * see the next theorem for the final assumptions. \n * The proof is essentially a well-founded induction on [measure config].\n * Fairness ensures that the measure must decrease at some point,\n * which leads to a second induction on [FirstMoveNLW w d config]. *)\nLemma weber_correct_aux w config d :\n  Fair d -> \n  invariant w config ->\n  Stream.forever (Stream.instant similarity_da_prop) d ->\n  Stream.forever (Stream.instant flex_da_prop) d ->\n  WillGather (execute gatherW d config).\nProof using lt_0n delta_g0.\nassert (Hdelta1 : (Rmin delta 1 > 0)%R).\n{ unfold Rmin. destruct_match ; lra. }\nrevert d.\ninduction config as [config IH] using (well_founded_ind (lt_config_wf Hdelta1)).\nintros d Hfair Hinv Hsim Hflex.\ncase (gathered_at_dec config w) as [Hgather | HNgather].\n{ apply Stream.Now. exists w. now apply gathered_over. }\ninduction (non_webloop_will_activate Hsim Hfair HNgather Hinv) as [d config id Hact Hnwl | d config Hnwl_later IHnwl].\n+ apply Stream.Later. apply IH ; auto.\n  - unfold lt_config. split ; [apply measure_nonneg|].\n    apply round_decreases_measure_strong with w ; auto.\n    * apply Hsim.\n    * apply Hflex.\n    * exists id. intuition.\n  - apply Hfair.  \n  - apply round_preserves_invariant ; [apply Hsim | auto].\n  - apply Hsim.\n  - apply Hflex.\n+ apply Stream.Later. \n  case (gathered_at_dec (round gatherW (Stream.hd d) config) w) as [HRgather | HRNgather].\n  - apply Stream.Now. exists w. apply gathered_over ; auto.\n    * apply Hsim.\n    * now apply round_preserves_invariant ; [apply Hsim|].\n  - apply IHnwl ; auto.\n    * intros c Hc. apply IH. unfold lt_config in Hc |- *.\n      split ; [apply measure_nonneg|].\n      etransitivity ; [apply Hc|].\n      unfold Rminus. apply Rplus_le_compat_r.\n      apply round_decrease_measure with w ; auto. apply Hsim.\n    * apply Hfair.\n    * apply round_preserves_invariant ; [apply Hsim | auto].\n    * apply Hsim. \n    * apply Hflex.\nQed.\n\n(* This is the main theorem. *)\nTheorem weber_correct config d :\n  Fair d -> \n  (* Initially, no robot is moving. *)\n  config_stay config -> \n  (* Initially, the configuration has a unique weber point *)\n  OnlyWeber (pos_list config) (weber_calc (pos_list config)) -> \n  (* The frame changes (chosen by the demon) are similarities centered on the observing robot. *)\n  Stream.forever (Stream.instant similarity_da_prop) d ->\n  (* We are in a flexible setting *)\n  Stream.forever (Stream.instant flex_da_prop) d ->\n  (* The robots will gather on the weber point (this is not explicit in this theorem). *)\n  WillGather (execute gatherW d config).\nProof using lt_0n delta_g0.\nintros Hfair Hstay Hsim Hflex. \napply weber_correct_aux with (weber_calc (pos_list config)) ; auto.\nnow split ; [apply config_stay_impl_config_stg|]. \nQed.\n\nEnd Gathering.", "meta": {"author": "MathisBD", "repo": "pactole_stage", "sha": "4b63da0898ae4f48956408dc31f7831d3ad8930f", "save_path": "github-repos/coq/MathisBD-pactole_stage", "path": "github-repos/coq/MathisBD-pactole_stage/pactole_stage-4b63da0898ae4f48956408dc31f7831d3ad8930f/CaseStudies/Gathering/InR2/Weber/Gather_flex_async.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6771596103832634}}
{"text": "Require Import prosa.classic.util.all.\nRequire Import prosa.classic.analysis.global.parallel.bertogna_edf_theory.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop div path.\n\nModule ResponseTimeIterationEDF.\n\n  Import ResponseTimeAnalysisEDF.\n\n  (* In this section, we define the algorithm for Bertogna and Cirinei's\n     response-time analysis for EDF scheduling with parallel jobs. *)\n  Section Analysis.\n    \n    Context {sporadic_task: eqType}.\n    Variable task_cost: sporadic_task -> time.\n    Variable task_period: sporadic_task -> time.\n    Variable task_deadline: sporadic_task -> time.\n\n    (* As input for each iteration of the algorithm, we consider pairs\n       of tasks and computed response-time bounds. *)\n    Let task_with_response_time := (sporadic_task * time)%type.\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 -> sporadic_task.\n\n    (* Consider a platform with num_cpus processors. *)  \n    Variable num_cpus: nat.\n\n    (* First, recall the jitter-aware interference bound for EDF, ... *)\n    Let I (rt_bounds: seq task_with_response_time)\n          (tsk: sporadic_task) (delta: time) :=\n      total_interference_bound_edf task_cost task_period task_deadline tsk rt_bounds delta.\n\n    (* ..., which yields the following response-time bound. *)\n    Definition edf_response_time_bound (rt_bounds: seq task_with_response_time)\n                                           (tsk: sporadic_task) (delta: time) :=\n      task_cost tsk + div_floor (I rt_bounds tsk delta) num_cpus.\n\n    (* Also note that a response-time is only valid if it is no larger\n       than the deadline. *)\n    Definition R_le_deadline (pair: task_with_response_time) :=\n      let (tsk, R) := pair in\n        R <= task_deadline tsk.\n\n    (* Next we define the fixed-point iteration for computing\n       Bertogna's response-time bound of a task set. *)\n    \n    (* Given a sequence 'rt_bounds' of task and response-time bounds\n       from the previous iteration, we compute the response-time\n       bound of a single task using the RTA for EDF. *)\n    Definition update_bound (rt_bounds: seq task_with_response_time)\n                        (pair : task_with_response_time) :=\n      let (tsk, R) := pair in\n        (tsk, edf_response_time_bound rt_bounds tsk R).\n\n    (* To compute the response-time bounds of the entire task set,\n       We start the iteration with a sequence of tasks and costs:\n       <(task1, cost1), (task2, cost2), ...>. *)\n    Let initial_state (ts: seq sporadic_task) :=\n      map (fun t => (t, task_cost t)) ts.\n\n    (* Then, we successively update the the response-time bounds based\n       on the slack computed in the previous iteration. *)\n    Definition edf_rta_iteration (rt_bounds: seq task_with_response_time) :=\n      map (update_bound rt_bounds) rt_bounds.\n\n    (* To ensure that the procedure converges, we run the iteration a\n       \"sufficient\" number of times: task_deadline tsk - task_cost tsk + 1.\n       This corresponds to the time complexity of the procedure. *)\n    Let max_steps (ts: seq sporadic_task) :=\n      \\sum_(tsk <- ts) (task_deadline tsk - task_cost tsk) + 1.\n\n    (* This yields the following definition for the RTA. At the end of\n       the iteration, we check if all computed response-time bounds\n       are less than or equal to the deadline, in which case they are\n       valid. *)\n    Definition edf_claimed_bounds (ts: seq sporadic_task) :=\n      let R_values := iter (max_steps ts) edf_rta_iteration (initial_state ts) in\n        if (all R_le_deadline R_values) then\n          Some R_values\n        else None.\n\n    (* The schedulability test simply checks if we got a list of\n       response-time bounds (i.e., if the computation did not fail). *)\n    Definition edf_schedulable (ts: seq sporadic_task) :=\n      edf_claimed_bounds ts != None.\n\n    (* In the following section, we prove several helper lemmas about the\n       list of tasks/response-time bounds. *)\n    Section SimpleLemmas.\n\n      (* Updating a single response-time bound does not modify the task. *)\n      Lemma edf_claimed_bounds_unzip1_update_bound :\n        forall l rt_bounds,\n          unzip1 (map (update_bound rt_bounds) l) = unzip1 l.\n      Proof.\n        induction l; first by done.\n        intros rt_bounds.\n        simpl; f_equal; last by done.\n        by unfold update_bound; desf.\n      Qed.\n\n      (* At any point of the iteration, the tasks are the same. *)\n      Lemma edf_claimed_bounds_unzip1_iteration :\n        forall l k,\n          unzip1 (iter k edf_rta_iteration (initial_state l)) = l.\n      Proof.\n        intros l k; clear -k.\n        induction k; simpl.\n        {\n          unfold initial_state.\n          induction l; first by done.\n          by simpl; rewrite IHl.\n        }\n        {\n          unfold edf_rta_iteration. \n          by rewrite edf_claimed_bounds_unzip1_update_bound.\n        }\n      Qed.\n\n      (* The iteration preserves the size of the list. *)\n      Lemma edf_claimed_bounds_size :\n        forall l k,\n          size (iter k edf_rta_iteration (initial_state l)) = size l.\n      Proof.\n        intros l k; clear -k.\n        induction k; simpl; first by rewrite size_map.\n        by rewrite size_map.\n      Qed.\n\n      (* If the analysis succeeds, the computed response-time bounds are no smaller\n         than the task cost. *)\n      Lemma edf_claimed_bounds_ge_cost :\n        forall l k tsk R,\n          (tsk, R) \\in (iter k edf_rta_iteration (initial_state l)) ->\n          R >= task_cost tsk.\n      Proof.\n        intros l k tsk R IN.\n        destruct k.\n        {\n          move: IN => /mapP IN; destruct IN as [x IN EQ]; inversion EQ.\n          by apply leqnn.\n        }\n        {\n          rewrite iterS in IN.\n          move: IN => /mapP IN; destruct IN as [x IN EQ].\n          unfold update_bound in EQ; destruct x; inversion EQ.\n          by unfold edf_response_time_bound; apply leq_addr.\n        }\n      Qed.\n\n      (* If the analysis suceeds, the computed response-time bounds are no larger\n         than the deadline. *)\n      Lemma edf_claimed_bounds_le_deadline :\n        forall ts rt_bounds tsk R,\n          edf_claimed_bounds ts = Some rt_bounds ->\n          (tsk, R) \\in rt_bounds ->\n          R <= task_deadline tsk.\n      Proof.\n        intros ts rt_bounds tsk R SOME PAIR; unfold edf_claimed_bounds in SOME.\n        destruct (all R_le_deadline (iter (max_steps ts)\n                                          edf_rta_iteration (initial_state ts))) eqn:DEADLINE;\n          last by done.\n        move: DEADLINE => /allP DEADLINE.\n        inversion SOME as [EQ]; rewrite -EQ in PAIR.\n        by specialize (DEADLINE (tsk, R) PAIR).\n      Qed.\n\n      (* The list contains a response-time bound for every task in the task set. *)\n      Lemma edf_claimed_bounds_has_R_for_every_task :\n        forall ts rt_bounds tsk,\n          edf_claimed_bounds ts = Some rt_bounds ->\n          tsk \\in ts ->\n          exists R,\n            (tsk, R) \\in rt_bounds.\n      Proof.\n        intros ts rt_bounds tsk SOME IN.\n        unfold edf_claimed_bounds in SOME.\n        destruct (all R_le_deadline (iter (max_steps ts) edf_rta_iteration (initial_state ts)));\n          last by done.\n        inversion SOME as [EQ]; clear SOME EQ.\n        generalize dependent tsk.\n        induction (max_steps ts) as [| step]; simpl in *.\n        {\n          intros tsk IN; unfold initial_state.\n          exists (task_cost tsk).\n          by apply/mapP; exists tsk.\n        }\n        {\n          intros tsk IN.\n          set prev_state := iter step edf_rta_iteration (initial_state ts).\n          fold prev_state in IN, IHstep.\n          specialize (IHstep tsk IN); des.\n          exists (edf_response_time_bound prev_state tsk R).\n          by apply/mapP; exists (tsk, R); [by done | by f_equal].\n        }\n      Qed.\n     \n    End SimpleLemmas.\n\n    (* In this section, we prove the convergence of the RTA procedure.\n       Since we define the RTA procedure as the application of a function\n       a fixed number of times, this translates into proving that the value\n       of the iteration at (max_steps ts) is equal to the value at (max_steps ts) + 1. *)\n    Section Convergence.\n\n      (* Consider any sequence of tasks with valid parameters. *)\n      Variable ts: seq sporadic_task.\n      Hypothesis H_valid_task_parameters:\n        valid_sporadic_taskset task_cost task_period task_deadline ts.\n      \n      (* To simplify, let f denote the RTA procedure. *)\n      Let f (k: nat) := iter k edf_rta_iteration (initial_state ts).\n\n      (* Since the iteration is applied directly to a list of tasks and response-times,\n         we define a corresponding relation \"<=\" over those lists. *)\n\n      (* Let 'all_le' be a binary relation over lists of tasks/response-time bounds.\n         It states that every element of list l1 has a response-time bound R that is less\n         than or equal to the corresponding response-time bound R' in list l2 (point-wise).\n         In addition, the relation states that the tasks of both lists are unchanged. *)\n      Let all_le := fun (l1 l2: list task_with_response_time) =>\n        (unzip1 l1 == unzip1 l2) &&\n        all (fun p => (snd (fst p)) <= (snd (snd p))) (zip l1 l2).\n\n      (* Similarly, we define a strict version of 'all_le' called 'one_lt', which states that\n         there exists at least one element whose response-time bound increases. *)\n      Let one_lt := fun (l1 l2: list task_with_response_time) =>\n        (unzip1 l1 == unzip1 l2) &&\n        has (fun p => (snd (fst p)) < (snd (snd p))) (zip l1 l2).\n\n      (* Next, we prove some basic properties about the relation all_le. *)\n      Section RelationProperties.\n\n        (* The relation is reflexive, ... *)\n        Lemma all_le_reflexive : reflexive all_le.\n        Proof.\n          intros l; unfold all_le; rewrite eq_refl andTb.\n          destruct l; first by done.\n          by apply/(zipP t (fun x y => snd x <= snd y)).\n        Qed.\n\n        (* ... and transitive. *)\n        Lemma all_le_transitive: transitive all_le.\n        Proof.\n          unfold transitive, all_le.\n          move => y x z /andP [/eqP ZIPxy LExy] /andP [/eqP ZIPyz LEyz].\n          apply/andP; split; first by rewrite ZIPxy -ZIPyz.\n          move: LExy => /(zipP _ (fun x y => snd x <= snd y)) LExy.\n          move: LEyz => /(zipP _ (fun x y => snd x <= snd y)) LEyz.\n          assert (SIZExy: size (unzip1 x) = size (unzip1 y)).\n            by rewrite ZIPxy.\n          assert (SIZEyz: size (unzip1 y) = size (unzip1 z)).\n            by rewrite ZIPyz.\n          rewrite 2!size_map in SIZExy; rewrite 2!size_map in SIZEyz.\n          destruct y.\n          {\n            apply size0nil in SIZExy; symmetry in SIZEyz.\n            by apply size0nil in SIZEyz; subst.\n          }\n          apply/(zipP t (fun x y => snd x <= snd y));\n            first by rewrite SIZExy -SIZEyz. \n          intros i LTi.\n          exploit LExy; first by rewrite SIZExy.\n          {\n            rewrite size_zip -SIZEyz -SIZExy minnn in LTi.\n            by rewrite size_zip -SIZExy minnn; apply LTi.\n          }\n          instantiate (1 := t); intro LE.\n          exploit LEyz; first by apply SIZEyz.\n          {\n            rewrite size_zip SIZExy SIZEyz minnn in LTi.\n            by rewrite size_zip SIZEyz minnn; apply LTi.\n          }\n          by instantiate (1 := t); intro LE'; apply (leq_trans LE).\n        Qed.\n\n        (* At any step of the iteration, the corresponding list\n           is larger than or equal to the initial state. *)\n        Lemma bertogna_edf_comp_iteration_preserves_minimum :\n          forall step, all_le (initial_state ts) (f step). \n        Proof.\n          unfold f.\n          intros step; destruct step; first by apply all_le_reflexive.\n          apply/andP; split.\n          {\n            assert (UNZIP0 := edf_claimed_bounds_unzip1_iteration ts 0).\n            by simpl in UNZIP0; rewrite UNZIP0 edf_claimed_bounds_unzip1_iteration.\n          }  \n          destruct ts as [| tsk0 ts'].\n          {\n            clear -step; induction step; first by done.\n            by rewrite iterSr IHstep.\n          }\n\n          apply/(zipP (tsk0,0) (fun x y => snd x <= snd y));\n            first by rewrite edf_claimed_bounds_size size_map.\n\n          intros i LTi; rewrite iterS; unfold edf_rta_iteration at 1.\n          have MAP := @nth_map _ (tsk0,0) _ (tsk0,0).\n          rewrite size_zip edf_claimed_bounds_size size_map minnn in LTi.\n          rewrite MAP; clear MAP; last by rewrite edf_claimed_bounds_size.\n          destruct (nth (tsk0, 0) (initial_state (tsk0 :: ts')) i) as [tsk_i R_i] eqn:SUBST.\n          rewrite SUBST; unfold update_bound.\n          unfold initial_state in SUBST.\n          have MAP := @nth_map _ tsk0 _ (tsk0, 0).\n          rewrite ?MAP // in SUBST; inversion SUBST; clear MAP. \n          assert (EQtsk: tsk_i = fst (nth (tsk0, 0) (iter step edf_rta_iteration\n                                                         (initial_state (tsk0 :: ts'))) i)).\n          {\n            have MAP := @nth_map _ (tsk0,0) _ tsk0 (fun x => fst x).\n            rewrite -MAP; clear MAP; last by rewrite edf_claimed_bounds_size.\n            have UNZIP := edf_claimed_bounds_unzip1_iteration; unfold unzip1 in UNZIP.\n            by rewrite UNZIP; symmetry. \n          }\n          destruct (nth (tsk0, 0) (iter step edf_rta_iteration (initial_state (tsk0 :: ts')))) as [tsk_i' R_i'].\n          by simpl in EQtsk; rewrite -EQtsk; subst; apply leq_addr.\n        Qed.\n\n        (* The application of the function is inductive. *)\n        Lemma bertogna_edf_comp_iteration_inductive (P : seq task_with_response_time -> Type) :\n          P (initial_state ts) ->\n          (forall k, P (f k) -> P (f (k.+1))) ->\n          P (f (max_steps ts)).\n        Proof.\n          by intros P0 Pn; induction (max_steps ts); last by apply Pn.\n        Qed.\n\n        (* As a last step, we show that edf_rta_iteration preserves order, i.e., for any\n           list l1 no smaller than the initial state, and list l2 such that\n           l1 <= l2, we have (edf_rta_iteration l1) <= (edf_rta_iteration l2). *)\n        Lemma bertogna_edf_comp_iteration_preserves_order :\n          forall l1 l2,\n            all_le (initial_state ts) l1 ->\n            all_le l1 l2 ->\n            all_le (edf_rta_iteration l1) (edf_rta_iteration l2).\n        Proof.\n          rename H_valid_task_parameters into VALID.\n          intros x1 x2 LEinit LE.\n          move: LE => /andP [/eqP ZIP LE]; unfold all_le.\n\n          assert (UNZIP': unzip1 (edf_rta_iteration x1) = unzip1 (edf_rta_iteration x2)).\n          {\n            by rewrite 2!edf_claimed_bounds_unzip1_update_bound.\n          }\n\n          apply/andP; split; first by rewrite UNZIP'.\n          apply f_equal with (B := nat) (f := fun x => size x) in UNZIP'.\n          rename UNZIP' into SIZE.\n          rewrite size_map [size (unzip1 _)]size_map in SIZE.\n          move: LE => /(zipP _ (fun x y => snd x <= snd y)) LE.\n          destruct x1 as [| p0 x1'], x2 as [| p0' x2']; try (by ins).\n          apply/(zipP p0 (fun x y => snd x <= snd y)); first by done.\n\n          intros i LTi.\n          exploit LE; first by rewrite 2!size_map in SIZE.\n          {\n            by rewrite size_zip 2!size_map -size_zip in LTi; apply LTi.\n          }\n          rewrite 2!size_map in SIZE.\n          instantiate (1 := p0); intro LEi.\n          rewrite (nth_map p0);\n            last by rewrite size_zip 2!size_map -SIZE minnn in LTi.\n          rewrite (nth_map p0);\n            last by rewrite size_zip 2!size_map SIZE minnn in LTi.\n          unfold update_bound, edf_response_time_bound; desf; simpl.\n          rename s into tsk_i, s0 into tsk_i', t into R_i, t0 into R_i', Heq into EQ, Heq0 into EQ'.\n          assert (EQtsk: tsk_i = tsk_i').\n          {\n            destruct p0 as [tsk0 R0], p0' as [tsk0' R0']; simpl in H2; subst.\n            have MAP := @nth_map _ (tsk0',R0) _ tsk0' (fun x => fst x) i ((tsk0', R0) :: x1').\n            have MAP' := @nth_map _ (tsk0',R0) _ tsk0' (fun x => fst x) i ((tsk0', R0') :: x2').\n            assert (FSTeq: fst (nth (tsk0', R0)((tsk0', R0) :: x1') i) =\n                           fst (nth (tsk0',R0) ((tsk0', R0') :: x2') i)).\n            {\n              rewrite -MAP;\n                last by simpl; rewrite size_zip 2!size_map /= -H0 minnn in LTi.\n              rewrite -MAP';\n                last by simpl; rewrite size_zip 2!size_map /= H0 minnn in LTi.\n              by f_equal; simpl; f_equal.\n            }\n            apply f_equal with (B := sporadic_task) (f := fun x => fst x) in EQ.\n            apply f_equal with (B := sporadic_task) (f := fun x => fst x) in EQ'.\n            by rewrite FSTeq EQ' /= in EQ; rewrite EQ.\n          }\n          subst tsk_i'; rewrite leq_add2l.\n          unfold I, total_interference_bound_edf; apply leq_div2r.\n          rewrite 2!big_cons.\n          destruct p0 as [tsk0 R0], p0' as [tsk0' R0'].\n          simpl in H2; subst tsk0'.\n          rename R_i into delta, R_i' into delta'.\n          rewrite EQ EQ' in LEi; simpl in LEi.\n          rename H0 into SIZE, H1 into UNZIP; clear EQ EQ'.\n\n          assert (SUBST: forall l delta,\n                    \\sum_(j <- l | let '(tsk_other, _) := j in\n                      different_task tsk_i tsk_other)\n                        (let '(tsk_other, R_other) := j in\n                          interference_bound_edf task_cost task_period task_deadline tsk_i delta\n                            (tsk_other, R_other)) =\n                    \\sum_(j <- l | different_task tsk_i (fst j))\n                      interference_bound_edf task_cost task_period task_deadline tsk_i delta j).\n          {\n            intros l x; clear -l.\n            induction l; first by rewrite 2!big_nil.\n            by rewrite 2!big_cons; rewrite IHl; desf; rewrite /= Heq in Heq0.\n          } rewrite 2!SUBST; clear SUBST.\n\n          assert (VALID': valid_sporadic_taskset task_cost task_period task_deadline\n                                                       (unzip1 ((tsk0, R0) :: x1'))).\n          {\n            move: LEinit => /andP [/eqP EQinit _].\n            rewrite -EQinit; unfold valid_sporadic_taskset.\n            move => tsk /mapP IN. destruct IN as [p INinit EQ]; subst.\n            by move: INinit => /mapP INinit; destruct INinit as [tsk INtsk]; subst; apply VALID.\n          }\n\n          assert (GE_COST: all (fun p => task_cost (fst p) <= snd p) ((tsk0, R0) :: x1')). \n          {\n            clear LE; move: LEinit => /andP [/eqP UNZIP' LE].\n            move: LE => /(zipP _ (fun x y => snd x <= snd y)) LE.\n            specialize (LE (tsk0, R0)).\n            apply/(all_nthP (tsk0,R0)).\n            intros j LTj; generalize UNZIP'; simpl; intro SIZE'.\n            have F := @f_equal _ _ size (unzip1 (initial_state ts)).\n            apply F in SIZE'; clear F; rewrite /= 3!size_map in SIZE'.\n            exploit LE; [by rewrite size_map /= | |].\n            {\n              rewrite size_zip size_map /= SIZE' minnn.\n              by simpl in LTj; apply LTj.\n            }\n            clear LE; intro LE.\n            unfold initial_state in LE.\n            have MAP := @nth_map _ tsk0 _ (tsk0,R0).\n            rewrite MAP /= in LE;\n              [clear MAP | by rewrite SIZE'; simpl in LTj].\n            apply leq_trans with (n := task_cost (nth tsk0 ts j));\n              [apply eq_leq; f_equal | by done].\n            have MAP := @nth_map _ (tsk0, R0) _ tsk0 (fun x => fst x).\n            rewrite -MAP; [clear MAP | by done].\n            unfold unzip1 in UNZIP'; rewrite -UNZIP'; f_equal.\n            clear -ts; induction ts; [by done | by simpl; f_equal].\n          }\n          move: GE_COST => /allP GE_COST.\n\n          assert (LESUM: \\sum_(j <- x1' | different_task tsk_i (fst j))\n                        interference_bound_edf task_cost task_period task_deadline tsk_i delta j <=                                  \\sum_(j <- x2' | different_task tsk_i (fst j))\n                        interference_bound_edf task_cost task_period task_deadline tsk_i delta' j).\n          {\n            set elem := (tsk0, R0); rewrite 2!(big_nth elem).\n            rewrite -SIZE.\n            rewrite big_mkcond [\\sum_(_ <- _ | different_task _ _)_]big_mkcond.\n            rewrite big_seq_cond [\\sum_(_ <- _ | true) _]big_seq_cond.\n            apply leq_sum; intros j; rewrite andbT; intros INj.\n            rewrite mem_iota add0n subn0 in INj; move: INj => /andP [_ INj].\n            assert (FSTeq: fst (nth elem x1' j) = fst (nth elem x2' j)).\n            {\n              have MAP := @nth_map _ elem _ tsk0 (fun x => fst x).\n              by rewrite -2?MAP -?SIZE //; f_equal.\n            } rewrite -FSTeq.\n            destruct (different_task tsk_i (fst (nth elem x1' j))) eqn:INTERF;\n              last by done.\n            {\n              exploit (LE elem); [by rewrite /= SIZE | | intro LEj].\n              {\n                rewrite size_zip 2!size_map /= -SIZE minnn in LTi.\n                by rewrite size_zip /= -SIZE minnn; apply (leq_ltn_trans INj).\n              }\n              simpl in LEj.\n              exploit (VALID' (fst (nth elem x1' j))); last intro VALIDj.\n              {\n                apply/mapP; exists (nth elem x1' j); last by done.\n                by rewrite in_cons; apply/orP; right; rewrite mem_nth.\n              }\n              exploit (GE_COST (nth elem x1' j)); last intro GE_COSTj.\n              {\n                by rewrite in_cons; apply/orP; right; rewrite mem_nth.\n              }\n              unfold is_valid_sporadic_task in *.\n              destruct (nth elem x1' j) as [tsk_j R_j] eqn:SUBST1,\n                       (nth elem x2' j) as [tsk_j' R_j'] eqn:SUBST2.\n              rewrite SUBST1 SUBST2 in LEj.\n              simpl in FSTeq; rewrite -FSTeq; simpl in LEj; simpl in VALIDj; des.\n              by apply interference_bound_edf_monotonic.\n            }\n          }\n          destruct (different_task tsk_i tsk0) eqn:INTERFtsk0; last by done.\n          apply leq_add; last by done.\n          {             \n            exploit (LE (tsk0, R0)); [by rewrite /= SIZE | | intro LEj];\n              first by instantiate (1 := 0); rewrite size_zip /= -SIZE minnn.\n            exploit (VALID' tsk0); first by rewrite in_cons; apply/orP; left.\n            exploit (GE_COST (tsk0, R0)); first by rewrite in_cons eq_refl orTb.\n            unfold is_valid_sporadic_task; intros GE_COST0 VALID0; des; simpl in LEj.\n            by apply interference_bound_edf_monotonic.\n          }\n        Qed.\n\n        (* It follows from the properties above that the iteration is monotonically increasing. *)\n        Lemma bertogna_edf_comp_iteration_monotonic: forall k, all_le (f k) (f k.+1).\n        Proof.\n          unfold f; intros k.\n          apply fun_mon_iter_mon_generic with (x1 := k) (x2 := k.+1);\n            try (by done);\n            [ by apply all_le_reflexive\n            | by apply all_le_transitive\n            | by apply bertogna_edf_comp_iteration_preserves_order\n            | by apply bertogna_edf_comp_iteration_preserves_minimum].\n        Qed.\n\n      End RelationProperties.\n\n      (* Knowing that the iteration is monotonically increasing (with respect to all_le),\n         we show that the RTA procedure converges to a fixed point. *)\n\n      (* First, note that when there are no tasks, the iteration trivially converges. *)\n      Lemma bertogna_edf_comp_f_converges_with_no_tasks :\n        size ts = 0 ->\n        f (max_steps ts) = f (max_steps ts).+1.\n      Proof.\n        intro SIZE; destruct ts; last by inversion SIZE.\n        unfold max_steps; rewrite big_nil /=.\n        by unfold edf_rta_iteration.\n      Qed.\n\n      (* Otherwise, if the iteration reached a fixed point before (max_steps ts), then\n         the value at (max_steps ts) is still at a fixed point. *)\n      Lemma bertogna_edf_comp_f_converges_early :\n        (exists k, k <= max_steps ts /\\ f k = f k.+1) ->\n        f (max_steps ts) = f (max_steps ts).+1.\n      Proof.\n        by intros EX; des; apply fixedpoint.iter_fix with (k := k).\n      Qed.\n\n      (* Else, we derive a contradiction. *)\n      Section DerivingContradiction.\n\n        (* Assume that there are tasks. *)\n        Hypothesis H_at_least_one_task: size ts > 0.\n\n        (* Assume that the iteration continued to diverge. *)\n        Hypothesis H_keeps_diverging:\n          forall k,\n            k <= max_steps ts -> f k != f k.+1.\n\n        (* Since the iteration is monotonically increasing, it must be\n           strictly increasing. *)\n        Lemma bertogna_edf_comp_f_increases :\n          forall k,\n            k <= max_steps ts -> one_lt (f k) (f k.+1).\n        Proof.\n          rename H_at_least_one_task into NONEMPTY.\n          intros step LEstep; unfold one_lt; apply/andP; split;\n            first by rewrite 2!edf_claimed_bounds_unzip1_iteration.\n          rewrite -[has _ _]negbK; apply/negP; unfold not; intro ALL.\n          rewrite -all_predC in ALL.\n          move: ALL => /allP ALL.\n          exploit (H_keeps_diverging step); [by done | intro DIFF].\n          assert (DUMMY: exists tsk: sporadic_task, True).\n          {\n            destruct ts as [|tsk0]; first by rewrite ltnn in NONEMPTY.\n            by exists tsk0.\n          }\n          des; clear DUMMY.\n          move: DIFF => /eqP DIFF; apply DIFF.\n          apply eq_from_nth with (x0 := (tsk, 0));\n            first by simpl; rewrite size_map.\n          {\n            intros i LTi.\n            remember (nth (tsk, 0)(f step) i) as p_i;rewrite -Heqp_i.\n            remember (nth (tsk, 0)(f step.+1) i) as p_i';rewrite -Heqp_i'.\n            rename Heqp_i into EQ, Heqp_i' into EQ'.\n            exploit (ALL (p_i, p_i')).\n            {\n              rewrite EQ EQ'.\n              rewrite -nth_zip; last by unfold f; rewrite iterS size_map.\n              apply mem_nth; rewrite size_zip.\n              unfold f; rewrite iterS size_map.\n              by rewrite minnn.\n            }\n            unfold predC; simpl; rewrite -ltnNge; intro LTp.\n\n            have GROWS := bertogna_edf_comp_iteration_monotonic step.\n            move: GROWS => /andP [_ /allP GROWS].\n            exploit (GROWS (p_i, p_i')).\n            {\n              rewrite EQ EQ'.\n              rewrite -nth_zip; last by unfold f; rewrite iterS size_map.\n              apply mem_nth; rewrite size_zip.\n              unfold f; rewrite iterS size_map.\n              by rewrite minnn.\n            }\n            simpl; intros LE.\n            destruct p_i as [tsk_i R_i], p_i' as [tsk_i' R_i'].\n            simpl in *.\n            assert (EQtsk: tsk_i = tsk_i').\n            {\n              unfold edf_rta_iteration in EQ'.\n              rewrite (nth_map (tsk, 0)) in EQ'; last by done.\n              by unfold update_bound in EQ'; desf.\n            }\n            rewrite EQtsk; f_equal.\n            by apply/eqP; rewrite eqn_leq; apply/andP; split.\n          }\n        Qed.\n\n        (* In the end, each response-time bound is so high that the sum\n           of all response-time bounds exceeds the sum of all deadlines.\n           Contradiction! *)\n        Lemma bertogna_edf_comp_rt_grows_too_much :\n          forall k,\n            k <= max_steps ts ->\n            \\sum_((tsk, R) <- f k) (R - task_cost tsk) + 1 > k.\n        Proof.\n          have LT := bertogna_edf_comp_f_increases.\n          have MONO := bertogna_edf_comp_iteration_monotonic.\n          rename H_at_least_one_task into NONEMPTY.\n          unfold valid_sporadic_taskset, is_valid_sporadic_task in *.\n          rename H_valid_task_parameters into VALID.\n          intros step LE.\n          assert (DUMMY: exists tsk: sporadic_task, True).\n          {\n            destruct ts as [|tsk0]; first by rewrite ltnn in NONEMPTY.\n            by exists tsk0.\n          } destruct DUMMY as [elem _].\n\n          induction step; first by rewrite addn1.\n          {\n            rewrite -addn1 ltn_add2r.\n            apply leq_ltn_trans with (n := \\sum_(i <- f step) (let '(tsk, R) := i in R - task_cost tsk)).\n            {\n              rewrite -ltnS; rewrite addn1 in IHstep.\n              by apply IHstep, ltnW.\n            }\n            rewrite (eq_bigr (fun x => snd x - task_cost (fst x)));\n              last by ins; destruct i.\n            rewrite [\\sum_(_ <- f step.+1)_](eq_bigr (fun x => snd x - task_cost (fst x)));\n              last by ins; destruct i.\n            unfold f at 2; rewrite iterS.\n            rewrite big_map; fold (f step).\n            rewrite -(ltn_add2r (\\sum_(i <- f step) task_cost (fst i))).\n            rewrite -2!big_split /=.\n            rewrite big_seq_cond [\\sum_(_ <- _ | true)_]big_seq_cond.\n            rewrite (eq_bigr (fun i => snd i)); last first.\n            {\n              intro i; rewrite andbT; intro IN;\n              rewrite subh1; first by rewrite -addnBA // subnn addn0.\n              have GE_COST := edf_claimed_bounds_ge_cost ts step.\n              by destruct i; apply GE_COST.\n            }\n            rewrite [\\sum_(_ <- _ | _)(_ - _ + _)](eq_bigr (fun i => snd (update_bound (f step) i))); last first.\n            {\n              intro i; rewrite andbT; intro IN.\n              unfold update_bound; destruct i; simpl.\n              rewrite subh1; first by rewrite -addnBA // subnn addn0.\n              apply (edf_claimed_bounds_ge_cost ts step.+1).\n              by rewrite iterS; apply/mapP; exists (s, t).\n            }\n            rewrite -2!big_seq_cond.\n           \n            specialize (LT step (ltnW LE)).\n            specialize (MONO step).\n            move: LT => /andP [_ LT]; move: LT => /hasP LT.\n            destruct LT as [[x1 x2] INzip LT]; simpl in *.\n            move: MONO => /andP [_ /(zipP _ (fun x y => snd x <= snd y)) MONO].\n            rewrite 2!(big_nth (elem, 0)).\n            apply mem_zip_exists with (elem := (elem, 0)) (elem' := (elem, 0)) in INzip; des;\n              last by rewrite size_map.\n            rewrite -> big_cat_nat with (m := 0) (n := idx) (p := size (f step));\n              [simpl | by done | by apply ltnW].\n            rewrite -> big_cat_nat with (m := idx) (n := idx.+1) (p := size (f step));\n              [simpl | by done | by done].\n            rewrite big_nat_recr /=; last by done.\n            rewrite -> big_cat_nat with (m := 0) (n := idx) (p := size (f step));\n              [simpl | by done | by apply ltnW].\n            rewrite -> big_cat_nat with (m := idx) (n := idx.+1) (p := size (f step));\n              [simpl | by done | by done].\n            rewrite big_nat_recr /=; last by done.\n            rewrite [\\sum_(idx <= i < idx) _]big_geq // add0n.\n            rewrite [\\sum_(idx <= i < idx) _]big_geq // add0n.\n            rewrite -addn1 -addnA; apply leq_add.\n            {\n              rewrite big_nat_cond [\\sum_(_ <= _ < _ | true) _]big_nat_cond.\n              apply leq_sum; move => i /andP [/andP [LT1 LT2] _].\n              exploit (MONO (elem,0)); [by rewrite size_map | | intro LEi].\n              {\n                rewrite size_zip; apply (ltn_trans LT2).\n                by apply leq_trans with (n := size (f step));\n                  [by done | by rewrite size_map minnn].\n              }\n              unfold edf_rta_iteration in LEi.\n              by rewrite -> nth_map with (x1 := (elem, 0)) in LEi;\n                last by apply (ltn_trans LT2).\n            }\n            rewrite -addnA [_ + 1]addnC addnA; apply leq_add.\n            {\n              unfold edf_rta_iteration in INzip2; rewrite addn1.\n              rewrite -> nth_map with (x1 := (elem, 0)) in INzip2; last by done.\n              by rewrite -INzip2 -INzip1.\n            }\n            {\n              rewrite big_nat_cond [\\sum_(_ <= _ < _ | true) _]big_nat_cond.\n              apply leq_sum; move => i /andP [/andP [LT1 LT2] _].\n              exploit (MONO (elem,0));\n                [ by rewrite size_map\n                | by rewrite size_zip; apply (leq_trans LT2); rewrite size_map minnn | intro LEi ].\n              unfold edf_rta_iteration in LEi.\n              by rewrite -> nth_map with (x1 := (elem, 0)) in LEi; last by done.\n            }\n          }\n        Qed.\n\n      End DerivingContradiction. \n\n      (* Using the lemmas above, we prove that edf_rta_iteration reaches\n         a fixed point after (max_steps ts) step, ... *)\n      Lemma edf_claimed_bounds_finds_fixed_point_of_list :\n        forall rt_bounds,\n          edf_claimed_bounds ts = Some rt_bounds ->\n          valid_sporadic_taskset task_cost task_period task_deadline ts ->\n          f (max_steps ts) = edf_rta_iteration (f (max_steps ts)). \n      Proof.\n        intros rt_bounds SOME VALID.\n        unfold valid_sporadic_taskset, is_valid_sporadic_task in *.\n        unfold edf_claimed_bounds in SOME; desf.\n        rename Heq into LE.\n        fold (f (max_steps ts)) in *; fold (f (max_steps ts).+1).\n\n        (* Either the task set is empty or not. *)\n        destruct (size ts == 0) eqn:EMPTY;\n          first by apply bertogna_edf_comp_f_converges_with_no_tasks; apply/eqP.\n        apply negbT in EMPTY; rewrite -lt0n in EMPTY.\n\n        (* Either f converges by the deadline or not. *)\n        destruct ([exists k in 'I_((max_steps ts).+1), f k == f k.+1]) eqn:EX.\n        {\n          move: EX => /exists_inP EX; destruct EX as [k _ ITERk].\n          destruct k as [k LTk]; simpl in ITERk.\n          apply bertogna_edf_comp_f_converges_early.\n          exists k; split; [by apply LTk | by apply/eqP].\n        }\n\n        (* If not, then we reach a contradiction *)\n        apply negbT in EX; rewrite negb_exists_in in EX.\n        move: EX => /forall_inP EX.\n\n        assert (SAMESUM: \\sum_(tsk <- ts) task_cost tsk = \\sum_(p <- f (max_steps ts)) task_cost (fst p)).\n        {\n          have MAP := @big_map _ 0 addn _ _ (fun x => fst x) (f (max_steps ts))\n                               (fun x => true) (fun x => task_cost x).\n          have UNZIP := edf_claimed_bounds_unzip1_iteration ts (max_steps ts).\n          fold (f (max_steps ts)) in UNZIP; unfold unzip1 in UNZIP.\n          by rewrite UNZIP in MAP; rewrite MAP.\n        }\n        \n        (* Show that the sum is less than the sum of all deadlines. *)\n        assert (SUM: \\sum_(p <- f (max_steps ts)) (snd p - task_cost (fst p)) + 1 <= max_steps ts). \n        {\n          unfold max_steps at 2; rewrite leq_add2r.\n          rewrite -(leq_add2r (\\sum_(tsk <- ts) task_cost tsk)).\n          rewrite {1}SAMESUM -2!big_split /=.\n          rewrite big_seq_cond [\\sum_(_ <- _ | true)_]big_seq_cond.\n          rewrite (eq_bigr (fun x => snd x)); last first.\n          {\n            intro i; rewrite andbT; intro IN.\n            rewrite subh1; first by rewrite -addnBA // subnn addn0.\n            have GE_COST := edf_claimed_bounds_ge_cost ts (max_steps ts).\n            fold (f (max_steps ts)) in GE_COST.\n            by destruct i; apply GE_COST.\n          }\n          rewrite (eq_bigr (fun x => task_deadline x)); last first.\n          {\n            intro i; rewrite andbT; intro IN.\n            rewrite subh1; first by rewrite -addnBA // subnn addn0.\n            by specialize (VALID i IN); des.\n          }\n          rewrite -2!big_seq_cond.\n          have MAP := @big_map _ 0 addn _ _ (fun x => fst x) (f (max_steps ts))\n                               (fun x => true) (fun x => task_deadline x).\n          have UNZIP := edf_claimed_bounds_unzip1_iteration ts (max_steps ts).\n          fold (f (max_steps ts)) in UNZIP; unfold unzip1 in UNZIP.\n          rewrite UNZIP in MAP; rewrite MAP.\n          rewrite big_seq_cond [\\sum_(_ <- _|true)_]big_seq_cond.\n          apply leq_sum; intro i; rewrite andbT; intro IN.\n          move: LE => /allP LE; unfold R_le_deadline in LE.\n          by specialize (LE i IN); destruct i.\n        }\n\n        have TOOMUCH :=\n          bertogna_edf_comp_rt_grows_too_much EMPTY _ (max_steps ts) (leqnn (max_steps ts)).\n        exploit TOOMUCH; [| intro BUG].\n        {\n          intros k LEk; rewrite -ltnS in LEk.\n          by exploit (EX (Ordinal LEk)); [by done | by ins].\n        }\n        rewrite (eq_bigr (fun i => snd i - task_cost (fst i))) in BUG;\n          last by ins; destruct i.\n        by apply (leq_ltn_trans SUM) in BUG; rewrite ltnn in BUG. \n      Qed.\n\n      (* ...and since there cannot be a vector of response-time bounds with values less than\n         the task costs, this solution is also the least fixed point. *)\n      Lemma edf_claimed_bounds_finds_least_fixed_point :\n        forall v,\n          all_le (initial_state ts) v ->\n          v = edf_rta_iteration v ->\n          all_le (f (max_steps ts)) v.\n      Proof.\n        intros v GE0 EQ.\n        apply bertogna_edf_comp_iteration_inductive; first by done.\n        intros k GEk.\n        rewrite EQ.\n        apply bertogna_edf_comp_iteration_preserves_order; last by done.\n        by apply bertogna_edf_comp_iteration_preserves_minimum.\n      Qed.\n\n      (* Therefore, with regard to the response-time bound recurrence, ...*)\n      \n      (* ..., the individual response-time bounds (elements of the list) are also fixed points. *)\n      Theorem edf_claimed_bounds_finds_fixed_point_for_each_bound :\n        forall tsk R rt_bounds,\n          edf_claimed_bounds ts = Some rt_bounds ->\n          (tsk, R) \\in rt_bounds ->\n          R = edf_response_time_bound rt_bounds tsk R.\n      Proof.\n        intros tsk R rt_bounds SOME IN.\n        have CONV := edf_claimed_bounds_finds_fixed_point_of_list rt_bounds.\n        rewrite -iterS in CONV; fold (f (max_steps ts).+1) in CONV.\n        unfold edf_claimed_bounds in *; desf.\n        exploit (CONV); [by done | by done | intro ITER; clear CONV].\n        unfold f in ITER.\n\n        cut (update_bound (iter (max_steps ts)\n               edf_rta_iteration (initial_state ts)) (tsk,R) = (tsk, R)).\n        {\n          intros EQ.\n          have F := @f_equal _ _ (fun x => snd x) _ (tsk, R).\n          by apply F in EQ; simpl in EQ.\n        }\n        set s := iter (max_steps ts) edf_rta_iteration (initial_state ts).\n        fold s in ITER, IN.\n        move: IN => /(nthP (tsk,0)) IN; destruct IN as [i LT EQ].\n        generalize EQ; rewrite ITER iterS in EQ; intro EQ'.\n        fold s in EQ.\n        unfold edf_rta_iteration in EQ.\n        have MAP := @nth_map _ (tsk,0) _ _ (update_bound s). \n        by rewrite MAP // EQ' in EQ; rewrite EQ.\n      Qed.\n      \n    End Convergence.\n\n    Section MainProof.\n\n      (* Consider a task set ts where... *)\n      Variable ts: taskset_of sporadic_task.\n      \n      (* ...all tasks have valid parameters ... *)\n      Hypothesis H_valid_task_parameters:\n        valid_sporadic_taskset task_cost task_period task_deadline ts.\n\n      (* ...and constrained deadlines.*)\n      Hypothesis H_constrained_deadlines:\n        forall tsk, tsk \\in ts -> task_deadline tsk <= task_period tsk.\n\n      (* Next, consider any arrival sequence such that...*)\n      Context {arr_seq: arrival_sequence Job}.\n\n     (* ...all jobs come from task set ts, ...*)\n      Hypothesis H_all_jobs_from_taskset:\n        forall j, arrives_in arr_seq j -> job_task j \\in ts.\n      \n      (* ...they 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      (* ... and satisfy the sporadic task model.*)\n      Hypothesis H_sporadic_tasks:\n        sporadic_task_model task_period job_arrival job_task arr_seq.\n      \n      (* Then, consider any platform with at least one CPU such that...*)\n      Variable sched: schedule Job num_cpus.\n      Hypothesis H_at_least_one_cpu: num_cpus > 0.\n      Hypothesis H_jobs_come_from_arrival_sequence:\n        jobs_come_from_arrival_sequence sched arr_seq.\n\n      (* ...jobs only execute after they arrived and no longer\n         than their execution costs,... *)\n      Hypothesis H_jobs_must_arrive_to_execute:\n        jobs_must_arrive_to_execute job_arrival sched.\n      Hypothesis H_completed_jobs_dont_execute:\n        completed_jobs_dont_execute job_cost sched.\n\n      (* Assume a work-conserving scheduler with EDF policy. *)\n      Hypothesis H_work_conserving: work_conserving job_arrival job_cost arr_seq sched.\n      Hypothesis H_edf_policy: respects_JLFP_policy job_arrival job_cost arr_seq sched\n                                                    (EDF job_arrival job_deadline).\n\n      Definition no_deadline_missed_by_task (tsk: sporadic_task) :=\n        task_misses_no_deadline job_arrival job_cost job_deadline job_task arr_seq sched tsk.\n      Definition no_deadline_missed_by_job :=\n        job_misses_no_deadline job_arrival job_cost job_deadline sched.\n      Let response_time_bounded_by (tsk: sporadic_task) :=\n        is_response_time_bound_of_task job_arrival job_cost job_task arr_seq sched tsk.\n\n      (* In the following theorem, we prove that any response-time bound contained\n         in edf_claimed_bounds is safe. The proof follows by direct application of\n         the main Theorem from bertogna_edf_theory.v. *)\n      Theorem edf_analysis_yields_response_time_bounds :\n        forall tsk R,\n          (tsk, R) \\In edf_claimed_bounds ts ->\n          response_time_bounded_by tsk R.\n      Proof.\n        intros tsk R IN j JOBj.\n        destruct (edf_claimed_bounds ts) as [rt_bounds |] eqn:SOME; last by done.\n        unfold edf_rta_iteration in *.\n        have BOUND := bertogna_cirinei_response_time_bound_edf.\n        unfold is_response_time_bound_of_task in *.\n        apply BOUND with (task_cost := task_cost) (task_period := task_period)\n           (arr_seq := arr_seq) (task_deadline := task_deadline) (job_deadline := job_deadline)\n           (job_task := job_task) (ts := ts) (tsk := tsk) (rt_bounds := rt_bounds); try (by ins).\n          by unfold edf_claimed_bounds in SOME; desf; rewrite edf_claimed_bounds_unzip1_iteration.\n          by ins; apply edf_claimed_bounds_finds_fixed_point_for_each_bound with (ts := ts).\n          by ins; rewrite (edf_claimed_bounds_le_deadline ts rt_bounds).\n      Qed.\n      \n      (* Therefore, if the schedulability test suceeds, ...*)\n      Hypothesis H_test_succeeds: edf_schedulable ts.\n      \n      (*... no task misses its deadline. *)\n      Theorem taskset_schedulable_by_edf_rta :\n        forall tsk, tsk \\in ts -> no_deadline_missed_by_task tsk.\n      Proof.\n        have RLIST := (edf_analysis_yields_response_time_bounds).\n        have DL := (edf_claimed_bounds_le_deadline ts).\n        have HAS := (edf_claimed_bounds_has_R_for_every_task ts).\n        unfold no_deadline_missed_by_task, task_misses_no_deadline,\n               job_misses_no_deadline, completed,\n               edf_schedulable,\n               valid_sporadic_job in *.\n        rename H_valid_job_parameters into JOBPARAMS,\n               H_valid_task_parameters into TASKPARAMS,\n               H_constrained_deadlines into RESTR,\n               H_completed_jobs_dont_execute into COMP,\n               H_jobs_must_arrive_to_execute into MUSTARRIVE,\n               H_all_jobs_from_taskset into ALLJOBS,\n               H_test_succeeds into TEST.\n        \n        move => tsk INtsk j ARRj JOBtsk.\n        destruct (edf_claimed_bounds ts) as [rt_bounds |] eqn:SOME; last by ins.\n        exploit (HAS rt_bounds tsk); [by ins | by ins | clear HAS; intro HAS; des].\n        have COMPLETED := RLIST tsk R HAS j ARRj JOBtsk.\n        exploit (DL rt_bounds tsk R);\n          [by ins | by ins | clear DL; intro DL].\n        apply leq_trans with (n := service sched j (job_arrival j + R)); last first.\n        {\n          unfold valid_sporadic_taskset, is_valid_sporadic_task in *.\n          apply extend_sum; rewrite // leq_add2l.\n          specialize (JOBPARAMS j ARRj); des; rewrite JOBPARAMS1.\n          by rewrite JOBtsk.\n        }\n        by done.\n      Qed.\n\n      (* For completeness, since all jobs of the arrival sequence\n         are spawned by the task set, we conclude that no job misses\n         its deadline. *)\n      Theorem jobs_schedulable_by_edf_rta :\n        forall j, arrives_in arr_seq j -> no_deadline_missed_by_job j.\n      Proof.\n        intros j ARRj.\n        have SCHED := taskset_schedulable_by_edf_rta.\n        unfold no_deadline_missed_by_task, task_misses_no_deadline in *.\n        apply SCHED with (tsk := job_task j); try (by done).\n        by apply H_all_jobs_from_taskset.\n      Qed.\n      \n    End MainProof.\n\n  End Analysis.\n\nEnd ResponseTimeIterationEDF.\n", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/classic/analysis/global/parallel/bertogna_edf_comp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6771595982245711}}
{"text": "\nRequire Export Coq.Lists.List.\nRequire Export Iron.Language.DelayedSimpleUS.Tactics.Chargueraud.\n\n\n(********************************************************************)\n(* Forall Lemmas *)\n\nLemma Forall_inst\n :  forall {A B} a' xs (P: A -> B -> Prop)\n ,  Forall (fun x => forall a, P a x) xs\n -> Forall (fun x => P a' x) xs.\nProof.\n intros.\n induction xs.\n - auto.\n - eapply Forall_cons.\n   + inverts H. eapply H2.\n   + inverts H. eapply IHxs. assumption.\nQed.\n\n\nLemma Forall_mp\n :  forall {A} (P Q: A -> Prop)  xs\n ,  Forall (fun x => P x -> Q x) xs\n -> Forall (fun x => P x)        xs\n -> Forall (fun x => Q x)        xs.\nProof.\n intros.\n induction xs.\n - auto.\n - eapply Forall_cons.\n   + inverts H. inverts H0. auto.\n   + inverts H. inverts H0. auto.\nQed. \n\n\nLemma Forall_mp_const \n :  forall {A} P (Q: A -> Prop)  xs\n ,  P\n -> Forall (fun x => P -> Q x) xs\n -> Forall (fun x => Q x)      xs.\nProof.\n intros.\n induction H.\n - auto.\n - apply Forall_cons.\n   + auto.\n   + auto.\nQed.\n\n\nLemma Forall_map\n :  forall {A B}\n    (P: B -> Prop) (f: A -> B) (xs: list A)\n ,  Forall (fun x => P (f x)) xs\n -> Forall P (map f xs).\nProof.\n intros. induction xs.\n  apply Forall_nil.\n  inverts H. simpl. intuition.\nQed.\n\n\n(********************************************************************)\n(* Forall2 Lemmas *)\n\nLemma Forall2_mp\n :  forall {A B} (P Q: A -> B -> Prop)  aa bb\n ,  Forall2 (fun a b => P a b -> Q a b) aa bb\n -> Forall2 (fun a b => P a b)          aa bb\n -> Forall2 (fun a b => Q a b)          aa bb.\nProof.\n intros.\n induction H0.\n - auto.\n - inverts H.\n   apply Forall2_cons; auto.\nQed.\n\n\nLemma Forall2_map\n :  forall {A B C D}\n    (P:  B -> D -> Prop) (f:  A -> B) (g:  C -> D) \n    (xs: list A) (ys: list C)\n ,  Forall2 (fun x y => P (f x) (g y)) xs ys\n -> Forall2 P (map f xs) (map g ys).\nProof.\n intros.\n induction H.\n - simpl. auto.\n - simpl. apply Forall2_cons; auto. \nQed.\n\n\nLemma Forall2_map'\n :  forall {A B C D}\n    (P: B -> D -> Prop) (f:  A -> B) (g:  C -> D)\n    (xs: list A) (ys: list C)\n ,  Forall2 P (map f xs) (map g ys)\n -> Forall2 (fun x y => P (f x) (g y)) xs ys.\nProof.\n intros. gen ys.\n induction xs; intros.\n  induction ys; intros.\n   auto.\n   inverts H.\n   destruct ys.\n    inverts H.\n    simpl in H.\n    inverts H. eauto.\nQed.\n\n\n(********************************************************************)\n(* Convert Forall to Forall2 *)\nLemma Forall_Forall2_right\n :  forall  {A B C} \n    (P: B -> C -> Prop) \n    (f: A -> B) (g: A -> C) (aa: list A)\n ,  Forall  (fun b => forall c, P b c) (map f aa)\n -> Forall2 P (map f aa) (map g aa).\nProof.\n intros.\n induction aa.\n - simpl. auto.\n - simpl in *.\n   inverts H.\n   apply Forall2_cons.\n   auto. auto.\nQed.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Language/DelayedSimpleUS/Data/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.6771418024682555}}
{"text": "Require Import HoTT.\nLocal Open Scope path_scope.\nLocal Open Scope equiv_scope.\n\n(* Exercise 2.1 *)\n\nLemma translr {A : Type} {x y z : A} (p : x = y) (q : y = z) : x = z.\n  induction p. induction q. reflexivity.\nDefined.\n\nLemma transl {A : Type} {x y z : A} (p : x = y) (q : y = z) : x = z.\n  induction p. apply q.\nDefined.\n\nLemma transr {A : Type} {x y z : A} (p : x = y) (q : y = z) : x = z.\n  induction q. apply p.\nDefined.\n\nLemma eq_lr_l {A : Type} {x y z : A} (p : x = y) (q : y = z) : translr p q = transl p q.\n  induction p. induction q. reflexivity.\nDefined.\n\nLemma eq_l_r {A : Type} {x y z : A} (p : x = y) (q : y = z) : transl p q = transr p q.\n  induction p. induction q. reflexivity.\nDefined.\n\n(* Cleverly need to swap these arguments >:-) Otherwise, running sym on\nthe correctly oriented version would also work.  *)\nLemma eq_lr_r {A : Type} {x y z : A} (p : x = y) (q : y = z) : translr p q = transr p q.\n  induction q. induction p. reflexivity.\nDefined.\n\n\n(* in all the proofs, we need to do induction on both equalities, because\nwe need to compute to refl = refl. *)\n\n(* Exercise 2.2 *)\nLemma eq_triangle {A : Type} {x y z : A} (p : x = y) (q : y = z) : eq_lr_l p q @ eq_l_r p q = eq_lr_r p q.\n  induction p. induction q. reflexivity.\nQed.\n\n(* Exercise 2.3 *)\n(* It's not obvious that there /is/ another proof, but there is, which\nworks off of a variant of the Yoneda lemma. An alternative way of looking\nat it is we are strengthening the inductive hypothesis. *)\nLemma transy {A : Type} {x y z : A} (p : x = y) (q : y = z) : x = z.\n  generalize q; clear q.\n  generalize z; clear z.\n  induction p. trivial.\nDefined.\n\nPrint transy.\n(*\ntransy = \nfun (A : Type) (x y z : A) (p : x = y) (q : y = z) =>\npaths_rect x (fun (y0 : A) (_ : x = y0) => forall z0 : A, y0 = z0 -> x = z0)\n  (fun z0 : A => idmap) y p z q\n     : forall (A : Type) (x y z : A), x = y -> y = z -> x = z\n*)\nPrint transl.\n(*\ntransl = \nfun (A : Type) (x y z : A) (p : x = y) (q : y = z) =>\npaths_rect x (fun (y0 : A) (_ : x = y0) => y0 = z -> x = z) idmap y p q\n     : forall (A : Type) (x y z : A), x = y -> y = z -> x = z\n*)\n\nLemma eq_y_l {A : Type} {x y z : A} (p : x = y) (q : y = z) : transy p q = transl p q.\n  induction p. reflexivity.\nQed.\n\n(* Exercise 2.4 *)\n\n(*\n0-path is a point\n1-path is a path (the boundary is the two endpoints)\n2-path is a homotopy of paths (the boundary is the two endpaths)\n*)\n\n(* The key insight is that the 'type' of a n-dimensional path contains\na sigma in it.  You rarely see sigma when we talk about the 'type' of paths\nbecause we will usually have some endpoints in the context.  If you remove\nthe context, you need to somehow provide the context.  Who provides the\ncontext?  If it's considered part of the path itself, the context needs to\nbe baked in with the path; since it's part of the type it is in a sigma. *)\n\n(*\nA 0-path in A is a point in A.\nA 1-path is (x, y, p) with x y : A,     p : x = y\nA 2-path is (p, q, r) with p q : x = y, r : p = q\n*)\n\nFixpoint npath (A : Type) (n : nat) :=\n  match n with\n      | 0 => A\n      | S n' => { x : npath A n' & { y : npath A n' & x = y } }\n  end.\nEval compute in (npath nat 2).\n\n(* This is equivalent to what you need, but it's worth convincing yourself that\nthis is in fact that the equalities all work out.\n {x : nat & x' : nat & y : nat & y' : nat & p : x = y & q : x' = y' & ex : x = x' & ey : y = y' & p = transport2 ex ey q } *)\n\n(* Exercise 2.5 *)\nDefinition eq2_3_6 {A B x y} (f : A -> B) (p : x = y) : f x = f y -> transport (fun _ => B) p (f x) = f y :=\n  fun q => transport_const _ _ @ q.\nDefinition eq2_3_7 {A B x y} (f : A -> B) (p : x = y) : transport (fun _ => B) p (f x) = f y -> f x = f y :=\n  fun q => (transport_const _ _)^ @ q. (* careful with associativity precedence *)\n\n(* I don't know what an \"inverse equivalence\" is, but it seems like these ought to form an equivalence *)\n\nDefinition ex2_5_beta {A B x y} (f : A -> B) (p : x = y) (fp : f x = f y) : eq2_3_7 f p (eq2_3_6 f p fp) = idmap fp.\n  unfold eq2_3_6, eq2_3_7.\n  path_induction; reflexivity.\nDefined.\n\nDefinition ex2_5_alpha {A B x y} (f : A -> B) (p : x = y) (fp : transport (fun _ => B) p (f x) = f y) : eq2_3_6 f p (eq2_3_7 f p fp) = idmap fp.\n  unfold eq2_3_6, eq2_3_7.\n  path_induction; reflexivity.\nDefined.\n\n(* Because this chapter does not contain a discussion of the \"adjointification\" of equivalences\n(and all of the proofs simply assume a black box way to get there), we don't worry about it either.) *)\nLemma ex2_5 {A B x y} (f : A -> B) (p : x = y) : IsEquiv (eq2_3_6 f p).\n  apply (isequiv_adjointify _ (eq2_3_7 f p) (ex2_5_alpha f p) (ex2_5_beta f p)).\nQed.\n\n(* In some cases, however, the adjointification condition is pretty easy to do. *)\nLemma ex2_5' {A B x y} (f : A -> B) (p : x = y) : IsEquiv (eq2_3_6 f p).\n  refine (BuildIsEquiv _ _ _ (eq2_3_7 f p) (ex2_5_alpha f p) (ex2_5_beta f p) _).\n  intros; unfold ex2_5_alpha, ex2_5_beta, eq2_3_6, eq2_3_7; path_induction; reflexivity.\nDefined.\n\n(* Exercise 2.6 *)\n\nDefinition invconcat {A} {x y z : A} (p : x = y) : x = z -> y = z.\n  path_induction; reflexivity.\nDefined.\n\nDefinition concat_alpha {A} {x y z : A} (p : x = y) (q : x = z) : @concat A x y z p (@invconcat A x y z p q) = idmap q.\n  path_induction; reflexivity.\nDefined.\n\nDefinition concat_beta {A} {x y z : A} (p : x = y) (q : y = z) : @invconcat A x y z p (@concat A x y z p q) = idmap q.\n  path_induction; reflexivity.\nDefined.\n\nLemma ex2_6 {A} {x y z : A} (p : x = y) : IsEquiv (@concat A x y z p).\n  apply (isequiv_adjointify _ (@invconcat A x y z p) (concat_alpha p) (concat_beta p)).\nDefined.\n\nLemma ex2_6' {A} {x y z : A} (p : x = y) : IsEquiv (@concat A x y z p).\n  refine (BuildIsEquiv _ _ _ (@invconcat A x y z p) (concat_alpha p) (concat_beta p) _).\n  intros; unfold invconcat, concat_alpha, concat_beta, concat; path_induction; reflexivity.\nDefined.\n\n(* Exercise 2.7 *)\n\n(* pair^= is path_prod.  It's important to give the second path_prod the\narguments to help Coq figure out the definitional equality.\nThis lemmma is called ap_functor_prod in the standard library, and f is\ndefined as functor_prod *)\n(* NB: defining f using fst/snd and not a match is fairly essential to\n   convincing Coq that things are definitionally equal in the way necessa *)\nTheorem theorem2_6_5 {A B A' B'} (g : A -> A') (h : B -> B') (x y : A * B) (p : fst x = fst y) (q : snd x = snd y) :\n  let f z := (g (fst z), h (snd z)) in\n    ap f (path_prod x y p q) = path_prod (f x) (f y) (ap g p) (ap h q).\n  intros. destruct x; destruct y; simpl in *. path_induction; reflexivity.\nQed.\nPrint ap_functor_prod.\n\n(* The key to writing down the generalized version of this theorem relies\non the three useful lemmas 2.3.{9-11}.  They're available in the HoTT library\nbut it is instructive to state and prove them here. *)\n\nLemma lemma2_3_9 {A : Type} (P : A -> Type) {x y z : A} (p : x = y) (q : y = z) (u : P x) :\n  transport _ q (transport _ p u) = transport _ (p @ q) u.\n  path_induction; reflexivity.\nDefined.\nPrint transport_pp. (* Actually, you don't need this one. Yet. *)\n\nLemma lemma2_3_10 {A B : Type} (f : A -> B) (P : B -> Type) {x y : A} (p : x = y) (u : P (f x)) :\n  transport (P o f) p u = transport P (ap f p) u.\n  path_induction; reflexivity.\nDefined.\nPrint transport_compose.\n\nLemma lemma2_3_11 {A : Type} (P Q : A -> Type) (f : forall x : A, P x -> Q x) {x y : A} (p : x = y) (u : P x) :\n  transport Q p (f x u) = f y (transport P p u).\n  path_induction; reflexivity.\nDefined.\nPrint ap_transport. (* It's not entirely clear why it's called 'ap' transport, since no ap is involved. *)\n\n(* A useful trick which jgross showed me: if you are not sure how a theorem should\nbe stated, replace it with a : Type, and fill it out using tactic mode.  This is actually\none of those cases where Agda would be superior to Coq for doing these types of proofs,\nsince holes are natively supported in goals, whereas we have to do some acrobatics. *)\n\nTheorem ex2_7' {A A'} {P : A -> Type} {P' : A' -> Type} (g : A -> A') (h : forall a, P a -> P' (g a)) (x y : sigT P) (p : x.1 = y.1) (q : transport _ p x.2 = y.2) : Type.\n  refine (let f z := (g z.1 ; h z.1 z.2) in\n    ap f (path_sigma P x y p q) = path_sigma P' (f x) (f y) (ap g p) _).\n  subst f; simpl.\n  transitivity (transport (P' o g) p (h x .1 x .2)).\n  symmetry. apply (lemma2_3_10 g P' _ _).\n  transitivity (h y .1 (transport P p x .2)). \n  apply (lemma2_3_11 P (P' o g) _ _ _).\n  apply ap.\n  exact q.\nDefined.\n\n(* Unfortunately, Coq has expanded some of the lemmas into matches on identity,\nso we will have to reverse engineer the true theorem in one go. *)\nPrint ex2_7'.\n\nTheorem ex2_7 {A A'} {P : A -> Type} {P' : A' -> Type} (g : A -> A') (h : forall a, P a -> P' (g a)) (x y : sigT P) (p : x.1 = y.1) (q : transport _ p x.2 = y.2) :\n  let f z := (g z.1 ; h z.1 z.2) in\n    ap f (path_sigma P x y p q) =\n       path_sigma P' (f x) (f y) (ap g p) (concat (inverse (lemma2_3_10 g P' _ _))\n                                                  (concat (lemma2_3_11 P (P' o g) _ _ _) (ap _ q))).\n  intros; subst f. destruct x; destruct y; simpl in *; unfold lemma2_3_10, lemma2_3_11.\n  path_induction; reflexivity.\nQed.\n\n(* This is stated and proved in the library proper in slightly different form *)\nPrint ap_functor_sigma.\n\n(* Exercise 2.8 *)\n\n(* Reader is also encouraged to check out commentary here, by Bob Harper:\nhttps://www.dropbox.com/sh/jwtpx1rzal7um28/sOgTLhW1Zu/cancellation.pdf  *)\n\n(* coproducts aka sums *)\nRequire Import Sum.\n\n(* We first reproduce the left-code and the right-code which is presented in\nSection 2.12 of the HoTT book, as well as the appropriate equivalences. *)\n\nDefinition lcode {A B} (a0 : A) (x : A + B) :=\n  match x return Type with inl a => a0 = a | inr b => Empty end.\nDefinition lencode {A B} {a0 : A} {x : A + B} (p : inl a0 = x) : lcode a0 x :=\n  transport (lcode a0) p 1.\nDefinition ldecode {A B} {a0 : A} {x : A + B} (c : lcode a0 x) : inl a0 = x.\n  destruct x. exact (ap inl c). destruct c.\nDefined.\n(* Done with tactics to automatically push the lambda abstraction inside the\ncase on x and avoid writing all of the annotations for dependent match. *)\nPrint ldecode.\nLemma thm2_12_15_alpha {A B} {a0 : A} {x : A + B} (c : lcode a0 x) : (lencode (ldecode c)) = c.\n  destruct x; destruct c; reflexivity.\nQed.\nLemma thm2_12_15_beta {A B} {a0 : A} {x : A + B} (p : inl a0 = x) : (ldecode (lencode p)) = p.\n  path_induction; reflexivity.\nQed.\nTheorem thm2_12_15 {A B} (a0 : A) (x : A + B) : IsEquiv (@lencode A B a0 x).\n  apply (isequiv_adjointify _ ldecode thm2_12_15_alpha thm2_12_15_beta ).\nQed.\n\nDefinition rcode {A B} (b0 : B) (x : A + B) := match x return Type with inl a => Empty | inr b => b0 = b end.\nDefinition rencode {A B} {b0 : B} {x : A + B} (p : inr b0 = x) : rcode b0 x := transport (rcode b0) p 1.\nDefinition rdecode {A B} {b0 : B} {x : A + B} (c : rcode b0 x) : inr b0 = x.\n  destruct x. destruct c. f_ap.\nDefined.\nLemma thm2_12_15'_alpha {A B} {b0 : B} {x : A + B} (c : rcode b0 x) : (rencode (rdecode c)) = c.\n  destruct x; destruct c. reflexivity.\nQed.\nLemma thm2_12_15'_beta {A B} {b0 : B} {x : A + B} (p : inr b0 = x) : (rdecode (rencode p)) = p.\n  path_induction. reflexivity.\nQed.\nTheorem thm2_12_15' {A B} (b0 : B) (x : A + B) : IsEquiv (@rencode A B b0 x).\n  apply (isequiv_adjointify _ rdecode thm2_12_15'_alpha thm2_12_15'_beta ).\nQed.\n\n(* To a new reader, it probably will not be obvious what the codes are for.\nThe hardest part of this question is knowing how to /state/ the functoriality\nproperty at all.\n\nReferring back to the question statement, we've been asked to state and\nprove a corresponding theorem to the functoriality of ap on products.\nWe can go ahead and attempt to translate the theorem into the language\nof coproducts, but the first question one has to answer here is, what corresponds\npair^= here?  We have been instructed that pair^= is the \"introduction rule\"\nfor equality on products; we are looking for a similar introduction rule for\nequality on sums.  But where it was simply enough to provide two equalities\nin the case of product (a negative type former), which equality we provide\nfor a sum type depends on the tags of the values. (a positive type variable)\nSo what this \"equality\" is, is in fact the *code* for equality over coproducts.\n\nWhile we may not have a good idea what the type of this introduction rule\nis, we might know what it is named.  Fortunately, the standard library\nalready provides us the introduction rule for coproducts; and we can see what\nthe *code* is (the lhs of the arrow): *)\n\nCheck path_sum.\n\n(* In the HoTT library, the matches for the codes for coproducts are all explicitly\nwritten out.  However, it will simplify our work if we wrap them up in a definition,\nwhich we will call 'code'. I take advantage of the previous left-code and right-code\ndefinitions, but there's not any specific reason why they have to be used.  When\nHarper gives a presentation of this material, he simply states that these are\ndefined by double case-match. *)\n\nDefinition code {A B} (x0 : A + B) (x : A + B) :=\n  match x0 with\n      inl a0 => lcode a0 x\n    | inr b0 => rcode b0 x\n  end.\n\n(* For completeness, though, here is the expanded version: *)\nDefinition code' {A B} (x0 : A + B) (x : A + B) :=\n  match x0 with\n      inl a0 => match x with\n                    inl a => a0 = a\n                  | inr b => Empty\n                end\n    | inr b0 => match x with\n                    inl a => Empty\n                  | inr b => b0 = b\n                end\n  end.\n(* Sanity check that these are definitionally equal: *)\nLemma code_code' {A B} (x0 : A + B) (x : A + B) : code x0 x = code' x0 x. reflexivity. Qed.\n\nDefinition encode {A B} {x0 x : A + B} (p : x0 = x) : code x0 x.\n  destruct x0; [ exact (lencode p) | exact (rencode p) ].\nDefined.\nDefinition decode {A B} {x0 x : A + B} (c : code x0 x) : x0 = x.\n  destruct x0; [ exact (ldecode c) | exact (rdecode c) ].\nDefined.\nLemma encode_eq_alpha {A B} {x0 : A + B} {x : A + B} (c : code x0 x) : encode (decode c) = c.\n  destruct x0. apply thm2_12_15_alpha. apply thm2_12_15'_alpha.\nDefined.\nLemma encode_eq_beta {A B} {x0 : A + B} {x : A + B} (p : x0 = x) : decode (encode p) = p.\n  path_induction; destruct x0; reflexivity.\nQed.\nTheorem encode_eq {A B} (x0 : A + B) (x : A + B) : IsEquiv (@encode A B x0 x).\n  apply (isequiv_adjointify _ decode encode_eq_alpha encode_eq_beta ).\nQed.\n\n(* The statement of functoriality ap, then, says what the action of ap\nis on elements of the /code/. (In the case of products, that was just the pair of equalities.) *)\n\nTheorem ex2_8 {A B A' B' : Type} (g : A -> A') (h : B -> B') (x y : A + B) (pq : code x y) :\n  let f z := match z with inl z' => inl (g z') | inr z' => inr (h z') end in\n  ap f (path_sum x y pq) = path_sum (f x) (f y)\n     ((match x return code x y -> code (f x) (f y) with\n          inl a0 => match y return lcode a0 y -> lcode (g a0) (f y) with\n                        inl a => ap g\n                      | inr b => fun p => p\n                    end\n        | inr b0 => match y return rcode b0 y -> rcode (h b0) (f y) with\n                        inl a => fun p => p\n                      | inr b => ap h\n                    end\n      end) pq).\n  destruct x; destruct y; unfold code, lcode, rcode in *;\n  try solve [destruct pq]; path_induction; reflexivity.\nQed.\n\n(* Harper describes a rather interesting alternate method for proving functoriality, which\nI tried developing here, but gave up midway.\nDefinition apf_inv {A B} (f : A -> B) {eq : IsEquiv f} {a a' : A} : f a = f a' -> a = a' :=\n  fun q => ((eissect f a) ^ @ ap (f ^-1)%equiv q @ (eissect f a'))%path.\nDefinition apf_alpha {A B} {f : A -> B} {eq : IsEquiv f} {a a' : A} (p : a = a') : apf_inv f (ap f p) = p.\n  path_induction. unfold apf_inv; simpl.\n  refine (concat (ap (fun p => (p @ eissect f a)%path) (concat_p1 _)) _).\n  apply concat_Vp.\nDefined.\nDefinition apf_beta {A B} {f : A -> B} {eq : IsEquiv f} {a a' : A} (q : f a = f a') : ap f (apf_inv f q) = q.\n  (* Notice path_induction doesn't do anything *)\n  (* Discover the correct path *)\n  unfold apf_inv.\n  refine ((concat_p1 _) ^ @ _)%path.\n  assert (p : a = a').\n    refine ((eissect f a) ^ @ _)%path.\n    refine ((ap (f ^-1)%equiv q) @ _)%path.\n    exact ((eissect f a')).\n  unfold apf_inv.\n  path_induction.\n  \n\nTheorem apf_eq {A B} {f : A -> B} {eq : IsEquiv f} {x y : A}: IsEquiv (@ap _ _ f x y).\n  *)\n(* Exercise 2.9 *)\n\nDefinition sum_universal_iso {A B X : Type} (f : A + B -> X) : (A -> X) * (B -> X) := (fun a => f (inl a), fun b => f (inr b)).\nDefinition sum_universal_osi {A B X : Type} (hg : (A -> X) * (B -> X)) : A + B -> X := let (g, h) := hg in fun x => match x with inl a => g a | inr b => h b end.\nDefinition sum_universal_alpha {A B X : Type} `{Funext} (f : A + B -> X) : sum_universal_osi (sum_universal_iso f) = f.\n  unfold sum_universal_iso, sum_universal_osi. apply H; intro x. destruct x; reflexivity.\nDefined.\nDefinition sum_universal_beta {A B X : Type} (hg : (A -> X) * (B -> X)) : sum_universal_iso (sum_universal_osi hg) = hg.\n  unfold sum_universal_iso, sum_universal_osi. destruct hg; reflexivity.\nDefined.\n\nDefinition sum_universal {A B X : Type} `{Funext} : (A -> X) * (B -> X) <~> (A + B -> X).\n  apply (equiv_adjointify sum_universal_osi sum_universal_iso sum_universal_alpha sum_universal_beta).\nDefined.\n\n(* Presence of function extensionality makes doing the adjointified version annoying. *)\n\n(* Exercise 2.10 *)\n\nDefinition sigma_assoc_iso {A} {B : A -> Type} (C : sigT (fun x : A => B x) -> Type) (p : sigT (fun x : A => sigT (fun y : B x => C (x; y)))) : (sigT (fun (p : sigT (fun x : A => B x)) => C p)) := ((p.1; p.2.1); p.2.2).\n\nDefinition sigma_assoc_osi {A} {B : A -> Type} (C : sigT (fun x : A => B x) -> Type) (p : sigT (fun (p : sigT (fun x : A => B x)) => C p)) : (sigT (fun x : A => sigT (fun y : B x => C (x; y)))).\n  destruct p. destruct x. refine (x; _). refine (b; _). exact c.\nDefined.\n(* Looking at the dependent pattern match is instructive, and shows the classic\ntrick for refining the type of c. But I'm a lazy bastard, and the match is about\nwhat I want. *)\nPrint sigma_assoc_osi.\n\nLtac simplHyp :=\n  match goal with\n      | [ H : _ * _ |- _ ] => destruct H\n      | [ H : sigT _ |- _ ] => destruct H\n  end.\n\nLtac crush := simpl in *; repeat simplHyp; try trivial; try solve [f_ap].\n\nDefinition sigma_assoc {A} {B : A -> Type} (C : sigT (fun x : A => B x) -> Type) :\n  sigT (fun x : A => sigT (fun y : B x => C (x; y))) <~> sigT (fun (p : sigT (fun x : A => B x)) => C p).\n  refine (equiv_adjointify (@sigma_assoc_iso A B C) (@sigma_assoc_osi A B C) _ _);\n  intro; unfold sigma_assoc_osi, sigma_assoc_iso; crush.\nQed.\n \n(* Exercise 2.11 *)\n\n(* To show that something is the corner of a pullback square, we just need to\nshow the desired equivalence. *)\n\nRequire Import ObjectClassifier.\nPrint pullback.\n\nDefinition pullback1 {A B C} (f : A -> C) (g : B -> C) (p : pullback f g) : A := p.1.\nDefinition pullback2 {A B C} (f : A -> C) (g : B -> C) (p : pullback f g) : B := p.2.1.\n\n(* Stating the definitions of pullf and pullf_inv using apD10 is *critical*;\n we will be doing reasoning with the fact that apD10 is an equivalence, and\n if some of the parts of the definition are unfolded it will greatly obscure\n what is going on. *)\nDefinition pullf {A B C} X `{Funext} (f : A -> C) (g : B -> C) (h : X -> pullback f g) : pullback (@compose X _ _ f) (@compose X _ _ g).\n  refine (pullback1 f g o h; _).\n  refine (pullback2 f g o h; _).\n  apply path_forall; intro.\n  exact (h x).2.2.\nDefined.\nDefinition pullf_inv {A B C} X (f : A -> C) (g : B -> C) (z : pullback (@compose X _ _ f) (@compose X _ _ g)) (x : X) : pullback f g.\n  refine (z.1 x; (z.2.1 x; _)).\n  exact (apD10 z.2.2 x).\nDefined.\n\nTheorem ex2_11 `{Funext} {A B C X} {f : A -> C} {g : B -> C} : IsEquiv (pullf X f g).\n  refine (isequiv_adjointify _ (pullf_inv X f g) _ _).\n\n  unfold Sect, pullf_inv, pullf, path_forall; simpl. destruct 0 as [f' [g' p]]; simpl. f_ap. f_ap.\n  apply ((ap apD10)^-1)%equiv.\n  apply (eisretr apD10).\n\n  unfold Sect, pullf_inv, pullf, path_forall; intro h; simpl.\n  apply path_forall; intro x.\n  repeat (apply path_sigma_uncurried; exists idpath; simpl).\n  change (h x).2.2 with ((fun x' => (h x').2.2) x); f_ap. (* because higher-order unification is undecidable *)\n  apply eisretr.\nQed.\n\n(* Exercise 2.12 *)\n\n(* In the previous exercise we specialized (since h = .1 and k = .2.1), but for this exercise P is\ngeneric so it will be good to properly define pullback squares and the induced map in full\ngenerality. *)\n\n(* P.S. I tried an alternate formulation where squares were defined specifically as pullbacks.\nBut this is a little annoying when you have two squares joined together, because you have\nto explicitly state that two edges of the square are equal. So I decided to go back to the\nmore straightforward version. *)\n\n(* It's important to specify the input type of compose, since the inferencer gets\nconfused otherwise. *)\n\n(* P -> A\n   ↓    ↓\n   B -> C *)\nDefinition induced_map `{Funext} {P A B C} (f : A -> C) (g : B -> C) (h : P -> A) (k : P -> B) (p : f o h = g o k) X (i : X -> P) : pullback (@compose X _ _ f) (@compose X _ _ g).\n  refine (h o i; (k o i; _)).\n  change (f o h o i = g o k o i).\n  refine (apD10 _ i).\n  exact (ap compose p).\nDefined.\n\n(* BTW, why couldn't pullf be defined in the same, graceful manner?  Well,\nthe trouble is while the p here is explicitly provided, in the pullback case\nwe got it out of the fact that pullbacks come with equality proofs.  We could\nhave factored this out, so that the call-site of pullf was responsible\nfor the extraction, but doing it the other way seemed more natural. It's a\nsleight of hand that reduces the arguments you need to pass around. (In\na sense, we embedded the proof that it is a commutative square). *)\n\nDefinition pullback_square `{Funext} {P A B C}\n                           (f : A -> C) (g : B -> C) (h : P -> A) (k : P -> B)\n                           (p : f o h = g o k) := \n  forall X, IsEquiv (induced_map f g h k p X).\n\n(* The squares reproduced for your convenience:\n  A -> C -> E\n  ↓ p  ↓ q  ↓\n  B -> D -> F \n    \\--r--/  *)\n\n(* XXX I don't actually know if this is called whiskering *)\nDefinition whisker\n          {A B C D E F} \n          {ac : A -> C}\n          {ab : A -> B}\n          {cd : C -> D}\n          {bd : B -> D}\n          {ce : C -> E}\n          {ef : E -> F}\n          {df : D -> F}\n          (p : cd o ac = bd o ab)\n          (q : ef o ce = df o cd)\n  : ef o ce o ac = df o bd o ab.\ntransitivity (df o cd o ac); [f_ap|].\nchange (df o (cd o ac) = df o (bd o ab)); f_ap.\nDefined.\n\n(* the hard one *)\nDefinition induced_map_inv1\n          `{Funext}\n          {A B C D E F X}\n          (ac : A -> C)\n          (ab : A -> B)\n          (cd : C -> D)\n          (bd : B -> D)\n          (ce : C -> E)\n          (ef : E -> F)\n          (df : D -> F)\n          (p : cd o ac = bd o ab)\n          (q : ef o ce = df o cd)\n          (P : pullback_square ef df ce cd q)\n          (S : pullback_square cd bd ac ab p)\n          (z : pullback (@compose X _ _ ef) (@compose X _ _ (df o bd)))\n          : X -> A.\nlet r := constr:((z.1; (bd o z.2.1; z.2.2)) : pullback (@compose X _ _ ef) (@compose X _ _ df)) in pose r as z'.\nlet r := constr:(@equiv_inv _ _ _ (P X) z') in pose r as xc.\nlet r := constr:(induced_map ef df ce cd q X xc) in pose r as z''.\nlet r := constr:(@eisretr _ _ _ (P X) _ : z'' = z') in pose r as alpha. (* crucial! *)\napply (S X).\nrefine (xc ; (z.2.1 ; _)).\n  etransitivity; [| apply (alpha..2..1)]. (* ho ho, use the retraction! *)\n  destruct (alpha ..1). (* get rid of pesky transport *) reflexivity.\nDefined.\nPrint induced_map_inv1.\nDefinition induced_map_inv2\n          `{Funext}\n          {A B C D E F X}\n          (ac : A -> C)\n          (ab : A -> B)\n          (cd : C -> D)\n          (bd : B -> D)\n          (ce : C -> E)\n          (ef : E -> F)\n          (df : D -> F)\n          (p : cd o ac = bd o ab)\n          (q : ef o ce = df o cd)\n          (P : pullback_square ef df ce cd q)\n          (S : pullback_square ef (df o bd) (ce o ac) ab (whisker p q))\n          (z : pullback (@compose X _ _ cd) (@compose X _ _ bd))\n          : X -> A.\napply (S X).\nrefine (ce o z.1 ; (z.2.1 ; _)).\ndestruct z as [xc [xb r]]; simpl.\ntransitivity (df o cd o xc). change (ef o ce o xc = df o cd o xc); f_ap.\nchange (df o (cd o xc) = df o (bd o xb)); f_ap.\nDefined.\n\nTheorem ex2_12\n          `{Funext}\n          {A B C D E F}\n          (ac : A -> C)\n          (ab : A -> B)\n          (cd : C -> D)\n          (bd : B -> D)\n          (ce : C -> E)\n          (ef : E -> F)\n          (df : D -> F)\n          (p : cd o ac = bd o ab)\n          (q : ef o ce = df o cd)\n          (P : pullback_square ef df ce cd q)\n  : (pullback_square cd bd ac ab p <-> pullback_square ef (df o bd) (ce o ac) ab (whisker p q)).\nconstructor; intro S; intro X.\n\nrefine (isequiv_adjointify _ (induced_map_inv1 ac ab cd bd ce ef df p q P S) _ _).\nintro z.  destruct z as [x [y r]].\n(* The proof here now acts a little differently than the other equivalence\nproofs we have encountered.  The first instinct (especially given the other\nequivalence proofs in this chapter) is to destruct the input as much as possible,\nand then show that things simplify to the original.  However, this strategy\nwill not work here,   *)\nadmit.\nintro z. unfold induced_map; simpl. unfold induced_map_inv1; simpl.\nadmit.\n\nrefine (isequiv_adjointify _ (induced_map_inv2 ac ab cd bd ce ef df p q P S) _ _).\nintro z. unfold induced_map_inv2.\nAbort.\n\n(* Exercise 2.13 *)\n\n(* Intuitively, the two inhabitants of Bool ~ Bool are id and neg. *)\n\nDefinition equiv_bool_id : Equiv Bool Bool.\n\nDefinition ex2_13_f (H : Equiv Bool Bool) : Bool.\n  destruct H.\nAbort.\n\nDefinition ex2_13_g : Bool -> Equiv Bool Bool.\n  intro b; destruct b.\nAbort.\n\nLemma ex2_13 : Equiv (Equiv Bool Bool) Bool.\nAbort.", "meta": {"author": "ezyang", "repo": "HoTT-coqex", "sha": "54e5f14408ff330e219821b183cd9edb3cdbfccb", "save_path": "github-repos/coq/ezyang-HoTT-coqex", "path": "github-repos/coq/ezyang-HoTT-coqex/HoTT-coqex-54e5f14408ff330e219821b183cd9edb3cdbfccb/ch2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835330070838, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.6771417896928285}}
{"text": "(** Support for atoms, i.e., objects with decidable equality.  We\n    provide here the ability to generate an atom fresh for any finite\n    collection, e.g., the lemma [atom_fresh_for_set], and a tactic to\n    pick an atom fresh for the current proof context.\n\n    Authors: Arthur Charguéraud and Brian Aydemir.\n\n    Implementation note: In older versions of Coq, [OrderedTypeEx]\n    redefines decimal constants to be integers and not natural\n    numbers.  The following scope declaration is intended to address\n    this issue.  In newer versions of Coq, the declaration should be\n    benign. *)\n\nRequire Import List.\nRequire Import Max.\nRequire Import OrderedType.\nRequire Import OrderedTypeEx.\nOpen Scope nat_scope.\n\nRequire Import FiniteSets.\nRequire Import FSetDecide.\nRequire Import FSetNotin.\nRequire Import ListFacts.\n\n\n(* ********************************************************************** *)\n(** * Definition *)\n\n(** Atoms are structureless objects such that we can always generate\n    one fresh from a finite collection.  Equality on atoms is [eq] and\n    decidable.  We use Coq's module system to make abstract the\n    implementation of atoms.  The [Export AtomImpl] line below allows\n    us to refer to the type [atom] and its properties without having\n    to qualify everything with \"[AtomImpl.]\". *)\n\nModule Type ATOM.\n\n  Parameter atom : Set.\n\n  Parameter atom_fresh_for_list :\n    forall (xs : list atom), {x : atom | ~ List.In x xs}.\n\n  Declare Module Atom_as_OT : UsualOrderedType with Definition t := atom.\n\n  Parameter eq_atom_dec : forall x y : atom, {x = y} + {x <> y}.\n\nEnd ATOM.\n\n(** The implementation of the above interface is hidden for\n    documentation purposes. *)\n\nModule AtomImpl : ATOM.\n\n  (* begin hide *)\n\n  Definition atom := nat.\n\n  Lemma max_lt_r : forall x y z,\n    x <= z -> x <= max y z.\n  Proof.\n    induction x. auto with arith.\n    induction y; auto with arith.\n      simpl. induction z. omega. auto with arith.\n  Qed.\n\n  Lemma nat_list_max : forall (xs : list nat),\n    { n : nat | forall x, In x xs -> x <= n }.\n  Proof.\n    induction xs as [ | x xs [y H] ].\n    (* case: nil *)\n    exists 0. inversion 1.\n    (* case: cons x xs *)\n    exists (max x y). intros z J. simpl in J. destruct J as [K | K].\n      subst. auto with arith.\n      auto using max_lt_r.\n  Qed.\n\n  Lemma atom_fresh_for_list :\n    forall (xs : list nat), { n : nat | ~ List.In n xs }.\n  Proof.\n    intros xs. destruct (nat_list_max xs) as [x H].\n    exists (S x). intros J. lapply (H (S x)). omega. trivial.\n  Qed.\n\n  Module Atom_as_OT := Nat_as_OT.\n  Module Facts := OrderedTypeFacts Atom_as_OT.\n\n  Definition eq_atom_dec : forall x y : atom, {x = y} + {x <> y} :=\n    Facts.eq_dec.\n\n  (* end hide *)\n\nEnd AtomImpl.\n\nExport AtomImpl.\n\n\n(* ********************************************************************** *)\n(** * Finite sets of atoms *)\n\n\n(* ********************************************************************** *)\n(** ** Definitions *)\n\nModule AtomSet : FiniteSets.S with Module E := Atom_as_OT :=\n  FiniteSets.Make Atom_as_OT.\n\n(** The type [atoms] is the type of finite sets of [atom]s. *)\n\nNotation atoms := AtomSet.F.t.\n\n(** Basic operations on finite sets of atoms are available, in the\n    remainder of this file, without qualification.  We use [Import]\n    instead of [Export] in order to avoid unnecessary namespace\n    pollution. *)\n\nImport AtomSet.F.\n\n(** We instantiate two modules which provide useful lemmas and tactics\n    work working with finite sets of atoms. *)\n\nModule AtomSetDecide := FSetDecide.Decide AtomSet.F.\nModule AtomSetNotin  := FSetNotin.Notin   AtomSet.F.\n\n\n(* *********************************************************************** *)\n(** ** Tactics for working with finite sets of atoms *)\n\n(** The tactic [fsetdec] is a general purpose decision procedure\n    for solving facts about finite sets of atoms. *)\n\nLtac fsetdec := try apply AtomSet.eq_if_Equal; AtomSetDecide.fsetdec.\n\n(** The tactic [notin_simpl] simplifies all hypotheses of the form [(~\n    In x F)], where [F] is constructed from the empty set, singleton\n    sets, and unions. *)\n\nLtac notin_simpl := AtomSetNotin.notin_simpl_hyps.\n\n(** The tactic [notin_solve], solves goals of the form [(~ In x F)],\n    where [F] is constructed from the empty set, singleton sets, and\n    unions.  The goal must be provable from hypothesis of the form\n    simplified by [notin_simpl]. *)\n\nLtac notin_solve := AtomSetNotin.notin_solve.\n\n\n(* *********************************************************************** *)\n(** ** Lemmas for working with finite sets of atoms *)\n\n(** We make some lemmas about finite sets of atoms available without\n    qualification by using abbreviations. *)\n\nNotation eq_if_Equal        := AtomSet.eq_if_Equal.\nNotation notin_empty        := AtomSetNotin.notin_empty.\nNotation notin_singleton    := AtomSetNotin.notin_singleton.\nNotation notin_singleton_rw := AtomSetNotin.notin_singleton_rw.\nNotation notin_union        := AtomSetNotin.notin_union.\n\n\n(* ********************************************************************** *)\n(** * Additional properties *)\n\n(** One can generate an atom fresh for a given finite set of atoms. *)\n\nLemma atom_fresh_for_set : forall L : atoms, { x : atom | ~ In x L }.\nProof.\n  intros L. destruct (atom_fresh_for_list (elements L)) as [a H].\n  exists a. intros J. contradiction H.\n  rewrite <- InA_iff_In. auto using elements_1.\nQed.\n\n\n(* ********************************************************************** *)\n(** * Additional tactics *)\n\n\n(* ********************************************************************** *)\n(** ** #<a name=\"pick_fresh\"></a># Picking a fresh atom *)\n\n(** We define three tactics which, when combined, provide a simple\n    mechanism for picking a fresh atom.  We demonstrate their use\n    below with an example, the [example_pick_fresh] tactic.\n\n   [(gather_atoms_with F)] returns the union of [(F x)], where [x]\n   ranges over all objects in the context such that [(F x)] is\n   well typed.  The return type of [F] should be [atoms].  The\n   complexity of this tactic is due to the fact that there is no\n   support in [Ltac] for folding a function over the context. *)\n\nLtac gather_atoms_with F :=\n  let rec gather V :=\n    match goal with\n    | H: ?S |- _ =>\n      let FH := constr:(F H) in\n      match V with\n      | empty => gather FH\n      | context [FH] => fail 1\n      | _ => gather (union FH V)\n      end\n    | _ => V\n    end in\n  let L := gather empty in eval simpl in L.\n\n(** [(beautify_fset V)] takes a set [V] built as a union of finite\n    sets and returns the same set with empty sets removed and union\n    operations associated to the right.  Duplicate sets are also\n    removed from the union. *)\n\nLtac beautify_fset V :=\n  let rec go Acc E :=\n     match E with\n     | union ?E1 ?E2 => let Acc1 := go Acc E2 in go Acc1 E1\n     | empty => Acc\n     | ?E1 => match Acc with\n              | empty => E1\n              | context [E1] => Acc\n              | _ => constr:(union E1 Acc)\n              end\n     end\n  in go empty V.\n\n(** The tactic [(pick fresh Y for L)] takes a finite set of atoms [L]\n    and a fresh name [Y], and adds to the context an atom with name\n    [Y] and a proof that [(~ In Y L)], i.e., that [Y] is fresh for\n    [L].  The tactic will fail if [Y] is already declared in the\n    context. *)\n\nTactic Notation \"pick\" \"fresh\" ident(Y) \"for\" constr(L) :=\n  let Fr := fresh \"Fr\" in\n  let L := beautify_fset L in\n  (destruct (atom_fresh_for_set L) as [Y Fr]).\n\n\n(* ********************************************************************** *)\n(** ** Demonstration *)\n\n(** The [example_pick_fresh] tactic below illustrates the general\n    pattern for using the above three tactics to define a tactic which\n    picks a fresh atom.  The pattern is as follows:\n      - Repeatedly invoke [gather_atoms_with], using functions with\n        different argument types each time.\n      - Union together the result of the calls, and invoke\n        [(pick fresh ... for ...)] with that union of sets. *)\n\nLtac example_pick_fresh Y :=\n  let A := gather_atoms_with (fun x : atoms => x) in\n  let B := gather_atoms_with (fun x : atom => singleton x) in\n  pick fresh Y for (union A B).\n\nLemma example_pick_fresh_use : forall (x y z : atom) (L1 L2 L3: atoms), True.\n(* begin show *)\nProof.\n  intros x y z L1 L2 L3. example_pick_fresh k.\n\n  (** At this point in the proof, we have a new atom [k] and a\n      hypothesis [Fr : ~ In k (union L1 (union L2 (union L3 (union\n      (singleton x) (union (singleton y) (singleton z))))))]. *)\n\n  trivial.\nQed.\n(* end show *)\n", "meta": {"author": "jeapostrophe", "repo": "redex", "sha": "8e5810e452878a4ab5153d19725cfc4cf2b0bf46", "save_path": "github-repos/coq/jeapostrophe-redex", "path": "github-repos/coq/jeapostrophe-redex/redex-8e5810e452878a4ab5153d19725cfc4cf2b0bf46/icfp09-atotcaia/coercions/Atom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.6771417787235989}}
{"text": "(* ***************************************************************** *)\n(*                                                                   *)\n(* Released: 2020/04/04.                                             *)\n(* Due: 2020/04/08, 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 PL.Imp.\nRequire Import PL.ImpExt3.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import Coq.micromega.Psatz.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Classes.Morphisms.\n\n(** In this assignment, we are going to establish another denotational semantics\n    for our simple imperative language. This time, a program's denotation is\n    defined as a ternary relation. Specifically, [st1, t, st2] belongs to the\n    denotation of program [c] if and only if executing [c] from [st1] may take\n    time [t] and stop at state [st2].\n\n    We could write a more realistic definition here, but in order to make things\n    simple, we assume every assignment command takes one unit of time, every\n    testing (for either if-command, or loop condition testing) takes one unit of\n    time and the [Skip] command does not take any time. *)\n\nDefinition skip_sem: state -> Z -> state -> Prop :=\n  fun st1 t st2 =>\n    st1 = st2 /\\ t = 0.\n\nDefinition asgn_sem (X: var) (E: aexp): state -> Z -> state -> Prop :=\n  fun st1 t st2 =>\n    st2 X = aeval E st1 /\\\n    forall Y, X <> Y -> st1 Y = st2 Y /\\\n    t = 1.\n\nDefinition seq_sem (d1 d2: state -> Z -> state -> Prop)\n  : state -> Z -> state -> Prop\n:=\n  fun st1 t st3 =>\n    exists t1 t2 st2,\n      d1 st1 t1 st2 /\\ d2 st2 t2 st3 /\\ t = t1 + t2.\n\nDefinition test_sem (X: state -> Prop): state -> Z -> state -> Prop :=\n  fun st1 t st2 =>\n    st1 = st2 /\\ X st1 /\\ t = 1.\n\nDefinition union_sem (d d': state -> Z -> state -> Prop)\n  : state -> Z -> state -> Prop\n:=\n  fun st1 t st2 =>\n    d st1 t st2 \\/ d' st1 t st2.\n\nDefinition if_sem (b: bexp) (d1 d2: state -> Z -> state -> Prop)\n  : state -> Z -> state -> Prop\n:=\n  union_sem\n    (seq_sem (test_sem (beval b)) d1)\n    (seq_sem (test_sem (beval (! b))) d2).\n\nFixpoint iter_loop_body\n  (b: bexp)\n  (loop_body: state -> Z -> state -> Prop)\n  (n: nat)\n  : state -> Z -> state -> Prop\n:=\n  match n with\n  | O => test_sem (beval (! b))\n  | S n' => seq_sem\n              (test_sem (beval b))\n              (seq_sem loop_body (iter_loop_body b loop_body n'))\n  end.\n\nDefinition omega_union_sem (d: nat -> state -> Z -> state -> Prop)\n  : state -> Z -> state -> Prop\n:=\n  fun st1 t st2 => exists n, d n st1 t st2.\n\nDefinition loop_sem (b: bexp) (loop_body: state -> Z -> state -> Prop)\n  : state -> Z -> state -> Prop\n:=\n  omega_union_sem (iter_loop_body b loop_body).\n\nFixpoint ceval (c: com): state -> Z -> state -> Prop :=\n  match c with\n  | CSkip => skip_sem\n  | CAss X E => asgn_sem X E\n  | CSeq c1 c2 => seq_sem (ceval c1) (ceval c2)\n  | CIf b c1 c2 => if_sem b (ceval c1) (ceval c2)\n  | CWhile b c => loop_sem b (ceval c)\n  end.\n\n(* ################################################################# *)\n(** * Task 1: The Theory Of Ternary Relations *)\n\nDefinition sem_equiv (d1 d2: state -> Z -> state -> Prop): Prop :=\n  forall st1 t st2, d1 st1 t st2 <-> d2 st1 t st2.\n\n(** You should first prove that [sem_equiv] is an equivalence relation and it\n    is preserved by [seq_sem], [union_sem], [omega_union_sem]. Also, [test_sem]\n    will always turn equivalent state sets into equivalent ternary relations. *)\n\n(** **** Exercise: 1 star, standard (sem_equiv_refl)  *)\n\nLemma sem_equiv_refl: Reflexive sem_equiv.\nProof.\n  unfold Reflexive, sem_equiv.\n  intros.\n  split;intro;exact H.\nQed.\n(** [] *)\n  \n(** **** Exercise: 1 star, standard (sem_equiv_sym)  *)\n\nLemma sem_equiv_sym: Symmetric sem_equiv.\nProof.\n  unfold Symmetric, sem_equiv.\n  intros.\n  split;intro;apply H,H0.\nQed.\n(** [] *)\n  \n(** **** Exercise: 1 star, standard (sem_equiv_trans)  *)\n\nLemma sem_equiv_trans: Transitive sem_equiv.\nProof.\n  unfold Transitive, sem_equiv.\n  intros.\n  split;intro.\n  - apply H0, H, H1.\n  - apply H, H0, H1.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (seq_sem_equiv)  *)\n\nLemma seq_sem_equiv: Proper (sem_equiv ==> sem_equiv ==> sem_equiv) seq_sem.\nProof.\n  unfold Proper, respectful.\n  intros. unfold seq_sem, sem_equiv.\n  intros. split;intros [t1 [t2 [st' [H1 [H2 H3]]]]].\n  - exists t1, t2, st'. repeat split.\n    + apply H. exact H1.\n    + apply H0. exact H2.\n    + exact H3.\n  - exists t1, t2, st'. repeat split.\n    + apply H. exact H1.\n    + apply H0. exact H2.\n    + exact H3.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (union_sem_equiv)  *)\n\nLemma union_sem_equiv: Proper (sem_equiv ==> sem_equiv ==> sem_equiv) union_sem.\nProof.\n  unfold Proper, respectful.\n  intros. unfold union_sem, sem_equiv.\n  intros. split;intros [H1|H1];\n  try apply H in H1; try apply H0 in H1; tauto.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (omega_union_sem_equiv)  *)\n\nLemma omega_union_sem_equiv: forall d1 d2: nat -> state -> Z -> state -> Prop,\n  (forall n: nat, sem_equiv (d1 n) (d2 n)) ->\n  sem_equiv (omega_union_sem d1) (omega_union_sem d2).  \nProof.\n  intros.\n  unfold sem_equiv, omega_union_sem.\n  split;intros [n H0];exists n;apply H;tauto.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard (test_sem_equiv)  *)\n\nLemma test_sem_equiv: Proper (Sets.equiv ==> sem_equiv) test_sem.\nProof.\n  unfold Proper, respectful.\n  intros. unfold sem_equiv,test_sem.\n  intros. split; intros [H1 [H2 H3]];apply H in H2;tauto.\nQed.\n(** [] *)\n\nExisting Instances sem_equiv_refl\n                   sem_equiv_sym\n                   sem_equiv_trans\n                   seq_sem_equiv\n                   union_sem_equiv\n                   test_sem_equiv.\n\n(** Also, it is important that [union_sem] is commutative and associative, and\n    [seq_sem] is associative, distributive and absorbing [skip_sem].  *)\n\n(** **** Exercise: 1 star, standard (union_sem_comm)  *)\n\nLemma union_sem_comm: forall d1 d2,\n  sem_equiv (union_sem d1 d2) (union_sem d2 d1).\nProof.\n  intros.\n  unfold sem_equiv, union_sem.\n  intros. tauto.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (union_sem_assoc)  *)\n\nLemma union_sem_assoc: forall d1 d2 d3,\n  sem_equiv (union_sem d1 (union_sem d2 d3)) (union_sem (union_sem d1 d2) d3).\nProof.\n  intros.\n  unfold sem_equiv, union_sem.\n  intros. tauto.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (seq_sem_assoc)  *)\n\nLemma seq_sem_assoc: forall d1 d2 d3,\n  sem_equiv (seq_sem d1 (seq_sem d2 d3)) (seq_sem (seq_sem d1 d2) d3).\nProof.\nProof.\n  intros.\n  unfold sem_equiv, seq_sem.\n  intros.\n  split; intros [t1 [t2 [st3 [H1 H2]]]].\n  - destruct H2 as [[t3 [t4 [st4 [H2 [H3 H4]]]]] H5].\n    exists (t1+t3), t4, st4.\n    repeat split;subst t t2;auto;try lia.\n    exists t1,t3, st3.\n    tauto.\n  - destruct H2 as [H4 H5].\n    destruct H1 as [t3 [t4 [st4 [H1 [H2 H3]]]]].\n    exists t3, (t4 + t2), st4.\n    repeat split;auto;try lia.\n    exists t4, t2, st3.\n    tauto.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (seq_union_distr_l)  *)\n\nLemma seq_union_distr_l: forall d1 d2 d3,\n  sem_equiv\n    (seq_sem d1 (union_sem d2 d3))\n    (union_sem (seq_sem d1 d2) (seq_sem d1 d3)).\nProof.\n  intros. unfold sem_equiv.\n  intros. unfold seq_sem, union_sem. split;intro.\n  - destruct H as [t1 [t2 [st3 [H1 [[H2|H2] H3]]]]].\n    + left. exists t1, t2,st3. tauto.\n    + right. exists t1, t2, st3. tauto.\n  - destruct H as [[t1 [t2 [st3 H]]]|[t1 [t2 [st3 H]]]];\n    exists t1, t2, st3;tauto.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (seq_union_distr_r)  *)\n\nLemma seq_union_distr_r: forall d1 d2 d3,\n  sem_equiv\n    (seq_sem (union_sem d1 d2) d3)\n    (union_sem (seq_sem d1 d3) (seq_sem d2 d3)).\nProof.\n  unfold sem_equiv, seq_sem, union_sem.\n  intros. split;intro.\n  - destruct H as [t1 [t2 [st3 [[H|H] H1]]]].\n    + left. exists t1, t2, st3. tauto.\n    + right. exists t1, t2, st3. tauto.\n  - destruct H as [[t1 [t2 [st3 H]]]|[t1 [t2 [st3 H]]]];\n    exists t1, t2, st3;tauto.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (seq_skip_l)  *)\n\nLemma seq_skip_l: forall d, sem_equiv (seq_sem skip_sem d) d.\nProof.\n  intros. unfold sem_equiv, seq_sem, skip_sem.\n  intros. split;intro.\n  - destruct H as [t1 [t2 [st3 [[? ?] [? ?]]]]].\n    subst. apply H1. \n  -  exists 0, t, st1. tauto.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (seq_skip_r)  *)\n\nLemma seq_skip_r: forall d, sem_equiv (seq_sem d skip_sem) d.\nProof.\n  intros. unfold sem_equiv, seq_sem, skip_sem.\n  intros. split;intro.\n  - destruct H as [t1 [t2 [st3 [? [[? ?] ?]]]]].\n    subst. rewrite Zplus_0_r. apply H. \n  - exists t, 0, st2. rewrite Zplus_0_r. tauto.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Task 2: Program Equivalence Is An Equivalence *)\n\n(** By a different program semantics, we can have a different sense of program\n    equivalence. For example, the following two program were thought to be\n    equivalent in class because they have the same effects: [ X ::= 0 ] vs.\n    [ X ::= 1;; X ::= 0 ]. However, they take different amount of time to\n    execute according to our semantic model. Thus, in some sense, they are\n    not that equivalent.\n\n    In this task, we will prove for you that our new program equivalence (see\n    below) is an equivalence relation. You need to answer some questions about\n    these proofs. *)\n\nDefinition com_equiv (c1 c2: com): Prop :=\n  sem_equiv (ceval c1) (ceval c2).\n\nLemma com_equiv_refl: Reflexive com_equiv.\nProof.\n  unfold Reflexive, com_equiv.\n  intros.\n  reflexivity.\nQed.\n\n(** **** Exercise: 1 star, standard (com_equiv_refl_uses)  *)\n\n(** Which property/properties about [sem_equiv] does this proof use?\n\n    1. Reflexivity, [sem_equiv_refl];\n\n    2. Symmetry, [sem_equiv_sym];\n\n    3. Transitivity, [sem_equiv_trans].\n\n    Hint: this is a multiple-choice problem. You should use an ascending Coq\n    list to describe your answer, e.g. [1; 2; 3; 4], [1; 3], [2]. *)\n\nDefinition com_equiv_refl_uses: list Z := [1].\n(** [] *)\n\nLemma com_equiv_sym: Symmetric com_equiv.\nProof.\n  unfold Symmetric, com_equiv.\n  intros.\n  rewrite H.\n  reflexivity.\nQed.\n\n(** **** Exercise: 1 star, standard (com_equiv_sym_uses)  *)\n\n(** Which property/properties about [sem_equiv] does this proof use?\n\n    1. Reflexivity, [sem_equiv_refl];\n\n    2. Symmetry, [sem_equiv_sym];\n\n    3. Transitivity, [sem_equiv_trans]. *)\n\nDefinition com_equiv_sym_uses: list Z := [1;2;3].\n(** [] *)\n\nLemma com_equiv_trans: Transitive com_equiv.\nProof.\n  unfold Transitive, com_equiv.\n  intros.\n  rewrite H, H0.\n  reflexivity.\nQed.\n\n(** **** Exercise: 1 star, standard (com_equiv_trans_uses)  *)\n\n(** Which property/properties about [sem_equiv] does this proof use?\n\n    1. Reflexivity, [sem_equiv_refl];\n\n    2. Symmetry, [sem_equiv_sym];\n\n    3. Transitivity, [sem_equiv_trans]. *)\n\nDefinition com_equiv_trans_uses: list Z := [1;3].\n(** [] *)\n\n(* ################################################################# *)\n(** * Task 3: Program Equivalence Is A Congruence *)\n\n(** In this task, you need to prove that [com_equiv] is a congruence. The first\n    one is done for you.*)\n\nLemma CSeq_congr: Proper (com_equiv ==> com_equiv ==> com_equiv) CSeq.\nProof.\n  unfold Proper, respectful.\n  unfold com_equiv.\n  intros c1 c1' ? c2 c2' ?.\n  simpl.\n  rewrite H, H0.\n  reflexivity.\nQed.\n\n(** **** Exercise: 1 star, standard (CAss_congr)  *)\n\nInstance asgn_congr: forall (X: var),\nProper (aexp_equiv ==> sem_equiv) (asgn_sem X).\nProof.\n  unfold Proper, respectful.\n  intros. unfold sem_equiv.\n  unfold ceval, asgn_sem, sem_equiv.\n  intros. split;intro.\n  - rewrite <- H. exact H0.\n  - rewrite H. exact H0.\nQed.\n\nLemma CAss_congr: forall (X: var),\n  Proper (aexp_equiv ==> com_equiv) (CAss X).\nProof.\n  unfold Proper, respectful.\n  unfold com_equiv.\n  intros X s1 s1' ?. simpl.\n  rewrite H.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (CIf_congr)  *)\n\nLemma CIf_congr:\n  Proper (bexp_equiv ==> com_equiv ==> com_equiv ==> com_equiv) CIf.\nProof.\n  unfold Proper, respectful.\n  unfold com_equiv.\n  intros b b' ? x y ? x' y' ?.\n  simpl. unfold if_sem. rewrite H0. rewrite H1.\n  unfold bexp_equiv in H.\n  simpl. rewrite H.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (CWhile_congr)  *)\n\nLemma CWhile_congr:\n  Proper (bexp_equiv ==> com_equiv ==> com_equiv) CWhile.\nProof.\n  hnf. unfold respectful.\n  unfold com_equiv.\n  intros b b' ? x x' ?.\n  simpl. unfold loop_sem.\n  apply omega_union_sem_equiv.\n  intros.\n  induction n.\n  - simpl. unfold bexp_equiv in H. rewrite H.\n    reflexivity.\n  - simpl. rewrite IHn. unfold bexp_equiv in H.\n    rewrite H. rewrite H0. reflexivity.\nQed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Task 4: Typical Program Transiformations *)\n\n(** In this task, you need to prove that the following transformations still\n    genetate equivalent programs, according to our new definition of\n    [com_equiv]. Hint: some lemmas that we have proved in previous tasks may be\n    helpful. *)\n\n(** **** Exercise: 1 star, standard (swap_if_branches)  *)\n\nTheorem swap_if_branches : forall b c1 c2,\n  com_equiv\n    (If b Then c1 Else c2 EndIf)\n    (If (BNot b) Then c2 Else c1 EndIf).\nProof.\n  intros.\n  unfold com_equiv. simpl.\n  unfold if_sem.\n  simpl.\n  rewrite Sets_complement_complement.\n  apply union_sem_comm.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (seq_assoc)  *)\n\nTheorem seq_assoc : forall c1 c2 c3,\n  com_equiv ((c1;;c2);;c3) (c1;;(c2;;c3)).\nProof.\n  intros.\n  unfold com_equiv.\n  simpl. rewrite seq_sem_assoc.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (if_seq)  *)\nTheorem if_seq : forall b c1 c2 c3,\n  com_equiv\n    (If b Then c1 Else c2 EndIf;; c3)\n    (If b Then c1;; c3 Else c2;; c3 EndIf).\nProof.\n  intros.\n  unfold com_equiv.\n  simpl. unfold if_sem.\n  rewrite seq_union_distr_r.\n  rewrite !seq_sem_assoc.\n  reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Task 5: Understanding Bourbaki-Witt Fix Point *)\n\nModule BW_FixPoint.\n\nSection BW_FixPoint.\n\n(** Given a boolean expression [b] and a loop body's denotation [d], we have\n    defined [loop_sem b d] as the whole loop's denotation. In this new\n    denotational semantics, [loop_sem b d] is also the least fix point of the\n    following [F], although its construction is not identical to the one in\n    Bourbaki-Witt Fix Point theorem. *)\n\nVariable b: bexp.\nVariable d: state -> Z -> state -> Prop.\n  \nDefinition F X := if_sem b (seq_sem d X) skip_sem.\n\n(** In other words, [loop_sem b d] is equivalent with [F (loop_sem b d)]. *)\n\n(** Now, let's discover the relation between our definition of [loop_sem] and\n    Bourbaki-Witt's construction. Bourbaki-Witt's construction is based on a\n    bottom element, in this case, the empty ternary relation. *)\n\nDefinition Bot: state -> Z -> state -> Prop := fun _ _ _ => False.\n\n(** And the least fix point is the least upper bound of:\n\n    - Bot\n\n    - F Bot\n\n    - F (F Bot)\n\n    - F (F (F Bot))\n\n    - ... *)\n\nFixpoint FBot (n: nat) :=\n  match n with\n  | O => Bot\n  | S n' => F (FBot n')\n  end.\n\nDefinition loop_sem' := omega_union_sem (FBot).\n\n(** In this case, the least upper bound of a ternary relation sequence is their\n    [omega_union_sem]. Thus, Bourbaki-Witt's fixpoint can be formalized as\n    [loop_sem'] above. *)\n\nEnd BW_FixPoint.\n\n(** Now, let's discover the relationship between [loop_sem]'s construction and\n    [loop_sem']'s construction.\n\n    Hint 1: Both [iter_loop_body] and [FBot] are recursively defined. You may\n    write [simpl] to use their definitions.\n\n    Hint 2: Some properties about [union_sem], [seq_sem] and [skip_sem] in\n    previous tasks may be helpful here.\n\n    Hint 3: Proving some extra properties about [Bot] could make your proofs\n    more concise. *)\n\n(** **** Exercise: 2 stars, standard (FBot1_fact)  *)\n\nFact FBot1_fact: forall b d, sem_equiv (iter_loop_body b d 0) (FBot b d 1).\nProof.\n  intros.\n  simpl.\n  unfold F, if_sem.\n  simpl. rewrite seq_skip_r.\n  split;intro.\n  - right. exact H.\n  - destruct H.\n    + hnf in H. destruct H as [t1 [t2 [st3 [? [? ?]]]]].\n      hnf in H0. destruct H0 as [t3 [t4 [st4 [? [? ?]]]]].\n      hnf in H2. destruct H2.\n    + exact H.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (FBot2_fact)  *)\n\nInstance FB_congruence b d : Proper (sem_equiv ==> sem_equiv) (F b d ).\nProof. hnf. intros.\n  unfold F. unfold if_sem. rewrite H.\n  reflexivity.\nQed.\n\nFact FBot2_fact: forall b d,\n  sem_equiv\n    (union_sem (iter_loop_body b d 1) (iter_loop_body b d 0))\n    (FBot b d 2).\nProof.\n  intros.\n  replace (FBot b d 2) with (F b d (FBot b d 1)) by reflexivity.\n  rewrite <- FBot1_fact.\n  simpl. unfold F, if_sem.\n  rewrite seq_skip_r.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (FBot_n_fact_statement)  *)\n\n(** For generic natural number [n], what is the connection between [FBot b d n]\n    and [iter_loop_body]? Write down a proposition to describe this connection.\n    Note that your [FBot_n_fact_statement] should have the following form:\n\n    - forall b d n, sem_equiv (...) (FBot b d n).\n\n    And you probably need to write some auxiliary definition(s) first. *)\n\nFixpoint finite_union_sem (n:nat)\n   (rs: nat -> state -> Z -> state -> Prop): state -> Z -> state -> Prop :=\n   match n with\n   | O => rs O\n   | S n' => union_sem (rs (S n')) (finite_union_sem n' rs)\n   end.\n\nDefinition FBot_n_fact_statement: Prop :=\n  forall b d n, sem_equiv (finite_union_sem n (iter_loop_body b d)) (FBot b d (S n)).\n\nLemma FBot_n_fact_help: forall b d n,\n  sem_equiv\n    (finite_union_sem (S n) (iter_loop_body b d))\n    ( union_sem\n      (test_sem (beval (! b)))\n      (seq_sem (test_sem (beval b))\n         (seq_sem d (finite_union_sem n (iter_loop_body b d))))).\nProof.\n  induction n.\n  + simpl. apply union_sem_comm.\n  + replace (finite_union_sem (S (S n)) (iter_loop_body b d)) with\n    (union_sem (iter_loop_body b d (S (S n))) (finite_union_sem (S n) (iter_loop_body b d)))\n    by reflexivity.\n    rewrite IHn at 1.\n    rewrite union_sem_assoc.\n    rewrite (union_sem_comm _ (test_sem (beval (! b)))).\n    rewrite <- union_sem_assoc.\n    simpl. rewrite seq_union_distr_l.\n    rewrite seq_union_distr_l. reflexivity.\nQed.\n\nTheorem FBot_n_fact: FBot_n_fact_statement.\nProof.\n  hnf. intros.\n  induction n.\n  - apply FBot1_fact.\n  - replace (FBot b d (S (S n))) \n      with (F b d (FBot b d (S n))) by reflexivity.\n    rewrite <- IHn.\n    simpl. unfold F, if_sem.\n    rewrite seq_skip_r.\n    destruct n.\n    + simpl. reflexivity.\n    + simpl.\n      rewrite (FBot_n_fact_help b d n) at 1.\n      rewrite seq_union_distr_l.\n      rewrite seq_union_distr_l.\n      simpl.\n      rewrite (union_sem_comm (test_sem (Sets.complement (beval b)))).\n      rewrite union_sem_assoc.\n      reflexivity.\nQed.\n\n(** [] *)\n\nEnd BW_FixPoint.\n\n(* Fri Apr 3 20:44:10 CST 2020 *)\n", "meta": {"author": "ltzone", "repo": "2020Spring", "sha": "bc7fdf60850c81d77825cdcc77a1ad265da98f11", "save_path": "github-repos/coq/ltzone-2020Spring", "path": "github-repos/coq/ltzone-2020Spring/2020Spring-bc7fdf60850c81d77825cdcc77a1ad265da98f11/CS263/Assignment4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.6771417787235988}}
{"text": "Variables A B : Prop.\nLemma ex7 : ((A \\/ B) /\\ ~ A) -> B.\nProof.\n  intro HaOrHb_and_Hna.\n  destruct HaOrHb_and_Hna as [Ha_or_Hb Hna].\n  destruct Ha_or_Hb as [Ha | Hb].\n  +\n    contradiction.\n  +\n    exact Hb.\nQed.", "meta": {"author": "alvarofpp", "repo": "course-coq", "sha": "64dc0d9a2e6564f9fa5df508fa946a137901feee", "save_path": "github-repos/coq/alvarofpp-course-coq", "path": "github-repos/coq/alvarofpp-course-coq/course-coq-64dc0d9a2e6564f9fa5df508fa946a137901feee/logica_proposicional_e_predicados/disjuncao/exercicio_07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240211961401, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6770846333480389}}
{"text": "(** * Definition of functions and constructors *)\n\nRequire Export Relations.\nSet Implicit Arguments.\n\nSection Global.\n\n  Section Def.\n\n    Variables X Y X' Y': Type.\n\n(*\n    Record function: Type := mkfun {\n      body:> relation2 X Y -> relation2 X Y;\n      Hmon: forall R S, incl R S -> incl (body R) (body S)\n    }.\n*)\n\n    Definition function2 := relation2 X Y -> relation2 X' Y'.\n    Definition function  := relation2 X Y -> relation2 X Y.\n\n    Definition increasing (F: function) := \n      forall R S, incl R S -> incl (F R) (F S).\n\n    Definition contains (F G: function2) := forall R, incl (F R) (G R).\n\n    (** Constant and identity functions *)\n    Definition constant S: function2 := fun _ => S.\n    Definition identity: function := fun R => R.\n\n    (** Binary and general union functions *)\n    Definition Union2 F G: function2 := fun R => union2 (F R) (G R).\n    Definition Union I H: function2 := fun R => union (fun i: I => H i R).\n\n  End Def.\n\n  Section Def'.\n\n    Variables X Y Z X' Y' Z' X'' Y'': Type.\n\n    Definition transparent (B: relation X) (F: function2 X Y X Y') := \n      forall R, incl (F (comp (star B) R)) (comp (star B) (F R)).\n\n    (** Chaining functions *)\n    Definition chaining_l (S: relation2 X Y): function2 Y Z X Z := comp S.\n    Definition chaining_r (S: relation2 Y Z): function2 X Y X Z := fun R => comp R S.\n    Definition Chain (F: function2 X Y X' Y') (G: function2 X Y Y' Z') := fun R => comp (F R) (G R).\n\n    (** Composition *)\n    Definition Comp (G: function2 X' Y' X'' Y'') (F: function2 X Y X' Y') := fun R => G (F R).\n    \n\n    Variable F: function X Y.   \n    Variable R: relation2 X Y.\n\n    (** Simple iteration function *)\n    Fixpoint Exp(n: nat): relation2 X Y :=\n      match n with\n\t| O => R\n\t| S n => F (Exp n)\n      end.\n    Definition Iter := union Exp.\n\n    (** Increasing iteration function *)\n    (* inverser n et R ? *)\n    Fixpoint UExp(n: nat): relation2 X Y := \n      match n with\n\t| O => R\n\t| S n => union2 (UExp n) (F (UExp n))\n      end.\n    Definition UIter := union UExp.\n\n    Lemma UExp_incl: forall n, incl (UExp n) (UExp (S n)).\n    Proof. intros n x y H; left; auto. Qed.\n\n    Lemma UIter_incl: incl R UIter.\n    Proof. intros x y H; exists 0; auto. Qed.\n  \n  End Def'.\n\n  Section UIter.\n    Variables X Y: Type.\n    Variable F: function X Y.\n    Hypothesis HF: increasing F.\n\n    Lemma UExp_inc: forall n R S, incl R S -> incl (UExp F R n) (UExp F S n).\n    Proof.\n      intros n R S H; induction n as [ | n IH ]; intros x y XY; simpl; auto.\n      celim XY; intro XY. \n      left; exact (IH _ _ XY).\n      right; apply (HF IH XY).\n    Qed.\n\n    (* begin hide *)\n    Lemma UIter_inc: increasing (UIter F).\n    Proof.\n      intros R S H x y XY; destruct XY as [ n XY ].\n      exists n; apply (UExp_inc n H _ _ XY).\n    Qed.\n\n    Lemma UExp_UExp: forall R m n, UExp F (UExp F R n) m = UExp F R (m+n).\n    Proof.\n      intros R m; induction m as [ | m IH ]; intros n.\n      reflexivity.\n      simpl; rewrite IH; reflexivity.\n    Qed.\n\n    Hypothesis HF0: forall R, incl R (F R).\n    Hypothesis HF2: forall R, incl (F (F R)) (F R).\n    Lemma UIter_02: contains (UIter F) F.\n    Proof.\n      intros R x y H; destruct H as [ n H ]; cgen H; cgen y; cgen x; \n\tinduction n as [ | n IH ]; intros x y H.\n      apply HF0; exact H.\n      celim H; intro H; auto.\n      apply HF2; exact (HF IH H).\n    Qed. \n    (* end hide *)\n\n  End UIter.\n \n  Section UIter'.\n    Variable X: Type.\n    Variable F: function X X.\n    Hypothesis HF: forall R, eeq (trans (F R)) (F (trans R)) .\n    Hypothesis HF': increasing F.\n\n    Lemma UExp_trans: forall n R, eeq (trans (UExp F R n)) (UExp F (trans R) n).\n      intros n R; induction n as [ | n IH ]; split; intros x y H; auto; celim H; intro H.\n      left; exact (proj1 IH _ _ H).\n      right; apply (HF' (proj1 IH)); apply (proj1 (HF (UExp F R n))); auto.\n      left; exact (proj2 IH _ _ H).\n      right; apply (proj2 (HF (UExp F R n))); apply (HF' (proj2 IH) H).\n    Qed.\n\n    Lemma UIter_trans: forall R, eeq (trans (UIter F R)) (UIter F (trans R)).\n      intro R; split; intros x y H; destruct H as [ i H ]; exists i.\n      exact (proj1 (UExp_trans i R) _ _ H).\n      exact (proj2 (UExp_trans i R) _ _ H).\n    Qed.\n  End UIter'.\nEnd Global.\n\nHint Immediate UExp_incl.\nHint Immediate UIter_incl.\n", "meta": {"author": "coq-contribs", "repo": "weak-up-to", "sha": "6780e1d43bc9583d5e6fe47418980d4dbc8f6527", "save_path": "github-repos/coq/coq-contribs-weak-up-to", "path": "github-repos/coq/coq-contribs-weak-up-to/weak-up-to-6780e1d43bc9583d5e6fe47418980d4dbc8f6527/Functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6770457053763336}}
{"text": "Require Export Bool.\nRequire Export List.\nExport ListNotations.\n\nRequire Export common.\n\nModule BLang.\n\n\n(* The terms of our boolean logic, all at one level *)\nInductive bterm : Type :=\n  | BTrue   : bterm\n  | BFalse  : bterm\n  | BIf     : bterm -> bterm -> bterm -> bterm\n  | BZero   : bterm\n  | BSucc   : bterm -> bterm\n  | BPred   : bterm -> bterm\n  | BIsZero : bterm -> bterm.\n\n(* Notation for if statements *)\nNotation \"'BIF' t1 'THEN' t2 'ELSE' t3 'FI'\" :=\n  (BIf t1 t2 t3) (at level 80, right associativity).\n\n\nReserved Notation \"t '||' t'\" (at level 50, left associativity).\n\n(* Evaluation relations, defined inductively *)\nInductive bevalR : bterm -> bterm -> Prop :=\n  | E_IfTrue: forall (t2 t3: bterm),\n      (BIF BTrue THEN t2 ELSE t3 FI || t2)\n  | E_IfFalse: forall (t2 t3: bterm),\n      (BIF BFalse THEN t2 ELSE t3 FI || t3)\n  | E_If: forall (t1 t1' t2 t3: bterm),\n      (t1 || t1') ->\n      (BIF t1 THEN t2 ELSE t3 FI || BIF t1' THEN t2 ELSE t3 FI)\n  where \"t '||' t'\" := (bevalR t t') : type_scope.\n\n(**\ns = if true then false else false\ndef\nt = if s then true else true\ndef\nu = if false then true else true\n\nif t then false else false -> if u then false else false\n\nwitnessed by the following derivation tree:\n\n------------- E-IfTrue\ns -> false\n\n------------- E-If\nt ->  u\n\n------------- E-If\nif t then false else false -> if u then false else false\n\n**)\n\nDefinition s : bterm := \n  BIF BTrue THEN BFalse ELSE BFalse FI.\n\nDefinition t : bterm := \n  BIF s THEN BTrue ELSE BTrue FI.\n\nDefinition u : bterm := \n  BIF BFalse THEN BTrue ELSE BTrue FI.\n\nExample Ex353:\n  (BIF t THEN BFalse ELSE BFalse FI || BIF u THEN BFalse ELSE BFalse FI).\nProof.\n  apply E_If.\n  apply E_If.\n  apply E_IfTrue.\nQed.\n\n(**\nTheorem [Determinacy of one-step evaluation]:\n  If t -> t' and t -> t'' then t' == t''\n**)\n\nTheorem one_step_deterministic : forall t t' t'' : bterm,\n  (t || t') ->\n  (t || t'') -> \n  t' = t''.\nProof.\n  intros t t' t'' erel1  erel2.\n  generalize dependent t''.\n  (* By induction on a derivation of t -> t' *)\n  bevalR_cases (induction erel1; intros) Case.\n  (* If the rule used in the derivation of t -> t' is E-IfTrue *)\n  Case \"E_IfTrue\".\n    (* If the rule used in the derivation of t -> t'' is E-IfTrue,\n     *  then trivially t = t''  *)\n    inversion erel2. reflexivity.\n    (* E-IfFalse is ruled out by the fact that t = true *)\n    (* E-If is ruled out by the fact that t is not further reducable *)\n    inversion H3.\n  (* A simular argument holds if t -> t' is E-IfFalse *)\n  Case \"E_IfFalse\".\n    inversion erel2. reflexivity.\n    inversion H3.\n  (* Finaly, if the last rule in the derivation of t -> t' is E-If,\n   * then we have evidence that the guard of this has an evaluation\n   * relation. *)\n  Case \"E_If\".\n    bevalR_cases (inversion erel2) SCase.\n    (* We can rule out E-IfFalse by false's lack of relation *)\n    SCase \"E_IfTrue\".\n      subst.\n      inversion erel1.\n    (* Similarly E-IfTrue *)\n    SCase \"E_IfFalse\".\n      subst.\n      inversion erel1.\n    (* And now, the induction hypothesis applies *)\n    SCase \"E_If\".\n      rewrite IHerel1 with t1'0.\n      reflexivity.\n      assumption.\nQed.\n\nEnd BLang.\n", "meta": {"author": "christian-marie", "repo": "tapl-coq", "sha": "0ce09a8b4333397f0d9c38a36e3c8633df2e3fcb", "save_path": "github-repos/coq/christian-marie-tapl-coq", "path": "github-repos/coq/christian-marie-tapl-coq/tapl-coq-0ce09a8b4333397f0d9c38a36e3c8633df2e3fcb/bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6770457023022523}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import notations List.\nRequire Export coherence_graph.\n\n(** * Syntax for observations *)\nInductive observation {G : Graph} :=\n| o_true : observation\n| o_false : observation\n| o_obs : vertex -> observation\n| o_or : observation -> observation -> observation\n| o_and : observation -> observation -> observation\n| o_impl : observation -> observation -> observation.\n\nNotation \"⊤o\" := o_true.\nNotation \"⊥o\" := o_false.\nNotation \" ⦑ o ⦒ \" := (o_obs o).\nInfix \" ⟇ \" := o_or (at level 50).\nInfix \" ⟑ \" := o_and (at level 50).\nInfix \" → \" := o_impl (at level 50).\n\nDefinition Join {G : Graph} : list observation -> observation :=\n  fold_right o_or ⊥o.\nDefinition Meet {G : Graph} : list observation -> observation :=\n  fold_right o_and ⊤o.\n\nNotation \" ⋁ \" := Join.\nNotation \" ⋀ \" := Meet.\n\nDefinition π {G : Graph} {decG : DecidableGraph G} (s : fcliques) :=\n  ⋀ (map o_obs ($ s)).\n\n", "meta": {"author": "monstrencage", "repo": "obs-alg-proofs", "sha": "71855181e306d8a14ec9c20d6757adaf6dc08007", "save_path": "github-repos/coq/monstrencage-obs-alg-proofs", "path": "github-repos/coq/monstrencage-obs-alg-proofs/obs-alg-proofs-71855181e306d8a14ec9c20d6757adaf6dc08007/src/syntax_obs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6769810430642059}}
{"text": "Require Import Logic.Axiom.LEM.\n\nRequire Import Logic.Fol.Syntax.\n\nRequire Import Logic.Set.Set.\nRequire Import Logic.Set.Incl.\nRequire Import Logic.Set.Elem.\nRequire Import Logic.Set.Equal.\nRequire Import Logic.Set.Foundation.\n\nRequire Import Logic.Lang1.Syntax.\nRequire Import Logic.Lang1.Context.\nRequire Import Logic.Lang1.SemanCtx.\nRequire Import Logic.Lang1.Semantics.\nRequire Import Logic.Lang1.Environment.\n\nOpen Scope Set_Incl_scope.\n\n(* Lemma 'coherence' expressed in set theory abstract syntax.                   *)\n(* This formulation is correct provided the variables n m are distinct.         *)\nDefinition coherenceF (n m:nat) : Formula :=\n    All n (All m (Imp (Sub n m) (Not (Elem m n)))).\n\nImport Semantics.\n(* Evaluating coherenceF in any environment 'yields' the lemma coherence.       *)\nLemma evalCoherenceF : forall (e:Env) (n m:nat),\n    m <> n ->\n    eval e (coherenceF n m)\n        <->\n    forall (x y:set), x <= y -> ~ y :: x.\nProof.\n    intros e n m Hmn. unfold coherenceF. rewrite evalAll. split; intros H x.\n    - remember (H x)  as H' eqn:E. clear E H.  rewrite evalAll in H'. intros y.\n      remember (H' y) as H  eqn:E. clear E H'. rewrite evalImp in H. \n      rewrite evalSub in H. rewrite evalNot in H. rewrite evalElem in H.\n      rewrite bindSame in H. rewrite bindDiff in H. rewrite bindSame in H.\n        + assumption.\n        + assumption.\n    - rewrite evalAll. intros y. rewrite evalImp, evalSub, evalNot, evalElem.\n      rewrite bindSame, bindDiff, bindSame. apply H.\n        + assumption.\nQed.\n\n\nImport SemanCtx.\nLemma evalCoherenceFCtx : forall (G:Context) (n m:nat),\n    n <> m ->\n    G :- (coherenceF n m) >>\n        forall (x y:set), x <= y -> ~ y :: x.\nProof.\n    intros G n m H1. unfold coherenceF.\n    apply evalAll. intros x. apply evalAll. intros y. apply evalImp.\n    - apply evalSub.\n        + apply FindS; try assumption. apply FindZ.\n        + apply FindZ.\n    - apply evalNot, evalElem.\n        + apply FindZ.\n        + apply FindS; try assumption. apply FindZ.\nQed.\n \n(* Lemma 'noSelfElem' expressed in set theory abstract syntax.                  *)\nDefinition noSelfElemF (n:nat) : Formula := All n (Not (Elem n n)).\n\nImport Semantics.\n(* Evaluating noSelfElemF in any environment 'yields' the lemma noSelfElem.     *)\nLemma evalNoSelfElemF : forall (e:Env) (n:nat),\n    eval e (noSelfElemF n) <-> forall (x:set), ~ x :: x.\nProof.\n    intros e n. unfold noSelfElemF. rewrite evalAll. split; intros H x.\n    - remember (H x) as H' eqn:E. clear E H. rewrite evalNot in H'.\n      rewrite evalElem in H'. rewrite bindSame in H'. assumption.\n    - rewrite evalNot, evalElem, bindSame. apply H.\nQed.\n\nImport SemanCtx.\nLemma evalNoSelfElemFCtx : forall (G:Context) (n:nat),\n    G :- (noSelfElemF n) >>  forall (x:set), ~ x :: x.\nProof.\n    intros G n. unfold noSelfElemF.\n    apply evalAll. intros x. apply evalNot, evalElem; apply FindZ.\nQed.\n\n\n(* Lemma 'noUniverse' expressed in set theory abstract syntax.                  *)\n(* This formulation is correct provided the variables n m are distinct.         *)\nDefinition noUniverseF (n m:nat) : Formula := Not (Exi n (All m (Elem m n))).\n\nImport Semantics.\n(* Evaluating noUniverseF in any environment 'yields' the lemma noUniverse.     *)\nLemma evalNoUniverseF : LEM -> forall (e:Env) (n m:nat),\n    m <> n ->\n    eval e (noUniverseF n m)\n        <->\n    ~ exists (x:set), forall (y:set), y :: x.\nProof.\n    intros L e n m Hmn. unfold noUniverseF. rewrite evalNot, evalExi.\n    split; intros H1 [x H2]; apply H1; exists x.\n    - rewrite evalAll. intros y. rewrite evalElem, bindSame, bindDiff, bindSame. \n      apply H2. assumption.\n    - rewrite evalAll in H2. intros y. remember (H2 y) as H eqn:E. clear E H2 H1.\n      rewrite evalElem in H. rewrite bindSame in H. rewrite bindDiff in H.\n      rewrite bindSame in H. assumption. assumption.\n    - assumption.\nQed.\n\nImport SemanCtx.\nLemma evalNoUniverseFCtx : LEM -> forall (G:Context) (n m:nat),\n    n <> m ->\n    G :- (noUniverseF n m) >>\n        ~ exists (x:set), forall (y:set), y :: x.\nProof.\n    intros L G n m H1. unfold noUniverseF.\n    apply evalNot, evalExi; try assumption. intros x. apply evalAll. intros y.\n    apply evalElem; try (apply FindZ). apply FindS; try assumption. apply FindZ.\nQed.\n \n\n(* Theorem 'foundation' expressed in set theory abstract syntax.                *)\n(* This formulation is correct provided the variables n m are distinct.         *)\n(* Of course this formulation is somewhat arbitrary as we decided to introduce  *)\n(* the builtin predicate 'Min' as part of the language.                         *)\nDefinition foundationF (n m:nat) : Formula := \n    All n (Imp (Not (Empty n)) (Exi m (Min m n))).\n\nImport Semantics.\n(* Evaluating foundationF in any environment 'yields' the theorem foundation.   *)\nLemma evalFoundationF : LEM -> forall (e:Env) (n m:nat),\n    m <> n ->\n    eval e (foundationF n m) \n        <->\n    forall (x:set), ~(x == Nil) -> exists (y:set), minimal y x.\nProof.\n    intros L e n m Hmn. unfold foundationF. rewrite evalAll. split; intros H x.\n    - remember (H x) as H' eqn:E. clear E H. rewrite evalImp in H'.\n      rewrite evalNot in H'. rewrite evalEmpty in H'. rewrite bindSame in H'. \n      intros H. remember (H' H) as H0 eqn:E. clear E H H'.\n      rewrite evalExi in H0. destruct H0 as [y H]. exists y.\n      rewrite evalMin in H. rewrite bindSame in H. rewrite bindDiff in H.\n      rewrite bindSame in H.\n        + assumption.\n        + assumption.\n        + assumption.\n        + assumption.\n    - rewrite evalImp, evalNot, evalEmpty, bindSame, evalExi.\n      remember (H x) as H' eqn:E. clear E H. intros H.\n      remember (H' H) as H1 eqn:E. clear E H H'. destruct H1 as [y H].\n      exists y. rewrite evalMin, bindSame, bindDiff, bindSame.\n        + assumption.\n        + assumption.\n        + assumption.\n        + assumption.\nQed.\n\nImport SemanCtx.\nLemma evalFoundationFCtx : LEM -> forall (G:Context) (n m:nat),\n    n <> m ->\n    G :- (foundationF n m)  >>\n        forall (x:set), ~(x == Nil) -> exists (y:set), minimal y x.\nProof.\n    intros L G n m H1. unfold foundationF. \n    apply evalAll. intros x. apply evalImp. \n    - apply evalNot, evalEmpty, FindZ.\n    - apply evalExi; try assumption. intros y. apply evalMin; try assumption.\n        + apply FindZ.\n        + apply FindS; try assumption. apply FindZ.\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/Lang1/Foundation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6769810323323097}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.ProofIrrelevance.\nRequire Import Program.\n\nRequire Import LensLaws.Isomorphism.\nRequire Import LensLaws.Crush.\n\nDefinition Lens (A B : Set) : Type := { X : Set & Iso A (X * B) }.\n\nLemma iso_is_lens_ex {A B} (i : Iso A B) : Iso A (prod unit B).\nProof.\n  destruct i as [f g H H0].\n  apply (MkIso\n    (fun (a : A) => (tt, f(a)))\n    (fun (p : unit * B) => match p with (tt, b) => g b end)); crush. Defined.\n\nLemma iso_is_lens {A B} (i : Iso A B) : Lens A B.\nProof.\n  exists unit.\n  exact (iso_is_lens_ex i). Defined.\n\nLemma lens_compose {A B C} (ab : Lens A B) (bc : Lens B C) : Lens A C.\nProof.\n  intros.\n  destruct ab as [X ab]. destruct ab as [axb xba H H0].\n  destruct bc as [Y bc]. destruct bc as [byc ycb H1 H2].\n  exists (prod X Y).\n\n  apply (MkIso\n    (fun (a : A) => (fst (axb a), fst (byc (snd (axb a))), snd (byc (snd (axb a)))))\n    (fun (t : X * Y * C) => xba (fst (fst t), ycb (snd (fst t), snd t)))); crush. Defined.\n\nDefinition lens_view {A B} (lens : Lens A B) (a : A) : B.\nProof.\n  destruct lens.\n  destruct i.\n  exact (snd (f a)). Defined.\n\nDefinition lens_set {A B} (lens : Lens A B) (a : A) (b : B) : A.\nProof.\n  destruct lens.\n  destruct i.\n  exact (g (fst (f a), b)). Defined.\n\nTheorem lens_law1 {A B} (lens : Lens A B) :\n  forall a b, lens_view lens (lens_set lens a b) = b.\nProof.\n  intros a b. destruct lens as [X ab]. destruct ab as [axb xba H H0]. crush. Qed.\n\nTheorem lens_law2 {A B} (lens : Lens A B) :\n  forall a, lens_set lens a (lens_view lens a) = a.\nProof.\n  intros a. destruct lens as [X ab]. destruct ab as [axb xba H H0]. crush. Qed.\n\nLemma lens_law3_weak {A B} (lens : Lens A B) :\n  forall a b, lens_set lens (lens_set lens a b) b = lens_set lens a b.\nProof.\n  intros a b.\n  assert (\n    lens_set lens (lens_set lens a b) b =\n    lens_set lens (lens_set lens a b) (lens_view lens (lens_set lens a b))).\n    f_equal. symmetry. apply lens_law1.\n  rewrite H.\n  rewrite lens_law2.\n  reflexivity. Qed.\n\nTheorem lens_law3 {A B} (lens : Lens A B) :\n  forall a b b', lens_set lens (lens_set lens a b') b = lens_set lens a b.\nProof.\n  intros a b b'. destruct lens as [X ab]. destruct ab as [axb xba H H0]. crush. Qed.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.ProofIrrelevance.\n\nLemma sigma_eq {A} {P : A -> Prop} (x y : A) (px : P x) (py : P y) (eqp : x = y) :\n  (eq_ind x P px y eqp = py) ->\n  exist P x px = exist P y py.\nProof.\n  intros. subst. f_equal. Qed.\n\nTheorem lens_complete {A B : Set} (view : A -> B) (set : A -> B -> A):\n  (forall a b, view (set a b) = b) ->\n  (forall a, set a (view a) = a) ->\n  (forall a b b', set (set a b) b' = set a b') ->\n  Lens A B.\nProof.\n  intros law1 law2 law3.\n\n  exists ({ba : B -> A | exists (a : A), ba = set a}).\n\n  (* This definitions help to find right forms *)\n  (*\n  assert (FWD: A -> {ba : B -> A | exists (a : A), ba = set a} * B).\n  refine\n    (fun (a : A) => (exist _ (set a) (ex_intro _ a eq_refl), view a)).\n  assert (BWD: {ba : B -> A | exists (a : A), ba = set a} * B -> A).\n  refine\n    (fun p => match p as A with (exist _ ba _, b) => ba b end).\n  *)\n\n  set (FWD := fun (a : A) => (exist (fun ba => exists (a : A), ba = set a) (set a) (ex_intro (fun x => set a = set x) a eq_refl), view a)).\n  set (BWD := fun (p : {ba : B -> A | exists (a : A), ba = set a} * B) => match p as A with (exist _ ba _, b) => ba b end).\n\n  apply (MkIso FWD BWD); subst FWD; subst BWD.\n\n  - intro a; simpl. symmetry. apply law2.\n  - intro p. destruct p as [ba b]; destruct ba as [ba Hba]. destruct Hba as [a Hba].\n    f_equal.\n    + simpl. subst. symmetry.\n      assert (set (set a b) = set a) as Hsetset.\n      extensionality b'. apply law3.\n      apply sigma_eq with (eqp := Hsetset).\n      apply proof_irrelevance.\n    + rewrite Hba. symmetry. apply law1. Defined.\n", "meta": {"author": "phadej", "repo": "lens-laws", "sha": "6edf23f694f853c3722f0547944e53201392849e", "save_path": "github-repos/coq/phadej-lens-laws", "path": "github-repos/coq/phadej-lens-laws/lens-laws-6edf23f694f853c3722f0547944e53201392849e/theories/Lens.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619959279793, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.6768532284472161}}
{"text": "Load \"8_filter_even_gt_7.v\".\n\nRequire Import PeanoNat.\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X := pair (filter test l) (filter (fun x => negb (test x)) l).\n\nCheck pair.\nSearch (nat -> bool).\n\nExample test_partition1: partition Nat.odd [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof.\n  simpl. reflexivity.\nQed.\n\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof.\n  simpl. 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/9_partition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.6768532232359039}}
{"text": "\n\n\n(*---------------------------------- Descriptions ---------------------------------------\n\nIn this file we define the idea of graph isomorphism between graphs on two different \ndomains say A and B. This is done by defining following predicates:\n\n  Definition iso_usg (f: A->A)(G G': @UG A) :=\n     (forall x, In x G -> 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 morph_using (f: A-> B)(G: @UG A)(G': @UG B):=\n  (nodes G') = (img f G) /\\  (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-> B)(g: B-> A)(G: @UG A)(G': @UG B):=\n    morph_using f G G' /\\ morph_using g G' G /\\ (forall x, In x G -> g (f x) = x).\n\n Definition iso (G: @UG A)(G': @UG B):=\n    exists (f: A-> B)(g: B-> A), iso_using f g G G'.\n  \n\nWhen we say (iso_using f g G1 G2), we mean f and g are the function establishing the\nisomorphism between graphs G1 and G2. \n\nLemma iso_is_isomorph (G G': @UG A)(f: A-> A): iso_usg f G G' -> iso_using f f G G'.\nLemma isomorph_is_iso (G G': @UG A)(f: A-> A): iso_using f f G G' ->  iso_usg f G G'.\n\n\nWe also prove that this relation is symmetric and transitive. Note the mutually \ninvertible nature of f and g that makes them one_one on both G1 and G2. \n\n\nFollowing are some useful property of functions f and g establishing the isomorphism:\n\nLemma fx_is_one_one (l: list A)(f: A->B)(g: B->A): \n            (forall x, In x l ->  g (f x) = x) ->  one_one_on l f.\nLemma f_gx_is_x (l: list A)(s: list B)(f: A->B)(g: B->A):\n    (forall x, In x l-> g (f x) = x) -> (s = (img f l)) -> (forall y, In y s -> f (g y) = y).\n\nLemma img_of_img (l: list A)(f: A->B)(g: B-> A)(Hl: IsOrd l):\n    (forall x, In x l-> g (f x) = x) -> img g (img f l) = l.\nLemma img_of_img2 (l: list B)(f: A->B)(g: B-> A)(Hl: IsOrd l):\n      (forall x, In x l-> f (g x) = x) -> img f (img g l) = l.\nLemma iso_sym1 (G : @UG A)(G': @UG B)(f: A-> B)(g: B-> A): \n      iso_using f g G G' -> iso_using g f G' G.\n\nLemma iso_one_one_on_l (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(l: list A):\n    iso_using f g G G'-> l [<=] G -> one_one_on l f.\nLemma iso_one_one_on_s (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(s: list B):\n    iso_using f g G G'-> s [<=] G' -> one_one_on s g.\nLemma iso_cardinal (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A) : iso_using f g G G' -> |G|=|G'|.\nLemma iso_sub_cardinal (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(X: list A):\n    iso_using f g G G' -> NoDup X -> X [<=] G -> |X|= | img f X |.\nLemma iso_sub_cardinal1 (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(Y: list B):\n    iso_using f g G G' -> NoDup Y -> Y [<=] G' -> |Y|= | img g Y |. \nLemma iso_edg1 (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(x y:A):\n     iso_using f g G G' -> In x G -> In y G-> (edg G x y = edg G' (f x) (f y)).\nLemma iso_edg2  (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(x y: B):\n    iso_using f g G G' -> In x G'-> In y G'-> (edg G' x y = edg G (g x) (g y)).\nLemma iso_img_of_img3 (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(l: list A):\n    IsOrd l -> l [<=] G -> iso_using f g G G' -> l = img g (img f l).\nLemma iso_img_of_img4 (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(l: list B):\n    IsOrd l -> l [<=] G' -> iso_using f g G G' -> l = img f (img g l).\n\n-------------------------------------------------------------------------------------\n\n Stable Set, Cliq and Coloring of graphs has exact counterpart in the isomorphic Graphs.\n These results of existence of isomorphic counterparts are summarized below: \n\n\nLemma iso_cliq_in (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(K: list A):\n    iso_using f g G G' -> Cliq_in G K -> Cliq_in G' (img f K).\nLemma iso_stable_in (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(I: list A):\n    iso_using f g G G' -> Stable_in G I -> Stable_in G' (img f I).\n\nLemma max_K_in_G' (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(K: list A):\n    iso_using f g G G' -> Max_K_in G K -> Max_K_in G' (img f K). \nLemma cliq_num_G' (G: @UG A)(G':@UG B)(n: nat):iso G G' -> cliq_num G n -> cliq_num G' n.\nLemma max_I_in_G' (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(I: list A):\n    iso_using f g G G' -> Max_I_in G I -> Max_I_in G' (img f I).\nLemma i_num_G' (G: @UG A)(G':@UG B)(n: nat): iso G G' -> i_num G n -> i_num G' n.\nLemma chrom_num_G'(G: @UG A)(G':@UG B)(n: nat):iso G G'->chrom_num G n-> chrom_num G' n.\n\nLemma nice_G' (G: @UG A)(G':@UG B) : iso G G' -> Nice G -> Nice G’.\nLemma iso_subgraphs (G H: @UG A)(G':@UG B)(f: A->B)(g: B-> A): iso_using f g G G'->\n        Ind_subgraph H G ->(exists H', Ind_subgraph H' G'/\\ iso_using f g H H’).\nLemma perfect_G' (G: @UG A)(G':@UG B): iso G G' -> Perfect G -> Perfect G’.\n\nLemma iso_trans (G1 :@UG A)(G2: @UG B)(G3: @UG C): iso G1 G2 -> iso G2 G3 -> iso G1 G3.\n\n\n------------------------------------------------------------------------------------------*)\n\nRequire Export MoreUG.\n\nSet Implicit Arguments.\n\n\nSection GraphMorphism.\n\n  Context { A B: ordType }.\n\n  Definition morph_using (f: A-> B)(G: @UG A)(G': @UG B):=\n    (nodes G') = (img f G) /\\  (forall x y, In x G-> In y G-> edg G x y = edg G' (f x) (f y)).\n\n   Definition iso_usg (f: A->A)(G G': @UG A) :=\n     (forall x, In x G -> 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 (G G': @UG A) := exists (f: A->A), iso_usg f G G'. *)\n\n  \nEnd GraphMorphism.\n\n\n\n\nSection GraphIsomorphism.\n  Context { A B: ordType }.\n\n  Definition iso_using (f: A-> B)(g: B-> A)(G: @UG A)(G': @UG B):=\n    morph_using f G G' /\\ morph_using g G' G /\\ (forall x, In x G -> g (f x) = x).\n\n  Definition iso (G: @UG A)(G': @UG B):=\n    exists (f: A-> B)(g: B-> A), iso_using f g G G'.\n  \nEnd GraphIsomorphism.\n\n\nSection IsoVsIsomorph.\n  Context {A: ordType }.\n\n   Lemma img_of_imgf (l: list A)(f: A->A)(Hl: IsOrd l):\n    (forall x, In x l->  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 iso_is_isomorph (G G': @UG A)(f: A-> A): iso_usg f G G' -> iso_using f f G G'.\n  Proof. { intro h1. destruct h1 as [h1 h2]. destruct h2 as [h2 h3]. split.\n         { split;auto. } split.\n         { split. rewrite h2. symmetry. apply img_of_imgf. all: auto.\n           intros x y h4 h5.\n           assert (h6: exists x0, In x0 G /\\ x = f x0).\n           { rewrite h2 in h4; auto. }\n           assert (h7: exists y0, In y0 G /\\ y = f y0).\n           { rewrite h2 in h5; auto. }\n           destruct h6 as [x0 h6]. destruct h7 as [y0 h7].\n           replace x with (f x0). replace y with (f y0).\n           replace (f (f x0)) with x0. replace (f (f y0)) with y0.\n           symmetry;apply h3. apply h6. apply h7.\n           symmetry;apply h1;apply h7.\n           symmetry;apply h1;apply h6.\n           symmetry; apply h7.\n           symmetry;apply h6. } auto.   } Qed.\n\n  Lemma isomorph_is_iso (G G': @UG A)(f: A-> A): iso_using f f G G' ->  iso_usg f G G'.\n  Proof.  { intro h1. destruct h1 as [h1 h2]. destruct h2 as [h2 h3].\n            split; (auto || split;apply h1). } Qed.\n             \n\nEnd IsoVsIsomorph.\n\nHint Immediate img_of_imgf iso_is_isomorph isomorph_is_iso: core.\n\n\n\nSection GraphIsoProp.\n\n  Context { A B: ordType }.\n\n   (*---------------- properties of bijective function f and g for isomorphism ---------*)\n\n     \n  Lemma fx_is_one_one (l: list A)(f: A->B)(g: B->A):\n    (forall x, In x l ->  g (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 (g (f y)). rewrite <- HC.\n           symmetry;eapply H;eauto. eauto. } Qed.\n\n  Lemma f_gx_is_x (l: list A)(s: list B)(f: A->B)(g: B->A):\n    (forall x, In x l-> g (f x) = x) -> (s = (img f l)) -> (forall y, In y s -> f (g y) = y).\n  Proof. { intros h1 h2 y h3.\n           assert (h4: exists x, In x l /\\ y = f x).\n           { subst s; eauto. }\n           destruct h4 as [x h4]. destruct h4 as [h4a h4]. subst y.\n           replace (g (f x)) with x. auto. symmetry;auto. } Qed. \n\n  Lemma gx_is_one_one (s: list B)(f: A-> B)(g: B->A):\n    (forall y, In y s -> f (g y) = y) -> one_one_on s g.\n  Proof. { intros H. unfold one_one_on. intros x y Hx Hy Hxy HC. absurd (x=y).\n           auto. replace y with (f (g y)). rewrite <- HC. symmetry;auto. auto. } Qed.\n\n  Lemma img_of_img (l: list A)(f: A->B)(g: B-> A)(Hl: IsOrd l):\n    (forall x, In x l-> g (f x) = x) -> img g (img f l) = l.\n Proof. { intro H.\n         assert (H1: Equal (img g (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 = g 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 (g (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 (g (f a)) (img g (img f l))). auto.\n             replace (g (f a)) with a in H2a. auto. symmetry;auto. } } \n         auto. } Qed.\n  \n\n   Lemma img_of_img1 (l: list A)(f: A->B)(g: B->A)(Hl: IsOrd l):\n     (forall x, In x l-> g (f x) = x) -> l = img g (img f l).\n   Proof. intros. symmetry. auto using img_of_img. Qed.\n\n    Lemma img_of_img2 (l: list B)(f: A->B)(g: B-> A)(Hl: IsOrd l):\n    (forall x, In x l-> f (g x) = x) -> img f (img g l) = l.\n    Proof. { intro H.\n         assert (H1: Equal (img f (img g l)) l).\n         { unfold Equal. split.\n           { unfold Subset. intros a H1.\n             assert (H2: exists b, In b (img g 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 = g x ); auto.\n             destruct H3 as [x H3]. destruct H3 as [H3a H3b].\n             subst a. subst b. replace (f (g x)) with x. auto. symmetry;auto. }\n           { unfold Subset. intros a H1.\n             assert (H2: In (g a) (img g l)). auto.\n             assert (H2a: In (f (g a)) (img f (img g l))). auto.\n             replace (f (g a)) with a in H2a. auto. symmetry;auto. } } \n         auto. } Qed.\n\n  Lemma img_of_img3 (l: list B)(f: A->B)(g: B-> A)(Hl: IsOrd l):\n    (forall x, In x l-> f (g x) = x) -> l = img f (img g l).\n    Proof. intros. symmetry. auto using img_of_img2. Qed.\n    \n   \n    Hint Resolve  fx_is_one_one img_of_img img_of_img1: core.\n    Hint Resolve img_of_img2 img_of_img3: core.\n\n   (* ---------------------- Isomorphism is commutative -----------------------*)\n    Lemma iso_sym1 (G : @UG A)(G': @UG B)(f: A-> B)(g: B-> A):\n      iso_using f g G G' -> iso_using g f G' G.\n    Proof. { intro H. destruct H as [Ha H]; destruct H as [Hb H].\n           split.\n           { auto. }\n           split.\n           { auto. }\n           { eapply f_gx_is_x with (l:= G). auto. apply Ha. } } Qed.\n\n    Lemma iso_sym (G: @UG A)(G': @UG B): iso G G' -> iso G' G.\n    Proof. { intro H. destruct H as [f H]. destruct H as [g H].\n             exists g. exists f. apply iso_sym1. auto. } Qed.\n\n    Lemma iso_using_iso (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A):\n      iso_using f g G G' -> iso G G'.\n    Proof. intros h. exists f. exists g. auto. Qed.\n\n    Lemma iso_using_iso1 (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A):\n      iso_using f g G G' -> iso G' G.\n    Proof. intro h. apply iso_sym. eapply iso_using_iso. eauto. Qed.\n\n    Lemma iso_elim1 (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(x:A):\n      iso_using f g 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: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(x:B):\n     iso_using f g G G'-> In x G'-> In (g x) G.\n  Proof. intros H Hx. replace (nodes G) with (img g G'). auto. symmetry.\n         apply iso_sym1 in H as Ha. apply Ha. 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  (*--------------- Isomorphism is a one one function --------------------------------*)\n\n  Lemma iso_one_one1 (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A):\n    iso_using f g G G' -> one_one_on G f.\n  Proof.  intro H; eapply fx_is_one_one; apply H. Qed.\n\n  Lemma iso_one_one2 (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A):\n    iso_using f g G G' -> one_one_on G' g.\n  Proof. intro H. assert (h1: iso_using g f G' G); auto.\n         eapply gx_is_one_one; apply h1. Qed. \n\n  Lemma iso_using_G' (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A):\n    iso_using f g G G' -> nodes G' = (img f G).\n  Proof.  intro H;apply H. Qed.\n\n  Lemma iso_using_G (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A):\n    iso_using f g G G' -> nodes G = (img g G').\n  Proof. intro H0. cut (iso_using g f G' G). intro H;apply H. auto. Qed.\n\n  Lemma iso_one_one_on_l (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(l: list A):\n    iso_using f g G G'-> l [<=] G -> one_one_on l f.\n  Proof. intros H H1. eapply fx_is_one_one. intros x h1. eapply H. auto. Qed.\n\n  Lemma iso_one_one_on_s (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(s: list B):\n    iso_using f g G G'-> s [<=] G' -> one_one_on s g.\n  Proof. intros H H1. eapply gx_is_one_one. intros x h1.\n         assert (H2: iso_using g f G' G). auto.\n         eapply H2. auto. Qed.\n\n  \n    Hint Immediate iso_one_one1 iso_one_one2 iso_one_one_on_l iso_one_one_on_s\n         iso_using_G iso_using_G': core.\n\n    Lemma iso_cardinal (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A) :\n      iso_using f g 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; eauto using iso_using_G'. } Qed.\n  \n  Lemma iso_sub_cardinal (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(X: list A):\n    iso_using f g G G' -> NoDup X -> X [<=] G -> |X|= | img f X |.\n  Proof. { intros H H0 H1.\n         assert (H2: one_one_on G f). eauto.\n         assert (H2a: one_one_on X f). eauto. auto. } Qed.\n\n  Lemma iso_sub_cardinal1 (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(Y: list B):\n    iso_using f g G G' -> NoDup Y -> Y [<=] G' -> |Y|= | img g Y |.\n   Proof. { intros H H0 H1.\n         assert (H2: one_one_on G' g). eauto.\n         assert (H2a: one_one_on Y g). eauto. auto. } Qed.\n\n   (*------------- Isomorphism between graph preserves edge relation -------------*)\n  \n  \n   Lemma iso_edg1 (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(x y:A):\n     iso_using f g G G' -> In x G -> In y G-> (edg G x y = edg G' (f x) (f y)).\n  Proof. intro H;apply H. Qed.\n\n  Lemma iso_edg2  (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(x y: B):\n    iso_using f g G G' -> In x G'-> In y G'-> (edg G' x y = edg G (g x) (g y)).\n  Proof. intro H0. cut (iso_using g f G' G). intro H;apply H. auto. Qed.\n\n Hint Immediate iso_cardinal iso_sub_cardinal iso_sub_cardinal1 iso_edg1 iso_edg2: core.\n\n Lemma iso_edg3(G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(x y:A):\n   iso_using f g G G' -> In x G -> In y G-> 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); eauto.  Qed.\n\n  Lemma iso_edg4  (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(x y: A):\n    iso_using f g G G' -> In x G -> In y G-> ~ 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); eauto. Qed.\n\n  Hint Immediate iso_edg3 iso_edg4: core.\n\n\n  (*----- f and g when composed with each other returns the initial sets -----------*)\n                                                                \n\n  Lemma iso_image1 (G : @UG A)(G': @UG B)(f: A-> B)(g: B-> A):\n    iso_using f g G G' -> (nodes G') = (img f G).\n  Proof. intros h1. destruct h1 as [h1 h2]. apply h1. Qed. \n\n  Lemma iso_image2 (G : @UG A)(G': @UG B)(f: A-> B)(g: B-> A):\n    iso_using f g G G' -> (nodes G) = (img g G').\n  Proof. intros h1. destruct h1 as [h1 h2]. apply h2. Qed. \n\n  Lemma iso_img_of_img1 (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A):\n    iso_using f g G G' -> (forall x, In x G -> g (f x) = x).\n  Proof. intros h1. destruct h1 as [h1 h2]. apply h2. Qed.\n\n   Lemma iso_img_of_img2 (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A):\n    iso_using f g G G' -> (forall x, In x G' -> f (g x) = x).\n   Proof. intros h1. cut (iso_using  g f G' G). intro h2.\n          destruct h2 as [h2 h3]. apply h3. auto. Qed.\n\n    Lemma iso_img_of_img3 (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(l: list A):\n    IsOrd l -> l [<=] G -> iso_using f g G G' -> l = img g (img f l).\n    Proof. intros h1 h2 h3. eapply img_of_img1. auto. intros x h4.\n           eapply iso_img_of_img1. eauto. auto. Qed.\n\n     Lemma iso_img_of_img4 (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(l: list B):\n    IsOrd l -> l [<=] G' -> iso_using f g G G' -> l = img f (img g l).\n  Proof. intros h1 h2 h3. eapply img_of_img3. auto. intros x h4.\n           eapply iso_img_of_img2. eauto. auto. Qed.\n  \n    \n  Hint Resolve iso_image1 iso_image2: core.\n  Hint Resolve iso_img_of_img1 iso_img_of_img2 iso_img_of_img3 iso_img_of_img4: core.\n  \n\n   (* ------------- Isomorphism preserves Cliques and for a graph-----------------*)\n\n   Lemma iso_cliq (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A) (K: list A):\n    iso_using f g 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: @UG A)(G':@UG B)(K: list A):\n    iso G G' -> K [<=] G -> Cliq G K -> NoDup K -> (exists K', Cliq G' K' /\\ |K|=|K'|).\n  Proof. { intros H h1 H1 H2. destruct H as [f H]. destruct H as [g H].\n         exists (img f K). split. eauto using iso_cliq.\n         assert (H3: one_one_on K f). eauto. auto. } Qed.\n  \n\n  Lemma iso_cliq_in (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(K: list A):\n    iso_using f g 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].\n           destruct Ha as [Ha1 Ha]. rewrite Ha1; auto. }\n         split.\n         { auto. }\n         { eauto using iso_cliq. }  } Qed.\n\n  Lemma iso_cliq_in1 (G: @UG A)(G':@UG B)(K: list A):\n    iso G G' -> Cliq_in G K -> (exists K', Cliq_in G' K' /\\ |K|=|K'|).\n  Proof. { intros H H1. destruct H as [f H]. destruct H as [g H].\n           exists (img f K). split. eauto using iso_cliq_in.\n           assert (H3: one_one_on K f). cut (K [<=] G). eauto. apply H1.\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   (*---------- Isomorphism preserves Stable set for a graph ----------------------------*)\n\n   Lemma iso_stable (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(I: list A):\n    iso_using f g 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: @UG A)(G':@UG B)(I: list A):\n    iso G G' -> I [<=] G-> Stable G I -> NoDup I -> (exists I', Stable G' I' /\\ |I|=|I'|).\n  Proof. { intros H h1 H1 H2. destruct H as [f H]. destruct H as [g 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: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(I: list A):\n    iso_using f g 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]. destruct Ha as [Ha1 Ha].\n           rewrite Ha1; auto. }\n         split.\n         { auto. }\n         { eauto using iso_stable. }  } Qed.\n\n  Lemma iso_stable_in1 (G: @UG A)(G':@UG B)(I: list A):\n    iso G G' -> Stable_in G I -> (exists I', Stable_in G' I' /\\ |I|=|I'|).\n  Proof. { intros H H1. destruct H as [f H]. destruct H as [g H].\n           exists (img f I). split. eauto using iso_stable_in.\n           assert (H3: one_one_on I f).\n           { cut (I [<=] G). eauto. auto. }\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  (*----------- Isomorphism, graph coloring for graphs -------------------------*)\n  \n  \n  Lemma iso_coloring (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(C: A->nat):\n    iso_using f g G G' -> Coloring_of G C -> Coloring_of G' (fun (x:B) => C (g x)).\n  Proof. { intros H H1. assert (Ha: iso_using g f G' G);auto. unfold Coloring_of.\n           intros x y Hx Hy H2.\n           assert (H3: edg G (g x) (g y)).\n           { replace  (edg G (g x) (g y)) with (edg G' x y). auto. eauto. }\n            apply H1; eauto. } Qed.\n          \n  Lemma iso_same_clrs  (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(C: A->nat):\n    iso_using f g G G' -> Coloring_of G C -> (clrs_of C G) = clrs_of (fun (x:B) => C (g x)) G'.\n  Proof. { intros H H1. assert (Ha: iso_using g f G' G). auto.\n           assert (H2: (nodes G) = img g G'). apply H.\n           unfold clrs_of; rewrite H2; auto. } Qed.\n  \n  Hint Resolve iso_coloring iso_same_clrs: core.\n\n\nEnd GraphIsoProp.\n\n\n\n\nHint Resolve fx_is_one_one img_of_img img_of_img1: core.\nHint Resolve img_of_img2 img_of_img3: core.\n\nHint Immediate iso_sym1 iso_sym iso_elim1 iso_elim2: core.\nHint Resolve iso_using_iso iso_using_iso1: core.\n\n Hint Immediate iso_one_one1 iso_one_one2 iso_one_one_on_l iso_one_one_on_s\n      iso_using_G iso_using_G': core.\n \nHint Immediate iso_cardinal iso_sub_cardinal iso_sub_cardinal1 iso_edg1 iso_edg2: core.\nHint Immediate iso_edg3 iso_edg4: core.\nHint Resolve iso_image1 iso_image2: core.\nHint Resolve iso_img_of_img1 iso_img_of_img2 iso_img_of_img3 iso_img_of_img4 : core.\n\nHint Immediate iso_cliq iso_cliq1 iso_cliq_in iso_cliq_in1: core.\n\nHint Immediate iso_stable iso_stable1 iso_stable_in iso_stable_in1: core.\nHint Resolve iso_coloring iso_same_clrs: core.\n\n\n\n\n\nSection IsoMaxIKC.\n\n  Context {A B: ordType }.\n\n  (*-------------------- Max_K has an iso counterpart--------------------- *)\n\n  Lemma max_K_in_G' (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(K: list A):\n    iso_using f g G G' -> Max_K_in G K -> Max_K_in G' (img f K). \n  Proof. { intros H H1. assert (H0: iso_using g 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 g Y|).\n           replace (|img f K|) with (|K|).\n            assert (H3: Cliq_in G (img g 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: @UG A)(G':@UG B)(n: nat):iso G G' -> cliq_num G n -> cliq_num G' n.\n  Proof. { intros H H1. destruct H as [f H]. destruct H as [g H].\n           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  (*------------------- Max_I has an iso counterpart----------------------- *)\n\n   Lemma max_I_in_G' (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(I: list A):\n    iso_using f g G G' -> Max_I_in G I -> Max_I_in G' (img f I).\n   Proof. { intros H H1. assert (H0: iso_using g 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 g Y|).\n           replace (|img f I|) with (|I|).\n           assert (H3: Stable_in G (img g 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: @UG A)(G':@UG B)(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 H as [g H].\n           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  (*-------------------- Cliq_num and Isomorphism ---------------------------------*)\n\n   Lemma best_coloring_of_G' (G: @UG A)(G':@UG B)(f: A->B)(g: B-> A)(C: A->nat):\n    iso_using f g G G' -> Best_coloring_of G C -> Best_coloring_of G' (fun (x:B) => C (g x)).\n  Proof. { unfold Best_coloring_of.  intros H H1.\n         assert (H0: iso_using g f G' G). auto.\n         destruct H1 as [H1 H2].\n         split.\n         { eauto using iso_coloring. }\n         { intros C' H3.\n           assert (H4: (clrs_of C G) = clrs_of (fun (x:B) => C (g x)) G').\n           { eapply iso_same_clrs. apply H. auto. }\n           rewrite <- H4.\n           assert (H5: (clrs_of C' G') = clrs_of (fun (x:A) => C' (f x)) G).\n           eapply iso_same_clrs with (f0:=g). all: auto.\n           rewrite H5.\n           apply H2. eauto using iso_coloring. } } Qed. \n                  \n  Lemma chrom_num_G' (G: @UG A)(G':@UG B)(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 H as [g H].\n           destruct H1 as [C H1]. destruct H1 as [H1 H2].\n           exists (fun (x:B) => C (g x)). split. eauto using best_coloring_of_G'.\n           subst n. replace (clrs_of (fun x : B => C (g x)) G') with (clrs_of C G).\n           auto. destruct H1 as [H1 H2].\n           eapply iso_same_clrs. apply H. auto. } Qed.\n\n  Hint Resolve best_coloring_of_G': core.\n  Hint Immediate chrom_num_G': core.\n\nEnd IsoMaxIKC.\n\n\nHint Immediate max_K_in_G' cliq_num_G': core.\nHint Immediate max_I_in_G' i_num_G': core.\n\nHint Resolve best_coloring_of_G': core.\nHint Immediate chrom_num_G': core.\n\n\n\nSection IsoNicePerfect.\n\n  Context { A B: ordType }.\n  \n  (*------------Isomorphism, nice graphs and perfect graph--------------------------------*)\n\n  Lemma nice_G' (G: @UG A)(G':@UG B) : 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 H: @UG A)(G':@UG B)(f: A->B)(g: B-> A): iso_using f g G G'->\n        Ind_subgraph H G ->(exists H', Ind_subgraph H' G'/\\ iso_using f g H H').\n  Proof.  { intros F1 F2.\n            assert (F0: iso_using g 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. apply F1. }\n            assert (h1: img f H [<=] G').\n            { replace (nodes G') with (img f G).\n                cut (H [<=] G). auto. apply F2.  symmetry. apply F1. }\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 g H H' *)\n              unfold iso_using.\n              split.\n              { (*--  morph_using f H H'--*)\n                split.\n                (*-- H' = img f H --*)\n                unfold H'. simpl. auto.\n                (*-- forall x y : A, In x H -> In y H -> edg H x y = edg H' (f x) (f y) --*)\n                simpl. intros x y Hx Hy.\n                replace (edg H x y) with (edg G x y). rewrite <- h2.\n                assert (H2: In (f x) (img f H)). auto.\n                replace ((edg G' at_ img f H) (f x) (f y)) with (edg G' (f x)(f y)).\n                destruct F2. cut(In y G). cut(In x G). all: auto. eauto.\n                symmetry. auto.  }\n              split.\n              {(*---  morph_using g H' H--*)\n                split.\n                (*--  H = img g H' ---*)\n                unfold H'. simpl. rewrite <- h2.\n                assert (h3: IsOrd H). auto.\n                assert (h4: H [<=] G). auto. eapply iso_img_of_img3 with (G0:=G).\n                all: auto. eauto.\n                (* forall x y : B, In x H' -> In y H' -> edg H' x y = edg H (g x) (g y)--*)\n                simpl. rewrite <- h2. intros x y Hx Hy.\n                replace ((edg G' at_ img f H) x y) with (edg G' x y).\n                replace (edg H (g x) (g y)) with (edg G (g x) (g y)).\n                apply F1. all:auto. symmetry. apply F2.\n                assert (h3: exists x0, In x0 H /\\ x = f x0). auto.\n                destruct h3 as [x0 h3]. destruct h3 as [h3 h4]. subst x.\n                replace  (g (f x0)) with x0. auto. symmetry. apply F1. apply F2. auto.\n                assert (h3: exists y0, In y0 H /\\ y = f y0). auto.\n                destruct h3 as [y0 h3]. destruct h3 as [h3 h4]. subst y.\n                replace  (g (f y0)) with y0. auto. symmetry. apply F1. apply F2. auto. }\n                intros x h3. apply F1. apply F2. auto. } } Qed.\n                \n\n\nEnd IsoNicePerfect.\n\nHint Immediate nice_G' iso_subgraphs : core.\n\n\n\nSection IsoPerfect.\n  \n  Context {A B: ordType}.\n\nLemma perfect_G' (G: @UG A)(G':@UG B): iso G G' -> Perfect G -> Perfect G'.\n  Proof. { intro F.  assert (F0: iso G' G). auto.\n         unfold Perfect. destruct F0 as [g F0]. destruct F0 as [f F0].\n         intros F1 H' F2.\n         assert (F3: exists H, Ind_subgraph H G /\\ iso_using g 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. exists g. cut (iso_using f g H H'); auto. } auto.  } Qed.\n\nEnd IsoPerfect.\n\nHint Immediate perfect_G': core.\n\n\n\n\n\nSection IsomorphTrans.\n  Context {A B C: ordType}.\n\n  Lemma iso_trans (G1 :@UG A)(G2: @UG B)(G3: @UG C):\n    iso G1 G2 -> iso G2 G3 -> iso G1 G3.\n  Proof. { intros h1 h2. destruct h1 as [f h1]. destruct h1 as [g h1].\n           destruct h2 as [f' h2]. destruct h2 as [g' h2].\n           assert (h3: nodes G2 = img f G1). eauto.\n           assert (h4: nodes G1 = img g G2). eauto.\n           assert (h5: nodes G3 = img f' G2). eauto.\n           assert (h6: nodes G2 = img g' G3). eauto.\n           \n           set (F:= fun x:A => f' (f  x)). set (G:= fun z:C => g (g' z)).\n           exists F. exists G. unfold iso_using.\n           split.\n           (* --- morph_using F G1 G3 ------ *)\n           { unfold morph_using.\n             split.\n             (*--- G3 = img F G1 ----*)\n             unfold F. replace (img (fun x : A => f' (f x)) G1) with (img f' (img f G1)).\n             rewrite <- h3. auto. eauto. \n             (*-- (forall x y : A, In x G1 -> In y G1 -> edg G1 x y = edg G3 (F x) (F y))---*)\n             unfold F.\n             intros x y hx hy. replace (edg G1 x y) with (edg G2 (f x) (f y)).\n             cut (In (f y) G2). cut (In (f x) G2). apply h2.\n             rewrite h3;auto. rewrite h3;auto. symmetry. apply h1. all: auto. }\n           split. \n           (* ---- morph_using G G3 G1 ------ *)\n           { unfold morph_using.\n             split.\n             (*--- G1 = img G G3 ----*)\n             unfold G. replace (img (fun z : C => g (g' z)) G3) with (img g (img g' G3)).\n             rewrite <- h6. auto. eauto. \n             (*-- (forall x y : C, In x G3 -> In y G3 -> edg G3 x y = edg G1 (G x) (G y) ---*)\n             unfold G.\n             intros x y hx hy. replace (edg G3 x y) with (edg G2 (g' x) (g' y)).\n             cut (In (g' y) G2). cut (In (g' x) G2). apply h1.\n             rewrite h6;auto. rewrite h6;auto. symmetry. apply h2. all: auto. }\n           (* -----(forall x : A, In x G1 -> G (F x) = x) -------*)\n           { intros x hx. unfold F. unfold G.\n             replace (g' (f' (f x))) with (f x). apply h1. auto.\n             symmetry. apply h2. rewrite h3. auto. } } Qed.\n  \nEnd IsomorphTrans.\n\nHint Immediate iso_trans: core.\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/GenIso.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.6768532154926449}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import Ascii.\n\n\nFixpoint asciiEnumFn (n : nat) : list ascii :=\n        match n with\n        | 0 => []\n        | S m => (ascii_of_nat m) :: asciiEnumFn m\n        end.\n\nDefinition asciiEnum : list ascii := asciiEnumFn 256.\n\nLemma ascii_finite : forall a : ascii, In a asciiEnum.\nProof.\n  intros. destruct a.\n  destruct b; destruct b0; destruct b1; destruct b2;\n    destruct b3; destruct b4; destruct b5; destruct b6;\n  repeat(try(left; reflexivity); right).\nQed.\n", "meta": {"author": "egolf-cs", "repo": "Verbatim", "sha": "97133d764ca742c7abe190808b304e2c535bb19c", "save_path": "github-repos/coq/egolf-cs-Verbatim", "path": "github-repos/coq/egolf-cs-Verbatim/Verbatim-97133d764ca742c7abe190808b304e2c535bb19c/Utils/asciiFinite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.6768366669617352}}
{"text": "Require Export Lists.\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\nModule MUMBLEBAZ.\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 mumble (b a 5)).\nCheck (d bool (b a 5)).\nCheck (e bool true).\nCheck (e mumble (b c 0)).\nCheck c.\n\nEnd MUMBLEBAZ.\nCheck (cons nat 2 (nil nat)).\nCheck cons.\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\nArguments nil {X}.\nArguments cons {X} _ _.\n\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\nArguments app {X} l1 l2.\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).\nFixpoint snoc {X : Type} (a : list X) (b : X) : list X :=\n  match a with\n    | nil => [b]\n    | h :: t => h :: (snoc t b)\n  end.\n\nTheorem snoc_with_append :\n  forall (X : Type) (l1 l2 : list X) (v : X),\n    snoc (l1 ++ l2) v = l1 ++ (snoc l2 v).\n\nProof.\n  induction l1.\n  reflexivity.\n  simpl.\n  intros l2 v.\n  rewrite -> IHl1.\n  reflexivity.\nQed.\n\nInductive prod (X Y :Type) : Type :=\n  pair : X -> Y -> prod X Y.\n\nArguments pair {X Y} _ _.\n\nNotation \"( x , y )\" := (pair x y).\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\nDefinition prod_curry {X Y Z:Type}\n           (f : (X * Y) -> Z) (x : X) (y : Y) : Z :=\n  f (x,y).\n\nDefinition prod_uncurry {X Y Z :Type}\n           (f : X -> Y -> Z) ( p : (X * Y)) : Z :=\n  match p with\n    | (x , y) => f x y\n  end.\n\nTheorem uncurry_curry :\n  forall (X Y Z : Type),\n  forall (f : X -> Y -> Z),\n  forall (x : X) (y : 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 :\n  forall (X Y Z : Type)\n         (f : (X * Y) -> Z)\n         (p : (X * Y)),\n    (prod_uncurry (prod_curry f)) p = f p.\nProof.\n  intros X Y Z f p.\n  destruct p as [x y].\n  reflexivity.\nQed.\n\nDefinition doit3times {X:Type} (f : X -> X) (x : X) : X :=\n  f (f (f x)).\n\nCheck (doit3times (fun n => match n with\n                              | O => O\n                              | S x => x\n                            end) 10).\n\nDefinition override {Y : Type} (f : nat -> Y) (x : nat) (y : Y) :(nat -> Y):=\n  fun (x' : nat) => if (beq_nat x' x)\n                    then y\n                    else f x'.\nDefinition plus3 :=\n  plus 3.\n\nTheorem unfold_example :\n  forall n m,\n    3 + n = m ->\n    plus3 n + 1 = m + 1.\n\nProof.\n  intros n m H.\n  unfold plus3.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem override_eq :\n  forall (X :  Type)\n         x k (f : nat -> X),\n    (override f k x) k = x.\nProof.\n  intros X x k f.\n  unfold override.\n  replace (beq_nat k k) with true.\n  reflexivity.\n  induction k.\n  reflexivity.\n  simpl.\n  rewrite -> IHk.\n  reflexivity.\nQed.\n\nModule CHURCH.\n  Definition nat := forall (X : Type),\n                      (X -> X) -> X -> X.\n  Definition zero : nat :=\n    fun (X : Type) (f : X -> X) (x : X) => x.\n  Definition succ (a : nat) : nat :=\n    fun (X : Type) (f : X -> X) (x : X) => f (a X f x).\n  Definition one : nat :=\n    fun (X : Type) (f : X -> X) (x : X) => f x.\n\n  \n  Example succ_1 : succ zero = one. \n  Proof.\n    reflexivity.\n  Qed.\n  Definition plus (a b : nat) : nat :=\n    fun (X : Type) (f : X -> X) (x : X) =>\n      b X f (a X f x).\n  Example plus_1 : plus zero one = one.\n  Proof.\n    reflexivity.\n  Qed.\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/5th.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.6768366659575878}}
{"text": "Require Import String.\nRequire Import Nat.\nRequire Import Coq.Vectors.Vector.\nRequire Import List.\nRequire Import Lia.\nImport ListNotations.\nOpen Scope string_scope.\nFrom ST Require Import EVarsScratchwork.\nFrom ST Require Export ST.SoftType.\nFrom ST Require Export Logic.V Logic.Term Logic.Predicate.\nImport VectorNotations.\n(** ** Formulas\n\nThe grammar of formulas is rather straightforward. Honestly, I was unsure how\n\"slick\" I should be: [Verum] could be defined as [Not Falsum], but using a \nminimal set of connectives seemed _too_ slick for my tastes.\n*)\nInductive Formula : Type :=\n| Falsum\n| Atom : Predicate -> Formula\n| And : Formula -> Formula -> Formula\n| Or : Formula -> Formula -> Formula\n| Implies : Formula -> Formula -> Formula\n| Exists : Formula -> Formula.\n\nDefinition Not (p : Formula) := Implies p Falsum.\nDefinition Verum : Formula := Implies Falsum Falsum.\nDefinition Forall (p : Formula) := Not (Exists (Not p)).\n\nDefinition is_and (p : Formula) : bool :=\nmatch p with\n| And _ _ => true\n| _ => false\nend.\n\nDefinition Is_and (p : Formula) : Prop :=\nmatch p with\n| And _ _ => True\n| _ => False\nend.\n\nDefinition Iff (a b : Formula) :=\n  And (Implies a b) (Implies b a).\n\nFixpoint formula_contains_bvar (index : nat) (A : Formula) : Prop :=\nmatch A with\n  | Falsum => False\n  | Atom pred => contains_bvar index pred\n  | And fm1 fm2 | Or fm1 fm2 | Implies fm1 fm2 => (formula_contains_bvar index fm1) \\/ (formula_contains_bvar index fm2)\n  | Exists fm => (formula_contains_bvar (S index) fm)\nend.\n\nGlobal Instance ContainsBVarFormula : ContainsBVar Formula := {\n  contains_bvar := formula_contains_bvar\n}.\n\nFixpoint is_ground_formula (phi : Formula) :=\nmatch phi with\n| Falsum => True\n| Atom p => is_ground p\n| And f1 f2 | Or f1 f2 | Implies f1 f2 => (is_ground_formula f1) /\\ (is_ground_formula f2)\n| Exists f => is_ground_formula f\nend.\n\nGlobal Instance GroundFormula : Ground Formula := {\n  is_ground := is_ground_formula\n}.\n\nDefinition is_sentence (A : Formula) := is_ground_formula A.\n\n(** We can recursively test if two [Formula] objects are identical. This is an\nequality at the level of syntax. *)\nFixpoint eq_formula (A B : Formula) : bool :=\nmatch A,B with\n| Falsum, Falsum => true\n| Atom (P n1 s1 args1), Atom (P n2 s2 args2) => \n      if andb (eqb n1 n2) (eqb s1 s2)\n      then vectors_eqb args1 args2 term_eqb\n      else false\n| And A1 A2, And B1 B2 => andb (eq_formula A1 B1) (eq_formula A2 B2)\n| Or A1 A2, Or B1 B2 => andb (eq_formula A1 B1) (eq_formula A2 B2)\n| Implies A1 A2, Implies B1 B2 =>  andb (eq_formula A1 B1) (eq_formula A2 B2)\n| Exists A1, Exists B1 => eq_formula A1 B1\n| _, _ => false\nend.\n\nGlobal Instance EqFormula : Eq Formula := {\n  eqb := eq_formula\n}.\n\nTheorem eq_dec : forall a b : Formula, {a = b} + {a <> b}.\nProof.\n  decide equality. apply Predicate.eq_dec.\nDefined.\n\n(** \"Variable closing\", or binding a free variable to a quantifier (or any\nbinder), is a bit tricky. We have a helper function here for the iterative\nstep. It behaves \"functorially\", descending to the leafs, i.e., [Falsum] and\n[Atom]. *)\nFixpoint var_closing_iter (x : name) (n : nat) (phi : Formula) : Formula :=\nmatch phi with\n| Falsum => phi\n| Atom pred => Atom (subst (FVar x) (Var (BVar n)) pred)\n| And fm1 fm2 => And (var_closing_iter x n fm1) (var_closing_iter x n fm2)\n| Or fm1 fm2 => Or (var_closing_iter x n fm1) (var_closing_iter x n fm2)\n| Implies fm1 fm2 => Implies (var_closing_iter x n fm1) (var_closing_iter x n fm2)\n| Exists fm => Exists (var_closing_iter x (S n) fm)\nend.\n\nDefinition quantify (x : name) (phi : Formula) : Formula :=\n  var_closing_iter x 0 phi.\n\n(** Substitution, when replacing a bound variable with an arbitrary term,\nrequires care. Why? Because we need to lift the bound variable as we encounter\nquantifiers. \n\nParticular care must be taken when the term refers to variables or quantities\nin the \"context part\". Towards that end, we must [lift] the term whenever a\nquantifier is encountered.\n*)\n\nFixpoint capture_free_subst (n : nat) (t : Term) (phi : Formula) : Formula :=\nmatch phi with\n| Falsum => phi\n| Atom pred => Atom (subst (BVar n) t pred)\n| And fm1 fm2 => And (capture_free_subst n t fm1) (capture_free_subst n t fm2)\n| Or fm1 fm2 => Or (capture_free_subst n t fm1) (capture_free_subst n t fm2)\n| Implies fm1 fm2 => Implies (capture_free_subst n t fm1) (capture_free_subst n t fm2)\n| Exists fm => Exists (capture_free_subst (S n) (lift (S n) 1 t) fm)\nend.\n\nLemma forall_subst : forall (n : nat) (t : Term) (A : Formula),\n  capture_free_subst n t (Forall A) = Forall (capture_free_subst (S n) (lift (S n) 1 t) A).\nProof.\n  intros; simpl; auto.\nQed.\n\n(** Specialization and choosing a witness for existential quantification\namounts to the same \"operations\" of peeling off an outermost quantifier, then\nbehaving as expected. *)\nFixpoint quantifier_elim_subst (n : nat) (t : Term) (phi : Formula) : Formula :=\nmatch phi with\n| Exists fm => capture_free_subst n t fm\n| And A B => And (quantifier_elim_subst n t A) (quantifier_elim_subst n t B)\n| Or A B => Or (quantifier_elim_subst n t A) (quantifier_elim_subst n t B)\n| Implies A B => Implies (quantifier_elim_subst n t A) (quantifier_elim_subst n t B)\n| _ => phi\nend.\n\nExample subst_bvar_1 : quantifier_elim_subst 0 (Fun \"t\" []) (Forall (Exists (Atom (P 2 \"P\" [Var (BVar 0); Var (BVar 1)]))))\n= Not (Not (Exists (Atom (P 2 \"P\" [Var (BVar 0); Fun \"t\" []])))).\nProof.\n  trivial.\nQed.\n\nExample subst_bvar_2 : quantifier_elim_subst 0 (Fun \"t\" [Var (BVar 0)]) (Forall (Exists (Atom (P 2 \"P\" [Var (BVar 0); Var (BVar 1)]))))\n= Not (Not (Exists (Atom (P 2 \"P\" [Var (BVar 0); Fun \"t\" [Var (BVar 0)]])))).\nProof.\n  trivial.\nQed.\n\nExample subst_bvar_3 : quantifier_elim_subst 0 (Fun \"t\" []) \n(Forall (Forall (Forall (Exists (Atom (P 3 \"P\" [Var (BVar 0); Var (BVar 1); Var (BVar 3)]))))))\n= Not (Not (Forall (Forall (Exists (Atom (P 3 \"P\" [Var (BVar 0); Var (BVar 1); (Fun \"t\" []) ])))))).\nProof.\n  simpl; auto.\nQed.\n\n(* In [Fun \"t\" [(Var (BVar 1))]], the parameter [BVar 1] is interpreted as a \nfree variable. For this reason, it will be \"kept above\" the syntactic depth\nof the outermost binder in the resulting formula. There are 3 quantifiers\nin the result, therefore we expect it to be [BVar 4] in the outcome. *)\nExample subst_bvar_4 : quantifier_elim_subst 0 (Fun \"t\" [(Var (BVar 1))]) \n(Forall (Forall (Forall (Exists (Atom (P 3 \"P\" [Var (BVar 0); Var (BVar 1); Var (BVar 3)]))))))\n= Not (Not (Forall (Forall (Exists (Atom (P 3 \"P\" [Var (BVar 0); Var (BVar 1); (Fun \"t\" [(Var (BVar 4))]) ])))))).\nProof.\n  simpl; auto.\nQed.\n\nFixpoint lift_formula (c d : nat) (phi : Formula) : Formula :=\n  match phi with\n  | Falsum => phi\n  | Atom pred => Atom (lift c d pred)\n  | And fm1 fm2 => And (lift_formula c d fm1) (lift_formula c d fm2)\n  | Or fm1 fm2 => Or (lift_formula c d fm1) (lift_formula c d fm2)\n  | Implies fm1 fm2 => Implies (lift_formula c d fm1) (lift_formula c d fm2)\n  | Exists fm => Exists (lift_formula (S c) d fm)\n  end.\n\nFixpoint unlift_formula (c d : nat) (phi : Formula) : Formula :=\n  match phi with\n  | Falsum => phi\n  | Atom pred => Atom (unlift c d pred)\n  | And fm1 fm2 => And (unlift_formula c d fm1) (unlift_formula c d fm2)\n  | Or fm1 fm2 => Or (unlift_formula c d fm1) (unlift_formula c d fm2)\n  | Implies fm1 fm2 => Implies (unlift_formula c d fm1) (unlift_formula c d fm2)\n  | Exists fm => Exists (unlift_formula (S c) d fm)\n  end.\n\nGlobal Instance LiftFormula : Lift Formula :=\n{\n  lift := lift_formula;\n  unlift := unlift_formula\n}.\n  \nLemma lift_forall : forall (c d : nat) (A : Formula),\n  lift c d (Forall A) = Forall (lift (S c) d A).\nProof.\n  intros; simpl; auto.\nQed.\n(**\nWe would encode $\\forall x\\exists y P(x,y)$ as \n[Forall (Exists (Atom (P 2 \"P\" [BVar 1; BVar 0])))], using de Bruijn indices.\n*)\n\nTheorem lift_id : forall {n : nat} (A : Formula),\n  lift n 0 A = A.\nProof.\n  intros.\n  assert (lift n 0 A = lift_formula n 0 A). { simpl; auto. } rewrite H; clear H.\n  generalize dependent n. induction A.\n  - intros; simpl; auto.\n  - intros; unfold lift_formula. destruct n as [|n].\n    + rewrite Predicate.lift_id. reflexivity.\n    + assert (lift 0 0 p = p). { apply Predicate.lift_id. }\n      rewrite (Predicate.bigger_lift_is_id 0 0 (S n)). \n      reflexivity. lia. rewrite Predicate.lift_id; reflexivity.\n  - intros; simpl; auto; rewrite IHA1; rewrite IHA2; reflexivity.\n  - intros; simpl; auto; rewrite IHA1; rewrite IHA2; reflexivity.\n  - intros; simpl; auto; rewrite IHA1; rewrite IHA2; reflexivity.\n  - intros; simpl; auto; rewrite (IHA (S n)); reflexivity.\nQed.\n\n\nTheorem lift_comp : forall (c d1 d2 : nat) (A : Formula),\n  lift c d1 (lift c d2 A) = lift c (d1 + d2) A.\nProof.\n  intros. generalize dependent c.\n  induction A.\n  - intros. simpl; auto.\n  - intros. assert(lift c d1 (lift c d2 (Atom p)) = Atom (lift c d1 (lift c d2 p))). {\n      simpl; auto.\n    } rewrite H.\n    assert (lift c (d1 + d2) (Atom p) = Atom (lift c (d1 + d2) p)). {\n      simpl; auto.\n    } rewrite H0.\n    assert (lift c d1 (lift c d2 p) = lift c (d1 + d2) p). {\n      apply Predicate.lift_comp.\n    } rewrite H1. reflexivity.\n  - intros. assert (lift c d1 (lift c d2 (And A1 A2)) = And (lift c d1 (lift c d2 A1)) (lift c d1 (lift c d2 A2))). {\n      simpl; auto.\n    } rewrite H; rewrite IHA1; rewrite IHA2.\n    assert (lift c (d1 + d2) (And A1 A2) = And (lift c (d1 + d2) A1) (lift c (d1 + d2) A2)). {\n      simpl; auto.\n    } rewrite H0. reflexivity.\n  - intros. assert (lift c d1 (lift c d2 (Or A1 A2)) = Or (lift c d1 (lift c d2 A1)) (lift c d1 (lift c d2 A2))). {\n      simpl; auto.\n    } rewrite H; rewrite IHA1; rewrite IHA2.\n    assert (lift c (d1 + d2) (Or A1 A2) = Or (lift c (d1 + d2) A1) (lift c (d1 + d2) A2)). {\n      simpl; auto.\n    } rewrite H0. reflexivity.\n  - intros. assert (lift c d1 (lift c d2 (Implies A1 A2)) = Implies (lift c d1 (lift c d2 A1)) (lift c d1 (lift c d2 A2))). {\n      simpl; auto.\n    } rewrite H; rewrite IHA1; rewrite IHA2.\n    assert (lift c (d1 + d2) (Implies A1 A2) = Implies (lift c (d1 + d2) A1) (lift c (d1 + d2) A2)). {\n      simpl; auto.\n    } rewrite H0. reflexivity.\n  - intros. assert (lift c d1 (lift c d2 (Exists A)) = Exists (lift (S c) d1 (lift (S c) d2 A))). { simpl; auto. }\n    assert (lift c (d1 + d2) (Exists A) = Exists (lift (S c) (d1 + d2) A)). { simpl; auto. }\n    rewrite H; rewrite H0. rewrite (IHA (S c)). reflexivity.\nQed.\n\nTheorem lift_seq : forall (c d2 d1 : nat) (A : Formula),\n  d1 > 0 -> lift (S c) d2 (lift c d1 A) = lift c (d2 + d1) A.\nProof.\n  intros. generalize dependent c.\n  induction A.\n  - intros. simpl; auto.\n  - intros. assert(lift (S c) d2 (lift c d1 (Atom p)) = Atom (lift (S c) d2 (lift c d1 p))). {\n      simpl; auto.\n    } rewrite H0.\n    assert (lift c (d2 + d1) (Atom p) = Atom (lift c (d2 + d1) p)). {\n      simpl; auto.\n    } rewrite H1.\n    assert (lift (S c) d2 (lift c d1 p) = lift c (d2 + d1) p). {\n      apply Predicate.lift_seq. assumption.\n    } rewrite H2. reflexivity.\n  - intros. assert (lift (S c) d2 (lift c d1 (And A1 A2)) = And (lift (S c) d2 (lift c d1 A1)) (lift (S c) d2 (lift c d1 A2))). {\n      simpl; auto.\n    } rewrite H0; rewrite IHA1; rewrite IHA2.\n    assert (lift c (d2 + d1) (And A1 A2) = And (lift c (d2 + d1) A1) (lift c (d2 + d1) A2)). {\n      simpl; auto.\n    } rewrite H1. reflexivity.\n  - intros. assert (lift (S c) d2 (lift c d1 (Or A1 A2)) = Or (lift (S c) d2 (lift c d1 A1)) (lift (S c) d2 (lift c d1 A2))). {\n      simpl; auto.\n    } rewrite H0; rewrite IHA1; rewrite IHA2.\n    assert (lift c (d2 + d1) (Or A1 A2) = Or (lift c (d2 + d1) A1) (lift c (d2 + d1) A2)). {\n      simpl; auto.\n    } rewrite H1. reflexivity.\n  - intros. assert (lift (S c) d2 (lift c d1 (Implies A1 A2)) = Implies (lift (S c) d2 (lift c d1 A1)) (lift (S c) d2 (lift c d1 A2))). {\n      simpl; auto.\n    } rewrite H0; rewrite IHA1; rewrite IHA2.\n    assert (lift c (d2 + d1) (Implies A1 A2) = Implies (lift c (d2 + d1) A1) (lift c (d2 + d1) A2)). {\n      simpl; auto.\n    } rewrite H1. reflexivity.\n  - intros. assert (lift (S c) d2 (lift c d1 (Exists A)) = Exists (lift (S (S c)) d2 (lift (S c) d1 A))). { simpl; auto. }\n    assert (lift c (d2 + d1) (Exists A) = Exists (lift (S c) (d2 + d1) A)). { simpl; auto. }\n    rewrite H0; rewrite H1. rewrite (IHA (S c)). reflexivity.\nQed.\n\n(*\nLemma variadic_lift_seq : forall (m : nat) (A : Formula),\n  (lift (S m) 1 (lift 1 m A)) = lift 1 (S m) A.\nProof.\n  intros. generalize dependent m.\n  induction A.\n  - intros. simpl; auto.\n  - intros. assert(lift (S m) 1 (lift 1 m (Atom p)) = Atom (lift (S m) 1 (lift 1 m p))). {\n      simpl; auto.\n    } rewrite H.\n    assert (lift 1 (S m) (Atom p) = Atom (lift 1 (S m) p)). {\n      simpl; auto.\n    } rewrite H0.\n    assert (lift (S m) 1 (lift 1 m p) = lift 1 (S m) p). {\n      apply Predicate.variadic_lift_seq.\n    } rewrite H1. reflexivity.\n  - intros. assert (lift (S m) 1 (lift 1 m (And A1 A2)) = And (lift (S m) 1 (lift 1 m A1)) (lift (S m) 1 (lift 1 m A2))). {\n      simpl; auto.\n    } rewrite H; rewrite IHA1; rewrite IHA2.\n    assert (lift 1 (S m) (And A1 A2) = And (lift 1 (S m) A1) (lift 1 (S m) A2)). {\n      simpl; auto.\n    } rewrite H0. reflexivity.\n  - intros. assert (lift (S m) 1 (lift 1 m (Or A1 A2)) = Or (lift (S m) 1 (lift 1 m A1)) (lift (S m) 1 (lift 1 m A2))). {\n      simpl; auto.\n    } rewrite H; rewrite IHA1; rewrite IHA2.\n    assert (lift 1 (S m) (Or A1 A2) = Or (lift 1 (S m) A1) (lift 1 (S m) A2)). {\n      simpl; auto.\n    } rewrite H0. reflexivity.\n  - intros. assert (lift (S m) 1 (lift 1 m (Implies A1 A2)) = Implies (lift (S m) 1 (lift 1 m A1)) (lift (S m) 1 (lift 1 m A2))). {\n      simpl; auto.\n    } rewrite H; rewrite IHA1; rewrite IHA2.\n    assert (lift 1 (S m) (Implies A1 A2) = Implies (lift 1 (S m) A1) (lift 1 (S m) A2)). {\n      simpl; auto.\n    } rewrite H0. reflexivity.\n  - intros. assert (lift (S m) 1 (lift 1 m (Exists A)) = Exists (lift (S (S m)) 1 (lift 2 m A))). { simpl; auto. }\n    assert (lift 1 (S m) (Exists A) = Exists (lift 2 (S m) A)). { simpl; auto. }\n    rewrite H; rewrite H0. rewrite (IHA (S m)). reflexivity.\nQed.\n*)\n\n\nLemma variadic_lift_seq : forall (k m : nat) (A : Formula),\n  k > 0 -> (lift (k + m) 1 (lift k m A)) = lift k (S m) A.\nProof.\n  intros. generalize dependent k. generalize dependent m.\n  induction A.\n  - intros. simpl; auto.\n  - intros. assert(lift (k + m) 1 (lift k m (Atom p)) = Atom (lift (k + m) 1 (lift k m p))). {\n      simpl; auto.\n    } rewrite H0.\n    assert (lift k (S m) (Atom p) = Atom (lift k (S m) p)). {\n      simpl; auto.\n    } rewrite H1.\n    assert (lift (k + m) 1 (lift k m p) = lift k (S m) p). {\n      apply Predicate.variadic_quantifier_lift_seq. assumption.\n    } rewrite H2. reflexivity.\n  - intros. assert (lift (k + m) 1 (lift k m (And A1 A2)) \n                    = And (lift (k + m) 1 (lift k m A1)) (lift (k + m) 1 (lift k m A2))). {\n      simpl; auto.\n    } rewrite H0; rewrite IHA1. rewrite IHA2.\n    assert (lift k (S m) (And A1 A2) = And (lift k (S m) A1) (lift k (S m) A2)). {\n      simpl; auto.\n    } rewrite H1. reflexivity. assumption. assumption.\n  - intros. assert (lift (k + m) 1 (lift k m (Or A1 A2)) = Or (lift (k + m) 1 (lift k m A1)) (lift (k + m) 1 (lift k m A2))). {\n      simpl; auto.\n    } rewrite H0; rewrite IHA1. rewrite IHA2.\n    assert (lift k (S m) (Or A1 A2) = Or (lift k (S m) A1) (lift k (S m) A2)). {\n      simpl; auto.\n    } rewrite H1. reflexivity. assumption. assumption.\n  - intros. assert (lift (k + m) 1 (lift k m (Implies A1 A2)) = Implies (lift (k + m) 1 (lift k m A1)) (lift (k + m) 1 (lift k m A2))). {\n      simpl; auto.\n    } rewrite H0; rewrite IHA1. rewrite IHA2.\n    assert (lift k (S m) (Implies A1 A2) = Implies (lift k (S m) A1) (lift k (S m) A2)). {\n      simpl; auto.\n    } rewrite H1. reflexivity. assumption. assumption.\n  - intros. assert (lift (k + m) 1 (lift k m (Exists A)) = Exists (lift (S (k + m)) 1 (lift (S k) m A))). { simpl; auto. }\n    assert (lift k (S m) (Exists A) = Exists (lift (S k) (S m) A)). { simpl; auto. }\n    rewrite H0; rewrite H1.\n    assert (lift (S k + m) 1 (lift (S k) m A) = lift (S k) (S m) A). {\n      apply (IHA m (S k)). apply Gt.gt_Sn_O.\n    }\n    assert (S k + m = S (k + m)). lia. rewrite H3 in H2.\n    rewrite H2; reflexivity.\nQed.\n\n(**\nWe now have a helper function to quantify over a given variable. They handle\nlifting and replacement, if the variable appears at all in the [Formula]. If\n[n] does not appear in [Formula], then the formula [phi] is returned unchanged.\n*)\nDefinition every (n : name) (phi : Formula) : Formula :=\n  let phi' := quantify n (shift phi)\n  in if eqb phi' (shift phi) then phi else Forall phi'.\n\nDefinition any (n : name) (phi : Formula) : Formula :=\n  let phi' := quantify n (shift phi)\n  in if eqb phi' (shift phi) then phi else Exists phi'.\n\n(** As a smoke check, we see if variations on a simple formula are \"parsed\" as\nexpected. *)\nExample quantifier_example_1 : (every \"x\" (any \"y\" (Atom (P 2 \"P\" [Var (FVar \"x\"); Var (FVar \"y\")]))))\n= Forall (Exists (Atom (P 2 \"P\" [Var (BVar 1); Var (BVar 0)]))).\nProof.\n  trivial.\nQed.\n\nExample quantifier_example_2 : \n  every \"z\" (any \"y\" (Atom (P 2 \"P\" [Var (FVar \"x\"); Var (FVar \"y\")])))\n  = Exists (Atom (P 2 \"P\" [Var (FVar \"x\"); Var (BVar 0)])).\nProof.\n  trivial.\nQed.\n\n\nFixpoint fresh_formula (c : Term) (p : Formula) : Prop :=\n  match p with\n  | Falsum => True\n  | Atom phi => fresh c phi\n  | And A B | Or A B | Implies A B => (fresh_formula c A) /\\ (fresh_formula c B)\n  | Exists A => fresh_formula c A\n  end.\n  \nGlobal Instance FreshFormula : Fresh Formula := {\n  fresh := fresh_formula\n}.\n\nGlobal Instance FreshContext : Fresh (list Formula) := {\n  fresh c Γ := List.Forall (fresh c) Γ\n}.\n\n(** * Listing the Existential Variables appearing in a Formula *)\nFixpoint list_evars_formula (phi : Formula) : list nat :=\nmatch phi with\n| Falsum => []%list\n| Atom pred => list_evars pred\n| And fm1 fm2 | Or fm1 fm2 | Implies fm1 fm2 => insert_merge (list_evars_formula fm1) (list_evars_formula fm2)\n| Exists fm => (list_evars_formula fm)\nend.\n\nGlobal Instance EnumerateEVarsFormula : EnumerateEVars Formula := {\nlist_evars := list_evars_formula\n}. \n\nTheorem list_evars_formula_sorted : forall (phi : Formula),\n  sorted (list_evars phi).\nProof. intros. induction phi.\n- simpl; auto. apply sorted_nil.\n- unfold list_evars; unfold EnumerateEVarsFormula. apply list_evars_predicate_sorted.\n- unfold list_evars; unfold EnumerateEVarsFormula.\n  apply insert_merge_sorted2; assumption.\n- unfold list_evars; unfold EnumerateEVarsFormula.\n  apply insert_merge_sorted2; assumption.\n- unfold list_evars; unfold EnumerateEVarsFormula.\n  apply insert_merge_sorted2; assumption.\n- simpl; auto.\nQed.\n\nGlobal Instance EnumerateEVarsFormulaList : EnumerateEVars (list Formula) := {\nlist_evars Γ := (List.fold_left (fun l' => fun (phi : Formula) => insert_merge (list_evars phi) l')\n Γ []%list)\n}. \n\nTheorem list_evars_formula_list_sorted : forall (l : list Formula),\n  sorted (list_evars l).\nProof.\n  intros. unfold list_evars; unfold EnumerateEVarsFormulaList.\n  apply insert_merge_list_fold_sorted. apply sorted_nil.\nQed.\n\nFixpoint lift_evars_formula (k : nat) (phi : Formula) : Formula :=\nmatch phi with\n| Falsum => phi\n| Atom pred => Atom (lift_evars k pred)\n| And fm1 fm2 => And (lift_evars_formula k fm1) (lift_evars_formula k fm2)\n| Or fm1 fm2 => Or (lift_evars_formula k fm1) (lift_evars_formula k fm2)\n| Implies fm1 fm2 => Implies (lift_evars_formula k fm1) (lift_evars_formula k fm2)\n| Exists fm => Exists (lift_evars_formula k fm)\nend.\n\nGlobal Instance LiftEvarsFormula : LiftEvars Formula := {\n  lift_evars := lift_evars_formula\n}.\n\nGlobal Instance LiftEvarsListFormula : LiftEvars (list Formula) := {\n  lift_evars k Γ := List.map (lift_evars k) Γ\n}.\n\nDefinition fresh_evar_counter (Γ : list Formula) (p : Formula) : nat :=\nfirst_new 0 (list_evars (p::Γ)%list).\n\nDefinition fresh_evar (Γ : list Formula) (p : Formula) : Term :=\nEConst (fresh_evar_counter Γ p).\n\n(* TODO: these next two results should be proven, but I am lazy. *)\nLemma fresh_evar_context : forall (Γ : list Formula) (p : Formula),\n  fresh (fresh_evar Γ p) Γ.\nAdmitted.\n\n(* Exercise: Prove the following.\n\nLemma fresh_evar_body : forall (Γ : list Formula) (p : Formula),\n  fresh (fresh_evar Γ p) p.\nAdmitted.\n*)\n(*\nLemma capture_free_subst_id0 : forall (p : Formula),\n  capture_free_subst 0 (Var (BVar 0)) p = p.\nProof.\n  intros. induction p.\n  - simpl; auto.\n  - unfold capture_free_subst; rewrite Predicate.subst_id; reflexivity.\n  - simpl; auto; rewrite IHp1; rewrite IHp2; reflexivity. \n  - simpl; auto; rewrite IHp1; rewrite IHp2; reflexivity. \n  - simpl; auto; rewrite IHp1; rewrite IHp2; reflexivity. \n  - assert (capture_free_subst 0 (Var (BVar 0)) (Exists p)\n            = Exists (capture_free_subst (S 0) (lift (S 0) 1 (Var (BVar 0))) p)). {\n      simpl; auto.\n    admit.\n    }\n    rewrite H.\n    assert (lift 1 1 (Var (BVar 0)) = Var (BVar 0)). {\n      simpl; auto.\n    }\n    rewrite H0.\n    admit.\nAdmitted.\n\nLemma capture_free_subst_id : forall (n : nat) (p : Formula),\n  capture_free_subst n (Var (BVar n)) p = p.\nProof.\n  intros. generalize dependent n. induction p.\n  - intros; simpl; auto.\n  - intros; unfold capture_free_subst; rewrite Predicate.subst_id; reflexivity.\n  - intros; simpl; auto; rewrite IHp1; rewrite IHp2; reflexivity. \n  - intros; simpl; auto; rewrite IHp1; rewrite IHp2; reflexivity. \n  - intros; simpl; auto; rewrite IHp1; rewrite IHp2; reflexivity. \n  - intros.\n    assert (capture_free_subst n (Var (BVar n)) (Exists p)\n            = Exists (capture_free_subst (S n) (lift (S n) 1 (Var (BVar n))) p)). {\n      simpl; auto.\n    }\n    assert (lift (S n) 1 (Var (BVar n)) = Var (BVar n)). {\n      assert (lift (S n) 1 (Var (BVar n)) = Var (lift (S n) 1 (BVar n))). {\n        simpl; auto.\n      } rewrite H0.\n      assert (lift (S n) 1 (BVar n) = BVar n). {\n        apply case_lift_is_id. simpl; auto.\n      }\n      rewrite H1; reflexivity.\n    }\n    rewrite H; rewrite H0.\nAdmitted.\n*)\n\nFixpoint contains_formula (sub : Term) (fm : Formula) : Prop := match fm with\n  | Falsum => False\n  | Atom p => contains sub p\n  | And A B | Or A B | Implies A B => (contains_formula sub A) \\/ (contains_formula sub B)\n  | Exists A => contains_formula sub A\nend.\n\nGlobal Instance ContainsFormula : Contains Formula := {\n  contains := contains_formula\n}.\n\n(* Syntactic substitution *)\nFixpoint subst_formula (x : V) (t : Term) (A : Formula) :=\nmatch A with\n| Falsum => A\n| Atom pred => Atom (subst x t pred)\n| Or p q => Or (subst_formula x t p) (subst_formula x t q)\n| And p q => And (subst_formula x t p) (subst_formula x t q)\n| Implies p q => Implies (subst_formula x t p) (subst_formula x t q)\n| Exists p => Exists (subst_formula x t p)\nend.\n\nGlobal Instance SubstFormula : Subst Formula :=\n{\n  subst := subst_formula\n}.\n", "meta": {"author": "pqnelson", "repo": "soft-type", "sha": "4a46a11ea98b89425d571fcb1ba0c73a30cd91c4", "save_path": "github-repos/coq/pqnelson-soft-type", "path": "github-repos/coq/pqnelson-soft-type/soft-type-4a46a11ea98b89425d571fcb1ba0c73a30cd91c4/ST/Logic/Formula.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.676836659851334}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** Here are collected some results about the type sumbool (see INIT/Specif.v)\n   [sumbool A B], which is written [{A}+{B}], is the informative\n   disjunction \"A or B\", where A and B are logical propositions.\n   Its extraction is isomorphic to the type of booleans. *)\n\n(** A boolean is either [true] or [false], and this is decidable *)\n\nDefinition sumbool_of_bool : forall b:bool, {b = true} + {b = false}.\n  destruct b; auto.\nDefined.\n\nHint Resolve sumbool_of_bool: bool.\n\nDefinition bool_eq_rec :\n  forall (b:bool) (P:bool -> Set),\n    (b = true -> P true) -> (b = false -> P false) -> P b.\n  destruct b; auto.\nDefined.\n\nDefinition bool_eq_ind :\n  forall (b:bool) (P:bool -> Prop),\n    (b = true -> P true) -> (b = false -> P false) -> P b.\n  destruct b; auto.\nDefined.\n\n\n(** Logic connectives on type [sumbool] *)\n\nSection connectives.\n\n  Variables A B C D : Prop.\n\n  Hypothesis H1 : {A} + {B}.\n  Hypothesis H2 : {C} + {D}.\n\n  Definition sumbool_and : {A /\\ C} + {B \\/ D}.\n    case H1; case H2; auto.\n  Defined.\n\n  Definition sumbool_or : {A \\/ C} + {B /\\ D}.\n    case H1; case H2; auto.\n  Defined.\n\n  Definition sumbool_not : {B} + {A}.\n    case H1; auto.\n  Defined.\n\nEnd connectives.\n\nHint Resolve sumbool_and sumbool_or: core.\nHint Immediate sumbool_not : core.\n\n(** Any decidability function in type [sumbool] can be turned into a function\n    returning a boolean with the corresponding specification: *)\n\nDefinition bool_of_sumbool :\n  forall A B:Prop, {A} + {B} -> {b : bool | if b then A else B}.\n  intros A B H.\n  elim H; intro; [exists true | exists false]; assumption.\nDefined.\nArguments bool_of_sumbool : default implicits.\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/Bool/Sumbool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357568, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.6768366516554156}}
{"text": "(** * Basics: Functional Programming in Coq *)\n\n\n(* REMINDER:\n\n          #####################################################\n          ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n          #####################################################\n\n   (See the [Preface] for why.) \n\n*)\n\n(* [Admitted] is Coq's \"escape hatch\" that says accept this definition\n   without proof.  We use it to mark the 'holes' in the development\n   that should be completed as part of your homework exercises.  In\n   practice, [Admitted] is useful when you're incrementally developing\n   large proofs. *)\nDefinition admit {T: Type} : T.  Admitted.\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\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 to\n    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 special phrases [Admitted] and [admit] can be used as a\n    placeholder for an incomplete definition or proof.  We'll use them\n    in exercises, to indicate the parts that we're leaving for you --\n    i.e., your job is to replace [admit] or [Admitted] with real\n    definitions or 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 \n  (* SOLUTION: *) := \n  match b1 with\n  | true => negb b2\n  | false => true\n  end.\n\nExample test_nandb1:               (nandb true false) = true.\n(* SOLUTION: *) Proof. simpl. reflexivity.  Qed.\nExample test_nandb2:               (nandb false false) = true.\n(* SOLUTION: *) Proof. simpl. reflexivity.  Qed.\nExample test_nandb3:               (nandb false true) = true.\n(* SOLUTION: *) Proof. simpl. reflexivity.  Qed.\nExample test_nandb4:               (nandb true true) = false.\n(* SOLUTION: *) Proof. simpl. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 1 star (andb3)  *)\n(** Do the same for the [andb3] function below. This function should\n    return [true] when all of its inputs are [true], and [false]\n    otherwise. *)\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool \n  (* SOLUTION: *) :=\n  andb b1 (andb b2 b3).\n\nExample test_andb31:                 (andb3 true true true) = true.\n(* SOLUTION: *) Proof. simpl. reflexivity.  Qed.\nExample test_andb32:                 (andb3 false true true) = false.\n(* SOLUTION: *) Proof. simpl. reflexivity.  Qed.\nExample test_andb33:                 (andb3 true false true) = false.\n(* SOLUTION: *) Proof. simpl. reflexivity.  Qed.\nExample test_andb34:                 (andb3 true true false) = false.\n(* SOLUTION: *) Proof. 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 the natural numbers as follows: *)\n\nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\n(** The clauses of this definition can be read:\n      - [O] is a natural number (note that this is the letter \"[O],\"\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_.  The definition of [nat] says how\n    expressions in the set [nat] can be constructed:\n\n    - the expression [O] belongs to the set [nat];\n    - if [n] is an expression belonging to the set [nat], then [S n]\n      is also an expression belonging to the set [nat]; and\n    - expressions formed in these two ways are the only ones belonging\n      to the set [nat].\n\n    The same rules apply for our definitions of [day] and [bool]. The\n    annotations we used for their constructors are analogous to the\n    one for the [O] constructor, indicating that they don't take any\n    arguments.\n\n    These three 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 like\n    [true], [andb true false], and [S (S false)] do not.\n\n    We can write simple functions that pattern match on natural\n    numbers just as we did above -- for example, 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!\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 that is a bit easier to work with: *)\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 bogus\n    variable 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  (* SOLUTION: *) :=\n  match n with\n  | O => 1\n  | S n' => mult n (factorial n')\n  end.\n\nExample test_factorial1:          (factorial 3) = 6.\n(* SOLUTION: *) Proof. simpl. reflexivity.  Qed.\nExample test_factorial2:          (factorial 5) = (mult 10 12).\n(* SOLUTION: *) Proof. simpl. reflexivity.  Qed.\n(** [] *)\n\n(** We can make numerical expressions a little easier to read and\n    write by introducing _notations_ for addition, multiplication, and\n    subtraction. *)\n\nNotation \"x + y\" := (plus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x - y\" := (minus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x * y\" := (mult x y)\n                       (at level 40, left associativity)\n                       : nat_scope.\n\nCheck ((0 + 1) + 1).\n\n(** (The [level], [associativity], and [nat_scope] annotations\n    control how these notations are treated by Coq's parser.  The\n    details are not important, but interested readers can refer to the\n    optional \"More on Notation\" section at the end of 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\n    operation! *)\n\n(** The [beq_nat] function tests [nat]ural numbers for [eq]uality,\n    yielding a [b]oolean.  Note the use of nested [match]es (we could\n    also have used a simultaneous match, as we did in [minus].)  *)\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\n(** 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  (* SOLUTION: *) :=\n  (leb (S n) m).\n\nExample test_blt_nat1:             (blt_nat 2 2) = false.\n(* SOLUTION: *) Proof. simpl. reflexivity.  Qed.\nExample test_blt_nat2:             (blt_nat 2 4) = true.\n(* SOLUTION: *) Proof. simpl. reflexivity.  Qed.\nExample test_blt_nat3:             (blt_nat 4 2) = false.\n(* SOLUTION: *) Proof. 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\n    almost exactly the same as the simpler examples we saw earlier;\n    there are 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. *)\n(** You may want to add calls to [simpl] before [reflexivity] to\n    see the simplifications that Coq performs on the terms before\n    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\n(** (Can you explain why this happens?  Step through both proofs\n    with Coq and notice how the goal and context change.)\n\n    When stuck in the middle of a proof, we can use the [Abort]\n    command to give up on it for the moment. *)\n\nAbort.\n\n(** The next chapter will introduce _induction_, a powerful\n    technique that can be used for proving this goal.  For the moment,\n    though, let's look at a few more simple tactics. *)\n\n(* ################################################################# *)\n(** * Proof by Rewriting *)\n\n(** This theorem is a bit more interesting than the others we've\n    seen: *)\n\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + n = m + m.\n\n(** Instead of making a universal claim about all numbers [n] and [m],\n    it talks about a more specialized property that only holds when [n\n    = m].  The arrow symbol is pronounced \"implies.\"\n\n    As before, we need to be able to reason by assuming 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  (* SOLUTION: *)\n  intros m n o.\n  intros EQmn.\n  intros EQno.\n  rewrite -> EQmn.\n  rewrite -> EQno.\n  reflexivity.  Qed.\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] (or\n    [admit]) you are leaving a door open for total nonsense to enter\n    Coq's nice, 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  (* SOLUTION: *)\n  intros. rewrite plus_1_l.\n  rewrite <- H.  reflexivity. Qed.\n(** [] *)\n\n\n(* ################################################################# *)\n(** * Proof by Case Analysis *)\n\n(** Of course, not everything can be proved by simple\n    calculation and rewriting: In general, unknown, hypothetical\n    values (arbitrary numbers, booleans, lists, etc.) can block\n    simplification.  For example, if we try to prove the following\n    fact using the [simpl] tactic as above, we get stuck. *)\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\n    c] line right above it.  Besides [-] and [+], Coq proofs can also\n    use [*] (asterisk) as a third kind of bullet. If we ever encounter\n    a proof that generates more than three levels of subgoals, we can\n    also enclose individual subgoals in curly braces ([{ ... }]): *)\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  (* SOLUTION: *)\n  intros b [] H.\n  - reflexivity.\n  - rewrite <- H.\n    destruct b.\n    + reflexivity.\n    + reflexivity.  Qed.\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  (* SOLUTION: *)\n  intros [|n].\n  - reflexivity.\n  - reflexivity.  Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** More on Notation (Optional) *)\n\n(** (In general, sections marked Optional are not needed to follow the\n    rest of the book, except possibly other Optional sections.  On a\n    first reading, you might want to skim these sections so that you\n    know what's there for future reference.)\n\n    Recall the notation definitions for infix plus and times: *)\n\nNotation \"x + y\" := (plus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x * y\" := (mult x y)\n                       (at level 40, left associativity)\n                       : nat_scope.\n\n(** For each notation symbol in Coq, we can specify its _precedence\n    level_ and its _associativity_.  The precedence level [n] is\n    specified by writing [at level n]; this helps Coq parse compound\n    expressions.  The associativity setting helps to disambiguate\n    expressions containing multiple occurrences of the same\n    symbol. For example, the parameters specified above for [+] and\n    [*] say that the expression [1+2*3*4] is shorthand for\n    [(1+((2*3)*4))]. Coq uses precedence levels from 0 to 100, and\n    _left_, _right_, or _no_ associativity.  We will see more examples\n    of this later, e.g., in the [Lists]\n    chapter.\n\n    Each notation symbol is also associated with a _notation scope_.\n    Coq tries to guess what scope is meant from context, so when it\n    sees [S(O*O)] it guesses [nat_scope], but when it sees the\n    cartesian product (tuple) type [bool*bool] it guesses\n    [type_scope].  Occasionally, it is necessary to help it out with\n    percent-notation by writing [(x*y)%nat], and sometimes in what Coq\n    prints it will use [%nat] to indicate what scope a notation is in.\n\n    Notation scopes also apply to numeral notation ([3], [4], [5],\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(* ================================================================= *)\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(* SOLUTION: *)\n(*\nFixpoint factorial_bad (n:nat) : nat :=\n  match beq_nat n 0 with\n  | true => 1\n  | false => n * (factorial_bad (n-1))\n  end.\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  (* SOLUTION: *)\n  intros f H b.\n  rewrite H. rewrite H. reflexivity. 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\n(* SOLUTION: *)\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. rewrite H. destruct b.\n  - reflexivity.\n  - reflexivity. 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\nLemma fact1 : andb true false = false.\nProof. reflexivity. Qed.\nLemma fact2 : andb false true = false.\nProof. reflexivity. Qed.\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  (* SOLUTION: *)\n  intros [] [] H.\n  - reflexivity.\n  - rewrite <- fact1. rewrite H. reflexivity.\n  - rewrite <- fact2. rewrite H. reflexivity.\n  - reflexivity. Qed.\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] from class,\n\n         Inductive nat : Type :=\n           | O : nat\n           | 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 numbers.\n\n    (c) Write five unit tests [test_bin_incr1], [test_bin_incr2], etc.\n        for your increment and binary-to-unary functions. Notice that\n        incrementing a binary number and then converting it to unary\n        should yield the same result as first converting it to unary and\n        then incrementing.\n*)\n\n(* SOLUTION: *)\nInductive bin : Type :=\n  | BZ : bin\n  | T2 : bin -> bin\n  | T2P1 : bin -> bin.\n\nFixpoint incr (m:bin) : bin :=\n  match m with\n  | BZ      => T2P1 BZ\n  | T2 m'   => T2P1 m'\n  | T2P1 m' => T2 (incr m')\n  end.\n\nFixpoint bin_to_nat (m:bin) : nat :=\n  match m with\n  | BZ      => O\n  | T2   m' => 2 * bin_to_nat m'\n  | T2P1 m' => 1 + 2 * bin_to_nat m'\n  end.\n\nExample test_bin_incr1 : (incr (T2P1 BZ)) = T2 (T2P1 BZ).\n  reflexivity. Qed.\n\nExample test_bin_incr2 : (incr (T2 (T2P1 BZ))) = T2P1 (T2P1 BZ).\n  reflexivity. Qed.\n\nExample test_bin_incr3 : bin_to_nat (T2 (T2P1 BZ)) = 2.\n  reflexivity. Qed.\n\nExample test_bin_incr4 :\n        bin_to_nat (incr (T2P1 BZ)) = 1 + bin_to_nat (T2P1 BZ).\n  reflexivity. Qed.\n\nExample test_bin_incr5 :\n        bin_to_nat (incr (incr (T2P1 BZ))) = 2 + bin_to_nat (T2P1 BZ).\n  reflexivity. Qed.\n\n(** [] *)\n\n(** $Date: 2016-08-29 15:12:34 -0500 (Mon, 29 Aug 2016) $ *)\n\n", "meta": {"author": "HugoTian", "repo": "CS386L_PL_coq", "sha": "34dea8b5badf8164dd1b10e49b32d17233e6e71d", "save_path": "github-repos/coq/HugoTian-CS386L_PL_coq", "path": "github-repos/coq/HugoTian-CS386L_PL_coq/CS386L_PL_coq-34dea8b5badf8164dd1b10e49b32d17233e6e71d/homework/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.7981867729389245, "lm_q1q2_score": 0.6768366486158504}}
{"text": "(* week_35_exercises.v *)\n(* dIFP 2014-2015, Q1 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* ********** *)\n\n(*\n\nThe learning goals of this first lecture are as follows:\n\n* Install Coq on each student's laptop.\n\n* Preferably use Emacs with Proof General,\n  because it scales better than CoqIde\n  (tick \"3 Windows mode layout\" in the Coq top menu;\n  use the hybrid mode if your screen is not wide enough).\n\n* Understand the basic idea of stepping forward and backwards through\n  a Coq file, either with the arrows \"Next\" and \"Undo\" in the tool bar,\n  or C-c C-n and C-c C-u on the keyboard.\n\n* Visualize that a proof is a tree, similarly to an abstract-syntax tree\n  and a typing-derivation tree.  (About that, it would be a good idea\n  to read\n    http://users-cs.au.dk/danvy/dProgSprog/Lecture-notes/week-22.html\n  again.)  When proving a theorem in Coq, we interactively construct\n  its proof tree.\n\n* Make formal statements:\n\n    <formal-statement> ::= <keyword> <identifier> : <logical-formula>\n             <keyword> ::= Lemma\n                         | Theorem\n                         | Corollary\n          <identifier> ::= ...\n     <logical-formula> ::= forall {<identifier>}+, <logical-expression>\n  <logical-expression> ::= <identifier>\n                         | <logical-expression> -> <logical-expression>\n                         | <logical-expression> /\\ <logical-expression>\n                         | <logical-expression> \\/ <logical-expression>\n\n  where\n    \"A -> B\" is an implication,\n    \"A /\\ B\" is a conjunction, and\n    \"A /\\ B\" is a disjunction.\n\n* Syntactic sugar: \"A <-> B\" is the conjunction\n    \"(A -> B) /\\ (B -> A)\"\n\n* Prove formal statements:\n\n  <proof-script> ::= Proof.  {<coq-commands>}+  Qed.\n\n  At the end of a proof, either write \"Qed.\" to tell Coq that the\n  proof script is complete, or write \"Admitted.\" if you can prove it\n  but you believe in your heart that it holds, or write \"Abort.\" if\n  you can prove it and you don't want to rely on it later in the file.\n\n* Processing goals:\n\n  When the goal is \"forall x : blah1, blah2\", write \"intro x.\"\n  to move x from your goal to your assumptions.\n\n  When the goal is \"A -> B\", write \"intro H_A.\"\n  to declare the hypothesis about A in your assumptions.\n\n  When the goal is \"P\" and you have an assumption about it, H_P,\n  write \"apply H_P.\".\n\n  Instead of writing \"intro X.  intro Y.  intro Z.\"\n  you can more concisely write \"intros X Y Z.\".\n\n  Instead of writing \"intro H_X.  intro H_Y.  intro H_Z.\"\n  you can more concisely write \"intros H_X H_Y H_Z.\".\n\n  When the goal is \"A /\\ B -> C\", use Coq's pattern-matching facility\n  and write \"intros [H_A H_B].\"\n  to directly name the hypotheses about A and B.\n\n  When the goal is \"A \\/ B -> C\", use Coq's pattern-matching facility\n  and write \"intros [H_A | H_B].\"\n  to directly name the hypotheses about A and B.\n  (This will create a subgoal.)\n\n  When the goal is a conjunction, write \"split.\".\n  (This will create a subgoal.)\n\n  So in particular, when the goal is an equivalence \"A <-> B\",\n  write \"split.\".\n\n  When the goal is a disjunction, write \"left.\" or \"right.\"\n  depending on which disjunct you want to prove.\n\n* Apply lemmas or theorems that were already proved.\n\n* Load a library of lemmas and theorems:\n\n    Require Import Arith.\n\n* Use an equality lemma to rewrite a formula\n  (see comm_a et al. below).\n\n* Use \"reflexivity.\" and \"symmetry.\".\n\n* Restart a proof.\n\n* Simple convention about indentation:\n  the number of indentations (two white spaces) matches the number of subgoals.\n\n* Readability:\n  don't hesitate to put empty lines in your proofs,\n  to delineate conceptual blocks.\n\n*)\n\n(* ********** *)\n\n(* Exercise 1:\n   Prove that conjunction and disjunctions are associative.\n*)\n\nTheorem conjunction_is_associative_either_way :\n  forall P1 P2 P3 : Prop,\n    P1 /\\ (P2 /\\ P3) <-> (P1 /\\ P2) /\\ P3.\nProof.\n  intros P1 P2 P3.\n  split.\n    (* -> *)\n    intros [H_P1 [H_P2 H_P3]].\n    split.\n      split.\n        apply H_P1.\n      apply H_P2.\n    apply H_P3.\n  (* <- *)\n  intros [[H_P1 H_P2] H_P3].\n  split.\n    apply H_P1.\n  split.\n    apply H_P2.\n  apply H_P3.\nQed.\n\nTheorem disjunction_is_associative_either_way :\n  forall P1 P2 P3 : Prop,\n    P1 \\/ (P2 \\/ P3) <-> (P1 \\/ P2) \\/ P3.\nProof.\n  split.\n    (* -> *)\n    intros [H_P1 | [H_P2 | H_P3]].\n        left. left. apply H_P1.\n      left. right. apply H_P2.\n    right. apply H_P3.\n  (* <- *)\n  intros [[H_P1 | H_P2] | H_P3].\n      left. apply H_P1.\n    right. left. apply H_P2.\n  right. right. apply H_P3.\nQed.\n\n(* ********** *)\n\n(* Exercise 2:\n   Prove that conjunction and disjunctions are commutative.\n*)\n\nLemma conjunction_is_commutative :\n  forall P Q : Prop,\n    P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [H_P H_Q].\n  split.\n    apply H_Q.\n  apply H_P.\nQed.\n\nLemma conjunction_is_commutative_either_way :\n  forall P Q : Prop,\n    P /\\ Q <-> Q /\\ P.\nProof.\n  intros P Q.\n  split.\n    apply (conjunction_is_commutative).\n  apply (conjunction_is_commutative).\nQed.\n\nLemma disjunction_is_commutative :\n  forall P Q : Prop,\n    P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q [H_P | H_Q].\n    right. apply H_P.\n  left. apply H_Q.\nQed.\n\nLemma disjunction_is_commutative_either_way :\n  forall P Q : Prop,\n    P \\/ Q <-> Q \\/ P.\nProof.\n  intros P Q.\n  split.\n    apply (disjunction_is_commutative).\n  apply (disjunction_is_commutative).\nQed.\n\n(* ********** *)\n\n(* Exercise 3:\n   Prove the following lemma, Curry_and_unCurry.\n*)\n\nLemma Curry_and_unCurry :\n  forall P Q R : Prop,\n    (P /\\ Q -> R) <-> P -> Q -> R.\nProof.\n  intros P Q R.\n  split.\n    intros H_P_con_Q_imp_R H_P H_Q.\n    apply H_P_con_Q_imp_R.\n    split.\n      apply H_P.\n    apply H_Q.\n  intros H_P_imp_Q_imp_R [H_P H_Q].\n  apply H_P_imp_Q_imp_R.\n    apply H_P.\n  apply H_Q.\nQed.\n\n(* ********** *)\n\n(* Here is how to import a Coq library about arithmetic expressions: *)\n\nRequire Import Arith.\n\nCheck plus_comm.\n\n(*\nplus_comm\n     : forall n m : nat, n + m = m + n\n*)\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).\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  Restart.\n\n  intros a b c.\n  rewrite -> (plus_comm c (b + a)).\n  rewrite -> (plus_comm b a).\n  reflexivity.\n\n  Restart.\n\n  intros a b c.\n  rewrite <- (plus_comm (b + a) c).\n  rewrite <- (plus_comm a b).\n  reflexivity.\n\n  Restart.\n\n  intros a b c.\n  rewrite <- (plus_comm a b).\n  rewrite <- (plus_comm (a + b) c).\n  reflexivity.\n\n  Restart.\n\n  intros a b c.\n  rewrite -> (plus_comm a b).\n  rewrite <- (plus_comm (b + a) c).\n  reflexivity.\n\n(* Qed. *)\n\n(* Exercise 4:\n   Add a couple more proofs for Lemma comm_a.\n\n   For the over-achievers:\n   How many distinct proofs are there for Lemma comm_a?\n*)\n  Restart.\n  \n  intros a b c.\n  rewrite -> (plus_comm (a + b) c).\n  rewrite -> (plus_comm b a).\n  reflexivity.\n\n  Restart.\n\n  intros a b c.\n  rewrite <- (plus_comm b a).\n  rewrite <- (plus_comm (b + a) c).\n  reflexivity.\n\nQed.\n\n(* ********** *)\n\nLemma comm_b :\n  forall x y z : nat,\n    (x + y) + z = z + (y + x).\nProof.\n  intros x y z.\n  apply (comm_a x y z).\n\n  Restart.\n\n  apply comm_a.\nQed.\n\n(* ********** *)\n\n(* symmetry *)\n\nLemma comm_c :\n  forall a b c : nat,\n    c + (b + a) = (a + b) + c.\nProof.\n  intros a b c.\n  symmetry.\n  apply (comm_a a b c).\nQed.\n\n(* ********** *)\n\nCheck plus_assoc.\n\n(*\nplus_assoc\n     : forall n m p : nat, n + (m + p) = n + m + p\n*)\n\n(* Exercise 5, for the over-achievers:\n   find a couple of alternative proofs for the following lemma.\n*)\n\nLemma assoc_a :\n  forall a b c d : nat,\n    a + (b + (c + d)) = ((a + b) + c) + d.\nProof.\n  intros a b c d.\n  rewrite -> (plus_assoc a b (c + d)).\n  rewrite <- (plus_assoc (a + b) c d).\n  reflexivity.\n\n  Restart.\n\n  intros a b c d.\n  rewrite -> (plus_assoc a b (c + d)).\n  rewrite -> (plus_assoc (a + b) c d).\n  reflexivity.\n\n  Restart.\n\n  intros a b c d.\n  rewrite <- (plus_assoc (a + b) c d).\n  rewrite <- (plus_assoc a b (c + d)).\n  reflexivity.\n\nQed.\n(* You should replace \"Abort.\" by a proof, if there is one. *)\n\n(* ********** *)\n\n(* Exercise 6:\n   Prove the following lemma, mixed_a.\n*)\n\nLemma mixed_a :\nforall a b c d : nat,\n    (c + (a + b)) + d = (b + (d + c)) + a.\nProof.\n  intros a b c d.\n  rewrite -> (plus_comm c (a + b)).\n  rewrite -> (plus_comm d c).\n  rewrite -> (plus_comm (b + (c + d)) a).\n  symmetry. apply assoc_a.\nQed.\n\n(* ********** *)\n\n(* end of week_35_exercises.v *)\n", "meta": {"author": "blacksails", "repo": "dIFP", "sha": "9d3e5f2838674f4fae670668c8a249f11eba0fac", "save_path": "github-repos/coq/blacksails-dIFP", "path": "github-repos/coq/blacksails-dIFP/dIFP-9d3e5f2838674f4fae670668c8a249f11eba0fac/w35/week_35_Nørgaard_Benjamin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.6768366414783258}}
{"text": "Require Coq.setoid_ring.Ncring.\nRequire Coq.setoid_ring.Cring.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.micromega.Lia.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.OnSubterms.\nRequire Import Crypto.Util.Tactics.Revert.\nRequire Import Crypto.Util.Tactics.RewriteHyp.\nRequire Import Crypto.Algebra.Hierarchy Crypto.Algebra.Group Crypto.Algebra.Monoid.\nRequire Coq.ZArith.ZArith Coq.PArith.PArith.\n\n\nSection Ring.\n  Context {T eq zero one opp add sub mul} `{@ring T eq zero one opp add sub mul}.\n  Local Infix \"=\" := eq : type_scope. Local Notation \"a <> b\" := (not (a = b)) : type_scope.\n  Local Notation \"0\" := zero. Local Notation \"1\" := one.\n  Local Infix \"+\" := add. Local Infix \"-\" := sub. Local Infix \"*\" := mul.\n\n  Lemma mul_0_l : forall x, 0 * x = 0.\n  Proof using Type*.\n    intros x.\n    assert (0*x = 0*x) as Hx by reflexivity.\n    rewrite <-(right_identity 0), right_distributive in Hx at 1.\n    assert (0*x + 0*x - 0*x = 0*x - 0*x) as Hxx by (rewrite Hx; reflexivity).\n    rewrite !ring_sub_definition, <-associative, right_inverse, right_identity in Hxx; exact Hxx.\n  Qed.\n\n  Lemma mul_0_r : forall x, x * 0 = 0.\n  Proof using Type*.\n    intros x.\n    assert (x*0 = x*0) as Hx by reflexivity.\n    rewrite <-(left_identity 0), left_distributive in Hx at 1.\n    assert (opp (x*0) + (x*0 + x*0)  = opp (x*0) + x*0) as Hxx by (rewrite Hx; reflexivity).\n    rewrite associative, left_inverse, left_identity in Hxx; exact Hxx.\n  Qed.\n\n  Lemma sub_0_l x : 0 - x = opp x.\n  Proof using Type*. rewrite ring_sub_definition. rewrite left_identity. reflexivity. Qed.\n\n  Lemma mul_opp_r x y : x * opp y = opp (x * y).\n  Proof using Type*.\n    assert (Ho:x*(opp y) + x*y = 0)\n      by (rewrite <-left_distributive, left_inverse, mul_0_r; reflexivity).\n    rewrite <-(left_identity (opp (x*y))), <-Ho; clear Ho.\n    rewrite <-!associative, right_inverse, right_identity; reflexivity.\n  Qed.\n\n  Lemma mul_opp_l x y : opp x * y = opp (x * y).\n  Proof using Type*.\n    assert (Ho:opp x*y + x*y = 0)\n      by (rewrite <-right_distributive, left_inverse, mul_0_l; reflexivity).\n    rewrite <-(left_identity (opp (x*y))), <-Ho; clear Ho.\n    rewrite <-!associative, right_inverse, right_identity; reflexivity.\n  Qed.\n\n  Definition opp_zero_iff : forall x, opp x = 0 <-> x = 0 := Group.inv_id_iff.\n\n  Global Instance is_left_distributive_sub : is_left_distributive (eq:=eq)(add:=sub)(mul:=mul).\n  Proof using Type*.\n    split; intros. rewrite !ring_sub_definition, left_distributive.\n    eapply Group.cancel_left, mul_opp_r.\n  Qed.\n\n  Global Instance is_right_distributive_sub : is_right_distributive (eq:=eq)(add:=sub)(mul:=mul).\n  Proof using Type*.\n    split; intros. rewrite !ring_sub_definition, right_distributive.\n    eapply Group.cancel_left, mul_opp_l.\n  Qed.\n\n  Lemma sub_zero_iff x y : x - y = 0 <-> x = y.\n  Proof using Type*.\n    split; intro E.\n    { rewrite <-(right_identity y), <- E, ring_sub_definition.\n      rewrite commutative, <-associative, commutative.\n      rewrite left_inverse, left_identity. reflexivity. }\n    { rewrite E, ring_sub_definition, right_inverse; reflexivity. }\n  Qed.\n\n  Lemma neq_sub_neq_zero x y (Hxy:x<>y) : x-y <> 0.\n  Proof using Type*.\n    intro Hsub. apply Hxy. rewrite <-(left_identity y), <-Hsub, ring_sub_definition.\n    rewrite <-associative, left_inverse, right_identity. reflexivity.\n  Qed.\n\n  Lemma zero_product_iff_zero_factor {Hzpzf:@is_zero_product_zero_factor T eq zero mul} :\n    forall x y : T, eq (mul x y) zero <-> eq x zero \\/ eq y zero.\n  Proof using Type*.\n    split; eauto using zero_product_zero_factor; [].\n    intros [Hz|Hz]; rewrite Hz; eauto using mul_0_l, mul_0_r.\n  Qed.\n\n  Lemma nonzero_product_iff_nonzero_factor {Hzpzf:@is_zero_product_zero_factor T eq zero mul} :\n    forall x y : T, not (eq (mul x y) zero) <-> (not (eq x zero) /\\ not (eq y zero)).\n  Proof using Type*. intros; rewrite zero_product_iff_zero_factor; tauto. Qed.\n\n  Global Instance Ncring_Ring_ops : @Ncring.Ring_ops T zero one add mul sub opp eq := {}.\n  Global Instance Ncring_Ring : @Ncring.Ring T zero one add mul sub opp eq Ncring_Ring_ops.\n  Proof using Type*.\n    split; exact _ || cbv; intros; eauto using left_identity, right_identity, commutative, associative, right_inverse, left_distributive, right_distributive, ring_sub_definition with core typeclass_instances.\n    - (* TODO: why does [eauto using @left_identity with typeclass_instances] not work? *)\n      eapply @left_identity; eauto with typeclass_instances.\n    - eapply @right_identity; eauto with typeclass_instances.\n    - eapply associative.\n    - intros; eapply right_distributive.\n    - intros; eapply left_distributive.\n  Qed.\nEnd Ring.\n\nSection Homomorphism.\n  Context {R EQ ZERO ONE OPP ADD SUB MUL} `{@ring R EQ ZERO ONE OPP ADD SUB MUL}.\n  Context {S eq zero one opp add sub mul} `{@ring S eq zero one opp add sub mul}.\n  Context {phi:R->S}.\n  Local Infix \"=\" := eq. Local Infix \"=\" := eq : type_scope.\n\n  Class is_homomorphism :=\n    {\n      homomorphism_is_homomorphism : Monoid.is_homomorphism (phi:=phi) (OP:=ADD) (op:=add) (EQ:=EQ) (eq:=eq);\n      homomorphism_mul : forall x y, phi (MUL x y) = mul (phi x) (phi y);\n      homomorphism_one : phi ONE = one\n    }.\n  Global Existing Instance homomorphism_is_homomorphism.\n\n  Context `{phi_homom:is_homomorphism}.\n\n  Lemma homomorphism_zero : phi ZERO = zero.\n  Proof using Type*. apply Group.homomorphism_id. Qed.\n\n  Lemma homomorphism_add : forall x y,  phi (ADD x y) = add (phi x) (phi y).\n  Proof using phi_homom. apply Monoid.homomorphism. Qed.\n\n  Definition homomorphism_opp : forall x,  phi (OPP x) = opp (phi x) :=\n    (Group.homomorphism_inv (INV:=OPP) (inv:=opp)).\n\n  Lemma homomorphism_sub : forall x y, phi (SUB x y) = sub (phi x) (phi y).\n  Proof using Type*.\n    intros.\n    rewrite !ring_sub_definition, Monoid.homomorphism, homomorphism_opp. reflexivity.\n  Qed.\n\n  Global Instance monoid_homomorphism_mul :\n    Monoid.is_homomorphism (phi:=phi) (OP:=MUL) (op:=mul) (EQ:=EQ) (eq:=eq).\n  Proof using phi_homom. split; destruct phi_homom; assumption || exact _. Qed.\nEnd Homomorphism.\n\n(* TODO: file a Coq bug for rewrite_strat -- it should accept ltac variables *)\nLtac push_homomorphism phi :=\n  let H := constr:(_ : @is_homomorphism _ _ _ _ _ _ _ _ _ _ phi) in\n  pose proof (@homomorphism_zero _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H)\n    as _push_homomrphism_0;\n  pose proof (@homomorphism_one _ _ _ _ _ _ _ _ _ _ _ H)\n    as _push_homomrphism_1;\n  pose proof (@homomorphism_add _ _ _ _ _ _ _ _ _ _ _ H)\n    as _push_homomrphism_p;\n  pose proof (@homomorphism_opp _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H)\n    as _push_homomrphism_o;\n  pose proof (@homomorphism_sub _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H)\n    as _push_homomrphism_s;\n  pose proof (@homomorphism_mul _ _ _ _ _ _ _ _ _ _ _ H)\n    as _push_homomrphism_m;\n  (rewrite_strat bottomup (terms _push_homomrphism_0 _push_homomrphism_1 _push_homomrphism_p _push_homomrphism_o _push_homomrphism_s _push_homomrphism_m));\n  clear _push_homomrphism_0 _push_homomrphism_1 _push_homomrphism_p _push_homomrphism_o _push_homomrphism_s _push_homomrphism_m.\n\nLtac pull_homomorphism phi :=\n  let H := constr:(_ : @is_homomorphism _ _ _ _ _ _ _ _ _ _ phi) in\n  pose proof (@homomorphism_zero _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H)\n    as _pull_homomrphism_0;\n  pose proof (@homomorphism_one _ _ _ _ _ _ _ _ _ _ _ H)\n    as _pull_homomrphism_1;\n  pose proof (@homomorphism_add _ _ _ _ _ _ _ _ _ _ _ H)\n    as _pull_homomrphism_p;\n  pose proof (@homomorphism_opp _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H)\n    as _pull_homomrphism_o;\n  pose proof (@homomorphism_sub _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H)\n    as _pull_homomrphism_s;\n  pose proof (@homomorphism_mul _ _ _ _ _ _ _ _ _ _ _ H)\n    as _pull_homomrphism_m;\n  symmetry in _pull_homomrphism_0;\n  symmetry in _pull_homomrphism_1;\n  symmetry in _pull_homomrphism_p;\n  symmetry in _pull_homomrphism_o;\n  symmetry in _pull_homomrphism_s;\n  symmetry in _pull_homomrphism_m;\n  (rewrite_strat bottomup (terms _pull_homomrphism_0 _pull_homomrphism_1 _pull_homomrphism_p _pull_homomrphism_o _pull_homomrphism_s _pull_homomrphism_m));\n  clear _pull_homomrphism_0 _pull_homomrphism_1 _pull_homomrphism_p _pull_homomrphism_o _pull_homomrphism_s _pull_homomrphism_m.\n\n\nSection Isomorphism.\n  Context {F EQ ZERO ONE OPP ADD SUB MUL} {ringF:@ring F EQ ZERO ONE OPP ADD SUB MUL}.\n  Context {H} {eq : H -> H -> Prop} {zero one : H} {opp : H -> H} {add sub mul : H -> H -> H} {inv : H -> H} {div : H -> H -> H}.\n  Context {phi:F->H} {phi':H->F}.\n  Local Infix \"=\" := EQ. Local Infix \"=\" := EQ : type_scope.\n  Context (phi'_phi_id : forall A, phi' (phi A) = A)\n          (phi'_eq : forall a b, EQ (phi' a) (phi' b) <-> eq a b)\n          {phi'_zero : phi' zero = ZERO}\n          {phi'_one : phi' one = ONE}\n          {phi'_opp : forall a, phi' (opp a) = OPP (phi' a)}\n          (phi'_add : forall a b, phi' (add a b) = ADD (phi' a) (phi' b))\n          (phi'_sub : forall a b, phi' (sub a b) = SUB (phi' a) (phi' b))\n          (phi'_mul : forall a b, phi' (mul a b) = MUL (phi' a) (phi' b)).\n\n  Lemma ring_by_isomorphism\n    : @ring H eq zero one opp add sub mul\n      /\\ @is_homomorphism F EQ ONE ADD MUL H eq one add mul phi\n      /\\ @is_homomorphism H eq one add mul F EQ ONE ADD MUL phi'.\n  Proof using phi'_add phi'_eq phi'_mul phi'_one phi'_opp phi'_phi_id phi'_sub phi'_zero ringF.\n    repeat match goal with\n           | [ H : field |- _ ] => destruct H; try clear H\n           | [ H : commutative_ring |- _ ] => destruct H; try clear H\n           | [ H : ring |- _ ] => destruct H; try clear H\n           | [ H : commutative_group |- _ ] => destruct H; try clear H\n           | [ H : group |- _ ] => destruct H; try clear H\n           | [ H : monoid |- _ ] => destruct H; try clear H\n           | [ H : is_commutative |- _ ] => destruct H; try clear H\n           | [ H : is_left_distributive |- _ ] => destruct H; try clear H\n           | [ H : is_right_distributive |- _ ] => destruct H; try clear H\n           | [ H : is_zero_neq_one |- _ ] => destruct H; try clear H\n           | [ H : is_associative |- _ ] => destruct H; try clear H\n           | [ H : is_left_identity |- _ ] => destruct H; try clear H\n           | [ H : is_right_identity |- _ ] => destruct H; try clear H\n           | [ H : Equivalence _ |- _ ] => destruct H; try clear H\n           | [ H : is_left_inverse |- _ ] => destruct H; try clear H\n           | [ H : is_right_inverse |- _ ] => destruct H; try clear H\n           | _ => intro\n           | _ => split\n           | [ H : eq _ _ |- _ ] => apply phi'_eq in H\n           | [ |- eq _ _ ] => apply phi'_eq\n           | [ H : (~eq _ _)%type |- _ ] => pose proof (fun pf => H (proj1 (@phi'_eq _ _) pf)); clear H\n           | [ H : EQ _ _ |- _ ] => rewrite H\n           | _ => progress erewrite ?phi'_zero, ?phi'_one, ?phi'_opp, ?phi'_add, ?phi'_sub, ?phi'_mul, ?phi'_phi_id by reflexivity\n           | [ H : _ |- _ ] => progress erewrite ?phi'_zero, ?phi'_one, ?phi'_opp, ?phi'_add, ?phi'_sub, ?phi'_mul, ?phi'_phi_id in H by reflexivity\n           | _ => solve [ eauto ]\n           end.\n  Qed.\nEnd Isomorphism.\n\nSection TacticSupportCommutative.\n  Context {T eq zero one opp add sub mul} `{@commutative_ring T eq zero one opp add sub mul}.\n\n  Global Instance Cring_Cring_commutative_ring :\n    @Cring.Cring T zero one add mul sub opp eq Ncring_Ring_ops Ncring_Ring.\n  Proof using Type. unfold Cring.Cring; intros; cbv. eapply commutative. Qed.\n\n  Lemma ring_theory_for_stdlib_tactic : Ring_theory.ring_theory zero one add mul sub opp eq.\n  Proof using Type*.\n    constructor; intros. (* TODO(automation): make [auto] do this? *)\n    - apply left_identity.\n    - apply commutative.\n    - apply associative.\n    - apply left_identity.\n    - apply commutative.\n    - apply associative.\n    - apply right_distributive.\n    - apply ring_sub_definition.\n    - apply right_inverse.\n  Qed.\nEnd TacticSupportCommutative.\n\nSection Z.\n  Import ZArith.\n  Global Instance ring_Z : @ring Z Logic.eq 0%Z 1%Z Z.opp Z.add Z.sub Z.mul.\n  Proof. repeat split; auto using Z.eq_dec with zarith typeclass_instances. Qed.\n\n  Global Instance commutative_ring_Z : @commutative_ring Z Logic.eq 0%Z 1%Z Z.opp Z.add Z.sub Z.mul.\n  Proof. eauto using @commutative_ring, @is_commutative, ring_Z with zarith. Qed.\n\n  Global Instance integral_domain_Z : @integral_domain Z Logic.eq 0%Z 1%Z Z.opp Z.add Z.sub Z.mul.\n  Proof.\n    split.\n    { apply commutative_ring_Z. }\n    { split. intros. eapply Z.eq_mul_0; assumption. }\n    { split. discriminate. }\n  Qed.\nEnd Z.\n\nSection of_Z.\n  Import ZArith PArith. Local Open Scope Z_scope.\n  Context {R Req Rzero Rone Ropp Radd Rsub Rmul}\n          {Rring : @ring R Req Rzero Rone Ropp Radd Rsub Rmul}.\n  Local Infix \"=\" := Req. Local Infix \"=\" := Req : type_scope.\n\n  Fixpoint of_nat (n:nat) : R :=\n    match n with\n    | O => Rzero\n    | S n' => Radd (of_nat n') Rone\n    end.\n  Definition of_Z (x:Z) : R :=\n    match x with\n    | Z0 => Rzero\n    | Zpos p => of_nat (Pos.to_nat p)\n    | Zneg p => Ropp (of_nat (Pos.to_nat p))\n    end.\n\n  Lemma of_Z_0 : of_Z 0 = Rzero.\n  Proof using Type*. reflexivity. Qed.\n\n  Lemma of_nat_add x :\n    of_nat (Nat.add x 1) = Radd (of_nat x) Rone.\n  Proof using Type*. destruct x; rewrite ?Nat.add_1_r; reflexivity. Qed.\n\n  Lemma of_nat_sub x (H: (0 < x)%nat):\n    of_nat (Nat.sub x 1) = Rsub (of_nat x) Rone.\n  Proof using Type*.\n    induction x; [lia|simpl].\n    rewrite <-of_nat_add.\n    rewrite Nat.sub_0_r, Nat.add_1_r.\n    simpl of_nat.\n    rewrite ring_sub_definition, <-associative.\n    rewrite right_inverse, right_identity.\n    reflexivity.\n  Qed.\n\n  Lemma of_Z_add_1_r :\n    forall x, of_Z (Z.add x 1) = Radd (of_Z x) Rone.\n  Proof using Type*.\n    destruct x; [reflexivity| | ]; simpl of_Z.\n    { rewrite Pos2Nat.inj_add, of_nat_add.\n      reflexivity. }\n    { rewrite Z.pos_sub_spec; break_match;\n        match goal with\n        | H : _ |- _ => rewrite Pos.compare_eq_iff in H\n        | H : _ |- _ => rewrite Pos.compare_lt_iff in H\n        | H : _ |- _ => rewrite Pos.compare_gt_iff in H;\n                          apply Pos.nlt_1_r in H; tauto\n        end;\n        subst; simpl of_Z; simpl of_nat.\n      { rewrite left_identity, left_inverse; reflexivity. }\n      { rewrite Pos2Nat.inj_sub by assumption.\n        rewrite of_nat_sub by apply Pos2Nat.is_pos.\n        rewrite ring_sub_definition, Group.inv_op, Group.inv_inv.\n        rewrite commutative; reflexivity. } }\n  Qed.\n\n  Lemma of_Z_sub_1_r :\n    forall x, of_Z (Z.sub x 1) = Rsub (of_Z x) Rone.\n  Proof using Type*.\n    induction x as [|p|].\n    { simpl; rewrite ring_sub_definition, !left_identity;\n        reflexivity. }\n    { case_eq (1 ?= p)%positive; intros;\n        match goal with\n        | H : _ |- _ => rewrite Pos.compare_eq_iff in H\n        | H : _ |- _ => rewrite Pos.compare_lt_iff in H\n        | H : _ |- _ => rewrite Pos.compare_gt_iff in H;\n                          apply Pos.nlt_1_r in H; tauto\n        end.\n      { subst. simpl; rewrite ring_sub_definition, !left_identity,\n                      right_inverse; reflexivity. }\n      { rewrite <-Pos2Z.inj_sub by assumption; simpl of_Z.\n        rewrite Pos2Nat.inj_sub by assumption.\n        rewrite of_nat_sub by apply Pos2Nat.is_pos.\n        reflexivity. } }\n    { simpl. rewrite Pos2Nat.inj_add, of_nat_add.\n      rewrite ring_sub_definition, Group.inv_op, commutative.\n      reflexivity. }\n  Qed.\n\n  Lemma of_Z_opp : forall a,\n      of_Z (Z.opp a) = Ropp (of_Z a).\n  Proof using Type*.\n    destruct a; simpl; rewrite ?Group.inv_id, ?Group.inv_inv;\n      reflexivity.\n  Qed.\n\n  Lemma of_Z_add : forall a b,\n      of_Z (Z.add a b) = Radd (of_Z a) (of_Z b).\n  Proof using Type*.\n    intros a b.\n    let x := match goal with |- ?x => x end in\n    let f := match (eval pattern b in x) with ?f _ => f end in\n    apply (Z.peano_ind f); intros.\n    { rewrite !right_identity. reflexivity. }\n    { match goal with\n      | [ |- context[?a + Z.succ ?x'] ]\n        => rename x' into x\n      end.\n      replace (a + Z.succ x) with ((a + x) + 1) by ring.\n      replace (Z.succ x) with (x+1) by ring.\n      rewrite !of_Z_add_1_r; rewrite_hyp *.\n      rewrite associative; reflexivity. }\n    { match goal with\n      | [ |- context[?a + Z.pred ?x'] ]\n        => rename x' into x\n      end.\n      replace (a + Z.pred x) with ((a+x)-1)\n        by (rewrite <-Z.sub_1_r; ring).\n      replace (Z.pred x) with (x-1) by apply Z.sub_1_r.\n      rewrite !of_Z_sub_1_r; rewrite_hyp *.\n      rewrite !ring_sub_definition.\n      rewrite associative; reflexivity. }\n  Qed.\n\n  Lemma of_Z_mul : forall a b,\n      of_Z (Z.mul a b) = Rmul (of_Z a) (of_Z b).\n  Proof using Type*.\n    intros a b.\n    let x := match goal with |- ?x => x end in\n    let f := match (eval pattern b in x) with ?f _ => f end in\n    apply (Z.peano_ind f); intros *; try intro IHb.\n    { rewrite !mul_0_r; reflexivity. }\n    { rewrite Z.mul_succ_r, <-Z.add_1_r.\n      rewrite of_Z_add, of_Z_add_1_r.\n      rewrite IHb.\n      rewrite left_distributive, right_identity.\n      reflexivity. }\n    { rewrite Z.mul_pred_r, <-Z.sub_1_r.\n      rewrite of_Z_sub_1_r.\n      rewrite <-Z.add_opp_r.\n      rewrite of_Z_add, of_Z_opp.\n      rewrite IHb.\n      rewrite ring_sub_definition, left_distributive.\n      rewrite mul_opp_r,right_identity.\n      reflexivity. }\n  Qed.\n\n\n  Global Instance homomorphism_of_Z :\n    @is_homomorphism\n      Z Logic.eq Z.one Z.add Z.mul\n      R Req  Rone  Radd  Rmul\n      of_Z.\n  Proof using Type*.\n    repeat constructor; intros.\n    { apply of_Z_add. }\n    { repeat intro; subst; reflexivity. }\n    { apply of_Z_mul. }\n    { simpl. rewrite left_identity; reflexivity. }\n  Qed.\nEnd of_Z.\n\nSection of_Z_absorbs_homomorphism.\n  Context {R Req Rzero Rone Ropp Radd Rsub Rmul}\n          {Rring : @ring R Req Rzero Rone Ropp Radd Rsub Rmul}.\n  Context {R' R'eq R'zero R'one R'opp R'add R'sub R'mul}\n          {R'ring : @ring R' R'eq R'zero R'one R'opp R'add R'sub R'mul}.\n  Context {phi}\n          {Hphi:@is_homomorphism R Req Rone Radd Rmul\n                                     R' R'eq R'one R'add R'mul phi}.\n\n  Local Notation R_of_nat := (@of_nat R Rzero Rone Radd) (only parsing).\n  Local Notation R'_of_nat := (@of_nat R' R'zero R'one R'add) (only parsing).\n  Local Notation R_of_Z := (@of_Z R Rzero Rone Ropp Radd) (only parsing).\n  Local Notation R'_of_Z := (@of_Z R' R'zero R'one R'opp R'add) (only parsing).\n\n  Lemma of_nat_absorbs_homomorphism x\n    : R'eq (phi (R_of_nat x)) (R'_of_nat x).\n  Proof.\n    induction x as [|x IHx]; cbn [of_nat];\n      repeat first [ rewrite homomorphism_zero\n                   | rewrite homomorphism_add\n                   | rewrite homomorphism_one\n                   | rewrite IHx\n                   | reflexivity ].\n  Qed.\n\n  Lemma of_Z_absorbs_homomorphism x\n    : R'eq (phi (R_of_Z x)) (R'_of_Z x).\n  Proof.\n    cbv [of_Z]; break_innermost_match;\n      repeat first [ rewrite homomorphism_zero\n                   | rewrite homomorphism_opp\n                   | rewrite of_nat_absorbs_homomorphism\n                   | reflexivity ].\n  Qed.\nEnd of_Z_absorbs_homomorphism.\n\nDefinition char_ge\n           {R eq zero one opp add} {sub:R->R->R} {mul:R->R->R}\n           C :=\n  @Hierarchy.char_ge R eq zero (fun p => (@of_Z R zero one opp add) (BinInt.Z.pos p)) C.\nExisting Class char_ge.\n\n(*** Tactics for ring equations *)\nRequire Export Coq.setoid_ring.Ring_tac.\nLtac ring_simplify_subterms := tac_on_subterms ltac:(fun t => ring_simplify t).\n\nLtac ring_simplify_subterms_in_all :=\n  reverse_nondep; ring_simplify_subterms; intros.\n\nCreate HintDb ring_simplify discriminated.\nCreate HintDb ring_simplify_subterms discriminated.\nCreate HintDb ring_simplify_subterms_in_all discriminated.\nGlobal Hint Extern 1 => progress ring_simplify : ring_simplify.\nGlobal Hint Extern 1 => progress ring_simplify_subterms : ring_simplify_subterms.\nGlobal Hint Extern 1 => progress ring_simplify_subterms_in_all : ring_simplify_subterms_in_all.\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/Algebra/Ring.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6767151474653288}}
{"text": "(* Basic Group Theory definitions. *)\n\nFrom CGT Require Import A1_setup B1_fmap B2_perm B3_word.\nRequire Import Lia.\n\n(***\n:: Groups ::\n\nThe Schreier-Sims algorithm describes groups, but we want to avoid proving more\nGroup Theory than strictly necessary. Instead of defining groups generically we\nrestrict ourselves to groups defined as words over a list of generators. It\nfollows from the properties of permutation composition that these words obey the\nusual group axioms: composition is associative, there is an identity element,\nand every permutation has an inverse.\n*)\nSection Groups.\n\n(* The generating set. *)\nVariable gen : list perm.\n\n(* A permutation can be composed from the generating set. *)\nDefinition Generates π := ∃w, w ⊆ gen /\\ π == compose' w.\n\n(* The number of distinct permutations that are generated. *)\nRecord Group_Order (ord : positive) := Group_Order_Witness {\n  enum : positive -> perm;\n  enum_surjective : ∀π, Generates π -> ∃i, i <= ord /\\ π == enum i;\n  enum_injective : ∀i j, i <= ord -> j <= ord -> enum i == enum j -> i = j;\n}.\n\n(***\nTheorems\n*)\n\nHypothesis perms : Forall Perm gen.\n\nTheorem generates_ident :\n  Generates ident.\nProof.\nexists []; easy.\nQed.\n\nTheorem generates_generator σ :\n  In σ gen -> Generates σ.\nProof.\nexists [σ]; split. auto with datatypes.\nintros i; simpl; rewrite apply_compose; easy.\nQed.\n\nTheorem generates_subst π τ :\n  τ == π -> Generates π -> Generates τ.\nProof.\nintros ? [w []]; exists w; split. easy.\netransitivity. apply H. easy.\nQed.\n\nTheorem generates_compose π τ :\n  Generates π -> Generates τ -> Generates (τ ∘ π).\nProof.\nintros [w []] [w' []]; exists (w ++ w'); split.\nauto with datatypes. rewrite fold_right_app.\nintros i; rewrite compose''_compose', ?apply_compose, <-H0, <-H2; easy.\nQed.\n\nTheorem generates_perm π :\n  Generates π -> Perm π.\nProof.\nintros [w []]; eapply perm_subst.\napply H0. clear H0; induction w; simpl.\napply perm_ident. apply incl_cons_inv in H as [].\napply perm_compose. auto. eapply Forall_forall with (P:=Perm).\napply perms. apply H.\nQed.\n\nTheorem generates_inv π :\n  Generates π -> Generates (inv π).\nProof.\nintros; destruct (perm_order π) as [n Hn].\napply generates_perm, H. destruct H as [w []].\nexists (concat (repeat w n)); split.\n- intros τ Hτ; apply in_concat in Hτ as [w' []].\n  apply repeat_spec in H1; subst; auto.\n- (* We must show that the inverse of π is unique. *)\nAdmitted.\n\nEnd Groups.\n\nTheorem generates_inclusion gen gen' π :\n  Forall (Generates gen) gen' -> Generates gen' π -> Generates gen π.\nProof.\nintros H [w []]. eapply generates_subst; [apply H1|clear H1].\ninduction w; simpl. apply generates_ident.\napply incl_cons_inv in H0 as []. apply generates_compose.\neapply Forall_forall; [apply H|apply H0]. apply IHw, H1.\nQed.\n\nTheorem unit_group_order :\n  Group_Order [] 1.\nProof.\nexists (λ _, ident); repeat split; intros. destruct H as [w []].\napply incl_l_nil in H; subst; simpl in H0. exists 1; easy. lia.\nDefined.\n", "meta": {"author": "bergwerf", "repo": "permutation_factors", "sha": "1a57a691fbaa607be6ae95cb399d1d9a92cee2fb", "save_path": "github-repos/coq/bergwerf-permutation_factors", "path": "github-repos/coq/bergwerf-permutation_factors/permutation_factors-1a57a691fbaa607be6ae95cb399d1d9a92cee2fb/v1/B4_group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.67671514036423}}
{"text": "(** * Poly: Polymorphism and Higher-Order Functions *)\n\n(* FINAL REMINDER: Please do not put solutions to the exercises in\n   publicly accessible places.  Thank you! *)\n\nRequire Export Lists.\n\n(* ###################################################### *)\n(** * Polymorphism *)\n\n(** In this chapter we continue our development of basic\n    concepts of functional programming.  The critical new ideas are\n    _polymorphism_ (abstracting functions over the types of the data\n    they manipulate) and _higher-order functions_ (treating functions\n    as data).  We begin with polymorphism.\n*)\n\n(* ###################################################### *)\n(** ** Polymorphic Lists *)\n\n(** For the last couple of chapters, we've been working just\n    with lists of numbers.  Obviously, interesting programs also need\n    to be able to manipulate lists with elements from other types --\n    lists of strings, lists of booleans, lists of lists, etc.  We\n    _could_ just define a new inductive datatype for each of these,\n    for example... *)\n\nInductive boollist : Type :=\n  | bool_nil : boollist\n  | bool_cons : bool -> boollist -> boollist.\n\n(** ... but this would quickly become tedious, partly because we\n    have to make up different constructor names for each datatype, but\n    mostly because we would also need to define new versions of all\n    our list manipulating functions ([length], [rev], etc.)  for each\n    new datatype definition. *)\n\n(** To avoid all this repetition, Coq supports _polymorphic_\n    inductive type definitions.  For example, here is a _polymorphic\n    list_ datatype. *)\n\nInductive list (X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\n(** This is exactly like the definition of [natlist] from the\n    previous chapter, except that the [nat] argument to the [cons]\n    constructor has been replaced by an arbitrary type [X], a binding\n    for [X] has been added to the header, and the occurrences of\n    [natlist] in the types of the constructors have been replaced by\n    [list X].  (We can re-use the constructor names [nil] and [cons]\n    because the earlier definition of [natlist] was inside of a\n    [Module] definition that is now out of scope.) *)\n\n(** What sort of thing is [list] itself?  One good way to think\n    about it is that [list] is a _function_ from [Type]s to\n    [Inductive] definitions; or, to put it another way, [list] is a\n    function from [Type]s to [Type]s.  For any particular type [X],\n    the type [list X] is an [Inductive]ly defined set of lists whose\n    elements are things of type [X]. *)\n\n(** With this definition, when we use the constructors [nil] and\n    [cons] to build lists, we need to tell Coq the type of the\n    elements in the lists we are building -- that is, [nil] and [cons]\n    are now _polymorphic constructors_.  Observe the types of these\n    constructors: *)\n\nCheck nil.\n(* ===> nil : forall X : Type, list X *)\nCheck cons.\n(* ===> cons : forall X : Type, X -> list X -> list X *)\n\n(** (Side note on notation: In .v files, the \"forall\" quantifier is\n    spelled out in letters.  In the generated HTML files, [forall] is\n    usually typeset as the usual mathematical \"upside down A,\" but\n    you'll see the spelled-out \"forall\" in a few places, as in the\n    above comments.  This is just a quirk of typesetting: there is no\n    difference in meaning.) *)\n\n(** The \"[forall X]\" in these types can be read as an additional\n    argument to the constructors that determines the expected types of\n    the arguments that follow.  When [nil] and [cons] are used, these\n    arguments are supplied in the same way as the others.  For\n    example, the list containing [2] and [1] is written like this: *)\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\n(** (We've written [nil] and [cons] explicitly here because we haven't\n    yet defined the [ [] ] and [::] notations for the new version of\n    lists.  We'll do that in a bit.) *)\n\n(** We can now go back and make polymorphic versions of all the\n    list-processing functions that we wrote before.  Here is [repeat],\n    for example: *)\n\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\n(** As with [nil] and [cons], we can use [repeat] by applying it\n    first to a type and then to its list argument: *)\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity.  Qed.\n\n(** To use [repeat] to build other kinds of lists, we simply\n    instantiate it with an appropriate type parameter: *)\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity.  Qed.\n\n\n\n\nModule MumbleGrumble.\n\n(** **** Exercise: 2 stars (mumble_grumble)  *)\n(** Consider the following two inductively defined types. *)\n\nInductive mumble : Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\n\nInductive grumble (X:Type) : Type :=\n  | d : mumble -> grumble X\n  | e : X -> grumble X.\n\n(** Which of the following are well-typed elements of [grumble X] for\n    some type [X]?\n      - [d (b a 5)]\n      - [d mumble (b a 5)]\n      - [d bool (b a 5)]\n      - [e bool true]\n      - [e mumble (b c 0)]\n      - [e bool (b c 0)]\n      - [c]\n(* FILL IN HERE *)\n*)\n(** [] *)\n\nEnd MumbleGrumble.\n\n\n(* ###################################################### *)\n(** *** Type Annotation Inference *)\n\n(** Let's write the definition of [repeat] again, but this time we\n    won't specify the types of any of the arguments. Will Coq still\n    accept it? *)\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0        => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\n(** Indeed it will.  Let's see what type Coq has assigned to [repeat']: *)\n\nCheck repeat'.\n(* ===> forall X : Type, X -> nat -> list X *)\nCheck repeat.\n(* ===> forall X : Type, X -> nat -> list X *)\n\n(** It has exactly the same type type as [repeat].  Coq was able\n    to use _type inference_ to deduce what the types of [X], [x], and\n    [count] must be, based on how they are used.  For example, since\n    [X] is used as an argument to [cons], it must be a [Type], since\n    [cons] expects a [Type] as its first argument; matching [count]\n    with [0] and [S] means it must be a [nat]; and so on.\n\n    This powerful facility means we don't always have to write\n    explicit type annotations everywhere, although explicit type\n    annotations are still quite useful as documentation and sanity\n    checks, so we will continue to use them most of the time.  You\n    should try to find a balance in your own code between too many\n    type annotations (which can clutter and distract) and too\n    few (which forces readers to perform type inference in their heads\n    in order to understand your code). *)\n\n(* ###################################################### *)\n(** *** Type Argument Synthesis *)\n\n(** To we use a polymorphic function, we need to pass it one or\n    more types in addition to its other arguments.  For example, the\n    recursive call in the body of the [repeat] function above must\n    pass along the type [X].  But since the second argument to\n    [repeat] is an element of [X], it seems entirely obvious that the\n    first argument can only be [X] -- why should we have to write it\n    explicitly?\n\n    Fortunately, Coq permits us to avoid this kind of redundancy.  In\n    place of any type argument we can write the \"implicit argument\"\n    [_], which can be read as \"Please try to figure out for yourself\n    what belongs here.\"  More precisely, when Coq encounters a [_], it\n    will attempt to _unify_ all locally available information -- the\n    type of the function being applied, the types of the other\n    arguments, and the type expected by the context in which the\n    application appears -- to determine what concrete type should\n    replace the [_].\n\n    This may sound similar to type annotation inference -- indeed, the\n    two procedures rely on the same underlying mechanisms.  Instead of\n    simply omitting the types of some arguments to a function, like\n      repeat' X x count : list X :=\n    we can also replace the types with [_]\n      repeat' (X : _) (x : _) (count : _) : list X :=\n    to tell Coq to attempt to infer the missing information.\n\n    Using implicit arguments, the [count] function can be written\n    like this: *)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n(** In this instance, we don't save much by writing [_] instead of\n    [X].  But in many cases the difference in both keystrokes and\n    readability is nontrivial.  For example, suppose we want to write\n    down a list containing the numbers [1], [2], and [3].  Instead of\n    writing this... *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...we can use argument synthesis to write this: *)\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ###################################################### *)\n(** *** Implicit Arguments *)\n\n(** We can go further and even avoid writing [_]'s in most cases by\n    telling Coq _always_ to infer the type argument(s) of a given\n    function.  The [Arguments] directive specifies the name of the\n    function (or constructor) and then lists its argument names, with\n    curly braces around any arguments to be treated as implicit.  (If\n    some arguments of a definition don't have a name, as is often the\n    case for constructors, they can be marked with a wildcard pattern\n    [_].) *)\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\n(** Now, we don't have to supply type arguments at all: *)\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\n(** Alternatively, we can declare an argument to be implicit\n    when defining the function itself, by surrounding it in curly\n    braces.  For example: *)\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0        => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n(** (Note that we didn't even have to provide a type argument to the\n    recursive call to [repeat''']; indeed, it would be invalid to\n    provide one!)\n\n    We will use the latter style whenever possible, but we will\n    continue to use use explicit [Argument] declarations for\n    [Inductive] constructors.  The reason for this is that marking the\n    parameter of an inductive type as implicit causes it to become\n    implicit for the type itself, not just for its constructors.  For\n    instance, consider the following alternative definition of the\n    [list] type: *)\n\nInductive list' {X:Type} : Type :=\n  | nil' : list'\n  | cons' : X -> list' -> list'.\n\n(** Because [X] is declared as implicit for the _entire_ inductive\n    definition including [list'] itself, we now have to write just\n    [list'] whether we are talking about lists of numbers or booleans\n    or anything else, rather than [list' nat] or [list' bool] or\n    whatever; this is a step too far. *)\n\n(** Let's finish by re-implementing a few other standard list\n    functions on our new polymorphic lists... *)\n\nFixpoint app {X : Type} (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity.  Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity.  Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity.  Qed.\n\n(** One small problem with declaring arguments [Implicit] is\n    that, occasionally, Coq does not have enough local information to\n    determine a type argument; in such cases, we need to tell Coq that\n    we want to give the argument explicitly just this time.  For\n    example, suppose we write this: *)\n\nFail Definition mynil := nil.\n\n(** (The [Fail] qualifier that appears before [Definition] can be\n    used with _any_ command, and is used to ensure that that command\n    indeed fails when executed. If the command does fail, Coq prints\n    the corresponding error message, but continues processing the rest\n    of the file.)\n\n    Here, Coq gives us an error because it doesn't know what type\n    argument to supply to [nil].  We can help it by providing an\n    explicit type declaration (so that Coq has more information\n    available when it gets to the \"application\" of [nil]): *)\n\nDefinition mynil : list nat := nil.\n\n(** Alternatively, we can force the implicit arguments to be explicit by\n   prefixing the function name with [@]. *)\n\nCheck @nil.\n\nDefinition mynil' := @nil nat.\n\n(** Using argument synthesis and implicit arguments, we can\n    define convenient notation for lists, as before.  Since we have\n    made the constructor type arguments implicit, Coq will know to\n    automatically infer these when we use the notations. *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** Now lists can be written just the way we'd hope: *)\n\nDefinition list123''' := [1; 2; 3].\n\n\n\n\n\n(* ###################################################### *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, optional (poly_exercises)  *)\n(** Here are a few simple exercises, just like ones in the [Lists]\n    chapter, for practice with polymorphism.  Complete the proofs below. *)\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  (* FILL IN HERE *) Admitted.\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(** [] *)\n\n(** **** Exercise: 2 stars, optional (more_poly_exercises)  *)\n(** Here are some slightly more interesting ones... *)\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Polymorphic Pairs *)\n\n(** Following the same pattern, the type definition we gave in\n    the last chapter for pairs of numbers can be generalized to\n    _polymorphic pairs_, often called _products_: *)\n\nInductive prod (X Y : Type) : Type :=\n| pair : X -> Y -> prod X Y.\n\nArguments pair {X} {Y} _ _.\n\n(** As with lists, we make the type arguments implicit and define the\n    familiar concrete notation. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** We can also use the [Notation] mechanism to define the standard\n    notation for product _types_: *)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** (The annotation [: type_scope] tells Coq that this abbreviation\n    should only be used when parsing types.  This avoids a clash with\n    the multiplication symbol.) *)\n\n(** It is easy at first to get [(x,y)] and [X*Y] confused.\n    Remember that [(x,y)] is a _value_ built from two other values,\n    while [X*Y] is a _type_ built from two other types.  If [x] has\n    type [X] and [y] has type [Y], then [(x,y)] has type [X*Y]. *)\n\n(** The first and second projection functions now look pretty\n    much as they would in any functional programming language. *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\n(** The following function takes two lists and combines them\n    into a list of pairs.  In other functional languages, it is often\n    called [zip]; we call it [combine] for consistency with Coq's\n    standard library. *)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\n(** **** Exercise: 1 star, optional (combine_checks)  *)\n(** Try answering the following questions on paper and\n    checking your answers in coq:\n    - What is the type of [combine] (i.e., what does [Check\n      @combine] print?)\n    - What does\n        Compute (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    languages, it is called [unzip].\n\n    Uncomment the material below and fill in the definition of\n    [split].  Make sure it passes the given unit test. *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) :=\n(* FILL IN HERE *) admit.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Polymorphic Options *)\n\n(** One last polymorphic type for now: _polymorphic options_,\n    which generalize [natoption] from the previous chapter: *)\n\nInductive option (X:Type) : Type :=\n  | Some : X -> option X\n  | None : option X.\n\nArguments Some {X} _.\nArguments None {X}.\n\n(** We can now rewrite the [nth_error] function so that it works\n    with any type of lists. *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity.  Qed.\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\nProof. reflexivity.  Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, optional (hd_error_poly)  *)\n(** Complete the definition of a polymorphic version of the\n    [hd_error] function from the last chapter. Be sure that it\n    passes the unit tests below. *)\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  (* FILL IN HERE *) admit.\n\n(** Once again, to force the implicit arguments to be explicit,\n    we can use [@] before the name of the function. *)\n\nCheck @hd_error.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\n (* FILL IN HERE *) Admitted.\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Functions as Data *)\n\n(** Like many other modern programming languages -- including\n    all functional languages (ML, Haskell, Scheme, Scala, Clojure,\n    etc.) -- Coq treats functions as first-class citizens, allowing\n    them to be passed as arguments to other functions, returned as\n    results, stored in data structures, etc.*)\n\n(* ###################################################### *)\n(** ** Higher-Order Functions *)\n\n(** Functions that manipulate other functions are often called\n    _higher-order_ functions.  Here's a simple one: *)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\n(** The argument [f] here is itself a function (from [X] to\n    [X]); the body of [doit3times] applies [f] three times to some\n    value [n]. *)\n\nCheck @doit3times.\n(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity.  Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity.  Qed.\n\n(* ###################################################### *)\n(** ** Filter *)\n\n(** Here is a more useful higher-order function, taking a list\n    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])\n    and \"filtering\" the list, returning a new list containing just\n    those elements for which the predicate returns [true]. *)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | []     => []\n  | h :: t => if test h then h :: (filter test t)\n                        else       filter test t\n  end.\n\n(** For example, if we apply [filter] to the predicate [evenb]\n    and a list of numbers [l], it returns a list containing just the\n    even members of [l]. *)\n\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity.  Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  beq_nat (length l) 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n\n(** We can use [filter] to give a concise version of the\n    [countoddmembers] function from the [Lists] chapter. *)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity.  Qed.\n\n(* ###################################################### *)\n(** ** Anonymous Functions *)\n\n(** It is arguably a little sad, in the example just above, to\n    be forced to define the function [length_is_1] and give it a name\n    just to be able to pass it as an argument to [filter], since we\n    will probably never use it again.  Moreover, this is not an\n    isolated example: when using higher-order functions, we often want\n    to pass as arguments \"one-off\" functions that we will never use\n    again; having to give each of these functions a name would be\n    tedious.\n\n    Fortunately, there is a better way.  We can construct a function\n    \"on the fly\" without declaring it at the top level or giving it a\n    name. *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity.  Qed.\n\n(** The expression [(fun n => n * n)] can be read as \"the function\n    that, given a number [n], yields [n * n].\" *)\n\n(** Here is the [filter] example, rewritten to use an anonymous\n    function. *)\n\nExample test_filter2':\n    filter (fun l => beq_nat (length l) 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 2 stars (filter_even_gt7)  *)\n(** Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  (* FILL IN HERE *) admit.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\n (* FILL IN HERE *) Admitted.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\n (* FILL IN HERE *) Admitted.\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}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X :=\n(* FILL IN HERE *) admit.\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\n(* FILL IN HERE *) Admitted.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Map *)\n\n(** Another handy higher-order function is called [map]. *)\n\nFixpoint map {X Y:Type} (f:X->Y) (l:list X) : (list Y) :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]\n    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has\n    been applied to each element of [l] in turn.  For example: *)\n\nExample test_map1: map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** The element types of the input and output lists need not be\n    the same, since [map] takes _two_ type arguments, [X] and [Y]; it\n    can thus be applied to a list of numbers and a function from\n    numbers to booleans to yield a list of booleans: *)\n\nExample test_map2:\n  map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity.  Qed.\n\n(** It can even be applied to a list of numbers and\n    a function from numbers to _lists_ of booleans to\n    yield a _list of lists_ of booleans: *)\n\nExample test_map3:\n    map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity.  Qed.\n\n\n\n(** *** Exercises *)\n\n(** **** Exercise: 3 stars (map_rev)  *)\n(** Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (flat_map)  *)\n(** The function [map] maps a [list X] to a [list Y] using a function\n    of type [X -> Y].  We can define a similar function, [flat_map],\n    which maps a [list X] to a [list Y] using a function [f] of type\n    [X -> list Y].  Your definition should work by 'flattening' the\n    results of [f], like so:\n        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  (* FILL IN HERE *) admit.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Lists are not the only inductive type that we can write a\n    [map] function for.  Here is the definition of [map] for the\n    [option] type: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\n(** **** Exercise: 2 stars, optional (implicit_args)  *)\n(** The definitions and uses of [filter] and [map] use implicit\n    arguments in many places.  Replace the curly braces around the\n    implicit arguments with parentheses, and then fill in explicit\n    type parameters where necessary and use Coq to check that you've\n    done so correctly.  (This exercise is not to be turned in; it is\n    probably easiest to do it on a _copy_ of this file that you can\n    throw away afterwards.)  [] *)\n\n(* ###################################################### *)\n(** ** Fold *)\n\n(** An even more powerful higher-order function is called\n    [fold].  This function is the inspiration for the \"[reduce]\"\n    operation that lies at the heart of Google's map/reduce\n    distributed programming framework. *)\n\nFixpoint fold {X Y:Type} (f: X->Y->Y) (l:list X) (b:Y)\n                         : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(** Intuitively, the behavior of the [fold] operation is to\n    insert a given binary operator [f] between every pair of elements\n    in a given list.  For example, [ fold plus [1;2;3;4] ] intuitively\n    means [1+2+3+4].  To make this precise, we also need a \"starting\n    element\" that serves as the initial second input to [f].  So, for\n    example,\n   fold plus [1;2;3;4] 0\n    yields\n   1 + (2 + (3 + (4 + 0))).\n    Some more examples:\n*)\n\nCheck (fold andb).\n(* ===> fold andb : list bool -> bool -> bool *)\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n\n(** **** Exercise: 1 star, advanced (fold_types_different)  *)\n(** Observe that the type of [fold] is parameterized by _two_ type\n    variables, [X] and [Y], and the parameter [f] is a binary operator\n    that takes an [X] and a [Y] and returns a [Y].  Can you think of a\n    situation where it would be useful for [X] and [Y] to be\n    different? *)\n\n(* ###################################################### *)\n(** ** Functions That Construct Functions *)\n\n(** Most of the higher-order functions we have talked about so\n    far take functions as arguments.  Let's look at some examples that\n    involve _returning_ functions as the results of other functions.\n    To begin, here is a function that takes a value [x] (drawn from\n    some type [X]) and returns a function from [nat] to [X] that\n    yields [x] whenever it is called, ignoring its [nat] argument. *)\n\nDefinition constfun {X: Type} (x: X) : nat->X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** In fact, the multiple-argument functions we have already\n    seen are also examples of passing functions as data.  To see why,\n    recall the type of [plus]. *)\n\nCheck plus.\n(* ==> nat -> nat -> nat *)\n\n(** Each [->] in this expression is actually a _binary_ operator\n    on types.  This operator is _right-associative_, so the type of\n    [plus] is really a shorthand for [nat -> (nat -> nat)] -- i.e., it\n    can be read as saying that \"[plus] is a one-argument function that\n    takes a [nat] and returns a one-argument function that takes\n    another [nat] and returns a [nat].\"  In the examples above, we\n    have always applied [plus] to both of its arguments at once, but\n    if we like we can supply just the first.  This is called _partial\n    application_. *)\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity.  Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity.  Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity.  Qed.\n\n(* ##################################################### *)\n(** * Additional Exercises *)\n\nModule Exercises.\n\n(** **** Exercise: 2 stars (fold_length)  *)\n(** Many common functions on lists can be implemented in terms of\n   [fold].  For example, here is an alternative definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length]. *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\n(* FILL IN HERE *) Admitted.\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(* FILL IN HERE *) admit.\n\n(** Write down a theorem [fold_map_correct] in Coq stating that\n   [fold_map] is correct, and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (currying)  *)\n(** In Coq, a function [f : A -> B -> C] really has the type [A\n    -> (B -> C)].  That is, if you give [f] a value of type [A], it\n    will give you function [f' : B -> C].  If you then give [f'] a\n    value of type [B], it will return a value of type [C].  This\n    allows for partial application, as in [plus3].  Processing a list\n    of arguments with functions that return functions is called\n    _currying_, in honor of the logician Haskell Curry.\n\n    Conversely, we can reinterpret the type [A -> B -> C] as [(A *\n    B) -> C].  This is called _uncurrying_.  With an uncurried binary\n    function, both arguments must be given at once as a pair; there is\n    no partial application. *)\n\n(** We can define currying as follows: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** As an exercise, define its inverse, [prod_uncurry].  Then prove\n    the theorems below to show that the two are inverses. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z :=\n  (* FILL IN HERE *) admit.\n\n(** Thought exercise: before running the following commands, can you\n    calculate the types of [prod_curry] and [prod_uncurry]? *)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (nth_error_informal)  *)\n(** Recall the definition of the [nth_error] function:\n   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n     match l with\n     | [] => None\n     | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\n     end.\n   Write an informal proof of the following theorem:\n   forall X n l, length l = n -> @nth_error X l n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (church_numerals)  *)\n(** This exercise explores an alternative way of defining natural\n    numbers, using the so-called _Church numerals_, named after\n    mathematician Alonzo Church.  We can represent a natural number\n    [n] as a function that takes a function [f] as a parameter and\n    returns [f] iterated [n] times. *)\n\nModule Church.\nDefinition nat := forall X : Type, (X -> X) -> X -> X.\n\n(** Let's see how to write some numbers with this notation. Iterating\n    a function once should be the same as just applying it. Thus, *)\n\nDefinition one : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** Similarly, [two] should apply [f] twice to its argument: *)\n\nDefinition two : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** Defining [zero] is somewhat trickier: how can we \"apply a function\n    zero times\"? The answer is actually simple: just return the\n    argument untouched. *)\n\nDefinition zero : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(** More generally, a number [n] can be written as [fun X f x => f (f\n    ... (f x) ...)], with [n] occurrences of [f].  Notice in\n    particular how the [doit3times] function we've defined previously\n    is actually just the Church representation of [3]. *)\n\nDefinition three : nat := @doit3times.\n\n(** Complete the definitions of the following functions. Make sure\n    that the corresponding unit tests pass by proving them with\n    [reflexivity]. *)\n\n(** Successor of a natural number: *)\n\nDefinition succ (n : nat) : nat :=\n  (* FILL IN HERE *) admit.\n\nExample succ_1 : succ zero = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample succ_2 : succ one = two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample succ_3 : succ two = three.\nProof. (* FILL IN HERE *) Admitted.\n\n(** Addition of two natural numbers: *)\n\nDefinition plus (n m : nat) : nat :=\n  (* FILL IN HERE *) admit.\n\nExample plus_1 : plus zero one = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample plus_2 : plus two three = plus three two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. (* FILL IN HERE *) Admitted.\n\n(** Multiplication: *)\n\nDefinition mult (n m : nat) : nat :=\n  (* FILL IN HERE *) admit.\n\nExample mult_1 : mult one one = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample mult_2 : mult zero (plus three three) = zero.\nProof. (* FILL IN HERE *) Admitted.\n\nExample mult_3 : mult two three = plus three three.\nProof. (* FILL IN HERE *) Admitted.\n\n(** Exponentiation: *)\n\n(** (_Hint_: Polymorphism plays a crucial role here.  However,\n    choosing the right type to iterate over can be tricky.  If you hit\n    a \"Universe inconsistency\" error, try iterating over a different\n    type: [nat] itself is usually problematic.) *)\n\nDefinition exp (n m : nat) : nat :=\n  (* FILL IN HERE *) admit.\n\nExample exp_1 : exp two two = plus two two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample exp_2 : exp three two = plus (mult two (mult two two)) one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample exp_3 : exp three zero = one.\nProof. (* FILL IN HERE *) Admitted.\n\nEnd Church.\n(** [] *)\n\nEnd Exercises.\n\n(** $Date: 2016-01-28 15:02:07 -0500 (Thu, 28 Jan 2016) $ *)\n", "meta": {"author": "lingxiao", "repo": "CIS500", "sha": "5b6e3a9cfe1ecaeaa9112b350022f3ca84924d4a", "save_path": "github-repos/coq/lingxiao-CIS500", "path": "github-repos/coq/lingxiao-CIS500/CIS500-5b6e3a9cfe1ecaeaa9112b350022f3ca84924d4a/hw5/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.870597273444551, "lm_q1q2_score": 0.6767151397875141}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Lia Eqdep_dec Bool.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac utils_list finite.\n\nFrom Undecidability.Shared.Libs.DLW.Vec \n  Require Import pos vec.\n\nFrom Undecidability.FOL.TRAKHTENBROT\n  Require Import notations decidable fol_ops membership hfs.\n\nSet Implicit Arguments.\n\n(* * Construction of the Hereditary Finite Sets model *)\n\nSection bt_model_n.\n\n  (*  This discussion briefly describes how we encode finite and discrete \n      model X with a decidable nt-ary relation R into an hereditary finite \n      set (hfs) with two elements l and r, l representing the points in X\n      and r representing the n-tuples in R.\n\n      Because X is finite and discrete, one can compute a bijection X <~> pos n\n      where n is the cardinal of X. Hence we assume that X = pos n and the\n      nt-art relation is R : vec (pos n) nt -> Prop\n      \n      1) We find a transitive hfs l such that (pos n) bijects with the elements\n         of l (transitive means ∀x, x∈l -> x⊆l). Hence\n\n                            pos n <-> { x | x ∈ l } \n\n         For this, we use the encoding of natural numbers into sets, \n         ie 0 := ø and 1+i := {i} U i and choose l to be the encoding \n         of n (the cardinal of X = pos n above).\n\n         Notice that since l is transitive then so is P(l) (powerset)\n         and hence P^i(l) for any i.\n    \n      2) forall x,y ∈ l, both {x} and {x,y} belong to P(l) \n         hence (x,y) = {{x},{x,y}} ∈ P(P(l))=P^2(l)\n        \n      3) l contains the empty set (cardinal > 0)\n  \n      4) Hence P^2nt(l) contains all nt-tuples build \n         from the elements of l by induction on n\n\n      5) So we can encode R as hfs r ∈ p := P^(2nt+1)(l) = P(P^2nt(l)) and\n         p serves as our model, ie \n\n                      Y := { x : hfs | x ∈b p } \n\n         where x ∈b p is the Boolean encoding of x ∈ p to ensure \n         uniqueness of witnesses/proofs.\n         \n      6) In the logic, we replace any \n      \n               R v by [v] ∈ r\n\n         encoded according to the above description.\n\n      *)\n\n  Variable (X : Type) (Xfin : finite_t X) (Xdiscr : discrete X) (x0 : X) (nt : nat).\n\n  Notation \"∅\" := hfs_empty.\n  Infix \"∈\" := hfs_mem.\n  Notation \"x ⊆ y\" := (forall u, u ∈ x -> u ∈ y).\n  Notation \"⟬ x , y ⟭\" := (hfs_opair x y).\n\n  (* First we compute a bijection with the cardinal of X *)\n\n  Section the_model.\n\n    Local Definition X_surj_hfs : { d : hfs & \n                     { f : hfs -> X & \n                     { g : X -> hfs |\n                        hfs_transitive d\n                     /\\ ∅ ∈ d\n                     /\\ (forall p, g p ∈ d)\n                     /\\ (forall x, x ∈ d -> exists p, x = g p)\n                     /\\ (forall p, f (g p) = p) \n                     }}}.\n    Proof using x0 Xfin Xdiscr.\n      destruct (finite_t_discrete_bij_t_pos Xfin)\n        as ([ | n ] & Hn); auto.\n      1: { exfalso; destruct Hn as (f & g & H1 & H2).\n           generalize (f x0); intro p; invert pos p. }\n      destruct Hn as (f & g & H1 & H2).\n      destruct (hfs_pos_n_transitive n) \n        as (l & g' & f' & G1 & G0 & G2 & G3 & G4).\n      exists l, (fun x => g (g' x)), (fun x => f' (f x)); msplit 4; auto.\n      + intros x Hx.\n        destruct (G3 x Hx) as (p & Hp).\n        exists (g p); rewrite H2; auto.\n      + intros p; rewrite G4; auto.\n    Qed.\n\n    (* First a surjective map from some transitive set d to X *)\n\n    Local Definition d := projT1 X_surj_hfs.\n    Local Definition s := projT1 (projT2 X_surj_hfs).\n    Local Definition i := proj1_sig (projT2 (projT2 (X_surj_hfs))).\n\n    Let Hd : hfs_transitive d.       Proof. apply (proj2_sig (projT2 (projT2 (X_surj_hfs)))). Qed.\n    Let Hempty : ∅ ∈ d.              Proof. apply (proj2_sig (projT2 (projT2 (X_surj_hfs)))). Qed.\n\n    Local Fact Hs : forall x, s (i x) = x.  \n    Proof. apply (proj2_sig (projT2 (projT2 (X_surj_hfs)))). Qed.\n\n    Local Fact Hi : forall x, i x ∈ d.\n    Proof. apply (proj2_sig (projT2 (projT2 (X_surj_hfs)))). Qed.\n\n    Local Fact Hi' : forall s, s ∈ d -> exists x, s = i x.\n    Proof. apply (proj2_sig (projT2 (projT2 (X_surj_hfs)))). Qed.\n\n    (* Now we build P^(1+2nt) d that contains all the sets of nt-tuples of d *)\n\n    Local Definition p := iter hfs_pow d (1+(2*nt)).\n\n    Local Fact Hp1 : hfs_transitive p.\n    Proof. apply hfs_iter_pow_trans; auto. Qed.\n\n    Local Fact Hp2 : d ∈ p.\n    Proof.\n      apply hfs_iter_pow_le with (n := 1); simpl; auto; try lia.\n      apply hfs_pow_spec; auto.\n    Qed.\n\n    Local Fact Hp5 n v : (forall p, vec_pos v p ∈ d) -> @hfs_tuple n v ∈ iter hfs_pow d (2*n).\n    Proof. apply hfs_tuple_pow; auto. Qed.\n\n    Local Fact Hp6 n v : n <= nt -> (forall p, vec_pos v p ∈ d) -> @hfs_tuple n v ∈ p.\n    Proof. \n      intros L H; apply Hp5 in H.\n      revert H; apply hfs_iter_pow_le; try lia; auto.\n    Qed.\n\n  End the_model.\n\n  Variable (R : vec X nt -> Prop).\n  Hypothesis HR : forall v, { R v } + { ~ R v }.\n\n  Hint Resolve finite_t_prod hfs_mem_fin_t : core.\n  Hint Resolve Hp1 Hp2 Hp5 Hp6 Hs Hi Hi' : core.\n\n  Section the_relation.\n\n    (* We encode R as a subset of tuples of elements of d in p *)\n\n    Let encode_R : { r | r ∈ p \n                      /\\ (forall v, @hfs_tuple nt v ∈ r -> forall q, vec_pos v q ∈ d)\n                      /\\ forall v, R v <-> hfs_tuple (vec_map i v) ∈ r }.\n    Proof.\n      set (P v := R (vec_map s v) /\\ forall q, vec_pos v q ∈ d).\n      set (f := @hfs_tuple nt).\n      destruct hfs_comprehension with (P := P) (f := f) as (r & Hr).\n      + apply fin_t_dec.\n        * intros; apply HR.\n        * apply fin_t_vec with (P := fun t => t ∈ d).\n          apply hfs_mem_fin_t.\n      + exists r; msplit 2.\n        * unfold p; rewrite Nat.add_comm, iter_plus with (b := 1).\n          apply hfs_pow_spec; intros x; rewrite Hr.\n          intros (v & H1 & <-).\n          apply Hp5, H1.\n        * unfold f; intros v.\n          rewrite Hr.\n          intros (w & H1 & H2).\n          apply hfs_tuple_spec in H2; subst w.\n          apply H1.\n        * intros v.\n          rewrite Hr.\n          split.\n          - exists (vec_map i v); split; auto.\n            split; auto.\n            ++ rewrite vec_map_map.\n               revert H; apply fol_equiv_ext.\n               f_equal; apply vec_pos_ext; intro; rew vec.\n            ++ intro; rew vec.\n          - intros (w & (H1 & _) & H2).\n            apply hfs_tuple_spec in H2.\n            revert H1; subst w; apply fol_equiv_ext.\n            f_equal; apply vec_pos_ext; intro; rew vec.\n    Qed.\n\n    Local Definition r := proj1_sig encode_R.\n  \n    Local Fact Hr1 : r ∈ p.\n    Proof. apply (proj2_sig encode_R). Qed.\n\n    Local Fact Hr2 v : @hfs_tuple nt v ∈ r -> forall q, vec_pos v q ∈ d.\n    Proof. apply (proj2_sig encode_R). Qed.\n\n    Local Fact Hr3 v : R v <-> hfs_tuple (vec_map i v) ∈ r.\n    Proof. apply (proj2_sig encode_R). Qed.\n\n  End the_relation.\n\n  Hint Resolve Hr1 Hr2 Hr3 : core.\n\n  (* The Boolean encoding of x ∈ p *)\n\n  Local Definition p_bool x := if hfs_mem_dec x p then true else false.\n\n  Local Fact p_bool_spec x : x ∈ p <-> p_bool x = true.\n  Proof.   \n    unfold p_bool.\n    destruct (hfs_mem_dec x p); split; try tauto; discriminate.\n  Qed.\n\n  Local Fact p_bool_spec1 x : x ∈ p -> p_bool x = true.\n  Proof. apply p_bool_spec. Qed.\n\n  Local Fact p_bool_spec2 x : p_bool x = true -> x ∈ p.\n  Proof. apply p_bool_spec. Qed.\n\n  Local Definition Y := sig (fun x => p_bool x = true).\n\n  Notation π1 := (@proj1_sig _ (fun x => p_bool x = true)).\n\n  Hint Resolve p_bool_spec p_bool_spec1 p_bool_spec2 : core.\n\n  Local Fact eqY : forall x y : Y, π1 x = π1 y -> x = y.\n  Proof. \n    intros (x & Hx) (y & Hy); simpl.\n    intros; subst; f_equal; apply UIP_dec, bool_dec.\n  Qed.\n\n  Local Fact HY : finite_t Y.\n  Proof. \n    apply fin_t_finite_t.\n    + intros; apply UIP_dec, bool_dec.\n    + generalize (hfs_mem_fin_t p); apply fin_t_equiv.\n      intros x; auto.\n  Qed.\n\n  (* This one is not needed anymore *)\n\n  Local Fact discrY : discrete Y.\n  Proof.\n    intros (x & Hx) (y & Hy).\n    destruct (hfs_eq_dec x y) as [ -> | D ].\n    + left; f_equal; apply UIP_dec, bool_dec.\n    + right; contradict D; inversion D; auto.\n  Qed.\n\n  Local Definition mem (x y : Y) := π1 x ∈ π1 y.\n\n  Local Fact mem_dec : forall x y, { mem x y } + { ~ mem x y }.\n  Proof.\n    intros (a & ?) (b & ?); unfold mem; simpl; apply hfs_mem_dec.\n  Qed.\n\n  Local Definition yd : Y := exist _ _ (p_bool_spec1 Hp2).\n  Local Definition yr : Y := exist _ _ (p_bool_spec1 Hr1).\n\n  Local Fact fa_mem_Y (P : _ -> Prop) :\n                           (forall a, a ∈ p -> P a)\n                       <-> (forall a, P (π1 a)).\n  Proof.\n    split.\n    + intros H (a & Ha); simpl; auto.\n    + intros H a Ha.\n      apply (H (exist _ _ (p_bool_spec1 Ha))).\n  Qed.\n\n  Local Fact ex_mem_Y (P : _ -> Prop) :\n                           (exists a, a ∈ p /\\ P a)\n                       <-> (exists a, P (π1 a)).\n  Proof.\n    split.\n    + intros (a & H & Ha). \n      exists (exist _ a (p_bool_spec1 H)); auto.\n    + intros ((a & Ha) & H); simpl in *; eauto.\n  Qed.\n\n  Local Fact mem_fa_Y (P : _ -> Prop) k : k ∈ p -> (forall a, P a -> a ∈ p)\n                       -> (forall a, a ∈ k <-> P a)\n                       <-> (forall a, π1 a ∈ k <-> P (π1 a)).\n  Proof.\n    intros H1 H2.\n    rewrite <- fa_mem_Y with (P := fun a => a ∈ k <-> P a).\n    split.\n    + intros H ? _; auto.\n    + intros H a; split. \n      * intros Ha; apply H; auto.\n        apply (Hp1 Ha); auto.\n      * intros Ha; apply H; auto.\n  Qed.\n\n  (* Membership equivalence is identity in the model *)\n\n  Local Fact mem_equiv_Y u v : \n                        u ∈ p \n                     -> v ∈ p\n                     -> (forall y : Y, π1 y ∈ u <-> π1 y ∈ v)\n                    <-> (forall x : hfs, x ∈ u <-> x ∈ v).\n  Proof.\n    intros Hu Hv.\n    symmetry; apply mem_fa_Y; auto.\n    intros s Hs; apply (Hp1 Hs); auto.\n  Qed.\n\n  Local Fact is_equiv : forall x y, mb_equiv mem x y <-> π1 x = π1 y.\n  Proof.\n    intros (x & Hx) (y & Hy); simpl.\n    unfold mb_equiv, mem; simpl; split.\n    2: { intros []; tauto. }\n    rewrite mem_equiv_Y; auto; apply hfs_mem_ext.\n  Qed.\n\n  Local Fact mem_ext_Y x y : x ∈ p -> y ∈ p -> (forall a, π1 a ∈ x <-> π1 a ∈ y) <-> x = y.\n  Proof.\n    intros H1 H2; split.\n    + intros H; apply hfs_mem_ext.\n      rewrite mem_fa_Y; auto.\n      intros z Hz; apply (Hp1 Hz); auto.\n    + intros ->; tauto.\n  Qed.\n\n  Hint Resolve mem_ext_Y : core.\n\n  Local Fact is_pair : forall x y k, mb_is_pair mem k x y \n                                 <-> π1 k = hfs_pair (π1 x) (π1 y).\n  Proof.\n    intros (x & Hx) (y & Hy) (k & Hk); simpl.\n    unfold mb_is_pair; simpl.\n    unfold mb_equiv, mem; simpl.\n    rewrite hfs_pair_spec'.\n    rewrite mem_fa_Y; auto.\n    2: intros ? [ -> | -> ]; auto.\n    fol equiv; intros (a & Ha); simpl.\n    fol equiv; try tauto.\n    fol equiv; auto.\n  Qed.\n\n  Local Fact is_opair : forall x y k, mb_is_opair mem k x y \n                                  <-> π1 k = ⟬π1 x,π1 y⟭.\n  Proof.\n    intros (x & Hx) (y & Hy) (k & Hk); simpl.\n    unfold mb_is_opair; simpl.\n    split.\n    + intros ((a & Ha) & (b & Hb) & H); revert H.\n      repeat rewrite is_pair; simpl.\n      intros (-> & -> & ->); auto.\n    + intros ->.\n      generalize Hx Hy Hk; revert Hx Hy Hk.\n      do 3 rewrite <- p_bool_spec at 1.\n      intros Hx' Hy' Hk' Hx Hy Hk.\n      apply hfs_trans_opair_inv in Hk'; auto.\n      do 2 rewrite p_bool_spec in Hk'.\n      destruct Hk' as (H1 & H2).\n      exists (exist _ (hfs_pair x x) H1).\n      exists (exist _ (hfs_pair x y) H2).\n      repeat rewrite is_pair; simpl; auto.\n  Qed.\n\n  Local Fact is_tuple n : forall v t, @mb_is_tuple _ mem t n v \n                                  <-> π1 t = hfs_tuple (vec_map π1 v).\n  Proof.\n    induction n as [ | n IHn ]; intros v (t & Ht).\n    + vec nil v; clear v; simpl; split.\n      * intros H; apply hfs_mem_ext.\n        intros z; split.\n        - intros Hz.\n          assert (Hz' : p_bool z = true).\n          { apply p_bool_spec.\n            apply Hp1 with (1 := Hz), p_bool_spec; auto. }\n          destruct (H (exist _ z Hz')); auto.\n        - rewrite hfs_empty_spec; tauto. \n      * intros -> (z & ?); unfold mem; simpl.\n        rewrite hfs_empty_spec; tauto.\n    + vec split v with x; simpl; split.\n      * intros (t' & H1 & H2).\n        rewrite IHn in H2; try lia.\n        rewrite <- H2.\n        apply is_opair with (k := exist _ t Ht); auto.\n      * intros ->.\n        assert (H1 : p_bool (hfs_tuple (vec_map π1 v)) = true).\n        { apply p_bool_spec.\n          apply p_bool_spec in Ht.\n          apply hfs_trans_opair_inv, proj2, hfs_trans_pair_inv in Ht; auto; tauto. }\n        exists (exist _ (hfs_tuple (vec_map π1 v)) H1); split.\n        - rewrite is_opair; simpl; auto.\n        - rewrite IHn; simpl; auto.\n  Qed.\n\n  Local Fact has_tuples : mb_has_tuples mem yd nt.\n  Proof.\n    intros v Hv.\n    set (t := hfs_tuple (vec_map (proj1_sig (P:=fun x : hfs => p_bool x = true)) v)).\n    assert (H1 : p_bool t = true).\n    { apply p_bool_spec, Hp6; auto; intro; rew vec; apply Hv. }\n    exists (exist _ t H1).\n    apply is_tuple; simpl; reflexivity.\n  Qed.\n\n  Local Definition i' x : Y := exist _ _ (p_bool_spec1 (Hp1 (Hi x) Hp2)).\n \n  Local Fact Hi'' x : mem (i' x) yd.\n  Proof. unfold i', yd, mem; simpl; auto. Qed.\n\n  Hint Resolve Hi'' : core.\n\n  Local Definition s' (y : Y) : X := s (π1 y).\n\n  (*\n    For finite and discrete type X, non empty (as witnessed by a given element)\n    equipped with a Boolean ternary relation R, one can compute a type Y, finite\n    (and discrete), equipped with a Boolean binary membership predicate ∈ (which is \n    extensional). Y is a finite (set like) model which contains two sets yd and \n    yr and there is a bijection between X and (the elements of) yd. All ordered \n    nt-tuples build from elements of yd exist in Y, and yr encodes R in the set \n    of (ordered) nt-tuples it contains. \n    (Finally, membership equivalence (≈) is the same as identity (=) in Y).\n\n    Membership equivalence : x ≈ y := ∀z, z∈x <-> z∈y\n    Membership extensional : x ≈ y -> ∀z, x∈z -> y∈z\n\n    Tuples are build the usual way (in set theory)\n      - z ∈ {x,y} := z ≈ x \\/ z ≈ y\n      - ordered pairs: (x,y) is {{x},{x,y}}\n      - ordered triples: (x,y,z) is ((x,y),z), etc\n\n    Non-emptyness is not really necessary but then the bijection between X=ø \n    and yl has to be implemented with dependent functions, more cumbersome to work\n    with. And first order models can never be empty because one has to be able\n    to interpret variables. \n\n    Maybe a discussion on the case of empty models could help, but then \n    the FO logic been reduced to True/False in that case.\n    Any ∀ formula is True, any ∃ is False and no atomic formula can ever\n    be evaluated (because it contains terms that cannot be interpreted). \n    Only closed formula have a meaning in the empty model \n  *)\n  \n  Theorem reln_hfs : { Y : Type &\n                     { _ : finite_t Y & \n                     { mem : Y -> Y -> Prop &\n                     { _ : forall u v, { mem u v } + { ~ mem u v } & \n                     { yd : Y &\n                     { yr : Y & \n                     { i : X -> Y & \n                     { s : Y -> X &\n                             (forall x, mem (i x) yd)\n                          /\\ (forall y, mem y yd -> exists x, y = i x)\n                          /\\ (forall v, R v <-> mb_is_tuple_in mem yr (vec_map i v))\n                      }}}}}}}}.\n  Proof using x0 Xfin Xdiscr HR.\n    exists Y, HY, mem, mem_dec, yd, yr, i', s'.\n    msplit 2; auto.\n    + intros y Hy; unfold i'.\n      destruct (Hi' Hy) as (x & Hx).\n      exists x; apply eqY; simpl; auto.\n    + intros v; rewrite Hr3; split.\n      * intros Hv.\n        red.\n        assert (H1 : p_bool (hfs_tuple (vec_map i v)) = true).\n        { apply p_bool_spec, Hp1 with (1 := Hv); auto. }\n        exists (exist _ (hfs_tuple (vec_map i v)) H1); split.\n        - apply is_tuple; simpl; rewrite vec_map_map; auto.\n        - unfold yr; red; simpl; auto.\n      * intros ((t & Ht) & H1 & H2).\n        rewrite is_tuple in H1.\n        simpl in H1, H2.\n        rewrite vec_map_map in H1; subst t; auto.\n  Qed.\n\nEnd bt_model_n.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/FOL/TRAKHTENBROT/reln_hfs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6766461527828317}}
{"text": "Require Export LL.Misc.Utils. \nRequire Export LL.FOLL.Syntax.\n\nExport ListNotations.\nSet Implicit Arguments.\n\nSection LL2Sequent.\n  Context `{OLS: OLSig}.\n  Definition multiset := list.\n \n  Reserved Notation \"n '|--' B ';' L \" (at level 80).\n\n  Inductive LL2N:  nat -> multiset oo -> multiset oo -> Prop :=\n  (* axioms *)\n  | ll2_init : forall B A L n, Permutation L [atom A; perp A] -> n |-- B ; L\n  | ll2_one : forall B n, n |-- B ; [One]\n  | ll2_top : forall B M L n, Permutation L (Top :: M) ->\n      n |-- B ; L\n  (* additives *)      \n  | ll2_plus1 : forall B M F G L n, Permutation L ((AOr F G)::M) ->\n      n |-- B ; F::M -> S n |-- B ; L\n  | ll2_plus2 : forall B M F G L n, Permutation L ((AOr F G)::M) ->\n      n |-- B ; G::M -> S n |-- B ; L\n  | ll2_with : forall B M F G L n, Permutation L ((AAnd F G)::M) ->\n      n |-- B ; F :: M ->\n      n |-- B ; G :: M -> S n |-- B ; L \n  (* multiplicatives *)     \n  | ll2_bot : forall B M L n, Permutation L (Bot :: M) ->\n      n |-- B ; M -> S n |-- B ; L\n  | ll2_par : forall B M F G L n, Permutation L ((MOr F G) :: M) ->\n      n |-- B ; F::G::M -> S n |-- B ; L         \n  | ll2_tensor : forall B M N F G L n, Permutation L ((MAnd F G)::(M ++ N)) ->\n                                        (n |-- B ; F::M) ->\n                                        (n |-- B ; G::N) ->\n                                        (S n) |-- B ; L \n   (* exponentials *)          \n  | ll2_quest : forall B M F L n, Permutation L ((Quest F) :: M) ->\n      n |-- F::B ; M -> S n |-- B ; L   \n  | ll2_bang : forall B F n,\n      n |-- B ; [F] -> S n |-- B ; [Bang F]\n  (* quantifiers *)   \n  | ll2_ex  : forall B FX M L t n,  Permutation L ((Some  FX)::M) ->\n      uniform_oo FX -> proper t -> n |-- B; (FX t)::M -> S n|-- B; L\n  | ll2_fx  : forall B FX M L n, Permutation L ((All  FX)::M) ->\n      uniform_oo FX -> (forall x, proper x -> n |-- B ; (FX x) ::  M) ->\n      S n |-- B ; L      \n  (* structurals *)            \n  | ll2_abs : forall B L F n, \n     In F B -> n |-- B ; F::L -> S n |-- B ; L \n  \n                                                                                                                    \n  where \"n '|--' B ';' L \" := (LL2N n B L).\n   \n  Reserved Notation \"'|--' B ';' L\" (at level 80).\n\n  Inductive LL2S:  multiset oo -> multiset oo -> Prop :=\n  (* axioms *)  \n  | ll2_init' : forall B A L, Permutation L [atom A; perp A] -> |-- B ; L\n  | ll2_one' : forall B, |-- B ; [One]\n  | ll2_top' : forall B M L, Permutation L (Top :: M) ->\n      |-- B ; L\n  (* additives *)  \n  | ll2_plus1' : forall B M F G L, Permutation L ((AOr F G)::M) ->\n      |-- B ; F::M -> |-- B ; L\n  | ll2_plus2' : forall B M F G L, Permutation L ((AOr F G)::M) ->\n      |-- B ; G::M -> |-- B ; L    \n  | ll2_with' : forall B M F G L, Permutation L ((AAnd F G)::M) ->\n      |-- B ; F :: M ->\n      |-- B ; G :: M -> |-- B ; L      \n  (* multiplicatives *)  \n  | ll2_bot' : forall B M L, Permutation L (Bot :: M) ->\n      |-- B ; M -> |-- B ; L\n  | ll2_par' : forall B M F G L, Permutation L ((MOr F G) :: M) ->\n      |-- B ; F::G::M -> |-- B ; L  \n  | ll2_tensor' : forall B M N F G L, Permutation L ((MAnd F G)::(M ++ N)) ->\n                                        |-- B ; F::M ->\n                                        |-- B ; G::N ->\n                                        |-- B ; L       \n  (* exponentials *) \n  | ll2_quest' : forall B M F L, Permutation L ((Quest F) :: M) ->\n      |-- F::B ; M -> |-- B ; L      \n  | ll2_bang' : forall B F,\n      |-- B ; [F] -> |-- B ; [Bang F]     \n  (* quantifiers *)   \n  | ll2_ex'  : forall B FX M L t,  Permutation L ((Some  FX)::M) ->\n      uniform_oo FX -> proper t -> |-- B; (FX t)::M -> |-- B; L\n  | ll2_fx'  : forall B FX M L, Permutation L ((All  FX)::M) ->\n      uniform_oo FX -> (forall x, proper x -> |-- B ; (FX x) ::  M) ->\n      |-- B ; L        \n  (* structurals *)     \n  | ll2_abs' : forall B L F, \n     In F B -> |-- B ; F::L -> |-- B ; L \n  where \"'|--' B ';' L \" := (LL2S B L).\n\n  \n End LL2Sequent .\n\nGlobal Hint Constructors LL2N : core .\nGlobal Hint Constructors LL2S : core. \n \nNotation \"'LL2' n '|--' B ';' L \" := (LL2N n B L)  (at level 80).\nNotation \"'LL2' '|--' B ';' L \" := (LL2S B L)  (at level 80).\n\n", "meta": {"author": "brunofx86", "repo": "LLFramework", "sha": "d12e01875912ef52397d8cd899b7fb0e26977ac5", "save_path": "github-repos/coq/brunofx86-LLFramework", "path": "github-repos/coq/brunofx86-LLFramework/LLFramework-d12e01875912ef52397d8cd899b7fb0e26977ac5/FOLL/Dyadic/Sequent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6766461449823005}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrnat eqtype ssrfun seq tuple.\nFrom mathcomp Require Import choice path bigop finfun fintype.\n\n(* IPDL only needs a simple, terminating model for distributions. A probability distribution is a program that depends on a finite number of coin flips. *)\n\n\nInductive Dist A :=\n  | DRet : A -> Dist A\n  | Flip : (bool -> Dist A) -> Dist A.\n\nArguments DRet [A].\nArguments Flip [A].\n\nFixpoint dbind {A B} (d : Dist A) (k : A -> Dist B) : Dist B :=\n  match d with\n    | DRet x => k x\n    | Flip f =>\n      Flip (fun b => dbind (f b) k)\n  end.\n\n\n(* Distributions are given semantics by simply counting the number of occurences of return values. *)\n\nFixpoint interpDist {A} (d : Dist A) : list A :=\n  match d with\n  | DRet y => [:: y]\n  | Flip k =>\n    interpDist (k false) ++ interpDist (k true) end.\n\nLemma interp_dbind {A B} (d : Dist A) (k : A -> Dist B) :\n  interpDist (dbind d k) = flatten (map (fun x => interpDist (k x)) (interpDist d)).\n    induction d; rewrite //=.\n    rewrite cats0 //=.\n    rewrite !H.\n    rewrite map_cat //= flatten_cat //=.\nQed.\n\n\n(* A distribution is uniform if every return value appears the same amount of times in the interpretation. *)\nDefinition uniform {A : finType} (d : Dist A) :=\n  exists n,\n    forall x, \\sum_(j <- interpDist d) (j == x) = n.\n\n\nClass unif (A : finType) :=\n  {\n    Unif : Dist A;\n    is_unif : uniform Unif }.\n\nFixpoint Unif_bv (n : nat) : Dist (n.-tuple bool) :=\n  match n with\n    | 0%nat => DRet [tuple]\n    | S n' =>\n      Flip (fun x =>\n              dbind (Unif_bv n') (fun t => DRet [tuple of x :: t])) end.\n\nLemma uniform_Unif n : uniform (Unif_bv n).\n    exists 1.\n    induction n.\n    intro.\n    simpl.\n    rewrite big_cons big_nil //=.\n    have -> : x = [tuple] by apply tuple0.\n    done.\n    intro; rewrite //= !big_cat //= !interp_dbind !big_flatten //= !big_map //=.\n    under eq_bigr => m do rewrite !big_cons big_nil addn0.\n    rewrite addnC.\n    under eq_bigr => m do rewrite !big_cons big_nil addn0.\n    destruct (tupleP x); simpl.\n    under eq_bigr => m do rewrite eqE //=.\n    rewrite addnC.\n    under eq_bigr => m do rewrite eqE //=.\n    destruct x; simpl.\n\n    rewrite big_const_seq //=.\n    rewrite iter_addn_0 mul0n //=.\n    under eq_bigr => m do rewrite eqE //=.\n                          rewrite IHn //=.\n\n    rewrite big_const_seq //=.\n    rewrite iter_addn_0 mul0n //=.\n    under eq_bigr => m do rewrite eqE //=.\n                          rewrite IHn //=.\nQed.\n\n#[export]\nInstance unif_bv (n : nat) : unif [finType of n.-tuple bool] :=\n  {\n  Unif := Unif_bv n;\n  is_unif := (uniform_Unif n) }.\n\nDefinition uniform_bool : Dist bool := Flip (fun b => DRet b).\nLemma uniform_boolP : uniform uniform_bool.\n  exists 1.\n  intro.\n  simpl.\n  rewrite !big_cons big_nil; destruct x; rewrite //=.\nQed.\n  \n#[export]\nInstance unif_bool : unif [finType of bool] :=\n  {\n  Unif := uniform_bool;\n  is_unif := uniform_boolP\n             }.\n\nDefinition Unif_pair X Y `{unif X} `{unif Y} : Dist (X * Y) :=\n  dbind Unif (fun x => dbind Unif (fun y => DRet (x, y))).\nLemma Unif_pair_unif X Y `{unif X} `{unif Y} : \n    uniform (Unif_pair X Y).\n    destruct H.\n    destruct H0.\n    destruct is_unif0.\n    destruct is_unif1.\n    exists (x * x0).\n    intro.\n    rewrite interp_dbind.\n    rewrite big_flatten //=.\n    rewrite big_map //=.\n    etransitivity.\n    apply eq_bigr; intros.\n    rewrite interp_dbind.\n    rewrite big_flatten //=.\n    simpl.\n    etransitivity.\n    apply eq_bigr; intros.\n    rewrite big_map.\n    simpl.\n    etransitivity.\n    apply eq_bigr; intros.\n    rewrite big_cons big_nil addn0 //=.\n    done.\n    simpl.\n    destruct x1; simpl.\n    etransitivity.\n    apply eq_bigr; intros.\n    have -> :\n      \\sum_(i0 <- interpDist Unif1) ((i, i0) == (s, s0)) =\n      (i == s) * \\sum_(i0 <- interpDist Unif1) (i0 == s0).\n      rewrite big_distrr //=; apply eq_bigr; intros.\n      rewrite eqE //= mulnb //=.\n    rewrite e0.\n    done.\n    simpl.\n    have -> :\n      \\sum_(i <- interpDist Unif0) ((i == s) * x0) =\n      x0 * \\sum_(i <- interpDist Unif0) ((i == s)).\n      rewrite big_distrr //=; apply eq_bigr; intros.\n      rewrite mulnC //=.\n    rewrite e mulnC //=.\nQed.\n\n#[export]\nInstance unif_pair X Y `{unif X} `{unif Y} : unif [finType of X * Y] :=\n  {|\n    Unif := Unif_pair X Y;\n    is_unif := Unif_pair_unif X Y\n  |}.\n", "meta": {"author": "ipdl", "repo": "ipdl", "sha": "d41b022c9a216acfefaefcbd0ede9e52e350ab8a", "save_path": "github-repos/coq/ipdl-ipdl", "path": "github-repos/coq/ipdl-ipdl/ipdl-d41b022c9a216acfefaefcbd0ede9e52e350ab8a/lib/Dist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6766461438227526}}
{"text": "Require Export Arith.\nRequire Export ArithRing.\nRequire Export Omega.\n \nFixpoint two_power (n : nat) : nat :=\n match n with 0 => 1 | S p => 2 * two_power p end.\n \nTheorem div2_rec:\n forall (P : nat ->  Set),\n P 0 -> P 1 -> (forall n, P n ->  P (S (S n))) -> forall (n : nat),  P n.\nProof.\nintros P H0 H1 Hrec n; assert (P n * P (S n))%type.\nelim n; intuition.\nintuition.\nQed.\n \nTheorem div2_spec:\n forall n,  ({x : nat | 2 * x = n}) + ({x : nat | 2 * x + 1 = n}).\nintros n; elim n  using div2_rec.\nleft; exists 0; trivial.\nright; exists 0; trivial.\nintros p [[x Heq]|[x Heq]].\nleft; exists (S x); rewrite <- Heq; ring.\nright; exists (S x); rewrite <- Heq; ring.\nQed.\n \nTheorem half_smaller0: forall n x, 2 * x = S n ->  (x < S n).\nProof.\nintros; omega.\nQed.\n \nTheorem half_smaller1: forall n x, 2 * x + 1 = n ->  (x < n).\nProof.\nintros; omega.\nQed.\n \nDefinition log2_F:\n forall (n : nat),\n (forall (y : nat),\n  y < n -> y <> 0 ->  ({p : nat | two_power p <= y /\\ y < two_power (p + 1)})) ->\n n <> 0 ->  ({p : nat | two_power p <= n /\\ n < two_power (p + 1)}).\nintros n; case n.\nintros log2 Hn0; elim Hn0; trivial.\nintros n' log2 _.\nelim (div2_spec (S n')).\nintros [x]; case x.\nsimpl; intros; discriminate.\nintros x' Heqx'; assert (Hn0: S x' <> 0).\nauto with arith.\ndestruct (log2 (S x') (half_smaller0 _ _ Heqx') Hn0) as [v Heqv].\nexists (S v); simpl.\nrewrite <- Heqx'.\nomega.\nintros [x]; case x.\nsimpl.\nintros Heq; rewrite <- Heq; exists 0.\nsimpl; auto with arith.\nintros x' Heqx'; assert (Hn0: S x' <> 0).\nauto with arith.\ndestruct (log2 (S x') (half_smaller1 _ _ Heqx') Hn0) as [v Heqv].\nexists (S v); rewrite <- Heqx'.\nsimpl; omega.\nQed.\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/gen-rec/SRC/log2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6766461348626733}}
{"text": "Require Import GeoCoq.Axioms.parallel_postulates.\nRequire Import GeoCoq.Tarski_dev.Ch12_parallel.\n\nSection proclus_SPP.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma proclus_s_postulate_implies_strong_parallel_postulate :\n  proclus_postulate -> strong_parallel_postulate.\nProof.\nintros HP P Q R S T U HPTQ HRTS HNC1 HCop HCong1 Hcong2.\nunfold BetS in *; spliter.\nelim (col_dec P Q R); [exists P; split; ColR|intro HNC2].\ndestruct (HP P R Q S P U) as [I [HCol1 HCol2]]; [..|exists I; split]; Col.\napply l12_17 with T; [assert_diffs|split..]; Cong.\nassert (Coplanar P Q R S) by (exists T; left; split; Col).\nCopR.\nQed.\n\nEnd proclus_SPP.", "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/proclus_SPP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904955, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6766461220023279}}
{"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.Rfunctions.\nRequire BuiltIn.\nRequire int.Int.\nRequire real.Real.\nRequire real.RealInfix.\n\nRequire Import Exponentiation.\nImport Rfunctions.\n\n(* Why3 comment *)\n(* power is replaced with (Reals.Rfunctions.powerRZ x x1) by the coq driver *)\n\nLemma power_is_exponentiation :\n  forall x n, (0 <= n)%Z -> powerRZ x n = Exponentiation.power _ R1 Rmult x n.\nProof.\nintros x [|n|n] H.\neasy.\n2: now elim H.\nunfold Exponentiation.power, powerRZ.\nsimpl.\ninduction (nat_of_P n).\neasy.\nsimpl.\nnow rewrite IHn0.\nQed.\n\n(* Why3 goal *)\nLemma Power_0 :\nforall (x:R), ((Reals.Rfunctions.powerRZ x 0%Z) = 1%R).\nProof.\nintros x.\neasy.\nQed.\n\n(* Why3 goal *)\nLemma Power_s :\nforall (x:R) (n:Z),\n (0%Z <= n)%Z ->\n ((Reals.Rfunctions.powerRZ x (n + 1%Z)%Z) = (x * (Reals.Rfunctions.powerRZ x n))%R).\nProof.\nintros x n h1.\nrewrite 2!power_is_exponentiation by auto with zarith.\nnow apply Power_s.\nQed.\n\n(* Why3 goal *)\nLemma Power_s_alt :\nforall (x:R) (n:Z),\n (0%Z < n)%Z ->\n ((Reals.Rfunctions.powerRZ x n) = (x * (Reals.Rfunctions.powerRZ x (n - 1%Z)%Z))%R).\nintros x n h1.\nrewrite <- Power_s.\nf_equal; omega.\nomega.\nQed.\n\n(* Why3 goal *)\nLemma Power_1 :\nforall (x:R), ((Reals.Rfunctions.powerRZ x 1%Z) = x).\nProof.\nexact Rmult_1_r.\nQed.\n\n(* Why3 goal *)\nLemma Power_sum :\nforall (x:R) (n:Z) (m:Z),\n (0%Z <= n)%Z ->\n ((0%Z <= m)%Z ->\n  ((Reals.Rfunctions.powerRZ x (n + m)%Z) = ((Reals.Rfunctions.powerRZ x n) * (Reals.Rfunctions.powerRZ x m))%R)).\nProof.\nintros x n m h1 h2.\nrewrite 3!power_is_exponentiation by auto with zarith.\napply Power_sum ; auto with real.\nQed.\n\n(* Why3 goal *)\nLemma Power_mult :\nforall (x:R) (n:Z) (m:Z),\n (0%Z <= n)%Z ->\n ((0%Z <= m)%Z ->\n  ((Reals.Rfunctions.powerRZ x (n * m)%Z) = (Reals.Rfunctions.powerRZ (Reals.Rfunctions.powerRZ x n) m))).\nProof.\nintros x n m h1 h2.\nrewrite 3!power_is_exponentiation by auto with zarith.\napply Power_mult ; auto with real.\nQed.\n\n(* Why3 goal *)\nLemma Power_comm1 :\nforall (x:R) (y:R),\n ((x * y)%R = (y * x)%R) ->\n forall (n:Z),\n  (0%Z <= n)%Z ->\n  (((Reals.Rfunctions.powerRZ x n) * y)%R = (y * (Reals.Rfunctions.powerRZ x n))%R).\nintros x y h1 n h2.\napply Rmult_comm.\nQed.\n\n(* Why3 goal *)\nLemma Power_comm2 :\nforall (x:R) (y:R),\n ((x * y)%R = (y * x)%R) ->\n forall (n:Z),\n  (0%Z <= n)%Z ->\n  ((Reals.Rfunctions.powerRZ (x * y)%R n) = ((Reals.Rfunctions.powerRZ x n) * (Reals.Rfunctions.powerRZ y n))%R).\nProof.\nintros x y h1 n h2.\nrewrite 3!power_is_exponentiation by auto with zarith.\napply Power_comm2 ; auto with real.\nQed.\n\n(* Why3 goal *)\nLemma Pow_ge_one :\nforall (x:R) (n:Z),\n ((0%Z <= n)%Z /\\ (1%R <= x)%R) -> (1%R <= (Reals.Rfunctions.powerRZ x n))%R.\nintros x n (h1,h2).\ngeneralize h1.\npattern n; apply Z_lt_induction; auto.\nclear n h1; intros n Hind h1.\nassert (h: (n = 0 \\/ 0 < n)%Z) by omega.\ndestruct h.\nsubst n; rewrite Power_0; auto with *.\nreplace n with ((n-1)+1)%Z by omega.\nrewrite Power_s; auto with zarith.\nassert (h : (1 <= powerRZ x (n-1))%R).\napply Hind; omega.\nreplace 1%R with (1*1)%R by auto with real.\napply Rmult_le_compat; auto with real.\nQed.\n\n", "meta": {"author": "florianschanda", "repo": "why3", "sha": "dc0d2720d58c6d130b9c3e1db820a07275a133eb", "save_path": "github-repos/coq/florianschanda-why3", "path": "github-repos/coq/florianschanda-why3/why3-dc0d2720d58c6d130b9c3e1db820a07275a133eb/lib/coq/real/PowerInt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7905303137346444, "lm_q1q2_score": 0.6765762815352863}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect.\nRequire Import ssrbool.\nRequire Import funs.\nRequire Import dataset.\nRequire Import ssrnat.\nRequire Import znat.\nRequire Import frac.\nRequire Import real.\nRequire Import realsyntax.\nRequire Import Setoid.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nSection RealOperations.\n\n(**********************************************************)\n(**  Derived real operations:                             *)\n(*     definition by nondeterministic/deterministiccases, *)\n(*     min, max                                           *)\n(*     injections from Z, and Q into R                    *)\n(*     floor, range1r (unit interval)                     *)\n(**********************************************************)\n\nVariable R : real_structure.\n\nOpen Scope real_scope.\n\nDefinition pickr_set P1 P2 (x1 x2 y : R) := P1 /\\ y == x1 \\/ P2 /\\ y == x2.\n\nDefinition pickr P1 P2 x1 x2 := supr (pickr_set P1 P2 x1 x2).\n\nDefinition selr P := pickr P (~ P).\n\nDefinition minr x1 x2 := pickr (x1 <= x2) (x2 <= x1) x1 x2.\n\nDefinition maxr x1 x2 := pickr (x1 <= x2) (x2 <= x1) x2 x1.\n\nCoercion Local natR := natr R.\n\nDefinition znatr m := match m with Zpos n => natr R n | Zneg n => - S n end.\n\nCoercion Local znatr : znat >-> real_carrier.\n\nDefinition fracr f := let: Frac d m := f in m / S d.\n\nInductive floor_set (x : R) : R -> Prop :=\n  FloorSet : forall m : znat, m <= x -> floor_set x m.\n\nDefinition floor x := supr (floor_set x).\n\nDefinition range1r (x y : R) := x <= y < x + 1.\n\nEnd RealOperations.\n\nNotation \"'select' { x1 'if' P1 , x2 'if' P2 }\" := (pickr P1 P2 x1 x2)\n   (at level 10, x1, x2, P1, P2 at level 100,\n    format \"'select'  { x1  'if'  P1 ,  x2  'if'  P2 }\") : real_scope.\n\nNotation \"'select' { x1 'if' P , 'else' x2 }\" := (selr P x1 x2)\n   (at level 10, x1, x2, P at level 100,\n    format \"'select'  { x1  'if'  P ,  'else'  x2 }\") : real_scope.\n\nNotation min := (@minr _).\nNotation max := (@maxr _).\n\nSection RealLemmas.\n\n(* Basic arithmetic/order/setoid lemmas for real numbers.    *)\n(* The local definitions below need to be included verbatim  *)\n(* by clients of this module, along with all the setoid      *)\n(* declaration, in order to make setoid rewriting usable.    *)\n(* Note that the sup and inverse operators are not morphisms *)\n(* because of the undefined cases.                           *)\n(*   Most of the lemmas here do not depend explicitly on     *)\n(* classical reasoning; to underscore this we only prove the *)\n(* excluded middle at the very end of this section, when it  *)\n(* is needed to prove, e.g., the archimedean property.       *)\n\nVariable R : real_model.\n\nOpen Scope real_scope.\n\nLet RR : Type := R.\nLet isR (x : RR) := x.\nLet eqR : RR -> RR -> Prop := @eqr _.\nLet leqR : RR -> RR -> Prop := locked (@leqr _).\nLet addR : RR -> RR -> RR := locked (@addr _).\nLet oppR : RR -> RR := locked (@oppr _).\nLet mulR : RR -> RR -> RR := locked (@mulr _).\nLet selR : Prop -> RR -> RR -> RR := locked (@selr _).\nLet minR : RR -> RR -> RR := locked (@minr _).\nLet maxR : RR -> RR -> RR := locked (@maxr _).\nLet floorR : RR -> RR := locked (@floor _).\nLet range1R : RR -> RR -> Prop := @range1r _.\nCoercion Local natR := natr R.\nCoercion Local znatR := znatr R.\nCoercion Local fracR := fracr R.\n\nRemark rwR : forall x1 x2, x1 == x2 -> eqR (isR x1) (isR x2). Proof. done. Qed.\n\nRemark leqRI : forall x1 x2, (x1 <= x2) = leqR (isR x1) (isR x2).\nProof. by unlock leqR. Qed.\n\nRemark eqRI : forall x1 x2, (x1 == x2) = eqR (isR x1) (isR x2).\nProof. by unlock eqR. Qed.\n\nRemark addRI : forall x1 x2, (x1 + x2)%R = addR (isR x1) (isR x2).\nProof. by unlock addR. Qed.\n\nRemark oppRI : forall x, - x = oppR (isR x).\nProof. by unlock oppR. Qed.\n\nRemark mulRI : forall x1 x2, x1 * x2 = mulR (isR x1) (isR x2).\nProof. by unlock mulR. Qed.\n\nRemark selRI : forall P x1 x2,\n  select {x1 if P, else x2} = selR P (isR x1) (isR x2).\nProof. by unlock selR. Qed.\n\nRemark minRI : forall x1 x2, min x1 x2 = minR (isR x1) (isR x2).\nProof. by unlock minR. Qed.\n\nRemark maxRI : forall x1 x2, max x1 x2 = maxR (isR x1) (isR x2).\nProof. by unlock maxR. Qed.\n\nRemark floorRI : forall x, floor x = floorR (isR x).\nProof. by unlock floorR. Qed.\n\nRemark range1RI : forall x, range1r x = range1R (isR x).\nProof. by unlock range1R. Qed.\n\n(*********************************************************)\n(**     Comparisons and the least upper bound axioms     *)\n(*********************************************************)\n\nLemma eqr_leq2 : forall x1 x2 : R, x1 == x2 <-> x1 <= x2 <= x1.\nProof. by split. Qed.\n\nLemma eqr_leq : forall x1 x2 : R, x1 == x2 -> x1 <= x2.\nProof. by move=> x1 x2 [Hx12 _]. Qed.\n\nLemma ltr_neq : forall x1 x2 : R, x1 < x2 -> x1 != x2.\nProof. rewrite /eqr; tauto. Qed.\n\nLemma gtr_neq : forall x1 x2 : R, x2 < x1 -> x1 != x2.\nProof. rewrite /eqr; tauto. Qed.\n\nLemma leqrr : forall x : R, x <= x.\nProof. exact (leqr_reflexivity R). Qed.\nHint Resolve leqrr.\n\nLemma leqr_trans : forall x1 x2 x3 : R, x1 <= x2 -> x2 <= x3 -> x1 <= x3.\nProof. exact (leqr_transitivity R). Qed.\n\nLemma ubr_sup : forall E : R -> Prop, hasr (ubr E) -> ubr E (sup E).\nProof.\nby move=> E HhiE x Hx; apply: (supr_upper_bound R) (Hx); split; first by exists x.\nQed.\n\nLemma ubr_geq_sup : forall E (x : R), hasr (ubr E) -> sup E <= x -> ubr E x.\nProof. move=> E x; move/ubr_sup=> HhiE Hx y Hy; apply: leqr_trans Hx; auto. Qed.\n\nLemma supr_total : forall (x : R) E, has_supr E -> boundedr x E \\/ sup E <= x.\nProof. exact (supr_totality R). Qed.\n\nLemma leqr_total : forall x1 x2 : R, x1 <= x2 \\/ x2 <= x1.\nProof.\nmove=> x1 x2; pose E y := x2 = y.\nhave HE: (has_supr E) by split; exists x2; last by move=> x <-.\n case: (supr_total x1 HE) => [[y <-]|HEx1]; first by left.\nby right; apply: leqr_trans HEx1; apply: ubr_sup => //; exists x2; move=> x <-.\nQed.\n\nLemma ltr_total : forall x1 x2 : R, x1 != x2 -> x1 < x2 \\/ x2 < x1.\nProof. move=> x1 x2; rewrite /eqr; move: (leqr_total x1 x2); tauto. Qed.\n\nLemma ltrW : forall x1 x2 : R, x1 < x2 -> x1 <= x2.\nProof. by move=> x1 x2 Hx12; case: (leqr_total x1 x2) => // *; case: Hx12. Qed.\nHint Resolve ltrW.\n\nLemma leqr_lt_trans : forall x1 x2 x3 : R, x1 <= x2 -> x2 < x3 -> x1 < x3.\nProof. move=> x1 x2 x3 Hx12 Hx23 Hx31; case: Hx23; exact: leqr_trans Hx12. Qed.\n\nLemma ltr_leq_trans : forall x1 x2 x3 : R, x1 < x2 -> x2 <= x3 -> x1 < x3.\nProof. move=> x1 x2 x3 Hx12 Hx23 Hx31; case: Hx12; exact: leqr_trans Hx31. Qed.\n\nLemma ltr_trans : forall x1 x2 x3 : R, x1 < x2 -> x2 < x3 -> x1 < x3.\nProof. move=> x1 x2 x3 Hx12; apply: leqr_lt_trans; exact: ltrW. Qed.\n\n(**********************************************************)\n(**      The setoid structure                             *)\n(**********************************************************)\n\nLemma eqr_refl : forall x : R, x == x.\nProof. split; apply: leqrr. Qed.\nHint Resolve eqr_refl.\nHint Unfold eqR.\n\nRemark eqR_refl : forall x : R, eqR x x. Proof. auto. Qed.\nHint Resolve eqR_refl.\n\nLemma eqr_sym : forall x1 x2 : R, x1 == x2 -> x2 == x1.\nProof. rewrite /eqr; tauto. Qed.\nHint Immediate eqr_sym.\n\nLemma eqr_trans : forall x1 x2 x3 : R, x1 == x2 -> x2 == x3 -> x1 == x3.\nProof.\nmove=> x1 x2 x3 [Hx12 Hx21] [Hx23 Hx32]; split; eapply leqr_trans; eauto.\nQed.\n\nLemma eqr_theory : Setoid_Theory RR eqR.\nProof. split; auto; exact eqr_trans. Qed.\n\nAdd Setoid RR eqR eqr_theory.\n\nAdd Morphism isR : isr_morphism. Proof. done. Qed.\n\nAdd Morphism (@leqr _ : RR -> RR -> Prop) : leqr_morphism.\nProof. move: leqr_trans => Htr x1 y1 x2 y2 [_ Hyx1] [Hxy2 _]; eauto. Qed.\n\nAdd Morphism leqR : leqR_morphism.\nProof. unlock leqR; exact leqr_morphism. Qed.\n\n(**********************************************************)\n(**       Addition                                        *)\n(**********************************************************)\n\nLemma addrC : forall x1 x2 : R, x1 + x2 == x2 + x1.\nProof. exact (addr_commutativity R). Qed.\n\nAdd Morphism (@addr _ : RR -> RR -> RR) : addr_morphism.\nProof.\nmove=> x1 y1 x2 y2 Dx1 Dx2; apply eqr_trans with (x1 + y2).\n  by case Dx2; split; apply: (addr_monotony R).\nrewrite eqRI (rwR (addrC x1 y2)) (rwR (addrC y1 y2)).\nby case Dx1; split; apply: (addr_monotony R).\nQed.\n\nAdd Morphism addR : addR_morphism.\nProof. unlock addR; exact addr_morphism. Qed.\n\nLemma addrA : forall x1 x2 x3 : R, x1 + (x2 + x3) == x1 + x2 + x3.\nProof. exact (addr_associativity R). Qed.\n\nLemma addrCA : forall x1 x2 x3 : R, x1 + (x2 + x3) ==  x2 + (x1 + x3).\nProof.\nmove=> x1 x2 x3; rewrite eqRI (rwR (addrA x1 x2 x3)) (rwR (addrA x2 x1 x3)).\nby rewrite addRI (rwR (addrC x1 x2)) -addRI.\nQed.\n\nLemma add0r : forall x : R, 0 + x == x.\nProof. exact (addr_neutral_left R). Qed.\n\nLemma addr0 : forall x : R, x + 0 == x.\nProof. move=> x; rewrite eqRI (rwR (addrC x 0)); exact: add0r. Qed.\n\nLemma subrr : forall x : R, x - x == 0.\nProof. exact (addr_inverse_right R). Qed.\n\nLemma addr_inv : forall x1 x2 : R, - x1 + (x1 + x2) == x2.\nProof.\nmove=> x1 x2; rewrite eqRI (rwR (addrCA (- x1) x1 x2)).\nrewrite (rwR (addrA x1 (- x1) x2)) addRI (rwR (subrr x1)) -addRI; exact: add0r.\nQed.\n\nLemma addr_injl : forall x x1 x2 : R, x + x1 == x + x2 -> x1 == x2.\nProof.\nmove=> x x1 x2 Ex12; rewrite eqRI -(rwR (addr_inv x x1)) addRI (rwR Ex12) -addRI.\nexact: addr_inv.\nQed.\n\nLemma addr_injr : forall x x1 x2 : R, x1 + x == x2 + x -> x1 == x2.\nProof.\nmove=> x x1 x2; rewrite eqRI (rwR (addrC x1 x)) (rwR (addrC x2 x)).\nexact: addr_injl.\nQed.\n\nLemma oppr_opp : forall x : R, - - x == x.\nProof.\nmove=> x; apply addr_injr with (- x); rewrite eqRI (rwR (subrr x)).\nrewrite (rwR (addrC (- - x) (- x))); exact: subrr.\nQed.\n\nLemma oppr_add : forall x1 x2 : R, - (x1 + x2) == - x1 - x2.\nProof.\nmove=> x1 x2; apply addr_injl with (x1 + x2); rewrite eqRI.\nrewrite (rwR (addrCA (x1 + x2) (-x1) (-x2))) (rwR (subrr (x1 + x2))).\nrewrite addRI -(rwR (addrA x1 x2 (-x2))) -addRI.\nby rewrite (rwR (addr_inv x1 (x2 - x2))) (rwR (subrr x2)).\nQed.\n\nLemma oppr_sub : forall x1 x2 : R, - (x1 - x2) == x2 - x1.\nProof.\nmove=> x1 x2; rewrite eqRI (rwR (oppr_add x1 (- x2))) addRI (rwR (oppr_opp x2)).\nrewrite -addRI; apply: addrC.\nQed.\n\nLemma leqr_add2l : forall x x1 x2 : R, x + x1 <= x + x2 <-> x1 <= x2.\nProof.\nmove=> x x1 x2; split; last exact: (addr_monotony R).\nmove=> Hx12; rewrite leqRI -(rwR (addr_inv x x1)) -(rwR (addr_inv x x2)) -leqRI.\nexact: (addr_monotony R).\nQed.\n\nLemma leqr_add2r : forall x x1 x2 : R, x1 + x <= x2 + x <-> x1 <= x2.\nProof.\nmove=> x x1 x2; rewrite leqRI (rwR (addrC x1 x)) (rwR (addrC x2 x)) -leqRI.\nexact: leqr_add2l.\nQed.\n\nLemma leqr_0sub : forall x1 x2 : R, x1 <= x2 <-> 0 <= x2 - x1.\nProof.\nmove=> x1 x2; rewrite -(leqr_add2r (- x1) x1 x2) leqRI (rwR (subrr x1)) -leqRI.\nby split.\nQed.\n\nLemma leqr_sub0 : forall x1 x2 : R, x1 <= x2 <-> x1 - x2 <= 0.\nProof.\nmove=> x1 x2; rewrite -(leqr_add2r (- x2) x1 x2) leqRI (rwR (subrr x2)) -leqRI.\nby split.\nQed.\n\nLemma leqr_opp2 : forall x1 x2 : R, - x1 <= - x2 <-> x2 <= x1.\nProof.\nmove=> x1 x2; rewrite (leqr_0sub (- x1) (- x2)) (leqr_0sub x2 x1).\nrewrite leqRI addRI (rwR (oppr_opp x1)) -addRI (rwR (addrC (oppr x2) x1)) -leqRI.\nby split.\nQed.\n\nLemma oppr_inj : forall x1 x2 : R, - x1 == - x2 -> x1 == x2.\nProof.\nmove=> x y; rewrite /eqR /eqr (leqr_opp2 x y) (leqr_opp2 y x); tauto.\nQed.\n\nAdd Morphism (@oppr _ : RR -> RR) : oppr_morphism.\nProof.\nmove=> x y; rewrite /eqR /eqr (leqr_opp2 x y) (leqr_opp2 y x); tauto.\nQed.\n\nAdd Morphism oppR : oppR_morphism.\nProof. unlock oppR; exact oppr_morphism. Qed.\n\nLemma oppr0 : - (0 : R) == 0.\nProof. by rewrite eqRI -(rwR (subrr 0)) (rwR (add0r (- 0))). Qed.\n\n(**********************************************************)\n(**       Multiplication                                  *)\n(**********************************************************)\n\nLemma mulrC : forall x1 x2 : R, x1 * x2 == x2 * x1.\nProof. exact (mulr_commutativity R). Qed.\n\nLemma mulr_addr : forall x x1 x2 : R, x * (x1 + x2) == x * x1 + x * x2.\nProof. exact (mulr_addr_distributivity_right R). Qed.\n\nLemma mulr_addl : forall x x1 x2 : R, (x1 + x2) * x == x1 * x + x2 * x.\nProof.\nmove=> x x1 x2;\n rewrite eqRI (rwR (mulrC (x1 + x2) x)) (rwR (mulr_addr x x1 x2)).\nby rewrite addRI (rwR (mulrC x x1)) (rwR (mulrC x x2)) -addRI.\nQed.\n\nAdd Morphism (@mulr _ : RR -> RR -> RR) : mulr_morphism.\nProof.\nhave Hpos: forall x x1 x2 : R, 0 <= x -> x1 == x2 -> x * x1 == x * x2.\n  by move=> x x1 x2 Hx [Hx12 Hx21]; split; apply (mulr_monotony R).\nhave Hmull: forall x x1 x2 : R, x1 == x2 -> x * x1 == x * x2.\nmove=> x x1 x2 Dx1; case: (leqr_total 0 x) => Hx; auto.\n  have Hx': 0 <= - x by move: Hx; rewrite -(leqr_opp2 0 x) !leqRI (rwR oppr0).\n  apply addr_injr with (- x * x1).\n  rewrite eqRI -(rwR (mulr_addl x1 x (- x))) 2!addRI -addRI.\n  rewrite (rwR (Hpos _ _ _ Hx' Dx1)) -addRI -(rwR (mulr_addl x2 x (- x))).\n  apply: Hpos; last done; apply eqr_leq; apply eqr_sym; apply subrr.\nrewrite /eqR; move=> x1 y1 x2 y2 Dx1 Dx2.\napply eqr_trans with (x1 * y2); auto.\nrewrite eqRI (rwR (mulrC x1 y2)) (rwR (mulrC y1 y2)) -eqRI; auto.\nQed.\n\nAdd Morphism mulR : mulR_morphism. Proof. unlock mulR; exact mulr_morphism. Qed.\n\nLemma mulrA : forall x1 x2 x3 : R, x1 * (x2 * x3) == x1 * x2 * x3.\nProof. exact (mulr_associativity R). Qed.\n\nLemma mulrCA : forall x1 x2 x3 : R, x1 * (x2 * x3) == x2 * (x1 * x3).\nProof.\nmove=> x1 x2 x3; rewrite eqRI (rwR (mulrA x1 x2 x3)) (rwR (mulrA x2 x1 x3)).\nby rewrite mulRI (rwR (mulrC x1 x2)) -mulRI.\nQed.\n\nLemma mul1r : forall x : R, 1 * x == x.\nProof. exact (mulr_neutral_left R). Qed.\n\nLemma mulr1 : forall x : R, x * 1 == x.\nProof. move=> x; rewrite eqRI (rwR (mulrC x 1)); exact: mul1r. Qed.\n\nLemma mul2r : forall x : R, 2 * x == x + x.\nProof.\nby move=> x; rewrite eqRI (rwR (mulr_addl x 1 1)) !addRI (rwR (mul1r x)).\nQed.\n\nLemma mul0r : forall x : R, 0 * x == 0.\nProof.\nmove=> x; apply addr_injl with (1 * x); rewrite eqRI -(rwR (mulr_addl x 1 0)).\nby rewrite (rwR (addr0 (1 * x))) !mulRI (rwR (addr0 1)).\nQed.\n\nLemma mulr0 : forall x : R, x * 0 == 0.\nProof. by move=> x; rewrite eqRI (rwR (mulrC x 0)); apply: mul0r. Qed.\n\nLemma mulr_oppr :\n forall x1 x2 : R, x1 * - x2 == - (x1 * x2).\nProof.\nmove=> x1 x2; apply addr_injl with (x1 * x2).\nrewrite eqRI -(rwR (mulr_addr x1 x2 (- x2))) (rwR (subrr (x1 * x2))).\nrewrite mulRI (rwR (subrr x2)) -mulRI; exact: mulr0.\nQed.\n\nLemma mulr_oppl : forall x1 x2 : R, - x1 * x2 == - (x1 * x2).\nProof.\nmove=> x1 x2; rewrite eqRI (rwR (mulrC (- x1) x2)) (rwR (mulr_oppr x2 x1)).\nby rewrite !oppRI (rwR (mulrC x2 x1)).\nQed.\n\nLemma mulr_opp : forall x : R, - 1 * x == - x.\nProof.\nby move=> x; rewrite eqRI (rwR (mulr_oppl 1 x)) !oppRI (rwR (mul1r x)).\nQed.\n\nLemma mulr_opp1 : forall x : R, x * - 1 == - x.\nProof. move=> x; rewrite eqRI (rwR (mulrC x (- 1))); exact: mulr_opp. Qed.\n\n(* Properties of 1 (finally!) *)\n\nLemma neqr10 : (1 : R) != 0.\nProof. exact (mulr_neutral_nonzero R). Qed.\n\nLemma ltr01 : (0 : R) < 1.\nProof.\ncase/ltr_total: neqr10 => // H H10; case: H; move: (H10).\nrewrite -(leqr_opp2 0 1) -(leqr_opp2 1 0) !leqRI (rwR oppr0) -leqRI.\nmove=> Hn1; rewrite -(rwR (mulr1 (- 1))) -(rwR (mulr0 (- 1))) -leqRI.\nexact: (mulr_monotony R).\nQed.\nHint Resolve ltr01.\n\nLemma ltrSr : forall x : R, x < x + 1.\nProof.\nby move=> x; rewrite leqRI -(rwR (addr0 x)) -leqRI (leqr_add2l x 1 0).\nQed.\nImplicit Arguments ltrSr [].\n\nLemma ltPrr : forall x : R, x - 1 < x.\nProof.\nmove=> x /=; rewrite -(leqr_opp2 (x - 1) x) leqRI (rwR (oppr_add x (- 1))).\nrewrite addRI (rwR (oppr_opp 1)) -addRI -leqRI; exact: ltrSr.\nQed.\nImplicit Arguments ltPrr [].\n\nLemma ltr02 : (0 : R) < 2.\nProof. exact (ltr_trans ltr01 (ltrSr _)). Qed.\nHint Resolve ltr02.\n\n(* Division (well, mostly inverse) *)\n\nLemma divrr : forall x : R, x != 0 -> x / x == 1.\nProof. exact (mulr_inverse_right R). Qed.\n\nLemma leqr_pmul2l : forall x x1 x2 : R, x > 0 -> (x * x1 <= x * x2 <-> x1 <= x2).\nProof.\nmove=> x x1 x2 Hx; split; last by apply (mulr_monotony R); exact: ltrW.\nmove=> Hx12; rewrite leqRI -(rwR (mul1r x1)) -(rwR (mul1r x2)).\nrewrite !mulRI -(rwR (divrr (gtr_neq Hx))) (rwR (mulrC x (/ x))) -!mulRI.\nrewrite -(rwR (mulrA (/ x) x x1)) -(rwR (mulrA (/ x) x x2)) -leqRI.\napply: (mulr_monotony R) Hx12; apply ltrW; move=> Hix.\ncase ltr01; rewrite leqRI -(rwR (divrr (gtr_neq Hx))) -(rwR (mulr0 x)) -leqRI.\napply: (mulr_monotony R) Hix; exact: ltrW.\nQed.\n\nLemma leqr_pmul2r : forall x x1 x2 : R, x > 0 -> (x1 * x <= x2 * x <-> x1 <= x2).\nProof.\nmove=> x x1 x2 Hx; rewrite leqRI (rwR (mulrC x1 x)) (rwR (mulrC x2 x)) -leqRI.\nexact: leqr_pmul2l Hx.\nQed.\n\nLemma pmulr_inv : forall x x1 : R, x > 0 -> / x * (x * x1) == x1.\nProof.\nmove=> x x1 Hx; rewrite eqRI (rwR (mulrCA (/ x) x x1)) (rwR (mulrA x (/ x) x1)).\nrewrite mulRI (rwR (divrr (gtr_neq Hx))) -mulRI; apply: mul1r.\nQed.\n\nLemma posr_pmull : forall x1 x2 : R, x1 > 0 -> (x1 * x2 <= 0 <-> x2 <= 0).\nProof.\nmove=> x1 x2 Hx1; rewrite -(leqr_pmul2l x2 0 Hx1) 2!leqRI (rwR (mulr0 x1)); tauto.\nQed.\n\nLemma pmulr_injl : forall x x1 x2 : R, x > 0 -> x * x1 == x * x2 -> x1 == x2.\nProof.\nmove=> x x1 x2 Hx Ex12; rewrite eqRI -(rwR (pmulr_inv x1 Hx)) mulRI (rwR Ex12).\nrewrite -mulRI; exact (pmulr_inv x2 Hx).\nQed.\n\nLemma pmulr_injr : forall x x1 x2 : R, x > 0 -> x1 * x == x2 * x -> x1 == x2.\nProof.\nmove=> x x1 x2 Hx; rewrite eqRI (rwR (mulrC x1 x)) (rwR (mulrC x2 x)).\nby apply: pmulr_injl.\nQed.\n\nLemma mulr_injl : forall x x1 x2 : R, x != 0 -> x * x1 == x * x2 -> x1 == x2.\nProof.\nmove=> x x1 x2 Hx; case: (leqr_total (real0 _) x) => Hx0.\n  by apply: pmulr_injl => [H0x]; case Hx; split.\nmove/oppr_morphism; rewrite eqRI -(rwR (mulr_oppl x x1)) -(rwR (mulr_oppl x x2)).\napply: pmulr_injl; rewrite leqRI -(rwR oppr0) -leqRI (leqr_opp2 x 0).\nby move=> H0x; case Hx; split.\nQed.\n\nLemma mulr_injr : forall x x1 x2 : R, x != 0 -> x1 * x == x2 * x -> x1 == x2.\nProof.\nmove=> x x1 x2 Hx; rewrite eqRI (rwR (mulrC x1 x)) (rwR (mulrC x2 x)).\nexact: mulr_injl.\nQed.\n\n(* The inverse is only a partial morphism. It might be worth fixing, say,  *)\n(* 1/0 = 0 in order to make setoid rewriting work better.                  *)\n\nLemma invr_morphism : forall x y : R, x != 0 -> x == y -> / x == / y.\nProof.\nmove=> x y Hx Dx; have Hy: y != 0 by rewrite eqRI -(rwR Dx).\napply: (mulr_injl Hx); rewrite eqRI (rwR (divrr Hx)) -(rwR (divrr Hy)).\nby rewrite !mulRI (rwR Dx).\nQed.\n\nLemma invr1 : / (1 : R) == 1.\nProof. by rewrite eqRI -(rwR (divrr neqr10)) (rwR (mul1r (invr 1))). Qed.\n\nLemma invr_pmul : forall x1 x2 : R, x1 > 0 -> x2 > 0 ->\n  / (x1 * x2) == / x1 * / x2.\nProof.\nmove=> x1 x2 Hx1 Hx2; set y := / (x1 * x2); apply: (pmulr_injl Hx1).\nrewrite eqRI (rwR (mulrCA x1 (/ x1) (/ x2))) (rwR (pmulr_inv (/ x2) Hx1)) /isR.\napply: (pmulr_injl Hx2); rewrite eqRI (rwR (divrr (gtr_neq Hx2))).\nrewrite (rwR (mulrCA x2 x1 y)) (rwR (mulrA x1 x2 y)).\napply: divrr; apply: gtr_neq; rewrite leqRI -(rwR (mulr0 x1)) -leqRI.\nby rewrite (leqr_pmul2l x2 0 Hx1).\nQed.\n\nLemma invr_opp : forall x : R, x != 0 -> / - x == - / x.\nProof.\nmove=> x Hx; apply: (mulr_injl Hx); apply oppr_inj.\nrewrite eqRI -(rwR (mulr_oppl x (/ - x))) -(rwR (mulr_oppr x (- / x))).\nrewrite !mulRI (rwR (oppr_opp (/ x))) -!mulRI (rwR (divrr Hx)); apply: divrr.\nby rewrite eqRI -(rwR oppr0) -eqRI; move/oppr_inj.\nQed.\n\nLemma posr_inv : forall x : R, x > 0 -> / x > 0.\nProof.\nmove=> x Hx; rewrite -(leqr_pmul2l (/ x) 0 Hx).\nby rewrite leqRI (rwR (mulr0 x)) (rwR (divrr (gtr_neq Hx))) -leqRI.\nQed.\n\nLemma leqr_pinv2 : forall x1 x2 : R, x1 > 0 -> x2 > 0 ->\n  ( / x1 <= / x2 <-> x2 <= x1).\nProof.\nmove=> x1 x2 Hx1 Hx2; rewrite -(leqr_pmul2r (/ x1) (/ x2) Hx1).\nrewrite -(leqr_pmul2l (/ x1 * x1) (/ x2 * x1) Hx2).\nrewrite !leqRI (rwR (mulrC x2 (/ x1 * x1))) -(rwR (mulrA (/ x1) x1 x2)).\nrewrite (rwR (mulrCA x2 (/ x2) x1)) (rwR (pmulr_inv x1 Hx2)).\nrewrite (rwR (pmulr_inv x2 Hx1)); tauto.\nQed.\n\n(**********************************************************)\n(**      The least upper bound and derived operations.    *)\n(**********************************************************)\n\nLemma leqr_sup_ub : forall E (x : R), hasr E -> ubr E x -> sup E <= x.\nProof.\nmove=> E x HloE Hx; set y := sup E; pose z := (x + y) / 2.\nhave Dz: 2 * z == x + y.\n  apply: (eqr_trans (mulrA _ _ _)); apply: (eqr_trans (mulrC _ _)).\n  apply: pmulr_inv; exact ltr02.\nhave HE: has_supr E by split; last by exists x.\ncase: (supr_total z HE) => [[t Ht Hzt]|Hyz].\n  rewrite -(leqr_add2l x y x) leqRI -(rwR Dz) -(rwR (mul2r x)) -leqRI.\n  rewrite (leqr_pmul2l z x ltr02); apply: (leqr_trans Hzt); auto.\nrewrite -(leqr_add2r y y x) leqRI -(rwR Dz) -(rwR (mul2r y)) -leqRI.\nby rewrite (leqr_pmul2l y z ltr02).\nQed.\n\nLemma supr_sup : forall E, has_supr E -> forall x : R, ubr E x <-> sup E <= x.\nProof.\nby move=> E [HloE HhiE] x; split; [ apply leqr_sup_ub | apply ubr_geq_sup ].\nQed.\n\n(* Partial morphism property of the sup function; similarly to 1/0,   *)\n(* it might be helpful to define (supr [_]True) and (supr [_]False).  *)\n\nLemma supr_morphism : forall E, has_supr E -> forall E',\n  (forall x : R, E x <-> E' x) -> sup E == sup E'.\nProof.\nhave Hleq: forall E E', hasr E -> hasr (ubr E') ->\n    (forall x : R, E x -> E' x) -> sup E <= sup E'.\n  by move=> *; apply: leqr_sup_ub => // x Hx; apply ubr_sup; auto.\nmove=> E [HloE HhiE] E' DE'.\nsplit; (apply Hleq; auto; last by move=> x; case (DE' x); auto).\n  by move: HhiE => [y Hy]; exists y; move=> x; case (DE' x); auto.\nby move: HloE => [x Hx]; case (DE' x); exists x; auto.\nQed.\n\n(* Definition by nondeterministic cases.                        *)\n\nSection PickrCases.\n\nVariables (P1 P2 : Prop) (x1 x2 : R).\nHypotheses (HP : P1 \\/ P2) (HPx : P1 /\\ P2 -> x1 == x2).\n\nInductive pickr_spec : R -> Prop :=\n  PickrSpec : forall y, pickr_set P1 P2 x1 x2 y -> pickr_spec y.\n\nLemma pickr_cases : pickr_spec (select {x1 if P1, x2 if P2}).\nProof.\npose ps := pickr_set P1 P2 x1 x2; set x := select {x1 if P1, x2 if P2}.\nhave [x3 Hx3lo Ex3]:  exists2 x3, ps x3 & forall y, ps y <-> y == x3.\n  case: HP => HPi; [ exists x1; try split; try by left; split\n                   | exists x2; try split; try by right; split ];\n   case; case=> Hpj Dy //; apply: (eqr_trans Dy); auto; apply eqr_sym; auto.\nhave Hx3hi: ubr ps x3.\n  by move=> x4; rewrite (Ex3 x4); move=> Dx4; rewrite leqRI (rwR Dx4) -leqRI.\nsplit; rewrite -/ps (Ex3 x); split; last by apply: ubr_sup; first by exists x3.\nby apply: leqr_sup_ub; first by exists x3.\nQed.\n\nEnd PickrCases.\n\nSection PickrMorphism.\n\nVariables (P1 P2 : Prop) (x1 x2 : R).\nHypotheses (HP : P1 \\/ P2) (HPx : P1 /\\ P2 -> x1 == x2).\n\nLemma pickr_morphism : forall Q1 Q2 y1 y2,\n   (P1 <-> Q1) -> (P2 <-> Q2) -> x1 == y1 -> x2 == y2 ->\n  select {x1 if P1, x2 if P2} == select {y1 if Q1, y2 if Q2}.\nProof.\nmove=> Q1 Q2 y1 y2 DP1 DP2 Dx1 Dx2; rewrite -/eqR.\nhave HQ: Q1 \\/ Q2 by rewrite -DP1 -DP2.\nhave HQy: Q1 /\\ Q2 -> y1 == y2 by rewrite -DP1 -DP2 eqRI -(rwR Dx1) -(rwR Dx2).\ncase: (pickr_cases HQ HQy) => y; case: (pickr_cases HP HPx) => x.\nrewrite /pickr_set -DP1 -DP2 (eqRI y y1) -(rwR Dx1) (eqRI y y2) -(rwR Dx2) -!eqRI.\ncase; case=> HPi Dx; case; case=> HPj Dy;\n rewrite /eqR eqRI (rwR Dx) (rwR Dy) -eqRI; auto; apply eqr_sym; auto.\nQed.\n\nEnd PickrMorphism.\n\n(* min and max.                                                         *)\n\nSection MinMaxReal.\n\nVariable x1 x2 : R.\n\nLet Hx12 := leqr_total x1 x2.\nLet Ex12 (H : x1 <= x2 <= x1) := H : x1 == x2.\nLet Ex21 (H : x1 <= x2 <=x1) := eqr_sym H.\n\nLemma leqr_minl : min x1 x2 <= x1.\nProof.\nrewrite /minr; case: (pickr_cases Hx12 Ex12) => x3.\nby case; case=> Hx Dx3; rewrite leqRI (rwR Dx3) -leqRI.\nQed.\n\nLemma leqr_minr : min x1 x2 <= x2.\nProof.\nrewrite /minr; case: (pickr_cases Hx12 Ex12) => x3.\nby case; case=> Hx Dx3; rewrite leqRI (rwR Dx3) -leqRI.\nQed.\nHint Resolve leqr_minl leqr_minr.\n\nLemma ltr_min : forall x : R, x < min x1 x2 <-> x < x1 /\\ x < x2.\nProof.\nrewrite /minr; case: (pickr_cases Hx12 Ex12) => x3.\ncase; case=> Hx Dx3 x; rewrite leqRI (rwR Dx3) -leqRI;\n by split; [ split; try exact: ltr_leq_trans Hx | case ].\nQed.\n\nLemma leqr_min : forall x : R, x <= min x1 x2 <-> x <= x1 /\\ x <= x2.\nProof.\nmove=> x; split; first by split; eapply leqr_trans; eauto.\n move=> [Hxx1 Hxx2]; rewrite /minr; case: (pickr_cases Hx12 Ex12) => x3.\nby case; case=> Hx Dx3; rewrite leqRI (rwR Dx3) -leqRI.\nQed.\n\nLemma leqr_maxl : x1 <= max x1 x2.\nProof.\nrewrite /maxr; case: (pickr_cases Hx12 Ex21) => x3.\nby case; case=> Hx Dx3; rewrite leqRI (rwR Dx3) -leqRI.\nQed.\n\nLemma leqr_maxr : x2 <= max x1 x2.\nProof.\nrewrite /maxr; case: (pickr_cases Hx12 Ex21) => x3.\nby case; case=> Hx Dx3; rewrite leqRI (rwR Dx3) -leqRI.\nQed.\nHint Resolve leqr_maxl leqr_maxr.\n\nLemma ltr_max : forall x : R, max x1 x2 < x <-> x1 < x /\\ x2 < x.\nProof.\nrewrite /maxr; case: (pickr_cases Hx12 Ex21) => x3.\ncase; case=> Hx Dx3 x; rewrite leqRI (rwR Dx3) -leqRI;\n by split; [ split; try exact: (leqr_lt_trans Hx) | case ].\nQed.\n\nLemma leqr_max : forall x : R, maxr x1 x2 <= x <-> x1 <= x /\\ x2 <= x.\nProof.\nmove=> x; split; first by split; eapply leqr_trans; eauto.\nmove=> [Hxx1 Hxx2]; rewrite /maxr; case: (pickr_cases Hx12 Ex21) => x3.\nby case; case=> Hx Dx3; rewrite leqRI (rwR Dx3) -leqRI.\nQed.\n\nEnd MinMaxReal.\n\nAdd Morphism (minr (R := _) : RR -> RR -> RR) : minr_morphism.\nProof.\nmove=> x1 y1 x2 y2 Dx1 Dx2; apply: (pickr_morphism _ _ _) => //;\n try apply leqr_total; by rewrite !leqRI Dx1 Dx2; split.\nQed.\n\nAdd Morphism minR : minR_morphism. Proof. unlock minR; exact minr_morphism. Qed.\n\nAdd Morphism (maxr (R := _) : RR -> RR -> RR) : maxr_morphism.\nProof.\nmove=> x1 y1 x2 y2 Dx1 Dx2; apply: (pickr_morphism _ _ _) => //;\n try apply leqr_total; try by rewrite !leqRI Dx1 Dx2; split.\nby move/eqr_sym.\nQed.\n\nAdd Morphism maxR : maxR_morphism. Proof. unlock maxR; exact maxr_morphism. Qed.\n\n(**********************************************************)\n(** Properties of the injections from N, Z, and Q into R  *)\n(**********************************************************)\n\nLemma natr_S : forall n, S n == n + 1.\nProof.\ncase=> [|n] /=; first by rewrite eqRI (rwR (add0r 1)).\nelim: n {2 3}(real1 R) => //= [] x; apply addrC.\nQed.\n\nLemma ltr0Sn : forall n, 0 < S n.\nProof.\nelim=> // n Hrec; apply: ltr_trans Hrec _.\nrewrite leqRI -(rwR (addr0 (S n))) (rwR (natr_S (S n))) -leqRI.\nby rewrite (leqr_add2l (S n) 1 0).\nQed.\nImplicit Arguments ltr0Sn [].\n\nLemma leqr0n : forall n : nat, 0 <= n.\nProof. by move=> [|n]; [ apply leqrr | apply ltrW; apply ltr0Sn ]. Qed.\n\nLemma znatr_inc : forall m, incz m == m + 1.\nProof.\nmove=> [n|n]; rewrite eqRI; first by rewrite /= -/natR -(rwR (natr_S n)).\ncase: n => [|n]; first by rewrite /= (rwR (addrC (- 1) 1)) (rwR (subrr 1)).\nrewrite {2}/znatR /znatr -/natR addRI oppRI (rwR (natr_S (S n))) -oppRI.\nrewrite (rwR (oppr_add (S n) 1)) -addRI.\nrewrite -(rwR (addrA (- S n) (- 1) 1)) addRI (rwR (addrC (- 1) 1)).\nby rewrite (rwR (subrr 1)) -addRI (rwR (addr0 (- (S n)))).\nQed.\n\nLemma znatr_dec : forall m, decz m == m - 1.\nProof.\nmove=> m; rewrite -{2}[m]incz_dec; move/decz: m => m.\nrewrite eqRI addRI (rwR (znatr_inc m)) -addRI -(rwR (addrA m 1 (- 1))).\nby rewrite addRI (rwR (subrr 1)) -addRI (rwR (addr0 m)).\nQed.\n\nLemma znatr_opp : forall m, (- m)%Z == - m.\nProof.\nmove=> [[|[|n]]|[|m]] //=; apply eqr_sym; first [ exact: oppr0 | exact: oppr_opp ].\nQed.\n\nLemma znatr_add : forall m1 m2, (m1 + m2)%Z == m1 + m2.\nProof.\nhave znatr_addpos: forall (n : nat) m, (n + m)%Z == n + m.\n  move=> n m; elim: n => [|n Hrec]; first by rewrite add0z /= eqRI (rwR (add0r m)).\n  rewrite eqRI addRI (rwR (natr_S n)) -addRI -add1n zpos_addn -addzA addzC.\n  rewrite -incz_def (rwR (znatr_inc (n + m))) addRI (rwR Hrec) -addRI.\n  rewrite -(rwR (addrA n m 1)) -(rwR (addrA n 1 m)).\n  by rewrite addRI (rwR (addrC m 1)) -addRI.\nmove=> [n1|m1] m2; first by apply: znatr_addpos.\nset m12 := (_ + _)%Z; rewrite -(oppz_opp m12) eqRI.\nrewrite (rwR (znatr_opp (- m12))) {}/m12 oppz_add [addz]lock /= -lock.\nrewrite oppRI (rwR (znatr_addpos (S m1) (- m2)%Z)) -oppRI.\nrewrite (rwR (oppr_add (S m1) (- m2)%Z)) addRI.\nby rewrite -(rwR (znatr_opp (- m2))) oppz_opp -addRI.\nQed.\n\nLemma znatr_subz : forall m1 m2, (m1 - m2)%Z == m1 - m2.\nProof.\nmove=> m1 m2; rewrite eqRI (rwR (znatr_add m1 (- m2))).\nby rewrite !addRI (rwR (znatr_opp m2)).\nQed.\n\nLemma znatr_mul : forall m1 m2, (m1 * m2)%Z == m1 * m2.\nProof.\nmove=> m1 m2; elim/oppz_cases: m1 => [m1 Dm12|n1].\nrewrite mulz_oppl eqRI (rwR (znatr_opp (m1 * m2))) oppRI {Dm12}(rwR Dm12).\n  by rewrite -oppRI -(rwR (mulr_oppl m1 m2)) !mulRI (rwR (znatr_opp m1)).\nelim: n1 => [|n1 Hrec]; first by rewrite mul0z eqRI /= (rwR (mul0r m2)).\nrewrite -add1n zpos_addn mulzC mulz_addr !(mulzC m2) eqRI [(_ * _)%Z]/= mulRI.\nrewrite (rwR (znatr_add (Zpos 1%nat) n1)) (rwR (znatr_add m2 (n1 * m2)%Z)) -mulRI.\nrewrite addRI (rwR Hrec) /= -/natR (rwR (mulr_addl m2 1 n1)) addRI.\nby rewrite (rwR (mul1r m2)).\nQed.\n\nLemma znatr_scale : forall d m, scalez d m == S d * m.\nProof. move=> d m; exact (znatr_mul (S d) m). Qed.\n\nLemma znatr_addbit : forall m : znat, m == oddz m + 2 * halfz m.\nProof.\nmove=> m; rewrite -{1}[m]odd_double_halfz; move/halfz: m (oddz m) => m b.\nrewrite eqRI (rwR (znatr_add b (m + m))) 2!addRI (rwR (mul2r m)).\nby rewrite (rwR (znatr_add m m)).\nQed.\n\nLemma znatr_leqPx : forall m1 m2 : znat, reflect (m1 <= m2) (m1 <= m2)%Z.\nProof.\nmove=> m1 m2; rewrite /leqz; apply: (iffP idP);\n  rewrite (leqr_sub0 m1 m2) leqRI -(rwR (znatr_subz m1 m2)) -leqRI;\n  case: (m1 - m2)%Z => [[|n]|m] //; last by case/ltr0Sn.\nrewrite leqRI -(rwR oppr0) -leqRI /znatR /znatr -/natR (leqr_opp2 (S m) 0).\nclear; exact: leqr0n.\nQed.\n\nNotation znatr_leqP := (znatr_leqPx _ _).\n\nLemma znatr_ltPx : forall m1 m2 : znat, reflect (m1 < m2) (incz m1 <= m2)%Z.\nProof.\nmove=> m1 m2; rewrite -negb_leqz.\nby apply: (iffP idP) => Hm12; [ move/znatr_leqP: Hm12 | apply/znatr_leqP ].\nQed.\n\nNotation znatr_ltP := (znatr_ltPx _ _).\n\n(* Embedding the rationals.                                                     *)\n\nLemma fracr_eq : forall d m f, f = Frac d m -> m == S d * f.\nProof.\nmove=> d m f Df; rewrite Df /fracR /fracr -/natR -/znatR eqRI.\nrewrite (rwR (mulrA (S d) m (/ S d))) (rwR (mulrC (S d * m) (/ S d))).\nby rewrite (rwR (pmulr_inv m (ltr0Sn d))).\nQed.\n\nLemma fracr_leqPx : forall f1 f2 : frac, reflect (f1 <= f2) (leqf f1 f2).\nProof.\nmove=> f1 f2; case Df1: {2}f1 => [d1 m1]; case Df2: {2}f2 => [d2 m2] /=.\nsuffice [Hzr Hrz]: scalez d2 m1 <= scalez d1 m2 <-> f1 <= f2.\n  exact: (iffP (znatr_leqPx _ _)).\nrewrite leqRI (rwR (znatr_scale d2 m1)) (rwR (znatr_scale d1 m2)).\nrewrite !mulRI (rwR (fracr_eq Df1)) (rwR (fracr_eq Df2)) -!mulRI.\nrewrite (rwR (mulrCA (S d2) (S d1) f1)) -leqRI.\nrewrite (leqr_pmul2l (S d2 * f1) (S d2 * f2) (ltr0Sn d1)).\napply: leqr_pmul2l; exact: ltr0Sn.\nQed.\n\nNotation fracr_leqP := (fracr_leqPx _ _).\n\nLemma fracr_ltPx : forall f1 f2 : frac, reflect (f1 < f2) (ltf f1 f2).\nProof.\nmove=> f1 f2; rewrite /ltf; case (fracr_leqPx f2 f1); constructor; tauto.\nQed.\n\nNotation fracr_ltP := (fracr_ltPx _ _).\n\nLemma fracrz : forall m, let f := Frac 0%nat m in m == f.\nProof. move=> m f; rewrite eqRI -(rwR (mul1r f)); exact: (@fracr_eq 0%nat). Qed.\n\nLemma fracr0 : F0 == 0.\nProof. apply eqr_sym; exact (fracrz 0%nat). Qed.\n\nLemma fracr1 : F1 == 1.\nProof. apply eqr_sym; exact (fracrz 1%nat). Qed.\n\nLemma fracr2 : F2 == 2.\nProof. apply eqr_sym; exact (fracrz 2%nat). Qed.\n\nLemma fracr_posPx : forall f : frac, reflect (f <= 0) (negb (posf f)).\nProof.\nmove=> f; rewrite -nposfI.\nby apply: (iffP (fracr_leqPx _ _)); rewrite !leqRI (rwR fracr0).\nQed.\n\nNotation fracr_posP := (fracr_posPx _).\n\nLemma fracr_opp : forall f, oppf f == - f.\nProof.\nmove=> [d m]; rewrite /oppf /fracR /fracr -/znatR -/natR eqRI.\nrewrite !mulRI (rwR (znatr_opp m)) -!mulRI; apply: mulr_oppl.\nQed.\n\nLemma natr_muld : forall d1 d2 : nat, S (muld d1 d2) == S d1 * S d2.\nProof.\nmove=> d1 d2; apply: eqr_trans (znatr_mul (S d1) (S d2)).\nby rewrite muldE mulz_nat.\nQed.\n\nLemma fracr_add : forall f1 f2, addf f1 f2 == f1 + f2.\nProof.\nmove=> f1 f2; move Df: (addf f1 f2) => f.\ncase Df1: {1}f1 Df => [d1 m1]; case Df2: {1}f2 => [d2 m2] /=.\nset d := muld d1 d2; move/esym=> Df; apply: (pmulr_injl (ltr0Sn d)).\nrewrite eqRI (rwR (mulr_addr (S d) f1 f2)) -{Df}(rwR (fracr_eq Df)).\nrewrite (rwR (znatr_add (scalez d2 m1) (scalez d1 m2))) !addRI.\nrewrite (rwR (znatr_scale d2 m1)) (rwR (znatr_scale d1 m2)) !mulRI {}/d.\nrewrite (rwR (fracr_eq Df1)) (rwR (fracr_eq Df2)) (rwR (natr_muld d1 d2)) -!mulRI.\nrewrite (rwR (mulrCA (S d2) (S d1) f1)).\nby rewrite (rwR (mulrA (S d1) (S d2) f1)) (rwR (mulrA (S d1) (S d2) f2)).\nQed.\n\nLemma fracr_mul : forall f1 f2, mulf f1 f2 == f1 * f2.\nProof.\nmove=> f1 f2; move Df: (mulf f1 f2) => f.\ncase Df1: {1}f1 Df => [d1 m1]; case Df2: {1}f2 => [d2 m2] /=.\nset d := muld d1 d2; move/esym=> Df; apply: (pmulr_injl (ltr0Sn d)).\nrewrite eqRI -(rwR (fracr_eq Df)) (rwR (znatr_mul m1 m2)).\nrewrite mulRI (rwR (fracr_eq Df1)) (rwR (fracr_eq Df2)) -mulRI.\nrewrite -(rwR (mulrA (S d1) f1 (S d2 * f2))).\nrewrite mulRI (rwR (mulrCA f1 (S d2) f2)) -mulRI.\nrewrite (rwR (mulrA (S d1) (S d2) (f1 * f2))).\nby rewrite mulRI -(rwR (natr_muld d1 d2)) -/d -mulRI.\nQed.\n\nLemma fracr_pinv : forall f, posf f -> invf f == / f.\nProof.\nmove=> f Hff; have Hf: 0 < f.\n  move: Hff; rewrite -posfI; move/fracr_leqP.\n  by rewrite leqRI /F0 -(rwR (fracrz 0%nat)) -leqRI.\napply: (pmulr_injl Hf); rewrite eqRI (rwR (divrr (gtr_neq Hf))).\ncase Df: {1 3}f Hff => [d [[|m]|m]] // _; rewrite /invf {2}/fracR /fracr /znatr.\nrewrite -/natR (rwR (mulrA f (S d) (/ S m))) mulRI (rwR (mulrC f (S d))).\nrewrite -(rwR (fracr_eq Df)) -mulRI; apply: divrr; apply gtr_neq; exact: ltr0Sn.\nQed.\n\n(* The floor function                                                   *)\n\n\nRemark ubr_floor_set : forall x : R, ubr (floor_set x) x.\nProof. by move=> x y [m]. Qed.\nHint Resolve ubr_floor_set.\n\nRemark hasr_ub_floor_set : forall x : R, hasr (ubr (floor_set x)).\nProof. by move=> x; exists x. Qed.\nHint Resolve hasr_ub_floor_set.\n\nRemark hasr_floor_max : forall x : R, hasr (floor_set x) -> x < floor x + 1.\nProof.\nmove=> x Hxlo Hx; have Hinc: forall m : znat, m <= x -> incz m <= x.\n  move=> m Hm; apply: leqr_trans Hx; rewrite leqRI (rwR (znatr_inc m)) -leqRI.\n  rewrite (leqr_add2r 1 m (floor x)); apply: ubr_sup; auto.\n  by rewrite /znatR; split.\nhave Hsup: has_supr (floor_set x) by split.\ncase: (supr_total (floor x - 1) Hsup); last exact: ltPrr.\nmove=> [_ [m]]; do 2 move/Hinc.\nrewrite -/znatR -{2}[m]decz_inc; move/incz: m => m Hm.\nrewrite leqRI (rwR (znatr_dec m)) -!leqRI (leqr_add2r (- 1) (floor x) m).\nmove=> H; case: {H}(leqr_lt_trans H (ltrSr _)).\nby rewrite leqRI -(rwR (znatr_inc m)) -leqRI /znatR; apply: ubr_sup; auto; split.\nQed.\n\nRemark hasr_lb_floor_set : forall x : R, hasr (floor_set x).\nProof.\nmove=> x; case: (leqr_total 0 x) => Hx; first by exists (znatr R 0%nat); split.\nhave Hnx: has_supr (floor_set (- x)).\n  split; auto; exists (znatr R 0%nat); split.\n  by rewrite leqRI /= -(rwR oppr0) -leqRI (leqr_opp2 0 x).\n  case: (supr_total (floor (- x) - 1) Hnx); last by case/ltPrr.\ncase; auto; move=> _ [m _] Hm; set m1 := incz m; set m2 := incz m1.\nexists (znatr R (- m2)); split; move: Hm.\nrewrite -/znatR !leqRI -[m]decz_inc -/m1 (rwR (znatr_dec m1)).\nrewrite (rwR (znatr_opp m2)) -(rwR (oppr_opp x)) -!leqRI.\nrewrite (leqr_add2r (- 1) (floor (- x)) m1) (leqr_opp2 m2 (- x)).\nrewrite -(leqr_add2r 1 (floor (- x)) m1) leqRI -(rwR (znatr_inc m1)) -leqRI.\nby apply: leqr_trans; apply ltrW; apply hasr_floor_max; case Hnx.\nQed.\nHint Resolve hasr_lb_floor_set.\n\nLemma has_supr_floor_set : forall x : R, has_supr (floor_set x).\nProof. by split. Qed.\nHint Resolve has_supr_floor_set.\n\nAdd Morphism (@floor _ : RR -> RR) : floor_morphism.\nProof.\nmove=> x x' Dx; apply: supr_morphism; first by split.\nby move=> y; split; case=> m Hm {y}; split; apply: (leqr_trans Hm); case Dx.\nQed.\n\nAdd Morphism floorR : floorR_morphism.\nProof. unlock floorR; exact floor_morphism. Qed.\n\nAdd Morphism range1R : range1r_morphism.\nProof.\nmove=> x1 y1 x2 y2 Dx1 Dx2.\nby rewrite /range1R /range1r !leqRI !addRI (rwR Dx1) (rwR Dx2).\nQed.\n\nLemma range1r_floor : forall x : R, range1r (floor x) x.\nProof. by move=> x; split; [ apply: leqr_sup_ub | apply hasr_floor_max ]. Qed.\n\nLemma znat_floor : forall x : R, exists m : znat, floor x == m.\nProof.\nmove=> x; case: (range1r_floor x); set y := floor x => Hyx Hxy; pose h2 : R := / 2.\nhave Hh2: 0 < h2 by exact: posr_inv.\nhave Hyh2: y - h2 < y.\n  rewrite (leqr_0sub y (y - h2)) leqRI (rwR (addrC (y - h2) (- y))).\n  by rewrite (rwR (addr_inv y (- h2))) -(rwR oppr0) -leqRI (leqr_opp2 0 h2).\ncase: (supr_total (y - h2) (has_supr_floor_set x)) => Hy2; last by case: Hyh2.\ncase: Hy2 => [_ [m Hmx] Hym]; rewrite -/znatR in Hmx Hym; exists m.\nsplit; last by apply: ubr_sup; auto; rewrite /znatR; split.\napply: leqr_sup_ub; auto => _ [m' Hm'].\napply: znatr_leqP; rewrite -leqz_inc2; apply/znatr_ltP; set m1 := m + h2.\nhave Hym1: y <= m1.\n  rewrite -(leqr_add2r (- h2) y m1); apply: (leqr_trans Hym); apply eqr_leq.\n  rewrite eqRI /m1 addRI (rwR (addrC m h2)) -addRI.\n  by rewrite (rwR (addrC (h2 + m) (- h2))) (rwR (addr_inv h2 m)).\nmove: (Hh2); rewrite -(leqr_add2l m1 h2 0) leqRI (rwR (addr0 m1)).\nrewrite {1}/m1 -(rwR (addrA m h2 h2)) addRI -(rwR (mul2r h2)) /h2.\nrewrite (rwR (divrr (gtr_neq ltr02))) -addRI -(rwR (znatr_inc m)) -leqRI.\nby apply: leqr_lt_trans; apply: (ubr_geq_sup _ Hym1) => //; rewrite /znatR; split.\nQed.\n\nLemma range1z_inj : forall (x : R) (m1 m2 : znat),\n  range1r m1 x -> range1r m2 x -> m1 = m2.\nProof.\nmove=> x.\nsuffice: forall m1 m2 : znat, range1r m1 x -> range1r m2 x -> (m1 <= m2)%Z.\n  by move=> Hle m1 m2 Hm1 Hm2; apply: eqP; rewrite eqz_leq !Hle.\nmove=> m1 m2 [Hm1 _] [_ Hm2]; rewrite -leqz_inc2; apply/znatr_ltP.\nrewrite leqRI (rwR (znatr_inc m2)) -leqRI; eapply leqr_lt_trans; eauto.\nQed.\n\nLemma range1zz : forall m : znat, range1r m m.\nProof.\nmove=> m; split; auto; rewrite leqRI -(rwR (znatr_inc m)) -leqRI.\napply: znatr_ltP; exact: leqzz.\nQed.\n\nLemma range1z_floor : forall (m : znat) (x : R), range1r m x <-> floor x == m.\nProof.\nhave Hlr: forall (m : znat) (x : R), floor x == m -> range1r m x.\n  move=> m x Dm; rewrite range1RI -(rwR Dm); exact: range1r_floor.\nmove=> m x; split; auto; case: (znat_floor x) => [m' Dm'] Hm.\nby rewrite -(range1z_inj (Hlr _ _ Dm') Hm).\nQed.\n\nLemma floor_znat : forall m : znat, floor m == m.\nProof. move=> m; rewrite -(range1z_floor m m); exact: range1zz. Qed.\n\nLemma find_range1z : forall x : R, exists m : znat, range1r m x.\nProof.\nmove=> x; case: (znat_floor x) => [m Hm]; exists m; case (range1z_floor m x); auto.\nQed.\n\nLemma fracr_dense : forall x y : R, x < y -> exists2 f : frac, x < f & f < y.\nProof.\nmove=> x y Hxy; pose z := y - x.\nhave Hz: z > 0 by rewrite leqRI -(rwR (subrr x)) -leqRI /z (leqr_add2r (- x) y x).\ncase: (find_range1z (invr z)) => [[d|m] [Hdz Hzd]].\nset dd : R := S d; have Hdd: dd > 0 by exact: ltr0Sn.\ncase: (find_range1z (dd * x)) => [m [Hmx Hxm]].\nmove Df': (Frac d (incz m)) => f'; move/esym: Df' => Df'; exists f'.\n- rewrite -(leqr_pmul2l f' x Hdd) {1}/dd leqRI -(rwR (fracr_eq Df')).\n  by rewrite (rwR (znatr_inc m)) -leqRI.\n- rewrite -(leqr_pmul2l y f' Hdd) {2}/dd leqRI -(rwR (fracr_eq Df')).\n  rewrite mulRI -(rwR (addr_inv x y)) (rwR (addrC (- x) (x + y))).\n  rewrite -(rwR (addrA x y (- x))) -/z -mulRI (rwR (znatr_inc m)).\n  rewrite (rwR (mulr_addr dd x z)) -leqRI; move: Hmx.\n  rewrite -(leqr_add2r (dd * z) m (dd * x)); apply: ltr_leq_trans.\n  rewrite (leqr_add2l m (dd * z) 1).\n  rewrite leqRI -(rwR (divrr (gtr_neq Hz))) (rwR (mulrC dd z)) -leqRI.\n  by rewrite (leqr_pmul2l (dd : RR) (invr z) Hz) leqRI /dd (rwR (natr_S d)) -leqRI.\ncase Hzd; apply ltrW; apply: leqr_lt_trans (posr_inv Hz).\nrewrite leqRI -(rwR (znatr_inc (Zneg m))) -leqRI.\nby apply: (znatr_leqPx _ 0%nat); case m.\nQed.\n\n(**********************************************************)\n(*   The excluded middle, and lemmas that depend on       *)\n(* explicit classical reasoning.                          *)\n(**********************************************************)\n\nLemma reals_classic : excluded_middle.\nProof.\nmove=> P; pose E (x : R) := 0 = x \\/ P /\\ 2 = x.\nhave HhiE: (hasr (ubr E)) by exists (2 : R); move=> x [<-|[_ <-]] //; apply ltrW.\nhave HE: has_supr E by split; first by exists (0 : R); left.\ncase: (supr_total 1 HE) => HE1.\n  by left; case: HE1 => [x [<-|[HP _]]] // *; case ltr01.\nright; move=> HP; case: (ltrSr 1); apply: leqr_trans HE1.\nby apply ubr_sup; last by right; split.\nQed.\n\n(* Deciding comparisons. *)\n\nLemma leqr_eqVlt : forall x1 x2 : R, x1 <= x2 <-> x1 == x2 \\/ x1 < x2.\nProof.\nmove=> x1 x2; rewrite /eqr.\ncase: (reals_classic (x2 <= x1)) (leqr_total x1 x2); tauto.\nQed.\n\nLemma ltr_neqAle : forall x1 x2 : R, x1 < x2 <-> x1 != x2 /\\ x1 <= x2.\nProof. move=> x1 x2; rewrite (leqr_eqVlt x1 x2) /eqr; tauto. Qed.\n\n(* Deciding definition by cases. *)\n\nLemma selr_cases : forall P (x1 x2 : R),\n  pickr_spec P (~ P) x1 x2 (select {x1 if P, else x2}).\nProof. move=> P x1 x2; apply: pickr_cases; try tauto; exact: reals_classic. Qed.\n\nAdd Morphism (@selr _ : Prop -> RR -> RR -> RR) : selr_morphism.\nProof.\nmove=> P Q x1 y1 x2 y2 DP Dx1 Dx2; apply: pickr_morphism; try tauto.\nexact: reals_classic.\nQed.\n\nAdd Morphism selR : selR_morphism. Proof. unlock selR; exact selr_morphism. Qed.\n\nEnd RealLemmas.\n\nImplicit Arguments neqr10 [].\nImplicit Arguments ltr01 [].\nImplicit Arguments ltr02 [].\nImplicit Arguments ltrSr [R].\nImplicit Arguments ltPrr [R].\nImplicit Arguments ltr0Sn [].\n\nSet Strict Implicit.\nUnset Implicit Arguments.\n\n", "meta": {"author": "tangentforks", "repo": "FourColorTheorem", "sha": "eb30720f9e773fdcbf13dc6c61fdb245587cf401", "save_path": "github-repos/coq/tangentforks-FourColorTheorem", "path": "github-repos/coq/tangentforks-FourColorTheorem/FourColorTheorem-eb30720f9e773fdcbf13dc6c61fdb245587cf401/realprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6765762670025274}}
{"text": "(* polynomials in a semiring *)\n\nSet Nested Proofs Allowed.\nSet Implicit Arguments.\n\nRequire Import Utf8 Arith.\nImport List List.ListNotations.\nRequire Import Init.Nat.\n\nRequire Import Misc.\nRequire Import Semiring SRsummation SRproduct.\n\n(* property of a polynomial: its coefficient of higher degree is not 0 *)\n(* returns a boolean to allow proof of equality to be unique *)\n\nDefinition polyn_prop_test T {so : semiring_op T} {fdp : sring_dec_prop T}\n    f n :=\n  match n with\n  | 0 => true\n  | S n => if srng_eq_dec (f n) 0%Srng then false else true\n  end.\n\n(* polynomial *)\n\nRecord polynomial T (so : semiring_op T) (sdp : sring_dec_prop T) := mk_polyn\n  { polyn_list : list T;\n    polyn_prop :\n      polyn_prop_test (λ i, nth i polyn_list 0%Srng) (length polyn_list) =\n      true }.\n\nArguments polynomial T%type_scope {so sdp}.\nArguments mk_polyn {T so sdp}.\n\nDefinition polyn_coeff T {so : semiring_op T} {sdp : sring_dec_prop T} P i :=\n  nth i (polyn_list P) 0%Srng.\n\n(* degree of a polynomial *)\n\nDefinition polyn_degree_plus_1 T {so : semiring_op T} {sdp : sring_dec_prop T}\n     P :=\n  length (polyn_list P).\n\nDefinition polyn_degree T {so : semiring_op T} {sdp : sring_dec_prop T} P :=\n  polyn_degree_plus_1 P - 1.\n\n(* evaluation of a polynomial *)\n\n(* could be a theorem, perhaps...\nDefinition eval_polyn T {so : semiring_op T} {sdp : sring_dec_prop}\n    (P : polynomial T) x :=\n  match polyn_degree_plus_1 P with\n  | 0 => 0%Srng\n  | S n => (Σ (i = 0, n), polyn_coeff P i * x ^ i)%Srng\n  end.\n*)\n\nDefinition eval_polyn_list T {so : semiring_op T} (la : list T) x :=\n  fold_right (λ a acc, (acc * x + a)%Srng) 0%Srng la.\n\nDefinition eval_polyn T {so : semiring_op T} {sdp : sring_dec_prop T}\n    (P : polynomial T) :=\n  eval_polyn_list (polyn_list P).\n\n(* algebraically closed set *)\n\nClass algeb_closed_prop T {so : semiring_op T} {sdp : sring_dec_prop T} :=\n  { alcl_roots :\n      ∀ P : polynomial T, polyn_degree P > 0 → ∃ x, eval_polyn P x = 0%Srng }.\n\nSection in_ring.\n\nContext {T : Type}.\nContext {ro : ring_op T}.\nContext (so : semiring_op T).\nContext {sp : semiring_prop T}.\nContext {rp : ring_prop T}.\nContext {sdp : sring_dec_prop T}.\nContext {acp : algeb_closed_prop}.\n\nTheorem fold_eval_polyn_list : ∀ la (x : T),\n  fold_right (λ a acc, (acc * x + a)%Srng) 0%Srng la = eval_polyn_list la x.\nProof. easy. Qed.\n\n(* normalize a list, i.e. remove all trailing 0s *)\n\nFixpoint strip_0s l :=\n  match l with\n  | [] => []\n  | a :: l' => if srng_eq_dec a 0%Srng then strip_0s l' else l\n  end.\n\nDefinition norm_polyn_list l := rev (strip_0s (rev l)).\n\nTheorem fold_norm_polyn_list : ∀ la,\n  rev (strip_0s (rev la)) = norm_polyn_list la.\nProof. easy. Qed.\n\n(* polynomial from and to a list *)\n\nTheorem polyn_of_list_prop : ∀ l,\n  polyn_prop_test (λ i, nth i (norm_polyn_list l) 0%Srng)\n    (length (norm_polyn_list l)) = true.\nProof.\nintros.\nunfold norm_polyn_list.\nremember (rev l) as l' eqn:Hl.\nclear l Hl.\nrename l' into l.\nrewrite rev_length.\ninduction l as [| a]; [ easy | cbn ].\ndestruct (srng_eq_dec a 0%Srng) as [Haz| Haz]; [ apply IHl | cbn ].\nrewrite app_nth2; rewrite rev_length; [ | now unfold ge ].\nrewrite Nat.sub_diag; cbn.\nnow destruct (srng_eq_dec a 0%Srng).\nQed.\n\nDefinition polyn_of_list l :=\n  mk_polyn (norm_polyn_list l) (polyn_of_list_prop l).\n\nDefinition list_of_polyn (P : polynomial T) :=\n  polyn_list P.\n\nDefinition polyn_of_const x := polyn_of_list [x].\n\nTheorem fold_polyn_of_const : ∀ c,\n  polyn_of_list [c] = polyn_of_const c.\nProof. easy. Qed.\n\n(*\nEnd in_ring.\n\nRequire Import ZArith.\nOpen Scope Z_scope.\n\nTheorem Z_neq_1_0 : 1%Z ≠ 0%Z. Proof. easy. Qed.\n\nDefinition Z_sring_dec_prop T :=\n  {| srng_eq_dec := Z.eq_dec;\n     srng_1_neq_0 := Z_neq_1_0 |}.\n\nCompute let ro := Z_ring_op in let sdp := Z_sring_dec_prop T in polyn_of_list [3; 4; 7; 0].\nCompute let ro := Z_ring_op in let sdp := Z_sring_dec_prop T in list_of_polyn (polyn_of_list [3; 4; 7; 0]).\nCompute let ro := Z_ring_op in let sdp := Z_sring_dec_prop T in list_of_polyn (polyn_of_list [0]).\n*)\n\n(* monomial *)\n\nDefinition _x := polyn_of_list [0; 1]%Srng.\n\n(* addition of polynomials *)\n\nFixpoint polyn_list_add la lb :=\n  match la with\n  | [] => lb\n  | a :: la' =>\n      match lb with\n      | [] => la\n      | b :: lb' => (a + b)%Srng :: polyn_list_add la' lb'\n      end\n  end.\n\nDefinition polyn_add P Q :=\n  polyn_of_list (polyn_list_add (polyn_list P) (polyn_list Q)).\n\n(*\nEnd in_ring.\n\nRequire Import ZArith.\nOpen Scope Z_scope.\n\nTheorem Z_neq_1_0 : 1%Z ≠ 0%Z. Proof. easy. Qed.\n\nDefinition Z_sring_dec_prop T :=\n  {| srng_eq_dec := Z.eq_dec;\n     srng_1_neq_0 := Z_neq_1_0 |}.\n\nCompute let ro := Z_ring_op in let sdp := Z_sring_dec_prop T in list_of_polyn (polyn_add (polyn_of_list [3; 4; 7; 0])\n(polyn_of_list [7; 0; 0; 22; -4])).\nCompute let ro := Z_ring_op in let sdp := Z_sring_dec_prop T in list_of_polyn (polyn_add (polyn_of_list [3; 4; 7; 0])\n(polyn_of_list [7; 2; -7])).\n*)\n\n(* opposite of a polynomial *)\n\nTheorem polyn_opp_prop_test : ∀ P,\n  polyn_prop_test (λ i, nth i (map rng_opp (polyn_list P)) 0%Srng)\n    (length (map rng_opp (polyn_list P))) = true.\nProof.\nintros.\nrewrite map_length.\ndestruct P as (l, p).\nunfold polyn_prop_test in p |-*; cbn.\nremember (length l) as len eqn:Hlen.\nsymmetry in Hlen.\ndestruct len; [ easy | ].\nrewrite (List_map_nth_in _ 0%Srng); [ | flia Hlen ].\ndestruct (srng_eq_dec (nth len l 0%Srng) 0%Srng) as [H| Hz]; [ easy | ].\nclear p.\ndestruct (srng_eq_dec (- nth len l 0%Srng)%Rng 0%Srng) as [H| H]; [ | easy ].\nrewrite <- rng_opp_involutive in H.\napply rng_opp_inj in H.\nnow rewrite rng_opp_0 in H.\nQed.\n\nDefinition polyn_opp P :=\n  mk_polyn (map rng_opp (polyn_list P)) (polyn_opp_prop_test P).\n\n(* subtraction of polynomials *)\n\nDefinition polyn_sub P Q :=\n  polyn_add P (polyn_opp Q).\n\nTheorem fold_polyn_sub : ∀ P Q, polyn_add P (polyn_opp Q) = polyn_sub P Q.\nProof. easy. Qed.\n\n(* multiplication of polynomials *)\n\nDefinition polyn_list_convol_mul la lb i :=\n  (Σ (j = 0, i), nth j la 0 * nth (i - j) lb 0)%Srng.\n\nDefinition polyn_list_mul la lb :=\n  map (polyn_list_convol_mul la lb) (seq 0 (length la + length lb - 1)).\n\nDefinition polyn_mul P Q :=\n  polyn_of_list (polyn_list_mul (polyn_list P) (polyn_list Q)).\n\n(*\nEnd in_ring.\n\nRequire Import ZArith.\nOpen Scope Z_scope.\n\nTheorem Z_neq_1_0 : 1%Z ≠ 0%Z. Proof. easy. Qed.\n\nDefinition Z_sring_dec_prop T :=\n  {| srng_eq_dec := Z.eq_dec;\n     srng_1_neq_0 := Z_neq_1_0 |}.\n\nCompute let ro := Z_ring_op in let sdp := Z_sring_dec_prop T in polyn_list_mul [1] [3; 4].\nCompute let ro := Z_ring_op in let sdp := Z_sring_dec_prop T in polyn_list_mul [1; 1; 0] [-1; 1; 0].\nCompute let ro := Z_ring_op in let sdp := Z_sring_dec_prop T in list_of_polyn (polyn_mul (polyn_of_list [1; 1]) (polyn_of_list [-1; 1])).\n*)\n\n(* polynomial syntax *)\n\nDeclare Scope polynomial_scope.\nDelimit Scope polynomial_scope with P.\n\nNotation \"0\" := (polyn_of_list []) : polynomial_scope.\nNotation \"1\" := (polyn_of_const 1%Srng) : polynomial_scope.\nNotation \"P + Q\" := (polyn_add P Q) : polynomial_scope.\nNotation \"P - Q\" := (polyn_sub P Q) : polynomial_scope.\nNotation \"P * Q\" := (polyn_mul P Q) : polynomial_scope.\nNotation \"- P\" := (polyn_opp P) : polynomial_scope.\n\nDeclare Scope polyn_list_scope.\nDelimit Scope polyn_list_scope with PL.\n\n(*\nNotation \"0\" := ([]) : polyn_list_scope.\n*)\nNotation \"1\" := ([1%Srng]) : polyn_list_scope.\nNotation \"la + lb\" := (polyn_list_add la lb) : polyn_list_scope.\nNotation \"la * lb\" := (polyn_list_mul la lb) : polyn_list_scope.\n\n(*\nNotation \"'Σ' ( i = b , e ) , g\" :=\n  (iter_seq b e (λ c i, (c + g)%P) 0%P)\n  (at level 45, i at level 0, b at level 60, e at level 60) :\n     polynomial_scope.\n\nNotation \"'Π' ( i = b , e ) , g\" :=\n  (iter_seq b e (λ c i, (c * g)%P) 1%P)\n  (at level 45, i at level 0, b at level 60, e at level 60) :\n     polynomial_scope.\n*)\n\nArguments norm_polyn_list l%PL.\nArguments polyn_coeff {T so sdp} P%P i%nat.\nArguments polyn_degree {T so sdp} P%P.\nArguments polyn_of_const x%Rng.\n\n(* semiring and ring of polynomials *)\n\nDefinition polyn_semiring_op : semiring_op (polynomial T) :=\n  {| srng_zero := polyn_of_list [];\n     srng_one := polyn_of_list [1%Srng];\n     srng_add := polyn_add;\n     srng_mul := polyn_mul |}.\n\nDefinition polyn_ring_op : ring_op (polynomial T) :=\n  {| rng_opp := polyn_opp |}.\n\nExisting Instance polyn_semiring_op.\nExisting Instance polyn_ring_op.\n\n(* degree of opposite of a polynomial *)\n\nTheorem polyn_degree_opp : ∀ P, polyn_degree (- P) = polyn_degree P.\nProof.\nintros.\nunfold polyn_degree, polyn_degree_plus_1.\nnow cbn; rewrite map_length.\nQed.\n\n(* equality of polynomials ↔ equality of their lists *)\n\nTheorem polyn_eq : ∀ P Q,\n  polyn_list P = polyn_list Q\n  → P = Q.\nProof.\nintros (PL, PP) (QL, QP) HPQ.\ncbn in HPQ |-*.\nsubst QL.\nf_equal.\napply (Eqdep_dec.UIP_dec Bool.bool_dec).\nQed.\n\n(* often encountered cases: \"if 0=0\" and if \"1=0\" *)\n\nTheorem if_0_eq_0 : ∀ A (a b : A),\n  (if srng_eq_dec 0 0 then a else b) = a.\nintros.\nnow destruct (srng_eq_dec 0 0).\nQed.\n\nTheorem if_1_eq_0 : ∀ A (a b : A),\n  (if srng_eq_dec 1 0 then a else b) = b.\nintros.\ndestruct (srng_eq_dec 1 0) as [H| H]; [ now apply srng_1_neq_0 in H | ].\neasy.\nQed.\n\n(* polynomials ring properties *)\n\nTheorem polyn_of_opp_const : ∀ c,\n  polyn_of_const (- c) = (- polyn_of_const c)%P.\nProof.\nintros.\napply polyn_eq; cbn.\ndestruct (srng_eq_dec c 0) as [Hcz| Hcz]. {\n  rewrite Hcz.\n  now rewrite rng_opp_0, if_0_eq_0.\n}\ndestruct (srng_eq_dec (- c)%Rng 0) as [Hocz| Hocz]; [ | easy ].\napply (f_equal rng_opp) in Hocz.\nnow rewrite rng_opp_involutive, rng_opp_0 in Hocz.\nQed.\n\nTheorem polyn_list_add_comm : ∀ la lb,\n  polyn_list_add la lb = polyn_list_add lb la.\nProof.\nintros.\nrevert lb.\ninduction la as [| a]; intros; [ now destruct lb | ].\ndestruct lb as [| b]; [ easy | cbn ].\nf_equal; [ | apply IHla ].\napply srng_add_comm.\nQed.\n\nTheorem polyn_add_comm : ∀ P Q : polynomial T, (P + Q)%P = (Q + P)%P.\nProof.\nintros (PL, PP) (QL, QP); cbn.\napply polyn_eq; cbn.\nf_equal; f_equal; f_equal.\nclear PP QP.\napply polyn_list_add_comm.\nQed.\n\nTheorem polyn_list_add_0_l : ∀ la, polyn_list_add [] la = la.\nProof. easy. Qed.\n\nTheorem polyn_list_add_0_r : ∀ la, polyn_list_add la [] = la.\nProof.\nintros; rewrite polyn_list_add_comm; apply polyn_list_add_0_l.\nQed.\n\nTheorem polyn_add_0_l : ∀ P, (0 + P)%P = P.\nProof.\nintros (la, Pa); cbn.\napply polyn_eq.\ncbn - [ polyn_list_add ].\nrewrite polyn_list_add_0_l.\nunfold norm_polyn_list.\nrewrite <- rev_involutive; f_equal.\nrewrite <- (rev_involutive la) in Pa.\nrewrite rev_length in Pa.\nremember (rev la) as l; clear la Heql.\nrename l into la.\nunfold polyn_prop_test in Pa.\ndestruct la as [| a]; [ easy | ].\ncbn - [ nth ] in Pa |-*.\ndestruct (srng_eq_dec a 0%Srng) as [Haz| Haz]; [ | easy ].\nsubst a; exfalso.\nrewrite app_nth2 in Pa; [ | now unfold ge; rewrite rev_length ].\nrewrite rev_length, Nat.sub_diag in Pa; cbn in Pa.\nnow rewrite if_0_eq_0 in Pa.\nQed.\n\nTheorem polyn_add_0_r : ∀ P, (P + 0)%P = P.\nProof.\nintros.\nrewrite polyn_add_comm.\napply polyn_add_0_l.\nQed.\n\nTheorem strip_0s_idemp : ∀ la,\n  strip_0s (strip_0s la) =\n  strip_0s la.\nProof.\nintros.\ninduction la as [| a]; [ easy | cbn ].\ndestruct (srng_eq_dec a 0%Srng) as [Haz| Haz]; [ easy | cbn ].\nnow destruct (srng_eq_dec a 0%Srng).\nQed.\n\nTheorem strip_0s_app : ∀ la lb,\n  strip_0s (la ++ lb) =\n    match strip_0s la with\n    | [] => strip_0s lb\n    | a :: la' => a :: la' ++ lb\n    end.\nProof.\nintros.\nremember (strip_0s la) as lc eqn:Hlc; symmetry in Hlc.\ndestruct lc as [| c]. {\n  induction la as [| a]; [ easy | ].\n  cbn in Hlc |-*.\n  destruct (srng_eq_dec a 0%Srng) as [Haz| Haz]; [ now apply IHla | easy ].\n}\nrevert lb c lc Hlc.\ninduction la as [| a]; intros; [ easy | cbn ].\ndestruct (srng_eq_dec a 0%Srng) as [Haz| Haz]. {\n  subst a; cbn in Hlc.\n  rewrite if_0_eq_0 in Hlc.\n  apply IHla, Hlc.\n}\ncbn in Hlc.\ndestruct (srng_eq_dec a 0%Srng) as [H| H]; [ easy | clear H ].\nnow injection Hlc; clear Hlc; intros; subst c lc.\nQed.\n\nTheorem strip_0s_repeat_0s : ∀ n,\n  strip_0s (repeat 0%Srng n) = [].\nProof.\nintros.\ninduction n; [ easy | cbn ].\nnow rewrite if_0_eq_0.\nQed.\n\nTheorem eq_strip_0s_nil : ∀ la,\n  strip_0s la = [] ↔ la = repeat 0%Srng (length la).\nProof.\nintros.\nsplit. {\n  intros Hla.\n  induction la as [| a]; [ easy | ].\n  cbn in Hla.\n  destruct (srng_eq_dec a 0%Srng) as [Haz| Haz]; [ | easy ].\n  subst a.\n  specialize (IHla Hla).\n  now cbn; f_equal.\n} {\n  intros H; rewrite H.\n  apply strip_0s_repeat_0s.\n}\nQed.\n\nTheorem norm_polyn_list_app : ∀ la lb,\n  norm_polyn_list (la ++ lb) =\n  match norm_polyn_list lb with\n  | [] => norm_polyn_list la\n  | lc => la ++ lc\n  end.\nProof.\nintros.\nunfold norm_polyn_list.\nrewrite rev_app_distr.\nrewrite strip_0s_app.\nremember (strip_0s (rev lb)) as lc eqn:Hlc.\nsymmetry in Hlc.\ndestruct lc as [| c]; [ easy | ].\nrewrite app_comm_cons.\nrewrite rev_app_distr.\nrewrite rev_involutive.\nremember (rev (c :: lc)) as ld eqn:Hld.\nsymmetry in Hld.\ndestruct ld as [| d]; [ | easy ].\nnow apply List_eq_rev_nil in Hld.\nQed.\n\nTheorem polyn_list_add_repeat_0s_l : ∀ n la,\n  polyn_list_add (repeat 0%Srng n) la = la ++ repeat 0%Srng (n - length la).\nProof.\nintros.\nrevert la.\ninduction n; intros; [ now rewrite app_nil_r | ].\ndestruct la as [| a]; [ easy | cbn ].\nrewrite srng_add_0_l; f_equal.\napply IHn.\nQed.\n\nTheorem neq_strip_0s_cons_0 : ∀ la lb,\n  strip_0s la ≠ 0%Srng :: lb.\nProof.\nintros * Hll.\nrevert lb Hll.\ninduction la as [| a]; intros; [ easy | cbn ].\ncbn in Hll.\ndestruct (srng_eq_dec a 0%Srng) as [Haz| Haz]. {\n  now apply IHla in Hll.\n}\nnow injection Hll; intros.\nQed.\n\nTheorem polyn_list_add_app_l : ∀ la lb lc,\n  polyn_list_add (la ++ lb) lc =\n  polyn_list_add la (firstn (length la) lc) ++\n  polyn_list_add lb (skipn (length la) lc).\nProof.\nintros.\nrevert la lb.\ninduction lc as [| c]; intros; cbn. {\n  rewrite firstn_nil, skipn_nil.\n  now do 3 rewrite polyn_list_add_0_r.\n}\ndestruct la as [| a]; [ easy | cbn ].\nf_equal; apply IHlc.\nQed.\n\nTheorem polyn_list_add_app_r : ∀ la lb lc,\n  polyn_list_add la (lb ++ lc) =\n  polyn_list_add (firstn (length lb) la) lb ++\n  polyn_list_add (skipn (length lb) la) lc.\nProof.\nintros.\ndo 3 rewrite polyn_list_add_comm.\nrewrite polyn_list_add_app_l.\nrewrite (polyn_list_add_comm lb).\nrewrite (polyn_list_add_comm lc).\neasy.\nQed.\n\nTheorem List_eq_app_repeat : ∀ A la lb n (c : A),\n  la ++ lb = repeat c n\n  → la = repeat c (length la) ∧ lb = repeat c (length lb) ∧\n     length la + length lb = n.\nProof.\nintros A * Hll.\nrevert n Hll.\ninduction la as [| a]; intros; cbn. {\n  cbn in Hll; subst lb; cbn.\n  now rewrite repeat_length.\n}\ndestruct n; [ easy | ].\ncbn in Hll.\ninjection Hll; clear Hll; intros Hll H; subst c.\nspecialize (IHla n Hll).\ndestruct IHla as (H1 & H2 & H3).\nnow rewrite <- H1, <- H2, H3.\nQed.\n\nTheorem polyn_list_add_length : ∀ la lb,\n  length (la + lb)%PL = max (length la) (length lb).\nProof.\nintros.\nrevert lb.\ninduction la as [| a]; intros; [ easy | cbn ].\ndestruct lb as [| b]; [ easy | cbn ].\nf_equal; apply IHla.\nQed.\n\nTheorem polyn_list_mul_length : ∀ la lb,\n  length (la * lb)%PL = length la + length lb - 1.\nProof.\nintros.\nunfold polyn_list_mul; cbn.\nnow rewrite map_length, seq_length.\nQed.\n\nTheorem norm_polyn_list_involutive : ∀ la,\n  norm_polyn_list (norm_polyn_list la) = norm_polyn_list la.\nProof.\nintros.\ninduction la as [| a] using rev_ind; [ easy | ].\nrewrite norm_polyn_list_app.\nremember (norm_polyn_list [a]) as x eqn:Hx.\ncbn in Hx; subst x.\ndestruct (srng_eq_dec a 0) as [Haz| Haz]; [ easy | ].\ncbn - [ norm_polyn_list ].\nrewrite norm_polyn_list_app; cbn.\nnow destruct (srng_eq_dec a 0).\nQed.\n\nTheorem norm_polyn_list_add_idemp_l : ∀ la lb,\n  norm_polyn_list (polyn_list_add (norm_polyn_list la) lb) =\n  norm_polyn_list (polyn_list_add la lb).\nProof.\nintros.\nunfold norm_polyn_list; f_equal.\nrevert la.\ninduction lb as [| b]; intros. {\n  do 2 rewrite polyn_list_add_0_r.\n  now rewrite rev_involutive, strip_0s_idemp.\n}\ncbn.\ndestruct la as [| a]; [ easy | cbn ].\ndo 2 rewrite strip_0s_app; cbn.\nrewrite <- IHlb.\nremember (strip_0s (rev la)) as lc eqn:Hlc; symmetry in Hlc.\ndestruct lc as [| c]. {\n  cbn.\n  destruct (srng_eq_dec a 0) as [Haz| Haz]. {\n    subst a; rewrite srng_add_0_l; cbn.\n    now rewrite strip_0s_app.\n  }\n  cbn.\n  now rewrite strip_0s_app.\n}\ncbn.\nrewrite rev_app_distr; cbn.\nnow rewrite strip_0s_app.\nQed.\n\nTheorem norm_polyn_list_add_idemp_r : ∀ la lb,\n  norm_polyn_list (polyn_list_add la (norm_polyn_list lb)) =\n  norm_polyn_list (polyn_list_add la lb).\nProof.\nintros.\nrewrite polyn_list_add_comm.\nrewrite norm_polyn_list_add_idemp_l.\nnow rewrite polyn_list_add_comm.\nQed.\n\nTheorem polyn_list_add_assoc : ∀ la lb lc,\n  polyn_list_add la (polyn_list_add lb lc) =\n  polyn_list_add (polyn_list_add la lb) lc.\nProof.\nintros.\nrevert lb lc.\ninduction la; intros; [ easy | ].\ndestruct lb; [ easy | cbn ].\ndestruct lc; [ easy | cbn ].\nrewrite srng_add_assoc.\nf_equal.\napply IHla.\nQed.\n\nTheorem polyn_add_assoc : ∀ P Q R, (P + (Q + R) = (P + Q) + R)%P.\nProof.\nintros (la, Pa) (lb, Pb) (lc, Pc).\napply polyn_eq.\ncbn - [ polyn_list_add ].\nrewrite norm_polyn_list_add_idemp_l.\nrewrite norm_polyn_list_add_idemp_r.\nf_equal.\napply polyn_list_add_assoc.\nQed.\n\nTheorem polyn_add_add_swap : ∀ P Q R, (P + Q + R = P + R + Q)%P.\nProof.\nintros.\ndo 2 rewrite <- polyn_add_assoc.\nnow rewrite (polyn_add_comm R).\nQed.\n\nTheorem polyn_list_convol_c_mul_comm :\n  if srng_is_comm then\n    ∀ la lb i,\n    polyn_list_convol_mul la lb i = polyn_list_convol_mul lb la i\n  else True.\nProof.\nspecialize srng_c_mul_comm as srng_mul_comm.\ndestruct srng_is_comm; [ | easy ].\nintros.\nunfold polyn_list_convol_mul.\nrewrite srng_summation_rtl; [ | easy ].\napply srng_summation_eq_compat.\nintros j Hj.\nrewrite Nat.add_0_r.\nrewrite Nat_sub_sub_assoc; [ | flia Hj ].\nrewrite Nat.add_comm, Nat.add_sub.\napply srng_mul_comm.\nQed.\n\nTheorem polyn_list_c_mul_comm :\n  if srng_is_comm then\n    ∀ la lb, polyn_list_mul la lb = polyn_list_mul lb la\n  else True.\nProof.\nspecialize polyn_list_convol_c_mul_comm as polyn_list_convol_mul_comm.\ndestruct srng_is_comm; [ | easy ].\nintros la lb.\nunfold polyn_list_mul.\nrewrite (Nat.add_comm (length lb)).\napply map_ext.\napply polyn_list_convol_mul_comm.\nQed.\n\nTheorem polyn_c_mul_comm :\n  if srng_is_comm then ∀ P Q, (P * Q = Q * P)%P else True.\nProof.\nspecialize polyn_list_c_mul_comm as polyn_list_mul_comm.\ndestruct srng_is_comm; [ | easy ].\nintros.\nunfold polyn_mul.\napply polyn_eq.\nf_equal; f_equal.\napply polyn_list_mul_comm.\nQed.\n\nTheorem strip_0s_map_0 : ∀ A (la lb : list A),\n  strip_0s (map (λ _, 0%Srng) la) = strip_0s (map (λ _, 0%Srng) lb).\nProof.\nintros A *.\nrevert lb.\ninduction la as [| a]; intros; cbn. {\n  induction lb as [| b]; [ easy | cbn ].\n  now rewrite if_0_eq_0.\n}\nnow rewrite if_0_eq_0.\nQed.\n\nTheorem polyn_list_convol_mul_0_l : ∀ n la i,\n  polyn_list_convol_mul (repeat 0%Srng n) la i = 0%Srng.\nProof.\nintros.\nunfold polyn_list_convol_mul.\napply all_0_srng_summation_0; [ easy | ].\nintros j ahj.\nremember (@srng_zero T so) as z.\nreplace (nth j (repeat z n) z) with z; subst z. 2: {\n  symmetry; clear.\n  revert j.\n  induction n; intros; cbn; [ now destruct j | ].\n  destruct j; [ easy | ].\n  apply IHn.\n}\napply srng_mul_0_l.\nQed.\n\nTheorem polyn_list_convol_mul_0_r : ∀ n la i,\n  polyn_list_convol_mul la (repeat 0%Srng n) i = 0%Srng.\nProof.\nspecialize srng_nc_mul_0_r as srng_mul_0_r.\nspecialize polyn_list_convol_c_mul_comm as polyn_list_convol_mul_comm.\ndestruct srng_is_comm. {\n  intros.\n  rewrite polyn_list_convol_mul_comm.\n  apply polyn_list_convol_mul_0_l.\n}\nintros.\nunfold polyn_list_convol_mul.\napply all_0_srng_summation_0; [ easy | ].\nintros j ahj.\nremember (@srng_zero T so) as z.\nreplace (nth (i - j) (repeat z n) z) with z; subst z. 2: {\n  symmetry; clear.\n  remember (i - j) as k; clear Heqk.\n  revert k.\n  induction n; intros; cbn; [ now destruct k | ].\n  destruct k; [ easy | ].\n  apply IHn.\n}\napply srng_mul_0_r.\nQed.\n\nTheorem map_polyn_list_convol_mul_0_l : ∀ n la li,\n  map (polyn_list_convol_mul (repeat 0%Srng n) la) li =\n  repeat 0%Srng (length li).\nProof.\nintros.\ninduction li as [| i]; [ easy | ].\ncbn - [ polyn_list_convol_mul ].\nrewrite IHli; f_equal.\napply polyn_list_convol_mul_0_l.\nQed.\n\nTheorem map_polyn_list_convol_mul_0_r : ∀ n la li,\n  map (polyn_list_convol_mul la (repeat 0%Srng n)) li =\n  repeat 0%Srng (length li).\nProof.\nintros.\ninduction li as [| i]; [ easy | ].\ncbn - [ polyn_list_convol_mul ].\nrewrite IHli; f_equal.\napply polyn_list_convol_mul_0_r.\nQed.\n\nTheorem norm_polyn_list_repeat_0 : ∀ n,\n  norm_polyn_list (repeat 0%Srng n) = [].\nProof.\nintros.\ninduction n; [ easy | ].\nrewrite List_repeat_succ_app.\nrewrite norm_polyn_list_app; cbn.\nnow rewrite if_0_eq_0.\nQed.\n\nTheorem map_polyn_list_convol_c_mul_comm :\n  if srng_is_comm then\n    ∀ la lb ln,\n    map (polyn_list_convol_mul la lb) ln =\n    map (polyn_list_convol_mul lb la) ln\n  else True.\nProof.\nspecialize polyn_list_convol_c_mul_comm as polyn_list_convol_mul_comm.\ndestruct srng_is_comm; [ | easy ].\nintros.\napply map_ext_in.\nintros i Hi.\napply polyn_list_convol_mul_comm.\nQed.\n\nTheorem map_polyn_list_convol_mul_cons_r_gen : ∀ b la lb sta len,\n  map (polyn_list_convol_mul la (b :: lb)) (seq sta len) =\n  polyn_list_add\n    (map (λ n, nth n la 0 * b) (seq sta len))%Srng\n    (map\n       (λ n,\n          if zerop n then 0%Srng\n          else (Σ (j = 0, n - 1), nth j la 0 * nth (n - j - 1) lb 0)%Srng)\n       (seq sta len)).\nProof.\nintros.\nunfold polyn_list_convol_mul.\nrevert sta.\ninduction len; intros; [ easy | ].\nrewrite List_seq_succ_r.\nrewrite map_app, IHlen.\ndo 2 rewrite map_app.\nrewrite polyn_list_add_app_r, map_length.\nrewrite firstn_app, map_length, Nat.sub_diag, firstn_O.\nrewrite app_nil_r.\nrewrite skipn_app, map_length, Nat.sub_diag, skipn_O.\nrewrite polyn_list_add_app_l.\nrewrite skipn_length.\ndo 2 rewrite List_firstn_map.\nrewrite map_length.\ndo 2 rewrite List_skipn_map.\nrewrite seq_length.\nrewrite List_firstn_seq, Nat.min_id.\nrewrite List_skipn_seq; [ | easy ].\nrewrite Nat.sub_diag.\nrewrite polyn_list_add_0_l.\nremember (firstn 0 _) as x; cbn in Heqx; subst x.\nremember (skipn 0 _) as x; cbn in Heqx; subst x.\nremember (map _ []) as x; cbn in Heqx; subst x.\nrewrite app_nil_l.\nf_equal.\ncbn - [ nth seq sub ].\nf_equal.\ndestruct (Nat.eq_dec (sta + len) 0) as [Hz| Hz]. {\n  rewrite Hz; cbn.\n  apply srng_add_comm.\n}\nremember (sta + len) as n eqn:Hn.\ndestruct n; [ easy | ].\ncbn - [ nth seq sub ].\nrewrite srng_add_comm.\nreplace (S n - 1) with n by flia.\nrewrite srng_summation_split_last; [ | apply Nat.le_0_l ].\nrewrite Nat.sub_diag.\nf_equal.\nrewrite srng_summation_succ_succ.\napply srng_summation_eq_compat.\nintros i Hi.\nrewrite Nat.sub_succ, Nat.sub_0_r.\nf_equal.\nreplace (S n - i) with (S (n - i)) by flia Hi.\nnow rewrite Nat.sub_succ, Nat.sub_0_r.\nQed.\n\nTheorem map_polyn_list_convol_mul_cons_r : ∀ b la lb len,\n  map (polyn_list_convol_mul la (b :: lb)) (seq 0 (S len)) =\n  polyn_list_add (map (λ n, (nth n la 0 * b)%Srng) (seq 0 (S len)))\n    (0%Srng :: map (λ n, polyn_list_convol_mul la lb (n - 1)) (seq 1 len)).\nProof.\nintros.\nrewrite map_polyn_list_convol_mul_cons_r_gen.\nf_equal.\nrewrite <- (Nat.add_1_l len).\nrewrite seq_app.\ncbn - [ nth seq sub ].\nrewrite map_app.\nreplace (seq 0 1) with [0] by easy.\ncbn - [ nth seq sub ].\nf_equal.\napply map_ext_in.\nintros i Hi.\napply in_seq in Hi.\ndestruct (zerop i) as [H| H]; [ flia Hi H | ].\napply srng_summation_eq_compat.\nintros j Hj.\nnow rewrite Nat_sub_sub_swap.\nQed.\n\n(* (a+xP)Q = aQ+x(PQ) *)\n(* flemme de devoir reprendre map_polyn_list_convol_mul_cons_r_gen\n   et map_polyn_list_convol_mul_cons_r; alors, pour l'instant, je\n   dis que ça ne marche que si c'est commutatif *)\nTheorem map_polyn_list_convol_c_mul_cons_l :\n  if srng_is_comm then\n    ∀ a la lb len,\n    map (polyn_list_convol_mul (a :: la) lb) (seq 0 (S len)) =\n    polyn_list_add (map (λ n, (a * nth n lb 0)%Srng) (seq 0 (S len)))\n      (0%Srng :: map (λ n, polyn_list_convol_mul la lb (n - 1)) (seq 1 len))\n  else True.\nProof.\nspecialize srng_c_mul_comm as srng_mul_comm.\nspecialize map_polyn_list_convol_c_mul_comm as map_polyn_list_convol_mul_comm.\nspecialize polyn_list_convol_c_mul_comm as polyn_list_convol_mul_comm.\ndestruct srng_is_comm; [ | easy ].\nintros.\nrewrite map_polyn_list_convol_mul_comm.\nrewrite map_polyn_list_convol_mul_cons_r.\nerewrite map_ext_in. 2: {\n  intros i Hi.\n  apply srng_mul_comm.\n}\nf_equal; f_equal.\nerewrite map_ext_in. 2: {\n  intros i Hi.\n  apply polyn_list_convol_mul_comm.\n}\neasy.\nQed.\n\nTheorem map_polyn_list_convol_mul_const_l : ∀ n a ln lb,\n  map (λ i, polyn_list_convol_mul (a :: repeat 0%Srng n) lb i) ln =\n  map (λ i, a * nth i lb 0)%Srng ln.\nProof.\nintros.\nunfold polyn_list_convol_mul.\napply map_ext_in.\nintros i Hi.\ndestruct i; [ cbn; apply srng_add_0_l | ].\nrewrite srng_summation_split_first; [ | easy | apply Nat.le_0_l ].\nrewrite all_0_srng_summation_0; [ | easy | ]. 2: {\n  intros j Hj.\n  destruct j; [ easy | cbn ].\n  rewrite List_nth_repeat.\n  destruct (lt_dec j n); apply srng_mul_0_l.\n}\nnow rewrite Nat.sub_0_r, srng_add_0_r.\nQed.\n\nTheorem all_0_norm_polyn_list_map_0 : ∀ A (ln : list A) f,\n  (∀ n, n ∈ ln → f n = 0%Srng)\n  ↔ norm_polyn_list (map f ln) = [].\nProof.\nintros A *.\nsplit; intros Hf. {\n  unfold norm_polyn_list.\n  apply List_eq_rev_nil.\n  rewrite rev_involutive.\n  induction ln as [| n]; [ easy | cbn ].\n  rewrite strip_0s_app.\n  rewrite IHln. 2: {\n    intros i Hi.\n    now apply Hf; right.\n  }\n  cbn.\n  destruct (srng_eq_dec (f n) 0) as [H| H]; [ easy | ].\n  exfalso; apply H.\n  now apply Hf; left.\n} {\n  intros n Hn.\n  unfold norm_polyn_list in Hf.\n  apply List_eq_rev_nil in Hf.\n  apply eq_strip_0s_nil in Hf.\n  rewrite rev_length, map_length in Hf.\n  apply List_eq_rev_l in Hf.\n  apply (in_map f) in Hn.\n  rewrite Hf in Hn.\n  apply in_rev in Hn.\n  now apply repeat_spec in Hn.\n}\nQed.\n\nTheorem length_strip_0s_le : ∀ la, length (strip_0s la) ≤ length la.\nProof.\nintros.\ninduction la as [| a]; [ easy | cbn ].\ndestruct (srng_eq_dec a 0) as [Haz| Haz]; [ | easy ].\ntransitivity (length la); [ easy | ].\napply Nat.le_succ_diag_r.\nQed.\n\nTheorem norm_polyn_list_cons_0 : ∀ la lb,\n  norm_polyn_list la = norm_polyn_list lb\n  → norm_polyn_list (0%Srng :: la) =\n     norm_polyn_list (0%Srng :: lb).\nProof.\nintros * Hll.\nunfold norm_polyn_list in Hll |-*.\nf_equal.\napply List_rev_inj in Hll; cbn.\ndo 2 rewrite strip_0s_app.\nnow rewrite Hll.\nQed.\n\nTheorem polyn_list_convol_mul_more : ∀ n la lb i len,\n  length la + length lb - 1 ≤ i + len\n  → norm_polyn_list (map (polyn_list_convol_mul la lb) (seq i len)) =\n    norm_polyn_list (map (polyn_list_convol_mul la lb) (seq i (len + n))).\nProof.\nintros.\ninduction n; [ now rewrite Nat.add_0_r | ].\nrewrite Nat.add_succ_r.\nrewrite List_seq_succ_r.\nrewrite map_app.\nrewrite norm_polyn_list_app.\nrewrite <- IHn.\ncbn - [ norm_polyn_list nth seq sub ].\nunfold polyn_list_convol_mul at 2.\nrewrite all_0_srng_summation_0; [ now cbn; rewrite if_0_eq_0 | easy | ].\nintros j (_, Hj).\ndestruct (le_dec (length la) j) as [H1| H1]. {\n  rewrite nth_overflow; [ | easy ].\n  apply srng_mul_0_l.\n} {\n  apply Nat.nle_gt in H1.\n  destruct (le_dec (length lb) (i + (len + n) - j)) as [H2| H2]. {\n    rewrite (nth_overflow lb); [ | easy ].\n    apply srng_mul_0_r.\n  }\n  exfalso; apply H2; clear H2.\n  flia H H1.\n}\nQed.\n\nFixpoint map_seq A (f : nat → A) b len :=\n  match len with\n  | 0 => []\n  | S len' => f b :: map_seq f (S b) len'\n  end.\n\nTheorem eq_map_seq : ∀ A (f : nat → A) b len,\n  map f (seq b len) = map_seq f b len.\nProof.\nintros A *.\nrevert b.\ninduction len; intros; [ easy | cbn ].\nnow rewrite IHlen.\nQed.\n\nTheorem norm_polyn_list_app_repeat_0 : ∀ la,\n  la =\n    norm_polyn_list la ++\n    repeat 0%Rng (length la - length (norm_polyn_list la)).\nProof.\nintros.\ninduction la as [| a]; [ easy | ].\ncbn.\nrewrite rev_length.\nrewrite strip_0s_app.\nremember (strip_0s (rev la)) as lb eqn:Hlb; symmetry in Hlb.\ndestruct lb as [| b]. {\n  cbn.\n  destruct (srng_eq_dec a 0) as [Haz| Haz]. {\n    cbn; subst a; f_equal.\n    apply eq_strip_0s_nil in Hlb.\n    apply List_eq_rev_l in Hlb.\n    now rewrite rev_length, List_rev_repeat in Hlb.\n  } {\n    cbn; f_equal.\n    rewrite Nat.sub_0_r.\n    apply eq_strip_0s_nil in Hlb.\n    apply List_eq_rev_l in Hlb.\n    now rewrite rev_length, List_rev_repeat in Hlb.\n  }\n} {\n  cbn.\n  rewrite rev_app_distr; cbn; f_equal.\n  replace (rev lb ++ [b]) with (rev (b :: lb)) by easy.\n  rewrite <- Hlb.\n  rewrite app_length; cbn.\n  rewrite Nat.add_1_r.\n  replace (S (length lb)) with (length (b :: lb)) by easy.\n  rewrite <- Hlb.\n  now rewrite <- (rev_length (strip_0s _)).\n}\nQed.\n\nTheorem polyn_list_convol_mul_app_rep_0_l : ∀ la lb i len n,\n  norm_polyn_list\n    (map (polyn_list_convol_mul (la ++ repeat 0%Srng n) lb) (seq i len)) =\n  norm_polyn_list\n    (map (polyn_list_convol_mul la lb) (seq i len)).\nProof.\nintros.\nrevert la i len.\ninduction n; intros; [ now cbn; rewrite app_nil_r | cbn ].\nremember (0%Srng) as z.\nreplace (z :: repeat z n) with ([z] ++ repeat z n) by easy.\nsubst z.\nrewrite app_assoc.\nrewrite IHn; clear n IHn.\nrevert la i.\ninduction len; intros; [ easy | ].\nrewrite <- Nat.add_1_l.\nrewrite seq_app.\ndo 2 rewrite map_app.\ndo 2 rewrite norm_polyn_list_app.\ncbn - [ norm_polyn_list nth sub ].\nrewrite IHlen.\nassert\n  (Hll :\n     polyn_list_convol_mul la lb i =\n     polyn_list_convol_mul (la ++ [0%Srng]) lb i). {\n  unfold polyn_list_convol_mul.\n  apply srng_summation_eq_compat.\n  intros j Hj.\n  destruct (lt_dec j (length la)) as [Hjla| Hjla]. {\n    now rewrite app_nth1.\n  }\n  apply Nat.nlt_ge in Hjla.\n  rewrite (nth_overflow la); [ | easy ].\n  rewrite app_nth2; [ | easy ].\n  destruct (Nat.eq_dec j (length la)) as [Hjla2| Hjla2]. {\n    now rewrite Hjla2, Nat.sub_diag.\n  }\n  symmetry.\n  rewrite nth_overflow; [ easy | cbn; flia Hjla Hjla2 ].\n}\nnow rewrite Hll.\nQed.\n\nTheorem norm_polyn_list_cons_norm : ∀ a la lb i len,\n  length (a :: la) + length lb - 1 ≤ i + len\n  → norm_polyn_list\n      (map (polyn_list_convol_mul (a :: norm_polyn_list la) lb) (seq i len)) =\n    norm_polyn_list\n      (map (polyn_list_convol_mul (a :: la) lb) (seq i len)).\nProof.\nintros * Hlen.\nrewrite (norm_polyn_list_app_repeat_0 la) at 2.\nrewrite app_comm_cons.\nnow rewrite polyn_list_convol_mul_app_rep_0_l.\nQed.\n\nTheorem norm_polyn_list_mul_idemp_l : ∀ la lb,\n  norm_polyn_list (polyn_list_mul (norm_polyn_list la) lb) =\n  norm_polyn_list (polyn_list_mul la lb).\nProof.\nintros.\nunfold polyn_list_mul.\ndestruct la as [| a]; [ easy | ].\ncbn - [ nth seq sub ].\nrewrite strip_0s_app.\nrewrite rev_length.\nremember (strip_0s (rev la)) as lc eqn:Hlc; symmetry in Hlc.\ndestruct lc as [| c]. {\n  apply eq_strip_0s_nil in Hlc.\n  apply List_eq_rev_l in Hlc.\n  rewrite List_rev_repeat, rev_length in Hlc.\n  rewrite Hlc.\n  cbn - [ nth seq sub ].\n  destruct (srng_eq_dec a 0) as [Haz| Haz]. {\n    subst a.\n    cbn - [ nth seq sub ].\n    rewrite (map_polyn_list_convol_mul_0_l 0).\n    rewrite seq_length.\n    rewrite norm_polyn_list_repeat_0; cbn.\n    symmetry.\n    apply List_eq_rev_nil.\n    rewrite rev_involutive.\n    apply eq_strip_0s_nil.\n    rewrite repeat_length.\n    rewrite Nat.sub_0_r.\n    rewrite rev_length, map_length, seq_length.\n    symmetry.\n    apply List_eq_rev_l.\n    rewrite List_rev_repeat; symmetry.\n    rewrite (map_polyn_list_convol_mul_0_l (S (length la))).\n    now rewrite seq_length.\n  }\n  rewrite Nat.sub_succ, Nat.sub_0_r.\n  rewrite Nat.sub_succ, Nat.sub_0_r.\n  rewrite repeat_length; cbn.\n  rewrite (map_polyn_list_convol_mul_const_l 0).\n  rewrite (map_polyn_list_convol_mul_const_l (length la)).\n  rewrite Nat.add_comm.\n  rewrite seq_app, map_app.\n  rewrite norm_polyn_list_app; cbn.\n  remember (norm_polyn_list (map _ (seq _ (length la)))) as ld eqn:Hld.\n  symmetry in Hld.\n  destruct ld as [| d]; [ easy | exfalso ].\n  rewrite map_ext_in with (g := λ i, 0%Srng) in Hld. 2: {\n    intros j Hj.\n    apply in_seq in Hj.\n    rewrite nth_overflow; [ | easy ].\n    apply srng_mul_0_r.\n  }\n  now rewrite (proj1 (all_0_norm_polyn_list_map_0 _ _)) in Hld.\n}\nrewrite Nat.sub_succ, Nat.sub_0_r.\nrewrite app_comm_cons, app_length.\ncbn - [ norm_polyn_list ].\nrewrite Nat.sub_0_r.\nrewrite rev_app_distr; cbn.\ndo 2 rewrite (Nat.add_comm _ (length lb)).\nrewrite\n  (polyn_list_convol_mul_more\n     (length la - length (norm_polyn_list la))). 2: {\n  cbn; rewrite app_length, rev_length; cbn.\n  rewrite Nat.sub_0_r.\n  now rewrite Nat.add_comm.\n}\nremember (norm_polyn_list la) as x eqn:Hx.\nunfold norm_polyn_list in Hx.\nrewrite Hlc in Hx; subst x.\nrewrite rev_length.\nremember (length (c :: lc)) as x eqn:Hx.\ncbn in Hx; subst x.\nrewrite <- Nat.add_assoc.\nrewrite Nat.add_sub_assoc. 2: {\n  specialize (length_strip_0s_le (rev la)) as H.\n  now rewrite Hlc, rev_length in H.\n}\nrewrite Nat.add_1_r, (Nat.add_comm _ (length la)).\nrewrite Nat.add_sub.\nunfold norm_polyn_list at 2.\nreplace (rev lc ++ [c]) with (rev (c :: lc)) by easy.\nrewrite <- Hlc.\ndo 2 rewrite fold_norm_polyn_list.\napply norm_polyn_list_cons_norm.\ncbn.\nnow rewrite Nat.sub_0_r, Nat.add_comm.\nQed.\n\n(* flemme de faire comme norm_polyn_list_mul_idemp_l;\n   alors je dis pour l'instant que ça ne marche que\n   si srng_is_comm *)\nTheorem norm_polyn_list_c_mul_idemp_r :\n  if srng_is_comm then\n    ∀ la lb,\n    norm_polyn_list (polyn_list_mul la (norm_polyn_list lb)) =\n    norm_polyn_list (polyn_list_mul la lb)\n  else True.\nProof.\nspecialize polyn_list_c_mul_comm as polyn_list_mul_comm.\ndestruct srng_is_comm; [ | easy ].\nintros.\nrewrite polyn_list_mul_comm.\nrewrite norm_polyn_list_mul_idemp_l.\nnow rewrite polyn_list_mul_comm.\nQed.\n\nTheorem polyn_of_list_mul_1_l : ∀ la,\n  polyn_list_mul (polyn_list 1%P) la = la.\nProof.\nintros.\ncbn - [ seq ].\nrewrite if_1_eq_0.\ncbn - [ seq ].\nunfold polyn_list_mul.\nunfold length at 1.\nrewrite (Nat.add_comm 1), Nat.add_sub.\nreplace (map _ _) with (map (λ i, nth i la 0%Srng) (seq 0 (length la))). 2: {\n  apply map_ext_in.\n  intros j Hj.\n  apply in_seq in Hj.\n  unfold polyn_list_convol_mul.\n  rewrite srng_summation_split_first; [ | easy | easy ].\n  unfold nth at 2.\n  rewrite srng_mul_1_l, Nat.sub_0_r.\n  rewrite all_0_srng_summation_0; [ now rewrite srng_add_0_r | easy | ].\n  intros i Hi.\n  destruct i; [ flia Hi | ].\n  now destruct i; cbn; rewrite srng_mul_0_l.\n}\ninduction la as [| a]; [ easy | ].\ncbn - [ nth seq ].\nrewrite <- Nat.add_1_l.\nrewrite seq_app.\nrewrite map_app.\nrewrite Nat.add_0_l.\nremember (map _ (seq 0 1)) as x; cbn in Heqx; subst x.\nrewrite <- List_cons_app; f_equal.\nrewrite <- seq_shift.\nnow rewrite map_map.\nQed.\n\nTheorem polyn_mul_1_l : ∀ P, (1 * P)%P = P.\nProof.\nintros.\nunfold polyn_mul.\nrewrite polyn_of_list_mul_1_l.\napply polyn_eq; cbn.\nunfold norm_polyn_list.\ndestruct P as (la, Hla); cbn.\nunfold polyn_prop_test in Hla.\ndestruct la as [| a]; [ easy | ].\ncbn - [ nth ] in Hla.\ndestruct (srng_eq_dec (nth (length la) (a :: la) 0%Srng) 0)\n  as [Hz| Hz]; [ easy | ].\nsymmetry; apply List_eq_rev_l; symmetry.\nclear Hla.\nremember (rev (a :: la)) as lb eqn:Hlb.\nsymmetry in Hlb.\napply List_eq_rev_l in Hlb.\nrewrite Hlb in Hz.\napply (f_equal length) in Hlb.\ncbn in Hlb; rewrite rev_length in Hlb.\nrewrite rev_nth in Hz; [ | flia Hlb ].\nrewrite <- Hlb, Nat.sub_diag in Hz.\nclear Hlb.\ninduction lb as [| b]; [ easy | ].\ncbn in Hz |-*.\nnow destruct (srng_eq_dec b 0).\nQed.\n\n(* flemme de faire comme polyn_mul_1_l\n   alors je dis pour l'instant que ça ne marche que\n   si srng_is_comm *)\nTheorem polyn_c_mul_1_r : if srng_is_comm then ∀ P, (P * 1)%P = P else True.\nProof.\nspecialize polyn_c_mul_comm as polyn_mul_comm.\ndestruct srng_is_comm; [ | easy ].\nintros.\nrewrite polyn_mul_comm.\napply polyn_mul_1_l.\nQed.\n\nTheorem eq_norm_polyn_list_eq_length : ∀ la lb,\n  norm_polyn_list la = norm_polyn_list lb\n  → length la = length lb\n  → la = lb.\nProof.\nintros * Hll Hlen.\nunfold norm_polyn_list in Hll.\napply (f_equal (@rev _)) in Hll.\ndo 2 rewrite rev_involutive in Hll.\nsetoid_rewrite <- rev_length in Hlen.\napply List_rev_inj.\nremember (rev la) as l; clear la Heql; rename l into la.\nremember (rev lb) as l; clear lb Heql; rename l into lb.\nrevert la Hll Hlen.\ninduction lb as [| b]; intros. {\n  now apply length_zero_iff_nil in Hlen.\n}\ndestruct la as [| a]; [ easy | ].\ncbn in Hll, Hlen.\napply Nat.succ_inj in Hlen.\ndestruct (srng_eq_dec a 0) as [Haz| Haz]. {\n  destruct (srng_eq_dec b 0) as [Hbz| Hbz]. {\n    subst a b; f_equal.\n    now apply IHlb.\n  }\n  exfalso; clear - Hbz Hll Hlen.\n  assert (H : length la ≤ length lb) by flia Hlen.\n  clear Hlen; rename H into Hlen.\n  induction la as [| a]; [ easy | ].\n  cbn in Hll.\n  destruct (srng_eq_dec a 0) as [Haz| Haz]. {\n    cbn in Hlen.\n    apply IHla; [ easy | flia Hlen ].\n  }\n  rewrite Hll in Hlen; cbn in Hlen.\n  flia Hlen.\n}\ndestruct (srng_eq_dec b 0) as [Hbz| Hbz]. {\n  exfalso; clear b Hbz.\n  clear - Haz Hll Hlen.\n  assert (H : length lb ≤ length la) by flia Hlen.\n  clear Hlen; rename H into Hlen.\n  induction lb as [| b]; [ easy | ].\n  cbn in Hll.\n  destruct (srng_eq_dec b 0) as [Hbz| Hbz]. {\n    cbn in Hlen.\n    apply IHlb; [ easy | flia Hlen ].\n  }\n  rewrite <- Hll in Hlen; cbn in Hlen.\n  flia Hlen.\n}\neasy.\nQed.\n\nFixpoint polyn_list_convol_mul_add (la lb lc : list T) i len :=\n  match len with\n  | O => []\n  | S len1 =>\n      (Σ (j = 0, i),\n       List.nth j la 0 *\n       (List.nth (i - j) lb 0 + List.nth (i - j) lc 0))%Srng ::\n       polyn_list_convol_mul_add la lb lc (S i) len1\n  end.\n\nTheorem list_polyn_nth_add : ∀ k la lb,\n  (List.nth k (la + lb)%PL 0 =\n   List.nth k la 0 + List.nth k lb 0)%Srng.\nProof.\nintros k la lb.\nrevert la lb.\ninduction k; intros. {\n destruct la as [| a]; cbn; [ now rewrite srng_add_0_l | ].\n destruct lb as [| b]; cbn; [ now rewrite srng_add_0_r | easy ].\n} {\n destruct la as [| a]; cbn; [ now rewrite srng_add_0_l | ].\n destruct lb as [| b]; cbn; [ now rewrite srng_add_0_r | easy ].\n}\nQed.\n\nTheorem map_polyn_list_convol_mul_add : ∀ la lb lc i len,\n  map (polyn_list_convol_mul la (lb + lc)%PL) (seq i len) =\n  polyn_list_convol_mul_add la lb lc i len.\nProof.\nintros la lb lc i len.\nrevert la lb lc i.\ninduction len; intros; [ easy | ].\nrewrite <- Nat.add_1_l.\nrewrite seq_app.\nrewrite map_app.\nrewrite IHlen.\nrewrite (Nat.add_comm i).\ncbn - [ nth ]; f_equal.\nrewrite Nat.sub_0_r.\ndo 2 rewrite srng_add_0_l.\ndo 2 (rewrite fold_left_srng_add_fun_from_0; [ symmetry | easy ]).\nf_equal. {\n  f_equal.\n  apply list_polyn_nth_add.\n}\nreplace i with (S i - 1) at 1 2 by flia.\napply srng_summation_eq_compat.\nintros j Hj.\nnow rewrite list_polyn_nth_add.\nQed.\n\nTheorem map_polyn_list_add_convol_mul : ∀ la lb lc i len,\n  (map (polyn_list_convol_mul la lb) (seq i len) +\n   map (polyn_list_convol_mul la lc) (seq i len))%PL =\n  polyn_list_convol_mul_add la lb lc i len.\nProof.\nintros la lb lc i len.\nrevert la lb lc i.\ninduction len; intros; [ easy | ].\ncbn - [ nth sub ].\nrewrite IHlen; f_equal.\nunfold polyn_list_convol_mul.\nrewrite <- srng_summation_add_distr; [ | easy ].\napply srng_summation_eq_compat; intros j (_, Hj).\nnow rewrite srng_mul_add_distr_l.\nQed.\n\nTheorem norm_polyn_list_mul_add_distr_l : ∀ la lb lc,\n  norm_polyn_list (la * (lb + lc))%PL =\n  norm_polyn_list (la * lb + la * lc)%PL.\nProof.\nintros la lb lc.\nunfold polyn_list_mul.\nremember (length la + length (lb + lc)%PL - 1) as labc.\nremember (length la + length lb - 1) as lab.\nremember (length la + length lc - 1) as lac.\nrewrite Heqlabc.\nremember (lb + lc)%PL as lbc.\nsymmetry in Heqlbc.\nrewrite <- Heqlbc in Heqlabc |-*.\nrewrite (polyn_list_convol_mul_more (lab + lac)); [ | subst; flia ].\nrewrite <- Heqlabc.\nsymmetry.\nrewrite Heqlab.\nrewrite <- norm_polyn_list_add_idemp_l.\nrewrite (polyn_list_convol_mul_more (labc + lac)); [ | flia ].\nrewrite <- Heqlab.\nrewrite norm_polyn_list_add_idemp_l.\nrewrite polyn_list_add_comm.\nrewrite <- norm_polyn_list_add_idemp_l.\nrewrite Heqlac.\nrewrite (polyn_list_convol_mul_more (labc + lab)); [ | flia ].\nrewrite norm_polyn_list_add_idemp_l.\nrewrite <- Heqlac.\nrewrite Nat.add_comm.\nrewrite polyn_list_add_comm.\nrewrite Nat.add_assoc, Nat.add_shuffle0, Nat.add_comm, Nat.add_assoc.\nsymmetry.\nrewrite map_polyn_list_convol_mul_add.\nnow rewrite map_polyn_list_add_convol_mul.\nQed.\n\nTheorem polyn_list_mul_add_distr_l : ∀ la lb lc,\n  (la * (lb + lc))%PL = (la * lb + la * lc)%PL.\nProof.\nintros.\napply eq_norm_polyn_list_eq_length. {\n  apply norm_polyn_list_mul_add_distr_l.\n}\nunfold polyn_list_mul.\nrewrite map_length, seq_length.\ndo 2 rewrite polyn_list_add_length.\ndo 2 rewrite map_length, seq_length.\nrewrite <- Nat.add_max_distr_l.\nnow rewrite Nat.sub_max_distr_r.\nQed.\n\nTheorem polyn_mul_add_distr_l : ∀ P Q R, (P * (Q + R) = P * Q + P * R)%P.\nProof.\nintros.\nunfold polyn_mul.\napply polyn_eq; cbn.\nrewrite fold_norm_polyn_list.\n(* à finir *)\n...\nrewrite norm_polyn_list_mul_idemp_r.\nrewrite norm_polyn_list_add_idemp_l.\nrewrite norm_polyn_list_add_idemp_r.\nf_equal.\napply polyn_list_mul_add_distr_l.\nQed.\n\nTheorem polyn_mul_add_distr_r : ∀ P Q R, ((P + Q) * R = P * R + Q * R)%P.\nProof.\nintros.\nrewrite polyn_mul_comm.\nrewrite polyn_mul_add_distr_l.\nnow do 2 rewrite (polyn_mul_comm R).\nQed.\n\nTheorem polyn_list_mul_0_l : ∀ la,\n  norm_polyn_list ([] * la)%PL = [].\nProof.\nintros.\napply List_eq_rev_r.\napply eq_strip_0s_nil; cbn.\nrewrite rev_length, map_length.\nrewrite seq_length.\napply List_eq_rev_r.\nrewrite List_rev_repeat.\nrewrite (map_polyn_list_convol_mul_0_l 0).\nnow rewrite seq_length.\nQed.\n\nTheorem polyn_list_mul_0_r : ∀ la,\n  norm_polyn_list (la * [])%PL = [].\nProof.\nintros.\nrewrite polyn_list_mul_comm.\napply polyn_list_mul_0_l.\nQed.\n\nTheorem polyn_mul_0_l : ∀ P, (0 * P = 0)%P.\nProof.\nintros.\napply polyn_eq.\napply polyn_list_mul_0_l.\nQed.\n\nTheorem polyn_mul_0_r : ∀ P, (P * 0 = 0)%P.\nProof.\nintros.\nrewrite polyn_mul_comm.\napply polyn_mul_0_l.\nQed.\n\nTheorem list_nth_polyn_list_eq : ∀ la lb,\n  (∀ i, (List.nth i la 0 = List.nth i lb 0)%Rng)\n  → norm_polyn_list la = norm_polyn_list lb.\nProof.\nintros * Hi.\nunfold norm_polyn_list; f_equal.\nrevert lb Hi.\ninduction la as [| a]; intros. {\n  induction lb as [| b]; [ easy | ].\n  specialize (Hi 0) as H; cbn in H.\n  subst b; cbn.\n  rewrite strip_0s_app; cbn.\n  remember (strip_0s (rev lb)) as lc eqn:Hlc; symmetry in Hlc.\n  destruct lc as [| c]; [ now destruct (srng_eq_dec _ _) | ].\n  assert (H : norm_polyn_list [] = norm_polyn_list lb). {\n    unfold norm_polyn_list; cbn.\n    cbn in IHlb.\n    change (rev [] = rev (strip_0s (rev lb))).\n    f_equal.\n    rewrite Hlc.\n    apply IHlb.\n    intros i; cbn; rewrite match_id.\n    now specialize (Hi (S i)); cbn in Hi.\n  }\n  cbn in H.\n  unfold norm_polyn_list in H.\n  rewrite Hlc in H.\n  symmetry in H.\n  now apply List_eq_rev_nil in H.\n} {\n  cbn.\n  rewrite strip_0s_app.\n  remember (strip_0s (rev la)) as lc eqn:Hlc; symmetry in Hlc.\n  destruct lc as [| c]. {\n    assert (Hla : ∀ i, nth i la 0%Rng = 0%Rng). {\n      intros i.\n      clear - Hlc.\n      revert i.\n      induction la as [| a]; intros; [ now cbn; rewrite match_id | cbn ].\n      destruct i. {\n        cbn in Hlc.\n        rewrite strip_0s_app in Hlc; cbn in Hlc.\n        remember (strip_0s (rev la)) as lb eqn:Hlb; symmetry in Hlb.\n        destruct lb as [| b]; [ now destruct (srng_eq_dec a 0) | easy ].\n      }\n      apply IHla.\n      cbn in Hlc.\n      rewrite strip_0s_app in Hlc; cbn in Hlc.\n      remember (strip_0s (rev la)) as lb eqn:Hlb; symmetry in Hlb.\n      destruct lb as [| b]; [ now destruct (srng_eq_dec a 0) | easy ].\n    }\n    cbn.\n    destruct (srng_eq_dec a 0) as [Haz| Haz]. {\n      assert (Hlb : ∀ i, nth i lb 0%Rng = 0%Rng). {\n        intros.\n        rewrite <- Hi; cbn.\n        destruct i; [ easy | ].\n        apply Hla.\n      }\n      clear - Hlb.\n      induction lb as [| b]; [ easy | cbn ].\n      specialize (Hlb 0) as H1; cbn in H1; subst b.\n      rewrite strip_0s_app; cbn.\n      rewrite <- IHlb; [ now rewrite if_0_eq_0 | ].\n      intros i.\n      now specialize (Hlb (S i)).\n    }\n    destruct lb as [| b]; [ now specialize (Hi 0); cbn in Hi | cbn ].\n    rewrite strip_0s_app; cbn.\n    remember (strip_0s (rev lb)) as ld eqn:Hld; symmetry in Hld.\n    destruct ld as [| d]. {\n      destruct (srng_eq_dec b 0) as [Hbz| Hbz]. {\n        subst b.\n        now specialize (Hi 0).\n      }\n      f_equal.\n      now specialize (Hi 0).\n    }\n    specialize (IHla lb).\n    assert (H : ∀ i : nat, nth i la 0%Rng = nth i lb 0%Rng). {\n      intros i.\n      now specialize (Hi (S i)); cbn in Hi.\n    }\n    specialize (IHla H); clear H.\n    now rewrite Hld in IHla.\n  }\n  destruct lb as [| b]. {\n    specialize (IHla []).\n    assert (H : ∀ i : nat, nth i la 0%Rng = nth i [] 0%Rng). {\n      intros i; cbn; rewrite match_id.\n      now specialize (Hi (S i)).\n    }\n    now specialize (IHla H).\n  }\n  cbn.\n  rewrite strip_0s_app; cbn.\n  remember (strip_0s (rev lb)) as ld eqn:Hld; symmetry in Hld.\n  destruct ld as [| d]. {\n    destruct (srng_eq_dec b 0) as [Hbz| Hbz]. {\n      subst b.\n      specialize (IHla lb).\n      assert (H : ∀ i : nat, nth i la 0%Rng = nth i lb 0%Rng). {\n        intros i.\n        now specialize (Hi (S i)); cbn in Hi.\n      }\n      specialize (IHla H); clear H.\n      now rewrite Hld in IHla.\n    }\n    specialize (IHla lb).\n    assert (H : ∀ i : nat, nth i la 0%Rng = nth i lb 0%Rng). {\n      intros i.\n      now specialize (Hi (S i)); cbn in Hi.\n    }\n    specialize (IHla H); clear H.\n    now rewrite Hld in IHla.\n  }\n  specialize (Hi 0) as H1; cbn in H1; subst b.\n  do 2 rewrite app_comm_cons; f_equal.\n  rewrite <- Hld.\n  apply IHla.\n  now intros i; specialize (Hi (S i)).\n}\nQed.\n\nTheorem list_nth_polyn_list_convol_mul_aux : ∀ la lb n i len,\n  List.length la + List.length lb - 1 = (i + len)%nat\n  → (List.nth n (map (polyn_list_convol_mul la lb) (seq i len)) 0%Rng =\n     Σ (j = 0, n + i),\n     List.nth j la 0 * List.nth (n + i - j) lb 0)%Rng.\nProof.\nintros la lb n i len Hlen.\nrevert la lb i n Hlen.\ninduction len; intros. {\n  rewrite Nat.add_0_r in Hlen.\n  rewrite all_0_srng_summation_0; [ now destruct n | easy | ].\n  intros j (_, Hj).\n  destruct (le_dec (length la) j) as [H1| H1]. {\n    rewrite nth_overflow; [ | easy ].\n    now rewrite srng_mul_0_l.\n  }\n  destruct (le_dec (length lb) (n + i - j)) as [H2| H2]. {\n   rewrite srng_c_mul_comm.\n   rewrite nth_overflow; [ | easy ].\n   now rewrite rng_mul_0_l.\n  }\n  exfalso; apply H2; clear Hj H2.\n  apply Nat.nle_gt in H1; subst i.\n  flia H1.\n} {\n  destruct n; [ easy | ].\n  rewrite Nat.add_succ_r, <- Nat.add_succ_l in Hlen.\n  cbn - [ iter_seq sub ].\n  rewrite IHlen; [ | easy ].\n  now rewrite Nat.add_succ_r, <- Nat.add_succ_l.\n}\nQed.\n\nTheorem list_nth_polyn_list_convol_mul : ∀ la lb i len,\n  len = length la + length lb - 1\n  → (List.nth i (map (polyn_list_convol_mul la lb) (seq 0 len)) 0 =\n     Σ (j = 0, i), List.nth j la 0 * List.nth (i - j) lb 0)%Rng.\nProof.\nintros la lb i len Hlen.\nsymmetry in Hlen.\nrewrite list_nth_polyn_list_convol_mul_aux; [ | easy ].\nnow rewrite Nat.add_0_r.\nQed.\n\nTheorem srng_summation_mul_polyn_list_nth_map_list_convol_mul : ∀ la lb lc k,\n  (Σ (i = 0, k),\n     List.nth i la 0 *\n     List.nth (k - i)\n       (map (polyn_list_convol_mul lb lc) (seq 0 (length lb + length lc - 1)))\n       0 =\n   Σ (i = 0, k),\n     List.nth i la 0 *\n     Σ (j = 0, k - i),\n       List.nth j lb 0 * List.nth (k - i - j) lc 0)%Rng.\nProof.\nintros la lb lc k.\napply srng_summation_eq_compat.\nintros i (_, Hi).\nf_equal.\nnow rewrite list_nth_polyn_list_convol_mul.\nQed.\n\nTheorem srng_summation_mul_polyn_list_nth_map_list_convol_mul_2 : ∀ la lb lc k,\n   (Σ (i = 0, k),\n      List.nth i lc 0 *\n      List.nth (k - i)\n        (map (polyn_list_convol_mul la lb)\n           (seq 0 (length la + length lb - 1))) 0 =\n    Σ (i = 0, k),\n      List.nth (k - i) lc 0 *\n      Σ (j = 0, i),\n        List.nth j la 0 * List.nth (i - j) lb 0)%Rng.\nProof.\nintros la lb lc k.\nrewrite srng_summation_rtl; [ | easy ].\napply srng_summation_eq_compat.\nintros i (_, Hi).\nrewrite Nat.add_0_r.\nf_equal.\nrewrite Nat_sub_sub_distr; [ | easy ].\nrewrite Nat.sub_diag.\nnow apply list_nth_polyn_list_convol_mul.\nQed.\n\nTheorem srng_summation_aux_summation_aux_mul_swap : ∀ g1 (g2 : nat → T) g3 b1 b2 len,\n  fold_left\n    (λ c i, (c + fold_left (λ d j, d + g2 i * g3 i j) (seq b2 (g1 i)) 0)%Rng)\n    (seq b1 len) 0%Rng =\n  fold_left\n    (λ c i, (c + g2 i * fold_left (λ d j, d + g3 i j) (seq b2 (g1 i)) 0)%Rng)\n    (seq b1 len) 0%Rng.\nProof.\nintros.\nrevert b1 b2.\ninduction len; intros; [ easy | ].\nrewrite List_seq_succ_r.\ndo 2 rewrite fold_left_app.\nrewrite IHlen.\nrewrite fold_left_srng_add_fun_from_0; [ symmetry | easy ].\nrewrite fold_left_srng_add_fun_from_0; [ symmetry | easy ].\napply srng_add_compat_l.\ncbn; do 2 rewrite srng_add_0_l.\ndestruct (zerop (b2 + g1 (b1 + len))) as [Hz| Hz]. {\n  apply Nat.eq_add_0 in Hz.\n  destruct Hz as (Hbz, Hgz).\n  subst b2; rewrite Hgz.\n  cbn; symmetry.\n  apply srng_mul_0_r.\n}\nrewrite fold_iter_seq_2; [ | easy ].\nrewrite fold_iter_seq_2; [ | easy ].\nsymmetry.\nnow apply srng_mul_summation_distr_l.\nQed.\n\nTheorem srng_summation_summation_mul_swap : ∀ g1 (g2 : nat → T) g3 k,\n  (Σ (i = 0, k), (Σ (j = 0, g1 i), g2 i * g3 i j)\n   = Σ (i = 0, k), g2 i * Σ (j = 0, g1 i), g3 i j)%Rng.\nProof.\nintros.\napply srng_summation_aux_summation_aux_mul_swap.\nQed.\n\nTheorem norm_polyn_list_mul_assoc : ∀ la lb lc,\n  norm_polyn_list (la * (lb * lc))%PL =\n  norm_polyn_list ((la * lb) * lc)%PL.\nProof.\nintros la lb lc.\nsymmetry; rewrite polyn_list_mul_comm.\nunfold polyn_list_mul.\ndo 2 rewrite map_length, seq_length.\ndestruct lc as [| c]. {\n  destruct la as [| a]. {\n    do 2 rewrite (map_polyn_list_convol_mul_0_l 0).\n    now rewrite (Nat.add_comm (length []) (length lb)).\n  }\n  destruct lb as [| b]. {\n    do 2 rewrite (map_polyn_list_convol_mul_0_l 0).\n    rewrite (map_polyn_list_convol_mul_0_r 0).\n    now do 2 rewrite norm_polyn_list_repeat_0.\n  }\n  cbn - [ norm_polyn_list ].\n  rewrite (map_polyn_list_convol_mul_0_l 0).\n  rewrite (map_polyn_list_convol_mul_0_r 0).\n  rewrite map_polyn_list_convol_mul_0_r.\n  now do 2 rewrite norm_polyn_list_repeat_0.\n}\ndestruct la as [| a]. {\n  do 2 rewrite (map_polyn_list_convol_mul_0_l 0).\n  rewrite map_polyn_list_convol_mul_0_r.\n  now do 2 rewrite norm_polyn_list_repeat_0.\n}\ndestruct lb as [| b]. {\n  rewrite (map_polyn_list_convol_mul_0_l 0).\n  rewrite (map_polyn_list_convol_mul_0_r 0).\n  rewrite map_polyn_list_convol_mul_0_r.\n  rewrite map_polyn_list_convol_mul_0_r.\n  now do 2 rewrite norm_polyn_list_repeat_0.\n}\nmove b before a; move c before b.\nremember (a :: la) as la' eqn:Hla'.\nremember (b :: lb) as lb' eqn:Hlb'.\nremember (c :: lc) as lc' eqn:Hlc'.\nmove lb' before la'; move lc' before lb'.\nremember (length la' + length lb' + length lc' - 2) as len eqn:Hlen.\nreplace (length lc' + (length la' + length lb' - 1) - 1) with len. 2: {\n  subst la' lb' lc'; cbn in Hlen |-*; flia Hlen.\n}\nreplace (length la' + (length lb' + length lc' - 1) - 1) with len. 2: {\n  subst la' lb' lc'; cbn in Hlen |-*; flia Hlen.\n}\napply list_nth_polyn_list_eq; intros k.\nremember\n  (map (polyn_list_convol_mul la' lb') (seq 0 (length la' + length lb' - 1)))\n  as ld eqn:Hld.\nremember\n  (map (polyn_list_convol_mul lb' lc') (seq 0 (length lb' + length lc' - 1)))\n  as le eqn:Hle.\nsymmetry in Hld, Hle.\nmove le before ld.\ndestruct ld as [| d]. {\n  apply map_eq_nil in Hld.\n  apply List_seq_eq_nil in Hld.\n  rewrite Hla', Hlb' in Hld; cbn in Hld.\n  flia Hld.\n}\ndestruct le as [| e]. {\n  apply map_eq_nil in Hle.\n  apply List_seq_eq_nil in Hle.\n  rewrite Hlc', Hlb' in Hle; cbn in Hle.\n  flia Hle.\n}\ndestruct (lt_dec k len) as [Hklen| Hklen]. {\n  rewrite (List_map_nth_in _ 0); [ | now rewrite seq_length ].\n  rewrite (List_map_nth_in _ 0); [ | now rewrite seq_length ].\n  rewrite seq_nth; [ | easy ].\n  rewrite Nat.add_0_l.\n  unfold polyn_list_convol_mul.\n  rewrite <- Hld, <- Hle.\n  rewrite srng_summation_mul_polyn_list_nth_map_list_convol_mul_2; symmetry.\n  rewrite srng_summation_mul_polyn_list_nth_map_list_convol_mul; symmetry.\n  rewrite <- srng_summation_summation_mul_swap.\n  rewrite <- srng_summation_summation_mul_swap.\n  rewrite srng_summation_summation_exch; [ | easy ].\n  rewrite srng_summation_summation_shift; [ | easy ].\n  apply srng_summation_eq_compat.\n  intros i Hi.\n  apply srng_summation_eq_compat.\n  intros j Hj.\n  rewrite srng_c_mul_comm, srng_mul_assoc.\n  rewrite Nat.add_comm, Nat.add_sub.\n  rewrite Nat.add_comm.\n  rewrite Nat.add_comm, Nat.sub_add_distr.\n  now rewrite Nat_sub_sub_swap.\n}\napply Nat.nlt_ge in Hklen.\nrewrite nth_overflow; [ | now rewrite map_length, seq_length ].\nrewrite nth_overflow; [ | now rewrite map_length, seq_length ].\neasy.\nQed.\n\nTheorem polyn_mul_assoc : ∀ P Q R, (P * (Q * R))%P = (P * Q * R)%P.\nProof.\nintros (la, Pa) (lb, Pb) (lc, Pc).\napply polyn_eq.\ncbn - [ polyn_list_mul ].\nrewrite norm_polyn_list_mul_idemp_l.\nrewrite norm_polyn_list_mul_idemp_r.\napply norm_polyn_list_mul_assoc.\nQed.\n\nDefinition polyn_semiring_prop : semiring_prop (polynomial T) :=\n  {| srng_is_comm := srng_is_comm;\n     srng_add_comm := polyn_add_comm;\n     srng_add_assoc := polyn_add_assoc;\n     srng_add_0_l := polyn_add_0_l;\n     srng_mul_assoc := polyn_mul_assoc;\n     srng_mul_1_l := polyn_mul_1_l;\n     srng_mul_add_distr_l := polyn_mul_add_distr_l;\n     srng_mul_0_l := polyn_mul_0_l |}.\n\nDefinition polyn_sring_comm_prop : sring_comm_prop (polynomial T) :=\n  {| srng_c_mul_comm := polyn_mul_comm |}.\n\nExisting Instance polyn_semiring_prop.\nExisting Instance polyn_sring_comm_prop.\n\nCanonical Structure polyn_semiring_prop.\nCanonical Structure polyn_sring_comm_prop.\n\nTheorem polyn_add_opp_l : ∀ P : polynomial T, (- P + P)%P = 0%P.\nProof.\nintros.\napply polyn_eq; cbn.\ndestruct P as (la, Hla); cbn.\napply List_eq_rev_r; cbn.\napply eq_strip_0s_nil.\napply List_eq_rev_r; cbn.\nrewrite List_rev_repeat.\nrewrite rev_length.\nclear Hla.\ninduction la as [| a]; [ easy | cbn ].\nnow rewrite rng_add_opp_l; f_equal.\nQed.\n\nTheorem polyn_add_opp_r : ∀ P : polynomial T, (P - P)%P = 0%P.\nProof.\nintros.\nunfold polyn_sub.\nrewrite polyn_add_comm.\napply polyn_add_opp_l.\nQed.\n\nDefinition polyn_ring_prop : ring_prop (polynomial T) :=\n  {| rng_add_opp_l := polyn_add_opp_l |}.\n\nExisting Instance polyn_ring_prop.\n\nTheorem polyn_eq_dec : ∀ P Q : polynomial T, {P = Q} + {P ≠ Q}.\nProof.\nintros.\ndestruct P as (la, Hla).\ndestruct Q as (lb, Hlb).\nenough (H : {la = lb} + {la ≠ lb}). {\n  destruct H as [H| H]. {\n    subst la; left.\n    now apply polyn_eq; cbn.\n  } {\n    right.\n    intros H'; apply H; clear H.\n    now injection H'.\n  }\n}\nclear Hla Hlb.\napply list_eq_dec, sdp.\nQed.\n\nArguments polyn_eq_dec P%P Q%P.\n\nTheorem polyn_1_neq_0 : 1%P ≠ 0%P.\nProof.\nunfold polyn_of_list; cbn.\nintros H.\ninjection H; clear H; intros.\nunfold norm_polyn_list in H; cbn in H.\nnow rewrite if_1_eq_0 in H.\nQed.\n\nDefinition polyn_sring_dec_prop : @sring_dec_prop _ polyn_semiring_op :=\n  {| srng_eq_dec := polyn_eq_dec;\n     srng_1_neq_0 := polyn_1_neq_0 |}.\n\nCanonical Structure polyn_semiring_op.\n(*\nCanonical Structure polyn_ring_op.\nCanonical Structure polyn_semiring_prop.\nCanonical Structure polyn_ring_prop.\nCanonical Structure polyn_sring_dec_prop.\n*)\n\n(* monic polynomial: polynomial whose leading coefficient is 1 *)\n\nDefinition is_monic_polyn (P : polynomial T) :=\n  polyn_coeff P (polyn_degree P) = 1%Srng.\n\nArguments is_monic_polyn P%P.\n\nTheorem polyn_x_minus_is_monic : ∀ a,\n  polyn_degree a = 0\n  → is_monic_polyn (_x - a).\nProof.\nintros * Ha.\nunfold polyn_degree in Ha; cbn in Ha.\nunfold polyn_degree_plus_1 in Ha; cbn in Ha.\napply Nat.sub_0_le in Ha.\ndestruct a as (la, Hla).\ncbn in Ha |-*.\ndestruct la as [| a]. {\n  unfold is_monic_polyn; cbn.\n  rewrite if_1_eq_0; cbn.\n  now rewrite if_1_eq_0.\n}\ndestruct la; [ | cbn in Ha; flia Ha ].\ncbn in Hla.\nunfold is_monic_polyn; cbn.\nrewrite if_1_eq_0; cbn.\nnow rewrite if_1_eq_0.\nQed.\n\n(* *)\n\nTheorem norm_polyn_list_app_last_nz : ∀ (la lb : list T),\n  last (la ++ lb) 0%Srng ≠ 0%Srng\n  → norm_polyn_list (la ++ lb) = la ++ norm_polyn_list lb.\nProof.\nintros * Hlb.\nrevert lb Hlb.\ninduction la as [| a]; intros; [ easy | ].\ncbn - [ norm_polyn_list ].\nrewrite List_cons_app.\nrewrite norm_polyn_list_app.\nremember (la ++ lb) as lc eqn:Hlc.\nsymmetry in Hlc.\ndestruct lc as [| c]. cbn. {\n  apply app_eq_nil in Hlc.\n  destruct Hlc; subst la lb.\n  cbn in Hlb |-*.\n  now destruct (srng_eq_dec a 0).\n}\nrewrite <- Hlc.\nrewrite IHla. 2: {\n  cbn in Hlb.\n  rewrite Hlc in Hlb.\n  now rewrite <- Hlc in Hlb.\n}\ndestruct lb as [| b]. {\n  cbn in Hlb.\n  rewrite Hlc in Hlb.\n  rewrite app_nil_r in Hlc.\n  now rewrite Hlc.\n}\ndestruct la as [| a1]; [ | easy ].\ncbn in Hlc.\ncbn - [ norm_polyn_list ].\nremember (norm_polyn_list (b :: lb)) as ld eqn:Hld.\nsymmetry in Hld.\ndestruct ld as [| d]; [ | easy ].\nexfalso; apply Hlb; clear Hlb.\nclear IHla Hlc.\nrevert b Hld.\ninduction lb as [| b1]; intros. {\n  cbn in Hld.\n  now destruct (srng_eq_dec b 0).\n}\ncbn - [ last ].\nrewrite List_last_cons_cons.\napply IHlb.\ncbn in Hld |-*.\napply List_eq_rev_l in Hld.\napply List_eq_rev_r.\nrewrite strip_0s_app in Hld.\nremember (strip_0s (rev lb ++ [b1])) as le eqn:Hle.\nsymmetry in Hle.\nnow destruct le.\nQed.\n\nTheorem norm_polyn_list_id : ∀ (la : list T),\n  last la 0%Srng ≠ 0%Srng\n  → norm_polyn_list la = la.\nProof.\nintros * Hla.\nunfold norm_polyn_list; f_equal.\napply List_eq_rev_r.\nremember (rev la) as lb eqn:Hlb.\napply List_eq_rev_r in Hlb; subst la.\nrename lb into la.\nrewrite List_rev_last in Hla.\ndestruct la as [| a]; [ easy | ].\ncbn in Hla |-*.\nnow destruct (srng_eq_dec a 0).\nQed.\n\nTheorem norm_polyn_list_cons : ∀ (a : T) la,\n  last (a :: la) 0%Srng ≠ 0%Srng\n  → norm_polyn_list (a :: la) = a :: norm_polyn_list la.\nProof.\nintros * Hla.\nnow specialize (norm_polyn_list_app_last_nz [a] la Hla) as H.\nQed.\n\nTheorem polyn_degree_lt_add : ∀ P Q,\n  polyn_degree Q < polyn_degree P\n  → polyn_degree (P + Q) = polyn_degree P.\nProof.\nintros * Hdeg.\nunfold polyn_degree in Hdeg |-*.\nunfold polyn_degree_plus_1 in Hdeg |-*.\nf_equal.\ndestruct P as (la, Hla).\ndestruct Q as (lb, Hlb).\nmove lb before la.\ncbn - [ norm_polyn_list ] in Hdeg |-*.\nunfold polyn_prop_test in Hla, Hlb.\ndestruct la as [| a]; [ easy | ].\ncbn - [ nth ] in Hla.\ndestruct (srng_eq_dec (nth (length la) (a :: la) 0%Srng) 0) as [Haz| Haz]. {\n  easy.\n}\nclear Hla.\ndestruct lb as [| b]. {\n  rewrite polyn_list_add_0_r.\n  rewrite norm_polyn_list_id; [ easy | ].\n  now rewrite List_last_nth_cons.\n}\ncbn - [ nth ] in Hlb.\ndestruct (srng_eq_dec (nth (length lb) (b :: lb) 0%Srng) 0) as [Hbz| Hbz]. {\n  easy.\n}\nclear Hlb.\ncbn in Hdeg.\ndo 2 rewrite Nat.sub_0_r in Hdeg.\nrewrite <- List_last_nth_cons in Haz.\nrewrite <- List_last_nth_cons in Hbz.\ncbn - [ norm_polyn_list ].\nrevert a b lb Haz Hbz Hdeg.\ninduction la as [| a1]; intros; [ easy | ].\ndestruct lb as [| b1]. {\n  cbn - [ norm_polyn_list ].\n  now rewrite norm_polyn_list_id.\n}\ncbn - [ norm_polyn_list ].\ncbn in Hdeg.\napply Nat.succ_lt_mono in Hdeg.\nrewrite List_last_cons_cons in Haz, Hbz.\nspecialize (IHla a1 b1 lb Haz Hbz Hdeg).\nrewrite norm_polyn_list_cons. {\n  cbn - [ norm_polyn_list ].\n  now rewrite IHla.\n}\nrewrite List_last_cons_cons.\nclear - so Haz Hdeg.\nrevert lb a1 b1 Haz Hdeg.\ninduction la as [| a]; intros; [ easy | cbn ].\ndestruct lb as [| b]; [ easy | ].\nremember (a :: la) as x; cbn in Haz; subst x.\ncbn in Hdeg.\napply Nat.succ_lt_mono in Hdeg.\nnow apply IHla.\nQed.\n\n(* normalized list is smaller than the list *)\n\nTheorem norm_polyn_list_length_le : ∀ la,\n  length (norm_polyn_list la) ≤ length la.\nProof.\nintros.\ninduction la as [| a] using rev_ind; [ easy | ].\nrewrite norm_polyn_list_app, app_length; cbn.\ndestruct (srng_eq_dec a 0%Srng) as [Hz| Hz]. {\n  cbn; flia IHla.\n}\ncbn.\nnow rewrite app_length.\nQed.\n\n(* degree of sum and summation upper bound *)\n\nTheorem polyn_degree_add_ub : ∀ P Q,\n  polyn_degree (P + Q) ≤ max (polyn_degree P) (polyn_degree Q).\nProof.\nintros (la, Hla) (lb, Hlb).\nmove lb before la.\ncbn - [ \"+\"%PL ].\nrewrite Nat.sub_max_distr_r.\napply Nat.sub_le_mono_r.\ndestruct la as [| a]. {\n  clear Hla.\n  rewrite Nat.max_r; [ | cbn; flia ].\n  rewrite polyn_list_add_0_l.\n  destruct lb as [| b]; [ easy | ].\n  cbn - [ nth ] in Hlb.\n  destruct (srng_eq_dec (nth (length lb) (b :: lb) 0%Srng) 0)\n    as [| H]; [ easy | clear Hlb ].\n  rewrite <- List_last_nth_cons in H.\n  rewrite norm_polyn_list_cons; [ cbn | easy ].\n  apply -> Nat.succ_le_mono.\n  apply norm_polyn_list_length_le.\n}\ncbn - [ nth ] in Hla.\ndestruct (srng_eq_dec (nth (length la) (a :: la) 0%Srng) 0)\n  as [Haz| Haz]; [ easy | clear Hla ].\nrewrite <- List_last_nth_cons in Haz.\ndestruct lb as [| b]. {\n  cbn - [ norm_polyn_list ].\n  clear Hlb.\n  revert a Haz.\n  induction la as [| a1]; intros. {\n    cbn in Haz |-*.\n    now destruct (srng_eq_dec a 0).\n  }\n  rewrite List_last_cons_cons in Haz.\n  rewrite norm_polyn_list_cons; [ | easy ].\n  remember (a1 :: la) as lc; cbn; subst lc.\n  apply -> Nat.succ_le_mono.\n  now apply IHla.\n}\ncbn - [ nth ] in Hlb.\ndestruct (srng_eq_dec (nth (length lb) (b :: lb) 0%Srng) 0)\n  as [Hbz| Hbz]; [ easy | clear Hlb ].\nrewrite <- List_last_nth_cons in Hbz.\nmove b before a.\nrevert a b lb Haz Hbz.\ninduction la as [| a1]; intros. {\n  cbn in Haz.\n  cbn - [ norm_polyn_list ].\n  remember (a + b)%Srng as c; clear Heqc.\n  revert b c Hbz.\n  induction lb as [| b1]; intros. {\n    cbn in Hbz |-*.\n    destruct (srng_eq_dec c 0); cbn; flia.\n  }\n  rewrite norm_polyn_list_cons; [ | easy ].\n  rewrite List_last_cons_cons in Hbz.\n  remember (b1 :: lb) as lc; cbn; subst lc.\n  apply -> Nat.succ_le_mono.\n  now apply (IHlb b1).\n}\nrewrite List_last_cons_cons in Haz.\nremember (a1 :: la) as lc.\ncbn - [ norm_polyn_list ].\nsubst lc.\ndestruct lb as [| b1]. {\n  rewrite polyn_list_add_0_r.\n  cbn in Hbz.\n  rewrite norm_polyn_list_cons; [ | easy ].\n  cbn - [ norm_polyn_list ] in IHla |-*.\n  apply -> Nat.succ_le_mono.\n  clear IHla.\n  revert a1 Haz.\n  induction la as [| a2]; intros. {\n    cbn.\n    now destruct (srng_eq_dec a1 0).\n  }\n  rewrite List_last_cons_cons in Haz.\n  rewrite norm_polyn_list_cons; [ | easy ].\n  cbn - [ norm_polyn_list ].\n  apply -> Nat.succ_le_mono.\n  now apply IHla.\n}\nrewrite List_last_cons_cons in Hbz.\nspecialize (IHla _ _ _ Haz Hbz).\napply Nat.succ_le_mono in IHla.\netransitivity; [ | apply IHla ].\nremember ((a1 :: la) + (b1 :: lb))%PL as lc eqn:Hlc.\nremember (a + b)%Srng as c; clear a b Heqc.\nclear.\nrevert c.\ninduction lc as [| c1] using rev_ind; intros. {\n  cbn.\n  now destruct (srng_eq_dec c 0); cbn; flia.\n}\ndestruct (srng_eq_dec c1 0) as [Hz| Hz]. {\n  subst c1.\n  rewrite app_comm_cons.\n  do 2 rewrite norm_polyn_list_app.\n  cbn - [ norm_polyn_list ].\n  unfold norm_polyn_list at 1 3.\n  cbn - [ norm_polyn_list ].\n  rewrite if_0_eq_0.\n  cbn - [ norm_polyn_list ].\n  apply IHlc.\n}\nrewrite app_comm_cons.\ndo 2 rewrite norm_polyn_list_app.\ncbn - [ norm_polyn_list ].\nunfold norm_polyn_list at 1 3.\ncbn - [ norm_polyn_list ].\nnow destruct (srng_eq_dec c1 0).\nQed.\n\n(* highest coefficient *)\n\nDefinition polyn_highest_coeff P :=\n  polyn_coeff P (polyn_degree P).\n\nTheorem polyn_highest_coeff_neq_0 : ∀ (P : polynomial T),\n  polyn_degree P ≠ 0\n  → polyn_highest_coeff P ≠ 0%Srng.\nProof.\nintros (la, Hla) Hd.\ncbn in Hla, Hd |-*.\ndestruct la as [| a] using rev_ind; [ easy | clear IHla ].\nrewrite <- List_last_nth, List_last_app.\nrewrite app_length, Nat.add_comm in Hla.\ncbn in Hla.\nrewrite app_nth2 in Hla; [ | now unfold ge ].\nrewrite Nat.sub_diag in Hla; cbn in Hla.\nnow destruct (srng_eq_dec a 0).\nQed.\n\nTheorem polyn_degree_add_not_cancel : ∀ P Q,\n  polyn_degree P = polyn_degree Q\n  → (polyn_highest_coeff P + polyn_highest_coeff Q ≠ 0)%Srng\n  → polyn_degree (P + Q) = polyn_degree P.\nProof.\nintros (la, Hla) (lb, Hlb) HPQ HCPQ.\nmove lb before la.\ncbn - [ norm_polyn_list ] in *.\ndestruct la as [| a] using rev_ind. {\n  cbn in HPQ, HCPQ |-*.\n  rewrite rev_length.\n  destruct lb as [| b]; [ easy | cbn ].\n  cbn in HPQ; rewrite Nat.sub_0_r in HPQ.\n  symmetry in HPQ.\n  apply length_zero_iff_nil in HPQ; subst lb.\n  cbn in Hlb, HCPQ |-*.\n  now destruct (srng_eq_dec b 0).\n}\nclear IHla.\nrewrite app_length in Hla, HCPQ, HPQ.\nrewrite Nat.add_1_r in Hla; cbn in Hla.\nrewrite Nat.add_sub in HPQ, HCPQ.\nrewrite app_nth2 in Hla; [ | now unfold ge ].\nrewrite app_nth2 in HCPQ; [ | now unfold ge ].\nrewrite Nat.sub_diag in Hla; cbn in Hla.\nrewrite Nat.sub_diag in HCPQ; cbn in HCPQ.\ndestruct lb as [| b] using rev_ind. {\n  apply length_zero_iff_nil in HPQ; subst la; cbn.\n  now destruct (srng_eq_dec a 0).\n}\nclear IHlb.\nmove b before a.\nrewrite app_length in Hlb, HCPQ, HPQ.\nrewrite Nat.add_1_r in Hlb; cbn in Hlb.\nrewrite Nat.add_sub in HPQ, HCPQ.\nrewrite app_nth2 in Hlb; [ | now unfold ge ].\nrewrite app_nth2 in HCPQ; [ | now unfold ge ].\nrewrite Nat.sub_diag in Hlb; cbn in Hlb.\nrewrite Nat.sub_diag in HCPQ; cbn in HCPQ.\nrewrite app_length, Nat.add_sub.\nrewrite polyn_list_add_app_l.\nrewrite firstn_app, HPQ, firstn_all, Nat.sub_diag, firstn_O, app_nil_r.\nrewrite skipn_app, skipn_all, app_nil_l, Nat.sub_diag, skipn_O; cbn.\nrewrite norm_polyn_list_app; cbn.\ndestruct (srng_eq_dec (a + b) 0) as [H| H]; [ easy | clear H; cbn ].\nrewrite app_length, Nat.add_sub.\nrewrite polyn_list_add_length, max_r; [ easy | ].\nnow rewrite HPQ.\nQed.\n\nTheorem polyn_degree_add_compat : ∀ Pa Pb Qa Qb,\n  polyn_degree Pa = polyn_degree Pb\n  → polyn_degree Qa = polyn_degree Qb\n  → (polyn_highest_coeff Pa + polyn_highest_coeff Qa)%Srng ≠ 0%Srng\n  → (polyn_highest_coeff Pb + polyn_highest_coeff Qb)%Srng ≠ 0%Srng\n  → polyn_degree (Pa + Qa) = polyn_degree (Pb + Qb).\nProof.\nintros * HP HQ Hha Hhb.\ndestruct (lt_dec (polyn_degree Pa) (polyn_degree Qa)) as [HPQ| HPQ]. {\n  rewrite polyn_add_comm.\n  rewrite polyn_degree_lt_add; [ | easy ].\n  rewrite polyn_add_comm.\n  rewrite polyn_degree_lt_add; [ easy | ].\n  now rewrite <- HP, <- HQ.\n}\napply Nat.nlt_ge in HPQ.\ndestruct (lt_dec (polyn_degree Qa) (polyn_degree Pa)) as [HQP| HQP]. {\n  rewrite polyn_degree_lt_add; [ | easy ].\n  rewrite polyn_degree_lt_add; [ easy | ].\n  now rewrite <- HP, <- HQ.\n}\napply Nat.nlt_ge in HQP.\napply Nat.le_antisymm in HPQ; [ clear HQP | easy ].\nrewrite polyn_degree_add_not_cancel; [ | easy | easy ].\nrewrite polyn_degree_add_not_cancel; [ | congruence | easy ].\ncongruence.\nQed.\n\nTheorem polyn_degree_add_le_compat : ∀ P P' Q Q',\n  polyn_degree P ≤ polyn_degree P'\n  → polyn_degree Q ≤ polyn_degree Q'\n  → (polyn_highest_coeff P' + polyn_highest_coeff Q')%Srng ≠ 0%Srng\n  → polyn_degree (P + Q) ≤ polyn_degree (P' + Q').\nProof.\nintros * HP HQ Hhb.\ndestruct (lt_dec (polyn_degree P) (polyn_degree Q)) as [HPQ| HPQ]. {\n  rewrite polyn_add_comm.\n  rewrite polyn_degree_lt_add; [ | easy ].\n  rewrite polyn_add_comm.\n  destruct (lt_dec (polyn_degree Q') (polyn_degree P')) as [HQP| HQP]. {\n    rewrite polyn_add_comm, polyn_degree_lt_add; [ | easy ].\n    etransitivity; [ apply HQ | ].\n    now apply Nat.lt_le_incl.\n  }\n  apply Nat.nlt_ge in HQP.\n  destruct (lt_dec (polyn_degree P') (polyn_degree Q')) as [H| H]. {\n    now rewrite polyn_degree_lt_add.\n  }\n  apply Nat.nlt_ge in H.\n  apply Nat.le_antisymm in HQP; [ clear H | easy ].\n  rewrite polyn_degree_add_not_cancel; [ | easy | now rewrite srng_add_comm ].\n  easy.\n}\napply Nat.nlt_ge in HPQ.\ndestruct (lt_dec (polyn_degree Q) (polyn_degree P)) as [HQP| HQP]. {\n  rewrite polyn_degree_lt_add; [ | easy ].\n  rewrite polyn_add_comm.\n  destruct (lt_dec (polyn_degree Q') (polyn_degree P')) as [HQP'| HQP']. {\n    now rewrite polyn_add_comm, polyn_degree_lt_add.\n  }\n  apply Nat.nlt_ge in HQP'.\n  destruct (lt_dec (polyn_degree P') (polyn_degree Q')) as [H| H]. {\n    rewrite polyn_degree_lt_add; [ | easy ].\n    etransitivity; [ apply HP | easy ].\n  }\n  apply Nat.nlt_ge in H.\n  apply Nat.le_antisymm in HQP'; [ clear H | easy ].\n  rewrite polyn_degree_add_not_cancel; [ | easy | now rewrite srng_add_comm ].\n  congruence.\n}\napply Nat.nlt_ge in HQP.\napply Nat.le_antisymm in HPQ; [ clear HQP | easy ].\netransitivity; [ apply polyn_degree_add_ub | ].\nrewrite max_l; [ | now rewrite HPQ ].\ndestruct (lt_dec (polyn_degree Q') (polyn_degree P')) as [HQP'| HQP']. {\n  now rewrite polyn_degree_lt_add.\n}\napply Nat.nlt_ge in HQP'.\ndestruct (lt_dec (polyn_degree P') (polyn_degree Q')) as [H| H]. {\n  rewrite polyn_add_comm, polyn_degree_lt_add; [ | easy ].\n  etransitivity; [ apply HP | easy ].\n}\napply Nat.nlt_ge in H.\napply Nat.le_antisymm in HQP'; [ clear H | easy ].\nnow rewrite polyn_degree_add_not_cancel.\nQed.\n\n(* *)\n\nTheorem nth_norm_polyn_list_map : ∀ i len f,\n  (∀ i, len ≤ i → f i = 0%Srng)\n  → nth i (norm_polyn_list (map f (seq 0 len))) 0%Srng = f i.\nProof.\nintros * Hf.\nrevert i.\ninduction len; intros. {\n  cbn; rewrite match_id; symmetry.\n  apply Hf, Nat.le_0_l.\n}\nrewrite List_seq_succ_r.\nrewrite map_app.\nrewrite norm_polyn_list_app.\ncbn - [ norm_polyn_list ].\nunfold norm_polyn_list at 1.\ncbn - [ norm_polyn_list ].\ndestruct (srng_eq_dec (f len) 0) as [Hfz| Hfz]. {\n  cbn - [ norm_polyn_list ].\n  apply IHlen.\n  intros j Hj.\n  destruct (Nat.eq_dec j len) as [Hjlen| Hjlen]. {\n    now rewrite Hjlen.\n  }\n  apply Hf.\n  flia Hj Hjlen.\n}\ncbn.\ndestruct (lt_dec i len) as [Hilen| Hilen]. {\n  rewrite app_nth1; [ | now rewrite map_length, seq_length ].\n  rewrite (List_map_nth_in _ 0); [ | now rewrite seq_length ].\n  now rewrite seq_nth.\n}\napply Nat.nlt_ge in Hilen.\nrewrite app_nth2; [ | now rewrite map_length, seq_length ].\nrewrite map_length, seq_length.\ndestruct (Nat.eq_dec i len) as [Hiel| Hiel]. {\n  now rewrite Hiel, Nat.sub_diag.\n}\nrewrite nth_overflow; [ | cbn; flia Hilen Hiel ].\nsymmetry.\napply Hf.\nflia Hilen Hiel.\nQed.\n\nTheorem polyn_coeff_overflow : ∀ P n,\n  polyn_degree P < n\n  → polyn_coeff P n = 0%Srng.\nProof.\nintros (la, Hla) n Hpn.\ncbn in Hpn |-*.\nrewrite nth_overflow; [ easy | flia Hpn ].\nQed.\n\nTheorem polyn_coeff_1_of_x_add_const : ∀ c,\n  polyn_coeff (_x + polyn_of_const c) 1 = 1%Srng.\nProof.\nintros.\nunfold polyn_coeff; cbn.\nrewrite if_1_eq_0; cbn.\nnow destruct (srng_eq_dec c 0); cbn; rewrite if_1_eq_0.\nQed.\n\nTheorem polyn_coeff_mul : ∀ P Q i,\n  polyn_coeff (P * Q)%P i =\n    (Σ (j = 0, i), polyn_coeff P j * polyn_coeff Q (i - j))%Srng.\nProof.\nintros.\ncbn - [ iter_seq ].\ndestruct P as (la, Hla).\ndestruct Q as (lb, Hlb).\ncbn - [ iter_seq norm_polyn_list ].\nunfold polyn_list_convol_mul.\nremember (length la + length lb - 1) as len eqn:Hlen.\ndestruct (lt_dec i len) as [Hilen| Hilen]. 2: {\n  apply Nat.nlt_ge in Hilen.\n  rewrite nth_overflow. 2: {\n    etransitivity; [ apply norm_polyn_list_length_le | ].\n    now rewrite map_length, seq_length.\n  }\n  symmetry.\n  apply all_0_srng_summation_0; [ easy | ].\n  intros j Hj.\n  destruct (lt_dec j (length la)) as [Hjla| Hjla]. 2: {\n    apply Nat.nlt_ge in Hjla.\n    rewrite nth_overflow; [ | easy ].\n    apply srng_mul_0_l.\n  }\n  destruct (lt_dec (i - j) (length lb)) as [Hjlb| Hjlb]. 2: {\n    apply Nat.nlt_ge in Hjlb.\n    rewrite (nth_overflow lb); [ | easy ].\n    apply srng_mul_0_r.\n  }\n  flia Hlen Hilen Hj Hjla Hjlb.\n}\nrewrite nth_norm_polyn_list_map; [ easy | ].\nintros j Hj.\napply all_0_srng_summation_0; [ easy | ].\nintros k Hk.\ndestruct (lt_dec k (length la)) as [Hka| Hka]. 2: {\n  apply Nat.nlt_ge in Hka.\n  rewrite nth_overflow; [ | easy ].\n  apply srng_mul_0_l.\n}\ndestruct (lt_dec (j - k) (length lb)) as [Hjkb| Hjkb]. 2: {\n  apply Nat.nlt_ge in Hjkb.\n  rewrite (nth_overflow lb); [ | easy ].\n  apply srng_mul_0_r.\n}\nflia Hlen Hj Hka Hjkb.\nQed.\n\n(* degree of monomial \"x\" *)\n\nTheorem polyn_degree_monom : polyn_degree _x = 1.\nProof.\nnow cbn; rewrite if_1_eq_0.\nQed.\n\nTheorem polyn_degree_summation_ub : ∀ b e f,\n  polyn_degree (Σ (i = b, e), f i)%Srng ≤ Max (i = b, e), polyn_degree (f i).\nProof.\nintros.\nunfold iter_seq.\nremember (S e - b) as len eqn:Hlen.\nclear e Hlen.\nrevert b.\ninduction len; intros; [ cbn; flia | ].\ncbn; rewrite polyn_add_0_l.\nrewrite fold_left_srng_add_fun_from_0.\nrewrite fold_left_max_fun_from_0.\ncbn - [ polyn_degree ].\nrewrite polyn_add_comm.\netransitivity; [ apply polyn_degree_add_ub | ].\nrewrite Nat.max_comm.\napply Nat.max_le_compat_l.\napply IHlen.\napply polyn_semiring_prop.\nQed.\n\nTheorem polyn_coeff_opp : ∀ P i,\n  polyn_coeff (- P) i = (- polyn_coeff P i)%Rng.\nProof.\nintros (la, Hla) *; cbn.\nunfold polyn_coeff.\ndestruct (lt_dec i (length la)) as [Hila| Hila]. {\n  now rewrite (List_map_nth_in _ 0%Rng).\n}\napply Nat.nlt_ge in Hila.\nrewrite nth_overflow; [ | now rewrite map_length ].\nrewrite nth_overflow; [ | easy ].\nsymmetry.\napply rng_opp_0.\nQed.\n\nTheorem is_monic_polyn_add : ∀ (P Q : polynomial T),\n  polyn_degree Q < polyn_degree P\n  → is_monic_polyn P\n  → is_monic_polyn (P + Q).\nProof.\nintros * Hdeg HP.\nunfold is_monic_polyn in HP |-*.\nrewrite polyn_degree_lt_add; [ | easy ].\ncbn in HP |-*.\ndestruct P as (la, Hla).\ndestruct Q as (lb, Hlb).\nmove lb before la.\ncbn in Hla, Hlb, Hdeg, HP.\ncbn - [ norm_polyn_list ].\ndestruct la as [| a]; [ easy | ].\ncbn - [ nth ] in HP.\ncbn - [ norm_polyn_list \"+\"%PL ].\nrewrite Nat.sub_0_r in HP |-*.\ndestruct lb as [| b]. {\n  rewrite polyn_list_add_0_r.\n  rewrite norm_polyn_list_id; [ easy | ].\n  rewrite List_last_nth_cons, HP.\n  apply srng_1_neq_0.\n}\ncbn in Hdeg.\ndo 2 rewrite Nat.sub_0_r in Hdeg.\nrewrite <- List_last_nth_cons in HP.\nclear - Hdeg HP.\nmove b before a.\nrevert a b lb Hdeg HP.\ninduction la as [| a1]; intros; [ easy | ].\nrewrite List_last_cons_cons in HP.\ndestruct lb as [| b1]. {\n  cbn - [ norm_polyn_list ].\n  rewrite norm_polyn_list_id. 2: {\n    remember (a1 :: la) as l; cbn; subst l.\n    rewrite HP.\n    apply srng_1_neq_0.\n  }\n  remember (a1 :: la) as l; cbn; subst l.\n  now rewrite List_last_nth_cons in HP.\n}\ncbn - [ norm_polyn_list ].\ncbn in Hdeg.\napply Nat.succ_lt_mono in Hdeg.\nspecialize (IHla a1 b1 lb Hdeg HP).\nrewrite norm_polyn_list_cons; [ easy | ].\nrewrite List_last_cons_cons.\nclear - so sdp HP Hdeg.\nrevert lb a1 b1 HP Hdeg.\ninduction la as [| a]; intros; [ easy | cbn ].\nrewrite List_last_cons_cons in HP.\ndestruct lb as [| b]. {\n  rewrite HP.\n  apply srng_1_neq_0.\n}\ncbn in Hdeg.\napply Nat.succ_lt_mono in Hdeg.\nnow apply IHla.\nQed.\n\nTheorem polyn_list_add_map : ∀ A f g (l : list A),\n  (map f l + map g l)%PL = (map (λ i, (f i + g i)%Rng) l).\nProof.\nintros A *.\ninduction l as [| a la]; [ easy | ].\nnow cbn; rewrite IHla.\nQed.\n\nTheorem polyn_list_add_repeat_0_r : ∀ la n,\n  (la + repeat 0%Srng n)%PL = la ++ repeat 0%Srng (n - length la).\nProof.\nintros.\nrevert n.\ninduction la as [| a]; intros. {\n  now cbn; rewrite Nat.sub_0_r.\n}\ndestruct n. {\n  now cbn; rewrite app_nil_r.\n}\ncbn; rewrite srng_add_0_r; f_equal.\napply IHla.\nQed.\n\nTheorem polyn_degree_mul : ∀ (P Q : polynomial T),\n  (polyn_coeff P (polyn_degree P) * polyn_coeff Q (polyn_degree Q) ≠ 0)%Srng\n  → polyn_degree (P * Q) = polyn_degree P + polyn_degree Q.\nProof.\nintros * HPQ.\nunfold polyn_degree; cbn.\nunfold polyn_degree_plus_1.\ndestruct P as (la, Hla).\ndestruct Q as (lb, Hlb).\nmove lb before la.\ncbn - [ norm_polyn_list polyn_list_mul ].\ncbn in HPQ.\ndo 2 rewrite <- List_last_nth in HPQ.\nrewrite norm_polyn_list_id. 2: {\n  destruct la as [| a]. {\n    exfalso; apply HPQ; cbn.\n    apply srng_mul_0_l.\n  }\n  destruct lb as [| b]. {\n    exfalso; apply HPQ; cbn.\n    apply srng_mul_0_r.\n  }\n  rewrite List_last_nth.\n  cbn; rewrite map_length, seq_length, Nat.sub_0_r.\n  rewrite Nat.add_succ_r, Nat.sub_succ, Nat.sub_0_r.\n  rewrite (List_map_nth_in _ 0); [ | rewrite seq_length; flia ].\n  rewrite seq_nth; [ | flia ].\n  rewrite Nat.add_0_l.\n  unfold polyn_list_convol_mul.\n  destruct (zerop (length la)) as [Hzla| Hzla]. {\n    rewrite Hzla, Nat.add_0_l.\n    apply length_zero_iff_nil in Hzla; subst la.\n    rewrite srng_summation_split_first; [ | easy | flia ].\n    rewrite Nat.sub_0_r, <- List_hd_nth_0; unfold hd.\n    rewrite <- List_last_nth_cons.\n    rewrite all_0_srng_summation_0; [ | easy | ]. 2: {\n      intros i Hi.\n      rewrite nth_overflow; [ | easy ].\n      apply srng_mul_0_l.\n    }\n    now rewrite srng_add_0_r.\n  }\n  rewrite srng_summation_split with (j := length la - 1); [ | easy | flia ].\n  rewrite all_0_srng_summation_0; [ | easy | ]. 2: {\n    intros i (_, Hi).\n    rewrite (nth_overflow (b :: lb)); [ | cbn; flia Hi Hzla ].\n    apply srng_mul_0_r.\n  }\n  rewrite srng_add_0_l.\n  rewrite Nat.sub_add; [ | easy ].\n  rewrite srng_summation_split_first; [ | easy | flia ].\n  rewrite Nat.add_comm, Nat.add_sub.\n  do 2 rewrite <- List_last_nth_cons.\n  rewrite all_0_srng_summation_0; [ | easy | ]. 2: {\n    intros i Hi.\n    rewrite nth_overflow; [ | easy ].\n    apply srng_mul_0_l.\n  }\n  now rewrite srng_add_0_r.\n}\nunfold \"*\"%PL.\nrewrite map_length, seq_length.\ndestruct (zerop (length la)) as [Hzla| Hzla]. {\n  exfalso; apply HPQ.\n  apply length_zero_iff_nil in Hzla; subst la; cbn.\n  apply srng_mul_0_l.\n}\ndestruct (zerop (length lb)) as [Hzlb| Hzlb]. {\n  exfalso; apply HPQ.\n  apply length_zero_iff_nil in Hzlb; subst lb; cbn.\n  apply srng_mul_0_r.\n}\nflia Hzla Hzlb.\nQed.\n\nTheorem polyn_degree_mul_le : ∀ P Q,\n  polyn_degree (P * Q) ≤ polyn_degree P + polyn_degree Q.\nProof.\nintros.\ndestruct\n  (srng_eq_dec\n     (polyn_coeff P (polyn_degree P) * polyn_coeff Q (polyn_degree Q)) 0)\n  as [Hzz| Hzz]. 2: {\n  now rewrite polyn_degree_mul.\n}\nunfold polyn_degree; cbn.\nunfold polyn_degree_plus_1.\ndestruct P as (la, Hla).\ndestruct Q as (lb, Hlb).\nmove lb before la.\ncbn - [ norm_polyn_list polyn_list_mul ].\ncbn in Hzz.\ndo 2 rewrite <- List_last_nth in Hzz.\nunfold \"*\"%PL.\ndestruct la as [| a]. {\n  clear Hla.\n  unfold polyn_list_convol_mul.\n  rewrite (proj1 (all_0_norm_polyn_list_map_0 _ _)); [ cbn; flia | ].\n  intros i Hi; cbn in Hi.\n  apply all_0_srng_summation_0; [ easy | ].\n  intros j Hj.\n  destruct j; cbn; apply srng_mul_0_l.\n}\ncbn - [ nth ] in Hla.\nrewrite <- List_last_nth_cons in Hla.\ndestruct (srng_eq_dec (last (a :: la) 0%Srng) 0) as [Haz| Haz]; [ easy | ].\nclear Hla.\ncbn - [ norm_polyn_list ].\ndo 2 rewrite Nat.sub_0_r.\ndestruct lb as [| b]. {\n  clear Hlb.\n  unfold polyn_list_convol_mul.\n  rewrite (proj1 (all_0_norm_polyn_list_map_0 _ _)); [ cbn; flia | ].\n  intros i Hi.\n  apply all_0_srng_summation_0; [ easy | ].\n  intros j Hj.\n  destruct (i - j); cbn; apply srng_mul_0_r.\n}\ncbn - [ nth ] in Hlb.\nrewrite <- List_last_nth_cons in Hlb.\ndestruct (srng_eq_dec (last (b :: lb) 0%Srng) 0) as [Hbz| Hbz]; [ easy | ].\nclear Hlb.\ncbn - [ norm_polyn_list ].\nrewrite Nat.sub_0_r.\nrewrite Nat.add_succ_r.\ncbn - [ norm_polyn_list ].\nrewrite srng_add_0_l.\nremember (_ :: _) as l in |-*.\ndestruct (srng_eq_dec (last l 0%Srng) 0) as [Hlab| Hlab]. 2: {\n  subst l.\n  rewrite norm_polyn_list_cons; [ | easy ].\n  cbn; rewrite Nat.sub_0_r.\n  remember (_ :: _) as l in Hlab.\n  symmetry in Heql.\n  destruct l as [| x]; [ easy | ].\n  injection Heql; clear Heql; intros Hl Hab; subst x.\n  rewrite Hl.\n  destruct l as [| x]; [ cbn; flia | ].\n  rewrite List_last_cons_cons in Hlab.\n  rewrite norm_polyn_list_id; [ | easy ].\n  rewrite <- Hl.\n  now rewrite map_length, seq_length.\n}\netransitivity; [ apply Nat.sub_le_mono_r, norm_polyn_list_length_le | ].\nrewrite Heql; cbn.\nrewrite map_length, seq_length.\nnow rewrite Nat.sub_0_r.\nQed.\n\nTheorem polyn_coeff_mul_at_0 : ∀ P Q,\n  polyn_coeff (P * Q) 0 = (polyn_coeff P 0 * polyn_coeff Q 0)%Srng.\nProof.\nintros (la, Hla) (lb, Hlb).\nmove lb before la.\ncbn - [ polyn_list_mul ].\ndestruct la as [| a]. {\n  rewrite polyn_list_mul_0_l; cbn.\n  symmetry.\n  apply srng_mul_0_l.\n}\ncbn - [ nth ] in Hla.\nrewrite <- List_last_nth_cons in Hla.\ndestruct (srng_eq_dec (last (a :: la) 0%Srng) 0) as [| Haz]; [ easy | ].\nclear Hla.\ncbn - [ norm_polyn_list polyn_list_mul ].\ndestruct lb as [| b]. {\n  rewrite polyn_list_mul_0_r; cbn.\n  symmetry.\n  apply srng_mul_0_r.\n}\ncbn - [ nth ] in Hlb.\nrewrite <- List_last_nth_cons in Hlb.\ndestruct (srng_eq_dec (last (b :: lb) 0%Srng) 0) as [| Hbz]; [ easy | ].\nclear Hlb; cbn.\nrewrite Nat.sub_0_r, Nat.add_succ_r; cbn.\nrewrite srng_add_0_l.\nrewrite strip_0s_app; cbn.\nremember (strip_0s _) as lc eqn:Hlc.\nsymmetry in Hlc.\ndestruct lc as [| c]; [ now destruct (srng_eq_dec (a * b) 0) | ].\nnow cbn; rewrite rev_app_distr; cbn.\nQed.\n\nTheorem polyn_of_list_0 : polyn_of_list [0%Rng] = 0%P.\nProof.\napply polyn_eq; cbn.\nnow destruct (srng_eq_dec 0 0).\nQed.\n\nTheorem polyn_degree_1 : ∀ P,\n  polyn_degree P = 0\n  → polyn_degree (_x + P) = 1.\nProof.\nintros (la, Hla) HP.\ncbn - [ norm_polyn_list ] in HP |-*.\nrewrite norm_polyn_list_add_idemp_l.\ndestruct la as [| a] using rev_ind; [ now cbn; rewrite if_1_eq_0 | ].\nclear IHla.\ndestruct la as [| a1]. 2: {\n  cbn in HP.\n  rewrite app_length in HP; cbn in HP; flia HP.\n}\nclear HP; cbn.\nnow rewrite if_1_eq_0.\nQed.\n\nTheorem polyn_degree_of_const : ∀ a, polyn_degree (polyn_of_const a) = 0.\nProof.\nnow intros; cbn; destruct (srng_eq_dec a 0).\nQed.\n\nTheorem polyn_coeff_of_const : ∀ a, polyn_coeff (polyn_of_const a) 0 = a.\nProof.\nnow intros; cbn; destruct (srng_eq_dec a 0).\nQed.\n\nTheorem polyn_of_list_repeat_0s : ∀ n,\n  polyn_of_list (repeat 0%Rng n) = 0%P.\nProof.\nintros.\napply polyn_eq; cbn.\ninduction n; [ easy | ].\nrewrite List_repeat_succ_app.\nrewrite norm_polyn_list_app; cbn.\nnow rewrite if_0_eq_0.\nQed.\n\nTheorem polyn_coeff_add : ∀ P Q i,\n  polyn_coeff (P + Q)%P i = (polyn_coeff P i + polyn_coeff Q i)%Srng.\nProof.\nintros (la, Hla) (lb, Hlb) i.\nmove lb before la.\ncbn - [ norm_polyn_list ].\nunfold polyn_prop_test in Hla.\nunfold polyn_prop_test in Hlb.\ninduction la as [| a] using rev_ind. {\n  rewrite polyn_list_add_0_l.\n  rewrite (nth_overflow []); [ | cbn; flia ].\n  rewrite srng_add_0_l.\n  revert i.\n  induction lb as [| b] using rev_ind; intros; [ easy | ].\n  rewrite app_length, Nat.add_comm in Hlb; cbn in Hlb.\n  rewrite app_nth2 in Hlb; [ | now unfold ge ].\n  rewrite Nat.sub_diag in Hlb; cbn in Hlb.\n  rewrite norm_polyn_list_app; cbn.\n  now destruct (srng_eq_dec b 0).\n}\nclear IHla.\nrewrite app_length, Nat.add_comm in Hla; cbn in Hla.\nrewrite app_nth2 in Hla; [ | now unfold ge ].\nrewrite Nat.sub_diag in Hla; cbn in Hla.\ndestruct (srng_eq_dec a 0) as [Haz| Haz]; [ easy | clear Hla ].\ninduction lb as [| b] using rev_ind. {\n  rewrite polyn_list_add_0_r.\n  rewrite (nth_overflow []); [ | cbn; flia ].\n  rewrite srng_add_0_r.\n  rewrite norm_polyn_list_id; [ easy | now rewrite List_last_app ].\n}\nclear IHlb.\nrewrite app_length, Nat.add_comm in Hlb; cbn in Hlb.\nrewrite app_nth2 in Hlb; [ | now unfold ge ].\nrewrite Nat.sub_diag in Hlb; cbn in Hlb.\ndestruct (srng_eq_dec b 0) as [Hbz| Hbz]; [ easy | clear Hlb ].\nmove b before a.\ndestruct (Nat.eq_dec (length la) (length lb)) as [Hlab| Hlab]. 2: {\n  rewrite norm_polyn_list_id. 2: {\n    destruct (lt_dec (length la) (length lb)) as [Hll| Hll]. {\n      clear Hlab i.\n      rewrite polyn_list_add_app_r.\n      rewrite skipn_all2; [ | now rewrite app_length, Nat.add_1_r ].\n      now rewrite List_last_app_not_nil_r.\n    } {\n      assert (H : length lb < length la) by flia Hlab Hll.\n      clear Hlab Hll i.\n      rewrite polyn_list_add_app_l.\n      rewrite skipn_all2; [ | now rewrite app_length, Nat.add_1_r ].\n      now rewrite List_last_app_not_nil_r.\n    }\n  }\n  apply list_polyn_nth_add.\n}\nrewrite polyn_list_add_app_l.\nrewrite firstn_app.\nrewrite Hlab, firstn_all.\nrewrite Nat.sub_diag, firstn_O.\nrewrite app_nil_r.\nrewrite skipn_app.\nrewrite skipn_all, Nat.sub_diag, skipn_O.\nrewrite app_nil_l; cbn.\nrewrite norm_polyn_list_app; cbn.\ndestruct (srng_eq_dec (a + b) 0) as [Habz| Habz]. {\n  cbn.\n  destruct (lt_dec i (length la)) as [Hil| Hil]. {\n    rewrite app_nth1; [ | easy ].\n    rewrite app_nth1; [ | congruence ].\n    clear a b Haz Hbz Habz.\n    revert i lb Hlab Hil.\n    induction la as [| a]; intros. {\n      rewrite (nth_overflow []); [ | cbn; flia ].\n      symmetry in Hlab.\n      apply length_zero_iff_nil in Hlab; subst lb.\n      now rewrite srng_add_0_l.\n    }\n    destruct lb as [| b]; [ easy | ].\n    cbn in Hlab.\n    apply Nat.succ_inj in Hlab.\n    destruct i. {\n      cbn.\n      rewrite strip_0s_app.\n      remember (strip_0s _) as lc eqn:Hlc.\n      symmetry in Hlc.\n      destruct lc as [| c]; [ now cbn; destruct (srng_eq_dec (a + b) 0) | ].\n      now cbn; rewrite rev_app_distr.\n    }\n    cbn in Hil.\n    apply Nat.succ_lt_mono in Hil.\n    cbn - [ norm_polyn_list ].\n    specialize (IHla _ _ Hlab Hil) as H1.\n    unfold norm_polyn_list in H1 |-*; cbn.\n    rewrite strip_0s_app.\n    remember (strip_0s (rev (la + lb)%PL)) as lc eqn:Hlc.\n    symmetry in Hlc.\n    destruct lc as [| c]. {\n      cbn in H1 |-*.\n      destruct (srng_eq_dec (a + b) 0) as [Habz| Habz]; [ now destruct i | ].\n      easy.\n    }\n    cbn in H1 |-*.\n    now rewrite rev_app_distr.\n  }\n  apply Nat.nlt_ge in Hil.\n  rewrite app_nth2; [ | easy ].\n  rewrite app_nth2; [ | now rewrite <- Hlab ].\n  destruct (Nat.eq_dec i (length la)) as [Hila| Hila]. {\n    rewrite Hila, Hlab, Nat.sub_diag; cbn.\n    rewrite Habz.\n    apply nth_overflow.\n    etransitivity; [ apply norm_polyn_list_length_le | ].\n    rewrite polyn_list_add_length.\n    rewrite max_r; [ easy | ].\n    now rewrite Hlab.\n  }\n  rewrite (nth_overflow [a]); [ | cbn; flia Hil Hila ].\n  rewrite (nth_overflow [b]); [ | cbn; flia Hil Hila Hlab ].\n  rewrite srng_add_0_l.\n  apply nth_overflow.\n  etransitivity; [ apply norm_polyn_list_length_le | ].\n  rewrite polyn_list_add_length.\n  rewrite max_l; [ easy | ].\n  now rewrite Hlab.\n}\ncbn.\ndestruct (lt_dec i (length la)) as [Hil| Hil]. {\n  rewrite app_nth1. 2: {\n    rewrite polyn_list_add_length.\n    rewrite max_l; [ easy | ].\n    now rewrite Hlab.\n  }\n  rewrite app_nth1; [ | easy ].\n  rewrite app_nth1; [ | now rewrite <- Hlab ].\n  apply list_polyn_nth_add.\n}\ndestruct (lt_dec (length la) i) as [Hlai| Hlai]. {\n  rewrite nth_overflow. 2: {\n    rewrite app_length, Nat.add_1_r.\n    rewrite polyn_list_add_length.\n    rewrite max_l; [ easy | ].\n    now rewrite Hlab.\n  }\n  rewrite nth_overflow. 2: {\n    now rewrite app_length, Nat.add_1_r.\n  }\n  rewrite nth_overflow. 2: {\n    now rewrite app_length, Nat.add_1_r, <- Hlab.\n  }\n  now rewrite srng_add_0_l.\n}\napply Nat.nlt_ge in Hil.\napply Nat.nlt_ge in Hlai.\napply Nat.le_antisymm in Hil; [ | easy ].\nrewrite Hil.\nrewrite app_nth2. 2: {\n  rewrite polyn_list_add_length.\n  unfold ge.\n  rewrite max_l; [ easy | now rewrite Hlab ].\n}\nrewrite polyn_list_add_length.\nrewrite max_l; [ | now rewrite Hlab ].\nrewrite app_nth2; [ | now unfold ge ].\nrewrite app_nth2; [ | now unfold ge; rewrite Hlab ].\nrewrite Hlab.\nnow rewrite Nat.sub_diag.\nQed.\n\n(* sub-polynomial:\n   polynomial skipping i coefficients:\n     input: Σ (j = 0, n), a_j x^j\n     output: Σ (j = i, n), a_j x^(j-i) *)\n\nTheorem sub_polyn_prop : ∀ i P,\n  polyn_prop_test (λ i0 : nat, nth i0 (skipn i (polyn_list P)) 0%Srng)\n    (length (skipn i (polyn_list P))) = true.\nProof.\nintros i (la, Hla); cbn.\nrevert i.\ninduction la as [| a]; intros; [ now rewrite skipn_nil | ].\ncbn - [ nth ] in Hla.\nrewrite <- List_last_nth_cons in Hla.\ndestruct (srng_eq_dec (last (a :: la) 0%Srng) 0) as [H| Haz]; [ easy | ].\nclear Hla.\nrewrite skipn_length.\ncbn - [ sub ].\nassert (H : polyn_prop_test (λ i : nat, nth i la 0%Srng) (length la) = true). {\n  clear - Haz.\n  revert a Haz.\n  induction la as [| a1]; intros; [ easy | ].\n  cbn - [ nth ].\n  rewrite  <- List_last_nth_cons.\n  rewrite List_last_cons_cons in Haz.\n  now destruct (srng_eq_dec (last (a1 :: la) 0%Srng) 0).\n}\nspecialize (IHla H); clear H.\ndestruct i. {\n  rewrite Nat.sub_0_r.\n  cbn - [ nth ].\n  rewrite  <- List_last_nth_cons.\n  now destruct (srng_eq_dec (last (a :: la) 0%Srng) 0).\n}\nrewrite Nat.sub_succ.\nspecialize (IHla i) as H1.\nnow rewrite skipn_length in H1.\nQed.\n\nTheorem polyn_list_length : ∀ P,\n  length (polyn_list P) = polyn_degree_plus_1 P.\nProof. easy. Qed.\n\nDefinition sub_polyn_list (la : list T) i := skipn i la.\n\nDefinition sub_polyn P i :=\n  {| polyn_list := sub_polyn_list (polyn_list P) i;\n     polyn_prop := sub_polyn_prop i P |}.\n\nTheorem eval_polyn_list_cons : ∀ la (a x : T),\n  eval_polyn_list (a :: la) x = (a + x * eval_polyn_list la x)%Srng.\nProof.\nintros.\ncbn; rewrite srng_add_comm; f_equal.\napply srng_c_mul_comm.\nQed.\n\nTheorem last_polyn_list_add_length_lt : ∀ la lb d,\n  length lb < length la\n  → last (la + lb)%PL d = last la d.\nProof.\nintros * Hll.\nrewrite polyn_list_add_comm.\nrevert la Hll.\ninduction lb as [| b] using rev_ind; intros; [ easy | ].\ndestruct la as [| a] using rev_ind; [ now cbn in Hll | clear IHla ].\ndo 2 rewrite app_length, Nat.add_1_r in Hll.\napply Nat.succ_lt_mono in Hll.\nrewrite List_last_app.\nrewrite polyn_list_add_app_l.\nrewrite firstn_app.\nrewrite (proj2 (Nat.sub_0_le _ _)); [ | flia Hll ].\nrewrite firstn_O, app_nil_r.\nrewrite skipn_app.\nrewrite (proj2 (Nat.sub_0_le _ _)); [ | flia Hll ].\nrewrite skipn_O.\nrewrite List_last_app_not_nil_r. 2: {\n  now destruct (skipn (length lb) la).\n}\ncbn.\nremember (skipn (length lb) la) as lc eqn:Hlc.\nsymmetry in Hlc.\ndestruct lc as [| c]. {\n  exfalso.\n  remember (length lb) as len.\n  clear - Hll Hlc.\n  revert la Hll Hlc.\n  induction len; intros; cbn. {\n    now cbn in Hlc; subst la.\n  }\n  destruct la as [| a]; [ easy | ].\n  cbn in Hll, Hlc.\n  apply Nat.succ_lt_mono in Hll.\n  now apply (IHlen la).\n}\ncbn.\nrewrite List_last_app.\nremember (lc ++ [a]) as ld eqn:Hld.\nsymmetry in Hld.\ndestruct ld; [ | easy ].\nnow apply app_eq_nil in Hld.\nQed.\n\nTheorem polyn_list_mul_last : ∀ la lb,\n  last (la * lb)%PL 0%Srng = (last la 0 * last lb 0)%Srng.\nProof.\nintros.\nunfold polyn_list_mul.\nremember (length la + length lb - 1) as len eqn:Hlen.\nsymmetry in Hlen.\nrevert la lb Hlen.\ninduction len; intros. {\n  cbn.\n  destruct la as [| a]; [ now cbn; rewrite srng_mul_0_l | ].\n  cbn in Hlen; rewrite Nat.sub_0_r in Hlen.\n  destruct la; [ | easy ].\n  apply length_zero_iff_nil in Hlen; subst lb; cbn.\n  symmetry; apply srng_mul_0_r.\n}\nrewrite List_seq_succ_r.\nrewrite map_app.\ncbn - [ last polyn_list_convol_mul ].\nrewrite List_last_app.\nunfold polyn_list_convol_mul.\ndo 2 rewrite List_last_nth.\ndestruct la as [| a]. {\n  rewrite all_0_srng_summation_0; [ | easy | ]. 2: {\n    intros i Hi.\n    rewrite nth_overflow; [ | cbn; flia ].\n    apply srng_mul_0_l.\n  }\n  cbn; symmetry.\n  apply srng_mul_0_l.\n}\ndestruct lb as [| b]. {\n  rewrite all_0_srng_summation_0; [ | easy | ]. 2: {\n    intros i Hi.\n    rewrite (nth_overflow []); [ | cbn; flia ].\n    apply srng_mul_0_r.\n  }\n  cbn; symmetry.\n  apply srng_mul_0_r.\n}\ncbn in Hlen.\ncbn - [ iter_seq nth ].\ndo 2 rewrite Nat.sub_0_r.\ndestruct la as [| a1]. {\n  cbn in Hlen.\n  apply Nat.succ_inj in Hlen.\n  rewrite srng_summation_split_first; [ | easy | flia ].\n  rewrite all_0_srng_summation_0; [ | easy | ]. 2: {\n    intros i Hi.\n    destruct i; [ easy | ].\n    rewrite nth_overflow; [ | cbn; flia ].\n    apply srng_mul_0_l.\n  }\n  rewrite srng_add_0_r, Nat.sub_0_r.\n  now rewrite Hlen.\n}\nrewrite <- List_last_nth_cons.\nrewrite List_last_cons_cons.\nrewrite List_last_nth_cons.\nrewrite Nat.sub_0_r in Hlen; cbn in Hlen.\nrewrite srng_summation_split with (j := S (length la)); [ | easy | flia Hlen ].\nrewrite srng_summation_split with (j := length la); [ | easy | flia Hlen ].\nrewrite all_0_srng_summation_0; [ | easy | ]. 2: {\n  intros i Hi.\n  rewrite (nth_overflow (b :: lb)); [ | cbn; flia Hlen Hi ].\n  apply srng_mul_0_r.\n}\nrewrite srng_add_0_l.\nrewrite Nat.add_1_r.\nrewrite srng_summation_only_one; [ | easy ].\nrewrite all_0_srng_summation_0; [ | easy | ]. 2: {\n  intros i Hi.\n  rewrite (nth_overflow (a :: a1 :: la)); [ | cbn; flia Hlen Hi ].\n  apply srng_mul_0_l.\n}\nrewrite srng_add_0_r.\nnow replace (len - S (length la)) with (length lb) by flia Hlen.\nQed.\n\n(* division of a polynomial P with (x - c) *)\n(* P = (x-c).Q + R with\n   Q = a_n.x^{n-1} +\n       (a_n.c+a_{n-1}).x^{n-2} +\n       ... +\n       ((a_n.c+a_{n-1})c+...+a_1)x^0\n   R = P(c) *)\n\nDefinition polyn_list_div_x_sub_const la c :=\n  (map (λ i, eval_polyn_list (sub_polyn_list la i) c) (seq 1 (length la - 1)),\n   eval_polyn_list la c).\n\nDefinition polyn_div_x_sub_const P c :=\n  (polyn_of_list (fst (polyn_list_div_x_sub_const (polyn_list P) c)),\n   snd (polyn_list_div_x_sub_const (polyn_list P) c)).\n\nTheorem norm_polyn_list_div_x_sub_const_prop : ∀ la lq c r,\n  last la 0%Srng ≠ 0%Srng\n  → polyn_list_div_x_sub_const la c = (lq, r)\n  → norm_polyn_list ([(- c); 1]%Rng * lq + [r])%PL =\n     ([(- c); 1]%Rng * lq + [r])%PL.\nProof.\nintros * Haz Hqr.\nremember (length la) as n eqn:Hn; symmetry in Hn.\ndestruct n. {\n  now apply length_zero_iff_nil in Hn; subst la.\n}\ndestruct n. {\n  destruct la as [| a]; [ easy | ].\n  destruct la; [ | easy ].\n  injection Hqr; clear Hqr; intros Hr Hq.\n  rewrite srng_mul_0_l, srng_add_0_l in Hr.\n  subst a lq; cbn.\n  rewrite srng_mul_0_r, srng_add_0_l, srng_add_0_l.\n  now destruct (srng_eq_dec r 0).\n}\napply norm_polyn_list_id.\nrewrite last_polyn_list_add_length_lt. 2: {\n  cbn - [ polyn_list_mul ].\n  destruct lq as [| q]; [ exfalso | cbn; flia ].\n  injection Hqr; clear Hqr; intros Hr Hq.\n  apply map_eq_nil in Hq.\n  now rewrite Hn in Hq.\n}\nrewrite polyn_list_mul_last.\ncbn; rewrite srng_mul_1_l.\ninjection Hqr; clear Hqr; intros Hr Hq.\nrewrite Hn, Nat.sub_succ, Nat.sub_0_r in Hq.\nrewrite <- Hq.\nrewrite List_seq_succ_r.\nrewrite map_app.\ncbn - [ sub_polyn_list ].\nrewrite List_last_app.\nunfold sub_polyn_list.\nreplace (S n) with (length la - 1) by flia Hn.\nrewrite List_skipn_last with (d := 0%Srng) by now destruct la.\nnow cbn; rewrite srng_mul_0_l, srng_add_0_l.\nQed.\n\n(* P = (x-c) Q + r *)\nTheorem polyn_list_div_x_sub_const_prop0 : ∀ la lq c r,\n  last la 0%Srng ≠ 0%Srng\n  → polyn_list_div_x_sub_const la c = (lq, r)\n  → la = ([(- c)%Rng; 1%Srng] * lq + [r])%PL.\nProof.\nintros * Hqz Hqr.\nremember (length la) as n eqn:Hn; symmetry in Hn.\ninjection Hqr; clear Hqr; intros Hr Hq.\ndestruct (lt_dec n 2) as [Hn2| Hn2]. {\n  destruct n. {\n    now apply length_zero_iff_nil in Hn; subst la.\n  }\n  destruct n; [ | flia Hn2 ].\n  destruct la as [| a]; [ easy | ].\n  destruct la; [ | easy ].\n  cbn in Hr.\n  rewrite srng_mul_0_l, srng_add_0_l in Hr.\n  subst a lq; cbn.\n  rewrite srng_mul_0_r, srng_add_0_l, srng_add_0_l.\n  now destruct (srng_eq_dec r 0).\n}\napply Nat.nlt_ge in Hn2.\nsubst r lq.\ncbn; rewrite srng_add_0_l, polyn_list_add_0_r.\nrewrite map_length, seq_length.\nrewrite (List_map_nth_in _ 0); [ | rewrite seq_length; flia Hn Hn2 ].\nrewrite seq_nth; [ | flia Hn Hn2 ].\nrewrite Nat.add_0_r.\nreplace (sub_polyn_list la 1) with (tl la). 2: {\n  subst n.\n  destruct la; [ cbn in Hn2; flia Hn2 | ].\n  destruct la; [ cbn in Hn2; flia Hn2 | easy ].\n}\nreplace la with (hd 0%Srng la :: tl la) at 3. 2: {\n  destruct la; [ cbn in Hn; flia Hn Hn2 | easy ].\n}\nrewrite eval_polyn_list_cons.\nrewrite srng_add_comm.\nrewrite rng_mul_opp_l.\nrewrite fold_rng_sub, rng_add_sub.\ndestruct la as [| a]; [ cbn in Hn; flia Hn Hn2 | ].\nf_equal.\ncbn; rewrite Nat.sub_0_r.\napply (proj2 (List_eq_iff _ _)).\nrewrite map_length, seq_length.\nsplit; [ easy | ].\nintros.\ndestruct (le_dec (length la) i) as [Hila| Hila]. {\n  rewrite nth_overflow; [ | easy ].\n  rewrite nth_overflow; [ easy | ].\n  now rewrite map_length, seq_length.\n}\napply Nat.nle_gt in Hila.\nrewrite (List_map_nth_in _ 0); [ | now rewrite seq_length ].\nrewrite seq_nth; [ | easy ].\nrewrite (Nat.add_1_l i).\nunfold polyn_list_convol_mul.\nrewrite srng_summation_split_first; [ | easy | apply Nat.le_0_l ].\nerewrite srng_summation_eq_compat. 2: {\n  intros j Hj.\n  rewrite (List_map_nth_in _ 0). 2: {\n    rewrite seq_length.\n    flia Hila Hj.\n  }\n  easy.\n}\ncbn - [ iter_seq nth sub ].\nremember (nth 0 _ _) as x; cbn in Heqx; subst x.\nrewrite Nat.sub_0_r.\nrewrite srng_summation_split_first; [ | easy | flia ].\nrewrite all_0_srng_summation_0; [ | easy | ]. 2: {\n  intros j Hj.\n  rewrite nth_overflow; [ | easy ].\n  apply srng_mul_0_l.\n}\nrewrite srng_add_0_r.\nremember (nth 1 _ _) as x; cbn in Heqx; subst x.\nrewrite srng_mul_1_l.\nrewrite Nat.sub_succ, Nat.sub_0_r.\nrewrite seq_nth; [ | easy ].\ndestruct (le_dec (length la) (S i)) as [Hsila| Hsila]. {\n  assert (Hi : length la = S i) by flia Hila Hsila.\n  rewrite nth_overflow with (n := S i). 2: {\n    now rewrite map_length, seq_length.\n  }\n  rewrite srng_mul_0_r, srng_add_0_l.\n  rewrite Nat.add_1_l, <- Hi.\n  replace (length la) with (length (a :: la) - 1). 2: {\n    now cbn; rewrite Nat.sub_0_r.\n  }\n  unfold sub_polyn_list.\n  rewrite List_skipn_last with (d := d); [ | easy ].\n  remember (a :: la) as lb; cbn; subst lb.\n  rewrite srng_mul_0_l, srng_add_0_l.\n  rewrite List_last_nth_cons.\n  now rewrite Hi.\n}\napply Nat.nle_gt in Hsila.\nrewrite (List_map_nth_in _ 0); [ | now rewrite seq_length ].\nrewrite seq_nth; [ | easy ].\nunfold sub_polyn_list.\nrewrite List_skipn_cons_nth_skipn_succ with (n := 1 + i) (d := d). 2: {\n  now apply -> Nat.succ_lt_mono.\n}\nremember (1 + S i) as x; cbn in Heqx; subst x.\nremember (S (1 + i)) as x; cbn in Heqx; subst x.\nrewrite skipn_cons.\nremember (nth (1 + i) (a :: la)) as x; cbn in Heqx; subst x.\nremember (skipn (S i) la) as lb eqn:Hlb.\ncbn; unfold eval_polyn_list.\nrewrite srng_add_assoc, srng_c_mul_comm.\nrewrite rng_mul_opp_r.\nrewrite rng_add_opp_l; symmetry.\napply srng_add_0_l.\nQed.\n\nTheorem polyn_list_div_x_sub_const_prop : ∀ la lq c r,\n  last la 0%Srng ≠ 0%Srng\n  → polyn_list_div_x_sub_const la c = (lq, r)\n  → la = norm_polyn_list ([(- c)%Rng; 1%Srng] * lq + [r])%PL.\nProof.\nintros * Haz Hqr.\nrewrite (norm_polyn_list_div_x_sub_const_prop Haz); [ | easy ].\napply (polyn_list_div_x_sub_const_prop0 Haz Hqr).\nQed.\n\n(* P = (x - c) Q + r *)\nTheorem polyn_div_x_sub_const_prop : ∀ P c Q r,\n  polyn_div_x_sub_const P c = (Q, r)\n  → P = ((_x - polyn_of_const c) * Q + polyn_of_const r)%P.\nProof.\nintros * Hqr.\napply polyn_eq.\ncbn - [ norm_polyn_list polyn_list_mul ].\nrewrite norm_polyn_list_add_idemp_l.\nrewrite norm_polyn_list_add_idemp_l.\nrewrite norm_polyn_list_add_idemp_r.\nreplace  ([0%Srng; 1%Srng] + map rng_opp (norm_polyn_list [c]))%PL\n  with [(- c)%Rng; 1%Srng]. 2: {\n  cbn.\n  destruct (srng_eq_dec c 0) as [Hcz| Hcz]. {\n    subst c; cbn.\n    now rewrite rng_opp_0.\n  }\n  cbn.\n  now rewrite srng_add_0_l.\n}\nremember (norm_polyn_list [_; _]) as x eqn:Hx.\ncbn in Hx.\nrewrite if_1_eq_0 in Hx; cbn in Hx; subst x.\nunfold polyn_div_x_sub_const in Hqr.\nremember (polyn_list_div_x_sub_const _ _) as ll eqn:Hll.\nsymmetry in Hll.\ndestruct ll as (lq, rr).\ninjection Hqr; clear Hqr; intros Hr Hq; subst Q rr.\nremember (polyn_list (polyn_of_list lq)) as x eqn:Hx.\ncbn in Hx; subst x.\nrewrite <- norm_polyn_list_add_idemp_l.\nrewrite norm_polyn_list_mul_idemp_r.\nrewrite norm_polyn_list_add_idemp_l.\ndestruct (polyn_eq_dec P 0) as [Hpz| Hpz]. {\n  subst P.\n  cbn in Hll |-*.\n  injection Hll; clear Hll; intros; subst r lq; cbn.\n  rewrite srng_mul_0_r.\n  do 2 rewrite srng_add_0_l.\n  now rewrite if_0_eq_0.\n}\napply polyn_list_div_x_sub_const_prop; [ | easy ].\ndestruct P as (la, Hla).\ncbn in Hla |-*.\ndestruct la as [| a]. {\n  exfalso; apply Hpz.\n  now apply polyn_eq.\n}\ncbn - [ nth ] in Hla.\nclear Hll Hpz.\nrewrite <- List_last_nth_cons in Hla.\nnow destruct (srng_eq_dec (last (a :: la) 0%Srng) 0).\nQed.\n\nTheorem polyn_of_degree_1_eq : ∀ P r,\n  polyn_degree P = 1\n  → eval_polyn P r = 0%Srng\n  → P = (polyn_of_const (polyn_coeff P 1) * (_x - polyn_of_const r))%P.\nProof.\nintros * Hp Hr.\napply polyn_eq.\ndestruct P as (la, Hla).\ncbn - [ polyn_mul ].\napply Nat.add_sub_eq_nz in Hp; [ | easy ].\nsymmetry in Hp; cbn in Hp.\ncbn in Hr.\ndestruct la as [| a1]; [ easy | ].\ndestruct la as [| a2]; [ easy | ].\ndestruct la; [ clear Hp | easy ].\nmove r before a2.\ncbn in Hr.\nrewrite srng_mul_0_l, srng_add_0_l in Hr.\ncbn in Hla.\ndestruct (srng_eq_dec a2 0) as [Ha2z| Ha2z]; [ easy | clear Hla ].\nunfold nth.\ncbn.\ndestruct (srng_eq_dec a2 0) as [H| H]; [ easy | clear H; cbn ].\nrewrite if_1_eq_0; cbn.\ndestruct (srng_eq_dec r 0) as [Hrz| Hrz]; cbn. {\n  rewrite if_1_eq_0; cbn.\n  rewrite srng_add_0_l, srng_mul_1_r, srng_mul_0_l.\n  rewrite srng_add_0_r, srng_mul_0_r, srng_add_0_r.\n  destruct (srng_eq_dec a2 0) as [H| H]; [ easy | clear H ].\n  now rewrite Hrz, srng_mul_0_r, srng_add_0_l in Hr; subst a1.\n}\nrewrite if_1_eq_0; cbn.\nrewrite srng_add_0_l, srng_mul_1_r, srng_mul_0_l.\nrewrite srng_add_0_r.\ndestruct (srng_eq_dec a2 0) as [H| H]; [ easy | clear H ].\ncbn; rewrite srng_add_0_l, srng_add_0_l; f_equal.\nrewrite srng_add_comm in Hr.\napply rng_add_move_0_r in Hr; subst a1.\nsymmetry.\napply rng_mul_opp_r.\nQed.\n\n(* in algebraically closed set, a polynomial P is the\n   product of its highest coefficient and all (x-rn)\n   where rn cover all roots of P *)\n\nTheorem polyn_in_algeb_closed :\n  ∀ (P : polynomial T),\n  ∃ RL, P =\n      (polyn_of_const (polyn_highest_coeff P) *\n       Π (i = 1, polyn_degree P),\n         (_x - polyn_of_const (nth (i - 1) RL 0%Srng))%P)%Srng.\nProof.\nintros.\nremember (polyn_degree P) as n eqn:Hn; symmetry in Hn.\nrevert P Hn.\ninduction n; intros. {\n  exists [].\n  unfold polyn_highest_coeff.\n  unfold polyn_coeff.\n  rewrite Hn; cbn.\n  rewrite polyn_mul_1_r.\n  apply polyn_eq; cbn.\n  destruct (srng_eq_dec (nth 0 (polyn_list P) 0%Srng) 0) as [Hpz| Hpz]. {\n    destruct P as (la, Hla).\n    destruct la as [| a]; [ easy | exfalso ].\n    cbn in Hn; rewrite Nat.sub_0_r in Hn.\n    apply length_zero_iff_nil in Hn; subst la.\n    cbn in Hla, Hpz.\n    subst a.\n    now rewrite if_0_eq_0 in Hla.\n  }\n  destruct P as (la, Hla).\n  destruct la as [| a]; [ easy | cbn ].\n  now destruct la.\n}\ndestruct acp as (Hroots).\nspecialize (Hroots P) as H1.\nrewrite Hn in H1.\nspecialize (H1 (Nat.lt_0_succ _)).\ndestruct H1 as (x, Hx).\nremember (polyn_div_x_sub_const P x) as QR eqn:HQR.\nsymmetry in HQR.\ndestruct QR as (Q, R).\nspecialize (polyn_div_x_sub_const_prop HQR) as Hpqr.\ndestruct n. {\n  exists [x]; cbn.\n  unfold polyn_highest_coeff.\n  rewrite Hn, srng_mul_1_l.\n  clear - Hx Hn csp.\n  now apply polyn_of_degree_1_eq.\n}\nassert (Hpcq : polyn_coeff Q (polyn_degree Q) ≠ 0%Srng). {\n  destruct (polyn_eq_dec Q 0) as [Hqz| Hqz]. {\n    rewrite Hqz in Hpqr.\n    rewrite polyn_mul_0_r, polyn_add_0_l in Hpqr.\n    rewrite Hpqr in Hn.\n    now rewrite polyn_degree_of_const in Hn.\n  }\n  destruct Q as (lb, Hlb); cbn.\n  destruct lb as [| b]. {\n    exfalso; apply Hqz.\n    now apply polyn_eq.\n  }\n  cbn - [ nth ].\n  rewrite Nat.sub_0_r.\n  cbn - [ nth ] in Hlb.\n  clear - Hlb.\n  now destruct (srng_eq_dec (nth (length lb) (b :: lb) 0%Srng) 0).\n}\nspecialize (IHn Q) as H1.\nassert (Hqd : polyn_degree Q = S n). {\n  move Hn at bottom.\n  rewrite Hpqr in Hn.\n  rewrite polyn_degree_lt_add in Hn. 2: {\n    rewrite polyn_degree_of_const.\n    rewrite polyn_degree_mul. 2: {\n      unfold polyn_sub at 2.\n      rewrite polyn_degree_1. 2: {\n        rewrite polyn_degree_opp.\n        apply polyn_degree_of_const.\n      }\n      unfold polyn_sub.\n      rewrite <- polyn_of_opp_const.\n      rewrite polyn_coeff_1_of_x_add_const.\n      rewrite srng_mul_1_l.\n      destruct (polyn_eq_dec Q 0) as [Hqz| Hqz]. {\n        exfalso.\n        rewrite Hqz, polyn_mul_0_r, polyn_add_0_l in Hn.\n        now rewrite polyn_degree_of_const in Hn.\n      }\n      destruct Q as (lb, Hlb); cbn.\n      destruct lb as [| b]. {\n        exfalso; apply Hqz.\n        now apply polyn_eq.\n      }\n      cbn - [ nth ].\n      rewrite Nat.sub_0_r.\n      cbn - [ nth ] in Hlb.\n      clear - Hlb.\n      now destruct (srng_eq_dec (nth (length lb) (b :: lb) 0%Srng) 0).\n    }\n    unfold polyn_sub.\n    rewrite polyn_degree_1; [ flia | ].\n    rewrite polyn_degree_opp.\n    apply polyn_degree_of_const.\n  }\n  rewrite polyn_degree_mul in Hn. 2: {\n    unfold polyn_sub.\n    rewrite polyn_degree_1. 2: {\n      rewrite polyn_degree_opp.\n      apply polyn_degree_of_const.\n    }\n    rewrite <- polyn_of_opp_const.\n    rewrite polyn_coeff_1_of_x_add_const.\n    now rewrite srng_mul_1_l.\n  }\n  unfold polyn_sub in Hn.\n  rewrite polyn_degree_1 in Hn; [ flia Hn | ].\n  rewrite polyn_degree_opp.\n  apply polyn_degree_of_const.\n}\nspecialize (H1 Hqd).\ndestruct H1 as (RL, Hq).\nexists (x :: RL).\nmove Hpqr at bottom.\ninjection HQR; intros HR HQ; clear HQ.\nrewrite <- HR in Hpqr.\nunfold eval_polyn in Hx.\nrewrite Hx in Hpqr.\nassert (H : (polyn_of_const 0 = 0)%P). {\n  apply polyn_eq; cbn.\n  now rewrite if_0_eq_0.\n}\nrewrite H in Hpqr; clear H.\nrewrite polyn_add_0_r in Hpqr.\ngeneralize Hpqr; intros Hpqr'.\nrewrite Hq in Hpqr.\nrewrite srng_product_split_first; [ | | | flia ]; cycle 1. {\n  apply polyn_semiring_prop.\n} {\n  apply polyn_sring_comm_prop.\n}\nrewrite Nat.sub_diag.\nremember (nth 0 _ _) as y eqn:Hy; cbn in Hy; subst y.\nrewrite srng_c_mul_comm, <- srng_mul_assoc.\nrewrite Hpqr at 1.\nremember (Π (i = _, _), _)%Srng as y eqn:Hy in |-*.\nremember (Π (i = _, _), _)%Srng as z eqn:Hz in |-*.\ncbn; f_equal; rewrite srng_c_mul_comm.\ncbn; subst y z; f_equal. {\n  unfold iter_seq.\n  symmetry.\n  rewrite <- seq_shift, List_fold_left_map.\n  rewrite (Nat.sub_succ (S (S n))).\n  erewrite List_fold_left_ext_in. 2: {\n    intros i * Hi.\n    now rewrite Nat.sub_succ, Nat.sub_0_r.\n  }\n  do 2 rewrite fold_iter_seq.\n  apply srng_product_eq_compat. {\n    apply polyn_semiring_prop.\n  } {\n    apply polyn_sring_comm_prop.\n  }\n  intros i Hi.\n  destruct i; [ easy | ].\n  now rewrite Nat.sub_succ, Nat.sub_0_r.\n}\nrewrite Hpqr'.\nunfold polyn_highest_coeff.\nrewrite polyn_degree_mul. 2: {\n  unfold polyn_sub.\n  rewrite polyn_degree_1. 2: {\n    rewrite polyn_degree_opp.\n    apply polyn_degree_of_const.\n  }\n  rewrite <- polyn_of_opp_const.\n  rewrite polyn_coeff_1_of_x_add_const.\n  now rewrite srng_mul_1_l.\n}\nunfold polyn_sub.\nrewrite polyn_degree_1. 2: {\n  rewrite polyn_degree_opp.\n  apply polyn_degree_of_const.\n}\nrewrite polyn_coeff_mul.\nrewrite srng_summation_split_first; [ | easy | apply Nat.le_0_l ].\nrewrite (@polyn_coeff_overflow _ (1 + polyn_degree Q)); [ | flia ].\nrewrite srng_mul_0_r, srng_add_0_l.\nrewrite srng_summation_split_first; [ | easy | flia ].\nrewrite <- polyn_of_opp_const.\nrewrite polyn_coeff_1_of_x_add_const.\nrewrite srng_mul_1_l.\nrewrite Nat.add_comm, Nat.add_sub.\nrewrite all_0_srng_summation_0; [ | easy | ]. 2: {\n  intros i Hi.\n  rewrite polyn_coeff_overflow. 2: {\n    rewrite polyn_degree_1; [ easy | ].\n    apply polyn_degree_of_const.\n  }\n  apply srng_mul_0_l.\n}\nnow rewrite srng_add_0_r.\nQed.\n\nEnd in_ring.\n\nModule polynomial_Notations.\n\nDeclare Scope polynomial_scope.\nDelimit Scope polynomial_scope with P.\n\nNotation \"0\" := (polyn_of_list []) : polynomial_scope.\nNotation \"1\" := (polyn_of_list [1%Srng]) : polynomial_scope.\nNotation \"P + Q\" := (polyn_add P Q) : polynomial_scope.\nNotation \"P - Q\" := (polyn_sub P Q) : polynomial_scope.\nNotation \"P * Q\" := (polyn_mul P Q) : polynomial_scope.\nNotation \"- P\" := (polyn_opp P) : polynomial_scope.\n\nDeclare Scope polyn_list_scope.\nDelimit Scope polyn_list_scope with PL.\n\n(*\nNotation \"0\" := ([]) : polyn_list_scope.\n*)\nNotation \"1\" := ([1%Srng]) : polyn_list_scope.\nNotation \"la + lb\" := (polyn_list_add la lb) : polyn_list_scope.\nNotation \"la * lb\" := (polyn_list_mul la lb) : polyn_list_scope.\n\n(*\nNotation \"'Σ' ( i = b , e ) , g\" :=\n  (iter_seq b e (λ c i, (c + g)%P) 0%P)\n  (at level 45, i at level 0, b at level 60, e at level 60) :\n     polynomial_scope.\n\nNotation \"'Π' ( i = b , e ) , g\" :=\n  (iter_seq b e (λ c i, (c * g)%P) 1%P)\n  (at level 45, i at level 0, b at level 60, e at level 60) :\n     polynomial_scope.\n*)\n\nArguments _x {T so sdp}.\nArguments is_monic_polyn {T so sdp} P%P.\nArguments norm_polyn_list {T so sdp} l%PL.\nArguments polyn_coeff {T so sdp} P%P i%nat.\nArguments polyn_degree {T so sdp} P%P.\nArguments polyn_eq_dec {T so sdp} P%P Q%P.\nArguments polyn_list_convol_mul {T so} la%PL lb%PL _%nat.\nArguments polyn_list {T so sdp} p%P.\nArguments polyn_of_list_repeat_0s {T so sdp}.\n\nEnd polynomial_Notations.\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/old/SRpolynomial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6765762640959753}}
{"text": "(** * Terms for a given signature. *)\n(** Gianluca Amato,  Marco Maggesi, Cosimo Perini Brogi 2019-2021 *)\n(**\nThis file contains a formalization of terms over a signature, implemented as a sequence of\noperation symbols. This sequence is though to be executed by a stack machine: each\nsymbol of arity _n_ virtually pops _n_ elements from the stack and pushes a new element.\nA sequence of function symbols is a term when the result of the execution is a stack\nwith a single element and no stack underflow or type errors occur.\n\nHere we only define ground terms, while terms with variables will be defined in <<VTerms.v>>.\n*)\n\nRequire Import UniMath.MoreFoundations.Notations.\n\nRequire Import UniMath.Combinatorics.Maybe.\nRequire Import UniMath.Algebra.Universal.SortedTypes.\nRequire Export UniMath.Algebra.Universal.Signatures.\n\nLocal Open Scope sorted.\nLocal Open Scope hvec.\nLocal Open Scope list.\n\n(** ** Definition of [oplist] (operations list). *)\n(**\nAn [oplist] is a list of operation symbols, interpreted as commands to be executed by a stack\nmachine. Elements of the stack are sorts. When an operation symbol is executed  its arity is\npopped out from the stack and replaced by its range. When a stack underflow occurs,\nor when the sorts present in the stack are not the ones expected by the operator, the stack goes into an\nerror condition which is propagated by successive operations. A term is an [oplist] that produces\na stack of length one, when execution starts from the empty stack. Operation symbols are executed in\norder from the last element of the [oplist] to the first.\n*)\n\nLocal Definition oplist (σ: signature):= list (names σ).\n\nBind Scope list_scope with oplist.\n\nIdentity Coercion oplistislist: oplist >-> list.\n\nLocal Corollary isasetoplist (σ: signature): isaset (oplist σ).\nProof.\n  apply isofhlevellist.\n  apply setproperty.\nDefined.\n\nLocal Definition stack (σ: signature): UU := maybe (list (sorts σ)).\n\nLocal Lemma isasetstack (σ: signature): isaset (stack σ).\nProof.\n  apply isasetmaybe.\n  apply isofhlevellist.\n  apply isasetifdeceq.\n  apply decproperty.\nDefined.\n\nSection Oplists.\n\n  Context {σ: signature}.\n\n  (** *** The [opexec] and [oplistexec] functions. *)\n  (**\n     The function [opexec nm] is the stack transformation corresponding to the execution of\n     the operation symbol [nm], while [oplistexec l] returns the stack corresponding to the\n     execution of the entire oplist [l] starting from the empty stack. The list is executed from the last\n     to the first operation symbol. Finally [isaterm l] holds when the result of [oplistexec l]\n     is a stack of length one.\n   *)\n\n  Local Definition opexec (nm: names σ): stack σ → stack σ\n    := flatmap (λ ss, just (sort nm :: ss)) ∘ flatmap (λ ss, prefix_remove (arity nm) ss).\n\n  Local Definition oplistexec (l: oplist σ): stack σ := foldr opexec (just []) l.\n\n  Local Definition isaterm (s: sorts σ) (l: oplist σ): UU := oplistexec l = just ([s]).\n\n  Local Lemma isapropisaterm (s: sorts σ) (l: oplist σ): isaprop (isaterm s l).\n  Proof.\n    apply isasetstack.\n  Defined.\n\n  Local Lemma opexec_dec (nm: names σ) (ss: list (sorts σ))\n    : ((opexec nm (just ss) = nothing) × (prefix_remove (arity nm) ss = nothing))\n              ⨿  ∑ (ss': list (sorts σ)), (opexec nm (just ss) = just ((sort nm) :: ss')) × (prefix_remove (arity nm) ss = just ss').\n  Proof.\n    unfold opexec, just.\n    simpl.\n    induction (prefix_remove (arity nm) ss) as [ ss' | error ].\n    - apply ii2.\n      exists ss'.\n      split; apply idpath.\n    - apply ii1.\n      split.\n      + apply idpath.\n      + induction error.\n        apply idpath.\n  Defined.\n\n  Local Lemma opexec_just_f (nm: names σ) (ss: list (sorts σ)) (arityok: isprefix (arity nm) ss)\n    : ∑ ss': list (sorts σ), opexec nm (just ss) = just ((sort nm) :: ss') ×  prefix_remove (arity nm) ss = just ss'.\n  Proof.\n    induction (opexec_dec nm ss) as [err | ok].\n    - induction err as [_  err].\n      contradicts arityok err.\n    - assumption.\n  Defined.\n\n  Local Lemma opexec_just_b (nm: names σ) (st: stack σ) (ss: list (sorts σ))\n    : opexec nm st = just ss → ∑ ss', ss = sort nm :: ss' × st = just ((arity nm) ++ ss').\n  Proof.\n    intro scons.\n    induction st as [stok | sterror].\n    - induction (opexec_dec nm stok) as [scons_err | scons_ok].\n      + induction scons_err as [scons_err _].\n        set (H := ! scons @ scons_err).\n        contradiction (negpathsii1ii2 _ _ H).\n      + induction scons_ok as [ss' [X1 X2]].\n        exists ss'.\n        split.\n        * apply just_injectivity.\n          exact (!scons @ X1).\n        * apply maponpaths.\n          apply prefix_remove_back.\n          assumption.\n   -  contradiction (negpathsii2ii1 _ _ scons).\n  Defined.\n\n  Local Lemma opexec_zero_b (nm: names σ) (st: stack σ)\n    : ¬ (opexec nm st = just nil).\n  Proof.\n    induction st as [stok | sterror].\n    - induction (opexec_dec nm stok) as [scons_err| scons_ok].\n      + induction scons_err as [scons_err _].\n        intro H.\n        set (H' :=  (!! scons_err @ H)).\n        apply negpathsii1ii2 in H'.\n        assumption.\n      + induction scons_ok as [p [proofp _]].\n        intro H.\n        set (H' :=  (!proofp @ H)).\n        apply ii1_injectivity in H'.\n        apply negpathsconsnil in H'.\n        assumption.\n    - apply negpathsii2ii1.\n  Defined.\n\n  Local Lemma oplistexec_nil\n    : oplistexec (nil: oplist σ) = just nil.\n  Proof.\n    apply idpath.\n  Defined.\n\n  Local Lemma oplistexec_cons (nm: names σ) (l: oplist σ)\n    : oplistexec (nm :: l) = opexec nm (oplistexec l).\n  Proof.\n    apply idpath.\n  Defined.\n\n  Local Lemma oplistexec_zero_b (l: oplist σ): oplistexec l = just nil → l = nil.\n  Proof.\n    revert l.\n    refine (list_ind _ _ _).\n    - reflexivity.\n    - intros x xs _ lstack.\n      apply opexec_zero_b in lstack.\n      contradiction.\n  Defined.\n\n  Local Lemma oplistexec_positive_b (l: oplist σ) (s: sorts σ) (ss: list (sorts σ))\n    : oplistexec l = just (s :: ss) → ∑ (x: names σ) (xs: oplist σ), l = x :: xs.\n  Proof.\n    revert l.\n    refine (list_ind _ _ _).\n    - intro nilstack.\n      cbn in nilstack.\n      apply ii1_injectivity in nilstack.\n      apply negpathsnilcons in nilstack.\n      contradiction.\n    - intros x xs _ lstack.\n      exists x.\n      exists xs.\n      apply idpath.\n  Defined.\n\n  (** *** The [stackconcatenate] function. *)\n\n  (**\n  [stackconcatenate] simply appends the two lists which make the stacks, possibly propagating\n  erroneous states.\n  *)\n\n  Local Definition stackconcatenate (st1 st2: stack σ): stack σ\n    := flatmap (λ st2', flatmap (λ st1', just (st1' ++ st2')) st1) st2.\n\n  Local Lemma stackconcatenate_opexec (nm: names σ) (st1 st2: stack σ)\n    : opexec nm st1 != nothing\n       → stackconcatenate (opexec nm st1) st2 = opexec nm (stackconcatenate st1 st2).\n  Proof.\n    induction st1 as [ss1 | ].\n    2: contradiction.\n    induction st2 as [ss2| ].\n    2: reflexivity.\n    intro H.\n    induction (opexec_dec nm ss1) as [Xerr | Xok].\n    - contradicts H (pr1 Xerr).\n    - induction Xok as [tl [scons pref]].\n      unfold just in scons.\n      rewrite scons.\n      simpl.\n      rewrite concatenateStep.\n      unfold opexec.\n      simpl.\n      erewrite prefix_remove_concatenate.\n      * apply idpath.\n      * assumption.\n  Defined.\n\n Local Lemma oplistexec_concatenate (l1 l2: oplist σ)\n    : oplistexec l1 != nothing\n      → oplistexec (concatenate l1 l2)\n        = stackconcatenate (oplistexec l1) (oplistexec l2).\n  Proof.\n    revert l1.\n    refine (list_ind _ _ _).\n    - intros.\n      change ([] ++ l2) with (l2).\n      induction (oplistexec l2) as [l2ok | l2error].\n      + apply idpath.\n      + induction l2error.\n        apply idpath.\n    - intros x xs IHxs noerror.\n      change (oplistexec (x :: xs)) with (opexec x (oplistexec xs))  in *.\n      rewrite stackconcatenate_opexec by (assumption).\n      rewrite <- IHxs.\n      + apply idpath.\n      + intro error.\n        rewrite error in noerror.\n        contradiction.\n  Defined.\n\n  (** *** The [oplistsplit] function. *)\n\n  (**\n     [oplistsplit] splits an oplist into an oplist of up to [n] terms and an oplist of the remaining\n     terms.\n   *)\n\n  Local Definition oplistsplit (l: oplist σ) (n: nat): oplist σ × oplist σ.\n  Proof.\n    revert l n.\n    refine (list_ind _ _ _).\n    - intros.\n      exact (nil ,, nil).\n    - intros x xs IHxs n.\n      induction n.\n      + exact (nil,, (x :: xs)).\n      + induction (IHxs (length (arity x) + n)) as [IHfirst IHsecond].\n        exact ((x :: IHfirst) ,, IHsecond).\n  Defined.\n\n  Local Lemma oplistsplit_zero (l: oplist σ): oplistsplit l 0 = nil,, l.\n  Proof.\n    revert l.\n    refine (list_ind _ _ _) ; reflexivity.\n  Defined.\n\n  Local Lemma oplistsplit_nil (n: nat): oplistsplit nil n = nil,, nil.\n  Proof.\n    apply idpath.\n  Defined.\n\n  Local Lemma oplistsplit_cons (x: names σ) (xs: oplist σ) (n: nat)\n    : oplistsplit (x :: xs) (S n)\n      = (x :: (pr1 (oplistsplit xs (length (arity x) + n)))) ,, (pr2 (oplistsplit xs (length (arity x) + n))).\n  Proof.\n    apply idpath.\n  Defined.\n\n  Local Lemma oplistsplit_concatenate (l1 l2: oplist σ) (n: nat) (ss: list (sorts σ))\n    : oplistexec l1 = just ss → n ≤ length ss\n      → oplistsplit (l1 ++ l2) n\n        = make_dirprod (pr1 (oplistsplit l1 n)) (pr2 (oplistsplit l1 n) ++ l2).\n  Proof.\n    revert l1 ss n.\n    refine (list_ind _ _ _).\n    - intros ss n l1stack nlehss.\n      apply ii1_injectivity in l1stack.\n      rewrite <- l1stack in nlehss.\n      apply natleh0tois0 in nlehss.\n      rewrite nlehss.\n      rewrite oplistsplit_zero.\n      apply idpath.\n    - intros x1 xs1 IHxs1 ss n l1stack nlehss.\n      change ((x1 :: xs1) ++ l2) with (x1 :: (xs1 ++ l2)).\n      induction n.\n      + apply idpath.\n      + change (oplistexec (x1 :: xs1)) with (opexec x1 (oplistexec xs1)) in l1stack.\n        apply opexec_just_b in l1stack.\n        induction l1stack as [sstail [ssdef xs1stack]].\n        eset (IHinst := IHxs1 (arity x1 ++ sstail) (length (arity x1) + n) xs1stack _).\n        do 2 rewrite oplistsplit_cons.\n        apply pathsdirprod.\n        * cbn.\n          apply maponpaths.\n          apply (maponpaths pr1) in IHinst.\n          cbn in IHinst.\n          assumption.\n        * apply (maponpaths dirprod_pr2) in IHinst.\n          assumption.\n     Unshelve.\n     rewrite length_concatenate.\n     apply natlehandplusl.\n     rewrite ssdef in nlehss.\n     assumption.\n  Defined.\n\n  Local Lemma concatenate_oplistsplit (l: oplist σ) (n: nat): pr1 (oplistsplit l n) ++ pr2 (oplistsplit l n) = l.\n  Proof.\n    revert l n.\n    refine (list_ind _ _ _).\n    - reflexivity.\n    - intros x xs IHxs n.\n      induction n.\n      + apply idpath.\n      + rewrite oplistsplit_cons.\n        simpl.\n        rewrite concatenateStep.\n        apply maponpaths.\n        apply IHxs.\n  Defined.\n\n  Local Lemma oplistexec_oplistsplit (l: oplist σ) {ss: list (sorts σ)} (n: nat)\n    : oplistexec l = just ss → n ≤ length ss\n      → ∑ t1 t2: list (sorts σ),\n          ss = t1 ++ t2\n          × oplistexec (pr1 (oplistsplit l n)) = just t1\n          × oplistexec (pr2 (oplistsplit l n)) = just t2\n          × length t1 = n.\n  Proof.\n    revert l ss n.\n    refine (list_ind _ _ _).\n    - intros m ss nilstack nlehss.\n      cbn.\n      apply ii1_injectivity in nilstack.\n      rewrite <- nilstack in *.\n      apply natleh0tois0 in nlehss.\n      rewrite nlehss.\n      exists nil.\n      exists nil.\n      repeat split.\n    - intros x xs IHxs ss n lstack nlehss.\n      induction n.\n      + rewrite oplistsplit_zero.\n        exists nil.\n        exists ss.\n        repeat split.\n        assumption.\n      + rewrite oplistsplit_cons.\n        simpl.\n        change (oplistexec (x :: xs)) with (opexec x (oplistexec xs)) in lstack.\n        apply opexec_just_b in lstack.\n        induction lstack as [sstail [ssdef xsstack]].\n        eset (IHinst := IHxs (arity x ++ sstail) (length (arity x) + n) xsstack _).\n        induction IHinst as  [t1 [ t2 [ t1t2concat [ t1def [ t2def t1len ] ] ] ] ].\n        exists ((sort x) :: MoreLists.drop t1 (length (arity x))).\n        exists t2.\n        repeat split.\n        * rewrite concatenateStep.\n          rewrite <- drop_concatenate.\n          -- rewrite <- t1t2concat.\n             rewrite drop_concatenate.\n             2: apply isreflnatleh.\n             rewrite drop_full.\n             assumption.\n          -- rewrite t1len.\n             apply natlehnplusnm.\n        * rewrite oplistexec_cons.\n          rewrite t1def.\n          unfold opexec.\n          simpl.\n          rewrite prefix_remove_drop.\n          -- simpl.\n             apply maponpaths.\n             apply idpath.\n          -- intro H.\n             apply (prefix_remove_concatenate2 _ _ t2) in H.\n             ++ rewrite <- t1t2concat in H.\n                rewrite prefix_remove_prefix in H.\n                exact (negpathsii1ii2 _ _ H).\n             ++ rewrite t1len.\n                apply natlehnplusnm.\n        * apply t2def.\n        * rewrite length_cons.\n          apply maponpaths.\n          rewrite length_drop.\n          rewrite t1len.\n          rewrite natpluscomm.\n          apply plusminusnmm.\n   Unshelve.\n   rewrite length_concatenate.\n   apply natlehandplusl.\n   rewrite ssdef in nlehss.\n   assumption.\n  Defined.\n\n  Local Corollary oplistsplit_self {l: oplist σ} {ss: list (sorts σ)}\n    : oplistexec l = just ss → oplistsplit l (length ss) = l ,, nil.\n  Proof.\n    intro lstack.\n    set (H := oplistexec_oplistsplit l (length ss) lstack (isreflnatleh (length ss))).\n    induction H as [t1 [t2 [t1t2 [t1def [t2def t1len]]]]].\n    set (normalization := concatenate_oplistsplit l (length ss)).\n    apply (maponpaths length) in t1t2.\n    rewrite length_concatenate in t1t2.\n    rewrite t1len in t1t2.\n    apply pathsinv0 in t1t2.\n    rewrite natpluscomm in t1t2.\n    apply (maponpaths (λ a, a - length ss)) in t1t2.\n    rewrite plusminusnmm in t1t2.\n    rewrite minuseq0' in t1t2.\n    apply length_zero_back in t1t2.\n    rewrite t1t2 in t2def.\n    apply oplistexec_zero_b in t2def.\n    rewrite t2def in normalization.\n    rewrite concatenate_nil in normalization.\n    induction (oplistsplit l (length ss)) as [l1 l2].\n    simpl in *.\n    rewrite t2def.\n    rewrite normalization.\n    apply idpath.\n  Defined.\n\nEnd Oplists.\n\nSection Term.\n\n  (** ** Terms and related constructors and destructors. *)\n\n  (**  A [term] is an oplist together with the proof it is a term. *)\n\n  Local Definition term (σ: signature) (s: sorts σ): UU\n    := ∑ t: oplist σ, isaterm s t.\n\n  Definition make_term {σ: signature} {s: sorts σ} {l: oplist σ} (lstack: isaterm s l)\n    : term σ s := l ,, lstack.\n\n  Coercion term2oplist {σ: signature} {s: sorts σ}: term σ s → oplist σ := pr1.\n\n  Definition term2proof {σ: signature} {s: sorts σ}: ∏ t: term σ s, isaterm s t := pr2.\n\n  Lemma isasetterm {σ: signature} (s: sorts σ): isaset (term σ s).\n  Proof.\n    apply isaset_total2.\n    - apply isasetoplist.\n    - intros.\n      apply isasetaprop.\n      apply isasetstack.\n  Defined.\n\n  Local Definition termset (σ: signature) (s: sorts σ): hSet\n    := make_hSet (term σ s) (isasetterm s).\n\n  Context {σ: signature}.\n\n  Lemma term_extens {s: sorts σ} {t1 t2 : term σ s} (p : term2oplist t1 = term2oplist t2)\n    : t1 = t2.\n  Proof.\n    apply subtypePairEquality'.\n    2: apply isapropisaterm.\n    assumption.\n  Defined.\n\n  (** *** The [vecoplist2oplist] and [oplist2vecoplist] functions *)\n  (**\n  These functions transform a vec of [n] oplists into an oplists of stack [n]\n  ([vecoplist2oplist]) and viceversa ([oplist2vecoplist]).\n  *)\n\n  Local Definition vecoplist2oplist {n: nat} (v: vec (oplist σ) n): oplist σ\n    := vec_foldr concatenate nil v.\n\n  Local Lemma vecoplist2oplist_vcons {n: nat} (x: oplist σ) (v: vec (oplist σ) n)\n    : vecoplist2oplist (x ::: v) = concatenate x (vecoplist2oplist v).\n  Proof.\n    apply idpath.\n  Defined.\n\n  Local Lemma vecoplist2oplist_inj {n: nat} {ar: vec (sorts σ) n} {v1 v2: hvec (vec_map (term σ) ar)}\n    : vecoplist2oplist (h1map_vec (λ _, term2oplist) v1) = vecoplist2oplist (h1map_vec (λ _, term2oplist) v2)\n      → v1 = v2.\n  Proof.\n    revert n ar v1 v2.\n    refine (vec_ind _ _ _).\n    - intros.\n      induction v1.\n      induction v2.\n      apply idpath.\n    - intros x n xs IHxs v1 v2 eq.\n      induction v1 as [v1x v1xs].\n      induction v2 as [v2x v2xs].\n      simpl in eq.\n      apply (maponpaths (λ l, oplistsplit l 1)) in eq.\n      rewrite (oplistsplit_concatenate _ _ 1 [x] (term2proof v1x) (isreflnatleh _)) in eq.\n      rewrite (oplistsplit_concatenate _ _ 1 [x] (term2proof v2x) (isreflnatleh _)) in eq.\n      do 2 change 1 with (length (hd (x ::: xs) :: [])) in eq at 1.\n      do 2 change 1 with (length (hd (x ::: xs) :: [])) in eq at 1.\n      rewrite (oplistsplit_self (term2proof v1x)) in eq.\n      rewrite (oplistsplit_self (term2proof v2x)) in eq.\n      cbn in eq.\n      simpl.\n      apply map_on_two_paths.\n      + apply subtypePairEquality'.\n        * apply (maponpaths pr1 eq).\n        * apply isapropisaterm.\n      + apply IHxs.\n        apply (maponpaths (λ l, pr2 l: oplist σ) eq).\n  Defined.\n\n  Local Lemma oplistexec_vecoplist2oplist {n: nat} {ar: vec (sorts σ) n} {v: hvec (vec_map (term σ) ar)}\n    : oplistexec (vecoplist2oplist (h1map_vec (λ _, term2oplist) v)) = just (n ,, ar).\n  Proof.\n    revert n ar v.\n    refine (vec_ind _ _ _).\n    - induction v.\n      reflexivity.\n    - intros x n xs IHxs v.\n      induction v as [vx vxs].\n      simpl in *.\n      rewrite oplistexec_concatenate.\n      unfold h1map_vec in IHxs.\n      + rewrite IHxs.\n        rewrite (term2proof vx).\n        apply idpath.\n      + rewrite (term2proof vx).\n        apply negpathsii1ii2.\n  Defined.\n\n  Local Definition oplist2vecoplist {n: nat} {ar: vec (sorts σ) n} (l: oplist σ) (lstack: oplistexec l = just (n,, ar))\n    : ∑ (v: hvec (vec_map (term σ) ar))\n        , (hvec (h1map_vec (λ _ t, hProptoType (length (term2oplist t) ≤ length l)) v))\n          × vecoplist2oplist (h1map_vec (λ _, term2oplist) v) = l.\n  Proof.\n    revert n ar l lstack.\n    refine (vec_ind _ _ _).\n    - intros.\n      exists [()].\n      exists [()].\n      apply oplistexec_zero_b in lstack.\n      rewrite lstack.\n      apply idpath.\n    - intros x n xs IHxs l lstack.\n      induction (oplistexec_oplistsplit l 1 lstack (natleh0n 0))\n         as [firststack [reststack [concstack [firststackp [reststackp firstlen]]]]].\n      change (S n,, (x ::: xs)%vec) with (x :: (n ,, xs)) in concstack.\n      set (first := pr1 (oplistsplit l 1)) in *.\n      set (rest := pr2 (oplistsplit l 1)) in *.\n      apply length_one_back in firstlen.\n      induction firstlen as [a firststack'].\n      induction (!firststack').\n      change ((a :: []) ++ reststack) with (a :: reststack) in concstack.\n      pose (concstack' := concstack).\n      apply cons_inj1 in concstack'.\n      apply cons_inj2 in concstack.\n      induction (!concstack).\n      induction (!concstack').\n      induction (IHxs rest reststackp) as [v [vlen vflatten]].\n      exists ((make_term firststackp) ::: v).\n      repeat split.\n      + change (length first ≤ length l).\n        rewrite <- (concatenate_oplistsplit l 1).\n        apply length_sublist1.\n      + change (hvec (h1map_vec (λ (s: sorts σ) (t: term σ s), hProptoType (length (term2oplist t) ≤ length l)) v)).\n        eapply (h2map (λ _ _ p, istransnatleh p _) vlen).\n        Unshelve.\n        rewrite <- (concatenate_oplistsplit l 1).\n        apply length_sublist2.\n      + simpl.\n        unfold h1map_vec in vflatten.\n        rewrite vflatten.\n        apply concatenate_oplistsplit.\n  Defined.\n\n  (** ** Constructors and destuctors. *)\n\n  (** [build_term] builds a term starting from principal operation symbol and subterms, while\n  [princop] and [subterms] are the corresponding destructors. *)\n\n  Local Definition oplist_build (nm: names σ) (v: vec (oplist σ) (length (arity nm)))\n    : oplist σ := cons nm (vecoplist2oplist v).\n\n  Local Lemma oplist_build_isaterm (nm: names σ) (v: (term σ)⋆ (arity nm))\n    : isaterm (sort nm) (oplist_build nm (h1map_vec (λ _, term2oplist) v)).\n  Proof.\n    unfold oplist_build, isaterm.\n    rewrite oplistexec_cons.\n    rewrite oplistexec_vecoplist2oplist.\n    change (length (arity nm),, pr2 (arity nm)) with (arity nm).\n    induction (opexec_just_f nm (arity nm) (isprefix_self _)) as [rest [p1 p2]].\n    rewrite prefix_remove_self in p2.\n    apply just_injectivity in p2.\n    induction p2.\n    assumption.\n  Defined.\n\n  Local Definition build_term (nm: names σ) (v: (term σ)⋆ (arity nm)): term σ (sort nm).\n  Proof.\n    exists (oplist_build nm (h1map_vec (λ _, term2oplist) v)).\n    apply oplist_build_isaterm.\n  Defined.\n\n  Local Definition term_decompose {s: sorts σ} (t: term  σ s):\n    ∑ (nm:names σ) (v: (term σ)⋆ (arity nm))\n      , (hvec (h1map_vec (λ _ t', hProptoType (length (term2oplist t') < length t)) v))\n         × sort nm = s\n         × oplist_build nm (h1map_vec (λ _, term2oplist) v) = t.\n  Proof.\n    induction t as [l lstack].\n    cbv [pr1 term2oplist].\n    revert l lstack.\n    refine (list_ind _ _ _).\n    - intro lstack.\n      apply ii1_injectivity in lstack.\n      apply (maponpaths length) in lstack.\n      apply negpaths0sx in lstack.\n      contradiction.\n    - intros x xs IHxs lstack.\n      exists x.\n      unfold isaterm in lstack.\n      rewrite oplistexec_cons in lstack.\n      apply opexec_just_b in lstack.\n      induction lstack as [xssort [xsdef stackxs]].\n      pose (xsdef' := xsdef).\n      apply cons_inj1 in xsdef'.\n      apply cons_inj2 in xsdef.\n      induction xsdef'.\n      induction xsdef.\n      rewrite concatenate_nil in stackxs.\n      induction (oplist2vecoplist xs stackxs) as [vtail [vlen vflatten]].\n      exists vtail.\n      repeat split.\n      + exact (h2map (λ _ _ p, natlehtolthsn _ _ p) vlen).\n      + unfold oplist_build.\n        rewrite <- vflatten.\n        apply idpath.\n  Defined.\n\n  Definition princop {s: sorts σ} (t: term σ s): names σ\n    := pr1 (term_decompose t).\n\n  Definition subterms {s: sorts σ} (t: term σ s): (term σ)⋆ (arity (princop t))\n    := pr12 (term_decompose t).\n\n  Local Definition subterms_length {s: sorts σ} (t: term σ s)\n    : hvec (h1map_vec (λ _ t', hProptoType (length (term2oplist t') < length t)) (subterms t))\n    := pr122 (term_decompose t).\n\n  Local Definition princop_sorteq {s: sorts σ} (t: term σ s): sort (princop t) = s\n    := pr122 (pr2 (term_decompose t)).\n\n  Local Definition oplist_normalization {s: sorts σ} (t: term σ s)\n     : term2oplist (build_term (princop t) (subterms t)) = t\n     := pr222 (pr2 (term_decompose t)).\n\n  (** *** Term normalization *)\n  (**\n    We prove that [princop (build_term nm v) = nm], [subterms (build_term nm v) = v] and\n    [build_term (princop t) (subterms t))] is equal to [t] modulo [transport].\n  *)\n\n  Local Lemma term_normalization {s: sorts σ} (t: term σ s)\n     : transportf (term σ) (princop_sorteq t) (build_term (princop t) (subterms t)) = t.\n  Proof.\n    unfold princop, subterms, princop_sorteq.\n    induction (term_decompose t) as [nm [v [vlen [nmsort normalization]]]].\n    induction nmsort.\n    change (build_term nm v = t).\n    apply subtypePairEquality'.\n    - apply normalization.\n    - apply isapropisaterm.\n  Defined.\n\n  Local Lemma princop_build_term (nm: names σ) (v: (term σ)⋆ (arity nm))\n    : princop (build_term nm v) = nm.\n  Proof.\n    apply idpath.\n  Defined.\n\n  Local Lemma subterms_build_term (nm: names σ) (v: (term σ)⋆ (arity nm))\n    : subterms (build_term nm v) = v.\n  Proof.\n    set (t := build_term nm v).\n    set (tnorm := term_normalization t).\n    assert (princop_sorteq_idpath: princop_sorteq t = idpath (sort nm)).\n    {\n      apply proofirrelevance.\n      apply isasetifdeceq.\n      apply decproperty.\n    }\n    rewrite princop_sorteq_idpath in tnorm.\n    change (transportb (term σ) (idpath (sort nm)) t) with t in tnorm.\n    set (tnorm_list := maponpaths pr1 tnorm).\n    apply cons_inj2 in tnorm_list.\n    apply vecoplist2oplist_inj in tnorm_list.\n    exact tnorm_list.\n  Defined.\n\n  (** *** Miscellanea properties for terms. *)\n\n  Local Lemma length_term {s: sorts σ} (t: term σ s): length t > 0.\n  Proof.\n    induction t as [l stackl].\n    induction (oplistexec_positive_b _ _ _ stackl) as [x [xs lstruct]].\n    induction (! lstruct).\n    apply idpath.\n  Defined.\n\n  Local Lemma term_notnil {X: UU} {s: sorts σ} {t: term σ s}: length t ≤ 0 → X.\n  Proof.\n    intro tlen.\n    apply natlehneggth in tlen.\n    contradicts tlen (length_term t).\n  Defined.\n\nEnd Term.\n\n(** ** Term induction. *)\n\n(**\nIf [P] is a map from terms to properties, then [term_ind_HP P] is the inductive hypothesis for terms:\ngiven an operation symbol [nm], a sequence of terms of type specified by the arity of [nm], a proof of\nthe property [P] for eache of the terms in [v], we need a proof of [P] for the term built from [nm] and [v].\n*)\n\nSection TermInduction.\n\n  Context {σ: signature}.\n\n  Definition term_ind_HP (P: ∏ (s: sorts σ), term σ s → UU) :=\n    ∏ (nm: names σ)\n      (v: (term σ)⋆ (arity nm))\n      (IH: hvec (h1map_vec P v))\n    , P (sort nm) (build_term nm v).\n\n  (**\n  The proof of the induction principle [term_ind] for terms proceeds by induction on the lenght of\n  the oplist forming the terms in [term_ind_onlength].\n  *)\n\n  Local Lemma term_ind_onlength (P: ∏ (s: sorts σ), term σ s → UU) (R: term_ind_HP P)\n    : ∏ (n: nat) (s: sorts σ) (t: term σ s), length t ≤ n →  P s t.\n  Proof.\n    induction n.\n    - intros s t tlen.\n      exact (term_notnil tlen).\n    - intros s t tlen.\n      apply (transportf (P s) (term_normalization t)).\n      induction (princop_sorteq t).\n      change (P (sort (princop t)) (build_term (princop t) (subterms t))).\n      apply (R (princop t) (subterms t)).\n      refine (h2map _ (subterms_length t)).\n      intros.\n      apply IHn.\n      apply natlthsntoleh.\n      eapply natlthlehtrans.\n      + exact X.\n      + exact tlen.\n  Defined.\n\n(*\n  I would like to prove something like the following:\n\n  Lemma term_ind_onlength_step (P: ∏ (s: sorts σ), term σ s → UU) (R: term_ind_HP P) (nm: names σ) (v: (term σ)⋆ (arity nm))\n    : ∏ (n: nat) (tlehn:  length (build_term nm v) ≤ n),\n        term_ind_onlength P R n _ _ tlehn\n        =  R nm v (transportf (λ x, hvec (hmap_vec P x))\n                              (subterms_build_term nm v)\n                              (hhmap (subterms_length (build_term nm v)) (λ s t p, term_ind_onlength P R n s t (istransnatleh (natlthtoleh _ _ p) tlehn)))).\n*)\n\n  Theorem term_ind (P: ∏ (s: sorts σ), term σ s → UU) (R: term_ind_HP P) {s: sorts σ} (t: term σ s)\n    : P s t.\n  Proof.\n    exact (term_ind_onlength P R (length t) s t (isreflnatleh _)).\n  Defined.\n\n  (** *** Term induction step *)\n\n  (** In order to use term_induction, we need to prove an unfolding property. For example, for natural\n  number induction the unfolding property is [nat_rect P a IH (S n) = IH n (nat_rect P a IH n)], in our\n  case is given by [term_ind_step].\n  *)\n\n  Local Lemma term_ind_onlength_nirrelevant (P: ∏ (s: sorts σ), term σ s → UU) (R: term_ind_HP P)\n    : ∏ (n m1 m2: nat)\n        (m1lehn: m1 ≤ n) (m2lehn: m2 ≤ n)\n        (s: sorts σ) (t: term σ s)\n        (lenm1: length t ≤ m1) (lenm2: length t ≤ m2)\n      , term_ind_onlength P R m1 s t lenm1 = term_ind_onlength P R m2 s t lenm2.\n  Proof.\n    induction n.\n    - intros.\n      exact (term_notnil (istransnatleh lenm1 m1lehn)).\n    - intros.\n      induction m1.\n      + exact (term_notnil lenm1).\n      + induction m2.\n        * exact (term_notnil lenm2).\n        * simpl.\n          apply maponpaths.\n          set (f := paths_rect _ _ _).\n          apply (maponpaths (λ x, f x _ _)).\n          apply maponpaths.\n          apply (maponpaths (λ x, h2map x _)).\n          do 3 (apply funextsec; intro).\n          apply IHn.\n          -- apply m1lehn.\n          -- apply m2lehn.\n  Defined.\n\n  Local Lemma nat_rect_step {P: nat → UU} (a: P 0) (IH: ∏ n: nat, P n → P (S n)) (n: nat):\n    nat_rect P a IH (S n) = IH n (nat_rect P a IH n).\n  Proof. apply idpath. Defined.\n\n  Local Lemma paths_rect_step (A : UU) (a : A) (P : ∏ a0 : A, a = a0 → UU) (x: P a (idpath a))\n     : paths_rect A a P x a (idpath a) = x.\n  Proof. apply idpath. Defined.\n\n  Lemma term_ind_step (P: ∏ (s: sorts σ), term σ s → UU) (R: term_ind_HP P) (nm: names σ) (v: (term σ)⋆ (arity nm))\n    : term_ind P R (build_term nm v) = R nm v (h2map (λ s t q, term_ind P R t) (h1lift v)).\n  Proof.\n    unfold term_ind.\n    set (t := build_term nm v).\n    simpl (length t).\n    unfold term_ind_onlength at 1.\n    rewrite nat_rect_step.\n    set (v0len := subterms_length t).\n    set (v0norm := term_normalization t).\n    clearbody v0len v0norm.  (* Needed to make induction work *)\n    change (princop t) with nm in *.\n    induction (! (subterms_build_term nm v: subterms t = v)).\n    assert (princop_sorteq_idpath: princop_sorteq t = idpath (sort nm)).\n    {\n      apply proofirrelevance.\n      apply isasetifdeceq.\n      apply decproperty.\n    }\n    induction (! princop_sorteq_idpath).\n    change (build_term nm v = t) in v0norm.\n    assert (v0normisid: v0norm = idpath _).\n    {\n      apply proofirrelevance.\n      apply isasetterm.\n    }\n    induction (! v0normisid).\n    rewrite idpath_transportf.\n    rewrite paths_rect_step.\n    apply maponpaths.\n    rewrite (h1map_h1lift_as_h2map v v0len).\n    apply (maponpaths (λ x, h2map x _)).\n    repeat (apply funextsec; intro).\n    apply (term_ind_onlength_nirrelevant P R  (pr1 (vecoplist2oplist (h1map_vec (λ x2 : sorts σ, term2oplist) v)))).\n    - apply isreflnatleh.\n    - apply natlthsntoleh.\n      apply x1.\n  Defined.\n\n  (** *** Immediate applications of term induction *)\n\n  (**\n  [depth] returns the depth of a term, while [fromterm] is the evaluation map from terms\n  to an algebra. Finally, [fromtermstep] is the unfolding property for [fromterm].\n  *)\n\n  Definition depth {s: sorts σ}: term σ s → nat\n    := term_ind (λ _ _, nat)\n                (λ (nm: names σ) (v: (term σ)⋆ (arity nm)) (depths: hvec (h1map_vec (λ _ _, nat) v)),\n                   1 + h2foldr (λ _ _, max) 0 depths).\n\n  Local Definition fromterm {A: sUU (sorts σ)} (op : ∏ (nm : names σ), A⋆ (arity nm) → A (sort nm)) {s: sorts σ}\n    : term σ s → A s\n    := term_ind (λ s _, A s) (λ nm v rec, op nm (h2lower rec)).\n\n  Lemma fromtermstep {A: sUU (sorts σ)} (nm: names σ)\n                     (op : ∏ (nm : names σ), A⋆ (arity nm) → A (sort nm))\n                     (v: (term σ)⋆ (arity nm))\n    : fromterm op (build_term nm v) = op nm (h1map (@fromterm A op) v).\n  Proof.\n    unfold fromterm.\n    rewrite term_ind_step.\n    rewrite h2lower_h1map_h1lift.\n    apply idpath.\n  Defined.\n\nEnd TermInduction.\n\n(** ** Notations for ground terms. *)\n(**\nSince [term], [termset], [fromterm] and [fromtermstep]  will be redefined in\n[UniMath.Algebra.Universal.VTerms] in their more general form with variables, we introduce\nhere notations [gterm], [make_gterm] and similar to make the ground version publically\navailable with special names.\n*)\n\nNotation gterm := term.\n\nNotation gtermset := termset.\n\nNotation fromgterm := fromterm.\n\nNotation fromgtermstep := fromtermstep.\n\nNotation build_gterm := build_term.\n\n(** * Curried version of [build_term] *)\n\n(** Defines a curried version of [build_term] which is easier to use in practice. **)\n\nSection iterbuild.\n\n  (**\n    If [v] is a vector of types of length [n], [iterfun v B] is the curried version of [v → B], i.e.\n    [iterfun v B] =  [(el v 1) → ((el v 2) → ...... → ((el v n) → B)].\n  *)\n\n  Definition iterfun {n: nat} (v: vec UU n) (B: UU): UU.\n  Proof.\n    revert n v.\n    refine (vec_ind _ _ _).\n    - exact B.\n    - intros x n xs IHxs.\n      exact (x → IHxs).\n  Defined.\n\n  (**\n     If  [f: hvec v → B], then [itercurry f] is the curried version of [f], which has type\n     [iterfun v B].\n  *)\n\n  Definition itercurry {n: nat} {v: vec UU n} {B: UU} (f: hvec v → B): iterfun v B.\n  Proof.\n    revert n v f.\n    refine (vec_ind _ _ _).\n    - intros.\n      exact (f tt).\n    - intros x n xs IHxs f.\n      simpl in f.\n      simpl.\n      intro a.\n      exact (IHxs (λ l, f (a,, l))).\n  Defined.\n\n  (**\n    [build_term_curried nm t1 ... tn] builds a term from the operation symbol [nm] and terms (of the\n    correct sort) [t1] ... [tn].\n  *)\n\n  Definition build_gterm_curried {σ: signature} (nm: names σ)\n    : iterfun (vec_map (term σ) (pr2 (arity nm))) (term σ (sort nm))\n    := itercurry (build_term nm).\n\nEnd iterbuild.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/Algebra/Universal/Terms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.6765733427628924}}
{"text": "Require Import Morphisms.\nRequire Import Equivalence.\nRequire Import Program.Basics.\nRequire Import Lra Lia.\nRequire Import Classical.\nRequire Import FunctionalExtensionality.\nRequire Import IndefiniteDescription ClassicalDescription.\nRequire Import PropExtensionality.\n\nRequire Import Reals RealAdd.\nRequire Import Coquelicot.Coquelicot.\nRequire Export RandomVariableFinite.\nRequire Import quotient_space.\nRequire Import RbarExpectation.\n\nRequire Import Almost.\nRequire Import utils.Utils.\nRequire Import List.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\n(** This defines the space Lp (https://en.wikipedia.org/wiki/Lp_space) for finite p. \n    This is the space of RandomVariables, where the pth power of its absolute value\n    has a finite expectation, module (quotiented by) the a.e relation.\n    The a.e. (almostR2 equal) relation is an equivalence relation  that equates random variables\n    that are equal with probablity 1.\n*)\n(**\n   There are differences depending on $p$.  The world splits into a couple cases:\n   nonnegative p: Lp is a module space (vector space)\n     p = 0: nothing extra :-). Note that this is the space of all RandomVariables modulo a.e.\n     0 < p < 1: not done yet.\n     1 <= p: This is a complete normed vector space.\n       p = 2: This is a hilbert space.  See RandomVariableL2 for more information.\n     p = ∞: This is defined in the file RandomVariableLinf, see there for more information.\n\n*)\n\nLocal Notation NNR x := (mknonnegreal x ltac:(lra)) (only parsing).\n\nSection Lp.\n  Context {Ts:Type} \n          {dom: SigmaAlgebra Ts}\n          (prts: ProbSpace dom).\n\n  Global Instance rvnneg_const (pp:nonnegreal) : \n    RandomVariable dom borel_sa (fun x : Ts => const pp x).\n  Proof.\n    destruct pp; simpl.\n    apply rvconst.\n  Qed.\n\n  \n  Definition IsLp n (rv_X:Ts->R)\n    := IsFiniteExpectation prts (rvpower (rvabs rv_X) (const n)).\n\n  Existing Class IsLp.\n  Typeclasses Transparent IsLp.\n\n  Global Instance Lp_FiniteLp n rv_X\n         {islp:IsLp n rv_X}\n    : IsFiniteExpectation prts (rvpower (rvabs rv_X) (const n))\n    := islp.\n\n  Global Instance IsLp_proper\n    : Proper (eq ==> rv_eq ==> iff) IsLp.\n  Proof.\n    intros ?? eqq1 x y eqq2.\n    unfold IsLp.\n    now rewrite eqq1, eqq2.\n  Qed.\n\n  Lemma IsLp_proper_almostR2 n rv_X1 rv_X2\n        {rrv1:RandomVariable dom borel_sa rv_X1}\n        {rrv2:RandomVariable dom borel_sa rv_X2}\n        {islp1:IsLp n rv_X1}\n    :\n      almostR2 prts eq rv_X1 rv_X2 ->\n      IsLp n rv_X2.\n  Proof.\n    unfold IsLp in *.\n    red; intros.\n    eapply (IsFiniteExpectation_proper_almostR2 _ (rvpower (rvabs rv_X1) (const n)))\n    ; try eapply islp; trivial\n    ; try typeclasses eauto.\n    now rewrite H.\n  Qed.\n\n  Definition IsLp_Rbar n (rv_X:Ts->Rbar)\n    := is_finite (Rbar_NonnegExpectation\n                    (fun omega => Rbar_power (Rbar_abs (rv_X omega)) n )).\n\n  Global Instance IsLp_Rbar_proper\n    : Proper (eq ==> rv_eq ==> iff) IsLp_Rbar.\n  Proof.\n    intros ?? eqq1 x y eqq2.\n    unfold IsLp_Rbar.\n    rewrite eqq1.\n    rewrite Rbar_NonnegExpectation_ext with (nnf2 := power_abs_pos y y0).\n    tauto.\n    intro xx.\n    now rewrite eqq2.\n  Qed.\n\n  Global Instance almostR2_eq_Rbar_power_proper :\n   Proper (almostR2 prts eq ==> eq ==> almostR2 prts eq) Rbar_rvpower.\nProof.\n  intros x1 x2 eqq1 ? n ?; subst.\n  apply (almostR2_sub prts eq (fun x => Rbar_rvpower x n)); trivial.\n  intros.\n  unfold Rbar_rvpower, Rbar_power.\n  now rewrite H.\nQed.\n\nGlobal Instance almostR2_eq_Rbar_abs_proper :\n  Proper (almostR2 prts eq ==> almostR2 prts eq) Rbar_rvabs.\nProof.\n  eapply almostR2_sub; eauto; try typeclasses eauto.\n  intros.\n  unfold Rbar_rvabs.\n  now rewrite H.\nQed.\n\n\n    Lemma Rbar_Expectation_proper_almostR2 (rv_X1 rv_X2 : Ts -> Rbar)\n        (rv1pos: Rbar_NonnegativeFunction rv_X1)\n        (rv2pos: Rbar_NonnegativeFunction rv_X2):\n        almostR2 prts eq rv_X1 rv_X2 ->\n        Rbar_NonnegExpectation rv_X1 = \n        Rbar_NonnegExpectation rv_X2.\n  Proof.\n    unfold almostR2; intros.\n    destruct H as [P [? ?]].\n    assert (dec:forall x: Ts, {P x} + {~ P x}).\n    {\n      intros.\n      apply ClassicalDescription.excluded_middle_informative.\n    }\n    assert (0 < ps_P P) by lra.\n    generalize (event_restricted_Rbar_NonnegExpectation prts P H H1 rv_X1 rv1pos); intros.\n    generalize (event_restricted_Rbar_NonnegExpectation prts P H H1 rv_X2 rv2pos); intros.\n    rewrite H2, H3.\n    apply Rbar_NonnegExpectation_ext.\n    intro x.\n    unfold event_restricted_function.\n    destruct x.\n    simpl.\n    now apply H0.\n  Qed.\n\n  Lemma IsLp_Rbar_proper_almostR2 n (rv_X1 rv_X2 : Ts -> Rbar)\n        {islp1:IsLp_Rbar n rv_X1} :\n      almostR2 prts eq rv_X1 rv_X2 ->\n      IsLp_Rbar n rv_X2.\n  Proof.\n    unfold IsLp_Rbar in *; intros.\n    assert (Rbar_NonnegativeFunction\n              (fun omega : Ts => Rbar_power (Rbar_abs (rv_X1 omega)) n)) by\n        apply power_abs_pos.\n    erewrite Rbar_Expectation_proper_almostR2; trivial.\n    unfold almostR2 in *.\n    destruct H as [P [? ?]].\n    exists P.\n    split; trivial.\n    intros.\n    now rewrite H1.\n  Qed.\n\n  Lemma FiniteExpectation_Lp_pos p y\n        {islp:IsLp p y} :\n    0 <= FiniteExpectation prts (rvpower (rvabs y) (const p)).\n  Proof.\n    apply FiniteExpectation_pos.\n    typeclasses eauto.\n  Qed.\n\n  (* Note that IsLp 0 always holds, so it says that we are not making any assumptions *)\n  Global Instance IsL0_True (rv_X:Ts->R) : IsLp (NNR 0) rv_X.\n  Proof.\n    red.\n    assert(eqq:rv_eq (rvpower (rvabs rv_X) (const 0))\n                     (rvchoice (fun x => if Req_EM_T (rv_X x) 0 then true else false)\n                               (const 0)\n                               (const 1))).\n    {\n      intros a.\n      rv_unfold.\n      unfold power.\n      destruct (Req_EM_T (rv_X a)).\n      - rewrite e.\n        rewrite Rabs_R0.\n        match_destr.\n        lra.\n      - generalize (Rabs_pos (rv_X a)); intros.\n        match_destr.\n        + assert (e: Rabs (rv_X a) = 0) by lra.\n          apply Rabs_eq_0 in e; congruence.          \n        + rewrite Rpower_O; trivial; lra.\n    } \n    rewrite eqq.\n    typeclasses eauto.\n  Qed.\n\n  Lemma IsL1_Finite (rv_X:Ts->R)\n(*         {rrv:RandomVariable dom borel_sa rv_X} *)\n        {lp:IsLp 1 rv_X} : IsFiniteExpectation prts rv_X.\n  Proof.\n    red.\n    red in lp.\n    apply Expectation_abs_then_finite; trivial.\n    now rewrite rvabs_pow1 in lp.\n  Qed.\n\n  Lemma IsL1_abs_Finite (rv_X:Ts->R)\n        {lp:IsLp 1 rv_X} : IsFiniteExpectation prts (rvabs rv_X).\n  Proof.\n    red.\n    red in lp.\n    now rewrite rvabs_pow1 in lp.\n  Qed.\n\n  Lemma Finite_abs_IsL1 (rv_X:Ts->R)\n        {isfe:IsFiniteExpectation prts (rvabs rv_X)} :\n    IsLp 1 rv_X.\n  Proof.\n    red.\n    now rewrite rvabs_pow1.\n  Qed.\n\n  Lemma IsLp_bounded n rv_X1 rv_X2\n        (rle:rv_le (rvpower (rvabs rv_X1) (const n)) rv_X2)\n        {islp:IsFiniteExpectation prts rv_X2}\n    :\n      IsLp n rv_X1.\n  Proof.\n    unfold IsLp in *.\n    intros.\n    eapply (IsFiniteExpectation_bounded prts (const 0) _ rv_X2); trivial.\n    intros a.\n    unfold const, rvabs, rvpower.\n    apply power_nonneg.\n  Qed.      \n\n    Lemma IsLp_down_le m n (rv_X:Ts->R)\n        {rrv:RandomVariable dom borel_sa rv_X}\n        (pfle:0 <= n <= m)\n        {lp:IsLp m rv_X} : IsLp n rv_X.\n    Proof.\n      red in lp; red.\n      apply (@IsLp_bounded _ _\n                           (rvmax\n                              (const 1)\n                              (rvpower (rvabs rv_X) (const m))))\n      ; [| typeclasses eauto].\n      intros a.\n      rv_unfold.\n      destruct (Rle_lt_dec 1 (Rabs (rv_X a))).\n      - eapply Rle_trans; [| eapply Rmax_r].\n        now apply Rle_power.\n      - eapply Rle_trans; [| eapply Rmax_l].\n        unfold power.\n        match_destr; [lra | ].\n        generalize (Rabs_pos (rv_X a)); intros.\n        destruct (Req_EM_T n 0).\n        + subst.\n          rewrite Rpower_O; lra.\n        + assert (eqq:1 = Rpower 1 n).\n          {\n            unfold Rpower.\n            rewrite ln_1.\n            rewrite Rmult_0_r.\n            now rewrite exp_0.\n          }\n          rewrite eqq.\n          apply Rle_Rpower_l; lra.\n  Qed.\n\n  Lemma Expectation_abs_neg_part_finite (rv_X : Ts -> R)\n(*        {rv:RandomVariable dom borel_sa rv_X} *) : \n    is_finite (NonnegExpectation (rvabs rv_X)) ->\n    is_finite (NonnegExpectation (neg_fun_part rv_X)).\n  Proof.\n    apply Finite_NonnegExpectation_le.\n    apply neg_fun_part_le.\n  Qed.\n  \n  Lemma Expectation_pos_part_finite (rv_X : Ts -> R)\n        {isfe:IsFiniteExpectation prts rv_X} :\n    is_finite (NonnegExpectation (pos_fun_part rv_X)).\n  Proof.\n    red in isfe.\n    unfold Expectation in isfe.\n    destruct (NonnegExpectation (fun x : Ts => pos_fun_part rv_X x)).\n    destruct (NonnegExpectation (fun x : Ts => neg_fun_part rv_X x)).     \n    now unfold is_finite.\n    simpl in isfe; tauto.\n    simpl in isfe; tauto.     \n    destruct (NonnegExpectation (fun x : Ts => neg_fun_part rv_X x));\n      simpl in isfe; tauto.\n    destruct (NonnegExpectation (fun x : Ts => neg_fun_part rv_X x));\n      simpl in isfe; tauto.\n  Qed.\n\n  Lemma Expectation_neg_part_finite (rv_X : Ts -> R)\n        {isfe:IsFiniteExpectation prts rv_X} :\n    is_finite (NonnegExpectation (neg_fun_part rv_X)).\n  Proof.\n    red in isfe.\n    unfold Expectation in isfe.\n    destruct (NonnegExpectation (fun x : Ts => pos_fun_part rv_X x)).\n    destruct (NonnegExpectation (fun x : Ts => neg_fun_part rv_X x)).     \n    now unfold is_finite.\n    simpl in isfe; tauto.\n    simpl in isfe; tauto.     \n    destruct (NonnegExpectation (fun x : Ts => neg_fun_part rv_X x));\n      simpl in isfe; tauto.\n    destruct (NonnegExpectation (fun x : Ts => neg_fun_part rv_X x));\n      simpl in isfe; tauto.\n  Qed.\n  \n  Global Instance IsLp_scale p (c:R) (rv_X:Ts->R)\n         {islp:IsLp p rv_X} :\n    IsLp p (rvscale c rv_X).\n  Proof.\n    unfold IsLp in *.\n    rewrite rv_abs_scale_eq.\n    rewrite rvpower_abs_scale.\n    typeclasses eauto.\n  Qed.\n\n  Lemma IsLp_scale_inv p c rv_X \n        {islp:IsLp p (rvscale c rv_X)} :\n    c > 0 ->\n    IsLp p rv_X.\n  Proof.\n    intros.\n    unfold IsLp in *.\n    rewrite rv_abs_scale_eq in islp.\n    rewrite rvpower_abs_scale in islp.\n    eapply IsFiniteExpectation_scale_inv; try eassumption.\n    generalize (power_pos (Rabs c) p); intros HH.\n    cut_to HH.\n    - lra.\n    - apply Rabs_pos_lt.\n      now apply Rgt_not_eq.\n  Qed.\n  \n  Global Instance IsLp_opp p (rv_X:Ts->R)\n         {islp:IsLp p rv_X} :\n    IsLp p (rvopp rv_X).\n  Proof.\n    now apply IsLp_scale.\n  Qed.\n                                       \n  Global Instance IsLp_const p c : IsLp p (const c).\n  Proof.\n    red.\n    rewrite rv_abs_const_eq, rvpower_const.\n    typeclasses eauto.\n  Qed.\n  \n  Global Instance IsLp_abs p\n         (rv_X : Ts -> R)\n         {islp:IsLp p rv_X} :\n    IsLp p (rvabs rv_X).\n  Proof.\n    unfold IsLp.\n    rewrite rv_abs_abs.\n    apply islp.\n  Qed.\n\n  Global Instance IsLp_choice p\n         c\n         (rv_X1 rv_X2 : Ts -> R)\n         {rv1 : RandomVariable dom borel_sa rv_X1}\n         {rv2 : RandomVariable dom borel_sa rv_X2} \n         {islp1:IsLp p rv_X1}\n         {islp2:IsLp p rv_X2} :\n    IsLp p (rvchoice c rv_X1 rv_X2).\n  Proof.\n    unfold IsLp in *.\n    eapply (IsLp_bounded _)\n    ; try eapply rvpowabs_choice_le.\n    apply IsFiniteExpectation_plus; eauto\n    ; typeclasses eauto. \n  Qed.\n  \n  Global Instance IsLp_max p\n         (rv_X1 rv_X2 : Ts -> R)\n         {rv1 : RandomVariable dom borel_sa rv_X1}\n         {rv2 : RandomVariable dom borel_sa rv_X2}\n         {islp1:IsLp p rv_X1}\n         {islp2:IsLp p rv_X2} :\n    IsLp p (rvmax rv_X1 rv_X2).\n  Proof.\n    rewrite rvmax_choice.\n    typeclasses eauto.\n  Qed.\n\n  Global Instance IsLp_min p\n         (rv_X1 rv_X2 : Ts -> R)\n         {rv1 : RandomVariable dom borel_sa rv_X1}\n         {rv2 : RandomVariable dom borel_sa rv_X2}\n         {islp1:IsLp p rv_X1}\n         {islp2:IsLp p rv_X2} :\n    IsLp p (rvmin rv_X1 rv_X2).\n  Proof.\n    rewrite rvmin_choice.\n    typeclasses eauto.\n  Qed.\n\n  Lemma big_nneg n (nbig: 1 <= n) : 0 <= n.\n  Proof.\n    lra.\n  Qed.\n  \n  Lemma IsLp_Finite n (rv_X:Ts->R)\n        {rrv:RandomVariable dom borel_sa rv_X}\n        (nbig:1<=n)\n        {lp:IsLp n rv_X} : IsFiniteExpectation prts rv_X.\n  Proof.\n    apply IsL1_Finite; trivial.\n    eapply IsLp_down_le; try eapply lp; trivial; lra.\n  Qed.\n\n  Lemma IsLSp_abs_Finite n (rv_X:Ts->R)\n        {rrv:RandomVariable dom borel_sa rv_X}\n        (nbig:1<=n)\n        {lp:IsLp n rv_X} : IsFiniteExpectation prts (rvabs rv_X).\n  Proof.\n    apply IsL1_abs_Finite; trivial.\n    apply (IsLp_down_le n 1); trivial.\n    lra.\n  Qed.\n\n  Global Instance IsLp_plus (p:nonnegreal)\n         (rv_X1 rv_X2 : Ts -> R)\n         {rv1 : RandomVariable dom borel_sa rv_X1}\n         {rv2 : RandomVariable dom borel_sa rv_X2} \n         {islp1:IsLp p rv_X1}\n         {islp2:IsLp p rv_X2} :\n    IsLp p (rvplus rv_X1 rv_X2).\n  Proof.\n    destruct p as [p ?].\n    apply (IsLp_bounded _ _ (rvscale ((power 2 p)) (rvplus (rvpower (rvabs rv_X1) (const p)) (rvpower (rvabs rv_X2) (const p)))))\n    ; [| typeclasses eauto].\n    intros x.\n    rv_unfold.\n    now apply power_abs_ineq.\n  Qed.\n\n  Global Instance IsLp_minus (p:nonnegreal)\n         (rv_X1 rv_X2 : Ts -> R)\n         {rv1 : RandomVariable dom borel_sa rv_X1}\n         {rv2 : RandomVariable dom borel_sa rv_X2} \n         {islp1:IsLp p rv_X1}\n         {islp2:IsLp p rv_X2} :\n    IsLp p (rvminus rv_X1 rv_X2).\n  Proof.\n    unfold rvminus.\n    apply IsLp_plus; \n      typeclasses eauto.\n  Qed.\n\n  Section packed.\n    Context {p:R}.\n\n    Record LpRRV : Type\n      := LpRRV_of {\n             LpRRV_rv_X :> Ts -> R\n             ; LpRRV_rv :> RandomVariable dom borel_sa LpRRV_rv_X\n             ; LpRRV_lp :> IsLp p LpRRV_rv_X\n           }.\n    \n    Global Existing Instance LpRRV_rv.\n    Global Existing Instance LpRRV_lp.\n    \n    Global Instance LpRRV_LpS_FiniteLp (rv_X:LpRRV)\n      : IsFiniteExpectation prts (rvpower (rvabs rv_X) (const p))\n      := LpRRV_lp _.\n\n\n    Definition pack_LpRRV (rv_X:Ts -> R) {rv:RandomVariable dom borel_sa rv_X} {lp:IsLp p rv_X}\n      := LpRRV_of rv_X rv lp.\n    \n    Definition LpRRV_seq (rv1 rv2:LpRRV) (* strict equality *)\n      := rv_eq (LpRRV_rv_X rv1) (LpRRV_rv_X rv2).\n\n    Definition LpRRV_eq (rv1 rv2:LpRRV)\n      := almostR2 prts eq rv1 rv2.\n\n    Global Instance LpRRV_seq_eq : subrelation LpRRV_seq LpRRV_eq.\n    Proof.\n      red; unfold LpRRV_seq, LpRRV_eq, rv_eq.\n      intros x y eqq.\n      now apply almostR2_eq_subr.\n    Qed.      \n    \n    Global Instance LpRRV_seq_equiv : Equivalence (LpRRV_seq).\n    Proof.\n      unfold LpRRV_seq.\n      apply Equivalence_pullback.\n      apply rv_eq_equiv.\n    Qed.\n\n    Global Instance LpRRV_eq_equiv : Equivalence LpRRV_eq.\n    Proof.\n      unfold LpRRV_eq.\n      constructor.\n      - intros [x?].\n        reflexivity.\n      - intros [x?] [y?] ps1; simpl in *.\n        now symmetry.\n      - intros [x??] [y??] [z??] ps1 ps2.\n        simpl in *.\n        etransitivity; eauto.\n    Qed.\n\n    Definition LpRRVconst (x:R) : LpRRV\n      := pack_LpRRV (const x).\n\n    Definition LpRRVzero : LpRRV := LpRRVconst 0.\n\n    Program Definition LpRRVscale (x:R) (rv:LpRRV) : LpRRV\n      := pack_LpRRV (rvscale x rv).\n\n    Global Instance LpRRV_scale_sproper : Proper (eq ==> LpRRV_seq ==> LpRRV_seq) LpRRVscale.\n    Proof.\n      unfold Proper, respectful, LpRRV_eq.\n      intros ? x ? [x1??] [x2??] eqqx.\n      subst.\n      simpl in *.\n      unfold rvscale.\n      red.\n      simpl.\n      red in eqqx.\n      simpl in *.\n      now rewrite eqqx.\n    Qed.\n\n    Global Instance LpRRV_scale_proper : Proper (eq ==> LpRRV_eq ==> LpRRV_eq) LpRRVscale.\n    Proof.\n      unfold Proper, respectful, LpRRV_eq.\n      intros ? x ? [x1??] [x2??] eqqx.\n      subst.\n      simpl in *.\n      rewrite eqqx.\n      reflexivity.\n    Qed.\n\n    Definition LpRRVopp (rv:LpRRV) : LpRRV\n      := pack_LpRRV (rvopp rv).\n    \n    Global Instance LpRRV_opp_sproper : Proper (LpRRV_seq ==> LpRRV_seq) LpRRVopp.\n    Proof.\n      unfold Proper, respectful.\n      intros x y eqq.\n      generalize (LpRRV_scale_sproper (-1) _ (eq_refl _) _ _ eqq)\n      ; intros HH.\n      destruct x as [x?]\n      ; destruct y as [y?].\n      apply HH.\n    Qed.\n\n    Global Instance LpRRV_opp_proper : Proper (LpRRV_eq ==> LpRRV_eq) LpRRVopp.\n    Proof.\n      unfold Proper, respectful.\n      intros x y eqq.\n      generalize (LpRRV_scale_proper (-1) _ (eq_refl _) _ _ eqq)\n      ; intros HH.\n      destruct x as [x?]\n      ; destruct y as [y?].\n      apply HH.\n    Qed.\n\n    Lemma LpRRVopp_scale (rv:LpRRV) :\n      LpRRV_eq \n        (LpRRVopp rv) (LpRRVscale (-1) rv).\n    Proof.\n      red.\n      reflexivity.\n    Qed.\n\n    Definition LpRRVabs (rv:LpRRV) : LpRRV\n      := pack_LpRRV (rvabs rv).\n\n    Global Instance LpRRV_abs_sproper : Proper (LpRRV_seq ==> LpRRV_seq) LpRRVabs.\n    Proof.\n      unfold Proper, respectful.\n      intros x y eqq.\n      red in eqq.\n      red; simpl.\n      now rewrite eqq.\n    Qed.\n\n    Global Instance LpRRV_abs_proper : Proper (LpRRV_eq ==> LpRRV_eq) LpRRVabs.\n    Proof.\n      unfold Proper, respectful.\n      intros x y eqq.\n      now apply almostR2_eq_abs_proper.\n    Qed.\n\n    Section quoted.\n\n      Definition LpRRVq : Type := quot LpRRV_eq.\n\n      Definition LpRRVq_const (x:R) : LpRRVq := Quot _ (LpRRVconst x).\n\n      Lemma LpRRVq_constE x : LpRRVq_const x = Quot _ (LpRRVconst x).\n      Proof.\n        reflexivity.\n      Qed.\n\n      Hint Rewrite LpRRVq_constE : quot.\n\n      Definition LpRRVq_zero : LpRRVq := LpRRVq_const 0.\n\n      Lemma LpRRVq_zeroE : LpRRVq_zero = LpRRVq_const 0.\n      Proof.\n        reflexivity.\n      Qed.\n\n      Hint Rewrite LpRRVq_zeroE : quot.\n\n      Definition LpRRVq_scale (x:R) : LpRRVq -> LpRRVq\n        := quot_lift (LpRRVscale x).\n\n      Lemma LpRRVq_scaleE x y : LpRRVq_scale x (Quot _ y)  = Quot _ (LpRRVscale x y).\n      Proof.\n        apply quot_liftE.\n      Qed.\n\n      Hint Rewrite LpRRVq_scaleE : quot.\n      \n      Definition LpRRVq_opp  : LpRRVq -> LpRRVq\n        := quot_lift LpRRVopp.\n\n      Lemma LpRRVq_oppE x : LpRRVq_opp (Quot _ x)  = Quot _ (LpRRVopp x).\n      Proof.\n        apply quot_liftE.\n      Qed.\n\n      Hint Rewrite LpRRVq_oppE : quot.\n      \n      Definition LpRRVq_abs  : LpRRVq -> LpRRVq\n        := quot_lift LpRRVabs.\n\n    End quoted.\n    \n  End packed.\n\n  Hint Rewrite @LpRRVq_constE : quot.\n  Hint Rewrite @LpRRVq_zeroE : quot.\n  Hint Rewrite @LpRRVq_scaleE : quot.\n  Hint Rewrite @LpRRVq_oppE : quot.\n      \n\n  Global Arguments LpRRV : clear implicits.\n  Global Arguments LpRRVq : clear implicits.\n\n  Section packednonneg.\n\n    Context {p:nonnegreal}.\n\n    Definition LpRRVplus (rv1 rv2:LpRRV p) : LpRRV p\n      := pack_LpRRV (rvplus rv1  rv2).\n\n    Global Instance LpRRV_plus_sproper : Proper (LpRRV_seq ==> LpRRV_seq ==> LpRRV_seq) LpRRVplus.\n    Proof.\n      unfold Proper, respectful, LpRRV_seq.\n      intros [x1??] [x2??] eqqx [y1??] [y2??] eqqy.\n      simpl in *.\n      simpl in *.\n      now rewrite eqqx, eqqy.\n    Qed.\n\n    Global Instance LpRRV_plus_proper : Proper (LpRRV_eq ==> LpRRV_eq ==> LpRRV_eq) LpRRVplus.\n    Proof.\n      unfold Proper, respectful, LpRRV_eq.\n      intros [x1??] [x2??] eqqx [y1??] [y2??] eqqy.\n      simpl in *.\n      now apply almostR2_eq_plus_proper.\n    Qed.\n\n    Definition LpRRVminus (rv1 rv2:LpRRV p) : LpRRV p\n      := pack_LpRRV (rvminus rv1 rv2).\n\n    Lemma LpRRVminus_plus (rv1 rv2:LpRRV p) :\n      LpRRV_seq \n        (LpRRVminus rv1 rv2) (LpRRVplus rv1 (LpRRVopp rv2)).\n    Proof.\n      intros ?.\n      reflexivity.\n    Qed.\n\n    Lemma LpRRValmost_sub_zero_eq (x y:LpRRV p)\n      (eqq: almostR2 prts eq (LpRRVminus x y) (LpRRVzero (p:=p))) :\n      almostR2 prts eq x y.\n    Proof.\n      generalize (almostR2_eq_plus_proper prts _ _ eqq _ _ (reflexivity y))\n      ; intros HH.\n      transitivity (rvplus (LpRRVzero (p:=p)) y).\n      - rewrite <- HH.\n        apply almostR2_eq_subr.\n        intros ?; simpl.\n        rv_unfold.\n        lra.\n      - apply almostR2_eq_subr.\n        intros ?; simpl.\n        rv_unfold.\n        lra.\n    Qed.\n    \n    Global Instance LpRRV_minus_sproper : Proper (LpRRV_seq ==> LpRRV_seq ==> LpRRV_seq) LpRRVminus.\n    Proof.\n      unfold Proper, respectful, LpRRV_seq.\n\n      intros x1 x2 eqq1 y1 y2 eqq2; simpl.\n      now rewrite eqq1, eqq2.\n    Qed.\n\n    Global Instance LpRRV_minus_proper : Proper (LpRRV_eq ==> LpRRV_eq ==> LpRRV_eq) LpRRVminus.\n    Proof.\n      unfold Proper, respectful, LpRRV_eq.\n\n      intros x1 x2 eqq1 y1 y2 eqq2.\n      \n      generalize (LpRRV_plus_proper _ _ eqq1 _ _ (LpRRV_opp_proper _ _ eqq2)) \n      ; intros HH.\n      destruct x1 as [???]; destruct x2 as [???]\n      ; destruct y1 as [???]; destruct y2 as [???].\n      apply HH.\n    Qed.\n\n    Ltac LpRRV_simpl\n      := repeat match goal with\n                | [H : LpRRV |- _ ] => destruct H as [???]\n                end\n         ; unfold LpRRVplus, LpRRVminus, LpRRVopp, LpRRVscale\n         ; simpl.\n\n    \n    Lemma LpRRV_plus_comm x y : LpRRV_eq (LpRRVplus x y) (LpRRVplus y x).\n    Proof.\n      red; intros.\n      LpRRV_simpl.\n      apply almostR2_eq_subr; intros ?.\n      unfold rvplus; lra.\n    Qed.\n    \n    Lemma LpRRV_plus_assoc (x y z : LpRRV p) : LpRRV_eq (LpRRVplus x (LpRRVplus y z)) (LpRRVplus (LpRRVplus x y) z).\n    Proof.\n      red; intros.\n      LpRRV_simpl.\n      apply almostR2_eq_subr; intros ?.\n      unfold rvplus.\n      lra.\n    Qed.\n\n    Lemma LpRRV_plus_zero (x : LpRRV p) : LpRRV_eq (LpRRVplus x (LpRRVconst 0)) x.\n    Proof.\n      red; intros.\n      LpRRV_simpl.\n      apply almostR2_eq_subr; intros ?.\n      unfold rvplus, const.\n      lra.\n    Qed.\n\n    Lemma LpRRV_plus_inv (x: LpRRV p) : LpRRV_eq (LpRRVplus x (LpRRVopp x)) (LpRRVconst 0).\n    Proof.\n      red; intros.\n      LpRRV_simpl.\n      apply almostR2_eq_subr; intros ?.\n      unfold rvplus, rvopp, rvscale, const.\n      lra.\n    Qed.\n\n    Lemma LpRRV_scale_scale (x y : R) (u : LpRRV p) :\n      LpRRV_eq (LpRRVscale x (LpRRVscale y u)) (LpRRVscale (x * y) u).\n    Proof.\n      red; intros.\n      LpRRV_simpl.\n      apply almostR2_eq_subr; intros ?.\n      unfold rvplus, rvopp, rvscale, const, mult; simpl.\n      lra.\n    Qed.\n\n    Lemma LpRRV_scale1 (u : LpRRV p) :\n      LpRRV_eq (LpRRVscale one u) u.\n    Proof.\n      red; intros.\n      LpRRV_simpl.\n      apply almostR2_eq_subr; intros ?.\n      unfold rvplus, rvopp, rvscale, const, mult, one; simpl.\n      lra.\n    Qed.\n    \n    Lemma LpRRV_scale_plus_l (x : R) (u v : LpRRV p) :\n      LpRRV_eq (LpRRVscale x (LpRRVplus u v)) (LpRRVplus (LpRRVscale x u) (LpRRVscale x v)).\n    Proof.\n      red; intros.\n      LpRRV_simpl.\n      apply almostR2_eq_subr; intros ?.\n      unfold rvplus, rvopp, rvscale, const, mult; simpl.\n      lra.\n    Qed.\n    \n    Lemma LpRRV_scale_plus_r (x y : R) (u : LpRRV p) :\n      LpRRV_eq (LpRRVscale (x + y) u) (LpRRVplus (LpRRVscale x u) (LpRRVscale y u)).\n    Proof.\n      red; intros.\n      LpRRV_simpl.\n      apply almostR2_eq_subr; intros ?.\n      unfold rvplus, rvopp, rvscale, const, mult; simpl.\n      lra.\n    Qed.\n\n    (* Lp is a module space for all finite nonnegative p *)\n    Section quotnneg.\n\n      Definition LpRRVq_plus  : LpRRVq p -> LpRRVq p -> LpRRVq p\n        := quot_lift2 LpRRVplus.\n      \n      Lemma LpRRVq_plusE x y : LpRRVq_plus (Quot _ x) (Quot _ y) = Quot _ (LpRRVplus x y).\n      Proof.\n        apply quot_lift2E.\n      Qed.\n\n      Hint Rewrite LpRRVq_plusE : quot.\n\n      Definition LpRRVq_minus  : LpRRVq p -> LpRRVq p -> LpRRVq p\n        := quot_lift2 LpRRVminus.\n\n      Lemma LpRRVq_minusE x y : LpRRVq_minus (Quot _ x) (Quot _ y) = Quot _ (LpRRVminus x y).\n      Proof.\n        apply quot_lift2E.\n      Qed.\n\n      Hint Rewrite LpRRVq_minusE : quot.\n\n      Ltac LpRRVq_simpl\n        := repeat match goal with\n                  | [H: LpRRVq _ |- _ ] =>\n                    let xx := fresh H in destruct (Quot_inv H) as [xx ?]; subst H; rename xx into H\n                  end\n           ; try autorewrite with quot\n           ; try apply (@eq_Quot _ _ LpRRV_eq_equiv).\n\n      Lemma LpRRVq_minus_plus (rv1 rv2:LpRRVq p) :\n        LpRRVq_minus rv1 rv2 = LpRRVq_plus rv1 (LpRRVq_opp rv2).\n      Proof.\n        LpRRVq_simpl.\n        now rewrite LpRRVminus_plus.\n      Qed.\n\n      Lemma LpRRVq_opp_scale (rv:LpRRVq p) :\n        LpRRVq_opp rv = LpRRVq_scale (-1) rv.\n      Proof.\n        LpRRVq_simpl.\n        apply LpRRVopp_scale.\n      Qed.\n      \n      Lemma LpRRVq_plus_comm x y : LpRRVq_plus x y = LpRRVq_plus y x.\n      Proof.\n        LpRRVq_simpl.\n        apply LpRRV_plus_comm.\n      Qed.\n      \n      Lemma LpRRVq_plus_assoc (x y z : LpRRVq p) : LpRRVq_plus x (LpRRVq_plus y z) = LpRRVq_plus (LpRRVq_plus x y) z.\n      Proof.\n        LpRRVq_simpl.\n        apply LpRRV_plus_assoc.\n      Qed.\n\n\n      Lemma LpRRVq_plus_zero (x : LpRRVq p) : LpRRVq_plus x LpRRVq_zero = x.\n      Proof.\n        LpRRVq_simpl.\n        apply LpRRV_plus_zero.\n      Qed.\n\n      Lemma LpRRVq_plus_inv (x: LpRRVq p) : LpRRVq_plus x (LpRRVq_opp x) = LpRRVq_zero.\n      Proof.\n        LpRRVq_simpl.\n        apply LpRRV_plus_inv.\n      Qed.\n      \n      Definition LpRRVq_AbelianGroup_mixin : AbelianGroup.mixin_of (LpRRVq p)\n        := AbelianGroup.Mixin (LpRRVq p) LpRRVq_plus LpRRVq_opp LpRRVq_zero\n                              LpRRVq_plus_comm LpRRVq_plus_assoc\n                              LpRRVq_plus_zero LpRRVq_plus_inv.\n\n      Canonical LpRRVq_AbelianGroup :=\n        AbelianGroup.Pack (LpRRVq p) LpRRVq_AbelianGroup_mixin (LpRRVq p).\n\n      Ltac LpRRVq_simpl ::=\n        repeat match goal with\n               | [H: LpRRVq _ |- _ ] =>\n                 let xx := fresh H in destruct (Quot_inv H) as [xx ?]; subst H; rename xx into H\n               | [H: AbelianGroup.sort LpRRVq_AbelianGroup |- _ ] =>\n                 let xx := fresh H in destruct (Quot_inv H) as [xx ?]; subst H; rename xx into H\n               end\n        ; try autorewrite with quot\n        ; try apply (@eq_Quot _ _ LpRRV_eq_equiv).\n      \n      Lemma LpRRVq_scale_scale (x y : R_Ring) (u : LpRRVq_AbelianGroup) :\n        LpRRVq_scale x (LpRRVq_scale y u) = LpRRVq_scale (x * y) u.\n      Proof.\n        LpRRVq_simpl.\n        apply LpRRV_scale_scale.\n      Qed.\n      \n      Lemma LpRRVq_scale1 (u : LpRRVq_AbelianGroup) :\n        LpRRVq_scale one u = u.\n      Proof.\n        LpRRVq_simpl.\n        apply LpRRV_scale1.\n      Qed.\n      \n      Lemma LpRRVq_scale_plus_l (x : R_Ring) (u v : LpRRVq_AbelianGroup) :\n        LpRRVq_scale x (plus u v) = plus (LpRRVq_scale x u) (LpRRVq_scale x v).\n      Proof.\n        LpRRVq_simpl.\n        apply LpRRV_scale_plus_l.\n      Qed.\n\n      Lemma LpRRVq_scale_plus_r (x y : R_Ring) (u : LpRRVq_AbelianGroup) :\n        LpRRVq_scale (plus x y) u = plus (LpRRVq_scale x u) (LpRRVq_scale y u).\n      Proof.\n        LpRRVq_simpl.\n        apply LpRRV_scale_plus_r.\n      Qed.\n\n      Definition LpRRVq_ModuleSpace_mixin : ModuleSpace.mixin_of R_Ring LpRRVq_AbelianGroup\n        := ModuleSpace.Mixin R_Ring LpRRVq_AbelianGroup\n                             LpRRVq_scale LpRRVq_scale_scale LpRRVq_scale1\n                             LpRRVq_scale_plus_l LpRRVq_scale_plus_r.\n\n      Canonical LpRRVq_ModuleSpace :=\n        ModuleSpace.Pack R_Ring (LpRRVq p) (ModuleSpace.Class R_Ring (LpRRVq p) LpRRVq_AbelianGroup_mixin LpRRVq_ModuleSpace_mixin) (LpRRVq p).\n\n    End quotnneg.\n  End packednonneg.\n\n    (** At this point, we will be spliting into three cases:\n        p = 0       => This is the space of Random Variables modulo almostR2-equal.  \n                      We already showed what we know about it.  (It is a ModuleSpace)\n        1 <= p < ∞  => This is a normed vector space\n        0 < p < 1   => This is a metric space.\n     *)\n\n    Section normish.\n      (** For p = 0, this is not really defined.\n          For 1 <= p this defines a norm.\n          For 0 < p < 1 this defines a quasi norm\n       *)\n      Context {p:R}.\n      Definition LpRRVnorm (rv_X:LpRRV p) : R\n        := power (FiniteExpectation prts (rvpower (rvabs rv_X) (const p))) (Rinv p).\n\n      Global Instance LpRRV_norm_proper : Proper (LpRRV_eq ==> eq) LpRRVnorm.\n      Proof.\n        unfold Proper, respectful, LpRRVnorm, LpRRV_eq.\n        intros.\n        f_equal.\n        eapply FiniteExpectation_proper_almostR2\n        ; try typeclasses eauto.\n        rewrite H.\n        reflexivity.\n      Qed.\n\n      Global Instance LpRRV_norm_sproper : Proper (LpRRV_seq ==> eq) LpRRVnorm.\n      Proof.\n        unfold Proper, respectful; intros.\n        now rewrite H.\n      Qed.\n\n      Lemma almostR20_lpf_almostR20 (rv_X:Ts->R)\n            {rrv:RandomVariable dom borel_sa rv_X}\n            {isfe: IsFiniteExpectation prts (rvpower (rvabs rv_X) (const p))}:\n        almostR2 prts eq rv_X (const 0) <->\n        almostR2 prts eq (rvpower (rvabs rv_X) (const p)) (const 0).\n      Proof.\n        intros.\n      unfold almostR2 in *.\n      split; intros [P [Pall eq_on]]\n      ; exists P; split; trivial\n      ; intros a Pa\n      ; rv_unfold.\n      - rewrite eq_on by trivial.\n        now rewrite Rabs_R0, power0_Sbase.\n      - specialize (eq_on _ Pa).\n        apply power_integral in eq_on.\n        generalize (Rabs_pos (rv_X a)); intros.\n        apply Rabs_eq_0.\n        lra.\n      Qed.\n\n      (* If the norm is 0 then p is a.e. 0 *)\n      Theorem LpFin0_almostR20 (rv_X:Ts->R)\n            {rrv:RandomVariable dom borel_sa rv_X}\n            {isfe: IsFiniteExpectation prts (rvpower (rvabs rv_X) (const p))}:\n        FiniteExpectation prts (rvpower (rvabs rv_X) (const p)) = 0 ->\n        almostR2 prts eq rv_X (const 0).\n      Proof.\n        intros fin0.\n        eapply FiniteExpectation_zero_pos in fin0\n        ; try typeclasses eauto.\n        now apply almostR20_lpf_almostR20\n        ; try typeclasses eauto.\n      Qed.\n\n      Lemma LpRRV_norm0 (x:LpRRV p) :\n        LpRRVnorm x = 0 ->\n        almostR2 prts eq x (LpRRVzero (p:=p)).\n      Proof.\n        unfold LpRRVnorm, LpRRVzero, LpRRVconst.\n        intros.\n        apply power_integral in H.\n        generalize (FiniteExpectation_Lp_pos p x); intros.\n        assert (FiniteExpectation prts (rvpower (rvabs x) (const p)) = 0)\n          by now apply Rle_antisym.\n        now apply  LpFin0_almostR20 in H1; try typeclasses eauto.\n      Qed.\n      \n      Lemma LpRRVnorm_const c : p <> 0 -> LpRRVnorm (LpRRVconst c) = Rabs c.\n      Proof.\n        intros.\n        unfold LpRRVnorm; simpl.\n        rv_unfold.\n        generalize (FiniteExpectation_const prts (power (Rabs c) p))\n        ; intros HH.\n        unfold const in HH.\n        erewrite FiniteExpectation_pf_irrel.\n        rewrite HH.\n        apply inv_power_cancel; trivial.\n        apply Rabs_pos.\n      Qed.\n  \n      Lemma LpRRVnorm0 : p <> 0 -> LpRRVnorm LpRRVzero = 0.\n      Proof.\n        intros.\n        unfold LpRRVzero.\n        rewrite LpRRVnorm_const; trivial.\n        now rewrite Rabs_R0.\n      Qed.\n\n    End normish.\n\n    Definition LpRRVpoint (p:R) : LpRRV p := LpRRVconst 0.\n\n    Definition bignneg n (nbig: 1 <= n) : nonnegreal\n      := mknonnegreal n (big_nneg n nbig).\n\n    Section packedbigp.\n      Context {p:R}.\n      Context (pbig:1 <= p).\n\n      Let pnneg : nonnegreal := bignneg p pbig.\n      Canonical pnneg.\n      \n      Lemma Minkowski_rv (x y : LpRRV p) (t:R): \n        0 < t < 1 -> \n        rv_le (rvpower (rvplus (rvabs x) (rvabs y)) (const p))\n              (rvplus\n                 (rvscale (power (/t) (p-1)) (rvpower (rvabs x) (const p))) \n                 (rvscale (power (/(1-t)) (p-1)) (rvpower (rvabs y) (const p)))).\n      Proof.\n        intros.\n        intro x0.\n        generalize (@power_minkowski_helper p (rvabs x x0) (rvabs y x0) t); intros.\n        rv_unfold.\n        apply H0; trivial.\n        apply Rabs_pos.\n        apply Rabs_pos.\n      Qed.\n\n      Lemma rvpower_plus_le (x y : LpRRV p) :\n        rv_le (rvpower (rvabs (rvplus x y)) (const p)) (rvpower (rvplus (rvabs x) (rvabs y)) (const p)).\n      Proof.\n        intro x0.\n        rv_unfold.\n        apply Rle_power_l; [lra|].\n        split.\n        - apply Rabs_pos.\n        - apply Rabs_triang.\n      Qed.\n\n      Lemma Minkowski_1 (x y : LpRRV p) (t:R):\n        0 < t < 1 -> \n        (FiniteExpectation prts (rvpower (rvabs (rvplus x y)) (const p)))  <=\n        (power (/t) (p-1)) * (FiniteExpectation prts (rvpower (rvabs x) (const p))) + \n        (power (/(1-t)) (p-1)) * (FiniteExpectation prts (rvpower (rvabs y) (const p))).\n      Proof.\n        intros.\n        generalize (Minkowski_rv x y t H); intros.\n        generalize (rvpower_plus_le x y); intros.\n        assert (IsFiniteExpectation prts (rvpower (rvplus (rvabs x) (rvabs y)) (const p))).\n        {\n          eapply (IsFiniteExpectation_bounded _ _ _ _ H1 H0).\n        } \n        assert (FiniteExpectation prts (rvpower (rvabs (rvplus x y)) (const p)) <=\n                FiniteExpectation prts (rvpower (rvplus (rvabs x) (rvabs y)) (const p))).\n        {\n          apply FiniteExpectation_le.\n          apply rvpower_plus_le.\n        } \n        generalize (FiniteExpectation_le _ _ _ H0); intros.\n        rewrite FiniteExpectation_plus in H4.\n        rewrite FiniteExpectation_scale in H4.\n        rewrite FiniteExpectation_scale in H4.\n        apply Rle_trans with \n            (r2 := FiniteExpectation prts (rvpower (rvplus (rvabs x) (rvabs y)) (const p))); trivial.\n      Qed.\n\n      Lemma Minkowski_2 (x y : LpRRV p)\n            (xexppos : 0 < FiniteExpectation prts (rvpower (rvabs x) (const p)))\n            (yexppos : 0 < FiniteExpectation prts (rvpower (rvabs y) (const p))) :\n        FiniteExpectation prts (rvpower (rvabs (rvplus x y)) (const p))  <=\n        power ((power (FiniteExpectation prts (rvpower (rvabs x) (const p))) (/ p)) +\n               (power (FiniteExpectation prts (rvpower (rvabs y) (const p))) (/ p))) p.\n      Proof.\n        generalize (Minkowski_1 x y); intros.\n        pose (a := power (FiniteExpectation prts (rvpower (rvabs x) (const p))) (/ p)).\n        pose (b := power (FiniteExpectation prts (rvpower (rvabs y) (const p))) (/ p)).\n        assert (0 < a)\n          by (apply power_pos; lra).\n        assert (0 < b)\n          by (apply power_pos; lra).\n        replace (FiniteExpectation prts (rvpower (rvabs x) (const p))) with (power a p) in H\n          by (apply power_inv_cancel; lra).\n        replace (FiniteExpectation prts (rvpower (rvabs y) (const p))) with (power b p) in H\n          by (apply power_inv_cancel; lra).\n        specialize (H (a /(a + b))).\n        cut_to H.\n        - rewrite (power_minkowski_subst p H0 H1) in H; trivial.\n        - now apply minkowski_range.\n      Qed.\n\n      Lemma Rle_power_inv_l (a b : R) :\n        0 < a -> a  <= b -> power a (/ p) <= power b (/ p).\n      Proof.\n        intros.\n        apply Rle_power_l.\n        - left; apply Rinv_0_lt_compat; lra.\n        - lra.\n      Qed.\n      \n      Lemma Minkowski_lt (x y : LpRRV p)\n            (xexppos : 0 < FiniteExpectation prts (rvpower (rvabs x) (const p)))\n            (yexppos : 0 < FiniteExpectation prts (rvpower (rvabs y) (const p))) \n            (xyexppos : 0 < FiniteExpectation prts (rvpower (rvabs (rvplus x y)) (const p))) :\n        power (FiniteExpectation prts (rvpower (rvabs (rvplus x y)) (const p))) (/ p)  <=\n        power (FiniteExpectation prts (rvpower (rvabs x) (const p))) (/ p) +\n        power (FiniteExpectation prts (rvpower (rvabs y) (const p))) (/ p).\n      Proof.\n        generalize (Minkowski_2 x y xexppos yexppos); intros.\n        apply Rle_power_inv_l in H; try lra.\n        rewrite inv_power_cancel in H; trivial; try lra.\n        apply Rplus_le_le_0_compat\n        ; apply power_nonneg.\n      Qed.   \n\n      Theorem Minkowski (x y : LpRRV p) :\n        power (FiniteExpectation prts (rvpower (rvabs (rvplus x y)) (const p))) (/ p)  <=\n        power (FiniteExpectation prts (rvpower (rvabs x) (const p))) (/ p) +\n        power (FiniteExpectation prts (rvpower (rvabs y) (const p))) (/ p).\n      Proof.\n        destruct (FiniteExpectation_pos prts (rvpower (rvabs x) (const p))).\n        - {\n            destruct (FiniteExpectation_pos prts (rvpower (rvabs y) (const p))).\n            - {\n                - destruct (FiniteExpectation_pos prts (rvpower (rvabs (rvplus x y)) (const p))). \n                  + now apply Minkowski_lt.\n                  + rewrite <- H1.\n                    rewrite power0_Sbase\n                      by (apply Rinv_neq_0_compat; lra).\n                    apply Rplus_le_le_0_compat\n                    ; apply power_nonneg.\n              } \n            - rewrite <- H0.\n              rewrite power0_Sbase\n                by (apply Rinv_neq_0_compat; lra).\n              symmetry in H0.\n              eapply LpFin0_almostR20 in H0; try typeclasses eauto.\n              rewrite (FiniteExpectation_proper_almostR2 prts (rvpower (rvabs (rvplus x y)) (const p)) (rvpower (rvabs x) (const p))).\n              + lra.\n              + rewrite H0.\n                apply almostR2_eq_subr.\n                intros ?.\n                rv_unfold.\n                repeat f_equal.\n                lra.\n          }                                                    \n        - rewrite <- H.\n          rewrite power0_Sbase\n            by (apply Rinv_neq_0_compat; lra).\n          symmetry in H.\n          eapply LpFin0_almostR20 in H; try typeclasses eauto.\n          rewrite (FiniteExpectation_proper_almostR2 prts (rvpower (rvabs (rvplus x y)) (const p)) (rvpower (rvabs y) (const p))).\n          + lra.\n          + rewrite H.\n            apply almostR2_eq_subr.\n            intros a.\n            rv_unfold.\n            repeat f_equal.\n            lra.\n      Qed.\n\n      Lemma LpRRV_norm_plus (x y:LpRRV p) : LpRRVnorm (LpRRVplus x y) <= LpRRVnorm x + LpRRVnorm y.\n      Proof.\n        unfold Proper, respectful, LpRRVnorm, LpRRVplus.\n        simpl LpRRV_rv_X.\n        simpl LpRRV_LpS_FiniteLp.\n        apply Minkowski.\n      Qed.\n\n      Lemma LpRRV_norm_scal_strong (x:R) (y:LpRRV p) : LpRRVnorm (LpRRVscale x y) = Rabs x * LpRRVnorm y.\n      Proof.\n        unfold LpRRVnorm, LpRRVscale.\n        simpl LpRRV_rv_X.\n        assert (eqq:rv_eq\n                      (rvpower (rvabs (rvscale x y)) (const p))\n                      (rvscale (power (Rabs x) p) (rvpower (rvabs y) (const p)))).\n        {\n          rewrite rv_abs_scale_eq.\n          rv_unfold; intros a.\n          rewrite power_mult_distr; trivial; apply Rabs_pos.\n        } \n        rewrite (FiniteExpectation_ext prts _ _ eqq).\n        rewrite FiniteExpectation_scale.\n        rewrite <- power_mult_distr.\n        - f_equal.\n          rewrite inv_power_cancel; try lra.\n          apply Rabs_pos.\n        - apply power_nonneg. \n        - apply FiniteExpectation_Lp_pos.\n      Qed.\n\n      Lemma LpRRV_norm_scal (x:R) (y:LpRRV p) : LpRRVnorm (LpRRVscale x y) <= Rabs x * LpRRVnorm y.\n      Proof.\n        right.\n        apply LpRRV_norm_scal_strong.\n      Qed.\n\n      Definition LpRRVball (x:LpRRV p) (e:R) (y:LpRRV p): Prop\n        := LpRRVnorm (LpRRVminus x y) < e.\n\n      Ltac LpRRV_simpl\n        := repeat match goal with\n                   | [H : LpRRV _ |- _ ] => destruct H as [???]\n                   end;\n            unfold LpRRVball, LpRRVnorm, LpRRVplus, LpRRVminus, LpRRVopp, LpRRVscale, LpRRVnorm in *\n            ; simpl pack_LpRRV; simpl LpRRV_rv_X in *.\n\n\n      Global Instance LpRRV_ball_sproper : Proper (LpRRV_seq ==> eq ==> LpRRV_seq ==> iff) LpRRVball.\n      Proof.\n        intros ?? eqq1 ?? eqq2 ?? eqq3.\n        unfold LpRRVball in *.\n        rewrite <- eqq1, <- eqq2, <- eqq3.\n        reflexivity.\n      Qed.\n\n      Global Instance LpRRV_ball_proper : Proper (LpRRV_eq ==> eq ==> LpRRV_eq ==> iff) LpRRVball.\n      Proof.\n        intros ?? eqq1 ?? eqq2 ?? eqq3.\n        unfold LpRRVball in *.\n        rewrite <- eqq1, <- eqq2, <- eqq3.\n        reflexivity.\n      Qed.\n\n      Lemma LpRRV_ball_refl x (e : posreal) : LpRRVball x e x.\n      Proof.\n        LpRRV_simpl.\n        assert (eqq1:rv_eq (rvpower (rvabs (rvminus LpRRV_rv_X0 LpRRV_rv_X0)) (const p))\n                           (const 0)).\n        {\n          rewrite rvminus_self.\n          rewrite rv_abs_const_eq.\n          rewrite Rabs_pos_eq by lra.\n          rewrite rvpower_const.\n          rewrite power0_Sbase.\n          reflexivity.\n        }\n        rewrite (FiniteExpectation_ext _ _ _ eqq1).\n        rewrite FiniteExpectation_const.\n        rewrite power0_Sbase.\n        apply cond_pos.\n      Qed.\n      \n      Lemma LpRRV_ball_sym x y e : LpRRVball x e y -> LpRRVball y e x.\n      Proof.\n        LpRRV_simpl.\n        intros.\n        rewrite (FiniteExpectation_ext _ _  (rvpower (rvabs (rvminus LpRRV_rv_X1 LpRRV_rv_X0)) (const p)))\n        ; trivial.\n        rewrite rvabs_rvminus_sym.\n        reflexivity.\n      Qed.\n\n      Lemma LpRRV_ball_trans x y z e1 e2 : LpRRVball x e1 y -> LpRRVball y e2 z -> LpRRVball x (e1+e2) z.\n      Proof.\n        generalize (LpRRV_norm_plus\n                      (LpRRVminus x y)\n                      (LpRRVminus y z)).\n        LpRRV_simpl.\n        intros.\n\n        apply (Rle_lt_trans\n                 _ \n                 ((power (FiniteExpectation prts (rvpower (rvabs (rvminus LpRRV_rv_X2 LpRRV_rv_X1)) (const p))) (/ p)) +\n                  (power  (FiniteExpectation prts (rvpower (rvabs (rvminus LpRRV_rv_X1 LpRRV_rv_X0)) (const p))) (/ p))))\n        ; [ | now apply Rplus_lt_compat].\n\n        (* by minkowski *)\n        rewrite (FiniteExpectation_ext _ (rvpower (rvabs (rvminus LpRRV_rv_X2 LpRRV_rv_X0)) (const p))\n                                       (rvpower (rvabs (rvplus (rvminus LpRRV_rv_X2 LpRRV_rv_X1) (rvminus LpRRV_rv_X1 LpRRV_rv_X0))) (const p))); trivial.\n        intros a.\n        rv_unfold.\n        f_equal.\n        f_equal.\n        lra.\n      Qed.\n\n      Lemma LpRRV_close_close (x y : LpRRV p) (eps : R) :\n        LpRRVnorm (LpRRVminus y x) < eps ->\n        LpRRVball x eps y.\n      Proof.\n        intros.\n        apply LpRRV_ball_sym.\n        apply H.\n      Qed.\n\n      Definition LpRRVnorm_factor : R := 1.\n      \n      Lemma LpRRV_norm_ball_compat (x y : LpRRV p) (eps : posreal) :\n        LpRRVball x eps y -> LpRRVnorm (LpRRVminus y x) < LpRRVnorm_factor * eps.\n      Proof.\n        intros HH.\n        apply LpRRV_ball_sym in HH.\n        unfold LpRRVnorm_factor.\n        field_simplify.\n        apply HH.\n      Qed.\n\n      Lemma LpRRV_plus_opp_minus (x y : LpRRV p) :\n        LpRRV_eq (LpRRVplus x (LpRRVopp y)) (LpRRVminus x y).\n      Proof.\n        unfold LpRRVminus, LpRRVplus, LpRRVopp.\n        simpl.\n        apply almostR2_eq_subr.\n        intros ?.\n        reflexivity.\n      Qed.\n\n      Lemma LpRRV_norm_telescope_minus (f : nat -> LpRRV p) :\n        forall (n k:nat), \n          LpRRVnorm (LpRRVminus (f ((S k)+n)%nat) (f n)) <= \n          sum_n_m (fun m => LpRRVnorm (LpRRVminus (f (S m)) (f m))) n (k + n).\n      Proof.\n        intros.\n        induction k.\n        - replace (0+n)%nat with n by lia.\n          rewrite sum_n_n.\n          simpl; lra.\n        - replace (S k + n)%nat with (S (k + n)%nat) by lia.\n          rewrite sum_n_Sm; [|lia].\n          rewrite (LpRRV_norm_proper (LpRRVminus (f (S (S k) + n)%nat) (f n))\n                                     (LpRRVplus  \n                                        (LpRRVminus (f (S (S k) + n)%nat) (f ((S k)+n)%nat))\n                                        (LpRRVminus (f ((S k) + n)%nat) (f n)))).\n          generalize (LpRRV_norm_plus  \n                        (LpRRVminus (f (S (S k) + n)%nat) (f (S k + n)%nat))\n                        (LpRRVminus (f (S k + n)%nat) (f n))); intros.\n          apply Rle_trans with (r2 := LpRRVnorm (LpRRVminus (f (S k + n)%nat) (f n)) +\n                                      LpRRVnorm (LpRRVminus (f (S (S k) + n)%nat) (f (S k + n)%nat))).\n          now rewrite Rplus_comm.\n          now apply Rplus_le_compat_r.\n          do 3 rewrite LpRRVminus_plus.\n          rewrite LpRRV_plus_assoc.\n          rewrite <- LpRRV_plus_assoc with (x := (f (S (S k) + n)%nat)).\n          rewrite <- (@LpRRV_plus_comm pnneg (f (S k + n)%nat)).\n          rewrite LpRRV_plus_inv.          \n          now rewrite LpRRV_plus_zero.\n      Qed.\n\n      Lemma sum_geom (n : nat) (c : R):\n        c <> 1 ->\n        sum_n (fun k => pow c k) n = (pow c (S n) - 1)/(c - 1).\n      Proof.\n        intros.\n        induction n.\n        - rewrite sum_O, pow_O, pow_1.\n          unfold Rdiv.\n          rewrite Rinv_r; lra.\n        - unfold sum_n.\n          rewrite sum_n_Sm; [|lia].\n          unfold sum_n in IHn.\n          rewrite IHn.\n          unfold plus; simpl.\n          field; lra.\n      Qed.\n\n      Lemma sum_geom_n_m (n m : nat) (c : R) :\n        c <> 1 ->\n        (S n <= m)%nat ->\n        sum_n_m (fun k => pow c k) (S n) m = (pow c (S m) - pow c (S n))/(c-1).\n      Proof.\n        intros.\n        rewrite sum_n_m_sum_n; [|lia].\n        rewrite sum_geom; trivial.\n        rewrite sum_geom; trivial.\n        unfold minus, plus, opp; simpl.\n        field; lra.\n      Qed.\n\n      Global Instance IsLp_sum (n : nat)\n             (rv_X : nat -> Ts -> R)\n             {rv : forall n, RandomVariable dom borel_sa (rv_X n)}\n             {islp:forall n, IsLp p (rv_X n)} :\n        IsLp p (rvsum rv_X n).\n      Proof.\n        intros.\n        induction n.\n        - assert (rv_eq (rvsum rv_X 0%nat)\n                        (rv_X 0%nat)).\n          + intros ?.\n            unfold rvsum.\n            now rewrite sum_O.\n          + now rewrite H.\n        - assert (rv_eq (rvsum rv_X (S n)) (rvplus (rvsum rv_X n) (rv_X (S n)))).\n          + intros ?.\n            unfold rvsum, sum_n, rvplus.\n            rewrite sum_n_Sm; [|lia].\n            reflexivity.\n          + rewrite H.\n            typeclasses eauto.\n      Qed.\n\n      Definition LpRRVsum (rvn:nat -> LpRRV p) (n:nat) : LpRRV p\n        := pack_LpRRV (rvsum rvn n).\n\n      Lemma LpRRV_norm_sum (f : nat -> LpRRV p) :\n        forall (n:nat), \n          LpRRVnorm (LpRRVsum f n) <=\n          sum_n (fun m => LpRRVnorm (f m)) n.\n      Proof.\n        unfold sum_n; intros.\n        induction n.\n        - unfold sum_n.\n          rewrite sum_n_n.\n          assert (LpRRV_eq  (LpRRVsum f 0) (f 0%nat)).\n          + apply almostR2_eq_subr.\n            intro x.\n            unfold LpRRVsum; simpl.\n            unfold rvsum.\n            now rewrite sum_O.\n          + rewrite H; lra.\n        - rewrite sum_n_Sm; [|lia].\n          assert (LpRRV_eq (LpRRVsum f (S n)) (LpRRVplus (LpRRVsum f n) (f (S n)))).\n          + apply almostR2_eq_subr.\n            intro x.\n            unfold LpRRVsum; simpl.\n            unfold rvsum, sum_n.\n            rewrite sum_n_Sm; [|lia].\n            now unfold rvplus, plus; simpl.\n          + rewrite H.\n            generalize (LpRRV_norm_plus (LpRRVsum f n) (f (S n))); intros.\n            apply Rle_trans with (r2 := LpRRVnorm (LpRRVsum f n) + LpRRVnorm (f (S n))); trivial.\n            unfold plus; simpl; lra.\n      Qed.\n\n      Lemma norm_abs (f : LpRRV p) :\n        LpRRVnorm (LpRRVabs f) = LpRRVnorm f.\n      Proof.\n        unfold LpRRVnorm.\n        f_equal.\n        unfold LpRRVabs.\n        simpl.\n        erewrite FiniteExpectation_ext with (rv_X2 := rvpower (rvabs f) (const p)).\n        reflexivity.\n        now rewrite rv_abs_abs.\n      Qed.\n      \n      Lemma c_pow_bound(c : R) (n : nat) :\n        0 < c < 1 ->\n        (1-c^n) / (1-c) <= 1/(1-c).\n      Proof.\n        intros.\n        unfold Rdiv.\n        apply Rmult_le_reg_r with (r := 1-c); [lra|].\n        rewrite Rmult_assoc.\n        rewrite <- Rinv_l_sym; [|lra].\n        rewrite Rmult_assoc.\n        rewrite <- Rinv_l_sym; [|lra].\n        apply Rplus_le_reg_r with (r := -1).\n        apply Ropp_le_cancel.\n        ring_simplify.\n        left; apply pow_lt; lra.\n      Qed.\n\n      Lemma lp_telescope_norm_bound (f : nat -> LpRRV p) :\n        (forall (n:nat), LpRRVnorm (LpRRVminus (f (S n)) (f n)) < / (pow 2 n)) ->\n        forall (n:nat), \n          LpRRVnorm (LpRRVsum (fun n0 => LpRRVabs (LpRRVminus (f (S n0)) (f n0))) n) <= 2.\n      Proof.\n        intros.\n        apply Rle_trans with (r2 := sum_n (fun n0 => LpRRVnorm (LpRRVabs (LpRRVminus (f (S n0)) (f n0)))) n).\n        apply LpRRV_norm_sum.\n        apply Rle_trans with (r2 := sum_n (fun n0 => / 2^n0) n).\n        unfold sum_n.\n        apply sum_n_m_le.\n        intros; left.\n        rewrite norm_abs.\n        apply H.\n        rewrite sum_n_ext with (b := fun n0 => (/ 2)^n0) by (intros; now rewrite Rinv_pow).\n        rewrite sum_geom; [|lra].\n        generalize (c_pow_bound (/2) (S n)); intros.\n        lra.\n      Qed.\n\n      Lemma power_inv_le b q c :\n            0 < q -> 0 <= b -> 0 <= c ->\n            power b (/ q) <= c ->\n            b <= power c q.\n      Proof.\n        intros.\n        replace c with (power (power c q) (/q)) in H2.\n        apply power_incr_inv in H2; trivial.\n        now apply Rinv_0_lt_compat.\n        apply power_nonneg.\n        apply inv_power_cancel; lra.\n      Qed.\n\n      Lemma isfin_Lim_seq (f : nat -> Ts -> R) :\n        (forall (omega:Ts), ex_finite_lim_seq (fun n => f n omega)) ->\n        forall (omega:Ts), is_finite (Lim_seq (fun n => f n omega)).\n      Proof.\n        intros.\n        now apply ex_finite_lim_seq_correct.\n      Qed.\n\n      Lemma rvlim_incr (f : nat -> LpRRV p)  :\n        (forall (n:nat), NonnegativeFunction  (f n)) ->\n        (forall (n:nat), rv_le (f n) (f (S n))) ->\n        (forall (omega:Ts), ex_finite_lim_seq (fun n => f n omega)) ->\n        (forall (n:nat), rv_le (f n) (rvlim f)).\n      Proof.\n        unfold rv_le, pointwise_relation, rvlim; intros.\n        generalize (Lim_seq_le_loc (fun _ => f n a) (fun n0 => f n0 a)); intros.\n        cut_to H2.\n        rewrite Lim_seq_const in H2.\n        generalize (isfin_Lim_seq _ H1); intros.\n        now rewrite <- (H3 a) in H2.\n        exists n; intros.\n        now apply (incr_le_strong (fun n => f n a)).\n      Qed.\n\n      Definition p_power (x:R) := (power x p).\n\n      Lemma continuity_p_power_pos (x : R) :\n        0 < x ->\n        continuity_pt p_power x.\n      Proof.\n        intros.\n        unfold p_power.\n        generalize (continuity_pt_filterlim); intros.\n        apply derivable_continuous_pt.\n        generalize (derivable_pt_lim_power' x p H); intros.\n        unfold derivable_pt, derivable_pt_abs.\n        eauto.\n      Qed.\n\n      (* implicitly assumes p > 0 *)\n      Lemma continuity_p_power_Rabs (x : R) :\n        continuity_pt (fun x0 => p_power (Rabs x0)) x.\n      Proof.\n        destruct (Req_dec x 0).\n        - unfold p_power.\n          repeat red; intros.\n          exists (power eps (/ p)).\n          split; [apply power_pos; lra | ].\n          unfold dist; simpl; unfold R_dist.\n          intros; subst.\n          rewrite Rabs_R0.\n          rewrite Rminus_0_r in H1.\n          destruct H1.\n          rewrite power0_Sbase, Rminus_0_r.\n          rewrite Rabs_right; [| apply Rle_ge, power_nonneg].\n          replace (eps) with (power (power eps (/p)) p) by (apply power_inv_cancel; lra).\n          apply Rlt_power_l; [lra |].\n          split; trivial.\n          apply Rabs_pos.\n        - apply continuity_pt_comp with (f2 := p_power).\n          generalize Rcontinuity_abs.\n          now unfold continuity.\n          apply continuity_p_power_pos.\n          generalize (Rabs_pos x); intros.\n          destruct H0; trivial.\n          symmetry in H0; apply Rabs_eq_0 in H0.\n          lra.\n      Qed.\n\n      (* need stronger version of monotone_convergence to remove\n         is_finite (Lim_seq (fun n : nat => f n omega))) hypothesis *)\n      Lemma islp_rvlim_bounded (f : nat -> LpRRV p) (c : R) :\n        (forall (n:nat), LpRRVnorm (f n) <= c) ->\n        (forall (n:nat), RandomVariable dom borel_sa (f n)) ->\n        (forall (n:nat), NonnegativeFunction  (f n)) ->\n        (forall (n:nat), rv_le (f n) (f (S n))) ->\n        (forall (omega:Ts), ex_finite_lim_seq (fun n : nat => f n omega)) ->\n        IsLp p (rvlim f).\n      Proof.\n        intros fnorm f_rv fpos fincr exfinlim.\n        assert (cpos: 0 <= c).\n        {\n          specialize (fnorm 0%nat).\n          apply Rle_trans with (r2 := (LpRRVnorm (f 0%nat))); trivial.\n          unfold LpRRVnorm.\n          apply power_nonneg.\n        }\n        generalize (isfin_Lim_seq _ exfinlim); intros isfin_flim.\n        unfold LpRRVnorm in fnorm.\n        unfold IsLp.\n        assert (finexp: forall n, FiniteExpectation prts (rvpower (rvabs (f n)) (const p)) <= \n                                  power c p).\n        {\n        intros.\n        apply power_inv_le; trivial.\n        lra.\n        apply FiniteExpectation_Lp_pos.\n\n        }\n        assert (forall n, NonnegativeFunction (rvpower (rvabs (f n)) (const p))).\n        {\n          intros.\n          unfold NonnegativeFunction, rvpower; intros.\n          apply power_nonneg.\n        }\n        assert (rvlim_rv: RandomVariable dom borel_sa (rvpower (rvabs (rvlim (fun x : nat => f x))) (const p))).\n        apply rvpower_rv.\n        apply rvabs_rv.\n        apply rvlim_rv; trivial.\n        typeclasses eauto.\n        generalize ( monotone_convergence \n                      (rvpower (rvabs (rvlim (fun x : nat => f x))) (const p))\n                      (fun n => (rvpower (rvabs (f n)) (const p))) _ _ _ _); intro monc.\n\n        cut_to monc.\n        - unfold IsFiniteExpectation.\n          assert (NonnegativeFunction  (rvpower (rvabs (rvlim (fun x : nat => f x))) (const p))).\n          {\n            unfold NonnegativeFunction, rvpower; intros.\n            apply power_nonneg.            \n          }\n          rewrite Expectation_pos_pofrf with (nnf := H0).\n          assert (Rbar_le\n                    (Lim_seq (fun n : nat => NonnegExpectation (rvpower (rvabs (f n)) (const p)))) (power c p)).\n          replace (Finite (power c p)) with (Lim_seq (fun _ => power c p)).\n          apply Lim_seq_le_loc.\n          exists (0%nat).\n          intros.\n          specialize (finexp n).\n          now rewrite FiniteNonnegExpectation with (posX := (H n)) in finexp.\n          apply Lim_seq_const.\n          rewrite monc in H1.\n          cut (is_finite (NonnegExpectation (rvpower (rvabs (rvlim (fun x : nat => f x))) (const p)))).\n          + intros eqq; now rewrite <- eqq.\n           + eapply bounded_is_finite.\n            * eapply NonnegExpectation_pos.\n            * eapply H1.\n        - intros n x.\n          unfold rvpower.\n          apply Rle_power_l; [ unfold const; lra |].\n          split; [apply Rabs_pos |].\n          unfold rvabs.\n          rewrite Rabs_right by apply Rle_ge, fpos.\n          rewrite Rabs_right.\n          apply rvlim_incr; trivial.\n          apply Rge_trans with (r2 := f n x).\n          + apply Rle_ge.\n            apply rvlim_incr; trivial.\n          + apply Rle_ge, fpos.\n        - intros n x.\n          apply Rle_power_l.\n          + unfold const; lra.\n          + unfold rvabs.\n            split; [apply Rabs_pos |].\n            rewrite Rabs_right by apply Rle_ge, fpos.\n            rewrite Rabs_right by apply Rle_ge, fpos.\n            apply fincr.\n        - intros; apply IsFiniteNonnegExpectation.\n          apply (@LpRRV_LpS_FiniteLp p (f n)).\n        - intros.\n          unfold rvpower, rvabs, rvlim, const.\n          apply is_lim_seq_ext with (u := fun n : nat => p_power (Rabs (f n omega))).\n          now unfold p_power.\n          apply is_lim_seq_continuous with (f := fun x => p_power (Rabs x)).\n          apply continuity_p_power_Rabs.\n          generalize (Lim_seq_correct (fun n : nat => f n omega)); intros.\n          rewrite <- (isfin_flim omega) in H0.\n          apply H0.\n          apply ex_lim_seq_incr.\n          now unfold rv_le, pointwise_relation in fincr.\n        Qed.\n\n\n      Lemma is_lim_power_inf (f : nat -> R) :\n        is_lim_seq f p_infty -> is_lim_seq (fun n => power (f n) p) p_infty.\n      Proof.\n        do 2 rewrite <- is_lim_seq_spec.\n        unfold is_lim_seq'; intros.\n        specialize (H (power (Rmax M 0) (/p))).\n        destruct H.\n        exists x.\n        intros.\n        specialize (H n H0).\n        apply Rle_lt_trans with (r2 := Rmax M 0).\n        apply Rmax_l.\n        replace (Rmax M 0) with (power (power (Rmax M 0) (/p)) p).\n        apply Rlt_power_l.\n        lra.\n        split; trivial.\n        apply power_nonneg.\n        apply power_inv_cancel; try lra.\n        apply Rmax_r.\n      Qed.\n\n      Lemma lim_power_inf (f : nat -> R) :\n        ex_lim_seq f ->\n        Lim_seq f = p_infty -> Lim_seq (fun n => power (f n) p) = p_infty.\n      Proof.\n        intros.\n        apply Lim_seq_correct in H.\n        rewrite H0 in H.\n        apply is_lim_power_inf in H.\n        now apply is_lim_seq_unique in H.\n      Qed.\n\n      Lemma Rbar_power_lim_comm (f : nat -> Ts -> R) (x:Ts) :\n        (forall (n:nat), rv_le (f n) (f (S n))) ->\n        Rbar_power (Rbar_abs (Lim_seq (fun n : nat => f n x))) p = Lim_seq (fun n : nat => power (Rabs (f n x)) p).\n      Proof.\n        intros.\n        assert (exlim: ex_lim_seq (fun n => f n x)).\n        {\n          apply ex_lim_seq_incr.\n          intros; apply H.\n        }\n        case_eq (Lim_seq (fun n : nat => f n x)); intros.\n        - generalize (is_lim_seq_continuous (fun x => p_power (Rabs x)) (fun n => f n x) (Lim_seq (fun n => f n x))); intros.\n          cut_to H1.\n          + apply is_lim_seq_unique in H1.\n            unfold p_power in H1.\n            rewrite H0 in H1.\n            rewrite H1.\n            now simpl.\n          + apply continuity_p_power_Rabs.\n          + assert (is_finite (Lim_seq (fun n => f n x))) by now rewrite H0.\n            rewrite H2.\n            now apply Lim_seq_correct.\n        - simpl; symmetry.\n          generalize (ex_lim_seq_abs _ exlim); intros.\n          apply lim_power_inf; trivial.\n          rewrite Lim_seq_abs; trivial.\n          rewrite H0.\n          now simpl.\n        - simpl; symmetry.\n          generalize (ex_lim_seq_abs _ exlim); intros.\n          apply lim_power_inf; trivial.\n          rewrite Lim_seq_abs; trivial.\n          rewrite H0.\n          now simpl.\n      Qed.\n\n      (* stronger version monotone_convergence_Rbar allows us to remove\n         is_finite (Lim_seq (fun n : nat => f n omega))) hypothesis *)\n      Lemma islp_Rbar_rvlim_bounded (f : nat -> LpRRV p) (c : R) :\n(*        0 <= c -> *)\n        (forall (n:nat), LpRRVnorm (f n) <= c) ->\n        (forall (n:nat), RandomVariable dom borel_sa (f n)) ->\n        (forall (n:nat), NonnegativeFunction  (f n)) ->\n        (forall (n:nat), rv_le (f n) (f (S n))) ->\n        IsLp_Rbar p (Rbar_rvlim (fun n => LpRRV_rv_X (f n))).\n      Proof.\n        intros fnorm f_rv fpos fincr.\n        assert (cpos: 0 <= c).\n        {\n          specialize (fnorm 0%nat).\n          apply Rle_trans with (r2 := (LpRRVnorm (f 0%nat))); trivial.\n          unfold LpRRVnorm.\n          apply power_nonneg.\n        }\n        unfold LpRRVnorm in fnorm.\n        unfold IsLp_Rbar.\n        assert (finexp: forall n, FiniteExpectation prts (rvpower (rvabs (f n)) (const p)) <= \n                                  power c p).\n        {\n        intros.\n        apply power_inv_le; trivial.\n        lra.\n        apply FiniteExpectation_Lp_pos.\n\n        }\n        assert (forall n, NonnegativeFunction (rvpower (rvabs (f n)) (const p))).\n        {\n          intros.\n          unfold NonnegativeFunction, rvpower; intros.\n          apply power_nonneg.\n        }\n        generalize ( monotone_convergence_Rbar_rvlim_fin\n                      (fun n => (rvpower (rvabs (f n)) (const p))) _ _ ); intro monc.\n        cut_to monc.\n        - assert (Rbar_le\n                    (ELim_seq (fun n : nat => NonnegExpectation (rvpower (rvabs (f n)) (const p)))) (power c p)).\n          {\n            replace (Finite (power c p)) with (ELim_seq (fun _ => power c p)).\n            - apply ELim_seq_le_loc.\n              apply filter_forall; intros n.\n              specialize (finexp n).\n              rewrite <- (FiniteNonnegExpectation_alt _ _).\n              apply finexp.\n            - apply ELim_seq_const.\n          }\n          rewrite monc in H0.\n          assert (Rbar_NonnegativeFunction (Rbar_rvlim (fun n : nat => rvpower (rvabs (f n)) (const p)))) by typeclasses eauto.\n          rewrite Rbar_NonnegExpectation_ext with (nnf2 := H1).\n          + eapply bounded_is_finite.\n            * eapply Rbar_NonnegExpectation_pos.\n            * eapply H0.\n          + intro x.\n            unfold Rbar_rvlim, rvpower, rvabs, const.\n            repeat rewrite Elim_seq_fin.\n            apply (Rbar_power_lim_comm f x fincr).\n        - intros n x.\n          unfold rvpower.\n          apply Rle_power_l; [ unfold const; lra |].\n          split; [apply Rabs_pos |].\n          unfold rvabs.\n          rewrite Rabs_right by apply Rle_ge, fpos.\n          rewrite Rabs_right.\n          apply fincr.\n          apply Rle_ge, fpos.\n    Qed.\n\n      Lemma LpRRVsum_pos (f : nat -> LpRRV p) (n : nat) :\n        (forall n, NonnegativeFunction (f n)) ->\n        NonnegativeFunction (LpRRVsum f n).\n      Proof.\n        unfold NonnegativeFunction.\n        intros.\n        unfold LpRRVsum, pack_LpRRV; simpl.\n        unfold rvsum.\n        induction n.\n        - now rewrite sum_O.\n        - rewrite sum_Sn.\n          unfold rvplus, plus; simpl.\n          now apply Rplus_le_le_0_compat.\n      Qed.\n          \n      Lemma islp_lim_telescope_abs (f : nat -> LpRRV p) :\n        (forall (n:nat), LpRRVnorm (LpRRVminus (f (S n)) (f n)) < / (pow 2 n)) ->\n        (forall (n:nat), RandomVariable dom borel_sa (f n)) ->\n        (forall omega : Ts,\n            ex_finite_lim_seq\n              (fun n : nat =>\n                 LpRRVsum (fun n0 : nat => LpRRVabs (LpRRVminus (f (S n0)) (f n0))) n omega)) ->\n        IsLp p (rvlim\n                  (fun n => LpRRVsum (fun n0 => LpRRVabs (LpRRVminus (f (S n0)) (f n0))) n)).\n      Proof.\n        intros.\n        apply islp_rvlim_bounded with (c := 2); try lra.\n        intros.\n        apply lp_telescope_norm_bound; trivial.\n        - intros.\n          typeclasses eauto.\n        - intros.\n          apply LpRRVsum_pos.\n          typeclasses eauto.\n        - intros n x.\n          unfold LpRRVsum, pack_LpRRV; simpl.\n          unfold rvsum.\n          rewrite sum_Sn.\n          apply Rplus_le_compat1_l.\n          unfold rvabs.\n          apply Rabs_pos.\n        - apply H1.\n      Qed.\n      \n      Lemma islp_Rbar_lim_telescope_abs_c (f : nat -> LpRRV p) (c : R) :\n        (forall n : nat,\n            LpRRVnorm\n              (LpRRVsum (fun n0 : nat => LpRRVabs (LpRRVminus (f (S n0)) (f n0))) n) <= c) ->\n        (forall (n:nat), RandomVariable dom borel_sa (f n)) ->\n        IsLp_Rbar p (Rbar_rvlim\n                  (fun n => LpRRV_rv_X (LpRRVsum (fun n0 => LpRRVabs (LpRRVminus (f (S n0)) (f n0))) n))).\n      Proof.\n        intros.\n        apply islp_Rbar_rvlim_bounded with (c := c); trivial; try lra.\n        - intros.\n          typeclasses eauto.\n        - intros.\n          apply LpRRVsum_pos.\n          typeclasses eauto.\n        - intros n x.\n          unfold LpRRVsum, pack_LpRRV; simpl.\n          unfold rvsum.\n          rewrite sum_Sn.\n          apply Rplus_le_compat1_l.\n          unfold rvabs.\n          apply Rabs_pos.\n      Qed.\n\n      Lemma islp_Rbar_lim_telescope_abs (f : nat -> LpRRV p) :\n        (forall (n:nat), LpRRVnorm (LpRRVminus (f (S n)) (f n)) < / (pow 2 n)) ->\n        (forall (n:nat), RandomVariable dom borel_sa (f n)) ->\n        IsLp_Rbar p (Rbar_rvlim\n                  (fun n => LpRRV_rv_X (LpRRVsum (fun n0 => LpRRVabs (LpRRVminus (f (S n0)) (f n0))) n))).\n      Proof.\n        intros.\n        apply islp_Rbar_lim_telescope_abs_c with (c := 2); trivial.\n        now apply lp_telescope_norm_bound.\n      Qed.\n\n      Lemma lp_norm_seq_pow2 (f : nat -> LpRRV p) :\n        (forall (n:nat), LpRRVnorm (LpRRVminus (f (S n)) (f n)) < / (pow 2 n)) ->\n        forall (n m:nat), (m > S n)%nat -> \n                          LpRRVnorm (LpRRVminus (f m) (f (S n))) <= / (pow 2 n).\n      Proof.\n        intros.\n        generalize (LpRRV_norm_telescope_minus f (S n) (m-S (S n))%nat); intros.\n        replace (S (m - S (S n)) + (S n))%nat with (m) in H1 by lia.\n        replace (m - S (S n) + (S n))%nat with (m-1)%nat in H1 by lia.\n        apply Rle_trans with \n            (r2 := sum_n_m (fun m : nat => LpRRVnorm (LpRRVminus (f (S m)) (f m))) (S n) (m - 1)); trivial.\n        apply Rle_trans with (r2 := sum_n_m (fun m0 => / (2 ^ m0)) (S n) (m-1)%nat).\n        apply sum_n_m_le; intros; left.\n        apply H.\n        assert (forall n, (/ (pow 2 n)) = pow (/ 2) n).\n        intros.\n        now rewrite <- Rinv_pow.\n        rewrite sum_n_m_ext with (b := fun m0 => pow (/ 2) m0); trivial.\n        rewrite sum_geom_n_m; [|lra|lia].\n        replace (/2 ^ n) with ((/2)^n) by now rewrite H2.\n        replace (S (m-1)) with (m) by lia.\n        unfold Rdiv.\n        replace (/2 - 1) with (-/2) by lra.\n        rewrite <- Ropp_inv_permute; [|lra].\n        field_simplify.\n        simpl.\n        rewrite <- Rmult_assoc.\n        replace (2 * / 2) with (1) by lra.\n        ring_simplify.\n        replace ((/ 2)^n) with (0 + (/ 2)^n) at 2 by lra.\n        apply Rplus_le_compat_r.\n        apply Ropp_le_cancel.\n        ring_simplify.\n        replace (m) with (S (m-1)) by lia.\n        simpl.\n        field_simplify.\n        apply pow_le; lra.\n     Qed.\n\n      Definition LpRRV_UniformSpace_mixin : UniformSpace.mixin_of (LpRRV p)\n        := UniformSpace.Mixin  (LpRRV p) (LpRRVpoint p) LpRRVball\n                               LpRRV_ball_refl\n                               LpRRV_ball_sym\n                               LpRRV_ball_trans.\n\n      Canonical LpRRV_UniformSpace :=\n        UniformSpace.Pack (LpRRV p) LpRRV_UniformSpace_mixin (LpRRV p).\n      \n      Section quotbigp.\n      Ltac LpRRVq_simpl :=\n        repeat match goal with\n               | [H: LpRRVq p |- _ ] =>\n                 let xx := fresh H in destruct (Quot_inv H) as [xx ?]; subst H; rename xx into H\n               | [H: AbelianGroup.sort LpRRVq_AbelianGroup |- _ ] =>\n                 let xx := fresh H in destruct (Quot_inv H) as [xx ?]; subst H; rename xx into H\n               end\n        ; try autorewrite with quot in *\n        ; try apply (@eq_Quot _ _ LpRRV_eq_equiv).\n      \n      Hint Rewrite @LpRRVq_constE : quot.\n      Hint Rewrite @LpRRVq_zeroE : quot.\n      Hint Rewrite @LpRRVq_scaleE : quot.\n      Hint Rewrite @LpRRVq_oppE : quot.\n      Hint Rewrite @LpRRVq_plusE : quot.\n      Hint Rewrite @LpRRVq_minusE : quot.\n\n      Definition LpRRVq_ball : LpRRVq p -> R -> LpRRVq p -> Prop\n        := quot_lift_ball LpRRV_eq LpRRVball.\n\n      Lemma LpRRVq_ballE x e y : LpRRVq_ball (Quot _ x) e (Quot _ y)  = LpRRVball x e y.\n      Proof.\n        apply quot_lift_ballE.\n      Qed.\n\n      Hint Rewrite LpRRVq_ballE : quot.\n      \n      Definition LpRRVq_point : LpRRVq p\n        := Quot _ (LpRRVpoint p).\n\n\n      Lemma LpRRVq_pointE : LpRRVq_point  = Quot _ (LpRRVpoint p).\n      Proof.\n        reflexivity.\n      Qed.\n\n      Hint Rewrite LpRRVq_pointE : quot.\n\n      Lemma LpRRVq_ball_refl x (e : posreal) : LpRRVq_ball x e x.\n      Proof.\n        LpRRVq_simpl.\n        apply LpRRV_ball_refl.\n      Qed.\n      \n      Lemma LpRRVq_ball_sym x y e : LpRRVq_ball x e y -> LpRRVq_ball y e x.\n      Proof.\n        LpRRVq_simpl.\n        apply LpRRV_ball_sym.\n      Qed.\n\n      Lemma LpRRVq_ball_trans x y z e1 e2 : LpRRVq_ball x e1 y -> LpRRVq_ball y e2 z -> LpRRVq_ball x (e1+e2) z.\n      Proof.\n        LpRRVq_simpl.\n        apply LpRRV_ball_trans.\n      Qed.\n\n      Definition LpRRVq_UniformSpace_mixin : UniformSpace.mixin_of (LpRRVq p)\n        := UniformSpace.Mixin  (LpRRVq p) LpRRVq_point LpRRVq_ball\n                               LpRRVq_ball_refl\n                               LpRRVq_ball_sym\n                               LpRRVq_ball_trans.\n\n      Canonical LpRRVq_UniformSpace :=\n        UniformSpace.Pack (LpRRVq p) LpRRVq_UniformSpace_mixin (LpRRVq p).\n\n      Canonical LpRRVq_NormedModuleAux :=\n        NormedModuleAux.Pack R_AbsRing (LpRRVq p)\n                             (NormedModuleAux.Class R_AbsRing (LpRRVq p)\n                                                    (ModuleSpace.class _ LpRRVq_ModuleSpace)\n                                                    (LpRRVq_UniformSpace_mixin)) (LpRRVq p).\n\n      \n      Definition LpRRVq_norm : (LpRRVq p) -> R\n        := quot_rec LpRRV_norm_proper.\n\n      Lemma LpRRVq_normE x : LpRRVq_norm (Quot _ x)  = LpRRVnorm x.\n      Proof.\n        apply quot_recE.\n      Qed.\n\n      Hint Rewrite LpRRVq_normE : quot.\n\n      Lemma LpRRVq_norm_plus (x y:LpRRVq p) : LpRRVq_norm (LpRRVq_plus x y) <= LpRRVq_norm x + LpRRVq_norm y.\n      Proof.\n        LpRRVq_simpl.\n        now apply LpRRV_norm_plus.\n      Qed.\n      \n      Lemma LpRRVq_norm_scal_strong (x:R) (y:LpRRVq p) : LpRRVq_norm (LpRRVq_scale x y) = Rabs x * LpRRVq_norm y.\n      Proof.\n        LpRRVq_simpl.\n        now apply LpRRV_norm_scal_strong.\n      Qed.\n\n      Lemma LpRRVq_norm_scal x (y:LpRRVq p) : LpRRVq_norm (LpRRVq_scale x y) <= Rabs x * LpRRVq_norm y.\n      Proof.\n        LpRRVq_simpl.\n        now apply LpRRV_norm_scal.\n      Qed.\n\n      Lemma LpRRVq_norm0 x : LpRRVq_norm x = 0 -> x = LpRRVq_zero.\n      Proof.\n        intros.\n        LpRRVq_simpl.\n        now apply LpRRV_norm0.\n      Qed.\n\n      Lemma LpRRVq_minus_minus (x y : LpRRVq p) :\n        minus x y = LpRRVq_minus x y.\n      Proof.\n        unfold minus, plus, opp; simpl.\n        LpRRVq_simpl.\n        now rewrite LpRRVminus_plus.\n      Qed.\n\n      Lemma LpRRVq_minus_plus_opp\n            (x y : LpRRVq p) :\n        LpRRVq_minus x y = LpRRVq_plus x (LpRRVq_opp y).\n      Proof.\n        unfold minus, plus, opp; simpl.\n        LpRRVq_simpl.\n        now rewrite LpRRVminus_plus.\n      Qed.\n\n      Lemma LpRRVq_close_close (x y : LpRRVq p) (eps : R) :\n        LpRRVq_norm (minus y x) < eps ->\n        LpRRVq_ball x eps y.\n      Proof.\n        intros.\n        rewrite LpRRVq_minus_minus in H.\n        LpRRVq_simpl.\n        now apply LpRRV_close_close.\n      Qed.\n\n      Lemma LpRRVq_norm_ball_compat (x y : LpRRVq p) (eps : posreal) :\n        LpRRVq_ball x eps y -> LpRRVq_norm (minus y x) < LpRRVnorm_factor * eps.\n      Proof.\n        intros.\n        rewrite LpRRVq_minus_minus.\n        LpRRVq_simpl.\n        now apply LpRRV_norm_ball_compat.\n      Qed.\n \n      Definition LpRRVq_NormedModule_mixin : NormedModule.mixin_of R_AbsRing LpRRVq_NormedModuleAux\n        := NormedModule.Mixin R_AbsRing LpRRVq_NormedModuleAux\n                              LpRRVq_norm\n                              LpRRVnorm_factor\n                              LpRRVq_norm_plus\n                              LpRRVq_norm_scal\n                              LpRRVq_close_close\n                              LpRRVq_norm_ball_compat\n                              LpRRVq_norm0.\n\n      Canonical LpRRVq_NormedModule :=\n        NormedModule.Pack R_AbsRing (LpRRVq p)\n                          (NormedModule.Class R_AbsRing (LpRRVq p)\n                                              (NormedModuleAux.class _ LpRRVq_NormedModuleAux)\n                                              LpRRVq_NormedModule_mixin)\n                          (LpRRVq p).\n\n\n    End quotbigp.\n\n  End packedbigp.\n\n    Global Arguments LpRRV : clear implicits.\n    Global Arguments LpRRVq : clear implicits.\n\nEnd Lp.\n\nHint Rewrite LpRRVq_constE : quot.\nHint Rewrite LpRRVq_zeroE : quot.\nHint Rewrite LpRRVq_scaleE : quot.\nHint Rewrite LpRRVq_oppE : quot.\nHint Rewrite LpRRVq_plusE : quot.\nHint Rewrite LpRRVq_minusE : quot.\nHint Rewrite @LpRRVq_constE : quot.\nHint Rewrite @LpRRVq_zeroE : quot.\nHint Rewrite @LpRRVq_scaleE : quot.\nHint Rewrite @LpRRVq_oppE : quot.\nHint Rewrite @LpRRVq_plusE : quot.\nHint Rewrite @LpRRVq_minusE : quot.\nHint Rewrite @LpRRVq_constE : quot.\nHint Rewrite LpRRVq_normE : quot.\n\nGlobal Arguments LpRRVq_AbelianGroup {Ts} {dom} prts p.\nGlobal Arguments LpRRVq_ModuleSpace {Ts} {dom} prts p.\n\nGlobal Arguments LpRRVq_UniformSpace {Ts} {dom} prts p.\nGlobal Arguments LpRRVq_NormedModule {Ts} {dom} prts p.\n\nLtac LpRRVq_simpl :=\n  repeat match goal with\n         | [H: LpRRVq _ _ |- _ ] =>\n           let xx := fresh H in destruct (Quot_inv H) as [xx ?]; subst H; rename xx into H\n         | [H: AbelianGroup.sort (LpRRVq_AbelianGroup _ _ _) |- _ ] =>\n           let xx := fresh H in destruct (Quot_inv H) as [xx ?]; subst H; rename xx into H\n         | [H: ModuleSpace.sort R_Ring (LpRRVq_ModuleSpace _ _) |- _ ] =>\n           let xx := fresh H in destruct (Quot_inv H) as [xx ?]; subst H; rename xx into H\n         end\n  ; try autorewrite with quot in *\n  ; try apply (@eq_Quot _ _ (LpRRV_eq_equiv _)).\n\nLtac LpRRV_simpl\n  := repeat match goal with\n            | [H : LpRRV _ _ |- _ ] => destruct H as [???]\n            end\n     ; unfold LpRRVplus, LpRRVminus, LpRRVopp, LpRRVscale\n     ; simpl\n.\n\nGlobal Arguments LpRRV_seq {Ts} {dom} {prts} {p} rv1 rv2.\n(* Global Arguments LpRRV_eq {Ts} {dom}{prts} {p} rv1 rv2. *)\n\nSection complete.\n  Section complete1.\n\n    Context {Ts:Type} \n            {dom: SigmaAlgebra Ts}\n            (prts: ProbSpace dom).\n    \n    Context {p:R}.\n    Context (pbig:1 <= p).\n\n  Let pnneg : nonnegreal := bignneg p pbig.\n  Canonical pnneg.\n\n  Lemma LpRRV_norm_opp (x : LpRRV prts p) : LpRRVnorm prts (LpRRVopp prts x) = LpRRVnorm prts x.\n  Proof.\n    unfold LpRRVnorm, LpRRVopp.\n    f_equal.\n    apply FiniteExpectation_ext.\n    simpl.\n    intro z.\n    rv_unfold.\n    f_equal.\n    replace (-1 * (x z)) with (- x z) by lra.\n    now rewrite Rabs_Ropp.\n  Qed.\n\n     Lemma inv_pow_2_pos  (n : nat) :\n        0 < / (2 ^ n) .\n  Proof.\n    apply Rinv_0_lt_compat.\n    apply pow_lt.\n    lra.\n  Qed.\n\n  Definition LpRRV_lim_ball_center_center \n             (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop) :\n    ProperFilter F -> cauchy F ->\n    forall (n:nat), \n      {b:LpRRV_UniformSpace prts pbig |\n        F (Hierarchy.ball (M:= LpRRV_UniformSpace prts pbig) b (mkposreal _ (inv_pow_2_pos n)))}.\n  Proof.\n    intros Pf cF n.\n    pose ( ϵ := / (2 ^ n)).\n    assert (ϵpos : 0 < ϵ) by apply inv_pow_2_pos.\n    destruct (constructive_indefinite_description _ (cF (mkposreal ϵ ϵpos)))\n      as [x Fx].\n    now exists x.\n  Defined.\n\n  Definition LpRRV_lim_ball_center \n             (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop) :\n    ProperFilter F -> cauchy F ->\n    forall (n:nat), {b:LpRRV prts p ->Prop | F b}.\n  Proof.\n    intros Pf cF n.\n    pose ( ϵ := / (2 ^ n)).\n    assert (ϵpos : 0 < ϵ) by apply inv_pow_2_pos.\n    destruct (constructive_indefinite_description _ (cF (mkposreal ϵ ϵpos)))\n      as [x Fx].\n    simpl in *.\n    now exists  (Hierarchy.ball (M:= LpRRV_UniformSpace prts pbig) x ϵ).\n  Defined.\n\n  Definition LpRRV_lim_ball_cumulative\n             (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n             (PF:ProperFilter F)\n             (cF:cauchy F)\n             (n:nat) : {x:LpRRV prts p->Prop | F x}\n    := fold_right (fun x y =>\n                     exist _ _ (Hierarchy.filter_and\n                       _ _ (proj2_sig x) (proj2_sig y)))\n                  (exist _ _ Hierarchy.filter_true)\n                  (map (LpRRV_lim_ball_center F PF cF) (seq 0 (S n))).\n\n  Definition LpRRV_lim_picker\n             (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n             (PF:ProperFilter F)\n             (cF:cauchy F)\n             (n:nat) : LpRRV prts p\n    := (proj1_sig (\n            constructive_indefinite_description\n              _\n              (filter_ex\n                 _\n                 (proj2_sig (LpRRV_lim_ball_cumulative F PF cF n))))).\n\n  Definition LpRRV_lim_picker_ext0\n             (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n             (PF:ProperFilter F)\n             (cF:cauchy F)\n             (n:nat) : LpRRV prts p\n    := match n with\n       | 0 => LpRRVzero prts\n       | S n' => LpRRV_lim_picker F PF cF n\n       end.\n\n    Lemma lim_picker_cumulative_included\n             (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n             (PF:ProperFilter F)\n             (cF:cauchy F)\n             (N n:nat) :\n      (N <= n)%nat ->\n      forall x,\n      proj1_sig (LpRRV_lim_ball_cumulative F PF cF n) x ->\n       (proj1_sig (LpRRV_lim_ball_center F PF cF N)) x.\n    Proof.\n      unfold LpRRV_lim_ball_cumulative.\n      intros.\n      assert (inn:In N (seq 0 (S n))).\n      {\n        apply in_seq.\n        lia.\n      }\n      revert inn H0.\n      generalize (seq 0 (S n)).\n      clear.\n      induction l; simpl.\n      - tauto.\n      - intros [eqq | inn]; intros.\n        + subst.\n          tauto.\n        + apply (IHl inn).\n          tauto.\n    Qed.\n    \n  Lemma lim_picker_included\n             (F : (LpRRV_UniformSpace prts pbig  -> Prop) -> Prop)\n             (PF:ProperFilter F)\n             (cF:cauchy F)\n             (N n:nat) :\n    (N <= n)%nat ->\n    (proj1_sig (LpRRV_lim_ball_center F PF cF N)) \n      (LpRRV_lim_picker F PF cF n).\n  Proof.\n    intros.\n    unfold LpRRV_lim_picker.\n    unfold proj1_sig at 2.\n    match_destr.\n    eapply lim_picker_cumulative_included; eauto.\n  Qed.\n\n  Lemma lim_ball_center_ball_center_center  (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F)\n        (n:nat) :\n    forall (x:UniformSpace.sort (LpRRV_UniformSpace prts pbig)),\n      (Hierarchy.ball (M:= LpRRV_UniformSpace prts pbig)\n                      (proj1_sig (LpRRV_lim_ball_center_center F PF cF n))\n                      (mkposreal _ (inv_pow_2_pos n))) x\n\n      <-> proj1_sig (LpRRV_lim_ball_center F PF cF n) x.\n  Proof.\n    unfold LpRRV_lim_ball_center; simpl.\n    unfold LpRRV_lim_ball_center_center; simpl.\n    intros.\n    destruct ( constructive_indefinite_description\n            (fun x0 : LpRRV prts p => F (Hierarchy.ball x0 (/ 2 ^ n)))\n            (cF {| pos := / 2 ^ n; cond_pos := inv_pow_2_pos n |})); simpl.\n    tauto.\n  Qed.\n    \n  Lemma lim_picker_center_included\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F)\n        (n:nat) :\n    (Hierarchy.ball (M:= LpRRV_UniformSpace prts pbig)\n                    (proj1_sig (LpRRV_lim_ball_center_center F PF cF n))\n                    (mkposreal _ (inv_pow_2_pos n)))\n      (LpRRV_lim_picker F PF cF n).\n  Proof.\n    simpl.\n    apply lim_ball_center_ball_center_center.\n    now apply lim_picker_included.\n  Qed.\n\n  Lemma lim_picker_center_included2\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F)\n        (N:nat) :\n    forall (n:nat), \n      (n >= N)%nat ->\n      (Hierarchy.ball (M:= LpRRV_UniformSpace prts pbig)\n                    (proj1_sig (LpRRV_lim_ball_center_center F PF cF N))\n                    (mkposreal _ (inv_pow_2_pos N)))\n      (LpRRV_lim_picker F PF cF n).\n  Proof.\n    intros.\n    simpl.\n    apply lim_ball_center_ball_center_center.\n    apply lim_picker_included.\n    lia.\n  Qed.\n\n  Lemma LpRRVq_opp_opp (x : LpRRVq_AbelianGroup prts (bignneg _ pbig)) :\n    opp x = LpRRVq_opp prts x.\n  Proof.\n    unfold opp; simpl.\n    LpRRVq_simpl.\n    reflexivity.\n  Qed.\n\n  Lemma LpRRVq_minus_plus_opp'\n        (x y : LpRRVq prts p) :\n    LpRRVq_minus prts x y = LpRRVq_plus prts x (LpRRVq_opp prts y).\n  Proof.\n    unfold minus, plus, opp; simpl.\n    LpRRVq_simpl.\n    now rewrite LpRRVminus_plus.\n  Qed.\n\n  Lemma lim_ball_center_dist (x y : LpRRV prts p)\n             (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n             (PF:ProperFilter F)\n             (cF:cauchy F)\n             (N:nat) :\n    (proj1_sig (LpRRV_lim_ball_center F PF cF N)) x ->\n    (proj1_sig (LpRRV_lim_ball_center F PF cF N)) y ->\n    LpRRVnorm prts (LpRRVminus prts x y) < 2 / 2 ^ N.\n  Proof.\n    unfold LpRRV_lim_ball_center; simpl.\n    unfold proj1_sig.\n    match_case; intros.\n    match_destr_in H.\n    invcs H.\n    unfold Hierarchy.ball in *; simpl in *.\n    unfold ball in *; simpl in *.\n    generalize (Rplus_lt_compat _ _ _ _ H0 H1)\n    ; intros HH.\n    field_simplify in HH.\n    - eapply Rle_lt_trans; try eapply HH.\n      generalize (LpRRV_norm_plus prts pbig (LpRRVminus prts (p:=bignneg _ pbig) x x1) (LpRRVminus prts x1 y)); intros HH2.\n      repeat rewrite LpRRVminus_plus in HH2.\n      repeat rewrite LpRRVminus_plus.\n      assert (eqq:LpRRV_seq (LpRRVplus prts (LpRRVplus prts x (LpRRVopp prts x1))\n                                   (LpRRVplus prts x1 (LpRRVopp prts y)))\n                            ((LpRRVplus prts x (LpRRVopp prts y)))).\n      {\n        intros ?; simpl.\n        rv_unfold; lra.\n      }\n      generalize (LpRRV_norm_opp (LpRRVplus prts x (LpRRVopp prts x1)))\n      ; intros eqq3.\n      subst pnneg.\n      rewrite <- eqq.\n      eapply Rle_trans; try eapply HH2.\n      apply Rplus_le_compat_r.\n      simpl in *.\n      rewrite <- eqq3.\n      right.\n      apply LpRRV_norm_sproper.\n      intros ?; simpl.\n      rv_unfold; lra.\n    - revert HH.\n      apply pow_nzero.\n      lra.\n  Qed.\n  \n  Lemma lim_filter_cauchy \n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    forall N : nat,\n      forall n m : nat,\n        (n >= N)%nat ->\n        (m >= N)%nat -> \n        LpRRVnorm prts (LpRRVminus \n                            prts  \n                            (LpRRV_lim_picker F PF cF n)\n                            (LpRRV_lim_picker F PF cF m)) < 2 / 2 ^ N.\n  Proof.\n    intros.\n    apply (lim_ball_center_dist _ _ F PF cF); now apply lim_picker_included.\n  Qed.    \n    \n  Lemma cauchy_filter_sum_bound \n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) (pbigger:1 < p):\n    ex_series (fun n => \n                 LpRRVnorm prts \n                             (LpRRVminus prts\n                                (LpRRV_lim_picker F PF cF (S n))\n                                (LpRRV_lim_picker F PF cF n))).\n  Proof.\n    apply (@ex_series_le R_AbsRing R_CompleteNormedModule) with\n        (b := fun n => 2 / 2 ^ n).\n    intros; unfold norm; simpl.\n    unfold abs; simpl.\n    rewrite Rabs_pos_eq.\n    left.\n    apply (lim_filter_cauchy F PF cF n (S n) n); try lia.\n    unfold LpRRVnorm.\n    apply power_nonneg.\n    unfold Rdiv.\n    apply (@ex_series_scal_l R_AbsRing R_CompleteNormedModule).\n    apply ex_series_ext with (a := fun n => (/ 2) ^ n).\n    - intros.\n      intros; rewrite Rinv_pow; lra.\n    - apply ex_series_geom.\n      rewrite Rabs_Rinv by lra.\n      rewrite Rabs_pos_eq; try lra.\n Qed.\n  \n  Lemma series_sum_le (f : nat -> R) (x: R) :\n    is_series f x ->\n    (forall n, 0 <= f n) ->\n    forall n, sum_n f n <= x.\n  Proof.\n    intros.\n    rewrite <- series_is_lim_seq in H.\n    apply is_lim_seq_incr_compare; trivial.\n    intros.\n    rewrite sum_Sn.\n    now apply Rplus_le_pos_l.\n  Qed.    \n\n  Lemma islp_Rbar_lim_telescope_abs_gen (f : nat -> LpRRV prts p) :\n    ex_series (fun n => \n                 LpRRVnorm prts \n                           (LpRRVminus prts (f (S n)) (f n))) ->\n    (forall (n:nat), RandomVariable dom borel_sa (f n)) ->\n    IsLp_Rbar prts p\n              (Rbar_rvlim\n                 (fun n => LpRRV_rv_X _ (LpRRVsum \n                                      prts pbig\n                                      (fun n0 => LpRRVabs prts (LpRRVminus prts (f (S n0)) \n                                                                        (f n0))) n))).\n  Proof.\n    intros.\n    apply ex_series_ext with (b := fun n : nat => LpRRVnorm prts (LpRRVabs prts (LpRRVminus prts (f (S n)) (f n))))\n      in H.\n    - unfold ex_series in H.\n      destruct H.\n      apply islp_Rbar_rvlim_bounded with (c := x); try lra.\n      + intros.\n        eapply Rle_trans.\n        apply LpRRV_norm_sum.\n        apply series_sum_le; trivial.\n        intros.\n        unfold LpRRVnorm.\n        apply power_nonneg.\n      + intros.\n        typeclasses eauto.\n      + intros.\n        apply LpRRVsum_pos.\n        typeclasses eauto.\n      + intros n xx.\n        unfold LpRRVsum, pack_LpRRV; simpl.\n        unfold rvsum.\n        rewrite sum_Sn.\n        apply Rplus_le_compat1_l.\n        unfold rvabs.\n        apply Rabs_pos.\n    - intros.\n      now rewrite norm_abs.\n  Qed.\n\n  Lemma cauchy_filter_sum_abs\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    IsLp_Rbar \n      prts p\n      (Rbar_rvlim\n         (fun n0 =>\n            LpRRV_rv_X _ \n                       (LpRRVsum prts pbig \n                                 (fun n =>\n                                    (LpRRVabs prts\n                                              (LpRRVminus prts\n                                                          (LpRRV_lim_picker F PF cF (S (S n)))\n                                                          (LpRRV_lim_picker F PF cF (S n))))) n0))).\n  Proof.\n    apply (islp_Rbar_lim_telescope_abs prts pbig\n                                       (fun n => LpRRV_lim_picker F PF cF (S n)))\n    ; [ | typeclasses eauto ]; intros.\n    generalize (lim_filter_cauchy F PF cF (S n) (S (S n)) (S n)); intros.\n    simpl.\n    cut_to H; try lia.\n    simpl in H.\n    unfold Rdiv in H.\n    rewrite Rinv_mult_distr in H; try lra; [|apply pow_nzero; lra].\n    rewrite <- Rmult_assoc in H.\n    rewrite Rinv_r in H; try lra.\n    rewrite Rmult_1_l in H.\n    apply H.\n  Qed.\n\n  Lemma cauchy_filter_sum_abs_ext0\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    IsLp_Rbar \n      prts p\n      (Rbar_rvlim\n         (fun n0 =>\n            LpRRV_rv_X _ (LpRRVsum prts pbig \n                     (fun n =>\n                        (LpRRVabs prts\n                                  (LpRRVminus prts\n                                              (LpRRV_lim_picker_ext0 F PF cF (S n))\n                                              (LpRRV_lim_picker_ext0 F PF cF n)))) n0))).\n  Proof.\n    apply  islp_Rbar_lim_telescope_abs_gen\n    ; [ | typeclasses eauto ]; intros.\n\n    apply (@ex_series_le R_AbsRing R_CompleteNormedModule) with\n        (b := fun n => match n with \n                       | 0 => LpRRVnorm prts (LpRRV_lim_picker_ext0 F PF cF 1)\n                       | S n' => 2 / (pow 2 n')\n                       end).\n\n    - intros; unfold norm; simpl.\n      unfold abs; simpl.\n      rewrite Rabs_pos_eq.\n      match_destr.\n      + simpl.\n        unfold LpRRVminus, LpRRVzero.\n        unfold pack_LpRRV, LpRRVconst.\n        unfold rvminus, rvplus, rvopp, rvscale, const; simpl.\n        right.\n        apply LpRRV_norm_sproper.\n        intro z.\n        simpl.\n        ring.\n      + left.\n        simpl.\n        apply (lim_filter_cauchy F PF cF n (S (S n)) (S n)); try lia.\n      + unfold LpRRVnorm.\n        apply power_nonneg.\n    - rewrite ex_series_incr_1.\n      unfold Rdiv.\n      apply (@ex_series_scal_l R_AbsRing R_CompleteNormedModule).\n      apply ex_series_ext with (a := fun n => (/ 2)^n).\n      intros; now rewrite Rinv_pow.\n      apply ex_series_geom.\n      rewrite Rabs_pos_eq; lra.\n Qed.\n\n  Lemma cauchy_filter_sum\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    IsLp_Rbar prts p \n         (Rbar_rvlim\n            (rvsum\n               (fun n =>\n                  (LpRRVminus prts\n                              (LpRRV_lim_picker F PF cF (S (S n)))\n                              (LpRRV_lim_picker F PF cF (S n)))))).\n  Proof.\n    generalize (cauchy_filter_sum_abs F PF cF).\n    unfold IsLp_Rbar; intros.\n    unfold LpRRVnorm in H.\n    eapply (is_finite_Rbar_NonnegExpectation_le _ _ _ H).\n    Unshelve.\n    intro x.\n    unfold Rbar_rvlim.\n    apply Rbar_power_le with (p := p); [simpl; lra | apply Rbar_abs_nneg | ].\n    simpl.\n    repeat rewrite Elim_seq_fin.\n    apply Rbar_Rabs_lim_sum_le.\n  Qed.\n\n  Lemma cauchy_filter_sum_ext0\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    IsLp_Rbar prts p\n         (Rbar_rvlim\n            (rvsum\n               (fun n =>\n                  (LpRRVminus prts\n                              (LpRRV_lim_picker_ext0 F PF cF (S n))\n                              (LpRRV_lim_picker_ext0 F PF cF n))))).\n  Proof.\n    generalize (cauchy_filter_sum_abs_ext0 F PF cF).\n    unfold IsLp_Rbar; intros.\n    unfold LpRRVnorm in H.\n    eapply (is_finite_Rbar_NonnegExpectation_le _ _ _ H).\n    Unshelve.\n    intro x.\n    unfold Rbar_rvlim.\n    apply Rbar_power_le with (p := p); [simpl; lra | apply Rbar_abs_nneg | ].\n    simpl.\n    repeat rewrite Elim_seq_fin.\n    apply Rbar_Rabs_lim_sum_le.\n  Qed.\n\n  Lemma LpRRVsum_telescope0\n        (f: nat -> LpRRV prts p) : \n    forall n0,\n      LpRRV_seq (LpRRVsum prts pbig\n                (fun n => (LpRRVminus prts (f (S n)) (f n))) \n                n0)\n      (LpRRVminus prts (f (S n0)) (f 0%nat)).\n   Proof.\n     intros; induction n0.\n     - intros x; simpl.\n       unfold rvsum.\n       now rewrite sum_O.\n     - simpl in *.\n       intros x; simpl.\n       specialize (IHn0 x).\n       simpl in *.\n       unfold rvsum in *.\n       rewrite sum_Sn.\n       rewrite IHn0.\n       rv_unfold.\n       unfold plus; simpl.\n       lra.\n   Qed.\n\n   Lemma LpRRVsum_telescope\n        (f: nat -> LpRRV prts p) : \n     forall n0,\n      LpRRV_seq (LpRRVplus prts (f 0%nat)\n                 (LpRRVsum prts pbig\n                           (fun n => (LpRRVminus prts (f (S n)) (f n))) \n                           n0))\n                 (f (S n0)).\n     Proof.\n       intros.\n       rewrite LpRRVsum_telescope0.\n       rewrite LpRRVminus_plus.\n       intros ?; simpl.\n       rv_unfold; lra.\n     Qed.\n\n  Lemma cauchy_filter_sum_telescope\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    forall n0, \n      LpRRV_seq (LpRRVplus \n                   prts\n                   (LpRRV_lim_picker F PF cF (S 0%nat))\n                   (LpRRVsum prts pbig \n                             (fun n =>\n                                (LpRRVminus prts\n                                            (LpRRV_lim_picker F PF cF (S (S n)))\n                                            (LpRRV_lim_picker F PF cF (S n)))) n0))\n                (LpRRV_lim_picker F PF cF (S (S n0))).\n  Proof.\n    intros.\n    apply (LpRRVsum_telescope \n             (fun n =>\n                LpRRV_lim_picker F PF cF (S n))).\n  Qed.\n\n  Lemma cauchy_filter_Rbar_lim\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    IsLp_Rbar prts p\n         (Rbar_rvlim\n            (fun n => LpRRV_rv_X _ (LpRRVminus prts\n                        (LpRRV_lim_picker F PF cF (S (S n)))\n                        (LpRRV_lim_picker F PF cF (S 0%nat)))\n                        \n         )).\n  Proof.\n   apply (IsLp_Rbar_proper prts p) with\n       (x :=  \n             (Rbar_rvlim\n               (fun n0 =>\n                  LpRRV_rv_X _ (LpRRVsum prts pbig \n                           (fun n =>\n                              (LpRRVminus prts\n                                          (LpRRV_lim_picker F PF cF (S (S n)))\n                                          (LpRRV_lim_picker F PF cF (S n))))\n                           n0)))); trivial.\n   intro z.\n   unfold Rbar_rvlim.\n   apply ELim_seq_ext.\n   intros.\n   f_equal.\n   apply (LpRRVsum_telescope0 (fun n => (LpRRV_lim_picker F PF cF (S n)))).\n   apply cauchy_filter_sum.\n  Qed.\n\n   Lemma cauchy_filter_Rbar_lim_ext0\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    IsLp_Rbar prts p\n         (Rbar_rvlim\n            (fun n => LpRRV_rv_X _ (LpRRVminus prts\n                        (LpRRV_lim_picker_ext0 F PF cF (S n))\n                        (LpRRV_lim_picker_ext0 F PF cF 0%nat)))\n                        \n         ).\n  Proof.\n   apply (IsLp_Rbar_proper prts p) with\n       (x :=  \n             (Rbar_rvlim\n               (fun n0 =>\n                  LpRRV_rv_X _ (LpRRVsum prts pbig \n                           (fun n =>\n                              (LpRRVminus prts\n                                          (LpRRV_lim_picker_ext0 F PF cF (S n))\n                                          (LpRRV_lim_picker_ext0 F PF cF n)))\n                           n0)))); trivial.\n   intro z.\n   unfold Rbar_rvlim.\n   apply ELim_seq_ext.\n   intros.\n   f_equal.\n   apply (LpRRVsum_telescope0 (fun n => (LpRRV_lim_picker_ext0 F PF cF n))).\n   apply  cauchy_filter_sum_ext0.\n  Qed.\n\n  Lemma IsLp_IsLp_Rbar (f : LpRRV prts p) :\n    IsLp_Rbar prts p (LpRRV_rv_X prts f).\n  Proof.\n    unfold IsLp_Rbar.\n    unfold IsLp, IsLp_Rbar; intros.\n    generalize (LpRRV_LpS_FiniteLp prts f); intros.\n    unfold IsFiniteExpectation in H.\n    generalize (rvpower_nnf (rvabs f) (const p)); intros.\n    rewrite Expectation_pos_pofrf with (nnf := H0) in H.\n    match_case_in H; intros.\n    - rewrite NNExpectation_Rbar_NNExpectation in H1.\n      unfold rvpower, rvabs, const in H1.\n      unfold Rbar_power, Rbar_abs.\n      erewrite Rbar_NonnegExpectation_pf_irrel.\n      erewrite Rbar_NonnegExpectation_pf_irrel in H1.      \n      now rewrite H1.\n    - now rewrite H1 in H.\n    - generalize (NonnegExpectation_pos (rvpower (rvabs f) (const p))); intros.\n      rewrite H1 in H2.\n      now simpl in H2.\n   Qed.\n\n  Lemma IsLp_Rbar_IsLp (f : Ts -> R) :\n    IsLp_Rbar prts p f ->\n    IsLp prts p f.\n  Proof.\n    unfold IsLp, IsLp_Rbar; intros.\n    unfold IsFiniteExpectation.\n    generalize (rvpower_nnf (rvabs f) (const p)); intros.\n    rewrite Expectation_pos_pofrf with (nnf := H0).\n    rewrite NNExpectation_Rbar_NNExpectation.\n    unfold Rbar_power, Rbar_abs in H.\n    unfold rvpower, rvabs, const.\n    erewrite Rbar_NonnegExpectation_pf_irrel.\n    erewrite Rbar_NonnegExpectation_pf_irrel in H.\n    now rewrite <- H.\n  Qed.\n\n  Lemma cauchy_filter_Rbar_rvlim1\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    IsLp_Rbar prts p\n              (Rbar_rvlim (fun n => (LpRRV_rv_X _ (LpRRV_lim_picker F PF cF (S n))))).\n   Proof.\n     generalize (cauchy_filter_Rbar_lim_ext0 F PF cF); intros.\n     unfold LpRRV_lim_picker_ext0 in H.\n     eapply IsLp_Rbar_proper; trivial.\n     shelve.\n     apply H.\n     Unshelve.\n     intro x.\n     unfold Rbar_rvlim.\n     apply ELim_seq_ext.\n     intros.\n     f_equal.\n     unfold LpRRVzero, LpRRVconst, const.\n     unfold pack_LpRRV; simpl.\n     unfold rvminus, rvplus, rvopp, rvscale.\n     ring.\n   Qed.\n\n  Instance nnf_0 :\n    (@Rbar_NonnegativeFunction Ts (fun x => const 0 x)).\n  Proof.\n    unfold Rbar_NonnegativeFunction.\n    intros.\n    simpl.\n    unfold const.\n    lra.\n  Qed.\n\n  Lemma Rbar_IsLp_bounded n (rv_X1 rv_X2 : Ts -> Rbar)\n        (rle:Rbar_rv_le (fun (omega : Ts) => Rbar_power (Rbar_abs (rv_X1 omega)) n) rv_X2)\n        {islp:Rbar_IsFiniteExpectation prts rv_X2}\n    :\n      IsLp_Rbar prts n rv_X1.\n  Proof.\n    unfold IsLp_Rbar.\n    assert (Rbar_IsFiniteExpectation prts (fun x => const 0 x)).\n    {\n      generalize (Rbar_Expectation_pos_pofrf (fun x => Finite (const 0 x))); intros.\n      unfold Rbar_IsFiniteExpectation.\n      rewrite H.\n      assert (0 <= 0) by lra.\n      generalize (Rbar_NonnegExpectation_const 0 H0); intros.\n      rewrite Rbar_NonnegExpectation_pf_irrel with (nnf2 := nnf_0) in H1.\n      now rewrite H1.\n    }\n    generalize (Rbar_IsFiniteExpectation_bounded prts (const 0)\n                                                 (fun (omega : Ts) => Rbar_power (Rbar_abs (rv_X1 omega)) n) rv_X2); intros.\n    cut_to H0; trivial.\n    - unfold Rbar_IsFiniteExpectation in H0.\n      rewrite Rbar_Expectation_pos_pofrf with (nnf := power_abs_pos rv_X1 n) in H0.\n      match_destr_in H0; easy.\n    - intro x.\n      unfold const.\n      apply Rbar_power_nonneg.\n  Qed.\n\n  Instance Rbar_power_pos m (rv_X: Ts -> Rbar) :\n    Rbar_NonnegativeFunction \n      (fun omega => Rbar_power (rv_X omega) m).\n  Proof.\n    intro x.\n    apply Rbar_power_nonneg.\n  Qed.\n\n  Lemma IsLp_Rbar_down_le m n (rv_X:Ts->Rbar)\n        {rrv:RandomVariable dom Rbar_borel_sa rv_X}\n        (pfle:0 <= n <= m)\n        {lp:IsLp_Rbar prts m rv_X} : IsLp_Rbar prts n rv_X.\n  Proof.\n    apply Rbar_IsLp_bounded with (rv_X2 := fun omega => Rbar_max 1 (Rbar_power (Rbar_abs (rv_X omega)) m)).\n    - intros a.\n      case_eq (rv_X a); intros.\n      + unfold Rbar_abs, Rbar_power.\n        replace (Rbar_max 1 (power (Rabs r) m)) with (Finite (Rmax 1 (power (Rabs r) m))).\n        unfold Rbar_le.\n        destruct (Rle_lt_dec 1 (Rabs r)).\n        * eapply Rle_trans; [| eapply Rmax_r].\n          now apply Rle_power.\n        * eapply Rle_trans; [| eapply Rmax_l].\n          unfold power.\n          match_destr; [lra | ].\n          generalize (Rabs_pos r); intros.\n          destruct (Req_EM_T n 0).\n          -- subst.\n             rewrite Rpower_O; lra.\n          -- assert (eqq:1 = Rpower 1 n).\n             {\n               unfold Rpower.\n               rewrite ln_1.\n               rewrite Rmult_0_r.\n               now rewrite exp_0.\n             }\n             rewrite eqq.\n             apply Rle_Rpower_l; lra.\n        * unfold Rbar_max.\n          match_case; intros.\n          -- simpl in r0.\n             now rewrite Rmax_right.\n          -- simpl in n0.\n             rewrite Rmax_left; trivial.\n             left; lra.\n      + simpl.\n        unfold Rbar_max.\n        case_eq (Rbar_le_dec 1 p_infty); intros; trivial.\n        now simpl in n0.\n      + simpl.\n        unfold Rbar_max.\n        case_eq (Rbar_le_dec 1 p_infty); intros; trivial.\n        now simpl in n0.\n    - assert (Rbar_NonnegativeFunction \n                 (fun omega : Ts => Rbar_max 1 (Rbar_power (Rbar_abs (rv_X omega)) m))).\n      {\n        intro x.\n        unfold Rbar_max.\n        match_destr.\n        - apply Rbar_power_nonneg.\n        - simpl; lra.\n      }\n      unfold Rbar_IsFiniteExpectation.\n      rewrite Rbar_Expectation_pos_pofrf with (nnf := H).\n      unfold IsLp_Rbar in lp.\n      assert (0 <= 1) by lra.\n\n      assert (rv1: RandomVariable dom Rbar_borel_sa \n                                  (fun omega => (Rbar_power (Rbar_abs (rv_X omega)) m))).\n      {\n        apply Rbar_measurable_rv.\n        apply Rbar_power_measurable.\n        apply Rbar_Rabs_measurable.\n        now apply rv_Rbar_measurable.\n      }\n      generalize (@Rbar_NonnegExpectation_plus Ts dom prts\n                    (const (Finite 1))\n                    (fun omega => (Rbar_power (Rbar_abs (rv_X omega)) m))\n                    _ _ (nnfconst _ H0) _ ); intros.\n      assert (is_finite\n                 (@Rbar_NonnegExpectation Ts dom prts\n            (Rbar_rvplus (@const Rbar Ts (Finite (IZR (Zpos xH))))\n               (fun omega : Ts => Rbar_power (Rbar_abs (rv_X omega)) m))\n            (@pos_Rbar_plus Ts \n                            (@const Rbar Ts (Finite (IZR (Zpos xH))))\n                            (fun omega : Ts => Rbar_power (Rbar_abs (rv_X omega)) m)\n                            (nnfconst _ H0)\n                            (Rbar_power_pos m (fun omega : Ts => Rbar_abs (rv_X omega))) ))).\n      {\n        rewrite H1.\n        assert (is_finite (@Rbar_NonnegExpectation Ts dom prts (@const Rbar Ts (Finite 1))  (nnfconst _ H0))).\n        - generalize (Rbar_NonnegExpectation_const _ H0); intros.\n          unfold const in H2.\n          unfold const.\n          rewrite H2.\n          now simpl.\n        - rewrite <- H2.\n          rewrite <- lp.\n          now simpl.\n      } \n      assert (Rbar_rv_le\n                (fun omega : Ts => Rbar_max 1 (Rbar_power (Rbar_abs (rv_X omega)) m))\n                (Rbar_rvplus (const (Finite 1))\n                             (fun omega => Rbar_power (Rbar_abs (rv_X omega)) m))).\n      {\n        intro x.\n        unfold Rbar_rvplus, const, Rbar_max.\n        match_destr.\n        - replace (Rbar_power (Rbar_abs (rv_X x)) m) with\n              (Rbar_plus (Finite 0) (Rbar_power (Rbar_abs (rv_X x)) m)) at 1.\n          + apply Rbar_plus_le_compat.\n            * simpl; lra.\n            * apply Rbar_le_refl.\n          + apply Rbar_plus_0_l.\n        - replace (Finite 1) with (Rbar_plus (Finite 1) (Finite 0)) at 1.\n          + apply Rbar_plus_le_compat.\n            * apply Rbar_le_refl.\n            * apply Rbar_power_nonneg.\n          + simpl.\n            apply Rbar_finite_eq.\n            lra.\n      }\n      generalize (is_finite_Rbar_NonnegExpectation_le _ _ H3 H2); intros.\n      now rewrite <- H4.\n   Qed.\n\n  Lemma IsL1_Rbar_abs_Finite (rv_X:Ts->Rbar)\n        {lp:IsLp_Rbar prts 1 rv_X} : is_finite (Rbar_NonnegExpectation (Rbar_rvabs rv_X)).\n  Proof.\n    red in lp.\n    assert (rv_eq (fun omega => Rbar_power (Rbar_abs (rv_X omega)) 1)\n                  (Rbar_rvabs rv_X)).\n    - intro x.\n      unfold Rbar_power, Rbar_rvabs.      \n      destruct (rv_X x); simpl; trivial.\n      unfold power.\n      match_destr.\n      + generalize (Rabs_pos r); intros.\n        apply Rbar_finite_eq.\n        lra.\n      + rewrite Rpower_1; trivial.\n        apply Rabs_pos_lt.\n        unfold Rabs in n.\n        match_destr_in n; lra.\n    - now rewrite (Rbar_NonnegExpectation_ext _ _ H) in lp.\n    Qed.\n\n  Lemma IsL1_Rbar_Finite (rv_X:Ts->Rbar)\n        {rv:RandomVariable dom Rbar_borel_sa rv_X}\n        {lp:IsLp_Rbar prts 1 rv_X} : Rbar_IsFiniteExpectation prts rv_X.\n  Proof.\n    apply finiteExp_Rbar_rvabs; trivial.\n    now apply IsL1_Rbar_abs_Finite.\n  Qed.\n\n  Lemma Rbar_IsLp_IsFiniteExpectation (f : Ts -> Rbar) (n : R)\n        {rrv:RandomVariable dom Rbar_borel_sa f} :\n    1 <= n ->\n    IsLp_Rbar prts n f -> Rbar_IsFiniteExpectation prts f.\n  Proof.\n    intros.\n    apply IsL1_Rbar_Finite; trivial.\n    apply (IsLp_Rbar_down_le n 1 f); trivial.\n    lra.\n  Qed.\n\n  Lemma Rbar_IsLp_almostR2_finite (f : Ts -> Rbar) (n : R)\n        {rrv:RandomVariable dom Rbar_borel_sa f} :\n    1 <= n ->\n    IsLp_Rbar prts n f ->\n    ps_P (exist (sa_sigma _) _ (sa_finite_Rbar f rrv)) = 1.    \n  Proof.\n    intros.\n    apply Rbar_IsLp_IsFiniteExpectation in H0; trivial.\n    now apply finite_Rbar_Expectation_almostR2_finite.\n  Qed.\n\n  Instance picker_rv\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) \n        (n : nat) :\n    RandomVariable dom borel_sa (LpRRV_rv_X prts (LpRRV_lim_picker F PF cF n)).\n  Proof.\n    exact (LpRRV_rv prts (LpRRV_lim_picker F PF cF n)).\n  Qed.\n\n  Lemma Rbar_lim_seq_pos_rv\n        (f : nat -> Ts -> Rbar) :\n    (forall n, RandomVariable dom Rbar_borel_sa (f n)) ->\n    (forall n, Rbar_NonnegativeFunction (f n)) ->\n    RandomVariable dom Rbar_borel_sa (fun omega => ELim_seq (fun n => f n omega)).\n  Proof.\n    intros.\n    unfold RandomVariable.\n    apply Rbar_borel_sa_preimage2.    \n    intros.\n    apply Rbar_lim_seq_measurable_pos; trivial.\n    intros.\n    unfold RbarMeasurable.\n    apply Rbar_borel_sa_preimage2.        \n    apply H.\n  Qed.\n    \n   Lemma cauchy_filter_sum_abs_finite00\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n     almost prts (fun x =>\n          is_finite (ELim_seq \n                       (fun n0 =>\n                          LpRRVsum prts pbig \n                                   (fun n =>\n                                      (LpRRVabs prts\n                                                (LpRRVminus prts\n                                                            (LpRRV_lim_picker F PF cF (S (S n)))\n                                                            (LpRRV_lim_picker F PF cF (S n))))) n0 x))).\n   Proof.\n    generalize (cauchy_filter_sum_abs F PF cF); intros.\n    pose (limpick :=\n             (Rbar_rvlim\n           (fun n0 : nat =>\n            LpRRV_rv_X _ (LpRRVsum prts pbig\n              (fun n : nat =>\n               LpRRVabs prts\n                 (LpRRVminus prts (LpRRV_lim_picker F PF cF (S (S n)))\n                    (LpRRV_lim_picker F PF cF (S n)))) n0)))).\n    assert (rv:RandomVariable dom Rbar_borel_sa limpick).\n    {\n      subst limpick.\n      unfold Rbar_rvlim.\n      apply Rbar_lim_seq_pos_rv.\n      - intros.\n        apply borel_Rbar_borel.\n        apply LpRRV_rv.\n      - intros.\n        apply positive_Rbar_positive.\n        apply LpRRVsum_pos.\n        intros.\n        unfold LpRRVabs, pack_LpRRV;simpl.\n        apply nnfabs.\n    }\n    exists (exist _ _ (sa_finite_Rbar limpick rv)).\n    split.\n    - subst limpick.\n      apply Rbar_IsLp_almostR2_finite with (n := p); trivial.\n    - intros.\n      apply H0.\n  Qed.\n\n   Lemma cauchy_filter_sum_abs_ext0_finite00\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    almost prts (fun x =>\n          is_finite (ELim_seq \n                       (fun n0 =>\n                          LpRRVsum prts pbig \n                                   (fun n =>\n                                      (LpRRVabs prts\n                                                (LpRRVminus prts\n                                                            (LpRRV_lim_picker_ext0 F PF cF (S n))\n                                                            (LpRRV_lim_picker_ext0 F PF cF n)))) n0 x))).\n   Proof.\n    generalize (cauchy_filter_sum_abs_ext0 F PF cF); intros.\n    pose (limpick :=\n             (Rbar_rvlim\n           (fun n0 : nat =>\n            LpRRV_rv_X _ (LpRRVsum prts pbig\n              (fun n : nat =>\n               LpRRVabs prts\n                 (LpRRVminus prts (LpRRV_lim_picker_ext0 F PF cF (S n))\n                    (LpRRV_lim_picker_ext0 F PF cF n))) n0)))).\n    assert (rv:RandomVariable dom Rbar_borel_sa limpick).\n    {\n      subst limpick.\n      unfold Rbar_rvlim.\n      apply Rbar_lim_seq_pos_rv.\n      - intros.\n        apply borel_Rbar_borel.\n        apply LpRRV_rv.\n      - intros.\n        apply positive_Rbar_positive.\n        apply LpRRVsum_pos.\n        intros.\n        unfold LpRRVabs, pack_LpRRV;simpl.\n        apply nnfabs.\n    }\n    exists (exist _ _ (sa_finite_Rbar limpick rv)).\n    split.\n    - subst limpick.\n      apply Rbar_IsLp_almostR2_finite with (n := p); trivial.\n    - intros.\n      apply H0.\n  Qed.\n\n  Lemma cauchy_filter_sum_finite00\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    almost prts (fun x =>\n          ex_finite_lim_seq\n            (fun n0 =>\n               LpRRVsum prts pbig \n                        (fun n =>\n                           (LpRRVminus prts\n                                       (LpRRV_lim_picker F PF cF (S (S n)))\n                                       (LpRRV_lim_picker F PF cF (S n)))) n0 x)).\n  Proof.\n    generalize (cauchy_filter_sum_abs_finite00 F PF cF); intros.\n    destruct H as [P [? ?]].\n    exists P; split; trivial.\n    intros.\n    specialize (H0 x H1).\n    unfold LpRRVsum, pack_LpRRV, rvsum; simpl.\n    unfold LpRRVsum, pack_LpRRV, rvsum in H0; simpl in H0.\n    unfold rvabs in H0.\n    rewrite Elim_seq_fin in H0.\n    now apply lim_sum_abs_bounded.\n Qed.\n\n  Lemma cauchy_filter_sum_ext0_finite00\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    almost prts (fun x =>\n          ex_finite_lim_seq\n            (fun n0 =>\n               LpRRVsum prts pbig \n                        (fun n =>\n                           (LpRRVminus prts\n                                       (LpRRV_lim_picker_ext0 F PF cF (S n))\n                                       (LpRRV_lim_picker_ext0 F PF cF n))) n0 x)).\n  Proof.\n    generalize (cauchy_filter_sum_abs_ext0_finite00 F PF cF); intros.\n    destruct H as [P [? ?]].\n    exists P; split; trivial.\n    intros.\n    specialize (H0 x H1).\n    unfold LpRRVsum, pack_LpRRV, rvsum; simpl.\n    unfold LpRRVsum, pack_LpRRV, rvsum in H0; simpl in H0.\n    unfold rvabs in H0.\n    rewrite Elim_seq_fin in H0.\n    now apply lim_sum_abs_bounded.\n Qed.\n    \n  Lemma cauchy_filter_rvlim_finite0\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    almost prts (fun x =>\n                   ex_finite_lim_seq (fun n => (LpRRV_lim_picker F PF cF (S (S n))) x)).\n  Proof.\n    generalize (cauchy_filter_sum_finite00 F PF cF); intros.\n    destruct H as [P [? ?]].\n    exists P; split; trivial.\n    intros.\n    specialize (H0 x H1).\n    rewrite ex_finite_lim_seq_ext in H0.\n    shelve.\n    intros.\n    generalize (LpRRVsum_telescope0 (fun n => LpRRV_lim_picker F PF cF (S n)) n); intros.\n    apply H2.\n    Unshelve.\n    unfold LpRRVminus, pack_LpRRV in H0; simpl in H0.\n    unfold rvminus, rvplus, rvopp, rvscale in H0.\n    unfold ex_finite_lim_seq in H0.\n    destruct H0 as [l ?].\n    unfold ex_finite_lim_seq.\n    exists (l + LpRRV_lim_picker F PF cF 1 x).\n    apply is_lim_seq_ext with\n        (u :=  fun n : nat =>\n                 (LpRRV_lim_picker F PF cF (S (S n)) x + -1 * LpRRV_lim_picker F PF cF 1 x)\n                   +\n                   (LpRRV_lim_picker F PF cF 1 x)); [(intros; lra) |].\n    apply is_lim_seq_plus'; trivial.\n    apply is_lim_seq_const.\n Qed.\n\n    Lemma cauchy_filter_rvlim_ext0_finite0\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    almost prts (fun x =>\n                   ex_finite_lim_seq (fun n => (LpRRV_lim_picker F PF cF (S n)) x)).\n  Proof.\n    generalize (cauchy_filter_sum_ext0_finite00 F PF cF); intros.\n    destruct H as [P [? ?]].\n    exists P; split; trivial.\n    intros.\n    specialize (H0 x H1).\n    rewrite ex_finite_lim_seq_ext in H0.\n    shelve.\n    intros.\n    generalize (LpRRVsum_telescope0 (fun n => LpRRV_lim_picker_ext0 F PF cF n) n); intros.\n    apply H2.\n    Unshelve.\n    unfold LpRRVminus, pack_LpRRV in H0; simpl in H0.\n    unfold rvminus, rvplus, rvopp, rvscale, const in H0.\n    rewrite ex_finite_lim_seq_ext in H0.\n    apply H0.\n    intros.\n    lra.\n Qed.\n\n    Lemma cauchy_filter_rvlim_Sext0_finite0\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    almost prts (fun x =>\n                   ex_finite_lim_seq (fun n => (LpRRV_lim_picker F PF cF n) x)).\n   Proof.\n     generalize (cauchy_filter_rvlim_ext0_finite0 F PF cF); intros.\n     destruct H as [P [? ?]].\n     exists P.\n     split; trivial; intros.\n     specialize (H0 x H1).\n     now apply ex_finite_lim_seq_S.\n   Qed.\n\n  Lemma cauchy_filter_rvlim_finite\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    exists (P: event dom),\n      exists (dec: forall x, {P x} + {~ P x}),\n        ps_P P = 1 /\\\n        (forall x,\n          ex_finite_lim_seq (fun n => (rvmult (EventIndicator dec)\n                                              (LpRRV_lim_picker F PF cF (S n)))\n                                        x) ) /\\\n        IsLp prts p\n             (rvlim (fun n => (rvmult (EventIndicator dec)\n                                      (LpRRV_lim_picker F PF cF (S n))))).\n  Proof.\n    generalize (cauchy_filter_rvlim_ext0_finite0 F PF cF); intros.\n    destruct H as [P [? ?]].\n    exists P.\n    assert (forall x: Ts, {P x} + {~ P x}).\n    {\n      intros.\n      apply ClassicalDescription.excluded_middle_informative.\n    }\n    exists X.\n    split; trivial.\n    split.\n    - intros.\n      destruct (X x).\n      + specialize (H0 x e).\n        unfold ex_finite_lim_seq.\n        unfold ex_finite_lim_seq in H0.\n        destruct H0.\n        exists x0.\n        eapply is_lim_seq_ext.\n        shelve.\n        apply H0.\n        Unshelve.\n        intros; simpl.\n        unfold rvmult, EventIndicator.\n        match_destr; try tauto; lra.\n      + unfold rvmult, EventIndicator, ex_finite_lim_seq.\n        exists 0.\n        apply is_lim_seq_ext with (u := (const 0)); [|apply is_lim_seq_const].\n        intros.\n        unfold const.\n        match_destr; try tauto; lra.\n    - generalize (cauchy_filter_Rbar_rvlim1 F PF cF); intros.\n      apply IsLp_Rbar_IsLp.\n      apply (IsLp_Rbar_proper_almostR2 prts _ (Rbar_rvlim (fun n : nat => LpRRV_rv_X _ (LpRRV_lim_picker F PF cF (S n)))))\n      ; try typeclasses eauto; trivial.\n      exists P. split; trivial; intros a Pa.\n      specialize (H0 _ Pa).\n      unfold Rbar_rvlim.\n      unfold rvlim.\n      unfold rvmult, EventIndicator.\n      destruct (X a); [| tauto].\n      rewrite Lim_seq_ext with (u := (fun n : nat => 1 * LpRRV_lim_picker F PF cF (S n) a))\n                               (v := (fun n : nat => LpRRV_lim_picker F PF cF (S n) a)); [|intros; lra].\n      rewrite ex_finite_lim_seq_correct in H0.\n      destruct H0.\n      rewrite Elim_seq_fin.\n      auto.\n  Qed.\n\n  Lemma cauchy_filter_rvlim_finite1\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    { P: event dom | \n         exists dec: forall x, {P x} + {~ P x},\n           ps_P P = 1 /\\\n           (forall x,\n               ex_finite_lim_seq (fun n => (rvmult (EventIndicator dec)\n                                                (LpRRV_lim_picker F PF cF (S n)))\n                                             x) ) /\\\n           IsLp prts p\n                (rvlim (fun n => (rvmult (EventIndicator dec)\n                                      (LpRRV_lim_picker F PF cF (S n)))))\n    }.\n  Proof.\n    apply constructive_indefinite_description.\n    apply cauchy_filter_rvlim_finite.\n  Qed.\n\n  Lemma cauchy_filter_rvlim_finite2\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F) :\n    { P: event dom &\n         {dec: forall x, {P x} + {~ P x} |\n           ps_P P = 1 /\\\n           (forall x,\n               ex_finite_lim_seq (fun n => (rvmult (EventIndicator dec)\n                                                   (LpRRV_lim_picker F PF cF (S n)))\n                                          x) ) /\\\n           IsLp prts p\n                (rvlim (fun n => (rvmult (EventIndicator dec)\n                                         (LpRRV_lim_picker F PF cF (S n)))))}\n    }.\n  Proof.\n    destruct (cauchy_filter_rvlim_finite1 F PF cF).\n    exists x.\n    apply constructive_indefinite_description.\n    apply e.\n  Qed.\n\n  Definition cauchy_rvlim_fun  (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n             (PF:ProperFilter F)\n             (cF:cauchy F) : Ts -> R\n    := match cauchy_filter_rvlim_finite2 F PF cF with\n       | existT P (exist dec PP) =>  (rvlim (fun n => (rvmult (EventIndicator dec)\n                                                              (LpRRV_lim_picker F PF cF (S n)))))\n       end.\n\n  Global Instance cauchy_rvlim_fun_isl2 (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n             (PF:ProperFilter F)\n             (cF:cauchy F) : IsLp prts p (cauchy_rvlim_fun F PF cF).\n  Proof.\n    unfold cauchy_rvlim_fun.\n    repeat match_destr.\n    tauto.\n  Qed.\n\n  Global Instance cauchy_rvlim_fun_rv (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n             (PF:ProperFilter F)\n             (cF:cauchy F) : RandomVariable dom borel_sa (cauchy_rvlim_fun F PF cF).\n  Proof.\n    unfold cauchy_rvlim_fun.\n    repeat match_destr.\n    apply rvlim_rv.\n    - typeclasses eauto.\n    - tauto.\n  Qed.\n  \n  Definition LpRRV_lim_with_conditions (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n             (PF:ProperFilter F)\n             (cF:cauchy F) : LpRRV prts p\n      := pack_LpRRV prts (cauchy_rvlim_fun F PF cF).\n\n  Definition LpRRV_lim (F : ((LpRRV prts p -> Prop) -> Prop)) : LpRRV prts p.\n  Proof.\n    destruct (excluded_middle_informative (ProperFilter F)).\n    - destruct (excluded_middle_informative (cauchy (T:= LpRRV_UniformSpace prts pbig) F)).\n      + exact (LpRRV_lim_with_conditions _ _ c).\n      + exact (LpRRVzero prts).\n    - exact (LpRRVzero prts).\n  Defined.\n  \n  Lemma Lim_seq_continuous (f : R -> R) (u : nat -> R) :\n    continuity_pt f (Lim_seq u) ->\n    ex_finite_lim_seq u ->\n    Lim_seq (fun n => f (u n)) = f (Lim_seq u).\n  Proof.\n    intros.\n    unfold ex_finite_lim_seq in H0.\n    destruct H0.\n    generalize (is_lim_seq_continuous f u x); intros.\n    generalize (is_lim_seq_unique _ _ H0); intros.\n    rewrite H2 in H.\n    specialize (H1 H H0).\n    apply is_lim_seq_unique in H1.\n    now rewrite H2.\n  Qed.\n\n  Lemma is_finite_Lim_seq_continuous (f : R -> R) (u : nat -> R) :\n    continuity_pt f (Lim_seq u) ->\n    ex_finite_lim_seq u ->\n    is_finite (Lim_seq (fun n => f (u n))).\n  Proof.\n    intros.\n    unfold ex_finite_lim_seq in H0.\n    destruct H0.\n    generalize (is_lim_seq_continuous f u x); intros.\n    generalize (is_lim_seq_unique _ _ H0); intros.\n    rewrite H2 in H.\n    specialize (H1 H H0).\n    apply is_lim_seq_unique in H1.\n    now rewrite H1.\n  Qed.\n\n  Lemma ex_lim_seq_continuous (f : R -> R) (u : nat -> R) :\n    continuity_pt f (Lim_seq u) ->\n    ex_finite_lim_seq u ->\n    ex_lim_seq (fun n => f (u n)).\n  Proof.\n    intros.\n    unfold ex_finite_lim_seq in H0.\n    destruct H0.\n    generalize (is_lim_seq_continuous f u x); intros.\n    generalize (is_lim_seq_unique _ _ H0); intros.\n    unfold ex_lim_seq.\n    exists (f x).\n    rewrite H2 in H.\n    now apply H1.\n  Qed.\n\n  Lemma lim_seq_lim_inf (f : nat -> R) :\n    ex_lim_seq f ->\n    Lim_seq f = LimInf_seq f.\n  Proof.\n    intros.\n    rewrite ex_lim_LimSup_LimInf_seq in H.\n    unfold Lim_seq.\n    rewrite H.\n    now rewrite x_plus_x_div_2.\n  Qed.\n\n  Lemma is_finite_LimInf_seq_continuous (f : R -> R) (u : nat -> R) :\n    continuity_pt f (Lim_seq u) ->\n    ex_finite_lim_seq u ->\n    is_finite (LimInf_seq (fun n => f (u n))).\n  Proof.\n    intros.\n    rewrite <- lim_seq_lim_inf.\n    apply is_finite_Lim_seq_continuous; trivial.\n    now apply ex_lim_seq_continuous.\n Qed.\n\n  Lemma LpRRVnorm_NonnegExpectation \n        (f : LpRRV prts p)\n        (rv : RandomVariable dom borel_sa f) :\n    LpRRVnorm prts f = power (NonnegExpectation (rvpower (rvabs f)  (const p))) (/ p).\n  Proof.\n    unfold LpRRVnorm.\n    f_equal.\n    now erewrite FiniteNonnegExpectation.\n  Qed.\n\n   Lemma rvpowerabs_rvminus_rvlim_comm (f : nat -> Ts -> R) (n:nat):\n     (forall x, ex_finite_lim_seq (fun n0 => f n0 x)) ->\n     (rv_eq\n        (rvpower (rvabs (rvminus (rvlim f) (f n))) (const p))\n        (rvlim (fun x => (rvpower (rvabs (rvminus (f x) (f n))) (const p))))).\n    Proof.\n      intros exfin z.\n      unfold rvpower, rvabs, rvminus, rvplus, rvopp, rvscale, rvlim, const.\n      pose (p_power_abs := fun x => @p_power p (Rabs x) ).\n      generalize (Lim_seq_ext \n                    (fun n0 : nat => power (Rabs (f n0 z + -1 * f n z)) p)\n                    (fun n0 => p_power_abs (f n0 z + -1 * f n z))); intros.\n      rewrite H.\n      - rewrite Lim_seq_continuous; trivial.\n        + unfold p_power_abs, p_power.\n          rewrite Lim_seq_plus, Lim_seq_const.\n          * specialize (exfin z).\n            rewrite ex_finite_lim_seq_correct in exfin.\n            destruct exfin.\n            rewrite <- H1.\n            now simpl.\n          * specialize (exfin z).\n            rewrite ex_finite_lim_seq_correct in exfin.\n            now destruct exfin.\n          * apply ex_lim_seq_const.\n          * specialize (exfin z).\n            rewrite ex_finite_lim_seq_correct in exfin.\n            destruct exfin.\n            rewrite <- H1.\n            rewrite Lim_seq_const.\n            now simpl.\n        + apply continuity_p_power_Rabs; lra.\n        + unfold ex_finite_lim_seq.\n          specialize (exfin z).\n          unfold ex_finite_lim_seq in exfin.\n          destruct exfin.\n          exists (x + -1 * f n z).\n          apply is_lim_seq_plus'; trivial.\n          apply is_lim_seq_const.\n      - intros.\n        now unfold p_power_abs.\n   Qed.\n\n    Lemma lt_Rbar_lt (x : Rbar) (y : R) :\n      0 < y ->\n      Rbar_lt x y -> (real x) < y.\n    Proof.\n      intros.\n      destruct x.\n      - now simpl in H.\n      - now simpl.\n      - now simpl.\n    Qed.\n\n    Lemma le_Rbar_le (x : Rbar) (y : R) :\n      0 <= y ->\n      Rbar_le x y -> (real x) <= y.\n    Proof.\n      intros.\n      destruct x.\n      - now simpl in H.\n      - now simpl.\n      - now simpl.\n    Qed.\n\n    Lemma LimInf_seq_ext (f g : nat -> R) :\n      eventually (fun n => f n = g n) ->\n      LimInf_seq f = LimInf_seq g.\n    Proof.\n      intros.\n      unfold eventually in H.\n      destruct H.\n      apply Rbar_le_antisym.\n      - apply LimInf_le.\n        exists x.\n        intros.\n        specialize (H n H0).\n        lra.\n      - apply LimInf_le.\n        exists x.\n        intros.\n        specialize (H n H0).\n        lra.\n    Qed.\n\n  Instance Rbar_real_rv \n           (f : Ts -> Rbar)\n           (rv : RandomVariable dom Rbar_borel_sa f) :\n    RandomVariable dom borel_sa (fun omega => real (f omega)).\n  Proof.\n    apply measurable_rv.\n    apply Rbar_real_measurable.\n    now apply rv_Rbar_measurable.\n  Qed.\n  \n  Lemma norm_rvminus_rvlim_le\n        (f : nat -> LpRRV prts p) \n        (rvl : RandomVariable dom borel_sa (rvlim f)) \n        (isl : IsLp prts p (rvlim f)) :\n    (forall x, ex_finite_lim_seq (fun n => f n x)) ->\n    (forall (eps:posreal),\n      exists (N : nat),\n        forall (n m : nat), \n          (n >= N)%nat ->\n          (m >= N)%nat ->\n          (LpRRVnorm prts (LpRRVminus prts (f m) (f n))) < eps) ->\n    forall (eps : posreal),\n      exists (N : nat),\n        forall (n : nat), \n          (n >= N)%nat ->\n          (LpRRVnorm prts (LpRRVminus prts (pack_LpRRV prts (rvlim f)) (f n))) <= eps. \n  Proof.\n    intros.\n    specialize (H0 eps).\n    destruct H0 as [N ?].\n    exists N.\n    intros.\n    unfold LpRRVnorm, LpRRVminus, pack_LpRRV; simpl.\n    replace (pos eps) with (power (power eps p) (/ p)) by (apply inv_power_cancel; [left; apply cond_pos| lra]).\n    apply Rle_power_l.\n    left; apply Rinv_0_lt_compat; lra.\n    split.\n    apply FiniteExpectation_pos; typeclasses eauto.\n    assert (1 <= 2) by lra.\n    generalize (rvpowerabs_rvminus_rvlim_comm f n H); intros.\n    rewrite (FiniteExpectation_ext_alt _ _ _ H3).\n    assert (rv_eq \n              (rvlim (fun x : nat => rvpower (rvabs (rvminus (f x) (f n))) (const p)))\n              (fun omega => LimInf_seq (fun x : nat => rvpower (rvabs (rvminus (f x) (f n))) (const p) omega))).\n    {\n      intros z.\n      unfold rvlim.\n      rewrite lim_seq_lim_inf; trivial.\n      pose (p_power_abs := fun x => @p_power p (Rabs x) ).      \n      unfold rvpower, rvabs, const, rvminus, rvplus, rvopp, rvscale.\n      apply ex_lim_seq_ext with (u := fun n0 => p_power_abs (f n0 z + -1 * f n z)).\n      intros.\n      now unfold p_power_abs, p_power.\n      specialize (H z).\n      unfold ex_finite_lim_seq in H.\n      destruct H.\n      unfold ex_lim_seq.\n      exists (p_power_abs (x + -1 * f n z)).\n      apply is_lim_seq_continuous.\n      apply continuity_p_power_Rabs; lra.\n      apply is_lim_seq_plus'; trivial.\n      apply is_lim_seq_const.\n    }\n    rewrite (FiniteExpectation_ext_alt _ _ _ H4).\n    unfold LpRRVnorm in H0.\n    erewrite FiniteNonnegExpectation.\n    apply le_Rbar_le.\n    rewrite <- (power0_Sbase p).\n    assert (0 < eps) by apply cond_pos.\n    apply Rle_power_l; lra.\n    assert (forall omega : Ts, is_finite (LimInf_seq (fun n0 : nat => rvpower (rvabs (rvminus (f n0) (f n))) (const p) omega))).\n    {\n      intros.\n      unfold rvpower, rvabs, rvminus, rvplus, rvopp, rvscale, rvlim, const.\n      pose (p_power_abs := fun x => @p_power p (Rabs x) ).\n      specialize (H omega).\n\n      generalize (LimInf_seq_ext \n                    (fun n0 : nat => power (Rabs (f n0 omega + -1 * f n omega)) p)\n                    (fun n0 => p_power_abs (f n0 omega + -1 * f n omega))); intros.\n      rewrite H5.\n      - apply is_finite_LimInf_seq_continuous.\n        + rewrite ex_finite_lim_seq_correct in H.\n          destruct H.\n          unfold p_power_abs, p_power.\n          rewrite Lim_seq_plus, Lim_seq_const; trivial.\n          * apply continuity_p_power_Rabs; lra.\n          * apply ex_lim_seq_const.\n          * rewrite Lim_seq_const.\n            rewrite <- H6.\n            now simpl.\n        + unfold ex_finite_lim_seq.\n          unfold ex_finite_lim_seq in H.\n          destruct H.\n          exists (x + -1 * f n omega).\n          apply is_lim_seq_plus'; trivial.\n          apply is_lim_seq_const.\n      - intros.\n        exists (0%nat); intros.\n        now unfold p_power_abs.\n    }\n    eapply Rbar_le_trans.\n    - apply Fatou; trivial.\n      + intros; typeclasses eauto.\n      + intros.\n        generalize (IsLp_minus prts pnneg (f n0) (f n)); intros.\n        unfold IsLp in H6.\n        unfold IsFiniteExpectation in H6.\n        erewrite Expectation_pos_pofrf in H6.\n        simpl in H6.\n        match_case_in H6; intros.\n        * rewrite H7; now simpl.\n        * now rewrite H7 in H6.\n        * now rewrite H7 in H6.\n      + eapply (RandomVariable_proper _ _ (reflexivity _) _ _ (reflexivity _)).\n        { intros ?.\n          rewrite <- ELimInf_seq_fin.\n          reflexivity.\n        }\n        apply borel_Rbar_borel.\n        generalize Rbar_lim_inf_rv.\n        intros.\n        typeclasses eauto.\n    - simpl.\n      unfold LpRRVnorm in H1.\n      simpl in H1.\n      assert (forall n0,\n                 (n0 >= N)%nat ->\n                 NonnegExpectation (fun omega : Ts => rvpower (rvabs (rvminus (f n0) (f n))) (const p) omega) <=\n                 (power eps p)).\n      {\n        intros.\n        specialize (H0 n n0 H1 H6).\n        generalize (Rle_power_l (power (FiniteExpectation prts (rvpower (rvabs (rvminus (f n0) (f n))) (const p))) (/ p) ) (pos eps) p); intros.\n        rewrite power_inv_cancel in H7.\n        erewrite FiniteNonnegExpectation in H7.\n        apply H7.\n        lra.\n        split; [apply power_nonneg |].\n        erewrite FiniteNonnegExpectation in H0.\n        left; apply H0.\n        apply FiniteExpectation_pos.\n        typeclasses eauto.\n        lra.\n      }\n      replace (Finite (power eps p)) with (LimInf_seq (fun _ => power eps p)) by apply LimInf_seq_const.\n      apply LimInf_le.\n      exists N; intros.\n      apply H6.\n      lia.\n  Qed.\n    \n  Lemma norm_rvminus_rvlim\n        (f : nat -> LpRRV prts p) \n        (rvl : RandomVariable dom borel_sa (rvlim f)) \n        (isl : IsLp prts p (rvlim f)) :\n    (forall x, ex_finite_lim_seq (fun n => f n x)) ->\n    (forall (eps:posreal),\n      exists (N : nat),\n        forall (n m : nat), \n          (n >= N)%nat ->\n          (m >= N)%nat ->\n          (LpRRVnorm prts (LpRRVminus prts (f m) (f n))) < eps) ->\n    forall (eps : posreal),\n      exists (N : nat),\n        forall (n : nat), \n          (n >= N)%nat ->\n          (LpRRVnorm prts (LpRRVminus prts (pack_LpRRV prts (rvlim f)) (f n))) < eps.\n  Proof.\n    intros.\n    assert (0 < eps) by apply cond_pos.\n    assert (0 < eps/2) by lra.\n    generalize (norm_rvminus_rvlim_le f rvl isl H H0 (mkposreal _ H2)); intros.\n    destruct H3 as [N ?].\n    exists N.\n    intros.\n    eapply Rle_lt_trans.\n    apply H3; trivial.\n    simpl; lra.\n  Qed.\n\n  End complete1.\n\n  Section complete2.\n        \n  Context {Ts:Type} \n          {dom: SigmaAlgebra Ts}\n          (prts: ProbSpace dom).\n\n  Context {p:R}.\n  Context (pbig:1 <= p).\n\n  Let pnneg : nonnegreal := bignneg p pbig.\n  Canonical pnneg.\n\n  Global Instance event_restricted_islp P n (pf1 : ps_P P = 1) pf \n           (f : Ts -> R) \n           (isl:  IsLp  prts n f):\n    IsLp (event_restricted_prob_space prts P pf) n (event_restricted_function P f).\n  Proof.\n    unfold IsLp, IsFiniteExpectation in *.\n    now rewrite (event_restricted_Expectation _ P pf1 pf) in isl.\n  Qed.\n\n  Program Definition event_restricted_LpRRV n P (pf1 : ps_P P = 1) pf (rv:LpRRV prts n) :\n    LpRRV (event_restricted_prob_space prts P pf) n\n    := {|\n    LpRRV_rv_X := event_restricted_function P (LpRRV_rv_X _ rv)\n      |} .\n  Next Obligation.\n    destruct rv.\n    now apply event_restricted_islp.\n  Qed.\n\n  Lemma restricted_LpRRVminus P (pf1 : ps_P P = 1) pf\n        (f g : LpRRV prts p) :\n    LpRRV_seq \n      (LpRRVminus (event_restricted_prob_space prts P pf)\n                  (event_restricted_LpRRV p P pf1 pf f)\n                  (event_restricted_LpRRV p P pf1 pf g))\n      (event_restricted_LpRRV p P pf1 pf (LpRRVminus prts f g)).\n  Proof.\n    easy.\n  Qed.\n\n  Lemma restricted_LpRRVnorm P (pf1 : ps_P P = 1) pf\n        (f : LpRRV prts p) :\n    LpRRVnorm prts f = LpRRVnorm (event_restricted_prob_space prts P pf)\n                                 (event_restricted_LpRRV p P pf1 pf f).\n  Proof.\n    intros.\n    unfold LpRRVnorm.\n    f_equal.\n    unfold FiniteExpectation.\n    simpl.\n    destruct (IsFiniteExpectation_Finite prts (rvpower (rvabs f) (const p))).\n    destruct (IsFiniteExpectation_Finite \n                (event_restricted_prob_space prts P pf)\n                (rvpower (rvabs (event_restricted_function P f)) (const p))).\n    simpl.\n    rewrite (event_restricted_Expectation _ P pf1 pf) in e.\n    assert (rv_eq\n              (event_restricted_function P (rvpower (rvabs f) (const p)))\n              (rvpower (rvabs (event_restricted_function P f)) (const p))) by easy.\n    rewrite (Expectation_ext H) in e.\n    rewrite e in e0.\n    now inversion e0.\n  Qed.\n\n  Lemma restricted_LpRRV_rvlim P (pf1 : ps_P P = 1) pf\n        (f : nat -> LpRRV prts p) \n        (rv : RandomVariable dom borel_sa (rvlim (fun x : nat => f x)))\n        (isl : IsLp prts p (rvlim (fun x : nat => f x)))\n        (rve : RandomVariable (event_restricted_sigma P) borel_sa\n         (rvlim (fun x : nat => event_restricted_LpRRV p P pf1 pf (f x)))) \n        (isle : IsLp (event_restricted_prob_space prts P pf) p\n         (rvlim (fun x : nat => event_restricted_LpRRV p P pf1 pf (f x)))) :\n    ps_P P = 1 ->\n    LpRRV_seq \n      (pack_LpRRV (event_restricted_prob_space prts P pf)\n                  (rvlim (fun x : nat => event_restricted_LpRRV p P pf1 pf (f x))))\n      (event_restricted_LpRRV p P pf1 pf\n                               (pack_LpRRV prts (rvlim (fun x : nat => f x)))).\n  Proof.\n    easy.\n  Qed.\n\n  Lemma norm_rvminus_rvlim_almostR2 \n        (f : nat -> LpRRV prts p) \n        (rvl : RandomVariable dom borel_sa (rvlim f)) \n        (isl : IsLp prts p (rvlim f))\n        (P : event dom) :\n    ps_P P = 1 ->\n    (forall x, P x -> ex_finite_lim_seq (fun n => f n x)) ->\n    (forall (eps:posreal),\n      exists (N : nat),\n        forall (n m : nat), \n          (n >= N)%nat ->\n          (m >= N)%nat ->\n          (LpRRVnorm prts (LpRRVminus prts (f m) (f n))) < eps) ->\n    forall (eps : posreal),\n      exists (N : nat),\n        forall (n : nat), \n          (n >= N)%nat ->\n          (LpRRVnorm prts (LpRRVminus prts (pack_LpRRV prts (rvlim f)) (f n))) < eps.\n  Proof.\n    intros.\n    pose (nts := event_restricted_domain P).\n    pose (ndom := event_restricted_sigma P).\n    assert (pf : 0 < ps_P P).\n    rewrite H; lra.\n    pose (nprts := event_restricted_prob_space prts P pf).\n    pose (nf := fun n => event_restricted_LpRRV _ P H pf (f n)).\n    pose (nrvlim := event_restricted_function P (rvlim f)).\n    assert (rv_eq nrvlim (rvlim nf)) by easy.\n    assert (nrvl : RandomVariable ndom borel_sa (rvlim nf)).\n    {\n      apply rvlim_rv.\n      - typeclasses eauto.\n      - intros.\n        destruct omega; simpl.\n        apply H0.\n        now simpl.\n    }\n    assert (nisl : IsLp nprts p (rvlim nf)).\n    {\n      unfold nprts, nf.\n      generalize (event_restricted_islp P p H pf _ isl); intros.\n      apply H3.\n    }\n    generalize (norm_rvminus_rvlim nprts pbig nf nrvl nisl); intros.\n    cut_to H3.\n    - specialize (H3 eps).\n      destruct H3 as [N ?].\n      exists N.\n      intros.\n      specialize (H3 n H4).\n      rewrite restricted_LpRRVnorm with (P := P) (pf := pf) (pf1 := H); trivial.\n      unfold nprts in H3.\n      rewrite <- restricted_LpRRVminus; trivial.\n      unfold nf in H3.\n      rewrite restricted_LpRRV_rvlim in H3; trivial.\n      apply H3.\n    - intros.\n      unfold nf.\n      unfold event_restricted_domain in x.\n      apply H0.\n      destruct x.\n      now simpl.\n    - intros.\n      specialize (H1 eps0).\n      destruct H1 as [N ?].\n      exists N.\n      intros.\n      specialize (H1 n m H4 H5).\n      unfold nprts, nf.\n      generalize (restricted_LpRRVminus P H pf (f m) (f n)); intros.\n      unfold pnneg in H6.\n      rewrite (LpRRV_norm_sproper (event_restricted_prob_space prts P pf) _ _ H6).\n      now rewrite  <- restricted_LpRRVnorm.\n   Qed.\n \n\n  Lemma two_pow_gt (r : R) :\n    exists n, r < pow 2 n.\n  Proof.\n    assert (2 > 1) by lra.\n    replace (2) with (Rabs 2) in H by (apply Rabs_right; lra).\n    generalize (Pow_x_infinity 2 H r); intros.\n    destruct H0 as [N ?].\n    exists (S N).\n    specialize (H0 N).\n    rewrite Rabs_right in H0.\n    cut_to H0; try lia.\n    apply Rge_le in H0.\n    eapply Rle_lt_trans.\n    apply H0.\n    replace (2^N) with (1 * (2^N)) by lra.\n    simpl.\n    apply Rmult_lt_compat_r; try lra.\n    apply pow2_pos.\n    left.\n    apply pow2_pos.\n  Qed.\n        \n  Lemma inv_two_pow_lt (eps : posreal) :\n    exists n, / (pow 2 n) < eps.\n  Proof.\n    generalize (two_pow_gt (/ eps)); intros.\n    destruct H.\n    exists x.\n    replace (pos eps) with (/ / eps) by\n        (rewrite Rinv_involutive; trivial; apply Rgt_not_eq; apply cond_pos).\n    apply Rinv_lt_contravar; trivial.\n    apply Rmult_lt_0_compat.\n    - apply Rinv_0_lt_compat, cond_pos.\n    - apply pow2_pos.\n  Qed.\n\n\n  Lemma Npow_eps (eps : posreal) :\n    exists (N : nat), 2 / (pow 2 N) < eps.\n  Proof.\n    generalize (cond_pos eps); intros.\n    assert (0 < eps/2) by lra.\n    generalize (inv_two_pow_lt (mkposreal _ H0)); intros.\n    destruct H1 as [N ?].\n    exists N.\n    unfold Rdiv.\n    rewrite Rmult_comm.\n    apply Rmult_lt_reg_r with (r := /2).\n    apply Rinv_0_lt_compat; lra.\n    rewrite Rmult_assoc.\n    rewrite <- Rinv_r_sym; try lra.\n    rewrite Rmult_1_r.\n    unfold Rdiv in H1.\n    apply H1.\n  Qed.\n\n  Lemma LpRRVnorm_rvminus_rvlim_almostR2 \n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F)\n        (eps : posreal)\n        (rv : RandomVariable dom borel_sa (rvlim (fun n : nat => LpRRV_lim_picker prts pbig F PF cF (S n)))) \n        (islp : IsLp prts p (rvlim (fun n : nat => LpRRV_lim_picker prts pbig F PF cF (S n)))):\n    let f := fun n => LpRRV_lim_picker prts pbig F PF cF (S n)  in \n    forall (eps : posreal),\n      exists (N : nat),\n        forall (n : nat), \n          (n >= N)%nat ->\n          (LpRRVnorm prts (LpRRVminus prts (pack_LpRRV prts (rvlim f)) (f n))) < eps.\n\n  Proof.\n    unfold cauchy in cF.\n    generalize (cauchy_filter_rvlim_finite2 prts pbig F PF cF); intros.\n    destruct X as [P [dec [? [? ?]]]].\n    apply norm_rvminus_rvlim_almostR2  with (P := P); trivial.\n    - intros.\n      specialize (H0 x).\n      rewrite ex_finite_lim_seq_ext in H0.\n      apply H0.\n      intros.\n      unfold rvmult, EventIndicator.\n      match_destr; try tauto.\n      subst f.\n      lra.\n    - intros.\n      generalize (lim_filter_cauchy prts pbig F PF cF); intros.\n      generalize (Npow_eps eps1); intros.\n      destruct H3 as [N ?].\n      exists N; intros.\n      specialize (H2 N (S m) (S n)).\n      subst f.\n      eapply Rlt_trans.\n      apply H2; try lia.\n      apply H3.\n   Qed.\n  \n  Global Instance IsLp_EventIndicator_mult {P : event dom} (dec : forall x, {P x} + {~ P x}) \n         (rv_X: Ts -> R)\n         {rv : RandomVariable dom borel_sa rv_X}\n         {islp:IsLp prts p rv_X} :\n    IsLp prts p (rvmult (EventIndicator dec) rv_X).\n  Proof.\n    generalize (IsLp_bounded prts p (rvmult (EventIndicator dec) rv_X) (rvpower (rvabs rv_X) (const p))); intros.\n    apply H; trivial.\n    intro x.\n    unfold rvpower, rvabs, rvmult, const, EventIndicator.\n    apply Rle_power_l.\n    lra.\n    split.\n    apply Rabs_pos.\n    match_destr.\n    - rewrite Rmult_1_l; now right.\n    - rewrite Rmult_0_l.\n      rewrite Rabs_R0.\n      apply Rabs_pos.\n  Qed.\n\n  Definition LpRRVindicator {P : event dom} (dec : forall x, {P x} + {~ P x}) (rv : LpRRV prts p) : LpRRV prts p\n    :=  pack_LpRRV prts (rvmult (EventIndicator dec) rv).\n\n  Instance rvlim_rv_almostR2_P \n           (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n           (PF:ProperFilter F)\n           (cF:cauchy F)\n           {P : event dom} \n           (dec : forall x, {P x} + {~ P x})\n           (pf:forall x : Ts,\n               ex_finite_lim_seq\n                 (fun n : nat => rvmult (EventIndicator dec) (LpRRV_lim_picker prts pbig F PF cF (S n)) x)):\n    let f := fun n : nat => LpRRVindicator dec (LpRRV_lim_picker prts pbig F PF cF (S n)) in\n    RandomVariable dom borel_sa (rvlim f).\n  Proof.\n    intros.\n    subst f.\n    apply rvlim_rv.\n    unfold LpRRVindicator.\n    unfold pack_LpRRV; simpl.\n    typeclasses eauto.\n    intros.\n    eauto.\n  Qed.\n\n  Lemma LpRRVminus_indicator_comm {P : event dom} (dec : forall x, {P x} + {~ P x})\n        (f g : LpRRV prts p) :\n    LpRRV_seq\n      (LpRRVminus prts (LpRRVindicator dec f) (LpRRVindicator dec g))\n      (LpRRVindicator dec (LpRRVminus prts f g)).\n  Proof.\n    intro x.\n    unfold LpRRVindicator.\n    unfold LpRRVminus, pack_LpRRV; simpl.\n    unfold EventIndicator, rvminus, rvmult, rvplus, rvopp, rvscale.\n    match_destr; lra.\n  Qed.\n\n  Lemma LpRRVnorm_indicator {P : event dom} (dec : forall x, {P x} + {~ P x})\n        (f : LpRRV prts p) :\n    ps_P P = 1 ->\n    LpRRVnorm prts f = LpRRVnorm prts (LpRRVindicator dec f).\n  Proof.\n    intros.\n    unfold LpRRVnorm.\n    f_equal.\n    apply FiniteExpectation_proper_almostR2.\n    typeclasses eauto.\n    typeclasses eauto.\n    unfold almostR2.\n    exists P.\n    split; trivial.\n    intros.\n    unfold LpRRVindicator, pack_LpRRV; simpl.\n    unfold rvpower, rvabs, const, rvmult, EventIndicator.\n    match_destr.\n    - now rewrite Rmult_1_l.\n    - tauto.\n  Qed.\n\n  Lemma LpRRVnorm_rvminus_rvlim_almostR2_P\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F)\n        (eps : posreal):\n    let '(existT P (exist dec _)) := (cauchy_filter_rvlim_finite2 prts pbig F PF cF) in\n    let f := fun n : nat => LpRRVindicator dec (LpRRV_lim_picker prts pbig F PF cF (S n)) in \n    exists (rv:RandomVariable dom borel_sa (rvlim f)),\n    exists (isl: IsLp prts p (rvlim f)),\n    ps_P P = 1 /\\\n    (forall x : Ts, ex_finite_lim_seq (fun n : nat => f n x)) /\\\n    forall (eps : posreal),\n      exists (N : nat),\n        forall (n : nat), \n          (n >= N)%nat ->\n          (LpRRVnorm prts (LpRRVminus prts (pack_LpRRV prts (rvlim f)) (f n))) < eps.\n  Proof.\n    unfold cauchy in cF.\n    destruct (cauchy_filter_rvlim_finite2 prts pbig F PF cF)\n             as [P [dec [? [? ?]]]].\n    intros.\n    exists (rvlim_rv_almostR2_P _ _ _ _ H0).\n    exists H1.\n    generalize ( norm_rvminus_rvlim_almostR2 f); intros.\n    simpl.\n    split; trivial.\n    split; trivial.\n    intros.\n    subst f.\n    specialize (H2 (rvlim_rv_almostR2_P F PF cF dec H0)).\n    specialize (H2 H1 P H).\n    apply H2; [intros; apply H0 |].\n    intros.\n    generalize (lim_filter_cauchy prts pbig F PF cF); intros.\n    generalize (Npow_eps eps1); intros.\n    destruct H4 as [N ?].\n    exists N; intros.\n    specialize (H3 N (S m) (S n) ).\n    cut_to H3; try lia.\n    rewrite LpRRVminus_indicator_comm .\n    rewrite <- LpRRVnorm_indicator; trivial.\n    eapply Rlt_trans.\n    apply H3.\n    apply H4.\n  Qed.\n\n  Lemma LpRRVnorm_LpRRV_cauchy_picker\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F)\n        (eps : posreal) :\n    exists (N : nat),\n    exists (x : LpRRV prts p),\n      (F (Hierarchy.ball x eps)) /\\\n      (forall (n:nat), (n >= N)%nat ->\n                       ((Hierarchy.ball (M := LpRRV_UniformSpace prts pbig) x eps) \n                          (LpRRV_lim_picker prts pbig F PF cF n))).\n   Proof.\n     intros.\n     generalize (inv_two_pow_lt eps); intros.\n     destruct H as [N ?].\n     generalize (lim_picker_center_included2 prts pbig F PF cF N); intros.\n     pose (x0 := (LpRRV_lim_ball_center_center prts pbig F PF cF N)).     \n     exists N.\n     exists (proj1_sig x0).\n     intros.\n     generalize (ball_le (M:= LpRRV_UniformSpace prts pbig) (proj1_sig x0) (mkposreal _ (inv_pow_2_pos N)) eps); intros.\n     split.\n     - destruct x0.\n       simpl in *.\n       eapply filter_imp; try eapply f.\n       apply ball_le.\n       lra.\n     - intros.\n       specialize (H0 n).\n       apply H1.\n       now left.\n       now apply H0.\n   Qed.\n\n   Lemma ball_LpRRV_lim_picker\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F)\n        (eps : posreal) :\n     exists (N : nat),\n       forall (n : nat), (n >= N)%nat ->\n                         (Hierarchy.ball (M := LpRRV_UniformSpace prts pbig) \n                                         (LpRRV_lim_picker prts pbig F PF cF (S n)) eps (LpRRV_lim prts pbig F)).\n     Proof.\n       generalize (LpRRVnorm_rvminus_rvlim_almostR2_P F PF cF eps); intros.\n       match_case_in H; intros.\n       rewrite H0 in H.\n       match_destr_in H.\n       simpl in H.\n       destruct H as [? [? [? [? ?]]]].\n       specialize (H2 eps).\n       destruct H2 as [N ?].\n       exists N.\n       intros.\n       specialize (H2 n H3).\n       unfold LpRRV_lim.\n       match_destr; try tauto.\n       match_destr; try tauto.\n       do 2 red; simpl.\n       unfold LpRRV_lim_with_conditions.\n       unfold LpRRVball, LpRRVnorm.\n       unfold LpRRVnorm in H1.\n       unfold bignneg; simpl.\n       assert ((FiniteExpectation prts (rvpower (rvabs (rvminus (LpRRV_lim_picker prts pbig F PF cF (S n)) (cauchy_rvlim_fun prts pbig F p0 c))) (const p))) =\n                 (FiniteExpectation prts\n            (rvpower\n               (rvabs\n                  (LpRRVminus prts\n                     (pack_LpRRV prts (rvlim (fun n : nat => rvmult (EventIndicator x0) (LpRRV_lim_picker prts pbig F PF cF (S n)))))\n                     (LpRRVindicator x0 (LpRRV_lim_picker prts pbig F PF cF (S n))))) (const p)))).\n       {\n         apply FiniteExpectation_proper_almostR2.       \n         typeclasses eauto.\n         typeclasses eauto.\n         unfold almostR2.\n         exists x.\n         split; trivial.\n         intros.\n         unfold rvpower, const.\n         f_equal.\n         unfold rvabs, LpRRVminus, pack_LpRRV; simpl.\n         unfold rvminus, rvplus, rvopp, rvscale, cauchy_rvlim_fun.\n         rewrite (proof_irrelevance _ p0 PF).\n         rewrite (proof_irrelevance _ c cF).\n         rewrite H0.\n         rewrite <- Rabs_Ropp at 1.\n         f_equal.\n         rewrite Rplus_comm.\n         ring_simplify.\n         f_equal.\n         unfold EventIndicator, rvmult.\n         match_destr.\n         lra.\n         tauto.\n       }\n       unfold LpRRVnorm, LpRRVminus, pack_LpRRV in H2.\n       simpl in H2.\n       clear H0.\n       clear a.\n       erewrite FiniteExpectation_pf_irrel; rewrite H4.\n       erewrite FiniteExpectation_pf_irrel in H2.\n       apply H2.\n     Qed.\n\n  Lemma LpRRVnorm_LpRRV_lim\n        (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n        (PF:ProperFilter F)\n        (cF:cauchy F)\n        (eps : posreal) :\n    exists (x : LpRRV prts p),\n      (F (Hierarchy.ball x eps)) /\\\n      ((Hierarchy.ball (M := LpRRV_UniformSpace prts pbig) x eps) (LpRRV_lim prts pbig F)).\n  Proof.\n    generalize (cond_pos eps); intro eps_pos.\n    assert (eps_half: 0 < eps/2) by lra.\n    generalize (LpRRVnorm_LpRRV_cauchy_picker F PF cF (mkposreal _ eps_half)); intros.\n    destruct H as [N [x [? ?]]].\n    exists x.\n    split.\n    - generalize (ball_le (M:= LpRRV_UniformSpace prts pbig) x (mkposreal _ eps_half) eps); intros.\n      eapply filter_imp.\n      apply H1.\n      simpl; lra.\n      apply H.\n    - generalize (ball_LpRRV_lim_picker F PF cF (mkposreal _ eps_half)); intros.\n      destruct H1.\n      specialize (H0 (S (max N x0))).\n      cut_to H0; try lia.\n      specialize (H1 (max N x0)).\n      cut_to H1; try lia.\n      replace (pos eps) with ((mkposreal _ eps_half) + (mkposreal _ eps_half)) by (simpl; lra).\n      now apply Hierarchy.ball_triangle with (y := (LpRRV_lim_picker prts pbig F PF cF (S (max N x0)))).\n   Qed.      \n\n  Lemma L2RRV_lim_complete (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop) \n        (PF : ProperFilter F)\n        (cF : cauchy F) :\n    forall eps : posreal, F (Hierarchy.ball (LpRRV_lim  prts pbig F) eps).\n  Proof.\n    intros.\n    assert (0 < eps/2).\n    {\n      apply Rlt_div_r; try lra.\n      rewrite Rmult_0_l.\n      apply cond_pos.\n    }\n    generalize (LpRRVnorm_LpRRV_lim F PF cF (mkposreal _ H)); intros.\n    destruct H0 as [? [? ?]].\n    generalize (Hierarchy.ball_triangle \n                  (M := LpRRV_UniformSpace prts pbig)); intros.\n    apply filter_imp with (P := (Hierarchy.ball x (mkposreal _ H))); trivial.\n    intros.\n    apply Hierarchy.ball_sym in H1.\n    replace (pos eps) with ((pos (mkposreal _ H)) + (pos (mkposreal _ H))).\n    apply (Hierarchy.ball_triangle _ _ _ _ _ H1 H3).\n    simpl; lra.\n  Qed.\n\n  Program Definition LpRRVq_lim_with_conditions (F : (LpRRV_UniformSpace prts pbig -> Prop) -> Prop)\n          (PF:ProperFilter F)\n          (cF:cauchy F) : LpRRVq prts p\n    := Quot _ (LpRRV_lim_with_conditions prts pbig F PF cF).\n\n  Lemma LpRRVq_lim_with_conditionsE F PF cF : LpRRVq_lim_with_conditions F PF cF  = Quot _ (LpRRV_lim_with_conditions prts pbig F PF cF).\n  Proof.\n    reflexivity. \n  Qed.\n  \n  Hint Rewrite LpRRVq_lim_with_conditionsE : quot.\n\n  Definition LpRRV_toLpRRVq_set (s:(LpRRV prts p)->Prop) (x:LpRRVq prts p) : Prop\n    := forall y, x = Quot _ y -> s y.\n\n  Definition LpRRVq_filter_to_LpRRV_filter (F:((LpRRVq prts p)->Prop)->Prop) : ((LpRRV prts p)->Prop)->Prop\n    := (fun x:(LpRRV prts p)->Prop => F (LpRRV_toLpRRVq_set x)).\n  \n  Lemma LpRRVq_filter_to_LpRRV_filter_filter (F:((LpRRVq prts p)->Prop)->Prop) \n        (FF:Filter F) :\n    Filter (LpRRVq_filter_to_LpRRV_filter F).\n  Proof.\n    destruct FF.\n    unfold LpRRVq_filter_to_LpRRV_filter, LpRRV_toLpRRVq_set.\n    constructor; intros.\n    - eapply filter_imp; try eapply filter_true; intros.\n      destruct (Quot_inv x); subst.\n      eauto.\n    - generalize (filter_and _ _ H H0); intros HH.\n      eapply filter_imp; try eapply HH; intros ? [??].\n      intros; subst.\n      specialize (H1 _ (eq_refl _)).\n      specialize (H2 _ (eq_refl _)).\n      tauto.\n    - eapply filter_imp; try eapply H0; simpl; intros.\n      subst.\n      apply H.\n      now apply H1.\n  Qed.\n\n  Lemma LpRRVq_filter_to_LpRRV_filter_proper (F:((LpRRVq prts p)->Prop)->Prop) \n        (PF:ProperFilter F) :\n    ProperFilter (LpRRVq_filter_to_LpRRV_filter F).\n  Proof.\n    destruct PF.\n    constructor.\n    - intros.\n      destruct (filter_ex (LpRRV_toLpRRVq_set P) H).\n      destruct (Quot_inv x); subst.\n      exists x0.\n      unfold LpRRV_toLpRRVq_set in *.\n      now apply H0.\n    - now apply LpRRVq_filter_to_LpRRV_filter_filter.\n  Qed.\n\n  Lemma rvpower2 (x:Ts->R) {posx:NonnegativeFunction x} : rv_eq (rvpower x (const 2)) (rvsqr x).\n  Proof.\n    intros ?.\n    unfold rvpower, rvsqr, const.\n    apply power2_sqr.\n    apply posx.\n  Qed.\n          \n  Lemma LpRRVq_filter_to_LpRRV_filter_cauchy\n        (F : (LpRRVq_UniformSpace prts p pbig -> Prop) -> Prop)\n    (PF:ProperFilter F)\n    (cF:cauchy F) : \n    @cauchy (LpRRV_UniformSpace prts pbig) (LpRRVq_filter_to_LpRRV_filter F).\n  Proof.\n    unfold cauchy ; intros.\n    destruct (cF eps) as [??]; simpl in *.\n    unfold LpRRVq_filter_to_LpRRV_filter, LpRRV_toLpRRVq_set.\n    destruct (Quot_inv x); subst.\n    exists x0.\n    eapply filter_imp; try eapply H; intros; subst.\n    repeat red.\n    do 2 red in H0.\n    simpl in H0.\n    rewrite LpRRVq_ballE in H0.\n    apply H0.\n  Qed.\n\n  Definition LpRRVq_lim_with_conditions2 (F : (LpRRVq_UniformSpace prts p pbig -> Prop) -> Prop)\n    (PF:ProperFilter F)\n    (cF:cauchy F) : LpRRVq prts p.\n    Proof.\n      simpl in F.\n      pose (LpRRVq_filter_to_LpRRV_filter F).\n      generalize (LpRRVq_lim_with_conditions P); intros.\n      specialize (X (LpRRVq_filter_to_LpRRV_filter_proper F PF)).\n      specialize (X (LpRRVq_filter_to_LpRRV_filter_cauchy F PF cF)).\n      exact X.\n  Defined.\n\n  Definition LpRRVq_lim (lim : ((LpRRVq prts p -> Prop) -> Prop)) : LpRRVq prts p.\n  Proof.\n    destruct (excluded_middle_informative (ProperFilter lim)).\n    - destruct (excluded_middle_informative (cauchy (T:=LpRRVq_UniformSpace prts p pbig) lim)).\n      + exact (LpRRVq_lim_with_conditions2 _ p0 c).\n      + exact (LpRRVq_zero prts).\n    - exact (LpRRVq_zero prts).\n  Defined.\n\n  Lemma LpRRVq_lim_complete (F : (LpRRVq_UniformSpace prts p pbig -> Prop) -> Prop) :\n    ProperFilter F -> cauchy F -> forall eps : posreal, F (LpRRVq_ball prts pbig (LpRRVq_lim F) eps).\n  Proof.\n    intros.\n    unfold LpRRVq_lim; simpl.\n    match_destr; [| tauto].\n    match_destr; [| tauto].\n    generalize (L2RRV_lim_complete (LpRRVq_filter_to_LpRRV_filter F)); intros.\n    generalize (LpRRVq_filter_to_LpRRV_filter_proper F H); intros.\n    generalize (LpRRVq_filter_to_LpRRV_filter_cauchy F H H0); intros.\n    specialize (H1 H2 H3 eps).\n    unfold LpRRV_lim in H1; simpl in H1.\n    match_destr_in H1; [|tauto].\n    match_destr_in H1; [|tauto].\n    unfold Hierarchy.ball, UniformSpace.ball in H1; simpl in H1.\n    unfold LpRRVq_lim_with_conditions2.\n    rewrite  LpRRVq_lim_with_conditionsE.\n    rewrite (proof_irrelevance _ _ p1).\n    rewrite (proof_irrelevance _ _ c0).\n    unfold LpRRVq_filter_to_LpRRV_filter in *.\n    eapply filter_imp; try eapply H1.\n    intros x; simpl in *.\n\n    unfold LpRRV_toLpRRVq_set; simpl; intros HH.\n    unfold ball, minus, plus, opp; simpl.\n    destruct (Quot_inv x); subst.\n    rewrite LpRRVq_ballE.\n    specialize (HH _ (eq_refl _)).\n    unfold LpRRVball in *.\n    eapply Rle_lt_trans; try eapply HH.\n    unfold LpRRVnorm.\n    apply Rle_power_l; [| split].\n    - simpl.\n      left; apply Rinv_pos; lra.\n    - apply FiniteExpectation_pos.\n      typeclasses eauto.\n    - apply FiniteExpectation_le.\n      reflexivity.\n  Qed.\n\n  Lemma LpRRVq_lim_close (F1 F2 : (LpRRVq_UniformSpace prts p pbig -> Prop) -> Prop) :\n    filter_le F1 F2 ->\n    filter_le F2 F1 ->\n    @close (LpRRVq_UniformSpace prts p pbig) (LpRRVq_lim F1) (LpRRVq_lim F2).\n  Proof.\n    intros.\n    replace F1 with F2.\n    apply close_refl.\n    apply functional_extensionality.\n    intros x.\n    unfold filter_le in *.\n    apply propositional_extensionality; split.\n    apply H.\n    apply H0.\n  Qed.\n\n  Definition LpRRVq_Complete_mixin : CompleteSpace.mixin_of (LpRRVq_UniformSpace prts p pbig)\n    := CompleteSpace.Mixin (LpRRVq_UniformSpace prts p pbig)\n                           LpRRVq_lim\n                           LpRRVq_lim_complete\n                           LpRRVq_lim_close.\n\n\n  Canonical LpRRVq_Complete :=\n    CompleteSpace.Pack (LpRRVq prts p)\n                       (CompleteSpace.Class _ (LpRRVq_UniformSpace_mixin prts pbig)\n                                            LpRRVq_Complete_mixin)\n                       (LpRRVq prts p).\n\n  Canonical LpRRVq_CompleteNormedModule :=\n        CompleteNormedModule.Pack R_AbsRing (LpRRVq prts p)\n                                  (CompleteNormedModule.Class\n                                     R_AbsRing (LpRRVq prts p)\n                                     (NormedModule.class R_AbsRing \n                                                         (LpRRVq_NormedModule prts p pbig))\n                                  LpRRVq_Complete_mixin)\n                                  (LpRRVq prts p).\n\n  End complete2.\n\nEnd complete.\n\nSection more_Lp_props.\n  Context {Ts:Type} \n          {dom: SigmaAlgebra Ts}\n          (prts: ProbSpace dom).\n\n  Global Instance EventIndicator_islp (p:nonnegreal) {P} (dec : dec_pre_event P) :\n    IsLp prts p (EventIndicator dec).\n  Proof.\n    unfold IsLp.\n    apply IsFiniteExpectation_bounded with (rv_X1 := const 0) (rv_X3 := const 1).\n    - apply IsFiniteExpectation_const.\n    - apply IsFiniteExpectation_const.\n    - intro x.\n      unfold const, rvpower.\n      apply power_nonneg.\n    - intro x.\n      unfold rvpower, const.\n      replace (1) with (power 1 p).\n      + apply Rle_power_l.\n        { apply cond_nonneg.\n        } \n        unfold rvabs.\n        split.\n        * apply Rabs_pos.\n        * unfold EventIndicator.\n          match_destr.\n          -- rewrite Rabs_R1; lra.\n          -- rewrite Rabs_R0; lra.\n      + now rewrite power_base_1.\n  Qed.\n\n  Lemma LpRRVnorm_minus_sym {p:nonnegreal} (x y : LpRRV prts p) :\n    LpRRVnorm prts (LpRRVminus prts x y) = LpRRVnorm prts (LpRRVminus prts y x).\n  Proof.\n    unfold LpRRVnorm, LpRRVminus.\n    f_equal.\n    apply FiniteExpectation_ext.\n    intro z.\n    unfold rvpower, rvabs, pack_LpRRV; f_equal; simpl.\n    do 2 rewrite rvminus_unfold.\n    apply Rabs_minus_sym.\n  Qed.\n\n  Definition LpRRV_dist {p:nonnegreal} (x y : LpRRV prts p) := \n    LpRRVnorm prts (LpRRVminus prts x y).\n\n  Lemma LpRRV_norm_dist {p:nonnegreal} (x y : LpRRV prts p) :\n    LpRRV_dist x y = LpRRVnorm prts (LpRRVminus prts x y).  \n  Proof.\n    easy.\n  Qed.\n  \n  Lemma LpRRV_dist_comm {p:nonnegreal} (x y : LpRRV prts p) :\n    LpRRV_dist x y = LpRRV_dist y x.\n  Proof.\n    unfold LpRRV_dist, LpRRVnorm, LpRRVminus.\n    f_equal.\n    apply FiniteExpectation_ext.\n    intro z.\n    unfold rvpower, rvabs, pack_LpRRV.\n    f_equal.\n    simpl.\n    do 2 rewrite rvminus_unfold.\n    now rewrite Rabs_minus_sym.\n  Qed.\n\n  Lemma LpRRV_dist_triang {p:R} (pbig:1<= p) (x y z : LpRRV prts p) :\n    LpRRV_dist (p := bignneg _ pbig) x z <= LpRRV_dist (p := bignneg _ pbig) x y + LpRRV_dist (p := bignneg _ pbig) y z.\n  Proof.\n    unfold LpRRV_dist.\n    generalize (LpRRV_norm_plus prts pbig (LpRRVminus prts (p := bignneg _ pbig) x y) (LpRRVminus prts (p := bignneg _ pbig) y z)); intros.\n    do 2 rewrite LpRRVminus_plus in H.\n    rewrite <- LpRRV_plus_assoc in H.\n    rewrite (LpRRV_plus_assoc prts (p := bignneg _ pbig) (LpRRVopp prts y) _) in H.     \n    rewrite (LpRRV_plus_comm prts (p := bignneg _ pbig) _ y) in H.\n    rewrite LpRRV_plus_inv in H.\n    rewrite (LpRRV_plus_comm prts (p := bignneg _ pbig) (LpRRVconst prts 0) _ ) in H.\n    rewrite LpRRV_plus_zero in H.\n    now repeat rewrite <- LpRRVminus_plus in H.\n  Qed.  \n\nEnd more_Lp_props.\n\nSection sa_sub.\n\n  Context {Ts:Type} \n          {dom: SigmaAlgebra Ts}\n          (prts:ProbSpace dom)\n          {dom2 : SigmaAlgebra Ts}\n          (sub : sa_sub dom2 dom).\n  \n  Lemma IsLp_prob_space_sa_sub\n        p (x:Ts->R)\n        {rv:RandomVariable dom2 borel_sa x} :\n    IsLp prts p x <->\n    IsLp (prob_space_sa_sub prts sub) p x.\n  Proof.\n    unfold IsLp, IsFiniteExpectation; intros.\n    now rewrite Expectation_prob_space_sa_sub by typeclasses eauto.\n  Qed.\n\n  Definition LpRRV_sa_sub p\n             (x: LpRRV (prob_space_sa_sub prts sub) p) : LpRRV prts p\n    := pack_LpRRV _ x\n                  (rv:=RandomVariable_sa_sub sub x)\n                  (lp:=(proj2 (IsLp_prob_space_sa_sub p x)) _).\n\n  Definition LpRRV_sa_sub_f p\n             (x:LpRRV prts p)\n             {rv:RandomVariable dom2 borel_sa x}\n    : LpRRV (prob_space_sa_sub prts sub) p\n    := pack_LpRRV _ x (lp:=(proj1 (IsLp_prob_space_sa_sub p x)) _).\n\n  Lemma LpRRV_sa_sub_b_f p (x:LpRRV prts p)\n        {rv:RandomVariable dom2 borel_sa x} :\n    LpRRV_seq (LpRRV_sa_sub p (LpRRV_sa_sub_f p x)) x.\n  Proof.\n    intros ?.\n    now destruct x; simpl.\n  Qed.    \n\n  Lemma LpRRV_sa_sub_f_b p (x:LpRRV (prob_space_sa_sub prts sub) p) :\n    LpRRV_seq (LpRRV_sa_sub_f p (LpRRV_sa_sub p x) (rv:=LpRRV_rv _ _)) x.\n  Proof.\n    intros ?.\n    now destruct x; simpl.\n  Qed.    \n\nEnd sa_sub.\n", "meta": {"author": "IBM", "repo": "FormalML", "sha": "e399d096f1ad572420dbd1c638d593eee2129cbe", "save_path": "github-repos/coq/IBM-FormalML", "path": "github-repos/coq/IBM-FormalML/FormalML-e399d096f1ad572420dbd1c638d593eee2129cbe/coq/ProbTheory/RandomVariableLpR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6765733387162086}}
{"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 Relations.\n\nSet Implicit Arguments.\n\nSection list_splits.\n\n  Variables (X : Type).\n  \n  Implicit Types (l : list X).\n\n  Fixpoint list_splits l := \n    match l with \n      | nil =>  ((nil,nil)::nil)\n      | x::l => (nil,x::l)::map (fun (c : list X * list X) => let (u,v) := c in (x::u,v)) (list_splits l) \n    end.\n    \n  Fact list_splits_spec l x y : In (x,y) (list_splits l) <-> x++y = l.\n  Proof.\n    revert x y.\n    induction l as [ | a l IH ]; intros x y; simpl; split.\n    intros [ H | [] ]; injection H; intros; subst; auto.\n    destruct x; destruct y; try discriminate 1; tauto.\n    intros [ H | H ].\n    injection H; intros; subst; auto.\n    apply in_map_iff in H.\n    destruct H as ((u,v) & H1 & H2).\n    injection H1; clear H1; intros ? ?; subst x y.\n    rewrite IH in H2.\n    rewrite <- H2; auto.\n    intros H.\n    destruct x as [ | a' x ].\n    simpl in H; subst y; left; auto.\n    injection H; clear H; intros ? ?; subst a' l; right.\n    apply in_map_iff.\n    exists (x,y).\n    rewrite IH; auto.\n  Qed.\n\n  Definition lmr l := flat_map (fun c => match c with (_,nil) => nil | (l,x::r) => (l,(x,r))::nil end) (list_splits l).\n\n  Fact lmr_spec ll w : In w (lmr ll) <-> exists l x r, ll = l++x::r /\\ w = (l,(x,r)).\n  Proof.\n    unfold lmr; rewrite in_flat_map.\n    split.\n\n    intros ((l,[ | x r ]) & H1 & H2).\n    destruct H2.\n    destruct H2 as [ H2 | [] ]; subst.\n    apply list_splits_spec in H1; subst.\n    exists l, x, r; auto.\n    \n    intros (l & x & r & H1 & H2); subst.\n    exists (l,x::r); split; simpl; auto.\n    rewrite list_splits_spec; auto.\n  Qed.\n \n  Let list_msplits k l : { ll | forall m, In m ll <-> flat_map (fun x => x) m = l /\\ length m = S k }.\n  Proof.\n    revert l; induction k as [ | k IH ]; intros l.\n    \n    exists ((l::nil)::nil); split.\n    intros [ ? | [] ]; subst; simpl; rewrite <- app_nil_end; auto.\n    intros (H1 & H2).\n    destruct m as [ | a [ | ] ]; try discriminate H2; simpl in H1.\n    rewrite <- app_nil_end in H1; subst a; left; auto.\n    \n    set (h l := proj1_sig (IH l)).\n    assert (Hh : forall l m, In m (h l) <-> flat_map (fun x => x) m = l /\\ length m = S k).\n      intros u; apply (proj2_sig (IH u)).\n    generalize h Hh; clear h Hh IH; intros h Hh.\n    \n    set (g (c : list X * list X) := let (w1,w2) := c in map (fun d => w1::d) (h w2)).\n    \n    exists (flat_map g (list_splits l)).\n    intros m; split.\n    \n    rewrite in_flat_map.\n    intros ((u,v) & H1 & H2).\n    unfold g in H2.\n    rewrite list_splits_spec in H1.\n    rewrite in_map_iff in H2.\n    destruct H2 as (ll & H2 & H3).\n    rewrite Hh in H3.\n    destruct H3 as (H3 & H4).\n    subst m l v; split; simpl; auto.\n    \n    intros (H1 & H2). \n    rewrite in_flat_map.\n    destruct m as [ | a m ]; try discriminate H2.\n    simpl in H2; injection H2; clear H2; intros H2.\n    simpl in H1; subst l.\n    exists (a, flat_map (fun x => x) m); split.\n    rewrite list_splits_spec; auto.\n    unfold g.\n    rewrite in_map_iff.\n    exists m; split; auto.\n    rewrite Hh; split; auto.\n  Qed.\n  \n  Definition list_multi_splits k l := proj1_sig (list_msplits k l).\n  \n  Fact list_multi_splits_spec k l mm : In mm (list_multi_splits k l) <-> flat_map (fun x => x) mm = l /\\ length mm = S k.\n  Proof.\n    apply (proj2_sig (list_msplits k l)).\n  Qed.\n\nEnd list_splits.\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_split.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830605, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.6765167236471459}}
{"text": "(*|\n########################################\nInductive definition for family of types\n########################################\n\n:Link: https://stackoverflow.com/q/37366941\n|*)\n\n(*|\nQuestion\n********\n\nI have been struggling on this for a while now. I have an inductive\ntype:\n|*)\n\nDefinition char := nat.\nDefinition string := list char.\n\nInductive Exp : Set :=\n| Lit  : char -> Exp\n| And  : Exp -> Exp -> Exp\n| Or   : Exp -> Exp -> Exp\n| Many : Exp -> Exp.\n\n(*| from which I define a family of types inductively: |*)\n\nInductive Language : Exp -> Set :=\n| LangLit     : forall c : char, Language (Lit c)\n| LangAnd     :\n  forall r1 r2 : Exp, 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    :\n  forall r : Exp, Language (Many r) -> Language r -> Language (Many r).\n\n(*|\nThe rational here is that given a regular expression ``r : Exp`` I am\nattempting to represent the language associated with ``r`` as a type\n``Language r``, and I am doing so with a single inductive definition.\n\nI would like to prove:\n|*)\n\nLemma L1 : forall (c : char) (x : Language (Lit c)),\n    x = LangLit c.\nAbort. (* .none *)\n\n(*|\n(In other words, the type ``Language (Lit c)`` has only one element,\ni.e. the language of the regular expression ``'c'`` is made of the\nsingle string ``\"c\"``. Of course I need to define some semantics\nconverting elements of ``Language r`` to ``string``)\n\nNow the specifics of this problem are not important and simply serve\nto motivate my question: let us use ``nat`` instead of ``Exp`` and let\nus define a type ``List n`` which represents the lists of length\n``n``:\n|*)\n\nParameter A : Set.\nInductive List : nat -> Set :=\n| ListNil  : List 0\n| ListCons : forall n : nat, A -> List n -> List (S n).\n\n(*|\nHere again I am using a single inductive definition to define a family\nof types ``List n``.\n\nI would like to prove:\n|*)\n\nLemma L2 : forall x : List 0, x = ListNil.\nAbort. (* .none *)\n\n(*|\n(in other words, the type ``List 0`` has only one element).\n\nI have run out of ideas on this one.\n\nNormally when attempting to prove (negative) results with inductive\ntypes (or predicates), I would use the ``elim`` tactic (having made\nsure all the relevant hypothesis are inside my goal (``generalize``)\nand only variables occur in the type constructors). But ``elim`` is no\ngood in this case.\n|*)\n\n(*|\nAnswer\n******\n\nIf you are willing to accept more than just the basic logic of Coq,\nyou can just use the ``dependent destruction`` tactic, available in\nthe ``Program`` library (I've taken the liberty of rephrasing your\nlast example in terms of standard-library vectors):\n|*)\n\nRequire Coq.Vectors.Vector.\n\nRequire Import Program.\n\nLemma l0 A (v : Vector.t A 0) : v = @Vector.nil A.\nProof.\n  now dependent destruction v.\nQed.\n\n(*|\nIf you inspect the term, you'll see that this tactic relied on the\n``JMeq_eq`` axiom to get the proof to go through:\n|*)\n\nPrint Assumptions l0. (* .unfold *)\n\n(*|\nFortunately, it is possible to prove ``l0`` without having to resort\nto features outside of Coq's basic logic, by making a small change to\nthe statement of the previous lemma.\n|*)\n\nLemma l0_gen A n (v : Vector.t A n) :\n  match n return Vector.t A n -> Prop with\n  | 0 => fun v => v = @Vector.nil A\n  | _ => fun _ => True\n  end v.\nProof.\n  now destruct v.\nQed.\n\nLemma l0' A (v : Vector.t A 0) : v = @Vector.nil A.\nProof.\n  exact (l0_gen A 0 v).\nQed.\n\n(*|\nWe can see that this new proof does not require any additional axioms:\n|*)\n\nPrint Assumptions l0'. (* .unfold *)\n\n(*|\nWhat happened here? The problem, roughly speaking, is that in Coq we\ncannot perform case analysis on terms of dependent types whose indices\nhave a specific shape (such as ``0``, in your case) *directly*.\nInstead, we must prove a more general statement where the problematic\nindices are replaced by variables. This is exactly what the ``l0_gen``\nlemma is doing. Notice how we had to make the match on ``n`` return a\nfunction that abstracts on ``v``. This is another instance of what is\nknown as `\"convoy pattern\"\n<http://adam.chlipala.net/cpdt/html/Cpdt.MoreDep.html>`__. Had we\nwritten\n\n.. code-block:: coq\n\n    match n with\n    | 0 => v = @Vector.nil A\n    | _ => True\n    end.\n\nCoq would see the ``v`` in the ``0`` branch as having type ``Vector.t\nA n``, making that branch ill-typed.\n\nComing up with such generalizations is one of the big pains of doing\ndependently typed programming in Coq. Other systems, such as Agda,\nmake it possible to write this kind of code with much less effort, but\nit was only recently `shown\n<https://people.cs.kuleuven.be/~jesper.cockx/Without-K/Pattern-matching-without-K.pdf>`__\nthat this can be done without relying on the extra axioms that Coq\nwanted to avoid including in its basic theory. We can only hope that\nthis will be simplified in future versions.\n\n----\n\n**A:** I also find this alternative proof ``by apply: eq_dep_eq; move\nE: {1 2}0 v => iz v; case: iz / v E.`` useful sometimes. Indeed,\n``eq_dep`` and similar tricks can be very useful when working with\ndependent types.\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/inductive-definition-for-family-of-types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.6765167139534054}}
{"text": "(** * Logic: Logic in Coq *)\n(* Zhiwei Wu, Wenrui Meng  5 hours for each*)\n\nRequire Export MoreProp. \nInductive Ptree (X:Type) : Type :=\n | c1 : X -> X -> Ptree X\n | c2 : Ptree X -> Ptree X -> Ptree X\n.\nImplicit Arguments c1 [[X]].\nImplicit Arguments c2 [[X]].\nFixpoint flug {X Y : Type } (l : Ptree X) (f : X->Y) : Ptree Y :=\nmatch l with\n|  c1 x1 x2 => c1 (f x1) (f x2)\n|  c2 p1 p2 => c2 (flug p1 f) (flug p2 f)\nend\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(** * 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. inversion H as [HP HQ].\n apply HQ. Qed.\n\n(** [] *)\n\nTheorem and_commut : forall P Q : Prop, \n  P /\\ Q -> Q /\\ P.\nProof.\n  (* 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. split. apply HP. apply HQ. apply HR.\n  Qed.\n\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  intros. induction n as [| n'].\n  Case \"n = 0\". \n  split. intro. apply ev_0.\n  intro. inversion H. \n\n  Case \"n = S n'\".\n  split. inversion IHn' as [HN HS].\n  apply HS.  \n  inversion IHn' as [H1 H2]. intro. \n  inversion H. unfold even in H1. apply H1 in H3.\n  apply ev_SS. apply H3.\n  Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (conj_fact) *)\n(** Construct a proof object demonstrating the following proposition. *)\nTheorem conj_fact' : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R.\nProof.\nintros. apply conj. apply proj1 in H. apply H.\napply proj2 in H0. apply H0. Qed.\n\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\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(** **** 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\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(** [] *)\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(* FILL IN HERE *)\n(** [] *)\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof. \n  intros P Q R. intros H. inversion H as [HP | [HQ HR]]. \n    Case \"left\". split.\n      SCase \"left\". left. apply HP.\n      SCase \"right\". left. apply HP.\n    Case \"right\". split.\n      SCase \"left\". right. apply HQ.\n      SCase \"right\". right. apply HR.  Qed.\n\n(** **** Exercise: 2 stars (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.\n inversion H0.\n Case \"P\".\n apply or_introl. apply H2.\n Case \"Q R\". inversion H1. \n   SCase \"P\". apply or_introl. apply H3.\n   SCase \"Q\". apply or_intror. split. apply H2. apply H3.\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  (* 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_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  (* FILL IN HERE *) Admitted.\n\nTheorem orb_true : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem orb_false : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof. \n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################### *)\n(** * Falsehood *)\n\n(** Logical falsehood can be represented in Coq as an inductively\n    defined proposition with no constructors. *)\n\nInductive False : Prop := . \n\n(** Intuition: [False] is a proposition for which there is no way\n    to give evidence. *)\n\n\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 := P.\n\n\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           Suppose P as a Prop, we must show (P->False)->False according to the definition of not.\n           Suppose (P-> False) as H, we need make a implication False according to the hypertheses. \n           We can apply P in H, then we get False, which is exact the goal.\n(* FILL IN HERE *)\n   []\n\n*)\n\n(** **** Exercise: 2 stars (contrapositive) *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\nintros. unfold not in H0.\nunfold not. intro. \napply H in H1. apply H0 in H1.\napply H1.\nQed.\n\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. \nintros. unfold not. intro.\ninversion H. apply H1 in H0. apply H0.\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(* FILL IN HERE *)\n(**\n_Proof_: \nBy the definition of not, we must show  P/\\ ~P -> False.\nThen we split the hyperthesis P/\\~P into two hypertheses P as H1 and ~P as H2.\nWe change H2 to P -> False according to the definition of not.\nApplying H1 in H2, we can get False.\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 \"basecase\".\n  intro H'. inversion H'.\n  Case \"inductive\".  \n  intro. apply SSev__even in H0. apply IHev in H0.\n  apply H0. Qed.\n\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(* 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 intros n n'. remember (beq_nat n n') as b.\n destruct b.\n Case \"true\". intro. apply beq_nat_eq in Heqb.\n unfold not in H. apply H in Heqb. inversion Heqb.\n Case \"false\". intro. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_false_not_eq) *)\nTheorem beq_false_not_eq : forall n m,\n  false = beq_nat n m -> n <> m.\nProof.\n\n  (* FILL IN HERE *) Admitted.\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(* FILL IN HERE *)\n\n(** Complete the definition of the following proof object: *)\n\nDefinition p : ex nat (fun n => beautiful (S n)) :=\n(* FILL IN HERE *) admit.\n(** [] *)\n\n(** **** Exercise: 1 star (dist_not_exists) *)\n(** Prove that \"[P] holds for all [x]\" and \"there is no [x] for\n    which [P] does not hold\" are equivalent assertions. *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof. \n  intro X. intro P. intro H. unfold not.\n  intro H0. elim H0. intros.\n  assert (P witness). apply H. apply H1 in H2. inversion H2.\n  Qed.\n\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.\nintros X P. split. intro H.\ninversion H as [x H1]. inversion H1 as [HL | HR]. \napply or_introl. apply ex_intro with (witness := x). apply HL.\napply or_intror. apply ex_intro with (witness := x). apply HR.\n\nintro H. inversion H. inversion H0 as [x H1].\napply ex_intro with (witness := x). apply or_introl. apply H1.\ninversion H0. apply ex_intro with (witness := witness). apply or_intror.\napply H1. Qed.\n\n(** [] *)\n\nPrint 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(** [] *)\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\nn   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(* FILL IN HERE *) Admitted.\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\nInductive total_relation : nat -> nat -> Prop := \ntr : forall n1 n2 : nat, total_relation n1 n2.\n\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\nInductive empty_relation : nat -> nat -> Prop := \ner : forall n m : nat, False -> empty_relation n m.\n\n(** [] *)\n\n(** **** Exercise: 3 stars (R_provability) *)\nModule R.\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0 \n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n  \n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* FILL IN HERE\n[R 1 1 2] is provable. The other is not. \nNo, it wouldn't change. \n\nNo, it wouldn't change. c1 and c2 can derive c4.\n\n *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact) *)  \n(** State and prove an equivalent characterization of the relation\n    [R].  That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n*)\n\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| all_nil : all X P []\n| all_recursive : forall (hd : X) (l : list X), P hd -> all X P l \n                                                -> all X P (hd::l).\n  (* FILL IN HERE *)\n\n\n(** Recall the function [forallb], from the exercise\n    [forall_exists_challenge] in chapter [Poly]: *)\n\n(*Fixpoint 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\nTheorem all_forallb : forall (X : Type) (test : X -> bool) (l : list X), (all X (fun x:X => (test x = true)) l) <-> (forallb  test l = true).\nProof.\nintros. split.\nCase \"forward\".\nintro H. induction l as [| h tl].\n   SCase \"nil for l\". reflexivity.\n   SCase \"inductive case\". simpl. inversion H. rewrite H2.\n   simpl. apply IHtl. apply H3.\n\nCase \"backward\".\nintro H. induction l as [| h tl].\n    SCase \"nil for l\". apply all_nil. \n    SCase \"inductive case\". apply all_recursive.\n    simpl in H. apply andb_true_elim1 in H. apply H.\n    simpl in H. apply andb_true_elim2 in H. apply IHtl. apply H.\nQed.    \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].)  *)\nInductive in_order_merge {X:Type}: list X -> list X -> list X -> Prop :=\n| nil_l : forall l, in_order_merge nil l l\n| l_nil : forall l, in_order_merge l nil l\n| head_l: forall (x:X) (l1 l2 l: list X), \n  in_order_merge l1 l2 l -> in_order_merge (x::l1) l2 (x::l)\n| l_head: forall (x:X) (l1 l2 l: list X), \n  in_order_merge l1 l2 l -> in_order_merge l1 (x::l2) (x::l).\n\nLemma all_false_filter_empty : forall (X : Type) (l : list X) (test: X->bool), \nall X (fun x => test x = false) l -> filter test l = [].\nProof.\nintros. induction l as [| hd tl].\nCase \"[]\". reflexivity.\nCase \"hd :: l'\".\ninversion H.\napply IHtl in H3.\nsimpl. rewrite H2. apply H3.\nQed.\n\nLemma all_true_filter_full : forall (X : Type) (l : list X) (test: X->bool), \nall X (fun x => test x = true) l -> filter test l = l.\nProof.\nintros. induction l as [| hd tl].\nCase \"[]\". reflexivity.\nCase \"hd :: l'\".\ninversion H.\napply IHtl in H3.\nsimpl. rewrite H2. rewrite H3.\nreflexivity. Qed.\n\n\nTheorem filter_challenge : forall (X : Type) (l l1 l2 : list X) (test : X -> bool),\nall X  (fun x => test x = true) l1 ->\nall X  (fun x => test x = false) l2 ->\nin_order_merge l1 l2 l -> \nfilter test l = l1.\nProof.\nintros.  induction H1. \nCase \"nil_l \". apply all_false_filter_empty.  apply H0.\nCase \"l_nil\".  apply all_true_filter_full.   apply H.\nCase \"head_l \". inversion H. apply IHin_order_merge in H5. simpl.\n                rewrite H4. rewrite H5. reflexivity.\n                apply H0.\nCase \"l_head\". inversion H0. simpl. rewrite H4. \n               apply IHin_order_merge. apply H. apply H5.\nQed.\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*)\nCheck ai_later.\nCheck ai_here.\nDefinition appears_example : forall x y : nat, appears_in  4 [x, 4, y]:=\nfun x y => ai_later 4 x [4, y] (ai_here 4 [y]).\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.\nintros. induction xs as [|h l'].\nCase \"xs = []\". simpl in H. apply or_intror. apply H.\nCase \"xs = h :: l'\". inversion H. \n      SCase \"ai_here\". rewrite <- H1. apply or_introl. apply ai_here.\n      SCase \"ai_later\". apply IHl' in H1. inversion H1. apply or_introl.    \n                        apply ai_later. apply H3.\n                        apply or_intror. apply H3.\nQed.\n\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.\nintros. inversion H. \nCase \"left\".\ninduction xs as [| hd l]. \n        SCase \"xs = []\". inversion H0.\n        SCase \"xs = hd :: l\". inversion H0. apply ai_here. \n                unfold app. apply ai_later. assert (appears_in x l \\/ appears_in x ys).\n                apply or_introl. apply H2. apply IHl in H4. apply H4. apply H2.\nCase \"right\".\ninduction xs as [| hd l]. \n        SCase \"xs = nil\". apply H0.\n        SCase \"xs = hd :: l\". apply ai_later. assert (appears_in x l \\/ appears_in x ys).\n                  apply or_intror. apply H0. apply IHl in H1. apply H1.\nQed.\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\nDefinition disjoint (X:Type) (l1 l2 : list X) :=\n    forall x:X, appears_in x l1 -> not (appears_in x l2).\n\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\nInductive no_repeats (X : Type) : list X -> Prop := \n| nil_case : no_repeats X nil\n| head_case : forall x l, ~(appears_in x l) -> no_repeats X l \n                                           -> no_repeats X (x::l).\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(*I proved two related theorems*)\nLemma head_not_appears : forall (X : Type) (x:X) (l1 l2 : list X), \nno_repeats X ((x::l1) ++ l2) -> ~ appears_in x l2.\nProof.\nintros. \ninduction l1 as [| hd l'].\nsimpl in H. inversion H. apply H2.\nsimpl in H. inversion H. inversion H3.\n\nassert (~ appears_in x (l'++l2)). unfold not.\nintro. assert (appears_in x (hd::l'++l2)). apply ai_later. apply H8.\nunfold not in H2. apply H2 in H9. apply H9.\n\napply IHl'. apply head_case. apply H8. apply H7.\nQed.\n\n\nTheorem disjoint_no_repeats : forall (X : Type) (l1 l2 : list X),\n no_repeats X (l1 ++ l2) -> disjoint X l1 l2.\nProof.\nintros. induction l1 as [| x l'].\nCase \"l1 = nil\".\nunfold disjoint. intros z H1.  inversion H1.\nCase \"l1 = x :: l'\".\ninversion H. apply IHl' in H3. \n\nassert (~ appears_in x l2). apply head_not_appears with (l1:=l').\napply H.\n\nunfold disjoint. intros. inversion H5.\n      SCase \"x1 = x\". apply H4.\n      SCase \"x1 is not head\". unfold disjoint in H3.\n             apply H3 in H7. apply H7.\nQed.\n\n\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  (* FILL IN HERE *) Admitted.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof. \n  intros n m.  generalize dependent n.  induction m. \n  (* FILL IN HERE *) Admitted. \n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof. \n (* FILL IN HERE *) Admitted.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_n_Sn_false : forall n m,\n  ble_nat n (S m) = false ->\n  ble_nat n m = false.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  (* Hint: Do the right induction! *)\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (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 | nil_nostutter : nostutter nil\n | one_nostutter : forall (x : nat), nostutter [x]\n | two_nostutter : forall (x y : nat), (x <> y) -> nostutter [x,y]\n | heads_nostutter : forall (x y : nat) (l : list nat), \n                            nostutter (y :: l) -> (x <> y) -> 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_false_not_eq; auto. Qed.\n\nExample test_nostutter_2:  nostutter [].\nProof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n\nExample test_nostutter_3:  nostutter [5].\nProof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n\nExample test_nostutter_4:      not (nostutter [3,1,1,4]).\n  Proof. intro.\n  repeat match goal with \n    h: nostutter _ |- _ => inversion h; clear h; subst \n  end.\n  contradiction H5;  auto. contradiction H5. auto.\nQed.\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. \nintros. induction l1 as [| hd tl].\nCase \"l1 = []\".\nreflexivity.\nCase \"l1 = hd :: tl\".\nsimpl. rewrite IHtl. reflexivity.\nQed.\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.\nintros.\ninduction l as [| hd tl].\nCase \"l = nil\".\ninversion H.\nCase \"l = hd :: tl\".\ninversion H. SCase \"x = hd\". exists nil. exists tl. reflexivity.\n             SCase \"ai_later\". apply IHtl in H1. inversion H1 as [l1' Hl2].\n                               inversion Hl2 as [l2' Hl12]. \n                               exists (hd::l1'). exists (l2'). simpl.\n                               rewrite Hl12. reflexivity.\nQed.\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 | repeat_head : forall (x : X) (l : list X), appears_in x l -> repeats (x::l)\n | repeat_tail : forall (x : X) (l : list X), 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 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\nLemma pigeonhole_helper: forall {X:Type} (x y : X) (l1 l2 : list X),\nappears_in x (l1++(y::l2)) -> x<>y -> appears_in x (l1++l2).\nProof.\nintros. induction l1 as [| hd tl].\nCase \"l1 = nil\". simpl in H. inversion H. contradiction H0. apply H2.\nCase \"l1 = hd::tl\". inversion H. apply ai_here. \napply IHtl in H2. apply ai_later. apply H2.\nQed.\n\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. generalize dependent l2.\ninduction l1 as [| hd tl].\nCase \"l1 = nil\".\nintros. inversion H1.\nCase \"l1 = hd :: tl\".\nassert ((appears_in hd tl) \\/ (~ appears_in hd tl)).  \napply H.  \ninversion H0. intros.  \n   SCase \"repeat_head appears_in hd tl\". apply repeat_head. apply H1.\n   SCase \"repeat_tail ~ appears_in hd tl\". intros. \n          assert (appears_in hd l2). apply H2. apply ai_here.\n          apply appears_in_app_split in H4. inversion H4 as [ la Hb ].\n          inversion Hb as [lb]. \n          remember (la ++ lb) as l2'. apply repeat_tail.  apply IHtl with (l2:= l2').  \n\n          intros. assert (x <> hd). unfold not. intro. rewrite H7 in H6. \n          apply H1 in H6. apply H6. rewrite Heql2'. \n          apply ai_later with (b := hd) in H6. apply H2 in H6. rewrite H5 in H6.\n          apply pigeonhole_helper in H6. apply H6. apply H7.\n           \n          rewrite H5 in H3.  rewrite app_length in H3. simpl in H3.\n          rewrite <- plus_n_Sm in H3. rewrite <- app_length in H3. rewrite Heql2'.\n          apply Lt.lt_S_n. apply H3.\nQed.\n(** [] *)\n\n(* $Date: 2013-02-06 20:50:09 -0500 (Wed, 06 Feb 2013) $ *)\n\n\nInductive ptree (X:Type) : Type :=\n| c11 : X -> X -> ptree X\n| c21 : ptree X -> ptree X -> ptree X.\n\n\n\n\n\n\n\n\n\n\n\nDefinition exam_test1 : forall (P Q R : Prop), (P \\/ Q -> R) -> Q -> R :=\nfun (P Q R : Prop) => fun (H: P \\/ Q -> R) (X:Q) => H (or_intror P Q X).\nCheck le_n. Check (le_n 1 ).\n\n(*Fixpoint remove {X:Type} (l1 : list X) (x: X) : list X :=\nmatch l1 with\n[] => []\n|hd::l1' => if hd = x then l1' else [hd]++ remove l1' x\nend. *)\n", "meta": {"author": "steven7woo", "repo": "Coq-CIS500", "sha": "405653248c19d78ec35f4b7bc2b2144c4aa92738", "save_path": "github-repos/coq/steven7woo-Coq-CIS500", "path": "github-repos/coq/steven7woo-Coq-CIS500/Coq-CIS500-405653248c19d78ec35f4b7bc2b2144c4aa92738/For_wenrui/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.6765167113064541}}
{"text": "\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** \n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Lesson 8: summary\n\n- OOP with mix-ins\n- subtypes & automation\n\nLet's remember the truth:\n\n#<div style='color: red; font-size: 150%;'>#\nCoq is an object oriented\nprogramming language.\n#</div>#\n\n\n#</div>#\n----------------------------------------------------------\n#<div class=\"slide\">#\n** OOP\n\n# <img style=\"width: 100%\" src=\"demo-support-master.png\"/>#\n\nLet's see another interface, the one of finite types\n\n#<div>#\n*)\n\nPrint Finite.class_of. (* we extend choice with a mix in *)\n\nPrint Finite.mixin_of. (* we mix in countable and two specific\n                          fields: an enumeration and an axiom *)\n\nPrint Finite.axiom.\nPrint count_mem.\n\nEval lazy in count_mem 3 [:: 1;2;3;4;3;2;1].\n\n(* The property of finite types is that *)\n\nCheck fun (T : eqType) (enum : seq T) =>\n        forall x : T, count_mem x enum = 1.\n\nSection Example.\n\nVariable T : finType.\n\n(* Cardinality of a finite type *)\nCheck #| T |.\n\n(* \"bounded\" quantification *)\nCheck [forall x : T, x == x] && false.\nFail Check (forall x : T, x == x) && false.\n\nEnd Example.\n\n\n(**\n#</div>#\n\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\nThis slide corresponds to\nsection 6.1 and 6.2 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#<p><br/><p>#\n#</div>#\n\n\n\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Sub types\n\nA sub type extends another type by adding a property.\nThe new type has a richer theory.\nThe new type inherits the original theory.\n\nLet's define the type of homogeneous tuples\n\n#<div>#\n*)\n\nModule Tup.\n\nRecord tuple_of n T := Tuple {\n  tval  :> seq T;\n  tsize :  size tval == n\n}.\nNotation \"n .-tuple\" := (tuple_of n) : type_scope.\n\nLemma size_tuple T n (t : n .-tuple T) : size t = n.\nProof. by case: t => s /= /eqP. Qed.\n\nExample seq_on_tuple (n : nat) (t : n .-tuple nat) :\n  size (rev [seq 2 * x | x <- rev t]) = size t.\nProof. \nby rewrite map_rev revK size_map.\nUndo.\nrewrite size_tuple.\nFail rewrite size_tuple.\nAbort.\n\n\n(**\n#</div>#\n\nWe instrument Coq to automatically promote\nsequences to tuples.\n\n#<div>#\n*)\n\nLemma rev_tupleP n A (t : n .-tuple A) : size (rev t) == n.\nProof. by rewrite size_rev size_tuple. Qed.\nCanonical rev_tuple n A (t : n .-tuple A) := Tuple (rev_tupleP t).\n\nLemma map_tupleP n A B (f: A -> B) (t: n .-tuple A) : size (map f t) == n.\nProof. by rewrite size_map size_tuple. Qed.\nCanonical map_tuple n A B (f: A -> B) (t: n .-tuple A) := Tuple (map_tupleP f t).\n\nExample seq_on_tuple2 n (t : n .-tuple nat) :\n  size (rev [seq 2 * x | x <- rev t]) = size t.\nProof. rewrite size_tuple. rewrite size_tuple. by []. Qed.\n\n(**\n#</div>#\n\nReamrk how [t] is a tuple, then it becomes a list by going\ntrough rev and map, and is finally \"promoted\" back to a tuple\nby this [Canonical] magic.\n\n\nNow we the tuple type to form an eqType,\nexactly as seq does.\n\nWhich is the expected comparison for tuples?\n\n#<div>#\n*)\n\nLemma p1 : size [:: 1;2] == 2. Proof. by []. Qed.\nLemma p2 : size ([:: 1] ++ [::2]) == 2. Proof. by rewrite cat_cons cat0s. Qed.\n\nDefinition t1 := {| tval := [::1;2];        tsize := p1 |}.\nDefinition t2 := {| tval := [::1] ++ [::2]; tsize := p2 |}.\n\nLemma tuple_uip : t1 = t2.\nProof.\nrewrite /t1 /t2. rewrite /=.\nFail by [].\ncongr (Tuple _).\nFail by [].\n(*About bool_irrelevance.*)\napply: bool_irrelevance.\nQed.\n\n(**\n#</div>#\n\nGiven that propositions are expressed (whenever possible)\nas booleans we can systematically prove that proofs\nof these properties are irrelevant.\n\nAs a consequence we can form subtypes and systematically\nprove that the projection to the supertype is injective,\nthat means we can craft an eqType.\n\n#<div>#\n*)\n\n\nCanonical tuple_subType n T := Eval hnf in [subType for (@tval n T)].\nDefinition tuple_eqMixin n (T : eqType) := Eval hnf in [eqMixin of n .-tuple T by <:].\nCanonical tuple_eqType n (T : eqType) := Eval hnf in EqType (n .-tuple T) (tuple_eqMixin n T).\n\nCheck [eqType of 3.-tuple nat].\n\nExample test_eqtype (x y : 3.-tuple nat) : x == y -> True.\nProof.\nmove=> /eqP H.\nAbort.\n\nEnd Tup.\n\n(**\n#<div/>#\n\nTuples is are part of the library, that also contains\nmany other \"promotions\"\n\n#<div>#\n*)\n\nCheck [finType of 3.-tuple bool].\nFail Check [finType of 3.-tuple nat].\n\n(**\n#<div/>#\n\nTuples is not the only subtype part of the library.\nAnother one is ['I_n], the finite type of natural\nnumbers smaller than n.\n\n#<div>#\n*)\n\nPrint ordinal.\nCheck [eqType of 'I_3].\nCheck [finType of 'I_3].\n\nAbout tnth. (* like the safe nth function for vectors *)\n\n(**\n#<div/>#\n\nIt is easy to combine these bricks by subtyping (and \"specialization\")\n\n#<div>#\n*)\n\nCheck {set 'I_4} : Type.\nCheck forall a : {set 'I_4}, (a == set0) || (1 < #| a | < 4).\nPrint set_type.\nCheck {ffun 'I_4 -> bool} : Type.\nPrint finfun_type.\nCheck [eqType of #| 'I_4 | .-tuple bool].\nCheck [finType of #| 'I_4 | .-tuple bool].\n\nCheck {ffun 'I_4 * 'I_6 -> nat} : Type.\nCheck [eqType of {ffun 'I_4 * 'I_6 -> nat}] : Type.\n\nFrom mathcomp Require Import all_algebra.\nOpen Scope ring_scope.\n\nPrint matrix.\n\nSection Rings.\n\nVariable R : ringType.\n\nCheck forall x : R, x * 1 == x.\n\nCheck forall m : 'M[R]_(4,4), m == m * m.\n\nEnd Rings.\n\n(**\n#</div>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\nThis slide corresponds to\nsection 6.1 and 6.2 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#<p><br/><p>#\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Sum up\n\n- subtypes add properties and inherit the theory of the supertype\n  thanks to boolean predicates (UIP).\n  In some cases the property can be inferred by Coq, letting one apply\n  a lemma about the subtype on terms of the supertype.\n\n\n#</div>#\n\n*)\n", "meta": {"author": "gares", "repo": "COQWS18", "sha": "2d438b94357d4be0baf47808db111214f08db467", "save_path": "github-repos/coq/gares-COQWS18", "path": "github-repos/coq/gares-COQWS18/COQWS18-2d438b94357d4be0baf47808db111214f08db467/lesson8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830605, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.6765167099313495}}
{"text": "Set Implicit Arguments.\nSet Asymmetric Patterns.\nRequire Import Cpdt.CpdtTactics.\nRequire Import Classical_Prop.\nRequire Import List.\nRequire Import Bool.Bool.\n\nDefinition var := nat % type. \nDefinition total_map := var -> bool.\nDefinition t_empty : total_map :=\n  (fun _ => false).\nDefinition t_update (m : total_map)\n                    (x : var) (v : bool) :=\n  fun x' => if PeanoNat.Nat.eqb x x' then v else m x'.\n(* to create an empty total map with default value *)\nNotation \"'_' '!->' v\" := t_empty\n                            (at level 100, right associativity).\n(* extending existing map with some bindings *)\nNotation \"x '!->' v ';' m\" := (t_update m x v)\n                              (at level 100, v at next level, right associativity).\n\nLemma t_update_eq : forall (m : total_map) x v,\n  (x !-> v ; m) x = v.\nProof. intros. \n       unfold t_update. rewrite PeanoNat.Nat.eqb_refl. crush. Qed. \n\nDefinition tvals := total_map.\n\nInductive formula : Set :=\n| Var : var -> formula\n| Not : var -> formula\n| Disj : formula -> formula -> formula                        \n| Conj : formula -> formula -> formula.   \n\nDefinition eq_nat_dec (n m : var) : {n = m} + {n <> m}.\ndecide equality.\nDefined.\n(* \nDefinition In_lst (x : var) (ls : list var) : {In x ls} + {~(In x ls)}.\n  induction ls.\n  - crush.\n  - inversion IHls.\n    left. crush.\n    destruct (eq_nat_dec x a).\n    + left. crush.\n    + right. crush. \nDefined.       \n\nFixpoint remove_dups ls : list var :=\n  match ls with\n  | nil => nil\n  | x :: xs => match (In_lst x xs) with \n                 | left _ => remove_dups xs\n                 | right _ => x :: remove_dups xs \n                 end\n  end.            \n *)\n\nDefinition nodup_var := nodup eq_nat_dec. \n\nFixpoint vars_in_formula f : list var :=\n  match f with\n  | Var v => v :: nil\n  | Not v => v :: nil\n  | Disj f1 f2 => nodup_var (vars_in_formula f1 ++ vars_in_formula f2)             \n  | Conj f1 f2 => nodup_var (vars_in_formula f1 ++ vars_in_formula f2)\n  end.                                 \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 for convenient usage of type maybe. *)\nNotation \"{{ x | P }}\" := (maybe (fun x => P)).\nNotation \"??\" := (Unknown _ ).\nNotation \"[| x |]\" := (Found _ x _).\n\nFixpoint evalFormula f map {struct f} : bool :=\n  match f with\n  | Var v => map v \n  | Not v => negb (map v)  \n  | Disj f1 f2 => orb (evalFormula f1 map) (evalFormula f2 map)  \n  | Conj f1 f2 => andb (evalFormula f1 map) (evalFormula f2 map)\n  end.  \n\nFixpoint CreateAllFalsesMap (ls : list var) map : tvals :=\n  match ls with\n  | nil => map\n  | x :: xs => CreateAllFalsesMap xs (x !-> false ; map) \n  end.                                 \n\nEval simpl in CreateAllFalsesMap (1 :: 2 :: 3 :: nil) t_empty.\n(* remove_dups (vars_in_formula_dupl f) - all vars in formula \n\ncheckVars начинает работу с карты, на которой all vars = false. \n1) пробует изменить первую вару на тру. если нашли решение - возвращаем \n2) \n\n*)\n\nDefinition checkVars : forall (ls : list var) (f : formula) (map : tvals), {{ map' | evalFormula f map' = true }}.\n  refine (fix F (ls : list var) (f : formula) (map : tvals) : {{ map' | evalFormula f map' = true }} := \n  match ls with\n  | nil => _\n  | x :: xs => match F xs f (x !-> true; map) with\n               | ?? => F xs f (x !-> false; map)\n               | res => res\n               end\n  end).\n  destruct (evalFormula f map) eqn:E.\n  - eapply (Found _ map E).\n  - apply ??.\nDefined.     \n\nDefinition f :=  (Disj (Var 1) (Disj (Var 2) (Not 3))).\nEval simpl in checkVars (nodup_var (vars_in_formula f)) f t_empty.\n\nDefinition f1 :=  (Conj (Var 1) (Not 1)).\nEval simpl in checkVars ((vars_in_formula f1)) f1 t_empty.\n\nSearch PeanoNat.Nat.eqb.\nLocate PeanoNat.Nat.eqb.\nCheck PeanoNat.Nat.eqb.\n\nPrint In. \n(* отличается от библиотечного In тем, что возвращает bool, а не Prop *)\nFixpoint In_var_ls' (x : var) (ls : list var) : bool :=\n  match ls with\n  | nil => false\n  | x' :: xs => match PeanoNat.Nat.eqb x x' with\n                | true => true\n                | false => In_var_ls' x xs\n                end                     \n  end.                                                                   \n\nEval simpl in In_var_ls' 0 (1 :: 2 :: 3 :: nil).\n\nLocate reflect.\nPrint Coq.Bool.Bool.reflect.\n(*\nInductive reflect (P : Prop) : bool -> Set :=\n    ReflectT : P -> reflect P true | ReflectF : ~ P -> reflect P false\n*)\nLemma In_reflect : forall x ls, reflect (In x ls) (In_var_ls' x ls).\n  intros. induction ls.\n  - crush.\n  - destruct (PeanoNat.Nat.eqb x a) eqn:E.\n    + crush. constructor. left.\n      apply PeanoNat.Nat.eqb_eq. rewrite PeanoNat.Nat.eqb_sym. auto.\n    + crush. inversion IHls. constructor. crush. constructor. crush. \n      Search PeanoNat.Nat.eqb. assert (H' : PeanoNat.Nat.eqb x x = true ).\n      apply (PeanoNat.Nat.eqb_refl x). crush. \nQed.   \n\n(* Definition In_var_ls : forall x ls, {In_var_ls' x ls = true} + {~(In_var_ls' x ls = true)}. *)\n\nInductive formula_List_Vars : list var -> formula -> Set := \n| FVars_Var : forall v ls, In_var_ls' v ls  = true -> formula_List_Vars ls (Var v)\n| FVars_Not : forall v ls, In_var_ls' v ls = true -> formula_List_Vars ls (Not v)\n| FVars_Disj : forall f1 f2 ls1 ls2, formula_List_Vars ls1 f1->\n                                     formula_List_Vars ls2 f2 ->\n                                     formula_List_Vars (nodup_var (ls1 ++ ls2)) (Disj f1 f2)\n| FVars_Conj : forall f1 f2 ls1 ls2, formula_List_Vars ls1 f1 ->\n                                     formula_List_Vars ls2 f2 ->\n                                     formula_List_Vars (nodup_var (ls1 ++ ls2)) (Conj f1 f2).\nSearch list. \nInductive formula_List_Vars_sub : list var -> formula -> Set := \n| FVars_Var : forall v ls, In_var_ls' v ls  = true -> formula_List_Vars ls (Var v)\n| FVars_Not : forall v ls, In_var_ls' v ls = true -> formula_List_Vars ls (Not v)\n| FVars_Disj : forall f1 f2 ls1 ls2, formula_List_Vars ls1 f1->\n                                     formula_List_Vars ls2 f2 ->\n                                     formula_List_Vars (nodup_var (ls1 ++ ls2)) (Disj f1 f2)\n| FVars_Conj : forall f1 f2 ls1 ls2, formula_List_Vars ls1 f1 ->\n                                     formula_List_Vars ls2 f2 ->\n                                     formula_List_Vars (nodup_var (ls1 ++ ls2)) (Conj f1 f2).\n\n\nLemma flv : forall f, formula_List_Vars (vars_in_formula f) f.\n  intros. induction f0.\n  - crush. constructor. crush. rewrite (PeanoNat.Nat.eqb_refl v). reflexivity.\n  - crush. constructor. crush. rewrite (PeanoNat.Nat.eqb_refl v). reflexivity.\n  - simpl. constructor. crush. crush.\n  - simpl. constructor. crush. crush. \nQed.\n\nFixpoint eq_map (ls : list var) (m1 m2 : tvals) : bool :=\n  match ls with\n  | nil => true\n  | x :: xs => if eqb (m1 x) (m2 x) then eq_map xs m1 m2 else false\n  end.                                                              \n\nNotation \"m1 '==(' vrs ')' m2\" := (eq_map vrs m1 m2 = true) (at level 50).\n\nLemma inFalse : forall v vrs m1, In_var_ls' v vrs = true -> (v !-> true ; m1) ==(vrs) (v !-> false ; m1). Admitted.\n\nInductive formulaTrue : tvals -> formula -> Prop :=\n| TVar : forall tv var, tv var = true -> formulaTrue tv (Var var)\n| TNot : forall tv var, tv var = false -> formulaTrue tv (Not var)\n| TDisj : forall f1 f2 tv, formulaTrue tv f1 \\/ formulaTrue tv f2 ->\n                           formulaTrue tv (Disj f1 f2)\n| TConj : forall f1 f2 tv, formulaTrue tv f1 -> formulaTrue tv f2 -> formulaTrue tv (Conj f1 f2). \n\nInductive formula_map : tvals -> formula -> Set :=\n| FM_Var_True : forall map var, map var = true -> formula_map map (Var var)\n| FM_Var_False : forall map var, map var = false -> formula_map map (Var var)\n| FM_Not_True : forall map var, map var = true -> formula_map map (Not var)\n| FM_Not_False : forall map var, map var = false -> formula_map map (Not var)\n| FM_Disj : forall f1 f2 map, formula_map map f1 ->\n                              formula_map map f2 ->\n                              formula_map map (Disj f1 f2)\n| FM_Conj : forall f1 f2 map, formula_map map f1 ->\n                              formula_map map f2 ->\n                              formula_map map (Conj f1 f2).\n\nLemma t_empty_map : forall f, formula_map t_empty f.\n  intros. induction f0. apply FM_Var_False. unfold t_empty. auto.\n  apply FM_Not_False. unfold t_empty. auto. constructor. auto. crush. constructor. crush. crush. \nQed.\n\nDefinition checkOneMap (f : formula) (map : tvals) : {formulaTrue map f} + {~formulaTrue map f}.\n  Hint Constructors formulaTrue.\n  induction f.\n  - destruct (map v) eqn:G. left. constructor. auto. right.\n      unfold not. intros. inversion H. crush. \n  - destruct (map v) eqn:G. right; crush. inversion H. crush.\n    left. constructor. auto.\n  - inversion IHf1; inversion IHf2; crush. right. intros. inversion H1. crush.\n  - inversion IHf1; inversion IHf2; crush. right. intros. inversion H1. crush.\n    right. intros. inversion H1. crush. right. intros. inversion H1. crush. \nDefined.   \n\nLemma not_nil : forall f, formula_List_Vars nil f -> forall truth, ~ formulaTrue truth f.\n  intros.\n  induction f0.\n  - crush. inversion H. inversion H3.\n  - crush. inversion H. inversion H3.\n  - unfold not. intros. inversion H. crush.\n    inversion H0.\n    (* доказать, что ls1 = nil /\\ ls2 = nil, subst.  *)\nAdmitted. \n\nDefinition CheckFormulaHelp : forall f ls map, formula_List_Vars_sub ls f -> formula_map map f -> {truth : tvals | formulaTrue truth f } + {forall truth, ~ formulaTrue truth f }.\nrefine (fix F f ls map pf1 pf2 : {truth : tvals | formulaTrue truth f } + {forall truth, ~ formulaTrue truth f } :=\n          match ls return {truth : tvals | formulaTrue truth f } + {forall truth, ~ formulaTrue truth f } with\n          | nil => _\n          | x :: xs => match F f xs (x !-> true; map) _ _ with\n                       | ?? => F xs f (x !-> false; map)\n                       | res => res\n                       end\n          end).                  \n- admit. \n- \n\n  Definition CheckFormula (f : formula) : {truth : tvals | formulaTrue truth f } + {forall truth, ~ formulaTrue truth f } := @CheckFormulaHelp f (vars_in_formula f) t_empty (flv f) (t_empty_map f). \n\n\nDefinition checkFormula : forall (f : formula) (pf :  formula_List_Vars (vars_in_formula f) f),\n    {truth : tvals | evalFormula f truth = true } + {forall truth, evalFormula f truth = false}.\nrefine (fix F f pf : {truth : tvals | evalFormula f truth = true } + {forall truth, evalFormula f truth = false} :=\n          match f return {truth : tvals | evalFormula f truth = true } + {forall truth, evalFormula f truth = false} with\n          | Var v => _\n          | Not v => _\n          | Disj f1 f2 => _\n          | Conj f1 f2 => _\n          end).                  \n\n(* Definition CheckFormulaHelp : forall f ls map, formula_List_Vars ls f -> formula_map map f -> *)\n(*   {truth : tvals | formula_map truth f -> formulaDenote truth f = true} + {forall truth, formula_map truth f ->  evalFormula truth f = false}. *)\n\nDefinition checkVars : forall (ls : list var) (f : formula) (map : tvals), {{ map' | evalFormula f map' = true }}.\n\n1. как показать, что если ls = nil то map уже не удастся изменять. Не нашли\n2. как показать, что если map изменить нельзя, то не существует возможной оценки.\n3. что значит, что map изменять нельзя.\n\nDefinition checkVars' : forall (ls : list var) (f : formula) (map : tvals), { map' | evalFormula f map' = true } + {\nforall map', map'\nevalFormula f map' = false\n                                                                                                                   }.\n  \n  refine (fix F (ls : list var) (f : formula) (map : tvals) : { map' | evalFormula f map' = true } + {forall map', evalFormula f map' = false} := \n  match ls with\n  | nil => _\n  | x :: xs => match F xs f (x !-> true; map) with\n               | ?? => F xs f (x !-> false; map)\n               | res => res\n               end\n  end).\n  destruct (evalFormula f map) eqn:E.\n  - eapply (Found _ map E).\n  - apply ??.\nDefined.     \n\n(* BELOW NAT\"S DEFINITIONS *)\n\n\n\n\nInductive formulaTrue : tvals -> formula -> Prop :=\n| TVar : forall tv var, tv var = Some true -> formulaTrue tv (Lit (Var var))\n| TNot : forall tv var, tv var = Some false -> formulaTrue tv (Lit (Not var)).\n\n(* что список принадлежит формуле (это ее контекст) with duplicates, I probably don't need this Prop *)\nInductive formula_List_Vars : list var -> formula -> Prop := \n| FVars_Var : forall var ls, In var ls -> formula_List_Vars ls (Lit (Var var))\n| FVars_Not : forall var ls, In var ls -> formula_List_Vars ls (Lit (Not var)).\n\n(* что мапа принадлежит формуле, может формула и не true на этой мапе. НАДО? *)\nInductive formula_map : tvals -> formula -> Set :=\n| FM_Var_True : forall map var, map var = Some true -> formula_map map (Lit (Var var))\n| FM_Var_False : forall map var, map var = Some false -> formula_map map (Lit (Var var))\n| FM_Not_True : forall map var, map var = Some true -> formula_map map (Lit (Not var))\n| FM_Not_False : forall map var, map var = Some false -> formula_map map (Lit (Not var)).\n\nInductive formula_all_maps : list tvals -> formula -> Type :=\n| FAM_Var : forall map ls v, In map ls -> formula_map map (Lit (Var v)) -> length ls = 2  -> formula_all_maps ls (Lit (Var v))\n| FAM_Not : forall map ls v, In map ls -> formula_map map (Lit (Not v)) -> length ls = 2  -> formula_all_maps ls (Lit (Not v)).\n\nTheorem all_maps_not_nil : forall f, formula_all_maps nil f -> False.\n  intros. induction f; destruct l; crush. inversion X. crush. inversion X. crush. \nQed. \n\nDefinition checkOneMap (f : formula) (map : tvals) : {formulaTrue map f} + {~formulaTrue map f}.\n  Hint Constructors formulaTrue.\n  induction f.\n  - induction l.\n    + destruct (map v) eqn:G. destruct b eqn:E. left. constructor. auto. right.\n      unfold not. intros. inversion H. crush. right. unfold not. intros. inversion H. crush.\n    + destruct (map v) eqn:G. (destruct b); crush. right; crush. inversion H. crush.\n      right. unfold not. intros. inversion H. crush.\nDefined.       \n\nDefinition equal_maps_on_formula (m1 m2 : tvals) : Prop :=\n  forall (v : var) (f : formula) (ls : list var), formula_List_Vars ls f /\\ m1 v = m2 v /\\ In v ls.\n\n(* теорема в своем док-ве опирается на длину списка всех возможных для формулы мапов *)\nTheorem FAM : forall f t, formula_all_maps (t :: nil) f -> ~ formulaTrue t f -> (forall truth, ~formulaTrue truth f ).\n  intros. unfold not. intros.\ninversion X. crush. crush. Qed. \n\n(* ПЛАН РАБОТЫ \n0) ввести длину списка в formula_all_maps\n0) переписать определение (In map tvals) чтобы оно было ориентировано на tvals \n1) создать подтип от formula_all_maps, formula_all_maps_sub : list tvals -> formula -> n\n*)\n\nDefinition checkFormula : forall f : formula, {truth : tvals | formulaTrue truth f } + {forall truth, ~formulaTrue truth f }.\n  intros f.\n  assert (H : formula_List_Vars (remove_dups (vars_in_formula_dupl f)) f ).\n  { induction f. induction l. simpl. constructor. crush. simpl. constructor. crush. }\n  assert (G : formula_all_maps (makeAllMaps (remove_dups (vars_in_formula_dupl f)) ( (CreateAllFalsesMap (remove_dups (vars_in_formula_dupl f)) empty) :: nil)) f).\n  { induction f.\n    - induction l.\n      + simpl in H. simpl. eapply FAM_Var. simpl. crush. constructor.\n        rewrite update_shadow. rewrite update_eq. reflexivity. crush. \n      + simpl in H. simpl. eapply FAM_Not. simpl. crush. constructor.\n        rewrite update_shadow. rewrite update_eq. reflexivity. crush. \n  }\n  remember (remove_dups (vars_in_formula_dupl f)) as fav.\n  remember (makeAllMaps fav (CreateAllFalsesMap fav empty :: nil)) as fam.\n  clear Heqfav H Heqfam fav.\n    generalize dependent f. generalize dependent fam.\n  refine (fix F fam f pf :  {truth : tvals | formulaTrue truth f} + {forall truth : tvals, ~ formulaTrue truth f} :=\n            match f return  {truth : tvals | formulaTrue truth f} + {forall truth : tvals, ~ formulaTrue truth f}\n            with\n            | Lit (Var v) => _\n            | Lit (Not v) => _\n            end).                 \n  - destruct fam.\n    + crush. apply all_maps_not_nil in pf. inversion pf.\n    + \n\n\n  \n\n  - admit.\n  - left. exists x. auto. \n  - \n    \n", "meta": {"author": "klausnat", "repo": "SAT-solver-DPLL-CNF", "sha": "cd8e31deb86ac8585ed81730a60cc4e4cb8d6167", "save_path": "github-repos/coq/klausnat-SAT-solver-DPLL-CNF", "path": "github-repos/coq/klausnat-SAT-solver-DPLL-CNF/SAT-solver-DPLL-CNF-cd8e31deb86ac8585ed81730a60cc4e4cb8d6167/Exercises_04_From_Subset_SAT_Solver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339636614181, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.6765167054282557}}
{"text": "Inductive bool := true | false.\n\nInductive even : nat -> Prop :=\n  | zero_even: even 0 \n  | ssn_even: forall n, even n -> even (S (S n)).\n\nLemma ev8 : even 8. apply ssn_even. apply ssn_even. apply ssn_even. apply ssn_even.\n                    apply zero_even.\n                    Qed.", "meta": {"author": "kolemannix", "repo": "oplss2015", "sha": "d2973dfbcb3bc345bec49841fb6c8bbf78d65a16", "save_path": "github-repos/coq/kolemannix-oplss2015", "path": "github-repos/coq/kolemannix-oplss2015/oplss2015-d2973dfbcb3bc345bec49841fb6c8bbf78d65a16/chlipala/dybjer_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6763973087879045}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Lists                                                                   *\n**************************************************************************)\n\nSet Implicit Arguments. \nGeneralizable Variables A B.\nRequire Import LibTactics LibLogic LibReflect LibOperation\n LibProd LibOption LibNat LibInt LibWf LibRelation.\nRequire Export List.\nOpen Local Scope nat_scope.\nOpen Local Scope comp_scope.\n\n\n\n(** Fixing implicit arguments *)\n\nImplicit Arguments nil [[A]].\nImplicit Arguments cons [[A]].\n\n\n(* ********************************************************************** *)\n(** * Inhabited *)\n\nInstance list_inhab : forall A, Inhab (list A).\nProof. intros. apply (prove_Inhab nil). Qed.\n\n\n(* ********************************************************************** *)\n(** * Logical predicates *)\n\nSection LogicList.\nVariables A A1 A2 B C : Type.\n\n(** [Forall P L] asserts that all the elements in the list [L]\n    satisfy the predicate [P]. *)\n\nInductive Forall (P : A -> Prop) \n  : list A -> Prop :=\n  | Forall_nil : \n      Forall P nil\n  | Forall_cons : forall l x, \n      P x -> Forall P l -> \n      Forall P (x::l).\n\n(** [Forall2 P L1 L2] asserts that the lists [L1] and [L2] \n    have the same length and that elements at corresponding\n    indices are related by the binary relation [P]. *)\n\nInductive Forall2 (P : A -> B -> Prop) \n  : list A -> list B -> Prop :=\n  | Forall2_nil : \n      Forall2 P nil nil\n  | Forall2_cons : forall l1 l2 x1 x2, \n      P x1 x2 -> Forall2 P l1 l2 -> \n      Forall2 P (x1::l1) (x2::l2).\n\n(** Similar to [Forall2] except that it relates three lists *)\n\nInductive Forall3 (P : A -> B -> C -> Prop) \n  : list A -> list B -> list C -> Prop :=\n  | Forall3_nil : \n      Forall3 P nil nil nil\n  | Forall3_cons : forall l1 l2 l3 x1 x2 x3, \n      P x1 x2 x3 -> Forall3 P l1 l2 l3 -> \n      Forall3 P (x1::l1) (x2::l2) (x3::l3).\n\n(** [exists P L] asserts that there exists a value in the\n    list [L] that satisfied the predicate [P]. *)\n\nInductive Exists (P : A -> Prop) \n  : list A -> Prop :=\n  | Exists_here : forall l x, \n      P x -> Exists P (x::l)\n  | Exists_next : forall l x, \n      Exists P l -> \n      Exists P (x::l).\n\n(** [exists2 P L1 L2] asserts that there exists an index [n]\n    such that the n-th element of [L1] and the n-th element\n    of [L2] are related by the binary relation [P]. *)\n\nInductive Exists2 (P : A1 -> A2 -> Prop) \n  : list A1 -> list A2 -> Prop :=\n  | Exists2_here : forall l1 l2 x1 x2,\n      P x1 x2 -> Exists2 P (x1::l1) (x2::l2)\n  | Exists2_next : forall l1 l2 x1 x2, \n      Exists2 P l1 l2 -> \n      Exists2 P (x1::l1) (x2::l2).\n\n(** [filters P L L'] asserts that [L'] is the sublist of [L]\n    made exactly of the elements of [L] that satisfy [P]. *)\n\nInductive Filters (P : A -> Prop) \n  : list A -> list A -> Prop :=\n  | Filters_nil : Filters P nil nil\n  | Filters_cons_yes : forall l l' x,\n      P x -> Filters P l l' -> \n      Filters P (x::l) (x::l')\n  | Filters_cons_no : forall l l' x,\n      ~ (P x) -> Filters P l l' -> \n      Filters P (x::l) l'.\n\n(** [Mem x l] asserts that [x] belongs to [M] *)\n\nInductive Mem (x:A) : list A -> Prop :=\n  | Mem_here : forall l, \n      Mem x (x::l)\n  | Mem_next : forall y l, \n      Mem x l -> \n      Mem x (y::l).\n\n(** [Nth n L x] asserts that the n-th element of the list [L]\n    exists and is exactly [x] *)\n\nInductive Nth : nat -> list A -> A -> Prop :=\n  | Nth_here : forall l x,\n      Nth 0 (x::l) x\n  | Nth_next : forall y n l x, \n      Nth n l x ->\n      Nth (S n) (y::l) x.\n\n(** [Assoc x v l] asserts that [(x,v)] the first pair of the \n    form [(x,_)] in [l] *)\n\nInductive Assoc (x:A) (v:B) : list (A*B) -> Prop :=\n  | Assoc_here : forall l , \n      Assoc x v ((x,v)::l)\n  | Assoc_next : forall y l (w:B), \n      Assoc x v l -> x <> y ->\n      Assoc x v ((y,w)::l).\n\n(** [has pair x1 x2 l1 l2] asserts that there exists an\n    index [n] such that the n-th element of [l1] is [x1]\n    and the n-th element of [l2] is [x2] *)\n\nDefinition has_pair x1 x2 l1 l2 :=\n  Exists2 (fun v1 v2 => v1 = x1 /\\ v2 = x2) l1 l2.\n\nLemma has_pair_here : forall x1 x2 l1 l2,\n  has_pair x1 x2 (x1::l1) (x2::l2).\nProof. intros. constructor~. Qed.\n\nLemma has_pair_next : forall x1 x2 y1 y2 l1 l2,\n  has_pair x1 x2 l1 l2 ->\n  has_pair x1 x2 (y1::l1) (y2::l2).\nProof. introv H. apply* Exists2_next. Qed.\n\nEnd LogicList.\n\n\n(* ********************************************************************** *)\n(** * Operations *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Operations on lists *)\n\nSection Folds.\nContext {A B : Type}.\nImplicit Types l a b : list A.\nImplicit Types x : A. \n\nFixpoint fold_right (f : A -> B -> B) (acc : B) l :=\n  match l with\n  | nil => acc\n  | x::L' => f x (fold_right f acc L')\n  end.\n\nFixpoint fold_left (f : A -> B -> B) (acc : B) l :=\n  match l with\n  | nil => acc\n  | x::L' => fold_left f (f x acc) L'\n  end.\n\nEnd Folds.\n\nSection Operations.\nVariables (A B C : Type) (IA : Inhab A). \nImplicit Types l a b : list A.\nImplicit Types x : A. \n\nDefinition map (f : A -> C) :=\n  nosimpl (fold_right (fun x acc => (f x)::acc) (@nil C)).\n\nDefinition filter (f : predb A) :=\n  nosimpl (fold_right (fun x acc => if f x then x::acc else acc) (@nil A)).\n\nDefinition append l1 l2 :=\n  nosimpl (fold_right (fun x (acc:list A) => x::acc) l2 l1).\n\nDefinition concat :=\n  nosimpl (fold_right append (@nil A)).\n\nDefinition rev :=\n  nosimpl (fold_left (fun x acc => x::acc) (@nil A)).\n\nDefinition length :=\n  nosimpl (fold_right (fun x acc => 1+acc) 0).\n\nDefinition for_all (f : predb A) := \n  nosimpl (fold_right (fun x acc => acc && (f x)) true).\n\nDefinition exists_st (f : predb A) := \n  nosimpl (fold_right (fun x acc => acc || (f x)) false).\n\nDefinition count (f : predb A) :=\n  nosimpl (fold_right (fun x acc => (if f x then 1 else 0) + acc) 0).\n\nFixpoint mem x l := \n  match l with\n  | nil => false\n  | y::l' => (x '= y) || mem x l'\n  end.\n\nFixpoint remove x l :=\n  match l with\n  | nil => nil\n  | y::l' => let acc := remove x l' in\n             If x = y then acc else y::acc\n  end.\n\nFixpoint removes l2 l1 :=\n  match l2 with\n  | nil => l1\n  | x::l2' => removes l2' (remove x l1) \n  end.\n\nFixpoint split (l: list (A*B)) : (list A * list B) :=\n  match l with \n  | nil => (nil,nil)\n  | (a,b)::l' => let (la,lb) := split l' in (a::la, b::lb)\n  end.\n\nFixpoint combine (la : list A) (lb : list B) : list (A*B) :=\n  match la with\n  | nil => nil\n  | a::la' =>\n    match lb with \n    | nil => arbitrary\n    | b::lb' => (a,b)::(combine la' lb')\n    end\n  end.\n\nFixpoint drop (n:nat) (l: list A) : list A :=\n  match n with \n  | 0 => l\n  | S n' => match l with\n    | nil => nil\n    | a::l' => drop n' l'\n    end\n  end.\n\nFixpoint take (n:nat) (l: list A) : list A :=\n  match n with \n  | 0 => nil\n  | S n' => match l with\n    | nil => nil\n    | a::l' => a::(take n' l')\n    end\n  end.\n\nFixpoint nth n l : A :=\n  match l with\n  | nil => arbitrary \n  | x::L' => \n     match n with\n     | 0 => x\n     | S n' => nth n' L'\n     end\n  end.\n\nEnd Operations.\n\nImplicit Arguments fold_left [[A] [B]].\nImplicit Arguments fold_right [[A] [B]].\nImplicit Arguments append [[A]].\nImplicit Arguments concat [[A]].\nImplicit Arguments rev [[A]].\nImplicit Arguments length [[A]].\nImplicit Arguments mem [[A]].\nImplicit Arguments remove [[A]].\nImplicit Arguments removes [[A]].\nImplicit Arguments nth [[A] [IA]].\n(* todo: implicit arguments for the other functions *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Notation *)\n\n(** [l1 ++ l2] concatenates two lists *)\n\nInfix \"++\" := append (right associativity, at level 60) : list_scope.\n\n(** [l & x] extends the list [l] with the value [x] at the right end *)\n\nNotation \"l & x\" := (l ++ (x::nil)) \n  (at level 28, left associativity) : list_scope.\n\n\n(* ********************************************************************** *)\n(** * Properties of operations *)\n\nSection AppFoldProperties.\nVariable A B : Type.\nImplicit Types x : A.\nImplicit Types l : list A.\n\nLemma app_cons : forall x l1 l2,\n  (x::l1) ++ l2 = x::(l1++l2).\nProof. auto. Qed.\nLemma app_nil_l : forall l,\n  nil ++ l = l.\nProof. auto. Qed.\nLemma app_nil_r : forall l,\n  l ++ nil = l.\nProof. induction l. auto. rewrite app_cons. fequals~. Qed.\nLemma app_assoc : forall l1 l2 l3,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof. \n  intros. induction l1.\n  rewrite_all~ app_nil_l. \n  rewrite_all~ app_cons. fequals~.\nQed.\nLemma app_last : forall x l1 l2,\n  l1 ++ (x::l2) = (l1 & x) ++ l2.\nProof. intros. rewrite~ app_assoc. Qed.\nLemma app_last_sym : forall x l1 l2,\n  (l1 & x) ++ l2 = l1 ++ (x::l2).\nProof. intros. rewrite~ <- app_last. Qed.\nLemma app_cons_one : forall x l,\n  (x::nil) ++ l = x::l.\nProof. auto. Qed.\n\n\nSection FoldRight.\nVariables (f : A -> B -> B) (i : B).\nLemma fold_right_nil : \n  fold_right f i nil = i.\nProof. auto. Qed.\nLemma fold_right_cons : forall x l,\n  fold_right f i (x::l) = f x (fold_right f i l) .\nProof. auto. Qed.\nLemma fold_right_app : forall l1 l2,\n  fold_right f i (l1 ++ l2) = fold_right f (fold_right f i l2) l1.\nProof.\n  intros. induction l1. auto. \n  rewrite app_cons. simpl. fequals~.\nQed.\nLemma fold_right_last : forall x l,\n  fold_right f i (l & x) = fold_right f (f x i) l.\nProof. intros. rewrite~ fold_right_app. Qed.\nEnd FoldRight.\n\n\nSection FoldLeft.\nVariables (f : A -> B -> B) (i : B).\nLemma fold_left_nil : \n  fold_left f i nil = i.\nProof. auto. Qed.\nLemma fold_left_cons : forall x l,\n  fold_left f i (x::l) = fold_left f (f x i) l.\nProof. auto. Qed.\nLemma fold_left_app : forall l1 l2,\n  fold_left f i (l1 ++ l2) = fold_left f (fold_left f i l1) l2.\nProof.\n  intros. gen i. induction l1; intros. auto. \n  rewrite app_cons. simpl. rewrite~ IHl1.\nQed.\nLemma fold_left_last : forall x l,\n  fold_left f i (l & x) = f x (fold_left f i l).\nProof. intros. rewrite~ fold_left_app. Qed.\nEnd FoldLeft.\n\nEnd AppFoldProperties.\n\nSection LengthProperties.\nVariable A : Type.\nImplicit Types l : list A.\n\nLemma length_nil : \n  length (@nil A) = 0.\nProof. auto. Qed.\nLemma length_cons : forall x l,\n  length (x::l) = 1 + length l.\nProof. auto. Qed.\nLemma length_app : forall l1 l2,\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros. unfold length at 1. rewrite fold_right_app.\n  fold (length l2). induction l1; simple~.\nQed.\nLemma length_last : forall x l,\n  length (l & x) = 1 + length l.\nProof. \n  intros. rewrite length_app.\n  rewrite length_cons. rewrite length_nil.\n  simpl. math.\nQed.\nLemma length_zero_inv : forall l,\n  length l = 0%nat -> l = nil.\nProof.\n  destruct l. auto. rewrite length_cons. intros. false. \nQed.\n\nEnd LengthProperties.\n\nSection OperationProperties.\nVariable A B : Type.\nImplicit Types x : A.\nImplicit Types l : list A.\n\nLemma rev_nil : \n  rev (@nil A) = nil.\nProof. auto. Qed.\nLemma rev_app : forall l1 l2,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros. unfold rev. asserts K1: (forall l accu,\n   fold_left (fun x acc => x :: acc) accu l =\n   fold_left (fun x acc => x :: acc) nil l ++ accu).\n   induction l; intros; simpl. auto. \n   rewrite IHl. rewrite (@IHl (a::nil)). rewrite~ app_last.\n  asserts K2: (forall accu,\n   fold_left (fun x acc => x :: acc) accu (l1 ++ l2) =\n   fold_left (fun x acc => x :: acc) nil l2 ++\n   fold_left (fun x acc => x :: acc) nil l1 ++ accu).\n  induction l1; intros; simpl.\n    do 2 rewrite app_nil_l. apply K1.\n    rewrite IHl1. rewrite (@K1 l1 (a::nil)). rewrite~ app_last.\n  lets K3: (@K2 nil). rewrite app_nil_r in K3. auto.\nQed.\nLemma rev_cons : forall x l,\n  rev (x::l) = rev l & x.\nProof. intros. rewrite <- app_cons_one. rewrite~ rev_app. Qed.\nLemma rev_last : forall x l,\n  rev (l & x) = x::(rev l).\nProof. intros. rewrite~ rev_app. Qed.\nLemma rev_cons_app : forall x l1 l2,\n  rev (x :: l1) ++ l2 = rev l1 ++ (x::l2).\nProof. intros. rewrite rev_cons. rewrite~ <- app_last. Qed.\nLemma app_rev_cons : forall x l1 l2,\n  l1 ++ rev (x :: l2) = (l1 ++ rev l2) & x.\nProof. intros. rewrite rev_cons. rewrite~ app_assoc. Qed.\nLemma rev_rev : forall l,\n  rev (rev l) = l.\nProof. \n  induction l. auto. rewrite rev_cons. rewrite rev_last. fequals.\nQed.\nLemma length_rev : forall l, \n  length (rev l) = length l.\nProof.\n  induction l. auto. rewrite rev_cons.\n  rewrite length_last. rewrite~ length_cons.\nQed.\n\nLemma concat_nil : \n  concat (@nil (list A)) = nil.\nProof. auto. Qed.\nLemma concat_cons : forall l m,\n  concat (l::m) = l ++ concat m.\nProof. auto. Qed.\nLemma concat_one : forall l,\n  concat (l::nil) = l.\nProof.\n  intros. rewrite concat_cons. rewrite concat_nil.\n  rewrite~ app_nil_r. \nQed.\nLemma concat_app : forall m1 m2 : list (list A),\n  concat (m1 ++ m2) = concat m1 ++ concat m2.\nProof.\n  induction m1; intros.\n  rewrite concat_nil. do 2 rewrite~ app_nil_l.\n  rewrite app_cons. do 2 rewrite concat_cons.\n   rewrite app_assoc. fequals.\nQed.\nLemma concat_last : forall l m,\n  concat (m & l) = concat m ++ l.\nProof. intros. rewrite~ concat_app. rewrite~ concat_one. Qed.\n\nSection MapProp.\nVariable f : A -> B.\nLemma map_nil : \n  map f nil = nil.\nProof. auto. Qed.\nLemma map_cons : forall x l,\n  map f (x::l) = f x :: map f l.\nProof. auto. Qed.\nLemma map_app : forall l1 l2,\n  map f (l1 ++ l2) = map f l1 ++ map f l2.\nProof. \n  intros. unfold map.\n  assert (forall accu,\n    fold_right (fun x acc => f x :: acc) accu (l1 ++ l2) =\n    fold_right (fun x acc => f x :: acc) nil l1 ++\n     fold_right (fun x acc => f x :: acc) nil l2 ++ accu).\n  induction l1; intros; simpl. \n   do 2 rewrite app_nil_l. gen accu.\n   induction l2; intros; simpl.\n     auto. \n     rewrite IHl2. rewrite~ app_cons.\n   rewrite IHl1. rewrite~ app_cons.\n  specializes H (@nil B). rewrite~ app_nil_r in H.\nQed.\nLemma map_last : forall x l,\n  map f (l & x) = map f l & f x.\nProof. intros. rewrite~ map_app. Qed.\nLemma length_map : forall l,\n  length (map f l) = length l.\nProof. \n  induction l. auto.\n  rewrite map_cons. do 2 rewrite length_cons. auto.\nQed.\nEnd MapProp.\n\nSection FilterProp.\nVariable f : A -> bool.\nLemma filter_nil : \n  filter f nil = nil.\nProof. auto. Qed.\nLemma filter_cons : forall x l,\n  filter f (x::l) = if f x then x :: filter f l else filter f l.\nProof. auto. Qed.\nLemma filter_app : forall l1 l2,\n  filter f (l1 ++ l2) = filter f l1 ++ filter f l2.\nProof.  (* todo: factorise with map_app *)\n  intros. unfold filter.\n  assert (forall accu,\n    fold_right (fun x acc => if f x then x::acc else acc) accu (l1 ++ l2) =\n    fold_right (fun x acc => if f x then x::acc else acc) nil l1 ++\n     fold_right (fun x acc => if f x then x::acc else acc) nil l2 ++ accu).\n  induction l1; intros; simpl. \n   do 2 rewrite app_nil_l. gen accu.\n   induction l2; intros; simpl.\n     auto. \n     case_if. fequals. rewrite IHl2. rewrite~ app_cons. fequals.\n    case_if. fequals. rewrite IHl1. rewrite~ app_cons. apply IHl1.\n  specializes H (@nil A). rewrite~ app_nil_r in H.\nQed.\nLemma filter_last : forall x l,\n  filter f (l & x) = filter f l ++ (if f x then x::nil else nil).\nProof. intros. rewrite~ filter_app. Qed.\n(*later:\nLemma length_filter : forall l,\n  length (filter f l) <= length l.\n*)\nEnd FilterProp.\n\nSection MemProp.\nImplicit Types k : A.\nLemma mem_nil : forall k,\n  mem k nil = false.\nProof. auto. Qed.\nLemma mem_cons : forall k x l,\n  mem k (x::l) = (k '= x) || (mem k l).\nProof. auto. Qed.\nLemma mem_app : forall f l1 l2,\n  mem f (l1 ++ l2) = (mem f l1) || mem f l2.\nProof.\n  intros. induction l1.\n  rew_bool. rewrite~ app_nil_l.\n  rewrite app_cons. simpl. rewrite~ IHl1.\n  rewrite~ assoc_or.\nQed.\nLemma mem_last : forall k x l,\n  mem k (l & x) = (k '= x) || (mem k l).\nProof. \n  intros. rewrite mem_app. simpl. \n  rewrite LibBool.comm_or. rew_bool. auto.\nQed.\nLemma mem_cons_eq : forall x l,\n  mem x (x::l) = true.\nProof. intros. simpl. rewrite~ eqb_self. Qed.\nLemma mem_last_eq : forall x l,\n  mem x (l & x) = true.\nProof. intros. rewrite mem_last. rewrite~ eqb_self. Qed.\nEnd MemProp.\n\nLemma drop_struct : forall n l,\n  n <= length l -> exists l', \n  length l' = n /\\ l = l' ++ (drop n l).\nProof.\n  induction n; introv Len.\n    exists~ (@nil A).\n    destruct l. rewrite length_nil in Len. math.\n     destruct (IHn l) as [l' [Le Eq]].\n      rewrite length_cons in Len. math.\n     exists (a::l'). split. rewrite length_cons. rewrite~ Le.\n     rewrite app_cons. simpl. fequals~.\nQed.\n(* todo: missing properties of drop *)\n\n\nLemma take_nil : forall l, \n  take 0 l = nil.\nProof. auto. Qed.\n\nLemma take_cons : forall x l n, \n  take (S n) (x::l) = x :: (take n l).\nProof. auto. Qed.\n\nLemma take_cons_pred : forall x l n, \n  (n > 0) ->\n  take n (x::l) = x :: (take (n-1) l).\nProof.\n  introv H. destruct n. false; math. \n  simpl. fequals_rec. math.\nQed.\n\nLemma take_app_l : forall n l l', \n  (n <= length l) ->\n  take n (l ++ l') = take n l.\nProof. \n  induction n; destruct l; introv H;\n   try rewrite length_nil in H; \n   try rewrite length_cons in H; auto.\n  math. \n  rewrite app_cons. do 2 rewrite take_cons. fequals.\n   applys IHn. math.\nQed.\n\nLemma take_app_r : forall n l l', \n  (n >= length l) ->\n  take n (l ++ l') = l ++ take (n - length l) l'.\nProof.\n  intros. gen n. induction l; introv H. \n  rewrite length_nil in *. do 2 rewrite app_nil_l.\n   fequals. math.\n  rewrite length_cons in *. destruct n as [|n'].\n    false. math. \n    do 2 rewrite app_cons. rewrite take_cons. \n    fequals. applys IHl. math.\nQed.\n\nLemma take_app_length : forall l l', \n  take (length l) (l ++ l') = l.\nProof.\n  intros. rewrite take_app_r.\n  asserts_rewrite (forall a, a - a = 0). math. \n  rewrite take_nil. apply app_nil_r. math.\nQed.\n \nLemma take_at_length : forall l, \n  take (length l) l = l.\nProof.\n  intros. lets: (@take_app_length l nil).\n  rewrite~ app_nil_r in H.\nQed.\n\n  (* todo: or name as take_length ? *)\nLemma length_take : forall n l, \n  n <= length l ->\n  length (take n l) = n.\nProof.\n  induction n; introv H. \n  rewrite~ take_nil.\n  destruct l. rewrite length_nil in H. math.\n  rewrite take_cons.\n   rewrite length_cons in *. rewrite IHn; math.\nQed.\n\nLemma take_struct : forall n l,\n  n <= length l -> \n  exists l', length (take n l) = n \n          /\\ l = (take n l) ++ l'.\nProof. (* todo: relate with drop ! *) \n  induction n; introv Len.\n    exists~ l.\n    destruct l. rewrite length_nil in Len. math. simpl.\n     destruct (IHn l) as [l' [Le Eq]].\n      rewrite length_cons in Len. math.\n     exists l'. split. rewrite length_cons. rewrite~ Le.\n     rewrite app_cons. fequals~.\nQed.\n\nLemma split_cons : forall {A1 A2} \n (l1:list A1) (l2:list A2) (x1:A1) (x2:A2) (l:list (A1*A2)),\n  (l1,l2) = split l ->\n  split ((x1,x2)::l) = (x1::l1,x2::l2).\nProof.\n  intros. destruct l; inverts H; simpl.\n    auto.\n    destruct p. simpl. destruct (split l). fequals.\nQed.\n \nLemma take_and_drop : forall n l f r,\n  f = take n l -> r = drop n l -> n <= length l -> \n  l = f ++ r /\\ length f = n /\\ length r = length l - n.\nProof.\n  induction n; introv F R L; simpls.\n  subst. splits~. math.\n  destruct l.\n    rewrite length_nil in L. math.\n    rewrite length_cons in L.\n     forwards~ (F'&R'&L'): (>> IHn l (take n l) r). math.\n     subst f. splits.\n       rewrite app_cons. fequals.\n       rewrite length_cons. math.\n       rewrite length_cons. math.\nQed.\n  \n\nEnd OperationProperties.\n\nImplicit Arguments length_zero_inv [A l].\nImplicit Arguments take_struct [A].\n\nModule TakeInt.\nRequire Import LibInt.\nSection Facts.\nVariables (A:Type).\nImplicit Types x : A.\nImplicit Types l : list A.\n\nLemma take_cons_pred_int : forall x l (n:int), \n  n > 0 ->\n  take (abs n) (x::l) = x :: (take (abs (n-1)) l).\nProof.\n  introv Pos. rewrite take_cons_pred.\n  rewrite abs_minus; try math. auto. apply~ abs_gt. \nQed.\n\nLemma take_cons_int : forall x l (n:int), \n  n >= 0 ->\n  take (abs (n+1)) (x::l) = x :: (take (abs n) l).\nProof.\n  introv Pos. rewrite~ abs_plus.\n  rewrite~ plus_comm. math.\nQed.\n\n(* begin hide *)\n\nLemma take_last_int : forall l (n:int),\n  n > 0 -> n <= length l -> exists x,\n  take (abs n) l = (take (abs (n - 1)) l) & x.\nProof.\n  introv Gt Le.\n  destruct (take_struct (abs (n-1)) l) as (l'&L&E).\n  apply abs_le. math.\n  destruct l'.\n    false. rewrite app_nil_r in E.\n    asserts M: (forall A B (f:A->B) (x y:A), x = y -> f x = f y).\n      introv Q. rewrite~ Q.\n    asserts N: (forall A B (f:A->B) (x y:A), x = y -> f x <> f y -> False).\n      introv Q D. apply D. apply M. auto.\n    applys N (@length A) E.\n    rewrite length_take. skip. skip. skip. (*TODO: under construction *)\nAdmitted.\n\n(* end hide *)\n\nEnd Facts.\nEnd TakeInt.\nExport TakeInt.\n\n\n\n(* ********************************************************************** *)\n(** * Association lists *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Operations *)\n\nSection Assoc.\nContext {A B : Type}.\nVariables (IB:Inhab B).\nImplicit Types x : A.\nImplicit Types l : list (A*B).\n\nFixpoint assoc k l : B :=\n  match l with \n  | nil => arbitrary\n  | (x,v)::l' => If x = k then v else assoc k l' \n  end.\n\nDefinition mem_assoc k := \n  exists_st (fun p:A*B => k '= fst p).\n\nDefinition keys :=\n  @map (A*B) A (@fst _ _).\n\nFixpoint remove_assoc k l : list (A*B) :=\n  match l with \n  | nil => nil\n  | (x,v)::l' => \n      If k = x \n        then l' \n        else (x,v)::(remove_assoc k l')\n  end.\n\nEnd Assoc.\n\nImplicit Arguments assoc [[A] [B] [IB]].\nImplicit Arguments mem_assoc [[A] [B]].\nImplicit Arguments keys [[A] [B]].\nImplicit Arguments remove_assoc [[A] [B]].\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties *)\n\nSection AssocProperties.\nVariable (A B : Type) (IB:Inhab B).\nImplicit Types x : A.\nImplicit Types l : list (A*B).\n\nLemma assoc_cons : forall k x y l,\n  assoc k ((x,y)::l) = If x = k then y else assoc k l.\nProof. auto. Qed.\nLemma assoc_here : forall x y l,\n  assoc x ((x,y)::l) = y.\nProof. intros. simpl. case_if~. Qed.\nLemma assoc_next : forall x y k l,\n  k '<> x -> assoc k ((x,y)::l) = assoc k l.\nProof. intros. simpl. fold_prop. case_if~. Qed.\n\nLemma keys_nil : \n  keys (@nil (A*B)) = nil.\nProof. auto. Qed.\nLemma keys_cons : forall x y l,\n  keys ((x,y)::l) = x :: (keys l).\nProof. auto. Qed.\nLemma keys_app : forall l1 l2,\n  keys (l1 ++ l2) = keys l1 ++ keys l2.\nProof. intros. applys map_app. Qed.\nLemma keys_last : forall x y l,\n  keys (l & (x,y)) = (keys l) & x.\nProof. intros. rewrite~ keys_app. Qed.\n\nLemma remove_assoc_nil : forall x,\n  remove_assoc x nil = (@nil (A*B)).\nProof. auto. Qed.\nLemma remove_assoc_cons : forall x x' y l,\n  remove_assoc x ((x',y)::l) = \n    If x = x' then l else (x',y)::remove_assoc x l.\nProof. auto. Qed.\n\nEnd AssocProperties.\n\n\n(* ********************************************************************** *)\n(* * Tactics for rewriting *)\n\nHint Rewrite app_cons app_nil_l app_nil_r app_assoc \n app_cons_one : rew_app. (* app_last *)\nHint Rewrite fold_right_nil fold_right_cons fold_right_app\n fold_right_last : rew_foldr.\nHint Rewrite fold_left_nil fold_left_cons fold_left_app\n fold_left_last : rew_foldl.\nHint Rewrite length_nil length_cons length_app\n length_last length_rev : rew_length.\nHint Rewrite rev_nil rev_app rev_cons rev_last rev_rev : rew_rev.\n (* +rev_cons_app *)\nHint Rewrite concat_nil concat_app concat_cons concat_last : rew_concat.\nHint Rewrite map_nil map_cons map_app map_last : rew_map.\nHint Rewrite mem_nil mem_cons mem_app mem_last \n mem_cons_eq mem_last_eq : rew_mem.\nHint Rewrite keys_nil keys_cons keys_app keys_last : rew_keys.\nHint Rewrite assoc_cons assoc_here : rew_assoc.\n\nTactic Notation \"rew_app\" :=\n  autorewrite with rew_app.\nTactic Notation \"rew_foldr\" :=\n  autorewrite with rew_foldr rew_app.\nTactic Notation \"rew_foldl\" :=\n  autorewrite with rew_foldl rew_app.\nTactic Notation \"rew_length\" :=\n  autorewrite with rew_length.\nTactic Notation \"rew_rev\" :=\n  autorewrite with rew_rev rew_app.\nTactic Notation \"rew_concat\" :=\n  autorewrite with rew_concat rew_app.\nTactic Notation \"rew_map\" :=\n  autorewrite with rew_map rew_app.\nTactic Notation \"rew_mem\" :=\n  autorewrite with rew_mem rew_app.\nTactic Notation \"rew_keys\" :=\n  autorewrite with rew_keys rew_app.\nTactic Notation \"rew_assoc\" :=\n  autorewrite with rew_assoc rew_app.\n\nTactic Notation \"rew_app\" \"in\" hyp(H) :=\n  autorewrite with rew_app in H.\nTactic Notation \"rew_foldr\" \"in\" hyp(H) :=\n  autorewrite with rew_foldr rew_app in H.\nTactic Notation \"rew_foldl\" \"in\" hyp(H) :=\n  autorewrite with rew_foldl rew_app in H.\nTactic Notation \"rew_length\" \"in\" hyp(H) :=\n  autorewrite with rew_length in H.\nTactic Notation \"rew_rev\" \"in\" hyp(H) :=\n  autorewrite with rew_rev rew_app in H.\nTactic Notation \"rew_concat\" \"in\" hyp(H) :=\n  autorewrite with rew_concat rew_app in H.\nTactic Notation \"rew_map\" \"in\" hyp(H) :=\n  autorewrite with rew_map rew_app in H.\nTactic Notation \"rew_mem\" \"in\" hyp(H) :=\n  autorewrite with rew_mem rew_app in H.\nTactic Notation \"rew_keys\" \"in\" hyp(H) :=\n  autorewrite with rew_keys rew_app in H.\nTactic Notation \"rew_assoc\" \"in\" hyp(H) :=\n  autorewrite with rew_assoc rew_app in H.\n\nTactic Notation \"rew_app\" \"in\" \"*\" :=\n  autorewrite with rew_app in *.\nTactic Notation \"rew_foldr\" \"in\" \"*\" :=\n  autorewrite with rew_foldr rew_app in *.\nTactic Notation \"rew_foldl\" \"in\" \"*\" :=\n  autorewrite with rew_foldl rew_app in *.\nTactic Notation \"rew_length\" \"in\" \"*\" :=\n  autorewrite with rew_length in *.\nTactic Notation \"rew_rev\" \"in\" \"*\" :=\n  autorewrite with rew_rev rew_app in *.\nTactic Notation \"rew_concat\" \"in\" \"*\" :=\n  autorewrite with rew_concat rew_app in *.\nTactic Notation \"rew_map\" \"in\" \"*\" :=\n  autorewrite with rew_map rew_app in *.\nTactic Notation \"rew_mem\" \"in\" \"*\" :=\n  autorewrite with rew_mem rew_app in *.\nTactic Notation \"rew_keys\" \"in\" \"*\" :=\n  autorewrite with rew_keys rew_app in *.\nTactic Notation \"rew_assoc\" \"in\" \"*\" :=\n  autorewrite with rew_assoc rew_app in *.\n\nTactic Notation \"rew_app\" \"~\" :=\n  rew_app; auto_tilde.\nTactic Notation \"rew_rev\" \"~\" :=\n  rew_rev; auto_tilde.\nTactic Notation \"rew_mem\" \"~\" :=\n  rew_mem; auto_tilde.\nTactic Notation \"rew_length\" \"~\" :=\n  rew_length; auto_tilde.\n\nHint Rewrite app_cons app_nil_l app_nil_r app_assoc \n app_cons_one \n fold_right_nil fold_right_cons fold_right_app\n fold_right_last \n fold_left_nil fold_left_cons fold_left_app\n fold_left_last \n length_nil length_cons length_app length_rev\n length_last \n rev_nil rev_app rev_cons rev_last rev_rev\n concat_nil concat_app concat_cons concat_last \n  map_nil map_cons map_app map_last : rew_list.\n\nHint Rewrite app_cons app_nil_l app_nil_r app_assoc \n app_cons_one \n mem_nil mem_cons mem_app mem_last \n mem_cons_eq mem_last_eq \n keys_nil keys_cons keys_app keys_last\n assoc_cons assoc_here : rew_lists.\n\nTactic Notation \"rew_list\" :=\n  autorewrite with rew_list.\nTactic Notation \"rew_list\" \"~\" :=\n  rew_list; auto_tilde.\nTactic Notation \"rew_list\" \"*\" :=\n  rew_list; auto_star.\nTactic Notation \"rew_list\" \"in\" \"*\" :=\n  autorewrite with rew_list in *.\nTactic Notation \"rew_list\" \"~\" \"in\" \"*\" :=\n  rew_list in *; auto_tilde.\nTactic Notation \"rew_list\" \"*\" \"in\" \"*\" :=\n  rew_list in *; auto_star.\nTactic Notation \"rew_list\" \"in\" hyp(H) :=\n  autorewrite with rew_list in H.\nTactic Notation \"rew_list\" \"~\" \"in\" hyp(H) :=\n  rew_list in H; auto_tilde.\nTactic Notation \"rew_list\" \"*\" \"in\" hyp(H) :=\n  rew_list in H; auto_star.\n\nTactic Notation \"rew_lists\" :=\n  autorewrite with rew_lists.\nTactic Notation \"rew_lists\" \"~\" :=\n  rew_lists; auto_tilde.\nTactic Notation \"rew_lists\" \"*\" :=\n  rew_lists; auto_star.\nTactic Notation \"rew_lists\" \"in\" \"*\" :=\n  autorewrite with rew_lists in *.\nTactic Notation \"rew_lists\" \"~\" \"in\" \"*\" :=\n  rew_lists in *; auto_tilde.\nTactic Notation \"rew_lists\" \"*\" \"in\" \"*\" :=\n  rew_lists in *; auto_star.\nTactic Notation \"rew_lists\" \"in\" hyp(H) :=\n  autorewrite with rew_lists in H.\nTactic Notation \"rew_lists\" \"~\" \"in\" hyp(H) :=\n  rew_lists in H; auto_tilde.\nTactic Notation \"rew_lists\" \"*\" \"in\" hyp(H) :=\n  rew_lists in H; auto_star.\n\n\n(* ********************************************************************** *)\n(** * Other definitions and results *)\n\n(* ---------------------------------------------------------------------- *)\n(** * TODO *)\n\n(* todo *)\n\nDefinition is_head A (l:list A) (x:A) :=\n  exists t, l = x::t.\n\nDefinition is_tail A (l:list A) (t:list A) :=\n  exists x, l = x::t.\n\nDefinition is_last A (l:list A) (x:A) :=\n  exists t, l = t&x.\n\nDefinition is_init A (l:list A) (t:list A) :=\n  exists x, l = t&x.\n\nHint Unfold is_head is_tail is_last is_init.\n\nSection IsProp.\nVariables A : Type.\nImplicit Types x : A.\n\nLemma is_last_one : forall x,\n  is_last (x::nil) x.\nProof. intros. unfolds. exists~ (@nil A). Qed.\n\nLemma is_init_one : forall x,\n  is_init (x::nil) nil.\nProof. intros. unfolds. exists~ x. Qed.\n\nEnd IsProp.\n\nHint Immediate is_last_one.\nHint Immediate is_init_one.\n\n\n(* ---------------------------------------------------------------------- *)\n(** * Inversions on the structure of lists *)\n\nSection Inversions.\nVariables A : Type.\nImplicit Types l : list A.\n\nLemma cons_neq_nil : forall x l, \n  x::l <> nil.\nProof. auto_false. Qed.\n\nLemma last_eq_nil_inv : forall a l,\n  l & a = nil -> False.\nProof. induction l; rew_app; intros; false. Qed.\n\nLemma nil_eq_last_inv : forall a l,\n  nil = l & a -> False.\nProof. intros. apply* last_eq_nil_inv. Qed.\n\nLemma rev_eq_nil_inv : forall l,\n  rev l = nil -> l = nil.\nProof.\n  destruct l; rew_rev; intros. auto. \n  false* last_eq_nil_inv. \nQed.\n\nLemma nil_eq_rev_inv : forall l,\n  nil = rev l -> l = nil.\nProof. introv H. apply~ rev_eq_nil_inv. Qed.\n\nLemma app_eq_nil_inv : forall l1 l2,\n  l1 ++ l2 = nil -> l1 = nil /\\ l2 = nil.\nProof. destruct l1; destruct l2; intros; tryfalse~; auto. Qed.\n\nLemma nil_eq_app_inv : forall l1 l2,\n  nil = l1 ++ l2 -> l1 = nil /\\ l2 = nil.\nProof. intros. symmetry in H. apply* app_eq_nil_inv. Qed.\n\nLemma app_eq_self_inv_r : forall l1 l2,\n  l2 = l1 ++ l2 -> l1 = nil.\nProof.\n  introv E. apply length_zero_inv.\n  lets: (func_eq_1 length E). rew_length in H. math.\nQed.\n\nLemma app_eq_self_inv_l : forall l1 l2,\n  l1 = l1 ++ l2 -> l2 = nil.\nProof.\n  introv E. apply length_zero_inv.\n  lets: (func_eq_1 length E). rew_length in H. math.\nQed.\n\nLemma app_rev_eq_nil_inv : forall l1 l2,\n  l1 ++ rev l2 = nil -> l1 = nil /\\ l2 = nil.\nProof.\n  intros. lets H1 H2: (app_eq_nil_inv _ _ H).\n  applys_to H2 rev_eq_nil_inv. auto*.\nQed.\n\nLemma nil_eq_app_rev_inv : forall l1 l2,\n  nil = l1 ++ rev l2 -> l1 = nil /\\ l2 = nil.\nProof. intros. apply* app_rev_eq_nil_inv. Qed.\n\n(* todo: too specific? *)\n\nLemma nil_eq_last_val_app_inv : forall x l1 l2,\n  nil = l1 & x ++ l2 -> False.\nProof. intros. destruct l1; inverts H. Qed.\n\nLemma cons_eq_last_val_app_inv : forall x y l1 l2 l,\n  x :: l = l1 & y ++ l2 ->\n  (l1 = nil /\\ x = y /\\ l = l2) \\/ (exists l1', l1 = x::l1').\nProof.\n  intros. destruct l1; rew_list in H; inverts H.\n   left~. right*.\nQed.\n\nLemma last_inv : forall l,\n  (length l > 0%nat) -> \n  exists x l', l = l' & x.\nProof.\n  induction l; rew_length; introv H.\n  false. math.\n  destruct l.\n    exists~ a (@nil A).\n    destruct IHl as (x&l'&E). rew_length in *. math.\n    exists x (a::l'). rewrite~ E.\nQed.   \n\nLemma app_not_empty_l : forall l1 l2,\n  l1 <> nil -> l1 ++ l2 <> nil.\nProof. introv NE K. apply NE. destruct~ (app_eq_nil_inv _ _ K). Qed.\n\nLemma app_not_empty_r : forall l1 l2,\n  l2 <> nil -> l1 ++ l2 <> nil.\nProof. introv NE K. apply NE. destruct~ (app_eq_nil_inv _ _ K). Qed.\n\nEnd Inversions.\n\nImplicit Arguments last_eq_nil_inv [A a l].\nImplicit Arguments nil_eq_last_inv [A a l].\nImplicit Arguments rev_eq_nil_inv [A l].\nImplicit Arguments nil_eq_rev_inv [A l].\nImplicit Arguments app_eq_nil_inv [A l1 l2].\nImplicit Arguments nil_eq_app_inv [A l1 l2].\nImplicit Arguments app_rev_eq_nil_inv [A l1 l2].\nImplicit Arguments nil_eq_app_rev_inv [A l1 l2].\nImplicit Arguments nil_eq_last_val_app_inv [A x l1 l2]. \nImplicit Arguments cons_eq_last_val_app_inv [A x y l1 l2 l].\n\n\n(* ---------------------------------------------------------------------- *)\n(* ** Function for mapping partial function on lists *)\n\nDefinition map_partial (A B : Type) (f : A -> option B) :=\n  fix aux (l : list A) : option (list B) := match l with\n    | nil => Some nil\n    | x::l' => LibOption.apply_on (f x) (fun v =>\n                 LibOption.map (cons v) (aux l'))\n   end.\n\nLemma map_partial_inv : forall (A B:Type) (f: A->option B) lx ly,\n  map_partial f lx = Some ly ->\n  Forall2 (fun x y => f x = Some y) lx ly. \nProof.\n  induction lx; simpl map_partial; introv Eq.\n  inverts Eq. apply Forall2_nil.\n  lets fa Fa Eq2: (apply_on_inv Eq).\n   lets ly1 Eqly ?: (map_on_inv Eq2). subst ly.\n   apply* Forall2_cons.\nQed.\n\nImplicit Arguments map_partial_inv [A B f lx ly].\n\n\n(* ---------------------------------------------------------------------- *)\n(* ** Induction principle on lists *)\n\nSection ListSub.\nVariable (A:Type).\n\nInductive list_sub : list A -> list A -> Prop :=\n  | list_sub_cons : forall x l, \n      list_sub l (x::l).\n\nHint Constructors list_sub.\nLemma list_sub_wf : wf list_sub.\nProof.\n  intros l. induction l;\n  apply Acc_intro; introv H; inverts~ H. \nQed.\n\nEnd ListSub.\n\nImplicit Arguments list_sub [[A]].\nHint Constructors list_sub.\nHint Resolve list_sub_wf : wf.\n\n\n(* ********************************************************************** *)\n(** * Properties of predicate on lists *)\n\nSection PropProperties.\nVariables A : Type.\nImplicit Types l : list A.\n\nHint Constructors Forall.\n\nLemma Forall_app : forall P l1 l2, \n  Forall P l1 -> Forall P l2 -> \n  Forall P (l1 ++ l2).\nProof. introv H Px. induction H; rew_app; auto. Qed.\n\nLemma Forall_app_inv : forall P l1 l2, \n  Forall P (l1 ++ l2) ->\n  Forall P l1 /\\ Forall P l2.\nProof.\n  intros. induction l1. auto.\n  rew_app in H. inverts* H.\nQed.\n\nLemma Forall_last : forall P l x, \n  Forall P l -> P x -> \n  Forall P (l & x).\nProof. intros. apply~ Forall_app. Qed.\n\nLemma Exists_nil_inv : forall (P : A -> Prop),\n  Exists P nil -> False.\nProof. introv H. invert* H. Qed.\n\nLemma Exists_cons_inv : forall (P : A -> Prop) l x,\n  Exists P (x::l) -> P x \\/ Exists P l.\nProof. induction l; introv H; inverts~ H. Qed.\n\nEnd PropProperties.\n\nSection ForallToConj.\nVariables (A : Type) (P : A->Prop).\nHint Constructors Forall.\nLtac forall_to_conj_prove :=\n  extens; iff H;\n  repeat (match goal with H: Forall _ _ |- _ => inversion H end); \n  repeat (first [constructor | auto* ]).\n\nLemma Forall_to_conj_1 : forall x1,\n  Forall P (x1::nil) = (P x1).\nProof. forall_to_conj_prove. Qed.\n\nLemma Forall_to_conj_2 : forall x1 x2,\n  Forall P (x1::x2::nil) = (P x1 /\\ P x2).\nProof. forall_to_conj_prove. Qed.\n\nLemma Forall_to_conj_3 : forall x1 x2 x3,\n  Forall P (x1::x2::x3::nil) = (P x1 /\\ P x2 /\\ P x3).\nProof. forall_to_conj_prove. Qed.\n\nLemma Forall_to_conj_4 : forall x1 x2 x3 x4,\n  Forall P (x1::x2::x3::x4::nil) = (P x1 /\\ P x2 /\\ P x3 /\\ P x4).\nProof. forall_to_conj_prove. Qed.\n\nEnd ForallToConj.\n\nHint Resolve has_pair_here has_pair_next.\n\nSection PropProperties2.\nVariables A1 A2 : Type.\nImplicit Types l : list A1.\nImplicit Types r : list A2.\nHint Constructors Forall2.\n\nLemma Forall2_app : forall P l1 l2 r1 r2, \n      Forall2 P l1 r1 -> Forall2 P l2 r2 ->\n      Forall2 P (l1 ++ l2) (r1 ++ r2).\nProof. introv H H'. induction H; rew_app; auto. Qed.\n\nLemma Forall2_last : forall P l r x1 x2, \n      Forall2 P l r -> P x1 x2 ->\n      Forall2 P (l & x1) (r & x2).\nProof. intros. apply~ Forall2_app. Qed.\n\nLemma Forall2_last_inv : forall P l1 r' x1, \n  Forall2 P (l1 & x1) r' ->\n  exists (r2:list A2) x2, \n  r' = r2 & x2 /\\ P x1 x2 /\\ Forall2 P l1 r2.\nProof. \n  introv H. sets_eq l': (l1&x1). gen l1 x1.\n  induction H; intros; subst.\n  false* nil_eq_last_inv.\n  destruct l0; rew_app in EQl'; inverts EQl'.\n    inverts H0. exists~ (@nil A2) x2.\n    forwards~ (r2'&x2'&?&?&?): IHForall2. subst. exists~ (x2::r2') x2'.   \nQed.\n\nLemma Forall2_length : forall P l r,\n  Forall2 P l r -> length l = length r.\nProof.\n  introv H. induction H. simple~. \n  do 2 rewrite~ length_cons. \nQed.\n\nLemma Forall2_take : forall P n l r,\n  Forall2 P l r ->\n  Forall2 P (take n l) (take n r).\nProof. induction n; introv H; inverts H; simple~. Qed.\n\nHint Constructors Forall2.\nHint Resolve Forall2_last.\n\nLemma Forall2_rev : forall P l r,\n  Forall2 P l r -> Forall2 P (rev l) (rev r).\nProof. induction l; introv M; inverts M; rew_rev; auto. Qed.\n\nEnd PropProperties2.\n\nImplicit Arguments Forall2_last_inv [A1 A2 P l1 r' x1].\n\n(** [list_equiv E l1 l2] asserts that the lists [l1] and [l2]\n    are equal when their elements are compared modulo E *)\n\nDefinition list_equiv (A:Type) (E:binary A) : binary (list A) :=\n   Forall2 E.\n\nSection ListEquiv.\nHint Constructors Forall2.\n\nLemma list_equiv_equiv : forall A (E:binary A),\n  equiv E -> equiv (list_equiv E).\nProof.\n  introv Equiv. unfold list_equiv. constructor.\n  unfolds. induction x. auto. constructor*.\n  unfolds. induction x; destruct y; introv H; inversions* H.\n  unfolds. induction y; destruct x; destruct z; introv H1 H2;\n   inversions H1; inversions* H2.\nQed.\n\nEnd ListEquiv.\n\n(* todo : inversion lemmas for other predicates *)\n\nSection NthProperties.\nVariables (A : Type) (IA : Inhab A).\nImplicit Types l : list A.\nImplicit Types x : A.\nImplicit Types n : nat.\nHint Constructors Nth.\n\nLemma Nth_lt_length : forall n l x,\n  Nth n l x -> n < length l.\nProof. \n  induction n; introv H; inverts H.\n  rewrite length_cons. math.\n  rewrite length_cons. simpl. rew_nat*.\nQed.\n\nLemma Nth_func: forall n l x1 x2,\n  Nth n l x1 -> Nth n l x2 -> x1 = x2.\nProof. introv H1. induction H1; intro H2; inverts~ H2. Qed.\n\nLemma Nth_to_nth : forall n l x,\n  Nth n l x -> nth n l = x.\nProof. introv H. induction~ H. Qed.\n\nLemma mem_Nth : forall l x,\n  mem x l -> exists n, Nth n l x.\nProof. \n  intros. induction l.\n  rewrite mem_nil in H. false.\n  rewrite mem_cons in H. rew_reflect in H. destruct H.\n   fold_prop. subst*.\n   forwards* [n ?]: IHl.\nQed.\n\nImplicit Arguments mem_Nth [l x].\n\nLemma mem_nth : forall l x,\n  mem x l -> exists n, nth n l = x.\nProof.\n  intros. forwards [n P]: (mem_Nth H).\n  exists n. apply~ Nth_to_nth.\nQed.\n\nLemma Nth_app_l : forall n x l1 l2,\n  Nth n l1 x -> Nth n (l1 ++ l2) x.\nProof. induction n; introv H; inverts H; rew_list*. Qed.\n\nLemma Nth_app_r : forall n m x l1 l2,\n  Nth m l2 x -> n = (m + length l1)%nat -> Nth n (l1 ++ l2) x.\nProof.\n  intros. subst. gen m. induction l1; introv H.\n  rew_list. applys_eq~ H 3.\n  rew_list. applys_eq* Nth_next 3. \nQed.\n\nLemma Nth_app_inv : forall n x l1 l2,\n  Nth n (l1++l2) x -> \n     (Nth n l1 x)\n  \\/ (exists m, n = (length l1 + m)%nat /\\ Nth m l2 x).\nProof.\n  introv. gen n. induction l1; introv H; rew_list in H.\n  right. rew_length. exists~ n.\n  inverts H. left~.\n   forwards* M: IHl1. destruct M.\n    left~. intuit. rew_length.\n    right*. exists x0. split~. math.\nQed.\n\nLemma Nth_nil_inv : forall n x,\n  Nth n nil x -> False.\nProof. introv H. inverts H. Qed.\n\nLemma Nth_cons_inv : forall n x l,\n  Nth n l x -> \n     (exists q, l = x::q /\\ n = 0%nat)\n  \\/ (exists y q m, l = y::q /\\ Nth m q x /\\ n = (m+1)%nat).\nProof.\n  introv H. inverts H. left*.\n  right. eauto 8 with maths. \nQed.\n\nEnd NthProperties.\n\n(* ---------------------------------------------------------------------- *)\n(* ** Mem *)\n\nSection MemFacts.\nHint Constructors Mem.\n\nLemma Mem_nil_eq : forall A (x:A),\n  Mem x nil = False.\nProof. intros. extens. iff H; inverts H. Qed.\n\nLemma Mem_cons_eq : forall A (x y:A) l,\n  Mem x (y::l) = ((x = y) \\/ (Mem x l)).\nProof. intros. extens. iff H; inverts~ H. Qed.\n\nLemma Mem_app_or_eq : forall (A:Type) (l1 l2 : list A) x,\n  Mem x (l1 ++ l2) = (Mem x l1 \\/ Mem x l2).\nProof.\n  intros. extens. induction l1; rew_app.\n  split. auto. introv [H|?]. inverts H. auto.\n  iff M. inverts~ M. rewrite IHl1 in H0. destruct* H0.\n   destruct M. inverts~ H. constructors. rewrite~ IHl1.  \n   constructors. rewrite~ IHl1.  \nQed.\n\nLemma Mem_app_or : forall (A:Type) (l1 l2 : list A) x,\n  Mem x l1 \\/ Mem x l2 -> Mem x (l1 ++ l2).\nProof. intros. rewrite~ Mem_app_or_eq. Qed.\n\nLemma Mem_last : forall A (L:list A) x,\n  Mem x (L & x).\nProof. intros. apply* Mem_app_or. Qed.\n\nLemma Mem_rev : forall A (L:list A) x,\n  Mem x L -> Mem x (rev L).\nProof. introv H. induction H; rew_rev; apply~ Mem_app_or. Qed.\n\nLemma Mem_inv : forall A (L:list A) x y,\n  Mem x (y::L) -> x = y \\/ x <> y /\\ Mem x L.\nProof. introv H. tests: (x = y). eauto. inverts H. false. eauto. Qed.\n\nEnd MemFacts.\n\n(* ---------------------------------------------------------------------- *)\n(* ** Update of a functional list *)\n\nDefinition Update A (n:nat) (x:A) l l' :=\n    length l' = length l \n  /\\ (forall y m, Nth m l y -> m <> n -> Nth m l' y)\n  /\\ Nth n l' x.\n\nSection UpdateProp.\nVariables A : Type.\nImplicit Types x : A.\nImplicit Types l : list A.\nImplicit Types n : nat.\nHint Constructors Nth.\n\nLemma Update_here : forall x y l,\n  Update 0 x (y::l) (x::l).\nProof. \n  intros. splits.\n  rew_length~.\n  introv M H. inverts* M.\n  auto*.\nQed.\n\nLemma Update_cons : forall i x y l l',\n  Update i x l l' -> Update (S i) x (y::l) (y::l').\nProof.\n  introv (L&O&E). splits.\n  rew_length~.\n  introv M H. inverts* M.\n  auto*.\nQed.\n\nLemma Update_app_l : forall i x l1 l1' l2,\n  Update i x l1 l1' -> Update i x (l1++l2) (l1'++l2).\nProof.\n  introv (L&O&E). splits.\n  rew_length~.\n  introv M H. destruct (Nth_app_inv _ _ M).\n    apply~ Nth_app_l.\n    intuit. apply* Nth_app_r. math.\n  apply~ Nth_app_l.\nQed.\n\nLemma Update_app_r : forall i j x l1 l2 l2',\n  Update j x l2 l2' -> i = (j + length l1)%nat -> Update i x (l1++l2) (l1++l2').\nProof.\n  introv (L&O&E) Eq. splits.\n  rew_length~.\n  introv M H. destruct (Nth_app_inv _ _ M).\n    apply~ Nth_app_l.\n    intuit. apply* Nth_app_r. apply* O. math. math.\n  apply* Nth_app_r.\nQed.\n\nLemma Update_length : forall i x l l',\n  Update i x l l' -> length l = length l'.\nProof. introv (L&O&E). auto. Qed. \n\nLemma Update_not_nil : forall i x l1 l2,\n  Update i x l1 l2 -> l2 <> nil.\nProof. introv (L&O&E) K. subst. inverts E. Qed.\n\nEnd UpdateProp.\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/LibList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.6762864588390313}}
{"text": "(*\n  Project 2: H10_SAT_to_H10p_SAT\n    Many-one reduction from \n\tDiophantine Equation Solvability to\n  Positive Diophantine Equation Solvability\n\n  Constructive Theory of Computation\n  Summer Semester 2020\n  Saarland University\n\n  Assignees:\n    Ullrich, Marcel\n    Patzek, Jaqueline\n    Spaniol, Daniel\n    (Dutra, Rafael)\n*)\n\nFrom Coq Require Import Lia.\nFrom Coq Require Import ssreflect ssrfun ssrbool.\n\nNotation \" g ∘ f \" := (fun x => g (f x)) (at level 40, left associativity).\n\n(* multivariate Diophantine polynomial *)\nInductive dio : Set :=\n  | dio_var : nat -> dio (* variable *)\n  | dio_one : dio (* constant 1 *)\n  | dio_sum : dio -> dio -> dio (* sum *)\n  | dio_prod : dio -> dio -> dio. (* product *)\n\nNotation \"` n\" := (dio_var n) (at level 30).\nInfix \"`+\" := dio_sum (at level 60).\nInfix \"`*\" := dio_prod (at level 55).\nNotation \"`1\" := dio_one.\nNotation \"`2\" := (dio_sum dio_one dio_one).\n\n(* Diophantine polynomial evaluation wrt. φ *)\nFixpoint eval (φ: nat -> nat) (p: dio) : nat :=\n  match p with\n  | dio_var x => φ x\n  | dio_one => 1\n  | dio_sum q r => eval φ q + eval φ r\n  | dio_prod q r => eval φ q * eval φ r\n  end.\n\n(* Diophantine Equation Solvability *)\nDefinition H10_SAT : (dio * dio) -> Prop :=\n  fun '(p, q) => exists (φ: nat -> nat), eval φ p = eval φ q.\n\n(* Positive Diophantine Equation Solvability *)\nDefinition H10p_SAT : (dio * dio) -> Prop :=\n  fun '(p, q) => exists (φ: nat -> nat), eval (fun x => 1 + φ x) p = eval (fun x => 1 + φ x) q.\n\n(* many-one reduction *)\nDefinition reduces {X Y} (p : X -> Prop) (q : Y -> Prop) := exists f : X -> Y, forall x, p x <-> q (f x).\n(* \n  For all formulas p that evaluate to some n with the valuation ϕ,\n  we can get an equivalent formula q-r that evaluates to n with the\n  valuation S∘ϕ.\n\n      E ϕ p = E (S∘ϕ) (q - r)\n            = E (S∘ϕ) q - E (S∘ϕ) r\n\n  to stay positive we reformulate this as\n\n      E ϕ p + E (S∘ϕ) r = E (S∘ϕ) q\n*)\nDefinition translate (p : dio) : { '(q, r) |\n  forall ϕ, eval ϕ p + eval (S ∘ ϕ) r = eval (S ∘ ϕ) q }.\nProof.\n  elim: p => [ x\n             |\n             | p1 [[q1 r1] IH1] p2 [[q2 r2] IH2]\n             | p1 [[q1 r1] IH1] p2 [[q2 r2] IH2] ].\n  - exists (`x, `1)=> /=. lia.\n  - exists (`2, `1)=> /=. lia.\n  - exists ((q1 `+ q2) , (r1 `+ r2))=> > /=. rewrite -(IH1 _) -(IH2 _) ; lia.\n  - exists ((q1 `* q2 `+ r1 `* r2) , (q1 `* r2 `+ r1 `* q2)) => > /=. rewrite -(IH1 _) -(IH2 _) ; lia.\nDefined.\n    \n(*\n  For all p₁, p₂ we have some q₁,r₁,q₂,r₂ such that:\n\n      E ϕ p₁ = E (S∘ϕ) q₁ - E (S∘ϕ) r₁\n      E ϕ q₁ = E (S∘ϕ) q₂ - E (S∘ϕ) r₂\n\n  From this we get the reduction:\n  \n         E ϕ p₁                  = E ϕ q₁\n      ⇔  E (S∘ϕ) q₁ - E (S∘ϕ) r₁ = E (S∘ϕ) q₂ - E (S∘ϕ) r₂\n      ⇔  E (S∘ϕ) q₁ + E (S∘ϕ) r₂ = E (S∘ϕ) q₂ + E (S∘ϕ) r₁\n*)\nDefinition reduction (p1p2 : dio * dio) : dio * dio :=\n  let (p1 , p2) := p1p2 in\n  let (q1 , r1) := proj1_sig (translate p1) in\n  let (q2 , r2) := proj1_sig (translate p2) in\n  ((q1 `+ r2) , (q2 `+ r1)).\n\nTheorem H10_SAT_to_H10p_SAT : reduces H10_SAT H10p_SAT.\nProof.\n  exists reduction => [[p1 p2]].\n  rewrite /reduction.\n  move: (translate p1) (translate p2) => [[q1 r1] H1] [[q2 r2] H2] /=.\n  split=> [[ϕ]|[ϕ]].\n  - exists ϕ. rewrite -(H1 _) -(H2 _). lia.\n  - rewrite -(H1 _) -(H2 _). exists ϕ. lia.\nQed.\n", "meta": {"author": "NeuralCoder3", "repo": "ctc20", "sha": "5be17b6044da8fdc2102a0b7b0be1f10094fb9fd", "save_path": "github-repos/coq/NeuralCoder3-ctc20", "path": "github-repos/coq/NeuralCoder3-ctc20/ctc20-5be17b6044da8fdc2102a0b7b0be1f10094fb9fd/Project_02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.6762864508622554}}
{"text": "(** *Integers mod p *)\n\n(** By Alvaro Pelayo, Vladimir Voevodsky and Michael A. Warren *)\n\n(** December 2011 *)\n\n(** made compatible with the current UniMath library by Ralph Matthes in October 2017 *)\n\n(** Imports *)\n\nRequire Import UniMath.PAdics.lemmas.\nRequire Import UniMath.NumberSystems.Integers.\nRequire Import UniMath.Foundations.Preamble.\n\nUnset Kernel Term Sharing. (** for quicker proof-checking, approx. by factor 10 *)\n\nLocal Open Scope hz_scope.\n\n(** * I. Divisibility and the division algorithm *)\n\nDefinition hzdiv0 : hz -> hz -> hz -> UU :=\n  fun n m k => n * k = m.\n\nDefinition hzdiv : hrel hz := fun n m => ∃ k : hz, hzdiv0 n m k.\n\nLemma hzdivisrefl : isrefl hzdiv.\nProof.\n  red.\n  intro.\n  unfold hzdiv.\n  apply total2tohexists.\n  split with 1.\n  apply hzmultr1.\nDefined.\n\nLemma hzdivistrans : istrans hzdiv.\nProof.\n  intros a b c p q.\n  use (hinhuniv _ p).\n  intro k.\n  destruct k as [ k f ].\n  use (hinhuniv _ q).\n  intro l.\n  destruct l as [ l g ].\n  intros P s.\n  apply s.\n  unfold hzdiv0 in f, g.\n  split with ( k * l ).\n  red.\n  rewrite <- hzmultassoc.\n  rewrite f.\n  assumption.\nDefined.\n\nLemma hzdivlinearcombleft ( a b c d : hz ) ( f : a = b + c )\n  ( x : hzdiv d a ) ( y : hzdiv d b ) : hzdiv d c.\nProof.\n  intros P s.\n  use (hinhuniv _ x).\n  intro x'.\n  use (hinhuniv _ y).\n  intro y'.\n  apply s.\n  destruct x' as [ k g ].\n  destruct y' as [ l h ].\n  unfold hzdiv0 in *.\n  split with ( k + - l ).\n  rewrite hzldistr.\n  rewrite g.\n  rewrite ( ringrmultminus hz ).\n  change ( ( a + ( - ( d * l ) ) )%hz = c ).\n  rewrite h.\n  apply ( hzplusrcan _ _ b ).\n  rewrite hzplusassoc.\n  rewrite hzlminus.\n  rewrite hzplusr0.\n  rewrite hzpluscomm.\n  assumption.\nDefined.\n\nLemma hzdivlinearcombright ( a b c d : hz ) ( f : a = b + c )\n  ( x: hzdiv d b ) ( y : hzdiv d c ) : hzdiv d a.\nProof.\n  intros P s.\n  use (hinhuniv _ x).\n  intro x'.\n  use (hinhuniv _ y).\n  intro y'.\n  apply s.\n  destruct x' as [ k g ].\n  destruct y' as [ l h ].\n  unfold hzdiv0 in *.\n  split with ( k + l ).\n  rewrite hzldistr.\n  change ( (d * k + d * l)%hz = a ).\n  rewrite g, h, f.\n  apply idpath.\nDefined.\n\nLemma divalgorithmnonneg ( n : nat ) ( m : nat ) ( p : hzlth 0 ( nattohz m ) ) :\n  ∑ qr : hz × hz,\n    nattohz n = ( ( nattohz m ) * ( pr1 qr ) ) + ( pr2 qr )  ×\n        ( hzleh 0 ( pr2 qr ) × hzlth ( pr2 qr ) ( nattohz m ) ).\nProof.\n  revert p.\n  induction n.\n  - intros.\n    split with ( make_dirprod 0 0 ).\n    split.\n    + simpl.\n      rewrite ( ringrunax1 hz ).\n      rewrite ( ringmultx0 hz ).\n      rewrite nattohzand0.\n      change ( 0 = 0%hz ).\n      apply idpath.\n    + split.\n      * apply isreflhzleh.\n      * assumption.\n  - intro p.\n    set ( q' := pr1 ( pr1 ( IHn p ) ) ).\n    set ( r' := pr2 ( pr1 ( IHn p ) ) ).\n    set ( f := pr1 ( pr2 ( IHn p ) ) ).\n    assert ( hzleh ( r' + 1 ) ( nattohz m ) ) as p'.\n    { assert ( hzlth ( r' + 1 ) ( nattohz m + 1 ) ) as p''.\n      { apply hzlthandplusr.\n        apply ( pr2 ( pr2 ( pr2 ( IHn p ) ) ) ).\n      }\n      apply hzlthsntoleh.\n      assumption.\n    }\n    set ( choice := hzlehchoice ( r' + 1 ) ( nattohz m ) p' ).\n    destruct choice as [ k | h ].\n    + split with ( make_dirprod q' ( r' + 1 ) ).\n      split.\n      * rewrite (nattohzandS _ ).\n        rewrite hzpluscomm.\n        rewrite f.\n        change ( nattohz m * q' + r' + 1 = nattohz m * q' + ( r' + 1 ) ).\n        apply ringassoc1.\n      * split.\n        -- apply ( istranshzleh 0 r' ( r' + 1 ) ).\n           ++ apply ( pr2 ( pr2 ( IHn p ) ) ).\n           ++ apply hzlthtoleh.\n              apply hzlthnsn.\n        -- assumption.\n    + split with ( make_dirprod ( q' + 1 ) 0 ).\n      split.\n      * rewrite ( nattohzandS _ ).\n        rewrite hzpluscomm.\n        rewrite f.\n        change ( nattohz m * q' + r' + 1 = nattohz m * ( q' + 1 ) + 0 ).\n        rewrite hzplusassoc.\n        rewrite h.\n        rewrite ( ringldistr _ q' _ ).\n        rewrite ringrunax2.\n        rewrite hzplusr0.\n        apply idpath.\n      * split.\n        -- apply isreflhzleh.\n        -- assumption.\nDefined.\n\n(* A test of the division algorithm for non-negative integers: *)\nLocal Lemma testlemma1 : hzneq 0 1.\nProof.\n  change 0 with ( nattohz 0%nat ).\n  rewrite <- nattohzand1.\n  apply nattohzandneq.\n  intro f.\n  apply ( isirreflnatlth 1 ).\n  assert ( natlth 0 1 ) as i by apply natlthnsn.\n  rewrite <- f in *.\n  assumption.\nDefined.\n\nLocal Lemma testlemma2 : hzneq 0 ( 1 + 1 ).\nProof.\n  change 0 with ( nattohz 0%nat ).\n  rewrite <- nattohzand1.\n  rewrite <- nattohzandplus.\n  apply nattohzandneq.\n  assert ( natneq ( 1 + 1 ) 0 ) as x.\n  { apply ( natgthtoneq ( 1 + 1 ) 0 ).\n    simpl.\n    apply idpath. }\n  intro f.\n  apply pathsinv0 in f.\n  simpl in f.\n  assert (natneq ( 1 + 1 ) 2 ) as y.\n  { rewrite f.\n    assumption. }\n  simpl in y.\n  assumption.\nDefined.\n\nLocal Lemma testlemma21 : hzlth 0 ( nattohz 2 ).\nProof.\n  change 0 with ( nattohz 0%nat ).\n  apply nattohzandlth.\n  apply ( istransnatlth _ 1 ).\n  - apply natlthnsn.\n  - apply natlthnsn.\nDefined.\n\nLocal Lemma testlemma3 : hzlth 0 ( nattohz 3 ).\nProof.\n  apply ( istranshzlth _ ( nattohz 2 ) ).\n  - apply testlemma21.\n  - change 0 with ( nattohz 0%nat ).\n    apply nattohzandlth.\n    apply natlthnsn.\nDefined.\n\nLemma testlemma9 : hzlth 0 ( nattohz 9 ).\nProof.\n  apply ( istranshzlth _ ( nattohz 3 ) ).\n  - apply testlemma3.\n  - apply ( istranshzlth _ ( nattohz 6 ) ).\n    + apply testlemma3.\n    + apply testlemma3.\nDefined.\n\n(*\nEval lazy in hzabsval ( pr1 ( pr1 ( divalgorithmnonneg 1 ( 1 + 1 ) testlemma21 ) ) ).\nEval lazy in hzabsval ( pr1 ( pr1 ( divalgorithmnonneg ( 5 ) ( 1 + 1 ) testlemma21 ) ) ).\nEval lazy in hzabsval ( pr2 ( pr1 ( divalgorithmnonneg ( 5 ) ( 1 + 1 ) testlemma21 ) ) ).\nEval lazy in hzabsval ( pr1 ( pr1 ( divalgorithmnonneg 16 3 testlemma3 ) ) ).\nEval lazy in hzabsval ( pr2 ( pr1 ( divalgorithmnonneg 16 3 testlemma3 ) ) ).\nEval lazy in hzabsval ( pr1 ( pr1 ( divalgorithmnonneg 18 9 testlemma9 ) ) ).\nEval lazy in hzabsval ( pr2 ( pr1 ( divalgorithmnonneg 18 9 testlemma9 ) ) ).\n*)\n\nTheorem divalgorithmexists ( n m : hz ) ( p : hzneq 0 m ) :\n  ∑ qr : hz × hz,\n    n = m * ( pr1 qr ) + pr2 qr ×\n    ( hzleh 0 ( pr2 qr ) ×\n      hzlth ( pr2 qr ) ( nattohz ( hzabsval m ) ) ).\nProof.\n  intros.\n  destruct ( hzlthorgeh n 0 ) as [ n_neg | n_nonneg ].\n  - destruct ( hzlthorgeh m 0 ) as [ m_neg | m_nonneg ].\n    + (*Case I: n<0, m<0:*)\n      set ( n' := hzabsval n ).\n      set ( m' := hzabsval m ).\n      assert ( nattohz m' = ( - m ) ) as f.\n      { apply hzabsvallth0.\n        assumption. }\n      assert ( - - n = - ( nattohz n' ) ) as f0.\n      { rewrite <- ( hzabsvallth0 n_neg ).\n        rewrite ( hzabsvallth0 n_neg ).\n        unfold n'.\n        rewrite ( hzabsvallth0 n_neg ).\n        apply idpath.\n      }\n      assert ( hzlth 0 ( nattohz m' ) ) as p'.\n      { assert ( hzlth 0 ( - m ) ) as q.\n        { apply hzlth0andminus.\n          assumption. }\n        rewrite f.\n        assumption.\n      }\n      set ( a := divalgorithmnonneg n' m' p' ).\n      set ( q := pr1 ( pr1 a ) ).\n      set ( r := pr2 ( pr1 a ) ).\n      set ( Q := q + 1 ).\n      set ( R := - m - r ).\n      destruct ( hzlehchoice 0 r ( pr1 ( pr2 ( pr2 a ) ) )) as [ less | equal ].\n      * split with ( make_dirprod Q R ).\n        split.\n        -- rewrite ( pathsinv0( ringminusminus hz n) ).\n           assert ( - nattohz n' = ( m * Q + R ) ) as f1.\n           { unfold Q.\n             unfold R.\n             rewrite ( pr1 ( ( pr2 a ) ) ).\n             change ( pr1 ( pr1 a ) ) with q.\n             change ( pr2 ( pr1 a ) ) with r.\n             rewrite hzaddinvplus.\n             rewrite <- ( ringlmultminus hz ).\n             rewrite f.\n             rewrite ringminusminus.\n             rewrite ( ringldistr _ q _ _ ).\n             rewrite hzmultr1.\n             change ( ( m * q ) + - r = ( m * q + m ) + ( - m + - r ) ).\n             rewrite hzplusassoc.\n             rewrite <- ( hzplusassoc m _ _ ).\n             change ( m + - m ) with ( m - m ).\n             rewrite hzrminus.\n             rewrite hzplusl0.\n             apply idpath.\n           }\n           exact ( pathscomp0 f0 f1 ).\n        -- split.\n           ++ unfold R.\n              assert ( hzlth r ( - m ) ) as u.\n              { rewrite <- hzabsvalleh0.\n                ** apply ( pr2 ( pr2 ( pr2 ( a ) ) ) ).\n                ** apply hzlthtoleh.\n                   assumption.\n              }\n              rewrite <- ( hzlminus m ).\n              change ( pr2 ( make_dirprod Q ( - m - r ) ) ) with ( - m - r ).\n              apply hzlehandplusl.\n              apply hzlthtoleh.\n              rewrite <- ( ringminusminus hz m ).\n              apply hzlthminusswap.\n              assumption.\n           ++ unfold R.\n              unfold m'.\n              rewrite hzabsvalleh0.\n              ** change ( hzlth ( - m + - r ) ( - m ) ).\n                 assert ( hzlth ( - m - r ) ( - m + 0 ) ) as u.\n                 { apply hzlthandplusl.\n                   apply hzgth0andminus.\n                   exact less.\n                 }\n                 assert ( - m + 0 = ( - m ) ) as f' by apply hzplusr0.\n                 exact ( transportf ( fun x =>\n                                        hzlth ( - m + - r ) x ) f' u ).\n              ** apply hzlthtoleh.\n                 assumption.\n      * split with (make_dirprod q 0 ).\n        split.\n        -- rewrite <- ( ringminusminus hz n ).\n           assert ( - nattohz n' = m * q + 0 ) as f1.\n           { rewrite ( pr1 ( pr2 a ) ).\n             change ( pr1 (pr1 a ) ) with q.\n             change ( pr2 ( pr1 a ) ) with r.\n             rewrite hzplusr0.\n             rewrite ( pathsinv0 equal ).\n             rewrite hzplusr0.\n             assert ( - ( nattohz m' * q ) = - ( nattohz m' ) * q ) as f2.\n             { apply pathsinv0.\n               apply ringlmultminus. }\n             rewrite f2.\n             unfold m'.\n             rewrite hzabsvalleh0.\n             ++ apply ( maponpaths ( fun x => x * q ) ).\n                apply ringminusminus.\n             ++ apply hzlthtoleh.\n                assumption.\n           }\n           exact ( pathscomp0 f0 f1 ).\n        -- split.\n           ++ change ( pr2 ( make_dirprod q 0 ) ) with 0.\n              apply isreflhzleh.\n           ++ rewrite equal.\n              change ( pr2 ( make_dirprod q r ) ) with r.\n              apply ( pr2 ( pr2 ( pr2 a ) ) ).\n    + destruct ( hzgehchoice m 0 m_nonneg ) as [ h | k ].\n      * (*====*)\n        (*Case II: n<0, m>0. *)\n        assert ( hzlth 0 ( nattohz ( hzabsval m ) ) ) as p'.\n        { rewrite hzabsvalgth0.\n          -- apply h.\n          -- assumption. }\n        set ( a := divalgorithmnonneg ( hzabsval n ) ( hzabsval m ) p' ).\n        set ( q' := pr1 ( pr1 a ) ).\n        set ( r' := pr2 ( pr1 a ) ).\n        assert ( n = - - n ) as f0.\n        { apply pathsinv0.\n          apply ringminusminus. }\n        assert ( - - n = - ( nattohz ( hzabsval n ) ) ) as f1.\n        { apply pathsinv0.\n          apply maponpaths.\n          apply hzabsvalleh0.\n          apply hzlthtoleh.\n          assumption.\n        }\n        destruct ( hzlehchoice 0 r' ( pr1 ( pr2 ( pr2 a ) ) ) ) as [ less | equal ].\n        -- split with (make_dirprod ( - q' - 1 ) ( m - r' ) ).\n           split.\n           ++ change ( pr1 ( make_dirprod ( - q' - 1 ) ( m - r' ) ) ) with ( - q' - 1 ).\n              change ( pr2 ( make_dirprod ( - q' - 1 ) ( m - r' ) ) ) with ( m - r' ).\n              change ( - q' - 1 ) with ( - q' + ( - 1%hz ) ).\n              rewrite hzldistr.\n              assert ( - nattohz ( hzabsval n ) =\n                       ( m * ( - q' ) + m * ( - 1%hz ) ) + ( m - r' ) ) as f2.\n              { rewrite ( pr1 ( pr2 a ) ).\n                change ( pr1 ( pr1 a ) ) with q'.\n                change ( pr2 ( pr1 a ) ) with r'.\n                rewrite hzabsvalgth0.\n                ** rewrite hzaddinvplus.\n                   rewrite ( ringrmultminus hz ).\n                   rewrite ( hzplusassoc _ ( m * ( - 1%hz ) ) ).\n                   apply ( maponpaths ( fun x => - ( m * q' ) + x ) ).\n                   assert ( - m + ( m - r' ) = m * ( - 1%hz ) + ( m - r' ) ) as f3.\n                   { apply ( maponpaths ( fun x => x + ( m - r' ) ) ).\n                     apply pathsinv0.\n                     assert ( m * ( - 1%hz ) = - ( m * 1%hz ) ) as f30\n                     by apply ringrmultminus.\n                     assert ( - ( m * 1 ) = - m ) as f31.\n                     { rewrite hzmultr1.\n                       apply idpath. }\n                     rewrite f30.\n                     assumption.\n                   }\n                   assert ( - r' = - m + ( m - r' ) ) as f4.\n                   { change ( - r' = -m + ( m + - r' ) ).\n                     rewrite <- hzplusassoc.\n                     rewrite hzlminus, hzplusl0.\n                     apply idpath.\n                   }\n                   rewrite f4.\n                   assumption.\n                ** assumption.\n              }\n              rewrite f0, f1.\n              assumption.\n           ++ split.\n              ** change ( pr2 ( make_dirprod ( - q' - 1 ) ( m - r' ) ) ) with ( m - r' ).\n                 apply hzlthtoleh.\n                 rewrite <- ( hzrminus r' ).\n                 apply hzlthandplusr.\n                 rewrite <- ( hzabsvalgeh0 m_nonneg ).\n                 apply ( pr2 ( pr2 a ) ).\n              ** rewrite ( hzabsvalgeh0 m_nonneg ).\n                 assert ( hzlth ( m - r' ) ( m + 0 ) ) as u.\n                 { apply hzlthandplusl.\n                   apply hzgth0andminus.\n                   apply less.\n                 }\n                 rewrite hzplusr0 in u.\n                 assumption.\n        -- split with ( make_dirprod ( - q' ) 0 ).\n           split.\n           ++ change ( pr1 ( make_dirprod ( - q' ) 0 ) ) with ( - q' ).\n              change ( pr2 ( make_dirprod ( - q' ) 0 ) ) with 0.\n              assert ( - nattohz ( hzabsval n ) = m * - q' + 0 ) as f2.\n              { rewrite hzplusr0.\n                rewrite ( pr1 ( pr2 a ) ).\n                change ( pr1 ( pr1 a ) ) with q'.\n                change ( pr2 ( pr1 a ) ) with r'.\n                rewrite <- equal.\n                rewrite hzplusr0.\n                rewrite hzabsvalgeh0.\n                ** apply pathsinv0.\n                   apply ringrmultminus.\n                ** assumption.\n              }\n              rewrite f0, f1.\n              assumption.\n           ++ split.\n              ** apply isreflhzleh.\n              ** rewrite equal.\n                 apply ( pr2 ( pr2 ( pr2 a ) ) ).\n      * apply fromempty.\n        rewrite k in p.\n        simpl in p.\n        apply p.\n        apply idpath.\n  - set ( choice2 := hzlthorgeh m 0 ).\n    destruct choice2 as [ m_neg | m_nonneg ].\n    + (*Case III. Assume n>=0, m<0:*)\n      assert ( hzlth 0 ( nattohz ( hzabsval m ) ) ) as p'.\n      { rewrite hzabsvallth0.\n        * rewrite <- ( ringminusminus hz m ) in m_neg.\n          set ( d:= hzlth0andminus m_neg ).\n          rewrite ringminusminus in d.\n          apply d.\n        * assumption.\n      }\n      set ( a := divalgorithmnonneg ( hzabsval n ) ( hzabsval m ) p' ).\n      set ( q' := pr1 ( pr1 a ) ).\n      set ( r' := pr2 ( pr1 a ) ).\n      split with ( make_dirprod ( - q' ) r' ).\n      split.\n      * rewrite <- hzabsvalgeh0.\n        -- rewrite ( pr1 ( pr2 a ) ).\n           change ( pr1 ( pr1 a ) ) with q'.\n           change ( pr2 ( pr1 a ) ) with r'.\n           change ( pr1 ( make_dirprod ( - q' ) r' ) ) with ( - q' ).\n           change ( pr2 ( make_dirprod ( - q' ) r' ) ) with r'.\n           rewrite hzabsvalleh0.\n           ++ apply ( maponpaths ( fun x => x + r' ) ).\n              assert ( - m * q' = - ( m * q' ) ) as f0\n              by apply ringlmultminus.\n              assert ( - ( m * q' ) = m * ( - q' ) ) as f1.\n              { apply pathsinv0.\n                apply ringrmultminus. }\n              exact ( pathscomp0 f0 f1 ).\n           ++ apply hzlthtoleh.\n              assumption.\n        -- assumption.\n      * split.\n        -- apply (pr1 ( pr2 ( pr2 a ) ) ).\n        -- apply ( pr2 ( pr2 ( pr2 a ) ) ).\n    + (*Case IV: n>=0, m>0.*)\n      assert ( hzlth 0 ( nattohz ( hzabsval m ) ) ) as p'.\n      { rewrite hzabsvalgeh0.\n        * destruct ( hzneqchoice 0 m ) as [ l | r ].\n          -- apply p.\n          -- apply fromempty.\n             apply ( isirreflhzgth 0 ).\n             apply ( hzgthgehtrans 0 m 0 ); assumption.\n          -- assumption.\n        * assumption.\n      }\n      set ( a := divalgorithmnonneg ( hzabsval n ) ( hzabsval m ) p' ).\n      set ( q' := pr1 ( pr1 a ) ).\n      set ( r' := pr2 ( pr1 a ) ).\n      split with ( make_dirprod q' r' ).\n      split.\n      -- rewrite <- hzabsvalgeh0.\n         ++ rewrite ( pr1 ( pr2 a ) ).\n            change ( pr1 ( pr1 a ) ) with q'.\n            change ( pr2 ( pr1 a ) ) with r'.\n            change ( pr1 ( make_dirprod q' r' ) ) with q'.\n            change ( pr2 ( make_dirprod q' r' ) ) with r'.\n            rewrite hzabsvalgeh0.\n            ** apply idpath.\n            ** assumption.\n         ++ assumption.\n      -- split.\n         ++ apply ( pr1 ( pr2 ( pr2 a ) ) ).\n         ++ apply ( pr2 ( pr2 ( pr2 a ) ) ).\nDefined.\n\nLemma hzdivhzabsval ( a b : hz ) ( p : hzdiv a b ) :\n  natleh ( hzabsval a ) ( hzabsval b ) ∨ hzabsval b = 0%nat.\nProof.\n  intros P q.\n  apply ( p P ).\n  intro t.\n  destruct t as [ k f ].\n  unfold hzdiv0 in f.\n  apply q.\n  apply natdivleh with ( hzabsval k ).\n  rewrite hzabsvalandmult.\n  rewrite f.\n  apply idpath.\nDefined.\n\nLemma divalgorithm ( n m : hz ) ( p : hzneq 0 m ) :\n  iscontr ( ∑ qr : hz × hz,\n    n = ( m * ( pr1 qr ) ) + ( pr2 qr ) ×\n         ( hzleh 0 ( pr2 qr ) ×\n           hzlth ( pr2 qr ) ( nattohz ( hzabsval m ) ) ) ).\nProof.\n  intros.\n  split with ( divalgorithmexists n m p ).\n  intro t.\n  destruct t as [ qr' t' ].\n  destruct qr' as [ q' r' ].\n  simpl in t'.\n  destruct t' as [ f' p2p2t ].\n  destruct p2p2t as [ p1p2p2t p2p2p2t ].\n  destruct divalgorithmexists as [ qr v ].\n  destruct qr as [ q r ].\n  destruct v as [ f p2p2dae ].\n  destruct p2p2dae as [ p1p2p2dae p2p2p2dae ].\n  simpl in f.\n  simpl in p1p2p2dae.\n  simpl in p2p2p2dae.\n  assert ( r' = r ) as h.\n  { (* Proof that r' = r : *)\n    assert ( m * ( q - q' ) = ( r' - r ) ) as h0.\n    { change ( q - q' ) with ( q + - q' ).\n      rewrite hzldistr.\n      rewrite <- ( hzplusr0 ( r' - r ) ).\n      rewrite <- ( hzrminus ( m * q' ) ).\n      change ( r' - r ) with ( r' + ( - r ) ).\n      rewrite ( hzplusassoc r' ).\n      change ( ( m * q' ) - ( m * q' ) ) with ( ( m * q' ) + ( - ( m * q' ) ) ).\n      rewrite <- ( hzplusassoc ( - r ) ).\n      rewrite ( hzpluscomm ( -r ) ).\n      rewrite <- ( hzplusassoc r' ).\n      rewrite <- ( hzplusassoc r' ).\n      rewrite ( hzpluscomm r' ).\n      rewrite <- f'.\n      rewrite f.\n      rewrite ( hzplusassoc ( m * q ) ).\n      change ( r + - r ) with ( r - r ).\n      rewrite hzrminus.\n      rewrite hzplusr0.\n      rewrite ( ringrmultminus hz ).\n      change ( m * q + - ( m * q' ) ) with ( ( m * q + - ( m * q' ) )%ring ).\n      apply idpath.\n    }\n    assert ( natleh ( hzabsval m ) ( hzabsval ( r' - r ) ) ∨\n             hzabsval ( r' - r ) = 0%nat ) as v.\n    { apply hzdivhzabsval.\n      intro P.\n      intro s.\n      apply s.\n      split with ( q - q' ).\n      unfold hzdiv0.\n      assumption.\n    }\n    assert ( isaprop ( r' = r ) ) as P by apply isasethz.\n    apply ( v ( make_hProp ( r' = r ) P ) ).\n    intro s.\n    destruct s as [ left | right ].\n    - assert ( hzlth ( nattohz ( hzabsval ( r' - r ) ) ) ( nattohz ( hzabsval m ) ) ) as u.\n      { destruct ( hzgthorleh r' r ) as [ greater | lesseq ].\n        + assert ( hzlth 0 ( r' - r ) ) as e.\n          { rewrite <- ( hzrminus r ).\n            apply hzlthandplusr.\n            assumption.\n          }\n          rewrite hzabsvalgth0.\n          * apply hzlthminus.\n            -- exact p2p2p2t.\n            -- exact p2p2p2dae.\n            -- exact p1p2p2dae.\n          * apply e.\n        + destruct ( hzlehchoice r' r lesseq ) as [ less | equal ].\n          * rewrite hzabsvalandminuspos.\n            -- rewrite hzabsvalgth0.\n               ++ apply hzlthminus.\n                  ** exact p2p2p2dae.\n                  ** exact p2p2p2t.\n                  **  exact p1p2p2t.\n               ++ apply hzlthminusequiv.\n                  assumption.\n            -- exact p1p2p2t.\n            -- exact p1p2p2dae.\n          * rewrite equal.\n            rewrite hzrminus.\n            rewrite hzabsval0.\n            rewrite nattohzand0.\n            assert (hzabsval m ≠ 0).\n            { apply hzabsvalneq0.\n              intro Q.\n              rewrite Q in p.\n              simpl in p.\n              apply p.\n              apply idpath.\n            }\n            apply lemmas.hzabsvalneq0. (* the culprit is the prefix [lemmas] *)\n            assumption.\n      }\n      apply fromempty.\n      apply ( isirreflhzlth ( nattohz ( hzabsval m ) ) ).\n      apply ( hzlehlthtrans _ ( nattohz ( hzabsval ( r' - r ) ) ) _ ).\n      + apply nattohzandleh.\n        assumption.\n      + assumption.\n    - assert ( r' = r ) as i.\n      { assert ( r' - r = 0 ) as i0.\n        { apply hzabsvaleq0.\n          assumption. }\n        rewrite <- ( hzplusl0 r ).\n        rewrite <- ( hzplusr0 r' ).\n        assert ( r' + ( r - r ) = ( 0 + r ) ) as i00.\n        { change ( r - r ) with ( r + - r ).\n          rewrite ( hzpluscomm _ ( - r ) ).\n          rewrite <- hzplusassoc.\n          apply ( maponpaths ( fun x : _ => x + r ) ).\n          apply i0.\n        }\n        exact ( transportf ( fun x : _ => ( r' + x = ( 0 + r ) ) )\n                           ( ( hzrminus r ) ) i00 ).\n      }\n      apply i.\n  }\n  assert ( q' = q ) as g.\n  { (* Proof that q' = q:*)\n    rewrite h in f'.\n    rewrite f in f'.\n    apply ( hzmultlcan q' q m ).\n    - intro i.\n      rewrite i in p.\n      simpl in p.\n      apply p.\n      apply idpath.\n    - apply ( hzplusrcan ( m * q' ) ( m * q ) r ).\n      apply pathsinv0.\n      apply f'.\n  }\n  (* Path in direct product: *)\n  assert ( make_dirprod q' r' = ( make_dirprod q r ) ) as j\n  by (apply pathsdirprod; assumption).\n  (* Proof of general path: *)\n  apply ( total2_paths2_f j ).\n  assert ( iscontr ( n = m * q + r ×\n             ( hzleh 0 r ×\n               hzlth r ( nattohz ( hzabsval m ) ) ) ) ) as contract.\n  { change iscontr with ( isofhlevel 0 ).\n    apply isofhleveldirprod.\n    - split with f.\n      intro t.\n      apply isasethz.\n    - apply isofhleveldirprod.\n      + split with p1p2p2dae.\n        intro t.\n        apply hzleh.\n      + split with p2p2p2dae.\n        intro t.\n        apply hzlth.\n  }\n  apply proofirrelevancecontr.\n  assumption.\nDefined.\n\nDefinition hzquotientmod ( p : hz ) ( x : hzneq 0 p ) : hz -> hz :=\n  fun n : hz => pr1 ( pr1 ( divalgorithmexists n p x ) ).\n\nDefinition hzremaindermod ( p : hz ) ( x : hzneq 0 p ) : hz -> hz :=\n  fun n : hz => pr2 ( pr1 ( divalgorithmexists n p x ) ).\n\nDefinition hzdivequationmod ( p : hz ) ( x : hzneq 0 p ) ( n : hz ) :\n  n = p * ( hzquotientmod p x n ) + ( hzremaindermod p x n ) :=\n  pr1 ( pr2 ( divalgorithmexists n p x ) ).\n\nDefinition hzleh0remaindermod ( p : hz ) ( x : hzneq 0 p ) ( n : hz ) :\n  hzleh 0 ( hzremaindermod p x n ) :=\n  pr1 ( pr2 ( pr2 ( divalgorithmexists n p x ) ) ).\n\nDefinition hzlthremaindermodmod ( p : hz ) ( x : hzneq 0 p ) ( n : hz ) :\n  hzlth ( hzremaindermod p x n ) ( nattohz ( hzabsval p ) ) :=\n  pr2 ( pr2 ( pr2 ( divalgorithmexists n p x ) ) ).\n\n(*\nEval lazy in hzabsval ( ( ( hzquotientmod ( 1 + 1 ) testlemma2\n( 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 ) ) ) ).\nEval lazy in hzabsval ( ( ( hzremaindermod ( 1 + 1 ) testlemma2\n( 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 ) ) ) ).\n*)\n\n(** * II. QUOTIENTS AND REMAINDERS *)\n\nDefinition isaprime ( p : hz ) : UU :=\n  hzlth 1 p ×\n  forall m : hz, hzdiv m p -> m = 1 ∨ m = p.\n\nLemma isapropisaprime ( p : hz ) :\n  isaprop ( isaprime p ).\nProof.\n  intros.\n  apply isofhleveldirprod.\n  - apply ( hzlth 1 p ).\n  - apply impred.\n    intro m.\n    apply impredfun.\n    apply ( m = 1 ∨ m = p ).\nDefined.\n\nLemma isaprimetoneq0 { p : hz } ( x : isaprime p ) : hzneq 0 p.\nProof.\n  intros. intros f.\n  apply ( isirreflhzlth 0 ).\n  apply ( istranshzlth _ 1 _ ).\n  - apply hzlthnsn.\n  - rewrite f.\n    apply ( pr1 x ).\nDefined.\n\nLemma hzqrtest ( m : hz ) ( x : hzneq 0 m ) ( a q r : hz ) :\n  a = ( m * q ) + r ×\n  ( hzleh 0 r × hzlth r ( nattohz (hzabsval m ) ) ) ->\n  q = hzquotientmod m x a × r = hzremaindermod m x a.\nProof.\n  intros d.\n  set ( k := tpair ( P := ( fun qr : hz × hz =>\n    a = m * ( pr1 qr ) + pr2 qr ×\n    ( hzleh 0 ( pr2 qr ) × hzlth ( pr2 qr ) ( nattohz ( hzabsval m ) ) ) ) )\n    ( make_dirprod q r ) d ).\n  assert ( k = pr1 ( divalgorithm a m x ) ) as f\n  by apply ( pr2 ( divalgorithm a m x ) ).\n  split.\n  - change q with ( pr1 ( pr1 k ) ).\n    rewrite f.\n    apply idpath.\n  - change r with ( pr2 ( pr1 k ) ).\n    rewrite f.\n    apply idpath.\nDefined.\n\nDefinition hzqrtestq ( m : hz ) ( x : hzneq 0 m ) ( a q r : hz )\n  ( d : a = ( m * q ) + r ×\n        ( hzleh 0 r × hzlth r ( nattohz ( hzabsval m ) ) ) ) :=\n  pr1 ( hzqrtest m x a q r d ).\n\nDefinition hzqrtestr ( m : hz ) ( x : hzneq 0 m ) ( a q r : hz )\n  ( d : a = ( m * q ) + r ×\n        ( hzleh 0 r × hzlth r ( nattohz ( hzabsval m ) ) ) ) :=\n  pr2 ( hzqrtest m x a q r d ).\n\nLemma hzqrand0eq ( p : hz ) ( x : hzneq 0 p ) : 0 = ( p * 0 ) + 0.\nProof.\n  intros.\n  rewrite hzmultx0.\n  rewrite hzplusl0.\n  apply idpath.\nDefined.\n\nLemma hzqrand0ineq ( p : hz ) ( x : hzneq 0 p ) :\n  hzleh 0 0  × hzlth 0 ( nattohz ( hzabsval p ) ).\nProof.\n  intros.\n  split.\n  - apply isreflhzleh.\n  - apply lemmas.hzabsvalneq0. (* [lemmas] is the culprit *)\n    assumption.\nDefined.\n\nLemma hzqrand0q ( p : hz ) ( x : hzneq 0 p ) : hzquotientmod p x 0 = 0.\nProof.\n  intros.\n  apply pathsinv0.\n  apply ( hzqrtestq p x 0 0 0 ).\n  split.\n  - apply ( hzqrand0eq p x ).\n  - apply ( hzqrand0ineq p x ).\nDefined.\n\nLemma hzqrand0r ( p : hz ) ( x : hzneq 0 p ) : hzremaindermod p x 0 = 0.\nProof.\n  intros.\n  apply pathsinv0.\n  apply ( hzqrtestr p x 0 0 0 ).\n  split.\n  - apply ( hzqrand0eq p x ).\n  - apply ( hzqrand0ineq p x ).\nDefined.\n\nLemma hzqrand1eq ( p : hz ) ( is : isaprime p ) : 1 = ( ( p * 0 ) + 1 ).\nProof.\n  intros.\n  rewrite hzmultx0.\n  rewrite hzplusl0.\n  apply idpath.\nDefined.\n\nLemma hzqrand1ineq ( p : hz ) ( is : isaprime p ) :\n  hzleh 0 1 × hzlth 1 ( nattohz ( hzabsval p ) ).\nProof.\n  intros.\n  split.\n  - apply hzlthtoleh.\n    apply hzlthnsn.\n  - rewrite hzabsvalgth0.\n    + apply is.\n    + apply ( istranshzgth _ 1 _ ).\n      * apply is.\n      * apply ( hzgthsnn 0 ).\nDefined.\n\nLemma hzqrand1q ( p : hz ) ( is : isaprime p ) :\n  hzquotientmod p ( isaprimetoneq0 is ) 1 = 0.\nProof.\n  intros.\n  apply pathsinv0.\n  apply ( hzqrtestq p ( isaprimetoneq0 is ) 1 0 1 ).\n  split.\n  - apply ( hzqrand1eq p is ).\n  - apply ( hzqrand1ineq p is ).\nDefined.\n\nLemma hzqrand1r ( p : hz ) ( is : isaprime p ) :\n  hzremaindermod p ( isaprimetoneq0 is ) 1 = 1.\nProof.\n  intros.\n  apply pathsinv0.\n  apply ( hzqrtestr p ( isaprimetoneq0 is ) 1 0 1 ).\n  split.\n  - apply ( hzqrand1eq p is ).\n  - apply ( hzqrand1ineq p is ).\nDefined.\n\nLemma hzqrandselfeq ( p : hz ) ( x : hzneq 0 p ) : p = ( p * 1 + 0 ).\nProof.\n  intros.\n  rewrite hzmultr1.\n  rewrite hzplusr0.\n  apply idpath.\nDefined.\n\nLemma hzqrandselfineq ( p : hz ) ( x : hzneq 0 p ) :\n  hzleh 0 0 × hzlth 0 ( nattohz ( hzabsval p ) ).\nProof.\n  split.\n  - apply isreflhzleh.\n  - apply lemmas.hzabsvalneq0.\n    assumption.\nDefined.\n\nLemma hzqrandselfq ( p : hz ) ( x : hzneq 0 p ) : hzquotientmod p x p = 1.\nProof.\n  intros.\n  apply pathsinv0.\n  apply ( hzqrtestq p x p 1 0 ).\n  split.\n  - apply ( hzqrandselfeq p x ).\n  - apply ( hzqrandselfineq p x ).\nDefined.\n\nLemma hzqrandselfr ( p : hz ) ( x : hzneq 0 p ) : hzremaindermod p x p = 0.\nProof.\n  intros.\n  apply pathsinv0.\n  apply ( hzqrtestr p x p 1 0 ).\n  split.\n  - apply ( hzqrandselfeq p x ).\n  - apply ( hzqrandselfineq p x ).\nDefined.\n\nLemma hzqrandpluseq ( p : hz ) ( x : hzneq 0 p ) ( a c : hz ) :\n  ( a + c ) =\n  ( ( p * ( hzquotientmod p x a + hzquotientmod p x c +\n            hzquotientmod p x ( hzremaindermod p x a + hzremaindermod p x c ) ) ) +\n    hzremaindermod p x ( ( hzremaindermod p x a ) + ( hzremaindermod p x c ) ) ).\nProof.\n  intros.\n  rewrite 2! hzldistr.\n  rewrite hzplusassoc.\n  rewrite <- ( hzdivequationmod p x ( hzremaindermod p x a + hzremaindermod p x c ) ).\n  rewrite hzplusassoc.\n  rewrite ( hzpluscomm ( hzremaindermod p x a ) ).\n  rewrite <- ( hzplusassoc ( p * hzquotientmod p x c ) ).\n  rewrite <- ( hzdivequationmod p x c ).\n  rewrite ( hzpluscomm c ).\n  rewrite <- hzplusassoc.\n  rewrite <- ( hzdivequationmod p x a ).\n  apply idpath.\nDefined.\n\nLemma hzqrandplusineq ( p : hz ) ( x : hzneq 0 p ) ( a c : hz ) :\n  hzleh 0 ( hzremaindermod p x ( hzremaindermod p x a +\n                                           hzremaindermod p x c ) ) ×\n  hzlth ( hzremaindermod p x ( hzremaindermod p x a +\n                                         hzremaindermod p x c ) )\n                  ( nattohz ( hzabsval p ) ).\nProof.\n  intros.\n  split.\n  - apply hzleh0remaindermod.\n  - apply hzlthremaindermodmod.\nDefined.\n\nLemma hzremaindermodandplus ( p : hz ) ( x : hzneq 0 p ) ( a c : hz ) :\n  hzremaindermod p x ( a + c ) =\n  hzremaindermod p x ( hzremaindermod p x a + hzremaindermod p x c ).\nProof.\n  intros.\n  apply pathsinv0.\n  apply ( hzqrtest p x ( a + c ) _ _ ( make_dirprod ( hzqrandpluseq p x a c )\n                                                   ( hzqrandplusineq p x a c ) ) ).\nDefined.\n\nLemma hzquotientmodandplus ( p : hz ) ( x : hzneq 0 p ) ( a c : hz ) :\n  hzquotientmod p x ( a + c ) =\n  ( hzquotientmod p x a + hzquotientmod p x c +\n    hzquotientmod p x ( hzremaindermod p x a + hzremaindermod p x c ) ).\nProof.\n  intros.\n  apply pathsinv0.\n  apply ( hzqrtest p x ( a + c ) _ _ ( make_dirprod ( hzqrandpluseq p x a c )\n                                                   ( hzqrandplusineq p x a c ) ) ).\nDefined.\n\nLemma hzqrandtimeseq ( m : hz ) ( x : hzneq 0 m ) ( a b : hz ) :\n  ( a * b ) =\n  ( ( m * ( ( hzquotientmod m x ) a * ( hzquotientmod m x ) b * m +\n            ( hzremaindermod m x b ) * ( hzquotientmod m x a ) +\n            ( hzremaindermod m x a ) * ( hzquotientmod m x b ) +\n            ( hzquotientmod m x ( hzremaindermod m x a * hzremaindermod m x b ) ) ) ) +\n              hzremaindermod m x ( hzremaindermod m x a * hzremaindermod m x b ) ).\nProof.\n  intros.\n  rewrite 3! hzldistr.\n  rewrite ( hzplusassoc _ _ ( hzremaindermod m x\n              ( hzremaindermod m x a * hzremaindermod m x b ) ) ).\n  rewrite <- hzdivequationmod.\n  rewrite ( hzmultassoc _ _ m ).\n  rewrite <- ( hzmultassoc m _ ( hzquotientmod m x b * m ) ).\n  rewrite ( hzmultcomm _ m ).\n  change ( ((m * hzquotientmod m x a * (m * hzquotientmod m x b))%hz +\n            m * (hzremaindermod m x b * hzquotientmod m x a)%hz)%ring ) with\n           ((m * hzquotientmod m x a * (m * hzquotientmod m x b)) +\n            m * (hzremaindermod m x b * hzquotientmod m x a) )%hz.\n  change ( a * b =\n                 (((m * hzquotientmod m x a * (m * hzquotientmod m x b) +\n                    m * (hzremaindermod m x b * hzquotientmod m x a))%hz +\n                    m * (hzremaindermod m x a * hzquotientmod m x b)%hz)%ring +\n                   hzremaindermod m x a * hzremaindermod m x b) ) with\n          ( a * b =\n                 (((m * hzquotientmod m x a * (m * hzquotientmod m x b) +\n                    m * (hzremaindermod m x b * hzquotientmod m x a)) +\n                    m * (hzremaindermod m x a * hzquotientmod m x b))%hz +\n                    hzremaindermod m x a * hzremaindermod m x b) ).\n  rewrite ( hzplusassoc ( m * hzquotientmod m x a *\n                          ( m * hzquotientmod m x b ) ) _ _ ).\n  rewrite ( hzpluscomm ( m * ( hzremaindermod m x b * hzquotientmod m x a ) )\n                       ( m * ( hzremaindermod m x a * hzquotientmod m x b ) ) ).\n  rewrite <- ( hzmultassoc m ( hzremaindermod m x a ) ( hzquotientmod m x b ) ).\n  rewrite ( hzmultcomm m ( hzremaindermod m x a ) ).\n  rewrite ( hzmultassoc ( hzremaindermod m x a ) m ( hzquotientmod m x b ) ).\n  rewrite <- ( hzplusassoc ( m * hzquotientmod m x a * ( m * hzquotientmod m x b ) )\n                           ( hzremaindermod m x a * ( m * hzquotientmod m x b ) ) _ ).\n  rewrite <- hzrdistr.\n  rewrite <- hzdivequationmod.\n  rewrite hzplusassoc.\n  rewrite ( hzmultcomm ( hzremaindermod m x b ) ( hzquotientmod m x a ) ).\n  rewrite <- ( hzmultassoc m ( hzquotientmod m x a ) ( hzremaindermod m x b ) ).\n  rewrite <- hzrdistr.\n  rewrite <- hzdivequationmod.\n  rewrite <- hzldistr.\n  rewrite <- hzdivequationmod.\n  apply idpath.\nDefined.\n\nLemma hzqrandtimesineq ( m : hz ) ( x : hzneq 0 m ) ( a b : hz ) :\n  hzleh 0 ( hzremaindermod m x ( hzremaindermod m x a *\n                                           hzremaindermod m x b ) ) ×\n  hzlth ( hzremaindermod m x ( hzremaindermod m x a *\n                                         hzremaindermod m x b ) )\n                  ( nattohz ( hzabsval m ) ).\nProof.\n  intros.\n  split.\n  - apply hzleh0remaindermod.\n  - apply hzlthremaindermodmod.\nDefined.\n\nLemma hzquotientmodandtimes ( m : hz ) ( x : hzneq 0 m ) ( a b : hz ) :\n  hzquotientmod m x ( a * b ) =\n  ( ( hzquotientmod m x ) a * ( hzquotientmod m x ) b * m +\n    ( hzremaindermod m x b ) * ( hzquotientmod m x a ) +\n    ( hzremaindermod m x a ) * ( hzquotientmod m x b ) +\n    ( hzquotientmod m x ( hzremaindermod m x a * hzremaindermod m x b ) ) ).\nProof.\n  intros.\n  apply pathsinv0.\n  apply ( hzqrtestq m x ( a * b ) _ ( hzremaindermod m x\n            ( hzremaindermod m x a * hzremaindermod m x b ) ) ).\n  split.\n  - apply hzqrandtimeseq.\n  - apply hzqrandtimesineq.\nDefined.\n\nLemma hzremaindermodandtimes ( m : hz ) ( x : hzneq 0 m ) ( a b : hz ) :\n  hzremaindermod m x ( a * b ) =\n  ( hzremaindermod m x ( hzremaindermod m x a * hzremaindermod m x b ) ).\nProof.\n  intros.\n  apply pathsinv0.\n  apply ( hzqrtestr m x ( a * b )\n                    ( ( hzquotientmod m x ) a * ( hzquotientmod m x ) b * m +\n                      ( hzremaindermod m x b ) * ( hzquotientmod m x a ) +\n                      ( hzremaindermod m x a ) * ( hzquotientmod m x b ) +\n                      ( hzquotientmod m x ( hzremaindermod m x a *\n                                            hzremaindermod m x b ) ) ) _ ).\n  split.\n  - apply hzqrandtimeseq.\n  - apply hzqrandtimesineq.\nDefined.\n\nLemma hzqrandremaindereq ( m : hz ) ( is : hzneq 0 m ) ( n : hz ) :\n  hzremaindermod m is n =\n  ( ( m * ( pr1 ( make_dirprod 0 ( hzremaindermod m is n ) ) ) +\n          ( pr2 ( make_dirprod (@ringunel1 hz ) ( hzremaindermod m is n ) ) ) ) ).\nProof.\n  intros.\n  simpl.\n  rewrite hzmultx0.\n  rewrite hzplusl0.\n  apply idpath.\nDefined.\n\nLemma hzqrandremainderineq ( m : hz ) ( is : hzneq 0 m ) ( n : hz ) :\n  hzleh ( @ringunel1 hz ) ( hzremaindermod m is n ) ×\n  hzlth ( hzremaindermod m is n ) ( nattohz ( hzabsval m ) ).\nProof.\n  intros.\n  split.\n  - apply hzleh0remaindermod.\n  - apply hzlthremaindermodmod.\nDefined.\n\nLemma hzremaindermoditerated ( m : hz ) ( is : hzneq 0 m ) ( n : hz ) :\n  hzremaindermod m is ( hzremaindermod m is n ) = ( hzremaindermod m is n ).\nProof.\n  intros.\n  apply pathsinv0.\n  apply ( hzqrtestr m is ( hzremaindermod m is n ) 0 ( hzremaindermod m is n ) ).\n  split.\n  - apply hzqrandremaindereq.\n  - apply hzqrandremainderineq.\nDefined.\n\nLemma hzqrandremainderq ( m : hz ) ( is : hzneq 0 m ) ( n : hz ) :\n  0 = hzquotientmod m is ( hzremaindermod m is n ).\nProof.\n  intros.\n  apply ( hzqrtestq m is ( hzremaindermod m is n ) 0 ( hzremaindermod m is n ) ).\n  split.\n  - apply hzqrandremaindereq.\n  - apply hzqrandremainderineq.\nDefined.\n\n(** * III. THE EUCLIDEAN ALGORITHM *)\n\nDefinition iscommonhzdiv ( k n m : hz ) :=\n  hzdiv k n × hzdiv k m.\n\nLemma isapropiscommonhzdiv ( k n m : hz ) : isaprop ( iscommonhzdiv k n m ).\nProof.\n  intros.\n  unfold isaprop.\n  apply isofhleveldirprod.\n  - apply hzdiv.\n  - apply hzdiv.\nDefined.\n\nDefinition hzgcd ( n m : hz ) : UU :=\n  ∑ k : hz, iscommonhzdiv k n m ×\n            forall l : hz, iscommonhzdiv l n m -> hzleh l k.\n\nLemma isaprophzgcd0 ( k n m : hz ) :\n  isaprop ( iscommonhzdiv k n m ×\n            forall l : hz, iscommonhzdiv l n m -> hzleh l k ).\nProof.\n  intros.\n  apply isofhleveldirprod.\n  - apply isapropiscommonhzdiv.\n  - apply impred.\n    intro t.\n    apply impredfun.\n    apply hzleh.\nDefined.\n\nLemma isaprophzgcd ( n m : hz ) : isaprop ( hzgcd n m ).\nProof.\n  intros. intros k l.\n  assert ( isofhlevel 2 ( hzgcd n m ) ) as aux.\n  { apply isofhleveltotal2.\n    - apply isasethz.\n    - intros x.\n      apply hlevelntosn.\n      apply isofhleveldirprod.\n      + apply isapropiscommonhzdiv.\n      + apply impred.\n        intro t.\n        apply impredfun.\n        apply ( hzleh t x ).\n  }\n  assert ( k = l ) as f.\n  { destruct k as [ k pq ].\n    destruct pq as [ p q ].\n    destruct l as [ l pq ].\n    destruct pq as [ p' q' ].\n    assert ( k = l ) as f0.\n    { apply isantisymmhzleh.\n      - apply q'.\n        assumption.\n      - apply q.\n        assumption.\n    }\n    apply ( total2_paths2_f f0 ).\n    assert ( isaprop ( iscommonhzdiv l n m ×\n                       forall x : hz, iscommonhzdiv x n m -> hzleh x l ) ) as is.\n    { apply isofhleveldirprod.\n      - apply isapropiscommonhzdiv.\n      - apply impred.\n        intro t.\n        apply impredfun.\n        apply ( hzleh t l ).\n    }\n    apply is.\n  }\n  split with f.\n  intro g.\n  destruct k as [ k pq ].\n  destruct pq as [ p q ].\n  destruct l as [ l pq ].\n  destruct pq as [ p' q' ].\n  apply aux.\nDefined.\n\n(* Euclidean algorithm for calculating the GCD of two numbers (here\nassumed to be natural numbers ( m <= n )):\n\ngcd ( n , m ) := 1. if m = 0, then take n.  2. if m \\neq 0, then\n  divide n = q * m + r and take g := gcd ( m , r ).  *)\n\nLemma hzdivandmultl ( a c d : hz ) ( p : hzdiv d a ) : hzdiv d ( c * a ).\nProof.\n  intros. intros P s.\n  use (hinhuniv _ p).\n  intro k.\n  destruct k as [ k f ].\n  apply s.\n  unfold hzdiv0.\n  split with ( c * k ).\n  rewrite ( hzmultcomm d ).\n  rewrite hzmultassoc.\n  unfold hzdiv0 in f.\n  rewrite ( hzmultcomm k ).\n  rewrite f.\n  apply idpath.\nDefined.\n\nLemma hzdivandmultr ( a c d : hz ) ( p : hzdiv d a ) : hzdiv d ( a * c ).\nProof.\n  intros.\n  rewrite hzmultcomm.\n  apply hzdivandmultl.\n  assumption.\nDefined.\n\nLemma hzdivandminus ( a d : hz ) ( p : hzdiv d a ) : hzdiv d ( - a ).\nProof.\n  intros. intros P s.\n  use (hinhuniv _ p).\n  intro k.\n  destruct k as [ k f ].\n  apply s.\n  split with ( - k ).\n  unfold hzdiv0.\n  unfold hzdiv0 in f.\n  rewrite ( ringrmultminus hz ).\n  apply maponpaths.\n  assumption.\nDefined.\n\nDefinition natgcd ( m n : nat ) : ( natneq 0%nat n ) ->\n                                  ( natleh m n ) ->\n                                  ( hzgcd ( nattohz n ) ( nattohz m ) ).\nProof.\n  revert m n.\n  set ( E := ( fun m : nat => forall n : nat,\n                   ( natneq 0%nat n ) ->\n                   ( natleh m n ) ->\n                   (hzgcd ( nattohz n ) ( nattohz m ) ) ) ).\n  assert ( forall x : nat, E x ) as goal.\n  { apply stronginduction.\n    - (* BASE CASE: *)\n      intros n x0 x1.\n      split with ( nattohz n ).\n      split.\n      + unfold iscommonhzdiv.\n        split.\n        * unfold hzdiv.\n          intros P s.\n          apply s.\n          unfold hzdiv0.\n          split with 1.\n          rewrite hzmultr1.\n          apply idpath.\n        * unfold hzdiv.\n          intros P s.\n          apply s.\n          unfold hzdiv0.\n          split with 0.\n          rewrite hzmultx0.\n          rewrite nattohzand0.\n          apply idpath.\n      + intros l t.\n        destruct t as [ t0 t1 ].\n        destruct ( hzgthorleh l 0 ) as [ left | right ].\n        * rewrite <- hzabsvalgth0.\n          -- apply nattohzandleh.\n             unfold hzdiv in t0.\n             use (hinhuniv _ t0).\n             intro t2.\n             destruct t2 as [ k t2 ].\n             unfold hzdiv0 in t2.\n             assert ( natleh ( hzabsval l ) n ⨿ ( n = 0%nat ) ) as C.\n             { apply ( natdivleh ( hzabsval l ) n ( hzabsval k ) ).\n               apply ( invmaponpathsincl _ isinclnattohz ).\n               rewrite nattohzandmult.\n               rewrite 2! hzabsvalgeh0.\n               ++ assumption.\n               ++ assert ( hzgeh ( l * k ) ( l * 0 ) ) as i.\n                  { rewrite hzmultx0.\n                    rewrite t2.\n                    change 0 with ( nattohz 0%nat ).\n                    apply nattohzandgeh.\n                    apply x1.\n                  }\n                  apply ( hzgehandmultlinv _ _ l ); assumption.\n               ++ apply hzgthtogeh.\n                  assumption.\n             }\n             destruct C as [ C0 | C1 ].\n             ++ assumption.\n             ++ apply fromempty.\n                rewrite C1 in x0.\n                apply x0.\n          -- assumption.\n        * apply ( istranshzleh _ 0 _ ).\n          { assumption. }\n          change 0 with ( nattohz 0%nat ).\n          apply nattohzandleh.\n          assumption.\n    - (* INDUCTION CASE: *)\n      intros m p q. intros n i j.\n      assert ( hzlth 0 ( nattohz m ) ) as p'.\n      { change 0 with ( nattohz 0%nat ).\n        apply nattohzandlth.\n        apply natneq0togth0.\n        apply p.\n      }\n      set ( a := divalgorithmnonneg n m p' ).\n      destruct a as [ qr a ].\n      destruct qr as [ quot rem ].\n      destruct a as [ f a ].\n      destruct a as [ a b ].\n      simpl in b.\n      simpl in f.\n      assert ( natlth ( hzabsval rem ) m ) as p''.\n      { rewrite <- ( hzabsvalandnattohz m ).\n        apply nattohzandlthinv.\n        rewrite 2! hzabsvalgeh0.\n        + assumption.\n        + apply hzgthtogeh.\n          apply ( hzgthgehtrans _ rem ); assumption.\n        + assumption.\n      }\n      assert ( natleh ( hzabsval rem ) n ) as i''.\n      { apply natlthtoleh.\n        apply nattohzandlthinv.\n        rewrite hzabsvalgeh0.\n        + apply ( hzlthlehtrans _ ( nattohz m ) _ ).\n          * assumption.\n          * apply nattohzandleh.\n            assumption.\n        + assumption.\n      }\n      assert ( natneq 0%nat m ) as p'''.\n      { apply issymm_natneq.\n        (* the culprit is using this lemma instead of direct arguments *)\n        assumption.\n      }\n      destruct ( q ( hzabsval rem ) p'' m p''' ( natlthtoleh _ _ p'' ) )\n        as [ rr c ].\n      destruct c as [ c0 c1 ].\n      split with rr.\n      split.\n      + split.\n        * apply ( hzdivlinearcombright ( nattohz n )\n                                       ( nattohz m * quot ) rem rr f ).\n          -- apply hzdivandmultr.\n             exact ( pr1 c0 ).\n          -- rewrite hzabsvalgeh0 in c0.\n             ++ exact ( pr2 c0 ).\n             ++ assumption.\n        * exact ( pr1 c0 ).\n      + intros l o.\n        apply c1.\n        split.\n        * exact ( pr2 o ).\n        * rewrite hzabsvalgeh0.\n          -- apply ( hzdivlinearcombleft ( nattohz n )\n                                         ( nattohz m * quot ) rem l f ).\n             ++ exact ( pr1 o ).\n             ++ apply hzdivandmultr.\n                exact ( pr2 o ).\n          -- assumption.\n  }\n  assumption.\nDefined.\n\nLemma hzgcdandminusl ( m n : hz ) : hzgcd m n = hzgcd ( - m ) n.\nProof.\n  intros.\n  assert ( make_hProp ( hzgcd m n ) ( isaprophzgcd _ _ )\n      = ( make_hProp ( hzgcd ( - m ) n ) ( isaprophzgcd _ _ ) ) ) as x.\n  { apply hPropUnivalence.\n    - intro i.\n      destruct i as [ a i ].\n      destruct i as [ i0 i1 ].\n      destruct i0 as [ j0 j1 ].\n      split with a.\n      split.\n      + split.\n        * use (hinhuniv _ j0).\n          intro k.\n          destruct k as [ k f ].\n          unfold hzdiv0 in f.\n          intros P s.\n          apply s.\n          split with ( - k ).\n          unfold hzdiv0.\n          rewrite ( ringrmultminus hz ).\n          apply maponpaths.\n          assumption.\n        * assumption.\n      + intros l f.\n        apply i1.\n        split.\n        * use (hinhuniv _ ( pr1 f )).\n          intro k.\n          destruct k as [ k g ].\n          unfold hzdiv0 in g.\n          intros P s.\n          apply s.\n          split with ( - k ).\n          unfold hzdiv0.\n          rewrite ( ringrmultminus hz ).\n          rewrite <- ( ringminusminus hz m).\n          apply maponpaths.\n          assumption.\n        * exact ( pr2 f ).\n    - intro i.\n      destruct i as [ a i ].\n      destruct i as [ i0 i1 ].\n      destruct i0 as [ j0 j1 ].\n      split with a.\n      split.\n      + split.\n        * use (hinhuniv _ j0).\n          intro k.\n          destruct k as [ k f ].\n          unfold hzdiv0 in f.\n          intros P s.\n          apply s.\n          split with ( - k ).\n          unfold hzdiv0.\n          rewrite ( ringrmultminus hz ).\n          rewrite <- ( ringminusminus hz m ).\n          apply maponpaths.\n          assumption.\n        * assumption.\n      + intros l f.\n        apply i1.\n        split.\n        * use (hinhuniv _ ( pr1 f )).\n          intro k.\n          destruct k as [ k g ].\n          unfold hzdiv0 in g.\n          intros P s.\n          apply s.\n          split with ( - k ).\n          unfold hzdiv0.\n          rewrite (ringrmultminus hz ).\n          apply maponpaths.\n          assumption.\n        * exact ( pr2 f ).\n  }\n  apply ( base_paths _ _ x ).\nDefined.\n\nLemma hzgcdsymm ( m n : hz ) : hzgcd m n = hzgcd n m.\nProof.\n  intros.\n  assert ( make_hProp ( hzgcd m n ) ( isaprophzgcd _ _ ) =\n         ( make_hProp ( hzgcd n m ) ( isaprophzgcd _ _ ) ) ) as x.\n  { apply hPropUnivalence.\n    - intro i.\n      destruct i as [ a i ].\n      destruct i as [ i0 i1 ].\n      destruct i0 as [ j0 j1 ].\n      split with a.\n      split.\n      + split; assumption.\n      + intros l o.\n        apply i1.\n        split.\n        * exact ( pr2 o ).\n        * exact ( pr1 o ).\n    - intro i.\n      destruct i as [ a i ].\n      destruct i as [ i0 i1 ].\n      destruct i0 as [ j0 j1 ].\n      split with a.\n      split.\n      + split; assumption.\n      + intros l o.\n        apply i1.\n        split.\n        * exact ( pr2 o ).\n        * exact ( pr1 o ).\n  }\n  apply ( base_paths _ _ x ).\nDefined.\n\nLemma hzgcdandminusr ( m n : hz ) : hzgcd m n = hzgcd m ( - n ).\nProof.\n  intros.\n  rewrite 2! ( hzgcdsymm m ).\n  rewrite hzgcdandminusl.\n  apply idpath.\nDefined.\n\nDefinition euclidean ( n m : hz ) ( i : hzneq 0 n )\n           ( p : natleh ( hzabsval m ) ( hzabsval n ) ) :\n  hzgcd n m.\nProof.\n  intros.\n  assert ( natneq 0%nat ( hzabsval n ) ) as j.\n  { (* this proof very different from the original development: *)\n    apply issymm_natneq.\n    apply hzabsvalneq0.\n    intro x.\n    rewrite x in i.\n    simpl in i.\n    apply i.\n    apply idpath.\n  }\n  set ( a := natgcd ( hzabsval m ) ( hzabsval n ) j p ).\n  destruct ( hzlthorgeh 0 n ) as [ left_n | right_n ].\n  - destruct ( hzlthorgeh 0 m ) as [ left_m | right_m ].\n    + rewrite 2! ( hzabsvalgth0 ) in a; assumption.\n    + rewrite hzabsvalgth0 in a.\n      * rewrite hzabsvalleh0 in a.\n        -- rewrite hzgcdandminusr.\n           assumption.\n        -- assumption.\n      * assumption.\n  - destruct ( hzlthorgeh 0 m ) as [ left_m | right_m ].\n    + rewrite ( hzabsvalgth0 left_m ) in a.\n      rewrite hzabsvalleh0 in a.\n      * rewrite hzgcdandminusl.\n        assumption.\n      * assumption.\n    + rewrite 2! hzabsvalleh0 in a.\n      * rewrite hzgcdandminusl.\n        rewrite hzgcdandminusr.\n        assumption.\n      * assumption.\n      * assumption.\nDefined.\n\nTheorem euclideanalgorithm ( n m : hz ) ( i : hzneq 0 n ) :\n  iscontr ( hzgcd n m ).\nProof.\n  intros.\n  destruct ( natgthorleh ( hzabsval m ) ( hzabsval n ) ) as [ left | right ].\n  - assert ( hzneq 0 m ) as i'.\n    { intro f.\n      apply ( negnatlthn0 ( hzabsval n ) ).\n      rewrite <- f in left.\n      rewrite hzabsval0 in left.\n      assumption.\n    }\n    set ( a := euclidean m n i' ( natlthtoleh _ _ left ) ).\n    rewrite hzgcdsymm in a.\n    split with a.\n    intro.\n    apply isaprophzgcd.\n  - split with ( euclidean n m i right ).\n    intro.\n    apply isaprophzgcd.\nDefined.\n\nDefinition gcd ( n m : hz ) ( i : hzneq 0 n ) : hz :=\n  pr1 ( pr1 ( euclideanalgorithm n m i ) ).\n\nDefinition gcdiscommondiv ( n m : hz ) ( i : hzneq 0 n ) :\n  iscommonhzdiv (gcd n m i) n m :=\n  pr1 ( pr2 ( pr1 ( euclideanalgorithm n m i ) ) ).\n\nDefinition gcdisgreatest ( n m : hz ) ( i : hzneq 0 n ):\n  ∏ l : hz, iscommonhzdiv l n m → hzleh l (gcd n m i) :=\n  pr2 ( pr2 ( pr1 ( euclideanalgorithm n m i ) ) ).\n\nLemma hzdivand0 ( n : hz ) : hzdiv n 0.\nProof.\n  intros. intros P s.\n  apply s.\n  split with 0.\n  unfold hzdiv0.\n  apply hzmultx0.\nDefined.\n\nLemma nozerodiv ( n : hz ) ( i : hzneq 0 n ) : neg ( hzdiv 0 n ).\nProof.\n  intros. intro p.\n  unfold hzneq in i. (* is crucial *)\n  simpl in i.\n  apply i.\n  apply ( p ( make_hProp ( 0 = n ) ( isasethz 0 n ) ) ).\n  intro t.\n  destruct t as [ k f ].\n  unfold hzdiv0 in f.\n  rewrite ( hzmult0x ) in f.\n  assumption.\nDefined.\n\n\n(** * IV. Bezout's lemma and the commutative ring Z/pZ *)\n\nLemma commonhzdivsignswap ( k n m : hz ) ( p : iscommonhzdiv k n m ) :\n  iscommonhzdiv ( - k ) n m .\nProof.\n  intros.\n  destruct p as [ p0 p1 ].\n  split.\n  - use (hinhuniv _ p0).\n    intro t. intros P s.\n    apply s.\n    destruct t as [ l f ].\n    unfold hzdiv0 in f.\n    split with ( - l ).\n    unfold hzdiv0.\n    change ( k * l ) with ( k * l )%ring in f.\n    rewrite <- ringmultminusminus in f.\n    assumption.\n  - use (hinhuniv _ p1).\n    intro t.\n    destruct t as [ l f ].\n    unfold hzdiv0 in f.\n    intros P s.\n    apply s.\n    split with ( - l ).\n    unfold hzdiv0.\n    change ( k * l ) with ( k * l )%ring in f.\n    rewrite <- ringmultminusminus in f.\n    assumption.\nDefined.\n\nLemma gcdneq0 ( n m : hz ) ( i : hzneq 0 n ) : hzneq 0 ( gcd n m i ).\nProof.\n  intros.\n  intro f.\n  apply ( nozerodiv n ).\n  - assumption.\n  - rewrite f.\n    exact ( pr1 ( gcdiscommondiv n m i ) ).\nDefined.\n\nLemma gcdpositive ( n m : hz ) ( i : hzneq 0 n ) : hzlth 0 ( gcd n m i ).\nProof.\n  intros.\n  destruct ( hzneqchoice 0 ( gcd n m i )\n                           ( gcdneq0 n m i ) ) as [ left | right ].\n  - apply fromempty.\n    assert ( hzleh ( - ( gcd n m i ) ) ( gcd n m i ) ) as i0.\n    { apply ( gcdisgreatest n m i ).\n      apply commonhzdivsignswap.\n      exact ( gcdiscommondiv n m i ).\n    }\n    apply ( isirreflhzlth 0 ).\n    apply ( istranshzlth _ ( - ( gcd n m i ) ) _ ).\n    + apply hzlth0andminus.\n      assumption.\n    + apply ( hzlehlthtrans _ ( gcd n m i ) _ ); assumption.\n  - assumption.\nDefined.\n\nLemma gcdanddiv ( n m : hz ) ( i : hzneq 0 n ) ( p : hzdiv n m ) :\n  ( gcd n m i = n )  ⨿ ( gcd n m i = - n ).\nProof.\n  intros.\n  destruct ( hzneqchoice 0 n i ) as [ left | right ].\n  - apply ii2.\n    apply isantisymmhzleh.\n    + use (hinhuniv _\n        ( hzdivhzabsval ( gcd n m i ) n ( pr1 ( gcdiscommondiv n m i ) ) )).\n      intro c'.\n      destruct c' as [ c0 | c1 ].\n      * rewrite <- hzabsvalgeh0.\n        -- rewrite <- hzabsvallth0.\n           ++ apply nattohzandleh.\n              assumption.\n           ++ assumption.\n        -- apply hzgthtogeh.\n           apply ( gcdpositive n m i ).\n      * apply fromempty.\n        assert ( n = 0 ) as f.\n        { rewrite hzabsvaleq0.\n          -- apply idpath.\n          -- assumption.\n        }\n        unfold hzneq in i. (* crucial *)\n        apply i.\n        apply pathsinv0.\n        assumption.\n    + apply gcdisgreatest.\n      apply commonhzdivsignswap.\n      split.\n      * apply hzdivisrefl.\n      * assumption.\n  - apply ii1.\n    apply isantisymmhzleh.\n    + use (hinhuniv _\n        ( hzdivhzabsval ( gcd n m i ) n ( pr1 ( gcdiscommondiv n m i ) ) )).\n      intro c'.\n      destruct c' as [ c0 | c1 ].\n      * rewrite <- hzabsvalgth0.\n        -- assert ( n = nattohz ( hzabsval n ) ) as f.\n           { apply pathsinv0.\n             apply hzabsvalgth0.\n             assumption.\n           }\n           assert ( hzleh ( nattohz ( hzabsval ( gcd n m i ) ) )\n                          ( nattohz ( hzabsval n ) ) ) as j.\n           { apply nattohzandleh.\n             assumption. }\n           exact ( transportf ( fun x =>\n             hzleh ( nattohz ( hzabsval ( gcd n m i ) ) ) x ) ( pathsinv0 f ) j ).\n        -- apply gcdpositive.\n      * apply fromempty.\n        unfold hzneq in i. (* crucial *)\n        apply i.\n        apply pathsinv0.\n        rewrite hzabsvaleq0.\n        -- apply idpath.\n        -- assumption.\n    + apply ( gcdisgreatest n m i ).\n      split.\n      * apply hzdivisrefl.\n      * assumption.\nDefined.\n\nLemma gcdand0 ( n : hz ) ( i : hzneq 0 n ) :\n  ( gcd n 0 i = n ) ⨿ ( gcd n 0 i = - n ).\nProof.\n  intros.\n  apply gcdanddiv.\n  apply hzdivand0.\nDefined.\n\nLemma natbezoutstrong ( m n : nat ) ( i : hzneq 0 ( nattohz n ) ) :\n  ∑ ab : hz × hz,\n       gcd ( nattohz n ) ( nattohz m ) i =\n       pr1 ab * nattohz n + pr2 ab * nattohz m.\nProof.\n  revert m n i.\n  set ( E := ( fun m : nat => forall n : nat, forall i : hzneq 0 ( nattohz n ),\n          ∑ ab : hz × hz,\n            gcd ( nattohz n ) ( nattohz m ) i =\n            pr1 ab * nattohz n + pr2 ab * nattohz m ) ).\n  assert ( forall x : nat, E x ) as goal.\n  { apply stronginduction.\n    - (* Base Case: *)\n      unfold E.\n      intros.\n      split with ( make_dirprod 1 0 ).\n      simpl.\n      rewrite nattohzand0.\n      destruct ( gcdand0 ( nattohz n ) i ) as [ left | right ].\n      + rewrite hzmultl1.\n        rewrite hzplusr0.\n        assumption.\n      + apply fromempty.\n        apply ( isirreflhzlth ( gcd ( nattohz n ) 0 i ) ).\n        apply ( istranshzlth _ 0 _ ).\n        * rewrite right.\n          apply hzgth0andminus.\n          change 0 with ( nattohz 0%nat ).\n          apply nattohzandgth.\n          apply natneq0togth0.\n          use (pr1 (natneq_iff_neq _ _)). (* this is the culprit for advancing *)\n          intro f.\n          unfold hzneq in i. (* crucial *)\n          apply i.\n          rewrite f.\n          apply idpath.\n        * apply gcdpositive.\n    - (* Induction Case: *)\n      intros m x y. intros n i.\n      assert ( hzneq 0 ( nattohz m ) ) as p.\n      { intro f.\n        set (aux := pr2 (natneq_iff_neq _ _) x). (* this is the culprit for advancing *)\n        apply aux.\n        apply pathsinv0.\n        rewrite <- hzabsvalandnattohz.\n        change 0%nat with ( hzabsval ( nattohz 0%nat ) ).\n        apply maponpaths.\n        assumption.\n      }\n      set ( r := hzremaindermod ( nattohz m ) p ( nattohz n ) ).\n      set ( q := hzquotientmod ( nattohz m ) p ( nattohz n ) ).\n      assert ( natlth (hzabsval r ) m ) as p'.\n      { rewrite <- ( hzabsvalandnattohz m ).\n        apply hzabsvalandlth.\n        + exact ( hzleh0remaindermod ( nattohz m ) p ( nattohz n ) ).\n        + unfold r.\n          rewrite <- ( hzabsvalgeh0 ( hzleh0remaindermod ( nattohz m ) p ( nattohz n ) ) ).\n          apply nattohzandlth.\n          assert ( natlth ( hzabsval ( hzremaindermod ( nattohz m ) p ( nattohz n ) ) )\n                          ( hzabsval ( nattohz m ) ) ) as ii.\n          { apply hzabsvalandlth.\n            * exact ( hzleh0remaindermod ( nattohz m ) p ( nattohz n ) ).\n            * assert ( nattohz ( hzabsval ( nattohz m ) ) = nattohz m ) as f.\n              { apply maponpaths.\n                apply hzabsvalandnattohz.\n              }\n              exact ( transportf ( fun x =>\n                                     hzlth\n                                       ( hzremaindermod ( nattohz m ) p ( nattohz n ) ) x ) f\n                                 ( hzlthremaindermodmod ( nattohz m ) p ( nattohz n ) )\n                    ).\n          }\n          exact ( transportf ( fun x =>\n                                 natlth\n                                   ( hzabsval ( hzremaindermod ( nattohz m ) p ( nattohz n ) ) )\n                                   x )\n                             ( hzabsvalandnattohz m ) ii ).\n      }\n      set ( c := y ( hzabsval r ) p' m p ).\n      destruct c as [ ab f ].\n      destruct ab as [ a b ].\n      simpl in f.\n      (* split with ( make_dirprod ( ( nattohz n ) - q * ( nattohz m ) ) ( a - b * q ) ).*)\n      split with ( make_dirprod b ( a - b * q ) ).\n      assert ( gcd ( nattohz m ) ( nattohz ( hzabsval r ) ) p =\n             ( gcd ( nattohz n ) ( nattohz m ) i ) ) as g.\n      { apply isantisymmhzleh.\n        + apply ( gcdisgreatest ( nattohz n ) ( nattohz m ) i ).\n          split.\n          * apply ( hzdivlinearcombright ( nattohz n )\n              ( nattohz m * hzquotientmod ( nattohz m ) p ( nattohz n ) ) r ).\n            -- exact ( hzdivequationmod ( nattohz m ) p ( nattohz n ) ).\n            -- apply hzdivandmultr.\n               apply gcdiscommondiv.\n            -- unfold r.\n               rewrite ( hzabsvalgeh0 ( hzleh0remaindermod ( nattohz m ) p ( nattohz n ) ) ) .\n               apply ( pr2 ( gcdiscommondiv ( nattohz m )\n                               ( hzremaindermod ( nattohz m ) p ( nattohz n ) ) p ) ).\n          * apply gcdiscommondiv.\n        + apply gcdisgreatest.\n          split.\n          * apply ( pr2 ( gcdiscommondiv _ _ _ ) ).\n          * apply ( hzdivlinearcombleft ( nattohz n ) ( nattohz m *\n              hzquotientmod ( nattohz m ) p ( nattohz n ) ) ( nattohz ( hzabsval r ) ) ).\n            -- unfold r.\n               rewrite ( hzabsvalgeh0 ( hzleh0remaindermod ( nattohz m ) p ( nattohz n ) ) ).\n               exact ( hzdivequationmod ( nattohz m ) p ( nattohz n ) ).\n            -- apply gcdiscommondiv.\n            -- apply hzdivandmultr.\n               apply ( pr2 ( gcdiscommondiv _ _ _ ) ).\n      }\n      rewrite <- g.\n      rewrite f.\n      simpl.\n      assert ( nattohz ( hzabsval r ) = ( nattohz n  - ( q * nattohz m ) ) ) as h.\n      { rewrite ( hzdivequationmod ( nattohz m ) p ( nattohz n ) ).\n        change ( hzquotientmod ( nattohz m ) p ( nattohz n ) ) with q.\n        change ( hzremaindermod ( nattohz m ) p ( nattohz n ) ) with r.\n        rewrite hzpluscomm.\n        change (r + nattohz m * q - q * nattohz m) with\n        ( ( r + nattohz m * q ) + ( - ( q * nattohz m ) ) ).\n        rewrite hzmultcomm.\n        rewrite hzplusassoc.\n        (* Coq hangs on the following command:\n        change (q * nattohz m + - (q * nattohz m)) with\n               (q * nattohz m - (q * nattohz m)).\n         *)\n        intermediate_path (r + 0).\n        + rewrite hzplusr0.\n          apply hzabsvalgeh0.\n          apply ( hzleh0remaindermod ( nattohz m ) p ( nattohz n ) ).\n        + apply maponpaths.\n          (* Coq again hangs on the following command:\n          change (q * nattohz m + - (q * nattohz m)) with\n               (q * nattohz m - (q * nattohz m)).\n          *)\n          rewrite <- (hzrminus (q * nattohz m)).\n          apply idpath.\n      }\n      rewrite h.\n      change ( (nattohz n - q * nattohz m) ) with\n             ( (nattohz n + ( - ( q * nattohz m) ) ) ) at 1.\n      rewrite ( ringldistr hz ).\n      rewrite <- hzplusassoc.\n      rewrite ( hzpluscomm ( a * nattohz m ) ).\n      rewrite ringrmultminus.\n      rewrite <- hzmultassoc.\n      rewrite <- ringlmultminus.\n      rewrite hzplusassoc.\n      rewrite <- ( ringrdistr hz ).\n      change (b * nattohz n + (a - b * q) * nattohz m) with\n            ((b * nattohz n)%ring + ((a + - (b * q)%hz) * nattohz m)%ring).\n      apply idpath.\n  }\n  apply goal.\nDefined.\n\nLemma divandhzabsval ( n : hz ) : hzdiv n ( nattohz ( hzabsval n ) ).\nProof.\n  intros.\n  destruct ( hzlthorgeh 0 n ) as [ left | right ].\n  - intros P s.\n    apply s.\n    split with 1.\n    unfold hzdiv0.\n    rewrite hzmultr1.\n    rewrite hzabsvalgth0.\n    + apply idpath.\n    + assumption.\n  - intros P s.\n    apply s.\n    split with ( - 1%hz ).\n    unfold hzdiv0.\n    rewrite ( ringrmultminus hz ).\n    rewrite hzmultr1.\n    rewrite hzabsvalleh0.\n    + apply idpath.\n    + assumption.\nDefined.\n\nLemma bezoutstrong ( m n : hz ) ( i : hzneq 0 n ) :\n  ∑ ab : hz × hz, gcd n m i = pr1 ab  * n + pr2 ab  * m.\nProof.\n  intros.\n  assert ( hzneq 0 ( nattohz ( hzabsval n ) ) ) as i'.\n  { intro f.\n    unfold hzneq in i. (* crucial *)\n    apply i.\n    destruct ( hzneqchoice 0 n i ) as [ left | right ].\n    - rewrite hzabsvallth0 in f.\n      + rewrite <- ( ringminusminus hz ).\n        change 0 with ( - - 0 ).\n        apply maponpaths.\n        assumption.\n      + assumption.\n    - rewrite hzabsvalgth0 in f; assumption.\n  }\n  set ( c := (natbezoutstrong (hzabsval m) (hzabsval n) i')).\n  destruct c as [ ab f ].\n  destruct ab as [ a b ].\n  simpl in f.\n  assert ( gcd n m i =\n           gcd ( nattohz ( hzabsval n ) ) ( nattohz ( hzabsval m ) ) i' ) as g.\n  { destruct ( hzneqchoice 0 n i ) as [ left_n | right_n ].\n    - apply isantisymmhzleh.\n      + apply gcdisgreatest.\n        split.\n        * rewrite hzabsvallth0.\n          -- apply hzdivandminus.\n             apply gcdiscommondiv.\n          -- assumption.\n        * destruct ( hzlthorgeh 0 m ) as [ left_m | right_m ].\n          -- rewrite hzabsvalgth0.\n             ++ apply ( pr2 ( gcdiscommondiv _ _ _ ) ).\n             ++ assumption.\n          -- rewrite hzabsvalleh0.\n             ++ apply hzdivandminus.\n                apply ( pr2 ( gcdiscommondiv _ _ _ ) ).\n             ++ assumption.\n      + apply gcdisgreatest.\n        split.\n        * apply ( hzdivistrans _ ( nattohz ( hzabsval n ) ) _ ).\n          -- apply gcdiscommondiv.\n          -- rewrite hzabsvallth0.\n             ++ rewrite <- ( ringminusminus hz n ).\n                apply hzdivandminus.\n                rewrite ( ringminusminus hz n ).\n                apply hzdivisrefl.\n             ++ assumption.\n        * apply ( hzdivistrans _ ( nattohz ( hzabsval m ) ) _ ).\n          -- apply ( pr2 ( gcdiscommondiv _ _ _ ) ).\n          -- destruct ( hzlthorgeh 0 m ) as [ left_m | right_m ].\n             ++ rewrite hzabsvalgth0.\n                ** apply hzdivisrefl.\n                ** assumption.\n             ++ rewrite hzabsvalleh0.\n                ** rewrite <- ( ringminusminus hz m ).\n                   apply hzdivandminus.\n                   rewrite ( ringminusminus hz m ).\n                   apply hzdivisrefl.\n                ** assumption.\n    - apply isantisymmhzleh.\n      + apply gcdisgreatest.\n        split.\n        * rewrite hzabsvalgth0.\n          -- apply gcdiscommondiv.\n          -- assumption.\n        * apply ( hzdivistrans _ ( nattohz ( hzabsval m ) ) _ ).\n          -- destruct ( hzlthorgeh 0 m ) as [ left_m | right_m ].\n             ++ rewrite hzabsvalgth0.\n                ** apply ( pr2 ( gcdiscommondiv _ _ _ ) ).\n                ** assumption.\n             ++ rewrite hzabsvalleh0.\n                ** apply hzdivandminus.\n                   apply ( pr2 ( gcdiscommondiv _ _ _ ) ).\n                ** assumption.\n          -- apply hzdivisrefl.\n      + apply gcdisgreatest.\n        split.\n        * apply ( hzdivistrans _ ( nattohz ( hzabsval n ) ) _ ).\n          -- apply gcdiscommondiv.\n          -- rewrite hzabsvalgth0.\n             ++ apply hzdivisrefl.\n             ++ assumption.\n        * apply ( hzdivistrans _ ( nattohz ( hzabsval m ) ) _ ).\n          -- apply ( pr2 ( gcdiscommondiv _ _ _ ) ).\n          -- destruct ( hzlthorgeh 0 m ) as [ left_m | right_m ].\n             ++ rewrite hzabsvalgth0.\n                ** apply hzdivisrefl.\n                ** assumption.\n             ++ rewrite hzabsvalleh0.\n                ** rewrite <- ( ringminusminus hz m ).\n                   apply hzdivandminus.\n                   rewrite ( ringminusminus hz m ).\n                   apply hzdivisrefl.\n                ** assumption.\n  }\n  destruct ( hzneqchoice 0 n i ) as [ left_n | right_n ].\n  - destruct ( hzlthorgeh 0 m ) as [ left_m | right_m ].\n    + split with ( make_dirprod ( - a ) b ).\n      simpl.\n      assert ( - a * n + b * m =\n             ( a * nattohz ( hzabsval n ) + b * nattohz ( hzabsval m ) ) ) as l.\n      { rewrite hzabsvallth0.\n        * rewrite hzabsvalgth0.\n          -- rewrite ( ringlmultminus hz ).\n             rewrite <- ( ringrmultminus hz ).\n             apply idpath.\n          -- assumption.\n        * assumption.\n      }\n      rewrite l.\n      rewrite g.\n      exact f.\n    + split with ( make_dirprod ( - a ) ( - b ) ).\n      simpl.\n      rewrite 2! ( ringlmultminus hz ).\n      rewrite <- 2! ( ringrmultminus hz ).\n      rewrite <- hzabsvallth0.\n      * rewrite <- hzabsvalleh0.\n        -- rewrite g.\n           exact f.\n        -- assumption.\n      * assumption.\n  - destruct ( hzlthorgeh 0 m ) as [ left_m | right_m ].\n    + split with ( make_dirprod a b ).\n      simpl.\n      rewrite g.\n      rewrite f.\n      rewrite 2! hzabsvalgth0.\n      * apply idpath.\n      * assumption.\n      * assumption.\n    + split with ( make_dirprod a ( - b ) ).\n      rewrite g.\n      rewrite f.\n      simpl.\n      rewrite hzabsvalgth0.\n      * rewrite hzabsvalleh0.\n        -- rewrite ( ringrmultminus hz ).\n           rewrite <- ( ringlmultminus hz ).\n           apply idpath.\n        -- assumption.\n      * assumption.\nDefined.\n\n(** * V. Z/nZ *)\n\nLemma hzmodisaprop ( p : hz ) ( x : hzneq 0 p ) ( n m : hz ) :\n  isaprop ( hzremaindermod p x n = hzremaindermod p x m ).\nProof.\n  intros.\n  apply isasethz.\nDefined.\n\nDefinition hzmod ( p : hz ) ( x : hzneq 0 p ) : hrel hz.\nProof.\n  intros n m.\n  exact ( make_hProp ( hzremaindermod p x n = hzremaindermod p x m )\n                    ( hzmodisaprop p x n m ) ).\nDefined.\n\nLemma hzmodisrefl ( p : hz ) ( x : hzneq 0 p ) : isrefl ( hzmod p x ).\nProof.\n  intros.\n  unfold isrefl.\n  intro n.\n  unfold hzmod.\n  assert ( hzremaindermod p x n = hzremaindermod p x n ) as a\n      by apply idpath.\n  apply a.\nDefined.\n\nLemma hzmodissymm ( p : hz ) ( x : hzneq 0 p ) : issymm ( hzmod p x ).\nProof.\n  intros.\n  unfold issymm.\n  intros n m.\n  unfold hzmod.\n  intro v.\n  assert ( hzremaindermod p x m = hzremaindermod p x n ) as a\n  by exact ( pathsinv0 v ).\n  apply a.\nDefined.\n\nLemma hzmodistrans ( p : hz ) ( x : hzneq 0 p ) : istrans ( hzmod p x ).\nProof.\n  intros.\n  unfold istrans.\n  intros n m k. intros u v.\n  unfold hzmod.\n  unfold hzmod in u.\n  unfold hzmod in v.\n  assert ( hzremaindermod p x n = hzremaindermod p x k ) as a\n  by exact ( pathscomp0 u v ).\n  apply a.\nDefined.\n\nLemma hzmodiseqrel ( p : hz ) ( x : hzneq 0 p ) : iseqrel ( hzmod p x ).\nProof.\n  intros.\n  apply iseqrelconstr.\n  - exact ( hzmodistrans p x ).\n  - exact ( hzmodisrefl p x ).\n  - exact ( hzmodissymm p x ).\nDefined.\n\nLemma hzmodcompatmultl ( p : hz ) ( x : hzneq 0 p ) :\n  forall a b c : hz, hzmod p x a b -> hzmod p x ( c * a ) ( c * b ).\nProof.\n  intros a b c v.\n  unfold hzmod.\n  change (hzremaindermod p x (c * a) = hzremaindermod p x (c * b)).\n  rewrite hzremaindermodandtimes.\n  rewrite v.\n  rewrite <- hzremaindermodandtimes.\n  apply idpath.\nDefined.\n\nLemma hzmodcompatmultr ( p : hz ) ( x : hzneq 0 p ) :\nforall a b c : hz, hzmod p x a b -> hzmod p x ( a * c ) ( b * c ).\nProof.\n  intros a b c v.\n  rewrite hzmultcomm.\n  rewrite ( hzmultcomm b ).\n  apply hzmodcompatmultl.\n  assumption.\nDefined.\n\nLemma hzmodcompatplusl ( p : hz ) ( x : hzneq 0 p ) :\n  forall a b c : hz, hzmod p x a b -> hzmod p x ( c + a ) ( c + b ).\nProof.\n  intros a b c v.\n  unfold hzmod.\n  change ( hzremaindermod p x ( c + a ) = hzremaindermod p x ( c + b ) ).\n  rewrite hzremaindermodandplus.\n  rewrite v.\n  rewrite <- hzremaindermodandplus.\n  apply idpath.\nDefined.\n\nLemma hzmodcompatplusr ( p : hz ) ( x : hzneq 0 p ) :\n  forall a b c : hz, hzmod p x a b -> hzmod p x ( a + c ) ( b + c ).\nProof.\n  intros a b c v.\n  rewrite hzpluscomm.\n  rewrite ( hzpluscomm b ).\n  apply hzmodcompatplusl.\n  assumption.\nDefined.\n\nLemma hzmodisringeqrel ( p : hz ) ( x : hzneq 0 p ) : ringeqrel ( X := hz ).\nProof.\n  intros.\n  split with ( tpair ( hzmod p x ) ( hzmodiseqrel p x ) ).\n  split.\n  - split.\n    + apply hzmodcompatplusl.\n    + apply hzmodcompatplusr.\n  - split.\n    + apply hzmodcompatmultl.\n    + apply hzmodcompatmultr.\nDefined.\n\nDefinition hzmodp ( p : hz ) ( x : hzneq 0 p ) :=\n  commringquot ( hzmodisringeqrel p x ).\n\nLemma isdeceqhzmodp ( p : hz ) ( x : hzneq 0 p ) : isdeceq ( hzmodp p x ).\nProof.\n  intros.\n  apply ( isdeceqsetquot ( hzmodisringeqrel p x ) ).\n  intros a b.\n  unfold isdecprop.\n  - destruct ( isdeceqhz ( hzremaindermod p x a )\n                       ( hzremaindermod p x b ) ) as [ l | r ].\n    + unfold hzmodisringeqrel.\n      simpl.\n      split.\n      * apply ii1.\n        assumption.\n      * apply isasethz.\n    + unfold hzmodisringeqrel.\n      simpl.\n      split.\n      * apply ii2.\n        assumption.\n      * apply isasethz.\nDefined.\n\nDefinition acommring_hzmod ( p : hz ) ( x : hzneq 0 p ) : acommring.\nProof.\n  intros.\n  split with ( hzmodp p x ).\n  split with ( tpair _ ( deceqtoneqapart ( isdeceqhzmodp p x ) ) ).\n  split.\n  - split.\n    + intros a b c q.\n      simpl.\n      simpl in q.\n      intro f.\n      apply q.\n      rewrite f.\n      apply idpath.\n    + intros a b c q.\n      simpl in q.\n      simpl.\n      intro f.\n      apply q.\n      rewrite f.\n      apply idpath.\n  - split.\n    + intros a b c q.\n      simpl in q.\n      simpl.\n      intros f.\n      apply q.\n      rewrite f.\n      apply idpath.\n    + intros a b c q.\n      simpl.\n      simpl in q.\n      intro f.\n      apply q.\n      rewrite f.\n      apply idpath.\nDefined.\n\nLemma hzremaindermodanddiv ( p : hz ) ( x : hzneq 0 p ) ( a : hz )\n      ( y : hzdiv p a ) : hzremaindermod p x a = 0.\nProof.\n  intros.\n  assert ( isaprop ( hzremaindermod p x a = 0 ) ) as v\n  by apply isasethz.\n  apply ( y ( make_hProp _ v ) ).\n  intro t.\n  destruct t as [ k f ].\n  unfold hzdiv0 in f.\n  assert ( a = p * k + 0 ) as f'.\n  { rewrite f.\n    rewrite hzplusr0.\n    apply idpath.\n  }\n  set ( e := tpair ( P := (fun qr : hz × hz =>\n                             a = p * pr1 qr + pr2 qr ×\n                             ( hzleh 0 (pr2 qr) ×\n                               hzlth (pr2 qr) (nattohz (hzabsval p)))) )\n         ( make_dirprod k 0 ) (make_dirprod f'\n                              ( make_dirprod ( isreflhzleh 0 ) ( lemmas.hzabsvalneq0 p x ) ) ) ).\n  assert ( e = pr1 ( divalgorithm a p x ) ) as s\n  by apply ( pr2 ( divalgorithm a p x ) ).\n  set ( w := base_paths _ _ ( pathsinv0 s ) ).\n  unfold e in w.\n  unfold hzremaindermod.\n  apply ( maponpaths ( fun z : hz × hz => pr2 z ) w ).\nDefined.\n\nLemma gcdandprime ( p : hz ) ( x : hzneq 0 p ) ( y : isaprime p )\n      ( a : hz ) ( q : neg ( hzmod p x a 0 ) ) : gcd p a x = 1.\nProof.\n  intros.\n  assert ( isaprop ( gcd p a x = 1) ) as is\n  by apply isasethz.\n  apply ( pr2 y ( gcd p a x )\n              ( pr1 ( gcdiscommondiv p a x ) ) (make_hProp _ is ) ).\n  intro t.\n  destruct t as [ t0 | t1 ].\n  - apply t0.\n  - apply fromempty.\n    apply q.\n    simpl.\n    assert ( hzremaindermod p x a = 0 ) as f.\n    { assert ( hzdiv p a ) as u.\n      { rewrite <- t1.\n        apply ( pr2 ( gcdiscommondiv _ _ _ ) ).\n      }\n      rewrite hzremaindermodanddiv.\n      + apply idpath.\n      + assumption.\n    }\n    rewrite f.\n    rewrite hzqrand0r.\n    apply idpath.\nDefined.\n\nLemma hzremaindermodandmultl ( p : hz ) ( x : hzneq 0 p ) ( a b : hz ) :\n  hzremaindermod p x ( p * a + b ) = hzremaindermod p x b.\nProof.\n  intros.\n  assert ( p * a + b =\n         ( p * ( a + hzquotientmod p x b ) + hzremaindermod p x b ) ) as f.\n  { rewrite hzldistr.\n    rewrite hzplusassoc.\n    rewrite <- ( hzdivequationmod p x b ).\n    apply idpath.\n  }\n  rewrite hzremaindermodandplus.\n  rewrite hzremaindermodandtimes.\n  rewrite hzqrandselfr.\n  rewrite hzmult0x.\n  rewrite hzqrand0r.\n  rewrite hzplusl0.\n  rewrite hzremaindermoditerated.\n  apply idpath.\nDefined.\n\nLemma hzmodprimeinv ( p : hz ) ( x : hzneq 0 p ) ( y : isaprime p )\n  ( a : hz ) ( q : neg ( hzmod p x a 0 ) ) :\n  ∑ v : hz, hzmod p x ( a * v ) 1 × hzmod p x ( v * a ) 1.\nProof.\n  intros.\n  split with ( pr2 ( pr1 ( bezoutstrong a p x ) ) ).\n  assert ( 1 = pr1 (pr1 (bezoutstrong a p x)) * p +\n               pr2 (pr1 (bezoutstrong a p x)) * a ) as f'.\n  { assert ( 1 = gcd p a x ) as f''.\n    { apply pathsinv0.\n      apply gcdandprime; assumption.\n    }\n    rewrite f''.\n    apply ( bezoutstrong a p x ).\n  }\n  split.\n  - rewrite f'.\n    simpl.\n    rewrite ( hzmultcomm ( pr1 ( pr1 ( bezoutstrong a p x ) ) ) _ ).\n    rewrite hzremaindermodandmultl.\n    rewrite hzmultcomm.\n    apply idpath.\n  - rewrite f'.\n    simpl.\n    rewrite hzremaindermodandplus.\n    rewrite ( hzremaindermodandtimes p x _ p ).\n    rewrite hzqrandselfr.\n    rewrite hzmultx0.\n    rewrite hzqrand0r.\n    rewrite hzplusl0.\n    rewrite hzremaindermoditerated.\n    apply idpath.\nDefined.\n\nLemma quotientringsumdecom ( X : commring ) ( R : ringeqrel ( X := X ) ) ( a b : X ) :\n  @op2 ( commringquot R ) ( setquotpr R a ) ( setquotpr R b ) =\n  ( setquotpr R ( a * b )%ring ).\nProof.\n  intros.\n  apply idpath.\nDefined.\n\nDefinition ahzmod ( p : hz ) ( y : isaprime p ) : afld.\nProof.\n  intros.\n  split with ( acommring_hzmod p ( isaprimetoneq0 y ) ).\n  split.\n  - simpl.\n    intro f.\n    apply ( isirreflhzlth 0 ).\n    assert ( hzlth 0 1 ) as i by apply hzlthnsn.\n    change ( 1%ring ) with\n    ( setquotpr ( hzmodisringeqrel p ( isaprimetoneq0 y ) ) 1%hz ) in f.\n    change ( 0%ring ) with\n    ( setquotpr ( hzmodisringeqrel p ( isaprimetoneq0 y ) ) 0%hz ).\n    assert ( hzmodisringeqrel p ( isaprimetoneq0 y ) 1%hz 0%hz ) as o.\n    { apply ( weqpathsinsetquot\n                ( hzmodisringeqrel p ( isaprimetoneq0 y ) ) 1%hz 0%hz ).\n      assumption.\n    }\n    unfold hzmodisringeqrel in o.\n    simpl in o.\n    assert ( hzremaindermod p ( isaprimetoneq0 y ) 0 = 0 ) as o'.\n    { rewrite hzqrand0r.\n      apply idpath.\n    }\n    rewrite o' in o.\n    assert ( hzremaindermod p ( isaprimetoneq0 y ) 1 = 1 ) as o''.\n    { assert ( hzlth 1 p ) as v by apply  y.\n      rewrite hzqrand1r.\n      apply idpath.\n    }\n    rewrite o'' in o.\n    assert ( hzlth 0 1 ) as o''' by apply hzlthnsn.\n    rewrite o in o'''.\n    assumption.\n  - assert ( forall x0 : acommring_hzmod p ( isaprimetoneq0 y ),\n      isaprop ( ( x0 # 0)%ring ->\n        multinvpair ( acommring_hzmod p ( isaprimetoneq0 y ) ) x0 ) ) as int.\n    { intro a.\n      apply impred.\n      intro q.\n      apply isapropmultinvpair.\n    }\n    apply ( setquotunivprop _ ( fun x0 => make_hProp _ ( int x0 ) ) ).\n    intro a.\n    simpl.\n    intro q.\n    assert ( neg ( hzmod p ( isaprimetoneq0 y ) a 0 ) ) as q'.\n    { intro g.\n      unfold hzmod in g.\n      simpl in g.\n      apply q.\n      change ( 0%ring ) with\n      ( setquotpr ( hzmodisringeqrel p ( isaprimetoneq0 y ) ) 0%hz ).\n      apply ( iscompsetquotpr ( hzmodisringeqrel p ( isaprimetoneq0 y ) ) ).\n      apply g.\n    }\n    split with ( setquotpr ( hzmodisringeqrel p ( isaprimetoneq0 y ) )\n                           ( pr1 ( hzmodprimeinv p ( isaprimetoneq0 y ) y a q' ) ) ).\n    split.\n    + simpl.\n      rewrite ( quotientringsumdecom hz ( hzmodisringeqrel p ( isaprimetoneq0 y ) ) ).\n      change 1%multmonoid with\n      ( setquotpr ( hzmodisringeqrel p ( isaprimetoneq0 y ) ) 1%hz ).\n      apply ( iscompsetquotpr ( hzmodisringeqrel p ( isaprimetoneq0 y ) ) ).\n      simpl.\n      change (pr2 (pr1 (bezoutstrong a p ( isaprimetoneq0 y ))) * a)%ring with\n      (pr2 (pr1 (bezoutstrong a p ( isaprimetoneq0 y ))) * a)%hz.\n      exact ( ( pr2 ( pr2 ( hzmodprimeinv p ( isaprimetoneq0 y ) y a q' ) ) )).\n    + simpl.\n      rewrite ( quotientringsumdecom hz ( hzmodisringeqrel p ( isaprimetoneq0 y ) ) ).\n      change 1%multmonoid with\n      ( setquotpr ( hzmodisringeqrel p ( isaprimetoneq0 y ) ) 1%hz ).\n      apply ( iscompsetquotpr ( hzmodisringeqrel p ( isaprimetoneq0 y ) ) ).\n      change (a * pr2 (pr1 (bezoutstrong a p ( isaprimetoneq0 y ))))%ring with\n      (a * pr2 (pr1 (bezoutstrong a p ( isaprimetoneq0 y ))))%hz.\n      exact ( ( pr1 ( pr2 ( hzmodprimeinv p ( isaprimetoneq0 y ) y a q' ) ) )).\nDefined.\n\nClose Scope hz_scope.\n(** END OF FILE *)\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/PAdics/z_mod_p.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571775, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.6762864497675806}}
{"text": "(** * positives: basic facts about binary positive numbers *)\n\nRequire Export BinNums.\nRequire Import comparisons.\n\n(** positives as a [cmpType] *)\n\nFixpoint eqb_pos i j := \n  match i,j with \n    | xH,xH => true\n    | xI i,xI j | xO i, xO j => eqb_pos i j\n    | _,_ => false\n  end.\n\nLemma eqb_pos_spec: forall i j, reflect (i=j) (eqb_pos i j).\nProof. induction i; intros [j|j|]; simpl; (try case IHi); constructor; congruence. Qed.\n\nFixpoint pos_compare i j := \n  match i,j with\n    | xH, xH => Eq\n    | xO i, xO j | xI i, xI j => pos_compare i j\n    | xH, _ => Lt\n    | _, xH => Gt\n    | xO _, _ => Lt \n    | _,_ => Gt\n  end.\n \nLemma pos_compare_spec: forall i j, compare_spec (i=j) (pos_compare i j).\nProof. induction i; destruct j; simpl; try case IHi; try constructor; congruence. Qed.\n\nCanonical Structure cmp_pos := mk_cmp _ eqb_pos_spec _ pos_compare_spec.\n\n\n(** positive maps (for making environments) *)\n(** we redefine such trees here rather than importing them from the standard library: \n   since we do not need any proof about them, this avoids us a heavy Require Import *)\nSection e.\nVariable A: Type.\nInductive sigma := sigma_empty | N(l: sigma)(o: option A)(r: sigma).\nFixpoint sigma_get default m i :=\n  match m with \n    | N l o r => \n      match i with\n        | xH => match o with None => default | Some a => a end\n        | xO i => sigma_get default l i\n        | xI i => sigma_get default r i\n      end\n    | _ => default\n  end.\nFixpoint sigma_add i v m :=\n    match m with\n    | sigma_empty =>\n        match i with\n        | xH => N sigma_empty (Some v) sigma_empty\n        | xO i => N (sigma_add i v sigma_empty) None sigma_empty\n        | xI i => N sigma_empty None (sigma_add i v sigma_empty)\n        end\n    | N l o r =>\n        match i with\n        | xH => N l (Some v) r\n        | xO i => N (sigma_add i v l) o r\n        | xI i => N l o (sigma_add i v r)\n        end\n    end.\nEnd e.\n\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/positives.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094304, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6762817493858994}}
{"text": "Require Import Statement ImprovedPredicative.\n\nRequire Import ZArith Lia.\n\nOpen Scope Z_scope.\n\nOpen Scope stmt_scope.\n\nDefinition spec : Stmt (Z*Z) := ⟨fun '(x,y) '(x',y') => x' = y /\\ y' = x⟩.\n\nDefinition prog := $(x,y) := (x - y, y); $(x,y) := (x, x + y); $(x,y) := (y - x, y).\n\nTheorem correctness : prog ⊑ spec.\nProof.\n  intros (x,y) ((u,v),_); clear u v.\n  split.\n  { intros (x',y'); simpl.\n    intros HHeq; inversion_clear HHeq.\n    lia.\n  }\n  { exists (y,x); simpl. f_equal; lia. }\nQed.\n\nPrint Assumptions correctness.\n\nDefinition prog' := $(x,y) := (x + y, y); $(x,y) := (x, x - y); $(x,y) := (x - y, y).\n\nTheorem equiv : forall s s', pred prog s s' <-> pred prog' s s'.\nProof.\n  intros (x,y) (x',y'); simpl.\n  split; intros H; inversion H; subst; f_equal.\n  all : lia.\nQed.\n\nPrint Assumptions equiv.\n\nClose Scope stmt_scope.", "meta": {"author": "bsall", "repo": "thesis-dev", "sha": "88761620d621b3435e2e4e6e8ce616b24836506f", "save_path": "github-repos/coq/bsall-thesis-dev", "path": "github-repos/coq/bsall-thesis-dev/thesis-dev-88761620d621b3435e2e4e6e8ce616b24836506f/src/examples/ImprovedPredicative_Swap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.676213788322572}}
{"text": "(** * Maps: Total and Partial Maps *)\nAdd LoadPath \"/Users/Harry/Documents/Fall 2016/CSC 495/Software Foundations - Code\".\n(** Maps (or dictionaries) are ubiquitous data structures, both in\n    software construction generally and in the theory of programming\n    languages in particular; we're going to need them in many places\n    in the coming chapters.  They also make a nice case study using\n    ideas we've seen in previous chapters, including building data\n    structures out of higher-order functions (from [Basics] and\n    [Poly]) and the use of reflection to streamline proofs (from\n    [IndProp]).\n\n    We'll define two flavors of maps: _total_ maps, which include a\n    \"default\" element to be returned when a key being looked up\n    doesn't exist, and _partial_ maps, which return an [option] to\n    indicate success or failure.  The latter is defined in terms of\n    the former, using [None] as the default element. *)\n\n(* ################################################################# *)\n(** * The Coq Standard Library *)\n\n(** One small digression before we start.\n\n    Unlike the chapters we have seen so far, this one does not\n    [Require Import] the chapter before it (and, transitively, all the\n    earlier chapters).  Instead, in this chapter and from now, on\n    we're going to import the definitions and theorems we need\n    directly from Coq's standard library stuff.  You should not notice\n    much difference, though, because we've been careful to name our\n    own definitions and theorems the same as their counterparts in the\n    standard library, wherever they overlap. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(** Documentation for the standard library can be found at\n    http://coq.inria.fr/library/.  \n\n    The [SearchAbout] command is a good way to look for theorems \n    involving objects of specific types. *)\n\n(* ################################################################# *)\n(** * Identifiers *)\n\n(** First, we need a type for the keys that we use to index into our\n    maps.  For this purpose, we again use the type [id] from the\n    [Lists] chapter.  To make this chapter self contained, we repeat\n    its definition here, together with the equality comparison\n    function for [id]s and its fundamental property. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id id1 id2 :=\n  match id1,id2 with\n    | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\nTheorem beq_id_refl : forall id, true = beq_id id id.\nProof.\n  intros [n]. simpl. rewrite <- beq_nat_refl.\n  reflexivity. Qed.\n\n(** The following useful property of [beq_id] follows from an\n    analogous lemma about numbers: *)\n\nTheorem beq_id_true_iff : forall id1 id2 : id,\n  beq_id id1 id2 = true <-> id1 = id2.\nProof.\n   intros [n1] [n2].\n   unfold beq_id.\n   rewrite beq_nat_true_iff.\n   split.\n   - (* -> *) intros H. rewrite H. reflexivity.\n   - (* <- *) intros H. inversion H. reflexivity.\nQed.\n\n(** Similarly: *)\n\nTheorem beq_id_false_iff : forall x y : id,\n  beq_id x y = false\n  <-> x <> y.\nProof.\n  intros x y. rewrite <- beq_id_true_iff.\n  rewrite not_true_iff_false. reflexivity. Qed.\n\n(** This useful variant follows just by rewriting: *)\n\nTheorem false_beq_id : forall x y : id,\n   x <> y\n   -> beq_id x y = false.\nProof.\n  intros x y. rewrite beq_id_false_iff.\n  intros H. apply H. Qed.\n\n(* ################################################################# *)\n(** * Total Maps *)\n\n(** Our main job in this chapter will be to build a definition of\n    partial maps that is similar in behavior to the one we saw in the\n    [Lists] chapter, plus accompanying lemmas about their behavior.\n\n    This time around, though, we're going to use _functions_, rather\n    than lists of key-value pairs, to build maps.  The advantage of\n    this representation is that it offers a more _extensional_ view of\n    maps, where two maps that respond to queries in the same way will\n    be represented as literally the same thing (the same function),\n    rather than just \"equivalent\" data structures.  This, in turn,\n    simplifies proofs that use maps.\n\n    We build partial maps in two steps.  First, we define a type of\n    _total maps_ that return a default value when we look up a key\n    that is not present in the map. *)\n\nDefinition total_map (A:Type) := id -> A.\n\n(** Intuitively, a total map over an element type [A] _is_ just a\n    function that can be used to look up [id]s, yielding [A]s.\n\n    The function [t_empty] yields an empty total map, given a default\n    element; this map always returns the default element when applied\n    to any id. *)\n\nDefinition t_empty {A:Type} (v : A) : total_map A :=\n  (fun _ => v).\n\n(** More interesting is the [update] function, which (as before) takes\n    a map [m], a key [x], and a value [v] and returns a new map that\n    takes [x] to [v] and takes every other key to whatever [m] does. *)\n\nDefinition t_update {A:Type} (m : total_map A)\n                    (x : id) (v : A) :=\n  fun x' => if beq_id x x' then v else m x'.\n\n(** This definition is a nice example of higher-order programming.\n    The [t_update] function takes a _function_ [m] and yields a new\n    function [fun x' => ...] that behaves like the desired map.\n\n    For example, we can build a map taking [id]s to [bool]s, where [Id\n    3] is mapped to [true] and every other key is mapped to [false],\n    like this: *)\n\nDefinition examplemap :=\n  t_update (t_update (t_empty false) (Id 1) false)\n           (Id 3) true.\n\n(** This completes the definition of total maps.  Note that we don't\n    need to define a [find] operation because it is just function\n    application! *)\n\nExample update_example1 : examplemap (Id 0) = false.\nProof. reflexivity. Qed.\n\nExample update_example2 : examplemap (Id 1) = false.\nProof. reflexivity. Qed.\n\nExample update_example3 : examplemap (Id 2) = false.\nProof. reflexivity. Qed.\n\nExample update_example4 : examplemap (Id 3) = true.\nProof. reflexivity. Qed.\n\n(** To use maps in later chapters, we'll need several fundamental\n    facts about how they behave.  Even if you don't work the following\n    exercises, make sure you thoroughly understand the statements of\n    the lemmas!  (Some of the proofs require the functional\n    extensionality axiom discussed in the [Logic] chapter, which is\n    also included in the standard library.) *)\n\n(** **** Exercise: 2 stars, optional (t_update_eq)  *)\n(** First, if we update a map [m] at a key [x] with a new value [v]\n    and then look up [x] in the map resulting from the [update], we\n    get back [v]: *)\n\nLemma t_update_eq : forall A (m: total_map A) x v,\n  (t_update m x v) x = v.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_neq)  *)\n(** On the other hand, if we update a map [m] at a key [x1] and then\n    look up a _different_ key [x2] in the resulting map, we get the\n    same result that [m] would have given: *)\n\nTheorem t_update_neq : forall (X:Type) v x1 x2\n                         (m : total_map X),\n  x1 <> x2 ->\n  (t_update m x1 v) x2 = m x2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_shadow)  *)\n(** If we update a map [m] at a key [x] with a value [v1] and then\n    update again with the same key [x] and another value [v2], the\n    resulting map behaves the same (gives the same result when applied\n    to any key) as the simpler map obtained by performing just\n    the second [update] on [m]: *)\n\nLemma t_update_shadow : forall A (m: total_map A) v1 v2 x,\n    t_update (t_update m x v1) x v2\n  = t_update m x v2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** For the final two lemmas about total maps, it's convenient to use\n    the reflection idioms introduced in chapter [IndProp].  We begin\n    by proving a fundamental _reflection lemma_ relating the equality\n    proposition on [id]s with the boolean function [beq_id]. *)\n\n(** **** Exercise: 2 stars (beq_idP)  *)\n(** Use the proof of [beq_natP] in chapter [IndProp] as a template to\n    prove the following: *)\n\nLemma beq_idP : forall x y, reflect (x = y) (beq_id x y).\nProof.\n  intros.\n  apply iff_reflect. \n  split.\n    - intros. rewrite H. rewrite <- beq_id_refl. reflexivity.\n    - intros. apply beq_id_true_iff. apply H.\nQed. \n(** [] *)\n\n(** Now, given [id]s [x1] and [x2], we can use the [destruct (beq_idP\n    x1 x2)] to simultaneously perform case analysis on the result of\n    [beq_id x1 x2] and generate hypotheses about the equality (in the\n    sense of [=]) of [x1] and [x2]. *)\n\n(** **** Exercise: 2 stars (t_update_same)  *)\n(** Using the example in chapter [IndProp] as a template, use\n    [beq_idP] to prove the following theorem, which states that if we\n    update a map to assign key [x] the same value as it already has in\n    [m], then the result is equal to [m]: *)\n\nTheorem t_update_same : forall X x (m : total_map X),\n  t_update m x (m x) = m.\nProof.\n  intros.  unfold t_update.\n  apply functional_extensionality_dep.\n  intros. destruct (beq_idP x x0).\n  - apply f_equal. apply e.\n  - reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (t_update_permute)  *)\n(** Use [beq_idP] to prove one final property of the [update]\n    function: If we update a map [m] at two distinct keys, it doesn't\n    matter in which order we do the updates. *)\n\nTheorem t_update_permute : forall (X:Type) v1 v2 x1 x2\n                             (m : total_map X),\n  x2 <> x1 ->\n    (t_update (t_update m x2 v2) x1 v1)\n  = (t_update (t_update m x1 v1) x2 v2).\nProof.\n  intros. unfold t_update.\n  apply functional_extensionality_dep.\n  intros. destruct (beq_idP x1 x).\n    - destruct (beq_idP x2 x).\n      + destruct (beq_id_true_iff x1 x). destruct H0.\n        * apply H1. apply e.\n        * destruct H. apply e0.\n      + reflexivity.\n    - destruct (beq_idP x2 x); reflexivity.\nQed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Partial maps *)\n\n(** Finally, we define _partial maps_ on top of total maps.  A partial\n    map with elements of type [A] is simply a total map with elements\n    of type [option A] and default element [None]. *)\n\nDefinition partial_map (A:Type) := total_map (option A).\n\nDefinition empty {A:Type} : partial_map A :=\n  t_empty None.\n\nDefinition update {A:Type} (m : partial_map A)\n                  (x : id) (v : A) :=\n  t_update m x (Some v).\n\n(** We can now lift all of the basic lemmas about total maps to\n    partial maps.  *)\n\nLemma update_eq : forall A (m: partial_map A) x v,\n  (update m x v) x = Some v.\nProof.\n  intros. unfold update. rewrite t_update_eq.\n  reflexivity.\nQed.\n\nTheorem update_neq : forall (X:Type) v x1 x2\n                       (m : partial_map X),\n  x2 <> x1 ->\n  (update m x2 v) x1 = m x1.\nProof.\n  intros X v x1 x2 m H.\n  unfold update. rewrite t_update_neq. reflexivity.\n  apply H. Qed.\n\nLemma update_shadow : forall A (m: partial_map A) v1 v2 x,\n  update (update m x v1) x v2 = update m x v2.\nProof.\n  intros A m v1 v2 x1. unfold update. rewrite t_update_shadow.\n  reflexivity.\nQed.\n\nTheorem update_same : forall X v x (m : partial_map X),\n  m x = Some v ->\n  update m x v = m.\nProof.\n  intros X v x m H. unfold update. rewrite <- H.\n  apply t_update_same.\nQed.\n\nTheorem update_permute : forall (X:Type) v1 v2 x1 x2\n                                (m : partial_map X),\n  x2 <> x1 ->\n    (update (update m x2 v2) x1 v1)\n  = (update (update m x1 v1) x2 v2).\nProof.\n  intros X v1 v2 x1 x2 m. unfold update.\n  apply t_update_permute.\nQed.\n\n(** $Date: 2015-12-11 17:17:29 -0500 (Fri, 11 Dec 2015) $ *)\n\n", "meta": {"author": "hpbrown92", "repo": "Coq-Solutions", "sha": "2467e185261bfe2dc043b2a49e353c8a9217b75e", "save_path": "github-repos/coq/hpbrown92-Coq-Solutions", "path": "github-repos/coq/hpbrown92-Coq-Solutions/Coq-Solutions-2467e185261bfe2dc043b2a49e353c8a9217b75e/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.8824278710924296, "lm_q1q2_score": 0.6761988681000055}}
{"text": "Require Import prosa.classic.util.all.\nRequire Import prosa.classic.model.arrival.basic.task prosa.classic.model.priority prosa.classic.model.schedule.global.workload.\nRequire Import prosa.classic.model.schedule.global.jitter.job prosa.classic.model.schedule.global.jitter.schedule.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.\n\nRequire prosa.classic.model.schedule.global.basic.interference.\n\nModule Interference.\n\n  Import ScheduleOfSporadicTaskWithJitter Priority Workload.\n\n  (* We import some of the basic definitions, but we need to re-define almost everything\n     since the definition of backlogged (and thus the definition of interference)\n     changes with jitter. *)\n  Import prosa.classic.model.schedule.global.basic.interference.\n  Export Interference.\n  \n  Section InterferenceDefs.\n\n    Context {sporadic_task: eqType}.\n    Context {Job: eqType}.\n    Variable job_arrival: Job -> time.\n    Variable job_cost: Job -> time.\n    Variable job_task: Job -> sporadic_task.\n    Variable job_jitter: Job -> time.\n\n    (* Consider any job arrival sequence...*)\n    Variable arr_seq: arrival_sequence Job.\n\n    (* ... and any schedule of those jobs. *)\n    Context {num_cpus: nat}.\n    Variable sched: schedule Job num_cpus.\n\n    (* Consider any job j that incurs interference. *)\n    Variable j: Job.\n\n    (* Recall the definition of backlogged (pending and not scheduled). *)\n    Let job_is_backlogged := backlogged job_arrival job_cost job_jitter sched j.\n\n    (* First, we define total interference. *)\n    Section TotalInterference.\n      \n      (* The total interference incurred by job j during [t1, t2) is the\n         cumulative time in which j is backlogged in this interval. *)\n      Definition total_interference (t1 t2: time) :=\n        \\sum_(t1 <= t < t2) job_is_backlogged t.\n\n    End TotalInterference.\n    \n    (* Next, we define job interference. *)\n    Section JobInterference.\n\n      (* Let job_other be a job that interferes with j. *)\n      Variable job_other: Job.\n\n      (* The interference caused by job_other during [t1, t2) is the cumulative\n         time in which j is backlogged while job_other is scheduled. *)\n      Definition job_interference (t1 t2: time) :=\n        \\sum_(t1 <= t < t2)\n          \\sum_(cpu < num_cpus)\n            (job_is_backlogged t &&\n            scheduled_on sched job_other cpu t).\n\n    End JobInterference.\n    \n    (* Next, we define task interference. *)\n    Section TaskInterference.\n\n      (* In order to define task interference, consider any interfering task tsk_other. *)\n      Variable tsk_other: sporadic_task.\n    \n      (* The interference caused by tsk during [t1, t2) is the cumulative time\n         in which j is backlogged while tsk is scheduled. *)\n      Definition task_interference (t1 t2: time) :=\n        \\sum_(t1 <= t < t2)\n          \\sum_(cpu < num_cpus)\n            (job_is_backlogged t &&\n            task_scheduled_on job_task sched tsk_other cpu t).\n\n    End TaskInterference.\n\n    (* Next, we define an approximation of the total interference based on\n       each per-task interference. *)\n    Section TaskInterferenceJobList.\n\n      Variable tsk_other: sporadic_task.\n\n      Definition task_interference_joblist (t1 t2: time) :=\n        \\sum_(j <- jobs_scheduled_between sched t1 t2 | job_task j == tsk_other)\n         job_interference j t1 t2.\n\n    End TaskInterferenceJobList.\n\n    (* Now we prove some basic lemmas about interference. *)\n    Section BasicLemmas.\n\n      (* First, we show that total interference cannot be larger than the interval length. *)\n      Lemma total_interference_le_delta :\n        forall t1 t2,\n          total_interference t1 t2 <= t2 - t1.\n      Proof.\n        unfold total_interference; intros t1 t2.\n        apply leq_trans with (n := \\sum_(t1 <= t < t2) 1);\n          first by apply leq_sum; ins; apply leq_b1.\n        by rewrite big_const_nat iter_addn mul1n addn0 leqnn.\n      Qed.\n\n      (* Next, we prove that job interference is bounded by the service of the interfering job. *)\n      Lemma job_interference_le_service :\n        forall j_other t1 t2,\n          job_interference j_other t1 t2 <= service_during sched j_other t1 t2.\n      Proof.\n        intros j_other t1 t2; unfold job_interference, service_during.\n        apply leq_sum; intros t _.\n        unfold service_at; rewrite [\\sum_(_ < _ | scheduled_on _ _ _  _)_]big_mkcond.\n        apply leq_sum; intros cpu _.\n        destruct (job_is_backlogged t); [rewrite andTb | by rewrite andFb].\n        by destruct (scheduled_on sched j_other cpu t).\n      Qed.\n      \n      (* We also prove that task interference is bounded by the workload of the interfering task. *)\n      Lemma task_interference_le_workload :\n        forall tsk t1 t2,\n          task_interference tsk t1 t2 <= workload job_task sched tsk t1 t2.\n      Proof.\n        unfold task_interference, workload; intros tsk t1 t2.\n        apply leq_sum; intros t _.\n        apply leq_sum; intros cpu _.\n        destruct (job_is_backlogged t); [rewrite andTb | by rewrite andFb].\n        unfold task_scheduled_on, service_of_task.\n        by destruct (sched cpu t).\n      Qed.\n\n    End BasicLemmas.\n\n    (* Now we prove some bounds on interference for sequential jobs. *)\n    Section InterferenceSequentialJobs.\n\n      (* If jobs are sequential, ... *)\n      Hypothesis H_sequential_jobs: sequential_jobs sched.\n    \n      (* ... then the interference incurred by a job in an interval\n         of length delta is at most delta. *)\n      Lemma job_interference_le_delta :\n        forall j_other t1 delta,\n          job_interference j_other t1 (t1 + delta) <= delta.\n      Proof.\n        rename H_sequential_jobs into SEQ.\n        unfold job_interference, sequential_jobs in *.\n        intros j_other t1 delta.\n        apply leq_trans with (n := \\sum_(t1 <= t < t1 + delta) 1);\n          last by rewrite big_const_nat iter_addn mul1n addn0 addKn leqnn.\n        apply leq_sum; intros t _.\n        destruct ([exists cpu, scheduled_on sched j_other cpu t]) eqn:EX.\n        {\n          move: EX => /existsP [cpu SCHED].\n          rewrite (bigD1 cpu) // /=.\n          rewrite big_mkcond (eq_bigr (fun x => 0)) /=;\n            first by simpl_sum_const; rewrite leq_b1.\n          intros cpu' _; des_if_goal; last by done.\n          destruct (scheduled_on sched j_other cpu' t) eqn:SCHED'; last by rewrite andbF.\n          move: SCHED SCHED' => /eqP SCHED /eqP SCHED'.\n          by specialize (SEQ j_other t cpu cpu' SCHED SCHED'); rewrite SEQ in Heq.\n        }\n        {\n          apply negbT in EX; rewrite negb_exists in EX.\n          move: EX => /forallP EX.\n          rewrite (eq_bigr (fun x => 0)); first by simpl_sum_const.\n          by intros cpu _; specialize (EX cpu); apply negbTE in EX; rewrite EX andbF.\n        }\n      Qed.\n\n    End InterferenceSequentialJobs.\n\n    (* Next, we show that the cumulative per-task interference bounds the total\n       interference. *)\n    Section BoundUsingPerJobInterference.\n      \n      Lemma interference_le_interference_joblist :\n        forall tsk t1 t2,\n          task_interference tsk t1 t2 <= task_interference_joblist tsk t1 t2.\n      Proof.\n        intros tsk t1 t2.\n        unfold task_interference, task_interference_joblist, job_interference, job_is_backlogged.\n        rewrite [\\sum_(_ <- _ sched _ _ | _) _]exchange_big /=.\n        rewrite big_nat_cond [\\sum_(_ <= _ < _ | true) _]big_nat_cond.\n        apply leq_sum; move => t /andP [LEt _].\n        rewrite exchange_big /=.\n        apply leq_sum; intros cpu _.\n        destruct (backlogged job_arrival job_cost job_jitter sched j t) eqn:BACK;      \n          last by rewrite andFb (eq_bigr (fun x => 0));\n            first by rewrite big_const_seq iter_addn mul0n addn0.\n        rewrite andTb.\n        destruct (task_scheduled_on job_task sched tsk cpu t) eqn:SCHED; last by done.\n        unfold scheduled_on, task_scheduled_on in *.\n        destruct (sched cpu t) as [j' |] eqn:SOME; last by done.\n        rewrite big_mkcond /= (bigD1_seq j') /=; last by apply undup_uniq.\n        {\n          by rewrite SCHED eq_refl.\n        }\n        {\n          unfold jobs_scheduled_between.\n          rewrite mem_undup; apply mem_bigcat_nat with (j := t);\n            first by done.\n          apply mem_bigcat_ord with (j := cpu); first by apply ltn_ord.\n          by unfold make_sequence; rewrite SOME mem_seq1 eq_refl.\n        }\n      Qed.\n        \n    End BoundUsingPerJobInterference.\n    \n  End InterferenceDefs.\n\nEnd Interference.", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/classic/model/schedule/global/jitter/interference.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072387, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6761971358539819}}
{"text": "Require Import Setoid.\n\nParameter expr : Set.\nParameter comp : expr -> expr -> expr.\n\nNotation \"a ** b\" := (comp a b) (at level 10).\n\nAxiom associativity : forall a b c, (a ** b) ** c = a ** (b ** c).\n\nDefinition existsunique {A} (P : A -> Prop) := exists x, P x /\\ forall x', P x' -> x' = x.\n\nDefinition pullback f g h := \n  exists h', h ** f = g ** h' /\\ \n             forall i j, h ** i = g ** j -> existsunique (fun k => f ** k = i /\\ h' ** k = j).\n\nDefinition monic f :=\n  forall g h, f ** g = f ** h -> g = h.\n\nLemma pullback_of_monic_is_monic :\n  forall f g h, pullback f g h -> monic g -> monic f.\nProof.\n  intros f g h H_pullback H_g_monic g0 h0 H_f_monic_ass.\n  assert (H_f_monic_ass_left_h : h ** f ** g0 = h ** f ** h0) by (repeat (rewrite associativity); congruence).\n  destruct H_pullback as [h' [H_pullback_comm H_pullback_univ]].\n  assert (h'_cofork : h' ** g0 = h' ** h0).\n  * rewrite H_pullback_comm in H_f_monic_ass_left_h.\n    repeat rewrite associativity in H_f_monic_ass_left_h.\n    apply H_g_monic; assumption.\n  * clear H_g_monic. \n    rewrite H_pullback_comm in H_f_monic_ass_left_h at 2.\n    repeat rewrite associativity in H_f_monic_ass_left_h.\n    specialize (H_pullback_univ _ _ H_f_monic_ass_left_h). clear H_f_monic_ass_left_h.\n    destruct H_pullback_univ as [k [[k_comm_1 k_comm_2] k_unique]].\n    assert (g0 = k).\n    + specialize (k_unique g0). \n      rewrite h'_cofork in k_unique.\n      auto.\n    + assert (h0 = k).\n      - specialize (k_unique h0).\n        rewrite H_f_monic_ass in k_unique.\n        auto.\n      - congruence.\nQed.\n  ", "meta": {"author": "xu-hao", "repo": "cat", "sha": "d7d30547d137f134c77c8a801d0399cf0039aab8", "save_path": "github-repos/coq/xu-hao-cat", "path": "github-repos/coq/xu-hao-cat/cat-d7d30547d137f134c77c8a801d0399cf0039aab8/Topos.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819236, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6761971347819282}}
{"text": "From mathcomp Require Import all_ssreflect.\nRequire Import bigmin extra.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection tarjan.\n\nVariable (V : finType) (successors : V -> seq V).\nNotation infty := #|V|.+1.\n\n(*************************************************************)\n(*               Tarjan 72 algorithm,                        *)\n(* rewritten in a functional style  with extra modifications *)\n(*************************************************************)\n\nRecord env := Env {esccs : {set {set V}}; serial : nat; num : {ffun V -> nat}}.\n\nDefinition visit x e :=\n  Env (esccs e) (serial e).+1 (finfun [eta num e with x |-> serial e]).\nDefinition store C e :=\n  Env (C |: esccs e) (serial e) [ffun x => if x \\in C then #|V| else num e x].\n\nDefinition dfs1 dfs x e :=\n    let: (m1, C, e1) := dfs [set y in successors x] (visit x e) in\n    let xC := x |: C in\n    if m1 < serial e then (m1, xC, e1) else (#|V|, set0, store xC e1).\n\nDefinition dfs dfs1 dfs (roots : {set V}) e : nat * {set V} * env :=\n  if [pick x in roots] isn't Some x then (#|V|, set0, e) else\n  let: (m1, C1, e1) := if num e x != infty then (num e x, set0, e) else dfs1 x e in\n  let: (m2, C2, e2) := dfs (roots :\\ x) e1 in (minn m1 m2, C1 :|: C2, e2).\n\nFixpoint tarjan_rec n :=\n  if n is n.+1 then dfs (dfs1 (tarjan_rec n)) (tarjan_rec n)\n  else fun r e => (#|V|, set0, e).\n\nLet N := #|V| * #|V|.+1 + #|V|.\nDefinition e0 := (Env set0 0 [ffun _ => infty]).\nDefinition tarjan := esccs (tarjan_rec N setT e0).2.\n\n(*****************)\n(* Abbreviations *)\n(*****************)\n\nNotation edge := (grel successors).\nNotation gconnect := (connect edge).\nNotation gsymconnect := (symconnect edge).\nNotation gsccs := (sccs edge).\nNotation gscc_of := (pblock gsccs).\nNotation gconnected := (connected edge).\n\n(*******************)\n(* next, and nexts *)\n(*******************)\n\nSection Nexts.\nVariable (D : {set V}).\n\nDefinition nexts (A : {set V}) :=\n  \\bigcup_(v in A) [set w in connect (relfrom (mem D) edge) v].\n\nLemma nexts0 : nexts set0 = set0.\nProof. by rewrite /nexts big_set0. Qed.\n\nLemma nexts1 x :\n  nexts [set x] = x |: (if x \\in D then nexts [set y in successors x] else set0).\nProof.\napply/setP=> y; rewrite /nexts big_set1 !inE.\nhave [->|neq_yx/=] := altP eqP; first by rewrite connect0.\napply/idP/idP=> [/connect1l[]// z/=/andP[/= xD xz zy]|].\n  by rewrite xD; apply/bigcupP; exists z; rewrite !inE.\ncase: ifPn; rewrite ?inE// => xD /bigcupP[z]; rewrite !inE.\nby move=> xz; apply/connect_trans/connect1; rewrite /= xD.\nQed.\n\nLemma nextsU A B : nexts (A :|: B) = nexts A :|: nexts B.\nProof. exact: bigcup_setU. Qed.\n\nLemma nextsS (A : {set V}) : A \\subset nexts A.\nProof. by apply/subsetP=> a aA; apply/bigcupP; exists a; rewrite ?inE. Qed.\n\nLemma nextsT : nexts setT = setT.\nProof. by apply/eqP; rewrite eqEsubset nextsS subsetT. Qed.\n\nLemma nexts_id (A : {set V}) : nexts (nexts A) = nexts A.\nProof.\napply/eqP; rewrite eqEsubset nextsS andbT; apply/subsetP=> x.\nmove=> /bigcupP[y /bigcupP[z zA]]; rewrite !inE => /connect_trans yto /yto zx.\nby apply/bigcupP; exists z; rewrite ?inE.\nQed.\n\nLemma in_nextsW A y : y \\in nexts A -> exists2 x, x \\in A & gconnect x y.\nProof.\nmove=>/bigcupP[x xA]; rewrite inE => xy; exists x => //.\nby apply: connect_sub xy => u v /andP[_ /connect1].\nQed.\n\nEnd Nexts.\n\nLemma sub_nexts (D D' A B : {set V}) :\n  D \\subset D' -> A \\subset B -> nexts D A \\subset nexts D' B.\nProof.\nmove=> /subsetP subD /subsetP subAB; apply/subsetP => v /bigcupP[a /subAB aB].\nrewrite !inE => av; apply/bigcupP; exists a; rewrite ?inE //=.\nby apply: connect_sub av => x y /andP[xD xy]; rewrite connect1//= subD.\nQed.\n\nLemma nextsUI A B C : nexts B A \\subset A ->\n  A :|: nexts (B :&: ~: A) C = A :|: nexts B C.\nProof.\nmove=> subA; apply/setP=> y; rewrite !inE; have [//|/= yNA] := boolP (y \\in A).\napply/idP/idP; first by apply: subsetP; rewrite sub_nexts// subsetIl.\nmove=> /bigcupP[z zr zy]; apply/bigcupP; exists z; first by [].\nrewrite !inE; apply: contraTT isT => Nzy; move: zy; rewrite !inE.\nmove=> /(connect_from (mem (~: A))) /= [t].\nrewrite !inE => -[xtxy zt ty]; move: zt.\nrewrite (@eq_connect _ _ (relfrom (mem (B :&: ~: A)) edge)); last first.\n  by move=> u v /=; rewrite !inE andbCA andbA.\ncase: (altP eqP) xtxy => /= [<-|neq_yt]; first by rewrite (negPf Nzy).\nrewrite implybF negbK => tA zt; rewrite -(negPf yNA) (subsetP subA)//.\nby apply/bigcupP; exists t; rewrite // inE.\nQed.\n\nLemma nexts1_split (A : {set V}) x : x \\in A ->\n  nexts A [set x] = x |: nexts (A :\\ x) [set y in successors x].\nProof.\nmove=> xA; apply/setP=> y; apply/idP/idP; last first.\n  rewrite nexts1 !inE xA; case: (_ == _); rewrite //=.\n  by apply: subsetP; rewrite sub_nexts// subsetDl.\nmove=> /bigcupP[z]; rewrite !inE => /eqP[{z}->].\nmove=> /connectP[p /shortenP[[_ _ _ /eqP->//|z q/=/andP[/andP[_ xz]]]]].\nrewrite path_from => /andP[zq] /allP/= qA.\nmove=> /and3P[xNzq _ _] _ ->; apply/orP; right.\napply/bigcupP; exists z; rewrite !inE//.\napply/connectP; exists q; rewrite // path_from zq/=.\napply/allP=> t tq; rewrite !inE qA ?andbT//.\nby apply: contraNneq xNzq=> <-; apply: mem_belast tq.\nQed.\n\n(*******************)\n(* Well formed env *)\n(*******************)\n\nDefinition seen e := [set x | num e x < infty].\nNotation sn e := #|seen e|.\nDefinition stack e := [set x | num e x < sn e].\nNotation new_stack e1 e2 := (stack e2 :\\: stack e1).\n\nLemma num_lt_infty e x : num e x < infty = (x \\in seen e).\nProof. by rewrite inE. Qed.\n\nLemma sub_stack_seen e : stack e \\subset seen e.\nProof.\napply/subsetP => x; rewrite !inE => /leq_trans; apply;\nby rewrite leqW// max_card.\nQed.\n\nSection wfenv.\n\nVariable (e : env).\n\nRecord wf_env e := WfEnv {\n  serialE : serial e = sn e;\n  sub_gsccs : esccs e \\subset gsccs;\n  max_num : forall x, num e x <= infty;\n  num_lt_V_is_stack : forall x, num e x < #|V| -> num e x < sn e;\n  num_sccs : forall x, (num e x == #|V|) = (x \\in cover (esccs e));\n  le_connect : forall x y, num e x <= num e y < sn e -> gconnect x y;\n}.\n\nVariables (e_wf : wf_env e).\n\nLemma num_lt_sn x : num e x < sn e = (x \\in stack e).\nProof. by rewrite inE. Qed.\n\nLemma seen_visit x : seen (visit x e) = x |: seen e.\nProof.\napply/setP=> y; rewrite !inE ffunE/= ?serialE//; case: (altP eqP);\nby rewrite //= ltnS max_card.\nQed.\n\nLemma sub_new_stack_seen e1 e2: new_stack e1 e2 \\subset seen e2.\nProof. by rewrite (subset_trans _ (sub_stack_seen _)) ?subsetDl. Qed.\n\nLemma notseen_num x : x \\notin seen e -> num e x = infty.\nProof. by rewrite inE ltn_neqAle max_num// andbT negbK => /eqP. Qed.\n\nLemma num_lt_V x : (num e x < #|V|) = (num e x < sn e).\nProof.\napply/idP/idP => [/num_lt_V_is_stack//|]; first exact.\nby move=> /leq_trans; apply; rewrite max_card.\nQed.\n\nLemma num_lt_card x (A : pred V) : seen e \\subset A ->\n  (num e x < #|A|) = (num e x < sn e).\nProof.\nmove=> subeA; apply/idP/idP => /leq_trans.\n  by rewrite -num_lt_V; apply; rewrite max_card.\nby apply; rewrite subset_leq_card.\nQed.\n\nLemma seenE : seen e = stack e :|: cover (esccs e).\nProof.\nby apply/setP=> x; rewrite !inE ltnS leq_eqVlt -num_sccs// num_lt_V orbC.\nQed.\n\nLemma vs_disjoint : [disjoint stack e & cover (esccs e)].\nProof.\nrewrite -setI_eq0; apply/eqP/setP=> x; rewrite !inE -num_sccs//.\nby rewrite -num_lt_V; case: ltngtP.\nQed.\n\nLemma sub_sccs_seen : cover (esccs e) \\subset seen e.\nProof. by apply/subsetP => x; rewrite !inE -num_sccs// => /eqP->. Qed.\n\nLemma stack_visit x : x \\notin seen e -> stack (visit x e) = x |: stack e.\nProof.\nmove=> xNseen; apply/setP=> y; rewrite !inE/= ffunE/= ?serialE// seen_visit.\nhave [->|neq_yx]//= := altP eqP; first by rewrite cardsU1 xNseen ltnS ?leqnn.\nby rewrite num_lt_card// subsetUr.\nQed.\n\nEnd wfenv.\n\nLemma wf_visit e x : wf_env e ->\n   (forall y, num e y < sn e -> gconnect y x) ->\n   x \\notin seen e -> wf_env (visit x e).\nProof.\nmove=> e_wf x_connected xNseen.\nconstructor=> [||y|y|y|] //=; rewrite ?inE ?ffunE/= ?serialE//.\n- by rewrite seen_visit// cardsU1 xNseen.\n- exact: sub_gsccs.\n- by case: ifP; rewrite ?max_num// leqW ?max_card.\n- rewrite seen_visit// cardsU1 xNseen; case: ifPn => // _.\n  by rewrite num_lt_V// ltnS => /ltnW.\n- have [->|] := altP (y =P x); last by rewrite num_sccs.\n  rewrite -num_sccs// notseen_num// eq_sym !gtn_eqF//.\n  by rewrite (@leq_trans #|x |: seen e|) ?max_card// cardsU1 xNseen.\nmove=> y z; rewrite !ffunE/=.\nhave sub_visit : seen e \\subset seen (visit x e).\n  by apply/subsetP => ?; rewrite seen_visit// !inE orbC => ->.\nhave [{y}->|neq_yx] := altP eqP; have [{z}->|neq_zx]//= := altP eqP.\n+ by rewrite num_lt_card//; case: ltngtP.\n+ move=> /andP[/leq_ltn_trans lt/lt].\n  by rewrite num_lt_card//; apply: x_connected.\n+ by rewrite num_lt_card//; apply: le_connect.\nQed.\n\nDefinition subenv e1 e2 := [&&\n  esccs e1 \\subset esccs e2,\n  [forall x, (num e1 x < infty) ==> (num e2 x == num e1 x)] &\n  [forall x, (num e2 x < sn e1) ==> (num e1 x < sn e1)]].\n\nLemma sub_sccs e1 e2 : subenv e1 e2 -> esccs e1 \\subset esccs e2.\nProof. by move=> /and3P[]. Qed.\n\nLemma sub_snum e1 e2 : subenv e1 e2 -> forall x, num e1 x < infty -> num e2 x = num e1 x.\nProof. by move=> /and3P[_ /forall_inP /(_ _ _) /eqP]. Qed.\n\nLemma sub_vnum e1 e2 : subenv e1 e2 -> forall x, num e1 x < sn e1 -> num e2 x = num e1 x.\nProof.\nmove=> sube12 x num_lt; rewrite (sub_snum sube12)//.\nby rewrite (leq_trans num_lt)// leqW// max_card.\nQed.\n\nLemma sub_num_lt e1 e2 : subenv e1 e2 ->\n  forall x, (num e1 x < sn e1) = (num e2 x < sn e1).\nProof.\nmove=> /and3P[_ /forall_inP /(_ _ _)/eqP num_eq /forall_inP] num_lt x.\nhave nume1_lt := num_lt x; apply/idP/idP => // {nume1_lt}nume1_lt.\nby rewrite num_eq ?inE// (leq_trans nume1_lt)// leqW// max_card.\nQed.\n\nLemma sub_seen e1 e2 : subenv e1 e2 -> seen e1 \\subset seen e2.\nProof.\nmove=> sube12; apply/subsetP=> x; rewrite !inE => x_seen1.\nby rewrite (sub_snum sube12)// inE.\nQed.\n\nLemma leq_sn e1 e2 : subenv e1 e2 -> sn e1 <= sn e2.\nProof. by move=> sube12; rewrite subset_leq_card// sub_seen. Qed.\n\nLemma sub_stack e1 e2 : subenv e1 e2 -> stack e1 \\subset stack e2.\nProof.\nmove=> sube12; apply/subsetP=> x; rewrite !inE => x_stack.\nby rewrite (sub_vnum sube12)// (leq_trans x_stack)// leq_sn.\nQed.\n\nLemma new_stackE e1 e2 : subenv e1 e2 ->\n  new_stack e1 e2 = [set x | sn e1 <= num e2 x < sn e2].\nProof.\nmove=> sube12; apply/setP=> x; rewrite !inE.\nhave [x_e2|] := ltnP (num e2 x) (sn e2); rewrite ?andbT ?andbF//.\nhave [e1_after|e1_before] /= := leqP (sn e1) (num e1 x).\n  by rewrite leqNgt -sub_num_lt// -leqNgt.\nby rewrite leqNgt -sub_num_lt// e1_before.\nQed.\n\nNotation new_seen e1 e2 := (seen e2 :\\: seen e1).\n\nLemma new_seenE e1 e2 : wf_env e1 -> wf_env e2 -> subenv e1 e2 ->\n(new_seen e1 e2) = (new_stack e1 e2) :|: cover (esccs e2) :\\: cover (esccs e1).\nProof.\nmove=> e1_wf e2_wf sube12; rewrite !seenE//; apply/setP=> x.\nrewrite !inE -!num_sccs -?num_lt_V//; do 2!case: ltngtP => //=.\n  by rewrite num_lt_V// (sub_num_lt sube12)// => ->; rewrite ltnNge max_card.\nby move=> xe2 xe1; move: xe2; rewrite (sub_snum sube12)// ?xe1// ltnn.\nQed.\n\nLemma sub_new_stack_new_seen e1 e2 : subenv e1 e2 -> wf_env e1 -> wf_env e2 ->\n  (new_stack e1 e2) \\subset (new_seen e1 e2).\nProof. by move=> e1_wf e2_wf sube12; rewrite (@new_seenE e1 e2)// subsetUl. Qed.\n\nLemma sub_refl e : subenv e e.\nProof. by rewrite /subenv !subxx /=; apply/andP; split; apply/forall_inP. Qed.\nHint Resolve sub_refl.\n\nLemma sub_trans : transitive subenv.\nProof.\nmove=> e2 e1 e3 sub12 sub23; rewrite /subenv.\nrewrite (subset_trans (sub_sccs sub12))// ?sub_sccs//=.\napply/andP; split; apply/forall_inP=> x xP.\n  by rewrite (sub_snum sub23) ?(sub_snum sub12)//.\nhave x2 : num e3 x < sn e2 by rewrite (leq_trans xP)// leq_sn.\nby rewrite (sub_num_lt sub12)// -(sub_vnum sub23)// (sub_num_lt sub23).\nQed.\n\nLemma sub_visit e x : wf_env e -> x \\notin seen e -> subenv e (visit x e).\nProof.\nmove=> e_wf xNseen; rewrite /subenv subxx/=; apply/andP; split; last first.\n  by apply/forall_inP => y; rewrite !ffunE ?serialE//=; case: ifP; rewrite ?ltnn.\napply/forall_inP => y y_in; rewrite !ffunE/=.\nby case: (altP (y =P x)) xNseen => // <-; rewrite inE y_in.\nQed.\n\nLemma stackE e : wf_env e -> stack e = seen e :\\: cover (esccs e).\nProof.\nmove=> e_wf; apply/setP=> x; rewrite seenE// setDUl setDv setU0.\nby rewrite !inE -num_sccs// -num_lt_V//; case: ltngtP.\nQed.\n\nLemma seen_store (A : {set V}) e : A \\subset seen e -> seen (store A e) = seen e.\nProof.\nmove=> A_sub; apply/setP=> x; rewrite !inE/= ffunE.\nby case: ifPn => // /(subsetP A_sub); rewrite inE leqnn => ->.\nQed.\n\nLemma stack_store (A : {set V}) e : A \\subset seen e ->\n  stack (store A e) = stack e :\\: A.\nProof.\nmove=> A_sub; apply/setP => x; rewrite !inE seen_store//= ffunE.\nby case: (x \\in A); rewrite //= ltnNge max_card.\nQed.\n\n(*********************)\n(* DFS specification *)\n(*********************)\n\nDefinition outenv (roots : {set V}) m scc (e e' : env) := [/\\\n  m = val (\\min_(x in nexts (~:seen e) roots) @inord #|V| (num e' x)),\n  scc = new_stack e e',\n  {in new_stack e e' &, gconnected},\n  {in new_stack e e', forall x, exists2 y, y \\in stack e & gconnect x y} &\n  seen e' = seen e :|: nexts (~: seen e) roots].\n\nVariant dfs_spec_def (dfs : nat * {set V} * env) (roots : {set V}) e :\n  (nat * {set V} * env) -> nat  -> {set V} -> env -> Type := DfsSpec me' m C e' of\n    me' = (m, C, e') &\n    wf_env e' & subenv e e' & outenv roots m C e e' :\n  dfs_spec_def dfs roots e me' m C e'.\nNotation dfs_spec dfs roots e := (dfs_spec_def dfs roots e dfs dfs.1.1 dfs.1.2 dfs.2).\n\nDefinition dfs_correct dfs (roots : {set V}) e := wf_env e ->\n  {in stack e & roots, gconnected} -> dfs_spec (dfs roots e) roots e.\nDefinition dfs1_correct dfs1 x e := wf_env e -> x \\notin seen e ->\n  {in stack e & [set x], gconnected} -> dfs_spec (dfs1 x e) [set x] e.\n\n(*****************)\n(* Correctness *)\n(*****************)\n\nLemma dfsP dfs1 dfsrec (roots : {set V}) e:\n  (forall x, x \\in roots -> dfs1_correct dfs1 x e) ->\n  (forall x, x \\in roots -> forall e1, subenv e e1 ->\n     dfs_correct dfsrec (roots :\\ x) e1) ->\n  dfs_correct (dfs dfs1 dfsrec) roots e.\nProof.\nrewrite /dfs => dfs1P dfsP e_wf roots_connected.\ncase: pickP => /= [x x_roots|]; last first.\n  move=> r0; have {r0}r_eq0 : roots = set0 by apply/setP=> x; rewrite inE.\n  do ?constructor=> //=;\n    rewrite ?setDv ?r_eq0 ?nexts0 ?sub0set ?eqxx ?setU0 ?big_set0 //=;\n    by move=> ?; rewrite inE.\nhave [numx_infty|numx_ninfty]/= := altP eqP; last first.\n  have numx_lt : num e x < infty by rewrite ltn_neqAle numx_ninfty max_num.\n  have x_seen : x \\in seen e by rewrite inE.\n  case: dfsP => //= [u v ve|??? e1 -> e1_wf subee1 [-> -> new1c new1old seen1E]].\n    by rewrite inE => /andP[_ v_roots]; rewrite roots_connected.\n  do !constructor=> //=; rewrite ?set0U ?serialE //=.\n    rewrite -[in RHS](setD1K x_roots) nextsU nexts1 inE x_seen/= setU0.\n    by rewrite bigmin_setU /= big_set1/= (@sub_snum e e1)// inordK//.\n  rewrite -(setD1K x_roots) nextsU nexts1 inE x_seen/=.\n  by rewrite setU0 setUCA setUA [x |: _](setUidPr _) ?sub1set.\ncase: dfs1P => //=; first by rewrite inE numx_infty ltnn.\n  by move=> u v ue; rewrite inE => /eqP->; apply: roots_connected.\nmove=> _ _ _ e1 -> e1_wf subee1 [-> -> new1c new1old seen1E].\ncase: dfsP => //= [u v ue1|_ _ _ e2 -> e2_wf sube12 [-> ->new2c new2old seen2E]].\n  rewrite inE => /andP[_ v_roots].\n  have [ue|uNe] := boolP (u \\in stack e); first by rewrite roots_connected.\n  have [|w we] := new1old u; first by rewrite inE ue1 uNe.\n  by move=> /connect_trans->//; rewrite roots_connected//.\nhave sube2 : subenv e e2 by exact: sub_trans sube12.\nhave nexts_split : nexts (~: seen e) roots =\n      nexts (~: seen e) [set x] :|: nexts (~: seen e1) (roots :\\ x).\n  by rewrite -[in LHS](setD1K x_roots) nextsU seen1E setCU nextsUI// nexts_id.\ndo 2!constructor=> //=.\n- rewrite (eq_bigr (fun x => inord (num e2 x))); last first.\n    move=> y y_in; rewrite (@sub_snum e1 e2)// num_lt_infty.\n      by rewrite seen1E setUC inE y_in.\n  by rewrite -[LHS]/(val (ord_minn _ _)) -bigmin_setU /= -nexts_split.\n- by rewrite setUC setUD ?sub_stack.\n- rewrite -(@setUD _ (stack e1)) ?sub_stack//.\n  apply: connectedU => // y z; last first.\n    rewrite !new_stackE// ?inE => /andP[y_ge y_lt] /andP[z_ge z_lt].\n    rewrite (@le_connect e2) // z_lt (leq_trans _ z_ge)//.\n    by rewrite (sub_vnum sube12)// ltnW.\n  rewrite !new_stackE// ?inE => /andP[y_ge y_lt] /andP[z_ge z_lt].\n  have [|r] := new2old y; rewrite ?new_stackE ?inE ?y_ge//.\n  move=> r_lt /connect_trans->//; have [rz|zr] := leqP (num e1 r) (num e1 z).\n    by rewrite (@le_connect e1)// rz/=.\n  by rewrite new1c ?new_stackE ?inE ?z_ge ?z_lt //= (leq_trans z_ge)// ltnW.\n- move=> y; rewrite ?new_stackE ?inE// => /andP[y_ge y_lt].\n  have [y_lt1|y_ge1] := ltnP (num e1 y) (sn e1).\n    have [|r] := new1old y; last by exists r.\n    by rewrite new_stackE ?inE// ?y_lt1 -(sub_vnum sube12) ?y_ge.\n  have [|r r_lt1 yr] := new2old y; first by rewrite !inE -leqNgt y_ge1//.\n  rewrite ?inE in r_lt1; have [r_lt|r_ge] := ltnP (num e r) (sn e).\n    by exists r; rewrite ?inE.\n  have [|r' r's rr'] := new1old r; first by rewrite ?inE -leqNgt r_ge r_lt1.\n  by exists r'; rewrite // (connect_trans yr rr').\n- by rewrite seen2E {1}seen1E nexts_split setUA.\nQed.\n\nLemma dfs1P dfs x e (A := [set y in successors x]):\n  dfs_correct dfs A (visit x e) -> dfs1_correct (dfs1 dfs) x e.\nProof.\nrewrite /dfs1 => dfsP e_wf xNseen x_connected.\nhave subexe: subenv e (visit x e) by exact: sub_visit.\nhave num0x : num e x = infty by apply: notseen_num.\nhave xNstack : x \\notin stack e.\n  by rewrite inE num0x ltnNge leqW// max_card.\nhave xe_wf : wf_env (visit x e).\n  by apply: wf_visit => // y y_lt; rewrite x_connected ?inE.\nhave nexts1E : nexts (~: seen e) [set x] = x |: nexts (~: (x |: seen e)) A.\n  by rewrite nexts1_split ?setDE ?setCU 1?setIC 1?inE.\ncase: dfsP => //=.\n  rewrite stack_visit// => u v; rewrite in_setU1=> /predU1P[->|ue];\n  rewrite inE => /(@connect1 _ edge)// /(connect_trans _)->//.\n  by rewrite x_connected// set11.\nmove=> _ _ _ e1 -> e1_wf subxe1 [/= -> -> newc new_old seen1E].\nhave sube1 : subenv e e1 by apply: sub_trans subxe1.\nhave num1x : num e1 x = sn e.\n  by rewrite (sub_snum subxe1)// ?inE ?ffunE ?serialE/= ?eqxx// ltnS max_card.\nrewrite ?seen_visit ?serialE// in seen1E *.\nhave lt_sn_sn1 : sn e < sn e1.\n  by rewrite (leq_trans _ (leq_sn subxe1))// seen_visit// cardsU1 xNseen.\nhave x_seen1 : x \\in seen e1 by rewrite seen1E inE setU11.\nhave x_stack : x \\in stack e1.\n  by rewrite (subsetP (sub_stack subxe1))//= stack_visit// setU11.\nhave -> : (x |: new_stack (visit x e) e1) = new_stack e e1.\n  by rewrite stack_visit// [_ |: stack e]setUC -setDDl setD1K// inE xNstack.\nhave [min_after|min_before] := leqP; last first.\n  do 2!constructor => //=.\n  - rewrite nexts1E bigmin_setU big_set1 /= inordK ?num1x ?ltnS ?max_card//.\n    by rewrite (minn_idPr _)// ltnW.\n  - move=> y z; have [-> _|neq_yx] := eqVneq y x.\n      by rewrite new_stackE ?inE// -num1x; apply: le_connect.\n    rewrite -(@setUD _ (stack (visit x e))) ?sub_stack//.\n    rewrite [in X in _ :|: X]stack_visit// setDUl setDv setU0.\n    rewrite [_ :\\: stack e](setDidPl _) ?disjoint1s//.\n    rewrite setUC !in_setU1 (negPf neq_yx)/=.\n    move=> y_e1 /predU1P[->|]; last exact: newc y_e1.\n    have [t] := new_old y y_e1; rewrite !inE => t_le /connect_trans->//.\n    rewrite (@le_connect (visit x e))// andbC; move: t_le.\n    rewrite seen_visit// !ffunE ?serialE//=.\n    by rewrite eqxx cardsU1 xNseen add1n !ltnS leqnn.\n  - move=> y; have [v ve xv] : exists2 v, v \\in stack e & gconnect x v.\n    have [|v] := @eq_bigmin_cond _ _ (mem (nexts (~: (x |: seen e)) A))\n                               (@inord #|V| \\o (num e1)).\n      rewrite card_gt0; apply: contraTneq min_before => ->.\n      by rewrite big_set0 -leqNgt max_card.\n    rewrite !inE => v_in min_is_v; move: min_before; rewrite min_is_v/=.\n    rewrite inordK; last by rewrite num_lt_infty seen1E inE v_in orbT.\n    rewrite -sub_num_lt// => v_lt; exists v; rewrite ?inE//.\n    move: v_in => /in_nextsW[z]; rewrite inE => /(@connect1 _ edge).\n    by apply: connect_trans.\n  - rewrite -(@setUD _ (stack (visit x e))) ?sub_stack//.\n    rewrite [in X in _ :|: X]stack_visit// setDUl setDv setU0.\n    rewrite [_ :\\: stack e](setDidPl _) ?disjoint1s// setUC !in_setU1.\n    move=> /predU1P[->|]; first by exists v.\n    move=> /new_old[z]; rewrite stack_visit// in_setU1.\n    move=> /predU1P[->|]; last by exists z.\n    by move=> yx; exists v; rewrite // (connect_trans yx).\n  - by rewrite nexts1E setUCA setUA seen1E.\nhave all_geq y : y \\in nexts (~: seen e) [set x] ->\n  (#|seen e| <= num e1 y) * (num e1 y < infty).\n  have := min_after; have sn_inord : sn e = @inord #|V| (sn e).\n    by rewrite inordK// ltnS max_card.\n  rewrite {1}sn_inord; move/bigmin_geqP => /(_ y) y_ge.\n  rewrite nexts1E !inE => /predU1P[->|yA]; rewrite ?num1x.\n    by rewrite ltnS max_card leqnn.\n  rewrite sn_inord (leq_trans (y_ge _))// ?inordK//;\n  by rewrite num_lt_infty seen1E 2!inE yA orbT.\nconstructor=> //=.\n- constructor=> //=; rewrite ?serialE ?seen_store ?sub_new_stack_seen//.\n  + rewrite subUset sub_gsccs// andbT sub1set.\n    suff -> : new_stack e e1 = gscc_of x by rewrite pblock_mem ?cover_sccs.\n    apply/setP=> y; rewrite mem_scc /symconnect.\n    have [->|neq_yx] := eqVneq y x.\n      by rewrite connect0 !inE num0x -leqNgt leqW ?max_card//= num1x lt_sn_sn1.\n    apply/idP/andP=> [|[xy yx]].\n      move=> y_ee1; have y_xee1 : y \\in new_stack (visit x e) e1.\n        by rewrite inE stack_visit// in_setU1 (negPf neq_yx)/= -in_setD.\n      split; last first.\n        have [z] := new_old _ y_xee1.\n        rewrite stack_visit// in_setU1 => /predU1P[->//|/x_connected].\n        by move=> /(_ _ (set11 x))/(connect_trans _) xz /xz.\n      have: y \\in new_seen (visit x e) e1.\n        by apply: subsetP y_xee1; rewrite sub_new_stack_new_seen.\n      rewrite inE seen1E in_setU seen_visit//; case: (y \\in _ |: _) => //=.\n      move=> /in_nextsW[z]; rewrite inE=> /(@connect1 _ edge).\n      exact: connect_trans.\n    have /(connect_from (mem (~: seen e))) [z []] := xy; rewrite inE.\n    move=> eq_yz xz zy; have /all_geq [] : z \\in nexts (~: seen e) [set x].\n      by apply/bigcupP; exists x; rewrite !inE.\n    rewrite leqNgt -sub_num_lt// -num_lt_V// -leqNgt ltnS => zNstack.\n    have zNcover e' : wf_env e' -> z \\in cover (esccs e') ->\n                      x \\in cover (esccs e').\n      move=> e'_wf /bigcupP[C] Ce zC; apply/bigcupP; exists C => //.\n      have /def_scc: C \\in gsccs by apply: subsetP Ce; apply: sub_gsccs.\n      move=> /(_ _ zC)<-; rewrite mem_scc /= /symconnect (connect_trans zy)//=.\n      by apply: connect_sub xz => ?? /andP[_ /connect1].\n    rewrite leq_eqVlt num_sccs// num_lt_V// => /orP[|z_stack].\n       move=> /zNcover; rewrite -num_sccs// num1x => /(_ _) /eqP eq_V.\n       by rewrite eq_V// ltnNge max_card in lt_sn_sn1.\n    have zNseen : z \\notin seen e.\n      rewrite inE -leqNgt ltn_neqAle eq_sym num_sccs// zNstack andbT.\n      apply: contraTN isT => /(zNcover _ e_wf).\n      by rewrite -num_sccs// num0x; elim: #|V|.\n    move: eq_yz; rewrite zNseen /= => /andP[/eqP eq_yz _].\n    rewrite -eq_yz in zNstack z_stack.\n    by rewrite !inE -num_lt_V// -leqNgt zNstack.\n  + by move=> v; rewrite ffunE/=; case: ifP; rewrite ?max_num //.\n  + move=> v; rewrite ffunE/=; case: ifPn; rewrite ?ltnn// => vNe12.\n    by rewrite num_lt_V// seen_store.\n  + move=> v; rewrite ffunE /= cover1U [in RHS]inE.\n    by case: ifPn; rewrite ?eqxx//= => vNe12; rewrite -num_sccs//.\n  + move=> y z; rewrite !ffunE; case: ifPn => _.\n      by move=> /andP[/leq_ltn_trans Vsmall/Vsmall]; rewrite ltnNge max_card.\n    by case: ifPn => _; [by rewrite ltnNge max_card andbF|exact : le_connect].\n- rewrite /subenv /= (subset_trans (sub_sccs sube1)) ?subsetUr//=.\n  apply/andP; split; apply/forallP => v; apply/implyP;\n  rewrite ffunE/= new_stackE// ?inE.\n    move=> vs; rewrite (sub_snum sube1)// leqNgt -!num_lt_V// -leqNgt ifN//.\n    by apply/negP => /andP[/leq_ltn_trans Vlt/Vlt]; rewrite ltnNge max_card.\n  by case: ifPn; [move=> _; rewrite ltnNge max_card|rewrite -sub_num_lt].\n- rewrite /outenv stack_store ?seen_store ?sub_new_stack_seen//.\n  rewrite setDDr setDUl setDv set0D set0U setDIl !setDv setI0.\n  split; do ?by [move=> ?; rewrite ?inE//=|]; last first.\n    by rewrite seen1E -setUA setUCA -nexts1E.\n  rewrite big1// => y xy; rewrite ffunE new_stackE ?inE//=.\n  have y_seen1 : num e1 y < infty.\n    by rewrite num_lt_infty seen1E -setUA setUCA -nexts1E inE xy orbT.\n  apply/val_inj=> /=; case: ifPn; rewrite ?inordK//.\n  rewrite all_geq//= -num_lt_V// -leqNgt; move: y_seen1; rewrite ltnS.\n  by case: ltngtP.\nQed.\n\nTheorem tarjan_rec_terminates n (roots : {set V}) e :\n  n >= #|~: seen e| * #|V|.+1 + #|roots| ->\n  dfs_correct (tarjan_rec n) roots e.\nProof.\nmove=> n_ge; elim: n => [|n IHn/=] in roots e n_ge *.\n  move: n_ge; rewrite leqn0 addn_eq0 cards_eq0 => /andP[_ /eqP-> e_wf _]/=.\n  constructor=> //=; rewrite /outenv ?nexts0 ?setDv ?big_set0// ?setU0.\n  by split=> // ?; rewrite inE.\napply: dfsP=> x x_roots; last first.\n  move=> e1 subee1; apply: IHn; rewrite -ltnS (leq_trans _ n_ge)//.\n  rewrite (cardsD1 x roots) x_roots add1n -addSnnS ltn_add2r ltnS.\n  by rewrite leq_mul2r //= subset_leq_card// setCS sub_seen.\nmove=> e_wf xNseen; apply: dfs1P => //; apply: IHn.\nrewrite seen_visit// setCU setIC -setDE -ltnS (leq_trans _ n_ge)//.\nrewrite (cardsD1 x (~: _)) inE xNseen add1n mulSnr -addnA ltn_add2l.\nby rewrite ltn_addr// ltnS max_card.\nQed.\n\nLemma seen0 : seen e0 = set0.\nProof. by apply/setP=> y; rewrite !inE ffunE ltnn. Qed.\n\nLemma stack0 : stack e0 = set0.\nProof. by apply/setP=> y; rewrite !inE ffunE ltnNge leqW ?max_card. Qed.\n\nLemma tarjan_recP :\n   tarjan_rec N setT e0 = (#|V|, set0, Env gsccs #|V| [ffun x => #|V|]).\nProof.\ncase: tarjan_rec_terminates; first by rewrite seen0 setC0 cardsT.\n- constructor; rewrite /= ?serialE ?seen0 ?cards0 ?sub0set// => x; rewrite !ffunE//.\n  + by rewrite ltnNge leqW//.\n  + by rewrite gtn_eqF// /cover big_set0 inE.\n  + by move=> y; rewrite !ffunE//= andbC ltnNge leqW// ?max_card.\n  + by move=> y; rewrite !inE !ffunE/= ltnNge leqW// max_card.\nmove=> _ _ _ e -> e_wf _ [-> -> _]; rewrite stack0 setD0.\nhave [stacke _|[x xe]] := set_0Vmem (stack e); last first.\n  by move=> /(_ _ xe)[?]; rewrite inE.\nrewrite seen0 set0U setC0 nextsT => seene.\nhave numE x : num e x = #|V|.\n  apply/eqP; have /setP/(_ x) := seene.\n  by rewrite seenE// stacke set0U !inE -num_sccs.\nhave serialE : serial e = #|V| by rewrite serialE// seene cardsT.\nhave sccse : esccs e = gsccs.\n  apply/eqP; rewrite eqEsubset sub_gsccs//=; apply/subsetP => _/imsetP[/=x _->].\n  have: x \\in cover (esccs e) by rewrite -num_sccs ?numE//.\n  move=> /bigcupP [C Csccs /(def_scc (subsetP (sub_gsccs e_wf) _ Csccs))] eqC.\n  rewrite -eqC (_ : [set _ in _ | _] = gscc_of x)// in Csccs *.\n  by apply/setP => y; rewrite !inE mem_scc /=.\nrewrite big1; last by move=> x _; apply: val_inj; rewrite /= inordK// ?numE.\ncongr (_, _, _) => //.\ncase: e {stacke seene e_wf} => /= sccs sn num in numE serialE sccse *.\nby congr (Env _ _) => //; apply/ffunP=> x; rewrite ffunE.\nQed.\n\nTheorem tarjan_correct : tarjan = gsccs.\nProof. by rewrite /tarjan; have [->] := tarjan_recP. Qed.\n\nEnd tarjan.\n", "meta": {"author": "coq-community", "repo": "tarjan", "sha": "afc3e6f51db80bc6171ff882caec5433b6290b50", "save_path": "github-repos/coq/coq-community-tarjan", "path": "github-repos/coq/coq-community-tarjan/tarjan-afc3e6f51db80bc6171ff882caec5433b6290b50/theories/tarjan_nocolor_optim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809304, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6761652556757134}}
{"text": "Require Import Reals.\nFrom ValidSDP Require Import validsdp posdef_check.\nRequire matrices.\nLocal Open Scope R_scope.\n\nTest Default Proof Mode.\nRequire Import Ltac2.Ltac2. (* TODO: this will later be unnecessary *)\nTest Default Proof Mode.\n(* Set Default Proof Mode \"Ltac2\". (implied) *)\n\n(* To enable debug mode: *)\n(* Ltac2 Set deb := fun str => Message.print str. *)\n\nSection Tests.\n\nLet test1 x y : 0 < x -> 1 <= y -> x + y >= 0.\nProof.\nTime validsdp.\nQed.\n\nLet test2 x y : 2 / 3 * x ^ 2 + y ^ 2 >= 0.\nProof.\nTime validsdp.\nQed.\n\nLet test3 x y : 2 / 3 * x ^ 2 + y ^ 2 + 1 > 0.\nProof.\nTime validsdp.\nQed.\n\nLet p x y := 2 / 3 * x ^ 2 + y ^ 2.\n\nLet test4 x y : p x y + 1 > 0.\nProof.\nTime validsdp.\nQed.\n\nLet test6 x : x >= 10 -> x <= 12 -> 0 <= 2 + x ^ 2.\nProof.\nvalidsdp.\nQed.\n\nEnd Tests.\n", "meta": {"author": "validsdp", "repo": "validsdp", "sha": "135dd32a2b1166f357df764b469ce14e24711536", "save_path": "github-repos/coq/validsdp-validsdp", "path": "github-repos/coq/validsdp-validsdp/validsdp-135dd32a2b1166f357df764b469ce14e24711536/test-suite/test_validsdp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6761652555189529}}
{"text": "From FA Require Import String.\nFrom mathcomp Require Import all_ssreflect.\n\nRecord dfa: Type :=\n    mkdfa\n    {\n       dfa_state     :> finType;\n       dfa_start     : dfa_state;\n       dfa_transition: dfa_state -> Sigma -> dfa_state;\n       dfa_finals    : {set dfa_state}\n    }.\n\nFixpoint dfa_multistep (d: dfa) (q: dfa_state d) (s: String): dfa_state d :=\n  match s with\n    | eps      => q\n    | glue x y => dfa_transition d (dfa_multistep d q x) y\n  end.\n\nLemma dfa_ms_ss: forall (d: dfa) (s: d) (c: Sigma),\n  dfa_transition d s c = dfa_multistep d s (glue eps c).\nProof. intros. simpl. easy. Qed.\n\nDefinition dfa_acceptance (d: dfa) (st: @dfa_state d) (s: String): bool :=\n  [exists y, (y == (dfa_multistep d st s)) && (y \\in (@dfa_finals d))].\n\nDefinition dfa_language (d: dfa) := [pred w | dfa_acceptance d (@dfa_start d) w].\n", "meta": {"author": "ekiciburak", "repo": "FiniteStateMachines", "sha": "b2beae4ffa773a2ed5e039565fd1180a01caa42d", "save_path": "github-repos/coq/ekiciburak-FiniteStateMachines", "path": "github-repos/coq/ekiciburak-FiniteStateMachines/FiniteStateMachines-b2beae4ffa773a2ed5e039565fd1180a01caa42d/DFA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314707995588, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6761652484481706}}
{"text": "Require Import Arith.\nRequire Import Program.\nRequire Import Omega.\nParameters (var: Set)\n           (sig: nat -> Set).\n\nAxiom var_eq_dec: forall v1 v2: var, { v1 = v2 } + { v1 <> v2 }.\n\nInductive ilist (A: Set) : nat -> Set :=\n| niln: ilist A 0\n| consn: forall n, A -> ilist A n -> ilist A (S n)\n.\n\nInductive fin : nat -> Set :=\n| f0: fin 1\n| fs: forall n, fin n -> fin (S n)\n.\n\nDefinition dlist n (P: fin n -> Set): Set := forall (i: fin n), P i. \n\nFixpoint fin_to_nat n (m: fin n): nat.\n  destruct m _eqn: Heq.\n  exact 0.\n  apply S.\n  apply (fin_to_nat n f).\nDefined.\n\n\nVariable axiom: Set.\n\nInductive term: Set :=\n  | tm_var: var -> term\n  | tm_cong: forall n (s: sig n), (fin n -> term) -> term\n.\n\nInductive deriv: term -> term -> Set :=\n| drv_refl: forall s, deriv s s\n| drv_sym: forall s t, deriv s t -> deriv t s\n| drv_trans: forall s t u, deriv s t -> deriv t u -> deriv s u\n| drv_cong: forall n (s: sig n) (ss ts: fin n -> term), dlist n (fun x => deriv (ss x) (ts x)) -> deriv (tm_cong n s ss) (tm_cong n s ts). \n\n(* example: refl *)\nGoal forall s, deriv s s.\n      apply drv_refl.\nQed.\n\nFixpoint subst (s: term) (u: term) (x: var): term :=\n  match s with\n  | tm_var v =>\n    if var_eq_dec v x then u else tm_var v\n  | tm_cong n si t =>\n    tm_cong n si (fun i : fin n => subst (t i) u x)\n  end.\n\nSection monoid_theory.\n  Axiom mul_sig: sig 2.\n  Definition mul: term -> term -> term :=\n    fun a b : term =>\ntm_cong 2 mul_sig\n   (fun i0 : fin 2 =>\n    match\n      i0 in (fin n0) return (forall i1 : fin n0, i1 = i0 -> term)\n    with\n    | f0 => fun (i1 : fin 1) (_ : i1 = f0) => a\n    | fs n0 f1 => fun (i1 : fin (S n0)) (_ : i1 = fs n0 f1) => b\n    end i0 eq_refl).\n  Print mul.\n  Axiom e_sig: sig 0.\n  Definition e: term.\n                  apply (tm_cong 0 e_sig).\n                  intro i.\n                  inversion i.\n  Defined.\n  Axiom unit_law_l: forall s, deriv (mul e s) s.\n  Axiom unit_law_r: forall s, deriv (mul s e) s.\n\n  Theorem mul_well_defined: forall s1 s2 t1 t2, deriv s1 t1 -> deriv s2 t2 -> deriv (mul s1 s2) (mul t1 t2).\n                                                  intros s1 s2 t1 t2 H H0.\n                                                  apply drv_cong.\n                                                  intro i.\n                                                  destruct i _eqn:ieq.\n                                                  exact H.\n                                                  exact H0.\n                                                  Qed.\nEnd monoid_theory.\n\nSection subst_closed.\n  \nEnd subst_closed.\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/equ_logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6761505860403831}}
{"text": "(**\nHere we define the category of setoids.\nThe objects are setoids and the morphisms are setoid mophisms.\nWe also show it has sums, products, and exponentials.\nWe end by showing that the quotient from setoids to set is a left adjoint.\n *)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.Combinatorics.FiniteSets.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Equivalences.\nRequire Import UniMath.CategoryTheory.categories.HSET.All.\nRequire Import UniMath.CategoryTheory.limits.binproducts.\nRequire Import UniMath.CategoryTheory.limits.bincoproducts.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Core.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Constructions.\nRequire Import UniMath.CategoryTheory.exponentials.\nRequire Import UniMath.CategoryTheory.Adjunctions.Core.\n\nRequire Import setoids.base.\n\nOpen Scope cat.\n\n(** The category of setoids *)\nDefinition setoid_cat_ob_mor\n  : precategory_ob_mor.\nProof.\n  use make_precategory_ob_mor. \n  - exact setoid.\n  - exact setoid_morphism.\nDefined.\n\nDefinition id_setoid_morphism (X : setoid)\n  : setoid_morphism X X.\nProof.\n  use make_setoid_morphism.\n  - exact (idfun X).\n  - exact (λ x y, idfun (x ≡ y)).\nDefined.\n\nDefinition comp_setoid_morphism\n           {X₁ X₂ X₃ : setoid}\n           (f₁ : setoid_morphism X₁ X₂)\n           (f₂ : setoid_morphism X₂ X₃)\n  : setoid_morphism X₁ X₃.\nProof.\n  use make_setoid_morphism.\n  - exact (λ z, f₂(f₁ z)).\n  - exact (λ x y p, map_eq f₂(map_eq f₁ p)).\nDefined.\n\nDefinition setoid_cat_data\n  : precategory_data.\nProof.\n  use make_precategory_data.\n  - exact setoid_cat_ob_mor.\n  - exact id_setoid_morphism.\n  - exact @comp_setoid_morphism.\nDefined.\n\nDefinition setoid_precat\n  : precategory.\nProof.\n  use make_precategory.\n  - exact setoid_cat_data.\n  - repeat (use tpair) ; cbn.\n    + reflexivity.\n    + reflexivity.\n    + reflexivity.\n    + reflexivity.\nDefined.\n\nDefinition setoid_cat\n  : category.\nProof.\n  use make_category.\n  - exact setoid_precat.\n  - intros X₁ X₂ ; cbn.\n    apply isaset_setoid_morphism.\nDefined.\n\n(** Sums in the category of setoids *)\nDefinition sum_rel\n           {X Y : hSet}\n           (R₁ : eqrel X)\n           (R₂ : eqrel Y)\n  : eqrel (setcoprod X Y)%set.\nProof.\n  use make_eq_rel.\n  - intros s₁ s₂.\n    destruct s₁ as [x₁ | y₁], s₂ as [x₂ | y₂].\n    + exact (R₁ x₁ x₂).\n    + exact hfalse.\n    + exact hfalse.\n    + exact (R₂ y₁ y₂).\n  - intros s.\n    destruct s as [x | y].\n    + exact (id x)%setoid.\n    + exact (id y)%setoid.\n  - intros s₁ s₂.\n    destruct s₁ as [x₁ | y₁], s₂ as [x₂ | y₂].\n    + exact (λ p , ! p)%setoid.\n    + exact (idfun _).\n    + exact (idfun _).\n    + exact (λ p , ! p)%setoid.\n  - intros s₁ s₂ s₃.\n    destruct s₁ as [x₁ | y₁], s₂ as [x₂ | y₂].\n    + destruct s₃ as [x₃ | y₃].\n      * exact (λ p q , p @ q)%setoid.\n      * exact (λ _, fromempty).\n    + exact fromempty.\n    + exact fromempty.\n    + destruct s₃ as [x₃ | y₃].\n      * exact (λ _, fromempty).\n      * exact (λ p q , p @ q)%setoid.\nDefined.\n\nDefinition sum_setoid (X Y : setoid_cat)\n  : setoid_cat\n  := make_setoid (sum_rel (carrier_eq X) (carrier_eq Y)).\n\nDefinition setoid_inl\n           (X₁ X₂ : setoid_cat)\n  : X₁ --> sum_setoid X₁ X₂.\nProof.\n  use make_setoid_morphism.\n  - exact (λ x, inl x).\n  - exact (λ _ _ p, p).\nDefined.\n\nDefinition setoid_inr\n           (X₁ X₂ : setoid_cat)\n  : X₂ --> sum_setoid X₁ X₂.\nProof.\n  use make_setoid_morphism.\n  - exact (λ x, inr x).\n  - exact (λ _ _ p, p).\nDefined.\n\nDefinition setoid_plus\n           {X₁ X₂ Y : setoid_cat}\n           (f : X₁ --> Y)\n           (g : X₂ --> Y)\n  : sum_setoid X₁ X₂ --> Y.\nProof.\n  unshelve esplit.\n  - intro z.\n    destruct z as [x | x] ; cbn in *.\n    + exact (f x).\n    + exact (g x).\n  - intros z₁ z₂ p.\n    destruct z₁ as [x₁ | x₁ ], z₂ as [x₂ | x₂].\n    + exact (map_eq f p).\n    + exact (fromempty p).\n    + exact (fromempty p).\n    + exact (map_eq g p).\nDefined.\n\nDefinition sum_setoid_is_bincoproduct\n           (X₁ X₂ : setoid_cat)\n  : isBinCoproduct\n      setoid_cat X₁ X₂\n      (sum_setoid X₁ X₂) (setoid_inl X₁ X₂) (setoid_inr X₁ X₂).\nProof.\n  intros Y f g ; cbn.\n  use tpair.\n  - use tpair.\n    + exact (setoid_plus f g).\n    + split ; reflexivity.\n  - intros h.\n    use subtypePath.\n    + intro.\n      apply isapropdirprod ; apply setoid_cat.\n    + use setoid_morphism_eq ; cbn.\n      intro z.\n      destruct z as [x | x].\n      * induction (pr12 h).\n        reflexivity.\n      * induction (pr22 h).\n        reflexivity.\nDefined.\n\nDefinition setoid_cat_bincoproducts\n  : BinCoproducts setoid_cat.\nProof.\n  intros X₁ X₂.\n  use tpair.\n  - exact (sum_setoid X₁ X₂ ,, setoid_inl X₁ X₂ ,, setoid_inr X₁ X₂).\n  - exact (sum_setoid_is_bincoproduct X₁ X₂).\nDefined.\n\n(** The category of setoids has binary products *)\nDefinition prod_rel\n           {X Y : hSet}\n           (R₁ : eqrel X)\n           (R₂ : eqrel Y)\n  : eqrel (X × Y)%set.\nProof.\n  use make_eq_rel.\n  - exact (λ z₁ z₂, (hconj (R₁ (pr1 z₁) (pr1 z₂)) (R₂ (pr2 z₁) (pr2 z₂)))).\n  - exact (λ z, (id (pr1 z) ,, id (pr2 z)))%setoid.\n  - exact (λ _ _ p, (! (pr1 p) ,, ! (pr2 p)))%setoid.\n  - exact (λ _ _ _ p q, ((pr1 p @ pr1 q) ,, (pr2 p @ pr2 q)))%setoid.\nDefined.\n\nDefinition prod_setoid (X Y : setoid_cat)\n  : setoid_cat\n  := make_setoid (prod_rel (carrier_eq X) (carrier_eq Y)).\n\nDefinition setoid_pr1\n           (X₁ X₂ : setoid_cat)\n  : prod_setoid X₁ X₂ --> X₁.\nProof.\n  use make_setoid_morphism.\n  - exact (λ z ,  pr1 z).\n  - exact (λ _ _, pr1).\nDefined.\n\nDefinition setoid_pr2\n           (X₁ X₂ : setoid_cat)\n  : prod_setoid X₁ X₂ --> X₂.\nProof.\n  use make_setoid_morphism.\n  - exact (λ z ,  pr2 z).\n  - exact (λ _ _, pr2).\nDefined.\n\nDefinition setoid_pair\n           {X₁ X₂ Y : setoid_cat}\n           (f : Y --> X₁)\n           (g : Y --> X₂)\n  : Y --> prod_setoid X₁ X₂.\nProof.\n  use make_setoid_morphism ; cbn in *.\n  - exact (λ y, (f y ,, g y)).\n  - exact (λ _ _ p, (map_eq f p ,, map_eq g p)).\nDefined.\n\nDefinition prod_setoid_is_binproduct\n           (X₁ X₂ : setoid_cat)\n  : isBinProduct\n      setoid_cat X₁ X₂\n      (prod_setoid X₁ X₂) (setoid_pr1 X₁ X₂) (setoid_pr2 X₁ X₂).\nProof.\n  intros Y f g ; cbn.\n  use tpair.\n  - use tpair.\n    + exact (setoid_pair f g).\n    + split ; reflexivity.\n  - intros h.\n    use subtypePath.\n    + intro.\n      apply isapropdirprod ; apply setoid_cat.\n    + use setoid_morphism_eq ; cbn.\n      intro z.\n      use dirprod_paths.\n      * induction (pr12 h).\n        reflexivity.\n      * induction (pr22 h).\n        reflexivity.\nDefined.\n\nDefinition setoid_cat_binproducts\n  : BinProducts setoid_cat.\nProof.\n  intros X₁ X₂.\n  use tpair.\n  - exact (prod_setoid X₁ X₂ ,, setoid_pr1 X₁ X₂ ,, setoid_pr2 X₁ X₂).\n  - exact (prod_setoid_is_binproduct X₁ X₂).\nDefined.\n\n(** Exponentials of setoids *)\nDefinition setoid_morphism_hSet (X₁ X₂ : setoid)\n  : hSet.\nProof.\n  use make_hSet.\n  - exact (setoid_morphism X₁ X₂).\n  - apply isaset_setoid_morphism.\nDefined.\n\nDefinition fun_rel\n           (X₁ X₂ : setoid)\n  : eqrel (setoid_morphism_hSet X₁ X₂).\nProof.\n  use make_eq_rel.\n  - intros f g ; cbn in *.\n    exact (∀ (x : X₁), f x ≡ g x).\n  - exact (λ f x, id _ _)%setoid.\n  - exact (λ f g p x, ! (p x))%setoid.\n  - exact (λ f g h p₁ p₂ x, p₁ x @ p₂ x)%setoid.\nDefined.\n\nDefinition setoid_exp\n           (X₁ X₂ : setoid_cat)\n  : setoid_cat\n  := make_setoid (fun_rel X₁ X₂).\n\nDefinition setoid_exp_functor_data\n           (X : setoid)\n  : functor_data setoid_cat setoid_cat.\nProof.\n  use make_functor_data.\n  - exact (setoid_exp X).\n  - intros Y₁ Y₂ f ; cbn in *.\n    use make_setoid_morphism ; cbn.\n    + exact (λ g, comp_setoid_morphism g f).\n    + exact (λ g₁ g₂ p x, map_eq f (p x)).\nDefined.\n\nDefinition setoid_exp_functor\n           (X : setoid)\n  : setoid_cat ⟶ setoid_cat.\nProof.\n  use make_functor.\n  - exact (setoid_exp_functor_data X).\n  - split.\n    + intros Y.\n      use setoid_morphism_eq.\n      reflexivity.\n    + intros Y₁ Y₂ Y₃ f₁ f₂.\n      use setoid_morphism_eq.\n      reflexivity.\nDefined.\n\nDefinition setoid_exp_unit\n           (X : setoid)\n  : (functor_identity setoid_precat)\n      ⟹\n      constprod_functor1 setoid_cat_binproducts X ∙ setoid_exp_functor X.\nProof.\n  use make_nat_trans.\n  - intros Y.\n    use make_setoid_morphism.\n    + intros y.\n      use make_setoid_morphism.\n      * exact (λ x, x ,, y).\n      * exact (λ x₁ x₂ p , p ,, id _ _)%setoid.\n    + exact (λ y₁ y₂ p x , id _ _ ,, p)%setoid.\n  - intros Y₁ Y₂ f.\n    abstract (\n        use setoid_morphism_eq ;\n        intro y ;\n        use setoid_morphism_eq ;\n        reflexivity).\nDefined.\n\nDefinition setoid_exp_counit\n           (X : setoid)\n  : (setoid_exp_functor X ∙ constprod_functor1 setoid_cat_binproducts X)\n      ⟹\n      functor_identity setoid_precat.\nProof.\n  use make_nat_trans.\n  - intros Y.\n    use make_setoid_morphism.\n    + intro z ; cbn in *.\n      exact (pr2 z (pr1 z)).\n    + intros z₁ z₂ p ; cbn in *.\n      exact (map_eq (pr2 z₁) (pr1 p) @ pr2 p (pr1 z₂))%setoid.\n  - intros Y₁ Y₂ f.\n    use setoid_morphism_eq.\n    reflexivity.\nDefined.\n\nDefinition setoid_cat_has_exponentials\n  : Exponentials setoid_cat_binproducts.\nProof.\n  intro X.\n  use tpair.\n  - exact (setoid_exp_functor X).\n  - use make_are_adjoints.\n    + exact (setoid_exp_unit X).\n    + exact (setoid_exp_counit X).\n    + split.\n      * abstract(\n            intros Y ;\n            use setoid_morphism_eq ;\n            reflexivity).\n      * abstract\n          (intros Y ;\n           use setoid_morphism_eq ;\n           intro ;\n           use setoid_morphism_eq ;\n           reflexivity).\nDefined.\n\n(** Functor from set to setoid *)\nDefinition path_rel\n           (X : hSet)\n  : eqrel X\n  := make_eq_rel\n       (λ x y, eqset x y)\n       idpath\n       (λ _ _ p, ! p)\n       (λ _ _ _ p q, p @ q).\n\nDefinition path_setoid_data : functor_data SET setoid_cat.\nProof.\n  use make_functor_data.\n  - exact (λ X, make_setoid (path_rel X)).\n  - intros X Y f.\n    use make_setoid_morphism.\n    + exact f.\n    + exact (λ x y p, maponpaths f p).\nDefined.\n      \nDefinition path_setoid : SET ⟶ setoid_cat.\nProof.\n  use make_functor.\n  - exact path_setoid_data.\n  - split.\n    + intros X ; cbn.\n      use setoid_morphism_eq.\n      reflexivity.\n    + intros X Y Z f g ; cbn.\n      use setoid_morphism_eq.\n      reflexivity.\nDefined.\n\n(** Functor fom setoid to set *)\nDefinition quotient_setoid_ob\n           (X : setoid)\n  : hSet.\nProof.\n  use setquotinset.\n  - exact X.\n  - exact (carrier_eq X).\nDefined.\n\nDefinition quotient_setoid_mor\n           {X₁ X₂ : setoid}\n           (f : setoid_morphism X₁ X₂)\n  : quotient_setoid_ob X₁ → quotient_setoid_ob X₂.\nProof.\n  use setquotuniv ; cbn.\n  - exact (λ x, setquotpr _ (f x)).\n  - exact (λ x y p, iscompsetquotpr _ (f x) (f y) (map_eq f p)).\nDefined.\n\nDefinition quotient\n  : setoid_cat ⟶ SET.\nProof.\n  use make_functor.\n  - use make_functor_data.\n    + exact quotient_setoid_ob.\n    + exact @quotient_setoid_mor.\n  - split.\n    + intros X ; cbn.\n      use funextsec ; intro x.\n      use (setquotunivprop' (λ z, _ z = z)).\n      * intro.\n        apply isasetsetquot.\n      * intro y ; cbn.\n        reflexivity.\n    + intros X Y Z f g ; cbn.\n      use funextsec ; intro x.\n      use (setquotunivprop' (λ z, _ z = quotient_setoid_mor g (quotient_setoid_mor f z))).\n      * intro.\n        apply isasetsetquot.\n      * intro y ; cbn.\n        reflexivity.\nDefined.\n\nDefinition quotient_unit\n  : functor_identity setoid_cat ⟹ quotient ∙ path_setoid.\nProof.\n  use make_nat_trans.\n  - intro X ; cbn.\n    use make_setoid_morphism.\n    + exact (setquotpr _).\n    + exact (iscompsetquotpr _).\n  - abstract\n      (intros X Y f ; cbn ;\n       use setoid_morphism_eq ;\n       intro x ;\n       reflexivity).\nDefined.\n\nDefinition quotient_counit\n  : path_setoid ∙ quotient ⟹ functor_identity SET.\nProof.\n  use make_nat_trans.\n  - intro X ; cbn.\n    use setquotuniv.\n    + exact (idfun _).\n    + exact (λ x y p, p).\n  - abstract\n      (intros X Y f ;\n       use funextsec ;\n       intro x ;\n       revert x ;\n       use setquotunivprop' ;\n       [ intro ; apply Y | reflexivity ]).\nDefined.\n\nDefinition quotient_counit_is_inverse\n           (X : SET)\n  : is_inverse_in_precat (quotient_counit X) (setquotpr (carrier_eq (path_setoid X))).\nProof.\n  split.\n  - use funextsec.\n    use setquotunivprop'.\n    { intro. apply isasetsetquot. }\n    reflexivity.\n  - use funextsec.\n    intro.\n    reflexivity.\nQed.\n\nDefinition quotient_counit_is_nat_iso\n  : is_nat_iso quotient_counit.\nProof.\n  intros X.\n  use is_iso_qinv.\n  - exact (setquotpr _).\n  - exact (quotient_counit_is_inverse X).\nDefined.\n\n(** The quotient is a left adjoint *)\nDefinition quotient_adjunction\n  : adjunction setoid_cat SET.\nProof.\n  simple refine ((quotient ,, (path_setoid ,, (_ ,, _))) ,, _).\n  - exact quotient_unit.\n  - exact quotient_counit.\n  - split.\n    + abstract\n        (intro X ;\n         use funextsec ;\n         intro x ; revert x ; cbn ;\n         use setquotunivprop' ;\n         [ intro ; apply isasetsetquot | reflexivity ]).\n    + abstract\n        (intro X ;\n         use setoid_morphism_eq ;\n         intro x ; cbn in * ;\n         reflexivity).\nDefined.\n", "meta": {"author": "nmvdw", "repo": "FinitaryFunctors", "sha": "7342b68819209fda64d2be8c8f0dbf5305e3608a", "save_path": "github-repos/coq/nmvdw-FinitaryFunctors", "path": "github-repos/coq/nmvdw-FinitaryFunctors/FinitaryFunctors-7342b68819209fda64d2be8c8f0dbf5305e3608a/new_code/setoids/setoid_category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730775, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6761505830760146}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf2 : natural) (z : natural) (x : natural)\n  : natural := plus Zero lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj194_coqofml_vAuSZv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574068, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6761505779092195}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\nInductive natural : Type :=   Zero : natural | Succ : natural -> natural .\n\nInductive lst : Type :=  Nil : lst | Cons : natural -> lst -> lst .\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) : natural\n           := match mult_arg0, mult_arg1 with\n              | Zero, n => Zero\n              | Succ n, m => plus (mult n m) m\n              end.\n\nFixpoint qmult (qmult_arg0 : natural) (qmult_arg1 : natural) (qmult_arg2 : natural) : natural\n           := match qmult_arg0, qmult_arg1, qmult_arg2 with\n              | Zero, n, m => m\n              | Succ n, m, p => qmult n m (plus p m)\n              end.\n\nLemma plus_succ : forall (x y : natural), plus x (Succ y) = Succ (plus x y).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_assoc : forall (x y z : natural), plus (plus x y) z = plus x (plus y z).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_zero : forall (x : natural), plus x Zero = x.\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_commut : forall (x y : natural), plus x y = plus y x.\nProof.\n   intros.\n   induction x.\n   - rewrite plus_zero. reflexivity.\n   - simpl. rewrite plus_succ. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_qmult : forall (x y z a : natural), plus (qmult x y z) a = qmult x y (plus z a).\nProof.\n   intro.\n   induction x.\n   - reflexivity.\n   - intros. simpl. rewrite IHx. lfind. Admitted.\n\n", "meta": {"author": "ana-brendel", "repo": "coq-benchmarks", "sha": "78b9ca2993b0fb579d814ed17e63c6859e79681c", "save_path": "github-repos/coq/ana-brendel-coq-benchmarks", "path": "github-repos/coq/ana-brendel-coq-benchmarks/coq-benchmarks-78b9ca2993b0fb579d814ed17e63c6859e79681c/modifications/quickchick_fails/test50_goal34/lfind_goal34.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6761344141171448}}
{"text": "  From Autosubst Require Import Autosubst.\n\n(* Formalisation de l'arithmétique de Peano                         *\n * Introduction des types inductifs corespondant aux entiers de     *\n * Peano (Pnat) et aux propriétés portant sur ces entiers (Pprop)   *)\n\nInductive Pnat : Set :=\n  | PO : Pnat\n  | PS : Pnat -> Pnat\n  | plus : Pnat -> Pnat -> Pnat\n  | times : Pnat -> Pnat -> Pnat\n  | Pvar : var -> Pnat.\n\nInductive Pprop :=\n  | Pfalse : Pprop\n  | Ptrue : Pprop\n  | Peq : Pnat -> Pnat -> Pprop\n  | Pfa (_ : {bind Pnat in Pprop}) (* {bind Pnat in Pprop} -> Pprop *)\n  | Pex (_ : {bind Pnat in Pprop})\n  | Pim : Pprop -> Pprop -> Pprop\n  | Pan : Pprop -> Pprop -> Pprop\n  | Por : Pprop -> Pprop -> Pprop\n  | dummy (_ : var). (* type var -> Pprop *)\n\n\nNotation \"'Pno' f\" := (Pim f Pfalse) (at level 0).\n\n\n\n(* Les déclarations suivantes proviennent du manuel d'autosubst et  *\n * permettent de faire fonctionner la substitution sur les          *\n * expressions de type Pnat et Pprop.                               *)\n\nInstance Ids_Pnat : Ids Pnat. derive. Defined.\nInstance Rename_Pnat : Rename Pnat. derive. Defined.\nInstance Subst_Pnat : Subst Pnat. derive. Defined.\n\nInstance SubstLemmas_Pnat : SubstLemmas Pnat. derive. Qed.\n\nInstance Hsubst_Pprop : HSubst Pnat Pprop. derive. Defined.\n\nInstance Ids_Pprop : Ids Pprop. derive. Defined.\nInstance Rename_Pprop : Rename Pprop. derive. Defined.\nInstance Subst_Pprop : Subst Pprop. derive. Defined.\n\nInstance HSubstLemmas_Pprop : HSubstLemmas Pnat Pprop. derive. Qed.\nInstance SubstHSubstComp_Pnat_Pprop : SubstHSubstComp Pnat Pprop. derive. Qed.\nInstance SubstLemmas_Pprop : SubstLemmas Pprop. derive. Qed.\n\n\n\n(* On teste la substitution sur des expressions de type Pnat        *)\n\nCheck ((Pvar 0).[PO/]).\nEval compute in ((Pvar 0).[PO/]).\n\n(* On teste la substitution sur des expressions de type Pprop       *)\n\nCheck (Pfa (Peq (Pvar 0) (Pvar 0))).\nEval compute in (Pfalse.|[PO/]).\nEval compute in ((Peq (Pvar 0) (Pvar 0)).|[PO/]).\nEval compute in ((Peq (Pvar 0) (Pvar 1)).|[PO.:ids]).\n\n\n\n(* On définit les 7 axiomes de Peano :                              *\n * 1. ∀x.¬S(x) = 0                                                  *\n * 2. ∀x.∃y.(¬x = 0 ⇒ S(y) = x)                                     *\n * 3. ∀x.∀y.(S(x) = S(y) ⇒ x = y)                                   *\n * 4. ∀x.x + 0 = x                                                  *\n * 5. ∀x.∀y.S(x) + y = S(x + y)                                     *\n * 6. ∀x.(0 ∗ x = 0)                                                *\n * 7. ∀x.∀y.S(x) ∗ y = (x ∗ y) + y                                  *)\n\nDefinition succ_is_non_zero : Pprop :=\n  Pfa (Pno (Peq (PS (Pvar 0)) PO)).\n\nDefinition non_zero_has_succ : Pprop :=\n  Pfa (Pex (Pim (Pno (Peq (Pvar 1) PO)) (Peq (PS (Pvar 0)) (Pvar 1)))).\n\nDefinition eq_succ_implies_eq : Pprop :=\n  Pfa (Pfa (Pim (Peq (PS (Pvar 1)) (PS (Pvar 0))) (Peq (Pvar 1) (Pvar 0)) )).\n\nDefinition zero_is_neutral : Pprop :=\n  Pfa (Peq (plus (Pvar 0) (PO)) (Pvar 0)).\n\nDefinition succ_can_extend : Pprop :=\n  Pfa (Pfa (Peq (plus (PS (Pvar 1)) (Pvar 0)) (PS (plus (Pvar 1) (Pvar 0))))).\n\nDefinition zero_absorbs : Pprop :=\n  Pfa (Peq (times (Pvar 0) PO) (PO)).\n\nDefinition times_distributes : Pprop :=\n  Pfa (Pfa (Peq (times (Pvar 1) (PS (Pvar 0))) (plus (times (Pvar 1) (Pvar 0)) (Pvar 1)))).\n\n(* On ajoute aussi le schéma de récurrence, paramétré par un objet  *\n * de type Pprop                                                    *)\n\nDefinition recurrence_scheme : Pprop -> Pprop :=\n  fun (P : Pprop) => (Pim (P.|[PO/]) (Pim (Pfa (Pim (P.|[Pvar 0/]) (P.|[(PS (Pvar 0))/]))) (Pfa (P.|[Pvar 0/])))).\n\n(* On traite également le tiers exclu comme un axiome, qui          *\n * permettra d'étendre l'arithmétique de Heyting en l'arithmétique  *\n * de Heyting.                                                      *)\n\nDefinition excluded_middle : Pprop -> Pprop :=\n  fun (P : Pprop) => (Por P (Pno P)).\n\n(* Enfin, on définit les propriétés habituelles de l’égalité        *\n * (reflexivité, élimination).                                      *)\n\nDefinition reflexivity : Pprop :=\n  Pfa (Pfa (Pim (Peq (Pvar 0) (Pvar 1)) (Peq (Pvar 1) (Pvar 0)))).\n\nDefinition elimination : Pprop :=\n  Pfa (Pfa (Pfa (Pim (Peq (plus (Pvar 0) (Pvar 1)) (plus (Pvar 0) (Pvar 2))) (Peq (Pvar 1) (Pvar 2))))).\n\n\n\n(* Définition du contexte Γ utilisé dans la déduction naturelle:    *\n *   -- nilc est les contexte vide;                                 *\n *   -- intc signale une déclaration de variable;                   *\n *   -- assume ajoute une proposition (contenant éventuellement des *\n *      variables libres) à un contexte.                            *\n * Note : on suppose qu'un contexte bien formé est un contexte où   *\n * il n'existe pas de formule contenant de variable libre non liée  *\n * par un intc, càd que l'on ne pourra écrire Pvar k dans une       *\n * formule que si l'on a traversé au moins k+1 'binders' intc.      *)\n\nInductive Ctxt : Type :=\n  | nilc : Ctxt\n  | intc : Ctxt -> Ctxt \n  | assume : Pprop -> Ctxt -> Ctxt. \n\n(* On teste la définition du contexte sur le contexte               *\n * [x : nat; x = x; y : nat; y = 2]                                 *\n * Note : on choisit de placer les déclarations de variables en     *\n * amont des propositions qui les concernent, afin de faciliter la  *\n * réflection sur les contextes dans la suite.                      *)\n\nEval compute in (intc (assume (Peq (Pvar 0) (Pvar 0)) (intc (assume (Peq (Pvar 0) (PS (PS (PO)))) (nilc))))).\n\n(* On définit ensuite un contexte formé par les axiomes qui         *\n * permettent de paramétrer la déduction naturelle, le problème     *\n * étant que le schéma d'induction et le tiers exclu (pour le cas   * \n * de la logique classique) ne peuvent être ajoutés à ce contexte   *)\n\nDefinition HAxioms : Ctxt :=\n  assume succ_is_non_zero (assume non_zero_has_succ (assume eq_succ_implies_eq (assume zero_is_neutral (assume succ_can_extend (assume zero_absorbs (assume times_distributes (nilc))))))).\n\n\n\n(* Dans cette section on définit la fonction de réflection.         *\n * Cette fonction est en fait divisée en trois :                    *\n *   -- une réflection pour les entiers de Peano de type Pnat;      *\n *   -- une réflection pour les proposition de Peano de type Pprop; *\n *   -- une réflection sur les contextes de type Ctxt.              *\n * On va également paramétrer la fonction de réflection par une     *\n * interprétation des variables (de type var), qui prend la forme   *\n * d'une liste de naturels (de type nat). La fonction var_to_nat    *\n * permet alors de retourner l'interprétation de la variable i en   *\n * tant que naturel.                                                *)\n\nFixpoint var_to_nat (x : var) (l : list nat) : nat :=\n  match x, l  with\n   | 0, (cons v _) => v\n   | S y, (cons _ l)  => (var_to_nat y l)\n   | _, _ => 0\n  end.\n\n\nFixpoint refl_Pnat (x : Pnat) (l : list nat) : nat :=\n  match x with\n   | PO => O\n   | PS x => S (refl_Pnat x l)\n   | plus y z => (refl_Pnat y l) + (refl_Pnat z l)\n   | times y z => (refl_Pnat y l) * (refl_Pnat z l)\n   | Pvar y => var_to_nat y l\n  end.\n\n\nFixpoint refl_Pprop (P : Pprop) (l : list nat) : Prop :=\n  match P with\n   | Pfalse => False\n   | Ptrue => True\n   | Peq x y => (refl_Pnat x l) = (refl_Pnat y l)\n   | Pfa Q => forall (x : nat), refl_Pprop Q (cons x l)\n   | Pex Q => exists (x : nat), refl_Pprop Q (cons x l)\n   | Pim Q R => (refl_Pprop Q l) -> (refl_Pprop R l)\n   | Pan Q R => (refl_Pprop Q l) /\\ (refl_Pprop R l)\n   | Por Q R => (refl_Pprop Q l) \\/ (refl_Pprop R l)\n   | dummy x => True\n  end.\n\n\nFixpoint refl_Ctxt (C : Ctxt) (l : list nat) : Prop :=\n  match C with\n    | nilc => True\n    | intc D => forall x, refl_Ctxt D (cons x l)\n    | assume P D => (refl_Pprop P l)/\\(refl_Ctxt D l)\n  end.\n\n\n(* On va tester si refl_Pprop (∀x.∃y.x = S(y) ∨ x = 0) se réduit    *\n * bien vers l’objet de type Prop forall x, exists y, x=(S y)\\/x=O  *\n * comme cela devrait être le cas selon l'énoncé                    *)\n\nEval compute in (refl_Pprop (Pfa (Pex (Por (Peq (Pvar 1) (PS (Pvar 0))) (Peq (Pvar 1) (PO))))) nil).\n\nEval compute in (refl_Pprop (Pfa (Pfa (Pim (Peq (PS (Pvar 1)) (PS (Pvar 0))) (Peq (Pvar 1) (Pvar 0)) ))) nil).\n\n(* On teste la réflection sur le contexte                           *\n * [x : nat; x = x; y : nat; y = x], qui devrait donner             *\n * forall x : nat, x = x /\\ (forall y : nat, y = x /\\ True)         *) \n\nEval compute in (refl_Ctxt (intc (assume (Peq (Pvar 0) (Pvar 0)) (intc (assume (Peq (Pvar 0) (Pvar 1)) (nilc))))) nil).\n\n\n\n(* Dans cette section on définit les règles logiques de la          *\n * déduction naturelle adaptées aux objets de type Pprop et aux     *\n * contextes de type Ctxt. La définition est 'dédoublée' en une     *\n * définition 'intuitionniste' (sans règle em) et une définition    *\n * 'classique' (avec une règle em) : c'est un peu maladroit mais je *\n * n'ai pas réussi à faire mieux malheureusement.                   *)\n\nInductive ded_nat : Ctxt -> Pprop -> Prop :=\n\n  | axiom G A : ded_nat (assume A G) A\n\n  | weak G A B : ded_nat G A -> ded_nat (assume B G) A \n\n  | impi G A B : ded_nat (assume A G) B -> ded_nat G (Pim A B) \n\n  | impe G A B : ded_nat G (Pim A B) -> ded_nat G A -> ded_nat G B \n\n  | andi G A B : ded_nat G A -> ded_nat G B -> ded_nat G (Pan A B)\n\n  | andle G A B : ded_nat G (Pan A B) -> ded_nat G A\n\n  | andre G A B : ded_nat G (Pan A B) -> ded_nat G B\n\n  | orli G A B : ded_nat G A -> ded_nat G (Por A B)\n\n  | orri G A B : ded_nat G B -> ded_nat G (Por A B)\n\n  | ore G A B C : ded_nat G (Por A B) -> ded_nat (assume A G) C -> ded_nat (assume B G) C -> ded_nat G C\n\n  | bote G A : ded_nat G Pfalse -> ded_nat G A\n\n  | topi G : ded_nat G Ptrue\n\n  | foralli G A : ded_nat (intc G) A -> ded_nat G (Pfa A)\n\n  | foralle G A t : ded_nat G (Pfa A) -> ded_nat G (A.|[t.:ids])\n\n  | existi G A t : ded_nat G (A.|[t.:ids]) -> ded_nat G (Pex A)\n\n  | existe G A C : ded_nat G (Pex A) -> ded_nat (assume A (intc G)) (C.|[ren(+1)]) -> ded_nat G C.\n\n\n\nInductive ded_nat_em : Ctxt -> Pprop -> Prop :=\n\n  | axiom_em G A : ded_nat_em (assume A G) A\n\n  | weak_em G A B : ded_nat_em G A -> ded_nat_em (assume B G) A \n\n  | impi_em G A B : ded_nat_em (assume A G) B -> ded_nat_em G (Pim A B) \n\n  | impe_em G A B : ded_nat_em G (Pim A B) -> ded_nat_em G A -> ded_nat_em G B \n\n  | andi_em G A B : ded_nat_em G A -> ded_nat_em G B -> ded_nat_em G (Pan A B)\n\n  | andle_em G A B : ded_nat_em G (Pan A B) -> ded_nat_em G A\n\n  | andre_em G A B : ded_nat_em G (Pan A B) -> ded_nat_em G B\n\n  | orli_em G A B : ded_nat_em G A -> ded_nat_em G (Por A B)\n\n  | orri_em G A B : ded_nat_em G B -> ded_nat_em G (Por A B)\n\n  | ore_em G A B C : ded_nat_em G (Por A B) -> ded_nat_em (assume A G) C -> ded_nat_em (assume B G) C -> ded_nat_em G C\n\n  | bote_em G A : ded_nat_em G Pfalse -> ded_nat_em G A\n\n  | topi_em G : ded_nat_em G Ptrue\n\n  | foralli_em G A : ded_nat_em (intc G) A -> ded_nat_em G (Pfa A)\n\n  | foralle_em G A t : ded_nat_em G (Pfa A) -> ded_nat_em G (A.|[t.:ids])\n\n  | existi_em G A t : ded_nat_em G (A.|[t.:ids]) -> ded_nat_em G (Pex A)\n\n  | existe_em G A C : ded_nat_em G (Pex A) -> ded_nat_em (assume A (intc G)) (C.|[ren(+1)]) -> ded_nat_em G C\n\n  | em G A : ded_nat_em G (Por A (Pno A)).\n\n\n(* 4.2 Questions : implémentation                                   *\n * On demande, dans un premier temps d’écrire en Coq les fonctions  *\n * de réflection. Ensuite, de prouver que s’il existe une           *\n * dérivation dans l’arithmétique de Peano intuitionniste d’une     *\n * formule P dans un contexte Γ, alors, il existe un terme Coq de   *\n * type tr(Γ) → tr(P). C’est cette dernière étape qui constitue la  *\n * réflection proprement dite.                                      *)\n\n(* On peut commencer par prouver que les axiomes de l'arithmétique  *\n * de Peano définis ci-dessus sont prouvables dans Coq.             *)\n\n\nTheorem succ_is_non_zero_is_provable : refl_Pprop succ_is_non_zero nil.\nProof.\nsimpl refl_Pprop; apply PeanoNat.Nat.neq_succ_0.\nQed.\n\nTheorem eq_succ_implies_eq_is_provable : refl_Pprop eq_succ_implies_eq nil.\nProof.\nsimpl refl_Pprop; apply PeanoNat.Nat.succ_inj.\nQed.\n\nTheorem zero_is_neutral_is_provable : refl_Pprop zero_is_neutral nil.\nProof.\nsimpl refl_Pprop; apply PeanoNat.Nat.add_0_r.\nQed.\n\nTheorem succ_can_extend_is_provable : refl_Pprop succ_can_extend nil.\nProof.\nsimpl refl_Pprop; trivial.\nQed.\n\nTheorem zero_absorbs_is_provable : refl_Pprop zero_absorbs nil.\nProof.\nsimpl refl_Pprop; apply PeanoNat.Nat.mul_0_r.\nQed.\n\nTheorem times_distributes_is_provable : refl_Pprop times_distributes nil.\nProof.\nsimpl refl_Pprop; apply PeanoNat.Nat.mul_succ_r.\nQed.\n\n(*\n\nTheorem recurrence_scheme_is_provable : forall P : Pprop, (refl_Pprop (recurrence_scheme P) nil).\nProof.\nintros.\nsimpl refl_Pprop.\nintros.\nrevert.\n\n*)\n\nTheorem reflection (G : Ctxt) (P : Pprop): ded_nat G P -> (refl_Ctxt G nil) -> (refl_Pprop P nil).\nProof.\ninduction 1.\n- simpl; intros; destruct H; trivial.\n- simpl; intros; destruct H0; apply IHded_nat; trivial.\n- simpl; intros; apply IHded_nat; simpl; refine (conj _ _); trivial.\n- intros; simpl refl_Pprop in IHded_nat1; apply IHded_nat1; trivial; apply IHded_nat2; trivial.\n- simpl; intros; refine (conj _ _).\n  -- apply IHded_nat1; trivial.\n  -- apply IHded_nat2; trivial.\n- intros; simpl refl_Pprop in IHded_nat; apply IHded_nat; trivial.\n- intros; simpl refl_Pprop in IHded_nat; apply IHded_nat; trivial.\n- simpl; intros; left; apply IHded_nat; trivial.\n- simpl; intros; right; apply IHded_nat; trivial.\n- intros; simpl refl_Pprop in IHded_nat1.\n  simpl refl_Ctxt in IHded_nat2; simpl refl_Ctxt in IHded_nat3.\n  pose (H3 := IHded_nat1 H2); case H3.\n  -- intros; apply IHded_nat2; refine (conj _ _).\n     --- trivial.\n     --- trivial.\n  -- intros; apply IHded_nat3; refine (conj _ _).\n     --- trivial.\n     --- trivial.\n- intros; simpl refl_Pprop in IHded_nat; pose (H1 := IHded_nat H0); case H1.\n- simpl; intros; exact I.\n- simpl.\n intros; simpl refl_Ctxt in IHded_nat.\n\nAdmitted.\n\n(* La preuve du théorème de reflection permettrait de montrer que   *\n * tout ce qui est prouvable dans notre formalisme intuitionniste   *\n * est aussi prouvable dans Coq, autrement dit que notre formalisme *\n * est consistant avec Coq.                                         *)\n\n\n(* Dans cette section on définit la traduction de Friedman pour les *\n * propriétés et les contextes.                                     *)\n\nFixpoint Friedman (P : Pprop) (A : Pprop) : Pprop :=\n  match P with\n    | Pfalse => Por Pfalse A\n    | Ptrue => Ptrue\n    | Peq x y => Por (Peq x y) A\n    | Pfa B => Pfa (Pim (Pim (Friedman B A) A) A)\n    | Pex B => Pim (Pim (Pex (Friedman B A)) A) A\n    | Pim B C => Pim (Pim (Pim (Friedman B A) A) A) (Pim (Pim (Friedman C A) A) A)\n    | Pan B C => Pan (Pim (Pim (Friedman B A) A) A) (Pim (Pim (Friedman C A) A) A)\n    | Por B C => Por (Pim (Pim (Friedman B A) A) A) (Pim (Pim (Friedman C A) A) A)\n    | dummy x => Por (dummy x) A \n  end.\n\nFixpoint Friedman_ctxt (C : Ctxt) (A : Pprop) :=\n  match C with\n    | nilc => nilc\n    | intc D => Friedman_ctxt D A\n    | assume P D => assume (Friedman P A) (Friedman_ctxt D A)\n  end.\n\n\n\n(* Lemme 1: On étend, de manière triviale, la transformée par double*\n * négation aux contextes. S’il existe une dérivation de Γ t P dans *\n * l’arithmétique de Peano, il existe une dérivation de             *\n * Γ^A t ¬^A ¬^A P^A dans l’arithmétique de Heyting.                *)  \n\nLemma Peano_Heyting (P : Pprop) (C : Ctxt) (A : Pprop) : (ded_nat_em C P ) -> ded_nat (Friedman_ctxt C A) (Pim (Pim (Friedman P A) A) A).\nProof.\ninduction 1.\n- simpl.\n  apply (impi ((assume (Friedman A0 A) (Friedman_ctxt G A))) ((Pim (Friedman A0 A) A)) (A)).\n  apply (impe (assume (Pim (Friedman A0 A) A) (assume (Friedman A0 A) (Friedman_ctxt G A))) (Friedman A0 A) A).\n -- apply (axiom (assume (Friedman A0 A) (Friedman_ctxt G A)) (Pim (Friedman A0 A) A)).\n -- apply (weak ((assume (Friedman A0 A) (Friedman_ctxt G A))) ((Friedman A0 A)) ((Pim (Friedman A0 A) A))).\n    apply (axiom ((Friedman_ctxt G A)) ((Friedman A0 A))).\n- simpl.\n  apply (impi ((assume (Friedman B A) (Friedman_ctxt G A))) ((Pim (Friedman A0 A) A)) (A)).\n  admit.\n- simpl.\nadmit.\n- simpl.\n  apply (impi ((Friedman_ctxt G A)) (Pim (Friedman B A) A) A).\n  apply (impe ((assume (Pim (Friedman B A) A) (Friedman_ctxt G A))) (Friedman B A) (A)).\n  -- apply (axiom ( (Friedman_ctxt G A)) ((Pim (Friedman B A) A))).\n  -- admit.\n- apply (impi ((Friedman_ctxt G A)) ((Pim (Friedman (Pan A0 B) A) A)) (A)).\n  apply (impe ((assume (Pim (Friedman (Pan A0 B) A) A)\n     (Friedman_ctxt G A))) (Friedman (Pan A0 B) A) (A)).\n  -- apply (axiom ( (Friedman_ctxt G A)) ((Pim (Friedman (Pan A0 B) A) A))).\n  -- simpl Friedman.\n     apply (andi ((assume (Pim (Pan (Pim (Pim (Friedman A0 A) A) A) (Pim (Pim (Friedman B A) A) A)) A) (Friedman_ctxt G A))) ((Pim (Pim (Friedman A0 A) A) A)) ((Pim (Pim (Friedman B A) A) A))).\n     --- apply (impi ((assume (Pim (Pan (Pim (Pim (Friedman A0 A) A) A) (Pim (Pim (Friedman B A) A) A)) A) (Friedman_ctxt G A))) ((Pim (Friedman A0 A) A)) (A)).\n         apply (impe ((assume (Pim (Friedman A0 A) A) (assume (Pim (Pan (Pim (Pim (Friedman A0 A) A) A) (Pim (Pim (Friedman B A) A) A)) A) (Friedman_ctxt G A)))) (A0) (A)).   \n         ----- \n(* Lemme 2 : Les formules sans quantificateurs sont décidables      *\n * (en particulier dans Coq).                                       *)\n\n(* On définit d'abord une fonction qui détermine si une formule     *\n * contient ou non des quantifieurs :                               *)\n\nFixpoint not_quant (P : Pprop) : Prop :=\n  match P with\n    | Pfalse => True\n    | Ptrue => True\n    | Peq x y => True\n    | Pfa B => False\n    | Pex B => False\n    | Pim B C => (not_quant B) /\\ (not_quant C)\n    | Pan B C => (not_quant B) /\\ (not_quant C)\n    | Por B C => (not_quant B) /\\ (not_quant C)\n    | dummy x => True\n  end.\n\n\nLemma not_quant_decidable (P : Pprop) (A : Pprop) : not_quant P -> (refl_Pprop (Friedman P A) nil) \\/ (refl_Pprop (Pno (Friedman P A)) nil).\nProof.\ninduction P, A; simpl refl_Pprop.\n- right.\nright.\n\n\n\n(* Lemme 3 : Soit P une formule sans quantificateurs. On a, dans    * \n * Coq, P^A ⇐⇒ P ∨ A.                                               *)\n\nLemma Friedman_equiv_A_disj (P : Pprop) (A : Pprop) : (not_quant P) -> ((Friedman P A -> Por P A) /\\ (Por P A -> Friedman P A)).\n\n\n\n\n", "meta": {"author": "AdeleMortier", "repo": "coq_arithmetic", "sha": "4ed8895e317281d8fe43588a9ba5b013289b29b9", "save_path": "github-repos/coq/AdeleMortier-coq_arithmetic", "path": "github-repos/coq/AdeleMortier-coq_arithmetic/coq_arithmetic-4ed8895e317281d8fe43588a9ba5b013289b29b9/proj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.676134411681907}}
{"text": "Set Implicit Arguments.\n\nRequire Import\n        Discrete.DiscType\n        Discrete.Filter\n        Discrete.In\n        Discrete.Inclusion\n        Tactics.Tactics.\n\nSection REM.\n  Variable A : discType.\n  Context {eq_A_dec : eq_dec A}.\n\n  Definition rem (xs : list A) x :=\n    filter (fun y => y <> x) xs.\n\n  Lemma In_rem_iff x xs y :\n    x el rem xs y <-> x el xs /\\ x <> y.\n  Proof.\n    apply In_filter_iff.\n  Qed.\n\n  Lemma rem_not_in x y xs :\n    x = y \\/ ~ x el xs -> ~ x el rem xs y.\n  Proof.\n    intros D E. apply In_rem_iff in E. tauto.\n  Qed.\n\n  Lemma rem_incl xs x :\n    rem xs x <<= xs.\n  Proof.\n    apply filter_incl.\n  Qed.\n\n  Lemma rem_mono xs ys x :\n    xs <<= ys -> rem xs x <<= rem ys x.\n  Proof.\n    apply filter_mono.\n  Qed.\n\n  Lemma rem_cons xs ys x :\n    xs <<= ys -> rem (x :: xs) x <<= ys.\n  Proof.\n    intros E y F. apply E. apply In_rem_iff in F.\n    destruct F as [[|]]; congruence.\n  Qed.\n\n  Hint Resolve rem_cons.\n\n  Lemma rem_cons' xs ys x y :\n    x el ys -> rem xs y <<= ys -> rem (x :: xs) y <<= ys.\n  Proof.\n    intros E F u G.\n    apply In_rem_iff in G. crush.\n    apply F. apply In_rem_iff. splits*. \n  Qed.\n\n  Lemma rem_in x y xs :\n    x el rem xs y -> x el xs.\n  Proof.\n    apply rem_incl.\n  Qed.\n\n  Lemma rem_neq x y xs :\n    x <> y -> x el xs -> x el rem xs y.\n  Proof.\n    intros E F. apply In_rem_iff. auto.\n  Qed.\n\n  Hint Resolve rem_in rem_neq.\n\n  Lemma rem_app x xs ys :\n    x el xs -> ys <<= xs ++ rem ys x.\n  Proof.\n    intros E y F. decide (x=y) as [[]|] ;\n      try apply In_app_iff ; crush.\n  Qed.\n\n  Lemma rem_app' x xs ys zs :\n    rem xs x <<= zs -> rem ys x <<= zs -> rem (xs ++ ys) x <<= zs.\n  Proof.\n    unfold rem ; rewrite filter_app ; auto.\n  Qed.\n\n  Lemma rem_equi x xs :\n    x :: xs === x :: rem xs x.\n  Proof.\n    split ; intros y; \n    intros [[]|E] ; decide (x=y) as [[]|D] ; crush ; eauto.\n  Qed.\n\n  Lemma rem_comm xs x y :\n    rem (rem xs x) y = rem (rem xs y) x.\n  Proof.\n    apply filter_comm.\n  Qed.\n\n  Lemma rem_fst x xs :\n    rem (x :: xs) x = rem xs x.\n  Proof.\n    unfold rem. rewrite filter_fst'; auto.\n  Qed.\n\n  Lemma rem_fst' x y xs :\n    x <> y -> rem (x :: xs) y = x :: rem xs y.\n  Proof.\n    intros E. unfold rem. rewrite filter_fst ; auto.\n  Qed.\n\n  Lemma rem_id x xs :\n    ~ x el xs -> rem xs x = xs.\n  Proof.\n    intros D. apply filter_id.\n    intros y E F. subst. auto.\n  Qed.\n\n  Lemma rem_reorder x xs :\n    x el xs -> xs === x :: rem xs x.\n  Proof.\n    intros D. rewrite <- rem_equi. apply equiv_push, D.\n  Qed.\n\n  Lemma rem_inclr xs ys x :\n    xs <<= ys -> ~ x el xs -> xs <<= rem ys x.\n  Proof.\n    intros D E y F. apply In_rem_iff.\n    intuition; subst; auto.\n  Qed.\nEnd REM.\n\nArguments rem {A}{eq_A_dec} xs x.\n\nHint Resolve rem_not_in rem_incl rem_mono\n     rem_cons rem_cons' rem_app rem_app' rem_in rem_neq rem_inclr.\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/Discrete/Remove.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.676134411464551}}
{"text": "\nRequire Export Iron.DiscipleKernel.TyExp.\nRequire Export Iron.DiscipleKernel.TyWfT.\n\n\n(*******************************************************************)\n(* Lift type indices that are at least a certain depth. *)\nFixpoint liftTT (n: nat) (d: nat) (tt: ty) : ty :=\n match tt with\n |  TVar ix\n => if le_gt_dec d ix\n     then TVar (ix + n)\n     else tt\n\n |  TCon _      => tt\n |  TForall k t => TForall k (liftTT n (S d) t)\n |  TApp t1 t2  => TApp      (liftTT n d t1) (liftTT n d t2)\n |  TSum t1 t2  => TSum      (liftTT n d t1) (liftTT n d t2)\n |  TBot k      => TBot k\n end.\nHint Unfold liftTT.\n\n\n(********************************************************************)\n(* Lifting and well-formedness *)\nLemma liftTT_wfT\n :  forall kn t d\n ,  wfT kn t\n -> wfT (S kn) (liftTT 1 d t).\nProof.\n intros. gen kn d.\n lift_burn t; inverts H; try burn.\n \n Case \"TVar\".\n  repeat (simpl; lift_cases).\n   eapply WfT_TVar. burn.\n   eapply WfT_TVar. burn.\nQed.\nHint Resolve liftTT_wfT.\n\n\n(********************************************************************)\nLemma liftTT_zero\n :  forall d t\n ,  liftTT 0 d t = t.\nProof.\n intros. gen d. lift_burn t.\nQed.\nHint Rewrite liftTT_zero : global.\n\n\nLemma liftTT_comm\n :  forall n m d t\n ,  liftTT n d (liftTT m d t)\n =  liftTT m d (liftTT n d t).\nProof.\n intros. gen d. lift_burn t.\nQed.\n\n\nLemma liftTT_succ\n :  forall n m d t\n ,  liftTT (S n) d (liftTT m     d t)\n =  liftTT n     d (liftTT (S m) d t).\nProof.\n intros. gen d m n. lift_burn t.\nQed.\nHint Rewrite liftTT_succ : global. \n\n\nLemma liftTT_plus\n : forall n m d t\n , liftTT n d (liftTT m d t) = liftTT (n + m) d t.\nProof.\n intros. gen n d.\n induction m; intros.\n rewrite liftTT_zero; burn.\n\n rw (n + S m = S n + m). \n  rewrite liftTT_comm.\n  rewrite <- IHm.\n  rewrite liftTT_comm.\n  burn.\nQed. \nHint Rewrite <- liftTT_plus : global.\n\n\n(******************************************************************************)\nLemma liftTT_wfT_1\n :  forall t n ix\n ,  wfT n t\n -> liftTT 1 (n + ix) t = t.\nProof.\n intros. gen n ix.\n induction t; intros; inverts H; simpl; auto.\n\n  Case \"TVar\".\n   lift_cases; burn.\n\n  Case \"TForall\".\n   f_equal. spec IHt H1.\n   rw (S (n + ix) = S n + ix).\n   burn.\n\n  Case \"TApp\".\n   rs. burn.\n\n  Case \"TSum\".\n   rs. burn.\nQed.\nHint Resolve liftTT_wfT_1.\n\n\nLemma liftTT_closedT_id_1\n :  forall t d\n ,  closedT t\n -> liftTT 1 d t = t.\nProof.\n intros.\n rw (d = d + 0). eauto.\nQed.\nHint Resolve liftTT_closedT_id_1.\n\n\nLemma liftTT_closedT_10\n :  forall t\n ,  closedT t\n -> closedT (liftTT 1 0 t).\nProof.\n intros. red.\n rw (0 = 0 + 0).\n rewrite liftTT_wfT_1; auto.\nQed.\nHint Resolve liftTT_closedT_10.\n\n\n(********************************************************************)\n(* Changing the order of lifting.\n   We build this up in stages. \n   Start out by only allow lifting by a single place for both\n   applications. Then allow lifting by multiple places in the first\n   application, then multiple places in both. \n*)\nLemma liftTT_liftTT_11\n :  forall d d' t\n ,  liftTT 1 d              (liftTT 1 (d + d') t) \n =  liftTT 1 (1 + (d + d')) (liftTT 1 d t).\nProof.\n intros. gen d d'.\n induction t; intros; simpl; try burn.\n\n Case \"TVar\".\n  repeat (lift_cases; unfold liftTT); burn.\n\n Case \"TForall\".\n  rw (S (d + d') = (S d) + d').\n  burn.\nQed.\n\n\nLemma liftTT_liftTT_1\n :  forall n1 m1 n2 t\n ,  liftTT m1   n1 (liftTT 1 (n2 + n1) t)\n =  liftTT 1 (m1 + n2 + n1) (liftTT m1 n1 t).\nProof.\n intros. gen n1 m1 n2 t.\n induction m1; intros; simpl.\n  burn. \n\n  rw (S m1 = 1 + m1).\n  rewrite <- liftTT_plus.\n  rs.\n  rw (m1 + n2 + n1 = n1 + (m1 + n2)).\n  rewrite liftTT_liftTT_11.\n  burn.\nQed.\n\n\nLemma liftTT_liftTT\n :  forall m1 n1 m2 n2 t\n ,  liftTT m1 n1 (liftTT m2 (n2 + n1) t)\n =  liftTT m2 (m1 + n2 + n1) (liftTT m1 n1 t).\nProof.\n intros. gen n1 m1 n2 t.\n induction m2; intros.\n  burn.\n\n  rw (S m2 = 1 + m2).\n  rewrite <- liftTT_plus.\n  rewrite liftTT_liftTT_1.\n  rewrite IHm2.\n  burn.\nQed.\nHint Rewrite liftTT_liftTT : global.\n\n\nLemma liftTT_map_liftTT\n :  forall m1 n1 m2 n2 ts\n ,  map (liftTT m1 n1) (map (liftTT m2 (n2 + n1)) ts)\n =  map (liftTT m2 (m1 + n2 + n1)) (map (liftTT m1 n1) ts).\nProof.\n induction ts; simpl; burn.\nQed.  \n\n", "meta": {"author": "Warbo", "repo": "iron", "sha": "69997b162a52e07456562d00908ef4791b47a15a", "save_path": "github-repos/coq/Warbo-iron", "path": "github-repos/coq/Warbo-iron/iron-69997b162a52e07456562d00908ef4791b47a15a/devel/Iron/DiscipleKernel/TyLift.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6761344088119567}}
{"text": "From Undecidability.Synthetic Require Import DecidabilityFacts EnumerabilityFacts ListEnumerabilityFacts.\nFrom Undecidability.Shared Require Import Dec.\n\nRequire Import List.\nImport ListNotations.\n\nLemma enumerable_enum {X} {p : X -> Prop} :\n  enumerable p <-> list_enumerable p.\nProof.\n  split. eapply enumerable_list_enumerable. eapply list_enumerable_enumerable.\nQed.\n\n\n\nLemma enumerable_disj X (p q : X -> Prop) :\n  enumerable p -> enumerable q -> enumerable (fun x => p x \\/ q x).\nProof.\n  intros [Lp H] % enumerable_enum [Lq H0] % enumerable_enum.\n  eapply enumerable_enum.\n  exists (fix f n := match n with 0 => [] | S n => f n ++ (Lp n) ++ (Lq n) end).\n  intros x. split.\n  - intros [H1 | H1].\n    * eapply H in H1 as [m]. exists (1 + m). cbn.\n      apply in_or_app. right. apply in_or_app. now left.\n    * eapply H0 in H1 as [m]. exists (1 + m). cbn.\n      apply in_or_app. right. apply in_or_app. now right.\n  - intros [m]. induction m.\n    * inversion H1.\n    * apply in_app_iff in H1.\n      destruct H1 as [?|H1]; [now auto|].\n      apply in_app_iff in H1.\n      unfold list_enumerator in *; firstorder easy.\nQed.\n\nLemma enumerable_conj X (p q : X -> Prop) :\n  discrete X -> enumerable p -> enumerable q -> enumerable (fun x => p x /\\ q x).\nProof.\n  intros [] % discrete_iff [Lp] % enumerable_enum [Lq] % enumerable_enum.\n  eapply enumerable_enum.\n  exists (fix f n := match n with 0 => [] | S n => f n ++ (filter (fun x => Dec (In x (cumul Lq n))) (cumul Lp n)) end).\n  intros x. split.\n  + intros []. eapply (list_enumerator_to_cumul H) in H1 as [m1].\n    eapply (list_enumerator_to_cumul H0) in H2 as [m2].\n    exists (1 + m1 + m2). cbn. apply in_or_app. right.\n    apply filter_In. split.\n    * eapply cum_ge'; eauto; lia.\n    * eapply Dec_auto. eapply cum_ge'; eauto; lia.\n  + intros [m]. induction m.\n    * inversion H1.\n    * apply in_app_iff in H1. destruct H1 as [?|H1]; [now auto|].\n      apply filter_In in H1. destruct H1 as [? H1].\n      split. \n      ** eapply (list_enumerator_to_cumul H). eauto.\n      ** destruct (Dec _) in H1; [|easy].\n         eapply (list_enumerator_to_cumul H0). eauto.\nQed.\n\nLemma projection X Y (p : X * Y -> Prop) :\n  enumerable p -> enumerable (fun x => exists y, p (x,y)).\nProof.\n  intros [f].\n  exists (fun n => match f n with Some (x, y) => Some x | None => None end).\n  intros; split.\n  - intros [y ?]. eapply H in H0 as [n]. exists n. now rewrite H0.\n  - intros [n ?]. destruct (f n) as [ [] | ] eqn:E; inversion H0; subst.\n    exists y. eapply H. eauto.\nQed.\n\nLemma projection' X Y (p : X * Y -> Prop) :\n  enumerable p -> enumerable (fun y => exists x, p (x,y)).\nProof.\n  intros [f].\n  exists (fun n => match f n with Some (x, y) => Some y | None => None end).\n  intros y; split.\n  - intros [x ?]. eapply H in H0 as [n]. exists n. now rewrite H0.\n  - intros [n ?]. destruct (f n) as [ [] | ] eqn:E; inversion H0; subst.\n    exists x. eapply H. eauto.\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/Synthetic/MoreEnumerabilityFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6761344088119566}}
{"text": "Require Import List Mergesort Setoid Permutation Sorted Orders Omega.\n\nSet Implicit Arguments.\n\nFixpoint LinearSearch (A : Type)(l : list A)(f : A -> bool) : option nat := \n  match l with\n  | nil => None\n  | l_head :: l_tail =>\n      match f l_head with\n      | true => Some O\n      | false => \n          match LinearSearch l_tail f with\n          | None => None\n          | Some n => Some (S n)\n          end\n      end\n  end.\n\nTheorem SearchNoneFalse : forall A (l : list A) f, \n  LinearSearch l f = None -> \n    (forall n d, f d = false -> f (nth n l d) = false).\n  intros A l f H.\n  induction l.\n  simpl in *.\n  destruct n.\n  trivial.\n  trivial.\n  simpl in *.\n  intros.\n  remember (f a) as b.\n  destruct b.\n  inversion H.\n  destruct n.\n  auto.\n  apply IHl.\n  remember (LinearSearch l f) as R.\n  destruct R.\n  inversion H.\n  trivial.\n  trivial.\nQed.\n\nTheorem FalseSearchNone : forall A (l : list A) f d,\n  f d = false ->\n  (forall n, f (nth n l d) = false) ->\n    LinearSearch l f = None.\n  intros.\n  induction l.\n  trivial.\n  simpl.\n  assert(LinearSearch l f = None) as HR.\n  apply IHl.\n  intros.\n  remember (H0 (S n)).\n  trivial.\n  rewrite HR in *.\n  remember(H0 0).\n  simpl in *.\n  rewrite e.\n  trivial.\nQed.\n\nTheorem TrueSearchSome : forall A d f (l : list A) m,\n  f d = false -> \n    f (nth m l d) = true ->\n      (forall n, n < m -> f (nth n l d) = false) ->\n        LinearSearch l f = Some m.\n  induction l.\n  intros.\n  simpl in *.\n  destruct m;\n  rewrite H in H0;\n  inversion H0.\n  intros.\n  simpl in *.\n  destruct m.\n  rewrite H0 in *.\n  trivial.\n  assert(f a = false).\n  remember(H1 0).\n  simpl in *.\n  auto with *.\n  rewrite H2 in *.\n  assert(LinearSearch l f = Some m).\n  apply IHl.\n  trivial.\n  trivial.\n  intros.\n  remember(H1 (S n)).\n  simpl in *.\n  apply e.\n  subst.\n  auto with *.\n  rewrite H3.\n  trivial.\nQed.\n\nTheorem SomeTrueSearch : forall A d f (l : list A) m,\n  LinearSearch l f = Some m ->\n    f d = false -> \n      f (nth m l d) = true ->\n        (forall n, n < m -> f (nth n l d) = false).\n  induction l.\n  simpl in *.\n  destruct n;\n  trivial.\n  intros.\n  simpl in *.\n  destruct m.\n  omega.\n  remember (f a) as b.\n  destruct b.\n  inversion H.\n  destruct n.\n  auto.\n  remember (LinearSearch l f) as L.\n  destruct L.\n  assert(m = n0).\n  inversion H.\n  trivial.\n  subst.\n  eapply IHl.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n  inversion H.\nQed.", "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/LinearSearch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825655188238, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.6761323132973375}}
{"text": "From mathcomp Require Import ssreflect seq ssrnat ssrbool eqtype ssrfun choice.\nFrom mf Require Import all_mf.\nRequire Import Morphisms.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nNotation \"L '\\is_sublist_of' K\" := (List.incl L K) (at level 2).\n\nSection sublists.\nContext (T: Type).\n\nLemma subl_refl: Reflexive (@List.incl T).\nProof. by move => L t. Qed.\n\nLemma subl_trans: Transitive (@List.incl T).\nProof. by move => L K M subl subl' t lstn; apply/subl'/subl. Qed.\n\nLemma subl0 (L: seq T): L \\is_sublist_of [::] -> L = [::].\nProof. by elim: L => // t L ih subl; have []:= subl t; left. Qed.\n\nLemma drop_subl (L : seq T) n: (drop n L) \\is_sublist_of L.\nProof.\nelim: n => [ | n ih]; first by rewrite drop0.\nrewrite -add1n -drop_drop drop1 => t lstn.\nby apply/ih; case: (drop n L) lstn => //; right.\nQed.\n\nLemma lstn_app (L K: seq T)t: List.In t (L ++ K) <-> List.In t L \\/ List.In t K.\nProof.\nsplit; last by have:= List.in_or_app L K t.\nelim: L => [ | l L ihL /= [eq | lstn]]; [ | left; left | ] => //.\n- by elim: K => // l K ihK /= [eq | lstn]; [right; left | right; right].\nby case: (ihL lstn); [ left; right | right ].\nQed.\nEnd sublists.\n\nLemma lstn_flatten T (Ln: seq (seq T)) t:\n  List.In t (flatten Ln) <-> exists L, List.In t L /\\ List.In L Ln.\nProof.\nsplit.\n- elim: Ln => [| L Ln ih /=]// /lstn_app [lstn | lstn]; first by exists L; split => //; left.\n  by have [K []] := ih lstn; exists K; split => //; right.\nelim: Ln => [[L []] | L Ln ih [K [lstn /=[-> | lstn']]]]//; apply/lstn_app; first by left.\nby right; apply/ih; exists K.\nQed.\n\nLemma flatten_subl T (Ln Kn: seq (seq T)):\n  Ln \\is_sublist_of Kn -> (flatten Ln) \\is_sublist_of (flatten Kn).\nProof.\nmove => subl t /lstn_flatten [L [lstn lstn']].\nby rewrite lstn_flatten; exists L; split; last apply subl.\nQed.\n\n\nSection initial_segments.\n  Context (Q: Type) (cnt: nat -> Q).\n\n  Fixpoint segment_rec n m {struct m} :=\n    match m with\n    | 0 => [::]\n    | S m' => [:: cnt (n + m') & segment_rec n m']\n    end.\n  \n  Lemma size_seg_rec n m: size (segment_rec n m) = m.\n  Proof. by elim: m => // m /= ->. Qed.\n\n  Definition segment n m := segment_rec n (m.+1-n).\n\n  Lemma size_seg n m: size (segment n m) = m.+1-n.\n  Proof. by rewrite /segment; apply size_seg_rec. Qed.\n\n  Lemma seg_recr n m : n <= m.+1 ->\n\t               segment n m.+1 = segment m.+1 m.+1 ++ segment n m.\n  Proof. by move => ineq; rewrite /segment (@subSn (m.+1)) // subSn// subnn /= addn0 subnKC. Qed.\n\n  Lemma seg_recl n m: n <= m -> segment n m = segment n.+1 m ++ segment n n.\n  Proof.\n    move => ineq; rewrite /segment subnS subSn//= subSn // subnn/= addn0.\n    by elim: (m - n) => [ | k ih]; [rewrite addn0 | rewrite /= ih addSn addnS].\n  Qed.\n\n  Lemma cat_seg n k m:\n    segment (n + k).+1 ((n + k).+1 + m) ++ segment n (n + k)\n    = segment n ((n + k).+1 + m).\n  Proof.\n    elim: k => [ | k /= ih].\n    - rewrite !addn0 (@seg_recl n (n.+1 + m)) //.\n      by rewrite addSn; apply /leqW/leq_addr.\n      rewrite -addnS in ih; rewrite /=addSn (@seg_recr n (n + k.+1 + m)); last first.\n    - by apply/leqW; rewrite -addnA; apply/leq_addr.\n    rewrite -ih catA -(@seg_recr (n + k.+1) (n + k.+1 + m)); last first.\n    - by apply/leqW/leq_addr.\n    rewrite (@seg_recl (n + k.+1)); last by apply/leqW/leq_addr.\n    by rewrite -catA addnS -(@seg_recr n)//; last by apply/leqW/leq_addr.\n  Qed.\n\n  Fixpoint iseg n:=\n    match n with\n    | 0 => nil\n    | S n' => [:: cnt n' & iseg n']\n    end.\n  \n  Lemma iseg_seg n: iseg n.+1 = segment 0 n.\n  Proof. by rewrite /segment; elim: n => // n; rewrite /= !add0n => ->. Qed.\n  \n  Lemma iseg_cat_seg n k: n.+1 < k -> segment n.+1 k.-1 ++ iseg n.+1 = iseg k.\n  Proof.\n    case: k => //; case => //k ineq; rewrite iseg_seg.\n    have:= cat_seg 0 n (k - n); rewrite !add0n.\n    by rewrite addSn subnKC // iseg_seg.\n  Qed.\n\n  Lemma size_iseg n: size (iseg n) = n.\n  Proof. by elim: n => // n /= ->. Qed.\n\n  Lemma iseg_subl n m:\n    n <= m -> (iseg n) \\is_sublist_of (iseg m).\n  Proof.\n    elim: m => [ | m ih]; first by rewrite leqn0 => /eqP ->.\n    by rewrite leq_eqVlt; case/orP => [/eqP -> | ] //=; right; apply/ih.\n  Qed.\n\n  Lemma iseg_ex a n: List.In a (iseg n) -> exists m, m < n /\\ cnt m = a.\n  Proof.\n    elim: n => // n ih/=; case => [ | lstn]; first by exists n.\n    by have [m []]:= ih lstn; exists m; split => //; rewrite leqW.\n  Qed.\n\n  Lemma drop_iseg k m: drop k (iseg m) = iseg (m - k).\n  Proof.\n    move: {2}k (leqnn k) => l.\n    elim: l k m => [k m | n ih k m].\n    - by rewrite leqn0 => /eqP ->; rewrite drop0 subn0.\n    rewrite leq_eqVlt; case/orP => [/eqP ->| ]; last exact/ih.\n    rewrite -addn1 addnC -drop_drop ih//.\n    case: n ih => [ih | n ih]; last by rewrite ih // addSn add0n !subnS subn0.\n    by rewrite subn0 addn0; elim: (m) => //m' ihm /=; rewrite drop0 subn1.\n  Qed.\n\n  Lemma nth_iseg n m: nth (cnt 0) (iseg m) n = cnt (m - n).-1.\n  Proof. by rewrite -{1}(addn0 n) -nth_drop drop_iseg; elim: (m - n). Qed.\n\n  Context (sec: Q -> nat).\n  Fixpoint max_elt K :=\n    match K with\n    | nil => 0\n    | cons q K' => maxn (sec (q: Q)).+1 (max_elt K')\n    end.\n\n  Lemma melt_app L K:\n    max_elt (L ++ K) = maxn (max_elt L) (max_elt K).\n  Proof. by elim: L K; [move => K; rewrite max0n | intros; rewrite /= (H K) maxnA]. Qed.\n\n  Definition pickle_min:= forall n, max_elt (iseg n) <= n.\n  \n  Lemma lstn_melt K a: List.In a K -> sec a < max_elt K.\n  Proof.\n    elim: K a => // a K ih a'/=.\n    by case => [<- | lstn]; apply/leq_trans; [|exact: leq_maxl|apply ih|exact: leq_maxr].\n  Qed.\n\n  Lemma melt_subl L K:\n    L \\is_sublist_of K -> max_elt L <= max_elt K.\n  Proof.\n    elim: L => //a L ih /=subl.\n    case/orP: (leq_total (sec a).+1 (max_elt L)) => [/maxn_idPr -> | /maxn_idPl ->].\n    - by apply/ih => q lstn; apply/subl; right.\n    by apply/lstn_melt/subl; left.\n  Qed.\n\n  Lemma lstn_iseg_S a: cancel sec cnt -> List.In a (iseg (sec a).+1).\n  Proof. by move => cncl; left. Qed.\n\n  Lemma lstn_iseg q m:\n    List.In q (iseg m) <-> exists n, n < m /\\ cnt n = q. \n  Proof.\n    split => [ | [n []]]; first exact/iseg_ex; elim: m => // m ih.\n    by rewrite leq_eqVlt; case/orP => [/eqP [<-]| ]; [left | right; apply/ih].\n  Qed.\n\n  Definition minimal_section Q (cnt: nat -> Q) (sec : Q -> nat) :=\n    cancel sec cnt /\\ forall s,(forall m, cnt m = s -> sec s <= m).\n\n  Lemma iseg_base a n: minimal_section cnt sec -> List.In a (iseg n) -> sec a < n.\n  Proof.\n    move => [cncl min]; elim: n => // n ih/=.\n    by case => [<- | lstn]; [apply/min | rewrite leqW//; apply/ih].\n  Qed.\n\n  Lemma melt_iseg n : minimal_section cnt sec -> max_elt (iseg n) <= n.\n  Proof.\n    move => [cncl min]; elim: n => // n ih /=.\n    by rewrite geq_max; apply/andP; split; [apply/min | rewrite leqW].\n  Qed.\n\n  Lemma iseg_melt K: minimal_section cnt sec -> K \\is_sublist_of (iseg (max_elt K)).\n  Proof. by move => [cncl min] q lstn; apply/iseg_subl/lstn_iseg_S/cncl/lstn_melt. Qed.\nEnd initial_segments.\n\nRequire Import Psatz.\n\nSection naturals.\n  Lemma seg_iota n k: segment id n (n + k) = rev (iota n k.+1).\n  Proof.\n    elim: k n => [n | k ih n]; first by rewrite addn0 /segment /= subSn // subnn /= addn0 /rev /=.\n    rewrite seg_recl; last exact/leq_addr.\n    have ->: rev (iota n k.+2) = rev (iota n.+1 k.+1) ++ [:: n] by rewrite /rev /= -catrev_catr /=.\n    rewrite -ih addSn addnS; f_equal.\n    by rewrite /segment subSn // subnn /= addn0.\n  Qed.\n\n  Lemma seg_map Q (cnt: nat -> Q) n k: segment cnt n (n + k) = map cnt (segment id n (n + k)).\n  Proof.\n    elim: k => [ | k].\n    by rewrite /segment subSn addn0// subnn /=.\n    rewrite addnS/segment => ih.\n    rewrite subSn /=; first by f_equal; rewrite ih.\n    rewrite -addnS.\n    exact/leq_addr.\n  Qed.\n\n  Definition init_seg:= iseg id.\n\n  Lemma iseg_iota n: init_seg n = rev (iota 0 n).\n  Proof. by case: n => //n; rewrite /init_seg iseg_seg seg_iota. Qed.\n    \n  Lemma iseg_eq T (cnt cnt':nat -> T) n:\n    iseg cnt n = iseg cnt' n <-> (forall i, i< n -> cnt i = cnt' i). \n  Proof.\n    split.\n    elim: n => // n ih /= [eq eq'] i.\n      by rewrite leq_eqVlt; case/orP => [/eqP [->] | ]; last exact/ih.\n    elim: n => // n ih prp /=.\n    rewrite ih => [ | i ineq]; first f_equal; apply/prp => //.\n    exact/leqW.\n  Qed.\n\n  \n  (* Most code from this section was provided by Vincent *)\n  Context (p: nat -> bool).\n\n  Let Fixpoint searchU m k : nat :=\n    match k with\n    | 0 => m\n    | k'.+1 => let n := m - k in if p n then n else searchU m k'\n    end.\n\n  Lemma searchUS m k: k<= m ->\n    searchU m.+1 k.+1 = if searchU m k != m then searchU m k else\n                          if p m then m else m.+1.\n  Proof.\n    rewrite /= subSS.\n    elim: k => [ | k ih klm]; first by rewrite /= subn0; have ->: m != m = false by apply/eqP.\n    rewrite /=.\n    case: ifP; first by case: ifP => // /eqP -> ->.\n    rewrite subSS ih.\n    case: ifP => //.\n    by apply/leq_trans/klm.\n  Qed.\n    \n  Let searchU_find m k: k <= m ->\n    searchU m k = if has p (iota (m - k) k) then find p (iota (m - k) k) + (m - k) else m.\n  Proof.\n    elim: k => // k ih ineq.    \n    rewrite [LHS]/= ih; last exact/leq_trans/ineq.\n    case: ifP => [pmk | ].\n    - case: ifP => [_ | ]//; first by rewrite /= pmk add0n.\n      rewrite /= => /orP neg.\n      by exfalso; apply/neg; left.\n    move => pmk.\n    rewrite /= subnSK //.\n    case: ifP => hs.\n    - case: ifP => [_ | /orP neg]; last by exfalso; apply/neg; right.\n      by rewrite pmk addSn -addnS subnSK//.\n    by case: ifP => // /orP; first by rewrite pmk; case.\n  Qed.\n    \n  Let searchU_correct m k :\n    p m -> p (searchU m k).\n  Proof.\n    move => hm.\n    by elim: k => // n ih /=; case: ifP.\n  Qed.\n    \n  Let searchU_le m k :\n    searchU m k <= m.\n  Proof.\n    elim: k => // n ih /=; case: ifP => // _.\n    rewrite /subn /subn_rec; apply /leP; lia.\n  Qed.    \n    \n  Let searchU_minimal m k :\n    (forall n, p n -> m - k <= n) -> forall n, p n -> searchU m k <= n.\n  Proof.\n    elim: k.\n    - move => h n /=; rewrite -(subn0 m); exact: h.\n      move => k ih h n /=; case: ifP.\n    - move => _; exact: h.\n      move => hk; apply: ih => i hi.\n      case: (i =P m - k.+1).\n      move => eq.\n      rewrite -eq in hk.\n      by rewrite hk in hi.\n    move: (h i hi).\n    by rewrite /subn /subn_rec => /leP prp cnd; apply/leP; lia.\n  Qed.\n\n  Let searchU_fail m k:\n    (forall n, p n -> m < n) -> searchU m k = m.\n  Proof.\n    elim: k => //k ih prp /=.\n    case: ifP => [pm | neg]; last exact/ih/prp.\n    have:= prp (m-k.+1) pm.\n    by rewrite ltn_subRL -{2}(add0n m) ltn_add2r.\n  Qed.\n    \n  Definition search n := searchU n n.\n\n  Lemma search_correct n: p n -> p (search n).\n  Proof. exact: searchU_correct. Qed.\n    \n  Lemma search_le n: search n <= n.\n  Proof. exact: searchU_le. Qed.\n\n  Lemma search_min n m:\tp m -> search n <= m.\n  Proof.\n    apply searchU_minimal => k pk.\n    by rewrite /subn/subn_rec; apply/leP; lia.\n  Qed.\n    \n  Lemma worder_nat:\n    (exists n, p n) -> exists n, p n /\\ forall m, p m -> n <= m.\n  Proof.\n    move => [m pm].\n    exists (search m ).\n    split; first exact: search_correct.\n    exact: search_min.\n  Qed.\n\n  Lemma not_has_find T q (s: seq T): ~~ has q s -> find q s = size s.\n  Proof.\n    rewrite has_find => ass.\n    suff /leP ineq: size s <= find q s by have /leP ineq':= find_size q s; lia.\n    by rewrite leqNgt.\n  Qed.\n\n  Lemma search_find n: search n = find p (iota 0 n).\n  Proof.\n    rewrite /search searchU_find; last exact/leqnn.\n    rewrite subnn addn0; case: ifP => //.\n    elim: n => // n ih neg.    \n    by rewrite not_has_find; [rewrite size_iota | rewrite neg].\n  Qed.\n    \n  Lemma search_fail n: (forall m, p m -> n < m) -> search n = n.\n  Proof. exact/searchU_fail. Qed.\n    \n  Lemma searchS n :\n    search n.+1 = if search n != n then search n else if p n then n  else n.+1.\n  Proof. by rewrite /search searchUS. Qed.\n   \n  Lemma search_inc n m: n <= m -> search n <= search m.\n  Proof.\n    elim: m => [ | m ih].\n    by rewrite leqn0 => /eqP ->.\n    rewrite leq_eqVlt; case/orP => [ /eqP -> | ineq]//.\n    apply/leq_trans; first exact/ih.\n    rewrite searchS.\n    case: ifP => // /eqP ->.\n    by case: ifP.\n  Qed.\n\n  Lemma search_eq m n: p m -> (m <= n)%nat -> search m = search n.\n  Proof.\n    move => pm ineq; apply/eqP; rewrite eqn_leq; apply/andP.\n    by split; [apply/search_inc | apply/search_min/search_correct].\n  Qed.\n\nEnd naturals.\n\nLemma search_ext (p p': pred nat) n:\n  (forall k, (k < n)%nat -> p k = p' k) -> search p n = search p' n.\nProof.\n  rewrite !search_find => ass.\n  apply/eq_in_find => k.\n  rewrite mem_iota add0n => /andP [_ ineq].\n  exact/ass.\nQed.\n\nSection countTypes.\n  Context (Q: countType) (noq: Q) (noq_spec: pickle noq = 0).\n\n  Definition inverse_pickle n:= match pickle_inv Q n with\n\t                        | Some q => q\n\t                        | None => noq\n                                end.\n\n  Lemma min_ip: minimal_section inverse_pickle pickle.\n  Proof.\n    rewrite /inverse_pickle; split => [q | q n <-]; first by rewrite pickleK_inv.\n    case E: pickle_inv => [a  | ]; last by rewrite noq_spec.\n    by have := pickle_invK Q n; rewrite /oapp E => <-.\nQed.\nEnd countTypes.", "meta": {"author": "FlorianSteinberg", "repo": "incone", "sha": "e4ca64f3f50bd8084677f35215b35a6e2a43b639", "save_path": "github-repos/coq/FlorianSteinberg-incone", "path": "github-repos/coq/FlorianSteinberg-incone/incone-e4ca64f3f50bd8084677f35215b35a6e2a43b639/baire_spaces/countability/iseg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832332, "lm_q2_score": 0.8031737892899221, "lm_q1q2_score": 0.6761322918372207}}
{"text": "Require Import QArith.\nRequire Import primitives.\n\n(* AUXILIARY FUNCTIONS *)\n\nFixpoint bezier_curve_init (b : bezier_curve) : bezier_curve :=\n  match b with\n    | [P0] => [P0]\n    | Pi :: [P0] => [Pi]\n    | Pi :: b' => Pi :: (bezier_curve_init b')\n  end.\n  \nFixpoint bezier_curve_tail (b : bezier_curve) : bezier_curve :=\n  match b with\n    | [P0] => [P0]\n    | Pi :: b' => b'\n  end.\n  \nFixpoint bezier_curve_length (b : bezier_curve) : nat :=\n  match b with\n    | [P0] => 1%nat\n    | P0 :: b' =>  S (bezier_curve_length b')\n  end.\n  \nFixpoint bezier_curve_head (b : bezier_curve) : point :=\n  match b with\n    | [P0] => P0\n    | P0 :: _ => P0\n  end.\n\n\n(*\n  TODO: add some examples\n*)\n\n(*\n  fact_pos : Given a natural n,\n              returns n! as a positive\n              \n  This function is necessary due to Coq's\n  recursive definition of a natural number,\n  which easily causes a 'stack overflow'\n  for larger computations.\n*)\nFixpoint fact_pos (n : nat) : positive :=\n  match n with\n    | O => 1\n    | S n' => (Pos.of_nat n) * (fact_pos n')\n  end.\n\n(*\n  pow : Given a natural n and a rational q,\n              returns q^n as a rational.\n*)\nFixpoint pow (x : Q) (n : nat) : Q :=\n  match n with\n    | O => 1\n    | S n' => Qmult x (pow x n')\n  end.\n\n(*\n  minus_1_sgn : Given a natural exp,\n              returns (-1)^exp.\n*)\nDefinition minus_1_sgn (exp : nat) : Q := \n  match (Nat.even exp) with\n    | true => 1\n    | false => inject_Z (-1)\n  end.\n\nFixpoint calc_binomial_pos (n p : nat) : positive :=\n  match p with\n  | O => 1%positive\n  | S p' =>\n      match Nat.eqb n p with\n      | true => 1%positive\n      | false =>\n          match n with\n          | S n' => (calc_binomial_pos n' p') + (calc_binomial_pos n' (S p'))\n          | _ => 1%positive\n          end\n      end\n  end.\n\nFixpoint app (l r : bezier_curve) : bezier_curve :=\n  match l with\n  | [h] => h :: r\n  | h :: t => h :: app t r\n  end.\n\nInfix \"++\" := app (right associativity, at level 60).\n\nFixpoint rev (b : bezier_curve) : bezier_curve :=\n  match b with\n  | [h] => [h]\n  | h :: t => (rev t) ++ [h]\n  end.  ", "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/auxiliary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6760349727109233}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Frederic Blanqui, 2009-03-19 (setoid)\n- Adam Koprowski, 2007-04-02\n\nArithmetic over vectors on some semiring.\n*)\n\nSet Implicit Arguments.\n\nFrom Coq Require Import Setoid Morphisms.\nFrom CoLoR Require Import VecUtil RelUtil SemiRing OrdSemiRing NatUtil\n  LogicUtil.\n\nModule VectorArith (SRT : SemiRingType).\n\n  Module Export SR := SemiRing SRT.\n\n  Notation vec := (vector A).\n\n  Definition zero_vec := Vconst A0.\n\n  Definition id_vec n i (ip : i < n) := Vreplace (zero_vec n) ip A1.\n\n  Notation \"v1 =v v2\" := (Vforall2 eqA v1 v2) (at level 70).\n\n  (***********************************************************************)\n  (** addition *)\n\n  Definition vector_plus n (v1 v2 : vec n) := Vmap2 Aplus v1 v2.\n\n  Infix \"[+]\" := vector_plus (at level 50).\n\n  Global Instance vector_plus_mor n :\n    Proper (Vforall2 eqA ==> Vforall2 eqA ==> Vforall2 eqA) (@vector_plus n).\n\n  Proof.\n    intros u u' uu' v v' vv'. apply Vforall2_intro_nth. intros.\n    unfold vector_plus. rewrite !Vnth_map2.\n    (*COQ: rewrite H does not work even if Vnth is declared as morphism *)\n    apply Aplus_mor; apply Vforall2_elim_nth; hyp.\n  Qed.\n\n  Lemma vector_plus_nth n (vl vr : vec n) i (ip : i < n) :\n    Vnth (vl [+] vr) ip =A= Vnth vl ip + Vnth vr ip.\n\n  Proof. unfold vector_plus. rewrite Vnth_map2. refl. Qed.\n\n  Lemma vector_plus_comm n (v1 v2 : vec n) : v1 [+] v2 =v v2 [+] v1.\n\n  Proof. apply Vforall2_intro_nth. intros. rewrite !vector_plus_nth. ring. Qed.\n\n  Lemma vector_plus_assoc n (v1 v2 v3 : vec n) :\n    v1 [+] (v2 [+] v3) =v v1 [+] v2 [+] v3.\n\n  Proof. apply Vforall2_intro_nth. intros. rewrite !vector_plus_nth. ring. Qed.\n\n  Lemma vector_plus_zero_r n (v : vec n) : v [+] zero_vec n =v v.\n\n  Proof.\n    apply Vforall2_intro_nth. intros. rewrite vector_plus_nth.\n    set (w := Vnth_const A0 ip). fold zero_vec in w. rewrite w. ring.\n  Qed.\n\n  Lemma vector_plus_zero_l n (v : vec n) : zero_vec n [+] v =v v.\n\n  Proof. rewrite vector_plus_comm. apply vector_plus_zero_r. Qed.\n\n  (***********************************************************************)\n  (** sum of a vector of vectors *)\n\n  Definition add_vectors n k (v : vector (vec n) k) := \n    Vfold_left_rev (@vector_plus n) (zero_vec n) v.\n\n  Global Instance add_vectors_mor n k :\n    Proper (Vforall2 (Vforall2 eqA) ==> Vforall2 eqA) (@add_vectors n k).\n\n  Proof.\n    intro x; revert x.\n    induction x; simpl; intros. VOtac. refl. revert H. VSntac y.\n    unfold add_vectors. simpl. rewrite Vforall2_cons_eq. intuition.\n    rewrite H1. apply vector_plus_mor. 2: refl.\n    eapply Vfold_left_rev_Vforall2. apply vector_plus_mor. refl. hyp.\n  Qed.\n\n  Lemma add_vectors_cons n i (a : vec n) (v : vector (vec n) i) :\n    add_vectors (Vcons a v) =v a [+] add_vectors v.\n\n  Proof. unfold add_vectors. simpl. rewrite vector_plus_comm. refl. Qed.\n\n  Lemma add_vectors_zero n k : forall v : vector (vec n) k, \n    Vforall (fun v => v =v zero_vec n) v -> add_vectors v =v zero_vec n.\n\n  Proof.\n    induction v. refl. rewrite add_vectors_cons. simpl. intuition.\n    rewrite H0, vector_plus_zero_l. hyp.\n  Qed.\n\n  Lemma add_vectors_perm n i v v' (vs : vector (vec n) i) :\n    add_vectors (Vcons v (Vcons v' vs)) =v add_vectors (Vcons v' (Vcons v vs)).\n\n  Proof.\n    rewrite !add_vectors_cons, !vector_plus_assoc, (vector_plus_comm v v').\n    refl.\n  Qed.\n\n  Lemma add_vectors_nth n k : forall (vs : vector (vec n) k) i (ip : i < n),\n    Vnth (add_vectors vs) ip\n    =A= Vfold_left_rev Aplus A0 (Vmap (fun v => Vnth v ip) vs).\n\n  Proof.\n    induction vs; simpl; intros.\n    unfold add_vectors, zero_vec; simpl. rewrite Vnth_const. refl.\n    rewrite (Vforall2_elim_nth (R:=eqA)). 2: rewrite add_vectors_cons; refl.\n    rewrite vector_plus_nth, IHvs, Aplus_comm. refl.\n  Qed.\n\n  Lemma add_vectors_split n : forall k (v vl vr : vector (vec n) k),\n    (forall i (ip : i < k), Vnth v ip =v Vnth vl ip [+] Vnth vr ip) ->\n    add_vectors v =v add_vectors vl [+] add_vectors vr.\n\n  Proof.\n    induction k; intros.\n    VOtac. unfold add_vectors. simpl. rewrite vector_plus_zero_r. refl.\n    VSntac v. VSntac vl. VSntac vr.\n    rewrite !add_vectors_cons, (IHk (Vtail v) (Vtail vl) (Vtail vr)),\n      !Vhead_nth, (H 0 (lt_O_Sn k)).\n    match goal with\n      |- (?A [+] ?B) [+] (?C [+] ?D) =v (?A [+] ?C) [+] (?B [+] ?D) =>\n        set (X := A); set (Y := B); set (W := C); set (V := D) end.\n    rewrite <- !vector_plus_assoc, (vector_plus_assoc W Y V),\n      (vector_plus_comm W Y), !vector_plus_assoc. refl.\n    intros. rewrite !Vnth_tail. apply H.\n  Qed.\n\n  (***********************************************************************)\n  (** point-wise product *)\n\n  Definition dot_product n (l r : vec n) :=\n    Vfold_left_rev Aplus A0 (Vmap2 Amult l r).\n\n  Global Instance dot_product_mor n :\n    Proper (Vforall2 eqA ==> Vforall2 eqA ==> eqA) (@dot_product n).\n\n  Proof.\n    intros u u' uu' v v' vv'; revert u u' uu' v v' vv'.\n    induction n; intros. VOtac. refl.\n    revert uu' vv'. VSntac u. VSntac v. VSntac u'. VSntac v'. intros H3 H4.\n    rewrite Vforall2_cons_eq in H3. rewrite Vforall2_cons_eq in H4. intuition.\n    unfold dot_product. simpl. unfold dot_product in IHn.\n    rewrite (IHn _ _ H6 _ _ H7), H5, H3. refl.\n  Qed.\n\n  Lemma dot_product_zero : forall n (v v' : vec n),\n    Vforall (fun el => el =A= A0) v -> dot_product v v' =A= A0.\n\n  Proof.\n    induction n; intros.\n    VOtac. refl.\n    VSntac v. VSntac v'. unfold dot_product. simpl.\n    fold (dot_product (Vtail v) (Vtail v')). rewrite IHn.\n    assert (Vhead v =A= A0). rewrite Vhead_nth. apply Vforall_nth. hyp.\n    rewrite H2. ring.\n    apply Vforall_incl with (S n) v. intros.\n    apply Vin_tail. hyp. hyp.\n  Qed.\n\n  Lemma dot_product_id : forall i n (ip : i < n) v,\n    dot_product (id_vec ip) v =A= Vnth v ip.\n\n  Proof.\n    induction i. intros. \n    destruct n. lia.\n\n    (* induction base *)\n    VSntac v. unfold id_vec, dot_product. simpl.\n    change (dot_product (Vconst A0 n) (Vtail v) + A1 * Vhead v =A= Vhead v).\n    rewrite dot_product_zero. ring.\n    apply Vforall_nth_intro. intros.\n    rewrite Vnth_const. refl.\n\n    (* induction step *)\n    intros. destruct n. lia.\n    VSntac v. unfold dot_product. simpl.\n    rewrite <- (IHi n (lt_S_n ip) (Vtail v)).\n    ring_simplify. unfold dot_product. refl.\n  Qed.\n\n  Lemma dot_product_comm : forall n (u v : vec n),\n    dot_product u v =A= dot_product v u.\n\n  Proof.\n    induction n. refl. intros. VSntac u. VSntac v. unfold dot_product. simpl.\n    unfold dot_product in IHn. rewrite IHn. ring.\n  Qed.\n\n  Lemma dot_product_distr_r : forall n (v vl vr : vec n),\n    dot_product v (vl [+] vr) =A= dot_product v vl + dot_product v vr.\n\n  Proof.\n    induction n; intros.\n    VOtac. unfold dot_product. simpl. ring.\n    VSntac v. VSntac vl. VSntac vr. unfold dot_product. simpl.\n    fold (Vtail vl [+] Vtail vr).\n    fold (dot_product (Vtail v) (Vtail vl [+] Vtail vr)).\n    rewrite IHn. unfold dot_product. ring.\n  Qed.\n\n  Lemma dot_product_distr_l n (v vl vr : vec n) :\n    dot_product (vl [+] vr) v =A= dot_product vl v + dot_product vr v.\n\n  Proof.\n    rewrite dot_product_comm, dot_product_distr_r, (dot_product_comm v vl),\n      (dot_product_comm v vr). refl.\n  Qed.\n\n  Lemma dot_product_cons : forall n al ar (vl vr : vec n),\n    dot_product (Vcons al vl) (Vcons ar vr) =A= al * ar + dot_product vl vr.\n\n  Proof. intros. unfold dot_product. simpl. ring. Qed.\n\n  Lemma dot_product_distr_mult : forall n a (v v' : vec n),\n    a * dot_product v v'\n    =A= dot_product (Vbuild (fun i ip => a * Vnth v ip)) v'.\n\n  Proof.\n    induction n; intros.\n    VOtac. unfold dot_product. simpl. ring.\n    rewrite (VSn_eq (Vbuild (fun i (ip : i < S n) => a * Vnth v ip))).\n    VSntac v. VSntac v'. rewrite !dot_product_cons. ring_simplify.\n    rewrite IHn, Vbuild_tail, Vbuild_head. simpl. ring_simplify.\n    match goal with\n      |- _ + dot_product ?X _ =A= _ + dot_product ?Y _ => replace X with Y end.\n    refl. apply Veq_nth. intros. \n    rewrite !Vbuild_nth, lt_Sn_nS. refl.\n  Qed.\n\n  (***********************************************************************)\n  (** hints *)\n\n  Global Hint Rewrite vector_plus_zero_l vector_plus_zero_r add_vectors_cons : arith.\n\nEnd VectorArith.\n\n(***********************************************************************)\n(** product ordering on vectors *)\n\nModule OrdVectorArith (OSRT : OrdSemiRingType).\n\n  Module Export VA := VectorArith OSRT.SR.\n  Module Export OSR := OrdSemiRing OSRT.\n\n(***********************************************************************)\n(** [ge] on vectors *)\n\n  Infix \">=v\" := (Vforall2 ge) (at level 70).\n\n  Global Instance vec_ge_mor n :\n    Proper (Vforall2 eqA ==> Vforall2 eqA ==> iff) (Vforall2 ge (n:=n)).\n\n  Proof. apply Vforall2_aux_Proper. class. Qed.\n\n  Arguments vec_ge_mor [n x y] _ [x0 y0] _ : rename.\n\n  Lemma vec_plus_ge_compat : forall n (vl vl' vr vr' : vec n), \n    vl >=v vl' -> vr >=v vr' -> vl [+] vr >=v vl' [+] vr'.\n\n  Proof.\n    unfold vector_plus. intros. apply Vforall2_intro_nth.\n    intros. simpl. rewrite !Vnth_map2.\n    apply plus_ge_compat.\n    apply Vforall2_elim_nth. hyp.\n    apply Vforall2_elim_nth. hyp.\n  Qed.\n\n  Lemma vec_plus_ge_compat_r : forall n (vl vl' vr : vec n), \n    vl >=v vl' -> vl [+] vr >=v vl' [+] vr.\n\n  Proof. intros. apply vec_plus_ge_compat. hyp. refl. Qed.\n\n  Lemma vec_plus_ge_compat_l : forall n (vl vr vr' : vec n), \n    vr >=v vr' -> vl [+] vr >=v vl [+] vr'.\n\n  Proof. intros. apply vec_plus_ge_compat. refl. hyp. Qed.\n\nEnd OrdVectorArith.\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Util/Vector/VecArith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6760349608251613}}
{"text": "(******************************************************************************)\n(** * Lemmas about sorted lists *)\n(******************************************************************************)\n\nRequire Import HahnBase HahnSets HahnList HahnRelationsBasic HahnEquational.\nRequire Export Sorted Setoid.\n\nSet Implicit Arguments.\n\nAdd Parametric Morphism A : (@StronglySorted A) with signature\n  inclusion ==> eq ==> Basics.impl as StronglySorted_mori.\nProof.\n  unfold inclusion; red; ins; desf.\n  induction H0; econs; ins.\n  rewrite Forall_forall in *; ins; desf; eauto.\nQed.\n\nAdd Parametric Morphism A : (@StronglySorted A) with signature\n  same_relation ==> eq ==> iff as StronglySorted_more.\nProof.\n  by split; [rewrite (proj1 H)|rewrite (proj2 H)].\nQed.\n\n\nLemma StronglySorted_cons_iff A (r : relation A) (a : A) (l : list A) :\n  StronglySorted r (a :: l) <-> StronglySorted r l /\\ Forall (r a) l.\nProof.\n  split; ins; desf; auto using SSorted_cons, StronglySorted_inv.\nQed.\n\nLemma StronglySorted_app_iff A (r: relation A) l1 l2 :\n  StronglySorted r (l1 ++ l2) <->\n  StronglySorted r l1 /\\ StronglySorted r l2 /\\\n  (forall x1 (IN1: In x1 l1) x2 (IN2: In x2 l2), r x1 x2).\nProof.\n  induction l1; ins; [by intuition; vauto|].\n  rewrite !StronglySorted_cons_iff, IHl1, Forall_app.\n  clear; intuition; desf; eauto.\n  all: rewrite Forall_forall in *; eauto.\nQed.\n\nLemma StronglySorted_app A (r: relation A) l1 l2\n    (S1: StronglySorted r l1) (S2: StronglySorted r l2)\n    (L: forall x1 (IN1: In x1 l1) x2 (IN2: In x2 l2), r x1 x2):\n  StronglySorted r (l1 ++ l2).\nProof.\n  by apply StronglySorted_app_iff.\nQed.\n\nLemma StronglySorted_app_l A r (l l': list A):\n  StronglySorted r (l ++ l') -> StronglySorted r l.\nProof.\n  rewrite StronglySorted_app_iff; tauto.\nQed.\n\nLemma StronglySorted_app_r A r (l l': list A):\n  StronglySorted r (l ++ l') -> StronglySorted r l'.\nProof.\n  rewrite StronglySorted_app_iff; tauto.\nQed.\n\nLemma StronglySorted_filter A r f (l : list A):\n  StronglySorted r l -> StronglySorted r (filter f l).\nProof.\n  induction l; ins; eauto; desf; rewrite StronglySorted_cons_iff in *; desf.\n  all: splits; desf; eauto using Forall_filter.\nQed.\n\nLemma StronglySorted_filterP A r f (l : list A):\n  StronglySorted r l -> StronglySorted r (filterP f l).\nProof.\n  induction l; ins; eauto; desf; rewrite StronglySorted_cons_iff in *; desf.\n  all: splits; desf; eauto using Forall_filterP.\nQed.\n\nLemma NoDup_StronglySorted A (r: relation A) (IRR: irreflexive r)\n      l (SS: StronglySorted r l):\n  NoDup l.\nProof.\n  induction l; ins.\n  apply StronglySorted_inv in SS; desc.\n  rewrite Forall_forall in *.\n  constructor; eauto.\nQed.\n\nGlobal Hint Resolve NoDup_StronglySorted : hahn.\nGlobal Hint Resolve SSorted_nil : hahn.\nGlobal Hint Resolve StronglySorted_filterP : hahn.\nGlobal Hint Resolve StronglySorted_filter : hahn.\n\nLemma sorted_perm_eq : forall A (cmp: A -> A -> Prop)\n  (TRANS: transitive cmp)\n  (ANTIS: antisymmetric cmp)\n  l l' (P: Permutation l l')\n  (S : StronglySorted cmp l) (S' : StronglySorted cmp l'), l = l'.\nProof.\n  induction l; ins.\n    by apply Permutation_nil in P; desf.\n  assert (X: In a l') by eauto using Permutation_in, Permutation_sym, in_eq.\n  apply In_split2 in X; desf; apply Permutation_cons_app_inv in P.\n  destruct l1; ins; [by inv S; inv S'; eauto using f_equal|].\n  assert (X: In a0 l) by eauto using Permutation_in, Permutation_sym, in_eq.\n  inv S; inv S'; rewrite Forall_forall in *; ins.\n  destruct X0; left; apply ANTIS; eauto with hahn.\nQed.\n\nLemma StronglySorted_eq A (r: relation A) (ORD: strict_partial_order r) l l'\n   (SS: StronglySorted r l) (SS': StronglySorted r l')\n   (EQ: forall x, In x l <-> In x l'): l = l'.\nProof.\n  red in ORD; desc.\n  eapply sorted_perm_eq; eauto using NoDup_Permutation with hahn.\nQed.\n\nLemma StronglySorted_restr A cond (r: relation A) l:\n  StronglySorted (restr_rel cond r) l -> StronglySorted r l.\nProof.\n  induction l; ins; vauto.\n  rewrite StronglySorted_cons_iff, ForallE in *.\n  firstorder.\nQed.\n\n\nFixpoint isort A (r : relation A) l :=\n  match l with\n  | nil => nil\n  | x :: l =>\n    let l' := isort r l in\n    filterP (fun y => r y x) l' ++ x :: filterP (fun y => ~ r y x) l'\n  end.\n\nGlobal Hint Resolve SSorted_nil : hahn.\nGlobal Hint Resolve StronglySorted_filterP : hahn.\n\nLemma in_isort_iff A x (r : relation A) l : In x (isort r l) <-> In x l.\nProof.\n  induction l; ins; rewrite in_app_iff; ins; in_simp; rewrite IHl.\n  tauto.\nQed.\n\nLemma StronglySorted_isort A (r : relation A)\n      (TOT: strict_total_order (fun _ : A => True) r)\n      l (ND: NoDup l) :\n  StronglySorted r (isort r l).\nProof.\n  destruct TOT as [[IRR T] TOT].\n  induction l; ins; vauto.\n  rewrite nodup_cons in *; desc.\n  apply StronglySorted_app; ins; in_simp; eauto with hahn.\n    econs; eauto with hahn.\n    apply Forall_forall; ins; in_simp.\n  all: rewrite in_isort_iff in *; desf.\n    forward eapply TOT with (a:=x) (b:=a); try red; ins; desf; eauto.\n    forward eapply TOT with (a:=x1) (b:=x2); try red; ins; desf; eauto.\n  exfalso; eauto.\nQed.\n", "meta": {"author": "vafeiadis", "repo": "hahn", "sha": "d486f449a51c14b8e1093f14d096cc99833974d7", "save_path": "github-repos/coq/vafeiadis-hahn", "path": "github-repos/coq/vafeiadis-hahn/hahn-d486f449a51c14b8e1093f14d096cc99833974d7/HahnSorted.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.675994968139549}}
{"text": "Inductive bool : Set :=\n| true\n| false.\n\nDefinition notb (b : bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nDefinition andb (b1 b2 : bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\nLemma andb_comm :\n  forall b1 b2,\n    andb b1 b2 = andb b2 b1.\nProof.\n  intro b1.\n  intro b2.\n  destruct b1.\n    - destruct b2.\n      + reflexivity.\n      + simpl. reflexivity.\n    - destruct b2.\n      + simpl. reflexivity.\n      + reflexivity.\nQed.\n\nPrint andb_comm.", "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/01-lecture-01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.6759708357063207}}
{"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 Export Field.\nRequire Export QArith_base.\nRequire Import NArithRing.\n\n(** * field and ring tactics for rational numbers *)\n\nDefinition Qsrt : ring_theory 0 1 Qplus Qmult Qminus Qopp Qeq.\nProof.\n  constructor.\n  exact Qplus_0_l.\n  exact Qplus_comm.\n  exact Qplus_assoc.\n  exact Qmult_1_l.\n  exact Qmult_comm.\n  exact Qmult_assoc.\n  exact Qmult_plus_distr_l.\n  reflexivity.\n  exact Qplus_opp_r.\nQed.\n\nDefinition Qsft : field_theory 0 1 Qplus Qmult Qminus Qopp Qdiv Qinv Qeq.\nProof.\n  constructor.\n  exact Qsrt.\n  discriminate.\n  reflexivity.\n  intros p Hp.\n  rewrite Qmult_comm.\n  apply Qmult_inv_r.\n  exact Hp.\nQed.\n\nLemma Qpower_theory : power_theory 1 Qmult Qeq Z_of_N Qpower.\nProof.\nconstructor.\nintros r [|n];\nreflexivity.\nQed.\n\nLtac isQcst t :=\n  match t with\n  | inject_Z ?z => isZcst z\n  | Qmake ?n ?d =>\n    match isZcst n with\n      true => isPcst d\n    | _ => false\n    end\n  | _ => false\n  end.\n\nLtac Qcst t :=\n  match isQcst t with\n    true => t\n    | _ => NotConstant\n  end.\n\nLtac Qpow_tac t :=\n  match t with\n  | Z0 => N0\n  | Zpos ?n => Ncst (Npos n)\n  | Z_of_N ?n => Ncst n\n  | NtoZ ?n => Ncst n\n  | _ => NotConstant\n  end.\n\nAdd Field Qfield : Qsft\n (decidable Qeq_bool_eq,\n  completeness Qeq_eq_bool,\n  constants [Qcst],\n  power_tac Qpower_theory [Qpow_tac]).\n\n(** Exemple of use: *)\n\nSection Examples.\n\nLet ex1 : forall x y z : Q, (x+y)*z ==  (x*z)+(y*z).\n  intros.\n  ring.\nQed.\n\nLet ex2 : forall x y : Q, x+y == y+x.\n  intros.\n  ring.\nQed.\n\nLet ex3 : forall x y z : Q, (x+y)+z == x+(y+z).\n  intros.\n  ring.\nQed.\n\nLet ex4 : (inject_Z 1)+(inject_Z 1)==(inject_Z 2).\n  ring.\nQed.\n\nLet ex5 : 1+1 == 2#1.\n  ring.\nQed.\n\nLet ex6 : (1#1)+(1#1) == 2#1.\n  ring.\nQed.\n\nLet ex7 : forall x : Q, x-x== 0.\n  intro.\n  ring.\nQed.\n\nLet ex8 : forall x : Q, x^1 == x.\n  intro.\n  ring.\nQed.\n\nLet ex9 : forall x : Q, x^0 == 1.\n  intro.\n  ring.\nQed.\n\nLet ex10 : forall x y : Q, ~(y==0) -> (x/y)*y == x.\nintros.\nfield.\nauto.\nQed.\n\nEnd Examples.\n\nLemma Qopp_plus : forall a b,  -(a+b) == -a + -b.\nProof.\n  intros; ring.\nQed.\n\nLemma Qopp_opp : forall q, - -q==q.\nProof.\n  intros; ring.\nQed.\n", "meta": {"author": "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/QArith/Qfield.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870013740061, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6759705025025073}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\nRequire Import BinNat.\nLocal Open Scope N_scope.\n\n\n\nDefinition Pdiv_eucl a b := N.pos_div_eucl a (Npos b).\n\nDefinition Pdiv_eucl_correct a b :\nlet (q,r) := Pdiv_eucl a b in Npos a = q * Npos b + r\n:= N.pos_div_eucl_spec a (Npos b).\n\nLemma Pdiv_eucl_remainder a b :\nsnd (Pdiv_eucl a b) < Npos b.\nProof. hammer_hook \"Ndiv_def\" \"Ndiv_def.Pdiv_eucl_remainder\".   now apply (N.pos_div_eucl_remainder a (Npos b)). Qed.\n\nNotation Ndiv_eucl := N.div_eucl (compat \"8.3\").\nNotation Ndiv := N.div (compat \"8.3\").\nNotation Nmod := N.modulo (compat \"8.3\").\n\nNotation Ndiv_eucl_correct := N.div_eucl_spec (compat \"8.3\").\nNotation Ndiv_mod_eq := N.div_mod' (compat \"8.3\").\nNotation Nmod_lt := N.mod_lt (compat \"8.3\").\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/NArith/Ndiv_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6759704941788323}}
{"text": "(** printing ==>  $⟹$  #⟹#  *)\n(** printing ==>* $⟹*$ #⟹*# *)\n(** printing |-   $⊢$  #⊢#  *)\n(** printing \\in  $∈$  #∈#  *)\n\n(** * Types: Type Systems *)\n\n(** Our next major topic is _type systems_ -- static program\n    analyses that classify expressions according to the \"shapes\" of\n    their results.  We'll begin with a typed version of the simplest\n    imaginable language, to introduce the basic ideas of types and\n    typing rules and the fundamental theorems about type systems:\n    _type preservation_ and _progress_.  In chapter [Stlc] we'll move\n    on to the _simply typed lambda-calculus_, which lives at the core\n    of every modern functional programming language (including\n    Coq!). *)\n\nRequire Import Coq.Arith.Arith.\n\nLoad Relation.\nLoad Maps.\n\nHint Constructors multi.\n\n(* ################################################################# *)\n(** * Typed Arithmetic Expressions *)\n\n(** To motivate the discussion of type systems, let's begin as\n    usual with a tiny toy language.  We want it to have the potential\n    for programs to go wrong because of runtime type errors, so we\n    need something a tiny bit more complex than the language of\n    constants and addition that we used in chapter [Smallstep]: a\n    single kind of data (e.g., numbers) is too simple, but just two\n    kinds (numbers and booleans) gives us enough material to tell an\n    interesting story.\n\n    The language definition is completely routine. *)\n\n(* ================================================================= *)\n(** ** Syntax *)\n\n(** Here is the syntax, informally:\n<<\n    t ::= true\n        | false\n        | if t then t else t\n        | 0\n        | succ t\n        | pred t\n        | iszero t\n>>\n    And here it is formally: *)\n\nInductive tm : Type :=\n  | ttrue : tm\n  | tfalse : tm\n  | tif : tm -> tm -> tm -> tm\n  | tzero : tm\n  | tsucc : tm -> tm\n  | tpred : tm -> tm\n  | tiszero : tm -> tm.\n\n(** _Values_ are [true], [false], and numeric values... *)\n\nInductive bvalue : tm -> Prop :=\n  | bv_true : bvalue ttrue\n  | bv_false : bvalue tfalse.\n\nInductive nvalue : tm -> Prop :=\n  | nv_zero : nvalue tzero\n  | nv_succ : forall t, nvalue t -> nvalue (tsucc t).\n\nDefinition value (t:tm) := bvalue t \\/ nvalue t.\n\nHint Constructors bvalue nvalue.\nHint Unfold value.\nHint Unfold update.\n\n(* ================================================================= *)\n(** ** Operational Semantics *)\n\n(** Here is the single-step relation, first informally... *)\n(**\n<<\n                    ------------------------------                  (ST_IfTrue)\n                    if true then t1 else t2 ==> t1\n\n                   -------------------------------                 (ST_IfFalse)\n                   if false then t1 else t2 ==> t2\n\n                              t1 ==> t1'\n            ------------------------------------------------            (ST_If)\n            if t1 then t2 else t3 ==> if t1' then t2 else t3\n\n                              t1 ==> t1'\n                         --------------------                         (ST_Succ)\n                         succ t1 ==> succ t1'\n\n                             ------------                         (ST_PredZero)\n                             pred 0 ==> 0\n\n                           numeric value v1\n                        ---------------------                     (ST_PredSucc)\n                        pred (succ v1) ==> v1\n\n                              t1 ==> t1'\n                         --------------------                         (ST_Pred)\n                         pred t1 ==> pred t1'\n\n                          -----------------                     (ST_IszeroZero)\n                          iszero 0 ==> true\n\n                           numeric value v1\n                      --------------------------                (ST_IszeroSucc)\n                      iszero (succ v1) ==> false\n\n                              t1 ==> t1'\n                       ------------------------                     (ST_Iszero)\n                       iszero t1 ==> iszero t1'\n>>\n*)\n\n(** ... and then formally: *)\n\nReserved Notation \"t1 '==>' t2\" (at level 40).\n\nInductive step : tm -> tm -> Prop :=\n  | ST_IfTrue : forall t1 t2,\n      (tif ttrue t1 t2) ==> t1\n  | ST_IfFalse : forall t1 t2,\n      (tif tfalse t1 t2) ==> t2\n  | ST_If : forall t1 t1' t2 t3,\n      t1 ==> t1' ->\n      (tif t1 t2 t3) ==> (tif t1' t2 t3)\n  | ST_Succ : forall t1 t1',\n      t1 ==> t1' ->\n      (tsucc t1) ==> (tsucc t1')\n  | ST_PredZero :\n      (tpred tzero) ==> tzero\n  | ST_PredSucc : forall t1,\n      nvalue t1 ->\n      (tpred (tsucc t1)) ==> t1\n  | ST_Pred : forall t1 t1',\n      t1 ==> t1' ->\n      (tpred t1) ==> (tpred t1')\n  | ST_IszeroZero :\n      (tiszero tzero) ==> ttrue\n  | ST_IszeroSucc : forall t1,\n       nvalue t1 ->\n      (tiszero (tsucc t1)) ==> tfalse\n  | ST_Iszero : forall t1 t1',\n      t1 ==> t1' ->\n      (tiszero t1) ==> (tiszero t1')\n\nwhere \"t1 '==>' t2\" := (step t1 t2).\n\nHint Constructors step.\n\n(** Notice that the [step] relation doesn't care about whether\n    expressions make global sense -- it just checks that the operation\n    in the _next_ reduction step is being applied to the right kinds\n    of operands.  For example, the term [succ true] (i.e., \n    [tsucc ttrue] in the formal syntax) cannot take a step, but the\n    almost as obviously nonsensical term\n<<\n       succ (if true then true else true)\n>>\n    can take a step (once, before becoming stuck). *)\n\n(* ================================================================= *)\n(** ** Normal Forms and Values *)\n\n(** The first interesting thing to notice about this [step] relation\n    is that the strong progress theorem from the [Smallstep] chapter\n    fails here.  That is, there are terms that are normal forms (they\n    can't take a step) but not values (because we have not included\n    them in our definition of possible \"results of reduction\").  Such\n    terms are _stuck_. *)\n\nNotation step_normal_form := (normal_form step).\n\nDefinition stuck (t:tm) : Prop :=\n  step_normal_form t /\\ ~ value t.\n\nHint Unfold stuck.\n\n(** **** Exercise: 2 stars (some_term_is_stuck)  *)\nExample some_term_is_stuck :\n  exists t, stuck t.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** However, although values and normal forms are _not_ the same in this\n    language, the set of values is included in the set of normal\n    forms.  This is important because it shows we did not accidentally\n    define things so that some value could still take a step. *)\n\n(** **** Exercise: 3 stars (value_is_nf)  *)\nLemma value_is_nf : forall t,\n  value t -> step_normal_form t.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** (Hint: You will reach a point in this proof where you need to\n    use an induction to reason about a term that is known to be a\n    numeric value.  This induction can be performed either over the\n    term itself or over the evidence that it is a numeric value.  The\n    proof goes through in either case, but you will find that one way\n    is quite a bit shorter than the other.  For the sake of the\n    exercise, try to complete the proof both ways.) *)\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (step_deterministic)  *)\n(** Use [value_is_nf] to show that the [step] relation is also\n    deterministic. *)\n\nTheorem step_deterministic:\n  deterministic step.\nProof with eauto.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Typing *)\n\n(** The next critical observation is that, although this\n    language has stuck terms, they are always nonsensical, mixing\n    booleans and numbers in a way that we don't even _want_ to have a\n    meaning.  We can easily exclude such ill-typed terms by defining a\n    _typing relation_ that relates terms to the types (either numeric\n    or boolean) of their final results.  *)\n\nInductive ty : Type :=\n  | TBool : ty\n  | TNat : ty.\n\n(** In informal notation, the typing relation is often written\n    [|- t \\in T] and pronounced \"[t] has type [T].\"  The [|-] symbol\n    is called a \"turnstile.\"  Below, we're going to see richer typing\n    relations where one or more additional \"context\" arguments are\n    written to the left of the turnstile.  For the moment, the context\n    is always empty. *)\n(** \n<<\n                           ----------------                            (T_True)\n                           |- true \\in Bool\n\n                          -----------------                           (T_False)\n                          |- false \\in Bool\n\n             |- t1 \\in Bool    |- t2 \\in T    |- t3 \\in T\n             --------------------------------------------                (T_If)\n                    |- if t1 then t2 else t3 \\in T\n\n                             ------------                              (T_Zero)\n                             |- 0 \\in Nat\n\n                            |- t1 \\in Nat\n                          ------------------                           (T_Succ)\n                          |- succ t1 \\in Nat\n\n                            |- t1 \\in Nat\n                          ------------------                           (T_Pred)\n                          |- pred t1 \\in Nat\n\n                            |- t1 \\in Nat\n                        ---------------------                        (T_IsZero)\n                        |- iszero t1 \\in Bool\n>>\n*)\n\nReserved Notation \"'|-' t '\\in' T\" (at level 40).\n\nInductive has_type : tm -> ty -> Prop :=\n  | T_True :\n       |- ttrue \\in TBool\n  | T_False :\n       |- tfalse \\in TBool\n  | T_If : forall t1 t2 t3 T,\n       |- t1 \\in TBool ->\n       |- t2 \\in T ->\n       |- t3 \\in T ->\n       |- tif t1 t2 t3 \\in T\n  | T_Zero :\n       |- tzero \\in TNat\n  | T_Succ : forall t1,\n       |- t1 \\in TNat ->\n       |- tsucc t1 \\in TNat\n  | T_Pred : forall t1,\n       |- t1 \\in TNat ->\n       |- tpred t1 \\in TNat\n  | T_Iszero : forall t1,\n       |- t1 \\in TNat ->\n       |- tiszero t1 \\in TBool\n\nwhere \"'|-' t '\\in' T\" := (has_type t T).\n\nHint Constructors has_type.\n\nExample has_type_1 :\n  |- tif tfalse tzero (tsucc tzero) \\in TNat.\nProof.\n  apply T_If.\n    - apply T_False.\n    - apply T_Zero.\n    - apply T_Succ.\n       + apply T_Zero.\nQed.\n\n(** (Since we've included all the constructors of the typing relation\n    in the hint database, the [auto] tactic can actually find this\n    proof automatically.) *)\n\n(** It's important to realize that the typing relation is a\n    _conservative_ (or _static_) approximation: it does not consider\n    what happens when the term is reduced -- in particular, it does\n    not calculate the type of its normal form. *)\n\nExample has_type_not :\n  ~ (|- tif tfalse tzero ttrue \\in TBool).\nProof.\n  intros Contra. solve_by_inverts 2.  Qed.\n\n(** **** Exercise: 1 star, optional (succ_hastype_nat__hastype_nat)  *)\nExample succ_hastype_nat__hastype_nat : forall t,\n  |- tsucc t \\in TNat ->\n  |- t \\in TNat.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Canonical forms *)\n\n(** The following two lemmas capture the fundamental property that the\n    definitions of boolean and numeric values agree with the typing\n    relation. *)\n\nLemma bool_canonical : forall t,\n  |- t \\in TBool -> value t -> bvalue t.\nProof.\n  intros t HT HV.\n  inversion HV; auto.\n  induction H; inversion HT; auto.\nQed.\n\nLemma nat_canonical : forall t,\n  |- t \\in TNat -> value t -> nvalue t.\nProof.\n  intros t HT HV.\n  inversion HV.\n  inversion H; subst; inversion HT.\n  auto.\nQed.\n\n(* ================================================================= *)\n(** ** Progress *)\n\n(** The typing relation enjoys two critical properties.  The first is\n    that well-typed normal forms are not stuck -- or conversely, if a\n    term is well typed, then either it is a value or it can take at\n    least one step.  We call this _progress_. *)\n\n(** **** Exercise: 3 stars (finish_progress)  *)\nTheorem progress : forall t T,\n  |- t \\in T ->\n  value t \\/ exists t', t ==> t'.\n\n(** Complete the formal proof of the [progress] property.  (Make sure\n    you understand the parts we've given of the informal proof in the\n    following exercise before starting -- this will save you a lot of\n    time.) *)\nProof with auto.\n  intros t T HT.\n  induction HT...\n  (* The cases that were obviously values, like T_True and\n     T_False, were eliminated immediately by auto *)\n  - (* T_If *)\n    right. inversion IHHT1; clear IHHT1.\n    + (* t1 is a value *)\n    apply (bool_canonical t1 HT1) in H.\n    inversion H; subst; clear H.\n      exists t2...\n      exists t3...\n    + (* t1 can take a step *)\n      inversion H as [t1' H1].\n      exists (tif t1' t2 t3)...\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advancedM (finish_progress_informal)  *)\n(** Complete the corresponding informal proof: *)\n\n(** _Theorem_: If [|- t \\in T], then either [t] is a value or else\n    [t ==> t'] for some [t']. *)\n\n(** _Proof_: By induction on a derivation of [|- t \\in T].\n\n      - If the last rule in the derivation is [T_If], then [t = if t1\n        then t2 else t3], with [|- t1 \\in Bool], [|- t2 \\in T] and [|- t3\n        \\in T].  By the IH, either [t1] is a value or else [t1] can step\n        to some [t1'].\n\n            - If [t1] is a value, then by the canonical forms lemmas\n              and the fact that [|- t1 \\in Bool] we have that [t1]\n              is a [bvalue] -- i.e., it is either [true] or [false].\n              If [t1 = true], then [t] steps to [t2] by [ST_IfTrue],\n              while if [t1 = false], then [t] steps to [t3] by\n              [ST_IfFalse].  Either way, [t] can step, which is what\n              we wanted to show.\n\n            - If [t1] itself can take a step, then, by [ST_If], so can\n              [t].\n\n      - (* FILL IN HERE *)\n[] *)\n\n(** This theorem is more interesting than the strong progress theorem\n    that we saw in the [Smallstep] chapter, where _all_ normal forms\n    were values.  Here a term can be stuck, but only if it is ill\n    typed. *)\n\n(* ================================================================= *)\n(** ** Type Preservation *)\n\n(** The second critical property of typing is that, when a well-typed\n    term takes a step, the result is also a well-typed term. *)\n\n(** **** Exercise: 2 stars (finish_preservation)  *)\nTheorem preservation : forall t t' T,\n  |- t \\in T ->\n  t ==> t' ->\n  |- t' \\in T.\n\n(** Complete the formal proof of the [preservation] property.  (Again,\n    make sure you understand the informal proof fragment in the\n    following exercise first.) *)\n\nProof with auto.\n  intros t t' T HT HE.\n  generalize dependent t'.\n  induction HT;\n         (* every case needs to introduce a couple of things *)\n         intros t' HE;\n         (* and we can deal with several impossible\n            cases all at once *)\n         try solve_by_invert.\n    - (* T_If *) inversion HE; subst; clear HE.\n      + (* ST_IFTrue *) assumption.\n      + (* ST_IfFalse *) assumption.\n      + (* ST_If *) apply T_If; try assumption.\n        apply IHHT1; assumption.\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advancedM (finish_preservation_informal)  *)\n(** Complete the following informal proof: *)\n\n(** _Theorem_: If [|- t \\in T] and [t ==> t'], then [|- t' \\in T]. *)\n\n(** _Proof_: By induction on a derivation of [|- t \\in T].\n\n      - If the last rule in the derivation is [T_If], then [t = if t1\n        then t2 else t3], with [|- t1 \\in Bool], [|- t2 \\in T] and [|- t3\n        \\in T].\n\n        Inspecting the rules for the small-step reduction relation and\n        remembering that [t] has the form [if ...], we see that the\n        only ones that could have been used to prove [t ==> t'] are\n        [ST_IfTrue], [ST_IfFalse], or [ST_If].\n\n           - If the last rule was [ST_IfTrue], then [t' = t2].  But we\n             know that [|- t2 \\in T], so we are done.\n\n           - If the last rule was [ST_IfFalse], then [t' = t3].  But we\n             know that [|- t3 \\in T], so we are done.\n\n           - If the last rule was [ST_If], then [t' = if t1' then t2\n             else t3], where [t1 ==> t1'].  We know [|- t1 \\in Bool] so,\n             by the IH, [|- t1' \\in Bool].  The [T_If] rule then gives us\n             [|- if t1' then t2 else t3 \\in T], as required.\n\n      - (* FILL IN HERE *)\n[] *)\n\n(** **** Exercise: 3 stars (preservation_alternate_proof)  *)\n(** Now prove the same property again by induction on the\n    _evaluation_ derivation instead of on the typing derivation.\n    Begin by carefully reading and thinking about the first few\n    lines of the above proofs to make sure you understand what\n    each one is doing.  The set-up for this proof is similar, but\n    not exactly the same. *)\n\nTheorem preservation' : forall t t' T,\n  |- t \\in T ->\n  t ==> t' ->\n  |- t' \\in T.\nProof with eauto.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The preservation theorem is often called _subject reduction_,\n    because it tells us what happens when the \"subject\" of the typing\n    relation is reduced.  This terminology comes from thinking of\n    typing statements as sentences, where the term is the subject and\n    the type is the predicate. *)\n\n(* ================================================================= *)\n(** ** Type Soundness *)\n\n(** Putting progress and preservation together, we see that a\n    well-typed term can never reach a stuck state.  *)\n\nDefinition multistep := (multi step).\nNotation \"t1 '==>*' t2\" := (multistep t1 t2) (at level 40).\n\nCorollary soundness : forall t t' T,\n  |- t \\in T ->\n  t ==>* t' ->\n  ~(stuck t').\nProof.\n  intros t t' T HT P. induction P; intros [R S].\n  destruct (progress x T HT); auto.\n  apply IHP.  apply (preservation x y T HT H).\n  unfold stuck. split; auto.   Qed.\n\n\n(* ################################################################# *)\n(** * Aside: the [normalize] Tactic *)\n\n(** When experimenting with definitions of programming languages\n    in Coq, we often want to see what a particular concrete term steps\n    to -- i.e., we want to find proofs for goals of the form [t ==>*\n    t'], where [t] is a completely concrete term and [t'] is unknown.\n    These proofs are quite tedious to do by hand.  Consider, for\n    example, reducing an arithmetic expression using the small-step\n    relation [astep]. *)\n\n\nTactic Notation \"print_goal\" :=\n  match goal with |- ?x => idtac x end.\nTactic Notation \"normalize\" :=\n  repeat (print_goal; eapply multi_step ;\n            [ (eauto 10; fail) | (instantiate; simpl)]);\n  apply multi_refl.\n\nExample step_example1'' :\n  tif (tiszero (tsucc tzero)) (tsucc tzero) (tpred (tsucc (tzero)))\n  ==>* tzero.\nProof.\n  normalize.\n  (* The [print_goal] in the [normalize] tactic shows\n     a trace of how the expression reduced...\n\n     (tif (tiszero (tsucc tzero)) (tsucc tzero) (tpred (tsucc tzero)) ==>* tzero)\n     (multi step (tif tfalse (tsucc tzero) (tpred (tsucc tzero))) tzero)\n     (multi step (tpred (tsucc tzero)) tzero)\n     (multi step tzero tzero)\n  *)\nQed.\n\n(** The [normalize] tactic also provides a simple way to calculate the\n    normal form of a term, by starting with a goal with an existentially\n    bound variable. *)\n\nExample step_example1''' : exists e',\n  tif (tiszero (tsucc tzero)) (tsucc tzero) (tpred (tsucc (tzero)))\n  ==>* e'.\nProof.\n  eapply ex_intro. normalize.\n(* This time, the trace is:\n\n  (tif (tiszero (tsucc tzero)) (tsucc tzero) (tpred (tsucc tzero)) ==>* ?e')\n  (multi step (tif tfalse (tsucc tzero) (tpred (tsucc tzero))) ?e')\n  (multi step (tpred (tsucc tzero)) ?e')\n  (multi step tzero ?e')\n\n   where ?e' is the variable ``guessed'' by eapply. *)\nQed.\n\n(** **** Exercise: 1 star (normalize_ex)  *)\nTheorem normalize_ex : exists e',\n  (tsucc (tpred (tpred tzero)))\n  ==>* e'.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (normalize_ex')  *)\n(** For comparison, prove it using [apply] instead of [eapply]. *)\n\nTheorem normalize_ex' : exists e',\n  (tsucc (tpred (tpred tzero)))\n  ==>* e'.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ================================================================= *)\n(** ** Additional Exercises *)\n\n(** **** Exercise: 2 stars, recommendedM (subject_expansion)  *)\n(** Having seen the subject reduction property, one might\n    wonder whether the opposity property -- subject _expansion_ --\n    also holds.  That is, is it always the case that, if [t ==> t']\n    and [|- t' \\in T], then [|- t \\in T]?  If so, prove it.  If\n    not, give a counter-example.  (You do not need to prove your\n    counter-example in Coq, but feel free to do so.)\n\n    (* FILL IN HERE *)\n[] *)\n\n(** **** Exercise: 2 starsM (variation1)  *)\n(** Suppose, that we add this new rule to the typing relation:\n<<\n      | T_SuccBool : forall t,\n           |- t \\in TBool ->\n           |- tsucc t \\in TBool\n>>\n   Which of the following properties remain true in the presence of\n   this rule?  For each one, write either \"remains true\" or\n   else \"becomes false.\" If a property becomes false, give a\n   counterexample.\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n[] *)\n\n(** **** Exercise: 2 starsM (variation2)  *)\n(** Suppose, instead, that we add this new rule to the [step] relation:\n<<\n      | ST_Funny1 : forall t2 t3,\n           (tif ttrue t2 t3) ==> t3\n>>\n   Which of the above properties become false in the presence of\n   this rule?  For each one that does, give a counter-example.\n\n[] *)\n\n(** **** Exercise: 2 stars, optional (variation3)  *)\n(** Suppose instead that we add this rule:\n<<\n      | ST_Funny2 : forall t1 t2 t2' t3,\n           t2 ==> t2' ->\n           (tif t1 t2 t3) ==> (tif t1 t2' t3)\n>>\n   Which of the above properties become false in the presence of\n   this rule?  For each one that does, give a counter-example.\n\n[] *)\n\n(** **** Exercise: 2 stars, optional (variation4)  *)\n(** Suppose instead that we add this rule:\n<<\n      | ST_Funny3 :\n          (tpred tfalse) ==> (tpred (tpred tfalse))\n>>\n   Which of the above properties become false in the presence of\n   this rule?  For each one that does, give a counter-example.\n\n[] *)\n\n(** **** Exercise: 2 stars, optional (variation5)  *)\n(** Suppose instead that we add this rule:\n<<\n      | T_Funny4 :\n            |- tzero \\in TBool\n>>\n   Which of the above properties become false in the presence of\n   this rule?  For each one that does, give a counter-example.\n\n[] *)\n\n(** **** Exercise: 2 stars, optional (variation6)  *)\n(** Suppose instead that we add this rule:\n<<\n      | T_Funny5 :\n            |- tpred tzero \\in TBool\n>>\n   Which of the above properties become false in the presence of\n   this rule?  For each one that does, give a counter-example.\n\n[] *)\n\n(** **** Exercise: 3 stars, optional (more_variations)  *)\n(** Make up some exercises of your own along the same lines as\n    the ones above.  Try to find ways of selectively breaking\n    properties -- i.e., ways of changing the definitions that\n    break just one of the properties and leave the others alone.\n[] *)\n\n(** **** Exercise: 1 starM (remove_predzero)  *)\n(** The reduction rule [ST_PredZero] is a bit counter-intuitive: we\n    might feel that it makes more sense for the predecessor of zero to\n    be undefined, rather than being defined to be zero.  Can we\n    achieve this simply by removing the rule from the definition of\n    [step]?  Would doing so create any problems elsewhere?\n\n(* FILL IN HERE *)\n[] *)\n\n(** **** Exercise: 4 stars, advancedM (prog_pres_bigstep)  *)\n(** Suppose our evaluation relation is defined in the big-step style.\n    What are the appropriate analogs of the progress and preservation\n    properties?  (You do not need to prove them.)\n\n(* FILL IN HERE *)\n[] *)\n\n(** $Date: 2016-12-20 11:35:30 -0500 (Tue, 20 Dec 2016) $ *)\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/5/extypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744806385543, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.6758984586938903}}
{"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(** Properties of addition. [add] is defined in [Init/Peano.v] as:\n<<\nFixpoint plus (n m:nat) : nat :=\n  match n with\n  | O => m\n  | S p => S (p + m)\n  end\nwhere \"n + m\" := (plus n m) : nat_scope.\n>>\n *)\n\nRequire Import Le.\nRequire Import Lt.\n\nOpen Local Scope nat_scope.\n\nImplicit Types m n p q : nat.\n\n(** * Zero is neutral \nDeprecated : Already in Init/Peano.v *)\nNotation plus_0_l := plus_O_n (only parsing).\nDefinition plus_0_r n := eq_sym (plus_n_O n).\n\n(** * Commutativity *)\n\nLemma plus_comm : forall n m, n + m = m + n.\nProof.\n  intros n m; elim n; simpl in |- *; auto with arith.\n  intros y H; elim (plus_n_Sm m y); auto with arith.\nQed.\nHint Immediate plus_comm: arith v62.\n\n(** * Associativity *)\n\nDefinition plus_Snm_nSm : forall n m, S n + m = n + S m:=\n plus_n_Sm.\n\nLemma plus_assoc : forall n m p, n + (m + p) = n + m + p.\nProof.\n  intros n m p; elim n; simpl in |- *; auto with arith.\nQed.\nHint Resolve plus_assoc: arith v62.\n\nLemma plus_permute : forall n m p, n + (m + p) = m + (n + p).\nProof.\n  intros; rewrite (plus_assoc m n p); rewrite (plus_comm m n); auto with arith.\nQed.\n\nLemma plus_assoc_reverse : forall n m p, n + m + p = n + (m + p).\nProof.\n  auto with arith.\nQed.\nHint Resolve plus_assoc_reverse: arith v62.\n\n(** * Simplification *)\n\nLemma plus_reg_l : forall n m p, p + n = p + m -> n = m.\nProof.\n  intros m p n; induction n; simpl in |- *; auto with arith.\nQed.\n\nLemma plus_le_reg_l : forall n m p, p + n <= p + m -> n <= m.\nProof.\n  induction p; simpl in |- *; auto with arith.\nQed.\n\nLemma plus_lt_reg_l : forall n m p, p + n < p + m -> n < m.\nProof.\n  induction p; simpl in |- *; auto with arith.\nQed.\n\n(** * Compatibility with order *)\n\nLemma plus_le_compat_l : forall n m p, n <= m -> p + n <= p + m.\nProof.\n  induction p; simpl in |- *; auto with arith.\nQed.\nHint Resolve plus_le_compat_l: arith v62.\n\nLemma plus_le_compat_r : forall n m p, n <= m -> n + p <= m + p.\nProof.\n  induction 1; simpl in |- *; auto with arith.\nQed.\nHint Resolve plus_le_compat_r: arith v62.\n\nLemma le_plus_l : forall n m, n <= n + m.\nProof.\n  induction n; simpl in |- *; auto with arith.\nQed.\nHint Resolve le_plus_l: arith v62.\n\nLemma le_plus_r : forall n m, m <= n + m.\nProof.\n  intros n m; elim n; simpl in |- *; auto with arith.\nQed.\nHint Resolve le_plus_r: arith v62.\n\nTheorem le_plus_trans : forall n m p, n <= m -> n <= m + p.\nProof.\n  intros; apply le_trans with (m := m); auto with arith.\nQed.\nHint Resolve le_plus_trans: arith v62.\n\nTheorem lt_plus_trans : forall n m p, n < m -> n < m + p.\nProof.\n  intros; apply lt_le_trans with (m := m); auto with arith.\nQed.\nHint Immediate lt_plus_trans: arith v62.\n\nLemma plus_lt_compat_l : forall n m p, n < m -> p + n < p + m.\nProof.\n  induction p; simpl in |- *; auto with arith.\nQed.\nHint Resolve plus_lt_compat_l: arith v62.\n\nLemma plus_lt_compat_r : forall n m p, n < m -> n + p < m + p.\nProof.\n  intros n m p H; rewrite (plus_comm n p); rewrite (plus_comm m p).\n  elim p; auto with arith.\nQed.\nHint Resolve plus_lt_compat_r: arith v62.\n\nLemma plus_le_compat : forall n m p q, n <= m -> p <= q -> n + p <= m + q.\nProof.\n  intros n m p q H H0.\n  elim H; simpl in |- *; auto with arith.\nQed.\n\nLemma plus_le_lt_compat : forall n m p q, n <= m -> p < q -> n + p < m + q.\nProof.\n  unfold lt in |- *. intros. change (S n + p <= m + q) in |- *. rewrite plus_Snm_nSm.\n  apply plus_le_compat; assumption.\nQed.\n\nLemma plus_lt_le_compat : forall n m p q, n < m -> p <= q -> n + p < m + q.\nProof.\n  unfold lt in |- *. intros. change (S n + p <= m + q) in |- *. apply plus_le_compat; assumption.\nQed.\n\nLemma plus_lt_compat : forall n m p q, n < m -> p < q -> n + p < m + q.\nProof.\n  intros. apply plus_lt_le_compat. assumption.\n  apply lt_le_weak. assumption.\nQed.\n\n(** * Inversion lemmas *)\n\nLemma plus_is_O : forall n m, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intro m; destruct m as [| n]; auto.\n  intros. discriminate H.\nQed.\n\nDefinition plus_is_one :\n  forall m n, m + n = 1 -> {m = 0 /\\ n = 1} + {m = 1 /\\ n = 0}.\nProof.\n  intro m; destruct m as [| n]; auto.\n  destruct n; auto.\n  intros.\n  simpl in H. discriminate H.\nDefined.\n\n(** * Derived properties *)\n\nLemma plus_permute_2_in_4 : forall n m p q, n + m + (p + q) = n + p + (m + q).\nProof.\n  intros m n p q.\n  rewrite <- (plus_assoc m n (p + q)). rewrite (plus_assoc n p q).\n  rewrite (plus_comm n p). rewrite <- (plus_assoc p n q). apply plus_assoc.\nQed.\n\n(** * Tail-recursive plus *)\n\n(** [tail_plus] is an alternative definition for [plus] which is\n    tail-recursive, whereas [plus] is not. This can be useful\n    when extracting programs. *)\n\nFixpoint tail_plus n m : nat :=\n  match n with\n    | O => m\n    | S n => tail_plus n (S m)\n  end.\n\nLemma plus_tail_plus : forall n m, n + m = tail_plus n m.\ninduction n as [| n IHn]; simpl in |- *; auto.\nintro m; rewrite <- IHn; simpl in |- *; auto.\nQed.\n\n(** * Discrimination *)\n\nLemma succ_plus_discr : forall n m, n <> S (plus m n).\nProof.\n  intros n m; induction n as [|n IHn].\n  discriminate.\n  intro H; apply IHn; apply eq_add_S; rewrite H; rewrite <- plus_n_Sm;\n    reflexivity.\nQed.\n\nLemma n_SSn : forall n, n <> S (S n).\nProof.\n  intro n; exact (succ_plus_discr n 1).\nQed.\n\nLemma n_SSSn : forall n, n <> S (S (S n)).\nProof.\n  intro n; exact (succ_plus_discr n 2).\nQed.\n\nLemma n_SSSSn : forall n, n <> S (S (S (S n))).\nProof.\n  intro n; exact (succ_plus_discr n 3).\nQed.\n", "meta": {"author": "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/Plus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117812622843, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.6758984533659562}}
{"text": "(** Coq coding by choukh, Oct 2021 **)\n\nRequire Import BBST.Axiom.Meta.\nRequire Import BBST.Axiom.Extensionality.\nRequire Import BBST.Axiom.Separation.\nRequire Import BBST.Axiom.Union.\nRequire Import BBST.Definition.Include.\nRequire Import BBST.Definition.Emptyset.\nRequire Import BBST.Definition.Intersect.\nRequire Import BBST.Definition.BinaryUnion.\nRequire Import BBST.Definition.BinaryIntersect.\nRequire Import BBST.Definition.Complement.\n\nLemma 并交吸收律 : ∀ A B, A ∪ (A ∩ B) = A.\nProof with auto.\n  intros. 外延... apply 二元并除去 in H as []...\n  apply 二元交除去 in H as []...\nQed.\n\nLemma 交并吸收律 : ∀ A B, A ∩ (A ∪ B) = A.\nProof with auto.\n  intros. 外延... apply 二元交除去 in H as []...\nQed.\n\nLemma 交并分配律 : ∀ A B C, (A ∩ B) ∪ C = (A ∪ C) ∩ (B ∪ C).\nProof with auto.\n  intros. 外延.\n  - apply 二元并除去 in H as []...\n    apply 二元交除去 in H as []...\n  - apply 二元交除去 in H as [];\n    apply 二元并除去 in H as [];\n    apply 二元并除去 in H0 as []...\nQed.\n\nLemma 并交分配律 : ∀ A B C, (A ∪ B) ∩ C = (A ∩ C) ∪ (B ∩ C).\nProof with auto.\n  intros. 外延.\n  - apply 二元交除去 in H as [].\n    apply 二元并除去 in H as []...\n  - apply 二元并除去 in H as [];\n    apply 二元交除去 in H as []...\nQed.\n\nLemma 并补分配律 : ∀ A B C, (A ∪ B) - C = (A - C) ∪ (B - C).\nProof.\n  intros. 外延.\n  - apply 分离除去 in H as [Hx Hx'].\n    apply 二元并除去 in Hx as [].\n    + apply 左并介入. now apply 分离介入.\n    + apply 右并介入. now apply 分离介入.\n  - apply 二元并除去 in H as [];\n    apply 分离除去 in H as [Hx Hx']; apply 分离介入; auto.\nQed.\n\nLemma 交补分配律 : ∀ A B C, (A ∩ B) - C = (A - C) ∩ (B - C).\nProof.\n  intros. 外延.\n  - apply 分离除去 in H as [Hx Hx'].\n    apply 二元交除去 in Hx as [].\n    apply 二元交介入; now apply 分离介入.\n  - apply 二元交除去 in H as [].\n    apply 分离除去 in H as [HxA HxC].\n    apply 分离之父集 in H0. apply 分离介入; auto.\nQed.\n\nCorollary 交补分配律_简化 : ∀ A B C, (A ∩ B) - C = A ∩ (B - C).\nProof.\n  intros. rewrite 交补分配律. 外延.\n  - apply 二元交除去 in H as []. apply 分离之父集 in H.\n    apply 二元交介入; auto.\n  - apply 二元交除去 in H as [H1 H2].\n    apply 分离除去 in H2 as [Hx Hx'].\n    apply 二元交介入; apply 分离介入; auto.\nQed.\n\nLemma 补并德摩根律 : ∀ A B C, C - (A ∪ B) = (C - A) ∩ (C - B).\nProof.\n  intros. 外延.\n  - apply 分离除去 in H as [Hx Hx'].\n    apply 二元交介入; apply 分离介入; auto.\n  - apply 二元交除去 in H as [H1 H2].\n    apply 分离除去 in H1 as [Hx Hx']. apply 分离之条件 in H2.\n    apply 分离介入; auto. now apply 二元并外介入.\nQed.\n\nLemma 补交德摩根律 : ∀ A B C, C - (A ∩ B) = (C - A) ∪ (C - B).\nProof.\n  intros. 外延.\n  - apply 分离除去 in H as [Hx Hx'].\n    apply 二元交外除去 in Hx' as [].\n    + apply 左并介入. now apply 分离介入.\n    + apply 右并介入. now apply 分离介入.\n  - apply 二元并除去 in H as [];\n    apply 分离除去 in H as [Hx Hx'];\n    apply 分离介入; auto; apply 二元交外介入; auto.\nQed.\n\nLemma 先补再并等于没补 : ∀ A B, A ∪ (B - A) = A ∪ B.\nProof with auto.\n  intros. 外延.\n  - apply 二元并除去 in H as []... apply 分离之父集 in H...\n  - apply 二元并除去 in H as []...\n    排中 (x ∈ A)... apply 右并介入. apply 分离介入...\nQed.\n\nLemma 先并再补等于没并 : ∀ A B, (A ∪ B) - A = B - A.\nProof with auto.\n  intros. 外延; apply 分离除去 in H as [].\n  - apply 二元并除去 in H as []. exfalso... apply 分离介入...\n  - apply 分离介入...\nQed.\n\nLemma 并自身之补得全集 : ∀ A S, A ⊆ S → A ∪ (S - A) = S.\nProof with auto.\n  intros. rewrite 先补再并等于没补. 外延...\n  apply 二元并除去 in H0 as []; auto.\nQed.\n\nLemma 交自身之补得空集 : ∀ A S, A ∩ (S - A) = ∅.\nProof.\n  intros. apply 空集介入. intros x H.\n  apply 二元交除去 in H as [H1 H2].\n  now apply 分离之条件 in H2.\nQed.\n", "meta": {"author": "choukh", "repo": "Baby-Set-Theory", "sha": "e41d9363ea2a657fc5c1286f92d25db062d4105f", "save_path": "github-repos/coq/choukh-Baby-Set-Theory", "path": "github-repos/coq/choukh-Baby-Set-Theory/Baby-Set-Theory-e41d9363ea2a657fc5c1286f92d25db062d4105f/Theory/BasicAlgebraOfSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012104, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.6758984529978441}}
{"text": "(** * Poly: Polymorphism and Higher-Order Functions *)\n\n(* Final reminder: Please do not put solutions to the exercises in\n   publicly accessible places.  Thank you!! *)\n\n(* Suppress some annoying warnings from Coq: *)\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Lists.\nSearch (evenb (S _)).\n(* ################################################################# *)\n(** * Polymorphism *)\n\n(** In this chapter weopt continue our development of basic\n    concepts of functional programming.  The critical new ideas are\n    _polymorphism_ (abstracting functions over the types of the data\n    they manipulate) and _higher-order functions_ (treating functions\n    as data).  We begin with polymorphism. *)\n\n(* ================================================================= *)\n(** ** Polymorphic Lists *)\n\n(** For the last chapter, we've been working with lists\n    containing just numbers.  Obviously, interesting programs also\n    need to be able to manipulate lists with elements from other\n    types -- lists of booleans, lists of lists, etc.  We _could_ just\n    define a new inductive datatype for each of these, for\n    example... *)\n\nInductive boollist : Type :=\n  | bool_nil\n  | bool_cons (b : bool) (l : boollist).\n\n(** ... but this would quickly become tedious, partly because we\n    have to make up different constructor names for each datatype, but\n    mostly because we would also need to define new versions of all\n    our list manipulating functions ([length], [rev], etc.) and all\n    their properties ([rev_length], [app_assoc], etc.) for each\n    new datatype definition. *)\n\n(** To avoid all this repetition, Coq supports _polymorphic_\n    inductive type definitions.  For example, here is a _polymorphic\n    list_ datatype. *)\n\nInductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\n(** This is exactly like the definition of [natlist] from the\n    previous chapter, except that the [nat] argument to the [cons]\n    constructor has been replaced by an arbitrary type [X], a binding\n    for [X] has been added to the function header on the first line,\n    and the occurrences of [natlist] in the types of the constructors\n    have been replaced by [list X].\n\n    What sort of thing is [list] itself?  A good way to think about it\n    is that the definition of [list] is a _function_ from [Type]s to\n    [Inductive] definitions; or, to put it more concisely, [list] is a\n    function from [Type]s to [Type]s.  For any particular type [X],\n    the type [list X] is the [Inductive]ly defined set of lists whose\n    elements are of type [X]. *)\n\nCheck list : Type -> Type.\n\n(** The parameter [X] in the definition of [list] automatically\n    becomes a parameter to the constructors [nil] and [cons] -- that\n    is, [nil] and [cons] are now polymorphic constructors; when we use\n    them, we must now provide a first argument that is the type of the\n    list they are building. For example, [nil nat] constructs the\n    empty list of type [nat]. *)\n\nCheck (nil nat) : list nat.\n\n(** Similarly, [cons nat] adds an element of type [nat] to a list of\n    type [list nat]. Here is an example of forming a list containing\n    just the natural number 3. *)\n\nCheck (cons nat 3 (nil nat)) : list nat.\n\n(** What might the type of [nil] be? We can read off the type\n    [list X] from the definition, but this omits the binding for [X]\n    which is the parameter to [list]. [Type -> list X] does not\n    explain the meaning of [X]. [(X : Type) -> list X] comes\n    closer. Coq's notation for this situation is [forall X : Type,\n    list X]. *)\n\nCheck nil : forall X : Type, list X.\n\n(** Similarly, the type of [cons] from the definition looks like\n    [X -> list X -> list X], but using this convention to explain the\n    meaning of [X] results in the type [forall X, X -> list X -> list\n    X]. *)\n\nCheck cons : forall X : Type, X -> list X -> list X.\n\n(** (A side note on notations: In .v files, the \"forall\" quantifier\n    is spelled out in letters.  In the generated HTML files and in the\n    way various IDEs show .v files, depending on the settings of their\n    display controls, [forall] is usually typeset as the standard\n    mathematical \"upside down A,\" though you'll still see the\n    spelled-out \"forall\" in a few places.  This is just a quirk of\n    typesetting -- there is no difference in meaning.) *)\n\n(** Having to supply a type argument for every single use of a\n    list constructor would be rather burdensome; we will soon see ways\n    of reducing this annotation burden. *)\n\nCheck (cons nat 2 (cons nat 1 (nil nat)))\n      : list nat.\n\n(** We can now go back and make polymorphic versions of all the\n    list-processing functions that we wrote before.  Here is [repeat],\n    for example: *)\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\n(** As with [nil] and [cons], we can use [repeat] by applying it\n    first to a type and then to an element of this type (and a number): *)\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity. Qed.\n\n(** To use [repeat] to build other kinds of lists, we simply\n    instantiate it with an appropriate type parameter: *)\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, standard (mumble_grumble) \n\n    Consider the following two inductively defined types. *)\n\nModule MumbleGrumble.\n\nInductive mumble : Type :=\n  | a\n  | b (x : mumble) (y : nat)\n  | c.\n\nInductive grumble (X:Type) : Type :=\n  | d (m : mumble)\n  | e (x : X).\n\n(** Which of the following are well-typed elements of [grumble X] for\n    some type [X]?  (Add YES or NO to each line.)\n      - [d (b a 5)]  NO -> d doit prendre un type X en premier argument puis un second argument de type mumble\n      - [d mumble (b a 5)] YES grumble mumble\n      - [d bool (b a 5)]      YES grumble bool\n      - [e bool true]         YES grumble bool\n      - [e mumble (b c 0)] YES grumble mumble\n      - [e bool (b c 0)]      NO mal typé\n      - [c]  NO -> il est bien typé de type mumble est pas grumble X*)            \n(* FILL IN HERE *)\nCheck grumble.\nCheck d.\nEnd MumbleGrumble.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_mumble_grumble : option (nat*string) := None.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Annotation Inference *)\n\n(** Let's write the definition of [repeat] again, but this time we\n    won't specify the types of any of the arguments.  Will Coq still\n    accept it? *)\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0        => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\n(** Indeed it will.  Let's see what type Coq has assigned to [repeat']: *)\n\nCheck repeat'\n  : forall X : Type, X -> nat -> list X.\nCheck repeat\n  : forall X : Type, X -> nat -> list X.\n\n(** It has exactly the same type as [repeat].  Coq was able to\n    use _type inference_ to deduce what the types of [X], [x], and\n    [count] must be, based on how they are used.  For example, since\n    [X] is used as an argument to [cons], it must be a [Type], since\n    [cons] expects a [Type] as its first argument; matching [count]\n    with [0] and [S] means it must be a [nat]; and so on.\n\n    This powerful facility means we don't always have to write\n    explicit type annotations everywhere, although explicit type\n    annotations can still be quite useful as documentation and sanity\n    checks, so we will continue to use them much of the time. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Argument Synthesis *)\n\n(** To use a polymorphic function, we need to pass it one or\n    more types in addition to its other arguments.  For example, the\n    recursive call in the body of the [repeat] function above must\n    pass along the type [X].  But since the second argument to\n    [repeat] is an element of [X], it seems entirely obvious that the\n    first argument can only be [X] -- why should we have to write it\n    explicitly?\n\n    Fortunately, Coq permits us to avoid this kind of redundancy.  In\n    place of any type argument we can write a \"hole\" [_], which can be\n    read as \"Please try to figure out for yourself what belongs here.\"\n    More precisely, when Coq encounters a [_], it will attempt to\n    _unify_ all locally available information -- the type of the\n    function being applied, the types of the other arguments, and the\n    type expected by the context in which the application appears --\n    to determine what concrete type should replace the [_].\n\n    This may sound similar to type annotation inference -- and, indeed,\n    the two procedures rely on the same underlying mechanisms.  Instead\n    of simply omitting the types of some arguments to a function, like\n\n      repeat' X x count : list X :=\n\n    we can also replace the types with holes\n\n      repeat' (X : _) (x : _) (count : _) : list X :=\n\n    to tell Coq to attempt to infer the missing information.\n\n    Using holes, the [repeat] function can be written like this: *)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n(** In this instance, we don't save much by writing [_] instead of\n    [X].  But in many cases the difference in both keystrokes and\n    readability is nontrivial.  For example, suppose we want to write\n    down a list containing the numbers [1], [2], and [3].  Instead of\n    this... *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...we can use holes to write this: *)\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ----------------------------------------------------------------- *)\n(** *** Implicit Arguments *)\n\n(** In fact, we can go further and even avoid writing [_]'s in most\n    cases by telling Coq _always_ to infer the type argument(s) of a\n    given function.\n\n    The [Arguments] directive specifies the name of the function (or\n    constructor) and then lists its argument names, with curly braces\n    around any arguments to be treated as implicit.  (If some\n    arguments of a definition don't have a name, as is often the case\n    for constructors, they can be marked with a wildcard pattern\n    [_].) *)\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\n(** Now, we don't have to supply type arguments at all: *)\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\n(** Alternatively, we can declare an argument to be implicit\n    when defining the function itself, by surrounding it in curly\n    braces instead of parens.  For example: *)\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0        => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n(** (Note that we didn't even have to provide a type argument to the\n    recursive call to [repeat'''].  Indeed, it would be invalid to\n    provide one, because Coq is not expecting it.)\n\n    We will use the latter style whenever possible, but we will\n    continue to use explicit [Argument] declarations for [Inductive]\n    constructors.  The reason for this is that marking the parameter\n    of an inductive type as implicit causes it to become implicit for\n    the type itself, not just for its constructors.  For instance,\n    consider the following alternative definition of the [list]\n    type: *)\n\nInductive list' {X:Type} : Type :=\n  | nil'\n  | cons' (x : X) (l : list').\n\n(** Because [X] is declared as implicit for the _entire_ inductive\n    definition including [list'] itself, we now have to write just\n    [list'] whether we are talking about lists of numbers or booleans\n    or anything else, rather than [list' nat] or [list' bool] or\n    whatever; this is a step too far. *)\n\n(** Let's finish by re-implementing a few other standard list\n    functions on our new polymorphic lists... *)\n\nFixpoint app {X : Type} (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity. Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Supplying Type Arguments Explicitly *)\n\n(** One small problem with declaring arguments [Implicit] is\n    that, once in a while, Coq does not have enough local information\n    to determine a type argument; in such cases, we need to tell Coq\n    that we want to give the argument explicitly just this time.  For\n    example, suppose we write this: *)\n\nFail Definition mynil := nil.\n\n(** (The [Fail] qualifier that appears before [Definition] can be\n    used with _any_ command, and is used to ensure that that command\n    indeed fails when executed. If the command does fail, Coq prints\n    the corresponding error message, but continues processing the rest\n    of the file.)\n\n    Here, Coq gives us an error because it doesn't know what type\n    argument to supply to [nil].  We can help it by providing an\n    explicit type declaration (so that Coq has more information\n    available when it gets to the \"application\" of [nil]): *)\n\nDefinition mynil : list nat := nil.\n\n(** Alternatively, we can force the implicit arguments to be explicit by\n   prefixing the function name with [@]. *)\n\nCheck @nil : forall X : Type, list X.\n\nDefinition mynil' := @nil nat.\n\n(** Using argument synthesis and implicit arguments, we can\n    define convenient notation for lists, as before.  Since we have\n    made the constructor type arguments implicit, Coq will know to\n    automatically infer these when we use the notations. *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** Now lists can be written just the way we'd hope: *)\n\nDefinition list123''' := [1; 2; 3].\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, standard, optional (poly_exercises) \n\n    Here are a few simple exercises, just like ones in the [Lists]\n    chapter, for practice with polymorphism.  Complete the proofs below. *)\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros X l.\n  induction 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  intros A l m n.\n  induction l.\n  - reflexivity.\n  - simpl.\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  intros X l1 l2.\n  induction l1.\n  - reflexivity.\n  - simpl.\n    rewrite IHl1.\n    reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (more_poly_exercises) \n\n    Here are some slightly more interesting ones... *)\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros X l1 l2.\n  induction l1 as [| x l1' IHl1'].\n  - simpl.\n    Search (_ ++ []).\n    rewrite -> app_nil_r.\n    reflexivity.\n  - simpl.\n    rewrite IHl1'.\n    Search ((_ ++ _ ) ++ _).\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(* ================================================================= *)\n(** ** Polymorphic Pairs *)\n\n(** Following the same pattern, the definition for pairs of\n    numbers that we gave in the last chapter can be generalized to\n    _polymorphic pairs_, often called _products_: *)\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\n\nArguments pair {X} {Y} _ _.\n\n(** As with lists, we make the type arguments implicit and define the\n    familiar concrete notation. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** We can also use the [Notation] mechanism to define the standard\n    notation for product _types_: *)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** (The annotation [: type_scope] tells Coq that this abbreviation\n    should only be used when parsing types, not when parsing\n    expressions.  This avoids a clash with the multiplication\n    symbol.) *)\n\n(** It is easy at first to get [(x,y)] and [X*Y] confused.\n    Remember that [(x,y)] is a _value_ built from two other values,\n    while [X*Y] is a _type_ built from two other types.  If [x] has\n    type [X] and [y] has type [Y], then [(x,y)] has type [X*Y]. *)\n\n(** The first and second projection functions now look pretty\n    much as they would in any functional programming language. *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\n(** The following function takes two lists and combines them\n    into a list of pairs.  In other functional languages, it is often\n    called [zip]; we call it [combine] for consistency with Coq's\n    standard library. *)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\n(** **** Exercise: 1 star, standard, optional (combine_checks) \n\n    Try answering the following questions on paper and\n    checking your answers in Coq:\n    - What is the type of [combine] (i.e., what does [Check\n      @combine] print?)\n    - What does\n\n        Compute (combine [1;2] [false;false;true;true]).\n\n      print?\n\n    [] *)\n\n(** **** Exercise: 2 stars, standard, especially useful (split) \n\n    The function [split] is the right inverse of [combine]: it takes a\n    list of pairs and returns a pair of lists.  In many functional\n    languages, it is called [unzip].\n\n    Fill in the definition of [split] below.  Make sure it passes the\n    given unit test. *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n  : (list X) * (list Y) :=\n  match l with\n  | [] => ([], [])\n  | (x,y)::l' =>\n    match split l' with\n      (l1,l2) => (x::l1, y::l2)\n    end\n  end.\n\nFixpoint split' {X Y : Type} (l : list (X*Y))\n  : (list X) * (list Y) :=\n  match l with\n  | [] => ([], [])\n  | (x,y)::l' => (x::fst(split l'), y::snd(split l'))\n  end.\n\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof.\n  reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Options *)\n\n(** Our last polymorphic type for now is _polymorphic options_,\n    which generalize [natoption] from the previous chapter.  (We put\n    the definition inside a module because the standard library\n    already defines [option] and it's this one that we want to use\n    below.) *)\n\nModule OptionPlayground.\n\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\n\nArguments Some {X} _.\nArguments None {X}.\n\nEnd OptionPlayground.\n\n(** We can now rewrite the [nth_error] function so that it works\n    with any type of lists. *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | nil => None\n  | a :: l' => match n with\n               | O => Some a\n               | S n' => nth_error l' n'\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, standard, optional (hd_error_poly) \n\n    Complete the definition of a polymorphic version of the\n    [hd_error] function from the last chapter. Be sure that it\n    passes the unit tests below. *)\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n  | [] => None\n  | x::_ => Some x\n  end.\n\n(** Once again, to force the implicit arguments to be explicit,\n    we can use [@] before the name of the function. *)\n\nCheck @hd_error : forall X : Type, list X -> option X.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Functions as Data *)\n\n(** Like most modern programming languages -- especially other\n    \"functional\" languages, including OCaml, Haskell, Racket, Scala,\n    Clojure, etc. -- Coq treats functions as first-class citizens,\n    allowing them to be passed as arguments to other functions,\n    returned as results, stored in data structures, etc. *)\n\n(* ================================================================= *)\n(** ** Higher-Order Functions *)\n\n(** Functions that manipulate other functions are often called\n    _higher-order_ functions.  Here's a simple one: *)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\n(** The argument [f] here is itself a function (from [X] to\n    [X]); the body of [doit3times] applies [f] three times to some\n    value [n]. *)\n\nCheck @doit3times : forall X : Type, (X -> X) -> X -> X.\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity. Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\n\n(* ================================================================= *)\n(** ** Filter *)\n\n(** Here is a more useful higher-order function, taking a list\n    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])\n    and \"filtering\" the list, returning a new list containing just\n    those elements for which the predicate returns [true]. *)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X) : (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\n(** For example, if we apply [filter] to the predicate [evenb]\n    and a list of numbers [l], it returns a list containing just the\n    even members of [l]. *)\n\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity. Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  (length l) =? 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\n(** We can use [filter] to give a concise version of the\n    [countoddmembers] function from the [Lists] chapter. *)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity. Qed.\n\n(* ================================================================= *)\n(** ** Anonymous Functions *)\n\n(** It is arguably a little sad, in the example just above, to\n    be forced to define the function [length_is_1] and give it a name\n    just to be able to pass it as an argument to [filter], since we\n    will probably never use it again.  Moreover, this is not an\n    isolated example: when using higher-order functions, we often want\n    to pass as arguments \"one-off\" functions that we will never use\n    again; having to give each of these functions a name would be\n    tedious.\n\n    Fortunately, there is a better way.  We can construct a function\n    \"on the fly\" without declaring it at the top level or giving it a\n    name. *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity. Qed.\n\n(** The expression [(fun n => n * n)] can be read as \"the function\n    that, given a number [n], yields [n * n].\" *)\n\n(** Here is the [filter] example, rewritten to use an anonymous\n    function. *)\n\nExample test_filter2':\n    filter (fun l => (length l) =? 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, standard (filter_even_gt7) \n\n    Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n    filter (fun n => andb (evenb n) (leb 7 n)) l.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity. Qed.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (partition) \n\n    Use [filter] to write a Coq function [partition]:\n\n      partition : forall X : Type,\n                  (X -> bool) -> list X -> list X * list X\n\n   Given a set [X], a predicate of type [X -> bool] and a [list X],\n   [partition] should return a pair of lists.  The first member of the\n   pair is the sublist of the original list containing the elements\n   that satisfy the test, and the second is the sublist containing\n   those that fail the test.  The order of elements in the two\n   sublists should be the same as their order in the original list. *)\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X :=\n    (filter test l, filter (fun x => negb (test x)) l).\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Map *)\n\n(** Another handy higher-order function is called [map]. *)\n\nFixpoint map {X Y: Type} (f:X->Y) (l:list X) : (list Y) :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]\n    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has\n    been applied to each element of [l] in turn.  For example: *)\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\n(** The element types of the input and output lists need not be\n    the same, since [map] takes _two_ type arguments, [X] and [Y]; it\n    can thus be applied to a list of numbers and a function from\n    numbers to booleans to yield a list of booleans: *)\n\nExample test_map2:\n  map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity. Qed.\n\n(** It can even be applied to a list of numbers and\n    a function from numbers to _lists_ of booleans to\n    yield a _list of lists_ of booleans: *)\n\nExample test_map3:\n    map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 3 stars, standard (map_rev) \n\n    Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\nLemma map_fct_comm : forall (X Y: Type) (f:X->Y)(l: list X) (x:X),\n     map f (l ++ [x]) = map f l ++ [f x].\nProof.\n intros X Y f l x.\n induction l as [| n l'].\n - simpl. reflexivity.\n - simpl. rewrite -> IHl'.\n   reflexivity. Qed.\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 [| x l1' IHl1'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHl1'.\n           rewrite -> map_fct_comm.\n           reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, especially useful (flat_map) \n\n    The function [map] maps a [list X] to a [list Y] using a function\n    of type [X -> Y].  We can define a similar function, [flat_map],\n    which maps a [list X] to a [list Y] using a function [f] of type\n    [X -> list Y].  Your definition should work by 'flattening' the\n    results of [f], like so:\n\n        flat_map (fun n => [n;n+1;n+2]) [1;5;10]\n      = [1; 2; 3; 5; 6; 7; 10; 11; 12].\n*)\n\nFixpoint flat_map {X Y: Type} (f: X -> list Y) (l: list X)\n                   : (list Y) :=\n match l with\n | nil => nil\n | h :: t => app (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].\n  Proof. reflexivity. Qed.\n\n(** Lists are not the only inductive type for which [map] makes sense.\n    Here is a [map] for the [option] type: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\n(** **** Exercise: 2 stars, standard, optional (implicit_args) \n\n    The definitions and uses of [filter] and [map] use implicit\n    arguments in many places.  Replace the curly braces around the\n    implicit arguments with parentheses, and then fill in explicit\n    type parameters where necessary and use Coq to check that you've\n    done so correctly.  (This exercise is not to be turned in; it is\n    probably easiest to do it on a _copy_ of this file that you can\n    throw away afterwards.)\n*)\n(** [] *)\n\n(* ================================================================= *)\n(** ** Fold *)\n\n(** An even more powerful higher-order function is called\n    [fold].  This function is the inspiration for the \"[reduce]\"\n    operation that lies at the heart of Google's map/reduce\n    distributed programming framework. *)\n\nFixpoint fold {X Y: Type} (f: X->Y->Y) (l: list X) (b: Y)\n                         : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(** Intuitively, the behavior of the [fold] operation is to\n    insert a given binary operator [f] between every pair of elements\n    in a given list.  For example, [ fold plus [1;2;3;4] ] intuitively\n    means [1+2+3+4].  To make this precise, we also need a \"starting\n    element\" that serves as the initial second input to [f].  So, for\n    example,\n\n       fold plus [1;2;3;4] 0\n\n    yields\n\n       1 + (2 + (3 + (4 + 0))).\n\n    Some more examples: *)\n\nCheck (fold andb) : list bool -> bool -> bool.\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, advanced (fold_types_different) \n\n    Observe that the type of [fold] is parameterized by _two_ type\n    variables, [X] and [Y], and the parameter [f] is a binary operator\n    that takes an [X] and a [Y] and returns a [Y].  Can you think of a\n    situation where it would be useful for [X] and [Y] to be\n    different? *)\n\n(* Oui, dans la situation ou on veut  faire une operation arithmetique sur les nombres\n   avec differents type tel que  float et integer par exemple *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_types_different : option (nat*string) := None.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Functions That Construct Functions *)\n\n(** Most of the higher-order functions we have talked about so\n    far take functions as arguments.  Let's look at some examples that\n    involve _returning_ functions as the results of other functions.\n    To begin, here is a function that takes a value [x] (drawn from\n    some type [X]) and returns a function from [nat] to [X] that\n    yields [x] whenever it is called, ignoring its [nat] argument. *)\n\nDefinition constfun {X: Type} (x: X) : nat->X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** In fact, the multiple-argument functions we have already\n    seen are also examples of passing functions as data.  To see why,\n    recall the type of [plus]. *)\n\nCheck plus : nat -> nat -> nat.\n\n(** Each [->] in this expression is actually a _binary_ operator\n    on types.  This operator is _right-associative_, so the type of\n    [plus] is really a shorthand for [nat -> (nat -> nat)] -- i.e., it\n    can be read as saying that \"[plus] is a one-argument function that\n    takes a [nat] and returns a one-argument function that takes\n    another [nat] and returns a [nat].\"  In the examples above, we\n    have always applied [plus] to both of its arguments at once, but\n    if we like we can supply just the first.  This is called _partial\n    application_. *)\n\nDefinition plus3 := plus 3.\nCheck plus3 : nat -> nat.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity. Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity. Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity. Qed.\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\nModule Exercises.\n\n(** **** Exercise: 2 stars, standard (fold_length) \n\n    Many common functions on lists can be implemented in terms of\n    [fold].  For example, here is an alternative definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length].  (Hint: It may help to\n    know that [reflexivity] simplifies expressions a bit more\n    aggressively than [simpl] does -- i.e., you may find yourself in a\n    situation where [simpl] does nothing but [reflexivity] solves the\n    goal.) *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros X l.\n  induction l as [| n l'].\n  - reflexivity.\n  - simpl. rewrite <- IHl'.\n     reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (fold_map) \n\n    We can also define [map] in terms of [fold].  Finish [fold_map]\n    below. *)\n\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y := \n   fold (fun x tail=> f(x):: tail ) l [].\n\n\nExample test_map1: fold_map ( fun x => x*x )[2;0;2] = [4;0;4].\nProof. reflexivity. Qed.\n\nExample mytest2: fold_map (fun x => x * x )[] = [].\nProof. reflexivity. Qed.\n\n\n\n(** Write down a theorem [fold_map_correct] in Coq stating that\n   [fold_map] is correct, and prove it.  (Hint: again, remember that\n   [reflexivity] simplifies expressions a bit more aggressively than\n   [simpl].) *)\n\n\n\nTheorem fold_map_correct : forall X Y (l : list X) (f: X -> Y),\n  fold_map f l = map f l.\n  Proof. \n  intros X Y l f.\n  induction l as [| n l'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHl'.\n    reflexivity. Qed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_map : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (currying) \n\n    In Coq, a function [f : A -> B -> C] really has the type [A\n    -> (B -> C)].  That is, if you give [f] a value of type [A], it\n    will give you function [f' : B -> C].  If you then give [f'] a\n    value of type [B], it will return a value of type [C].  This\n    allows for partial application, as in [plus3].  Processing a list\n    of arguments with functions that return functions is called\n    _currying_, in honor of the logician Haskell Curry.\n\n    Conversely, we can reinterpret the type [A -> B -> C] as [(A *\n    B) -> C].  This is called _uncurrying_.  With an uncurried binary\n    function, both arguments must be given at once as a pair; there is\n    no partial application. *)\n\n(** We can define currying as follows: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** As an exercise, define its inverse, [prod_uncurry].  Then prove\n    the theorems below to show that the two are inverses. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z :=  f (fst p) (snd p).\n\n\n(** As a (trivial) example of the usefulness of currying, we can use it\n    to shorten one of the examples that we saw above: *)\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\n(** Thought exercise: before running the following commands, can you\n    calculate the types of [prod_curry] and [prod_uncurry]? *)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\nintros X Y Z f x y.\n  reflexivity. Qed.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros X Y Z f p.\n  destruct p as [x y].  reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (nth_error_informal) \n\n    Recall the definition of the [nth_error] function:\n\n   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n     match l with\n     | [] => None\n     | a :: l' => if n =? O then Some a else nth_error l' (pred n)\n     end.\n\n   Write an informal proof of the following theorem:\n\n   forall X l n, length l = n -> @nth_error X l n = None\n*)\n(* THéorème : Pour tous listes de types X [l] et n de type nat, length l = n -> @nth_error X l n = None.\n\npreuve  : Par induction sur [l].\n\n  - premièrement, on suppose que [l = []]. Et on doit montre que\n\n      length [] = n -> nth_error X [] n = None.\n\n      Ce qui est vraie de la definition de [nth_error]. \n      Si 0 = n l'egalite None = None est toujours vraie.\n  \n  - Secondement, on suppose que [l = n::l'], avec\n\n *) \n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_proof : option (nat*string) := None.\n(** [] *)\n\n(** The following exercises explore an alternative way of defining\n    natural numbers, using the so-called _Church numerals_, named\n    after mathematician Alonzo Church.  We can represent a natural\n    number [n] as a function that takes a function [f] as a parameter\n    and returns [f] iterated [n] times. *)\n\nModule Church.\nDefinition cnat := forall X : Type, (X -> X) -> X -> X.\n\n(** Let's see how to write some numbers with this notation. Iterating\n    a function once should be the same as just applying it.  Thus: *)\n\nDefinition one : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** Similarly, [two] should apply [f] twice to its argument: *)\n\nDefinition two : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** Defining [zero] is somewhat trickier: how can we \"apply a function\n    zero times\"?  The answer is actually simple: just return the\n    argument untouched. *)\n\nDefinition zero : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(** More generally, a number [n] can be written as [fun X f x => f (f\n    ... (f x) ...)], with [n] occurrences of [f].  Notice in\n    particular how the [doit3times] function we've defined previously\n    is actually just the Church representation of [3]. *)\n\nDefinition three : cnat := @doit3times.\n\n(** Complete the definitions of the following functions. Make sure\n    that the corresponding unit tests pass by proving them with\n    [reflexivity]. *)\n\n(** **** Exercise: 1 star, advanced (church_succ)  *)\n\n(** Successor of a natural number: given a Church numeral [n],\n    the successor [succ n] is a function that iterates its\n    argument once more than [n]. *)\nDefinition succ (n : cnat) : cnat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample succ_1 : succ zero = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample succ_2 : succ one = two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample succ_3 : succ two = three.\nProof. (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (church_plus)  *)\n\n(** Addition of two natural numbers: *)\nDefinition plus (n m : cnat) : cnat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample plus_1 : plus zero one = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample plus_2 : plus two three = plus three two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (church_mult)  *)\n\n(** Multiplication: *)\nDefinition mult (n m : cnat) : cnat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample mult_1 : mult one one = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample mult_2 : mult zero (plus three three) = zero.\nProof. (* FILL IN HERE *) Admitted.\n\nExample mult_3 : mult two three = plus three three.\nProof. (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (church_exp)  *)\n\n(** Exponentiation: *)\n\n(** (_Hint_: Polymorphism plays a crucial role here.  However,\n    choosing the right type to iterate over can be tricky.  If you hit\n    a \"Universe inconsistency\" error, try iterating over a different\n    type.  Iterating over [cnat] itself is usually problematic.) *)\n\nDefinition exp (n m : cnat) : cnat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample exp_1 : exp two two = plus two two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample exp_2 : exp three zero = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample exp_3 : exp three two = plus (mult two (mult two two)) one.\nProof. (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\nEnd Church.\nEnd Exercises.\n\n(* 2020-09-09 20:51 *)\n", "meta": {"author": "JeanDeboutGat", "repo": "Logique-Plus", "sha": "f27e260848b281cb46845d9f5352c18440706d8d", "save_path": "github-repos/coq/JeanDeboutGat-Logique-Plus", "path": "github-repos/coq/JeanDeboutGat-Logique-Plus/Logique-Plus-f27e260848b281cb46845d9f5352c18440706d8d/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312006227324, "lm_q2_score": 0.8577680977182187, "lm_q1q2_score": 0.6758622470909933}}
{"text": "(* Exercise 29 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\nTheorem exercise_029 : ~A -> (~(A \\/ ~B) \\/ (~A /\\ ~B)).\nProof.\nimp_i a1.\ndis_e (B \\/ ~B) a2 a2.\nLEM.\ndis_i1.\nneg_i (1=1) a3.\ndis_e (A \\/ ~B) a4 a4.\nhyp a3.\nneg_e A.\nhyp a1.\nhyp a4.\nneg_e B.\nhyp a4.\nhyp a2.\nlin_solve.\ndis_i2.\ncon_i.\nhyp a1.\nhyp a2.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop029.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6758588217157777}}
{"text": "(* Exercise 25 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\nTheorem exercise_025 : A -> (~B \\/ (A /\\ B)).\nProof.\nimp_i Sigma.\ndis_e (B \\/ ~B) G H.\nLEM.\ndis_i2.\ncon_i.\nhyp Sigma.\nhyp G.\ndis_i1.\nhyp H.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak10/Taak10_prop025.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6758588188317746}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Lia.\n\nFrom Undecidability.Shared.Libs.DLW \n  Require Import utils list_bool pos vec subcode sss.\n\nFrom Undecidability.MinskyMachines.MMA\n  Require Import mma_defs mma_utils.\n\nSet Implicit Arguments.\nSet Default Goal Selector \"!\".\n\nTactic Notation \"rew\" \"length\" := autorewrite with length_db.\n\n#[local] Notation \"e #> x\" := (vec_pos e x).\n#[local] Notation \"e [ v / x ]\" := (vec_change e x v).\n\n#[local] Notation \"P // s -+> t\" := (sss_progress (@mma_sss _) P s t).\n#[local] Notation \"P // s ->> t\" := (sss_compute (@mma_sss _) P s t).\n\n(* Utils for Binary Stack Machines simulation *)\n\nSection Minsky_Machine_alt_utils_BSM.\n\n  Variable (n : nat).\n\n  Ltac dest x y := destruct (pos_eq_dec x y) as [ | ]; [ subst x | ]; rew vec.\n\n  Hint Resolve subcode_refl : core.\n\n  Notation JUMPₐ := mma_jump.\n  Notation TRANSFERTₐ := mma_transfert.\n  Notation MULT_CSTₐ := mma_mult_cst.\n\n  Hint Rewrite mma_jump_length \n               mma_transfert_length \n               mma_mult_cst_length : length_db.\n\n  Section mma_div2_branch.\n\n    Variable (x q : pos n) (Hxq : x <> q) (i j0 j1 : nat).\n\n    Definition mma_div2_branch :=\n           DECₐ x (3+i)\n        :: JUMPₐ j0 x\n        ++ DECₐ x (6+i)\n        :: JUMPₐ j1 x\n        ++ INCₐ q\n        :: JUMPₐ i x.\n\n    Fact mma_div2_branch_length : length mma_div2_branch = 9.\n    Proof. unfold mma_div2_branch; rew length; auto. Qed.\n\n    Local Fact mma_div2_branch_2k k v st :\n            v#>x = 2*k\n         -> st = (j0,v[0/x][(k+(v#>q))/q])\n         -> (i,mma_div2_branch) // (i,v) -+> st.\n    Proof using Hxq.\n      revert v st; induction k as [ | k IHk ]; intros v st H1 ->; unfold mma_div2_branch.\n      + mma sss DEC zero with x (3+i).\n        apply subcode_sss_compute with (P := (1+i,JUMPₐ j0 x)); auto.\n        simpl in H1; rewrite <- H1 at 3; simpl; rewrite !vec_change_same.\n        apply mma_jump_spec.\n      + replace (2*S k) with (S (S (2*k))) in H1 by lia.\n        mma sss DEC S with x (3+i) (S (2*k)).\n        mma sss DEC S with x (6+i) (2*k); rew vec.\n        mma sss INC with q; rew vec.\n        apply subcode_sss_compute_trans with (P := (7+i,JUMPₐ i  x)) (st2 := (i,v[(2*k)/x][(S (v#>q))/q])); auto.\n        * apply sss_progress_compute, mma_jump_progress; auto.\n        * apply sss_progress_compute, IHk; rew vec.\n          f_equal; apply vec_pos_ext; intros p; dest p x; dest p q; lia.\n    Qed.\n\n    Local Fact mma_div2_branch_2k1 k v st :\n           v#>x = 2*k+1\n         -> st = (j1,v[0/x][(k+(v#>q))/q])\n         -> (i,mma_div2_branch) // (i,v) -+> st.\n    Proof using Hxq.\n      revert v st; induction k as [ | k IHk ]; intros v st H1 ->; unfold mma_div2_branch.\n      + mma sss DEC S with x (3+i) 0.\n        mma sss DEC zero with x (6+i); rew vec.\n        apply subcode_sss_compute with (P := (4+i,JUMPₐ j1 x)); auto.\n        simpl plus.\n        apply sss_progress_compute, mma_jump_progress; auto.\n        apply vec_pos_ext; intros p; dest p x; dest p q; lia.\n      + replace (2*S k+1) with (S (S (2*k+1))) in H1 by lia.\n        mma sss DEC S with x (3+i) (S (2*k+1)).\n        mma sss DEC S with x (6+i) (2*k+1); rew vec.\n        mma sss INC with q; rew vec.\n        apply subcode_sss_compute_trans with (P := (7+i,JUMPₐ i  x)) (st2 := (i,v[(2*k+1)/x][(S (v#>q))/q])); auto.\n        * apply sss_progress_compute, mma_jump_progress; auto.\n        * apply sss_progress_compute, IHk; rew vec.\n          f_equal. \n          apply vec_pos_ext; intros p; dest p x; dest p q; lia.\n    Qed.\n\n    (** mma_div2_branch performs an Euclidean division of v#>x\n        by 2, adding the quotient to v#>q and jumping to j[r]\n        where r is the remainder *)\n\n    Fact mma_div2_branch_progress v st :\n          let (k,b) := div2 (v#>x) in \n          st = (if b then j1 else j0,v[0/x][(k+(v#>q))/q])\n       -> (i,mma_div2_branch) // (i,v) -+> st.\n    Proof using Hxq.\n      generalize (div2_spec (v#>x)).\n      destruct (div2 (v#>x)) as (k,[]); intros Hv ->.\n      + apply mma_div2_branch_2k1 with k; auto.\n      + apply mma_div2_branch_2k with k; auto.\n    Qed.\n\n  End mma_div2_branch.\n\n  Notation DIV2ₐ := mma_div2_branch.\n\n  Hint Rewrite mma_div2_branch_length : length_db.\n\n  Fixpoint stack_enc (s : list bool) : nat :=\n    match s with \n      | nil     => 1\n      | One::s  => 1+2*stack_enc s\n      | Zero::s =>   2*stack_enc s\n    end.\n\n  Fact stack_enc_S s : { k | stack_enc s = S k }.\n  Proof.\n    induction s as [ | [] s (k & Hk) ].\n    + exists 0; auto.\n    + exists (2*stack_enc s); auto.\n    + exists (S (2*k)); simpl; lia.\n  Qed.\n\n  Section mma_push.\n\n    Variables (src zero : pos n) \n              (Hsz : src <> zero) \n              (i : nat).\n\n    Definition mma_push_Zero := \n    (*    i *)  TRANSFERTₐ src zero i ++ \n    (*  3+i *)  MULT_CSTₐ zero src 2 (3+i).\n \n    Fact mma_push_Zero_length : length mma_push_Zero = 10.\n    Proof. reflexivity. Qed.\n\n    Fact mma_push_Zero_progress s v :\n         v#>zero = 0\n      -> v#>src  = stack_enc s\n      -> (i,mma_push_Zero) // (i,v) -+> (10+i,v[(stack_enc (Zero::s))/src]).\n    Proof using Hsz.\n      intros H1 H2.\n      unfold mma_push_Zero.\n      apply sss_progress_trans with (st2 := (3+i,v[0/src][(v#>src)/zero])).\n      + apply subcode_sss_progress with (P := (i,TRANSFERTₐ src zero i)); auto.\n        apply mma_transfert_progress; auto.\n        do 2 f_equal; lia.\n      + apply subcode_sss_progress with (P := (3+i,MULT_CSTₐ zero src 2 (3+i))); auto.\n        apply mma_mult_cst_progress; auto.\n        f_equal; rew vec.\n        apply vec_pos_ext; intros p.\n        dest p src; simpl; try lia. \n        dest p zero.\n    Qed.\n\n    Definition mma_push_One := mma_push_Zero ++ INCₐ src :: nil.\n\n    Fact mma_push_One_length : length mma_push_One = 11.\n    Proof. reflexivity. Qed.\n\n    Hint Rewrite mma_push_Zero_length : length_db.\n\n    Fact mma_push_One_progress s v :\n         v#>zero = 0\n      -> v#>src  = stack_enc s\n      -> (i,mma_push_One) // (i,v) -+> (11+i,v[(stack_enc (One::s))/src]).\n    Proof using Hsz.\n      intros H1 H2.\n      unfold mma_push_One.\n      apply sss_progress_trans with (10+i,v[(stack_enc (Zero::s))/src]).\n      + apply subcode_sss_progress with (P := (i,mma_push_Zero)); auto.\n        apply mma_push_Zero_progress; auto.\n      + mma sss INC with src.\n        mma sss stop; f_equal; rew vec.\n    Qed.\n\n  End mma_push.\n\n  Section mma_pop.\n\n    Variables (src zero : pos n) (Hsz : src <> zero) (i j0 j1 je : nat).\n\n    Local Fact Hzs : zero <> src.\n    Proof using Hsz. auto. Qed.\n\n    Hint Resolve Hzs : core.\n\n    Let src' := src.\n \n    Definition mma_pop :=\n    (*     i *)  TRANSFERTₐ src zero i ++\n    (*   3+i *)  DIV2ₐ zero src (3+i) j0 (12+i) ++\n    (*  12+i *)  DECₐ src (16+i) ::\n    (*  13+i *)  INCₐ src ::\n    (*  14+i *)  JUMPₐ je src ++\n    (*  16+i *)  INCₐ src' ::\n    (*  17+i *)  JUMPₐ j1 src.\n\n    Fact mma_pop_length : length mma_pop = 19.\n    Proof. reflexivity. Qed.\n\n    Fact mma_pop_void_progress v :\n         v#>zero = 0\n      -> v#>src  = stack_enc nil \n      -> (i,mma_pop) // (i,v) -+> (je,v).\n    Proof using Hsz.\n      intros H1 H2; unfold mma_pop.\n      apply sss_progress_trans with (st2 := (3+i,v[0/src][(v#>src)/zero])).\n      1:{ apply subcode_sss_progress with (P := (i,TRANSFERTₐ src zero i)); auto.\n          apply mma_transfert_progress; auto.\n          do 2 f_equal; lia. }\n      apply sss_progress_trans with (st2 := (12+i,v[0/src][0/zero])).\n      1:{ apply subcode_sss_progress with (P := (3+i,DIV2ₐ zero src (3+i) j0 (12 + i))); auto.\n          simpl in H2. \n          generalize (mma_div2_branch_progress Hzs (3+i) j0 (12+i) (v[0/src][1/zero])); rew vec; intros H3.\n          simpl div2 in H3.\n          rewrite H2; apply H3; f_equal; simpl; rew vec.\n          apply vec_pos_ext; intros p; dest p src. }\n      mma sss DEC zero with src (16+i); rew vec.\n      mma sss INC with src; rew vec.\n      apply subcode_sss_compute with (P := (14+i,JUMPₐ je src)); auto.\n      apply sss_progress_compute, mma_jump_progress.\n      apply vec_pos_ext; intros p; dest p src; dest p zero.\n    Qed.\n\n    Fact mma_pop_One_progress v s:\n         v#>zero = 0\n      -> v#>src  = stack_enc (One::s) \n      -> (i,mma_pop) // (i,v) -+> (j1,v[(stack_enc s)/src]).\n    Proof using Hsz.\n      intros H1 H2; unfold mma_pop.\n      apply sss_progress_trans with (st2 := (3+i,v[0/src][(v#>src)/zero])).\n      1:{ apply subcode_sss_progress with (P := (i,TRANSFERTₐ src zero i)); auto.\n          apply mma_transfert_progress; auto.\n          do 2 f_equal; lia. }\n      apply sss_progress_trans with (st2 := (12+i,v[(stack_enc s)/src][0/zero])).\n      1:{ apply subcode_sss_progress with (P := (3+i,DIV2ₐ zero src (3+i) j0 (12 + i))); auto. \n          match goal with |- _ // _ -+> ?st => \n            generalize (mma_div2_branch_progress Hzs (3+i) j0 (12+i) (v[0/src][(2*stack_enc s+1)/zero]) st)\n          end. \n          rew vec; intros H3. \n          rewrite div2_2p1 in H3.\n          rewrite (Nat.add_comm _ 1) in H3.\n          rewrite H2.\n          apply H3; f_equal; simpl; rew vec.\n          apply vec_pos_ext; intros p; dest p src; dest p zero. }\n      destruct (stack_enc_S s) as (k & Hk).\n      mma sss DEC S with src (16+i) k; rew vec.\n      mma sss INC with src'; rew vec.\n      apply subcode_sss_compute with (P := (17+i,JUMPₐ j1 src)); auto.\n      apply sss_progress_compute, mma_jump_progress.\n      unfold src'; apply vec_pos_ext; intros p; dest p src; dest p zero.\n    Qed.\n\n    Fact mma_pop_Zero_progress v s:\n         v#>zero = 0 \n      -> v#>src  = stack_enc (Zero::s) \n      -> (i,mma_pop) // (i,v) -+> (j0,v[(stack_enc s)/src]).\n    Proof using Hsz.\n      intros H1 H2; unfold mma_pop.\n      apply sss_progress_trans with (st2 := (3+i,v[0/src][(v#>src)/zero])).\n      1:{ apply subcode_sss_progress with (P := (i,TRANSFERTₐ src zero i)); auto.\n          apply mma_transfert_progress; auto.\n          do 2 f_equal; lia. }\n      apply subcode_sss_progress with (P := (3+i,DIV2ₐ zero src (3+i) j0 (12 + i))); auto.\n      match goal with |- _ // _ -+> ?st => \n        generalize (mma_div2_branch_progress Hzs (3+i) j0 (12+i) (v[0/src][(2*stack_enc s)/zero]) st)\n      end.\n      rew vec; intros H3. \n      rewrite div2_2p0 in H3.\n      rewrite (Nat.add_comm _ 0) in H3.\n      rewrite H2.\n      apply H3; f_equal.\n      apply vec_pos_ext; intros p; dest p src; dest p zero.\n    Qed.\n\n  End mma_pop.\n\nEnd Minsky_Machine_alt_utils_BSM.\n\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/MMA/mma_utils_bsm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6758094040676043}}
{"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(*                                                                          *)\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_Square.v                               *)\n(****************************************************************************)\nRequire Export Lib_Exp.\n\nDefinition Square (n : nat) := n * n.\n\nLemma Square_exp_2 : forall n : nat, Square (exp_2 n) = exp_2 (2 * n).\nintro.\nunfold Square in |- *.\nelim exp_2_n_plus_m.\nrewrite plus_mult; reflexivity.\nQed.\nHint Resolve Square_exp_2.\n\n\n\nLemma eq_Square_exp_n : forall n : nat, Square n = exp_n n 2.\nunfold Square in |- *.\nsimpl in |- *.\nintro; elim (mult_comm 1 n); simpl in |- *; auto with arith.\nQed.\nHint Resolve eq_Square_exp_n.\n\nLemma Square_inc : forall n m : nat, n <= m -> Square n <= Square m.\nintros.\nunfold Square in |- *.\napply le_mult_csts; assumption.\nQed.\nHint Resolve Square_inc.\n\nLemma Square_strict_inc : forall n m : nat, n < m -> Square n < Square m.\nintros.\nunfold Square in |- *.\napply lt_mult_csts; assumption.\nQed.\nHint Resolve Square_strict_inc.\n\n\n\nLemma le_n_Square : forall n : nat, n <= Square n.\nsimple induction n; auto with arith.\nintros.\nunfold Square in |- *.\nsimpl in |- *.\napply le_n_S.\nelim mult_comm; simpl in |- *.\nchange (n0 <= n0 + (n0 + Square n0)) in |- *.\napply le_plus_l.\nQed.\nHint Resolve le_n_Square.\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_Square.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.8152324983301567, "lm_q1q2_score": 0.6757778556706905}}
{"text": "From Enderton Require Export RelationsFunctions.\n\n(** This chapter focuses on embedding the natural numbers into set theory.\n    We start with a few supporting definitions and a new axiom, then define the\n    set omega of all natural numbers. We include a few basic properties of\n    omega for future use.*)\n\nDefinition Succ (a aplus : set) : Prop :=\n  exists Sa, Singleton a Sa /\\ BinaryUnion a Sa aplus.\n\nTheorem Succ_Exists : forall a, exists aplus, Succ a aplus.\nProof.\n  intros a. singleton a. binary_union a x. exists x0.\n  exists x. split; try assumption.\nQed.\n\nTheorem Succ_Unique : forall a aplus aplus', Succ a aplus -> Succ a aplus' ->\n  aplus = aplus'.\nProof.\n  intros a aplus aplus' Haplus Haplus'. destruct Haplus as [Sa [HSa Haplus]].\n  destruct Haplus' as [Sa' [HSa' Haplus']]. apply Extensionality_Axiom.\n  intros x. split; intros H.\n  - apply Haplus'. replace Sa' with Sa. apply Haplus. assumption.\n    apply (Singleton_Unique a Sa Sa'); try assumption.\n  - apply Haplus. replace Sa with Sa'. apply Haplus'. assumption.\n    apply (Singleton_Unique a Sa' Sa); try assumption.\nQed.\n\nLtac succ n := destruct (Succ_Exists n).\n\nDefinition Inductive (A : set ) : Prop :=\n  (exists empty, Empty empty /\\ In empty A) /\\\n  forall a aplus, Succ a aplus -> In a A -> In aplus A.\n\nAxiom Infinity_Axiom : exists A, Inductive A.\n\nDefinition NaturalNumber (x : set) : Prop :=\n  forall A, Inductive A -> In x A.\n\nDefinition Nats (omga : set) : Prop :=\n  forall x, In x omga <-> NaturalNumber x.\n\nTheorem Enderton4A : exists omga, Nats omga.\nProof.\n  destruct Infinity_Axiom as [A HA].\n  build_set\n    set\n    (fun (t c x : set) => NaturalNumber x)\n    A\n    A.\n  rename x into omga. rename H into Homga. exists omga.\n  intros n. split; intros H.\n  - apply Homga, H.\n  - apply Homga. split; try assumption. apply H, HA.\nQed.\n\nTheorem Nats_Unique : forall omga omga', Nats omga -> Nats omga' -> omga = omga'.\nProof.\n  intros omga omga' H H'. apply Extensionality_Axiom. intros n. split; intros I.\n  - apply H', H, I.\n  - apply H, H', I.\nQed.\n\nLtac omga := destruct Enderton4A as [omga Homga].\n\nLtac zero := empty.\n\nTheorem Enderton4B : forall omga, Nats omga -> Inductive omga /\\\n  forall A, Inductive A -> Subset omga A.\nProof.\n  intros omga Homga. split.\n  - split.\n    + empty. exists x. split; try assumption. apply Homga.\n      intros A HA. destruct HA as [HA HA']. destruct HA as [x' [Hx' HA]].\n      replace x with x'; try assumption. apply Empty_Unique; assumption.\n    + intros a a' Ha' Ha. apply Homga. apply Homga in Ha.\n      intros A HA. destruct HA as [HA HA'].\n      apply (HA' a a'); try assumption. apply Ha. split; assumption.\n  - intros A HA n Hn. apply Homga; assumption.\nQed.\n\nTheorem Induction_Principle_for_Omega : forall A omga, Nats omga ->\n  Inductive A -> Subset A omga -> A = omga.\nProof.\n  intros A omga Homga HA Hsub. apply SubsetSymmetric_iff_Equal.\n  split; try assumption. apply Enderton4B; assumption.\nQed.\n\nLemma Zero_NaturalNumber : forall x, Empty x -> NaturalNumber x.\nProof.\n  intros x Hx A HA. destruct HA as [[x' [Hx' HA]] _].\n  replace x with x'; try assumption. apply Empty_Unique; try assumption.\nQed.\n\nLemma Succ_NaturalNumber : forall m n, NaturalNumber m -> Succ m n ->\n  NaturalNumber n.\nProof.\n  intros m n Hm Hn A [HA HA']. apply (HA' m n Hn). apply Hm. split; assumption.\nQed.\n\nLemma Succ_Inversion : forall m n p, Succ m p -> Succ n p -> m = n.\nProof.\n  intros m n p Hp Hp'. destruct Hp as [Sm [HSm Hp]].\n  destruct Hp' as [Sn [HSn Hp']].\nAbort.\n\nTheorem Enderton4C : forall x, NaturalNumber x -> ~ Empty x ->\n  exists w, NaturalNumber w /\\ Succ w x.\nProof.\n  omga.\n  build_set set\n    (fun (t c x : set) => ~Empty x -> exists w, NaturalNumber w /\\ Succ w x)\n    omga omga.\n  rename x into A. rename H into HA. intros n Hn.\n  destruct (Enderton4B omga Homga) as [[He Hind] Hsub].\n  apply HA. replace A with omga; try apply Homga; try assumption.\n  symmetry. apply Induction_Principle_for_Omega; try assumption.\n  - split.\n    + empty. exists x. split; try assumption. apply HA. split.\n      * apply Homga. apply Zero_NaturalNumber; try assumption.\n      * intros C. apply C in H. destruct H.\n    + intros a a' Ha' Ha. apply HA. split.\n      * apply (Hind a a' Ha'). apply HA; assumption.\n      * intros C. exists a. split; try assumption. apply Homga. apply HA, Ha.\n  - intros a Ha. apply HA. assumption.\nQed.\n\n(** Exercise 4-1 : Show that 1 <> 3. TODO *)\n\n(** Next, we embed Peano's postulates in ZF[C]. Peano's postulates are a\n    minimal axiomatization of the natural numbers which are provable in ZF[C].\n    We will later use this result to prove familiar properites of the natural\n    numbers with addition, multiplication, and exponentiation. *)\n\nDefinition Peano1 (N S e : set) : Prop :=\n  forall ranS, Range S ranS -> ~ In e ranS.\n\nDefinition Peano2 (N S e : set) : Prop :=\n  OneToOne S.\n\nDefinition Peano3 (N S e : set) : Prop :=\n  forall A, Subset A N -> In e A ->\n  (forall n Sn, FunVal S n Sn -> In n A -> In Sn A) -> A = N.\n\nDefinition PeanoSystem (P : set) : Prop :=\n  exists N S NS e, OrdPair N S NS /\\ OrdPair NS e P /\\\n  FuncFromInto S N N /\\ In e N /\\ Peano1 N S e /\\ Peano2 N S e /\\ Peano3 N S e.\n\nDefinition SuccessorFunc (sigma : set) : Prop :=\n  forall nn', In nn' sigma <-> exists n n', OrdPair n n' nn' /\\\n  NaturalNumber n /\\ Succ n n'.\n\nTheorem SuccessorFunc_Exists : exists sigma, SuccessorFunc sigma.\nProof.\n  omga. prod omga omga. rename x into omgaxomga. rename H into Homgaxomga.\n  build_set\n    set\n    (fun (t c nm : set) => exists n m, OrdPair n m nm /\\ NaturalNumber n /\\ Succ n m)\n    omga\n    omgaxomga.\n  rename x into sigma. rename H into Hsigma. exists sigma.\n  intros nn'. split; intros H; try apply Hsigma, H.\n  apply Hsigma. split; try assumption.\n  apply Homgaxomga. destruct H as [n [n' [Hnn' [Hn Hn']]]].\n  exists n, n'. repeat (split; try assumption).\n  - apply Homga, Hn.\n  - apply Homga. intros A [HA' HA]. apply (HA n n' Hn'). apply Homga.\n    + apply Homga, Hn.\n    + split; assumption.\nQed.\n\nTheorem SuccessorFunc_Unique : forall sigma sigma',\n  SuccessorFunc sigma -> SuccessorFunc sigma' -> sigma = sigma'.\nProof.\n  intros sigma sigma' H H'. apply Extensionality_Axiom. intros x. split; intros I.\n  - apply H', H, I.\n  - apply H, H', I.\nQed.\n\nLemma SuccessorFunc_Into : forall sigma omga, SuccessorFunc sigma ->\n  Nats omga -> FuncFromInto sigma omga omga.\nProof.\n  intros sigma omga Hsigma Homga. split; try split.\n  - intros mn Hmn. apply Hsigma in Hmn. destruct Hmn as [m [n [Hmn _]]].\n    exists m, n. assumption.\n  - intros m n p mn mp Hmn Hmp H I. apply Hsigma in H. apply Hsigma in I.\n    destruct H as [m' [n' [Hmn' [_ Hn]]]].\n    replace m' with m in *;\n    try (apply (Enderton3A m n m' n' mn mn Hmn Hmn'); trivial).\n    replace n' with n in *;\n    try (apply (Enderton3A m n m n' mn mn Hmn Hmn'); trivial).\n    clear m' n' Hmn'. destruct I as [m' [p' [Hmp' [_ Hp]]]].\n    replace m' with m in *;\n    try (apply (Enderton3A m p m' p' mp mp Hmp Hmp'); trivial).\n    replace p' with p in *;\n    try (apply (Enderton3A m p m p' mp mp Hmp Hmp'); trivial).\n    clear m' p' Hmp'. apply (Succ_Unique m n p); assumption.\n  - intros m. split; intros H.\n    + succ m. rename x into m'. rename H0 into Hm'.\n      ordpair m m'. rename x into mm'. rename H0 into Hmm'.\n      exists m', mm'. split; try assumption. apply Hsigma.\n      exists m, m'. repeat (split; try assumption). apply Homga, H.\n    + destruct H as [m' [mm' [Hmm' H]]]. apply Hsigma in H.\n      destruct H as [n [n' [Hnn' [Hn Hn']]]]. replace m with n.\n      apply Homga, Hn. apply (Enderton3A n n' m m' mm' mm' Hnn' Hmm'). trivial.\n  - range sigma. rename x into ransigma. rename H into Hransigma.\n    exists ransigma. split; try assumption.\n    intros n H. apply Homga. apply Hransigma in H.\n    destruct H as [m [mn [Hmn H]]]. apply Hsigma in H.\n    destruct H as [m' [n' [Hmn' [Hm Hn]]]]. replace n with n'.\n    apply (Succ_NaturalNumber m' n'); try assumption.\n    apply (Enderton3A m' n' m n mn mn Hmn' Hmn). trivial.\nQed.\n\nLtac sigma := destruct (SuccessorFunc_Exists) as [sigma Hsigma].\n\nDefinition PeanoSystem_of_NaturalNumbers (P : set) : Prop :=\n  exists N S NS e, OrdPair N S NS /\\ OrdPair NS e P /\\\n  Nats N /\\ SuccessorFunc S /\\ Empty e.\n\nTheorem PeanoSystem_of_NaturalNumbers_Exists : exists P,\n  PeanoSystem_of_NaturalNumbers P.\nProof.\n  empty. rename x into e. rename H into He. omga. sigma.\n  ordpair omga sigma. rename x into os. rename H into Hos.\n  ordpair os e. rename x into P. rename H into HP. exists P.\n  exists omga, sigma, os, e. repeat (split; try assumption).\nQed.\n\nTheorem PeanoSystem_of_NaturalNumbers_Unique : forall P P',\n  PeanoSystem_of_NaturalNumbers P -> PeanoSystem_of_NaturalNumbers P' -> P = P'.\nProof.\n  intros P P' H H'. destruct H as [N [S [NS [e [HNS [HP [HN [HS He]]]]]]]].\n  destruct H' as [N' [S' [NS' [e' [HNS' [HP' [HN' [HS' He']]]]]]]].\n  apply (OrdPair_Unique NS e P P'); try assumption.\n  replace NS with NS'. replace e with e'. assumption.\n  - apply Empty_Unique; try assumption.\n  - apply (OrdPair_Unique N S NS' NS); try assumption.\n    replace N with N'. replace S with S'. assumption.\n    + apply SuccessorFunc_Unique; assumption.\n    + apply Nats_Unique; assumption.\nQed.\n\n(** Theorem 4D states that the Peano System of Natural Numbers is, in fact,\n    a Peano System. It is state here by Enderton, but the full proof requires\n    some of the following results concerning transitive sets. For this reason,\n    we will delary the theorem statement for now. *)\n\nDefinition TransitiveSet (A : set) : Prop :=\n  forall a x, In a A -> In x a -> In x A.\n\nTheorem Enderton4E : forall a a' Ua', Succ a a' ->\n  Union a' Ua' -> TransitiveSet a -> Ua' = a.\nProof.\n  intros a a' Ua' Ha' HUa' Ha.\n  apply Extensionality_Axiom. intros x. split; intros H.\n  - apply HUa' in H. destruct H as [y [H I]].\n    destruct Ha' as [Sa [HSa Ha']]. apply Ha' in I. destruct I as [I | I].\n    + apply (Ha y x); try assumption.\n    + apply HSa in I. rewrite <- I. assumption.\n  - apply HUa'. exists a. split; try assumption.\n    destruct Ha' as [Sa [HSa Ha']]. apply Ha'.\n    right. apply HSa. trivial.\nQed.\n\nTheorem Enderton4F : forall n, NaturalNumber n -> TransitiveSet n.\nProof.\n  omga. build_set set (fun (t c x : set) => TransitiveSet x) omga omga.\n  rename x into A. rename H into HA.\n  intros n Hn. apply HA. replace A with omga. apply Homga, Hn.\n  symmetry. apply Induction_Principle_for_Omega; try assumption.\n  - split.\n    + empty. exists x. split; try assumption. apply HA. split.\n      * apply Homga. apply (Zero_NaturalNumber x H).\n      * intros z y Hz Hy. apply H in Hz. destruct Hz.\n    + intros a a' Ha' Ha. apply HA. apply HA in Ha as [Ha Htrans]. split.\n      * apply Homga in Ha. apply Homga. apply (Succ_NaturalNumber a a' Ha Ha').\n      * intros y x Hy Hx. destruct Ha' as [Sa [HSa Ha']].\n        apply Ha' in Hy. destruct Hy as [Hy | Hy].\n        { apply Ha'. left. apply (Htrans y x Hy Hx). }\n        { apply HSa in Hy. replace y with a in Hx. apply Ha'. left. assumption. }\n  - intros a Ha. apply HA, Ha.\nQed.\n\nTheorem Enderton4D : forall P, PeanoSystem_of_NaturalNumbers P -> PeanoSystem P.\nProof.\n  intros P HP. destruct HP as [N [S [NS [e [HNS [HP [HN [HS He]]]]]]]].\n  exists N, S, NS, e. split; try assumption. split; try assumption.\n  split; try apply (SuccessorFunc_Into S N HS HN).\n  split; try apply HN, (Zero_NaturalNumber e), He.\n  split; try split.\n  - intros ranS HranS C. apply HranS in C. destruct C as [d [de [Hde C]]].\n    apply (He d). apply HS in C. destruct C as [d' [e' [Hde' [Hd' He']]]].\n    replace d with d'. replace e with e'. destruct He' as [Sd [HSd He']].\n    apply He'. right. apply HSd. trivial.\n    + apply (Enderton3A d' e' d e de de Hde' Hde). trivial.\n    + apply (Enderton3A d' e' d e de de Hde' Hde). trivial.\n  - split; try apply (SuccessorFunc_Into S N HS HN).\n    intros m n p mp np Hmp Hnp H I. apply HS in H. apply HS in I.\n    destruct H as [m' [p' [Hmp' [Hm Hp]]]].\n    assert (T : m = m' /\\ p = p').\n    { apply (Enderton3A m p m' p' mp mp Hmp Hmp'). trivial. }\n    replace m' with m in *; replace p' with p in *; try apply T.\n    clear m' p' T. destruct I as [n' [p' [Hnp' [Hn Hp']]]].\n    assert (T : n = n' /\\ p = p').\n    { apply (Enderton3A n p n' p' np np Hnp Hnp'). trivial. }\n    replace n' with n in *; replace p' with p in *; try apply T.\n    clear n' p' T Hmp' Hnp'. union p. rename x into Up. rename H into HUp.\n    transitivity Up.\n    + symmetry. apply (Enderton4E m p Up Hp HUp).\n      apply Enderton4F. assumption.\n    + apply (Enderton4E n p Up Hp' HUp). apply Enderton4F. assumption.\n  - intros A Hsub HeA Hind.\n    apply Induction_Principle_for_Omega; try assumption. split.\n    + exists e. split; assumption.\n    + intros a a' Ha' Ha. apply (Hind a a'); try assumption.\n      intros _ _. ordpair a a'. rename x into aa'. rename H into Haa'.\n      exists aa'. split; try assumption. apply HS.\n      exists a, a'. split; try assumption. split; try assumption.\n      apply HN. apply Hsub. assumption.\nQed.\n\nTheorem Enderton4G : forall omga, Nats omga -> TransitiveSet omga.\nProof.\n  intros omga Homga n m Hn Hm.\n  build_set set (fun (t c x : set) => Subset x t) omga omga.\n  rename x into T. rename H into HT.\n  assert (P : T = omga).\n  { apply Induction_Principle_for_Omega; try assumption; try split.\n    - empty. exists x. split; try assumption. apply HT. split.\n      + apply Homga, Zero_NaturalNumber, H.\n      + intros y Hy. apply H in Hy. destruct Hy.\n    - intros a a' Ha' Ha. apply HT in Ha. destruct Ha as [Ha1 Ha2].\n      apply HT. split.\n      + apply Homga, (Succ_NaturalNumber a a'); try assumption.\n        apply Homga, Ha1.\n      + intros x Hx. destruct Ha' as [Sa [HSa Ha']].\n        apply Ha' in Hx. destruct Hx as [Hx | Hx].\n        * apply Ha2. assumption.\n        * replace x with a; try assumption. symmetry. apply HSa. assumption.\n    - intros x H. apply HT. assumption. }\n  rewrite <- P in Hn. apply HT in Hn. destruct Hn as [Hn Hn'].\n  apply Hn'. assumption.\nQed.\n\nTheorem Exercise4_2 : forall a a', Succ a a' ->\n  TransitiveSet a -> TransitiveSet a'.\nProof.\n  intros a a' Ha' Ha. destruct Ha' as [Sa [HSa Ha']].\n  intros y x Hy Hx. apply Ha' in Hy. destruct Hy as [Hy | Hy].\n  - apply Ha'. left. apply (Ha y x); assumption.\n  - apply Ha'. apply HSa in Hy. rewrite Hy in Hx. left. assumption.\nQed.\n\nTheorem Exercise4_3a : forall a Pa, PowerSet a Pa ->\n  TransitiveSet a -> TransitiveSet Pa.\nProof.\n  intros a Pa HPa Ha. intros Y X HY HX. apply HPa in HY.\n  apply HPa. intros x Hx. apply HY in HX.\n  apply (Ha X x); assumption.\nQed.\n\nTheorem Exercise4_3b : forall a Pa, PowerSet a Pa ->\n  TransitiveSet Pa -> TransitiveSet a.\nProof.\n  intros a Pa HPa H y x Hy Hx. assert (P : Subset y a).\n  { apply HPa. singleton y. rename x0 into Sy. rename H0 into HSy.\n    apply (H Sy y).\n    - apply HPa. intros u Hu. apply HSy in Hu. replace u with y. assumption.\n    - apply HSy. trivial. }\n  apply P. assumption.\nQed.\n\nTheorem Exercise4_4 : forall a Ua, Union a Ua ->\n  TransitiveSet a -> TransitiveSet Ua.\nProof.\n  intros a Ua HUa H y x Hy Hx. apply HUa. apply HUa in Hy.\n  destruct Hy as [Y [Hy HY]]. exists y. split; try assumption.\n  apply (H Y y); try assumption.\nQed.\n\nTheorem Exercise4_5a : forall A UA, Union A UA ->\n  (forall a, In a A -> TransitiveSet a) -> TransitiveSet UA.\nProof.\n  intros A UA HUA HA. intros y x Hy Hx. apply HUA. apply HUA in Hy.\n  destruct Hy as [Y [Hy HY]]. apply HA in HY as HY'.\n  exists Y. split; try assumption. apply (HY' y x); try assumption.\nQed.\n\nTheorem Exercise4_5b : forall A NA, ~Empty A -> Intersect A NA ->\n  (forall a, In a A -> TransitiveSet a) -> TransitiveSet NA.\nProof.\n  intros A NA Hne HNA HA y x Hy Hx. apply (HNA Hne).\n  intros Y HY. assert (Hy' : forall z, In z A -> In y z).\n  { apply (HNA Hne). assumption. }\n  apply HA in HY as HY'. apply (HY' y x); try assumption.\n  apply Hy'. assumption.\nQed.\n\nTheorem Exercise4_6 : forall a a' Ua', Succ a a' -> Union a' Ua' ->\n  a = Ua' -> TransitiveSet a.\nProof.\n  intros a a' Ua' Ha' HUa' Heq y x Hy Hx. replace a with Ua'.\n  apply HUa'. destruct Ha' as [Sa [HSa Ha']].\n  exists y. split; try assumption.\n  apply Ha'. left. assumption.\nQed.\n\n(** What follows is arguably the most interesting result so far. If we recall\n    to the beginning of the book the concept of proving sets to be\n    well-defined, we can extend this notion to our Peano systems. Peano's\n    postulates were intended to be an axiomatization of the natural numbers, \n    that is to say, they fully describe all the known/provable properties of\n    the natural numbers, and they don't describe any other structure. We have\n    already acheived the first part of the well-definedness proof; that there is\n    a Peano system embedded in ZF[C]. This is Theorem 4D, that our definition\n    for the natural numbers extendeds into a Peano system. Later, we will prove\n    that many important theorems of Peano's postulates hold for our own\n    construction of the natural numbers. Next, however, we need to show the\n    second part of well-definedness, that every other Peano system besides our\n    own cannonical example is isomorphic to our own, i.e. that our natural\n    numbers are unique. This will require the Recursion Theorem, which is the\n    main goal of the next stretch of definitions and theorems. The uniqueness\n    result (isomorphism result) is a corollary of the Recursion Theorem on omega. *)\n\nDefinition RecursiveFunction (A a F h : set) : Prop :=\n  exists omga zero, Nats omga /\\ Empty zero /\\ FuncFromInto h omga A /\\\n  FunVal h zero a /\\ forall n n' hn hn' Fhn, In n omga -> Succ n n' ->\n  FunVal h n hn -> FunVal h n' hn' -> FunVal F hn Fhn -> hn' = Fhn.\n\nLemma RecursiveFunction_Exists : forall A a F,\n  In a A -> FuncFromInto F A A -> exists h, RecursiveFunction A a F h.\nProof.\n  intros A a F Ha HFAA. omga.\n  prod omga A. rename x into omgaxA. rename H into HomgaxA.\n  powerset omgaxA. rename x into PomgaxA. rename H into HPomgaxA.\n  build_set\n    (prod (prod set set) (prod set set))\n    (fun (t : (set * set) * (set * set)) (c v : set) => Func v /\\\n      exists domv ranv e, Domain v domv /\\ Range v ranv /\\ Empty e /\\\n      Subset domv (fst (fst t)) /\\ Subset ranv (snd (fst t)) /\\\n      (In e domv -> FunVal v e (snd (snd t))) /\\\n      (forall n n' vn', In n (fst (fst t)) -> Succ n n' -> FunVal v n' vn' ->\n      In n' (fst (fst t)) -> In n' domv -> In n domv /\\ exists vn Fvn,\n      FunVal v n vn /\\ FunVal (fst (snd t)) vn Fvn /\\ vn' = Fvn))\n    ((omga, A), (F, a))\n    PomgaxA.\n  rename H into HH. rename x into H.\n  union H. rename x into h. rename H0 into Hh.\n  empty. rename x into o. rename H0 into Ho. exists h, omga, o.\n  range h. rename x into ranh. rename H0 into Hranh.\n  assert (P : Subset ranh A).\n  { intros x Hx. apply Hranh in Hx. destruct Hx as [n [nx [Hnx Hx]]].\n    apply Hh in Hx. destruct Hx as [v [I J]]. apply HH in J.\n    destruct J as [J _]. apply HPomgaxA in J. apply J in I.\n    apply HomgaxA in I. destruct I as [n' [x' [Hn [Hx Hnx']]]].\n    replace x with x'; try assumption.\n    apply (Enderton3A n' x' n x nx nx Hnx'); try trivial. }\n  assert (Q : Func h). {\n    split.\n    - intros na I. apply Hh in I. destruct I as [v [I J]].\n      apply HH in J. destruct J as [J _]. apply HPomgaxA in J.\n      apply J in I. apply HomgaxA in I. destruct I as [x [y [_ [_ Hna]]]].\n      exists x, y. assumption.\n    - intros x y z xy xz Hxy Hxz I J. build_set \n        set\n        (fun (t c x : set) => forall y z xy xz, OrdPair x y xy -> OrdPair x z xz ->\n          In xy t -> In xz t -> y = z)\n        h\n        omga.\n      rename x0 into S. rename H0 into HS. apply Hh in I as I'.\n      destruct I' as [v [I1 I2]]. apply HH in I2 as [I2 _].\n      apply HPomgaxA in I2. apply I2 in I1. apply HomgaxA in I1.\n      destruct I1 as [x' [y' [Hx [Hy Hxy']]]]. assert (T : x = x' /\\ y = y').\n      { apply (Enderton3A x y x' y' xy xy Hxy Hxy'). trivial. }\n      replace x' with x in *; replace y' with y in *; try apply T.\n      clear x' y' T. replace omga with S in Hx. apply HS in Hx.\n      destruct Hx as [_ Hx]. apply (Hx y z xy xz); try assumption.\n      apply Induction_Principle_for_Omega; try assumption; try split.\n      + exists o. split; try assumption. apply HS.\n        split; try apply Homga, Zero_NaturalNumber, Ho.\n        intros a' a'' oa' oa'' Hoa' Hoa'' K L.\n        apply Hh in K. apply Hh in L. destruct K as [v1 [K1 K2]].\n        destruct L as [v2 [L1 L2]]. apply HH in K2. apply HH in L2.\n        destruct K2 as [_ [Hv1 [domv1 [_ [e1 [Hdomv1 [_ [He1 [_ [_ [K2 _]]]]]]]]]]].\n        destruct L2 as [_ [Hv2 [domv2 [_ [e2 [Hdomv2 [_ [He2 [_ [_ [L2 _]]]]]]]]]]].\n        transitivity a.\n        * apply (FunVal_Unique v1 o a' a); try assumption.\n          { exists domv1. split; try assumption. apply Hdomv1.\n            exists a', oa'. split; try assumption. }\n          { intros _ _. exists oa'. split; assumption. }\n          { replace e1 with o in *; try (apply Empty_Unique; assumption).\n            apply K2. apply Hdomv1. exists a', oa'. split; assumption. }\n        * apply (FunVal_Unique v2 o a a''); try assumption.\n          { exists domv2. split; try assumption. apply Hdomv2.\n            exists a'', oa''. split; assumption. }\n          { replace e2 with o in *; try (apply Empty_Unique; assumption).\n            apply L2. apply Hdomv2. exists a'', oa''. split; assumption. }\n          { intros _ _. exists oa''. split; try assumption. }\n      + intros m n Hn Hm. apply HS. apply HS in Hm. destruct Hm as [Hm Hm'].\n        apply Homga in Hm. split; try (apply Homga, (Succ_NaturalNumber m); assumption).\n        intros hn hn' nhn nhn' Hnhn Hnhn' K L. apply Hh in K. apply Hh in L.\n        destruct K as [v1 [K1 K2]]. destruct L as [v2 [L1 L2]].\n        apply HH in K2 as K2'. apply HH in L2 as L2'.\n        destruct K2' as [_ [Hv1 [domv1 [ranv1 [_ [Hdomv1 [Hranv1 [_ [_ [Hsub [_ K2']]]]]]]]]]].\n        destruct L2' as [_ [Hv2 [domv2 [_ [_ [Hdomv2 [_ [_ [_ [_ [_ L2']]]]]]]]]]].\n        apply Homga in Hm.\n        destruct (K2' m n hn Hm Hn) as [Hmv1 [v1m [Fv1m [Hv1m [HFv1m K2'']]]]].\n        { intros _ _. exists nhn. split; assumption. }\n        { simpl. apply Homga. apply (Succ_NaturalNumber m n); try assumption.\n          apply Homga. assumption. }\n        { apply Hdomv1. exists hn, nhn. split; assumption. }\n        destruct (L2' m n hn' Hm Hn) as [Hmv2 [v2m [Fv2m [Hv2m [HFv2m L2'']]]]].\n        { intros _ _. exists nhn'. split; try assumption. }\n        { simpl. apply Homga. apply (Succ_NaturalNumber m n); try assumption.\n          apply Homga. assumption. }\n        { apply Hdomv2. exists hn', nhn'. split; assumption. }\n        rewrite K2''. rewrite L2''. destruct HFAA as [HF [HdomF _]].\n        replace v2m with v1m in HFv2m. apply (FunVal_Unique F v1m); try assumption.\n        exists A. split; try assumption. apply Hsub. apply Hranv1. exists m.\n        apply Hv1m; try assumption. exists domv1. split; try assumption.\n        destruct Hv1m as [mv1m [Hmv1m Hmv1m']]; try assumption.\n        { exists domv1. split; try assumption. }\n        destruct Hv2m as [mv2m [Hmv2m Hmv2m']]; try assumption.\n        { exists domv2. split; try assumption. }\n        apply (Hm' v1m v2m mv1m mv2m); try assumption.\n        * apply Hh. exists v1. split; try assumption.\n        * apply Hh. exists v2. split; assumption.\n      + intros s. apply HS. }\n    domain h. rename x into domh. rename H0 into Hdomh.\n    assert (R : Domain h omga).\n    { intros x. split.\n      - build_set set (fun (t c x : set) => exists y xy, OrdPair x y xy /\\ In xy t) h omga.\n        rename x0 into S. rename H0 into HS. intros Hx. replace omga with S in Hx.\n        apply HS. assumption.\n        apply Induction_Principle_for_Omega; try assumption; try split.\n        + exists o. split; try assumption. apply HS.\n          split; try (apply Homga, (Zero_NaturalNumber); assumption).\n          ordpair o a. rename x0 into oa. rename H0 into Hoa.\n          exists a, oa. split; try assumption. apply Hh.\n          singleton oa. rename x0 into v. rename H0 into Hv. exists v.\n          split; try (apply Hv; trivial). apply HH. repeat split.\n          * apply HPomgaxA. intros oa' Hoa'. apply HomgaxA.\n            exists o, a. split; try (apply Homga, (Zero_NaturalNumber o Ho)).\n            split; try assumption. apply Hv in Hoa'. rewrite Hoa'; assumption.\n          * intros oa' Hoa'. exists o, a. replace oa' with oa; try assumption.\n            apply Hv in Hoa'. symmetry. assumption.\n          * intros x' y z xy xz Hxy Hxz I J. transitivity a.\n            { apply (Enderton3A x' y o a oa oa); try  assumption; try trivial.\n              apply Hv in I. rewrite <- I. assumption. }\n            { apply (Enderton3A o a x' z oa oa); try assumption; try trivial.\n              apply Hv in J. rewrite <- J. assumption. }\n          * domain v. rename x0 into domv. rename H0 into Hdomv.\n            range v. rename x0 into ranv. rename H0 into Hranv.\n            exists domv, ranv, o. repeat (split; try assumption).\n            { intros o' Ho'. apply Homga.\n              replace o' with o; try (apply (Zero_NaturalNumber o Ho)).\n              apply Hdomv in Ho'. destruct Ho' as [a' [oa' [Hoa' Ho']]].\n              apply (Enderton3A o a o' a' oa oa Hoa); try trivial.\n              apply Hv in Ho'. rewrite <- Ho'. assumption. }\n            { intros a' Ha'. replace a' with a; try assumption.\n              apply Hranv in Ha'. destruct Ha' as [o' [oa' [Hoa' Ho']]].\n              apply (Enderton3A o a o' a' oa oa Hoa); try trivial.\n              apply Hv in Ho'. rewrite <- Ho'. assumption. }\n            { intros I. intros _ _. apply Hdomv in I. destruct I as [a' I].\n              replace a with a'; try assumption. destruct I as [oa' [Hoa' I]].\n              apply (Enderton3A o a' o a oa' oa' Hoa'); try trivial.\n              apply Hv in I. rewrite I. assumption. }\n            { destruct (Ho n). replace o with n'.\n              destruct H1 as [Sn [HSn H1]]. apply H1. right. apply HSn. trivial.\n              apply Hdomv in H4. destruct H4 as [a' [oa' [Hoa' H4]]].\n              apply (Enderton3A n' a' o a oa' oa' Hoa'); try trivial.\n              apply Hv in H4. rewrite H4. assumption. }\n            { destruct (Ho n). replace o with n'.\n              destruct H1 as [Sn [HSn H1]]. apply H1. right. apply HSn. trivial.\n              apply Hdomv in H4. destruct H4 as [a' [oa' [Hoa' H4]]].\n              apply (Enderton3A n' a' o a oa' oa' Hoa'); try trivial.\n              apply Hv in H4. rewrite H4. assumption. }\n        + intros n n' Hn' Hn. apply HS. apply HS in Hn.\n          destruct Hn as [Hn [hn [nhn [Hnhn I]]]]. apply Homga in Hn.\n          split; try (apply Homga, (Succ_NaturalNumber n n' Hn Hn')).\n          destruct (FunVal_Exists F hn); try apply HFAA.\n          { exists A. split. apply HFAA. apply P. apply Hranh.\n            exists n, nhn. split; try assumption. }\n          rename x0 into Fhn. rename H0 into HFhn. apply Hh in I.\n          destruct I as [v [I Hv]]. apply HH in Hv.\n          ordpair n' Fhn. rename x0 into n'hn'. rename H0 into Hn'hn'.\n          exists Fhn, n'hn'. split; try assumption. apply Hh.\n          singleton n'hn'. rename x0 into Sn'hn'. rename H0 into HSn'hn'.\n          binary_union v Sn'hn'. rename x0 into v'. rename H0 into Hv'.\n          exists v'. split. apply Hv'. right. apply HSn'hn'. trivial.\n          assert (U : Func v'). {\n            split.\n            - intros xy Hxy. apply Hv' in Hxy. destruct Hxy as [Hxy | Hxy].\n              { apply Hv. assumption. }\n              { exists n', Fhn. apply HSn'hn' in Hxy. rewrite Hxy. assumption. }\n            - intros s t u st su Hst Hsu J K. apply Hv' in J. apply Hv' in K.\n              destruct J as [J | J]; destruct K as [K | K].\n              { destruct Hv as [_ [[Hv1 Hv2] _]]. apply (Hv2 s t u st su); assumption. }\n              { apply HSn'hn' in K. assert (T : n' = s /\\ Fhn = u).\n                { apply (Enderton3A n' Fhn s u su su); try trivial; try assumption.\n                  rewrite K. assumption. }\n                replace s with n' in *; replace u with Fhn in *; try apply T.\n                clear T s u. replace su with n'hn' in *. clear K Hsu.\n                destruct Hv as [Hv1 [Hfv [domv [ranv [e [Hdomv [Hranv [He [Hsuv' [Hsub [Hev Hv]]]]]]]]]]].\n                destruct (Hv n n' t) as [H1 H2]; try assumption.\n                - apply Homga. apply Hn.\n                - intros _ _. exists st. split; assumption.\n                - apply Homga. apply (Succ_NaturalNumber n); assumption.\n                - apply Hdomv. exists t, st. split; try assumption.\n                - destruct H2 as [vn [Fvn [Hvn [HFvn H2]]]].\n                  transitivity Fvn; try assumption.\n                  apply (FunVal_Unique F vn Fvn Fhn); try assumption; try apply HFAA.\n                  exists A. split. try apply HFAA. apply Hsub. apply Hranv. exists n.\n                  apply Hvn; try assumption. exists domv. split; try assumption.\n                  replace vn with hn. assumption. destruct Q as [Q1 Q2].\n                  destruct Hvn as [nvn [Hnvn Hnvn']]; try assumption.\n                  { exists domv. split; try assumption. }\n                  apply (Q2 n hn vn nhn nvn); try assumption.\n                  + apply Hh. exists v. split; try assumption. apply HH.\n                    repeat (split; try assumption). exists domv, ranv, e.\n                    repeat (split; try assumption).\n                  + apply Hh. exists v. split; try assumption. apply HH.\n                    repeat (split; try assumption). exists domv, ranv, e.\n                    repeat (split; try assumption). }\n              { rename t into tmp. rename u into t. rename tmp into u.\n                rename st into tmp. rename su into st. rename tmp into su.\n                rename J into tmp. rename K into J. rename tmp into K.\n                apply HSn'hn' in K. assert (T : n' = s /\\ Fhn = u).\n                { apply (Enderton3A n' Fhn s u su su); try trivial; try assumption.\n                  rewrite K. assumption. }\n                replace s with n' in *; replace u with Fhn in *; try apply T.\n                clear T s u. replace su with n'hn' in *. clear K Hst.\n                destruct Hv as [Hv1 [Hfv [domv [ranv [e [Hdomv [Hranv [He [Hsuv' [Hsub [Hev Hv]]]]]]]]]]].\n                destruct (Hv n n' t) as [H1 H2]; try assumption.\n                - apply Homga. apply Hn.\n                - intros _ _. exists st. split; assumption.\n                - apply Homga. apply (Succ_NaturalNumber n); assumption.\n                - apply Hdomv. exists t, st. split; try assumption.\n                - destruct H2 as [vn [Fvn [Hvn [HFvn H2]]]].\n                  transitivity Fvn; try (symmetry; assumption).\n                  apply (FunVal_Unique F vn Fhn Fvn); try assumption; try apply HFAA.\n                  exists A. split. try apply HFAA. apply Hsub. apply Hranv. exists n.\n                  apply Hvn; try assumption. exists domv. split; try assumption.\n                  replace vn with hn. assumption. destruct Q as [Q1 Q2].\n                  destruct Hvn as [nvn [Hnvn Hnvn']]; try assumption.\n                  { exists domv. split; try assumption. }\n                  apply (Q2 n hn vn nhn nvn); try assumption.\n                  + apply Hh. exists v. split; try assumption. apply HH.\n                    repeat (split; try assumption). exists domv, ranv, e.\n                    repeat (split; try assumption).\n                  + apply Hh. exists v. split; try assumption. apply HH.\n                    repeat (split; try assumption). exists domv, ranv, e.\n                    repeat (split; try assumption). }\n              { apply HSn'hn' in J. apply HSn'hn' in K. replace st with n'hn' in *.\n                replace su with n'hn' in *. clear J K. transitivity Fhn.\n                - apply (Enderton3A s t n' Fhn n'hn' n'hn' Hst Hn'hn'). trivial.\n                - apply (Enderton3A n' Fhn s u n'hn' n'hn' Hn'hn' Hsu). trivial. } }\n          apply HH. repeat (split; try assumption).\n          * apply HPomgaxA. intros xy Hxy. apply Hv' in Hxy. destruct Hxy as [Hxy | Hxy].\n            { destruct Hv as [Hv _]. apply HPomgaxA in Hv. apply Hv. assumption. }\n            { apply HomgaxA. exists n', Fhn. split; try split.\n              - apply Homga. apply (Succ_NaturalNumber n n' Hn Hn').\n              - destruct HFAA as [HF [HdomF [ranF [HranF Hsub]]]]. apply Hsub.\n                apply HranF. exists hn. apply HFhn; try assumption.\n                exists A. split; try assumption. apply P. apply Hranh.\n                exists n, nhn. split; try assumption. apply Hh. exists v.\n                split; try assumption. apply HH. assumption.\n              - apply HSn'hn' in Hxy. rewrite Hxy. assumption. }\n          * domain v'. rename x0 into domv'. rename H0 into Hdomv'.\n            range v'. rename x0 into ranv'. rename H0 into Hranv'.\n            destruct Hv as [HvP [Hfv [domv [ranv [e [Hdomv [Hranv [He [Hsubd [Hsubr [Hv1 Hv2]]]]]]]]]]].\n            exists domv', ranv', o. repeat (split; try assumption).\n            { intros m Hm. simpl. apply Hdomv' in Hm.\n              destruct Hm as [vm [mvm [Hmvm Hmvm']]]. apply Hv' in Hmvm'.\n              destruct Hmvm' as [Hmvm' | Hmvm'].\n              - apply Hsubd. apply Hdomv. exists vm, mvm. split; assumption.\n              - apply HSn'hn' in Hmvm'. replace m with n'.\n                + apply Homga. apply (Succ_NaturalNumber n n'); try assumption.\n                + apply (Enderton3A n' Fhn m vm n'hn' n'hn' Hn'hn').\n                  rewrite <- Hmvm'; try assumption. trivial. }\n            { intros vm Hvm. simpl. apply Hranv' in Hvm.\n              destruct Hvm as [m [mvm [Hmvm Hvm]]]. apply Hv' in Hvm.\n              destruct Hvm as [Hvm | Hvm].\n              - apply Hsubr. apply Hranv. exists m, mvm. split; assumption.\n              - apply HSn'hn' in Hvm. replace mvm with n'hn' in *.\n                replace vm with Fhn. destruct HFAA as [HF [HdomF [ranF [HranF Hsub]]]].\n                apply Hsub. apply HranF. exists hn. apply HFhn; try assumption.\n                exists A. split; try assumption. apply P. apply Hranh.\n                exists n, nhn. split; try assumption. apply Hh.\n                exists v. split; try assumption. apply HH. repeat (split; try assumption).\n                exists domv, ranv, e. repeat (split; try assumption).\n                apply (Enderton3A n' Fhn m vm n'hn' n'hn'); try assumption. }\n            { intros C. apply Hdomv' in C. destruct C as [a' [oa' [Hoa' C]]].\n              apply Hv' in C. destruct C as [C | C].\n              - intros _ _. exists oa'. split.\n                + replace a with a'; try assumption. apply (FunVal_Unique v o a' a).\n                  assumption. exists domv. split; try assumption.\n                  apply Hdomv. exists a', oa'. split; try assumption.\n                  intros _ _. exists oa'. split; try assumption.\n                  replace o with e in *; try apply Hv1, Hdomv.\n                  exists a', oa'. split; try assumption.\n                  apply Empty_Unique; assumption.\n                + apply Hv'. left. trivial.\n              - intros _ _. apply HSn'hn' in C. replace oa' with n'hn' in *.\n                clear C. destruct (Ho n). replace o with n'.\n                + destruct Hn' as [Sn [HSn Hn']]. apply Hn'. right.\n                  apply HSn. trivial.\n                + apply (Enderton3A n' Fhn o a' n'hn' n'hn'); try assumption. trivial. }\n            { simpl in *. rename n0 into m. rename n'0 into m'. rename vn' into vm'.\n              apply Hdomv'. destruct H2 as [m'vm' [Hm'vm' H2]]; try assumption.\n              exists domv'. split; try assumption.\n              apply Hv' in H2. destruct H2 as [H2 | H2].\n              - destruct (Hv2 m m' vm') as [Hv2' _]; try assumption.\n                + intros _ _. exists m'vm'. split; try assumption.\n                + apply Hdomv. exists vm', m'vm'. split; assumption.\n                + apply Hdomv in Hv2'. destruct Hv2' as [vm [mvm [Hmvm Hv2']]].\n                  exists vm, mvm. split; try assumption. apply Hv'. left. assumption.\n              - exists hn, nhn. split.\n                + replace m with n. assumption. apply HSn'hn' in H2.\n                  replace m'vm' with n'hn' in *. clear H2.\n                  replace m' with n' in *;\n                  try (apply (Enderton3A n' Fhn m' vm' n'hn' n'hn' Hn'hn' Hm'vm'); trivial).\n                  union n'. transitivity x0.\n                  * symmetry. apply (Enderton4E n n'); try assumption.\n                    apply (Enderton4F). assumption.\n                  * apply (Enderton4E m n'); try assumption.\n                    apply Enderton4F. apply Homga. assumption.\n                + apply Hv'. left. assumption. }\n            { simpl in *. rename n0 into m. rename n'0 into m'. rename vn' into vm'.\n              destruct H2 as [m'vm' [Hm'vm' H2]]; try assumption.\n              exists domv'. split; try assumption.\n              apply Hv' in H2. destruct H2 as [H2 | H2].\n              - destruct (Hv2 m m' vm') as [Y Hv2']; try assumption.\n                + intros _ _. exists m'vm'. split; try assumption.\n                + apply Hdomv. exists vm', m'vm'. split; assumption.\n                + destruct Hv2' as [vm [Fvm [Hvm [HFvm Hv2']]]]. \n                  exists vm, Fvm. repeat (split; try assumption).\n                  intros _ _. destruct Hvm as [mvm [Hmvm Hmvm']]; try assumption.\n                  exists domv. split; try assumption.\n                  exists mvm. split; try assumption. apply Hv'. left. assumption.\n              - exists hn, Fhn. replace m with n in *. split; try split.\n                + intros _ _. exists nhn. split; try assumption.\n                  apply Hv'. left. assumption.\n                + assumption.\n                + apply (Enderton3A m' vm' n' Fhn m'vm' n'hn' Hm'vm' Hn'hn').\n                  apply HSn'hn' in H2. assumption.\n                + union n'. transitivity x0.\n                  * symmetry. apply (Enderton4E n n'); try assumption.\n                    apply (Enderton4F). assumption.\n                  * apply (Enderton4E m n'); try assumption.\n                    replace n' with m'; try assumption.\n                    apply (Enderton3A m' vm' n' Fhn m'vm' n'hn' Hm'vm' Hn'hn').\n                    apply HSn'hn' in H2. assumption.\n                    apply (Enderton4F). apply Homga. assumption. }\n        + intros s Hs. apply HS. assumption.\n      - intros I. destruct I as [y [xy [Hxy I]]].\n        apply Hh in I. destruct I as [v [I J]].\n        apply HH in J. destruct J as [J _].\n        apply HPomgaxA in J. apply J in I. apply HomgaxA in I.\n        destruct I as [x' [y' [Hx [Hy Hxy']]]]. replace x with x'; try assumption.\n        apply (Enderton3A x' y' x y xy xy Hxy' Hxy). trivial. }\n    repeat (split; try assumption).\n  - exists ranh. split; assumption.\n  - intros _ [domh' [Hdomh' I]]. apply Hdomh' in I.\n    destruct I as [a' [oa' [Hoa' I]]]. exists oa'. split; try assumption.\n    apply Hh in I. destruct I as [v [I J]]. apply HH in J.\n    destruct J as [_ [Hfv [domv [_ [e [Hdomv [_ [He [_ [_ [Hv _]]]]]]]]]]].\n    assert (T : o = e). { apply Empty_Unique; assumption. }\n    replace o with e in *. clear T o Ho.\n    assert (T : In e domv).\n    { apply Hdomv. exists a', oa'. split; try assumption. }\n    apply Hv in T. simpl in *. destruct T as [ea [Hea Hea']]; try assumption.\n    exists domv. split; try assumption. apply Hdomv.\n    exists a', oa'. split; try assumption. replace a with a'. assumption.\n    destruct Hfv as [_ Hfv]. apply (Hfv e a' a oa' ea); try assumption.\n  - intros m n hm hn Fhm Hm Hn Hhm Hhn HFhm.\n    destruct Hhn as [nhn [Hnhn Hnhn']]; try assumption.\n    exists omga. split; try assumption. apply Homga. apply Homga in Hm.\n    apply (Succ_NaturalNumber m n); try assumption.\n    apply Hh in Hnhn'. destruct Hnhn' as [v [I J]]. apply HH in J as J'.\n    destruct J' as [_ [Hfv [domv [_ [_ [Hdomv [_ [_ [_ [_ [_ Hv]]]]]]]]]]].\n    destruct (Hv m n hn) as [J' [vm [Fvm [Hvm [HFvm Hv']]]]]; try assumption.\n    + intros _ _. exists nhn. split; try assumption.\n    + simpl. apply Homga. apply Homga in Hm. apply (Succ_NaturalNumber m n).\n      assumption. assumption.\n    + apply Hdomv. exists hn, nhn. split; assumption.\n    + simpl in *. transitivity Fvm; try assumption.\n      destruct Hvm as [mvm [Hmvm Hmvm']]; try assumption.\n      { exists domv. split; try assumption. }\n      destruct Hhm as [mhm [Hmhm Hmhm']]; try assumption.\n      { exists omga. split; assumption. }\n      destruct HFAA as [[HF HF'] [HdomF [ranF [HranF Hsub]]]].\n      destruct HFvm as [vmFvm [H0 H1]]; try (split; assumption).\n      { exists A. split; try assumption. apply P. apply Hranh.\n        exists m, mvm. split; try assumption. apply Hh.\n        exists v. split; try assumption. }\n      destruct HFhm as [hmFhm [H2 H3]]; try (split; assumption).\n      { exists A. split; try assumption. apply P. apply Hranh.\n        exists m, mhm. split; try assumption. }\n      apply (HF' hm Fvm Fhm vmFvm hmFhm); try assumption.\n      replace hm with vm; try assumption.\n      destruct Q as [Q1 Q2]. apply (Q2 m vm hm mvm mhm); try assumption.\n      apply Hh. exists v. split; try assumption.\nQed.\n\nLemma RecursiveFunction_Unique : forall A a F h h' , In a A ->\n  FuncFromInto F A A -> RecursiveFunction A a F h ->\n  RecursiveFunction A a F h' -> h = h'.\nProof.\n  intros A a F h h' Ha [Hf [Hdomf [ranf [Hranf Hsub]]]] Hh Hh'.\n  omga. build_set\n    (prod set set )\n    (fun (t : set * set) (c x : set) => forall b c, FunVal (fst t) x b ->\n      FunVal (snd t) x c -> b = c)\n    (h, h')\n    omga.\n  destruct Hh as [omga' [o [Homga' [Ho [HhomgaA [Hho Hhn']]]]]].\n  replace omga' with omga in *; try (apply Nats_Unique; assumption).\n  clear omga' Homga'.\n  destruct Hh' as [omga' [o' [Homga' [Ho' [Hh'omgaA [Hh'o Hh'n']]]]]].\n  replace omga' with omga in *; try (apply Nats_Unique; assumption).\n  replace o' with o in *; try (apply Empty_Unique; assumption).\n  rename x into S. rename H into HS. assert (P : S = omga).\n  { apply Induction_Principle_for_Omega; try assumption; try split.\n    - empty. exists x. split; try assumption. apply HS.\n      split; try (apply Homga, (Zero_NaturalNumber), H).\n      intros b c Hb Hc. simpl in *. transitivity a.\n      + apply (FunVal_Unique h x b a); try assumption; try apply HhomgaA.\n        { exists omga. split.\n          - try apply HhomgaA.\n          - apply Homga, Zero_NaturalNumber, H. }\n        replace x with o; try assumption. apply (Empty_Unique); assumption.\n      + apply (FunVal_Unique h' x a c); try assumption; try apply Hh'omgaA.\n        { exists omga. split.\n          - apply Hh'omgaA.\n          - apply Homga, Zero_NaturalNumber, H. }\n        replace x with o; try assumption. apply (Empty_Unique); assumption.\n    - intros m n Hn Hm. apply HS. apply HS in Hm. destruct Hm as [Hm Hm'].\n      apply Homga in Hm.\n      split; try (apply Homga, (Succ_NaturalNumber m n); assumption).\n      intros b c Hb Hc. simpl in *.\n      assert (H0 : exists domh, Domain h domh /\\ In m domh).\n      { exists omga. split; try (apply Homga; assumption). apply HhomgaA. }\n      assert (H1 : exists domh', Domain h' domh' /\\ In m domh').\n      { exists omga. split; try (apply Homga; assumption). apply Hh'omgaA. }\n      assert (H0' : Func h). { apply HhomgaA. }\n      assert (H1' : Func h'). { apply Hh'omgaA. }\n      funval H0' H0 h m. rename x into hm. rename H into Hhm.\n      funval H1' H1 h' m. rename x into h'm. rename H into Hh'm.\n      assert (P : hm = h'm). { apply Hm'; assumption. }\n      replace h'm with hm in *. clear h'm P.\n      assert (H3 : exists domF, Domain F domF /\\ In hm domF).\n      { exists A. split; try assumption.\n        destruct HhomgaA as [_ [_ [ranh [Hranh Hsub']]]].\n        apply Hsub'. apply Hranh. exists m. apply Hhm; try assumption. }\n      funval Hf H3 F hm. rename x into Fhm. rename H into HFhm.\n      transitivity Fhm.\n      + apply (Hhn' m n hm b Fhm); try assumption. apply Homga. assumption.\n      + symmetry. apply (Hh'n' m n hm c Fhm); try assumption. apply Homga. assumption.\n    - intros s Hs. apply HS, Hs. }\n  apply Extensionality_Axiom. intros xy. split; intros H.\n  - destruct HhomgaA as [[Hhr Hhf] HhomgaA].\n    apply Hhr in H as I. destruct I as [x [y Hxy]].\n    assert (T : In x omga).\n    { destruct HhomgaA as [Hdomh _]. apply Hdomh. exists y, xy.\n      split; assumption. }\n    assert (H0 : Func h'). { apply Hh'omgaA. }\n    assert (H1 : exists domh', Domain h' domh' /\\ In x domh').\n    { exists omga. split. apply Hh'omgaA. assumption. }\n    funval H0 H1 h' x. rename x0 into h'x. rename H2 into Hh'x.\n    rewrite <- P in T. apply HS in T. destruct T as [T1 T2].\n    destruct (Hh'x H0 H1) as [xy' [Hxy' Hxy'']].\n    replace xy with xy'; try assumption.\n    apply (OrdPair_Unique x y xy' xy); try assumption.\n    replace y with h'x; try assumption. symmetry. apply T2.\n    + intros _ _. exists xy. split; try assumption.\n    + assumption.\n  - destruct Hh'omgaA as [[Hh'r Hh'f] Hh'omgaA].\n    apply Hh'r in H as I. destruct I as [x [y Hxy]].\n    assert (T : In x omga).\n    { destruct Hh'omgaA as [Hdomh' _]. apply Hdomh'. exists y, xy.\n      split; assumption. }\n    assert (H0 : Func h). { apply HhomgaA. }\n    assert (H1 : exists domh, Domain h domh /\\ In x domh).\n    { exists omga. split. apply HhomgaA. assumption. }\n    funval H0 H1 h x. rename x0 into hx. rename H2 into Hhx.\n    rewrite <- P in T. apply HS in T. destruct T as [T1 T2].\n    destruct (Hhx H0 H1) as [xy' [Hxy' Hxy'']].\n    replace xy with xy'; try assumption.\n    apply (OrdPair_Unique x y xy' xy); try assumption.\n    replace y with hx; try assumption. apply T2.\n    + assumption.\n    + intros _ _. exists xy. split; assumption.\nQed.\n\nLtac recursion A a F Ha HFAA := destruct (RecursiveFunction_Exists A a F Ha HFAA).\n\nTheorem Recursion_Theorem_on_Omega : forall A a F, In a A -> FuncFromInto F A A ->\n  exists h, RecursiveFunction A a F h /\\ forall h', RecursiveFunction A a F h' ->\n  h = h'.\nProof.\n  intros A a F Ha HFAA. recursion A a F Ha HFAA. exists x.\n  split; try assumption. intros h' H'.\n  apply (RecursiveFunction_Unique A a F x h' Ha HFAA H H').\nQed.\n\nCorollary Enderton4H : forall N S e NS P omga sigma empty os Q,\n  OrdPair N S NS -> OrdPair NS e P -> PeanoSystem P ->\n  OrdPair omga sigma os -> OrdPair os empty Q -> PeanoSystem_of_NaturalNumbers Q ->\n  exists h, FuncFromOnto h omga N /\\ OneToOne h /\\\n  (forall n sn hsn hn Shn, In n omga -> FunVal sigma n sn -> FunVal h sn hsn ->\n  FunVal h n hn -> FunVal S hn Shn -> hsn = Shn) /\\\n  forall ho, FunVal h empty ho -> ho = e.\nProof.\n  intros N S e NS PN omga sigma empty os Pw HNS HNSe HPN Hos Hose HPw.\n  destruct HPw as [omga' [sigma' [os' [empty' [Hos' [Hose' [Homga [Hsigma He]]]]]]]].\n  assert (T : os = os' /\\ empty = empty').\n  { apply (Enderton3A os empty os' empty' Pw Pw Hose Hose'). trivial. }\n  replace os' with os in *; replace empty' with empty in *; try apply T.\n  clear os' empty' T. rename empty into o. rename He into Ho.\n  assert (T : omga = omga' /\\ sigma = sigma').\n  { apply (Enderton3A omga sigma omga' sigma' os os Hos Hos'). trivial. }\n  replace omga' with omga in *; replace sigma' with sigma in *; try apply T.\n  clear omga' sigma' Hos' T Hose'.\n  destruct HPN as [N' [S' [NS' [e' [HNS' [HNSe' [HS [He [HP1 [HP2 HP3]]]]]]]]]].\n  assert (T : NS = NS' /\\ e = e').\n  { apply (Enderton3A NS e NS' e' PN PN HNSe HNSe'). trivial. }\n  replace NS' with NS in *; replace e' with e in *; try apply T.\n  clear NS' e' T. assert (T : N = N' /\\ S = S').\n  { apply (Enderton3A N S N' S' NS NS HNS HNS'). trivial. }\n  replace N' with N in *; replace S' with S in *; try apply T.\n  clear N' S' HNS' T HNSe'. recursion N e S He HS.\n  rename x into h. rename H into Hh. exists h.\n  destruct Hh as [omga' [o' [Homga' [Ho' [HhomgaN [Hho Hhsn]]]]]].\n  assert (T : o = o'). { apply Empty_Unique; try assumption. }\n  replace o' with o in *; try apply T. clear o' T Ho'.\n  assert (T : omga = omga'). { apply Nats_Unique; try assumption. }\n  replace omga' with omga in *; try apply T. clear omga' T Homga'.\n  destruct HhomgaN as [Hfh [Hdomh [ranh [Hranh Hsub]]]].\n  assert (P : ranh = N).\n  { apply (HP3 ranh Hsub). unfold Peano3 in HP3.\n    - apply Hranh. exists o. apply Hho; try assumption.\n      exists omga. split; try assumption.\n      apply Homga, Zero_NaturalNumber, Ho.\n    - intros hn Shn HShn Hhn. apply Hranh in Hhn.\n      destruct Hhn as [n [nhn [Hnhn Hnhn']]].\n      succ n. rename x into n'. rename H into Hn'.\n      assert (T : exists domh, Domain h domh /\\ In n' domh).\n      { exists omga. split; try assumption. apply Homga.\n        apply (Succ_NaturalNumber n n'); try assumption.\n        apply Homga. apply Hdomh. exists hn, nhn. split; assumption. }\n      funval Hfh T h n'. rename x into hn'. rename H into Hhn'.\n      replace Shn with hn'.\n      + apply Hranh. exists n'. apply Hhn'; assumption.\n      + apply (Hhsn n n' hn hn' Shn); try assumption.\n        * apply Hdomh. exists hn, nhn. split; assumption.\n        * intros _ _. exists nhn. split; assumption. }\n  repeat (split; try assumption).\n  - intros H. rewrite <- P in H. apply Hranh in H. assumption.\n  - intros H. apply Hsub. apply Hranh. assumption.\n  - build_set set (fun (h c n : set) => forall m a na ma, OrdPair n a na ->\n      OrdPair m a ma -> In na h -> In ma h -> n = m) h omga.\n    rename x into T. rename H into HT. intros n m a na ma Hna Hma I J.\n    assert (Q : In n omga).\n    { apply Hdomh. exists a, na. split; assumption. }\n    replace omga with T in Q. apply HT in Q. destruct Q as [_ Q].\n    apply (Q m a na ma); try assumption.\n    clear n m a na ma Hna Hma I J Q. \n    apply Induction_Principle_for_Omega; try assumption; try split.\n    + exists o. split; try assumption. apply HT.\n      split; try (apply Homga, (Zero_NaturalNumber), Ho).\n      intros m' hm' ohm' m'hm' Hohm' Hm'ho H I.\n      assert (Q : o = m' \\/ o <> m'). { apply REM. }\n      destruct Q as [Q | Q]; try trivial.\n      destruct (Enderton4C m') as [m [Hm Hm']].\n      { apply Homga, Hdomh. exists hm', m'hm'. split; assumption. }\n      { intros c. apply Q. apply Empty_Unique; assumption. }\n      range S. rename x into ranS. rename H0 into HranS.\n      destruct (HP1 ranS HranS). apply HranS. apply Homga in Hm.\n      assert (H0 : exists domh, Domain h domh /\\ In m domh).\n      { exists omga. split; try assumption. }\n      funval Hfh H0 h m. rename x into hm. rename H1 into Hhm.\n      exists hm. destruct (FunVal_Exists S hm); try apply HS.\n      { exists N. split. apply HS. apply Hsub. apply Hranh. exists m.\n        apply Hhm; try assumption. }\n      rename x into Shm. rename H1 into HShm.\n      replace e with Shm. apply HShm; try apply HS.\n      { exists N. split. apply HS. apply Hsub. apply Hranh. exists m.\n        apply Hhm; assumption. }\n      transitivity hm'.\n      * symmetry. apply (Hhsn m m' hm hm' Shm Hm Hm'); try assumption.\n        intros _ _. exists m'hm'. split; assumption.\n      * apply (FunVal_Unique h o hm' e); try assumption.\n        { exists omga. split; try assumption. apply Homga, Zero_NaturalNumber, Ho. }\n        { intros _ _. exists ohm'. split; try assumption. }\n    + intros n n' Hn' Hn. apply HT. apply HT in Hn.\n      destruct Hn as [Hn1 Hn2]. apply Homga in Hn1.\n      split; try (apply Homga, (Succ_NaturalNumber n n'); assumption).\n      intros m' hn' n'hn' m'hn' Hn'hn' Hm'hn' H I.\n      destruct (Enderton4C m') as [m [Hm Hm']].\n      { apply Homga, Hdomh. exists hn', m'hn'. split; assumption. }\n      { intros C. range S. rename x into ranS. rename H0 into HranS.\n        destruct (HP1 ranS HranS). apply HranS. apply Homga in Hn1.\n        assert (H0 : exists domh, Domain h domh /\\ In n domh).\n        { exists omga. split; try assumption. }\n        funval Hfh H0 h n. rename x into hn. rename H1 into Hhn.\n        exists hn. destruct (FunVal_Exists S hn); try apply HS.\n        { exists N. split. apply HS. apply Hsub. apply Hranh. exists n.\n          apply Hhn; try assumption. }\n        rename x into Shn. rename H1 into HShn.\n        replace e with Shn. apply HShn; try apply HS.\n        { exists N. split. apply HS. apply Hsub. apply Hranh. exists n.\n          apply Hhn; assumption. }\n        transitivity hn'.\n        * symmetry. apply (Hhsn n n' hn hn' Shn Hn1 Hn'); try assumption.\n          intros _ _. exists n'hn'. split; assumption.\n        * apply (FunVal_Unique h m' hn' e); try assumption.\n          { exists omga. split; try assumption. apply Homga, Zero_NaturalNumber, C. }\n          { intros _ _. exists m'hn'. split; try assumption. }\n          replace m' with o; try assumption. apply Empty_Unique; assumption. }\n      assert (H0 : exists domh, Domain h domh /\\ In n domh).\n      { exists omga. split; try assumption. apply Homga; assumption. }\n      assert (H1 : exists domh, Domain h domh /\\ In m domh).\n      { exists omga. split; try assumption. apply Homga; assumption. }\n      funval Hfh H0 h n. rename x into hn. rename H2 into Hhn.\n      funval Hfh H1 h m. rename x into hm. rename H2 into Hhm.\n      assert (H2 : exists domS, Domain S domS /\\ In hn domS).\n      { exists N. split. apply HS. apply Hsub. apply Hranh.\n        exists n. apply Hhn; assumption. }\n      assert (H3 : exists domS, Domain S domS /\\ In hm domS).\n      { exists N. split. apply HS. apply Hsub. apply Hranh.\n        exists m. apply Hhm; assumption. }\n      destruct HS as [HfS HS].\n      funval HfS H2 S hn. rename x into Shn. rename H4 into HShn.\n      funval HfS H3 S hm. rename x into Shm. rename H4 into HShm.\n      apply (Succ_Unique m); try assumption. replace m with n; try assumption.\n      assert (Q : Shn = Shm).\n      { transitivity hn'.\n        - symmetry. apply (Hhsn n n' hn hn' Shn); try assumption.\n          + apply Homga; assumption.\n          + intros _ _. exists n'hn'. split; assumption.\n        - apply (Hhsn m m' hm hn' Shm); try assumption.\n          + apply Homga; assumption.\n          + intros _ _. exists m'hn'. split; assumption. }\n      assert (R : hn = hm).\n      { destruct HP2 as [_ HP2].\n        destruct HShn as [hnShn [HhnShn HhnShn']]; try assumption.\n        destruct HShm as [hmShm [HhmShm HhmShm']]; try assumption.\n        ordpair hm Shn. rename x into hmShn. rename H into HhmShn.\n        apply (HP2 hn hm Shn hnShn hmShn); try assumption.\n        replace hmShn with hmShm; try assumption.\n        apply (OrdPair_Unique hm Shm); try assumption. rewrite <- Q. assumption. }\n      destruct Hhn as [nhn [Hnhn Hnhn']]; try assumption.\n      destruct Hhm as [mhm [Hmhm Hmhm']]; try assumption.\n      ordpair m hn. rename x into mhn. rename H4 into Hmhn.\n      apply (Hn2 m hn nhn mhn); try assumption.\n      replace mhn with mhm; try assumption.\n      apply (OrdPair_Unique m hm mhm mhn); try assumption.\n      rewrite <- R. assumption.\n    + intros t Ht. apply HT in Ht as [Ht _]. assumption.\n  - intros n sn hsn hn Shn Hsn Hhsn' Hhn HShn.\n    apply (Hhsn n sn hn hsn Shn); try assumption.\n    destruct Hhsn' as [nsn [Hnsn Hnsn']].\n    + destruct (SuccessorFunc_Into sigma omga); try assumption.\n    + exists omga. split; try assumption.\n      destruct (SuccessorFunc_Into sigma omga) as [_ [H0 _]]; try assumption.\n    + apply Hsigma in Hnsn'. destruct Hnsn' as [n' [sn' [Hnsn' [Hn Hn']]]].\n      assert (T : n' = n /\\ sn' = sn).\n      { apply (Enderton3A n' sn' n sn nsn nsn Hnsn' Hnsn). trivial. }\n      replace n with n'; replace sn with sn'; try apply T. assumption.\n  - intros ho Hho'. apply (FunVal_Unique h o ho e); try assumption.\n    exists omga. split; try assumption. apply Homga.\n    apply Zero_NaturalNumber. apply Ho.\nQed.\n\n(** Exercise 4 - 7 : Complete part of the proof of the recusion theorem. *)\n\nTheorem Exercise4_8 : forall f A c ranf Amranf h, FuncFromInto f A A ->\n  OneToOne f -> Range f ranf -> SetMinus A ranf Amranf -> In c Amranf ->\n  RecursiveFunction A c f h -> OneToOne h.\nProof.\n  intros f A c ranf Amranf h HfAA Hf Hranf HAmranf Hc Hh.\n  destruct Hh as [omga [o [Homga [Ho [HhomgaA [Hho Hhn']]]]]].\n  split; try apply HhomgaA. intros m n hm mhm nhm Hmhm Hnhm H I.\n  build_set set (fun (h c m : set) => forall n hm mhm nhm, OrdPair m hm mhm ->\n    OrdPair n hm nhm -> In mhm h -> In nhm h -> m = n) h omga.\n  rename x into S. rename H0 into HS. assert (P : In m omga).\n  { apply HhomgaA. exists hm, mhm. split; assumption. }\n  replace omga with S in P. apply HS in P. destruct P as [_ P].\n  apply (P n hm mhm nhm); try assumption.\n  clear Hnhm Hmhm n hm mhm nhm H I P m.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros s Hs; apply HS in Hs; destruct Hs as [Hs _]; assumption).\n  - exists o. split; try assumption. apply HS. split.\n    + apply Homga, Zero_NaturalNumber. assumption.\n    + intros n' hm mhm n'hm Hmhm Hn'hm H I.\n      assert (Q : o = n' \\/ o <> n'). { apply REM. }\n      destruct Q as [Q | Q]; try assumption. apply HAmranf in Hc.\n      destruct Hc as [Hc Hc']. destruct Hc'. apply Hranf.\n      destruct (Enderton4C n') as [n [Hn Hn']].\n      { apply Homga, HhomgaA. exists hm, n'hm. split; assumption. }\n      { intros C. apply Q. apply Empty_Unique; try assumption. }\n      assert (R : hm = c).\n      { apply (FunVal_Unique h o hm c); try apply  HhomgaA; try assumption.\n        - exists omga. split. apply HhomgaA.\n          apply Homga, Zero_NaturalNumber, Ho.\n        - intros _ _. exists mhm. split; assumption. }\n      replace hm with c in *. clear R.\n      assert (H0 : exists domh, Domain h domh /\\ In n domh).\n      { exists omga. split. try apply HhomgaA. apply Homga. assumption. }\n      destruct HhomgaA as [Hfh HhomgaA].\n      funval Hfh H0 h n. rename x into hn. rename H1 into Hhn.\n      destruct Hhn as [nhn [Hnhn Hnhn']]; try assumption.\n      destruct HhomgaA as [Hdomh [rnah [Hranh Hsub]]].\n      exists hn. destruct (FunVal_Exists f hn); try apply HfAA.\n      { exists A. split. apply HfAA. apply Hsub. apply Hranh.\n        exists n, nhn. split; try assumption. }\n      rename x into fhn. rename H1 into Hfhn.\n      destruct Hfhn as [hnfhn [Hhnfhn Hhnfhn']]; try apply HfAA.\n      { exists A. split. apply HfAA. apply Hsub. apply Hranh.\n        exists n, nhn. split; try assumption. }\n      exists hnfhn. split; try assumption. replace c with fhn; try assumption.\n      symmetry. apply (Hhn' n n' hn c fhn); try assumption.\n      * apply Homga; assumption.\n      * intros _ _. exists nhn. split; assumption.\n      * intros _ _. exists n'hm. split; assumption.\n      * intros _ _. exists hnfhn. split; assumption.\n  - intros n n' Hn' Hn. apply HS. apply HS in Hn. destruct Hn as [Hn1 Hn2].\n    apply Homga in Hn1. split; try (apply Homga, (Succ_NaturalNumber n n'); assumption).\n    intros m' hm' n'hm' m'hm' Hn'hm' Hm'hm' H I.\n    destruct HhomgaA as [Hfh [Hdomh [ranh [Hranh Hsub]]]].\n    destruct (Enderton4C m') as [m [Hm Hm']].\n    { apply Homga, Hdomh. exists hm', m'hm'. split; assumption. }\n    { intros C. apply HAmranf in Hc. destruct Hc as [Hc Hc']. apply Hc'.\n      apply Hranf. assert (T : hm' = c).\n      { apply (FunVal_Unique h o hm' c); try assumption.\n        - exists omga. split; try assumption. apply Homga, Zero_NaturalNumber, Ho.\n        - intros _ _. exists m'hm'. split; try assumption.\n          replace o with m'; try assumption. apply Empty_Unique; try assumption. }\n      replace hm' with c in *. clear T.\n      assert (H0 : exists domh, Domain h domh /\\ In n domh).\n      { exists omga. split; try assumption. apply Homga. assumption. }\n      funval Hfh H0 h n. rename x into hn. rename H1 into Hhn.\n      destruct Hhn as [nhn [Hnhn Hnhn']]; try assumption.\n      exists hn. destruct (FunVal_Exists f hn); try apply HfAA.\n      { exists A. split. apply HfAA. apply Hsub. apply Hranh.\n        exists n, nhn. split; try assumption. }\n      rename x into fhn. rename H1 into Hfhn.\n      destruct Hfhn as [hnfhn [Hhnfhn Hhnfhn']]; try apply HfAA.\n      { exists A. split. apply HfAA. apply Hsub. apply Hranh.\n        exists n, nhn. split; try assumption. }\n      exists hnfhn. split; try assumption. replace c with fhn; try assumption.\n      symmetry. apply (Hhn' n n' hn c fhn); try assumption.\n      * apply Homga; assumption.\n      * intros _ _. exists nhn. split; try assumption.\n      * intros _ _. exists n'hm'. split; assumption.\n      * intros _ _. exists hnfhn. split; assumption. }\n    assert (H0 : exists domh, Domain h domh /\\ In n domh).\n    { exists omga. split; try assumption. apply Homga. assumption. }\n    assert (H1 : exists domh, Domain h domh /\\ In m domh).\n    { exists omga. split; try assumption. apply Homga. assumption. }\n    funval Hfh H0 h n. rename x into hn. rename H2 into Hhn.\n    funval Hfh H1 h m. rename x into hm. rename H2 into Hhm.\n    destruct Hhn as [nhn [Hnhn Hnhn']]; try assumption.\n    destruct Hhm as [mhm [Hmhm Hmhm']]; try assumption.\n    assert (H2 : exists domf, Domain f domf /\\ In hm domf).\n    { exists A. split. apply HfAA. apply Hsub. apply Hranh.\n      exists m, mhm. split; assumption. }\n    assert (H3 : exists domf, Domain f domf /\\ In hn domf).\n    { exists A. split. apply HfAA. apply Hsub. apply Hranh.\n      exists n, nhn. split; assumption. }\n    destruct HfAA as [Hff HfAA].\n    funval Hff H2 f hm. rename x into fhm. rename H4 into Hfhm.\n    funval Hff H3 f hn. rename x into fhn. rename H4 into Hfhn.\n    assert (P : fhm = fhn).\n    { transitivity hm'.\n      - symmetry. apply (Hhn' m m' hm hm' fhm); try assumption.\n        + apply Homga. assumption.\n        + intros _ _. exists mhm. split; assumption.\n        + intros _ _. exists m'hm'. split; assumption.\n      - apply (Hhn' n n' hn hm' fhn); try assumption.\n        + apply Homga. assumption.\n        + intros _ _. exists nhn. split; assumption.\n        + intros _ _. exists n'hm'. split; assumption. }\n    assert (Q : hm = hn).\n    { destruct Hf as [_ Hf].\n      destruct Hfhm as [hmfhm [Hhmfhm Hhmfhm']]; try assumption.\n      destruct Hfhn as [hnfhn [Hhnfhn Hfnhfn']]; try assumption.\n      apply (Hf hm hn fhm hmfhm hnfhn); try assumption.\n      replace fhm with fhn; try assumption. }\n    apply (Succ_Unique n n' m'); try assumption.\n    replace n with m; try assumption.\n    ordpair n hm. rename x into nhm. rename H2 into Hnhm.\n    symmetry. apply (Hn2 m hm nhm mhm); try assumption.\n    replace nhm with nhn; try assumption.\n    apply (OrdPair_Unique n hn nhn nhm); try assumption.\n    replace hn with hm; try assumption.\nQed. \n\nDefinition preClosure1 (f B A preC1 : set) : Prop :=\n  forall X, In X preC1 <-> Subset A X /\\ Subset X B /\\\n  forall fX, Image X f fX -> Subset fX X.\n\nTheorem preClosure1_Exists : forall f B A, exists preC1, preClosure1 f B A preC1.\nProof.\n  intros f B A. powerset B. rename x into PB. rename H into HPB.\n  build_set\n    (prod (prod set set) set)\n    (fun (t : set * set * set) (c X : set) => Subset (snd t) X /\\\n      Subset X (snd (fst t)) /\\ forall fX, Image X (fst (fst t)) fX -> Subset fX X)\n    (f, B, A)\n    PB.\n  rename x into preC1. rename H into HpreC1. exists preC1.\n  intros X. split; intros H; try apply HpreC1; try assumption.\n  split; try apply H. apply HPB. intros x Hx.\n  destruct H as [_ [H _]]. apply H. assumption.\nQed.\n\nTheorem preClosure1_Unique : forall f B A C C', preClosure1 f B A C ->\n  preClosure1 f B A C' -> C = C'.\nProof.\n  intros f B A C C' HC HC'.\n  apply Extensionality_Axiom. intros x. split; intros H.\n  - apply HC', HC, H.\n  - apply HC, HC', H.\nQed.\n\nDefinition GivenByImageClosure (f B F : set) : Prop :=\n  forall XY, In XY F <-> exists X Y fX, OrdPair X Y XY /\\\n  Subset X B /\\ Subset Y B /\\ Image X f fX /\\ BinaryUnion X fX Y.\n\nTheorem GivenByImageClosure_Exists : forall f B, exists F, GivenByImageClosure f B F.\nProof.\n  intros f B. powerset B. rename x into PB. rename H into HPB.\n  prod PB PB. rename x into PBxPB. rename H into HPBxPB.\n  build_set\n    (prod set set)\n    (fun (t : set * set) (c x : set) => exists X Y fX, OrdPair X Y x /\\\n      Subset X (fst t) /\\ Subset Y (fst t) /\\ Image X (snd t) fX /\\\n      BinaryUnion X fX Y)\n    (B, f)\n    PBxPB.\n  rename x into F. rename H into HF. exists F. intros XY. split; intros H.\n  - apply HF, H.\n  - apply HF. split; try assumption. apply HPBxPB.\n    destruct H as [X [Y [fX [HXY [HX [HY [HfX H]]]]]]].\n    exists X, Y. repeat (split; try assumption; try apply HPB; try assumption).\nQed.\n\nTheorem GivenByImageClosure_Unique : forall f B F G,\n  GivenByImageClosure f B F -> GivenByImageClosure f B G -> F = G.\nProof.\n  intros f B F G HF HG. apply Extensionality_Axiom. intros x; split; intros H.\n  - apply HG, HF, H.\n  - apply HF, HG, H.\nQed.\n\nTheorem GivenByImageClosure_Into : forall f B PB F, FuncFromInto f B B ->\n  PowerSet B PB -> GivenByImageClosure f B F -> FuncFromInto F PB PB.\nProof.\n  intros f B PB F [Hf [Hdomf [ranf [Hranf Hsub]]]] HPB HF. repeat split.\n  - intros xy H. apply HF in H. destruct H as [X [Y [_ [HXY _]]]].\n    exists X, Y. assumption.\n  - intros X Y Z XY XZ HXY HXZ H I. apply HF in H. apply HF in I.\n    destruct H as [X' [Y' [fX [HXY' [HX [HY [HfX H]]]]]]].\n    assert (T : X = X' /\\ Y = Y').\n    { apply (Enderton3A X Y X' Y' XY XY HXY HXY'). trivial. }\n    replace X' with X in *; replace Y' with Y in *; try apply T.\n    clear X' Y' T HXY'. destruct I as [X' [Z' [fX' [HXZ' [HX' [HY' [HfX' I]]]]]]].\n    assert (T : X = X' /\\ Z = Z').\n    { apply (Enderton3A X Z X' Z' XZ XZ HXZ HXZ'). trivial. }\n    replace X' with X in *; replace Z' with Z in *; try apply T.\n    clear X' Z' T HXZ'. apply (BinaryUnion_Unique X fX Y Z); try assumption.\n    replace fX with fX'; try assumption.\n    apply (Image_Unique X f fX' fX); assumption.\n  - rename x into X. intros HX. image X f. rename x into fX. rename H into HfX.\n    binary_union X fX. rename x into Y. rename H into HY.\n    ordpair X Y. rename x into XY. rename H into HXY.\n    exists Y, XY. split; try assumption. apply HF.\n    exists X, Y, fX. repeat (split; try assumption).\n    + apply HPB; assumption.\n    + intros y H. apply HY in H. destruct H as [H | H].\n      * apply HPB in HX. apply HX, H.\n      * apply HfX in H. destruct H as [x [xy [Hxy [H I]]]].\n        apply Hsub. apply Hranf. exists x, xy. split; try assumption.\n  - rename x into X. intros [Y [XY [HXY H]]]. apply HF in H.\n    destruct H as [X' [Y' [fX [HXY' [HX [HY [HfX H]]]]]]].\n    apply HPB. replace X with X'; try assumption.\n    apply (Enderton3A X' Y' X Y XY XY HXY' HXY). trivial.\n  - range F. rename x into ranF. rename H into HranF.\n    exists ranF. split; try assumption.\n    intros Y H. apply HranF in H. destruct H as [X [XY [HXY H]]].\n    apply HF in H. destruct H as [X' [Y' [fX [HXY' [_ [HY _]]]]]].\n    apply HPB. replace Y with Y'; try assumption.\n    apply (Enderton3A X' Y' X Y XY XY HXY' HXY). trivial.\nQed.\n\nDefinition preClosure2 (f B A preC2 : set) : Prop := FuncFromInto f B B ->\n  Subset A B -> exists PB F h, GivenByImageClosure f B F /\\ PowerSet B PB /\\\n  RecursiveFunction PB A F h /\\ Range h preC2.\n\nTheorem preClosure2_Exists : forall f B A, FuncFromInto f B B -> Subset A B ->\n  exists C, preClosure2 f B A C.\nProof.\n  intros f B A HfBB HAB. powerset B. rename x into PB. rename H into HPB.\n  destruct (GivenByImageClosure_Exists f B). rename x into F. rename H into HF.\n  assert (HFPBPB : FuncFromInto F PB PB).\n  { apply (GivenByImageClosure_Into f B); try assumption. }\n  assert (HA : In A PB).\n  { apply HPB. assumption. }\n  recursion PB A F HA HFPBPB. rename x into h. rename H into Hh.\n  range h. rename x into ranh. rename H into Hranh.\n  exists ranh. intros _ _. exists PB, F, h. repeat (split; try assumption).\nQed.\n\nTheorem preClosure2_Unique : forall f B A C C', FuncFromInto f B B ->\n  Subset A B -> preClosure2 f B A C ->\n  preClosure2 f B A C' -> C = C'.\nProof.\n  intros f B A C C' HfBB HAB HC HC'.\n  destruct HC as [PB [F [h [HF [HPB [Hh Hranh]]]]]]; try assumption.\n  destruct HC' as [PB' [F' [h' [HF' [HPB' [Hh' Hranh']]]]]]; try assumption.\n  apply (Range_Unique h C C'); try assumption.\n  replace h with h'; try assumption.\n  apply (RecursiveFunction_Unique PB A F h' h); try assumption.\n  { apply HPB; assumption. }\n  { apply (GivenByImageClosure_Into f B); try assumption. }\n  replace PB with PB'.\n  - replace F with F'; try assumption.\n    apply (GivenByImageClosure_Unique f B); try assumption.\n  - apply (Power_Set_Unique B PB' PB); try assumption.\nQed.\n\nLemma Subset_Transitive : forall A B C, Subset A B -> Subset B C -> Subset A C.\nProof.\n  intros A B C HAB HBC. intros a H. apply HBC, HAB, H.\nQed.\n\nTheorem Exercise4_9 : forall f B A C1 C2 NC1 UC2, FuncFromInto f B B ->\n  Subset A B -> preClosure1 f B A C1 -> preClosure2 f B A C2 -> \n  Intersect C1 NC1 -> Union C2 UC2 -> NC1 = UC2.\nProof.\n  intros f B A C1 C2 NC1 UC2 HfBB HAB HC1 HC2 HNC1 HUC2.\n  assert (Hne : ~ Empty C1).\n  { intros C. apply (C B). apply HC1. split; try assumption.\n    split; try apply Subset_Reflexive. intros fB HfB b H.\n    apply HfB in H. destruct H as [a [ab [Hab [Ha H]]]].\n    destruct HfBB as [Hf [Hdomf [ranf [Hranf Hsub]]]].\n    apply Hsub, Hranf. exists a, ab. split; try assumption. }\n  apply (SubsetSymmetric_iff_Equal). split.\n  - image UC2 f. rename x into fUC2. rename H into HfUC2.\n    assert (P : Subset fUC2 UC2).\n    { intros y H. apply HUC2. apply HfUC2 in H.\n      destruct H as [x [xy [Hxy [Hx H]]]]. apply HUC2 in Hx.\n      destruct Hx as [X [Hx HX]].\n      destruct HC2 as [PB [F [h [HF [HPB [Hh Hranh]]]]]]; try assumption.\n      apply Hranh in HX. destruct HX as [n [nX [HnX HX]]].\n      destruct Hh as [omga [e [Homga [He [[Hfh [Hdomh Hranh']] [Hhe Hhn']]]]]].\n      destruct Hranh' as [ranh' [Hranh' Hsub]].\n      succ n. rename x0 into n'. rename H0 into Hn'.\n      assert (H0 : exists domh, Domain h domh /\\ In n' domh).\n      { exists omga. split; try assumption. apply Homga.\n        apply (Succ_NaturalNumber n n'); try assumption.\n        apply Homga. apply Hdomh. exists X, nX. split; assumption. }\n      assert (H1 : exists domF, Domain F domF /\\ In X domF).\n      { exists PB. split. apply (GivenByImageClosure_Into f B); try assumption.\n        apply Hsub. apply Hranh'. exists n, nX. split; assumption. }\n      destruct (GivenByImageClosure_Into f B PB F) as [HfF _]; try assumption.\n      funval Hfh H0 h n'. rename x0 into Y. rename H2 into HY.\n      funval HfF H1 F X. rename x0 into Y'. rename H2 into HY'.\n      destruct HY' as [XY [HXY HXY']]; try assumption.\n      apply HF in HXY'. destruct HXY' as [X' [Y'' [fX [HXY' [HX' [HY' [HfX I]]]]]]].\n      exists Y''. split.\n      - apply I. right. apply HfX. exists x, xy. repeat (split; try assumption).\n        replace X' with X; try assumption.\n        apply (Enderton3A X Y' X' Y'' XY XY HXY HXY'). trivial.\n      - replace Y'' with Y. apply Hranh. exists n'. apply HY; try assumption.\n        transitivity Y'.\n        + apply (Hhn' n n' X Y Y'); try assumption.\n          * apply Hdomh. exists X, nX. split; try assumption.\n          * intros _ _. exists nX. split; try assumption.\n          * intros _ _. exists XY. split; try assumption.\n            apply HF. exists X', Y'', fX. repeat (split; try assumption).\n        + apply (Enderton3A X Y' X' Y'' XY XY HXY HXY'). trivial. }\n    assert (Q : In UC2 C1).\n    { apply HC1. \n      destruct HC2 as [PB [F [h [HF [HPB [Hh Hranh]]]]]]; try assumption.\n      destruct Hh as [omga [o [Homga [Ho [Hh [Hho Hhn']]]]]]. split; try split.\n      - intros a H. apply HUC2. exists A. split; try assumption.\n        apply Hranh. exists o. apply Hho; try apply Hh.\n        exists omga. split; try (apply Homga, Zero_NaturalNumber, Ho); apply Hh.\n      - intros b H. apply HUC2 in H. destruct H as [Y [H I]].\n        apply Hranh in I. destruct I as [X [XY [HXY I]]].\n        destruct Hh as [Hh [Hdomh [ranh [Hranh' Hsub]]]].\n        assert (T : In Y PB).\n        { apply Hsub. apply Hranh'. exists X, XY. split; assumption. }\n        apply HPB in T. apply T. assumption.\n      - intros fX HfX. replace fX with fUC2; try assumption.\n        apply (Image_Unique UC2 f); try assumption. }\n    intros x H. assert (R : forall X, In X C1 -> In x X).\n    { apply HNC1; try assumption. }\n    apply R, Q.\n  - intros y H. apply HUC2 in H. destruct H as [Y [H I]].\n    destruct HC2 as [PB [F [h [HF [HPB [Hh HC2]]]]]]; try assumption.\n    destruct Hh as [omga [o [Homga [Ho [Hh [Hho Hhn']]]]]].\n    build_set set\n      (fun (t c x : set) => forall hx, FunVal t x hx -> Subset hx NC1) h omga.\n    rename x into T. rename H0 into HT.\n    apply HC2 in I. destruct I as [n [nY [HnY I]]].\n    assert (P : In n omga).\n    { destruct Hh as [Hh [Hdomh _]]. apply Hdomh.\n      exists Y, nY. split; assumption. }\n    replace omga with T in P.\n    { apply HT in P. destruct P as [_ P]. apply (P Y); try assumption.\n      intros _ _. exists nY. split; assumption. }\n    apply Induction_Principle_for_Omega; try assumption; try split.\n    + exists o. split; try assumption. apply HT.\n      split; try apply Homga, Zero_NaturalNumber, Ho.\n      intros A' HA' a J. apply HNC1; try assumption.\n      intros X HX. apply HC1 in HX. destruct HX as [HX _].\n      apply HX. replace A with A'; try assumption.\n      apply (FunVal_Unique h o A' A); try assumption; try apply Hh.\n      exists omga. split. apply Hh. apply Homga, Zero_NaturalNumber, Ho.\n    + intros m m' Hm' Hm. apply HT in Hm. destruct Hm as [Hm IH].\n      apply HT. apply Homga in Hm.\n      split; try (apply Homga, (Succ_NaturalNumber m m'); try assumption).\n      intros X HX. destruct (GivenByImageClosure_Into f B PB F); try assumption.\n      destruct Hh as [Hh [Hdomh [ranh [Hranh Hsub]]]].\n      assert (H3 : exists domh, Domain h domh /\\ In m domh).\n      { exists omga. split; try assumption. apply Homga. assumption. }\n      funval Hh H3 h m. rename H2 into Hhm. rename x into hm.\n      assert (H2 : exists domF, Domain F domF /\\ In hm domF).\n      { exists PB; split. try apply H1. apply Hsub. apply Hranh.\n        exists m. apply Hhm; try assumption. }\n      funval H0 H2 F hm. rename x into Fhm. rename H4 into HFhm.\n      destruct HFhm as [hmFhm [HhmFhm HhmFhm']]; try assumption.\n      apply HF in HhmFhm' as [hm' [Fhm' [fhm [HhmFhm' [HhmB [HFhmB [Hfhm Q]]]]]]].\n      intros x J. replace X with Fhm' in J. apply Q in J.\n      assert (T0 : hm = hm' /\\ Fhm = Fhm').\n      { apply (Enderton3A hm Fhm hm' Fhm' hmFhm hmFhm HhmFhm HhmFhm'). trivial. }\n      replace hm' with hm in *; replace Fhm' with Fhm in *; try apply T0.\n      clear T0 hm' Fhm' HhmFhm'. destruct J as [J | J]; \n      try (apply (IH hm); assumption). apply Hfhm in J.\n      destruct J as [w [wx [Hwx [J K]]]]. apply HNC1; try assumption.\n      intros W HW. apply HC1 in HW.\n      image W f. rename x0 into fW. rename H4 into HfW.\n      destruct HW as [HW1 [HW2 HW]]. apply (HW fW); try assumption.\n      apply HfW. exists w, wx. repeat (split; try assumption).\n      apply IH in J; try assumption. assert (J' : forall y, In y C1 -> In w y).\n      { apply HNC1; try assumption. }\n      apply J'. apply HC1. repeat (split; try assumption).\n      { transitivity Fhm.\n        - apply (Enderton3A hm' Fhm' hm Fhm hmFhm hmFhm); try assumption. trivial.\n        - symmetry. apply (Hhn' m m' hm X Fhm); try assumption.\n          + apply Homga; try assumption.\n          + intros _ _. exists hmFhm. split; try assumption.\n            apply HF. exists hm', Fhm', fhm. repeat (split; try assumption). }\n    + intros t J. apply HT in J. apply J.\nQed.\n\n(** Exercise 4-10 : In exercise 9, assume that B is the set of real numbers,\n    f(x) = x^2, and A is the closed interval [0.5, 1]. What is the set called\n    NC1 or UC2?  TODO *)\n\n(** Exercise 4-11 : In exercise 9, assume that B is the set of real numbers,\n    f(x) = x - 1, and A = {0}. What is the set called NC1 or UC2? TODO *)\n\n(** Exercise 4-12 : Formulate an analog to Exercise 9 for a function f : BxB -> B.*)\n\n(** Having acheived the axiomatic basis for the natural numbers via Peano's\n    Postulates, we now turn our attention to the familiar arithmetic operations\n    on the natural numbers. We will given a set-theoretic definition of the\n    operations addition (+ : omega x omega -> omega), multiplication\n    ( * : omega x omega -> omega), and exponentiation (^ : omega x omega -> omega)\n    using the recursion theorem. We also prove some familiar algebraic\n    properties of these operations, which follow from Peano's postulates. *)\n\nDefinition Addn (n An : set) : Prop :=\n  NaturalNumber n -> exists omga sigma, Nats omga /\\ SuccessorFunc sigma /\\\n  RecursiveFunction omga n sigma An.\n\nTheorem Addn_Exists : forall n, NaturalNumber n -> exists An, Addn n An.\nProof.\n  intros n Hn. omga. sigma. apply Homga in Hn.\n  recursion omga n sigma Hn (SuccessorFunc_Into sigma omga Hsigma Homga).\n  rename x into An. rename H into HAn. exists An. intros _.\n  exists omga, sigma. repeat (split; try assumption).\nQed.\n\nTheorem Addn_Unique : forall n An Bn, NaturalNumber n -> Addn n An ->\n  Addn n Bn -> An = Bn.\nProof.\n  intros n An Bn Hn HAn HBn.\n  destruct HAn as [omga [sigma [Homga [Hsigma HAn]]]]; try assumption.\n  destruct HBn as [omga' [sigma' [Homga' [Hsigma' HBn]]]]; try assumption.\n  apply (RecursiveFunction_Unique omga n sigma); try assumption.\n  - apply Homga, Hn.\n  - apply SuccessorFunc_Into; try assumption.\n  - replace omga with omga'. replace sigma with sigma'; try assumption.\n    apply (SuccessorFunc_Unique); try assumption.\n    apply Nats_Unique; try assumption.\nQed.\n\nDefinition BinaryOperator (op A : set) : Prop :=\n  exists AxA, Prod A A AxA /\\ FuncFromInto op AxA A.\n\nDefinition Addition_w (add : set) : Prop :=\n  forall mnp, In mnp add <-> exists mn p m n Am, OrdPair mn p mnp /\\\n  OrdPair m n mn /\\ NaturalNumber m /\\ NaturalNumber n /\\ Addn m Am /\\\n  FunVal Am n p.\n\nTheorem Addition_w_Exists : exists add, Addition_w add.\nProof.\n  omga. prod omga omga. rename x into wxw. rename H into Hwxw.\n  prod wxw omga. rename x into wxwxw. rename H into Hwxwxw.\n  build_set\n    set\n    (fun (t c x : set) => exists mn p m n Am, OrdPair mn p x /\\\n      OrdPair m n mn /\\ NaturalNumber m /\\ NaturalNumber n /\\ Addn m Am /\\\n      FunVal Am n p)\n    omga\n    wxwxw.\n  rename x into add. rename H into Hadd. exists add.\n  intros mnp. split; intros H; try apply Hadd, H.\n  apply Hadd. split; try assumption.\n  apply Hwxwxw. destruct H as [mn [p [m [n [Am [Hmnp [Hmn [Hm [Hn [HAm Hp]]]]]]]]]].\n  exists mn, p. split; try split; try assumption.\n  - apply Hwxw. exists m, n.\n    repeat (split; try assumption); try apply Homga; assumption.\n  - destruct HAm as [omga' [sigma [Homga' [Hsigma HAm]]]]; try apply Hm.\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    clear omga' Homga'.\n    destruct HAm as [omga' [o [Homga' [Ho [HAm [HAmo HAmn']]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    clear omga' Homga'. destruct HAm as [HAm [HdomAm [ranAm [HranAm Hsub]]]].\n    apply Hsub. apply HranAm. exists n. apply Hp; try assumption.\n    exists omga. split; try assumption. apply Homga; assumption.\nQed. \n\nTheorem Addition_w_Unique : forall add add', Addition_w add -> Addition_w add' ->\n  add = add'.\nProof.\n  intros add add' H H'. apply Extensionality_Axiom. intros x. split; intros I.\n  - apply H', H, I.\n  - apply H, H', I.\nQed.\n\nLemma Addition_w_BinaryOperation : forall add omga, Addition_w add -> Nats omga ->\n  BinaryOperator add omga.\nProof.\n  intros add omga Hadd Homga.\n  prod omga omga. rename x into omgaxomga. rename H into Homgaxomga.\n  exists omgaxomga. split; try assumption. split; split.\n  - intros mnp Hmnp. apply Hadd in Hmnp.\n    destruct Hmnp as [mn [p [_ [_ [_ [Hmnp _]]]]]].\n    exists mn, p. assumption.\n  - intros mn p q mnp mnq Hmnp Hmnq H I.\n    apply Hadd in H. apply Hadd in I.\n    destruct H as [mn' [p' [m [n [Am [Hmnp' [Hmn [Hm [Hn [HAm Hp]]]]]]]]]].\n    assert (T : mn = mn' /\\ p = p').\n    { apply (Enderton3A mn p mn' p' mnp mnp Hmnp Hmnp'). trivial. }\n    replace mn' with mn in *; replace p' with p in *; try apply T.\n    clear T Hmnp' mn' p'.\n    destruct I as [mn' [q' [m' [n' [Am' [Hmnq' [Hmn' [_ [_ [HAm' Hq]]]]]]]]]].\n    assert (T : mn = mn' /\\ q = q').\n    { apply (Enderton3A mn q mn' q' mnq mnq Hmnq Hmnq'). trivial. }\n    replace mn' with mn in *; replace q' with q in *; try apply T.\n    clear T Hmnq' mn' q'.\n    assert (T : m = m' /\\ n = n').\n    { apply (Enderton3A m n m' n' mn mn Hmn Hmn'). trivial. }\n    replace m' with m in *; replace n' with n in *; try apply T.\n    clear m' n' T Hmn'.\n    replace Am' with Am in *; try apply (Addn_Unique m Am Am' Hm HAm HAm').\n    clear HAm' Am'.\n    destruct (HAm Hm) as [omga' [sigma [Homga' [Hsigma HAm']]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    clear Homga' omga'. destruct HAm' as [omga' [_ [Homga' [_ [HAm' _]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    apply (FunVal_Unique Am n p q); try assumption; try apply HAm'.\n    exists omga. split. apply HAm'. apply Homga, Hn.\n  - intros mn. split; intros H.\n    + apply Homgaxomga in H. destruct H as [m [n [Hm [Hn Hmn]]]].\n      apply Homga in Hm. destruct (Addn_Exists m Hm) as [Am HAm].\n      destruct (HAm Hm) as [omga' [sigma [Homga' [Hsigma HAm']]]].\n      replace omga' with omga in *; try (apply Nats_Unique; assumption).\n      clear Homga' omga'. destruct HAm' as [omga' [_ [Homga' [_ [HAm' _]]]]].\n      replace omga' with omga in *; try (apply Nats_Unique; assumption).\n      destruct HAm' as [HAm' [HdomAm _]].\n      assert (T : exists domAm, Domain Am domAm /\\ In n domAm).\n      { exists omga. split; try assumption. }\n      funval HAm' T Am n. rename x into p. rename H into Hp.\n      ordpair mn p. rename x into mnp. rename H into Hmnp.\n      exists p, mnp. split; try assumption. apply Hadd.\n      exists mn, p, m, n, Am. repeat (split; try assumption). apply Homga, Hn.\n    + destruct H as [p [mnp [Hmnp H]]]. apply Homgaxomga. apply Hadd in H.\n      destruct H as [mn' [p' [m [n [Am [Hmnp' [Hmn [Hm [Hn [HAm Hp]]]]]]]]]].\n      assert (T : mn = mn' /\\ p = p').\n      { apply (Enderton3A mn p mn' p' mnp mnp Hmnp Hmnp'). trivial. }\n      replace mn' with mn in *; replace p' with p in *; try apply T.\n      clear T mn' p' Hmnp'. exists m, n.\n      repeat (split; try assumption; try apply Homga; try assumption).\n  - exists omga. split; try apply Subset_Reflexive. intros p; split; intros H.\n    + zero. rename x into o. rename H0 into Ho.\n      ordpair p o. rename x into po. rename H0 into Hpo.\n      ordpair po p. rename x into pop. rename H0 into Hpop.\n      exists po, pop. split; try assumption. apply Hadd.\n      destruct (Addn_Exists p) as [Ap HAp]; try (apply Homga; assumption).\n      exists po, p, p, o, Ap. repeat (split; try apply Homga; try assumption).\n      * apply Homga, Zero_NaturalNumber, Ho.\n      * intros _ _. ordpair o p. rename x into op. rename H0 into Hop.\n        exists op. split; try assumption. apply Homga in H.\n        destruct (HAp H) as [omga' [sigma [Homga' [Hsigma HAp']]]].\n        replace omga' with omga in *; try apply Nats_Unique; try assumption.\n        clear omga' Homga'.\n        destruct HAp' as [omga' [o' [Homga' [Ho' [HAp' [HApo HApn']]]]]].\n        replace omga' with omga in *; try apply Nats_Unique; try assumption.\n        replace o' with o in *; try apply Empty_Unique; try assumption.\n        destruct HAp' as [HAp' [HdomAp _]].\n        assert (T : exists domAp, Domain Ap domAp /\\ In o domAp).\n        { exists omga. split; try assumption. apply Homga, Zero_NaturalNumber, Ho. }\n        destruct (HApo HAp' T) as [op' [Hop' Hop'']].\n        replace op with op'; try assumption.\n        apply (OrdPair_Unique o p op' op); try assumption.\n    + destruct H as [mn [mnp [Hmnp H]]]. apply Hadd in H.\n      destruct H as [mn' [p' [m [n [Am [Hmnp' [Hmn [Hm [Hn [HAm Hp]]]]]]]]]].\n      assert (T : mn = mn' /\\ p = p').\n      { apply (Enderton3A mn p mn' p' mnp mnp Hmnp Hmnp'). trivial. }\n      replace mn' with mn in *; replace p' with p in *; try apply T.\n      clear T mn' p' Hmnp'.\n      destruct (HAm Hm) as [omga' [sigma [Homga' [Hsigma HAm']]]].\n      replace omga' with omga in *; try apply Nats_Unique; try assumption.\n      clear omga' Homga'.\n      destruct HAm' as [omga' [o [Homga' [Ho [HAm' [HAmo HAmn']]]]]].\n      replace omga' with omga in *; try apply Nats_Unique; try assumption.\n      clear omga' Homga'.\n      destruct HAm' as [Ham' [HdomAm [ranAm [HranAm Hsub]]]].\n      apply Hsub. apply HranAm. exists n. apply Hp; try assumption.\n      exists omga. split; try assumption. apply Homga, Hn.\nQed.\n\nLtac add_w := destruct (Addition_w_Exists) as [add Hadd].\n\nDefinition Sum_w (m n p : set) : Prop := NaturalNumber m -> NaturalNumber n ->\n  exists add mn mnp, Addition_w add /\\ OrdPair m n mn\n  /\\ OrdPair mn p mnp /\\ In mnp add.\n\nTheorem Sum_w_Exists : forall m n, NaturalNumber m -> NaturalNumber n ->\n  exists p, Sum_w m n p.\nProof.\n  intros m n Hm Hn. ordpair m n. rename x into mn. rename H into Hmn.\n  add_w. omga. destruct (Addition_w_BinaryOperation add omga Hadd Homga) as\n    [omgaxomga [Homgaxomga H]].\n  destruct H as [Haddf [Hdomadd _]].\n  assert (P : In mn omgaxomga).\n  { apply Homgaxomga. exists m, n. repeat (split; try apply Homga; try assumption). }\n  apply Hdomadd in P. destruct P as [p [mnp [Hmnp P]]].\n  exists p. intros _ _. exists add, mn, mnp. repeat (split; try assumption).\nQed.\n\nTheorem Sum_w_Unique : forall m n p q, NaturalNumber m -> NaturalNumber n ->\n  Sum_w m n p -> Sum_w m n q -> p = q.\nProof.\n  intros m n p q Hm Hn Hp Hq.\n  destruct (Hp Hm Hn) as [add [mn [mnp [Hadd [Hmn [Hmnp Hp']]]]]].\n  destruct (Hq Hm Hn) as [add' [mn' [mnq [Hadd' [Hmn' [Hmnq Hq']]]]]].\n  replace add' with add in *; try (apply (Addition_w_Unique add add'); assumption).\n  replace mn' with mn in *; try (apply (OrdPair_Unique m n mn mn'); assumption).\n  clear add' mn' Hadd' Hmn'. omga.\n  destruct (Addition_w_BinaryOperation add omga Hadd Homga)\n    as [omgaxomga [Homgaxomga H]].\n  destruct H as [[_ Haddf] _]. apply (Haddf mn p q mnp mnq); try assumption.\nQed.\n\nLtac sum_w m n Hm Hn := destruct (Sum_w_Exists m n Hm Hn).\n\nDefinition A1 : Prop := forall m o, NaturalNumber m -> Empty o -> Sum_w m o m.\n\nDefinition A2 : Prop := forall m n n' mn mn' mn'', NaturalNumber m ->\n  NaturalNumber n -> Succ n n' -> Sum_w m n mn -> Sum_w m n' mn' -> Succ mn mn'' ->\n  mn' = mn''.\n\nTheorem Enderton4I : A1 /\\ A2.\nProof.\n  split.\n  - intros m o Hm Ho. intros _ _. add_w. exists add.\n    ordpair m o. rename x into mo. rename H into Hmno. exists mo.\n    ordpair mo m. rename x into mom. rename H into Hmom. exists mom.\n    repeat (split; try assumption). apply Hadd.\n    destruct (Addn_Exists m Hm) as [Am HAm]. exists mo, m, m, o, Am.\n    repeat (split; try assumption; try apply Zero_NaturalNumber, Ho).\n    intros _ _. destruct (HAm Hm) as [omga [sigma [Homga [Hsigma HAm']]]].\n    destruct HAm' as [omga' [o' [Homga' [Ho' [HAm' [HAmo _]]]]]].\n    replace omga' with omga in *; try apply Nats_Unique; try assumption.\n    clear omga' Homga'.\n    replace o' with o in *; try apply Empty_Unique; try assumption.\n    clear o' Ho'. apply HAmo; try apply HAm'.\n    exists omga. split. apply HAm'. apply Homga, Zero_NaturalNumber, Ho.\n  - intros m n n' mn mn' mn'' Hm Hn Hn' Hmn Hmn' Hmn''.\n    destruct (Hmn Hm Hn) as [add [mn0 [mn0mn [Hadd [Hmn0 [Hmnp H]]]]]].\n    apply Hadd in H.\n    destruct H as [mn0' [mn1 [m0 [n0 [Am [Hmn0mn' [Hmn0' [_ [_ [HAm HAmn]]]]]]]]]].\n    assert (T : mn0 = mn0' /\\ mn = mn1).\n    { apply (Enderton3A mn0 mn mn0' mn1 mn0mn mn0mn); try assumption. trivial. }\n    replace mn0' with mn0 in *; replace mn1 with mn in *; try apply T.\n    clear T mn0' mn1 Hmn0mn'.\n    assert (T : m = m0 /\\ n = n0).\n    { apply (Enderton3A m n m0 n0 mn0 mn0); try assumption. trivial. }\n    replace m0 with m in *; replace n0 with n in *; try apply T.\n    clear T m0 n0 Hmn0'.\n    assert (P : NaturalNumber n').\n    { apply (Succ_NaturalNumber n n'); try assumption. }\n    destruct (Hmn' Hm P) as [add' [mn'0 [mn'0mn' [Hadd' [Hmn'0 [Hmn'p I]]]]]].\n    replace add' with add in *; try (apply (Addition_w_Unique); assumption).\n    clear Hadd' add'. apply Hadd in I.\n    destruct I as [mn'0' [mn'1 [m0 [n'0 [Am' [Hmn'0mn'' [Hmn'0' [_ [_ [HAm' HAmn']]]]]]]]]].\n    assert (T : mn'0 = mn'0' /\\ mn' = mn'1).\n    { apply (Enderton3A mn'0 mn' mn'0' mn'1 mn'0mn' mn'0mn'); try assumption. trivial. }\n    replace mn'0' with mn'0 in *; replace mn'1 with mn' in *; try apply T.\n    clear T mn'0' mn'1 Hmn'0mn''.\n    assert (T : m = m0 /\\ n' = n'0).\n    { apply (Enderton3A m n' m0 n'0 mn'0 mn'0); try assumption. trivial. }\n    replace m0 with m in *; replace n'0 with n' in *; try apply T.\n    clear T m0 n'0 Hmn'0'.\n    replace Am' with Am in *; try (apply (Addn_Unique m Am Am'); assumption).\n    clear HAm' Am'. destruct (HAm Hm) as [omga [sigma [Homga [Hsigma HAm']]]].\n    destruct HAm' as [omga' [o [Homga' [Ho [HAm' [HAmo HAmsn]]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    apply (HAmsn n n' mn mn' mn''); try assumption; try apply Homga, Hn.\n    intros _ _. ordpair mn mn''. rename x into mnmn''. rename H into Hmnmn''.\n    exists mnmn''. split; try assumption. apply Hsigma.\n    exists mn, mn''. repeat (split; try assumption).\n    destruct HAm' as [HAm' [HdomAm [ranAm [HranAm Hsub]]]].\n    apply Homga, Hsub. apply HranAm. exists n. apply HAmn; try assumption.\n    exists omga. split; try assumption. apply Homga, Hn.\nQed.\n\nDefinition Multn (n Mn : set) : Prop :=\n  NaturalNumber n -> exists omga An o, Nats omga /\\ Addn n An /\\ Empty o /\\\n  RecursiveFunction omga o An Mn.\n\nTheorem Multn_Exists : forall n, NaturalNumber n -> exists Mn, Multn n Mn.\nProof.\n  intros n Hn. destruct (Addn_Exists n Hn) as [An HAn].\n  destruct (HAn Hn) as [omga [sigma [Homga [Hsigma HAn']]]].\n  destruct HAn' as [omga' [o [Homga' [Ho [HAn' [HAno HAnn']]]]]].\n  replace omga' with omga in *; try (apply Nats_Unique; assumption).\n  assert (T : In o omga). { apply Homga, Zero_NaturalNumber, Ho. }\n  recursion omga o An T HAn'. rename x into Mn. rename H into HMn.\n  exists Mn. intros _. exists omga, An, o. repeat (split; try assumption).\nQed.\n\nTheorem Multn_Unique : forall n Mn Nn, NaturalNumber n ->\n  Multn n Mn -> Multn n Nn -> Mn = Nn.\nProof.\n  intros n Mn Nn Hn HMn HNn.\n  destruct (HMn Hn) as [omga [An [o [Homga [HAn [Ho HMn']]]]]].\n  destruct (HNn Hn) as [omga' [Bn [o' [Homga' [HBn [Ho' HNn']]]]]].\n  replace o' with o in *; try (apply Empty_Unique; assumption).\n  replace omga' with omga in *; try (apply Nats_Unique; assumption).\n  clear omga' Homga' o' Ho'.\n  replace Bn with An in *; try\n    (apply (RecursiveFunction_Unique omga o An Mn);\n    try assumption;\n    try apply Homga, Zero_NaturalNumber, Ho).\n  - destruct (HAn Hn) as [omga' [sigma [Homga' [Hsigma HAn']]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    clear omga' Homga'. destruct HAn' as [omga' [o' [Homga' [Ho' [HAn' _]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    assumption.\n  - apply (Addn_Unique n An Bn Hn); assumption.\nQed.\n\nDefinition Multiplication_w (mult : set) : Prop :=\n  forall mnp, In mnp mult <-> exists mn p m n Mm, OrdPair mn p mnp /\\\n  OrdPair m n mn /\\ NaturalNumber m /\\ NaturalNumber n /\\ Multn m Mm /\\\n  FunVal Mm n p.\n\nTheorem Multiplication_w_Exists : exists mult, Multiplication_w mult.\nProof.\n  omga. prod omga omga. rename x into wxw. rename H into Hwxw.\n  prod wxw omga. rename x into wxwxw. rename H into Hwxwxw.\n  build_set\n    set\n    (fun (t c x : set) => exists mn p m n Mm, OrdPair mn p x /\\\n      OrdPair m n mn /\\ NaturalNumber m /\\ NaturalNumber n /\\ Multn m Mm /\\\n      FunVal Mm n p)\n    omga\n    wxwxw.\n  rename x into mult. rename H into Hmult. exists mult.\n  intros mnp. split; intros H; try apply Hmult; try assumption.\n  split; try apply H.\n  destruct H as [mn [p [m [n [Mm [Hmnp [Hmn [Hm [Hn [HMm H]]]]]]]]]].\n  apply Hwxwxw. exists mn, p. repeat (split; try assumption).\n  - apply Hwxw. exists m, n. repeat (split; try apply Homga; try assumption).\n  - destruct (HMm Hm) as [omga' [Am [o [Homga' [HAm [Ho HMm']]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    clear omga' Homga'. destruct HMm' as [omga' [o' [Homga' [Ho' [HMm' _]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    destruct HMm' as [HMm' [HdomMm [ranMm [HranMm Hsub]]]].\n    apply Hsub. apply HranMm. exists n. apply H; try assumption.\n    exists omga. split; try assumption. apply Homga, Hn.\nQed.\n\nTheorem Multiplication_w_Unique : forall mult mult',\n  Multiplication_w mult -> Multiplication_w mult' -> mult = mult'.\nProof.\n  intros mult mult' Hmult Hmult'.\n  apply Extensionality_Axiom. intros mnp. split; intros H.\n  - apply Hmult', Hmult, H.\n  - apply Hmult, Hmult', H.\nQed.\n\nLemma Multiplication_w_BinaryOperation : forall mult omga,\n  Multiplication_w mult -> Nats omga -> BinaryOperator mult omga.\nProof.\n  intros mult omga Hmult Homga.\n  prod omga omga. rename x into wxw. rename H into Hwxw.\n  exists wxw. split; try assumption. split; split.\n  - intros mnp Hmnp. apply Hmult in Hmnp.\n    destruct Hmnp as [mn [p [m [n [Mm [Hmnp [Hmn [Hm [Hn [HMm Hp]]]]]]]]]].\n    exists mn, p. assumption.\n  - intros mn p q mnp mnq Hmnp Hmnq H I.\n    apply Hmult in H.\n    destruct H as [mn' [p' [m [n [Mm [Hmnp' [Hmn [Hm [Hn [HMm Hp]]]]]]]]]].\n    assert (T : mn = mn' /\\ p = p').\n    { apply (Enderton3A mn p mn' p' mnp mnp Hmnp Hmnp'). trivial. }\n    replace mn' with mn in *; replace p' with p in *; try apply T.\n    clear mn' Hmnp' p' T. apply Hmult in I.\n    destruct I as [mn' [q' [m' [n' [Mm' [Hmnq' [Hmn' [_ [_ [HMm' Hq]]]]]]]]]].\n    assert (T : mn = mn' /\\ q = q').\n    { apply (Enderton3A mn q mn' q' mnq mnq Hmnq Hmnq'). trivial. }\n    replace mn' with mn in *; replace q' with q in *; try apply T.\n    clear mn' q' Hmnq' T.\n    assert (T : m = m' /\\ n = n').\n    { apply (Enderton3A m n m' n' mn mn Hmn Hmn'). trivial. }\n    replace m' with m in *; replace n' with n in *; try apply T.\n    clear m' n' T Hmn'.\n    replace Mm' with Mm in *; try (apply (Multn_Unique m Mm Mm'); assumption).\n    clear Mm' HMm'.\n    destruct (HMm Hm) as [omga' [Am [o [Homga' [HAm [Ho HMm']]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    clear omga' Homga'. destruct HMm' as [omga' [o' [Homga' [Ho' [HMm' _]]]]].\n    apply (FunVal_Unique Mm n p q); try assumption; try apply HMm'.\n    exists omga'. split. apply HMm'. apply Homga'. apply Hn.\n  - intros mn. split; intros H.\n    + apply Hwxw in H. destruct H as [m [n [Hm [Hn Hmn]]]].\n      apply Homga in Hm. destruct (Multn_Exists m Hm).\n      rename x into Mm. rename H into HMm.\n      destruct (HMm Hm) as [omga' [Am [o [Homga' [HAm [Ho HMm']]]]]].\n      replace omga' with omga in *; try (apply Nats_Unique; assumption).\n      clear omga' Homga'. destruct HMm' as [omga' [o' [Homga' [Ho' [HMm' _]]]]].\n      replace omga' with omga in *; try (apply Nats_Unique; assumption).\n      clear omga' Homga'. destruct HMm' as [HMm' [domMm' [ranMm' [HranMm' Hsub]]]].\n      replace o' with o in *; try (apply Empty_Unique; assumption).\n      clear o' Ho'. assert (P : exists domMm, Domain Mm domMm /\\ In n domMm).\n      { exists omga. split; try assumption. }\n      funval HMm' P Mm n. rename x into p. rename H into Hp.\n      destruct (Hp HMm' P) as [np [Hnp Hnp']].\n      ordpair mn p. rename x into mnp. rename H into Hmnp.\n      exists p, mnp. split; try assumption. apply Hmult.\n      exists mn, p, m, n, Mm. repeat (split; try assumption).\n      apply Homga; try assumption.\n    + destruct H as [p [mnp [Hmnp H]]]. apply Hmult in H.\n      destruct H as [mn' [p' [m [n [Mm [Hmnp' [Hmn [Hm [Hn [HMm Hp]]]]]]]]]].\n      assert (T : mn = mn' /\\ p = p').\n      { apply (Enderton3A mn p mn' p' mnp mnp Hmnp Hmnp'). trivial. }\n      replace mn' with mn in *; replace p' with p in *; try apply T.\n      clear mn' p' Hmnp' T. apply Hwxw. exists m, n.\n      repeat (split; try apply Homga; try assumption).\n  - range mult. rename x into ranmult. rename H into Hranmult.\n    exists ranmult. split; try assumption. intros p Hp.\n    apply Hranmult in Hp. destruct Hp as [mn [mnp [Hmnp H]]]. apply Hmult in H.\n    destruct H as [mn' [p' [m [n [Mm [Hmnp' [Hmn [Hm [Hn [HMm Hp]]]]]]]]]].\n    assert (T : mn = mn' /\\ p = p').\n    { apply (Enderton3A mn p mn' p' mnp mnp Hmnp Hmnp'). trivial. }\n    replace mn' with mn in *; replace p' with p in *; try apply T.\n    clear mn' p' Hmnp' T.\n    destruct (HMm Hm) as [omga' [Am [o [Homga' [HAm [Ho HMm']]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    clear omga' Homga'. destruct HMm' as [omga' [o' [Homga' [Ho' [HMm' _]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    clear omga' Homga'. destruct HMm' as [HMm' [HdomMm [ranMm [HranMm Hsub]]]].\n    apply Hsub. apply HranMm. exists n. apply Hp; try assumption.\n    exists omga. split; try assumption. apply Homga. assumption.\nQed.\n\nLtac mult_w := destruct (Multiplication_w_Exists) as [mult Hmult].\n\nDefinition Prod_w (m n p : set) : Prop := NaturalNumber m -> NaturalNumber n ->\n  exists mult mn mnp, Multiplication_w mult /\\ OrdPair m n mn\n  /\\ OrdPair mn p mnp /\\ In mnp mult.\n\nTheorem Prod_w_Exists : forall m n, NaturalNumber m -> NaturalNumber n ->\n  exists p, Prod_w m n p.\nProof.\n  intros m n Hm Hn. mult_w. omga.\n  destruct (Multiplication_w_BinaryOperation mult omga Hmult Homga) as [wxw [Hwxw H]].\n  destruct H as [Hmultf [Hdommult [ranmult [Hranmult Hsub]]]].\n  ordpair m n. rename x into mn. rename H into Hmn.\n  assert (P : In mn wxw).\n  { apply Hwxw. exists m, n. repeat (split; try apply Homga; try assumption). }\n  apply Hdommult in P. destruct P as [p [mnp [Hmnp P]]].\n  exists p. intros _ _. exists mult, mn, mnp. repeat (split; try assumption).\nQed.\n\nTheorem Prod_w_Unique : forall m n p q, NaturalNumber m -> NaturalNumber n ->\n  Prod_w m n p -> Prod_w m n q -> p = q.\nProof.\n  intros m n p q Hm Hn Hp Hq. omga.\n  destruct (Hp Hm Hn) as [mult [mn [mnp [Hmult [Hmn [Hmnp H]]]]]].\n  destruct (Hq Hm Hn) as [mult' [mn' [mnq [Hmult' [Hmn' [Hmnq I]]]]]].\n  replace mult' with mult in *;\n    try (apply (Multiplication_w_Unique mult mult'); assumption).\n  replace mn' with mn in *; try (apply (OrdPair_Unique m n mn mn'); assumption).\n  clear mn' Hmult' Hmn' mult'.\n  destruct (Multiplication_w_BinaryOperation mult omga Hmult Homga) as [wxw [Hwxw P]].\n  destruct P as [Hmultf [Hdommult [ranmult [Hranmult Hsub]]]].\n  destruct Hmultf as [_ Hmultf].\n  apply (Hmultf mn p q mnp mnq Hmnp Hmnq H I).\nQed.\n\nLtac prod_w m n Hm Hn := destruct (Prod_w_Exists m n Hm Hn).\n\nDefinition M1 : Prop := forall m o, NaturalNumber m -> Empty o -> Prod_w m o o.\n\nDefinition M2 : Prop := forall m n mtn n' mtn' mpmtn, NaturalNumber m ->\n  NaturalNumber n -> Prod_w m n mtn -> Succ n n' -> Prod_w m n' mtn' -> Sum_w m mtn mpmtn ->\n  mtn' = mpmtn.\n\nTheorem Enderton4J : M1 /\\ M2.\nProof.\n  split.\n  - intros m o Hm Ho _ _. mult_w.\n    ordpair m o. rename x into mo. rename H into Hmo. exists mult, mo.\n    ordpair mo o. rename x into moo. rename H into Hmoo. exists moo.\n    repeat (split; try assumption).\n    destruct (Multn_Exists m Hm). rename x into Mm. rename H into HMm.\n    apply Hmult. exists mo, o, m, o, Mm. repeat (split; try assumption).\n    + apply (Zero_NaturalNumber). assumption.\n    + destruct (HMm Hm) as [omga [Am [o' [Homga [HAm [Ho' HMm']]]]]].\n      replace o' with o in *; try (apply Empty_Unique; assumption).\n      clear o' Ho'. destruct HMm' as [omga' [o' [Homga' [Ho' [HMm' [HMmo _]]]]]].\n      replace o' with o in *; try (apply Empty_Unique; assumption).\n      clear o' Ho'. assumption.\n  - intros m n mtn n' mtn' mpmtn Hm Hn Hmtn Hn' Hmtn' Hmpmtn.\n    destruct (Hmtn Hm Hn) as [mult [mn [mnp [Hmult [Hmn [Hmnp H]]]]]].\n    apply Hmult in H.\n    destruct H as [mn' [mtn0 [m0 [n0 [Mm [Hmnp' [Hmn' [_ [_ [HMm Hp]]]]]]]]]].\n    assert (T : mn = mn' /\\ mtn = mtn0).\n    { apply (Enderton3A mn mtn mn' mtn0 mnp mnp); try assumption. trivial. }\n    replace mn' with mn in *; replace mtn0 with mtn in *; try apply T.\n    clear T mn' mtn0 Hmnp'. assert (T : m = m0 /\\ n = n0).\n    { apply (Enderton3A m n m0 n0 mn mn Hmn Hmn'). trivial. }\n    replace m0 with m in *; replace n0 with n in *; try apply T.\n    clear T m0 n0 Hmn'. destruct (HMm Hm) as [omga [Am [o [Homga [HAm [Ho HMm']]]]]].\n    destruct HMm' as [omga' [o' [Homga' [Ho' [HMm' [_ HMmn']]]]]].\n    replace o' with o in *; try (apply Empty_Unique; assumption).\n    clear o' Ho'.\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    clear omga' Homga'.\n    apply (HMmn' n n' mtn mtn' mpmtn); try assumption; try apply Homga, Hn.\n    + destruct (Hmtn' Hm) as [mult' [mn' [mn'p [Hmult' [Hmn' [Hmn'p I]]]]]];\n        try (apply (Succ_NaturalNumber n n'); assumption).\n      replace mult' with mult in *; try (apply Multiplication_w_Unique; assumption).\n      clear mult' Hmult'. apply Hmult in I.\n      destruct I as [mn'0 [mtn'0 [m0 [n'0 [Mm0 [Hmn'p' [Hmn'0 [_ [_ [HMm0 Hp']]]]]]]]]].\n      assert (T : mn' = mn'0 /\\ mtn' = mtn'0).\n      { apply (Enderton3A mn' mtn' mn'0 mtn'0 mn'p mn'p); try assumption. trivial. }\n      replace mn'0 with mn' in *; replace mtn'0 with mtn' in *; try apply T.\n      clear mn'0 mtn'0 T Hmn'p'. assert (T : m = m0 /\\ n' = n'0).\n      { apply (Enderton3A m n' m0 n'0 mn' mn' Hmn' Hmn'0). trivial. }\n      replace m0 with m in *; replace n'0 with n' in *; try apply T.\n      clear m0 n'0 T Hmn'0. replace Mm with Mm0; try assumption.\n      apply (Multn_Unique m); try assumption.\n    + destruct Hmpmtn as [add [mp [mpq [Hadd [Hmp [Hmpq I]]]]]]; try assumption.\n      { destruct HMm' as [HMm' [HdomMm [ranMm [HranMm Hsub]]]].\n        apply Homga. apply Hsub. apply HranMm. exists n.\n        apply Hp; try assumption. exists omga. split; try assumption.\n        apply Homga. assumption. }\n      apply Hadd in I.\n      destruct I as [mp' [mpmtn0 [m0 [mtn0 [Am' [Hmpq' [Hmn0 [_ [_ [HMm0 Hq]]]]]]]]]].\n      assert (T : mp = mp' /\\ mpmtn = mpmtn0).\n      { apply (Enderton3A mp mpmtn mp' mpmtn0 mpq mpq); try assumption. trivial. }\n      replace mp' with mp in *; replace mpmtn0 with mpmtn in *; try apply T.\n      clear mp' mpmtn0 T Hmpq'. assert (T : m = m0 /\\ mtn = mtn0).\n      { apply (Enderton3A m mtn m0 mtn0 mp mp); try assumption. trivial. }\n      replace mtn0 with mtn in *; replace m0 with m in *; try apply T.\n      clear mtn0 m0 T Hmn0. replace Am with Am'; try assumption.\n      apply (Addn_Unique m); try assumption.\nQed.\n\nDefinition Expn (n En : set) : Prop :=\n  NaturalNumber n -> exists omga Mn o o', Nats omga /\\ Multn n Mn /\\ Empty o /\\\n  Succ o o' /\\ RecursiveFunction omga o' Mn En.\n\nTheorem Expn_Exists : forall n, NaturalNumber n -> exists En, Expn n En.\nProof.\n  intros n Hn. destruct (Multn_Exists n Hn) as [Mn HMn].\n  destruct (HMn Hn) as [omga [An [o [Homga [HAn [Ho HMn']]]]]].\n  destruct HMn' as [omga' [o' [Homga' [Ho' [HMn' [HMno HMnn']]]]]].\n  replace omga' with omga in *; try (apply Nats_Unique; assumption).\n  replace o' with o in *; try (apply Empty_Unique; assumption).\n  clear o' Ho' omga' Homga'.\n  succ o. rename x into o'. rename H into Ho'. assert (T : In o' omga).\n  { apply Homga, (Succ_NaturalNumber o o'); try assumption.\n    apply Zero_NaturalNumber. assumption. }\n  recursion omga o' Mn T HMn'. rename x into En. rename H into HEn.\n  exists En. intros _. exists omga, Mn, o, o'. repeat (split; try assumption).\nQed.\n\nTheorem Expn_Unique : forall n En Fn, NaturalNumber n ->\n  Expn n En -> Expn n Fn -> En = Fn.\nProof.\n  intros n En Fn Hn HEn HFn.\n  destruct (HEn Hn) as [omga [Mn [o [o' [Homga [HMn [Ho [Ho' HEn']]]]]]]].\n  destruct (HFn Hn) as [omga' [Nn [o0 [o'0 [Homga' [HNn [Ho0 [Ho'0 HFn']]]]]]]].\n  replace o0 with o in *; try (apply Empty_Unique; assumption).\n  replace o'0 with o' in *; try (apply (Succ_Unique o); assumption).\n  replace omga' with omga in *; try (apply Nats_Unique; assumption).\n  clear omga' Homga' o0 Ho0 o'0 Ho'0.\n  replace Nn with Mn in *; try\n    (apply (RecursiveFunction_Unique omga o' Mn En);\n    try assumption).\n  - apply Homga. apply (Succ_NaturalNumber o o'); try assumption.\n    apply Zero_NaturalNumber, Ho.\n  - destruct (HMn Hn) as [omga' [An [o0 [Homga' [HAn [Ho0 HMn']]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    replace o0 with o in *; try (apply Empty_Unique; assumption).\n    clear omga' Homga' o0 Ho0. destruct HMn' as [omga' [o0 [Homga' [Ho0 [HMn' _]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    replace o0 with o in *; try (apply Empty_Unique; assumption).\n    assumption.\n  - apply (Multn_Unique n Mn Nn Hn); assumption.\nQed.\n\nDefinition Exponentiation_w (exp : set) : Prop :=\n  forall mnp, In mnp exp <-> exists mn p m n Em, OrdPair mn p mnp /\\\n  OrdPair m n mn /\\ NaturalNumber m /\\ NaturalNumber n /\\ Expn m Em /\\\n  FunVal Em n p.\n\nTheorem Exponentiation_w_Exists : exists exp, Exponentiation_w exp.\nProof.\n  omga. prod omga omga. rename x into wxw. rename H into Hwxw.\n  prod wxw omga. rename x into wxwxw. rename H into Hwxwxw.\n  build_set\n    set\n    (fun (t c x : set) => exists mn p m n Em, OrdPair mn p x /\\\n      OrdPair m n mn /\\ NaturalNumber m /\\ NaturalNumber n /\\ Expn m Em /\\\n      FunVal Em n p)\n    omga\n    wxwxw.\n  rename x into exp. rename H into Hexp. exists exp.\n  intros mnp. split; intros H; try apply Hexp; try apply H.\n  split; try apply H.\n  destruct H as [mn [p [m [n [En [Hmnp [Hmn [Hm [Hn [HEn H]]]]]]]]]].\n  apply Hwxwxw. exists mn, p. repeat (split; try assumption).\n  - apply Hwxw. exists m, n. repeat (split; try apply Homga; try assumption).\n  - destruct (HEn Hm) as [omga' [Mn [o [o' [Homga' [HMn [Ho [Ho' HEn']]]]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    clear omga' Homga'. destruct HEn' as [omga' [o'0 [Homga' [Ho'0 [HEn' _]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    destruct HEn' as [HEn' [HdomEn [ranEn [HranEn Hsub]]]].\n    apply Hsub. apply HranEn. exists n. apply H; try assumption.\n    exists omga. split; try assumption. apply Homga, Hn.\nQed.\n\nTheorem Exponentiation_w_Unique : forall exp exp',\n  Exponentiation_w exp -> Exponentiation_w exp' -> exp = exp'.\nProof.\n  intros exp exp' Hexp Hexp'.\n  apply Extensionality_Axiom. intros mnp. split; intros H.\n  - apply Hexp', Hexp, H.\n  - apply Hexp, Hexp', H.\nQed.\n\nLemma Exponentiation_w_BinaryOperation : forall exp omga,\n  Exponentiation_w exp -> Nats omga -> BinaryOperator exp omga.\nProof.\n  intros exp omga Hexp Homga.\n  prod omga omga. rename x into wxw. rename H into Hwxw.\n  exists wxw. split; try assumption. split; split.\n  - intros mnp Hmnp. apply Hexp in Hmnp.\n    destruct Hmnp as [mn [p [m [n [En [Hmnp [Hmn [Hm [Hn [HEn Hp]]]]]]]]]].\n    exists mn, p. assumption.\n  - intros mn p q mnp mnq Hmnp Hmnq H I.\n    apply Hexp in H.\n    destruct H as [mn' [p' [m [n [En [Hmnp' [Hmn [Hm [Hn [HEn Hp]]]]]]]]]].\n    assert (T : mn = mn' /\\ p = p').\n    { apply (Enderton3A mn p mn' p' mnp mnp Hmnp Hmnp'). trivial. }\n    replace mn' with mn in *; replace p' with p in *; try apply T.\n    clear mn' Hmnp' p' T. apply Hexp in I.\n    destruct I as [mn' [q' [m' [n' [En' [Hmnq' [Hmn' [_ [_ [HEn' Hq]]]]]]]]]].\n    assert (T : mn = mn' /\\ q = q').\n    { apply (Enderton3A mn q mn' q' mnq mnq Hmnq Hmnq'). trivial. }\n    replace mn' with mn in *; replace q' with q in *; try apply T.\n    clear mn' q' Hmnq' T.\n    assert (T : m = m' /\\ n = n').\n    { apply (Enderton3A m n m' n' mn mn Hmn Hmn'). trivial. }\n    replace m' with m in *; replace n' with n in *; try apply T.\n    clear m' n' T Hmn'.\n    replace En' with En in *; try (apply (Expn_Unique m En En'); assumption).\n    clear En' HEn'.\n    destruct (HEn Hm) as [omga' [Mn [o [o' [Homga' [HMn [Ho [Ho' HEn']]]]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    clear omga' Homga'. destruct HEn' as [omga' [o0 [Homga' [Ho0 [HEn' _]]]]].\n    apply (FunVal_Unique En n p q); try assumption; try apply HEn'.\n    exists omga'. split. apply HEn'. apply Homga'. apply Hn.\n  - intros mn. split; intros H.\n    + apply Hwxw in H. destruct H as [m [n [Hm [Hn Hmn]]]].\n      apply Homga in Hm. destruct (Expn_Exists m Hm).\n      rename x into En. rename H into HEn.\n      destruct (HEn Hm) as [omga' [Mn [o [o' [Homga' [HMn [Ho [Ho' HEn']]]]]]]].\n      replace omga' with omga in *; try (apply Nats_Unique; assumption).\n      clear omga' Homga'. destruct HEn' as [omga' [o0 [Homga' [Ho0 [HEn' _]]]]].\n      replace omga' with omga in *; try (apply Nats_Unique; assumption).\n      clear omga' Homga'. destruct HEn' as [HEn' [domEn' [ranEn' [HranEn' Hsub]]]].\n      replace o0 with o in *; try (apply Empty_Unique; assumption).\n      clear o0 Ho0. assert (P : exists domEn, Domain En domEn /\\ In n domEn).\n      { exists omga. split; try assumption. }\n      funval HEn' P En n. rename x into p. rename H into Hp.\n      destruct (Hp HEn' P) as [np [Hnp Hnp']].\n      ordpair mn p. rename x into mnp. rename H into Hmnp.\n      exists p, mnp. split; try assumption. apply Hexp.\n      exists mn, p, m, n, En. repeat (split; try assumption).\n      apply Homga; try assumption.\n    + destruct H as [p [mnp [Hmnp H]]]. apply Hexp in H.\n      destruct H as [mn' [p' [m [n [En [Hmnp' [Hmn [Hm [Hn [HEn Hp]]]]]]]]]].\n      assert (T : mn = mn' /\\ p = p').\n      { apply (Enderton3A mn p mn' p' mnp mnp Hmnp Hmnp'). trivial. }\n      replace mn' with mn in *; replace p' with p in *; try apply T.\n      clear mn' p' Hmnp' T. apply Hwxw. exists m, n.\n      repeat (split; try apply Homga; try assumption).\n  - range exp. rename x into ranexp. rename H into Hranexp.\n    exists ranexp. split; try assumption. intros p Hp.\n    apply Hranexp in Hp. destruct Hp as [mn [mnp [Hmnp H]]]. apply Hexp in H.\n    destruct H as [mn' [p' [m [n [En [Hmnp' [Hmn [Hm [Hn [HEn Hp]]]]]]]]]].\n    assert (T : mn = mn' /\\ p = p').\n    { apply (Enderton3A mn p mn' p' mnp mnp Hmnp Hmnp'). trivial. }\n    replace mn' with mn in *; replace p' with p in *; try apply T.\n    clear mn' p' Hmnp' T.\n    destruct (HEn Hm) as [omga' [Mn [o [o' [Homga' [HMn [Ho [Ho' HEn']]]]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    clear omga' Homga'. destruct HEn' as [omga' [o0 [Homga' [Ho0 [HEn' _]]]]].\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    clear omga' Homga'. destruct HEn' as [HMm' [HdomEn [ranEn [HranEn Hsub]]]].\n    apply Hsub. apply HranEn. exists n. apply Hp; try assumption.\n    exists omga. split; try assumption. apply Homga. assumption.\nQed.\n\nLtac exp_w := destruct (Exponentiation_w_Exists) as [exp Hexp].\n\nDefinition Pow_w (m n p : set) : Prop := NaturalNumber m -> NaturalNumber n ->\n  exists exp mn mnp, Exponentiation_w exp /\\ OrdPair m n mn\n  /\\ OrdPair mn p mnp /\\ In mnp exp.\n\nTheorem Pow_w_Exists : forall m n, NaturalNumber m -> NaturalNumber n ->\n  exists p, Pow_w m n p.\nProof.\n  intros m n Hm Hn. exp_w. omga.\n  destruct (Exponentiation_w_BinaryOperation exp omga Hexp Homga) as [wxw [Hwxw H]].\n  destruct H as [Hmultf [Hdommult [ranmult [Hranmult Hsub]]]].\n  ordpair m n. rename x into mn. rename H into Hmn.\n  assert (P : In mn wxw).\n  { apply Hwxw. exists m, n. repeat (split; try apply Homga; try assumption). }\n  apply Hdommult in P. destruct P as [p [mnp [Hmnp P]]].\n  exists p. intros _ _. exists exp, mn, mnp. repeat (split; try assumption).\nQed.\n\nTheorem Pow_w_Unique : forall m n p q, NaturalNumber m -> NaturalNumber n ->\n  Pow_w m n p -> Pow_w m n q -> p = q.\nProof.\n  intros m n p q Hm Hn Hp Hq. omga.\n  destruct (Hp Hm Hn) as [exp [mn [mnp [Hexp [Hmn [Hmnp H]]]]]].\n  destruct (Hq Hm Hn) as [exp' [mn' [mnq [Hexp' [Hmn' [Hmnq I]]]]]].\n  replace exp' with exp in *;\n    try (apply (Exponentiation_w_Unique exp exp'); assumption).\n  replace mn' with mn in *; try (apply (OrdPair_Unique m n mn mn'); assumption).\n  clear mn' Hexp' Hmn' exp'.\n  destruct (Exponentiation_w_BinaryOperation exp omga Hexp Homga) as [wxw [Hwxw P]].\n  destruct P as [Hexpf [Hdomexp [ranexp [Hranexp Hsub]]]].\n  destruct Hexpf as [_ Hexpf].\n  apply (Hexpf mn p q mnp mnq Hmnp Hmnq H I).\nQed.\n\nLtac pow_w m n Hm Hn := destruct (Pow_w_Exists m n Hm Hn).\n\nDefinition E1 : Prop := forall m o o', NaturalNumber m -> Empty o ->\n  Succ o o' -> Pow_w m o o'.\n\nDefinition E2 : Prop := forall m n men n' men' mtmen, NaturalNumber m ->\n  NaturalNumber n -> Pow_w m n men -> Succ n n' -> Pow_w m n' men' ->\n  Prod_w m men mtmen -> men' = mtmen.\n\nTheorem Enderton4J' : E1 /\\ E2.\nProof.\n  split.\n  - intros m o o' Hm Ho Ho'. assert (P : NaturalNumber o).\n    { apply Zero_NaturalNumber. assumption. }\n    assert (Q : NaturalNumber o').\n    { apply (Succ_NaturalNumber o o'); assumption. }\n    intros _ _. exp_w. ordpair m o. rename x into mo. rename H into Hmo.\n    ordpair mo o'. rename x into moo'. rename H into Hmoo'.\n    exists exp, mo, moo'. repeat (split; try assumption).\n    apply Hexp. destruct (Expn_Exists m Hm). rename x into Em. rename H into HEm.\n    exists mo, o', m, o, Em. repeat (split; try assumption). intros _ _.\n    ordpair o o'. rename x into oo'. rename H into Hoo'.\n    exists oo'. split; try assumption.\n    destruct (HEm Hm) as [omga [Mm [o0 [o'0 [Homga [HMm [Ho0 [Ho'0 HEm']]]]]]]].\n    replace o0 with o in *; try (apply Empty_Unique; assumption).\n    replace o'0 with o' in *; try (apply (Succ_Unique o); assumption).\n    clear o0 o'0 Ho0 Ho'0.\n    destruct HEm' as [omga' [o0 [Homga' [Ho0 [HEm' [HEmo _]]]]]].\n    replace o0 with o in *; try (apply Empty_Unique; assumption).\n    replace omga' with omga in *; try (apply Nats_Unique; assumption).\n    destruct HEmo as [oo'0 [Hoo'0 Hoo'0']].\n    { apply HEm'. }\n    { exists omga. split. apply HEm'. apply Homga, Zero_NaturalNumber, Ho. }\n    replace oo' with oo'0; try assumption.\n    apply (OrdPair_Unique o o'); try assumption.\n  - intros m n men n' men' mtmen Hm Hn Hmen Hn' Hmen' Hmentm.\n    destruct (Hmen Hm Hn) as [exp [mn [mnp [Hexp [Hmn [Hmnp H]]]]]].\n    apply Hexp in H.\n    destruct H as [mn' [p' [m' [n0 [Em [Hmnp' [Hmn' [_ [_ [HEm Hp]]]]]]]]]].\n    assert (T : mn = mn' /\\ men = p').\n    { apply (Enderton3A mn men mn' p' mnp mnp Hmnp Hmnp'). trivial. }\n    replace mn' with mn in *; replace p' with men in *; try apply T.\n    clear mn' p' T Hmnp'. assert (T : m = m' /\\ n = n0).\n    { apply (Enderton3A m n m' n0 mn mn Hmn Hmn'). trivial. }\n    replace m' with m in *; replace n0 with n in *; try apply T.\n    clear m' n0 T Hmn'.\n    destruct (Hmen' Hm) as [exp' [mn' [mn'p [Hexp' [Hmn' [Hmn'p H]]]]]].\n    { apply (Succ_NaturalNumber n n'); assumption. }\n    apply Hexp' in H.\n    destruct H as [mn'' [p' [m' [n0 [Em' [Hmn'p' [Hmn'' [_ [_ [HEm' Hp']]]]]]]]]].\n    assert (T : mn' = mn'' /\\ men' = p').\n    { apply (Enderton3A mn' men' mn'' p' mn'p mn'p Hmn'p Hmn'p'). trivial. }\n    replace mn'' with mn' in *; replace p' with men' in *; try apply T.\n    clear mn'' p' T Hmn'p'. assert (T : m = m' /\\ n' = n0).\n    { apply (Enderton3A m n' m' n0 mn' mn' Hmn' Hmn''). trivial. }\n    replace m' with m in *; replace n0 with n' in *; try apply T.\n    replace Em' with Em in *; try (apply (Expn_Unique m); assumption).\n    clear m' n0 T Hmn'' Em' HEm'.\n    destruct (HEm Hm) as [omga [Mm [o [o' [Homga [HMm' [Ho [Ho' HEm']]]]]]]].\n    destruct HEm' as [omga' [o0 [Homga' [Ho0 [HEm' [_ HEmn']]]]]].\n    replace omga' with omga in *; try (apply (Nats_Unique); assumption).\n    apply (HEmn' n n' men men' mtmen); try apply Homga; try assumption.\n    destruct (Hmentm Hm) as [mult [mp [mpq [Hmult [Hmp [Hmpq H]]]]]].\n    { destruct HEm' as [HEm' [HdomEm [ranEm [HranEm Hsub]]]]. apply Homga, Hsub.\n      apply HranEm. exists n. apply Hp; try assumption.\n      exists omga. split; try assumption. apply Homga; assumption. }\n    apply Hmult in H.\n    destruct H as [mp' [q' [m' [p' [Mm' [Hmpq' [Hmp' [_ [Hp0 [HMm0 Hp1]]]]]]]]]].\n    assert (T : mp = mp' /\\ mtmen = q').\n    { apply (Enderton3A mp mtmen mp' q' mpq mpq Hmpq Hmpq'). trivial. }\n    replace mp' with mp in *; replace q' with mtmen in *; try apply T.\n    clear Hmpq' T mp' q'.\n    assert (T : m = m' /\\ men = p').\n    { apply (Enderton3A m men m' p' mp mp Hmp Hmp'). trivial. }\n    replace m' with m in *; replace p' with men in *; try apply T.\n    clear m' p' Hmp' T. replace Mm with Mm'; try assumption.\n    apply (Multn_Unique m); assumption.\nQed.\n\nDefinition Addition_Associative_w : Prop :=\n  forall m n p np mn r l, NaturalNumber m -> NaturalNumber n -> NaturalNumber p ->\n  Sum_w n p np -> Sum_w m n mn -> Sum_w m np r -> Sum_w mn p l -> r = l.\n\nDefinition Addition_Commutative_w : Prop :=\n  forall m n mn nm, NaturalNumber m -> NaturalNumber n -> Sum_w m n mn ->\n  Sum_w n m nm -> mn = nm.\n\nDefinition Distributive_w : Prop :=\n  forall m n p np mnp mn mp mnmp, NaturalNumber m ->  NaturalNumber n ->\n  NaturalNumber p -> Sum_w n p np -> Prod_w m np mnp -> Prod_w m n mn -> Prod_w m p mp ->\n  Sum_w mn mp mnmp -> mnp = mnmp.\n\nDefinition Multiplication_Associative_w : Prop :=\n  forall m n p np mn r l, NaturalNumber m -> NaturalNumber n -> NaturalNumber p ->\n  Prod_w n p np -> Prod_w m n mn -> Prod_w m np r -> Prod_w mn p l -> r = l.\n\nDefinition Multiplication_Commutative_w : Prop :=\n  forall m n mn nm, NaturalNumber m -> NaturalNumber n -> Prod_w m n mn ->\n  Prod_w n m nm -> mn = nm.\n\nTheorem Enderton4K1 : Addition_Associative_w.\nProof.\n  intros m n p np mn r l Hm Hn Hp. generalize dependent l. generalize dependent r.\n  generalize dependent mn. generalize dependent np. omga.\n  build_set (prod set set)\n    (fun (t : set * set) (c p : set) => forall np mn r l, Sum_w (snd t) p np ->\n      Sum_w (fst t) (snd t) mn -> Sum_w (fst t) np r -> Sum_w mn p l -> r = l)\n    (m, n) omga.\n  rename x into A. rename H into HA. apply HA.\n  replace A with omga; try (apply Homga; assumption).\n  symmetry. apply Induction_Principle_for_Omega; try assumption; try split.\n  - empty. rename x into e. rename H into He.\n    exists e. split; try assumption. apply HA. split.\n    + apply Homga, Zero_NaturalNumber, He.\n    + intros np mn r l Hnp Hmn Hr Hl. simpl in *.\n      destruct (Enderton4I) as [A1 A2]. replace l with mn in *.\n      replace np with n in *. apply (Sum_w_Unique m n r mn); try assumption.\n      * apply (Sum_w_Unique n e n np); try assumption;\n        try apply Zero_NaturalNumber, He. apply (A1 n e); assumption.\n      * destruct Hmn as [add [Pmn [Pmnp [Hadd [HPmn [HPmnp H]]]]]]; try assumption.\n        destruct (Addition_w_BinaryOperation add omga) as [wxw [Hwxw Haddf]];\n        try assumption.\n        destruct Haddf as [Haddf [Hdomadd [ranadd [Hranadd Hsub]]]].\n        apply (Sum_w_Unique mn e mn l); try assumption;\n        try apply Zero_NaturalNumber, He.\n        apply Homga, Hsub. apply Hranadd. exists Pmn, Pmnp. split; try assumption.\n        apply (A1 mn e); try assumption.\n        apply Homga, Hsub, Hranadd. exists Pmn, Pmnp. split; try assumption.\n  - intros a a' Ha' Ha. apply HA in Ha. destruct Ha as [Ha0 Ha1].\n    apply Homga in Ha0. apply HA.\n    split; try (apply Homga, (Succ_NaturalNumber a a'); assumption).\n    intros np mn r l Hnp Hmn Hr Hl. simpl in *.\n    sum_w n a Hn Ha0. rename x into na. rename H into Hna.\n    assert (P : NaturalNumber na).\n    { apply Homga.\n      destruct Hna as [add [Pmn [Pmnp [Hadd [HPmn [HPmnp H]]]]]]; try assumption.\n      destruct (Addition_w_BinaryOperation add omga) as [wxw [Hwxw Haddf]]; try assumption.\n      destruct Haddf as [Haddf [Hdomadd [ranadd [Hranadd Hsub]]]].\n      apply Hsub. apply Hranadd. exists Pmn, Pmnp. split; try assumption. }\n    sum_w m na Hm P. rename x into mna. rename H into Hmna.\n    succ mna. rename x into Smna. rename H into HSmna. transitivity Smna.\n    + succ na. rename x into Sna. rename H into HSna.\n      assert (Q : NaturalNumber Sna).\n      { apply (Succ_NaturalNumber na Sna); try assumption. }\n      sum_w m Sna Hm Q. rename x into mSna. rename H into HmSna.\n      transitivity mSna.\n      * apply (Sum_w_Unique m Sna r mSna); try assumption.\n        replace Sna with np; try assumption.\n        destruct (Enderton4I) as [_ R].\n        apply (R n a a' na np Sna); try assumption.\n      * destruct Enderton4I as [_ R].\n        apply (R m na Sna mna mSna Smna); try assumption.\n    + assert (Q : NaturalNumber mn).\n      { apply Homga.\n        destruct Hmn as [add [Pmn [Pmnp [Hadd [HPmn [HPmnp H]]]]]]; try assumption.\n        destruct (Addition_w_BinaryOperation add omga) as [wxw [Hwxw Haddf]]; try assumption.\n        destruct Haddf as [Haddf [Hdomadd [ranadd [Hranadd Hsub]]]].\n        apply Hsub. apply Hranadd. exists Pmn, Pmnp. split; try assumption. }\n      sum_w mn a Q Ha0. rename x into mna0. rename H into Hmna0.\n      succ mna0. rename x into Smna0. rename H into HSmna0.\n      transitivity Smna0.\n      * apply (Succ_Unique mna Smna Smna0); try assumption.\n        replace mna with mna0; try assumption. symmetry.\n        apply (Ha1 na mn mna mna0); try assumption.\n      * destruct Enderton4I as [_ R]. symmetry.\n        apply (R mn a a' mna0); try assumption.\n  - intros a Ha. apply HA; assumption.\nQed.\n\nLemma A1_Commutative : forall o n, Empty o -> NaturalNumber n ->\n  Sum_w o n n.\nProof.\n  intros o n Ho Hn. generalize dependent n. omga.\n  build_set\n    set\n    (fun (o c n : set) => NaturalNumber n -> Sum_w o n n)\n    o\n    omga.\n  rename x into A. rename H into HA. intros n Hn. apply HA; try assumption.\n  replace A with omga; try apply Homga, Hn; try assumption.\n  symmetry. apply Induction_Principle_for_Omega; try assumption; try split.\n  - exists o. split; try assumption. apply HA.\n    split; try apply Homga, Zero_NaturalNumber, Ho.\n    intros Ho'. destruct Enderton4I as [A1 _].\n    apply A1; try assumption.\n  - intros a a' Ha' Ha. apply HA. apply HA in Ha. destruct Ha as [Ha IH].\n    apply Homga in Ha.\n    split; try (apply Homga, (Succ_NaturalNumber a a'); try assumption).\n    intros Ha'0. sum_w o a (Zero_NaturalNumber o Ho) Ha.\n    rename x into oa. rename H into Hoa.\n    succ oa. rename x into Soa. rename H into HSoa.\n    sum_w o a' (Zero_NaturalNumber o Ho) Ha'0. rename x into oa'. rename H into Hoa'.\n    replace oa' with a' in Hoa'; try assumption. transitivity Soa.\n    + apply (Succ_Unique a a' Soa); try assumption.\n      replace a with oa; try assumption.\n      apply (Sum_w_Unique o a oa a); try apply (Zero_NaturalNumber o); try assumption.\n      apply IH; assumption.\n    + destruct Enderton4I as [_ P]. symmetry.\n      apply (P o a a' oa oa' Soa); try assumption.\n      apply Zero_NaturalNumber. assumption.\n  - intros a Ha. apply HA, Ha.\nQed.\n\nLemma A2_Commutative : forall m n m' mn m'n mn', NaturalNumber m ->\n  NaturalNumber n -> Succ m m' -> Sum_w m n mn -> Sum_w m' n m'n -> Succ mn mn' ->\n  m'n = mn'.\nProof.\n  intros m n m' mn m'n mn' Hm Hn. omga. generalize dependent mn'.\n  generalize dependent m'n. generalize dependent mn. generalize dependent m'.\n  build_set set\n    (fun (m c n : set) => forall m' mn m'n mn',\n      Succ m m' -> Sum_w m n mn -> Sum_w m' n m'n -> Succ mn mn' -> m'n = mn')\n    m omga.\n  rename x into A. rename H into HA. apply HA.\n  replace A with omga; try apply Homga, Hn. symmetry.\n  apply Induction_Principle_for_Omega; try assumption; try split.\n  - empty. exists x. split; try assumption. rename x into o. rename H into Ho.\n    apply HA. split; try (apply Homga; apply Zero_NaturalNumber; assumption).\n    intros m' mn m'n mn' Hm' Hmn Hm'n Hmn'.\n    replace mn with m in *. replace m'n with m' in *.\n    apply (Succ_Unique m m' mn'); try assumption.\n    + apply (Sum_w_Unique m' o m' m'n); try assumption;\n      try (apply Zero_NaturalNumber; assumption);\n      try (apply (Succ_NaturalNumber m m'); assumption).\n      destruct Enderton4I as [A1 _]. apply A1; try assumption;\n      try (apply (Succ_NaturalNumber m m'); assumption).\n    + apply (Sum_w_Unique m o m mn); try assumption;\n      try (apply Zero_NaturalNumber; assumption).\n      destruct Enderton4I as [A1 _]. apply A1; assumption.\n  - intros a a' Ha' Ha. apply HA in Ha. destruct Ha as [Ha IH]. apply Homga in Ha.\n    apply HA. split; try (apply Homga, (Succ_NaturalNumber a a'); assumption).\n    intros m' mn m'n mn' Hm' Hmn Hm'n Hmn'.\n    assert (P : NaturalNumber m').\n    { apply (Succ_NaturalNumber m m'); try assumption. }\n    sum_w m' a P Ha. rename x into m'a. rename H into Hm'a.\n    succ m'a. rename x into Sm'a. rename H into HSm'a.\n    transitivity Sm'a.\n    + destruct Enderton4I as [_ A2].\n      apply (A2 m' a a' m'a m'n Sm'a); try assumption.\n    + sum_w m a Hm Ha. rename x into ma. rename H into Hma.\n      succ ma. rename x into Sma. rename H into HSma.\n      succ Sma. rename x into SSma. rename H into HSSma. transitivity SSma.\n      * apply (Succ_Unique m'a Sm'a SSma); try assumption.\n        replace m'a with Sma; try assumption.\n        symmetry. apply (IH m' ma m'a Sma); try assumption.\n      * apply (Succ_Unique mn SSma mn'); try assumption.\n        replace mn with Sma; try assumption.\n        destruct Enderton4I as [_ A2]. symmetry.\n        apply (A2 m a a' ma); try assumption.\n  - intros a Ha. apply HA, Ha.\nQed.\n\nTheorem Enderton4K2 : Addition_Commutative_w.\nProof.\n  intros m n mn nm Hm Hn. omga. generalize dependent nm. generalize dependent mn.\n  build_set set\n    (fun (m c n : set) => forall mn nm, Sum_w m n mn -> Sum_w n m nm -> mn = nm)\n    m omga.\n  rename x into A. rename H into HA. apply HA.\n  replace A with omga; try apply Homga, Hn. symmetry.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros a Ha; apply HA, Ha).\n  - empty. rename x into o. rename H into Ho. exists o. split; try assumption.\n    apply HA. split; try (apply Homga, Zero_NaturalNumber; assumption).\n    intros mn nm Hmn Hnm. replace mn with m in *. replace nm with m in *.\n    trivial.\n    + apply (Sum_w_Unique o m m nm); try assumption;\n      try (apply Zero_NaturalNumber, Ho).\n      apply (A1_Commutative); assumption.\n    + apply (Sum_w_Unique m o m mn); try assumption;\n      try (apply Zero_NaturalNumber, Ho).\n      destruct Enderton4I as [A1 _].\n      apply A1; assumption.\n  - intros a a' Ha' Ha. apply HA in Ha. destruct Ha as [Ha IH]. apply Homga in Ha.\n    apply HA. split; try (apply Homga, (Succ_NaturalNumber a a'); assumption).\n    intros mn nm Hmn Hnm.\n    sum_w a m Ha Hm. rename x into am. rename H into Ham.\n    sum_w m a Hm Ha. rename x into ma. rename H into Hma.\n    succ am. rename x into Sam. rename H into HSam.\n    succ ma. rename x into Sma. rename H into HSma.\n    transitivity Sma.\n    + destruct Enderton4I as [_ A2].\n      apply (A2 m a a' ma mn Sma); try assumption.\n    + transitivity Sam.\n      * apply (Succ_Unique ma Sma Sam); try assumption.\n        replace ma with am; try assumption.\n        symmetry. apply IH; try assumption.\n      * symmetry. apply (A2_Commutative a m a' am nm Sam); try assumption.\nQed.\n\nLemma Sum_NaturalNumber : forall n m p, NaturalNumber n -> NaturalNumber m ->\n  Sum_w n m p -> NaturalNumber p.\nProof.\n  intros n m p Hn Hm Hp. omga.\n  destruct (Hp Hn Hm) as [add [mn [mnp [Hadd [Hmn [Hmnp H]]]]]].\n  destruct (Addition_w_BinaryOperation add omga) as [wxw [Hwxw Hfadd]]; try assumption.\n  destruct Hfadd as [Hfadd [Hdomadd [ranadd [Hranadd Hsub]]]].\n  apply Homga, Hsub, Hranadd. exists mn, mnp. split; assumption.\nQed.\n\nLemma Prod_NaturalNumber : forall n m p, NaturalNumber n -> NaturalNumber m ->\n  Prod_w n m p -> NaturalNumber p.\nProof.\n  intros n m p Hn Hm Hp. omga.\n  destruct (Hp Hn Hm) as [mult [mn [mnp [Hadd [Hmn [Hmnp H]]]]]].\n  destruct (Multiplication_w_BinaryOperation mult omga) as [wxw [Hwxw Hfmult]]; try assumption.\n  destruct Hfmult as [Hfmult [Hdommult [ranmult [Hranmult Hsub]]]].\n  apply Homga, Hsub, Hranmult. exists mn, mnp. split; assumption.\nQed.\n\nTheorem Enderton4K3 : Distributive_w.\nProof.\n  intros m n p np mnp mn mp mnmp Hm Hn Hp. omga.\n  generalize dependent mnmp. generalize dependent mp. generalize dependent mn.\n  generalize dependent mnp. generalize dependent np.\n  build_set (prod set set)\n    (fun (t : set * set) (c p : set) => forall np mnp mn mp mnmp,\n      Sum_w (snd t) p np -> Prod_w (fst t) np mnp -> Prod_w (fst t) (snd t) mn ->\n      Prod_w (fst t) p mp -> Sum_w mn mp mnmp -> mnp = mnmp)\n    (m, n) omga.\n  rename x into T. rename H into HT. apply HT.\n  replace T with omga; try (apply Homga, Hp). symmetry.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros a Ha; apply HT, Ha).\n  - zero. rename x into o. rename H into Ho. exists o. split; try assumption.\n    apply HT. split; try (apply Homga, Zero_NaturalNumber, Ho).\n    intros np mnp mn mp mnmp Hnp Hmnp Hmn Hmp Hmnmp. simpl in *.\n    replace np with n in *. replace mp with o in *. replace mnmp with mn in *.\n    apply (Prod_w_Unique m n mnp mn); try assumption.\n    + destruct Enderton4I as [A1 A2].\n      apply (Sum_w_Unique mn o mn mnmp); try assumption.\n      * destruct (Hmn Hm Hn) as [mult [Pmn [Pmnp [Hmult [HPmn [HPmnp H]]]]]].\n        destruct (Multiplication_w_BinaryOperation mult omga) as [wxw [Hwxw Hfmult]];\n        try assumption.\n        destruct Hfmult as [Hfmult [Hdommult [ranmult [Hranmult Hsub]]]].\n        apply Homga, Hsub, Hranmult. exists Pmn, Pmnp. split; assumption.\n      * apply Zero_NaturalNumber, Ho.\n      * apply A1; try assumption.\n        destruct (Hmn Hm Hn) as [mult [Pmn [Pmnp [Hmult [HPmn [HPmnp H]]]]]].\n        destruct (Multiplication_w_BinaryOperation mult omga) as [wxw [Hwxw Hfmult]];\n        try assumption.\n        destruct Hfmult as [Hfmult [Hdommult [ranmult [Hranmult Hsub]]]].\n        apply Homga, Hsub, Hranmult. exists Pmn, Pmnp. split; assumption.\n    + apply (Prod_w_Unique m o o mp); try assumption; try (apply Zero_NaturalNumber, Ho).\n      destruct Enderton4J as [M1 M2]. apply M1; assumption.\n    + destruct (Sum_w_Unique n o n np); try assumption; try trivial;\n      try (apply Zero_NaturalNumber, Ho).\n      destruct Enderton4I as [A1 A2]. apply A1; assumption.\n  - clear p Hp. intros p p' Hp' Hp. apply HT in Hp. destruct Hp as [Hp IH].\n    apply HT. apply Homga in Hp.\n    split; try (apply Homga, (Succ_NaturalNumber p p'); assumption).\n    intros np' mnp' mn mp' mnmp' Hnp' Hmnp' Hmn Hmp' Hmnmp'. simpl in *.\n    prod_w m p Hm Hp. rename H into Hmp. rename x into mp.\n    sum_w mn mp (Prod_NaturalNumber m n mn Hm Hn Hmn)\n      (Prod_NaturalNumber m p mp Hm Hp Hmp).\n    rename H into Hmnmp. rename x into mnmp.\n    sum_w m mnmp Hm (Sum_NaturalNumber mn mp mnmp\n      (Prod_NaturalNumber m n mn Hm Hn Hmn)\n      (Prod_NaturalNumber m p mp Hm Hp Hmp) Hmnmp).\n    rename x into mmnmp. rename H into Hmmnmp. transitivity mmnmp.\n    + sum_w n p Hn Hp. rename x into np. rename H into Hnp.\n      prod_w m np Hm (Sum_NaturalNumber n p np Hn Hp Hnp).\n      rename x into mnp. rename H into Hmnp.\n      sum_w m mnp Hm\n        (Prod_NaturalNumber m np mnp Hm (Sum_NaturalNumber n p np Hn Hp Hnp) Hmnp).\n      rename x into mmnp. rename H into Hmmnp. transitivity mmnp.\n      * succ np. rename x into Snp. rename H into HSnp.\n        prod_w m Snp Hm (Succ_NaturalNumber np Snp (Sum_NaturalNumber n p np Hn Hp Hnp) HSnp).\n        rename x into mSnp. rename H into HmSnp. transitivity mSnp.\n        { apply (Prod_w_Unique m np' mnp' mSnp); try assumption;\n          try apply (Sum_NaturalNumber n p' np' Hn (Succ_NaturalNumber p p' Hp Hp') Hnp').\n          replace np' with Snp; try assumption.\n          destruct Enderton4I as [A1 A2]. symmetry.\n          apply (A2 n p p' np); assumption. }\n        { destruct Enderton4J as [M1 M2]. apply (M2 m np mnp Snp); try assumption.\n          apply (Sum_NaturalNumber n p np Hn Hp Hnp). }\n      * apply (Sum_w_Unique m mnp mmnp mmnmp); try assumption;\n        try apply (Prod_NaturalNumber m np mnp Hm \n          (Sum_NaturalNumber n p np Hn Hp Hnp) Hmnp).\n        replace mnp with mnmp; try assumption.\n        symmetry; apply (IH np mnp mn mp mnmp); assumption.\n    + sum_w mnmp m (Sum_NaturalNumber mn mp mnmp\n        (Prod_NaturalNumber m n mn Hm Hn Hmn)\n        (Prod_NaturalNumber m p mp Hm Hp Hmp) Hmnmp) Hm.\n      rename x into mnmpm. rename H into Hmnmpm. transitivity mnmpm.\n      * apply (Sum_w_Unique m mnmp mmnmp mnmpm); try assumption.\n        { apply (Sum_NaturalNumber mn mp); try assumption.\n          - apply (Prod_NaturalNumber m n); try assumption.\n          - apply (Prod_NaturalNumber m p); try assumption. }\n        replace mnmpm with mmnmp; try assumption.\n        apply (Enderton4K2 m mnmp mmnmp mnmpm); try assumption.\n        apply (Sum_NaturalNumber mn mp); try assumption.\n        apply (Prod_NaturalNumber m n); try assumption.\n        apply (Prod_NaturalNumber m p); try assumption.\n      * sum_w mp m (Prod_NaturalNumber m p mp Hm Hp Hmp) Hm.\n        rename x into mpm. rename H into Hmpm.\n        sum_w mn mpm (Prod_NaturalNumber m n mn Hm Hn Hmn)\n          (Sum_NaturalNumber mp m mpm (Prod_NaturalNumber m p mp Hm Hp Hmp) Hm Hmpm).\n        rename x into mnmpm'. rename H into Hmnmpm'. transitivity mnmpm'.\n        { symmetry. apply (Enderton4K1 mn mp m mpm mnmp); try assumption.\n          - apply (Prod_NaturalNumber m n mn Hm Hn Hmn).\n          - apply (Prod_NaturalNumber m p mp Hm Hp Hmp). }\n        { apply (Sum_w_Unique mn mpm mnmpm' mnmp'); try assumption.\n          - apply (Prod_NaturalNumber m n mn Hm Hn Hmn).\n          - apply (Sum_NaturalNumber mp m); try assumption.\n            apply (Prod_NaturalNumber m p); try assumption.\n          - replace mpm with mp'; try assumption.\n            sum_w m mp Hm (Prod_NaturalNumber m p mp Hm Hp Hmp).\n            rename x into mmp. rename H into Hmmp. transitivity mmp.\n            + destruct Enderton4J as [M1 M2]. apply (M2 m p mp p'); try assumption.\n            + apply (Enderton4K2 m mp mmp mpm);  try assumption.\n              apply (Prod_NaturalNumber m p); try assumption. }\nQed.\n\nTheorem Enderton4K4 : Multiplication_Associative_w.\nProof.\n  intros m n p np mn r l Hm Hn Hp. omga.\n  generalize dependent l. generalize dependent r. generalize dependent mn.\n  generalize dependent np. build_set (prod set set)\n    (fun (t : set * set) (c p : set) => forall np mn r l, Prod_w (snd t) p np ->\n      Prod_w (fst t) (snd t) mn -> Prod_w (fst t) np r -> Prod_w mn p l -> r = l)\n    (m,n) omga.\n  rename x into T. rename H into HT. apply HT.\n  replace T with omga; try (apply Homga, Hp). symmetry. clear p Hp.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros a Ha; apply HT, Ha).\n  - zero. rename x into o. rename H into Ho. exists o. split; try assumption.\n    apply HT. split; try (apply Homga, Zero_NaturalNumber, Ho).\n    intros np mn r l Hnp Hmn Hr Hl. simpl in *.\n    destruct (Enderton4J) as [M1 M2].\n    replace np with o in *. replace l with o in *.\n    replace r with o in *. trivial.\n    + apply (Prod_w_Unique m o o r); try assumption;\n      try apply (Zero_NaturalNumber), Ho.\n      apply M1; try assumption.\n    + apply (Prod_w_Unique mn o o l); try apply (Zero_NaturalNumber), Ho;\n      try apply (Prod_NaturalNumber m n); try assumption.\n      apply M1; try assumption.\n      apply (Prod_NaturalNumber m n); try assumption.\n    + apply (Prod_w_Unique n o o np); try assumption;\n      try apply Zero_NaturalNumber; try assumption.\n      apply M1; assumption.\n  - intros p p' Hp' Hp. apply HT in Hp. destruct Hp as [Hp IH].\n    apply HT. apply Homga in Hp.\n    split; try (apply Homga, (Succ_NaturalNumber p p'); assumption).\n    intros np' mn r l Hnp' Hmn Hr Hl. simpl in *.\n    prod_w n p Hn Hp. rename x into np. rename H into Hnp.\n    prod_w m np Hm (Prod_NaturalNumber n p np Hn Hp Hnp).\n    rename x into mnp. rename H into Hmnp.\n    sum_w mn mnp (Prod_NaturalNumber m n mn Hm Hn Hmn)\n      (Prod_NaturalNumber m np mnp Hm (Prod_NaturalNumber n p np Hn Hp Hnp) Hmnp).\n    rename x into mnmnp. rename H into Hmnmnp. transitivity mnmnp.\n    + sum_w n np Hn (Prod_NaturalNumber n p np Hn Hp Hnp).\n      rename x into nnp. rename H into Hnnp.\n      prod_w m nnp Hm (Sum_NaturalNumber n np nnp Hn\n        (Prod_NaturalNumber n p np Hn Hp Hnp) Hnnp).\n      rename x into mnnp. rename H into Hmnnp. transitivity mnnp.\n      * destruct Enderton4J as [M1 M2].\n        apply (Prod_w_Unique m np' r mnnp); try assumption.\n        { apply (Prod_NaturalNumber n p'); try assumption.\n          apply (Succ_NaturalNumber p p'); try assumption. }\n        replace np' with nnp; try assumption.\n        symmetry. apply (M2 n p np p' np'); try assumption.\n      * apply (Enderton4K3 m n np nnp mnnp mn mnp mnmnp); try assumption.\n        apply (Prod_NaturalNumber n p); try assumption.\n    + prod_w mn p (Prod_NaturalNumber m n mn Hm Hn Hmn) Hp.\n      rename x into mnp0. rename H into Hmnp0.\n      sum_w mn mnp0 (Prod_NaturalNumber m n mn Hm Hn Hmn)\n        (Prod_NaturalNumber mn p mnp0 (Prod_NaturalNumber m n mn Hm Hn Hmn) Hp Hmnp0).\n      rename x into mnmnp0. rename H into Hmnmnp0. transitivity mnmnp0.\n      * apply (Sum_w_Unique mn mnp mnmnp mnmnp0); try assumption.\n        { apply (Prod_NaturalNumber m n); try assumption. }\n        { apply (Prod_NaturalNumber m np); try assumption.\n          apply (Prod_NaturalNumber n p); try assumption. }\n        replace mnp with mnp0; try assumption.\n        symmetry. apply (IH np mn mnp mnp0); try assumption.\n      * destruct Enderton4J as [M1 M2]. symmetry.\n        apply (M2 mn p mnp0 p'); try assumption.\n        apply (Prod_NaturalNumber m n); assumption.\nQed.\n\nLemma M1_Commutative : forall o m, Empty o -> NaturalNumber m ->\n  Prod_w o m o.\nProof.\n  intros o m Ho Hm. omga. build_set set\n    (fun (o c m : set) => Prod_w o m o) o omga.\n  rename x into T. rename H into HT. apply HT.\n  replace T with omga; try (apply Homga, Hm). clear m Hm. symmetry.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros a Ha; apply HT, Ha).\n  - exists o. split; try assumption. apply HT.\n    split; try (apply Homga, Zero_NaturalNumber, Ho).\n    destruct Enderton4J as [M1 _]. apply M1; try assumption.\n    apply Zero_NaturalNumber. assumption.\n  - intros m m' Hm' Hm. apply HT in Hm. destruct Hm as [Hm IH].\n    apply HT. apply Homga in Hm.\n    split; try (apply Homga, (Succ_NaturalNumber m m'); assumption).\n    prod_w o m' (Zero_NaturalNumber o Ho) (Succ_NaturalNumber m m' Hm Hm').\n    rename x into om'. rename H into Hom'.\n    replace om' with o in Hom'; try assumption.\n    destruct Enderton4J as [_ M2]. symmetry.\n    apply (M2 o m o m'); try assumption; try apply Zero_NaturalNumber, Ho.\n    destruct Enderton4I as [A1 _].\n    apply A1; try apply Zero_NaturalNumber; assumption.\nQed.\n\nLemma M2_Commutative : forall m n mn m' m'n mnn,\n  NaturalNumber m -> NaturalNumber n -> Prod_w m n mn -> Succ m m' ->\n  Prod_w m' n m'n -> Sum_w mn n mnn -> m'n = mnn.\nProof.\n  intros m n mn m' m'n mnn Hm Hn. omga.\n  generalize dependent mnn. generalize dependent m'n.\n  generalize dependent m'. generalize dependent mn.\n  build_set set\n    (fun (m c n : set) => forall mn m' m'n mnn, Prod_w m n mn -> Succ m m' ->\n      Prod_w m' n m'n -> Sum_w mn n mnn -> m'n = mnn)\n    m omga.\n  rename x into T. rename H into HT. apply HT.\n  replace T with omga; try (apply Homga, Hn). symmetry. clear n Hn.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros a Ha; apply HT, Ha).\n  - zero. rename x into o. rename H into Ho. exists o. split; try assumption.\n    apply HT. split; try (apply Homga, Zero_NaturalNumber, Ho).\n    intros mn m' m'n mnn Hmn Hm' Hm'n Hmnn.\n    destruct Enderton4J as [M1 _].\n    replace mn with o in *. replace mnn with o in *.\n    replace m'n with o in *. trivial.\n    + apply (Prod_w_Unique m' o o m'n); try assumption;\n      try (apply Zero_NaturalNumber, Ho);\n      try (apply (Succ_NaturalNumber m m' Hm Hm')).\n      apply M1; try assumption.\n      apply (Succ_NaturalNumber m); try assumption.\n    + apply (Sum_w_Unique o o o mnn); try apply Zero_NaturalNumber; try assumption.\n      destruct Enderton4I as [A1 _].\n      apply A1; try assumption. apply Zero_NaturalNumber, Ho.\n    + apply (Prod_w_Unique m o o mn); try assumption;\n      try apply Zero_NaturalNumber, Ho.\n      apply M1; try assumption.\n  - intros n n' Hn' Hn. apply HT in Hn. destruct Hn as [Hn IH].\n    apply HT. apply Homga in Hn.\n    split; try (apply Homga, (Succ_NaturalNumber n n' Hn Hn')).\n    intros mn' m' m'n' mn'n' Hmn' Hm' Hm'n' Hmn'n'.\n    prod_w m n Hm Hn. rename x into mn. rename H into Hmn.\n    sum_w m n Hm Hn. rename x into mpn. rename H into Hmpn.\n    succ mpn. rename x into Smpn. rename H into HSmpn.\n    assert (T0 : NaturalNumber mn).\n    { apply (Prod_NaturalNumber m n); try assumption. }\n    assert (T1 : NaturalNumber Smpn).\n    { apply (Succ_NaturalNumber mpn); try assumption.\n      apply (Sum_NaturalNumber m n); try assumption. }\n    sum_w mn Smpn T0 T1. rename x into mnSmpn. rename H into HmnSmpn.\n    transitivity mnSmpn.\n    + sum_w mn n T0 Hn. rename x into mnn. rename H into Hmnn.\n      sum_w mnn m' (Sum_NaturalNumber mn n mnn T0 Hn Hmnn)\n        (Succ_NaturalNumber m m' Hm Hm').\n      rename x into mnnm. rename H into Hmnnm. transitivity mnnm.\n      * sum_w m' mnn (Succ_NaturalNumber m m' Hm Hm')\n          (Sum_NaturalNumber mn n mnn T0 Hn Hmnn).\n        rename x into mmnn. rename H into Hmmnn. transitivity mmnn.\n        { prod_w m' n (Succ_NaturalNumber m m' Hm Hm') Hn.\n          rename x into m'n. rename H into Hm'n.\n          sum_w m' m'n (Succ_NaturalNumber m m' Hm Hm')\n            (Prod_NaturalNumber m' n m'n (Succ_NaturalNumber m m' Hm Hm') Hn Hm'n).\n          rename x into m'm'n. rename H into Hm'm'n. transitivity m'm'n.\n          - destruct Enderton4J as [_ M2]. apply (M2 m' n m'n n'); try assumption.\n            apply (Succ_NaturalNumber m m'); try assumption.\n          - apply (Sum_w_Unique m' m'n m'm'n mmnn); try assumption;\n            try apply (Succ_NaturalNumber m m' Hm Hm').\n            + apply (Prod_NaturalNumber m' n); try assumption.\n              apply (Succ_NaturalNumber m m'); try assumption.\n            + replace m'n with mnn; try assumption.\n              symmetry. apply (IH mn m' m'n mnn); try assumption. }\n        { apply (Enderton4K2 m' mnn mmnn mnnm); try assumption.\n          apply (Succ_NaturalNumber m m'); try assumption.\n          apply (Sum_NaturalNumber mn n); try assumption. }\n      * sum_w n m Hn Hm. rename x into npm. rename H into Hnpm.\n        sum_w mn npm T0 (Sum_NaturalNumber n m npm Hn Hm Hnpm).\n        rename x into mnnpm. rename H into Hmnnpm.\n        succ mnnpm. rename x into Smnnpm. rename H into HSmnnpm.\n        transitivity Smnnpm.\n        { sum_w mnn m (Sum_NaturalNumber mn n mnn T0 Hn Hmnn) Hm.\n          rename x into mnnm'. rename H into Hmnnm'.\n          succ mnnm'. rename x into Smnnm. rename H into HSmnnm.\n          transitivity Smnnm.\n          - destruct Enderton4I as [A1 A2].\n            apply (A2 mnn m m' mnnm'); try assumption.\n            apply (Sum_NaturalNumber mn n); try assumption.\n          - apply (Succ_Unique mnnm' Smnnm Smnnpm); try assumption.\n            replace mnnm' with mnnpm; try assumption.\n            apply (Enderton4K1 mn n m npm mnn); try assumption. }\n        { sum_w mn mpn T0 (Sum_NaturalNumber m n mpn Hm Hn Hmpn).\n          rename x into mnmpn. rename H into Hmnmpn.\n          succ mnmpn. rename x into Smnmpn. rename H into HSmnmpn.\n          transitivity Smnmpn.\n          - apply (Succ_Unique mnnpm); try assumption.\n            replace mnnpm with mnmpn; try assumption.\n            apply (Sum_w_Unique mn mpn); try assumption;\n            try apply (Sum_NaturalNumber m n); try assumption.\n            replace mpn with npm; try assumption.\n            apply (Enderton4K2 n m npm mpn); assumption.\n          - destruct Enderton4I as [A1 A2]. symmetry.\n            apply (A2 mn mpn Smpn mnmpn); try assumption.\n            apply (Sum_NaturalNumber m n); assumption. }\n    + sum_w mn m T0 Hm. rename x into mnm. rename H into Hmnm.\n      sum_w mnm n' (Sum_NaturalNumber mn m mnm T0 Hm Hmnm)\n        (Succ_NaturalNumber n n' Hn Hn').\n      rename x into mnmn'. rename H into Hmnmn'. transitivity mnmn'.\n      * sum_w m n' Hm (Succ_NaturalNumber n n' Hn Hn').\n        rename x into mpn'. rename H into Hmpn'.\n        sum_w mn mpn' T0 (Sum_NaturalNumber m n' mpn' Hm\n          (Succ_NaturalNumber n n' Hn Hn') Hmpn').\n        rename x into mnmpn'. rename H into Hmnmpn'. transitivity mnmpn'.\n        { apply (Sum_w_Unique mn Smpn); try assumption.\n          replace Smpn with mpn'; try assumption.\n          destruct Enderton4I as [A1 A2]. apply (A2 m n n' mpn); try assumption. }\n        { apply (Enderton4K1 mn m n' mpn' mnm); try assumption.\n          apply (Succ_NaturalNumber n n'); assumption. }\n      * apply (Sum_w_Unique mnm n'); try assumption;\n        try apply (Sum_NaturalNumber mn m mnm T0 Hm Hmnm);\n        try apply (Succ_NaturalNumber n n' Hn Hn').\n        replace mnm with mn'; try assumption.\n        destruct Enderton4J as [M1 M2]. apply (M2 m n mn n'); try assumption.\n        sum_w m mn Hm T0. rename x into mmn. rename H into Hmmn.\n        replace mnm with mmn; try assumption.\n        apply (Enderton4K2 m mn); try assumption.\nQed.\n\nTheorem Enderton4K5 : Multiplication_Commutative_w.\nProof.\n  intros m n mn nm Hm Hn. omga. generalize dependent nm. generalize dependent mn.\n  build_set set\n    (fun (m c n : set) => forall mn nm, Prod_w m n mn -> Prod_w n m nm -> mn = nm)\n    m omga.\n  rename x into T. rename H into HT. apply HT.\n  replace T with omga; try (apply Homga, Hn). symmetry. clear n Hn.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros a Ha; apply HT, Ha).\n  - zero. rename x into o. rename H into Ho. exists o. split; try assumption.\n    apply HT. split; try (apply Homga, Zero_NaturalNumber, Ho).\n    intros mn nm Hmn Hnm. replace mn with o in *. replace nm with o in *.\n    trivial.\n    + apply (Prod_w_Unique o m o nm); try assumption;\n      try (apply Zero_NaturalNumber, Ho).\n      apply (M1_Commutative); try assumption.\n    + apply (Prod_w_Unique m o o mn); try assumption;\n      try (apply Zero_NaturalNumber, Ho).\n      destruct Enderton4J as [M1 M2]. apply M1; assumption.\n  - intros n n' Hn' Hn. apply HT in Hn. destruct Hn as [Hn IH].\n    apply HT. apply Homga in Hn.\n    split; try (apply Homga, (Succ_NaturalNumber n n' Hn Hn')).\n    intros mn' n'm Hmn' Hn'm.\n    prod_w n m Hn Hm. rename x into nm. rename H into Hnm.\n    prod_w m n Hm Hn. rename x into mn. rename H into Hmn.\n    sum_w m nm Hm (Prod_NaturalNumber n m nm Hn Hm Hnm).\n    rename x into mnm. rename H into Hmnm. transitivity mnm.\n    + sum_w m mn Hm (Prod_NaturalNumber m n mn Hm Hn Hmn).\n      rename x into mmn. rename H into Hmmn. transitivity mmn.\n      * destruct Enderton4J as [M1 M2]. apply (M2 m n mn n'); try assumption.\n      * apply (Sum_w_Unique m mn); try assumption;\n        try apply (Prod_NaturalNumber m n mn Hm Hn Hmn).\n        replace mn with nm; try assumption. symmetry.\n        apply (IH mn nm Hmn Hnm).\n    + sum_w nm m (Prod_NaturalNumber n m nm Hn Hm Hnm) Hm.\n      rename x into nmm. rename H into Hnmm. transitivity nmm.\n      * apply (Enderton4K2 m nm); try assumption;\n        try apply (Prod_NaturalNumber n m nm Hn Hm Hnm).\n      * symmetry. apply (M2_Commutative n m nm n'); try assumption.\nQed.\n\nLemma SumZero_implies_BothZero : forall m n o, NaturalNumber m ->\n  NaturalNumber n -> Empty o -> Sum_w m n o -> Empty m /\\ Empty n.\nProof.\n  intros m n o Hm Hn Ho. omga. generalize dependent n. build_set set\n    (fun (o c m : set) => forall n, NaturalNumber n -> Sum_w m n o ->\n      Empty m /\\ Empty n)\n    o omga.\n  rename x into T. rename H into HT. apply HT.\n  replace T with omga; try (apply Homga, Hm). symmetry. clear m Hm.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros t Ht; apply HT, Ht).\n  - exists o. split; try assumption. apply HT.\n    split; try (apply Homga, Zero_NaturalNumber, Ho).\n    intros n Hn H. split; try assumption. replace n with o; try assumption.\n    apply (Sum_w_Unique o n o n); try assumption;\n    try (apply Zero_NaturalNumber, Ho).\n    apply A1_Commutative; try assumption.\n  - intros m m' Hm' Hm. apply HT in Hm. destruct Hm as [Hm IH].\n    apply HT. apply Homga in Hm.\n    split; try (apply Homga, (Succ_NaturalNumber m m' Hm Hm')).\n    intros n Hn Hm'n. succ n. rename x into n'. rename H into Hn'.\n    sum_w m n Hm Hn. rename x into mn. rename H into Hmn.\n    sum_w m n' Hm (Succ_NaturalNumber n n' Hn Hn').\n    rename x into mn'. rename H into Hmn'.\n    sum_w m' n (Succ_NaturalNumber m m' Hm Hm') Hn.\n    rename x into m'n. rename H into Hm'n0.\n    assert (P : Sum_w m n' o).\n    { replace o with mn'; try assumption. transitivity m'n.\n      - succ mn. rename x into Smn. transitivity Smn.\n        + destruct Enderton4I as [A1 A2]. apply (A2 m n n' mn); assumption.\n        + symmetry. apply (A2_Commutative m n m' mn); try assumption.\n      - apply (Sum_w_Unique m' n m'n o); try assumption.\n        apply (Succ_NaturalNumber m m'); assumption. }\n    destruct (IH n' (Succ_NaturalNumber n n' Hn Hn') P) as [IH1 IH2].\n    destruct (IH2 n). destruct Hn' as [Sn [HSn Hn']]. apply Hn'. right.\n    apply HSn. trivial.\nQed.\n\nTheorem Exercise4_13 : forall m n o, NaturalNumber m -> NaturalNumber n ->\n  Empty o -> Prod_w m n o -> m = o \\/ n = o.\nProof.\n  intros m n o Hm Hn Ho. generalize dependent n. omga.\n  build_set set\n    (fun (o c m : set) => forall n, NaturalNumber n -> Prod_w m n o -> m = o \\/ n = o)\n    o omga.\n  rename x into T. rename H into HT. apply HT.\n  replace T with omga; try (apply Homga, Hm). symmetry. clear Hm m.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros t Ht; apply HT, Ht).\n  - exists o. split; try assumption. apply HT.\n    split; try (apply Homga, Zero_NaturalNumber, Ho).\n    intros n Hn Hon. left. trivial.\n  - intros m m' Hm' Hm. apply HT in Hm. destruct Hm as [Hm IH].\n    apply HT. apply Homga in Hm.\n    split; try (apply Homga, (Succ_NaturalNumber m m' Hm Hm')).\n    intros n Hn Hm'n. right.\n    prod_w m n Hm Hn. rename x into mn. rename H into Hmn.\n    apply (Empty_Unique); try assumption.\n    destruct (SumZero_implies_BothZero mn n o) as [_ H];\n    try apply H; try assumption; try apply (Prod_NaturalNumber m n mn Hm Hn Hmn).\n    sum_w mn n (Prod_NaturalNumber m n mn Hm Hn Hmn) Hn.\n    rename x into mnn. rename H into Hmnn. replace o with mnn; try assumption.\n    prod_w m' n (Succ_NaturalNumber m m' Hm Hm') Hn.\n    rename x into m'n. rename H into Hm'n0. transitivity m'n.\n    + symmetry. apply (M2_Commutative m n mn m'); try assumption.\n    + apply (Prod_w_Unique m' n m'n o); try assumption.\n      apply (Succ_NaturalNumber m m' Hm Hm').\nQed.\n\nDefinition Even_w (n : set) : Prop :=\n  exists p o o' o'', NaturalNumber p /\\ Empty o /\\ Succ o o' /\\ Succ o' o'' /\\\n  Prod_w o'' p n.\n\nDefinition Odd_w (n : set) : Prop :=\n  exists p o o' o'' tp, NaturalNumber p /\\ Empty o /\\ Succ o o' /\\ Succ o' o'' /\\\n  Prod_w o'' p tp /\\ Succ tp n.\n\nTheorem Exercise4_14 : forall n, NaturalNumber n -> Odd_w n \\/ Even_w n.\nProof.\n  intros n Hn. omga. destruct Enderton4I as [A1 A2].\n  build_set set (fun (t c n : set) => Odd_w n \\/ Even_w n) omga omga.\n  rename x into T. rename H into HT. apply HT.\n  replace T with omga; try (apply Homga, Hn). clear n Hn. symmetry.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros t Ht; apply HT, Ht).\n  - zero. exists x. split; try assumption. rename x into o. rename H into Ho.\n    apply HT. split; try apply Homga, Zero_NaturalNumber, Ho.\n    right. succ o. rename x into o'. rename H into Ho'.\n    succ o'. rename x into o''. rename H into Ho''.\n    exists o, o, o', o''; repeat (split; try assumption);\n    try apply Zero_NaturalNumber, Ho.\n    destruct Enderton4J as [M1 _]. apply M1; try assumption.\n    apply (Succ_NaturalNumber o' o''); try assumption.\n    apply (Succ_NaturalNumber o o'); try assumption.\n    apply Zero_NaturalNumber, Ho.\n  - intros n n' Hn' Hn. apply HT in Hn. destruct Hn as [Hn IH].\n    apply HT. apply Homga in Hn.\n    split; try apply Homga, (Succ_NaturalNumber n n' Hn Hn').\n    destruct IH as [IH | IH].\n    + right. destruct IH as [p [o [o' [o'' [tp [Hp [Ho [Ho' [Ho'' [Htp IH]]]]]]]]]].\n      succ p. rename x into p'. rename H into Hp'.\n      exists p', o, o', o''. repeat (split; try assumption);\n      try apply (Succ_NaturalNumber p p' Hp Hp').\n      assert (T0 : NaturalNumber o'').\n      { apply (Succ_NaturalNumber o' o''); try assumption.\n        apply (Succ_NaturalNumber o o'); try assumption.\n        apply Zero_NaturalNumber, Ho. }\n      prod_w o'' p' T0 (Succ_NaturalNumber p p' Hp Hp').\n      rename x into tp'. rename H into Htp'.\n      replace n' with tp'; try assumption.\n      sum_w o'' tp T0 (Prod_NaturalNumber o'' p tp T0 Hp Htp).\n      rename x into ttp. rename H into Http. transitivity ttp.\n      * destruct Enderton4J as [M1 M2]. apply (M2 o'' p tp p'); try assumption.\n      * sum_w tp o'' (Prod_NaturalNumber o'' p tp T0 Hp Htp) T0.\n        rename H into Htpt. rename x into tpt.\n        replace ttp with tpt.\n        sum_w tp o' (Prod_NaturalNumber o'' p tp T0 Hp Htp)\n          (Succ_NaturalNumber o o' (Zero_NaturalNumber o Ho) Ho').\n        rename H into Htpo'. rename x into tpo'.\n        succ tpo'. rename x into Stpo'. rename H into HStpo'.\n        replace tpt with Stpo'. apply (Succ_Unique tpo'); try assumption.\n        replace tpo' with n; try assumption.\n        apply (Succ_Unique tp); try assumption.\n        succ tp. rename x into Stp. rename H into HStp.\n        replace tpo' with Stp; try assumption.\n        sum_w tp o (Prod_NaturalNumber o'' p tp T0 Hp Htp) (Zero_NaturalNumber o Ho).\n        rename x into tpo. rename H into Htpo. symmetry.\n        apply (A2 tp o o' tpo); try assumption;\n        try apply Zero_NaturalNumber, Ho;\n        try apply (Prod_NaturalNumber o'' p); try assumption.\n        replace tpo with tp; try assumption.\n        apply (Sum_w_Unique tp o tp tpo); try assumption;\n        try apply Zero_NaturalNumber, Ho;\n        try apply (Prod_NaturalNumber o'' p); try assumption.\n        apply A1; try assumption;\n        try apply (Prod_NaturalNumber o'' p); try assumption.\n        symmetry. apply (A2 tp o' o'' tpo'); try assumption;\n        try apply (Succ_NaturalNumber o o'); try assumption;\n        try apply Zero_NaturalNumber, Ho;\n        try apply (Prod_NaturalNumber o'' p); try assumption.\n        apply (Enderton4K2 tp o''); try assumption;\n        try apply (Prod_NaturalNumber o'' p); assumption.\n    + left. destruct IH as [p [o [o' [o'' [Hp [Ho [Ho' [Ho'' IH]]]]]]]].\n      exists p, o, o', o'', n; repeat (split; try assumption).\nQed.\n\nLemma Pred_Unique : forall m n m' n', NaturalNumber m -> NaturalNumber n ->\n  Succ m m' -> Succ n n' -> m' = n' -> m = n.\nProof.\n  intros m n m' n' Hm Hn Hm' Hn' H.\n  union m'. rename x into Um'. rename H0 into HUm'.\n  union n'. rename x into Un'. rename H0 into HUn'.\n  apply (Union_Unique m').\n  - replace m with Um'; try assumption.\n    apply (Enderton4E m m'); try assumption.\n    apply (Enderton4F); assumption.\n  - replace m' with n'; try assumption.\n    replace n with Un'; try assumption.\n    apply (Enderton4E n n'); try assumption.\n    apply Enderton4F; assumption.\nQed.\n\nTheorem Exercise4_14' : forall n, NaturalNumber n -> ~ (Odd_w n /\\ Even_w n).\nProof.\n  intros n Hn. omga. destruct Enderton4J as [M1 M2]. destruct Enderton4I as [A1 A2].\n  build_set set (fun (t c n : set) => ~ (Odd_w n /\\ Even_w n)) omga omga.\n  rename x into T. rename H into HT. apply HT.\n  replace T with omga; try apply Homga, Hn. symmetry. clear Hn n.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros t Ht; apply HT, Ht).\n  - empty. rename x into o. rename H into Ho. exists o. split; try assumption.\n    apply HT. split; try apply Homga, Zero_NaturalNumber, Ho.\n    intros C. destruct C as [C1 C2].\n    destruct C1 as [p [o0 [o' [o'' [tp [Hp [Ho0 [Ho' [Ho'' [Htp H]]]]]]]]]].\n    replace o0 with o in *; try apply (Empty_Unique); try assumption.\n    clear o0 Ho0. apply (Ho tp). destruct H as [Stp [HStp H]].\n    apply H. right. apply HStp. trivial.\n  - intros n n' Hn' Hn. apply HT in Hn. destruct Hn as [Hn IH].\n    apply HT. apply Homga in Hn.\n    split; try apply Homga, (Succ_NaturalNumber n n' Hn Hn').\n    intros [C1 C2]. apply IH. split.\n    + destruct C2 as [p' [o [o' [o'' [Hp' [Ho [Ho' [Ho'' C2]]]]]]]].\n      assert (T0 : NaturalNumber o'').\n      { try apply (Succ_NaturalNumber o' o''\n          (Succ_NaturalNumber o o' (Zero_NaturalNumber o Ho) Ho') Ho''). }\n      destruct (Enderton4C p' Hp') as [p [Hp Hp'0]].\n      { intros C. apply (Ho n). replace o with n'.\n        - destruct Hn' as [Sn [HSn Hn']]. apply Hn'. right.\n          apply HSn. trivial.\n        - apply (Prod_w_Unique o'' p' n' o); try assumption.\n          replace p' with o; try apply M1; try assumption.\n          apply (Empty_Unique o p'); assumption. }\n      prod_w o'' p T0 Hp. rename x into tp. rename H into Htp.\n      assert (T1 : NaturalNumber tp).\n      { apply (Prod_NaturalNumber o'' p); try assumption. }\n      exists p, o, o', o'', tp. repeat (split; try assumption).\n      succ tp. rename x into Stp. rename H into HStp.\n      replace n with Stp; try assumption.\n      apply (Pred_Unique Stp n n' n'); try assumption; try trivial.\n      { apply (Succ_NaturalNumber tp); try assumption. }\n      succ Stp. rename x into SStp. rename H into HSStp.\n      replace n' with SStp; try assumption.\n      sum_w tp o'' T1 T0. rename x into tpt. rename H into Htpt.\n      transitivity tpt.\n      * sum_w tp o T1 (Zero_NaturalNumber o Ho).\n        rename x into tpo. rename H into Htpo.\n        succ tpo. rename H into HStpo. rename x into Stpo.\n        succ Stpo. rename H into HSStpo. rename x into SStpo.\n        transitivity SStpo.\n        { apply (Succ_Unique Stp); try assumption.\n          replace Stp with Stpo; try assumption.\n          apply (Succ_Unique tp); try assumption.\n          replace tp with tpo; try assumption.\n          apply (Sum_w_Unique tp o tpo tp); try assumption;\n          try apply Zero_NaturalNumber, Ho.\n          apply A1; assumption. }\n        { sum_w tp o' T1 (Succ_NaturalNumber o o' (Zero_NaturalNumber o Ho) Ho').\n          rename x into tpo'. rename H into Htpo'.\n          succ tpo'. rename x into Stpo'. rename H into HStpo'.\n          transitivity Stpo'.\n          - apply (Succ_Unique Stpo); try assumption.\n            replace Stpo with tpo'; try assumption.\n            apply (A2 tp o o' tpo); try assumption.\n            apply Zero_NaturalNumber, Ho.\n          - symmetry. apply (A2 tp o' o'' tpo'); try assumption.\n            apply (Succ_NaturalNumber o o'); try assumption.\n            apply Zero_NaturalNumber, Ho. }\n      * sum_w o'' tp T0 T1. rename x into ttp. rename H into Http.\n        transitivity ttp.\n        { apply (Enderton4K2 tp o''); try assumption. }\n        { symmetry. apply (M2 o'' p tp p'); try assumption. }\n    + destruct C1 as [p [o [o' [o'' [tp [Hp [Ho [Ho' [Ho'' [Htp C1]]]]]]]]]].\n      exists p, o, o', o''. repeat (split; try assumption).\n      replace n with tp; try assumption.\n      apply (Pred_Unique tp n n' n'); try assumption; try trivial.\n      apply (Prod_NaturalNumber o'' p); try assumption.\n      apply (Succ_NaturalNumber o' o''); try assumption.\n      apply (Succ_NaturalNumber o o'); try assumption.\n      apply Zero_NaturalNumber, Ho.\nQed.\n\n(** Exercise 4-15 : Prove part 1 of 4K. *)\n\n(** Exercise 4-16 : Prove part 5 of 4K. *)\n\nLemma Pow_NaturalNumber : forall m n mn, NaturalNumber m -> NaturalNumber n ->\n  Pow_w m n mn -> NaturalNumber mn.\nProof.\n  intros m n mn Hm Hn Hmn. omga.\n  destruct (Hmn Hm Hn) as [exp [Pmn [Pmnmn [Hexp [HPmn [HPmnmn H]]]]]].\n  destruct (Exponentiation_w_BinaryOperation exp omga) as [wxw [Hwxw Hfexp]];\n  try assumption.\n  destruct Hfexp as [Hfexp [Hdomexp [ranexp [Hranexp Hsub]]]].\n  apply Homga, Hsub, Hranexp. exists Pmn, Pmnmn. split; assumption.\nQed.\n\nTheorem Exercise4_17 : forall m n p np mnp mn mp mnmp,\n  NaturalNumber m -> NaturalNumber n -> NaturalNumber p -> Sum_w n p np ->\n  Pow_w m np mnp -> Pow_w m n mn -> Pow_w m p mp -> Prod_w mn mp mnmp ->\n  mnp = mnmp.\nProof.\n  intros m n p np mnp mn mp mnmp Hm Hn Hp. omga. destruct Enderton4J as [M1 M2].\n  destruct Enderton4I as [A1 A2]. destruct Enderton4J' as [E1 E2].\n  generalize dependent mnmp. generalize dependent mp. generalize dependent mn.\n  generalize dependent mnp. generalize dependent np.\n  build_set (prod set set)\n    (fun (t : set * set) (c p : set) => forall np mnp mn mp mnmp,\n      Sum_w (snd t) p np -> Pow_w (fst t) np mnp -> Pow_w (fst t) (snd t) mn ->\n      Pow_w (fst t) p mp -> Prod_w mn mp mnmp -> mnp = mnmp) (m,n) omga.\n  rename x into T. rename H into HT. apply HT.\n  replace T with omga; try apply Homga, Hp. clear p Hp. symmetry.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros t Ht; apply HT, Ht).\n  - empty. rename x into o. rename H into Ho. exists o. split; try assumption.\n    apply HT. split; try apply Homga, Zero_NaturalNumber, Ho.\n    intros np mnp mn mp mnmp Hnp Hmnp Hmn Hmp Hmnmp. simpl in *.\n    succ o. rename x into o'; rename H into Ho'.\n    replace np with n in *. replace mnp with mn in *.\n    replace mp with o' in *. replace mnmp with mn in *. trivial.\n    + sum_w mn o (Pow_NaturalNumber m n mn Hm Hn Hmn) (Zero_NaturalNumber o Ho).\n      rename x into mno. rename H into Hmno. transitivity mno.\n      * apply (Sum_w_Unique mn o mn mno); try assumption;\n        try apply (Pow_NaturalNumber m n mn Hm Hn Hmn);\n        try apply Zero_NaturalNumber, Ho.\n        apply A1; try assumption.\n        apply (Pow_NaturalNumber m n mn Hm Hn Hmn).\n      * prod_w mn o (Pow_NaturalNumber m n mn Hm Hn Hmn) (Zero_NaturalNumber o Ho).\n        rename x into mnto. rename H into Hmnto. replace o with mnto in Hmno.\n        { symmetry. apply (M2 mn o mnto o'); try assumption;\n          try apply Zero_NaturalNumber, Ho.\n          apply (Pow_NaturalNumber m n mn Hm Hn Hmn). }\n        { apply (Prod_w_Unique mn o mnto o); try assumption;\n          try apply Zero_NaturalNumber, Ho;\n          try apply (Pow_NaturalNumber m n mn Hm Hn Hmn).\n          apply M1; try assumption.\n          apply (Pow_NaturalNumber m n mn Hm Hn Hmn). }\n    + apply (Pow_w_Unique m o o' mp); try assumption;\n      try apply Zero_NaturalNumber, Ho. apply E1; try assumption.\n    + apply (Pow_w_Unique m n mn mnp); try assumption.\n    + apply (Sum_w_Unique n o n np); try assumption;\n      try apply Zero_NaturalNumber, Ho.\n      apply A1; try assumption.\n  - intros p p' Hp' Hp. apply HT in Hp. destruct Hp as [Hp IH].\n    apply HT. apply Homga in Hp.\n    split; try apply Homga, (Succ_NaturalNumber p p'); try assumption.\n    intros np' mnp' mn mp' mnmp' Hnp' Hmnp' Hmn Hmp' Hmnmp'. simpl in *.\n    pow_w m p Hm Hp. rename x into mp. rename H into Hmp.\n    prod_w mp mn (Pow_NaturalNumber m p mp Hm Hp Hmp)\n      (Pow_NaturalNumber m n mn Hm Hn Hmn).\n    rename x into mpmn. rename H into Hmpmn.\n    prod_w m mpmn Hm (Prod_NaturalNumber mp mn mpmn\n      (Pow_NaturalNumber m p mp Hm Hp Hmp) (Pow_NaturalNumber m n mn Hm Hn Hmn) Hmpmn).\n    rename x into mmpmn. rename H into Hmmpmn. transitivity mmpmn.\n    + sum_w n p Hn Hp. rename x into np. rename H into Hnp.\n      pow_w m np Hm (Sum_NaturalNumber n p np Hn Hp Hnp).\n      rename x into mnp. rename H into Hmnp.\n      prod_w m mnp Hm (Pow_NaturalNumber m np mnp Hm\n        (Sum_NaturalNumber n p np Hn Hp Hnp) Hmnp).\n      rename x into mmnp. rename H into Hmmnp. transitivity mmnp.\n      * succ np. rename x into Snp. rename H into HSnp.\n        pow_w m Snp Hm (Succ_NaturalNumber np Snp\n          (Sum_NaturalNumber n p np Hn Hp Hnp) HSnp).\n        rename x into mSnp. rename H into HmSnp. transitivity mSnp.\n        { apply (Pow_w_Unique m np' mnp' mSnp); try assumption;\n          try apply (Sum_NaturalNumber n p'); try assumption;\n          try apply (Succ_NaturalNumber p p'); try assumption.\n          replace np' with Snp; try assumption. symmetry.\n          apply (A2 n p p' np); try assumption. }\n        { apply (E2 m np mnp Snp); try assumption.\n          apply (Sum_NaturalNumber n p); try assumption. }\n      * prod_w mn mp (Pow_NaturalNumber m n mn Hm Hn Hmn)\n          (Pow_NaturalNumber m p mp Hm Hp Hmp).\n        rename x into mnmp. rename H into Hmnmp.\n        prod_w m mnmp Hm (Prod_NaturalNumber mn mp mnmp\n          (Pow_NaturalNumber m n mn Hm Hn Hmn)\n          (Pow_NaturalNumber m p mp Hm Hp Hmp) Hmnmp).\n        rename x into mmnmp. rename H into Hmmnmp. transitivity mmnmp.\n        { apply (Prod_w_Unique m mnp); try assumption.\n          try apply (Pow_NaturalNumber m np); try assumption;\n          try apply (Sum_NaturalNumber n p); try assumption.\n          replace mnp with mnmp; try assumption. symmetry.\n          apply (IH np mnp mn mp mnmp); try assumption. }\n        { apply (Prod_w_Unique m mnmp); try assumption;\n          try apply (Prod_NaturalNumber mn mp); try assumption;\n          try apply (Pow_NaturalNumber m n mn); try assumption;\n          try apply (Pow_NaturalNumber m p mp); try assumption.\n          replace mnmp with mpmn; try assumption.\n          apply (Enderton4K5 mp mn); try assumption;\n          try apply (Pow_NaturalNumber m p mp); try assumption;\n          try apply (Pow_NaturalNumber m n mn); try assumption. }\n    + prod_w mp' mn (Pow_NaturalNumber m p' mp' Hm (Succ_NaturalNumber p p' Hp Hp')\n        Hmp') (Pow_NaturalNumber m n mn Hm Hn Hmn).\n      rename x into mp'mn. rename H into Hmp'mn. transitivity mp'mn.\n      * prod_w m mp Hm (Pow_NaturalNumber m p mp Hm Hp Hmp).\n        rename x into mmp0. rename H into Hmmp0.\n        prod_w mmp0 mn (Prod_NaturalNumber m mp mmp0 Hm\n          (Pow_NaturalNumber m p mp Hm Hp Hmp) Hmmp0)\n          (Pow_NaturalNumber m n mn Hm Hn Hmn).\n        rename x into mmp0mn. rename H into Hmmp0mn. transitivity mmp0mn.\n        { apply (Enderton4K4 m mp mn mpmn mmp0); try assumption;\n          try apply (Pow_NaturalNumber m p mp); try assumption;\n          try apply (Pow_NaturalNumber m n); try assumption. }\n        { apply (Prod_w_Unique mmp0 mn); try assumption;\n          try apply (Prod_NaturalNumber m mp mmp0); try assumption;\n          try apply (Pow_NaturalNumber m p mp); try assumption;\n          try apply (Pow_NaturalNumber m n mn); try assumption.\n          replace mmp0 with mp'; try assumption.\n          apply (E2 m p mp p'); try assumption. }\n      * apply (Enderton4K5 mp' mn); try assumption;\n        try apply (Pow_NaturalNumber m p' mp'); try assumption;\n        try apply (Succ_NaturalNumber p p'); try assumption;\n        try apply (Pow_NaturalNumber m n); try assumption.\nQed.\n\n(** Now we have the basic algebraic operations on omega and corresponding\n    results. We next turn our attention to ordering on omega, and show that the\n    relation < is linear ordering as in the previous chapter. *)\n\nDefinition LessThan_w (lt : set) : Prop :=\n  forall mn, In mn lt <-> exists m n, OrdPair m n mn /\\ NaturalNumber m /\\\n  NaturalNumber n /\\ In m n.\n\nTheorem LessThan_w_Exists : exists lt, LessThan_w lt.\nProof.\n  omga. prod omga omga. rename x into wxw. rename H into Hwxw.\n  build_set set\n    (fun (t c mn : set) => exists m n, OrdPair m n mn /\\ NaturalNumber m /\\\n      NaturalNumber n /\\ In m n)\n    omga wxw.\n  rename x into lt. rename H into Hlt. exists lt.\n  intros mn. split; intros H; try apply Hlt, H.\n  apply Hlt. split; try assumption.\n  apply Hwxw. destruct H as [m [n [Hmn [Hm [Hn H]]]]].\n  exists m, n. repeat (split; try apply Homga; try assumption).\nQed.\n\nTheorem LessThan_w_Unique : forall lt lt', LessThan_w lt ->\n  LessThan_w lt' -> lt = lt'.\nProof.\n  intros lt lt' Hlt Hlt'.\n  apply Extensionality_Axiom. intros x. split; intros H.\n  - apply Hlt', Hlt, H.\n  - apply Hlt, Hlt', H.\nQed.\n\nLtac lt_w := destruct (LessThan_w_Exists) as [lt Hlt].\n\nDefinition In_ (x A : set) : Prop :=\n  In x A \\/ x = A.\n\nDefinition LessThanEq_w (le : set) : Prop :=\n  forall mn, In mn le <-> exists m n, OrdPair m n mn /\\ NaturalNumber m /\\\n  NaturalNumber n /\\ In_ m n.\n\nTheorem LessThanEq_w_Exists : exists le, LessThanEq_w le.\nProof.\n  omga. prod omga omga. rename x into wxw. rename H into Hwxw.\n  build_set set\n    (fun (t c mn : set) => exists m n, OrdPair m n mn /\\ NaturalNumber m /\\\n      NaturalNumber n /\\ In_ m n)\n    omga wxw.\n  rename x into le. rename H into Hle. exists le.\n  intros mn. split; intros H; try apply Hle, H.\n  apply Hle. split; try assumption.\n  destruct H as [m [n [Hmn [Hm [Hn H]]]]].\n  apply Hwxw. exists m, n. repeat (split; try apply Homga; try assumption).\nQed.\n\nTheorem Le_w_Unique : forall le le', LessThanEq_w le -> LessThanEq_w le' ->\n  le = le'.\nProof.\n  intros le le' Hle Hle'. apply Extensionality_Axiom. intros mn. split; intros H.\n  - apply Hle', Hle, H.\n  - apply Hle, Hle', H.\nQed.\n\nLtac le_w := destruct (LessThanEq_w_Exists) as [le Hle].\n\nLemma lt_w_succ_iff_le_w : forall lt le p k k' pk' pk,\n  LessThan_w lt -> LessThanEq_w le -> NaturalNumber p -> NaturalNumber k ->\n  Succ k k' -> OrdPair p k' pk' -> OrdPair p k pk -> In pk' lt <-> In pk le.\nProof.\n  intros lt le p k k' pk' pk Hlt Hle Hp Hk Hk' Hpk' Hpk. split; intros H.\n  - apply Hle. apply Hlt in H. destruct H as [p0 [k'0 [Hpk'o [Hp0 [Hk'0 H]]]]].\n    assert (T : p = p0 /\\ k' = k'0).\n    { apply (Enderton3A p k' p0 k'0 pk' pk'); try assumption; try trivial. }\n    replace p0 with p in *; replace k'0 with k' in *; try apply T.\n    clear T p0 Hp0 k'0 Hk'0. exists p, k.\n    repeat (split; try assumption). destruct Hk' as [Sk [HSk Hk']].\n    apply Hk' in H. destruct H as [H | H].\n    + left. assumption.\n    + right. apply HSk in H. assumption.\n  - apply Hle in H. destruct H as [p0 [k0 [Hpk0 [Hp0 [Hk0 H]]]]].\n    assert (T : p = p0 /\\ k = k0).\n    { apply (Enderton3A p k p0 k0 pk pk); try assumption; trivial. }\n    replace p0 with p in *; replace k0 with k in *; try apply T.\n    clear T p0 k0 Hp0 Hk0. apply Hlt. exists p, k'.\n    repeat (split; try assumption); try apply (Succ_NaturalNumber k k' Hk Hk').\n    destruct Hk' as [Sk [HSk Hk']]. apply Hk'. destruct H as [H | H].\n    + left. assumption.\n    + right. apply HSk. assumption.\nQed.\n\nDefinition Lt_w (m n : set) : Prop :=\n  exists lt mn, LessThan_w lt /\\ OrdPair m n mn /\\ In mn lt.\n\nDefinition Le_w (m n : set) : Prop :=\n  exists le mn, LessThanEq_w le /\\ OrdPair m n mn /\\ In mn le.\n\nCorollary Nats_sets_of_smaller_nats : forall n x, NaturalNumber n ->\n  In x n <-> NaturalNumber n /\\ Lt_w x n.\nProof.\n  intros n x Hn. split; intros H.\n  - split; try assumption. lt_w. ordpair x n. rename x0 into xn. rename H into Hxn.\n    exists lt, xn. repeat (split; try assumption).\n    apply Hlt. exists x, n. repeat (split; try assumption).\n    omga. apply Homga. apply (Enderton4G omga Homga n x); try assumption.\n    apply Homga, Hn.\n  - destruct H as [_ [lt [xn [Hlt [Hxn H]]]]].\n    apply Hlt in H. destruct H as [x' [n' [Hxn' [Hx' [Hn' H]]]]].\n    assert (T : x = x' /\\ n = n').\n    { apply (Enderton3A x n x' n' xn xn Hxn Hxn'); trivial. }\n    replace x' with x in *; replace n' with n in *; try apply T; assumption.\nQed.\n\nLemma lt_relation_on_omega : forall lt omga, LessThan_w lt -> Nats omga ->\n  RelationOn lt omga.\nProof.\n  intros lt omga Hlt Homga. intros mn Hmn.\n  apply Hlt in Hmn. destruct Hmn as [m [n [Hmn [Hm [Hn H]]]]].\n  exists m, n. repeat (split; try assumption); apply Homga; assumption.\nQed.\n\nLemma lt_transitive : forall lt, LessThan_w lt -> Transitive lt.\nProof.\n  intros lt Hlt m n p mn np mp Hmn Hnp Hmp H I.\n  apply Hlt. apply Hlt in H. apply Hlt in I.\n  destruct H as [m' [n' [Hmn' [Hm [Hn H]]]]].\n  assert (T : m = m' /\\ n = n').\n  { apply (Enderton3A m n m' n' mn mn Hmn Hmn'); trivial. }\n  replace m' with m in *; replace n' with n in *; try apply T.\n  clear T m' n' Hmn'. destruct I as [n' [p' [Hnp' [_ [Hp I]]]]].\n  assert (T : n = n' /\\ p = p').\n  { apply (Enderton3A n p n' p' np np Hnp Hnp'); trivial. }\n  replace n' with n in *; replace p' with p in *; try apply T.\n  clear T n' p' Hnp'. exists m, p. repeat (split; try assumption).\n  apply (Enderton4F p Hp n m); try assumption.\nQed.\n\nLemma Enderton4La : forall lt m n m' n' mn m'n', LessThan_w lt ->\n  NaturalNumber m -> NaturalNumber n -> Succ m m' -> Succ n n' ->\n  OrdPair m n mn -> OrdPair m' n' m'n' -> In mn lt <-> In m'n' lt.\nProof.\n  intros lt m n m' n' mn m'n' Hlt Hm Hn Hm' Hn' Hmn Hm'n'. split; intros H.\n  - generalize dependent m'n'. generalize dependent mn. generalize dependent n'.\n    generalize dependent m'. generalize dependent m.\n    omga. build_set set\n      (fun (lt c n : set) => forall m, NaturalNumber m -> forall m', Succ m m' ->\n        forall n', Succ n n' -> forall mn, OrdPair m n mn -> In mn lt ->\n        forall m'n', OrdPair m' n' m'n' -> In m'n' lt) lt omga.\n    rename x into T. rename H into HT. apply HT.\n    replace T with omga; try apply Homga, Hn. symmetry. clear n Hn.\n    apply Induction_Principle_for_Omega; try assumption; try split;\n    try (intros t Ht; apply HT, Ht).\n    + empty. rename x into o. rename H into Ho. exists o. split; try assumption.\n      apply HT. split; try apply Homga, Zero_NaturalNumber, Ho.\n      intros m Hm m' Hm' n' Hn' mn Hmn H m'n' Hm'n'.\n      apply Hlt. exists m', n'. repeat (split; try assumption).\n      * apply (Succ_NaturalNumber m m'); try assumption.\n      * apply (Succ_NaturalNumber o n'); try assumption;\n        apply (Zero_NaturalNumber), Ho.\n      * apply Hlt in H. destruct H as [m0 [n0 [Hmn0 [Hm0 [Hn0 H]]]]].\n        assert (P : m = m0 /\\ o = n0).\n        { apply (Enderton3A m o m0 n0 mn mn Hmn Hmn0); trivial. }\n        replace m0 with m in *; replace n0 with o in *; try apply P.\n        destruct (Ho m); try assumption.\n    + intros n n' Hn' Hn. apply HT in Hn. destruct Hn as [Hn IH].\n      apply HT. apply Homga in Hn.\n      split; try apply Homga, (Succ_NaturalNumber n n' Hn Hn').\n      intros m Hm m' Hm' n'' Hn'' mn' Hmn' H m'n'' Hm'n''.\n      apply Hlt. exists m', n''. split; try assumption.\n      split; try apply (Succ_NaturalNumber m m' Hm Hm').\n      split; try apply (Succ_NaturalNumber n' n''\n        (Succ_NaturalNumber n n' Hn Hn') Hn'').\n      apply Hlt in H. destruct H as [m0 [n'0 [Hmn'0 [Hm0 [Hn'0 H]]]]].\n      assert (P : m = m0 /\\ n' = n'0).\n      { apply (Enderton3A m n' m0 n'0 mn' mn' Hmn' Hmn'0); trivial. }\n      replace m0 with m in *; replace n'0 with n' in *; try apply P.\n      clear P m0 n'0 Hmn'0 Hm0.\n      destruct Hn'' as [Sn' [HSn' Hn'']]. apply Hn''.\n      destruct Hn' as [Sn [HSn Hn']]. apply Hn' in H.\n      destruct H as [H | H].\n      * left. ordpair m n. rename x into mn. rename H0 into Hmn.\n        ordpair m' n'. rename x into m'n'. rename H0 into Hm'n'.\n        assert (P : In mn lt).\n        { apply Hlt. exists m, n. repeat (split; try assumption). }\n        assert (Q : Succ n n').\n        { exists Sn. split; assumption. }\n        assert (R : In m'n' lt).\n        { apply (IH m Hm m' Hm' n' Q mn Hmn P m'n' Hm'n'). }\n        apply Hlt in R. destruct R as [m'0 [n'0 [Hm'n'0 [Hm'0 [Hn'0' R]]]]].\n        assert (S : m' = m'0 /\\ n' = n'0).\n        { apply (Enderton3A m' n' m'0 n'0 m'n' m'n' Hm'n' Hm'n'0); trivial. }\n        replace m'0 with m' in *; replace n'0 with n' in *; try apply S; apply R.\n      * right. apply HSn'. apply (Succ_Unique m m' n'); try assumption.\n        apply HSn in H. replace m with n; try assumption.\n        exists Sn. split; assumption.\n  - apply Hlt. exists m, n. repeat (split; try assumption).\n    apply Hlt in H. destruct H as [m'0 [n'0 [Hm'n'0 [_ [_ H]]]]].\n    assert (P : m' = m'0 /\\ n' = n'0).\n    { apply (Enderton3A m' n' m'0 n'0 m'n' m'n' Hm'n' Hm'n'0); trivial. }\n    replace m'0 with m' in *; replace n'0 with n' in *; try apply P.\n    destruct Hn' as [Sn [HSn Hn']]. destruct Hm' as [Sm [HSm Hm']].\n    apply Hn' in H. destruct H as [H | H].\n    + apply (Enderton4F n Hn m' m); try assumption.\n      apply Hm'. right. apply HSm. trivial.\n    + apply HSn in H. replace n with m'. apply Hm'. right. apply HSm. trivial.\nQed.\n\nLemma Enderton4Lb : forall m, NaturalNumber m -> ~ In m m.\nProof.\n  intros m Hm. omga. build_set set (fun (t c m : set) => ~ In m m) omga omga.\n  rename x into T. rename H into HT. apply HT.\n  replace T with omga; try apply Homga, Hm. clear m Hm. symmetry.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros t Ht; apply HT, Ht).\n  - empty. rename x into o. rename H into Ho. exists o. split; try assumption.\n    apply HT. split; try apply Homga, Zero_NaturalNumber, Ho.\n    intros C. apply (Ho o). assumption.\n  - intros m m' Hm' Hm. apply HT in Hm. destruct Hm as [Hm IH].\n    apply HT. apply Homga in Hm.\n    split; try apply Homga, (Succ_NaturalNumber m m' Hm Hm').\n    intros C. apply IH. lt_w. ordpair m m. rename x into mm. rename H into Hmm.\n    ordpair m' m'. rename x into m'm'. rename H into Hm'm'.\n    assert (P : In mm lt).\n    { apply (Enderton4La lt m m m' m' mm m'm'); try assumption.\n      apply Hlt. exists m', m'. repeat (split; try assumption);\n      apply (Succ_NaturalNumber m m' Hm Hm'). }\n    apply Hlt in P. destruct P as [m0 [m0' [Hmm0 [_ [_ P]]]]].\n    assert (Q : m = m0 /\\ m = m0').\n    { apply (Enderton3A m m m0 m0' mm mm Hmm Hmm0); trivial. }\n    replace m0 with m in *; replace m0' with m in *; try assumption; try apply Q.\nQed.\n\nLemma Zero_Leq_N : forall o n, Empty o -> NaturalNumber n -> In_ o n.\nProof.\n  intros o n Ho Hn. generalize dependent o. omga.\n  build_set set (fun (t c n : set) => forall o, Empty o -> In_ o n) omga omga.\n  rename x into T. rename H into HT. apply HT.\n  replace T with omga; try apply Homga, Hn. symmetry. clear n Hn.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros t Ht; apply HT, Ht).\n  - empty. rename x into o. rename H into Ho. exists o. split; try assumption.\n    apply HT. split; try apply Homga, Zero_NaturalNumber, Ho.\n    intros o' Ho'. replace o' with o; try (right; trivial).\n    apply Empty_Unique; assumption.\n  - intros n n' Hn' Hn. apply HT in Hn. destruct Hn as [Hn IH].\n    apply HT. apply Homga in Hn.\n    split; try apply Homga, (Succ_NaturalNumber n n' Hn Hn').\n    intros o Ho. destruct (IH o Ho) as [IHo | IHo].\n    + left. apply (Enderton4F n'\n        (Succ_NaturalNumber n n' Hn Hn') n o); try assumption.\n      destruct Hn' as [Sn [HSn Hn']]. apply Hn'. right. apply HSn. trivial.\n    + destruct Hn' as [Sn [HSn Hn']]. left. apply Hn'. right.\n      apply HSn. assumption.\nQed.\n\nLemma Trichotomous_w : forall omga lt, Nats omga -> LessThan_w lt ->\n  Trichotomous lt omga.\nProof.\n  intros omga lt Homga Hlt m n mn nm Hm. generalize dependent nm.\n  generalize dependent mn. generalize dependent n.\n  build_set set\n    (fun (lt omga m : set) => forall n mn nm, In n omga -> OrdPair m n mn ->\n      OrdPair n m nm -> In mn lt /\\ m <> n /\\ ~ In nm lt \\/\n      ~ In mn lt /\\ m = n /\\ ~ In nm lt \\/ ~ In mn lt /\\ m <> n /\\ In nm lt)\n    lt omga.\n  rename x into T. rename H into HT. apply HT.\n  replace T with omga; try assumption. clear m Hm. symmetry.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros t Ht; apply HT, Ht).\n  - empty. rename x into o. rename H into Ho. exists o. split; try assumption.\n    apply HT. split; try apply Homga, Zero_NaturalNumber, Ho.\n    intros n on no Hn Hon Hno. apply Homga in Hn.\n    destruct (Zero_Leq_N o n Ho Hn) as [H | H].\n    + left. split; try split.\n      * apply Hlt. exists o, n. repeat (split; try assumption).\n        apply Zero_NaturalNumber, Ho.\n      * intros C. rewrite C in H. apply (Enderton4Lb n); assumption.\n      * intros C. apply (Ho n). apply Hlt in C.\n        destruct C as [n' [o' [Hno' [_ [_ C]]]]].\n        assert (P : n = n' /\\ o = o').\n        { apply (Enderton3A n o n' o' no no Hno Hno'). trivial. }\n        replace n' with n in *; replace o' with o in *; try apply P. apply C.\n    + right. left. split; try split; try assumption.\n      * intros C. apply (Enderton4Lb n); try assumption.\n        apply Hlt in C. destruct C as [o' [n' [Hon' [_ [_ C]]]]].\n        assert (T0 : o = o' /\\ n = n').\n        { apply (Enderton3A o n o' n' on on); try assumption; trivial. }\n        replace o' with o in *; replace n' with n in *; try apply T0.\n        rewrite H in C. assumption.\n      * intros C. apply (Enderton4Lb n); try assumption.\n        apply Hlt in C. destruct C as [n' [o' [Hno' [_ [_ C]]]]].\n        assert (T0 : n = n' /\\ o = o').\n        { apply (Enderton3A n o n' o' no no); try assumption; trivial. }\n        replace o' with o in *; replace n' with n in *; try apply T0.\n        rewrite H in C. assumption.\n  - intros m m' Hm' Hm. apply HT in Hm. destruct Hm as [Hm IH].\n    apply HT. apply Homga in Hm.\n    split; try apply Homga, (Succ_NaturalNumber m m' Hm Hm').\n    intros n m'n nm' Hn Hm'n Hnm'.\n    ordpair m n. rename H into Hmn. rename x into mn.\n    ordpair n m. rename H into Hnm. rename x into nm.\n    destruct (IH n mn nm Hn Hmn Hnm) as [IH0 | [IH0 | IH0]];\n    destruct IH0 as [IH0 [IH1 IH2]].\n    + apply Homga in Hn. succ n. rename x into n'. rename H into Hn'. le_w.\n      ordpair m' n'. rename x into m'n'. rename H into Hm'n'.\n      assert (P : Lt_w m' n').\n      { exists lt, m'n'. repeat (split; try assumption).\n        apply (Enderton4La lt m n m' n' mn m'n' Hlt Hm Hn Hm' Hn' Hmn Hm'n').\n        assumption. }\n      destruct (lt_w_succ_iff_le_w lt le m' n n' m'n' m'n) as [H _];\n      try assumption; try (apply (Succ_NaturalNumber m m'); assumption).\n      assert (Q : In m'n' lt).\n      { destruct P as [lt' [m'n'0 [Hlt' [Hm'n'o P]]]].\n        replace lt with lt'; try (apply (LessThan_w_Unique lt' lt Hlt' Hlt)).\n        replace m'n' with m'n'0; try assumption.\n        apply (OrdPair_Unique m' n'); try assumption. }\n      apply H in Q. apply Hle in Q.\n      destruct Q as [m'0 [n0 [Hm'n0 [_ [_ Q]]]]].\n      assert (R : m' = m'0 /\\ n = n0).\n      { apply (Enderton3A m' n m'0 n0 m'n m'n Hm'n Hm'n0). trivial. }\n      replace m'0 with m' in *; replace n0 with n in *; try apply R.\n      clear R m'0 n0 Hm'n0. destruct Q as [Q | Q].\n      * left. split; try split.\n        { apply Hlt. exists m', n. repeat (split; try assumption);\n          try (apply (Succ_NaturalNumber m); assumption);\n          try (apply Homga; assumption). }\n        { intros C. rewrite C in Q. apply (Enderton4Lb n); assumption. }\n        { intros C. apply (Enderton4Lb m');\n          try (apply (Succ_NaturalNumber m); assumption).\n          apply (Enderton4F m' (Succ_NaturalNumber m m' Hm Hm') n m'); try assumption.\n          apply Hlt in C. destruct C as [n0 [m'0 [Hnm'0 [_ [_ C]]]]].\n          assert (R : n = n0 /\\ m' = m'0).\n          { apply (Enderton3A n m' n0 m'0 nm' nm' Hnm' Hnm'0). trivial. }\n          replace n0 with n in *; replace m'0 with m' in *; try apply R. apply C. }\n      * right. left. split; try split; try assumption.\n        { intros C. apply (Enderton4Lb n); try assumption.\n          apply Hlt in C. destruct C as [m'0 [n0 [Hm'n0 [_ [_ C]]]]].\n          replace m'0 with m' in C;\n          try (apply (Enderton3A m' n m'0 n0 m'n m'n Hm'n Hm'n0); try trivial).\n          replace n0 with n in *;\n          try (apply (Enderton3A m' n m'0 n0 m'n m'n Hm'n Hm'n0); try trivial).\n          rewrite Q in C. assumption. }\n        { intros C. apply (Enderton4Lb m'); try assumption.\n          try (apply (Succ_NaturalNumber m); assumption).\n          apply Hlt in C. destruct C as [n0 [m'0 [Hnm'0 [_ [_ C]]]]].\n          replace m'0 with m' in C;\n          try (apply (Enderton3A n m' n0 m'0 nm' nm' Hnm' Hnm'0); try trivial).\n          replace n0 with n in *;\n          try (apply (Enderton3A n m' n0 m'0 nm' nm' Hnm' Hnm'0); try trivial).\n          rewrite <- Q in C. assumption. }\n    + apply Homga in Hn. right. right. split; try split.\n      * intros C. apply (Enderton4Lb n); try assumption;\n        try (apply (Succ_NaturalNumber m); assumption).\n        apply (Enderton4F n Hn m' n).\n        { apply Hlt in C. destruct C as [m'0 [n0 [Hm'n0 [_ [_ C]]]]].\n          replace m'0 with m' in C;\n          try (apply (Enderton3A m' n m'0 n0 m'n m'n Hm'n Hm'n0); try trivial).\n          replace n0 with n in *;\n          try (apply (Enderton3A m' n m'0 n0 m'n m'n Hm'n Hm'n0); try trivial).\n          assumption. }\n        { replace n with m. destruct Hm' as [Sm [HSm Hm']].\n          apply Hm'. right. apply HSm. trivial. }\n      * intros C. apply (Enderton4Lb n); try assumption.\n        apply (Enderton4F n Hn m' n).\n        { replace m' with m. replace n with m'. destruct Hm' as [Sm [HSm Hm']].\n          apply Hm'. right. apply HSm. trivial.\n          transitivity n; try assumption; symmetry; assumption. }\n        { replace n with m. destruct Hm' as [Sm [HSm Hm']].\n          apply Hm'. right. apply HSm. trivial. }\n      * apply Hlt. exists n, m'. repeat (split; try assumption).\n        { apply (Succ_NaturalNumber m m'); assumption. }\n        { replace n with m. destruct Hm' as [Sm [HSm Hm']].\n          apply Hm'. right. apply HSm. trivial. }\n    + apply Homga in Hn. right. right. split; try split.\n      * intros C. apply (Enderton4Lb n); try assumption.\n        ordpair n n. rename x into nn. rename H into Hnn.\n        assert (P : In nn lt).\n        { apply (lt_transitive lt Hlt n m' n nm' m'n nn); try assumption.\n          ordpair m m'. rename x into mm'. rename H into Hmm'.\n          apply (lt_transitive lt Hlt n m m' nm mm' nm'); try assumption.\n          apply Hlt. exists m, m'. repeat (split; try assumption).\n          try (apply (Succ_NaturalNumber m); try assumption).\n          destruct Hm' as [Sm [HSm Hm']]. apply Hm'.\n          right. apply HSm. trivial. }\n        apply Hlt in P. destruct P as [n0 [n1 [Hnn' [_ [_ P]]]]].\n        assert (Q : n = n0 /\\ n = n1).\n        { apply (Enderton3A n n n0 n1 nn nn Hnn Hnn'). trivial. }\n        replace n0 with n in *; replace n1 with n in *; try apply Q; assumption.\n      * intros C. apply (Enderton4Lb m); try assumption.\n        apply (Enderton4F m Hm m' m).\n        { replace m' with n. apply Hlt in IH2.\n          destruct IH2 as [n0 [m0 [Hnm0 [_ [_ IH2]]]]].\n          assert (P : n = n0 /\\ m = m0).\n          { apply (Enderton3A n m n0 m0 nm nm Hnm Hnm0). trivial. }\n          replace n0 with n in *; replace m0 with m in *; try apply P; assumption. }\n        { destruct Hm' as [Sm [HSm Hm']]. apply Hm'. right. apply HSm. trivial. }\n      * le_w. apply (lt_w_succ_iff_le_w lt le n m m' nm' nm); try assumption.\n        apply Hle. exists n, m. repeat (split; try assumption).\n        left. apply Hlt in IH2. destruct IH2 as [n0 [m0 [Hnm0 [_ [_ IH2]]]]].\n        assert (P : n = n0 /\\ m = m0).\n        { apply (Enderton3A n m n0 m0 nm nm Hnm Hnm0). trivial. }\n        replace n0 with n in *; replace m0 with m in *; try apply P; assumption.\nQed.\n\nCorollary Nats_LinearOrdered : forall omga lt, Nats omga -> LessThan_w lt ->\n  LinearOrdering lt omga.\nProof.\n  intros omga lt Homga Hlt. split; try split.\n  - apply (lt_relation_on_omega); try assumption.\n  - apply lt_transitive; assumption.\n  - apply Trichotomous_w; try assumption.\nQed.\n\nDefinition ProperSubset (A B : set) : Prop := Subset A B /\\ A <> B.\n\nCorollary Enderton4M : forall m n, NaturalNumber m -> NaturalNumber n -> \n  In m n <-> ProperSubset m n.\nProof.\n  intros m n Hm Hn. split; intros H.\n  - split.\n    + intros p Hp. apply (Enderton4F n Hn m p); try assumption.\n    + intros C. rewrite C in H. apply (Enderton4Lb n); assumption.\n  - lt_w. omga. ordpair m n. rename x into mn. rename H0 into Hmn.\n    ordpair n m. rename x into nm. rename H0 into Hnm.\n    apply Homga in Hm. apply Homga in Hn.\n    destruct (Trichotomous_w omga lt Homga Hlt m n mn nm Hm Hn Hmn Hnm) as\n      [[H0 [H1 H2]] | [[H0 [H1 H2]] | [H0 [H1 H2]]]].\n    + apply Hlt in H0. destruct H0 as [m' [n' [Hmn' [_ [_ H0]]]]].\n      assert (T : m = m' /\\ n = n').\n      { apply (Enderton3A m n m' n' mn mn Hmn Hmn'). trivial. }\n      replace m' with m in *; replace n' with n in *; try assumption; try apply T.\n    + destruct H as [_ H]. destruct (H H1).\n    + apply Homga in Hn. destruct (Enderton4Lb n); try assumption.\n      destruct H as [H _]. apply H. apply Hlt in H2.\n      destruct H2 as [n' [m' [Hnm' [_ [_ H2]]]]].\n      assert (T : n = n' /\\ m = m').\n      { apply (Enderton3A n m n' m' nm nm Hnm Hnm'). trivial. }\n      replace n' with n in *; replace m' with m in *; try assumption; apply T.\nQed.\n\nCorollary Enderton4M' : forall m n, NaturalNumber m -> NaturalNumber n ->\n  In_ m n <-> Subset m n.\nProof.\n  intros m n Hm Hn. split; intros H.\n  - destruct H as [H | H].\n    + apply (Enderton4M m n Hm Hn). assumption.\n    + rewrite H. apply Subset_Reflexive.\n  - assert (P : m = n \\/ m <> n). { apply REM. }\n    destruct P as [P | P].\n    + right. assumption.\n    + left. apply (Enderton4M m n Hm Hn). split; try assumption.\nQed.\n\nTheorem Enderton4N : forall m n p mp np, NaturalNumber m -> NaturalNumber n ->\n  NaturalNumber p -> Sum_w m p mp -> Sum_w n p np -> In m n <-> In mp np.\nProof.\n  destruct Enderton4I as [A1 A2].\n  assert (I : forall m n p mp np, NaturalNumber m -> NaturalNumber n ->\n    NaturalNumber p -> Sum_w m p mp -> Sum_w n p np -> In m n -> In mp np).\n  { intros m n p mp np Hm Hn Hp. omga.\n    generalize dependent np. generalize dependent mp.\n    build_set (prod set set)\n      (fun (t : set * set) (c p : set) => forall mp np, Sum_w (fst t) p mp ->\n        Sum_w (snd t) p np -> In m n -> In mp np) (m, n) omga.\n    rename x into T. rename H into HT. simpl in HT. apply HT.\n    replace T with omga; try apply Homga, Hp. symmetry. clear p Hp.\n    apply Induction_Principle_for_Omega; try assumption; try split;\n    try (intros t Ht; apply HT, Ht).\n    + empty. exists x. split; try assumption. apply HT.\n      split; try apply Homga, Zero_NaturalNumber; try assumption.\n      intros mp np Hmp Hnp P. simpl in *.\n      replace mp with m. replace np with n. assumption.\n      * apply (Sum_w_Unique n x n np); try assumption;\n        try (apply Zero_NaturalNumber, H).\n        apply A1; assumption.\n      * apply (Sum_w_Unique m x m mp); try assumption;\n        try (apply Zero_NaturalNumber, H).\n        apply A1; assumption.\n    + intros p p' Hp' Hp. apply HT in Hp. destruct Hp as [Hp IH].\n      apply HT. apply Homga in Hp.\n      split; try apply Homga, (Succ_NaturalNumber p p' Hp Hp').\n      intros mp' np' Hmp' Hnp' H. simpl in *.\n      sum_w m p Hm Hp. rename x into mp. rename H0 into Hmp.\n      sum_w n p Hn Hp. rename x into np. rename H0 into Hnp. lt_w.\n      ordpair mp np. rename x into mpnp. rename H0 into Hmpnp.\n      succ mp. rename x into Smp. rename H0 into HSmp.\n      succ np. rename x into Snp. rename H0 into HSnp.\n      ordpair Smp Snp. rename x into SmpSnp. rename H0 into HSmpSnp.\n      assert (P : In mpnp lt).\n      { apply Hlt. exists mp, np. repeat (split; try assumption);\n        try apply (IH mp np Hmp Hnp H);\n        try (apply (Sum_NaturalNumber m p); assumption);\n        try (apply (Sum_NaturalNumber n p); assumption). }\n      apply (Enderton4La lt mp np Smp Snp mpnp SmpSnp) in P; try assumption;\n      try (apply (Sum_NaturalNumber m p); assumption);\n      try (apply (Sum_NaturalNumber n p); assumption). \n      apply Hlt in P. destruct P as [Smp' [Snp' [HSmpSnp' [HSmp' [HSnp' P]]]]].\n      assert (Q : Smp = Smp' /\\ Snp = Snp').\n      { apply (Enderton3A Smp Snp Smp' Snp' SmpSnp SmpSnp); try assumption; trivial. }\n      replace Smp' with Smp in *; replace Snp' with Snp in *; try apply Q.\n      replace mp' with Smp. replace np' with Snp. assumption.\n      * symmetry. apply (A2 n p p' np); try assumption.\n      * symmetry. apply (A2 m p p' mp); try assumption. }\n  intros m n p mp np Hm Hn Hp Hmp Hnp.\n  split; try (apply (I m n p mp np); assumption).\n  intros H. ordpair m n. rename x into mn. rename H0 into Hmn.\n  ordpair n m. rename x into nm. rename H0 into Hnm. lt_w. omga.\n  destruct (Trichotomous_w omga lt Homga Hlt m n mn nm) as [P | [P | P]];\n  try assumption; try apply Homga, Hn; try apply Homga, Hm;\n  destruct P as [P0 [P1 P2]].\n  + apply Hlt in P0. destruct P0 as [m' [n' [Hmn' [Hm' [Hn' P0]]]]].\n    assert (Q : m = m' /\\ n = n').\n    { apply (Enderton3A m n m' n' mn mn Hmn Hmn'); trivial. }\n    replace m' with m in *; replace n' with n in *; try apply Q; assumption.\n  + destruct (Enderton4Lb np); try (apply (Sum_NaturalNumber n p); assumption).\n    replace mp with np in H; try assumption.\n    apply (Sum_w_Unique n p); try assumption.\n    replace n with m. assumption.\n  + assert (Q : In np mp).\n    { apply (I n m p); try assumption. apply Hlt in P2.\n      destruct P2 as [n' [m' [Hnm' [Hn' [Hm' P2]]]]].\n      assert (R : n = n' /\\ m = m').\n      { apply (Enderton3A n m n' m' nm nm Hnm Hnm'); trivial. }\n      replace n' with n in *; replace m' with m in *; try apply R; assumption. }\n    destruct (Enderton4Lb mp); try (apply (Sum_NaturalNumber m p); assumption).\n    apply (Enderton4F mp (Sum_NaturalNumber m p mp Hm Hp Hmp) np mp); assumption.\nQed.\n\nTheorem Enderton4N' : forall m n p mp np, NaturalNumber m -> NaturalNumber n ->\n  NaturalNumber p -> ~Empty p -> Prod_w m p mp -> Prod_w n p np ->\n  In m n <-> In mp np.\nProof.\n  omga. lt_w. destruct Enderton4I as [A1 A2]. destruct Enderton4J as [M1 M2].\n  assert (I : forall m n p mp np, NaturalNumber m -> NaturalNumber n ->\n    NaturalNumber p -> ~ Empty p -> Prod_w m p mp -> Prod_w n p np ->\n    In m n -> In mp np).\n  { intros m n p mp np Hm Hn Hp. generalize dependent np. generalize dependent mp.\n    build_set (prod set set)\n      (fun (t : set * set) (c p : set) => forall mp np, ~Empty p ->\n        Prod_w (fst t) p mp -> Prod_w (snd t) p np -> In (fst t) (snd t) ->\n        In mp np)\n      (m, n) omga.\n    rename x into T. rename H into HT. apply HT.\n    replace T with omga; try apply Homga, Hp. symmetry. clear p Hp.\n    apply Induction_Principle_for_Omega; try assumption; try split;\n    try (intros t Ht; apply HT, Ht).\n    - empty. rename x into o. rename H into Ho. exists o. split; try assumption.\n      apply HT. split; try apply Homga, Zero_NaturalNumber, Ho.\n      intros mp np C. apply C in Ho. destruct Ho.\n    - intros p p' Hp' Hp. apply HT in Hp. destruct Hp as [Hp IH].\n      apply HT. apply Homga in Hp.\n      split; try apply Homga, (Succ_NaturalNumber p p' Hp Hp').\n      assert (P : Empty p \\/ ~ Empty p). { apply REM. }\n      intros mp' np' Hne Hmp' Hnp' H. simpl in *. destruct P as [P | P].\n      + replace mp' with m. replace np' with n. assumption.\n        * prod_w n p Hn Hp. rename x into np. rename H0 into Hnp.\n          sum_w n np Hn (Prod_NaturalNumber n p np Hn Hp Hnp).\n          rename x into nnp. rename H0 into Hnnp. transitivity nnp.\n          { sum_w n p Hn Hp. rename x into npp. rename H into Hnpp.\n            transitivity npp.\n            - apply (Sum_w_Unique n p); try assumption. apply A1; assumption.\n            - apply (Sum_w_Unique n p); try assumption.\n              replace p with np; try assumption.\n              apply (Prod_w_Unique n p); try assumption. apply M1; assumption. }\n          { symmetry. apply (M2 n p np p'); try assumption. }\n        * prod_w m p Hm Hp. rename x into mp. rename H0 into Hmp.\n          sum_w m mp Hm (Prod_NaturalNumber m p mp Hm Hp Hmp).\n          rename x into mmp. rename H0 into Hmmp. transitivity mmp.\n          { sum_w m p Hm Hp. rename x into mpp. rename H into Hmpp.\n            transitivity mpp.\n            - apply (Sum_w_Unique m p); try assumption. apply A1; assumption.\n            - apply (Sum_w_Unique m p); try assumption.\n              replace p with mp; try assumption.\n              apply (Prod_w_Unique m p); try assumption. apply M1; assumption. }\n          { symmetry. apply (M2 m p mp p'); try assumption. }\n      + prod_w m p Hm Hp. rename x into mp. rename H0 into Hmp.\n        prod_w n p Hn Hp. rename x into np. rename H0 into Hnp.\n        sum_w m mp Hm (Prod_NaturalNumber m p mp Hm Hp Hmp).\n        rename x into mmp. rename H0 into Hmmp.\n        sum_w n np Hn (Prod_NaturalNumber n p np Hn Hp Hnp).\n        rename x into nnp. rename H0 into Hnnp.\n        sum_w n mp Hn (Prod_NaturalNumber m p mp Hm Hp Hmp).\n        rename x into nmp. rename H0 into Hnmp.\n        replace mp' with mmp. replace np' with nnp.\n        apply (Enderton4F nnp (Sum_NaturalNumber n np nnp Hn\n          (Prod_NaturalNumber n p np Hn Hp Hnp) Hnnp) nmp).\n        * sum_w mp n (Prod_NaturalNumber m p mp Hm Hp Hmp) Hn.\n          rename x into mpn. rename H0 into Hmpn. replace nmp with mpn.\n          sum_w np n (Prod_NaturalNumber n p np Hn Hp Hnp) Hn.\n          rename x into npn. rename H0 into Hnpn. replace nnp with npn.\n          apply (Enderton4N mp np n mpn npn); try assumption;\n          try (apply (Prod_NaturalNumber m p); assumption);\n          try (apply (Prod_NaturalNumber n p); assumption).\n          apply (IH mp np P Hmp Hnp H).\n          { apply (Enderton4K2 np n); try assumption.\n            apply (Prod_NaturalNumber n p); assumption. }\n          { apply (Enderton4K2 mp n); try assumption.\n            apply (Prod_NaturalNumber m p); assumption. }\n        * apply (Enderton4N m n mp); try assumption.\n          apply (Prod_NaturalNumber m p); assumption.\n        * symmetry. apply (M2 n p np p'); try assumption.\n        * symmetry. apply (M2 m p mp p'); assumption. }\n  intros m n p mp np Hm Hn Hp Hne Hmp Hnp.\n  split; try apply (I m n p mp np); try assumption.\n  intros H. ordpair m n. rename x into mn. rename H0 into Hmn.\n  ordpair n m. rename x into nm. rename H0 into Hnm.\n  destruct (Trichotomous_w omga lt Homga Hlt m n mn nm) as [P | [P | P]];\n  try assumption; try (apply Homga; apply Hn); try (apply Homga; apply Hm);\n  destruct P as [P0 [P1 P2]].\n  - apply Hlt in P0. destruct P0 as [m' [n' [Hmn' [_ [_ P0]]]]].\n    assert (P : m = m' /\\ n = n').\n    { apply (Enderton3A m n m' n' mn mn Hmn Hmn'); trivial. }\n    replace m' with m in *; replace n' with n in *; try apply P; assumption.\n  - replace np with mp in H. destruct (Enderton4Lb mp); try assumption;\n    try (apply (Prod_NaturalNumber m p); assumption).\n    apply (Prod_w_Unique m p); try assumption. replace m with n; assumption.\n  - assert (Q : In n m).\n    { apply Hlt in P2. destruct P2 as [n' [m' [Hnm' [_ [_ P2]]]]].\n      assert (P : n = n' /\\ m = m').\n      { apply (Enderton3A n m n' m' nm nm Hnm Hnm'); trivial. }\n      replace m' with m in *; replace n' with n in *; try apply P; assumption. }\n    destruct (Enderton4Lb mp (Prod_NaturalNumber m p mp Hm Hp Hmp)).\n    apply (Enderton4F mp (Prod_NaturalNumber m p mp Hm Hp Hmp) np); try assumption.\n    apply (I n m p np mp); try assumption.\nQed.    \n\nCorollary Enderton4P : forall m n p mp np, NaturalNumber m -> NaturalNumber n ->\n  NaturalNumber p -> Sum_w m p mp -> Sum_w n p np -> mp = np -> m = n.\nProof.\n  intros m n p mp np Hm Hn Hp Hmp Hnp H. omga. lt_w.\n  ordpair m n. rename x into mn. rename H0 into Hmn.\n  ordpair n m. rename x into nm. rename H0 into Hnm.\n  destruct (Trichotomous_w omga lt Homga Hlt m n mn nm) as [P | [P | P]];\n  try assumption; try apply Homga; try assumption; destruct P as [P0 [P1 P2]].\n  - assert (P : In m n).\n    { apply Hlt in P0. destruct P0 as [m' [n' [Hmn' [_ [_ P0]]]]].\n      assert (T : m = m' /\\ n = n').\n      { apply (Enderton3A m n m' n' mn mn Hmn Hmn'); trivial. }\n      replace m' with m in *; replace n' with n in *; try apply T; assumption. }\n    assert (Q : In mp np).\n    { apply (Enderton4N m n p mp np); try assumption. }\n    rewrite H in Q. destruct (Enderton4Lb np); try assumption.\n    apply (Sum_NaturalNumber n p); assumption.\n  - assumption.\n  - assert (P : In n m).\n    { apply Hlt in P2. destruct P2 as [n' [m' [Hnm' [_ [_ P2]]]]].\n      assert (T : n = n' /\\ m = m').\n      { apply (Enderton3A n m n' m' nm nm Hnm Hnm'); trivial. }\n      replace m' with m in *; replace n' with n in *; try apply T; assumption. }\n    assert (Q : In np mp).\n    { apply (Enderton4N n m p np mp); try assumption. }\n    rewrite H in Q. destruct (Enderton4Lb np); try assumption.\n    apply (Sum_NaturalNumber n p); assumption.\nQed.\n\nCorollary Enderton4P' : forall m n p mp np, NaturalNumber m -> NaturalNumber n ->\n  NaturalNumber p -> Prod_w m p mp -> Prod_w n p np -> mp = np -> ~Empty p -> m = n.\nProof.\n  intros m n p mp np Hm Hn Hp Hmp Hnp H Hne. omga. lt_w.\n  ordpair m n. rename x into mn. rename H0 into Hmn.\n  ordpair n m. rename x into nm. rename H0 into Hnm.\n  destruct (Trichotomous_w omga lt Homga Hlt m n mn nm) as [P | [P | P]];\n  try assumption; try apply Homga; try assumption; destruct P as [P0 [P1 P2]].\n  - assert (P : In m n).\n    { apply Hlt in P0. destruct P0 as [m' [n' [Hmn' [_ [_ P0]]]]].\n      assert (T : m = m' /\\ n = n').\n      { apply (Enderton3A m n m' n' mn mn Hmn Hmn'); trivial. }\n      replace m' with m in *; replace n' with n in *; try apply T; assumption. }\n    assert (Q : In mp np).\n    { apply (Enderton4N' m n p mp np); try assumption. }\n    rewrite H in Q. destruct (Enderton4Lb np); try assumption.\n    apply (Prod_NaturalNumber n p); assumption.\n  - assumption.\n  - assert (P : In n m).\n    { apply Hlt in P2. destruct P2 as [n' [m' [Hnm' [_ [_ P2]]]]].\n      assert (T : n = n' /\\ m = m').\n      { apply (Enderton3A n m n' m' nm nm Hnm Hnm'); trivial. }\n      replace m' with m in *; replace n' with n in *; try apply T; assumption. }\n    assert (Q : In np mp).\n    { apply (Enderton4N' n m p np mp); try assumption. }\n    rewrite H in Q. destruct (Enderton4Lb np); try assumption.\n    apply (Prod_NaturalNumber n p); assumption.\nQed.\n\nDefinition LeastElt (a A : set) : Prop :=\n  In a A /\\ forall n, In n A -> In_ a n.\n\nTheorem Well_Ordering_of_w: forall A omga, Nats omga -> Subset A omga ->\n  ~ Empty A -> exists m, LeastElt m A.\nProof.\n  intros A omga Homga HA. apply ContrapositiveLaw.\n  intros C C'. apply C'. lt_w.\n  build_set set (fun (A c m : set) => forall n, In n m -> ~ In n A) A omga.\n  rename x into B. rename H into HB. intros a Ha.\n  apply HA in Ha as Ha'. replace omga with B in Ha'. apply HB in Ha'.\n  apply C. exists a. split; try assumption.\n  intros n. apply ContrapositiveLaw. intros H C0.\n  destruct Ha' as [_ Ha']. apply (Ha' n); try assumption.\n  ordpair n a. rename x into na. rename H0 into Hna.\n  ordpair a n. rename x into an. rename H0 into Han.\n  destruct (Trichotomous_w omga lt Homga Hlt n a na an) as [P | [P | P]];\n  try assumption; try apply HA; try assumption;\n  destruct P as [P0 [P1 P2]].\n  - apply Hlt in P0. destruct P0 as [n' [a' [Hna' [Hn' [Ha0 P0]]]]].\n    assert (T : n = n' /\\ a = a').\n    { apply (Enderton3A n a n' a' na na Hna Hna'); trivial. }\n    replace n' with n in *; replace a' with a in *; try apply T; assumption.\n  - destruct H. right. symmetry. assumption.\n  - destruct H. left. apply Hlt in P2.\n    destruct P2 as [a' [n' [Han' [Ha0 [Hn' P2]]]]].\n    assert (T : a = a' /\\ n = n').\n    { apply (Enderton3A a n a' n' an an Han Han'); trivial. }\n    replace n' with n in *; replace a' with a in *; try apply T; assumption.\n  - apply Induction_Principle_for_Omega; try assumption; try split;\n    try (intros t Ht; apply HB, Ht).\n    + empty. exists x. split; try assumption. apply HB.\n      split; try apply Homga, Zero_NaturalNumber, H.\n      intros n Hn. destruct (H n). assumption.\n    + intros n n' Hn' Hn. apply HB in Hn. destruct Hn as [Hn IH].\n      apply HB. apply Homga in Hn.\n      split; try apply Homga, (Succ_NaturalNumber n n' Hn Hn').\n      intros m Hm. destruct Hn' as [Sn [HSn Hn']].\n      apply Hn' in Hm. destruct Hm as [Hm | Hm].\n      * apply IH. assumption.\n      * intros D. apply C. exists m. split; try assumption.\n        intros p Hp. replace m with n in *;\n        try (apply HSn in Hm; symmetry; assumption).\n        ordpair n p. rename x into np. rename H into Hnp.\n        ordpair p n. rename x into pn. rename H into Hpn.\n        destruct (Trichotomous_w omga lt Homga Hlt n p np pn) as [P | [P | P]];\n        try assumption; try apply HA; try assumption;\n        destruct P as [P0 [P1 P2]].\n        { left. apply Hlt in P0. destruct P0 as [n0 [p' [Hnp' [Hn0 [Hp' P0]]]]].\n        assert (T : n = n0 /\\ p = p').\n        { apply (Enderton3A n p n0 p' np np Hnp Hnp'); trivial. }\n          replace n0 with n in *; replace p' with p in *; try apply T; assumption. }\n        { right. assumption. }\n        { destruct (IH p); try assumption. apply Hlt in P2.\n          destruct P2 as [p' [n0 [Hpn' [Hn0 [Hp' P2]]]]].\n          assert (T : p = p' /\\ n = n0).\n          { apply (Enderton3A p n p' n0 pn pn Hpn Hpn'); trivial. }\n        replace n0 with n in *; replace p' with p in *; try apply T; assumption. }\nQed.\n\nCorollary Enderton4Q : forall omga, Nats omga ->\n  ~ exists f, FuncFromInto f omga omga /\\ forall n n' fn fn', NaturalNumber n ->\n  Succ n n' -> FunVal f n fn -> FunVal f n' fn' -> In fn' fn.\nProof.\n  intros omga Homga C. destruct C as [f [[Hf [Hdomf [ranf [Hranf Hsub]]]] H]].\n  destruct (Well_Ordering_of_w ranf omga); try assumption.\n  - intros C. zero. rename x into o. rename H0 into Ho.\n    assert (T : exists domf, Domain f domf /\\ In o domf).\n    { exists omga. split; try assumption. apply Homga, Zero_NaturalNumber, Ho. }\n    funval Hf T f o. rename x into fo. rename H0 into Hfo.\n    apply (C fo). apply Hranf. exists o. apply Hfo; assumption.\n  - rename x into fn. rename H0 into Hfn.\n    destruct Hfn as [I J]. apply Hranf in I.\n    destruct I as [n [nfn [Hnfn I]]].\n    succ n. rename x into n'. rename H0 into Hn'.\n    assert (T : exists domf, Domain f domf /\\ In n' domf).\n    { exists omga. split; try assumption.\n      apply Homga, (Succ_NaturalNumber n); try assumption.\n      apply Homga. apply Hdomf. exists fn, nfn. split; assumption. }\n    funval Hf T f n'. rename x into fn'. rename H0 into Hfn'.\n    destruct (J fn'); try (apply Hranf; exists n'; apply Hfn'; assumption).\n    + destruct (Enderton4Lb fn); try apply Homga, Hsub.\n      { apply Hranf. exists n, nfn. split; assumption. }\n      assert (P : NaturalNumber fn).\n      { apply Homga. apply Hsub. apply Hranf. exists n, nfn. split; assumption. }\n      apply (Enderton4F fn P fn'); try assumption.\n      apply (H n n' fn fn'); try assumption.\n      * apply Homga. apply Hdomf. exists fn, nfn. split; assumption.\n      * intros _ _. exists nfn. split; assumption.\n    + apply (Enderton4Lb fn); try apply Homga, Hsub.\n      { apply Hranf. exists n, nfn. split; assumption. }\n      apply (H n n' fn fn); try assumption.\n      * apply Homga. apply Hdomf. exists fn, nfn. split; assumption.\n      * intros _ _. exists nfn. split; assumption.\n      * replace fn with fn'. assumption.\nQed.\n\nTheorem Strong_Induction_Principle_for_w : forall omga A, Nats omga ->\n  Subset A omga ->\n  (forall n, In n omga -> (forall x, In x n -> In x A) -> In n A) ->\n  A = omga.\nProof.\n  intros omga A Homga HA H. lt_w. assert (P : A = omga \\/ A <> omga).\n  { apply REM. }\n  destruct P as [P | P]; try assumption.\n  minus omga A. rename x into wmA. rename H0 into HwmA.\n  destruct (Well_Ordering_of_w wmA omga) as [m Hm]; try assumption.\n  - intros x I. apply HwmA in I. apply I.\n  - intros C. apply P. apply SubsetSymmetric_iff_Equal. split; try assumption.\n    intros a Ha. assert (Q : In a A \\/ ~ In a A). { apply REM. }\n    destruct Q as [Q | Q]; try assumption.\n    destruct (C a). apply HwmA. split; assumption.\n  - destruct Hm as [I J]. apply HwmA in I as [I1 I2].\n    destruct I2. apply H; try assumption.\n    intros n Hn. assert (Q : In n A \\/ ~ In n A). { apply REM. }\n    destruct Q as [Q | Q]; try assumption.\n    destruct (J n) as [L | L].\n    + apply HwmA. split; try assumption.\n      apply (Enderton4G omga Homga m n I1 Hn).\n    + destruct (Enderton4Lb m); try apply Homga, I1. apply Homga in I1.\n      apply (Enderton4F m I1 n); assumption.\n    + destruct (Enderton4Lb m); try apply Homga, I1.\n      rewrite <- L in Hn. assumption.\nQed.\n\n(** Exercise 4-18 : Simplify: <_{-1}[{7,8}]. (The image of {7, 8} under the\n    inverse less-than relation. *)\n\nTheorem Exercise4_19 : forall m d, NaturalNumber m -> NaturalNumber d ->\n  ~ Empty d -> exists q r dq dqr, NaturalNumber q /\\ NaturalNumber r /\\\n  Prod_w d q dq /\\ Sum_w dq r dqr /\\ m = dqr /\\ Lt_w r d.\nProof.\n  intros m d Hm. generalize dependent d. omga. le_w. lt_w.\n  destruct Enderton4I as [A1 A2]. destruct Enderton4J as [M1 M2].\n  build_set set (fun (t c m : set) => forall d, NaturalNumber d ->\n    ~ Empty d -> exists q r dq dqr, NaturalNumber q /\\ NaturalNumber r /\\\n    Prod_w d q dq /\\ Sum_w dq r dqr /\\ m = dqr /\\ Lt_w r d) omga omga.\n  rename x into T. rename H into HT. apply HT.\n  replace T with omga; try apply Homga, Hm. symmetry. clear m Hm.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros t Ht; apply HT, Ht).\n  empty. rename x into o. rename H into Ho. exists o. split; try assumption.\n  - apply HT. split; try apply Homga, Zero_NaturalNumber, Ho.\n    intros d Hd Hne. exists o, o, o, o. split; try split;\n    try apply (Zero_NaturalNumber o Ho). repeat split.\n    + apply M1; assumption.\n    + apply A1; try assumption; try apply (Zero_NaturalNumber o Ho).\n    + ordpair o d. rename x into od. rename H into Hod.\n      exists lt, od. repeat (split; try assumption). apply Hlt.\n      exists o, d. repeat (split; try assumption);\n      try (apply Zero_NaturalNumber; assumption).\n      apply (Enderton4M o d); try assumption;\n      try apply Zero_NaturalNumber; try assumption. split.\n      * intros x Hx. destruct (Ho x). assumption.\n      * intros C. apply Hne. replace d with o. assumption.\n  - intros n n' Hn' Hn. apply HT in Hn. destruct Hn as [Hn IH].\n    apply HT. apply Homga in Hn.\n    split; try (apply Homga, (Succ_NaturalNumber n n' Hn Hn')). intros d Hd Hne.\n    destruct (IH d Hd Hne) as [q [r [dq [dqr [Hq [Hr [Hdq [Hdqr [Heq Hlt']]]]]]]]].\n    destruct Hlt' as [lt' [rd [Hlt' [Hrd Hrd']]]].\n    succ dqr. rename x into Sdqr. rename H into HSdqr.\n    succ r. rename x into r'. rename H into Hr'.\n    sum_w dq r' (Prod_NaturalNumber d q dq Hd Hq Hdq)\n      (Succ_NaturalNumber r r' Hr Hr').\n    rename x into dqr'. rename H into Hdqr'.\n    succ d. rename x into d'. rename H into Hd'.\n    ordpair r' d. rename x into r'd. rename H into Hr'd.\n    assert (P : In r'd le).\n    { ordpair r' d'. rename x into r'd'. rename H into Hr'd'.\n      apply (lt_w_succ_iff_le_w lt le r' d d' r'd' r'd); try assumption;\n      try apply (Succ_NaturalNumber r r' Hr Hr').\n      apply (Enderton4La lt r d r' d' rd r'd'); try assumption.\n      replace lt with lt'; try assumption; apply LessThan_w_Unique; assumption. }\n    apply Hle in P. destruct P as [r'0 [d0 [Hr'd0 [Hr'0 [Hd0 P]]]]].\n    assert (Q : r' = r'0 /\\ d = d0).\n    { apply (Enderton3A r' d r'0 d0 r'd r'd Hr'd Hr'd0). trivial. }\n    replace r'0 with r' in *; replace d0 with d in *; try apply Q.\n    clear r'0 d0 Hr'd0 Q. destruct P as [P | P].\n    + exists q, r', dq, dqr'. repeat (split; try assumption).\n      * apply (Succ_Unique n); try assumption. replace n with dqr.\n        replace dqr' with Sdqr; try assumption.\n        symmetry. apply (A2 dq r r' dqr); try assumption.\n        apply (Prod_NaturalNumber d q); try assumption.\n      * exists lt, r'd. repeat (split; try assumption).\n        apply Hlt. exists r', d. repeat (split; try assumption).\n    + succ q. rename x into q'. rename H into Hq'.\n      zero. rename x into o. rename H into Ho.\n      prod_w d q' Hd (Succ_NaturalNumber q q' Hq Hq').\n      rename x into dq'. rename H into Hdq'.\n      exists q', o, dq', dq'. repeat (split ; try assumption).\n      * apply (Succ_NaturalNumber q); assumption.\n      * apply Zero_NaturalNumber. assumption.\n      * apply A1; try assumption.\n        apply (Prod_NaturalNumber d q'); try assumption.\n        apply (Succ_NaturalNumber q); try assumption.\n      * sum_w d dq Hd (Prod_NaturalNumber d q dq Hd Hq Hdq).\n        rename x into ddq. rename H into Hddq.\n        sum_w dq d (Prod_NaturalNumber d q dq Hd Hq Hdq) Hd.\n        rename x into dqd. rename H into Hdqd.\n        replace dq' with ddq. replace ddq with dqd. replace n' with Sdqr.\n        replace dqd with dqr'.\n        { symmetry. apply (A2 dq r r' dqr); try assumption.\n          apply (Prod_NaturalNumber d q); assumption. }\n        { apply (Sum_w_Unique dq r'); try assumption;\n          try (apply (Prod_NaturalNumber d q); assumption).\n          replace r' with d. assumption. }\n        { apply (Succ_Unique dqr); try assumption. replace dqr with n. assumption. }\n        { apply (Enderton4K2 dq d); try assumption;\n          try (apply (Prod_NaturalNumber d q); assumption). }\n        { symmetry. apply (M2 d q dq q'); try assumption. }\n      * ordpair o d. rename x into od. rename H into Hod.\n        exists lt, od. repeat (split; try assumption). apply Hlt.\n        exists o, d. repeat (split; try assumption);\n        try (apply Zero_NaturalNumber; assumption).\n        apply (Enderton4M o d); try assumption;\n        try apply Zero_NaturalNumber; try assumption. split.\n        { intros x Hx. destruct (Ho x). assumption. }\n        { intros C. apply Hne. replace d with o. assumption. }\nQed.\n\nTheorem Exercise4_20 : forall A UA omga, ~ Empty A -> Union A UA -> Nats omga ->\n  Subset A omga -> UA = A -> A = omga.\nProof.\n  intros A UA omga Hne HUA Homga Hsub Heq. lt_w. le_w.\n  destruct (Well_Ordering_of_w A omga Homga Hsub Hne) as [m [H Hm]].\n  apply Induction_Principle_for_Omega; try assumption; try split.\n  - empty. exists x. split; try assumption. rename x into o. rename H0 into Ho.\n    ordpair o m. rename x into om. rename H0 into Hom.\n    ordpair m o. rename x into mo. rename H0 into Hmo.\n    apply Hsub in H as Hm'.\n    destruct (Trichotomous_w omga lt Homga Hlt o m om mo) as [P | [P | P]];\n    try assumption; try apply Homga, Zero_NaturalNumber, Ho;\n    destruct P as [P [Q R]].\n    + apply Hlt in P. destruct P as [o' [m' [Hom' [Ho' [_ P]]]]].\n      rewrite <- Heq. apply HUA. exists m. split; try assumption.\n      assert (T : o = o' /\\ m = m').\n      { apply (Enderton3A o m o' m' om om Hom Hom'). trivial. }\n      replace o' with o in *; replace m' with m in *; try apply T; assumption.\n    + rewrite Q. assumption.\n    + destruct (Ho m). apply Hlt in R. destruct R as [m' [o' [Hmo' [_ [Ho' R]]]]].\n      assert (T : m = m' /\\ o = o').\n      { apply (Enderton3A m o m' o' mo mo Hmo Hmo'). trivial. }\n      replace o' with o in *; replace m' with m in *; try apply T; assumption.\n  - intros n n' Hn' Hn. rename Hn into IH. apply Hsub in IH as Hn.\n    rewrite <- Heq in IH. apply HUA in IH. destruct IH as [p [Hp IH]].\n    succ p. rename x into p'. rename H0 into Hp'.\n    ordpair n p. rename x into np. rename H0 into Hnp.\n    ordpair n' p'. rename x into n'p'. rename H0 into Hn'p'.\n    ordpair n' p. rename x into n'p. rename H0 into Hn'p.\n    apply Homga in Hn. apply Hsub in IH as Hp0. apply Homga in Hp0.\n    assert (P : In n'p' lt).\n    { apply (Enderton4La lt n p n' p' np n'p' Hlt Hn Hp0 Hn' Hp' Hnp Hn'p').\n      apply Hlt. exists n, p. repeat (split; try assumption). }\n    assert (R : In n'p le).\n    { apply (lt_w_succ_iff_le_w lt le n' p p' n'p' n'p) ; try assumption.\n      apply (Succ_NaturalNumber n n' Hn Hn'). }\n    apply Hle in R. destruct R as [n'0 [p0 [Hn'p0 [_ [Hp'0 R]]]]].\n    assert (T : n' = n'0 /\\ p = p0).\n    { apply (Enderton3A n' p n'0 p0 n'p n'p Hn'p Hn'p0). trivial. }\n    replace n'0 with n' in *; replace p0 with p in *; try apply T.\n    destruct R as [R | R].\n    + rewrite <- Heq. apply HUA. exists p. split; assumption.\n    + replace n' with p; assumption.\nQed.    \n\nTheorem Exercise4_21 : forall n x, NaturalNumber n -> In x n -> ~ Subset n x.\nProof.\n  intros n m Hn Hm C. omga. assert (Hm' : NaturalNumber m).\n  { apply (Nats_sets_of_smaller_nats n m Hn) in Hm.\n    destruct Hm as [_ Hm]. destruct Hm as [lt [mn [Hlt [Hmn P]]]].\n    destruct (lt_relation_on_omega lt omga Hlt Homga mn P) as\n      [m' [n' [Hmn' [Hm' Hn']]]].\n    replace m with m'; try apply Homga, Hm'.\n    apply (Enderton3A m' n' m n mn mn Hmn' Hmn). trivial. }\n  apply (Enderton4M m n Hm' Hn); try assumption.\n  apply SubsetSymmetric_iff_Equal. split; try assumption.\n  intros x Hx. apply (Enderton4F n Hn m x); assumption.\nQed.\n\nTheorem Exercise4_22 : forall m p p' mp', NaturalNumber m -> NaturalNumber p ->\n  Succ p p' -> Sum_w m p' mp' -> In m mp'.\nProof.\n  intros m p p' mp' Hm Hp Hp' Hmp'. zero. rename x into o. rename H into Ho.\n  destruct (Zero_Leq_N o p' Ho (Succ_NaturalNumber p p' Hp Hp')) as [P | P].\n  - apply (Enderton4N o p' m m mp') in P; try assumption;\n    try apply (Zero_NaturalNumber o Ho);\n    try apply (Succ_NaturalNumber p); try assumption.\n    + apply A1_Commutative; assumption.\n    + sum_w p' m (Succ_NaturalNumber p p' Hp Hp') Hm.\n      rename x into p'm. rename H0 into Hp'm.\n      replace mp' with p'm; try assumption.\n      apply (Enderton4K2 p' m); try assumption.\n      apply (Succ_NaturalNumber p p'); assumption.\n  - destruct (Ho p). rewrite P. destruct Hp' as [Sp [HSp Hp']].\n    apply Hp'. right. apply HSp. trivial.\nQed.\n\nTheorem Exercise4_23 : forall m n, NaturalNumber m -> NaturalNumber n ->\n  Lt_w m n -> exists p p' mp', NaturalNumber p /\\ Succ p p' /\\ Sum_w m p' mp' /\\\n  mp' = n.\nProof.\n  intros m n Hm Hn. omga.\n  build_set set (fun (m c n : set) => Lt_w m n -> exists p p' mp',\n    NaturalNumber p /\\ Succ p p' /\\ Sum_w m p' mp' /\\ mp' = n) m omga.\n  rename x into A. rename H into HA. apply HA.\n  replace A with omga; try apply Homga; try assumption; try symmetry; clear n Hn.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros a Ha; apply HA, Ha).\n  - empty. rename H into Ho. rename x into o. exists o. split; try assumption.\n    apply HA. split; try apply Homga, Zero_NaturalNumber, Ho.\n    intros Hmo. destruct (Ho m). destruct Hmo as [lt [mo [Hlt [Hmn H]]]].\n    apply Hlt in H. destruct H as [m' [o' [Hmo' [Hm' [Ho' H]]]]].\n    assert (T : m = m' /\\ o = o').\n    { apply (Enderton3A m o m' o' mo mo Hmn Hmo'). trivial. }\n    replace m' with m in *; replace o' with o in *; try assumption; try apply T.\n  - intros n n' Hn' Hn. apply HA in Hn. destruct Hn as [Hn IH].\n    apply Homga in Hn. apply HA.\n    split; try apply Homga, (Succ_NaturalNumber n n' Hn Hn').\n    intros H. destruct H as [lt [mn' [Hlt [Hmn' H]]]].\n    Check lt_w_succ_iff_le_w. ordpair m n. rename x into mn. rename H0 into Hmn. le_w.\n    apply (lt_w_succ_iff_le_w lt le m n n' mn' mn) in H; try assumption.\n    apply Hle in H. destruct H as [m0 [n0 [Hmn0 [Hm0 [Hn0 H]]]]].\n    assert (T : m = m0 /\\ n = n0).\n    { apply (Enderton3A m n m0 n0 mn mn Hmn Hmn0). trivial. }\n    replace m0 with m in *; replace n0 with n in *; try apply T.\n    clear T m0 n0. destruct H as [H | H].\n    + assert (T : Lt_w m n).\n      { exists lt, mn. repeat (split; try assumption). apply Hlt. exists m, n.\n        repeat (split; try assumption). }\n      apply IH in T. destruct T as [p [p' [mp' [Hp [Hp' [Hmp' T]]]]]].\n      succ mp'. rename x into Smp'. rename H0 into HSmp'.\n      succ p'. rename x into Sp'. rename H0 into HSp'.\n      exists p', Sp', Smp'. repeat (split; try assumption).\n      * apply (Succ_NaturalNumber p p' Hp Hp').\n      * sum_w m Sp' Hm (Succ_NaturalNumber p' Sp'\n          (Succ_NaturalNumber p p' Hp Hp') HSp').\n        rename x into mSp'. rename H0 into HmSp'.\n        replace Smp' with mSp'; try assumption.\n        destruct Enderton4I as [A1 A2]. apply (A2 m p' Sp' mp'); try assumption.\n        apply (Succ_NaturalNumber p p' Hp Hp').\n      * apply (Succ_Unique mp'); try assumption. replace mp' with n. assumption.\n    + zero. rename x into o. rename H0 into Ho.\n      succ o. rename x into o'. rename H0 into Ho'.\n      sum_w m o' Hm (Succ_NaturalNumber o o' (Zero_NaturalNumber o Ho) Ho').\n      rename x into mo'. rename H0 into Hmo'.\n      exists o, o', mo'. repeat (split; try assumption).\n      * apply Zero_NaturalNumber. assumption.\n      * sum_w m o Hm (Zero_NaturalNumber o Ho). rename x into mo. rename H0 into Hmo.\n        destruct Enderton4I as [A1 A2]. apply (A2 m o o' mo); try assumption;\n        try apply Zero_NaturalNumber, Ho. replace mo with n; try assumption.\n        replace mo with m; try (symmetry; assumption).\n        apply (Sum_w_Unique m o); try assumption; try apply (Zero_NaturalNumber o Ho).\n        apply A1; assumption.\nQed.\n\nTheorem Exercise4_24 : forall m n p q mn pq, NaturalNumber m ->\n  NaturalNumber n -> NaturalNumber p -> NaturalNumber q -> Sum_w m n mn ->\n  Sum_w p q pq -> mn = pq -> In m p <-> In q n.\nProof.\n  intros m n p q mn pq Hm. generalize dependent pq. generalize dependent mn.\n  generalize dependent q. generalize dependent p. generalize dependent n. omga.\n  build_set set (fun (t c m : set) => forall n p q mn pq, NaturalNumber n ->\n    NaturalNumber p -> NaturalNumber q -> Sum_w m n mn -> Sum_w p q pq ->\n    mn = pq -> In m p <-> In q n) omga omga.\n  rename x into A. rename H into HA. apply HA.\n  replace A with omga; try apply Homga,Hm. clear m Hm. symmetry.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros t Ht; apply HA, Ht).\n  - zero. rename x into o. rename H into Ho. exists o. split; try assumption.\n    apply HA. split; try apply Homga, Zero_NaturalNumber, Ho.\n    intros n p q on pq Hn Hp Hq Hon Hpq H. split; intros I.\n    + replace n with pq. \n      * sum_w o q (Zero_NaturalNumber o Ho) Hq. rename x into oq.\n        rename H0 into Hoq. replace q with oq.\n        apply (Enderton4N o p q oq pq (Zero_NaturalNumber o Ho) Hp Hq Hoq Hpq) in I.\n        assumption. apply (Sum_w_Unique o q); try assumption;\n        try apply Zero_NaturalNumber, Ho. apply A1_Commutative; assumption.\n      * transitivity on; try (symmetry; assumption).\n        apply (Sum_w_Unique o n); try assumption; try apply Zero_NaturalNumber, Ho.\n        apply A1_Commutative; assumption.\n    + lt_w. ordpair o p. rename x into op. rename H0 into Hop.\n      ordpair p o. rename x into po. rename H0 into Hpo.\n      destruct (Trichotomous_w omga lt Homga Hlt o p op po) as [P | [P | P]];\n      try assumption; try (apply Homga; try apply Hp; apply Zero_NaturalNumber, Ho);\n      try destruct P as [P0 [P1 P2]].\n      * apply Hlt in P0. destruct P0 as [o' [p' [Hop' [_ [_ P0]]]]].\n        assert (T : o = o' /\\ p = p').\n        { apply (Enderton3A o p o' p' op op Hop Hop'); trivial. }\n        replace o' with o in *; replace p' with p in *; try apply T; assumption.\n      * destruct (Enderton4Lb q Hq). replace n with q in I; try assumption.\n        symmetry. transitivity on. apply (Sum_w_Unique o n); try assumption.\n        apply (Zero_NaturalNumber o Ho). apply A1_Commutative; assumption.\n        transitivity pq; try assumption. apply (Sum_w_Unique p q); try assumption.\n        apply A1_Commutative; try assumption. rewrite <- P1. assumption.\n      * destruct (Ho p). apply Hlt in P2.\n        destruct P2 as [p' [o' [Hpo' [_ [_ P2]]]]].\n        assert (T : p = p' /\\ o = o').\n        { apply (Enderton3A p o p' o' po po Hpo Hpo'). trivial. }\n        replace p' with p in *; replace o' with o in *; try apply T; assumption.\n  - intros m m' Hm' Hm. apply HA in Hm. destruct Hm as [Hm IH].\n    apply Homga in Hm. apply HA.\n    split; try apply Homga, (Succ_NaturalNumber m m' Hm Hm').\n    intros n p q m'n pq Hn Hp Hq Hm'n Hpq H. split; intros I.\n    + sum_w m n Hm Hn. rename x into mn. rename H0 into Hmn.\n      rename p into p'. rename Hp into Hp'. rename Hpq into Hp'q. rename pq into p'q.\n      destruct (Enderton4C p' Hp') as [p [Hp Hp'0]];\n      try (intros C; destruct (C m'); try assumption).\n      sum_w p q Hp Hq. rename x into pq. rename H0 into Hpq.\n      apply (IH n p q mn pq Hn Hp Hq Hmn Hpq).\n      * succ mn. rename x into Smn. rename H0 into HSmn.\n        union Smn. rename x into USmn. rename H0 into HUSmn.\n        succ pq. rename x into Spq. rename H0 into HSpq.\n        union Spq. rename x into USpq. rename H0 into HUSpq.\n        apply (Union_Unique Smn).\n        { replace mn with USmn; try assumption.\n          apply (Enderton4E mn Smn); try assumption.\n          apply (Enderton4F). apply (Sum_NaturalNumber m n); assumption. }\n        { replace pq with USpq. replace Smn with Spq; try assumption.\n          - replace Spq with p'q. replace Smn with m'n; try (symmetry; assumption).\n            apply (A2_Commutative m n m' mn); assumption.\n            apply (A2_Commutative p q p' pq); assumption.\n          - apply (Enderton4E pq Spq); try assumption.\n            apply (Enderton4F). apply (Sum_NaturalNumber p q); assumption. }\n      * lt_w. ordpair m p. rename x into mp. rename H0 into Hmp.\n        ordpair m' p'. rename x into m'p'. rename H0 into Hm'p'.\n        assert (T : In m'p' lt).\n        { apply Hlt. exists m', p'. repeat (split; try assumption).\n          apply (Succ_NaturalNumber m m' Hm Hm'). }\n        apply (Enderton4La lt m p m' p' mp m'p') in T; try assumption.\n        apply Hlt in T. destruct T as [m0 [p0 [Hmp0 [_ [_ T]]]]].\n        assert (T0 : m = m0 /\\ p = p0).\n        { apply (Enderton3A m p m0 p0 mp mp Hmp Hmp0); trivial. }\n        replace m0 with m in *; replace p0 with p in *; try apply T0; assumption.\n    + succ n. rename x into n'. rename H0 into Hn'.\n      assert (P : In q n').\n      { apply (Enderton4F n' (Succ_NaturalNumber n n' Hn Hn') n q); try assumption.\n        destruct Hn' as [Sn [HSn Hn']]. apply Hn'. right. apply HSn. trivial. }\n      sum_w m n' Hm (Succ_NaturalNumber n n' Hn Hn'). rename x into mn'.\n      rename H0 into Hmn'. assert (Q : mn' = pq).\n      { sum_w m n Hm Hn. rename x into mn. rename H0 into Hmn.\n        succ mn. rename x into Smn. rename H0 into HSmn.\n        destruct (Enderton4I) as [A1 A2].\n        transitivity Smn. try (apply (A2 m n n' mn); assumption).\n        transitivity m'n; try assumption. symmetry.\n        apply (A2_Commutative m n m' mn); assumption. }\n      apply (IH n' p q mn' pq (Succ_NaturalNumber n n' Hn Hn') Hp Hq Hmn' Hpq Q) in P.\n      ordpair m p. rename x into mp. rename H0 into Hmp.\n      succ p. rename x into p'. rename H0 into Hp'.\n      ordpair m' p'. rename x into m'p'. rename H0 into Hm'p'. lt_w. le_w.\n      assert (R : In mp lt).\n      { apply Hlt. exists m, p. repeat (split; try assumption). }\n      apply (Enderton4La lt m p m' p' mp m'p') in R; try assumption.\n      ordpair m' p. rename x into m'p. rename H0 into Hm'p.\n      apply (lt_w_succ_iff_le_w lt le m' p p' m'p' m'p) in R; try assumption;\n      try (apply (Succ_NaturalNumber m); assumption).\n      apply Hle in R. destruct R as [m'0 [p0 [Hm'p0 [Hm'0 [_ R]]]]].\n      assert (T : m' = m'0 /\\ p = p0).\n      { apply (Enderton3A m' p m'0 p0 m'p m'p Hm'p Hm'p0). trivial. }\n      replace m'0 with m' in *; replace p0 with p in *; try apply T.\n      destruct R as [R | R]; try assumption.\n      destruct (Enderton4Lb n); try assumption.\n      replace q with n in I; try assumption. Check Enderton4P.\n      apply (Enderton4P n q p m'n pq); try assumption.\n      * replace p with m'. sum_w n m' Hn (Succ_NaturalNumber m m' Hm Hm').\n        rename x into nm'. rename H0 into Hnm'.\n        replace m'n with nm'; try assumption.\n        apply (Enderton4K2 n m'); try assumption.\n      * sum_w q p Hq Hp. rename x into qp. rename H0 into Hqp.\n        replace pq with qp; try assumption.\n        apply (Enderton4K2 q p); try assumption.\nQed.\n\nTheorem Exercise4_25 : forall m n p q mq np mp nq mqnp mpnq,\n  NaturalNumber m -> NaturalNumber n -> NaturalNumber p -> NaturalNumber q ->\n  Prod_w m q mq -> Prod_w n p np -> Prod_w m p mp -> Prod_w n q nq -> Sum_w mq np mqnp ->\n  Sum_w mp nq mpnq -> In mqnp mpnq.\nAdmitted.\n\nTheorem Exercise4_26 : forall n n' omga f ranf, NaturalNumber n -> Succ n n' ->\n  Nats omga -> FuncFromInto f n' omga -> Range f ranf -> exists x, In x ranf /\\\n  forall x', In x' ranf -> In_ x' x.\nProof.\n  intros n n' omga f ranf Hn Hn' Homga. generalize dependent ranf.\n  generalize dependent f. generalize dependent n'.\n  build_set set (fun (t omga n : set) => forall n', Succ n n' ->\n    forall f ranf, FuncFromInto f n' omga -> Range f ranf ->\n    exists x, In x ranf /\\ (forall x' : set, In x' ranf -> In_ x' x)) omga omga.\n  rename x into A. rename H into HA. apply HA.\n  replace A with omga; try apply Homga, Hn. symmetry. clear n Hn.\n  apply Induction_Principle_for_Omega; try assumption; try split;\n  try (intros t Ht; apply HA, Ht).\n  - zero. rename x into o. rename H into Ho. exists o. split; try assumption.\n    apply HA. split; try apply Homga, Zero_NaturalNumber, Ho.\n    intros o' Ho' f ranf [Hf [Hdomf [ranf' [Hranf' Hsub]]]] Hranf.\n    replace ranf' with ranf; try apply (Range_Unique f); try assumption.\n    assert (T : exists domf, Domain f domf /\\ In o domf).\n    { exists o'. split; try assumption. destruct Ho' as [So [HSo Ho']].\n      apply Ho'. right. apply HSo. trivial. }\n    funval Hf T f o. rename x into fo. rename H into Hfo. exists fo. split.\n    + apply Hranf. exists o. apply Hfo; assumption.\n    + intros fo' Hfo'. right. apply (FunVal_Unique f o); try assumption.\n      intros _ _. apply Hranf in Hfo'. destruct Hfo' as [o0 [ofo' [Hofo' H]]].\n      exists ofo'. split; try assumption. replace o with o0; try assumption.\n      assert (P : In o o').\n      { apply Hdomf. exists fo. apply Hfo; assumption. }\n      assert (Q : In o0 o').\n      { apply Hdomf. exists fo', ofo'. split; try assumption. }\n      destruct Ho' as [So [HSo Ho']]. apply Ho' in P. apply Ho' in Q.\n      destruct P as [P | P]; destruct Q as [Q | Q].\n      * destruct (Ho o). assumption.\n      * destruct (Ho o). assumption.\n      * destruct (Ho o0). assumption.\n      * apply HSo in Q. assumption.\n  - intros n n' Hn' Hn. apply HA in Hn. destruct Hn as [Hn IH].\n    apply HA. apply Homga in Hn.\n    split; try apply Homga, (Succ_NaturalNumber n n' Hn Hn').\n    intros n'' Hn'' f ranf [Hf [Hdomf [ranf' [Hranf' Hsub]]]] Hranf.\n    replace ranf' with ranf in *; try apply (Range_Unique f); try assumption.\n    clear ranf' Hranf'. restrict f n'. rename x into fln'. rename H into Hfln'.\n    range fln'. rename x into ranfln'. rename H into Hranfln'.\n    destruct (IH n' Hn' fln' ranfln'); try assumption.\n    { split; try split.\n      - intros xy H. apply Hfln' in H. destruct H as [x [y [Hxy _]]].\n        exists x, y. assumption.\n      - intros x y z xy xz Hxy Hxz H I. apply Hfln' in H. apply Hfln' in I.\n        destruct H as [x' [y' [Hxy' [H _]]]].\n        assert (T : x = x' /\\ y = y').\n        { apply (Enderton3A x y x' y' xy xy Hxy Hxy'); trivial. }\n        replace x' with x in *; replace y' with y in *; try apply T.\n        clear x' y' T Hxy'. destruct I as [x' [z' [Hxz' [I _]]]].\n        assert (T : x = x' /\\ z = z').\n        { apply (Enderton3A x z x' z' xz xz Hxz Hxz'); trivial. }\n        replace x' with x in *; replace z' with z in *; try apply T.\n        destruct Hf as [_ Hf]. apply (Hf x y z xy xz Hxy Hxz H I).\n      - intros x. split; intros H.\n        + assert (I : In x n'').\n          { destruct Hn'' as [Sn' [HSn' Hn'']]. apply Hn''. left. assumption. }\n          apply Hdomf in I. destruct I as [y [xy [Hxy I]]].\n          exists y, xy. split; try assumption. apply Hfln'.\n          exists x, y. split; try assumption. split; assumption.\n        + destruct H as [y [xy [Hxy H]]]. apply Hfln' in H.\n          destruct H as [x' [y' [Hxy' [H I]]]].\n          replace x with x'; try assumption.\n          apply (Enderton3A x' y' x y xy xy Hxy' Hxy); trivial.\n      - exists ranfln'. split; try assumption. intros y H.\n        apply Hranfln' in H. destruct H as [x [xy [Hxy H]]].\n        apply Hfln' in H. destruct H as [x' [y' [Hxy' [H I]]]].\n        apply Hsub. apply Hranf. exists x, xy. split; assumption. }\n    destruct H as [H Hmax]. rename x into m.\n    assert (T : exists domf, Domain f domf /\\ In n' domf).\n    { exists n''. split; try assumption. destruct Hn'' as [Sn' [HSn' Hn'']].\n      apply Hn''. right. apply HSn'. trivial. }\n    funval Hf T f n'. rename x into fn'. rename H0 into Hfn'.\n    ordpair m fn'. rename x into mfn'. rename H0 into Hmfn'.\n    ordpair fn' m. rename x into fn'm. rename H0 into Hfn'm. lt_w.\n    destruct Hn'' as [Sn' [HSn' Hn'']].\n    destruct (Trichotomous_w omga lt Homga Hlt m fn' mfn' fn'm) as [P | [P | P]];\n    try assumption; try destruct P as [P [Q R]].\n    { apply Hsub. apply Hranfln' in H. destruct H as [x [xy [Hxy H]]].\n      apply Hranf. exists x, xy. split; try assumption. apply Hfln' in H.\n      destruct H as [x' [y' [Hxy' [H _]]]]. assumption. }\n    { apply Hsub. apply Hranf. exists n'. apply Hfn'; assumption. }\n    + exists fn'. split.\n      { apply Hranf. exists n'. apply Hfn'; assumption. }\n      intros fp Hfp. apply Hranf in Hfp. destruct Hfp as [p [pfp [Hpfp Hfp]]].\n      assert (T0 : In p n'').\n      { apply Hdomf. exists fp, pfp. split; assumption. }\n      apply Hn'' in T0. destruct T0 as [T0 | T0].\n      * left. destruct (Hmax fp) as [T1 | T1].\n        { apply Hranfln'. exists p, pfp. split; try assumption.\n          apply Hfln'. exists p, fp. repeat (split; try assumption). }\n        { assert (S : NaturalNumber fn').\n          { apply Homga. apply Hsub. apply Hranf. exists n'. apply Hfn'; assumption. }\n          apply (Enderton4F fn' S m fp); try assumption.\n          apply Hlt in P. destruct P as [m' [fn'' [Hmfn'' [P0 [P1 P]]]]].\n          assert (U : m = m' /\\ fn' = fn'').\n          { apply (Enderton3A m fn' m' fn'' mfn' mfn' Hmfn' Hmfn''). trivial. }\n          replace m' with m in *; replace fn'' with fn' in *; try apply U; assumption. }\n        { apply Hlt in P. replace fp with m.\n          destruct P as [m' [fn'' [Hmfn'' [P0 [P1 P]]]]].\n          assert (S : m = m' /\\ fn' = fn'').\n          { apply (Enderton3A m fn' m' fn'' mfn' mfn' Hmfn' Hmfn''). trivial. }\n          replace m' with m in *; replace fn'' with fn' in *; try apply S; assumption. }\n      * right. apply (FunVal_Unique f p fp fn'); try assumption.\n        { exists n''. split; try assumption. apply Hdomf. exists fp, pfp.\n          split; assumption. }\n        { intros _ _. exists pfp. split; assumption. }\n        { replace p with n'; try assumption. apply HSn' in T0. symmetry. apply T0. }\n    + exists fn'. split.\n      { apply Hranf. exists n'. apply Hfn'; assumption. }\n      intros fp Hfp. apply Hranf in Hfp. destruct Hfp as [p [pfp [Hpfp Hfp]]].\n      assert (T0 : In p n'').\n      { apply Hdomf. exists fp, pfp. split; assumption. }\n      apply Hn'' in T0. destruct T0 as [T0 | T0].\n      * replace fn' with m. apply Hmax. apply Hranfln'. exists p, pfp.\n        split; try assumption. apply Hfln'.\n        exists p, fp. repeat (split; try assumption).\n      * right. apply HSn' in T0. apply (FunVal_Unique f n'); try assumption.\n        intros _ _. exists pfp. replace n' with p. split; assumption.\n    + exists m. split.\n      { apply Hranf. apply Hranfln' in H. destruct H as [x [xy [Hxy H]]].\n        exists x, xy. split; try assumption. apply Hfln' in H.\n        destruct H as [_ [_  [_ [H _]]]]. assumption. }\n      intros fp Hfp. apply Hranf in Hfp. destruct Hfp as [p [pfp [Hpfp Hfp]]].\n      assert (T0 : In p n'').\n      { apply Hdomf. exists fp, pfp. split; assumption. }\n      apply Hn'' in T0. destruct T0 as [T0 | T0].\n      * apply Hmax. apply Hranfln'. exists p, pfp. split; try assumption.\n        apply Hfln'. exists p, fp. repeat (split; try assumption).\n      * left. apply Hlt in R. destruct R as [fn'' [m' [Hfn'm' [R0 [R1 R]]]]].\n        assert (T1 : fn' = fn'' /\\ m = m').\n        { apply (Enderton3A fn' m fn'' m' fn'm fn'm Hfn'm Hfn'm'); trivial. }\n        replace fn'' with fn' in *; replace m' with m in *; try apply T1.\n        replace fp with fn'; try assumption.\n        apply (FunVal_Unique f n'); try assumption.\n        apply HSn' in T0. replace n' with p. intros _ _.\n        exists pfp. split; assumption.\nQed.\n\nTheorem Exercise4_27 : forall A G f1 f2 omga, Func G -> Nats omga ->\n  FuncFromInto f1 omga A -> FuncFromInto f2 omga A ->\n  (forall n f1ln f2ln domG f1n f2n Gf1ln Gf2ln, NaturalNumber n ->\n  Restriction f1 n f1ln -> Restriction f2 n f2ln -> Domain G domG ->\n  FunVal f1 n f1n -> FunVal f2 n f2n -> FunVal G f1ln Gf1ln ->\n  FunVal G f2ln Gf2ln -> In f1ln domG /\\ In f2ln domG /\\ f1n = Gf1ln /\\\n  f2n = Gf2ln) -> f1 = f2.\nAdmitted.\n\n(** Exercise 4-28 : Rewrite the proof of Theorem 4G using, in place of induction,\n    the well-ordering of omega. TODO *)\n\n(** Exercise 4-29 : Write an expression for the set named 4 using only the\n    empty set symbol, left and right curly braces, and commas. *)\n\n(** Exercise 4-30 : What is U4? What is N4? *)\n\n(** Exercise 4-31 : What is UU7? *)\n\n(** Exercise 4-32 :\n    \n    a) Let A = {1}. Calculate A+ and U(A+).\n    b) What is U({2}+)?  *)\n\n(** Exercise 4-33 : Which of the following sets are transitive? (For each set S\n    that is not transitive, specify a member of US not belonging to S.)\n    \n    a) {0, 1, {1}}\n    b) {1}\n    c) <0, 1> *)\n\n(** Exercise 4-34 : Find a suitable a, b, etc. making each of the following sets\n    transitive. \n    \n    a) { {{0}}, a, b }\n    b) { {{{0}}}, c, d, e} *)\n\n(** Exercise 4-35 : Let S be the set <1, 0>. \n\n    a) Find a transitive set T1 for which S is a subset of T1.\n    b) Find a transitive set T2 for which S is a member of T2. *)\n\n(** Exercise 4-36 : By the Recursion Theorem, there is a function\n    h : omega -> omega for which h(0) = 3 and h(n+) = 2 * h(n). What is h(4)? *)\n\n\nDefinition Has_n_Elts (S n : set) : Prop := NaturalNumber n /\\\n  exists f, FuncFromOnto f n S /\\ OneToOne f.\n\nDefinition Disjoint (A B : set) : Prop :=\n  exists AnB, BinaryIntersect A B AnB /\\ Empty AnB.\n\nTheorem Exercise4_36a : forall A B m n AuB mn, NaturalNumber m ->\n  NaturalNumber n -> Has_n_Elts A m -> Has_n_Elts B n -> BinaryUnion A B AuB ->\n  Sum_w m n mn -> Disjoint A B -> Has_n_Elts AuB mn.\nAdmitted.\n\nTheorem Exercise4_37b : forall A B m n AxB mn, NaturalNumber m ->\n  NaturalNumber n -> Has_n_Elts A m -> Has_n_Elts B n -> Prod A B AxB ->\n  Prod_w m n mn -> Has_n_Elts AxB mn.\nAdmitted.\n\n(** Exercise 4-38 : Assume that h is the function from omega into omega for which\n    h(0) = 1 and h(n+) = h(n) + 3 (and note that h exists by the Recursion\n    Theorem). Give an explicit (non-recursive) expression for h(n). *)\n\n(** Exercise 4-39 : Assume that h is the function from omega into omega for which\n    h(0) = 1 and h(n+) = h(n) + (2 * n) + 1 (and note that h exists by the\n    Recursion Theorem). Give an explicit (non-recursive) expression for h(n). *)\n\n(** Exercise 4-40 : Assume that h is the function from omega into omega defined\n    by h(n) = 5 * n + 2 (and note that h exists by the Recursion Theorem).\n    Express h(n+) in terms of h(n) as simply as possible.  *)", "meta": {"author": "stp59", "repo": "math-texts", "sha": "dcf36696cbd7526a35020aa32809e6e7d790d0da", "save_path": "github-repos/coq/stp59-math-texts", "path": "github-repos/coq/stp59-math-texts/math-texts-dcf36696cbd7526a35020aa32809e6e7d790d0da/enderton/NaturalNumbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6757442265230575}}
{"text": "(* An example for a generic option type. *)\nInductive Nullable (T : Type) : Type :=\n  | Some(t: T)\n  | None.\n\n(* An example for a generic either type. *)\nInductive Either (L R: Type) : Type :=\n  | Left(val: L)\n  | Right(val: R).\n\n(* TODO How to match over comparisons? *)\n(* TODO What's a Prop? *)\n(* TODO digest more of https://clarksmr.github.io/sf-lectures/textbook/lf/toc.html*)\n(* TODO continue with 23 https://www.youtube.com/watch?v=VYFTph2izIs&list=PLre5AT9JnKShFK9l9HYzkZugkJSsXioFs&index=23*)\nModule Allenalgebra.\n  (* TODO how to model product types? *)\n  (* TODO how to assert that from <= to? *)\n  Inductive AllenInterval : Type :=\n    AllenIntervalValue(from : nat) (to : nat).\n  \n  Inductive AllenPoint : Type := \n    AllenPointValue(val: nat).\n    \n  Inductive IntervalQueryy : Type := \n    IntervalQueryyVal(from to: nat).\n  (* TODO impl definitions for all the comments. *)\n  (* TODO given an interval query, provide the correct Allen result. *)\n  (* TODO impl allen over a query with an interval and a point. *)\n  (* TODO impl allen over a two points. *)\n  Inductive Allen : Type := \n(*\nA: |-----|\nB:           |-----|\na_l < b_l && a_l < b_r && a_r < b_l && a_r < b_r\n*)\n    | AllenPrecedes\n(*\nA:   |-----|\nB:         |-----|\na_l < b_l && a_l < b_r && a_r == b_l && a_r < b_r\n*)\n    | AllenMeets\n(*\nA:     |-----|\nB:       |-----|\na_l < b_l && a_l < b_r && a_r > b_l && a_r < b_r\n*)\n    | AllenOverlaps\n(*\nA:     |-----|\nB:       |---|\na_l < b_l && a_l < b_r && a_r > b_l && a_r == b_r\n*)\n    | AllenFinishedBy\n(*\nA:     |-----|\nB:       |-|\na_l < b_l && a_l < b_r && a_r > b_l && a_r > b_r\n*)\n    | AllenContains\n(*\nA:     |---|\nB:     |-----|\na_l == b_l && a_l < b_r && a_r > b_l && a_r < b_r\n*)\n    | AllenStarts\n(*\nA:     |-----|\nB:     |-----|\na_l == b_l && a_l == b_r && a_r == b_l && a_r == b_r\n*)\n    | AllenEquals\n(*\nA:     |-----|\nB:     |---|\na_l == b_l && a_l < b_r && a_r > b_l && a_r > b_r\n*)\n    | AllenStartedBy\n(*\nA:       |-|\nB:     |-----|\na_l > b_l && a_l > b_r && a_r < b_l && a_r < b_r\n*)\n    | AllenDuring\n(*\nA:       |---|\nB:     |-----|\na_l > b_l && a_l < b_r && a_r > b_l && a_r == b_r\n*)\n    | AllenFinishes\n(*\nA:       |-----|\nB:     |-----|\na_l > b_l && a_l < b_r && a_r > b_l && a_r > b_r\n*)\n    | AllenOverlappedBy\n(*\nA:         |-----|\nB:   |-----|\na_l > b_l && a_l == b_r && a_r > b_l && a_r > b_r\n*)\n    | AllenMetBy\n(*\nA:           |-----|\nB: |-----|\na_l > b_l && a_l > b_r && a_r > b_l && a_r > b_r\n*)\n    | AllenPrecededBy.\n \n  Definition is_preceded_by(a_l a_r: nat) (b_l b_r: nat) : bool :=\n    if (leb a_l b_l) then true\n    else false.\n  \nEnd Allenalgebra.\n", "meta": {"author": "modulovalue", "repo": "allens_coq", "sha": "932a0e5ac8511f5e1a96a94f44fbf36faf79c3ec", "save_path": "github-repos/coq/modulovalue-allens_coq", "path": "github-repos/coq/modulovalue-allens_coq/allens_coq-932a0e5ac8511f5e1a96a94f44fbf36faf79c3ec/allens_coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6757442122670032}}
{"text": "(* nat ⋈ N *)\n\nRequire Import HoTT Equiv_def Param_CComega Param_ind_parameters.\n\nRequire Import BinNat Nnat Vector Arith.Plus Omega ZArith.\n\nSet Universe Polymorphism.\n\nUnset Universe Minimization ToSet.\n\nLemma iter_op_succ : forall A (op:A->A->A),\n (forall x y z, op x (op y z) = op (op x y) z) ->\n forall p a,\n Pos.iter_op op (Pos.succ p) a = op a (Pos.iter_op op p a).\nProof.\n induction p; simpl; intros; try reflexivity.\n rewrite X. apply IHp.\nDefined.\n\nFixpoint plus_assoc (n m p : nat) : n + (m + p) = n + m + p.\n induction n. cbn. reflexivity.\n cbn. apply ap. apply plus_assoc.\nDefined. \n \nLemma inj_succ p : Pos.to_nat (Pos.succ p) = S (Pos.to_nat p).\nProof.\n unfold Pos.to_nat. rewrite iter_op_succ. reflexivity. \n apply plus_assoc.\nDefined.\n\nDefinition is_succ : forall p, {n:nat & Pos.to_nat p = S n}.\nProof.\n induction p using Pos.peano_rect.\n now exists 0.\n destruct IHp as (n,Hn). exists (S n). now rewrite inj_succ, Hn.\nDefined. \n\nTheorem Pos_id (n:nat) : n<>0 -> Pos.to_nat (Pos.of_nat n) = n.\nProof.\n induction n as [|n H]; trivial. now destruct 1.\n intros _. simpl Pos.of_nat. destruct n. reflexivity.\n rewrite inj_succ. f_equal. apply ap. now apply H.\nDefined.\n\nLemma of_nat_succ (n:nat) : Pos.of_succ_nat n = Pos.of_nat (S n).\nProof.\n induction n. reflexivity. simpl. apply ap. now rewrite IHn.\nDefined. \n\nTheorem id_succ (n:nat) : Pos.to_nat (Pos.of_succ_nat n) = S n.\nProof.\nrewrite of_nat_succ. now apply Pos_id.\nDefined.\n\nLemma inj (n m : nat) : Pos.of_succ_nat n = Pos.of_succ_nat m -> n = m.\nProof.\n intro H. apply (ap Pos.to_nat) in H. rewrite !id_succ in H.\n inversion H. reflexivity. \nDefined.\n\nTheorem Pos2Nat_id p : Pos.of_nat (Pos.to_nat p) = p.\nProof.\n induction p using Pos.peano_rect. reflexivity. \n rewrite inj_succ. rewrite <- (ap Pos.succ IHp).\n now destruct (is_succ p) as (n,->).\nDefined.\n\nLemma Pos2Nat_inj p q : Pos.to_nat p = Pos.to_nat q -> p = q.\nProof.\n intros H. now rewrite <- (Pos2Nat_id p), <- (Pos2Nat_id q), H.\nDefined.\n\nLemma N2Nat_id a : N.of_nat (N.to_nat a) = a.\nProof.\n  destruct a as [| p]; simpl. reflexivity.\n  destruct (is_succ p) as [n H]. rewrite H. simpl. apply ap. \n  apply Pos2Nat_inj. rewrite H. apply id_succ.\nDefined.\n\nTheorem Pos_id_succ p : Pos.of_succ_nat (Pos.to_nat p) = Pos.succ p.\nProof.\nrewrite of_nat_succ, <- inj_succ. apply Pos2Nat_id.\nDefined.\n\nTheorem id_succ' (n:nat) : Pos.to_nat (Pos.of_succ_nat n) = S n.\nProof.\nrewrite of_nat_succ. apply Pos_id. intro H. inversion H.\nDefined.\n\nLemma Nat2N_id n : N.to_nat (N.of_nat n) = n.\nProof.\n induction n; simpl; try reflexivity. apply id_succ'.\nDefined. \n\nInstance IsEquiv_N_nat : IsEquiv N.of_nat.\nProof.\n  unshelve refine (isequiv_adjointify _ _ _ _).\n  - exact N.to_nat. \n  - cbn; intro. exact (Nat2N_id _).\n  - cbn; intro. exact (N2Nat_id _).\nDefined.\n\n\nInstance Equiv_N_nat : nat ≃ N.\n  refine (BuildEquiv _ _ N.of_nat _).  \nDefined.\n\nInstance Equiv_nat_N : N ≃ nat := Equiv_inverse _.\n\nInstance R_N : Rel N N := funToRel id. \n\n(* #[export] Hint Extern 0 (?f ?x = ?y ) => refine (Move_equiv Equiv_nat_N x y _) *)\n(*                                : typeclass_instances. *)\n\n(* #[export] Hint Extern 0 (?f ?x = ?y ) => refine (Move_equiv Equiv_N_nat x y _) *)\n(*                                : typeclass_instances. *)\n\nInstance R_N_nat : Rel N nat | 0 := funToRel Equiv_nat_N.\n \nInstance compat_N_nat : N ⋈ nat := Fun _ _ Equiv_nat_N.\n\nInstance R_nat_N : Rel nat N | 0 := funToRel Equiv_N_nat. \n\nInstance compat_nat_N : nat ⋈ N := Fun _ _ Equiv_N_nat.\n\n#[export] Hint Extern 0 (nat ≈ N) => refine compat_nat_N\n                               : typeclass_instances.\n\nEval compute in (↑ [ 1 ; 2 ; 3 ] : list N).\n\n", "meta": {"author": "CoqHott", "repo": "parametricity-a-la-carte", "sha": "55cd3b97b13f534f6b903931d67576d83b289cd6", "save_path": "github-repos/coq/CoqHott-parametricity-a-la-carte", "path": "github-repos/coq/CoqHott-parametricity-a-la-carte/parametricity-a-la-carte-55cd3b97b13f534f6b903931d67576d83b289cd6/theories/NatBinDefs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6757442111416645}}
{"text": "(* Rappel syntaxe Coq : les commentaires s'écrivent entre (* et *). *)\n\n(* TAPFA - Partie Coq - TP 2 *)\n\n(* Rappel de l'URL des supports de Cours :\n\n   https://pfitaxel.github.io/tapfa-coq-alectryon/ *)\n\n(* N'hésitez pas à solliciter votre encadrant de TP sur Discord\n   pour toute question. *)\n\n(* Pour évaluer les phrases dans Emacs+ProofGeneral :\n   - aller jusqu'au curseur en faisant \"C-c RET\" (<=> Ctrl+C Entrée)\n     ou \"C-c C-RET\"\n   - avancer/reculer d'un cran avec \"C-c C-n\" et \"C-c C-u\"\n   - et pour aller à la fin de la zone validée, faire \"C-c C-.\"\n\n  Pour évaluer les phrases dans l'éditeur en ligne,\n  utiliser les trois boutons adéquats (ou Alt+N, Alt+P, Alt+Entrée) *)\n\n(******************************************)\n(* Retour sur la logique propositionnelle *)\n(******************************************)\n\nSection PremieresTactiques.\n\n(* Dans cette section, supposons trois propositions A, B et C *)\nVariables A B C : Prop.\n\n(* On pourrait faire toutes nos preuves en écrivant des fonctions du\n   bon type, comme au TP 1, mais ça devient vite inhumain ; Coq\n   propose donc un mode interactif dans lequel il va nous aider à\n   construire les preuves étape par étape (d'où le nom d'assistant de\n   preuve). *)\n\nLemma ex0 : B -> B.\n(* au lieu de Lemma, on pourrait utiliser les synonymes Theorem,\nRemark, Corollary, Fact, Example *)\nProof.\n(* on démarre une preuve interactive *)\n(* on tape maintenant des tactiques qui vont modifier les sous buts à\nprouver jusqu'à ce qu'il n'en reste plus *)\nintros Hb.\n(* notre première tactique, on bouge l'hypothèse B et on lui donne le nom Hb *)\n(* Hb a pour type B cad que Hb est une preuve de B *)\napply Hb.\n(* notre deuxième tactique, on utilise B *)\nQed.\n(* Quod Erat Demonstrandum, CQFD en latin, on enregistre et vérifie la preuve *)\n\n(* en fait, ici Coq sait se débrouiller tout seul *)\nLemma ex0' : B -> B.\nProof. auto. Qed.\n\n(* refaire les preuves précédentes en utilisant les tactiques intros et apply *)\nLemma ex1 : A -> B -> A.\nProof.\n(* ... (à compléter) *)\nAdmitted.\n\nLemma ex2 : A -> B -> B.\nProof.\n(* ... (à compléter) *)\nAdmitted.\n\n(*\n  Pour ex3, on remarquera que le type de la 2eme hypothese introduite est\n  un type fonctionnel. Il est donc possible d'appliquer la fonction sur un\n  argument de type A pour obtenir un B.\n  En déduire 2 preuves différentes de ex3', en utilisant la tactique apply\n  une seule fois ou bien deux fois.\n  On notera (Print ex3_Vi) que le terme construit est le même.\n*)\nLemma ex3_V1 : A -> (A -> B) -> B.\nProof.\n(* ... (à compléter) *)\nAdmitted.\n\nLemma ex3_V2 : A -> (A -> B) -> B.\nProof.\n(* ... (à compléter) *)\nAdmitted.\n\nLemma ex4 : (A -> B) -> (B -> C) -> A -> C.\nProof.\n(* ... (à compléter) *)\nAdmitted.\n\nLemma ex5 : (A -> B) -> (A -> B -> C) -> A -> C.\nProof.\n(* ... (à compléter) *)\nAdmitted.\n\n(* en présence de plusieurs sous-buts, on peut utiliser des accolades\n   pour les délimiter *)\nLemma ex5' : (A -> B) -> (A -> B -> C) -> A -> C.\nProof.\nintros Hab Habc Ha.\napply Habc.\n{ admit. (* ... (à compléter) *)\n}\nadmit. (* ... (à compléter) *)\nAdmitted.\n\n(* ou délimiter les sous-buts avec des items \"-\" *)\nLemma ex5'' : (A -> B) -> (A -> B -> C) -> A -> C.\nProof.\nintros Hab Habc Ha.\napply Habc.\n- admit. (* ... (à compléter) *)\n- admit.  (* ... (à compléter) *)\nAdmitted.\n\n(* remarque: ces lemmes sont assez simples et la tactique «auto» les\n   prouve tous *)\nLemma ex5''' : (A -> B) -> (A -> B -> C) -> A -> C.\nProof.\nauto.\nQed.\n\n(* Considérons la conjonction de 2 propositions : A /\\ B.\n   À partir de A et de B, on peut prouver A /\\ B en appliquant conj.\n   À ne pas confondre avec la fonction (andb : bool -> bool -> bool).\n*)\nCheck conj.\n\nLemma ex6 : A -> B -> A /\\ B.\nProof.\nintros Ha Hb.\napply conj.\n- apply Ha.\n- apply Hb.\nQed.\n\n(* la tactique «split» est un synonyme de «apply conj» *)\nLemma ex6' : A -> B -> A /\\ B.\nProof.\nintros Ha Hb.\nsplit. (* 2 sous-buts sont produits: prouver A, prouver B *)\n- apply Ha. (* 1er sous-but: on prouve A *)\n- apply Hb. (* 2eme sous-but: on prouve B *)\nQed.\n\n(* on peut détruire A /\\ B après l'avoir introduit, avec \"destruct …\"\nou \"destruct … as [Ha Hb]\" *)\nLemma ex7 : A /\\ B -> A.\nintros Hab. (* Hab est une preuve de A/\\B *)\ndestruct Hab as [Ha Hb]. (* Ha est une preuve de A, Hb une preuve de B *)\napply Ha.\nQed.\n\n(* Prouver le lemme suivant *)\nLemma ex8 : A /\\ B -> B /\\ A.\nProof.\n(* ... (à compléter) *)\nAdmitted.\n\n(* la disjonction (ou) est similaire : A \\/ B.\n   À partir de A (resp. B), on a une preuve de A \\/ B.\n   Si on a une preuve de A ou une preuve de B,\n   on peut prouver A \\/ B en appliquant or_introl (resp. or_intror) *)\nCheck or_introl.\nCheck or_intror.\n\nLemma ex9 : A -> A \\/ B.\nProof.\nintros Ha.\napply or_introl.\napply Ha.\nQed.\n\n(* la tactique «left» (resp. right) est un synonyme de «apply or_introl» *)\nLemma ex9' : A -> A \\/ B.\nProof.\nintros Ha.\nleft.\napply Ha.\nQed.\n\n(* de même que A /\\ B, on peut détruire A \\/ B avec \"destruct …\" ou\n   \"destruct … as [Ha | Hb]\"\n *)\n(* on notera que la destruction d'un ET produit 2 hypothèses alors que\n   la destruction d'un OU conduit à réaliser 2 preuves - 1 pour chaque hypothèse\n *)\nLemma ex10 : A \\/ B -> (B -> A) -> A.\nProof.\nintros Hab.\ndestruct Hab as [Ha | Hb]. (* crée 2 sous-buts *)\n- intros _. (* on n'a pas besoin de l'hypothèse introduite, donc on l'ignore avec _ *)\n  apply Ha.\n- intros Himpl.\n  apply Himpl.\n  apply Hb.\nQed.\n\n(* Prouver le lemme suivant *)\nLemma ex11 : A \\/ B -> B \\/ A.\nProof.\n(* ... (à compléter) *)\nAdmitted.\n\nEnd PremieresTactiques.\n\n(***************************************************)\n(* Calcul des prédicats (avec des quantificateurs) *)\n(***************************************************)\nSection CalculPredicats.\n\nVariable P Q : nat -> Prop.\nVariable R : nat -> nat -> Prop.\n\n(* Prouver *)\nLemma ex12 : (forall x, P x) /\\ (forall x, Q x) -> (forall x, P x /\\ Q x).\nProof. (* on pourra utiliser «intros x» et apply *)\n(* ... (à compléter) *)\nAdmitted.\n\n(* Prouver *)\nLemma ex13 : (forall x, P x) \\/ (forall x, Q x) -> (forall x, P x \\/ Q x).\nProof.\n(* ... (à compléter) *)\nAdmitted.\n\n(* Essayez de prouver (si c'est possible !) *)\nLemma ex14 : (forall x, P x \\/ Q x) -> (forall x, P x) \\/ (forall x, Q x).\nProof.\n(* ... (à compléter) *)\nAbort.\n\n(* (H : exists x, …) se détruit avec \"destruct H as [x Hx]\" *)\n(* et se prouve avec la tactique «exists x» : pour prouver une formule\n  exists x, P x, il faut fournir une valeur pour x et prouver qu'elle\n  satisfait P *)\nLemma ex15 : (exists x, forall y, R x y) -> (forall y, exists x, R x y).\nProof.\nintros Hex.\ndestruct Hex as [x Hx].\nintros y.\nexists x.\napply Hx.\nQed.\n\n(* Prouver *)\nLemma ex16 : (exists x, P x -> Q x) -> (forall x, P x) -> exists x, Q x.\nProof.\n(* ... (à compléter) *)\nAdmitted.\n\nEnd CalculPredicats.\n\n(**************************************)\n(* Retour aux booléens et aux entiers *)\n(**************************************)\n\nOpen Scope bool_scope.\n\n(* les booléens permettent de faire facilement des preuves par \"force brute\"\n(énumération de tous les cas) : *)\nLemma negneg : forall b, negb (negb b) = b.\nProof.\nintros b.\ndestruct b. (* génère un but pour chaque valeur possible de b *)\n- easy. (* un peu plus puissant que \"reflexivity\" *)\n- easy.\nQed.\n\n(* Prouver *)\nLemma and_commutatif : forall a b, a && b = b && a.\nProof.\n(* ... (à compléter) *)\nAdmitted.\n\n(* on considère l'addition sur les entiers définie dans la librairie Coq par :\n\nFixpoint plus n m :=\n  match n with\n  | 0 => m\n  | S p => S (plus p m)\n  end.\n\nOn notera donc que\n  - (plus 0 m) se réduit en m\n  - (plus (S n) m) se réduit en S (plus n m).\nPar contre (plus n 0) ne se réduit pas.\n *)\n\n(* la tactique «simpl» permet de simplifier des termes *)\nLemma plus0n : forall n, plus 0 n = n.\nProof.\nintros n.\nsimpl.\nreflexivity.\nQed.\n\n(* mais on peut aussi écrire directement *)\nLemma plus0n' : forall n, plus 0 n = n.\nProof.\nreflexivity. (* puisque les 2 termes sont identiques après réduction *)\nQed.\n\n(* ça ne marche pas dans l'autre sens *)\nLemma plusn0 : forall n, plus n 0 = n.\nProof.\nintros n.\nsimpl. (* ne fait rien *)\n(* en effet, plus est défini récursivement sur son premier argument,\nici il s'agit de n qui est un entier naturel quelconque (on ne sait\npas s'il est de la forme O ou S n') donc on ne peut rien calculer *)\nAbort.\n\n(* On va donc procéder par récurrence sur n on utilise pour cela la\n   tactique induction *)\nLemma plusn0 : forall n, plus n 0 = n.\nProof.\n(* pas besoin de faire \"intros n\" avant ! *)\ninduction n.\n- (* simpl. inutile *) reflexivity. (* cas de base *)\n- simpl. (* utile pour faire apparaitre le terme de gauche de l'égalité *)\n  rewrite IHn. (* hypothèse de récurrence *)\n  (* on peut utiliser rewrite avec n'importe quelle égalité *)\n  (* si besoin on pourrait utiliser l'égalité de droite à gauche en faisant\n     rewrite <-IHn *)\n  easy.\nQed.\n\n(* Prouver *)\nLemma plus1n : forall n, plus 1 n = S n.\nProof.\n(* ... (à compléter) *)\nAdmitted.\n\n(* Prouver *)\nLemma plusSn : forall n m, S (plus n m) = plus n (S m).\nProof.\n(* ... (à compléter) *)\nAdmitted.\n\n(* Prouver (un peu plus dur, ne pas hésiter à utiliser les lemmes précédents)  *)\nLemma plus_commutatif : forall n m, plus n m = plus m n.\nProof.\n(* ... (à compléter) *)\nAdmitted.\n\n(* on peut aussi utiliser les opérateurs +,* qui ne sont que des notations *)\nLemma plus_commutatif_bis : forall n m, n + m = m + n.\nProof.\napply plus_commutatif.\nQed.\n\nFrom Coq Require Import Lia. (* Linear Integer Aritmetic :\npreuve automatique de propriétés linéaires sur les entiers *)\n\nLemma plus_commutatif' : forall n m, n + m = m + n.\nProof.\nintros n m.\nlia. (* c'est automatique! *)\nQed.\n(* lia supporte la somme, le produit par une constante, les comparaisons *)\n\n(*****************************)\n(* Preuve en avant, Coupures *)\n(*****************************)\n\n(* Jusqu'à maintenant, les preuves ont été réalisées en modifiant le\nbut jusqu'à le rendre trivial ou le ramener à un lemme connu.\n\nOn fait souvent l'inverse quand on rédige une preuve sur papier : on\npart des hypothèses et on les modifie pour atteindre la conclusion.\nOn parle de style de preuve «en avant».\n\nCela consiste souvent à faire ce qu'on appelle une coupure : on met la\npreuve «en pause» pour prouver un résultat intermédiaire qui sera\nensuite utilisé.\n\nOn peut pour cela faire un lemme intermédiaire (comme le lemme \"plusSn\"\ndans la preuve de \"plus_commutatif\" plus haut) mais ça impose parfois\nde recopier toutes les hypothèses et de laisser traîner un lemme\npeut-être trop spécialisé pour être réellement réutilisable.\n\nLa tactique\n«assert (nom : propriété).» fournit une alternative plus légère. *)\n\nLemma plus_commutatif'' : forall n m, plus n m = plus m n.\nProof.\ninduction n.\n- intros m.\n  rewrite plusn0.\n  easy.\n- assert (HplusSn : forall m, S (plus m n) = plus m (S n)).\n  { induction m.\n    - easy.\n    - simpl.\n      rewrite IHm.\n      easy.\n  } (* on a maintenant HplusSn dans nos hypothèses *)\n  intros m.\n  simpl.\n  rewrite IHn.\n  rewrite HplusSn.\n  easy.\nQed.\n\n(**************************)\n(* Preuves sur les listes *)\n(**************************)\n\nRequire Import List.\nImport ListNotations.\n(* les 2 constructeurs sont notés [] et _::_ comme en Caml *)\n\nFixpoint append {T} (l1 l2 : list T) : list T := (* T rendu implicite *)\n  match l1 with\n    [] => l2\n  | x :: r => x :: append r l2 (* le 1er argument T est implicite *)\n  end.\nEval compute in append [1;2] [3;4].  (* utilise \"append\", défini précédemment *)\nEval compute in [1;2] ++ [3;4].  (* utilise \"app\" de la bibliothèque standard *)\n(* la concaténation est ainsi est notée \"… @ …\" en Caml, \"… ++ …\" en Coq *)\n\n(* Le principe d'induction sur les listes est automatiquement généré lors\n   de la définition du type list. L'itérateur le plus général sur les listes\n   a pour type le principe d'induction : *)\nCheck list_ind.\n\n(********************************************)\n(* Modules en Coq : un Type Abstrait Prouvé *)\n(********************************************)\n\n(* Voici une interface de module *)\nModule Type ListNat.\n  Parameter list_nat : Type.\n  Parameter nil : list_nat.\n  Parameter cons : nat -> list_nat -> list_nat.\n  Parameter list_nat_it :\n    forall T (f_nil : T) (f_cons : nat -> list_nat -> T -> T), list_nat -> T.\n  Parameter length : list_nat -> nat.\n\n  Axiom list_nat_ind :\n    forall (P : list_nat -> Prop),\n      P nil -> (forall (a : nat) (l : list_nat), P l -> P (cons a l)) ->\n      forall l : list_nat, P l.\n\n  Axiom list_nat_it_nil :\n    forall T f_nil f_cons, list_nat_it T f_nil f_cons nil = f_nil.\n  Axiom list_nat_it_cons :\n    forall T f_nil f_cons x l,\n      list_nat_it T f_nil f_cons (cons x l)\n      = f_cons x l (list_nat_it T f_nil f_cons l).\n\n  Axiom length_nil : length nil = 0.\n  Axiom length_cons : forall x l, length (cons x l) = 1 + length l.\nEnd ListNat.\n\n(* Pour un module L suivant cette interface, étendons le avec une\n   nouvelle opération.  *)\nModule ListNatExt (L : ListNat).\n\n(* Effectue une copie du module L dans le module ambient *)\nInclude L.\n\n(* implémenter la concaténation de deux liste \"app\" *)\nDefinition app (l l' : L.list_nat) : L.list_nat :=\n  L.nil. (* ... (à compléter (remplacer L.nil par votre implémentation)) *)\n\nLemma app_length : forall l l', L.length (app l l') = L.length l + L.length l'.\nProof.\n(* ... (à compléter) *)\nAdmitted.\n\nEnd ListNatExt.\n\n(* Implémenter un module de type ListNat *)\n(*\nModule ListNatImpl : ListNat.\n(* ... (à compléter) *)\n(* (penser à list_ind pour list_nat_ind) *)\nEnd ListNatImpl.\n*)\n\n(* on peut alors appliquer le foncteur ListNatExt *)\nModule L' := ListNatExt ListNatImpl.\n\n(* et utiliser le module résultant *)\nLemma app3 : forall l l', L'.length (L'.app l l') = L'.length (L'.app l' l).\nProof.\n(* ... (à compléter) *)\nAdmitted.\n", "meta": {"author": "irinacake", "repo": "notesMaster1", "sha": "c6ea86ab79ccdec5f5b2201815cbc920e217f4b6", "save_path": "github-repos/coq/irinacake-notesMaster1", "path": "github-repos/coq/irinacake-notesMaster1/notesMaster1-c6ea86ab79ccdec5f5b2201815cbc920e217f4b6/Mementos_Et_TPs_OCaml_L3_Info/TAPFA_TP_CoQ/tp2_tapfa_coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.8723473779969193, "lm_q1q2_score": 0.6757057932949512}}
{"text": "(* coq-robot (c) 2017 AIST and INRIA. License: LGPL-2.1-or-later. *)\nFrom mathcomp Require Import all_ssreflect ssralg ssrint ssrnum rat poly.\nFrom mathcomp Require Import closed_field polyrcf matrix mxalgebra mxpoly zmodp.\nFrom mathcomp Require Import realalg complex fingroup perm.\nFrom mathcomp.analysis Require Import reals forms.\nRequire Import ssr_ext.\n\n(******************************************************************************)\n(*                     Elements of Euclidean geometry                         *)\n(*                                                                            *)\n(* This file provides elements of Euclidean geometry, with specializations to *)\n(* the 3D case. It develops the theory of the dot-product and of the          *)\n(* cross-product with lemmas such as the double cross-product. It also        *)\n(* develops the theory of rotation matrices with lemmas such as the           *)\n(* preservation of the dot-product by orthogonal matrices or a closed formula *)\n(* for the characteristic polynomial of a 3x3 matrix.                         *)\n(*                                                                            *)\n(*  jacobi_identity == Jacobi identity                                        *)\n(* lieAlgebraType R == the type of Lie algebra over R                         *)\n(*        lie[x, y] == Lie brackets                                           *)\n(*                                                                            *)\n(*        u *d w == the dot-product of the vectors u and v, i.e., the only    *)\n(*                  component of the 1x1-matrix u * v^T                       *)\n(*        norm u == the norm of vector u, i.e., the square root of u *d u     *)\n(*   normalize u == scales vector u to be of unit norm                        *)\n(*       A _|_ B == A and B are normal                                        *)\n(*       'O[T]_n == the type of orthogonal matrices of size n                 *)\n(*      'SO[T]_n == the type of rotation matrices of size n                   *)\n(*       cross M == generalized cross-product                                 *)\n(*                                                                            *)\n(* Specializations to the 3D case:                                            *)\n(*      row2 a b == the row vector [a,b]                                      *)\n(*    row3 a b c == the row vector [a,b,c]                                    *)\n(*   col_mx2 u v == specialization of col_mx two row vectors of size 2        *)\n(* col_mx3 u v w == specialization of col_mx two row vectors of size 3        *)\n(*        u *v v == the cross-product of the vectors u and v, defined using   *)\n(*                  determinants                                              *)\n(* Module rv3LieAlgebra == the space R^3 with the cross-product is a Lie      *)\n(*                  algebra                                                   *)\n(* vaxis_euler M == the vector-axis of the rotation matrix M of Euler's       *)\n(*                  theorem                                                   *)\n(*                                                                            *)\n(******************************************************************************)\n\nReserved Notation \"*d%R\".\nReserved Notation \"u *d w\" (at level 40).\nReserved Notation \"*v%R\".\nReserved Notation \"u *v w\" (at level 40).\nReserved Notation \"''O[' T ]_ n\"\n  (at level 8, n at level 2, format \"''O[' T ]_ n\").\nReserved Notation \"''SO[' T ]_ n\"\n  (at level 8, n at level 2, format \"''SO[' T ]_ n\").\nReserved Notation \"A _|_ B\"  (at level 69). (* NB: used to be level 8 *)\nReserved Notation \"u _|_ A , B \" (A at next level, at level 69,\n format \"u  _|_  A , B \").\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport Order.TTheory GRing.Theory Num.Def Num.Theory.\n\nLocal Open Scope ring_scope.\n\nDefinition jacobi_identity (T : zmodType) (op : T -> T -> T) := forall x y z,\n  op x (op y z) + op y (op z x) + op z (op x y) = 0.\n\nReserved Notation \"lie[ t1 , t2 ]\" (format \"lie[ t1 ,  t2 ]\").\n\nModule LieAlgebra.\nRecord mixin_of (R : ringType) (L : lmodType R) := Mixin {\n  bracket : {bilinear L -> L -> L} ;\n  _ : forall x, bracket x x = 0 ;\n  _ : jacobi_identity bracket }.\n\nSection ClassDef.\nVariable R : ringType.\n\nRecord class_of L := Class {\n  base : GRing.Lmodule.class_of R L ;\n  mixin : mixin_of (GRing.Lmodule.Pack _ base) }.\nLocal Coercion base : class_of >-> GRing.Lmodule.class_of.\n\nStructure type (phR : phant R) := Pack { sort; _ : class_of sort }.\nLocal Coercion sort : type >-> Sortclass.\nVariable (phR : phant R) (T : Type) (cT : type phR).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack phR T c.\n\nDefinition pack b0 (m0 : @mixin_of R (@GRing.Lmodule.Pack R _ T b0)) :=\n  fun bT b & phant_id (@GRing.Lmodule.class R phR bT) b =>\n  fun m & phant_id m0 m => Pack phR (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition zmodType := @GRing.Zmodule.Pack cT class.\nDefinition lmodType := @GRing.Lmodule.Pack R phR cT class.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> GRing.Lmodule.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> GRing.Zmodule.type.\nCanonical zmodType.\nCoercion lmodType : type >-> GRing.Lmodule.type.\nCanonical lmodType.\nNotation lieAlgebraType R := (type (Phant R)).\nNotation LieAlgebraType R T m := (@pack _ (Phant R) T _ m _ _ id _ id).\nNotation LieAlgebraMixin := Mixin.\nNotation \"[ 'lieAlgebraType' R 'of' T 'for' cT ]\" :=\n  (@clone _ (Phant R) T cT _ idfun)\n  (at level 0, format \"[ 'lieAlgebraType' R 'of' T 'for' cT ]\") : form_scope.\nNotation \"[ 'lieAlgebraType' R 'of' T ]\" := (@clone _ (Phant R) T _ _ id)\n  (at level 0, format \"[ 'lieAlgebraType' R 'of' T ]\") : form_scope.\nEnd Exports.\nEnd LieAlgebra.\nImport LieAlgebra.Exports.\n\nDefinition liebracket (R : ringType) (G : lieAlgebraType R) :\n  {bilinear G -> G -> G} := LieAlgebra.bracket (LieAlgebra.class G).\nNotation \"lie[ t1 , t2 ]\" := (@liebracket _ _ t1 t2).\n\nSection liealgebra.\nVariables (R : ringType) (G : lieAlgebraType R).\n\nLemma liexx (x : G) : lie[x, x] = 0.\nProof. by case: G x => ? [? []]. Qed.\n\nLemma jacobi : jacobi_identity (@liebracket _ G).\nProof. by case: G => ? [? []]. Qed.\n\n(* Lie brackets are anticommutative *)\nLemma lieC (x y : G) : lie[x, y] = - lie[y, x].\nProof.\napply/eqP; rewrite -subr_eq0 opprK; apply/eqP.\nrewrite -[RHS](liexx (x + y)) linearDl 2!linearDr.\nby rewrite 2!liexx !(addr0,add0r).\nQed.\n\nEnd liealgebra.\n\nSection dot_product0.\n\nVariables (R : ringType) (n : nat).\n\nImplicit Types u v w : 'rV[R]_n.\n\nDefinition dotmul u v : R := (u *m v^T)``_0.\nLocal Notation \"*d%R\" := (@dotmul _).\nLocal Notation \"u *d w\" := (dotmul u w).\n\nLemma dotmulP u v : u *m v^T = (u *d v)%:M.\nProof. by rewrite /dotmul -mx11_scalar. Qed.\n\nLemma dotmulE u v : u *d v = \\sum_k u``_k * v``_k.\nProof. by rewrite [LHS]mxE; apply: eq_bigr=> i; rewrite mxE. Qed.\n\nLemma dotmul0v v : 0 *d v = 0.\nProof. by rewrite [LHS]mxE big1 // => i; rewrite mxE mul0r. Qed.\n\nLemma dotmulv0 v : v *d 0 = 0.\nProof. by rewrite /dotmul trmx0 mulmx0 mxE. Qed.\n\nLemma dotmulDr u b c : u *d (b + c) = u *d b + u *d c.\nProof. by rewrite {1}/dotmul linearD /= mulmxDr mxE. Qed.\n\nLemma dotmulDl u b c : (b + c) *d u = b *d u + c *d u.\nProof. by rewrite {1}/dotmul mulmxDl mxE. Qed.\n\nLemma dotmulvN u v : u *d -v = - (u *d v).\nProof. by rewrite /dotmul linearN /= mulmxN mxE. Qed.\n\nLemma dotmulNv u v : - u *d v = - (u *d v).\nProof. by rewrite /dotmul mulNmx mxE. Qed.\n\nLemma dotmulBr u b c : u *d (b - c) = u *d b - u *d c.\nProof. by rewrite dotmulDr dotmulvN. Qed.\n\nLemma dotmulBl u b c : (b - c) *d u = b *d u - c *d u.\nProof. by rewrite dotmulDl dotmulNv. Qed.\n\nLemma dotmulZv u k v : (k *: u) *d v = k * (u *d v).\nProof. by rewrite /dotmul -scalemxAl mxE. Qed.\n\nLemma dotmul_delta_mx u i : u *d 'e_i = u``_i.\nProof.\nrewrite /dotmul trmx_delta mxE (bigD1 i) //= mxE !eqxx mulr1.\nby rewrite big1 ?addr0 // => j jnei; rewrite mxE (negbTE jnei) /= mulr0.\nQed.\n\nLemma dote2 i j : ('e_i : 'rV[R]_n) *d 'e_j = (i == j)%:R.\nProof. by rewrite dotmul_delta_mx mxE eqxx eq_sym. Qed.\n\n(* Lemma dotmul_eq u v : (forall x, u *d x = v *d x) -> u = v. *)\n(* Proof. by move=> uv; apply/rowP => i; rewrite -!dotmul_delta_mx uv. Qed. *)\n\nLemma mxE_dotmul_row_col m p (M : 'M[R]_(m, n)) (N : 'M[R]_(n, p)) i j :\n  (M *m N) i j = (row i M) *d (col j N)^T.\nProof. rewrite !mxE dotmulE; apply/eq_bigr => /= k _; by rewrite !mxE. Qed.\n\nLemma coorE (p : 'rV[R]_n) i : p``_i = p *d 'e_i.\nProof. by rewrite dotmul_delta_mx. Qed.\n\nLemma colE (v : 'rV[R]_n) j : col j v = 'e_j *m v^T.\nProof.\napply/colP => i; rewrite {i}(ord1 i) !mxE coorE /dotmul mxE.\napply: eq_bigr => /= i _; rewrite !mxE eqxx /=.\ncase/boolP : (i == j) => /=; by rewrite ?(mulr1,mul1r,mul0r,mulr0).\nQed.\n\nLemma mxE_dotmul (M : 'M[R]_n) i j : M i j = 'e_j *d row i M.\nProof. by rewrite mxE_col_row /dotmul colE. Qed.\n\nEnd dot_product0.\n\nNotation \"*d%R\" := (@dotmul _ _) : ring_scope.\nNotation \"u *d w\" := (dotmul u w) : ring_scope.\n\nSection com_dot_product.\n\nVariables (R : comRingType) (n : nat).\n\nImplicit Types u v : 'rV[R]_n.\n\nLemma dotmulC u v : u *d v = v *d u.\nProof. by rewrite /dotmul -[_ *m _]trmxK trmx_mul !trmxK mxE. Qed.\n\nLemma dotmulD u v : (u + v) *d (u + v) = u *d u + (u *d v) *+ 2 + v *d v.\nProof. by rewrite dotmulDr 2!dotmulDl mulr2n !addrA ![v *d _]dotmulC. Qed.\n\nLemma dotmulvZ u k v : u *d (k *: v) = k * (u *d v).\nProof. by rewrite /dotmul linearZ /= -scalemxAr mxE. Qed.\n\nLemma dotmul_trmx u M v : u *d (v *m M) = (u *m M^T) *d v.\nProof. by rewrite /dotmul trmx_mul mulmxA. Qed.\n\nEnd com_dot_product.\n\nSection dotmul_bilinear.\n\nVariables (R : comRingType) (n : nat).\n\nDefinition dotmul_rev (v u : 'rV[R]_n) := u *d v.\nCanonical rev_dotmul := @RevOp _ _ _ dotmul_rev (@dotmul R n)\n  (fun _ _ => erefl).\n\nLemma dotmul_is_linear u : GRing.linear (dotmul u : 'rV[R]_n -> R^o).\nProof. move=> /= k v w; by rewrite dotmulDr dotmulvZ. Qed.\nCanonical dotmul_linear x := Linear (dotmul_is_linear x).\n\nLemma dotmul_rev_is_linear v : GRing.linear (dotmul_rev v : 'rV[R]_n -> R^o).\nProof. move=> /= k u w; by rewrite /dotmul_rev dotmulDl dotmulZv. Qed.\nCanonical dotmul_rev_linear v := Linear (dotmul_rev_is_linear v).\n\nCanonical dotmul_bilinear := [bilinear of (@dotmul R n)].\n\nEnd dotmul_bilinear.\n\nSection dot_product.\n\nVariables (T : realDomainType) (n : nat).\n\nImplicit Types u v w : 'rV[T]_n.\n\nLemma le0dotmul u : 0 <= u *d u.\nProof. rewrite dotmulE sumr_ge0 // => i _; by rewrite -expr2 sqr_ge0. Qed.\n\nLemma dotmulvv0 u : (u *d u == 0) = (u == 0).\nProof.\napply/idP/idP; last by move/eqP ->; rewrite dotmul0v.\nrewrite dotmulE psumr_eq0; last by move=> i _; rewrite -expr2 sqr_ge0.\nmove/allP => H; apply/eqP/rowP => i.\napply/eqP; by rewrite mxE -sqrf_eq0 expr2 -(implyTb ( _ == _)) H.\nQed.\n\nEnd dot_product.\n\nSection norm.\n\nVariables (T : rcfType) (n : nat).\nImplicit Types u v : 'rV[T]_n.\n\nDefinition norm u := Num.sqrt (u *d u).\n\nLemma normN u : norm (- u) = norm u.\nProof. by rewrite /norm dotmulNv dotmulvN opprK. Qed.\n\nLemma norm0 : norm 0 = 0.\nProof. by rewrite /norm dotmul0v sqrtr0. Qed.\n\nLemma norm_delta_mx i : norm 'e_i = 1.\nProof. by rewrite /norm /dotmul trmx_delta mul_delta_mx mxE !eqxx sqrtr1. Qed.\n\nLemma norm_ge0 u : norm u >= 0.\nProof. by apply sqrtr_ge0. Qed.\nHint Resolve norm_ge0 : core.\n\nLemma normr_norm u : `|norm u| = norm u.\nProof. by rewrite ger0_norm. Qed.\n\nLemma norm_eq0 u : (norm u == 0) = (u == 0).\nProof. by rewrite -sqrtr0 eqr_sqrt // ?dotmulvv0 // le0dotmul. Qed.\n\nLemma norm_gt0 u : (0 < norm u) = (u != 0).\nProof. by rewrite lt_neqAle norm_ge0 andbT eq_sym norm_eq0. Qed.\n\nLemma normZ (k : T) u : norm (k *: u) = `|k| * norm u.\nProof.\nby rewrite /norm dotmulvZ dotmulZv mulrA sqrtrM -expr2 ?sqrtr_sqr // sqr_ge0.\nQed.\n\nLemma dotmulvv u : u *d u = norm u ^+ 2.\nProof.\nrewrite /norm [_ ^+ _]sqr_sqrtr // dotmulE sumr_ge0 //.\nby move=> i _; rewrite sqr_ge0.\nQed.\n\nLemma polarization_identity v u :\n  v *d u = 1 / 4%:R * (norm (v + u) ^+ 2 - norm (v - u) ^+ 2).\nProof.\napply: (@mulrI _ 4%:R); first exact: pnatf_unit.\nrewrite [in RHS]mulrA div1r divrr ?pnatf_unit // mul1r.\nrewrite -2!dotmulvv dotmulD dotmulD mulr_natl (addrC (v *d v)).\nrewrite (_ : 4 = 2 + 2)%N // mulrnDr -3![in RHS]addrA; congr (_ + _).\nrewrite opprD addrCA [_ + (- _ + _)]addrA subrr add0r.\nby rewrite addrC opprD 2!dotmulvN dotmulNv opprK subrK -mulNrn opprK.\nQed.\n\nLemma sqr_norm u : norm u ^+ 2 = \\sum_i u``_i ^+ 2.\nProof. rewrite -dotmulvv dotmulE; apply/eq_bigr => /= i _; by rewrite expr2. Qed.\n\nLemma mxtrace_tr_mul u : \\tr (u^T *m u) = norm u ^+ 2.\nProof.\nrewrite /mxtrace sqr_norm; apply/eq_bigr => /= i _; by rewrite mulmx_trE -expr2.\nQed.\n\nSection norm1.\n\nVariable u : 'rV[T]_n.\nHypothesis u1 : norm u = 1.\n\nLemma norm1_neq0 : u != 0.\nProof. move: u1; rewrite -norm_eq0 => ->; exact: oner_neq0. Qed.\n\nLemma dotmul1 : u *m u^T = 1.\nProof. by rewrite dotmulP dotmulvv u1 expr1n. Qed.\n\nEnd norm1.\n\nEnd norm.\n\nSection normalize.\n\nVariables (T : rcfType) (n : nat).\nImplicit Type u v : 'rV[T]_3.\n\nDefinition normalize v := (norm v)^-1 *: v.\n\nLemma normalize0 : normalize 0 = 0.\nProof. by rewrite /normalize scaler0. Qed.\n\nLemma normalizeN u : normalize (- u) = - normalize u.\nProof. by rewrite /normalize normN scalerN. Qed.\n\nLemma normalizeI v : norm v = 1 -> normalize v = v.\nProof. by move=> v1; rewrite /normalize v1 invr1 scale1r. Qed.\n\nLemma norm_normalize v : v != 0 -> norm (normalize v) = 1.\nProof.\nmove=> v0; rewrite normZ ger0_norm; last by rewrite invr_ge0 // norm_ge0.\nby rewrite mulVr // unitfE norm_eq0.\nQed.\n\nLemma normalize_eq0 v : (normalize v == 0) = (v == 0).\nProof.\napply/idP/idP => [|/eqP ->]; last by rewrite normalize0.\ncase/boolP : (v == 0) => [//| /norm_normalize].\nrewrite -norm_eq0 => -> /negPn; by rewrite oner_neq0.\nQed.\n\nLemma norm_scale_normalize u : norm u *: normalize u = u.\nProof.\ncase/boolP : (u == 0) => [/eqP -> {u}|u0]; first by rewrite norm0 scale0r.\nby rewrite /normalize scalerA divrr ?scale1r // unitfE norm_eq0.\nQed.\n\nLemma normalizeZ u (u0 : u != 0) k (k0 : 0 < k) : normalize (k *: u) = normalize u.\nProof.\nrewrite {1}/normalize normZ gtr0_norm // invrM ?unitfE ?gt_eqF // ?norm_gt0 //.\nby rewrite scalerA -mulrA mulVr ?mulr1 ?unitfE ?gt_eqF.\nQed.\n\n(* NB: not used *)\nLemma dotmul_normalize_norm u : u *d normalize u = norm u.\nProof.\ncase/boolP : (u == 0) => [/eqP ->{u}|u0]; first by rewrite norm0 dotmul0v.\nrewrite -{1}(norm_scale_normalize u) dotmulZv dotmulvv norm_normalize //.\nby rewrite expr1n mulr1.\nQed.\n\nLemma dotmul_normalize u v : (normalize u *d v == 0) = (u *d v == 0).\nProof.\ncase/boolP : (u == 0) => [/eqP ->|u0]; first by rewrite normalize0.\napply/idP/idP.\n  rewrite /normalize dotmulZv mulf_eq0 => /orP [|//].\n  by rewrite invr_eq0 norm_eq0 (negbTE u0).\nrewrite /normalize dotmulZv => /eqP ->; by rewrite mulr0.\nQed.\n\nEnd normalize.\n\nSection normal.\nVariable F : fieldType.\n\nLocal Notation \"A _|_ B\" := (A%MS <= kermx B%MS^T)%MS.\n\nLemma normal_sym n k m (A : 'M[F]_(k, n)) (B : 'M[F]_(m, n)) :\n  A _|_ B = B _|_ A.\nProof.\nrewrite !(sameP sub_kermxP eqP) -{1}[A]trmxK -trmx_mul.\nby rewrite -{1}trmx0 (inj_eq (@trmx_inj _ _ _)).\nQed.\n\nLemma normalNm n k m (A : 'M[F]_(k, n)) (B : 'M[F]_(m, n)) :\n  (- A) _|_ B = A _|_ B.\nProof. by rewrite eqmx_opp. Qed.\n\nLemma normalmN n k m (A : 'M[F]_(k, n)) (B : 'M[F]_(m, n)) :\n  A _|_ (- B) = A _|_ B.\nProof. by rewrite ![A _|_ _]normal_sym normalNm. Qed.\n\nLemma normalDm n k m p (A : 'M[F]_(k, n)) (B : 'M[F]_(m, n)) (C : 'M[F]_(p, n)) :\n  (A + B _|_ C) = (A _|_ C) && (B _|_ C).\nProof. by rewrite addsmxE !(sameP sub_kermxP eqP) mul_col_mx col_mx_eq0. Qed.\n\nLemma normalmD n k m p (A : 'M[F]_(k, n)) (B : 'M[F]_(m, n)) (C : 'M[F]_(p, n)) :\n  (A _|_ B + C) = (A _|_ B) && (A _|_ C).\nProof. by rewrite ![A _|_ _]normal_sym normalDm. Qed.\n\nLemma normalvv n (u v : 'rV[F]_n) : (u _|_ v) = (u *d v == 0).\nProof. by rewrite (sameP sub_kermxP eqP) dotmulP fmorph_eq0. Qed.\n\nEnd normal.\n\nNotation \"A _|_ B\" := (A%MS <= kermx B%MS^T)%MS.\nNotation \"u _|_ A , B \" := (u _|_ (col_mx A B)).\n\nSection orthogonal_rotation_def.\n\nVariables (n : nat) (T : ringType).\n\nDefinition orthogonal := [qualify M : 'M[T]_n | M *m M^T == 1%:M].\nFact orthogonal_key : pred_key orthogonal. Proof. by []. Qed.\nCanonical orthogonal_keyed := KeyedQualifier orthogonal_key.\n\nDefinition rotation := [qualify M : 'M[T]_n | (M \\is orthogonal) && (\\det M == 1)].\nFact rotation_key : pred_key rotation. Proof. by []. Qed.\nCanonical rotation_keyed := KeyedQualifier rotation_key.\n\nEnd orthogonal_rotation_def.\n\nNotation \"''O[' T ]_ n\" := (orthogonal n T) : ring_scope.\n\nNotation \"''SO[' T ]_ n\" := (rotation n T) : ring_scope.\n\nSection orthogonal_rotation_properties0.\n\nVariables (n' : nat) (T : ringType).\nLet n := n'.+1.\n\nLemma orthogonalE M : (M \\is 'O[T]_n) = (M * M^T == 1). Proof. by []. Qed.\n\nLemma orthogonal1 : 1 \\is 'O[T]_n.\nProof. by rewrite orthogonalE trmx1 mulr1. Qed.\n\nLemma orthogonal_mul_tr M : (M \\is 'O[T]_n) -> M *m M^T = 1.\nProof. by move/eqP. Qed.\n\nLemma orthogonal_oppr_closed : oppr_closed 'O[T]_n.\nProof. by move=> x; rewrite !orthogonalE linearN /= mulNr mulrN opprK. Qed.\nCanonical orthogonal_is_oppr_closed := OpprPred orthogonal_oppr_closed.\n\nLemma rotation_sub : {subset 'SO[T]_n <= 'O[T]_n}.\nProof. by move=> M /andP []. Qed.\n\nLemma orthogonalP M :\n  reflect (forall i j, row i M *d row j M = (i == j)%:R) (M \\is 'O[T]_n).\nProof.\napply: (iffP idP) => [|H] /=.\n  rewrite orthogonalE => /eqP /matrixP H i j.\n  move/(_ i j) : H; rewrite /dotmul !mxE => <-.\n  apply eq_bigr => k _; by rewrite !mxE.\nrewrite orthogonalE.\napply/eqP/matrixP => i j; rewrite !mxE -H /dotmul !mxE.\napply eq_bigr => k _; by rewrite !mxE.\nQed.\n\nLemma OSn_On m (P : 'M[T]_n) :\n  (block_mx (1%:M : 'M_m) 0 0 P \\is 'O[T]_(m + n)) = (P \\is 'O[T]_n).\nProof.\nrewrite !qualifE tr_block_mx trmx1 !trmx0 mulmx_block.\nrewrite !(mulmx0, mul0mx, mulmx1, mul1mx, addr0, add0r) scalar_mx_block.\nby apply/eqP/eqP => [/eq_block_mx[] |->//].\nQed.\n\nEnd orthogonal_rotation_properties0.\n\nLemma SOSn_SOn (T : comRingType) n m (P : 'M[T]_n.+1) :\n  (block_mx (1%:M : 'M_m) 0 0 P \\is 'SO[T]_(m + n.+1)) = (P \\is 'SO[T]_n.+1).\nProof. by rewrite qualifE OSn_On det_lblock det1 mul1r. Qed.\n\nSection orthogonal_rotation_properties.\n\nVariables (n' : nat) (T : comUnitRingType).\nLet n := n'.+1.\n\nLemma orthogonalEinv M : (M \\is 'O[T]_n) = (M \\is a GRing.unit) && (M^-1 == M^T).\nProof.\nrewrite orthogonalE; have [Mu | notMu] /= := boolP (M \\in unitmx); last first.\n  by apply: contraNF notMu => /eqP /mulmx1_unit [].\nby rewrite -(inj_eq (@mulrI _ M^-1 _)) ?unitrV // mulr1 mulKr.\nQed.\n\nLemma orthogonal_unit M : (M \\is 'O[T]_n) -> (M \\is a GRing.unit).\nProof. by rewrite orthogonalEinv => /andP []. Qed.\n\nLemma orthogonalV M : (M^T \\is 'O[T]_n) = (M \\is 'O[T]_n).\nProof.\nby rewrite !orthogonalEinv unitmx_tr -trmxV (inj_eq (@trmx_inj _ _ _)).\nQed.\n\nLemma orthogonal_inv M : M \\is 'O[T]_n -> M^-1 = M^T.\nProof. by rewrite orthogonalEinv => /andP [_ /eqP]. Qed.\n\nLemma orthogonalEC M : (M \\is 'O[T]_n) = (M^T * M == 1).\nProof. by rewrite -orthogonalV orthogonalE trmxK. Qed.\n\nLemma orthogonal_tr_mul M : (M \\is 'O[T]_n) -> M^T *m M = 1.\nProof. by rewrite orthogonalEC => /eqP. Qed.\n\nLemma orthogonal_divr_closed : divr_closed 'O[T]_n.\nProof.\nsplit => [| P Q HP HQ]; first exact: orthogonal1.\nrewrite orthogonalE orthogonal_inv // trmx_mul trmxK -mulrA.\nby rewrite -orthogonal_inv // mulKr // orthogonal_unit.\nQed.\nCanonical orthogonal_is_mulr_closed := MulrPred orthogonal_divr_closed.\nCanonical orthogonal_is_divr_closed := DivrPred orthogonal_divr_closed.\nCanonical orthogonal_is_smulr_closed := SmulrPred orthogonal_divr_closed.\nCanonical orthogonal_is_sdivr_closed := SdivrPred orthogonal_divr_closed.\n\nLemma rotationE M : (M \\is 'SO[T]_n) = (M \\is 'O[T]_n) && (\\det M == 1). Proof. by []. Qed.\n\nLemma rotationV M : (M^T \\is 'SO[T]_n) = (M \\is 'SO[T]_n).\nProof. by rewrite rotationE orthogonalV det_tr -rotationE. Qed.\n\nLemma rotation_inv M : M \\is 'SO[T]_n -> M^-1 = M^T.\nProof. by rewrite rotationE orthogonalEinv => /andP[/andP[_ /eqP]]. Qed.\n\nLemma rotation_det M : M \\is 'SO[T]_n -> \\det M = 1.\nProof. by move=> /andP[_ /eqP]. Qed.\n\nLemma rotation1 : 1 \\is 'SO[T]_n.\nProof. apply/andP; by rewrite orthogonal1 det1. Qed.\n\nLemma rotation_tr_mul M : (M \\is 'SO[T]_n) -> M^T *m M = 1.\nProof. by move=> /rotation_sub /orthogonal_tr_mul. Qed.\n\nLemma rotation_divr_closed : divr_closed 'SO[T]_n.\nProof.\nsplit => [|P Q Prot Qrot]; first exact: rotation1.\nrewrite rotationE rpred_div ?rotation_sub //=.\nby rewrite det_mulmx det_inv !rotation_det // divr1.\nQed.\n\nCanonical rotation_is_mulr_closed := MulrPred rotation_divr_closed.\nCanonical rotation_is_divr_closed := DivrPred rotation_divr_closed.\n\nLemma orthogonalPcol M :\n  reflect (forall i j, (col i M)^T *d (col j M)^T = (i == j)%:R) (M \\is 'O[T]_n).\nProof.\napply: (iffP idP) => [MSO i j|H] /=.\n- move: (MSO); rewrite -rpredV orthogonal_inv // => /orthogonalP <-.\n  by rewrite 2!tr_col.\n- suff MSO : M^T \\is 'O[T]_n.\n    move/orthogonal_inv: (MSO); rewrite trmxK => <-; by rewrite rpredV.\n  apply/orthogonalP => i j; by rewrite -H 2!tr_col.\nQed.\n\nEnd orthogonal_rotation_properties.\n\nSection orthogonal_rotation_properties1.\n\nVariables (n' : nat) (T : realDomainType).\nLet n := n'.+1.\n\nLemma orthogonal_det M : M \\is 'O[T]_n -> `|\\det M| = 1.\nProof.\nmove=> /eqP /(congr1 determinant); rewrite detM det_tr det1 => /eqP.\nby rewrite sqr_norm_eq1 => /eqP.\nQed.\n\nEnd orthogonal_rotation_properties1.\n\nLemma orthogonal2P (T : ringType) M : reflect (M \\is 'O[T]_2)\n    [&& row 0 M *d row 0 M == 1, row 0 M *d row 1 M == 0,\n        row 1 M *d row 0 M == 0 & row 1 M *d row 1 M == 1].\nProof.\napply (iffP idP) => [/and4P[] /eqP H1 /eqP H2 /eqP H3 /eqP H4|]; last first.\n  move/orthogonalP => H; by rewrite !H /= !eqxx.\napply/orthogonalP => i j.\ncase/boolP : (i == 0) => [|/ifnot01P]/eqP->;\n  by case/boolP : (j == 0) => [|/ifnot01P]/eqP->.\nQed.\n\n(* TODO: move? use *d? *)\nLemma dotmul_conjc_eq0 {T : rcfType} n (v : 'rV[T[i]]_n.+1) :\n  (v *m map_mx conjc v^T == 0) = (v == 0).\nProof.\napply/idP/idP => [H|/eqP ->]; last by rewrite mul0mx.\nhave : \\sum_(i < n.+1) v``_i * (v``_i)^* = 0.\n  move/eqP/matrixP : H =>/(_ 0 0).\n  rewrite !mxE => H; rewrite -{2}H.\n  apply/eq_bigr => /= i _; by rewrite !mxE.\nmove/eqP; rewrite psumr_eq0 /= => [/allP K|]; last first.\n  move=> i _; by rewrite -sqr_normc exprn_ge0.\napply/eqP/rowP => i.\nmove: (K i); rewrite /index_enum -enumT mem_enum inE => /(_ isT).\nrewrite -sqr_normc sqrf_eq0 normr_eq0 => /eqP ->; by rewrite mxE.\nQed.\n\n(* eigenvalues of orthogonal matrices have norm 1 *)\n\nLemma eigenvalue_O (T : rcfType) n M : M \\is 'O[T]_n.+1 -> forall k,\n   k \\in eigenvalue (map_mx (fun x => x%:C%C) M) -> `| k | = 1.\nProof.\nmove=> MSO /= k.\ncase/eigenvalueP => v kv v0.\nmove/(congr1 trmx)/(congr1 (fun x => map_mx conjc x)) : (kv).\nrewrite trmx_mul map_mxM linearZ /= map_mxZ map_trmx.\nmove/(congr1 (fun x => (k *: v) *m x)).\nrewrite -{1}kv -mulmxA (mulmxA (map_mx _ M)) (_ : map_mx _ M *m _ = 1%:M); last first.\n  rewrite (_ : map_mx conjc _ = map_mx (fun x => x%:C%C) M^T); last first.\n    apply/matrixP => i j; by rewrite !mxE conjc_real.\n  rewrite orthogonalE in MSO.\n  by rewrite -map_mxM mulmxE (eqP MSO) map_mx1.\nrewrite mul1mx -scalemxAr /= -scalemxAl scalerA => /eqP.\nrewrite -subr_eq0 -{1}(scale1r (v *m _)) -scalerBl scaler_eq0 => /orP [].\n  by rewrite subr_eq0 mulrC -sqr_normc -{1}(expr1n _ 2) eqr_expn2 // ?ler01 // => /eqP.\nby rewrite dotmul_conjc_eq0 (negbTE v0).\nQed.\n\nLemma norm_row_of_O (T : rcfType) n M : M \\is 'O[T]_n.+1 -> forall i, norm (row i M) = 1.\nProof.\nmove=> MSO i.\napply/eqP; rewrite -(@eqr_expn2 _ 2) // ?norm_ge0 // expr1n; apply/eqP.\nrewrite -dotmulvv; move/orthogonalP : MSO => /(_ i i) ->; by rewrite eqxx.\nQed.\n\nLemma dot_row_of_O (T : ringType) n M : M \\is 'O[T]_n.+1 -> forall i j,\n  row i M *d row j M = (i == j)%:R.\nProof. by move/orthogonalP. Qed.\n\nLemma norm_col_of_O (T : rcfType) n M : M \\is 'O[T]_n.+1 -> forall i, norm (col i M)^T = 1.\nProof.\nmove=> MSO i.\napply/eqP.\nrewrite -(@eqr_expn2 _ 2) // ?norm_ge0 // expr1n -dotmulvv tr_col dotmulvv.\nby rewrite norm_row_of_O ?expr1n // orthogonalV.\nQed.\n\nLemma orth_preserves_sqr_norm (T : comRingType) n M : M \\is 'O[T]_n.+1 ->\n  {mono (fun u => u *m M) : x / x *d x}.\nProof.\nmove=> HM u; rewrite dotmul_trmx -mulmxA (_ : M *m _ = 1%:M) ?mulmx1 //.\nby move: HM; rewrite orthogonalE => /eqP.\nQed.\n\nLemma orth_preserves_dotmul {T : numDomainType} n (f : 'M[T]_n.+1) :\n  {mono (fun u => u *m f) : x y / x *d y} <-> f \\is 'O[T]_n.+1.\nProof.\nsplit => H.\n  apply/orthogonalP => i j.\n  by rewrite 2!rowE H dotmul_delta_mx mxE eqxx /= eq_sym.\nmove=> u v.\nhave := orth_preserves_sqr_norm H (u + v).\nrewrite mulmxDl dotmulD.\nrewrite dotmulD.\nrewrite orth_preserves_sqr_norm // (orth_preserves_sqr_norm H v) //.\nmove/(congr1 (fun x => x - v *d v)).\nrewrite -!addrA subrr 2!addr0.\nmove/(congr1 (fun x => - (u *d u) + x)).\nrewrite !addrA (addrC (- (u *d u))) subrr 2!add0r.\nrewrite -2!mulr2n => /eqP.\nby rewrite eqr_pmuln2r // => /eqP.\nQed.\n\nLemma orth_preserves_norm (T : rcfType) n M : M \\is 'O[T]_n.+1 ->\n  {mono (fun u => u *m M) : x / norm x }.\nProof. move=> HM v; by rewrite /norm (proj2 (orth_preserves_dotmul M) HM). Qed.\n\nLemma Oij_ub (T : rcfType) n (M : 'M[T]_n.+1) : M \\is 'O[T]_n.+1 -> forall i j, `| M i j | <= 1.\nProof.\nmove=> /norm_row_of_O MO i j; rewrite leNgt; apply/negP => abs.\nmove: (MO i) => /(congr1 (fun x => x ^+ 2)); apply/eqP.\nrewrite gt_eqF // sqr_norm (bigD1 j) //= !mxE -(addr0 (1 ^+ 2)) ltr_le_add //.\nby rewrite -(sqr_normr (M _ _)) ltr_expn2r.\nrewrite sumr_ge0 // => k ij; by rewrite sqr_ge0.\nQed.\n\nLemma O_tr_idmx (T : rcfType) n (M : 'M[T]_n.+1) : M \\is 'O[T]_n.+1 -> \\tr M = n.+1%:R -> M = 1.\nProof.\nmove=> MO; move: (MO) => /norm_row_of_O MO' tr3.\nhave Mdiag : forall i, M i i = 1.\n  move=> i; apply/eqP/negPn/negP => Mii; move: tr3; apply/eqP.\n  rewrite lt_eqF // /mxtrace.\n  rewrite (bigD1 i) //=.\n  rewrite (eq_bigr (fun i : 'I_n.+1 => M (inord i) (inord i))); last first.\n    by move=> j _; congr (M _ _); apply val_inj => /=; rewrite inordK.\n  rewrite -(big_mkord [pred x : nat | x != i] (fun i => M (inord i) (inord i))).\n  rewrite -[in n.+1%:R](card_ord n.+1) -sum1_card (bigD1 i) //= natrD.\n  rewrite ltr_le_add //; first by rewrite lt_neqAle Mii /= ler_norml1 // Oij_ub.\n  rewrite [in X in _ <= X](@big_morph _ _ _ 0 (fun x y => x + y)%R) //; last first.\n    by move=> x y; rewrite natrD.\n  rewrite -(big_mkord [pred x : nat | x != i] (fun i => 1)).\n  apply ler_sum => j ji; by rewrite ler_norml1 // Oij_ub.\napply/matrixP => i j; rewrite !mxE.\ncase/boolP : (i == j) => [/eqP ->|ij]; first by move : Mdiag => /(_ j).\nmove: (MO' i) => /(congr1 (fun x => x ^+ 2)).\nrewrite expr1n sqr_norm (bigD1 i) //= mxE.\nmove: Mdiag => /(_ i) -> /eqP.\nrewrite expr1n addrC eq_sym -subr_eq subrr eq_sym psumr_eq0 /=; last first.\n  by move=> *; rewrite sqr_ge0.\nby move/allP => /(_ j (mem_index_enum _)); rewrite eq_sym ij implyTb mxE sqrf_eq0 => /eqP.\nQed.\n\nSection Crossproduct.\nVariable (R : comRingType) (n' : nat).\nLet n := n'.+1.\n\nDefinition cross (u : 'M[R]_(n', n)) : 'rV_n :=\n  \\row_(k < n) \\det (col_mx (@delta_mx _ 1%N _ 0 k) u).\n\nLemma cross_multilinear (A B C : 'M_(n',n)) (i0 : 'I_n') (b c : R) :\n row i0 A = b *: row i0 B + c *: row i0 C ->\n row' i0 B = row' i0 A ->\n row' i0 C = row' i0 A -> cross A = b *: cross B + c *: cross C.\nProof.\nmove=> rABC rBA rCA; apply/rowP=> k; rewrite !mxE.\nhave bumpD (i k1 : 'I_n') : bump (bump 0 i0) i = (1 + k1)%N -> i0 != k1.\n  move=> Bi; apply/eqP => i0Ek1; move: Bi; rewrite -i0Ek1.\n  rewrite /bump !add1n; case: ltnP => [u0Li He|iLi0 He].\n    by rewrite -He leqNgt ltnS leqnn in u0Li.\n  by rewrite -ltnS -He ltnn in iLi0.\napply: (@determinant_multilinear _ _ _ _ _ (fintype.lift 0 i0)).\n-apply/rowP => i; rewrite !mxE; case: fintype.splitP; first by do 2 case.\n  move=> k1 H; rewrite (_ : k1 = i0).\n    by move/rowP : rABC => /(_ i); rewrite !mxE.\n  apply/val_eqP/eqP=> /=.\n  by rewrite /= /bump !add1n in H; case: H.\n- apply/matrixP => i j; rewrite !mxE /=; case: fintype.splitP => // k1 /= H1.\n  have /unlift_some[k2 k2E _] := bumpD i k1 H1.\n  by move/matrixP : rBA => /(_ k2 j); rewrite !mxE k2E.\napply/matrixP => i j; rewrite !mxE /=; case: fintype.splitP => // k1 /= H1.\nhave /unlift_some[k2 k2E _] := bumpD i k1 H1.\nby move/matrixP : rCA => /(_ k2 j); rewrite !mxE k2E.\nQed.\n\nLemma dot_cross (u : 'rV[R]_n) (V : 'M[R]_(n', n)) :\n  u *d (cross V) = \\det (col_mx u V).\nProof.\nrewrite dotmulE (expand_det_row _ 0); apply: eq_bigr => k _; rewrite !mxE /=.\ncase: fintype.splitP => j //=; rewrite ?ord1 //= => _ {j}; congr (_ * _).\nrewrite (expand_det_row _ 0) (bigD1 k) //= big1 ?addr0; last first.\n  move=> i neq_ik; rewrite !mxE; case: fintype.splitP=> //= j.\n  by rewrite ord1 mxE (negPf neq_ik) mul0r.\nrewrite !mxE; case: fintype.splitP => //= j _; rewrite ord1 !mxE !eqxx mul1r.\nrewrite !expand_cofactor; apply: eq_bigr => s s0; congr (_ * _).\napply: eq_bigr => i; rewrite !mxE.\nby case: fintype.splitP => //= j'; rewrite ord1 {j'} -val_eqE => /= ->.\nQed.\n\nEnd Crossproduct.\n\nSection Crossproduct_fieldType.\nVariable (F : fieldType) (n' : nat).\nLet n := n'.+1.\n\nLemma cross_normal (A : 'M[F]_(n', n)) : A _|_ cross A.\nProof.\napply/rV_subP => v /submxP [M ->]; rewrite normalvv dot_cross; apply/det0P.\nexists (row_mx (- 1) M); rewrite ?row_mx_eq0 ?oppr_eq0 ?oner_eq0 //.\nby rewrite mul_row_col mulNmx mul1mx addNr.\nQed.\n\nEnd Crossproduct_fieldType.\n\nSection row2.\nVariable R : ringType.\n\nDefinition row2 (a b : R) : 'rV[R]_2 :=\n  \\row_p [eta \\0 with 0 |-> a, 1 |-> b] p.\n\nLemma row2_of_row (M : 'M[R]_2) i : row i M = row2 (M i 0) (M i 1).\nProof. by apply/rowP=> j; rewrite !mxE /=; case: ifPn=> [|/ifnot01P]/eqP->. Qed.\n\nEnd row2.\n\nSection row3.\nVariable R : ringType.\nImplicit Types a b c : R.\n\nDefinition row3 a b c : 'rV[R]_3 :=\n  \\row_p [eta \\0 with 0 |-> a, 1 |-> b, 2%:R |-> c] p.\n\nLemma row3K (u : 'rV[R]_3) : u = row3 u``_0 u``_1 u``_(2%:R).\nProof. by apply/row3P/and3P; split; rewrite !mxE. Qed.\n\nLemma col_row3 a b c i : col i (row3 a b c) = ((row3 a b c) ``_ i)%:M.\nProof. by apply/rowP => k; rewrite (ord1 k) !mxE /= mulr1n. Qed.\n\nLemma row_mx_colE n (M : 'M[R]_(n, 3)) :\n  row_mx (col 0 M) (row_mx (col 1 M) (col 2%:R M)) = M.\nProof.\nrewrite -[in RHS](@hsubmxK _ n 1 2 M) (_ : lsubmx _ = col 0 M); last first.\n  apply/colP => i; rewrite !mxE /= (_ : lshift 2 0 = 0) //; exact/val_inj.\nrewrite (_ : rsubmx _ = row_mx (col 1 M) (col 2%:R M)) //.\nset a := rsubmx _; rewrite -[in LHS](@hsubmxK _ n 1 1 a); congr row_mx.\n  apply/colP => i; rewrite !mxE /= (_ : rshift 1 _ = 1) //; exact/val_inj.\napply/colP => i; rewrite !mxE /= (_ : rshift 1 (rshift 1 0) = 2%:R) //.\nexact/val_inj.\nQed.\n\nLemma row3E a b c : row3 a b c = row_mx a%:M (row_mx b%:M c%:M).\nProof. by rewrite -[LHS]row_mx_colE !col_row3 !mxE. Qed.\n\nLemma row_row3 n (M : 'M[R]_(n, 3)) i : row i M = row3 (M i 0) (M i 1) (M i 2%:R).\nProof.\nby apply/rowP=> k; rewrite !mxE /=; case: ifPn=>[|/ifnot0P/orP[]]/eqP->.\nQed.\n\nLemma row3N a b c : - row3 a b c = row3 (- a) (- b) (- c).\nProof.\napply/rowP => i; rewrite !mxE /= ; case: ifPn; rewrite ?opprB // => ?.\nby case: ifPn; rewrite ?opprB // => ?; case: ifPn; rewrite ?opprB // oppr0.\nQed.\n\nLemma row3Z a b c k : k *: row3 a b c = row3 (k * a) (k * b) (k * c).\nProof.\napply/rowP => i; rewrite !mxE /=.\ncase: ifPn => // ?; case: ifPn => // ?; case: ifPn => // ?; by Simp.r.\nQed.\n\nLemma row3D a b c a' b' c' :\n  row3 a b c + row3 a' b' c' = row3 (a + a') (b + b') (c + c').\nProof.\nrewrite 3!row3E (add_row_mx a%:M) (add_row_mx b%:M).\nrewrite -(scalemx1 _ a) -(scalemx1 _ a') -(scalemx1 _ b) -(scalemx1 _ b').\nrewrite -(scalemx1 _ c) -(scalemx1 _ c'); by do 3! rewrite -scalerDl scalemx1.\nQed.\n\nLemma row30 : row3 0 0 0 = 0 :> 'rV[R]_3.\nProof. by apply/rowP => a; rewrite !mxE /=; do 3 case: ifPn => //. Qed.\n\nLemma row3_proj (u : 'rV[R]_3) :\n  u = row3 (u``_0) 0 0 + row3 0 (u``_1) 0 + row3 0 0 (u``_2%:R).\nProof.\nrewrite 2!row3D !(addr0,add0r); apply/rowP => k; by rewrite -row_row3 mxE.\nQed.\n\nLemma e0row : 'e_0 = row3 1 0 0.\nProof.\nby apply/rowP=> i; rewrite !mxE /=; case: ifPn=> //;\n  rewrite ifnot0=> /orP[]/eqP ->.\nQed.\n\nLemma e1row : 'e_1 = row3 0 1 0.\nProof.\nby apply/rowP => i; rewrite !mxE /=; case: ifPn => [/eqP -> //|];\n  rewrite ifnot0=> /orP[]/eqP ->.\nQed.\n\nLemma e2row : 'e_2%:R = row3 0 0 1.\nProof.\nby apply/rowP => i; rewrite !mxE /=; case: ifPn => [/eqP -> //|];\n  rewrite ifnot0=> /orP[]/eqP ->.\nQed.\n\nLemma row3e0 a : row3 a 0 0 = a *: 'e_0.\nProof. by rewrite e0row row3Z mulr1 mulr0. Qed.\n\nLemma row3e1 a : row3 0 a 0 = a *: 'e_1.\nProof. by rewrite e1row row3Z mulr1 mulr0. Qed.\n\nLemma row3e2 a : row3 0 0 a = a *: 'e_2%:R.\nProof. by rewrite e2row row3Z mulr1 mulr0. Qed.\n\nEnd row3.\n\nLemma norm_row3z (T : rcfType) (z : T) : norm (row3 0 0 z) = `|z|.\nProof. by rewrite /norm dotmulE sum3E !mxE /= ?(mul0r,add0r) sqrtr_sqr. Qed.\n\nSection col_mx2.\nVariable (T : ringType).\nImplicit Types (u v : 'rV[T]_2) (M : 'M[T]_2).\n\nDefinition col_mx2 u v := \\matrix_(i < 2) [eta \\0 with 0 |-> u, 1 |-> v] i.\n\nLemma eq_col_mx2 a a' b b' c c' d d' :\n  col_mx2 (row2 a b) (row2 c d) = col_mx2 (row2 a' b') (row2 c' d') ->\n  [/\\ a = a', b = b', c = c' & d = d'].\nProof.\nmove/matrixP => H; split; by [\n  move/(_ 0 0) : H; rewrite !mxE | move/(_ 0 1) : H; rewrite !mxE |\n  move/(_ 1 0) : H; rewrite !mxE | move/(_ 1 1) : H; rewrite !mxE].\nQed.\n\nLemma col_mx2_rowE M : M = col_mx2 (row 0 M) (row 1 M).\nProof.\napply/row_matrixP => i; by rewrite rowK /=; case: ifPn => [|/ifnot01P]/eqP->.\nQed.\n\nLemma mul_col_mx2 n (c1 c2 : 'cV[T]_n) u v :\n  row_mx c1 c2 *m col_mx2 u v =\n  row_mx (c1 *m u``_0%:M + c2 *m v``_0%:M) (c1 *m u``_1%:M + c2 *m v``_1%:M).\nProof.\nsuff -> : col_mx2 u v = @block_mx _ 1 1 1 1 u``_0%:M u``_1%:M v``_0%:M v``_1%:M.\n  by rewrite (mul_row_block c1 c2 u``_0%:M).\napply/matrixP => a b; case/boolP : (a == 0) => a0.\n- case/boolP : (b == 0) => b0.\n  + rewrite (eqP a0) (eqP b0) !mxE /= split1 unlift_none //=.\n    by rewrite !mxE split1 unlift_none /= !mxE eqxx mulr1n.\n  + have /eqP b1 : b == 1 by rewrite -ifnot01.\n    rewrite b1 (eqP a0) [in LHS]mxE /=.\n    transitivity ((block_mx u``_0%:M u``_1%:M v``_0%:M v``_1%:M)\n                    (lshift 1 0) (rshift 1 0)); last by f_equal; exact/val_inj.\n    by rewrite block_mxEur mxE eqxx mulr1n.\n- have a1 : a == 1 by rewrite -ifnot01.\n  case/boolP : (b == 0) => b0.\n  + rewrite (eqP a1) (eqP b0) [in LHS]mxE /=.\n    transitivity ((block_mx u``_0%:M u``_1%:M v``_0%:M v``_1%:M)\n                    (rshift 1 0) (lshift 1 0)); last by f_equal; exact/val_inj.\n    by rewrite block_mxEdl mxE eqxx mulr1n.\n  + have /eqP b1 : b == 1 by rewrite -ifnot01.\n    rewrite (eqP a1) b1 [in LHS]mxE /=.\n    transitivity ((block_mx u``_0%:M u``_1%:M v``_0%:M v``_1%:M)\n      (rshift 1 0) (rshift 1 0)); last by f_equal; exact/val_inj.\n    by rewrite block_mxEdr mxE eqxx mulr1n.\nQed.\n\nEnd col_mx2.\n\nSection col_mx3.\nVariable (T : ringType).\nImplicit Types (u v w : 'rV[T]_3) (M : 'M[T]_3).\n\nDefinition col_mx3 u v w :=\n  \\matrix_(i < 3) [eta \\0 with 0 |-> u, 1 |-> v, 2%:R |-> w] i.\n\nLemma trmx_col_mx3_row3 (a b c e f g h i j : T) :\n  (col_mx3 (row3 a b c) (row3 e f g) (row3 h i j))^T =\n   col_mx3 (row3 a e h) (row3 b f i) (row3 c g j).\nProof. by apply/matrix3P/and9P; split; rewrite !mxE. Qed.\n\nLemma col_mx3_row M : col_mx3 (row 0 M) (row 1 M) (row 2%:R M) = M.\nProof.\nby apply/row_matrixP=> i; rewrite rowK /=; case: ifPn=> [|/ifnot0P/orP[]]/eqP->.\nQed.\n\nLemma mulmx_row3_col3 a b c u v w :\n  row3 a b c *m col_mx3 u v w = a *: u + b *: v + c *: w.\nProof. apply/rowP => n; by rewrite !mxE sum3E !mxE. Qed.\n\nLemma col_mx3E u v w : col_mx3 u v w = col_mx u (col_mx v w).\nProof.\nrewrite -[LHS]col_mx3_row; apply/row_matrixP => i; rewrite !rowK /=.\ncase: ifPn => [|/ifnot0P/orP[]]/eqP->.\n- by rewrite (_ : 0 = @lshift 1 _ 0) ?(@rowKu _ 1) ?row_id //; exact: val_inj.\n- rewrite (_ : 1 = @rshift 1 _ 0) ?(@rowKd _ 1); last exact: val_inj.\n  by rewrite  (_ : 0 = @lshift 1 _ 0) ?(@rowKu _ 1) ?row_id //; exact: val_inj.\n- rewrite (_ : 2%:R = @rshift 1 _ 1) ?(@rowKd _ 1); last exact: val_inj.\n  by rewrite (_ : 1 = @rshift 1 1 0) ?(@rowKd _ 1) ?row_id //; exact: val_inj.\nQed.\n\nLemma row'_col_mx3 (i : 'I_3) (u v w : 'rV[T]_3) :\n  row' i (col_mx3 u v w) = [eta \\0 with\n  0 |-> \\matrix_(k < 2) [eta \\0 with 0 |-> v, 1 |-> w] k,\n  1 |-> \\matrix_(k < 2) [eta \\0 with 0 |-> u, 1 |-> w] k,\n  2%:R |-> \\matrix_(k < 2) [eta \\0 with 0 |-> u, 1 |-> v] k] i.\nProof.\ncase: i => [[|[|[|?]]]] ?; apply/matrixP=> [] [[|[|[|?]]]] ? j;\nby rewrite !mxE.\nQed.\n\nLemma col_mx3_perm_12 u v w : xrow 1 2%:R (col_mx3 u v w) = col_mx3 u w v.\nProof.\napply/matrixP => -[[|[|[] //]] ?] [[|[|[] //]] ?]; by rewrite !mxE permE.\nQed.\n\nLemma col_mx3_perm_01 u v w : xrow 0 1 (col_mx3 u v w) = col_mx3 v u w.\nProof.\napply/matrixP => -[[|[|[] //]] ?] [[|[|[] //]] ?]; by rewrite !mxE permE.\nQed.\n\nLemma col_mx3_perm_02 u v w : xrow 0 2%:R (col_mx3 u v w) = col_mx3 w v u.\nProof.\napply/matrixP => -[[|[|[] //]] ?] [[|[|[] //]] ?]; by rewrite !mxE permE.\nQed.\n\nLemma col_mx3_mul M u v w :\n  col_mx3 (u *m M) (v *m M) (w *m M) = col_mx3 u v w * M.\nProof.\nby apply/matrixP => i j; move: i => -[[|[|[] // ]] ?];\n  rewrite !mxE; apply eq_bigr => /= ? _; rewrite mxE.\nQed.\n\nLemma mul_tr_col_mx3 (v : 'rV[T]_3) a b c :\n  v *m (col_mx3 a b c)^T = row3 (v *d a) (v *d b) (v *d c).\nProof.\nrewrite col_mx3E (tr_col_mx a) (tr_col_mx b) (mul_mx_row v a^T).\nby rewrite row3E (mul_mx_row v b^T) 3!dotmulP.\nQed.\n\nEnd col_mx3.\n\n(* extra? *)\nLemma vec3E (T : ringType) (u : 'rV[T]_3) :\n  u = (u``_0) *: 'e_0 + (u``_1) *: 'e_1 + (u``_2%:R) *: 'e_2%:R.\nProof. rewrite [LHS]row3_proj e0row e1row e2row !row3Z. by Simp.r. Qed.\n\nLemma mx_lin1K (T : ringType) (Q : 'M[T]_3) : lin1_mx (mx_lin1 Q) = Q.\nProof. apply/matrix3P; by rewrite !mxE !sum3E !mxE !eqxx /=; Simp.r. Qed.\n\nLemma mxtrace_sqr (T : comRingType) (M : 'M[T]_3) : \\tr (M ^+ 2) =\n  \\sum_i (M i i ^+2) + M 0 1 * M 1 0 *+ 2 + M 0 2%:R * M 2%:R 0 *+ 2 +\n  M 1 2%:R * M 2%:R 1 *+ 2.\nProof.\nrewrite sum3E.\ntransitivity (\\sum_(i < 3) (row i M) *d (col i M)^T).\n  by apply/eq_bigr => i _; rewrite mxE_dotmul_row_col.\nrewrite sum3E !dotmulE !sum3E !mxE -!expr2 -!addrA; congr (_ + _).\ndo 3 rewrite addrC -!addrA; congr (_ + _).\ndo 3 rewrite addrC -!addrA; congr (_ + _).\ncongr (_ + _).\nrewrite addrC -!addrA mulrC; congr (_ + _).\nrewrite addrC -!addrA mulrC; congr (_ + _).\nrewrite addrC -!addrA; congr (_ + _).\nby rewrite mulrC.\nQed.\n(* \\extra? *)\n\nDefinition crossmul {R : ringType} (u v : 'rV[R]_3) :=\n  locked (\\row_(k < 3) \\det (col_mx3 'e_k u v)).\n\nNotation \"*v%R\" := (@crossmul _) : ring_scope.\nNotation \"u *v w\" := (crossmul u w) : ring_scope.\n\nLemma cross3E {R : comRingType} (u v : 'rV[R]_3) :\n  cross (col_mx u v) = u *v v.\nProof.\nrewrite /crossmul; unlock.\nby apply/rowP => /= i; rewrite !mxE col_mx3E.\nQed.\n\nSection crossmullie.\nVariable R : comRingType.\nImplicit Types u v w : 'rV[R]_3.\n\nLemma crossmulE u v : (u *v v) = row3\n  (u``_1 * v``_2%:R - u``_2%:R * v``_1)\n  (u``_2%:R * v``_0 - u``_0 * v``_2%:R)\n  (u``_0 * v``_1 - u``_1 * v``_0).\nProof.\nrewrite /crossmul; unlock.\napply/rowP => i; rewrite !mxE (expand_det_row _ ord0).\nrewrite !(mxE, big_ord_recl, big_ord0) !(mul0r, mul1r, addr0).\nrewrite /cofactor !det_mx22 !mxE /= mul1r mulN1r opprB -signr_odd mul1r.\nby Simp.ord; case: i => [[|[|[]]]] //= ?; rewrite ?(mul1r,mul0r,add0r,addr0).\nQed.\n\nLemma double_crossmul u v w :\n  u *v (v *v w) = (u *d w) *: v - (u *d v) *: w.\nProof.\nsuff aux i : u *d w * v``_i - u *d v * w``_i =\n   u``_(i + 1) * (v``_i * w``_(i + 1) - v``_(i + 1) * w``_i) -\n   u``_(i + 2%:R) * (v``_(i + 2%:R) * w``_i - v``_i * w``_(i + 2%:R)).\n  apply/rowP=> -[[|[|[|?]]] ? //=];\n  by rewrite !crossmulE !mxE /= aux; Simp.ord.\nhave neq_iSi: i + 1 != i by case: i => [[|[|[|?]]] ? //=].\nhave neq_iSSi:  (i + 2%:R != i) && (i + 2%:R != i + 1).\n   by case: i neq_iSi => [[|[|[|?]]] ? //=].\ndo ![rewrite dotmulE (bigD1 i) // (bigD1 (i + 1)) // (bigD1 (i + 2%:R)) //=;\n     rewrite big1 ?mul0r ?addr0 ?mulrDl ?opprD;\n   last by move: i {neq_iSi neq_iSSi}; do 2![move => [[|[|[|?]]] ? //=]]].\nrewrite addrACA mulrAC subrr add0r addrACA -!mulrA -!mulrBr ![w``__ * _]mulrC.\nby congr (_ + _); rewrite -[RHS]mulrN opprB.\nQed.\n\nLemma crossmul_linear u : linear (crossmul u).\nProof.\nmove=> a v w.\nrewrite /crossmul; unlock.\napply/rowP => k; rewrite !mxE.\npose M w := col_mx3 ('e_k) u w.\nrewrite (@determinant_multilinear _ _ (M _) (M v) (M w) 2%:R a 1);\n  rewrite ?row'_col_mx3 ?mul1r ?scale1r ?mxE //=.\nby apply/rowP => j; rewrite !mxE.\nQed.\nCanonical crossmul_is_additive u := Additive (crossmul_linear u).\nCanonical crossmul_is_linear u := AddLinear (crossmul_linear u).\n\nDefinition crossmulr u := crossmul^~ u.\nCanonical RevOp_crossmulr := @RevOp _ _ _ crossmulr (@crossmul R)\n  (fun _ _ => erefl).\n\nLemma crossmulr_linear u : linear (crossmulr u).\nProof.\nmove=> a v w.\nrewrite /crossmulr /crossmul; unlock.\napply/rowP => k; rewrite !mxE.\npose M w := col_mx3 ('e_k) w u.\nrewrite (@determinant_multilinear _ _ _ (M v) (M w) 1%:R a 1);\n  rewrite ?row'_col_mx3 ?mul1r ?scale1r ?mxE //=.\nby apply/rowP => j; rewrite !mxE.\nQed.\nCanonical crossmulr_is_additive u := Additive (crossmulr_linear u).\nCanonical crossmulr_is_linear u := AddLinear (crossmulr_linear u).\nCanonical crossmul_bilinear := [bilinear of (@crossmul R)].\n\nEnd crossmullie.\n\nModule rv3LieAlgebra.\nSection rv3liealgebra.\nVariable R : comRingType.\n\nLemma liexx (u : 'rV[R]_3) : u *v u = 0.\nProof.\napply/rowP=> i.\nrewrite /crossmul; unlock.\nrewrite !mxE (@determinant_alternate _ _ _ 1 2%:R) //.\nby move=> j; rewrite !mxE.\nQed.\n\nLemma jacobi : jacobi_identity (@crossmul R).\nProof.\nmove=> u v w; rewrite 3!double_crossmul.\nrewrite !addrA -(addrA (_ *: v)) (dotmulC u v) -(addrC (_ *: w)) subrr addr0.\nrewrite -!addrA addrC -!addrA (dotmulC w u) -(addrC (_ *: v)) subrr addr0.\nby rewrite addrC dotmulC subrr.\nQed.\n\nDefinition rv3liealgebra_mixin := LieAlgebra.Mixin liexx jacobi.\nDefinition rv3liealgebra_type :=\n  LieAlgebra.Pack (Phant _) (LieAlgebra.Class rv3liealgebra_mixin).\nEnd rv3liealgebra.\nModule Exports.\nCanonical rv3liealgebra_type.\nEnd Exports.\nEnd rv3LieAlgebra.\nImport rv3LieAlgebra.Exports.\n\nSection crossmul_lemmas.\nVariable R : comRingType.\nImplicit Types u v w : 'rV[R]_3.\n\nLemma mulmxl_crossmulr M u v : M *m (u *v v) = u *v (M *m v).\nProof. by rewrite -(mul_rV_lin1 [linear of crossmul u]) mulmxA mul_rV_lin1. Qed.\n\nLemma mulmxl_crossmull M u v : M *m (u *v v) = ((M *m u) *v v).\nProof. by rewrite lieC mulmxN mulmxl_crossmulr -lieC. Qed.\n\nLemma crossmul_triple u v w : u *d (v *v w) = \\det (col_mx3 u v w).\nProof.\npose M (k : 'I_3) : 'M_3 := col_mx3 ('e_k) v w.\npose Mu12 := col_mx3 (u``_1 *: 'e_1 + u``_2%:R *: 'e_2%:R) v w.\nrewrite (@determinant_multilinear _ _ _ (M 0) Mu12 0 (u``_0) 1) ?mul1r\n        ?row'_col_mx3 //; last first.\n  apply/matrixP => i j; rewrite !mxE !eqxx /tnth /=.\n  by case: j => [[|[|[]]]] ? //=; Simp.ord; Simp.r.\nrewrite [\\det Mu12](@determinant_multilinear _ _ _\n  (M 1) (M 2%:R) 0 (u``_1) (u``_2%:R)) ?row'_col_mx3 //; last first.\n  apply/matrixP => i j; rewrite !mxE !eqxx.\n  by case: j => [[|[|[]]]] ? //=; Simp.ord; Simp.r.\nrewrite dotmulE !big_ord_recl big_ord0 addr0 /=.\nrewrite /crossmul; unlock.\nby rewrite !mxE; Simp.ord.\nQed.\n\nLemma nth_crossmul u v i :\n  (u *v v)``_i = u``_(i + 1) * v``_(i + 2%:R) - u``_(i + 2%:R) * v``_(i + 1).\nProof. by case: i => [[|[|[|?]]] ?]; rewrite crossmulE !mxE; Simp.ord. Qed.\n\nLemma crossmul0E u v :\n  (u *v v == 0) =\n  [forall i, [forall j, (i != j) ==> (u``_j * v``_i == u``_i * v``_j)]].\nProof.\napply/eqP/'forall_'forall_implyP; last first.\n  move=> uv_eq_vu; apply/rowP=> k; rewrite nth_crossmul mxE.\n  rewrite (eqP (uv_eq_vu _ _ _)) ?subrr //.\n  by case: k => [[|[|[|?]]] ?] //=.\nmove=> uv_eq0 i j neq_ij; have := nth_crossmul u v (-(i + j)).\nrewrite uv_eq0 !mxE => /(canLR (@addrNK _ _)); rewrite add0r.\nmove: i j neq_ij; do 2![move=> [[|[|[|?]]] ?] //=; Simp.ord => //=];\nby do ?[move=> _ -> //].\nQed.\n\nLemma dotmul_crossmul_shift u v w : u *d (v *v w) = w *d (u *v v).\nProof.\nrewrite crossmul_triple.\nrewrite -col_mx3_perm_12 xrowE det_mulmx det_perm /= odd_tperm /=.\nrewrite -col_mx3_perm_01 xrowE det_mulmx det_perm /= odd_tperm /=.\nby rewrite expr1 mulrA mulrNN 2!mul1r -crossmul_triple.\nQed.\n\nLemma dot_crossmulC u v x : u *d (v *v x) = (u *v v) *d x.\nProof. by rewrite dotmul_crossmul_shift dotmulC. Qed.\n\nLemma dot_crossmulCA u v w : u *d (v *v w) = - v *d (u *v w).\nProof. by do 2 rewrite dot_crossmulC; rewrite linearNl lieC. Qed.\n\nLemma det_crossmul_dotmul M u v w :\n  (\\det M *: (u *v v)) *d w = (((u *m M) *v (v *m M)) *m M^T) *d w.\nProof.\ntransitivity (\\det M * \\det (col_mx3 u v w)).\n  by rewrite dotmulZv -dot_crossmulC crossmul_triple.\nrewrite (mulrC (\\det M)) -det_mulmx mulmxE -col_mx3_mul.\nby rewrite -crossmul_triple dot_crossmulC dotmul_trmx.\nQed.\n\nLemma mulmx_crossmul' M u v : \\det M *: (u *v v) = ((u *m M) *v (v *m M)) *m M^T.\nProof. by apply/rowP=> i; rewrite -!dotmul_delta_mx det_crossmul_dotmul. Qed.\n\nLemma dotmul_crossmul2 u v w : (u *v v) *v (u *v w) = (u *d (v *v w)) *: u.\nProof.\nrewrite double_crossmul dot_crossmulC (dotmulC _ u) dot_crossmulC liexx.\nby rewrite dotmul0v scale0r subr0.\nQed.\n\nLemma crossmul0_dotmul u v : u *v v == 0 -> (u *d v) ^+ 2 = u *d u * (v *d v).\nProof.\nrewrite crossmul0E => uv0.\nrewrite !dotmulE expr2 !big_distrl /=.\napply eq_bigr => i _; rewrite -!mulrA; congr (_ * _).\nrewrite 2!big_distrr /=.\napply eq_bigr => j /= _; rewrite mulrCA !mulrA; congr (_ * _).\ncase/boolP : (i == j) => [/eqP ->|ij]; first by rewrite mulrC.\nmove/forallP : uv0 => /(_ i)/forallP/(_ j).\nby rewrite ij implyTb => /eqP.\nQed.\n\nEnd crossmul_lemmas.\n\nSection comUnit_crossmul.\n\nVariable (T : comUnitRingType).\n\nImplicit Types u v : 'rV[T]_3.\n\nLemma vece2 (i j : 'I_3) (k := - (i + j) : 'I_3) :\n  'e_i *v 'e_j = (-1)^(perm3 i j)%N *+ (i != j) *: 'e_k :> 'rV[T]__.\nProof.\nhave [->|neq_ij] := altP (i =P j); rewrite (mulr0n,mulr1n).\n  by rewrite scale0r liexx.\napply/rowP => k'; case: (I3P k' neq_ij); rewrite /crossmul; unlock; rewrite !mxE.\n- rewrite (@determinant_alternate _ _ _ 0 1) //=.\n    by move: i j @k neq_ij => [[|[|[|?]]] ?] [[|[|[|?]]] ?] //=; rewrite mulr0.\n  by move=> k''; rewrite !mxE.\n- rewrite (@determinant_alternate _ _ _ 0 2%:R) //=.\n    by move: i j @k neq_ij => [[|[|[|?]]] ?] [[|[|[|?]]] ?] //=; rewrite mulr0.\n  by move=> k''; rewrite !mxE.\nrewrite !eqxx mulr1 -[_ ^ _](@det_perm T) {k k'}; congr (\\det _).\napply/matrixP => a b; rewrite !mxE permE ffunE /=.\nby move: a b i j neq_ij; do 4![move=> [[|[|[|?]]] ?]; rewrite ?mxE //=].\nQed.\n\nLemma mulmx_crossmul M u v : M \\is a GRing.unit ->\n  (u *v v) *m (\\det M *: M^-1^T) = (u *m M) *v (v *m M).\nProof.\nmove=> invM.\nmove: (mulmx_crossmul' M u v) => /(congr1 (fun x => x *m M^T^-1)).\nrewrite -mulmxA mulmxV ?unitmx_tr // mulmx1 => <-.\nby rewrite -scalemxAr trmx_inv scalemxAl.\nQed.\n\nEnd comUnit_crossmul.\n\nSection field_crossmul.\n\nVariable (T : fieldType).\n\nImplicit Types u v w : 'rV[T]_3.\n\nLemma crossmul_normal u v : u _|_ (u *v v).\nProof.\nrewrite normalvv crossmul_triple.\nrewrite (determinant_alternate (oner_neq0 _)) => [|i] //.\nby rewrite !mxE.\nQed.\n\nLemma common_normal_crossmul u v : (u *v v) _|_ u + v.\nProof.\nrewrite normalmD ![(_ *v _) _|_ _]normal_sym crossmul_normal.\nby rewrite lieC normalmN crossmul_normal.\nQed.\n\nEnd field_crossmul.\n\nSection orthogonal_crossmul.\n\n(* \"From the geometrical definition, the cross product is invariant under\n   proper rotations about the axis defined by a × b\"\n   https://en.wikipedia.org/wiki/Cross_product *)\nLemma mulmxr_crossmulr (T : realDomainType) r u v : r \\is 'O[T]_3 ->\n  (u *v v) *m r = \\det r *: ((u *m r) *v (v *m r)).\nProof.\nmove=> rO; move: (rO).\nrewrite orthogonalEinv => /andP[r1 /eqP rT].\nrewrite -mulmx_crossmul //.\nmove/eqP: (orthogonal_det rO).\nrewrite eqr_norml // => /andP[ /orP[/eqP-> |/eqP->] _];\n  rewrite ?scale1r rT trmxK //.\nby rewrite -scalemxAr scalerA mulrNN !mul1r scale1r.\nQed.\n\nLemma eigenspace_trmx (T : fieldType) r (Hr : r \\is 'O[T]_3) (n : 'rV[T]_3) :\n  (n <= eigenspace r 1 <-> n <= eigenspace r^T 1)%MS.\nProof.\nmove: (Hr); rewrite orthogonalE => /eqP Hr1.\nmove: Hr; rewrite orthogonalEC => /eqP Hr2.\nsplit.\n  move/eigenspaceP; rewrite scale1r => nrn.\n  apply/eigenspaceP; rewrite scale1r.\n  by rewrite -{1}nrn -mulmxA mulmxE Hr1 mulmx1.\nmove/eigenspaceP; rewrite scale1r => nrn.\napply/eigenspaceP; rewrite scale1r.\nby rewrite -{1}nrn -mulmxA mulmxE Hr2 mulmx1.\nQed.\n\nLemma mulmxr_crossmulr_SO (T : realDomainType) r u v : r \\is 'SO[T]_3 ->\n  (u *v v) *m r = (u *m r) *v (v *m r).\nProof.\nrewrite rotationE => /andP[rO /eqP detr1].\nby rewrite mulmxr_crossmulr // detr1 scale1r.\nQed.\n\nLemma det_rotN1 (T : numDomainType) (M : 'M[T]_3) :\n  M \\is 'SO[T]_3 -> \\det (M - 1) = 0.\nProof.\nmove=> MSO; apply/eqP; rewrite -eqrNxx eq_sym.\nhave {1}-> : M - 1 = - (M *m (M - 1)^T).\n  rewrite raddfD /= raddfN /= trmx1 mulmxDr mulmxN mulmx1.\n  by rewrite orthogonal_mul_tr ?rotation_sub // opprB.\nrewrite -scaleN1r detZ -signr_odd detM det_tr.\nby rewrite [\\det M]rotation_det // mulN1r mul1r.\nQed.\n\nLemma rot_eigen1 (T : numFieldType) (M : 'M[T]_3) :\n  M \\is 'SO[T]_3 -> eigenspace M 1 != 0.\nProof.\nby move=> MS0; rewrite kermx_eq0 row_free_unit unitmxE det_rotN1 ?unitr0.\nQed.\n\nLemma euler (T : numFieldType) (M : 'M[T]_3) : M \\is 'SO[T]_3 ->\n  {x : 'rV[T]_3 | (x != 0) && (x *m M == x)}.\nProof.\nmove=> MSO; apply: sigW; have /rot_eigen1 /rowV0Pn [v v_eigen v_neq0] := MSO.\nby exists v; rewrite v_neq0 (eigenspaceP v_eigen) scale1r eqxx.\nQed.\n\nDefinition vaxis_euler (T : numFieldType) M :=\n  if (M \\is 'SO[T]_3) =P true is ReflectT MSO then sval (euler MSO) else 0.\n\nLemma vaxis_euler_neq0 (T : numFieldType) M :\n  M \\is 'SO[T]_3 -> vaxis_euler M != 0.\nProof.\nmove=> MSO; rewrite /vaxis_euler; case: eqP; last by rewrite MSO.\nmove=> {}MSO; by case: euler => v /= /andP[].\nQed.\n\nLemma vaxis_eulerP (T : numFieldType) M :\n  M \\is 'SO[T]_3 -> vaxis_euler M *m M = vaxis_euler M.\nProof.\nmove=> MSO; rewrite /vaxis_euler; case: eqP; last by rewrite MSO.\nmove=> {}MSO; by case: euler => v /= /andP[_ /eqP].\nQed.\n\nEnd orthogonal_crossmul.\n\nSection norm3.\n\nVariable T : rcfType.\nImplicit Types u : 'rV[T]_3.\n\nLemma norm_crossmul' u v :\n  (norm (u *v v)) ^+ 2 = (norm u * norm v) ^+ 2 - (u *d v) ^+ 2.\nProof.\nrewrite sqr_norm sum3E crossmulE /SimplFunDelta /= !mxE /=.\ntransitivity (((u``_0)^+2 + (u``_1)^+2 + (u``_2%:R)^+2)\n  * ((v``_0)^+2 + (v``_1)^+2 + (v``_2%:R)^+2)\n  - (u``_0 * v``_0 + u``_1 * v``_1 + u``_2%:R * v``_2%:R)^+2).\n  set u0 := u``_0. set v0 := v``_0.\n  set u1 := u``_1. set v1 := v``_1.\n  set u2 := u``_2%:R. set v2 := v``_2%:R.\n  rewrite !sqrrB !mulrDr !mulrDl !sqrrD.\n  set A := u1 * v2. set A' := u2 * v1.\n  set B := u2 * v0. set B' := u0 * v2.\n  set C := u0 * v1. set C' := u1 * v0.\n  set U0 := u0 ^+ 2. set U1 := u1 ^+ 2. set U2 := u2 ^+ 2.\n  set V0 := v0 ^+ 2. set V1 := v1 ^+ 2. set V2 := v2 ^+ 2.\n  rewrite (_ : u0 * v0 * (u1 * v1) = C * C'); last first.\n    rewrite /C /C' -2!mulrA; congr (_ * _).\n    rewrite mulrA mulrC; congr (_ * _); by rewrite mulrC.\n  rewrite mulrDl.\n  rewrite (_ : u0 * v0 * (u2 * v2) = B * B'); last first.\n    rewrite /B /B' [in RHS]mulrC -!mulrA; congr (_ * _).\n    rewrite mulrA -(mulrC v2); congr (_ * _); by rewrite mulrC.\n  rewrite (_ : u1 * v1 * (u2 * v2) = A * A'); last first.\n    rewrite /A /A' -!mulrA; congr (_ * _).\n    rewrite mulrA -(mulrC v2); congr (_ * _); by rewrite mulrC.\n  rewrite (_ : (u0 * v0) ^+ 2 = U0 * V0); last by rewrite exprMn.\n  rewrite (_ : (u1 * v1) ^+ 2 = U1 * V1); last by rewrite exprMn.\n  rewrite (_ : (u2 * v2) ^+ 2 = U2 * V2); last by rewrite exprMn.\n  rewrite 4![in RHS]opprD.\n  (* U0 * V0 *)\n  rewrite -3!(addrA (U0 * V0)) -3![in X in _ = _ + X](addrA (- (U0 * V0))).\n  rewrite [in RHS](addrAC (U0 * V0)) [in RHS](addrA (U0 * V0)) subrr add0r.\n  (* U1 * V1 *)\n  rewrite -(addrC (- (U1 * V1))) -(addrC (U1 * V1)) (addrCA (U1 * V0 + _)).\n  rewrite -3!(addrA (- (U1 * V1))) -![in X in _ = _ + X](addrA (U1 * V1)) addrCA.\n  rewrite [in RHS](addrA (- (U1 * V1))) [in RHS](addrC (- (U1 * V1))) subrr add0r.\n  (* U2 * V2 *)\n  rewrite -(addrC (- (U2 * V2))) -(addrC (U2 * V2)) -(addrC (U2 * V2 + _)).\n  rewrite [in RHS]addrAC 2!(addrA (- (U2 * V2))) -(addrC (U2 * V2)) subrr add0r.\n  (* C * C' ^+ 2 *)\n  rewrite (addrC (C ^+ 2 - _)) ![in LHS]addrA.\n  rewrite (addrC (C * C' *- 2)) ![in RHS]addrA; congr (_ - _).\n  rewrite (_ : U0 * V2 = B' ^+ 2); last by rewrite exprMn.\n  rewrite (_ : U1 * V2 = A ^+ 2); last by rewrite exprMn.\n  rewrite (_ : U0 * V1 = C ^+ 2); last by rewrite exprMn.\n  rewrite (_ : U1 * V0 = C' ^+ 2); last by rewrite exprMn.\n  rewrite (_ : U2 * V0 = B ^+ 2); last by rewrite exprMn.\n  rewrite (_ : U2 * V1 = A' ^+ 2); last by rewrite exprMn.\n  (* B' ^+ 2, A ^+ 2 *)\n  rewrite -(addrC (B' ^+ 2)) -!addrA; congr (_ + (_ + _)).\n  rewrite !addrA.\n  (* B ^+ 2 *)\n  rewrite -2!(addrC (B ^+ 2)) -!addrA; congr (_ + _).\n  rewrite !addrA.\n  (* C ^+ 2 *)\n  rewrite -(addrC (C ^+ 2)) -!addrA; congr (_ + _).\n  rewrite !addrA.\n  (* C' ^+ 2 *)\n  rewrite -(addrC (C' ^+ 2)) -!addrA; congr (_ + _).\n  rewrite !addrA.\n  (* A' ^+ 2 *)\n  rewrite -(addrC (A' ^+ 2)) -!addrA; congr (_ + _).\n  rewrite -!mulNrn !mulr2n !opprD.\n  rewrite addrC -!addrA; congr (_ + _).\n  rewrite addrA.\n  rewrite addrC -!addrA; congr (_ + _).\n  by rewrite addrC.\nrewrite exprMn -(sum3E (fun i => u``_i ^+ 2)) -(sum3E (fun i => v``_i ^+ 2)) -2!sqr_norm; congr (_ - _ ^+ 2).\nby rewrite dotmulE sum3E.\nQed.\n\nLemma orth_preserves_norm_crossmul M : M \\is 'O[T]_3 ->\n  {mono (fun u => u *m M) : x y / norm (x *v y)}.\nProof.\nmove=> MO u v.\nby rewrite -[in RHS](orth_preserves_norm MO) mulmxr_crossmulr // normZ orthogonal_det // mul1r.\nQed.\n\nLemma norm_crossmul_normal u v : u *d v = 0 ->\n  norm u = 1 -> norm v = 1 -> norm (u *v v) = 1.\nProof.\nmove=> uv0 u1 v1; apply/eqP.\nrewrite -(@eqr_expn2 _ 2) // ?norm_ge0 //.\nby rewrite norm_crossmul' u1 v1 uv0 expr0n /= subr0 mulr1 // norm_ge0.\nQed.\n\nLemma dotmul_eq0_crossmul_neq0 (u v : 'rV[T]_3) : u != 0 -> v != 0 -> u *d v == 0 -> u *v v != 0.\nProof.\nmove=> u0 v0 uv0.\nrewrite -norm_eq0 -(@eqr_expn2 _ 2) // ?norm_ge0 // exprnP expr0n -exprnP.\nrewrite norm_crossmul' (eqP uv0) expr0n subr0 -expr0n eqr_expn2 //.\nby rewrite mulf_eq0 negb_or 2!norm_eq0 u0.\nby rewrite mulr_ge0 // ?norm_ge0.\nQed.\n\nEnd norm3.\n\nSection properties_of_canonical_vectors.\n\nLemma normeE (T : rcfType) i : norm ('e_i : 'rV_3) = 1 :> T.\nProof. by rewrite norm_delta_mx. Qed.\n\nVariable T : comRingType.\n\nLemma vecij : 'e_0 *v 'e_1 = 'e_2%:R :> 'rV[T]__.\nProof.\napply/matrixP => i j; rewrite /crossmul; unlock.\nrewrite ord1 !mxE /= det_mx33 !mxE.\nby case: j => [] [|[|[|//]]] /=; Simp.r.\nQed.\n\nLemma vecik : 'e_0 *v 'e_2%:R = - 'e_1 :> 'rV[T]__.\nProof.\napply/matrixP => i j; rewrite /crossmul; unlock.\nrewrite ord1 !mxE /= det_mx33 !mxE.\nby case: j => [] [|[|[|//]]] /=; Simp.r.\nQed.\n\nLemma vecji : 'e_1 *v 'e_0 = - 'e_2%:R :> 'rV[T]__.\nProof.\napply/matrixP => i j; rewrite /crossmul; unlock.\nrewrite ord1 !mxE /= det_mx33 !mxE.\nby case: j => [] [|[|[|//]]] /=; Simp.r.\nQed.\n\nLemma vecjk : 'e_1 *v 'e_2%:R = 'e_0%:R :> 'rV[T]__.\nProof.\napply/matrixP => i j; rewrite /crossmul; unlock.\nrewrite ord1 !mxE /= det_mx33 !mxE.\nby case: j => [] [|[|[|//]]] /=; Simp.r.\nQed.\n\nLemma vecki : 'e_2%:R *v 'e_0 = 'e_1 :> 'rV[T]__.\nProof.\napply/matrixP => i j; rewrite /crossmul; unlock.\nrewrite ord1 !mxE /= det_mx33 !mxE.\nby case: j => [] [|[|[|//]]] /=; Simp.r.\nQed.\n\nLemma veckj : 'e_2%:R *v 'e_1 = - 'e_0 :> 'rV[T]__.\nProof.\napply/matrixP => i j; rewrite /crossmul; unlock.\nrewrite ord1 !mxE /= det_mx33 !mxE.\nby case: j => [] [|[|[|//]]] /=; Simp.r.\nQed.\n\nEnd properties_of_canonical_vectors.\n\nLemma orthogonal3P (T : rcfType) (M : 'M[T]_3) :\n  reflect (M \\is 'O[T]_3)\n  [&& norm (row 0 M) == 1, norm (row 1 M) == 1, norm (row 2%:R M) == 1,\n      row 0 M *d row 1 M == 0, row 0 M *d row 2%:R M == 0 & row 1 M *d row 2%:R M == 0].\nProof.\napply (iffP idP).\n- case/and6P => /eqP ni /eqP nj /eqP nk /eqP xy0 /eqP xz0 /eqP yz0 /=.\n  apply/orthogonalP => i j; case/boolP : (i == 0) => [|/ifnot0P/orP[]]/eqP->.\n  + case/boolP : (j == 0) => [|/ifnot0P/orP[]]/eqP->; by\n      [rewrite dotmulvv ni expr1n | rewrite xy0 | rewrite xz0].\n  + case/boolP : (j == 0) => [|/ifnot0P/orP[]]/eqP->; by\n      [rewrite dotmulC xy0 | rewrite dotmulvv nj expr1n | rewrite yz0].\n  + case/boolP : (j == 0) => [|/ifnot0P/orP[]]/eqP->; by\n      [rewrite dotmulC xz0 | rewrite dotmulC yz0 | rewrite dotmulvv nk expr1n].\n- move/orthogonalP => H; apply/and6P; split; first [\n    by rewrite -(@eqr_expn2 _ 2) // ?norm_ge0 // expr1n -dotmulvv H |\n    by rewrite H ].\nQed.\n\nLemma rotation3P (T : rcfType) (M : 'M[T]_3) :\n  reflect (M \\is 'SO[T]_3)\n  [&& norm (row 0 M) == 1, norm (row 1 M) == 1,\n      row 0 M *d row 1 M == 0 & row 2%:R M == row 0 M *v row 1 M].\nProof.\napply (iffP idP).\n- case/and4P => /eqP ni /eqP nj /eqP xy0 /eqP zxy0 /=.\n  rewrite rotationE; apply/andP; split.\n    apply/orthogonal3P.\n    rewrite ni nj /= zxy0 norm_crossmul_normal // xy0 !eqxx /= dot_crossmulC.\n    by rewrite liexx dotmul0v dot_crossmulCA liexx dotmulv0 !eqxx.\n  rewrite -(col_mx3_row M) -crossmul_triple zxy0 double_crossmul dotmulvv nj expr1n.\n  by rewrite scale1r (dotmulC (row 1 M)) xy0 scale0r subr0 dotmulvv ni expr1n.\n- move=> MSO; move: (MSO).\n  rewrite rotationE => /andP[/orthogonal3P/and6P[ni nj nk ij ik jk]].\n  by rewrite ni nj ij /= => _; rewrite !rowE -mulmxr_crossmulr_SO // vecij.\nQed.\n\nLemma SO_icrossj (T : rcfType) (r : 'M[T]_3) : r \\is 'SO[T]_3 ->\n  row 0 r *v row 1 r = row 2%:R r.\nProof. by case/rotation3P/and4P => _ _ _ /eqP ->. Qed.\n\nLemma SO_icrossk (T : rcfType) (r : 'M[T]_3) : r \\is 'SO[T]_3 ->\n  row 0 r *v row 2%:R r = - row 1 r.\nProof.\ncase/rotation3P/and4P => /eqP H1 _ /eqP H3 /eqP ->.\nby rewrite double_crossmul H3 scale0r add0r dotmulvv H1 expr1n scale1r.\nQed.\n\nLemma SO_jcrossk (T : rcfType) (r : 'M[T]_3) : r \\is 'SO[T]_3 ->\n  row 1 r *v row 2%:R r = row 0 r.\nProof.\ncase/rotation3P/and4P => _ /eqP H1 /eqP H3 /eqP ->.\nby rewrite double_crossmul dotmulvv H1 expr1n scale1r dotmulC H3 scale0r subr0.\nQed.\n\nSection characteristic_polynomial_dim3.\n\nVariable T : numFieldType.\n\n(* Cyril: a shorter proof of this fact goes through the\ntrigonalisation of complex matrice. Indeed, M = PTP^-1 with P unit and\nT triangular of diagonal x, y, z. Then\nchar_poly M = (X - x)(X - y)(X - z) =\nX³ - (x + y + z)X² + (xy + yz + zx)X  - xyz.\nBut tr M = tr T = x + y + z and tr M² = tr T² = x² + y² + z²,\nthen (tr M)² = (x + y + z)² = tr M² + 2(xy + yz + zx)\nthus: xy + yz + zx = 1/2 * ((tr M)² - tr M²) *)\nLemma char_poly3_coef1 (M : 'M[T]_3) :\n  let Z := 1 / 2%:R * (\\tr M ^+ 2 - \\tr (M ^+ 2)) in\n  (char_poly M)`_1 = Z.\nProof.\nmove=> Z.\nrewrite /char_poly /char_poly_mx det_mx33 !mxE mulr1n mulr0n !add0r.\nrewrite !mulNr !mulrN !opprK.\nrewrite !coefD.\n(* 1 *)\nrewrite [X in X + _ + _](_ : _ = M 0 0 * (M 2%:R 2%:R + M 1 1) +\n   (M 1 1 * M 2%:R 2%:R - M 2%:R 1 * M 1 2%:R)); last first.\n  rewrite coefM sum2E coefD coefX add0r coefN coefC [- _]/=.\n  rewrite subn0 coefD.\n  rewrite coefM sum2E subn0 coefD coefX add0r coefN (_ : _`_0 = M 1 1); last by rewrite coefC.\n  rewrite coefD coefX coefN coefC subr0 mulr1.\n  rewrite coefD coefN coefX coefN coefC subr0 mul1r.\n  rewrite subnn coefD coefX add0r coefN coefC [in X in - M 1 1 - X]/=.\n  rewrite coefM sum2E coefC coefC mulr0 add0r coefC mul0r subr0.\n  rewrite coefD coefX coefN coefC subr0 mul1r.\n  rewrite coefD coefM sum1E coefD coefX add0r coefN coefC [in X in - X * _`_ _]/=.\n  rewrite coefD coefX add0r coefN coefC mulrN !mulNr opprK.\n  rewrite coefN coefM sum1E coefC coefC [in X in M 1 1 * _ - X]/=.\n  by rewrite -opprB mulrN 2!opprK.\nrewrite [X in _ + X + _](_ : _ = - M 0 1 * M 1 0); last first.\n  rewrite coefN coefM sum2E coefC [in X in X * _]/= subnn.\n  rewrite coefD subn0 coefM sum2E.\n  rewrite subn0 subnn coefC coefC mulr0 add0r.\n  rewrite coefC mul0r add0r.\n  rewrite coefM sum2E subn0 subnn coefC coefD coefX coefN coefC subr0 mulr1.\n  rewrite coefC mul0r addr0 coefC mul0r addr0.\n  by rewrite mulNr.\nrewrite [X in _ + _ + X](_ : _ = - M 0 2%:R * M 2%:R 0); last first.\n  rewrite coefN coefM sum2E subn0 subnn coefC.\n  rewrite [in X in X * _]/=.\n  rewrite coefD coefM sum2E subn0 coefC coefC mulr0 add0r.\n  rewrite coefC mul0r add0r coefM sum2E subn0 subnn coefC [in X in X * _`_1]/=.\n  by rewrite coefD coefX coefN coefC subr0 mulr1 coefC mul0r addr0 coefC mul0r addr0 mulNr.\nrewrite /Z.\napply/(@mulrI _ 2%:R); first exact: pnatf_unit.\nrewrite mulrA div1r divrr ?pnatf_unit // mul1r.\nrewrite sqr_mxtrace.\nrewrite mxtrace_sqr.\nrewrite -4![in RHS]addrA [in RHS]addrCA [in RHS]opprD [in RHS](addrA (\\sum__ M _ _ ^+ 2)) subrr add0r.\nrewrite -3!mulrnDl -mulrnBl -[in RHS](mulr_natr _ 2) [in RHS](mulrC _ 2%:R); congr (_ * _).\nrewrite mulrDr.\nrewrite (addrC _ (M 0 0 * _)); rewrite -!addrA; congr (_ + _).\nrewrite !addrA -mulrDl -!addrA; congr (_ + _).\nrewrite addrCA opprD mulNr; congr (_ + _).\nrewrite opprD addrC mulNr; congr (_ + _).\nby rewrite mulrC.\nQed.\n\nLemma char_poly3 (M : 'M[T]_3) :\n  let Z := 1 / 2%:R * ((\\tr M) ^+ 2 - \\tr (M ^+ 2)) in\n  char_poly M = 'X^3 - (\\tr M) *: 'X^2 + Z *: 'X - (\\det M)%:P.\nProof.\nmove=> Z.\nrewrite -(coefK (char_poly M)) (size_char_poly M).\napply/polyP.\ncase. (* coef0 *)\n  rewrite coef_poly char_poly_det !coef_add_poly !coef_opp_poly !coefZ.\n  rewrite !coefX !coefXn add0r mulr0 oppr0 mulr0 add0r add0r coefC /=.\n  by rewrite exprS sqrrN expr1n mulr1 mulN1r.\ncase; last first.\n  case. (* coef2 *)\n    rewrite coef_poly !coef_add_poly !coef_opp_poly !coefZ !coefX !coefXn.\n    by rewrite add0r mulr0 mulr1 addr0 coefC subr0 char_poly_trace.\n  case; last first. (* coef n >= 4 *)\n    move=> n.\n    rewrite coef_poly !coef_add_poly !coef_opp_poly !coefZ !coefX !coefXn.\n    by rewrite add0r mulr0 mulr0 coefC subr0 addr0 oppr0.\n  (* coef3 *)\n  rewrite coef_poly !coef_add_poly !coef_opp_poly !coefZ !coefX !coefXn.\n  rewrite mulr0 subr0 mulr0 addr0 coefC subr0; apply/eqP.\n  rewrite (_ : _`_3 = lead_coef (char_poly M)); last first.\n    by rewrite lead_coefE size_char_poly.\n  by rewrite -monicE char_poly_monic.\n(* coef1 *)\nrewrite coef_poly !coef_add_poly !coef_opp_poly !coefZ !coefX !coefXn.\nrewrite add0r mulr1 mulr0 oppr0 add0r coefC subr0.\nsuff : (char_poly M)`_1 = Z by move=> ->.\nby rewrite char_poly3_coef1.\nQed.\n\nEnd characteristic_polynomial_dim3.\n", "meta": {"author": "affeldt-aist", "repo": "coq-robot", "sha": "5c7b536dc17748f3a397995f04cec7f99bca402b", "save_path": "github-repos/coq/affeldt-aist-coq-robot", "path": "github-repos/coq/affeldt-aist-coq-robot/coq-robot-5c7b536dc17748f3a397995f04cec7f99bca402b/euclidean.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.6757057759025124}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Examples for LibFix                                                     *\n**************************************************************************)\n\nSet Implicit Arguments.\nGeneralizable Variables A B.\nFrom TLC Require Import LibTactics LibLogic LibReflect LibFun LibEpsilon LibList\n  LibInt LibNat LibProd LibSum LibRelation LibWf LibFix LibStream.\nRequire Coq.Arith.Even. (* for demo *)\nOpen Scope nat_scope.\nOpen Scope comp_scope.\nOpen Scope fun_scope.\n\n(** Setting up of automation *)\n\nHint Resolve wf_lt : wf.\n\nLtac auto_tilde ::= auto with wf.\nLtac auto_star ::= try solve [ auto | false | math | intuition eauto ].\n\nHint Resolve equiv_eq equiv_list_equiv.\n\n\n(* ********************************************************************** *)\n(** * The log function -- basic recursion *)\n\n(** Properties of div2 *)\n\nLemma div2_lt : forall n m, m <= n -> n > 0 -> Nat.div2 m < n.\nProof using. (* using stdlib *)\n  nat_comp_to_peano. introv Le Gt.\n  forwards: Nat.div2_decr m (n-1). omega. omega.\nQed.\n\nLemma div2_grows : forall n m, m <= n -> Nat.div2 m <= Nat.div2 n.\nProof using.\n  nat_comp_to_peano.\n  induction n using peano_induction. introv Le.\n  destruct~ m. simpl. omega.\n  destruct~ n. simpl. omega.\n  destruct~ m. simpl. omega.\n  destruct~ n. simpl. omega.\n  simpl. forwards~: H n m. nat_math. nat_math. nat_math.\nQed.\n\nModule LogBasic.\n\n(** Definition of the functional *)\n\nDefinition Log log n :=\n If n <= 1 then 0 else 1 + log (Nat.div2 n).\n\n(** Construction of the fixed point *)\n\nDefinition log := FixFun Log.\n\nLemma fix_log : forall n,\n  log n = Log log n.\nProof using.\n  applys~ (FixFun_fix (@lt nat _)).\n  introv H. unfolds. case_if~.\n  fequals. apply H. apply* div2_lt.\nQed.\n\n(** Example of unfolding of the body *)\n\nLemma log_double : forall n, n > 0 ->\n  log(2*n) = 1 + log n.\nProof using.\n  introv Pos. rewrite fix_log. unfold Log.\n  case_if*. fequals. rewrite~ Nat.div2_double.\nQed.\n\n(** Example of reasoning by induction *)\n\nLemma log_grows : forall n m,\n  m <= n -> log m <= log n.\nProof using.\n  induction n using peano_induction. introv Le.\n  do 2 rewrite fix_log. unfolds Log.\n  (do 2 case_if); autos*.\n  forwards: H (Nat.div2 n) (Nat.div2 m).\n    apply* div2_lt. apply~ div2_grows.\n  math.\nQed.\n\n(*\nExtraction Language Ocaml.\nExtraction Inline Log.\nSet Extraction Optimize.\nExtraction log.\n*)\n\nEnd LogBasic.\n\n\n(* ********************************************************************** *)\n(** * The log function, version that computes *)\n\nModule LogCompute.\n(** Example of computing inside Coq *)\n\nDefinition Log log n :=\n  if le_dec n 1 then 0 else 1 + log (Nat.div2 n).\n\nDefinition log := FixFun Log.\n\nLemma fix_log : forall N n,\n  log n = func_iter N Log log n.\nProof using.\n  applys~ (FixFun_fix_iter (@lt nat _)).\n  introv H. unfolds. case_if~.\n  fequals. apply H. apply* div2_lt.\nQed.\n\nDefinition many_steps := 10.\n\nLemma log_compute : log 256 = 8.\nProof using.\n  rewrite (@fix_log many_steps). dup.\n  { reflexivity. }\n  { applys eq_trans. unfold Log; simpl. eauto. eauto. }\n  (* --TODO: eauto bug: it should try reflexivity before applying lemmas *)\nQed.\n\nEnd LogCompute.\n\n\n(* ********************************************************************** *)\n(** * Loop on odd numbers -- partial function *)\n\nModule OnlyEven.\n\n(** The function [F] defined in this module returns [1]\n    on any even number and \"loops\" on any odd number.\n    It does not actually loop, since when a recursive\n    call is not made on a smaller argument, the recursion\n    is stopped and a dummy value is returned. *)\n\nDefinition Only_even only_even n :=\n  If n = 0 then 1 else\n  If n = 1 then 1 + only_even 1 else\n  only_even (n - 2).\n\nDefinition only_even := FixFun Only_even.\n\nLemma only_even_fix : forall n, Nat.even n ->\n  only_even n = Only_even only_even n.\nProof using.\n  applys~ (FixFun_fix_partial (@lt nat _)).\n  intros f1 f2 n Pn IH. unfolds. case_if~. case_if as C'.\n  subst. inverts Pn as Pn'.\n  apply* IH. math_rewrite (n = S (S (n - 2))) in Pn.\n  rewrite Nat.even_succ_succ in Pn. auto.\n  (* --TODO: revive the TLC definition of even to avoid dependency\n     on stdlib\n     inverts Pn as Pn'; tryfalse. inverts Pn'. simpl. rew_nat~. *)\nQed.\n\nEnd OnlyEven.\n\n(** Same, but now computable version *)\n\nModule OnlyEvenCompute.\n\nImport Coq.Arith.Even.\n\nDefinition Only_even only_even n :=\n  if eq_nat_dec n 0 then 1 else\n  if eq_nat_dec n 1 then 1 + only_even 1 else\n  only_even (n - 2).\n\nDefinition only_even := FixFun Only_even.\n\nLemma only_even_fix : forall N n, even n ->\n  only_even n = func_iter N Only_even only_even n.\nProof using.\n  applys~ (FixFun_fix_partial_iter (@lt nat _)).\n  intros f1 f2 n Pn IH. unfolds. case_if~. case_if.\n  subst. inverts Pn as Pn'. inverts Pn'.\n  apply* IH. inverts Pn as Pn'; tryfalse. inverts Pn'. simpl. rew_nat~.\nQed.\n\nDefinition many_steps := 100.\n\nLemma even_8 : even 8.\nProof using. Hint Constructors even odd. eauto 18. Qed.\n\nLemma only_even_compute : only_even 8 = 1.\nProof using.\n  rewrite (@only_even_fix many_steps); [ | apply even_8 ].\n  { reflexivity. }\nQed.\n\n(* Note: many_steps needs to exceed the number of levels of recursion,\n   else reflexivity fails. *)\n\nEnd OnlyEvenCompute.\n\n\n(* ********************************************************************** *)\n(** * GCD function (binary currified function, by measure) *)\n\nDefinition Gcd gcd x y :=\n  If x = 0 then y else\n  If y = 0 then x else\n  If x <= y then gcd x (y-x) else gcd (x-y) y.\n\n(** The measure is the sum of the arguments *)\n\nDefinition gcd := FixFun2 Gcd.\n\nLemma fix_gcd : forall x y,\n  gcd x y = Gcd gcd x y.\nProof using.\n  applys~ (FixFun2_fix (measure2 plus)).\n  unfold measure2. introv IH. unfolds.\n  case_if~. case_if~. case_if. apply* IH. apply* IH.\nQed.\n\n\n(* ********************************************************************** *)\n(** * Zero function (nested recursion) *)\n\n(** [zero n] is a function that always returns [0]. *)\n\nDefinition Zero zero n :=\n  If n = 0 then 0 else zero (zero (n-1)).\n\nDefinition zero := FixFun Zero.\n\nLemma zero_fix : forall x, zero x = Zero zero x\n              /\\ forall x, zero x = 0.\nProof using.\n  forwards~ [H1 H2]: (FixFun_fix_partial_inv lt pred_true (fun (x y : nat) => y = 0) (F:=Zero)).\n  introv _ H. unfold Zero. case_if~.\n  forwards* [H1 H2]: (H (x-1)). rewrite <- H1. rewrite H2. apply* H.\nQed.\n\n\n(* ********************************************************************** *)\n(** * Ackerman's function (nested non-primitive recursion, two arguments) *)\n\nLtac emaths := eauto with maths.\n\nDefinition Ack ack m n :=\n  If m = 0 then n+1 else\n  If n = 0 then ack (m-1) 1 else\n  ack (m-1) (ack m (n-1)).\n\nDefinition ack := FixFun2 Ack.\n\nLemma fix_ack : forall m n,\n  ack m n = Ack ack m n.\nProof using.\n  applys~ (FixFun2_fix (lexico2 (@lt nat _) (@lt nat _))).\n  introv IH. unfolds. case_if~. case_if~.\n  apply IH. emaths.\n  rewrite IH. fequals~. emaths. emaths.\nQed.\n\n\n(* ********************************************************************** *)\n(** * McCarthy's 91 function (nested recursion) *)\n\n(** [McCarthy n] returns [n-10] if [n > 100] and returns\n    [91] otherwise. It is defined using nested recursion. *)\n\nDefinition McCarthy mcCarthy n :=\n  If n > 100\n    then n - 10\n    else mcCarthy (mcCarthy (n + 11)).\n\nDefinition mcCarthy := FixFun McCarthy.\n\nDefinition McCarthy_post n r :=\n  If n > 100 then r = n - 10 else r = 91.\n\nLemma McCarthy_fix_post :\n     (forall n, mcCarthy n = McCarthy mcCarthy n)\n  /\\ (forall n, McCarthy_post n (mcCarthy n)).\nProof using.\n  sets meas: (fun n => If n > 100 then 0 else 101 - n).\n  applys~ (FixFun_fix_inv (measure meas)). introv IH.\n  unfold McCarthy. unfold McCarthy_post. case_if~.\n  forwards [K1 K2]: IH (x+11). unfold measure, meas. case_if; case_if*.\n  rewrite <- K1 in *. sets y: (f1(x+11)). unfolds in K2.\n  forwards [L1 L2]: IH y. unfold measure, meas. case_if; case_if*. case_if*.\n  rewrite <- L1 in *. sets z: (f1 y). unfolds in L2. split~.\n  case_if*. case_if*.\nQed.\n\n(** Corrolaries *)\n\nLemma McCarthy_fix : forall n,\n  mcCarthy n = McCarthy mcCarthy n.\nProof using. apply (proj1 (McCarthy_fix_post)). Qed.\n\nLemma McCarthy_spec_gt100 : forall n,\n  n > 100 -> mcCarthy n = n - 10.\nProof using.\n  introv Lt. lets H: (proj2 McCarthy_fix_post n). unfolds in H. case_if*.\nQed.\n\nLemma McCarthy_spec_le100 : forall n,\n  n <= 100 -> mcCarthy n = 91.\nProof using.\n  introv Le. lets H: (proj2 McCarthy_fix_post n). unfolds in H. case_if*.\nQed.\n\n\n\n(* ********************************************************************** *)\n(** * Integer division (binary function) *)\n\n(** [div n m] returns a pair [(q,r)] such that\n    [n = q*m + r] with [r < m]. Its definition involves\n    non-structural recursion. *)\n\nDefinition Div div n m :=\n  If n < m then (0,n)\n  else let (q,r) := div (n-m) m : nat*nat in\n       (q+1,r).\n\nDefinition div := FixFun2 Div.\n\nLemma fix_div : forall n m, m <> 0 ->\n  div n m = Div div n m.\nProof using.\n  applys~ (FixFun2_fix_partial (measure (@fst nat nat))).\n  introv Posm IH. unfold Div. case_if~.\n  rewrite~ IH. unfolds. simpl. math.\nQed.\n\n\n\n(* ********************************************************************** *)\n(** * A function on trees -- higher-order recursion *)\n\nDefinition Mem A (x:A) l := Exists (=x) l. (* --TODO: move *)\n\n(** The congruence rule for [map] on lists *)\n\nLemma map_congr : forall A B (f1 f2 : A->B) l,\n  (forall x, Mem x l -> f1 x = f2 x) ->\n  LibList.map f1 l = LibList.map f2 l.\nProof using. Hint Constructors Exists. Hint Unfold Mem.\n  introv H. induction l. auto. rew_listx. fequals~.\nQed.\n\n(** Definition of trees *)\n\nInductive tree : Type :=\n  | leaf : nat -> tree\n  | node : list tree -> tree.\n\nInstance Inhab_tree : Inhab tree.\nProof using. intros. apply (Inhab_of_val (leaf 0)). Qed.\n\n(** An induction principle for trees *)\n\nSection Tree_induct.\nVariables\n(P : tree -> Prop)\n(Q : list tree -> Prop)\n(P1 : forall n, P (leaf n))\n(P2 : forall l, Q l -> P (node l))\n(Q1 : Q nil)\n(Q2 : forall t l, P t -> Q l -> Q (t::l)).\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 l => P2\n      ((fix tree_list_induct (l : list tree) : Q l :=\n      match l as x return Q x with\n      | nil   => Q1\n      | t::l' => Q2 (tree_induct_gen t) (tree_list_induct l')\n      end) l)\n  end.\n\nEnd Tree_induct.\n\nLemma tree_induct : forall (P : tree -> Prop),\n  (forall n : nat, P (leaf n)) ->\n  (forall l : list tree,\n    (forall t, Mem t l -> P t) -> P (node l)) ->\n  forall T : tree, P T.\nProof using.\n  introv Hl Hn. eapply tree_induct_gen with (Q := fun l =>\n    forall t, Mem t l -> P t); intros.\n  auto. auto. inversions H. inversions~ H1.\nQed.\n\n(** Definition of immediate subtrees *)\n\nInductive subtree : binary tree :=\n  | subtree_intro : forall t l,\n     Mem t l -> subtree t (node l).\n\nHint Constructors subtree.\n\nLemma subtree_wf : wf subtree.\nProof using.\n  intros t. induction t using tree_induct;\n  constructor; introv K; inversions~ K.\nQed.\n\n(** Definition of the [treeincr] function *)\n\nDefinition Treeincr treeincr t :=\n  match t with\n  | leaf n => leaf (S n)\n  | node l => node (LibList.map treeincr l)\n  end.\n\nDefinition treeincr := FixFun Treeincr.\n\nLemma treeincr_fix : forall t,\n  treeincr t = Treeincr treeincr t.\nProof using.\n  applys (FixFun_fix subtree).\n  reflexivity. apply subtree_wf.\n  introv H. unfold Treeincr. destruct x.\n    auto.\n    fequals. apply~ map_congr.\nQed.\n\n\n\n(* ********************************************************************** *)\n(** * DFS *)\n\nModule DFS.\n\nParameter marks : Type.\nParameter marks_inhab : Inhab marks.\nExisting Instance marks_inhab.\nImplicit Type i : nat.\n\nParameter is_marked : marks -> nat -> bool.\nParameter add_mark : marks -> nat -> marks.\nParameter nb_unmarked : marks -> nat.\nParameter add_mark_nb_unmarked : forall m i,\n  ~ is_marked m i ->\n  nb_unmarked (add_mark m i) < nb_unmarked m.\n\nParameter neighbours : nat -> list nat.\n\nDefinition Dfs dfs m i :=\n  'let m := add_mark m i in\n  'let v := neighbours i in\n  'let aux := (fun j m => if is_marked m j then m else dfs m j) in\n  fold_left aux m v.\n\nDefinition dfs := FixFun2 Dfs.\n\nLemma fix_dfs : forall m i,\n  ~ is_marked m i ->\n  dfs m i = Dfs dfs m i.\n  (* Could be added to the statement:\n     /\\ (forall m i, is_marked m i = false ->\n         nb_unmarked (Dfs dfs m i) < nb_unmarked m). *)\nProof using.\n  applys~ FixFun2_fix_partial_inv\n    (measure2 (fun m i => nb_unmarked m))\n    (fun m i m' => nb_unmarked m' < nb_unmarked m).\n  intros m i f1 f2 Hi IH. unfolds Dfs.\n  unfold measure2 in IH. sets_eq N: (nb_unmarked m).\n  let_name_all. let_name_all.\n  let_name_all as aux1. let_name_all as aux2.\n  asserts L: (nb_unmarked m0 < N).\n    subst N m0. applys* add_mark_nb_unmarked.\n  clears m i. gen m0. induction v as [|i v]. simple*.\n  intros m Lt. simpl.\n  asserts [E F]: (aux1 i m = aux2 i m /\\ nb_unmarked (aux1 i m) < N).\n    rewrite EQaux1, EQaux2. case_if as C.\n      auto.\n      forwards* [E L]: IH C. split. auto. math.\n  rewrite <- E. applys* IHv.\nQed.\n\n(*\nExtraction Language Ocaml.\nExtraction Inline Dfs\n  FixFun2Mod FixFun2 curry2 uncurry2 FixFunMod.\nSet Extraction Optimize.\nExtraction dfs.\n*)\n\nEnd DFS.\n\n\n(* ********************************************************************** *)\n(** * COFE for streams *)\n\n(** Definition of stream ordered family of requiv *)\n\nDefinition stream_mod_family A (E:binary A) : family nat (stream A) :=\n  nat_family (bisimilar_mod_upto E).\n\n(** Special case of comparing stream values wrt equality *)\n\nDefinition stream_family A := stream_mod_family (@eq A).\n\n(** Similarity for this OFE is equal to stream bisimilarity *)\n\nLemma stream_mod_similarity : forall A (E:binary A),\n  bisimilar_mod E = similar (stream_mod_family E).\nProof using.\n  extens. intros s1 s2.\n  unfold similar. simpl. split.\n  intros. apply~ bisimilar_mod_to_upto.\n  intros. apply~ bisimilar_mod_take.\nQed.\n\nHint Resolve stream_mod_similarity.\n\nLemma stream_similarity : forall A,\n  @bisimilar A = similar (stream_family A).\nProof using. intros. apply stream_mod_similarity. Qed.\n\nHint Resolve stream_similarity.\n\n(** Completeness of the OFE *)\n\nHint Unfold list_equiv.\nHint Constructors Forall2.\n\nLemma stream_mod_cofe : forall A {IA:Inhab A} (E:binary A),\n  equiv E -> COFE (stream_mod_family E).\nProof using.\n  introv IA Equiv. apply nat_cofe. typeclass.\n  intros. apply~ equiv_bisimilar_mod_upto.\n  introv H. exists (diagonal (fun i => u (S i)) 0).\n  induction i; unfolds.\n    simple~.\n    apply~ bisimilar_mod_upto_succ. apply~ (trans_sym_rl (u i)).\n    rewrite stream_diagonal_nth. math_rewrite~ (i + 0 = i).\nQed.\n\nLemma stream_cofe : forall A {IA:Inhab A}, COFE (stream_family A).\nProof using. intros. apply~ stream_mod_cofe. Qed.\n\nHint Resolve @stream_cofe.\n\n\n(* ********************************************************************** *)\n(** * Constant stream -- basic corecursive value *)\n\nDefinition Const1 const1 := (1%nat) ::: const1.\n\nDefinition const1 := FixValMod (@bisimilar nat) Const1.\n\nLemma const1_fix : const1 === Const1 const1.\nProof using.\n  applys~ (FixValMod_fix (stream_family nat)). typeclass.\n  intros i s1 s2 H. simpls. destruct~ i.\n  unfolds. simpl. constructor~. apply* H.\nQed.\n\n\n(* ********************************************************************** *)\n(** * Constant stream -- basic corecursion *)\n\nDefinition Const const (n:nat) := n ::: const n.\n\nDefinition const := FixFunMod (@bisimilar nat) Const.\n\nLemma const_fix : forall n, const n === Const const n.\nProof using.\n  intros.\n  applys (FixFunMod_corec (stream_family nat) (@pred_true nat)); autos*.\n  apply stream_cofe.\n  clear n. intros i n s1 s2 _ H. simpls. destruct~ i.\n  unfolds. simpl. constructor~. apply* H.\nQed.\n\n\n(* ********************************************************************** *)\n(** * Polymorphic Constant stream -- basic corecursion with polymorphism *)\n\nDefinition PConst A pconst (n:A) := n ::: pconst n.\n\nDefinition pconst `{IA:Inhab A} := FixFunMod (@bisimilar A) (@PConst A).\n\nLemma pconst_fix : forall A {IA:Inhab A} (n:A),\n  pconst n === PConst pconst n.\nProof using.\n  intros.\n  applys* (FixFunMod_corec (stream_family A) (@pred_true A)).\n  clears n. intros i n s1 s2 _ H. simpls. destruct~ i.\n  unfolds. simpl. constructor~. apply* H.\nQed.\n\nLemma pconst_spec : forall A {IA:Inhab A} (x:A),\n  LibStream.const x === pconst x.\nProof using.\n  intros.\n  apply bisimilar_mod_take. induction i. simple~.\n  apply* sym_inv. apply* trans_sym_lr.\n   apply bisimilar_mod_to_upto. apply pconst_fix.\n   simpl. constructor~.\nQed.\n\n(* ********************************************************************** *)\n(** * Mutually-defined stream -- basic corecursion *)\n(* u = 1::2::3::1::2::3::1::2::3::1::2::3::1::2::3::...*)\n\nDefinition MU (mu mv : stream nat) := (1%nat) ::: mv.\nDefinition MV (mu mv : stream nat) := (2%nat) ::: ((3%nat) ::: mu).\n\nDefinition muv := FixValModMut2 (@bisimilar nat) (@bisimilar nat) MU MV.\nDefinition mu := fst muv.\nDefinition mv := snd muv.\n\nLemma uv_fix : mu === MU mu mv /\\ mv === MV mu mv.\nProof using.\n  applys (FixValModMut2_fix\n    (prod_family (stream_family nat) (stream_family nat))).\n  rewrite~ prod2_eq_tuple_proj.\n  unfold bisimilar. rewrite stream_mod_similarity. apply prod_similar.\n  apply prod_cofe; typeclass.\n  intros i u1 v1 u2 v2 H. simpls. destruct~ i. split.\n    unfolds. simpl. constructor~. apply* H.\n    unfolds. simpl. constructor~. destruct i. simple~. simpl.\n     constructor~. apply* H.\nQed.\n\n(* ********************************************************************** *)\n(** * Stream of natural numbers *)\n\nDefinition Nats nats (n:nat) := n ::: nats (S n).\n\nDefinition nats := FixFunMod (@bisimilar nat) Nats.\n\nLemma nats_fix : forall (n:nat),\n  nats n === Nats nats n.\nProof using.\n  intros.\n  applys (FixFunMod_corec (stream_family nat) (@pred_true nat)); autos*.\n  apply stream_cofe.\n  clears n. intros i n s1 s2 _ H. simpls. destruct~ i.\n  unfolds. simpl. constructor~. apply* H.\nQed.\n\n\n(* ********************************************************************** *)\n(** * Filter on streams *)\n\nDefinition dist_to_next A (P:A->Prop) (s:stream A) :=\n  epsilon (first_st_at P s).\n\nLemma eventually_to_dist : forall A (P:A->Prop) s,\n  eventually P s -> exists n, first_st_at P s n.\nProof using.\n  introv H. induction H. exists 0. simple~.\n  destruct (prop_inv (P x)).\n    exists 0. simple~.\n    destruct IHeventually as [n Pn]. exists (S n). simple~.\nQed.\n\nLemma eventually_dist_cons : forall A (P:A->Prop) s x,\n  eventually P s -> ~ P x ->\n  dist_to_next P s < dist_to_next P (x:::s).\nProof using.\n  introv H Nx. unfold dist_to_next.\n  epsilon n. apply~ eventually_to_dist. intros Pn.\n  epsilon n'. apply~ eventually_to_dist. apply~ eventually_tail.\n  intros Pn'. clearbody n n'. destruct n'; simpl in Pn'; tryfalse.\n  rewrite* (@first_st_at_inj n n' A P s).\nQed.\n\nSection MyFilters.\nContext (A:Type) {IA:Inhab A}.\nVariable (P:A->Prop).\n\nDefinition Filter filter s :=\n  let '(x:::s') := s in\n  let s'' := filter s' in\n  If P x then x:::s'' else s''.\n\nDefinition filter := FixFunMod (@bisimilar A) Filter.\n\nLemma filter_fix : forall s,\n  infinitely_often P s ->\n  filter s === Filter filter s.\nProof using.\n  applys~ (FixFunMod_mixed_partial\n    (stream_family A)\n    (measure (dist_to_next P))\n    (infinitely_often P)\n    (@bisimilar A)).\n  intros i s f1 f2 Ps H. simpls.\n  destruct s. simpl. unfolds. destruct i. simple~.\n   inverts Ps as Ps' Ev. case_if as C.\n     simpl. constructor~. apply~ H. left*.\n     inverts Ev as Ev.\n       false.\n       apply~ H. right. split~.\n         forwards~: eventually_dist_cons Ev C.\nQed.\n\n\nEnd MyFilters.\n\n\n(* ********************************************************************** *)\n(** * An example with cofinite trees *)\n\nRequire Import TLC.LibNat.\n\n(** Definition of [itree], trees with possibly-infinite branches *)\n\nCoInductive itree : Type :=\n  | itree_leaf : nat -> itree\n  | itree_node : itree -> itree -> itree.\n\n(** The type [itree] is inhabited *)\n\nInstance Inhab_itree : Inhab itree.\nProof using. intros. apply (Inhab_of_val (itree_leaf 0)). Qed.\n\n(** Similarity up to level [i] between two trees *)\n\nFixpoint itree_similar_upto (i:nat) (m1 m2: itree) :=\n  match i with\n  | O => True\n  | S i' => match m1,m2 with\n     | itree_leaf n1, itree_leaf n2 => n1 = n2\n     | itree_node t11 t12, itree_node t21 t22 =>\n           itree_similar_upto i' t11 t21\n        /\\ itree_similar_upto i' t12 t22\n     | _, _ => False\n     end\n  end.\n\n(** Similarity upto is an equivalence *)\n\nLemma itree_similar_upto_equiv :\n  forall i, equiv (itree_similar_upto i).\nProof using.\n  constructor; unfolds.\n  induction i; intros; simple~. destruct~ x.\n  induction i; intros; simple~. destruct x; destruct y; simpls*.\n  induction i; intros; simple~. destruct x; destruct y; destruct z; simpls*.\nQed.\n\nHint Resolve itree_similar_upto_equiv.\nHint Extern 1 (itree_similar_upto ?i _ _) =>\n  apply (@equiv_refl _ _ (itree_similar_upto_equiv i)).\n\n(** Construction of the COFE for the family [itree] *)\n\nDefinition itree_family := Build_family lt itree_similar_upto.\n\nDefinition itree_left t :=\n  match t with\n  | itree_leaf n => arbitrary\n  | itree_node t1 t2 => t1\n  end.\n\nDefinition itree_right t :=\n  match t with\n  | itree_leaf n => arbitrary\n  | itree_node t1 t2 => t2\n  end.\n\nDefinition shifts A (u:nat->A) :=\n  fun n => u (S n).\n\nCoFixpoint itree_diagonal (u:nat->itree) : itree :=\n  match u 0 with\n  | itree_leaf n => itree_leaf n\n  | itree_node t1 t2 =>\n      itree_node (itree_diagonal (itree_left \\o shifts u))\n                 (itree_diagonal (itree_right \\o shifts u))\n  end.\n\nLemma itree_family_COFE : COFE itree_family.\nProof using.\n  apply~ nat_cofe'. typeclass.\n  introv H. exists (itree_diagonal (shifts u)).\n  cuts M: (forall k i u, i <= k ->\n    (forall i j : nat, i < j -> itree_similar_upto (S i) (u i) (u j)) ->\n      itree_similar_upto (S i) (u k) (itree_diagonal u)).\n    intros i. destruct i. simple~.\n    sets u': (shifts u). change (u (S i)) with (u' i).\n    apply M. math.\n      intros i' j' Ri'j'. unfold u', shifts. apply H. math.\n  clears u. induction k using peano_induction; introv Lik Coh.\n  tests: (k = 0). math_rewrite (i = 0). simpl. destruct~ (u 0).\n  unfolds. fold itree_similar_upto.\n  forwards S0: (>> Coh 0 k __). math. simpl in S0.\n  unfold itree_diagonal; fold itree_diagonal.\n  sets_eq <- u0: (u 0). sets_eq <- uk: (u k).\n  destruct u0 as [|t01 t02]; destruct uk as [|tk1 tk2]; auto_false.\n  split. (* --TODO: find a way to factorize both sides *)\n  (* left subtree *)\n  destruct i. simple~.\n  sets u': (itree_left \\o shifts u).\n  asserts_rewrite (tk1 = u' (k-1)).\n    unfold u'. unfold compose, shifts, itree_left.\n    math_rewrite (S (k - 1) = k). rewrite~ EQuk.\n  apply H; try math. intros i' j' Li'j'.\n  unfold u'. unfold compose, shifts, itree_left.\n  sets_eq i'': (S i'). sets_eq j'': (S j').\n  forwards Ssi: (Coh i'' j''). math.\n  simpl in Ssi. destruct (u i''); destruct (u j''); auto_false*.\n  (* right subtree *)\n  destruct i. simple~.\n  sets u': (itree_right \\o shifts u).\n  asserts_rewrite (tk2 = u' (k-1)).\n    unfold u'. unfold compose, shifts. unfold itree_right.\n    math_rewrite (S (k - 1) = k). rewrite~ EQuk.\n  apply H; try math. intros i' j' Li'j'.\n  unfold u'. unfold compose, shifts, itree_left.\n  sets_eq i'': (S i'). sets_eq j'': (S j').\n  forwards Ssi: (Coh i'' j''). math.\n  simpl in Ssi. destruct (u i''); destruct (u j''); auto_false*.\nQed.\n\n(** Two equivalent definitions of similarity between two trees,\n    one using an coinductive predicate and another constructed\n    as the intersection of the \"similarity-upto\" relations. *)\n\nCoInductive itree_similar : binary itree :=\n  | itree_similar_leaf : forall n,\n      itree_similar (itree_leaf n) (itree_leaf n)\n  | itree_similar_node : forall t11 t12 t21 t22 : itree,\n      itree_similar t11 t21 ->\n      itree_similar t12 t22 ->\n      itree_similar (itree_node t11 t12) (itree_node t21 t22).\n\nHint Constructors itree_similar.\n\nLemma itree_similar_eq : itree_similar = similar itree_family.\nProof using.\n  extens. intros t1 t2. iff H.\n  intros i. hnf. gen t1 t2. induction i; simpl; introv H.\n   auto. inversions~ H.\n  hnf in H. gen t1 t2. cofix IH.\n   intros t1 t2. destruct t1; destruct t2;\n    introv H; lets H1: (H 1); simpl in H1; inverts H1; constructor.\n      apply IH. intros i. lets_simpl HSi: (H (S i)). autos*.\n      apply IH. intros i. lets_simpl HSi: (H (S i)). autos*.\nQed.\n\n\n(** A first corecursive operation: the \"product\" of two trees.\n   Note that it always add a head element. *)\n\nDefinition Product product m1 m2 :=\n  match m1,m2 with\n  | itree_node t11 t12, itree_node t21 t22 =>\n     itree_node (product t11 t22) (product t12 t21)\n  | _, _ => itree_node m1 m2\n  end.\n\nDefinition product := FixFun2Mod itree_similar Product.\n\n(** We prove that [product] satisfies the fixed point equation *)\n\nLemma product_fixpoint : forall m1 m2,\n  itree_similar (product m1 m2) (Product product m1 m2).\nProof using.\n  apply (FixFun2Mod_corec itree_family).\n  reflexivity. apply itree_similar_eq. apply itree_family_COFE.\n  simpl. introv H. destruct i. simple~. unfold Product.\n  destruct x1; destruct x2; simpl; auto with maths.\nQed.\n\n(** And we show that it is productive wrt its arguments *)\n\nLemma product_incr_similarity : forall i m1 m1' m2 m2',\n   itree_similar_upto i m1 m1' ->\n   itree_similar_upto i m2 m2' ->\n   itree_similar_upto (S i) (product m1 m2) (product m1' m2').\nProof using.\n  induction i using peano_induction.\n  change (itree_similar_upto) with (family_sim itree_family).\n  introv K1 K2. (* --TODO: setoid rewrite *)\n  eapply cofe_similar_modulo. apply itree_family_COFE.\n    rewrite <- itree_similar_eq. apply product_fixpoint.\n    rewrite <- itree_similar_eq. apply product_fixpoint.\n  simpl in K1, K2 |- *.\n  destruct m1; destruct m2; simpl; auto.\n  destruct m1'; destruct m2'; simple~. destruct~ i. inversions K1.\n  destruct m1'; destruct m2'; simple~. destruct~ i. inversions K1.\n  destruct m1'; destruct m2'; simple~. destruct~ i. inversions K2.\n  destruct m1'; destruct m2'; simple~; destruct~ i.\n    inversions K1. inversions K1. inversions K2.\n    simpl in K1, K2. destruct K1. destruct K2. auto with maths.\nQed.\n\n(** A second corecursive function, which is not guarded:\n    it is productive only because the function [product]\n    is productive. *)\n\nDefinition Makeitree makeitree m :=\n  match m with\n  | itree_node t1 t2 => product (makeitree t1) (makeitree t2)\n  | itree_leaf n => itree_leaf (S n)\n  end.\n\nDefinition makeitree := FixFunMod itree_similar Makeitree.\n\n(** Still, we can establish the fixed point equation for our function *)\n\nLemma makeitree_fixpoint : forall m,\n  itree_similar (makeitree m) (Makeitree makeitree m).\nProof using.\n  apply (FixFunMod_corec_total itree_family).\n  reflexivity. apply itree_similar_eq. apply itree_family_COFE.\n  introv H. unfold Makeitree. simpl. destruct x.\n  auto.\n  destruct i. auto. apply product_incr_similarity.\n    apply H; simpl; auto with maths.\n    apply H; simpl; auto with maths.\nQed.\n\n\n\n(* ********************************************************************** *)\n(** * Verification of a recursive parser in CPS form *)\n\n\nLtac auto_tilde ::= auto with wf.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** The assertion construction *)\n\n(** The expression [ ##P## v ] is equivalent to [v],\n    with the assertion that [P] holds. If [P] does not hold,\n    then the expression is undefined. *)\n\nDefinition asserts (P:Prop) (A:Type) `{Inhab A} (v:A) :=\n  If P then v else arbitrary.\n\nNotation \"'##' P '##' v\" := (asserts P v) (at level 69).\n\nTactic Notation \"case_asserts\" :=\n  unfold asserts; case_if.\nTactic Notation \"case_asserts\" \"~\" :=\n  case_asserts; auto_tilde.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of the data types *)\n\nInductive regexp : Type :=\n  | regexp_null : regexp\n  | regexp_empty : regexp\n  | regexp_char : nat -> regexp\n  | regexp_alt : regexp -> regexp -> regexp\n  | regexp_seq : regexp -> regexp -> regexp\n  | regexp_star : regexp -> regexp.\n\nDefinition text := list nat.\n\nDefinition arg_type := (regexp * text * (text -> bool))%type.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of the regexp parser as an optimal fixed point *)\n\nDefinition Parse (parse : arg_type -> bool) (p : arg_type) : bool :=\n  let '(r,s,k) := p in\n  match r with\n  | regexp_null => false\n  | regexp_empty => k s\n  | regexp_char c =>\n     match s with\n     | nil => false\n     | c'::s' => If c = c' then k s' else false\n     end\n  | regexp_alt r1 r2 => parse (r1,s,k) || parse (r2,s,k)\n  | regexp_seq r1 r2 => parse (r1,s,(fun s' => parse (r2,s',k)))\n  | regexp_star r1 => k s || parse (r1,s,(fun s' => parse (r,s',k)))\n  end.\n\nDefinition parse := FixFun Parse.\n\n(** At this point, the function [parse] exists and can thus\n    be mentioned in other definitions. *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Domain of the parser *)\n\n(** [productive r] is the same as [not (nullable r)];\n    it asserts that [r] consumes at least one character *)\n\nFixpoint productive (r:regexp) : Prop :=\n  match r with\n  | regexp_null => True\n  | regexp_empty => False\n  | regexp_char c => True\n  | regexp_alt r1 r2 => productive r1 /\\ productive r2\n  | regexp_seq r1 r2 => productive r1 \\/ productive r2\n  | regexp_star r1 => False\n  end.\n\n(** [normal r] ensures that expressions under a star are productive *)\n\nFixpoint normal (r:regexp) : Prop :=\n  match r with\n  | regexp_null => True\n  | regexp_empty => True\n  | regexp_char c => True\n  | regexp_alt r1 r2 => normal r1 /\\ normal r2\n  | regexp_seq r1 r2 => normal r1 /\\ normal r2\n  | regexp_star r1 => productive r1 /\\ normal r1\n  end.\n\nHint Unfold productive normal.\n\n(** Definition of the domain *)\n\nDefinition parse_dom (p:arg_type) :=\n  let '(r,s,k) := p in normal r.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Termination relation for the parser *)\n\n(** Sub-expression order for [regexp] *)\n\nInductive regexp_sub : binary regexp :=\n  | regexp_sub_seq_1 : forall r1 r2,\n      regexp_sub r1 (regexp_seq r1 r2)\n  | regexp_sub_seq_2 : forall r1 r2,\n      regexp_sub r2 (regexp_seq r1 r2)\n  | regexp_sub_alt_1 : forall r1 r2,\n      regexp_sub r1 (regexp_alt r1 r2)\n  | regexp_sub_alt_2 : forall r1 r2,\n      regexp_sub r2 (regexp_alt r1 r2)\n  | regexp_sub_star : forall r1,\n      regexp_sub r1 (regexp_star r1).\n\nHint Constructors regexp_sub.\n\nLemma regexp_sub_wf : wf regexp_sub.\nProof using. intros r. induction r; constructor; intros r' le; inverts~ le. Qed.\n\nHint Resolve regexp_sub_wf : wf.\n\n(** [text_sub] is the transitive closure of the sub-list order *)\n\nDefinition text_sub : binary text := tclosure (@list_sub _).\n\nLemma text_sub_wf : wf text_sub.\nProof using. lets: wf_tclosure. unfold text_sub. solve_wf. Qed.\n\nHint Resolve text_sub_wf : wf.\n\nLemma text_sub_once : forall s c,\n  text_sub s (c::s).\nProof using. intros. apply~ tclosure_once. Qed.\n\nLemma trans_text_sub : trans text_sub.\nProof using. apply trans_tclosure. Qed.\n\nHint Resolve trans_text_sub text_sub_once.\n\nLemma text_sub_app : forall s s1 s2,\n  s = s1 ++ s2 ->\n  rclosure text_sub s2 s.\nProof using.\n  intros. rewrite rclosure_eq.\n  subst. induction s1; rew_list. auto.\n  inverts IHs1.\n    left. applys~ (@trans_inv text) (s1++s2).\n    rewrite <- H. left. apply text_sub_once.\nQed.\n\n(** [parse_sub] is the termination relation used for [parse];\n    It is the lexicographical order [(s,r)] *)\n\nDefinition parse_sub : binary (regexp * text) :=\n  lexico2 regexp_sub text_sub.\n\nLemma parse_sub_wf : wf parse_sub.\nProof using. solve_wf. Qed.\n\nHint Unfold parse_sub.\nHint Resolve parse_sub_wf : wf.\n\n(** [parse_arg_sub] is similar to [parse_sub] except that\n    it takes triples of the form [(r,s,k)] as arguments *)\n\nDefinition parse_arg_sub : binary arg_type :=\n  fun p1 p2 => let '(r1,s1,k1) := p1 in let '(r2,s2,k2) := p2 in\n               parse_sub (r1,s1) (r2,s2).\n\nLemma parse_arg_sub_wf : wf parse_arg_sub.\nProof using.\n  intros [[r s] k].\n  sets_eq p: (r,s). gen k r s. induction_wf IH: parse_sub_wf p.\n  intros. subst p. constructor. intros [[r2 s2] k2] S. applys~ IH S.\nQed.\n\nHint Unfold parse_arg_sub.\nHint Resolve parse_arg_sub_wf : wf.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Auxiliary recursive function *)\n\n(** [parse'] is a function equivalen to [parse] except that it includes\n    some assertions in order to make termination more obvious.\n    Those assertions appear in-between [##] symbols. *)\n\nDefinition Parse' (parse : arg_type -> bool) (p : arg_type) : bool :=\n  let '(r,s,k) := p in\n  match r with\n  | regexp_null => false\n  | regexp_empty => k s\n  | regexp_char c =>\n     match s with\n     | nil => false\n     | c'::s' => If c = c' then k s' else false\n     end\n  | regexp_alt r1 r2 => parse (r1,s,k) || parse (r2,s,k)\n  | regexp_seq r1 r2 => parse (r1,s,(fun s' => parse (r2,s',k)))\n  | regexp_star r1 => k s || parse (r1,s,(fun s' => ##text_sub s' s## parse (r,s',k)))\n  end.\n\nDefinition parse' := FixFun Parse'.\n\n(** Remark: I will show further on how to factorize the definitions\n    of [Parse] and [Parse'] so as to avoid the duplication of code. *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Proof of termination of the auxiliary function *)\n\n(** Thanks to the assertions it contains, [parse'] is a total function\n    that satisfies a contraction condition, and thus satisfies the\n    fixed point equation for [Parse']. *)\n\nLemma parse'_fix : forall p,\n  parse' p = Parse' parse' p.\nProof using.\n  applys~ (FixFun_fix parse_arg_sub).\n  intros f1 f2 [[r s] k] H. unfolds. destruct r; auto.\n  fequal; auto 7.\n  rewrite H; [|auto 7]. fequals_rec.\n   apply fun_ext_1. intros s'. apply~ H.\n  fequal. rewrite H; [|auto 7]. fequals_rec.\n   apply fun_ext_1. intros s'. case_asserts; auto 7.\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of the auxiliary function *)\n\n(** [select_sub r] is equivalent to the strict sub-text relation\n    when [r] is [productive], and it is otherwise equivalent to\n    the large sub-text relation. *)\n\nDefinition select_sub (r:regexp) : binary text :=\n  If productive r then text_sub else rclosure text_sub.\n\n(** The key result consists in showing that, when [r] is is normal form,\n    the computation of [parse' (r,s,k)] is not affected by the evaluations\n    of the assertions. *)\n\nLemma parse'_cont : forall r s k1 k2, normal r ->\n  (forall s', select_sub r s' s -> k1 s' = k2 s') ->\n  parse' (r,s,k1) = parse' (r,s,k2).\nProof using.\n  intros r s. sets_eq p: (r,s). gen r s. induction_wf IH: parse_sub_wf p.\n  introv P N E. subst p. do 2 rewrite parse'_fix. unfolds. destruct r; simpl in N.\n  auto.\n  apply E. hnf. rewrite~ If_r.\n  destruct s as [|c' s']. auto. case_if~. apply E. unfolds. rewrite~ If_l.\n  inverts N. asserts M: (forall r s', (r = r1 \\/ r = r2) -> select_sub r s' s ->\n                select_sub (regexp_alt r1 r2) s' s).\n    introv C S. hnf in S |- *. simpl. case_if as C'.\n      destruct C'. case_if. auto. inverts C; tryfalse.\n      case_if~.\n   fequals.\n     applys~ IH. auto 7. eauto 8.\n     applys~ IH. auto 7. eauto 8.\n  inverts N. applys~ IH. intros s' S'. applys~ IH.\n    intros s'' S''. apply E. hnf in S',S''|-*. simpl.\n    tests: (productive r1); tests: (productive r2).\n      rewrite~ If_l. applys* (@trans_inv text) s'.\n      rewrite~ If_l. applys* trans_rclosure_l s'.\n      rewrite~ If_l. applys* trans_rclosure_r s'.\n      rewrite If_r; [|rew_logic;auto]. applys~ trans_rclosure s'.\n  fequals.\n    apply E. unfold select_sub. simpl. rewrite~ If_r.\n  inverts N. applys~ IH. auto 7. intros s' S'. case_asserts~.\n   applys~ IH. hnf in S'. rewrite~ If_l in S'.\n   intros s'' S''. apply E. hnf in S'' |- *. simpls. case_if; tryfalse.\n   inverts S''. left. applys* trans_inv. auto.\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Proof of the fixed point equation for [parse] *)\n\n(** The first step consists in proving that [parse']\n    is a fixed point for [Parse] on the domain. This is done\n    by showing that the assertions in the continuations are\n    irrelevant, using the lemma [parse'_cont]. Yet, the statement\n    [ Lemma parse'_fix_Parse_simple : forall p, parse_dom p ->\n      parse' p = Parse parse' p. ]\n    is not strong enough. Indeed, we need to generalize this\n    into a form where we replace [parse'] with an arbitrary\n    other total function that behave like [parse'] on the domain. *)\n\nLemma parse'_fix_Parse :\n  fixed_point (pfun_equal parse_dom) Parse parse'.\nProof using.\n  intros f Hf [[r s] k] N. asserts E: (pfun_equal parse_dom f parse').\n    unfolds. apply~ equiv_sym. clear Hf.\n  rewrite~ E. rewrite parse'_fix.\n  unfold Parse, Parse'. destruct r; auto; simpl in N.\n  inverts N. fequals; rewrite~ E.\n  inverts N. rewrite~ E. apply~ parse'_cont. intros s' S'. rewrite~ E.\n  inverts N. fequals. rewrite~ E. apply~ parse'_cont. intros s' S'.\n   hnf in S'. rewrite~ If_l in S'. case_asserts; auto_false. rewrite~ E. simple~.\nQed.\n\n(** The second step consists in proving that the functional [Parse]\n    satisfies a contraction condition. This is almost the standard\n    contraction condition, except that [f1] is specialized as [parse'].\n    In this proof, we exploit the fact that [parse'] depends only\n    a subdomain of its continuation. Remark: the statement is equivalent\n    to [rec_contractive' eq parse_dom Parse parse_arg_sub parse']. *)\n\nLemma Parse_contractive_for_parse' : forall f' p, parse_dom p ->\n  (forall q, parse_dom q -> parse_arg_sub q p -> parse' q = f' q) ->\n  Parse parse' p = Parse f' p.\nProof using.\n  introv N IH. unfold Parse. destruct p as [[r s] k].\n  hnf in N. destruct r; simpl in N; auto.\n  inverts N. fequals; apply~ IH.\n  inverts N. erewrite parse'_cont; auto. apply~ IH.\n   simpl. intros s' S'. apply~ IH.\n  inverts N. fequals. erewrite parse'_cont; auto. apply IH; auto 7.\n   simpl. intros s' S'. hnf in S'. rewrite~ If_l in S'. apply~ IH; hnfs~.\nQed.\n\n(** Third and last step: we can put all the pieces together.\n    Since [parse'] is a generally-consistent fixed point for [Parse]\n    on the domain [parse_dom], [parse'] is extended by [parse],\n    which is the optimal fixed point of [Parse]. Hence, [parse]\n    and [parse'] agree on the domain [parse_dom]. It follows that\n    [parse] satsifies the fixed point equation for [Parse] on the domain. *)\n\nLemma parse_fix : forall p, parse_dom p ->\n  parse p = Parse parse p.\nProof using.\n  applys~ (FixFun_fix_partial' (P:=parse_dom) (R:=parse_arg_sub) (F:=Parse) (f':=parse')).\n  applys Parse_contractive_for_parse'. apply parse'_fix_Parse.\nQed.\n\nCorollary parse_fix' : forall r s k, normal r ->\n  parse (r,s,k) = Parse parse (r,s,k).\nProof using. intros. applys~ parse_fix. Qed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Bonus: factorization of the definitions of [Parse] and [Parse'] *)\n\n(** The idea is to define a single functional that takes as argument a\n    function, which is intented to be instantiated either as [asserts]\n    or as [ignore]. *)\n\nDefinition ignore (P:Prop) (A:Type) `{Inhab A} (v:A) := v.\n\nSection Common.\n\nContext (check : Prop -> forall A `{Inhab A}, A -> A).\n\nNotation \"'#' P '#' v\" := (@check P _ _ v) (at level 69).\n\n(** Here is the common definition to build [Parse] and [Parse']. *)\n\nDefinition Parse_common (parse : arg_type -> bool) (p : arg_type) : bool :=\n  let '(r,s,k) := p in\n  match r with\n  | regexp_null => false\n  | regexp_empty => k s\n  | regexp_char c =>\n     match s with\n     | nil => false\n     | c'::s' => If c = c' then k s' else false\n     end\n  | regexp_alt r1 r2 => parse (r1,s,k) || parse (r2,s,k)\n  | regexp_seq r1 r2 => parse (r1,s,(fun s' => parse (r2,s',k)))\n  | regexp_star r1 => k s || parse (r1,s,(fun s' => #text_sub s' s# parse (r,s',k)))\n  end.\n\nEnd Common.\n\n(** Here are the alternative definitions for [Parse] and [Parse']. *)\n\nDefinition Parse_alternative := Parse_common ignore.\nDefinition Parse'_alternative := Parse_common asserts.\n\n(** Finally, we can check that the alternative definitions are convertible\n    with the one we had written by hand previously. *)\n\nLemma Parse_alternative_correct : Parse = Parse_alternative.\nProof using. reflexivity. Qed.\n\nLemma Parse'_alternative_correct : Parse' = Parse'_alternative.\nProof using. reflexivity. Qed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Reasoning about [parse] *)\n\n(** The inductively-defined proposition [sem r s] asserts that the\n    string [s] matches the regular expression [r]. *)\n\nInductive sem : regexp -> text -> Prop :=\n  | sem_empty :\n      sem regexp_empty nil\n  | sem_char : forall c,\n      sem (regexp_char c) (c::nil)\n  | sem_alt_1 : forall r1 r2 s,\n      sem r1 s -> sem (regexp_alt r1 r2) s\n  | sem_alt_2 : forall r1 r2 s,\n      sem r2 s -> sem (regexp_alt r1 r2) s\n  | sem_seq : forall r1 r2 s1 s2,\n      sem r1 s1 -> sem r2 s2 -> sem (regexp_seq r1 r2) (s1 ++ s2)\n  | sem_star_void : forall r1,\n      sem (regexp_star r1) nil\n  | sem_star_step : forall r1 s1 s2,\n      sem r1 s1 ->\n      sem (regexp_star r1) s2 ->\n      sem (regexp_star r1) (s1 ++ s2).\n\nHint Constructors sem.\n\n(** Observe that if a string [s] matches a productive regular\n    expression [r], then [s] is not the empty string. *)\n\nLemma sem_productive : forall r s,\n  sem r s -> productive r -> s <> nil.\nProof using.\n  introv S. induction S; introv P; simpl in P; auto_false*.\n  intros E. destruct (app_eq_nil_inv E). subst. destruct* P.\nQed.\n\n(** The continuation [is_nil] holds only of the empty string *)\n\nDefinition is_nil (s:text) :=\n  match s with nil => true | _ => false end.\n\n(** The first result asserts that if [s] matches [r] semantically,\n    then the [parse] function applied to [r] and [s] returns true. *)\n\nLemma sem_to_parse_ind : forall r s s' k,\n  sem r s ->\n  normal r ->\n  k s' = true ->\n  parse (r, s ++ s', k) = true.\nProof using.\n  introv S N K. gen s' k N. induction S; intros;\n   (rewrite parse_fix; [ | apply N ]); unfold Parse at 1; simpl in N;\n   (try match type of N with _ /\\ _ => destruct N end).\n  rew_list~.\n  rew_list. rewrite~ If_l.\n  rewrite~ IHS.\n  rewrite IHS at 1; auto. rew_bool~.\n  rew_list. auto.\n  rew_list. rewrite~ K.\n  rew_list. rewrite~ IHS1. rew_bool~.\nQed.\n\nCorollary sem_to_parse : forall r s,\n  sem r s ->\n  normal r ->\n  parse (r,s,is_nil) = true.\nProof using. intros. forwards~ M: (@sem_to_parse_ind r s nil is_nil). rew_list~ in M. Qed.\n\n(** The second result asserts the reciprocal: if the parse function\n    applied to [r] and [s] returns true, then [s] matches [r] semantically. *)\n\nLemma parse_to_sem_ind : forall r s k,\n  normal r ->\n  parse (r,s,k) = true ->\n  exists s1 s2, s = s1 ++ s2 /\\ sem r s1 /\\ k s2 = true.\nProof using.\n  introv N P. sets_eq p: (r,s). gen r s k.\n  induction_wf IH: parse_sub_wf p. intros. subst p.\n  rewrite~ parse_fix in P. unfold Parse in P. destruct r;\n   simpl in N; (try match type of N with _ /\\ _ => destruct N end).\n  false.\n  exists (nil:text) s. splits~.\n  destruct s; tryfalse. case_if; tryfalse.\n   exists (n0::nil) s. subst. splits~.\n  case_eq (parse (r1,s,k)); intros P1.\n    forwards~ (s1&s2&E&S&P'): IH P1. auto 7. exists~ s1 s2.\n    rewrite P1 in P. rew_bool in P.\n    forwards~ (s1&s2&E&S&P'): IH P. auto 7. exists~ s1 s2.\n  forwards~ (s1&s2&E&S&P'): IH P. auto.\n    forwards~ (s3&s4&E'&S'&K): IH P'. auto.\n    forwards M: text_sub_app E. subst s s2. exists (s1 ++ s3) s4. rew_list~.\n  case_eq (k s); intros K.\n    exists (nil:text) s. splits~.\n    rewrite K in P. rew_bool in P.\n    forwards~ (s1&s2&E&S&P'): IH P. auto.\n    forwards~ (s3&s4&E'&S'&K'): IH P'; try solve [hnfs~].\n      forwards M: text_sub_app E. inverts M. auto. false.\n       applys~ sem_productive S. apply* self_eq_app_r_inv.\n    subst s s2. exists (s1++s3) s4. rew_list~.\nQed.\n\nCorollary parse_to_sem : forall r s,\n  normal r ->\n  parse (r,s,is_nil) = true ->\n  sem r s.\nProof using.\n  intros. forwards~ (s1&s2&E&S&K): (@parse_to_sem_ind r s is_nil).\n  subst. destruct s2; tryfalse. rew_list~ in *.\nQed.\n\n(** We can reformulate those two results in the form of an\n    equivalence between [sem] and [parse] *)\n\nTheorem parse_eq_sem : forall r s, normal r ->\n    (parse (r,s,is_nil) = true)\n  = (sem r s).\nProof using.\n  extens. iff. apply~ parse_to_sem. apply~ sem_to_parse.\nQed.\n\n(** A similar, more general, result *)\n\nTheorem parse_eq_sem_ind : forall r s k, normal r ->\n    (parse (r,s,k) = true)\n  = (exists s1 s2, s = s1 ++ s2 /\\ sem r s1 /\\ k s2 = true).\nProof using.\n  extens. iff M.\n  apply~ parse_to_sem_ind.\n  destruct M as (s1&s2&?&?&?). subst. apply~ sem_to_parse_ind.\nQed.\n", "meta": {"author": "tilk", "repo": "tlc", "sha": "9a07c989dfc12aba4c5fb02107761c8d7e281996", "save_path": "github-repos/coq/tilk-tlc", "path": "github-repos/coq/tilk-tlc/tlc-9a07c989dfc12aba4c5fb02107761c8d7e281996/src/LibFixDemos.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6757057725669335}}
{"text": "(*\nVerificación Formal - 2020-II\nArchivo de proposiciones - Lógica Intuicionista\n\nResultados de lógica intuicionista.\n*)\n\n(*\nDoble negación vs implicación\n*)\nLemma DobleNegacion_Implicacion_LI : \nforall A B : Prop, \n( ~ ~( A -> B) )  <-> ( (~ ~ A) -> (~ ~ B) ). \nProof.\n  unfold not.\n  split.\n  - intros.\n    apply H0.\n    intro.\n    apply H.\n    intro.\n    apply H3 in H2.\n    contradiction.\n  - intros.\n    (* Esta parte de la prueba es la sugerencia *)\n    apply H;\n      intro;\n      apply H0;\n      intro;\n      (*Se generan dos metas, en la primera hay una contradicción\n      y en la segunda es una hipotesis*)\n      contradiction || assumption.\nQed.\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/Tarea2/Props_LI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6757057674256982}}
{"text": "Lemma true_true : true = true.\nProof.\n  reflexivity.\nQed.\n\nLemma false_false : false = false.\nProof.\n  reflexivity.\nQed.\n\nLemma contrapos_bool_tt : forall (a b : bool),\n  (a = true -> b = true) -> (b = false -> a = false).\nProof.\n  intros.\n  case_eq a; intros Ha; try reflexivity.\n    rewrite H0 in H; symmetry; apply H; exact Ha.\nQed.\n\nLemma contrapos_bool_tf : forall (a b : bool),\n  (a = true -> b = false) -> (b = true -> a = false).\nProof.\n  intros a b H1 Hb.\n  case_eq a; intros Ha; try reflexivity.\n    rewrite Hb in *; specialize (H1 Ha); \n    rewrite H1 in *; discriminate.\nQed.\n\nLemma contrapos_bool_ft : forall (a b : bool),\n  (a = false -> b = true) -> (b = false -> a = true).\nProof.\n  intros a b H1 Hb.\n  case_eq a; \n  [reflexivity | \n    intros Ha; specialize (H1 Ha); rewrite H1 in *; discriminate].\nQed.\n\nLemma contrapos_bool_ff : forall (a b : bool),\n  (a = false -> b = false) -> (b = true -> a = true).\nProof.\n  intros a b H1 Hb.\n  case_eq a; intros Ha; [reflexivity | \n  specialize (H1 Ha); rewrite H1 in *; discriminate].\nQed.\n\nLemma contrapos_bool_or : forall (a b c : bool),\n  (a = true <-> b = true \\/ c = true) ->\n    (a = false <-> b = false /\\ c = false).\nProof.\n  intros a b c H.\n  destruct H as [f r].\n  case_eq a; intros Ha; rewrite Ha in *.\n    split; intros H1.\n      discriminate.\n\n      case_eq b; intros Hb; rewrite Hb in *;\n        destruct H1 as [L R]; try discriminate.\n\n        case_eq c; intros Hc; rewrite Hc in *.\n          discriminate.\n\n          symmetry.\n          specialize (f true_true). \n          destruct f; discriminate.\n\n          split; intros H1; try reflexivity.\n            apply conj.\n              case_eq b; intros Hb; rewrite Hb in *.\n                symmetry; apply r; left; reflexivity.\n\n                reflexivity.\n\n              case_eq c; intros Hc; rewrite Hc in *.\n                symmetry; apply r; right; reflexivity.\n\n                reflexivity.\nQed. \n\nLemma if_then_else_same : forall {A : Type} (a : bool) ( b : A),\n  (if a then b else b) = b.\nProof.\n  intros A a b.\n  case a; reflexivity.\nQed.\n\n\nLemma if_then_else_false : forall a : bool,\n  (if a then false else false )= false.\nProof.\n  intros; case a; reflexivity.\nQed.\n\nLemma if_then_else_true : forall a : bool,\n  (if a then true else true )= true.\nProof.\n  intros; case a; reflexivity.\nQed.\n\nLemma if_then_else_true_false : forall a : bool,\n(if a then true else false) = false -> a = false.\nProof.\n  intros a H.\n  case_eq a; intros Ha.\n    rewrite Ha in *.\n    discriminate.\n\n    reflexivity.\nQed.", "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_bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6756888272403192}}
{"text": "Require Import List.\nRequire Import Sorting.Sorted Sorting.Permutation.\n\nDefinition IsSorted {A:Set} (A_cmp:A -> A -> Prop) (l:list A) :=\n  (@StronglySorted A A_cmp l).\n\nDefinition SortedOf {A:Set} (A_cmp:A -> A -> Prop) (l l':list A) :=\n  (@Permutation A l l') /\\\n  (@IsSorted A A_cmp l').\n\nDefinition DecCmp {A:Set} (A_cmp:A -> A -> Prop) :=\n  forall x y,\n    {A_cmp x y} + {~ A_cmp x y}.\n\nDefinition Total {A:Set} (A_cmp:A -> A -> Prop) :=\n  forall x y,\n    (~ A_cmp x y) ->\n    A_cmp y x.\n\nLemma Permutation_cons_step:\n  forall A (a a':A) x y,\n    Permutation (a :: x) y ->\n    Permutation (a :: a' :: x) (a' :: y).\nProof.\n  intros. rename H into PM.\n  eapply Permutation_trans.\n  apply perm_swap.\n  apply perm_skip.\n  auto.\nQed.\n\n", "meta": {"author": "rfindler", "repo": "395-2013", "sha": "afaeb6f4076a1330bbdeb4537417906bbfab5119", "save_path": "github-repos/coq/rfindler-395-2013", "path": "github-repos/coq/rfindler-395-2013/395-2013-afaeb6f4076a1330bbdeb4537417906bbfab5119/sort/sorting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6756172521866547}}
{"text": "Require Import ZArith.\n\nModule NaiveLang.\n  Definition expr := (nat -> option Z) -> Prop.\n  Definition context := expr -> Prop.\n  Definition impp (e1 e2 : expr) : expr := fun st => e1 st -> e2 st.\n  Definition andp (e1 e2 : expr) : expr := fun st => e1 st /\\ e2 st.\n  Definition orp  (e1 e2 : expr) : expr := fun st => e1 st \\/ e2 st.\n  Definition falsep : expr := fun st => False.\n\n  Definition join : (nat -> option Z) -> (nat -> option Z) -> (nat -> option Z) -> Prop :=\n    fun x y z =>\n      forall p: nat,\n       (exists v, x p = Some v /\\ y p = None /\\ z p = Some v) \\/\n       (exists v, x p = None /\\ y p = Some v /\\ z p = Some v) \\/\n       (x p = None /\\ y p = None /\\ z p = None).\n  Definition sepcon (e1 e2 : expr) : expr := fun st =>\n    exists st1 st2, join st1 st2 st /\\ e1 st1 /\\ e2 st2.\n  Definition emp : expr := fun st =>\n    forall p, st p = None.\n\n  Definition provable (e : expr) : Prop := forall st, e st.\nEnd NaiveLang.\n\nRequire Import interface_1.\n\nModule NaiveRule.\n  Import NaiveLang.\n  Include DerivedNames (NaiveLang).\n  Lemma modus_ponens :\n    forall x y : expr, provable (impp x y) -> provable x -> provable y.\n  Proof. unfold provable, impp. auto. Qed.\n\n  Lemma axiom1 : forall x y : expr, provable (impp x (impp y x)).\n  Proof. unfold provable, impp. auto. Qed.\n\n  Lemma axiom2 : forall x y z : expr,\n      provable (impp (impp x (impp y z)) (impp (impp x y) (impp x z))).\n  Proof. unfold provable, impp. auto. Qed.\n\n  Lemma andp_intros :\n    forall x y : expr, provable (impp x (impp y (andp x y))).\n  Proof. unfold provable, impp, andp. auto. Qed.\n\n  Lemma andp_elim1 : forall x y : expr, provable (impp (andp x y) x).\n  Proof. unfold provable, impp, andp. tauto. Qed.\n\n  Lemma andp_elim2 : forall x y : expr, provable (impp (andp x y) y).\n  Proof. unfold provable, impp, andp. tauto. Qed.\n\n  Lemma orp_intros1 : forall x y : expr, provable (impp x (orp x y)).\n  Proof. unfold provable, impp, orp. auto. Qed.\n\n  Lemma orp_intros2 : forall x y : expr, provable (impp y (orp x y)).\n  Proof. unfold provable, impp, orp. auto. Qed.\n\n  Lemma orp_elim : forall x y z : expr,\n      provable (impp (impp x z) (impp (impp y z) (impp (orp x y) z))).\n  Proof. unfold provable, impp, orp. tauto. Qed.\n\n  Lemma falsep_elim : forall x : expr, provable (impp falsep x).\n  Proof. unfold provable, impp, falsep. destruct 1. Qed.\n\n  Lemma excluded_middle : forall x : expr, provable (orp x (negp x)).\n  Proof. unfold provable, orp, negp, impp, falsep. intros; tauto. Qed.\n\n  Axiom sepcon_comm: forall x y, provable (iffp (sepcon x y) (sepcon y x)).\n  Axiom sepcon_assoc: forall x y z,\n      provable (iffp (sepcon x (sepcon y z)) (sepcon (sepcon x y) z)).\n  Axiom sepcon_mono : (forall x1 x2 y1 y2 : expr, provable (impp x1 x2) -> provable (impp y1 y2) -> provable (impp (sepcon x1 y1) (sepcon x2 y2))) .\n  Axiom sepcon_emp : (forall x : expr, provable (iffp (sepcon x emp) x)) .\n  Axiom falsep_sepcon_left : (forall x : expr, provable (impp (sepcon falsep x) falsep)) .\n  Axiom orp_sepcon_left : (forall x y z : expr, provable (impp (sepcon (orp x y) z) (orp (sepcon x z) (sepcon y z)))) .\nEnd NaiveRule.\n\nModule T := LogicTheorem NaiveLang NaiveRule.\nModule Solver := IPSolver NaiveLang.\nImport T.\nImport Solver.\n\n\n", "meta": {"author": "QinxiangCao", "repo": "UnifySL", "sha": "cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d", "save_path": "github-repos/coq/QinxiangCao-UnifySL", "path": "github-repos/coq/QinxiangCao-UnifySL/UnifySL-cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d/LogicGenerator/demo/implementation_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658466, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6756172480068863}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(************************************************************************)\n(** * Some properties of the operators on relations                     *)\n(************************************************************************)\n(** * Initial version by Bruno Barras                                   *)\n(************************************************************************)\n\nSet Warnings \"-notation-overridden\".\n\nRequire Import CRelationClasses.\nRequire Import Equations.Init.\nRequire Import Equations.Type.Logic.\nRequire Import Equations.Type.Relation.\n\nImport Sigma_Notations.\nImport Id_Notations.\n\n(** Synonyms *)\nNotation inclusion R R' := (subrelation R R').\n\n#[export]\nHint Constructors sum : relations.\n\nSection Properties.\n\n  Context{A : Type}.\n  Variable R : relation A.\n\n  Section Clos_Refl_Trans.\n\n    Local Notation \"R *\" := (clos_refl_trans R)\n      (at level 8, no associativity, format \"R *\").\n\n    (** Correctness of the reflexive-transitive closure operator *)\n\n    Lemma clos_rt_is_preorder : PreOrder R*.\n    Proof.\n      constructor.\n      - exact (rt_refl R).\n      - exact (rt_trans R).\n    Defined.\n\n    (** Idempotency of the reflexive-transitive closure operator *)\n\n    Lemma clos_rt_idempotent : subrelation (R*)* R*.\n    Proof.\n      red.\n      induction 1; auto with relations.\n      intros.\n      apply rt_trans with y; auto with relations.\n    Defined.\n\n  End Clos_Refl_Trans.\n\n  Section Clos_Refl_Sym_Trans.\n\n    (** Reflexive-transitive closure is included in the\n        reflexive-symmetric-transitive closure *)\n\n    Lemma clos_rt_clos_rst :\n      subrelation (clos_refl_trans R) (clos_refl_sym_trans R).\n    Proof.\n      red.\n      induction 1; auto with relations.\n      apply rst_trans with y; auto with relations.\n    Defined.\n\n    (** Reflexive closure is included in the\n        reflexive-transitive closure *)\n\n    Lemma clos_r_clos_rt :\n      inclusion (clos_refl R) (clos_refl_trans R).\n    Proof.\n      induction 1 as [? ?| ].\n      - constructor; auto.\n      - constructor 2.\n    Defined.\n\n    Lemma clos_rt_t : forall x y z,\n      clos_refl_trans R x y -> trans_clos R y z ->\n      trans_clos R x z.\n    Proof.\n      induction 1 as [b d H1|b|a b d H1 H2 IH1 IH2]; auto.\n      intro H. apply t_trans with (y:=d); auto.\n      constructor. auto.\n    Defined.\n\n    (** Correctness of the reflexive-symmetric-transitive closure *)\n\n    Lemma clos_rst_is_equiv : Equivalence (clos_refl_sym_trans R).\n    Proof.\n      constructor.\n      - exact (rst_refl R).\n      - exact (rst_sym R).\n      - exact (rst_trans R).\n    Defined.\n\n    (** Idempotency of the reflexive-symmetric-transitive closure operator *)\n\n    Lemma clos_rst_idempotent :\n      inclusion (clos_refl_sym_trans (clos_refl_sym_trans R))\n      (clos_refl_sym_trans R).\n    Proof.\n      red.\n      induction 1; auto with relations.\n      apply rst_trans with y; auto with relations.\n    Defined.\n\n  End Clos_Refl_Sym_Trans.\n\n  Section Equivalences.\n\n  (** *** Equivalences between the different definition of the reflexive,\n      symmetric, transitive closures *)\n\n  (** *** Contributed by P. Castéran *)\n\n    (** Direct transitive closure vs left-step extension *)\n\n    Lemma clos_t1n_trans : forall x y, trans_clos_1n R x y -> trans_clos R x y.\n    Proof.\n     induction 1.\n     - left; assumption.\n     - right with y; auto.\n       left; auto.\n    Defined.\n\n    Lemma trans_clos_t1n : forall x y, trans_clos R x y -> trans_clos_1n R x y.\n    Proof.\n      induction 1.\n      - left; assumption.\n      - generalize IHX2; clear IHX2; induction IHX1.\n        -- right with y; auto.\n        -- right with y; auto.\n           eapply IHIHX1; auto.\n           apply clos_t1n_trans; auto.\n    Defined.\n\n    Lemma trans_clos_t1n_iff : forall x y,\n        trans_clos R x y <-> trans_clos_1n R x y.\n    Proof.\n      intros x y.\n      exists (trans_clos_t1n x y).\n      apply (clos_t1n_trans x y).\n    Defined.\n\n    (** Direct transitive closure vs right-step extension *)\n\n    Lemma clos_tn1_trans : forall x y, trans_clos_n1 R x y -> trans_clos R x y.\n    Proof.\n      induction 1.\n      - left; assumption.\n      - right with y; auto.\n        left; assumption.\n    Defined.\n\n    Lemma trans_clos_tn1 :  forall x y, trans_clos R x y -> trans_clos_n1 R x y.\n    Proof.\n      induction 1.\n      - left; assumption.\n      - elim IHX2.\n        -- intro y0; right with y; auto.\n        -- intros. right with y0; auto.\n    Defined.\n\n    Lemma trans_clos_tn1_iff : forall x y,\n        trans_clos R x y <-> trans_clos_n1 R x y.\n    Proof.\n      split.\n      - apply trans_clos_tn1.\n      - apply clos_tn1_trans.\n    Defined.\n\n    (** Direct reflexive-transitive closure is equivalent to\n        transitivity by left-step extension *)\n\n    Lemma clos_rt1n_step : forall x y, R x y -> clos_refl_trans_1n R x y.\n    Proof.\n      intros x y H.\n      right with y;[assumption|left].\n    Defined.\n\n    Lemma clos_rtn1_step : forall x y, R x y -> clos_refl_trans_n1 R x y.\n    Proof.\n      intros x y H.\n      right with x;[assumption|left].\n    Defined.\n\n    Lemma clos_rt1n_rt : forall x y,\n        clos_refl_trans_1n R x y -> clos_refl_trans R x y.\n    Proof.\n      induction 1.\n      - constructor 2.\n      - constructor 3 with y; auto.\n        constructor 1; auto.\n    Defined.\n\n    Lemma clos_rt_rt1n : forall x y,\n        clos_refl_trans R x y -> clos_refl_trans_1n R x y.\n    Proof.\n      induction 1.\n      - apply clos_rt1n_step; assumption.\n      - left.\n      - generalize IHX2; clear IHX2;\n          induction IHX1; auto.\n        right with y; auto.\n        eapply IHIHX1; auto.\n        apply clos_rt1n_rt; auto.\n    Defined.\n\n    Lemma clos_rt_rt1n_iff : forall x y,\n      clos_refl_trans R x y <-> clos_refl_trans_1n R x y.\n    Proof.\n      split.\n      - apply clos_rt_rt1n.\n      - apply clos_rt1n_rt.\n    Defined.\n\n    (** Direct reflexive-transitive closure is equivalent to\n        transitivity by right-step extension *)\n\n    Lemma clos_rtn1_rt : forall x y,\n        clos_refl_trans_n1 R x y -> clos_refl_trans R x y.\n    Proof.\n      induction 1.\n      - constructor 2.\n      - constructor 3 with y; auto.\n        constructor 1; assumption.\n    Defined.\n\n    Lemma clos_rt_rtn1 :  forall x y,\n        clos_refl_trans R x y -> clos_refl_trans_n1 R x y.\n    Proof.\n      induction 1.\n      - apply clos_rtn1_step; auto.\n      - left.\n      - elim IHX2; auto.\n        intros.\n        right with y0; auto.\n    Defined.\n\n    Lemma clos_rt_rtn1_iff : forall x y,\n        clos_refl_trans R x y <-> clos_refl_trans_n1 R x y.\n    Proof.\n      split.\n      - apply clos_rt_rtn1.\n      - apply clos_rtn1_rt.\n    Defined.\n\n    (** Induction on the left transitive step *)\n\n    Lemma clos_refl_trans_ind_left :\n      forall (x:A) (P:A -> Type), P x ->\n\t(forall y z:A, clos_refl_trans R x y -> P y -> R y z -> P z) ->\n\tforall z:A, clos_refl_trans R x z -> P z.\n    Proof.\n      intros.\n      revert X X0.\n      induction X1; intros; auto with relations.\n      { apply X0 with x; auto with relations. }\n      apply IHX1_2.\n      { apply IHX1_1; auto with relations. }\n      intros.\n      apply X0 with y0; auto with relations.\n      apply rt_trans with y; auto with relations.\n    Defined.\n\n    (** Induction on the right transitive step *)\n\n    Lemma rt1n_ind_right : forall (P : A -> Type) (z:A),\n      P z ->\n      (forall x y, R x y -> clos_refl_trans_1n R y z -> P y -> P x) ->\n      forall x, clos_refl_trans_1n R x z -> P x.\n      induction 3; auto.\n      apply X0 with y; auto.\n    Defined.\n\n    Lemma clos_refl_trans_ind_right : forall (P : A -> Type) (z:A),\n      P z ->\n      (forall x y, R x y -> P y -> clos_refl_trans R y z -> P x) ->\n      forall x, clos_refl_trans R x z -> P x.\n      intros P z Hz IH x Hxz.\n      apply clos_rt_rt1n_iff in Hxz.\n      elim Hxz using rt1n_ind_right; auto.\n      clear x Hxz.\n      intros x y Hxy Hyz Hy.\n      apply clos_rt_rt1n_iff in Hyz.\n      eauto.\n    Defined.\n\n    (** Direct reflexive-symmetric-transitive closure is equivalent to\n        transitivity by symmetric left-step extension *)\n\n    Lemma clos_rst1n_rst  : forall x y,\n      clos_refl_sym_trans_1n R x y -> clos_refl_sym_trans R x y.\n    Proof.\n      induction 1.\n      - constructor 2.\n      - constructor 4 with y; auto.\n        case s; [constructor 1 | constructor 3; constructor 1]; auto.\n    Defined.\n\n    Lemma clos_rst1n_trans : forall x y z, clos_refl_sym_trans_1n R x y ->\n        clos_refl_sym_trans_1n R y z -> clos_refl_sym_trans_1n R x z.\n      induction 1.\n      - auto.\n      - intros; right with y; eauto.\n    Defined.\n\n    Lemma clos_rst1n_sym : forall x y, clos_refl_sym_trans_1n R x y ->\n      clos_refl_sym_trans_1n R y x.\n    Proof.\n      intros x y H; elim H.\n      - constructor 1.\n      - intros x0 y0 z D H0 H1; apply clos_rst1n_trans with y0; auto.\n        right with x0.\n        + destruct D; [right|left]; auto.\n        + left.\n    Defined.\n\n    Lemma clos_rst_rst1n  : forall x y,\n      clos_refl_sym_trans R x y -> clos_refl_sym_trans_1n R x y.\n      induction 1.\n      - constructor 2 with y; auto with relations.\n        constructor 1.\n      - constructor 1.\n      - apply clos_rst1n_sym; auto.\n      - eapply clos_rst1n_trans; eauto.\n    Defined.\n\n    Lemma clos_rst_rst1n_iff : forall x y,\n      clos_refl_sym_trans R x y <-> clos_refl_sym_trans_1n R x y.\n    Proof.\n      split.\n      - apply clos_rst_rst1n.\n      - apply clos_rst1n_rst.\n    Defined.\n\n    (** Direct reflexive-symmetric-transitive closure is equivalent to\n        transitivity by symmetric right-step extension *)\n\n    Lemma clos_rstn1_rst : forall x y,\n      clos_refl_sym_trans_n1 R x y -> clos_refl_sym_trans R x y.\n    Proof.\n      induction 1.\n      - constructor 2.\n      - constructor 4 with y; auto.\n        case s; [constructor 1 | constructor 3; constructor 1]; auto.\n    Defined.\n\n    Lemma clos_rstn1_trans : forall x y z, clos_refl_sym_trans_n1 R x y ->\n      clos_refl_sym_trans_n1 R y z -> clos_refl_sym_trans_n1 R x z.\n    Proof.\n      intros x y z H1 H2.\n      induction H2.\n      - auto.\n      - intros.\n        right with y0; eauto.\n    Defined.\n\n    Lemma clos_rstn1_sym : forall x y, clos_refl_sym_trans_n1 R x y ->\n      clos_refl_sym_trans_n1 R y x.\n    Proof.\n      intros x y H; elim H.\n      - constructor 1.\n      - intros y0 z D H0 H1. apply clos_rstn1_trans with y0; auto.\n        right with z.\n        + destruct D; auto with relations.\n        + left.\n    Defined.\n\n    Lemma clos_rst_rstn1 : forall x y,\n      clos_refl_sym_trans R x y -> clos_refl_sym_trans_n1 R x y.\n    Proof.\n      induction 1.\n      - constructor 2 with x; auto with relations.\n        constructor 1.\n      - constructor 1.\n      - apply clos_rstn1_sym; auto.\n      - eapply clos_rstn1_trans; eauto.\n    Defined.\n\n    Lemma clos_rst_rstn1_iff : forall x y,\n      clos_refl_sym_trans R x y <-> clos_refl_sym_trans_n1 R x y.\n    Proof.\n      split.\n      - apply clos_rst_rstn1.\n      - apply clos_rstn1_rst.\n    Defined.\n\n  End Equivalences.\n\n  Lemma trans_clos_transp_permute : forall x y,\n    transp (trans_clos R) x y <-> trans_clos (transp R) x y.\n  Proof.\n    split; induction 1;\n    (apply t_step; assumption) || eapply t_trans; eassumption.\n  Defined.\n\nEnd Properties.\n", "meta": {"author": "mattam82", "repo": "Coq-Equations", "sha": "5603bfff39f3866eed8f010591b5503d5776fa4e", "save_path": "github-repos/coq/mattam82-Coq-Equations", "path": "github-repos/coq/mattam82-Coq-Equations/Coq-Equations-5603bfff39f3866eed8f010591b5503d5776fa4e/theories/Type/Relation_Properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.6756090279996879}}
{"text": "(* ********************************************** *)\n(* Types and Semantics for Programming Languages  *)\n(* ********************************************** *)\n\n(* Place an X in front of the appropriate statement *)\n(* [ ]  I have done Problems 1 and 2 *)\n(* [ ]  I have done Problems 1 and 3 *)\n\n\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 Export Maps.\nRequire Export SfLib.\n\n(* ********************************************** *)\n(* Problem 1 *)\n(* ********************************************** *)\n\nInductive last {X : Type} : list X -> X -> Prop :=\n  | last_end : forall x,\n      last (x :: nil) x\n  | last_step : forall x y xs,\n      last xs y -> last (x :: xs) y.\n\nTheorem last_app : forall (X : Type) (x : X) (xs : list X),\n  last xs x -> exists xs', xs = xs' ++ [x].\nProof.\n  intros.\n  induction xs.\n + inversion H.\n + inversion H. subst.\n    - exists nil. reflexivity.\n    - apply IHxs in H3. inversion H3. subst.\n      exists (a :: x1). reflexivity.\nQed.\n\n(* ********************************************** *)\n(* Problem 2 *)\n(* ********************************************** *)\n\n(* Arithmetic and boolean expressions *)\n\nDefinition state := total_map nat.\n\nDefinition ble_nat := leb.\t\t    \n\nInductive aexp : Type :=\n  | ANum : nat -> aexp\n  | AId : id -> aexp\n  | APlus : aexp -> aexp -> aexp\n  | AMinus : aexp -> aexp -> aexp\n  | AMult : aexp -> aexp -> aexp.\n\nInductive bexp : Type :=\n  | BTrue : bexp\n  | BFalse : bexp\n  | BEq : aexp -> aexp -> bexp\n  | BLe : aexp -> aexp -> bexp\n  | BNot : bexp -> bexp\n  | BAnd : bexp -> bexp -> bexp.\n\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\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  | CLoop : com -> 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 \"'IFB' c1 'THEN' c2 'ELSE' c3 'FI'\" :=\n  (CIf c1 c2 c3) (at level 80, right associativity).\nNotation \"'WHILE' b 'DO' c 'END'\" :=\n  (CWhile b c) (at level 80, right associativity).\nNotation \"'LOOP' c1 'WHILE' b 'DO' c2 'END'\" :=\n  (CLoop c1 b c2) (at level 80, right associativity).\n\n(* Evaluation relation *)\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 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_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  | E_LoopEnd : forall st st' c1 b c2,\n       c1 / st || st' ->\n       beval st' b = false ->\n       (LOOP c1 WHILE b DO c2 END) / st || st'\n  | E_LoopLoop : forall st st' st'' st''' c1 b c2,\n       c1 / st || st' ->\n       beval st' b = true ->\n       c2 / st' || st'' ->\n       (LOOP c1 WHILE b DO c2 END) / st'' || st''' ->\n       (LOOP c1 WHILE b DO c2 END) / st || st'''\n\n  where \"c1 '/' st '||' st'\" := (ceval c1 st st').\n\n(* Assertions *)\n\nDefinition Assertion := state -> Prop.\n\nDefinition assert_implies (P Q : Assertion) : Prop :=\n  forall st, P st -> Q st.\n\nNotation \"P ->> Q\" :=\n  (assert_implies P Q) (at level 80) : hoare_spec_scope.\nOpen Scope hoare_spec_scope.\n\nNotation \"P <<->> Q\" :=\n  (P ->> Q /\\ Q ->> P) (at level 80) : hoare_spec_scope.\n\n(* Hoare triples *)\n\nDefinition hoare_triple\n           (P:Assertion) (c:com) (Q:Assertion) : Prop :=\n  forall st st',\n       c / st || st'  ->\n       P st  ->\n       Q st'.\n\nNotation \"{{ P }}  c  {{ Q }}\" :=\n  (hoare_triple P c Q) (at level 90, c at next level)\n  : hoare_spec_scope.\n\n(* Assertions *)\n\nDefinition bassn b : Assertion :=\n  fun st => (beval st b = true).\n\nLemma bexp_eval_true : forall b st,\n  beval st b = true -> (bassn b) st.\nProof.\n  intros b st Hbe.\n  unfold bassn. assumption.  Qed.\n\nLemma bexp_eval_false : forall b st,\n  beval st b = false -> ~ ((bassn b) st).\nProof.\n  intros b st Hbe contra.\n  unfold bassn in contra.\n  rewrite -> contra in Hbe. inversion Hbe.  Qed.\n\n(* Assignment *)\n\n(*\n             ------------------------------ (hoare_asgn)\n             {{Q [X |-> a]}} X::=a {{Q}}\n*)\n\n\nDefinition assn_sub X a P : Assertion :=\n  fun (st : state) =>\n    P (t_update st X (aeval st a)).\n\nNotation \"P [ X |-> a ]\" := (assn_sub X a P) (at level 10).\n\nTheorem hoare_asgn : forall Q X a,\n  {{Q [X |-> a]}} (X ::= a) {{Q}}.\nProof.\n  unfold hoare_triple.\n  intros Q X a st st' HE HQ.\n  inversion HE. subst.\n  unfold assn_sub in HQ. assumption.  Qed.\n\n(* Consequence *)\n\n(*\n                {{P'}} c {{Q'}}\n                   P ->> P'\n                   Q' ->> Q\n         -----------------------------   (hoare_consequence)\n                {{P}} c {{Q}}\n*)\n\nTheorem hoare_consequence_pre : forall (P P' Q : Assertion) c,\n  {{P'}} c {{Q}} ->\n  P ->> P' ->\n  {{P}} c {{Q}}.\nProof.\n  intros P P' Q c Hhoare Himp.\n  intros st st' Hc HP. apply (Hhoare st st'). \n  assumption. apply Himp. assumption. Qed.\n\nTheorem hoare_consequence_post : forall (P Q Q' : Assertion) c,\n  {{P}} c {{Q'}} ->\n  Q' ->> Q ->\n  {{P}} c {{Q}}.\nProof.\n  intros P Q Q' c Hhoare Himp.\n  intros st st' Hc HP. \n  apply Himp.\n  apply (Hhoare st st'). \n  assumption. assumption. Qed.\n\nTheorem hoare_consequence : forall (P P' Q Q' : Assertion) c,\n  {{P'}} c {{Q'}} ->\n  P ->> P' ->\n  Q' ->> Q ->\n  {{P}} c {{Q}}.\nProof.\n  intros P P' Q Q' c Hht HPP' HQ'Q.\n  apply hoare_consequence_pre with (P' := P').\n  apply hoare_consequence_post with (Q' := Q').\n  assumption. assumption. assumption.  Qed.\n\n(* Skip *)\n\n(*\n             --------------------  (hoare_skip)\n             {{ P }} SKIP {{ P }}\n*)\n\nTheorem hoare_skip : forall P,\n     {{P}} SKIP {{P}}.\nProof.\n  intros P st st' H HP. inversion H. subst.\n  assumption.  Qed.\n\n(* Sequencing *)\n\n(*\n               {{ P }} c1 {{ Q }} \n               {{ Q }} c2 {{ R }}\n              ---------------------  (hoare_seq)\n              {{ P }} c1;;c2 {{ R }}\n*)\n\nTheorem hoare_seq : forall P Q R c1 c2,\n     {{Q}} c2 {{R}} ->\n     {{P}} c1 {{Q}} ->\n     {{P}} c1;;c2 {{R}}.\nProof.\n  intros P Q R c1 c2 H1 H2 st st' H12 Pre.\n  inversion H12; subst.\n  apply (H1 st'0 st'); try assumption.\n  apply (H2 st st'0); assumption. Qed.\n\n(* Conditional *)\n\n(*\n              {{P /\\  b}} c1 {{Q}}\n              {{P /\\ ~b}} c2 {{Q}}\n      ------------------------------------  (hoare_if)\n      {{P}} IFB b THEN c1 ELSE c2 FI {{Q}} \n*)\n\nTheorem hoare_if : forall P Q b c1 c2,\n  {{fun st => P st /\\ bassn b st}} c1 {{Q}} ->\n  {{fun st => P st /\\ ~(bassn b st)}} c2 {{Q}} ->\n  {{P}} (IFB b THEN c1 ELSE c2 FI) {{Q}}.\nProof.\n  intros P Q b c1 c2 HTrue HFalse st st' HE HP.\n  inversion HE; subst. \n  + (* \"b is true\" *)\n    apply (HTrue st st'). \n      assumption. \n      split. assumption. \n             apply bexp_eval_true. assumption.\n  + (* \"b is false\" *)\n    apply (HFalse st st'). \n      assumption. \n      split. assumption.\n             apply bexp_eval_false. assumption. Qed.\n\n(* While *)\n\n(*\n               {{P /\\ b}} c {{P}}\n        -----------------------------------  (hoare_while)\n        {{P}} WHILE b DO c END {{P /\\ ~b}}\n    The proposition [P] is called an _invariant_ of the loop.\n*)\n\nLemma hoare_while : forall P b c,\n  {{fun st => P st /\\ bassn b st}} c {{P}} ->\n  {{P}} WHILE b DO c END {{fun st => P st /\\ ~ (bassn b st)}}.\nProof.\n  intros P b c Hhoare st st' He HP.\n  (* Like we've seen before, we need to reason by induction \n     on [He], because, in the \"keep looping\" case, its hypotheses \n     talk about the whole loop instead of just [c]. *)\n  remember (WHILE b DO c END) as wcom eqn:Heqwcom.\n  induction He;\n    try (inversion Heqwcom); subst; clear Heqwcom.\n  + (* Case \"E_WhileEnd\" *)\n    split. assumption. apply bexp_eval_false. assumption.\n  + (* Case \"E_WhileLoop\" *)\n    apply IHHe2. reflexivity.\n    apply (Hhoare st st'). assumption.\n      split. assumption. apply bexp_eval_true. assumption.\nQed.\n\nTheorem hoare_loop : forall P Q c1 b c2,\n  {{P}} c1 {{Q}} ->\n  {{fun st => Q st /\\ bassn b st}} c2 {{P}} ->\n  {{P}} LOOP c1 WHILE b DO c2 END {{ fun st => Q st /\\ ~(bassn b st)}}.\nProof.\n    intros P Q c1 b c2 HTriple1 HTrue st st' HE HP.\n    remember (LOOP c1 WHILE b DO c2 END) as wcom eqn:Heqwcom.\n    induction HE;\n    try (inversion Heqwcom); subst; clear Heqwcom.\n    + split. \n       - apply ( HTriple1 st st'). assumption. assumption.\n       - apply bexp_eval_false. assumption.\n    + apply IHHE3. reflexivity.\n       apply (HTrue st'). assumption.\n       split.\n       - apply ( HTriple1 st st'). assumption. assumption.\n       - apply bexp_eval_true. assumption.  \nQed.\n\n(* ********************************************** *)\n(* Problem 3 *)\n(* ********************************************** *)\n\n(* Types *)\n\nInductive ty : Type := \n  | TBool  : ty \n  | TArrow : ty -> ty -> ty.\n\n(* Terms *)\n\nInductive tm : Type :=\n  | tvar : id -> tm\n  | tapp : tm -> tm -> tm\n  | tabs : id -> ty -> tm -> tm\n  | ttrue : tm\n  | tfalse : tm\n  | tif : tm -> tm -> tm -> tm.\n\n(* Values *)\n\nInductive value : tm -> Prop :=\n  | v_abs : forall x T t,\n      value (tabs x T t)\n  | v_true : \n      value ttrue\n  | v_false : \n      value tfalse.\n\nHint Constructors value.\n\n(* Substitution *)\n\nReserved Notation \"'[' x ':=' s ']' t\" (at level 20).\n\nFixpoint subst (x:id) (s:tm) (t:tm) : tm :=\n  match t with\n  | tvar x' => \n      if beq_id x x' then s else t\n  | tabs x' T t1 => \n      tabs x' T (if beq_id x x' then t1 else ([x:=s] t1)) \n  | tapp t1 t2 => \n      tapp ([x:=s] t1) ([x:=s] t2)\n  | ttrue => \n      ttrue\n  | tfalse => \n      tfalse\n  | tif t1 t2 t3 => \n      tif ([x:=s] t1) ([x:=s] t2) ([x:=s] t3)\n  end\n\nwhere \"'[' x ':=' s ']' t\" := (subst x s t).\n\n(* Evaluation relation *)\n\nReserved Notation \"t1 '==>' t2\" (at level 40).\n\nInductive step : tm -> tm -> Prop :=\n  | ST_AppAbs : forall x T t12 v2,\n         value v2 ->\n         (tapp (tabs x T t12) v2) ==> [x:=v2]t12\n  | ST_App1 : forall t1 t1' t2,\n         t1 ==> t1' ->\n         tapp t1 t2 ==> tapp t1' t2\n  | ST_App2 : forall v1 t2 t2',\n         value v1 ->\n         t2 ==> t2' -> \n         tapp v1 t2 ==> tapp v1  t2'\n  | ST_IfTrue : forall t1 t2,\n      (tif ttrue t1 t2) ==> t1\n  | ST_IfFalse : forall t1 t2,\n      (tif tfalse t1 t2) ==> t2\n  | ST_If : forall t1 t1' t2 t3,\n      t1 ==> t1' ->\n      (tif t1 t2 t3) ==> (tif t1' t2 t3)\n\nwhere \"t1 '==>' t2\" := (step t1 t2).\n\nHint Constructors step.\n\nDefinition relation a := a -> a -> Prop.\n\nInductive multi {X:Type} (R: relation X) : relation X :=\n  | multi_refl : forall (x : X), multi R x x\n  | multi_step : forall (x y z : X),\n                    R x y ->\n                    multi R y z ->\n                    multi R x z.\n\nNotation \"t1 '==>*' t2\" := (multi step t1 t2) (at level 40).\n\n(* Contexts *)\n\nDefinition context := partial_map ty.\n\n(* Typing relation *)\n\nReserved Notation \"Gamma '|-' t '\\in' T\" (at level 40).\n    \nInductive has_type : context -> tm -> ty -> Prop :=\n  | T_Var : forall Gamma x T,\n      Gamma x = Some T ->\n      Gamma |- tvar x \\in T\n  | T_Abs : forall Gamma x T11 T12 t12,\n      update Gamma x T11 |- t12 \\in T12 -> \n      Gamma |- tabs x T11 t12 \\in TArrow T11 T12\n  | T_App : forall T11 T12 Gamma t1 t2,\n      Gamma |- t1 \\in TArrow T11 T12 -> \n      Gamma |- t2 \\in T11 -> \n      Gamma |- tapp t1 t2 \\in T12\n  | T_True : forall Gamma,\n       Gamma |- ttrue \\in TBool\n  | T_False : forall Gamma,\n       Gamma |- tfalse \\in TBool\n  | T_If : forall t1 t2 t3 T Gamma,\n       Gamma |- t1 \\in TBool ->\n       Gamma |- t2 \\in T ->\n       Gamma |- t3 \\in T ->\n       Gamma |- tif t1 t2 t3 \\in T\n\nwhere \"Gamma '|-' t '\\in' T\" := (has_type Gamma t T).\n\nHint Constructors has_type.\n\n(* Canonical Forms *)\n\nLemma cannonical_forms_bool : forall t,\n  empty |- t \\in TBool ->\n  value t ->\n  (t = ttrue) \\/ (t = tfalse).\nProof.\n  intros t HT HVal.\n  inversion HVal; intros; subst; try inversion HT; auto.\nQed.\n\nLemma cannonical_forms_fun : forall t T1 T2,\n  empty |- t \\in (TArrow T1 T2) ->\n  value t ->\n  exists x u, t = tabs x T1 u.\nProof.\n  intros t T1 T2 HT HVal.\n  inversion HVal; intros; subst; try inversion HT; subst; auto.\n  exists x. exists t0.  auto.\nQed.\n   \n(* Progress, by induction on type derivation *)\n\nTheorem progress : forall t T, \n     empty |- t \\in T ->\n     value t \\/ exists t', t ==> t'.\n\nProof with eauto.\n  intros t T Ht.\n  remember (@empty ty) as Gamma.\n  induction Ht; subst Gamma...\n  + (* Case \"T_Var\" *)\n    (* contradictory: variables cannot be typed in an \n       empty context *)\n    inversion H. \n\n  + (* Case \"T_App\" *) \n    (* [t] = [t1 t2].  Proceed by cases on whether [t1] is a \n       value or steps... *)\n    right. destruct IHHt1...\n    - (* t1 is a value *)\n      destruct IHHt2...\n      * (* t2 is also a value *)\n        assert (exists x0 t0, t1 = tabs x0 T11 t0).\n        eapply cannonical_forms_fun; eauto.\n        destruct H1 as [x0 [t0 Heq]]. subst.\n        exists ([x0:=t2]t0)...\n\n      * (* t2 steps *)\n        inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...\n\n    - (* t1 steps *)\n      inversion H as [t1' Hstp]. exists (tapp t1' t2)...\n\n  + (* Case \"T_If\" *)\n    right. destruct IHHt1...\n    \n    - (* t1 is a value *)\n      destruct (cannonical_forms_bool t1); subst; eauto.\n\n    - (* t1 also steps *)\n      inversion H as [t1' Hstp]. exists (tif t1' t2 t3)...\nQed.\n\n\n", "meta": {"author": "i-zhen", "repo": "PG-Coursework", "sha": "7661a654978eb779fb126e1c0601761b538e5d5e", "save_path": "github-repos/coq/i-zhen-PG-Coursework", "path": "github-repos/coq/i-zhen-PG-Coursework/PG-Coursework-7661a654978eb779fb126e1c0601761b538e5d5e/TSPL - Software Foundation/Exam2014/Exam_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.6756090211999143}}
{"text": "Require Import List ListSet basic Morphisms RelationClasses Equivalence.\nImport ListNotations.\n\nSection Definitions.\n\nDefinition union_fold {A B} (eq_dec : dec_type B) (f : A -> set B) (s : set A) (base : set B) : set B :=\n  set_fold_left (fun acc a => set_union eq_dec acc (f a)) s base.\nDefinition union_map {A B} (eq_dec : dec_type B) (f : A -> set B) (s : set A) : set B :=\n  union_fold eq_dec f s (empty_set _).\n\nDefinition triple_union_fold {A B C D}\n           (Beq_dec : dec_type B) (Ceq_dec : dec_type C) (Deq_dec : dec_type D)\n           (f : A -> (set B * set C * set D)) (l : set A) (base : set B * set C * set D) :\n  (set B * set C * set D) :=\n  set_fold_left\n    (fun (acc : (set B * set C * set D)) (a : A) =>\n               match acc with\n                   (bs,cs,ds) =>\n                   match f a with\n                       (bs',cs',ds') =>\n                       (set_union Beq_dec bs bs', set_union Ceq_dec cs cs', set_union Deq_dec ds ds')\n                   end\n               end)\n    l base.\n\nDefinition triple_union_map {A B C D}\n           (Beq_dec : dec_type B) (Ceq_dec : dec_type C) (Deq_dec : dec_type D)\n           (f : A -> (set B * set C * set D)) (l : set A) : (set B * set C * set D) :=\n  triple_union_fold Beq_dec Ceq_dec Deq_dec f l ((empty_set _),(empty_set _),(empty_set _)).\nDefinition Subset {A} (s s' : set A) := forall x, In x s -> In x s'.\nDefinition Set_equiv {A} (s s' : set A) := Subset s s' /\\ Subset s' s.\n\nFixpoint dedup {A} (eq_dec : dec_type A) (s : set A) :=\n  match s with\n      nil => nil\n    | a::s' => if set_mem eq_dec a s' then\n                 dedup eq_dec s'\n               else\n                 a::(dedup eq_dec s')\n  end.\nFixpoint set_remove_all {A} (eq_dec : dec_type A) (a : A) (s : set A) :=\n  match s with\n      nil => nil\n    | a'::s' => if eq_dec a a' then\n                  set_remove_all eq_dec a s'\n                else\n                  a'::(set_remove_all eq_dec a s')\n  end.\n\nEnd Definitions.\n\nGlobal Program Instance subset_refl {A} : Reflexive (@Subset A).\nNext Obligation.\nintros y Hin; auto.\nQed.\nHint Immediate subset_refl.\n\nGlobal Program Instance subset_trans {A} : Transitive (@Subset A).\nNext Obligation. intros w Hin; apply H,H0 in Hin; assumption.\nQed.\n\nGlobal Program Instance set_equiv_equiv {A} : Equivalence (@Set_equiv A).\nNext Obligation.\nintro; split; reflexivity.\nQed.\nNext Obligation.\nintros ? ? [? ?]; split; auto.\nQed.\nNext Obligation.\nintros ? ? ? [H ?] [H1 ?]; split; intros ? ?;[apply H1,H|]; auto.\nQed.\n\nSection Facts.\nVariables (A : Type) (Aeq_dec : dec_type A).\n\nLemma set_add_elim_LEM : forall (s : set A) a b, set_In a (set_add Aeq_dec b s) ->\n                                                 (a = b /\\ ~ set_In a s) \\/ set_In a s.\nProof.\n  intros s a ? H; destruct (set_add_elim _ _ _ _ H);\n  [destruct (set_In_dec Aeq_dec a s)|]; auto.\nQed.\n\nTheorem set_union_elim_LEM : forall (s s' : set A) a, set_In a (set_union Aeq_dec s s') ->\n                                                      set_In a s \\/\n                                                      (set_In a s' /\\ ~ set_In a s).\nProof.\n  intros s ? a H; destruct (set_union_elim _ _ _ _ H);[|destruct (set_In_dec Aeq_dec a s)]; auto.\nQed.  \n\nLemma set_add_nodup : forall (s : set A) a, NoDup s -> NoDup (set_add Aeq_dec a s).\nProof.\n  induction s as [|a' s IH]; intros; simpl;\n  [constructor; [intro bad; inversion bad|constructor]\n  |destruct (Aeq_dec a a');\n    [|inversion H as [|? ? Hnin Hdup]; subst;\n      specialize (IH a Hdup);\n      constructor;\n      [intro Hin; apply set_add_elim2 in Hin;[apply Hnin in Hin|]\n      |]]]; auto.\nQed.\n\nLemma set_union_nodup : forall (s s' : set A), NoDup s -> NoDup (set_union Aeq_dec s s').\nProof.\n  induction s'; intro nds; [|apply set_add_nodup];auto.\nQed.\n\nTheorem set_remove_in : forall (s : set A) (a a' : A), set_In a (set_remove Aeq_dec a' s) -> set_In a s.\nProof.\n  induction s as [|a_ s IH]; intros a a' H;\n  [inversion H\n  |simpl in H;\n    destruct (Aeq_dec a' a_);\n    [right; auto\n    |inversion H; [subst; left|right; apply (IH a a')]; auto]].\nQed.\n\nTheorem set_remove_all_in : forall (s : set A) (a a' : A), set_In a (set_remove_all Aeq_dec a' s) -> set_In a s.\nProof.\n  induction s as [|a_ s IH]; intros a a' H;\n  [inversion H\n  |simpl in H;\n    destruct (Aeq_dec a' a_);\n    [subst; right; apply (IH a a_); auto\n    |inversion H; [subst; left|right; apply (IH a a')]]]; auto.\nQed.\n\nTheorem set_remove_all_neq : forall (s : set A) (a a' : A), set_In a (set_remove_all Aeq_dec a' s) -> a <> a'.\nProof.\n  induction s as [|a_ s IH]; intros a a' H;\n  [inversion H\n  |simpl in H;\n    destruct (Aeq_dec a' a_); [|inversion H];subst]; auto.\nQed.\n\nTheorem set_remove_all_neq_in : forall (s : set A) (a a' : A), set_In a s -> a <> a' -> set_In a (set_remove_all Aeq_dec a' s).\nProof.\n  induction s as [|a_ s IH]; intros a a' Hin Hneq;\n  [inversion Hin\n  |simpl;\n    destruct (Aeq_dec a' a_);\n    inversion Hin;\n    subst; [bad_eq|apply IH |left |right; apply IH]]; auto.\nQed.\n\nTheorem set_remove_all_notin : forall a (s : set A), ~ set_In a (set_remove_all Aeq_dec a s).\nProof.\n  induction s; [intros bad; inversion bad\n               |simpl; destruct (Aeq_dec a a0);\n                [subst|intro bad; inversion bad; [subst;bad_eq|]]; auto].\nQed.\n\nGlobal Program Instance set_union_respects : Proper (Set_equiv ==> Set_equiv ==> Set_equiv) (set_union Aeq_dec).\nNext Obligation.\nintros x y H0 z w H1; split; intros u Hin;\n(destruct (set_union_elim Aeq_dec _ _ _ Hin);\n[apply set_union_intro1, H0\n|apply set_union_intro2, H1]; auto).\nQed.\n\nGlobal Program Instance set_remove_all_respects : Proper ((@eq A) ==> Set_equiv ==> Set_equiv) (set_remove_all Aeq_dec).\nNext Obligation.\nintros ? ? Heq s s' [Sub Sub']; split; intros u Hin;\n(subst;\ncut (In u s');\n  [cut (u <> y);\n    [intros Hin' Hneq; apply set_remove_all_neq_in; try apply Sub'\n    |apply (set_remove_all_neq _ _ _ Hin)]\n  |apply set_remove_all_in in Hin; (apply Sub in Hin || apply Sub' in Hin)]; auto).\nQed.\n\nGlobal Program Instance set_add_respects : Proper ((@eq A) ==> Set_equiv ==> Set_equiv) (set_add Aeq_dec).\nNext Obligation.\n  intros ? ? Heq s s' [Sub Sub']; subst; split; intros u Hin;\n  (destruct (set_add_elim Aeq_dec _ _ _ Hin) as [|Hin'];\n    [subst; apply set_add_intro2; reflexivity\n    |(apply Sub in Hin' || apply Sub' in Hin'); apply set_add_intro1]; auto).\nQed.\n\nGlobal Program Instance set_diff_respects : Proper (Set_equiv ==> Set_equiv ==> Set_equiv) (set_diff Aeq_dec).\nNext Obligation.\nintros u v [Subv Subu] s s' [Subs Subs']; split; intros x Hin;\n(pose (need0 := set_diff_elim1 _ _ _ _ Hin);\npose (need1 := set_diff_elim2 _ _ _ _ Hin);\n(apply Subv in need0 || apply Subu in need0);\n((cut (~ In x s');[intro; apply set_diff_intro; auto|intro xs'; apply Subs' in xs'; contradiction])\n||(cut (~ In x s);[intro; apply set_diff_intro; auto|intro xs'; apply Subs in xs'; contradiction]))).\nQed.\n\nTheorem dedup_notin : forall (s : set A) a, ~ set_In a s -> ~ set_In a (dedup Aeq_dec s).\nProof.\n  induction s; intros a' Hnin bad; [inversion bad|simpl in bad;case_eq (set_mem Aeq_dec a s); intro res; rewrite res in bad;[apply IHs in bad; [|intro bad'; apply Hnin; right]; auto|]].\ninversion bad; [subst; apply Hnin; left; reflexivity|apply IHs in H; [|intro bad'; apply Hnin; right]]; auto.\nQed.\n\nTheorem dedup_in : forall (s : set A) a, set_In a (dedup Aeq_dec s) -> set_In a s.\nProof.\n  induction s; intros a' Hin; [inversion Hin|simpl in Hin].\n  case_eq (set_mem Aeq_dec a s); intro res; rewrite res in Hin.\n  apply IHs in Hin; right; auto.\n  inversion Hin; [subst; left|apply IHs in H; right]; auto.\nQed.\n\nTheorem in_dedup : forall (s : set A) a, set_In a s -> set_In a (dedup Aeq_dec s).\nProof.\n  induction s; intros a' Hin; [inversion Hin|simpl].\n  case_eq (set_mem Aeq_dec a s); intro res;\n  [apply set_mem_correct1 in res; apply IHs;\n   inversion Hin; subst; auto\n  |inversion Hin; subst; [left|right; apply IHs]; auto].\nQed.\n\nTheorem dedup_nodup : forall (s : set A), NoDup (dedup Aeq_dec s).\nProof.\n  induction s;[constructor|simpl; case_eq (set_mem Aeq_dec a s);intro res;[auto|apply set_mem_complete1 in res]].\n  apply dedup_notin in res; constructor; auto.\nQed.\n\nGlobal Program Instance dedup_respects : Proper (Set_equiv ==> Set_equiv) (dedup Aeq_dec).\nNext Obligation.\nintros s s' [Subs Subs']; split; intros ? ?; apply in_dedup; [apply Subs|apply Subs']; apply dedup_in; auto.\nQed.\n\nTheorem fold_left_nodup : forall B (f: set A -> B -> set A) (fprop : forall X b, NoDup X -> NoDup (f X b))\n                                 (s : set B) (b : set A),\n                            NoDup b -> NoDup (set_fold_left f s b).\nProof.\n  induction s; intros b ndb;[|apply IHs, fprop]; auto.\nQed.\n\nTheorem union_map_nodup : forall B (f : B -> set A) s, NoDup (union_map Aeq_dec f s).\nProof.\n  intros; apply fold_left_nodup;\n  [intros; apply set_union_nodup; auto\n  |constructor].\nQed.\n\n\nTheorem union_fold_base_subset : forall B (f: B -> set A) (s : set B) (base : set A),\n                                   Subset base (union_fold Aeq_dec f s base).\nProof.\n  induction s as [|b s IH]; intros base; simpl.\n  reflexivity.\n  transitivity (set_union Aeq_dec base (f b)); [intros ? ?; apply set_union_intro1; auto|apply IH].\nQed.\n\nTheorem fold_left_subset : forall B (f: B -> set A) (s : set B) (base : set A),\n                             Subset base (set_fold_left (fun acc b =>\n                                                           set_union Aeq_dec acc (f b))\n                                                        s base).\nProof.\n  induction s; intros b a' Hin.\n  auto.\n  simpl in *.\n  apply IHs.\n  apply set_union_intro1; auto.\nQed.\n\nTheorem union_subset1 : forall {B} (Beq_dec : dec_type B) (s s' s'' : set B), Subset (set_union Beq_dec s s') s'' ->\n                                                                              Subset s s''.\nProof.\n  intros; intros x Hin; apply (set_union_intro1 Beq_dec _ _ s'),H in Hin; auto.\nQed.\n\nTheorem union_subset2 : forall {B} (Beq_dec : dec_type B) (s s' s'' : set B), Subset (set_union Beq_dec s s') s'' ->\n                                                                              Subset s' s''.\nProof.\n  intros; intros x Hin; apply (set_union_intro2 Beq_dec _ _ s'),H in Hin; auto.\nQed.\n\nDefinition Triple_subset {A B C} (s s' : set A * set B * set C) : Prop :=\n  match s,s' with\n      (As,Bs,Cs),(As',Bs',Cs') => Subset As As' /\\ Subset Bs Bs' /\\ Subset Cs Cs'\n  end.\nTheorem triple_union_fold_base_subset : forall B C D (Beq_dec : dec_type B) (Ceq_dec : dec_type C)\n                                               (f: D -> set A * set B * set C) (s : set D)\n                                               (base : set A * set B * set C),\n                                          Triple_subset base (triple_union_fold Aeq_dec Beq_dec Ceq_dec f s base).\nProof.\n  induction s; intros [[Bas Bbs] Bcs].\n  hnf; repeat split; reflexivity.\n  simpl.\n  specialize (IHs (let (p, ds') := f a in\n          let (bs', cs') := p in\n          (set_union Aeq_dec Bas bs', set_union Beq_dec Bbs cs',\n          set_union Ceq_dec Bcs ds'))).\n  destruct (f a) as [[bs' cs'] ds'].\n  destruct (triple_union_fold Aeq_dec Beq_dec Ceq_dec f s\n         (set_union Aeq_dec Bas bs', set_union Beq_dec Bbs cs',\n         set_union Ceq_dec Bcs ds')) as [[As' Bs'] Cs'].\n  destruct IHs as [X [Y Z]]; repeat split; solve [eapply union_subset1; eauto| eapply union_subset2; eauto].\nQed.\n\nTheorem fold_left_subset_in : forall B (f: B -> set A) (s : set B) (base : set A) b,\n                             In b s -> Subset (f b) (set_fold_left (fun acc b =>\n                                                           set_union Aeq_dec acc (f b))\n                                                        s base).\n\nProof.\n  induction s; intros base b Hin a' Hin'.\n  inversion Hin.\n  simpl in *.\n  inversion Hin as [Heq|Hrest].\n  subst; apply union_fold_base_subset,set_union_intro2; auto.\n  apply (IHs (set_union Aeq_dec base (f a)) b Hrest); auto.\nQed.\n\nTheorem union_fold_subset_in : forall B (f: B -> set A) (s : set B) (base : set A) b,\n                                 In b s -> Subset (f b) (union_fold Aeq_dec f s base).\nProof.\n  intros; apply fold_left_subset_in; auto.\nQed.\n\n\nTheorem triple_union_fold_subset_in : forall B C D\n                                            (Beq_dec : dec_type B) (Ceq_dec : dec_type C)\n                                            (f: D -> set A * set B * set C) (s : set D)\n                                            (base : set A * set B * set C) d,\n                                       In d s ->\n                                       Triple_subset (f d) (triple_union_fold Aeq_dec Beq_dec Ceq_dec f s base).\nProof.\n  induction s; intros base d Hin; inversion Hin; [subst|apply IHs; auto].\n\n  case_eq (triple_union_fold Aeq_dec Beq_dec Ceq_dec f s\n         (let (p, ds) := base in\n          let (bs, cs) := p in\n          let (p0, ds') := f d in\n          let (bs', cs') := p0 in\n          (set_union Aeq_dec bs bs', set_union Beq_dec cs cs',\n          set_union Ceq_dec ds ds'))).\n    intros [As' Bs'] Cs' peq.\n    pose (L := triple_union_fold_base_subset).\n    specialize (L _ _ _ Beq_dec Ceq_dec f s (let (p, ds) := base in\n           let (bs, cs) := p in\n           let (p0, ds') := f d in\n           let (bs', cs') := p0 in\n           (set_union Aeq_dec bs bs', set_union Beq_dec cs cs',\n           set_union Ceq_dec ds ds'))).\n    rewrite peq in L.\n    simpl; rewrite peq.\n    destruct base as [[bs cs] ds].\n    destruct (f d) as [[a b] c].\n    destruct L as [Asub [Bsub Csub]]; repeat split; solve [eapply union_subset1; eauto | eapply union_subset2; eauto].\nQed.\n\nTheorem union_map_subset : forall B (f : B -> set A) s b, In b s -> Subset (f b) (union_map Aeq_dec f s).\nProof.\n  intros; apply union_fold_subset_in; auto.\nQed.\n\nTheorem triple_union_map_subset : forall B C D (Beq_dec : dec_type B) (Ceq_dec : dec_type C)\n                                          (f : D -> (set A * set B * set C)) (s : set D) d,\n                                    set_In d s ->\n                                    Triple_subset (f d) (triple_union_map Aeq_dec Beq_dec Ceq_dec f s).\nProof.\n  intros; apply triple_union_fold_subset_in; auto.\nQed.\n\nLemma in_set_ind : forall A (P : set A -> Prop),\n                     P nil ->\n                     forall s',\n                       (forall s a, P s /\\ In a s' /\\ Subset s s' -> P (a :: s)) ->\n                       P s'.\ninduction s'; intros; auto.\napply H0; split. apply IHs'; intros ? ? [? [? ?]]. apply H0; repeat split; [|right|intros x X; apply H3 in X;right]; auto.\n(* Todo *)\nsplit;[left|right];auto.\nQed.\n\nTheorem union_folded_property : forall B (f : B -> set A) (P : A -> Prop) s base\n                                       (fprop : forall b, set_In b s -> Forall P (f b)),\n                                  Forall P base ->\n                                  Forall P (union_fold Aeq_dec f s base).\nProof.\n  intros ? ? ? s;\n  apply (@in_set_ind _ (fun s =>\n                     forall base (fprop : forall b, set_In b s -> Forall P (f b)),\n                       Forall P base ->\n                       Forall P (union_fold Aeq_dec f s base))).\n  intros base fprop allbase; auto.\n  intros s' a [IH [ains Hsub]] base fprop allbase.\n  simpl; apply IH.\n  intros b Hin; apply fprop; right; auto.\n  rewrite Forall_forall; intros x Hin; apply set_union_elim in Hin.\n  destruct Hin as [inbase|inf].\n  rewrite Forall_forall in allbase; apply allbase; auto.\n  specialize (fprop a (or_introl (eq_refl _))); rewrite Forall_forall in fprop; apply fprop; auto.\nQed.\n\n(*\nInductive Forall3 {D B C} (P : D -> B -> C -> Prop) : list D -> list B -> list C -> Prop :=\n  nil_forall3 : Forall3 P nil nil nil\n| cons_forall3 : forall d b c Ds Bs Cs, Forall3 P Ds Bs Cs -> P d b c -> Forall3 P (d::Ds) (b::Bs) (c::Cs).\n\nFixpoint In3 {D B C} (d : D) (b : B) (c : C) (Ds : list D) (Bs : list B) (Cs : list C) : Prop :=\n  length Ds = length Bs /\\ length Bs = length Cs /\\\n  match Ds,Bs,Cs with\n      d'::Ds,b'::Bs,c'::Cs => (d = d' /\\ b' = b /\\ c' = c) \\/ (In3 d b c Ds Bs Cs)\n    | nil,nil,nil => False\n    | _,_,_ => True (* bad lists just make this meaningless *)\n  end.\nFixpoint list3 {D B C} (Ds : list D) (Bs : list B) (Cs : list C) : Prop :=\n  match Ds,Bs,Cs with\n      d'::Ds,b'::Bs,c'::Cs => (list3 Ds Bs Cs)\n    | _,_,_ => True\n  end.\nFunctional Scheme in3_ind := Induction for list3 Sort Prop.\n\nTheorem Forall3_forall : forall D B C (P : D -> B -> C -> Prop) (Ds : list D) (Bs : list B) (Cs : list C),\n                           (Forall3 P Ds Bs Cs) <-> (length Ds = length Bs /\\ length Bs = length Cs /\\ forall d b c, In3 d b c Ds Bs Cs -> P d b c).\nProof.\n  intros; split.\n  intro H; induction H; repeat split.\n  intros d b c Hin; inversion Hin.\n  intuition.\n  destruct IHForall3 as [len0 [len1 IH]]; simpl; auto.\n  destruct IHForall3 as [len0 [len1 IH]]; simpl; auto.\n  intros d' b' c' Hin.\n  inversion Hin as [len0 [len1 [[dd [bb cc]]|Hrest]]].\n  subst; auto.\n  apply IHForall3; auto.\n  apply (@in3_ind _ _ _ (fun Ds Bs Cs prp => prp -> length Ds = length Bs /\\ length Bs = length Cs /\\ (forall d b c, In3 d b c Ds Bs Cs -> P d b c) -> Forall3 P Ds Bs Cs)); intros; try solve [auto |contradiction|intuition; simpl in *; discriminate].\n  subst; intuition; simpl in *;\n  cut (Bs0 = []); [|destruct Bs0; [auto|discriminate]];\n  intro;\n  cut (Cs0 = []); [|destruct Cs0; [auto|subst; simpl in *; discriminate]];\n  intros; subst; constructor.\n\n  subst.\n  destruct H1 as [? [? ?]].\n  simpl in *.\n  injects H2; injects H1.\n  remember H3 as IH; clear HeqIH.\n  specialize (H3 _x _x0 _x1 (conj H1 (conj H2 (or_introl (conj (eq_refl _x) (conj (eq_refl _x0) (eq_refl _x1))))))).\n  constructor; auto.\n  apply H; auto.\n  repeat split; auto.\n  revert Bs Cs.\n  induction Ds; simpl; [auto|];\n  induction Bs; simpl; [auto|];\n  induction Cs; simpl; [auto|];\n  apply IHDs.\nQed.\n*)\nTheorem triple_union_folded_property : forall B C D (Beq_dec : dec_type B) (Ceq_dec : dec_type C)\n                                              (f : D -> set A * set B * set C)\n                                              (PA : A -> Prop) (PB : B -> Prop) (PC : C -> Prop) s\n                                              (base : set A * set B * set C)\n                                              (fprop : forall d, set_In d s -> match (f d) with (As,Bs,Cs) => Forall PA As /\\ Forall PB Bs /\\ Forall PC Cs end),\n                                         match base with (As,Bs,Cs) => Forall PA As /\\ Forall PB Bs /\\ Forall PC Cs end  ->\n                                         (match (triple_union_fold Aeq_dec Beq_dec Ceq_dec f s base) with\n                                              (As,Bs,Cs) => Forall PA As /\\ Forall PB Bs /\\ Forall PC Cs end).\n  intros ? ? ? ? ? ? ? ? ? s;\n  apply (@in_set_ind _ (fun s => forall (base : set A * set B * set C)\n                                              (fprop : forall d, set_In d s -> match (f d) with (As,Bs,Cs) => Forall PA As /\\ Forall PB Bs /\\ Forall PC Cs end),\n                                         match base with (As,Bs,Cs) => Forall PA As /\\ Forall PB Bs /\\ Forall PC Cs end  ->\n                                         (match (triple_union_fold Aeq_dec Beq_dec Ceq_dec f s base) with\n                                              (As,Bs,Cs) => Forall PA As /\\ Forall PB Bs /\\ Forall PC Cs end))).\n  auto.\n  intros s' a IH base fprop allbase.\n  simpl; apply IH.\n  intros d Hin; apply fprop; right; auto.\n  destruct base as [[ds bs] cs].\n  case_eq (f a); intros [bs' cs'] ds' Heq.\n  repeat rewrite Forall_forall; repeat split; intros x Hin;\n  specialize (fprop a (or_introl (eq_refl _)));\n  rewrite Heq in fprop;\n  repeat rewrite Forall_forall in *;\n  apply set_union_elim in Hin; destruct Hin as [inbase|inf];\n  try solve [apply allbase; auto|apply fprop;auto].\nQed.\n\n  \nTheorem length_add : forall s a, ~ set_In a s -> length (set_add Aeq_dec a s) = S (length s).\nProof.\n  induction s as [|a s IH]; intros a' H;\n  [|simpl;\n     destruct (Aeq_dec a' a);\n     [subst; elimtype False; apply H; left\n     |simpl; f_equal; apply IH; intro bad; apply H; right]]; auto.\nQed.\n\nEnd Facts.", "meta": {"author": "deeglaze", "repo": "concrete-summaries", "sha": "2be8622f2c79734f6c0060013b56807ab83992fe", "save_path": "github-repos/coq/deeglaze-concrete-summaries", "path": "github-repos/coq/deeglaze-concrete-summaries/concrete-summaries-2be8622f2c79734f6c0060013b56807ab83992fe/ListSetFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.6756090193159824}}
{"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\nPrint reflect.\n\nNotation  \"a >=? b\" := (Nat.leb b a)\n                          (at level 70) : nat_scope.\nNotation  \"a >? b\"  := (Nat.ltb b a)\n                         (at level 70) : nat_scope.\n\n\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\n\n\nExample reflect_example1: forall a,\n    (if a <? 5 then a else 2) < 6.\nProof.\n  intros a.\n  (* The next two lines aren't strictly necessary, but they\n     help make it clear what destruct does. *)\n  assert (R: reflect (a < 5) (a <? 5)) by apply ltb_reflect.\n  remember (a <? 5) as guard.\n  destruct R as [H|H] eqn:HR.\n  * (* ReflectT *) lia.\n  * (* ReflectF *) lia.\nQed.\n\n\nHint Resolve ltb_reflect leb_reflect eqb_reflect : bdestruct.\n\nLtac bdestruct X :=\n  let H := fresh in let e := fresh \"e\" in\n   evar (e: Prop);\n   assert (H: reflect e X); subst e;\n    [eauto with bdestruct\n    | destruct H as [H|H];\n       [ | try first [apply not_lt in H | apply not_le in H]]].\n\nExample reflect_example2: forall a,\n    (if a <? 5 then a else 2) < 6.\nProof.\n  intros.\n  bdestruct (a <? 5); (* instead of: destruct (ltb_reflect a 5). *)\n  lia.\nQed.\n\n\nDefinition maybe_swap (al: list nat) : list nat :=\n  match al with\n  | a :: b :: ar => if a >? b then b :: a :: ar else a :: b :: ar\n  | _            => al\n  end.\n\nTheorem maybe_swap_idempotent: forall al,\n    maybe_swap (maybe_swap al) = maybe_swap al.\nProof.\n  intros [ | a [ | b al]]; simpl; try reflexivity.\n  bdestruct (a >? b); simpl.\n  - bdestruct (b >? a); simpl.\n    + lia.\n    + reflexivity.\n  - bdestruct (a >? b); simpl.\n    + lia.\n    + reflexivity.\nQed.\n\n\n\nPrint Permutation.\nSearch Permutation.\n\nExample butterfly: forall b u t e r f l y : nat,\n  Permutation ([b;u;t;t;e;r]++[f;l;y]) ([f;l;u;t;t;e;r]++[b;y]).\nProof.\n  intros.\n  change [b;u;t;t;e;r] with ([b]++[u;t;t;e;r]).\n  change [f;l;u;t;t;e;r] with ([f;l]++[u;t;t;e;r]).\n  remember [u;t;t;e;r] as utter. clear Hequtter.\n  change [f;l;y] with ([f;l]++[y]).\n  remember [f;l] as fl. clear Heqfl.\n  replace ((fl ++ utter) ++ [b;y]) with (fl ++ utter ++ [b;y])\n    by apply app_assoc.\n  apply perm_trans with (fl ++ [y] ++ ([b] ++ utter)).\n  - replace (fl ++ [y] ++ [b] ++ utter) with ((fl ++ [y]) ++ [b] ++ utter).\n    + apply Permutation_app_comm.\n    + rewrite <- app_assoc. reflexivity.\n  -\n    apply Permutation_app_head.\n    apply perm_trans with (utter ++ [y] ++ [b]).\n    + replace ([y] ++ [b] ++ utter) with (([y] ++ [b]) ++ utter).\n      * apply Permutation_app_comm.\n      * rewrite app_assoc. reflexivity.\n    + apply Permutation_app_head.\n      apply perm_swap.\nQed.\n\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.\nExample permut_example: forall (a b: list nat),\n  Permutation (5 :: 6 :: a ++ b) ((5 :: b) ++ (6 :: a ++ [])).\nProof.\n  intros.\n  rewrite app_nil_r.\n  rewrite <- app_comm_cons.\n  apply perm_skip.\n  rewrite app_comm_cons.\n  apply Permutation_app_comm.\nQed.\n\n\nCheck Permutation_cons_inv.\nCheck Permutation_length_1_inv.\nExample not_a_permutation:\n  ~ Permutation [1;1] [1;2].\nProof.\n  unfold not. intros.\n  apply Permutation_cons_inv in H.\n  apply Permutation_length_1_inv in H.\n  discriminate H.\nQed.\n\n\nTheorem maybe_swap_perm: forall al,\n  Permutation al (maybe_swap al).\nProof.\n  unfold maybe_swap.\n  destruct al as [ | a [ | b al]].\n  - simpl. apply perm_nil.\n  - apply Permutation_refl.\n  - bdestruct (b <? a).\n    + apply perm_swap.\n    + apply Permutation_refl.\nQed.\n\nDefinition first_le_second (al: list nat) : Prop :=\n  match al with\n  | a :: b :: _ => a <= b\n  | _           => True\n  end.\n\nTheorem maybe_swap_correct: forall al,\n    Permutation al (maybe_swap al) /\\ first_le_second (maybe_swap al).\nProof.\n  intros. split.\n  - apply maybe_swap_perm.\n  - unfold maybe_swap.\n    destruct al as [ | a [ | b al]]; simpl; auto.\n    bdestruct (a >? b); simpl; lia.\nQed.\n\n\nLtac inv H := inversion H; clear H; subst.\n\nPrint Forall.\n\nTheorem Forall_perm: forall {A} (f: A -> Prop) al bl,\n  Permutation al bl ->\n  Forall f al -> Forall f bl.\nProof.\n  intros.\n  induction H.\n  - assumption.\n  - inv H0.\n    apply Forall_cons.\n    + assumption.\n    + apply (IHPermutation H4).\n  - inv H0. inv H3.\n    apply Forall_cons.\n    assumption.\n    apply Forall_cons.\n    assumption.\n    assumption.\n  - apply IHPermutation2.\n    apply IHPermutation1.\n    assumption.\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/Perm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.6756090128841851}}
{"text": "(* The El Gamal encryption scheme and a proof that it is IND-CPA-secure. *)\n\nSet Implicit Arguments.\n\nRequire Import FCF.\nRequire Import RndGrpElem.\nRequire Import Encryption_PK.\nRequire Import DiffieHellman.\nRequire Import OTP.\n\nLocal Open Scope group_scope.\n\nSection ElGamal.\n\n  Context`{FCG : FiniteCyclicGroup}.\n\n  Hypothesis GroupElement_EqDec : EqDec GroupElement.\n\n  Definition ElGamalKeygen :=\n    m <-$ [0 .. order);\n    ret (m, g^m).\n\n  Definition ElGamalEncrypt(msg key : GroupElement) := \n    m <-$ [0 .. order);\n    ret (g^m, key^m * msg).\n\n  Variable A_State : Set.\n  Hypothesis A_State_EqDec : EqDec A_State.\n\n  Variable A1 : GroupElement -> Comp (GroupElement * GroupElement * A_State).\n  Hypothesis wfA1 : forall x, well_formed_comp (A1 x).\n\n  Variable A2 : (GroupElement * GroupElement * A_State) -> Comp bool.\n  Hypothesis wfA2 : forall x, well_formed_comp (A2 x).  \n\n  (* Build an adversary from A1 and A2 that can win DDH *)\n  Definition B(g_xyz : (GroupElement * GroupElement * GroupElement)) : Comp bool :=\n    [gx, gy, gz] <-3 g_xyz;\n    [p0, p1, s] <-$3 A1(gx);\n    b <-$ {0,1};\n    pb <- if b then p0 else p1;\n      c <- (gy, gz * pb);\n      b' <-$ (A2 (c, s));\n      ret (eqb b b').\n\n  Theorem ElGamal_IND_CPA0 :\n    Pr[IND_CPA_G ElGamalKeygen ElGamalEncrypt A1 A2] == \n    Pr[(@DDH0 _ _ _ _ _ g order B)].\n    \n    unfold IND_CPA_G, DDH0, ElGamalKeygen, ElGamalEncrypt, B.\n\n    inline_first.\n    comp_skip.\n\n    dist_at dist_inline rightc 1%nat.\n    comp_swap rightc.\n    comp_skip.\n\n    destruct x0.\n    destruct p.\n\n    dist_at dist_inline rightc 1%nat.\n    comp_swap rightc.\n    comp_skip.\n\n    comp_inline leftc.\n    comp_skip.\n\n    comp_inline rightc.\n    comp_skip.\n    rewrite groupExp_mult; intuition.\n\n    comp_simp.\n    intuition.\n  Qed.\n\n  Definition G1 :=\n    gx <-$ RndG;\n    gy <-$ RndG;\n    [p0, p1, s] <-$3 (A1 gx);\n    b <-$ {0, 1};\n    gz' <-$ (\n    pb <- if b then p0 else p1;\n    gz <-$ RndG ; ret (gz * pb));\n    b' <-$ (A2 (gy, gz', s));\n    ret (eqb b b').\n\n  Definition G2 :=\n    gx <-$ RndG;\n    gy <-$ RndG;\n    [p0, p1, s] <-$3 (A1 gx);\n    gz <-$ RndG ;\n    b' <-$ (A2 (gy, gz, s));\n    b <-$ {0, 1};\n    ret (eqb b b').\n\n  Theorem ElGamal_G1_DDH1 :\n    Pr [ G1] == Pr [ (@DDH1 _ _ _ _ _ g order B) ].\n\n    unfold G1, DDH1, B, RndGrpElem.\n\n    inline_first.\n    comp_skip.\n    inline_first.\n    comp_skip.\n\n    comp_at comp_inline rightc 1%nat.\n    comp_swap rightc.\n    comp_skip.\n\n    destruct x1.\n    destruct p.\n\n    dist_at dist_inline leftc 1%nat.\n    dist_at dist_inline leftc 1%nat.\n    comp_swap leftc.\n    comp_skip.\n    \n    comp_inline rightc.\n    comp_skip.\n    \n    inline_first.\n    comp_skip.\n\n    comp_simp.\n    intuition.\n    \n  Qed.   \n\n  Theorem ElGamal_G1_G2 :\n    Pr[G1] == Pr[G2].\n    \n    unfold G1, G2, B.\n\n    (* we do this step in the program logic *)\n    eapply comp_spec_eq_impl_eq.\n\n    do 3 comp_skip.\n\n    prog_at_r prog_swap 1%nat.\n    prog_swap_r.\n    comp_skip.\n\n    eapply comp_spec_symm.\n    eapply comp_spec_seq; eauto with inhabited.\n    eapply group_OTP_r.\n    intuition.\n    subst.\n    eapply comp_spec_consequence.\n    eapply comp_spec_eq_refl.\n    intuition.\n  Qed.\n\n  Theorem ElGamal_G2_OneHalf :\n    Pr [G2] == 1 / 2.\n   \n    unfold G2.\n\n    (* ignore the first 5 commands *)\n    do 3 dist_irr_l.\n    comp_simp.\n    do 2 dist_irr_l.\n    (* compute the probability *)\n    dist_compute.\n  Qed.\n  \n  Theorem ElGamal_IND_CPA_Advantage :\n    (IND_CPA_Advantage ElGamalKeygen ElGamalEncrypt A1 A2) ==\n    (@DDH_Advantage _ _ _ _ _ g order B).\n\n    unfold IND_CPA_Advantage, DDH_Advantage.\n    eapply ratDistance_eqRat_compat.    \n    eapply ElGamal_IND_CPA0.\n    rewrite <- ElGamal_G1_DDH1.\n    rewrite ElGamal_G1_G2.\n    symmetry.\n    eapply ElGamal_G2_OneHalf.\n  Qed.\n\nEnd ElGamal.", "meta": {"author": "FreeAndFair", "repo": "RLA", "sha": "4295e4bb700ebbfe69affeb35dda7ed42273c3a1", "save_path": "github-repos/coq/FreeAndFair-RLA", "path": "github-repos/coq/FreeAndFair-RLA/RLA-4295e4bb700ebbfe69affeb35dda7ed42273c3a1/src/fcf/ElGamal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6754899844061261}}
{"text": "Require Export ConnectivityGraph.\nRequire Export Layouts.\nRequire Export MappingConstraints.\nRequire Import StandardGateSet.\nImport StdList.\n\n(* Alogrithm 3.1 *)\n\nFixpoint hierarchical_product_permuter_part1 pi permuter_g1g2 (deg_ham : nat) :=  (* line 2 *)\n  match deg_ham with\n  | 0 => pi\n  | n =>\n      let r = partial_permutation permuter_g1g2  (* line 1*)\n          g' = route_v_to_k r permuter_g1g2  (* line 3,4 *)\n          new_g = route_communicator_v_g1 g'  (* line 5,6 *)\n      in\n      hierarchical_product_permuter_part1 pi new_g (n-1)\n  end.\n\n\nFixpoint hierarchical_product_permuter_part2 v1 pi permuter_g1g2 :=  (* line 7 *)\n  match v1 with\n  | [] => pi\n  | (h :: t) =>\n      let\n        new_pi = route_v_Vi_to_pi h pi permuter_g1g2  (*line 8 *)\n      in\n      hierarchical_product_permuter_part2 t new_pi permuter_g1g2\n  end,\n\n\nDefinition hierarchical_product_permuter pi permuter_g1g2 deg_ham := (* Algorithm 3.1 *)\nlet\n  new_pi = hierarchical_product_permuter_part1 pi permuter_g1g2 deg_ham\n  v1 = V(new_pi,1)\nin\nhierarchical_product_permuter_part2 v1 new_pi permuter_g1g2\n\n(* Algorithm 3.2 *)\n\nFixpoint choose_distinct_sets pi sigma r rowi_V2 :=\nmatch rowi_V2 with\n| [] => sigma\n| i :: tail => let v = (dom pi) - (dom sigma)\n                   E = (head v, pi_v (v,1), current_v (v, i)) (* line 4 *)\n                   U, V = list_n (num_of (V1 pi)) (* ni = |Vi| *) (* line 6 *)\n                   G = (U, V, E) (* line 6 *)\n                   V_match = v_set (find_minimum_weight G (add_u_v_e G r)) (* line 7~11 *)\n                   new_sigma =  app sigma (v_list V_match) (* line 12 *)\n               in\n                   choose_distinct_sets pi new_sigma (r-1) t\n\n\n(* Algorithm 3.3 *)\n\nFixpoint routing_tokens_to_destination pi :=\nif (pi == id_dom pi)\nthen (*return seq of transpositions *)\nelse\n  if exists_happy_swap\n  then routing_tokens_to_destination (do_transposition pi)\n  else\n    if (exists_v (dom pi)) and (exists_u (Nu_dom_pi v))\n    then routing_tokens_to_destination (no_token_swap v u)\n    else routing_tokens_to_destination (unhappy_swap)\n", "meta": {"author": "lec9243", "repo": "Qmapping", "sha": "1df50ea422b2a597664a4a7154c7404d27f9eb5d", "save_path": "github-repos/coq/lec9243-Qmapping", "path": "github-repos/coq/lec9243-Qmapping/Qmapping-1df50ea422b2a597664a4a7154c7404d27f9eb5d/useless_KeepAsRef/Routing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.6753920085766268}}
{"text": "Require Export Utilities.\nRequire Export SQIR.UnitaryOps.\n\nLocal Open Scope ucom.\n\n(****************************)\n(**   Program Definition   **)\n(****************************)\n\n(** Quantum Phase Estimation (QPE) program definition **)\n\n(* Controlled rotation cascade on n qubits. *)\nFixpoint controlled_rotations n : base_ucom n :=\n  match n with\n  | 0 | 1 => SKIP\n  | 2     => control 1 (Rz (2 * PI / 2 ^ n) 0) (* makes 0,1 cases irrelevant *)\n  | S n'  => cast (controlled_rotations n') n ;\n            control n' (Rz (2 * PI / 2 ^ n) 0)\n  end.\n\n(* Quantum Fourier transform on n qubits. \n   We use the definition below (with cast and map_qubits) for proof convenience.\n   For a more standard functional definition of QFT see Quipper:\n   https://www.mathstat.dal.ca/~selinger/quipper/doc/src/Quipper/Libraries/QFT.html *)\nFixpoint QFT n : base_ucom n :=\n  match n with\n  | 0    => SKIP\n  | 1    => H 0\n  | S n' => H 0 ; controlled_rotations n ;\n           cast (map_qubits S (QFT n')) n \n  end.\n\n(* The QFT puts the qubits in the wrong order, so you typically want to reverse\n   them at the end. *)\nFixpoint reverse_qubits' dim n : base_ucom dim :=\n  match n with\n  | 0    => SKIP\n  | 1    => SWAP 0 (dim - 1) (* makes 0 case irrelevant *)\n  | S n' => reverse_qubits' dim n' ; SWAP n' (dim - n' - 1)\n  end.\nDefinition reverse_qubits n := reverse_qubits' n (n/2)%nat.\nDefinition QFT_w_reverse n := QFT n ; reverse_qubits n.\n\nFixpoint controlled_powers' {n} (c : base_ucom n) k kmax : base_ucom (kmax + n) :=\n  match k with\n  | 0    => SKIP\n  | 1    => cast (control (kmax - 1) c) (kmax + n) (* makes 0 case irrelevant *)\n  | S k' => controlled_powers' c k' kmax ;\n           cast (niter (2 ^ k') (control (kmax - k' - 1) c)) (kmax + n)\n  end.\nDefinition controlled_powers {n} (c : base_ucom n) k := controlled_powers' c k k.\n\n(* k = number of digits in result\n   n = number of qubits in input state *)\nDefinition QPE k n (c : base_ucom n) : base_ucom (k + n) :=\n  cast (npar k U_H) (k + n) ;\n  controlled_powers (map_qubits (fun q => k + q)%nat c) k; \n  cast (invert (QFT_w_reverse k)) (k + n).\n\nFixpoint controlled_powers_var' {n} (f : nat -> base_ucom n) k kmax : base_ucom (kmax + n) :=\n  match k with\n  | 0    => SKIP\n  | 1    => cast (control (kmax - 1) (f O)) (kmax + n) (* makes 0 case irrelevant *)\n  | S k' => controlled_powers_var' f k' kmax ;\n           cast (control (kmax - k' - 1) (f k')) (kmax + n)\n  end.\nDefinition controlled_powers_var {n} (f : nat -> base_ucom n) k := controlled_powers_var' f k k.\n\nDefinition QPE_var k n (f : nat -> base_ucom n) : base_ucom (k + n) :=\n  cast (npar k U_H) (k + n) ;\n  controlled_powers_var (fun x => map_qubits (fun q => k + q)%nat (f x)) k; \n  cast (invert (QFT_w_reverse k)) (k + n).\n\n(****************************)\n(**         Proofs         **)\n(****************************)\n\n\n(** Well-typedness of QFT (used in proof of QPE) **)\n\nLocal Opaque control.\nLocal Transparent Rz.\nLemma controlled_rotations_WT : forall n,\n  (n > 1)%nat -> uc_well_typed (controlled_rotations n).\nProof.\n  intros n Hn.\n  destruct n; try lia.\n  destruct n; try lia.\n  induction n.\n  simpl. \n  apply uc_well_typed_control; repeat split; try lia.\n  1,2: constructor; auto.\n  replace (controlled_rotations (S (S (S n)))) with (cast (controlled_rotations (S (S n))) (S (S (S n))) ; control (S (S n)) (Rz (2 * PI / 2 ^ (S (S (S n)))) 0)) by reflexivity.\n  constructor.\n  apply typed_cast; try lia.\n  apply IHn; try lia.\n  apply uc_well_typed_control; repeat split; try lia.\n  1,2: constructor; lia.\nQed.\nLocal Opaque Rz.\nLocal Transparent control.\n\nLemma QFT_WT : forall n, (n > 0)%nat -> uc_well_typed (QFT n).\nProof.\n  intros n Hn.\n  destruct n; try lia.\n  induction n.\n  simpl. apply uc_well_typed_H; lia.\n  replace (QFT (S (S n))) with (H 0 ; controlled_rotations (S (S n)) ; cast (map_qubits S (QFT (S n))) (S (S n))) by reflexivity.\n  repeat constructor.\n  apply uc_well_typed_H; lia.\n  apply controlled_rotations_WT; lia.\n  replace S with (fun i => 1 + i)%nat by reflexivity.\n  apply uc_well_typed_map_qubits.\n  simpl. apply IHn. lia.\nQed.\n\nLemma reverse_qubits_WT : forall n, (n > 0)%nat -> uc_well_typed (reverse_qubits n).\nProof.\n  assert (H: forall n dim, (n > 0)%nat -> (2 * n <= dim)%nat -> uc_well_typed (reverse_qubits' dim n)).\n  { intros n dim Hn Hdim.\n    destruct n; try lia.\n    induction n.\n    apply uc_well_typed_SWAP; lia.\n    replace (reverse_qubits' dim (S (S n))) with (reverse_qubits' dim (S n) ; SWAP (S n) (dim - (S n) - 1)) by reflexivity.\n    constructor.\n    apply IHn; lia.\n    apply uc_well_typed_SWAP; lia. }\n  intros n Hn.\n  bdestruct (n =? 1); subst.\n  unfold reverse_qubits; simpl.\n  apply uc_well_typed_ID; lia. \n  apply H.\n  apply Nat.div_str_pos. lia.\n  apply Nat.mul_div_le. lia.\nQed.\n\nLemma QFT_w_reverse_WT : forall n, (n > 0)%nat -> uc_well_typed (QFT_w_reverse n).\nProof. intros. constructor. apply QFT_WT; auto. apply reverse_qubits_WT; auto. Qed.\n\n(** Proof of QFT semantics **)\n\nDefinition b2R (b : bool) : R := if b then 1%R else 0%R.\nLocal Coercion b2R : bool >-> R.\nLemma f_to_vec_controlled_Rz : forall (n i j : nat) (θ : R) (f : nat -> bool),\n  (i < n)%nat -> (j < n)%nat -> (i <> j)%nat ->\n  uc_eval (control i (Rz θ j)) × (f_to_vec n f) \n      = (Cexp (f i * f j * θ)) .* f_to_vec n f.\nProof.\n  intros. \n  rewrite control_correct; auto.\n  rewrite Mmult_plus_distr_r.\n  rewrite Mmult_assoc.\n  rewrite f_to_vec_Rz by auto.\n  rewrite Mscale_mult_dist_r.\n  destruct (f i) eqn:fi.\n  rewrite (f_to_vec_proj_eq _ _ _ true) by auto.\n  rewrite (f_to_vec_proj_neq _ _ _ false); auto.\n  2: rewrite fi; easy.\n  Msimpl_light.\n  rewrite Rmult_1_l.\n  reflexivity.\n  rewrite (f_to_vec_proj_eq _ _ _ false) by auto.\n  rewrite (f_to_vec_proj_neq _ _ _ true); auto.\n  2: rewrite fi; easy.\n  simpl.\n  autorewrite with R_db Cexp_db.\n  Msimpl_light.\n  reflexivity. \n  Local Transparent Rz.\n  1,2: constructor; auto.\n  Local Opaque Rz.\nQed.\n\nLemma controlled_rotations_action_on_basis : forall n f,\n  (n > 1)%nat ->\n  (uc_eval (controlled_rotations n)) × (f_to_vec n f) = \n    Cexp (2 * PI * (f O) * INR (funbool_to_nat (n-1) (shift f 1%nat)) / (2 ^ n)) .* \n      (f_to_vec n f).\nProof.\n  intros n f Hn.\n  destruct n; try lia.\n  destruct n; try lia.\n  induction n.\n  - simpl uc_eval. \n    rewrite f_to_vec_controlled_Rz by lia.\n    apply f_equal2; try reflexivity.\n    unfold funbool_to_nat, shift; simpl.\n    destruct (f (S O)); destruct (f O); simpl;\n    autorewrite with R_db; reflexivity. \n  - (* easier way to do the following? \"simpl\" produces a gross expression;\n       also, too much manual rewriting below *)\n    replace (uc_eval (controlled_rotations (S (S (S n))))) with (uc_eval (control (S (S n)) (Rz (2 * PI / 2 ^ (S (S (S n)))) 0)) × uc_eval (cast (controlled_rotations (S (S n))) (S (S (S n))))) by reflexivity.\n    replace (f_to_vec (S (S (S n))) f) with (f_to_vec (S (S n)) f ⊗ ∣ Nat.b2n (f (S (S n))) ⟩) by reflexivity.\n    replace (S (S (S n))) with (S (S n) + 1)%nat by lia.\n    rewrite <- pad_dims_r.\n    simpl I.\n    rewrite Mmult_assoc.\n    replace (2 ^ ((S (S n)) + 1))%nat with (2 ^ (S (S n)) * (2 ^ 1))%nat by unify_pows_two.\n    restore_dims. \n    rewrite kron_mixed_product.\n    rewrite IHn by lia.\n    Msimpl.\n    rewrite Mscale_kron_dist_l.\n    replace (f_to_vec (S (S n)) f ⊗ ∣ Nat.b2n (f (S (S n))) ⟩) with (f_to_vec (S (S (S n))) f) by reflexivity.\n    replace (2 ^ ((S (S n)) + 1))%nat with (2 ^ (S (S n)) * (2 ^ 1))%nat by unify_pows_two.\n    rewrite Mscale_mult_dist_r.\n    replace (1 * 1)%nat with 1%nat by reflexivity.\n    replace (2 ^ (S (S n)) * (2 ^ 1))%nat with (2 ^ ((S (S n)) + 1))%nat by unify_pows_two.\n    replace (2 ^ (S (S n)) * 2)%nat with (2 ^ ((S (S n)) + 1))%nat by unify_pows_two.\n    replace (S (S (S n))) with (S (S n) + 1)%nat by lia.\n    rewrite f_to_vec_controlled_Rz by lia.\n    rewrite Mscale_assoc.\n    apply f_equal2; try reflexivity.\n    rewrite <- Cexp_add.\n    replace (f (S (S n)) * f O * (2 * PI / 2 ^ (S (S n) + 1)))%R with (2 * PI * f O * f (S (S n)) * / 2 ^ (S (S n) + 1))%R by lra.\n    autorewrite with R_db.\n    repeat rewrite Rmult_assoc.\n    repeat rewrite <- Rmult_plus_distr_l.\n    repeat rewrite <- Rmult_assoc.\n    simpl.\n    replace (INR (funbool_to_nat (S n) (shift f 1)) * / (2 * (2 * 2 ^ n)) + f (S (S n)) * / (2 * (2 * 2 ^ (n + 1))))%R with (INR (funbool_to_nat (S (n + 1)) (shift f 1)) * / (2 * (2 * 2 ^ (n + 1))))%R.\n    repeat rewrite Rmult_assoc.\n    reflexivity. \n    replace (n + 1)%nat with (S n) by lia.\n    unfold funbool_to_nat. \n    simpl binlist_to_nat.\n    repeat rewrite plus_INR.\n    unfold shift; simpl.\n    field_simplify_eq; try nonzero. \n    replace (S (n + 1)) with (S (S n)) by lia.\n    destruct (f (S (S n))); simpl; lra.\n    apply controlled_rotations_WT; lia.\nQed.\n\nLemma QFT_semantics : forall n f,\n  (n > 0)%nat -> \n  uc_eval (QFT n) × (f_to_vec n f) =\n    / √(2 ^ n) .* vkron n (fun i => ∣0⟩ .+ Cexp (2 * PI * INR (funbool_to_nat (n - i) (shift f i)) / 2 ^ (n - i)) .* ∣1⟩).\nProof.\n  intros n f Hn.\n  generalize dependent f.\n  destruct n; try lia.\n  induction n; intro f.\n  - simpl QFT.\n    rewrite f_to_vec_H by lia.\n    simpl; Msimpl.\n    unfold funbool_to_nat, shift; simpl. \n    destruct (f O); simpl; autorewrite with R_db; try reflexivity.\n    replace (2 * PI * / 2)%R with PI by lra.\n    reflexivity.\n  - replace (QFT (S (S n))) with (H 0 ; controlled_rotations (S (S n)) ; cast (map_qubits S (QFT (S n))) (S (S n))) by reflexivity. \n    Local Opaque QFT controlled_rotations Nat.pow funbool_to_nat.\n    simpl uc_eval.\n    repeat rewrite Mmult_assoc.\n    rewrite f_to_vec_H by lia. \n    distribute_scale. distribute_plus. distribute_scale.\n    rewrite 2 controlled_rotations_action_on_basis by lia.\n    rewrite 2 update_index_eq. \n    rewrite 2 Mscale_mult_dist_r.\n    specialize (pad_dims_l (QFT (S n)) (S O)) as H.\n    simpl in H. \n    replace (fun q : nat => S q) with S in H by reflexivity.\n    rewrite <- H; clear H. \n    rewrite 2 (f_to_vec_split 0 (S (S n)) 0) by lia.\n    remember (S n) as n'.\n    simpl f_to_vec.\n    replace (0 + 0)%nat with O by reflexivity.\n    rewrite 2 update_index_eq.\n    Msimpl_light.\n    replace (n' - 0 - 0)%nat with n' by lia.\n    repeat rewrite kron_mixed_product.\n    Msimpl_light.\n    rewrite 2 f_to_vec_shift_update_oob by lia.\n    assert (H: (n' > 0)%nat) by lia.\n    specialize (IHn H (shift f 1)).\n    rewrite IHn; clear - Heqn'.\n    distribute_scale.\n    repeat rewrite <- Mscale_kron_dist_l.\n    rewrite <- kron_plus_distr_r.\n    simpl Cexp at 1 3; autorewrite with R_db C_db Cexp_db.\n    rewrite Cmult_comm.\n    rewrite <- Mscale_assoc.\n    rewrite <- Mscale_plus_distr_r.\n    rewrite <- Mscale_kron_dist_l.\n    rewrite Mscale_assoc.\n    rewrite Mscale_kron_dist_l.\n    apply f_equal2. (* some missing automation from lca/lra here *)\n    rewrite <- tech_pow_Rmult.\n    rewrite sqrt_mult; try lra.\n    rewrite RtoC_mult.\n    rewrite Cinv_mult_distr; nonzero.\n    apply pow_le; lra.\n    replace (n' - 0)%nat with n' by lia.    \n    rewrite <- Cexp_add.\n    replace (shift (update f 0 true) 1) with (shift f 1).\n    2: { unfold shift. apply functional_extensionality.\n         intro x. rewrite update_index_neq; auto. lia. }\n    replace (VectorStates.b2R (f O) * PI + 2 * PI * INR (funbool_to_nat n' (shift f 1)) * / (2 * 2 ^ n'))%R with (2 * PI * INR (funbool_to_nat (S n') f) * / (2 ^ S n'))%R.\n    2: { Local Transparent funbool_to_nat.\n         rewrite funbool_to_nat_shift with (k:=S O) by lia.\n         unfold funbool_to_nat; simpl.\n         field_simplify_eq; try nonzero. \n         replace (n' - 0)%nat with n' by lia. \n         repeat (try rewrite mult_INR; try rewrite plus_INR; try rewrite pow_INR). \n         simpl. replace (1 + 1)%R with 2%R by lra. \n         destruct (f O); simpl; lra. }\n    remember (fun i => ∣0⟩ .+ Cexp (2 * PI * INR (funbool_to_nat (S n' - i) (shift f i)) / 2 ^ (S n' - i)) .* ∣1⟩) as f'.\n    replace (fun i => ∣0⟩ .+ Cexp (2 * PI * INR (funbool_to_nat (n' - i) (shift (shift f 1) i)) / 2 ^ (n' - i)) .* ∣1⟩) with (shift f' 1).\n    2: { rewrite Heqf'. unfold shift.\n         apply functional_extensionality. intro x.\n         replace (S n' - (x + 1))%nat with (n' - x)%nat by lia.\n         replace (fun i => f (i + (x + 1))%nat) with (fun i => f (i + x + 1)%nat).\n         reflexivity.\n         apply functional_extensionality. intro x0.\n         replace (x0 + x + 1)%nat with (x0 + (x + 1))%nat by lia.\n         reflexivity. }\n    simpl Nat.b2n.\n    replace (∣ 0 ⟩ .+ Cexp (2 * PI * INR (funbool_to_nat (S n') f) * / 2 ^ S n') .* ∣ 1 ⟩) with (f' O).\n    2: { subst; simpl. rewrite shift_0. reflexivity. }\n    rewrite vkron_extend_l.\n    reflexivity.\n    intro i; subst; simpl; auto with wf_db.\nQed.\nLocal Transparent QFT controlled_rotations Nat.pow funbool_to_nat.\n\n(* The property in the previous lemma can be stated without the shift operation *)\nLemma Cexp_shift : forall n i f, (i < n)%nat ->\n  Cexp (2 * PI * INR (funbool_to_nat (n - i) (shift f i)) / 2 ^ (n - i)) =\n    Cexp (2 * PI * INR (funbool_to_nat n f) / 2 ^ (n - i)).\nProof.\n  intros n i f H.\n  rewrite (funbool_to_nat_shift n f i) by auto.\n  rewrite plus_INR, mult_INR, pow_INR.\n  replace (INR 2) with 2%R by (simpl; lra).\n  rewrite Rmult_plus_distr_l, Rdiv_plus_distr.\n  rewrite Cexp_add.\n  replace (2 * PI * (2 ^ (n - i) * INR (funbool_to_nat i f)) / 2 ^ (n - i))%R with (IZR (2 * Z_of_nat (funbool_to_nat i f)) * PI)%R.\n  rewrite Cexp_2nPI.\n  lca.\n  rewrite mult_IZR, <- INR_IZR_INZ.\n  field_simplify_eq; nonzero.\nQed.\n\nLemma SWAP_action_on_product_state : \n  forall m n dim (A : Vector (2 ^ m)) (B : Vector (2 ^ (n - m - 1))) (C : Vector (2 ^ (dim - n - 1))) (ψ1 ψ2 : Vector 2),\n  (m < n)%nat -> (n < dim)%nat ->\n  WF_Matrix ψ1 -> WF_Matrix ψ2 -> WF_Matrix A -> WF_Matrix B -> WF_Matrix C ->\n  @ Mmult _ _ (1 * 1 * 1 * 1 * 1) (@uc_eval dim (SWAP m n)) (A ⊗ ψ1 ⊗ B ⊗ ψ2 ⊗ C) = A ⊗ ψ2 ⊗ B ⊗ ψ1 ⊗ C.\nProof.\n  intros m n dim A B C ψ1 ψ2 ? ? ? ? ? ? ?.\n  autorewrite with eval_db. \n  gridify.\n  replace ((m + (1 + x + 1) + d1 - (m + 1 + x) - 1))%nat with d1 by lia.\n  rewrite (ket_decomposition ψ1) by auto.\n  rewrite (ket_decomposition ψ2) by auto.\n  autorewrite with ket_db.\n  repeat rewrite (Cmult_comm (ψ1 _ _)).\n  lma.\nQed.\n\nLemma SWAP_symmetric : forall m n dim, (@SWAP dim m n) ≡ SWAP n m.\nProof.\n  intros. unfold uc_equiv.\n  autorewrite with eval_db.\n  gridify.\nQed.\n\nLemma SWAP_on_2_qubits : @uc_eval 2 (SWAP 0 1) = swap.\nProof. autorewrite with eval_db. solve_matrix. Qed.\n\nLemma SWAP_action_on_vkron : forall dim m n (f : nat -> Vector 2),\n  (dim > 0)%nat -> (m < dim)%nat -> (n < dim)%nat -> (m <> n)%nat ->\n(*  (forall i, (i < dim)%nat -> WF_Matrix (f i)) -> *)\n  (forall i, WF_Matrix (f i)) -> (* Changed *)\n  @Mmult _ _ (1 * 1) (uc_eval (SWAP m n)) (vkron dim f) = \n    vkron dim (fun k => if (k =? m) then f n else if (k =? n) then f m else f k).\nProof.\n  intros dim m n f Hdim Hm Hn Hneq WF.\n  destruct dim; try lia.\n  destruct dim; try lia. \n  destruct dim.\n  - destruct n; destruct m; try lia.\n    destruct m; try lia. simpl. \n    rewrite SWAP_symmetric, SWAP_on_2_qubits.\n    Qsimpl. reflexivity.\n    destruct n; try lia. simpl. \n    rewrite SWAP_on_2_qubits.\n    Qsimpl. reflexivity.\n  - remember (S (S (S dim))) as dim'.\n    remember (fun k : nat => if k =? m then f n else if k =? n then f m else f k) as f'.\n    bdestruct (m <? n).\n    + assert (WF' : forall i, WF_Matrix (f' i)). subst. intros. destruct (i =? m), (i =? n); auto.\n      rewrite 2 (vkron_split dim' m); auto with wf_db; try lia.\n      rewrite 2 (vkron_split (dim' - 1 - m) (n - m - 1)); auto with wf_db; try lia. \n      replace (dim' - 1 - m - 1 - (n - m - 1))%nat with (dim' - n - 1)%nat by lia. (* slow *)\n      restore_dims. repeat rewrite <- kron_assoc by auto with wf_db. restore_dims.\n      repeat rewrite shift_simplify.\n      rewrite SWAP_action_on_product_state; auto with wf_db.\n      repeat rewrite shift_plus.\n      replace (n - m - 1 + (m + 1))%nat with n by lia.\n      replace (n - m - 1 + 1 + (m + 1))%nat with (n + 1)%nat by lia.\n      rewrite (vkron_eq _ f f').\n      replace (f n) with (f' m).\n      rewrite (vkron_eq _ (shift f (m + 1)) (shift f' (m + 1))).\n      replace (f m) with (f' n).\n      rewrite (vkron_eq _ (shift f (n + 1)) (shift f' (n + 1))).\n      reflexivity.\n      all: intros; subst f'; unfold shift; bdestruct_all; trivial.\n      all: try apply vkron_WF; intros; apply WF; lia.\n    + assert (WF' : forall i, WF_Matrix (f' i)). subst. intros. destruct (i =? m), (i =? n); auto.\n      rewrite 2 (vkron_split dim' n); auto with wf_db; try lia.\n      rewrite 2 (vkron_split (dim' - 1 - n) (m - n - 1)); auto with wf_db; try lia.\n      replace (dim' - 1 - n - 1 - (m - n - 1))%nat with (dim' - m - 1)%nat by lia. \n      restore_dims. repeat rewrite <- kron_assoc by auto with wf_db. restore_dims.\n      repeat rewrite shift_simplify.\n      rewrite SWAP_symmetric.\n      rewrite SWAP_action_on_product_state; auto with wf_db; try lia.\n      repeat rewrite shift_plus.\n      replace (m - n - 1 + (n + 1))%nat with m by lia.\n      replace (m - n - 1 + 1 + (n + 1))%nat with (m + 1)%nat by lia.\n      rewrite (vkron_eq _ f f').\n      replace (f m) with (f' n).\n      rewrite (vkron_eq _ (shift f (n + 1)) (shift f' (n + 1))).\n      replace (f n) with (f' m).\n      rewrite (vkron_eq _ (shift f (m + 1)) (shift f' (m + 1))).\n      reflexivity.\n      all: intros; subst f'; unfold shift; bdestruct_all; trivial.\n      all: try apply vkron_WF; intros; apply WF; lia.\nQed.\n\nLemma reverse_qubits'_action_on_vkron : forall dim n (f : nat -> Vector 2),\n  (n > 0)%nat -> (2 * n <= dim)%nat ->\n  (forall i : nat, WF_Matrix (f i)) ->\n  @Mmult _ _ 1 (uc_eval (reverse_qubits' dim n)) (vkron dim f) = \n    vkron dim (fun k => if ((k <? n)%nat || (dim - n - 1 <? k)%nat) \n                     then f (dim - k - 1)%nat else f k).\nProof.\n  intros dim n f Hn1 Hn2 WF.\n  induction n; try lia.\n  destruct n.\n  - clear IHn. simpl.\n    rewrite SWAP_action_on_vkron; try lia.\n    apply vkron_eq.\n    intros.\n    bdestruct_all; simpl.\n    subst. replace (dim - 0 - 1)%nat with (dim - 1)%nat by lia. reflexivity.\n    subst. replace (dim - (dim - 1) - 1)%nat with O by lia. reflexivity.\n    reflexivity.\n    apply WF.\n  - replace (uc_eval (reverse_qubits' dim (S (S n)))) with (uc_eval (SWAP (S n) (dim - (S n) - 1)) × uc_eval (reverse_qubits' dim (S n))) by reflexivity.\n    rewrite Mmult_assoc.\n    rewrite IHn by lia; clear IHn.\n    rewrite SWAP_action_on_vkron; try lia.\n    apply vkron_eq.\n    intros.\n    bdestruct_all; simpl; subst; trivial.\n    replace (dim - (dim - S n - 1) - 1)%nat with (S n) by lia.\n    reflexivity.\n    intros.\n    bdestruct_all; simpl; apply WF; lia.\nQed.\n\nLemma reverse_qubits_action_on_vkron : forall n f,\n  (n > 1)%nat -> (forall i : nat, WF_Matrix (f i)) ->\n  uc_eval (reverse_qubits n) × (vkron n f) = vkron n (fun k => f (n - k - 1)%nat).\nProof. \n  intros n f Hn WF.\n  unfold reverse_qubits.\n  rewrite reverse_qubits'_action_on_vkron.\n  apply vkron_eq.\n  intros i Hi.\n  bdestruct (i <? n / 2); bdestruct (n - n / 2 - 1 <? i); simpl; try reflexivity.\n  destruct (Nat.even n) eqn:evn.\n  apply Nat.even_spec in evn.\n  destruct evn. subst.\n  rewrite (Nat.mul_comm 2 x) in *.\n  try rewrite Nat.div_mul in *; lia.\n  apply negb_true_iff in evn.\n  apply Nat.odd_spec in evn.\n  destruct evn. subst.\n  replace ((2 * x + 1) / 2)%nat with x in *.\n  replace (2 * x + 1 - i - 1)%nat with i by lia. reflexivity.\n  rewrite Nat.add_comm.\n  replace (S O) with (Nat.b2n true) by reflexivity. \n  rewrite Nat.add_b2n_double_div2. reflexivity.\n  apply Nat.div_str_pos. lia. \n  apply Nat.mul_div_le. lia.\n  apply WF.\nQed.\n\n(* QFT w/ reverse takes basis state ∣x⟩ to (1/√N) \\sum_{k=0}^{N-1} e^{2πixk/N} ∣k⟩;\n   this is a more useful form of QFT_semantics *)\nLemma QFT_w_reverse_semantics : forall n (f : nat -> bool),\n  (n > 1)%nat ->\n  uc_eval (QFT_w_reverse n) × (f_to_vec n f) = \n    / √(2 ^ n) .* big_sum (fun k => Cexp (2 * PI * INR (funbool_to_nat n f * k) / (2 ^ n)) .* basis_vector (2^n) k) (2^n).\nProof.\n  intros n f Hn.\n  unfold QFT_w_reverse; simpl.\n  rewrite Mmult_assoc.\n  rewrite QFT_semantics by lia.\n  distribute_scale.\n  rewrite reverse_qubits_action_on_vkron; auto with wf_db.\n  apply f_equal2; try reflexivity.\n  remember (2 * PI * INR (funbool_to_nat n f) / 2 ^ n)%R as c.\n  rewrite (vkron_eq _ _ (fun k : nat => ∣0⟩ .+ Cexp (c * 2 ^ (n - k - 1)) .* ∣1⟩)).\n  rewrite (big_sum_eq_bounded _ (fun k : nat => Cexp (c * INR k) .* basis_vector (2 ^ n) k)).\n  apply vkron_to_vsum1. lia.\n  intros i Hi.\n  subst. apply f_equal2; try reflexivity. apply f_equal. \n  rewrite mult_INR. lra.\n  intros i Hi. \n  rewrite Cexp_shift by lia.\n  subst. do 2 (apply f_equal2; try reflexivity). apply f_equal.\n  field_simplify_eq; try nonzero.\n  repeat rewrite Rmult_assoc.\n  rewrite <- pow_add.\n  replace (n - (n - i - 1) + (n - i - 1))%nat with n by lia.\n  reflexivity.\nQed.\n\nLemma Csum_geometric_series : forall (c : C) (n : nat),\n  1 - c <> 0 -> Σ (fun i => c ^ i) n = (1 - c ^ n) / (1 - c).\nProof.\n  intros c n Hc.\n  induction n; simpl. lca.\n  rewrite IHn. \n  field_simplify_eq; try lca. (* lca should complete proof here... *)\n  apply Hc.\nQed.\n\nLemma Cexp_neq_1 : forall x,\n  x <> 0 -> -2 * PI < x < 2 * PI -> Cexp x <> 1.\nProof.\n  intros x Hnz [Hlt Hgt] contra.\n  apply pair_equal_spec in contra as [H _].\n  assert (cos x < 1).\n  { destruct (Rlt_le_dec x 0).\n    destruct (Rlt_le_dec x (- PI)).\n    rewrite <- cos_2PI, <- cos_neg.\n    apply cos_increasing_1; lra.\n    rewrite <- cos_0, <- cos_neg.\n    apply cos_decreasing_1; lra.\n    destruct (Rlt_le_dec x PI).\n    rewrite <- cos_0.\n    apply cos_decreasing_1; lra.\n    rewrite <- cos_2PI.\n    apply cos_increasing_1; lra. }\n  lra.  \nQed.\n\nLemma Csum_Cexp_nonzero : forall (z : BinInt.Z) (N : nat), \n  (IZR z <> 0) -> (- INR N < IZR z < INR N)%R ->\n  Σ (fun i => Cexp (2 * PI * IZR z / INR N) ^ i) N = 0.\nProof.\n  intros z N Hnz [Hineq1 Hineq2].\n  rewrite Csum_geometric_series.\n  rewrite Cexp_pow.\n  replace (2 * PI * IZR z / INR N * INR N)%R with (IZR (2 * z) * PI)%R.\n  rewrite Cexp_2nPI. lca.\n  rewrite mult_IZR. field_simplify_eq; try nonzero.\n  assert (H : Cexp (2 * PI * IZR z / INR N) <> 1).\n  apply Cexp_neq_1.\n  (* is there a tactic that can prove inequalities over R? *)\n  do 3 (apply Rmult_integral_contrapositive_currified; try nonzero).\n  apply PI_neq0.\n  split.\n  assert (2 * PI * (- INR N) / INR N < 2 * PI * IZR z / INR N).\n  replace (2 * PI * - INR N / INR N)%R with (- INR N * (2 * PI / INR N))%R.\n  replace (2 * PI * IZR z / INR N)%R with (IZR z * (2 * PI / INR N))%R.\n  apply Rmult_lt_compat_r. \n  apply Rmult_lt_0_compat.\n  apply Rgt_2PI_0.\n  nonzero.\n  assumption.\n  1,2: field_simplify_eq; nonzero.\n  replace (2 * PI * - INR N / INR N)%R with (-2 * PI)%R in H.\n  2: field_simplify_eq; nonzero.\n  assumption.\n  replace (2 * PI * IZR z / INR N)%R with (IZR z * (2 * PI / INR N))%R.\n  replace (2 * PI)%R with (INR N * (2 * PI / INR N))%R at 2.    \n  apply Rmult_lt_compat_r. \n  apply Rmult_lt_0_compat.\n  apply Rgt_2PI_0.\n  nonzero.\n  assumption.\n  1,2: field_simplify_eq; nonzero. \n  apply Cminus_eq_contra.\n  apply not_eq_sym.\n  assumption.\nQed.\n\nLemma QFT_w_reverse_semantics_inverse : forall n (f : nat -> bool),\n  (n > 1)%nat ->\n  uc_eval (invert (QFT_w_reverse n)) × f_to_vec n f = \n    (/ √(2 ^ n) .* big_sum (fun k => Cexp (- 2 * PI * INR (funbool_to_nat n f * k) / (2 ^ n)) .* basis_vector (2^n) k) (2^n)).\nProof.\n  intros n f Hn.\n  rewrite <- invert_correct. \n  rewrite <- (Mmult_1_l _ _ (_ .* _)); auto with wf_db.\n  assert (H : (n > 0)%nat) by lia.\n  specialize (uc_eval_unitary n (QFT_w_reverse n) (QFT_w_reverse_WT n H)) as [_ WFU].\n  rewrite <- WFU.\n  rewrite Mmult_assoc.\n  apply f_equal2; try reflexivity.\n  distribute_scale. rewrite Mmult_Msum_distr_l.\n  erewrite big_sum_eq_bounded.\n  2: { intros i Hi.\n       distribute_scale.\n       rewrite basis_f_to_vec_alt by auto.\n       rewrite QFT_w_reverse_semantics by auto.\n       rewrite Mscale_assoc.\n       rewrite <- Mscale_Msum_distr_r.\n       erewrite big_sum_eq_bounded.\n       2: { intros i0 Hi0.\n            rewrite Mscale_assoc. \n            rewrite (Cmult_comm _ (/ _)).\n            rewrite <- Cmult_assoc, <- Cexp_add.\n            rewrite nat_to_funbool_inverse by auto.\n            replace (-2 * PI * INR (funbool_to_nat n f * i) / 2 ^ n + 2 * PI * INR (i * i0) / 2 ^ n)%R with ((2 * PI * (INR i0 - INR (funbool_to_nat n f)) / 2 ^ n) * INR i)%R.\n            reflexivity.\n            repeat rewrite mult_INR; lra. }\n       reflexivity. }\n  rewrite big_sum_swap_order.\n  rewrite (big_sum_eq_bounded _ (fun i => / √ (2 ^ n) .* (if i =? funbool_to_nat n f then (2 ^ n) .* basis_vector (2 ^ n) i else Zero))).\n  2: { intros i Hi.\n       rewrite Mscale_Msum_distr_l.\n       rewrite <- Csum_mult_l.\n       rewrite <- Mscale_assoc.\n       apply f_equal2; try reflexivity.\n       bdestruct (i =? funbool_to_nat n f).\n       subst.\n       rewrite Csum_1.\n       rewrite pow_INR; simpl. replace (1 + 1)%R with 2%R by lra. \n       rewrite <- RtoC_pow. reflexivity.\n       intro x.\n       simpl. rewrite <- Cexp_0. apply f_equal. lra.\n       replace (fun x : nat => Cexp (2 * PI * (INR i - INR (funbool_to_nat n f)) / 2 ^ n * INR x)) with (fun x => Cexp (2 * PI * (IZR (Z.of_nat i - Z.of_nat (funbool_to_nat n f))) / INR (2 ^ n)) ^ x).\n       rewrite Csum_Cexp_nonzero. Msimpl. reflexivity.\n       rewrite minus_IZR. rewrite <- 2 INR_IZR_INZ. \n       apply Rminus_eq_contra. \n       apply not_INR. assumption.\n       specialize (funbool_to_nat_bound n f) as Hf.\n       clear - Hi Hf.\n       apply inj_lt in Hi. apply inj_lt in Hf.\n       replace (INR (2 ^ n)) with (IZR (Z.of_nat (2 ^ n))). \n       split. \n       rewrite <- opp_IZR. apply IZR_lt. lia.\n       apply IZR_lt. lia. \n       rewrite <- INR_IZR_INZ, pow_INR; simpl.\n       replace (1 + 1)%R with 2%R by lra. reflexivity.\n       apply functional_extensionality; intro x. \n       rewrite Cexp_pow.\n       rewrite minus_IZR. rewrite <- 2 INR_IZR_INZ.\n       rewrite pow_INR.\n       reflexivity. }\n  rewrite Mscale_Msum_distr_r.\n  rewrite Mscale_assoc.\n  replace (big_sum (fun i : nat => if i =? funbool_to_nat n f then (2 ^ n) .* basis_vector (2 ^ n) i else Zero) (2 ^ n)) with (2 ^ n .* basis_vector (2 ^ n) (funbool_to_nat n f)).\n  rewrite basis_f_to_vec.\n  rewrite Mscale_assoc.\n  rewrite <- (Mscale_1_l _ _ (basis_vector _ _)) at 1.\n  apply f_equal2; try reflexivity.\n  field_simplify_eq; try nonzero.\n  rewrite Csqrt_sqrt. rewrite RtoC_pow. reflexivity.\n  rewrite pow_IZR. apply IZR_le. apply Z.pow_nonneg. lia.\n  specialize (funbool_to_nat_bound n f) as ?.\n  erewrite big_sum_unique. \n  reflexivity.\n  exists (funbool_to_nat n f).\n  repeat split.\n  assumption.\n  rewrite Nat.eqb_refl. reflexivity.\n  intros. bdestruct_all. reflexivity.\nQed.\n\n(** Proof of QPE semantics **)\n\nLemma f_to_vec_controlled_U : forall n k (c : base_ucom n) (ψ : Vector (2 ^ n)) (θ : R) i j (f : nat -> bool),\n  (k > 0)%nat -> (n > 0)%nat -> (j < k)%nat -> (i > 0)%nat ->\n  uc_well_typed c -> WF_Matrix ψ ->\n  (uc_eval c) × ψ = Cexp θ .* ψ ->\n  @Mmult _ _ (1 * 1) (uc_eval (cast (niter i (control j (map_qubits (fun q : nat => (k + q)%nat) c))) (k + n))) ((f_to_vec k f) ⊗ ψ) = \n    Cexp (f j * INR i * θ) .* (f_to_vec k f) ⊗ ψ.\nProof.\n  intros n k c ψ θ i j f ? ? ? ? WT WF Heig. \n  rewrite cast_niter_commute. \n  rewrite niter_correct by lia.\n  rewrite cast_control_commute.\n  rewrite <- niter_correct by lia.\n  rewrite niter_control_commute by lia.\n  rewrite control_correct; try lia.\n  rewrite Mmult_plus_distr_r.\n  rewrite Mmult_assoc.\n  rewrite niter_correct by lia.\n  rewrite <- pad_dims_l.\n  replace (2 ^ (k + n))%nat with (2 ^ k * 2 ^ n)%nat by unify_pows_two.\n  rewrite Mmult_n_kron_distr_l. \n  rewrite kron_mixed_product. \n  rewrite Mmult_n_1_r.\n  Msimpl.\n  erewrite Mmult_n_eigenvector; auto.\n  2: apply Heig.\n  distribute_scale.\n  replace (proj j (k + n) false) with (proj j k false ⊗ I (2 ^ n)).\n  2: unfold proj; autorewrite with eval_db; gridify; trivial.\n  replace (proj j (k + n) true) with (proj j k true ⊗ I (2 ^ n)).\n  2: unfold proj; autorewrite with eval_db; gridify; trivial.\n  restore_dims. \n  repeat rewrite kron_mixed_product.\n  Msimpl.\n  destruct (f j) eqn:fj.\n  rewrite (f_to_vec_proj_eq _ _ _ true) by auto.\n  rewrite (f_to_vec_proj_neq _ _ _ false); auto.\n  2: rewrite fj; easy.\n  Msimpl.\n  rewrite Rmult_1_l. \n  rewrite Cexp_pow.\n  rewrite Rmult_comm.\n  reflexivity.\n  rewrite (f_to_vec_proj_eq _ _ _ false) by auto.\n  rewrite (f_to_vec_proj_neq _ _ _ true); auto.\n  2: rewrite fj; easy.\n  simpl. autorewrite with R_db Cexp_db.\n  Msimpl.\n  reflexivity. \n  apply is_fresh_niter; auto.\n  apply map_qubits_fresh; auto.\n  apply uc_well_typed_niter.\n  apply uc_well_typed_map_qubits; auto.\nQed.\n\nLemma niter_1 : forall {d} (c : base_ucom d), niter 1 c = c.\nProof. reflexivity. Qed.\n\nLemma controlled_powers'_action_on_basis : \n  forall k kmax n (c : base_ucom n) (ψ : Vector (2^n)) f θ,\n  (n > 0)%nat -> (k > 0)%nat -> (kmax >= k)%nat -> uc_well_typed c -> WF_Matrix ψ ->\n  (uc_eval c) × ψ = Cexp (2 * PI * θ) .* ψ ->\n  @Mmult _ _ (1 * 1) (uc_eval (controlled_powers' (map_qubits (fun q => kmax + q)%nat c) k kmax)) ((f_to_vec kmax f) ⊗ ψ) =\n    Cexp (2 * PI * θ * INR (funbool_to_nat k (shift f (kmax - k)))) .* ((f_to_vec kmax f) ⊗ ψ).\nProof.\n  intros k kmax n c ψ f θ Hn Hk Hkmax WT WF Heigen.\n  destruct k; try lia.\n  induction k.\n  - simpl.\n    rewrite <- (niter_1 (cast _ _)).\n    rewrite <- cast_niter_commute.\n    erewrite f_to_vec_controlled_U; try apply Heigen; auto.\n    2: lia.\n    rewrite Mscale_kron_dist_l.\n    apply f_equal2; try reflexivity.\n    unfold funbool_to_nat, shift; simpl.\n    rewrite Nat.add_0_r.\n    apply f_equal.\n    destruct (f (kmax - 1)%nat); simpl; lra.\n  - replace (controlled_powers' (map_qubits (fun q : nat => (kmax + q)%nat) c) (S (S k)) kmax) with (controlled_powers' (map_qubits (fun q : nat => (kmax + q)%nat) c) (S k) kmax ; cast (niter (2 ^ (S k)) (control (kmax - (S k) - 1) (map_qubits (fun q : nat => (kmax + q)%nat) c))) (kmax + n)) by reflexivity.\n    Local Opaque controlled_powers' Nat.pow. \n    simpl uc_eval.\n    rewrite Mmult_assoc. \n    rewrite IHk by lia; clear IHk.\n    distribute_scale.\n    erewrite f_to_vec_controlled_U; try apply Heigen; auto.\n    2,3: lia.\n    2: assert (2 ^ S k <> 0)%nat by (apply Nat.pow_nonzero; lia); lia.\n    restore_dims. distribute_scale. \n    apply f_equal2; try reflexivity. \n    rewrite <- Cexp_add.\n    apply f_equal.\n    rewrite (funbool_to_nat_shift (S (S k)) _ (S O)) by lia.\n    replace (S (S k) - 1)%nat with (S k) by lia.\n    replace (shift (shift f (kmax - S (S k))) 1) with (shift f (kmax - S k)).\n    2: { unfold shift. apply functional_extensionality; intro x. \n         replace (x + 1 + (kmax - S (S k)))%nat with (x + (kmax - S k))%nat by lia.\n         reflexivity. }\n    rewrite plus_INR, mult_INR. repeat rewrite pow_INR. \n    unfold shift; simpl. \n    replace (1 + 1)%R with 2%R by lra.\n    replace (kmax - S (S k))%nat with (kmax - S k - 1)%nat by lia.\n    unfold funbool_to_nat; simpl.\n    field_simplify_eq. \n    destruct (f (kmax - S k - 1)%nat); simpl; lra.\nQed.\n\nLemma controlled_powers_action_on_basis : \n  forall k n (c : base_ucom n) (ψ : Vector (2^n)) f θ,\n  (n > 0)%nat -> (k > 0)%nat -> uc_well_typed c -> WF_Matrix ψ ->\n  (uc_eval c) × ψ = Cexp (2 * PI * θ) .* ψ ->\n  @Mmult _ _ (1 * 1) (uc_eval (controlled_powers (map_qubits (fun q => k + q)%nat c) k)) ((f_to_vec k f) ⊗ ψ) =\n  Cexp (2 * PI * θ * INR (funbool_to_nat k f)) .* ((f_to_vec k f) ⊗ ψ).\nProof.\n  intros k n c ψ f θ Hn Hk WT WF Heigen.\n  unfold controlled_powers.\n  erewrite controlled_powers'_action_on_basis; try apply Heigen; auto.\n  replace (k - k)%nat with O by lia.\n  rewrite shift_0.\n  reflexivity.\nQed.\n\n(* Simplify the expression uc_eval (QPE k n c) × (k ⨂ ∣0⟩ ⊗ ψ) *)\nLocal Opaque QFT_w_reverse Nat.mul Nat.pow.\nLemma QPE_simplify : forall k n (c : base_ucom n) (ψ : Vector (2 ^ n)) θ,\n  (n > 0)%nat -> (k > 1)%nat -> uc_well_typed c -> WF_Matrix ψ ->\n  (uc_eval c) × ψ = Cexp (2 * PI * θ) .* ψ ->\n  @Mmult _ _ (1 * 1) (uc_eval (QPE k n c)) (k ⨂ ∣0⟩ ⊗ ψ) = \n    (/ (2 ^ k) .* big_sum (fun i : nat => (Σ (fun j => Cexp (2 * PI * (θ - INR i / 2 ^ k) * INR j)) (2 ^ k)) .* basis_vector (2 ^ k) i) (2 ^ k) ⊗ ψ).\nProof.\n  intros k n c ψ θ Hn Hk WT WF Heig.\n  unfold QPE; simpl.\n  repeat rewrite Mmult_assoc.\n  repeat rewrite <- pad_dims_r.\n  rewrite npar_H by lia.\n  replace (2 ^ (k + n))%nat with (2 ^ k * 2 ^ n)%nat by unify_pows_two. \n  replace (1 * 1)%nat with (1 ^ k * 1)%nat.\n  2: rewrite Nat.pow_1_l; reflexivity.\n  rewrite kron_mixed_product.\n  Msimpl. \n  rewrite H0_kron_n_spec_alt by lia.\n  restore_dims. distribute_scale.\n  rewrite kron_Msum_distr_r.\n  replace (2 ^ (k + n))%nat with (2 ^ k * 2 ^ n)%nat by unify_pows_two. \n  rewrite Mmult_Msum_distr_l.\n  erewrite big_sum_eq_bounded.\n  2: { intros i Hi.\n       rewrite basis_f_to_vec_alt by auto. restore_dims.\n       erewrite controlled_powers_action_on_basis; try apply Heig; auto; try lia. \n       rewrite nat_to_funbool_inverse by auto. reflexivity. }\n  rewrite Mmult_Msum_distr_l.\n  erewrite big_sum_eq_bounded.\n  2: { intros i Hi.\n       rewrite Mscale_mult_dist_r.\n       rewrite kron_mixed_product.\n       Msimpl.\n       rewrite QFT_w_reverse_semantics_inverse by auto.\n       distribute_scale.\n       rewrite (Cmult_comm _ (/ _)).\n       rewrite <- Mscale_assoc.\n       rewrite <- Mscale_kron_dist_l.\n       rewrite <- Mscale_Msum_distr_r.       \n       erewrite big_sum_eq_bounded.\n       2: { intros i0 Hi0.\n            rewrite Mscale_assoc. \n            rewrite <- Cexp_add.\n            rewrite nat_to_funbool_inverse by auto.\n            replace (2 * PI * θ * INR i + -2 * PI * INR (i * i0) / 2 ^ k)%R with ((2 * PI * (θ - INR i0 / 2 ^ k)) * INR i)%R.\n            reflexivity.\n            repeat rewrite mult_INR; lra. }\n       rewrite <- Mscale_kron_dist_l.\n       reflexivity. }\n  rewrite <- kron_Msum_distr_r.\n  rewrite Mscale_Msum_distr_r. \n  distribute_scale.\n  rewrite big_sum_swap_order.\n  erewrite big_sum_eq_bounded.\n  2: { intros i Hi.\n       rewrite Mscale_Msum_distr_l.\n       reflexivity. }\n  replace (/ √ (2 ^ k) * / √ (2 ^ k)) with (/ 2 ^ k).\n  reflexivity.\n  rewrite <- Cinv_mult_distr; try nonzero.\n  rewrite <- RtoC_mult, sqrt_def, <- RtoC_pow.\n  reflexivity. \n  apply pow_le. lra. \n  apply npar_WT; try lia.\n  rewrite <- uc_well_typed_invert.\n  apply QFT_w_reverse_WT.\n  lia.\nQed.\nLocal Transparent QFT_w_reverse Nat.mul.\n\n(** Simplified QPE - for the general proof see QPEGeneral.v\n\n  Preconditions:\n   - z is the k-bit dyadic rational representation of θ\n   - U × ∣ψ⟩ = Cexp (2πθ / 2^k) .* ∣ψ⟩\n\n  Postcondition: the first k bits of the output state are z *)\nLemma QPE_semantics_simplified : forall k n (c : base_ucom n) z (ψ : Vector (2 ^ n)),\n  (n > 0)%nat -> (k > 1)%nat -> uc_well_typed c -> WF_Matrix ψ ->\n  let θ := (INR (funbool_to_nat k z) / 2 ^ k)%R in\n  (uc_eval c) × ψ = Cexp (2 * PI * θ) .* ψ ->\n  @Mmult _ _ (1 * 1) (uc_eval (QPE k n c)) (k ⨂ ∣0⟩ ⊗ ψ) = (f_to_vec k z) ⊗ ψ.\nProof.\n  intros k n c z ψ Hn Hk WT WF θ Heig.\n  rewrite QPE_simplify with (θ := θ) by assumption.\n  rewrite (big_sum_eq_bounded _ (fun i => if i =? funbool_to_nat k z then (2 ^ k) .* basis_vector (2 ^ k) i else Zero)).\n  specialize (funbool_to_nat_bound k z) as Hz.\n  rewrite (big_sum_unique (2 ^ k .* basis_vector (2 ^ k) (funbool_to_nat k z))). \n  distribute_scale. \n  replace (/ 2 ^ k * 2 ^ k) with C1.\n  rewrite Mscale_1_l.\n  rewrite basis_f_to_vec. reflexivity.\n  rewrite Cinv_l; nonzero.\n  exists (funbool_to_nat k z).\n  repeat split.\n  assumption.\n  rewrite Nat.eqb_refl. reflexivity.\n  intros. bdestruct_all. reflexivity.\n  intros i Hi.\n  bdestruct (i =? funbool_to_nat k z).\n  rewrite Csum_1.\n  rewrite RtoC_pow, pow_INR; simpl. reflexivity.\n  intro x.\n  subst i θ.\n  simpl. rewrite <- Cexp_0.\n  apply f_equal. lra.\n  replace (fun j => Cexp (2 * PI * (θ - INR i / 2 ^ k) * INR j)) with (fun j => Cexp (2 * PI * IZR (Z.of_nat (funbool_to_nat k z) - Z.of_nat i) / INR (2 ^ k)) ^ j).\n  rewrite Csum_Cexp_nonzero.\n  Msimpl. reflexivity.\n  rewrite minus_IZR, <- 2 INR_IZR_INZ. \n  apply Rminus_eq_contra. \n  apply not_INR. apply not_eq_sym. assumption.\n  specialize (funbool_to_nat_bound k z) as Hz.\n  clear - Hi Hz.\n  apply inj_lt in Hi. apply inj_lt in Hz.\n  replace (INR (2 ^ k))%R with (IZR (Z.of_nat (2 ^ k))). \n  split. \n  rewrite <- opp_IZR. apply IZR_lt. lia.\n  apply IZR_lt. lia. \n  rewrite <- INR_IZR_INZ, pow_INR; simpl.\n  replace (1 + 1)%R with 2%R by lra. reflexivity.\n  apply functional_extensionality; intro x. \n  rewrite Cexp_pow.\n  rewrite minus_IZR, <- 2 INR_IZR_INZ.\n  subst θ. apply f_equal. \n  rewrite pow_INR.\n  replace (INR 2) with 2 by reflexivity.\n  lra.\nQed.\n\n(* QPE_var is the variant of QPE used in our implementation of Shor's.\n   It takes a circuit constructor (f : nat -> base_ucom), which has the \n   same effect as (fun i => niter (2^i) c) when acting on eigenstates.\n*)\n\nLocal Transparent Nat.pow controlled_powers'.\n\nLemma f_to_vec_controlled_U_var : forall n k (fc : nat -> base_ucom n) (ψ : Vector (2 ^ n)) (θ : R) i j (f : nat -> bool),\n  (k > 0)%nat -> (n > 0)%nat -> (j < k)%nat -> (i > 0)%nat ->\n  uc_well_typed (fc i) -> WF_Matrix ψ ->\n  (uc_eval (fc i)) × ψ = Cexp (θ * (INR (2^i))) .* ψ ->\n  @Mmult _ _ (1 * 1) (uc_eval (cast (control j (map_qubits (fun q : nat => (k + q)%nat) (fc i))) (k + n)%nat)) ((f_to_vec k f) ⊗ ψ) = \n    Cexp (f j * θ * INR (2^i)) .* (f_to_vec k f) ⊗ ψ.\nProof.\n  intros n k c ψ θ i j f ? ? ? ? WT WF Heig. \n  rewrite cast_control_commute.\n  rewrite control_correct; try lia.\n  rewrite Mmult_plus_distr_r.\n  rewrite Mmult_assoc.\n  rewrite <- pad_dims_l.\n  replace (2 ^ (k + n))%nat with (2 ^ k * 2 ^ n)%nat by unify_pows_two.\n  rewrite kron_mixed_product. \n  Msimpl.\n  distribute_scale.\n  replace (proj j (k + n) false) with (proj j k false ⊗ I (2 ^ n)).\n  2: unfold proj; autorewrite with eval_db; gridify; trivial.\n  replace (proj j (k + n) true) with (proj j k true ⊗ I (2 ^ n)).\n  2: unfold proj; autorewrite with eval_db; gridify; trivial.\n  restore_dims. \n  repeat rewrite kron_mixed_product.\n  Msimpl.\n  destruct (f j) eqn:fj.\n  rewrite (f_to_vec_proj_eq _ _ _ true) by auto.\n  rewrite (f_to_vec_proj_neq _ _ _ false); auto.\n  2: rewrite fj; easy.\n  Msimpl.\n  rewrite Rmult_1_l.\n  rewrite Heig.\n  distribute_scale.\n  reflexivity.\n  rewrite (f_to_vec_proj_eq _ _ _ false) by auto.\n  rewrite (f_to_vec_proj_neq _ _ _ true); auto.\n  2: rewrite fj; easy.\n  simpl. autorewrite with R_db Cexp_db.\n  Msimpl.\n  reflexivity. \n  apply map_qubits_fresh; auto.\n  apply uc_well_typed_map_qubits; auto.\nQed.\n\nLemma controlled_powers_var'_action_on_basis : \n  forall k kmax n (fc : nat -> base_ucom n) (ψ : Vector (2^n)) f θ,\n    (n > 0)%nat -> (k > 0)%nat -> (kmax >= k)%nat ->\n    (forall i, (i < k)%nat -> uc_well_typed (fc i)) ->\n    WF_Matrix ψ ->\n    (forall i, (i < k)%nat -> (uc_eval (fc i)) × ψ = Cexp (2 * PI * θ * (INR (2^i))) .* ψ) ->\n    @Mmult _ _ (1 * 1) (uc_eval (controlled_powers_var' (fun i => map_qubits (fun q => kmax + q)%nat (fc i)) k kmax)) ((f_to_vec kmax f) ⊗ ψ) =\n    Cexp (2 * PI * θ * INR (funbool_to_nat k (shift f (kmax - k)))) .* ((f_to_vec kmax f) ⊗ ψ).\nProof.\n  intros k kmax n fc ψ f θ Hn Hk Hkmax WT WF Heigen.\n  destruct k; try lia.\n  induction k.\n  - simpl.\n    rewrite <- (niter_1 (cast _ _)).\n    rewrite <- cast_niter_commute.\n    erewrite f_to_vec_controlled_U; try apply Heigen; auto.\n    2: lia.\n    rewrite Mscale_kron_dist_l.\n    apply f_equal2; try reflexivity.\n    unfold funbool_to_nat, shift; simpl.\n    rewrite Nat.add_0_r.\n    apply f_equal.\n    destruct (f (kmax - 1)%nat); simpl; lra.\n  - remember (S k) as k'.\n    simpl. subst. \n    Local Opaque controlled_powers_var' Nat.pow. \n    simpl uc_eval.\n    rewrite Mmult_assoc.\n    restore_dims.\n    assert (forall i : nat, (i < S k)%nat -> uc_well_typed (fc i)) by (intros; apply WT; lia).\n    assert (forall i : nat, (i < S k)%nat -> uc_eval (fc i) × ψ = Cexp (2 * PI * θ * INR (2 ^ i)) .* ψ) by (intros; apply Heigen; lia).\n    rewrite IHk by (try easy; lia). clear IHk.\n    distribute_scale.\n    erewrite f_to_vec_controlled_U_var; try apply Heigen; auto.\n    2,3,4: lia.\n    restore_dims. distribute_scale. \n    apply f_equal2; try reflexivity. \n    rewrite <- Cexp_add.\n    apply f_equal.\n    rewrite (funbool_to_nat_shift (S (S k)) _ (S O)) by lia.\n    replace (S (S k) - 1)%nat with (S k) by lia.\n    replace (shift (shift f (kmax - S (S k))) 1) with (shift f (kmax - S k)).\n    2: { unfold shift. apply functional_extensionality; intro x. \n         replace (x + 1 + (kmax - S (S k)))%nat with (x + (kmax - S k))%nat by lia.\n         reflexivity. }\n    rewrite plus_INR, mult_INR. repeat rewrite pow_INR. \n    unfold shift; simpl. \n    replace (1 + 1)%R with 2%R by lra.\n    replace (kmax - S (S k))%nat with (kmax - S k - 1)%nat by lia.\n    unfold funbool_to_nat; simpl.\n    field_simplify_eq. \n    destruct (f (kmax - S k - 1)%nat); simpl; lra.\nQed.\n\nLemma controlled_powers_var_action_on_basis : \n  forall k n (fc : nat -> base_ucom n) (ψ : Vector (2^n)) f θ,\n    (n > 0)%nat -> (k > 0)%nat ->\n    (forall i, (i < k)%nat -> uc_well_typed (fc i)) ->\n    WF_Matrix ψ ->\n    (forall i, (i < k)%nat -> (uc_eval (fc i)) × ψ = Cexp (2 * PI * θ * (INR (2^i))) .* ψ) ->\n    @Mmult _ _ (1 * 1) (uc_eval (controlled_powers_var (fun i => map_qubits (fun q => k + q)%nat (fc i)) k)) ((f_to_vec k f) ⊗ ψ) =\n    Cexp (2 * PI * θ * INR (funbool_to_nat k f)) .* ((f_to_vec k f) ⊗ ψ).\nProof.\n  intros k n c ψ f θ Hn Hk WT WF Heigen.\n  unfold controlled_powers_var.\n  erewrite controlled_powers_var'_action_on_basis; try apply Heigen; auto.\n  replace (k - k)%nat with O by lia.\n  rewrite shift_0.\n  reflexivity.\nQed.\n\nLemma QPE_var_equivalent :\n  forall k n (c : base_ucom n) (f : nat -> base_ucom n) (ψ : Vector (2^n)) θ,\n    (n > 0)%nat ->\n    WF_Matrix ψ ->\n    uc_well_typed c ->\n    (uc_eval c) × ψ = Cexp (2 * PI * θ) .* ψ ->\n    (forall i, (i < k)%nat -> uc_well_typed (f i)) ->\n    (forall i, (i < k)%nat -> (uc_eval (f i)) × ψ = Cexp (2 * PI * θ * (INR (2^i))) .* ψ) ->\n    @Mmult _ _ (1 * 1) (uc_eval (QPE k n c)) (k ⨂ qubit0 ⊗ ψ) = @Mmult _ _ (1 * 1) (uc_eval (QPE_var k n f)) (k ⨂ qubit0 ⊗ ψ).\nProof.\n  assert (G: forall {n} (A B : base_ucom n), uc_eval (A; B) = uc_eval B × uc_eval A) by intuition.\n  intros k n c0 f0.\n  intros.\n  unfold QPE, QPE_var.\n  repeat rewrite G.\n  repeat rewrite Mmult_assoc.\n  bdestruct (k <=? 0). assert (k = O) by lia. subst. easy.\n  rewrite <- pad_dims_r with (c := npar k U_H) by (apply npar_WT; lia).\n  rewrite npar_H by lia.\n  replace (2 ^ (k + n))%nat with (2 ^ k * 2 ^ n)%nat by unify_pows_two. \n  replace (1 * 1)%nat with (1 ^ k * 1)%nat.\n  2: rewrite Nat.pow_1_l; reflexivity.\n  rewrite kron_mixed_product.\n  Msimpl.\n  rewrite H0_kron_n_spec_alt by lia.\n  restore_dims. distribute_scale.\n  rewrite kron_Msum_distr_r.\n  replace (2 ^ (k + n))%nat with (2 ^ k * 2 ^ n)%nat by unify_pows_two. \n  rewrite Mmult_Msum_distr_l.\n  rewrite Mmult_Msum_distr_l with (f := (fun i : nat => basis_vector (2 ^ k) i ⊗ ψ)).\n  do 2 apply f_equal.\n  apply big_sum_eq_bounded. intros.\n  rewrite basis_f_to_vec_alt by easy.\n  restore_dims.\n  rewrite controlled_powers_action_on_basis with (θ := θ) by (try easy; try lia).\n  rewrite controlled_powers_var_action_on_basis with (θ := θ); try easy; try lia.\nQed.\n\nLocal Transparent controlled_powers_var' SKIP ID.\nLemma controlled_powers_var_WT : forall n (f : nat -> base_ucom n) k,\n  (k > 0)%nat -> \n  (forall i, uc_well_typed (f i)) ->\n  uc_well_typed (controlled_powers_var \n                  (fun x : nat => map_qubits (fun q : nat => (k + q)%nat) (f x)) k).\nProof.\n  intros n f k Hk WT.\n  unfold controlled_powers_var.\n  assert (forall kmax, (kmax >= k)%nat -> \n    uc_well_typed (controlled_powers_var' \n                    (fun x : nat => map_qubits (fun q : nat => (kmax + q)%nat) (f x)) k kmax)).\n  { intros kmax Hkmax.\n    induction k. lia.\n    simpl. destruct k. \n    rewrite cast_control_commute.\n    apply uc_well_typed_control.\n    split; [| split].\n    lia.\n    apply map_qubits_fresh. lia.\n    apply uc_well_typed_map_qubits.\n    apply WT.\n    constructor.\n    apply IHk. lia. lia.\n    rewrite cast_control_commute.\n    apply uc_well_typed_control.\n    split; [| split].\n    lia.\n    apply map_qubits_fresh. lia.\n    apply uc_well_typed_map_qubits.\n    apply WT. }\n  apply H. lia.\nQed.\n\nLemma QPE_var_WT : forall k n (f : nat -> base_ucom n),\n  (k > 0)%nat -> \n  (forall i, uc_well_typed (f i)) ->\n  uc_well_typed (QPE_var k n f).\nProof.\n  intros k n f Hk WT.\n  unfold QPE_var.\n  constructor. constructor.\n  apply typed_cast.\n  apply npar_WT.\n  auto. lia.\n  apply controlled_powers_var_WT; auto.\n  apply typed_cast.\n  rewrite <- uc_well_typed_invert.\n  apply QFT_w_reverse_WT.\n  auto. lia.\nQed.\n", "meta": {"author": "inQWIRE", "repo": "SQIR", "sha": "7d2938bf63080e37d47059befa27a57f12cc099c", "save_path": "github-repos/coq/inQWIRE-SQIR", "path": "github-repos/coq/inQWIRE-SQIR/SQIR-7d2938bf63080e37d47059befa27a57f12cc099c/examples/examples/QPE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245911726382, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6753920071291064}}
{"text": "Require Import ZArith.\n\nRequire Import Statement ImprovedPredicative Wpr.\n\nRequire Import Lia.\n\nOpen Scope stmt_scope.\n\nDefinition spec := ⟨fun '(i,n) '(i',n') => i <= n /\\ i' = n /\\ n = n'⟩.\n\nDefinition prog := WWhile (fun '(i,n) => i <> n) Do $(i,n) := (i+1,n) Done.\n\n\nTheorem correctness : prog ⊑ spec.\nProof.\n  intros (i,n) ((u,v),(HHin,_)); clear u v.\n  set (K := wpr prog (pred spec)).\n  generalize i HHin; clear i HHin.\n  induction n; intros i HHin.\n  { apply wpr_while_construct; right; simpl. lia. }\n  { apply Lt.le_lt_or_eq in HHin.\n    destruct HHin as [ HHin | HHin ].\n    { assert (i <= n) as HHin' by lia. \n      cut ((fun '(i,n) '(i',n') => i' <= n' /\\ K (i,S n) (i',S n')) (i, n) (i, n)).\n      { intros (HH1,HH2); auto. }\n      { apply (IHn _ HHin'); clear i n HHin HHin' IHn.\n        intros (i,n) (i',n'). intros [ (HHin,(HHi'n',HHind)) | HH ]; split; try lia.\n        { apply wpr_while_construct; left; split; auto. lia. }\n        { simpl in HH; apply wpr_while_construct; left; split; try lia; fold prog K.\n          apply wpr_while_construct; right; simpl. lia.\n        }\n      }\n    }\n    { apply wpr_while_construct; right; simpl. lia. }\n  }\nQed.\n\n\n", "meta": {"author": "bsall", "repo": "thesis-dev", "sha": "88761620d621b3435e2e4e6e8ce616b24836506f", "save_path": "github-repos/coq/bsall-thesis-dev", "path": "github-repos/coq/bsall-thesis-dev/thesis-dev-88761620d621b3435e2e4e6e8ce616b24836506f/src/examples/Wpr_Count.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6753618477527474}}
{"text": "\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n(* Requires No helper lemma *)\nTheorem theorem0 : forall (x : natural) (y : natural), eq (plus x (Succ (Succ y))) (Succ (Succ (plus x y))).\nProof.\n   intros.\n  induction x.\n  - simpl. rewrite IHx. reflexivity.\n  - reflexivity.\nQed.\n\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal67.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6753618425231455}}
{"text": "Require Export TopologicalSpaces.\nRequire Export Subbases.\nRequire Export Continuity.\nRequire Export Nets.\nFrom ZornsLemma Require Export InverseImage.\nFrom ZornsLemma Require Import FiniteIntersections.\n\n(* Also called \"initial topology\". Its construction is dual\n   (in the categorical sense) to the construction of the strong topology. *)\n\nSection WeakTopology.\n\nVariable X:Type.\nVariable A:Type.\nVariable Y:A->TopologicalSpace.\nVariable f:forall a:A, X->point_set (Y a).\n\nInductive weak_topology_subbasis : Family X :=\n  | intro_fa_inv_image: forall (a:A) (V:Ensemble (point_set (Y a))),\n    open V -> In weak_topology_subbasis (inverse_image (f a) V).\n\nDefinition WeakTopology : TopologicalSpace :=\n  Build_TopologicalSpace_from_subbasis X weak_topology_subbasis.\n\nLemma weak_topology_makes_continuous_funcs:\n  forall a:A, continuous (f a) (X:=WeakTopology).\nProof.\nintro.\nred; intros.\npose proof (Build_TopologicalSpace_from_subbasis_subbasis\n  _ weak_topology_subbasis).\napply H0.\nconstructor; trivial.\nQed.\n\nLemma weak_topology_is_weakest: forall (T':Family X)\n  (H1:_) (H2:_) (H3:_),\n  (forall a:A, continuous (f a)\n     (X := Build_TopologicalSpace X T' H1 H2 H3)) ->\n  forall U:Ensemble X, @open WeakTopology U -> T' U.\nProof.\nintros.\ndestruct H0.\napply H1.\nintros.\napply H0 in H4.\ninduction H4.\n- exact H3.\n- destruct H4.\n  apply H; trivial.\n- apply H2; trivial.\nQed.\n\nLemma weak_topology_continuous_char (W : TopologicalSpace)\n      (g : (point_set W) -> (point_set (WeakTopology))) :\n      continuous g <-> (forall a, continuous (compose (f a) g)).\nProof.\nsplit.\n- intros.\n  unfold compose. apply continuous_composition.\n  + apply weak_topology_makes_continuous_funcs.\n  + assumption.\n- intros.\n  apply continuous_subbasis with weak_topology_subbasis.\n  { apply Build_TopologicalSpace_from_subbasis_subbasis. }\n  intros. induction H0.\n  rewrite <- inverse_image_composition.\n  apply H. assumption.\nQed.\n\nSection WeakTopology_and_Nets.\n\nVariable I:DirectedSet.\nHypothesis I_nonempty: inhabited (DS_set I).\nVariable x:Net I WeakTopology.\nVariable x0:X.\n\nLemma net_limit_in_weak_topology_impl_net_limit_in_projections :\n  net_limit x x0 ->\n  forall a:A, net_limit (fun i:DS_set I => (f a) (x i)) ((f a) x0).\nProof.\nintros.\napply continuous_func_preserves_net_limits; trivial.\napply continuous_func_continuous_everywhere.\napply weak_topology_makes_continuous_funcs.\nQed.\n\nLemma net_limit_in_projections_impl_net_limit_in_weak_topology :\n  (forall a:A, net_limit (fun i:DS_set I => (f a) (x i))\n                         ((f a) x0)) ->\n  net_limit x x0.\nProof.\nintros.\nred; intros.\nassert (@open_basis WeakTopology\n        (finite_intersections weak_topology_subbasis)).\n{ apply Build_TopologicalSpace_from_open_basis_basis. }\ndestruct (open_basis_cover _ H2 x0 U) as [V [? [? ?]]]; trivial.\nassert (for large i:DS_set I, In V (x i)).\n{ clear H4.\n  induction H3.\n  - destruct I_nonempty.\n    exists X0; constructor.\n  - destruct H3.\n    destruct H5.\n    apply eventually_impl_base with (fun i:DS_set I => In V (f a (x i))).\n    + intros.\n      constructor; trivial.\n    + apply H; trivial.\n  - apply eventually_impl_base with\n        (fun i:DS_set I => In U0 (x i) /\\ In V (x i)).\n    + intros.\n      destruct H6.\n      constructor; trivial.\n    + destruct H5.\n      apply eventually_and;\n        (apply IHfinite_intersections || apply IHfinite_intersections0);\n        trivial.\n}\nrefine (eventually_impl_base _ _ _ H6).\nintro; apply H4.\nQed.\n\nEnd WeakTopology_and_Nets.\n\nEnd WeakTopology.\n\nArguments WeakTopology {X} {A} {Y}.\nArguments weak_topology_subbasis {X} {A} {Y}.\n\nRequire Import ClassicalChoice.\n\nSection WeakTopology1.\n\nVariable X:Type.\nVariable Y:TopologicalSpace.\nVariable f:X->point_set Y.\n\nDefinition WeakTopology1 := WeakTopology (True_rect f).\n\nLemma weak_topology1_makes_continuous_func:\n  continuous f (X:=WeakTopology1).\nProof.\nexact (weak_topology_makes_continuous_funcs _ _ _ (True_rect f) I).\nQed.\n\nLemma weak_topology1_topology:\n  forall U:Ensemble X, @open WeakTopology1 U <->\n  exists V:Ensemble (point_set Y), open V /\\ U = inverse_image f V.\nProof.\nsplit.\n2: {\n  intros.\n  destruct H as [V []].\n  subst.\n  apply weak_topology1_makes_continuous_func.\n  assumption.\n}\nintros.\nred in H.\nsimpl in H.\ndestruct H.\nassert (forall U:Ensemble X,\n  In (finite_intersections (weak_topology_subbasis (True_rect f))) U ->\n  exists V:Ensemble (point_set Y), open V /\\ U = inverse_image f V).\n{ intros.\n  induction H0.\n  - exists Full_set.\n    split.\n    + apply open_full.\n    + symmetry. apply inverse_image_full.\n  - destruct H0.\n    destruct a.\n    simpl.\n    exists V.\n    split; trivial.\n  - destruct IHfinite_intersections as [V1 [? ?]].\n    destruct IHfinite_intersections0 as [V2 [? ?]].\n    exists (Intersection V1 V2).\n    split.\n    + auto with topology.\n    + rewrite H3; rewrite H5.\n      rewrite inverse_image_intersection.\n      trivial.\n}\ndestruct (choice (fun (U:{U:Ensemble X | In F U}) (V:Ensemble (point_set Y))\n  => open V /\\ proj1_sig U = inverse_image f V)) as [choice_fun].\n{ intros.\n  destruct x as [U].\n  simpl.\n  apply H0; auto with sets.\n}\nexists (IndexedUnion choice_fun).\nsplit.\n{ apply open_indexed_union.\n  apply H1.\n}\napply Extensionality_Ensembles; split; red; intros.\n- destruct H2.\n  constructor.\n  exists (exist _ S H2).\n  pose proof (H1 (exist _ S H2)).\n  destruct H4.\n  simpl in H5.\n  rewrite H5 in H3.\n  destruct H3.\n  exact H3.\n- destruct H2.\n  inversion H2.\n  pose proof (H1 a).\n  destruct H5.\n  destruct a as [U].\n  exists U; trivial.\n  simpl in H6.\n  rewrite H6.\n  constructor.\n  exact H3.\nQed.\n\nLemma weak_topology1_topology_closed:\n  forall U:Ensemble X, @closed WeakTopology1 U <->\n  exists V:Ensemble (point_set Y), closed V /\\ U = inverse_image f V.\nProof.\nunfold closed.\nsplit.\n- intros. unfold closed in *.\n  rewrite weak_topology1_topology in H.\n  destruct H as [V []].\n  exists (Complement V).\n  rewrite inverse_image_complement.\n  rewrite <- H0.\n  rewrite !Complement_Complement.\n  auto.\n- intros. destruct H as [V []].\n  subst. apply continuous_closed; try assumption.\n  apply weak_topology1_makes_continuous_func.\nQed.\n\nLemma weak_topology1_continuous_char (Z : TopologicalSpace)\n      (g : Z -> WeakTopology1) :\n  continuous g <->\n  continuous (compose f g).\nProof.\n  replace f with (True_rect f I).\n  2: { reflexivity. }\n  unfold WeakTopology1.\n  rewrite weak_topology_continuous_char.\n  split; intros; auto.\n  destruct a. assumption.\nQed.\n\nEnd WeakTopology1.\n\nArguments WeakTopology1 {X} {Y}.\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/WeakTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6753389291167667}}
{"text": "Require Export FunctionProperties.\nRequire Import DecidableDec.\nRequire Import Description.\nRequire Import Classical.\n\n(* CSB = Cantor-Schroeder-Bernstein theorem *)\n\nSection CSB.\nVariable X Y:Type.\nVariable f:X->Y.\nVariable g:Y->X.\nHypothesis f_inj: injective f.\nHypothesis g_inj: injective g.\n\nInductive X_even: X->Prop :=\n  | not_g_img: forall x:X, (forall y:Y, g y <> x) -> X_even x\n  | g_Y_odd: forall y:Y, Y_odd y -> X_even (g y)\nwith Y_odd: Y->Prop :=\n  | f_X_even: forall x:X, X_even x -> Y_odd (f x).\nInductive X_odd: X->Prop :=\n  | g_Y_even: forall y:Y, Y_even y -> X_odd (g y)\nwith Y_even: Y->Prop :=\n  | not_f_img: forall y:Y, (forall x:X, f x <> y) -> Y_even y\n  | f_X_odd: forall x:X, X_odd x -> Y_even (f x).\n\nScheme X_even_coind := Minimality for X_even Sort Prop\n  with Y_odd_coind := Minimality for Y_odd Sort Prop.\nScheme X_odd_coind := Minimality for X_odd Sort Prop\n  with Y_even_coind := Minimality for Y_even Sort Prop.\n\nLemma even_odd_excl: forall x:X, ~(X_even x /\\ X_odd x).\nProof.\nintro.\nassert (X_even x -> ~ X_odd x).\n2:tauto.\npose proof (X_even_coind (fun x:X => ~ X_odd x) (fun y:Y => ~ Y_even y)).\napply H.\nintuition.\ndestruct H1.\napply H0 with y.\nreflexivity.\nintuition.\ninversion H2.\napply g_inj in H3.\napply H1.\nrewrite <- H3.\nassumption.\nintuition.\ninversion H2.\napply H3 with x0.\nreflexivity.\napply f_inj in H3.\napply H1.\nrewrite <- H3.\nassumption.\nQed.\n\nLemma even_odd_excl2: forall y:Y, ~(Y_even y /\\ Y_odd y).\nProof.\nintro.\nassert (Y_odd y -> ~ Y_even y).\n2:tauto.\npose proof (Y_odd_coind (fun x:X => ~ X_odd x) (fun y:Y => ~ Y_even y)).\napply H.\nintuition.\ndestruct H1.\napply H0 with y0.\nreflexivity.\nintuition.\ninversion H2.\napply g_inj in H3.\napply H1.\nrewrite <- H3.\nassumption.\nintuition.\ninversion H2.\napply H3 with x.\nreflexivity.\napply f_inj in H3.\napply H1.\nrewrite <- H3.\nassumption.\nQed.\n\nDefinition finv: forall y:Y, (exists x:X, f x = y) ->\n  { x:X | f x = y }.\nintros.\napply constructive_definite_description.\ndestruct H.\nexists x.\nred; split.\nassumption.\nintros.\napply f_inj.\ntransitivity y; trivial.\nsymmetry; trivial.\nDefined.\n\nDefinition ginv: forall x:X, (exists y:Y, g y = x) ->\n  { y:Y | g y = x }.\nintros.\napply constructive_definite_description.\ndestruct H.\nexists x0.\nred; split.\nassumption.\nintros.\napply g_inj.\ntransitivity x; trivial; symmetry; trivial.\nDefined.\n\nDefinition ginv_odd: forall x:X, X_odd x ->\n  { y:Y | g y = x }.\nintros.\napply ginv.\ndestruct H.\nexists y.\nreflexivity.\nDefined.\n\nDefinition finv_noteven: forall y:Y, ~ Y_even y ->\n  { x:X | f x = y }.\nintros.\napply finv.\napply NNPP.\nred; intro.\ncontradict H.\nconstructor 1.\nintro; red; intro.\napply H0.\nexists x.\nassumption.\nDefined.\n\nDefinition CSB_bijection (x:X) : Y :=\n  match (classic_dec (X_odd x)) with\n  | left o => proj1_sig (ginv_odd x o)\n  | right _ => f x\n  end.\nDefinition CSB_bijection2 (y:Y) : X :=\n  match (classic_dec (Y_even y)) with\n  | left _ => g y\n  | right ne => proj1_sig (finv_noteven y ne)\n  end.\n\nLemma CSB_comp1: forall x:X, CSB_bijection2 (CSB_bijection x) = x.\nProof.\nintro.\nunfold CSB_bijection; case (classic_dec (X_odd x)).\nintro.\ndestruct ginv_odd.\nsimpl.\nunfold CSB_bijection2; case (classic_dec (Y_even x1)).\nintro.\nassumption.\nintro.\ndestruct x0.\ncontradict n.\napply g_inj in e.\nrewrite e.\nassumption.\nintro.\nunfold CSB_bijection2; case (classic_dec (Y_even (f x))).\nintro.\ncontradict n.\ninversion y.\npose proof (H x).\ncontradict H1; reflexivity.\napply f_inj in H.\nrewrite <- H.\nassumption.\nintro.\ndestruct finv_noteven.\nsimpl.\napply f_inj.\nassumption.\nQed.\n\nLemma CSB_comp2: forall y:Y, CSB_bijection (CSB_bijection2 y) = y.\nProof.\nintro.\nunfold CSB_bijection2; case (classic_dec (Y_even y)).\nintro.\nunfold CSB_bijection; case (classic_dec (X_odd (g y))).\nintro.\ndestruct ginv_odd.\nsimpl.\napply g_inj.\nassumption.\nintro.\ncontradict n.\nconstructor.\nassumption.\nintro.\ndestruct finv_noteven.\nsimpl.\nunfold CSB_bijection; case (classic_dec (X_odd x)).\nintro.\ncontradict n.\nrewrite <- e.\nconstructor 2.\nassumption.\ntrivial.\nQed.\n\nTheorem CSB: exists h:X->Y, bijective h.\nProof.\nexists CSB_bijection.\napply invertible_impl_bijective.\nexists CSB_bijection2.\nexact CSB_comp1.\nexact CSB_comp2.\nQed.\n\nEnd CSB.\n", "meta": {"author": "dschepler", "repo": "coq-zorns-lemma", "sha": "4ad354c50f73758c094f43da5fc0f2c6dd8e3da2", "save_path": "github-repos/coq/dschepler-coq-zorns-lemma", "path": "github-repos/coq/dschepler-coq-zorns-lemma/coq-zorns-lemma-4ad354c50f73758c094f43da5fc0f2c6dd8e3da2/CSB.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.675338920152343}}
{"text": "Require Import Coq.Arith.PeanoNat.\nRequire Import Coq.Classes.RelationClasses.\nRequire Export Coq.Lists.List.\nRequire Import Coq.Sets.Multiset.\nRequire Export Coq.Sorting.Permutation.\nRequire Import Coq.Sorting.PermutSetoid.\nRequire Import Coq.Sorting.PermutEq.\nRequire Import Omega.\n\nOpaque Nat.eq_dec.\n\n(** Refer to README.md for documentation. *)\n\n(** (foreverbell): generalize to all decidable instances. *)\n\nLemma list_contents_app_multiplicity_plus :\n  forall (a : nat) (l m : list nat),\n    multiplicity (list_contents eq Nat.eq_dec (l ++ m)) a =\n    multiplicity (list_contents eq Nat.eq_dec l) a +\n    multiplicity (list_contents eq Nat.eq_dec m) a.\nProof.\n  intros; specialize (list_contents_app eq Nat.eq_dec l m).\n  intros. unfold meq, munion in H.\n  specialize (H a); auto.\nQed.\n\nLtac permutation_simplify a (* variable for functional extensionality *) :=\n  repeat\n    match goal with\n    | [ H : Permutation _ _ |- _ ] =>\n        rewrite (permutation_Permutation Nat.eq_dec) in H;\n        unfold permutation, meq in H;\n        specialize (H a);\n        repeat (\n          simpl list_contents in H;\n          unfold munion in H;\n          simpl multiplicity in H;\n          try rewrite list_contents_app_multiplicity_plus in H\n        )\n    | [ |- Permutation _ _ ] =>\n        rewrite (permutation_Permutation Nat.eq_dec);\n        unfold permutation, meq;\n        intros a;\n        repeat (\n          simpl list_contents;\n          unfold munion;\n          simpl multiplicity;\n          try rewrite list_contents_app_multiplicity_plus\n        )\n    end.\n\nLtac permutation_solver :=\n  let a := fresh \"a\" in permutation_simplify a;\n  repeat\n    match goal with\n    | [ |- context [if ?A then _ else _] ] => destruct A\n    end; omega.\n", "meta": {"author": "foreverbell", "repo": "permutation-solver", "sha": "bd0147489134e046418cb9e7d35ae0df12e171d3", "save_path": "github-repos/coq/foreverbell-permutation-solver", "path": "github-repos/coq/foreverbell-permutation-solver/permutation-solver-bd0147489134e046418cb9e7d35ae0df12e171d3/PermutationSolver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6753389183102111}}
{"text": "(*common header begin*)\nRequire Import Utf8.\nFrom Coq Require Import ssreflect ssrfun ssrbool.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Maximal Implicit Insertion.\n\nRequire Import List.\nImport ListNotations.\n(*common header end*)\n\nRequire Import PeanoNat.\nRequire Import Omega.\n\nRequire Import ListFacts.\nRequire Import UserTactics.\n\n\n(*HintDb containing lemmas regarding the last element of seq*)\nCreate HintDb seq.\n\nLemma seq_last : forall (start length : nat), \n  seq start (S length) = (seq start length) ++ [start + length].\nProof.\nmove => start length.\nelim : length start.\nintros; cbn; f_equal; omega.\n\nmove => length IH start; cbn.\nf_equal.\nhave : start + S length = (S start) + length by omega.\nmove => ->.\napply : IH.\nQed.\n\nLemma repeat_last : forall (T : Type) (a : T) (length : nat), \n  repeat a (S length) = (repeat a length) ++ [a].\nProof.\nmove => T a length.\nelim : length => //.\n\nmove => length IH; cbn.\nf_equal.\nauto.\nQed.\n\n\nLemma map_singleton (T U : Type) : forall (f : T -> U) (a : T), map f [a] = [f a].\nProof. reflexivity. Qed.\n\nLemma Forall_app_singleton : forall (T : Type) (P : T -> Prop) (l : list T) (a : T), \n  Forall P (l ++ [a]) <-> Forall P l /\\ (P a).\nProof.\nintros *.\nsplit.\nmove /Forall_app.\nintuition.\ngimme Forall; by inversion.\n\nrewrite ? Forall_forall.\nintuition.\ngimme In; rewrite ? in_app_iff.\nintuition.\ngimme In; inversion; done.\nQed.\n\nHint Rewrite seq_last : seq.\nHint Rewrite @repeat_last : seq.\nHint Rewrite map_app : seq.\nHint Rewrite @map_singleton : seq.\nHint Rewrite plus_O_n plus_n_O : seq.\nHint Rewrite @Forall_app_singleton : seq.\nHint Rewrite <- plus_n_O : seq.\n\n(*list of pars of list elements along with their index starting with start*)\nFixpoint indexed (T : Type) (start : nat) (l : list T) :=\n  match l with\n  | nil => nil\n  | (cons a l) => cons (start, a) (indexed (S start) l)\n  end.\n\n\nLemma indexed_app : forall (v w : list nat) (n : nat), indexed n (v ++ w) = (indexed n v) ++ (indexed (length v+n) w).\nProof.\nelim; cbn; first done.\nmove => a v IH w n.\nhave : S (length v + n) = length v + (S n) by omega.\nmove => ->.\nf_equal; eauto.\nQed.\n\nHint Rewrite @indexed_app : seq.\n\nLemma in_indexed_in : forall (T : Type) (l : list T) (i n : nat) (a : T), In (i, a) (indexed n l) -> In a l.\nProof.\nmove => T.\nelim; cbn; first done.\nmove => b l IH i n a.\ncase; first case; eauto.\nQed.\n\nLemma in_indexed_bounds : forall (T : Type) (l : list T) (i n : nat) (a : T), In (i, a) (indexed n l) -> n <= i /\\ i < n + length l.\nProof.\nmove => T.\nelim; cbn; first done.\nmove => b l IH i n a.\ncase; first case.\nintros; omega.\nmove /IH.\ncase; intros; omega.\nQed.\n\nLemma in_indexed_eq : forall (T : Type) (l : list T) (i n : nat) (a b : T), In (i, a) (indexed n l) -> In (i, b) (indexed n l) -> a = b.\nProof.\nmove => T.\nelim; cbn; first done.\nmove => c l IH i n a b.\ncase.\ncase=> ? ?.\ncase.\ncase=> ? ?; congruence.\nsubst.\nmove /in_indexed_bounds; intros; omega.\nmove => ?.\ncase.\ncase => ? ?; subst.\ngimme In.\nmove /in_indexed_bounds; intros; omega.\neauto.\nQed.\n\nLemma in_in_indexed : forall (T : Type)  (a : T) (l : list T) (n : nat), In a l -> exists (i : nat), In (i, a) (indexed n l).\nProof.\nmove => T a.\nelim => //.\nmove => b l IH n; cbn.\ncase.\nintro; subst; exists n; by left.\nmove /IH; move /(_ (S n)). firstorder.\nQed.", "meta": {"author": "mrhaandi", "repo": "lambda-cap", "sha": "3b08f0d5d693355b967d26f7560890da030458c8", "save_path": "github-repos/coq/mrhaandi-lambda-cap", "path": "github-repos/coq/mrhaandi-lambda-cap/lambda-cap-3b08f0d5d693355b967d26f7560890da030458c8/Seq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.6752200826195197}}
{"text": "(* Copyright (c) 2014, Robert Dockins *)\n\nRequire Import basics.\nRequire Import preord.\nRequire Import categories.\nRequire Import sets.\nRequire Import finsets.\nRequire Import esets.\n\nRequire Import NArith.\n\n(**  * Effective preorders.\n\n       We define the notion of \"effective\" preorders: those\n       for which the order relation is decidable and the\n       members of the preorder are enumerable.\n  *)\n\nRecord effective_order (A:preord) :=\n  EffectiveOrder\n  { eff_ord_dec : forall x y:A, {x ≤ y} + {x ≰ y}\n  ; eff_enum : eset A\n  ; eff_complete : forall x:A, x ∈ eff_enum\n  }.\n\n\n(**  Effective orders have a decidable equality.\n  *)\nCanonical Structure eff_to_ord_dec A (Heff:effective_order A) : ord_dec A :=\n  OrdDec A (eff_ord_dec A Heff).\nCoercion eff_to_ord_dec : effective_order >-> ord_dec.\n\n\n(**  The positive integers form an effective preorder.\n  *)\nProgram Definition Ndisc_ord : preord :=\n  Preord.Pack N (Preord.Mixin N (@eq N) _ _).\nSolve Obligations of Ndisc_ord using intros; subst; auto.\nCanonical Structure Ndisc_ord.\n\nProgram Definition effective_Nord : effective_order Ndisc_ord\n  := EffectiveOrder Ndisc_ord _ (fun n => Some n) _.\nNext Obligation.\n  simpl. unfold Preord.ord_op. simpl.\n  apply N_eq_dec.\nQed.\nNext Obligation.\n  intros. exists x. auto.\nQed.\n\n\n(**  Given an effective preorder, we can calculate a canonical\n     index value for any given element of the preorder.\n\n     We do this by first generating the subset of the enumeration set\n     containing all elements equal to [x]; then we choose the smallest\n     index from that set that is defined.  Such an element exists\n     because we know the set is inhabited.  The weak principle of countable\n     choice then suffices to choose the index.\n  *)\n\nDefinition unenumerate_set (A:preord) (Heff:effective_order A) (x:A) \n  : eset A :=\n  fun n => \n    match eff_enum A Heff n with\n    | Some x' => \n        if PREORD_EQ_DEC A (eff_to_ord_dec A Heff) x x' \n           then Some x'\n           else None\n    | None => None\n    end.\n\nLemma unenumerate_set_inhabited A Heff x :\n  einhabited (unenumerate_set A Heff x).\nProof.\n  apply member_inhabited.\n  generalize (eff_complete A Heff x).\n  intros [n ?].\n  case_eq (eff_enum A Heff n); intros.\n  rewrite H0 in H.\n  exists c. exists n.\n  unfold unenumerate_set. rewrite H0.\n  destruct (PREORD_EQ_DEC A (eff_to_ord_dec A Heff) x c); auto.\n  rewrite H0 in H. elim H.\nQed.\n  \nDefinition unenumerate (A:preord) (Heff:effective_order A) (x:A) : N :=\n  proj1_sig (projT2\n    (find_inhabitant A\n      (unenumerate_set A Heff x)\n      (unenumerate_set_inhabited A Heff x))).\n  \nLemma unenumerate_correct A Heff x :\n  exists x', eff_enum A Heff (unenumerate A Heff x) = Some x' /\\ x ≈ x'.\nProof.\n  unfold unenumerate. \n  destruct (find_inhabitant A\n               (unenumerate_set A Heff x)\n               (unenumerate_set_inhabited A Heff x)); simpl.\n  destruct s as [n ?].\n  destruct a. simpl.\n  case_eq (eff_enum A Heff n); intros.\n  unfold unenumerate_set in e.\n  rewrite H in e.\n  destruct ((PREORD_EQ_DEC A (eff_to_ord_dec A Heff)) x c).\n  inversion e. subst x0.\n  exists c. split; auto.\n  discriminate.\n  unfold unenumerate_set in e.\n  rewrite H in e. discriminate.\nQed.\n\n(**  The unenumeration index is unique (up to Leibniz equality)\n     and equal indexes imply equal elements.\n  *)\nLemma unenumerate_uniq A Heff x x' :\n  x ≈ x' ->\n  unenumerate A Heff x = unenumerate A Heff x'.\nProof.\n  intros.\n  unfold unenumerate. \n  destruct (find_inhabitant A\n               (unenumerate_set A Heff x)\n               (unenumerate_set_inhabited A Heff x)); simpl.\n  destruct (find_inhabitant A\n               (unenumerate_set A Heff x')\n               (unenumerate_set_inhabited A Heff x')); simpl.\n  destruct s as [n [??]].\n  destruct s0 as [n' [??]].\n  simpl.\n  unfold unenumerate_set in e.\n  case_eq (eff_enum A Heff n); intros.\n  rewrite H0 in e.\n  destruct (PREORD_EQ_DEC A (eff_to_ord_dec A Heff) x c).\n  inversion e; subst x0. clear e.\n  unfold unenumerate_set in e0.\n  case_eq (eff_enum A Heff n'); intros.\n  rewrite H1 in e0.\n  destruct (PREORD_EQ_DEC A (eff_to_ord_dec A Heff) x' c0).\n  inversion e0; subst x1. clear e0.\n  apply N.le_antisymm.\n  apply l with c0; auto.\n  unfold unenumerate_set.\n  rewrite H1.\n  destruct (PREORD_EQ_DEC A (eff_to_ord_dec A Heff) x c0). auto.\n  elim n0. rewrite H; auto.\n  apply l0 with c; auto.\n  unfold unenumerate_set.\n  rewrite H0.\n  destruct (PREORD_EQ_DEC A (eff_to_ord_dec A Heff) x' c). auto.\n  elim n0. rewrite <- H; auto.\n  discriminate.\n  rewrite H1 in e0. discriminate.\n  discriminate.\n  rewrite H0 in e. discriminate.\nQed.\n\nLemma unenumerate_reflects A Heff x x' :\n  unenumerate A Heff x = unenumerate A Heff x' ->\n  x ≈ x'.\nProof.\n  intros.\n  unfold unenumerate in *.\n  destruct (find_inhabitant A\n               (unenumerate_set A Heff x)\n               (unenumerate_set_inhabited A Heff x)); simpl in *.\n  destruct (find_inhabitant A\n               (unenumerate_set A Heff x')\n               (unenumerate_set_inhabited A Heff x')); simpl in *.\n  destruct s as [n [??]].\n  destruct s0 as [m [??]].\n  simpl in *.\n  subst m.\n  unfold unenumerate_set in e.\n  unfold unenumerate_set in e0.\n  case_eq (eff_enum A Heff n); intros.\n  rewrite H in e, e0.\n  destruct (PREORD_EQ_DEC A (eff_to_ord_dec A Heff) x c).\n  inversion e; subst x0.\n  destruct (PREORD_EQ_DEC A (eff_to_ord_dec A Heff) x' c).\n  inversion e0; subst x1.\n  rewrite e1; auto.\n  discriminate.\n  discriminate.\n  rewrite H in e. discriminate.\nQed.\n\nLemma eff_in_dec : forall {A:preord} (Heff:effective_order A) (M:finset A) (x:A),\n  { x ∈ M } + { x ∉ M }.\nProof.\n  intros. apply finset_in_dec.\n  apply eff_to_ord_dec. auto.\nQed.\n\n(** The one-point preorder is effective. *)\nProgram Definition effective_unit : effective_order unitpo\n   := EffectiveOrder unitpo (fun _ _ => left I) (single tt) _.\nNext Obligation.\n  intro. apply single_axiom. destruct x; auto.\nQed.\n\n\n(** The empty preorder is effective. *)\nProgram Definition effective_empty : effective_order emptypo :=\n  EffectiveOrder _ _ (fun x => None) _.\nNext Obligation.\n  intros. elim x.\nQed.\nNext Obligation.\n  intros. elim x.\nQed.\n\n\n(** The binary product of effective preorders is effective. *)\nProgram Definition effective_prod {A B:preord}\n  (HA:effective_order A)\n  (HB:effective_order B)\n  : effective_order (A×B)\n  := EffectiveOrder _ _ (eprod (eff_enum A HA) (eff_enum B HB)) _.\nNext Obligation.\n  intros. destruct x; destruct y.\n  destruct (eff_ord_dec A HA c c1).\n  destruct (eff_ord_dec B HB c0 c2).\n  left. split; auto.\n  right. intros [??]; apply n; auto.\n  right. intros [??]; apply n; auto.\nQed.\nNext Obligation.\n  intros.\n  destruct x as [a b].\n  apply eprod_elem.\n  split; apply eff_complete.\nQed.\n\n(** The binary sum of effective preorders is effective. *)\nProgram Definition effective_sum {A B:preord}\n  (HA:effective_order A)\n  (HB:effective_order B)\n  : effective_order (sum_preord A B)\n  := EffectiveOrder _ _ (esum (eff_enum A HA) (eff_enum B HB)) _.\nNext Obligation.\n  intros.\n  destruct x; destruct y.\n  destruct (eff_ord_dec A HA c c0).\n  left. auto.\n  right. auto.\n  right. intro. elim H.\n  right. intro. elim H.\n  destruct (eff_ord_dec B HB c c0).\n  left. auto.\n  right. auto.\nQed.\nNext Obligation.\n  intros.\n  destruct x.\n  apply esum_left_elem. apply eff_complete.\n  apply esum_right_elem. apply eff_complete.\nQed.\n\n\n(** The lift of an effective preorder is effective. *)\nDefinition enum_lift (A:preord) (X:eset A) : eset (lift A) :=\n  union2 (single None) (image (liftup A) X).\n\nProgram Definition effective_lift {A:preord}\n  (HA:effective_order A)\n  : effective_order (lift A) :=\n  EffectiveOrder _ _ (enum_lift A (eff_enum A HA)) _.\nNext Obligation.\n  intros.\n  destruct x; destruct y; simpl; auto.\n  destruct (eff_ord_dec A HA c c0); auto.\n  left. hnf. auto.\nQed.\nNext Obligation.\n  intros. unfold enum_lift.\n  apply union2_elem.\n  destruct x. right.\n  apply image_axiom1'. exists c. split; auto.\n  apply eff_complete.\n  left. apply single_axiom; auto.\nQed.\n\n\n(** FIXME? this doesn't really fit here, but the current\n    module tree means it can't go in esets.v.  Maybe semidec\n    should get split out into a separate file?\n  *)\nLemma semidec_ex (A B:preord) (P:A -> B -> Prop)\n  (Hok : forall a b c, b ≈ c -> P a b -> P a c)\n  (HB:effective_order B) :\n  (forall ab, semidec (P (fst ab) (snd ab))) ->\n  (forall a, semidec (@ex B (P a))).\nProof.\n  intros.\n  apply Semidec with (fun n =>\n    let (p,q) := pairing.unpairing n in\n       match eff_enum B HB p with\n       | None => None\n       | Some b => decset _ (X (a,b)) q\n       end).\n  split; simpl; intros.\n  destruct H as [n ?].\n  case_eq (pairing.unpairing n); intros.\n  rewrite H0 in H.\n  destruct (eff_enum B HB n0); intros.\n  case_eq (decset (P a c) (X (a,c)) n1); intros.\n  rewrite H1 in H.\n  exists c.\n  rewrite <- (decset_correct _ (X (a,c))). simpl.\n  hnf; simpl. exists n1. rewrite H1. auto.\n  rewrite H1 in H. elim H. elim H.\n\n  destruct H.\n  generalize (eff_complete B HB x).\n  intros [p ?].\n  case_eq (eff_enum B HB p); intros.\n  rewrite H1 in H0.\n  assert (P a c).\n  apply Hok with x; auto.\n  rewrite <- (decset_correct _ (X (a,c))) in H2.\n  destruct H2 as [q ?].\n  simpl in *.\n  exists (pairing.pairing (p,q)).\n  rewrite pairing.unpairing_pairing.\n  rewrite H1.\n  destruct (decset (P a c) (X (a,c)) q); auto.\n  rewrite H1 in H0. elim H0.\nQed.\n", "meta": {"author": "Ninijura", "repo": "bachelorproject", "sha": "dcfd46c08f0a0c5ad1f606b5114702c8e3e0c867", "save_path": "github-repos/coq/Ninijura-bachelorproject", "path": "github-repos/coq/Ninijura-bachelorproject/bachelorproject-dcfd46c08f0a0c5ad1f606b5114702c8e3e0c867/domains/effective.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.845942452844325, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6752200765278502}}
{"text": "Require Export Functor.\n\nArguments Compose_Functors {_} {_} {_} _ _.\nArguments fmap {_} {_} _ {_} {_} _.\nArguments fobj {_} {_} _ _.\n\nCheck fobj.\n\nClass NaturalTransformation (C D: Category) \n                            (F  : Functor C D)\n                            (G  : Functor C D): Type :=\n  mk_nt\n  {\n    trans    : forall (a: @obj C), (@arrow D (fobj G a) (fobj F a));\n    comm_diag: forall {a b: @obj C} (f: arrow  b a), fmap G f o trans a  = trans b o fmap F f;\n  }.\nCheck NaturalTransformation.\n\n\nArguments NaturalTransformation {_} {_} _ _.\nArguments trans {_} {_} {_} {_} _ _.\n\n\nDefinition IdNt (C D: Category) \n                (F  : Functor C D): NaturalTransformation F F.\nProof. unshelve econstructor.\n       - intros. exact (fmap _(@identity C a)).\n       - intros. destruct F. simpl. rewrite !preserve_id.\n         now rewrite identity_f, f_identity.\nDefined.\n\nProgram Definition Compose_NaturalTransformations_H \n                          (C D E: Category)\n                          (F    : Functor C D)\n                          (G    : Functor C D)\n                          (H    : Functor D E)\n                          (I    : Functor D E)\n                          (nt1  : NaturalTransformation F G)\n                          (nt2  : NaturalTransformation H I):\n                                `(NaturalTransformation (Compose_Functors F H) \n                                                        (Compose_Functors G I)).\nProof. unshelve econstructor.\n       - destruct F, G, H, I, nt1, nt2. simpl in *.\n         intros. exact (((fmap2 _ _ (trans0 a)) o trans1 (fobj  a))).\n       - destruct F, G, H, I, nt1, nt2. simpl in *.\n         intros. rewrite !comm_diag1. rewrite assoc.\n         rewrite comm_diag1. rewrite <- assoc.\n         rewrite <- !preserve_comp1.\n         rewrite <- assoc.\n         rewrite <- !preserve_comp1. now rewrite comm_diag0.\nDefined.\n\nProgram Definition Compose_NaturalTransformations \n                      (C D: Category)\n                      (F  : @Functor C D)\n                      (G  : @Functor C D)\n                      (H  : @Functor C D)\n                      (nt1: NaturalTransformation F G)\n                      (nt2: NaturalTransformation G H): `(NaturalTransformation F H) :=\n{|\n    trans := fun a: @obj C =>  trans nt2 a o trans nt1 a;\n|}.\nNext Obligation.\n      rewrite assoc.\n      rewrite (@comm_diag C D G H nt2 a).\n      do 2 rewrite <- assoc.\n      rewrite (@comm_diag C D F G nt1 a).\n      reflexivity.\nDefined.\n\nArguments Compose_NaturalTransformations {_} {_} {_} {_} {_} _ _.\n\nLemma Nt_split: forall (C D: Category)\n                       (F  : @Functor C D) \n                       (G  : @Functor C D)\n                       (nt1: NaturalTransformation F G)\n                       (nt2: NaturalTransformation F G), trans nt1 = trans nt2 <-> nt1 = nt2.\nProof. intros. split. intros. destruct nt1, nt2, F, G.\n       simpl in *. revert comm_diag0. rewrite H. intros.\n       specialize (proof_irrelevance (forall (a b : @obj C) (f : arrow b a),\n             fmap0 a b f o trans1 a = trans1 b o fmap a b f) comm_diag0 comm_diag1).\n       now destruct (proof_irrelevance _ comm_diag0 comm_diag1).\n       intros. rewrite H. easy.\nQed.\n\nClass Cone (C D: Category) (F: Functor C D): Type := mkCone\n  {\n     cobj: @obj D;\n     cobl: NaturalTransformation (ConstantFunctor C D cobj) F\n  }.\n\nClass Limit (C D: Category) (F: Functor C D): Type := mkLimit\n {\n    limc : Cone C D F;\n    limob: forall (a b: @obj C) (Cn: Cone C D F), exists !(u: arrow (@cobj C D F limc) (@cobj C D F Cn)),\n            trans (@cobl C D F limc) a o u = trans (@cobl C D F Cn) a /\\\n            trans (@cobl C D F limc) b o u = trans (@cobl C D F Cn) b \n }.\n\nDefinition has_Limits (D: Category) := forall (C: Category) (F: Functor C D), Limit C D F.\n\nDefinition FunctorCategory (C D: Category): Category.\n(* Proof. refine(@mk_Category (@Functor C D F)\n                           NaturalTransformation\n                           (IdNt C D F)\n                           (Compose_NaturalTransformations)\n                            _ _ _ ).\n       intros. unfold Compose_NaturalTransformations. simpl.\n       destruct a, b, c, d, f, g, h. simpl. f_equal.\n*)\nProof.\n       unshelve econstructor.\n       - exact (Functor C D).\n       - intros F G. exact (NaturalTransformation G F).\n       - intros. exact (@IdNt C D a).\n       - intros F G H nt1 nt2.\n         exact (Compose_NaturalTransformations nt2 nt1).\n       - repeat intro. now rewrite H, H0.\n       - intros. apply Nt_split. simpl.\n         destruct f, g, h. simpl.\n         extensionality a0. now rewrite assoc.\n       - intros. apply Nt_split. simpl.\n         destruct f, a, b. simpl.\n         extensionality a0.\n         now rewrite preserve_id0, identity_f.\n       - intros. apply Nt_split. simpl.\n         destruct f, a, b. simpl.\n         extensionality a0.\n         now rewrite preserve_id, f_identity.\nDefined.\n\nDefinition Cat: Category.\nProof. unshelve econstructor.\n       - exact Category.\n       - intros C D. exact (Functor C D).\n       - intro C. exact (@Id C).\n       - intros E D C F G. exact (Compose_Functors F G).\n       - repeat intro. now subst.\n       - intros D C B A F G H. exact (FunctorCompositionAssoc F G H).\n       - intros D C F. exact (ComposeIdl F).\n       - intros D C F. exact (ComposeIdr F).\nDefined.\n\nClass IsomorphismFunctorial {C D: Category} : Type := {\n  toC   : Functor C D;\n  fromC : Functor D C;\n\n  iso_to_fromC : Compose_Functors toC fromC = @Id C;\n  iso_from_toD : Compose_Functors fromC toC = @Id D\n}.\n\nClass IsomorphismNT {C D: Category} (F G: Functor C D): Type :=\n  mk_IsomorphisnNT\n  {\n     nt1        : NaturalTransformation F G;\n     nt2        : NaturalTransformation G F;\n     equivnt_ob1: Compose_NaturalTransformations nt1 nt2 = IdNt C D F;\n     equivnt_ob2: Compose_NaturalTransformations nt2 nt1 = IdNt C D G\n  }.\n\nLemma eqIso1: forall (C D: @obj Cat), @Isomorphism Cat C D -> @IsomorphismFunctorial C D.\nProof. intros C D I; destruct I; cbn in *.\n       unshelve econstructor.\n       - exact iso_from_to.\n       - exact iso_to_from.\nQed.\n\nLemma eqIso2: forall (C D: @obj Cat), @IsomorphismFunctorial C D -> @Isomorphism Cat C D.\nProof. intros C D I.\n       unshelve econstructor; destruct I; cbn in *.\n       - exact fromC0.\n       - exact toC0.\n       - exact iso_from_toD0.\n       - exact iso_to_fromC0.\nQed.\n\nLemma eqIso3: forall C D (F G: Functor C D), \n                         @Isomorphism (FunctorCategory C D) F G ->\n                         @IsomorphismNT C D F G.\nProof. intros C D F G E.\n       destruct E; cbn in *.\n       - unshelve econstructor.\n         + exact iso_from_to.\n         + exact iso_to_from.\nQed.\n\nLemma eqIso4: forall C D (F G: Functor C D),\n                         @IsomorphismNT C D F G ->\n                         @Isomorphism (FunctorCategory C D) F G.\nProof. intros C D F G I.\n       destruct I; unshelve econstructor; cbn in *.\n       - exact nt3.\n       - exact nt4.\n       - exact equivnt_ob4.\n       - exact equivnt_ob3.\nQed.\n\nClass EquivalenceCat {C D: Category} (F: Functor C D) (G: Functor D C): Type :=\n  mk_EquivalenceCat\n  {\n     equiv_ob1: @Isomorphism (FunctorCategory C C) (Compose_Functors F G) (@Id C);\n     equiv_ob2: @Isomorphism (FunctorCategory D D) (Compose_Functors G F) (@Id D)\n  }.\n\n(*\nDefinition CurryingFunctor (C D E: Category) (F: Functor (Product_Category C D) E):\n  Functor C (FunctorCategory D E).\nProof. intros.\n       unshelve econstructor.\n       - cbn. intro a.\n         + unshelve econstructor.\n           ++ cbn. destruct F. cbn in *. intro b.\n              exact (fobj (a, b)).\n           ++ cbn. intros. destruct F. cbn in *.\n              clear fmapP preserve_id preserve_comp.\n              specialize (fmap (a, a0) (a, b)). cbn in *.\n              apply fmap. exact (identity a, f).\n           ++ repeat intro. now subst.\n           ++ cbn. intros. destruct F. cbn in .\n              now rewrite preserve_id.\n           ++ cbn. intros. destruct F. cbn in *.\n              specialize (preserve_comp (a, a0) (a, b) (a, c)). cbn in *.\n              specialize (preserve_comp  (identity a, g) (identity a, f)). cbn in *.\n              rewrite identity_f in preserve_comp. now rewrite preserve_comp.\n       - intros. cbn.\n         unshelve econstructor.\n         + intros. cbn. destruct F. cbn in *.\n           clear fmapP preserve_id preserve_comp.\n           apply fmap. cbn. exact (f, identity a0).\n         + intros. cbn. destruct F. cbn in *.\n*)\n\nDefinition muT(C D   : Category) \n              (F     : @Functor C D)\n              (G     : @Functor D C)\n              (T     := (Compose_Functors F G))\n              (T2    := (Compose_Functors T T))\n              (epstr : (NaturalTransformation T (@Id C))): (NaturalTransformation T2 T).\nProof. destruct epstr, F, G. simpl in *. unfold T in *.\n       refine (@mk_nt C\n                      C\n                      T2\n                      T\n                      (fun a => fmap0 _ _ (fmap _ _ (trans0 a))) _).\n       intros. unfold T, T2, id in *. simpl in *.\n       now rewrite <- !preserve_comp0, <- !preserve_comp, comm_diag0.\nDefined.\n\nDefinition delD (C D  : Category) \n                (F    : @Functor C D)\n                (G    : @Functor D C)\n                (cT   := (Compose_Functors G F))\n                (cT2  := (Compose_Functors cT cT))\n                (etatr: (NaturalTransformation (@Id D) cT)): (NaturalTransformation cT cT2).\nProof. destruct etatr, F, G. simpl in *. unfold cT in *.\n       refine (@mk_nt D\n                      D\n                      cT\n                      cT2\n                      (fun a => fmap _ _ (fmap0 _ _ (trans0 a))) _).\n       intros. unfold cT, cT2, id in *. simpl in *.\n       now rewrite <- !preserve_comp, <- !preserve_comp0, comm_diag0.\nDefined.\n\n", "meta": {"author": "ekiciburak", "repo": "ComparisonTheorem-MacLane", "sha": "f1a5b0e35554c7115fc0dba32d550dfa0121d07a", "save_path": "github-repos/coq/ekiciburak-ComparisonTheorem-MacLane", "path": "github-repos/coq/ekiciburak-ComparisonTheorem-MacLane/ComparisonTheorem-MacLane-f1a5b0e35554c7115fc0dba32d550dfa0121d07a/NaturalTransformation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6751013241046095}}
{"text": "Require Export D.\n\n\n\n(** **** Problem #1 : 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  | O => nil\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.\n  reflexivity.\nQed.\n\nTheorem snoc_with_append : forall X : Type,\n                         forall l1 l2 : list X,\n                         forall v : X,\n  snoc (l1 ++ l2) v = l1 ++ (snoc l2 v).\nProof.\n  intros. induction l1. reflexivity.\n  simpl. rewrite -> IHl1. 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/P02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.6751013227770979}}
{"text": "Require Import Reals.\n\nTheorem IRsubset :\n forall yl yu zl zu : R,\n (zl <= yl)%R -> (yu <= zu)%R ->\n forall y : R,\n (yl <= y <= yu)%R ->\n (zl <= y <= zu)%R.\nProof.\nintros yl yu zl zu Hzl Hzu y (Hyl,Hyu).\nsplit.\napply Rle_trans with (1 := Hzl) (2 := Hyl).\napply Rle_trans with (1 := Hyu) (2 := Hzu).\nQed.\n\nTheorem IRplus :\n forall xl xu yl yu zl zu : R,\n (zl <= xl + yl)%R -> (xu + yu <= zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x + y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hzl Hzu x y (Hxl,Hxu) (Hyl,Hyu).\napply IRsubset with (1 := Hzl) (2 := Hzu).\nsplit.\napply Rplus_le_compat with (1 := Hxl) (2 := Hyl).\napply Rplus_le_compat with (1 := Hxu) (2 := Hyu).\nQed.\n\nTheorem IRopp :\n forall yl yu zl zu : R,\n (zl <= -yu)%R -> (-yl <= zu)%R ->\n forall y : R,\n (yl <= y <= yu)%R ->\n (zl <= -y <= zu)%R.\nProof.\nintros yl yu zl zu Hzl Hzu y (Hyl,Hyu).\napply IRsubset with (1 := Hzl) (2 := Hzu).\nsplit.\napply Ropp_le_contravar with (1 := Hyu).\napply Ropp_le_contravar with (1 := Hyl).\nQed.\n\nTheorem IRminus :\n forall xl xu yl yu zl zu : R,\n (zl <= xl - yu)%R -> (xu - yl <= zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x - y <= zu)%R.\nProof.\nunfold Rminus.\nintros xl xu yl yu zl zu Hzl Hzu x y Hx Hy.\napply IRplus with (1 := Hzl) (2 := Hzu) (3 := Hx).\napply IRopp with (3 := Hy) ; auto with real.\nQed.\n\nLemma monotony_1p :\n forall a x y : R, (0 <= a)%R -> (x <= y)%R -> (a * x <= a * y)%R.\nProof.\nauto with real.\nQed.\n\nLemma monotony_2p :\n forall a x y : R, (0 <= a)%R -> (x <= y)%R -> (x * a <= y * a)%R.\nProof.\nauto with real.\nQed.\n\nLemma monotony_1n :\n forall a x y : R, (a <= 0)%R -> (x <= y)%R -> (a * y <= a * x)%R.\nProof.\nauto with real.\nQed.\n\nLemma monotony_2n :\n forall a x y : R, (a <= 0)%R -> (x <= y)%R -> (y * a <= x * a)%R.\nProof.\nintros a x y Ha H.\nrewrite Rmult_comm. rewrite (Rmult_comm x).\napply Rge_le.\nauto with real.\nQed.\n\nTheorem IRmult_pp :\n forall xl xu yl yu zl zu : R,\n (0 <= xl)%R -> (0 <= yl)%R ->\n (zl <= xl * yl)%R -> (xu * yu <= zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x * y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hx Hy Hzl Hzu x y (Hxl,Hxu) (Hyl,Hyu).\napply IRsubset with (1 := Hzl) (2 := Hzu).\nsplit.\napply Rle_trans with (xl * y)%R.\nexact (monotony_1p _ _ _ Hx Hyl).\nexact (monotony_2p _ _ _ (Rle_trans _ _ _ Hy Hyl) Hxl).\napply Rle_trans with (x * yu)%R.\nexact (monotony_1p _ _ _ (Rle_trans _ _ _ Hx Hxl) Hyu).\nexact (monotony_2p _ _ _ (Rle_trans _ _ _ Hy (Rle_trans _ _ _ Hyl Hyu)) Hxu).\nQed.\n\nTheorem IRmult_po :\n forall xl xu yl yu zl zu : R,\n (0 <= xl)%R -> (yl <= 0)%R -> (0 <= yu)%R ->\n (zl <= xu * yl)%R -> (xu * yu <= zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x * y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hx Hy1 Hy2 Hzl Hzu x y (Hxl,Hxu) (Hyl,Hyu).\napply IRsubset with (1 := Hzl) (2 := Hzu).\nsplit.\napply Rle_trans with (x * yl)%R.\nexact (monotony_2n _ _ _ Hy1 Hxu).\nexact (monotony_1p _ _ _ (Rle_trans _ _ _ Hx Hxl) Hyl).\napply Rle_trans with (x * yu)%R.\nexact (monotony_1p _ _ _ (Rle_trans _ _ _ Hx Hxl) Hyu).\nexact (monotony_2p _ _ _ Hy2 Hxu).\nQed.\n\nTheorem IRmult_pn :\n forall xl xu yl yu zl zu : R,\n (0 <= xl)%R -> (yu <= 0)%R ->\n (zl <= xu * yl)%R -> (xl * yu <= zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x * y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hx Hy Hzl Hzu x y (Hxl,Hxu) (Hyl,Hyu).\napply IRsubset with (1 := Hzl) (2 := Hzu).\nsplit.\napply Rle_trans with (xu * y)%R.\nexact (monotony_1p _ _ _ (Rle_trans _ _ _ Hx (Rle_trans _ _ _ Hxl Hxu)) Hyl).\nexact (monotony_2n _ _ _ (Rle_trans _ _ _ Hyu Hy) Hxu).\napply Rle_trans with (x * yu)%R.\nexact (monotony_1p _ _ _ (Rle_trans _ _ _ Hx Hxl) Hyu).\nexact (monotony_2n _ _ _ Hy Hxl).\nQed.\n\nTheorem IRmult_op :\n forall xl xu yl yu zl zu : R,\n (xl <= 0)%R -> (0 <= xu)%R -> (0 <= yl)%R ->\n (zl <= xl * yu)%R -> (xu * yu <= zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x * y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hx1 Hx2 Hy Hzl Hzu x y (Hxl,Hxu) (Hyl,Hyu).\napply IRsubset with (1 := Hzl) (2 := Hzu).\nsplit.\napply Rle_trans with (xl * y)%R.\nexact (monotony_1n _ _ _ Hx1 Hyu).\nexact (monotony_2p _ _ _ (Rle_trans _ _ _ Hy Hyl) Hxl).\napply Rle_trans with (xu * y)%R.\nexact (monotony_2p _ _ _ (Rle_trans _ _ _ Hy Hyl) Hxu).\nexact (monotony_1p _ _ _ Hx2 Hyu).\nQed.\n\nTheorem IRmult_oo :\n forall xl xu yl yu zl zu : R,\n (xl <= 0)%R -> (0 <= xu)%R -> (yl <= 0)%R -> (0 <= yu)%R ->\n (zl <= xu * yl)%R -> (zl <= xl * yu)%R ->\n (xl * yl <= zu)%R -> (xu * yu <= zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x * y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hx1 Hx2 Hy1 Hy2 Hzl1 Hzl2 Hzu1 Hzu2 x y (Hxl,Hxu) (Hyl,Hyu).\ncase (Rlt_le_dec 0 x) ; intro H.\ngeneralize (Rlt_le _ _ H). clear H. intro H.\nsplit.\napply Rle_trans with (1 := Hzl1).\napply Rle_trans with (x * yl)%R.\nexact (monotony_2n _ _ _ Hy1 Hxu).\nexact (monotony_1p _ _ _ H Hyl).\napply Rle_trans with (2 := Hzu2).\napply Rle_trans with (x * yu)%R.\nexact (monotony_1p _ _ _ H Hyu).\nexact (monotony_2p _ _ _ Hy2 Hxu).\nsplit.\napply Rle_trans with (1 := Hzl2).\napply Rle_trans with (x * yu)%R.\nexact (monotony_2p _ _ _ Hy2 Hxl).\nexact (monotony_1n _ _ _ H Hyu).\napply Rle_trans with (2 := Hzu1).\napply Rle_trans with (x * yl)%R.\nexact (monotony_1n _ _ _ H Hyl).\nexact (monotony_2n _ _ _ Hy1 Hxl).\nQed.\n\nTheorem IRmult_on :\n forall xl xu yl yu zl zu : R,\n (xl <= 0)%R -> (0 <= xu)%R -> (yu <= 0)%R ->\n (zl <= xu * yl)%R -> (xl * yl <= zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x * y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hx1 Hx2 Hy Hzl Hzu x y (Hxl,Hxu) (Hyl,Hyu).\napply IRsubset with (1 := Hzl) (2 := Hzu).\nsplit.\napply Rle_trans with (xu * y)%R.\nexact (monotony_1p _ _ _ Hx2 Hyl).\nexact (monotony_2n _ _ _ (Rle_trans _ _ _ Hyu Hy) Hxu).\napply Rle_trans with (xl * y)%R.\nexact (monotony_2n _ _ _ (Rle_trans _ _ _ Hyu Hy) Hxl).\nexact (monotony_1n _ _ _ Hx1 Hyl).\nQed.\n\nTheorem IRmult_np :\n forall xl xu yl yu zl zu : R,\n (xu <= 0)%R -> (0 <= yl)%R ->\n (zl <= xl * yu)%R -> (xu * yl <= zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x * y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hx Hy Hzl Hzu x y (Hxl,Hxu) (Hyl,Hyu).\napply IRsubset with (1 := Hzl) (2 := Hzu).\nsplit.\napply Rle_trans with (x * yu)%R.\nexact (monotony_2p _ _ _ (Rle_trans _ _ _ Hy (Rle_trans _ _ _ Hyl Hyu)) Hxl).\nexact (monotony_1n _ _ _ (Rle_trans _ _ _ Hxu Hx) Hyu).\napply Rle_trans with (xu * y)%R.\nexact (monotony_2p _ _ _ (Rle_trans _ _ _ Hy Hyl) Hxu).\nexact (monotony_1n _ _ _ Hx Hyl).\nQed.\n\nTheorem IRmult_no :\n forall xl xu yl yu zl zu : R,\n (xu <= 0)%R -> (yl <= 0)%R -> (0 <= yu)%R ->\n (zl <= xl * yu)%R -> (xl * yl <= zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x * y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hx Hy1 Hy2 Hzl Hzu x y (Hxl,Hxu) (Hyl,Hyu).\napply IRsubset with (1 := Hzl) (2 := Hzu).\nsplit.\napply Rle_trans with (x * yu)%R.\nexact (monotony_2p _ _ _ Hy2 Hxl).\nexact (monotony_1n _ _ _ (Rle_trans _ _ _ Hxu Hx) Hyu).\napply Rle_trans with (x * yl)%R.\nexact (monotony_1n _ _ _ (Rle_trans _ _ _ Hxu Hx) Hyl).\nexact (monotony_2n _ _ _ Hy1 Hxl).\nQed.\n\nTheorem IRmult_nn :\n forall xl xu yl yu zl zu : R,\n (xu <= 0)%R -> (yu <= 0)%R ->\n (zl <= xu * yu)%R -> (xl * yl <= zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x * y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hx Hy Hzl Hzu x y (Hxl,Hxu) (Hyl,Hyu).\napply IRsubset with (1 := Hzl) (2 := Hzu).\nsplit.\napply Rle_trans with (xu * y)%R.\nexact (monotony_1n _ _ _ Hx Hyu).\nexact (monotony_2n _ _ _ (Rle_trans _ _ _ Hyu Hy) Hxu).\napply Rle_trans with (xl * y)%R.\nexact (monotony_2n _ _ _ (Rle_trans _ _ _ Hyu Hy) Hxl).\nexact (monotony_1n _ _ _ (Rle_trans _ _ _ (Rle_trans _ _ _ Hxl Hxu) Hx) Hyl).\nQed.\n\nInductive interval_sign (xl xu : R) : Set :=\n  | Nsign : (xu <= 0)%R -> interval_sign xl xu\n  | Msign : (xl <= 0)%R -> (0 <= xu)%R -> interval_sign xl xu\n  | Psign : (0 <= xl)%R -> interval_sign xl xu.\n\nLemma interval_sign_correct :\n forall xl xu : R, (xl <= xu)%R -> interval_sign xl xu.\nProof.\nintros xl xu H.\ncase (Rlt_le_dec xu 0); intro H0.\nexact (Nsign _ _ (Rlt_le _ _ H0)).\ncase (Rlt_le_dec xl 0); intro H1.\nexact (Msign _ _ (Rlt_le _ _ H1) H0).\nexact (Psign _ _ H1).\nQed.\n\nLemma Rmin_trans :\n forall a b c : R, (c <= Rmin a b)%R -> (c <= a)%R /\\ (c <= b)%R.\nProof.\nintros a b c H.\nsplit.\nexact (Rle_trans _ _ _ H (Rmin_l _ _)).\nexact (Rle_trans _ _ _ H (Rmin_r _ _)).\nQed.\n\nLemma Rmax_trans :\n forall a b c : R, (Rmax a b <= c)%R -> (a <= c)%R /\\ (b <= c)%R.\nProof.\nintros a b c H.\nsplit.\nexact (Rle_trans _ _ _ (RmaxLess1 _ _) H).\nexact (Rle_trans _ _ _ (RmaxLess2 _ _) H).\nQed.\n\nLemma IRmult_minmax :\n forall xl xu yl yu zl zu : R,\n (zl <= Rmin (Rmin (xl * yl) (xl * yu)) (Rmin (xu * yl) (xu * yu)))%R ->\n (Rmax (Rmax (xl * yl) (xl * yu)) (Rmax (xu * yl) (xu * yu)) <= zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x * y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hzl Hzu x y Hx Hy.\ndecompose [and] (Rmin_trans _ _ _ Hzl).\ndecompose [and] (Rmin_trans _ _ _ H).\ndecompose [and] (Rmin_trans _ _ _ H0).\nclear Hzl H H0.\ndecompose [and] (Rmax_trans _ _ _ Hzu).\ndecompose [and] (Rmax_trans _ _ _ H).\ndecompose [and] (Rmax_trans _ _ _ H0).\nclear Hzu H H0.\ncase (interval_sign_correct _ _ (Rle_trans _ _ _ (proj1 Hx) (proj2 Hx))) ;\ncase (interval_sign_correct _ _ (Rle_trans _ _ _ (proj1 Hy) (proj2 Hy))) ; intros.\napply IRmult_nn with xl xu yl yu ; assumption.\napply IRmult_no with xl xu yl yu ; assumption.\napply IRmult_np with xl xu yl yu ; assumption.\napply IRmult_on with xl xu yl yu ; assumption.\napply IRmult_oo with xl xu yl yu ; assumption.\napply IRmult_op with xl xu yl yu ; assumption.\napply IRmult_pn with xl xu yl yu ; assumption.\napply IRmult_po with xl xu yl yu ; assumption.\napply IRmult_pp with xl xu yl yu ; assumption.\nQed.\n\nLemma Rle_Rinv_pos :\n forall x y : R,\n (0 < x)%R -> (x <= y)%R ->\n (/y <= /x)%R.\nProof.\nintros x y Hx H.\napply Rle_Rinv with (1 := Hx) (3 := H).\napply Rlt_le_trans with (1 := Hx) (2 := H).\nQed.\n\nLemma Rle_Rinv_neg :\n forall x y : R,\n (y < 0)%R -> (x <= y)%R ->\n (/y <= /x)%R.\nProof.\nintros x y Hy H.\napply Ropp_le_cancel.\nrepeat rewrite Ropp_inv_permute.\napply Rle_Rinv_pos.\napply Ropp_0_gt_lt_contravar with (1 := Hy).\napply Ropp_le_contravar with (1 := H).\nexact (Rlt_not_eq _ _ Hy).\nexact (Rlt_not_eq _ _ (Rle_lt_trans _ _ _ H Hy)).\nQed.\n\nLemma IRinv_p :\n forall yl yu zl zu : R,\n (0 < yl)%R ->\n (zl <= /yu)%R -> (/yl <= zu)%R ->\n forall y : R,\n (yl <= y <= yu)%R ->\n (zl <= /y <= zu)%R.\nProof.\nintros yl yu zl zu Hy Hzl Hzu y (Hyl,Hyu).\napply IRsubset with (1 := Hzl) (2 := Hzu).\nsplit.\napply Rle_Rinv_pos with (2 := Hyu).\nexact (Rlt_le_trans _ _ _ Hy Hyl).\nexact (Rle_Rinv_pos _ _ Hy Hyl).\nQed.\n\nLemma IRinv_n :\n forall yl yu zl zu,\n (yu < 0)%R ->\n (zl <= /yu)%R -> (/yl <= zu)%R ->\n forall y : R,\n (yl <= y <= yu)%R ->\n (zl <= /y <= zu)%R.\nProof.\nintros yl yu zl zu Hy Hzl Hzu y (Hyl,Hyu).\napply IRsubset with (1 := Hzl) (2 := Hzu).\nsplit.\nexact (Rle_Rinv_neg _ _ Hy Hyu).\napply Rle_Rinv_neg with (2 := Hyl).\nexact (Rle_lt_trans _ _ _ Hyu Hy).\nQed.\n\nLemma IRinv_disj :\n forall yl yu zl zu : R,\n (yu < 0)%R \\/ (0 < yl)%R ->\n (zl <= /yu)%R -> (/yl <= zu)%R ->\n forall y : R,\n (yl <= y <= yu)%R ->\n (zl <= /y <= zu)%R.\nProof.\nintros yl yu zl zu [Hy2|Hy1] Hzl Hzu y Hy.\nexact (IRinv_n _ _ _ _ Hy2 Hzl Hzu _ Hy).\nexact (IRinv_p _ _ _ _ Hy1 Hzl Hzu _ Hy).\nQed.\n\nLemma IRdiv_minmax :\n forall xl xu yl yu zl zu : R,\n (yu < 0)%R \\/ (yl > 0)%R ->\n (zl <= Rmin (Rmin (xl / yu) (xl / yl)) (Rmin (xu / yu) (xu / yl)))%R ->\n (Rmax (Rmax (xl / yu) (xl / yl)) (Rmax (xu / yu) (xu / yl)) <= zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x / y <= zu)%R.\nProof.\nunfold Rdiv.\nintros xl xu yl yu zl zu H Hzl Hzu x y Hx Hy.\napply (IRmult_minmax _ _ (/yu) (/yl) _ _ Hzl Hzu _ (/y) Hx).\napply (IRinv_disj _ _ (/yu) (/yl) H) with (3 := Hy) ; auto with real.\nQed.\n\nLemma IRdiv_aux_p :\n forall yl yu y : R,\n (0 < yl)%R -> (yl <= y <= yu)%R ->\n (0 <= / yl)%R /\\ (0 <= / yu)%R /\\ (yl <> 0)%R /\\ (yu <> 0)%R /\\ (/ yu <= /y <= / yl)%R.\nProof.\nintros yl yu y Hyl Hy.\nsplit. left.\napply Rinv_0_lt_compat.\nexact Hyl.\nsplit. left.\napply Rinv_0_lt_compat.\nexact (Rlt_le_trans _ _ _ Hyl (Rle_trans _ _ _ (proj1 Hy) (proj2 Hy))).\nsplit.\napply Rgt_not_eq.\nexact Hyl.\nsplit.\napply Rgt_not_eq.\nexact (Rlt_le_trans _ _ _ Hyl (Rle_trans _ _ _ (proj1 Hy) (proj2 Hy))).\nsplit.\nexact (Rle_Rinv_pos _ _ (Rlt_le_trans _ _ _ Hyl (proj1 Hy)) (proj2 Hy)).\nexact (Rle_Rinv_pos _ _ Hyl (proj1 Hy)).\nQed.\n\nTheorem IRdiv_pp :\n forall xl xu yl yu zl zu : R,\n (0 <= xl)%R ->\n (0 < yl)%R ->\n (yu * zl <= xl)%R ->\n (xu <= yl * zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x / y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hxl Hyl Hzl Hzu x y Hx Hy.\ngeneralize (IRdiv_aux_p _ _ _ Hyl Hy).\nintros (Hy1, (Hy2, (Hy3, (Hy4, Hy5)))).\nunfold Rdiv.\napply IRmult_pp with (1 := Hxl) (2 := Hy2) (5 := Hx) (6 := Hy5).\nreplace zl with (yu * zl * / yu)%R.\nexact (monotony_2p _ _ _ Hy2 Hzl).\nfield. exact Hy4.\nreplace zu with (yl * zu * / yl)%R.\nexact (monotony_2p _ _ _ Hy1 Hzu).\nfield. exact Hy3.\nQed.\n\nTheorem IRdiv_op :\n forall xl xu yl yu zl zu : R,\n (xl <= 0)%R ->\n (0 <= xu)%R ->\n (0 < yl)%R ->\n (yl * zl <= xl)%R ->\n (xu <= yl * zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x / y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hxl Hxu Hyl Hzl Hzu x y Hx Hy.\ngeneralize (IRdiv_aux_p _ _ _ Hyl Hy).\nintros (Hy1, (Hy2, (Hy3, (Hy4, Hy5)))).\nunfold Rdiv.\napply IRmult_op with (1 := Hxl) (2 := Hxu) (3 := Hy2) (6 := Hx) (7 := Hy5).\nreplace zl with (yl * zl * / yl)%R.\nexact (monotony_2p _ _ _ Hy1 Hzl).\nfield. exact Hy3.\nreplace zu with (yl * zu * / yl)%R.\nexact (monotony_2p _ _ _ Hy1 Hzu).\nfield. exact Hy3.\nQed.\n\nTheorem IRdiv_np :\n forall xl xu yl yu zl zu : R,\n (xu <= 0)%R ->\n (0 < yl)%R ->\n (yl * zl <= xl)%R ->\n (xu <= yu * zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x / y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hxu Hyl Hzl Hzu x y Hx Hy.\ngeneralize (IRdiv_aux_p _ _ _ Hyl Hy).\nintros (Hy1, (Hy2, (Hy3, (Hy4, Hy5)))).\nunfold Rdiv.\napply IRmult_np with (1 := Hxu) (2 := Hy2) (5 := Hx) (6 := Hy5).\nreplace zl with (yl * zl * / yl)%R.\nexact (monotony_2p _ _ _ Hy1 Hzl).\nfield. exact Hy3.\nreplace zu with (yu * zu * / yu)%R.\nexact (monotony_2p _ _ _ Hy2 Hzu).\nfield. exact Hy4.\nQed.\n\nLemma IRdiv_aux_n :\n forall yl yu y : R,\n (yu < 0)%R -> (yl <= y <= yu)%R ->\n (/ yl <= 0)%R /\\ (/ yu <= 0)%R /\\ (yl <> 0)%R /\\ (yu <> 0)%R /\\ (/ yu <= /y <= / yl)%R.\nProof.\nintros yl yu y Hyu Hy.\nsplit. left.\napply Rinv_lt_0_compat.\nexact (Rle_lt_trans _ _ _ (Rle_trans _ _ _ (proj1 Hy) (proj2 Hy)) Hyu).\nsplit. left.\napply Rinv_lt_0_compat.\nexact Hyu.\nsplit.\napply Rlt_not_eq.\nexact (Rle_lt_trans _ _ _ (Rle_trans _ _ _ (proj1 Hy) (proj2 Hy)) Hyu).\nsplit.\napply Rlt_not_eq.\nexact Hyu.\nsplit.\nexact (Rle_Rinv_neg _ _ Hyu (proj2 Hy)).\nexact (Rle_Rinv_neg _ _ (Rle_lt_trans _ _ _ (proj2 Hy) Hyu) (proj1 Hy)).\nQed.\n\nTheorem IRdiv_pn :\n forall xl xu yl yu zl zu : R,\n (0 <= xl)%R ->\n (yu < 0)%R ->\n (xu <= yu * zl)%R ->\n (yl * zu <= xl)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x / y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hxl Hyu Hzl Hzu x y Hx Hy.\ngeneralize (IRdiv_aux_n _ _ _ Hyu Hy).\nintros (Hy1, (Hy2, (Hy3, (Hy4, Hy5)))).\nunfold Rdiv.\napply IRmult_pn with (1 := Hxl) (2 := Hy1) (5 := Hx) (6 := Hy5).\nreplace zl with (yu * zl * / yu)%R.\nexact (monotony_2n _ _ _ Hy2 Hzl).\nfield. exact Hy4.\nreplace zu with (yl * zu * / yl)%R.\nexact (monotony_2n _ _ _ Hy1 Hzu).\nfield. exact Hy3.\nQed.\n\nTheorem IRdiv_on :\n forall xl xu yl yu zl zu : R,\n (xl <= 0)%R ->\n (0 <= xu)%R ->\n (yu < 0)%R ->\n (xu <= yu * zl)%R ->\n (yu * zu <= xl)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x / y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hxl Hxu Hyu Hzl Hzu x y Hx Hy.\ngeneralize (IRdiv_aux_n _ _ _ Hyu Hy).\nintros (Hy1, (Hy2, (Hy3, (Hy4, Hy5)))).\nunfold Rdiv.\napply IRmult_on with (1 := Hxl) (2 := Hxu) (3 := Hy1) (6 := Hx) (7 := Hy5).\nreplace zl with (yu * zl * / yu)%R.\nexact (monotony_2n _ _ _ Hy2 Hzl).\nfield. exact Hy4.\nreplace zu with (yu * zu * / yu)%R.\nexact (monotony_2n _ _ _ Hy2 Hzu).\nfield. exact Hy4.\nQed.\n\nTheorem IRdiv_nn :\n forall xl xu yl yu zl zu : R,\n (xu <= 0)%R ->\n (yu < 0)%R ->\n (xu <= yl * zl)%R ->\n (yu * zu <= xl)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x / y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hxu Hyu Hzl Hzu x y Hx Hy.\ngeneralize (IRdiv_aux_n _ _ _ Hyu Hy).\nintros (Hy1, (Hy2, (Hy3, (Hy4, Hy5)))).\nunfold Rdiv.\napply IRmult_nn with (1 := Hxu) (2 := Hy1) (5 := Hx) (6 := Hy5).\nreplace zl with (yl * zl * / yl)%R.\nexact (monotony_2n _ _ _ Hy1 Hzl).\nfield. exact Hy3.\nreplace zu with (yu * zu * / yu)%R.\nexact (monotony_2n _ _ _ Hy2 Hzu).\nfield. exact Hy4.\nQed.\n\nTheorem IRsquare_o :\n forall yl yu zl zu : R,\n (yl <= 0)%R -> (0 <= yu)%R -> (zl <= 0)%R ->\n (yl * yl <= zu)%R -> (yu * yu <= zu)%R ->\n forall y : R,\n (yl <= y <= yu)%R ->\n (zl <= y * y <= zu)%R.\nProof.\nintros yl yu zl zu Hy1 Hy2 Hzl Hzu1 Hzu2 y (Hyl,Hyu).\nsplit.\nfold (Rsqr y).\napply Rle_trans with 0%R ; auto with real.\ncase (Rlt_le_dec 0 y) ; intro H.\ngeneralize (Rlt_le _ _ H). clear H. intro H.\napply Rle_trans with (yu * yu)%R ; auto with real.\napply Rle_trans with (2 := Hzu1).\napply Rle_trans with (y * yl)%R.\nexact (monotony_1n _ _ _ H Hyl).\nexact (monotony_2n _ _ _ Hy1 Hyl).\nQed.\n\nTheorem IRsqrt :\n forall yl yu zl zu : R,\n match (Rlt_le_dec 0 zl) with\n | left _ => (zl * zl <= yl)%R\n | right _ => (0 <= yl)%R\n end -> (0 <= zu)%R -> (yu <= zu * zu)%R ->\n forall y : R,\n (yl <= y <= yu)%R ->\n (zl <= sqrt y <= zu)%R.\nProof.\nintros yl yu zl zu.\ncase (Rlt_le_dec 0 zl) ; intros Hzl1 Hzl2 Hzu1 Hzu2 y (Hyl,Hyu).\nassert (H1: (zl * zl <= y)%R).\napply Rle_trans with (1 := Hzl2) (2 := Hyl).\nassert (H2: (0 <= y)%R).\napply Rle_trans with (2 := H1).\nexact (Rle_0_sqr _).\nsplit.\nrewrite <- (sqrt_square zl).\napply sqrt_le_1. 3: exact H1.\nexact (Rle_0_sqr _).\nexact H2.\nexact (Rlt_le _ _ Hzl1).\nrewrite <- (sqrt_square zu). 2: exact Hzu1.\napply sqrt_le_1.\nexact H2.\nexact (Rle_0_sqr _).\napply Rle_trans with (1 := Hyu) (2 := Hzu2).\nsplit.\napply Rle_trans with (1 := Hzl1).\napply sqrt_positivity.\napply Rle_trans with (1 := Hzl2) (2 := Hyl).\nrewrite <- (sqrt_square zu). 2: exact Hzu1.\napply sqrt_le_1.\napply Rle_trans with (1 := Hzl2) (2 := Hyl).\nexact (Rle_0_sqr _).\napply Rle_trans with (1 := Hyu) (2 := Hzu2).\nQed.\n\nTheorem IRcompose :\n forall xl xu yl yu zl zu : R,\n (-1 <= xl)%R -> (-1 <= yl)%R ->\n (zl <= xl + yl + xl * yl)%R -> (xu + yu + xu * yu <= zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= x + y + x * y <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hx Hy Hzl Hzu x y (Hxl,Hxu) (Hyl,Hyu).\nreplace (x + y + x * y)%R with ((1 + x) * (1 + y) - 1)%R. 2: ring.\nassert (H : (1 + zl <= (1 + x) * (1 + y) <= 1 + zu)%R).\nassert (H0 : (0 = 1 + -1)%R). ring.\nassert (Hc : forall a b : R, ((1 + a) * (1 + b) = 1 + (a + b + a * b))%R).\nintros a b. ring.\nassert (Hi : forall a b c : R, (a <= b)%R -> (b <= c)%R -> (1 + a <= 1 + b <= 1 + c)%R).\nintros a b c H1 H2. split.\napply Rplus_le_compat_l with (1 := H1).\napply Rplus_le_compat_l with (1 := H2).\napply IRmult_pp with (1 + xl)%R (1 + xu)%R (1 + yl)%R (1 + yu)%R.\nrewrite H0. apply Rplus_le_compat_l with (1 := Hx).\nrewrite H0. apply Rplus_le_compat_l with (1 := Hy).\nrewrite Hc. apply Rplus_le_compat_l with (1 := Hzl).\nrewrite Hc. apply Rplus_le_compat_l with (1 := Hzu).\napply Hi with (1 := Hxl) (2 := Hxu).\napply Hi with (1 := Hyl) (2 := Hyu).\nassert (H0 : forall a : R, (a = (1 + a) + -1)%R).\nintros a. ring.\nsplit.\nrewrite (H0 zl). exact (Rplus_le_compat_r _ _ _ (proj1 H)).\nrewrite (H0 zu). exact (Rplus_le_compat_r _ _ _ (proj2 H)).\nQed.\n\nTheorem IRcompose_inv :\n forall xl xu yl yu zl zu : R,\n (-1 <= xl)%R -> (-1 < yl)%R ->\n (yu + zl + yu * zl <= xl)%R -> (xu <= yl + zu + yl * zu)%R ->\n forall x y : R,\n (xl <= x <= xu)%R -> (yl <= y <= yu)%R ->\n (zl <= (x - y) / (1 + y) <= zu)%R.\nProof.\nintros xl xu yl yu zl zu Hx Hy Hzl Hzu x y (Hxl,Hxu) (Hyl,Hyu).\nassert (H0: (0 = 1 + -1)%R). ring.\nassert (Hc: (0 < 1 + yl)%R).\nrewrite H0.\napply Rplus_lt_compat_l with (1 := Hy).\nreplace ((x - y) / (1 + y))%R with ((1 + x) / (1 + y) - 1)%R.\nassert (H : (1 + zl <= (1 + x) / (1 + y) <= 1 + zu)%R).\nassert (Hi : forall a b c : R, (a <= b)%R -> (b <= c)%R -> (1 + a <= 1 + b <= 1 + c)%R).\nintros a b c H1 H2. split.\napply Rplus_le_compat_l with (1 := H1).\napply Rplus_le_compat_l with (1 := H2).\ndestruct (IRdiv_aux_p _ _ _ Hc (Hi _ _ _ Hyl Hyu))%R as (H1, (H2, (H3, (H4, H5)))).\nunfold Rdiv.\napply IRmult_pp with (2 := H2) (5 := Hi _ _ _ Hxl Hxu) (6 := H5).\nrewrite H0. apply Rplus_le_compat_l with (1 := Hx).\nreplace (1 + zl)%R with ((1 + zl) * (1 + yu) * /(1 + yu))%R.\napply monotony_2p with (1 := H2).\nreplace ((1 + zl) * (1 + yu))%R with (1 + (yu + zl + yu * zl))%R. 2: ring.\napply Rplus_le_compat_l with (1 := Hzl).\nfield. exact H4.\nreplace (1 + zu)%R with ((1 + zu) * (1 + yl) * /(1 + yl))%R.\napply monotony_2p with (1 := H1).\nreplace ((1 + zu) * (1 + yl))%R with (1 + (yl + zu + yl * zu))%R. 2: ring.\napply Rplus_le_compat_l with (1 := Hzu).\nfield. exact H3.\nreplace zl with (1 + zl + -1)%R. 2: ring.\nreplace zu with (1 + zu + -1)%R. 2: ring.\nunfold Rminus.\nsplit ; apply Rplus_le_compat_r.\nexact (proj1 H).\nexact (proj2 H).\nfield.\napply Rgt_not_eq.\nunfold Rgt.\napply Rlt_le_trans with (1 := Hc).\napply Rplus_le_compat_l with (1 := Hyl).\nQed.\n\nTheorem IRabs_p :\n forall yl yu zl zu : R,\n (0 <= yl)%R ->\n (zl <= yl)%R -> (yu <= zu)%R ->\n forall y : R,\n (yl <= y <= yu)%R ->\n (zl <= Rabs y <= zu)%R.\nProof.\nintros yl yu zl zu Hy Hzl Hzu y Hylu.\nrewrite Rabs_pos_eq.\napply IRsubset with (1 := Hzl) (2 := Hzu) (3 := Hylu).\napply Rle_trans with (1 := Hy) (2 := proj1 Hylu).\nQed.\n\nTheorem IRabs_o :\n forall yl yu zl zu : R,\n (zl <= 0)%R -> (-yl <= zu)%R -> (yu <= zu)%R ->\n forall y : R,\n (yl <= y <= yu)%R ->\n (zl <= Rabs y <= zu)%R.\nProof.\nintros yl yu zl zu Hzl Hzu1 Hzu2 y (Hyl,Hyu).\nsplit.\napply Rle_trans with (1 := Hzl) (2 := Rabs_pos y).\nunfold Rabs. case Rcase_abs ; intro H.\napply Rle_trans with (2 := Hzu1).\napply Ropp_le_contravar with (1 := Hyl).\napply Rle_trans with (1 := Hyu) (2 := Hzu2).\nQed.\n\nTheorem IRabs_n :\n forall yl yu zl zu : R,\n (yu <= 0)%R ->\n (zl <= -yu)%R -> (-yl <= zu)%R ->\n forall y : R,\n (yl <= y <= yu)%R ->\n (zl <= Rabs y <= zu)%R.\nProof.\nintros yl yu zl zu Hy Hzl Hzu y Hylu.\nrewrite Rabs_left1.\napply IRopp with (1 := Hzl) (2 := Hzu) (3 := Hylu).\napply Rle_trans with (1 := proj2 Hylu) (2 := Hy).\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_real.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6751013099870729}}
{"text": "(*|\n###############################################################\nHow to prove ``False`` from obviously contradictory assumptions\n###############################################################\n\n:Link: https://stackoverflow.com/q/29286679\n|*)\n\n(*|\nQuestion\n********\n\nSuppose I want to prove following Theorem:\n|*)\n\nTheorem succ_neq_zero : forall n m: nat, S n = m -> 0 = m -> False.\nAbort. (* .none *)\n\n(*|\nThis one is trivial since ``m`` cannot be both successor and zero, as\nassumed. However I found it quite tricky to prove it, and I don't know\nhow to make it without an auxiliary lemma:\n|*)\n\nLemma succ_neq_zero_lemma : forall n : nat, O = S n -> False.\nProof. intros. inversion H. Qed.\n\nTheorem succ_neq_zero : forall n m : nat, S n = m -> 0 = m -> False.\nProof.\n  intros. symmetry in H.\n  apply (succ_neq_zero_lemma n). transitivity m.\n  - assumption.\n  - assumption.\nQed.\n\n(*|\nI am pretty sure there is a better way to prove this. What is the best\nway to do it?\n|*)\n\n(*|\nAnswer (Arthur Azevedo De Amorim)\n*********************************\n\nYou just need to substitute for ``m`` in the first equation:\n|*)\n\nReset Initial. (* .none *)\nTheorem succ_neq_zero : forall n m : nat, S n = m -> 0 = m -> False.\nProof.\n  intros n m H1 H2. rewrite <- H2 in H1. inversion H1.\nQed.\n\n(*|\n----\n\n**A:** Or a bit more concise yet still explicit:\n|*)\n\nReset Initial. (* .none *)\nTheorem succ_neq_zero : forall n m : nat, S n = m -> 0 = m -> False.\nProof.\n  intros n m H <-. discriminate H.\nQed.\n\n(*| less explicit works too: |*)\n\nReset Initial. (* .none *)\nTheorem succ_neq_zero : forall n m : nat, S n = m -> 0 = m -> False.\nProof.\n  intros. subst. discriminate.\nQed.\n\n(*|\nAnswer (Gilles 'SO- stop being evil')\n*************************************\n\nThere's a very easy way to prove it:\n|*)\n\nReset Initial. (* .none *)\nTheorem succ_neq_zero : forall n m : nat, S n = m -> 0 = m -> False.\nProof.\n  congruence.\nQed.\n\n(*|\nThe ``congruence`` tactic is a decision procedure for ground\nequalities on uninterpreted symbols. It's complete for uninterpreted\nsymbols and for constructors, so in cases like this one, it can prove\nthat the equality ``0 = m`` is impossible.\n|*)\n\n(*|\nAnswer (larsr)\n**************\n\nIt might be useful to know how congruence works.\n\nTo prove that two terms constructed by different constructors are in\nfact different, just create a function that returns ``True`` in one\ncase and ``False`` in the other cases, and then use it to prove ``True\n= False``. I think this is explained in `Coq'Art\n<https://www.labri.fr/perso/casteran/CoqArt/>`__\n|*)\n\nExample not_congruent : 0 <> 1.\nProof.\n  intros C. (* now our goal is 'False' *)\n  pose (fun m => match m with 0 => True | S _ => False end) as f.\n  assert (Contra: f 1 = f 0) by (rewrite C; reflexivity).\n  now replace False with True by Contra.\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-false-from-obviously-contradictory-assumptions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.67504392070701}}
{"text": "(** This module defines substitution of closed terms into open terms,\nand substitution of a single closed type into an open type.  *)\n\nFrom Coq Require Export List.\n\nFrom Rattus Require Export RawSyntax.\n\n\n\n(* Substitution in types *)\nFixpoint tsubst (j : index) (A : type) (B : type) : type :=\n  match A with\n  | TypeVar k  => if j =? k\n                  then B\n                  else TypeVar k\n  | Times A1 A2    => Times (tsubst j A1 B) (tsubst j A2 B)\n  | Plus A1 A2    => Plus (tsubst j A1 B) (tsubst j A2 B)\n  | Arrow A1 A2    => Arrow (tsubst j A1 B) (tsubst j A2 B)\n  | Delay A'       => Delay (tsubst j A' B)\n  | Box A'       => Box (tsubst j A' B)\n  | Fix A'       => Fix (tsubst (S j) A' B)\n  | _          => A\n  end.\n\n\n(* = Terms = *)\n\nDefinition sub := list (option term).\n\nDefinition sub_lookup (g : sub) i := \n  match nth_error g i with\n    | Some (Some t) => Some t\n    | _ => None\n  end.\n\nFixpoint sub_app (g : sub) (t : term) : term :=\n  match t with\n  | var j    => match sub_lookup g j with\n                | Some t => t\n                | None => var j\n                end\n  | abs t'   => abs (sub_app (None::g) t')\n  | letin t1 t2 => letin (sub_app g t1) (sub_app (None::g) t2)\n  | app t1 t2 => app (sub_app g t1) (sub_app g t2)\n  | pair t1 t2 => pair (sub_app g t1) (sub_app g t2)\n  | pr1 t'=> pr1 (sub_app g t')\n  | pr2 t'=> pr2 (sub_app g t')\n  | in1 t'=> in1 (sub_app g t')\n  | in2 t'=> in2 (sub_app g t')\n  | case t1 t2 t3 => case (sub_app g t1) (sub_app (None :: g) t2) (sub_app (None :: g) t3)\n  | delay  t' => delay (sub_app g t')\n  | adv  t' => adv (sub_app g t')\n  | box  t'  => box (sub_app g t')\n  | unbox  t' => unbox (sub_app g t')\n  | into t'=> into (sub_app g t')\n  | out t'=> out (sub_app g t')\n\n  | fixp t'=> fixp (sub_app (None::g) t')\n  | unit => unit\n  | natlit n => natlit n\n  | add t1 t2 => add (sub_app g t1) (sub_app g t2)\n  | ref l => ref l\n  end.\n\nImport ListNotations.\n\n(* substitute u into t *)\nDefinition sub_term (t u : term) : term := sub_app [ Some u ] t.\n\n\nInductive sub_empty : sub -> Prop :=\n| sub_empty_nil : sub_empty nil\n| sub_empty_cons g : sub_empty g -> sub_empty (None :: g).\n\n#[global] Hint Constructors sub_empty : core.\n\n\nLemma sub_empty_app t g : sub_empty g -> sub_app g t = t.\nProof.\n  generalize dependent g. induction t;intros;simpl;f_equal;eauto.\n\n  generalize dependent g. generalize dependent (var i).\n  induction i;intros; inversion H; simpl; eauto.\nQed.\n", "meta": {"author": "pa-ba", "repo": "Rattus-coq", "sha": "4c983c75ffb7c28098298c60466008f03a6a1517", "save_path": "github-repos/coq/pa-ba-Rattus-coq", "path": "github-repos/coq/pa-ba-Rattus-coq/Rattus-coq-4c983c75ffb7c28098298c60466008f03a6a1517/theories/Substitutions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6750439164929248}}
{"text": "Load \"list.v\".\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\nCompute fold (fun x y => x + y) [1;2;3] 0.\nCheck fold (fun x y => x + y) [1;2;3] 0. (* X = Y *)\n\nCompute fold cons [1;2;3] []. (* X = nat, Y = list nat *)\nCheck fold cons [1;2;3] [].\nCheck cons.", "meta": {"author": "FengZiGG", "repo": "coqlf", "sha": "73aea6d263b0e05d8e25c5ce1f6609faf8e3956c", "save_path": "github-repos/coq/FengZiGG-coqlf", "path": "github-repos/coq/FengZiGG-coqlf/coqlf-73aea6d263b0e05d8e25c5ce1f6609faf8e3956c/4_Poly/13_fold_types_different.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6750439110581913}}
{"text": "Require Import Coq.Logic.Classical.\n\nSection Classical_Predicates.\n\n(* Reset Initial *)\n\nVariables A B : Set.\n\n(* These are essentially just functions in Coq *)\nVariables P Q : A -> Prop.\n\n(* We can also use Relations between elements of a set or sets. *)\nVariable R : A -> B -> Prop.\n\n(* to say that all elements of A have a property P we write *)\nLemma allAhaveP : forall x:A, P x.\nAdmitted.\n\nVariable PP : Prop.\n\n(* All of A have property PP possibly containing x:A *)\nLemma allAhavePP : forall x:A, PP.\nAdmitted.\n\n(* Any element of A which has P also has Q, a clever student is also funny :) *)\nLemma allAwPalsoQ : forall x:A, P x -> Q x.\nAdmitted.\n\n(* If all A have P, all A with P also have Q, then all A have Q. *)\nLemma allAhaveQ : (forall  x:A, P x) -> (forall x:A, P x -> Q x) -> forall x:A, Q x.\nProof.\nintros H1 H2.\nintro a.\napply H2.\napply H1.\nQed.\n\nLemma ex_from_forall : (exists x:A, P x) <-> ~ forall x:A, ~ P x.\nProof.\nsplit.\n(* proving -> *)\nintro ex.\nintro H.\ndestruct ex as [a p].\nassert (npa : ~ (P a)).\napply H.\napply npa.\napply p.\n(* proving <- *)\nintro H.\napply NNPP.\nintro nex.\napply H.\nintros a p.\napply nex.\nexists a.\nexact p.\nQed.\n\nEnd Classical_Predicates.\n\n\n(* Parno's 2008 HotSec paper *)\n\nSection Cuckoo.\n\n(* we have sets Person, Computers, TPMs *)\nVariables P C T : Set.\n\n(* Properties of P's *)\nVariables TrustedPerson  : P -> Prop.\n\n(* Properties of C's *)\nVariables TrustedC PhysSecure : C -> Prop.\n\n(* Properties of TPMs *)\nVariables TrustedT : T -> Prop.\n\n(* Relations of P and C *)\nVariables SaysSecure : P -> C -> Prop.\n\n(* Relations of T and C *)\nVariables On : T -> C -> Prop.\n\n(* Relations of C and T *)\nVariables CompSaysOn : C -> T -> Prop.\n\n(* Relevant axioms of the trusted system are encoded here *)\n\n(* If a trusted person says so, it is so ... *)\nHypothesis rule1 : forall (p:P) (c:C), TrustedPerson p /\\ SaysSecure p c -> PhysSecure c.\n\n(* A TPM on an insecure system can't be trusted *)\nHypothesis rule2 : forall (t:T) (c:C), On t c /\\ ~PhysSecure c -> ~TrustedT t.\n\n(* A TPM on a secure system is a trusted *)\nHypothesis rule3 : forall (t:T) (c:C), On t c /\\ PhysSecure c -> TrustedT t.\n\n(* A computer with a trusted TPM can be trusted *)\nHypothesis rule4 : forall (t:T) (c:C), On t c /\\ TrustedT t -> TrustedC c.\n\n(* A computer with an untrusted TPM can't be trusted *)\nHypothesis rule5 : forall (t:T) (c:C), On t c /\\ ~TrustedT t -> ~TrustedC c.\n\n(* The TPM indicated by the computer is the computers TPM. *)\nHypothesis rule6 : forall (c:C) (t:T), CompSaysOn c t -> On t c.\n\n(* Now we encode the assumptions we make about the trust establishment *)\n\nVariable alice : P. (* Alice *)\nVariable c : C. (* Alice's computer *)\nVariable m : C. (* Adversaries machien *)\nVariable tpmm : T. (* Adversaries tpmm *)\n\n(* Alice trusts herself *)\nHypothesis ass1 : TrustedPerson alice.\n(* Alice says her computer is secure *)\nHypothesis ass2 : SaysSecure alice c.\n(* Adversary controls TPMm on M *)\nHypothesis ass3 : On tpmm m.\n(* M is not secure *)\nHypothesis ass4 : ~PhysSecure m.\n(* Malware causes Alice's computer to say that TPMm is installed *)\nHypothesis ass5 : CompSaysOn c tpmm.\n\n\n(* computer C is secure *)\nTheorem CisSecure : TrustedPerson alice /\\ SaysSecure alice c -> PhysSecure c.\nProof.\n  apply rule1.\nQed.\n\n(* Provable with all assumptions ... *)\nTheorem PhysSecureC : \n  TrustedPerson alice /\\ \n  SaysSecure alice c /\\ \n  On tpmm m /\\ \n  ~PhysSecure m /\\ \n  CompSaysOn c tpmm -> TrustedC c.\nProof.\n  intro H.\n  assert (TrustedPerson alice /\\ SaysSecure alice c -> PhysSecure c).\n    - intro H0. apply rule1 in H0. exact H0.\n    - Abort.\n\n(* TPM is on C *)\nTheorem TPMmONc : PhysSecure c /\\ CompSaysOn c tpmm -> On tpmm c.\nProof.\n  intro H.\n  destruct H.\n  apply rule6 in H0.\n  exact H0.\nQed.\n\n(* This lets us know that tpmm is on c *)\nLemma TonC : CompSaysOn c tpmm -> On tpmm c.\nProof.\n  apply rule6.\nQed.\n\n(* tpmm is trusted *)\nLemma TPM_trusted : On tpmm c /\\ PhysSecure c -> TrustedT tpmm.\nProof.\n  apply rule3.\nQed.\n\n(* C is trusted *)\nLemma C_trusted : On tpmm c /\\ TrustedT tpmm -> TrustedC c.\nProof.\n  apply rule4.\nQed.\n\n(* TPM can't be trusted *)\nLemma TPM_not_trusted : On tpmm m /\\ ~PhysSecure m -> ~TrustedT tpmm.\nProof.\n  apply rule2.\nQed.\n\nLemma C_not_trusted : On tpmm c /\\ ~TrustedT tpmm -> ~TrustedC c.\nProof.\n  apply rule5.\nQed.\n\n(* C_trusted and C_not_trusted ! *)\n\nEnd Cuckoo.\n\n\n\n\n\n\n", "meta": {"author": "hagenlauer", "repo": "GoldeneyeAttack", "sha": "09aaa21a0efe6e5795ec0d698c22d82397f712d7", "save_path": "github-repos/coq/hagenlauer-GoldeneyeAttack", "path": "github-repos/coq/hagenlauer-GoldeneyeAttack/GoldeneyeAttack-09aaa21a0efe6e5795ec0d698c22d82397f712d7/Cuckoo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.674995046329773}}
{"text": "Require Import BigO.Notation.\nRequire Import BigO.Util.DecField.\nRequire Import MathClasses.interfaces.abstract_algebra.\nRequire Import MathClasses.interfaces.vectorspace.\nRequire Import MathClasses.interfaces.orders.\n\nSection BigThetaReflexive.\n  Context `{SemiNormedSpace K V}.\n  Context `{SemiNormedSpace K W}.\n  Context `{!FullPseudoSemiRingOrder Kle Klt}.\n\n  Lemma big_Theta_refl : reflexive (V → W) big_Theta.\n    unfold reflexive.\n    intros f.\n    unfold big_Theta.\n    split.\n    { (* big_O x x *)\n      unfold big_O.\n      exists 1. (* our constant k *)\n      split.\n       - exact zero_lt_one_dec.\n       - exists 1. (* our constant *)\n        intros.\n        split.\n         * exact zero_lt_one_dec.\n         * intros n' one_leq_n.\n           rewrite left_identity.\n           apply reflexivity.\n    }\n\n    { (* big_Omega x x *)\n      unfold big_Omega.\n      exists 1. (* our constant *)\n      split.\n       - exact zero_lt_one_dec.\n       - exists 1. (* our constant *)\n         split.\n         * exact zero_lt_one_dec.\n         * intros n' one_leq_n.\n           now rewrite left_identity.\n    }\n  Qed.\nEnd BigThetaReflexive.", "meta": {"author": "langston-barrett", "repo": "coq-big-o", "sha": "8042cc068b02574ac94de469a55a9f89268616c3", "save_path": "github-repos/coq/langston-barrett-coq-big-o", "path": "github-repos/coq/langston-barrett-coq-big-o/coq-big-o-8042cc068b02574ac94de469a55a9f89268616c3/src/Equivalence/Reflexivity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.674995034198134}}
{"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 drop (drop_arg0 : natural) (drop_arg1 : lst) : lst\n           := match drop_arg0, drop_arg1 with\n              | x, Nil => Nil\n              | Zero, x => x\n              | Succ x, Cons y z => drop x z\n              end.\n\n(* No helper lemma needed. *)\nTheorem theorem0 : forall (v : natural) (w : natural) (x : natural) (y : natural) (z : lst),\n  eq (drop (Succ v) (drop (Succ w) (Cons x (Cons y z)))) (drop (Succ v) (drop w (Cons x z))).\nProof.\nintros. assert (forall n x l, drop (Succ n) (Cons x l) = drop n l). \n  - intros. reflexivity.\n  - rewrite H. induction w.\n    + rewrite H. rewrite H. reflexivity.\n    + reflexivity.\nQed. \n\n", "meta": {"author": "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/goal55.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6749496520450647}}
{"text": "Require Import ZArith.\n\nModule NaiveLang.\n  Definition expr := (nat -> option Z) -> Prop.\n  Definition context := expr -> Prop.\n  Definition impp (e1 e2 : expr) : expr := fun st => e1 st -> e2 st.\n  Definition andp (e1 e2 : expr) : expr := fun st => e1 st /\\ e2 st.\n  Definition orp  (e1 e2 : expr) : expr := fun st => e1 st \\/ e2 st.\n  Definition falsep : expr := fun st => False.\n  Definition coq_prop (P: Prop): expr := fun _ => P.\n\n  Definition join : (nat -> option Z) -> (nat -> option Z) -> (nat -> option Z) -> Prop :=\n    fun x y z =>\n      forall p: nat,\n       (exists v, x p = Some v /\\ y p = None /\\ z p = Some v) \\/\n       (exists v, x p = None /\\ y p = Some v /\\ z p = Some v) \\/\n       (x p = None /\\ y p = None /\\ z p = None).\n  Definition sepcon (e1 e2 : expr) : expr := fun st =>\n    exists st1 st2, join st1 st2 st /\\ e1 st1 /\\ e2 st2.\n  Definition wand (e1 e2 : expr) : expr := fun st =>\n    forall st1 st2, join st st1 st2 -> e1 st1 -> e2 st2.\n  Definition emp : expr := fun st =>\n    forall p, st p = None.\n  Definition corable (e: expr): Prop := forall s1 s2, e s1 <-> e s2.\n  \n  Definition provable (e : expr) : Prop := forall st, e st.\nEnd NaiveLang.\n\nRequire Import interface_5.\n\nModule NaiveRule.\n  Include DerivedNames (NaiveLang).\n  Lemma modus_ponens :\n    forall x y : expr, provable (impp x y) -> provable x -> provable y.\n  Proof. unfold provable, impp. auto. Qed.\n\n  Lemma axiom1 : forall x y : expr, provable (impp x (impp y x)).\n  Proof. unfold provable, impp. auto. Qed.\n\n  Lemma axiom2 : forall x y z : expr,\n      provable (impp (impp x (impp y z)) (impp (impp x y) (impp x z))).\n  Proof. unfold provable, impp. auto. Qed.\n\n  Lemma andp_intros :\n    forall x y : expr, provable (impp x (impp y (andp x y))).\n  Proof. unfold provable, impp, andp. auto. Qed.\n\n  Lemma andp_elim1 : forall x y : expr, provable (impp (andp x y) x).\n  Proof. unfold provable, impp, andp. tauto. Qed.\n\n  Lemma andp_elim2 : forall x y : expr, provable (impp (andp x y) y).\n  Proof. unfold provable, impp, andp. tauto. Qed.\n\n  Lemma orp_intros1 : forall x y : expr, provable (impp x (orp x y)).\n  Proof. unfold provable, impp, orp. auto. Qed.\n\n  Lemma orp_intros2 : forall x y : expr, provable (impp y (orp x y)).\n  Proof. unfold provable, impp, orp. auto. Qed.\n\n  Lemma orp_elim : forall x y z : expr,\n      provable (impp (impp x z) (impp (impp y z) (impp (orp x y) z))).\n  Proof. unfold provable, impp, orp. tauto. Qed.\n\n  Lemma falsep_elim : forall x : expr, provable (impp falsep x).\n  Proof. unfold provable, impp, falsep. destruct 1. Qed.\n\n  Lemma peirce_law : forall x y: expr, provable (impp (impp (impp x y) x) x).\n  Proof. unfold provable, impp. intros; tauto. Qed.\n\n  Lemma coq_prop_intros : (forall P : Prop, P -> provable (coq_prop P)) .\n  Proof. unfold provable, coq_prop. intros; tauto. Qed.\n  \n  Lemma coq_prop_elim : (forall (P : Prop) (x : expr), (P -> provable x) -> provable (impp (coq_prop P) x)) .\n  Proof. unfold provable, impp, coq_prop. intros; auto. Qed.\n    \n  Lemma coq_prop_impp : (forall P Q : Prop, provable (impp (impp (coq_prop P) (coq_prop Q)) (coq_prop (P -> Q)))) .\n  Proof. unfold provable, impp, coq_prop. intros; auto. Qed.\n  \n  Axiom sepcon_comm: forall x y, provable (iffp (sepcon x y) (sepcon y x)).\n  Axiom sepcon_assoc: forall x y z,\n      provable (iffp (sepcon x (sepcon y z)) (sepcon (sepcon x y) z)).\n  Axiom sepcon_mono : (forall x1 x2 y1 y2 : expr, provable (impp x1 x2) -> provable (impp y1 y2) -> provable (impp (sepcon x1 y1) (sepcon x2 y2))) .\n  Axiom sepcon_emp : (forall x : expr, provable (iffp (sepcon x emp) x)) .\n  Axiom falsep_sepcon_left : (forall x : expr, provable (impp (sepcon falsep x) falsep)) .\n  Axiom orp_sepcon_left : (forall x y z : expr, provable (impp (sepcon (orp x y) z) (orp (sepcon x z) (sepcon y z)))) .\n  Axiom corable_coq_prop : (forall P : Prop, corable (coq_prop P)) .\n  Axiom corable_preserved' : (forall x y : expr, provable (iffp x y) -> corable x -> corable y) .\n  Axiom corable_andp_sepcon1 : (forall x y z : expr, corable x -> provable (iffp (sepcon (andp x y) z) (andp x (sepcon y z)))) .\n  Axiom wand_sepcon_adjoint : (forall x y z : expr, provable (impp (sepcon x y) z) <-> provable (impp x (wand y z))) .\nEnd NaiveRule.\n\nModule T := LogicTheorem NaiveLang NaiveRule.\nModule Solver := IPSolver NaiveLang.\nImport T.\nImport Solver.\n\n\nRequire Import ExportSolvers.Normalize.\n\nNotation \"|--  x\" := (provable x) (at level 71, no associativity) : syntax.\nNotation \"'!!' e\" := (coq_prop e) (at level 25) : syntax.\nNotation \"x && y\" := (andp x y) (at level 40, left associativity) : syntax.\nNotation \"x <--> y\" := (iffp x y) (at level 60, no associativity) : syntax.\nNotation \"x --> y\" := (impp x y) (at level 55, right associativity) : syntax.\nNotation \"x * y\" := (sepcon x y) (at level 40, left associativity) : syntax.\n\nModule Normalize := ExportTactic T.\nImport Normalize.\nLocal Open Scope syntax.\nGoal forall x y z (P: Prop), |-- (!! P && x) * y * z --> (!! P && x) * (!! P && y) * (!! P && z).\nProof.\n  intros.\n  repeat normalize.\nAbort.\n\n", "meta": {"author": "QinxiangCao", "repo": "LOGIC", "sha": "d1476d57345c87447ea500b3d5ea99ee6d0f6863", "save_path": "github-repos/coq/QinxiangCao-LOGIC", "path": "github-repos/coq/QinxiangCao-LOGIC/LOGIC-d1476d57345c87447ea500b3d5ea99ee6d0f6863/LogicGenerator/demo/implementation_5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6749496284422151}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n\n(****************************************************************************)\n(*                                                                          *)\n(*                Computing a BDT coding the prime implicants               *)\n(*      (also called minimal solutions) of a function given by its BDT      *)\n(*                                                                          *)\n(*            Algorithm designed by A.Rauzy of LaBRI Bordeaux               *)\n(*                    restricted to monotonic functions                     *)\n(*                                                                          *)\n(****************************************************************************)\n(*                                 Primes.v                                 *)\n(****************************************************************************)\n\nRequire Import Prelude_BDT.\nRequire Import CanonBDDs.rauzy.algorithme1.Boolean_functions.\nRequire Import CanonBDDs.rauzy.algorithme1.BDTs.\nRequire Import Prelude_Paths.\nRequire Import Prelude_Implicants.\nRequire Import Prelude_Primes.\nRequire Import Operator_W.\nRequire Import Monotony.\n\n\n(*--------------------------------------------------------------------------*)\n(*                Specification of procedures computing Primes      \n   An algorithm A is correct iff A(b) is Sound and Complete with respect to b\n   for all BDT b. Notation: (Sound b A(b))/\\(Complete b A(b))               *)\n(*--------------------------------------------------------------------------*)\n \nDefinition Sound (b1 b2 : BDT) :=\n  forall p : Path, Solution p b2 -> Prime p (Fun b1).\nDefinition Complete (b1 b2 : BDT) :=\n  forall p : Path, Prime p (Fun b1) -> Solution p b2.\nDefinition Correct (b1 b2 : BDT) := Sound b1 b2 /\\ Complete b1 b2.\n\n\nHint Unfold Correct.\n\n\n(*---------       Needed properties of the specification         ------------*)\n\nLemma LC2_S_fac1 :\n forall p1 b1 : BDT,\n Sound b1 p1 ->\n forall b2 b3 : BDT,\n W_sound p1 b2 b3 -> forall p : Path, Solution p b3 -> Prime p (Fun b1).\nProof.\nintros p1 b1 Def_p1 b2 b3 Def_b3 p Def_p.\nunfold W_sound in Def_b3.\nunfold Sound in Def_p1.\napply Def_p1; elim (Def_b3 p Def_p); trivial with arith.\nQed.\n\n\nLemma LC2_C_fac1 :\n forall pb1 b1 : BDT,\n Complete b1 pb1 ->\n forall b2 b3 : BDT,\n W_complete pb1 b2 b3 ->\n forall p : Path,\n Prime p (Fun b1) ->\n ~ Implicant p (Fun b2) -> exists p' : Path, Solution p' b3 /\\ Divides p' p.\nProof.\nintros pb1 b1 Def_pb1 b2 b3 Def_b3 p H1p H2p.\nunfold W_complete in Def_b3.\nunfold Complete in Def_pb1.\nexact (Def_b3 p (Def_pb1 p H1p) H2p).\nQed.\n\n\nLemma Zero_complete : forall b : BDT, OBDT b -> Complete b Zero -> b = Zero.\nProof.\nintros b Hb.\nelim (eq_BDT_decidable b Zero); intro Cas.\nelim Cas; trivial with arith.\nunfold Complete in |- *; intro H.\nelim (Prime_exists b Hb Cas); intros p Def_p.\nabsurd (Solution p Zero); [ exact (No_solution_Zero p) | exact (H p Def_p) ].\nQed.\n\n\n\n(*--------------------------------------------------------------------------*)\n(*                  Rauzy's solution for A based on Operaor W               *)\n(*             \n        A(Zero)= Zero                               (E1)\n        A(One) = One                                (E2)\n        A(Node(i,l,r)) = Node(i,W(A(l),r),A(r))     (E3)\n                                                                            *)\n(*--------------------------------------------------------------------------*)\n\n\n(*--------------        Correctness equations E1 and E2        --------------*)\n\nLemma BDT2_of_Zero : Sound Zero Zero /\\ Complete Zero Zero.\nProof.\nsplit.\n(* Soundness *)\nunfold Sound in |- *.\nintros p H_absurde.\nabsurd (Solution p Zero); [ exact (No_solution_Zero p) | assumption ].\n(* Completeness *)\nunfold Complete in |- *; simpl in |- *.\nintros p H_absurde.\nabsurd (Prime p FALSE); [ exact (No_prime_FALSE p) | assumption ].\nQed.\n\n\nLemma BDT2_of_One : Sound One One /\\ Complete One One.\nProof.\nsplit.\n(* Soundness *)\nunfold Sound in |- *.\nintros p Def_p; unfold Prime in |- *.\nsplit.\napply Implicants_TRUE.\napply Solution_OBDT_ordered with One; trivial with arith.\nintros p' H1_p' H2_p'.\nrewrite (Solution_of_One_is_Nil p Def_p).\nexact (Nil_divides_all p').\n(* Completeness *)\nunfold Complete in |- *; simpl in |- *.\nintros p Def_p.\nrewrite (Nil_only_prime_of_TRUE p Def_p).\nexact Sol_One.\nQed.\n\n\n(*---------------------------------------------------------------------------*)\n(*----------            Correctness of equation E3               ------------*)\n(*---------------------------------------------------------------------------*)\n\n\nSection Case_recursion.\n\nVariable i : nat.\nVariable l r : BDT.\n\nHypothesis HO : OBDT (Node i l r).\nHint Resolve HO.\n\nVariable pl pr : BDT.\n\nHypothesis HOpl : OBDT pl.\nHint Resolve HOpl.\n\nHypothesis HOpr : OBDT pr.\nHint Resolve HOpr.\n\nHypothesis HDpl : Dim pl <= Dim l.\nHint Resolve HDpl.\n\nHypothesis HDpr : Dim pr <= Dim r.\nHint Resolve HDpr.\n\nVariable w : BDT.\n\nHypothesis HOw : OBDT w.\nHint Resolve HOw.\n\nHypothesis HDw : Dim w <= Dim pl.\nHint Resolve HDw.\n\n\n(*--------   Proof of the correctness of the optimisation    -------*)\n(*                   No need to check left=right                    *)\n\nLemma Result_Ordered :\n Correct l pl -> Correct r pr -> W_correct pl r w -> OBDT (Node i w pr).\nProof.\nintros HCpl HCpr HCw.\napply order_node; auto with arith.\napply gt_le_trans with (Dim l);\n [ elim (dim_node_dim_sons i l r); auto with arith\n | apply le_trans with (Dim pl); auto with arith ].\napply gt_le_trans with (Dim r);\n [ elim (dim_node_dim_sons i l r); auto with arith | auto with arith ].\n(*---- ~w=pr -----*)\nunfold not in |- *; intro Habsurde.\nelim (LT1 w HOw); intro Hcas.\n   (* Case w = Zero  *)\nabsurd (OBDT (Node i l r)); auto with arith.\napply Contra with (l = r);\n [ intro H; clear H | apply ordered_node_neq_sons with i; auto with arith ].\napply (trans_equal (A:=BDT)) with Zero.\napply Zero_complete;\n [ elim (ordered_node_ordered_sons i l r HO); trivial with arith | idtac ].\nelim (LP2 pl HOpl); [ elim HCpl; auto with arith | idtac ].\npattern Zero at 2 in |- *; elim Hcas.\nelim (Zero_complete r);\n [ elim HCw; trivial with arith\n | elim (ordered_node_ordered_sons i l r HO); trivial with arith\n | elim Hcas; rewrite Habsurde; elim HCpr; trivial with arith ].\nsymmetry  in |- *; apply Zero_complete;\n [ elim (ordered_node_ordered_sons i l r HO); trivial with arith\n | elim Hcas; rewrite Habsurde; elim HCpr; trivial with arith ].\n   (* Case w=/=Zero *)\nelim Hcas; intros p Def_p. \nabsurd (Implicant p (Fun r)). \nelim HCw; unfold W_sound in |- *; intros HCSw HCCw.\nelim (HCSw p Def_p); trivial with arith.\napply Prime_implicant.\nelim HCpr; unfold Sound in |- *; intros HCSpr HCCpr.\napply HCSpr; elim Habsurde; assumption.\nQed.\n\nLemma Soundness_right :\n Sound l pl ->\n Sound r pr ->\n W_sound pl r w ->\n forall p : Path, Solution p pr -> Prime p (Fun (Node i l r)).\nProof.\nintros HSpl HSpr HSw p Def_p.\nunfold Sound in HSpr.\nunfold Prime in |- *; split.\n(*  Implicant *)\napply L10; [ idtac | auto with arith ].\napply Gt_dim_out_of_solution with pr; [ assumption | auto with arith | idtac ].\napply gt_le_trans with (Dim r);\n [ elim (dim_node_dim_sons i l r HO); trivial with arith | auto with arith ].\n(*  Smallest  *)\nintros p' H1p' H2p'.\nelim (HSpr p Def_p); intros Hp_Impl Hp_Smallest. \napply Hp_Smallest; [ idtac | assumption ].\napply (L5 i l r p' H1p').\napply L80 with p; [ assumption | idtac ].\napply Gt_dim_out_of_solution with pr; [ assumption | auto with arith | idtac ].\napply gt_le_trans with (Dim r);\n [ elim (dim_node_dim_sons i l r HO); trivial with arith | auto with arith ].\nQed.\n\nLemma Soundness_left_impl :\n Sound l pl ->\n W_sound pl r w ->\n forall tl : Path,\n Solution tl w ->\n forall p : Path, p = Cons i tl -> Implicant p (Fun (Node i l r)).\nProof.\nintros HSpl HSw tl Def_tl p Def_p.\nrewrite Def_p; apply (L2 i l r HO tl).\napply Prime_implicant.\nexact (LC2_S_fac1 pl l HSpl r w HSw tl Def_tl).\napply gt_le_trans with (Dim w);\n [ idtac | apply Head_of_solution_le_dim; auto with arith ].\napply gt_le_trans with (Dim l);\n [ elim (dim_node_dim_sons i l r HO); trivial with arith\n | apply le_trans with (Dim pl); auto with arith ].\nQed.\n\n\nLemma Soundness_left_smallest_order :\n forall tl : Path, Solution tl w -> Ordered (Cons i tl).\nProof.\nintros tl Def_tl.\napply Cons_ordered; [ exact (Solution_OBDT_ordered w tl Def_tl HOw) | idtac ].\napply gt_le_trans with (Dim l);\n [ elim (dim_node_dim_sons i l r HO); trivial with arith\n | apply le_trans with (Dim w);\n    [ exact (Head_of_solution_le_dim tl w Def_tl HOw)\n    | apply le_trans with (Dim pl); auto with arith ] ].\nQed.\n\n\nLemma Soundness_left_smallest_in :\n Correct l pl ->\n Correct r pr ->\n W_correct pl r w ->\n forall tl : Path,\n Solution tl w ->\n forall p : Path,\n p = Cons i tl ->\n forall p' : Path,\n Implicant p' (Fun (Node i l r)) -> Divides p' p -> Of i p' -> Divides p p'.\nProof.\nintros HCpl HCpr HCw tl Def_tl p Def_p.\nelim HCpl; intros HCSpl HCCpl.\nelim HCpr; intros HCSpr HCCpr.\nelim HCw; intros HCSw HCCw.\nintros p' H1p' H2p' Hi.\nrewrite Def_p.\nelim (Tail_exists_with_dim_head i w pr) with p p';\n [ intros tl' Def_p'; rewrite Def_p'\n | exact (Result_Ordered HCpl HCpr HCw)\n | rewrite Def_p; auto with arith\n | elim (inv_Implicant p' (Fun (Node i l r)) H1p'); auto with arith\n | assumption\n | assumption ].\napply Divides_tail_divides_cons;\n elim (LC2_S_fac1 pl l HCSpl r w HCSw tl Def_tl); intros H1tl H2tl.\napply H2tl; [ apply (L40 i l r HO tl'); elim Def_p'; assumption | idtac ].\napply Divides_cons_divides_tail with i;\n [ elim Def_p'; elim (inv_Implicant p' (Fun (Node i l r)) H1p');\n    trivial with arith\n | exact (Soundness_left_smallest_order tl Def_tl)\n | elim Def_p'; elim Def_p; assumption ].\nQed.\n\n\nLemma Soundness_left_smallest_out :\n Monotonic (Fun (Node i l r)) ->\n Correct l pl ->\n Correct r pr ->\n W_correct pl r w ->\n forall tl : Path,\n Solution tl w ->\n forall p : Path,\n p = Cons i tl ->\n forall p' : Path,\n Implicant p' (Fun (Node i l r)) -> Divides p' p -> ~ Of i p' -> Divides p p'.\nProof.\nintros Hmon HCpl HCpr HCw tl Def_tl p Def_p.\nelim HCpl; intros HCSpl HCCpl.\nelim HCpr; intros HCSpr HCCpr.\nelim HCw; intros HCSw HCCw.\nintros p' H1p' H2p' Hi.\nabsurd (Implicant tl (Fun r)).\nunfold W_sound in HCSw.\nelim (HCSw tl Def_tl); trivial with arith.\napply (L9 p');\n [ apply (L8 p' tl i); [ elim Def_p; assumption | assumption ]\n | idtac\n | exact (Solution_OBDT_ordered w tl Def_tl HOw)\n | exact (L5 i l r p' H1p' Hi) ].\nelim (LC2_S_fac1 pl l HCSpl r w HCSw tl Def_tl); intros H1tl H2tl.\napply H2tl;\n [ idtac | apply (L8 p' tl i); [ elim Def_p; assumption | assumption ] ].\napply (L15 i l r HO Hmon); [ idtac | exact (L5 i l r p' H1p' Hi) ].\napply (Pth_ord9 i tl);\n [ exact (Soundness_left_smallest_order tl Def_tl)\n | elim (inv_Implicant p' (Fun (Node i l r)) H1p'); trivial with arith\n | apply (L8 p' tl i); [ elim Def_p; assumption | assumption ] ].\nQed.\n\n\nLemma Soundness_left :\n Monotonic (Fun (Node i l r)) ->\n Correct l pl ->\n Correct r pr ->\n W_correct pl r w ->\n forall tl : Path,\n Solution tl w ->\n forall p : Path, p = Cons i tl -> Prime p (Fun (Node i l r)).\nProof.\nintros Hmon HCpl HCpr HCw tl Def_tl p Def_p.\nelim HCpl; intros HCSpl HCCpl.\nelim HCpr; intros HCSpr HCCpr.\nelim HCw; intros HCSw HCCw.\nunfold Sound in HCSpr.\nunfold Prime in |- *; split.\n(*----- Implicant -----*)\nexact (Soundness_left_impl HCSpl HCSw tl Def_tl p Def_p).\n(*----- Smallest  -----*)\nintros p' H1p' H2p'.\nelim (Of_path_dec p' i); intro Hi.\n          (*   i in p'   *)\nexact\n (Soundness_left_smallest_in HCpl HCpr HCw tl Def_tl p Def_p p' H1p' H2p' Hi).\n          (*  i out of p'  *)\nexact\n (Soundness_left_smallest_out Hmon HCpl HCpr HCw tl Def_tl p Def_p p' H1p'\n    H2p' Hi).\nQed.\n\n\nLemma Soundness :\n Monotonic (Fun (Node i l r)) ->\n Correct l pl ->\n Correct r pr -> W_correct pl r w -> Sound (Node i l r) (Node i w pr).\nProof.\nintros Hmon HCpl HCpr HCw.\nelim HCpl; intros HCSpl HCCpl.\nelim HCpr; intros HCSpr HCCpr.\nelim HCw; intros HCSw HCCw.\nunfold Sound in |- *.\nintros p Def_p.\nelim (p_inv_Solution p (Node i w pr) Def_p).\n(*  Case right (Solution p pr) *)\nintro Cas_def_p.\nexact (Soundness_right HCSpl HCSpr HCSw p Cas_def_p).\n(*  Case left p=(Cons i tl) /\\ (Solution tl w) *)\nsimple induction 1; intro tl; simple induction 1; intros H1tl H2tl; clear H0.\nexact (Soundness_left Hmon HCpl HCpr HCw tl H1tl p H2tl).\nQed.\n\n\nLemma Completness :\n Correct l pl ->\n Correct r pr -> W_correct pl r w -> Complete (Node i l r) (Node i w pr).\nProof.\nintros HCpl HCpr HCw.\nelim HCpl; intros HCSpl HCCpl.\nelim HCpr; intros HCSpr HCCpr.\nelim HCw; intros HCSw HCCw.\nunfold Complete in |- *.\nintros p Def_p.\nelim (Of_path_dec p i); intro Hi.\n(*----- Case  (Of i p) -----*)\nelim (L4bis i l r HO p Def_p Hi); intro tl; simple induction 1;\n intros H1tl H2tl; clear H.\nrewrite H1tl; apply Sol_Left.\nelim (LC2_C_fac1 pl l HCCpl r w HCCw tl H2tl);\n [ intro tl'; simple induction 1; intros H1tl' H2tl'; clear H\n | apply (L12 i l r); elim H1tl; exact Def_p ].\nelim (Ordered_paths_eq tl' (Solution_OBDT_ordered w tl' H1tl' HOw) tl);\n [ exact H1tl'\n | elim (inv_Implicant tl (Fun l) (Prime_implicant tl (Fun l) H2tl));\n    trivial with arith\n | exact H2tl'\n | idtac ]. \nelim H2tl; intros H2tl_impl H2tl_smallest; clear H2tl.\napply H2tl_smallest;\n [ exact\n    (Prime_implicant tl' (Fun l) (LC2_S_fac1 pl l HCSpl r w HCSw tl' H1tl'))\n | exact H2tl' ].\n(*---- Case ~(Of i p) ------*)\napply Sol_Right.\nunfold Complete in HCCpr; apply HCCpr.\nexact (L5bis i l r p Def_p Hi).\nQed.\n\n\nLemma Correctness :\n Monotonic (Fun (Node i l r)) ->\n Correct l pl ->\n Correct r pr -> W_correct pl r w -> Correct (Node i l r) (Node i w pr).\nProof.\nintros Hmon HCpl HCpr HCw.\nunfold Correct in |- *; split.\nexact (Soundness Hmon HCpl HCpr HCw).\nexact (Completness HCpl HCpr HCw).\nQed.\n\nEnd Case_recursion.\n\n\n(*--------------------------------------------------------------------------*)\n(*             Proof-programming of the algorithm computing a BDT           *)\n(*        coding the primes of a boolean function defined by its BDT        *)\n(*--------------------------------------------------------------------------*)\n\n \nTheorem Existence_BDT2 :\n forall b1 : BDT,\n OBDT b1 ->\n Monotonic (Fun b1) ->\n {b2 : BDT | OBDT b2 /\\ Dim b2 <= Dim b1 /\\ Correct b1 b2}.\nProof.\n(*----- Structural recursion on b1  ----*)\nsimple induction b1; clear b1.\nintros.\n(*---- if b1 = Zero  then b2 = Zero ----*)\nexists Zero.\nsplit;\n [ trivial with arith | split; [ trivial with arith | exact BDT2_of_Zero ] ].\nintros.\n(*---- if b1 = One  then b2 = One  ----*)\nexists One.\nsplit; [ trivial with arith | split; [ trivial with arith | exact BDT2_of_One ] ].\n(*---- if b1 = (Node i1 h1 l1) then  .... *)\nintros i1 l1 Hrec_l1 r1 Hrec_r1 Node_orded Node_monotonic.\nelim Hrec_l1;\n [ intros Prm_l1 Def_Prm_l1; clear Hrec_l1\n | elim (ordered_node_ordered_sons i1 l1 r1 Node_orded); trivial with arith\n | elim (Mon_node_Mon_sons i1 l1 r1 Node_orded Node_monotonic);\n    trivial with arith ].\nelim Def_Prm_l1; intro HO_Prm_l1.\nsimple induction 1; intros HD_Prm_l1 HCorr_Prm_l1; clear H.\nelim Hrec_r1;\n [ intros Prm_r1 Def_Prm_r1; clear Hrec_r1\n | elim (ordered_node_ordered_sons i1 l1 r1 Node_orded); trivial with arith\n | elim (Mon_node_Mon_sons i1 l1 r1 Node_orded Node_monotonic);\n    trivial with arith ].\nelim Def_Prm_r1; intro HO_Prm_r1.\nsimple induction 1; intros HD_Prm_r1 HCorr_Prm_r1; clear H.\nclear Def_Prm_r1; clear Def_Prm_l1.\nelim (Existence_Op_W Prm_l1 r1);\n [ intros Prm_l1_W_r1 Correctness_W\n | assumption\n | elim (ordered_node_ordered_sons i1 l1 r1 Node_orded); trivial with arith\n | elim (Mon_node_Mon_sons i1 l1 r1 Node_orded Node_monotonic);\n    trivial with arith ].\nelim Correctness_W; intro HO_Prm_l1_W_r1.\nsimple induction 1; intros HD_Prm_l1_W_r1 HCorr_Prm_l1_W_r1; clear H.\nclear Correctness_W.\n   (*   ..... b2 = (Node i1 Prm_l1_W_r1 Prm_r1)  ... *) \nexists (Node i1 Prm_l1_W_r1 Prm_r1); split.\nexact\n (Result_Ordered i1 l1 r1 Node_orded Prm_l1 Prm_r1 HO_Prm_l1 HO_Prm_r1\n    HD_Prm_l1 HD_Prm_r1 Prm_l1_W_r1 HO_Prm_l1_W_r1 HD_Prm_l1_W_r1\n    HCorr_Prm_l1 HCorr_Prm_r1 HCorr_Prm_l1_W_r1).\nsplit;\n [ auto with arith\n | exact\n    (Correctness i1 l1 r1 Node_orded Prm_l1 Prm_r1 HO_Prm_l1 HO_Prm_r1\n       HD_Prm_l1 HD_Prm_r1 Prm_l1_W_r1 HO_Prm_l1_W_r1 HD_Prm_l1_W_r1\n       Node_monotonic HCorr_Prm_l1 HCorr_Prm_r1 HCorr_Prm_l1_W_r1) ].\nQed.\n", "meta": {"author": "coq-contribs", "repo": "canon-bdds", "sha": "1420af91ba2f898b70404a6600c2b87881338a0e", "save_path": "github-repos/coq/coq-contribs-canon-bdds", "path": "github-repos/coq/coq-contribs-canon-bdds/canon-bdds-1420af91ba2f898b70404a6600c2b87881338a0e/rauzy/algorithmes_2_et_3/Primes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6749496262020821}}
{"text": "Require Import Omega.\n\nLemma nat_eps (P : nat -> Prop) :\n  (forall n, { P n } + { ~ P n }) ->\n  (exists n, P n) ->\n  { n | P n }.\nProof.\n  intros HPdec Hex.\n  refine (@Fix _\n    (fun n m => S m = n /\\ (forall m, m < n -> ~ P m)) _\n    (fun n => (forall m, m < n -> ~ P m) -> { n | P n })\n    (fun n eps HnP =>\n      if HPdec n then exist _ n _\n      else eps (S n) _ _) 0 _); eauto.\n  - destruct Hex as [ n HP ]. intros m.\n    remember (n - m) as p. generalize dependent m.\n    induction p as [ | p ]; intros m Heqp; constructor; intros ? [? HnP]; subst.\n    + destruct (HnP n); eauto; omega.\n    + apply IHp. omega.\n  - split; eauto. intros m ?. destruct (Nat.eq_dec n m); subst; eauto.\n    apply HnP. omega.\n  - intros m ?. destruct (Nat.eq_dec n m); subst; eauto.\n    apply HnP. omega.\n  - intros ? ?. omega.\nDefined.\n\nTheorem eps A (P : A -> Prop) (f : nat -> A) :\n  (forall x, exists n, f n = x) ->\n  (forall x, { P x } + { ~ P x }) ->\n  (exists x, P x) ->\n  { x | P x }.\nProof.\n  intros Hsurj HPdec Hex.\n  destruct (nat_eps (fun n => P (f n))); eauto.\n  - intros. apply HPdec.\n  - destruct Hex as [ x ]. destruct (Hsurj x). subst. eauto.\nDefined.\n", "meta": {"author": "fetburner", "repo": "Misc", "sha": "c48f9166e922dee111c98157d6da45b77cda5ea6", "save_path": "github-repos/coq/fetburner-Misc", "path": "github-repos/coq/fetburner-Misc/Misc-c48f9166e922dee111c98157d6da45b77cda5ea6/Prop2Type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.7662936430859598, "lm_q1q2_score": 0.674949206498686}}
{"text": "Require Import Frap.\n\n(*\n *\n * Modeling a full-feature Imperative programming language to allow us to reason about imperative programs in Coq \n *\n *)\n\n\n(* \n * 1: Our imperative language constructs and syntax.\n *)\n\n(* natural number expression *)\nInductive exp :=\n| Const (n : nat)\n| Var (x : string)\n| ReadMem (e1 : exp)\n| Plus (e1 e2 : exp)\n| Minus (e1 e2 : exp)\n| Times (e1 e2 : exp)\n| DivBy2 (e1: exp).\n\n(* Those were the expressions of numeric type.  Here are the Boolean\n * expressions. *)\nInductive bexp :=\n| Equal (e1 e2 : exp)\n| Less (e1 e2 : exp).\n\n(* Heap allows for pointer/index based access *)\nDefinition heap := fmap nat nat.\n(* Values of variables (almost like the stack) *)\nDefinition valuation := fmap var nat.\n(* An assertion allows us to check the state of the program\n   on the heap and valuation, and see if it conforms with \n   some desired property *)\nDefinition assertion := heap -> valuation -> Prop.\n\n(* The statements in our language, these do not have a value themselves\n   but can have side effects (can make changes to the heap or valuation) *)\nInductive cmd :=\n| Skip\n| AssignVar (x : var) (e : exp)\n| AssignMem (e1 e2 : exp)\n| Seq (c1 c2 : cmd)\n| If_ (be : bexp) (then_ else_ : cmd)\n| While_ (inv : assertion) (be : bexp) (body : cmd)\n(* Think of this more as an annotation\n   something we will add to our programs that help us analyze them. *)\n| Assert (a : assertion).\n\n(* BEGIN syntax macros that won't be explained *)\n(* These allow us to override Coq's syntax with our own *)\nCoercion Const : nat >-> exp.\nCoercion Var : string >-> exp.\nNotation \"*[ e ]\" := (ReadMem e) : cmd_scope.\nInfix \"+\" := Plus : cmd_scope.\nInfix \"-\" := Minus : cmd_scope.\nInfix \"*\" := Times : cmd_scope.\nNotation \"e / '2'\" := (DivBy2 e) (at level 70) : cmd_scope.\nInfix \"=\" := Equal : cmd_scope.\nInfix \"<\" := Less : cmd_scope.\nDefinition set (dst src : exp) : cmd :=\n  match dst with\n  | ReadMem dst' => AssignMem dst' src\n  | Var dst' => AssignVar dst' src\n  | _ => AssignVar \"Bad LHS\" 0\n  end.\nInfix \"<-\" := set (no associativity, at level 70) : cmd_scope.\nInfix \";;\" := Seq (right associativity, at level 75) : cmd_scope.\nNotation \"'_if_' b '_then_' then_ '_else_' else_ '_done_'\" := (If_ b then_ else_) (at level 75, b at level 0).\nNotation \"{{ I }} '_while_' b '_loop_' body '_done_'\" := (While_ I b body) (at level 75).\nNotation \"'assert' {{ I }}\" := (Assert I) (at level 75).\nDelimit Scope cmd_scope with cmd.\n\nInfix \"+\" := plus : reset_scope.\nInfix \"-\" := Init.Nat.sub : reset_scope.\nInfix \"*\" := mult : reset_scope.\nInfix \"=\" := eq : reset_scope.\nInfix \"<\" := lt : reset_scope.\nDelimit Scope reset_scope with reset.\nOpen Scope reset_scope.\n\n(* Finite map notation: *)\n(* <map> $? <key> -> Some <value> or None if key is not in the map *)\n(* <map> $! <key> -> <value> or 0 if key is not in the map *)\n(* <map> $+ (<key>, <value>) adds (key, value) to the map *)\nNotation \"m $! k\" := (match m $? k with Some n => n | None => O end) (at level 30).\n(* END macros *)\n\n(*\n * End of 1\n *)\n\n\n\n(*\n * 2: The semantics of our programming languages: we are explaining\n *    to coq what each construct in our programming language mean\n *)\n\n(* Interpreters for nat and bool expression *)\nFixpoint eval_div2 (n: nat): nat :=\n  match n with\n  | 0 => 0\n  | S n =>\n    match n with\n    | 0 => 0 (* 1 / 2 = 0 *)\n    | S n => 1 + eval_div2 n\n    end\n  end.\n\nFixpoint eval (e : exp) (h : heap) (v : valuation) : nat :=\n  match e with\n  | Const n => n\n  | Var x => v $! x\n  | ReadMem e1 => h $! eval e1 h v\n  | Plus e1 e2 => eval e1 h v + eval e2 h v\n  | Minus e1 e2 => eval e1 h v - eval e2 h v\n  | Times e1 e2 => eval e1 h v * eval e2 h v\n  | DivBy2 e => eval_div2 (eval e h v)\n  end.\nFixpoint beval (b : bexp) (h : heap) (v : valuation) : bool :=\n  match b with\n  | Equal e1 e2 => if eval e1 h v ==n eval e2 h v then true else false\n  | Less e1 e2 => if eval e2 h v <=? eval e1 h v then false else true\nend.\n\n(* This is different than the previous problems\n   We will go through something like this in lab 3. *)\n(* This is one way of encoding what is called small step semantics. \n   Instead of using an interpreter, which has several drawbacks, including problematic\n   requirements on termination, we can use an inductive relation, to specify the meaning of the program\n   one statement at a time (hence small-step). *)\n(* This is an inductive relation of type (heap * valuation * cmd) -> (heap * valuation * cmd)\n   in other words, it *relates* two tuples together, each made out of a heap, valuation and a command\n   from our imperative language. If two such tuples are related, it means that if we are given\n   a program state matching the first tuple, a valid single step of execution of our programming language \n   will give us back a new step, matching the second tuple. *)\n(* One important advantage this kind of modeling has over interpreters is that this is a relation,\n   as opposed to a function (in the case of interpreters). This means that a single program state may\n   be related to several next-step states, which helps model things like non-determinism, randomized algorithms,\n   concurrency, and parallelism. *)\nInductive step : heap * valuation * cmd -> heap * valuation * cmd -> Prop :=\n(* Assign a value to a variable gives us a new valuation with the new value of the variable *)\n(* Notice the use of Skip as the command in the next step. This indicates that this assignment\n   statement has been consumed completely. Do not worry about sequencing or composing commands together\n   other rules here will acheive that *)\n| StAssign : forall h v x e,\n  step (h, v, AssignVar x e) (h, v $+ (x, eval e h v), Skip)\n(* AssignMem does not change the valuation, but it changes the heap *)\n| StWrite : forall h v e1 e2,\n  step (h, v, AssignMem e1 e2) (h $+ (eval e1 h v, eval e2 h v), v, Skip)\n\n(* Sequencing base case: if we have sequence (c1; c2) and c1 is skip,\n   then we can immediately go to c2. *)\n| StStepSkip : forall h v c,\n  step (h, v, Seq Skip c) (h, v, c)\n(* Sequencing recursive case: if we have sequence (c1; c2) and c1 gets us to c1'\n   then we can go to (c1'; c2), and any effects c1 had on heap and valuation are carried through. *)\n| StStepRec : forall h1 v1 c1 h2 v2 c1' c2,\n  step (h1, v1, c1) (h2, v2, c1')\n  -> step (h1, v1, Seq c1 c2) (h2, v2, Seq c1' c2)\n\n(* If statement execution depends on the value of its condition *)\n| StIfTrue : forall h v b c1 c2,\n  beval b h v = true\n  -> step (h, v, If_ b c1 c2) (h, v, c1)\n| StIfFalse : forall h v b c1 c2,\n  beval b h v = false\n  -> step (h, v, If_ b c1 c2) (h, v, c2)\n\n(* While loop also depends on the value of its condition *)\n| StWhileFalse : forall I h v b c,\n  beval b h v = false\n  -> step (h, v, While_ I b c) (h, v, Skip)\n| StWhileTrue : forall I h v b c,\n  beval b h v = true\n  (* This is sometimes called loop unwinding, a loop with a true condition\n     is equivalent to executing the body once, then going back to the loop *)\n  -> step (h, v, While_ I b c) (h, v, Seq c (While_ I b c))\n\n(* Finally, asserts have no effect, and are equivalent to skips *)\n| StAssert : forall h v (a : assertion),\n  a h v -> step (h, v, Assert a) (h, v, Skip).\n\n\n\n\n", "meta": {"author": "KinanBab", "repo": "CS591K1-Labs", "sha": "d4569bf99d20c22cd56721024688cda247d1447f", "save_path": "github-repos/coq/KinanBab-CS591K1-Labs", "path": "github-repos/coq/KinanBab-CS591K1-Labs/CS591K1-Labs-d4569bf99d20c22cd56721024688cda247d1447f/homework1/Problem4/Modeling.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6749492064041556}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Export axioms.\n\nModule Application.\n\nDefinition axioms a b f := forall x, inc x a -> inc (f x) b.\n\nDefinition injects a (f:E1) := forall x y, inc x a -> inc y a -> f x = f y -> x = y.\n\nDefinition covers a b f := forall y, inc y b -> exists x, inc x a & f x = y.\n\nDefinition injective a b f := and (axioms a b f) (injects a f).\nDefinition surjective a b f := and (axioms a b f) (covers a b f).\nDefinition bijective a b f := and (axioms a b f) (and (injects a f) (covers a b f)).\n\nLemma injective_surjective_back : forall a b, (exists f, injective a b f) -> \nnonempty a -> exists f, surjective b a f.\nProof.\nir. nin H0.\ndestruct H as [f H].\nexists (fun y => by_cases \n(fun _ : (exists x, inc x a & f x = y) => unique_choose (fun x => inc x a & f x = y))\n(fun _ : (~ exists x, inc x a & f x = y) => x)).\nuhg;ee.\nuhg;ir.\napply by_cases with (exists x1, inc x1 a & f x1 = x0);ir.\nrw by_cases_if.\napply unique_choose_pr in H2. am.\nuhg;ir. ee. ap H;au. rw H5;au.\nam.\nrw by_cases_if_not;am.\n\nuhg;ir.\nexists (f y).\nee. ap H. am.\nrw by_cases_if.\nassert (exists x0, inc x0 a & f x0 = f y). exists y;ee;tv.\napply unique_choose_pr in H2.\nee.\nuh H;ee. apply H4 in H3.\nam. am. am.\nuhg;ir. ee;ap H;au. rw H5;au.\n\nexists y;ee;tv.\nQed.\n\n(*needs choice*)\nLemma surjective_injective_back : forall a b, (exists f, surjective a b f) -> \nexists f, injective b a f.\nProof.\nir. destruct H as [f H].\n\nexists (fun y => choose (fun x => inc x a & f x = y)).\nset (f' := fun y => choose (fun x => inc x a & f x = y)).\nassert (forall y, inc y b -> (inc (f' y) a & f (f' y) = y)).\nir. uf f'. ap choose_pr.\nuh H;ee. uh H1. ap H1. am.\n\nuhg;ee. uhg;ir.\nap H0. am.\n\nuhg;ir.\ncp (H0 x H1). cp (H0 y H2).\nee.\nwr H7. rw H3. am.\nQed.\n\nLemma cantor_strong : forall x, ~ exists f, surjective x (powerset x) f.\nProof.\nir.\nuhg;ir.\ndestruct H as [f H].\npose (z := Z x (fun a => ~ inc a (f a))).\n\nassert (inc z (powerset x)). ap powerset_inc. ap Z_sub.\ncp H0. apply H in H1. nin H1. ee.\nassert (~ inc x0 z). wr H2.\nuhg;ir.\ncp H3. rwi H2 H4. apply Z_all in H4;ee.\nau.\nap H3. ap Z_inc. am.\nrw H2. am.\nQed.\n\n(*needs choice?*)\nLemma cantor_weak : forall x, ~ exists f, injective (powerset x) x f.\nProof.\nir;uhg;ir. apply cantor_strong with x.\nap injective_surjective_back. am.\neconstructor. ap powerset_inc. ap emptyset_sub_all.\nQed.\n\nEnd Application.\n\nModule Relators.\n\nSection Definitions.\n\nVariables (r : E2P) (a : E).\n\nDefinition reflexiveT := forall x, inc x a -> r x x.\n\nDefinition antisymmetricT := forall x, inc x a -> forall y, inc y a -> r x y ->\n r y x -> x=y.\n\nDefinition symmetricT := forall x, inc x a -> forall y, inc y a -> r x y -> r y x.\n\nDefinition transitiveT := forall x, inc x a -> forall y, inc y a -> r x y ->\n forall z, inc z a -> r y z -> r x z.\n\nDefinition irreflexiveT := forall x, inc x a -> ~ r x x.\n\nDefinition is_order := and (reflexiveT ) (and (antisymmetricT ) (transitiveT )).\n\nDefinition is_strict_order := and (irreflexiveT ) (transitiveT ).\n\nDefinition is_total := forall x, inc x a -> forall y, inc y a -> (r x y \\/ r y x).\n\nDefinition is_total_order := and (is_order) (is_total).\n\nDefinition is_equivalence := and (reflexiveT ) (and (symmetricT ) (transitiveT )).\n\nDefinition class_of x := Z a (r x).\n\nDefinition quotient := Im class_of a.\n\nInductive is_class : EP :=\n  | class_of_class : forall x, inc x a -> is_class (class_of x).\n\nLemma in_quotient_is_class : forall q, inc q quotient -> is_class q.\nProof.\nir. apply Im_ex in H;nin H;ee;subst.\nap class_of_class;am.\nQed.\n\nLemma class_of_in_quotient : forall x, inc x a -> inc (class_of x) quotient.\nProof.\nap Im_inc.\nQed.\n\nLemma class_in_quotient : forall q, is_class q -> inc q quotient.\nProof.\nir. nin H. ap Im_inc. am.\nQed.\n\nLemma quotient_rw : quotient = Z (powerset a) (is_class).\nProof.\nap extensionality;uhg;ir.\napply Im_ex in H;nin H;ee;subst.\nap Z_inc. ap powerset_inc. ap Z_sub. ap class_of_class. am.\nap class_in_quotient. eapply Z_pr. am.\nQed.\n\nLemma class_of_sub : forall x, sub (class_of x) a.\nProof.\nir. ap Z_sub.\nQed.\n\nLemma class_sub : forall q, is_class q -> sub q a.\nProof.\nir. nin H. ap class_of_sub.\nQed.\n\nLemma related_classes_eq : is_equivalence -> forall x, inc x a ->\n forall y, inc y a -> r x y -> class_of x = class_of y.\nProof.\nintro H.\nassert (forall x, inc x a -> forall y, inc y a -> r x y -> sub (class_of x) (class_of y)).\nir. uhg;ir. apply Z_all in H3. ee.\nap Z_inc. am. uh H;ee. apply H6 with x;au. \nir.\nap extensionality;ap H0;au.\nap H. am. am. am.\nQed.\n\nLemma class_of_origin : is_equivalence -> forall x, inc x a -> inc x (class_of x).\nProof.\nir;ap Z_inc;au. uh H;ee;ap H;am.\nQed.\n\nLemma classes_eq_related : is_equivalence -> forall x, inc x a -> forall y, inc y a -> \nclass_of x = class_of y -> r x y.\nProof.\nir. eapply Z_pr.\ncp (class_of_origin H H1). wri H2 H3. ap H3.\nQed.\n\nLemma class_nonempty : is_equivalence -> forall q, is_class q -> nonempty q.\nProof.\nir. nin H0. exists x. ap class_of_origin;am.\nQed.\n\nLemma class_rep_inc : is_equivalence -> forall q, is_class q -> inc (rep q) q.\nProof.\nir. ap rep_inc. ap class_nonempty;am. \nQed.\n\nLemma class_of_class_of : is_equivalence -> forall x, inc x a ->\n class_of x = class_of (rep (class_of x)).\nProof.\nir.\nap related_classes_eq. am. am.\neapply class_sub. eapply class_of_class. am.\nap class_rep_inc. am. ap class_of_class;am.\ncp (class_rep_inc H (class_of_class H0)).\napply Z_pr in H1. am.\nQed.\n\nLemma class_of_rep : is_equivalence -> forall q, is_class q -> q = class_of (rep q).\nProof.\nir. nin H0. ap class_of_class_of;am.\nQed.\n\nDefinition lt_of x y := and (r x y) (x<>y).\n\nEnd Definitions.\n\nLemma sub_is_order : forall a, is_order sub a.\nProof.\nir;uhg;ee;uhg;ir.\nap sub_refl. ap extensionality;am.\napply sub_trans with y;am.\nQed.\n\nLemma eq_equivalence : forall a, is_equivalence eq a.\nProof.\nir. uhg;ee;uhg;ir.\ntv.\nsymmetry;am.\ntransitivity y;am.\nQed.\n\nEnd Relators. Export Relators.\n\nModule Relation.\n\nDefinition relation r := forall x, inc x r -> is_pair x.\nDefinition functional r := forall x, unicity (fun y => inc (pair x y) r).\n\nDefinition domain f := Z (union (union f)) (fun x => exists y, inc (pair x y) f).\n\nLemma domain_inc : forall f x, (exists y, inc (pair x y) f) -> \ninc x (domain f).\nProof.\nir. ap Z_inc.\nnin H.\nap union_inc.\neconstructor. ee.\nap union_inc. econstructor.\nee. ap H. ap doubleton_r.\nap doubleton_l.\nam.\nQed.\n\nLemma domain_rel_P_in : forall f, relation f -> forall x, inc x f -> \ninc (P x) (domain f).\nProof.\nir. uh H.\ncp (H x H0). nin H1. clpr.\nap domain_inc. exists b;am.\nQed.\n\nDefinition range f := Im Q (Z f is_pair).\n\nLemma range_inc : forall f y, (exists x, inc (pair x y) f) -> inc y (range f).\nProof.\nir. nin H.\nap Im_show_inc. econstructor;ee. ap Z_inc. ap H.\nap pair_is_pair. clpr. tv.\nQed.\n\nDefinition R r x y := inc (pair x y) r.\n\nLemma domain_range_ex : forall r x, inc x (domain r) -> exists y, R r x y.\nProof.\nir. apply Z_pr in H.\nnin H. exists x0;am.\nQed.\n\nLemma range_domain_ex : forall r y, inc y (range r) -> exists x, R r x y.\nProof.\nir. apply Im_ex in H. nin H. ee.\napply Z_all in H. ee. nin H1;subst.\nclpr. exists a;am.\nQed.\n\nLemma related_domain : forall r x y, R r x y -> inc x (domain r).\nProof.\nir. ap domain_inc. exists y. am.\nQed.\n\nLemma related_range : forall r x y, R r x y -> inc y (range r).\nProof.\nir;ap range_inc. exists x;am.\nQed.\n\nLemma domain_inc_rw : forall r a, inc a (domain r) = exists b, R r a b.\nProof.\nir;ap iff_eq.\nap domain_range_ex.\nap domain_inc.\nQed.\n\nLemma range_inc_rw : forall r b, inc b (range r) = exists a, R r a b.\nProof.\nir;ap iff_eq.\nap range_domain_ex.\nap range_inc.\nQed.\n\nLemma emptyset_relation : relation emptyset.\nProof.\nuhg;ir. emptyset_auto.\nQed.\n\nLemma relation_related : forall r, relation r -> forall p, inc p r ->\n inc (pair (P p) (Q p)) r.\nProof.\nir. cp H0;apply H in H0;nin H0. clpr. am.\nQed.\n\nDefinition reverse r := Im (fun p => if P_dec (is_pair p) \nthen pair (Q p) (P p) else p) r.\n\nLemma pair_reverse : forall r a b, R r a b -> R (reverse r) b a.\nProof.\nuf R;ir. \nap Im_show_inc. econstructor;ee. am.\nrw P_dec_if. clpr. tv.\nconstructor.\nQed.\n\nLemma reverse_pair : forall r a b, R (reverse r) a b -> R r b a.\nProof.\nuf R;ir.\nIm_nin H. \nnin (P_dec (is_pair x)). nin a0. clpri H0.\napply pair_eq in H0. ee;subst. am.\nsubst. nin b0. constructor.\nQed.\n\nLemma reverse_R_rw : forall r, R (reverse r) = fun a b => R r b a.\nProof.\nir. ap arrow_extensionality. ir. ap arrow_extensionality.\nintro b. ap iff_eq.\nap reverse_pair. ap pair_reverse.\nQed.\n\nLemma not_pair_reverse : forall x, ~ (is_pair x) -> forall r, inc x r ->\n inc x (reverse r).\nProof.\nir. ap Im_show_inc. exists x;ee. am. rw P_dec_if_not. tv. am.\nQed.\n\nLemma reverse_not_pair : forall x, ~ (is_pair x) -> forall r, inc x (reverse r) ->\n inc x r.\nProof.\nir. Im_nin H0.\nrwi P_dec_if_not H1. subst. am.\nuhg;ir. rwi P_dec_if H1. subst. ap H. constructor.\nam.\nQed.\n\nLemma reverse_reverse : forall r, reverse (reverse r) = r.\nProof.\nir;ap extensionality;uhg;ir.\napply by_cases with (is_pair a);ir.\nnin H0. ap reverse_pair. ap reverse_pair. am.\nap reverse_not_pair. am. ap reverse_not_pair. am. am.\napply by_cases with (is_pair a);ir.\nnin H0. ap pair_reverse. ap pair_reverse. am.\nap not_pair_reverse. am. ap not_pair_reverse. am. \nam.\nQed.\n\nLemma reverse_relation : forall r, relation (reverse r) = relation r.\nProof.\nassert (forall r, relation (reverse r) -> relation r).\nuhg;ir. ap excluded_middle;intro.\nap H1. ap H. ap Im_show_inc. exists x.\nee. am. rw P_dec_if_not. tv. am.\n\nir. ap iff_eq.\nam.\nir. ap H. rw reverse_reverse. am.\nQed.\n\nDefinition relates r a b := sub r (product a b).\n\nLemma relates_relation : forall r a b, relates r a b -> relation r.\nProof.\nuhg;ir.\napply H in H0. apply product_pr in H0;am.\nQed.\n\nLemma emptyset_relates : forall a b, relates emptyset a b.\nProof.\nir. ap emptyset_sub_all.\nQed.\n\nLemma product_relates : forall a b, relates (product a b) a b.\nProof.\nir;ap sub_refl.\nQed.\n\nLemma sub_relates : forall r a b, relates r a b -> forall r', sub r' r -> relates r' a b.\nProof.\nir;apply sub_trans with r;am.\nQed.\n\nLemma relates_inc_rw : forall r a b, relates r a b = inc r (powerset (product a b)).\nProof.\nuf relates. ir. symmetry. ap powerset_rw.\nQed.\n\nLemma relates_inc : forall r a b, relates r a b -> forall x y, R r x y ->\n and (inc x a) (inc y b).\nProof.\nir. ap product_pair_pr. ap H. am.\nQed.\n\nLemma relates_inc_l : forall r a b, relates r a b -> forall x y, R r x y -> inc x a.\nProof.\nap relates_inc.\nQed.\n\nLemma relates_inc_r : forall r a b, relates r a b -> forall x y, R r x y -> inc y b.\nProof.\nap relates_inc.\nQed.\n\nLemma relates_reverse : forall r a b, relates r a b -> relates (reverse r) b a.\nProof.\nir. uhg;uhg;ir.\nIm_nin H0. apply H in H0. apply product_pr in H0.\nee. nin H0. clpri H2;clpri H3;clpri H1.\nrwi P_dec_if H1. subst. ap product_pair_inc.\nam. am.\nconstructor.\nQed.\n\nLemma reverse_relates : forall r a b, relates (reverse r) a b -> relates r b a.\nProof.\nir. wr (reverse_reverse r).\nap relates_reverse. am.\nQed.\n\nDefinition superrel r := product (union2 (domain r) (range r))\n                                                  (union2 (domain r) (range r)).\n\nLemma superrel_sub : forall r, relation r -> sub r (superrel r).\nProof.\nuhg;ir. cp H0;apply H in H0. nin H0.\nap product_pair_inc.\nap union2_l;eapply domain_inc. exists b;am.\nap union2_r;eapply range_inc. exists a;am.\nQed.\n\nLemma product_relation : forall a b, relation (product a b).\nProof.\nuhg. ir;eapply product_pr;am.\nQed.\n\nLemma superrel_relation : forall r, relation (superrel r).\nProof.\nir;ap product_relation.\nQed.\n\nLemma relates_superrel : forall r a b, relates r a b -> \nrelates (superrel r) (union2 a b) (union2 a b).\nProof.\nuf relates. uhg;ir.\nufi superrel H0. apply product_pr in H0. ee.\nnin H0;clpri H1;clpri H2.\napply union2_or in H1;apply union2_or in H2.\nrwi domain_inc_rw H1. rwi domain_inc_rw H2.\nrwi range_inc_rw H1;rwi range_inc_rw H2.\nrw product_pair_rw. rw union2_rw. rw union2_rw.\nee.\n nin H1;nin H0;apply H in H0;apply product_pair_pr in H0;ee;au.\n nin H2;nin H0;apply H in H0;apply product_pair_pr in H0;ee;au.\nQed.\n\nLemma product_related_rw : forall a b x y, R (product a b) x y = (inc x a & inc y b).\nProof.\nap product_pair_rw.\nQed.\n\nLemma superrel_rw : forall r x y, R (superrel r) x y =\n ((exists b : E, R r x b) \\/ (exists a : E, R r a x) &\n (exists b : E, R r y b) \\/ (exists a : E, R r a y)).\nProof.\nir. uf superrel.\n rw product_related_rw. rw union2_rw. rw union2_rw.\n repeat rw domain_inc_rw. repeat rw range_inc_rw.\ntv.\nQed.\n\nLemma superrel_reverse : forall r, superrel (reverse r) = superrel r.\nProof.\nir; ap extensionality;intros a H.\nassert (is_pair a). eapply product_pr;am.\nnin H0.\nchange (R (superrel (reverse r)) a b) in H.\nrwi superrel_rw H.\nchange (R (superrel (r)) a b).\nrw superrel_rw.\nrepeat rwi reverse_R_rw H. ee;tauto.\n\nassert (is_pair a). eapply product_pr;am.\nnin H0.\nchange (R (superrel r) a b) in H.\nrwi superrel_rw H.\nchange (R (superrel (reverse r)) a b).\nrw superrel_rw.\nrepeat rw reverse_R_rw. ee;tauto.\nQed.\n\nLemma reverse_superrel : forall r, reverse (superrel r) = superrel r.\nProof.\nir; ap extensionality;intros a H.\nassert (relation (superrel r)). eapply relates_relation. ap sub_refl.\nwri reverse_relation H0.\ncp (H0 a H). nin H1.\napply reverse_pair in H.\nrwi superrel_rw H. \nchange (R (superrel r) a b). rw superrel_rw. tauto.\n\nassert (relation (superrel r)). eapply relates_relation. ap sub_refl.\ncp (H0 a H);nin H1.\nchange (R (superrel r) a b) in H. rwi superrel_rw H.\nap pair_reverse. rw superrel_rw. tauto.\nQed.\n\nLemma relation_relates : forall r, relation r -> relates r (domain r) (range r).\nProof.\nuhg;uhg;ir.\ncp (H a H0). nin H1.\nrw product_pair_rw. rw domain_inc_rw.\nrw range_inc_rw.\nee;eauto.\nQed.\n\nLemma relation_relates_endo : forall r, relation r -> exists a, relates r a a.\nProof.\nir.\npose (a := union2 (domain r) (range r)).\ncp union2_inc.\nexists a;uhg;uhg;ir.\ncp H1. apply H in H1.\nnin H1.\nap product_pair_inc.\nap H0. left. ap domain_inc. exists b;am.\nap H0. right. ap range_inc. exists a0;am.\nQed.\n\nLemma relation_sub_relation : forall r, relation r -> forall r', sub r' r -> relation r'.\nProof.\nuhg;ir. ap H;ap H0;am.\nQed.\n\nLemma sub_superrel : forall r, sub r (superrel r) -> relation r.\nProof.\nintro. ap relation_sub_relation. ap superrel_relation.\nQed.\n\nLemma relates_sub_l : forall r a b, relates r a b -> sub (domain r) a.\nProof.\nuhg;ir. apply domain_range_ex in H0. nin H0.\napply H in H0. apply product_pair_pr in H0;am.\nQed.\n\nLemma relates_sub_r : forall r a b, relates r a b -> sub (range r) b.\nProof.\nuhg;ir. apply range_domain_ex in H0. nin H0.\napply H in H0. apply product_pair_pr in H0;am.\nQed.\n\nLemma reverse_domain : forall r, domain (reverse r) = range r.\nProof.\nir. ap extensionality_rw. ir.\nrw domain_inc_rw. rw range_inc_rw.\nrw reverse_R_rw. tv.\nQed.\n\nLemma reverse_range : forall r, range (reverse r) = domain r.\nProof.\nir. wr (reverse_reverse r).\nrw reverse_domain.\nrw reverse_reverse. tv.\nQed.\n\nDefinition symmetric_rel r := (forall x y, R r x y -> R r y x).\n\nDefinition transitive_rel r := forall x y, R r x y -> forall z, R r y z -> R r x z.\n\nDefinition reflexive_rel r a := (forall x, inc x a -> R r x x).\n\nDefinition antisymmetric_rel r := forall x y, R r x y -> R r y x -> x=y.\n\nDefinition irreflexive_rel r := forall x, ~ R r x x.\n\n\nLemma superrel_trans : forall r, transitive_rel (superrel r).\nProof.\nuhg;ir.\nrwi superrel_rw H. rwi superrel_rw H0.\nee.\nrw superrel_rw. ee.\nam. am.\nQed.\n\nLemma symm_rev_eq : forall r, symmetric_rel r -> reverse r = r.\nProof.\nir.\nap extensionality;uhg;ir.\nIm_nin H0. destruct (P_dec (is_pair x)).\nsubst. ap H. nin i. clpr. am.\nsubst. am.\n\napply by_cases with (is_pair a);ir. nin H1.\nap pair_reverse. ap H. am.\nap Im_show_inc;exists a. ee. am.\nrw P_dec_if_not;au.\nQed.\n\nLemma rev_eq_symm : forall r, reverse r = r -> symmetric_rel r.\nProof.\nuhg;ir.\nwr (reverse_reverse r). ap pair_reverse. rw H. am.\nQed.\n\nLemma symm_rev_rw : forall r, symmetric_rel r = (reverse r = r).\nProof.\nir;ap iff_eq.\n ap symm_rev_eq.\n ap rev_eq_symm.\nQed.\n\nLemma superrel_symm : forall r, symmetric_rel (superrel r).\nProof.\nir. ap rev_eq_symm. ap reverse_superrel.\nQed.\n\nLemma superrel_refl : forall r a, sub a (union2 (domain r) (range r)) -> \nreflexive_rel (superrel r) a.\nProof.\nuhg;ir.\nap product_pair_inc;ap H;am.\nQed.\n\nSection Relator_rewrites.\n\nVariables (r a : E).\nHypothesis (Hrel : relates r a a).\n\nLemma symm_symmT : symmetric_rel r -> symmetricT (R r) a.\nProof.\nir. uhg;ir.\nap H;am.\nQed.\n\nLemma symmT_symm : symmetricT (R r) a -> symmetric_rel r.\nProof.\nuhg. ir.\nap H.\neapply relates_inc_l;am. eapply relates_inc_r;am.\nam.\nQed.\n\nLemma symm_rel_rw : symmetricT (R r) a = symmetric_rel r.\nProof.\nap iff_eq. ap symmT_symm.\nap symm_symmT.\nQed.\n\nLemma trans_transT : transitive_rel r -> transitiveT (R r) a.\nProof.\nuhg;ir. eapply H;am.\nQed.\n\nLemma transT_trans : transitiveT (R r) a -> transitive_rel r.\nProof.\nuhg;ir.\ncp (relates_inc Hrel H0). ee.\ncp (relates_inc_r Hrel H1).\napply H with y;am.\nQed.\n\nLemma transT_trans_rw : transitiveT (R r) a = transitive_rel r.\nProof.\nap iff_eq.\nap transT_trans.\nap trans_transT.\nQed.\n\nLemma refl_reflT : reflexive_rel r a -> reflexiveT (R r) a.\nProof.\nuhg. uf reflexive_rel. intro. ee.\nam.\nQed.\n\nLemma reflT_refl : reflexiveT (R r) a -> reflexive_rel r a.\nProof.\nuhg;ir.\nap H. am.\nQed.\n\nLemma reflT_refl_rw : reflexiveT (R r) a = reflexive_rel r a.\nProof.\ntv. \nQed.\n\nLemma antisym_antisymT : antisymmetric_rel r -> antisymmetricT (R r) a.\nProof.\nuhg;ir. ap H. am. am.\nQed.\n\nLemma antisymT_antisym : antisymmetricT (R r) a -> antisymmetric_rel r.\nProof.\nuhg;ir. ap H.\neapply relates_inc_l;am.\neapply relates_inc_l;am.\nam. am.\nQed.\n\nLemma antisymT_antisym_rw : antisymmetricT (R r) a = antisymmetric_rel r.\nProof.\nap iff_eq.\nap antisymT_antisym.\nap antisym_antisymT.\nQed.\n\nLemma irrefl_irreflT : irreflexive_rel r -> irreflexiveT (R r) a.\nProof.\nuhg;ir. ap H.\nQed.\n\nLemma irreflT_irrefl : irreflexiveT (R r) a -> irreflexive_rel r.\nProof.\nuhg;ir. uhg;ir. apply H with x.\neapply relates_inc_l;am. am.\nQed.\n\nLemma irreflT_refl_rw : irreflexiveT (R r) a = irreflexive_rel r.\nProof.\nap iff_eq.\nap irreflT_irrefl.\nap irrefl_irreflT.\nQed.\n\nEnd Relator_rewrites.\n\nSection Closure.\n\nDefinition trans_clos r := inter (Z (powerset (superrel r))\n   (fun r' => sub r r' & transitive_rel r')).\n\nLemma trans_clos_superrel_aux : forall r a, relates r a a ->\n sub (trans_clos r) (superrel r).\nProof.\nuhg;intros r a Hr;ir.\nassert (inc (superrel r) (powerset (superrel r))).\nap powerset_inc. ap sub_refl.\nassert (inc (superrel r) (Z (powerset (superrel r))\n   (fun r' : E => r ⊂ r' & transitive_rel r'))).\nap Z_inc. am.\nee. ap superrel_sub.\neapply relates_relation. am.\nap superrel_trans.\neapply inter_all;am.\nQed.\n\nLemma trans_clos_nonrel : forall r, ~ relation r -> trans_clos r = emptyset.\nProof.\nir. ap empty_emptyset;ir.\napply Z_sub in H0.\napply union_ex in H0. nin H0.\nee. apply Z_all in H0. ee.\napply powerset_sub in H0.\nap H.\napply relation_sub_relation with (superrel r). \nap product_relation.\neapply sub_trans;am.\nQed.\n\nLemma trans_clos_superrel : forall r, sub (trans_clos r) (superrel r).\nProof.\nir. apply by_cases with (relation r);ir.\napply relation_relates_endo in H. nin H.\napply trans_clos_superrel_aux with x;am.\n\nreplace (trans_clos r) with emptyset. ap emptyset_sub_all.\nsymmetry. ap trans_clos_nonrel. am.\nQed.\n\nLemma trans_clos_nonempty_aux : forall r, relation r -> nonempty\n  (Z (powerset (superrel r)) (fun r' : E => r ⊂ r' & transitive_rel r')).\nProof.\nir.\nexists (superrel r). ap Z_inc. ap powerset_inc;ap sub_refl.\nee. ap superrel_sub. am.\nap superrel_trans.\nQed.\n\nLemma trans_clos_sub : forall r, relation r -> sub r (trans_clos r).\nProof.\nir. uhg;ir.\nap inter_inc.\nap trans_clos_nonempty_aux. am.\nir. apply Z_pr in H1. ee.\nau.\nQed.\n\nLemma trans_clos_smallest : forall r, relation r -> forall r',\nsub r r' -> transitive_rel r' -> sub (trans_clos r) r'.\nProof.\nir.\nuhg;ir.\nassert (forall k, inc k (Z (powerset (superrel r))\n            (fun r' : E => r ⊂ r' & transitive_rel r')) -> inc a k).\nap inter_all. am.\nassert (forall k, sub k (superrel r) -> sub r k -> transitive_rel k -> inc a k).\nir;ap H3. ap Z_inc. ap powerset_inc;am. ee;am.\nclear H3.\nassert (forall k, sub r k -> transitive_rel k -> inc a k).\nir. assert (inc a (inter2 k (superrel r))).\nap H4. ap inter2_r. \nuhg;ir. ap inter2_inc. au. ap superrel_sub.\n(* here use relation r*)\nam.\nam.\nuhg;ir. apply inter2_and in H6;apply inter2_and in H7. ee.\nap inter2_inc. apply H5 with y;am. apply superrel_trans with y;am.\neapply inter2_l;am. clear H4.\nap H3. am. am.\nQed.\n\nLemma trans_clos_trans : forall r, transitive_rel (trans_clos r).\nProof.\nir. apply by_cases with (relation r);ir.\n\nFocus 2. rw trans_clos_nonrel. uhg;ir. ufi R H0. emptyset_auto.\nam.\n\nuhg;ir.\nufa R.\nap inter_inc. ap trans_clos_nonempty_aux. am.\nir. apply Z_all in H2;ee.\napply H4 with y.\neapply inter_all. am.\nap Z_inc. am. ee. am. am.\neapply inter_all. am.\nap Z_inc;ee;am.\nQed.\n\nSection Reachable.\n\nVariable (R : E2P).\n\nInductive reachable : E2P :=\n  | R_reach : forall x y, R x y -> reachable x y\n  | reach_trans : forall x y, reachable x y -> forall z, reachable y z -> reachable x z\n.\n\nLemma reachable_trans : forall a, transitiveT reachable a.\nProof.\nuhg. ir;apply reach_trans with y;am.\nQed.\n\nLemma reach_cons : forall x y, R x y -> forall z, reachable y z -> reachable x z.\nProof.\nintros ? ? ?.\nap reach_trans. constructor. am.\nQed.\n\nInductive path_n : nat -> E -> E -> Type :=\n  | path_0 : forall x, path_n 0 x x\n  | path_S : forall x y, R x y -> forall n z, path_n n y z -> path_n (S n) x z\n.\n\nLemma path_0_eq : forall x y, path_n 0 x y -> x=y.\nProof.\nir. inversion X;au.\nQed.\n\nLemma path_n_reach : forall n x y, path_n (S n) x y -> reachable x y.\nProof.\nassert (forall n, n<>0 -> forall x y, path_n n x y -> reachable x y).\nir. nin X. nin H;tv.\ndestruct n.\napply path_0_eq in X. subst. constructor;am.\napply reach_cons with y. am. ap IHX. uhg;ir.\ninversion H0.\n\nir;eapply H;try am. uhg;ir;inversion H0.\nQed.\n\nDefinition path_n_trans : forall n x y, path_n n x y -> forall m z, path_n m y z -> \npath_n (n+m) x z.\nintros ? ? ? H.\nnin H.\nir. simpl. am.\nir. simpl.\neapply path_S. am. ap IHpath_n. am.\nDefined.\n\nLemma reach_path_n : forall x y, reachable x y ->\n exists n, n<>0 & nonemptyT (path_n n x y).\nProof.\nir. nin H.\nexists 1. ee. uhg;ir;inversion H0. econstructor.\neapply path_S. am. constructor.\nnin IHreachable1;nin IHreachable2. ee.\nnin H3;nin H4.\nexists (x0+x1).\nee. uhg;ir;destruct x0. nin H1;tv. inversion H3.\n econstructor.\neapply path_n_trans. am. am.\nQed.\n\nLemma reach_smallest : forall R' : E2P, (forall x y, R x y -> R' x y) -> \n(forall x y, R' x y -> forall z, R' y z -> R' x z) -> \nforall x y, reachable x y -> R' x y.\nProof.\nir.\nnin H1. ap H;am.\napply H0 with y;am.\nQed.\n\nLemma trans_reach_eq : (forall x y, R x y -> forall z, R y z -> R x z) -> \nreachable = R.\nProof.\nir;ap arrow_extensionality;intros x;ap arrow_extensionality;intros y.\nap iff_eq;ir.\nnin H0. am. apply H with y;am.\nap R_reach. am.\nQed.\n\nLemma reachable_domain : forall x y, reachable x y -> exists y', R x y'.\nProof.\nir. nin H.\nexists y;am.\nam.\nQed.\n\nLemma reachable_range : forall x y, reachable x y -> exists x', R x' y.\nProof.\nir;nin H.\nexists x;am.\nam.\nQed.\n\nEnd Reachable.\n\nLemma reach_trans_clos : forall r, relation r -> forall x y, reachable (R r) x y -> \nR (trans_clos r) x y.\nProof.\nir. nin H0.\nap trans_clos_sub. am. am.\napply trans_clos_trans with y;am.\nQed.\n\nLemma relation_ex : forall r, exists r', relation r' & R r = R r'.\nProof.\nir. exists (Z r is_pair). ee.\nuhg. ap Z_pr.\nap arrow_extensionality;ir;ap arrow_extensionality;ir.\nap iff_eq;ir.\nap Z_inc. am. ap pair_is_pair.\neapply Z_sub;am.\nQed.\n\nLemma same_rel_eq : forall r, relation r -> forall r', relation r' -> \nR r = R r' -> r=r'.\nProof.\nir;ap extensionality_rw;ir.\napply by_cases with (is_pair a);ir. nin H2.\nchange (R r a b = R r' a b). rw H1;tv.\nap iff_eq;ir;nin H2;au.\nQed.\n\nLemma reachable_rel : forall r, exists r', relation r' & reachable (R r) = R r'.\nProof.\nir.\nexists (Z (product (domain r) (range r)) (fun p => reachable (R r) (P p) (Q p))).\nee. uhg;ir. apply Z_sub in H;eapply product_pr;am.\nap arrow_extensionality;ir;ap arrow_extensionality;intro b.\nap iff_eq;ir.\ncp (reachable_domain H).\ncp (reachable_range H).\nap Z_inc. ap product_pair_inc.\nap domain_inc. am.\nap range_inc;am.\nclpr. am.\n\napply Z_pr in H. clpri H. am.\nQed.\n\nLemma relation_sub : forall r, relation r -> forall r',\n (forall x y, R r x y -> R r' x y) = sub r r'.\nProof.\nir;ap iff_eq;ir.\nuhg;ir. cp (H a H1). nin H2. ap H0;am.\nap H0;am.\nQed.\n\nLemma trans_clos_reach : forall r, relation r ->\n forall x y, R (trans_clos r) x y -> reachable (R r) x y.\nProof.\nintros ? Hr;ir.\ncp (reachable_rel r).\ndestruct H0 as [r' H0];ee.\nrw H1.\neapply trans_clos_smallest. Focus 4.\nam.\nam.\nwr relation_sub. wr H1. \nap R_reach.\nam.\nuhg. wr H1. ap reach_trans.\nQed.\n\nLemma trans_clos_reach_rw : forall r, relation r ->\n R (trans_clos r) = reachable (R r).\nProof.\nir.\nap arrow_extensionality;ir;ap arrow_extensionality;ir.\nap iff_eq. ap trans_clos_reach. am.\nap reach_trans_clos. am.\nQed.\n\n\n\nEnd Closure.\n\nEnd Relation.\nExport Relation.\n\nModule Function.\n\nDefinition axioms f := and (relation f) (functional f).\n\nDefinition ev f x := union (range (Z f (fun p => eq x (P p)))).\n\n(*\nDefinition ev f x := choose (fun y => inc (pair x y) f).\n*)\n\n\nLemma fun_show_ev : forall f, axioms f -> forall x y, inc (pair x y) f -> \ny = ev f x.\nProof.\nir.\nuf ev.\nap extensionality;uhg;ir.\nap union_inc. econstructor. ee.\nap range_inc.\nexists x. ap Z_inc. am. clpr;tv. am.\n\napply union_ex in H1;nin H1;ee.\napply range_domain_ex in H1. nin H1.\napply Z_all in H1. ee.\nclpri H3. subst.\nuh H. ee. uh H3. cp (H3 x1 x0 H1 y H0). subst. am.\nQed.\n\nLemma domain_ev_inc : forall f x, axioms f -> inc x (domain f) -> \ninc (pair x (ev f x)) f.\nProof.\nir. ufi domain H0.\napply Z_all in H0;ee. nin H1;ee.\nassert (x0 = ev f x). ap fun_show_ev. am.\nam. subst. am.\nQed.\n\nLemma domain_P_in : forall f, axioms f -> forall x, inc x f -> \ninc (P x) (domain f).\nProof.\nintros f Hf. ap domain_rel_P_in.\nam.\nQed.\n\nLemma domain_P_rw : forall f, axioms f -> domain f = Im P f.\nProof.\nir. ap extensionality;uhg;ir.\napply Z_pr in H0. nin H0.\nap Im_show_inc. exists (pair a x). ee. am.\nclpr. tv.\napply Im_ex in H0;nin H0. ee;subst.\nap domain_P_in. am. am.\nQed.\n\n\nLemma range_ev_inc : forall f, axioms f -> forall x, inc x (domain f) ->\n inc (ev f x) (range f).\nProof.\nir. ap range_inc. exists x. ap domain_ev_inc.\nam. am.\nQed.\n\nLemma range_show_inc : forall f, axioms f -> forall y,\n (exists x, inc x (domain f) & ev f x = y) -> \ninc y (range f).\nProof.\nir. nin H0;ee;subst. ap range_ev_inc. am. am.\nQed.\n\nLemma fun_ev_eq : forall f, axioms f -> forall x, inc x f -> \nx = pair (P x) (ev f (P x)).\nProof.\nir. cp H0.\napply H in H0. nin H0. clpr.\nuh H;ee. assert (b = (ev f a)).\nap fun_show_ev. uhg;ee;am.\nam.\nsubst. tv.\nQed.\n\nLemma fun_Q_ev : forall f, axioms f -> forall x, inc x f -> \nQ x = ev f (P x).\nProof.\nir. apply fun_ev_eq in H0. rw H0. clpr. tv. am.\nQed.\n\nLemma range_ex : forall f, axioms f -> forall y, inc y (range f) -> \nexists x, inc x (domain f) & y = ev f x.\nProof.\nir.\napply range_domain_ex in H0. nin H0.\nexists x;ee. ap domain_inc. exists y;am.\nap fun_show_ev. am. am.\nQed.\n\nLemma range_Q_rw : forall f, axioms f -> range f = Im Q f.\nProof.\nir. uf range. ap uneq.\nap extensionality. ap Z_sub.\nuhg;ir;ap Z_inc. am. ap H;am.\nQed.\n\nLemma range_Im_rw : forall f, axioms f -> range f = Im (ev f) (domain f).\nProof.\nir.\nap extensionality;uhg;ir.\napply range_ex in H0. nin H0;ee. subst.\nap Im_inc. am.\nam.\napply Im_ex in H0. nin H0;ee;subst.\nap range_ev_inc. am.\nam.\nQed.\n\nLemma sub_axioms : forall f, axioms f -> forall g, sub g f -> axioms g.\nProof.\nir.\nuhg;uh H;ee;intro;ir. \nap H. au.\nintro;ir. eapply H1. ap H0;am. ap H0;am.\nQed.\n\nLemma function_sub : forall f g, axioms f -> axioms g -> \nsub (domain g) (domain f) -> \n(forall x, inc x (domain g) -> ev f x = ev g x) -> \nsub g f.\nProof.\nir.\nuhg;ir.\ncp H3. apply H0 in H4.\nnin H4.\nassert (inc a (domain g)).\nap domain_inc. exists b;am.\ncp H3. apply fun_Q_ev in H5. clpri H5.\nsubst.\nwr H2.\nap domain_ev_inc. am. ap H1. am.\nam. am.\nQed.\n\nLemma function_extensionality : forall f g, axioms f -> axioms g -> \n(domain f = domain g) -> \n(forall x, inc x (domain f) -> ev f x = ev g x) -> \nf=g.\nProof.\nir. ap extensionality;ap function_sub;try am.\nrw H1. ap sub_refl.\nir. symmetry. ap H2. am.\nrw H1;ap sub_refl.\nir. ap H2. rw H1. am.\nQed.\n\nLemma singleton_axioms : forall a b, axioms (singleton (J a b)).\nProof.\nir;uhg;ee;uhg;ir.\napply singleton_eq in H. subst;ap pair_is_pair.\nuhg;ir;apply singleton_eq in H;apply singleton_eq in H0.\napply pair_eq in H;apply pair_eq in H0;ee. rw H1;am.\nQed.\n\nLemma singleton_domain : forall a b, domain (singleton (J a b)) = singleton a.\nProof.\nir;ap extensionality;uhg;ir.\napply domain_ev_inc in H. apply singleton_eq in H. apply pair_eq in H;ee.\nrw H;ap singleton_inc.\nap singleton_axioms.\napply singleton_eq in H;subst.\nap domain_inc. exists b;ap singleton_inc.\nQed.\n\nDefinition create a f := Im (fun x => pair x (f x)) a.\n\nLemma create_emptyset : forall f, create emptyset f = emptyset.\nProof.\nir;ap empty_emptyset;ir.\nufi create H. apply Im_ex in H;nin H.\nee. apply emptyset_empty with x;am.\nQed.\n\nLemma create_axioms : forall a f, axioms (create a f).\nProof.\nir. uhg;ee;uhg;ir.\napply Im_ex in H. nin H. ee. subst. ap pair_is_pair.\nuhg;ir;apply Im_ex in H;apply Im_ex in H0;nin H;nin H0;ee;subst.\napply pair_eq in H2. ee;subst. apply pair_eq in H1;ee;subst. tv.\nQed.\n\nLemma create_domain : forall a f, domain (create a f) = a.\nProof.\nir.\nap extensionality;uhg;ir.\nrwi domain_P_rw H. apply Im_ex in H. nin H;ee;subst.\napply Im_ex in H;nin H;ee;subst. clpr. am.\nap create_axioms.\nrw domain_P_rw. ap Im_show_inc. econstructor.\nee. ap Im_show_inc. econstructor. ee.\nam. reflexivity. clpr. tv.\nap create_axioms.\nQed.\n\nLemma emptyset_axioms : axioms emptyset.\nProof.\nwr (create_emptyset (fun x => x)). ap create_axioms.\nQed.\n\nLemma emptyset_domain : domain emptyset = emptyset.\nProof.\nuf domain;ap empty_emptyset;ir.\napply Z_pr in H;nin H;ee. apply emptyset_empty in H;am.\nQed.\n\nLemma create_ev : forall a f, forall x, inc x a -> \nev (create a f) x = f x.\nProof.\nir.\nsymmetry. ap fun_show_ev.\nap create_axioms.\nap Im_show_inc. exists x;ee.\nam. tv.\nQed.\n\nLemma create_in : forall a f x y, inc (pair x y) (create a f) -> \ny = f x.\nProof.\nir.\napply Im_ex in H;nin H;ee;subst. apply pair_eq in H0;ee;subst. tv.\nQed.\n\nLemma domain_sub : forall f g, sub f g -> sub (domain f) (domain g).\nProof.\nir;uhg;ir.\nap domain_inc. apply Z_pr in H0. nin H0. exists x. au.\nQed.\n\nLemma range_sub : forall f g, sub f g -> sub (range f) (range g).\nProof.\nir;uhg;ir. ap range_inc.\napply range_domain_ex in H0. nin H0;exists x;au.\nQed.\n\nLemma create_range : forall a f, range (create a f) = Im f a.\nProof.\nir.\nap extensionality;uhg;ir.\napply range_ex in H.\nnin H;ee;subst. rwi create_domain H.\nrw create_ev. ap Im_inc. am. am. ap create_axioms.\napply Im_ex in H;nin H;ee;subst.\nap range_inc. exists x. ap Im_show_inc. exists x;ee;au.\nQed.\n\nLemma Im_ev_create : forall x f, Im (ev (create x f)) x = Im f x.\nProof.\nir;ap extensionality;uhg;ir.\napply Im_ex in H;nin H;ee. subst. rw create_ev;au.\nap Im_inc;am.\napply Im_ex in H;nin H;ee;subst.\nap Im_show_inc. exists x0;ee;au.\nrw create_ev;au.\nQed.\n\nLemma trans_of_ev : forall f, axioms f ->\n Application.axioms (domain f) (range f) (ev f).\nProof.\nir;uhg;ir.\nap range_ev_inc. am. am.\nQed.\n\nLemma create_recov : forall f, axioms f -> f = create (domain f) (ev f).\nProof.\nir. ap function_extensionality. am.\nap create_axioms.\nsymmetry. ap create_domain.\nir.\nsymmetry.\nap create_ev.\nam.\nQed.\n\nDefinition inverse_image a f := Z (domain f) (fun x => inc (ev f x) a).\n\nLemma create_extensionality : forall a f g, (forall x, inc x a -> f x = g x) -> \ncreate a f = create a g.\nProof.\nir.\nap function_extensionality;try ap create_axioms.\nrw create_domain. rw create_domain. tv.\nir. rwi create_domain H0.\nrw create_ev. rw create_ev. ap H;am. am. am.\nQed.\n\nLemma create_replace_inner : forall a b f g h, (forall x, inc x a -> inc (h x) b) ->\n create a (fun x => g (ev (create b f) (h x))) = create a (fun x => g (f (h x))).\nProof.\nir. ap create_extensionality.\nir. ap uneq. ap create_ev. ap H. am.\nQed.\n\nLemma create_create_sub : forall a b, sub a b -> forall f, \ncreate a (ev (create b f)) = create a f.\nProof.\nir. transitivity (create a (fun x => ev (create b f) x)).\nap uneq. ap arrow_extensionality. ir;tv.\ncp create_replace_inner.\ncp (H0 a b f (fun v => v) (fun v => v)).\nclear H0. simpl in H1. rw H1.\nap uneq. ap arrow_extensionality;ir;tv.\nam.\nQed.\n\nLemma create_create : forall a f, create a (ev (create a f)) = create a f.\nProof.\nir. ap create_create_sub.\nap sub_refl.\nQed.\n\nDefinition composable f g := \nand (axioms f)\n(and (axioms g)\n(sub (range g) (domain f))).\n\nDefinition compose f g := create (inverse_image (domain f) g)\n (fun x => ev f (ev g x)).\n\nLemma compose_axioms : forall f g, axioms (compose f g).\nProof.\nir;ap create_axioms.\nQed.\n\nLemma compose_domain : forall f g, domain (compose f g) =\n inverse_image (domain f) g.\nProof.\nir. ap create_domain.\nQed.\n\nLemma composable_domain : forall f g, composable f g -> \ndomain (compose f g) = domain g.\nProof.\nir.\nrw compose_domain.\nap extensionality;uhg;ir.\napply Z_all in H0. ee. am.\n\nap Z_inc. am.\nuh H;ee.\nap H2. ap range_ev_inc. am.\nam.\nQed.\n\nLemma compose_ev : forall f g x, inc x (domain (compose f g)) -> \nev (compose f g) x = ev f (ev g x).\nProof.\nir. uf compose. rwi compose_domain H.\nrw create_ev.\ntv. am.\nQed.\n\nDefinition id x := create x (fun y => y).\n\nLemma id_axioms : forall x, axioms (id x).\nProof.\nir;ap create_axioms.\nQed.\n\nLemma id_domain : forall x, domain (id x) = x.\nProof.\nir;ap create_domain.\nQed.\n\nLemma id_range : forall x, range (id x) = x.\nProof.\nir. uf id. rw create_range.\nap extensionality;uhg;ir.\n\napply Im_ex in H;nin H;ee;subst;am.\nap Im_show_inc. exists a;ee. am. tv.\nQed.\n\nLemma id_ev : forall x y, inc y x -> ev (id x) y = y.\nProof.\nir. uf id. ap create_ev. am.\nQed.\n\nLemma id_composable_l : forall f, axioms f -> forall x, sub (range f) x -> \ncomposable (id x) f.\nProof.\nir;uhg;ee. ap id_axioms. am.\nrw id_domain. am.\nQed.\n\nLemma id_composable_r : forall f, axioms f -> forall x, sub x (domain f) -> \ncomposable f (id x).\nProof.\nir.\nuhg;ee. am. ap id_axioms.\nrw id_range. am.\nQed.\n\nLemma compose_id_l : forall f, axioms f -> compose (id (range f)) f = f.\nProof.\nir. ap function_extensionality.\nap compose_axioms. am.\nrw composable_domain.\ntv. ap id_composable_l. am. ap sub_refl.\nir.\nrwi composable_domain H0.\nrw compose_ev. rw id_ev. tv.\nap range_ev_inc. am. am.\nrw composable_domain. am.\nap id_composable_l. am. ap sub_refl.\nap id_composable_l. am. ap sub_refl.\nQed.\n\nLemma compose_id_r : forall f, axioms f -> compose f (id (domain f)) = f.\nProof.\nir.\nap function_extensionality.\nap compose_axioms. am.\nrw composable_domain.\nap id_domain. ap id_composable_r. am. ap sub_refl.\nir.\nrwi composable_domain H0. rwi id_domain H0.\nrw compose_ev. rw id_ev. tv.\nam. rw composable_domain. rw id_domain. am.\nap id_composable_r. am. ap sub_refl.\nap id_composable_r. am. ap sub_refl.\nQed.\n\nLemma compose_assoc : forall f g h, axioms f -> axioms g -> axioms h -> \ncompose f (compose g h) = compose (compose f g) h.\nProof.\nir. cp compose_axioms.\nassert (domain (compose f (compose g h)) = domain (compose (compose f g) h)).\nrepeat rw compose_domain.\nap extensionality;uhg;ir.\napply Z_all in H3. ee.\nrwi compose_ev H4;au.\nrwi compose_domain H3. apply Z_all in H3;ee.\nap Z_inc. am. ap Z_inc. am. am.\napply Z_all in H3;ee.\napply Z_all in H4;ee.\nap Z_inc. rw compose_domain. ap Z_inc;au. rw compose_ev.\nam. rw compose_domain. ap Z_inc;au.\n\nap function_extensionality;au.\n\nir. rw compose_ev;au.\nrwi H3 H4. symmetry; rw compose_ev;au;symmetry.\nrwi compose_domain H4. apply Z_all in H4.\nee. rwi compose_domain H5;apply Z_all in H5;ee.\nrw compose_ev. rw compose_ev. tv.\nrw compose_domain. ap Z_inc;au.\nrw compose_domain;ap Z_inc;au.\nQed.\n\n\nDefinition restr f x := Z f (fun a => inc (P a) x).\n\nLemma restr_axioms : forall f x, axioms f -> axioms (restr f x).\nProof.\nir. apply sub_axioms with f. am. ap Z_sub.\nQed.\n\nLemma restr_domain : forall f x, axioms f ->\n domain (restr f x) = inter2 (domain f) x.\nProof.\nir.\nrw domain_P_rw. rw domain_P_rw.\nap extensionality;uhg;ir.\napply Im_ex in H0;nin H0;ee;subst.\napply Z_all in H0;ee.\nap inter2_inc. ap Im_inc. am.\nam.\napply inter2_and in H0. ee.\napply Im_ex in H0;nin H0;ee;subst.\nap Im_inc. ap Z_inc. am. am.\nam. ap restr_axioms. am.\nQed.\n\nLemma restr_sub_domain : forall f x, axioms f -> sub x (domain f) ->\n domain (restr f x) = x.\nProof.\nir. rw restr_domain;au. ap extensionality;uhg;ir.\neapply inter2_r;am. ap inter2_inc;au.\nQed.\n\nLemma restr_ev : forall f, axioms f -> forall a x, inc x a -> inc x (domain f) ->\n ev (restr f a) x = ev f x.\nProof.\nir. symmetry.\nap fun_show_ev. ap restr_axioms. am.\n\nap Z_inc. ap domain_ev_inc. am. am.\nclpr. am.\nQed.\n\nLemma restr_sub_ev : forall f, axioms f -> forall a, sub a (domain f) -> \nforall x, inc x a -> ev (restr f a) x = ev f x.\nProof.\nir. ap restr_ev. am. am. au.\nQed.\n\nLemma restr_recov : forall f, axioms f -> restr f (domain f) = f.\nProof.\nir.\nap function_extensionality.\nap restr_axioms. am. am.\nrw restr_domain. ap extensionality;uhg;ir.\napply inter2_and in H0. am.\nap inter2_inc;am.\nam.\n\nir.\nrwi restr_domain H0. apply inter2_and in H0;ee. clear H1.\nrw restr_sub_ev.\ntv.\nam. ap sub_refl.\nam. am.\nQed.\n\nLemma sub_ev_eq : forall f g, axioms f -> sub g f -> forall x, inc x (domain g) -> \nev g x = ev f x.\nProof.\nir.\nap fun_show_ev. am.\nap H0. ap domain_ev_inc. apply sub_axioms with f. am. am. am.\nQed.\n\nLemma restr_eq : forall f, axioms f -> forall g, axioms g -> \nsub (domain f) (domain g) -> (forall x , inc x (domain f) -> ev f x = ev g x) -> \nrestr g (domain f) = f.\nProof.\nir.\nap function_extensionality;ir.\nap restr_axioms;am.\nam.\nap restr_sub_domain. am. am.\n\nrw restr_ev. rwi restr_sub_domain H3;au.\nsymmetry;ap H2;am. rwi restr_sub_domain H3;au. \nrwi restr_sub_domain H3;au. \nrwi restr_sub_domain H3;au. \nQed.\n\nNotation L := create.\n\nDefinition union_strict_cond e := forall f, inc f e -> forall g, inc g e -> \nforall x, inc x (domain f) -> inc x (domain g) -> f = g.\n\nLemma union_strict_cond_rw : union_strict_cond = fun e => \n(forall f g, inc f e -> inc g e -> nonempty (inter2 (domain f) (domain g)) -> f=g).\nProof.\nap arrow_extensionality. intros e.\nap iff_eq;try uhg;ir.\nnin H2. apply inter2_and in H2. ee.\neapply H;try am.\nap H. am. am. exists x. ap inter2_inc. am. am.\nQed.\n\nLemma union_axioms : forall e, (forall f, inc f e -> axioms f) -> \nunion_strict_cond e -> \naxioms (union e).\nProof.\nrw union_strict_cond_rw.\nir;uhg;ee;uhg;ir.\napply union_ex in H1;nin H1;ee.\neapply H. am. am.\nuhg;ir;apply union_ex in H1;apply union_ex in H2.\nnin H1;nin H2;ee.\n\nassert (x0=x1). ap H0.\nam. am. exists x. ap inter2_inc;\nap domain_inc.\nexists y. am. exists y'. am.\nsubst.\neapply H. am. am. am.\nQed.\n\nLemma union2_axioms : forall f g, axioms f -> axioms g ->\n inter2 (domain f) (domain g) = emptyset -> \naxioms (union2 f g).\nProof.\nir;uf union2;ap union_axioms.\nir. apply doubleton_or in H2. nin H2;subst;am.\nuhg;ir.\napply doubleton_or in H2;apply doubleton_or in H3.\ncp (inter2_inc H4 H5).\nnin H2;nin H3;subst.\ntv. rwi H1 H6. apply emptyset_empty in H6. nin H6.\nrwi inter2_comm H6. rwi H1 H6. apply emptyset_empty in H6. nin H6.\ntv.\nQed.\n\nLemma union_domain : forall e, (forall f, inc f e -> axioms f) -> \nunion_strict_cond e -> \ndomain (union e) = union (Im domain e).\nProof.\nrw union_strict_cond_rw.\nir.\nap extensionality;uhg;ir.\napply domain_ev_inc in H1. apply union_ex in H1.\nnin H1;ee.\nap union_inc. econstructor;ee.\nap Im_inc. am. ap domain_inc. econstructor;am.\nap union_axioms;try am. rw union_strict_cond_rw;am.\napply union_ex in H1;nin H1;ee.\napply Im_ex in H1. nin H1;ee;subst.\nap domain_inc.\napply domain_ev_inc in H2.\neconstructor. ap union_inc. econstructor;ee. am. am.\nap H;am.\nQed.\n\nLemma union2_domain : forall f g, axioms f -> axioms g ->\n inter2 (domain f) (domain g) = emptyset -> \ndomain (union2 f g) = union2 (domain f) (domain g).\nProof.\nir;uf union2. rw union_domain;try rw union_strict_cond.\nap uneq. ap extensionality_rw. ir. rw Im_rw. ap iff_eq;ir.\nnin H2;ee. subst. apply doubleton_or in H2;nin H2;subst.\nap doubleton_l. ap doubleton_r.\napply doubleton_or in H2;nin H2;subst;econstructor;ee;try reflexivity.\nap doubleton_l. ap doubleton_r.\n\nir. apply doubleton_or in H2. nin H2;subst;am.\nrw union_strict_cond_rw. ir. nin H4.\napply doubleton_or in H2;apply doubleton_or in H3.\nnin H2;nin H3;subst.\ntv. rwi H1 H4. apply emptyset_empty in H4. nin H4.\nrwi inter2_comm H4. rwi H1 H4. apply emptyset_empty in H4. nin H4.\ntv.\nQed.\n\nLemma union_ev : forall e, (forall f, inc f e -> axioms f) -> \nunion_strict_cond e ->\nforall f, inc f e -> forall x, inc x (domain f) -> ev (union e) x = ev f x.\nProof.\nir.\nassert (inc x (domain (union e))).\nrw union_domain;try am. ap union_inc;econstructor.\nee. ap Im_inc. am. am.\napply domain_ev_inc in H3. \nassert (axioms (union e)). ap union_axioms. am. am.\napply H4 with x. am.\nap union_inc;econstructor. ee. am. ap domain_ev_inc. ap H;am. am.\nap union_axioms;am.\nQed.\n\nLemma union2_ev_l : forall f g, axioms f -> axioms g ->\n inter2 (domain f) (domain g) = emptyset -> \nforall x (Hinc : inc x (domain f)), ev (union2 f g) x = ev f x.\nProof.\nir. uf union2. ap union_ev.\n\nir. apply doubleton_or in H2. nin H2;subst;am.\nrw union_strict_cond_rw;ir. nin H4.\napply doubleton_or in H2;apply doubleton_or in H3.\nnin H2;nin H3;subst.\ntv. rwi H1 H4. apply emptyset_empty in H4. nin H4.\nrwi inter2_comm H4. rwi H1 H4. apply emptyset_empty in H4. nin H4.\ntv.\nap doubleton_l.\nam.\nQed.\n\nLemma union2_ev_r : forall f g, axioms f -> axioms g ->\n inter2 (domain f) (domain g) = emptyset -> \nforall x (Hinc : inc x (domain g)), ev (union2 f g) x = ev g x.\nProof.\nir. uf union2. ap union_ev.\n\nir. apply doubleton_or in H2. nin H2;subst;am.\nrw union_strict_cond_rw. ir. nin H4.\napply doubleton_or in H2;apply doubleton_or in H3.\nnin H2;nin H3;subst.\ntv. rwi H1 H4. apply emptyset_empty in H4. nin H4.\nrwi inter2_comm H4. rwi H1 H4. apply emptyset_empty in H4. nin H4.\ntv.\nap doubleton_r.\nam.\nQed.\n\nLemma union_range : forall e, (forall f, inc f e -> axioms f) -> \nunion_strict_cond e ->\nrange (union e) = union (Im range e).\nProof.\nir. ap extensionality;uhg;ir.\napply range_ex in H1. nin H1;ee;subst.\nrwi union_domain H1;try am.\napply union_ex in H1. nin H1;ee.\napply Im_ex in H1. nin H1;ee;subst.\nap union_inc;econstructor. ee.\nap Im_inc. am. ap range_show_inc.\nap H;am. econstructor;ee.\nam. \nsymmetry. ap union_ev. am. am.\nam. am.\nap union_axioms;am.\n\nap range_show_inc.\nap union_axioms;am.\napply union_ex in H1;nin H1;ee.\napply Im_ex in H1;nin H1;ee;subst.\napply range_ex in H2. nin H2;ee;subst.\neconstructor. ee. rw union_domain. ap union_inc;econstructor.\nee. ap Im_inc. am. am.\nam. am.\nap union_ev. am. am. am. am.\nap H;am.\nQed.\n\nLemma union2_range :  forall f g, axioms f -> axioms g ->\n inter2 (domain f) (domain g) = emptyset -> \nrange (union2 f g) = union2 (range f) (range g).\nProof.\nir. uf union2. etransitivity.\nap union_range.\n\nir. apply doubleton_or in H2. nin H2;subst;am.\nrw union_strict_cond_rw. ir. nin H4.\napply doubleton_or in H2;apply doubleton_or in H3.\nnin H2;nin H3;subst.\ntv. rwi H1 H4. apply emptyset_empty in H4. nin H4.\nrwi inter2_comm H4. rwi H1 H4. apply emptyset_empty in H4. nin H4.\ntv.\n\nap uneq.\nap extensionality_rw;ir.\nrw Im_rw. ap iff_eq;ir.\nnin H2;ee;subst. apply doubleton_or in H2. nin H2;subst;[apply doubleton_l|apply doubleton_r].\napply doubleton_or in H2;nin H2;ee;subst;econstructor;ee;au.\nap doubleton_l. ap doubleton_r.\nQed.\n\nDefinition union_cond e := forall f, inc f e -> forall g, inc g e -> \nforall x, inc x (domain f) -> inc x (domain g) -> ev f x = ev g x.\n\nLemma union_cond_rw : union_cond = fun e => \n(forall f g, inc f e -> inc g e -> forall x, inc x (inter2 (domain f) (domain g)) ->\n ev f x = ev g x).\nProof.\nap arrow_extensionality;intros e.\nuf union_cond;ap iff_eq;ir.\napply inter2_and in H2;ee;eapply H;try am.\neapply H;try am. ap inter2_inc;am.\nQed.\n\nLemma union_compatible_axioms : forall e, (forall f, inc f e -> axioms f) -> \nunion_cond e -> \naxioms (union e).\nProof.\nrw union_cond_rw;ir. uhg;ee;uhg;ir;[|uhg;ir].\napply union_ex in H1;nin H1. ee.\neapply H. am. am.\n\napply union_ex in H1;apply union_ex in H2;nin H1;nin H2;ee.\nassert (y = ev x0 x). ap fun_show_ev. ap H. am. am.\nrw H5. assert (y' = ev x1 x). ap fun_show_ev.\nap H;am. am. rw H6. ap H0. am. am. ap inter2_inc.\napply domain_P_in in H4. clpri H4. am. ap H;am.\napply domain_P_in in H3. clpri H3. am. ap H;am.\nQed.\n\nLemma union_compatible_domain : forall e, (forall f, inc f e -> axioms f) -> \nunion_cond e ->\ndomain (union e) = union (Im domain e).\nProof.\nrw union_cond_rw;ir.\nap extensionality;uhg;ir.\napply domain_ev_inc in H1. apply union_ex in H1.\nnin H1;ee.\nap union_inc. econstructor;ee.\nap Im_inc. am. ap domain_inc. econstructor;am.\nap union_compatible_axioms;try rw union_cond_rw;am.\napply union_ex in H1;nin H1;ee.\napply Im_ex in H1. nin H1;ee;subst.\nap domain_inc.\napply domain_ev_inc in H2.\neconstructor. ap union_inc. econstructor;ee. am. am.\nap H;am.\nQed.\n\nLemma union_compatible_ev :  forall e, (forall f, inc f e -> axioms f) -> \nunion_cond e -> \nforall f, inc f e -> forall x, inc x (domain f) -> ev (union e) x = ev f x.\nProof.\nrw union_cond_rw;ir.\nassert (inc x (domain (union e))).\nrw union_compatible_domain;try am. ap union_inc;econstructor.\nee. ap Im_inc. am. am.\nrw union_cond_rw;am.\napply domain_ev_inc in H3. \nassert (axioms (union e)). ap union_compatible_axioms. am. \nrw union_cond_rw;am.\napply H4 with x. am.\nap union_inc;econstructor. ee. am. ap domain_ev_inc. ap H;am. am.\nap union_compatible_axioms;try am. rw union_cond_rw;am.\nQed.\n\nLemma union_compatible_range : forall e, (forall f, inc f e -> axioms f) -> \nunion_cond e ->\nrange (union e) = union (Im range e).\nProof.\nir. assert (Hcond : union_cond e).\nam.\nrwi union_cond_rw H0.\nap extensionality;uhg;ir.\napply range_ex in H1. nin H1;ee;subst.\nrwi union_compatible_domain H1;try am.\napply union_ex in H1. nin H1;ee.\napply Im_ex in H1. nin H1;ee;subst.\nap union_inc;econstructor. ee.\nap Im_inc. am. ap range_show_inc.\nap H;am. econstructor;ee.\nam. \nsymmetry. ap union_compatible_ev. am. am.\nam. am.\nap union_compatible_axioms;am.\n\nap range_show_inc.\nap union_compatible_axioms;am.\napply union_ex in H1;nin H1;ee.\napply Im_ex in H1;nin H1;ee;subst.\napply range_ex in H2. nin H2;ee;subst.\neconstructor. ee. rw union_compatible_domain. ap union_inc;econstructor.\nee. ap Im_inc. am. am.\nam. am.\nap union_compatible_ev. am. am. am. am.\nap H;am.\nQed.\n\nLemma union_compatible_all : forall e, (forall f, inc f e -> axioms f) -> \nunion_cond e ->\n(axioms (union e) & domain (union e) = union (Im domain e) & \n(forall f, inc f e -> forall x, inc x (domain f) -> ev (union e) x = ev f x)).\nProof.\nir;ee.\nap union_compatible_axioms;am.\nap union_compatible_domain;am.\nap union_compatible_ev;am.\nQed.\n\nLemma union_compatible_restr : forall e, (forall f, inc f e -> axioms f) -> \nunion_cond e ->\nforall f, inc f e -> restr (union e) (domain f) = f.\nProof.\nir. destruct union_compatible_all with e.\nam. am.\nee.\n\nap function_extensionality;au.\nap restr_axioms. am.\nrw restr_domain;au.\nap extensionality. ap inter2_r.\nuhg;ir. ap inter2_inc;au.\nrw H3. ap union_inc. exists (domain f);ee.\nap Im_inc. am. am.\n\nir. rwi restr_domain H5;au. apply inter2_r in H5.\nrw restr_ev;au.\nrw H3. ap union_inc. exists (domain f);ee;au.\nap Im_inc;am.\nQed.\n\nLemma tack_on_axioms : forall f, axioms f -> forall x, ~inc x (domain f) -> forall y,\naxioms (tack_on f (J x y)).\nProof.\nir. uhg;ee;uhg;ir;[|uhg;ir].\nir. rwi tack_on_inc H1. nin H1. ap H;am.\nsubst. ap pair_is_pair.\nir. rwi tack_on_inc H1;rwi tack_on_inc H2;nin H1;nin H2.\neapply H;am.\napply pair_eq in H2. ee.\nsubst. nin H0.\nap domain_inc. exists y0;am.\napply pair_eq in H1;ee;subst.\nnin H0. ap domain_inc. exists y';am.\napply pair_eq in H2;au. apply pair_eq in H1;ee;subst;au.\nQed.\n\nLemma tack_on_ev_eq : forall f, axioms f -> forall x, ~ inc x (domain f) -> forall y,\nev (tack_on f (J x y)) x = y.\nProof.\nir. symmetry. ap fun_show_ev. ap tack_on_axioms;am.\nrw tack_on_inc;au.\nQed.\n\nLemma tack_on_ev_neq : forall f, axioms f -> forall x, ~ inc x (domain f) -> \nforall z, inc z (domain f) -> forall y, ev (tack_on f (J x y)) z = ev f z.\nProof.\nir;symmetry;ap fun_show_ev. ap tack_on_axioms;am.\nrw tack_on_inc;left. ap domain_ev_inc. am. am.\nQed.\n\nLemma tack_on_domain : forall f x y, domain (tack_on f (J x y)) =\n tack_on (domain f) x.\nProof.\nir. ap extensionality;uhg;ir.\nrw tack_on_inc.\napply Z_pr in H. nin H.\nrwi tack_on_inc H;nin H.\nleft. ap domain_inc. exists x0;am.\napply pair_eq in H;ee;subst.\nau.\nrwi tack_on_inc H;nin H;subst.\nap domain_inc. apply Z_pr in H. nin H.\nexists x0;rw tack_on_inc;au.\nap domain_inc. exists y;rw tack_on_inc;au.\nQed.\n\nEnd Function.\n\nModule Map.\nImport Function.\n\nDefinition is_map a b f := \nand (Function.axioms f)\n(and (domain f = a)\n(sub (range f) b)).\n\nLemma map_extensionality : forall a b f, is_map a b f -> forall g, is_map a b g -> \n(forall x, inc x a -> ev f x = ev g x) -> f=g.\nProof.\nir. ap function_extensionality. am. am.\ntransitivity a. am. symmetry;am.\nreplace (domain f) with a. am.\nsymmetry;am.\nQed.\n\nLemma map_sub : forall a b f, is_map a b f -> forall a' b' f', sub a a' -> \nis_map a' b' f' -> (forall x, inc x a -> ev f' x = ev f x) -> sub f f'.\nProof.\nir. ap function_sub;try am.\nreplace (domain f) with a. replace (domain f') with a'. am.\nsymmetry;am. symmetry;am.\nreplace (domain f) with a. am.\nsymmetry;am.\nQed.\n\nLemma trans_of_map : forall a b f, is_map a b f -> \nApplication.axioms a b (ev f).\nProof.\nir;uhg;ir.\nap H. ap range_ev_inc. am.\nuh H;ee. rw H1. am.\nQed.\n\nLemma map_of_trans : forall a b f, Application.axioms a b f -> \nis_map a b (create a f).\nProof.\nir.\nuhg;ee. ap create_axioms.\nap create_domain.\nuhg;ir. rewrite create_range in H0. apply Im_ex in H0. nin H0. ee.\nsubst.\nap H;am.\nQed.\n\nLemma axioms_map : forall f, axioms f -> is_map (domain f) (range f) f.\nProof.\nir. uhg;ee. am. tv. ap sub_refl.\nQed.\n\nDefinition injective a b f := is_map a b f & (Application.injects a (ev f)).\nDefinition surjective a b f := is_map a b f & (Application.covers a b (ev f)).\nDefinition bijective a b f := is_map a b f & (Application.injects a (ev f))\n&  (Application.covers a b (ev f)).\n\nLemma bijective_injective : forall a b f, bijective a b f -> injective a b f.\nProof.\nir;uhg;ee;am.\nQed.\n\nLemma bijective_surjective : forall a b f, bijective a b f -> surjective a b f.\nProof.\nir;uhg;ee;am.\nQed. \n\nLemma surjective_range : forall a b f, surjective a b f -> range f = b.\nProof.\nir. ap extensionality. am.\nuhg;ir.\nap range_show_inc. am.\ncp H0. apply H in H1. nin H1;ee. exists x. ee.\nuh H;ee;uh H;ee. rw H4. am. am.\nQed.\n\nLemma bijective_rw : forall a b f, bijective a b f = and (injective a b f) (surjective a b f).\nProof.\nir;ap iff_eq;ir;ee;uhg;ee;am.\nQed.\n\nLemma surjective_range_rw : forall a b f, surjective a b f = \nand (is_map a b f) (range f = b).\nProof.\nir. ap iff_eq;ir.\nee. am.\neapply surjective_range. am.\nee. uhg;ee. am.\nwr H0. uhg;ir.\napply range_ex in H1. uh H;ee. rwi H2 H1.\nnin H1. exists x;ee;au.\nam.\nQed.\n\nLemma range_surjective : forall a b f, is_map a b f -> range f = b -> \nsurjective a b f.\nProof.\nir;rw surjective_range_rw;ee;am.\nQed.\n\nLemma range_bijective : forall a b f, injective a b f -> range f = b -> \nbijective a b f.\nProof.\nir;rw bijective_rw;ee. am. ap range_surjective;am.\nQed.\n\nDefinition map_set a b := Z (powerset (product a b)) (fun f => is_map a b f).\n\nLemma map_set_map : forall a b f, inc f (map_set a b) -> is_map a b f.\nProof.\nir.\neapply Z_pr. am.\nQed.\n\nLemma map_map_set : forall a b f, is_map a b f -> inc f (map_set a b).\nProof.\nir.\nap Z_inc.\nap powerset_inc. uhg;ir.\ncp H0. apply H in H0. nin H0. uh H;ee.\nap product_pair_inc.\nwr H0. ap domain_inc. exists b0;am.\nap H2. ap range_inc. exists a0;am.\nam.\nQed.\n\nLemma map_set_rw : forall a b f, inc f (map_set a b) = is_map a b f.\nProof.\nir;ap iff_eq.\nap map_set_map. ap map_map_set.\nQed.\n\nLemma map_to_sub : forall b b', sub b b' -> forall a f, is_map a b f -> is_map a b' f.\nProof.\nir. uhg;ee;au.\napply sub_trans with b;am.\nQed.\n\nLemma injective_sub : forall b b', sub b b' -> forall a f, injective a b f ->\n injective a b' f.\nProof.\nir. uhg;ee.\napply map_to_sub with b;am. am.\nQed.\n\nLemma id_map : forall a, is_map a a (id a).\nProof.\nir. uhg;ee.\nap id_axioms. ap id_domain. rw id_range. ap sub_refl.\nQed.\n\nLemma id_injective : forall a, injective a a (id a).\nProof.\nir. uhg;ee. ap id_map.\nuhg;ir. rwi id_ev H1;au. rwi id_ev H1;au.\nQed.\n\nLemma id_surjective : forall a, surjective a a (id a).\nProof.\nir. uhg;ee. ap id_map.\nuhg;ir.\nexists y;ee. am. ap id_ev. am.\nQed.\n\nLemma id_bijective : forall a, bijective a a (id a).\nProof.\nir. rw bijective_rw. ee.\nap id_injective.\nap id_surjective.\nQed.\n\n(*needs choice*)\nDefinition inverse f := create (range f)\n (fun y => choose (fun x => inc x (domain f) & y = ev f x)).\n\nLemma inverse_axioms : forall f, axioms (inverse f).\nProof.\nir;ap create_axioms.\nQed.\n\nLemma inverse_domain : forall f, domain (inverse f) = range f.\nProof.\nir;ap create_domain.\nQed.\n\nLemma inverse_ev_pr : forall f, axioms f -> forall y, inc y (range f) -> \n(inc (ev (inverse f) y) (domain f) & y = ev f (ev (inverse f) y)).\nProof.\nir.\nuf inverse. rw create_ev.\nap choose_pr. apply range_ex in H0. am. am.\nam.\nQed.\n\nLemma inverse_range_sub : forall f, axioms f -> sub (range (inverse f)) (domain f).\nProof.\nir. uhg;ir.\napply range_ex in H0. nin H0;ee;subst.\nap inverse_ev_pr. am.\nwr inverse_domain. am.\nap inverse_axioms.\nQed.\n\nLemma inverse_ev_r : forall f, axioms f -> forall y, inc y (range f) -> \ny = ev f (ev (inverse f) y).\nProof.\nir;ap inverse_ev_pr. am. am.\nQed.\n\nLemma surjective_inverse_map : forall a b f, surjective a b f -> \nis_map b a (inverse f).\nProof.\nir. uhg;ee.\nap inverse_axioms.\nrw inverse_domain. eapply surjective_range. am.\n\nuh H;ee;uh H;ee.\nwr H1. ap inverse_range_sub. am.\nQed.\n\nLemma inverse_injects : forall f, axioms f ->\n Application.injects (range f) (ev (inverse f)).\nProof.\nuhg. ir.\nrw (inverse_ev_r H H0). rw (inverse_ev_r H H1).\nrw H2. tv.\nQed.\n\nLemma surjective_inverse_injective : forall a b f, surjective a b f ->\n injective b a (inverse f).\nProof.\nuhg. ir;ee. ap surjective_inverse_map. am.\nrwi surjective_range_rw H. ee;subst.\nap inverse_injects. am.\nQed.\n\nDefinition inverseT a b f g := \nand (forall x, inc x a -> g (f x) = x)\n(forall y, inc y b -> f (g y) = y).\n\nLemma inverseT_sym : forall a b f g, inverseT a b f g -> inverseT b a g f.\nProof.\nuf inverseT;ir;ee;am.\nQed.\n\nDefinition are_inverse a b f g := \nand (is_map a b f)\n(and (is_map b a g)\n(inverseT a b (ev f) (ev g))).\n\nLemma are_inverse_sym : forall a b f g, are_inverse a b f g -> are_inverse b a g f.\nProof.\nuf are_inverse;ir;ee;try am. ap inverseT_sym;am.\nQed.\n\nLemma are_inverse_bijective : forall a b f g, are_inverse a b f g -> bijective a b f.\nProof.\nir.\nuh H;ee. uh H1;ee.\nuhg;ee. am.\nuhg;ir.\ncp (uneq (ev g) H5).\nrwi H1 H6. rwi H1 H6. am. am. am.\nuhg;ir.\nexists (ev g y). ee. eapply trans_of_map;am. ap H2. am.\nQed.\n\nLemma inverseT_bijective : forall a b f g, Application.axioms a b f -> \nApplication.axioms b a g -> inverseT a b f g -> \nApplication.bijective a b f.\nProof.\nir. uhg;ee. am.\nuhg;ir.\ncp (uneq g H4).\nuh H1;ee. rwi H1 H5. rwi H1 H5. am. am. am.\nuhg;ir.\nuh H1;ee.\neconstructor;ee. ap H0. am.\nap H3;am.\nQed. (*need both axioms for bijective + covers*)\n\nLemma are_inverse_bijective_both : forall a b f g, are_inverse a b f g ->\nand (bijective a b f) (bijective b a g).\nProof.\nir;ee.\neapply are_inverse_bijective. am.\neapply are_inverse_bijective. ap are_inverse_sym. am.\nQed.\n\nLemma bijective_inverse_of : forall a b f, bijective a b f -> \nare_inverse a b f (inverse f).\nProof.\nir. uhg;ee.\nam.\nuhg;ee. ap inverse_axioms.\nrw inverse_domain. rwi bijective_rw H. rwi surjective_range_rw H.\nam.\nuh H;ee;uh H;ee. wr H2.\nap inverse_range_sub. am.\nuhg;ee.\nir. ap H.\neapply trans_of_map. eapply surjective_inverse_map. rwi bijective_rw H;am.\neapply trans_of_map;am.\nam.\nwr inverse_ev_r. tv. am. ap range_ev_inc. am. uh H;ee;uh H;ee. rw H3;am.\nir.\nsymmetry. ap inverse_ev_r. am.\nrwi bijective_rw H;rwi surjective_range_rw H. ee. rw H2;am.\nQed.\n\nLemma bijective_eq_inverse : forall a b f, bijective a b f = ex (are_inverse a b f).\nProof.\nir. ap iff_eq; ir.\nexists (inverse f). ap bijective_inverse_of. am.\nnin H. eapply are_inverse_bijective. am.\nQed.\n\nLemma inverse_unicity : forall a b f g, are_inverse a b f g ->\n forall g', are_inverse a b f g' -> \ng=g'.\nProof.\nir. uh H;ee;uh H0;ee.\nap function_extensionality;au.\netransitivity;au. symmetry;am.\nir.\n\nreplace (domain g) with b in H5.\nassert (x = ev f (ev g x)).\nsymmetry. ap H2. am.\nrw H6.\nuh H2;uh H4;ee. rw H2. rw H4. tv. \neapply trans_of_map;am. eapply trans_of_map;am.\nsymmetry;am.\nQed.\n\nLemma id_inverse : forall a, are_inverse a a (id a) (id a).\nProof.\nir.\nuhg;ee.\nap id_map. ap id_map.\nuhg;ee;ir;repeat rw id_ev;try am. tv. tv.\nQed.\n\nLemma bijective_inverse_bijective : forall a b f, bijective a b f -> \nbijective b a (inverse f).\nProof.\nir. apply bijective_inverse_of in H. apply are_inverse_bijective_both in H.\nam.\nQed.\n\nLemma bijective_range : forall a b f, bijective a b f -> range f = b.\nProof.\nir;rwi bijective_rw H;rwi surjective_range_rw H. am.\nQed.\n\nLemma map_composable : forall a b c f g, is_map a b f -> is_map b c g -> \ncomposable g f.\nProof.\nir. uh H;uh H0;ee;subst.\nuhg;ee.\nam. am.\nam.\nQed.\n\nLemma map_compose : forall a b c f g, is_map a b f -> is_map b c g -> \nis_map a c (compose g f).\nProof.\nir.\nassert (Hc : composable g f). eapply map_composable. am. am.\n uh H;uh H0;ee;subst.\nuhg;ee. ap compose_axioms.\nrw composable_domain. tv.\nuhg;ee;au.\nuhg;ir.\napply range_ex in H1. nin H1;ee.\nrwi composable_domain H1.\nsubst. ap H2. rw compose_ev.\nap range_ev_inc. am.\nap H4. ap range_ev_inc. am. am.\nrw composable_domain. am.\nam. am.\nap compose_axioms.\nQed.\n\nLemma map_compose_rw : forall a b c f g, is_map a b f -> is_map b c g -> \ncompose g f = L a (fun x => ev g (ev f x)).\nProof.\nir.\ncp (map_composable H H0).\n ap function_extensionality.\nap compose_axioms. ap create_axioms.\nrw create_domain. etransitivity. \nap composable_domain. am. am.\nir. assert (domain (compose g f) =  a).\nFocus 2. rwi H3 H2.\nrw create_ev. ap compose_ev.\nrw H3;am.\nam.\nrw composable_domain;am.\nQed.\n\nLemma map_compose_ev : forall a b c f g, is_map a b f -> is_map b c g -> \nforall x, inc x a -> ev (compose g f) x = ev g (ev f x).\nProof.\nir. erewrite map_compose_rw. etransitivity. ap create_ev.\nam. tv.\nam. am.\nQed.\n\nLemma map_compose_assoc : forall a b f, is_map a b f -> \nforall c g, is_map b c g -> \nforall d h, is_map c d h -> \ncompose h (compose g f) = compose (compose h g) f.\nProof.\nir.\nrw (map_compose_rw (map_compose H H0) H1).\nrw (map_compose_rw H H0).\nrw (map_compose_rw H (map_compose H0 H1)).\nrw (map_compose_rw H0 H1).\nap create_extensionality;ir.\nrepeat rw create_ev;au.\neapply trans_of_map;am.\nQed.\n\nLemma map_compose_id_r : forall a b f, is_map a b f -> \ncompose f (id a) = f.\nProof.\nir. erewrite map_compose_rw.\nFocus 2. ap id_map.\nFocus 2. am.\nap function_extensionality.\nap create_axioms. am.\nrw create_domain;symmetry;am.\nrw create_domain. ir.\nrw create_ev. rw id_ev. tv. am. am.\nQed.\n\nLemma map_compose_id_l : forall a b f, is_map a b f -> \ncompose (id b) f = f.\nProof.\nir. erewrite map_compose_rw.\nFocus 3. ap id_map.\nFocus 2. am.\nap function_extensionality.\nap create_axioms. am.\nrw create_domain;symmetry;am.\nrw create_domain. ir.\nrw create_ev. rw id_ev. tv. eapply trans_of_map;am. am.\nQed.\n\nLemma bijective_inverse_compose_r : forall a b f, bijective a b f -> \ncompose f (inverse f) = id b.\nProof.\nir. ap function_extensionality.\nap compose_axioms. ap id_axioms.\nrw id_domain. rw composable_domain. rw inverse_domain.\napply bijective_range with a;am.\neapply map_composable. ap bijective_inverse_bijective. am. am.\nir.\ncp (bijective_inverse_of H).\n rwi composable_domain H0. rwi inverse_domain H0. \nrwi (bijective_range H) H0. rw compose_ev.\nrw id_ev. ap H1. am. am.\nrw composable_domain. rw inverse_domain. erewrite bijective_range. ap H0.\nam. eapply map_composable. ap bijective_inverse_bijective. am.\nam. eapply map_composable. ap bijective_inverse_bijective. am.\nam.\nQed.\n\nLemma bijective_inverse_compose_l :  forall a b f, bijective a b f -> \ncompose (inverse f) f = id a.\nProof.\nir.\nassert (composable (inverse f) f). eapply map_composable. am.\nap bijective_inverse_bijective;am.\ncp (composable_domain H0). replace (domain f) with a in H1.\nap function_extensionality. ap compose_axioms. ap id_axioms.\nrw id_domain. am.\nir. rwi H1 H2. rw compose_ev. rw id_ev. cp (bijective_inverse_of H).\nuh H3;ee. uh H5;ee. ap H5. am. am. rw H1;am.\nuh H;ee. symmetry;ap H.\nQed.\n\nLemma bijective_inverse_ev_l : forall a b f, bijective a b f -> forall x, \ninc x a -> ev (inverse f) (ev f x) = x.\nProof.\nir. wr compose_ev. rw (bijective_inverse_compose_l H). ap id_ev;am.\nrw composable_domain. replace( domain f) with a. am. symmetry;uh H;ee;ap H.\neapply map_composable;try am. ap bijective_inverse_bijective;am.\nQed.\n\nLemma bijective_inverse_ev_r : forall a b f, bijective a b f -> forall x, \ninc x b -> ev f (ev (inverse f) x) = x.\nProof.\nir. wr compose_ev. rw (bijective_inverse_compose_r H). ap id_ev;am.\nrw composable_domain. \nrw inverse_domain. erewrite bijective_range;am.\neapply map_composable;try am. ap bijective_inverse_bijective;am.\nQed.\n\n\nDefinition are_equipotent a b := exists f, bijective a b f.\n\nLemma are_equipotent_refl : forall a, are_equipotent a a.\nProof.\nir. exists (id a). ap id_bijective.\nQed.\n\nLemma are_equipotent_sym : forall a b, are_equipotent a b -> are_equipotent b a.\nProof.\nir.\nnin H.\nexists (inverse x).\nap bijective_inverse_bijective. am.\nQed.\n\nLemma injective_compose : forall a b c f g, injective a b f -> injective b c g -> \ninjective a c (compose g f).\nProof.\nir.\nuhg;ee.\neapply map_compose. am. am.\nuh H;ee;uh H0;ee.\ncp ( map_composable H H0).\nuhg;ir.\nrwi compose_ev H6. rwi compose_ev H6.\napply H2 in H6. ap H1.\nam. am. am.\nuh H;uh H0;ee; subst.\nap H10. ap range_ev_inc. am. am.\n\nuh H;uh H0;ee; subst.\nap H10. ap range_ev_inc. am. am.\n\nrw composable_domain;au.\nuh H;ee;subst. am.\nrw composable_domain;au;uh H;ee;subst;am.\nQed.\n\nLemma surjective_compose : forall a b c f g, surjective a b f -> surjective b c g -> \nsurjective a c (compose g f).\nProof.\nintros a b c f g. repeat rw surjective_range_rw.\nir;ee. eapply map_compose;am.\nsubst. uh H;ee;uh H0;ee;subst.\nap extensionality;uhg;ir.\napply range_ex in H1. nin H1;ee;subst.\nrw compose_ev. ap range_ev_inc. am.\nrwi composable_domain H1. rw H3. ap range_ev_inc. am. am.\nuhg;ee;au. rw H3;ap sub_refl.\nam.\nap compose_axioms.\napply range_ex in H1. nin H1;ee;subst.\nrwi H3 H1. apply range_ex in H1. nin H1;ee. subst.\nap range_show_inc. ap compose_axioms. exists x0.\nee. rw composable_domain.\nam.\nuhg;ee;au. rw H3;ap sub_refl.\nap compose_ev. rw composable_domain. am.\nuhg;ee;au;rw H3;ap sub_refl.\nam. am.\nQed.\n\nLemma bijective_compose : forall a b c f g, bijective a b f -> bijective b c g -> \nbijective a c (compose g f).\nProof.\nintros a b c f g. repeat rw bijective_rw.\nir;ee. eapply injective_compose;am. eapply surjective_compose;am.\nQed.\n\nLemma are_equipotent_trans : forall a b c, are_equipotent a b ->\n are_equipotent b c -> are_equipotent a c.\nProof.\nir.\nnin H;nin H0. econstructor.\neapply bijective_compose;am.\nQed.\n\nLemma map_of_bijective : forall a b f, Application.bijective a b f ->\n bijective a b (create a f).\nProof.\nir. uh H;ee.\nuhg;ee.\nap map_of_trans. am.\nuhg;ir.\nap H0. am. am. rwi create_ev H4;au;rwi create_ev H4;au.\n\nuhg;ir. cp H2. apply H1 in H3. nin H3. ee;subst.\nexists x;ee. am.\nap create_ev;am.\nQed.\n\nLemma bijective_of_map : forall a b f, bijective a b f -> Application.bijective a b (ev f).\nProof.\nir;uhg;ee.\nap trans_of_map. am.\nam. am.\nQed.\n\nLemma are_equipotent_transformation : forall a b, are_equipotent a b =\n (ex (Application.bijective a b)).\nProof.\nir;ap iff_eq;ir;nin H.\nexists (ev x). ap bijective_of_map. am.\nexists (Function.create a x). ap map_of_bijective. am.\nQed.\n\nLemma trans_equipotent : forall a b, ex (Application.bijective a b) ->\n are_equipotent a b.\nProof.\nir;rw are_equipotent_transformation. am.\nQed.\n\nLemma map_set_curry : forall a b c, are_equipotent (map_set (product b c) a)\n (map_set c (map_set b a)).\nProof.\nir. rw are_equipotent_transformation.\nexists (fun f => L c (fun x => L b (fun y => ev f (J y x)))).\nuhg;ee;uhg;ir.\nrw map_set_rw. ap map_of_trans.\nuhg;ir. rw map_set_rw. ap map_of_trans.\nuhg;ir. rwi map_set_rw H. eapply trans_of_map.\nam. ap product_pair_inc;am.\nrwi map_set_rw H;rwi map_set_rw H0.\nap function_extensionality;try am.\nuh H0;ee. rw H2. am.\nir. uh H;ee. rwi H3 H2.\napply product_pr in H2;ee. nin H2. clpri H5;clpri H6.\ntransitivity (ev (ev  (L c (fun x0 : E => L b (fun y : E => ev x (J y x0)))) b0) a0).\nrw create_ev. rw create_ev. tv. am. am.\nrw H1.\nrw create_ev. rw create_ev. tv. am. am.\n\nrwi map_set_rw H.\nexists (L (product b c) (fun p => ev (ev y (Q p)) (P p))).\nee. rw map_set_rw.\nap map_of_trans. uhg;ir.\napply product_pr in H0;ee;nin H0. clpri H1;clpri H2.\nclpr. eapply trans_of_map. wr map_set_rw. eapply trans_of_map. am.\nam. am.\n\nap function_extensionality. ap create_axioms. am.\nrw create_domain. symmetry;am.\nir.\nrwi create_domain H0.\nrw create_ev. cp (trans_of_map H). cp (H1 x H0).\nclear H1.\nrwi map_set_rw H2.\nap function_extensionality. ap create_axioms. am.\nrw create_domain. symmetry;am.\nrw create_domain. ir.\nrw create_ev. rw create_ev. clpr.\ntv.\nap product_pair_inc;am. am. am.\nQed.\n\nLemma map_of_injective : forall a b f, Application.injective a b f ->\n injective a b (create a f).\nProof.\nir. uh H;ee.\nuhg;ee.\nap map_of_trans. am.\nuhg;ir.\nap H0. am. am. rwi create_ev H3;au;rwi create_ev H3;au.\nQed.\n\nLemma injective_of_map : forall a b f, injective a b f ->\n Application.injective a b (ev f).\nProof.\nir;uhg;ee.\nap trans_of_map. am.\nam.\nQed.\n\nLemma map_of_surjective : forall a b f, Application.surjective a b f ->\n surjective a b (create a f).\nProof.\nir. uh H;ee.\nuhg;ee.\nap map_of_trans. am.\nuhg;ir. cp H1. apply H0 in H2. nin H2. ee;subst.\nexists x;ee. am.\nap create_ev;am.\nQed.\n\nLemma surjective_of_map : forall a b f, surjective a b f ->\n Application.surjective a b (ev f).\nProof.\nir;uhg;ee.\nap trans_of_map. am.\nam.\nQed.\n\n\nLemma tack_on_map : forall a b f, is_map a b f -> forall x, ~inc x a -> forall y, \nis_map (tack_on a x) (tack_on b y) (tack_on f (J x y)).\nProof.\nir. uh H;ee. subst.\nuhg;ee. ap tack_on_axioms;am.\nap tack_on_domain.\nuhg;ir.\napply range_ex in H1. nin H1;ee;subst.\nrwi tack_on_domain H1. rwi tack_on_inc H1;nin H1;subst.\nrw tack_on_inc;left. ap H2. rw tack_on_ev_neq. ap range_ev_inc.\nam. am. am. am. am.\nrw tack_on_inc;right. rw tack_on_ev_eq;au.\nap tack_on_axioms;am.\nQed.\n\nLemma map_tack_on_ev_eq : forall a b f, is_map a b f -> \nforall x, ~inc x a -> forall y, ev (tack_on f (J x y)) x = y.\nProof.\nir. ap tack_on_ev_eq. am. uhg;ir. ap H0.\neapply eq_ind. am. am.\nQed.\n\nLemma map_tack_on_ev : forall a b f, is_map a b f ->\nforall x, ~inc x a -> forall z, inc z a -> forall y, ev (tack_on f (J x y)) z = ev f z.\nProof.\nir. ap tack_on_ev_neq. am. uhg;ir;ap H0;eapply eq_ind;am.\neapply eq_ind;try am. symmetry;am.\nQed.\n\nLemma tack_on_injective : forall a b f, injective a b f -> forall x, ~inc x a -> \nforall y, ~inc y b -> injective (tack_on a x) (tack_on b y) (tack_on f (J x y)).\nProof.\nir. uhg;ee. ap tack_on_map. am. am.\nuhg;ir.\nrwi tack_on_inc H2;rwi tack_on_inc H3;nin H2;nin H3;subst.\nrwi (map_tack_on_ev (and_P H)) H4;au. rwi (map_tack_on_ev (and_P H)) H4;au.\nap H;am.\nrwi (map_tack_on_ev (and_P H)) H4;au. rwi (map_tack_on_ev_eq (and_P H)) H4;au.\nnin H1. wr H4. eapply trans_of_map. am. am.\nrwi (map_tack_on_ev_eq (and_P H)) H4;au. rwi (map_tack_on_ev (and_P H)) H4;au.\nnin H1. rw H4. eapply trans_of_map. am. am.\ntv.\nQed.\n\nLemma tack_on_surjective : forall a b f, surjective a b f -> forall x, ~ inc x a -> \nforall y, surjective (tack_on a x) (tack_on b y) (tack_on f (J x y)).\nProof.\nir;uhg;ee. ap tack_on_map;am.\nuhg;ir.\nrwi tack_on_inc H1;nin H1;subst.\napply H in H1. nin H1;ee;subst.\nexists x0;ee. rw tack_on_inc;au.\nrw (map_tack_on_ev (and_P H)). tv. am. am.\nexists x;ee. rw tack_on_inc. au.\neapply map_tack_on_ev_eq. am. am.\nQed.\n\nLemma tack_on_bijective : forall a b f, bijective a b f -> forall x, ~inc x a -> \nforall y, ~inc y b -> bijective (tack_on a x) (tack_on b y) (tack_on f (J x y)).\nProof.\nir. rw bijective_rw. rwi bijective_rw H;ee.\nap tack_on_injective;am.\nap tack_on_surjective;am.\nQed.\n\nLemma bijective_inverseT : forall a b f, Application.bijective a b f -> exists g, \nApplication.bijective b a g & inverseT a b f g.\nProof.\nir.\ncp (map_of_bijective H).\ncp (bijective_inverse_of H0).\nexists (ev (inverse (L a f))). ee.\nap bijective_of_map. ap bijective_inverse_bijective. am.\nuh H1;ee.\nuhg;ee;ir. etransitivity. Focus 2. uh H3;ee. ap H3. am.\nrw create_ev;au.\n\netransitivity. Focus 2. ap H3. am.\nrw create_ev;au.\neapply trans_of_map. am. am.\nQed.\n\nLemma tack_on_equipotent : forall x y a b, ~inc a x -> ~ inc b y ->\nare_equipotent x y = are_equipotent (tack_on x a) (tack_on y b).\nProof.\nir;ap iff_eq;ir.\nnin H1. cp (bijective_of_map H1).\nassert (Application.bijective (tack_on x a) (tack_on y b) (fun z => \nif eq_dec z a then b else ev x0 z)).\nuhg;ee;uhg;ir.\nrwi tack_on_inc H3;nin H3. rw eq_dec_if_not.\nrw tack_on_inc;left. ap H2. am.\nuhg;ir;subst. au.\nsubst. rw eq_dec_if. rw tack_on_inc;au.\nrwi tack_on_inc H3;rwi tack_on_inc H4;nin H3;nin H4;subst.\nrwi eq_dec_if_not H5. rwi eq_dec_if_not H5.\nap H2;am.\nuhg;ir;subst. au.\nuhg;ir;subst;au.\nrwi eq_dec_if H5. rwi eq_dec_if_not H5.\nnin H0. wr H5. ap H2. am.\nuhg;ir. ap H. wr H4. am.\nrwi eq_dec_if H5. rwi eq_dec_if_not H5.\nnin H0. rw H5. ap H2. am.\nuhg;ir. ap H. wr H3. am.\ntv.\n\nrwi tack_on_inc H3;nin H3.\napply H2 in H3. nin H3;ee;subst.\nexists x1;ee. rw tack_on_inc;au.\nrw eq_dec_if_not. tv. uhg;ir;subst;au.\nsubst. exists a;ee. rw tack_on_inc;au.\nrw eq_dec_if. tv.\neconstructor. ap map_of_bijective. am.\n\nnin H1. cp (bijective_of_map H1).\nassert (inc b (tack_on y b)). rw tack_on_inc;au.\napply H1 in H3. nin H3;ee.\nsubst.\nrwi tack_on_inc H3;nin H3.\nassert (inc (ev x0 a) (tack_on y (ev x0 x1))). ap H2.\nrw tack_on_inc;au.\nrwi tack_on_inc H4;nin H4.\nFocus 2. apply H2 in H4. subst.\nnin H;am.\nrw tack_on_inc;au. rw tack_on_inc;au.\n\nassert (Application.bijective x y (fun z => if eq_dec z x1 then ev x0 a else\nev x0 z)).\nuhg;ee;uhg;ir.\nnin (eq_dec x2 x1). am.\nassert (inc (ev x0 x2) (tack_on y (ev x0 x1))). ap H2. rw tack_on_inc;au.\nrwi tack_on_inc H6;nin H6. am.\nnin b. ap H2. rw tack_on_inc;au. rw tack_on_inc;au.\nam.\n\nassert (forall j k, sub j (tack_on j k)).\nuhg;ir;rw tack_on_inc;au.\n\nnin (eq_dec x2 x1);nin (eq_dec y0 x1).\nsubst. tv.\napply H2 in H7;au. subst. nin H;am.\nrw tack_on_inc;au. ap H8. am.\nsubst. \napply H2 in H7 ;au. subst. nin H;am.\nap H8;am. rw tack_on_inc;au.\nap H2;au. ap H8;am. ap H8;am.\n\nnin (eq_dec y0 (ev x0 a)).\nsubst. exists x1;ee;au. rw eq_dec_if;tv.\nassert (inc y0 (tack_on y (ev x0 x1))).\nrw tack_on_inc;au.\napply H2 in H6. nin H6;ee;subst.\nrwi tack_on_inc H6;nin H6.\nexists x2;ee. am. rw eq_dec_if_not. tv.\nuhg;ir;subst. ap H0;am.\nsubst. nin b;tv.\neconstructor;ap map_of_bijective;am.\n\nsubst.\nassert (Application.bijective x y (ev x0)).\nuhg;ee;uhg;ir.\nassert (inc x1 (tack_on x a)). rw tack_on_inc;au.\napply H2 in H4. rwi tack_on_inc H4;nin H4;au.\nnin H. apply H2 in H4;au.\nsubst;au. rw tack_on_inc;au. rw tack_on_inc;au.\nap H2;au. rw tack_on_inc;au. rw tack_on_inc;au.\n\nassert (inc y0 (tack_on y (ev x0 a))).\nrw tack_on_inc;au. apply H2 in H4;nin H4;ee.\nsubst. rwi tack_on_inc H4;nin H4. exists x1;ee. am.\ntv.\nsubst. nin H0;am.\neconstructor;ap map_of_bijective;am.\nQed.\n\nLemma transfo_bijective_compose : forall a b c f g, Application.bijective a b f ->\n Application.bijective b c g -> \nApplication.bijective a c (fun x => g (f x)).\nProof.\nir. uhg;ee;uhg;ir.\nap H0;ap H;am.\nap H. am. am. ap H0;au. ap H;am. ap H;am.\ncp H1. apply H0 in H2. nin H2;ee.\napply H in H2. nin H2;ee;subst. exists x0;ee;au.\nQed.\n\nLemma union2_map : forall a b f a' b' g, is_map a b f -> is_map a' b' g -> \ninter2 a a' = emptyset -> is_map (union2 a a') (union2 b b') (union2 f g).\nProof.\nir.\nuh H;ee;uh H0;ee. wri H2 H1;wri H4 H1.\nuhg;ee.\nap union2_axioms;am. wr H2;wr H4. ap union2_domain;am.\nrw union2_range;try am.\n\nuhg;ir.\napply union2_or in H6. ap union2_inc. nin H6;au.\nQed.\n\nLemma union2_injective : forall a b f a' b' g, injective a b f -> injective a' b' g -> \ninter2 a a' = emptyset -> inter2 (range f) (range g) = emptyset ->\n injective (union2 a a') (union2 b b') (union2 f g).\nProof.\nir. uhg;ee.\nap union2_map;am.\nuhg;ir.\nassert (inter2 (domain f) (domain g) = emptyset).\nuh H;uh H0;ee;uh H;uh H0;ee.\nrw H10;rw H8. am.\napply union2_or in H3;apply union2_or in H4.\nnin H3;nin H4.\nrwi union2_ev_l H5. rwi union2_ev_l H5.\nap H. am. am. am.\nam. am. am. uh H;ee. uh H;ee. rw H8;am.\nam. am. am. uh H;ee. uh H;ee;rw H8;am.\n\nassert (domain f = a). uh H;ee. ap H.\nsubst. assert (domain g = a'). uh H0;ee;ap H0. subst.\nrwi union2_ev_l H5. rwi union2_ev_r H5.\nap False_rect. eapply emptyset_empty. wr H2.\nap inter2_inc. ap range_ev_inc. am. am. rw H5. ap range_ev_inc. am. am.\nam. am. am. am. am. am. am. am.\n\nassert (domain f = a). uh H;ee. ap H.\nsubst. assert (domain g = a'). uh H0;ee;ap H0. subst.\nrwi union2_ev_r H5. rwi union2_ev_l H5.\nap False_rect. eapply emptyset_empty. wr H2.\nap inter2_inc. ap range_ev_inc. am. am. wr H5. ap range_ev_inc. am. am.\nam. am. am. am. am. am. am. am.\n\nassert (domain f = a). uh H;ee. ap H.\nsubst. assert (domain g = a'). uh H0;ee;ap H0. subst.\nrwi union2_ev_r H5;try am. rwi union2_ev_r H5;try am.\nap H0. am. am. am.\nQed.\n\nLemma union2_fast_injective :  forall a b f a' b' g, injective a b f -> injective a' b' g -> \ninter2 a a' = emptyset -> inter2 b b' = emptyset ->\n injective (union2 a a') (union2 b b') (union2 f g).\nProof.\nir. ap union2_injective;try am.\nap empty_emptyset.\nir. \neapply emptyset_empty. wr H2. apply inter2_and in H3;ee.\nap inter2_inc;au. ap H. am. ap H0;am.\nQed.\n\nLemma union2_surjective : forall a b f a' b' g, surjective a b f -> surjective a' b' g -> \ninter2 a a' = emptyset -> surjective (union2 a a') (union2 b b') (union2 f g).\nProof.\nintros a b f a' b' g.\nrepeat rw surjective_range_rw. ir;ee.\nap union2_map;am.\nsubst. ap union2_range.\nam. am.\nreplace (domain f) with a;try am. wr H1. ap uneq. am. symmetry;am.\nQed.\n\nLemma union2_bijective : forall a b f a' b' g, bijective a b f -> bijective a' b' g -> \ninter2 a a' = emptyset -> inter2 (range f) (range g) = emptyset ->\n bijective (union2 a a') (union2 b b') (union2 f g).\nProof.\nintros until 0.\nrepeat rw bijective_rw. ir;ee;[ap union2_injective | ap union2_surjective];am.\nQed.\n\nLemma union2_fast_bijective : forall a b f a' b' g, bijective a b f -> bijective a' b' g -> \ninter2 a a' = emptyset -> inter2 b b' = emptyset ->\n bijective (union2 a a') (union2 b b') (union2 f g).\nProof.\nintros until 0.\nrepeat rw bijective_rw. ir;ee;[ap union2_fast_injective | ap union2_surjective];am.\nQed.\n\nDefinition iso_sub a b := exists x, are_equipotent a x & sub x b .\n\nLemma iso_sub_rw : forall a b, iso_sub a b = exists f, injective a b f.\nProof.\nir;ap iff_eq;ir.\nnin H. ee. nin H.\nexists x0. uhg;ee. uhg;ee. am. uh H;ee. ap H.\napply sub_trans with x. am. am. am.\nnin H. exists (range x). ee. Focus 2. am.\nexists x. rw bijective_rw. rw surjective_range_rw.\nassert (is_map a (range x) x). uhg;ee. am. uh H;ee;ap H. ap sub_refl.\nee. uhg;ee. am. am.\nam. tv.\nQed.\n\nDefinition iso_sub_strict a b := and (iso_sub a b) (~are_equipotent a b).\n\nLemma iso_sub_refl : forall a, iso_sub a a.\nProof.\nir;rw iso_sub_rw. exists (id a). ap id_injective.\nQed.\n\nLemma sub_iso_sub : forall a b, sub a b -> iso_sub a b.\nProof.\nir. uhg. exists a;ee;au.\nap are_equipotent_refl.\nQed.\n\nLemma iso_strict_irrefl : forall a, ~iso_sub_strict a a.\nProof.\nir;uhg;ir. ap H. ap are_equipotent_refl.\nQed.\n\nLemma iso_sub_trans : forall a b, iso_sub a b -> forall c, iso_sub b c -> iso_sub a c.\nProof.\nir. rwi iso_sub_rw H;rwi iso_sub_rw H0;rw iso_sub_rw.\nnin H;nin H0. econstructor.\neapply injective_compose. am. am.\nQed.\n\nLemma Im_iso_sub : forall x f, iso_sub (Im f x) x.\nProof.\nir. assert (Application.surjective x (Im f x) f).\nuhg;ee;uhg;ir. ap Im_inc;am. Im_nin H. subst;exists x0;ee;au.\nassert (ex (Application.surjective x (Im f x))). exists f;am.\napply Application.surjective_injective_back in H0.\nnin H0.\nrw iso_sub_rw. econstructor. ap map_of_injective. am.\nQed.\n\nLemma cantor_bernstein : forall s t, iso_sub s t -> iso_sub t s ->\n are_equipotent s t.\nProof.\nir. rwi iso_sub_rw H.\nrwi iso_sub_rw H0. destruct H as [f H];destruct H0 as [g H0].\nassert (Application.axioms s t (ev f) & Application.axioms t s (ev g)).\nee;eapply trans_of_map;am.\nee.\n\npose (cs := create (powerset s) (complement s)).\nassert (Application.axioms (powerset s) (powerset s) (complement s)).\nuhg;ir. ap powerset_inc. ap Z_sub. cp (map_of_trans H3).\npose (ct := create (powerset t) (complement t)).\nassert (Application.axioms (powerset t) (powerset t) (complement t)).\nuhg;ir. ap powerset_inc. ap Z_sub. cp (map_of_trans H5).\nfold cs in H4. fold ct in H6.\n\npose (z := fun a => complement s (Im (ev g) (complement t (Im (ev f) a)))).\nassert (Application.axioms (powerset s) (powerset s) z).\nuf z;uhg;ir. ap powerset_inc. ap Z_sub.\nassert (forall a b, sub a b -> sub (z a) (z b)).\nir. uf z. ap sub_complement.\nap Im_sub. ap sub_complement. ap Im_sub. am.\n\npose (F := Z (powerset s) (fun x => sub x (z x))).\nassert (nonempty F). exists emptyset. ap Z_inc.\nap powerset_inc. ap emptyset_sub_all. ap emptyset_sub_all.\n\npose (G := union F).\nassert (sub G s). uhg;ir. union_nin H10.\napply Z_sub in H10. apply powerset_sub in H10. au.\nassert (forall x, inc x F -> sub x G).\nir. uhg;ir;ap union_inc. exists x;ee;au.\nassert (forall x, inc x F -> sub x (z G)).\nir. cp (Z_all H12). ee. apply powerset_sub in H13.\napply sub_trans with (z x). am.\nap H8. ap H11. am.\n\nassert (sub G (z G)). uhg;ir.\nunion_nin H13. eapply H12. am. am.\nassert (sub (z G) (z (z G))). ap H8;am.\nassert (inc (z G) F). ap Z_inc.\nap powerset_inc. ap Z_sub. am.\nassert (sub (z G) G).\nuhg;ir;ap union_inc. exists (z G). ee. am. am.\n\nassert (z G = G). ap extensionality. am. am.\nassert (complement s G = Im (ev g) (complement t (Im (ev f) G))).\ntransitivity (complement s (z G)). rw H17. tv.\nuf z. ap complement_complement_id.\nuhg;ir. Im_nin H18.\nsubst. ap H2. eapply Z_sub;am.\n\npose (h := fun x => by_cases \n(fun _ : inc x G => ev f x)\n(fun _ : ~inc x G => ev (inverse g) x)).\n\nassert (sub (complement s G) (range g)).\nrw H18. uhg;ir.\nIm_nin H19;subst. ap range_ev_inc. am.\nreplace (domain g) with t. eapply Z_sub;am. symmetry.\nuh H0;ee;ap H0.\n\nassert (Application.axioms s t h).\nuhg;ir.\nuf h.\napply by_cases with (inc x G);ir.\nrw by_cases_if;try am.\nap H1. am.\nrw by_cases_if_not;try am.\nassert (inc x (complement s G)). ap Z_inc;am.\ncp (H19 x H22).\napply inverse_ev_pr in H23;try am.\nee.\nreplace t with (domain g). am. uh H0;ee;ap H0.\n\nassert (Hb : bijective t (range g) g).\nuhg;ee.\nuhg;ee. am. uh H0;ee;ap H0. ap sub_refl. am.\nuhg;ir. apply range_ex in H21. nin H21;ee;subst.\nexists x;ee;au. replace t with (domain g). am. uh H0;ee;ap H0.\nam.\n\nassert (bijective (range g) t (inverse g)).\nap bijective_inverse_bijective. am. \n\nassert (Application.bijective s t h).\nuhg;ee. am.\nuhg;ir. ufi h H24. apply by_cases with (inc x G);ir;apply by_cases with (inc y G);ir.\nrwi by_cases_if H24;try am. rwi by_cases_if H24;try am.\nap H. am. am. am.\n\nrwi by_cases_if H24;try am. rwi by_cases_if_not H24;try am.\nassert (inc y (complement s G)).\nap Z_inc;am. rwi H18 H27. Im_nin H27;subst.\napply Z_all in H27;ee.\nnin H28. ap Im_show_inc. exists x;ee.\nam. rw H24. \nrw (bijective_inverse_ev_l Hb). tv. am.\nrwi by_cases_if_not H24;try am. rwi by_cases_if H24;try am.\nassert (inc x (complement s G)). ap Z_inc;au.\nrwi H18 H27. Im_nin H27;subst.\napply Z_all in H27;ee. nin H28.\nap Im_show_inc. exists y;ee. am. wr H24. rw (bijective_inverse_ev_l Hb).\ntv. am.\n\nrwi by_cases_if_not H24;try am. rwi by_cases_if_not H24;try am.\nap H21. ap H19. ap Z_inc;au. ap H19. ap Z_inc;au.\nam.\nuhg;ir.\napply by_cases with (inc y (Im (ev f) G));ir.\nIm_nin H23;subst.\nexists x;ee. au. uf h. rw by_cases_if. tv. am.\ncp H22. apply H21 in H24. nin H24;ee;subst.\nexists x;ee. ap H0. am.\nuf h. rw by_cases_if_not. tv.\nuhg;ir.\nwri H17 H25. apply Z_all in H25;ee.\nap H26. ap Im_show_inc. exists (ev (inverse g) x);ee.\nap Z_inc;am. symmetry. eapply bijective_inverse_ev_r. ap Hb.\nam.\n\nexists (L s h). ap map_of_bijective. am.\nQed.\n\nEnd Map.\n\nModule Equipotent.\nExport Function. Export Map.\n\nLemma equipotent_union_strict : forall x y, \n(forall a b, inc a x -> inc b x -> nonempty (inter2 a b) -> a=b) -> \n(forall a b, inc a y -> inc b y -> nonempty (inter2 a b) -> a=b) ->\n(exists f, bijective x y f & forall a, inc a x -> are_equipotent a (ev f a)) -> \nare_equipotent (union x) (union y).\nProof.\nir. destruct H1 as [f H1];ee.\ncp (bijective_inverse_bijective H1).\nassert (forall a, inc a y -> are_equipotent a (ev (inverse f) a)).\nir. cp (bijective_inverse_ev_r H1).\ncp H4;apply H5 in H6. wr H6.\nrw (bijective_inverse_ev_l H1). Focus 2. eapply trans_of_map;am.\nap are_equipotent_sym. ap H2. eapply trans_of_map;am.\n\nrw are_equipotent_transformation.\npose (chpr := fun z a => inc a x & inc z a).\nassert (Hch : forall z, inc z (union x) -> chpr z (unique_choose (chpr z))).\nir;ap unique_choose_pr.\nunion_nin H5. exists x0;uhg;ee;am.\nuhg;ir. uh H6;ee;uh H7;ee.\nap H. am. am.\nexists z. ap inter2_inc;am.\n\npose (chpr' := fun z b => inc b y & inc z b).\nassert (Hch' : forall z, inc z (union y) -> chpr' z (unique_choose (chpr' z))).\nir;ap unique_choose_pr.\nunion_nin H5. exists x0;uhg;ee;am.\nuhg;ir. uh H6;ee;uh H7;ee.\nap H0. am. am.\nexists z. ap inter2_inc;am.\n\n(*NEED CHOICE FOR THIS*)\nassert (exists g, forall a, inc a x -> bijective a (ev f a) (g a)).\neconstructor;ir. cp (choose_pr (H2 a H5)). simpl in H6.\nap H6.\ndestruct H5 as [g H5].\nexists (fun z => let a := unique_choose (chpr z) in \n(*a is in x with z in a*)\nev (g a) z).\nuhg;ee;uhg;ir.\ncp (Hch x0 H6).\nuh H7;ee.\nap union_inc.\ncp (H5 (unique_choose (chpr x0)) H7).\ncp H8;apply (bijective_of_map H9) in H8.\neconstructor;ee. eapply trans_of_map. ap H1. ap H7.\nam.\n\napply Hch in H6;apply Hch in H7.\nset (a := unique_choose (chpr x0)) in *.\nset (b := unique_choose (chpr y0)) in *.\nuh H6;ee;uh H7;ee.\ncp (H5 a H6);cp (H5 b H7).\ncp H9. apply (bijective_of_map H11) in H13.\ncp H10. apply (bijective_of_map H12) in H14.\nassert (ev f a = ev f b).\nap H0. ap (bijective_of_map H1). am. ap (bijective_of_map H1). am.\nexists (ev (g a) x0). ap inter2_inc. am. rw H8. am.\n\napply H1 in H15.\nrwi H15 H8. apply H12.\nwr H15. am. am. am. am. am.\n\nunion_nin H6.\ncp H6. apply (bijective_of_map H1) in H8. nin H8;ee.\nsubst.\ncp (H5 x1 H8).\ncp H7. apply (bijective_of_map H9) in H10.\nnin H10;ee. subst.\nexists x0;dj. ap union_inc. exists x1;ee;am.\n\napply Hch in H11.\nuh H11;ee.\nassert (unique_choose (chpr x0) = x1).\nap H. am. am.\nexists x0;ap inter2_inc;am.\nrw H13. tv.\nQed.\n\nLemma union2_equipotent : forall a b, inter2 a b = emptyset -> \nforall a' b', inter2 a' b' = emptyset -> \nare_equipotent a a' -> are_equipotent b b' -> \nare_equipotent (union2 a b) (union2 a' b').\nProof.\nir;uf union2.\napply by_cases with (a = emptyset).\nintros.\nsubst.\nassert (a' = emptyset). ap empty_emptyset;ir.\nnin H1;apply H1 in H3. nin H3;ee;edestruct emptyset_empty;am.\nsubst.\nassert (union2 emptyset b = b).\nap extensionality. uhg;ir. apply union2_or in H3. nin H3.\nedestruct emptyset_empty;am. am.\nuhg;ir;ap union2_r;am. ufi union2 H3. rw H3.\nassert (union2 emptyset b' = b').\nap extensionality. uhg;ir. apply union2_or in H4. nin H4.\nedestruct emptyset_empty;am. am.\nuhg;ir;ap union2_r;am. ufi union2 H4. rw H4. am.\n\nintros Hnea.\napply by_cases with (b=emptyset).\nir. subst. assert (b' = emptyset).\nap empty_emptyset;ir.\nnin H2;apply H2 in H3. nin H3;ee;edestruct emptyset_empty;am.\nsubst.\nassert (union2 a emptyset = a).\nap extensionality. uhg;ir. apply union2_or in H3. nin H3. am.\nedestruct emptyset_empty;am.\nuhg;ir;ap union2_l;am. ufi union2 H3. rw H3.\nassert (union2 a' emptyset = a').\nap extensionality. uhg;ir. apply union2_or in H4. nin H4. am.\nedestruct emptyset_empty;am.\nuhg;ir;ap union2_l;am. ufi union2 H4. rw H4. am.\nintros Hneb.\n\nassert (Hneq : a<>b).\nuhg;ir;subst.\nap Hneb. ap empty_emptyset;ir.\ndestruct emptyset_empty with y. wr H;ap inter2_inc;am.\nassert (Hneq' : a' <> b').\nuhg;ir;subst.\nap Hnea. ap empty_emptyset;ir.\nnin H1. apply (bijective_of_map H1) in H3.\nedestruct emptyset_empty. wr H0. ap inter2_inc;am.\n\n\n\nap equipotent_union_strict.\nir. apply doubleton_or in H3;apply doubleton_or in H4.\nnin H3;nin H4;subst;au.\nrwi H H5. nin H5. edestruct emptyset_empty;am.\nrwi inter2_comm H5. rwi H H5. nin H5. edestruct emptyset_empty;am.\nir. apply doubleton_or in H3;apply doubleton_or in H4.\nnin H3;nin H4;subst;au.\nrwi H0 H5. nin H5. edestruct emptyset_empty;am.\nrwi inter2_comm H5. rwi H0 H5. nin H5. edestruct emptyset_empty;am.\nexists (L (doubleton a b) (fun x => if eq_dec a x then a' else b')).\nee. ap map_of_bijective. uhg;ee;uhg;ir.\nnin (eq_dec a x). ap doubleton_l. ap doubleton_r.\napply doubleton_or in H3;apply doubleton_or in H4;nin H3;nin H4;subst;au.\nrwi eq_dec_if H5. rwi eq_dec_if_not H5. \nnin Hneq';am.\nam. rwi eq_dec_if_not H5;au. rwi eq_dec_if H5. nin Hneq';au.\napply doubleton_or in H3;nin H3;subst.\nexists a;ee. ap doubleton_l. rw eq_dec_if;au.\nexists b;ee. ap doubleton_r. rw eq_dec_if_not;au.\n\nir. rw create_ev;au.\napply doubleton_or in H3;nin H3;subst. rw eq_dec_if;au. rw eq_dec_if_not;au.\nQed.\n\nLemma product_equipotent : forall a b a' b', are_equipotent a a' ->\n are_equipotent b b' -> are_equipotent (product a b) (product a' b').\nProof.\nir. rwi are_equipotent_transformation H;rwi are_equipotent_transformation H0.\nrw are_equipotent_transformation.\nnin H;nin H0.\nexists (fun p => J (x (P p)) (x0 (Q p))).\nuhg;ee;uhg;ir.\napply product_pr in H1;ee;nin H1. clpri H2;clpri H3;clpr.\nap product_pair_inc. ap H. am. ap H0;am.\napply product_pr in H1;apply product_pr in H2;ee;nin H1;nin H2.\nclpri H4;clpri H5;clpri H6;clpri H7;clpri H3.\napply pair_eq in H3;ee. apply H in H1;au. apply H0 in H2;au.\nsubst;au.\napply product_pr in H1;ee;nin H1. clpri H2;clpri H3.\napply H in H2;apply H0 in H3.\nnin H2;nin H3;ee;subst.\neconstructor;ee. ap product_pair_inc;am.\nclpr. tv.\nQed.\n\nLemma product_equipotent_assoc : forall a b c,\n are_equipotent (product a (product b c)) (product (product a b) c).\nProof.\nir.\nuhg. exists (L ((product a (product b c))) (fun p => J (J (P p) (P (Q p))) (Q (Q p)))).\napply are_inverse_bijective with (L (product (product a b) c)\n      (fun p => J (P (P p)) (J (Q (P p)) (Q ( p))))).\nuhg;ee;ir;try (ap map_of_trans;uhg;ir).\napply product_pr in H;ee;nin H. clpri H0;clpri H1.\napply product_pr in H1;ee;nin H. clpri H1;clpri H2.\nclpr. repeat ap product_pair_inc;am.\napply product_pr in H;ee;nin H. clpri H0;clpri H1.\napply product_pr in H0;ee;nin H. clpri H0;clpri H2.\nclpr. repeat ap product_pair_inc;am.\n\nuhg;ee;ir.\nrw create_ev;au.\napply product_pr in H;ee;nin H. clpri H0;clpri H1.\napply product_pr in H1;ee;nin H. clpri H1;clpri H2.\nclpr.\nrw create_ev;au.\nclpr. tv.\nrepeat ap product_pair_inc;am.\nrw create_ev. apply product_pr in H.\nee. apply product_pr in H1;ee.\nnin H. clpri H0;clpri H1. nin H1.\nclpri H2;clpri H3. clpr.\nrepeat ap product_pair_inc;am.\nam.\napply product_pr in H;ee. apply product_pr in H0;ee.\nnin H. clpri H0. nin H0. clpri H2;clpri H1;clpri H3.\nrw create_ev. rw create_ev.\nclpr. tv.\nrepeat ap product_pair_inc;au.\nrw create_ev. clpr. repeat ap product_pair_inc;au.\nrepeat ap product_pair_inc;au.\nQed.\n\nLemma injects_equipotent_Im : forall a f, Application.injects a f -> \nforall x, sub x a -> are_equipotent x (Im f x).\nProof.\nir.\nuh H.\nap trans_equipotent.\nexists f.\nuhg;ee. uhg;ir. ap Im_inc;am.\nuhg;ir. ap H;au.\nuhg;ir.\nIm_nin H1. exists x0;ee;au.\nQed.\n\nEnd Equipotent.\n\nModule Bounded.\n\n(* a property is bounded P iff there is a set x = { y | P y } *)\n\nDefinition property (p : EP) (x : E) :=\n  forall y : E, ((p y -> inc y x) & (inc y x -> p y)). \n\nDefinition axioms (p : EP) := ex (property p).\n\nDefinition create (p : EP) := unique_choose (property p). \n\n\nLemma criterion :\n forall p : EP,\n ex (fun x : E => forall y : E, p y -> inc y x) -> axioms p. \nir. nin H. unfold axioms in |- *.\nProof.\neapply ex_intro with (Z x p). unfold property in |- *.\nir; xd; ir. \nap Z_inc. ap H; au. au.\napply Z_pr in H0. am.\nQed. \n\n\n\nLemma lem1 : forall (p : EP) (y : E), axioms p -> inc y (create p) -> p y.\nProof.\nir. unfold create in H0. unfold axioms in H. \ncp H.\napply unique_choose_pr in H1.\nuh H1;ee.\ndestruct H1 with y;au.\n\nuhg;ir.\nuh H2;uh H3.\nap extensionality_rw;ir.\ndestruct H2 with a.\ndestruct H3 with a.\nap iff_eq;ir;au.\nQed. \n\nLemma lem2 : forall (p : EP) (y : E), axioms p -> p y -> inc y (create p).\nProof.\nir.\nuf create.\nassert (property p (unique_choose (property p))).\nap unique_choose_pr.\nam.\nuhg;ir. ap extensionality_rw;ir.\ndestruct H1 with a;destruct H2 with a.\nap iff_eq;ir;au.\nuh H1.\nap H1. am.\nQed.\n\n\nLemma inc_create :\n forall (p : EP) (y : E), axioms p -> inc y (create p) = p y. \nir. \nap iff_eq; ir. ap lem1; am. \nap lem2; am. \nQed. \n\nLemma trans_criterion :\n forall (p : EP) (f : E1) (x : E),\n (forall y : E, p y -> ex (fun z : E => and (inc z x) (f z = y))) ->\n axioms p.\nProof.\nir. \nap criterion. \nsh (Im f x). \nir. ap Im_show_inc. apply H in H0. nin H0. exists x0;ee;au.\nQed. \n\n(*\nLemma blob : forall a (p : EP), (forall x, p x -> inc x a) ->\n (forall x y, p x -> p y -> x=y) -> \nforall x, p x -> \nunion (Z a p) = x.\nProof.\nir.\nap extensionality;uhg;ir. apply union_ex in H2;nin H2;ee.\napply Z_all in H2;ee.\ncp (H0 x x0 H1 H4). subst. am.\ncp (H x H1).\nap union_inc. econstructor. ee. Focus 2. am. ap Z_inc.\nam. am.\nQed.\n\nLemma blob' : forall a (p : EP), (forall x, p x -> inc x a) ->\n (forall x y, p x -> p y -> x=y) -> \n(ex p) -> union (Z a p) = choose p.\nProof.\nir. ap blob. am. am. ap choose_pr. am.\nQed.\n*)\n\nEnd Bounded.\n\n\nModule Order.\n\nSection Basics.\n\nVariables (a : E) (r : E2P).\nHypothesis oH : is_order r a.\n\nNotation lt := (lt_of r).\n\nVariables x y z : E.\nHypotheses (Hx : inc x a) (Hy : inc y a) (Hz : inc z a).\n\nLemma lt_leq_trans : lt x y -> r y z -> lt x z.\nProof.\nir. uhg;ee. cp oH. uh H1;ee. apply H3 with y;am.\nuhg;ir;subst. uh H;ee.\nap H1. ap oH;au.\nQed.\n\nLemma leq_lt_trans : r x y -> lt y z -> lt x z.\nProof.\nir. uhg;ee.\ncp oH. uh H1;ee. apply H3 with y;am.\nuhg;ir;subst.\nap H0. ap oH;au.\nQed.\n\nLemma leq_refl : r x x.\nProof.\nir. ap oH;am.\nQed.\n\nLemma leq_trans : r x y -> r y z -> r x z.\nProof.\nir;apply oH with y;am.\nQed. \n\nLemma leq_antisym : r x y -> r y x -> x=y.\nProof.\nap oH;am.\nQed.\n\nLemma no_lt_leq : lt x y -> r y x -> False.\nProof.\nir. ap H. ap leq_antisym. am. am.\nQed. \n\nLemma leq_eq_or_lt : r x y -> x = y \\/ lt x y.\nProof.\nir. apply by_cases with (x=y);ir.\nau. right;uhg;ee;am.\nQed.\n\nEnd Basics.\n\nLemma subLt_sub_trans : forall x y, lt_of sub x y -> forall z, sub y z ->\n lt_of sub x z.\nProof.\nir;eapply lt_leq_trans.\nFocus 2. ap union2_l. ap singleton_inc.\nFocus 3. ap union2_r. ap union2_r. ap singleton_inc.\nFocus 3. am.\nFocus 2. ap union2_r. ap union2_l. ap singleton_inc.\nap sub_is_order. am.\nQed.\n\nLemma sub_subLt_trans : forall x y, sub x y -> forall z, lt_of sub y z ->\n lt_of sub x z.\nProof.\nir;uhg;ee. \napply sub_trans with y;am.\nuhg;ir;subst;ap H0;ap extensionality;am.\nQed.\n\nSection Symmetric_order.\n\nVariables (a : E) (r : E2P).\nHypothesis oH : is_order r a.\n\nDefinition symOrder x y := r y x.\n\nLemma symOrder_is_order : is_order symOrder a.\nProof.\ncp oH. clear oH.\nuh H;ee. uf symOrder.\nuhg;ee;uhg;au.\nir. apply H1 with y;au.\nQed.\n\nEnd Symmetric_order.\n\nLemma sym_sym_eq : forall r, symOrder (symOrder r) = r.\nProof.\nir. uf symOrder. ap arrow_extensionality. ir.\nap arrow_extensionality. ir. tv.\nQed.\n\nSection Bounds.\n\nVariable (a : E).\n\nDefinition is_upper_bound (r:E2P) b m := and (inc m a) (forall x, inc x b ->  r x m).\n\nDefinition is_lower_bound (r : E2P) b m := and (inc m a) (forall x, inc x b ->  r m x).\n\nDefinition upper_bounds r b := Z a (is_upper_bound r b).\nDefinition lower_bounds r b := Z a (is_lower_bound r b).\n\nLemma upper_bounds_inc : forall r b m, is_upper_bound r b m -> \ninc m (upper_bounds r b).\nProof.\nir;ap Z_inc;am.\nQed.\n\nLemma lower_bounds_inc : forall r b m, is_lower_bound r b m -> \ninc m (lower_bounds r b).\nProof.\nir;ap Z_inc;am.\nQed.\n\nDefinition is_super r b m := \nand (is_upper_bound r b m)\n(forall x, is_upper_bound r b x -> r m x).\n\nDefinition is_inf r b m :=\nand (is_lower_bound r b m)\n(forall x, is_lower_bound r b x -> r x m).\n\nDefinition is_max r b m :=\nand (is_upper_bound r b m)\n(inc m b).\n\nDefinition is_min r b m :=\nand (is_lower_bound r b m)\n(inc m b).\n\nVariable r:E2P.\n\nHypothesis oH : is_order r a.\n\nLemma super_upper : forall b m, is_super r b m -> is_upper_bound r b m.\nProof.\nir;am.\nQed.\n\nLemma inf_lower : forall b m, is_inf r b m -> is_lower_bound r b m.\nProof.\nir;am.\nQed.\n\nLemma max_upper : forall b m, is_max r b m -> is_upper_bound r b m.\nProof.\nir;am.\nQed.\n\nLemma min_lower : forall b m, is_min r b m -> is_lower_bound r b m.\nProof.\nir;am.\nQed.\n\nLemma super_unicity : forall b m, is_super r b m -> forall n, is_super r b n -> \nm=n.\nProof.\nir. ap oH;au.\nap H. ap super_upper;am.\nap H0. ap super_upper;am.\nQed.\n\nLemma inf_unicity : forall b, unicity (is_inf r b).\nProof.\nuhg.\nir. ap oH;au.\nap H0. ap inf_lower;am.\nap H. ap inf_lower;am.\nQed.\n\nLemma max_super : forall b m, is_max r b m -> is_super r b m.\nProof.\nir. uh H;ee. uhg;ee;au.\nir.\nuh H. ee.\nuh H1;ee. ap H3. am.\nQed.\n\nLemma min_inf : forall b m, is_min r b m -> is_inf r b m.\nProof.\nir. uhg;ee. am.\nir. uh H;uh H0. ee.\nap H1. am.\nQed.\n\nLemma max_unicity : forall b, unicity (is_max r b).\nProof.\nuhg;ir. apply super_unicity with b;au;ap max_super;au.\nQed.\n\nLemma min_unicity : forall b, unicity (is_min r b).\nProof.\nuhg;ir. apply inf_unicity with b;au;ap min_inf;au.\nQed.\n\nDefinition chooseSuper b := unique_choose (is_super r b).\nDefinition chooseInf b := unique_choose (is_inf r b).\n\nLemma lower_symOrder : forall b m, is_lower_bound r b m =\n is_upper_bound (symOrder r) b m.\nProof.\nir. ap iff_eq;uhg;ee;au.\nQed.\n\nLemma inf_symOrder : forall b m, is_inf r b m = is_super (symOrder r) b m.\nProof.\nir. ap iff_eq;uhg;ee;au.\nQed.\n\nLemma min_symOrder : forall b m, is_min r b m = is_max (symOrder r) b m.\nProof.\nuf symOrder. ir.\nap iff_eq;uhg;ee;au.\nQed.\n\nLemma chooseSup_pr : forall b, ex (is_super r b) -> is_super r b (chooseSuper b).\nProof.\nir. uf chooseSuper. ap unique_choose_pr.\nam.\nuhg;ir. eapply super_unicity.\nam. am.\nQed.\n\nLemma chooseInf_pr : forall b, ex (is_inf r b) -> is_inf r b (chooseInf b).\nProof.\nir. uf chooseInf. ap unique_choose_pr.\nam.\nuhg;ir. eapply inf_unicity.\nam. am.\nQed.\n\nLemma chooseSup_max : forall b, ex (is_max r b) -> is_max r b (chooseSuper b).\nProof.\nir.\nnin H.\ncp (max_super H).\ncp (ex_intro (is_super r b) x H0). apply chooseSup_pr in H1.\ncp (super_unicity H0 H1). subst. am.\nQed.\n\nLemma chooseInf_min : forall b, ex (is_min r b) -> is_min r b (chooseInf b).\nProof.\nir.\nnin H.\ncp (min_inf H).\ncp (ex_intro (is_inf r b) x H0). apply chooseInf_pr in H1.\ncp (inf_unicity H0 H1). subst. am.\nQed.\n\nEnd Bounds.\n\nLemma super_min_bounds : forall a r b, is_super a r b =\n is_min a r (upper_bounds a r b).\nProof.\nir;ap arrow_extensionality;intros m.\nap iff_eq;ir.\nuhg;ee. uhg;ee.\nam. ir. apply Z_pr in H0. ap H. am.\nap upper_bounds_inc. am.\nuhg;ee. eapply Z_pr. am.\nir. ap H. ap upper_bounds_inc. am.\nQed.\n\nLemma inf_max_bounds : forall a r b, is_inf a r b =\n is_max a r (lower_bounds a r b).\nProof.\nir;ap arrow_extensionality;intros m.\nap iff_eq;ir.\nuhg;ee. uhg;ee.\nam. ir. apply Z_pr in H0. ap H. am.\nap lower_bounds_inc. am.\nuhg;ee. eapply Z_pr. am.\nir. ap H. ap lower_bounds_inc. am.\nQed.\n\nSection Total.\n\nVariables (a : E) (le : E2P).\nHypothesis toH : is_total_order le a.\n\nNotation lt := (lt_of le).\n\nLemma lt_not_leq : forall x, inc x a -> forall y, inc y a -> \nlt x y = ~ le y x.\nProof.\nir. ap iff_eq;ir.\nuhg;ir.\nap H1. ap toH. am. am. am. am.\nuhg;ee. cp toH.\nuh H2;ee. destruct H3 with x y;au.\ndestruct H1;au.\nuhg;ir;subst. ap H1. ap toH. am.\nQed.\n\nLemma leq_not_lt : forall x, inc x a -> forall y, inc y a -> \nle x y = ~ lt y x.\nProof.\nir. rw lt_not_leq;try am.\nap iff_eq. ir;uhg;ir;au.\nap excluded_middle.\nQed.\n\nEnd Total.\n\nSection Well_order.\n\nDefinition is_well_order r a :=\n and (is_order r a) (forall b, sub b a -> nonempty b -> ex (is_min a r b)).\n\nLemma well_order_total : forall r a, is_well_order r a -> is_total r a.\nProof.\nir. uhg;ir.\nuh H;ee.\ndestruct H2 with (doubleton x y).\nuhg;ir. apply doubleton_or in H3. nin H3;rw H3;am.\nexists x;ap doubleton_l.\nuh H3;ee.\napply doubleton_or in H4. uh H3. ee.\nnin H4;subst.\nleft. ap H5. ap doubleton_r.\nright;ap H5;ap doubleton_l.\nQed.\n\nLemma well_order_total_order : forall r a, is_well_order r a -> is_total_order r a.\nProof.\nir;uhg;ee. am. ap well_order_total. am.\nQed.\n\nLemma wo_ind : \n forall (r : E2P) (a : E) (H : is_well_order r a) (p : EP),\n (forall x : E,\n  inc x a -> (forall y : E, inc y a -> lt_of r y x -> p y) -> p x) ->\n forall x : E, inc x (a) -> p x.\nProof.\nintros r a H p H0.\nap excluded_middle;uhg;ir.\npose (np := Z a (fun x => ~ p x)).\nuh H;ee.\ndestruct H2 with np.\nap Z_sub.\nap excluded_middle;uhg;ir.\nap H1. ir. ap excluded_middle;uhg;ir;ap H3;exists x;ap Z_inc;au.\n\nuh H3;ee.\napply Z_all in H4;ee.\nuh H3;ee.\n\nap H5.\nap H0. am. ir.\nuh H8;ee.\nap excluded_middle;uhg;ir.\nap H9. ap H. am. am. am.\nap H6. ap Z_inc. am.\nam.\nQed.\n\nEnd Well_order.\n\nSection Strict_order.\n\nLemma strict_of_order : forall r a, is_order r a -> is_strict_order (lt_of r) a.\nProof.\nir. uh H;ee;uhg;ee.\nuhg;ir. uhg;ir;uh H3;ee;au.\n\nuhg;ee. ir.\neapply lt_leq_trans. uhg;ee;am. am. ap H3. am. am. am.\nQed.\n\nDefinition leq_of (r:E2P) x y := (r x y) \\/ (x=y).\n\nLemma order_of_strict : forall r a, is_strict_order r a -> is_order (leq_of r) a.\nProof.\nir. uh H;ee;uhg;ee.\nuhg;ir. uhg;au.\nuhg;ir.\nuh H3;uh H4;ee.\nnin H3.\nnin H4.\nap False_rect. eapply H. am.\neapply H0. am. ap H1. am. am. am. au. au.\n\nuhg;ir.\nuh H3;uh H5;nin H3;nin H5;subst.\nuhg. left. apply H0 with y;am.\nleft. am.\nleft. am.\nright;tv.\nQed.\n\nEnd Strict_order.\n\nSection Suborder.\n\nVariable (r : E2P) (a : E).\n\nLemma subreflexiveT : reflexiveT r a -> forall b, sub b a -> reflexiveT r b.\nProof.\nir. uhg;ir. au.\nQed.\n\nLemma subantisym : antisymmetricT r a -> forall b, sub b a -> antisymmetricT r b.\nProof.\nuhg;ir;au.\nQed.\n\nLemma subsymmetricT : symmetricT r a -> forall b, sub b a -> symmetricT r b.\nProof.\nuhg;ir;au.\nQed.\n\nLemma subtransitiveT : transitiveT r a -> forall b, sub b a -> transitiveT r b.\nProof.\nuhg;ir;eauto.\nQed.\n\nLemma subirreflexiveT : irreflexiveT r a -> forall b, sub b a -> irreflexiveT r b.\nProof.\nuhg;ir;au.\nQed.\n\nLemma suborder : is_order r a -> forall b, sub b a -> is_order r b.\nProof.\nuhg;ir;ee;[eapply subreflexiveT | eapply subantisym | eapply subtransitiveT]; am.\nQed.\n\nLemma sub_strict_order : is_strict_order r a -> forall b, sub b a ->\n is_strict_order r b.\nProof.\nuhg;ir;ee;[eapply subirreflexiveT | eapply subtransitiveT];am.\nQed.\n\nLemma sub_total : is_total r a -> forall b, sub b a -> is_total r b.\nProof.\nuhg;ir;au.\nQed.\n\nLemma sub_totalorder : is_total_order r a -> forall b, sub b a ->\n is_total_order r b.\nProof.\nuhg;ir;ee;[eapply suborder | eapply sub_total];am.\nQed.\n\nLemma subequivalence : is_equivalence r a -> forall b, sub b a ->\n is_equivalence r b.\nProof.\nuhg;ir;ee;[eapply subreflexiveT | eapply subsymmetricT | eapply subtransitiveT ] ;am.\nQed.\n\nLemma sub_upper_bound : forall b, sub b a ->\n forall x y, is_upper_bound b r x y -> is_upper_bound a r x y.\nProof.\nir. uhg;ee. ap H;am. ap H0.\nQed.\n\nLemma sub_lower_bound : forall b, sub b a ->\n forall x y, is_lower_bound b r x y -> \nis_lower_bound a r x y.\nProof.\nir;uhg;ee;au. ap H;am.\nQed.\n\nLemma sub_min : forall b, sub b a ->\n forall x, sub x b -> is_min b r x = is_min a r x.\nProof.\nir;repeat (ap arrow_extensionality;ir).\nap iff_eq;ir. uhg;ee. eapply sub_lower_bound. am. am.\nam.\nuhg;ee.\nuhg;ee. ap H0;am. am. am.\nQed.\n\nLemma sub_max : forall b, sub b a ->\n forall x, sub x b -> is_max b r x = is_max a r x.\nProof.\nir;repeat (ap arrow_extensionality;ir).\nap iff_eq;ir. uhg;ee. eapply sub_upper_bound. am. am.\nam.\nuhg;ee.\nuhg;ee. ap H0;am. am. am.\nQed.\n\n(*note : sub_inf doesn't work because eg is_inf [0 ; 1] rLeq  [-6 ; -5] 0\nbut not is_inf R rLeq [-6 ; -5] 0*)\n\nLemma sub_wellorder : is_well_order r a ->\n forall b, sub b a -> is_well_order r b.\nProof.\nuhg;ir;ee. eapply suborder;am.\nir.\nrw (sub_min H0). ap H;try am. eapply sub_trans;am. am.\nQed.\n\nEnd Suborder.\n\nSection Initial.\n\nDefinition is_initial_segment r a b := \nand (sub b a)\n(forall x y, inc x a -> inc y b -> r x y -> inc x b).\n\nDefinition initial_segment_of r a (b:E) := Z a (fun x => lt_of r x b).\n\nLemma initial_of_initial : forall r a, is_order r a -> forall b, inc b a ->\n is_initial_segment r a (initial_segment_of r a b).\nProof.\nir;uhg;ee;ir. ap Z_sub.\napply Z_all in H2;ee;ap Z_inc. am.\nuhg;ee. eapply H. am. ap H2. am. am. am.\nuhg;ir;subst. ap H4. ap H;au. \nQed.\n\nLemma well_order_initial : forall r a, is_well_order r a -> forall b, \nis_initial_segment r a b ->\n (exists b', inc b' a & b = initial_segment_of r a b') \\/ (b=a).\nProof.\nir. apply by_cases with (nonempty (complement a b));ir.\napply H in H1. nin H1. left. exists x. ee. am.\nap extensionality;uhg;ir.\nap Z_inc. ap H0. am. uh H0;ee.\nassert (is_total r a). ap well_order_total. am.\ndestruct H4 with a0 x. ap H0;am. am.\nuhg;ee. am.\nuhg;ir. subst. \nuh H1;ee. apply Z_pr in H6;nin H6;am.\n\nuh H1;ee. apply Z_pr in H6;nin H6.\napply H3 with a0. am. am. am.\n\napply Z_all in H2. ee.\neapply use_complement. am.\nuhg;ir.\ncp H4. apply H1 in H5.\nap H3. ap H;au.\nap Z_sub.\n\nright. ap extensionality;try am;uhg;ir.\nap excluded_middle;uhg;ir;ap H1;exists a0;ap Z_inc;am.\nQed.\n\n\nEnd Initial.\n\nEnd Order.\n\nModule Relation_Morphism.\nImport Order. Import Function.\nImport Map.\n\nSection Definitions.\n\nVariables (r : E2P) (a : E) (r' : E2P) (b : E).\n\nDefinition is_morphism f := and (is_map a b f) \n(forall x, inc x a -> forall y, inc y a -> r x y -> r' (ev f x) (ev f y)).\n\nEnd Definitions.\n\nSection Total_Order_Morphism.\n\nLemma total_injective_leq_back : forall a r, is_total_order r a ->  \n forall a' r', is_order r' a' -> \n forall f, is_morphism r a r' a' f -> \n Application.injects a (ev f) ->\n forall x y, inc x a -> inc y a -> \n r' (ev f x) (ev f y) -> r x y.\nProof.\nir.\n\nrw (leq_not_lt H);au.\nuhg;ir.\nuh H6;ee. uh H1;ee.\ncp (H8 y H4 x H3 H6).\nap H7. ap H2;au.\nap H0;apply trans_of_map in H1;au.\nQed. \n\nLemma total_injective_lt_back : forall a r, is_total_order r a ->  \n forall a' r', is_order r' a' -> \n forall f, is_morphism r a r' a' f -> \n Application.injects a (ev f) ->\n forall x y, inc x a -> inc y a -> \n lt_of r' (ev f x) (ev f y) -> lt_of r x y.\nProof.\nir.\nuhg;ee.\neapply total_injective_leq_back. am. ap H0.\nam. am. am. am. am.\nuhg;ir;ap H5. rw H6;tv.\nQed.\n\nEnd Total_Order_Morphism.\n\nDefinition is_isomorphism (r : E2P) (a : E) (r' : E2P) (b : E) f :=\n and (is_morphism r a r' b f) (bijective a b f).\n\nLemma isomorphism_rw : forall r a r' b f, is_isomorphism r a r' b f =\n and (is_morphism r a r' b f)\n (and (Application.injects a (ev f))\n (Application.covers a b (ev f))).\nProof.\nir;ap iff_eq;ir;ee;au.\nuhg;ee. am. uhg;ee;am.\nQed.\n\nDefinition are_rel_isomorphic r a r' b := ex (is_isomorphism r a r' b).\n\nLemma are_rel_iso_refl : forall r a, are_rel_isomorphic r a r a.\nProof.\nir. exists (id a). uhg;ee. uhg;ee.\nap id_map. ir. rw id_ev. rw id_ev. am. am. am.\nap id_bijective.\nQed.\n\nLemma morphism_compose : forall r a r' a' r'' a'' f g, is_morphism r a r' a' f -> \nis_morphism r' a' r'' a'' g -> is_morphism r a r'' a'' (compose g f).\nProof.\nir. uhg;ee.\napply map_compose with a';am.\nir. uh H;ee;uh H0;ee. cp (trans_of_map H);cp (trans_of_map H0).\nrw compose_ev;au. rw compose_ev;au.\nrw composable_domain. uh H;ee. rw H8;am.\neapply map_composable. am. am.\nrw composable_domain. uh H;ee. rw H8;am.\neapply map_composable. am. am.\nQed.\n\nLemma isomorphism_compose : forall r a r' a' r'' a'' f g, is_isomorphism r a r' a' f -> \nis_isomorphism r' a' r'' a'' g -> is_isomorphism r a r'' a'' (compose g f).\nProof.\nir. uhg;ee. eapply morphism_compose;am.\neapply bijective_compose;am.\nQed.\n\nLemma are_rel_iso_trans : forall r a r' a' r'' a'', are_rel_isomorphic r a r' a' -> \nare_rel_isomorphic r' a' r'' a'' -> are_rel_isomorphic r a r'' a''.\nProof.\nir. nin H;nin H0.\nexists (compose x0 x).\neapply isomorphism_compose;am.\nQed.\n\nLemma isomorphism_inverse : forall r a r' a' f (Ht : is_total_order r a)\n(Ho : is_order r' a'), is_isomorphism r a r' a' f -> \nis_isomorphism r' a' r a (inverse f).\nProof.\nir. uhg;ee.\nuhg;ee. apply bijective_inverse_bijective. am.\nir.\nassert (are_inverse a a' f (inverse f)). ap bijective_inverse_of. am.\nuh H3;ee. uh H5;ee.\neapply (total_injective_leq_back Ht Ho).\nam. am. eapply trans_of_map;try am. eapply trans_of_map;try am.\nrepeat rw H6;am.\nap bijective_inverse_bijective. am.\nQed.\n\nLemma are_rel_iso_sym : forall r a r' a' (Ht : is_total_order r a)\n(Ho : is_order r' a'), are_rel_isomorphic r a r' a' -> \nare_rel_isomorphic r' a' r a.\nProof.\nir. nin H. exists (inverse x). ap isomorphism_inverse;am.\nQed.\n\nLemma isomorphism_of_trans : forall (r:E2P) a (r':E2P) a' f,\n Application.bijective a a' f -> \n(forall x y, inc x a -> inc y a -> r x y -> r' (f x) (f y)) ->\n is_isomorphism r a r' a' (create a f).\nProof.\nir. uhg;ee.\nuhg;ee. ap map_of_trans;am.\nir. rw create_ev;au. rw create_ev;au.\nap map_of_bijective. am.\nQed.\n\nEnd Relation_Morphism. Export Relation_Morphism.\n\n", "meta": {"author": "SkySkimmer", "repo": "ZF", "sha": "bcaefe0eff18d8b077da43c7fd383c915b5d70e6", "save_path": "github-repos/coq/SkySkimmer-ZF", "path": "github-repos/coq/SkySkimmer-ZF/ZF-bcaefe0eff18d8b077da43c7fd383c915b5d70e6/functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6749491992108357}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_inequalitysymmetric.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_localextension.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_doublereverse.\n\nSection Euclid.\nContext `{Ax:euclidean_neutral_ruler_compass}.\nLemma lemma_differenceofparts : \n   forall A B C a b c, \n   Cong A B a b -> Cong A C a c -> BetS A B C -> BetS a b c ->\n   Cong B C b c.\nProof.\nintros.\nassert (Cong B C b c).\nby cases on (eq B A \\/ neq B A).\n{\n assert (Cong A A a b) by (conclude cn_equalitysub).\n assert (Cong a b A A) by (conclude lemma_congruencesymmetric).\n assert (~ neq a b).\n  {\n  intro.\n  assert (neq A A) by (conclude axiom_nocollapse).\n  assert (eq A A) by (conclude cn_equalityreflexive).\n  contradict.\n  }\n assert (Cong A C A C) by (conclude cn_congruencereflexive).\n assert (Cong B C A C) by (conclude cn_equalitysub).\n assert (Cong B C a c) by (conclude lemma_congruencetransitive).\n assert (Cong b c b c) by (conclude cn_congruencereflexive).\n assert (Cong b c a c) by (conclude cn_equalitysub).\n assert (Cong a c b c) by (conclude lemma_congruencesymmetric).\n assert (Cong B C b c) by (conclude lemma_congruencetransitive).\n close.\n }\n{\n assert (~ eq C A).\n  {\n  intro.\n  assert (BetS A B A) by (conclude cn_equalitysub).\n  assert (~ BetS A B A) by (conclude axiom_betweennessidentity).\n  contradict.\n  }\n assert (neq A C) by (conclude lemma_inequalitysymmetric).\n let Tf:=fresh in\n assert (Tf:exists E, (BetS C A E /\\ Cong A E A C)) by (conclude lemma_localextension);destruct Tf as [E];spliter.\n assert (neq A C) by (conclude lemma_inequalitysymmetric).\n assert (neq a c) by (conclude axiom_nocollapse).\n assert (neq c a) by (conclude lemma_inequalitysymmetric).\n let Tf:=fresh in\n assert (Tf:exists e, (BetS c a e /\\ Cong a e a c)) by (conclude lemma_localextension);destruct Tf as [e];spliter.\n assert (Cong E A A E) by (conclude cn_equalityreverse).\n assert (Cong E A A C) by (conclude lemma_congruencetransitive).\n assert (Cong E A a c) by (conclude lemma_congruencetransitive).\n assert (Cong e a a e) by (conclude cn_equalityreverse).\n assert (Cong e a a c) by (conclude lemma_congruencetransitive).\n assert (Cong a c e a) by (conclude lemma_congruencesymmetric).\n assert (Cong E A a c) by (conclude lemma_congruencetransitive).\n assert (Cong E A e a) by (conclude lemma_congruencetransitive).\n assert (BetS E A C) by (conclude axiom_betweennesssymmetry).\n assert (BetS e a c) by (conclude axiom_betweennesssymmetry).\n assert (Cong E C e c) by (conclude cn_sumofparts).\n assert (BetS E A B) by (conclude axiom_innertransitivity).\n assert (BetS e a b) by (conclude axiom_innertransitivity).\n assert (Cong C B c b) by (conclude axiom_5_line).\n assert (Cong b c B C) by (forward_using lemma_doublereverse).\n assert (Cong B C b c) by (conclude lemma_congruencesymmetric).\n close.\n }\n(* cases *)\nclose.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_differenceofparts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.6748686503888195}}
{"text": "(********************************************************************)\n(*                                                                  *)\n(*  The Why3 Verification Platform   /   The Why3 Development Team  *)\n(*  Copyright 2010-2019   --   Inria - CNRS - Paris-Sud University  *)\n(*                                                                  *)\n(*  This software is distributed under the terms of the GNU Lesser  *)\n(*  General Public License version 2.1, with the special exception  *)\n(*  on linking described in file LICENSE.                           *)\n(*                                                                  *)\n(********************************************************************)\n\n(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire Reals.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 :\n  forall (x:Reals.Rdefinitions.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 :\n  forall (x:Reals.Rdefinitions.R) (y:Reals.Rdefinitions.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 :\n  forall (x:Reals.Rdefinitions.R), (0%R <= (Reals.Rbasic_fun.Rabs x))%R.\nexact Rabs_pos.\nQed.\n\n(* Why3 goal *)\nLemma Abs_sum :\n  forall (x:Reals.Rdefinitions.R) (y:Reals.Rdefinitions.R),\n  ((Reals.Rbasic_fun.Rabs (x + y)%R) <=\n   ((Reals.Rbasic_fun.Rabs x) + (Reals.Rbasic_fun.Rabs y))%R)%R.\nexact Rabs_triang.\nQed.\n\n(* Why3 goal *)\nLemma Abs_prod :\n  forall (x:Reals.Rdefinitions.R) (y:Reals.Rdefinitions.R),\n  ((Reals.Rbasic_fun.Rabs (x * y)%R) =\n   ((Reals.Rbasic_fun.Rabs x) * (Reals.Rbasic_fun.Rabs y))%R).\nexact Rabs_mult.\nQed.\n\n(* Why3 goal *)\nLemma triangular_inequality :\n  forall (x:Reals.Rdefinitions.R) (y:Reals.Rdefinitions.R)\n    (z:Reals.Rdefinitions.R),\n  ((Reals.Rbasic_fun.Rabs (x - z)%R) <=\n   ((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": "schrodibear", "repo": "why3", "sha": "9f8eb767380987a28e43b81729ae1d682363bb49", "save_path": "github-repos/coq/schrodibear-why3", "path": "github-repos/coq/schrodibear-why3/why3-9f8eb767380987a28e43b81729ae1d682363bb49/lib/coq/real/Abs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6748527510006442}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) : natural := plus Zero lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_90_mult_zero/goal33conj32_coqofml_S2AQTV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6748527391044088}}
{"text": "Require Import init.\n\nRequire Import rat.\nRequire Import set.\n\nDeclare Scope real_scope.\nDelimit Scope real_scope with real.\n\nDefinition dedekind_cut (a : rat → Prop) :=\n    a ≠ all ∧\n    a ≠ empty ∧\n    (∀ l u, a u → l < u → a l) ∧\n    (∀ l, a l → ∃ u, a u ∧ l < u).\n\nTheorem dedekind_le : ∀ a, dedekind_cut a → ∀ l u, a u → l ≤ u → a l.\nProof.\n    intros a a_cut l u au lu.\n    classic_case (l = u).\n    -   subst.\n        exact au.\n    -   apply (land (rand (rand a_cut)) _ _ au).\n        split; assumption.\nQed.\n\nTheorem dedekind_lt : ∀ a, dedekind_cut a → ∀ l u, a l → ¬a u → l < u.\nProof.\n    intros a a_cut l u al nau.\n    classic_case (l = u) as [eq|neq]; try (subst; contradiction).\n    classic_contradiction leq.\n    rewrite nlt_le in leq.\n    rewrite neq_sym in neq.\n    apply nau.\n    apply (land (rand (rand a_cut)) u l); try split; assumption.\nQed.\n\nNotation \"'real'\" := (set_type dedekind_cut).\n\nDefinition rat_to_real_base (a b : rat) := b < a.\nLemma rat_to_real_cut : ∀ a, dedekind_cut (rat_to_real_base a).\nProof.\n    intros a.\n    unfold rat_to_real_base.\n    split.\n    2: split.\n    3: split.\n    -   intros eq.\n        assert (all a) as contr by exact true.\n        rewrite <- eq in contr.\n        destruct contr; contradiction.\n    -   apply empty_neq.\n        exists (a + -(1)).\n        rewrite <- (plus_rid a) at 2.\n        apply lt_lplus.\n        apply pos_neg2.\n        exact one_pos.\n    -   intros l u ltq1 ltq2.\n        exact (trans ltq2 ltq1).\n    -   intros l ltq.\n        exists ((l + a) * div 2).\n        split.\n        +   apply lt_mult_rcancel_pos with 2; try exact two_pos.\n            rewrite mult_rlinv by apply two_pos.\n            rewrite ldist.\n            rewrite mult_rid.\n            apply lt_rplus.\n            exact ltq.\n        +   apply lt_mult_rcancel_pos with 2; try exact two_pos.\n            rewrite mult_rlinv by apply two_pos.\n            rewrite ldist.\n            rewrite mult_rid.\n            apply lt_lplus.\n            exact ltq.\nQed.\n\nDefinition rat_to_real a := [_|rat_to_real_cut a].\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/Dedekind/dedekind_real_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6748527391044087}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*             Ralph Matthes [+]                              *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*                             [+] Affiliation IRIT -- CNRS   *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Omega.\n\nRequire Import wf_utils.\n\nSet Implicit Arguments.\n\nSection lazy_list.\n\n  (* Implementation of lazy lists as the subset of co-lists \n     characterized by a finiteness predicate *)\n\n  Variable X : Type.\n\n  CoInductive llist : Type :=\n    | lnil : llist\n    | lcons : X -> llist -> llist.\n\n  Implicit Types (a: X) (s: llist) (l: list X).\n\n  Unset Elimination Schemes.\n    \n  Inductive lfin : llist-> Prop :=\n    | lfin_nil :  lfin lnil\n    | lfin_cons : forall a ll, lfin ll -> lfin (lcons a ll).\n\n  Arguments lfin_cons : clear implicits.\n\n  Set Elimination Schemes.\n\n  Section small_inversions.\n\n    Let shape_inv s := match s with lnil => False | _         => True   end.\n    Let pred_inv s  := match s with lnil => lnil  | lcons x s => s      end.\n    \n    Definition lfin_inv x s (H : lfin (lcons x s)) : lfin s :=\n      match H in lfin s return shape_inv s -> lfin (pred_inv s) with\n        | lfin_nil         => fun E => match E with end\n        | lfin_cons _ _ H1 => fun _ => H1\n      end I.\n\n    Let output_invert s : lfin s -> Prop := \n      match s as s' return lfin s' -> _ with\n        | lnil      => fun H => lfin_nil = H\n        | lcons x s => fun H => exists H', lfin_cons x s H' = H\n      end.\n\n    Definition lfin_invert s H : @output_invert s H :=\n      match H in lfin s return @output_invert s H with\n        | lfin_nil         => eq_refl\n        | lfin_cons _ _ H' => ex_intro _ H' eq_refl \n      end.\n\n  End small_inversions.\n\n  (** We show proof irrelevance for lfin by induction/inversion\n      where inversion is obtained by dependent pattern matching \n\n      Interesting case because lfin is not a decidable predicate\n      but nevertheless has provable PIRR \n    *)\n\n  Fixpoint lfin_pirr s (H1 : lfin s) : forall H2, H1 = H2.\n  Proof.\n    destruct H1 as [ | x s H1 ]; intros H2.\n    + apply (lfin_invert H2).\n    + destruct (lfin_invert H2) as (H & E).\n      subst; f_equal; apply lfin_pirr.\n  Defined.\n\n  Section lfin_rect.\n\n    (** We show dependent recursion principle for lfin implementing\n        what a command like\n\n        Scheme lfin_rect := Induction for lfin Sort Type.\n\n        But Scheme is not smart enough to invent PIRR ...\n        Remark that we use singleton elimination here ... *)\n\n    Variable P : forall s, lfin s -> Type.\n\n    Hypothesis HP1 : @P _ lfin_nil.\n    Hypothesis HP2 : forall x s H, @P s H -> P (@lfin_cons x s H).\n\n    Ltac pirr := match goal with |- @P _ ?a -> @P _ ?b => rewrite (@lfin_pirr _ a b); trivial end.\n\n    Fixpoint lfin_rect s H { struct H } : @P s H.\n    Proof.\n      revert H.\n      refine (match s with\n        | lnil      => fun H => _\n        | lcons x s => fun H => _\n      end).\n      + generalize HP1; pirr.\n      + generalize (@HP2 x s (lfin_inv H) (@lfin_rect s (lfin_inv H))); pirr.\n    Defined.\n\n  End lfin_rect.\n\n  (* Now we define lazy lists *)\n\n  Definition lazy_list := { s | lfin s }.\n\n  Implicit Type ll : lazy_list.\n\n  (* Constructors *)\n\n  Definition lazy_nil : lazy_list := exist _ _ lfin_nil.\n  Definition lazy_cons a : lazy_list -> lazy_list.\n  Proof.\n    intros (ll & H).\n    exists (lcons a ll).\n    apply lfin_cons, H.\n  Defined.\n\n  (* Injectivity of constructors *)\n\n  Fact lazy_cons_inj a b ll1 ll2 : lazy_cons a ll1 = lazy_cons b ll2 -> a = b /\\ ll1 = ll2.\n  Proof.\n    revert ll1 ll2; intros (s1 & H1) (s2 & H2); simpl.\n    intros E; apply f_equal with (f := @proj1_sig _ _) in E; simpl in E.\n    inversion E; subst; split; auto; f_equal.\n    apply lfin_pirr.\n  Qed.\n\n  Fact lazy_nil_cons_discr a ll : lazy_nil <> lazy_cons a ll.\n  Proof. destruct ll; discriminate. Qed.\n\n  (** And a dependent recursion principle similar to list_rect *)\n\n  Section lazy_list_rect.\n\n    Variable P : lazy_list -> Type.\n    \n    Hypothesis (HP0 : P lazy_nil).\n    Hypothesis (HP1 : forall a m, P m -> P (lazy_cons a m)).\n\n    Theorem lazy_list_rect : forall ll, P ll.\n    Proof. \n      intros (? & H). \n      induction H as [ | x s H IH ].\n      + apply HP0.\n      + apply HP1 with (1 := IH).\n    Defined.\n\n  End lazy_list_rect.\n\n  (* We have everything to define an isomorphism between list and lazy_list *)\n\n  Section list_lazy_iso.\n\n    Fixpoint list2lazy l :=\n      match l with\n        | nil  => lazy_nil\n        | x::l => lazy_cons x (list2lazy l)\n      end.\n\n    Fact list2lazy_inj l m : list2lazy l = list2lazy m -> l = m.\n    Proof.\n      revert m; induction l as [ | a l IH ]; intros [ | b m ]; simpl; auto.\n      + intros H; exfalso; revert H; apply lazy_nil_cons_discr.\n      + intros H; exfalso; symmetry in H; revert H; apply lazy_nil_cons_discr.\n      + intros H; apply lazy_cons_inj in H; destruct H; f_equal; auto.\n    Qed.\n\n    Section lazy2list.\n\n      Let lazy2list_rec ll : { l | ll = list2lazy l }.\n      Proof.\n        induction ll as [ | a ll (l & Hl) ] using lazy_list_rect.\n        + exists nil; auto.\n        + exists (a::l); simpl; f_equal; auto.\n      Qed.\n\n      Definition lazy2list ll := proj1_sig (lazy2list_rec ll).\n\n      Fact list2lazy2list ll : ll = list2lazy (lazy2list ll).\n      Proof. apply (proj2_sig (lazy2list_rec ll)). Qed.\n\n    End lazy2list.\n\n    Fact lazy2list2lazy l : l = lazy2list (list2lazy l).\n    Proof. apply list2lazy_inj; rewrite <- list2lazy2list; trivial. Qed.\n\n    (* Fixpoint equations *)\n\n    Fact lazy2list_nil : lazy2list lazy_nil = nil.\n    Proof. apply list2lazy_inj; rewrite <- list2lazy2list; auto. Qed.\n\n    Fact lazy2list_cons a ll : lazy2list (lazy_cons a ll) = a :: lazy2list ll.\n    Proof.\n      apply list2lazy_inj.\n      simpl; repeat rewrite <- list2lazy2list; trivial.\n    Qed.\n\n  End list_lazy_iso.\n\n  Definition lazy_length ll := length (lazy2list ll).\n  \n  Fact lazy_length_nil : lazy_length lazy_nil = 0.\n  Proof. unfold lazy_length; rewrite lazy2list_nil; auto. Qed.\n\n  Fact lazy_length_cons x ll : lazy_length (lazy_cons x ll) = S (lazy_length ll).\n  Proof. unfold lazy_length; rewrite lazy2list_cons; auto. Qed.\n\nEnd lazy_list.\n\nArguments lazy_nil {X}.\n\nSection Rotate.\n\n  (** From \"Simple and Efficient Purely Functional Queues and Deques\" by Chris Okasaki \n      See application in file fifo_3llists.v *)\n\n  Variable (X : Type).\n  \n  Implicit Type (l r m a : lazy_list X).\n  \n  Let prec l r := lazy_length r = 1 + lazy_length l.\n  Let spec l r a m := lazy2list m = lazy2list l ++ rev (lazy2list r) ++ lazy2list a.\n\n  Definition lazy_rotate l r : forall a, prec l r -> sig (spec l r a).\n  Proof.\n    induction on l r as loop with measure (lazy_length l); intros a.\n    induction r as [ | y r' _ ] using lazy_list_rect; intros H.\n    + exfalso; red in H; revert H; rewrite lazy_length_nil; intros; omega.\n    + revert H.\n      induction l as [ | x l' _ ] using lazy_list_rect; intros H.\n      * exists (lazy_cons y a); red in H |- *.\n        assert (r' = lazy_nil); [ | subst ].\n        { revert H.\n          induction r' as [ | ? r' ] using lazy_list_rect; auto.\n          do 2 rewrite lazy_length_cons.\n          rewrite lazy_length_nil; simpl; intros; omega. }\n        do 2 rewrite lazy2list_cons, lazy2list_nil; auto.\n      * refine (let (m,Hm) := loop l' r' _ (lazy_cons y a) _ in exist _ (lazy_cons x m) _).\n        - rewrite lazy_length_cons; omega.\n        - red in H |- *; do 2 rewrite lazy_length_cons in H; omega.\n        - red in H, Hm |- *.\n          repeat rewrite lazy2list_cons.\n          rewrite Hm, lazy2list_cons; simpl.\n          rewrite app_ass; auto.\n  Defined.\n\nEnd Rotate.\n\nArguments lazy_rotate {X}.\n\nExtraction Inline lfin_rect lazy_nil lazy_cons lazy_list_rect.\n\n \n", "meta": {"author": "DmxLarchey", "repo": "BFE", "sha": "0bf8376a80ca4378be1630689f6561744d43474e", "save_path": "github-repos/coq/DmxLarchey-BFE", "path": "github-repos/coq/DmxLarchey-BFE/BFE-0bf8376a80ca4378be1630689f6561744d43474e/coq/llist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.674850056308828}}
{"text": "Require Export Omega.\nSet Implicit Arguments.\n\nLocal Close Scope nat.\nLocal Open Scope Z.\n\n\nLemma Z_mul_neg1_r a:\n      a * -1 = - a.\nProof.\n omega.\nQed.\n\nLemma Z_add_neg_r a b:\n      a + -b = a - b.\nProof.\n omega.\nQed.\n\n\nLtac Z_simp_all\n := simpl in *;\n    repeat rewrite Z.add_0_r in *;\n    repeat rewrite Z.mul_1_r in *;\n    repeat rewrite Z_mul_neg1_r in *;\n    repeat rewrite Z_add_neg_r in *.\n\n\n", "meta": {"author": "amosr", "repo": "clustering-proof", "sha": "3667ac1e3a14b03333fba15062999825933f03bf", "save_path": "github-repos/coq/amosr-clustering-proof", "path": "github-repos/coq/amosr-clustering-proof/clustering-proof-3667ac1e3a14b03333fba15062999825933f03bf/Clustering/Tactics/Z.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6748500510963139}}
{"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: Qfield.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\nRequire Export Field.\nRequire Export QArith_base.\nRequire Import NArithRing.\n\n(** * field and ring tactics for rational numbers *)\n\nDefinition Qsrt : ring_theory 0 1 Qplus Qmult Qminus Qopp Qeq.\nProof.\n  constructor.\n  exact Qplus_0_l.\n  exact Qplus_comm.\n  exact Qplus_assoc.\n  exact Qmult_1_l.\n  exact Qmult_comm.\n  exact Qmult_assoc.\n  exact Qmult_plus_distr_l.\n  reflexivity.\n  exact Qplus_opp_r.\nQed.\n\nDefinition Qsft : field_theory 0 1 Qplus Qmult Qminus Qopp Qdiv Qinv Qeq.\nProof.\n  constructor.\n  exact Qsrt.\n  discriminate.\n  reflexivity.\n  intros p Hp.\n  rewrite Qmult_comm.\n  apply Qmult_inv_r.\n  exact Hp.\nQed.\n\nLemma Qpower_theory : power_theory 1 Qmult Qeq Z_of_N Qpower.\nProof.\nconstructor.\nintros r [|n];\nreflexivity.\nQed.\n\nLtac isQcst t :=\n  match t with\n  | inject_Z ?z => isZcst z\n  | Qmake ?n ?d =>\n    match isZcst n with\n      true => isPcst d\n    | _ => false\n    end\n  | _ => false\n  end.\n\nLtac Qcst t :=\n  match isQcst t with\n    true => t\n    | _ => NotConstant\n  end.\n\nLtac Qpow_tac t :=\n  match t with\n  | Z0 => N0\n  | Zpos ?n => Ncst (Npos n)\n  | Z_of_N ?n => Ncst n\n  | NtoZ ?n => Ncst n\n  | _ => NotConstant\n  end.\n\nAdd Field Qfield : Qsft\n (decidable Qeq_bool_eq,\n  completeness Qeq_eq_bool,\n  constants [Qcst],\n  power_tac Qpower_theory [Qpow_tac]).\n\n(** Exemple of use: *)\n\nSection Examples.\n\nLet ex1 : forall x y z : Q, (x+y)*z ==  (x*z)+(y*z).\n  intros.\n  ring.\nQed.\n\nLet ex2 : forall x y : Q, x+y == y+x.\n  intros.\n  ring.\nQed.\n\nLet ex3 : forall x y z : Q, (x+y)+z == x+(y+z).\n  intros.\n  ring.\nQed.\n\nLet ex4 : (inject_Z 1)+(inject_Z 1)==(inject_Z 2).\n  ring.\nQed.\n\nLet ex5 : 1+1 == 2#1.\n  ring.\nQed.\n\nLet ex6 : (1#1)+(1#1) == 2#1.\n  ring.\nQed.\n\nLet ex7 : forall x : Q, x-x== 0.\n  intro.\n  ring.\nQed.\n\nLet ex8 : forall x : Q, x^1 == x.\n  intro.\n  ring.\nQed.\n\nLet ex9 : forall x : Q, x^0 == 1.\n  intro.\n  ring.\nQed.\n\nLet ex10 : forall x y : Q, ~(y==0) -> (x/y)*y == x.\nintros.\nfield.\nauto.\nQed.\n\nEnd Examples.\n\nLemma Qopp_plus : forall a b,  -(a+b) == -a + -b.\nProof.\n  intros; ring.\nQed.\n\nLemma Qopp_opp : forall q, - -q==q.\nProof.\n  intros; ring.\nQed.\n", "meta": {"author": "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/QArith/Qfield.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199754937771, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.6748136202548772}}
{"text": "\n\n(** * Permutation over lists, and finite multisets. *)\n\nSet Implicit Arguments. \n\nFrom Coq Require Import List Relations Multiset Arith Setoid.\nFrom CoLoR Require Import decidable_set more_list equiv_list.\nFrom CoLoR Require list_permut.\n\n Definition permut (n : nat) (f : nat -> nat) :=\n  (forall i, n <= i -> f i = i) /\\\n  (forall i, i < n -> f i < n) /\\\n  (forall i j, i < n -> j < n -> f i = f j -> i = j).\n\nLemma adequacy :\n  forall (A : Type) (R : relation A) (l1 l2 : list A),\n  list_permut.permut0 R l1 l2 <-> \n  (length l1 = length l2 /\\ \n   exists pi, (permut (length l1) pi) /\\\n   forall i, i < length l1 ->\n   match (nth_error l1 i), (nth_error l2 (pi i)) with\n   | (Some ai), (Some bi) => R ai bi\n   | _, _ => False\n   end).\nProof.\nintros A R l1; pattern l1; apply list_rec2; clear l1.\nintro n; induction n as [ | n]; intros l1 L1 l2; split.\nintros P; inversion P; subst.\nsplit; trivial.\nexists (fun (i : nat) => i); repeat split; trivial.\nintros i L; simpl in L; inversion L.\nsimpl in L1; inversion L1.\nintros [L _]; destruct l1 as [ | a1 l1].\ndestruct l2 as [ | a2 l2].\napply list_permut.Pnil.\nsimpl in L; discriminate.\nsimpl in L1; inversion L1.\nintros P; inversion P as [ | a1 b1 l1' l2' l2'' a1_R_b1 Q ]; subst; split; trivial.\nexists (fun (i : nat) => i); repeat split; trivial.\nintros i L; simpl in L; inversion L.\nrewrite (list_permut.permut_length P); trivial.\nsimpl in L1; generalize (le_S_n _ _ L1); clear L1; intro L1.\nrewrite (IHn l1' L1 (l2' ++ l2'')) in Q.\ndestruct Q as [ L [pi [ Q H]]].\nexists (fun (i : nat) =>\n             match i with\n             | 0 => length l2'\n             | S i => \n                 if le_lt_dec (length l2') (pi i)\n                 then S (pi i)\n                 else pi i\n             end); split.\nunfold permut in *; repeat split.\nintros [ | i] L'; simpl in L'.\ninversion L'.\ngeneralize (le_S_n _ _ L'); clear L'; intro L'.\ndestruct Q as [Q _].\nrewrite (Q i L').\ndestruct (le_lt_dec (length l2') i) as [ll2'_le_i | ll2'_gt_i]; trivial.\nrewrite L in L'.\nabsurd (length l2' < length l2'); auto with arith.\napply le_lt_trans with i; trivial.\napply le_trans with (length (l2' ++ l2'')); trivial.\nrewrite length_app; auto with arith.\nintros [ | i] L'.\nsimpl; rewrite L; unfold lt; apply le_n_S; rewrite length_app; auto with arith.\nsimpl in L'; generalize (le_S_n _ _ L'); clear L'; intro L'.\ndestruct Q as [_ [Q _]].\ndestruct (le_lt_dec (length l2') (pi i)) as [ll2'_le_pii | ll2'_gt_pii].\nsimpl; unfold lt; apply le_n_S; apply Q; trivial.\nsimpl; apply lt_le_trans with (length l1').\napply Q; trivial.\nauto with arith.\ndestruct Q as [_ [_ Q]].\nintros [ | i] [ | j] L' L'' H'; trivial.\ndestruct  (le_lt_dec (length l2') (pi j)) as [ll2'_cmp_pij | ll2'_cmp_pij];\nrewrite H' in ll2'_cmp_pij;\nabsurd (S (pi j) <= pi j); trivial; auto with arith. \ndestruct  (le_lt_dec (length l2') (pi i)) as [ll2'_cmp_pii | ll2'_cmp_pii];\nrewrite <- H' in ll2'_cmp_pii;\nabsurd (S (pi i) <= pi i); trivial; auto with arith. \ndestruct  (le_lt_dec (length l2') (pi i)) as [ll2'_le_pii | ll2'_gt_pii];\ndestruct  (le_lt_dec (length l2') (pi j)) as [ll2'_le_pij | ll2'_gt_pij].\napply (f_equal (fun n => S n)); apply Q.\nsimpl in L'; apply lt_S_n; trivial.\nsimpl in L''; apply lt_S_n; trivial.\ninjection H'; trivial.\nabsurd (length l2' < length l2'); auto with arith.\napply le_lt_trans with (pi j); trivial.\nrewrite <- H'; auto with arith.\nabsurd (length l2' < length l2'); auto with arith.\napply le_lt_trans with (pi i); trivial.\nrewrite H'; auto with arith.\napply (f_equal (fun n => S n)); apply Q; trivial.\nsimpl in L'; apply lt_S_n; trivial.\nsimpl in L''; apply lt_S_n; trivial.\nintros [ | i] L'.\nsimpl; rewrite nth_error_at_pos; trivial.\nsimpl in L'; generalize (le_S_n _ _ L'); clear L'; intro L'.\nsimpl; rewrite (nth_error_remove b1 l2' l2'' (pi i)); apply H; trivial.\n\nintros [L [pi [P H]]].\ndestruct l1 as [ | a1 l1].\ndestruct l2 as [ | a2 l2].\napply list_permut.Pnil.\nsimpl in L; discriminate.\nassert (L' : 0 < length (a1 :: l1)).\nsimpl; auto with arith.\ngeneralize (H 0 L'); simpl.\nassert (H' := nth_error_ok_in (pi 0) l2).\ndestruct (nth_error l2 (pi 0)) as [ b1 | ].\nintro a1_R_b1; destruct (H' _ (eq_refl _)) as [l2' [l2'' [L'' H'']]]; clear H'.\nsubst l2; apply list_permut.Pcons; trivial.\nrewrite IHn; [split | simpl in L1; apply le_S_n; trivial].\nrewrite length_app in L; rewrite plus_comm in L; simpl in L; injection L; \nintro L'''; rewrite L'''; rewrite plus_comm; rewrite length_app; trivial.\nexists (fun i => \n               if le_lt_dec (length l1) i\n               then i\n               else\n                 if le_lt_dec (pi (S i)) (pi 0)  \n                 then pi (S i) \n                 else (pi (S i)) -1); split.\nunfold permut in *; repeat split.\n\nintros i L'''; \ndestruct (le_lt_dec (length l1) i) as [ll1_le_i | ll1_gt_i]; trivial.\nabsurd (i < i); auto with arith.\napply lt_le_trans with (length l1); trivial.\n\nintros i L'''; \ndestruct (le_lt_dec (length l1) i) as [ll1_le_i | _]; trivial.\nassert (L'''' : S i < length (a1 :: l1)).\nsimpl; auto with arith.\ndestruct (le_lt_dec (pi (S i)) (pi 0)) as [piSi_le_pi0 | piSi_gt_pi0].\nassert (piSi_lt_pi0 : pi (S i) < pi 0).\ndestruct (le_lt_or_eq _ _ piSi_le_pi0) as [L5 | E]; trivial.\ndestruct P as [_ [_ P]]. \nabsurd (S i = 0).\ndiscriminate.\napply (P (S i) 0); trivial.\napply lt_le_trans with (pi 0); trivial.\ndestruct P as [_ [P _]].\ngeneralize (P 0 (lt_O_Sn _)); simpl; auto with arith.\ndestruct P as [_ [P _]].\ngeneralize (P (S i) L''''); destruct (pi (S i)) as [ | p]; simpl.\nintros _; apply le_lt_trans with i; auto with arith.\nrewrite <- minus_n_O; auto with arith.\n\nintros i j Li Lj;\ndestruct (le_lt_dec (length l1) i) as [ll1_le_i | _];\ndestruct (le_lt_dec (length l1) j) as [ll1_le_j | _];\ntrivial.\nabsurd (i < i); auto with arith.\napply lt_le_trans with (length l1); trivial.\nabsurd (j < j); auto with arith.\napply lt_le_trans with (length l1); trivial.\ndestruct P as [_ [_ P]];\ndestruct (le_lt_dec (pi (S i)) (pi 0)) as [piSi_le_pi0 | piSi_gt_pi0];\ndestruct (le_lt_dec (pi (S j)) (pi 0)) as [piSj_le_pi0 | piSj_gt_pi0].\nintro piSi_eq_piSj; assert (Si_eq_Sj : S i = S j).\napply (P (S i) (S j)); simpl; auto with arith.\ninjection Si_eq_Sj; trivial.\ndestruct (le_lt_or_eq _ _ piSi_le_pi0) as [L5 | E]; clear piSi_le_pi0.\ndestruct (pi (S j)) as [ | pj].\nabsurd (pi 0 < 0); auto with arith.\nsimpl; rewrite <- minus_n_O.\nintro H'; rewrite H' in L5.\nabsurd (S pj < S pj); auto with arith.\napply le_lt_trans with (pi 0); auto with arith.\nabsurd (S i = 0).\ndiscriminate.\napply (P (S i) 0); trivial.\nsimpl; auto with arith.\ndestruct (le_lt_or_eq _ _ piSj_le_pi0) as [L5 | E]; clear piSj_le_pi0.\ndestruct (pi (S i)) as [ | qi].\nabsurd (pi 0 < 0); auto with arith.\nsimpl; rewrite <- minus_n_O.\nintro H'; rewrite <- H' in L5.\nabsurd (S qi < S qi); auto with arith.\napply le_lt_trans with (pi 0); auto with arith.\nabsurd (S j = 0).\ndiscriminate.\napply (P (S j) 0); trivial.\nsimpl; auto with arith.\nintro piSi_eq_piSj; assert (Si_eq_Sj : S i = S j).\napply (P (S i) (S j)); simpl; auto with arith.\ndestruct (pi (S i)) as [ | qi].\nabsurd (pi 0 < 0); auto with arith.\ndestruct (pi (S j)) as [ | pj].\nabsurd (pi 0 < 0); auto with arith.\nsimpl in piSi_eq_piSj; do 2 rewrite <- minus_n_O in piSi_eq_piSj; subst; trivial.\ninjection Si_eq_Sj; trivial.\n\nintros i Li; \ndestruct (le_lt_dec (length l1) i) as [ll1_lt_i | _].\nabsurd (i < i); auto with arith.\napply lt_le_trans with (length l1); trivial.\ngeneralize (H (S i) (lt_n_S _ _ Li)); simpl.\ndestruct (nth_error l1 i) as [ai | ]; trivial.\ngeneralize (nth_error_ok_in (pi (S i)) (l2' ++ b1 :: l2''));\ndestruct (nth_error (l2' ++ b1 :: l2'') (pi (S i))) as [bi | ]; \n[idtac | contradiction].\nintros H' ai_R_bi; destruct (H' _ (eq_refl _)) as [k2 [k2' [Lk2 H'']]]; clear H'.\ndestruct (in_in_split_set b1 bi l2' l2'' k2 k2' H'') as [[H''' | H'''] | H''']; clear H''.\ndestruct H''' as [l [H3 H4]]; subst.\nrewrite <- ass_app; rewrite <- Lk2; rewrite <- L''; simpl.\ndestruct (le_lt_dec (length k2) (length (k2 ++ bi :: l))) as [Ok | Ko].\nrewrite nth_error_at_pos; trivial.\nabsurd (length k2 < length k2); auto with arith.\napply le_lt_trans with (length (k2 ++ bi :: l)); trivial.\nrewrite length_app; auto with arith.\ndestruct H''' as [l [H3 H4]]; subst.\nrewrite <- Lk2; rewrite <- L''; simpl.\ndestruct (le_lt_dec (length (l2' ++ b1 :: l)) (length l2')) as [Ko | Ok].\nabsurd (length l2' < length l2'); auto with arith.\napply lt_le_trans with (length (l2' ++ b1 :: l)); trivial.\nrewrite length_app; rewrite plus_comm; simpl; auto with arith.\nrewrite (length_app l2' (b1 :: l)).\nrewrite plus_comm; simpl; rewrite <- minus_n_O; rewrite plus_comm;\nrewrite <- length_app.\nrewrite ass_app; rewrite nth_error_at_pos; trivial.\ndestruct H''' as [_ [H3 H4]]; subst;\nabsurd (0 = S i).\ndiscriminate.\ndestruct P as [_ [_ P]].\napply P; simpl; auto with arith.\nrewrite <- Lk2; rewrite L''; subst; trivial.\nintro; contradiction.\nQed.\n\nSection defs.\n\n  (** * From lists to multisets *)\n\n  Variable A : Type.\n  Variable eqA : relation A.\n  Hypothesis eqA_dec : forall x y:A, {eqA x y} + {~ eqA x y}.\n\n  Let emptyBag := EmptyBag A.\n  Let singletonBag := SingletonBag _ eqA_dec.\n\n  (** contents of a list *)\n\n  Fixpoint list_contents (l:list A) : multiset A :=\n    match l with\n      | nil => emptyBag\n      | a :: l => munion (singletonBag a) (list_contents l)\n    end.\n\n  (** * [permutation]: definition and basic properties *)\n  \n  Definition permutation (l m:list A) :=\n    meq (list_contents l) (list_contents m).\nEnd defs.\n\nLemma permut_closure : forall (A : Type) eqA \n (eqA_dec : forall a1 a2, {eqA a1 a2}+{~eqA a1 a2}), \nforall a1 a2, @permutation A eqA eqA_dec (a1 :: nil) (a2 :: nil) <-> \n(forall a, eqA a1 a <-> eqA a2 a).\nProof.\nintros A eqA eqA_dec; unfold permutation, meq; simpl.\nintros a1 a2; split.\nintros H a; assert (Ha := H a); clear H; do 2 rewrite <- plus_n_O in Ha.\ndestruct (eqA_dec a1 a) as [a1_eq_a | a1_diff_a];\ndestruct (eqA_dec a2 a) as [a2_eq_a | a2_diff_a].\nintuition.\ndiscriminate.\ndiscriminate.\nintuition.\nintros H a;\ndestruct (eqA_dec a1 a) as [a1_eq_a | a1_diff_a];\ndestruct (eqA_dec a2 a) as [a2_eq_a | a2_diff_a]; trivial.\nabsurd (eqA a2 a); trivial; rewrite <- (H a); trivial.\nabsurd (eqA a1 a); trivial; rewrite  (H a); trivial.\nQed.\n\n\n\n\n\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Coccinelle/list_extensions/math_permut.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.6748136052624499}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import all_ssreflect.\n(**\n#<div class=\"slide vfill\">#\n** Recap\n\n Proof language\n   - [: name], to prepare the goal for a tactic\n   - [=>] [name] [/view] [//] [/=] [{name}] [[]], to post-process the goal\n   - [rewrite lem -lem // /= /def]\n   - [apply: lem]\n Library\n   - naming convention: [addnC], [eqP], [orbN], [orNb], ...\n   - notations: [.+1], [if-is-then-else]\n   - [Search _ (_ + _) in ssrnat]\n   - [Search _ addn \"C\" in ssrnat]\n   - Use the HTML doc!\n Approach\n   - boolean predicates\n   - [reflect P b] to link bool with Prop\n\n#</div>#\n--------------------------------------------------------\n#<div class=\"slide vfill\">#\n** Today\n   - The [seq] library\n   - forward reasoning with [have]\n   - spec lemmas\n   - [rewrite] patterns\n\n#</div>#\n--------------------------------------------------------\n--------------------------------------------------------\n#<div class=\"slide\">#\n** Sequences\n  - an alias for lists (used to be differnt)\n  - many notations\n\n*)\nCheck [::].\nCheck [:: 3 ; 4].\nCheck [::] ++ [:: true ; false].\nEval compute in [seq x.+1 | x <- [:: 1; 2; 3]].\nEval compute in [seq x <- [::3; 4; 5] | odd x ].\nEval compute in rcons [:: 4; 5] 3.\nEval compute in all odd [:: 3; 5].\n\nModule polylist.\n\n(**\n#</div>#\n--------------------------------------------------------\n#<div class=\"slide\">#\n** Polymorphic lists\n   - This statement makes no assumptions on T\n   - recap: [// /= ->]\n*)\nLemma size_cat T (s1 s2 : seq T) : size (s1 ++ s2) = size s1 + size s2.\nProof.  by elim: s1 => //= x s1 ->. Qed.\n\nEnd polylist.\n\nEval compute in 3 \\in [:: 7; 4; 3].\n\nFail Check forall T : Type, forall x : T, x \\in [:: x ].\n\n(** \n#</div>#\n--------------------------------------------------------\n#<div class=\"slide\">#\n** Had-hoc polymorphism\n  - T : Type |- l : list T \n  - T : eqType |- l : list T\n  - eqType means: a type with a decidable equality (_ == _)\n*)\n\nCheck forall T : eqType, forall x : T, x \\in [:: x ].\n\n(**\n#</div>#\n--------------------------------------------------------\n#<div class=\"slide\">#\n** The \\in notation\n   - overloaded as [(_ == _)]\n   - pushing \\in with inE\n   - computable.\n   - rewrite !inE\n*)\nLemma test_in l : 3 \\in [:: 4; 5] ++ l -> l != [::].\nProof.\nby rewrite !inE => /=; apply: contraL => /eqP->.\nQed.\n\n(**\n#</div>#\n--------------------------------------------------------\n#<div class=\"slide\">#\n** Forward reasoning\n   - have\n   - have :=\n   - have + views\n   - do I need eqType here?\n*)\n(**\nDefinition of all\n<<\nFixpoint all a s := if s is x :: s' then a x && all a s' else true.\n>> *)\n(** \nDefinition of count\n<<\nFixpoint count a s := if s is x :: s' then a x + count s' else 0.\n>> *)\n(** \nA lemma linking the two concepts *)\nLemma all_count (T : eqType) (a : pred T) s :\n  all a s = (count a s == size s).\nProof.\nelim: s => //= x s.\nhave EM_a : a x || ~~ a x.\n  by exact: orbN.\nmove: EM_a => /orP EM_a. case: EM_a => [-> | /negbTE-> ] //= _.\n(*# have /orP[ ax | n_ax ] : a x || ~~ a x by case: (a x). #*)\nSearch _ count size in seq.\nby rewrite add0n eqn_leq andbC ltnNge count_size.\n(*# have := boolP (a x). #*)\nQed.\n\n(**\n#</div>#\n--------------------------------------------------------\n--------------------------------------------------------\n#<div class=\"slide\">#\n** Spec lemmas\n   - Inductive predicates to drive the proof\n*)\n\nModule myreflect1.\n\nInductive reflect (P : Prop) (b : bool) : Prop :=\n  | ReflectT (p : P) (e : b = true)\n  | ReflectF (np : ~ P) (e : b = false).\n\nFixpoint eqn m n :=\n  match m, n with\n  | 0, 0 => true\n  | j.+1,k.+1 => eqn j k\n  | _, _ => false\n  end.\nArguments eqn !m !n.\n\nAxiom eqP : forall m n, reflect (m = n) (eqn m n).\n\nLemma test_reflect1 m n : ~~ (eqn m n) || (n <= m <= n).\nProof.\ncase: (eqn m n) => /=.\n(*# case: (eqP m n) => [Enm -> | nE_mn ->] /=. #*)\nAdmitted.\n\nEnd myreflect1.\n\n(*#\nModule myreflect2.\n\nInductive reflect (P : Prop) : bool-> Prop :=\n  | ReflectT (p : P) : reflect P true\n  | ReflectF (np : ~ P) : reflect P false.\n\nFixpoint eqn m n :=\n  match m, n with\n  | 0, 0 => true\n  | j.+1,k.+1 => eqn j k\n  | _, _ => false\n  end.\nArguments eqn !m !n.\n\nAxiom eqP : forall m n, reflect (m = n) (eqn m n).\nArguments eqP {m n}.\n\nLemma test_reflect1 m n : ~~ (eqn m n) || (n <= m <= n).\nProof.\ncase: (@eqP m n) => [Enm | nE_mn ] /=.\nby case: eqP => [->|] //=; rewrite leqnn.\nQed.\n\nEnd myreflect2.\n\nCheck (_ =P _).\nCheck eqP.\n\n#*)\n\nInductive leq_xor_gtn m n : bool -> bool -> Prop :=\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\nAxiom leqP : forall m n : nat, leq_xor_gtn m n (m <= n) (n < m).\n\n(**\n#</div>#\n--------------------------------------------------------\n#<div class=\"slide\">#\n** Let's try out leqP on an ugly goal\n   - matching of indexes\n   - generalization of unresolved implicits\n   - instantiation by matching\n*)\nLemma test_leqP m n1 n2 :\n  (m <= (if n1 < n2 then n1 else n2)) =\n  (m <= n1) && (m <= n2) && ((n1 < n2) || (n2 <= n1)).\nProof.\ncase: leqP => [leqn21 | /ltnW ltn12 ]; rewrite /= andbT.\n  by rewrite andb_idl // => /leq_trans /(_ leqn21).\nby rewrite andb_idr // => /leq_trans->.\nQed.\n\n(**\n#</div>#\n--------------------------------------------------------\n#<div class=\"slide\">#\n** Another commodity: [ifP]\n   - a spec lemma for if-then-else\n   - handy with case, since matching spares you to write\n     the expressions involved\n*)\nLemma test_ifP n m : if n <= m then 0 <= m - n else m - n == 0.\nProof.\ncase: ifP => //.\nby move=> /negbT; rewrite subn_eq0 leqNgt negbK=> /ltnW.\nQed.\n\n(**\n#</div>#\n\n--------------------------------------------------------\n#<div class=\"slide\">#\n** Rewrite on steroids\n   - keyed matching\n   - instantiation\n   - localization\n*)\nLemma ugly_goal n m :\n  n + (m * 2).+1 = n + (m + m.+1).\nProof.\nrewrite addnC.\nrewrite (addnC m).\nrewrite [_ + m]addnC.\nrewrite [in n + _]addnC.\nrewrite [X in _ = X + n]addnC.\nrewrite [in RHS]addnC.\nAbort.\n\nLemma ugly_goal n m :\n  n + m = n + m.\nProof.\nrewrite addnC.\nrewrite [in RHS]addnC.\nAbort.\n\nLemma no_pattern n : n + 0 = n.\nProof.\nrewrite -[n in RHS]addn0.\nAbort.\n\n(**\n#</div>#\n--------------------------------------------------------\n#<div class=\"slide vfill\">#\n** References for this lesson:\n  - SSReflect #<a href=\"https://hal.inria.fr/inria-00258384\">manual</a>#\n  - documentation of the\n       #<a href=\"http://math-comp.github.io/math-comp/htmldoc/libgraph.html\">library</a>#\n    - in particular #<a href=\"http://math-comp.github.io/math-comp/htmldoc/mathcomp.ssreflect.seq.html\">seq</a>#\n\n#</div>#\n--------------------------------------------------------\n#<div class=\"slide\">#\n** Demo:\n   - you should be now able to read this proof\n\n*)\n\nLemma dvdn_fact m n : 0 < m <= n -> m %| n`!.\nProof.\ncase: m => //= m; elim: n => //= n IHn; rewrite ltnS leq_eqVlt.\nby move=> /orP[ /eqP-> | /IHn]; [apply: dvdn_mulr | apply: dvdn_mull].\nQed.\n\nLemma prime_above m : {p | m < p & prime p}.\nProof.\nCheck pdivP.\nhave /pdivP[p pr_p p_dv_m1]: 1 < m`! + 1 by rewrite addn1 ltnS fact_gt0.\nexists p => //; rewrite ltnNge; apply: contraL p_dv_m1 => p_le_m.\nCheck dvdn_addr.\nby rewrite dvdn_addr ?dvdn_fact ?prime_gt0 // gtnNdvd ?prime_gt1.\nQed.\n    \n(** #</div># *)\n\n\n", "meta": {"author": "gares", "repo": "CWS16", "sha": "608148973a715994ebbedb0a48724f2755c7bc89", "save_path": "github-repos/coq/gares-CWS16", "path": "github-repos/coq/gares-CWS16/CWS16-608148973a715994ebbedb0a48724f2755c7bc89/lesson2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.6748135921999423}}
{"text": "Require Import Setoid.\nRequire Import Morphisms.\nRequire Import Coq.Program.Basics.\nRequire Import ClassicalFacts.\n\nUnset Printing Records.\n\nFrom Ordinal Require Import Defs.\nFrom Ordinal Require Import Operators.\nFrom Ordinal Require Import Arith.\nFrom Ordinal Require Import Enumerate.\n\nSection fixpoints.\n  Variable f : Ord -> Ord.\n\n  Definition iter_f (base:Ord) : nat -> Ord :=\n    fix iter_f (n:nat) : Ord :=\n      match n with\n      | 0 => base\n      | S n' => f (iter_f n')\n      end.\n\n  Lemma iter_f_monotone :\n     (forall x y, x <= y -> f x <= f y) ->\n     forall i x y, x <= y -> iter_f x i <= iter_f y i.\n  Proof.\n    intro H. induction i; simpl; auto.\n  Qed.\n\n  Definition fixOrd (base:Ord) : Ord := supOrd (iter_f base).\n\n  Lemma fixOrd_above : forall base, base ≤ fixOrd base.\n  Proof.\n    intros.\n    unfold fixOrd.\n    apply (sup_le _ (iter_f base) 0%nat).\n  Qed.\n\n  Lemma iter_f_complete n :\n    forall base, complete base ->\n    (forall x, complete x -> complete (f x)) ->\n    complete (iter_f base n).\n  Proof.\n    induction n as [n IH1] using (well_founded_induction Wf_nat.lt_wf).\n    destruct n; simpl; auto.\n  Qed.\n\n  Lemma iter_f_index_monotone i j :\n    (forall x, complete x -> x <= f x) ->\n    (forall x, complete x -> complete (f x)) ->\n    (i <= j)%nat ->\n    forall base, complete base -> iter_f base i <= iter_f base j.\n  Proof.\n    intros Hf1 Hf2 H; induction H; intros base Hbase; simpl.\n    - reflexivity.\n    - rewrite IHle; auto.\n      apply Hf1. apply iter_f_complete; auto.\n  Qed.\n\n  Lemma directed_iter_f base :\n    (forall x, complete x -> x <= f x) ->\n    (forall x y, x <= y -> f x <= f y) ->\n    (forall x, complete x -> complete (f x)) ->\n    complete base ->\n    directed nat (iter_f base).\n  Proof.\n    intros. intros i j. exists (Nat.max i j).\n    split; apply iter_f_index_monotone; auto.\n    + apply PeanoNat.Nat.le_max_l.\n    + apply PeanoNat.Nat.le_max_r.\n  Qed.\n\n  Hypothesis Hmonotone : forall x y, x <= y -> f x <= f y.\n\n  Lemma fixOrd_monotone :\n     forall x y, x <= y -> fixOrd x <= fixOrd y.\n  Proof.\n    unfold fixOrd; intros.\n    apply sup_least. intro n.\n    eapply ord_le_trans with (iter_f y n); [ | apply sup_le ].\n    apply iter_f_monotone; auto.\n  Qed.\n\n  Hypothesis Hcont : strongly_continuous f.\n\n  Lemma fixOrd_prefixpoint : forall base, f (fixOrd base) ≤ fixOrd base.\n  Proof.\n    intros.\n    apply ord_le_trans with (supOrd (fun i => f (iter_f base i))).\n    - apply (Hcont nat (iter_f base) 0%nat).\n    - apply sup_least. intro i.\n      unfold fixOrd.\n      apply (sup_le _ (iter_f base) (S i)).\n  Qed.\n\n  Hypothesis Hinflationary : forall x, x ≤ f x.\n\n  Lemma fixOrd_fixpoint : forall base, fixOrd base ≈ f (fixOrd base).\n  Proof.\n    intros; split.\n    - apply Hinflationary.\n    - apply fixOrd_prefixpoint; auto.\n  Qed.\n\n  Lemma fixOrd_least : forall base z, base ≤ z -> f z ≤ z -> fixOrd base ≤ z.\n  Proof.\n    intros.\n    unfold fixOrd.\n    apply sup_least.\n    intro i; induction i; simpl; auto.\n    apply ord_le_trans with (f z); auto.\n  Qed.\n\n  Lemma normal_fix_continuous : strongly_continuous fixOrd.\n  Proof.\n    intros A g a0. unfold fixOrd.\n    apply sup_least; intro i.\n    induction i; simpl.\n    - apply sup_ord_le_morphism. intro a.\n      rewrite <- (sup_le _ _ 0%nat).\n      simpl. auto with ord.\n    - etransitivity; [ apply Hmonotone; apply IHi |].\n      rewrite (Hcont A (fun i => supOrd (iter_f (g i))) a0).\n      apply sup_ord_le_morphism. intro a.\n      apply fixOrd_prefixpoint.\n  Qed.\n\n  Lemma normal_fix_complete base :\n    complete base ->\n    (forall x, complete x -> x <= f x) ->\n    (forall x y, x <= y -> f x <= f y) ->\n    (forall x, complete x -> complete (f x)) ->\n    complete (fixOrd base).\n  Proof.\n    intros Hbase Hf1 Hf2 Hf3.\n    unfold fixOrd.\n    apply sup_complete; auto.\n    - intros; apply iter_f_complete; auto.\n    - apply directed_iter_f; auto.\n    - assert (Hc' : complete (f base)).\n      { apply Hf3; auto. }\n      destruct (complete_zeroDec base Hbase).\n      + destruct (complete_zeroDec (f base) Hc').\n        * right. intro i.\n          revert H H0. clear -Hf1 Hf2 Hbase. revert base Hbase.\n          induction i; simpl; intros; auto.\n          transitivity (f base); auto.\n          apply Hf2; auto.\n          rewrite IHi; auto.\n          apply zero_least.\n        * left.\n          exists 1%nat. simpl.\n          auto.\n      + left.\n        exists 0%nat. simpl. auto.\n  Qed.\n\nEnd fixpoints.\n\n\nLemma iter_f_monotone_func f g n :\n  (forall x, f x ≤ g x) ->\n  (forall x y, x ≤ y -> g x ≤ g y) ->\n  forall x, iter_f f x n ≤ iter_f g x n.\nProof.\n  intros Hf Hg.\n  induction n; intros; simpl.\n  - reflexivity.\n  - etransitivity; [ apply Hf | apply Hg; auto ].\nQed.\n\nLemma fixOrd_monotone_func f g :\n  (forall x, f x ≤ g x) ->\n  (forall x y, x ≤ y -> g x ≤ g y) ->\n  forall x, fixOrd f x ≤ fixOrd g x.\nProof.\n  intros.\n  unfold fixOrd. apply sup_ord_le_morphism.\n  intro n. apply iter_f_monotone_func; auto.\nQed.\n\n\nDefinition enum_fixpoints (f:Ord -> Ord) : Ord -> Ord :=\n  fix rec (x:Ord) : Ord :=\n  match x with\n  | ord B g => fixOrd f (ord B (fun b => rec (g b)))\n  end.\n\nLemma enum_fixpoints_monotone f :\n  (forall x y, x ≤ y -> f x ≤ f y) ->\n  (forall x y, x ≤ y -> enum_fixpoints f x ≤ enum_fixpoints f y).\nProof.\n  intros Hf x y; revert x.\n  induction y as [C h Hy].\n  destruct x as [B g].\n  simpl; intros.\n  unfold fixOrd.\n  apply sup_ord_le_morphism; intro i; simpl.\n  apply iter_f_monotone; auto.\n  rewrite ord_le_unfold; simpl; intro b.\n  rewrite ord_lt_unfold; simpl.\n  destruct (ord_le_subord _ _ H b) as [c Hb].\n  exists c.\n  apply Hy; auto.\nQed.\n\nLemma enum_fixpoints_increasing f :\n  (forall x y, x ≤ y -> f x ≤ f y) ->\n  (forall x y, x < y -> enum_fixpoints f x < enum_fixpoints f y).\nProof.\n  intros Hf x y H.\n  rewrite ord_lt_unfold in H.\n  destruct x as [B g].\n  destruct y as [C h].\n  simpl in *.\n  destruct H as [i ?].\n  eapply ord_lt_le_trans; [| apply fixOrd_above ].\n  rewrite ord_lt_unfold. exists i. simpl.\n  apply (enum_fixpoints_monotone f Hf (ord B g) (h i)); auto.\nQed.\n\nLemma enum_fixpoints_func_mono f g :\n  (forall x y, x ≤ y -> f x ≤ f y) ->\n  (forall x y, x ≤ y -> g x ≤ g y) ->\n  (forall x, f x ≤ g x) ->\n  (forall x, enum_fixpoints f x ≤ enum_fixpoints g x).\nProof.\n  intros Hf Hg Hfg.\n  induction x as [A q Hx]; simpl.\n  unfold fixOrd.\n  apply sup_ord_le_morphism. intro i.\n  transitivity (iter_f f (ord A (fun b : A => enum_fixpoints g (q b))) i).\n  - apply iter_f_monotone; auto.\n    rewrite ord_le_unfold; simpl; intro a.\n    rewrite ord_lt_unfold; simpl; exists a.\n    auto.\n  - apply iter_f_monotone_func; auto.\nQed.\n\nLemma enum_are_fixpoints f :\n  strongly_continuous f ->\n  (forall x, x ≤ f x) ->\n  forall x, enum_fixpoints f x ≈ f (enum_fixpoints f x).\nProof.\n  intros Hcont Hinflationary.\n  destruct x as [X g]; simpl.\n  apply fixOrd_fixpoint; auto.\nQed.\n\nLemma enum_fixpoints_zero f :\n  (forall x y, x ≤ y -> f x ≤ f y) ->\n  enum_fixpoints f zeroOrd ≈ fixOrd f zeroOrd.\nProof.\n  simpl.\n  split; apply fixOrd_monotone; auto.\n  - rewrite ord_le_unfold; simpl; intuition.\n  - rewrite ord_le_unfold; simpl; intuition.\nQed.\n\nLemma enum_fixpoints_succ f x :\n  enum_fixpoints f (succOrd x) ≈ fixOrd f (succOrd (enum_fixpoints f x)).\nProof.\n  simpl; intros. reflexivity.\nQed.\n\nLemma enum_fixpoints_cont f :\n  (forall x y, x ≤ y -> f x ≤ f y) ->\n  (forall x, x ≤ f x) ->\n  strongly_continuous f ->\n  strongly_continuous (enum_fixpoints f).\nProof.\n  intros Hmono Hinf Hcont A g a0.\n  apply fixOrd_least; auto.\n  - rewrite ord_le_unfold.\n    simpl.\n    intros [a i]. simpl.\n    rewrite <- (sup_le _ _ a).\n    apply enum_fixpoints_increasing; auto with ord.\n  - rewrite (Hcont A (fun i => enum_fixpoints f (g i)) a0).\n    apply sup_least; intro a.\n    rewrite <- enum_are_fixpoints; auto.\n    rewrite <- (sup_le _ _ a); auto with ord.\nQed.    \n\nTheorem enum_fixpoints_enumerates f:\n  (forall x, x ≤ f x) ->\n  (forall x y, x ≤ y -> f x ≤ f y) ->\n  strongly_continuous f ->\n  enumerates (enum_fixpoints f) (fun x => x ≈ f x).\nProof.\n  intros Hinf Hmono Hcont.\n  hnf; intros.\n  constructor; auto.\n  - apply enum_are_fixpoints; auto.\n  - intros; apply enum_fixpoints_monotone; auto.\n  - intros; apply enum_fixpoints_increasing; auto.\n  - intros x z Hz1 Hz2.\n    destruct x as [A g]. simpl.\n    apply fixOrd_least; auto.\n    + rewrite ord_le_unfold. simpl; intros.\n      apply Hz2. apply (index_lt (ord A g) a).\n    + apply Hz1.\nQed.\n\n\nLemma enum_fixpoints_enumerates_range f : \n  (forall x, x ≤ f x) ->\n  (forall x y, x ≤ y -> f x ≤ f y) ->\n  strongly_continuous f ->\n  enumerates (enum_fixpoints f) (fun x => exists y, x ≈ enum_fixpoints f y).\nProof.\n  intros Hinf Hmono Hcont.\n  hnf; intros.\n  constructor; auto.\n  - intro x. exists x. reflexivity.\n  - intros; apply enum_fixpoints_monotone; auto.\n  - intros; apply enum_fixpoints_increasing; auto.\n  - intros x z [y Hy] H.\n    destruct x as [A g]; simpl; intros.\n    apply fixOrd_least; auto.\n    + rewrite ord_le_unfold; simpl; intros.\n      apply H. apply (index_lt (ord A g)).\n    + transitivity (f (enum_fixpoints f y)).\n      apply Hmono. apply Hy.\n      rewrite Hy.\n      apply enum_are_fixpoints; auto.\nQed.\n\nLemma enum_fixpoints_complete f :\n  (forall x, complete x -> x ≤ f x) ->\n  (forall x y, x ≤ y -> f x ≤ f y) ->\n  (forall x, complete x -> complete (f x)) ->\n  forall x, complete x -> complete (enum_fixpoints f x).\nProof.\n  intros Hf1 Hf2 Hf3.\n  induction x as [B g Hx]. intro Hc.\n  simpl enum_fixpoints.\n  apply normal_fix_complete; auto.\n  apply lim_complete.\n  + intros; apply Hx. apply Hc.\n  + intros b1 b2. destruct (complete_directed _ Hc b1 b2) as [b' [Hb1 Hb2]].\n    exists b'. split; apply enum_fixpoints_monotone; auto.\n  + apply Hc.\nQed.\n\nDefinition ε (x:Ord) := enum_fixpoints powOmega x.\n\nLemma ε_monotone : forall x y, x ≤ y -> ε x ≤ ε y.\nProof.\n  unfold ε.\n  apply enum_fixpoints_monotone.\n  apply powOmega_monotone.\nQed.\n\nLemma ε_increasing : forall x y, x < y -> ε x < ε y.\nProof.\n  unfold ε.\n  apply enum_fixpoints_increasing.\n  apply powOmega_monotone.\nQed.\n\nLemma ε_continuous : strongly_continuous ε.\nProof.\n  unfold ε.\n  apply enum_fixpoints_cont; auto.\n  apply powOmega_monotone.\n  apply increasing_inflationary.\n  apply powOmega_increasing.\n  unfold powOmega.\n  apply expOrd_continuous.\nQed.\n\nLemma ε_fixpoint : forall x, ε x ≈ expOrd ω (ε x).\nProof.\n  intro x.\n  apply enum_are_fixpoints.\n  apply expOrd_continuous.\n  apply increasing_inflationary.\n  apply powOmega_increasing.\nQed.\n\nTheorem ε_enumerates : enumerates ε (fun x => x ≈ expOrd ω x).\nProof.\n  unfold ε.\n  apply enum_fixpoints_enumerates.\n  apply increasing_inflationary.\n  apply powOmega_increasing.\n  apply powOmega_monotone.\n  apply expOrd_continuous.\nQed.\n\nTheorem ε_complete x : complete x -> complete (ε x).\nProof.\n  intros. unfold ε.\n  apply enum_fixpoints_complete; auto.\n  intros; apply increasing_inflationary. apply powOmega_increasing.\n  apply powOmega_monotone.\n  intros; apply expOrd_complete; auto.\n  apply (index_lt ω 0%nat).\n  apply omega_complete.\nQed.\n\nOpaque foldOrd.\n\nTheorem ε0_least_expOmega_closed : \n  forall X, expOrd ω X ≤ X -> ε 0 ≤ X.\nProof.\n  intros.\n  unfold ε. simpl. unfold fixOrd.\n  apply sup_least; intro i.\n  induction i; simpl iter_f.\n  { rewrite ord_le_unfold; intros []. }\n  rewrite <- H.\n  unfold powOmega.\n  apply expOrd_monotone.\n  apply IHi.\nQed.\n\n\nTheorem KnuthUp_epsilon : KnuthUp 2 ω ω ≈ ε 0.\nProof.\n  rewrite KnuthUp_succ.\n  transitivity (foldOrd 1 (expOrd ω) ω); [ reflexivity |].\n  rewrite foldOrd_unfold.\n  split.\n  - apply lub_least.\n    + unfold ε; simpl.\n      unfold fixOrd.\n      rewrite <- (sup_le _ _ 1%nat).\n      apply succ_least. apply expOrd_nonzero.\n    + apply sup_least; intro n.\n      induction n.\n      * simpl.\n        rewrite foldOrd_unfold.\n        transitivity (expOrd ω 1).\n        { apply expOrd_monotone. apply lub_least; auto with ord.\n          apply sup_least; intros []. }\n        unfold fixOrd. rewrite <- (sup_le _ _ 2%nat).\n        unfold iter_f. unfold powOmega.\n        apply expOrd_monotone.\n        apply succ_least. apply expOrd_nonzero.\n      * unfold ε. simpl.\n        rewrite fixOrd_fixpoint.\n        unfold powOmega.\n        apply expOrd_monotone.\n        rewrite foldOrd_succ.\n        apply IHn.\n        intros. apply succ_least; apply expOrd_nonzero.\n        apply expOrd_continuous.\n        apply increasing_inflationary.\n        apply powOmega_increasing.\n  - unfold ε. simpl enum_fixpoints. unfold fixOrd.\n    apply sup_least; intro n.\n    rewrite <- lub_le2.\n    rewrite <- (sup_le _ _ n).\n    simpl.\n    induction n; simpl.\n    + rewrite ord_le_unfold; intros [].\n    + unfold powOmega at 1.\n      apply expOrd_monotone.\n      rewrite foldOrd_succ.\n      apply IHn.\n      intros. apply succ_least. apply expOrd_nonzero.\nQed.\n", "meta": {"author": "robdockins", "repo": "ordinals", "sha": "063164521baddfc99ab8c2d222cb01637e8833e1", "save_path": "github-repos/coq/robdockins-ordinals", "path": "github-repos/coq/robdockins-ordinals/ordinals-063164521baddfc99ab8c2d222cb01637e8833e1/Ordinal/Fixpoints.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552536, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6747957041190482}}
{"text": "(** * TAL-0 Typed Assembly Language *)\n\n(** Based on paper by Greg Morrisett , TAL-0 is the design of a RISC-style typed assembly language which focuses on control-flow safety. This post provides a mechanized metatheory, particularly a machine checked proof of soundness of the TAL-0 type system as proposed by the author in section 4.2.10 of the book Advanced Topics in Types and Programming Languages.  *)\n\n(** The TAL-0 language runs on an abstract machine which is represented by 3 components :\n\n1. A heap H which is a finite, partial map from labels to heap values\n\n2. a register file R which is a total map from registers to values, and \n\n3. a current instruction sequence I.  \n*)\n\nRequire Import Bool Arith Vector.\nRequire Import LibTactics Maps.\n\nDefinition registers := total_map nat.\nDefinition empty_regs : registers := t_empty 0.\n      \nInductive val : Type :=\n | ANum : nat -> val\n | AReg : nat -> val\n | ALab : nat -> val.\n\n(** We denote addresses of instructions stored in the heap as labels. Unlike a typical machine where labels are resolved to some machine address, which are integers, we maintain a distinction between labels and arbit integers, as this complies with our goal to state and prove the control-flow safety i.e. we can only branch to a valid label, and not to any arbit integer. This will ensure that the machine never gets stuck while trying to do some invalid operation. *)\n(*define relations for aeval , ieval*)\nFixpoint aeval (a : val) (R : registers) : nat :=\n  match a with\n | ANum n => n\n | AReg d => R (Id d)\n | ALab l => l\n  end.\n\n\nInductive instr : Type :=\n | IMov : forall d : nat,\n    val -> instr\n | IAdd : forall d s : nat,\n    instr\n | ISub : forall d v : nat,\n    instr\n | IIf : forall d : nat,\n    val -> instr.\n\nInductive instr_seq : Type :=\n | ISeq : instr -> instr_seq -> instr_seq\n | IJmp : val -> instr_seq.\n\n(** Simple Notations are chosen for the sake of clarity while writing programs.*)\nNotation \"'R(' d ')' ':=' a\" :=\n  (IMov d (ANum a)) (at level 60).\nNotation \"'R(' d ')' '+:=' 'R(' s ')'\" :=\n  (IAdd d s) (at level 60).\nNotation \"'R(' s ')' '-:=' v\" :=\n  (ISub s v) (at level 60).\nNotation \"i1 ;; i2\" :=\n  (ISeq i1 i2) (at level 80, right associativity).\nNotation \"'JIF' 'R(' d ')' v\" :=\n  (IIf d (ANum v)) (at level 70).\nNotation \"'JMP' v\" :=\n  (IJmp (ALab v)) (at level 80).\nNotation \"'JMP' 'R(' r ')'\" :=\n  (IJmp (AReg r)) (at level 80).\n\nCheck JIF R(1) 2.\nCheck R(1) := 10.\nCheck R(2) +:= R(1).\nCheck R(2) -:= 1.\nCheck R(2) +:= R(1) ;; R(2) -:= 1 ;; JMP 2.\nCheck JMP 2.\nCheck JMP R(2).\n\n      \nDefinition heaps := partial_map instr_seq.\nDefinition empty_heap : heaps := empty.\n\n(* Machine State *)\nInductive st : Type :=\n | St : heaps -> registers -> instr_seq -> st.\n\n(** Evaluation of instructions is supposed to change the Machine State and thus some of its components H, R or I. These changes are posed as relations between initial and final state of the machine. *)\nInductive ieval : st -> st -> Prop :=\n | R_IMov : forall H R I d a,\n    ieval (St H R (R(d) := a ;; I)) (St H (t_update R (Id d) a) I)\n | R_IAdd : forall H R I d s,\n     ieval (St H R (R(d) +:= R(s) ;; I)) (St H (t_update R (Id d) (aeval (AReg d) R + aeval (AReg s) R)) I)\n | R_ISub : forall H R I d v,\n     ieval (St H R (R(d) -:= v ;; I)) (St H (t_update R (Id d) (aeval (AReg d) R - aeval (ANum v) R)) I)\n | R_IJmp_Succ : forall H R I' a l,\n     l = (aeval a R) -> H (Id l) = Some I' -> ieval (St H R (JMP l)) (St H R I')\n | R_IJmpR_Succ : forall H R I' r,\n     H (Id (R (Id r))) = Some I' -> ieval (St H R (JMP R(r))) (St H R I')\n | R_IJmp_Fail : forall H R I a,\n     H (Id (aeval a R)) = None -> ieval (St H R I) (St H R I)\n | R_IIf_EQ : forall H R I I2 r v,\n     aeval (AReg r) R = 0 -> (H (Id v)) = Some I2 -> ieval (St H R (JIF R(r) v ;; I)) (St H R I2)\n | R_IIf_NEQ : forall H R I r v,\n     aeval (AReg r) R <> 0 -> ieval (St H R (JIF R(r) v ;; I)) (St H R I)   \n | R_ISeq : forall st st' st'',\n     ieval st st' -> ieval st' st'' -> ieval st st''.\n\n(** Example of a program fragment that multiplies 2 numbers stored in registers 1 and 2 and stores their product in register 3, before finally looping in its final state register 4. *)\nDefinition init_heap := update (update (update empty_heap (Id 1) (R(3) := 0 ;; JMP 2)) (Id 2) (JIF R(1) 3 ;; R(2) +:= R(3) ;; R(1) -:= 1 ;; JMP 2) ) (Id 3) (JMP R(4)).\n\nDefinition init_regs : registers :=  (t_update (t_update  (t_update (t_update (t_update empty_regs (Id 5) 1) (Id 6) 2) (Id 7) 3) (Id 1) 1) (Id 2) 2).\nDefinition final_regs : registers := (t_update (t_update (t_update  (t_update (t_update (t_update empty_regs (Id 5) 1) (Id 6) 2) (Id 4) 1) (Id 1) 0) (Id 2) 2) (Id 3) 2).\n\nEval compute in init_heap (Id (init_regs (Id 6))).\n\n(* jump to a label proof *)\nExample ieval_example1 : ieval (St init_heap init_regs\n                          (R(3) := 0 ;; JMP 2))\n                               (St init_heap (t_update init_regs (Id 3) 0)\n                          (JIF R(1) 3 ;; R(2) +:= R(3) ;; R(1) -:= 1 ;; JMP 2)).\nProof.\n  apply R_ISeq with (St init_heap (t_update init_regs (Id 3) 0) (IJmp (ALab 2))).\n  apply R_IMov.\n  apply R_IJmp_Succ with (a := ALab 2).\n  simpl.\n  reflexivity.\n  unfold init_heap.\n  rewrite update_neq.\n  rewrite update_eq.\n  reflexivity.\n  rewrite <- beq_id_false_iff; trivial.\nQed.\n\n\n(** The types consist of\n1. int -> represents arbit integer stored in a register\n\n2. reg -> a type constructor. Takes as input, the type of the register, to which this register is pointing.\n\n3. code -> takes as input a typing context Γ, and gives type (code Γ) which is the type of an instruction sequence that expects type of the Register file to be Γ before it begins execution \n\n4. arrow -> represents type of a single instruction (excluding JMP), which expects register file of type Γ1 before execution, and changes it to Γ2 after it has executed.\n\n5. T -> It is the super type. It is used to represent the type of a register in R, which contains the label of the instruction currently executing. Because in such a case, we have the equation : Γ (r) = code Γ, which in the absence of subtyping or polymorphic types can't be solved. Hence T is assigned the type for such a register as it subsumes all types including itself. When we jump through a register of type T, we forget the type assigned to it, and reassign T to it.\nMorrisett's paper uses the polymorphic type for due to some more benefits it affords. However we have used T type for its simplicity.\n *)\n\nInductive ty : Type :=\n | int : ty\n | reg : ty -> ty\n | code : partial_map ty -> ty\n | arrow : partial_map ty -> partial_map ty -> ty\n | True : ty.\n\n\nDefinition context := partial_map ty.\n\n(* register file types *)\nDefinition empty_Gamma : context := empty.\n\n(* heap types *)\nDefinition empty_Psi : context := empty.\n\n(** The Typing Rules *)\n(** Ψ is a partial map containing types of instruction sequences. As all instruction sequences end in a JMP statement, all valid values in Ψ are Some (code Γ) where Γ is the initial type state of register expected by that instruction sequence. Now, typing rules may require presence of either both Ψ and Γ, or only Ψ or neither. Hence, we introduce a combined context structure, that handles all the 3 cases. *)\nInductive cmbnd_ctx :=\n | EmptyCtx : cmbnd_ctx\n | PsiCtx : context -> cmbnd_ctx\n | PsiGammaCtx : context -> context -> cmbnd_ctx.\n\n(** Typing rules for arithmetic expressions *)\nInductive ahas_type : cmbnd_ctx -> val -> ty -> Prop :=\n | S_Int : forall Ψ n,\n     ahas_type (PsiCtx Ψ) (ANum n) int\n | S_Lab : forall Ψ Γ l v R,\n     Ψ (Id l) = Some (code Γ) -> l = aeval (ALab v) R -> ahas_type (PsiCtx Ψ) (ALab v) (code Γ)\n | S_Reg : forall Ψ Γ r,\n     Γ (Id r) = Some (reg int) -> ahas_type (PsiGammaCtx Ψ Γ) (AReg r) (reg int)\n | S_RegV : forall Ψ Γ r,\n     ahas_type (PsiGammaCtx Ψ Γ) (AReg r) (reg (code Γ))\n | S_RegT : forall Ψ Γ r,\n     ahas_type (PsiGammaCtx Ψ Γ) (AReg r) True\n | S_Val : forall Ψ Γ a tau,\n     ahas_type (PsiCtx Ψ) a tau -> ahas_type (PsiGammaCtx Ψ Γ) a tau.\n\nHint Constructors ahas_type.\n\n(** Typing rules for instructions *)\nInductive ihas_type : cmbnd_ctx -> instr -> ty -> Prop :=\n | S_Mov : forall Ψ Γ R d a tau,\n    ahas_type (PsiGammaCtx Ψ Γ) a tau -> ahas_type (PsiGammaCtx Ψ Γ) (AReg d) (reg tau) -> (update Γ (Id d) (reg tau)) = Γ -> ihas_type (PsiCtx Ψ) (R(d) := aeval a R) (arrow Γ Γ)\n | S_Add : forall Ψ Γ d s,\n    ahas_type (PsiGammaCtx Ψ Γ) (AReg s) (reg int) -> ahas_type (PsiGammaCtx Ψ Γ) (AReg d) (reg int) -> update Γ (Id d) (reg int) = Γ -> ihas_type (PsiCtx Ψ) (R(d) +:= R(s)) (arrow Γ Γ)\n | S_Sub : forall Ψ Γ s a v,\n      ahas_type (PsiGammaCtx Ψ Γ) a int -> ahas_type (PsiGammaCtx Ψ Γ) (AReg s) (reg int) -> a = ANum v -> ihas_type (PsiCtx Ψ) (R(s) -:= v) (arrow Γ Γ)\n | S_If :  forall Ψ Γ r v,\n     ahas_type (PsiGammaCtx Ψ Γ) (AReg r) (reg int) -> ahas_type (PsiGammaCtx Ψ Γ) (ALab v) (code Γ) -> ihas_type (PsiCtx Ψ) (JIF R(r) v) (arrow Γ Γ).\nHint Constructors ihas_type.\n\n\nInductive iseq_has_type : cmbnd_ctx -> instr_seq -> ty -> Prop :=\n | S_Jmp :  forall Ψ Γ v,\n     ahas_type (PsiGammaCtx Ψ Γ) (ALab v) (code Γ) -> iseq_has_type (PsiCtx Ψ) (JMP v) (code Γ)\n | S_JmpT :  forall Ψ Γ v,\n     ahas_type (PsiGammaCtx Ψ Γ) (AReg v) True -> iseq_has_type (PsiCtx Ψ) (JMP R(v)) (code Γ)\n | S_Seq :  forall Ψ i1 i2 Γ Γ2,\n     ihas_type (PsiCtx Ψ) i1 (arrow Γ Γ2) -> iseq_has_type (PsiCtx Ψ) i2 (code Γ2) -> iseq_has_type (PsiCtx Ψ) (ISeq i1 i2) (code Γ).                                           Hint Constructors iseq_has_type.\n\n\n\nDefinition init_Gamma : context := update (update (update (update empty_Gamma (Id 1) (reg int)) (Id 2) (reg int)) (Id 3) (reg int)) (Id 4) True.\nCheck init_Gamma.\nHint Unfold init_Gamma.\n\nDefinition init_Psi : context := update (update (update empty_Psi (Id 1) (code init_Gamma))(Id 3) (code init_Gamma)) (Id 2) (code init_Gamma).\nHint Unfold init_Psi.\n\n\nLtac match_map := repeat (try rewrite update_neq; try rewrite update_eq; try reflexivity).\nLtac inequality := (rewrite <- beq_id_false_iff; trivial).\nLtac crush_map := match_map ; inequality; try reflexivity.\n\nLtac rewrite_hyp :=\n     match goal with\n       | [ H : ?n = _ |- context[?n] ] => rewrite H\n     end.\n\nLtac crush_generic :=\n  repeat match goal with\n         | [ H : ?T |- ?T    ] => exact T\n         | [ |- ?T = ?T ] => reflexivity\n         | [ |- True         ] => constructor\n         | [ |- _ /\\ _       ] => constructor\n         | [ |- _ /\\ _ -> _  ] => intro\n         | [ H : _ /\\ _ |- _ ] => destruct H\n         | [ |- nat -> _     ] => intro\n         | _ => rewrite_hyp || eauto || jauto\n         end.\n\nLtac crush :=\n  repeat (crush_generic; match goal with\n                         | [ |- update _ _ _ _ = _ ] => crush_map\n                         | [ |- init_Gamma _ = _ ] => unfold init_Gamma\n                         | [ |- init_Psi _ = _ ] => unfold init_Psi\n                         | [ |- ieval _ _ ] => constructor; auto\n                         | [ |- ihas_type _ _ _] => constructor; auto\n                         | [ |- ?T -> False  ]  => assert T\n                         | _ => try subst; trivial\n                         end).\n    \n\n\nExample heap_2_type : forall I (R : registers), (init_heap (Id 2)) = Some I -> iseq_has_type (PsiCtx init_Psi) I (code init_Gamma).\nProof.\n  intros.\n  unfold init_heap in H.\n  rewrite update_neq in H.\n  rewrite update_eq in H.\n  symmetry in H.\n  inversion H.\n  apply S_Seq with (Γ2 := init_Gamma).\n  crush.\n  constructor; auto.\n  apply S_Lab with (l := 3) (R := R).\n  crush.\n  trivial.\n  apply S_Seq with (Γ2 := init_Gamma).\n  constructor; auto.\n  crush.\n  apply update_same.\n  crush.\n  apply S_Seq with (Γ2 := init_Gamma).\n  unfold init_Psi.\n  apply S_Sub with (a := ANum 1).\n  unfold init_Psi.\n  constructor; auto.\n  constructor; auto.\n  constructor; auto.\n  constructor; auto.\n  constructor; auto.\n  apply S_Lab with (l := 2) (R := R).\n  crush.\n  trivial.\n  trivial.\n  rewrite <- beq_id_false_iff.\n  trivial.\nQed.\n                   \n(** Typing rule for register file *)\nInductive Rhas_type : cmbnd_ctx -> registers -> context -> Prop :=\n| S_Regfile : forall Ψ Γ R r tau a,\n    (Γ (Id r)) = Some tau -> aeval a R = R (Id r) -> ahas_type (PsiGammaCtx Ψ Γ) a tau -> Rhas_type (PsiCtx Ψ) R Γ.\n\nHint Constructors Rhas_type.\n\n(** Typing rule for Heap *)\nInductive Hhas_type : cmbnd_ctx -> heaps -> context -> Prop :=\n| S_Heap : forall Ψ H,\n    (forall l tau, exists is, Ψ (Id l) = Some tau /\\ H (Id l) = Some is /\\ iseq_has_type (PsiCtx Ψ) is tau) -> Hhas_type EmptyCtx H Ψ.\n\nHint Constructors Hhas_type.\n\n(** Typing rule for a valid Machine State *)\nInductive M_ok : cmbnd_ctx -> heaps -> registers -> instr_seq -> Prop :=\n| S_Mach : forall H R Is Ψ Γ,\n    Hhas_type EmptyCtx H Ψ -> Rhas_type (PsiCtx Ψ) R Γ -> iseq_has_type (PsiCtx Ψ) Is (code Γ) -> M_ok EmptyCtx H R Is.\n\nHint Constructors M_ok.\n\n(** We will require some Canonical Values Lemmas in our proof of Soundness *)\nLemma Canonical_Values_Int : forall H Ψ Γ v tau,\n    Hhas_type EmptyCtx H Ψ -> ahas_type (PsiGammaCtx Ψ Γ) v tau -> tau = int -> exists n, v = ANum n.\nProof.\n  intros.\n  subst.\n  inversion H1.\n  inversion H6.\n  exists n.\n  crush.\nQed.\n\n\nLemma Canonical_Values_Reg :forall H Ψ Γ r R,\n    Hhas_type EmptyCtx H Ψ -> Rhas_type (PsiCtx Ψ) R Γ -> ahas_type (PsiGammaCtx Ψ Γ) (AReg r) (reg int) -> exists (n : nat), R (Id r) = n.\nProof.\n  intros.\n  exists (R (Id r)).\n  crush.\nQed.\n\nLemma Canonical_Values_label1 : forall H Ψ Γ v,\n    Hhas_type EmptyCtx H Ψ -> ahas_type (PsiGammaCtx Ψ Γ) (ALab v) (code Γ) ->  Ψ (Id v) = Some (code Γ) -> exists is, H (Id v) = Some is /\\ iseq_has_type (PsiCtx Ψ) is (code Γ).\nProof.\n  intros.\n  inversion H0.\n  inversion H1.\n  inversion H7.\n  simpl in H5.\n  specialize H4 with ( l := v) (tau := code Γ).\n  destruct H4 as [i G].\n  exists i.\n  crush.\nQed.\n\nLemma Canonical_Values_label2 : forall H Ψ Γ R r,\n    Hhas_type EmptyCtx H Ψ -> ahas_type (PsiGammaCtx Ψ Γ) (AReg r) True -> exists is, H (Id (R (Id r))) = Some is /\\ iseq_has_type (PsiCtx Ψ) is (code Γ).\nProof.\n  intros.\n  inversion H0.\n  inversion H1.\n  specialize H3 with ( l := R (Id r)) (tau := (code Γ)).\n  destruct H3 as [i G].\n  exists i.\n  apply G.\n  specialize H3 with ( l := R (Id r)) (tau := (code Γ)).\n  destruct H3 as [i G].\n  exists i.\n  crush.\n Qed.\n\n(** Finally the proof of Soundness *)\nTheorem Soundness : forall H R Is,\n    M_ok EmptyCtx H R Is -> exists H' R' Is', ieval (St H R Is) (St H' R' Is') /\\ M_ok EmptyCtx H' R' Is'.\nProof.\n  intros.\n  inversion H0 ; induction Is; inverts H4.\n  induction i; inversion H12;\n   try match goal with\n    | [H : Γ = Γ2 |- _ ] => symmetry in H\n    end;\n    try subst.\n\n\n  (* ISeq IMov I *)\n  exists H (t_update R (Id d) (aeval a R1)) Is.\n  crush.\n  apply S_Mach with (Ψ := Ψ) (Γ := Γ).\n  crush.\n  apply S_Regfile with (r := d) (tau := reg tau) (a := AReg d).\n  rewrite <- H16.\n  rewrite update_eq.\n  crush.\n  crush.\n  crush.\n  crush.\n  \n  (* ISeq IAdd I *)\n  exists H (t_update R (Id d) (aeval (AReg d) R + aeval (AReg s) R)) Is.\n  split.\n  crush.\n  apply S_Mach with (Ψ := Ψ) (Γ := Γ).\n  crush.\n  apply S_Regfile with (a := AReg d) (r := d) (tau := reg int).\n  rewrite <- H16; apply update_eq.\n  crush.\n  crush.\n  crush.\n  \n  (* ISeq ISub I *)\n  exists H (t_update R (Id d) (aeval (AReg d) R - aeval (ANum v) R)) Is.\n  split.\n  crush.\n  apply S_Mach with (Ψ := Ψ) (Γ := Γ).\n  crush.\n  apply S_Regfile with (a := AReg d) (r := d) (tau := reg int).\n  inversion H15.\n  crush.\n  crush.\n  inversion H15.\n  crush.\n  inversion H7.\n  trivial.\n  crush.\n  crush.\n  \n  (* ISeq IIf I *)\n  inversion H12.\n  inversion H9.\n  inversion H18.\n  subst.\n  simpl in H22.\n  \n  remember (R (Id d)) as rd; destruct rd.\n  pose proof Canonical_Values_label1 H Ψ Γ v0 H2 H9 H22 as CVL1.\n  destruct CVL1 as [Is' G].\n  exists H R Is'.\n  crush.\n\n  exists H R Is.\n  \n  split.\n  apply R_IIf_NEQ.\n  simpl.\n  symmetry in Heqrd; rewrite Heqrd.\n  apply beq_nat_false_iff.\n  trivial.\n  crush.\n  \n  (*IJmp*)\n  inversion H11; inversion H12.\n  simpl in H17.\n  subst.\n  pose proof Canonical_Values_label1 H Ψ Γ v0 H2 H11 H16 as CVL1.\n  destruct CVL1 as [Is G].\n\n  exists H R Is.\n  crush.\n  apply R_IJmp_Succ with (a := ALab v0).\n  crush.\n  crush.\n  \n  (*IJmpT*)\n  pose proof Canonical_Values_label2 H Ψ Γ R v0 H2 H11 as CVL3.\n  destruct CVL3 as [Is G].\n\n  exists H R Is.\n  crush.\nQed.\n", "meta": {"author": "ankitku", "repo": "TAL0", "sha": "54f3af321c1b657b98e8e5704aa771fa22c1713c", "save_path": "github-repos/coq/ankitku-TAL0", "path": "github-repos/coq/ankitku-TAL0/TAL0-54f3af321c1b657b98e8e5704aa771fa22c1713c/TAL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.674692435991174}}
{"text": "(* Steve Awodey's book on category theory *)\n(******************************************************************************)\n(* Chapter 1.3: Categories                                                    *)\n(******************************************************************************)\n(* @suharahiromichi *)\n\n(*\n(1) ベースライン\nhttp://www.megacz.com/berkeley/coq-categories/\nこれをもとに改変。Instance ... Proper を使うようにした。\n *)\n\n(*\n(2) Proper関数の定義\nA Gentle Introduction to Type Classes and Relations in Coq\n*)\n\n(*\n(3) Setoid を使うようにし、Setsと(P,<=)のインスタンスをつくる。\nhttp://www.iij-ii.co.jp/lab/techdoc/category/category1.html\n *)\n\n(* \nできるだけ Generalizable を使う。\n *)\n\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import finset fintype.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import Notations.\nRequire Import Morphisms.\nRequire Import Coq.Setoids.Setoid.\n\n(*\nReserved Notation \"x ~> y\" (at level 51, left associativity).\n*)\nReserved Notation \"x \\\\o y\" (at level 51, left associativity).\nReserved Notation \"x === y\" (at level 71, left associativity).\n\nGeneralizable Variables a b c d e x.\nGeneralizable Variables Obj.\n\n(* Calss Setoid (carrier : Type) とするのは難しい。なぜ？ *)\nClass Setoid : Type :=\n  {\n    carrier : Type;\n    eqv : carrier -> carrier -> Prop;\n    eqv_equivalence : Equivalence eqv\n  }.\nCoercion carrier : Setoid >-> Sortclass.\nNotation \"x === y\" := (eqv x y).\n\nClass Category `(Hom : Obj -> Obj -> Setoid) : Type :=\n  {\n    hom := Hom where \"a ~> b\" := (hom a b);\n    obj := Obj;\n    id   : forall {a : Obj}, (a ~> a);\n    comp : forall {a b c : Obj},\n             (b ~> c) -> (a ~> b) -> (a ~> c)\n                                       where \"f \\\\o g\" := (comp f g);\n    comp_respects   : forall {a b c : Obj},\n                        Proper (eqv ==> eqv ==> eqv) (@comp a b c);\n    left_identity   : forall `{f : a ~> b}, id \\\\o f === f;\n    right_identity  : forall `{f : a ~> b}, f \\\\o id === f;\n    associativity   : forall `{f : c ~> d} `{g : b ~> c} `{h : a ~> b},\n                        f \\\\o g \\\\o h === f \\\\o (g \\\\o h)\n}.\nCoercion obj : Category >-> Sortclass.\n\nNotation \"a ~> b\"  := (hom a b).\nNotation \"f \\\\o g\" := (comp f g).\n(* Notation \"a ~~{ C }~~> b\" := (@hom _ _ C a b). *)\n\n(* eqv が、Reflexive と Symmetric と Transitive とを満たす。 *)\nInstance category_eqv_Equiv `(C : Category Obj) (a b : Obj) :\n  Equivalence (@eqv (a ~> b)).\nProof.\n  by apply eqv_equivalence.\nQed.\n\n(* comp は eqv について固有関数である。 *)\nInstance category_comp_Proper `(C : Category Obj) (a b c : Obj) :\n  Proper (@eqv (b ~> c) ==> @eqv (a ~> b) ==> @eqv (a ~> c)) comp.\nProof.\n  by apply comp_respects.\nQed.\n\n\n(* 可換性についての定理を証明する。 *)\nLemma juggle1 : forall `{C : Category}\n                       `(f : d ~> e) `(g : c ~> d) `(h : b ~> c) `(k : a ~> b),\n                  f \\\\o g \\\\o h \\\\o k === f \\\\o (g \\\\o h) \\\\o k.\nProof.\n  intros.\n  rewrite <- associativity.\n  reflexivity.\nDefined.\n\nLemma juggle2 : forall `{C : Category}\n                       `(f : d ~> e) `(g : c ~> d) `(h : b ~> c) `(k : a ~> b),\n                  f \\\\o (g \\\\o (h \\\\o k)) === f \\\\o (g \\\\o h) \\\\o k.\nProof.\n  intros.\n  do ! rewrite <- associativity.\n  reflexivity.\nDefined.\n\nLemma juggle3 : forall `{C : Category}\n                       `(f : d ~> e) `(g : c ~> d) `(h : b ~> c) `(k : a ~> b),\n                  f \\\\o g \\\\o (h \\\\o k) === f \\\\o (g \\\\o h) \\\\o k.\nProof.\n  intros.\n  do ! rewrite <- associativity.\n  reflexivity.\nDefined.\n\nReserved Notation \"x &&& y\" (at level 50, left associativity).\n\n(* 直積 *)\nClass Product `{C : Category Obj} (Prod : Obj -> Obj -> Obj) : Type :=\n  {\n    obj' := Obj;\n    proj1 : forall {a b : Obj}, (Prod a b) ~> a;\n    proj2 : forall {a b : Obj}, (Prod a b) ~> b;\n    \n    (* 仲介射 *)\n    mediating : forall {a b x : Obj},\n                  (x ~> a) -> (x ~> b) -> (x ~> (Prod a b))\n                                            where \"f &&& g\" := (mediating f g);\n    \n    med_commute1 : forall `(f : x ~> a) `(g : x ~> b),\n                     proj1 \\\\o (f &&& g) === f;\n    med_commute2 : forall `(f : x ~> a) `(g : x ~> b),\n                     proj2 \\\\o (f &&& g) === g;\n    med_unique : forall `(f : x ~> a) `(g : x ~> b) `(h : x ~> (Prod a b)),\n                   proj1 \\\\o h === f ->\n                   proj2 \\\\o h === g ->\n                   h === (f &&& g)\n  }.\nCoercion obj': Product >-> Sortclass.\nNotation \"x &&& y\" := (mediating x y).\n\nCheck @proj1 : ∀Obj Hom C Prod _ a b, Prod a b ~> a.\nCheck @proj2 : ∀Obj Hom C Prod _ a b, Prod a b ~> b.\n\nSet Printing All.\nGeneralizable Variables Prod.\nDefinition parallel `{C : Category Obj} {Prod : Obj -> Obj -> Obj} {CP : Product Prod}\n           `(f : a ~> b) `(g : c ~> d) : (Prod a c) ~> (Prod b d) :=\n  let p1 := @proj1 Obj Hom C Prod CP a c in\n  let p2 := @proj2 Obj Hom C Prod CP a c in\n  (f \\\\o p1) &&& (g \\\\o p2).\nNotation \"f *** g\" := (parallel f g).      (* <f,g> *)\n\n(* **** *)\n(* Sets *)\n(* **** *)\nInstance EquivExt : forall (A B : Set), Equivalence (@eqfun A B) := (* notu *)\n  {\n    Equivalence_Reflexive := @frefl A B;\n    Equivalence_Symmetric := @fsym A B;\n    Equivalence_Transitive := @ftrans A B\n  }.\n\nInstance EqMor : forall (A B : Set), Setoid :=\n  {\n    carrier := A -> B;\n    eqv := @eqfun B A\n  }.\n  \nCheck @Category Set : (Set → Set → Setoid) → Type.\nCheck @Category Set EqMor : Type.\nCheck EqMor : Set -> Set -> Setoid.\n\nProgram Instance Sets : @Category Set EqMor.\nObligation 3.\nProof.\n  rewrite /Sets_obligation_2.\n  move=> homab homab' Hhomab hombc hombc' Hhombc.\n  move=> x //=.\n  rewrite Hhomab.\n  rewrite Hhombc.\n    by [].\nQed.\n\nCheck prod : (Type → Type → Type).\nCheck @Product Sets EqMor Sets prod.\nCheck Product prod : Type.\n\nProgram Instance SetsProd : @Product Sets EqMor Sets prod :=\n  {\n    proj1 A B := @fst A B;\n    proj2 A B := @snd A B;\n    mediating A B X := fun f g x => (f x, g x)\n  }.\nObligation 3.\nProof.\n  move: H H0.\n  rewrite /Sets_obligation_2 => H1 H2 x'.\n  rewrite -(H1 x').\n  rewrite -(H2 x').\n  by apply surjective_pairing.\nQed.\n\n(* **** *)\n(* P,<= *)\n(* **** *)\nOpen Scope coq_nat_scope.\nSearch \"_ <= _\".\nCheck 0 <= 0 : Prop.\n\nDefinition eq_le m n (p q : m <= n) := True.\n  \nInstance EquivGeq : forall (m n : nat), Equivalence (@eq_le m n). (* notu *)\nProof.\n    by [].\nQed. \n  \nInstance EqLe : forall (m n : nat), Setoid :=\n  {\n    carrier := m <= n;\n    eqv := @eq_le m n\n  }.\n\nCheck @Category nat : (nat → nat → Setoid) → Type.\nCheck EqLe : nat → nat → Setoid.\nCheck @Category nat EqLe.\n\nProgram Instance P_LE : @Category nat EqLe.\nObligation 2.\nProof.\n    by apply (@Le.le_trans a b c).\nDefined.\nObligation 3.\nProof.\n  rewrite /P_LE_obligation_1.\n  rewrite /P_LE_obligation_2.\n  move=> homab homab' Hhomab hombc hombc' Hhombc.\n  by rewrite /eq_le.\nDefined.\nObligation 4.\nProof.\n  rewrite /P_LE_obligation_1.\n  rewrite /P_LE_obligation_2.\n  by rewrite /eq_le.\nDefined.\nObligation 5.\nProof.\n  rewrite /P_LE_obligation_1.\n  rewrite /P_LE_obligation_2.\n  by rewrite /eq_le.\nDefined.\nObligation 6.\nProof.\n  rewrite /P_LE_obligation_2.\n  by rewrite /eq_le.\nDefined.\n\nCheck P_LE.\n\nCheck min : nat -> nat -> nat.\nCheck @Product P_LE EqLe P_LE min.\n\nProgram Instance P_LE_Prod : @Product P_LE EqLe P_LE min.\nObligation 1.\nProof.\n  Search (min _ _ <= _).\n  by apply Min.le_min_l.\nDefined.\nObligation 2.\n  by apply Min.le_min_r.\nDefined.\nObligation 3.\nProof.\n  Search (_ <= min _ _).\n  by apply Min.min_glb.\nDefined.\nObligation 4.\n  rewrite /P_LE_obligation_1.\n  rewrite /P_LE_obligation_2.\n  rewrite /P_LE_obligation_3.\n  by rewrite /eq_le.\nDefined.\nObligation 5.\n  rewrite /P_LE_obligation_1.\n  rewrite /P_LE_obligation_2.\n  rewrite /P_LE_obligation_3.\n  by rewrite /eq_le.\nDefined.\n\nCheck P_LE_Prod.\n\n(* an application of parallel (***) *)\nCheck @parallel.\nLemma parallel_min : forall (m n p q : nat),\n      m <= n -> p <= q -> min m p <= min n q.\nProof.\n  move=> m n p q Hmn Hpq.\n  Check @parallel nat EqLe P_LE min P_LE_Prod m n Hmn p q Hpq.\n    by apply: (@parallel nat EqLe P_LE min P_LE_Prod m n Hmn p q Hpq).\n    Undo 1.\n  Check Hmn *** Hpq.\n    by apply: (Hmn *** Hpq).\nQed.\nPrint parallel_min.\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/monad/Categories_4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6746924175508744}}
{"text": "(*|\n##########################\nProving a property on sets\n##########################\n\n:Link: https://stackoverflow.com/q/52448832\n|*)\n\n(*|\nQuestion\n********\n\nAs a Coq programming experience and following my question in `here\n<https://stackoverflow.com/q/52195198/9335627>`__, I'd like to know if\nthere is another proof, possibly shorter and without using Lemma\n``subset_listpair_conserve``, for proving Lemma\n``subset_listpair_consFalse``. I proved it but it is long and uses\nLemma ``subset_listpair_consve``.\n|*)\n\nRequire Import List.\nRequire Import Bool.\n\nDefinition entity := nat.\nDefinition entityID := nat.\nDefinition listPair : Set := list (entity * entityID).\n\n(* check if e is in list l *)\nFixpoint in_listpair e (l : listPair) :=\n  match l with\n  | nil          => false\n  | (x, y) :: l' => Nat.eqb e x || in_listpair e l'\n  end.\n\n(* check if list l1 is in list l2: i.e., 11 entities are in l2 *)\nFixpoint subset_listpair (l1 l2 : listPair) :=\n  match l1 with\n  | nil => true\n  | (x1, _) :: l1 => in_listpair x1 l2 && subset_listpair l1 l2\n  end.\n\nLemma subset_listpair_consver l1 l2 l3 e :\n  in_listpair e l2 = true ->\n  in_listpair e l3 = false ->\n  subset_listpair l1 l2 = true ->\n  subset_listpair l1 l3 = false.\nProof.\nAdmitted.\n\nLemma subset_listpair_consFalse l1 l2 l3 :\n  subset_listpair l1 l2 = true ->\n  subset_listpair l1 l3 = false -> subset_listpair l2 l3 = false.\nProof.\n  induction l1.\n  - induction l3.\n    + destruct l2.\n      * simpl. intros. inversion H0.\n      * intros. destruct p. simpl in *. reflexivity.\n    + simpl in *. intros. intuition. inversion H0.\n  - intros. rewrite IHl1.\n    + reflexivity.\n    + simpl in H0. destruct a. simpl in H.\n      rewrite andb_true_iff in H. rewrite andb_false_iff in H0.\n      elim H. intros. assumption.\n    + simpl in H0. destruct a. simpl in H.\n      rewrite andb_true_iff in H. rewrite andb_false_iff in H0.\n      elim H. intros.\n      * elim H0.\n        -- intros. pose proof subset_listpair_consver as H10.\n           assert (subset_listpair l1 l3 = false) as H11.\n           ++ rewrite H10 with (l2 := l2) (e := e).\n              ** reflexivity.\n              ** assumption.\n              ** assumption.\n              ** assumption.\n           ++ assumption.\n        -- intro. assumption.\nQed.\n\n(*|\nAnswer\n******\n\nHere is one possible solution. I didn't go for a lemma-less proof or\nfor the shortest proof. Instead, I tried to break down everything into\na bite-sized chunks that are (relatively) easy to manipulate.\n\nFirst, here is an auxiliary lemma missing from the standard library.\nIt simply states the law of contraposition in classical logic (we have\ndecidable propositions here, so those are kind of classical).\n|*)\n\nReset subset_listpair_consFalse. (* .none *)\nFrom Coq Require Import Arith Bool List.\n\nLemma contra b1 b2 :\n  (b2 = false -> b1 = false) <-> (b1 = true -> b2 = true).\nProof. destruct b1, b2; intuition. Qed.\n\n(*| Now, we will need the following easy property: |*)\n\nLemma in_subset_listpair {p l1 l2} :\n  in_listpair p l1 = true ->\n  subset_listpair l1 l2 = true ->\n  in_listpair p l2 = true.\nProof.\n  induction l1 as [| [x1 y1] l1 IH]; simpl; [easy |].\n  rewrite orb_true_iff, andb_true_iff. intros [->%Nat.eqb_eq |] []; trivial.\n  now apply IH.\nQed.\n\n(*| Next, we prove that ``subset`` is transitive: |*)\n\nLemma subset_listpair_transitive l2 l1 l3 :\n  subset_listpair l1 l2 = true ->\n  subset_listpair l2 l3 = true ->\n  subset_listpair l1 l3 = true.\nProof.\n  induction l1 as [| [x1 y1] l1 IH]; simpl; trivial.\n  intros [I1 S1]%andb_prop S2. rewrite (IH S1 S2), andb_true_r.\n  now apply (in_subset_listpair I1).\nQed.\n\n(*|\nAnd now, the target lemma, which is basically a contrapositive\nstatement of the transitivity property:\n|*)\n\nLemma subset_listpair_consFalse l1 l2 l3 :\n  subset_listpair l1 l2 = true ->\n  subset_listpair l1 l3 = false ->\n  subset_listpair l2 l3 = false.\nProof.\n  intros S12. rewrite contra.\n  now apply subset_listpair_transitive.\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/proving-a-property-on-sets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.6746924140172259}}
{"text": "(* Software Foundations *)\n(* Exercice 3 stars, filter_exercise *)\n\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nFixpoint filter{X: Type}(f: X -> bool)(l: list X):=\nmatch l with\n|[]   => []\n|h::t => if (f h) then h::(filter f t) else (filter f t)\nend.\n\nTheorem filter_exercise : forall (X : Type)(test : X -> bool)(x : X)(l lf : list X),\nfilter test l = x :: lf -> test x = true.\nProof.\n    intros. generalize dependent l. induction l as [|h t].\n    simpl. intros. inversion H.\n    intros. simpl in H. destruct (test h) eqn: th.\n    inversion H. rewrite H1 in th. apply th.\n    apply IHt in H. apply H.\nQed.\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter7_Library_MoreCoq/filter_exercise.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6746924074266036}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\nFrom compcert Require Import Raux.\nFrom compcert Require Import Defs.\nFrom compcert Require Import Digits.\nFrom compcert Require Import Generic_fmt.\nFrom compcert Require Import Float_prop.\nFrom compcert Require Import Bracket.\n\nSet Implicit Arguments.\nSet Strongly Strict Implicit.\n\nSection Fcalc_sqrt.\n\nVariable beta : radix.\nNotation bpow e := (bpow beta e).\n\nVariable fexp : Z -> Z.\n\n\n\nLemma mag_sqrt_F2R :\nforall m1 e1,\n(0 < m1)%Z ->\nmag beta (sqrt (F2R (Float beta m1 e1))) = Z.div2 (Zdigits beta m1 + e1 + 1) :> Z.\nProof. hammer_hook \"Sqrt\" \"Sqrt.mag_sqrt_F2R\".\nintros m1 e1 Hm1.\nrewrite <- (mag_F2R_Zdigits beta m1 e1) by now apply Zgt_not_eq.\napply mag_sqrt.\nnow apply F2R_gt_0.\nQed.\n\nDefinition Fsqrt_core m1 e1 e :=\nlet d1 := Zdigits beta m1 in\nlet m1' := (m1 * Zpower beta (e1 - 2 * e))%Z in\nlet (q, r) := Z.sqrtrem m1' in\nlet l :=\nif Zeq_bool r 0 then loc_Exact\nelse loc_Inexact (if Zle_bool r q then Lt else Gt) in\n(q, l).\n\nTheorem Fsqrt_core_correct :\nforall m1 e1 e,\n(0 < m1)%Z ->\n(2 * e <= e1)%Z ->\nlet '(m, l) := Fsqrt_core m1 e1 e in\ninbetween_float beta m e (sqrt (F2R (Float beta m1 e1))) l.\nProof. hammer_hook \"Sqrt\" \"Sqrt.Fsqrt_core_correct\".\nintros m1 e1 e Hm1 He.\nunfold Fsqrt_core.\nset (m' := Zmult _ _).\nassert (0 <= m')%Z as Hm'.\n{ apply Z.mul_nonneg_nonneg.\nnow apply Zlt_le_weak.\napply Zpower_ge_0. }\nassert (sqrt (F2R (Float beta m1 e1)) = sqrt (IZR m') * bpow e)%R as Hf.\n{ rewrite <- (sqrt_Rsqr (bpow e)) by apply bpow_ge_0.\nrewrite <- sqrt_mult.\nunfold Rsqr, m'.\nrewrite mult_IZR, IZR_Zpower by omega.\nrewrite Rmult_assoc, <- 2!bpow_plus.\nnow replace (_ + _)%Z with e1 by ring.\nnow apply IZR_le.\napply Rle_0_sqr. }\ngeneralize (Z.sqrtrem_spec m' Hm').\ndestruct Z.sqrtrem as [q r].\nintros [Hq Hr].\nrewrite Hf.\nunfold inbetween_float, F2R. simpl Fnum.\napply inbetween_mult_compat.\napply bpow_gt_0.\nrewrite Hq.\ncase Zeq_bool_spec ; intros Hr'.\n\nrewrite Hr', Zplus_0_r, mult_IZR.\nfold (Rsqr (IZR q)).\nrewrite sqrt_Rsqr.\nnow constructor.\napply IZR_le.\nclear -Hr ; omega.\n\nconstructor.\nsplit.\n\napply Rle_lt_trans with (sqrt (IZR (q * q))).\nrewrite mult_IZR.\nfold (Rsqr (IZR q)).\nrewrite sqrt_Rsqr.\napply Rle_refl.\napply IZR_le.\nclear -Hr ; omega.\napply sqrt_lt_1.\nrewrite mult_IZR.\napply Rle_0_sqr.\nrewrite <- Hq.\nnow apply IZR_le.\napply IZR_lt.\nomega.\napply Rlt_le_trans with (sqrt (IZR ((q + 1) * (q + 1)))).\napply sqrt_lt_1.\nrewrite <- Hq.\nnow apply IZR_le.\nrewrite mult_IZR.\napply Rle_0_sqr.\napply IZR_lt.\nring_simplify.\nomega.\nrewrite mult_IZR.\nfold (Rsqr (IZR (q + 1))).\nrewrite sqrt_Rsqr.\napply Rle_refl.\napply IZR_le.\nclear -Hr ; omega.\n\nrewrite Rcompare_half_r.\ngeneralize (Rcompare_sqr (2 * sqrt (IZR (q * q + r))) (IZR q + IZR (q + 1))).\nrewrite 2!Rabs_pos_eq.\nintros <-.\nreplace ((2 * sqrt (IZR (q * q + r))) * (2 * sqrt (IZR (q * q + r))))%R\nwith (4 * Rsqr (sqrt (IZR (q * q + r))))%R by (unfold Rsqr ; ring).\nrewrite Rsqr_sqrt.\nrewrite <- plus_IZR, <- 2!mult_IZR.\nrewrite Rcompare_IZR.\nreplace ((q + (q + 1)) * (q + (q + 1)))%Z with (4 * (q * q) + 4 * q + 1)%Z by ring.\ngeneralize (Zle_cases r q).\ncase (Zle_bool r q) ; intros Hr''.\nchange (4 * (q * q + r) < 4 * (q * q) + 4 * q + 1)%Z.\nomega.\nchange (4 * (q * q + r) > 4 * (q * q) + 4 * q + 1)%Z.\nomega.\nrewrite <- Hq.\nnow apply IZR_le.\nrewrite <- plus_IZR.\napply IZR_le.\nclear -Hr ; omega.\napply Rmult_le_pos.\nnow apply IZR_le.\napply sqrt_ge_0.\nQed.\n\nDefinition Fsqrt (x : float beta) :=\nlet (m1, e1) := x in\nlet e' := (Zdigits beta m1 + e1 + 1)%Z in\nlet e := Z.min (fexp (Z.div2 e')) (Z.div2 e1) in\nlet '(m, l) := Fsqrt_core m1 e1 e in\n(m, e, l).\n\nTheorem Fsqrt_correct :\nforall x,\n(0 < F2R x)%R ->\nlet '(m, e, l) := Fsqrt x in\n(e <= cexp beta fexp (sqrt (F2R x)))%Z /\\\ninbetween_float beta m e (sqrt (F2R x)) l.\nProof. hammer_hook \"Sqrt\" \"Sqrt.Fsqrt_correct\".\nintros [m1 e1] Hm1.\napply gt_0_F2R in Hm1.\nunfold Fsqrt.\nset (e := Z.min _ _).\nassert (2 * e <= e1)%Z as He.\n{ assert (e <= Z.div2 e1)%Z by apply Z.le_min_r.\nrewrite (Zdiv2_odd_eqn e1).\ndestruct Z.odd ; omega. }\ngeneralize (Fsqrt_core_correct m1 e1 e Hm1 He).\ndestruct Fsqrt_core as [m l].\napply conj.\napply Z.le_trans with (1 := Z.le_min_l _ _).\nunfold cexp.\nrewrite (mag_sqrt_F2R m1 e1 Hm1).\napply Z.le_refl.\nQed.\n\nEnd Fcalc_sqrt.\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/compcert/Sqrt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.7577943767446201, "lm_q1q2_score": 0.6746599648208523}}
{"text": "Require Import List.\nImport ListNotations.\n\nRequire Import Logic.Class.Eq.\n\nRequire Import Logic.Lam.Syntax.\n\nFixpoint subst_ (v:Type) (e:Eq v) (f:v -> T v) (xs:list v) (t:T v) : T v :=\n    match t with\n    | Var x     =>\n        match in_dec eqDec x xs with\n        | left _    => Var x    (* x is deemed bound    -> Var x                *)\n        | right _   => f x      (* x is deemed free     -> f x                  *)\n        end\n    | App t1 t2 => App (subst_ v e f xs t1) (subst_ v e f xs t2)\n    | Lam x t1  => Lam x (subst_ v e f (x :: xs) t1)        (* x now bound      *)\n    end.\n\nArguments subst_ {v} {e}.\n\nDefinition subst (v:Type) (e:Eq v) (f:v -> T v) (t:T v) : T v :=\n    subst_ f [] t.\n\nArguments subst {v} {e}.\n\nLemma substVar : forall (v:Type) (e:Eq v) (f:v -> T v) (t:T v) (x:v),\n    t = Var x -> subst f t = f x.\nProof. intros v e f t x H. rewrite H. reflexivity. Qed.\n\nLemma substApp : forall (v:Type) (e:Eq v) (f:v -> T v) (t1 t2 t:T v),\n    t = App t1 t2 -> subst f t = App (subst f t1) (subst f t2).\nProof. intros v e f t1 t2 t H. rewrite H. unfold subst. simpl. 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/Logic/Lam/Subst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896132, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6746599515861014}}
{"text": "\nInductive equivalent P Q := Equivalent (P_to_Q : P -> Q) (Q_to_P : Q -> P).\n\nInductive equal T (x : T) : T -> Type := Equal : equal T x x.\n\n(* Arithmetic *)\n\nInductive natural := Zero | Add_1_to (n : natural).\n\nFixpoint add (m n : natural) : natural :=\n  match m with Zero => n | Add_1_to m_minus_1 => add m_minus_1 (Add_1_to n) end.\n\nDefinition double (n : natural) : natural := add n n.\n\nInductive odd (n : natural) :=\n  Odd (half : natural)\n    (n_odd : equal natural n (Add_1_to (double half))).\n\nInductive less_than (m n : natural) :=\n  LessThan (diff : natural)\n    (m_lt_n : equal natural n (Add_1_to (add m diff))).\n\n(* Finite subsets *)\n\nDefinition injective_in T R (D : T -> Type) (f : T -> R) :=\n  forall x y, D x -> D y -> equal R (f x) (f y) -> equal T x y.\n\nInductive in_image T R (D : T -> Type) (f : T -> R) (a : R) :=\n  InImage (x : T) (x_in_D : D x) (a_is_fx : equal R a (f x)).\n\nInductive finite_of_order T (D : T -> Type) (n : natural) :=\n  FiniteOfOrder (rank : T -> natural)\n    (rank_injective : injective_in T natural D rank)\n    (rank_onto :\n       forall i, equivalent (less_than i n) (in_image T natural D rank i)).\n\n(* Constraints *)\nUniverses i j.\nInductive constraint1 : (Type -> Type) -> Type := mk_constraint1 : constraint1 (fun x : Type@{i} => (x : Type@{j})).\nConstraint i < j.\nInductive constraint2 : Type@{j} := mkc2 (_ : Type@{i}).\nUniverses i' j'.\nConstraint i' = j'.\nInductive constraint3 : (Type -> Type) -> Type := mk_constraint3 : constraint3 (fun x : Type@{i'} => (x : Type@{j'})).\nInductive constraint4 : (Type -> Type) -> Type\n  := mk_constraint4 : let U1 := Type in\n                      let U2 := Type in\n                      constraint4 (fun x : U1 => (x : U2)).\n\nModule CMP_CON.\n  (* Comparison of opaque constants MUST be up to the universe graph.\n     See #6798. *)\n  Universe big.\n\n  Polymorphic Lemma foo@{u} : Type@{big}.\n  Proof. exact Type@{u}. Qed.\n\n  Universes U V.\n\n  Definition yo : foo@{U} = foo@{V} := eq_refl.\nEnd CMP_CON.\n\nSet Universe Polymorphism.\n\nModule POLY_SUBTYP.\n\n  Module Type T.\n    Axiom foo : Type.\n    Parameter bar@{u v|u = v} : foo@{u}.\n  End T.\n\n  Module M.\n    Axiom foo : Type.\n    Axiom bar@{u v|u = v} : foo@{v}.\n  End M.\n\n  Module F (A:T). End F.\n\n  Module X := F M.\n\nEnd POLY_SUBTYP.\n\nModule POLY_IND.\n\n  Polymorphic Inductive ind@{u v | u < v} : Prop := .\n\n  Polymorphic Definition cst@{u v | v < u} := Prop.\n\nEnd POLY_IND.\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/coqchk/univ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6746599484636944}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_rayimpliescollinear.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_ray2.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_collinearitypreserved.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_raystrict.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_equalanglessymmetric : \n   forall A B C a b c, \n   CongA A B C a b c ->\n   CongA a b c A B C.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists U V u v, (Out B A U /\\ Out B C V /\\ Out b a u /\\ Out b c v /\\ Cong B U b u /\\ Cong B V b v /\\ Cong U V u v /\\ nCol A B C)) by (conclude_def CongA );destruct Tf as [U[V[u[v]]]];spliter.\nassert (Cong b u B U) by (conclude lemma_congruencesymmetric).\nassert (Cong b v B V) by (conclude lemma_congruencesymmetric).\nassert (Cong v u V U) by (forward_using lemma_doublereverse).\nassert (~ Col a b c).\n {\n intro.\n assert (Col b a u) by (conclude lemma_rayimpliescollinear).\n assert (Col b c v) by (conclude lemma_rayimpliescollinear).\n assert (Col B A U) by (conclude lemma_rayimpliescollinear).\n assert (Col B C V) by (conclude lemma_rayimpliescollinear).\n assert (Col a b u) by (forward_using lemma_collinearorder).\n assert (neq b a) by (conclude lemma_ray2).\n assert (neq a b) by (conclude lemma_inequalitysymmetric).\n assert (Col b u c) by (conclude lemma_collinear4).\n assert (Col c b u) by (forward_using lemma_collinearorder).\n assert (Col c b v) by (forward_using lemma_collinearorder).\n assert (neq b c) by (conclude lemma_ray2).\n assert (neq c b) by (conclude lemma_inequalitysymmetric).\n assert (Col b u v) by (conclude lemma_collinear4).\n assert (Cong u v U V) by (conclude lemma_congruencesymmetric).\n assert (Col B U V) by (conclude lemma_collinearitypreserved).\n assert (Col U B V) by (forward_using lemma_collinearorder).\n assert (Col U B A) by (forward_using lemma_collinearorder).\n assert (neq B U) by (conclude lemma_raystrict).\n assert (neq U B) by (conclude lemma_inequalitysymmetric).\n assert (Col B V A) by (conclude lemma_collinear4).\n assert (Col V B A) by (forward_using lemma_collinearorder).\n assert (Col V B C) by (forward_using lemma_collinearorder).\n assert (neq B V) by (conclude lemma_raystrict).\n assert (neq V B) by (conclude lemma_inequalitysymmetric).\n assert (Col B A C) by (conclude lemma_collinear4).\n assert (Col A B C) by (forward_using lemma_collinearorder).\n contradict.\n }\nassert (Cong u v U V) by (conclude lemma_congruencesymmetric).\nassert (CongA a b c A B C) by (conclude_def CongA ).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_equalanglessymmetric.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6746508351585103}}
{"text": "Require Import Arith.\nRequire Import List. \n\nRequire Import Omega.\n\nLtac numerical :=\n  let XP := fresh \"XP\" in\n    let XW := fresh \"XW\" in\n  match goal with \n    | H : False |- _ => inversion H\n    | _ : _ |- context [ eq_nat_dec ?x ?y ] => \n      case_eq (eq_nat_dec x y) ; intros XP XW ; \n        try (rewrite XW in *) ; clear XW ; simpl in * ; numerical\n    | _ : _ |- context [ le_lt_dec ?x ?y ] => \n      case_eq (le_lt_dec x y) ; intros XP XW ; \n        try (rewrite XW in *) ; clear XW ; simpl in * ; numerical\n    | H : context [ eq_nat_dec ?x ?y ] |- _ => \n      case_eq (eq_nat_dec x y) ; intros XP XW ; \n        rewrite XW in * ; clear XW ; simpl in * ; numerical\n    | H : context [ le_lt_dec ?x ?y ] |- _ => \n      case_eq (le_lt_dec x y) ; intros XP XW ; \n            rewrite XW in * ; clear XW ; simpl in * ; numerical\n    | _ : _ |- ?x = ?y => auto ; try (elimtype False ; simpl in * ; firstorder ; fail)\n    | _ : _ |- context [ False_rec ?x ?y ] => elimtype False\n(*  | _ : _ |- context [ False_rec ?x ?y ] => elimtype False ; simpl in * ; omega\n    | _ : _ |- ?x = ?y => elimtype False ; simpl in * ; omega *)\n    | _ : _ |- False => firstorder\n    | _ : _ |- _ => auto\n  end.\n\n(*\nRequire Import Peano.\nRequire Import Peano_dec.\n*) \n\nInductive Ty : Set := \n| TV : nat -> Ty\n| Imp : Ty -> Ty -> Ty \n| All : Ty -> Ty.\n\nLemma ty_eq_dec : forall (ty1 ty2 : Ty), {ty1 = ty2} + {ty1 <> ty2}.\nProof. \n  decide equality. decide equality.\nDefined.\n\nInductive Term : Set := \n| F : nat -> Term\n| V : nat -> Term \n| App : Term -> Term -> Term \n| TApp : Term -> Ty -> Term\n| Abs : Ty -> Term -> Term\n| Lam : Term -> Term.\n\nDefinition Zero := (All (TV 0)).\nDefinition One := (Imp Zero Zero).\nDefinition Unit := Abs Zero (V 0).\n\nDefinition FCtx := nat -> Ty.  \n\nInductive Ctx : Set := \n| ctx : FCtx -> nat -> list Ty -> Ctx.\n\nInductive Holds : Set := \n| H : Ctx -> Term -> Ty -> Holds. \n\nNotation \"[ d ; n ; l  |= t @ ty ]\" := (H (ctx d n l) t ty) (at level 0).\nOpen Scope list_scope.\n\nFixpoint tyshiftn (n : nat) (d : nat) (ty : Ty) {struct ty} : Ty := \n  match ty with \n    | TV m => if le_lt_dec d m then TV (n+m) else TV m\n    | Imp t s => Imp (tyshiftn n d t) (tyshiftn n d s) \n    | All t => All (tyshiftn n (S d) t) \n  end.\n\nDefinition tyshift := tyshiftn 1 0.\n\nDefinition tysub : forall (ty : Ty) (n : nat) (s : Ty), Ty.  \nProof.\n  refine \n    (fix tysub (ty : Ty) (n : nat) (s : Ty) {struct ty} : Ty := \n      match ty with \n        | TV m => match le_lt_dec n m with \n                    | left p => match eq_nat_dec n m with\n                                  | left _ => s \n                                  | right p' => \n                                    (match m as m' return (m = m' -> Ty) with \n                                      | 0 => (fun p'' => False_rec _ _)\n                                      | S m' => (fun _ => TV m')\n                                     end) (refl_equal m)\n                                end\n                    | right _ => TV m\n                  end\n        | Imp ty1 ty2 => Imp (tysub ty1 n s) (tysub ty2 n s) \n        | All t => All (tysub t (S n) (tyshift s))\n      end).\n  destruct m. apply le_n_O_eq in p. apply p'. auto. inversion p''.\nDefined.\n\nFixpoint tysubt (t : Term) (n : nat) (s : Ty) {struct t} : Term := \n  match t with \n    | F m => F m\n    | V m => V m\n    | Abs ty t => Abs (tysub ty n s) (tysubt t n s)\n    | Lam t => Lam (tysubt t (S n) (tyshift s))\n    | App f g => App (tysubt f n s) (tysubt g n s)\n    | TApp f ty => TApp (tysubt f n s) (tysub ty n s)\n  end.\n\nEval compute in tysubt (tysubt (Lam (TApp (V 0) (TV 2))) 0 (TV 0)) 0 (TV 3). \n\nFixpoint valid (ty : Ty) (n : nat) {struct ty} : Prop := \n  match ty with \n    | TV m => \n      if le_lt_dec n m\n        then False\n        else True\n    | Imp s t => valid s n /\\ valid t n\n    | All t => valid t (S n)\n  end.\n\nDefinition valid_dec : forall (ty : Ty) (n : nat), {valid ty n}+{~ valid ty n}.\nProof. \n  induction ty ; intros. \n  (* TV *)\n  case_eq (le_lt_dec n0 n). \n  intros. right. simpl. rewrite H0. auto.\n  intros. left. simpl. rewrite H0. auto.\n  (* Imp *)\n  firstorder.\n  (* All *) \n  firstorder.\nDefined.\n\nLemma valid_weaken : forall ty n m, \n  n <= m -> valid ty n -> valid ty m.\nProof.\n  induction ty ; simpl ; intros. \n  numerical.\n  inversion H1. \n  split. apply IHty1 with (n:=n). auto. auto. auto.  \n  apply IHty2 with (n:=n). auto. auto.\n  apply IHty with (n:=S n). firstorder. auto.\nDefined. \n\nLemma tyshift_level : forall ty1 n m, \n  valid ty1 n -> valid (tyshiftn 1 m ty1) (S n).\nProof.\n  induction ty1 ; simpl ; intros ; numerical.\n  destruct n ; numerical.\n  firstorder.\nQed.\n\nLemma tysub_level : forall ty1 ty2 n, \n  valid ty1 (S n) -> valid ty2 n -> valid (tysub ty1 n ty2) n.\nProof.\n  induction ty1 ; simpl ; intros ; numerical. \n  (* TV *)\n  destruct n ; numerical. \n  firstorder.\n  firstorder. \n\n  apply IHty1. auto. unfold tyshift.\n  apply tyshift_level. auto.\nQed.\n\nLemma tysub_level_gen : forall ty1 ty2 m n, \n  m <= n -> valid ty1 (S n) -> valid ty2 n -> valid (tysub ty1 m ty2) n.\nProof.\n  induction ty1 ; simpl ; intros ; numerical. \n  (* TV *)\n  destruct n ; numerical. \n  firstorder.\n  split. \n  apply IHty1_1 ; auto ; firstorder.\n  apply IHty1_2 ; auto ; firstorder.\n  apply IHty1. firstorder.  auto.  \n  apply tyshift_level. auto.\nQed.\n\nLemma tysub_level_Z : forall ty1 ty2 n, \n  valid ty1 (S n) -> valid ty2 n -> valid (tysub ty1 0 ty2) n.\nProof.\n  intros; apply tysub_level_gen ; firstorder.\nDefined.  \n\n\nInductive Derivation : Holds -> Set := \n| FunIntro : forall d n m l ty, \n  d m = ty -> \n  valid ty 0 ->\n  Derivation [d ; n ; l |= F m @ ty]\n| ImpIntro : forall d n l t ty xty,\n  valid xty n ->\n  Derivation [d ; n ; xty::l |= t @ ty] -> \n  Derivation [d ; n ; l |= (Abs xty t) @ (Imp xty ty)]\n| ImpElim : forall d n l t f ty xty,\n  Derivation [d ; n ; l |= t @ xty] ->\n  Derivation [d ; n ; l |= f @ (Imp xty ty)] -> \n  Derivation [d ; n ; l |= (App f t) @ ty]\n| AllIntro : forall d n l t ty,\n  Derivation [d ; S n ; map tyshift l |= t @ ty] -> \n  Derivation [d ; n ; l |= (Lam t) @ All ty]\n| AllElim : forall d n l t ty xty,\n  valid xty n ->\n  Derivation [d ; n ; l |= t @ All ty] -> \n  Derivation [d ; n ; l |= TApp t xty @ (tysub ty 0 xty)]\n| VarIntro : forall d n l ty i,\n  valid ty n -> i < length l -> nth i l Zero = ty ->\n  Derivation [d ; n ; l |= V i @ ty].\n\nLemma type_valid_at_n : forall t d n l ty, Derivation [d ; n ; l |= t @ ty] -> valid ty n.\nProof.\n  induction t.\n  (* F *) \n  intros ; inversion H0 ; subst. \n  apply valid_weaken with (n:=0). firstorder. auto.\n  (* V *) \n  intros. inversion H0. auto.\n  (* App *) \n  intros. inversion H0 ; subst. \n  apply IHt1 in H8. simpl in H8.  inversion H8. auto.  \n  (* TApp *) \n  intros. inversion H0. \n  subst. apply IHt in H8. simpl in *. \n  apply tysub_level_Z. auto. auto. \n  (* Abs *) \n  intros. inversion H0 ; subst.\n  simpl. split ; auto. apply IHt in H8. auto.\n  (* Lam *) \n  intros. inversion H0 ; subst.\n  simpl. apply IHt in H2. auto.\nDefined.   \n\nFixpoint typeof (d : FCtx) (n : nat) (l : list Ty) (t : Term) {struct t} : option Ty := \n  match t with \n    | F m => \n      if valid_dec (d m) 0 \n        then Some (d m)\n        else None\n    | V n' => \n      if le_lt_dec (length l) n' \n        then None \n        else (fun ty => \n          if valid_dec ty n\n            then Some ty \n            else None) (nth n' l Zero)\n    | App r s => \n      (fun mrty msty => \n        match mrty,msty with \n          | Some (Imp xty yty),Some xty' => \n            if ty_eq_dec xty' xty \n              then Some yty\n              else None\n          | _,_ => None\n        end) (typeof d n l r) (typeof d n l s)\n    | TApp r ty => \n      (fun mrty => \n        match mrty with \n          | Some (All ty') =>\n            if valid_dec ty n \n              then if valid_dec ty' (S n) \n                then Some (tysub ty' 0 ty)\n                else None\n              else None\n          | _ => None\n        end) (typeof d n l r)\n    | Abs ty r => \n      (fun mrty => \n        match mrty with \n          | Some ty' => \n            if valid_dec ty n\n              then Some (Imp ty ty')\n              else None\n          | _ => None\n        end) (typeof d n (ty::l) r)\n    | Lam r => \n      (fun mrty => \n        match mrty with \n          | Some ty' =>\n            if valid_dec ty' (S n) \n              then Some (All ty')\n              else None\n          | _ => None\n        end) (typeof d (S n) (map tyshift l) r)\n  end.\n\nRequire Import Sumbool.\n\nTheorem typeof_has_derivation : \n  forall t d n l ty, \n    typeof d n l t = Some ty -> Derivation [d ; n ; l |= t @ ty].\nProof.\n  induction t ; intros.\n  (* F *) \n  simpl in H0. \n  apply FunIntro.\n  case_eq (valid_dec (d n) 0); intros Ple Hle ; try (rewrite Hle in *) ; try congruence.  \n  case_eq (valid_dec (d n) 0); intros Ple Hle ; try (rewrite Hle in *) ; try congruence.\n  \n  (* V *)\n  simpl in H0.\n  case_eq (le_lt_dec (length l) n) ; \n    intros Ple Hle ; try (rewrite Hle in *) ; try congruence.\n  case_eq (valid_dec (nth n l Zero) n0) ; \n    intros Pval Hval ; try (rewrite Hval in *) ; try congruence.\n  apply VarIntro ; auto ; try congruence.\n\n  (* App *)\n  simpl in H0.\n  case_eq (typeof d n l t1) ; intros ; try (rewrite H1 in *) ; try congruence ;\n    destruct t ; try congruence.\n  case_eq (typeof d n l t2) ; intros ; try (rewrite H2 in *) ; try congruence.\n  case_eq (ty_eq_dec t t3) ; intros ; try (rewrite H3 in *) ; try congruence.  \n  inversion H0.  \n  eapply(ImpElim d n l t2 t1 ty t3). \n  apply IHt2. rewrite <- e. auto.\n  apply IHt1. rewrite <- H5. auto. \n  \n  (* TApp *)\n  intros. simpl in H0.\n  case_eq (typeof d n l t). intros. rewrite H1 in H0.\n  destruct t1 ; try congruence. \n  case_eq (valid_dec t0 n) ; intros ; try (rewrite H2 in *) ; try congruence.\n  case_eq (valid_dec t1 (S n)) ; intros ; try (rewrite H3 in *) ; try congruence.\n  inversion H0. subst.\n  apply AllElim. auto. auto.\n  intros. rewrite H1 in H0. inversion H0.   \n  \n  (* Abs *) \n  simpl in H0. case_eq (typeof d n (t::l) t0) ; intros ; try (rewrite H1 in *) ; try congruence. \n  case_eq (valid_dec t n) ; intros ; try (rewrite H2 in *) ; try congruence.\n  inversion H0.\n  eapply ImpIntro. auto. apply IHt. auto.\n\n  (* Lam *)\n  simpl in H0. case_eq (typeof d (S n) (map tyshift l) t) ; intros ; try (rewrite H1 in *) ; try congruence.\n  case_eq (valid_dec t0 (S n)). intros. rewrite H2 in H0. inversion H0.\n  eapply AllIntro. apply IHt in H1. auto.\n  intros. rewrite H2 in H0. inversion H0.\nDefined. \n  \nFixpoint shift (d : nat) (t : Term) {struct t} : Term := \n  match t with \n    | F m => F m\n    | V m => if le_lt_dec d m then V (S m) else V m\n    | App r s => App (shift d r) (shift d s) \n    | Lam r => Lam (shift d r)\n    | Abs ty r => Abs ty (shift (d+1) r)\n    | TApp r ty => TApp (shift d r) ty\n  end.\n\nFixpoint tyshift_term (d : nat) (t : Term) {struct t} : Term := \n  match t with \n    | F m => F m \n    | V m => V m \n    | App r s => App (tyshift_term d r) (tyshift_term d s) \n    | Lam r => Lam (tyshift_term (S d) r)\n    | Abs ty r => Abs (tyshiftn 1 d ty) (tyshift_term d r)\n    | TApp r ty => TApp (tyshift_term d r) (tyshiftn 1 d ty)\n  end.\n\nDefinition sub : forall (t : Term) (n : nat) (s : Term), Term.\nProof. \n  refine \n    (fix sub (t : Term) (n : nat) (s : Term) {struct t} : Term := \n      match t with \n        | F m => F m\n        | V m => match le_lt_dec n m with \n                   | left p => match eq_nat_dec n m with \n                                 | left p' => s\n                                 | right p' => \n                                   (match m as m' return (m = m' -> Term) with \n                                      | 0 => (fun p'' => False_rec _ _)\n                                      | S m' => (fun _ => V m')\n                                    end) (refl_equal m)\n                               end\n                   | right p => V m\n                 end\n        | Abs ty r => Abs ty (sub r (S n) (shift 0 s))\n        | Lam r => Lam (sub r n (tyshift_term 0 s))\n        | App f g => App (sub f n s) (sub g n s) \n        | TApp r ty => TApp (sub r n s) ty\n      end). destruct m. apply le_n_O_eq in p. apply p'. auto. inversion p''.\nDefined.\n\nLemma nth_sameL : forall A a (l:list A) G d i, \n  i < length G -> \n  nth i (G++(a::l)) d = nth i (G++l) d.\nProof.\n  induction G. intros. inversion H0.\n  intros. destruct i.\n  simpl. auto. simpl. apply IHG. simpl in H0.\n  apply lt_S_n. auto.\nDefined.\n \nLemma nth_sameR : forall A i a (l:list A) G d, \n  length G < S i -> \n  nth (S i) (G++(a::l)) d = nth i (G++l) d.\nProof.\n  refine\n    (fix nth_sameR A i a (l G:list A) d (H: length G < S i) {struct G} : nth (S i) (G++(a::l)) d = nth i (G++l) d := \n      (match G as G' return (G = G' -> nth (S i) (G++(a::l)) d = nth i (G++l) d) with \n         | nil => _\n         | cons a g => _\n       end) (refl_equal G)).\n  intros. rewrite H1 in *. simpl. auto.\n  intros. rewrite H1 in *. simpl. \n  destruct i. simpl in H0. unfold lt in H0. apply le_S_n in H0.\n  apply le_n_O_eq in H0. inversion H0. \n  apply nth_sameR.\n  simpl in H0. unfold lt in H0. apply le_S_n in H0.\n  unfold lt. auto.\nDefined.\n \nLemma one_longer : \n  forall A i (G :list A) xty l, (S i) < S (length (G ++ xty :: l)) -> i < S (length (G++l)).\nProof.\n  intros. rewrite app_length in H0. simpl in H0.\n  rewrite plus_comm in H0. simpl in H0.\n  unfold lt in *. apply le_S_n in H0.\n  rewrite app_length. rewrite plus_comm. auto.\nDefined.\n\nLemma strengthenG_gt : forall i d n l G xty ty, \n  length G < S i -> \n  Derivation [d ; n ; G ++ xty::l |= V (S i) @ ty] -> \n  Derivation [d ; n ; G ++ l |= V i @ ty].\nProof.\n  intros i d n l G xty ty Hlength HD.\n  inversion HD. \n  rewrite nth_sameR in H7.\n  apply VarIntro. auto.  \n  induction G. simpl in *.\n  firstorder. simpl in *. \n  apply one_longer in H6. auto. auto. auto.\nDefined.\n\nLemma strengthenG_lt : forall i d n l G xty ty, \n  i < length G -> \n  Derivation [d ; n ; G ++ xty::l |= V i @ ty] -> \n  Derivation [d ; n ; G ++ l |= V i @ ty].\nProof.\n  intros. inversion H1. subst. \n  apply VarIntro ; auto. \n  rewrite app_length. \n  unfold lt in *.\n  apply le_plus_trans. auto.\n  rewrite nth_sameL. auto. auto.\nDefined.\n\nDefinition weakenG_lt : forall i G d n L ty xty,\n  i < length G -> \n  Derivation [d ; n; G ++ L |= V i @ ty] ->\n  Derivation [d ; n; G ++ xty :: L |= V i @ ty].\nProof. \n  intros.\n  apply VarIntro ; auto. apply type_valid_at_n in H1. auto.\n  rewrite app_length.\n  apply lt_plus_trans. auto.\n  inversion H1; subst. simpl in *.\n  apply nth_sameL. auto.\nDefined.\n\nDefinition weakenG_gt : forall i G d n L ty xty,\n  length G < (S i) -> \n  Derivation [d; n; G ++ L |= V i @ ty] ->\n  Derivation [d; n; G ++ xty :: L |= V (S i) @ ty].\nProof. \n  intros.\n  inversion H1 ; subst.\n  apply VarIntro ; auto. rewrite app_length in *. \n  simpl. rewrite plus_comm. simpl.\n  apply lt_n_S. rewrite plus_comm. auto.\n  apply nth_sameR. auto.\nDefined.\n\nLemma nth_append : forall G xty l, nth (length G) (G ++ xty :: l) Zero = xty.\nProof.\n  induction G. intros. simpl. auto.\n  intros. simpl. apply IHG. \nDefined.\n\nLemma hole_at_i : forall i j k, \n  shift j (V i) = (V k) -> (~ j = k).\nProof. \n  intros. simpl in *.\n  case_eq (le_lt_dec j i).\n  intros. rewrite H1 in H0. clear H1. \n  unfold not. intros.\n  rewrite <- H1 in H0. inversion H0.\n  rewrite <- H3 in l.\n  apply (le_Sn_n i). auto.\n  intros. rewrite H1 in H0. clear H1.\n  inversion H0. rewrite H2 in *.\n  unfold not. intro. rewrite H1 in l.\n  apply (lt_irrefl k). auto.\nDefined.\n\nLemma shift_var : forall n i d G L xty ty, \n  Derivation [d; n; G ++ L |= V i @ ty] -> \n  Derivation [d; n; G ++ xty :: L |= shift (length G) (V i) @ ty].\nProof. \n  intros.\n  case_eq (shift (length G) (V i)). \n  (* F *) \n  intros. simpl in H1. \n  destruct (le_lt_dec (length G) i) ; auto ; inversion H1.\n \n  (* Var *) \n  intros.\n  cut (shift (length G) (V i) = V n0). intros Hdup.\n  apply hole_at_i in Hdup. \n  simpl in H1. \n  case_eq (le_lt_dec (length G) i). intros. \n  rewrite H2 in H1. inversion H1. \n  apply weakenG_gt. rewrite <- H4 in *.\n  unfold lt in *. apply le_n_S. auto.\n  auto. \n  intros. rewrite H2 in H1.\n  inversion H1. rewrite H4 in *. clear H2. \n  apply weakenG_lt. rewrite <- H4. auto. auto. auto. \n\n  (* App *) \n  intros. simpl in H1. \n  destruct (le_lt_dec (length G) i) ; auto ; inversion H1.\n  \n  (* TApp *) \n  intros. simpl in H1. \n  destruct (le_lt_dec (length G) i) ; auto ; inversion H1.\n  (* Abs *) \n  intros. simpl in H1. \n  destruct (le_lt_dec (length G) i) ; auto ; inversion H1.\n  (* Lam *) \n  intros. simpl in H1. \n  destruct (le_lt_dec (length G) i) ; auto ; inversion H1.\nDefined.\n\nLemma shift_correct : forall d n s xty ty G L, \n  Derivation [d ; n; G ++ L |= s @ ty] ->\n  Derivation [d ; n; G ++ (xty :: L) |= shift (length G) s @ ty].\nProof.\n    refine \n      (fix shift_correct (d : FCtx) (n : nat) (s : Term) (xty ty : Ty) (G L : list Ty)\n        (D : Derivation [d; n; G ++ L |= s @ ty]) {struct s}:\n        Derivation [d ; n; G ++ (xty :: L) |= shift (length G) s @ ty] := \n        (match s as s'\n           return (s = s' -> Derivation [d ; n; G ++ (xty :: L) |= shift (length G) s @ ty])\n           with \n           | F m => _\n           | V i => _\n           | Abs ty r => _\n           | Lam t => _\n           | App r s => _\n           | TApp r ty' => _\n         end) (refl_equal s)) ; intros ; subst.\n\n    (* F *) \n    inversion D. \n    simpl ; subst. \n    apply FunIntro. auto. auto.  \n  \n    (* V *)\n    inversion D. \n    apply shift_var. exact D.\n\n    (* App *)\n    simpl.\n    inversion D ; subst.\n    apply ImpElim with (xty:=xty0).\n    apply shift_correct ; clear shift_correct ; auto.\n    apply shift_correct ; clear shift_correct ; auto.\n\n    (* TApp *)\n    simpl. \n    inversion D ; subst.\n    apply AllElim. auto. \n    apply shift_correct ; clear shift_correct. auto.  \n\n    (* Abs *)\n    simpl.\n    inversion D ; subst. \n    apply ImpIntro. auto.\n    rewrite plus_comm. simpl.\n    cut (length  (ty0 :: G) = (S (length G))).\n    intros. rewrite <- H0.\n    rewrite app_comm_cons.\n    apply shift_correct with (G:=(ty0::G)) (ty:=ty1).\n    rewrite <- app_comm_cons.\n    auto. simpl. auto.\n\n    (* Lam *) \n    simpl. \n    inversion D ; subst.\n    apply AllIntro.\n    cut (length G = length (map tyshift G)).\n    intros. rewrite H0.\n    rewrite map_app. simpl.\n    apply shift_correct.\n    rewrite <- map_app. auto.\n    rewrite map_length. auto.\nDefined.\n\nTheorem tyhole_at_i : forall i j k, \n  tyshiftn 1 j (TV i) = (TV k) -> (~ j = k).\nProof. \n  intros. unfold tyshiftn in *.\n  case_eq (le_lt_dec j i). \n  intros. rewrite H1 in H0. inversion H0.\n  clear H1.\n  apply le_n_S in l. \n  unfold not. intros. rewrite H1 in l.\n  apply le_S_n in l. apply (le_Sn_n i). auto.\n  intros. rewrite H1 in H0. clear H1.\n  inversion H0. unfold not. intros.\n  subst. apply (lt_irrefl k). auto.\nQed.\n\nLemma tyshift_natural : forall G n m, \n  nth n (map (tyshiftn 1 m) G) Zero = tyshiftn 1 m (nth n G Zero).\nProof.\n  induction G. simpl. intros. destruct n ; auto.\n  intros. simpl. destruct n ; auto.\nQed.\n\nLemma tyshift_comm : forall xty m n,\n  m <= n ->\n  tyshiftn 1 (S n) (tyshiftn 1 m xty) = tyshiftn 1 m (tyshiftn 1 n xty).\nProof.\n  induction xty ; intros ; simpl ; numerical. \n\n  destruct n; numerical.\n  \n  rewrite IHxty2. rewrite IHxty1. auto. auto. auto.\n  \n  rewrite IHxty. auto. firstorder.\nQed.\n\nLemma tyshift_tyshift_map  : forall m G,\n  map (tyshiftn 1 0) (map (tyshiftn 1 m) G) = map (tyshiftn 1 (S m)) (map (tyshiftn 1 0) G).\nProof.\n  induction G. simpl. auto. simpl.\n  rewrite tyshift_comm. rewrite IHG. auto. \n  apply (le_O_n m). \nDefined.\n\nLemma tyshift_tysubL : forall ty m n xty,\n  m <= n ->\n  tyshiftn 1 m (tysub ty n xty) = tysub (tyshiftn 1 m ty) (S n) (tyshiftn 1 m xty).\nProof.\n  induction ty ; intros ; simpl ; numerical. \n\n  destruct n ; unfold tyshift ; simpl ; numerical. \n  destruct n ; unfold tyshift ; simpl ; numerical. \n\n  rewrite IHty1. rewrite IHty2. auto. auto. auto. \n\n  rewrite IHty. unfold tyshift.\n  rewrite tyshift_comm. auto.  \n  firstorder. firstorder.\nQed.\n\nLemma tyshift_tysubR : forall ty m n xty,\n  n <= m ->\n  tyshiftn 1 m (tysub ty n xty) = tysub (tyshiftn 1 (S m) ty) n (tyshiftn 1 m xty).\nProof.\n  induction ty ; intros ; simpl ; numerical.\n  destruct n ; unfold tyshift ; simpl ; numerical. \n  destruct n ; unfold tyshift ; simpl ; numerical. \n  destruct n ; unfold tyshift ; simpl ; numerical.\n\n  rewrite IHty1. rewrite IHty2. auto. auto. auto. \n\n  rewrite IHty. unfold tyshift.\n  rewrite tyshift_comm ; auto ; firstorder. firstorder.\nQed.\n\nLemma tyshiftn_closed_id : forall ty l n m, \n  n <= m -> valid ty n -> tyshiftn l m ty = ty.\nProof.\n  induction ty.\n  (* TV *) \n  intros; simpl in * ; numerical.\n\n  (* Imp *) \n  intros. simpl in *.\n  inversion H1.\n  apply (IHty1 l n m H0) in H2. \n  apply (IHty2 l n m H0) in H3.\n  rewrite H2. rewrite H3. auto.\n\n  (* All *) \n  intros. simpl in *.\n  apply (IHty l (S n) (S m)) in H1.\n  rewrite H1. auto. firstorder.\nDefined.\n\nLemma tysub_closed_id : forall ty xty n m, \n  n <= m -> valid ty n -> tysub ty m xty = ty.\nProof.\n  induction ty.\n  (* TV *) \n  intros ; simpl in * ; numerical.\n  (* Imp *)\n  intros ; simpl in *.\n  inversion H1.\n  apply (IHty1 xty n m H0) in H2. \n  apply (IHty2 xty n m H0) in H3.\n  rewrite H2. rewrite H3. auto.\n\n  (* All *) \n  intros. simpl in *.\n  apply (IHty (tyshift xty) (S n) (S m)) in H1.\n  rewrite H1. auto. firstorder.\nDefined.\n\nLemma tyshift_correct : forall s d n m G xty, \n  Derivation [d; n+m; G |= s @ xty] ->\n  Derivation [d; S (n+m); map (tyshiftn 1 m) G |= tyshift_term m s @ tyshiftn 1 m xty].\nProof.\n  induction s ; intros.\n\n  (* F *)\n  inversion H0 ; subst. simpl.  \n  apply FunIntro. \n  rewrite tyshiftn_closed_id with (n:=0). auto. firstorder. auto.\n  rewrite tyshiftn_closed_id with (n:=0). auto. firstorder. auto.\n  \n  (* V *) \n  inversion H0. subst. simpl.\n  apply VarIntro ; auto.\n  apply tyshift_level. auto. \n  rewrite map_length. auto.\n  apply tyshift_natural.\n\n  (* App *)\n  inversion H0. subst. simpl.\n  apply ImpElim with (xty:=tyshiftn 1 m xty0).\n  apply IHs2. auto.\n  cut (Imp (tyshiftn 1 m xty0) (tyshiftn 1 m xty) = tyshiftn 1 m (Imp xty0 xty)).\n  intros. rewrite H1. apply IHs1. auto. simpl. auto.\n  \n  (* TApp *) \n  simpl.\n  inversion H0 ; subst.\n  rewrite tyshift_tysubR.\n  apply AllElim. \n  apply tyshift_level. auto.\n  change (All (tyshiftn 1 (S m) ty)) with (tyshiftn 1 m (All ty)). \n  apply IHs. auto. \n  apply (le_O_n m). \n\n  (* Abs *) \n  simpl. inversion H0 ; subst.\n  simpl. apply ImpIntro. \n  apply tyshift_level. auto.\n  change (tyshiftn 1 m t :: map (tyshiftn 1 m) G) with (map (tyshiftn 1 m) (t :: G)).\n  apply IHs. auto.\n  \n  (* Lam *) \n  simpl. inversion H0 ; subst. \n  simpl. apply AllIntro. intros. unfold tyshift.\n  rewrite tyshift_tyshift_map.\n  intros.\n  change (S (S (n + m))) with (S ((S n) + m)).\n  rewrite plus_Snm_nSm.  \n  apply IHs. auto. \n  rewrite <- plus_Snm_nSm. auto.  \nQed.\n\nTheorem sub_preservation : forall t s d n xty ty G L,\n  Derivation [d; n ; G++xty::L |= t @ ty] -> \n  Derivation [d; n ; G++L |= s @ xty] -> \n  Derivation [d; n ; G++L |= sub t (length G) s @ ty].\nProof. \n  induction t.\n  (* FunIntro*)\n  intros. simpl.\n  inversion H0; subst.\n  apply FunIntro ; auto.\n\n  (* VarIntro *)\n  intros. unfold sub.\n  case_eq (le_lt_dec (length G) n) ; intros. \n  case_eq (eq_nat_dec (length G) n). intros. rewrite <- e in H0. \n  inversion H0. simpl in H10.\n  rewrite nth_append in H11. rewrite <- H11. auto.\n  destruct n. simpl in *.\n  intros. elimtype False. clear H2. clear H3.\n  apply le_n_O_eq in l. unfold not in n. apply n. auto. \n  intros. \n  \n  apply strengthenG_gt with (xty:=xty). clear H2.\n  apply le_lt_or_eq in l. inversion l ; auto. clear H3.\n  rewrite H2 in n1. unfold not in n1.\n  elimtype False. apply n1. auto.\n\n  exact H0.\n\n  apply strengthenG_lt with (xty:=xty). auto. auto. \n\n  (* ImpElim *)\n  intros. simpl.\n  inversion H0. subst. \n  apply ImpElim with (xty:=xty0). eapply IHt2. eexact H4.\n  exact H1. eapply IHt1. eexact H9. auto.\n\n  (* AllElim *)\n  intros. simpl.\n  inversion H0. subst.\n  apply AllElim. auto. auto. apply IHt with (xty:=xty). auto. auto.\n  \n  (* ImpIntro *) \n  intros. simpl. \n  inversion H0. subst.\n  apply ImpIntro. auto. \n  cut (S (length G) = (length (t::G))).\n  intros. rewrite H2. \n  rewrite app_comm_cons.\n  apply IHt with (G := (t :: G)) (xty:=xty). auto.\n  rewrite <- app_comm_cons. \n  cut (t::G++L = nil++(t::G++L)).\n  intros. rewrite H3.\n  \n  apply shift_correct with (G:=(nil (A:=Ty))). \n  simpl. auto. auto. auto. \n\n  (* AllIntro *)\n  intros. simpl in *.\n  inversion H0 ; subst.\n  apply AllIntro.\n  cut (n+0 = n). intro Hpz. rewrite <- Hpz in H1. \n  apply tyshift_correct in H1. simpl in H1.\n  cut (length (map (tyshiftn 1 0) G) = length G). intros.\n  rewrite <- H2.\n  rewrite map_app. \n  apply IHt with (xty:=tyshiftn 1 0 xty).\n  rewrite map_app in H3. simpl in H3. auto. \n  rewrite map_app in H1. \n  rewrite <- Hpz. auto. \n  apply map_length. simpl. auto.\nDefined.\n\nTheorem sub_preservation_basic : forall d n L t s xty ty, \n  Derivation [d ; n ; xty::L |= t @ ty] -> \n  Derivation [d ; n ; L |= s @ xty] -> \n  Derivation [d ; n ; L |= sub t 0 s @ ty].\nProof.\n  intros.\n  change L with (nil++L).\n  change 0 with (length  (A:=Ty) nil).\n  apply sub_preservation with (xty:=xty). simpl. auto. \n  simpl. auto.\nDefined.\n\nTheorem type_unique : forall d n L t ty1 ty2, \n  Derivation [d ; n ; L |= t @ ty1] -> Derivation [d ;n ; L |= t @ ty2] \n  -> ty1 = ty2. \nProof.\n  refine \n    (fix type_unique d n l (t : Term) ty1 ty2 \n      (d1 : Derivation [d; n ; l |= t @ ty1])\n      (d2 : Derivation [d; n ; l |= t @ ty2]) {struct t} \n      : ty1 = ty2 :=\n      (match t as t' return (t = t' -> ty1 = ty2)\n         with\n         | F n => _ \n         | V n => _\n         | App f g => _ \n         | Abs ty r => _ \n         | TApp r ty => _\n         | Lam r => _\n       end) (refl_equal t)) ; intros ; subst.\n\n  (* F *) \n  intros. inversion d1 ; inversion d2 ; subst ; auto.\n\n  (* V *) \n  intros. inversion d1 ; inversion d2 ; subst ; auto.\n  \n  (* App *) \n  intros. inversion d1 ; inversion d2 ; subst ; auto.\n  apply type_unique with (ty1:=xty) (ty2:=xty0) in H2 ; \n    apply type_unique with (ty1:=Imp xty ty1) (ty2:=Imp xty0 ty2) in H7.  \n  subst. inversion H7. auto. auto. auto. auto.\n\n  (* TApp *) \n  intros. inversion d1 ; inversion d2 ; subst ; auto.\n  apply type_unique with (ty1:=All ty0) (ty2:=All ty3) in H7.\n  inversion H7. auto. auto.\n\n  (* Abs *) \n  intros. inversion d1 ; inversion d2 ; subst ; auto.\n  apply type_unique with (ty1:=ty0) (ty2:=ty3) in H7.\n  subst ; auto. auto. \n\n  (* Lam *)\n  intros. inversion d1 ; inversion d2 ; subst ; auto.\n  apply type_unique with (ty1:=ty) (ty2:=ty0) in H7.\n  subst ; auto. auto.\nDefined.\n\nTheorem tysub_tyshift_id : forall a m ty, \n  tysub (tyshiftn 1 m a) m ty = a.\nProof. \n  induction a.\n  intros. simpl. numerical.\n\n  intros. simpl. \n  rewrite (IHa1 m ty).\n  rewrite (IHa2 m ty). auto.\n\n  intros. simpl. unfold tyshift.\n  rewrite (IHa (S m) (tyshiftn 1 0 ty)).\n  auto.\nQed.\n\nLemma tysub_tyshift_map_id : forall l m ty,  map (fun t => tysub t m ty) (map (tyshiftn 1 m) l) = l.\nProof.\n  induction l; intros m ty.\n  simpl. auto.\n  simpl. rewrite tysub_tyshift_id.\n  rewrite IHl. auto.\nDefined.\n\nTheorem nth_tysub_tyshift : forall l n m ty ty0,\n  nth n (map (tyshiftn 1 m) l) Zero = ty -> \n  nth n l Zero = tysub ty m ty0.\nProof.\n  induction l.\n  intros. simpl in *.\n  destruct n ; subst ; simpl ; auto.\n\n  intros.\n  destruct n. simpl in H0. \n  simpl. subst.\n  rewrite (tysub_tyshift_id a m ty0). auto.\n\n  simpl. apply IHl. simpl in H0. auto.\nDefined.\n\nLemma tyshiftn_z_id : forall ty n, tyshiftn 0 n ty = ty. \nProof.\n  induction ty.\n  intros. simpl. case (le_lt_dec n0 n) ; intros ; auto.\n\n  intros. simpl. rewrite IHty1. rewrite IHty2. auto.\n  \n  intros. simpl. rewrite IHty. auto.\nDefined. \n\nLemma tyhole_in : forall n m k ty, \n  tyshiftn (S n) m ty = (TV k) -> k > m+n \\/ k < m.\nProof.\n  intros. \n  simpl in H0. \n  destruct ty. simpl in *. \n  case_eq (le_lt_dec m n0) ; intros HP  HX ; rewrite HX in H0.\n  inversion H0. firstorder.\n  inversion H0. firstorder.\n  inversion H0. inversion H0.\nDefined.\n\nLemma tysub_into_hole : forall ty n m k ty',\n  k <= m+n /\\ k >= m ->\n  tysub (tyshiftn (S n) m ty) k ty' = tyshiftn n m ty.\nProof.\n  induction ty.\n\n  intros. simpl. numerical.\n\n  intros. simpl. intros. rewrite IHty1. rewrite IHty2. auto. auto. auto.\n  \n  intros. simpl. rewrite IHty. auto.\n  firstorder.\nDefined.  \n\nLemma nth_tysub_map : forall l n m ty1, nth n (map (fun ty : Ty => tysub ty m ty1) l) Zero =\n  tysub (nth n l Zero) m ty1.\nProof.\n  induction l ; auto.\n  intros. simpl. destruct n ; auto.\n  intros. simpl. destruct n. auto. \n  apply IHl. \nDefined. \n  \nLemma tyshift_sum : forall tyx n m, tyshiftn 1 n (tyshiftn m n tyx) = tyshiftn (S m) n tyx.\nProof.\n  induction tyx ; intros n0 m.\n  (* TV *) \n  simpl. auto. numerical.\n  (* Imp *) \n  simpl. \n  rewrite IHtyx1. rewrite IHtyx2. auto.\n  (* All *) \n  simpl. rewrite IHtyx. auto.\nDefined.\n\nLemma commute_tysub_tyshift_maps : forall l tyx m, map tyshift (map (fun ty : Ty => tysub ty m tyx) l)  = \n  map (fun ty => tysub ty (S m) (tyshift tyx)) (map tyshift l).\nProof. \n  induction l ; intros.\n  simpl. auto.\n  simpl.\n  cut (tyshift (tysub a m tyx) = tysub (tyshift a) (S m) (tyshift tyx)).\n  intros Heq; rewrite Heq. \n  rewrite IHl. auto. \n  unfold tyshift.\n  rewrite tyshift_tysubL. auto. firstorder.\nDefined.\n\n(* \nLemma F_weaken : forall ty d n l tyx, \n  Derivation [d; n; l |=F n @ tysub ty 0 tyx] -> \n  Derivation [d; n; nil |=F n @ ty].\nProof.\n  intros. \n  inversion H0. subst. \n  apply FunIntro. rewrite H3. \n  rewrite tysub_closed_id with (n:=0). auto. auto.\n\n  apply tysub_level_gen.\n \n  rewrite tysub_closed_id with (n:=0) in H7 . auto. firstorder.\n*)  \nAxiom tysub_comm : forall ty0 t0 tyx m, \n  tysub (tysub ty0 0 t0) m tyx =\n  tysub (tysub ty0 (S m) (tyshift tyx)) 0 (tysub t0 m tyx).\n\nLemma tysub_all : forall t ty tyx d n m l,\n  valid tyx (n+m) -> \n  Derivation [d; S (n+m); l |= t @ ty] -> \n  Derivation [d; (n+m); map (fun ty => tysub ty m tyx) l |= tysubt t m tyx @ tysub ty m tyx].\nProof. \n  induction t; intros ty tyx d n0 m l HV HD.\n  \n  (* F *) \n  apply FunIntro.  inversion HD. subst.\n  rewrite tysub_closed_id with (n:=0). auto. firstorder. auto.\n  inversion HD. subst. \n  rewrite tysub_closed_id with (n:=0). auto. firstorder. auto.\n\n  (* V *) \n  inversion HD. subst. \n  apply VarIntro. \n  apply tysub_level_gen. firstorder. auto. auto.\n  rewrite map_length. auto. \n  change (tysub (nth n l Zero) m tyx) with ((fun ty => tysub ty m tyx) (nth n l Zero)). \n  rewrite <- map_nth. unfold Zero. simpl. auto.\n  (* App *) \n  inversion HD. subst. \n  apply ImpElim with (xty := (tysub xty m tyx)). \n  apply IHt2. auto. auto. \n  change (Imp (tysub xty m tyx) (tysub ty m tyx)) with (tysub (Imp xty ty) m tyx).\n  apply IHt1. auto. auto.\n  (* TApp *) \n  inversion HD ; subst. \n  rewrite tysub_comm.   \n  apply AllElim. auto.\n  apply tysub_level_gen. firstorder. auto. auto.\n  fold tysubt.\n  change (All (tysub ty0 (S m) (tyshift tyx))) with (tysub (All ty0) m tyx).\n  apply IHt. auto. auto.\n  (* Abs *) \n  inversion HD ; subst.\n  simpl. \n  apply ImpIntro. \n  apply tysub_level_gen. firstorder. auto. auto. \n  change (tysub t m tyx :: map (fun ty : Ty => tysub ty m tyx) l) with \n    (map (fun ty : Ty => tysub ty m tyx) (t::l)).\n  apply IHt. auto. auto.\n  (* Lam *)\n  inversion HD. subst. \n  simpl. \n  apply AllIntro. \n  rewrite commute_tysub_tyshift_maps.\n  (*  cut (map tyshift (map (fun ty : Ty => tysub ty m tyx) l)  = \n     map (fun ty => tysub ty (S m) (tyshift tyx)) (map tyshift l)). \n  intros Heq. \n  rewrite Heq. *)\n  change (S (n0 + m)) with (S n0 + m).\n  rewrite plus_Snm_nSm.\n  apply IHt. fold tyshift.\n  rewrite <- plus_Snm_nSm.\n  apply tyshift_level. fold plus. auto. \n  rewrite <- plus_Snm_nSm.\n  auto.\nDefined.\n\nLemma tysub_derivation : forall t d n m l ty tyx, \n  valid tyx (n+m) -> \n  Derivation [d; S (n+m); map (tyshiftn 1 m) l |=t @ ty] -> \n  Derivation [d; (n+m); l |=tysubt t m tyx @ tysub ty m tyx].\nProof. \n  induction t ; intros d n0 m l ty tyx HV HD.\n  (* F *) \n  inversion HD ; subst ; simpl.\n  apply FunIntro. \n  rewrite tysub_closed_id with (n:=0) ; firstorder. \n  rewrite tysub_closed_id with (n:=0) ; firstorder.\n  \n  (* V *) \n  inversion HD ; subst ; simpl. \n  apply VarIntro. \n  apply tysub_level_gen ; firstorder.\n  rewrite map_length in H6. auto.\n  rewrite <- nth_tysub_map.\n  rewrite tysub_tyshift_map_id with (m :=m) (ty:=tyx). auto.\n  (* App *) \n  inversion HD ; subst ; simpl.\n  apply ImpElim with (xty := tysub xty m tyx).\n  apply IHt2 ; auto.\n  change (Imp (tysub xty m tyx) (tysub ty m tyx)) with (tysub (Imp xty ty) m tyx).\n  apply IHt1 ; auto. \n \n  (* TApp *)\n  inversion HD. subst. \n  simpl. \n  rewrite tysub_comm. \n  apply AllElim. \n  apply tysub_level_gen. firstorder. auto. auto. \n  change (All (tysub ty0 (S m) (tyshift tyx))) with (tysub (All ty0) m tyx).\n  apply IHt. auto. auto. \n  \n  (* Abs *) \n  inversion HD ; subst ; simpl.\n  apply ImpIntro.\n  apply tysub_level_gen ; firstorder.\n  cut (l = map (fun t => tysub t m tyx) (map (tyshiftn 1 m) l)).\n  intros Heq. rewrite Heq. \n  change (tysub t m tyx :: map (fun t1 : Ty => tysub t1 m tyx) (map (tyshiftn 1 m) l)) with \n    (map (fun t1 : Ty => tysub t1 m tyx) (t::(map (tyshiftn 1 m) l))).\n  apply tysub_all. auto. auto.\n  rewrite tysub_tyshift_map_id with (m:=m) (ty:=tyx).\n  auto.\n\n  (* Lam *)\n  inversion HD ; subst ; simpl.\n  apply AllIntro.\n  change (S (n0+m)) with (S n0 + m).\n  rewrite plus_Snm_nSm. \n  apply IHt. \n  rewrite <- plus_Snm_nSm. auto.\n  apply tyshift_level. fold plus. auto. \n  cut (map (tyshiftn 1 (S m)) (map tyshift l) = (map tyshift (map (tyshiftn 1 m) l))). \n  intros Heq. rewrite Heq. \n  rewrite <- plus_Snm_nSm. auto.\n  rewrite tyshift_tyshift_map. auto.\nDefined. \n\nLemma tysub_derivation_simple : forall t d n l ty tyx, \n  valid tyx n -> \n  Derivation [d; S n; map tyshift l |=t @ ty] -> \n  Derivation [d; n; l |=tysubt t 0 tyx @ tysub ty 0 tyx].\nProof.\n  intros.\n  change n with (0+n).\n  rewrite plus_comm.\n  apply tysub_derivation ; rewrite <- plus_comm ; firstorder. \nDefined.\n\nAxiom Delta : nat -> Term. \nAxiom Xi : forall d n l m ty, Derivation [d ; n ; l |= F m @ ty] -> Derivation [d ; n ; l |= Delta m @ ty]. \n\nInductive Ev : Term -> Term -> Set :=\n| ev_f : forall n, Ev (F n) (Delta n)\n| ev_app : forall t t' s, Ev t t' -> Ev (App t s) (App t' s)\n| ev_abs : forall t s ty, Ev (App (Abs ty t) s) (sub t 0 s)\n| ev_tapp : forall t t' ty, Ev t t' -> Ev (TApp t ty) (TApp t' ty)\n| ev_lam : forall t ty, Ev (TApp (Lam t) ty) (tysubt t 0 ty).\n\nTheorem Ev_preservation : forall t t' d n l ty, Derivation [d; n ; l |= t @ ty] ->  Ev t t' -> Derivation [d; n ; l |= t' @ ty]. \nProof. \n  refine (fix Ev_preservation t t' d n l ty (D : Derivation [d; n ; l |= t @ ty]) (EvH : Ev t t') : Derivation [d; n ; l |= t' @ ty] := _)\n    ; case_eq t ; intros; subst. \n  (* F *)\n  inversion EvH. subst. apply Xi. auto. \n  (* V *)\n  inversion EvH.\n  (* App *) \n  inversion EvH ; subst.\n  inversion D ; subst. \n  apply ImpElim with (xty:=xty). auto.\n  apply Ev_preservation with (t:=t0) ; auto.\n  inversion D ; subst.\n  inversion H7 ; subst.\n  apply sub_preservation_basic with (xty:=xty) ; auto. \n  (* TApp *) \n  inversion EvH ; subst.\n  inversion D ; subst. \n  apply AllElim ; auto. \n  apply Ev_preservation with (t:=t0) ; auto.\n  inversion D ; subst.\n  inversion H7 ; subst.\n  apply tysub_derivation_simple. auto. auto.\n  (* Abs *) \n  inversion EvH. \n  (* Lam *) \n  inversion EvH.\nDefined. \n\nDefinition Evplus := forall t t', Ev t t' \\/ Evstar t t'.\n\nFixpoint ev_in_n (tick : nat) d n l t ty (D : Derivation [d; 0; nil |= t @ ty]) : { t' | Ev \n  \n\nInductive trans : Term -> label -> term -> Prop := \n| trans_fst : forall t1 t2 A, (0, [] |= (prod t1 t2) @ A) -> trans (prod t1 t2) t1\n| trans_snd : forall t1 t2 A, (0, [] |= (prod t1 t2) @ A) -> trans (prod t1 t2) t2\n| trans_inl : forall t A B, (0, [] |= (inl t B) @ A) -> trans (inl t B) t\n| trans_inr : forall t A B, (0, [] |= (inr t B) @ A) -> trans (inr t B) t\n| trans_app : forall t1 t2, (0, [] |= t2 @ A) -> trans (abs t1) (app (abs t1) t2)\n| trans_next : forall t1 t2 t3 l, eval t1 t2 -> trans t2 l t3 -> trans t1 l t3.\n\nCoInductive Simulates : term -> term -> Prop := \n| simulates_base : forall a b, \n  (forall a' l, \n    trans a l a' -> \n    (exists b', trans b l b' /\\ simulates a' b')) -> \n  simulates a b.\n\n", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/Bisimulation/B2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.674650831047454}}
{"text": "Require Import TLC.LibTactics.\nRequire Import TLC.LibEqual.\nRequire Import TLC.LibLogic.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nRequire Import Filter.\nRequire Import ZArith.\nRequire Import Psatz.\nRequire Import LibZExtra.\nRequire Import LibRewrite.\nLocal Open Scope Z_scope.\n\n(* A notion of limit, or convergence, or divergence -- it all depends on which\n   filters one uses. The assertion [limit f] states that any property [P] that\n   is ultimately true of [y] is ultimately true of [f x]. If [f] is a function\n   from [nat] to [nat], equipped with its standard filter, this means that [f x]\n   tends to infinity as [x] tends to infinity. *)\n\n(* [limit] could take two arguments of type [filter A] and [filter B]. Instead,\n   we take two arguments of type [filterType]. *)\n\nSection Limit.\n\nVariables A B : filterType.\n\nDefinition limit f :=\n  finer (ultimately (image_filterType A f)) (ultimately B).\n\nLemma limitP f :\n  limit f =\n  forall P, ultimately B P -> ultimately A (fun x => P (f x)).\nProof. reflexivity. Qed.\n\nLemma limit_eq f g :\n  limit f ->\n  (forall a, f a = g a) ->\n  limit g.\nProof.\n  rewrite !limitP. intros L E P UP.\n  specializes L UP. revert L; filter_closed_under_intersection.\n  introv H. rewrite~ E in H.\nQed.\n\nLemma limit_ultimately_eq f g :\n  limit f ->\n  ultimately A (fun a => f a = g a) ->\n  limit g.\nProof.\n  rewrite !limitP. intros L UE P UP.\n  specializes L UP. revert L UE; filter_closed_under_intersection.\n  introv (H & E). rewrite~ E in H.\nQed.\n\nEnd Limit.\nArguments limit : clear implicits.\n\n(******************************************************************************)\n(* Instance for rewriting under [limit] *)\n\nProgram Instance Pw_eq_ultimately_proper (A B : filterType) :\n  Proper (pw eq ==> Basics.flip Basics.impl) (limit A B).\nNext Obligation.\n  intros. unfold respectful, pointwise_relation, Basics.flip, Basics.impl.\n  intros P1 P2 H U. eapply limit_eq; eauto.\nQed.\n\n(******************************************************************************)\n\nLemma limit_id:\n  forall A : filterType,\n  limit A A (fun a : A => a).\nProof. intros. rewrite limitP. auto. Qed.\n\nLemma limit_comp :\n  forall (A B C : filterType) (f : A -> B) (g : B -> C),\n  limit A B f ->\n  limit B C g ->\n  limit A C (fun x => g (f x)).\nProof.\n  introv LF LG. rewrite limitP in *.\n  intros P UP.\n  specializes LG UP. specializes LF LG. auto.\nQed.\n\nLemma limit_comp_eq :\n  forall (A B C : filterType) (f : A -> B) (g : B -> C) (h : A -> C),\n  limit A B f ->\n  limit B C g ->\n  (forall a, h a = g (f a)) ->\n  limit A C h.\nProof.\n  introv LF LG E. \n  forwards E': fun_ext_dep E.\n  rewrite E'. applys~ limit_comp.\nQed.\n\nSection LimitToZ.\n\nVariable A : filterType.\n\nLemma limitPZ (f : A -> Z) :\n  limit A Z_filterType f <->\n  (forall y, ultimately A (fun x => y <= f x)).\nProof.\n  rewrite limitP.\n   split.\n  - introv H. intro y. specializes H (ultimately_ge_Z y). auto.\n  - introv H. intros P HP. rewrite ZP in HP. destruct HP as (n0 & Hn0).\n    generalize (H n0). filter_closed_under_intersection. auto.\nQed.\n\nLemma limitPZ_ultimately (cond : Z -> Prop) (f : A -> Z) :\n  ultimately Z_filterType cond ->\n  limit A Z_filterType f <->\n  (forall y, cond y -> ultimately A (fun x => y <= f x)).\nProof.\n  intro Hcond.\n  rewrite limitP. split.\n  - introv H. intros y Cy. specializes H (ultimately_ge_Z y). auto.\n  - introv H. intros P HP.\n    rewrite~ (@ZP_ultimately cond) in HP. destruct HP as (n0 & Cn0 & Hn0).\n    generalize (H n0 Cn0). filter_closed_under_intersection. auto.\nQed.\n\nLemma limitPZ_ge_0 (f : A -> Z) :\n  limit A Z_filterType f <->\n  (forall y, 0 <= y -> ultimately A (fun x => y <= f x)).\nProof.\n  rewrite~ (@limitPZ_ultimately (fun x => 0 <= x)). reflexivity.\n  apply ultimately_ge_Z.\nQed.\n\nLemma limit_le f g :\n  limit A Z_filterType f ->\n  (forall a, f a <= g a) ->\n  limit A Z_filterType g.\nProof.\n  rewrite !limitPZ.\n  intros L I y. generalize (L y); filter_closed_under_intersection.\n  intros. specializes I a. lia.\nQed.\n\nLemma limit_ultimately_le f g :\n  limit A Z_filterType f ->\n  ultimately A (fun a => f a <= g a) ->\n  limit A Z_filterType g.\nProof.\n  rewrite !limitPZ.\n  intros L UI y. generalize (L y) UI; filter_closed_under_intersection.\n  intros. lia.\nQed.\n\nLemma limit_sum f g :\n  limit A Z_filterType f ->\n  limit A Z_filterType g ->\n  limit A Z_filterType (fun x => (f x) + (g x)).\nProof.\n  rewrite !limitPZ_ge_0.\n  intros LF LG y Y.\n  generalize (LF y Y) (LG y Y); filter_closed_under_intersection.\n  intros. lia.\nQed.\n\nLemma limit_sum_cst_l c f :\n  limit A Z_filterType f ->\n  limit A Z_filterType (fun x => c + (f x)).\nProof.\n  rewrite !limitPZ.\n  intros L y.\n  generalize (L (y - c)); filter_closed_under_intersection.\n  intros. lia.\nQed.\n\nLemma limit_sum_cst_r c f :\n  limit A Z_filterType f ->\n  limit A Z_filterType (fun x => (f x) + c).\nProof.\n  rewrite !limitPZ.\n  intros L y.\n  generalize (L (y - c)); filter_closed_under_intersection.\n  intros. lia.\nQed.\n\nLemma limit_sum_ultimately_ge_l lo f1 f2 :\n  ultimately A (fun x => lo <= f1 x) ->\n  limit A Z_filterType f2 ->\n  limit A Z_filterType (fun x => f1 x + f2 x).\nProof.\n  intros U L. rewrite limitPZ in *. intro y; specialize (L (y-lo)).\n  revert U L; filter_closed_under_intersection. intros. lia.\nQed.\n\nLemma limit_sum_ultimately_ge_r lo f1 f2 :\n  ultimately A (fun x => lo <= f2 x) ->\n  limit A Z_filterType f1 ->\n  limit A Z_filterType (fun x => f1 x + f2 x).\nProof.\n  intros U L. rewrite limitPZ in *. intro y; specialize (L (y-lo)).\n  revert U L; filter_closed_under_intersection. intros. lia.\nQed.\n\nLemma limit_mul f g :\n  limit A Z_filterType f ->\n  limit A Z_filterType g ->\n  limit A Z_filterType (fun x => (f x) * (g x)).\nProof.\n  rewrite !limitPZ_ge_0.\n  intros LF LG y Y.\n  generalize (LF y Y) (LG y Y); filter_closed_under_intersection.\n  intros. assert (y * y <= f a * g a) by nia. nia.\nQed.\n\nLemma limit_mul_cst_l c f :\n  0 < c ->\n  limit A Z_filterType f ->\n  limit A Z_filterType (fun x => c * (f x)).\nProof.\n  rewrite !limitPZ_ge_0.\n  intros C L y Y.\n  generalize (L y Y); filter_closed_under_intersection.\n  intros; nia.\nQed.\n\nLemma limit_mul_cst_r c f :\n  0 < c ->\n  limit A Z_filterType f ->\n  limit A Z_filterType (fun x => (f x) * c).\nProof.\n  intros. eapply limit_eq. applys~ limit_mul_cst_l c. eassumption.\n  intros; lia.\nQed.\n\nLemma limit_max f g :\n  limit A Z_filterType f ->\n  limit A Z_filterType g ->\n  limit A Z_filterType (fun x => Z.max (f x) (g x)).\nProof.\n  intros LF LG. rewrite limitPZ in *.\n  intros y. generalize (LF y) (LG y); filter_closed_under_intersection.\n  intros. lia.\nQed.\n\nEnd LimitToZ.\n\nLemma limit_product :\n  forall (A B C : filterType) (f : A -> B) (g : A -> C),\n  limit A B f ->\n  limit A C g ->\n  limit A (product_filterType B C) (fun i => (f i, g i)).\nProof.\n  introv Lf Lg. rewrite limitP in *.\n  simpl. intros Pp UPp. rewrite productP in UPp.\n  destruct UPp as (P1 & P2 & UP1 & UP2 & HPp).\n  specializes Lf UP1. specializes Lg UP2.\n  revert Lf Lg; filter_closed_under_intersection.\n  intros. apply HPp; tauto.\nQed.\n\nLemma limit_lift1 :\n  forall (A B C : filterType) (f : A -> C),\n  limit A C f ->\n  limit (product_filterType A B) C (fun '(a, _) => f a).\nProof.\n  introv L.\n  rewrite limitP in *. introv U. rewrite productP.\n  forwards~ UA: L U.\n  eexists. eexists. splits.\n  - apply UA.\n  - apply filter_universe.\n  - auto.\nQed.\n\nLemma limit_lift2 :\n  forall (A B C : filterType) (f : B -> C),\n  limit B C f ->\n  limit (product_filterType A B) C (fun '(_, b) => f b).\nProof.\n  introv L.\n  rewrite limitP in *. introv U. rewrite productP.\n  forwards~ UB: L U.\n  eexists. eexists. splits.\n  - apply filter_universe.\n  - apply UB.\n  - auto.\nQed.\n\n(******************************************************************************)\n\nLemma Zshift_limit (x0 : Z) :\n  limit Z_filterType Z_filterType (Zshift x0).\nProof.\n  intros. rewrite limitP. introv H.\n  rewrite ZP in H. destruct H as [x1 H1].\n  rewrite ZP. exists (x1 - x0)%Z. intros. apply H1.\n  unfold Zshift. lia.\nQed.\n\nLemma limit_liftl :\n  forall (A1 A2 B : filterType) f,\n  limit A1 B f ->\n  limit (product_filterType A1 A2) (product_filterType B A2) (liftl f).\nProof.\n  unfold limit, finer. introv Lf UP. simpl in *.\n  rewrite productP in UP. destruct UP as (P1 & P2 & UP1 & UP2 & HP).\n  rewrite imageP. rewrite productP. unfold liftl.\n  specializes Lf UP1. rewrite imageP in Lf.\n  do 2 eexists. splits~.\n  exact Lf. exact UP2.\n  simpl. intros. eauto.\nQed.\n\nLemma limit_liftr :\n  forall (A1 A2 B : filterType) f,\n  limit A2 B f ->\n  limit (product_filterType A1 A2) (product_filterType A1 B) (liftr f).\nProof.\n  unfold limit, finer. introv Lf UP. simpl in *.\n  rewrite productP in UP. destruct UP as (P1 & P2 & UP1 & UP2 & HP).\n  rewrite imageP. rewrite productP. unfold liftr.\n  specializes Lf UP2. rewrite imageP in Lf.\n  do 2 eexists. splits~.\n  exact UP1. exact Lf.\n  simpl. intros. eauto.\nQed.\n\nLemma limit_pow_l : forall p,\n  0 < p ->\n  limit Z_filterType Z_filterType (fun n => n ^ p).\nProof.\n  introv Hp.\n  rewrite limitP. intros P UP.\n  rewrite ZP_ultimately with (cond := fun n => 1 <= n) in UP\n    by (apply ultimately_ge_Z).\n  destruct UP as (n0 & N0 & HP). rewrite ZP.\n  exists n0. intros n N. apply HP.\n  rewrite <-(Z.pow_1_r n0).\n  apply Z.pow_le_mono; omega.\nQed.\n\nLemma limit_pow_r : forall p,\n  0 < p ->\n  limit Z_filterType Z_filterType (fun n => p ^ n).\nProof.\n  introv Hp.\n  rewrite limitP. intros P UP.\n  rewrite ZP_ultimately with (cond := fun n => 1 <= n) in UP\n    by (apply ultimately_ge_Z).\n  destruct UP as (n0 & N0 & HP). rewrite ZP.\n  exists n0. intros n N. apply HP.\n  admit. (* TODO *)\nQed.\n\n(* These variants combine [limit_comp] and [limit_pow_l]/[limit_pow_r]. This is\n   useful in particular when added to an auto hint base. *)\n\nLemma limit_pow_l_comp :\n  forall (A : filterType) f p,\n  0 < p ->\n  limit A Z_filterType f ->\n  limit A Z_filterType (fun n => (f n) ^ p).\nProof.\n  introv Hp L. apply limit_comp with (g := fun n => n ^ p).\n  assumption. apply limit_pow_l. assumption.\nQed.\n\nLemma limit_pow_r_comp :\n  forall (A : filterType) f p,\n  0 < p ->\n  limit A Z_filterType f ->\n  limit A Z_filterType (fun n => p ^ (f n)).\nProof.\n  introv Hp L. apply limit_comp with (g := fun n => p ^ n).\n  assumption. apply limit_pow_r. assumption.\nQed.\n\nLemma limit_log2 :\n  limit Z_filterType Z_filterType Z.log2.\nProof.\n  introv L.\n  rewrite ZP_ultimately with (cond := fun n => 1 <= n) in L\n    by apply ultimately_ge_Z.\n  destruct L as (n0 & N0 & HP).\n  rewrite imageP. rewrite ZP. exists (2 ^ n0). intros n N.\n  apply HP. rewrite <-Z.log2_le_mono; [| exact N].\n  apply Z.log2_le_pow2; auto with zarith.\n  forwards: pow_ge_1 2 n0; auto with zarith.\nQed.\n\n(* Similarly, this lemma is mostly useful in combination with auto. *)\n\nLemma limit_log2_comp :\n  forall (A : filterType) f,\n  limit A Z_filterType f ->\n  limit A Z_filterType (fun n => Z.log2 (f n)).\nProof.\n  introv L. apply limit_comp. assumption. apply limit_log2.\nQed.\n\n(******************************************************************************)\n(* Exports lemmas in a [limit] hint base. *)\n\nHint Resolve limit_id : limit.\nHint Resolve limit_sum : limit.\nHint Resolve limit_sum_cst_l : limit.\nHint Resolve limit_sum_cst_r : limit.\nHint Resolve limit_mul : limit.\nHint Resolve limit_mul_cst_l : limit.\nHint Resolve limit_mul_cst_r : limit.\nHint Resolve limit_max : limit.\nHint Resolve Zshift_limit : limit.\nHint Resolve limit_liftl : limit.\nHint Resolve limit_liftr : limit.\nHint Resolve limit_pow_l_comp : limit.\nHint Resolve limit_pow_r_comp : limit.\nHint Resolve limit_log2_comp : limit.\nHint Extern 2 (limit (product_filterType _ _) _ (fun '(a, _) => @?f a)) =>\n  apply limit_lift1 : limit.\nHint Extern 2 (limit (product_filterType _ _) _ (fun '(_, b) => @?f b)) =>\n  apply limit_lift2 : limit.\n(* FIXME? Required because [apply_nary] unfolds product_filterType *)\nHint Extern 2 (limit (FilterType _ (product_filterMixin _ _)) _ (fun '(a, _) => @?f a)) =>\n  apply limit_lift1 : limit.\n(* FIXME? Required because [apply_nary] unfolds product_filterType *)\nHint Extern 2 (limit (FilterType _ (product_filterMixin _ _)) _ (fun '(_, b) => @?f b)) =>\n  apply limit_lift2 : limit.\nHint Extern 2 (limit _ (product_filterType _ _) (fun _ => (_, _))) =>\n  apply limit_product : limit.\n\n(* By default [auto] does not do anything if it cannot prove the goal\n   completely. Here, if we would like it to still do progress even if it cannot\n   solve the goal.\n\n   Therefore this [Hint] should catch the leftover goals, and give them to the\n   user.\n*)\nHint Extern 999 (limit _ _ _) => shelve : limit_fallback.\n\n(******************************************************************************)\n\nLtac limit :=\n  unshelve (auto with zarith limit limit_fallback).\n\nLtac limit_trysolve :=\n  auto with zarith limit.\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/Limit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.674650830571159}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Lia.\n\nFrom Undecidability.Shared.Libs.DLW.Utils\n  Require Import utils_decidable fin_base.\n\nSet Implicit Arguments.\n\nTheorem finite_t_find_dec X (P : X -> Prop) \n           (Pdec : forall x, { P x } + { ~ P x }) \n           (HQ : finite_t X) :\n           { x | P x } + { forall x, ~ P x }.\nProof.\n  destruct HQ as (l & Hl). \n  destruct list_choose_dep with (P := P) (Q := fun x => ~ P x) (l := l)\n    as [ (? & ? & ?) | ]; eauto.\nQed.\n\nTheorem exists_dec_fin_t X (P Q : X -> Prop) \n           (Pdec : forall x, { P x } + { ~ P x }) \n           (HQ : fin_t Q)\n           (HPQ : forall x, P x -> Q x) :\n           { exists x, P x } + { ~ exists x, P x }.\nProof.\n  generalize (fin_t_dec _ Pdec HQ); intros ([ | x l ] & Hl).\n  + right; intros (x & Hx); apply (Hl x); split; auto.\n  + left; exists x; apply Hl; simpl; auto.\nQed.\n\n(* On discrete and finite types, one can weakly reify weak decidability \n    into inhabited strong decidability. But I do not think this could be done with \n    weak discreteness, weakly decidable equality *)\n\nDefinition list_weak_dec X (l : list X) (Q : X -> Prop) : \n             (forall x y, In x l -> In y l -> { x = y } + { x <> y } ) \n          -> (forall x, In x l -> Q x \\/ ~ Q x)\n          -> inhabited (forall x, In x l -> { Q x } + { ~ Q x }).\nProof. \n  induction l as [ | x l IHl ]; intros D H.\n  1: { exists; intros _ []. }\n  destruct IHl as [ f ].\n  + intros; apply D; simpl; auto.\n  + intros; apply H; simpl; auto.\n  + destruct (H x) as [ Hx | Hx ]; simpl; auto. \n    * exists; intros y Hy.\n      destruct (D x y) as [ H1 | H1 ]; simpl; auto.\n      - left; subst; auto.\n      - apply f; destruct Hy; auto; tauto.\n    * exists; intros y Hy.\n      destruct (D x y) as [ H1 | H1 ]; simpl; auto.\n      - right; subst; auto.\n      - apply f; destruct Hy; auto; tauto.\nQed.\n\nFact fin_weak_dec X (P Q : X -> Prop) :\n      (forall x y : X, P x -> P y -> { x = y } + { x <> y } )\n   -> fin P \n   -> (forall x, P x -> Q x \\/ ~ Q x)\n   -> inhabited (forall x, P x -> { Q x } + { ~ Q x }).\nProof.\n  intros H1 (l & Hl) H2.\n  destruct (list_weak_dec l Q) as [ f ].\n  + intros; apply H1; apply Hl; auto.\n  + intros; apply H2; apply Hl; auto.\n  + exists; intros; apply f, Hl; auto.\nQed.\n\nFact finite_weak_dec X (P : X -> Prop) :\n       finite X\n    -> (forall x y : X, { x = y } + { x <> y })\n    -> (forall x, P x \\/ ~ P x)\n    -> inhabited (forall x, { P x } + { ~ P x }).\nProof.\n  intros H1 H2 H3.\n  apply finite_fin_eq in H1.\n  destruct fin_weak_dec with (Q := P) (2 := H1); auto.\nQed.\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/Shared/Libs/DLW/Utils/fin_dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846387, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.674650823451984}}
{"text": "Load PropLogic.\nFrom Coq Require Import Setoids.Setoid.\n\nReserved Notation \"U |- A\" (at level 80).\nInductive Nd: list Proposition -> Proposition -> Prop :=\n| Assumption U A (H: In A U): U |- A\n| NotE U P (H1: U |- ¬ ¬ P) : U |- P\n| NotI U P Q (H1: P::U |- Q) (H2: P::U |- ¬ Q): U |- ¬ P\n| AndE1 U A B (H: U |- (A ∧ B)): U |- A\n| AndE2 U A B (H: U |- (A ∧ B)): U |- B\n| AndI U A B (H1: U |- A) (H2: U |- B): U |- (A ∧ B)\n| OrE U P Q R (H1: U |- P ∨ Q) (H2: P :: U |- R) (H3: Q :: U |- R): U |- R\n| OrI1 U P Q (H1: U |- P): U |- P ∨ Q\n| OrI2 U P Q (H1: U |- P): U |- Q ∨ P\n| ImpE U P Q (H1: U |- P) (H2: U |- P → Q): U |- Q\n| ImpI U P Q (H: (P :: U)%list |- Q): U |- P → Q\nwhere \"U |- A\" := (Nd U A).\n\nTheorem p_implies_p: forall U p,\n  U |- p → p.\nProof.\n  intros.\n  apply ImpI.\n  apply Assumption.\n  simpl.\n  left.\n  reflexivity.\nQed.\n\nExample example_1': forall p q,\n  [¬ p; q]|- ¬(p ∧ q).\nProof.\n  intros p q.\n  apply (NotI _ _ p).\n  - apply (AndE1 _ _ q). apply Assumption. simpl. left. reflexivity.\n  - apply Assumption. simpl. right. left. reflexivity.\nQed.\n\nExample example_2': forall fire smoke rain,\n  [fire → smoke; rain → ¬ smoke] |- rain → ¬ fire.\nProof.\n  intros fire smoke rain.\n  apply ImpI.\n  apply (NotI _ _ smoke).\n  - apply (ImpE _ fire _).\n    + apply Assumption. simpl. left. reflexivity.\n    + apply Assumption. simpl. right. right. left. reflexivity.\n  - apply (ImpE _ rain _).\n    + apply Assumption. simpl. right. left. reflexivity.\n    + apply Assumption. simpl. right. right. right. left. reflexivity.\nQed.\n\nTheorem principle_of_explosion: forall U p q,\n  [p ; ¬ p] ++ U |- q.\nProof.\n  intros.\n  apply NotE.\n  apply (NotI _ _ p)\n  ;apply Assumption\n  ;simpl.\n  - right. left. reflexivity.\n  - right. right. left. reflexivity.\nQed.\n\nTheorem law_of_excluded_middle: forall p,\n  [] |- p ∨ ¬ p.\nProof.\n  intros.\n  apply NotE.\n  apply (NotI _ _ ¬ p).\n  - apply (NotI _ _ (p ∨ ¬ p)).\n    + apply OrI1.\n      apply Assumption.\n      left.\n      reflexivity.\n    + apply Assumption. right. left. reflexivity.\n  - apply (NotI _ _ (p ∨ ¬ p)).\n    + apply OrI2.\n      apply Assumption.\n      left.\n      reflexivity.\n    + apply Assumption. right. left. reflexivity.\nQed.\n\nTheorem double_not_introduction: forall p,\n  [p] |- ¬ ¬ p.\nProof.\n  intros p.\n  apply (NotI _ _ p)\n  ; apply Assumption\n  ; simpl.\n  - right. left. reflexivity.\n  - left. reflexivity.\nQed.\n\nTheorem contrapositve: forall p q,\n  [p → q; ¬ q] |- ¬ p.\nProof.\n  intros.\n  apply (NotI _ _ q).\n  - apply (ImpE _ p _)\n    ; apply Assumption\n    ; simpl.\n    + left. reflexivity.\n    + right. left. reflexivity.\n  - apply Assumption.\n    simpl.\n    right. right. left.\n    reflexivity.\nQed.\n\nTheorem material_implication: forall p q,\n  [¬ p ∨ q] |- p → q.\nProof.\n  intros.\n  apply ImpI.\n  apply (OrE _ ¬ p q).\n  - apply Assumption. simpl. right. left. reflexivity.\n  - apply NotE.\n    apply (NotI _ _ p)\n    ;apply Assumption\n    ;simpl.\n    + right. right. left. reflexivity.\n    + right. left. reflexivity.\n  - apply Assumption. simpl. left. reflexivity.\nQed.\n\nTheorem NaturalDeduction_is_sound: forall Γ P,\n  Γ |- P -> Γ |= P.\nProof.\n  intros.\n  induction H.\n  - unfold models.\n    intros.\n    unfold Satisfies in H0.\n    apply H0 in H.\n    apply H.\n  - unfold models in IHNd.\n    unfold models.\n    intros.\n    destruct (valuation v P) eqn:E.\n    + reflexivity.\n    + apply IHNd in H0.\n      simpl in H0.\n      rewrite E in H0.\n      simpl in H0.\n      discriminate.\n  - unfold models in IHNd1.\n    unfold models in IHNd2.\n    unfold models.\n    simpl in IHNd2.\n    intros v.\n    destruct (valuation v P) eqn:E.\n    + intros. apply (satisfy_chain _ U _) in E.\n      * apply IHNd1 in E as IHNd1'.\n        apply IHNd2 in E as IHNd2'.\n        rewrite IHNd1' in IHNd2'.\n        discriminate.\n      * apply H1.\n    + intros.\n      simpl.\n      rewrite E.\n      simpl.\n      reflexivity.\n  - unfold models in IHNd.\n    unfold models.\n    intros.\n    apply IHNd in H0.\n    simpl in H0.\n    apply and_both_true in H0.\n    destruct H0 as [H0 _].\n    apply H0.\n  - unfold models in IHNd.\n    unfold models.\n    intros.\n    apply IHNd in H0.\n    simpl in H0.\n    apply and_both_true in H0.\n    destruct H0 as [_ H0].\n    apply H0.\n  - unfold models in IHNd1.\n    unfold models in IHNd2.\n    unfold models.\n    intros.\n    apply IHNd1 in H1 as IHNd1'.\n    apply IHNd2 in H1 as IHNd2'.\n    simpl.\n    rewrite IHNd1'.\n    rewrite IHNd2'.\n    reflexivity.\n  - unfold models in IHNd1.\n    unfold models in IHNd2.\n    unfold models in IHNd3. \n    unfold models.\n    intros.\n    apply IHNd1 in H2 as IHNd1'.\n    simpl in IHNd1'.\n    apply or_either_true in IHNd1'.\n    destruct IHNd1' as [H3 | H3].\n    + intros. apply (satisfy_chain _ U _) in H3.\n      * apply IHNd2 in H3 as IHNd2'.\n        apply IHNd2'.\n      * apply H2.\n    + intros. apply (satisfy_chain _ U _) in H3.\n      * apply IHNd3 in H3 as IHNd3'.\n        apply IHNd3'.\n      * apply H2.\n  - unfold models in IHNd.\n    unfold models.\n    intros.\n    apply IHNd in H0.\n    simpl.\n    rewrite H0.\n    simpl.\n    reflexivity.\n  - unfold models in IHNd.\n    unfold models.\n    intros.\n    apply IHNd in H0.\n    simpl.\n    rewrite H0.\n    destruct (valuation v Q);\n    simpl; reflexivity.\n  - unfold models in IHNd1.\n    unfold models in IHNd2.\n    unfold models.\n    intros.\n    apply IHNd1 in H1 as IHNd1'.\n    apply IHNd2 in H1 as IHNd2'.\n    simpl in IHNd2'.\n    rewrite IHNd1' in IHNd2'.\n    simpl in IHNd2'.\n    apply IHNd2'.\n  - unfold models in IHNd.\n    unfold models.\n    intros.\n    simpl.\n    destruct (valuation v P) eqn:E.\n    + apply (satisfy_chain _ U _) in E.\n      apply IHNd in E as IHNd'.\n      rewrite IHNd'. simpl. reflexivity.\n      apply H0.\n    + simpl. reflexivity.\nQed.\n", "meta": {"author": "wags-1314", "repo": "logic-in-Coq", "sha": "be5c9ab2fc951075142969d1fbbc33e962272959", "save_path": "github-repos/coq/wags-1314-logic-in-Coq", "path": "github-repos/coq/wags-1314-logic-in-Coq/logic-in-Coq-be5c9ab2fc951075142969d1fbbc33e962272959/NaturalDeduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772220439509, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6746508158565131}}
{"text": "Require Import Coq.micromega.Lia Coq.ZArith.ZArith.\nRequire Import bbv.NatLib.\n\nInductive BitWidth := BW32 | BW64.\n\nClass BitWidths := bitwidth: BitWidth.\n\nSection Widths.\n\n  Context {B: BitWidths}.\n\n  Definition wXLEN: nat :=\n    match bitwidth with\n    | BW32 => 32\n    | BW64 => 64\n    end.\n\n  Definition log2wXLEN: nat :=\n    match bitwidth with\n    | BW32 => 5\n    | BW64 => 6\n    end.\n\n  Definition wXLEN_in_bytes: nat :=\n    match bitwidth with\n    | BW32 => 4\n    | BW64 => 8\n    end.\n\n  Lemma pow2_wXLEN_4: 4 < pow2 wXLEN.\n  Proof.\n    unfold wXLEN, bitwidth. destruct B;\n      do 2 rewrite pow2_S;\n      change 4 with (2 * (2 * 1)) at 1;\n      (repeat apply mult_lt_compat_l; [ | repeat constructor ..]);\n      apply one_lt_pow2.\n  Qed.  \n  \nEnd Widths.\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/BitWidths.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6745753618979919}}
{"text": "Require Import ssreflect ssrfun ssrbool eqtype.\nRequire Import ssrnat seq choice.\nRequire Import order.\n\nSection Def.\n  Variable TK : totalOrderType.\n  Variable TV : eqType.\n  Inductive tree : Type :=\n    | empty : tree\n    | node2 of tree & TK * TV & tree\n    | node3 of tree & TK * TV & tree & TK * TV & tree.\n\n  Fixpoint eqn t0 t1 { struct t0 } :=\n    match t0,t1 with\n    | empty, empty => true\n    | node2 t0s0 t0e0 t0s1, node2 t1s0 t1e0 t1s1 =>\n      [&& eqn t0s0 t1s0, (t0e0 == t1e0) & eqn t0s1 t1s1]\n    | node3 t0s0 t0e0 t0s1 t0e1 t0s2,\n      node3 t1s0 t1e0 t1s1 t1e1 t1s2 =>\n      [&& eqn t0s0 t1s0, (t0e0 == t1e0),\n          eqn t0s1 t1s1, (t0e1 == t1e1) & eqn t0s2 t1s2]\n    | _,_ => false\n    end.\n\n  Lemma eqnP : Equality.axiom eqn.\n  Proof.\n    move=> t0 t1; apply: (iffP idP)=> [|<- {t1}].\n    - elim: t0 t1 => [|t0s0 Hs0 t0e0 t0s1 Hs1\n                      |t0s0 Hs0 t0e0 t0s1 Hs1 t0e1 t0s2 Hs2].\n      - by case.\n      - by case=> // t1s0 t1e0 t1s1 /=\n                  /and3P [/Hs0<- /eqP<- /Hs1<-].\n      - by case=> // t1s0 t1e0 t1s1 t1e1 t1s2 /=\n                  /and5P [/Hs0<- /eqP<- /Hs1<- /eqP<- /Hs2<-].\n    - elim: t0 => /= [|t0s0 -> t0e0 t0s1 ->\n                      |t0s0 -> t0e0 t0s1 -> t0e1 t0s2 ->].\n      - done.\n      - by rewrite eq_refl.\n      - by rewrite eq_refl eq_refl.\n  Qed.\n\n  Canonical tree_eqMixin := EqMixin eqnP.\n  Canonical tree_eqType := Eval hnf in EqType tree tree_eqMixin.\n\n  Fixpoint tree_check_ordered(t:tree) (lb ub:option TK) : bool :=\n    match t with\n    | empty =>\n      match lb,ub with\n      | Some lbs, Some ubs => lbs < ubs\n      | _, _ => true\n      end\n    | node2 t0 (k0,v0) t1 =>\n      tree_check_ordered t0 lb (Some k0) &&\n      tree_check_ordered t1 (Some k0) ub\n    | node3 t0 (k0,v0) t1 (k1,v1) t2 =>\n      [&& tree_check_ordered t0 lb (Some k0),\n          tree_check_ordered t1 (Some k0) (Some k1) &\n          tree_check_ordered t2 (Some k1) ub]\n    end.\n\n  Fixpoint tree_depth(t:tree) : nat :=\n    match t with\n    | empty => 0\n    | node2 t0 _ t1 => (maxn (tree_depth t0) (tree_depth t1)) .+1\n    | node3 t0 _ t1 _ t2 =>\n      (maxn (tree_depth t0) (maxn (tree_depth t1) (tree_depth t2))) .+1\n    end.\n\n  Fixpoint tree_check_depth(t:tree) : bool :=\n    match t with\n    | empty => true\n    | node2 t0 _ t1 =>\n      [&& (tree_depth t0 == tree_depth t1),\n          tree_check_depth t0 & nosimpl tree_check_depth t1]\n    | node3 t0 _ t1 _ t2 =>\n      [&& (tree_depth t0 == tree_depth t1), (tree_depth t1 == tree_depth t2),\n          tree_check_depth t0, tree_check_depth t1 & tree_check_depth t2]\n    end.\n\n  Definition tree_valid(t:tree) : bool :=\n    tree_check_ordered t None None && tree_check_depth t.\n\n  Definition T23 := sig tree_valid.\n\n  Definition tree_append(k:TK) (v:TV):tree -> bool*tree :=\n    fix recur(t:tree) :=\n    match t with\n    | empty => (true, node2 empty (k,v) empty)\n    | node2 t0 ((k0,_) as e0) t1 =>\n      if k < k0 then\n        match recur t0 with\n        | (true, node2 s0 se0 s1) =>\n          (false, node3 s0 se0 s1 e0 t1)\n        | (_, s) => (false, node2 s e0 t1)\n        end\n      else if k == k0 then\n        (false, node2 t0 (k,v) t1)\n      else\n        match recur t1 with\n        | (true, node2 s0 se0 s1) =>\n          (false, node3 t0 e0 s0 se0 s1)\n        | (_, s) => (false, node2 t0 e0 s)\n        end\n    | node3 t0 ((k0,_) as e0) t1 ((k1,_) as e1) t2 =>\n      if k < k0 then\n        match recur t0 with\n        | (true, s) =>\n          (true, node2 s e0 (node2 t1 e1 t2))\n        | (_, s) => (false, node3 s e0 t1 e1 t2)\n        end\n      else if k == k0 then\n        (false, node3 t0 (k,v) t1 e1 t2)\n      else if k < k1 then\n        match recur t1 with\n        | (true, node2 s0 se0 s1) =>\n          (true, node2 (node2 t0 e0 s0) se0 (node2 s1 e1 t2))\n        | (_, s) => (false, node3 t0 e0 s e1 t2)\n        end\n      else if k == k1 then\n        (false, node3 t0 e0 t1 (k,v) t2)\n      else\n        match recur t2 with\n        | (true, s) =>\n          (true, node2 (node2 t0 e0 t1) e1 s)\n        | (_, s) => (false, node3 t0 e0 t1 e1 s)\n        end\n    end.\n\n  Lemma tree_append_preserve_depth(t:tree) (k:TK) (v:TV):\n    let (r,t') := tree_append k v t in\n    (tree_depth t' =\n      if r then (tree_depth t) .+1 else tree_depth t) /\\\n    match r,t' with\n    | false,_ => true\n    | _,node2 _ _ _ => true\n    | _,_ => false\n    end.\n  Proof.\n    elim: t => [|t0 Ht0 [k0 v0] t1 Ht1\n                |t0 Ht0 [k0 v0] t1 Ht1 [k1 v1] t2 Ht2] /=.\n    - done.\n    - case: (compare3P TK k k0) => Hk.\n      - case: (tree_append k v t0) Ht0 => [[|] s].\n        - case: s => [|s0 se0 s1|s se0 s1 se1 s2] /= [[Ht0]] // _.\n          by rewrite maxnA Ht0.\n        - by move=> [<- _].\n      - done.\n      - case: (tree_append k v t1) Ht1 => [[|] s].\n        - case: s => [|s0 se0 s1|s se0 s1 se1 s2] /= [[Ht1]] // _.\n          by rewrite Ht1.\n        - by move=> [<- _].\n    - case: (compare3P TK k k0) => Hk0;\n          [| |case: (compare3P TK k k1) => Hk1].\n      - case: (tree_append k v t0) Ht0 => [[|] s].\n        - case: s => [|s0 se0 s1|s se0 s1 se1 s2] /= [[Ht0]] // _.\n          by rewrite maxnSS Ht0.\n        - by move=> [<- _].\n      - done.\n      - case: (tree_append k v t1) Ht1 => [[|] s].\n        - case: s => [|s0 se0 s1|s se0 s1 se1 s2] /= [[Ht1]] // _.\n          by rewrite maxnSS -maxnA (maxnA (tree_depth s0)) Ht1.\n        - by move=> [<- _].\n      - done.\n      - case: (tree_append k v t2) Ht2 => [[|] s].\n        - case: s => [|s0 se0 s1|s se0 s1 se1 s2] /= [[Ht2]] // _.\n          by rewrite maxnSS -maxnA Ht2.\n        - by move=> [<- _].\n  Qed.\n\n  Lemma maxn_eq m : maxn m m = m.\n  Proof.\n    by unfold maxn; case (m < m)%N.\n  Qed.\n\n  Lemma tree_append_preserves_depth_validity(t:tree) (k:TK) (v:TV):\n      tree_check_depth t -> tree_check_depth (tree_append k v t).2.\n  Proof.\n    elim: t => [|t0 Ht0 [k0 v0] t1 Ht1\n                |t0 Ht0 [k0 v0] t1 Ht1 [k1 v1] t2 Ht2] /=.\n    - done.\n    - case: (compare3P TK k k0) => Hk.\n      - case: (tree_append k v t0)\n              (tree_append_preserve_depth t0 k v) Ht0 => [[|] s].\n        - case: s => [|s0 se0 s1|s se0 s1 se1 s2] /= [[Hpd]] // _ Ht0A Ht0B.\n          move: Ht0B Hpd => /and3P [/eqP<- /Ht0A/and3P[/eqP<- -> ->] ->] <-.\n          by rewrite maxn_eq eq_refl.\n        - by move=> /= [-> _] Ht0 /and3P [-> /Ht0-> ->].\n      - done.\n      - case: (tree_append k v t1)\n              (tree_append_preserve_depth t1 k v) Ht1 => [[|] s].\n        - case: s => [|s0 se0 s1|s se0 s1 se1 s2] /= [[Hpd]] // _ Ht1A Ht1B.\n          move: Ht1B Hpd => /and3P [/eqP<- ->/Ht1A/and3P[/eqP<- -> ->]] <-.\n          by rewrite maxn_eq eq_refl.\n        - by move=> /= [-> _] Ht1 /and3P [-> -> /Ht1->].\n    - case: (compare3P TK k k0) => Hk0;\n          [| |case: (compare3P TK k k1) => Hk1].\n      - case: (tree_append k v t0)\n              (tree_append_preserve_depth t0 k v) Ht0 => [[|] s].\n        - case: s => [|s0 se0 s1|s se0 s1 se1 s2] /= [[Hpd]] // _ Ht0A Ht0B.\n          move: Ht0B Hpd =>\n              /and5P[/eqP-> /eqP<- /Ht0A/and3P[/eqP<- -> ->] -> ->] ->.\n          by rewrite maxn_eq eq_refl eq_refl eq_refl.\n        - by move=> /= [-> _] Ht0 /and5P[-> -> /Ht0-> -> ->].\n      - done.\n      - case: (tree_append k v t1)\n              (tree_append_preserve_depth t1 k v) Ht1 => [[|] s].\n        - case: s => [|s0 se0 s1|s se0 s1 se1 s2] /= [[Hpd]] // _ Ht1A Ht1B.\n          move: Ht1B Hpd =>\n              /and5P[/eqP-> /eqP<- -> /Ht1A/and3P[/eqP<- -> ->] ->].\n          rewrite maxn_eq=> <-.\n          by rewrite eq_refl eq_refl.\n        - by move=> /= [-> _] Ht1 /and5P[-> -> -> /Ht1-> ->].\n      - done.\n      - case: (tree_append k v t2)\n              (tree_append_preserve_depth t2 k v) Ht2 => [[|] s].\n        - case: s => [|s0 se0 s1|s se0 s1 se1 s2] /= [[Hpd]] // _ Ht2A Ht2B.\n          move: Ht2B Hpd =>\n              /and5P[/eqP-> /eqP<- -> -> /Ht2A/and3P[/eqP<- -> ->]] ->.\n          by rewrite maxn_eq eq_refl eq_refl eq_refl.\n        - by move=> /= [-> _] Ht2 /and5P[-> -> -> -> /Ht2->].\n  Qed.\n  Lemma tree_append_preserves_order_validity(t:tree)\n      (k:TK) (v:TV) (lb ub:option TK):\n      (if lb is Some lbs then lbs < k else true) ->\n      (if ub is Some ubs then k < ubs else true) ->\n      tree_check_ordered t lb ub -> tree_check_ordered (tree_append k v t).2 lb ub.\n  Proof.\n    elim: t lb ub => [|t0 Ht0 [k0 v0] t1 Ht1\n                |t0 Ht0 [k0 v0] t1 Ht1 [k1 v1] t2 Ht2] /=.\n    - by move=> lb ub -> -> _.\n    - case: (compare3P TK k k0) => Hk.\n      - case: (tree_append k v t0) Ht0\n            => [[|] [|s0 [sk0 sv0] s1|s [sk0 sv0] s1 [sk1 sv1] s2]]\n               /= Ht0A lb ub Hlb Hub /andP[Ht0B ->];\n          try by rewrite (Ht0A lb (Some k0) Hlb Hk Ht0B).\n        by rewrite Bool.andb_true_r Ht0A.\n      - by move: Hk => /eqP<-.\n      - by case: (tree_append k v t1) Ht1\n               => [[|] [|s0 [sk0 sv0] s1|s [sk0 sv0] s1 [sk1 sv1] s2]]\n                  /= Ht1A lb ub Hlb Hub /andP[-> Ht1B];\n           rewrite (Ht1A _ _ _ Hub Ht1B).\n    - case: (compare3P TK k k0) => Hk0;\n          [| |case: (compare3P TK k k1) => Hk1].\n      - by case: (tree_append k v t0) Ht0\n               => [[|] [|s0 se0 s1|s se0 s1 se1 s2]]\n                  /= Ht0A lb ub Hlb Hub /and3P[Ht0B -> ->];\n           rewrite (Ht0A _ _ Hlb _ Ht0B).\n      - by move: Hk0 => /eqP<-.\n      - case: (tree_append k v t1) Ht1\n            => [[|] [|s0 [sk0 sv0] s1|s [sk0 sv0] s1 [sk1 sv1] s2]]\n                     /= Ht1A lb ub Hlb Hub /and3P[-> Ht1B ->];\n          try by move: (Ht1A (Some k0) (Some k1) Hk0 Hk1 Ht1B)=> /andP [-> ->].\n        - by rewrite (lt_trans _ _ _ _ Hk0 Hk1).\n        - by rewrite (lt_trans _ _ _ _ Hk0 Hk1).\n      - by move: Hk1 => /eqP<-.\n      - by case: (tree_append k v t2) Ht2\n               => [[|] [|s0 se0 s1|s se0 s1 se1 s2]]\n                  /= Ht2A lb ub Hlb Hub /and3P[-> -> Ht2B];\n           rewrite (Ht2A _ _ _ Hub Ht2B).\n  Qed.\n\n  Lemma tree_append_preserves_validity(t:tree) (k:TK) (v:TV):\n      tree_valid t -> tree_valid (tree_append k v t).2.\n  Proof.\n    move=> /andP[valid_order valid_depth].\n    by rewrite /tree_valid\n        (tree_append_preserves_order_validity t k v None None isT isT valid_order)\n        (tree_append_preserves_depth_validity t k v valid_depth).\n  Qed.\n\n  Definition append(t:T23) (k:TK) (v:TV):T23 :=\n      exist _ (tree_append k v (proj1_sig t)).2\n      (tree_append_preserves_validity (proj1_sig t) k v (proj2_sig t)).\nEnd Def.", "meta": {"author": "qnighy", "repo": "T23", "sha": "4520e2b58a46a698a732def4ec3dc1965bb20c94", "save_path": "github-repos/coq/qnighy-T23", "path": "github-repos/coq/qnighy-T23/T23-4520e2b58a46a698a732def4ec3dc1965bb20c94/T23.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529778109184, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6745753468549611}}
{"text": "(* isomorphism.v *)\n\n(* ********** *)\n\nRequire Import Arith.\n\n(* ********** *)\n\n(* Tao's representation: *)\n\nInductive int : Type :=\n| Int : nat -> nat -> int.\n\nNotation \"a -- b\" := (Int a b) (at level 70, no associativity).\n\n(* Signed integer representation: *)\n\nInductive sint : Type :=\n| P : nat -> sint\n| Z : sint\n| N : nat -> sint.\n\n(* ********** *)\n\n(* Tao's integer equality: *)\n\nDefinition int_eq (x y : int) : Prop :=\n  match x, y with\n  | (a -- b), (c -- d) =>\n    a + d = c + b\n  end.\n\nDefinition int_eqb (x y : int) : bool :=\n  match x, y with\n  | (a -- b), (c -- d) =>\n    a + d =? c + b\n  end.\n\nDefinition test_int_of_sint (int_of_sint : sint -> int) : bool :=\n  (int_eqb (int_of_sint Z) (0 -- 0))\n    && (int_eqb (int_of_sint Z) (3 -- 3))\n    && (int_eqb (int_of_sint Z) (9 -- 9))\n    && (int_eqb (int_of_sint (P 0)) (1 -- 0))\n    && (int_eqb (int_of_sint (P 15)) (16 -- 0))\n    && (int_eqb (int_of_sint (P 4)) (7 -- 2))\n    && (int_eqb (int_of_sint (P 7)) (20 -- 12))\n    && (int_eqb (int_of_sint (N 0)) (0 -- 1))\n    && (int_eqb (int_of_sint (N 6)) (0 -- 7))\n    && (int_eqb (int_of_sint (N 9)) (6 -- 16))\n    && (int_eqb (int_of_sint (N 13)) (14 -- 28)).\n\nDefinition int_of_sint (x : sint) :=\n  match x with\n  | P px =>\n    (px + 1 -- 0)\n  | Z => (0 -- 0)\n  | N nx =>\n    (0 -- nx + 1)\n  end.\n\nCompute (test_int_of_sint int_of_sint).\n\n(* ********** *)\n\n(* Signed integer equality: *)\n\nDefinition sint_eq (i1 i2 : sint) : Prop :=\n  match i1 with\n  | P n1 =>\n    match i2 with\n    | P n2 =>\n      n1 = n2\n    | Z =>\n      False\n    | N n2 =>\n      False\n    end\n  | Z =>\n    match i2 with\n    | P n2 =>\n      False\n    | Z =>\n      True\n    | N n2 =>\n      False\n    end\n  | N n1 =>\n    match i2 with\n    | P n2 =>\n      False\n    | Z =>\n      False\n    | N n2 =>\n      n1 = n2\n    end\n  end.\n\nDefinition sint_eqb (i1 i2 : sint) : bool :=\n  match i1 with\n  | P n1 =>\n    match i2 with\n    | P n2 =>\n      n1 =? n2\n    | Z =>\n      false\n    | N n2 =>\n      false\n    end\n  | Z =>\n    match i2 with\n    | P n2 =>\n      false\n    | Z =>\n      true\n    | N n2 =>\n      false\n    end\n  | N n1 =>\n    match i2 with\n    | P n2 =>\n      false\n    | Z =>\n      false\n    | N n2 =>\n      n1 =? n2\n    end\n  end.\n\nDefinition test_sint_of_int (sint_of_int : int -> sint) : bool :=\n  (sint_eqb (sint_of_int (0 -- 0)) Z)\n    && (sint_eqb (sint_of_int (7 -- 7)) Z)\n    && (sint_eqb (sint_of_int (9 -- 8)) (P 0))\n    && (sint_eqb (sint_of_int (8 -- 9)) (N 0))\n    && (sint_eqb (sint_of_int (13 -- 2)) (P 10))\n    && (sint_eqb (sint_of_int (9 -- 15)) (N 5)).\n\nDefinition sint_of_int (x : int) :=\n  match x with\n  | (a -- b) =>\n    if a =? b\n    then Z\n    else if a <? b\n         then N (b - a - 1)\n         else P (a - b - 1)\n  end.\n\nCompute (test_sint_of_int sint_of_int).\n\n(* ********** *)\n\nProposition int_of_sint_and_back :\n  forall x : sint,\n    sint_eq x (sint_of_int (int_of_sint x)).\nProof.\n  intros [px |  | nx];\n    unfold int_of_sint, sint_of_int, sint_eq.\n  - Search (0 < S _).\n    assert (H_lt := Nat.lt_0_succ px).\n    case (px + 1 =? 0) as [ | ] eqn:H_eqb.\n    + assert (H_eq := beq_nat_true (px + 1) 0 H_eqb).\n      rewrite -> Nat.add_1_r in H_eq.\n      Search (_ < _ -> _ <> _).\n      contradiction (lt_0_neq (S px) H_lt (eq_sym H_eq)).\n    + case (px + 1 <? 0) as [ | ] eqn:H_ltb.\n      -- Search (_ < _ -> _).\n         assert (H_nlt := Nat.lt_asymm 0 (S px) H_lt).\n         unfold not in H_nlt.\n         destruct (Nat.ltb_lt (px + 1) 0) as [H_ltb_lt _].\n         assert (H_lt_absurd := H_ltb_lt H_ltb);\n           clear H_ltb_lt.\n         rewrite -> Nat.add_1_r in H_lt_absurd.\n         contradiction (H_nlt H_lt_absurd).\n      -- Search (_ - 0).\n         rewrite -> Nat.sub_0_r.\n         Search (_ + _ - _).\n         rewrite -> Nat.add_sub.\n         reflexivity.\n  - Search (Nat.eqb).\n    rewrite -> (Nat.eqb_refl 0).\n    exact I.\n  - Search (0 < S _).\n    assert (H_lt := Nat.lt_0_succ nx).\n    case (0 =? nx + 1) as [ | ] eqn:H_eqb.\n    + assert (H_eq := beq_nat_true 0 (nx + 1) H_eqb).\n      rewrite -> Nat.add_1_r in H_eq.\n      contradiction (lt_0_neq (S nx) H_lt H_eq).\n    + case (0 <? nx + 1) as [ | ] eqn:H_ltb.\n      -- rewrite -> Nat.sub_0_r.\n         rewrite -> Nat.add_sub.\n         reflexivity.\n      -- Search (_ <? _).\n         destruct (Nat.ltb_nlt 0 (nx + 1)) as [H_ltb_nlt _].\n         assert (H_nlt := H_ltb_nlt H_ltb);\n           clear H_ltb_nlt.\n         rewrite -> Nat.add_1_r in H_nlt.\n         unfold not in H_nlt.\n         contradiction (H_nlt H_lt).\nQed.\n         \nProposition sint_of_int_and_back :\n  forall x : int,\n    int_eq x (int_of_sint (sint_of_int x)).\nProof.\n  intros [a b].\n  unfold sint_of_int.\n  case (a =? b) as [ | ] eqn:H_eqb;\n    unfold int_of_sint, int_eq.\n  - rewrite -> Nat.add_0_r.\n    rewrite -> Nat.add_0_l.\n    exact (beq_nat_true a b H_eqb).\n  - case (a <? b) as [ | ] eqn:H_ltb.\n    + destruct (Nat.ltb_lt a b) as [H_ltb_lt _].\n      assert (H_lt := H_ltb_lt H_ltb);\n        clear H_ltb_lt; clear H_ltb.\n      Search (_ - _ + _).\n      Check (Nat.sub_add 1 (b - a)).\n      Search (_ < _ - _).\n      destruct (Nat.lt_add_lt_sub_r 0 b a) as [H_lt_add_sub _].\n      rewrite <- (Nat.add_0_l a) in H_lt.\n      assert (H_lt_sub := H_lt_add_sub H_lt);\n        clear H_lt_add_sub.\n      Search (_ < _ -> _ <= _).\n      assert (H_le_S := lt_le_S 0 (b - a) H_lt_sub).\n      rewrite -> (Nat.sub_add 1 (b - a) H_le_S).\n      Search (_ + _ - _).\n      rewrite -> Nat.add_0_l in H_lt.\n      rewrite -> (Nat.add_sub_assoc\n                    a b a (Nat.lt_le_incl a b H_lt)).\n      rewrite -> minus_plus.\n      rewrite -> Nat.add_0_l.\n      reflexivity.\n    + destruct (Nat.ltb_ge a b) as [H_ltb_ge _].\n      assert (H_ge := H_ltb_ge H_ltb);\n        clear H_ltb_ge.\n      assert (H_neq := beq_nat_false a b H_eqb).\n      Search ( _ <= _ /\\ _ <> _).\n      destruct (Nat.le_neq b a) as [_ H_le_neq].\n      assert (H_gt := H_le_neq (conj H_ge (Nat.neq_sym a b H_neq)));\n        clear H_le_neq.\n      destruct (Nat.lt_add_lt_sub_r 0 a b) as [H_lt_add_sub _].\n      rewrite <- Nat.add_0_l in H_gt at 1.\n      assert (H_gt_sub := H_lt_add_sub H_gt);\n        clear H_lt_add_sub.\n      assert (H_ge_S := lt_le_S 0 (a - b) H_gt_sub);\n        clear H_gt_sub.\n      rewrite -> (Nat.sub_add 1 (a - b) H_ge_S).\n      rewrite -> Nat.add_0_l in H_gt.\n      rewrite -> (Nat.sub_add b a H_ge).\n      rewrite -> Nat.add_0_r.\n      reflexivity.\nQed.\n\n(* ********** *)\n\n(* end of isomorphism.v *)\n", "meta": {"author": "wli-linda", "repo": "tao_tcpa", "sha": "d40daf9778e70bf782311bbda69967a72c9f6ddf", "save_path": "github-repos/coq/wli-linda-tao_tcpa", "path": "github-repos/coq/wli-linda-tao_tcpa/tao_tcpa-d40daf9778e70bf782311bbda69967a72c9f6ddf/isomorphism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.6744523311223116}}
{"text": "Require Import HoTT.\nRequire Import HoTT.Basics.PathGroupoids.\n\nTheorem fibers_equiv : forall (X : Type) (E : X -> Type) (x y : X)\n                              (f : x = y), E(x) <~> E(y).\nProof.\n  intros.\n  split with (equiv_fun:=(transport E f)).\n  simple refine (BuildIsEquiv _ _ _ (transport E (f^)) _ _ _).  \n  intro. induction f. simpl. reflexivity.\n  intro. induction f. simpl. reflexivity.\n  intro. simpl. induction f. simpl. reflexivity.\nQed.\n\nTheorem equiv_fibers : forall (X : Type) (E1 E2 : X -> Type),\n    ((sig E1) <~> (sig E2)) -> forall x, E1(x) <~> E2(x).\nProof.\n  intros X E1 E2 h. intro x.\n  \n", "meta": {"author": "co-dan", "repo": "hott-snippets", "sha": "0257a0e921c3d920a1dc58769afb2d9407123855", "save_path": "github-repos/coq/co-dan-hott-snippets", "path": "github-repos/coq/co-dan-hott-snippets/hott-snippets-0257a0e921c3d920a1dc58769afb2d9407123855/fibers_transport.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009480320035, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6744266912725424}}
{"text": "(*|\nA few things to keep in mind as you work through pset 1\n=======================================================\n|*)\n\nRequire Import Frap.\n\n(*|\nCoq resources\n-------------\n\n- Start by looking for examples in the course textbook, including the tactic appendix at the end of the book.\n\n- For help on standard Coq tactics, consult Coq's reference manual (https://coq.inria.fr/distrib/current/refman/), starting from the indices at https://coq.inria.fr/distrib/current/refman/appendix/indexes/index.html.  The manual can be overwhelming, so it's best used for looking up fine details.\n\nUseful commands\n---------------\n\nCoq comes with many predefined types, functions, and theorems (“objects”).  The most important commands to help you discover them are `Check`, `About`, `Print`, `Search`, and `Compute`.  Try the following examples:\n\n`Check` gives the type of any term, even with holes:\n|*)\n\nCheck (1 + _).\nCheck (fun b => match b with true => 0 | false => 1 end).\n\n(*|\n`About` gives general information about an object:\n|*)\n\nAbout bool.\nAbout nat.\n\n(*|\n`Print` displays the definition of an object:\n|*)\n\nPrint bool.\nPrint Nat.add.\n\n(*|\n`Search` finds objects.  Its syntax is very flexible:\n|*)\n\n(* Find functions of type [nat -> nat -> bool]. *)\nSearch (nat -> nat -> bool).\n(* Find theorems about \"+\". *)\nSearch \"+\".\n(* Find theorems whose statement mentions S and eq. *)\nSearch eq S.\n(* Search for a lemma proving the symmetry of eq. *)\nSearch (?x = ?y -> ?y = ?x).\n\n(*|\nIf you are puzzled by a notation, the `Locate` command can help:\n|*)\n\nLocate \"*\".\n\n(*|\nTo evaluate an expression, use `Compute`:\n|*)\n\nCompute (2 * 3, 4 + 4, 0 - 2 + 2, pred (S (S (S 0)))).\n\n(*|\nSyntax recap\n------------\n\nTo define a function inline, use `fun`:\n|*)\n\nCheck (fun x => x + 1).\nCheck (fun x: bool => xorb x x).\n\n(*|\nTo perform a case analysis on a value, use `match`:\n|*)\n\nCheck (fun b (x y: nat) =>\n         match b with\n         | true => x\n         | false => y\n         end).\n\nCheck (fun (n: nat) =>\n         match n with\n         | 0 => 1\n         | S n => n\n         end).\n\n(*|\nIn Coq, `if` is just short for `match`:\n|*)\n\nCheck (fun (b: bool) (x y: nat) =>\n         if b then x else y).\n\n(*|\nTo define a global object, use `Definition` or `Lemma` (`Theorem` is an alias of `Lemma`):\n|*)\n\nDefinition choose (b: bool) (x y: nat) :=\n  if b then x else y.\n\nCompute (choose true 6 822).\n\nLemma plus_commutes :\n  forall x, x = x + 0 + 0.\nProof.\n  intros.\n  Search (_ + 0).\n  rewrite <- plus_n_O.\n  rewrite <- plus_n_O.\n  equality.\nQed.\n\n(*|\nRecursive functions use the keyword `Fixpoint`:\n|*)\n\nFixpoint do_n_times (ntimes: nat) (step: nat -> nat) (start_from: nat) :=\n  match ntimes with\n  | 0 => start_from\n  | S ntimes' => step (do_n_times ntimes' step start_from)\n  end.\n\nCompute (6, do_n_times 12 (fun x => x + 65) 42).\n\n(*|\nYou can use bullets or braces to structure your proofs:\n|*)\n\nLemma both_zero:\n  forall x y z: nat, x + y + z = 0 -> x = 0 /\\ y = 0 /\\ z = 0.\nProof.\n  intros x.\n  cases x.\n  - intros.\n    cases y.\n    + propositional.\n    + simplify.\n      invert H.\n  - intros y z Heq.\n    simplify.\n    invert Heq.\nQed.\n\n(*|\nA few gotchas\n-------------\n\nNatural numbers saturate at 0:\n|*)\n\nCompute (3 - 5 + 3).\n\n(*|\nThe order in which you perform induction on variables matters: if `x` comes before `y` and you induct on `y`, your induction hypothesis will not be general enough.\n|*)\n\nLemma add_comm:\n  forall x y: nat, x + y = y + x.\nProof.\n  induct y.\n  - induct x; simplify; equality.\n  - simplify.\n    (* `IHy` is valid only for one specific `y` *)\nAbort.\n\nLemma add_comm:\n  forall x y: nat, x + y = y + x.\nProof.\n  induct x.\n  - induct y; simplify; equality.\n  - simplify.\n    (* `IHx` starts with `forall y`. *)\nAbort.\n\n(*|\nHere's an example where this subtlety matters:\n|*)\n\nFixpoint factorial (n: nat) :=\n  match n with\n  | O => 1\n  | S n' => n * factorial n'\n  end.\n\nFixpoint factorial_acc (n: nat) (acc: nat) :=\n  match n with\n  | O => acc\n  | S n' => factorial_acc n' (n * acc)\n  end.\n\n(*|\nFirst attempt, but our lemma is too weak.\n|*)\n\nLemma factorial_acc_correct:\n  forall n, factorial n = factorial_acc n 1.\nProof.\n  induct n.\n  - equality.\n  - simplify.\n    Search (_ * 1).\n    rewrite Nat.mul_1_r.\n\n(*|\nStuck!  We have no way to simplify `factorial_acc n (S n)`.\n|*)\n\nAbort.\n\n(*|\nSecond attempt: a generalized lemma, but we put the `acc` first, so induction will not generalize it.\n|*)\n\nLemma factorial_acc_correct:\n  forall acc n, factorial n * acc = factorial_acc n acc.\nProof.\n  induct n.\n  - simplify.\n    Search (_ + 0).\n    rewrite Nat.add_0_r.\n    equality.\n  - simplify.\n    Fail rewrite <- IHn.\n\n(*|\nStuck!  IHn is too weak.\n|*)\n\nAbort.\n\n(*|\nThird time's the charm!  Note how we ordered `n` and `acc`.\n|*)\n\nLemma factorial_acc_correct:\n  forall n acc, factorial n * acc = factorial_acc n acc.\nProof.\n  induct n.\n  - simplify.\n    linear_arithmetic.\n  - simplify.\n\n(*|\nIHn is strong enough now!\n|*)\n\n    rewrite <- IHn.\n    linear_arithmetic.\nQed.\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/Tips.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.8933094010836642, "lm_q1q2_score": 0.6743726646391772}}
{"text": "(*########################################################*)\n(*#-------3 Main Properties and other related terms------#*)\n(*########################################################*) \n\n\n\n\nRequire Export Definitions.\n\nSet Implicit Arguments.\n\n\nSection Properties.\n\n\nSection competitiveness.\n\nDefinition bcompetitive (b b':order):= (Nat.ltb (oprice b') (oprice b)) ||\n((Nat.eqb (oprice b') (oprice b)) && (Nat.leb (otime b) (otime b') )).\n\n\nDefinition acompetitive (a a':order):= (Nat.ltb (oprice a) (oprice a')) ||\n((Nat.eqb (oprice a) (oprice a')) && (Nat.leb (otime a) (otime a') )).\n\nDefinition eqcompetitive (a a':order):= ((Nat.eqb (oprice a) (oprice a')) && (Nat.eqb (otime a) (otime a') )).\n\n\nLemma bcompetitive_contadiction (b b':order):\nbcompetitive b b'-> bcompetitive b' b -> ~eqcompetitive b b' -> False.\nProof. unfold bcompetitive.  unfold eqcompetitive. intros. \n       move /orP in H. move /orP in H0. destruct H0; destruct H.\n       {  move /ltP in H. move /ltP in H0. lia. }\n       {  destruct H1. move /andP in H. destruct H.\n          apply /andP. move /eqP in H.  split. apply /eqP. \n          auto. move /ltP in H0. move /leP in H1. lia. }\n       {  destruct H1. move /andP in H0. destruct H0.\n          apply /andP. move /eqP in H0.  split. apply /eqP. \n          auto. move /ltP in H. move /leP in H1. lia. }\n       {  destruct H1. move /andP in H0. destruct H0.\n          move /andP in H. destruct H. apply /andP. split.\n          auto. move /leP in H1. move /leP in H2. apply /eqP. lia. } Qed.\n\nLemma acompetitive_contadiction (a a':order):\nacompetitive a a'-> acompetitive a' a -> ~eqcompetitive a a' -> False.\nProof. unfold acompetitive.  unfold eqcompetitive. intros. \n       move /orP in H. move /orP in H0. destruct H0; destruct H.\n       {  move /ltP in H. move /ltP in H0. lia. }\n       {  destruct H1. move /andP in H. destruct H.\n          apply /andP. move /eqP in H.  split. apply /eqP. \n          auto. move /ltP in H0. move /leP in H1. lia. }\n       {  destruct H1. move /andP in H0. destruct H0.\n          apply /andP. move /eqP in H0.  split. apply /eqP. \n          auto. move /ltP in H. move /leP in H1. lia. }\n       {  destruct H1. move /andP in H0. destruct H0.\n          move /andP in H. destruct H. apply /andP. split.\n          auto. move /leP in H1. move /leP in H2. apply /eqP. lia. } Qed.\n\nLemma bcompetitive_P : transitive bcompetitive /\\ comparable2 bcompetitive.\nProof.  { split.\n          { unfold transitive. unfold bcompetitive.  \n            intros y x z H H1. move /orP in H1. move /orP in H.\n            apply /orP. destruct H1;destruct H. \n            { left. move /leP in H0. move /leP in H. apply /leP. lia. }\n            { move /andP in H. destruct H. left.  \n              move /leP in H0. move /eqP in H. apply /leP. lia. }\n            { move /andP in H0. destruct H0. left.\n              move /leP in H. move /eqP in H0. apply /leP. lia. }\n            { move /andP in H0. move /andP in H. destruct H0. destruct H.\n              right.\n              move /eqP in H. move /eqP in H0. apply /andP.\n              split. apply /eqP. lia. apply /leP. move /leP in H1. \n              move /leP in H2. lia. } }\n            { unfold comparable2.\n              unfold bcompetitive. intros. destruct x. destruct y.  simpl. \n              assert((oprice0 = oprice)\\/(oprice0 < oprice)\\/(oprice < oprice0)).\n              lia. destruct H.\n              subst. assert(Nat.ltb oprice oprice = false).\n              apply /ltP. lia. rewrite H. simpl.\n              assert(Nat.eqb oprice oprice =true). auto. rewrite H0. simpl. \n              assert((otime0 <= otime)\\/(otime < otime0)). lia. destruct H1.\n              right. apply /leP. auto. left. apply /leP. lia.\n              destruct H. left. apply /orP. left. apply /ltP. auto. right.\n              apply /orP. left. apply /ltP. auto.\n               } } Qed.\n\nLemma acompetitive_P : transitive acompetitive /\\ comparable2 acompetitive.\nProof.  { split.\n          { unfold transitive. unfold acompetitive.  \n            intros y x z H H1. move /orP in H1. move /orP in H.\n            apply /orP. destruct H1;destruct H. \n            { left. move /leP in H0. move /leP in H. apply /leP. lia. }\n            { move /andP in H. destruct H. left.  \n              move /leP in H0. move /eqP in H. apply /leP. lia. }\n            { move /andP in H0. destruct H0. left.\n              move /leP in H. move /eqP in H0. apply /leP. lia. }\n            { move /andP in H0. move /andP in H. destruct H0. destruct H.\n              right.\n              move /eqP in H. move /eqP in H0. apply /andP.\n              split. apply /eqP. lia. apply /leP. move /leP in H1. \n              move /leP in H2. lia. } }\n            { unfold comparable2.\n              unfold acompetitive. intros. destruct x. destruct y.  simpl. \n              assert((oprice0 = oprice)\\/(oprice < oprice0)\\/(oprice0 < oprice)).\n              lia. destruct H.\n              subst. assert(Nat.ltb oprice oprice = false).\n              apply /ltP. lia. rewrite H. simpl.\n              assert(Nat.eqb oprice oprice =true). auto. rewrite H0. simpl. \n              assert((otime0 <= otime)\\/(otime < otime0)). lia. destruct H1.\n              right. apply /leP. auto. left. apply /leP. lia.\n              destruct H. left. apply /orP. left. apply /ltP. auto. right.\n              apply /orP. left. apply /ltP. auto.\n               } } Qed.\n\nLemma not_acompetitive (a1 a2:order): ~acompetitive a1 a2 -> acompetitive a2 a1.\nProof. unfold acompetitive. intros H. unfold not in H. apply /orP.\n       destruct(Nat.ltb (oprice a1) (oprice a2)) eqn:H1. \n       { simpl in H. destruct H. auto. }\n       { simpl in H.  destruct(Nat.eqb (oprice a1) (oprice a2)) eqn: H2.\n          { simpl in H. destruct (Nat.leb (otime a1) (otime a2)) eqn: H3.\n           destruct H. auto. right. apply /andP. split. move /eqP in H2.\n           rewrite H2. apply /eqP. auto. move /leP in H3. apply /leP. lia. }\n          { simpl in H. destruct (Nat.leb (otime a1) (otime a2)) eqn: H3.\n            move /ltP in H1. move /eqP in H2. left. apply /ltP. lia. \n            move /ltP in H1. move /eqP in H2. move /leP in H3. \n            left. apply /ltP. lia.\n           }\n         }\n         Qed.  \n\nLemma not_bcompetitive (b1 b2:order): ~bcompetitive b1 b2 -> bcompetitive b2 b1.\nProof. unfold bcompetitive. intros H. unfold not in H. apply /orP.\n       destruct(Nat.ltb (oprice b2) (oprice b1)) eqn:H1. \n       { simpl in H. destruct H. auto. }\n       { simpl in H.  destruct(Nat.eqb (oprice b2) (oprice b1)) eqn: H2.\n          { simpl in H. destruct (Nat.leb (otime b1) (otime b2)) eqn: H3.\n           destruct H. auto. right. apply /andP. split. move /eqP in H2.\n           rewrite H2. apply /eqP. auto. move /leP in H3. apply /leP. lia. }\n          { destruct (Nat.leb (otime b1) (otime b2)) eqn: H3.\n            move /ltP in H1. move /eqP in H2. left. apply /ltP. lia. \n            move /ltP in H1. move /eqP in H2. move /leP in H3. \n            left. apply /ltP. lia.\n           }\n         }\n         Qed.  \n\n\n\nEnd competitiveness.\n\nNotation \"s === t\" := (perm s t) (at level 80, no associativity).\n\nInductive command:Set:= \n|buy\n|sell\n|del.\n\nRecord instruction :Type:= Mk_instruction { cmd : command; ord : order}.\nDefinition action0:=del.\nDefinition tau0:={| cmd := action0; ord := w0 |}.\n\nDefinition Absorb (B A: list order)(tau: instruction):=\nmatch (cmd tau) with\n|buy => ((ord tau)::B, A)\n|sell =>(B, (ord tau)::A)\n|del =>(delete_order B (id (ord tau)), delete_order A (id (ord tau)))\nend. \n\nLemma Absorb_perm (B1 B2 A1 A2 : list order)(tau: instruction):\nperm B1 B2 -> perm A1 A2 ->\nperm (fst (Absorb B1 A1 tau)) (fst (Absorb B2 A2 tau))/\\\nperm (snd (Absorb B1 A1 tau)) (snd (Absorb B2 A2 tau)).\nProof. case (cmd tau) eqn:H. unfold Absorb. replace (cmd tau) with buy. simpl. eauto.\nunfold Absorb. replace (cmd tau) with sell. simpl. eauto.\nunfold Absorb. replace (cmd tau) with del. simpl. intros. split.\napply delete_order_perm. auto. apply delete_order_perm. auto. Qed.\n\nLemma Absorb_notIn_nodup_id (B A: list order)(tau: instruction):\nNoDup (ids B) ->NoDup (ids A) -> ~In (id (ord tau)) (ids B) -> ~In (id (ord tau)) (ids A) ->\nNoDup (ids (fst (Absorb B A tau)))/\\NoDup (ids (snd (Absorb B A tau))).\nProof. intros. case (cmd tau) eqn:Ht. \nsplit. unfold Absorb. replace (cmd tau) with buy. simpl. eauto.\nunfold Absorb. replace (cmd tau) with buy. simpl. eauto.\nunfold Absorb. replace (cmd tau) with sell. simpl. eauto.\nunfold Absorb. replace (cmd tau) with del. simpl. split.\napply delete_order_ids_nodup. auto. apply delete_order_ids_nodup. auto.\nQed.\n\nLemma Absorb_del_nodup_id (B A: list order)(tau: instruction):\nNoDup (ids B) ->NoDup (ids A) -> (cmd tau ) = del ->\nNoDup (ids (fst (Absorb B A tau)))/\\NoDup (ids (snd (Absorb B A tau))).\nProof. intros. unfold Absorb. rewrite H1. simpl. split. apply delete_order_ids_nodup. auto. apply delete_order_ids_nodup. auto. Qed.\n\nLemma Absorb_notIn_nodup_time (B A: list order)(tau: instruction):\nNoDup (timesof B) ->NoDup (timesof A) -> ~In (otime (ord tau)) (timesof B) -> \n~In (otime (ord tau)) (timesof A) ->\nNoDup (timesof (fst (Absorb B A tau)))/\\NoDup (timesof (snd (Absorb B A tau))). \nProof. intros. case (cmd tau) eqn:Ht. \nunfold Absorb. replace (cmd tau) with buy. simpl. eauto. \nunfold Absorb. replace (cmd tau) with sell. simpl. eauto. \nunfold Absorb. replace (cmd tau) with del. simpl.\nsplit. apply delete_order_timesof_nodup. auto. apply delete_order_timesof_nodup. auto.\nQed.\n\n\n\nDefinition Condition1 (M: list transaction)(B A hat_B hat_A: list order)\n(tau: instruction):Prop:=\nnot (matchable hat_B hat_A). \n\nDefinition Condition2a (M: list transaction)(B:list order):Prop:=\nforall b b', (In b B)/\\(In b' B)/\\(bcompetitive b b'/\\~eqcompetitive b b')/\\(In (id b') (ids_bid_aux M)) -> \n(Qty_bid M (id b)) = (oquantity b).\n\n\nDefinition Condition2b (M: list transaction)(A:list order):Prop:=\nforall a a', (In a A)/\\(In a' A)/\\(acompetitive a a'/\\~eqcompetitive a a')/\\(In (id a') (ids_ask_aux M)) -> \n(Qty_ask M (id a)) = (oquantity a).\n\n\nDefinition Condition3a (M: list transaction)(B A: list order)\n(tau: instruction):Prop:=\nlet B' := (fst (Absorb B A tau)) in\nlet A' := (snd (Absorb B A tau)) in\nMatching M B' A'.\n\nDefinition Condition3b (M: list transaction)(B A hat_B: list order)\n(tau: instruction):Prop:=\nlet B' := (fst (Absorb B A tau)) in\nhat_B === (odiff B' (bids M B')).\n\nDefinition Condition3c (M: list transaction)(B A hat_A: list order) \n(tau: instruction):Prop:=\nlet A' := (snd (Absorb B A tau)) in\n(hat_A === (odiff A' (asks M A'))).\n\nDefinition admissible (B A :list order) := \n(NoDup (ids B))/\\(NoDup (ids A))/\\\n(NoDup (timesof B))/\\(NoDup (timesof A)).\n\n\nDefinition Legal_input (B A :list order)(tau: instruction):=\nadmissible (fst (Absorb B A tau)) (snd (Absorb B A tau))/\\\nnot (matchable B A).\n\n\nLemma legal_perm (B1 B2 A1 A2 : list order)(tau: instruction):\nperm B1 B2/\\ perm A1 A2/\\Legal_input B1 A1 tau -> Legal_input B2 A2 tau.\nProof. unfold Legal_input. intros H. destruct H. destruct H0. \ndestruct H1 as [Hb Ha]. unfold admissible in Hb. \ndestruct Hb as [Hb Hc]. destruct Hc as [Hc Hd].  destruct Hd as [Hd He].\nassert(G1:=H). assert(G2:=H0).\nunfold perm in G1. move /andP in G1. destruct G1 as [G1a G1b].\nunfold perm in G2. move /andP in G2. destruct G2 as [G2a G2b].  \napply Absorb_perm with (B1:=B1)(B2:=B2)(tau:=tau) in H0.\ndestruct H0. repeat split.   \napply ids_perm in H0. eauto. \napply ids_perm in H1. eauto. \napply timesof_perm in H0. eauto. \napply timesof_perm in H1. eauto.  \nintro. destruct Ha.\nunfold matchable in H2. destruct H2. destruct H2.\nunfold matchable. exists x. exists x0. destruct H2.\ndestruct H3. \nsplit. eauto. split. eauto. auto. auto. Qed. \n\nDefinition Properties (Process: (list order) ->(list order) ->instruction\n-> (list order)*(list order)*(list transaction)):=\nforall A B tau,\nLegal_input B A tau -> \nlet B' := (fst (Absorb B A tau)) in\nlet A' := (snd (Absorb B A tau)) in\nlet hat_B := (Blist (Process B A tau)) in\nlet hat_A := (Alist (Process B A tau)) in\nlet M := (Mlist (Process B A tau)) in\n\nCondition1 M B A hat_B hat_A tau /\\\nCondition2a M B'/\\\nCondition2b M A'/\\\nCondition3a M B A tau /\\\nCondition3b M B A hat_B tau /\\\nCondition3c M B A hat_A tau.\n\n(*----------------Term require for Gloal theorem part----------------*)\n\nFixpoint orders (I:list instruction) :(list order):=\nmatch I with\n|nil => nil\n|i::I' => (ord i)::orders I'\nend.\n\n\nFixpoint tilln (l: list order)(k:nat):=\nmatch (l,k) with \n|(nil, 0) => nil \n|(x::l', 0) => x::nil \n|(nil, S k) => nil\n|(hd::tail, S k) => hd::(tilln tail k)\nend.\n\n\nLemma tilln_contains_nth (l: list order)(k:nat):\nl<>nil/\\|l|>=k+1 -> In (nth k l w0) (tilln l k).\nProof. revert k. induction l. intros. destruct H. destruct H. auto.\n       destruct k.  simpl. auto. simpl. \n       intros. destruct H. assert(l<>nil). intro.\n       subst l. simpl in H0. lia. right. apply IHl. split.\n       auto. lia. Qed.\n\n\nLemma tilln_Subset_whole (l: list order)(k:nat):\nSubset (tilln l k) l.\nProof. revert k. induction l. destruct k eqn: Hk. simpl. auto.\nsimpl. auto. destruct k eqn: Hk. simpl. auto. simpl. \napply Subset_intro. auto. Qed.\n\n\nLemma tilln_Subset_next (I: list order)(k:nat):\nSubset (tilln I (k-1)) (tilln I k).\nProof. revert I. induction k. simpl. auto. intros. \nreplace (S k -1) with k. destruct k. destruct I. simpl. auto.\nsimpl. auto. destruct I. simpl. auto. simpl. \nreplace (S k -1) with k in IHk. specialize (IHk I).\neauto. lia. lia. Qed.\n\n\nLemma timesof_nodup_notIn (B: list order)(k: nat): \nNoDup (timesof B) -> Sorted Nat.ltb (timesof B) -> \nS k <= (| B |) -> k>0 ->\n~In (otime (nth k B w0)) (timesof (tilln B (k - 1))).\nProof. revert B. induction k. intros. lia. \n destruct B. simpl. intros. lia. replace (S k -1) with k.\ndestruct k. simpl. intros. destruct B. simpl in H1. lia.\nsimpl. intro. destruct H3.\napply Sorted_elim4 with (x:= (otime o0)) in H0. move /ltP in H0.  lia.\nsimpl.  auto.  auto. simpl. intros. assert(In (nth (S k) B w0) B).\nassert(In (nth (S k) B w0) (tilln B (S k))).\napply tilln_contains_nth. split. intro.\nsubst B. simpl in H1. lia. lia. assert(Subset (tilln B (S k)) B).\napply tilln_Subset_whole. auto. intro.\ndestruct H4. apply timesof_elim in H3. \napply Sorted_elim4 with (x:= (otime (nth (S k) B w0))) in H0. \nmove /ltP in H0.  lia.  auto. assert(S (S k) <= (| B |)). lia.\napply IHk in H5. replace (S k -1) with k in H5.\ndestruct (H5 H4). lia. eauto. eauto. lia. lia. Qed.\n\n\nLemma ordersI_length (I:list instruction) :\n|I| = |orders I|.\nProof. induction I. simpl;auto. simpl;lia. Qed.\n\nLemma ordersI_nil (I:list instruction) :\nI <> nil -> (orders I) <> nil.\nProof. intros. induction I. destruct H. auto. simpl. \n       intro. inversion H0. Qed.\n\n\nDefinition structured (I :list instruction):= \n(forall t:nat,  (t+1) <= (length I) -> (cmd (nth t I tau0) = del)\\/\n(~In (id (ord (nth t I tau0))) (ids (tilln (orders I) (t-1))))\\/\n((id (ord (nth t I tau0))) = (id (ord (nth (t-1) I tau0)))/\\ \n(cmd (nth (t-1) I tau0) = del)))\n/\\ Sorted (Nat.ltb) (timesof (orders I))/\\ NoDup ((timesof (orders I))).\n\nFixpoint iterate (P: (list order)->(list order) -> instruction -> (list order)*(list order)*(list transaction))\n(I : list instruction)(k:nat) :=\nmatch k with\n|0 => (nil, nil, nil) \n| S k' =>  let it:=(iterate P I k') in P (Blist it) (Alist it) \n    (nth k' I tau0)\nend.\n\n\nDefinition iterated (P: (list order)->(list order) -> instruction -> (list order)*(list order)*(list transaction))\n(I : list instruction)(k:nat) := \nif (Nat.ltb (length I) k) then (nil,nil,nil) else iterate P I k.\n\nEnd Properties.", "meta": {"author": "suneel-sarswat", "repo": "cda", "sha": "ba1cd68cfa8f997495f9f00951b196de96ef3c68", "save_path": "github-repos/coq/suneel-sarswat-cda", "path": "github-repos/coq/suneel-sarswat-cda/cda-ba1cd68cfa8f997495f9f00951b196de96ef3c68/formalization/Properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6743726628287552}}
{"text": "Lemma eq_sym : forall (X : Type)(x y : X), x = y -> y = x.\nintros X x y A.\nrewrite A.\nreflexivity.\nQed.\n\nLemma modus_ponens : forall X Y : Prop, X -> (X -> Y) -> Y.\nintros X Y x A.\nexact (A x).\nQed.\n\nLemma barbara : forall X Y Z : Prop, (X -> Y) -> (Y -> Z) -> (X -> Z).\nintros X Y Z A B x.\nexact (B (A x)).\nQed.\n\n\nLemma eq_trans : forall (X : Type)(x y z : X), x = y -> y = z -> x = z.\nintros.\ntransitivity y.\nassumption.\napply H0.\nQed.\n\nLemma const : forall X Y, X -> Y -> X.\nintros.\napply X0.\nQed.\n\nGoal forall X Y, (forall Z, (X -> Y -> Z) ->\n Z) -> X.\nintros X Y Z0.\napply Z0.\napply const.\nQed.\n\nLemma const' : forall X Y, X -> Y -> Y.\nintros.\napply X1.\nQed.\n\n\nGoal forall X Y, (forall Z, (X -> Y -> Z) -> Z) -> Y.\nintros.\napply X0.\napply const'.\nQed.\n\nLemma leibniz_equality : forall (X : Type)(x y : X),(forall p : X -> Prop, p x -> p y) -> x = y.\nintros.\napply (H (fun z => x = z)).\nreflexivity.\nQed.\n\nGoal forall X : Type, (fun x : X => x) = (fun y : X => y).\nintros.\nreflexivity.\nQed.\n\nGoal forall X : Prop, X -> ~~X.\nintros X x A.\nexact (A x).\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/Computational_Logic3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6743726619588598}}
{"text": "From Coq Require Import Arith NArith Lia.\nRequire Import Nibble Instructions List2 Logic2.\n\n(** This is N(i, w) defined in (141), quite close to the paper. *)\nDefinition paper_next_valid_instruction_position (i: N) (b: byte)\n:= let push1  := N_of_byte (byte_of_instruction (PUSH  1 eq_refl)) in\n   let push32 := N_of_byte (byte_of_instruction (PUSH 32 eq_refl)) in\n   let w := N_of_byte b in\n   (if ((push1 <=? w)  &&  (w <=? push32))%bool\n     then i + w - push1 + 2\n     else i + 1)%N.\n\n(** This is a nicer equivalent of the previous function. *)\nDefinition next_valid_instruction_position (i: N) (b: byte)\n:= (i + match instruction_of_byte b with\n        | Some (PUSH n _) => n + 1\n        | _               => 1\n        end)%N.\n\nLemma next_valid_instruction_position_ok (i: N) (b: byte):\n  next_valid_instruction_position i b = paper_next_valid_instruction_position i b.\nProof.\nunfold paper_next_valid_instruction_position.\nmatch goal with\n|- _ = if ?cond then (i + ?a - ?b + ?c)%N else (i + 1)%N =>\n    replace (if cond then (i + a - b + c)%N else (i + 1)%N) \n      with  (i + if cond then a - b + c else 1)%N\nend.\n2:{\n  remember (andb _ _) as cond. destruct cond.\n  repeat (rewrite N.add_sub_assoc || rewrite N.add_assoc). 1-3: trivial.\n  symmetry in Heqcond.\n  apply Bool.andb_true_iff in Heqcond.\n  apply N.leb_le. tauto.\n}\nunfold next_valid_instruction_position.\nf_equal.\n(* this is stupid, we need an is_push test *)\ndestruct b as (b7, b6, b5, b4, b3, b2, b1, b0).\ndestruct b7; destruct b6; destruct b5; destruct b4;\ndestruct b3; destruct b2; destruct b1; destruct b0; trivial.\nQed.\n\nLemma next_valid_instruction_position_bound (i: N) (b: byte):\n  (i + 1 <= next_valid_instruction_position i b)%N.\nProof.\nunfold next_valid_instruction_position.\ndestruct (instruction_of_byte b) as [op|]; try destruct op; try apply N.le_refl.\nlia.\nQed.\n\n(**\n   This is as close to D_J(c, i) defined in (140) as feasible,\n   however, fuel had to be introduced to satisfy Coq's termination check.\n *)\nFixpoint paper_valid_jump_destinations_from (code: list byte)\n                                             (i: N)\n                                             (fuel: nat)\n: list N\n:= match fuel with\n   | O => nil\n   | S remaining_fuel =>\n      match List.nth_error code (N.to_nat i) with\n      | None => nil\n      | Some b =>\n         let tail := paper_valid_jump_destinations_from\n                       code\n                       (next_valid_instruction_position i b)\n                       remaining_fuel\n         in if (N_of_byte b =? N_of_byte (byte_of_instruction JUMPDEST))%N\n                then i :: tail\n                else tail\n      end\n   end.\n\nLocal Lemma valid_jump_destinations_from_2_helper\n                (code: list byte)\n                (i: N)\n                (b: byte)\n                (code_tail: list byte)\n                (ok: code_tail = List.skipn (N.to_nat i) code):\n  let next := next_valid_instruction_position i b in\n  List.skipn (N.to_nat (next - i)) code_tail = List.skipn (N.to_nat next) code.\nProof.\nsubst. intro. unfold next_valid_instruction_position in next.\nrewrite skipn_skipn.\nf_equal. subst next.\nrewrite N.add_comm.\nrewrite<- N.add_sub_assoc by apply N.le_refl.\nrewrite N.sub_diag.\nrewrite N.add_0_r.\nsymmetry. apply N2Nat.inj_add.\nQed.\n\n(* This version carries around the code tail so that it doesn't have to count from the start. *)\nLocal Fixpoint valid_jump_destinations_from_2 (code: list byte)\n                                                (i: N)\n                                                (fuel: nat)\n                                                (code_tail: list byte)\n                                                (ok: code_tail = List.skipn (N.to_nat i) code)\n: list N\n:= match fuel with\n   | O => nil\n   | S remaining_fuel =>\n      match List.hd_error code_tail with\n      | None => nil\n      | Some b =>\n         let next := next_valid_instruction_position i b in\n         let tail := valid_jump_destinations_from_2\n                       code\n                       next\n                       remaining_fuel\n                       (List.skipn (N.to_nat (next - i)) code_tail)\n                       (valid_jump_destinations_from_2_helper code i b code_tail ok)\n         in if (N_of_byte b =? N_of_byte (byte_of_instruction JUMPDEST))%N\n                then (i :: tail)%list\n                else tail\n      end\n   end.\n\nLocal Lemma valid_jump_destinations_from_2_ok (code: list byte)\n                                                (i: N)\n                                                (fuel: nat)\n                                                (code_tail: list byte)\n                                                (ok: code_tail = List.skipn (N.to_nat i) code):\n  paper_valid_jump_destinations_from code i fuel\n   =\n  valid_jump_destinations_from_2 code i fuel code_tail ok.\nProof.\nrevert ok. revert code_tail. revert i code.\ninduction fuel. { easy. }\nintros. cbn.\nsubst code_tail. rewrite<- List2.nth_hd_skipn.\ndestruct (List.nth_error code (N.to_nat i)). 2:{ trivial. }\ndestruct (N_of_byte b =? _)%N; now rewrite<- IHfuel.\nQed.\n\n(* This version replaces hd_error with a match and also drops [code] and [ok] parameters. *)\nLocal Fixpoint valid_jump_destinations_from_3 (code_tail: list byte)\n                                                (i: N)\n                                                (fuel: nat)\n: list N\n:= match fuel with\n   | O => nil\n   | S remaining_fuel =>\n      match code_tail with\n      | nil => nil\n      | (b :: _)%list =>\n         let next := next_valid_instruction_position i b in\n         let tail := valid_jump_destinations_from_3\n                       (List.skipn (N.to_nat (next - i)) code_tail)\n                       next\n                       remaining_fuel\n         in if (N_of_byte b =? N_of_byte (byte_of_instruction JUMPDEST))%N\n                then (i :: tail)%list\n                else tail\n      end\n   end.\n\nLocal Lemma valid_jump_destinations_from_3_ok (code: list byte)\n                                               (i: N)\n                                               (fuel: nat)\n                                               (code_tail: list byte)\n                                               (ok: code_tail = List.skipn (N.to_nat i) code):\n  valid_jump_destinations_from_3 code_tail i fuel\n   =\n  valid_jump_destinations_from_2 code i fuel code_tail ok.\nProof.\nrevert code i code_tail ok.\ninduction fuel. { easy. }\nintros. cbn.\ndestruct code_tail; cbn. { trivial. }\ndestruct (N_of_byte b =? _)%N; now rewrite<- IHfuel.\nQed.\n\n(* This version gets rid of the fuel and does skipping by itself. *)\nLocal Fixpoint valid_jump_destinations_from_4 (code: list byte) (current: N) (next_valid: N)\n: list N\n:= match code with\n   | nil => nil\n   | (h :: t)%list =>\n        if (current <? next_valid)%N\n           then valid_jump_destinations_from_4 t (current + 1)%N next_valid\n           else\n             let tail := valid_jump_destinations_from_4 t \n                                                        (current + 1)%N\n                                                        (next_valid_instruction_position current h)\n             in if (N_of_byte h =? N_of_byte (byte_of_instruction JUMPDEST))%N\n                  then (current :: tail)%list\n                  else tail\n  end.\n\nLocal Lemma valid_jump_destinations_from_4_skips (code: list byte) (current: N) (next_valid: N)\n                                                  (ok: (current <= next_valid)%N):\n  valid_jump_destinations_from_4 code current next_valid\n   =\n  valid_jump_destinations_from_4 (List.skipn (N.to_nat (next_valid - current)) code) \n                                 next_valid \n                                 next_valid.\nProof.\nremember (N.to_nat (next_valid - current)) as k.\nassert(K: next_valid = (current + N.of_nat k)%N) by lia.\nclear Heqk ok. subst next_valid.\nrevert code current.\ninduction k; intros. { cbn. now repeat rewrite N.add_0_r. }\ndestruct code; cbn. { trivial. }\nreplace (current <? current + N.pos (Pos.of_succ_nat k))%N with true. \n2:{\n  symmetry.\n  apply N.ltb_lt.\n  lia.\n}\nreplace (current + N.pos (Pos.of_succ_nat k))%N with (current + 1 + N.of_nat k)%N by lia.\napply IHk.\nQed.\n\nLocal Lemma valid_jump_destinations_from_4_ok (code: list byte)\n                                               (i: N)\n                                               (fuel: nat)\n                                               (EnoughFuel: (length code < fuel)%nat):\n  valid_jump_destinations_from_4 code i i\n   =\n  valid_jump_destinations_from_3 code i fuel.\nProof.\nrevert code EnoughFuel i.\ninduction fuel; intros. { now apply Nat.nlt_0_r in EnoughFuel. }\ncbn. destruct code. { easy. }\ncbn.\nreplace (i <? i)%N with false.\n2:{ symmetry. apply (b_false (N.ltb_lt _ _)). apply N.lt_irrefl. }\nreplace (valid_jump_destinations_from_4 code (i + 1) (next_valid_instruction_position i b))\n  with (valid_jump_destinations_from_3\n        (List.skipn (N.to_nat (next_valid_instruction_position i b - i)) (b :: code))\n        (next_valid_instruction_position i b) fuel).\n{ trivial. }\nassert (B := next_valid_instruction_position_bound i b).\nrewrite valid_jump_destinations_from_4_skips by assumption.\nsymmetry. rewrite IHfuel.\n{ \n  replace (N.to_nat (next_valid_instruction_position i b - i))\n     with (S ((N.to_nat (next_valid_instruction_position i b - (i + 1))))) by lia.\n  now rewrite List.skipn_cons.\n}\nrewrite List.skipn_length.\ncbn in EnoughFuel.\nlia.\nQed.", "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/JumpDest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139576, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6743726563959936}}
{"text": "Require Import NArith.\nRequire Import PArith.\nRequire Import ZArith.\nRequire Import Lia.\nRequire Import EquivDec.\nFrom sflib Require Import sflib.\n\nRequire Import PromisingArch.lib.Basic.\nRequire Import PromisingArch.lib.Order.\n\nSet Implicit Arguments.\n\n\nModule Time.\n  Include Nat.\n\n  Definition pred_opt (ts:t): option t :=\n    match ts with\n    | O => None\n    | S n => Some n\n    end.\n\n  (* Definition le (a b:t) := a <= b. *)\n  Definition join (a b:t) := max a b.\n  Definition bot: t := 0.\n\n  Global Program Instance order: orderC join bot.\n  Next Obligation. unfold join. lia. Qed.\n  Next Obligation. unfold join. lia. Qed.\n  Next Obligation. eauto using Max.max_assoc. Qed.\n  Next Obligation. eauto using Max.max_comm. Qed.\n  Next Obligation. unfold join. lia. Qed.\n  Next Obligation. unfold bot. lia. Qed.\n\n  Global Instance eqdec: EqDec t eq := nat_eq_eqdec.\nEnd Time.\n", "meta": {"author": "snu-sf", "repo": "promising-arm", "sha": "10291375ccd03152eadf739d280e2c59e10fa9af", "save_path": "github-repos/coq/snu-sf-promising-arm", "path": "github-repos/coq/snu-sf-promising-arm/promising-arm-10291375ccd03152eadf739d280e2c59e10fa9af/src/lib/Time.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.674372650833127}}
{"text": "Require Coq.Logic.Classical_Prop.\nRequire Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.lemma_onray_shared_initial_point.\nRequire Import ProofCheckingEuclid.lemma_s_conga.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_equalangleshelper :\n\tforall A B C a b c p q,\n\tCongA A B C a b c ->\n\tOnRay b a p ->\n\tOnRay b c q ->\n\tCongA A B C p b q.\nProof.\n\tintros A B C a b c p q.\n\tintros CongA_ABC_abc.\n\tintros OnRay_ba_p.\n\tintros OnRay_bc_q.\n\n\tdestruct CongA_ABC_abc 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_onray_shared_initial_point _ _ _ _ OnRay_ba_p OnRay_ba_u) as OnRay_bp_u.\n\tpose proof (lemma_onray_shared_initial_point _ _ _ _ OnRay_bc_q OnRay_bc_v) as OnRay_bq_v.\n\n\tpose proof (\n\t\tlemma_s_conga\n\t\tA B C p b q\n\t\t_ _ _ _\n\t\tOnRay_BA_U\n\t\tOnRay_BC_V\n\t\tOnRay_bp_u\n\t\tOnRay_bq_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_pbq.\n\n\texact CongA_ABC_pbq.\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_equalangleshelper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.6743518347372415}}
{"text": "Require Import Ensembles Relations.\nSet Implicit Arguments.\nImplicit Arguments In [U].\n\nDefinition var := nat.\nInductive formula : Set :=\n| Atom : var -> formula\n| Bot : formula\n| And : formula -> formula -> formula\n| Or : formula -> formula -> formula\n| Imp : formula -> formula -> formula.\nInfix \"'->\" := Imp (at level 70, right associativity).\nInfix \"'\\/\" := Or (at level 60).\nInfix \"'/\\\" := And (at level 50).\nCoercion Atom : var >-> formula.\n\nInductive provable : Ensemble formula -> formula -> Prop :=\n| By_axiom : forall fs f, In fs f -> provable fs f\n| By_K : forall fs f g, provable fs (f '-> g '-> f)\n| By_S : forall fs f g h,\n  provable fs ((f '-> g '-> h) '-> (f '-> g) '-> (f '-> h))\n| By_proj1 : forall fs f g, provable fs (f '/\\ g '-> f)\n| By_proj2 : forall fs f g, provable fs (f '/\\ g '-> g)\n| By_conj : forall fs f g, provable fs (f '-> g '-> f '/\\ g)\n| By_in1 : forall fs f g, provable fs (f '-> f '\\/ g)\n| By_in2 : forall fs f g, provable fs (g '-> f '\\/ g)\n| By_case : forall fs f g h,\n  provable fs ((f '-> h) '-> (g '-> h) '-> (f '\\/ g '-> h))\n| By_exfalso : forall fs f, provable fs (Bot '-> f)\n| By_MP : forall fs f g,\n  provable fs (f '-> g) -> provable fs f -> provable fs g.\n\nHint Constructors provable.\n\nModule Type KRIPKE_MODEL.\n  Parameter W : Type.\n  Parameter R : relation W.\n  Axiom R_refl : reflexive _ R.\n  Axiom R_trans : transitive _ R.\n  Parameter V : W -> var -> Prop.\n  Axiom monotone : forall x y p, V x p -> R x y -> V y p.\nEnd KRIPKE_MODEL.\n\nModule Kripke_Semantics (K : KRIPKE_MODEL).\n  Export K.\n\n  Fixpoint satisfies x f :=\n    match f with\n      | Atom p => V x p\n      | Bot => False\n      | And f f' => satisfies x f /\\ satisfies x f'\n      | Or f f' => satisfies x f \\/ satisfies x f'\n      | Imp f f' => forall y, R x y -> satisfies y f -> satisfies y f'\n    end.\n\n  Hint Resolve R_refl R_trans monotone.\n  Lemma hereditary : forall x y f, \n    satisfies x f -> R x y -> satisfies y f.\n    induction f; simpl; intuition eauto.\n  Qed.\n\n  Theorem soundness : forall fs f x,\n    provable fs f -> (forall g, In fs g -> satisfies x g) -> satisfies x f.\n    induction 1; simpl; intuition; eauto using hereditary.\n  Qed.\nEnd Kripke_Semantics.\n\nLemma deduction_theorem' : forall fs fs' f g,\n  provable fs' g -> fs' = Add _ fs f -> provable fs (f '-> g).\n  induction 1; intro; subst; [| eauto ..].\n  inversion H; try inversion H0; subst; eauto.\n  Existential 1 := Bot.\n  Existential 1 := Bot.\n  Existential 1 := Bot.\nQed.\n\nLemma deduction_theorem : forall fs f g,\n  provable (Add _ fs f) g -> provable fs (f '-> g).\n  eauto using deduction_theorem'.\nQed.\n\nLemma weakening : forall fs f g, provable fs f -> provable (Add _ fs g) f.\n  induction 1; solve [repeat constructor; auto | eauto]. \nQed.\n\nHint Constructors Union Singleton.\nHint Extern 1 (provable (Add _ _ _) _) => unfold Add.\n\nLemma converse_deduction_theorem :\n  forall fs f g, provable fs (f '-> g) -> provable (Add _ fs f) g.\n  intros; apply (@By_MP _ f g); auto using weakening.\nQed.\n\nModule Canonical_Model <: KRIPKE_MODEL.\n  Definition prime fs :=\n    forall f g, provable fs (f '\\/ g) -> provable fs f \\/ provable fs g.\n  Definition consistent fs := ~provable fs Bot.\n\n  Definition W := { T : Ensemble formula | prime T /\\ consistent T }.\n\n  Definition R (x y : W) :=\n    forall f, provable (proj1_sig x) f -> provable (proj1_sig y) f.\n  Hint Unfold R Included.\n  Lemma R_refl : forall x, R x x.\n    auto.\n  Qed.\n  Lemma R_trans : forall x y z, R x y -> R y z -> R x z.\n    auto.\n  Qed.\n  Definition V (x : W) (p : var) := provable (proj1_sig x) p.\n  Hint Unfold V.\n  Lemma monotone : forall x y p, V x p -> R x y -> V y p.\n    intuition.\n  Qed.\nEnd Canonical_Model.\n\nModule Canonical_Model_facts.\n  Module M := Kripke_Semantics Canonical_Model.\n  \n  Import M.\n\n  Hint Unfold R.\n\n  Axiom prime_lemma : forall fs f,\n    (forall x : W, (forall g, provable fs g -> provable (proj1_sig x) g) ->\n      provable (proj1_sig x) f) ->\n    provable fs f.\n\n  Ltac destruct_iff :=\n    match goal with\n      [ H : forall _, _ <-> _ |- _] =>\n      pose proof (fun x => proj1 (H x));\n        pose proof (fun x => proj2 (H x));\n          clear H\n    end.\n\n  Lemma equivalence : forall f x, provable (proj1_sig x) f <-> satisfies x f.\n    induction f;\n      intro x; destruct x as [T [? ?]];\n        simpl in *; intuition;\n          repeat destruct_iff; eauto 3.\n\n    assert (provable T f1 /\\ provable T f2) by firstorder.\n    intuition; eauto.\n\n    assert (provable T f1 \\/ provable T f2) by auto; intuition.\n\n    assert (provable T f1) by firstorder.\n    eauto.\n\n    assert (provable T f2) by firstorder.\n    eauto.\n\n    eauto.\n\n    apply deduction_theorem.\n    apply prime_lemma.\n    auto 8 using weakening.\n  Qed.\n\n  Hint Resolve (fun f x => proj1 (equivalence f x)).\n  Hint Resolve (fun f x => proj2 (equivalence f x)).\n\n  Theorem completeness : forall fs f,\n    (forall T, (forall g, In fs g -> satisfies T g) -> satisfies T f) ->\n    provable fs f.\n    auto 7 using prime_lemma.\n  Qed.\nEnd Canonical_Model_facts.\n", "meta": {"author": "kozima", "repo": "completenessproofs", "sha": "fe99b9f41e7dfdba14fabbe7849f0edada605872", "save_path": "github-repos/coq/kozima-completenessproofs", "path": "github-repos/coq/kozima-completenessproofs/completenessproofs-fe99b9f41e7dfdba14fabbe7849f0edada605872/ipc_Kripke.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.6743518210182595}}
{"text": "\nRequire Export Iron.Language.SystemF2Cap.Type.Exp.\nRequire Export Iron.Language.SystemF2Cap.Type.Relation.WfT.\nRequire Export Iron.Language.SystemF2Cap.Type.Relation.FreeT.\n\n\n(*******************************************************************)\n(* Lift type indices that are at least a certain depth. *)\nFixpoint liftTT (n: nat) (d: nat) (tt: ty) : ty :=\n match tt with\n |  TVar ix\n => match nat_compare ix d with\n    | Lt => tt\n    | _  => TVar (ix + n)\n    end\n\n |  TForall k t    => TForall k (liftTT n (S d) t)\n |  TApp t1 t2     => TApp      (liftTT n d t1) (liftTT n d t2)\n |  TSum t1 t2     => TSum      (liftTT n d t1) (liftTT n d t2)\n |  TBot k         => TBot  k\n\n |  TCon0 tc       => TCon0 tc\n |  TCon1 tc t1    => TCon1 tc  (liftTT n d t1)\n |  TCon2 tc t1 t2 => TCon2 tc  (liftTT n d t1) (liftTT n d t2)\n |  TCap  _        => tt\n end.\nHint Unfold liftTT.\n\n\n(********************************************************************)\nLemma liftTT_TVar_exists\n : forall n d n1\n , exists n2, liftTT n d (TVar n1) = liftTT n d (TVar n2).\nProof.\n intros.\n unfold liftTT. exists n1. snorm.\nQed.\n\n\nLemma liftTT_TVar_not_zero\n : forall t\n , liftTT 1 0 t <> TVar 0.\nProof.\n intros.\n destruct t;\n  try (solve [unfold not; snorm; inverts H; omega]);\n  try (solve [unfold not; snorm; nope]).\nQed.\nHint Resolve liftTT_TVar_not_zero.\n\n\nLemma liftTT_TVar_not_succ\n : forall t d\n ,             t <> TVar d\n -> liftTT 1 0 t <> TVar (S d).\nProof.\n intros. gen d.\n destruct t; intros;\n   try (solve [simpl; congruence]).\n\n - Case \"TVar\".\n   unfold liftTT. \n   snorm.\n   + subst. congruence.\n   + unfold not. intros. \n     inverts H0. omega.\n   + congruence.\nQed.\nHint Resolve liftTT_TVar_not_succ.\n\n\nLemma liftTT_TVar_above\n :  forall n i d\n ,  d > i \n -> liftTT n d (TVar i) = TVar i.\nProof.\n snorm; omega.\nQed.\nHint Resolve liftTT_TVar_above.\n\n\nLemma liftTT_isTVar_true\n :  forall n i t d\n ,  d > i\n -> IsTVar i (liftTT n d t)\n -> IsTVar i t.\nProof.\n intros.\n  destruct t; \n   try (solve [simpl; auto]).\n\n - Case \"TVar\".\n   apply isTVar_form in H0.\n   snorm; inverts H0; unfold IsTVar; snorm;\n    rewrite beq_nat_true_iff; omega.\nQed.\nHint Resolve liftTT_isTVar_true.\n\n\nLemma liftTT_TCap\n :  forall n d t tc\n ,  liftTT n d t = TCap tc\n -> t            = TCap tc.\nProof.\n intros.\n destruct t; simpl in *; nope.\n  snorm; nope.\nQed.\n\n\nLemma liftTT_wfT\n :  forall kn t d\n ,  WfT kn t\n -> WfT (S kn) (liftTT 1 d t).\nProof.\n intros. gen kn d.\n induction t; intros; inverts H; snorm.\nQed.\nHint Resolve liftTT_wfT.\n\n\nLemma liftTT_zero\n :  forall d t\n ,  liftTT 0 d t = t.\nProof.\n intros. gen d. lift_burn t.\nQed.\nHint Resolve liftTT_zero.\nHint Rewrite liftTT_zero : global.\n\n\nLemma liftTT_comm\n :  forall n m d t\n ,  liftTT n d (liftTT m d t)\n =  liftTT m d (liftTT n d t).\nProof.\n intros. gen d. lift_burn t.\nQed.\nHint Resolve liftTT_comm.\n\n\nLemma liftTT_succ\n :  forall n m d t\n ,  liftTT (S n) d (liftTT m     d t)\n =  liftTT n     d (liftTT (S m) d t).\nProof.\n intros. gen d m n. lift_burn t.\nQed.\nHint Resolve liftTT_succ.\nHint Rewrite liftTT_succ : global. \n\n\nLemma liftTT_plus\n : forall n m d t\n , liftTT (n + m) d t \n = liftTT n d (liftTT m d t).\nProof.\n intros. gen n d.\n induction m; intros.\n - rewrite liftTT_zero; burn.\n - rrwrite (n + S m = S n + m).\n   rewrite IHm.\n   rewrite liftTT_succ.\n   auto.\nQed. \nHint Resolve liftTT_plus.\nHint Rewrite liftTT_plus : global.\n\n\nLemma liftTT_wfT_1\n :  forall t n ix\n ,  WfT n t\n -> liftTT 1 (n + ix) t = t.\nProof.\n intros. gen n ix.\n induction t; intros; inverts H; burn;\n  try (solve [snorm; rewritess; burn]).\n\n - Case \"TForall\".\n   snorm. f_equal.\n   spec IHt H1.\n   rrwrite (S (n + ix) = S n + ix).\n   burn.\nQed.\nHint Resolve liftTT_wfT_1.\n\n\nLemma liftTT_closedT_id_1\n :  forall t d\n ,  ClosedT t\n -> liftTT 1 d t = t.\nProof.\n intros.\n rrwrite (d = d + 0). eauto.\nQed.\nHint Resolve liftTT_closedT_id_1.\n\n\nLemma liftTT_closedT_10\n :  forall t\n ,  ClosedT t\n -> ClosedT (liftTT 1 0 t).\nProof.\n intros. \n rrwrite (0 = 0 + 0).\n rewrite liftTT_wfT_1; auto.\nQed.\nHint Resolve liftTT_closedT_10.\n\n\n(* Changing the order of lifting.\n   We build this up in stages. \n   Start out by only allow lifting by a single place for both\n   applications. Then allow lifting by multiple places in the first\n   application, then multiple places in both. \n*)\nLemma liftTT_liftTT_11\n :  forall d d' t\n ,  liftTT 1 (1 + (d + d')) (liftTT 1 d t)\n =  liftTT 1 d              (liftTT 1 (d + d') t).\nProof.\n intros. gen d d'.\n induction t; intros.\n\n - Case \"TVar\".\n   repeat (lift_cases; unfold liftTT); try f_equal; try omega; burn.\n\n - Case \"TForall\".\n   snorm.   \n   rrwrite (S (d + d') = (S d) + d').\n   rewritess. snorm.\n\n - Case \"TApp\".\n   snorm; rewritess; auto.\n\n - Case \"TCon\".\n   snorm; rewritess; auto.\n\n - Case \"TBot\".\n   snorm; rewritess; auto.\n\n - Case \"TCon0\".\n   snorm; rewritess; auto.\n\n - Case \"TCon1\".\n   snorm; rewritess; auto.\n\n - Case \"TCon2\".\n   snorm; rewritess; auto.\n\n - Case \"TCap\".\n   snorm; rewritess; auto.\nQed.\n\n\nLemma liftTT_liftTT_1\n :  forall n1 m1 n2 t\n ,  liftTT m1   n1 (liftTT 1 (n2 + n1) t)\n =  liftTT 1 (m1 + n2 + n1) (liftTT m1 n1 t).\nProof.\n intros. gen n1 m1 n2 t.\n induction m1; intros; simpl.\n  burn. \n\n  rrwrite (S m1 = 1 + m1).\n  rewrite liftTT_plus.\n  rewritess.\n  rrwrite (m1 + n2 + n1 = n1 + (m1 + n2)) by omega.\n  rewrite <- liftTT_liftTT_11.\n  burn.\nQed.\n\n\nLemma liftTT_liftTT\n :  forall m1 n1 m2 n2 t\n ,  liftTT m2 (m1 + n2 + n1) (liftTT m1 n1 t)\n =  liftTT m1 n1 (liftTT m2 (n2 + n1) t).\nProof.\n intros. gen n1 m1 n2 t.\n induction m2; intros.\n  burn.\n  rrwrite (S m2 = 1 + m2).\n  rewrite liftTT_plus.\n  rewrite IHm2.\n  rewrite <- liftTT_liftTT_1.\n  burn.\nQed.\nHint Rewrite liftTT_liftTT : global.\n\n\nLemma liftTT_liftTT_Sd\n : forall n d t\n , liftTT n (S d) (liftTT 1 0 t)\n = liftTT 1 0     (liftTT n d t).\nProof.\n intros.\n lets D: liftTT_liftTT 1 0 n d t.\n simpl in D.\n rrwrite (d + 0 = d) in D.\n auto.\nQed.\nHint Rewrite liftTT_liftTT_Sd : global.\n\n\nLemma liftTT_map_liftTT\n :  forall m1 n1 m2 n2 ts\n ,  map (liftTT m1 n1) (map (liftTT m2 (n2 + n1)) ts)\n =  map (liftTT m2 (m1 + n2 + n1)) (map (liftTT m1 n1) ts).\nProof.\n induction ts; simpl; f_equal; norm; auto.\nQed.\n\n\nLemma liftTT_freeT\n : forall d t\n , ~(FreeT d (liftTT 1 d t)).\nProof.\n intros. gen d.\n induction t; snorm; firstorder.\nQed.\nHint Resolve liftTT_freeT.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/devel/Iron/Language/SystemF2Cap/Type/Operator/LiftTT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6743518074662643}}
{"text": "Require Import Arith.\nRequire Import Program.\nRequire Import Compare_dec.\n\nSet Implicit Arguments.\n\n(******************************************************************************)\n\nInductive variable : nat -> Set :=\n| var : forall g i, i < g -> variable g.\n\nInductive type : nat -> Set :=\n| ty_var    : forall g, variable g -> type g\n| ty_arr    : forall g, type g -> type g -> type g\n| ty_forall : forall g, type (S g) -> type g.\n\nDefinition shift_var : forall g c,\n  variable (c + g) -> variable (c + 1 + g).\nintros g c v. inversion v. subst.\ndestruct (le_lt_dec c i).\n apply var with (i:=S i). rewrite (plus_comm c 1). simpl. apply lt_n_S. assumption.\n apply var with (i:=i). rewrite <- plus_assoc. simpl. rewrite <- plus_Snm_nSm. apply le_S. assumption.\nDefined.\n\nDefinition shift (g : nat) (c : nat) :\n  type (c + g) -> type (c + 1 + g).\nintros.\nset (g':=c+g) in *. set (e:=refl_equal g' : g' = c+g). generalize g' H c e. clear g' H c e. intros g' H.\ninduction H; intros; subst.\n (* ty_var *)\n apply ty_var. apply shift_var. apply v.\n (* ty_arr *)\n apply ty_arr.\n  apply IHtype1. reflexivity.\n  apply IHtype2. reflexivity.\n (* ty_forall *)\n apply ty_forall.\n  change (S (c + 1 + g)) with ((S c) + 1 + g).\n  apply IHtype. reflexivity.\nDefined.\n\nDefinition shift1 : forall g, type g -> type (S g).\nintros.\nchange (S g) with (0 + 1 + g). \napply shift with (c:=0). apply H.\nDefined.\n\nDefinition subst_var (g c d : nat) (v : variable d) : \n d = c + 1 + g ->\n type (c + g) -> type (c + g).\nintros. destruct v. subst.\ndestruct (lt_eq_lt_dec i c) as [[X|X]|X].\n apply ty_var. apply var with (i:=i). apply lt_plus_trans. assumption.\n apply H0.\n destruct (O_or_S i) as [[i' i_eq_Si'] | i_eq_0].\n  apply ty_var. apply var with (i:=i'). subst. rewrite (plus_comm c 1) in l. simpl in l. apply lt_S_n. assumption.\n  elimtype False. subst. inversion X.\nDefined.\n\nDefinition subst (g : nat) (c : nat) :\n  type (c + g) ->\n  type (c + 1 + g) ->\n  type (c + g).\nintros. dependent induction H0.\n (* ty_var *)\n apply subst_var with (d:=c + 1 + g). assumption. reflexivity. assumption.\n (* ty_arr *)\n apply ty_arr.\n  apply IHtype1. apply H.\n  apply IHtype2. apply H.\n (* ty_forall *)\n apply ty_forall.\n apply IHtype with (c0:=S c). apply shift1. apply H. reflexivity.\nDefined.\n\nDefinition type_subst1 : forall g, type (S g) -> type g -> type g.\nintros. \nchange g with (0 + g).\napply subst. apply H0. apply H.\nDefined.\n", "meta": {"author": "bobatkey", "repo": "system-f-parametricity-model", "sha": "f34051fae684b9b066d355e3d33fcd1145bf08f7", "save_path": "github-repos/coq/bobatkey-system-f-parametricity-model", "path": "github-repos/coq/bobatkey-system-f-parametricity-model/system-f-parametricity-model-f34051fae684b9b066d355e3d33fcd1145bf08f7/TypeSyntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.6743518059342726}}
{"text": "\nSection MinimalPropositionalLogic.\n\nAxiom P : Prop.\nAxiom Q : Prop.\nAxiom R : Prop.\nAxiom T : Prop.\n\nTheorem ImplicationsAreTransitive : (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n  intro H0.\n  intro H1.\n  intro p.\n  apply H1.\n  apply H0.\n  assumption.\nQed.\n\nSection AssumptionExample.\n\nHypothesis H : P -> Q -> R.\n\nLemma L1 : P -> Q -> R.\nProof.\n  assumption.\nQed.\n\nEnd AssumptionExample.\n\nTheorem ApplyExample : (Q -> R -> T) -> (P -> Q) -> P -> R -> T.\nProof.\n  intros H1 H2 p.\n  apply H1.\n  exact (H2 p).\nQed.\n\n(*\nTheorem ImplicationIsDistributive : (forall A B C : Prop, (A -> (A -> B -> C) -> (A -> B) -> (B -> C))).\nProof.\n  intro A.\n  intro B.\n  intro C.\n  intro a.\n  intro H1.\n  intro H2.\n  intro H3.\n  apply H1.\n  assumption.\n  apply H3.\nQed.\n\n*)\n\n\nTheorem ImplicationIsDistributive : ((P -> Q -> R) -> (P -> Q) -> (P -> R)).\nProof.\n  intros H1 H2 p.\n  apply H1.\n  assumption.\n  exact (H2 p).\nQed.\n\nSection ExamplesCh3Section3.\n\nLemma Identity : (P -> P).\nProof.\n  intro p.\n  exact p.\nQed.\n\nLemma IdentityImplication : ((P -> P) -> (P -> P)).\nProof.\n  intro H0.\n  exact H0.\nQed.\n\nLemma ImplicationIsTransitive : ((P -> Q) -> (Q -> R) -> P -> R).\nProof.\n  intro H1.\n  intro H2.\n  intro p.\n  apply H2.\n  exact (H1 p).\nQed.\n\nLemma ImplicationPer : ((P -> Q -> R) -> (Q -> P -> R)).\nProof.\n  intro H1.\n  intro H2.\n  intro p.\n  apply H1.\n  - assumption.\n  - apply H2.\nQed.\n\nLemma IgnoreQ : ((P -> R) -> P -> Q -> R).\nProof.\n  intro H1.\n  intro H2.\n  intro H3.\n  apply H1.\n  apply H2.\nQed.\n\nLemma DeltaImplication : ((P -> Q) -> (P -> P -> Q)).\nProof.\n  intro H1.\n  intro H2.\n  intro H3.\n  apply H1.\n  apply H2.\nQed.\n\nLemma DeltaImplicationReverse : ((P -> P -> Q) -> P -> Q).\nProof.\n  intro H1.\n  intro H2.\n  apply H1.\n  assumption.\n  assumption.\nQed.\n\nLemma Diamond : ((P -> Q) -> (P -> R) -> (Q -> R -> T) -> P -> T).\nProof.\n  intro H1.\n  intro H2.\n  intro H3.\n  intro H4.\n  apply H3.\n  apply H1.\n  apply H4.\n  apply H2.\n  assumption.\nQed.\n\nLemma WeakPeirce : (((((P -> Q) -> P) -> P) -> Q) -> Q).\nProof.\n  intro H1.\n  apply H1.\n  intro H2.\n  apply H2.\n  intro H3.\n  apply H1.\n  intro H4.\n  assumption.\nQed.\n\nEnd ExamplesCh3Section3.\n\nTheorem ModusPonens : ((P -> Q) -> P -> Q).\nProof.\n  intros.\n  rename H into H1.\n  apply H1.\n  assumption.\nQed.\n\n(* TODO: Complete\nTheorem ModusTollens : ((P -> Q) -> ~Q -> ~P).\nProof.\n  intros.\n*)\n\nSection ProofOfTripleImplication.\n\nHypothesis H : (((P -> Q) -> Q) -> Q).\nHypothesis p : P.\n\nLemma Rem : ((P -> Q) -> Q).\nProof (fun H0: (P -> Q) => H0 p).\n\nTheorem TripleImplication : Q.\nProof (H Rem).\n\nEnd ProofOfTripleImplication.\n\nPrint TripleImplication.\n\nPrint Rem.\n\nTheorem ThenExample : (P -> Q -> (P -> Q -> R) -> R).\nProof.\n  intros p q H1.\n  apply H1; assumption.\nQed.\n\nTheorem TripleImplicationOneShot : ((((P -> Q) -> Q) -> Q) -> P -> Q).\nProof.\n  intros H p; apply H; intro H0; apply H0; assumption.\nQed.\n\nTheorem ComposeExample : ((P -> Q -> R) -> (P -> Q) -> (P -> R)).\nProof.\n  intros H1 H2 p.\n  apply H1; [assumption | apply H2; assumption].\nQed.\n\nLemma L3 : ((P -> Q) -> (P -> R) -> (P -> Q -> R -> T) -> P -> T).\nProof.\n  intros H1 H2 H3 p.\n  apply H3; [idtac | apply H1 | apply H2]; assumption.\nQed.\n\nTheorem ThenFailExample : ((P -> Q) -> (P -> Q)).\nProof.\n  intro H; apply H; fail.\nQed.\n\nSection SectionForCutExample.\n\nHypothesis (H1 : P -> Q)\n           (H2 : Q -> R)\n           (H3 : (P -> R) -> T -> Q)\n           (H4 : (P -> R) -> T).\n\nTheorem CutExample : Q.\nProof.\n  cut (P -> R).\n  intro H5.\n  apply H3.\n  assumption.\n  apply H4; assumption.\n  intro H6.\n  apply H2.\n  apply H1.\n  assumption.\nQed.\n\nPrint CutExample.\n\nTheorem CutWithoutCutExample : Q.\nProof.\n  apply H3.\n  intro H5.\n  apply H2.\n  apply H1.\n  assumption.\n  apply H4.\n  intro H5.\n  apply H2.\n  apply H1.\n  assumption.\nQed.\n\nEnd SectionForCutExample.\n\nEnd MinimalPropositionalLogic.\n\nPrint ImplicationIsDistributive.\n\nSection UsingImplicationIsDistributive.\n\nVariables (P1 P2 P3 : Prop).\n\n(* Not working\n\nCheck (ImplicationIsDistributive P1 P2 P3).\n\n*)\n\nTheorem Exercise5P5 : (forall A B C D : Set, A = C \\/ B = C \\/ C = C \\/ D = C).\nProof.\n  intro A.\n  intro B.\n  intro C.\n  intro D.\n  right.\n  right.\n  left.\n  reflexivity.\nQed.\n\n\nTheorem ModusTollens : (forall P Q : Prop, (P -> Q) -> ~Q -> ~P).\nProof.\n  intro P.\n  intro Q.\n  intro H.\n  unfold not.\n  apply (ImplicationTransitivity).\n  exact (H).\nQed.\n", "meta": {"author": "jflopezfernandez", "repo": "Coq-Math-Modules", "sha": "d75d3cf04acbedb5e2cb738c6925cb21ea7b37ea", "save_path": "github-repos/coq/jflopezfernandez-Coq-Math-Modules", "path": "github-repos/coq/jflopezfernandez-Coq-Math-Modules/Coq-Math-Modules-d75d3cf04acbedb5e2cb738c6925cb21ea7b37ea/src/PropositionalLogicInProgress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.6743518032042645}}
{"text": "Require Import Coq.Reals.Reals.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Reals.ROrderedType.\nRequire Import Lists.List.\nImport ListNotations.\nOpen Scope R_scope.\n\nFrom HYDLA Require Export Partial.\n\nDefinition Inf := None : option R.\n\n(* see https://coq.inria.fr/library/Coq.Reals.ROrderedType.html#Reqb *)\nDefinition Rleb r1 r2 := if Rle_dec r1 r2 then true else false.\nDefinition Rltb r1 r2 := if Rlt_dec r1 r2 then true else false.\nDefinition Rgeb r1 r2 := if Rge_dec r1 r2 then true else false.\nDefinition Rgtb r1 r2 := if Rgt_dec r1 r2 then true else false.\nExample test_Rleb1: forall r1 r2 : R, r1 <= r2 <-> Rleb r1 r2 = true.\nProof.\n  intros.\n  split.\n  - intros.\n    unfold Rleb.\n    destruct (Rle_dec r1 r2).\n    + trivial.\n    + apply Rnot_le_gt in n.\n      apply Rgt_lt in n.\n      apply Rle_lt_trans with (r3:=r1) in H.\n      * apply Rlt_irrefl in H.\n        inversion H.\n      * trivial.\n  - unfold Rleb.\n    destruct (Rle_dec r1 r2).\n    + trivial.\n    + intros.\n      discriminate H. Qed.\nExample test_Rleb2: forall r1 r2 : R, r1 > r2 <-> Rleb r1 r2 = false.\nProof.\n  intros.\n  split.\n  - intros.\n    unfold Rleb.\n    destruct (Rle_dec r1 r2).\n    + apply Rgt_lt in H.\n      apply Rle_lt_trans with (r3:=r1) in r.\n      * apply Rlt_irrefl in r.\n        inversion r.\n      * trivial.\n    + trivial.\n  - unfold Rleb.\n    destruct (Rle_dec r1 r2).\n    + intros.\n      discriminate H.\n    + intros.\n      apply Rnot_le_lt in n.\n      trivial. Qed.\nExample test_Rltb1: forall r1 r2 : R, r1 < r2 <-> Rltb r1 r2 = true.\nProof.\n  intros.\n  split.\n  - intros.\n    unfold Rltb.\n    destruct (Rlt_dec r1 r2).\n    + trivial.\n    + apply Rnot_lt_ge in n.\n      apply Rge_le in n.\n      apply Rlt_le_trans with (r3:=r1) in H.\n      * apply Rlt_irrefl in H.\n        inversion H.\n      * trivial.\n  - unfold Rltb.\n    destruct (Rlt_dec r1 r2).\n    + intros.\n      trivial.\n    + intros.\n      discriminate H. Qed.\nExample test_Rltb2: forall r1 r2 : R, r1 >= r2 <-> Rltb r1 r2 = false.\nProof.\n  intros.\n  split.\n  - intros.\n    unfold Rltb.\n    destruct (Rlt_dec r1 r2).\n    + apply Rge_le in H.\n      apply Rlt_le_trans with(r3:=r1) in r.\n      * apply Rlt_irrefl in r.\n        inversion r.\n      * trivial.\n    + trivial.\n  - intros.\n    unfold Rltb in H.\n    destruct (Rlt_dec r1 r2).\n    + inversion H.\n    + apply Rnot_lt_ge in n.\n      trivial. Qed.\nExample test_Reqb1: forall r1 r2 : R, r1 = r2 <-> Reqb r1 r2 = true.\nProof.\n  intros.\n  split.\n  - intros.\n    unfold Reqb.\n    destruct (Req_dec r1 r2).\n    + trivial.\n    + rewrite H in n.\n      apply Rdichotomy in n.\n      generalize n.\n      intros [A|B].\n      * apply Rlt_irrefl in A.\n        inversion A.\n      * apply Rgt_irrefl in B.\n        inversion B.\n  - unfold Reqb.\n    destruct (Req_dec r1 r2).\n    + trivial.\n    + intros.\n      discriminate H. Qed.\nExample test_Reqb2: forall r1 r2 : R, r1 <> r2 <-> Reqb r1 r2 = false.\nProof.\n  intros.\n  split.\n  - intros.\n    apply Rdichotomy in H.\n    generalize H.\n    intros [A|B].\n    + unfold Reqb.\n      destruct (Req_dec r1 r2).\n      * rewrite e in A.\n        apply Rlt_irrefl in A.\n        inversion A.\n      * trivial.\n    + unfold Reqb.\n      destruct (Req_dec r1 r2).\n      * rewrite e in B.\n        apply Rgt_irrefl in B.\n        inversion B.\n      * trivial.\n  - unfold Reqb.\n    destruct (Req_dec r1 r2).\n    + intros.\n      discriminate H.\n    + trivial. Qed.\n\n(* update value of m at x with v, i.e. m(x):=v *)\nDefinition update_pt (m : partial) (x : option R) (v : option R) :=\n  fun y =>\n    match x with\n    | Some x' => if Reqb x' y then v else m y\n    | None => m y\n    end.\nNotation \"x '|-->' v ';' m\" := (update_pt m x v)\n  (at level 100, v at next level, right associativity).\nNotation \"x '|-->' v\" := (update_pt empty x v)\n  (at level 100).\nExample test_update_pt1: (Some 0 |--> Some 10) 0 = Some 10.\nProof.\n  simpl.\n  destruct (Reqb 0 0) eqn:E.\n  - trivial.\n  - unfold Reqb in E.\n    destruct (Req_dec 0 0).\n    + discriminate E.\n    + apply Rdichotomy in n.\n      generalize n.\n      intros [A|B].\n      * apply Rlt_irrefl in A.\n        inversion A.\n      * apply Rgt_irrefl in B.\n        inversion B. Qed.\nExample test_update_pt2: (Some 0 |--> Some 10) 1 = None.\nProof.\n  simpl.\n  destruct (Reqb 0 1) eqn:E.\n  - apply test_Reqb1 in E.\n    apply eq01_False in E.\n    destruct E.\n  - unfold empty.\n    trivial. Qed.\n\n(* update m in open interval (begt, endt) by m' *)\nDefinition update_in (m : partial) (m' : partial) (begt : option R) (endt : option R) : partial :=\n  fun x' =>\n    match (begt, endt) with\n    | (Some begt', Some endt') => if andb (Rltb begt' x') (Rltb x' endt') then m' x' else m x'\n    | (Some begt', Inf) => if Rltb begt' x' then m' x' else m x'\n    | (_, _) => m x'\n    end.\nNotation \"n '|_(' begt ',' endt ')' ';' m\" := (update_in m n begt endt)\n  (at level 100, right associativity).\nNotation \"n '|_(' begt ',' endt ')'\" := (update_in empty n begt endt)\n  (at level 100).\nExample test_update_in1: (fun x => Some x)|_(Some 0, Some 2) 1 = Some 1.\nProof.\n  unfold update_in.\n  simpl.\n  destruct (Rltb 0 1) eqn:E1.\n  - simpl.\n    destruct (Rltb 1 2) eqn:E2.\n    + trivial.\n    + unfold Rltb in E2.\n      destruct (Rlt_dec 1 2).\n      * inversion E2.\n      * apply Rnot_lt_le in n.\n        apply le21_False in n.\n        destruct n.\n  - simpl.\n    unfold Rltb in E1.\n    destruct (Rlt_dec 0 1).\n    + discriminate E1.\n    + apply Rnot_lt_ge in n.\n      apply Rge_le in n.\n      apply le10_False in n.\n      destruct n. Qed.\nExample test_update_in2: (fun x => Some x)|_(Some 0, Some 2) 2 = None.\nProof.\n  unfold update_in.\n  unfold Rltb.\n  destruct (Rlt_dec 2 2).\n  - apply Rlt_irrefl in r.\n    destruct r.\n  - destruct (Rlt_dec 0 2).\n    + unfold empty. reflexivity.\n    + unfold empty. reflexivity. Qed.\n\nInductive phase : Type := pp (v : option R) | ip (m : partial) (begt : option R) (endt : option R).\nDefinition trajectory : Type := list phase.\n(* the def of trajectory dosen't request alternation of PP and IP, *)\n(* so validation might be needed *)\n\n(* entry point is valid, not valid2 *)\nRequire Import Coq.funind.Recdef.\n(* TODO: check continuity on ip *)\nFunction valid2 (tr : trajectory) {measure length tr} : Prop :=\n  match tr with\n  | [pp _; ip _ begt endt] => lt begt endt \\/ endt = Inf\n  | pp _ :: ip _ begt1 endt1 :: pp v2 :: ip m2 begt2 endt2 :: tr'\n      => (lt begt1 endt1 \\/ endt1 = Inf) /\\ endt1 = begt2 /\\ valid2 (pp v2 :: ip m2 begt2 endt2 :: tr')\n  | _ => False\n  end.\nProof.\n  intros.\n  simpl.\n  repeat apply lt_n_S.\n  apply lt_n_SSn. Qed.\nDefinition valid (tr : trajectory) : Prop :=\n  match tr with\n  | (pp v) :: (ip m (Some t) endt) :: tr' => t = 0 /\\ valid2 tr\n  | _ => False\n  end.\nExample test_valid1: valid [pp (Some 0) ; ip (fun x => Some x) (Some 0) Inf].\nProof.\n  unfold valid.\n  split.\n  - trivial.\n  - rewrite valid2_equation.\n    right.\n    trivial. Qed.\nExample test_valid2:\n  valid [pp (Some 0) ; ip (fun x => Some(2*x)) (Some 0) (Some 1) ; pp (Some 2) ; ip (fun x => Some x) (Some 1) Inf].\nProof.\n  unfold valid.\n  split.\n  - trivial.\n  - rewrite valid2_equation.\n    split.\n    + unfold lt.\n      left.\n      apply Rlt_0_1.\n    + split.\n      * trivial.\n      * rewrite valid2_equation.\n        right.\n        trivial. Qed.\nExample test_not_valid1: ~ valid [pp (Some 0) ; pp (Some 0)].\nProof.\n  unfold valid.\n  intro.\n  destruct H. Qed.\nExample test_not_valid2: ~ valid [pp (Some 0) ; ip (fun x => Some x) (Some 1) Inf].\nProof.\n  unfold valid.\n  intros [A B].\n  symmetry in A.\n  apply eq01_False in A.\n  destruct A. Qed.\nExample test_not_valid3: ~ valid [pp (Some 0) ; ip (fun x => Some x) (Some 0) (Some (-1))].\nProof.\n  unfold valid.\n  rewrite valid2_equation.\n  unfold lt.\n  intros [A B].\n  destruct B.\n  - apply Rlt_le_trans with (r3:=0) in H.\n    + apply Rlt_irrefl in H.\n      destruct H.\n    + left.\n      apply Rplus_lt_reg_l with (r:=1).\n      rewrite Rplus_opp_r.\n      rewrite Rplus_0_r.\n      apply Rlt_0_1.\n  - inversion H. Qed.\nExample test_not_valid4: ~ valid [pp (Some 0) ; ip (fun x => Some x) (Some 0) (Some 1); pp (Some 0) ; ip (fun x => Some x) (Some 0) (Some 1)].\nProof.\n  unfold valid.\n  rewrite valid2_equation.\n  intros [A [B [C D]]].\n  - inversion C.\n    symmetry in H0.\n    apply eq01_False in H0.\n    destruct H0. Qed.\n\n(* convert trajectory to partial *)\nFixpoint tr2partial (tr : trajectory) : partial :=\n  match tr with\n  | [] => empty\n  | (pp v) :: (ip m begt endt) :: tr' => (begt |--> v ; m|_(begt, endt) ; (tr2partial tr'))\n  | _ => empty\n  end.\nExample test_tr2partial1: tr2partial [pp (Some 0) ; ip (fun x => Some x) (Some 0) Inf] 1 = Some 1.\nProof.\n  unfold tr2partial.\n  unfold update_pt.\n  unfold update_in.\n  unfold Inf.\n  unfold Reqb.\n  destruct (Req_dec 0 1).\n  - apply eq01_False in e.\n    destruct e.\n  - unfold Rltb.\n    destruct (Rlt_dec 0 1).\n    + trivial.\n    + apply Rnot_lt_le in n0.\n      apply le10_False in n0.\n      destruct n0. Qed.\nExample test_tr2partial2: tr2partial [pp (Some 0) ; ip (fun x => Some x) (Some 0) Inf] (-1) = None.\nProof.\n  unfold tr2partial.\n  unfold update_pt.\n  unfold update_in.\n  unfold Inf.\n  unfold Reqb.\n  destruct (Req_dec 0 (-1)).\n  - apply eq0m1_False in e.\n    destruct e.\n  - unfold Rltb.\n    destruct (Rlt_dec 0 (-1)).\n    + apply Rplus_lt_compat_r with (r:=1) in r.\n      assert (0 + 1 = 1). { ring. } rewrite H in r.\n      assert (-1 + 1 = 0). { ring. } rewrite H0 in r.\n      apply Rlt_le in r.\n      apply le10_False in r.\n      destruct r.\n    + unfold empty.\n      trivial. Qed.", "meta": {"author": "HydLa", "repo": "Coq-Impl-of-Denotational-Semantics", "sha": "07f3fad4ef69f315a166a815a30615c2a4af6715", "save_path": "github-repos/coq/HydLa-Coq-Impl-of-Denotational-Semantics", "path": "github-repos/coq/HydLa-Coq-Impl-of-Denotational-Semantics/Coq-Impl-of-Denotational-Semantics-07f3fad4ef69f315a166a815a30615c2a4af6715/src/Trajectory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6743501907406274}}
{"text": "(** * Induction: Proof by Induction *)\n\n(** Before getting started, we need to import all of our\n    definitions from the previous chapter: *)\n\nAdd LoadPath \"/Users/Josh/Downloads/software foundations/lf/\".\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: Either\n\n         [make Basics.vo]\n\n       (assuming you've downloaded the whole LF directory and have a\n       working 'make' command) or\n\n         [coqc Basics.v]\n\n       (which should work from any terminal window).\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   In particular, if you see a message like\n\n      [Compiled library Foo makes inconsistent assumptions over library \n      Coq.Init.Bar] \n\n   you should check whether you have multiple installations of Coq on \n   your machine.  If so, it may be that commands (like [coqc]) that you\n   execute in a terminal window are getting a different version of Coq\n   than commands executed by Proof General or CoqIDE. *)\n(* ################################################################# *)\n(** * Proof by Induction *)\n\n(** We proved in the last chapter that [0] is a neutral element\n    for [+] on the left, using an easy argument based on\n    simplification.  We also observed that proving the fact that it is\n    also a neutral element on the _right_... *)\n\nTheorem plus_n_O_firsttry : forall n:nat,\n  n = n + 0.\n\n(** ... can't be done in the same simple way.  Just applying\n  [reflexivity] doesn't work, since the [n] in [n + 0] is an arbitrary\n  unknown number, so the [match] in the definition of [+] can't be\n  simplified.  *)\n\nProof.\n  intros n.\n  simpl. (* Does nothing! *)\nAbort.\n\n(** And reasoning by cases using [destruct n] doesn't get us much\n    further: the branch of the case analysis where we assume [n = 0]\n    goes through fine, but in the branch where [n = S n'] for some [n'] we\n    get stuck in exactly the same way. *)\n\nTheorem plus_n_O_secondtry : forall n:nat,\n  n = n + 0.\nProof.\n  intros n. destruct n as [| n'].\n  - (* n = 0 *)\n    reflexivity. (* so far so good... *)\n  - (* n = S n' *)\n    simpl.       (* ...but here we are stuck again *)\nAbort.\n\n(** We could use [destruct n'] to get one step further, but,\n    since [n] can be arbitrarily large, if we just go on like this\n    we'll never finish. *)\n\n(** To prove interesting facts about numbers, lists, and other\n    inductively defined sets, we usually need a more powerful\n    reasoning principle: _induction_.\n\n    Recall (from high school, a discrete math course, etc.) the\n    _principle of induction over natural numbers_: If [P(n)] is some\n    proposition involving a natural number [n] and we want to show\n    that [P] holds for all numbers [n], we can reason like this:\n         - show that [P(O)] holds;\n         - show that, for any [n'], if [P(n')] holds, then so does\n           [P(S n')];\n         - conclude that [P(n)] holds for all [n].\n\n    In Coq, the steps are the same: we begin with the goal of proving\n    [P(n)] for all [n] and break it down (by applying the [induction]\n    tactic) into two separate subgoals: one where we must show [P(O)]\n    and another where we must show [P(n') -> P(S n')].  Here's how\n    this works for the theorem at hand: *)\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)    reflexivity.\n  - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity.  Qed.\n\n(** Like [destruct], the [induction] tactic takes an [as...]\n    clause that specifies the names of the variables to be introduced\n    in the subgoals.  Since there are two subgoals, the [as...] clause\n    has two parts, separated by [|].  (Strictly speaking, we can omit\n    the [as...] clause and Coq will choose names for us.  In practice,\n    this is a bad idea, as Coq's automatic choices tend to be\n    confusing.)\n\n    In the first subgoal, [n] is replaced by [0].  No new variables\n    are introduced (so the first part of the [as...] is empty), and\n    the goal becomes [0 = 0 + 0], which follows by simplification.\n\n    In the second subgoal, [n] is replaced by [S n'], and the\n    assumption [n' + 0 = n'] is added to the context with the name\n    [IHn'] (i.e., the Induction Hypothesis for [n']).  These two names\n    are specified in the second part of the [as...] clause.  The goal\n    in this case becomes [S n' = (S n') + 0], which simplifies to\n    [S n' = S (n' + 0)], which in turn follows from [IHn']. *)\n\n\nTheorem minus_diag : forall n,\n  minus n n = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl. reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n\n(** (The use of the [intros] tactic in these proofs is actually\n    redundant.  When applied to a goal that contains quantified\n    variables, the [induction] tactic will automatically move them\n    into the context as needed.) *)\n\n(** **** Exercise: 2 stars, recommended (basic_induction)  *)\n(** Prove the following using induction. You might need previously\n    proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n- intros m. simpl. rewrite <- IHn'. reflexivity. Qed.\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  induction n as [| n' IHn'].\n  - intros m. simpl. rewrite <- plus_n_O. reflexivity.\n  - intros m. simpl. rewrite <- plus_n_Sm. rewrite <- IHn'.\n    reflexivity. Qed.\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - intros m p. simpl. rewrite -> IHn'. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars (double_plus)  *)\n(** Consider the following function, which doubles its argument: *)\n\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\n(** Use induction to prove this simple fact about [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity. Qed.\n\n\n(** **** Exercise: 2 stars, optional (evenb_S)  *)\n(** One inconvenient aspect of our definition of [evenb n] is the\n    recursive call on [n - 2]. This makes proofs about [evenb n]\n    harder when done by induction on [n], since we may need an\n    induction hypothesis about [n - 2]. The following lemma gives an\n    alternative characterization of [evenb (S n)] that works better\n    with induction: *)\n\nTheorem evenb_S : forall n : nat,\n  evenb (S n) = negb (evenb n).\nProof.\n  intros n. induction n as [| n' IHn'].\n  - reflexivity.\n  - rewrite -> IHn'. rewrite -> negb_involutive. reflexivity. Qed.\n\n(** **** Exercise: 1 star (destruct_induction)  *)\n(** Briefly explain the difference between the tactics [destruct]\n    and [induction].\n\nDestruct breaks down a goal into cases. It does not introduce an\nInductive hypothesis. Induction breaks a goal into 2 cases, the base\ncase and inductive case.\n\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:\n\n    let m, n be natural numbers.\n    we will induct on n.\n    - First, suppose n = 0. We must show 0 + m = m + 0\n\n      0 + m = m = m + 0\n\n    - Second, suppose n = S n' where n' + m = m + n'\n      We must show n + m = m + n\n      S n' + m = m + S n'\n      which by definition of addition implies\n      S (n' + m) = S (m + n')\n      which by the inductive hypothesis implies\n      S (n' + m) = S(n' + m)\n      Thus we conclude Addition is commutative.\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl_informal)  *)\n(** Write an informal proof of the following theorem, using the\n    informal proof of [plus_assoc] as a model.  Don't just\n    paraphrase the Coq tactics into English!\n\n    Theorem: [true = beq_nat n n] for any [n].\n\n    Proof: By Induction\n    - First 0 = 0 by definition.\n    - Second given n = S (n') and n' = n'\n      we need to show n = n\n      by the inductive hypothesis \n      n - 1 = n - 1\n      add 1 to both sides\n      n = n\n      Qed.\n\n[] *)\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, recommended (mult_comm)  *)\n(** Use [assert] to help prove this theorem.  You shouldn't need to\n    use induction on [plus_swap]. *)\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  (* Local associativity *)\n  assert (H1: n + (m + p) = (n + m) + p).\n  {rewrite -> plus_assoc. reflexivity. }\n  rewrite -> H1.\n  (* Local commutitivity *)\n  assert (H2: n + m = m + n).\n  {rewrite -> plus_comm. reflexivity. }\n  rewrite -> H2.\n  (* associativity *)\n  rewrite -> plus_assoc. reflexivity. Qed.\n\n(** Now prove commutativity of multiplication.  (You will probably\n    need to define and prove a separate subsidiary theorem to be used\n    in the proof of this one.  You may find that [plus_swap] comes in\n    handy.) *)\n    \nTheorem mult_1_r : forall p: nat, p * 1 = p.\nProof.\n  induction p as [| p' IHp'].\n  - reflexivity. \n  - simpl. rewrite -> IHp'. reflexivity. Qed.\n\n\nLemma mult_n_Sm : forall m n : nat,\n    n * (S m) = n + n * m.\nProof.\n  intros n m. induction m.\n  - reflexivity.\n  - simpl. rewrite -> IHm. rewrite -> plus_swap. reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  induction n as [n|n' IHn'].\n  - simpl. rewrite -> mult_0_r. reflexivity.\n  - simpl. rewrite -> mult_n_Sm. rewrite -> IHn'.\n    rewrite -> plus_comm. reflexivity. Qed.\n  \n\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (more_exercises)  *)\n(** Take a piece of paper.  For each of the following theorems, first\n    _think_ about whether (a) it can be proved using only\n    simplification and rewriting, (b) it also requires case\n    analysis ([destruct]), or (c) it also requires induction.  Write\n    down your prediction.  Then fill in the proof.  (There is no need\n    to turn in your piece of paper; this is just to encourage you to\n    reflect before you hack!) *)\n\nCheck leb.\n\nTheorem leb_refl : forall n:nat,\n  true = 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  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity. Qed.\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\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/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.8705972717658209, "lm_q1q2_score": 0.6743501900696052}}
{"text": "Require Export TopologicalSpaces.\nRequire Export Continuity.\nRequire Export SubspaceTopology.\n\nSection continuous_factorization.\n\nVariable X Y:TopologicalSpace.\nVariable f:point_set X -> point_set Y.\nVariable S:Ensemble (point_set Y).\nHypothesis f_cont: continuous f.\nHypothesis f_img: forall x:point_set X, In S (f x).\n\nDefinition continuous_factorization :\n  point_set X -> point_set (SubspaceTopology S) :=\n  fun x:point_set X => exist _ (f x) (f_img x).\n\nLemma factorization_is_continuous:\n  continuous continuous_factorization.\nProof.\nred; intros.\ndestruct (subspace_topology_topology _ _ V H) as [V' []].\nrewrite H1.\nrewrite <- inverse_image_composition.\nsimpl.\nassert (inverse_image (fun x:point_set X => f x) V' =\n        inverse_image f V').\napply Extensionality_Ensembles; split; red; intros.\ndestruct H2; constructor; trivial.\ndestruct H2; constructor; trivial.\nrewrite H2.\napply f_cont; trivial.\nQed.\n\nEnd continuous_factorization.\n\nArguments continuous_factorization {X} {Y}.\n\nSection continuous_surj_factorization.\n\nVariable X Y:TopologicalSpace.\nVariable f:point_set X -> point_set Y.\nHypothesis f_cont: continuous f.\n\nDefinition continuous_surj_factorization :\n  point_set X -> point_set (SubspaceTopology (Im Full_set f)).\napply continuous_factorization with f.\nintros.\nexists x.\nconstructor.\ntrivial.\nDefined.\n\nLemma continuous_surj_factorization_is_surjective:\n  surjective continuous_surj_factorization.\nProof.\nred; intros.\ndestruct y.\ndestruct i.\nexists x.\nunfold continuous_surj_factorization.\nunfold continuous_factorization.\npose proof (e).\nsymmetry in H.\ndestruct H.\nf_equal.\nf_equal.\napply proof_irrelevance.\napply proof_irrelevance.\nQed.\n\nLemma continuous_surj_factorization_is_continuous:\n  continuous continuous_surj_factorization.\nProof.\napply factorization_is_continuous.\nexact f_cont.\nQed.\n\nEnd continuous_surj_factorization.\n\nArguments continuous_surj_factorization {X} {Y}.\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/ContinuousFactorization.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6743501725361979}}
{"text": "Require Import init.\n\nRequire Export linear_base.\nRequire Export linear_combination.\nRequire Import set.\nRequire Import unordered_list.\n\n#[universes(template)]\nRecord Subspace U V `{Plus V, Zero V, ScalarMult U V} := make_subspace {\n    subspace_set : V → Prop;\n    subspace_zero : subspace_set 0;\n    subspace_plus : ∀ a b, subspace_set a → subspace_set b → subspace_set (a+b);\n    subspace_scalar : ∀ a v, subspace_set v → subspace_set (a · v);\n}.\nArguments make_subspace {U V H H0 H1}.\nArguments subspace_set {U V H H0 H1}.\nArguments subspace_zero {U V H H0 H1}.\nArguments subspace_plus {U V H H0 H1}.\nArguments subspace_scalar {U V H H0 H1}.\n\n(* begin hide *)\nSection Subspace.\n\nContext {U V} `{\n    UP : Plus U,\n    UZ : Zero U,\n    UN : Neg U,\n    UM : Mult U,\n    UO : One U,\n    @PlusComm U UP,\n    @PlusLid U UP UZ,\n    @PlusLinv U UP UZ UN,\n\n    VP : Plus V,\n    VZ : Zero V,\n    VN : Neg V,\n    @PlusComm V VP,\n    @PlusAssoc V VP,\n    @PlusLid V VP VZ,\n    @PlusLinv V VP VZ VN,\n\n    SM : ScalarMult U V,\n    @ScalarComp U V UM SM,\n    @ScalarId U V UO SM,\n    @ScalarLdist U V VP SM,\n    @ScalarRdist U V UP VP SM\n}.\n\n(* end hide *)\nTheorem subspace_eq : ∀ S1 S2 : Subspace U V, subspace_set S1 = subspace_set S2\n    → S1 = S2.\nProof.\n    intros [S1 S1_zero S1_plus S1_scalar] [S2 S2_zero S2_plus S2_scalar] eq.\n    cbn in eq.\n    subst S2.\n    rewrite (proof_irrelevance S2_zero S1_zero).\n    rewrite (proof_irrelevance S2_plus S1_plus).\n    rewrite (proof_irrelevance S2_scalar S1_scalar).\n    reflexivity.\nQed.\n\nVariable S : Subspace U V.\n\nTheorem subspace_neg : ∀ v, subspace_set S v → subspace_set S (-v).\nProof.\n    intros v v_in.\n    rewrite <- scalar_neg_one.\n    apply subspace_scalar.\n    exact v_in.\nQed.\n\nInstance subspace_plus_class : Plus (set_type (subspace_set S)) := {\n    plus a b := [[a|] + [b|] | subspace_plus S [a|] [b|] [|a] [|b]]\n}.\nInstance subspace_zero_class : Zero (set_type (subspace_set S)) := {\n    zero := [0|subspace_zero S]\n}.\nInstance subspace_neg_class : Neg (set_type (subspace_set S)) := {\n    neg a := [-[a|] | subspace_neg [a|] [|a]]\n}.\nProgram Instance subspace_plus_comm : PlusComm (set_type (subspace_set S)).\nNext Obligation.\n    apply set_type_eq; cbn.\n    apply plus_comm.\nQed.\nProgram Instance subspace_plus_assoc : PlusAssoc (set_type (subspace_set S)).\nNext Obligation.\n    apply set_type_eq; cbn.\n    apply plus_assoc.\nQed.\nProgram Instance subspace_plus_lid : PlusLid (set_type (subspace_set S)).\nNext Obligation.\n    apply set_type_eq; cbn.\n    apply plus_lid.\nQed.\nProgram Instance subspace_plus_linv : PlusLinv (set_type (subspace_set S)).\nNext Obligation.\n    apply set_type_eq; cbn.\n    apply plus_linv.\nQed.\nInstance subspace_scalar_class : ScalarMult U (set_type (subspace_set S)) := {\n    scalar_mult a v := [a · [v|] | subspace_scalar S a [v|] [|v]]\n}.\nProgram Instance subspace_scalar_comp : ScalarComp U (set_type (subspace_set S)).\nNext Obligation.\n    apply set_type_eq; cbn.\n    apply scalar_comp.\nQed.\nProgram Instance subspace_scalar_id : ScalarId U (set_type (subspace_set S)).\nNext Obligation.\n    apply set_type_eq; cbn.\n    apply scalar_id.\nQed.\nProgram Instance subspace_scalar_ldist : ScalarLdist U (set_type (subspace_set S)).\nNext Obligation.\n    apply set_type_eq; cbn.\n    apply scalar_ldist.\nQed.\nProgram Instance subspace_scalar_rdist : ScalarRdist U (set_type (subspace_set S)).\nNext Obligation.\n    apply set_type_eq; cbn.\n    apply scalar_rdist.\nQed.\n\n(* begin hide *)\nEnd Subspace.\n\nSection QuotientSpace.\n\nContext {U V} `{\n    UP : Plus U,\n    UZ : Zero U,\n    UN : Neg U,\n    UM : Mult U,\n    UO : One U,\n    @PlusComm U UP,\n    @PlusLid U UP UZ,\n    @PlusLinv U UP UZ UN,\n\n    VP : Plus V,\n    VZ : Zero V,\n    VN : Neg V,\n    @PlusComm V VP,\n    @PlusAssoc V VP,\n    @PlusLid V VP VZ,\n    @PlusLinv V VP VZ VN,\n\n    SM : ScalarMult U V,\n    @ScalarComp U V UM SM,\n    @ScalarId U V UO SM,\n    @ScalarLdist U V VP SM,\n    @ScalarRdist U V UP VP SM\n}.\n(* end hide *)\nVariable S : Subspace U V.\n\nTheorem subspace_linear_combination :\n    ∀ l, linear_list_in (subspace_set S) l →\n    subspace_set S (linear_combination l).\nProof.\n    intros [l l_unique] Sl.\n    unfold linear_list_in in Sl.\n    unfold linear_combination; cbn in *.\n    clear l_unique.\n    induction l using ulist_induction.\n    -   cbn.\n        rewrite ulist_image_end, ulist_sum_end.\n        apply subspace_zero.\n    -   rewrite ulist_image_add, ulist_sum_add.\n        rewrite ulist_prop_add in Sl.\n        apply subspace_plus.\n        +   apply subspace_scalar.\n            apply Sl.\n        +   apply IHl.\n            apply Sl.\nQed.\n\nLet subspace_eq a b := subspace_set S (a - b).\n(** Declaring this in algebra_scope is a bit of a hack to allow us to redefine\nit later.\n*)\n(* begin show *)\nLocal Infix \"~\" := subspace_eq : algebra_scope.\n(* end show *)\n\nLemma subspace_eq_reflexive : ∀ a, a ~ a.\nProof.\n    intros a.\n    unfold subspace_eq.\n    rewrite plus_rinv.\n    apply subspace_zero.\nQed.\nInstance subspace_eq_reflexive_class : Reflexive _ := {\n    refl := subspace_eq_reflexive\n}.\n\nLemma subspace_eq_symmetric : ∀ a b, a ~ b → b ~ a.\nProof.\n    unfold subspace_eq.\n    intros a b ab.\n    apply subspace_neg in ab.\n    rewrite neg_plus in ab.\n    rewrite neg_neg in ab.\n    rewrite plus_comm in ab.\n    exact ab.\nQed.\nInstance subspace_eq_symmetric_class : Symmetric _ := {\n    sym := subspace_eq_symmetric\n}.\n\nLemma subspace_eq_transitive : ∀ a b c, a ~ b → b ~ c → a ~ c.\nProof.\n    unfold subspace_eq.\n    intros a b c ab bc.\n    pose proof (subspace_plus S _ _ ab bc) as eq.\n    rewrite plus_assoc in eq.\n    rewrite plus_rlinv in eq.\n    exact eq.\nQed.\nInstance subspace_eq_transitive_class : Transitive _ := {\n    trans := subspace_eq_transitive\n}.\n\nDefinition subspace_equiv := make_equiv _ subspace_eq_reflexive_class\n    subspace_eq_symmetric_class subspace_eq_transitive_class.\n\nDefinition quotient_space := equiv_type subspace_equiv.\n\n(* begin show *)\nLocal Infix \"~\" := (eq_equal subspace_equiv).\n(* end show *)\n\nLemma qspace_plus_wd : ∀ a b c d, a ~ b → c ~ d → a + c ~ b + d.\nProof.\n    unfold eq_equal; cbn.\n    unfold subspace_eq.\n    intros a b c d ab cd.\n    pose proof (subspace_plus S _ _ ab cd) as eq.\n    rewrite <- plus_assoc in eq.\n    rewrite (plus_assoc (-b)) in eq.\n    rewrite (plus_comm (-b)) in eq.\n    rewrite <- plus_assoc in eq.\n    rewrite plus_assoc in eq.\n    rewrite <- neg_plus in eq.\n    exact eq.\nQed.\n\nInstance quotient_space_plus : Plus quotient_space := {\n    plus := binary_op (binary_self_wd qspace_plus_wd)\n}.\n\nLemma qspace_plus_assoc : ∀ a b c, a + (b + c) = (a + b) + c.\nProof.\n    intros a b c.\n    equiv_get_value a b c.\n    unfold plus; equiv_simpl.\n    apply f_equal.\n    apply plus_assoc.\nQed.\nInstance quotient_space_plus_assoc : PlusAssoc quotient_space := {\n    plus_assoc := qspace_plus_assoc\n}.\n\nLemma qspace_plus_comm : ∀ a b, a + b = b + a.\nProof.\n    intros a b.\n    equiv_get_value a b.\n    unfold plus; equiv_simpl.\n    apply f_equal.\n    apply plus_comm.\nQed.\nInstance quotient_space_plus_comm : PlusComm quotient_space := {\n    plus_comm := qspace_plus_comm\n}.\n\nInstance quotient_space_zero : Zero quotient_space := {\n    zero := to_equiv subspace_equiv 0\n}.\n\nLemma qspace_plus_lid : ∀ a, 0 + a = a.\nProof.\n    intros a.\n    equiv_get_value a.\n    unfold zero, plus; equiv_simpl.\n    apply f_equal.\n    apply plus_lid.\nQed.\nInstance quotient_space_plus_lid : PlusLid quotient_space := {\n    plus_lid := qspace_plus_lid\n}.\n\nLemma qspace_neg_wd : ∀ a b, a ~ b → -a ~ -b.\nProof.\n    unfold eq_equal; cbn.\n    unfold subspace_eq.\n    intros a b eq.\n    apply subspace_neg in eq.\n    rewrite neg_plus in eq.\n    exact eq.\nQed.\nInstance quotient_space_neg : Neg quotient_space := {\n    neg := unary_op (unary_self_wd qspace_neg_wd)\n}.\n\nLemma qspace_plus_linv : ∀ a, -a + a = 0.\nProof.\n    intros a.\n    equiv_get_value a.\n    unfold neg, plus, zero; equiv_simpl.\n    rewrite plus_linv.\n    reflexivity.\nQed.\nInstance quotient_space_plus_linv : PlusLinv quotient_space := {\n    plus_linv := qspace_plus_linv\n}.\n\nLemma qspace_scalar_wd : ∀ c u v, u ~ v → c · u ~ c · v.\nProof.\n    unfold eq_equal; cbn.\n    unfold subspace_eq.\n    intros c u v eq.\n    apply (subspace_scalar S c) in eq.\n    rewrite scalar_ldist in eq.\n    rewrite scalar_rneg in eq.\n    exact eq.\nQed.\nInstance quotient_space_scalar_mult : ScalarMult U quotient_space := {\n    scalar_mult c := unary_op (unary_self_wd (qspace_scalar_wd c))\n}.\n\nLemma qspace_scalar_comp : ∀ a b v, a · (b · v) = (a * b) · v.\nProof.\n    intros a b v.\n    equiv_get_value v.\n    unfold scalar_mult; equiv_simpl.\n    rewrite scalar_comp.\n    reflexivity.\nQed.\nInstance quotient_space_scalar_comp : ScalarComp _ _ := {\n    scalar_comp := qspace_scalar_comp\n}.\n\nLemma qspace_scalar_id : ∀ v, 1 · v = v.\nProof.\n    intros v.\n    equiv_get_value v.\n    unfold scalar_mult; equiv_simpl.\n    rewrite scalar_id.\n    reflexivity.\nQed.\nInstance quotient_space_scalar_id : ScalarId _ _ := {\n    scalar_id := qspace_scalar_id\n}.\n\nLemma qspace_scalar_ldist : ∀ a u v, a · (u + v) = a · u + a · v.\nProof.\n    intros a u v.\n    equiv_get_value u v.\n    unfold scalar_mult, plus; equiv_simpl.\n    rewrite scalar_ldist.\n    reflexivity.\nQed.\nInstance quotient_space_scalar_ldist : ScalarLdist _ _ := {\n    scalar_ldist := qspace_scalar_ldist\n}.\n\nLemma qspace_scalar_rdist : ∀ a b v, (a + b) · v = a · v + b · v.\nProof.\n    intros a b v.\n    equiv_get_value v.\n    unfold scalar_mult, plus at 2; equiv_simpl.\n    rewrite scalar_rdist.\n    reflexivity.\nQed.\nInstance quotient_space_scalar_rdist : ScalarRdist _ _ := {\n    scalar_rdist := qspace_scalar_rdist\n}.\n(* begin hide *)\n\nEnd QuotientSpace.\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/Linear/linear_subspace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6742936406384012}}
{"text": "(* infotheo (c) AIST. R. Affeldt, M. Hagiwara, J. Senizergues. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq div choice fintype.\nFrom mathcomp Require Import tuple finfun bigop prime binomial ssralg finset fingroup finalg matrix.\nRequire Import Reals Fourier.\nRequire Import Reals_ext ssr_ext ssralg_ext Rssr log2 Rbigop proba entropy ln_facts.\nRequire Import arg_rmax num_occ types jtypes divergence conditional_divergence entropy.\nRequire Import channel_code channel.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope channel_code_scope.\nLocal Open Scope channel_scope.\nLocal Open Scope entropy_scope.\nLocal Open Scope tuple_ext_scope.\nLocal Open Scope reals_ext_scope.\n\nSection scha_def.\n\nVariables B A M : finType.\nVariable n : nat.\n\n(** Decoding success rate: *)\n\nDefinition scha (W : `Ch_1(A, B)) (c : code A B M n) := 1 - echa(W , c).\n\nEnd scha_def.\n\nNotation \"scha( W , C )\" := (scha W C) (at level 50) : channel_code_scope.\n\nSection scha_facts.\n\nVariables B A M : finType.\nHypothesis Mnot0 : (0 < #|M|)%nat.\nVariable n : nat.\n\nLemma scha_pos (W : `Ch_1(A, B)) (c : code A B M n) : 0 <= scha(W, c).\nProof. rewrite /scha; by apply Rge_le, Rge_minus, Rle_ge, echa1. Qed.\n\n(** Expression of the success rate of decoding: *)\n\nLemma success_decode (W : `Ch_1(A, B)) (c : code A B M n) :\n  scha(W, c) = 1 / INR #|M| *\n    \\rsum_(m : M) \\rsum_(tb | dec c tb == Some m) (W ``^ n (| enc c m)) tb.\nProof.\nset rhs := \\rsum_(m | _ ) _.\nhave {rhs}-> : rhs = \\rsum_(m | m \\in M)\n  (1 - Pr (W ``^ n (| enc c m)) [set y | dec c y != Some m ]).\n  apply eq_bigr => i Hi.\n  transitivity (1 - Pr (W ``^ n (|(enc c) i)) (~: [set y | (dec c) y == Some i])).\n    rewrite -Pr_to_cplt.\n    apply eq_bigl => t /=.\n    by rewrite inE.\n  f_equal.\n  apply eq_bigl => tb /=.\n  by rewrite in_setC !inE.\nset rhs := \\rsum_(m | _ ) _.\nhave {rhs}-> : rhs = INR #|M|\n  - \\rsum_(m | m \\in M) Pr (W ``^ n (| enc c m)) [set y | dec c y != Some m ].\n  rewrite /rhs {rhs} big_split /= big_const iter_Rplus mulR1.\n  set lhs := \\rsum_(m | _ ) _.\n  set rhs := \\rsum_(m | _ ) _.\n  suff : lhs = - rhs by move=> ->; field.\n  by rewrite /rhs /lhs {rhs lhs} (big_morph _ morph_Ropp Ropp_0).\nrewrite Rmult_minus_distr_l /Rdiv -mulRA -Rinv_l_sym; last first.\n  apply not_0_INR => abs.\n  move: (Mnot0); by rewrite abs.\nby rewrite mul1R.\nQed.\n\nEnd scha_facts.\n\nLocal Open Scope types_scope.\nLocal Open Scope divergence_scope.\nLocal Open Scope set_scope.\n\nSection typed_success_decomp_sect.\n\nVariables A B M : finType.\nVariable W : `Ch_1*(A, B).\nHypothesis Mnot0 : (0 < #|M|)%nat.\n\nVariable n' : nat.\nLet n := n'.+1.\nVariable P : P_ n ( A ).\n\n(** Bound of the success rate of decoding for typed codes\n   using conditional divergence: *)\n\nDefinition success_factor (tc : typed_code B M P) (V : P_ n (A , B)) :=\n  exp2 (- INR n * `H(V | P)) / INR #|M| *\n  \\rsum_ (m : M) INR #| (V.-shell (tuple_of_row (enc tc m ))) :&:\n                        (@tuple_of_row B n @: ((dec tc) @^-1: [set Some m])) |.\n\nLet Anot0 : (0 < #|A|)%nat. Proof. by case: W. Qed.\n\nLet Bnot0 : (0 < #|B|)%nat.\nProof.\ncase/card_gt0P : Anot0 => a _; exact (dist_support_not_empty (W a)).\nQed.\n\nLemma typed_success (tc : typed_code B M P) : scha(W, tc) =\n  \\rsum_ (V | V \\in \\nu^{B}(P)) exp_cdiv P V W * success_factor tc V.\nProof.\nrewrite success_decode // /Rdiv mul1R; f_equal.\nsymmetry.\ntransitivity (/ INR #|M| * \\rsum_(m : M) \\rsum_(V | V \\in \\nu^{B}(P))\n    exp_cdiv P V W * INR #| V.-shell (tuple_of_row (enc tc m)) :&:\n                            (@tuple_of_row B n @: (dec tc @^-1: [set Some m])) | *\n    exp2 (- INR n * `H(V | P))).\n  rewrite exchange_big /= big_distrr /=.\n  apply eq_bigr => V _.\n  rewrite /success_factor !mulRA -(mulRC (/ INR #|M|)) -!mulRA; f_equal.\n  symmetry; rewrite -big_distrl /= -big_distrr /= -mulRA; f_equal.\n  by rewrite mulRC.\nf_equal.\napply eq_bigr=> m _.\nrewrite (reindex_onto (@row_of_tuple B n) (@tuple_of_row B n)); last first.\n  move=> i Hi; by rewrite tuple_of_rowK.\nrewrite (sum_tuples_ctypes (typed_prop tc m)) //.\napply eq_bigr=> V HV.\nrewrite -mulRA mulRC -mulRA -iter_Rplus_Rmult -big_const.\napply eq_big => tb.\n- rewrite inE row_of_tupleK eqxx andbT.\n  f_equal.\n  apply/imsetP/idP.\n    case=> v H ->; rewrite tuple_of_rowK.\n    by rewrite 2!inE in H.\n  move=> Hm.\n  exists (row_of_tuple tb); last by rewrite row_of_tupleK.\n  by rewrite !inE.\n- rewrite in_set.\n  move=> /andP [Htb _].\n  rewrite mulRC -(@dmc_exp_cdiv_cond_entropy _ _ _ _ _ _ _ (row_of_tuple tb) (typed_prop tc m) HV) //.\n  by rewrite row_of_tupleK.\nQed.\n\nEnd typed_success_decomp_sect.\n\nSection typed_success_factor_bound_sect.\n\nVariables A B M : finType.\nHypothesis Mnot0 : (0 < #|M|)%nat.\n\nVariable n' : nat.\nLet n := n'.+1.\nVariable V : P_ n ( A , B ).\nVariable P : P_ n ( A ).\n\n(** * Bound of the success rate of decoding for typed codes *)\n\nDefinition success_factor_bound :=\n  exp2(- INR n * +| log (INR #|M|) / INR n - `I(P ; V) |).\n\nVariable tc : typed_code B M P.\nHypothesis Vctyp : V \\in \\nu^{B}(P).\n\nLemma success_factor_bound_part1 : success_factor tc V <= 1.\nProof.\napply (Rmult_le_reg_l (INR #|M|)); first by apply lt_0_INR; apply/ltP.\nrewrite /success_factor /Rdiv -(mulRC (/ INR #|M|)) 2!mulRA Rinv_r; last first.\n  apply not_0_INR => /eqP; apply/negP; by rewrite -lt0n.\nrewrite mul1R -iter_Rplus_Rmult -big_const /=.\nrewrite (_ : \\rsum_(m | m \\in M ) 1 = \\rsum_(m : M) 1); last by apply eq_bigl.\nrewrite big_distrr /=.\napply: Rle_big_P_f_g => m _.\nrewrite Ropp_mult_distr_l_reverse exp2_Ropp.\napply (Rmult_le_reg_l (exp2 (INR n * `H( V | P)))); first by apply exp2_pos.\nrewrite mulRA Rinv_r; last by apply exp2_not_0.\nrewrite mulR1 mul1R.\napply (Rle_trans _ (INR #| V.-shell (tuple_of_row (enc tc m)) |) _); last first.\n  apply card_shelled_tuples => //.\n  by apply typed_prop.\n  case: (jtype.c V) => _ Anot0.\n  case/card_gt0P : (Anot0) => a _.\n  by move: (dist_support_not_empty (V a)) => Bnot0.\napply le_INR; apply/leP.\napply subset_leq_card.\napply/setIidPl/setP => tb.\nby rewrite in_set in_set andbC andbA andbb.\nQed.\n\nLet partition_pre_image : {set set_of_finType [finType of n.-tuple B]} :=\n  [set T_{ `tO( V ) } :&: (@tuple_of_row B n @: (dec tc @^-1: [set Some m])) |\n   m in M & [exists y, y \\in T_{`tO( V )} :&: (@tuple_of_row B n @: (dec tc @^-1: [set Some m]))]].\n\nLet trivIset_pre_image : trivIset partition_pre_image.\nProof.\napply/trivIsetP => /= E F.\ncase/imsetP => m _ Em.\ncase/imsetP => l _ El diffEF.\nhave m_l : m != l by apply/negP => /eqP abs; move: diffEF; apply/negPn/negPn; subst.\nrewrite disjoints_subset; apply/subsetP => y; subst E F; rewrite !in_set => /andP [H1 /eqP H2].\nrewrite H1 andTb.\nmove/eqP in H2.\ncase/imsetP : H2 => y1 Hy1 yy1.\napply/imsetP; case => y2 Hy2 yy2.\nrewrite !inE in Hy1.\nrewrite !inE in Hy2.\nsubst y.\nmove/tuple_of_row_inj : yy2 => ?; subst y2.\nrewrite (eqP Hy1) in Hy2.\ncase/eqP : Hy2 => ?; subst l.\nby rewrite eqxx in m_l.\nQed.\n\nLet cover_pre_image : cover partition_pre_image =\n  \\bigcup_(m : M) (T_{`tO( V )} :&: (@tuple_of_row B n @: (dec tc @^-1: [set Some m]))).\nProof.\napply/setP => tb.\ncase/boolP : (tb \\in cover partition_pre_image) => Hcase.\n- symmetry; case/bigcupP: Hcase => E.\n  rewrite /partition_pre_image; case/imsetP => m _ Em ; subst E => Hcase.\n  apply/bigcupP; by exists m.\n- symmetry.\n  apply/negP => abs; move: Hcase; apply/negP/negPn.\n  case/bigcupP : abs => m _ H.\n  rewrite /cover /partition_pre_image.\n  apply/bigcupP; exists (T_{`tO( V )} :&: (@tuple_of_row B n @: (dec tc @^-1: [set Some m]))) => //.\n  apply/imsetP; exists m => //.\n  rewrite in_set; apply/andP; split => //.\n  apply/existsP; by exists tb.\nQed.\n\nLemma success_factor_bound_part2 :\n  success_factor tc V <=  exp2(INR n * `I(P ; V)) / INR #|M|.\nProof.\nrewrite /success_factor -mulRA (mulRC (/ INR #|M|)) !mulRA.\napply Rmult_le_compat_r; first by apply Rlt_le, Rinv_0_lt_compat, lt_0_INR; apply/ltP.\nrewrite /mut_info /Rminus addRC addRA.\nrewrite (_ : - `H(P , V) + `H P = - `H( V | P )); last by rewrite /cond_entropy; field.\nrewrite mulRDr Ropp_mult_distr_r_reverse -Ropp_mult_distr_l_reverse exp2_plus.\napply Rmult_le_compat_l; first by apply Rlt_le, exp2_pos.\nrewrite -(@big_morph _ _ _ 0 _ O _ morph_plus_INR Logic.eq_refl).\napply (Rle_trans _ (INR #| T_{`tO( V )} |)); last first.\n  rewrite -output_type_out_entropy //; by apply card_typed_tuples.\napply le_INR; apply/leP.\napply: (@leq_trans (\\sum_m #| T_{`tO( V )} :&: (@tuple_of_row B n @: (dec tc @^-1: [set Some m]))|)).\n- apply leq_sum => m _.\n  by apply subset_leq_card, setSI, shell_subset_output_type.\n- set lhs := \\sum_ _ _.\n  rewrite (_ : lhs = #|\\bigcup_(i : M) (T_{`tO( V )} :&: (@tuple_of_row B n @: (dec tc @^-1: [set Some i]))) | ); last first.\n    subst lhs.\n    rewrite -cover_pre_image.\n    move: trivIset_pre_image ; rewrite /trivIset => /eqP => <-.\n    rewrite big_imset /= ; last first.\n      move=> m l _.\n      rewrite in_set; case/existsP => tb Htb.\n      move/setP/(_ tb); rewrite Htb; move: Htb.\n      rewrite in_set => /andP [_ Hl].\n      rewrite in_set => /andP [_ Hm].\n      apply Some_inj.\n      move: Hl Hm.\n      case/imsetP => v1 Hv1 ->.\n      case/imsetP => v2 Hv2.\n      move/tuple_of_row_inj => ?; subst v2.\n      rewrite !inE in Hv1, Hv2.\n      by rewrite -(eqP Hv1) -(eqP Hv2).\n    symmetry; rewrite big_mkcond /=.\n    apply eq_bigr => m _.\n    case : ifP => //; rewrite in_set => /negbT H.\n    symmetry; apply/eqP/negPn/negP => abs ; move: H.\n    apply/negP/negPn/existsP/card_gt0P; by rewrite lt0n.\n  apply subset_leq_card; apply/subsetP => tb.\n  case/bigcupP => m _.\n  by rewrite in_set => /andP [H _].\nQed.\n\nLemma success_factor_ub :\n  success_factor tc V <= success_factor_bound.\nProof.\nrewrite /success_factor_bound.\napply Rmax_case.\n- rewrite mulR0 exp2_0; by apply success_factor_bound_part1.\n- apply (Rle_trans _ (exp2(INR n * `I(P ; V)) / INR #|M|)); last first.\n  + apply Req_le; symmetry.\n    rewrite /Rminus mulRDr mulRC.\n    rewrite Rmult_opp_opp -mulRA Ropp_mult_distr_r_reverse Rinv_l; last first.\n      apply not_0_INR => /eqP; by apply/negP.\n    rewrite Ropp_mult_distr_r_reverse mulR1 exp2_plus mulRC /Rdiv; f_equal.\n    rewrite exp2_Ropp exp2_log //.\n    apply lt_0_INR; by apply/ltP.\n  + by apply success_factor_bound_part2.\nQed.\n\nEnd typed_success_factor_bound_sect.\n\nSection typed_success_bound_sect.\n\nVariables A B M : finType.\nVariable W : `Ch_1*(A, B).\nHypothesis Mnot0 : (0 < #|M|)%nat.\n\nVariable n' : nat.\nLet n := n'.+1.\nVariable P : P_ n ( A ).\nVariable tc : typed_code B M P.\n\nLet Anot0 : (0 < #|A|)%nat.\nProof.\nby case: (W) => _ Anot0.\nQed.\n\nLet Bnot0 : (0 < #|B|)%nat.\nProof.\ncase/card_gt0P : Anot0 => a _.\nby move: (dist_support_not_empty (W a)) => Bnot0.\nQed.\n\nLet V0 : P_ n (A, B).\nProof.\nmove: (jtype_not_empty n Anot0 Bnot0) => H.\nexact (enum_val (Ordinal H)).\nQed.\n\nLet exp_cdiv_bound := fun V => exp_cdiv P V W * success_factor_bound M V P.\n\n(** Bound of the success rate of decoding for typed codes\n   using mutual information: *)\n\nLemma typed_success_bound :\n  let Vmax := arg_rmax V0 [pred V | V \\in \\nu^{B}(P)] exp_cdiv_bound in\n  scha(W, tc) <= (INR n.+1)^(#|A| * #|B|) * exp_cdiv_bound Vmax.\nProof.\nmove=> Vmax.\nrewrite (typed_success W Mnot0 tc).\napply (Rle_trans _ ( \\rsum_(V|V \\in \\nu^{B}(P)) exp_cdiv P V W *\n  exp2 (- INR n *  +| log (INR #|M|) * / INR n - `I(P ; V) |))).\n  apply: Rle_big_P_f_g => V HV.\n  rewrite -mulRA; apply Rmult_le_compat_l.\n    rewrite /exp_cdiv.\n    case : ifP => _.\n    by apply Rlt_le, exp2_pos.\n    by apply Rle_refl.\n  rewrite /success_factor mulRA.\n  apply: success_factor_ub => //.\napply (Rle_trans _ (\\rsum_(V | V \\in \\nu^{B}(P)) exp_cdiv P Vmax W *\n                    exp2 (- INR n * +| log (INR #|M|) * / INR n - `I(P ; Vmax)|))).\n  apply: Rle_big_P_f_g => V HV.\n  move: (@arg_rmax2 [finType of (P_ n (A, B))] V0 [pred V | V \\in \\nu^{B}(P) ]\n                    (fun V => exp_cdiv P V W * success_factor_bound M V P)).\n  apply => //; by exists V.\nrewrite big_const iter_Rplus_Rmult /success_factor_bound.\napply Rmult_le_compat_r.\n- apply Rmult_le_pos.\n  + rewrite /exp_cdiv; case : ifP => _; by [apply Rlt_le, exp2_pos | apply Rle_refl].\n  + by apply Rlt_le, exp2_pos.\n- rewrite INR_pow_expn; apply le_INR; apply/leP.\n  by apply card_nu.\nQed.\n\nEnd typed_success_bound_sect.\n\nSection success_bound_sect.\n\nVariables A B M : finType.\nVariable W : `Ch_1*(A, B).\nHypothesis Mnot0 : (0 < #|M|)%nat.\n\nVariable n' : nat.\nLet n := n'.+1.\nVariable c : code A B M n.\n\nLemma Anot0 : (0 < #|A|)%nat.\nProof.\nby case: (W) => _ Anot0.\nQed.\n\nLet P0 : P_ n ( A ).\nProof.\nmove: (type_not_empty n' Anot0) => H.\nexact (enum_val (Ordinal H)).\nDefined.\n\nLocal Open Scope num_occ_scope.\n\n(** * Bound of the success rate of decoding *)\n\nLemma success_bound :\n  let Pmax := arg_rmax P0 predT (fun P => scha(W, P.-typed_code c)) in\n  scha(W, c) <= (INR n.+1) ^ #|A| * scha(W, Pmax.-typed_code c).\nProof.\nmove=> Pmax.\napply (Rle_trans _ (INR #| P_ n ( A ) | * scha W (Pmax.-typed_code c))); last first.\n  apply Rmult_le_compat_r; first by apply scha_pos.\n  rewrite INR_pow_expn; apply le_INR; apply/leP.\n  exact: (type_counting A n).\napply (Rle_trans _ (\\rsum_(P : P_ n ( A )) scha W (P.-typed_code c))); last first.\n  rewrite (_ : INR #| P_ n ( A ) | * scha W (Pmax.-typed_code c) =\n             \\rsum_(P : P_ n ( A )) scha W (Pmax.-typed_code c)); last first.\n    by rewrite big_const iter_Rplus_Rmult.\n  apply: Rle_big_P_f_g => P _.\n  apply: (@arg_rmax2 _ P0 xpredT (fun P1 : P_ n (A) => scha(W, P1.-typed_code c))).\n  by exists P.\n  reflexivity.\nrewrite success_decode // -(sum_messages_types c).\nrewrite /Rdiv mul1R (big_morph _ (morph_mulRDr _) (mulR0 _)).\napply: Rle_big_P_f_g => P _.\napply (Rmult_le_reg_l (INR #|M|)).\n  apply lt_0_INR; by apply/ltP.\nrewrite mulRA Rinv_r; last first.\n  apply not_0_INR => /eqP; apply/negP; by rewrite -lt0n.\nrewrite mul1R success_decode //.\nrewrite /Rdiv mul1R mulRA Rinv_r; last first.\n  apply not_0_INR => /eqP; apply/negP; by rewrite -lt0n.\nrewrite mul1R.\napply (Rle_trans _ (\\rsum_(m | m \\in enc_pre_img c P)\n                     \\rsum_(y | (dec (P.-typed_code c)) y == Some m)\n                     (W ``^ n (|(enc (P.-typed_code c)) m)) y)).\n  apply: Rle_big_P_f_g => m Hm.\n  apply Req_le, eq_big => tb // _.\n  rewrite inE in Hm.\n  by rewrite /tcode /= ffunE Hm.\n- apply: Rle_big_f_X_Y => m //.\n  apply: Rle_big_0_P_g => tb _; by apply Rle0f.\nQed.\n\nEnd success_bound_sect.\n", "meta": {"author": "johnbender", "repo": "shannon", "sha": "552c66f7c76ad687430f4fb8122a2a2b94b741ee", "save_path": "github-repos/coq/johnbender-shannon", "path": "github-repos/coq/johnbender-shannon/shannon-552c66f7c76ad687430f4fb8122a2a2b94b741ee/success_decode_bound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6742936362708916}}
{"text": "Require Import Bool ZArith.\n\nOpen Scope Z_scope.\n\nLtac app :=\n  match goal with\n    | [H0 : ?a, H1 : ?a -> ?b |- _] => apply H1 in H0\n  end.\n\nInductive iexpr : Set :=\n| IConst : Z -> iexpr\n| IVar : Z -> iexpr\n| IAdd : iexpr -> iexpr -> iexpr\n| IMul : iexpr -> iexpr -> iexpr.\n\nFixpoint sameIVar (i j : iexpr) : bool :=\n  match i with\n    | IVar v1 => \n      match j with\n        | IVar v2 =>\n          match Z.compare v1 v2 with\n            | Eq => true\n            | _ => false\n          end\n        | _ => false\n      end\n    | _ => false\n  end.\n\nFixpoint sameIConst (i j : iexpr) : bool :=\n  match i with\n    | IConst v1 => \n      match j with\n        | IConst v2 =>\n          match Z.compare v1 v2 with\n            | Eq => true\n            | _ => false\n          end\n        | _ => false\n      end\n    | _ => false\n  end.\n\nFixpoint iexprEq (i j : iexpr) : bool :=\n  match i with\n    | IAdd il ir =>\n      match j with\n        | IAdd jl jr =>\n          (iexprEq il jl) && (iexprEq ir jr)\n        | _ => false\n      end\n    | IMul il ir =>\n      match j with\n        | IMul jl jr => (iexprEq il jl) && (iexprEq ir jr)\n        | _ => false\n      end\n    | IConst _ => sameIConst i j\n    | IVar _ => sameIVar i j\n  end.\n\nFixpoint isConst (i : iexpr) : bool :=\n  match i with\n    | IConst _ => true\n    | _ => false\n  end.\n\nFixpoint constVal (i : iexpr) : option Z :=\n  match i with\n    | IConst c => Some c\n    | _ => None\n  end.\n\nFixpoint isSome (A : Type) (v : option A) : bool :=\n  match v with\n    | Some _ => true\n    | None => false\n  end.\n\nTheorem isSome_imp_v :\n  forall (A : Type) (v : option A),\n    isSome A v = true ->\n    exists b : A, v = Some b.\nProof.\n  intros; destruct v; [eapply ex_intro; reflexivity | discriminate].\nQed.\n\nFixpoint optionApply (A B : Type) (f : A -> A -> B) (l r : option A) : option B :=\n  match l with\n    | Some a =>\n      match r with\n        | Some b => Some (f a b)\n        | _ => None\n      end\n    | None => None\n  end.\n\nTheorem optionApply_on_somes :\n  forall (A B : Type) (f : A -> A -> B) (l r : option A),\n    isSome A l = true ->\n    isSome A r = true ->\n    exists (a b : A), optionApply A B f l r = Some (f a b).\nProof.\n  intros; pose proof isSome_imp_v as H1;\n\n  apply H1 in H0;\n  inversion H0 as [m0 Hm0];\n  rewrite -> Hm0;\n\n  apply H1 in H;\n  inversion H as [m Hm];\n  rewrite -> Hm;\n\n  simpl;\n  repeat (eapply ex_intro); reflexivity.\nQed.\n\nFixpoint constValRec (i : iexpr) : option Z :=\n  match i with\n    | IConst a => Some a\n    | IVar _ => None\n    | IAdd l r =>\n      let lc := constValRec l in\n      let rc := constValRec r in\n      optionApply Z Z Z.add lc rc\n    | IMul l r =>\n      let lc := constValRec l in\n      let rc := constValRec r in\n      optionApply Z Z Z.mul lc rc\n  end.\n\nTheorem constValRec_on_const_gives_const :\n  forall i : iexpr, isConst i = true -> constValRec i = constVal i.\nProof.\n  intros; destruct i; solve [trivial | simpl; discriminate].\nQed.\n\nFixpoint allConstants (i : iexpr) : bool :=\n  match i with\n    | IConst _ => true\n    | IVar _ => false\n    | IAdd l r => andb (allConstants l) (allConstants r)\n    | IMul l r => andb (allConstants l) (allConstants r)\n  end.\n\nTheorem allConstants_add_consts :\n  forall i j : iexpr,\n    allConstants (IAdd i j) = true ->\n    (allConstants i = true /\\ allConstants j = true).\nProof.\n  intros; simpl allConstants in H;\n  apply andb_true_iff in H; apply H.\nQed.\n\nTheorem allConstants_mul_consts :\n  forall i j : iexpr,\n    allConstants (IMul i j) = true ->\n    (allConstants i = true /\\ allConstants j = true).\nProof.\n  intros; simpl allConstants in H;\n  apply andb_true_iff in H; apply H.\nQed.  \n\nLtac startInduction n :=\n  intros; induction n; trivial.\n\nTheorem constValRec_works_on_allConstants :\n  forall i : iexpr, allConstants i = true -> isSome Z (constValRec i) = true.\nProof.\n  let start := startInduction i;\n               apply allConstants_add_consts in H;\n               inversion H as [Hl Hr];\n               pose proof optionApply_on_somes as A in\n  let finish := do 3 app; trivial;\n                inversion Hl as [a Ha]; inversion Ha as [b Hb];\n                simpl; rewrite -> Hb; trivial in\n  let s1 := specialize (A Z Z Z.add (constValRec i1) (constValRec i2)) in\n  let s2 := specialize (A Z Z Z.mul (constValRec i1) (constValRec i2)) in\n  start; [s1; finish | s2; finish].\nQed.\n\nTheorem constValRec_on_sum_of_consts :\n  forall i j : iexpr,\n    (exists a : Z, constValRec (IAdd i j) = Some a) ->\n    ((exists b : Z, constValRec i = Some b) /\\\n     (exists c : Z, constValRec j = Some c)).\nProof.\n  intros; inversion H as [m Hm]; simpl constValRec in Hm;\n  destruct (constValRec i); destruct (constValRec j);\n  split; first [discriminate | eapply ex_intro; trivial].\nQed.\n\nTheorem constValRec_on_prod_of_consts :\n  forall i j : iexpr,\n    (exists a : Z, constValRec (IMul i j) = Some a) ->\n    ((exists b : Z, constValRec i = Some b) /\\\n     (exists c : Z, constValRec j = Some c)).\nProof.\n  intros; inversion H as [m Hm]; simpl constValRec in Hm;\n  destruct (constValRec i); destruct (constValRec j);\n  split; first [discriminate | eapply ex_intro; trivial].\nQed.\n\nTheorem constValRec_works_imp_allConstants :\n  forall i : iexpr, isSome Z (constValRec i) = true -> allConstants i = true.\nProof.\n  let t := specialize (S i1 i2);\n           apply isSome_imp_v in H;\n           apply S in H; inversion H as [Hl Hr];\n           inversion Hl as [m Hm]; inversion Hr as [n Hn];\n           simpl allConstants;\n           rewrite -> Hm in IHi1; simpl isSome in IHi1;\n           rewrite -> Hn in IHi2; simpl isSome in IHi2;\n           intuition in\n   let p1 := pose proof constValRec_on_sum_of_consts as S in\n   let p2 := pose proof constValRec_on_prod_of_consts as S in\n   startInduction i; [p1; t | p2; t].\nQed.\n\nTheorem constValRec_works_iff_allConstants :\n  forall i : iexpr, isSome Z (constValRec i) = true <-> allConstants i = true.\nProof.\n  intros; unfold iff;\n  split; [apply constValRec_works_imp_allConstants |\n          apply constValRec_works_on_allConstants].\nQed.\n\nFixpoint tryFoldConstantsRec (i : iexpr) : iexpr :=\n  match constValRec i with\n    | Some c => IConst c\n    | None => i\n  end.\n", "meta": {"author": "dillonhuff", "repo": "IExpr", "sha": "9d8370a9caf49efa4622443ddcef50bc0d1cadf0", "save_path": "github-repos/coq/dillonhuff-IExpr", "path": "github-repos/coq/dillonhuff-IExpr/IExpr-9d8370a9caf49efa4622443ddcef50bc0d1cadf0/IExpr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6742936350734791}}
{"text": "(*\nMacBook-Air:~ billw$ /Applications/CoqIDE_8.4pl5.app/Contents/Resources/bin/coqtop\nWelcome to Coq 8.4pl5 (October 2014)\n\nCoq < Require Import Classical.\n\nCoq < Section Exercise_24.\n\nCoq < Goal forall m n o p:Prop, (((m /\\ n) \\/ (o /\\ p)) /\\ ((n \\/ o) -> ~p)) -> n.\n1 subgoal\n\n  ============================\n   forall m n o p : Prop, (m /\\ n \\/ o /\\ p) /\\ (n \\/ o -> ~ p) -> n\n\nUnnamed_thm < intros.\n1 subgoal\n\n  m : Prop\n  n : Prop\n  o : Prop\n  p : Prop\n  H : (m /\\ n \\/ o /\\ p) /\\ (n \\/ o -> ~ p)\n  ============================\n   n\n\nUnnamed_thm < elim H.\n1 subgoal\n\n  m : Prop\n  n : Prop\n  o : Prop\n  p : Prop\n  H : (m /\\ n \\/ o /\\ p) /\\ (n \\/ o -> ~ p)\n  ============================\n   m /\\ n \\/ o /\\ p -> (n \\/ o -> ~ p) -> n\n\nUnnamed_thm < intro.\n1 subgoal\n\n  m : Prop\n  n : Prop\n  o : Prop\n  p : Prop\n  H : (m /\\ n \\/ o /\\ p) /\\ (n \\/ o -> ~ p)\n  H0 : m /\\ n \\/ o /\\ p\n  ============================\n   (n \\/ o -> ~ p) -> n\n\nUnnamed_thm < intro.\n1 subgoal\n\n  m : Prop\n  n : Prop\n  o : Prop\n  p : Prop\n  H : (m /\\ n \\/ o /\\ p) /\\ (n \\/ o -> ~ p)\n  H0 : m /\\ n \\/ o /\\ p\n  H1 : n \\/ o -> ~ p\n  ============================\n   n\n\nUnnamed_thm < tauto.\nNo more subgoals.\n\nUnnamed_thm < Qed.\nintros.\nelim H.\nintro.\nintro.\ntauto.\n\nUnnamed_thm is defined\n\nCoq <\n\n*)\n\nRequire Import Classical.\nSection Exercise_24.\nGoal forall m n o p:Prop, (((m /\\ n) \\/ (o /\\ p)) /\\ ((n \\/ o) -> ~p)) -> n.\nintros.\nelim H.\nintro.\nintro.\n tauto.\n Qed.\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/concise/07chapt/page0392w.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.6742936307059695}}
{"text": "Require Export C12_Angles_Opposes.\n\nSection SUPPLEMENTARY_ANGLES.\n\nDefinition Supplementary (alpha beta : AS) :=\nexists A  : Point,  exists B  : Point,  exists C : Point,  exists D : Point, \n\tA <> C /\\ Between B A D /\\ Angle B A C = alpha /\\ Angle C A D = beta.\n\nLemma SupplementaryCommut : forall alpha beta : AS,\n\tSupplementary alpha beta ->\n\tSupplementary beta alpha.\nProof.\n\tunfold Supplementary in |- *;\n\t intros alpha beta (A, (B, (C, (D, (H0, (H1, (H2, H3))))))).\n\texists A; exists D; exists C; exists B; intuition.\n\t apply BetweenSym; trivial.\n\t rewrite AngleSym.\n\t  trivial.\n\t  apply (BetweenDistinctBC _ _ _ H1).\n\t  trivial.\n\t rewrite AngleSym.\n\t  trivial.\n\t  trivial.\n\t  apply (sym_not_eq (BetweenDistinctAB _ _ _ H1)).\nQed.\n \nLemma HalfLineBetweenBetween : forall A B C D : Point,\n       \tBetween A C D -> \n\tHalfLine C A B -> \n\tBetween B C D.\nProof.\n\tintros.\n\tapply BetweenSym; apply (BetweenHalfLineBetween D C A B).\n\t apply BetweenSym; trivial.\n\t trivial.\nQed.\n\nLemma SupplementBC : forall A B C D A' B' C' D' : Point,\n\tA <> C ->\n\tA' <> C' ->\n\tB <> C ->\n\tBetween B A D ->\n\tBetween B' A' D' ->\n\tAngle B A C = Angle B' A' C' ->\n\tAngle C A D = Angle C' A' D'.\nProof.\n\tintros A B C D A' B' C' D' dAC dA'C' dBC H0 H1 H2.\n\tassert (dAB := sym_not_eq (BetweenDistinctAB _ _ _ H0)).\t\n\tassert (dA'B' := sym_not_eq (BetweenDistinctAB _ _ _ H1)).\n\tdestruct (ExistsHalfLineEquidistant A' B' A B dA'B' dAB) as (B'', (H3, H4)).\n\tdestruct (ExistsHalfLineEquidistant A' C' A C dA'C' dAC) as (C'', (H5, H6)).\n\tassert (dAD := BetweenDistinctBC _ _ _ H0).\t\n\tassert (dA'D' := BetweenDistinctBC _ _ _ H1).\n\tdestruct (ExistsHalfLineEquidistant A' D' A D dA'D' dAD) as (D'', (H7, H8)).\n\trewrite (HalfLineAngleBC A' C' D' C'' D'' dA'C' dA'D' H5 H7).\n\tapply (CongruentSSS A C D A' C'' D'' dAC dAD (sym_eq H6) (sym_eq H8)).\n\tassert (dBD := sym_not_eq (BetweenDistinctCA _ _ _ H0)).\n\tassert (H9 : Distance B C = Distance B'' C'').\n\t apply (CongruentSAS A B C A' B'' C'' dAB dAC (sym_eq H4) (sym_eq H6)).\n\t   rewrite H2; apply (HalfLineAngleBC A' B' C' B'' C'' dA'B' dA'C' H3 H5).\n\t assert (H10 : Distance B D = Distance B'' D'').\n\t  rewrite <- (ChaslesBetween B A D H0).\n\t    rewrite (DistSym B A); rewrite <- H4.\n\t    rewrite <- H8; rewrite (DistSym A' B'').\n\t    apply ChaslesBetween.\n\t    apply (BetweenHalfLineBetween B'' A' D' D'').\n\t   apply (HalfLineBetweenBetween B'); trivial.\n\t   trivial.\n\t  apply (CongruentSAS B C D B'' C'' D'' dBC dBD H9 H10).\n\t    rewrite (HalfLineAngleC B C D A dBC dBD).\n\t   rewrite (HalfLineAngleC B'' C'' D'' A').\n\t    apply (CongruentSSS B C A B'' C'' A' dBC (sym_not_eq dAB) H9).\n\t     autoDistance.\n\t     autoDistance.\n\t    apply (EquiDistantDistinct B C B'' C'' dBC H9).\n\t    apply (EquiDistantDistinct B D B'' D'' dBD H10).\n\t    apply\n\t     (HalfLineSym B'' A' D''\n\t        (sym_not_eq (EquiDistantDistinct A B A' B'' dAB (sym_eq H4)))).\n\t      apply BetweenHalfLine.\n\t      apply (BetweenHalfLineBetween B'' A' D' D'').\n\t     apply (HalfLineBetweenBetween B'); trivial.\n\t     trivial.\n\t   apply (HalfLineSym B A D (sym_not_eq dAB)).\n\t     apply BetweenHalfLine; auto.\n Qed.\n\nLemma Supplement : forall A B C D A' B' C' D' : Point,\n\tA <> C ->\n\tA' <> C' ->\n\tBetween B A D ->\n\tBetween B' A' D' ->\n\tAngle B A C = Angle B' A' C' ->\n\tAngle C A D = Angle C' A' D'.\nProof.\n\tintros A B C D A' B' C' D' dAC dA'C' H0 H1 H2.\n\tassert (dAB := sym_not_eq (BetweenDistinctAB _ _ _ H0)).\n\tdestruct (CentralSymetPoint A B dAB) as (B'', (H3, H4)).\n\tassert (dBB'' := BetweenDistinctBC A B B'' H4).\n\tdestruct (Apart B B'' C dBB'').\n\t apply (SupplementBC A B C D A' B' C' D' dAC dA'C' H H0 H1 H2).\n\t apply (SupplementBC A B'' C D A' B' C' D' dAC dA'C' H).\n\t  apply (BetweenAssocRight B'' B A D (BetweenSym A B B'' H4) H0).\n\t  exact H1.\n\t  rewrite <- (HalfLineAngleB A B C B'' dAB dAC).\n\t   exact H2.\n\t   apply BetweenHalfLine; auto.\nQed.\n\nLemma SupplementaryEq : forall alpha beta gamma : AS,\n\tSupplementary alpha beta ->\n\tSupplementary alpha gamma ->\n\tbeta = gamma.\nProof.\n\tunfold Supplementary in |- *;\n\t intros alpha beta gamma (A, (B, (C, (D, (H0, (H1, (H2, H3)))))))\n\t  (A', (B', (C', (D', (H4, (H5, (H6, H7))))))).\n\trewrite <- H3; rewrite <- H7.\n\tapply (Supplement A B C D A' B' C' D' H0 H4 H1 H5).\n\tsubst; auto.\nQed.\n\nLemma OpposedAtVertex : forall A B C D E : Point,\n\tBetween B A D ->\n\tBetween C A E ->\n\tAngle B A C = Angle D A E.\nProof.\n\tintros.\n\tassert (dAB := sym_not_eq (BetweenDistinctAB _ _ _ H)).\n\tassert (dAC := sym_not_eq (BetweenDistinctAB _ _ _ H0)).\n\trewrite (AngleSym A B C dAB dAC).\n\tassert (dAD := BetweenDistinctBC _ _ _ H).\n\tapply (Supplement A D C B A C D E dAC dAD).\n\t apply BetweenSym; auto.\n\t trivial.\n\t apply AngleSym; auto.\nQed.\n\nLemma CongruentOpposedTriangles : forall A B C D I : Point,\n\tBetween A I C ->\n\tBetween B I D ->\n\tDistance I A = Distance I C ->\n\tDistance I B = Distance I D ->\n\tCongruentTriangles A I B C I D.\nProof.\n\tintros.\n\tapply CongruentTrianglesSASB.\n\t trivial.\n\t trivial.\n\t apply OpposedAtVertex; trivial.\n\t apply sym_not_eq; apply (BetweenDistinctAB _ _ _ H).\n\t apply sym_not_eq; apply (BetweenDistinctAB _ _ _ H0).\nQed.\n\nLemma SupplementaryRec : forall A B C D : Point,\n\tClockwise B A C ->\n\tClockwise C A D ->\n\tSupplementary (Angle B A C) (Angle C A D) ->\n\tBetween B A D.\nProof.\n\tintros.\n\tdestruct H1 as (A', (B', (C', (D', (H1, (H2, (H3, H4))))))).\n\tdestruct (ExistsHalfLineEquidistant A B A' B') as (B'', (H5, H6)).\n\t autoDistinct.\n\t apply sym_not_eq; apply (BetweenDistinctAB _ _ _ H2).\n\t destruct (ExistsHalfLineEquidistant A C A' C') as (C'', (H7, H8)).\n\t  autoDistinct.\n\t  trivial.\n\t  destruct (ExistsHalfLineEquidistant A D A' D') as (D'', (H9, H10)).\n\t   autoDistinct.\n\t   apply (BetweenDistinctBC _ _ _ H2).\n\t   destruct (ExistsBetweenEquidistant A B A' D') as (E, (H11, H12)).\n\t    autoDistinct.\n\t    apply (BetweenDistinctBC _ _ _ H2).\n\t    assert (CongruentStrictTriangles B'' A C'' B' A' C').\n\t     apply CongruentStrictTrianglesSASB.\n\t      trivial.\n\t      trivial.\n\t      rewrite H3; apply sym_eq; apply HalfLineAngleBC.\n\t       autoDistinct.\n\t       autoDistinct.\n\t       trivial.\n\t       trivial.\n\t      intro; elim (ClockwiseNotCollinear _ _ _ H).\n\t        apply CollinearBAC; apply (CollinearTrans A B'' B C).\n\t       apply (EquiDistantDistinct A' B' A B'').\n\t        apply sym_not_eq; apply (BetweenDistinctAB _ _ _ H2).\n\t        autoDistance.\n\t       apply CollinearACB; apply (HalfLineCollinear _ _ _ H5).\n\t       apply CollinearACB; apply (CollinearTrans A C'').\n\t        apply (EquiDistantDistinct A' C' A C''); auto.\n\t        apply CollinearACB; apply (HalfLineCollinear _ _ _ H7).\n\t        autoCollinear.\n\t     assert (CongruentStrictTriangles B'' E C'' B' D' C').\n\t      apply CongruentStrictTrianglesSASA.\n\t       rewrite <- (ChaslesBetween B'' A E).\n\t        rewrite (DistSym B'' A); rewrite H12; rewrite H6.\n\t          rewrite (DistSym A' B'); apply ChaslesBetween; auto.\n\t        apply BetweenSym; apply (BetweenHalfLineBetween E A B B''); trivial.\n\t       rewrite (DistSym B'' C''); rewrite (DistSym B' C').\n\t         apply (CongruentStrictTrianglesCA _ _ _ _ _ _ H13).\n\t       apply trans_eq with (y := Angle A B'' C'').\n\t        apply HalfLineAngleB.\n\t         intro; subst; canonize.\n\t           destruct (ClockwiseExists E A H2) as (F, H17).\n\t           elim (ClockwiseNotClockwise _ _ _ H17); auto.\n\t         intro; subst; elim (ClockwiseNotCollinear _ _ _ H).\n\t           apply CollinearBAC; apply (CollinearTrans A C'').\n\t          apply (EquiDistantDistinct A' C' A C''); auto.\n\t          apply CollinearACB; apply (HalfLineCollinear _ _ _ H5).\n\t          apply CollinearACB; apply (HalfLineCollinear _ _ _ H7).\n\t         apply HalfLineSym.\n\t          apply sym_not_eq; apply (HalfLineDistinct A B B'').\n\t           autoDistinct.\n\t           trivial.\n\t          apply BetweenHalfLine.\n\t            apply (HalfLineBetweenBetween B).\n\t           apply BetweenSym; trivial.\n\t           trivial.\n\t        apply trans_eq with (y := Angle A' B' C').\n\t         apply CongruentStrictTrianglesA; trivial.\n\t         apply HalfLineAngleB.\n\t          apply (BetweenDistinctAB _ _ _ H2).\n\t          intro; subst.\n\t            elim (ClockwiseNotCollinear _ _ _ H).\n\t            apply CollinearBAC; apply HalfLineCollinear.\n\t            apply NullAngleHalfLine.\n\t           autoDistinct.\n\t           autoDistinct.\n\t           rewrite <- H3; apply NullAngle.\n\t            trivial.\n\t            canonize.\n\t          apply BetweenHalfLine; trivial.\n\t       intro; destruct H13.\n\t         elim H15; apply (CollinearTrans B'' E).\n\t        intro; subst; canonize.\n\t          destruct (ClockwiseExists E A H2) as (F, H20).\n\t          elim (ClockwiseNotClockwise _ _ _ H20); auto.\n\t        apply CollinearBCA; apply (CollinearTrans A B).\n\t         autoDistinct.\n\t         apply (HalfLineCollinear _ _ _ H5).\n\t         apply CollinearBCA; apply (BetweenCollinear _ _ _ H11).\n\t        trivial.\n\t      assert (E = D'').\n\t       apply (SSSEqualCD C'' A).\n\t        clear H5 H2 H9; generalizeChange.\n\t          apply H15; apply ClockwiseCAB; apply H17; trivial.\n\t        clear H2 H5 H11; generalizeChangeSense.\n\t          apply H2; apply ClockwiseCAB; apply H9; autoClockwise.\n\t        apply trans_eq with (y := Distance C' D').\n\t         apply\n\t          (CongruentStrictTrianglesBC _ _ _ _ _ _\n\t             (CongruentStrictTrianglesACB _ _ _ _ _ _ H14)).\n\t         assert (CongruentStrictTriangles C'' A D'' C' A' D').\n\t          apply CongruentStrictTrianglesSASB.\n\t           trivial.\n\t           trivial.\n\t           rewrite H4; apply sym_eq; apply HalfLineAngleBC.\n\t            autoDistinct.\n\t            autoDistinct.\n\t            trivial.\n\t            trivial.\n\t           intro; elim (ClockwiseNotCollinear _ _ _ H0).\n\t             apply CollinearBAC; apply (CollinearTrans A C'').\n\t            apply (EquiDistantDistinct A' C'); auto.\n\t            apply CollinearACB; apply (HalfLineCollinear _ _ _ H7).\n\t            apply (CollinearTrans A D'').\n\t             apply (EquiDistantDistinct A' D').\n\t              apply (BetweenDistinctBC _ _ _ H2).\n\t              auto.\n\t             autoCollinear.\n\t             apply CollinearACB; apply (HalfLineCollinear _ _ _ H9).\n\t          apply sym_eq;\n\t           apply\n\t            (CongruentStrictTrianglesCA _ _ _ _ _ _\n\t               (CongruentStrictTrianglesCBA _ _ _ _ _ _ H15)).\n\t        autoDistance.\n\t       apply (BetweenHalfLineBetween B A D'').\n\t        subst; apply (BetweenSym _ _ _ H11).\n\t        apply HalfLineSym.\n\t         autoDistinct.\n\t         trivial.\nQed.\n\nEnd SUPPLEMENTARY_ANGLES.\n", "meta": {"author": "coq-contribs", "repo": "ruler-compass-geometry", "sha": "ee36f5cd523abaa2e0b676c4100c02ec496c0bfd", "save_path": "github-repos/coq/coq-contribs-ruler-compass-geometry", "path": "github-repos/coq/coq-contribs-ruler-compass-geometry/ruler-compass-geometry-ee36f5cd523abaa2e0b676c4100c02ec496c0bfd/C13_Angles_Supplem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6742936295085565}}
{"text": "(**\nAuthor: Niels van der Weide\n\nSuppose, we have a set `X` with a binary operation `f : X → X → X`.\nSince init elments for `f` are unique, the type of unit elements of `f` is a proposition.\n\nThis means we have two ways of defining a univalent category of sets with a unital binary operations:\n1. We define it as a full subcategory of the category of sets with a binary operation\n2. We use algebras of the signature describing sets with a binary operation and a unit, which satisfy the necessary axioms.\nNote that in the first category the morphismms are all functions between sets which preserve the binary relation, while the morphisms in the second category must preserve the unit element as well.\nAs a consequence, the forgetful is full and faithful in the first construction, while in the second it is only faithful.\n\nOn the nLab, there are definitions which describe when functors forget properties and when functors forget stuff.\nhttps://ncatlab.org/nlab/show/stuff%2C+structure%2C+property#definitions\nWith this terminology, we can argue why the first approach adds the unit as a property while in the second approach it is added as structure.\n *)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\n\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.Univalence.\nRequire Import UniMath.CategoryTheory.PrecategoryBinProduct.\nRequire Import UniMath.CategoryTheory.FunctorAlgebras.\nRequire Import UniMath.CategoryTheory.categories.HSET.Core.\nRequire Import UniMath.CategoryTheory.categories.HSET.Limits.\nRequire Import UniMath.CategoryTheory.categories.HSET.Univalence.\nRequire Import UniMath.CategoryTheory.limits.binproducts.\n\nRequire Import UniMath.CategoryTheory.DisplayedCats.Core.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Total.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Isos.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Univalence.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Constructions.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Projection.\n\nLocal Open Scope cat.\n\n(**\nLet us start by defining sets with a binary operation on them.\nTo do so, we use algebras on the diagonal functor.\nLet us repeat the diagonal.\nAfter that, we show we have a univalent category of sets with a binary operation.\n *)\nDefinition diag\n  : HSET ⟶ HSET.\nProof.\n  exact (bindelta_functor HSET ∙ binproduct_functor BinProductsHSET).\nDefined.\n\nDefinition binop_category\n  : category.\nProof.\n  simple refine (FunctorAlg diag).\nDefined.\n\nDefinition is_univalent_binop\n  : is_univalent binop_category.\nProof.\n  exact (is_univalent_FunctorAlg is_univalent_HSET diag).\nDefined.\n\nDefinition binop\n  : univalent_category.\nProof.\n  use make_univalent_category.\n  - exact binop_category.\n  - exact is_univalent_binop.\nDefined.\n\n(**\nIn the remainder, we need some projections.\n *)\nSection ProjectionsBinop.\n  Variable (m : binop).\n\n  Definition carrier\n    : hSet\n    := pr1 m.\n\n  Definition operation\n    : carrier → carrier → carrier\n    := λ x y, pr2 m (x ,, y).\nEnd ProjectionsBinop.\n\n(**\nNow we look at two ways of defining a category of sets with a binary operation and a unit.\nThe first way, is by using the full subcategory.\nThis gives rise to a univalent category since unit elements are unique.\n *)\nDefinition is_unit\n           (m : binop)\n           (e : carrier m)\n  : UU\n  := (∏ (x : carrier m), operation m x e = x)\n     ×\n     (∏ (x : carrier m), operation m e x = x).\n\nDefinition has_unit\n           (m : binop)\n  : UU\n  := ∑ (e : carrier m), is_unit m e.\n\nDefinition isaprop_has_unit\n           (m : binop)\n  : isaprop (has_unit m).\nProof.\n  use invproofirrelevance.\n  intros e₁ e₂.\n  use subtypePath.\n  { intro ; apply isapropdirprod ; use impred ; intro ; apply setproperty. }\n  exact (!(pr22 e₂ (pr1 e₁)) @ pr12 e₁ (pr1 e₂)).\nDefined.\n\nDefinition unit_binop_property_disp_cat\n  : disp_cat binop\n  := disp_full_sub binop has_unit.\n\nDefinition unit_binop_property_cat\n  : category\n  := total_category unit_binop_property_disp_cat.\n\nDefinition is_univalent_property_unit_binop\n  : is_univalent unit_binop_property_cat.\nProof.\n  use is_univalent_total_category.\n  - exact is_univalent_binop.\n  - use disp_full_sub_univalent.\n    exact isaprop_has_unit.\nDefined.\n\nDefinition unit_binop_property\n  : univalent_category.\nProof.\n  use make_univalent_category.\n  - exact unit_binop_property_cat.\n  - exact is_univalent_property_unit_binop.\nDefined.\n\n(**\nTo argue that the unit element is really added as a property, we look at the forgetful functor to sets with binary operations.\nThis functor only forgets the unit and, since the unit was added as a property, it is full and faithful.\nNote that in this displayed category:\n- the displayed objects form a proposition\n- the displayed morphisms are contractible\n *)\nDefinition forget_unit_property_adds_properties\n  : adds_properties unit_binop_property_disp_cat.\nProof.\n  apply pr1_category_fully_faithful.\n  intro ; intros.\n  apply iscontrunit.\nDefined.\n\n(**\nNext we show how to define sets with a binary operation and a unit where the unit is added as structure.\nTo do so, we use displayed categories.\nTo prove univalence of the total category, we use displayed univalence.\n *)\nDefinition point_disp_cat_ob_mor\n  : disp_cat_ob_mor binop.\nProof.\n  use make_disp_cat_ob_mor ; cbn.\n  - exact (λ X, carrier X).\n  - exact (λ X Y x y f, pr1 f x = y).\nDefined.\n\nDefinition point_disp_cat_id_comp\n  : disp_cat_id_comp binop point_disp_cat_ob_mor.\nProof.\n  use tpair.\n  - exact (λ _ _, idpath _).\n  - exact (λ X Y Z f g x y z p q, maponpaths (pr1 g) p @ q).\nDefined.\n\nDefinition point_disp_cat_data\n  : disp_cat_data binop.\nProof.\n  use tpair.\n  - exact point_disp_cat_ob_mor.\n  - exact point_disp_cat_id_comp.\nDefined.\n\nDefinition point_disp_cat_laws\n  : disp_cat_axioms binop point_disp_cat_data.\nProof.\n  repeat split.\n  - cbn ; intros ; apply setproperty.\n  - cbn ; intros ; apply setproperty.\n  - cbn ; intros ; apply setproperty.\n  - cbn ; intros.\n    apply isasetaprop.\n    apply setproperty.\nQed.\n\nDefinition point_disp_cat\n  : disp_cat binop.\nProof.\n  use tpair.\n  - exact point_disp_cat_data.\n  - exact point_disp_cat_laws.\nDefined.\n\nDefinition point_disp_cat_disp_univalent\n  : is_univalent_disp point_disp_cat.\nProof.\n  use is_univalent_disp_from_fibers.\n  intros X x y.\n  use isweq_iso.\n  - intros f.\n    exact (pr1 f).\n  - intros e.\n    induction e ; cbn.\n    apply idpath.\n  - intros e.\n    use subtypePath.\n    { intro ; apply isaprop_is_z_iso_disp. }\n    cbn.\n    induction (pr1 e).\n    apply idpath.\nDefined.\n\nDefinition pointed_binop_category\n  : category\n  := total_category point_disp_cat.\n\nDefinition pointed_binop\n  : univalent_category.\nProof.\n  simple refine (_ ,, _).\n  - exact pointed_binop_category.\n  - refine (is_univalent_total_category\n              _\n              point_disp_cat_disp_univalent).\n    exact is_univalent_binop.\nDefined.\n\n(**\nSome projections of sets with a binary operation and a point.\n *)\nSection ProjectionsPointedBinop.\n  Variable (m : pointed_binop).\n\n  Definition pointed_carrier\n    : hSet\n    := pr11 m.\n\n  Definition pointed_operation\n    : pointed_carrier → pointed_carrier → pointed_carrier\n    := λ x y, pr21 m (x ,, y).\n\n  Definition point_of\n    : pointed_carrier\n    := pr2 m.\nEnd ProjectionsPointedBinop.\n\n(**\nUp to now, we only added the element which represents the unit.\nBeside that, we also need to add the necessary laws.\n *)\nDefinition is_unit_point\n  : pointed_binop → UU\n  := λ X, is_unit (pr1 X) (pr2 X).\n\nDefinition isaprop_is_unit_point\n           (X : pointed_binop)\n  : isaprop (is_unit_point X).\nProof.\n  use isapropdirprod ; use impred ; intro ; apply setproperty.\nDefined.\n\nDefinition unit_binop_structure_disp_cat\n  : disp_cat binop\n  := sigma_disp_cat (disp_full_sub pointed_binop is_unit_point).\n\nDefinition unit_binop_structure_cat\n  : category\n  := total_category unit_binop_structure_disp_cat.\n\nDefinition is_univalent_structure_unit_binop\n  : is_univalent unit_binop_structure_cat.\nProof.\n  use is_univalent_total_category.\n  - apply binop.\n  - apply is_univalent_disp_from_fibers.\n    intros x xx yy.\n    use isweqimplimpl.\n    + intros f.\n      use subtypePath.\n      {\n        intro ; apply isapropdirprod ; use impred ; intro ; apply setproperty.\n      }\n      exact (pr11 f).\n    + apply isapropifcontr.\n      apply isaprop_has_unit.\n    + use invproofirrelevance.\n      intros f g.\n      use subtypePath.\n      { intro ; apply isaprop_is_z_iso_disp. }\n      use subtypePath.\n      { intro ; apply isapropunit. }\n      apply setproperty.\nDefined.\n\nDefinition unit_binop_structure\n  : univalent_category.\nProof.\n  use make_univalent_category.\n  - exact unit_binop_structure_cat.\n  - exact is_univalent_structure_unit_binop.\nDefined.\n\n(**\nWe finish by arguing that the unit is indeed added structure for this construction.\nTo do so, we prove that the forgetful functor is faithful.\n *)\nDefinition forget_unit_structure_faithful\n  : adds_structure unit_binop_structure_disp_cat.\nProof.\n  intros m₁ m₂ f.\n  apply pr1_category_faithful.\n  intro ; intros ; simpl.\n  use (@isaprop_total2 (make_hProp _ _) (λ _, make_hProp _ _)).\n  - apply setproperty.\n  - apply isapropunit.\nDefined.\n\n(**\nWe can also show that this forgetful functor isn't full.\nThis is because not every homomorphism between sets with binary operations preserve the unit element.\nFor that, we use the following example.\n *)\nDefinition nat_unit_binop_structure\n  : unit_binop_structure.\nProof.\n  simple refine ((natset ,, _) ,, _ ,, _) ; cbn.\n  - exact (λ n, pr1 n + pr2 n).\n  - exact 0.\n  - split ; cbn.\n    + apply natplusr0.\n    + apply natplusl0.\nDefined.\n\nDefinition bool_unit_binop_structure\n  : unit_binop_structure.\nProof.\n  simple refine ((boolset ,, _) ,, _ ,, _) ; cbn.\n  - exact (λ b, orb (pr1 b) (pr2 b)).\n  - exact false.\n  - split ; cbn ; intro x ; induction x ; apply idpath.\nDefined.\n\nDefinition nat_to_bool\n  : nat → bool\n  := λ _, true.\n\nDefinition nat_plus_to_bool_or\n  : pr1_category _ nat_unit_binop_structure\n    -->\n    pr1_category _ bool_unit_binop_structure.\nProof.\n  refine (nat_to_bool ,, _).\n  use funextsec.\n  intro x ; apply idpath.\nDefined.\n\nDefinition unit_binop_structure_disp_cat_not_adds_properties\n  : ¬(adds_properties unit_binop_structure_disp_cat).\nProof.\n  intros H.\n  induction H as [H₁ H₂].\n  clear H₂.\n  specialize (H₁ _ _ nat_plus_to_bool_or).\n  revert H₁.\n  use (@hinhuniv _ hfalse).\n  intros H ; cbn.\n  pose (pr121 H) as p.\n  cbn in p.\n  pose (eqtohomot (maponpaths pr1 (pr2 H)) 0) as q.\n  cbn in q.\n  pose (!q @ p) as r.\n  unfold nat_to_bool in r.\n  exact (nopathstruetofalse r).\nQed.\n\n(**\nNow let us look at the hlevels of the displayed objects and morphisms of this displayed category.\nMore specifically, both the type of displayed objects and the type of displayed morphisms form propositions.\n *)\nDefinition unit_binop_structure_disp_cat_mor_prop\n  : locally_propositional unit_binop_structure_disp_cat.\nProof.\n  apply disp_cat_is_locally_propositional.\n  apply forget_unit_structure_faithful.\nDefined.\n\nDefinition unit_binop_structure_disp_cat_mor_not_contr\n  : ¬(locally_contractible unit_binop_structure_disp_cat).\nProof.\n  intro H.\n  apply unit_binop_structure_disp_cat_not_adds_properties.\n  apply pr1_category_fully_faithful.\n  exact H.\nDefined.\n\nDefinition unit_binop_structure_disp_cat_ob_prop\n           (X : binop)\n  : isaprop (unit_binop_structure_disp_cat X).\nProof.\n  apply isaprop_has_unit.\nDefined.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/CategoryTheory/DisplayedCats/Examples/UnitalBinop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6742936295085565}}
{"text": "(* CS 499 - Mechanized Reasoning about Programs *)\n(* Copyright Northern Arizona University        *)\n(* All rights reserved                          *)\n\nRequire Import Arith ZArith List String Relation_Operators.\nImport ListNotations.\n\n(** * Identifiers and Polymorphic States *)\n\nModule Id.\n\n  Inductive t := Id : nat -> t.\n\n  Definition beq (id1 id2:t) : bool :=\n    match (id1, id2) with\n    | (Id n1, Id n2) => beq_nat n1 n2\n    end.\n\n  (** Properties of Id.beq: reflexivity, symmetry. *)\n\n  Fact beq_refl: forall id, beq id id = true.\n  Proof.\n    intros id.\n    destruct id as [ n ].\n    unfold beq.\n    symmetry.\n    apply beq_nat_refl.\n  Qed.\n\n  Fact beq_sym: forall id1 id2, beq id1 id2 = beq id2 id1.\n  Proof.\n    intros id1 id2.\n    destruct id1 as [ n1 ].\n    destruct id2 as [ n2 ].\n    unfold beq.\n    now rewrite Nat.eqb_sym.\n  Qed.\n\n  Fact beq_eq: forall id1 id2,\n      beq id1 id2 = true -> id1 = id2.\n  Proof.\n    intros [ id1 ] [ id2 ] H; unfold beq in *; simpl in *.\n    apply beq_nat_true in H; now rewrite H.\n  Qed.\n  \nEnd Id.\n\n(** Natural numbers can be understood as identifiers *)\nCoercion Id.Id: nat >-> Id.t.\n\n\n(** In the module [State], [t A] is the type of a state, i.e.  a\n    partial mapping from identifiers to values of type [A]. *)\n\nModule State.\n\n  Definition t := Id.t -> Z.\n  \n  Definition update (s:t)(x:Id.t)(v:Z) : t :=\n    fun y => if Id.beq y x\n          then v\n          else s y.\n  \nEnd State.\n\n\n(** * Arithmetic Expressions *)\n\nModule Aexp.\n\n  (** * The type of arithmetic expressions *) \n\n  Inductive binary_op : Type :=\n    Add | Mul | Sub.\n\n  Inductive t : Type :=\n  | Int: Z -> t\n  | Var: Id.t -> t\n  | Binop : binary_op -> t -> t -> t.\n\n  Definition get_op (op: binary_op): Z->Z->Z :=\n    match op with\n    | Add => Z.add\n    | Mul => Z.mul\n    | Sub => Z.sub\n    end.\n  \n  (** ** Evaluation of expressions *)\n  Fixpoint A (a:Aexp.t) (s:Id.t -> Z) : Z :=\n    match a with\n    | Aexp.Int z => z\n    | Aexp.Var id => s id\n    | Aexp.Binop op a1 a2 => (Aexp.get_op op) (A a1 s) (A a2 s)  \n    end.\n\n  Module Notations.\n  \n    (* Coercions *)\n    Coercion Int : Z >-> t.\n    Coercion Var : Id.t >-> t.\n    \n    (* Notations *)\n    Notation \"a0 + a1\" := (Binop Add a0 a1).\n    Notation \"a0 - a1\" := (Binop Sub a0 a1).\n    Notation \"a0 * a1\" := (Binop Mul a0 a1).\n\n  End Notations.\n    \n  (* Examples of expressions *)\n  Module Ex_t.\n    Import Notations.\n    \n    Definition x : Id.t := Id.Id 0. \n    Definition y : Id.t := Id.Id 1.\n    Definition z : Id.t := Id.Id 2.\n\n    (* Warning: scope Z is not opened! *)\n    Definition a0 : t := Binop Add x 1%Z.\n    Definition a1 : t := Binop Add x 1.\n    Print a0. (* 1%Z is considered as a numerical constant *)\n    Print a1. (* 1 is considered as an identifier! *)\n\n    Definition a2 : t := z - (x * (y + 1)).\n  End Ex_t.\n    \n  (* Examples of evaluation *)\n  Module Ex_A.\n    Import Ex_t.\n    \n    Definition s :=\n      fun z =>\n        if Id.beq z x then 42%Z else\n          if Id.beq z y then 0%Z else 0%Z.\n    \n    Example ex0 : A a0 s = 43%Z.\n    Proof. simpl. trivial. Qed.\n\n    Example ex1 : A a1 s = 42%Z.\n    Proof. simpl. trivial. Qed.\n\n    Example ex2 : A a2 s = 0%Z.\n    Proof. simpl. trivial. Qed.\n\n  End Ex_A.\n\n  (** ** Free variables *) \n\n  (* Instead of using a set of variables, we will use lists, and allow\n     a variable to be present several times in the list. *)\n  Fixpoint FV (a:t) : list Id.t :=\n    match a with\n    | Int z   => []     \n    | Var id  => [id]      \n    | Binop op a1 a2 => List.app (FV a1) (FV a2)\n    end.\n\n  Lemma lemma_1_12:\n    forall (s s':State.t) (a:t),\n      (forall x, In x (FV a) -> s x = s' x) ->\n      A a s = A a s'.\n  Proof.\n    intros s s' a H.\n    induction a as [ z | x | op a1 IH1 a2 IH2].\n    - simpl. trivial.\n    - simpl. apply H.\n      simpl. left. reflexivity.\n    - assert(A a1 s = A a1 s') as H1.\n      {\n        apply IH1.\n        intros x Hx.\n        apply H. simpl.\n        apply in_or_app.\n        left. assumption.\n      }\n      assert(A a2 s = A a2 s') as H2.\n      {\n        apply IH2.\n        intros x Hx.\n        apply H. simpl.\n        apply in_or_app.\n        right. assumption.\n      }\n      simpl.\n      rewrite H1, H2.\n      trivial.\n  Qed.\n\n  (** ** Substitution *)\n  Fixpoint subst (a:t) (y:Id.t) (a0:t) : t :=\n    match a with\n    | Int z  =>  Int z\n    | Var id =>  if Id.beq id y\n                then a0\n                else Var id\n    | Binop op a1 a2 =>\n      Binop op (subst a1 y a0) (subst a2 y a0)\n    end.\n\n  (** Lemma (Exercice) 1.14 (page 18) of Semantics with Applications\n      is written as follows: A[a[y →a0]]s = A[a](s[y →A[a0]s]) for all\n      states s.\n\n      A direct ``translation'' one could think of in would be: forall\n      s a a0 y, A (subst a y a0) s = A a (State.update s y (A a0 s)).\n\n      However (A a0 s) has type option Z, whereas function\n      State.update expect its third argument to be of type Z.\n\n      Therefore the correct statement in Coq is as follows: *)\n  Lemma lemma_1_14:\n    forall (s:State.t)(a a0:t)(y:Id.t),\n      A (subst a y a0) s = A a (State.update s y (A a0 s)). \n  Proof.\n    intros s a a0 y.\n    induction a as [ z | x | op a1 IH1 a2 IH2 ].\n    - trivial.\n    - unfold State.update. simpl.\n      destruct (Id.beq x y).\n      + trivial.\n      + trivial.\n    - simpl.\n      now rewrite IH1, IH2.\n  Qed.\n  \nEnd Aexp.\n\n(** * Boolean expressions *)\n\nModule Bexp.\n\n  (** ** Definition of boolean expressions *)\n  Inductive cmp_op : Type :=\n    Equal | LowerEq.\n\n  Definition get_cmp (cmp: cmp_op) : Z -> Z -> bool :=\n    match cmp with\n    | Equal => Z.eqb\n    | LowerEq => Z.leb\n    end.\n  \n  Inductive t : Type :=\n  | Bool: bool -> t      (* Constant: true or false *)\n  | Neg: t -> t       (* negation of an expression *)\n  | And: t -> t -> t   (* conjunction of two boolean expressions *)\n  | Cmp: cmp_op -> Aexp.t -> Aexp.t -> t\n                     (* comparison of two arithmetic expressions *)\n  .\n\n  (** ** Notations *)\n  Module Notations.\n  \n    Coercion Bool : bool >-> t.\n    Notation \"! b\":=(Neg b)(at level 70).\n    Infix \"&&\" := And.\n    Notation \"a1 == a2\" := (Cmp Equal a1 a2)(at level 70).\n    Notation \"a1 <= a2\" := (Cmp LowerEq a1 a2)(at level 70).\n\n  End Notations.\n\n  (** ** Examples *)\n  Module Ex_t.\n    Import Aexp.Notations Notations Aexp.Ex_t.\n    \n    Definition b1 : t := true.\n    Definition b2 : t := !(a1 == 0%Z).\n    Definition b3 : t := (0%Z <= x) && (x <= y).\n\n  End Ex_t.\n\n  Fixpoint B (b:Bexp.t) (s:Id.t -> Z) : bool :=\n  match b with\n  | Bexp.Bool b => b\n  | Bexp.Neg b  => negb(B b s)\n  | Bexp.And b1 b2 => andb (B b1 s) (B b2 s)\n  | Bexp.Cmp cmp a1 a2 => (Bexp.get_cmp  cmp) (Aexp.A a1 s) (Aexp.A a2 s)\n  end.\n\n  \n  Module Ex_B.\n    Import Ex_t Aexp.Ex_A.\n\n    Fact f1 : B b1 s = true.\n    Proof.  simpl. trivial. Qed.\n\n    Fact f2 : B b2 s = true.\n    Proof.  simpl. trivial. Qed.\n\n    Fact f3 : B b3 s = false.\n    Proof.  simpl. trivial. Qed.\n  End Ex_B.\n\n  (** ** Free variables *)\n  Fixpoint FV (b:t) : list Id.t :=\n    match b with\n    | Bool b   => []     \n    | Neg b  => FV b      \n    | And b1 b2 =>\n      List.app (FV b1) (FV b2)\n    | Cmp _ a1 a2 =>\n      List.app (Aexp.FV a1) (Aexp.FV a2)\n    end.\n\n  Module Ex_FV.\n    Import Ex_t Aexp.Ex_t.\n    \n    Fact f1 : FV b1 = [].\n    Proof. simpl. trivial. Qed.\n\n    Fact f2 : FV b2 = [x;y].\n    Proof. simpl. trivial. Qed.\n\n    Fact f3 : FV b3 = [x;x;y].\n    Proof. simpl. trivial. Qed.\n  End Ex_FV.    \n  \n  Lemma lemma_1_13:\n    forall (s s':State.t) (b:t),\n      (forall x, In x (FV b) -> s x = s' x) ->\n      B b s = B b s'.\n  Proof.\n    intros s s' b Hstates.\n    induction b as [ b | b IH | b1 IH1 b2 IH2 | cmp a1 a2 ]; simpl in *.\n    - trivial.\n    - rewrite IH; auto.\n    - rewrite IH1, IH2; auto; intros; intuition.\n    - assert(Aexp.A a1 s = Aexp.A a1 s') as H1\n          by (apply Aexp.lemma_1_12;intros; intuition).\n      assert(Aexp.A a2 s = Aexp.A a2 s') as H2\n          by (apply Aexp.lemma_1_12;intros; intuition).\n      now rewrite H1, H2.\n  Qed.\n\n  (** ** Substitution *)\n  Fixpoint subst (b:t) (y:Id.t) (a:Aexp.t) : t :=\n    match b with\n    | Bool b => Bool b\n    | Neg b => Neg(subst b y a)\n    | And b1 b2 =>\n      And (subst b1 y a) (subst b2 y a)\n    | Cmp cmp a1 a2 =>\n      Cmp cmp (Aexp.subst a1 y a) (Aexp.subst a2 y a)\n    end.\n    \n  Lemma lemma_1_15:\n    forall (s:State.t)(b:t)(a:Aexp.t)(y:Id.t),\n      B (subst b y a) s = B b (State.update s y (Aexp.A a s)). \n  Proof.\n    intros s; induction b; intros a y; simpl in *.\n    - trivial.\n    - now rewrite IHb.\n    - now rewrite IHb1, IHb2.\n    - now repeat rewrite Aexp.lemma_1_14.\n  Qed.\n\nEnd  Bexp.\n\n(** * Semantics as Relations *)\n\n(** ** Syntax *)\n\nInductive stm : Type :=\n| Skip : stm\n| Assign : Id.t -> Aexp.t -> stm\n| Seq : stm -> stm -> stm\n| If : Bexp.t -> stm -> stm -> stm\n| While: Bexp.t -> stm -> stm.\n\n(** ** Natural Semantics *)\n\n(** < S, s > -> s' *)\nInductive ns : stm -> State.t -> State.t -> Prop :=\n| ns_skip:    (* < Skip, s > -> s *)\n    forall s, ns Skip s s \n| ns_assign:  (* < x := a, s > -> s[x|->A[x]s] *)\n    forall (x:Id.t) (a:Aexp.t) (s:Id.t->Z),\n      ns (Assign x a)\n           s\n           (State.update s x (Aexp.A a s))\n| ns_comp:    (* < S1, s > -> s'   < S2, s'-> s\" \n                 -------------------------------\n                       < S1;S2, s > -> s\"        *)\n    forall S1 S2 s s' s'',\n      ns S1 s s' ->\n      ns S2 s' s'' -> \n      ns (Seq S1 S2) s s'' \n| ns_if_tt:  (* < S1 , s > -> s'      B[b]s = tt\n                --------------------------------\n                < if b then S1 else S2, s > -> s' *)\n    forall b S1 S2 s s',\n      Bexp.B b s = true ->\n      ns S1 s s' ->\n      ns (If b S1 S2) s s' \n| ns_if_ff:  (* < S2 , s > -> s'      B[b]s = ff\n                --------------------------------\n                < if b then S1 else S2, s > -> s' *)\n    forall b S1 S2 s s',\n      Bexp.B b s = false ->\n      ns S2 s s' ->\n      ns (If b S1 S2) s s'\n| ns_while_tt:\n  (* B[b]s = tt  < S, s > -> s'  <while b do S, s'>->s\"\n     --------------------------------------------------\n     <while b do S, s> -> s\"                         *)\n    forall b S s s' s'',\n      Bexp.B b s = true ->\n      ns S s s' ->\n      ns (While b S) s' s'' ->\n      ns (While b S) s s''\n| ns_while_ff:\n  (* B[b]s = ff \n     ----------------------- \n     <while b do S, s> -> s                          *)\n    forall b S s,\n      Bexp.B b s = false ->\n      ns (While b S) s s\n.\n\n(** ** Structural Operational Semantics *)\n\nInductive configuration : Type :=\n| Rem : stm -> State.t -> configuration\n| Fin : State.t -> configuration.\n\nInductive sos : stm -> State.t -> configuration -> Prop :=\n| sos_skip:    (* < Skip, s > -> s *)\n    forall s, sos Skip s (Fin s) \n| sos_assign:  (* < x := a, s > -> s[x|->A[x]s] *)\n    forall (x:Id.t) (a:Aexp.t) (s:Id.t->Z),\n      sos (Assign x a)\n          s\n          (Fin (State.update s x (Aexp.A a s)))\n| sos_comp1:\n    forall S1 S2 s S1' s',\n      sos S1 s (Rem S1' s') ->\n      sos (Seq S1 S2) s (Rem (Seq S1' S2) s')\n| sos_comp2:\n    forall S1 S2 s s',\n      sos S1 s (Fin s') ->\n      sos (Seq S1 S2) s (Rem S2 s')\n| sos_if_tt:\n    forall S1 S2 b s,\n      Bexp.B b s = true -> \n      sos (If b S1 S2) s (Rem S1 s)\n| sos_if_ff:\n    forall S1 S2 b s,\n      Bexp.B b s = false -> \n      sos (If b S1 S2) s (Rem S2 s)\n| sos_while:\n    forall b S s,\n      sos (While b S) s\n          (Rem (If b (Seq S (While b S)) Skip) s)\n.\n\n(*********************** AM Language ***********************)\n\n(* Evaluation Stack *)\nModule Stack.\n\n  Inductive A : Type :=\n  | z : Z -> A \n  | T: bool -> A.\n\n  Definition t : Type := list A.\n\nEnd Stack.\n\n(** ** Syntax *)\n(* Translated from page 68 in text, where c is represented using lists*)\nInductive inst: Type := \n| PUSH   : Z -> inst\n| ADD    | MULT | SUB \n| TRUE   | FALSE \n| EQ     | LE  \n| AND    | NEG\n| FETCH  : Id.t -> inst\n| STORE  : Id.t -> inst \n| NOOP   : inst\n| BRANCH : list inst -> list inst -> inst\n| LOOP   : list inst -> list inst -> inst.\n\n(*  Definition of c based of page 68, c is a list of inst which is called code here *)\nDefinition code: Type := list inst.\n\n(* Configuration has the form <c,e,s> where c is a sequence of inst,\n    e is the stack, and s is the storage*)\nDefinition config : Type := ( code * Stack.t * State.t) .\n\n(** ** Structural Operational Semantics *)\nInductive am : config -> config -> Prop :=\n(*NOOP (skip)*)\n| am_noop:\n    forall (c:code) (e:Stack.t)(s:State.t),\n      am  (NOOP::c, e, s)  (c , e, s)\n(*PUSH*)\n| am_push:\n  forall  (n:Z) (c:code) (e:Stack.t)(s:State.t),\n      am ((PUSH n)::c, e, s) (c, (Stack.z n)::e, s)\n\n(* Z operations *)\n| am_add:\n  forall  (z1 z2:Z) (c:code) (s:State.t)  (e:Stack.t),\n     am (ADD::c, (Stack.z z1)::(Stack.z z2)::e, s) (c, (Stack.z (Z.add z1 z2))::e, s)\n\n| am_sub:\n  forall (z1 z2: Z) (c:code) (s:State.t)  (e:Stack.t),\n     am (SUB::c, (Stack.z z1)::(Stack.z z2)::e, s) (c, (Stack.z (Z.sub z1 z2))::e, s)\n\n| am_mult:\n  forall (z1 z2: Z) (c:code) (s:State.t)  (e:Stack.t),\n     am (MULT::c, (Stack.z z1)::(Stack.z z2)::e, s) (c, (Stack.z (Z.mul z1 z2))::e, s)\n\n(* TRUE and FALSE *)\n| am_true:\n    forall (c:code) (s:State.t) (e:Stack.t) (tt:bool),\n       am (TRUE::c, e, s) (c, (Stack.T tt)::e, s)\n\n| am_false:\n    forall (c:code) (s:State.t) (e:Stack.t) (ff:bool),\n       am (FALSE::c, e, s) (c, (Stack.T ff)::e, s)\n\n(* EQ and LE *)\n| am_eq :\n  forall (c:code) (s:State.t) (e:Stack.t) (z1 z2: Z),\n    am (EQ::c,e,s) (c, (Stack.T (Z.eqb z1 z2))::e, s)\n\n| am_le :\n  forall (c:code) (s:State.t) (e:Stack.t) (z1 z2: Z),\n    am (LE::c,e,s) (c, (Stack.T (Z.leb z1 z2))::e, s)\n\n(* AND *) \n| am_and:\n  forall (c:code) (s:State.t) (e:Stack.t) (t1 t2:bool),\n    am (AND::c, e, s) (c,(Stack.T (andb t1 t2))::e,s)\n\n(*NEG *)\n|am_neg:\n  forall  (c:code) (s:State.t) (e:Stack.t) (t:bool),\n    am (NEG::c,(Stack.T t)::e,s) (c,(Stack.T (negb t))::e,s)\n\n(*FETCH*)\n| am_fetch:\n    forall (c:code) (s:State.t) (e:Stack.t) (x:Id.t),\n      am ((FETCH x)::c,e,s) (c, (Stack.z (s x))::e,s)\n\n(*STORE*)\n|am_store:\n    forall (c:code) (s:State.t) (e:Stack.t) (x:Id.t) (z:Z),\n      am ((STORE x)::c,(Stack.z z)::e,s) (c,e, (State.update s x z))\n\n(*BRANCH*)\n|am_branch_tt:\n    forall (c c1 c2:code) (s:State.t) (e:Stack.t),\n      am ((BRANCH c1 c2)::c, (Stack.T true)::e, s) (c1++c, e, s)\n\n|am_branch_ff:\n    forall (c c1 c2:code) (s:State.t) (e:Stack.t),\n      am ((BRANCH c1 c2)::c, (Stack.T false)::e, s) (c2++c, e, s)\n\n(* LOOP *)\n|am_loop:\n    forall (c c1 c2:code) (s:State.t) (e:Stack.t),\n      am ((LOOP c1 c2)::c, e, s) ( c1++(BRANCH(c2++[(LOOP c1 c2)]) [NOOP])::c,e,s).\n\nModule Examples.\n\n  Definition x : Id.t := Id.Id 0.\n\n  Definition s (y: Id.t) : Z := \n    if Id.beq y x \n      then 3%Z\n    else 0%Z.\n\n   Example ex_4_1 :\n      exists s', \n      (clos_refl_trans_1n _ am) ( (PUSH 1%Z)::(FETCH x)::(ADD)::(STORE x)::[],[ ], s ) \n                                             ([],[],s') /\\ s' x = 4%Z.\n   Proof. \n       repeat eexists.\n       do 10  econstructor.\n       simpl. reflexivity.\n  Qed.\n\n   Example ex_4_2:\n          (clos_trans  _ am) ( [ LOOP [TRUE] [NOOP] ], [ ], s) ([ LOOP [TRUE] [NOOP] ], [ ], s). \n      Proof.\n          do 5 (econstructor; simpl).\n      Qed.\n\n    (** ** Exercise 4.4 *)\n\n    (** First, we need to define what corresponds to ->k: *)\n    Inductive am_k : nat -> (code*Stack.t*State.t) -> (code*Stack.t*State.t) -> Prop :=\n    | am_O: forall config, am_k 0 config config\n    | am_Sn: forall config config' config'' k,\n        am config config' -> am_k k config' config'' -> am_k (S k) config config''.\n\n    Lemma ex_4_4:\n      forall k c1 e1 s c' e' s' c2 e2,\n        am_k k (c1, e1, s) (c', e', s') ->\n        am_k k (c1++c2, e1++e2, s) (c'++c2, e'++e2, s').\n    Proof.\n      induction e2.\n    \n    Notation am_star := (clos_refl_trans_1n  _ am).\n\n  Lemma ex_4_4':\n    forall c1 e1 s c' e' s' c2 e2,\n      am_star (c1, e1, s) (c', e', s') ->\n      am_star (c1++c2, e1++e2, s) (c'++c2, e'++e2, s').\n  Proof.\n  Admitted.\n    Lemma ex_4_6: \n      forall (c:code) (s:State.t) (e:Stack.t), \n      exists c' s' e', \n        (clos_refl_trans_1n _ am) (c,e,s) (c',e',s').\n    Proof. \n        repeat eexists.\n        admit.\n    Admitted.\n\n(*Theorem 2.9 (page 41?)*) (*should do induction on derivation tree*)\n(*show table 4.1 is determinisistc; use to prove there is only one \n   computation sequence. (pg 73?)\nInstead of taking am: prove for am; prove for reflex_trans am.*)\n\n\nEnd Examples.\n  \n", "meta": {"author": "chrisswhitneyy", "repo": "CS499_MechanicalReasoning", "sha": "ba1182cabc755bee52a432a24067a43f5bf093ce", "save_path": "github-repos/coq/chrisswhitneyy-CS499_MechanicalReasoning", "path": "github-repos/coq/chrisswhitneyy-CS499_MechanicalReasoning/CS499_MechanicalReasoning-ba1182cabc755bee52a432a24067a43f5bf093ce/Project4/WhileAndAm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6742936223585857}}
{"text": "CoInductive conat : Set := O' | S' (n : conat).\n\nCoFixpoint inf : conat := S' inf.\n\nFixpoint toCo (n : nat) : conat := match n with\n  | O => O'\n  | S n' => S' (toCo n') end.\n\nCoInductive bisim : conat -> conat -> Prop :=\n  | OO : bisim O' O'\n  | SS : forall n m : conat, bisim n m -> bisim (S' n) (S' m).\n\nNotation \"x == y\" := (bisim x y) (at level 70).\n\nDefinition conat_u (n : conat) : conat := match n with\n  | O' => O'\n  | S' n' => S' n' end.\n\nLemma conat_unfold : forall n : conat, n = conat_u n.\nProof. destruct n; auto. Qed.\n\nTheorem not_fin_then_inf : forall n : conat, ~ (exists m : nat, toCo m == n) -> (n == inf).\nProof.\n  cofix CIH. intros. destruct n.\n  - destruct H. exists 0. simpl. constructor.\n  - rewrite (conat_unfold inf). simpl. constructor.\n    apply CIH. intros [m contra]. apply H. exists (S m). simpl.\n    constructor. apply contra.\nQed. ", "meta": {"author": "Brethland", "repo": "LEARNING-STUFF", "sha": "eb2cef0556efb9a4ce11783f8516789ea48cc344", "save_path": "github-repos/coq/Brethland-LEARNING-STUFF", "path": "github-repos/coq/Brethland-LEARNING-STUFF/LEARNING-STUFF-eb2cef0556efb9a4ce11783f8516789ea48cc344/Coq/nat_inf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6742936207735373}}
{"text": "Inductive natprod : Type :=\n  | pair : nat -> nat -> natprod.\n\nNotation \"( x , y )\" := (pair x y).\n\nDefinition fst p : nat :=\n  match p with | (x,_) => x end.\n\nDefinition snd p : nat :=\n  match p with | (_,x) => x end.\n\nDefinition swap p : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\nLtac pair_simple p := destruct p as [m n]; simpl; reflexivity.\n\nTheorem surjective_pairing : forall p : natprod, p = (fst p, snd p).\nProof.\n  intro p. pair_simple p.\nQed.\n\nTheorem snd_fst_is_swap : forall p, swap p = (snd p, fst p).\nProof.\n  intro p. pair_simple p.\nQed.\n\nTheorem fst_swap_is_snd : forall p, fst (swap p) = snd p.\nProof.\n  intro p. pair_simple p.\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/pairs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.6742936195761244}}
{"text": "Inductive N:Set:= (*this is a comment line*)\n|zero: N\n|succ:N->N.\n\nFixpoint plus (m n:N):=\nmatch m with\n| zero=>n\n|succ m'=>succ(plus m' n)\nend.\n\nLemma zero_identity: forall n,n=plus n zero.\nProof.\ninduction n.\nauto.\nsimpl.\nf_equal.\nassumption.\nQed.\n\n", "meta": {"author": "mmaleki", "repo": "LogicalDifferentiation", "sha": "2a46afc6ae55680fb4416dadbe295c0b617bc4f4", "save_path": "github-repos/coq/mmaleki-LogicalDifferentiation", "path": "github-repos/coq/mmaleki-LogicalDifferentiation/LogicalDifferentiation-2a46afc6ae55680fb4416dadbe295c0b617bc4f4/ZeroIdentity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6742854115772331}}
{"text": "Require Import ZArith.\n\nModule NaiveLang.\n  Definition expr := (nat -> option Z) -> Prop.\n  Definition context := expr -> Prop.\n  Definition andp (e1 e2 : expr) : expr := fun st => e1 st /\\ e2 st.\n  Definition orp  (e1 e2 : expr) : expr := fun st => e1 st \\/ e2 st.\n  Definition falsep : expr := fun st => False.\n  Definition truep : expr := fun st => True.\n\n  Definition join : (nat -> option Z) -> (nat -> option Z) -> (nat -> option Z) -> Prop :=\n    fun x y z =>\n      forall p: nat,\n       (exists v, x p = Some v /\\ y p = None /\\ z p = Some v) \\/\n       (exists v, x p = None /\\ y p = Some v /\\ z p = Some v) \\/\n       (x p = None /\\ y p = None /\\ z p = None).\n  Definition sepcon (e1 e2 : expr) : expr := fun st =>\n    exists st1 st2, join st1 st2 st /\\ e1 st1 /\\ e2 st2.\n  Definition emp : expr := fun st =>\n    forall p, st p = None.\n  Definition derivable1 (e1 e2 : expr) : Prop := forall st, e1 st -> e2 st.\nEnd NaiveLang.\n\nRequire Import interface_4.\n\nModule NaiveRule.\n  Include DerivedNames (NaiveLang).\n  Axiom falsep_sepcon_left : (forall x : expr, derivable1 (sepcon falsep x) falsep) .\n  Axiom orp_sepcon_left : (forall x y z : expr, derivable1 (sepcon (orp x y) z) (orp (sepcon x z) (sepcon y z))) .\n  Axiom sepcon_emp_left : (forall x : expr, derivable1 (sepcon x emp) x) .\n  Axiom sepcon_emp_right : (forall x : expr, derivable1 x (sepcon x emp)) .\n  Axiom derivable1_sepcon_comm : (forall x y : expr, derivable1 (sepcon x y) (sepcon y x)) .\n  Axiom derivable1_sepcon_assoc1 : (forall x y z : expr, derivable1 (sepcon x (sepcon y z)) (sepcon (sepcon x y) z)) .\n  Axiom derivable1_sepcon_mono : (forall x1 x2 y1 y2 : expr, derivable1 x1 x2 -> derivable1 y1 y2 -> derivable1 (sepcon x1 y1) (sepcon x2 y2)) .\n  Axiom derivable1_truep_intros : (forall x : expr, derivable1 x truep) .\n  Axiom derivable1_falsep_elim : (forall x : expr, derivable1 falsep x) .\n  Axiom derivable1_orp_intros1 : (forall x y : expr, derivable1 x (orp x y)) .\n  Axiom derivable1_orp_intros2 : (forall x y : expr, derivable1 y (orp x y)) .\n  Axiom derivable1_orp_elim : (forall x y z : expr, derivable1 x z -> derivable1 y z -> derivable1 (orp x y) z) .\n  Axiom derivable1_andp_intros : (forall x y z : expr, derivable1 x y -> derivable1 x z -> derivable1 x (andp y z)) .\n  Axiom derivable1_andp_elim1 : (forall x y : expr, derivable1 (andp x y) x) .\n  Axiom derivable1_andp_elim2 : (forall x y : expr, derivable1 (andp x y) y) .\n\nEnd NaiveRule.\n\nModule T := LogicTheorem NaiveLang NaiveRule.\nModule Solver := IPSolver NaiveLang.\nImport T.\nImport Solver.\n\n\n", "meta": {"author": "QinxiangCao", "repo": "LOGIC", "sha": "d1476d57345c87447ea500b3d5ea99ee6d0f6863", "save_path": "github-repos/coq/QinxiangCao-LOGIC", "path": "github-repos/coq/QinxiangCao-LOGIC/LOGIC-d1476d57345c87447ea500b3d5ea99ee6d0f6863/LogicGenerator/demo/implementation_4_ideal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6742742978111116}}
{"text": "Require Import List Extraction.\nSection LLists.\n\nVariable (A:Type).\n\nCoInductive LList := \n  | LNil: LList\n  | LCons : A -> LList -> LList.\n\n\nInductive Finite : LList -> Prop :=\n  |Finite_LNil: Finite LNil\n  |Finite_LCons     : forall a l, Finite l-> Finite (LCons a l).\n\n\n(* An equivalent (one contructor) definition of Finite *)\n\nInductive Finite_alt (x:LList) :Prop := \n  |finite_alt_intro: (forall a y , x = LCons a y ->Finite_alt y)-> \n       Finite_alt x.\n\n\nLemma Finite_Finite_alt : forall x, Finite x -> Finite_alt x.\nProof.\n  intros x H;induction H.\n -  constructor; intros a y H;inversion H.\n -  constructor;intros b y;injection 1; intros;subst y;assumption.\nQed.\n\nLemma Finite_alt_Finite : forall x, Finite_alt x -> Finite x.\nProof.\n intros x H; induction H as [x H H0]; destruct x;constructor.\n eapply H0;eauto.  \nQed.\n\n\nDefinition Finite_rect_0 (P:LList->Type) :\n    (forall x : LList,\n        (forall(h:A) (y  : LList),  x = LCons h y -> P y) -> P x) ->\n    forall x : LList, Finite x -> P x.\nProof.\n intros H x Hx;apply Finite_Finite_alt in Hx.\n induction Hx.\n apply H; auto.\nDefined.\n\nDefinition Finite_rect (P:LList->Type) :\n P LNil ->\n (forall x (l:LList), P l -> (P (LCons  x l))) ->\n forall l, Finite l -> P l.\nProof.\n intros X X0 l H; induction H using Finite_rect_0.\n  destruct x; auto.\n  apply X0; apply X1 with a;reflexivity.\nDefined.\n\n\n\nFixpoint list_inject (l:list A) : LList :=\n match l with nil => LNil\n            |List.cons a l' => LCons a (list_inject l') \n end.\n\nLemma inj_Finite : forall l, Finite (list_inject l).\nProof. \n induction l;constructor;auto.\nQed.\n\nDefinition to_list_strong: forall x, Finite x-> {l:list A | x=list_inject l}.\nProof.\n  intros x H;  induction H using Finite_rect.\n -   exists nil;auto.\n -   destruct IHFinite as [l0 H0]; exists (x::l0);subst l;trivial. \nDefined.\n\n\nDefinition to_list: forall x, Finite x-> list A.\nProof.\n  intros x Hx;destruct (to_list_strong _ Hx) as  [x0 _];  exact x0.\nDefined.\n\n\nEnd LLists.\nRecursive Extraction to_list_strong.\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/ch13_co_inductive_types/SRC/Llist_to_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.674117203570617}}
{"text": "(** * Teorija tipov in λ-račun. *)\n\n(** Tipi so posplošitev množic, topološki prostorov in podatkovnih tipov. Naivno si jih\n    lahko predstavljamo kot množice. Dejstvo, da ima izraz [e] tip [A] pišemo [e : A].\n\n    Razne konstrukcije tipov se vedno uvede po istem vzorcu:\n\n    - _formacija_: kako se naredi nov tip\n\n    - _vpeljava_: kako se naredi ali sestavi elemente tipa (konstruktorji)\n\n    - _upraba_: kako se elemente uporabi ali razstavi na sestavne dele (eliminatorji)\n\n    - _enačbe_: kakšne enačbe povezujejo konstruktorje in eliminatorje\n*)\n\n(** ** Funkcije\n\n  Za vsaka dva tipa [A] in [B] lahko tvorimo tip funkcij:\n\n  - _formacija_: če sta [A] in [B] tipa, je tudi [A -> B] tip\n\n  - _vpeljava_: če je [x : A] spremenljivka tipa [A] in [t : B] izraz tipa [B],\n    odvisen od [x], potem je [fun (x : A) => t] tipa [A -> B]. Izrazu [fun ...]\n    pravimo _λ-abstrakcija_, ker se v logiki piše $\\lambda x : A . t$.\n\n  - _uporaba_: če je [f : A -> B] in [e : A] potem je [f e : B]. Pravimo, da smo\n    funkcijo [f] aplicirali na argumentu [e].\n\n  - _enačbe_:\n\n    - _pravilo $\\beta$_: [(fun (x : A) => t) e = t{e/x}] kjer zapis \"[t{e/x}]\" pomeni,\n      da v izrazu [t] vstavimo [e] namesto [x].\n\n    - _pravilo $\\eta$_: [(fun (x : A) => f x) = f]\n*)\n   \n(** ** Kartezični produkt\n\n    Da bomo lahko počeli kaj zanimivega, vpeljemo še kartezični produkt tipov:\n\n    - _formacija_: če sta [A] in [B] tipa, je [A * B] tip (matematični zapis $A \\times B$)\n\n    - _vpeljava_: če je [a : A] in [b : B], potem je [(a,b) : A * B], _urejeni par_\n\n    - _uporaba_: če je [p : A * B], potem imamo\n\n      - _prva projekcija_: [fst p : A]\n      - _druga projekcija_: [snd p : B]\n\n    - enačbe, pri čemer je [a : A], [b : B] in [p : A * B]:\n      - [fst (a, b) = a]\n      - [snd (a, b) = b]\n      - [p = (fst p, snd p)]\n\n    Poznamo še enotski tip:\n\n    - _formacija_: [unit] je tip\n    - _vpeljava_: [tt : unit]\n    - _uporaba_: pravil za uporabo ni\n    - _enačbe_: če je [u : unit], je [u = tt].\n*)\n\n(** V Coqu lahko datoteko razdelimo na posamične razdelke z [Section X.] in [End X.] *)\nSection RazneFunkcije.\n\n  (* Predpostavimo, da imamo tipe [A], [B] in [C]. *)\n  Context {A B C : Type}.\n\n  Definition vaja1_1 : A * B -> B * A :=\n    fun (p : A * B) => (snd p, fst p).\n                                  \n  Definition vaja1_2 : (A * B) * C -> A * (B * C) :=\n    fun (p : (A * B) * C) => (fst (fst p), (snd (fst p), snd p)).\n\n  Definition vaja1_3 : A -> (B -> A).\n  Admitted.\n\n  \n  Definition vaja1_4 : (A -> B -> C) -> (A -> B) -> (A -> C).\n  Admitted.\n\n  Definition vaja1_5 : (A * B -> C) -> (A -> (B -> C)).\n  Admitted.\n  \n  Definition vaja1_6 : (A -> (B -> C)) -> (A * B -> C) :=\n    fun (f : A -> (B -> C)) => (fun p : A * B => f (fst p) (snd p)).\n\n  Definition vaja1_7 : unit * A -> A.\n  Admitted.\n\n  Definition vaja1_8 : A -> unit * A :=\n    fun (a : A) => (tt, a).\nEnd RazneFunkcije.\n\n(** Ko zapremo razdelek [RazneFunkcije] nimamo več predpostavke, da so [A], [B], [C] tipi,\n    vse definicije iz razdelka pa postanejo funkcije z dodatnimi parametri [A], [B], [C]. *)\nPrint vaja1_1.\n\n(** Coq pravi: \"Arguments [A], [B] are implicit and maximally inserted\". To pomeni,\n    da jih ni treba podati, ko uporabimo funkcijo [vaja1_1]. *)\nEval compute in vaja1_1 (42, false).\n\n(* Če želimo eksplicitno nastaviti tudi [A] in [B], pišemo [@vaja1_1] namesto [vaja1_1]: *)\nEval compute in @vaja1_1 nat bool (42, false).\n\n(** ** Izomorfni tipi\n\n   Pravimo, da sta tipa [X] in [Y] izomorfna, če obstajata [f : X -> Y] in\n   [g : Y -> X], da velja [g (f x) = x] za vse [x : X] in [g (g y) = y] za vse [y : Y].\n*)\nDefinition iso (X : Type) (Y : Type) :=\n  exists (f : X -> Y) (g : Y -> X),\n    (forall x : X, g (f x) = x) /\\ (forall y : Y, f (g y) = y).\n\n(** V Coqu lahko uvedemo prikladno notacijo za izomorfizem. *)\nNotation \"X <~> Y\" := (iso X Y) (at level 60).\n\nSection Izomorfizmi1.\n  (** Predpostavimo, da imamo tipe [A], [B] in [C]. *)\n  Context {A B C : Type}.\n\n  (** Dokaži, da so naslednji tipi izomorfni. *)\n\n  Lemma vaja2_1 : A * B <~> B * A.\n  Proof.\n    admit.\n  Qed.\n\n  Lemma vaja2_2 : (A * B) * C <~> A * (B * C).\n  Proof.\n    admit.\n  Qed.\n\n  Lemma vaja2_3 : unit * A <~> A.\n  Proof.\n    admit.\n  Qed.\n\n  (** Pravimo, da sta funkciji [f g : X -> Y] _enaki po točkah_, če velja [forall x : X, f\n      x = g x]. Aksiom _funkcijske ekstenzionalnosti_ pravi, da sta funkciji enaki,\n      če sta enaki po točkah. Coq ne verjame v ta aksiom, zato ga po potrebi predpostavimo. \n      Najprej ga definirajmo. *)\n  Definition funext :=\n    forall (X Y : Type) (f g : X -> Y), (forall x, f x = g x) -> f = g.\n\n  (** S pomočjo ekstenzionalnosti lahko dokažemo nekatere izomorfizme. *)\n  Lemma vaja2_4 (F : funext) : (A * B -> C) <~> (A -> (B -> C)).\n  Proof.\n    admit.\n  Qed.\n\n  Lemma vaja2_5 (F : funext) : (unit -> A) <~> A.\n  Proof.\n    admit.\n  Qed.\n\n  Lemma vaja2_6 (F : funext) : (A -> unit) <~> unit.\n  Proof.\n    admit.\n  Qed.\nEnd Izomorfizmi1.\n\n(** ** Vsota tipov\n\n   Vsota tipov je kot disjunktna unija v teorijo množic ali koprodukt v kategorijah:\n\n   - _formacija_: če sta [A] in [B] tipa, je [A + B] tip\n\n   - _vpeljava_:\n\n      - če je [a : A], potem je [inl a : A + B]\n      - če je [b : B], potem je [inr b : A + B]\n\n   - _uporaba_: če pri predpostavki [x : A] velja [u(x) : C] in\n     če pri predpostavki [y : B] velja [v(y) : C] in če je [t : A + B], potem\n     ima\n     [(match t with\n       | inl x => u(x)\n       | inr y => v(y)\n      end)]\n     tip [C].\n\n   - _enačbe_:\n\n      - [match (inl a) with\n         | x => u(x)\n         | y => v(y)\n         end] je enako [u(a)].\n\n      - [match (inr b) with\n         | x => u(x)\n         | y => v(y)\n         end] je enako [v(b)].\n\n      - [match t with\n         | inl x => inl x\n         | inr y => inr y\n         end] je enako [t].\n\n*) \n\n(** ** Prazen tip\n\n    Nekoliko bolj nenavaden je prazen tip:\n\n    - _formacija_: [Empty_set] je tip\n   \n    - _vpeljava_: ni pravil za uporabo\n\n    - _uporaba_: če [t : Empty_set], potem ima [match t with end] tip [A]\n\n    - _enačbe_: [match t with end] je enako [a] za vse [a : A]\n*)\n\nSection FunkcijeVsote.\n  (** Predpostavimo, da imamo tipe [A], [B] in [C]. *)\n  Context {A B C : Type}.\n\n  Definition vaja3_1 : (A + B -> C) -> (A -> C) * (B -> C).\n  Admitted.\n\n  (* S stavkom match obravnavmo element, ki je vsota tipov. *)\n\n  Definition vaja3_2 : A + B -> B + A.\n  Admitted.\n\n  Definition vaja3_3 : (A + B) * C -> A * C + B * C.\n  Admitted.\n  \n  Definition vaja3_4 : A * C + B * C -> (A + B) * C.\n  Admitted.\n\n  Definition vaja3_5 : (A -> C) * (B -> C) -> (A + B -> C).\n  Admitted.\n\n  Definition vaja3_6 : Empty_set -> A.\n  Admitted.\n\n  Definition vaja3_7 : Empty_set + A -> A.\n  Admitted.\n\n  Definition vaja3_8 : A -> ((A -> Empty_set) -> Empty_set).\n  Admitted.\n\n  Definition vaja3_9 : A + (A -> Empty_set) -> (((A -> Empty_set) -> Empty_set) -> A).\n  Admitted.\n\nEnd FunkcijeVsote.\n\nSection Izomorfizmi2.\n  (** Sam ugotovi, kje potrebuješ funkcijsko ekstenzionalnost. *)\n\n  Context {A B C : Type}.\n\n  Definition vaja4_1 : A + B <~> B + A.\n  Proof.\n    admit.\n  Qed.\n\n  Definition vaja4_2 : (A + B) * C <~> A * C + B * C.\n  Proof.\n    admit.\n  Qed.\n\n  Definition vaja4_3 : (A + B -> C) <~> (A -> C) * (B -> C).\n  Proof.\n    admit.\n  Qed.\n\n  Definition vaja4_4 : Empty_set + A <~> A.\n  Proof.\n    admit.\n  Qed.\n\n  Definition vaja4_5 : (A -> Empty_set) <~> Empty_set.\n  Proof.\n    admit.\n  Qed.\n\n  Definition vaja5_5 : (Empty_set -> A) <~> unit.\n  Proof.\n    admit.\n  Qed.\n\nEnd Izomorfizmi2.\n\nSection Zabava.\n  (** Pa še neka vaj za zabavo. *)\n  Context {A B : Type}.\n\n  (* Koliko funkcij A * B -> A + B lahko definiraš? *)  \n  Definition vaja5_1_XX : A * B -> A + B.\n  Admitted.\n\n  (* Koliko funkcij tipa (A * A) * A -> A * A lahko definiraš? *)\n  Definition vaja5_2_XX : (A * A) * A -> A * A.\n  Admitted.\n\n  (* Koliko funkcij tipa (A -> A) -> (A -> A) lahko definiraš? *)\n  Definition vaja5_3_XX : (A -> A) -> (A -> A).\n  Admitted.\n\nEnd Zabava.\n", "meta": {"author": "andrejbauer", "repo": "lvr-coq", "sha": "b39e034ac4b9e373b08737dd064ac8972ff3d272", "save_path": "github-repos/coq/andrejbauer-lvr-coq", "path": "github-repos/coq/andrejbauer-lvr-coq/lvr-coq-b39e034ac4b9e373b08737dd064ac8972ff3d272/tipi-resitve-s-predavanj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.674117202841374}}
{"text": "Require Import ssreflect ssrbool ssrfun eqtype ssrnat div seq choice fintype.\nRequire Import finfun bigop finset.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nGoal FinSet [ffun x : 'I_3 => true] = setT.\napply/setP => /= x.\nrewrite {1}SetDef.pred_of_setE /=.\nrewrite {1}/in_mem.\nrewrite {1}/mem.\nrewrite /=.\nrewrite ffunE.\nrewrite in_setT.\ndone.\nQed.\n\n(* おまけ。 *)\nGoal [set: 'I_3] = setT.\napply/setP.\nby case => /=.\nQed.\n\nSection finset_example.\n\nVariable T : finType.\nVariables A B C : {set T}.\n\n(* use setP *)\nLemma exo20 : (A :&: B) :|: C = (A :|: C) :&: (B :|: C).\nProof.\n  Search (_ :&: _ :|: _).\n  by rewrite setUIl.\nQed.\n\nEnd finset_example.\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/jsst2014/ssr_jsst2014_finset_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.6741171958772978}}
{"text": "Theorem my_first_proof : (forall A : Prop, forall value_of_A: A, A).\nProof.\n  intros A.\n  (* intros proof_of_A.\n  exact proof_of_A. *)\n  intros value_of_B.\n  exact value_of_B.\n  (* case value_of_B. *)\n  (* elim value_of_B. *)\nQed.\n\nTheorem my_second_proof : (forall A : Prop, A -> A).\ntrivial.\nQed.\n\nTheorem forward_small : (forall A B : Prop, A -> (A->B) -> B).\nProof.\n intros A B.\n (* intros B. *)\n intros proof_of_A A_implies_B.\n (* intros A_implies_B. *)\n pose (proof_of_B := A_implies_B proof_of_A).\n exact proof_of_B.\nQed.\n\nTheorem lalal : (forall A B : Prop, A -> (A -> B) -> B).\nProof.\n  intros A B.\n  intros proof_of_A A_implies_B.\n  exact (A_implies_B proof_of_A).\nQed.\n\nTheorem forward_small_2 :\n (forall A B : Prop,\n  (forall value_of_A: A,\n   (forall A_implies_B: A->B, B))).\nProof.\n intros A B.\n (* intros B. *)\n intros proof_of_A A_implies_B.\n (* intros A_implies_B. *)\n pose (proof_of_B := A_implies_B proof_of_A).\n exact proof_of_B.\nQed.\n\nTheorem forward_small_3 : (forall A B : Prop, A -> (A->B) -> B).\nProof.\n intros A B.\n (* intros B. *)\n intros proof_of_A A_implies_B.\n (* intros A_implies_B. *)\n exact (A_implies_B proof_of_A).\nQed.\n\nTheorem backward_small : (forall A B : Prop, A -> (A->B)->B).\nProof.\n intros A B.\n intros proof_of_A A_implies_B.\n (* refine (A_implies_B _). *)\n refine (A_implies_B proof_of_A).\n (*  exact proof_of_A. *)\nQed.\n\nTheorem backward_huge : (forall A B C : Prop, A -> (A->B) -> (A->B->C) -> C).\nProof.\n intros A B C.\n intros proof_of_A A_implies_B A_imp_B_imp_C.\n refine (A_imp_B_imp_C _ _).\n  exact proof_of_A.\n\n  refine (A_implies_B _).\n   exact proof_of_A.\nShow Proof.\nQed.\n\nTheorem backward_huge2 : (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 exact (A_imp_B_imp_C proof_of_A (A_implies_B proof_of_A)).\nShow Proof.\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).\nShow Proof.\n (*exact proof_of_C.*)\n refine proof_of_C.\nShow Proof.\nQed.\nExtraction forward_huge.\n\n\n(* Inductive False : Prop := . *)\n\n\n(* Inductive True : Prop :=\n  | I : True.\n*)\n\n(*\nInductive bool : Set :=\n  | true : bool\n  | false : bool.\n*)\n\n(*\nDefinition not (A:Prop) := A -> False.\n*)\n\n(* Notation \"~ x\" := (not x) : type_scope. *)\n\n\nTheorem False_cannot_be_proven : ~False.\nProof.\n  (* unfold not. *)\n  (*unfold \"~ _\".*)\n  (* simpl. *)\n  intros proof_of_False.\n  exact proof_of_False.\nQed.\n\nTheorem False_cannot_be_proven2 : ~False.\nProof.\n  intros proof_of_False.\n  elim proof_of_False.\nQed.\n\n\nTheorem thm_true_imp_true : True -> True.\nProof.\n  intros proof_of_True.\n  exact I.\nQed.\n\n\nTheorem thm_false_imp_false : False -> False.\nProof.\n  intros.\n  case H.\nQed.\n\nTheorem thm_true_imp_false : ~(True -> False).\nProof.\n  unfold not.\n  intros True_implies_False.\n  case (True_implies_False I).\nQed.\n\nTheorem thm_true_imp_false_2 : ~(True -> False).\nProof.\n  intros T_implies_F.\n  refine (T_implies_F _).\n    case I.\n    case I.\n    elim I.\n    exact I.\nQed.\n\nTheorem thm_true_imp_false_3 : ~(True -> False).\nProof.\n  intros T_implies_F.\n  pose (f := T_implies_F I).\n  exact f.\nQed.\n\nTheorem absurd2 : forall A C : Prop, A -> ~ A -> C.\nProof.\n  intros A C.\n  intros proof_of_A.\n  intros not_A.\n  unfold not in not_A.\n  pose (f := not_A proof_of_A). \n  (* unfold not.\n  intros A_implies_False.\n  pose (f := A_implies_False proof_of_A). *)\n  case f.\nQed.\n\n\nTheorem absurd2_2 : forall A C : Prop, A -> ~ A -> C.\nProof.\n  intros A C.\n  intros proof_of_A.\n  intros not_A.\n  pose (f := not_A proof_of_A). \n  case f.\nQed.\n\nRequire Import Bool.\n\nDefinition eqb' (b1 b2:bool) : bool :=\n  match b1, b2 with\n    | true, true => true\n    | true, false => false\n    | false, true => false\n    | false, false => true\n  end.\n\nDefinition Is_true' (b:bool) :=\n  match b with\n    | true => True\n    | false => False\n  end.\n\n(*\nTheorem llala2 : forall b1 b2 : bool, eqb' b1 b2 = eqb b1 b2.\nProof.\n  intros b1 b2.\n  simpl.\n  case b1.\n    case b2.\n      pose (resEqb' := eqb' b1 b2).\n      pose (resEqb := eqb b1 b2).\n      exact (eqb' true true = eqb true true).\n*)\n\nTheorem true_is_True: Is_true true.\nProof.\n  unfold Is_true.\n  simpl.\n  exact I.\nQed.\n\nTheorem not_true_is_True: not (Is_true false).\n  unfold \"~\".\n  intros is_true_false.\n  simpl is_true_false.\n  unfold Is_true.\n  case is_true_false.\nQed.\n\nTheorem not_eqb_true_false: ~(Is_true (eqb true false)).\nProof.\n  simpl.\n  (*\n  unfold \"~\".\n  intros proof_of_False.\n  exact proof_of_False.\n  *)\n  exact False_cannot_be_proven.\nQed.\n\n\nTheorem eqb_a_a : (forall a : bool, Is_true (eqb a a)).\nProof.\n  intros a.\n  case a.\n    unfold Is_true.\n    simpl.\n    exact I.\n \n    simpl.\n    exact I. Qed.\n\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.\n    exact I.\n\n    simpl.\n    intros.\n    case H.\nQed.\n\n\n(*\nTheorem thm_eqb_a_t_2: (forall a:bool, (Is_true (eqb a true)) -> (Is_true a)).\nProof.\n  intros a.\n  simpl.\n  intros H.\n  case a.\n    simpl. trivial.\n    \n    simpl. simpl in H. \n\nQed.\n*)\n\n(* Inductive or (A B:Prop) : Prop :=\n  | or_introl : A -> A \\/ B\n  | or_intror : B -> A \\/ B\nwhere \"A \\/ B\" := (or A B) : type_scope. *)\n\n\nTheorem left_or : (forall A B : Prop, A -> A \\/ B).\nProof.\n  intros A B.\n  intros proof_of_A.\n  (* exact (or_introl 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\n\nTheorem right_or : (forall A B : Prop, B -> A \\/ B).\n  intros A B.\n  intros proof_of_B.\n  refine (or_intror _).\n    exact proof_of_B.\nQed.\n\nTheorem right_or2 : (forall A B : Prop, B -> A \\/ B).\n  intros A B.\n  intros proof_of_B.\n  refine (or_intror 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    exact (or_intror proof_of_A).\n  \n    intros proof_of_B.\n    exact (or_introl proof_of_B).\nQed.\n\n(*\nInductive and (A B:Prop) : Prop :=\n  conj : A -> B -> A /\\ B\n\nwhere \"A /\\ B\" := (and A B) : type_scope.\n*)\n\nTheorem both_and : (forall A B : Prop, A -> B -> A /\\ B).\nProof.\n  intros A B.\n  intros proof_of_A proof_of_B.\n  refine (conj _ _).\n    exact proof_of_A.\n    exact proof_of_B.\nQed.\nExtraction both_and.\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.\n    intros proof_of_B.\n    exact (conj proof_of_B proof_of_A).\nQed.\n\n\nTheorem and_commutes__again : (forall A B, A /\\ B -> B /\\ A).\nProof.\n  intros A B.\n  intros A_and_B.\n  destruct A_and_B as [ proof_of_A proof_of_B].\n  refine (conj _ _).\n    exact proof_of_B.\n    exact proof_of_A.\nQed.\n\n\n(*\nInfix \"&&\" := andb : bool_scope.\nInfix \"\" := orb : bool_scope.\n*)\n\n(*\nDefinition iff (A B:Prop) := (A -> B) /\\ (B -> A).\nNotation \"A <-> B\" := (iff A B) : type_scope.\n*)\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  \n  refine (conj _ _).\n    intros H.\n    case a, b.\n      simpl. exact (or_introl I).\n      simpl. exact (or_introl I).\n      simpl. exact (or_intror I).\n      simpl. simpl in H. (* exact (or_introl H). *) case H.\n\n    intros H.\n    case a, b.\n      simpl. exact I.\n      simpl. exact I.\n      simpl. exact I.\n      simpl. simpl in H. case H. trivial. trivial.\n\n  (*\n  case a.\n    case b.\n      simpl.\n      refine (conj _ _).\n        intros.\n        exact (or_introl I).\n\n        intros.\n        exact I.\n\n       \n      simpl.\n      refine (conj _ _).\n        intros.\n        exact (or_introl I).\n\n        intros.\n        exact I.\n\n    case b.\n      simpl.\n      refine (conj _ _).\n        intros.\n        exact (or_intror I).\n \n        intros _.\n        exact I.\n\n      simpl.\n      refine (conj _ _).\n        intros f.\n        exact (or_introl f).\n\n        intros f_or_f.\n        case f_or_f.\n          intros f.\n          exact f.\n\n          intros f.\n          exact f.\n  *)\nQed.\n        \nTheorem andb_is_and : (forall a b, Is_true (andb a b) <-> Is_true a /\\ Is_true b).\nProof.\n  intros a b.\n  unfold iff.\n  refine (conj _ _).\n    intros H.\n    case a, b.\n      simpl. exact (conj I I).\n      simpl. simpl in H. case H.\n      simpl. simpl in H. case H.\n      simpl. simpl in H. case H.\n\n    intros lala.\n    case a,b.\n      simpl. trivial.\n      simpl in lala. destruct lala as [ A B]. case B. (* case lala. intros _ f. exact f. *)\n      simpl. simpl in lala. case lala. intros f _. case f.\n      simpl. simpl in lala. case lala. intros f _. case f.\nQed.\n\n\nTheorem negb_is_not : (forall a, Is_true (negb a) <-> (~(Is_true a))).\nProof.\n  intros a.\n  unfold \"<->\".\n  unfold not.\n  (* case a. *)\n  refine (conj _ _).\n    case a.\n      simpl. intros f _. case f.\n      simpl. intros _ f. case f.\n\n    case a.\n      simpl. intros True_implies_False. exact (True_implies_False I).\n      simpl. intros _. exact I.\nQed.\n\nPrint ex.\n\nPrint or.\n\n(*\nInductive ex (A : Type) (P : A -> Prop) : Prop :=\n  ex_intro : forall x : A, P x -> ex (A) P.\n*)\n\n\n\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*)\n\nDefinition basic_predicate : bool -> Prop\n:=\n  (fun a => Is_true (andb a true))\n.\n\nTheorem thm_exists_basics : (ex basic_predicate).\nProof.\n  (*\n  pose (witness := true).\n  refine (ex_intro basic_predicate witness _).\n    unfold basic_predicate.\n    simpl.\n    exact I.\n  *)\n(*\nUnset Printing Notations.\n  simpl.\nSearchAbout .\nLocate \"exists\".\nPrint ex.\nCheck ex.\nExtraction ex.\n  pose (witness := true).\n  refine (ex_intro basic_predicate witness _).\n    simpl.\n    exact I.\n    intros H.\n    Check basic_predicate.\n    exact (basic_predicate true).  \n*)\n(*\nrefine (ex_intro basic_predicate true _).\n  simpl.\n  unfold basic_predicate.\n  simpl.\n  unfold Is_true.\n  exact (I).\n*)\n\nrefine (ex_intro _ true I).\n \nQed.\n\n Theorem thm_exists_basics__again : (exists a, Is_true (andb a true)).\nProof.\n  pose (witness := true).\n(*\n  refine (ex_intro _ _ _).\n  exact (Is_true (andb true true)).\n*)\n  refine (ex_intro _ witness _).\n    simpl.\n    exact I.\nQed.\n\nTheorem thm_forall_exists : (forall b, (exists a, Is_true(eqb a b))).\nProof.\n  intros b.\n  case b.\n    refine (ex_intro _ true I).\n    refine (ex_intro _ false I).\nQed.\n\nTheorem thm_forall_exists__again : (forall b, (exists a, Is_true(eqb a b))).\nProof.\n  intros b.\n  refine (ex_intro _ b _). \n     exact (eqb_a_a b).\nQed.\n\nTheorem thm_forall_exists__again2 : (forall (b : bool), (exists (a : bool), Is_true(eqb a b))).\nProof.\n  intros b.\n  refine ((ex_intro _) b _).\n    case b.\n      simpl.\n      exact I.\n\n      simpl.\n      exact I.\nQed.\n\n\nTheorem forall_exists : (forall P : Set->Prop, (forall x, ~(P x)) -> ~(exists x, P x)).\nProof.\n  intros p.\n  intros lala.\n  unfold not.\n  unfold not in lala.\n  intros existsbaba.\n  destruct existsbaba as [ ].\n  pose (haha := lala x).\n  pose (gaga := haha H).\n  case gaga.\nQed.\n\n\n\nTheorem forall_exists_2 : (forall P : Set->Prop, (forall x, ~(P x)) -> ~(exists x, P x)).\nProof.\n  intros P forallXNotPX notExistsPX.\n  unfold not in forallXNotPX, notExistsPX.\n  case notExistsPX.\n  intros x.\n  intros Px.\n  case (forallXNotPX x Px).\n  \n  (*\n  intros P forallXNotPX notExistsPX.\n  unfold not in forallXNotPX, notExistsPX.\n  destruct notExistsPX.\n  exact (forallXNotPX x H).\n  *)\nQed.\n\nTheorem exists_forall : (forall P : Set->Prop, ~(exists x, P x) -> (forall x, ~(P x))).\nProof.\n  intros.\n  unfold not.\n  unfold not in H.\n  intros Px.\n  case H.\n  exact (ex_intro P x Px).\nQed.\n\nTheorem lalala_eq : (forall (A : Set) (x : A), eq x x).\nProof.\n  intros.\n  exact (eq_refl : eq x x).\nQed.\n\n\nTheorem thm_eq_sym : (forall x y : Set, x = y -> y = x).\nProof.\nintros x y.\nintros eq_x_y.\n(*\ncase eq_x_y.\nexact eq_refl.\n*)\ndestruct eq_x_y.\nexact eq_refl.\nQed.\n\nTheorem thm_eq_trans : (forall x y z: Set, x = y -> y = z -> x = z).\nProof.\nintros.\ndestruct H, H0.\nexact eq_refl.\nQed.\n\n(*Require Coq.*)\nRequire Coq.Setoids.Setoid.\nTheorem thm_eq_trans__again : (forall x y z: Set, x = y -> y = z -> x = z).\nProof.\nintros.\nrewrite H.\nrewrite <- H0.\nexact eq_refl.\nQed.\n\nTheorem andb_sym : (forall a b, a && b = b && a).\nProof.\nintros.\ncase a,b.\n  simpl. exact eq_refl.\n  simpl. exact eq_refl. \n  simpl. exact eq_refl.\n  simpl. exact eq_refl.\nQed.\n\nTheorem neq_nega: (forall a, a <> (negb a)).\nProof.\nintros.\nunfold not.\ncase a.\n  unfold negb. discriminate.\n  unfold negb. intros. discriminate H.\nQed.\n\n\nTheorem plus_2_3 : (S (S O)) + (S (S (S O))) = (S (S (S (S (S O))))).\nProof.\n  simpl.\n  (* exact (eq_refl 5). *)\n  exact (eq_refl (S (S (S (S (S O)))))).\nQed.\n\nTheorem plus_O_n : (forall n, O + n = n).\nProof.\n  intros.\n  simpl.\n  exact (eq_refl n).\nQed.\n\n\nTheorem associativity_of_plus : (forall (n : nat) (m : nat), n + m = m + n).\nProof.\n  admit.\nQed.\n\nTheorem plus_n_O : (forall n, n + O = n).\nProof.\n  intros.\n  (* case n. *)\n  (*\n  induction n.\n    exact eq_refl.\n  \n    simpl.\n    rewrite IHn.\n    exact eq_refl.\n  *)\n  (* apply nat_ind with (n := n). *)\n  elim n.\n    (* apply eq_refl. *)\n    exact eq_refl.\n\n    intros m H.\n    simpl.\n    rewrite H.\n    exact (eq_refl).\nQed.\n\n\nTheorem plus_sym: (forall n m, n + m = m + n).\nProof.\n  intros n.\n  elim n.\n    intros m.\n    elim m.\n      simpl. exact (eq_refl).\n\n      intros.\n      simpl.\n      rewrite <- H.\n      simpl.\n      exact (eq_refl (S n0)).\n\n    intros.\n    simpl.\n    simpl H.\n    rewrite (H m).\n    elim m.\n      simpl. exact (eq_refl).\n\n      intros.\n      simpl.\n      rewrite H0.\n      exact (eq_refl).\nQed.\n\nRequire Import List.\n\nTheorem cons_adds_one_to_length :\n   (forall A:Type, (forall (x : A) (lst : list A),\n    length (x :: lst) = (S (length lst)))\n   ).\nProof.\n  intros.\n  simpl.\n  exact (eq_refl).\nQed.\n\n\n(*\nDefinition hd (A : Type) (default : A) (l : list A) : A\n:=\n  match l with\n    | nil => default\n    | h :: _ => h\n  end.\n*)\n\n\nDefinition my_hd_for_nat_lists : list nat -> nat\n:=\n  hd 0.\n\nCompute my_hd_for_nat_lists nil.\n\nCompute my_hd_for_nat_lists (5 :: 4 :: nil).\n\nTheorem correctness_of_hd :\n   (forall A:Type,\n   (forall (default : A) (x : A) (lst : list A),\n   (hd default nil) = default /\\ (hd default (x :: lst)) = x)).\nProof.\n  intros.\n  simpl.\n  refine (conj _ _).\n    exact eq_refl.\n    exact eq_refl.\nQed.\n\n\nDefinition hd_error (A : Type) (l : list A)\n:=\n  match l with\n    | nil => None\n    | x :: _ => Some x\n  end.\n\nCompute hd_error nat nil.\n\nCompute hd_error nat (5 :: 4 :: nil).\n\nTheorem correctness_of_hd_error :\n   (forall A:Type,\n   (forall (x : A) (lst : list A),\n   (hd_error A nil) = None /\\ (hd_error A (x :: lst)) = Some x)).\nProof.\n  intros.\n  simpl.\n  refine (conj _ _).\n    exact eq_refl.\n    exact eq_refl.\nQed.\n\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 cons_cant_equal_nil : (forall (A: Type), (forall (x : A) (rest : list A),\n  (x :: rest) <> nil)).\nProof.\n  unfold not.\n  intros.\n  discriminate H.\nQed.\n\nGoal forall A B C:Prop, A /\\ B /\\ C \\/ B /\\ C \\/ C /\\ A -> C.\n  intros.\n  decompose [and or] H.\n    assumption.\n    assumption.\n    assumption.\nQed.\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  unfold not.\n  intros.\n  assert (witness : ((x :: rest) = nil -> False)).\n    exact (cons_cant_equal_nil A x rest).\n  \n  refine (ex_intro _ witness _).\n  simpl.\n  exact (eq_refl).\nQed.\n\nDefinition tl_error (A : Type) (l : list A) \n  : option (list A) \n:= match l with\n   | nil => None\n   | _ :: tail => Some tail\n   end.\n\nTheorem correctness_of_tl_error :\n   (forall A:Type,\n   (forall (x : A) (lst : list A),\n   (tl_error A nil) = None /\\ (tl_error A (x :: lst)) = Some lst)).\nProof.\n  intros.\n  refine (conj _ _).\n    simpl.  trivial.\n    simpl.  trivial.\nQed.\n\nTheorem hd_tl :\n   (forall A:Type,\n   (forall (default : A) (x : A) (lst : list A),\n   (hd default (x::lst)) :: (tl (x::lst)) = (x :: lst))).\nProof.\n  intros.\n  simpl.\n  trivial.\nQed.\n\nTheorem app_nil_l : (forall A:Type, (forall l:list A, nil ++ l = l)).\nProof.\n  intros.\n  simpl.\n  trivial.\nQed.\n\nTheorem app_nil_r : (forall A:Type, (forall l:list A, l ++ nil = l)).\nProof.\n  intros.\n  elim l.\n    simpl. trivial.\n \n    intros.\n    simpl.\n    rewrite H.\n    trivial.\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  trivial.\nQed.\n\n\nTheorem app_assoc : forall A (l m n:list A), l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros.\n  simpl.\n  case l,m,n.\n    simpl. trivial.\n    \n    simpl. trivial.\n\n    simpl. trivial.\n\n    simpl. trivial.\n\n    simpl.\n    replace (app l nil) with (l).\n    replace (app l nil) with (l).\n    trivial.\n\n    pose (witness := app_nil_r A l).\n    rewrite (witness).\n    trivial.\n\n    pose (witness := app_nil_r A l).\n    rewrite (witness).\n    trivial.\n\n    simpl.\n    replace (app l nil) with (l).\n    trivial.\n\n    pose (witness := app_nil_r A l).\n    rewrite (witness).\n    trivial.\n\n    simpl.\n\n    admit.\n    \n    admit.\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  intros.\n  case x, y.\n    simpl in H.\n    discriminate H.\n\n    discriminate H.\n    \n    discriminate H.\n\n    discriminate H.\nQed.\n    \n", "meta": {"author": "cdepillabout", "repo": "coqplayground", "sha": "c0fa0cfdcffdfdd6e91f3c51dcbe92f2c4d26e18", "save_path": "github-repos/coq/cdepillabout-coqplayground", "path": "github-repos/coq/cdepillabout-coqplayground/coqplayground-c0fa0cfdcffdfdd6e91f3c51dcbe92f2c4d26e18/what.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6741171875641883}}
{"text": "Inductive day : Type :=\n| sun : day\n| mon : day\n| tue : day\n| wed : day\n| thu : day\n| fri : day\n| sat : day.\n\nLet 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\nDefinition prev_day d :=\n  match d with\n  | sun => sat\n  | mon => sun\n  | tue => mon\n  | wed => tue\n  | thu => wed\n  | fri => thu\n  | sat => fri\n  end.\n\nTheorem wed_after_tue : next_day tue = wed.\nProof.\n  auto.\nQed.\n\nTheorem wed_after_tue' : next_day tue = wed.\nProof.\n  simpl. trivial.\nQed.\n\n\nTheorem day_never_repeats : forall d : day, next_day d <> d.\nProof.\n  intros d. destruct d.\n  all: discriminate.\nQed.\n\nTheorem day_never_repeats'' : forall d : day, next_day d <> d.\nProof.\n  intros d. destruct d; discriminate.\nQed.\n\nTheorem mon_preceds_tues : forall d : day, \n  next_day d = tue -> d = mon.\nProof.\n  intros d next_day_is_tue.\n  destruct d.\n  all: discriminate || trivial.\nQed.\n\n\n", "meta": {"author": "sheeraSearch82", "repo": "Coq_assignments", "sha": "e93136c16ecebbbfe09cb356845f9b29f5850bfb", "save_path": "github-repos/coq/sheeraSearch82-Coq_assignments", "path": "github-repos/coq/sheeraSearch82-Coq_assignments/Coq_assignments-e93136c16ecebbbfe09cb356845f9b29f5850bfb/dayexample.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.6741073979290885}}
{"text": "From Coq Require Export List.\nFrom Coq Require Import Nat Recdef Lia.\nExport ListNotations.\n\n(* Verification of a simple SAT solver\n * -----------------------------------\n *)\n\n\n(* Types defining the problem and solution\n   ---------------------------------------\n\n   The solver takes as input a query in CNF form, representing a conjunction of\n   clauses, where each clause represents a conjunction of literals.\n\n   Each literal represents a boolean variable (or its negation), and the goal of\n   the solver is to produce a boolean assignation for each literal present in\n   the input formula.\n*)\n\n(* A literal. [Pos n] corresponds to literal n, and [Neg n] to its negation.\n*)\nInductive literal :=\n  | Pos : nat -> literal\n  | Neg : nat -> literal.\n\n(* A clause represents a disjunction of literals *)\nDefinition clause := list literal.\n\n(* A SAT problem in Conjunctive Normal Form:\n   it corresponds to a conjunction of clauses *)\nDefinition cnf := list clause.\n\n(* Example:\n\n   The following cnf:\n   [[Pos 1; Neg 2];\n    [Neg 1; Pos 3; Pos 4]]\n\n   corresponds to the boolean formula:\n   (x1 \\/ ~x2) /\\\n   (~x1 \\/ x3 \\/ x4)\n\n   where x1, x2, x3 and x4 are boolean variables.\n*)\n\n(* The goal of the solver is to produce an assignment. We represent it as a list\n   of literals, which correspond to the literals that are taken to be true.\n\n   In other words, if the assignment list contains [Neg 3], then the boolean\n   variable x3 should be assigned to false.\n\n   Note: we generally only want to consider \"valid\" assignments, which do not\n   include both a literal and its negation. We will come back to this later (see\n   [valid_assignment]).\n*)\nDefinition assignment := list literal.\n\n(* In fact, the solver we implement will return a list of all possible\n   solutions.\n\n   (This would be terribly inefficient if we were to run the solver and compute\n   the full list of solutions, but we can instead compute it using a\n   call-by-name strategy (thus, the list of solutions becomes a lazy list), and\n   only retrieve the first solution of the list.)\n*)\nDefinition solutions := list assignment.\n\n\n(* Helper functions and lemmas\n   ---------------------------\n\n   Mainly define the (computable) equality function on literals,\n   literal negation, and associated lemmas.\n*)\n\n(* Some auxiliary functions on literals. *)\nDefinition lit_eqb (l1 l2: literal): bool :=\n  match l1, l2 with\n  | Pos u, Pos v\n  | Neg u, Neg v => u =? v\n  | _, _ => false\n  end.\n\nLemma lit_eqb_eq l1 l2: lit_eqb l1 l2 = true <-> l1 = l2.\nProof.\n  destruct l1, l2; cbn; try now (split; congruence).\n  all: rewrite PeanoNat.Nat.eqb_eq; split; congruence.\nQed.\n\nLemma lit_eqb_neq l1 l2 : lit_eqb l1 l2 = false <-> l1 <> l2.\nProof.\n  destruct l1, l2; cbn; try now (split; congruence).\n  all: rewrite PeanoNat.Nat.eqb_neq; split; congruence.\nQed.\n\nDefinition lit_neg (l: literal): literal :=\n  match l with\n  | Pos n => Neg n\n  | Neg n => Pos n\n  end.\n\nLemma lit_neg_idemp (l: literal) : lit_neg (lit_neg l) = l.\nProof. destruct l; auto. Qed.\n\n(* The size of a CNF, defined as the the number of its literals.\n   Used to prove termination of the solver. *)\nFixpoint cnf_size (c: cnf): nat :=\n  match c with\n  | [] => 0\n  | cl :: rest => length cl + cnf_size rest\n  end.\n\nLtac case_if :=\n  match goal with\n    |- context [if ?b then _ else _] =>\n    destruct b eqn:?\n  end.\n\nLemma existsb_lit_notin l c : existsb (lit_eqb l) c = false <-> ~ In l c.\nProof.\n  split.\n  { intros ? ?. enough (existsb (lit_eqb l) c = true) by congruence.\n    apply existsb_exists. eexists; split; eauto. apply lit_eqb_eq; auto. }\n  { intros HH. destruct (existsb (lit_eqb l) c) eqn:Heq; auto. exfalso.\n    apply existsb_exists in Heq as [? [? ->%lit_eqb_eq]]. apply HH. auto. }\nQed.\n\n\n\n(* The solver definition\n   ------------------------\n\n   This is the implementation of the SAT solver itself.\n\n   Its main function is [resolve]. It relies on the [propagate] auxiliary\n   function, which implements literal propagation.\n\n   The high-level intuition is that [propagate l c] takes a literal [l] and a\n   cnf [c], and, assuming that [l] is to be assigned to true, simplifies [c]\n   into a new cnf which does not rely on [l] or [lit_neg l] anymore.\n\n\n   The [_variant] lemmas can be ignored, they are only used in the (included)\n   proof of termination for defining [resolve].\n*)\n\nDefinition remove_lit (l: literal) (cl: clause) :=\n  List.filter (fun l' => negb (lit_eqb l l')) cl.\n\nFixpoint propagate (l: literal) (c: cnf) : cnf :=\n  match c with\n  | [] => []\n  | cl :: rest =>\n    if List.existsb (lit_eqb l) cl\n    then propagate l rest\n    else (remove_lit (lit_neg l) cl) :: (propagate l rest)\n  end.\n\nLemma remove_lit_variant (l: literal) (cl: clause):\n  length (remove_lit l cl) <= length cl.\nProof.\n  induction cl as [| ? ? IHcl]; cbn; try case_if; cbn; auto.\n  unfold remove_lit in IHcl. lia.\nQed.\n\nLemma propagate_variant (l: literal) (c: cnf):\n  cnf_size (propagate l c) <= cnf_size c.\nProof.\n  induction c as [| cl c IHc]; cbn; auto.\n  case_if; cbn; try lia. pose proof (remove_lit_variant (lit_neg l) cl).\n  lia.\nQed.\n\nFunction resolve (c: cnf) {measure cnf_size c}: solutions :=\n  match c with\n  | [] => [[]]\n  | cl :: rest =>\n    match cl with\n    | [] => []\n    | l :: cl' =>\n      let c1 := propagate l rest in\n      let c2 := propagate (lit_neg l) (cl' :: rest) in\n      let solutions1 := List.map (List.cons l) (resolve c1) in\n      let solutions2 := List.map (List.cons (lit_neg l)) (resolve c2) in\n      solutions1 ++ solutions2\n    end\n  end.\nProof.\n  (* Proof of termination *)\n  all: intros c cl rest l cl'; intros -> ->; cbn.\n  { destruct (existsb (lit_eqb (lit_neg l))); cbn.\n    - pose proof (propagate_variant (lit_neg l) rest). lia.\n    - pose proof (remove_lit_variant (lit_neg (lit_neg l)) cl').\n      pose proof (propagate_variant (lit_neg l) rest). lia. }\n  { pose proof (propagate_variant l rest). lia. }\nDefined.\n\n(* NB: Function generates an induction principle for [resolve], and a lemma to\n   unfold its body. You will need to use them. *)\nCheck resolve_ind.\nCheck resolve_equation.\n\n\n(* Interpretation of clauses and cnf\n   ------------------------------------\n\n   Given an assignment, we can \"evaluate\" a clause/a cnf as a boolean.\n   This is done by the [interp] functions below.\n *)\n\nFixpoint interp_clause (cl: clause) (a: assignment): bool :=\n  match cl with\n  | [] => false\n  | l :: cl' => List.existsb (lit_eqb l) a || interp_clause cl' a\n  end.\n\nFixpoint interp (c: cnf) (a: assignment): bool :=\n  match c with\n  | [] => true\n  | cl :: rest => interp_clause cl a && interp rest a\n  end.\n\n\n\n(* To prove correctness of [resolve] in the unsat case we will need to define\nwhat a *valid* assignment is, i.e. one that does not contain both a literal and\nits negation. *)\nDefinition valid_assignment (a: assignment) :=\n  forall (l: literal),\n    List.In l a ->\n    ~ List.In (lit_neg l) a.\n\n    From Coq Require Import List Nat Recdef Lia.\n    Import ListNotations.\n    \n    \n    (* 1) Correctness of solutions returned by [resolve]\n    -------------------------------------------------\n    \n       A first correctness lemma: assignments produced by [resolve] are correct wrt\n       [interp].\n    *)\n    \n    (* The core of the proof relies on a similar correctness lemma for [propagate]. *)\n    Lemma propagate_correct (a: assignment) (l: literal) (c: cnf) :\n      interp (propagate l c) a = true ->\n      interp c (l :: a) = true.\n    Admitted.\n    \n    Lemma resolve_correct (c: cnf) (a: assignment):\n      List.In a (resolve c) ->\n      interp c a = true.\n    Admitted.\n    \n    \n    \n    (* 2) Correctness of [resolve] in the unsat case\n       ---------------------------------------------\n    \n       If [resolve] returns no solutions (the empty list), then the input CNF should\n       be unsatisfiable.\n    \n       To formally state this property, we first need to define what a *valid*\n       assignment is, i.e. one that does not contain both a literal and its negation.\n    *)\n    \n    (* You will need to formulate a lemma for [propagate], in a similar vein as\n       [propagate_correct].\n    \n       However, there's an extra subtlety here. Think: does the following hold\n       if (lit_neg) is in a?\n    \n         interp (propagate l c) a = false ->\n         interp c (l :: a) = false\n    *)\n    \n    Lemma resolve_unsat_correct (c: cnf):\n      resolve c = [] ->\n      forall a, valid_assignment a -> interp c a = false.\n    Admitted.\n    \n    \n    (* ==== This part is OPTIONAL and it is NOT graded. === *)\n    (* ==== We keep this for the sake of completeness of the specification === *)\n    (* ==== but exclude it from grading to keep the task complexity at bay. === *)\n    \n    (* 3) Validity of assignments produced by [resolve]\n       ------------------------------------------------\n    \n       To complete the proof of the solver, we finally need to prove that it only\n       produces valid assignments. Otherwise, a solver could simply return an\n       assignment containing every literal and its negation, which would be\n       considered as a valid solution according to [interp].\n    \n       The key idea is to prove that, for any literal that appears in an assignment\n       returned by [resolve c], then either the literal or its negation were present\n       in [c].\n    *)\n    \n    (* useful helper lemmas *)\n    Lemma valid_assignment_nil : valid_assignment [].\n    Proof. intros ? ?. cbn in *. auto. Qed.\n    \n    Lemma valid_assignment_cons a l:\n      valid_assignment a ->\n      ~ List.In (lit_neg l) a ->\n      valid_assignment (l :: a).\n    Proof.\n      intros Hv Ha l'. cbn. intros [->|Hl'].\n      { intros HH. apply Ha. destruct HH; auto. exfalso.\n        destruct l'; cbn in *; congruence. }\n      { intros [?|HH].\n        { subst l. rewrite lit_neg_idemp in Ha. auto. }\n        { eapply (Hv l' Hl'); auto. } }\n    Qed.\n    \n    Lemma resolve_valid (c: cnf) (a: assignment):\n      List.In a (resolve c) ->\n      valid_assignment a.\n    Admitted.", "meta": {"author": "jsarracino", "repo": "mirrorsolve", "sha": "74fc7790b21952d4f27ea70545b0038f298915b0", "save_path": "github-repos/coq/jsarracino-mirrorsolve", "path": "github-repos/coq/jsarracino-mirrorsolve/mirrorsolve-74fc7790b21952d4f27ea70545b0038f298915b0/tests/case-studies/SAT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126791, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.6741073871432619}}
{"text": "\n\n\n(*-------------Description ------------------------------------------------------  \n\nThis file implements maps on lists. Here we define functions to calculate range \nof a function on list l. We also define one-one function predicate and its boolean\ncounterpart. \n\nFollowing are the notions defined in this file:\n\n img f l                  : range set of f on list l\n one_one_on l f             : f is one one on l\n one_one_onb l f            : boolean counterpart of (one_one_on l f)\n\nLemma one_one_onP (l:list A) (f: A->B)(Hl: NoDup l):\n    reflect (one_one_on l f)(one_one_onb l f).\n\nFurthermore, we have results relating the cardinality of domain and range \nfor various kinds of functions (many one/one one).\n\n---------------------------------------------------------------------------------*)\n\n\nRequire Export SetReflect.\nRequire Export OrdList.\nRequire Export OrdSet.\n\n\nSet Implicit Arguments.\n\nSection List_maps.\n\n  Context { A B: Type }.\n\n  (*------- This definition of map on lists is from standard library --------------*)\n\n  (*  Lemma map_cons (x:A)(l:list A) : map (x::l) = (f x) :: (map l).\n\n      Lemma in_map :\n      forall (l:list A) (x:A), In x l -> In (f x) (map l).\n\n      Lemma in_map_iff : forall l y, In y (map l) <-> exists x, f x = y /\\ In x l.\n\n      Lemma map_length : forall l, length (map l) = length l.   *)\n\n  Lemma map_intro (f: A-> B): forall (l:list A) (x:A), In x l -> In (f x) (map f l).\n  Proof. apply in_map. Qed.\n\n  Lemma map_intro1 (f: A-> B)(l: list A) (y:B): (exists x, In x l /\\ y = f x) -> In y (map f l).\n  Proof. { intros h1. apply in_map_iff. destruct h1 as [x h1].\n           destruct h1 as [h1 h2]. exists x. split;auto. } Qed.\n\n  Lemma map_elim (f: A-> B)(l: list A) (y:B): In y (map f l) -> (exists x, In x l /\\ y = f x).\n  Proof. { intros h1. apply in_map_iff in h1 as h2.\n           destruct h2 as [x h2]. destruct h2 as [h2a h2].\n           exists x. split;auto. } Qed.\n  Lemma map_length_same (f: A-> B)(l: list A): |l| = |map f l|.\n  Proof. symmetry;apply map_length. Qed.\n\n  Hint Immediate map_elim map_intro map_intro1 map_length_same: core.\n\nEnd List_maps.\n\nHint Immediate map_elim map_intro map_intro1 map_length_same: core.\n\n\nSection Set_maps.\n  Context { A B: ordType }.    \n\n  Lemma EM_A: forall x y: A, x=y \\/  x<>y.\n  Proof.  eauto.  Qed.\n  Lemma EM_B: forall x y:B, x=y \\/ x<>y.\n  Proof. eauto.  Qed.\n\n  \n  Fixpoint img (f:A->B) (l:list A): list B:= match l with\n                                        | nil => nil\n                                        | a1::l1 => add (f a1) (img f l1)\n                                              end.\n\n  Lemma IsOrd_img (f:A->B) (l:list A):  IsOrd (img f l).\n  Proof. { induction l. simpl. constructor. simpl. eauto. } Qed.\n  \n  Lemma NoDup_img (f:A->B) (l:list A):  NoDup (img f l).\n    Proof. cut (IsOrd (img f l)). eauto. apply IsOrd_img. Qed.\n  \n  Lemma img_intro1(f: A->B)(l: list A)(a:A)(y: B): In y (img f l)-> In y (img f (a::l)).\n    Proof. simpl. eapply set_add_intro1. Qed.\n  Lemma img_intro2 (f: A->B)(l: list A)(x:A): In x l -> In (f x) (img f l).\n  Proof.  { induction l. simpl.  tauto.\n          cut (x=a \\/ x <> a). \n          intro H;destruct H as [Hl | Hr].\n          { intro H. rewrite Hl. simpl. eapply set_add_intro2. auto. }\n          { intro H. cut (In x l). intro H1. eapply img_intro1;eauto.\n            eapply in_inv2;eauto.  } eauto. } Qed.\n\n  Lemma img_elim (f:A->B) (l: list A)(a0:A)(fa:B): In (fa) (img f (a0::l))->\n                                                    fa = f(a0) \\/ In fa (img f l).\n    Proof. simpl. eapply set_add_elim. Qed.\n\n  Lemma img_elim2 (f:A->B) (l: list A)(a0:A)(fa:B): In (fa) (img f (a0::l))->\n                                                   fa <> f(a0) -> In fa (img f l).\n  Proof. simpl. eapply set_add_elim2.  Qed.\n  \n  Lemma img_elim3 (f:A->B)(l:list A)(a:A): ~ In a l -> In (f a) (img f l) ->\n                                           (exists y, In y l /\\ f a = f y).\n  Proof. { intros H H1. induction l. inversion H1.\n         assert (H2: ~ In a l). intro H2; apply H. simpl;tauto. \n         cut ( f a = f a0 \\/ f a <> f a0 ). intro H3; destruct H3 as [H3a | H3b]. exists a0.\n         split; auto. assert (H4: In (f a) (img f l)). eapply img_elim2.\n         eapply H1. exact H3b. assert (H5: exists y : A, In y l /\\ f a = f y). eauto.\n         destruct H5 as [y0 H5]. exists y0. split;  simpl. tauto. tauto.\n         eapply EM_B. } Qed.\n  Lemma img_elim4 (f: A->B)(l: list A)(b:B): In b (img f l)-> (exists a, In a l /\\ b = f a).\n  Proof. { induction l.\n         { simpl. tauto. }\n         { intro H. apply img_elim in H as H1. destruct H1.\n           { exists a. split;auto. }\n           { apply IHl in H0 as H1.\n             destruct H1 as [a' H1]; destruct H1 as [H1 H2].\n             exists a'. split;auto. } } } Qed.\n        \n  Hint Resolve IsOrd_img NoDup_img : core.\n  Hint Resolve img_intro1 img_intro2 img_elim: core.\n  Hint Resolve img_elim2 img_elim3 img_elim4: core.\n\n  Lemma map_is_img (f: A-> B)(l: list A): IsOrd (map f l) -> (map f l) = (img f l).\n  Proof. { intro h1. apply set_equal. auto. auto.\n           split.\n           { intros y h2. assert (h3: exists x, In x l /\\ y = f x). auto.\n             destruct h3 as [x h3]; destruct h3 as [h3a h3]. subst y; auto. }\n           { intros y h2. assert (h3: exists x, In x l /\\ y = f x). auto.\n             destruct h3 as [x h3]; destruct h3 as [h3a h3]. subst y; auto. } } Qed.\n\n  Hint Immediate map_is_img: core.\n  \n  Lemma funP (f: A->B)(x y: A): f x <> f y -> x <> y.\n  Proof. intros H H1. apply H;rewrite H1; auto. Qed.\n  \n  Definition one_one (f: A->B): Prop:= forall x y, x <> y -> f x <> f y.\n  \n  Lemma one_oneP1 (f:A->B): one_one f -> forall x y, f x = f y -> x =y.\n  Proof. { unfold one_one;intros H x y H1. elim (EM_A x y). tauto.\n           intro H2; absurd (f x = f y); auto. } Qed.\n  \n  Hint Immediate one_oneP1: core.\n  \n  Definition one_one_on (l: list A) (f: A-> B):Prop:= forall x y, In x l-> In y l ->  x<>y -> f x <> f y.\n  \n  Lemma one_one_on_elim (l:list A)(f: A-> B): one_one_on l f ->\n                                         (forall x y, In x l-> In y l-> f x = f y -> x = y). \n  Proof. { unfold one_one_on. intros H x y H1 H2. elim (EM_A x y). tauto.\n           intros H3 H4. absurd (f x = f y); auto. } Qed.\n  Lemma one_one_on_intro(l:list A)(f: A-> B): (forall x y, In x l-> In y l-> f x = f y -> x = y) ->\n                                         (one_one_on l f).\n  Proof. { intros H.  unfold one_one_on.\n         intros x y H1 H2 H3 H4. apply H3. auto. } Qed.  \n\n  Lemma one_one_on_nil (f:A->B): one_one_on nil f.\n  Proof. unfold one_one_on. intros x y H H0 H1 H2. inversion H. Qed.\n\n  Lemma one_one_on_intro1(l:list A) (f: A->B)(a:A):\n             (~ In (f a) (img f l)) -> (one_one_on l f) -> one_one_on (a::l) f.\n  Proof. { unfold one_one_on. intros H H1. \n         intros x y H2 H3. destruct H2; destruct H3.\n         rewrite <- H0; rewrite <- H2.  tauto.\n         rewrite <- H0. intros H3 H4. assert (H5: In (f a) (img f l)). rewrite H4.\n         apply img_intro2;auto. absurd (In (f a) (img f l)); assumption.\n         rewrite <- H2. intros H3 H4. absurd (In (f a) (img f l)). assumption.\n         rewrite <- H4. apply img_intro2;auto. apply H1; auto. } Qed.\n \n  Lemma one_one_on_elim1 (l:list A) (f: A->B)(a: A): one_one_on (a::l) f -> one_one_on l f.\n  Proof. { unfold one_one_on.  intro H. intros x y H1 H2. eapply H; auto. } Qed.\n  \n  Lemma one_one_on_elim2 (l:list A) (f: A->B)(a: A)(Hl: NoDup (a::l)):\n    one_one_on (a::l) f -> ~ In (f a)(img f l).\n  Proof. { unfold one_one_on.  intros H H1.\n         assert (H2: (exists y, In y l /\\ f a = f y)).\n         { eapply img_elim3. intro H2; inversion Hl;contradiction. auto. }\n         destruct H2 as [b H2]; destruct H2 as [H2 H3].\n         eapply H with (x:=a)(y:=b); auto. intro H4. rewrite <- H4 in H2.\n         inversion Hl;contradiction. } Qed.\n \n  \n  Hint Immediate one_one_on_nil one_one_on_elim one_one_on_elim1 one_one_on_elim2 : core.\n  Hint Immediate one_one_on_intro one_one_on_intro1: core.\n\n\n  Lemma NoDup_map (f:A->B) (l:list A): NoDup l-> one_one_on l f-> NoDup (map f l).\n  Proof. { induction l as [| a l'].\n           { simpl. auto. }\n           { intros h1 h2. simpl.\n             apply nodup_intro.\n             { intro h3.\n               assert (h3a: exists b, In b l' /\\ (f a) = (f b)).\n               { auto. } destruct h3a as [b h3a]. destruct h3a as [h3a h3b].\n               unfold one_one_on in h2.\n               absurd (f a = f b). apply h2. auto. auto. intros h4. subst b.\n               absurd (In a l'); auto. auto. }\n             apply IHl'. eauto. eauto. } } Qed.\n\n  Hint Resolve NoDup_map: core.\n\n  Lemma map_IsOrd (f: A->B)(l:list A):\n    IsOrd l -> (forall x y, In x l-> In y l-> x <b y -> f x <b f y)-> IsOrd (map f l).\n  Proof. { induction l as [|a l'].\n           { intros h1 h2. simpl. constructor. }\n           { intros h1 h2. simpl. apply IsOrd_intro.\n             apply IHl'. eauto. intros x y hx hy;apply h2;eauto.\n             intros fx h3. assert(h4: exists x, In x l' /\\ fx = f x). auto.\n             destruct h4 as [x h4]. destruct h4 as [h4 h5].\n             subst fx. apply h2;eauto. } } Qed.\n\n  Hint Resolve map_IsOrd: core.\n   \n\n  Fixpoint one_one_onb (l: list A) (f: A->B): bool:=\n    match l with\n    |nil => true\n    | a1::l1 => (negb ( memb (f a1) (img f l1))) && (one_one_onb l1 f)\n    end.\n\n\n   Lemma one_one_onP (l:list A) (f: A->B)(Hl: NoDup l):\n    reflect (one_one_on l f)(one_one_onb l f).\n  Proof. { apply reflect_intro. split.\n         { induction l.\n           { unfold one_one_onb. reflexivity. }\n           { intro H. simpl one_one_onb. apply /andP. split. cut (~ In (f a)(img f l)).\n             intro H1. assert (H2:  memb (f a) (img f l) = false ). apply /membP.\n             auto. rewrite H2. simpl. reflexivity. eapply one_one_on_elim2.\n             apply Hl. auto. apply IHl.\n             eauto. eauto. } }   \n         { induction l.\n           { auto.  }\n           { simpl. move /andP. intro H; destruct H as [H H1].\n             apply one_one_on_intro1.  \n             intro H2. unfold negb in H.\n             replace (memb (f a) (img f l)) with true in H. inversion H.\n             symmetry; apply /membP; eauto. apply IHl. eauto. apply H1. } }  } Qed.\n\n \n\n  (*--------- Some more properties of imgs-----------------------------------*)\n\n  Lemma one_one_img_elim (l: list A)(f: A->B)(x: A):\n    one_one f -> In (f x) (img f l) -> In x l.\n  Proof. { intros H H1. assert (H2: exists a, In a l /\\ f x = f a). auto.\n         destruct H2 as [a H2]. destruct H2 as [H2 H3].\n         cut (x = a). intros; subst x; auto. eauto. } Qed.\n  \n  Lemma img_subset (l s: list A)(f: A->B): l [<=] s -> (img f l) [<=] (img f s).\n  Proof. { intros H fx H1. assert (H2: exists x, In x l /\\ fx = f x). auto.\n         destruct H2 as [x H2]. destruct H2 as [H2 H3]. subst fx; auto. } Qed.\n\n  Lemma img_size_less (l: list A)(f: A->B): |img f l| <= |l|.\n  Proof.  { induction l.\n          { simpl;auto. }\n          { simpl. assert (H: (| add (f a) (img f l) |) <= S (| img f l |)).\n            auto. omega. } } Qed.\n          \n  Lemma img_size_same (l: list A)(f: A->B): NoDup l -> one_one_on l f-> |l|=| img f l|.\n  Proof.  { induction l.\n          { simpl. auto. }\n          { intros H H1.\n            assert (Hl: NoDup l). eauto.\n            assert (H1a: one_one_on l f). eauto.\n            assert (H2: (| l |) = (| img f l |)). auto.\n            simpl. assert (H3: ~ In (f a) (img f l)). auto.\n            rewrite H2; symmetry;auto. }  } Qed.\n  \n\n  Hint Resolve img_subset img_size_less img_size_same: core.\n\n  \n  Lemma img_strict_less (l: list A)(f: A->B):\n    NoDup l -> (|img f l| < |l|) -> ~ one_one_on l f.\n  Proof. intros H H1 H2. assert(H3: |l|=| img f l|). auto. omega. Qed. \n\n  Hint Immediate one_one_img_elim  img_strict_less : core.\n\n  \n  Lemma one_one_on_intro2 (l: list A)(f: A->B):\n    NoDup l -> (|img f l| = |l|)->  one_one_on l f.\n  Proof.  { induction l.\n          { simpl; auto. }\n          { intros H H0.\n            assert (Ha: NoDup l). eauto.\n            assert (Hb: ~ In a l ). auto.\n            assert (H1: |img f l| = |l|).\n            { match_up  (| img f l |)  (| l |).\n              { auto. }\n              { assert ((| img f (a :: l) |) <b (| a :: l |)).\n                { move /ltP in H1. apply /ltP. simpl.\n                  cut ((| add (f a) (img f l) |) <= S (|img f l|)). omega.\n                  auto. } by_conflict. }\n              { assert (H2: |img f l| <= |l|). auto.\n                move /lebP in H2. auto. } } \n            assert (H2: one_one_on l f). auto.\n            assert (H3: ~ In (f a) (img f l)).\n            { intro H3.\n              assert (H4: img f (a :: l) = (img f l)).\n              { simpl. eapply add_same. auto. auto. }\n              rewrite H4 in H0. rewrite H1 in H0. simpl in H0. omega. } auto. } } Qed.\n            \n\n  Lemma one_one_on_intro3 (l s: list A)(f: A-> B): s [<=] l -> one_one_on l f -> one_one_on s f.\n  Proof. intros H0 H1; unfold one_one_on; auto. Qed.\n\n  Hint Immediate one_one_on_intro2 one_one_on_intro3 : core.\n\n  (* ------------ set maps and set add interaction ------------------------ *)\n\n  Lemma img_add (a: A)(l: list A)(f: A-> B): img f (add a l) = add (f a) (img f l).\n  Proof. { apply set_equal;auto.\n         induction l.\n         { simpl. auto. }\n         {  simpl.\n           assert (H:  img f (add a l) = add (f a) (img f l)).\n           apply set_equal; auto.\n           destruct IHl as [IHl IHl1].  match_up a  a0.\n           { subst a. simpl. auto. }\n           { simpl. auto. }\n           { simpl. rewrite H. auto. } }  } Qed.\n            \n  Lemma img_same (l: list A) (f g: A->B): (forall x, In x l -> f x = g x)-> (img f l = img g l).\n  Proof. {  induction l.\n         { simpl; auto. }\n         { intro h1. simpl. replace (g a) with (f a). replace (img g l) with (img f l).\n           auto. apply IHl. intros x h2. apply h1; auto. apply h1; auto. } } Qed. \n  \n  Hint Resolve img_add img_same: core.\n\n  Lemma img_inter1 (l s: list A)(f: A-> B): img f (l [i] s) [<=] (img f l) [i] (img f s).\n  Proof. { intros y hy.\n           assert(h1: exists x, In x (l [i] s) /\\ y = f  x); auto.\n           destruct h1 as [x h1]. destruct h1 as [h1a h1].\n           cut (In y (img f s)). cut (In y (img f l)). auto.\n           subst y. cut (In x l); auto. eauto.\n           subst y. cut (In x s); auto. eauto. } Qed.\n  \n  Lemma img_inter2 (l s: list A)(f: A-> B): one_one_on (l [u] s) f ->\n                                             img f (l [i] s) = (img f l) [i] (img f s).\n  Proof. { intros h. apply set_equal. all: auto.\n           split. apply img_inter1. intros y h1.\n           assert (h1a: In y (img f l)). eauto.\n           assert (h1b: In y (img f s)). eauto.\n           assert (hx1: exists x, In x l /\\ y = f x). auto.\n           destruct hx1 as [x1 hx1]. destruct hx1 as [hx1 h2].\n           assert (hx2: exists x, In x s /\\ y = f x). auto.\n           destruct hx2 as [x2 hx2]. destruct hx2 as [hx2 h3].\n           subst y. assert (h4: x1 = x2).\n           cut (In x1 (l [u] s)). cut (In x2 (l [u] s)). eauto.\n           all: auto.\n           assert (h5: In x1 (l [i] s)). rewrite <- h4 in hx2; auto. auto. } Qed.\n\n  Lemma img_union (l s: list A)(f: A-> B): img f (l [u] s) = (img f l) [u] (img f s).\n  Proof.  { apply set_equal. all: auto.\n            split.\n            { intros y h1.\n              assert (hx1: exists x, In x (l [u] s) /\\ y = f x). auto.\n              destruct hx1 as [x1 hx1]. destruct hx1 as [hx1 h2].\n              assert (h3: In x1 l \\/ In x1 s). auto. destruct h3 as [h3 | h3].\n              cut (In y (img f l)). auto. subst y. auto.\n              cut (In y (img f s)). auto. subst y. auto. }\n            { intros y h1.\n              assert (h2: In y (img f l) \\/ In y (img f s)). auto.\n              destruct h2 as [h2a | h2b].\n              { assert (hx1: exists x, In x l /\\ y = f x). auto.\n                destruct hx1 as [x1 hx1]. destruct hx1 as [hx1 h3].\n                assert (h4: In x1 (l [u] s)). auto. subst y. auto. }\n              { assert (hx1: exists x, In x s /\\ y = f x). auto.\n                destruct hx1 as [x1 hx1]. destruct hx1 as [hx1 h3].\n                assert (h4: In x1 (l [u] s)). auto. subst y. auto. } } } Qed.\n            \n\n  Lemma img_diff (l s: list A)(f: A-> B): one_one_on (l [u] s) f ->\n                                           img f (l [\\] s) = (img f l) [\\] (img f s).\n  Proof.  { intros h. apply set_equal. all: auto.\n            split.\n            { intros y h1.\n              assert (hx1: exists x, In x (l [\\] s) /\\ y = f x). auto.\n              destruct hx1 as [x1 hx1]. destruct hx1 as [hx1 h2].\n              assert (hx1l: In x1 l). eauto.\n              assert (hx1s: ~ In x1 s). eauto.\n              cut (~ In y (img f s)). cut ( In y (img f l)). auto.\n              subst y. auto. intro h3.\n              assert (hx2: exists x, In x s /\\ y = f x). auto.\n              destruct hx2 as [x2 hx2]. destruct hx2 as [hx2 h4].\n              assert (h5: x1 = x2).\n              cut(In x1 (l [u] s)). cut(In x2 (l [u] s)). cut (f x1 = f x2).\n              eauto. subst y;auto. all: auto.\n              absurd (In x2 s). subst x2. all: auto. }\n            { intros y h1.\n              assert (hyl: In y (img f l)). eauto.\n              assert (hys: ~ In y (img f s)). eauto.\n              assert (hx: exists x, In x l /\\ y = f x). auto.\n              destruct hx as [x hx]. destruct hx as [hx h2].\n              assert (hxs: ~ In x s).\n              { intro h3. absurd (In y (img f s)). auto.\n                subst y. auto. }\n              cut (In x (l [\\] s)). subst y. auto. auto. } } Qed.\n  \n  Hint Resolve img_inter1 img_inter2 img_union img_diff: core.\n  \n    \nEnd Set_maps.\n\nHint Resolve IsOrd_img NoDup_img : core.\nHint Resolve img_intro1 img_intro2 img_elim: core.\nHint Resolve img_elim2 img_elim3 img_elim4 : core.\nHint Immediate one_oneP1: core.\n\nHint Resolve NoDup_map: core.\nHint Resolve map_IsOrd: core.\n\nHint Immediate map_is_img: core.\nHint Immediate one_one_on_nil one_one_on_elim one_one_on_elim1 one_one_on_elim2 : core.\nHint Immediate one_one_on_intro one_one_on_intro1: core.\nHint Resolve one_one_onP: core.\n\nHint Resolve img_subset img_size_less img_size_same: core.\nHint Immediate one_one_img_elim img_strict_less : core.\n\nHint Immediate one_one_on_intro2 one_one_on_intro3 : core.\n\nHint Resolve img_add img_same: core.\n\nHint Resolve img_inter1 img_inter2 img_union img_diff: core.\n\n\nSection Map_composition.\n\n  Context {A B C: ordType}.\n\n \n\n  (*-------------------------  A  --f-->  B  --g-->  C    --------------------------------*)\n\n  Lemma range_of_range (l:list A)(f: A->B)(g: B->C):\n    img g (img f l) = img ( fun x => g (f x)) l.\n  Proof. { assert (H: Equal  (img g (img f l)) (img ( fun x => g (f x)) l) ).\n         { unfold Equal.\n           split.\n           { unfold Subset. intros c Hc.\n             assert (Hb: exists b, In b (img f l) /\\ c = g b). auto.\n             destruct Hb as [b Hb]. destruct Hb as [Hb Hb1].\n             assert (Ha: exists a, In a l /\\ b = f a). auto.\n             destruct Ha as [a Ha]. destruct Ha as [Ha Ha1].\n             rewrite Hb1. set (gf := (fun x : A => g (f x))).\n             rewrite Ha1. \n             assert (H: (g (f a)) = (gf a)). unfold gf. auto.\n             rewrite H. eapply img_intro2. auto. }\n           { unfold Subset. intros c Hc.\n             assert (Ha: exists a, In a l /\\ c = g (f a)). auto.\n             destruct Ha as [a Ha]. destruct Ha as [Ha1 Ha2].\n             subst c. auto. } }  auto. } Qed.\n\n  Hint Resolve range_of_range: core.\nEnd Map_composition.\n\nHint Resolve range_of_range: core.\n\n\nSection Maps_on_A.\n  Context {A: ordType}.\n\n    (*----------Identity map and its properties ---------------------------------*)\n\n  Definition id:= fun (x:A)=> x.\n\n  Lemma id_is_identity1 (l:list A) : l [=] img id l.\n  Proof.  { induction l.\n          { simpl. auto. }\n          { simpl.  split.\n           { intros x h. destruct h as [h | h].\n             subst a. unfold id. auto.\n             cut (In x (img id l)). auto.  apply IHl. auto. }\n           { unfold id. fold id. intros x h.\n             cut (x=a \\/ In x (img id l)).\n             intro h1. destruct h1 as [h1a | h1b].\n             subst x. all: auto. cut (In x l). auto. apply IHl. auto. } } }  Qed. \n  \n\n  Lemma id_is_identity (l:list A)(hl: IsOrd l): l = img id l.\n  Proof. { induction l.\n         { simpl. auto. }\n         { apply set_equal. auto. auto. \n           simpl. replace (img id l) with l.\n           split.\n           { intros x h. destruct h as [h | h].\n             subst a. unfold id. auto. unfold id. auto. }\n           { unfold id. intros x h. cut (x=a \\/ In x l).\n             intro h1. destruct h1 as [h1a | h1b].\n             subst x. all: auto. } eauto. } }  Qed.\n\n  Hint Immediate id_is_identity id_is_identity1: core.\n\n  End Maps_on_A.\n\nHint Immediate id_is_identity id_is_identity1: core.\n\n\nSection One_one_onto.\n\n  Context {A B: ordType}.\n  Variable (da:A).\n  \n\n   (*-------------invertible functions --------------------------------------- *)\n\n  Lemma one_one_onto (l: list A)(s: list B)(f: A-> B):\n    IsOrd l -> IsOrd s -> one_one_on l f -> s = img f l ->\n    exists g, (one_one_on s g /\\ l = img g s /\\ forall x, In x l -> g (f x) = x).\n  Proof. { revert s. induction l.\n         { (*-------base step: when l is nil------*)\n           simpl. intros s h1 h2 h3 h4.\n           exists (fun x:B => da).\n           subst s. split. auto. split. auto. auto. } \n         { (*------ induction step: when l is a::l ---------*)\n           intros s h1 h2 h3 h4. simpl in h4. subst s. simpl.\n           assert (h5: exists g : B -> A, one_one_on (img f l) g /\\\n                                    l = img g (img f l) /\\ (forall x : A, In x l -> g (f x) = x)).\n           { apply IHl. all: auto. eauto. eauto. }\n           destruct h5 as [g0 h5].\n           set (g:= fun y:B => match (y == f(a)) with\n                            | true => a\n                            | false => g0 y\n                            end).\n           assert (hga: g (f a) = a).\n           { unfold g. replace (f a == f a) with true. auto. auto. }\n           assert (hg_g0: forall x:A, In x l -> g (f x) = g0 (f x)).\n           { intros x h6. unfold g.\n             assert (h6a: x <> a).\n             { intro  h7. subst x; absurd (In a l); auto. }\n             assert (h6b: f x <> f a). auto.\n             { replace (f x == f a) with false. auto. auto. } }\n           assert (hgg0: img g0 (img f l) = img g (img f l)).\n           { eapply img_same. intros y h6.\n             assert (h7: exists x, In x l /\\ y = f x ). auto.\n             destruct h7 as [x h7]. destruct h7 as [h7a h7].\n             symmetry. subst y. auto. }\n           \n           exists g. split. \n           { (*-------one_one_on (add (f a) (img f l)) g -------*)\n             apply one_one_on_intro. intros x y hx hy h6.\n             unfold g in h6.\n             destruct (x == f a) eqn: hxa; destruct (y == f a) eqn: hya.\n             { move /eqP in hxa;move /eqP in hya. subst x. auto. }\n             { absurd (a = g0 y).\n               cut (In (g0 y) l). cut (NoDup (a::l)). eauto.\n               auto.\n               assert (h5a: l = img g0 (img f l)). apply h5.\n               rewrite h5a. cut (In y (img f l)). auto. move /eqP in hya. eauto.\n               auto. }\n             { absurd (a = g0 x).\n               cut (In (g0 x) l). cut (NoDup (a::l)). eauto.\n               auto.\n               assert (h5a: l = img g0 (img f l)). apply h5.\n               rewrite h5a. cut (In x (img f l)). auto. move /eqP in hxa. eauto.\n               auto. }\n             { assert (h5a: one_one_on (img f l) g0). apply h5.\n               move /eqP in hxa. move /eqP in hya.\n               cut (In x (img f l)). cut (In y (img f l)). eauto.\n               all: eauto. } }\n           split.\n           { (*------- a :: l = img g (add (f a) (img f l)) -------*)\n             destruct h5 as [h5a h5]. destruct h5 as [h5b h5].  \n             assert (h6: img g (add (f a) (img f l)) = add (g (f a)) (img g (img f l))).\n             auto. rewrite h6. rewrite <- hgg0. rewrite <- h5b. rewrite hga.\n             auto. }\n           { (*--------  forall x : A, a = x \\/ In x l -> g (f x) = x --------*)\n             intros x h6. destruct h6 as [h6 | h6]. subst x. auto.\n             replace (g (f x)) with (g0 (f x)). apply h5. auto.\n             symmetry;auto. } } } Qed.\n  \n             \n           \n  \nEnd One_one_onto.\n\nHint Resolve one_one_onto: core.\n\n\nSection PHP.\n\n  Context {A B: ordType}.\n\n  Variable R: A -> B-> Prop.\n\n  Lemma php_eq (l: list A)(s: list B):\n    IsOrd l -> IsOrd s -> (|l| = |s|) -> (forall x, In x l -> (exists y, In y s /\\ R x y))->\n                                (forall x y z, In x l -> In y l -> In z s -> R x z -> R y z -> x = y)->\n                                (forall y, In y s -> (exists x, In x l /\\ R x y )).\n  Proof. { revert s. induction l as [|a l'].\n           { intros s h1 h2 h3 h4 h5.\n             assert (h6: s = nil).\n             { symmetry in h3. destruct s.\n               simpl. auto. simpl in h3. inversion h3. }\n             subst s. simpl. tauto. }\n           { intros s h1 h2 h3 h4 h5.\n             assert (h4a: exists b : B, In b s /\\ R a b).\n             { apply h4. auto. }\n             destruct h4a as [b h4a].\n             set (s':= rmv b s).\n             assert (hs: s = add b s').\n             { subst s'. cut (In b s). auto. apply h4a. }\n             assert (h6: |l'| = |s'|).\n             { rewrite hs in h3.\n               replace (| add b s'|) with (S (|s'|)) in h3. simpl in h3.\n               omega. symmetry. cut (~ In b s'). auto. subst s'.\n               apply set_rmv_elim3. auto. }\n             \n             assert (h7: forall y : B, In y s' -> exists x : A, In x l' /\\ R x y ).\n             { apply IHl'. eauto. subst s'. eauto. auto.\n               { (*--  forall x : A, In x l' -> exists y : B, In y s' /\\ R x y --*)\n                 intros x h7.\n                 assert (h4b: exists y : B, In y s /\\ R x y).\n                 { apply h4. auto. }\n                 destruct h4b as [b' h4b]. destruct h4b as [h4b h4c].\n                 exists b'. split. Focus 2.  auto.\n                 rewrite hs in h4b.\n                 assert (h8: b' = b \\/ In b' s'). auto.\n                 destruct h8 as [h8 |h8].  \n                 { absurd ( x = a). intro h9. subst x.\n                   absurd (In a l'); auto. subst b'.\n                   eapply h5. all: auto. apply h4a. auto. apply h4a. }\n                 auto. }\n               intros x y z hx hy hz h7. eapply h5. all: auto.\n               rewrite hs. auto. }\n\n             intros y h8.\n             assert (h8a: y = b \\/ In y s').\n             { rewrite hs in h8. auto. }\n             destruct h8a as [h8a | h8b].\n             { exists a. split. auto. subst y. apply h4a. }\n             { specialize (h7 y h8b) as h7a. destruct h7a as [x h7a].\n               exists x. split. cut (In x l'). auto. all: apply h7a. } } } Qed.\n             \n                                                                          \n  End PHP.\n\n\n\n ", "meta": {"author": "Abhishek-TIFR", "repo": "wpgt", "sha": "48c612063cbfbe51d6eed41d244c044e43bf8d67", "save_path": "github-repos/coq/Abhishek-TIFR-wpgt", "path": "github-repos/coq/Abhishek-TIFR-wpgt/wpgt-48c612063cbfbe51d6eed41d244c044e43bf8d67/SetMaps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619393159451, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.6740590381778294}}
{"text": "(* ** Abstract Reduction Systems *)\n(* from Semantics Lecture at Programming Systems Lab, https://www.ps.uni-saarland.de/courses/sem-ws13/ *)\n\nRequire Export Undecidability.Shared.Libs.PSL.Base Lia.\n\nModule ARSNotations.\n  Notation \"p '<=1' q\" := (forall x, p x -> q x) (at level 70).\n  Notation \"p '=1' q\" := (forall x, p x <-> q x) (at level 70).\n  Notation \"R '<=2' S\" := (forall x y, R x y -> S x y) (at level 70).\n  Notation \"R '=2' S\"  := (forall x y, R x y <-> S x y) (at level 70).\nEnd ARSNotations.\n\nImport ARSNotations.\n\n(* Relational composition *)\n\nDefinition rcomp X Y Z (R : X -> Y -> Prop) (S : Y -> Z -> Prop) \n: X -> Z -> Prop :=\n  fun x z => exists y, R x y /\\ S y z.\n\n(* Power predicates *)\n\nRequire Import Arith.\nDefinition pow X R n : X -> X -> Prop := it (rcomp R) n eq.\n\nDefinition functional {X Y} (R: X -> Y -> Prop) := forall x y1 y2, R x y1 -> R x y2 -> y1 = y2.\nDefinition terminal {X Y} (R: X -> Y -> Prop) x:= forall y, ~ R x y.\n\nSection FixX.\n  Variable X : Type.\n  Implicit Types R S : X -> X -> Prop.\n  Implicit Types x y z : X.\n\n  Definition reflexive R := forall x, R x x.\n  Definition symmetric R := forall x y, R x y -> R y x.\n  Definition transitive R := forall x y z, R x y -> R y z -> R x z.\n\n\n\n  (* Reflexive transitive closure *)\n\n  Inductive star R : X -> X -> Prop :=\n  | starR x : star R x x\n  | starC x y z : R x y -> star R y z -> star R x z.\n\n  Definition evaluates R x y := star R x y /\\ terminal R y.\n\n  (* Making first argument a non-uniform parameter doesn't simplify the induction principle. *)\n\n  Lemma star_simpl_ind R (p : X -> Prop) y :\n    p y ->\n    (forall x x', R x x' -> star R x' y -> p x' -> p x) -> \n    forall x, star R x y -> p x.\n  Proof.\n    intros A B. induction 1; eauto.\n  Qed.\n\n  Lemma star_trans R:\n    transitive (star R).\n  Proof.\n    induction 1; eauto using star.\n  Qed.\n\n  Lemma R_star R: R <=2 star R.\n  Proof.\n    eauto using star.\n  Qed.\n\n  Instance star_PO R: PreOrder (star R).\n  Proof.\n    constructor;repeat intro;try eapply star_trans;  now eauto using star.\n  Qed.\n  \n  (* Power characterization *)\n\n  Lemma star_pow R x y :\n    star R x y <-> exists n, pow R n x y.\n  Proof.\n    split; intros A.\n    - induction A as [|x x' y B _ [n IH]].\n      + exists 0. reflexivity.\n               + exists (S n), x'. auto.\n               - destruct A as [n A].\n                 revert x A. induction n; intros x A.\n                 + destruct A. constructor.\n                 + destruct A as [x' [A B]]. econstructor; eauto.\n  Qed.\n\n  Lemma pow_star R x y n:\n    pow R n x y -> star R x y.\n  Proof.\n    intros A. erewrite star_pow. eauto.\n  Qed.\n\n  (* Equivalence closure *)\n\n  Inductive ecl R : X -> X -> Prop :=\n  | eclR x : ecl R x x\n  | eclC x y z : R x y -> ecl R y z -> ecl R x z\n  | eclS x y z : R y x -> ecl R y z -> ecl R x z.\n\n  Lemma ecl_trans R :\n    transitive (ecl R).\n  Proof.\n    induction 1; eauto using ecl.\n  Qed.\n\n  Lemma ecl_sym R :\n    symmetric (ecl R).\n  Proof.\n    induction 1; eauto using ecl, (@ecl_trans R).\n  Qed.\n\n  Lemma star_ecl R :\n    star R <=2 ecl R.\n  Proof.\n    induction 1; eauto using ecl.\n  Qed.\n\n  (* Diamond, confluence, Church-Rosser *)\n\n  Definition joinable R x y :=\n    exists z, R x z /\\ R y z.\n\n  Definition diamond R :=\n    forall x y z, R x y -> R x z -> joinable R y z.\n\n  Definition confluent R := diamond (star R).\n\n  Definition semi_confluent R :=\n    forall x y z, R x y -> star R x z -> joinable (star R) y z.\n\n  Definition church_rosser R :=\n    ecl R <=2 joinable (star R).\n\n  Goal forall R, diamond R -> semi_confluent R.\n  Proof.\n    intros R A x y z B C.\n    revert x C y B.\n    refine (star_simpl_ind _ _).\n    - intros y C. exists y. eauto using star.\n    - intros x x' C D IH y E.\n      destruct (A _ _ _ C E) as [v [F G]].\n      destruct (IH _ F) as [u [H I]].\n      assert (J:= starC G H).\n      exists u. eauto using star.\n  Qed.\n\n  Lemma diamond_to_semi_confluent R :\n    diamond R -> semi_confluent R.\n  Proof.\n    intros A x y z B C. revert y B.\n    induction C as [|x x' z D _ IH]; intros y B.\n    - exists y. eauto using star.\n             - destruct (A _ _ _ B D) as [v [E F]].\n               destruct (IH _ F) as [u [G H]].\n               exists u. eauto using star.\n  Qed.\n\n  Lemma semi_confluent_confluent R :\n    semi_confluent R <-> confluent R.\n  Proof.\n    split; intros A x y z B C.\n    - revert y B.\n      induction C as [|x x' z D _ IH]; intros y B.\n      + exists y. eauto using star.\n               + destruct (A _ _ _ D B) as [v [E F]].\n                 destruct (IH _ E) as [u [G H]].\n                 exists u. eauto using (@star_trans R).\n               - apply (A x y z); eauto using star.\n  Qed.\n\n  Lemma diamond_to_confluent R :\n    diamond R -> confluent R.\n  Proof.\n    intros A. apply semi_confluent_confluent, diamond_to_semi_confluent, A.\n  Qed.\n\n  Lemma confluent_CR R :\n    church_rosser R <-> confluent R.\n  Proof.\n    split; intros A.\n    - intros x y z B C. apply A.\n      eauto using (@ecl_trans R), star_ecl, (@ecl_sym R).\n    - intros x y B. apply semi_confluent_confluent in A.\n      induction B as [x|x x' y C B IH|x x' y C B IH].\n      + exists x. eauto using star.\n               + destruct IH as [z [D E]]. exists z. eauto using star.\n               + destruct IH as [u [D E]].\n                 destruct (A _ _ _ C D) as [z [F G]].\n                 exists z. eauto using (@star_trans R).\n  Qed.\n\n\n  (* End Semantics Library *)\n\n  \n  (* Uniform confluence and parametrized confluence *)\n\n  Definition uniform_confluent (R : X -> X -> Prop ) := forall s t1 t2, R s t1 -> R s t2 -> t1 = t2 \\/ exists u, R t1 u /\\ R t2 u.\n\n  Lemma functional_uc R :\n    functional R -> uniform_confluent R.\n  Proof.\n    intros F ? ? ? H1 H2. left. eapply F. all:eauto.\n  Qed.\n\n  Lemma pow_add R n m (s t : X) : pow R (n + m) s t <-> rcomp (pow R n) (pow R m) s t.\n  Proof.\n    revert m s t; induction n; intros m s t.\n    - simpl. split; intros. econstructor. split. unfold pow. simpl. reflexivity. eassumption.\n      destruct H as [u [H1 H2]]. unfold pow in H1. simpl in *. subst s. eassumption.\n    - simpl in *; split; intros.\n      + destruct H as [u [H1 H2]].\n        change (it (rcomp R) (n + m) eq) with (pow R (n+m)) in H2.\n        rewrite IHn in H2.\n        destruct H2 as [u' [A B]]. unfold pow in A.\n        econstructor. \n        split. econstructor. repeat split; repeat eassumption. eassumption.\n      + destruct H as [u [H1 H2]].\n        destruct H1 as [u' [A B]].\n        econstructor.  split. eassumption. change (it (rcomp R) (n + m) eq) with (pow R (n + m)).\n        rewrite IHn. econstructor. split; eassumption.\n  Qed.\n  \n  Lemma rcomp_eq (R S R' S' : X -> X -> Prop) (s t : X) : (R =2 R') -> (S =2 S') -> (rcomp R S s t <-> rcomp R' S' s t).\n  Proof.\n    intros A B.\n    split; intros H; destruct H as [u [H1 H2]];\n    eapply A in H1; eapply B in H2;\n    econstructor; split; eassumption.\n  Qed.\n  \n  Lemma eq_ref : forall (R : X -> X -> Prop), R =2 R.\n  Proof.\n    split; tauto.\n  Qed.\n  \n  Lemma rcomp_1 (R : X -> X -> Prop): R =2 pow R 1.\n  Proof.\n    intros s t; split;unfold pow in *; simpl in *; intros H.\n    - econstructor. split; eauto.\n    - destruct H as [u [H1 H2]]; subst u; eassumption.\n  Qed.\n  \n  Lemma parametrized_semi_confluence (R : X -> X -> Prop) (m : nat) (s t1 t2 : X) :\n    uniform_confluent R ->\n    pow R m s t1 ->\n    R s t2 ->\n    exists k l u,\n      k <= 1 /\\ l <= m /\\ pow R k t1 u /\\ pow R l t2 u /\\ m + k = S l.\n  Proof.\n    intros unifConfR; revert s t1 t2; induction m; intros s t1 t2 s_to_t1 s_to_t2.\n    - unfold pow in s_to_t1. simpl in *. subst s.\n      exists 1, 0, t2.\n      repeat split; try lia.\n      econstructor. split; try eassumption; econstructor.\n    - destruct s_to_t1 as [v [s_to_v v_to_t1]].\n      destruct (unifConfR _ _ _ s_to_v s_to_t2) as [H | [u [v_to_u t2_to_u]]].\n      + subst v. eexists 0, m, t1; repeat split; try lia; eassumption.\n      + destruct (IHm _ _ _ v_to_t1 v_to_u) as [k [l [u' H]]].\n        eexists k, (S l), u'; repeat split; try lia; try tauto.\n        econstructor. split. eassumption. tauto.\n  Qed.\n  \n  Lemma rcomp_comm R m (s t : X) : rcomp R (it (rcomp R) m eq) s t <-> rcomp (it (rcomp R) m eq) R s t.\n  Proof.\n    split; intros H;\n    [rewrite (rcomp_eq s t (rcomp_1 R) (eq_ref _)) in H;\n      rewrite (rcomp_eq s t (eq_ref _) (rcomp_1 R)) |\n     rewrite (rcomp_eq s t (eq_ref _) (rcomp_1 R)) in H;\n       rewrite (rcomp_eq s t (rcomp_1 R) (eq_ref _))];\n    change ((it (rcomp R) m eq)) with (pow R m) in *;\n    try rewrite <- pow_add in *;\n    rewrite plus_comm; eassumption.\n  Qed.\n  \n  Lemma parametrized_confluence (R : X -> X -> Prop) (m n : nat) (s t1 t2 : X) : \n    uniform_confluent R ->\n    pow R m s t1 -> \n    pow R n s t2 -> \n    exists k l u,\n      k <= n /\\ l <= m /\\ pow R k t1 u /\\ pow R l t2 u /\\ m + k = n + l.\n  Proof.\n    revert n s t1 t2; induction m; intros n s t1 t2 unifConR s_to_t1 s_to_t2.\n    - unfold pow in s_to_t1. simpl in s_to_t1. subst s.\n      exists n, 0, t2. repeat split; try now lia. eassumption.\n    - unfold pow in s_to_t1. simpl in *.\n      destruct s_to_t1 as [v [s_to_v v_to_t1]].\n      destruct (parametrized_semi_confluence unifConR s_to_t2 s_to_v) as\n          [k [l [u [k_lt_1 [l_lt_n [t2_to_u [v_to_u H]]]]]]].\n      destruct (IHm _ _ _ _ unifConR v_to_t1 v_to_u) as\n          [l'[k'[u'[l'_lt_l [k'_lt_m [t1_to_u' [u_to_u' H2]]]]]]].\n      exists l', (k + k'), u'.\n      repeat split; try lia. eassumption.\n      rewrite pow_add.\n      econstructor; split; eassumption.\n  Qed.\n\n  Lemma uniform_confluent_noloop R x y:\n    uniform_confluent R ->\n    star R x y -> (forall y', ~ R y y') ->\n    ~exists z k, star R x z /\\ pow R (S k) z z.\n  Proof.\n    intros UC (k0&R0)%star_pow Term (z&k1&R1&RL).\n    induction R1 in k0,RL,R0|-*.\n    -edestruct parametrized_confluence with (m:=k0) (n:=S k1 + k0) as (i0&i1&?&?&?&?&?&?).\n     1,2:eassumption.\n     now eapply pow_add;eexists;split;eassumption.\n     destruct i0. destruct i1.\n     +now lia.\n     +destruct H2 as (?&?&_). edestruct Term. eauto.\n     +destruct H1 as (?&?&_). edestruct Term. eauto.\n    -edestruct parametrized_semi_confluence with (R:=R) (2:= R0) as (i0&?&?&?&?&?&?&?). 1,2:eassumption.\n     destruct i0. 2:{ destruct H2 as (?&?&_). edestruct Term. eauto. }\n     cbn in H2;inv H2.\n     eapply IHR1. all:eauto.\n  Qed.\n  \n Lemma uc_terminal R x y z n:\n    uniform_confluent R ->\n    R x y ->\n    pow R n x z ->\n    terminal R z ->\n    exists n' , n = S n' /\\ pow R n' y z.\n  Proof.\n    intros ? ? ? ter. edestruct parametrized_semi_confluence as (k&?&?&?&?&R'&?&?). 1-3:now eauto.\n    destruct k as [|].\n    -inv R'. rewrite <- plus_n_O in *. eauto.\n    -edestruct R' as (?&?&?). edestruct ter. eauto.\n  Qed.  \n\n\n  (* classical *)\n  Definition classical R x := terminal R x \\/ exists y, R x y.\n\n  (* Strong normalisation *)\n  \n  Inductive SN R : X -> Prop :=\n  | SNC x : (forall y, R x y -> SN R y) -> SN R x.\n\n  Fact SN_unfold R x :\n    SN R x <-> forall y, R x y -> SN R y.\n  Proof.\n    split.\n    - destruct 1 as [x H]. exact H.\n    - intros H. constructor. exact H.\n  Qed.\n  \nEnd FixX.\n\nExisting Instance star_PO.\n\n(* A notion of a reduction sequence which keeps track of the largest occuring state *)\n\nInductive redWithMaxSize {X} (size:X -> nat) (step : X -> X -> Prop): nat -> X -> X -> Prop:=\n  redWithMaxSizeR m s: m = size s -> redWithMaxSize size step m s s \n| redWithMaxSizeC s s' t m m': step s s' -> redWithMaxSize size step m' s' t -> m = max (size s) m' -> redWithMaxSize size step m s t.\n\nLemma redWithMaxSize_ge X size step (s t:X) m:\n  redWithMaxSize size step m s t -> size s<= m /\\ size t <= m.\nProof.\n  induction 1;subst;firstorder (repeat eapply Nat.max_case_strong; try lia).\nQed.\n\nLemma redWithMaxSize_trans X size step (s t u:X) m1 m2 m3:\n redWithMaxSize size step m1 s t -> redWithMaxSize size step m2 t u -> max m1 m2 = m3 -> redWithMaxSize size step m3 s u.\nProof.\n  induction 1 in m2,u,m3|-*;intros.\n  -specialize (redWithMaxSize_ge H0) as [].\n   revert H1;\n     repeat eapply Nat.max_case_strong; subst m;intros. all:replace m3 with m2 by lia. all:eauto.\n  - specialize (redWithMaxSize_ge H0) as [].\n    specialize (redWithMaxSize_ge H2) as [].\n    eassert (H1':=Max.le_max_l _ _);rewrite H3 in H1'.\n    eassert (H2':=Max.le_max_r _ _);rewrite H3 in H2'.\n    econstructor. eassumption.\n     \n    eapply IHredWithMaxSize. eassumption. reflexivity.\n    subst m;revert H3;repeat eapply Nat.max_case_strong;intros;try lia. \nQed.\n\nLemma redWithMaxSize_star {X} f (step : X -> X -> Prop) n x y:\n  redWithMaxSize f step n x y -> star step x y.\nProof.\n  induction 1;eauto using star.\nQed.\n\nLemma terminal_noRed {X} (R:X->X->Prop) x y :\n  terminal R x -> star R x y -> x = y.\nProof.\n  intros ? R'. inv R'. easy. edestruct H. eassumption.\nQed.\n\nLemma unique_normal_forms {X} (R:X->X->Prop) x y:\n  confluent R -> ecl R x y -> terminal R x -> terminal R y -> x = y.\nProof.\n  intros CR%confluent_CR E T1 T2.\n  specialize (CR _ _ E) as (z&R1&R2).\n  apply terminal_noRed in R1. apply terminal_noRed in R2. 2-3:eassumption. congruence.\nQed.\n\nInstance ecl_Equivalence {X} (R:X->X->Prop) : Equivalence (ecl R).\nProof.\n  split.\n  -constructor.\n  -apply ecl_sym.\n  -apply ecl_trans.\nQed.\n\nInstance star_ecl_subrel {X} (R:X->X->Prop) : subrelation (star R) (ecl R).\nProof.\n  intro. eapply star_ecl.\nQed.\n\nInstance pow_ecl_subrel {X} (R:X->X->Prop) n : subrelation (pow R n) (ecl R).\nProof.\n  intros ? ? H%pow_star. now rewrite H.\nQed.\n\nLemma uniform_confluence_parameterized_terminal (X : Type) (R : X -> X -> Prop) (m n : nat) (s t1 t2 : X):\n  uniform_confluent R -> terminal R t1 ->\n  pow R m s t1 -> pow R n s t2 -> exists n', pow R n' t2 t1 /\\ m = n + n'.\nProof.\n  intros H1 H2 H3 H4.\n  specialize (parametrized_confluence H1 H3 H4) as (n0&n'&?&?&?&R'&?&?).\n  destruct n0.\n  -inv R'. exists n'. intuition.\n  -exfalso. destruct R' as (?&?&?). eapply H2. eauto.\nQed.\n\nLemma uniform_confluence_parameterized_both_terminal (X : Type) (R : X -> X -> Prop) (n1 n2 : nat) (s t1 t2 : X):\n  uniform_confluent R -> terminal R t1 -> terminal R t2 ->\n  pow R n1 s t1 -> pow R n2 s t2 -> n1=n2 /\\ t1 = t2.\nProof.\n  intros H1 H2 H2' H3 H4.\n  specialize (parametrized_confluence H1 H3 H4) as (n0&n'&?&?&?&R'&R''&?).\n  destruct n0. destruct n'.\n  -inv R'. inv H5. split;first [lia | easy].\n  -exfalso. destruct R'' as (?&?&?). eapply H2'. eauto.\n  -exfalso. destruct R' as (?&?&?). eapply H2. eauto.\nQed.\n\nLemma uniform_confluent_confluent (X : Type) (R : X -> X -> Prop):\n  uniform_confluent R -> confluent R.\nProof.\n  intros H x y y' Hy Hy'. apply ARS.star_pow in Hy as (?&Hy). apply ARS.star_pow in Hy' as (?&Hy').\n  edestruct parametrized_confluence as (?&?&z&?&?&?&?&?).\n  eassumption. exact Hy. exact Hy'. exists z. split;eapply pow_star. all:eauto.\nQed.\n\nDefinition computesRel {X Y} (f : X -> option Y) (R:X -> Y -> Prop) :=\n  forall x, match f x with\n         Some y => R x y\n       | None => terminal R x\n       end.\n\nDefinition evaluatesIn (X : Type) (R : X -> X -> Prop) n (x y : X) := pow R n x y /\\ terminal R y.\n\nLemma evalevaluates_evaluatesIn X (step:X->X->Prop) s t:\n  evaluates step s t -> exists k, evaluatesIn step k s t.\nProof.\n  intros [(R&?)%star_pow ?]. unfold evaluatesIn. eauto.\nQed.\n", "meta": {"author": "uds-psl", "repo": "time-invariance-thesis-for-L", "sha": "41f4eb1f788cc4f096d9c7c286c9ca907588859f", "save_path": "github-repos/coq/uds-psl-time-invariance-thesis-for-L", "path": "github-repos/coq/uds-psl-time-invariance-thesis-for-L/time-invariance-thesis-for-L-41f4eb1f788cc4f096d9c7c286c9ca907588859f/theories/L/Prelim/ARS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.6740430709209984}}
{"text": "(* week-02_exercises.v *)\n(* FPP 2020 - YSC3236 2020-2011, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 23 Aug 2020 *)\n\n(* ********** *)\n\n(* Your name: Koo Zhengqun\n   Your e-mail address: zhengqun.koo@u.nus.edu\n   Your student number: A0164207L\n *)\n\n(* Your name: Bobbie Soedirgo\n   Your e-mail address: sram-b@comp.nus.edu.sg\n   Your student number: A0181001A\n *)\n\n(* Your name: Kuan Wei Heng\n   Your e-mail address: kuanwh@u.nus.edu\n   Your student number: A0121712X\n *)\n\n(**\n %\\title{Functional Programming in Coq}%\n %\\author{Bobbie Soedirgo, Koo Zhengqun, Kuan Wei Heng}%\n %\\date{\\today}%\n %\\maketitle%\n %\\tableofcontents%\n %\\newpage%\n *)\n\n(** * Introduction\n\nThis assignment first introduces polymorphic datatypes, terms of those polymorphic datatypes, and polymorphic functions over those polymorphic datatypes.\n\nThen, this assignment introduces polymorphic lambda types, and terms of those polymorphic lambda types.\n\nThen, this assignment introduces polymorphic propositions, and proofs of those polymorphic propositions.\n\nThe sheer number of types and proofs in this assignment is significant, since they help students internalize Coq's and Gallina's syntax.\n\n%\\newpage%\n *)\n\n(* begin hide *)\nRequire Import Arith Bool.\n(* end hide *)\n\n(* ********** *)\n\n(** * Exercise 1 *)\n\n(* definitions given *)\n\n(* begin hide *)\nInductive polymorphic_binary_tree (V : Type) : Type :=\n| PLeaf : V -> polymorphic_binary_tree V\n| PNode : polymorphic_binary_tree V -> polymorphic_binary_tree V -> polymorphic_binary_tree V.\n\nFixpoint eqb_polymorphic_binary_tree (V : Type) (eqb_V : V -> V -> bool) (t1 t2 : polymorphic_binary_tree V) : bool :=\n  match t1 with\n  | PLeaf _ v1 =>\n    match t2 with\n    | PLeaf _ v2 =>\n      eqb_V v1 v2\n    | PNode _ t11 t12 =>\n      false\n    end\n  | PNode _ t11 t12 =>\n    match t2 with\n    | PLeaf _ v2 =>\n      false\n    | PNode _ t21 t22 =>\n      eqb_polymorphic_binary_tree V eqb_V t11 t21\n      &&\n      eqb_polymorphic_binary_tree V eqb_V t21 t22\n    end\n  end.\n\nDefinition eqb_binary_tree_of_nats (t1 t2 : polymorphic_binary_tree nat) : bool :=\n  eqb_polymorphic_binary_tree nat beq_nat t1 t2.\n(* end hide *)\n\n(** ** a\nExhibit a Gallina expression of type [polymorphic_binary_tree (nat * bool)].\n\nAnswer:\n\n *)\n\nDefinition tree_nat_bool : polymorphic_binary_tree (nat * bool) :=\n  PLeaf (nat * bool) (0, true).\n\n(* begin hide *)\nCheck (tree_nat_bool : polymorphic_binary_tree (nat * bool)).\n(* end hide *)\n\n(** ** b\nExhibit a Gallina expression of type [polymorphic_binary_tree (polymorphic_binary_tree nat)].\n\nAnswer:\n\n *)\n\nDefinition tree_tree_nat : polymorphic_binary_tree (polymorphic_binary_tree nat) :=\n  PLeaf _ (PLeaf _ 0).\n\n(* begin hide *)\nCheck (tree_tree_nat : polymorphic_binary_tree (polymorphic_binary_tree nat)).\n(* end hide *)\n\n(* ********** *)\n\n(** * Exercise 2 *)\n\n(** ** a\nTo implement an equality function on binary trees of pairs of nats and bools, we can specialize the polymorphic function\n[eqb_polymorphic_binary_tree]. This requires us to produce a witness function to test the equality of pairs of nats and bools.\nInstead of constructing it directly, we will first write a more general form to test the equality of pairs\nparameterized over the types of the car and cdr, then specialize it for [nat * bool] with the witnesses [beq_a] and [beq_b].\n *)\n\nDefinition beq_pair (A B : Type) (beq_a : A -> A -> bool) (beq_b : B -> B -> bool) (p1 p2 : A * B) : bool :=\n  let (n1, b1) := p1 in\n  let (n2, b2) := p2 in\n  beq_a n1 n2 && beq_b b1 b2.\n\nDefinition eqb_binary_tree_of_nats_and_bools (t1 t2 : polymorphic_binary_tree (nat * bool)) : bool :=\n  eqb_polymorphic_binary_tree (nat * bool) (beq_pair nat bool beq_nat eqb) t1 t2.\n\n(** ** b\nFor binary trees of binary trees of natural numbers, no new definition is needed to construct the witness function.\n *)\n\nDefinition eqb_binary_tree_of_binary_trees_of_nats (t1 t2 : polymorphic_binary_tree (polymorphic_binary_tree nat)) : bool :=\n  eqb_polymorphic_binary_tree (polymorphic_binary_tree nat) eqb_binary_tree_of_nats t1 t2.\n\n(* ********** *)\n\n(** * Exercises about types\nAs in Week 04 of Intro to CS, the accompanying file contains 14 types in need of a program that has this type. Conjure up these programs (aiming for the simplest ones you can think of).\n\nHint: all these programs only need to have the shape <<(fun ... => e)>>, where:\n<<\ne ::= tt | x | fun x => e | e e | (e, e) | match e with p => e\np ::= x | (p, p)\n>>\n\nBecause types are never directly used to construct the program, for each type, we <<intro>> it but do not bind it to an identifier (we bind it to [_], which means we ignore it).\n\nThese exercises about types have a great similarity to the exercises about propositions. In fact, each of these numbered exercises (from [a] to [n]) correspond to the corresponding numbered exercises about propositions (from [a] to [n]). This allows us to apply insights from these exercises to the exercises about propositions, and vice versa. So let us start with the insights from these exercises.\n\nAnswer:\n\n *)\n\nDefinition ta : forall A : Type, A -> A * A :=\n  fun _ a => (a, a).\n\nDefinition tb : forall A B : Type, A -> B -> A * B :=\n  fun _ _ a b => (a, b).\n\nDefinition tc : forall A B : Type, A -> B -> B * A :=\n  fun _ _ a b => (b, a).\n\nCheck (tt : unit).\n\nDefinition td : forall (A : Type), (unit -> A) -> A :=\n  fun _ f => f tt.\n\nDefinition te : forall A B : Type, (A -> B) -> A -> B :=\n  fun _ _ f a => f a.\n\nDefinition tf : forall A B : Type, A -> (A -> B) -> B :=\n  fun _ _ a f => f a.\n\n(**\nWe note that [tg] is [fun _ _ _ f a b => f a b]. From lambda calculus, we know that this is eta-equivalent to [fun _ _ _ f => f]. So, we know that [pg] can be proven by doing 4 <<intro>>s, then doing <<exact>> on the 4th <<intro>>ed term.\n\n*)\nDefinition tg : forall A B C : Type, (A -> B -> C) -> A -> B -> C :=\n  fun _ _ _ f a b => f a b.\n\n(**\nKeeping in mind that [->] associates to the right, we note when compared to [tg : (A -> B -> C) -> (A -> B -> C)], that the exercise [th : (A -> B -> C) -> (B -> A -> C)] is significant, because [th] tells us that despite what the type [(B -> A -> C)] says, we do not need to apply [B] first followed by [A]. This is especially evident in the way the terms are constructed: both [tg] and [th] construct the term as [f a b]. We shall see a more fundamental reason in the exercises about propositoins.\n\n*)\n\nDefinition th : forall A B C : Type, (A -> B -> C) -> B -> A -> C :=\n  fun _ _ _ f b a => f a b.\n\nDefinition ti : forall A B C D : Type, (A -> C) -> (B -> D) -> A -> B -> C * D :=\n  fun _ _ _ _ f g a b => (f a, g b).\n\nDefinition tj : forall A B C : Type, (A -> B) -> (B -> C) -> A -> C :=\n  fun _ _ _ f g a => g (f a).\n\nDefinition tk : forall A B : Type, A * B -> B * A :=\n  fun _ _ ab => match ab with (a, b) => (b, a) end.\n\nDefinition tl : forall A B C : Type, (A * B -> C) -> A -> B -> C :=\n  fun _ _ _ f a b => f (a, b).\n\nDefinition tm : forall A B C : Type, (A -> B -> C) -> A * B -> C :=\n  fun _ _ _ f ab => match ab with (a, b) => f a b end.\n\n(* NOTE: Is (A * B) * C equivalent to A * B * C? *)\nDefinition tn : forall A B C : Type, (A * (B * C)) -> (A * B) * C :=\n  fun _ _ _ a_bc => match a_bc with (a, (b, c)) => ((a, b), c) end.\n\n(* ********** *)\n\n(** * Exercises about propositions\nThe accompanying file contains 14 propositions in need of a proof. Conjure up these proofs (aiming for the simplest ones you can think of).\n\nHint: all these proofs only need to use the following tactics:\n\n<<\nintro, intros\ndestruct\nsplit\nexact\napply\n>>\n\nHere, we write insights from these exercises that can be applied to the exercises about types.\n\nAnswer:\n\n *)\n\nProposition pa :\n  forall A : Prop,\n    A -> A * A.\nProof.\n  intros A H_A.\n  split.\n  - exact H_A.\n  - exact H_A.\nQed.\n\nProposition pb :\n  forall A B : Prop,\n    A -> B -> A * B.\nProof.\n  intros A B H_A H_B.\n  split.\n  - exact H_A.\n  - exact H_B.\nQed.\n\nProposition pc :\n  forall A B : Prop,\n    A -> B -> B * A.\nProof.\n  intros A B H_A H_B.\n  split.\n  - exact H_B.\n  - exact H_A.\nQed.\n\nCheck tt.\n\nProposition pd :\n  forall (A : Prop),\n    (unit -> A) -> A.\nProof.\n  intros A H_f.\n  exact (H_f tt).\nQed.\n\nProposition pe :\n  forall A B : Prop,\n    (A -> B) -> A -> B.\nProof.\n  intros A B H_f H_A.\n  exact (H_f H_A).\nQed.\n\nProposition pf :\n  forall A B : Prop,\n    A -> (A -> B) -> B.\nProof.\n  intros A B H_A H_f.\n  exact (H_f H_A).\nQed.\n\n(**\nIn proving [pg], we apply the insight of eta-conversion to get a proof that uses less tactics (the <<intros>> tactic is counted as many <<intro>>s).\n\nWe note that it is possible to prove both [pg] and [ph] by using the <<intro>> tactic as many times as possible. Then, we note that the hypotheses of [pg] are exactly the same as the hypotheses of [ph] (up to bounded names). This strongly suggests that the two propositions are equivalent. Indeed, we notice that each use of the <<intro>> tactic, to introduce a term as a hypothesis, eliminates the left side of only one implication. This corresponds to partial application of the type function of some arity, whereby the aforementioned introduced term is fixed, producing a type function with smaller arity.\n\n *)\n\nProposition pg :\n  forall A B C : Prop,\n    (A -> B -> C) -> A -> B -> C.\nProof.\n  intros A B C H_f H_A H_B.\n  exact (H_f H_A H_B).\n\n  Restart.\n\n  intros A B C H_f.\n  exact H_f.\nQed.\n\nProposition ph :\n  forall A B C : Prop,\n    (A -> B -> C) -> B -> A -> C.\nProof.\n  intros A B C H_f H_B H_A.\n  exact (H_f H_A H_B).\nQed.\n\nProposition pi :\n  forall A B C D : Prop,\n    (A -> C) -> (B -> D) -> A -> B -> C /\\ D.\nProof.\n  intros A B C D H_f H_g H_A H_B.\n  split.\n  - exact (H_f H_A).\n  - exact (H_g H_B).\nQed.\n\nProposition pj :\n  forall A B C : Prop,\n    (A -> B) -> (B -> C) -> A -> C.\nProof.\n  intros A B C H_f H_g H_A.\n  exact (H_g (H_f H_A)).\nQed.\n\nProposition pk :\n  forall A B : Prop,\n    A /\\ B -> B /\\ A.\nProof.\n  intros A B.\n  intros [H_A H_B].\n  split.\n  - exact H_B.\n  - exact H_A.\nQed.\n\nProposition pl :\n  forall A B C : Prop,\n    (A /\\ B -> C) -> A -> B -> C.\nProof.\n  intros A B C.\n  intros H_A_and_B_imp_C H_A H_B.\n  exact (H_A_and_B_imp_C (conj H_A H_B)).\nQed.\n\nProposition pm :\n  forall A B C : Prop,\n    (A -> B -> C) -> A /\\ B -> C.\nProof.\n  intros A B C.\n  intros H_A_imp_B_imp_C [H_A H_B].\n  apply H_A_imp_B_imp_C.\n  exact H_A.\n  exact H_B.\nQed.\n\nProposition pn :\n  forall A B C : Prop,\n    (A /\\ (B /\\ C)) -> (A /\\ B) /\\ C.\nProof.\n  intros A B C.\n  intros [H_A [H_B H_C]].\n  exact (conj (conj H_A H_B) H_C).\nQed.\n\n(*** week-01_fixpoints.ml *)\n(* FPP 2020 - YSC3236 2020-2011, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 20 Aug 2020, with an attuned definition of infinite_self_composition *)\n(* was: *)\n(* Version of 19 Aug 2020 *)\n(* was: *)\n(* Version of 18 Aug 2020 *)\n\n(* ********** *)\n\n(** <<\nlet rec infinite_self_composition s =\n  fun v -> s (infinite_self_composition s) v;;\n>> *)\n\n(* ********** *)\n\n(** * Exercise 8 of <<week-01_fixpoints.ml>> *)\n\n(** <<\nlet test_fib candidate =\n  (candidate 0 = 0) &&\n  (candidate 1 = 1) &&\n  (candidate 2 = 1) &&\n  (candidate 3 = 2) &&\n  (candidate 4 = 3) &&\n  (candidate 5 = 5) &&\n  (let n = Random.int 20\n   in candidate n = (candidate (n - 1)) + (candidate (n - 2)))\n  (* etc. *);;\n>>\n\n<<\nlet test_rev candidate =\n  (candidate [] = []) &&\n  (candidate [0] = [0]) &&\n  (candidate [0; 1] = [1; 0]) &&\n  (let vs = [0; 1; 2; 3; 4; 5]\n   in candidate (candidate vs) = vs)\n  (* etc. *);;\n>>\n\n<<\nlet test_concat candidate =\n  (candidate [] [] = []) &&\n  (candidate [0] [] = [0]) &&\n  (candidate [] [0] = [0]) &&\n  (candidate [0; 1; 2] [3; 4; 5] = [0; 1; 2; 3; 4; 5])\n  (* etc. *);;\n>>\n\n<<\n(* Fibonacci *)\nlet foo n =\n  assert (n >= 0);\n  infinite_self_composition (fun foo n ->\n    if n = 0 then 0 else\n    if n = 1 then 1 else\n    foo (n - 1) + foo (n - 2)\n    ) n;;\n\nlet () = assert (test_fib foo);;\n>>\n\n<<\n(* Reverse list *)\nlet bar vs =\n  infinite_self_composition (fun bar vs ->\n    match vs with\n    | [] -> []\n    | v :: vs' -> bar vs' @ [v]\n    ) vs;;\n\nlet () = assert (test_rev bar);;\n>>\n\n<<\n(* Reverse list, but using cons (\"::\") instead of\nthe list concatenation operator (\"@\") *)\nlet baz vs =\n  infinite_self_composition (fun baz vs a ->\n    match vs with\n    | [] -> a\n    | v :: vs' -> baz vs' (v :: a)\n    ) vs [];;\n\nlet () = assert (test_rev baz);;\n>>\n\n<<\n(* List concatenation *)\nlet yip vs ws =\n  infinite_self_composition (fun yip vs ws ->\n    match vs with\n    | [] -> ws\n    | v :: vs' -> v :: yip vs' ws\n    ) vs ws;;\n\nlet () = assert (test_concat yip);;\n>>\n\n<<\n(* Bonus: Reverse list, but with yip *)\nlet quux vs =\n  infinite_self_composition (fun quux vs ->\n    match vs with\n    | [] -> []\n    | v :: vs' -> yip (quux vs') [v]\n    ) vs;;\n\nlet () = assert (test_rev quux);;\n>> *)\n\n(* ********** *)\n\n(* end of week-01_fixpoints.ml *)\n\n(** * Exercise 12\nProve that disjunction distributes over conjunction on the left and right.\n\n *)\n\n(** ** Distributes on the left: Given incomplete proof\nProve that disjunction distributes over conjunction on the left.\n\n *)\n\nProposition disjunction_distributes_over_conjunction_on_the_left :\n  forall A B C : Prop,\n    A \\/ (B /\\ C) <-> (A \\/ B) /\\ (A \\/ C).\nProof.\n  intros A B C.\n  split.\n\n  - intros [H_A | [H_B H_C]].\n\n    + split.\n\n      * left.\n        exact H_A.\n\n      * left.\n        exact H_A.\n\n    + split.\n\n      * right.\n        exact H_B.\n\n      * right.\n        exact H_C.\n\n(** ** Distributes on the left: Completed proof\nProve that disjunction distributes over conjunction on the left.\n\n *)\n\n  - intros [[H_A | H_B] [H_A' | H_C]].\n    + left. exact H_A.\n    + left. exact H_A.\n    + left. exact H_A'.\n    + right.\n      exact (conj H_B H_C).\nQed.\n\n(** ** Distributes on the right\nProve that disjunction distributes over conjunction on the right.\n\n *)\n\nProposition disjunction_distributes_over_conjunction_on_the_right :\n  forall A B C : Prop,\n    (B /\\ C) \\/ A <-> (B \\/ A) /\\ (C \\/ A).\nProof.\n  intros A B C.\n  split.\n  - intros [[H_B H_C] | H_A].\n    + split.\n      * left. exact H_B.\n      * left. exact H_C.\n    + split.\n      * right. exact H_A.\n      * right. exact H_A.\n  - intros [[H_B | H_A] [H_C | H_A']].\n    + left. exact (conj H_B H_C).\n    + right. exact H_A'.\n    + right. exact H_A.\n    + right. exact H_A.\nQed.\n\n(** * Exercise 13\nProve that conjunction distributes over disjunction on the left and on the right.\n\n *)\n\nProposition conjunction_distributes_over_disjunction_on_the_left :\n  forall A B C : Prop,\n    A /\\ (B \\/ C) <-> (A /\\ B) \\/ (A /\\ C).\nProof.\n  intros A B C.\n  split.\n  - intros [H_A [H_B | H_C]].\n    + left. exact (conj H_A H_B).\n    + right. exact (conj H_A H_C).\n  - intros [[H_A H_B] | [H_A H_C]].\n    + split.\n      * exact H_A.\n      * left. exact H_B.\n    + split.\n      * exact H_A.\n      * right. exact H_C.\nQed.\n\nProposition conjunction_distributes_over_disjunction_on_the_right :\n  forall A B C : Prop,\n    (A \\/ B) /\\ C <-> (A /\\ C) \\/ (B /\\ C).\nProof.\n  intros A B C.\n  split.\n  - intros [[H_A | H_B] H_C].\n    + left. exact (conj H_A H_C).\n    + right. exact (conj H_B H_C).\n  - intros [[H_A H_C] | [H_B H_C']].\n    + split.\n      * left. exact H_A.\n      * exact H_C.\n    + split.\n      * right. exact H_B.\n      * exact H_C'.\nQed.\n\n(* ********** *)\n\n(** * Conclusion\nBy the Curry-Howard correspondence, proofs are terms, and propositions are types.\n\nPolymorphism is a significant constraint in this assignment. Because of polymorphism, a term cannot know which of the possible types it is building up to, as in %\\href{http://ecee.colorado.edu/ecen5533/fall11/reading/free.pdf}{Wadler}%, which says:\n\"Say that [r] is a function of type $r : \\forall X. X^* \\rightarrow X^*$. Here [X] is a type variable, and $X^*$ is the type “list of [X]”. [r] must work on lists of [X] for any type [X]. Since [r] is provided with no operations on values of type [X], all it can do is rearrange such lists, independent of the values contained in them.\"\n\nConcretely, there is only one solution to exercise [tk]. But if one considers integer-specific types, then alternative solutions are allowed, such as this:\n\n *)\n\n(* begin hide *)\nRequire Import BinInt.\nInclude BinIntDef.Z.\n(* end hide *)\n\nDefinition tk_int (p : Z * Z) : (Z * Z) :=\n  match p with (a, b) =>\n               let a := Z.sub b a in\n               let b := Z.sub b a in\n               let a := Z.add a b in\n               (a, b)\n  end.\n\n(**\nWe can write unit tests after defining equality on pairs of integers.\n\n *)\n\nDefinition beq_int_pair (p q : Z * Z) : bool :=\n  match p with (a, b) =>\n               match q with (c, d) =>\n                            eqb a c && eqb b d\n               end\n  end.\n\nNotation \"A =zp= B\" :=\n  (beq_int_pair A B) (at level 70, right associativity).\n\nDefinition test_tk (candidate : (Z * Z) -> (Z * Z)) : bool :=\n  ((candidate (Z0,succ Z0)) =zp= (succ Z0,Z0)) &&\n  ((candidate (succ Z0,Z0)) =zp= (Z0,succ Z0)) &&\n  ((candidate (Z0,succ (succ Z0))) =zp= (succ (succ Z0),Z0)) &&\n  ((candidate (succ (succ Z0),Z0)) =zp= (Z0,succ (succ Z0))).\n\n(**\nBoth the polymorphic [tk] and non-polymorphic [tk_int] pass the unit tests.\n\n *)\n\nCompute test_tk (tk Z Z).\nCompute test_tk tk_int.\n\n(**\nAs we have seen, only a small amount of term-building operators can be used to manipulate terms that belong to a polymorphic type, because polymorphic types contain less information. For example, we cannot construct [tk] with [tk_int], because the polymorphic type may not be of type int. We do not know which type the polymorphic type is.\n\nCorrespondingly, only a small amount of Coq tactics can be used to construct a proof that has only polymorphic types in its assumption.\n\n *)\n\n(* end of week-02_exercises.v *)\n", "meta": {"author": "soedirgo", "repo": "fpp", "sha": "5a43df151c5c8bc3f49d449ffd6f3eac67a16eab", "save_path": "github-repos/coq/soedirgo-fpp", "path": "github-repos/coq/soedirgo-fpp/fpp-5a43df151c5c8bc3f49d449ffd6f3eac67a16eab/w02/week-02_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.6740430660909948}}
{"text": "From Equations Require Import Equations.\nFrom Coq Require Import ssreflect ssrbool ssrfun.\nFrom mathcomp Require Import ssrnat eqtype seq path order bigop prime.\nFrom favssr Require Import prelude.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport Order.POrderTheory.\nImport Order.TotalTheory.\nOpen Scope order_scope.\n\nSection InsertionSort.\nContext {disp : unit} {T : orderType disp}.\nImplicit Types (xs ys : seq T).\n\n(* Definition *)\n\nFixpoint insort x xs :=\n  if xs is y :: xs' then\n    if x <= y then x :: y :: xs' else y :: insort x xs'\n    else [:: x].\n\nFixpoint isort xs :=\n  if xs is x :: xs' then insort x (isort xs') else [::].\n\n(* Functional Correctness *)\n\nLemma perm_insort x xs : perm_eq (insort x xs) (x :: xs).\nProof.\nelim: xs=>//= y xs IH; case: (_ <= _)=>//.\nrewrite -(perm_cons y) in IH.\napply: perm_trans; first by exact: IH.\nby apply/permP=>/=?; rewrite addnCA.\nQed.\n\nLemma perm_isort xs : perm_eq (isort xs) xs.\nProof.\nelim: xs=>//= x xs IH.\napply: perm_trans; first by apply: perm_insort.\nby rewrite perm_cons.\nQed.\n\nLemma sorted_insort a xs : sorted <=%O (insort a xs) = sorted <=%O xs.\nProof.\nelim: xs=>//= x xs IH.\ncase H: (_ <= _)=>/=; first by rewrite H.\nrewrite !le_path_sortedE (perm_all _ (perm_insort _ _)) /= IH.\nsuff: x <= a by move=>->.\nby rewrite leNgt lt_neqAle H andbF.\nQed.\n\nLemma sorted_isort xs : sorted <=%O (isort xs).\nProof. by elim: xs=>//= x xs; rewrite sorted_insort. Qed.\n\n(* Time complexity *)\n\nFixpoint T_insort x xs : nat :=\n  if xs is y :: xs' then\n    (if x <= y then 0 else T_insort x xs').+1\n    else 1.\n\nFixpoint T_isort xs : nat :=\n  if xs is x :: xs' then (T_isort xs' + T_insort x (isort xs')).+1 else 1.\n\nLemma T_insort_size x xs : T_insort x xs <= (size xs).+1.\nProof.\nelim: xs=>//=y xs IH.\nby case: (x <= y).\nQed.\n\n(* This seems to be unused *)\nLemma size_insort x xs : size (insort x xs) = (size xs).+1.\nProof. by move/perm_size: (perm_insort x xs). Qed.\n\nLemma size_isort xs : size (isort xs) = size xs.\nProof. by move/perm_size: (perm_isort xs). Qed.\n\nLemma T_isort_size xs : T_isort xs <= (size xs).+1 ^ 2.\nProof.\nelim: xs=>// x xs IH.\nrewrite -addn1 sqrnD /= -addn1 -!addnA.\napply: leq_add=>//; rewrite exp1n muln1 addnC leq_add2l.\napply: leq_trans; first by exact: T_insort_size.\nby rewrite size_isort; apply: leq_pmull.\nQed.\n\n(* Exercise 2.1 *)\n\nLemma isort_beh (f : seq T -> seq T) xs :\n  perm_eq (f xs) xs -> sorted <=%O (f xs) -> f xs = isort xs.\nProof.\nAdmitted.\n\n(* Exercise 2.2.1 *)\n\nLemma T_isort_optimal xs : sorted <=%O xs -> T_isort xs = (2 * size xs).+1.\nProof.\nAdmitted.\n\nEnd InsertionSort.\n\nSection InsertionSortNat.\n\n(* uphalf_addn from prelude might come in handy here *)\n(* Exercise 2.2.2 *)\nLemma T_isort_worst n : T_isort (rev (iota 0 n)) = uphalf ((n.+1)*(n.+2)).\nProof.\nAdmitted.\n\nEnd InsertionSortNat.\n\nSection QuickSort.\nContext {disp : unit} {T : orderType disp}.\nImplicit Types (xs ys : seq T).\n\n(* Definition *)\n\nEquations? quicksort xs : seq T by wf (size xs) lt :=\nquicksort [::]    => [::];\nquicksort (x::xs) => quicksort (filter (< x) xs) ++ [:: x] ++\n                     quicksort (filter (>= x) xs).\nProof. all: by rewrite size_filter /=; apply/ssrnat.ltP/count_size. Qed.\n\n(* Functional Correctness *)\n\nLemma perm_quicksort xs : perm_eq (quicksort xs) xs.\nProof.\napply_funelim (quicksort xs)=>//=x {}xs Hl Hg.\nrewrite perm_catC cat_cons perm_cons perm_sym -(perm_filterC (>= x)) perm_sym.\napply: perm_cat=>//.\nrewrite (eq_in_filter (a2 := < x)) //= =>y _.\nby rewrite ltNge.\nQed.\n\nLemma sorted_quicksort xs : sorted <=%O (quicksort xs).\nProof.\napply_funelim (quicksort xs)=>//= x {}xs Hl Hg.\nhave Hx : sorted <=%O [:: x] by [].\nmove: (merge_sorted le_total Hx Hg)=>{Hx}/=.\nrewrite allrel_merge; last first.\n- by rewrite allrel1l (perm_all _ (perm_quicksort _)) filter_all.\nmove/(merge_sorted le_total Hl); rewrite allrel_merge //=.\napply/allrelP=>y z.\nrewrite (perm_mem (perm_quicksort _) y) inE\n  (perm_mem (perm_quicksort _) z) !mem_filter /=.\ncase/andP=>Hy _; case/orP=>[/eqP ->|/andP [Hz _]];\nrewrite le_eqVlt; apply/orP; right=>//.\nby apply/lt_le_trans/Hz.\nQed.\n\n(* Exercise 2.3 *)\n\nEquations? quicksort2 xs ys : seq T by wf (size xs) lt :=\nquicksort2 xs ys => ys. (* FIXME *)\nProof.\nQed.\n\nLemma quick2_quick xs ys : quicksort2 xs ys = quicksort xs ++ ys.\nProof.\nAdmitted.\n\n(* Exercise 2.4 *)\n\n(* TODO rewrite in one pass? *)\nDefinition partition3 x xs : seq T * seq T * seq T :=\n  (filter (< x) xs, filter (pred1 x) xs, filter (> x) xs).\n\nEquations? quicksort3 xs : seq T by wf (size xs) lt :=\nquicksort3 [::]    => [::];\nquicksort3 (x::xs) with inspect (partition3 x xs) => {\n  | (ls, es, gs) eqn: eq => quicksort3 ls ++ x :: es ++ quicksort3 gs\n}.\nProof. all: by apply/ssrnat.ltP; rewrite size_filter; apply: count_size. Qed.\n\n(* this is the main part *)\nLemma quick_filter_ge x xs :\n  quicksort (filter (>= x) xs) = filter (pred1 x) xs ++ quicksort (filter (> x) xs).\nProof.\nAdmitted.\n\nLemma quick3_quick xs : quicksort3 xs = quicksort xs.\nProof.\nAdmitted.\n\n(* Exercise 2.5.1 *)\n\n(* TODO move to basics? *)\nFixpoint T_mapfilter {A} (ta : A -> nat) (s : seq A) : nat :=\n  if s is x :: s' then ta x + T_mapfilter ta s' + 1 else 1.\n\nLemma T_mapfilter_size {A} (xs : seq A) ta :\n  T_mapfilter ta xs = \\sum_(x<-xs) (ta x) + size xs + 1.\nProof.\nelim: xs=>/=; first by rewrite big_nil.\nby move=>x xs ->; rewrite big_cons -(addn1 (size _)) !addnA.\nQed.\n\nEquations? T_quicksort xs : nat by wf (size xs) lt :=\nT_quicksort [::]    => 1;\nT_quicksort (x::xs) => T_quicksort (filter (< x) xs) +\n                       T_quicksort (filter (>= x) xs) +\n                       2 * T_mapfilter (fun => 1%N) xs + 1.\nProof. all: by apply/ssrnat.ltP; rewrite size_filter; apply: count_size. Qed.\n\n(* FIXME replace these with concrete numbers *)\nParameters (a b c : nat).\n\nLemma quicksort_quadratic xs :\n  sorted <=%O xs -> T_quicksort xs = a * size xs ^ 2 + b * size xs + c.\nProof.\nAdmitted.\n\n(* Exercise 2.5.2 *)\n\nLemma quicksort_worst xs :\n  T_quicksort xs <= a * size xs ^ 2 + b * size xs + c.\nProof.\nAdmitted.\n\nEnd QuickSort.\n\nSection TopDownMergeSort.\nContext {disp : unit} {T : orderType disp}.\nImplicit Types (xs ys : seq T).\n\n(* reusing `merge` from mathcomp.path *)\n\nEquations? msort xs : seq T by wf (size xs) lt :=\nmsort [::]  => [::];\nmsort [::x] => [::x];\nmsort xs    => let n := size xs in\n               merge <=%O (msort (take n./2 xs))\n                          (msort (drop n./2 xs)).\nProof.\nall: apply/ssrnat.ltP.\n- by rewrite size_take /= !ltnS !half_le.\nby rewrite size_drop /= /leq subSS subnAC subnn.\nQed.\n\n(* Functional Correctness *)\n\nLemma perm_msort xs : perm_eq (msort xs) xs.\nProof.\nfunelim (msort xs)=>//=.\nrewrite perm_merge -{3}(cat_take_drop (size l)./2 (s0::l)) -cat_cons.\nby apply: perm_cat.\nQed.\n\nLemma sorted_msort xs : sorted <=%O (msort xs).\nProof. by funelim (msort xs)=>//=; apply: merge_sorted. Qed.\n\n(* Running Time Analysis *)\n\nFixpoint C_merge xs :=\n  if xs is x :: xs' then\n    let fix C_merge_xs ys :=\n      if ys is y :: ys' then\n        (if x <= y then C_merge xs' ys else C_merge_xs ys').+1\n      else 0 in\n    C_merge_xs\n  else fun => 0.\n\nEquations? C_msort xs : nat by wf (size xs) lt :=\nC_msort [::]  => 0;\nC_msort [::x] => 0;\nC_msort xs    => let n := (size xs) in\n                 let ys := take n./2 xs in\n                 let zs := drop n./2 xs in\n                 C_msort ys + C_msort zs + C_merge (msort ys) (msort zs).\nProof.\nall: apply/ssrnat.ltP.\n- by rewrite size_take /= !ltnS !half_le.\nby rewrite size_drop /= /leq subSS subnAC subnn.\nQed.\n\nLemma C_merge_leq xs ys : (C_merge xs ys <= size xs + size ys)%N.\nProof.\nelim: xs ys=>//= x xs IH1; elim=>//= y ys IH2.\ncase: ifP=>_.\n- rewrite -addn1 -!(addn1 (size _)) addnA leq_add2r addnAC.\n  apply: leq_trans; first by apply: IH1.\n  by rewrite addn1 addnS.\nby rewrite addnS ltnS; apply: IH2.\nQed.\n\nLemma C_msort_leq xs k: size xs = 2^k -> (C_msort xs <= k * 2^k)%N.\nProof.\nelim: k xs=>/=.\n- by move=>xs; rewrite expn0 =>/size1 [x] ->; simp C_msort.\nmove=>k IH xs H.\nhave Hs1 : (size xs > 1)%N by rewrite H -{1}(expn0 2); apply: ltn_exp2l.\ncase: (size2 Hs1)=> x[y][ys] He; rewrite He /= in H *; simp C_msort=>/=.\nhave Hp : (size ys)./2.+1 = ((size ys).+2)./2 by rewrite -addn2 halfD andbF /= addn1.\nhave Ht : size (x :: take (size ys)./2 (y :: ys)) = 2^k.\n- by rewrite /= size_take /= ltnS half_le Hp H expnS mul2n half_double.\nhave Hd : size (drop (size ys)./2 (y :: ys)) = 2^k.\n- rewrite size_drop /= subSn; last by apply: half_le.\n  by rewrite half_subn uphalf_half -addnS Hp H expnS mul2n half_double odd2 H oddX.\napply: leq_trans;\n  first by exact: (leq_add (leq_add (IH _ Ht) (IH _ Hd)) (C_merge_leq _ _)).\nrewrite !(perm_size (perm_msort _)) Ht Hd.\nby rewrite !addnn -!muln2 -mulnA -!expnSr -{3}(addn1 k) mulnDl mul1n.\nQed.\n\n(* Exercise 2.6 *)\n\nFixpoint halve {A: Type} (xs ys zs : seq A) : seq A * seq A :=\n  ([::],[::]). (* FIXME *)\n\nEquations? msort2 xs : seq T by wf (size xs) lt :=\nmsort2 [::]  => [::];\nmsort2 [::x] => [::x];\nmsort2 xs with inspect (halve xs [::] [::]) := {\n  | (ys1, ys2) eqn: eq => merge <=%O (msort2 ys1) (msort2 ys2)\n}.\nProof.\nall: apply/ssrnat.ltP.\n(* FIXME *)\n- by [].\nby [].\nQed.\n\nLemma perm_msort2 xs : perm_eq (msort2 xs) xs.\nProof.\nAdmitted.\n\nLemma sorted_msort2 xs : sorted <=%O (msort2 xs).\nProof.\nAdmitted.\n\nEnd TopDownMergeSort.\n\nSection BottomUpMergeSort.\nContext {disp : unit} {T : orderType disp}.\nImplicit Types (xs ys : seq T).\n\nEquations merge_adj : seq (seq T) -> seq (seq T) :=\nmerge_adj [::]          => [::];\nmerge_adj [::xs]        => [::xs];\nmerge_adj (xs::ys::zss) => merge <=%O xs ys :: merge_adj zss.\n\nLemma size_merge_adj xss : size (merge_adj xss) = uphalf (size xss).\nProof. by funelim (merge_adj xss)=>//=; congr S. Qed.\n\nEquations? merge_all (xss : seq (seq T)) : seq T by wf (size xss) lt :=\nmerge_all [::]   => [::];\nmerge_all [::xs] => xs;\nmerge_all xss    => merge_all (merge_adj xss).\nProof. by apply/ssrnat.ltP; rewrite size_merge_adj /= !ltnS; apply: uphalf_le. Qed.\n\nDefinition msort_bu xs : seq T :=\n  merge_all (map (fun x => [::x]) xs).\n\n(* Functional Correctness *)\n\nLemma perm_merge_adj xss : perm_eq (flatten (merge_adj xss)) (flatten xss).\nProof.\nfunelim (merge_adj xss)=>//=.\nrewrite catA; apply: perm_cat=>//.\nby rewrite perm_merge.\nQed.\n\nLemma perm_merge_all xss : perm_eq (merge_all xss) (flatten xss).\nProof.\nfunelim (merge_all xss)=>//=; first by rewrite cats0.\nby apply/(perm_trans H)/perm_merge_adj.\nQed.\n\nLemma perm_msort_bu xs : perm_eq (msort_bu xs) xs.\nProof.\nrewrite /msort_bu; apply: (perm_trans (perm_merge_all _)).\nby rewrite flatten_map1 map_id.\nQed.\n\nLemma sorted_merge_adj xss :\n  all (sorted <=%O) xss -> all (sorted <=%O) (merge_adj xss).\nProof.\nfunelim (merge_adj xss)=>//= /and3P [Hs1 Hs2] /H ->; rewrite andbT.\nby apply: merge_sorted.\nQed.\n\nLemma sorted_merge_all xss :\n  all (sorted <=%O) xss -> sorted <=%O (merge_all xss).\nProof.\nfunelim (merge_all xss)=>//=; first by rewrite andbT.\nmove: H; simp merge_adj=>/= H.\ncase/and3P=>Hs1 Hs2 Hs; apply/H/andP.\nby split; [apply: merge_sorted | apply: sorted_merge_adj].\nQed.\n\nLemma sorted_msort_bu xs : sorted <=%O (msort_bu xs).\nProof.\nrewrite /msort_bu; apply: sorted_merge_all; rewrite all_map.\nby elim: xs.\nQed.\n\n(* Running Time Analysis *)\n\nEquations C_merge_adj : seq (seq T) -> nat :=\nC_merge_adj [::]          => 0;\nC_merge_adj [::xs]        => 0;\nC_merge_adj (xs::ys::zss) => C_merge xs ys + C_merge_adj zss.\n\nEquations? C_merge_all (xss : seq (seq T)) : nat by wf (size xss) lt :=\nC_merge_all [::]   => 0;\nC_merge_all [::xs] => 0;\nC_merge_all xss    => C_merge_adj xss + C_merge_all (merge_adj xss).\nProof. by apply/ssrnat.ltP; rewrite size_merge_adj /= !ltnS; apply: uphalf_le. Qed.\n\nDefinition C_msort_bu xs : nat :=\n  C_merge_all (map (fun x => [::x]) xs).\n\nLemma merge_adj_sizes xss m :\n  ~~ odd (size xss) -> all (fun xs => size xs == m) xss ->\n  all (fun xs => size xs == m.*2) (merge_adj xss).\nProof.\nfunelim (merge_adj xss)=>//=; rewrite negbK=>Ho /and3P [/eqP Hx /eqP Hy Ha]; apply/andP.\nsplit; last by rewrite (H _ Ho Ha).\nby rewrite size_merge size_cat Hx Hy addnn.\nQed.\n\nLemma C_merge_adj_leq xss m :\n  all (fun xs => size xs == m) xss -> C_merge_adj xss <= m * size xss.\nProof.\nfunelim (C_merge_adj xss)=>//= /and3P [/eqP Hx /eqP Hy Ha].\nrewrite -add2n mulnDr muln2 -addnn; apply/leq_add/H=>//.\nby rewrite -{1}Hx -Hy; apply: C_merge_leq.\nQed.\n\nLemma C_merge_all_leq xss m k :\n  all (fun xs => size xs == m) xss -> size xss = 2 ^ k ->\n  C_merge_all xss <= m * k * 2^k.\nProof.\nfunelim (C_merge_all xss)=>//= /and3P [/eqP Hx /eqP Hy Ha] Hs.\nmove: H; simp merge_adj C_merge_adj=>/= H. (* slow for some reason *)\nhave [k0 Hk] : { k0 | k = k0.+1 } by move: Hs; case: k=>//=k0 _; exists k0.\nhave He : ~~ odd (size l1) by rewrite odd2 Hs oddX Hk.\nrewrite Hk expnS mulnS mulnDl in Hs *; apply: leq_add.\n- rewrite -Hs -addn2 mulnDr addnC.\n  apply: leq_add; first by apply: C_merge_adj_leq.\n  by rewrite muln2 -addnn -{1}Hx -Hy; apply: C_merge_leq.\nrewrite mulnCA !mulnA mul2n; apply: H.\n- apply/andP; split; last by apply: merge_adj_sizes.\n  by rewrite size_merge size_cat Hx Hy addnn.\napply/eqP; rewrite size_merge_adj -addn1 -(eqn_pmul2r (m:=2)) // mulnDl muln2.\nhave -> : (uphalf (size l1)).*2 = size l1\n  by rewrite -[in RHS](odd_double_half (size l1)) uphalf_half (negbTE He).\nby rewrite addn2 mulnC Hs.\nQed.\n\nLemma C_msort_bu_leq xs k : size xs = 2^k -> C_msort_bu xs <= k * 2^k.\nProof.\nmove=>H; rewrite -(mul1n (_ * _)) mulnA; apply: C_merge_all_leq.\n- by rewrite all_map; elim: {H}xs.\nby rewrite size_map.\nQed.\n\nEnd BottomUpMergeSort.\n\nSection NaturalMergeSort.\nContext {disp : unit} {T : orderType disp}.\nImplicit Types (xs ys : seq T) (xss : seq (seq T)).\n\nFixpoint runs_fix a xs : seq (seq T) :=\n  if xs is b::bs\n    then if b < a then desc b [:: a] bs else asc b (cons a) bs\n    else [::[::a]]\nwith asc x (xd : seq T -> seq T) ys : seq (seq T) :=\n  if ys is y::ys'\n    then if x <= y then asc y (xd \\o cons x) ys' else xd [::x] :: runs_fix y ys'\n    else [:: xd [::x]]\nwith desc x xs ys : seq (seq T) :=\n  if ys is y::ys'\n     then if y < x then desc y (x :: xs) ys' else (x :: xs) :: runs_fix y ys'\n     else [:: (x :: xs)].\n\nDefinition runs xs : seq (seq T) :=\n  if xs is x::xs' then runs_fix x xs' else [::].\n\nDefinition nmsort xs := merge_all (runs xs).\n\n(* Functional Correctness *)\n\nDefinition is_dlist (xd : seq T -> seq T) :=\n  forall ps qs, xd (ps ++ qs) = xd ps ++ qs.\n\nLemma perm_runs_asc_desc x xs ys xd :\n     perm_eq (flatten (runs_fix x ys)) (x :: ys)\n  /\\ perm_eq (flatten (desc x xs ys)) (x::xs ++ ys)\n  /\\ (is_dlist xd ->\n       perm_eq (flatten (asc x xd ys)) (x :: xd [::] ++ ys)).\nProof.\nelim: ys x xs xd=>/=.\n- move=>x xs xd; do!split=>//.\n  by move=>H; move: (H [::] [::x])=>/=; rewrite !cats0=>->; rewrite perm_catC.\nmove=>b bs IH x xs xd; do!split.\n- case: ifP=>_.\n  - apply: perm_trans; first by case: (IH b [::x] xd)=>_ [+ _]; apply.\n    by move: (perm_catCA [::b] [::x] bs)=>/=->.\n  apply: perm_trans; first by case: (IH b [::x] (cons x))=>_ [_] /=; apply.\n  by move: (perm_catCA [::b] [::x] bs)=>/=->.\n- case: ifP=>_.\n  - apply: perm_trans; first by case: (IH b (x::xs) xd)=>_ [+ _]; apply.\n    by move: (perm_catCA [::b] (x::xs) bs)=>/=->.\n  rewrite /= -!cat_cons perm_cat2l.\n  by case: (IH b xs xd)=>+ _; apply.\nmove=>H; case: ifP=>_.\n- apply: perm_trans.\n  - case: (IH b xs (xd \\o cons x))=>_ [_] /=; apply=>ps qs.\n    by rewrite /= -cat_cons; apply: H.\n  move: (H [::] [::x])=>/=->; move: (perm_catCA [::b] (xd [::] ++ [::x]) bs)=>/=->.\n  by rewrite -cat_cons perm_cat2r perm_catC.\nmove: (H [::] [::x])=>/=->; rewrite -cat_cons.\napply: perm_cat; first by rewrite perm_catC.\nby case: (IH b xs xd)=>+ _; apply.\nQed.\n\nLemma perm_runs xs : perm_eq (flatten (runs xs)) xs.\nProof.\ncase: xs=>//=x xs.\nby case: (perm_runs_asc_desc x [::] xs id).\nQed.\n\nLemma perm_nmsort xs : perm_eq (nmsort xs) xs.\nProof.\nrewrite /nmsort; apply/perm_trans/perm_runs.\nby apply: perm_merge_all.\nQed.\n\nLemma sorted_runs_asc_desc x xs ys xd :\n     all (sorted <=%O) (runs_fix x ys)\n  /\\ (sorted <=%O xs -> all (>= x) xs -> all (sorted <=%O) (desc x xs ys))\n  /\\ (is_dlist xd -> sorted <=%O (xd [::]) -> all (<= x) (xd [::]) ->\n      all (sorted <=%O) (asc x xd ys)).\nProof.\nelim: ys x xs xd=>/=.\n- move=>x xs xd; do!split.\n  - by move=>Hs Ha; rewrite andbT le_path_sortedE; apply/andP.\n  move=>Hd Hs Ha; rewrite andbT; move: (Hd [::] [::x])=>/=->.\n  rewrite cats1; apply: sorted_rcons=>//; exact: le_trans.\nmove=>b ys IH x xs xd; do!split.\n- case: ifP=>Ho.\n  - case: (IH b [::x] id)=>_ [+ _]; apply=>//.\n    by rewrite all_seq1 le_eqVlt Ho orbT.\n  case: (IH b xs (cons x))=>_ [_]; apply=>//.\n  by rewrite all_seq1 /= leNgt; apply/negbT.\n- move=>Hs Ha; case: ifP=>Ho /=.\n  - case: (IH b (x::xs) id)=>_ [+ _]; apply=>/=.\n    - by rewrite le_path_sortedE; apply/andP.\n    rewrite le_eqVlt Ho orbT /=; apply/sub_all/Ha=>z.\n    by apply/le_trans; rewrite le_eqVlt Ho orbT.\n  rewrite le_path_sortedE Ha Hs /=.\n  by case: (IH b xs xd)=>+ _; apply.\nmove=>Hd Hs Ha; case: ifP=>Ho /=.\n- case: (IH b xs (xd \\o cons x))=>_ [_] /=; apply.\n  - by move=>ps qs /=; rewrite -cat_cons; apply: Hd.\n  - move: (Hd [::] [::x])=>/=->.\n    by rewrite cats1; apply: sorted_rcons=>//; exact: le_trans.\n  move: (Hd [::] [::x])=>/=->.\n  rewrite cats1 all_rcons /= Ho /=.\n  by apply/sub_all/Ha=>z /= Hx; apply/le_trans/Ho.\napply/andP; split.\n- move: (Hd [::] [::x])=>/=->.\n  by rewrite cats1; apply: sorted_rcons=>//; exact: le_trans.\nby case: (IH b xs id)=>+ _; apply.\nQed.\n\nLemma sorted_runs xs : all (sorted <=%O) (runs xs).\nProof. by case: xs=>//=x xs; case: (sorted_runs_asc_desc x [::] xs id). Qed.\n\nLemma sorted_nmsort xs : sorted <=%O (nmsort xs).\nProof. by rewrite /nmsort; apply/sorted_merge_all/sorted_runs. Qed.\n\n(* Running Time Analysis *)\n\nFixpoint C_runs_fix a xs : nat :=\n  if xs is b::bs\n    then (if b < a then C_desc b bs else C_asc b bs).+1\n    else 0\nwith C_asc a xs : nat :=\n  if xs is b::bs\n    then (if a <= b then C_asc b bs else C_runs_fix b bs).+1\n    else 0\nwith C_desc a xs : nat :=\n  if xs is b::bs\n     then (if b < a then C_desc b bs else C_runs_fix b bs).+1\n     else 0.\n\nDefinition C_runs xs : nat :=\n  if xs is x::xs' then C_runs_fix x xs' else 0.\n\nDefinition C_nmsort xs : nat :=\n  C_runs xs + C_merge_all (runs xs).\n\nLemma C_merge_adj_flat xss : C_merge_adj xss <= size (flatten xss).\nProof.\nfunelim (C_merge_adj xss)=>//=; rewrite catA !size_cat.\nby apply: leq_add=>//; apply: C_merge_leq.\nQed.\n\nLemma merge_adj_flat xss :\n  size (flatten (merge_adj xss)) = size (flatten xss).\nProof.\nfunelim (merge_adj xss)=>//=.\nby rewrite catA !size_cat H size_merge size_cat.\nQed.\n\nLemma C_merge_adj_log2 xss :\n  C_merge_all xss <= size (flatten xss) * up_log 2 (size xss).\nProof.\nfunelim (C_merge_all xss)=>//=; move: H; simp C_merge_adj merge_adj.\nrewrite /= !size_cat merge_adj_flat size_merge_adj size_merge size_cat =>IH.\nrewrite up_log2S //= mulnS !addnA; apply: leq_add=>//.\nby apply/leq_add/C_merge_adj_flat/C_merge_leq.\nQed.\n\nLemma size_runs_asc_desc x xs ys xd :\n      size (flatten (runs_fix x ys)) = (size ys).+1\n  /\\  size (flatten (desc x xs ys)) = (size xs + size ys).+1\n  /\\ (is_dlist xd ->\n      size (flatten (asc x xd ys)) = (size (xd [::]) + size ys).+1).\nProof.\nelim: ys x xs xd=>/=.\n- move=>x xs xd; do!split; first by rewrite cats0 addn0.\n  by move=>H; move: (H [::] [::x])=>/=; rewrite !cats0=>->; rewrite size_cat addn0 /= addn1.\nmove=>b bs IH x xs xd; do!split.\n- case: ifP=>_.\n  - by case: (IH b [::x] id)=>_ [+ _]; rewrite /= addnC addn1.\n  case: (IH b [::x] (cons x))=>_ [_] /=; rewrite /= addnC addn1; apply.\n  by move=>??; rewrite cat_cons.\n- case: ifP=>_ /=.\n  - by case: (IH b (x::xs) id)=>_ [+ _]; rewrite /= addSnnS.\n  by case: (IH b xs xd)=>+ _; rewrite size_cat=>->.\nmove=>H; case: ifP=>_ /=.\n- case: (IH b xs (xd \\o cons x))=>_ [_] /=.\n  move: (H [::] [::x])=>/=->; rewrite size_cat /= addnAC -addnA addn1; apply.\n  by move=>?? /=; rewrite -cat_cons; apply: H.\nmove: (H [::] [::x])=>/=->; rewrite !size_cat /=.\nby case: (IH b xs xd)=>+ _; rewrite addnAC addn1=>->.\nQed.\n\nLemma size_runs xs : size (flatten (runs xs)) = size xs.\nProof. by case: xs=>//=x xs; case: (size_runs_asc_desc x [::] xs id). Qed.\n\nLemma size_runs_asc_desc_leq x xs ys xd :\n      (size (runs_fix x ys) <= (size ys).+1)%N\n  /\\  (size (desc x xs ys) <= (size ys).+1)%N\n  /\\ (is_dlist xd ->\n      (size (asc x xd ys) <= (size ys).+1)%N).\nProof.\nelim: ys x xs xd=>//= b bs IH x xs xd; do!split.\n- case: ifP=>_.\n  - by apply: leqW; case: (IH b [::x] id)=>_ [+ _].\n  apply: leqW; case: (IH b [::x] (cons x))=>_ [_]; apply.\n  by move=>??; rewrite cat_cons.\n- case: ifP=>_ /=.\n  - by apply: leqW; case: (IH b (x::xs) id)=>_ [+ _].\n  by rewrite ltnS; case: (IH b xs xd)=>+ _ /=.\nmove=>H; case: ifP=>_ /=.\n- apply: leqW; case: (IH b xs (xd \\o cons x))=>_ [_] /=; apply.\n  by move=>?? /=; rewrite -cat_cons; apply: H.\nby rewrite ltnS; case: (IH b xs xd)=>+ _.\nQed.\n\nLemma size_runs_leq xs : (size (runs xs) <= size xs)%N.\nProof. by case: xs=>//=x xs; case: (size_runs_asc_desc_leq x [::] xs id). Qed.\n\nLemma C_size_runs_asc_desc_leq x ys :\n     (C_runs_fix x ys <= size ys)%N\n  /\\ (C_desc x ys <= size ys)%N\n  /\\ (C_asc x ys <= size ys)%N.\nProof.\nelim: ys x=>//=b bs IH x.\nby do!split; case: ifP=>_; rewrite ltnS; case: (IH b)=>+ [].\nQed.\n\nLemma C_size_runs_leq xs : (C_runs xs <= (size xs).-1)%N.\nProof. by case: xs=>//=x xs; case: (C_size_runs_asc_desc_leq x xs). Qed.\n\nLemma C_merge_runs_leq xs n :\n  size xs = n -> (C_merge_all (runs xs) <= n * up_log 2 n)%N.\nProof.\nmove=>H; apply: leq_trans; first by apply: C_merge_adj_log2.\nrewrite size_runs H leq_mul2l; apply/orP.\ncase: n H=>[H|n H]; first by left.\nright; apply: leq_up_log; rewrite -H.\nby apply: size_runs_leq.\nQed.\n\nLemma C_nmsort_leq xs n :\n  size xs = n -> (C_nmsort xs <= n + n * up_log 2 n)%N.\nProof.\nmove=>H; rewrite /C_nmsort; apply/leq_add/C_merge_runs_leq=>//.\napply: leq_trans; first by apply: C_size_runs_leq.\nby rewrite H; exact: leq_pred.\nQed.\n\nEnd NaturalMergeSort.\n\nSection Stability.\nContext {disp : unit} {T : eqType} {K : orderType disp}.\nImplicit Types (xs ys : seq T).\n\n(* Definition *)\n\nFixpoint insort_key (f : T -> K) x xs : seq T :=\n  if xs is y :: xs' then\n    if f x <= f y then x :: y :: xs' else y :: insort_key f x xs'\n    else [:: x].\n\nFixpoint isort_key f xs :=\n  if xs is x :: xs' then insort_key f x (isort_key f xs') else [::].\n\nLemma perm_insort_key f x xs : perm_eq (insort_key f x xs) (x :: xs).\nProof.\nelim: xs=>//= y xs IH; case: (_ <= _)=>//.\nrewrite -(perm_cons y) in IH.\napply: perm_trans; first by exact: IH.\nby apply/permP=>/=?; rewrite addnCA.\nQed.\n\nLemma perm_isort_key f xs : perm_eq (isort_key f xs) xs.\nProof.\nelim: xs=>//= x xs IH.\napply: perm_trans; first by apply: perm_insort_key.\nby rewrite perm_cons.\nQed.\n\nLemma sorted_insort_key f a xs :\n  sorted <=%O (map f (insort_key f a xs)) = sorted <=%O (map f xs).\nProof.\nelim: xs=>//= x xs IH.\ncase H: (_ <= _)=>/=; first by rewrite H.\nrewrite !le_path_sortedE !all_map (perm_all _ (perm_insort_key _ _ _)) /= IH.\nsuff: f x <= f a by move=>->.\nby rewrite leNgt lt_neqAle H andbF.\nQed.\n\nLemma sorted_isort_key f xs : sorted <=%O (map f (isort_key f xs)).\nProof. by elim: xs=>//=x xs; rewrite sorted_insort_key. Qed.\n\nLemma insort_key_cons f a xs :\n  all (fun x => f a <= f x) xs -> insort_key f a xs = a :: xs.\nProof. by case: xs=>//=x xs /andP [-> _]. Qed.\n\nLemma filter_not_insort_key (p : pred T) f x xs :\n  ~~ p x -> filter p (insort_key f x xs) = filter p xs.\nProof.\nmove/negbTE=>Hp; elim: xs=>/=; first by rewrite Hp.\nmove=>y xs IH; case: ifP=>_ /=; first by rewrite Hp.\nby rewrite IH.\nQed.\n\nLemma filter_insort_key (p : pred T) f x xs :\n  sorted <=%O (map f xs) -> p x ->\n  filter p (insort_key f x xs) = insort_key f x (filter p xs).\nProof.\nmove/[swap]=>Hp; elim: xs=>/=; first by rewrite Hp.\nmove=>y xs IH; rewrite le_path_sortedE =>/andP [Ha Hs].\ncase: ifP=>Hf /=.\n- rewrite Hp; case: ifP=>/=; first by rewrite Hf.\n  rewrite insort_key_cons // all_filter.\n  rewrite all_map in Ha; apply/sub_all/Ha.\n  by move=>z /= Hf2; apply/implyP=>_; apply/le_trans/Hf2.\nby case: ifP=>/=; rewrite (IH Hs) // Hf.\nQed.\n\nLemma isort_key_stable f k xs :\n  filter (fun y => f y == k) (isort_key f xs) = filter (fun y => f y == k) xs.\nProof.\nelim: xs=>//=x xs IH; case: ifP; last first.\n- by move/negbT=>Hk; rewrite filter_not_insort_key.\nmove=>Hk; rewrite filter_insort_key //; last by apply: sorted_isort_key.\nrewrite IH insort_key_cons // all_filter (eq_in_all (a2:=predT)) ?all_predT //.\nby move=>z _ /=; apply/implyP; move/eqP: Hk=>->/eqP->.\nQed.\n\nEnd Stability.\n", "meta": {"author": "clayrat", "repo": "fav-ssr", "sha": "ec672bc001f6ace70cfc971990631371263b40f1", "save_path": "github-repos/coq/clayrat-fav-ssr", "path": "github-repos/coq/clayrat-fav-ssr/fav-ssr-ec672bc001f6ace70cfc971990631371263b40f1/src/sorting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.6740430625643156}}
{"text": "Require Import\n  HoTT.Classes.interfaces.abstract_algebra.\n\n(** If [B] is a (bounded) lattice, then so is [A -> B], pointwise.\n    This relies on functional extensionality. *)\nSection contents.\n  Context `{Funext}.\n\n  Context {A B : Type}.\n  Context `{BJoin : Join B}.\n  Context `{BMeet : Meet B}.\n  Context `{BBottom : Bottom B}.\n  Context `{BTop : Top B}.\n\n  Global Instance bot_fun : Bottom (A -> B)\n    := fun _ => ⊥.\n\n  Global Instance top_fun : Top (A -> B)\n    := fun _ => ⊤.\n\n  Global Instance join_fun : Join (A -> B) :=\n    fun (f g : A -> B) (a : A) => (f a) ⊔ (g a).\n\n  Global Instance meet_fun : Meet (A -> B) :=\n    fun (f g : A -> B) (a : A) => (f a) ⊓ (g a).\n\n  (** Try to solve some of the lattice obligations automatically *)\n  Create HintDb lattice_hints.\n  #[local]\n  Hint Resolve\n       associativity\n       absorption\n       commutativity | 1 : lattice_hints.\n  Local Ltac reduce_fun := compute; intros; apply path_forall; intro.\n\n  Global Instance lattice_fun `{!IsLattice B} : IsLattice (A -> B).\n  Proof.\n    repeat split; try apply _; reduce_fun.\n    1,4: apply associativity.\n    1,3: apply commutativity.\n    1,2: apply binary_idempotent.\n    1,2: apply absorption.\n  Defined.\n\n  Instance boundedjoinsemilattice_fun\n   `{!IsBoundedJoinSemiLattice B} :\n    IsBoundedJoinSemiLattice (A -> B).\n  Proof.\n    repeat split; try apply _; reduce_fun.\n    * apply associativity.\n    * apply left_identity.\n    * apply right_identity.\n    * apply commutativity.\n    * apply binary_idempotent.\n  Defined.\n\n  Instance boundedmeetsemilattice_fun\n   `{!IsBoundedMeetSemiLattice B} :\n    IsBoundedMeetSemiLattice (A -> B).\n  Proof.\n    repeat split; try apply _; reduce_fun.\n    * apply associativity.\n    * apply left_identity.\n    * apply right_identity.\n    * apply commutativity.\n    * apply binary_idempotent.\n  Defined.\n\n  Global Instance boundedlattice_fun\n   `{!IsBoundedLattice B} : IsBoundedLattice (A -> B).\n  Proof.\n    repeat split; try apply _; reduce_fun; apply absorption.\n  Defined.\nEnd contents.\n\n#[export]\n  Hint Resolve\n       associativity\n       absorption\n       commutativity | 1 : lattice_hints.\n\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Classes/implementations/pointwise.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.673992298491372}}
{"text": "Require Import HoTT.\n\nLemma lem_prop: forall A B, ~(A * B) -> IsHProp A -> IsHProp B -> IsHProp (A + B).\nintros A B H H0 H1.\napply ishprop_sum; auto.\nQed.\n\nLemma merely_functorial: forall P Q, (P -> Q) -> merely P -> merely Q.\n  intros P Q H.\n  apply Trunc_rec.\n  intro H0.\n  apply tr.\n  auto.\nDefined.\n\nTheorem thm7_2_2:\n  forall X: Type, forall R: X -> X -> hProp,\n  (forall x y, R x y -> x = y) -> IsHSet X.\nAdmitted.\n\nSection ex_7_1.\n  Proposition ex_7_1_q1: (forall A, merely A -> A) -> forall X, IsHSet X.\n  Proof.\n    intros H X.\n    apply (thm7_2_2 X (fun x y => merely (x = y))).\n    intros x y.\n    apply H.\n  Qed.\n  Goal (forall A B (f: A -> B), (forall b, merely (hfiber f b)) -> (forall b, hfiber f b))\n        -> forall X, IsHSet X.\n  Proof.\n    intros H X.\n    apply ex_7_1_q1.\n    intros A H0.\n    generalize (H A Unit (fun _ => tt)); intro H1.\n    unfold hfiber in H1.\n    apply H1.\n    induction b.\n    apply merely_functorial with (P := A); auto.\n    intro a.\n    exists a.\n    auto.\n    exact tt.\n  Qed.\nEnd ex_7_1.\n\nSection ex_7_7.\n  Definition GLEM m n := forall (A: TruncType n),\n    Trunc m (A + ~A).\n  Definition LEM := forall (A: hProp), A + ~A.\n  Goal forall m, GLEM (-1) m.+1 <-> LEM.\n    induction m.\n    split.\n    intros H A.\n    generalize (H A).\n    intro H0.\n    assert (IsHProp (A + ~A)).\n    apply lem_prop.\n    intro H1; destruct H1; auto.\n  Admitted.\nEnd ex_7_7.\n\n\n", "meta": {"author": "koba-e964", "repo": "HoTT-exercise", "sha": "9b0836fc78e1bf3d8d9616c4e69b790498bf3585", "save_path": "github-repos/coq/koba-e964-HoTT-exercise", "path": "github-repos/coq/koba-e964-HoTT-exercise/HoTT-exercise-9b0836fc78e1bf3d8d9616c4e69b790498bf3585/Ex7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.673992297678065}}
{"text": "(* Exercise 125 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n(* Peirce's law *)\n\nTheorem exercise_125 : ((A -> B) -> A) -> A.\nProof.\nimp_i a1.\nneg_e' (A) a2.\nhyp a2.\nimp_e (A -> B).\nhyp a1.\nimp_i a3.\nneg_e A.\nhyp a2.\nhyp a3.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop125.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6739922926968568}}
{"text": "(***********************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team    *)\n(* <O___,, *        INRIA-Rocquencourt  &  LRI-CNRS-Orsay              *)\n(*   \\VV/  *************************************************************)\n(*    //   *      This file is distributed under the terms of the      *)\n(*         *       GNU Lesser General Public License Version 2.1       *)\n(***********************************************************************)\n\nRequire Import FSets FMaps Arith Min Compare_dec NArith Nnat Pnat Ndec.\nImport Morphisms.\n\nSet Implicit Arguments.\nUnset Standard Proposition Elimination Names.\nOpen Scope N_scope.\n\nModule Type S.\n\n  Declare Module E : OrderedType.\n  Definition elt := E.t.\n\n  Parameter t : Type. (** the abstract type of sets *)\n\n  Parameter empty : t.\n  (** The empty set. *)\n\n  Parameter multi : elt -> t -> N.\n  (** [multi t s] gives the multiplicity of [t] in the multiset [s]. *)\n\n  Parameter update : elt -> N -> t -> t.\n  (** [update x m s] returns a multiset identical to [s], except that \n    multiplicity of [x] is now [m] *)\n\n  Parameter union : t -> t -> t.\n\n  Parameter inter : t -> t -> t.\n\n  Parameter diff : t -> t -> t.\n\n  Parameter equal : t -> t -> bool.\n\n  Parameter subset : t -> t -> bool.\n\n  Parameter fold : forall A : Type, (elt -> positive -> A -> A) -> t -> A -> A.\n  (** [fold] encounters only elements with non-null multiplicity *)\n\n  Parameter elements : t -> list (elt * positive).\n  (** [elements] returns the list of elements with non-null multiplicity *) \n\n\n  (** Logical predicates *)\n  Definition Equal s s' := forall a : elt, multi a s = multi a s'.\n  Definition Subset s s' := forall a : elt, multi a s <= multi a s'.\n  Definition Empty s := forall a : elt, multi a s = 0.\n  \n  Notation \"s [=] t\" := (Equal s t) (at level 70, no associativity).\n  Notation \"s [<=] t\" := (Subset s t) (at level 70, no associativity).\n\n  Section Spec. \n\n  Variable s s' s'' : t.\n  Variable x y : elt.\n  Variable n : N.\n  Variable p : positive.\n\n  (** Specification of [equal] *) \n  Parameter equal_1 : s[=]s' -> equal s s' = true.\n  Parameter equal_2 : equal s s' = true ->s[=]s'.\n\n  (** Specification of [subset] *)\n  Parameter subset_1 : s[<=]s' -> subset s s' = true.\n  Parameter subset_2 : subset s s' = true -> s[<=]s'.\n\n  (** Specification of [empty] *)\n  Parameter empty_1 : Empty empty.\n\n  (** Specification of [update] *)\n  Parameter update_1 : E.eq x y -> multi y (update x n s) = n.\n  Parameter update_2 : ~E.eq x y -> multi y (update x n s) = multi y s.\n\n  (** Specification of [union] *)\n  Parameter union_1 : multi x (union s s') = multi x s + multi x s'.\n\n  (** Specification of [inter] *)\n  Parameter inter_1 : multi x (inter s s') = Nmin (multi x s) (multi x s').\n\n  (** Specification of [diff] *)\n  Parameter diff_1 : multi x (diff s s') = multi x s - multi x s'.\n \n  (** Specification of [fold] *)  \n  Parameter fold_1 : forall (A : Type) (i : A) (f : elt -> positive -> A -> A),\n      fold f s i = fold_left (fun a p => f (fst p) (snd p) a) (elements s) i.\n\n  Definition eq_pair (p p':elt*positive) :=\n    E.eq (fst p) (fst p') /\\ (snd p) = (snd p').\n\n  Definition lt_pair (p p':elt*positive) := E.lt (fst p) (fst p').\n\n  (** Specification of [elements] *)\n  Parameter elements_1 : multi x s = Npos p -> InA eq_pair (x,p) (elements s).\n  Parameter elements_2 : InA eq_pair (x,p) (elements s) -> multi x s = Npos p.\n  Parameter elements_3 : sort lt_pair (elements s).  \n\n  End Spec.\n\nEnd S.\n\nModule Multi (X:OrderedType)(M:FMapInterface.S with Module E:=X) \n <: S with Module E:=X.\n\n Module E := X.\n\n Definition elt:=E.t.\n\n Definition t := M.t positive.\n Definition empty := M.empty positive.\n Definition multi x t := match M.find x t with \n  | None => 0 \n  | Some p => Npos p \n end.\n\n Definition update x n s := match n with \n  | N0 => M.remove x s\n  | Npos p => M.add x p s\n end.\n\n Definition union := M.map2 \n   (fun o o' => \n      match o,o' with \n        | None, None => None\n        | None, Some p => Some p\n        | Some p, None => Some p\n        | Some p, Some p' => Some (Pplus p p')\n      end).\n\n Definition inter := M.map2 \n   (fun o o' => \n      match o,o' with \n        | Some p, Some p' => Some (Pmin p p')\n        | _, _ => None\n      end).\n\n Definition diff := M.map2 \n   (fun o o' => \n      match o,o' with \n        | None, _ => None\n        | Some p, None => Some p\n        | Some p, Some p' => match Pcompare p p' Eq with \n            | Lt | Eq => None \n            | Gt => Some (Pminus p p')\n          end\n      end).\n\n Definition fold := @M.fold positive.\n\n Definition elements := @M.elements positive.\n\n Definition equal := M.equal Peqb.\n\n Definition subset s s' := equal (diff s s') empty.\n\n\n Definition Equal s s' := forall a : elt, multi a s = multi a s'.\n Definition Subset s s' := forall a : elt, multi a s <= multi a s'.\n Definition Empty s := forall a : elt, multi a s = 0.\n  \n Notation \"s [=] t\" := (Equal s t) (at level 70, no associativity).\n Notation \"s [<=] t\" := (Subset s t) (at level 70, no associativity).\n\n  Module F := FMapFacts.Facts(M).\n\n  Section Spec. \n\n  Variable s s' s'' : t.\n  Variable x y : elt.\n  Variable n : N.\n  Variable p : positive.\n\n  (** Specification of [empty] *)\n  Lemma empty_1 : Empty empty.\n  Proof.\n  unfold Empty, empty, multi; intros.\n  rewrite F.empty_o; auto.\n  Qed.\n\n  (** Specification of [update] *)\n  Lemma update_1 : E.eq x y -> multi y (update x n s) = n.\n  Proof.\n  unfold update, multi; intros.\n  destruct n.\n  rewrite F.remove_eq_o; auto.\n  rewrite F.add_eq_o; auto.\n  Qed.\n\n  Lemma update_2 : ~E.eq x y -> multi y (update x n s) = multi y s.\n  Proof.\n  unfold update, multi; intros.\n  destruct n.\n  rewrite F.remove_neq_o; auto.\n  rewrite F.add_neq_o; auto.\n  Qed.\n\n  (** Specification of [union] *)\n  Lemma union_1 : multi x (union s s') = multi x s + multi x s'.\n  Proof.\n  unfold union, multi; intros.\n  rewrite F.map2_1bis; auto.\n  destruct (M.find x s); destruct (M.find x s'); auto.\n  Qed.\n\n  (** Specification of [inter] *)\n  Lemma inter_1 : multi x (inter s s') = Nmin (multi x s) (multi x s').\n  Proof.\n  unfold inter, multi; intros.\n  rewrite F.map2_1bis; auto.\n  destruct (M.find x s); destruct (M.find x s'); auto.\n  unfold Nmin, Pmin, Nle.\n  simpl.\n  destruct (Pos.compare p0 p1); auto.\n  Qed.\n\n  (** Specification of [diff] *)\n  Lemma diff_1 : multi x (diff s s') = multi x s - multi x s'.\n  Proof.\n  unfold diff, multi; intros.\n  rewrite F.map2_1bis; auto.\n  destruct (M.find x s); destruct (M.find x s'); auto.\n  simpl.\n  case_eq (Pcompare p0 p1 Eq); intro H.\n  apply Pcompare_Eq_eq in H. rewrite H. now rewrite Pminus_mask_diag.\n  now rewrite (Pminus_mask_Lt p0 p1 H).\n  pose proof (Pminus_mask_Gt p0 p1 H) as H1. unfold Pminus.\n  destruct H1 as [h [H1 _]]; now rewrite H1.\n  Qed.\n\n  (** Specification of [fold] *)  \n  Lemma fold_1 : forall (A : Type) (i : A) (f : elt -> positive -> A -> A),\n      fold f s i = fold_left (fun a p => f (fst p) (snd p) a) (elements s) i.\n  Proof.\n  intros; unfold fold, elements.\n  apply M.fold_1.\n  Qed.\n\n  Definition eq_pair (p p':elt*positive) :=\n    E.eq (fst p) (fst p') /\\ (snd p) = (snd p').\n\n  Definition lt_pair (p p':elt*positive) := E.lt (fst p) (fst p').\n\n  (** Specification of [elements] *)\n  Lemma elements_1 : multi x s = Npos p -> InA eq_pair (x,p) (elements s).\n  Proof.\n  unfold multi, elements; intros.\n  apply (@M.elements_1 positive).\n  apply M.find_2.\n  destruct (M.find x s); congruence || discriminate.\n  Qed.\n\n  Lemma elements_2 : InA eq_pair (x,p) (elements s) -> multi x s = Npos p.\n  Proof.\n  unfold multi, elements; intros.\n  assert (H0:=@M.elements_2 positive _ _ _ H).\n  rewrite F.find_mapsto_iff in H0; rewrite H0; auto.\n  Qed.\n\n  Lemma elements_3 : sort lt_pair (elements s).\n  Proof.\n  apply (@M.elements_3 positive).\n  Qed.\n \n  (** Specification of [equal] *) \n  Lemma equal_1 : s[=]s' -> equal s s' = true.\n  Proof.\n  unfold equal, Equal, multi; intros.\n  apply M.equal_1.\n  unfold M.Equivb, Cmp; intros.\n  split; intros.\n  generalize (H k); clear H; intros H.\n  unfold M.In.\n  split; intros (e,He); exists e; rewrite F.find_mapsto_iff in *.\n   rewrite He in H; simpl in *.\n   destruct (M.find k s'); auto; discriminate || congruence.\n   rewrite He in H; simpl in *.\n   destruct (M.find k s); auto; discriminate || congruence.\n  rewrite F.find_mapsto_iff in *.\n  generalize (H k); clear H.\n  rewrite H0; rewrite H1; simpl.\n  inversion 1; subst; apply Peqb_correct.\n  Qed.\n\n  Lemma equal_2 : equal s s' = true ->s[=]s'.\n  Proof.\n  unfold equal, Equal, multi; intros.\n  generalize (M.equal_2 H); clear H; intros H.\n  destruct H.\n  unfold Cmp in *.\n  case_eq (M.find a s); case_eq (M.find a s'); simpl; intros; auto.\n  assert (H3:=H0 a p1 p0).\n  do 2 rewrite F.find_mapsto_iff in H3.\n  f_equal.\n  apply Peqb_complete; auto.\n  assert (M.In a s) by (exists p0; apply M.find_2; auto).\n  rewrite H in H3.\n  destruct H3; rewrite F.find_mapsto_iff in H3; congruence.\n  assert (M.In a s') by (exists p0; apply M.find_2; auto).\n  rewrite <- H in H3.\n  destruct H3; rewrite F.find_mapsto_iff in H3; congruence.\n  Qed.\n\n  End Spec.\n\n  (** Specification of [subset] *)\n  Lemma subset_1 : forall s s', s[<=]s' -> subset s s' = true.\n  Proof.\n  unfold subset, Subset; intros.\n  apply equal_1.\n  red; intros.\n  rewrite diff_1.\n  rewrite empty_1.\n  apply <- Nminus_N0_Nle; auto.\n  Qed.\n\n  Lemma subset_2 : forall s s', subset s s' = true -> s[<=]s'.\n  Proof.\n  unfold subset, Subset; intros.\n  assert (H0:=equal_2 H a).\n  rewrite diff_1 in H0.\n  rewrite empty_1 in H0.\n  apply -> Nminus_N0_Nle; auto.\n  Qed.\n\nEnd Multi.\n\n\n(* Example : A multiset on elements in type N *)\n\nModule Ma := FMapList.Make N_as_OT.\nModule Mu := Multi N_as_OT Ma.\n\nDefinition mens1 := Mu.update 2 7 (Mu.update 3 5 (Mu.empty)).\nDefinition mens2 := Mu.update 1 4 (Mu.update 3 6 (Mu.empty)).\n\nEval compute in Mu.elements (Mu.union mens1 mens2). \n\n(* Example: total multiplicity *)\n\nDefinition fmu := fun (_:Ma.key) p s => (Npos p) + s.\n\nDefinition total_multi s := Mu.fold fmu s 0.\n\nModule Import NP := FMapFacts.Properties Ma.\nImport NP.F.\nModule Import NP' := FMapFacts.OrdProperties Ma.\n\nLemma fmu_compat : Proper (eq==>eq==>eq==>eq) fmu.\nProof.\n repeat red; intros; subst; auto.\nQed.\n\nLemma fmu_transp : transpose_neqkey eq fmu.\nProof.\n red; intros.\n unfold fmu; do 2 rewrite Nplus_assoc; f_equal; apply Nplus_comm; auto.\nQed.\nHint Resolve fmu_compat fmu_transp.\n\nLemma total_multi_union:\n forall s s', total_multi (Mu.union s s') = total_multi s + total_multi s'.\nProof.\nunfold total_multi, Mu.fold.\ninduction s using map_induction; intros.\nrewrite elements_Empty in H.\nrewrite (@fold_Equal _ (Mu.union s s') s' _ (@eq N)); auto.\nrewrite (Ma.fold_1 s); rewrite H; auto.\n red; intros; unfold Mu.union; rewrite map2_1bis; auto.\n rewrite (elements_o s); rewrite H; simpl.\n destruct (Ma.find y s'); auto.\n\nreplace (Ma.fold fmu s2 0) with (fmu x e (Ma.fold fmu s1 0))\n by (symmetry; apply fold_Add; auto).\nunfold fmu at 2; simpl @snd.\nrewrite <- Nplus_assoc.\nrewrite <- IHs1.\ncase_eq (Ma.find x s'); intros.\n(* x may appear in s' hence in (Mu.union s1 s'). In this case we introduce \n   artificially (Ma.remove x (Mu.union s1 s')) and reason in two steps. *)\nset (u:=Ma.remove x (Mu.union s1 s')).\nreplace (Ma.fold fmu (Mu.union s2 s') 0) with (fmu x (Pplus e p) (Ma.fold fmu u 0)); \n [ | symmetry; apply fold_Add; auto ].\nreplace (Ma.fold fmu (Mu.union s1 s') 0) with (fmu x p (Ma.fold fmu u 0)); \n [ | symmetry; apply fold_Add; auto ].\nunfold fmu at 1 3; rewrite Nplus_assoc; f_equal.\nunfold u; apply Ma.remove_1; auto.\nunfold u, Mu.union; red; intros; rewrite add_o; rewrite remove_o.\nrewrite map2_1bis; auto.\n(* destruct (eq_dec x y); auto. ----> Not_found *)\ndestruct (P.F.eq_dec x y); auto.\ncompute in e0; subst; rewrite H1; auto.\nrewrite not_find_mapsto_iff in H; rewrite H; auto.\nunfold u; apply Ma.remove_1; auto.\nunfold u, Mu.union; red; intros; rewrite add_o; rewrite remove_o.\ndo 2 (rewrite map2_1bis; auto).\nrewrite H0; rewrite add_o.\ndestruct (P.F.eq_dec x y); auto.\ncompute in e0; subst; rewrite H1; auto.\n(* simple situation where x isn't in s' *)\nchange (Nplus (Npos e)) with (fmu x e).\napply fold_Add; auto.\nrewrite not_find_mapsto_iff; rewrite not_find_mapsto_iff in H.\nunfold Mu.union; rewrite map2_1bis; auto; rewrite H1; rewrite H; auto.\nred; intros; unfold Mu.union; rewrite add_o.\ndo 2 (rewrite map2_1bis; auto).\nrewrite H0; rewrite add_o.\ndestruct (P.F.eq_dec x y); auto.\ncompute in e0; subst; rewrite H1; auto.\nQed.\n\nLemma total_multi_update: forall s x n, \n total_multi (Mu.update x n s) + Mu.multi x s  = total_multi s + n.\nProof.\nunfold total_multi, Mu.fold.\ninduction s using map_induction; intros.\n\nrewrite elements_Empty in H.\nunfold Mu.multi.\nrewrite elements_o; rewrite H; simpl.\nunfold Mu.update; destruct n.\ndo 2 rewrite Nplus_0_r.\napply fold_Equal with (eqA:=@eq _); auto.\n red; intros; rewrite remove_o; rewrite elements_o; rewrite H; simpl.\n destruct (P.F.eq_dec x y); auto.\nrewrite Nplus_0_r; rewrite Nplus_comm.\nchange (Nplus (Npos p)) with (fmu x p).\napply fold_Add with (eqA:=@eq _); auto.\n rewrite not_find_mapsto_iff; rewrite elements_o; rewrite H; auto.\n red; auto.\n\nrename x0 into y; rename H into A1; rename H0 into A2.\nreplace (Ma.fold fmu s2 0) with (fmu x e (Ma.fold fmu s1 0)) \n by (symmetry; apply fold_Add; auto).\nunfold fmu at 2; rewrite <- Nplus_assoc. \nrewrite <- (IHs1 y n); clear IHs1; rewrite Nplus_assoc.\ndestruct (P.F.eq_dec x y) as [E|E].\n(* x=y *)\ncompute in E; subst y.\nreplace (Mu.multi x s2) with (Npos e).\nreplace (Mu.multi x s1) with 0.\nrewrite Nplus_0_r; rewrite Nplus_comm; f_equal.\napply fold_Equal with (eqA:=@eq _); eauto.\nred; intros; unfold Mu.update; destruct n.\ndo 2 rewrite remove_o; rewrite A2; rewrite add_o.\ndestruct (P.F.eq_dec x y); auto.\ndo 2 rewrite add_o; rewrite A2; rewrite add_o.\ndestruct (P.F.eq_dec x y); auto.\nunfold Mu.multi; rewrite not_find_mapsto_iff in A1; rewrite A1; auto.\nunfold Mu.multi.\nrewrite A2; rewrite add_o.\ndestruct (P.F.eq_dec x x) as [_|H]; [ auto | elim H; ME.order ].\n(* x<>y *)\nreplace (Mu.multi y s2) with (Mu.multi y s1).\nf_equal.\nchange (Nplus (Npos e)) with (fmu x e).\napply fold_Add; auto.\nrewrite not_find_mapsto_iff; rewrite not_find_mapsto_iff in A1.\nassert (y<>x) by (contradict E; auto).\ngeneralize (Mu.update_2 s1 n H).\nunfold Mu.multi; rewrite A1.\ndestruct (Ma.find x (Mu.update y n s1)); intros; discriminate || auto.\nred; intros; rewrite add_o.\nunfold Mu.update; destruct n; \n rewrite ?remove_o, ?add_o, A2, ?remove_o, ?add_o; \n destruct P.F.eq_dec; destruct P.F.eq_dec; auto; congruence.\nunfold Mu.multi; rewrite A2, add_o.\ndestruct (P.F.eq_dec x y) as [H|_]; [ elim E; auto | auto ].\nQed.\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/MultiSets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6739922926968568}}
{"text": "Require Export TopologicalSpaces.\nRequire Import WeakTopology.\n\nSection Subspace.\n\nVariable X:TopologicalSpace.\nVariable A:Ensemble X.\n\nDefinition SubspaceTopology : TopologicalSpace :=\n  WeakTopology1 (proj1_sig (P:=fun x:X => In A x)).\n\nDefinition subspace_inc :\n  SubspaceTopology -> X :=\n  proj1_sig (P:=fun x:X => In A x).\n\nLemma subspace_inc_continuous:\n  @continuous SubspaceTopology X (@proj1_sig _ _).\nProof.\napply weak_topology1_makes_continuous_func.\nQed.\n\nLemma subspace_continuous_char (Y : TopologicalSpace)\n      (f : Y -> SubspaceTopology) :\n  continuous f <->\n  continuous (compose subspace_inc f).\nProof.\n  apply weak_topology1_continuous_char.\nQed.\n\nLemma subspace_open_char: forall U:Ensemble {x: X | In A x},\n  @open SubspaceTopology U <-> exists V:Ensemble X,\n  open V /\\ U = inverse_image subspace_inc V.\nProof.\napply weak_topology1_topology.\nQed.\n\nLemma subspace_closed_char: forall U:Ensemble {x: X | In A x},\n  @closed SubspaceTopology U <-> exists V:Ensemble X,\n  closed V /\\ U = inverse_image subspace_inc V.\nProof.\napply weak_topology1_topology_closed.\nQed.\n\nLemma subspace_closure U :\n  closure U = inverse_image subspace_inc (closure (Im U subspace_inc)).\nProof.\n  apply Extensionality_Ensembles; split; red; intros.\n  - constructor.\n    apply continuous_closure.\n    { apply subspace_inc_continuous. }\n    apply Im_def.\n    assumption.\n  - destruct H.\n    unfold closure in H.\n    constructor. intros.\n    destruct H0. destruct H0.\n    rewrite subspace_closed_char in H0.\n    destruct H0 as [V []].\n    subst. constructor.\n    destruct H.\n    apply H. repeat split; try assumption.\n    intros ? ?. inversion H2; subst; clear H2.\n    apply H1. assumption.\nQed.\n\nEnd Subspace.\n\nArguments SubspaceTopology {X}.\nArguments subspace_inc {X}.\n\n(* Every set is dense in its closure. *)\nLemma dense_in_closure {X:TopologicalSpace} (A : Ensemble X) :\n  dense (inverse_image (subspace_inc (closure A)) A).\nProof.\n  apply Extensionality_Ensembles; split; red; intros.\n  { constructor. }\n  destruct x.\n  rewrite subspace_closure.\n  constructor. simpl.\n  rewrite inverse_image_image_surjective_locally.\n  { assumption. }\n  intros.\n  unshelve eexists (exist _ y _).\n  2: { reflexivity. }\n  apply closure_inflationary.\n  assumption.\nQed.\n\n(* If the subspace [F] is closed in [X], then its [subspace_inc] is a\n   closed map. *)\nLemma subspace_inc_takes_closed_to_closed\n  (X : TopologicalSpace) (F:Ensemble X) :\n  closed F ->\n  forall G:Ensemble (SubspaceTopology F),\n  closed G -> closed (Im G (subspace_inc F)).\nProof.\nintros.\nred in H0.\nrewrite subspace_open_char in H0.\ndestruct H0 as [U []].\nreplace (Im G (subspace_inc F)) with\n  (Intersection F (Complement U)).\n{ apply closed_intersection2; trivial.\n  red. now rewrite Complement_Complement. }\napply Extensionality_Ensembles; split; red; intros.\n- destruct H2.\n  exists (exist _ x H2); trivial.\n  apply NNPP. intro.\n  change (In (Complement G) (exist (In F) x H2)) in H4.\n  rewrite H1 in H4.\n  now destruct H4.\n- destruct H2 as [[y]].\n  subst y0.\n  constructor; trivial.\n  intro.\n  absurd (In (Complement G) (exist _ y i)).\n  + now intro.\n  + now rewrite H1.\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/SubspaceTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6739922877156482}}
{"text": "Require Import Arith. (* arith database for tactics *)\n\nTheorem example_for_intuition: \n  forall n p q : nat, n <= p \\/ n <= q -> n <= p \\/ n <= S q.\nProof.\n  intros n p q. intuition. (* auto with arith. will also work *)\nQed.\n\n(* intuition = intuition auto with * *)\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/intuition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938414, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6739830290722878}}
{"text": "Inductive listn : nat -> Set :=\n  | niln : listn 0\n  | consn : forall n : nat, nat -> listn n -> listn (S n).\n\nInductive empty : forall n : nat, listn n -> Prop :=\n    intro_empty : empty 0 niln.\n\nParameter\n  inv_empty : forall (n a : nat) (l : listn n), ~ empty (S n) (consn n a l).\n\nType\n  (fun (n : nat) (l : listn n) =>\n   match l in (listn n) return (empty n l \\/ ~ empty n l) with\n   | niln => or_introl (~ empty 0 niln) intro_empty\n   | consn n O y as b => or_intror (empty (S n) b) (inv_empty n 0 y)\n   | consn n a y as b => or_intror (empty (S n) b) (inv_empty n a y)\n   end).\n\n\nType\n  (fun (n : nat) (l : listn n) =>\n   match l in (listn n) return (empty n l \\/ ~ empty n l) with\n   | niln => or_introl (~ empty 0 niln) intro_empty\n   | consn n O y => or_intror (empty (S n) (consn n 0 y)) (inv_empty n 0 y)\n   | consn n a y => or_intror (empty (S n) (consn n a y)) (inv_empty n a y)\n   end).\n\n\n\nType\n  (fun (n : nat) (l : listn n) =>\n   match l in (listn n) return (empty n l \\/ ~ empty n l) with\n   | niln => or_introl (~ empty 0 niln) intro_empty\n   | consn O a y as b => or_intror (empty 1 b) (inv_empty 0 a y)\n   | consn n a y as b => or_intror (empty (S n) b) (inv_empty n a y)\n   end).\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/ideal-features/Case8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6739830215447643}}
{"text": "Require Export XR_INR.\nRequire Export XR_IZR.\n\nLocal Open Scope R_scope.\n\nLemma INR_IZR_INZ : forall n:nat, INR n = IZR (Z.of_nat n).\nProof.\n  intro n.\n  induction n as [ | n hin ].\n  {\n    simpl.\n    reflexivity.\n  }\n  {\n    simpl.\n    rewrite SuccNat2Pos.id_succ.\n    reflexivity.\n  }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_INR_IZR_INZ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.6739623222125507}}
{"text": "Require Import Utf8.\nRequire Import Coq.Program.Basics Setoid RelationClasses ProofIrrelevance FunctionalExtensionality.\n\n(* Note : Remember to use eq_rect for equality between morphisms\n  if necessary *)\nImport EqNotations.\n\n(* identity is unique, not sure if composition is, so I'll leave it as a parameter *)\n\nClass Category \n  (obj : Type) \n  (hom : obj -> obj -> Type)\n  (comp : forall {A B C} (f : hom B C) (g : hom A B), hom A C) := {\n  cid : forall A, hom A A;\n  \n  idLeft: forall {A B} (f: hom A B), comp (cid B) f = f;\n  idRight: forall {A B} (f : hom B A), comp f (cid B) = f;\n  compAssoc: forall {A B C D} (f : hom A B) (g : hom B C) (h : hom C D),\n    comp h (comp g f) = comp (comp h g) f\n}.\n\nGeneralizable Variables obj hom comp.\n\nDefinition homOp `{Category} := hom.\nDefinition compOp `{Category obj hom comp} := comp.\n\nNotation \"a --> b\" := (homOp a b).\nNotation \"1\" := (cid _).\nNotation \"f '•' g\" := (compOp _ _ _ f g) (at level 50).\n\n(*** Dualization *)\nInstance Dual `(Category obj hom comp) : Category obj (fun A B => B --> A)\n  (fun {A B C} f g => comp _ _ _ g f):= {}.\nProof.\n  - intros. apply 1.\n  - intros A B f. simpl. apply idRight.\n  - intros A B f. apply idLeft.\n  - intros A B C D f g h. simpl. rewrite compAssoc. reflexivity.\nDefined.\n\n(* If we don't remove this typclass instance search might not terminate *)\nRemove Hints Dual : typeclass_instances.\n\nNotation \"C ¯\" := (Dual C) (at level 20, left associativity).\n\n(** EXAMPLES **)\n\nInstance Category_Set : Category Type (fun A B => A -> B)\n  (fun A B C f g => compose f g) := {}.\n  - intros. apply X.\n  - intros. reflexivity.\n  - intros. reflexivity.\n  - intros. unfold compose. reflexivity.\nDefined.\n\nClass Poset {A : Type} (R : relation A) := {\n  Poset_Reflexive :> Reflexive R;\n  Poset_Transitive :> Transitive R;\n  Poset_Antisymmetric :> Antisymmetric A eq R;\n}.\n\nInstance Category_Poset (A : Type) (lt : relation A) (P : Poset lt) : Category A \n  (fun (a1 a2 : A) => lt a1 a2)\n  (fun (a1 a2 a3 : A) p1 p2 => @transitivity A lt (Poset_Transitive) a1 a2 a3 p2 p1)\n  := {}.\n  - apply reflexivity.\n  - intros; apply proof_irrelevance.\n  - intros; apply proof_irrelevance.\n  - intros; apply proof_irrelevance.\nDefined.", "meta": {"author": "mirithering", "repo": "coq", "sha": "bff4429c146a998a416f3c177b772b0fefd92d46", "save_path": "github-repos/coq/mirithering-coq", "path": "github-repos/coq/mirithering-coq/coq-bff4429c146a998a416f3c177b772b0fefd92d46/Category/Category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.673962306895683}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_betweennotequal.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_localextension.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_congruencesymmetric.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_betweennesspreserved : \n   forall A B C a b c, \n   Cong A B a b -> Cong A C a c -> Cong B C b c -> BetS A B C ->\n   BetS a b c.\nProof.\nintros.\nassert (neq A B) by (forward_using lemma_betweennotequal).\nassert (neq a b) by (conclude axiom_nocollapse).\nassert (neq B C) by (forward_using lemma_betweennotequal).\nassert (neq b c) by (conclude axiom_nocollapse).\nlet Tf:=fresh in\nassert (Tf:exists d, (BetS a b d /\\ Cong b d b c)) by (conclude lemma_localextension);destruct Tf as [d];spliter.\nassert (Cong b c b d) by (conclude lemma_congruencesymmetric).\nassert (Cong b c B C) by (conclude lemma_congruencesymmetric).\nassert (Cong b d B C) by (conclude cn_congruencetransitive).\nassert (Cong B C b d) by (conclude lemma_congruencesymmetric).\nassert (Cong C C c d) by (conclude axiom_5_line).\nassert (Cong c d C C) by (conclude lemma_congruencesymmetric).\nassert (~ neq c d).\n {\n intro.\n assert (neq C C) by (conclude axiom_nocollapse).\n assert (eq C C) by (conclude cn_equalityreflexive).\n contradict.\n }\nassert (BetS a b c) by (conclude cn_equalitysub).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_betweennesspreserved.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6739467953561064}}
{"text": "(* --------------------------------------------------------------------\n * (c) Copyright 2014--2015 IMDEA Software Institute.\n *\n * You may distribute this file under the terms of the CeCILL-B license\n * -------------------------------------------------------------------- *)\n\n(* -------------------------------------------------------------------------- *)\n(* This file provides a library for multivariate polynomials over ring        *)\n(* structures; it also provides an extended theory for polynomials            *)\n(* whose coefficients range over commutative rings and integral domains.      *)\n(*                                                                            *)\n(*          'X_{1..n} == the type of monomials in n variables. m : 'X_{1..n}  *)\n(*                       acts as a function from 'I_n to nat, returning the   *)\n(*                       power of the i-th variable in m. Notations related   *)\n(*                       to 'X_{1..n} lies in the multi_scope scope,          *)\n(*                       delimited by %MM                                     *)\n(* [multinom E i | i < n]                                                     *)\n(*                    == the monomial in n variables whose i-th power is E(i) *)\n(*             mdeg m == the degree of the monomial m; i.e.                   *)\n(*                         mdeg m = \\sum_(i < n) (m i)                        *)\n(*      'X_{1..n < k} == the finite type of monomials in n variables with     *)\n(*                       degree bounded by k.                                 *)\n(*      (m1 <= m2)%MM == the point-wise partial order over monomials, i.e.    *)\n(*                         (m1 <= m2)%MM <=> forall i, m1 i <= m2 i           *)\n(*       (m1 <= m2)%O == the total cpo (equipped with a cpoType) over         *)\n(*                       monomials. This is the degrevlex monomial ordering.  *)\n(* 0, 'U_i, m1 + m2,  == 'X_{1..n} is equipped with a semi-group structure,   *)\n(* m1 - m2, m *+ n, ...  all operations being point-wise. The substraction    *)\n(*                       is truncated when (m1 <= m2)%MM does not hold.       *)\n(*      mlcm m1 m2    == the monomial that is the least common multiple       *)\n(*       {mpoly R[n]} == the type of multivariate polynomials in n variables  *)\n(*                       and with coefficients of type R represented as       *)\n(*                       {free 'X_{1..n} / R}, i.e. as a formal sum over      *)\n(*                       'X_{1..n} and with coefficients in R.                *)\n(*          [mpoly D] == the multivariate polynomial constructed from a free  *)\n(*                       sum in {freeg 'X_{1..n} / R}                         *)\n(*  0, 1, - p, p + q, == the usual ring operations: {mpoly R} has a canonical *)\n(* p * q, p ^+ n, ...    ringType structure, which is commutative / integral  *)\n(*                       when R is commutative / integral, respectively.      *)\n(*       {ipoly R[n]} == the type obtained by iterating the univariate        *)\n(*                       polynomial type, with R as base ring.                *)\n(*     {ipoly R[n]}^p == copy of {ipoly R[n]} with a ring canonical structure *)\n(*           mwiden p == the canonical injection (ring morphism) from         *)\n(*                       {mpoly R[n]} to {mpoly R[n.+1]}                      *)\n(*    mpolyC c, c%:MP == the constant multivariate polynomial c               *)\n(*               'X_i == the variable i, for i : 'I_n                         *)\n(*             'X_[m] == the monomial m as a multivariate polynomial          *)\n(*            msupp p == the support of p, i.e. the m s.t. p@_m != 0          *)\n(*               p@_m == the coefficient of 'X_[m] in p.                      *)\n(*            msize p == 1 + the degree of p, or 0 if p = 0.                  *)\n(*            mlead p == the leading monomial of p; this is the maximum       *)\n(*                       monomial of p for the degrevlex monimial ordering.   *)\n(*                       mlead p defaults to 0%MM when p is 0.                *)\n(*            mlast p == the smallest non-zero monomial of p for the          *)\n(*                         degrevlex monimial ordering.                       *)\n(*                       mlast p defaults to 0%MM when p is 0.                *)\n(*           mleadc p == the coefficient of the highest monomial in p;        *)\n(*                       this is a notation for p@_(mlead p).                 *)\n(* p \\is a mpolyOver 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, where *)\n(*                       v is a n.-tuple R s.t. 'X_i evaluates to (tnth v i)  *)\n(*             p^`M() == formal derivative of p w.r.t the i-th variable       *)\n(*         p^`M(n, i) == formal n-derivative of p w.r.t the i-th variable     *)\n(*            p^`M[m] == formal parallel (m i)-derivative of p w.r.t the      *)\n(*                       i-th variable, i ranging in {0..n.-1}.               *)\n(*          p \\mPo lq == multivariate polynomial composition, where lq is a   *)\n(*                       (n.-tuple {mpoly R[k]}) s.t. 'X_i is substituted by  *)\n(*                       (tnth lq i).                                         *)\n(*      map_mpoly f p == the image of the polynomial by the function f (which *)\n(*                       is usually a ring morphism).                         *)\n(*    p \\is symmetric == p is a symmetric polynomial.                         *)\n(*          's_(n, k) == the k-th elementary symmetric polynomial with        *)\n(*                       n indeterminates. We prove the fundamental lemma of  *)\n(*                       symmetric polynomials.                               *)\n(*     p \\is d.-homog == p is a homogeneous polynomial of degree d.           *)\n(* -------------------------------------------------------------------------- *)\n\n(* -------------------------------------------------------------------- *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq path.\nFrom mathcomp Require Import choice fintype tuple finfun bigop finset binomial.\nFrom mathcomp Require Import order fingroup perm ssralg zmodp poly ssrint.\nFrom mathcomp Require Import matrix vector.\nFrom mathcomp Require Import bigenough.\n\nRequire Import ssrcomplements freeg.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport Order.Theory GRing.Theory BigEnough.\n\nLocal Open Scope ring_scope.\n\nDeclare Scope mpoly_scope.\nDeclare Scope multi_scope.\n\nDelimit Scope mpoly_scope with MP.\nDelimit Scope multi_scope with MM.\n\nLocal Notation simpm := Monoid.simpm.\n\nLocal Infix \"@@\" := (allpairs pair) (at level 60, right associativity).\n\nLocal Notation widen := (widen_ord (leqnSn _)).\n\nImport Order.DefaultProdLexiOrder.\nImport Order.DefaultSeqLexiOrder.\nImport Order.DefaultTupleLexiOrder.\n\n(* -------------------------------------------------------------------- *)\nReserved Notation \"''X_{1..' n '}'\"\n  (at level 0, n at level 2).\nReserved Notation \"''X_{1..' n  < b '}'\"\n  (at level 0, n, b at level 2).\nReserved Notation \"''X_{1..' n  < b1 , b2 '}'\"\n  (at level 0, n, b1, b2 at level 2).\nReserved Notation \"[ 'multinom' s ]\"\n  (at level 0, format \"[ 'multinom'  s ]\").\nReserved Notation \"[ 'multinom' 'of' s ]\"\n  (at level 0, format \"[ 'multinom'  'of'  s ]\").\nReserved Notation \"[ 'multinom' F | i < n ]\"\n  (at level 0, i at level 0,\n     format \"[ '[hv' 'multinom'  F '/'  |  i  <  n ] ']'\").\nReserved Notation \"'U_(' n )\"\n  (at level 0, n at level 2, no associativity, format \"'U_(' n )\").\nReserved Notation \"{ 'mpoly' T [ n ] }\"\n  (at level 0, T, n at level 2, format \"{ 'mpoly'  T [ n ] }\").\nReserved Notation \"[ 'mpoly' D ]\"\n  (at level 0, D at level 2, format \"[ 'mpoly'  D ]\").\nReserved Notation \"{ 'ipoly' T [ n ] }\"\n  (at level 0, T, n at level 2, format \"{ 'ipoly'  T [ n ] }\").\nReserved Notation \"{ 'ipoly' T [ n ] }^p\"\n  (at level 0, T, n at level 2, format \"{ 'ipoly'  T [ n ] }^p\").\nReserved Notation \"''X_' i\"\n  (at level 8, i at level 2, format \"''X_' i\").\nReserved Notation \"''X_[' i ]\"\n  (at level 8, i at level 2, format \"''X_[' i ]\").\nReserved Notation \"''X_[' R , i ]\"\n  (at level 8, R, i at level 2, format \"''X_[' R ,  i ]\").\nReserved Notation \"c %:MP\"\n  (at level 2, left associativity, format \"c %:MP\").\nReserved Notation \"c %:MP_[ n ]\"\n  (at level 2, left associativity, n at level 50, format \"c %:MP_[ n ]\").\nReserved Notation \"c %:IP\"\n  (at level 2, left associativity, format \"c %:IP\").\nReserved Notation \"s @_ i\"\n   (at level 3, i at level 2, left associativity, format \"s @_ i\").\nReserved Notation \"e .@[ x ]\"\n  (at level 2, left associativity, format \"e .@[ x ]\").\nReserved Notation \"e .@[< x >]\"\n  (at level 2, left associativity, format \"e .@[< x >]\").\nReserved Notation \"p \\mPo q\"\n  (at level 50).\nReserved Notation \"x ^[ f ]\"\n   (at level 2, left associativity, format \"x ^[ f ]\").\nReserved Notation \"x ^[ f , g ]\"\n   (at level 2, left associativity, format \"x ^[ f , g ]\").\nReserved Notation \"p ^`M ( m )\"\n   (at level 8, format \"p ^`M ( m )\").\nReserved Notation \"p ^`M ( m , n )\"\n   (at level 8, format \"p ^`M ( m ,  n )\").\nReserved Notation \"p ^`M [ m ]\"\n   (at level 8, format \"p ^`M [ m ]\").\nReserved Notation \"''s_' k\"\n  (at level 8, k at level 2, format \"''s_' k\").\nReserved Notation \"''s_' ( n , k )\"\n  (at level 8, n, k at level 2, format \"''s_' ( n ,  k )\").\nReserved Notation \"''s_' ( K , n , k )\"\n  (at level 8, n, k, K at level 2, format \"''s_' ( K ,  n ,  k )\").\nReserved Notation \"+%MM\"\n  (at level 0).\nReserved Notation \"-%MM\"\n  (at level 0).\n\n(* -------------------------------------------------------------------- *)\nSection MultinomDef.\nContext (n : nat).\n\nRecord multinom : predArgType := Multinom { multinom_val :> n.-tuple nat }.\n\nCanonical multinom_subType := Eval hnf in [newType for multinom_val].\n\nDefinition fun_of_multinom M (i : 'I_n) := tnth (multinom_val M) i.\n\nCoercion fun_of_multinom : multinom >-> Funclass.\n\nLemma multinomE M : Multinom M =1 tnth M.\nProof. by []. Qed.\n\nEnd MultinomDef.\n\nNotation \"[ 'multinom' s ]\" := (@Multinom _ s) : form_scope.\nNotation \"[ 'multinom' 'of'  s ]\" := [multinom [tuple of s]] : form_scope.\nNotation \"[ 'multinom' E | i < n ]\" :=\n  [multinom [tuple E%N | i < n]] : form_scope.\nNotation \"[ 'multinom' E | i < n ]\" :=\n  [multinom [tuple E%N : nat | i < n]] (only parsing) : form_scope.\n\n(* -------------------------------------------------------------------- *)\nNotation \"''X_{1..' n '}'\" := (multinom n) : type_scope.\n\nDefinition multinom_eqMixin n :=\n  Eval hnf in [eqMixin of 'X_{1..n} by <:].\nCanonical multinom_eqType n :=\n  Eval hnf in EqType 'X_{1..n} (multinom_eqMixin n).\nDefinition multinom_choiceMixin n :=\n  [choiceMixin of 'X_{1..n} by <:].\nCanonical multinom_choiceType n :=\n  Eval hnf in ChoiceType 'X_{1..n} (multinom_choiceMixin n).\nDefinition multinom_countMixin n :=\n  [countMixin of 'X_{1..n} by <:].\nCanonical multinom_countType n :=\n  Eval hnf in CountType 'X_{1..n} (multinom_countMixin n).\nCanonical multinom_subCountType n :=\n  Eval hnf in [subCountType of 'X_{1..n}].\n\nBind Scope multi_scope with multinom.\n\n(* -------------------------------------------------------------------- *)\nDefinition lem n (m1 m2 : 'X_{1..n}) :=\n  [forall i, m1%MM i <= m2%MM i].\n\nDefinition ltm n (m1 m2 : 'X_{1..n}) :=\n  (m1 != m2) && (lem m1 m2).\n\n(* -------------------------------------------------------------------- *)\nSection MultinomTheory.\nContext {n : nat}.\nImplicit Types (m : 'X_{1..n}).\n\nLemma mnm_tnth m j : m j = tnth m j.\nProof. by []. Qed.\n\nLemma mnm_nth x0 m j : m j = nth x0 m j.\nProof. by rewrite mnm_tnth (tnth_nth x0). Qed.\n\nLemma mnmE E j : [multinom E i | i < n] j = E j.\nProof. by rewrite multinomE tnth_mktuple. Qed.\n\nLemma mnm_valK t : [multinom t] = t :> n.-tuple nat.\nProof. by []. Qed.\n\nLemma mnmP m1 m2 : (m1 = m2) <-> (m1 =1 m2).\nProof.\ncase: m1 m2 => [m1] [m2] /=; split => [->//|h].\nby apply/val_inj/eq_from_tnth => i; rewrite -!multinomE.\nQed.\n\nEnd MultinomTheory.\n\n(* -------------------------------------------------------------------- *)\nSection MultinomMonoid.\nContext {n : nat}.\nImplicit Types (m : 'X_{1..n}).\n\nDefinition mnm0 := [multinom 0 | _ < n].\nDefinition mnm1 (c : 'I_n) := [multinom c == i | i < n].\nDefinition mnm_add m1 m2 := [multinom m1 i + m2 i | i < n].\nDefinition mnm_sub m1 m2 := [multinom m1 i - m2 i | i < n].\nDefinition mnm_muln m i := nosimpl iterop _ i mnm_add m mnm0.\n\nLocal Notation \"0\"         := mnm0 : multi_scope.\nLocal Notation \"'U_(' n )\" := (mnm1 n) : multi_scope.\nLocal Notation \"m1 + m2\"   := (mnm_add m1 m2) : multi_scope.\nLocal Notation \"m1 - m2\"   := (mnm_sub m1 m2) : multi_scope.\nLocal Notation \"x *+ n\"    := (mnm_muln x n) : multi_scope.\n\nLocal Notation \"+%MM\" := (@mnm_add) : fun_scope.\nLocal Notation \"-%MM\" := (@mnm_sub) : fun_scope.\n\nLocal Notation \"m1 <= m2\" := (lem m1 m2) : multi_scope.\nLocal Notation \"m1 < m2\"  := (ltm m1 m2) : multi_scope.\n\nLemma mnm0E i : 0%MM i = 0%N. Proof. exact/mnmE. Qed.\n\nLemma mnmDE i m1 m2 : (m1 + m2)%MM i = (m1 i + m2 i)%N. Proof. exact/mnmE. Qed.\n\nLemma mnmBE i m1 m2 : (m1 - m2)%MM i = (m1 i - m2 i)%N. Proof. exact/mnmE. Qed.\n\nLemma mnm_sumE (I : Type) i (r : seq I) P F :\n  (\\big[+%MM/0%MM]_(x <- r | P x) (F x)) i = (\\sum_(x <- r | P x) (F x i))%N.\nProof. by apply/(big_morph (fun m => m i)) => [x y|]; rewrite mnmE. Qed.\n\n(*-------------------------------------------------------------------- *)\nLemma mnm_lepP {m1 m2} : reflect (forall i, m1 i <= m2 i) (m1 <= m2)%MM.\nProof. exact: (iffP forallP). Qed.\n\nLemma lepm_refl m : (m <= m)%MM. Proof. exact/mnm_lepP. Qed.\n\nLemma lepm_trans m3 m1 m2 : (m1 <= m2 -> m2 <= m3 -> m1 <= m3)%MM.\nProof.\nmove=> h1 h2; apply/mnm_lepP => i.\nexact: leq_trans (mnm_lepP h1 i) (mnm_lepP h2 i).\nQed.\n\nLemma addmC : commutative +%MM.\nProof. by move=> m1 m2; apply/mnmP=> i; rewrite !mnmE addnC. Qed.\n\nLemma addmA : associative +%MM.\nProof. by move=> m1 m2 m3; apply/mnmP=> i; rewrite !mnmE addnA. Qed.\n\nLemma add0m : left_id 0%MM +%MM.\nProof. by move=> m; apply/mnmP=> i; rewrite !mnmE add0n. Qed.\n\nLemma addm0 : right_id 0%MM +%MM.\nProof. by move=> m; rewrite addmC add0m. Qed.\n\nCanonical mnm_monoid := Monoid.Law addmA add0m addm0.\nCanonical mnm_comoid := Monoid.ComLaw addmC.\n\nLemma subm0 m : (m - 0)%MM = m.\nProof. by apply/mnmP=> i; rewrite !mnmE subn0. Qed.\n\nLemma sub0m m : (0 - m = 0)%MM.\nProof. by apply/mnmP=> i; rewrite !mnmE sub0n. Qed.\n\nLemma addmK m : cancel (+%MM^~ m) (-%MM^~ m).\nProof. by move=> m' /=; apply/mnmP=> i; rewrite !mnmE addnK. Qed.\n\nLemma addIm : left_injective +%MM.\nProof. by move=> ? ? ? /(can_inj (@addmK _)). Qed.\n\nLemma addmI : right_injective +%MM.\nProof. by move=> m ? ?; rewrite ![(m + _)%MM]addmC => /addIm. Qed.\n\nLemma eqm_add2l m n1 n2 : (m + n1 == m + n2)%MM = (n1 == n2).\nProof. exact/inj_eq/addmI. Qed.\n\nLemma eqm_add2r m n1 n2 : (n1 + m == n2 + m)%MM = (n1 == n2).\nProof. exact: (inj_eq (@addIm _)). Qed.\n\nLemma submK m m' : (m <= m')%MM -> (m' - m + m = m')%MM.\nProof. by move/mnm_lepP=> h; apply/mnmP=> i; rewrite !mnmE subnK. Qed.\n\nLemma addmBA m1 m2 m3 :\n  (m3 <= m2)%MM -> (m1 + (m2 - m3))%MM = (m1 + m2 - m3)%MM.\nProof. by move/mnm_lepP=> h; apply/mnmP=> i; rewrite !mnmE addnBA. Qed.\n\nLemma submDA m1 m2 m3 : (m1 - m2 - m3)%MM = (m1 - (m2 + m3))%MM.\nProof. by apply/mnmP=> i; rewrite !mnmE subnDA. Qed.\n\nLemma submBA m1 m2 m3 : (m3 <= m2)%MM -> (m1 - (m2 - m3) = m1 + m3 - m2)%MM.\nProof. by move/mnm_lepP=> h; apply/mnmP=> i; rewrite !mnmE subnBA. Qed.\n\nLemma lem_subr m1 m2 : (m1 - m2 <= m1)%MM.\nProof. by apply/mnm_lepP=> i; rewrite !mnmE leq_subr. Qed.\n\nLemma lem_addr m1 m2 : (m1 <= m1 + m2)%MM.\nProof. by apply/mnm_lepP=> i; rewrite mnmDE leq_addr. Qed.\n\nLemma lem_addl m1 m2 : (m2 <= m1 + m2)%MM.\nProof. by apply/mnm_lepP=> i; rewrite mnmDE leq_addl. Qed.\n\n(* -------------------------------------------------------------------- *)\nLemma mulm0n m : (m *+ 0 = 0)%MM.\nProof. by []. Qed.\n\nLemma mulm1n m : (m *+ 1 = m)%MM.\nProof. by []. Qed.\n\nLemma mulmS m i : (m *+ i.+1 = m + m *+ i)%MM.\nProof. by rewrite /mnm_muln !Monoid.iteropE iterS. Qed.\n\nLemma mulmSr m i : (m *+ i.+1 = m *+ i + m)%MM.\nProof. by rewrite mulmS addmC. Qed.\n\nLemma mulmnE m k i : ((m *+ k) i)%MM = (m i * k)%N.\nProof.\nelim: k => [|k ih]; first by rewrite muln0 mulm0n !mnmE.\nby rewrite mulmS mulnS mnmDE ih.\nQed.\n\nLemma mnm1E i j : U_(i)%MM j = (i == j). Proof. exact/mnmE. Qed.\n\nLemma lep1mP i m : (U_(i) <= m)%MM = (m i != 0%N).\nProof.\napply/mnm_lepP/idP=> [/(_ i)|]; rewrite -lt0n; first by rewrite mnm1E eqxx.\nby move=> lt0_mi j; rewrite mnm1E; case: eqP=> // <-.\nQed.\n\nEnd MultinomMonoid.\n\n(* -------------------------------------------------------------------- *)\nNotation \"+%MM\" := (@mnm_add _).\nNotation \"-%MM\" := (@mnm_sub _).\n\nNotation \"0\"         := (@mnm0 _) : multi_scope.\nNotation \"'U_(' n )\" := (mnm1 n) : multi_scope.\nNotation \"m1 + m2\"   := (mnm_add m1 m2) : multi_scope.\nNotation \"m1 - m2\"   := (mnm_sub m1 m2) : multi_scope.\nNotation \"x *+ n\"    := (mnm_muln x n) : multi_scope.\n\nNotation \"m1 <= m2\" := (lem m1 m2) : multi_scope.\nNotation \"m1 < m2\"  := (ltm m1 m2) : multi_scope.\n\nNotation \"\\sum_ ( i <- r | P ) F\" :=\n  (\\big[+%MM/0%MM]_(i <- r | P%B) F%MM) : multi_scope.\nNotation \"\\sum_ ( i <- r ) F\" :=\n  (\\big[+%MM/0%MM]_(i <- r) F%MM) : multi_scope.\nNotation \"\\sum_ ( m <= i < n | P ) F\" :=\n  (\\big[+%MM/0%MM]_(m <= i < n | P%B) F%MM) : multi_scope.\nNotation \"\\sum_ ( m <= i < n ) F\" :=\n  (\\big[+%MM/0%MM]_(m <= i < n) F%MM) : multi_scope.\nNotation \"\\sum_ ( i | P ) F\" :=\n  (\\big[+%MM/0%MM]_(i | P%B) F%MM) : multi_scope.\nNotation \"\\sum_ i F\" :=\n  (\\big[+%MM/0%MM]_i F%MM) : multi_scope.\nNotation \"\\sum_ ( i : t | P ) F\" :=\n  (\\big[+%MM/0%MM]_(i : t | P%B) F%MM) (only parsing) : multi_scope.\nNotation \"\\sum_ ( i : t ) F\" :=\n  (\\big[+%MM/0%MM]_(i : t) F%MM) (only parsing) : multi_scope.\nNotation \"\\sum_ ( i < n | P ) F\" :=\n  (\\big[+%MM/0%MM]_(i < n | P%B) F%MM) : multi_scope.\nNotation \"\\sum_ ( i < n ) F\" :=\n  (\\big[+%MM/0%MM]_(i < n) F%MM) : multi_scope.\nNotation \"\\sum_ ( i 'in' A | P ) F\" :=\n  (\\big[+%MM/0%MM]_(i in A | P%B) F%MM) : multi_scope.\nNotation \"\\sum_ ( i 'in' A ) F\" :=\n  (\\big[+%MM/0%MM]_(i in A) F%MM) : multi_scope.\n\n(* -------------------------------------------------------------------- *)\nLemma multinomUE_id n (m : 'X_{1..n}) : m = (\\sum_i U_(i) *+ m i)%MM.\nProof.\napply/mnmP=> i; rewrite mnm_sumE (bigD1 i) //=.\nrewrite big1; first by rewrite addn0 mulmnE mnm1E eqxx mul1n.\nby move=> j ne_ji; rewrite mulmnE mnm1E (negbTE ne_ji).\nQed.\n\nLemma multinomUE n (s : 'S_n) (m : 'X_{1..n}) :\n  m = (\\sum_i U_(s i) *+ m (s i))%MM.\nProof.\nrewrite (reindex s^-1)%g //=; last first.\n  by exists s=> i _; rewrite (permK, permKV).\nby rewrite [LHS]multinomUE_id; apply/eq_bigr => i _; rewrite permKV.\nQed.\n\n(* -------------------------------------------------------------------- *)\nSection MultinomDeg.\nContext {n : nat}.\nImplicit Types (m : 'X_{1..n}).\n\nDefinition mdeg m := (\\sum_(i <- m) i)%N.\n\nLemma mdegE m : mdeg m = (\\sum_i (m i))%N.\nProof. exact: big_tuple. Qed.\n\nLemma mdeg0 : mdeg 0%MM = 0%N.\nProof. by rewrite mdegE big1 // => i; rewrite mnmE. Qed.\n\nLemma mdeg1 i : mdeg U_(i) = 1%N.\nProof.\nrewrite mdegE (bigD1 i) //= big1 => [|j]; first by rewrite mnmE eqxx addn0.\nby rewrite mnmE eq_sym => /negbTE ->.\nQed.\n\nLemma mdegD m1 m2 : mdeg (m1 + m2) = (mdeg m1 + mdeg m2)%N.\nProof. by rewrite !mdegE -big_split; apply/eq_bigr => i _; rewrite mnmE. Qed.\n\nLemma mdegB m1 m2 : mdeg (m1 - m2) <= mdeg m1.\nProof. by rewrite !mdegE; apply/leq_sum => i _; rewrite mnmE leq_subr.  Qed.\n\nLemma mdegMn m k : mdeg (m *+ k) = (mdeg m * k)%N.\nProof. by rewrite !mdegE big_distrl; apply/eq_bigr => i _; rewrite mulmnE. Qed.\n\nLemma mdeg_sum (I : Type) (r : seq I) P F :\n  mdeg (\\sum_(x <- r | P x) F x) = (\\sum_(x <- r | P x) mdeg (F x))%N.\nProof. exact/big_morph/mdeg0/mdegD. Qed.\n\nLemma mdeg_eq0 m : (mdeg m == 0%N) = (m == 0%MM).\nProof.\napply/idP/eqP=> [h|->]; last by rewrite mdeg0.\napply/mnmP=> i; move: h; rewrite mdegE mnm0E.\nby rewrite (bigD1 i) //= addn_eq0 => /andP[/eqP-> _].\nQed.\n\nLemma mnmD_eq0 m1 m2 : (m1 + m2 == 0)%MM = (m1 == 0%MM) && (m2 == 0%MM).\nProof. by rewrite -!mdeg_eq0 mdegD addn_eq0. Qed.\n\nLemma mnm1_eq0 i : (U_(i) == 0 :> 'X_{1..n})%MM = false.\nProof. by rewrite -mdeg_eq0 mdeg1. Qed.\n\nLemma eq_mnm1 (i j : 'I_n) : (U_(i)%MM == U_(j)%MM) = (i == j).\nProof.\nby apply/eqP/eqP => [/mnmP /(_ j)|->//]; rewrite !mnm1E eqxx; case: eqP.\nQed.\n\nLemma mdeg_eq1 m : (mdeg m == 1%N) = [exists i : 'I_n, m == U_(i)%MM].\nProof.\napply/eqP/idP=> [|/existsP[i /eqP ->]]; last by rewrite mdeg1.\nrewrite [m]multinomUE_id => Hmdeg.\nhave: [exists i, m i != 0%N].\n  rewrite -negb_forall; apply/contra_eqN: Hmdeg => /forallP Hm0.\n  by rewrite big1 ?mdeg0 //= => i _; rewrite (eqP (Hm0 i)).\ncase/existsP => i Hi; apply/existsP; exists i; move: Hmdeg.\nrewrite (bigD1 i) //= mdegD mdegMn mdeg1 mul1n.\ncase: (m i) Hi => [|[|]] //= _ [] /eqP; rewrite mdeg_eq0 => /eqP ->.\nby rewrite mulm1n addm0.\nQed.\n\nLemma mdeg1P m : reflect (exists i, m == U_(i)%MM) (mdeg m == 1%N).\nProof. by rewrite mdeg_eq1; apply/existsP. Qed.\n\nEnd MultinomDeg.\n\n(* -------------------------------------------------------------------- *)\nSection MultinomOrder.\nContext {n : nat}.\nImplicit Types (m : 'X_{1..n}).\n\nDefinition mnmc_le m1 m2 := (mdeg m1 :: m1 <= mdeg m2 :: m2)%O.\n\nDefinition mnmc_lt m1 m2 := (mdeg m1 :: m1 < mdeg m2 :: m2)%O.\n\nLocal Lemma lemc_refl : reflexive mnmc_le.\nProof. by move=> m; apply/le_refl. Qed.\n\nLocal Lemma lemc_anti : antisymmetric mnmc_le.\nProof. by move=> m1 m2 /le_anti [_] /val_inj/val_inj. Qed.\n\nLocal Lemma lemc_trans : transitive mnmc_le.\nProof. by move=> m2 m1 m3; apply/le_trans. Qed.\n\nLemma lemc_total : total mnmc_le.\nProof. by move=> m1 m2; apply/le_total. Qed.\n\nLocal Lemma ltmc_def m1 m2 : mnmc_lt m1 m2 = (m2 != m1) && mnmc_le m1 m2.\nProof.\napply/esym; rewrite andbC /mnmc_lt /mnmc_le lt_def lexi_cons eqseq_cons.\nby case: ltgtP; rewrite //= 1?andbC //; apply/contra_ltN => /eqP ->.\nQed.\n\nDefinition multinom_porderMixin :=\n  LePOrderMixin ltmc_def lemc_refl lemc_anti lemc_trans.\n\nCanonical multinom_porderType :=\n  Eval hnf in POrderType tt 'X_{1..n} multinom_porderMixin.\n\nLemma leEmnm m1 m2 : (m1 <= m2)%O = (mdeg m1 :: val m1 <= mdeg m2 :: val m2)%O.\nProof. by []. Qed.\n\nLemma ltEmnm m m' : (m < m')%O = (mdeg m :: m < mdeg m' :: m')%O.\nProof. by []. Qed.\n\nDefinition multinom_latticeMixin : totalPOrderMixin _ := lemc_total.\nCanonical multinom_latticeType :=\n  Eval hnf in LatticeType 'X_{1..n} multinom_latticeMixin.\nCanonical multinom_distrLatticeType :=\n  Eval hnf in DistrLatticeType 'X_{1..n} multinom_latticeMixin.\n\nCanonical multinom_orderType := OrderType 'X_{1..n} lemc_total.\n\nLemma le0m m : (0%MM <= m)%O.\nProof.\nrewrite leEmnm; have [/eqP|] := eqVneq (mdeg m) 0%N.\n  by rewrite mdeg_eq0 => /eqP->; rewrite lexx.\nby rewrite -lt0n mdeg0 lexi_cons leEnat; case: ltngtP.\nQed.\n\nDefinition multinom_blatticeMixin := Order.BottomMixin.Build le0m.\nCanonical multinom_blatticeType :=\n  Eval hnf in BLatticeType 'X_{1..n} multinom_blatticeMixin.\nCanonical multinom_bDistrLatticeType :=\n  [bDistrLatticeType of 'X_{1..n}].\n\nLemma ltmcP m1 m2 : mdeg m1 = mdeg m2 -> reflect\n  (exists2 i : 'I_n, forall (j : 'I_n), j < i -> m1 j = m2 j & m1 i < m2 i)\n  (m1 < m2)%O.\nProof.\nby move=> eq_mdeg; rewrite ltEmnm eq_mdeg eqhead_ltxiE; apply: ltxi_tuplePlt.\nQed.\n\nLemma lemc_mdeg m1 m2 : (m1 <= m2)%O -> mdeg m1 <= mdeg m2.\nProof. by rewrite leEmnm lexi_cons leEnat; case: ltngtP. Qed.\n\nLemma lt_mdeg_ltmc m1 m2 : mdeg m1 < mdeg m2 -> (m1 < m2)%O.\nProof. by rewrite ltEmnm ltxi_cons leEnat; case: ltngtP. Qed.\n\nLemma mdeg_max m1 m2 : mdeg (m1 `|` m2)%O = maxn (mdeg m1) (mdeg m2).\nProof.\nhave [/lemc_mdeg|Hgt] := leP; first by case: ltngtP.\nby apply/esym/maxn_idPl; apply/contra_lt_leq: Hgt => /lt_mdeg_ltmc /ltW.\nQed.\n\n(* FIXME: introduce \\max_ to replace \\join_ ? This would require bOrderType. *)\nLemma mdeg_bigmax (r : seq 'X_{1..n}) :\n  mdeg (\\join_(m <- r) m)%O = \\max_(m <- r) mdeg m.\nProof.\nelim: r => [|m r ih]; first by rewrite !big_nil mdeg0.\nby rewrite !big_cons mdeg_max ih.\nQed.\n\nLemma ltmc_add2r m m1 m2 : ((m + m1)%MM < (m + m2)%MM)%O = (m1 < m2)%O.\nProof.\ncase: (ltngtP (mdeg m1) (mdeg m2)) => [lt|lt|].\n+ by rewrite !lt_mdeg_ltmc // !mdegD ltn_add2l.\n+ rewrite !ltNge !le_eqVlt !lt_mdeg_ltmc ?orbT //.\n  by rewrite !mdegD ltn_add2l.\nmove=> eq; have eqD: mdeg (m + m1) = mdeg (m + m2).\n  by rewrite !mdegD (rwP eqP) eqn_add2l eq.\napply/ltmcP/ltmcP => // {eq eqD} -[i eq lt]; exists i.\n+ by move=> j /eq /eqP; rewrite !mnmDE (rwP eqP) eqn_add2l.\n+ by move: lt; rewrite !mnmDE ltn_add2l.\n+ by move=> j /eq /eqP; rewrite !mnmDE (rwP eqP) eqn_add2l.\n+ by rewrite !mnmDE ltn_add2l.\nQed.\n\nLemma ltmc_add2l m1 m2 m : ((m1 + m)%MM < (m2 + m)%MM)%O = (m1 < m2)%O.\nProof. by rewrite ![(_+m)%MM]addmC ltmc_add2r. Qed.\n\nLemma lemc_add2r m m1 m2 : ((m + m1)%MM <= (m + m2)%MM)%O = (m1 <= m2)%O.\nProof. by rewrite !le_eqVlt eqm_add2l ltmc_add2r. Qed.\n\nLemma lemc_add2l m1 m2 m : ((m1 + m)%MM <= (m2 + m)%MM)%O = (m1 <= m2)%O.\nProof. by rewrite ![(_+m)%MM]addmC lemc_add2r. Qed.\n\nLemma lemc_addr m1 m2 : (m1 <= (m1 + m2)%MM)%O.\nProof. by rewrite -{1}[m1]addm0 lemc_add2r le0x. Qed.\n\nLemma lemc_addl m1 m2 : (m2 <= (m1 + m2)%MM)%O.\nProof. by rewrite addmC lemc_addr. Qed.\n\nLemma lemc_lt_add m1 m2 n1 n2 :\n  (m1 <= n1 -> m2 < n2 -> (m1 + m2)%MM < (n1 + n2)%MM)%O.\nProof.\nmove=> le lt; apply/(le_lt_trans (y := n1 + m2)%MM).\n  by rewrite lemc_add2l. by rewrite ltmc_add2r.\nQed.\n\nLemma ltmc_le_add m1 m2 n1 n2 :\n  (m1 < n1 -> m2 <= n2 -> (m1 + m2)%MM < (n1 + n2)%MM)%O.\nProof.\nmove=> lt le; apply/(lt_le_trans (y := n1 + m2)%MM).\n  by rewrite ltmc_add2l. by rewrite lemc_add2r.\nQed.\n\nLemma ltm_add m1 m2 n1 n2 :\n  (m1 < n1 -> m2 < n2 -> (m1 + m2)%MM < (n1 + n2)%MM)%O.\nProof. by move=> lt1 /ltW /(ltmc_le_add lt1). Qed.\n\nLemma lem_add m1 m2 n1 n2 :\n  (m1 <= n1 -> m2 <= n2 -> (m1 + m2)%MM <= (n1 + n2)%MM)%O.\nProof.\nmove=> le1 le2; apply/(le_trans (y := m1 + n2)%MM).\n  by rewrite lemc_add2r. by rewrite lemc_add2l.\nQed.\n\nLemma lem_leo m1 m2 : (m1 <= m2)%MM -> (m1 <= m2)%O.\nProof. by move=> ml; rewrite -(submK ml) -{1}[m1]add0m lem_add // le0x. Qed.\n\n(* -------------------------------------------------------------------- *)\nSection WF.\nContext (P : 'X_{1..n} -> Type).\n\nLemma ltmwf :\n  (forall m1, (forall m2, (m2 < m1)%O -> P m2) -> P m1) -> forall m, P m.\nProof.\npose tof m := [tuple of mdeg m :: m].\nmove=> ih m; move: {2}(tof _) (erefl (tof m))=> t.\nelim/(@ltxwf _ [porderType of nat]): t m=> //=; last first.\n  move=> t wih m Em; apply/ih=> m' lt_m'm.\n  by apply/(wih (tof m')); rewrite // -Em.\nmove=> Q {}ih x; elim: x {-2}x (leqnn x).\n  move=> x; rewrite leqn0=> /eqP->; apply/ih.\n  by move=> y; rewrite ltEnat/= ltn0.\nmove=> k wih l le_l_Sk; apply/ih=> y; rewrite ltEnat => lt_yl.\nby apply/wih; have := leq_trans lt_yl le_l_Sk; rewrite ltnS.\nQed.\n\nEnd WF.\n\nLemma ltom_wf : @well_founded 'X_{1..n} <%O.\nProof. by apply: ltmwf=> m1 IH; apply: Acc_intro => m2 /IH. Qed.\n\nEnd MultinomOrder.\n\n(* -------------------------------------------------------------------- *)\nSection DegBoundMultinom.\nContext (n bound : nat).\n\nRecord bmultinom := BMultinom { bmnm :> 'X_{1..n}; _ : mdeg bmnm < bound }.\n\nCanonical bmultinom_subType := Eval hnf in [subType for bmnm].\n\nDefinition bmultinom_eqMixin      := Eval hnf in [eqMixin of bmultinom by <:].\nCanonical  bmultinom_eqType       := Eval hnf in EqType bmultinom bmultinom_eqMixin.\nDefinition bmultinom_choiceMixin  := [choiceMixin of bmultinom by <:].\nCanonical  bmultinom_choiceType   := Eval hnf in ChoiceType bmultinom bmultinom_choiceMixin.\nDefinition bmultinom_countMixin   := [countMixin of bmultinom by <:].\nCanonical  bmultinom_countType    := Eval hnf in CountType bmultinom bmultinom_countMixin.\nCanonical  bmultinom_subCountType := Eval hnf in [subCountType of bmultinom].\n\nLemma bmeqP (m1 m2 : bmultinom) : (m1 == m2) = (m1 == m2 :> 'X_{1..n}).\nProof. by []. Qed.\n\nLemma bmdeg (m : bmultinom) : mdeg m < bound.\nProof. by case: m. Qed.\n\nLemma bm0_proof : mdeg (0%MM : 'X_{1..n}) < bound.+1.\nProof. by rewrite mdeg0. Qed.\n\nEnd DegBoundMultinom.\n\nDefinition bm0 n b := BMultinom (bm0_proof n b).\nArguments bm0 {n b}.\n\nNotation \"''X_{1..' n  <  b '}'\"       := (bmultinom n b) : type_scope.\nNotation \"''X_{1..' n  <  b1 , b2 '}'\" :=\n  ('X_{1..n < b1} * 'X_{1..n < b2})%type : type_scope.\n\n(* -------------------------------------------------------------------- *)\nSection FinDegBound.\nContext (n b : nat).\n\nDefinition bmnm_enum : seq 'X_{1..n < b} :=\n  let project (x : n.-tuple 'I_b) := [multinom of map val x] in\n  pmap insub [seq (project x) | x <- enum {: n.-tuple 'I_b }].\n\nLemma bmnm_enumP : Finite.axiom bmnm_enum.\nProof.\ncase=> m lt_dm_b /=; rewrite count_uniq_mem; last first.\n  rewrite (pmap_uniq (@insubK _ _ _)) 1?map_inj_uniq ?enum_uniq //.\n  by move=> t1 t2 [] /(inj_map val_inj) /val_inj ->.\napply/eqP; rewrite eqb1 mem_pmap_sub /=; apply/mapP.\ncase: b m lt_dm_b=> // b' [m] /= lt_dm_Sb; exists [tuple of map inord m].\n  by rewrite mem_enum.\napply/mnmP=> i; rewrite !multinomE !tnth_map inordK //.\nmove: lt_dm_Sb; rewrite mdegE (bigD1 i) //= multinomE.\nby move=> /(leq_trans _) ->//; rewrite ltnS leq_addr.\nQed.\n\nCanonical bmnm_finMixin   := Eval hnf in FinMixin bmnm_enumP.\nCanonical bmnm_finType    := Eval hnf in FinType 'X_{1..n < b} bmnm_finMixin.\nCanonical bmnm_subFinType := Eval hnf in [subFinType of 'X_{1..n < b}].\n\nEnd FinDegBound.\n\nSection Mlcm.\nContext (n : nat).\nImplicit Types (m : 'X_{1..n}).\n\nDefinition mlcm m1 m2 := [multinom maxn (m1 i) (m2 i) | i < n].\n\nLemma mlcmC : commutative mlcm.\nProof.\nby move=> m1 m2; apply/mnmP=> i; rewrite /mlcm /= !mnmE maxnC.\nQed.\n\nLemma mlc0m : left_id 0%MM mlcm.\nProof. by move=> m; apply/mnmP=> i; rewrite /mlcm /= !mnmE max0n. Qed.\n\nLemma mlcm0 : right_id 0%MM mlcm.\nProof. by move=> m; rewrite mlcmC mlc0m. Qed.\n\nLemma mlcmE m1 m2 : mlcm m1 m2 = (m1 + (m2 - m1))%MM.\nProof. by apply/mnmP=> i; rewrite /mlcm /= !mnmE maxnE. Qed.\n\nLemma lem_mlcm m m1 m2 : (mlcm m1 m2 <= m)%MM = (m1 <= m)%MM && (m2 <= m)%MM.\nProof.\napply/forallP/andP => [H|[/forallP H1 /forallP H2] i]; first split.\n- by apply/forallP=> i; apply: leq_trans (H i); rewrite mnmE leq_maxl.\n- by apply/forallP=> i; apply: leq_trans (H i); rewrite mnmE leq_maxr.\nby rewrite mnmE geq_max H1 H2.\nQed.\n\nLemma lem_mlcml m1 m2 : (m1 <= mlcm m1 m2)%MM.\nProof. by apply/forallP=> i; rewrite /mlcm /= !mnmE leq_maxl. Qed.\n\nLemma lem_mlcmr m1 m2 : (m2 <= mlcm m1 m2)%MM.\nProof. by apply/forallP=> i; rewrite /mlcm /= !mnmE leq_maxr. Qed.\n\nEnd Mlcm.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyDef.\nContext (n : nat) (R : ringType).\n\nInductive mpoly := MPoly of {freeg 'X_{1..n} / R}.\n\nCoercion mpoly_val p := let: MPoly D := p in D.\n\nCanonical  mpoly_subType     := Eval hnf in [newType for mpoly_val].\nDefinition mpoly_eqMixin     := Eval hnf in [eqMixin of mpoly by <:].\nCanonical  mpoly_eqType      := Eval hnf in EqType mpoly mpoly_eqMixin.\nDefinition mpoly_choiceMixin := [choiceMixin of mpoly by <:].\nCanonical  mpoly_choiceType  := Eval hnf in ChoiceType mpoly mpoly_choiceMixin.\n\nDefinition mpoly_of of phant R := mpoly.\n\nIdentity Coercion type_mpoly_of : mpoly_of >-> mpoly.\n\nEnd MPolyDef.\n\nBind Scope ring_scope with mpoly_of.\nBind Scope ring_scope with mpoly.\n\nNotation \"{ 'mpoly' T [ n ] }\" := (mpoly_of n (Phant T)).\nNotation \"[ 'mpoly' D ]\" := (@MPoly _ _ D : {mpoly _[_]}).\n\n(* -------------------------------------------------------------------- *)\nSection MPolyTheory.\nContext (n : nat) (R : ringType).\nImplicit Types (p q r : {mpoly R[n]}) (D : {freeg 'X_{1..n} / R}).\n\nLemma mpoly_valK D : [mpoly D] = D :> {freeg _ / _}.\nProof. by []. Qed.\n\nLemma mpoly_eqP p q : (p = q) <-> (p = q :> {freeg _ / _}).\nProof.\nsplit=> [->//|]; case: p q => [p] [q].\nby rewrite !mpoly_valK=> ->.\nQed.\n\nDefinition mpolyC (c : R) : {mpoly R[n]} :=\n  [mpoly << c *g 0%MM >>].\n\nLocal Notation \"c %:MP\" := (mpolyC c) : ring_scope.\n\nLemma mpolyC_eq (c1 c2 : R) : (c1%:MP == c2%:MP) = (c1 == c2).\nProof.\napply/eqP/eqP=> [|->//] /eqP /freeg_eqP /(_ 0%MM).\nby rewrite !coeffU eqxx !mulr1.\nQed.\n\nDefinition mcoeff (m : 'X_{1..n}) p : R := coeff m p.\n\nLemma mcoeff_MPoly D m : mcoeff m (MPoly D) = coeff m D.\nProof. by []. Qed.\n\nLocal Notation \"p @_ i\" := (mcoeff i p) : ring_scope.\n\nLemma mcoeffC c m : c%:MP@_m = c * (m == 0%MM)%:R.\nProof. by rewrite mcoeff_MPoly coeffU eq_sym. Qed.\n\nLemma mpolyCK : cancel mpolyC (mcoeff 0%MM).\nProof. by move=> c; rewrite mcoeffC eqxx mulr1. Qed.\n\nDefinition msupp p : seq 'X_{1..n} := nosimpl (dom p).\n\nLemma msuppE p : msupp p = dom p :> seq _.\nProof. by []. Qed.\n\nLemma msupp_uniq p : uniq (msupp p).\nProof. by rewrite msuppE uniq_dom. Qed.\n\nLemma mcoeff_msupp p m : (m \\in msupp p) = (p@_m != 0).\nProof. by rewrite msuppE /mcoeff mem_dom. Qed.\n\nLemma memN_msupp_eq0 p m : m \\notin msupp p -> p@_m = 0.\nProof. by rewrite !msuppE /mcoeff => /coeff_outdom. Qed.\n\nLemma mcoeff_eq0 p m : (p@_m == 0) = (m \\notin msupp p).\nProof. by rewrite msuppE mem_dom /mcoeff negbK. Qed.\n\nLemma msupp0 : msupp 0%:MP = [::].\nProof. by rewrite msuppE /= freegU0 dom0. Qed.\n\nLemma msupp1 : msupp 1%:MP = [:: 0%MM].\nProof. by rewrite msuppE /= domU1. Qed.\n\nLemma msuppC (c : R) :\n  msupp c%:MP = if c == 0 then [::] else [:: 0%MM].\nProof. by have [->|nz_c] := eqVneq; [rewrite msupp0 | rewrite msuppE domU]. Qed.\n\nLemma mpolyP p q : (forall m, mcoeff m p = mcoeff m q) <-> (p = q).\nProof. by split=> [|->] // h; apply/mpoly_eqP/eqP/freeg_eqP/h. Qed.\n\nLemma freeg_mpoly p: p = [mpoly \\sum_(m <- msupp p) << p@_m *g m >>].\nProof. by case: p=> p; apply/mpoly_eqP; rewrite /= -{1}[p]freeg_sumE. Qed.\n\nEnd MPolyTheory.\n\nNotation \"c %:MP\" := (mpolyC _ c) : ring_scope.\nNotation \"c %:MP_[ n ]\" := (mpolyC n c) : ring_scope.\n\nNotation \"p @_ i\" := (mcoeff i p) : ring_scope.\n\n#[global] Hint Resolve msupp_uniq : core.\n\n(* -------------------------------------------------------------------- *)\nSection NVar0.\nContext (n : nat) (R : ringType).\nImplicit Types (p q r : {mpoly R[n]}).\n\nLemma nvar0_mnmE : @all_equal_to 'X_{1..0} 0%MM.\nProof. by move=> mon; apply/mnmP; case. Qed.\n\nLemma nvar0_mpolyC (p : {mpoly R[0]}): p = (p@_0%MM)%:MP.\nProof. by apply/mpolyP=> m; rewrite mcoeffC nvar0_mnmE eqxx mulr1. Qed.\n\nLemma nvar0_mpolyC_eq p : n = 0%N -> p = (p@_0%MM)%:MP.\nProof. by move=> z_p; move:p; rewrite z_p; apply/nvar0_mpolyC. Qed.\n\nEnd NVar0.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyZMod.\nContext (n : nat) (R : ringType).\nImplicit Types (p q r : {mpoly R[n]}).\n\nDefinition mpoly_opp p := [mpoly -(mpoly_val p)].\n\nDefinition mpoly_add p q := [mpoly mpoly_val p + mpoly_val q].\n\nLemma add_mpoly0 : left_id 0%:MP mpoly_add.\nProof. by move=> p; apply/mpoly_eqP; rewrite !mpoly_valK freegU0 add0r. Qed.\n\nLemma add_mpolyN : left_inverse 0%:MP mpoly_opp mpoly_add.\nProof. by move=> p; apply/mpoly_eqP; rewrite !mpoly_valK freegU0 addrC subrr. Qed.\n\nLemma add_mpolyC : commutative mpoly_add.\nProof. by move=> p q; apply/mpoly_eqP; rewrite !mpoly_valK addrC. Qed.\n\nLemma add_mpolyA : associative mpoly_add.\nProof. by move=> p q r; apply/mpoly_eqP; rewrite !mpoly_valK addrA. Qed.\n\nDefinition mpoly_zmodMixin :=\n  ZmodMixin add_mpolyA add_mpolyC add_mpoly0 add_mpolyN.\n\nCanonical mpoly_zmodType :=\n  Eval hnf in ZmodType {mpoly R[n]} mpoly_zmodMixin.\nCanonical mpolynomial_zmodType :=\n  Eval hnf in ZmodType (mpoly n R) mpoly_zmodMixin.\n\nDefinition mpoly_scale c p := [mpoly c *: (mpoly_val p)].\n\nLocal Notation \"c *:M p\" := (mpoly_scale c p)\n  (at level 40, left associativity).\n\nLemma scale_mpolyA c1 c2 p :\n  c1 *:M (c2 *:M p) = (c1 * c2) *:M p.\nProof. by apply/mpoly_eqP; rewrite !mpoly_valK scalerA. Qed.\n\nLemma scale_mpoly1m p : 1 *:M p = p.\nProof. by apply/mpoly_eqP; rewrite !mpoly_valK scale1r. Qed.\n\nLemma scale_mpolyDr c p1 p2 :\n  c *:M (p1 + p2) = c *:M p1 + c *:M p2.\nProof. by apply/mpoly_eqP; rewrite !mpoly_valK scalerDr. Qed.\n\nLemma scale_mpolyDl p c1 c2 :\n  (c1 + c2) *:M p = c1 *:M p + c2 *:M p.\nProof. by apply/mpoly_eqP; rewrite !mpoly_valK scalerDl. Qed.\n\nDefinition mpoly_lmodMixin :=\n  LmodMixin scale_mpolyA scale_mpoly1m scale_mpolyDr scale_mpolyDl.\n\nCanonical mpoly_lmodType :=\n  Eval hnf in LmodType R {mpoly R[n]} mpoly_lmodMixin.\nCanonical mpolynomial_lmodType :=\n  Eval hnf in LmodType R (mpoly n R) mpoly_lmodMixin.\n\nLocal Notation mcoeff := (@mcoeff n R).\n\nLemma mcoeff_is_additive m : additive (mcoeff m).\nProof. by move=> p q /=; rewrite /mcoeff raddfB. Qed.\n\nCanonical mcoeff_additive m: {additive {mpoly R[n]} -> R} :=\n  Additive (mcoeff_is_additive m).\n\nLemma mcoeff0   m   : mcoeff m 0 = 0               . Proof. exact: raddf0. Qed.\nLemma mcoeffN   m   : {morph mcoeff m: x / - x}    . Proof. exact: raddfN. Qed.\nLemma mcoeffD   m   : {morph mcoeff m: x y / x + y}. Proof. exact: raddfD. Qed.\nLemma mcoeffB   m   : {morph mcoeff m: x y / x - y}. Proof. exact: raddfB. Qed.\nLemma mcoeffMn  m k : {morph mcoeff m: x / x *+ k} . Proof. exact: raddfMn. Qed.\nLemma mcoeffMNn m k : {morph mcoeff m: x / x *- k} . Proof. exact: raddfMNn. Qed.\n\nLemma mcoeffZ c p m : mcoeff m (c *: p) = c * (mcoeff m p).\nProof. by rewrite /mcoeff coeffZ. Qed.\n\nCanonical mcoeff_linear m : {scalar {mpoly R[n]}} :=\n  AddLinear ((fun c => (mcoeffZ c)^~ m) : scalable_for *%R (mcoeff m)).\n\nLocal Notation mpolyC := (@mpolyC n R).\n\nLemma mpolyC_is_additive : additive mpolyC.\nProof. by move=> p q; apply/mpoly_eqP; rewrite /= freegUB. Qed.\n\nCanonical mpolyC_additive : {additive R -> {mpoly R[n]}} :=\n  Additive mpolyC_is_additive.\n\nLemma mpolyC0     : mpolyC 0 = 0               . Proof. exact: raddf0. Qed.\nLemma mpolyCN     : {morph mpolyC: x / - x}    . Proof. exact: raddfN. Qed.\nLemma mpolyCD     : {morph mpolyC: x y / x + y}. Proof. exact: raddfD. Qed.\nLemma mpolyCB     : {morph mpolyC: x y / x - y}. Proof. exact: raddfB. Qed.\nLemma mpolyCMn  k : {morph mpolyC: x / x *+ k} . Proof. exact: raddfMn. Qed.\nLemma mpolyCMNn k : {morph mpolyC: x / x *- k} . Proof. exact: raddfMNn. Qed.\n\nLemma msupp_eq0 p : (msupp p == [::]) = (p == 0).\nProof.\ncase: p=> p /=; rewrite msuppE /GRing.zero /= /mpolyC.\nby rewrite dom_eq0 freegU0 /=.\nQed.\n\nLemma msuppnil0 p : msupp p = [::] -> p = 0.\nProof. by move/eqP; rewrite msupp_eq0 => /eqP. Qed.\n\nLemma mpolyC_eq0 c : (c%:MP == 0 :> {mpoly R[n]}) = (c == 0).\nProof.\nrewrite eqE /=; apply/idP/eqP=> [/freeg_eqP/(_ 0%MM)|->//].\nby rewrite !coeffU eqxx !mulr1.\nQed.\n\nEnd MPolyZMod.\n\n(* -------------------------------------------------------------------- *)\nSection MMeasureDef.\nContext (n : nat).\n\nStructure measure := Measure {\n  mf : 'X_{1..n} -> nat;\n  _  : mf 0 = 0%N;\n  _  : {morph mf : m1 m2 / (m1 + m2)%MM >-> (m1 + m2)%N}\n}.\n\nCoercion mf : measure >-> Funclass.\n\nLet measure_id (mf1 mf2 : 'X_{1..n} -> nat) := phant_id mf1 mf2.\n\nDefinition clone_measure mf :=\n  fun (mfL : measure) & measure_id mfL mf =>\n  fun mf0 mfD (mfL' := @Measure mf mf0 mfD)\n    & phant_id mfL' mfL => mfL'.\n\nEnd MMeasureDef.\n\nNotation \"[ 'measure' 'of' f ]\" := (@clone_measure _ f _ id _ _ id)\n  (at level 0, format\"[ 'measure'  'of'  f ]\") : form_scope.\n\n(* -------------------------------------------------------------------- *)\nCanonical mdeg_measure n := Eval hnf in @Measure n _ mdeg0 mdegD.\n\n(* -------------------------------------------------------------------- *)\nSection MMeasure.\nContext (n : nat) (R : ringType) (mf : measure n).\nImplicit Types (m : 'X_{1..n}) (p q : {mpoly R[n]}).\n\nLemma mf0 : mf 0%MM = 0%N.\nProof. by case: mf. Qed.\n\nLemma mfD : {morph mf : m1 m2 / (m1 + m2)%MM >-> (m1 + m2)%N}.\nProof. by case: mf. Qed.\n\nLemma mfE m : mf m = (\\sum_(i < n) (m i) * mf U_(i)%MM)%N.\nProof.\nrewrite {1}(multinomUE_id m) (big_morph mf mfD mf0); apply/eq_bigr => i _.\nelim: (m i) => [// | d ih] /=; first by rewrite mul0n mulm0n mf0.\nby rewrite mulmS mulSn mfD ih.\nQed.\n\nDefinition mmeasure p := (\\max_(m <- msupp p) (mf m).+1)%N.\n\nLemma mmeasureE p : mmeasure p = (\\max_(m <- msupp p) (mf m).+1)%N.\nProof. by []. Qed.\n\nLemma mmeasure0 : mmeasure 0 = 0%N.\nProof. by rewrite /mmeasure msupp0 big_nil. Qed.\n\nLemma mmeasure_mnm_lt p m : m \\in msupp p -> mf m < mmeasure p.\nProof. by move=> m_in_p; rewrite /mmeasure (bigD1_seq m) //= leq_max leqnn. Qed.\n\nLemma mmeasure_mnm_ge p m : mmeasure p <= mf m -> m \\notin msupp p.\nProof. by apply/contra_leqN => /mmeasure_mnm_lt. Qed.\n\nEnd MMeasure.\n\n(* -------------------------------------------------------------------- *)\nSection MSuppZMod.\nContext (n : nat) (R : ringType).\nImplicit Types (p q r : {mpoly R[n]}) (D : {freeg 'X_{1..n} / R}).\n\nLemma msuppN p : perm_eq (msupp (-p)) (msupp p).\nProof. by apply/domN_perm_eq. Qed.\n\nLemma msuppD_le p q : {subset msupp (p + q) <= msupp p ++ msupp q}.\nProof. by move=> x /domD_subset. Qed.\n\nLemma msuppB_le p q : {subset msupp (p - q) <= msupp p ++ msupp q}.\nProof. by move=> x /msuppD_le; rewrite !mem_cat (perm_mem (msuppN _)). Qed.\n\nLemma msuppD (p1 p2 : {mpoly R[n]}) :\n     [predI (msupp p1) & (msupp p2)] =1 xpred0\n  -> perm_eq (msupp (p1 + p2)) (msupp p1 ++ msupp p2).\nProof. by apply/domD_perm_eq. Qed.\n\nLemma msupp_sum_le (T : Type) (F : T -> {mpoly R[n]}) P (r : seq T) :\n  {subset    msupp (\\sum_(i <- r | P i) (F i))\n          <= flatten [seq msupp (F i) | i <- r & P i]}.\nProof.\n  elim: r => /= [|x r ih]; first by rewrite !big_nil msupp0.\n  rewrite !big_cons; case: (P x)=> // m /msuppD_le.\n  by rewrite !mem_cat => /orP [->//|] /ih ->; rewrite orbT.\nQed.\n\nLemma msupp_sum (T : eqType) (r : seq T) (P : pred T) (F : T -> {mpoly R[n]}) :\n     uniq r\n  -> {in r &, forall x y, x != y ->\n        [predI (msupp (F x)) & (msupp (F y))] =1 xpred0}\n  -> perm_eq\n       (msupp (\\sum_(i <- r | P i) F i))\n       (flatten [seq msupp (F i) | i <- r & P i]).\nProof.\nelim: r => /= [|x r ih]; first by rewrite !big_nil msupp0.\ncase/andP=> x_notin_r uq_r h; rewrite !big_cons /=.\ncase: (P x); last apply/ih=> //; last first.\n  by move=> y1 y2 y1_in_r y2_in_r; apply/h; rewrite 1?mem_behead.\nmove/(_ uq_r): ih; rewrite -(perm_cat2l (msupp (F x))) => h'.\nrewrite -(permPr (h' _)); first apply/msuppD.\n  move=> m /=; case: (boolP (m \\in _))=> //= m_in_Fx.\n  apply/negP=> /msupp_sum_le /flattenP[/= ms] /mapP[y].\n  rewrite mem_filter => /andP[_ y_in_r] ->.\n  have /= := h x y _ _ _ m; rewrite m_in_Fx=> /= -> //.\n    by rewrite mem_head. by rewrite mem_behead.\n  by move/memPnC: x_notin_r => /(_ _ y_in_r).\nby move=> y1 y2 y1_in_r y2_in_r; apply/h; rewrite 1?mem_behead.\nQed.\n\nEnd MSuppZMod.\n\n(* -------------------------------------------------------------------- *)\nNotation msize p := (@mmeasure _ _ [measure of mdeg] p).\n\n(* -------------------------------------------------------------------- *)\nSection MWeight.\nContext {n : nat}.\nImplicit Types (m : 'X_{1..n}).\n\nDefinition mnmwgt m := (\\sum_i m i * i.+1)%N.\n\nLemma mnmwgt0 : mnmwgt 0 = 0%N.\nProof. by rewrite /mnmwgt big1 // => /= i _; rewrite mnm0E mul0n. Qed.\n\nLemma mnmwgt1 i : mnmwgt U_(i) = i.+1.\nProof.\nrewrite /mnmwgt (bigD1 i) //= mnm1E eqxx mul1n.\nrewrite big1 ?addn0 //= => j ne_ij; rewrite mnm1E.\nby rewrite eq_sym (negbTE ne_ij) mul0n.\nQed.\n\nLemma mnmwgtD m1 m2 : mnmwgt (m1 + m2) = (mnmwgt m1 + mnmwgt m2)%N.\nProof.\nrewrite /mnmwgt -big_split /=; apply/eq_bigr=> i _.\nby rewrite mnmDE mulnDl.\nQed.\n\nEnd MWeight.\n\nCanonical mnmwgt_measure n := Eval hnf in @Measure n _ mnmwgt0 mnmwgtD.\n\n(* -------------------------------------------------------------------- *)\nNotation mweight p := (@mmeasure _ _ [measure of mnmwgt] p).\n\nSection MSize.\nContext (n : nat) (R : ringType).\nImplicit Types (m : 'X_{1..n}) (p : {mpoly R[n]}).\n\nLemma msizeE p : msize p = (\\max_(m <- msupp p) (mdeg m).+1)%N.\nProof. exact/mmeasureE. Qed.\n\nDefinition msize0 := mmeasure0 R [measure of @mdeg n].\n\nLemma msize_mdeg_lt p m : m \\in msupp p -> mdeg m < msize p.\nProof. exact/mmeasure_mnm_lt. Qed.\n\nLemma msize_mdeg_ge p m : msize p <= mdeg m -> m \\notin msupp p.\nProof. exact/mmeasure_mnm_ge. Qed.\n\nEnd MSize.\n\n(* -------------------------------------------------------------------- *)\nSection MMeasureZMod.\nContext (n : nat) (R : ringType) (mf : measure n).\nImplicit Types (c : R) (m : 'X_{1..n}) (p q : {mpoly R[n]}).\n\nLocal Notation mmeasure := (@mmeasure n R mf).\n\nLemma mmeasureC c : mmeasure c%:MP = (c != 0%R) :> nat.\nProof.\nrewrite mmeasureE msuppC; case: (_ == 0)=> /=.\nby rewrite big_nil. by rewrite big_seq1 mf0.\nQed.\n\nLemma mmeasureD_le p q : mmeasure (p + q) <= maxn (mmeasure p) (mmeasure q).\nProof.\nrewrite {1}mmeasureE big_tnth; apply/bigmax_leqP=> /= i _.\nset m := tnth _ _; have: m \\in msupp (p + q) by apply/mem_tnth.\nmove/msuppD_le; rewrite leq_max mem_cat.\nby case/orP=> /mmeasure_mnm_lt->; rewrite !simpm.\nQed.\n\nLemma mmeasure_sum (T : Type) (r : seq _) (F : T -> {mpoly R[n]}) (P : pred T) :\n  mmeasure (\\sum_(i <- r | P i) F i) <= \\max_(i <- r | P i) mmeasure (F i).\nProof.\nelim/big_rec2: _ => /= [|i k p _ le]; first by rewrite mmeasure0.\napply/(leq_trans (mmeasureD_le _ _)); rewrite geq_max.\nby rewrite leq_maxl /= leq_max le orbC.\nQed.\n\nLemma mmeasureN p : mmeasure (-p) = mmeasure p.\nProof. by rewrite mmeasureE (perm_big _ (msuppN _)). Qed.\n\nLemma mmeasure_poly_eq0 p : (mmeasure p == 0%N) = (p == 0).\nProof.\napply/idP/eqP=> [z_p|->]; last by rewrite mmeasure0.\napply/mpoly_eqP; move: z_p; rewrite mmeasureE.\nrewrite {2}[p]freeg_mpoly; case: (msupp p).\n  by rewrite !big_nil /= freegU0.\nby move=> m q; rewrite !big_cons -leqn0 geq_max.\nQed.\n\nLemma mpolySpred p : p != 0 -> mmeasure p = (mmeasure p).-1.+1.\nProof. by rewrite -mmeasure_poly_eq0 -lt0n => /prednK. Qed.\n\nLemma mmeasure_msupp0 p : (mmeasure p == 0%N) = (msupp p == [::]).\nProof.\nrewrite mmeasureE; case: (msupp _) => [|m s].\n  by rewrite big_nil !eqxx.\nrewrite big_cons /= -[_::_==_]/false; apply/negbTE.\nby rewrite -lt0n leq_max.\nQed.\n\nEnd MMeasureZMod.\n\n(* -------------------------------------------------------------------- *)\nDefinition msizeC    n R := @mmeasureC n R [measure of mdeg].\nDefinition msizeD_le n R := @mmeasureD_le n R [measure of mdeg].\nDefinition msize_sum n R := @mmeasure_sum n R [measure of mdeg].\nDefinition msizeN    n R := @mmeasureN n R [measure of mdeg].\n\nDefinition msize_poly_eq0 n R := @mmeasure_poly_eq0 n R [measure of mdeg].\nDefinition msize_msupp0   n R := @mmeasure_msupp0 n R [measure of mdeg].\n\n(* -------------------------------------------------------------------- *)\nDefinition polyn (R : ringType) :=\n  fix polyn n := if n is p.+1 then [ringType of {poly (polyn p)}] else R.\n\nDefinition ipoly (T : Type) : Type := T.\n\nNotation \"{ 'ipoly' T [ n ] }\"   := (polyn T n).\nNotation \"{ 'ipoly' T [ n ] }^p\" := (ipoly {ipoly T[n]}).\n\nSection IPoly.\nContext (R : ringType) (n : nat).\n\nCanonical ipoly_eqType     := [eqType     of {ipoly R[n]}^p].\nCanonical ipoly_choiceType := [choiceType of {ipoly R[n]}^p].\nCanonical ipoly_zmodType   := [zmodType   of {ipoly R[n]}^p].\nCanonical ipoly_ringType   := [ringType   of {ipoly R[n]}^p].\n\nEnd IPoly.\n\n(* -------------------------------------------------------------------- *)\nSection Inject.\nContext (R : ringType).\n\nFixpoint inject n m (p : {ipoly R[n]}) : {ipoly R[m + n]} :=\n  if m is m'.+1 return {ipoly R[m + n]} then (inject m' p)%:P else p.\n\nLemma inject_inj n m : injective (@inject n m).\nProof. by elim: m=> [|m ih] p q //= /polyC_inj /ih. Qed.\n\nLemma inject_is_rmorphism n m : rmorphism (@inject n m).\nProof.\nelim: m => [|m ih] //=; rewrite -/(_ \\o _).\nby suff ->: inject m = RMorphism ih by exact/rmorphismP.\nQed.\n\nCanonical inject_rmorphism n m := RMorphism (inject_is_rmorphism n m).\nCanonical inject_additive  n m := Additive (inject_is_rmorphism n m).\n\nDefinition inject_cast n m k E : {ipoly R[n]} -> {ipoly R[k]} :=\n  ecast k (_ -> {ipoly R[k]}) E (@inject n m).\n\nLemma inject_cast_inj n m k E :\n  injective (@inject_cast n m k E).\nProof. by case: k / E; apply/inject_inj. Qed.\n\nLemma inject_cast_is_rmorphism n m k E :\n  rmorphism (@inject_cast n m k E).\nProof. by case: k / E; apply/rmorphismP. Qed.\n\nCanonical inject_cast_rmorphism n m k e := RMorphism (@inject_cast_is_rmorphism n m k e).\nCanonical inject_cast_additive  n m k e := Additive  (@inject_cast_is_rmorphism n m k e).\n\nLemma inject1_proof n (i : 'I_n.+1) : (n - i + i = n)%N.\nProof. by rewrite subnK // -ltnS. Qed.\n\nDefinition inject1 n (i : 'I_n.+1) (p : {ipoly R[i]}) : {ipoly R[n]} :=\n  inject_cast (inject1_proof i) p.\n\nLocal Notation \"c %:IP\" := (inject_cast (inject1_proof ord0) c).\n\nSection IScale.\nContext (n : nat).\n\nLemma iscaleA (c1 c2 : R) (p : {ipoly R[n]}) :\n  c1%:IP * (c2%:IP * p) = (c1 * c2)%:IP * p.\nProof. by rewrite mulrA rmorphM /=. Qed.\n\nLemma iscale1r (p : {ipoly R[n]}) : 1%:IP * p = p.\nProof. by rewrite rmorph1 mul1r. Qed.\n\nLemma iscaleDr (c : R) (p q : {ipoly R[n]}) :\n  c%:IP * (p + q) = c%:IP * p + c%:IP * q.\nProof. by rewrite mulrDr. Qed.\n\nLemma iscaleDl (p : {ipoly R[n]}) (c1 c2 : R) :\n  (c1 + c2)%:IP * p = c1%:IP * p + c2%:IP * p.\nProof. by rewrite raddfD /= mulrDl. Qed.\n\nDefinition iscale (c : R) (p : {ipoly R[n]}) := c%:IP * p.\n\nDefinition ipoly_lmodMixin :=\n  let mkMixin := @GRing.Lmodule.Mixin R (ipoly_zmodType R n) iscale in\n  mkMixin iscaleA iscale1r iscaleDr iscaleDl.\n\nCanonical ipoly_lmodType := LmodType R {ipoly R[n]}^p ipoly_lmodMixin.\n\nEnd IScale.\n\nDefinition injectX n (m : 'X_{1..n}) : {ipoly R[n]} :=\n  \\prod_(i < n) (@inject1 _ (rshift 1 i) 'X)^+(m i).\n\nDefinition minject n (p : {mpoly R[n]}) : {ipoly R[n]} :=\n  fglift (@injectX n : _ -> {ipoly R[n]}^p) p.\n\nEnd Inject.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyRing.\nContext (n : nat) (R : ringType).\nImplicit Types (p q r : {mpoly R[n]}) (m : 'X_{1..n}).\n\nLocal Notation \"`| p |\" := (msize p) : ring_scope.\nLocal Notation \"!| m |\" := (mdeg  m) (format \"!| m |\"): ring_scope.\n\nLocal Notation \"p *M_[ m ] q\" :=\n  << (p@_m.1)%MM * (q@_m.2)%MM *g (m.1 + m.2)%MM >>\n  (at level 40, no associativity, format \"p  *M_[ m ]  q\").\n\nDefinition mpoly_mul p q : {mpoly R[n]} := [mpoly\n  \\sum_(m <- msupp p @@ msupp q) (p *M_[m] q)\n].\n\nLocal Notation \"p *M q\" := (mpoly_mul p q)\n  (at level 40, left associativity, format \"p  *M  q\").\n\nLemma mul_poly1_eq0L p q (m : 'X_{1..n} * 'X_{1..n}) :\n  m.1 \\notin msupp p -> p *M_[m] q = 0.\nProof. by move/memN_msupp_eq0=> ->; rewrite mul0r freegU0. Qed.\n\nLemma mul_poly1_eq0R p q (m : 'X_{1..n} * 'X_{1..n}) :\n  m.2 \\notin msupp q -> p *M_[m] q = 0.\nProof. by move/memN_msupp_eq0=> ->; rewrite mulr0 freegU0. Qed.\n\nLemma mpoly_mulwE p q kp kq : msize p <= kp -> msize q <= kq ->\n  p *M q = [mpoly \\sum_(m : 'X_{1..n < kp, kq}) (p *M_[m] q)].\nProof.\npose Ip := [subFinType of 'X_{1..n < kp}].\npose Iq := [subFinType of 'X_{1..n < kq}].\nmove=> lep leq; apply/mpoly_eqP/esym=> /=.\nrewrite big_allpairs/= big_pairA.\nrewrite (big_mksub Ip) ?msupp_uniq //=; first last.\n  by move=> x /msize_mdeg_lt /leq_trans; apply.\nrewrite [X in _ = X]big_rmcond /=; last first.\n  move=> i /memN_msupp_eq0 ->; rewrite big1=> //.\n  by move=> j _; rewrite mul0r freegU0.\napply/eq_bigr=> i _; rewrite (big_mksub Iq) /=; first last.\n  by move=> x /msize_mdeg_lt /leq_trans; apply.\n  by rewrite msupp_uniq.\nrewrite [X in _ = X]big_rmcond //= => j /memN_msupp_eq0 ->.\nby rewrite mulr0 freegU0.\nQed.\n\nArguments mpoly_mulwE [p q].\n\nLemma mpoly_mul_revwE p q kp kq : msize p <= kp -> msize q <= kq ->\n  p *M q = [mpoly \\sum_(m : 'X_{1..n < kq, kp}) (p *M_[(m.2, m.1)] q)].\nProof.\nby move=> lep leq; rewrite big_pairA exchange_big pair_bigA -mpoly_mulwE.\nQed.\n\nArguments mpoly_mul_revwE [p q].\n\nLemma mcoeff_poly_mul p q m k : !|m| < k ->\n  (p *M q)@_m =\n    \\sum_(k : 'X_{1..n < k, k} | m == (k.1 + k.2)%MM)\n      (p@_k.1 * q@_k.2).\nProof.\npose_big_enough i; first rewrite (mpoly_mulwE i i) // => lt_mk.\n  rewrite mcoeff_MPoly raddf_sum /=; have lt_mi: k < i by [].\n  apply/esym; rewrite big_cond_mulrn !big_pairA /=.\n  pose Ik := [subFinType of 'X_{1..n < k}].\n  pose Ii := [subFinType of 'X_{1..n < i}].\n  pose F i j := (p@_i * q@_j) *+ (m == (i + j))%MM.\n  pose G i   := \\sum_(j : 'X_{1..n < k}) (F i j).\n  rewrite (big_sub_widen Ik Ii xpredT G) /=; last first.\n    by move=> x /leq_trans; apply.\n  rewrite big_rmcond /=; last first.\n    case=> /= j _; rewrite -leqNgt => /(leq_trans lt_mk) h.\n    rewrite {}/G {}/F big1 // => /= l _.\n    case: eqP h => [{1}->|]; last by rewrite mulr0n.\n    by rewrite mdegD ltnNge leq_addr.\n  apply/eq_bigr=> j _; rewrite {}/G.\n  rewrite (big_sub_widen Ik Ii xpredT (F _)) /=; last first.\n    by move=> x /leq_trans; apply.\n  rewrite big_rmcond => //=; last first.\n    move=> l; rewrite -leqNgt => /(leq_trans lt_mk) h.\n    rewrite {}/F; case: eqP h; rewrite ?mulr0n //.\n    by move=> ->; rewrite mdegD ltnNge leq_addl.\n  by apply/eq_bigr=> l _; rewrite {}/F coeffU eq_sym mulr_natr.\nby close.\nQed.\n\nLemma mcoeff_poly_mul_rev p q m k : !|m| < k ->\n  (p *M q)@_m =\n    \\sum_(k : 'X_{1..n < k, k} | m == (k.1 + k.2)%MM) (p@_k.2 * q@_k.1).\nProof.\nmove=> /mcoeff_poly_mul ->; rewrite big_cond_mulrn.\nrewrite big_pairA /= exchange_big pair_bigA /=.\nby rewrite /= -big_cond_mulrn; apply/eq_big=> // i /=; rewrite addmC.\nQed.\n\nLemma mcoeff_poly_mul_lin p q m k : !|m| < k ->\n  (p *M q)@_m = \\sum_(k : 'X_{1..n < k} | (k <= m)%MM) p@_k * q@_(m-k).\nProof.\nmove=> lt_m_k; rewrite (mcoeff_poly_mul _ _ (k := k)) //.\npose P (k1 k2 : 'X_{1..n < k}) := m == (k1 + k2)%MM.\npose Q (k : 'X_{1..n < k}) := (k <= m)%MM.\npose F (k1 k2 : 'X_{1..n}) := p@_k1 * q@_k2.\nrewrite -(pair_big_dep xpredT P F) (bigID Q) /= addrC.\n(rewrite big1 ?add0r {}/P {}/Q; first apply/eq_bigr)=> /= h1.\n+ move=> le_h1_m; have pr: !|m - h1| < k.\n    by rewrite (leq_ltn_trans _ lt_m_k) // mdegB.\n  rewrite (big_pred1 (BMultinom pr)) //= => h2 /=.\n  rewrite bmeqP /=; apply/eqP/eqP=> ->.\n  * by rewrite addmC addmK.\n  * by rewrite addmC submK //; apply/mnm_lepP.\n+ rewrite negb_forall => /existsP /= [i Nle].\n  rewrite big_pred0 //= => h2; apply/negbTE/eqP.\n  move/mnmP/(_ i); rewrite mnmDE=> eq; move: Nle.\n  by rewrite eq leq_addr.\nQed.\nArguments mcoeff_poly_mul_lin [p q m].\n\nLocal Notation mcoeff_pml := mcoeff_poly_mul_lin.\n\nLemma mcoeff_poly_mul_lin_rev p q m k : !|m| < k ->\n  (p *M q)@_m = \\sum_(k : 'X_{1..n < k} | (k <= m)%MM) p@_(m-k) * q@_k.\nProof.\nmove=> /[dup] /mcoeff_pml -> lt.\nhave pr (h : 'X_{1..n}) : !|m - h| < k by exact: leq_ltn_trans (mdegB _ _) _.\npose F (k : 'X_{1..n < k}) := BMultinom (pr k).\nhave inv_F (h : 'X_{1..n}): (h <= m)%MM -> (m - (m - h))%MM = h.\n  by move=> le_hm; rewrite submBA // addmC addmK.\nrewrite (reindex_onto F F) //=; last first.\n  by move=> h /inv_F eqh; apply/eqP; rewrite eqE /= eqh.\napply/esym/eq_big => [h /=|h /inv_F -> //]; apply/esym; rewrite lem_subr eqE /=.\nby apply/eqP/idP => [<-|/inv_F //]; apply/mnm_lepP=> i; rewrite !mnmBE leq_subr.\nQed.\nArguments mcoeff_poly_mul_lin_rev [p q m].\n\nLocal Notation mcoeff_pmlr := mcoeff_poly_mul_lin_rev.\n\nLemma poly_mulA : associative mpoly_mul.\nProof.\nmove=> p q r; apply/mpolyP=> mi; pose_big_enough b.\nrewrite (mcoeff_pml b) // (mcoeff_pmlr b) //. 2: by close.\nhave h m: !|mi - m| < b by exact/(leq_ltn_trans (mdegB mi m)).\npose coef3 mj mk := p@_mj * (q@_(mi - mj - mk)%MM * r@_mk).\ntransitivity (\\sum_(mj : 'X_{1..n < b} | (mj <= mi)%MM)\n                \\sum_(mk : 'X_{1..n < b} | (mk <= mi - mj)%MM)\n                   coef3 mj mk).\n  by apply/eq_bigr=> /= mj _; rewrite (mcoeff_pmlr b) 1?big_distrr.\npose P (mj : 'X_{1..n < b}) := (mj <= mi)%MM.\nrewrite (exchange_big_dep P) //= {}/P; last first.\n  by move=> mj mk _ /lepm_trans; apply; apply/lem_subr.\napply/eq_bigr=> /= mk /mnm_lepP le_mk_mi.\ntransitivity (\\sum_(mj : 'X_{1..n < b} | (mj <= mi - mk)%MM) coef3 mj mk).\n+ apply/eq_bigl=> m /=.\n  apply/idP/idP => [/andP[/mnm_lepP le1 /mnm_lepP le2]|le1].\n  * apply/mnm_lepP => i; rewrite mnmBE /leq subnBA // addnC -subnBA //.\n    by rewrite -mnmBE; apply/le2.\n  * have le2: (m <= mi)%MM by rewrite (lepm_trans le1) ?lem_subr.\n    rewrite le2; apply/mnm_lepP=> i; rewrite mnmBE /leq.\n    move/mnm_lepP: le2 => le2; rewrite subnBA // addnC.\n    by rewrite -subnBA //; move/mnm_lepP/(_ i): le1; rewrite mnmBE.\nrewrite (mcoeff_pml b) /coef3 1?big_distrl //=.\nby apply/eq_bigr=> mj le_mj_miBk; rewrite !mulrA !submDA addmC.\nQed.\n\nLemma poly_mul1m : left_id 1%:MP mpoly_mul.\nProof.\nmove=> p; apply/mpoly_eqP/esym; rewrite /mpoly_mul /=.\nrewrite msupp1 big_allpairs big_seq1 {1}[p]freeg_mpoly /=.\nby apply: eq_bigr => i _; rewrite mpolyCK !simpm.\nQed.\n\nLemma poly_mulm1 : right_id 1%:MP mpoly_mul.\nProof.\nmove=> p; apply/mpoly_eqP/esym; rewrite /mpoly_mul /=.\nrewrite msupp1 big_allpairs exchange_big big_seq1 {1}[p]freeg_mpoly /=.\nby apply: eq_bigr=> i _; rewrite mpolyCK !simpm.\nQed.\n\nLemma poly_mulDl : left_distributive mpoly_mul +%R.\nProof.\nmove=> p q r; pose_big_enough i.\n  rewrite !(mpoly_mulwE i (msize r)) //=.\n  apply/mpoly_eqP=> /=; rewrite -big_split /=; apply: eq_bigr.\n  by case=> [[i1 /= _] [i2 /= _]] _; rewrite freegUD -mulrDl -mcoeffD.\nby close.\nQed.\n\nLemma poly_mulDr : right_distributive mpoly_mul +%R.\nProof.\nmove=> p q r; pose_big_enough i.\n  rewrite !(mpoly_mulwE (msize p) i) //=.\n  apply/mpoly_eqP=> /=; rewrite -big_split /=; apply: eq_bigr.\n  by case=> [[i1 /= _] [i2 /= _]] _; rewrite freegUD -mulrDr -mcoeffD.\nby close.\nQed.\n\nLemma poly_oner_neq0 : 1%:MP != 0 :> {mpoly R[n]}.\nProof. by rewrite mpolyC_eq oner_eq0. Qed.\n\nDefinition mpoly_ringMixin :=\n  RingMixin poly_mulA poly_mul1m poly_mulm1\n            poly_mulDl poly_mulDr poly_oner_neq0.\nCanonical mpoly_ringType :=\n  Eval hnf in RingType {mpoly R[n]} mpoly_ringMixin.\nCanonical mpolynomial_ringType :=\n  Eval hnf in RingType (mpoly n R) mpoly_ringMixin.\n\nLemma mcoeff1 m : 1@_m = (m == 0%MM)%:R.\nProof. by rewrite mcoeffC mul1r. Qed.\n\nLemma mcoeffM p q m :\n  (p * q)@_m =\n    \\sum_(k : 'X_{1..n < !|m|.+1, !|m|.+1} | m == (k.1 + k.2)%MM)\n      (p@_k.1 * q@_k.2).\nProof. exact: mcoeff_poly_mul. Qed.\n\nLemma mcoeffMr p q m :\n  (p * q)@_m =\n    \\sum_(k : 'X_{1..n < !|m|.+1, !|m|.+1} | m == (k.1 + k.2)%MM)\n      (p@_k.2 * q@_k.1).\nProof.\nrewrite mcoeffM big_cond_mulrn big_pairA/=.\nrewrite exchange_big pair_bigA /= -big_cond_mulrn.\nby apply: eq_bigl=> k /=; rewrite addmC.\nQed.\n\nLemma msuppM_le p q :\n  {subset msupp (p * q) <= [seq (m1 + m2)%MM | m1 <- msupp p, m2 <- msupp q]}.\nProof.\nmove=> m; rewrite -[_ \\in _]negbK -mcoeff_eq0 mcoeffM=> nz_s.\napply/memPn=> /= h; move: nz_s; rewrite big1 ?eqxx //=.\ncase=> m1 m2 /=; pose m'1 : 'X_{1..n} := m1; pose m'2 : 'X_{1..n} := m2.\nmove/eqP=> mE; case: (boolP (m'1 \\in msupp p)); last first.\n  by move/memN_msupp_eq0=> ->; rewrite mul0r.\ncase: (boolP (m'2 \\in msupp q)); last first.\n  by move/memN_msupp_eq0=> ->; rewrite mulr0.\nrewrite {}/m'1 {}/m'2=> m2_in_q m1_in_p; absurd false=> //.\nmove: (h m); rewrite eqxx; apply; apply/allpairsP=> /=.\nexists (m1 : 'X_{1..n}, m2 : 'X_{1..n}) => /=.\nby rewrite m1_in_p m2_in_q /=.\nQed.\n\nLemma mul_mpolyC c p : c%:MP * p = c *: p.\nProof.\nhave [->|nz_c] := eqVneq c 0; first by rewrite scale0r mul0r.\napply/mpoly_eqP=> /=; rewrite big_allpairs msuppC (negbTE nz_c) big_seq1.\nby apply: eq_bigr => i _; rewrite mpolyCK !simpm.\nQed.\n\nLemma mcoeffCM c p m : (c%:MP * p)@_m = c * p@_m.\nProof. by rewrite mul_mpolyC mcoeffZ. Qed.\n\nLemma msuppZ_le (c : R) p : {subset msupp (c *: p) <= msupp p}.\nProof.\nmove=> /= m; rewrite !mcoeff_msupp -mul_mpolyC.\nrewrite mcoeffCM; have [->|//] := eqVneq p@_m 0.\nby rewrite mulr0 eqxx.\nQed.\n\nLemma mpolyC_is_multiplicative : multiplicative (mpolyC n (R := R)).\nProof.\nsplit=> // p q; apply/mpolyP=> m.\nby rewrite mcoeffCM !mcoeffC mulrA.\nQed.\n\nCanonical mpolyC_rmorphism : {rmorphism R -> {mpoly R[n]}} :=\n  AddRMorphism mpolyC_is_multiplicative.\n\nLemma mpolyC1 : mpolyC n 1 = 1.\nProof. exact: rmorph1. Qed.\n\nLemma msize1_polyC p : msize p <= 1 -> p = (p@_0)%:MP.\nProof.\nmove=> le_p_1; apply/mpolyP=> m; rewrite mcoeffC.\ncase: (m =P 0%MM)=> [->|/eqP]; first by rewrite mulr1.\nrewrite mulr0 -mdeg_eq0 => nz_m; rewrite memN_msupp_eq0 //.\nby apply/msize_mdeg_ge; rewrite 1?(@leq_trans 1) // lt0n.\nQed.\n\nLemma msize_poly1P p : reflect (exists2 c, c != 0 & p = c%:MP) (msize p == 1%N).\nProof.\napply: (iffP eqP)=> [pC|[c nz_c ->]]; last by rewrite msizeC nz_c.\nhave def_p: p = (p@_0)%:MP by rewrite -msize1_polyC ?pC.\nby exists p@_0; rewrite // -(mpolyC_eq0 n) -def_p -msize_poly_eq0 pC.\nQed.\n\nLemma mpolyC_nat (k : nat) : (k%:R)%:MP = k%:R :> {mpoly R[n]}.\nProof.\napply/mpolyP=> i; rewrite mcoeffC mcoeffMn mcoeffC.\nby rewrite mul1r commr_nat mulr_natr.\nQed.\n\nLemma mpolyCM : {morph mpolyC n (R := _): p q / p * q}.\nProof. exact: rmorphM. Qed.\n\nLemma mmeasure1 mf : mmeasure mf 1 = 1%N.\nProof. by rewrite mmeasureC oner_eq0. Qed.\n\nLemma msize1 : msize 1 = 1%N.\nProof. exact/mmeasure1. Qed.\n\nLemma mmeasureZ_le mf (p : {mpoly R[n]}) c :\n  mmeasure mf (c *: p) <= mmeasure mf p.\nProof.\nrewrite {1}mmeasureE big_tnth; apply/bigmax_leqP=> /= i _.\nset m := tnth _ _; have: m \\in msupp (c *: p) by apply/mem_tnth.\nby move/msuppZ_le=> /mmeasure_mnm_lt->.\nQed.\n\nLemma mpoly_scaleAl c p q : c *: (p * q) = (c *: p) * q.\nProof. by rewrite -!mul_mpolyC mulrA. Qed.\n\nCanonical mpoly_lalgType :=\n  Eval hnf in LalgType R {mpoly R[n]} mpoly_scaleAl.\nCanonical mpolynomial_lalgType :=\n  Eval hnf in LalgType R (mpoly n R) mpoly_scaleAl.\n\nLemma alg_mpolyC c : c%:A = c%:MP :> {mpoly R[n]}.\nProof. by rewrite -mul_mpolyC mulr1. Qed.\n\nLemma mcoeff0_is_multiplicative :\n  multiplicative (mcoeff 0%MM : {mpoly R[n]} -> R).\nProof.\nsplit=> [p q|]; rewrite ?mpolyCK //.\nrewrite (mcoeff_poly_mul _ _ (k := 1)) ?mdeg0 //.\nrewrite (bigD1 (bm0, bm0)) ?simpm //=; last first.\nrewrite [X in _+X]big1 ?addr0 // => i /andP [] h.\nrewrite eqE /= !bmeqP /=; move/eqP/esym/(congr1 mdeg): h.\nrewrite mdegD [X in _=X]mdeg0 => /eqP; rewrite addn_eq0.\nby rewrite !mdeg_eq0=> /andP [/eqP->/eqP->]; rewrite !eqxx.\nQed.\n\nCanonical mcoeff0_rmorphism  := AddRMorphism mcoeff0_is_multiplicative.\nCanonical mcoeff0_lrmorphism := [lrmorphism of mcoeff 0%MM].\n\nEnd MPolyRing.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyVar.\nContext (n : nat) (R : ringType).\n\nDefinition mpolyX_def (m : 'X_{1..n}) : {mpoly R[n]} := [mpoly << m >>].\n\nFact mpolyX_key : unit. Proof. by []. Qed.\n\nDefinition mpolyX m : {mpoly R[n]} :=\n  locked_with mpolyX_key (mpolyX_def m).\n\nCanonical mpolyX_unlockable m := [unlockable of (mpolyX m)].\n\nDefinition mX (k : 'I_n) : 'X_{1..n} :=\n  nosimpl [multinom (i == k : nat) | i < n].\n\nEnd MPolyVar.\n\nNotation \"'X_[ R , m ]\" := (@mpolyX _ R m).\nNotation \"'X_[ m ]\"     := (@mpolyX _ _ m).\nNotation \"'X_ i\"        := (@mpolyX _ _ U_(i)).\n\n(* -------------------------------------------------------------------- *)\nSection MPolyVarTheory.\nContext (n : nat) (R : ringType).\nImplicit Types (p q r : {mpoly R[n]}) (m : 'X_{1..n}).\n\nLocal Notation \"'X_[ m ]\" := (@mpolyX n R m).\n\nLemma msuppX m : msupp 'X_[m] = [:: m].\nProof. by rewrite unlock /msupp domU1. Qed.\n\nLemma mem_msuppXP m m' : reflect (m = m') (m' \\in msupp 'X_[m]).\nProof. by rewrite msuppX mem_seq1; apply: (iffP eqP). Qed.\n\nLemma mcoeffX m k : 'X_[m]@_k = (m == k)%:R.\nProof. by rewrite unlock /mpolyX_def mcoeff_MPoly coeffU mul1r. Qed.\n\nLemma mcoeffXU (i j : 'I_n) : ('X_i : {mpoly R[n]})@_U_(j) = (i == j)%:R.\nProof. by rewrite mcoeffX eq_mnm1. Qed.\n\nLemma mmeasureX mf m : mmeasure mf 'X_[R, m] = (mf m).+1.\nProof. by rewrite mmeasureE msuppX big_seq1. Qed.\n\nLemma msizeX m : msize 'X_[R, m] = (mdeg m).+1.\nProof. exact/mmeasureX. Qed.\n\nLemma msupp_rem (p : {mpoly R[n]}) m :\n  perm_eq (msupp (p - p@_m *: 'X_[m])) (rem m (msupp p)).\nProof.\ncase: (boolP (m \\in msupp p)) => h.\n  apply/uniq_perm; rewrite ?rem_uniq //.\n  move=> m'; rewrite mem_rem_uniq // inE /=.\n  rewrite !mcoeff_msupp mcoeffB mcoeffZ mcoeffX.\n  case: (eqVneq m' m) => [->|] /=.\n  by rewrite mulr1 subrr eqxx. by rewrite mulr0 subr0.\nhave/rem_id -> := h; move: h.\nrewrite mcoeff_msupp negbK=> /eqP ->.\nby rewrite scale0r subr0.\nQed.\n\nLemma mpolyX0 : 'X_[0] = 1.\nProof. by apply/mpolyP=> m; rewrite mcoeffX mcoeffC mul1r eq_sym. Qed.\n\nLemma mpolyXD m1 m2 : 'X_[m1 + m2] = 'X_[m1] * 'X_[m2] :> {mpoly R[n]}.\nProof.\napply/mpoly_eqP; rewrite /GRing.mul /= !msuppX big_seq1 /=.\nby rewrite !mcoeffX !eqxx !simpm unlock /=.\nQed.\n\nLemma mpolyX_prod s P :\n  \\prod_(i <- s | P i) 'X_[i] = 'X_[\\sum_(i <- s | P i) i].\nProof.\nelim: s => [|i s ih]; first by rewrite !big_nil mpolyX0.\nby rewrite !big_cons; case: (P i); rewrite ?mpolyXD ih.\nQed.\n\nLemma mpolyXn m i : 'X_[m] ^+ i = 'X_[m *+ i].\nProof.\nelim: i=> [|i ih]; first by rewrite expr0 mulm0n mpolyX0.\nby rewrite mulmS mpolyXD -ih exprS.\nQed.\n\nLemma mprodXnE {I} F P (m : I -> nat) (r : seq _) :\n    \\prod_(i <- r | P i) 'X_[R, F i] ^+ m i\n  = 'X_[\\sum_(i <- r | P i) (F i *+ m i)].\nProof.\nelim/big_rec2: _ => /= [|i m' p Pi ->].\n  by rewrite mpolyX0. by rewrite ?(mpolyXD, mpolyXn).\nQed.\n\nLemma mprodXE {I} (F : I -> 'X_{1..n}) P (r : seq _) :\n  \\prod_(i <- r | P i) 'X_[R, F i] = 'X_[\\sum_(i <- r | P i) F i].\nProof.\nrewrite (eq_bigr (fun i => 'X_[R, F i] ^+ 1)) => [|i _].\n  by rewrite mprodXnE. by rewrite expr1.\nQed.\n\nLemma mpolyXE (s : 'S_n) m : 'X_[m] = \\prod_(i < n) 'X_(s i) ^+ m (s i).\nProof.\nrewrite {1}[m](multinomUE s) -mprodXE.\nby apply/eq_bigr=> i _; rewrite mpolyXn.\nQed.\n\nLemma mpolyXE_id m : 'X_[m] = \\prod_(i < n) 'X_i ^+ m i.\nProof. by rewrite (mpolyXE 1); apply/eq_bigr=> /= i _; rewrite perm1. Qed.\n\nLemma mcoeffXn m i k : ('X_[m] ^+ i)@_k = ((m *+ i)%MM == k)%:R.\nProof. by rewrite mpolyXn mcoeffX. Qed.\n\nLemma mpolyE p : p = \\sum_(m <- msupp p) (p@_m *: 'X_[m]).\nProof.\napply/mpolyP=> m; rewrite {1}[p]freeg_mpoly /= mcoeff_MPoly.\nrewrite !raddf_sum /=; apply/eq_bigr=> i _.\nby rewrite -mul_mpolyC mcoeffCM mcoeffX coeffU.\nQed.\n\nLemma mpolywE k p : msize p <= k ->\n  p = \\sum_(m : 'X_{1..n < k}) (p@_m *: 'X_[m]).\nProof.\nmove=> lt_pk; pose I := [subFinType of 'X_{1..n < k}].\nrewrite {1}[p]mpolyE (big_mksub I) //=; first last.\n  by move=> x /msize_mdeg_lt /leq_trans; apply.\n  by rewrite msupp_uniq.\nby rewrite big_rmcond //= => i; move/memN_msupp_eq0 ->; rewrite scale0r.\nQed.\n\nLemma mpolyME p q :\n  p * q = \\sum_(m <- msupp p @@ msupp q) (p@_m.1 * q@_m.2) *: 'X_[m.1 + m.2].\nProof.\napply/mpolyP=> m; rewrite {1}/GRing.mul /= mcoeff_MPoly.\nrewrite !raddf_sum; apply/eq_bigr=> i _ /=.\nby rewrite coeffU -mul_mpolyC mcoeffCM mcoeffX.\nQed.\n\nLemma mpolywME p q k : msize p <= k -> msize q <= k ->\n  p * q = \\sum_(m : 'X_{1..n < k, k}) (p@_m.1 * q@_m.2) *: 'X_[m.1 + m.2].\nProof.\nmove=> ltpk ltqk; rewrite mpolyME; pose I := [subFinType of 'X_{1..n < k}].\nrewrite big_allpairs (big_mksub I) /=; last first.\n  by move=> m /msize_mdeg_lt /leq_trans; apply. by rewrite msupp_uniq.\nrewrite big_rmcond /= => [|i]; last first.\n  by move/memN_msupp_eq0=> ->; rewrite big1 // => j _; rewrite mul0r scale0r.\nrewrite big_pairA /=; apply/eq_bigr=> i _; rewrite (big_mksub I)/=; last first.\n- by move=> m /msize_mdeg_lt /leq_trans; apply.\n- by rewrite msupp_uniq.\nrewrite big_rmcond /= => [//|j].\nby move/memN_msupp_eq0=> ->; rewrite mulr0 scale0r.\nQed.\n\nLemma commr_mpolyX m p : GRing.comm p 'X_[m].\nProof.\napply/mpolyP=> k; rewrite mcoeffM mcoeffMr.\nby apply/eq_bigr=> /= i _; rewrite !mcoeffX GRing.commr_nat.\nQed.\n\nLemma mcoeffMX p m k : (p * 'X_[m])@_(m + k) = p@_k.\nProof.\nrewrite commr_mpolyX mpolyME msuppX big_allpairs.\nrewrite big_seq1 [X in _=X@__]mpolyE !raddf_sum /=.\nby apply/eq_bigr=> i _; rewrite !mcoeffZ !mcoeffX eqxx mul1r eqm_add2l.\nQed.\n\nLemma msuppMX p m :\n  perm_eq (msupp (p * 'X_[m])) [seq (m + m')%MM | m' <- msupp p].\nProof.\napply/uniq_perm=> //; first rewrite map_inj_uniq //.\n  by move=> m1 m2 /=; rewrite ![(m + _)%MM]addmC; apply: addIm.\nmove=> m'; apply/idP/idP; last first.\n  case/mapP=> mp mp_in_p ->; rewrite mcoeff_msupp.\n  by rewrite mcoeffMX -mcoeff_msupp.\nmove/msuppM_le; rewrite msuppX => /allpairsP [[p1 p2]] /=.\nrewrite mem_seq1; case=> p1_in_p /eqP <- ->.\nby apply/mapP; exists p1; last rewrite addmC.\nQed.\n\nLemma msuppMCX c m : c != 0 -> msupp (c *: 'X_[m]) = [:: m].\nProof.\nmove=> nz_c; rewrite -mul_mpolyC; apply/perm_small_eq=> //.\nby rewrite (permPl (msuppMX _ _)) msuppC (negbTE nz_c) /= addm0.\nQed.\n\nLemma msupp_sumX (r : seq 'X_{1..n}) (f : 'X_{1..n} -> R) :\n  uniq r -> {in r, forall m, f m != 0} ->\n  perm_eq (msupp (\\sum_(m <- r) (f m) *: 'X_[m])) r.\nProof.\nmove=> uq_r h; set F := fun m => (f m *: 'X_[m] : {mpoly R[n]}).\nhave msFm m: m \\in r -> msupp (f m *: 'X_[m]) = [:: m].\n  by move=> m_in_r; rewrite msuppMCX // h.\nrewrite (permPl (msupp_sum xpredT _ _)) //.\n  move/eq_in_map: msFm; rewrite filter_predT=> ->.\n  set s := flatten _; have ->: s = r => //.\n  by rewrite {}/s; elim: {uq_r h} r=> //= m r ->.\nmove=> m1 m2 /h nz_fm1 /h nz_fm2 nz_m1m2 m /=.\nrewrite !msuppMCX // !mem_seq1; case: eqP=> //= ->.\nby rewrite (negbTE nz_m1m2).\nQed.\n\nLemma mcoeff_mpoly (E : 'X_{1..n} -> R) m k : mdeg m < k ->\n  (\\sum_(m : 'X_{1..n < k}) (E m *: 'X_[m]))@_m = E m.\nProof.\nmove=> lt_mk; rewrite raddf_sum (bigD1 (Sub m lt_mk)) //=.\nrewrite big1 ?addr0; last first.\n  case=> i /= lt_ik; rewrite eqE /= => ne_im.\n  by rewrite mcoeffZ mcoeffX (negbTE ne_im) mulr0.\nby rewrite mcoeffZ mcoeffX eqxx mulr1.\nQed.\n\nLemma MPoly_is_linear: linear (@MPoly n R).\nProof. by move=> c p q; apply/mpoly_eqP. Qed.\n\nCanonical MPoly_additive := Additive MPoly_is_linear.\nCanonical MPoly_linear   := Linear   MPoly_is_linear.\n\nLemma MPolyU c m : MPoly << c *g m >> = c *: 'X_[m].\nProof.\napply/mpolyP=> k; rewrite mcoeff_MPoly.\nby rewrite mcoeffZ mcoeffX coeffU.\nQed.\n\nLemma mpolyrect (P : {mpoly R[n]} -> Type) :\n     P 0\n  -> (forall c m p, m \\notin msupp p -> c != 0 -> P p -> P (c *: 'X_[m] + p))\n  -> forall p, P p.\nProof.\nmove=> h0 hS [p] /=; elim/freeg_rect_dom0: p => [|c q m mdom nz_c /hS h].\n  by rewrite raddf0.\nby rewrite raddfD /= MPolyU; apply: h.\nQed.\n\nLemma mpolyind (P : {mpoly R[n]} -> Prop) :\n     P 0\n  -> (forall c m p, m \\notin msupp p -> c != 0 -> P p -> P (c *: 'X_[m] + p))\n  -> forall p, P p.\nProof. exact: mpolyrect. Qed.\n\nEnd MPolyVarTheory.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyLead.\nContext (n : nat) (R : ringType).\nImplicit Types (p q r : {mpoly R[n]}).\n\nDefinition mlead p : 'X_{1..n} := (\\join_(m <- msupp p) m)%O.\n\nLemma mleadC (c : R) : mlead c%:MP = 0%MM.\nProof.\nrewrite /mlead msuppC; case: eqP=> _.\n  by rewrite big_nil. by rewrite big_seq1.\nQed.\n\nLemma mlead0 : mlead 0 = 0%MM.\nProof. by rewrite mleadC. Qed.\n\nLemma mlead1 : mlead 1 = 0%MM.\nProof. by rewrite mleadC. Qed.\n\nLemma mleadXm m : mlead 'X_[m] = m.\nProof. by rewrite /mlead msuppX big_seq1. Qed.\n\nLemma mlead_supp p : p != 0 -> mlead p \\in msupp p.\nProof.\nrewrite -msupp_eq0 /mlead => nz_p; case: bigjoinP => //; first exact: le_total.\nby case: (msupp p) nz_p.\nQed.\n\nLemma mlead_deg p : p != 0 -> (mdeg (mlead p)).+1 = msize p.\nProof.\nmove=> /mlead_supp lc_in_p; rewrite /mlead msizeE mdeg_bigmax.\nhave: msupp p != [::] by case: (msupp p) lc_in_p.\nelim: (msupp p)=> [|m [|m' r] ih] // _; first by rewrite !big_seq1.\nby rewrite big_cons -maxnSS {}ih // !big_cons.\nQed.\n\nLemma msupp_le_mlead p m : m \\in msupp p -> (m <= mlead p)%O.\nProof. by move=> mp; apply/joins_sup_seq. Qed.\n\nLemma mleadN p : mlead (-p) = mlead p.\nProof.\nhave [->|nz_p] := eqVneq p 0; first by rewrite oppr0.\nby rewrite /mlead (perm_big _ (msuppN p)).\nQed.\n\nLemma mleadD_le p q : (mlead (p + q) <= mlead p `|` mlead q)%O.\nProof.\nhave [->|] := eqVneq (p+q) 0; first by rewrite mlead0 le0x.\nmove/mlead_supp/msuppD_le; rewrite mem_cat => /orP[].\n+ by move/msupp_le_mlead=> h; apply/(le_trans h)/leUl.\n+ by move/msupp_le_mlead=> h; apply/(le_trans h)/leUr.\nQed.\n\nLemma mleadB_le p q : (mlead (p - q) <= mlead p `|` mlead q)%O.\nProof. by rewrite -(mleadN q); apply/mleadD_le. Qed.\n\nLemma mleadc_eq0 p : (p@_(mlead p) == 0) = (p == 0).\nProof.\napply/idP/idP => [|/eqP->]; last by rewrite mcoeff0.\nby case: (p =P 0) => // /eqP /mlead_supp; rewrite mcoeff_eq0 => ->.\nQed.\n\nLemma mcoeff_gt_mlead p m : (mlead p < m)%O -> p@_m = 0.\nProof.\nmove=> lt_lcp_m; apply/eqP; rewrite mcoeff_eq0; apply/negP.\nby move/msupp_le_mlead; rewrite leNgt lt_lcp_m.\nQed.\n\nLemma mleadDr (p1 p2 : {mpoly R[n]}) :\n  (mlead p1 < mlead p2)%O -> mlead (p1 + p2) = mlead p2.\nProof.\nmove=> lt_p1p2. apply/le_anti.\nmove/ltW/join_r: (lt_p1p2) (mleadD_le p1 p2) => -> -> /=.\nrewrite leNgt; apply/negP=> /mcoeff_gt_mlead.\nrewrite mcoeffD mcoeff_gt_mlead // add0r => /eqP.\nrewrite mleadc_eq0=> /eqP z_p2; move: lt_p1p2.\nby rewrite z_p2 mlead0 ltx0.\nQed.\n\nLemma mleadDl (p1 p2 : {mpoly R[n]}) :\n  (mlead p2 < mlead p1)%O -> mlead (p1 + p2) = mlead p1.\nProof. by move/mleadDr; rewrite addrC => ->. Qed.\n\nLemma mleadD (p1 p2 : {mpoly R[n]}) :\n  mlead p1 != mlead p2 -> mlead (p1 + p2) = (mlead p1 `|` mlead p2)%O.\nProof. by case: ltgtP => [/mleadDr ->|/mleadDl ->|->] //; rewrite eqxx. Qed.\n\nLemma mlead_sum_le {T} (r : seq T) P F :\n  (mlead (\\sum_(p <- r | P p) F p) <= \\join_(p <- r | P p) mlead (F p))%O.\nProof.\nelim/big_rec2: _ => /= [|x m p Px le]; first by rewrite mlead0.\nby apply/(le_trans (mleadD_le _ _))/leU2.\nQed.\n\nLemma mlead_sum {T} (r : seq T) P F :\n  uniq [seq mlead (F x) | x <- r & P x] ->\n  mlead (\\sum_(p <- r | P p) F p) = (\\join_(p <- r | P p) mlead (F p))%O.\nProof.\nelim: r=> [|p r ih]; first by rewrite !big_nil mlead0.\nrewrite !big_cons /=; case: (P p)=> //= /andP[Fp_ml uq_ml].\npose Q i := P (nth p r i); rewrite !(big_nth p) -!(big_filter _ Q).\nset itg := [seq _ <- _ | _]; have [/size0nil->|nz_szr] := eqVneq (size itg) 0%N.\n  by rewrite !big_nil joinx0 addr0.\nmove: {ih}(ih uq_ml); rewrite !(big_nth p) -!(big_filter _ Q) -/itg.\nmove=> ih; rewrite mleadD ih //.\ncase: bigjoinP; [exact: le_total | by rewrite /nilp; case: eqP nz_szr |].\nmove=> /= x; rewrite mem_filter => /andP[Px].\nrewrite mem_iota add0n subn0 => /andP[_ lt_x_szr].\napply/contra: Fp_ml=> /eqP-> {Q itg uq_ml nz_szr ih}.\nelim: r x Px lt_x_szr=> [|y r ih] [|x] //=.\n  by move=> -> /=; rewrite mem_head.\nrewrite ltnS=> Px lt_x_szr; case: (P y)=> /=.\n  by rewrite 1?mem_behead //=; apply/ih. by apply/ih.\nQed.\n\nLemma mleadM_le p q : (mlead (p * q) <= (mlead p + mlead q)%MM)%O.\nProof.\nhave [->|] := eqVneq (p * q) 0; first by rewrite mlead0 le0x.\nmove/mlead_supp/msuppM_le/allpairsP => [[m1 m2] /=] [m1_in_p m2_in_q ->].\nby apply/lem_add; apply/msupp_le_mlead.\nQed.\n\nLemma mlead_prod_le T (r : seq T) (P : pred T) F :\n  (mlead (\\prod_(p <- r | P p) F p) <= (\\sum_(p <- r | P p) mlead (F p))%MM)%O.\nProof.\nelim/big_rec2: _ => /= [|x m p Px ih]; first by rewrite mlead1.\nby apply/(le_trans (mleadM_le (F x) p)); apply/lem_add.\nQed.\n\nNotation mleadc p := (p@_(mlead p)).\n\nLemma mleadcC (c : R) : mleadc c%:MP_[n] = c.\nProof. by rewrite mleadC mcoeffC eqxx mulr1. Qed.\n\nLemma mleadc0 : mleadc (0 : {mpoly R[n]}) = 0.\nProof. by rewrite mleadcC. Qed.\n\nLemma mleadc1 : mleadc (1 : {mpoly R[n]}) = 1.\nProof. by rewrite mleadcC. Qed.\n\nLemma mleadcM p q :\n  (p * q)@_(mlead p + mlead q) = mleadc p * mleadc q.\nProof.\nhave [->|nz_p] := eqVneq p 0; first by rewrite mleadc0 !mul0r mcoeff0.\nhave [->|nz_q] := eqVneq q 0; first by rewrite mleadc0 !mulr0 mcoeff0.\nrewrite mpolyME (bigD1_seq (mlead p, mlead q)) /=; first last.\n+ by rewrite allpairs_uniq => // -[? ?] [].\n+ by rewrite allpairs_f// !mlead_supp.\nrewrite mcoeffD mcoeffZ mcoeffX eqxx mulr1.\nrewrite big_seq_cond raddf_sum /= big1 ?addr0 //.\ncase=> m1 m2; rewrite in_allpairs//= -andbA; case/and3P.\nmove=> m1_in_p m2_in_q ne_m_lc; rewrite mcoeffZ mcoeffX.\nmove/msupp_le_mlead: m1_in_p; move/msupp_le_mlead: m2_in_q.\nrewrite le_eqVlt => /predU1P[m2E|]; last first.\n  by move=> lt /lemc_lt_add /(_ lt) /lt_eqF ->; rewrite mulr0.\nmove: ne_m_lc; rewrite m2E xpair_eqE eqxx andbT.\nrewrite le_eqVlt=> /negbTE -> /=; rewrite eqm_add2r.\nby move/lt_eqF=> ->; rewrite mulr0.\nQed.\n\nLemma mleadcMW p q (mp mq : 'X_{1..n}) :\n     (mlead p <= mp)%O -> (mlead q <= mq)%O\n  -> (p * q)@_(mp + mq)%MM = p@_mp * q@_mq.\nProof.\ncase: (boolP ((mlead p < mp) || (mlead q < mq)))%O; last first.\n  by case: ltgtP => // <-; case: ltgtP => // <- _ _ _; apply: mleadcM.\nmove=> lt_lm lep leq; have lt_lmD: ((mlead p + mlead q)%MM < (mp + mq)%MM)%O.\n  by case/orP: lt_lm=> lt; [apply/ltmc_le_add | apply/lemc_lt_add].\nmove/(le_lt_trans (mleadM_le p q))/mcoeff_gt_mlead: lt_lmD.\nby case/orP: lt_lm=> /mcoeff_gt_mlead ->; rewrite ?(mul0r, mulr0).\nQed.\n\nLemma mleadc_prod T (r : seq T) (P : pred T) (F : T -> {mpoly R[n]}) :\n     (\\prod_(p <- r | P p) F p)@_(\\sum_(p <- r | P p) mlead (F p))%MM\n  =  \\prod_(p <- r | P p) mleadc (F p).\nProof.\nelim: r => [|p r ih]; first by rewrite !big_nil mcoeff1 eqxx.\nrewrite !big_cons; case: (P p); rewrite // mleadcMW //.\n  by rewrite ih. by apply/mlead_prod_le.\nQed.\n\nLemma mleadcZ c p : (c *: p)@_(mlead p) = c * mleadc p.\nProof. by rewrite mcoeffZ. Qed.\n\nLemma mleadM_proper p q : mleadc p * mleadc q != 0 ->\n  mlead (p * q) = (mlead p + mlead q)%MM.\nProof.\nmove: (mleadM_le p q); rewrite le_eqVlt => /predU1P[->//|].\nrewrite -mleadcM mcoeff_eq0 negbK => ltm /msupp_le_mlead lem.\nby move: (lt_le_trans ltm lem); rewrite ltxx.\nQed.\n\nLemma mleadcM_proper p q : mleadc p * mleadc q != 0 ->\n  mleadc (p * q) = mleadc p * mleadc q.\nProof. by move/mleadM_proper=> ->; rewrite mleadcM. Qed.\n\nLemma lreg_mleadc p : GRing.lreg (mleadc p) -> GRing.lreg p.\nProof.\nmove/mulrI_eq0=> reg_p; apply/mulrI0_lreg=> q /eqP.\napply/contraTeq => nz_q; rewrite -mleadc_eq0.\nby rewrite mleadcM_proper reg_p mleadc_eq0.\nQed.\n\nSection MLeadProd.\nContext (T : eqType) (r : seq T) (P : pred T) (F : T -> {mpoly R[n]}).\n\nLemma mlead_prod_proper :\n  (forall x, x \\in r -> P x -> GRing.lreg (mleadc (F x))) ->\n  mlead (\\prod_(p <- r | P p) F p) = (\\sum_(p <- r | P p) mlead (F p))%MM.\nProof.\npose Q (s : seq T) := forall x, x \\in s -> P x -> GRing.lreg (mleadc (F x)).\nrewrite -/(Q r); elim: r => [|x s ih] h; first by rewrite !big_nil mleadC.\nhave lreg_s: Q s.\n  by move=> y y_in_s; apply: (h y); rewrite mem_behead.\nrewrite !big_cons; case: (boolP (P x))=> Px; last exact/ih.\nhave lreg_x := (h x (mem_head _ _) Px).\nrewrite mleadM_proper; first by rewrite ih.\nby rewrite mulrI_eq0 ?ih // mleadc_prod; apply/lreg_neq0/lreg_prod.\nQed.\n\nLemma mleadc_prod_proper :\n  (forall x, x \\in r -> P x -> GRing.lreg (mleadc (F x))) ->\n  mleadc (\\prod_(p <- r | P p) F p) = \\prod_(p <- r | P p) mleadc (F p).\nProof. by move/mlead_prod_proper=> ->; rewrite mleadc_prod. Qed.\n\nEnd MLeadProd.\n\nLemma mleadX_le p k : (mlead (p ^+ k) <= (mlead p *+ k)%MM)%O.\nProof.\nrewrite -[k](card_ord k) -prodr_const /mnm_muln.\nby rewrite Monoid.iteropE -big_const; apply/mlead_prod_le.\nQed.\n\nLemma mleadcX p k : (p ^+ k)@_(mlead p *+ k) = (mleadc p) ^+ k.\nProof.\nrewrite -[k](card_ord k) -prodr_const /mnm_muln.\nby rewrite Monoid.iteropE -big_const mleadc_prod prodr_const.\nQed.\n\nLemma mleadX_proper p k : GRing.lreg (mleadc p) ->\n  mlead (p ^+ k) = (mlead p *+ k)%MM.\nProof.\nmove=> h; rewrite -[k](card_ord k) -prodr_const.\nrewrite /mnm_muln Monoid.iteropE -big_const.\nby apply/mlead_prod_proper=> /= i _ _.\nQed.\n\nLemma mleadcX_proper p k : GRing.lreg (mleadc p) ->\n  mleadc (p ^+ k) = mleadc p ^+ k.\nProof.\nmove=> h; rewrite -[k](card_ord k) -!prodr_const.\nby apply/mleadc_prod_proper=> /= i _ _.\nQed.\n\nLemma msizeM_le (p q : {mpoly R[n]}) :\n  msize (p * q) <= (msize p + msize q).+1.\nProof.\nhave [->|nz_p ] := eqVneq p 0; first by rewrite mul0r msize0.\nhave [->|nz_q ] := eqVneq q 0; first by rewrite mulr0 msize0.\nhave [->|nz_pq] := eqVneq (p * q) 0; first by rewrite msize0.\nrewrite -!mlead_deg // !(addSn, addnS) 2?ltnW // !ltnS.\nby have /lemc_mdeg := mleadM_le p q; rewrite mdegD.\nQed.\n\nLemma msizeM_proper p q : mleadc p * mleadc q != 0 ->\n   msize (p * q) = (msize p + msize q).-1.\nProof.\nhave [->|nz_p ] := eqVneq p 0; first by rewrite mleadc0 mul0r eqxx.\nhave [->|nz_q ] := eqVneq q 0; first by rewrite mleadc0 mulr0 eqxx.\nmove=> h; rewrite -?[msize p]mlead_deg -?[msize q]mlead_deg //.\nrewrite !(addSn, addnS) -mdegD /= -mleadM_proper //.\nrewrite mlead_deg //; apply/negP; pose m := (mlead p + mlead q)%MM.\nmove/eqP/(congr1 (mcoeff m)); rewrite mleadcM mcoeff0.\nby move/eqP; rewrite (negbTE h).\nQed.\n\nLemma mleadZ_le c p : (mlead (c *: p) <= mlead p)%O.\nProof.\nhave [->|] := eqVneq (c *: p) 0; first by rewrite mlead0 le0x.\nby move/mlead_supp/msuppZ_le/msupp_le_mlead.\nQed.\n\nLemma mleadZ_proper c p : c * mleadc p != 0 -> mlead (c *: p) = mlead p.\nProof.\nmove: (mleadZ_le c p); rewrite le_eqVlt => /predU1P[->//|].\nrewrite -mleadcZ mcoeff_eq0 negbK => ltm /msupp_le_mlead lem.\nby move: (lt_le_trans ltm lem); rewrite ltxx.\nQed.\n\nLemma ltm_mleadD p (q := p - p@_(mlead p) *: 'X_[mlead p]) :\n    p != 0 -> q != 0 ->  (mlead q < mlead p)%O.\nProof.\nmove=> Zp Zq; have: mlead q \\in (rem (mlead p) (msupp p)).\n  by rewrite -(perm_mem (msupp_rem p _)) // mlead_supp.\nrewrite (rem_filter _ (msupp_uniq p)) mem_filter /= => /andP[h].\nsuff: (mlead q <= mlead p)%O by rewrite le_eqVlt (negPf h).\napply: le_trans (mleadB_le _ _) _; rewrite leUx lexx /=.\nby rewrite (le_trans (mleadZ_le _ _)) // mleadXm.\nQed.\n\nLemma msizeZ_le p c : msize (c *: p) <= msize p.\nProof. exact: mmeasureZ_le. Qed.\n\nLemma msizeZ_proper (p : {mpoly R[n]}) c :\n  c * mleadc p != 0 -> msize (c *: p) = msize p.\nProof.\nhave [->|nz_p] := eqVneq p 0; first by rewrite mleadc0 mulr0 eqxx.\nhave [->|nz_c] := eqVneq c 0; first by rewrite mul0r eqxx.\nmove=> h; rewrite -[msize p]mlead_deg // -(mleadZ_proper h).\nrewrite mlead_deg //; pose m := (mlead p); apply/negP.\nmove/eqP/(congr1 (mcoeff m)); rewrite mcoeffZ mcoeff0.\nby move/eqP; rewrite (negbTE h).\nQed.\n\nLemma mleadrect (P : {mpoly R[n]} -> Type) :\n  (forall p, (forall q, (mlead q < mlead p)%O -> P q) -> P p) -> forall p, P p.\nProof.\nmove=> ih p; move: {2}(mlead p) (lexx (mlead p))=> m.\nelim/(ltmwf (n := n)): m p=> m1 wih p lt_pm1; apply/ih=> q lt_pq.\nby apply/(wih (mlead q)); first exact: lt_le_trans lt_pq _.\nQed.\n\nEnd MPolyLead.\n\nNotation mleadc p := (p@_(mlead p)).\n\n(* -------------------------------------------------------------------- *)\nSection MPolyLast.\nContext {R : ringType} {n : nat}.\n\nDefinition mlast (p : {mpoly R[n]}) : 'X_{1..n} :=\n  head 0%MM (sort <=%O (msupp p)).\n\nLemma mlast0 : mlast 0 = 0%MM.\nProof. by rewrite /mlast msupp0. Qed.\n\nLemma mlast_supp p : p != 0 -> mlast p \\in msupp p.\nProof.\nrewrite -msupp_eq0 /mlast; move: (msupp p) => s nz_s.\nrewrite -(perm_mem (permEl (perm_sort <=%O%O _))).\nby rewrite -nth0 mem_nth // size_sort lt0n size_eq0.\nQed.\n\nLemma mlast_lemc m p : m \\in msupp p -> (mlast p <= m)%O.\nProof.\nrewrite /mlast -nth0; set s := sort _ _.\nhave: perm_eq s (msupp p) by apply/permEl/perm_sort.\nhave: sorted <=%O%O s by apply/sort_sorted/le_total.\ncase: s => /= [_|m' s srt_s]; first rewrite perm_sym.\n  by move/perm_small_eq=> -> //.\nmove/perm_mem => <-; rewrite in_cons => /predU1P[->//|].\nelim: s m' srt_s => //= m'' s ih m' /andP[le_mm' /ih {}ih].\nby rewrite in_cons => /predU1P[->//|/ih /(le_trans le_mm')].\nQed.\n\nLemma mlastE (p : {mpoly R[n]}) (m  : 'X_{1..n}) :\n     m \\in msupp p\n  -> (forall m' : 'X_{1..n}, m' \\in msupp p -> (m <= m')%O)\n  -> mlast p = m.\nProof.\nmove=> mp le; apply/le_anti; rewrite mlast_lemc //=.\nby apply/le; rewrite mlast_supp // -msupp_eq0; case: msupp mp.\nQed.\n\nLemma mcoeff_lt_mlast p m : (m < mlast p)%O -> p@_m = 0.\nProof.\nmove=> le; case/boolP: (m \\in msupp p).\n  by move/mlast_lemc/(lt_le_trans le); rewrite ltxx.\nby rewrite mcoeff_msupp negbK => /eqP.\nQed.\n\nEnd MPolyLast.\n\n(* -------------------------------------------------------------------- *)\nSection MPoly0.\nContext (R : ringType).\n\nLemma mpolyKC : cancel (@mcoeff 0 R 0%MM) (@mpolyC 0 R).\nProof.\n  move=> p; apply/mpolyP=> m; rewrite mcoeffC.\n  case: (m =P 0%MM)=> [->|/eqP]; first by rewrite mulr1.\n  by apply/contraNeq=> _; apply/eqP/mnmP; case.\nQed.\n\nEnd MPoly0.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyDeriv.\nContext (n : nat) (R : ringType).\nImplicit Types (p q r : {mpoly R[n]}) (m : 'X_{1..n}).\n\nDefinition mderiv (i : 'I_n) p :=\n  \\sum_(m <- msupp p) ((m i)%:R * p@_m) *: 'X_[m - U_(i)].\n\nLocal Notation \"p ^`M ( i )\" := (mderiv i p).\n\nLemma mderivwE i p k : msize p <= k ->\n  p^`M(i) = \\sum_(m : 'X_{1..n < k}) ((m i)%:R * p@_m) *: 'X_[m - U_(i)].\nProof.\npose I := [subFinType of 'X_{1..n < k}].\nmove=> le_pk; rewrite /mderiv (big_mksub I) /=; first last.\n  by move=> x /msize_mdeg_lt/leq_trans/(_ le_pk).\n  by rewrite msupp_uniq.\nrewrite big_rmcond //= => j /memN_msupp_eq0 ->.\nby rewrite mulr0 scale0r.\nQed.\nArguments mderivwE [i p].\n\nLemma mcoeff_deriv i m p : p^`M(i)@_m = p@_(m + U_(i)) *+ (m i).+1.\nProof.\npose_big_enough j; first rewrite {2}[p](mpolywE (k := j)) //.\n  rewrite !(mderivwE j) // !raddf_sum -sumrMnl; apply/eq_bigr.\n  move=> /= [k /= _] _; rewrite !mcoeffZ !mcoeffX.\n  case: (k =P m + U_(i))%MM=> [{1 3}->|].\n    by rewrite mnmDE mnm1E eqxx addn1 addmK eqxx !simpm mulr_natl.\n  rewrite !simpm mul0rn; have [->|nz_mi] := (eqVneq (k i) 0%N).\n    by rewrite !simpm.\n  case: eqP=> [{1}<-|]; rewrite ?simpm //.\n  rewrite submK //; apply/mnm_lepP => l; rewrite mnm1E.\n  by case: (i =P l) nz_mi=> // ->; rewrite -lt0n.\nby close.\nQed.\n\nLemma mderiv_is_linear i : linear (mderiv i).\nProof.\nmove=> c p q; pose_big_enough j; first rewrite !(mderivwE j) //.\n  rewrite scaler_sumr -big_split /=; apply/eq_bigr=> k _.\n  rewrite !scalerA -scalerDl; congr (_ *: _).\n  by rewrite mcoeffD mcoeffZ mulrDr !mulrA commr_nat.\nby close.\nQed.\n\nCanonical mderiv_additive i := Additive (mderiv_is_linear i).\nCanonical mderiv_linear   i := Linear   (mderiv_is_linear i).\n\nLemma mderiv0 i : mderiv i 0 = 0.\nProof. exact: raddf0. Qed.\n\nLemma mderivC i c : mderiv i c%:MP = 0.\nProof.\napply/mpolyP=> m; rewrite mcoeff0 mcoeff_deriv mcoeffC.\nby rewrite mnmD_eq0 mnm1_eq0 andbF mulr0 mul0rn.\nQed.\n\nLemma mderivX i m : mderiv i 'X_[m] = (m i)%:R *: 'X_[m - U_(i)].\nProof. by rewrite /mderiv msuppX big_seq1 mcoeffX eqxx mulr1. Qed.\n\nLemma commr_mderivX i m p : GRing.comm p ('X_[m])^`M(i).\nProof.\nrewrite /GRing.comm mderivX -mul_mpolyC mpolyC_nat.\nby rewrite -{1}commr_nat mulrA commr_nat commr_mpolyX mulrA.\nQed.\n\nLemma mderivN i : {morph mderiv i: x / - x}.\nProof. exact: raddfN. Qed.\n\nLemma mderivD i : {morph mderiv i: x y / x + y}.\nProof. exact: raddfD. Qed.\n\nLemma mderivB i : {morph mderiv i: x y / x - y}.\nProof. exact: raddfB. Qed.\n\nLemma mderivMn i k : {morph mderiv i: x / x *+ k}.\nProof. exact: raddfMn. Qed.\n\nLemma mderivMNn i k : {morph mderiv i: x / x *- k}.\nProof. exact: raddfMNn. Qed.\n\nLemma mderivZ i c p : (c *: p)^`M(i) = c *: p^`M(i).\nProof. by rewrite linearZ. Qed.\n\nLemma mderiv_mulC i c p : (c%:MP * p)^`M(i) = c%:MP * p^`M(i).\nProof. by rewrite !mul_mpolyC mderivZ. Qed.\n\nLemma mderivM i p q : (p * q)^`M(i) = (p^`M(i) * q) + (p * q^`M(i)).\nProof.\nelim/mpolyind: p; first by rewrite !(mul0r, add0r, mderiv0).\nmove=> c m p _ _ ih; rewrite !(mulrDl, mderivD) -addrA.\nrewrite [X in _=_+X]addrCA -ih addrA => {ih}; congr (_ + _).\nrewrite -!scalerAl !mderivZ -scalerAl -scalerDr; congr (_ *: _).\npose_big_enough k; rewrite 1?[q](mpolywE (k := k)) //; try by close.\ndo! rewrite mulr_sumr ?raddf_sum /=; rewrite -big_split /=.\napply/eq_bigr=> h _; rewrite -!commr_mpolyX -scalerAl -mpolyXD.\nrewrite !mderivZ -commr_mderivX -!scalerAl -scalerDr; congr (_ *: _).\nrewrite !mderivX -!commr_mpolyX -!scalerAl -!mpolyXD mnmDE.\nhave [z_mi|ne_mi] := eqVneq (m i) 0%N.\n  rewrite z_mi addn0 scale0r add0r; congr (_ *: 'X_[_]).\n  apply/mnmP=> j; rewrite !(mnmBE, mnmDE, mnm1E).\n  by case: eqP => /= [<-|]; rewrite ?subn0 // z_mi !addn0.\napply/esym; rewrite addmC addmBA; last by rewrite lep1mP.\nhave [z_hi|ne_hi] := eqVneq (h i) 0%N.\n  by rewrite z_hi add0n scale0r addr0.\nrewrite addrC addmC addmBA; last by rewrite lep1mP.\nby rewrite addmC -scalerDl natrD.\nQed.\n\nLemma mderiv_comm i j p : p^`M(i)^`M(j) = p^`M(j)^`M(i).\nProof.                          (* FIXME: f_equal *)\npose_big_enough k; first pose mderivE := (mderivwE k).\n  rewrite ![p^`M(_)]mderivE // !raddf_sum /=; apply/eq_bigr.\n  move=> l _; rewrite !mderivZ !mderivX !scalerA.\n  rewrite !submDA addmC -!commr_nat -!mulrA -!natrM.\n  f_equal; congr (_ * _%:R); rewrite !mnmBE !mnm1E.\n  by case: eqVneq => [->|_] //=; rewrite !subn0 mulnC.\nby close.\nQed.\n\nLemma mderiv_perm (s1 s2 : seq 'I_n) p :\n  perm_eq s1 s2 -> foldr mderiv p s1 = foldr mderiv p s2.\nProof.\npose M q s := foldr mderiv q s; rewrite -!/(M _ _).\nhave h (s : seq 'I_n) (x : 'I_n) q: x \\in s ->\n  M q s = M q (x :: rem x s).\n+ elim: s=> [|y s ih] //; rewrite in_cons /=.\n  by case: eqVneq => [->|ne_xy {}/ih ->] //=; rewrite mderiv_comm.\nelim: s1 s2 => [|x s1 ih] s2.\n  by rewrite perm_sym=> /perm_small_eq=> ->.\nmove=> peq_xDs1_s2; have x_in_s2: x \\in s2.\n  by rewrite -(perm_mem peq_xDs1_s2) mem_head.\nhave /h ->/= := x_in_s2; rewrite -ih // -(perm_cons x).\nby rewrite (permPl peq_xDs1_s2) perm_to_rem.\nQed.\n\nDefinition mderivm m p : {mpoly R[n]} :=\n  foldr (fun i => iter (m i) (mderiv i)) p (enum 'I_n).\n\nLocal Notation \"p ^`M [ m ]\" := (mderivm m p).\n\nLemma mderivm_foldr m p :\n  let s := flatten [seq nseq (m i) i | i <- enum 'I_n] in\n  p^`M[m] = foldr mderiv p s.\nProof.\nrewrite /mderivm; elim: (enum _)=> //= i s ih.\nby rewrite foldr_cat; elim: (m i)=> //= k ->.\nQed.\n\nLemma mderivm0m p : p^`M[0] = p.\nProof.\nrewrite mderivm_foldr (eq_map (_ : _ =1 fun=> [::])); first by elim: (enum _).\nby move=> i /=; rewrite mnm0E.\nQed.\n\nLemma mderivmDm m1 m2 p : p^`M[m1 + m2] = p^`M[m1]^`M[m2].\nProof.\nrewrite !mderivm_foldr -foldr_cat; apply/mderiv_perm.\napply/seq.permP => /= a; rewrite count_cat !count_flatten.\nrewrite !sumnE !big_map -big_split /=; apply/eq_bigr=> i _.\nby rewrite mnmDE nseqD count_cat addnC.\nQed.\n\nLemma mderiv_summ (T : Type) (r : seq T) (P : pred T) F p :\n    p^`M[\\sum_(x <- r | P x) (F x)]\n  = foldr mderivm p [seq F x | x <- r & P x].\nProof.\nelim: r => //= [|x s ih]; first by rewrite big_nil mderivm0m.\nby rewrite big_cons; case: (P x); rewrite //= addmC mderivmDm ih.\nQed.\n\nLemma mderivmU1m i p : p^`M[U_(i)] = p^`M(i).\nProof.\nrewrite mderivm_foldr (@mderiv_perm _ [:: i]) //.\napply/seq.permP=> /= a; rewrite addn0 count_flatten sumnE !big_map.\nrewrite -/(index_enum _) (bigD1 i) //=.\nrewrite mnm1E eqxx /= big1 ?addn0 // => j ne_ji.\nby rewrite mnm1E eq_sym (negbTE ne_ji).\nQed.\n\nLemma mderivm_is_linear m : linear (mderivm m).\nProof.\nmove=> c p q; rewrite /mderivm; elim: (enum _)=> //= i s ih.\nby elim: (m i) => //= {ih}k ->; rewrite mderivD mderivZ.\nQed.\n\nCanonical mderivm_additive m := Additive (mderivm_is_linear m).\nCanonical mderivm_linear   m := Linear   (mderivm_is_linear m).\n\nLemma mderivmN m : {morph mderivm m: x / - x}.\nProof. exact: raddfN. Qed.\n\nLemma mderivmD m : {morph mderivm m: x y / x + y}.\nProof. exact: raddfD. Qed.\n\nLemma mderivmB m : {morph mderivm m: x y / x - y}.\nProof. exact: raddfB. Qed.\n\nLemma mderivmMn m k : {morph mderivm m: x / x *+ k}.\nProof. exact: raddfMn. Qed.\n\nLemma mderivmMNn m k : {morph mderivm m: x / x *- k}.\nProof. exact: raddfMNn. Qed.\n\nLemma mderivmZ m c p : (c *: p)^`M[m] = c *: p^`M[m].\nProof. by rewrite linearZ. Qed.\n\nLemma mderivm_mulC m c p : (c%:MP * p)^`M[m] = c%:MP * p^`M[m].\nProof. by rewrite !mul_mpolyC mderivmZ. Qed.\n\nLocal Notation \"p ^`M ( i , n )\" := (mderivm (U_(i) *+ n) p).\n\nLemma mderivn0 i p : p^`M(i, 0) = p.\nProof. by rewrite mulm0n mderivm0m. Qed.\n\nLemma nderivn1 i p : p^`M(i, 1) = p^`M(i).\nProof. by rewrite mulm1n mderivmU1m. Qed.\n\nLemma mderivSn i k p : p^`M(i, k.+1) = p^`M(i)^`M(i, k).\nProof. by rewrite mulmS mderivmDm mderivmU1m. Qed.\n\nLemma mderivnS i k p : p^`M(i, k.+1) = p^`M(i, k)^`M(i).\nProof. by rewrite mulmS addmC mderivmDm mderivmU1m. Qed.\n\nLemma mderivn_iter i k p :\n  p^`M(i, k) = iter k (mderiv i) p.\nProof. by elim: k => /= [|k ih]; rewrite ?mderivn0 // mderivnS ih. Qed.\n\nLemma mderivmX m1 m2 :\n  ('X_[m1])^`M[m2] = (\\prod_(i < n) (m1 i)^_(m2 i))%:R *: 'X_[m1-m2].\nProof.\nrewrite [m2]multinomUE_id mderiv_summ filter_predT /index_enum -enumT /=.\nelim: (enum _) (enum_uniq 'I_n) => /= [|i s ih /andP [i_notin_s uq_s]].\n  by move=> _; rewrite !big_nil scale1r subm0.\npose F j := (m1 j) ^_ (m2 j); rewrite ih // mderivmZ.\nrewrite big_seq [X in X%:R](eq_bigr F) -?big_seq; last first.\n  move=> j j_in_s; rewrite (bigD1_seq j) //=.\n  rewrite mnmDE mnm_sumE mulmnE mnm1E eqxx mul1n.\n  rewrite big1 ?addn0 // => j' ne_j'j; rewrite mulmnE.\n  by rewrite mnm1E (negbTE ne_j'j).\nrewrite big_cons mulnC natrM -scalerA; apply/esym.\nrewrite 2![X in X%:R*:(_*:_)](big_seq, eq_bigr F); last first.\n  move=> j j_in_s; rewrite big_cons mnmDE mnm_sumE.\n  rewrite (bigD1_seq j) //= big1 ?addn0 => [|j' ne_j'j].\n    rewrite !mulmnE !mnm1E eqxx mul1n; move/memPn: i_notin_s.\n    by rewrite eq_sym => /(_ j j_in_s) /negbTE ->.\n  by rewrite mulmnE mnm1E (negbTE ne_j'j).\nrewrite -big_seq; congr (_ *: _); rewrite !big_cons.\nrewrite mnmDE mnm_sumE big_seq big1 ?addn0; last first.\n  move=> /= j j_in_s; rewrite mulmnE mnm1E; move/memPn: i_notin_s.\n  by move/(_ j j_in_s)=> /negbTE->.\nrewrite mulmnE mnm1E eqxx mul1n; elim: (m2 i)=> /= [|k ihk].\n  by rewrite ffactn0 scale1r mulm0n add0m mderivm0m.\nrewrite mderivnS -ihk mderivZ mderivX scalerA -natrM.\nrewrite submDA Monoid.mulmAC /= mulmSr; congr (_%:R *: 'X_[_]).\nrewrite mnmBE mnmDE mnm_sumE big_seq big1; last first.\n  move=> /= j j_in_s; rewrite mulmnE mnm1E; move: i_notin_s.\n  by move/memPn/(_ j j_in_s)=> /negbTE->.\nby rewrite addn0 mulmnE mnm1E eqxx mul1n ffactnSr.\nQed.\n\nLemma mderivmE m p : p^`M[m] =\n  \\sum_(m' <- msupp p)\n     (p@_m' * (\\prod_(i < n) (m' i)^_(m i))%:R *: 'X_[m'-m]).\nProof.\nrewrite {1}[p]mpolyE raddf_sum /=; apply/eq_bigr=> m' _.\nby rewrite mderivmZ -scalerA -mderivmX.\nQed.\n\nLemma mderivmwE k m p : msize p <= k -> p^`M[m] =\n  \\sum_(m' : 'X_{1..n < k})\n     (p@_m' * (\\prod_(i < n) (m' i)^_(m i))%:R *: 'X_[m'-m]).\nProof.\nmove=> lt_pk; pose P (m : 'X_{1..n < k}) := (val m) \\in msupp p.\nrewrite (bigID P) {}/P /= addrC big1 ?add0r; last first.\n  by move=> m' /memN_msupp_eq0=> ->; rewrite mul0r scale0r.\nrewrite mderivmE (big_mksub [subFinType of 'X_{1..n < k}]) //=.\n  exact/msupp_uniq.\nby move=> m' /msize_mdeg_lt /leq_trans; apply.\nQed.\n\nLemma mderivnE i k p : p^`M(i, k) =\n  \\sum_(m <- msupp p) (((m i)^_k)%:R * p@_m) *: 'X_[m - U_(i) *+ k].\nProof.\nrewrite mderivmE; apply/eq_bigr=> /= m _.\nrewrite -commr_nat (bigD1 i) //= big1 ?muln1.\n  by rewrite mulmnE mnm1E eqxx mul1n.\nby move=> j ne_ji; rewrite mulmnE mnm1E eq_sym (negbTE ne_ji).\nQed.\n\nLemma mderivnX i k m : 'X_[m]^`M(i, k) = ((m i)^_k)%:R *: 'X_[m - U_(i) *+ k].\nProof. by rewrite mderivnE msuppX big_seq1 mcoeffX eqxx mulr1. Qed.\n\nLemma mcoeff_mderivm m p m' :\n  (p^`M[m])@_m' = p@_(m + m') *+ (\\prod_(i < n) ((m + m')%MM i)^_(m i)).\nProof.\npose_big_enough i; first rewrite (@mderivmwE i) //.\n  have lt_mDm'_i: mdeg (m + m') < i by [].\n  rewrite (bigD1 (Sub (m + m')%MM lt_mDm'_i)) //=.\n  rewrite mcoeffD raddf_sum /= [X in _+X]big1; last first.\n    case=> j lt_ji; rewrite eqE /= => ne_j_mDm'.\n    rewrite mcoeffZ mcoeffX; case: eqP; rewrite ?mulr0 //=.\n    move=> eq_m'_jBm; move: ne_j_mDm'; rewrite -eq_m'_jBm.\n    case: (boolP (m <= j))%MM => [/addmBA->|].\n      by rewrite [(m + j)%MM]addmC /= addmK eqxx.\n    rewrite negb_forall; case/existsP=> /= k Nle_mj.\n    by rewrite (bigD1 k) //= ffact_small ?simpm // ltnNge.\n  rewrite addr0 mcoeffZ mcoeffX {3}[(m + m')%MM]addmC addmK.\n  by rewrite eqxx mulr1 mulr_natr.\nby close.\nQed.\n\nLemma mcoeff_mderiv i p m : (p^`M(i))@_m = p@_(m + U_(i)) *+ (m i).+1.\nProof.\nrewrite -mderivmU1m mcoeff_mderivm addmC /=.\nrewrite (bigD1 i) //= mnmDE !mnm1E eqxx addn1 ffactn1.\nrewrite (eq_bigr (fun _ => 1%N)) ?prod_nat_const /=.\n  by rewrite exp1n muln1.\nmove=> j ne_ji; rewrite mnmDE mnm1E eq_sym.\nby rewrite (negbTE ne_ji) ffactn0.\nQed.\n\nEnd MPolyDeriv.\n\nNotation \"p ^`M ( i )\"     := (mderiv i p).\nNotation \"p ^`M [ m ]\"     := (mderivm m p).\nNotation \"p ^`M ( i , n )\" := (mderivm (U_(i) *+ n) p).\n\n(* -------------------------------------------------------------------- *)\nSection MPolyMorphism.\nContext (n : nat) (R S : ringType).\nImplicit Types (p q r : {mpoly R[n]}) (m : 'X_{1..n}).\n\nSection Defs.\nContext (f : R -> S) (h : 'I_n -> S).\nDefinition mmap1 m := \\prod_(i < n) (h i)^+(m i).\nDefinition mmap  p := \\sum_(m <- msupp p) (f p@_m) * (mmap1 m).\nEnd Defs.\n\nLemma mmap11 h : mmap1 h 0%MM = 1.\nProof. by rewrite /mmap1 big1 // => /= i _; rewrite mnm0E expr0. Qed.\n\nLemma mmap1U h i : mmap1 h U_(i) = h i.\nProof.\npose inj j := insubd i j; rewrite /mmap1.\npose F j := h (inj j) ^+ U_(i)%MM (inj j).\nhave FE j: j < n -> F j = (h (inj j)) ^+ (i == j :> nat).\n  move=> lt_jn; rewrite /F /inj /insubd insubT /=.\n  by rewrite mnm1E -val_eqE.\nrewrite (eq_bigr (F \\o val)) //; last first.\n  by move=> j _ /=; rewrite FE // mnm1E /inj /insubd valK.\nhave ->: n = (i.+1 + (n - i.+1))%N by rewrite subnKC.\nrewrite big_split_ord /= [X in _*X]big1 ?mulr1; last first.\n  case=> j /= lt_nBSi _; rewrite FE -?ltn_subRL //.\n  case: (_ =P _); last by rewrite expr0.\n  by rewrite addSnnS -{1}[val i]addn0 /= => /addnI.\nrewrite big_ord_recr /= big1 ?mul1r; last first.\n  case=> j /= lt_ji _; rewrite FE; last first.\n    by rewrite (@leq_trans i) // ltnW.\n  by rewrite eq_sym (ltn_eqF lt_ji) expr0.\nby rewrite FE // eqxx expr1 /inj /insubd valK.\nQed.\n\nLemma commr_mmap1_M h m1 m2 :\n     (forall i x, GRing.comm x (h i))\n  -> mmap1 h (m1 + m2) = (mmap1 h m1) * (mmap1 h m2).\nProof.\nmove=> comm; pose F (i : 'I_n) := (h i ^+ m1 i) * (h i ^+ m2 i).\nrewrite /mmap1 (eq_bigr F) => [|i _]; last first.\n  by rewrite mnmDE exprD.\nrewrite {}/F; elim/big_rec3: _; first by rewrite mulr1.\nmove=> i y1 y2 y3 _ ->; rewrite -!mulrA; congr (_ * _).\nhave commn k j x: GRing.comm x ((h j)^+k) by apply/commrX.\nby rewrite -commn -mulrA commn.\nQed.\n\nLocal Notation \"m ^[ h ]\"     := (mmap1 h m).\nLocal Notation \"p ^[ f , h ]\" := (mmap f h p).\n\nSection Additive.\nContext (h : 'I_n -> S) (f : {additive R -> S}).\n\nLemma mmapE p i : msize p <= i ->\n  p^[f,h] = \\sum_(m : 'X_{1..n < i}) (f p@_m) * m^[h].\nProof.\nmove=> le_pi; set I := [subFinType of 'X_{1..n < i}].\nrewrite /mmap (big_mksub I) ?msupp_uniq //=; first last.\n  by move=> x /msize_mdeg_lt /leq_trans; apply.\nrewrite big_rmcond //= => j /memN_msupp_eq0 ->.\nby rewrite raddf0 mul0r.\nQed.\nArguments mmapE [p].\n\nLemma mmap_is_additive : additive (mmap f h).\nProof.\nmove=> p q /=; pose_big_enough i.\n  rewrite !(mmapE i) // -sumrB; apply/eq_bigr.\n  by case=> /= [m _] _; rewrite !raddfB /= mulrDl mulNr.\nby close.\nQed.\n\nCanonical mmap_additive := Additive mmap_is_additive.\n\nLocal Notation mmap := (mmap f h).\n\nLemma mmap0     : mmap 0 = 0               . Proof. exact: raddf0. Qed.\nLemma mmapN     : {morph mmap: x / - x}    . Proof. exact: raddfN. Qed.\nLemma mmapD     : {morph mmap: x y / x + y}. Proof. exact: raddfD. Qed.\nLemma mmapB     : {morph mmap: x y / x - y}. Proof. exact: raddfB. Qed.\nLemma mmapMn  k : {morph mmap: x / x *+ k} . Proof. exact: raddfMn. Qed.\nLemma mmapMNn k : {morph mmap: x / x *- k} . Proof. exact: raddfMNn. Qed.\n\nLemma mmapC c : mmap c%:MP = f c.\nProof.\nhave [->|nz_c] := eqVneq c 0; first by rewrite mmap0 raddf0.\nrewrite /mmap msuppC (negbTE nz_c) big_seq1 mmap11 mulr1.\nby rewrite mcoeffC eqxx mulr1.\nQed.\n\nEnd Additive.\n\nArguments mmapE [h f p].\n\nSection Multiplicative.\nContext (h : 'I_n -> S) (f : {rmorphism R -> S}).\n\nLemma mmapX m : ('X_[m])^[f,h] = m^[h].\nProof. by rewrite /mmap msuppX big_seq1 mcoeffX eqxx rmorph1 mul1r. Qed.\n\nLemma mmapZ c p : (c *: p)^[f,h] = (f c) * p^[f,h].\nProof.\npose_big_enough i.\n  rewrite !(mmapE i) // mulr_sumr; apply/eq_bigr.\n  by move=> j _; rewrite mcoeffZ mulrA -rmorphM.\nby close.\nQed.\n\nHypothesis commr_h: forall i x, GRing.comm x (h i).\nHypothesis commr_f: forall p m m', GRing.comm (f p@_m) (m'^[h]).\n\nLemma commr_mmap_is_multiplicative: multiplicative (mmap f h).\nProof.\nsplit=> //= [p q|]; last first.\n  by rewrite /mmap msupp1 big_seq1 mpolyCK rmorph1 mul1r mmap11.\npose_big_enough i.\n  rewrite (mpolywME (k := i)) // raddf_sum /= !(mmapE i) //.\n  rewrite big_distrlr /= pair_bigA; apply/eq_bigr=> /=.\n  case=> j1 j2 _ /=; rewrite mmapZ mmapX; apply/esym.\n  rewrite [f q@__ * _]commr_f mulrA -[X in X*_]mulrA.\n  by rewrite -commr_mmap1_M // -mulrA -commr_f !mulrA rmorphM.\nby close.\nQed.\n\nEnd Multiplicative.\nEnd MPolyMorphism.\n\nArguments mmapE [n R S h f p].\n\n(* -------------------------------------------------------------------- *)\nLemma mmap1_eq n (R : ringType) (f1 f2 : 'I_n -> R) m :\n  f1 =1 f2 -> mmap1 f1 m = mmap1 f2 m.\nProof.\nmove=> eq_f; rewrite /mmap1; apply/eq_bigr.\nby move=> /= i _; rewrite eq_f.\nQed.\n\nLemma mmap1_id n (R : ringType) m :\n  mmap1 (fun i => 'X_i) m = 'X_[m] :> {mpoly R[n]}.\nProof. by rewrite mpolyXE_id. Qed.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyMorphismComm.\nContext (n : nat) (R : ringType) (S : comRingType).\nContext (h : 'I_n -> S) (f : {rmorphism R -> S}).\nImplicit Types (p q r : {mpoly R[n]}).\n\nLemma mmap_is_multiplicative : multiplicative (mmap f h).\nProof.\n  apply/commr_mmap_is_multiplicative.\n  + by move=> i x; apply/mulrC.\n  + by move=> p m m'; apply/mulrC.\nQed.\n\nCanonical mmap_rmorphism := AddRMorphism mmap_is_multiplicative.\n\nEnd MPolyMorphismComm.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyComRing.\nContext (n : nat) (R : comRingType).\nImplicit Types (p q r : {mpoly R[n]}).\n\nLemma mpoly_mulC p q : p * q = q * p.\nProof.\napply/mpolyP=> /= m; rewrite mcoeffM mcoeffMr.\nby apply: eq_bigr=> /= i _; rewrite mulrC.\nQed.\n\nCanonical mpoly_comRingType :=\n  Eval hnf in ComRingType {mpoly R[n]} mpoly_mulC.\nCanonical mpolynomial_comRingType :=\n  Eval hnf in ComRingType (mpoly n R) mpoly_mulC.\n\nCanonical mpoly_algType :=\n  Eval hnf in CommAlgType R {mpoly R[n]}.\nCanonical mpolynomial_algType :=\n  Eval hnf in [algType R of mpoly n R for mpoly_algType].\n\nEnd MPolyComRing.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyComp.\nContext (n : nat) (R : ringType) (k : nat).\nImplicit Types (p q : {mpoly R[n]}) (lp lq : n.-tuple {mpoly R[k]}).\n\nDefinition comp_mpoly lq p : {mpoly R[k]} := mmap (@mpolyC _ R) (tnth lq) p.\n\nLocal Notation \"p \\mPo lq\" := (comp_mpoly lq p).\n\nLemma comp_mpolyE p lq :\n  p \\mPo lq = \\sum_(m <- msupp p) p@_m *: \\prod_(i < n) (tnth lq i)^+(m i).\nProof. by apply/eq_bigr=> m _; rewrite -mul_mpolyC. Qed.\n\nLemma comp_mpolywE p lq w : msize p <= w -> p \\mPo lq =\n  \\sum_(m : 'X_{1..n < w}) (p@_m *: \\prod_(i < n) (tnth lq i)^+(m i)).\nProof.\nmove=> le_szp_w; rewrite /comp_mpoly (mmapE w) //=.\nby apply/eq_bigr=> m _; rewrite mul_mpolyC.\nQed.\n\nLemma comp_mpoly_is_additive lq : additive (comp_mpoly lq).\nProof. by move=> p q; rewrite /comp_mpoly -mmapB. Qed.\n\nCanonical comp_mpoly_additive lq := Additive (comp_mpoly_is_additive lq).\n\nLemma comp_mpoly0   lq   : 0 \\mPo lq = 0                     . Proof. exact: raddf0. Qed.\nLemma comp_mpolyN   lq   : {morph comp_mpoly lq: x / - x}    . Proof. exact: raddfN. Qed.\nLemma comp_mpolyD   lq   : {morph comp_mpoly lq: x y / x + y}. Proof. exact: raddfD. Qed.\nLemma comp_mpolyB   lq   : {morph comp_mpoly lq: x y / x - y}. Proof. exact: raddfB. Qed.\nLemma comp_mpolyMn  lq l : {morph comp_mpoly lq: x / x *+ l} . Proof. exact: raddfMn. Qed.\nLemma comp_mpolyMNn lq l : {morph comp_mpoly lq: x / x *- l} . Proof. exact: raddfMNn. Qed.\n\nLemma comp_mpoly_is_linear lq : linear (comp_mpoly lq).\nProof.\nmove=> c p q; rewrite comp_mpolyD /comp_mpoly.\nby rewrite mmapZ mul_mpolyC.\nQed.\n\nCanonical comp_mpoly_linear lq := Linear (comp_mpoly_is_linear lq).\n\nLemma comp_mpoly1 lq : 1 \\mPo lq = 1.\nProof. by rewrite /comp_mpoly -mpolyC1 mmapC. Qed.\n\nLemma comp_mpolyC c lq : c%:MP \\mPo lq = c%:MP.\nProof. by rewrite [LHS]mmapC. Qed.\n\nLemma comp_mpolyZ c p lq : (c *: p) \\mPo lq = c *: (p \\mPo lq).\nProof. exact/linearZ. Qed.\n\nLemma comp_mpolyXU i lq : 'X_i \\mPo lq = lq`_i.\nProof. by rewrite /comp_mpoly mmapX mmap1U -tnth_nth. Qed.\n\nLemma comp_mpolyX m lq : 'X_[m] \\mPo lq = \\prod_(i < n) (tnth lq i)^+(m i).\nProof. by rewrite [LHS]mmapX. Qed.\n\nLemma comp_mpolyEX p lq :\n  p \\mPo lq = \\sum_(m <- msupp p) (p@_m *: ('X_[m] \\mPo lq)).\nProof. by apply/eq_bigr=> m _; rewrite mul_mpolyC comp_mpolyX. Qed.\n\nEnd MPolyComp.\n\nNotation \"p \\mPo lq\" := (@comp_mpoly _ _ _ lq p).\n\nSection MPolyCompComm.\nContext (n : nat) (R : comRingType) (k : nat) (lp : n.-tuple {mpoly R[k]}).\n\nLemma comp_mpoly_is_multiplicative : multiplicative (comp_mpoly lp).\nProof. exact: mmap_is_multiplicative. Qed.\n\nCanonical comp_mpoly_rmorphism := AddRMorphism comp_mpoly_is_multiplicative.\nCanonical comp_mpoly_lrmorphism := [lrmorphism of (comp_mpoly lp)].\n\nEnd MPolyCompComm.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyCompHomo.\nContext (n : nat) (R : ringType).\nImplicit Types (p q : {mpoly R[n]}).\n\nLemma comp_mpoly_id p : p \\mPo [tuple 'X_i | i < n] = p.\nProof.\nrewrite [p]mpolyE raddf_sum /=; apply/eq_bigr.\nmove=> m _; rewrite comp_mpolyZ; congr (_ *: _).\nrewrite /comp_mpoly mmapX -mmap1_id; apply/mmap1_eq.\nby move=> /= i; rewrite tnth_map tnth_ord_tuple.\nQed.\n\nEnd MPolyCompHomo.\n\n(* -------------------------------------------------------------------- *)\nSection MEval.\nContext (n : nat) (R : ringType).\nImplicit Types (p q r : {mpoly R[n]}) (v : 'I_n -> R).\n\nDefinition meval v p := mmap idfun v p.\n\nLemma mevalE v p : meval v p = \\sum_(m <- msupp p) p@_m * \\prod_i v i ^+ m i.\nProof. by []. Qed.\n\nLemma meval_is_additive v : additive (meval v).\nProof. exact/mmap_is_additive. Qed.\n\nCanonical meval_additive v := Additive (meval_is_additive v).\n\nLemma meval0   v   : meval v 0 = 0               . Proof. exact: raddf0. Qed.\nLemma mevalN   v   : {morph meval v: x / - x}    . Proof. exact: raddfN. Qed.\nLemma mevalD   v   : {morph meval v: x y / x + y}. Proof. exact: raddfD. Qed.\nLemma mevalB   v   : {morph meval v: x y / x - y}. Proof. exact: raddfB. Qed.\nLemma mevalMn  v k : {morph meval v: x / x *+ k} . Proof. exact: raddfMn. Qed.\nLemma mevalMNn v k : {morph meval v: x / x *- k} . Proof. exact: raddfMNn. Qed.\n\nLemma mevalC v c : meval v c%:MP = c.\nProof. by rewrite [LHS]mmapC. Qed.\n\nLemma meval1 v : meval v 1 = 1.\nProof. exact/mevalC. Qed.\n\nLemma mevalXU v i : meval v 'X_i = v i.\nProof. by rewrite [LHS]mmapX mmap1U. Qed.\n\nLemma mevalX v m : meval v 'X_[m] = \\prod_(i < n) (v i) ^+ (m i).\nProof. by rewrite [LHS]mmapX. Qed.\n\nLemma meval_is_scalable v : scalable_for *%R (meval v).\nProof. by move=> /= c p; rewrite [LHS]mmapZ. Qed.\n\nLemma mevalZ v c p : meval v (c *: p) = c * (meval v p).\nProof. exact: meval_is_scalable. Qed.\n\nLemma meval_eq v1 v2 p : v1 =1 v2 -> meval v1 p = meval v2 p.\nProof.\nmove=> eq_v; rewrite !mevalE; apply/eq_bigr=> i _.\nby congr *%R; apply/eq_bigr=> j _; rewrite eq_v.\nQed.\n\nEnd MEval.\n\nNotation \"p .@[ v ]\" := (@meval _ _ v p).\nNotation \"p .@[< v >]\" := (@meval _ _ (nth v) p).\n\n(* -------------------------------------------------------------------- *)\nSection MEvalCom.\nContext (n k : nat) (R : comRingType).\nImplicit Types (p q r : {mpoly R[n]}) (v : 'I_n -> R).\n\nLemma meval_is_lrmorphism v : lrmorphism_for *%R (meval v).\nProof.\n  split; first split.\n  + exact/mmap_is_additive.\n  + exact/mmap_is_multiplicative.\n  by move=> /= c p; rewrite [LHS]mmapZ.\nQed.\n\nCanonical meval_rmorphism  v := RMorphism (meval_is_lrmorphism v).\nCanonical meval_linear     v := AddLinear (meval_is_lrmorphism v).\nCanonical meval_lrmorphism v := [lrmorphism of meval v].\n\nLemma mevalM v : {morph meval v: x y / x * y}.\nProof. exact: rmorphM. Qed.\n\nEnd MEvalCom.\n\n(* -------------------------------------------------------------------- *)\nSection MEvalComp.\nContext (n k : nat) (R : comRingType) (v : 'I_n -> R) (p : {mpoly R[k]}).\nContext (lq : k.-tuple {mpoly R[n]}).\n\nLemma comp_mpoly_meval : (p \\mPo lq).@[v] = p.@[fun i => (tnth lq i).@[v]].\nProof.\nrewrite comp_mpolyEX [X in _ = X.@[_]](mpolyE p) !raddf_sum /=.\napply/eq_bigr => m _; rewrite !mevalZ; congr *%R.\nrewrite comp_mpolyX rmorph_prod /= mevalX.\nby apply/eq_bigr=> i _; rewrite rmorphX.\nQed.\n\nEnd MEvalComp.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyMap.\nContext (n : nat) (R S : ringType).\nImplicit Types (p q r : {mpoly R[n]}).\n\nDefinition map_mpoly (f : R -> S) p : {mpoly S[n]} :=\n  mmap ((@mpolyC n _) \\o f) (fun i => 'X_i) p.\n\nSection Additive.\nContext (f : {additive R -> S}).\n\nLocal Notation \"p ^f\" := (map_mpoly f p).\n\nLemma map_mpoly_is_additive : additive (map_mpoly f).\nProof. exact/mmap_is_additive. Qed.\n\nCanonical map_mpoly_additive := Additive map_mpoly_is_additive.\n\nLemma map_mpolyC c : map_mpoly f c%:MP_[n] = (f c)%:MP_[n].\nProof. by rewrite [LHS]mmapC. Qed.\n\nLemma map_mpolyE p k : msize p <= k ->\n  p^f = \\sum_(m : 'X_{1..n < k}) (f p@_m) *: 'X_[m].\nProof.\nrewrite /map_mpoly; move/mmapE=> -> /=; apply/eq_bigr.\nby move=> i _; rewrite mmap1_id mul_mpolyC.\nQed.\nArguments map_mpolyE [p].\n\nLemma mcoeff_map_mpoly m p : p^f@_m = f p@_m.\nProof.\npose_big_enough i; first rewrite (map_mpolyE i) //.\n  by rewrite (mcoeff_mpoly (fun m => (f p@_m))).\nby close.\nQed.\n\nEnd Additive.\n\nSection Multiplicative.\nContext (f : {rmorphism R -> S}).\n\nLocal Notation \"p ^f\" := (map_mpoly f p).\n\nLemma map_mpoly_is_multiplicative : multiplicative (map_mpoly f).\nProof.\napply/commr_mmap_is_multiplicative => /=.\n+ by move=> i x; apply/commr_mpolyX.\n+ by move=> p m m'; rewrite mmap1_id; apply/commr_mpolyX.\nQed.\n\nCanonical map_mpoly_multiplicative :=\n  AddRMorphism map_mpoly_is_multiplicative.\n\nLemma map_mpolyX (m : 'X_{1..n}) :\n  map_mpoly f 'X_[m] = 'X_[m].\nProof. by rewrite /map_mpoly mmapX mmap1_id. Qed.\n\nLemma map_mpolyZ (c : R) (p : {mpoly R[n]}) :\n  map_mpoly f (c *: p) = (f c) *: (map_mpoly f p).\nProof. by rewrite /map_mpoly mmapZ /= mul_mpolyC. Qed.\n\nLemma msupp_map_mpoly p :\n  injective f -> perm_eq (msupp (map_mpoly f p)) (msupp p).\nProof.\nmove=> inj_f; apply/uniq_perm; rewrite ?msupp_uniq //=.\nby move=> m; rewrite !mcoeff_msupp mcoeff_map_mpoly raddf_eq0.\nQed.\n\nEnd Multiplicative.\nEnd MPolyMap.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyMapComp.\nContext (n k : nat) (R S : ringType) (f : {rmorphism R -> S}).\nContext (lq : n.-tuple {mpoly R[k]}) (p : {mpoly R[n]}).\n\nLocal Notation \"p ^f\" := (map_mpoly f p).\n\nLemma map_mpoly_comp : injective f ->\n  (p \\mPo lq)^f = (p^f) \\mPo [tuple of [seq map_mpoly f q | q <- lq]].\nProof.\nmove=> inj_f; apply/mpolyP=> m; rewrite mcoeff_map_mpoly.\nrewrite !raddf_sum (perm_big _ (msupp_map_mpoly _ inj_f)) /=.\napply/eq_bigr=> m' _; rewrite mcoeff_map_mpoly !mcoeffCM rmorphM /=.\ncongr *%R; rewrite /mmap1 -mcoeff_map_mpoly rmorph_prod /=.\nby congr _@__; apply/eq_bigr=> i /=; rewrite tnth_map rmorphX.\nQed.\n\nEnd MPolyMapComp.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyOver.\nContext (n : nat) (R : ringType).\n\nDefinition mpolyOver (S : {pred R}) :=\n  [qualify a p : {mpoly R[n]} | all (mem S) [seq p@_m | m <- msupp p]].\n\nFact mpolyOver_key S : pred_key (mpolyOver S). Proof. by []. Qed.\nCanonical mpolyOver_keyed S := KeyedQualifier (mpolyOver_key S).\n\nLemma mpolyOverS (S1 S2 : {pred R}) :\n  {subset S1 <= S2} -> {subset mpolyOver S1 <= mpolyOver S2}.\nProof.\nmove=> sS12 p /(all_nthP 0)S1p.\nby apply/(all_nthP 0)=> i /S1p; apply: sS12.\nQed.\n\nLemma mpolyOver0 S: 0 \\is a mpolyOver S.\nProof. by rewrite qualifE msupp0. Qed.\n\nLemma mpolyOver_mpoly (S : {pred R}) E :\n     (forall m : 'X_{1..n}, m \\in dom E -> coeff m E \\in S)\n  -> [mpoly E] \\is a mpolyOver S.\nProof.\nmove=> S_E; apply/(all_nthP 0)=> i; rewrite size_map /= => lt.\nby rewrite (nth_map 0%MM) // mcoeff_MPoly S_E ?mem_nth.\nQed.\n\nSection MPolyOverAdd.\nContext (S : predPredType R) (addS : addrPred S) (kS : keyed_pred addS).\n\nLemma mpolyOverP {p} : reflect (forall m, p@_m \\in kS) (p \\in mpolyOver kS).\nProof.\ncase: p=> E; rewrite qualifE /=; apply: (iffP allP); last first.\n  by move=> h x /mapP /= [m m_in_E] ->; apply/h.\nmove=> h m; case: (boolP (m \\in msupp (MPoly E))).\n  by move=> m_in_E; apply/h/map_f.\n  by rewrite -mcoeff_eq0 => /eqP->; rewrite rpred0.\nQed.\n\nLemma mpolyOverC c : (c%:MP \\in mpolyOver kS) = (c \\in kS).\nProof.\nrewrite qualifE msuppC; case: eqP=> [->|] //=;\nby rewrite ?rpred0 // andbT mcoeffC eqxx mulr1.\nQed.\n\nLemma mpolyOver_addr_closed : addr_closed (mpolyOver kS).\nProof.\nsplit=> [|p q Sp Sq]; first exact: mpolyOver0.\nby apply/mpolyOverP=> i; rewrite mcoeffD rpredD ?(mpolyOverP _).\nQed.\n\nCanonical mpolyOver_addrPred := AddrPred mpolyOver_addr_closed.\n\nEnd MPolyOverAdd.\n\nLemma mpolyOverNr S (addS : zmodPred S) (kS : keyed_pred addS) :\n  oppr_closed (mpolyOver kS).\nProof.\nby move=> p /mpolyOverP Sp; apply/mpolyOverP=> i; rewrite mcoeffN rpredN.\nQed.\n\nCanonical mpolyOver_opprPred S addS kS := OpprPred (@mpolyOverNr S addS kS).\nCanonical mpolyOver_zmodPred S addS kS := ZmodPred (@mpolyOverNr S addS kS).\n\nSection MPolyOverSemiring.\nContext (S : predPredType R) (ringS : semiringPred S) (kS : keyed_pred ringS).\n\nLemma mpolyOver_mulr_closed : mulr_closed (mpolyOver kS).\nProof.\nsplit=> [|p q /mpolyOverP Sp /mpolyOverP Sq].\n  by rewrite mpolyOverC rpred1.\napply/mpolyOverP=> i; rewrite mcoeffM rpred_sum //.\nby move=> j _; apply: rpredM.\nQed.\n\nCanonical mpolyOver_mulrPred := MulrPred mpolyOver_mulr_closed.\nCanonical pmolyOver_semiringPred := SemiringPred mpolyOver_mulr_closed.\n\nLemma mpolyOverZ :\n  {in kS & mpolyOver kS, forall c p, c *: p \\is a mpolyOver kS}.\nProof.\nmove=> c p Sc /mpolyOverP Sp; apply/mpolyOverP=> i.\nby rewrite mcoeffZ rpredM ?Sp.\nQed.\n\nLemma mpolyOverX m : 'X_[m] \\in mpolyOver kS.\nProof. by rewrite qualifE msuppX /= mcoeffX eqxx rpred1. Qed.\n\nLemma rpred_mhorner :\n  {in mpolyOver kS, forall p (v : 'I_n -> R),\n     [forall i : 'I_n, v i \\in kS] -> p.@[v] \\in kS}.\nProof.\nmove=> p /mpolyOverP Sp v Sv; rewrite mevalE rpred_sum // => m _.\nrewrite rpredM // rpred_prod //= => /= i _.\nby rewrite rpredX //; move/forallP: Sv; apply; apply/mem_tnth.\nQed.\n\nEnd MPolyOverSemiring.\n\nSection MPolyOverRing.\nContext (S : predPredType R) (ringS : subringPred S) (kS : keyed_pred ringS).\n\nCanonical mpolyOver_smulrPred := SmulrPred (mpolyOver_mulr_closed kS).\nCanonical mpolyOver_subringPred := SubringPred (mpolyOver_mulr_closed kS).\n\nLemma mpolyOverXaddC m c : ('X_[m] + c%:MP \\in mpolyOver kS) = (c \\in kS).\nProof. by rewrite rpredDl ?mpolyOverX ?mpolyOverC. Qed.\n\nEnd MPolyOverRing.\nEnd MPolyOver.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyIdomain.\nContext (n : nat) (R : idomainType).\nImplicit Types (p q r : {mpoly R[n]}).\n\nLemma mleadM p q : p != 0 -> q != 0 -> mlead (p * q) = (mlead p + mlead q)%MM.\nProof.\nmove=> nz_p nz_q; rewrite mleadM_proper //.\nby rewrite mulf_neq0 // mleadc_eq0.\nQed.\n\nLemma mlead_prod (T : eqType) (r : seq T) (P : pred T) (F : T -> {mpoly R[n]}) :\n     (forall x, x \\in r -> P x -> F x != 0)\n  -> mlead (\\prod_(p <- r | P p) F p) = (\\sum_(p <- r | P p) mlead (F p))%MM.\nProof.\nmove=> nz_Fr; rewrite mlead_prod_proper // => x x_in_r Px.\napply/lregP; rewrite mleadc_eq0; exact/nz_Fr.\nQed.\n\nLemma mleadX p k : p != 0 -> mlead (p ^+ k) = (mlead p *+ k)%MM.\nProof.\nby move=> nz_p; rewrite mleadX_proper //; apply/lregP; rewrite mleadc_eq0.\nQed.\n\nLemma mleadZ c p : c != 0 -> mlead (c *: p) = mlead p.\nProof.\nmove=> nz_c; have [->|nz_p] := eqVneq p 0; first by rewrite scaler0.\nby rewrite mleadZ_proper // mulf_neq0 // mleadc_eq0.\nQed.\n\nLemma mleadcZE a p : mleadc (a *: p) = a * mleadc p.\nProof.\nhave [->|Za] := eqVneq a 0; last by rewrite mleadZ // mcoeffZ.\nby rewrite scale0r mleadc0 mul0r.\nQed.\n\nLemma msizeM p q : p != 0 -> q != 0 -> msize (p * q) = (msize p + msize q).-1.\nProof. by move=> nz_p nz_q; rewrite msizeM_proper ?mulf_neq0 // mleadc_eq0. Qed.\n\nLemma msuppZ c p : c != 0 -> perm_eq (msupp (c *: p)) (msupp p).\nProof.\nmove=> nz_c; apply/uniq_perm=> // m.\nby rewrite !mcoeff_msupp mcoeffZ mulf_eq0 (negbTE nz_c).\nQed.\n\nLemma mscalerI a p : (a *: p == 0) = (a == 0) || (p == 0).\nProof.\nhave [/eqP->| /(msuppZ p)/perm_size] := boolP (a == 0).\n  by rewrite scale0r eqxx.\nby rewrite -!msupp_eq0; case: msupp => [|a1 l1]; case: msupp.\nQed.\n\nLemma mmeasureZ c p mf : c != 0 -> mmeasure mf (c *: p) = mmeasure mf p.\nProof. by move=> nz_c; rewrite !mmeasureE; apply/perm_big/msuppZ. Qed.\n\nLemma msizeZ c p : c != 0 -> msize (c *: p) = msize p.\nProof. exact/mmeasureZ. Qed.\n\nLemma mpoly_idomainAxiom p q : p * q = 0 -> (p == 0) || (q == 0).\nProof.\napply: contra_eqT => /norP[nz_p nz_q]; rewrite -msize_poly_eq0 msizeM //.\nby rewrite (mpolySpred _ nz_p) (mpolySpred _ nz_q) addnS.\nQed.\n\nDefinition mpoly_unit : pred {mpoly R[n]} :=\n  fun p => (p == (p@_0)%:MP) && (p@_0 \\in GRing.unit).\n\nDefinition mpoly_inv p :=\n  if p \\in mpoly_unit then (p@_0)^-1%:MP else p.\n\nLemma mpoly_mulVp : {in mpoly_unit, left_inverse 1 mpoly_inv *%R}.\nProof.\nmove=> p Up; rewrite /mpoly_inv Up; case/andP: Up.\nby move/eqP=> {3}->; rewrite -mpolyCM => /mulVr ->.\nQed.\n\nLemma mpoly_intro_unit p q : q * p = 1 -> p \\in mpoly_unit.\nProof.\nmove=> qp1; apply/andP; split; last first.\n  apply/unitrP; exists q@_0.\n  by rewrite 2!mulrC -rmorphM qp1 rmorph1.\napply/eqP/msize1_polyC; have: msize (q * p) == 1%N.\n  by rewrite qp1 msize1.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 msize0.\nhave [-> | nz_q] := eqVneq q 0; first by rewrite mul0r msize0.\nrewrite msizeM // (mpolySpred _ nz_p) (mpolySpred _ nz_q).\nby rewrite addnS addSn !eqSS addn_eq0 => /andP[] _ /eqP->.\nQed.\n\nLemma mpoly_inv_out : {in [predC mpoly_unit], mpoly_inv =1 id}.\nProof.  by rewrite /mpoly_inv => p /negbTE /= ->. Qed.\n\nDefinition mpoly_comUnitMixin :=\n  ComUnitRingMixin mpoly_mulVp mpoly_intro_unit mpoly_inv_out.\n\nCanonical mpoly_unitRingType :=\n  Eval hnf in UnitRingType {mpoly R[n]} mpoly_comUnitMixin.\nCanonical mpolynomial_unitRingType :=\n  Eval hnf in [unitRingType of mpoly n R for mpoly_unitRingType].\n\nCanonical mpoly_unitAlgType :=\n  Eval hnf in [unitAlgType R of {mpoly R[n]}].\nCanonical mpolynomial_unitAlgType :=\n  Eval hnf in [unitAlgType R of mpoly n R].\n\nCanonical mpoly_comUnitRingType :=\n  Eval hnf in [comUnitRingType of {mpoly R[n]}].\nCanonical mpolynomial_comUnitRingType :=\n  Eval hnf in [comUnitRingType of mpoly n R].\n\nCanonical mpoly_idomainType :=\n  Eval hnf in IdomainType {mpoly R[n]} mpoly_idomainAxiom.\nCanonical mpolynomial_idomainType :=\n  Eval hnf in [idomainType of mpoly n R for mpoly_idomainType].\n\nEnd MPolyIdomain.\n\n(* -------------------------------------------------------------------- *)\nSection MWeightTheory.\nContext (n : nat) (R : ringType).\nImplicit Types (m : 'X_{1..n}) (p : {mpoly R[n]}).\n\nLemma leq_mdeg_mnmwgt m : mdeg m <= mnmwgt m.\nProof.\nrewrite /mnmwgt mdegE leq_sum //= => i _; exact: leq_pmulr.\nQed.\n\nLemma leq_msize_meight p : msize p <= mweight p.\nProof.\nrewrite !mmeasureE; elim: (msupp p)=> [|m r ih].\n  by rewrite !big_nil.\nrewrite !big_cons geq_max !leq_max !ltnS.\nby rewrite leq_mdeg_mnmwgt /= ih orbT.\nQed.\n\nEnd MWeightTheory.\n\n(* -------------------------------------------------------------------- *)\nSection MPerm.\nContext (n : nat) (R : ringType).\nImplicit Types (m : 'X_{1..n}).\n\nLocal Notation \"m # s\" := [multinom m (s i) | i < n]\n  (at level 40, left associativity, format \"m # s\").\n\nLemma mperm_inj (s : 'S_n) : injective (fun m => m#s).\nProof.\nmove=> m1 m2 /= /mnmP h; apply/mnmP=> i.\nby move: (h (s^-1 i)%g); rewrite !mnmE permKV.\nQed.\n\nLemma mperm1 m : m#(1 : 'S_n)%g = m.\nProof. by apply/mnmP=> i; rewrite mnmE perm1. Qed.\n\nLemma mpermM m (s1 s2 : 'S_n) : m#(s1 * s2)%g = m#s2#s1.\nProof. by apply/mnmP=> i; rewrite !mnmE permM. Qed.\n\nLemma mpermKV (s : 'S_n) : cancel (fun m => m#s) (fun m => m#(s^-1))%g.\nProof. by move=> m /=; apply/mnmP=> i; rewrite !mnmE permKV. Qed.\n\nLemma mpermK (s : 'S_n) : cancel (fun m => m#(s^-1))%g (fun m => m#s).\nProof. by move=> m /=; apply/mnmP=> i; rewrite !mnmE permK. Qed.\n\nLemma mdeg_mperm m (s : 'S_n) : mdeg (m#s) = mdeg m.\nProof.\nrewrite !mdegE (reindex_inj (h := s^-1))%g /=; last exact/perm_inj.\nby apply/eq_bigr=> j _; rewrite !mnmE permKV.\nQed.\n\nEnd MPerm.\n\n(* -------------------------------------------------------------------- *)\nSection MPolySym.\nContext (n : nat) (R : ringType).\nImplicit Types (p q r : {mpoly R[n]}).\n\nDefinition msym (s : 'S_n) p : {mpoly R[n]} :=\n  mmap (@mpolyC n R) (fun i => 'X_(s i)) p.\n\nLocal Notation \"m # s\" := [multinom m (s i) | i < n]\n  (at level 40, left associativity, format \"m # s\").\n\nLemma msymE p (s : 'S_n) k : msize p <= k ->\n  msym s p = \\sum_(m : 'X_{1..n < k}) (p@_m *: 'X_[m#(s^-1)%g]).\nProof.\nmove=> lt_pk; rewrite /msym (mmapE k) //=; apply/eq_bigr.\nmove=> m' _; rewrite mul_mpolyC; congr (_ *: _).\nrewrite /mmap1 mprodXnE [X in _=X]mpolyXE_id mprodXnE.\nrewrite [X in _='X_[X]](reindex (fun i : 'I_n => s i)) /=.\n  congr 'X_[_]; apply/eq_bigr=> i _; congr (_ *+ _)%MM.\n  by rewrite mnmE /= permK.\nby exists (s^-1)%g=> i _; rewrite (permK, permKV).\nQed.\n\nArguments msymE [p].\n\nLemma mcoeff_sym p (s : 'S_n) m : (msym s p)@_m = p@_(m#s).\nProof.\npose_big_enough i; first rewrite (msymE s i) //.\n  apply/esym; rewrite {1}[p](mpolywE (k := i)) //.\n  rewrite !raddf_sum /=; apply/eq_bigr=> j _.\n  rewrite !mcoeffZ !mcoeffX; congr (_ * _).\n  have bijF: bijective (fun (m : 'X_{1..n}) => m#(s^-1)%g).\n    exists (fun (m : 'X_{1..n}) => m#s) => m'.\n    + by apply/mnmP=> k; rewrite !mnmE permK.\n    + by apply/mnmP=> k; rewrite !mnmE permKV.\n  rewrite -(bij_eq bijF); have ->//: m#s#(s^-1)%g = m.\n  by apply/mnmP=> k; rewrite !mnmE /= permKV.\nby close.\nQed.\n\nLemma msymX m s : msym s 'X_[m] = 'X_[m#(s^-1)%g].\nProof.\napply/mpolyP=> m'; rewrite mcoeff_sym !mcoeffX.\ncongr (_ : bool)%:R; apply/eqP/eqP=> [->|<-].\n+ by apply/mnmP=> i; rewrite !mnmE permKV.\n+ by apply/mnmP=> i; rewrite !mnmE permK.\nQed.\n\nLemma msym_is_additive s: additive (msym s).\nProof. exact/mmap_is_additive. Qed.\n\nCanonical msym_additive s := Additive (msym_is_additive s).\n\nLemma msym0   s   : msym s 0 = 0               . Proof. exact: raddf0. Qed.\nLemma msymN   s   : {morph msym s: x / - x}    . Proof. exact: raddfN. Qed.\nLemma msymD   s   : {morph msym s: x y / x + y}. Proof. exact: raddfD. Qed.\nLemma msymB   s   : {morph msym s: x y / x - y}. Proof. exact: raddfB. Qed.\nLemma msymMn  s k : {morph msym s: x / x *+ k} . Proof. exact: raddfMn. Qed.\nLemma msymMNn s k : {morph msym s: x / x *- k} . Proof. exact: raddfMNn. Qed.\n\nLemma msym_is_multiplicative s : multiplicative (msym s).\nProof.\napply/commr_mmap_is_multiplicative => [i x|p m1 m2]; first exact/commr_mpolyX.\nrewrite /= /mmap1; elim/big_rec: _ => [|i q _]; first exact/commr1.\nexact/commrM/commrX/commr_mpolyX.\nQed.\n\nCanonical msym_multiplicative s := AddRMorphism (msym_is_multiplicative s).\n\nLemma msym1 s : msym s 1 = 1.\nProof. exact: rmorph1. Qed.\n\nLemma msymM s : {morph msym s: x y / x * y}.\nProof. exact: rmorphM. Qed.\n\nLemma msymZ c p s : msym s (c *: p) = c *: (msym s p).\nProof.\npose_big_enough i; first rewrite !(msymE s i) //.\n  rewrite scaler_sumr; apply/eq_bigr => j _.\n  by rewrite mcoeffZ scalerA.\nby close.\nQed.\n\nCanonical msym_linear (s : 'S_n) : {linear {mpoly R[n]} -> {mpoly R[n]}} :=\n  AddLinear ((fun c => (msymZ c)^~ s) : scalable_for *:%R (msym s)).\n\nCanonical msym_lrmorphism s := [lrmorphism of msym s].\n\nDefinition symmetric : qualifier 0 {mpoly R[n]} :=\n  [qualify p | [forall s, msym s p == p]].\n\nFact symmetric_key : pred_key symmetric. Proof. by []. Qed.\nCanonical symmetric_keyed := KeyedQualifier symmetric_key.\n\nLemma issymP p : reflect (forall s, msym s p = p) (p \\is symmetric).\nProof.\napply: (iffP forallP)=> /= h s; last by rewrite h.\nby rewrite (eqP (h s)).\nQed.\n\nLemma sym_zmod : zmod_closed symmetric.\nProof.\nsplit=> [|p q /issymP sp /issymP sq]; apply/issymP=> s.\n  by rewrite msym0.\nby rewrite msymB sp sq.\nQed.\n\nCanonical sym_opprPred := OpprPred sym_zmod.\nCanonical sym_addrPred := AddrPred sym_zmod.\nCanonical sym_zmodPred := ZmodPred sym_zmod.\n\nLemma sym_mulr_closed : mulr_closed symmetric.\nProof.\nsplit=> [|p q /issymP sp /issymP sq]; apply/issymP=> s.\n  by rewrite msym1.\nby rewrite msymM sp sq.\nQed.\n\nCanonical sym_mulrPred     := MulrPred     sym_mulr_closed.\nCanonical sym_smulrPred    := SmulrPred    sym_mulr_closed.\nCanonical sym_semiringPred := SemiringPred sym_mulr_closed.\nCanonical sym_subringPred  := SubringPred  sym_mulr_closed.\n\nLemma sym_submod_closed : submod_closed symmetric.\nProof.\nsplit=> [|c p q /issymP sp /issymP sq]; apply/issymP=> s.\n  by rewrite msym0.\nby rewrite msymD msymZ sp sq.\nQed.\n\nCanonical sym_submodPred := SubmodPred sym_submod_closed.\nCanonical sym_subalgPred := SubalgPred sym_submod_closed.\n\nLemma issym_msupp p (s : 'S_n) (m : 'X_{1..n}) : p \\is symmetric ->\n  (m#s \\in msupp p) = (m \\in msupp p).\nProof. by rewrite !mcoeff_msupp -mcoeff_sym => /issymP ->. Qed.\n\nLocal Notation \"m # s\" := [multinom m (s i) | i < n]\n  (at level 40, left associativity, format \"m # s\").\n\nLemma msym_coeff (p : {mpoly R[n]}) (m : 'X_{1..n}) (s : 'S_n) :\n  p \\is symmetric -> p@_(m#s) = p@_m.\nProof.\nmove/issymP=> /(_ s^-1)%g {1}<-; rewrite mcoeff_sym.\nby congr (_@__); apply/mnmP=> i /=; rewrite !mnmE permKV.\nQed.\n\nLemma msym1m p : msym 1 p = p.\nProof. by apply/mpolyP=> m; rewrite mcoeff_sym mperm1. Qed.\n\nLemma msymMm p (s1 s2 : 'S_n) : msym (s1 * s2)%g p = msym s2 (msym s1 p).\nProof. by apply/mpolyP=> m; rewrite !mcoeff_sym mpermM. Qed.\n\nLemma inj_msym (s : 'S_n) : injective (msym s).\nProof.\nmove=> p q; move/(congr1 (msym s^-1)%g).\nby rewrite -!msymMm mulgV !msym1m.\nQed.\n\nLemma mlead_msym_sorted (p : {mpoly R[n]}) : p \\is symmetric ->\n  forall (i j : 'I_n), i <= j -> (mlead p) j <= (mlead p) i.\nProof.\nmove=> sym_p i j le_ij; have [->|nz_p] := eqVneq p 0.\n  by rewrite mlead0 !mnm0E.\nset m := mlead p; case: leqP=> // h.\npose s := tperm i j; pose ms := m#s; have: (m < ms)%O.\n  apply/ltmcP; first by rewrite mdeg_mperm.\n  exists i=> [k lt_ki|]; last by rewrite mnmE tpermL.\n  rewrite mnmE tpermD // neq_ltn orbC ?lt_ki //.\n  by move/leq_trans: lt_ki => /(_ _ le_ij) ->.\nhave: ms \\in msupp p by rewrite issym_msupp // mlead_supp.\nby move/msupp_le_mlead; rewrite leNgt => /negbTE=> ->.\nQed.\n\nEnd MPolySym.\n\nArguments inj_msym  {n R}.\nArguments symmetric {n R}.\n\n(* -------------------------------------------------------------------- *)\nSection MPolySymComp.\nContext (n : nat) (R : ringType).\n\nLemma mcomp_sym k (p : {mpoly R[n]}) (t : n.-tuple {mpoly R[k]}) :\n  (forall i : 'I_n, t`_i \\is symmetric) -> p \\mPo t \\is symmetric.\nProof.\nmove=> sym_t; pose_big_enough l.\n  rewrite (comp_mpolywE _ (w := l)) //. 2: by close.\napply/rpred_sum=> m _; apply/rpredZ/rpred_prod=> i _.\nby rewrite (tnth_nth 0); apply/rpredX/sym_t.\nQed.\n\nEnd MPolySymComp.\n\n(* -------------------------------------------------------------------- *)\nSection MPolySymCompCom.\nContext (n : nat) (R : comRingType).\n\nLocal Notation \"m # s\" := [multinom m (s i) | i < n]\n  (at level 40, left associativity, format \"m # s\").\n\nLemma msym_mPo (s : 'S_n) (p : {mpoly R[n]}) k (T : n.-tuple {mpoly R[k]}) :\n  (msym s p) \\mPo T = p \\mPo [tuple tnth T (s i) | i < n].\nProof.\npose_big_enough l; [rewrite !(comp_mpolywE _ (w := l)) // | by close].\nhave FP (m : 'X_{1..n < l}) : mdeg (m#s) < l by rewrite mdeg_mperm bmdeg.\npose F (m : 'X_{1..n < l}) := BMultinom (FP m).\nhave inj_F: injective F.\n  by move=> m1 m2 /(congr1 val) /mperm_inj /val_inj.\nrewrite [RHS](reindex_inj inj_F); apply/eq_bigr=> m _ /=.\nrewrite mcoeff_sym (reindex_inj (@perm_inj _ s)) /=; congr (_ *: _).\nby apply/eq_bigr=> i _; rewrite mnmE tnth_mktuple.\nQed.\n\nLemma msym_comp_poly k (p : {mpoly R[n]}) (t : n.-tuple {mpoly R[k]}) :\n     p \\is symmetric\n  -> (forall s : 'S_k, perm_eq t [tuple (msym s t`_i) | i < n])\n  -> p \\mPo t \\is symmetric.\nProof.\nmove=> sym_p sym_t; apply/issymP=> s; pose_big_enough l.\n  rewrite (comp_mpolywE _ (w := l)) //. 2: by close.\ncase/tuple_permP: (sym_t s^-1)%g => s' tE.\npose F (m : 'X_{1..n < l}) := insubd m [multinom m (s' i) | i < n].\nhave FE m: F m = [multinom m (s' i) | i < n] :> 'X_{1..n}.\n  by rewrite insubdK // -topredE /= mdeg_mperm ?bmdeg.\nrewrite raddf_sum {1}(reindex_inj (h := F)) /=; last first.\n  move=> m1 m2 /(congr1 (@bmnm _ _)); rewrite !FE.\n  by move/mperm_inj=> /val_inj.\napply/eq_bigr=> m _; rewrite linearZ /= FE msym_coeff //.\nrewrite rmorph_prod /= (reindex_inj (perm_inj (s := s'^-1))) /=.\ncongr (_ *: _); apply/eq_bigr=> i _; rewrite rmorphX /=.\nrewrite mnmE permKV (tnth_nth 0) {1}tE -!tnth_nth.\nrewrite !tnth_map !tnth_ord_tuple permKV -msymMm.\nby rewrite mulVg msym1m -tnth_nth.\nQed.\n\nEnd MPolySymCompCom.\n\n(* -------------------------------------------------------------------- *)\nSection MPolySymUnit.\nContext (n : nat) (R : idomainType).\nImplicit Types (p q r : {mpoly R[n]}).\n\nLemma msymMK (p q : {mpoly R[n]}) :\n  p != 0 -> p \\is symmetric -> p * q \\is symmetric -> q \\is symmetric.\nProof.\nmove=> nz_p /issymP sym_p /issymP sym_pq; apply/issymP => s.\nby move/(_ s): sym_pq; rewrite msymM sym_p => /(mulfI nz_p).\nQed.\n\nLemma sym_divring : divring_closed (symmetric (n := n) (R := R)).\nProof.\nsplit; try solve [apply/rpred1 | apply/rpredB].\nmove=> p q sym_p sym_q /=; case: (boolP (q \\isn't a GRing.unit)).\n  by move/invr_out=> ->; apply/rpredM.\nrewrite negbK=> inv_q; apply/(msymMK _ sym_q).\n  by apply/contraTneq: inv_q=> ->; rewrite unitr0.\nby rewrite mulrCA divrr // mulr1.\nQed.\n\nCanonical sym_divringPred  := DivringPred sym_divring.\n\nEnd MPolySymUnit.\n\n(* -------------------------------------------------------------------- *)\nSection MElemPolySym.\nContext (n : nat) (R : ringType).\nImplicit Types (p q r : {mpoly R[n]}) (h : {set 'I_n}).\n\nDefinition mesym (k : nat) : {mpoly R[n]} :=\n  \\sum_(h : {set 'I_n} | #|h| == k) \\prod_(i in h) 'X_i.\n\nLocal Notation \"''s_' k\" := (@mesym k).\n\nLocal Notation \"m # s\" := [multinom m (s i) | i < n]\n  (at level 40, left associativity, format \"m # s\").\n\nDefinition mesym1 (h : {set 'I_n}) := [multinom i \\in h | i < n].\n\nLemma mesym1_set0 : mesym1 set0 = 0%MM.\nProof. by apply/mnmP=> i; rewrite mnmE mnm0E in_set0. Qed.\n\nLemma mesym1_set1 i : mesym1 [set i] = U_(i)%MM.\nProof. by apply/mnmP=> j; rewrite mnmE in_set1 mnmE eq_sym. Qed.\n\nLemma mesym1_setT : mesym1 setT = (\\sum_(i < n) U_(i))%MM.\nProof.\napply/mnmP=> i; rewrite mnmE mnm_sumE in_setT /=.\nrewrite (bigD1 i) //= mnmE eqxx big1 ?addn0 //.\nby move=> j; rewrite mnmE => /negbTE->.\nQed.\n\nLemma mesymE k : 's_k = \\sum_(h : {set 'I_n} | #|h| == k) 'X_[mesym1 h].\nProof.\napply/eq_bigr=> /= h _; rewrite mprodXE; congr 'X_[_].\napply/mnmP=> i; rewrite mnmE mnm_sumE big_mkcond /=.\nrewrite (bigD1 i) //= mnmE eqxx /= big1 ?addn0 // => j ne_ji.\nby case: (_ \\in _); rewrite // mnmE (negbTE ne_ji).\nQed.\n\nLemma mdeg_mesym1 h : mdeg (mesym1 h) = #|h|.\nProof.\nrewrite mdegE (bigID (mem h)) /= addnC big1 ?add0n; last first.\n  by move=> i i_notin_h; rewrite mnmE (negbTE i_notin_h).\nrewrite (eq_bigr (fun _ => 1%N)) ?sum1_card //.\nby move=> i i_in_h; rewrite mnmE i_in_h.\nQed.\n\nLemma inj_mesym1 : injective mesym1.\nProof.\nmove=> h1 h2 /mnmP eqh; apply/setP=> /= i.\nby have := eqh i; rewrite !mnmE; do! case: (_ \\in _).\nQed.\n\nLocal Hint Resolve inj_mesym1 : core.\n\nLemma msupp_mesym k :\n  perm_eq\n    (msupp 's_k)\n    [seq mesym1 h | h : {set 'I_n} <- enum {set 'I_n} & #|h| == k].\nProof.\nrewrite mesymE; apply/(perm_trans (msupp_sum _ _ _))=> /=.\n+ by rewrite /index_enum -enumT enum_uniq.\n+ move=> h1 h2 _ _ ne_h1h2 m /=; rewrite !msuppX !mem_seq1.\n  apply/negbTE/negP=> /andP[/eqP->] /eqP /inj_mesym1.\n  by move/eqP; rewrite (negbTE ne_h1h2).\nrewrite /index_enum -enumT /= (eq_map (fun h => msuppX _ (mesym1 h))).\nby rewrite (map_comp (cons^~ [::])) flatten_seq1.\nQed.\n\nLemma msupp_mesymP (k : nat) m :\n  (m \\in msupp 's_k) = [exists h : {set 'I_n}, (#|h| == k) && (m == mesym1 h)].\nProof.\nrewrite (perm_mem (msupp_mesym _)); apply/idP/existsP=> /=.\n+ case/mapP=> /= h; rewrite mem_filter=> /andP[/eqP<- _ ->].\n  by exists h; rewrite !eqxx.\n+ case=> h /andP[/eqP<- /eqP->]; apply/mapP; exists h=> //.\n  by rewrite mem_filter eqxx /= mem_enum.\nQed.\n\nDefinition mechar k (m : 'X_{1..n}) := (mdeg m == k) && [forall i, m i <= 1%N].\n\nLemma mecharP k m :\n  mechar k m = [exists h : {set 'I_n}, (m == mesym1 h) && (#|h| == k)].\nProof.\napply/idP/existsP=> /=; last first.\n  case=> h /andP[/eqP-> /eqP<-]; rewrite /mechar.\n  rewrite mdeg_mesym1 eqxx /=; apply/forallP=> /= i.\n  by rewrite mnmE leq_b1.\ncase/andP=> /eqP<- /forallP /= mE; exists [set i | m i != 0%N].\napply/andP; split; [apply/eqP/mnmP=> i|apply/eqP].\n  by rewrite mnmE inE; have := mE i; case: (m i)=> [|[|]].\nrewrite mdegE (bigID (fun i => m i == 0%N)) /=.\nrewrite big1 ?add0n; last by move=> i /eqP->.\nrewrite (eq_bigr (fun _ => 1%N)) ?sum1_card ?cardsE //.\nby move=> i; have := mE i; case: (m i) => [|[|]].\nQed.\n\nLemma mcoeff_mesym (k : nat) m : ('s_k)@_m = (mechar k m)%:R.\nProof.\nrewrite mecharP; case: (altP existsP) => /= [[h /andP[/eqP-> /eqP<-]]|].\n  rewrite mesymE raddf_sum (bigD1 h) //= mcoeffX eqxx big1 ?addr0 //.\n  move=> h' /andP[_ ne_h]; rewrite mcoeffX -[0]/0%:R.\n  by congr _%:R; apply/eqP; rewrite eqb0 inj_eq.\nrewrite negb_exists=> /forallP /= ne.\nrewrite mesymE raddf_sum big1 //= => h cardh; have := ne h.\nby rewrite cardh andbT mcoeffX; case: eqVneq.\nQed.\n\nLemma mem_msupp_mesym k m : m \\in msupp 's_k = mechar k m.\nProof.\nrewrite mcoeff_msupp mcoeff_mesym.\nby case: (mechar _ _); rewrite ?eqxx // oner_eq0.\nQed.\n\nLemma mperm_mechar k (m : 'X_{1..n}) (s : 'S_n) :\n  mechar k (m#s) = mechar k m.\nProof.\nrewrite /mechar mdeg_mperm; congr (_ && _).\napply/forallP/forallP=> //=.\n+ by move=> h i; move/(_ (s^-1 i))%g: h; rewrite mnmE permKV.\n+ by move=> h i; rewrite mnmE; apply/h.\nQed.\n\nLemma mesym_sym k : 's_k \\is symmetric.\nProof.\napply/issymP=> s; apply/mpolyP=> m.\nby rewrite mcoeff_sym !mcoeff_mesym mperm_mechar.\nQed.\n\nLemma mem_mesym1_mesym h : mesym1 h \\in msupp 's_#|h|.\nProof.\nrewrite mem_msupp_mesym mecharP; apply/existsP.\nby exists h; rewrite !eqxx.\nQed.\n\nLemma mesym0E : 's_0 = 1.\nProof.\nrewrite mesymE (bigD1 set0) ?cards0 //= mesym1_set0 mpolyX0.\nby rewrite big1 ?addr0 // => i /andP[/eqP/cards0_eq->]; rewrite eqxx.\nQed.\n\nLemma mesym1E : 's_1 = \\sum_(i < n) 'X_i.\nProof.\nrewrite mesymE -big_set /=; set S := [set _ | _].\nhave ->: S = [set [set i] | i : 'I_n].\n  apply/eqP; rewrite eqEcard (card_imset _ set1_inj).\n  rewrite card_draws /= !card_ord bin1 leqnn andbT.\n  apply/subsetP=> /= s; rewrite inE => /cards1P /= [i {s}->].\n  by apply/imsetP; exists i.\nrewrite big_imset /=; last by move=> i1 i2 _ _; apply/set1_inj.\nby apply/eq_bigr=> i _; rewrite mesym1_set1.\nQed.\n\nLemma mesymnnE : 's_n = \\prod_(i < n) 'X_i.\nProof.\nrewrite mesymE (bigD1 setT) ?cardsT ?card_ord //=.\nrewrite [X in _+X]big1 ?addr0; last first.\n  move=> i /andP []; rewrite eqEcard => /eqP ->.\n  by rewrite subsetT cardsT card_ord leqnn.\nby rewrite mprodXE mesym1_setT.\nQed.\n\nLemma mesym_geqnE i : i > n -> mesym i = 0.\nProof.\nrewrite /mesym => Hn; apply: big1 => s /eqP Hs; exfalso.\nby have:= subset_leq_card (subsetT s); rewrite Hs cardsT card_ord leqNgt Hn.\nQed.\n\nDefinition mesymlmnm k : {set 'I_n} := [set i : 'I_n | i < k].\nDefinition mesymlm   k : 'X_{1..n}  := mesym1 (mesymlmnm k).\n\nLet card_mesymlmnm k (le_kn : k <= n) : #|mesymlmnm k| = k.\nProof.\nrewrite -sum1dep_card -(big_ord_widen _ (fun _ => 1%N)) //=.\nby rewrite sum1_card card_ord.\nQed.\n\nLet mesymlmE k : mesymlm k = [multinom (i < k : nat) | i < n].\nProof. by apply/mnmP=> i; rewrite !mnmE in_set. Qed.\n\nLet mesymlm_max (h : {set 'I_n}) : #|h| <= n -> (mesym1 h <= mesymlm #|h|)%O.\nProof.                        (* FIXME: far too convoluted *)\nmove=> le_Ch_n; pose P := [exists i : 'I_n, (i < #|h|) && (i \\notin h)].\ncase: (boolP P)=> [/existsP[/= i /andP[lt_ih i_notin_h]]|hNP]; last first.\n  suff ->: h = mesymlmnm #|h|; first by rewrite card_mesymlmnm.\n  move: hNP; rewrite negb_exists => /forallP /= {P} hNP.\n  have eq1: forall i : 'I_n, i < #|h| -> i \\in h.\n    move=> i lt_i_Ch; move: (hNP i); rewrite negb_and.\n    by rewrite lt_i_Ch /= negbK.\n  have eq2: forall i : 'I_n, i >= #|h| -> i \\notin h.\n    move=> i le_Ch_i; apply/negP=> i_in_h; move: (leqnn #|h|).\n    rewrite -{1}sum1_card; pose P (j : 'I_n) := j < #|h|.\n    rewrite (bigID P) big_andbC (eq_bigl P) {}/P /=; last first.\n      move=> j /=; apply/andb_idr=> lt_j_Ch; have := hNP j.\n      by rewrite lt_j_Ch /= negbK.\n    rewrite -(big_ord_widen _ (fun _ => 1%N)) // sum1_card card_ord.\n    rewrite -[X in _<=X]addn0 leq_add2l leqn0; apply/eqP.\n    by rewrite (bigD1 i) // -leqNgt le_Ch_i andbT.\n  apply/setP=> i; rewrite in_set; case: (leqP #|h| i).\n    by move/eq2/negbTE. by move/eq1.\npose i0 : 'I_n := [arg min_(j < i | j \\notin h) j].\napply/ltW/ltmcP; first by rewrite !mdeg_mesym1 card_mesymlmnm.\nexists i0; rewrite {}/i0; case: arg_minnP => //=.\n+ move=> i0 i0_notin_h i0_min j lt_j_i0; rewrite !mnmE in_set.\n  rewrite (@ltn_trans i) // 1?(@leq_trans i0) // ?i0_min //.\n  by case: (boolP (j \\in h))=> // /i0_min; rewrite leqNgt lt_j_i0.\n+ move=> i0 i0_notin_h i0_min; rewrite !mnmE in_set.\n  by rewrite (negbTE i0_notin_h) lt0n // (@leq_ltn_trans i) // i0_min.\nQed.\n\nLemma mesym_neq0 k (le_kn : k <= n) : 's_k != 0 :> {mpoly R[n]}.\nProof.\napply/eqP=> z_sk; pose h : {set 'I_n} := mesymlmnm k.\nhave := mem_mesym1_mesym h; rewrite card_mesymlmnm //.\nby rewrite mcoeff_msupp z_sk mcoeff0 eqxx.\nQed.\n\nLemma mlead_mesym k (le_kn : k <= n) :\n  mlead 's_k = [multinom (i < k : nat) | i < n].\nProof.\nrewrite -mesymlmE /mlead (bigD1_seq (mesymlm k)) //=; last first.\n  rewrite mem_msupp_mesym mecharP; apply/existsP.\n  by exists (mesymlmnm k); rewrite card_mesymlmnm ?eqxx.\napply/join_l/joinsP_seq=> /= {}m.\nrewrite msupp_mesymP => /existsP[/=].\nmove=> h /andP[/eqP Chk /eqP->] _; rewrite -Chk.\nby apply/mesymlm_max; rewrite Chk.\nQed.\n\nLemma mleadc_mesym k (le_kn : k <= n) : mleadc 's_k = 1.\nProof.\nrewrite mcoeff_mesym; case: (boolP (mechar _ _))=> //=.\nby rewrite -mem_msupp_mesym mlead_supp // mesym_neq0.\nQed.\n\nDefinition tmono (n : nat) (h : seq 'I_n) :=\n  sorted ltn (map val h).\n\nLemma uniq_tmono (h : seq 'I_n) : tmono h -> uniq h.\nProof.\nrewrite /tmono => /sorted_uniq; rewrite (map_inj_uniq val_inj).\nby apply; [apply/ltn_trans | move=> ?; rewrite /ltn /= ltnn].\nQed.\n\nLemma eq_tmono (h1 h2 : seq 'I_n) : tmono h1 -> tmono h2 -> h1 =i h2 -> h1 = h2.\nProof.\nmove=> tm1 tm2 h; apply/(inj_map val_inj).\napply/(irr_sorted_eq (leT := ltn)) => //.\n  exact/ltn_trans.\n  by move=> ?; rewrite /ltn /= ltnn.\nmove=> m; apply/mapP/mapP; case=> /= x;\n  by rewrite (h, =^~ h)=> {}h ->; exists x.\nQed.\n\nLemma mesym_tupleE (k : nat) : 's_k =\n  \\sum_(h : k.-tuple 'I_n | tmono h) \\prod_(i <- h) 'X_i.\nProof.\nhave tval_tcast T k1 k2 (eq : k1 = k2) (x : k1.-tuple T) :\n  tval (tcast eq x) = tval x.\n+ by rewrite /tcast; case: k2 / eq.\npose t2s (t : k.-tuple 'I_n) := [set x | x \\in t].\nrewrite /mesym -[X in X=_]big_set -[X in _=X]big_set /=.\nset E := [set t2s x | x in [pred t | tmono (tval t)]].\nhave h: E = [set i : {set 'I_n} | #|i| == k].\n  apply/setP=> /= h; rewrite inE; apply/imsetP/idP=> /=.\n  + case=> t; rewrite inE => tmono_t -> /=; rewrite /t2s.\n    rewrite cardsE /= -[X in _==X](size_tuple t).\n    by apply/eqP/card_uniqP/uniq_tmono.\n  + move/eqP=> eq_sz; exists (tcast eq_sz [tuple of (enum h)]).\n    * rewrite inE /tmono tval_tcast /=; pose I := enum 'I_n.\n      apply/(subseq_sorted _ (s2 := [seq val i | i <- I])).\n        exact/ltn_trans.\n        by apply/map_subseq; rewrite /enum_mem -enumT; apply/filter_subseq.\n        by rewrite val_enum_ord iota_ltn_sorted.\n    * by apply/setP=> i; rewrite !(inE, memtE) tval_tcast mem_enum.\nrewrite -h {h}/E big_imset 1?big_set /=; last first.\n  move=> t1 t2; rewrite !inE => tmono_t1 tmono_t2 /setP eq.\n  apply/eqP; rewrite eqE /=; apply/eqP/eq_tmono => // i.\n  by move/(_ i): eq; rewrite /t2s !inE.\napply/eq_big=> // i; rewrite inE 1?big_set /=.\ncase: i => i sz_i /= tmono_i; rewrite (eq_bigl (mem i)) //=.\nby rewrite !mprodXE big_uniq //; apply/uniq_tmono.\nQed.\n\nEnd MElemPolySym.\n\nLocal Notation \"''s_' ( K , n , k )\" := (@mesym n K k).\nLocal Notation \"''s_' ( n , k )\" := (@mesym n _ k).\n\n(* -------------------------------------------------------------------- *)\nSection MWiden.\nContext (n : nat) (R : ringType).\n\nDefinition mwiden (p : {mpoly R[n]}) : {mpoly R[n.+1]} :=\n  mmap (@mpolyC _ _) (fun i => 'X_(widen i)) p.\n\nDefinition mnmwiden (m : 'X_{1..n}) : 'X_{1..n.+1} := [multinom of rcons m 0%N].\n\nLemma mnmwiden_ordmax m : (mnmwiden m) ord_max = 0%N.\nProof.\nrewrite multinomE (tnth_nth 0%N) nth_rcons /=.\nby rewrite size_tuple ltnn eqxx.\nQed.\n\nLemma mnmwiden_widen m (i : 'I_n) : (mnmwiden m) (widen i) = m i.\nProof.\ncase: m=> m; rewrite !(mnm_nth 0%N) nth_rcons.\nby rewrite size_tuple /=; case: i => i /= ->.\nQed.\n\nLemma mnmwiden0 : mnmwiden 0 = 0%MM.\nProof.\napply/mnmP=> i; rewrite mnmE (mnm_nth 0%N) nth_rcons.\ncase: ssrnat.ltnP; last by rewrite ?if_same.\nrewrite size_tuple=> lt_in; pose oi := Ordinal lt_in.\nby rewrite (nth_map oi) //; rewrite size_tuple.\nQed.\n\nLemma mnmwidenD m1 m2 : mnmwiden (m1 + m2) = (mnmwiden m1 + mnmwiden m2)%MM.\nProof.\napply/mnmP=> i; rewrite mnmDE !multinomE !(tnth_nth 0%N) /=.\nrewrite !nth_rcons size_map size_enum_ord !size_tuple !if_same.\ncase h: (i < n); last by rewrite addn0.\nrewrite (nth_map (Ordinal h)) ?size_enum_ord //.\nby rewrite !(mnm_nth 0%N) /= !nth_enum_ord.\nQed.\n\nLemma mnmwiden_sum (I : Type) (r : seq I) P F :\n    mnmwiden (\\sum_(x <- r | P x) (F x))\n  = (\\sum_(x <- r | P x) (mnmwiden (F x)))%MM.\nProof. exact/big_morph/mnmwiden0/mnmwidenD. Qed.\n\nLemma mnmwiden1 i : (mnmwiden U_(i) = U_(widen i))%MM.\nProof.\napply/mnmP; case=> j /= lt; rewrite /mnmwiden !mnmE; apply/esym.\nrewrite eqE multinomE /tnth /=; move: (tnth_default _ _) => x.\nrewrite nth_rcons size_map size_enum_ord; move: lt.\nrewrite ltnS leq_eqVlt => /predU1P[->|lt].\n  by apply/eqP; rewrite ltnn eqxx eqb0 ltn_eqF.\nrewrite lt (nth_map i) ?size_enum_ord //.\nby apply/esym; rewrite eqE /= nth_enum_ord.\nQed.\n\nLemma inj_mnmwiden : injective mnmwiden.\nProof.\nmove=> m1 m2 /mnmP h; apply/mnmP=> i; move: (h (widen i)).\nby rewrite !mnmwiden_widen.\nQed.\n\nLemma mwiden_is_additive : additive mwiden.\nProof. exact/mmap_is_additive. Qed.\n\nLemma mwiden0     : mwiden 0 = 0               . Proof. exact: raddf0. Qed.\nLemma mwidenN     : {morph mwiden: x / - x}    . Proof. exact: raddfN. Qed.\nLemma mwidenD     : {morph mwiden: x y / x + y}. Proof. exact: raddfD. Qed.\nLemma mwidenB     : {morph mwiden: x y / x - y}. Proof. exact: raddfB. Qed.\nLemma mwidenMn  k : {morph mwiden: x / x *+ k} . Proof. exact: raddfMn. Qed.\nLemma mwidenMNn k : {morph mwiden: x / x *- k} . Proof. exact: raddfMNn. Qed.\n\nCanonical mwiden_additive := Additive mwiden_is_additive.\n\nLemma mwiden_is_multiplicative : multiplicative mwiden.\nProof.\napply/commr_mmap_is_multiplicative=> [i p|p m m']; first exact/commr_mpolyX.\nrewrite /= /mmap1; elim/big_rec: _ => /= [|i q _]; first exact/commr1.\nexact/commrM/commrX/commr_mpolyX.\nQed.\n\nCanonical mwiden_rmorphism := AddRMorphism mwiden_is_multiplicative.\n\nLemma mwiden1 : mwiden 1 = 1.\nProof. exact: rmorph1. Qed.\n\nLemma mwidenM : {morph mwiden: x y / x * y}.\nProof. exact: rmorphM. Qed.\n\nLemma mwidenC c : mwiden c%:MP = c%:MP.\nProof. by rewrite /mwiden mmapC. Qed.\n\nLemma mwidenN1 : mwiden (-1) = -1.\nProof. by rewrite raddfN /= mwidenC. Qed.\n\nLemma mwidenX m : mwiden 'X_[m] = 'X_[mnmwiden m].\nProof.\nrewrite /mwiden mmapX /mmap1 /= (mpolyXE _ 1); apply/esym.\nrewrite (eq_bigr (fun i => 'X_i ^+ (mnmwiden m i))); last first.\n  by move=> i _; rewrite perm1.\nrewrite big_ord_recr /= mnmwiden_ordmax expr0 mulr1.\nby apply/eq_bigr=> i _; rewrite mnmwiden_widen.\nQed.\n\nLemma mwidenZ c p : mwiden (c *: p) = c *: mwiden p.\nProof. by rewrite /mwiden mmapZ /= mul_mpolyC. Qed.\n\nLemma mwidenE (p : {mpoly R[n]}) (k : nat) : msize p <= k ->\n  mwiden p = \\sum_(m : 'X_{1..n < k}) (p@_m *: 'X_[mnmwiden m]).\nProof.\nmove=> h; rewrite {1}[p](mpolywE (k := k)) //.\nrewrite raddf_sum /=; apply/eq_bigr=> m _.\nby rewrite mwidenZ mwidenX.\nQed.\n\nLemma mwiden_mnmwiden p m : (mwiden p)@_(mnmwiden m) = p@_m.\nProof.\nrewrite (mwidenE (k := msize p)) // raddf_sum /=.\nrewrite [X in _=X@__](mpolywE (k := msize p)) //.\nrewrite raddf_sum /=; apply/eq_bigr=> i _.\nby rewrite !mcoeffZ !mcoeffX inj_eq //; apply/inj_mnmwiden.\nQed.\n\nLemma inj_mwiden : injective mwiden.\nProof.\nmove=> m1 m2 /mpolyP h; apply/mpolyP=> m.\nby move: (h (mnmwiden m)); rewrite !mwiden_mnmwiden.\nQed.\n\nDefinition mpwiden (p : {poly {mpoly R[n]}}) : {poly {mpoly R[n.+1]}} :=\n  map_poly mwiden p.\n\nLemma mpwiden_is_additive : additive mpwiden.\nProof. exact: map_poly_is_additive. Qed.\n\nCanonical mpwiden_additive := Additive mpwiden_is_additive.\n\nLemma mpwiden_is_rmorphism : rmorphism mpwiden.\nProof. exact: map_poly_is_rmorphism. Qed.\n\nCanonical mpwiden_rmorphism := RMorphism mpwiden_is_rmorphism.\n\nLemma mpwidenX : mpwiden 'X = 'X.\nProof. by rewrite /mpwiden map_polyX. Qed.\n\nLemma mpwidenC c : mpwiden c%:P = (mwiden c)%:P.\nProof. by rewrite /mpwiden map_polyC. Qed.\n\nLemma mpwidenZ c p : mpwiden (c *: p) = mwiden c *: (mpwiden p).\nProof. by rewrite /mpwiden map_polyZ. Qed.\n\nEnd MWiden.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyUni.\nContext (n : nat) (R : ringType).\nImplicit Types (p q : {mpoly R[n.+1]}).\n\nLet X (i : 'I_n.+1) : {poly {mpoly R[n]}} :=\n  match split (cast_ord (esym (addn1 n)) i) with\n  | inl j => ('X_j)%:P\n  | inr _ => 'X\n  end.\n\nDefinition muni (p : {mpoly R[n.+1]}) : {poly {mpoly R[n]}} :=\n  nosimpl (mmap (polyC \\o @mpolyC _ _) X p).\n\nLet XE m : mmap1 X m = 'X_[[multinom (m (widen i)) | i < n]] *: 'X^(m ord_max).\nProof.\nhave X1: X ord_max = 'X.\n  rewrite /X; case: splitP=> //; case=> j lt_jn /eqP /=.\n  by have := lt_jn; rewrite ltn_neqAle eq_sym=> /andP[/negbTE->].\nhave X2 i: X (widen i) = ('X_i)%:P.\n  rewrite /X; case: splitP=> [j eq|j].\n    by congr ('X__)%:P; apply/val_inj=> /=; rewrite -eq.\n  by rewrite ord1 /= addn0 => /eqP /=; rewrite ltn_eqF.\nrewrite /mmap1 big_ord_recr /= X1 -mul_polyC.\nrewrite mpolyXE_id rmorph_prod /=; congr (_ * _).\nby apply/eq_bigr=> i _; rewrite X2 rmorphX /= mnmE.\nQed.\n\nLemma muniE p : muni p =\n  \\sum_(m <- msupp p)\n     p@_m *: 'X_[[multinom (m (widen i)) | i < n]] *: 'X^(m ord_max).\nProof.\napply/eq_bigr=> m _; rewrite XE /= -!mul_polyC.\nby rewrite mulrA -polyCM mul_mpolyC.\nQed.\n\nDefinition mmulti (p : {poly {mpoly R[n]}}) : {mpoly R[n.+1]} :=\n  \\sum_(i < size p) ((mwiden p`_i) * ('X_ord_max) ^+ i).\n\nLemma muni_is_additive : additive muni. Proof. exact/mmap_is_additive. Qed.\n\nCanonical muni_additive := Additive muni_is_additive.\n\nLemma muni0     : muni 0 = 0               . Proof. exact: raddf0. Qed.\nLemma muniN     : {morph muni: x / - x}    . Proof. exact: raddfN. Qed.\nLemma muniD     : {morph muni: x y / x + y}. Proof. exact: raddfD. Qed.\nLemma muniB     : {morph muni: x y / x - y}. Proof. exact: raddfB. Qed.\nLemma muniMn  k : {morph muni: x / x *+ k} . Proof. exact: raddfMn. Qed.\nLemma muniMNn k : {morph muni: x / x *- k} . Proof. exact: raddfMNn. Qed.\n\nLemma muni_is_multiplicative : multiplicative muni.\nProof.\napply/commr_mmap_is_multiplicative=> /= [i p|p m1 m2].\n  rewrite /X; case: splitP=> j _; last exact/commr_polyX.\n  by apply/polyP=> k; rewrite coefCM coefMC; apply/commr_mpolyX.\napply/polyP=> k; rewrite coefCM coefMC XE coefZ coefXn.\ncase: eqP; rewrite ?(mulr0, mul0r, mulr1, mul1r) //= => _.\nexact/commr_mpolyX.\nQed.\n\nCanonical muni_rmorphism : {rmorphism {mpoly R[n.+1]} -> {poly {mpoly R[n]}}} :=\n  AddRMorphism muni_is_multiplicative.\n\nLemma muni1 : muni 1 = 1.\nProof. exact: rmorph1. Qed.\n\nLemma muniM : {morph muni: x y / x * y}.\nProof. exact: rmorphM. Qed.\n\nLemma muniC c : muni c%:MP = (c%:MP)%:P.\nProof. by rewrite /muni mmapC. Qed.\n\nLemma muniN1 : muni (-1) = -1.\nProof. by rewrite raddfN /= muniC. Qed.\n\nLemma muniZ c p : muni (c *: p) = c%:MP *: muni p.\nProof. by rewrite /muni mmapZ /= mul_polyC. Qed.\n\nEnd MPolyUni.\n\n(* -------------------------------------------------------------------- *)\nSection MESymViete.\nLocal Notation mw  := mwiden.\nLocal Notation mpw := mpwiden.\n\nLocal Notation swiden h :=\n  [set widen x | x in h : {set 'I__}]\n  (only parsing).\n\nLocal Notation S1 n k :=\n  [set swiden h | h in {set 'I_n} & #|h| == k.+1]\n  (only parsing).\n\nLocal Notation S2 n k :=\n  [set ord_max |: swiden h | h in {set 'I_n} & #|h| == k]\n  (only parsing).\n\nLet inj_widen n : injective (widen : 'I_n -> _).\nProof. by move=> x y /eqP; rewrite eqE /= val_eqE => /eqP. Qed.\n\nLocal Hint Resolve inj_widen : core.\n\nLet inj_swiden n : injective (fun h : {set 'I_n} => swiden h).\nProof.\nhave h m (x : 'I_n): (widen x \\in swiden m) = (x \\in m).\n  apply/imsetP/idP=> /= [[y y_in_m /inj_widen ->//]|].\n  by move=> x_in_m; exists x.\nmove=> m1 m2 /= /setP eq; apply/setP=> /= x.\nby have := eq (widen x); rewrite !h.\nQed.\n\nLocal Hint Resolve inj_swiden : core.\n\nLet inj_mDswiden n : injective (fun h : {set 'I_n} => ord_max |: swiden h).\nProof.\nmove=> h1 h2 /= /setP eq; apply/inj_swiden.\napply/setP => /= x; have {eq} := (eq x).\nrewrite !inE; case: eqP=> [-> _|//].\nhave E (h : {set 'I_n}): ord_max \\in swiden h = false.\n  apply/negP; case/imsetP=> /= y _ /eqP.\n  by rewrite eqE /= eq_sym ltn_eqF.\nby rewrite !E.\nQed.\n\nLet disjoint_S n k : [disjoint (S1 n k) & (S2 n k)].\nProof.\nrewrite -setI_eq0; apply/eqP/setP=> /= x.\nrewrite !in_set; apply/negP=> /andP[].\ncase/imsetP=> /= h1 _ -> /imsetP /= [h2 _].\nmove/setP/(_ ord_max); rewrite !in_set eqxx /=.\ncase/imsetP=> /= {h1 h2} m _ /eqP.\nby rewrite eqE /= eq_sym ltn_eqF.\nQed.\n\nLet union_S n k :\n  [set h in {set 'I_n.+1} | #|h| == k.+1] = S1 n k :|: S2 n k.\nProof.\napply/eqP; rewrite eq_sym eqEcard; apply/andP; split.\n  rewrite subUset; apply/andP; split.\n    apply/subsetP=> h /imsetP /= [m]; rewrite inE.\n    by move=> eq ->; rewrite inE card_imset //=.\n  apply/subsetP=> h /imsetP /= [m]; rewrite inE.\n  move=> eq->; rewrite inE cardsU1 card_imset //=.\n  rewrite -[k.+1]add1n (eqP eq) eqn_add2r eqb1.\n  apply/negP=> /imsetP [/=] x _ /eqP.\n  by rewrite eqE /= eq_sym ltn_eqF.\nhave := disjoint_S n k; rewrite -leq_card_setU=> /eqP->.\nrewrite !card_imset //= ?card_draws /=;\n  try exact/inj_swiden; try exact/inj_mDswiden.\n  (* remove the line above once requiring Coq >= 8.17 *)\nby rewrite !card_ord binS.\nQed.\n\nLemma mesymSS (R : ringType) n k :\n  's_(n.+1, k.+1) = mw 's_(n, k.+1) + mw 's_(n, k) * 'X_(ord_max)\n  :> {mpoly R[n.+1]}.\nProof.\nrewrite /mesym -big_set /= union_S big_set.\nrewrite bigU ?disjoint_S //=; congr (_ + _).\n+ rewrite big_imset /=; last by move=> ?? _ _; apply/inj_swiden.\n  rewrite big_set /= raddf_sum /=; apply/eq_bigr=> h _.\n  rewrite !mprodXE mwidenX; congr 'X_[_]; apply/mnmP=> j.\n  rewrite mnmwiden_sum !mnm_sumE big_imset //=; last first.\n    by move=> ?? _ _; apply/inj_widen.\n  by apply/eq_bigr=> i _; rewrite mnmwiden1.\n+ rewrite big_imset /=; last by move=> t1 t2 _ _; apply/inj_mDswiden.\n  rewrite big_set /= raddf_sum /= mulr_suml; apply/eq_bigr=> h _.\n  rewrite !mprodXE mwidenX -mpolyXD; congr 'X_[_].\n  rewrite (big_setD1 ord_max) /= ?in_setU1 ?eqxx //=.\n  rewrite addmC setU1K //= ?mnmwiden_sum ?big_imset /=.\n    by congr (_ + _)%MM; apply/eq_bigr=> i _; rewrite mnmwiden1.\n    by move=> ?? _ _; apply/inj_widen.\n    apply/negP; case/imsetP=> /= x _ /eqP.\n    by rewrite eqE /= eq_sym ltn_eqF.\nQed.\n\nLemma Viete :\n  forall n,\n       \\prod_(i < n   ) ('X - ('X_i)%:P)\n    =  \\sum_ (k < n.+1) (-1)^+k *: ('s_(n, k) *: 'X^(n-k))\n    :> {poly {mpoly int[n]}}.\nProof.\nelim => [|n ih].\n  by rewrite !big_ord0 big_ord1 mesym0E expr0 !scale1r.\npose F n k : {poly {mpoly int[n]}} :=\n  (-1)^+k *: ('s_(n, k) *: 'X^(n-k)).\nhave Fn0 l: F l 0%N = 'X^l.\n  by rewrite /F expr0 mesym0E !scale1r subn0.\nhave Fnn l: F l l = (-1)^+l *: \\prod_(i < l) ('X_i)%:P.\n  by rewrite /F mesymnnE subnn expr0 alg_polyC rmorph_prod.\nrewrite big_ord_recr /=; set p := (\\prod_(_ < _) _).\nhave {p}->: p = mpw (\\prod_(i < n) ('X - ('X_i)%:P)).\n  rewrite /mpwiden rmorph_prod /=; apply/eq_bigr.\n  move=> /= i _; rewrite raddfB /= map_polyX map_polyC /=.\n  by rewrite mwidenX mnmwiden1.\nrewrite {}ih (eq_bigr (F n.+1 \\o val)) //; apply/esym.\nrewrite (eq_bigr (F n \\o val)) // -!(big_mkord xpredT).\nrewrite raddf_sum /= mulrBr !mulr_suml.\nrewrite big_nat_recl 1?[X in X-_]big_nat_recl //.\nrewrite -!addrA !Fn0; congr (_ + _).\n  by rewrite rmorphX /= mpwidenX exprSr.\nrewrite big_nat_recr 1?[X in _-X]big_nat_recr //=.\nrewrite opprD !addrA; congr (_ + _); last first.\n  rewrite !Fnn !mpwidenZ !rmorphX /= mwidenN1.\n  rewrite exprS mulN1r scaleNr -scalerAl; congr (- (_ *: _)).\n  rewrite big_ord_recr rmorph_prod /=; congr (_ * _).\n  by apply/eq_bigr=> i _; rewrite mpwidenC mwidenX mnmwiden1.\nrewrite -sumrB !big_seq; apply/eq_bigr => i /=.\nrewrite mem_index_iota => /andP [_ lt_in]; rewrite {Fn0 Fnn}/F.\nrewrite subSS mesymSS !mpwidenZ !rmorphX /= !mwidenN1 !mpwidenX.\nrewrite exprS mulN1r !scaleNr mulNr -opprD; congr (-_).\nrewrite -!scalerAl -scalerDr; congr (_ *: _).\nrewrite -exprSr -subSn // subSS scalerDl; congr (_ + _).\nby rewrite -!mul_polyC !mulrA mulrAC polyCM.\nQed.\n\nLemma mroots_coeff (R : idomainType) n (cs : n.-tuple R) (k : 'I_n.+1) :\n    (\\prod_(c <- cs) ('X - c%:P))`_(n - k)\n  = (-1)^+k * 's_(n, k).@[tnth cs].\nProof.\npose P := (\\prod_(i < n) ('X - ('X_i)%:P) : {poly {mpoly int[n]}}).\npose f := mmap intr (tnth cs): {mpoly int[n]} -> R.\npose F := fun i => 'X - (tnth cs i)%:P.\nmove: (Viete n) => /(congr1 (map_poly f)).\nrewrite rmorph_prod /= (eq_bigr F); last first.\n  move=> i _; rewrite raddfB /= map_polyX map_polyC /=.\n  by rewrite mmapX mmap1U.\nrewrite big_tuple => ->; rewrite raddf_sum coef_sum /=.\nrewrite (bigD1 k) //= big1 ?addr0; last first.\n  case=> i /= lt_iSk; rewrite eqE /= => ne_ik.\n  rewrite !map_polyZ /= map_polyXn !coefZ coefXn.\n  rewrite -(eqn_add2r i) subnK // addnC.\n  rewrite -(eqn_add2r k) -addnA subnK 1?addnC; last first.\n    by move: (ltn_ord k); rewrite ltnS.\n  by rewrite eqn_add2l (negbTE ne_ik) !mulr0.\nrewrite !map_polyZ !rmorphX raddfN /= mmapC !coefZ /=.\ncongr (_ * _); rewrite map_polyX coefXn eqxx mulr1.\nrewrite /mesym; rewrite !raddf_sum /=; apply/eq_bigr.\nmove=> i _; rewrite !rmorph_prod /=; apply/eq_bigr.\nby move=> j _; rewrite mmapX mmap1U mevalXU.\nQed.\n\nLemma mroots_sum (R : idomainType) (n : nat) (cs : n.+1.-tuple R) :\n  \\sum_(c <- cs) c = - (\\prod_(c <- cs) ('X - c%:P))`_n.\nProof.\nmove: (mroots_coeff cs) => /(_ 1); rewrite subSS subn0=> ->.\nrewrite expr1 mulN1r opprK mesym1E raddf_sum /=.\nby rewrite big_tuple; apply/eq_bigr=> /= i _; rewrite mevalXU.\nQed.\n\nEnd MESymViete.\n\n(* -------------------------------------------------------------------- *)\nSection MESymFundamental.\nContext (n : nat) (R : comRingType).\nImplicit Types (m : 'X_{1..n}).\n\nLocal Notation \"m # s\" := [multinom m (s i) | i < n]\n  (at level 40, left associativity, format \"m # s\").\n\nLocal Notation S := [tuple 's_(R, n, i.+1) | i < n].\n\nLet mlead_XS m :\n  mlead ('X_[R, m] \\mPo S) = [multinom \\sum_(j : 'I_n | i <= j) (m j) | i < n].\nProof.\nrewrite comp_mpolyX mlead_prod_proper=> /=; last first.\n  move=> i _ _; rewrite tnth_map tnth_ord_tuple.\n  rewrite mleadX_proper /= ?mleadc_mesym //; last exact/lreg1.\n  by rewrite mleadcX ?mleadc_mesym //; apply/lregX/lreg1.\npose F (i : 'I_n) := [multinom (j <= i) * (m i) | j < n].\nrewrite (eq_bigr F) {}/F=> [|i _]; last first.\n  rewrite tnth_map tnth_ord_tuple mleadX_proper.\n    rewrite mlead_mesym //; apply/mnmP=> j.\n    by rewrite mulmnE !mnmE mulnC ltnS.\n  by rewrite mleadc_mesym //; apply/lreg1.\napply/mnmP=> i; apply/esym; rewrite mnm_sumE mnmE big_mkcond /=.\napply/eq_bigr=> j _; rewrite mnmE; case: leqP=> _.\n  by rewrite mul1n. by rewrite mul0n.\nQed.\n\nLet mleadc_XS l : mleadc ('X_[l] \\mPo S) = 1.\nProof.\nrewrite comp_mpolyX mlead_prod_proper ?mleadc_prod; last first.\n  move=> /= i _ _; rewrite tnth_map tnth_ord_tuple.\n  rewrite mleadX_proper // ?mleadcX ?mleadc_mesym //.\n    exact/lregX/lreg1. exact/lreg1.\nrewrite (eq_bigr (fun _ => 1)) /=; last first.\n  move=> i _; rewrite tnth_map tnth_ord_tuple.\n  rewrite mleadX_proper ?mleadcX ?mleadc_mesym //.\n    by rewrite expr1n. exact/lreg1.\nby rewrite prodr_const expr1n.\nQed.\n\nLet free_XS : injective (fun m => mlead ('X_[R, m] \\mPo S)).\nProof.\nmove=> m1 m2; apply: contra_eq.\nmove=> ne_m1m2; apply/negP=> /eqP eqXS.\npose F m i := (\\sum_(j : 'I_n | i <= j) (m j))%N.\nhave {eqXS} eqF i: F m1 i = F m2 i.\n  case: (ssrnat.ltnP i n)=> [lt_in|le_ni]; last first.\n    rewrite /F !big1 //= => j /(leq_trans le_ni);\n    by rewrite leqNgt ltn_ord.\n  by move/mnmP/(_ (Ordinal lt_in)): eqXS; rewrite !mlead_XS !mnmE.\napply/negP: ne_m1m2; rewrite negbK; apply/eqP/mnmP=> i.\nrewrite -[i in m1 i]rev_ordK -[i in m2 i]rev_ordK.\npose G m i := nth 0%N m (n-i.+1); rewrite !(mnm_nth 0%N) /=.\napply/(@psumn_eq n (G m1) (G m2)); rewrite ?subnSK ?leq_subr //.\nmove=> j le_jn; have Geq m: (\\sum_(i < n | i < j) G m i = F m (n-j))%N.\n  rewrite (reindex_inj rev_ord_inj) /= /F; apply/eq_big=> l /=.\n  + by rewrite subnSK // !leq_subLR addnC.\n  + by move=> _; rewrite /G subnS subKn //= (mnm_nth 0%N).\nby rewrite !Geq.\nQed.\n\nLet mlead_XLS (m : 'X_{1..n}) :\n  let c i := nth 0%N m i in\n  let F i := (c i - c i.+1)%N in\n     (forall i j : 'I_n, i <= j -> m j <= m i)\n  -> mlead ('X_[R, F#val] \\mPo S) = m.\nProof.\nmove=> c F srt_m; rewrite mlead_XS; apply/mnmP=> i.\nrewrite mnmE; rewrite (eq_bigr (F \\o val)); last first.\n  by move=> /= j _; rewrite mnmE.\nrewrite -big_mkord (big_cat_nat _ (n := i)) // 1?ltnW //=.\nrewrite big_nat_cond big_pred0 ?add0n; last first.\n  by move=> j /=; rewrite ltnNge andNb.\nrewrite big_nat_cond (eq_bigl (fun j => i <= j < n)); last first.\n  by move=> j /=; apply/andb_idr=> /andP[].\nrewrite -big_nat; rewrite sumn_range 1?ltnW //.\n  rewrite /c [X in (_-X)%N]nth_default ?size_tuple //.\n  by rewrite subn0 (mnm_nth 0%N).\nmove=> j1 j2; rewrite ltnS=> /andP[le_j1j2].\nrewrite leq_eqVlt ltn_subRL => /predU1P[->|].\n  by rewrite subnK ?[i <= _]ltnW // /c nth_default // size_tuple.\nrewrite addnC=> lt_j2Di_n; have lt_j1Di_n: j1 + i < n.\n  by apply/(@leq_ltn_trans (j2+i)); rewrite // leq_add2r.\nhave /= := srt_m (Ordinal lt_j1Di_n) (Ordinal lt_j2Di_n).\nby rewrite !(mnm_nth 0%N) /=; apply; rewrite leq_add2r.\nQed.\n\nLet mweight_XLS (m : 'X_{1..n}) :\n  let c i := nth 0%N m i in\n  let F i := (c i - c i.+1)%N in\n     (forall i j : 'I_n, i <= j -> m j <= m i)\n  -> mweight 'X_[R, F#val] = (mdeg m).+1.\nProof.\nmove=> c F srt_m; rewrite mmeasureX /mnmwgt /=; congr _.+1.\nrewrite (eq_bigr (fun i : 'I_n => (F i) * i.+1))%N; last first.\n  by move=> i _; rewrite mnmE.\nrewrite mdegE sumn_wgt_range; last first.\n  move=> i j /andP[le_ij]; rewrite ltnS leq_eqVlt => /predU1P[->|].\n    by rewrite {1}/c nth_default // size_tuple.\n  move=> lt_jn; have lt_in: i < n by exact: leq_ltn_trans le_ij _.\n  have /(_ le_ij) := srt_m (Ordinal lt_in) (Ordinal lt_jn).\n  by rewrite /fun_of_multinom !(tnth_nth 0%N).\nrewrite {2}/c nth_default ?size_tuple // muln0 subn0.\nby apply/eq_bigr=> /= i _; rewrite /fun_of_multinom (tnth_nth 0%N).\nQed.\n\nDefinition symf1 (p : {mpoly R[n]}) : {mpoly R[n]} * {mpoly R[n]} :=\n  if p == 0 then (0, 0) else\n    let m := mlead p in\n    let c := nth 0%N m in\n    let F := fun i => (c i - c i.+1)%N in\n    (p@_m *: 'X_[F#val], p - p@_m *: ('X_[F#val] \\mPo S)).\n\nFixpoint symfn (k : nat) (p : {mpoly R[n]}) :=\n  if k is k'.+1 then\n    let (t1, p) := symf1 p in\n    let (t2, p) := symfn k' p in\n      (t1 + t2, p)\n  else symf1 p.\n\nLemma symf1E0 : symf1 0 = (0, 0).\nProof. by rewrite /symf1 eqxx. Qed.\n\nLemma symfnE0 k : symfn k 0 = (0, 0).\nProof. by elim: k => /= [|k ih]; rewrite symf1E0 //= ih addr0. Qed.\n\nLemma symf1P (p : {mpoly R[n]}) : p \\is symmetric ->\n  [&& ((symf1 p).2 == 0) || (mlead (symf1 p).2 < mlead p)%O\n    , (symf1 p).2 \\is symmetric\n    & p == (symf1 p).1 \\mPo S + (symf1 p).2].\nProof.\nrewrite /symf1; case: (eqVneq p 0) => [->|nz_p sym_p] /=.\n  by rewrite comp_mpoly0 addr0 eqxx andbT.\nrewrite addrCA comp_mpolyZ subrr addr0 eqxx andbT rpredB //; last first.\n  by apply/rpredZ/mcomp_sym => i; rewrite -tnth_nth tnth_map; apply/mesym_sym.\ncase: eqVneq; rewrite //= andbT.\nhave := mlead_XLS (mlead_msym_sorted sym_p).\nset c := nth 0%N (mlead p); pose F i := (c i - c i.+1)%N.\nrewrite -/(F#val) => mE.\nset q : {mpoly R[n]} := p@_(mlead p) *: (_ \\mPo _).\nrewrite lt_neqAle andbC /= => nz_pBq.\nhave := mleadB_le p q; rewrite mleadZ_proper; last first.\n  by rewrite mE mulrC mulrI_eq0 ?mleadc_eq0 // -mE mleadc_XS; apply/lreg1.\nrewrite mE joinxx => -> /=; apply/contraTneq: nz_pBq.\nrewrite -mleadc_eq0 => ->; rewrite /q mcoeffB mcoeffZ -{3}mE.\nby rewrite mleadc_XS mulr1 subrr eqxx.\nQed.\n\nLemma symfnP k (p : {mpoly R[n]}) : p \\is symmetric ->\n  [&& ((symfn k p).2 == 0) || (mlead (symfn k p).2 < mlead p)%O\n    , (symfn k p).2 \\is symmetric\n    & p == (symfn k p).1 \\mPo S + (symfn k p).2].\nProof.\nelim: k p=> [|k ih] p sym_p /=; first exact/symf1P.\nhave E T U (z : T * U) : z = (z.1, z.2) by case: z.\nrewrite [symf1 p]E [symfn _ _]E /= => {E}.\ncase/and3P: (symf1P sym_p); case/orP=> [/eqP-> _ /eqP pE|].\n  by rewrite symfnE0 /= eqxx rpred0 /= {1}pE !simpm.\nmove=> le_q1_p /ih /and3P[]; case/orP=> [/eqP-> _|].\n  move=> /eqP q1E /eqP pE; rewrite eqxx rpred0 /=.\n  by rewrite {1}pE {1}q1E !simpm raddfD.\nmove=> le_q2_q1 -> /eqP q1E /eqP pE.\nrewrite (lt_trans le_q2_q1) ?orbT //= {1}pE {1}q1E.\nby rewrite addrA raddfD.\nQed.\n\nLemma symfnS (p : {mpoly R[n]}) :\n  { n : nat | p \\is symmetric -> (symfn n p).2 = 0 }.\nProof.\nhave: p \\is symmetric -> { n : nat | (symfn n p).2 = 0 }.\n  elim/mleadrect: p => p ih sym_p; case/and3P: (symf1P sym_p).\n  case: ((symf1 p).2 =P 0)=> /= [z_q1|nz_q1]; first by exists 0%N.\n  move=> le_q1 /ih -/(_ le_q1) [k z_q2] /eqP pE.\n  exists k.+1=> /=; have E T U (z : T * U): z = (z.1, z.2) by case: z.\n  by rewrite [symf1 _]E [symfn _ _]E z_q2.\nby case: (p \\is symmetric)=> [[]// k eq|_]; [exists k | exists 0%N].\nQed.\n\nDefinition symf (p : {mpoly R[n]}) :=\n  nosimpl (symfn (tag (symfnS p)) p).1.\n\nLemma symfP (p : {mpoly R[n]}) : p \\is symmetric -> p = symf p \\mPo S.\nProof.\nmove=> sym_p; rewrite /symf; set k := tag _.\ncase/and3P: (symfnP k sym_p)=> /= _ _ /eqP {1}->.\nby rewrite {}/k; case: symfnS=> /= k -> //; rewrite !simpm.\nQed.\n\n(* -------------------------------------------------------------------- *)\nLemma symf1_wgle (p : {mpoly R[n]}) : p \\is symmetric ->\n  mweight (symf1 p).1 <= msize p.\nProof.\nmove=> sym_p; rewrite /symf1; case: (p =P 0).\n  by rewrite mmeasure0.\nmove=> /eqP nz_p; set X := 'X_[_] => /=.\nrewrite (@leq_trans (mweight X)) ?mmeasureZ_le //.\nrewrite -?mlead_deg ?mleadc_eq0 // mweight_XLS //.\nexact/mlead_msym_sorted.\nQed.\n\nLemma symfn_wgle k (p : {mpoly R[n]}) : p \\is symmetric ->\n  mweight (symfn k p).1 <= msize p.\nProof.\nelim: k p => [|k ih] p sym_p /=; first exact/symf1_wgle.\nhave E T U (z : T * U): z = (z.1, z.2) by case: z.\nrewrite [symf1 p]E [symfn _ _]E /= => {E}.\ncase/and3P: (symf1P sym_p); case/orP=> [/eqP-> _ /eqP pE|].\n  by rewrite symfnE0 /= addr0; apply/symf1_wgle.\nmove=> le_q1_p sym_q2 /eqP pE.\nrewrite (leq_trans (mmeasureD_le _ _ _)) //.\nrewrite geq_max symf1_wgle //= (leq_trans (ih _ _)) //.\nhave [->|nz_p] := eqVneq p 0; first by rewrite symf1E0 msize0.\nhave [->|nz_f1p] := eqVneq (symf1 p).2 0; first by rewrite msize0.\nby rewrite -!mlead_deg // ltnS lemc_mdeg // ltW.\nQed.\n\n(* -------------------------------------------------------------------- *)\nLemma sym_fundamental (p : {mpoly R[n]}) : p \\is symmetric ->\n  { t | t \\mPo S = p /\\ mweight t <= msize p}.\nProof. by exists (symf p); rewrite {2}[p]symfP ?symfn_wgle. Qed.\n\n(* -------------------------------------------------------------------- *)\nLocal Notation XS m := ('X_[R, m] \\mPo S) (only parsing).\n\nLemma msym_fundamental_un0 (t : {mpoly R[n]}) : t \\mPo S = 0 -> t = 0.\nProof.\nset S := S; move/eqP; apply/contraTeq=> nz_t; rewrite -mleadc_eq0.\nhave h m: m \\in msupp t -> mlead (t@_m *: (XS m)) = mlead (XS m).\n  move=> m_in_t; rewrite mleadZ_proper // mleadc_XS.\n  by rewrite mulr1 mcoeff_eq0 m_in_t.\nrewrite comp_mpolyEX mlead_sum ?filter_predT; last first.\n  rewrite (iffLR (eq_in_map _ _ _) h) -/S.\n  apply/(@uniqP _ 0%MM) => i j; rewrite size_map.\n  move=> lti ltj; rewrite !(nth_map 0%MM) // => /free_XS.\n  exact: (can_in_inj (nthK _ _)).\nrewrite big_seq (eq_bigr _ h) -big_seq.\ncase: (eq_bigjoin (fun m => mlead (XS m)) _ (r := msupp t)).\n  exact/le_total. by rewrite msupp_eq0.\nmove=> /= m m_in_t /eqP/esym; rewrite -/S=> lmm.\nrewrite -lmm raddf_sum /= (bigD1_seq m) //= mcoeffZ.\nrewrite mleadc_XS mulr1 big_seq_cond big1.\n  by rewrite addr0 mcoeff_eq0 m_in_t.\nmove=> /= m' /andP[m'_in_t ne_m'm]; rewrite mcoeffZ.\nrewrite [X in _*X]mcoeff_gt_mlead ?mulr0 //.\nrewrite lt_neqAle (contra_neq (@free_XS _ _)) //= lmm.\nexact: (joins_sup_seq (fun m => mlead (XS m))).\nQed.\n\nLemma msym_fundamental_un (t1 t2 : {mpoly R[n]}) :\n  t1 \\mPo S = t2 \\mPo S -> t1 = t2.\nProof.\nmove/eqP; rewrite -subr_eq0 -raddfB /= => /eqP.\nby move/msym_fundamental_un0/eqP; rewrite subr_eq0=> /eqP.\nQed.\n\nEnd MESymFundamental.\n\n(* -------------------------------------------------------------------- *)\nDefinition ishomog1 {n} {R : ringType}\n  (d : nat) (mf : measure n) : qualifier 0 {mpoly R[n]}\n  := [qualify p | all [pred m | mf m == d] (msupp p)].\n\n(* -------------------------------------------------------------------- *)\nModule MPolyHomog1Key.\n\nFact homog1_key {n} {R : ringType} d mf : pred_key (@ishomog1 n R d mf).\nProof. by []. Qed.\n\nDefinition homog1_keyed {n R} d mf := KeyedQualifier (@homog1_key n R d mf).\n\nEnd MPolyHomog1Key.\n\nCanonical MPolyHomog1Key.homog1_keyed.\n\n(* -------------------------------------------------------------------- *)\nDefinition ishomog {n} {R : ringType} mf : qualifier 0 {mpoly R[n]} :=\n  [qualify p | p \\is ishomog1 (@mmeasure _ _ mf p).-1 mf].\n\n(* -------------------------------------------------------------------- *)\nModule MPolyHomogKey.\n\nFact homog_key {n} {R : ringType} mf : pred_key (@ishomog n R mf).\nProof. by []. Qed.\n\nDefinition homog_keyed {n R} mf := KeyedQualifier (@homog_key n R mf).\n\nEnd MPolyHomogKey.\n\nCanonical MPolyHomogKey.homog_keyed.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyHomogTheory.\nContext (n : nat) (R : ringType) (mf : measure n).\nImplicit Types (p q : {mpoly R[n]}).\n\nLocal Notation \"d .-homog\" := (@ishomog1 _ _ d mf)\n  (at level 1, format \"d .-homog\") : form_scope.\n\nLocal Notation homog := (@ishomog _ _ mf).\n\nLocal Notation \"[ 'in' R [ n ] , d .-homog ]\" := (@ishomog1 n R d mf)\n  (at level 0, R, n at level 2, d at level 0,\n     format \"[ 'in'  R [ n ] ,  d .-homog ]\") : form_scope.\n\nLemma dhomogE d p: (p \\is d.-homog) = all [pred m | mf m == d] (msupp p).\nProof. by []. Qed.\n\nLemma dhomogP d p: reflect {in msupp p, forall m, mf m = d} (p \\is d.-homog).\nProof. by apply/(iffP allP)=> /= h m /h => [/eqP|->]. Qed.\n\nLemma dhomog_mf d p: p \\is d.-homog -> {in msupp p, forall m, mf m = d}.\nProof. by move/dhomogP. Qed.\n\nLemma dhomog_nemf_coeff d p m: p \\is d.-homog -> mf m != d -> p@_m = 0.\nProof.\n  move/dhomogP=> hg_p; apply/contraTeq; rewrite -mcoeff_msupp.\n  by move/hg_p=> ->; rewrite negbK.\nQed.\n\nLemma dhomog1 : (1 : {mpoly R[n]}) \\is 0.-homog.\nProof.\nby apply/dhomogP; rewrite msupp1=> m; rewrite inE=> /eqP ->; exact: mf0.\nQed.\n\nLemma dhomog_uniq p d e : p != 0 -> p \\is d.-homog -> p \\is e.-homog -> d = e.\nProof.\nby move=> nz_p /dhomogP /(_ _ (mlead_supp nz_p)) <- /dhomogP/(_ _ (mlead_supp nz_p)).\nQed.\n\nLemma dhomog_submod_closed d : submod_closed [in R[n], d.-homog].\nProof.\nsplit=> [|c p q]; first by rewrite dhomogE msupp0.\nmove=> /dhomogP hg_p /dhomogP hg_q; apply/dhomogP=> m.\nmove/msuppD_le; rewrite mem_cat; case/orP=> [/msuppZ_le|].\n  by move/hg_p. by move/hg_q.\nQed.\n\nCanonical dhomog_addPred    d := AddrPred   (dhomog_submod_closed d).\nCanonical dhomog_oppPred    d := OpprPred   (dhomog_submod_closed d).\nCanonical dhomog_zmodPred   d := ZmodPred   (dhomog_submod_closed d).\nCanonical dhomog_submodPred d := SubmodPred (dhomog_submod_closed d).\n\nLemma dhomog0 d: 0 \\is [in R[n], d.-homog].\nProof. exact/rpred0. Qed.\n\nLemma dhomogX d m: ('X_[m] \\is [in R[n], d.-homog]) = (mf m == d).\nProof. by rewrite dhomogE msuppX /= andbT. Qed.\n\nLemma dhomogD d: {in d.-homog &, forall p q, p + q \\is d.-homog}.\nProof. exact/rpredD. Qed.\n\nLemma dhomogN d: {mono -%R: p / p \\in [in R[n], d.-homog]}.\nProof. exact/rpredN. Qed.\n\nLemma dhomogZ d c p: p \\in d.-homog -> (c *: p) \\in d.-homog.\nProof. exact/rpredZ. Qed.\n\nLocal Notation mfsize p := (@mmeasure _ _ mf p).\n\nLemma homog_msize p : (p \\is homog) = (p \\is (mfsize p).-1.-homog).\nProof. by []. Qed.\n\nLemma dhomog_msize d p : p \\is d.-homog -> p \\is (mfsize p).-1.-homog.\nProof.\nrewrite mmeasureE => /dhomogP h; apply/dhomogP => m m_in_p.\nrewrite h // big_seq (eq_bigr (fun _ => d.+1)); last by move=> i /h ->.\nrewrite -big_seq (perm_big _ (perm_to_rem m_in_p)) big_cons /=.\nelim: (rem _ _)=> [|x s ih]; first by rewrite big_nil maxn0.\nby rewrite big_cons maxnA maxnn -ih.\nQed.\n\nLemma homogE d p : p \\is d.-homog -> p \\is homog.\nProof. by move/dhomog_msize. Qed.\n\nLemma homogP p : reflect (exists d, p \\is d.-homog) (p \\is homog).\nProof.\nby apply: (iffP idP)=> [h|[d /dhomog_msize]] //; exists (mfsize p).-1.\nQed.\n\nLemma dhomogM d p e q :\n  p \\is d.-homog -> q \\is e.-homog -> p * q \\is (d + e).-homog.\nProof.\nmove=> /dhomogP homp /dhomogP homq; apply/dhomogP=> m.\ncase/msuppM_le/allpairsP=> /= -[m1 m2] [/=].\nby move=> /homp <- /homq <- ->; apply/mfD.\nQed.\n\nLemma dhomogMn d p k : p \\is d.-homog -> p ^+ k \\is (d * k).-homog.\nProof.\nelim: k => [| k ihk] homp; first by rewrite muln0; apply/dhomog1.\nby rewrite exprS /= mulnS; apply/dhomogM/ihk.\nQed.\n\nLemma homog_prod (s : seq {mpoly R[n]}) :\n  all (fun p => p \\is homog) s -> \\prod_(p <- s) p \\is homog.\nProof.\nmove=> homs; apply/homogP; elim: s homs => [_ | p s ihs] /=.\n  by exists 0%N; rewrite big_nil; apply/dhomog1.\ncase/andP=> /homogP [dp p_hdp] {}/ihs [d ih].\nby exists (dp + d)%N; rewrite big_cons; apply/dhomogM.\nQed.\n\nLemma dhomog_prod {l} (dt : l.-tuple nat) (mt : l.-tuple {mpoly R[n]}) :\n     (forall i : 'I_l, tnth mt i \\is (tnth dt i).-homog)\n  -> \\prod_(i <- mt) i \\is (\\sum_(i <- dt) i).-homog.\nProof.\nelim: l dt mt => [| l ihl] dt mt hom.\n  by rewrite tuple0 big_nil tuple0 big_nil dhomog1.\ncase/tupleP: dt hom => d dt; case/tupleP: mt => p mt /= hom.\nrewrite !big_cons; apply/dhomogM.\n  by move: (hom ord0); rewrite (tnth_nth 0) (tnth_nth 0%N).\napply/ihl => i; have:= hom (inord i.+1).\nby rewrite !(tnth_nth 0) !(tnth_nth 0%N) !inordK ?ltnS.\nQed.\n\nEnd MPolyHomogTheory.\n\nNotation \"[ 'in' R [ n ] , d .-homog 'for' mf ]\" := (@ishomog1 n R d mf)\n  (at level 0, R, n at level 2, d at level 0,\n     format \"[ 'in'  R [ n ] , d .-homog  'for'  mf ]\") : form_scope.\n\nNotation \"[ 'in' R [ n ] , d .-homog ]\" :=\n  [in R[n], d.-homog for [measure of mdeg]]\n  (at level 0, R, n at level 2, d at level 0) : form_scope.\n\nNotation \"d .-homog 'for' mf\" := (@ishomog1 _ _ d mf)\n  (at level 1, format \"d .-homog  'for'  mf\") : form_scope.\n\nNotation \"d .-homog\" := (d .-homog for [measure of mdeg])\n  (at level 1, format \"d .-homog\") : form_scope.\n\nNotation \"'homog' mf\" := (@ishomog _ _ mf)\n  (at level 1, format \"'homog'  mf\") : form_scope.\n\n(* -------------------------------------------------------------------- *)\nSection HomogNVar0.\nContext (n : nat) (R : ringType).\n\nLemma nvar0_homog (mf : measure 0%N) (p : {mpoly R[0]}) :\n  p \\is 0.-homog for mf.\nProof. by apply/dhomogP; case=> t; rewrite tuple0 mfE big_ord0. Qed.\n\nLemma nvar0_homog_eq (mf : measure n) (p : {mpoly R[n]}) :\n  n = 0%N -> p \\is 0.-homog for mf.\nProof. by move=> z_n; move: mf p; rewrite z_n; apply/nvar0_homog. Qed.\n\nEnd HomogNVar0.\n\n(* -------------------------------------------------------------------- *)\nSection ProjHomog.\nContext (n : nat) (R : ringType) (mf : measure n).\nImplicit Types (p q r : {mpoly R[n]}) (m : 'X_{1..n}).\n\nLocal Notation mfsize p := (@mmeasure _ _ mf p).\n\nSection Def.\nVariable (d : nat).\n\nDefinition pihomog p : {mpoly R[n]} :=\n  \\sum_(m <- msupp p | mf m == d) p@_m *: 'X_[m].\n\nLemma pihomogE p : pihomog p =\n  \\sum_(m <- msupp p | mf m == d) p@_m *: 'X_[m].\nProof. by []. Qed.\n\nLemma pihomogwE k p : msize p <= k ->\n  pihomog p = \\sum_(m : 'X_{1..n < k} | mf m == d) p@_m *: 'X_[m].\nProof.\nmove=> lt_pk; pose I := [subFinType of 'X_{1..n < k}].\nrewrite pihomogE (big_mksub_cond I) //=; first last.\n+ by move=> x /msize_mdeg_lt /leq_trans /(_ lt_pk) ->.\n+ by rewrite msupp_uniq.\nrewrite -big_filter_cond big_rmcond ?big_filter //=.\nby move=> m /memN_msupp_eq0 ->; rewrite scale0r.\nQed.\n\nLemma pihomogX m : pihomog 'X_[m] = if mf m == d then 'X_[m] else 0.\nProof.\nby rewrite pihomogE msuppX big_mkcond /= big_seq1 mcoeffX eqxx scale1r.\nQed.\n\nLemma pihomog_is_linear : linear pihomog.\nProof.\nmove=> c p q /=; pose_big_enough l.\n  rewrite (pihomogwE _ (k := l)) //.\n  rewrite (pihomogwE _ (k := l) (p := p)) //.\n  rewrite (pihomogwE _ (k := l) (p := q)) //.\n  rewrite scaler_sumr -big_split /=; apply: eq_bigr => m _.\n  by rewrite linearP /= scalerDl scalerA.\nby close.\nQed.\n\nCanonical pihomog_additive : {additive {mpoly R[n]} -> {mpoly R[n]}} :=\n  Additive pihomog_is_linear.\nCanonical pihomog_linear := Linear pihomog_is_linear.\n\nLemma pihomog0     : pihomog 0 = 0               . Proof. exact: raddf0. Qed.\nLemma pihomogN     : {morph pihomog: x / - x}    . Proof. exact: raddfN. Qed.\nLemma pihomogD     : {morph pihomog: x y / x + y}. Proof. exact: raddfD. Qed.\nLemma pihomogB     : {morph pihomog: x y / x - y}. Proof. exact: raddfB. Qed.\nLemma pihomogMn  k : {morph pihomog: x / x *+ k} . Proof. exact: raddfMn. Qed.\nLemma pihomogMNn k : {morph pihomog: x / x *- k} . Proof. exact: raddfMNn. Qed.\n\nLemma pihomog_dE p : p \\is d.-homog for mf -> pihomog p = p.\nProof.\nmove/dhomogP => hom_p; rewrite pihomogE big_seq_cond.\nrewrite (eq_bigl [pred m | m \\in msupp p]); last first.\n  by move=> m /=; rewrite andb_idr // => /hom_p ->.\nby rewrite -big_seq -mpolyE.\nQed.\n\nLemma pihomogP p : pihomog p \\is d.-homog for mf.\nProof.\napply/rpred_sum=> m /eqP eqd_mfm; apply/rpredZ.\nby apply/dhomogP => m0 /mem_msuppXP <-.\nQed.\n\nLemma pihomog_id p : pihomog (pihomog p) = pihomog p.\nProof. by rewrite pihomog_dE; last exact: pihomogP. Qed.\n\nLemma homog_piE p : p \\is d.-homog for mf = (pihomog p == p).\nProof.\napply: (sameP idP); apply: (iffP idP); last by move /pihomog_dE ->.\nby move=> /eqP <-; apply/pihomogP.\nQed.\n\nEnd Def.\n\nLemma pihomog_ne0 d b p : d != b ->\n  p \\is d.-homog for mf -> pihomog b p = 0.\nProof.\nmove=> ne /dhomogP hom; rewrite pihomogE big_seq_cond.\nby apply/big_pred0 => m; apply/contraNF: ne=> /andP[/hom->].\nQed.\n\nLemma pihomog_partitionE k p :\n  mfsize p <= k -> p = \\sum_(d < k) pihomog d p.\nProof.\nmove=> h; rewrite (exchange_big_dep predT) //= {1}[p]mpolyE.\napply/eq_bigr => m _; rewrite -scaler_sumr.\ncase: (ssrnat.leqP k (mf m)) => [|lt_mk].\n  move/(leq_trans h)/mmeasure_mnm_ge/memN_msupp_eq0.\n  by move=> ->; by rewrite !scale0r.\nrewrite (eq_bigl (fun i : 'I_k => i == Ordinal lt_mk)).\n  by rewrite big_pred1_eq. by move=> i /=; rewrite eq_sym.\nQed.\n\nEnd ProjHomog.\n\n(* -------------------------------------------------------------------- *)\nSection MPolyHomogType.\nContext (n : nat) (R : ringType) (d : nat).\n\nRecord dhomog :=\n  DHomog { mpoly_of_dhomog :> {mpoly R[n]}; _ : mpoly_of_dhomog \\is d.-homog }.\n\nCanonical  dhomog_subType := Eval hnf in [subType for @mpoly_of_dhomog].\nDefinition dhomog_eqMixin := Eval hnf in [eqMixin of dhomog by <:].\nCanonical  dhomog_eqType  := Eval hnf in EqType dhomog dhomog_eqMixin.\n\nDefinition dhomog_choiceMixin := [choiceMixin of dhomog by <:].\nCanonical  dhomog_choiceType  := Eval hnf in ChoiceType dhomog dhomog_choiceMixin.\n\nDefinition dhomog_zmodMixin := [zmodMixin of dhomog by <:].\nCanonical  dhomog_zmodType  := Eval hnf in ZmodType dhomog dhomog_zmodMixin.\n\nDefinition dhomog_lmodMixin := [lmodMixin of dhomog by <:].\nCanonical  dhomog_lmodType  := Eval hnf in LmodType R dhomog dhomog_lmodMixin.\n\nLemma mpoly_of_dhomog_is_linear: linear mpoly_of_dhomog.\nProof. by []. Qed.\n\nCanonical mpoly_of_dhomog_additive := Additive mpoly_of_dhomog_is_linear.\nCanonical mpoly_of_dhomog_linear   := Linear   mpoly_of_dhomog_is_linear.\n\nEnd MPolyHomogType.\n\nLemma dhomog_is_dhomog n (R : ringType) d (p : dhomog n R d) :\n  (val p) \\is [in R[n], d.-homog for [measure of mdeg]].\nProof. by case: p. Qed.\n\n#[global] Hint Extern 0 (is_true (_ \\is _.-homog mf)) =>\n  (by apply/dhomog_is_dhomog) : core.\n\nDefinition indhomog n (R : ringType) d : {mpoly R[n]} -> dhomog n R d :=\n  fun p => insubd (0 : dhomog n R d) p.\n\nNotation \"[ ''dhomog_' d p ]\" := (@indhomog _ _ d p)\n  (at level 8, d, p at level 2, format \"[ ''dhomog_' d p ]\").\n\n(* -------------------------------------------------------------------- *)\nSection MPolyHomogVec.\nLocal Notation isorted s := (sorted leq [seq val i | i <- s]).\n\nDefinition basis n d : {set (d.-tuple 'I_n)} :=\n  [set t in {: d.-tuple 'I_n } | isorted t].\n\nDefinition s2m n (m : seq 'I_n) :=\n  [multinom count_mem i m | i < n].\n\nDefinition m2s n (m : 'X_{1..n}) :=\n  flatten [seq nseq (m i) i | i <- enum 'I_n].\n\nLemma inj_s2m n d: {in basis n d &, injective (@s2m n \\o val)}.\nProof.\nmove=> t1 t2; rewrite !inE=> srt_t1 srt_t2 eq_tm.\napply/val_inj/(inj_map val_inj).\napply/(sorted_eq leq_trans anti_leq srt_t1 srt_t2).\napply/perm_map/allP=> /= i _; move/mnmP/(_ i): eq_tm.\nby rewrite !mnmE => ->.\nQed.\n\nLemma srt_m2s n (m : 'X_{1..n}): isorted (m2s m).\nProof.\nhave h (T : eqType) (leT : rel T) (s : seq T) (F : T -> nat) x:\n  reflexive leT -> transitive leT ->\n     path leT x s\n  -> path leT x (flatten [seq nseq (F x) x | x <- s]).\n* move=> leTxx leT_tr; elim: s x => //= y s ih x /andP[le_xy pt_ys].\n  case: (F y)=> /= [|k]; first apply/ih.\n    rewrite path_min_sorted; do ?apply: (introT allP).\n      exact/(path_sorted (x := y)).\n    move=> z z_in_s /=; apply/(leT_tr y)=> //.\n    by move/order_path_min: pt_ys => /(_ leT_tr) /allP /(_ _ z_in_s).\n  rewrite le_xy /= cat_path; apply/andP; split.\n    by elim: k=> //= k ->; rewrite leTxx.\n  by have ->: last y (nseq k y) = y; [elim: k | apply/ih].\ncase: n m=> [|n] m.\n  case: m => t /=; rewrite /m2s; have ->//: enum 'I_0 = [::].\n  by apply/size0nil; rewrite size_enum_ord.\napply/(path_sorted (x := val (0 : 'I_n.+1))).\npose P := [rel i j : 'I_n.+1 | i <= j].\nrewrite (map_path (e' := P) (b := xpred0)) //=; last first.\n  by apply/hasP; case.\napply/h; try solve [exact/leqnn | exact/leq_trans].\nrewrite -(map_path (h := val) (e := leq) (b := xpred0)) //.\n  rewrite val_enum_ord /= path_min_sorted ?iota_sorted//;\n  do ?exact: (introT allP).\nby apply/hasP; case.\nQed.\n\nLemma size_m2s n (m : 'X_{1..n}): size (m2s m) = mdeg m.\nProof.\nrewrite /m2s size_flatten /shape -map_comp /=.\nrewrite (eq_map (_ : _ =1 m)); first by rewrite mdegE sumnE !big_map.\nby move=> i /=; rewrite size_nseq.\nQed.\n\nLemma s2mK n (m : 'X_{1..n}): s2m (m2s m) = m.\nProof.\napply/mnmP=> i; rewrite mnmE /m2s /=.\nrewrite count_flatten sumnE !big_map (bigD1 i) //=.\nrewrite -sum1_count /= big_nseq_cond eqxx iter_succn.\nrewrite add0n big1 ?addn0 // => j ne_ji; apply/count_memPn.\nby apply/negP=> /nseqP [/esym/eqP]; rewrite (negbTE ne_ji).\nQed.\n\nLocal Notation sbasis n d :=\n  [seq s2m t | t : d.-tuple 'I_n <- enum (basis n d)].\n\nLemma basis_cover n d (m : 'X_{1..n}): (mdeg m == d) = (m \\in sbasis n d).\nProof.\napply/eqP/idP=> [eq_szm_d|].\n  apply/mapP; have /eqP := size_m2s m; rewrite -eq_szm_d => sz_tm.\n  exists (Tuple sz_tm); first by rewrite mem_enum inE /= srt_m2s.\n  by rewrite s2mK.\ncase/mapP=> /= t _ ->; pose F i := count_mem i t.\n  rewrite mdegE (eq_bigr F) {}/F; last first.\n  by move=> /= i _; rewrite mnmE.\ntransitivity (\\sum_i \\sum_(j <- t | j == i) 1)%N.\n  by apply: eq_bigr => i _; rewrite -big_filter sum1_size size_filter.\nrewrite (exchange_big_dep predT)//=.\ntransitivity (\\sum_(j <- t) 1)%N; last by rewrite sum1_size size_tuple.\nby apply: eq_bigr => i _; rewrite (eq_bigl _ _ (eq_sym _)) big_pred1_eq.\nQed.\n\nLemma size_basis n d: size (sbasis n.+1 d) = 'C(d + n, d).\nProof. by rewrite size_map -cardE; apply/card_sorted_tuples. Qed.\n\nLemma uniq_basis n d: uniq (sbasis n d).\nProof.\nrewrite map_inj_in_uniq ?enum_uniq // => t1 t2.\nby rewrite !mem_enum; apply/inj_s2m.\nQed.\n\n(* -------------------------------------------------------------------- *)\nContext (n : nat) (R : ringType) (d : nat).\n\nLemma dhomog_vecaxiom: Vector.axiom 'C(d + n, d) (dhomog n.+1 R d).\nProof.\npose b := sbasis n.+1 d.\npose t := [tuple of nseq d (0 : 'I_n.+1)].\npose M := fun i => nth 0%MM b i.\npose f (p : dhomog n.+1 R d) :=\n  \\row_(i < 'C(d + n, d)) p@_(nth 0%MM b i).\nexists f => /= [c p q|].\n  by apply/matrixP=> i j; rewrite !mxE /= mcoeffD mcoeffZ.\npose g (r : 'rV[R]_('C(d + n, d))) : {mpoly R[_]} :=\n  \\sum_(i < 'C(d + n, d)) (r 0 i) *: 'X_[M i].\nhave dhg r: g r \\is d.-homog.\n  rewrite rpred_sum //= => i _; apply/rpredZ.\n  rewrite dhomogX basis_cover /M (nth_map t); last first.\n    by rewrite -cardE card_sorted_tuples.\n  by apply/map_f/mem_nth; rewrite -cardE card_sorted_tuples.\nexists (fun r => DHomog (dhg r)); last first.\n  move=> r; rewrite /g /f /=; apply/matrixP=> i j.\n  rewrite mxE ord1 raddf_sum /= -/(M _) (bigD1 j) //=.\n  rewrite mcoeffZ mcoeffX eqxx mulr1 big1 ?addr0 //.\n  move=> k ne_kj; rewrite mcoeffZ mcoeffX /M.\n  rewrite nth_uniq ?size_basis ?uniq_basis //.\n  by rewrite (inj_eq (val_inj)) (negbTE ne_kj) mulr0.\nmove=> p; apply/val_inj/mpolyP=> m /=; rewrite /g /f.\npose P := fun (p : {mpoly R[n.+1]}) m => p@_m *: 'X_[m].\nrewrite (eq_bigr (P p \\o M \\o val)) /P /=; last first.\n  by move=> /= i _; rewrite mxE.\nrewrite -(big_map (M \\o val) xpredT (P p)) {}/P /M /=.\nrewrite /index_enum -enumT /= map_comp val_enum_ord.\nset r := map _ _; have {r}->: r = b; rewrite ?raddf_sum /=.\n  apply/(@eq_from_nth _ 0%MM).\n    by rewrite size_map size_iota size_basis.\n  rewrite size_map size_iota=> i lt_i_C.\n  by rewrite (nth_map 0%N) ?size_iota // nth_iota.\ncase: (mdeg m =P d)=> /eqP; rewrite basis_cover -/b.\n  move=> m_in_b; rewrite (bigD1_seq m) ?uniq_basis //=.\n  rewrite mcoeffZ mcoeffX eqxx mulr1 big1 ?addr0 // => m' ne.\n  by rewrite mcoeffZ mcoeffX (negbTE ne) mulr0.\nmove=> m_notin_b; rewrite big_seq big1 /=.\n  apply/esym/(@dhomog_nemf_coeff _ _ [measure of mdeg] d).\n    exact/dhomog_is_dhomog. by rewrite basis_cover.\nmove=> m'; apply/contraTeq; rewrite mcoeffZ mcoeffX.\nby case: (m' =P m)=> [->|_]; last rewrite mulr0 eqxx.\nQed.\n\nDefinition dhomog_vectMixin := VectMixin dhomog_vecaxiom.\n\nCanonical dhomog_vectType :=\n  Eval hnf in VectType R (dhomog n.+1 R d) dhomog_vectMixin.\n\nEnd MPolyHomogVec.\n\n(* -------------------------------------------------------------------- *)\nSection MSymHomog.\nContext (n : nat) (R : comRingType).\nImplicit Types (p q r : {mpoly R[n]}).\n\nLemma msym_pihomog d p (s : 'S_n) :\n  msym s (pihomog [measure of mdeg] d p) =\n    pihomog [measure of mdeg] d (msym s p).\nProof.\nrewrite (mpolyE p) ![_ (\\sum_(m <- msupp p) _)]linear_sum /=.\nrewrite [msym s _]linear_sum linear_sum /=.\napply: eq_bigr => m _; rewrite !linearZ /=; congr (_ *: _).\nrewrite msymX !pihomogX /=.\nhave -> : mdeg [multinom m ((s^-1)%g i) | i < n] = mdeg m.\n  by apply/perm_big/tuple_permP; exists (s^-1)%g.\nby case: (mdeg m == d); rewrite ?msym0 ?msymX.\nQed.\n\nLemma pihomog_sym d p :\n  p \\is symmetric -> pihomog [measure of mdeg] d p \\is symmetric.\nProof. by move=> /issymP Hp; apply/issymP => s; rewrite msym_pihomog Hp. Qed.\n\nEnd MSymHomog.\n\n(* -------------------------------------------------------------------- *)\nSection MESymFundamentalHomog.\nContext (n : nat) (R : comRingType).\n\nLocal Notation S := [tuple mesym n R i.+1  | i < n].\n\nLemma dhomog_mesym d : mesym n R d \\is d.-homog.\nProof.\napply/dhomogP => m; rewrite msupp_mesymP => /existsP [/= s].\nby case/andP=> /eqP<- {d} /eqP -> {m}; exact/mdeg_mesym1.\nQed.\n\nLemma dhomog_XS (m : 'X_{1..n}) : 'X_[m] \\mPo S \\is (mnmwgt m).-homog.\nProof.\npose dt := [tuple (i.+1 * m i)%N | i < n].\npose mt := [tuple (mesym n R i.+1) ^+ m i | i < n].\nrewrite [X in X \\is _](_ : _ = \\prod_(i <- mt) i); last first.\n  rewrite comp_mpolyX (eq_bigr (tnth mt)) ?big_tuple //.\n  by move=> i _ /=; rewrite !tnth_mktuple.\nrewrite [X in X.-homog](_ : _ = (\\sum_(i <- dt) i)%N); last first.\n  rewrite /mnmwgt big_tuple (eq_bigr (tnth dt)) //.\n  by move=> i _ /=; rewrite !tnth_mktuple mulnC.\napply/dhomog_prod => i; rewrite !tnth_mktuple => {mt dt}.\nexact/dhomogMn/dhomog_mesym.\nQed.\n\nLemma pihomog_mPo p d :\n    pihomog [measure of mdeg] d (p \\mPo S)\n = (pihomog [measure of mnmwgt] d p) \\mPo S.\nProof.\nelim/mpolyind: p; first by rewrite !linear0.\nmove=> c m p msupp cn0 ihp; rewrite !linearP /= {}ihp.\ncongr (c *: _ + _); case: (eqVneq (mnmwgt m) d) => wgtm.\n+ have /eqP := wgtm; rewrite -(dhomogX R) => /pihomog_dE ->.\n  by have := dhomog_XS m; rewrite wgtm => /pihomog_dE ->.\nrewrite (pihomog_ne0 wgtm (dhomog_XS m)).\nby rewrite (pihomog_ne0 wgtm) ?linear0 // dhomogX.\nQed.\n\nLemma mwmwgt_homogE (p : {mpoly R[n]}) d :\n  (p \\is d.-homog for [measure of mnmwgt]) = (p \\mPo S \\is d.-homog).\nProof.\nby rewrite !homog_piE pihomog_mPo; apply/eqP/eqP=> [->|/msym_fundamental_un ->].\nQed.\n\nLemma sym_fundamental_homog (p : {mpoly R[n]}) (d : nat) :\n  p \\is symmetric -> p \\is d.-homog ->\n  { t | t \\mPo S = p /\\ t \\is d.-homog for [measure of mnmwgt] }.\nProof.\nmove/sym_fundamental => [t [tSp _]] homp.\nexists (pihomog [measure of mnmwgt] d t); split.\n+ by rewrite -pihomog_mPo tSp pihomog_dE.\n+ exact: pihomogP.\nQed.\n\nEnd MESymFundamentalHomog.\n", "meta": {"author": "math-comp", "repo": "multinomials", "sha": "fc3a21d5aeddcc494e59f606260b240c0d61da34", "save_path": "github-repos/coq/math-comp-multinomials", "path": "github-repos/coq/math-comp-multinomials/multinomials-fc3a21d5aeddcc494e59f606260b240c0d61da34/src/mpoly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.673946786410162}}
{"text": "(** * G2: Zippery, czyli łażenie po drzewach [TODO] *)\n\nFrom Typonomikon Require Import D5.\n\n(** * Predykaty na listach i drzewach - przypomnienie (TODO) *)\n\n(** * Indeksowanie drzew (TODO) *)\n\n(** Pamiętasz zapewne funkcję [nth] z rozdziału o listach, której\n    celem było znalezienie [n]-tego elementu na liście [l]. Jeżeli\n    twoja implementacja była poprawna i elegancka, to wyglądała\n    zapewne jakoś tak: *)\n\nPrint nth.\n(* ===> nth =\n        fix nth (A : Type) (n : nat) (l : list A) {struct l} :\n        option A :=\n          match l with\n          | [] => None\n          | h :: t =>\n            match n with\n            | 0 => Some h\n            | S n' => nth A n' t\n            end\n          end\n             : forall A : Type, nat -> list A -> option A *)\n\n(** Obraz wyłaniający się z tej definicji jest prosty:\n    - w pustej liście nic nie znajdziemy\n    - jeżeli lista jest niepusta, to przemierzamy ją, zerkając co i rusz\n      na indeks [n]. [0] oznacza \"już\", zaś [S _] oznacza \"jeszcze krok\"\n\n    Ma to sens, czyż nie? Zastanówmy się więc teraz, jak można\n    indeksować inne struktury danych, takie jak wektory czy drzewa (co\n    w zasadzie wyczerpuje pytanie, bo elementy każdego typu induktywnego\n    to nic innego jak drzewa). *)\n\nDefinition nat' : Type := list unit.\n\n(** Pierwsza rzecz, którą musimy zauważyć, to to, że liczby naturalne i\n    listy [unit]ów to w zasadzie to samo. No bo pomyśl:\n    - jest [0] i jest [nil]\n    - jest [S 0] i jest [tt :: nil]\n    - jest [S (S 0)] i jest [tt :: tt :: nil]\n    - etc. *)\n\n(** **** Ćwiczenie *)\n\n(** Pokaż, że typy [nat] i [list unit] są izomorficzne. *)\n\n(* begin hide *)\n(* TODO *)\n(* end hide *)\n\n(** Podsumowując: listy indeksujemy liczbami naturalnymi, które są tym\n    samym co listy [unit]ów. Przypadek? Nie sądzę. Można tę konstatację\n    sparafrazować tak: [list A] indeksujemy za pomocą [list unit].\n\n    Jest w tym sporo mądrości: [list A] to podłużny byt wypełniony\n    elementami typu [A], zaś [list unit] to po prostu podłużny byt -\n    jego zawartość jest nieistotna.\n\n    ACHTUNG: to wszystko kłamstwa, sprawa jest skomplikowańsza niż\n    myślałem. *)\n\nModule BT.\n\n(* 1 + A * X^2 *)\nInductive BT (A : Type) : Type :=\n| E : BT A\n| N : A -> BT A -> BT A -> BT A.\n\nArguments E {A}.\nArguments N {A} _ _ _.\n\n(** Tutaj typ indeksów jest oczywisty: możemy iść do lewego albo prawego poddrzewa,\n    co odpowiada konstruktorom [L] i [R], albo oznajmić, że już dotarliśmy do celu,\n    co odpowiada konstruktorowi [here]. *)\n\n(* 1 + 2 * X *)\nInductive IndexBT : Type :=\n| here : IndexBT\n| L : IndexBT -> IndexBT\n| R : IndexBT -> IndexBT.\n\n(** Najważniejszą operacją, jaką możemy wykonać mając typ indeksów, jest pójście\n    do poddrzewa odpowiadającego temu indeksowi. *)\n\nFixpoint subtree {A : Type} (i : IndexBT) (t : BT A) : option (BT A) :=\nmatch i, t with\n| here, _ => Some t\n| L _, E => None\n| L i', N _ l _ => subtree i' l\n| R _, E => None\n| R i', N _ _ r => subtree i' r\nend.\n\n(** Znalezienie elementu trzymanego w korzeniu danego poddrzewa jest jedynie\n    operacją pochodną. *)\n\nDefinition index {A : Type} (i : IndexBT) (t : BT A) : option A :=\nmatch subtree i t with\n| Some (N v _ _) => Some v\n| _              => None\nend.\n\n(** Choć można oczywiście posłużyć się osobną implementacją, która jest równoważna\n    powyższej. *)\n\nFixpoint index' {A : Type} (t : BT A) (i : IndexBT) {struct i} : option A :=\nmatch t, i with\n| E, _          => None\n| N v _ _, here => Some v\n| N _ l _, L i' => index' l i'\n| N _ _ r, R i' => index' r i'\nend.\n\nLemma index_index' :\n  forall {A : Type} (i : IndexBT) (t : BT A),\n    index i t = index' t i.\nProof.\n  induction i; destruct t; cbn; intros.\n    all: try reflexivity.\n    apply IHi.\n    apply IHi.\nQed.\n\nEnd BT.\n\nModule T.\n\n(** Dla drzew z dowolnym rozgałęzieniem jest podobnie jak dla drzew binarnych. *)\n\n(* 1 + A * X^I *)\nInductive T (I A : Type) : Type :=\n| E : T I A\n| N : A -> (I -> T I A) -> T I A.\n\nArguments E {I A}.\nArguments N {I A} _ _.\n\n(** Indeksy: albo już doszliśmy ([here]), albo idziemy dalej ([there]). *)\n\n(* 1 + I * X *)\nInductive Index (I : Type) : Type :=\n| here : Index I\n| there : I -> Index I -> Index I.\n\nArguments here {I}.\nArguments there {I} _ _.\n\nFixpoint subtree {I A : Type} (i : Index I) (t : T I A) : option (T I A) :=\nmatch i, t with\n| here      , _ => Some t\n| there _ _ , E => None\n| there j i', N _ f => subtree i' (f j)\nend.\n\nDefinition index {I A : Type} (i : Index I) (t : T I A) : option A :=\nmatch subtree i t with\n| Some (N v _) => Some v\n| _            => None\nend.\n\n(*\nFixpoint index {I A : Type} (t : T I A) (i : Index I) : option A :=\nmatch t, i with\n| E, _ => None\n| N v _, here => Some v\n| N _ f, there j i' => index (f j) i'\nend.\n*)\nEnd T.\n\nModule T2.\n\n(** A teraz coś trudniejszego: są dwa konstruktory rekurencyjne o różnej\n    liczbie argumentów. *)\n\n(* 1 + A * X + B * X^2 *)\nInductive T (A B : Type) : Type :=\n| E : T A B\n| NA : A -> T A B -> T A B\n| NB : B -> T A B -> T A B -> T A B.\n\nArguments E  {A B}.\nArguments NA {A B} _ _.\nArguments NB {A B} _ _ _.\n\n(** Jedyny sensowny pomysł na typ indeksów jest taki, że odróżniamy\n    [NA] od [NB] - jeżeli chcemy wejść do złego konstruktora, to się\n    nam po prostu nie udaje. *)\n\nInductive Index : Type :=\n| here : Index\n| therea : Index -> Index\n| thereb : bool -> Index -> Index.\n\n(** Jak widać działa, ale co to za działanie. *)\n\nFixpoint subtree {A B : Type} (i : Index) (t : T A B) : option (T A B) :=\nmatch i, t with\n| here           , _           => Some t\n| therea       i', (NA _ t')   => subtree i' t'\n| thereb false i', (NB _ t' _) => subtree i' t'\n| thereb true  i', (NB _ _ t') => subtree i' t'\n| _              , _           => None\nend.\n\n(** [index] też działa, ale typ zwracany robi się skomplikowańszy. *)\n\nDefinition index\n  {A B : Type} (i : Index) (t : T A B) : option (A + B) :=\nmatch subtree i t with\n| Some (NA a _)   => Some (inl a)\n| Some (NB b _ _) => Some (inr b)\n| _               => None\nend.\n\nEnd T2.\n\nModule T3.\n\n(** A teraz inny tłist: co jeżeli jest więcej [nil]i? *)\n\nSet Implicit Arguments.\nSet Maximal Implicit Insertion.\nSet Reversible Pattern Implicit.\n\n(* 1 + 1 + A * X * X *)\nInductive T (A : Type) : Type :=\n| EL | ER\n| N (a : A) (l : T A) (r : T A).\n\nArguments EL {A}.\nArguments ER {A}.\n\n(** Typ indeksów jest łatwy. *)\n\nInductive Index : Type :=\n| here : Index\n| there : bool -> Index -> Index.\n\nFixpoint subtree {A : Type} (i : Index) (t : T A) : option (T A) :=\nmatch i, t with\n| here      , _         => Some t\n| there b i', (N _ l r) => if b then subtree i' l else subtree i' r\n| _         , _         => None\nend.\n\nInductive Arg (A : Type) : Type :=\n| BadIndex\n| EmptyLeft\n| EmptyRight\n| Node (a : A).\n\nArguments BadIndex   {A}.\nArguments EmptyLeft  {A}.\nArguments EmptyRight {A}.\n\nDefinition index {A : Type} (i : Index) (t : T A) : Arg A :=\nmatch subtree i t with\n| None           => BadIndex\n| Some EL        => EmptyLeft\n| Some ER        => EmptyRight\n| Some (N a _ _) => Node a\nend.\n\nEnd T3.\n\n(** Przemyślenia: indeksowanie jest dużo bardziej związane z zipperami,\n    niż mi się wydawało. Zipper pozwala sfokusować się na jakimś miejscu\n    w strukturze i musimy pamiętać, jak do tego miejsca doszliśmy, tj.\n    co pominęliśmy po drodze.\n\n    Jeżeli zależy nam wyłącznie na tym, aby pokazać palcem na dane\n    miejsce w strukturze, to nie musimy pamiętać, co pominęliśmy.\n    Podsumowując: intuicja dotycząca typów indeksów oraz zipperów\n    jest dość jasna, ale związki z różniczkowaniem są mocno pokrętne.\n\n    Kwestią jest też jak przenieść te intuicje na indeksowane rodziny.\n    Na pewno indeksami [Vec n] jest [Fin n], a skądinąd [Vec n] to\n    [{n : nat & {l : list A | length l = n}}], zaś [Fin n] to [nat],\n    tylko trochę ograniczone.\n\n    Zapewne działa to bardzo dobrze... taki huj, jednak nie. *)\n\nFrom Typonomikon Require Vec.\n\nModule Vec'.\n\nSet Warnings \"-notation-overridden\".\nImport Vec.\nSet Warnings \"notation-overridden\".\n\n(** A teraz to samo dla rodzin indeksowanych. *)\n\nPrint vec.\n(* ===> Inductive vec (A : Type) : nat -> Type :=\n        | vnil : vec A 0\n        | vcons : forall n : nat, A -> vec A n -> vec A (S n)\n*)\n\nInductive Fin : nat -> Type :=\n| FZ : forall n : nat, Fin (S n)\n| FS : forall n : nat, Fin n -> Fin (S n).\n\nArguments FZ {n}.\nArguments FS {n} _.\n\nFixpoint index {A : Type} {n : nat} (i : Fin n) (v : vec A n) : A.\nProof.\n  destruct i as [| n i'].\n    inversion v. exact X.\n    inversion v. exact (index _ _ i' X0).\nDefined.\n\nEnd Vec'.\n\nModule hTree.\n\nInductive T (A : Type) : nat -> Type :=\n| E : T A 0\n| N : forall {n m : nat},\n        A -> T A n -> T A m -> T A (S (max n m)).\n\n(** To jednak działa inaczej niż myślałem. *)\n\nEnd hTree.\n\nFrom Typonomikon Require G1.\n\nModule W.\n\nImport G1.\n\nInductive IW {A : Type} (B : A -> Type) : Type :=\n| here  : IW B\n| there : forall x : A, B x -> IW B -> IW B.\n\nArguments here {A B}.\nArguments there {A B x} _.\n\nDefinition A (X : Type) : Type := unit + X.\n\nDefinition B {X : Type} (a : A X) : Type :=\nmatch a with\n| inl _ => False\n| inr _ => unit\nend.\n\nFixpoint nat_IW {X : Type} (n : nat) : (@IW (A X) (@B X)).\nProof.\n  destruct n as [| n'].\n    exact here.\n    eapply there. Unshelve.\nAbort.\n\nEnd W.\n\n(** * Zippery dla list - chodzenie po linie (TODO) *)\n\n(** * Szukanie dziury w typie, czyli różniczkowanie (TODO) *)\n\n(** * Zippery dla typów induktywnych (TODO) *)\n\n(** * Zippery dla typów koinduktywnych (TODO) *)", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/book/G2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.6739467837395516}}
{"text": "Require Import Coq.Arith.Arith.\nRequire Import SfLib.\nRequire Import Imp.\nRequire Import Smallstep.\n\nHint Constructors multi.\n\nInductive tm : Type :=\n  | ttrue   : tm\n  | tfalse  : tm\n  | tif     : tm  -> tm  -> tm  -> tm\n  | tzero   : tm\n  | tsucc   : tm  -> tm\n  | tpred   : tm  -> tm\n  | tiszero : tm  -> tm.\n\nInductive bvalue : tm -> Prop :=\n  | bv_true  : bvalue ttrue\n  | bv_false : bvalue tfalse.\n\nInductive nvalue : tm -> Prop :=\n  | nv_zero  : nvalue tzero\n  | nv_succ  : forall t, nvalue t -> nvalue (tsucc t).\n\nDefinition value t := bvalue t \\/ nvalue t.\n\nHint Constructors bvalue nvalue.\nHint Unfold update.\nHint Unfold value.\n\nFixpoint nat_to_tm (n : nat) : tm :=\n  match n with\n    | 0   => tzero\n    | S n => tsucc (nat_to_tm n)\n  end.\n\nFixpoint bool_to_tm (b : bool) : tm :=\n  if b then ttrue else tfalse.\n\nReserved Notation \"t1 '==>' t2\" (at level 40).\n\nInductive step : tm -> tm -> Prop :=\n  | ST_IfTrue  : forall t1 t2,\n      tif ttrue  t1 t2 ==> t1\n  | ST_IfFalse : forall t1 t2,\n      tif tfalse t1 t2 ==> t2\n  | ST_If      : forall t t' t1 t2,\n      t ==> t' ->\n      tif t t1 t2 ==> tif t' t1 t2\n  | ST_Succ    : forall t1 t2,\n      t1 ==> t2 ->\n      tsucc t1 ==> tsucc t2\n  | ST_PredZero :\n      tpred tzero ==> tzero\n  | ST_PredSucc : forall t,\n      nvalue t ->\n      tpred (tsucc t) ==> t\n  | ST_Pred    : forall t1 t2,\n      t1 ==> t2 ->\n      tpred t1 ==> tpred t2\n  | ST_IszeroZero :\n      tiszero tzero ==> ttrue\n  | ST_IszeroSucc : forall t,\n      nvalue t ->\n      tiszero (tsucc t) ==> tfalse\n  | ST_Iszero : forall t1 t2,\n      t1 ==> t2 ->\n      tiszero t1 ==> tiszero t2\n  where \"t1 '==>' t2\" := (step t1 t2).\n\nHint Constructors step.\n\nNotation step_normal_form := (normal_form step).\n\nDefinition stuck (t : tm) : Prop :=\n  step_normal_form t /\\ ~ value t.\n\nHint Unfold stuck.\n\n(* Exercise: 2 stars (some_term_is_stuck) *)\n\nExample some_term_is_stuck :\n  exists t, stuck t.\nProof.\n  exists (tsucc ttrue).\n  split; intro contra; solve by inversion 3.\nQed.\n\n(* END some_term_is_stuck. *)\n\n(* Exercise: 3 stars, advanced (value_is_nf) *)\n\nLemma value_is_nf : forall t,\n  value t -> step_normal_form t.\nProof.\n  intros t [bval | nval]; intro contra; destruct contra.\n  - solve by inversion 2.\n  - generalize dependent x.\n(*  induction t; inversion nval; intros; try solve by inversion.\n    inversion H1; subst.\n    apply IHt with t2; assumption.\nQed. *)\n    induction nval; intros; inversion H; subst.\n    apply IHnval with t2; assumption.\nQed.\n\n(* END value_is_nf. *)\n\n(* Exercise: 3 stars, optional (step_deterministic) *)\n\nLemma n_normal :\n  forall n n', nvalue n -> (n ==> n' -> False).\nProof.\n  intros. assert (value n) by (right; assumption).\n  apply value_is_nf in H1. unfold normal_form in H1.\n  apply H1. exists n'. assumption.\nQed.\n\nLtac nvalue_step :=\n  match goal with\n    H1 : nvalue ?E, H2 : ?E ==> ?F |- _ =>\n        eapply n_normal in H1; eauto; contradiction\n  end.\n\nLtac deterministic_tac :=\n  match goal with\n    H1 : ?R ?E ?F, H2 : forall e, ?R ?E e -> ?G = e |- _ =>\n      solve [ apply H2 in H1; subst; trivial ]\n  end\n  || fail \"is not a deterministic relation\".\n\nTheorem step_deterministic:\n  deterministic step.\nProof with eauto.\n  unfold deterministic.\n  intros.\n  generalize dependent y2.\n  induction H; intros; inversion H0; subst; try solve by inversion;\n    try solve_by_inversion_step (try nvalue_step); trivial;\n    try deterministic_tac.\nQed.\n\n(* END step_deterministic. *)\n\nInductive ty : Type :=\n  | TBool : ty\n  | TNat  : ty.\n\nReserved Notation \"'|-' t '\\in' S\" (at level 40).\n\nInductive has_type : tm -> ty -> Prop :=\n  | T_True :\n      |- ttrue  \\in TBool\n  | T_False :\n      |- tfalse \\in TBool\n  | T_If : forall (t1 t2 t3 : tm) (T : ty),\n      |- t1 \\in TBool ->\n      |- t2 \\in T ->\n      |- t3 \\in T ->\n      |- tif t1 t2 t3 \\in T\n  | T_Zero :\n      |- tzero \\in TNat\n  | T_Succ : forall t,\n      |- t \\in TNat ->\n      |- tsucc t \\in TNat\n  | T_Pred : forall t,\n      |- t \\in TNat ->\n      |- tpred t \\in TNat\n  | T_Iszero : forall t,\n      |- t \\in TNat ->\n      |- tiszero t \\in TBool\n  where \"'|-' t '\\in' S\" := (has_type t S).\n\nHint Constructors has_type.\n\n(* Exercise: 1 star, optional (succ_hastype_nat__hastype_nat) *)\n\nExample succ_hastype_nat__hastype_nat : forall t,\n  |- tsucc t \\in TNat ->\n  |- t \\in TNat.\nProof.\n  intros. inversion H. assumption.\nQed.\n\n(* END succ_hastype_nat__hastype_nat. *)\n\nLemma bool_canonical : forall t,\n  value t -> (|- t \\in TBool <-> bvalue t).\nProof.\n  split; intros; inversion H0; subst; auto; inversion H; solve by inversion.\nQed.\n\nLemma nat_canonical : forall n,\n  value n -> (|- n \\in TNat <-> nvalue n).\nProof.\n  split; intros.\n  - inversion H; try assumption; solve by inversion 2.\n  - induction H0; auto.\nQed.\n\n(* Exercise: 3 stars (finish_progress) *)\n\nTheorem progress : forall t T,\n  |- t \\in T ->\n  value t \\/ exists t', t ==> t'.\nProof.\n  intros.\n  induction H; auto.\n  - right. destruct IHhas_type1.\n    + apply bool_canonical in H; try assumption.\n      inversion H; subst; [ exists t2 | exists t3 ]; auto.\n    + destruct H2. exists (tif x t2 t3). auto.\n  - destruct IHhas_type.\n    + left. right. constructor. apply nat_canonical; auto.\n    + right. destruct H0. exists (tsucc x). auto.\n  - right. destruct IHhas_type.\n    + apply nat_canonical in H; try assumption. clear H0.\n      inversion H; subst; [ exists tzero | exists t0 ]; auto.\n    + destruct H0. exists (tpred x). auto.\n  - right. destruct IHhas_type.\n    + apply nat_canonical in H; try assumption; clear H0.\n      inversion H; subst; [ exists ttrue | exists tfalse ]; auto.\n    + destruct H0. exists (tiszero x). auto.\nQed.\n\n(* END finish_progress. *)\n\n(* Exercise: 3 stars, advanced (finish_progress_informal) *)\n\n(*\nIf the last rule in the derivation is `tsucc t`, then either |- t \\in Nat or\nthere exists t' such that t ==> t'. In the first case, `tsucc t` is a value by\nnv_succ and the fact that `t` is an nvalue by nat_canonical. In the second,\nthere exists a step (t ==> t' -> tsucc t ==> tsucc t').\n\nIf the last rule is `tpred t`, then either |- t \\in Nat or there exists t' such\nthat t ==> t. In all these cases there exists a next step. If |- t \\in Nat,\nthen it is an nvalue and is thus either an tzero, applicable for\n`tpred tzero ==> tzero`, or tsucc t' for some nvalue t', applicable for\n`tpred (tsucc t') ==> t'`. If `t ==> t'`, then `tpred t ==> tpred t'`.\n\nIf the last rule is `tiszero t`, then either |- t \\in Nat and t in an nvalue,\nor `t ==> t'` for some t'. In the first case, t can be tzero or tsucc t' for\nsome t', the first stepping into ttrue, the second stepping into tfalse. In the\ncase where `t ==> t'`, `tzero t ==> tzero t'`.\n*)\n\n(* END finish_progress_informal. *)\n\n(* Exercise: 1 star (step_review) *)\n\n(*\n + Every well-typed normal form is a value.\n + Every value is a normal form.\n + The single-step reduction relation is a partial function\n   (i.e., it is deterministic).\n - The single-step reduction relation is a total function.\n*)\n\n(* END step_review. *)\n\n(* Exercise: 2 stars (finish_preservation) *)\n\nTheorem preservation : forall t t' T,\n  |- t  \\in T ->\n  t ==> t'   ->\n  |- t' \\in T.\nProof with auto.\n  intros t t' T Htt Hst. generalize dependent t'.\n  induction Htt; intros; inversion Hst; subst...\n  inversion Htt...\nQed.\n\n(* END finish_preservation. *)\n\n(* Exercise: 3 stars (preservation_alternate_proof) *)\n\nTheorem preservation' : forall t t' T,\n  |- t  \\in T ->\n  t ==> t'   ->\n  |- t' \\in T.\nProof with eauto.\n  intros t t' T Htt Hst. generalize dependent T.\n  induction Hst; intros; inversion Htt...\n  inversion H1...\nQed.\n\n(* END preservation_alternate_proof. *)\n\nTactic Notation \"print_goal\" := match goal with |- ?x => idtac x end.\nTactic Notation \"normalize\" :=\n   repeat (print_goal; eapply multi_step ;\n             [ (eauto 10; fail) | (instantiate; simpl)]);\n   apply multi_refl.\n\n(* Exercise: 1 star (normalize_ex) *)\n\nTheorem normalize_ex : exists e',\n  multi (astep empty_state) (AMult (ANum 3) (AMult (ANum 2) (ANum 1))) e'.\nProof. eapply ex_intro. normalize. Qed.\n\n(* END normalize_ex. *)\n\nHint Constructors astep aval.\n\n(* Exercise: 1 star, optional (normalize_ex') *)\n\nTheorem normalize_ex' : exists e',\n  multi (astep empty_state) (AMult (ANum 3) (AMult (ANum 2) (ANum 1))) e'.\nProof. apply ex_intro with (ANum 6). normalize. Qed.\n\n(* END normalize_ex'. *)\n\n(* Exercise: 2 stars, recommended (subject_expansion) *)\n\nTheorem subject_expansion_not_holds :\n ~ (forall t t' T,\n    t ==> t' ->\n    |- t' \\in T ->\n    |- t  \\in T).\nProof.\n  assert (tif ttrue ttrue tzero ==> ttrue) by auto.\n  assert (|- ttrue \\in TBool) by auto.\n  assert (~ |- tif ttrue ttrue tzero \\in TBool).\n  { intro contra. solve by inversion 2. }\n  intro contra. apply H1. apply contra with ttrue; auto.\nQed.\n\n(* END subject_expansion. *)\n\n(* Exercise: 2 stars (variation1) *)\n\n(* \n      | T_SuccBool : ∀t,\n           ⊢ t ∈ TBool →\n           ⊢ tsucc t ∈ TBool\n\n  + Determinism of step (step itself doesn't even change)\n  - Progress (`tsucc ttrue` would have correct type but be stuck)\n  + Preservation\n\n*)\n\n(* END variation1. *)\n\n(* Exercise: 2 stars (variation2) *)\n\n(* \n       | ST_Funny1 : ∀t2 t3,\n           (tif ttrue t2 t3) ⇒ t3\n\n  - Determinism of step (`tif ttrue ttrue tfalse`\n      could return both ttrue and tfalse)\n  + Progress\n  + Preservation\n\n*)\n\n(* END variation2. *)\n\n(* Exercise: 2 stars, optional (variation3) *)\n\n(*\n       | ST_Funny2 : ∀t1 t2 t2' t3,\n           t2 ⇒ t2' →\n           (tif t1 t2 t3) ⇒ (tif t1 t2' t3) \n\n  - Determinism of step (`tif tfalse (tiszero tzero) tfalse`\n      could become `tfalse` or `tif tfalse ttrue tfalse`)\n  + Progress\n  + Preservation\n\n*)\n\n(* END variation3. *)\n\n(* Exercise: 2 stars, optional (variation4) *)\n\n(*\n       | ST_Funny3 :\n          (tpred tfalse) ⇒ (tpred (tpred tfalse)) \n\n  + Determinism of step\n  + Progress\n  + Preservation\n\n*)\n\n(* END variation4. *)\n\n(* Exercise: 2 stars, optional (variation5) *)\n\n(*\n\n       | T_Funny4 :\n            ⊢ tzero ∈ TBool\n\n  + Determinism of step\n  - Progress (`tif tzero ttrue ttrue` would stall even with a correct type)\n  - Preservation (|- tpred tzero \\in TNat ==> |- tzero \\in TBool)\n\n*)\n\n(* END variation5. *)\n\n(* Exercise: 2 stars, optional (variation6) *)\n\n(*\n\n       | T_Funny5 :\n            ⊢ tpred tzero ∈ TBool\n\n  + Determinism of step\n  + Progress\n  - Preservation (|- tpred tzero \\in TBool ==> |- tzero \\in TBool)\n\n*)\n\n(* END variation6. *)\n\n(* Exercise: 1 star (remove_predzero) *)\n\n(* Doing so would break the progress property since `tpred tzero` would be type\ncorrect but stuck. *)\n\n(* END remove_predzero. *)\n\n(* Exercise: 4 stars, advanced (prog_pres_bigstep) *)\n\n(* The analog of progress in big-step evaluation is always having a rule for\nthe next big step. For example, suppose we define a language\n\n          -------\n          C n ⇓ n\n\n          t2 ⇓ n2\n ---------------------\n P (C n1) t2 ⇓ n1 + n2\n\nThis is a big-step notation, but the progress isn't being make in case of\n`P (P (C 0) (C 2)) (C 3)`.\n\nNow, there is no straightforward analog for preservation since there are no\nsteps through which the types must be preserved. Nevertheless, we are able to\ndefine a type property such that all the programs that have it are either\nlooped or have a value. For this language, we can have\n\n ------------------\n |- (C n) \\in Const\n\n |- c1 \\in Const  |- t1 \\in Exp\n ------------------------------\n      |- P c1 t1 \\in Exp\n\n*)\n\n(* END prog_pres_bigstep. *)\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/Types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6739467783983306}}
{"text": "(* Steve Awodey's book on category theory *)\n(******************************************************************************)\n(* Chapter 1.3: Categories                                                    *)\n(******************************************************************************)\n(* @suharahiromichi *)\n\n(*\n(1) ベースライン\nhttp://www.megacz.com/berkeley/coq-categories/\nこれをもとに改変。Instance ... Proper を使うようにした。\n *)\n\n(*\n(2) Proper関数の定義\nA Gentle Introduction to Type Classes and Relations in Coq\n*)\n\n(*\n(3) Setoid を使うようにし、Setsと(P,<=)のインスタンスをつくる。\nhttp://www.iij-ii.co.jp/lab/techdoc/category/category1.html\n *)\n\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import finset fintype.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import Notations.\nRequire Import Morphisms.\nRequire Import Coq.Setoids.Setoid.\n\n(*\nReserved Notation \"x ~> y\" (at level 51, left associativity).\n*)\nReserved Notation \"x \\\\o y\" (at level 51, left associativity).\nReserved Notation \"x === y\" (at level 71, left associativity).\n\nGeneralizable Variables a b c d e.\n\nClass Setoid :=\n  {\n    carrier : Type;\n    eqv : carrier -> carrier -> Prop;\n    eqv_equivalence : Equivalence eqv\n  }.\nCoercion carrier : Setoid >-> Sortclass.\nNotation \"x === z\" := (eqv x z).\n\nClass Category (Obj : Type) (Hom : Obj -> Obj -> Setoid) :=\n  {\n    hom := Hom where \"a ~> b\" := (hom a b);\n    ob  := Obj;\n    id   : forall {a : Obj}, (a ~> a);\n    comp : forall {a b c : Obj},\n             (a ~> b) -> (b ~> c) -> (a ~> c)\n                                       where \"f \\\\o g\" := (comp f g);\n    comp_respects   : forall {a b c : Obj},\n                        Proper (@eqv (a ~> b) ==> @eqv (b ~>c) ==> @eqv (a ~> c)) comp;\n    left_identity   : forall `(f : a ~> b), id \\\\o f === f;\n    right_identity  : forall `(f : a ~> b), f \\\\o id === f;\n    associativity   : forall `(f : a ~> b) `(g : b ~> c) `(h : c ~> d),\n                        f \\\\o g \\\\o h === f \\\\o (g \\\\o h)\n}.\nCoercion ob : Category >-> Sortclass.\n\nNotation \"a ~> b\"       := (hom a b).\nNotation \"f === g\"      := (eqv f g).\nNotation \"f \\\\o g\"      := (comp f g).\n(* Notation \"a ~~{ C }~~> b\" := (@hom _ _ C a b). *)\n\nGeneralizable Variables Obj Hom Prod.\n\n(* eqv が、Reflexive と Symmetric と Transitive とを満たす。 *)\nInstance category_eqv_Equiv `(C : Category Obj) (a b : Obj) :\n  Equivalence (@eqv (a ~> b)).\nProof.\n  by apply eqv_equivalence.\nQed.\n\n(* comp は eqv について固有関数である。 *)\nInstance category_comp_Proper `(C : Category Obj) (a b c : Obj) :\n  Proper (@eqv (a ~> b) ==> @eqv (b ~>c) ==> @eqv (a ~> c)) comp.\nProof.\n  by apply comp_respects.\nQed.\n\n\n(* 可換性についての定理を証明する。 *)\nLemma juggle1 : forall `{C : Category}\n                       `(f : a ~> b) `(g : b ~> c) `(h : c ~> d) `(k : d ~> e),\n                  f \\\\o g \\\\o h \\\\o k === f \\\\o (g \\\\o h) \\\\o k.\nProof.\n  intros.\n  Check associativity f g h.\n  rewrite <- associativity.\n  reflexivity.\nDefined.\n\nLemma juggle2 : forall `{C : Category}\n                       `(f : a ~> b) `(g : b ~> c) `(h : c ~> d) `(k : d ~> e),\n                  f \\\\o (g \\\\o (h \\\\o k)) === f \\\\o (g \\\\o h) \\\\o k.\nProof.\n  intros.\n  do ! rewrite <- associativity.\n  reflexivity.\nDefined.\n\nLemma juggle3 : forall `{C : Category}\n                       `(f : a ~> b) `(g : b ~> c) `(h : c ~> d) `(k : d ~> e),\n                  f \\\\o g \\\\o (h \\\\o k) === f \\\\o (g \\\\o h) \\\\o k.\nProof.\n  intros.\n  do ! rewrite <- associativity.\n  reflexivity.\nDefined.\n\nReserved Notation \"x &&& y\" (at level 50, left associativity).\n\n(* 直積 *)\nClass Product `{CP : Category Obj}\n      `(proj1 : forall {a b : Obj}, (Prod a b) ~> a)\n      `(proj2 : forall {a b : Obj}, (Prod a b) ~> b) :=\n  {\n    (* 仲介射 *)\n    mediating : forall {a b x : Obj},\n                  (x ~> a) -> (x ~> b) -> (x ~> (Prod a b))\n                                            where \"f &&& g\" := (mediating f g);\n    \n    med_commute1 : forall (a b x : Obj) (f : x ~> a) (g : x ~> b),\n                     (f &&& g) \\\\o proj1 === f;\n    med_commute2 : forall (a b x : Obj) (f : x ~> a) (g : x ~> b),\n                     (f &&& g) \\\\o proj2 === g;\n    med_unique : forall (a b x : Obj) (f : x ~> a) (g : x ~> b) (h : x ~> (Prod a b)),\n                   h \\\\o proj1 === f ->\n                   h \\\\o proj2 === g ->\n                   h === (f &&& g)\n  }.\n\n(* **** *)\n(* Sets *)\n(* **** *)\nInstance EquivExt : forall (A B : Set), Equivalence (@eqfun A B) := (* notu *)\n  {\n    Equivalence_Reflexive := @frefl A B;\n    Equivalence_Symmetric := @fsym A B;\n    Equivalence_Transitive := @ftrans A B\n  }.\n\nInstance EqMor : forall (A B : Set), Setoid :=\n  {\n    carrier := A -> B;\n    eqv := @eqfun B A\n  }.\n  \nCheck @Category Set : (Set → Set → Setoid) → Type.\nCheck EqMor : Set -> Set -> Setoid.\nCheck @Category Set EqMor : Type.\n\nProgram Instance Sets : @Category Set EqMor.\nObligation 3.\nProof.\n  rewrite /Sets_obligation_2.\n  move=> homab homab' Hhomab hombc hombc' Hhombc.\n  move=> x //=.\n  rewrite Hhomab.\n  rewrite Hhombc.\n    by [].\nQed.\n\n(*\nInstance Prod : Product prod :=\n  {\n    proj1 A B := @fst A B;\n    proj2 A B := @snd A B ;\n    mediating A B X := fun f g x => (f x, g x)\n  }.\nProof.\n  - by rewrite //=.\n       - by rewrite //=.\n            - rewrite /commute /= /eqfun.\n    move=> A B X f g h H H0 x.\n    rewrite -H -H0.\n        by apply surjective_pairing.\n  Qed.\n*)\n\n\n(* **** *)\n(* P,<= *)\n(* **** *)\nOpen Scope coq_nat_scope.\nSearch \"_ <= _\".\nCheck 0 <= 0 : Prop.\n\nDefinition eq_le m n (p q : m <= n) := True.\n  \nInstance EquivGeq : forall m n, Equivalence (@eq_le m n). (* notu *)\nProof.\n    by [].\nQed. \n  \nInstance EqLe : forall m n, Setoid :=\n  {\n    carrier := m <= n;\n    eqv := @eq_le m n\n  }.\n\nCheck @Category nat : (nat → nat → Setoid) → Type.\nCheck EqLe : nat → nat → Setoid.\nCheck @Category nat EqLe.\n\nProgram Instance P_LE : @Category nat EqLe.\nObligation 2.\nProof.\n    by apply (@Le.le_trans a b c).\nDefined.\nObligation 3.\nProof.\n  rewrite /P_LE_obligation_1.\n  rewrite /P_LE_obligation_2.\n  move=> homab homab' Hhomab hombc hombc' Hhombc.\n  by rewrite /eq_le.\nDefined.\nObligation 4.\nProof.\n  rewrite /P_LE_obligation_1.\n  rewrite /P_LE_obligation_2.\n  by rewrite /eq_le.\nDefined.\nObligation 5.\nProof.\n  rewrite /P_LE_obligation_1.\n  rewrite /P_LE_obligation_2.\n  by rewrite /eq_le.\nDefined.\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/monad/Categories_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6739467730571096}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nSection Relations.\nVariable U : Type.\n\nDefinition Relation := U -> U -> Prop.\nVariable R : Relation.\n\nDefinition Reflexive : Prop := forall x : U, R x x.\n\nDefinition Transitive : Prop := forall x y z : U, R x y -> R y z -> R x z.\n\nDefinition Antisymmetric : Prop := forall x y : U, R x y /\\ R y x -> x = y.\n\nDefinition Order : Prop := (Reflexive /\\ Transitive) /\\ Antisymmetric.\n\nDefinition Symmetric : Prop := forall x y : U, R x y -> R y x.\n\nDefinition Equivalence : Prop := (Reflexive /\\ Symmetric) /\\ Transitive.\n\nDefinition PER : Prop := Symmetric /\\ Transitive.\n\nEnd Relations.\nHint Unfold Reflexive.\nHint Unfold Transitive.\nHint Unfold Antisymmetric.\nHint Unfold Order.\nHint Unfold Symmetric.\nHint Unfold Equivalence.\nHint Unfold PER.\n\nTheorem sym_not_P :\nforall (U : Type) (P : Relation U) (x y : U),\nSymmetric U P -> ~ P x y -> ~ P y x.\nProof. hammer_hook \"Relations\" \"Relations.sym_not_P\".\nintros U P x y H' H'0; unfold not at 1 in |- *; intro H'1.\napply H'0; apply H'; auto.\nQed.\n\nTheorem Equiv_from_order :\nforall (U : Type) (R : Relation U),\nOrder U R -> Equivalence U (fun x y : U => R x y /\\ R y x).\nProof. hammer_hook \"Relations\" \"Relations.Equiv_from_order\".\nintros U R H'; red in |- *.\nelim H'; intros H'0 H'1; elim H'0; intros H'2 H'3; clear H' H'0.\nsplit; [ split; red in |- * | red in |- * ].\nintro x; split; try exact (H'2 x).\nintros x y H'; elim H'; intros H'0 H'4; clear H'; auto.\nintros x y z H' H'0; elim H'0; intros H'4 H'5; clear H'0; elim H';\nintros H'6 H'7; clear H'.\nred in H'3.\nsplit; apply H'3 with y; auto.\nQed.\nHint Resolve Equiv_from_order.\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/group-theory/Relations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.673946771254748}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import coqutil.Z.Lia.\nRequire Import Coq.btauto.Btauto.\n\nLocal Open Scope Z_scope.\nLocal Open Scope bool_scope.\n\nModule Z.\n\n  Lemma testbit_minus1 i (H:0<=i) :\n    Z.testbit (-1) i = true.\n  Proof.\n    destruct i; try blia; exact eq_refl.\n  Qed.\n\n  Lemma testbit_mod_pow2 a n i (H:0<=n) :\n    Z.testbit (a mod 2 ^ n) i = (i <? n) && Z.testbit a i.\n  Proof.\n    destruct (Z.ltb_spec i n); rewrite\n      ?Z.mod_pow2_bits_low, ?Z.mod_pow2_bits_high by auto; auto.\n  Qed.\n\n  Lemma testbit_ones n i (H : 0 <= n) :\n    Z.testbit (Z.ones n) i = (0 <=? i) && (i <? n).\n  Proof.\n    destruct (Z.leb_spec 0 i), (Z.ltb_spec i n); cbn;\n      rewrite ?Z.testbit_neg_r, ?Z.ones_spec_low, ?Z.ones_spec_high by blia; trivial.\n  Qed.\n\n  Lemma testbit_ones_nonneg n i (Hn : 0 <= n) (Hi: 0 <= i) :\n    Z.testbit (Z.ones n) i = (i <? n).\n  Proof.\n    rewrite testbit_ones by blia.\n    destruct (Z.leb_spec 0 i); cbn; solve [trivial | blia].\n  Qed.\n\n  Lemma shiftl_spec': forall a n m : Z,\n      Z.testbit (Z.shiftl a n) m = negb (m <? 0) && Z.testbit a (m - n).\n  Proof.\n    intros.\n    destruct (Z.ltb_spec m 0).\n    - rewrite Z.testbit_neg_r; trivial.\n    - apply Z.shiftl_spec. assumption.\n  Qed.\n\n  Lemma shiftr_spec': forall a n m : Z,\n      Z.testbit (Z.shiftr a n) m = negb (m <? 0) && Z.testbit a (m + n).\n  Proof.\n    intros.\n    destruct (Z.ltb_spec m 0).\n    - rewrite Z.testbit_neg_r; trivial.\n    - apply Z.shiftr_spec. assumption.\n  Qed.\n\n  Lemma lnot_spec' : forall a n : Z,\n      Z.testbit (Z.lnot a) n = negb (n <? 0) && negb (Z.testbit a n).\n  Proof.\n    intros.\n    destruct (Z.ltb_spec n 0).\n    - rewrite Z.testbit_neg_r; trivial.\n    - apply Z.lnot_spec. assumption.\n  Qed.\n\n  Lemma div_pow2_bits' : forall a n m : Z,\n      0 <= n ->\n      Z.testbit (a / 2 ^ n) m = negb (m <? 0) && Z.testbit a (m + n).\n  Proof.\n    intros.\n    destruct (Z.ltb_spec m 0).\n    - rewrite Z.testbit_neg_r; trivial.\n    - apply Z.div_pow2_bits; trivial.\n  Qed.\n\n  Lemma bits_opp' : forall a n : Z,\n      Z.testbit (- a) n = negb (n <? 0) && negb (Z.testbit (Z.pred a) n).\n  Proof.\n    intros.\n    destruct (Z.ltb_spec n 0).\n    - rewrite Z.testbit_neg_r; trivial.\n    - apply Z.bits_opp; trivial.\n  Qed.\n\n  Lemma testbit_ones_nonneg' : forall n i : Z,\n      0 <= n ->\n      Z.testbit (Z.ones n) i = negb (i <? 0) && (i <? n).\n  Proof.\n    intros.\n    destruct (Z.ltb_spec i 0).\n    - rewrite Z.testbit_neg_r; trivial.\n    - apply testbit_ones_nonneg; trivial.\n  Qed.\n\n  Lemma testbit_minus1' : forall i : Z,\n      Z.testbit (-1) i = negb (i <? 0).\n  Proof.\n    intros.\n    destruct (Z.ltb_spec i 0).\n    - rewrite Z.testbit_neg_r; trivial.\n    - apply testbit_minus1; trivial.\n  Qed.\n\n  Lemma or_to_plus: forall a b,\n      Z.land a b = 0 ->\n      Z.lor a b = a + b.\n  Proof.\n    intros.\n    rewrite <- Z.lxor_lor by assumption.\n    symmetry. apply Z.add_nocarry_lxor. assumption.\n  Qed.\n\n  (* 3 kinds of rewrite lemmas to turn (Z.testbit (Z.some_op ...)) into a boolean expression: *)\n\n  (* 1) lemmas without any hypotheses (these are our favorites) *)\n  #[global]\n  Hint Rewrite\n       Z.lor_spec\n       Z.lxor_spec\n       Z.land_spec\n       Z.ldiff_spec\n       Z.testbit_0_l\n    : z_bitwise_no_hyps.\n  #[global]\n  Hint Rewrite <-Z.ones_equiv : z_bitwise_no_hyps.\n\n  (* 2) lemmas which have linear arithmetic hypotheses (good if we can solve the hypotheses) *)\n  #[global]\n  Hint Rewrite\n       Z.shiftl_spec_low\n       Z.shiftl_spec_alt\n       Z.shiftl_spec\n       Z.shiftr_spec_aux\n       Z.lnot_spec\n       Z.shiftr_spec\n       Z.ones_spec_high\n       Z.ones_spec_low\n       Z.div_pow2_bits\n       Z.pow2_bits_eqb\n       Z.bits_opp\n       Z.testbit_mod_pow2\n       Z.testbit_ones_nonneg\n       Z.testbit_minus1\n       using solve [auto with zarith]\n    : z_bitwise_with_hyps.\n\n  (* 3) lemmas where we move some or all linear algebra preconditions into the conclusion\n     by turning them into a boolean test\n     (used as a fallback to make sure the bitblaster knows that it's worth case-destructing) *)\n  #[global]\n  Hint Rewrite\n       Z.shiftl_spec'\n       Z.shiftr_spec'\n       Z.lnot_spec'\n       Z.div_pow2_bits'\n       Z.bits_opp'\n       Z.testbit_ones_nonneg'\n       Z.testbit_minus1'\n       using solve [auto with zarith]\n    : z_bitwise_forced_no_hyps.\n\n  Ltac rewrite_bitwise :=\n    repeat (autorewrite with z_bitwise_no_hyps;\n            autorewrite with z_bitwise_with_hyps);\n    autorewrite with z_bitwise_forced_no_hyps.\n\n  Ltac destruct_ltbs :=\n    repeat match goal with\n           | |- context [ ?a <? ?b ] => destruct (Z.ltb_spec a b)\n           end.\n\n  Ltac discover_equal_testbit_indices :=\n    repeat match goal with\n           | |- context [Z.testbit _ ?i] =>\n             assert_fails (is_var i);\n             let l := fresh \"l\" in remember i as l\n           end;\n    repeat match goal with\n           | i: Z, j: Z |- _ => replace i with j in * by blia; clear i\n           end.\n\n  Ltac bitblast_core :=\n    rewrite_bitwise;\n    discover_equal_testbit_indices;\n    destruct_ltbs;\n    try (exfalso; blia);\n    try btauto.\n\n  (* Note: The Coq Standard library already provides a tactic called \"Z.bitwise\", but\n     it's less powerful because it does no splitting *)\n  Ltac bitblast := eapply Z.bits_inj'; intros ?i ?Hi; bitblast_core.\n\nEnd Z.\n\nGoal forall v i j k,\n    0 <= i ->\n    i <= j ->\n    j <= k ->\n    Z.land (Z.shiftl (v / 2 ^ i) i) (Z.ones j) +\n    Z.land (Z.shiftl (v / 2 ^ j) j) (Z.ones k) =\n    Z.land (Z.shiftl (v / 2 ^ i) i) (Z.ones k).\nProof.\n  intros. rewrite <- Z.or_to_plus; Z.bitblast.\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/bitblast.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6739467695182494}}
{"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 Nk_ind.\nRequire Export Npow.\nRequire Export Ndiv.\nOpen Scope nat_scope.\n\n(** * Definition of a finite product on [nat] with an index starting from 0 *)\nFixpoint Nfinite_prod_0_n (n:nat) (f:nat -> nat) {struct n} : nat :=\nmatch n with\n| 0 => f 0\n| S n' => (Nfinite_prod_0_n n' f) * (f n)\nend.\n\n(** * Properties of finite product *)\n(** Compatibility with equality (limited equality) *)\nLemma Nfinite_prod_subtle_eq_compat : forall n f g,\n  (forall k, k <= n -> f k = g k) -> Nfinite_prod_0_n n  f= Nfinite_prod_0_n n g.\nProof.\ninduction n.\ncompute. intros.\napply H. trivial.\nintros.\nunfold Nfinite_prod_0_n. fold Nfinite_prod_0_n.\nrewrite (IHn f g).\nrewrite (H (S n)).\nreflexivity.\ntrivial.\nintros.\napply H.\nauto with arith.\nQed.\n\n(** Compatibility with equality (unlimited equality) *)\nLemma Nfinite_prod_eq_compat : forall n f g,\n  (forall k, f k = g k) -> Nfinite_prod_0_n n f = Nfinite_prod_0_n n g.\nProof.\nintros.\napply Nfinite_prod_subtle_eq_compat.\nintros.\napply H.\nQed.\n\n(** One term, upper splitting of finite product *)\nLemma Nfinite_prod_split_upper : forall n f,\n  Nfinite_prod_0_n (S n) f = (Nfinite_prod_0_n n f) * (f (S n)).\nProof.\nunfold Nfinite_prod_0_n. fold Nfinite_prod_0_n.\nreflexivity.\nQed.\n\n(** One term, lower splitting of finite product *)\nLemma Nfinite_prod_split_lower : forall n f,\n  Nfinite_prod_0_n (S n) f = (f 0) * (Nfinite_prod_0_n n (fun k => f (S k))).\nProof.\ninduction n.\nintros.\nunfold Nfinite_prod_0_n.\nreflexivity.\nintros.\nrewrite Nfinite_prod_split_upper.\nrewrite IHn.\nrewrite Nfinite_prod_split_upper.\nring.\nQed.\n\n(** Compatibility with multiplication *)\nLemma Nfinite_prod_mult_compat : forall n f a g,\n  (forall k, k <= n -> f k = a * g k) -> Nfinite_prod_0_n n f = a^(S n) * Nfinite_prod_0_n n g.\nProof.\ninduction n.\nintros.\nunfold Nfinite_prod_0_n.\nunfold Npower. unfold iter_nat.\nrewrite mult_1_r.\napply H.\nauto with arith.\nintros.\nrewrite Nfinite_prod_split_upper.\nrewrite Nfinite_prod_split_upper.\nrewrite H.\nrewrite IHn with f a g.\nrewrite Npower_succ.\nrewrite Npower_succ.\nrewrite Npower_succ.\nring.\nintros.\napply H.\nauto with arith.\nauto with arith.\nQed.\n\n(** 0 is absorbant *)\nLemma Nfinite_prod_0_absord : forall n f k,\n  k <= n -> f k = 0 -> Nfinite_prod_0_n n f = 0.\nProof.\ninduction n.\nintros.\ncompute.\napply le_n_O_eq in H.\nrewrite <- H in H0.\nexact H0.\n\nintros.\nrewrite Nfinite_prod_split_upper.\napply le_le_S_eq in H.\ndestruct H.\nrewrite IHn with f k.\nring.\nauto with arith.\nexact H0.\nrewrite <- H.\nrewrite H0.\nring.\nQed.\n\n(** Factorial is a finite product *)\nLemma Nfactorial_is_finite_prod : forall n,\n  fact (S n) = Nfinite_prod_0_n n (fun k => S k).\nProof.\ninduction n.\ncompute. reflexivity.\nassert (fact (S(S n))=S(S n)*fact(S n)).\ncompute. reflexivity.\nrewrite H. clear H.\nrewrite Nfinite_prod_split_upper.\nrewrite IHn.\nring.\nQed.\n\n(** Index reversal *)\nLemma Nfinite_prod_index_reversal : forall n f,\n  Nfinite_prod_0_n n f = Nfinite_prod_0_n n (fun k => f(n - k)).\nProof.\ninduction n.\ncompute. reflexivity.\nintros.\nrewrite Nfinite_prod_split_upper.\nrewrite Nfinite_prod_split_lower.\nrewrite IHn.\nrewrite <- minus_n_O.\nassert (Nfinite_prod_0_n n (fun k : nat => f (S n - S k)) =\n  Nfinite_prod_0_n n (fun k : nat => f (n - k))).\napply Nfinite_prod_subtle_eq_compat.\nintros.\nassert (S n-S k=n-k).\nauto with arith.\nrewrite H0. reflexivity.\nrewrite H.\nring.\nQed.\n\n(** Divisibility of finite product *)\nLemma Nfinite_prod_div : forall n f k p,\n  k <= n -> (p | f k) -> (p | Nfinite_prod_0_n n f).\nProof.\ninduction n.\nintros.\ninversion H.\nrewrite H1 in * |- *.\nsimpl. auto.\nintros.\napply le_le_S_eq in H.\ndestruct H.\napply le_S_n in H.\nsimpl.\napply Ndiv_mult_compat.\napply IHn with k.\nauto. auto.\nsimpl.\nrewrite mult_comm.\napply Ndiv_mult_compat.\nrewrite <- H.\nauto.\nQed.\n", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/rls/rls1/Arith/Nfinite_prod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673223709251, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.6738172763998433}}
{"text": "(** * Ccpo.v: Specification and properties of a cpo *)\n\nRequire Export Arith.\n(* Require Export Omega. *)\nFrom Coq Require Import Lia.\n\nRequire Export Coq.Classes.SetoidTactics.\nRequire Export Coq.Classes.SetoidClass.\nRequire Export Coq.Classes.Morphisms.\n\nDeclare Scope signature_scope.\nLocal Open Scope signature_scope.\nDeclare Scope O_scope.\nDelimit Scope O_scope with O.\nLocal Open Scope O_scope.\n\n(** ** Ordered type *)\n\nDefinition eq_rel {A} (E1 E2:relation A) := forall x y, E1 x y <-> E2 x y.\n\nClass Order {A} (E:relation A)  (R:relation A) :=\n  {reflexive :> Reflexive R;\n   order_eq : forall x y, R x y /\\ R y x <-> E x y;\n   transitive :> Transitive R }.\n\nGeneralizable Variables A E R.\n\n#[export] Instance OrderEqRefl `{Order A E R} : Reflexive E.\ndestruct H as  (rO,aO,tO).\nintros x.\nrewrite <- aO; intuition.\nQed.\n\n#[export] Instance OrderEqSym `{Order A E R} : Symmetric E.\ndestruct H as (rO,aO,tO).\nintros x y e.\npose (aO x y); pose (aO y x); intuition.\nQed.\n\n#[export] Instance OrderEqTrans `{Order A E R} : Transitive E.\ndestruct H as (rO,aO,tO).\nintros x y z e1 e2.\npose (aO x y); pose (aO y z); pose (aO x z); pose (tO x y z); pose (tO z y x); intuition.\nQed.\n\n#[export] Instance OrderEquiv `{Order A E R} : Equivalence E.\nsplit; auto with *.\napply OrderEqTrans.\nQed.\nOpaque OrderEquiv.\n\nClass ord A :=\n   {  Oeq : relation A;\n      Ole : relation A;\n      order_rel :> Order Oeq Ole }.\n\n\nLemma OrdSetoid `(o:ord A) : Setoid A.\nintros. split with Oeq. apply OrderEquiv.\n(* compatibility with Jan's version *)\n(*try (split; [apply OrderEqRefl| apply OrderEqSym| apply OrderEqTrans]).*)\nDefined.\n\n(*\n#[export] Typeclasses Opaque equiv.\n\n#[export] Instance OrdEquiv `(o:ord A) : Equivalence (equiv (A:=A)).\nintros A (E,R,O); apply OrderEquiv.\nQed.\n*)\n\nAdd Parametric Relation {A} {o:ord A} : A (@Oeq _ o)\nreflexivity proved  by OrderEqRefl\nsymmetry proved  by OrderEqSym\ntransitivity proved by OrderEqTrans\nas Oeq_setoid.\n\n(** printing <= $\\le$ # &le; # *)\n(** printing == $\\equiv$ # &asymp; # *)\n\nInfix \"<=\" := Ole : O_scope.\nInfix \"==\" := Oeq : type_scope.\n\nDefinition Oge {O} {o:ord O} := fun (x y:O) => y <= x.\nInfix \">=\" := Oge : O_scope.\n\n\nLemma Ole_refl_eq : forall {O} {o:ord O} (x y:O), x == y -> x <= y.\nintros O (oeq,ole,(rO,aO,tO)) x y; simpl; pose (aO x y); intuition.\nQed.\n\n#[export] Hint Immediate Ole_refl_eq : core.\n\nLemma Ole_refl_eq_inv : forall {O} {o:ord O} (x y:O), x == y -> y <= x.\nintros O (oeq,ole,(rO,aO,tO)) x y; simpl; pose (aO x y); intuition.\nQed.\n\n#[export] Hint Immediate Ole_refl_eq_inv : core.\n\nLemma Ole_trans : forall {O} {o:ord O} (x y z:O), x <= y -> y <= z -> x <= z.\nintros O (oeq,ole,(rO,aO,tO)) x y z H1 H2; simpl; apply tO with y; auto.\nQed.\n\nLemma Ole_refl : forall {O} {o:ord O} (x:O), x <= x.\nintros O (oeq,ole,(rO,aO,tO)) x; simpl; auto.\nQed.\n\n#[export] Hint Resolve Ole_refl : core.\n\nAdd Parametric Relation {A} {o:ord A} : A (@Ole _ o)\nreflexivity proved  by Ole_refl\ntransitivity proved by Ole_trans\nas Ole_setoid.\n\nLemma Ole_antisym : forall {O} {o:ord O} (x y:O), x <= y -> y <= x -> x == y.\nintros O (oeq,ole,(rO,aO,tO)) x y; simpl; pose (aO x y); intuition.\nQed.\n#[export] Hint Immediate Ole_antisym : core.\n\nLemma Oeq_refl : forall {O} {o:ord O} (x:O), x == x.\nintros; apply OrderEqRefl.\nQed.\n#[export] Hint Resolve Oeq_refl : core.\n\nLemma Oeq_refl_eq : forall {O} {o:ord O} (x y:O), x = y -> x == y.\nintros O o x y H; rewrite H; auto.\nQed.\n#[export] Hint Resolve Oeq_refl_eq : core.\n\nLemma Oeq_sym : forall {O} {o:ord O} (x y:O), x == y -> y == x.\nintros; apply OrderEqSym; trivial.\nQed.\n\nLemma Oeq_le : forall {O} {o:ord O} (x y:O), x == y -> x <= y.\nintros O (oeq,ole,(rO,aO,tO)) x y; simpl; pose (aO x y); intuition.\nQed.\n\nLemma Oeq_le_sym : forall {O} {o:ord O} (x y:O), x == y -> y <= x.\nintros O (oeq,ole,(rO,aO,tO)) x y; simpl; pose (aO x y); intuition.\nQed.\n\n#[export] Hint Resolve Oeq_le : core.\n#[export] Hint Immediate Oeq_sym Oeq_le_sym : core.\n\nLemma Oeq_trans\n   : forall {O} {o:ord O} (x y z:O), x == y -> y == z -> x == z.\nintros; apply OrderEqTrans with y; trivial.\nQed.\n#[export] Hint Resolve Oeq_trans : core.\n\n\n\nAdd Parametric Morphism `(o:ord A): (Ole (ord:=o))\nwith signature (Oeq (A:=A) ==> Oeq (A:=A) ==> iff) as Ole_eq_compat_iff.\nintros x1 y1 e1 x2 y2 e2.\nsplit; intros.\ntransitivity x1; auto.\ntransitivity x2; auto.\ntransitivity y1; auto.\ntransitivity y2; auto.\nQed.\n\n(** Equivalence of orders *)\n\nDefinition eq_ord {O} (o1 o2:ord O) := eq_rel (Ole (ord:=o1)) (Ole (ord:=o2)).\n\nLemma eq_ord_equiv : forall {O} (o1 o2:ord O), eq_ord o1 o2 ->\n      eq_rel (Oeq (ord:=o1)) (Oeq (ord:=o2)).\nintros O (eq1,le1,(r1,as1,t1)) (eq2,le2,(r2,as2,t2)); unfold eq_ord, eq_rel; simpl; intros.\ntransitivity (le2 x y /\\ le2 y x); auto.\nrewrite <- as1; auto.\nrepeat rewrite H; reflexivity.\nQed.\n\n(** printing ==> %\\ensuremath\\Longrightarrow% #&#8702;# *)\n\nLemma Ole_eq_compat :\n     forall {O} {o:ord O} (x1 x2 : O),\n       x1 == x2 -> forall x3 x4 : O, x3 == x4 -> x1 <= x3 -> x2 <= x4.\nintros o x1 x2 H1 x3 x4 H2 H3; case (Ole_eq_compat_iff o x1 x2 H1 x3 x4 H2); auto.\nQed.\n\nLemma Ole_eq_right : forall {O} {o:ord O} (x y z: O),\n             x <= y -> y == z -> x <= z.\nintros; apply Ole_eq_compat with x y; auto.\nQed.\n\nLemma Ole_eq_left : forall {O} {o:ord O} (x y z: O),\n             x == y -> y <= z -> x <= z.\nintros; apply Ole_eq_compat with y z; auto.\nQed.\n\nAdd Parametric Morphism `{o:ord A} : (Oeq (A:=A))\n       with signature Oeq ==> Oeq ==>  iff as Oeq_iff_morphism.\nintros.\nrewrite H.\nrewrite H0.\nintuition.\nQed.\n\nAdd Parametric Morphism `{o:ord A} : (Ole (A:=A))\n       with signature Oeq ==> Oeq ==>  iff as Ole_iff_morphism.\nintros.\nrewrite H.\nrewrite H0.\nintuition.\nQed.\n\nAdd Parametric Morphism `{o:ord A} : (Ole (A:=A))\n       with signature Ole --> Ole ==>  Basics.impl as Ole_impl_morphism.\nred; intros.\ntransitivity x; trivial.\ntransitivity x0; trivial.\nQed.\n\n(** ** Definition and properties of [ x < y ] *)\nDefinition Olt `{o:ord A} (r1 r2:A) : Prop := (r1 <= r2) /\\ ~ (r1 == r2).\n\nInfix \"<\" := Olt : O_scope.\n\nLemma Olt_eq_compat `{o:ord A} :\nforall x1 x2 : A, x1 == x2 -> forall x3 x4 : A, x3 == x4 -> x1 < x3 -> x2 < x4.\nunfold Olt; intros x1 x2 eq1 x3 x4 eq2 (Hle,Hne).\nrewrite <- eq1; rewrite <- eq2; auto.\nQed.\n\nAdd Parametric Morphism `{o:ord A} : (Olt (A:=A))\nwith signature Oeq ==> Oeq ==> iff as Olt_iff_morphism.\nintros x1 x2 eq1 x3 x4 eq2; split.\nexact (Olt_eq_compat _ _ eq1 _ _ eq2).\nintros; apply Olt_eq_compat with x2 x4; auto.\nQed.\n\nLemma Olt_neq `{o:ord A} : forall x y:A, x < y -> ~ x == y.\nunfold Olt; intuition.\nQed.\n\nLemma Olt_neq_rev `{o:ord A} : forall x y:A, x < y -> ~ y == x.\nintros x y (Hle,Hne) H; auto.\nQed.\n\nLemma Olt_le `{o:ord A} : forall x y, x < y -> x <= y.\nintros x y (Hle,Hne); auto.\nQed.\n\nLemma Olt_notle `{o:ord A} : forall x y, x < y -> ~ y <= x.\nintros x y (Hle,Hne) H; auto.\nQed.\n\nLemma Olt_trans `{o:ord A} : forall x y z:A, x < y -> y < z -> x < z.\nintros x y z (Hle1,Hne1) (Hle2,Hne2); split.\ntransitivity y; trivial.\nintro Heq; apply Hne2.\napply Ole_antisym; auto.\nrewrite <- Heq; trivial.\nQed.\n\nLemma Ole_diff_lt `{o:ord A} : forall x y : A,  x <= y -> ~ x == y -> x < y.\nred; intuition.\nQed.\n\nLemma Ole_notle_lt `{o:ord A} : forall x y : A,  x <= y -> ~ y <= x -> x < y.\nred; intuition.\nQed.\n\n#[export] Hint Immediate Olt_neq Olt_neq_rev Olt_le Olt_notle : core.\n#[export] Hint Resolve Ole_diff_lt : core.\n\nLemma Olt_antirefl `{o:ord A} : forall x:A, ~ x < x.\nunfold Olt; intuition.\nQed.\n\n\nLemma Ole_lt_trans `{o:ord A} : forall x y z:A, x <= y -> y < z -> x < z.\nintros x y z H (Hle,Hne); split.\ntransitivity y; trivial.\nintro Heq; apply Hne; apply Ole_antisym; auto.\nrewrite <- Heq; trivial.\nQed.\n\nLemma Olt_le_trans `{o:ord A} : forall x y z:A, x < y -> y <= z -> x < z.\nintros x y z (Hle,Hne) H; split.\ntransitivity y; trivial.\nintro Heq; apply Hne; apply Ole_antisym; auto.\nrewrite Heq; trivial.\nQed.\n\n#[export] Hint Resolve Olt_antirefl : core.\n\nLemma Ole_not_lt `{o:ord A} : forall x y:A, x <= y -> ~ y < x.\nintros x y H (Hle,Hne).\napply Hne; auto.\nQed.\n#[export] Hint Resolve Ole_not_lt : core.\n\nAdd Parametric Morphism `{o:ord A} : (Olt (A:=A))\n       with signature Ole --> Ole ==>  Basics.impl as Olt_le_compat.\nred; intros.\napply Ole_lt_trans with x; trivial.\napply Olt_le_trans with x0; trivial.\nQed.\n\n(** *** Dual order *)\n\n(** - [ Iord x y =  y <= x ]  *)\nDefinition Iord : forall O {o:ord O}, ord O.\nintros O o; exists (Oeq (A:=O)) (fun x y => y <=x).\nabstract (split; intuition; red; intros; transitivity y; auto).\nDefined.\n\nArguments Iord O {o}.\n\n(** *** Order on functions *)\n\nDefinition fun_ext A B (R:relation B) : relation (A -> B) :=\n                fun f g => forall x, R (f x) (g x).\nArguments fun_ext A [B] R.\n\n(** - [ ford f g ] := [ forall x, f x <= g x ] *)\n#[export] Program Instance ford A O {o:ord O} : ord (A -> O) :=\n  {Oeq:=fun_ext A (Oeq (A:=O)); Ole:=fun_ext A (Ole (A:=O))}.\nNext Obligation.\nabstract (split; unfold fun_ext; intros; intuition;\n               red; intros;transitivity (y x0); auto).\nDefined.\n\nLemma ford_le_elim : forall A O (o:ord O) (f g:A -> O), f <= g -> forall n, f n <= g n.\nauto.\nQed.\n#[export] Hint Immediate ford_le_elim : core.\n\n\nLemma ford_le_intro : forall A O (o:ord O) (f g:A -> O), ( forall n, f n <= g n ) -> f <= g.\nauto.\nQed.\n#[export] Hint Resolve ford_le_intro : core.\n\nLemma ford_eq_elim : forall A O (o:ord O) (f g:A -> O), f == g -> forall n, f n == g n.\nauto.\nQed.\n#[export] Hint Immediate ford_eq_elim : core.\n\nLemma ford_eq_intro : forall A O (o:ord O) (f g:A -> O), ( forall n, f n == g n ) -> f == g.\nauto.\nQed.\n#[export] Hint Resolve ford_eq_intro : core.\n\n(** ** Monotonicity *)\n\n(** *** Definition and properties *)\n\nGeneralizable Variables Oa Ob Oc Od.\n\nClass monotonic `{o1:ord Oa} `{o2:ord Ob} (f : Oa -> Ob) :=\n      monotonic_def : forall x y, x <= y -> f x <= f y.\n\nLemma monotonic_intro : forall  `{o1:ord Oa} `{o2:ord Ob} (f : Oa -> Ob),\n  (forall x y, x <= y -> f x <= f y) -> monotonic f.\nred; auto.\nQed.\n#[export] Hint Resolve monotonic_intro : core.\n\n\n(*\nInstance monotonic_morphism `{o1:ord Oa} `{o2:ord Ob} (f : Oa -> Ob) {m:monotonic f} :\n  Morphism (Ole (A:=Oa) ==> Ole (A:=Ob)) f.\n *)\n\nAdd Parametric Morphism `{o1:ord Oa} `{o2:ord Ob} (f : Oa -> Ob) {m:monotonic f} : f\nwith signature (Ole (A:=Oa) ==> Ole (A:=Ob))\nas monotonic_morphism.\nauto.\nQed.\n\nClass stable `{o1:ord Oa} `{o2:ord Ob} (f : Oa -> Ob) :=\n      stable_def : forall x y, x == y -> f x == f y.\n#[export] Hint Unfold stable : core.\n\nLemma stable_intro : forall  `{o1:ord Oa} `{o2:ord Ob} (f : Oa -> Ob),\n  (forall x y, x == y -> f x == f y) -> stable f.\nred; auto.\nQed.\n#[export] Hint Resolve stable_intro : core.\n\nAdd Parametric Morphism `{o1:ord Oa} `{o2:ord Ob} (f : Oa -> Ob) {s:stable f} : f\nwith signature (Oeq (A:=Oa) ==> Oeq (A:=Ob))\nas stable_morphism.\nauto.\nQed.\n\n#[export] Typeclasses Opaque monotonic stable.\n\n#[export] Instance monotonic_stable `{o1:ord Oa} `{o2:ord Ob} (f : Oa -> Ob) {m:monotonic f}\n         :  stable  f.\nunfold monotonic, stable; simpl; intros.\napply Ole_antisym; auto.\nQed.\n\n(** *** Type of monotonic functions *)\n\nRecord fmon `{o1:ord Oa} `{o2:ord Ob}:= mon\n          {fmont :> Oa -> Ob;\n           fmonotonic: monotonic fmont}.\n\n#[export]\nExisting Instance fmonotonic.\n\nArguments mon [Oa o1 Ob o2] fmont {fmonotonic}.\nArguments fmon Oa [o1] Ob {o2}.\n\n#[export] Hint Resolve fmonotonic : core.\n\n(** printing -m> %\\ensuremath{\\stackrel{m}{\\rightarrow}}% #-m>#*)\n(** printing -m-> %\\ensuremath{\\stackrel{m}{\\rightarrow}\\!\\!-}% #-m->#*)\n(** printing --m-> %\\ensuremath{-\\!\\!\\stackrel{m}{\\rightarrow}\\!\\!-}% #--m->#*)\n(** printing --m> %\\ensuremath{-\\!\\!\\stackrel{m}{\\rightarrow}}% #--m>#*)\n\nNotation \"Oa -m> Ob\" := (fmon Oa Ob)\n   (right associativity, at level 30) : O_scope.\nNotation \"Oa --m> Ob\" := (fmon Oa (o1:=Iord Oa) Ob )\n   (right associativity, at level 30) : O_scope.\nNotation \"Oa --m-> Ob\" := (fmon Oa (o1:=Iord Oa) Ob (o2:=Iord Ob))\n   (right associativity, at level 30) : O_scope.\nNotation \"Oa -m-> Ob\" := (fmon Oa Ob  (o2:=Iord Ob))\n   (right associativity, at level 30) : O_scope.\n\nOpen Scope O_scope.\n\n\nLemma mon_simpl : forall `{o1:ord Oa} `{o2:ord Ob} (f:Oa -> Ob){mf: monotonic f} x,\n      mon f x = f x.\ntrivial.\nQed.\n#[export] Hint Resolve mon_simpl : core.\n\n\n#[export] Instance fstable `{o1:ord Oa} `{o2:ord Ob} (f:Oa -m> Ob) : stable f.\nintros; apply monotonic_stable; auto.\nQed.\n\n#[export] Hint Resolve fstable : core.\n\nLemma fmon_le : forall `{o1:ord Oa} `{o2:ord Ob} (f:Oa -m> Ob) x y,\n                x <= y -> f x <= f y.\nintros; apply (fmonotonic f); auto.\nQed.\n#[export] Hint Resolve fmon_le : core.\n\nLemma fmon_eq : forall `{o1:ord Oa} `{o2:ord Ob} (f:Oa -m> Ob) x y,\n                x == y -> f x == f y.\nintros; apply (fstable f); auto.\nQed.\n#[export] Hint Resolve fmon_eq : core.\n\n#[export] Program Instance fmono Oa Ob {o1:ord Oa} {o2:ord Ob} : ord (Oa -m> Ob)\n   := {Oeq := fun (f g : Oa-m> Ob)=> forall x, f x == g x;\n       Ole := fun (f g : Oa-m> Ob)=> forall x, f x <= g x}.\nNext Obligation.\nabstract (split; unfold fun_ext; intros; intuition;\n               red; intros; transitivity (y x0); auto).\nDefined.\n\nLemma mon_le_compat : forall `{o1:ord Oa} `{o2:ord Ob} (f g:Oa -> Ob)\n      {mf:monotonic f} {mg:monotonic g}, f <= g -> mon f <= mon g.\nred; intros; auto.\nQed.\n#[export] Hint Resolve mon_le_compat : core.\n\nLemma mon_eq_compat : forall `{o1:ord Oa} `{o2:ord Ob} (f g:Oa-> Ob)\n      {mf:monotonic f} {mg:monotonic g}, f == g -> mon f == mon g.\nred; intros; auto.\nQed.\n#[export] Hint Resolve mon_eq_compat : core.\n\nAdd Parametric Morphism `{o1:ord Oa} `{o2:ord Ob}\n       : (fmont (Oa:=Oa) (Ob:=Ob))\n       with signature Oeq ==> Oeq ==> Oeq as fmont_eq_morphism.\nintros [f] [g] H x y h.\nsimpl.\nrewrite (H x).\nrewrite h.\nsimpl.\nauto.\nQed.\n\n(** *** Monotonicity and dual order *)\n\nLemma Imonotonic `{o1:ord Oa} `{o2:ord Ob} (f:Oa -> Ob) {m:monotonic f}\n         : monotonic (o1:=Iord Oa) (o2:=Iord Ob) f.\nred; simpl; intros.\napply m; auto.\nQed.\n\n#[export] Hint Extern 2 (@monotonic _ (Iord _) _ (Iord _) _) => apply @Imonotonic\n  : typeclass_instances.\n\nDefinition imon `{o1:ord Oa} `{o2:ord Ob} (f:Oa -> Ob) {m:monotonic f}\n   : Oa --m-> Ob := mon (o1:=Iord Oa) (o2:=Iord Ob) f.\n\nLemma imon_simpl : forall `{o1:ord Oa} `{o2:ord Ob} (f:Oa -> Ob) {m:monotonic f} (x:Oa),\n     imon f x = f x.\ntrivial.\nQed.\n\n(** - [Iord (A -> U)] corresponds to [A -> Iord U] *)\n\nLemma Iord_app {A} `{o1:ord Oa} (x: A) : ((A -> Oa) --m-> Oa).\nintros; exists (fun f => f x).\nabstract(red; auto).\nDefined.\n\n(** - [Imon f] uses f as monotonic function over the dual order. *)\n\nDefinition Imon : forall `{o1:ord Oa} `{o2:ord Ob}, (Oa -m> Ob) -> (Oa --m-> Ob).\nintros Oa o1 Ob o2 f.\nexists (fmont f); abstract (apply Imonotonic; auto).\nDefined.\n\nLemma Imon_simpl : forall `{o1:ord Oa} `{o2:ord Ob} (f:Oa -m> Ob)(x:Oa),\n                   Imon f x = f x.\ntrivial.\nQed.\n\n(** *** Monotonicity and equality *)\n\nLemma mon_fun_eq_monotonic\n  : forall `{o1:ord Oa} `{o2:ord Ob} (f:Oa -> Ob) (g:Oa -m> Ob),\n            f == g -> monotonic f.\nred; intros.\nrewrite (H x); rewrite (H y); auto.\nQed.\n\nDefinition mon_fun_subst `{o1:ord Oa} `{o2:ord Ob} (f:Oa -> Ob) (g:Oa -m> Ob) (H:f == g)\n   : Oa -m> Ob := mon f (fmonotonic:= mon_fun_eq_monotonic _ _ H).\n\nLemma mon_fun_eq\n  : forall `{o1:ord Oa} `{o2:ord Ob} (f:Oa -> Ob) (g:Oa -m> Ob)\n            (H:f == g), g == mon_fun_subst f g H.\nintros; intro x; unfold mon_fun_subst.\nsymmetry; apply (H x).\nQed.\n\n(** *** Monotonic functions with 2 arguments *)\n\nClass monotonic2 `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc} (f:Oa -> Ob -> Oc) :=\n    monotonic2_intro : forall (x y:Oa) (z t:Ob), x <= y -> z <= t -> f x z <= f y t.\n\n\n#[export] Instance mon2_intro `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc} (f:Oa -> Ob -> Oc)\n    {m1:monotonic f} {m2: forall x, monotonic (f x)} : monotonic2 f | 10.\nred; intros.\ntransitivity (f y z).\napply (m1 x); trivial.\napply (m2 y); trivial.\nQed.\n\nLemma mon2_elim1 `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc} (f:Oa -> Ob -> Oc)\n    {m:monotonic2 f} : monotonic f.\nred; intros; intro z.\napply m; auto.\nQed.\n\nLemma mon2_elim2 `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc} (f:Oa -> Ob -> Oc)\n    {m:monotonic2 f} : forall x, monotonic (f x).\nred; intros.\napply m; auto.\nQed.\n#[export] Hint Immediate mon2_elim1 mon2_elim2: typeclass_instances.\n\nDefinition mon_comp {A} `{o1: ord Oa} `{o2: ord Ob}\n         (f:A -> Oa -> Ob) {mf:forall x, monotonic (f x)} : A -> Oa -m> Ob\n         := fun x => mon (f x).\n\n#[export] Instance mon_fun_mon `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc} (f:Oa -> Ob -> Oc)\n    {m:monotonic2 f} : monotonic (fun x => mon (f x)).\nred; intros; unfold mon_comp.\nintro z; apply m; auto.\nQed.\n\nClass stable2 `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc} (f:Oa -> Ob -> Oc) :=\n    stable2_intro : forall (x y:Oa) (z t:Ob), x==y -> z == t -> f x z == f y t.\n\n#[export] Instance monotonic2_stable2 `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc}\n    (f:Oa -> Ob -> Oc) {m:monotonic2 f} : stable2 f.\nred; intros; apply Ole_antisym; auto.\nQed.\n\n#[export] Typeclasses Opaque monotonic2 stable2.\n\nDefinition mon2 `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc} (f:Oa -> Ob -> Oc)\n     {mf:monotonic2 f} : Oa -m> Ob -m> Oc := mon (fun x => mon (f x)).\n\nLemma mon2_simpl : forall `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc} (f:Oa -> Ob -> Oc)\n     {mf:monotonic2 f} x y, mon2 f x y = f x y.\ntrivial.\nQed.\n#[export] Hint Resolve mon2_simpl : core.\n\nLemma mon2_le_compat :  forall `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc}\n     (f g:Oa -> Ob -> Oc) {mf: monotonic2 f} {mg:monotonic2 g},\n     f <= g -> mon2 f <= mon2 g.\nred; simpl; intros.\napply H; trivial.\nQed.\n\nDefinition fun2 `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc} (f:Oa -> Ob -m> Oc)\n     : Oa -> Ob -> Oc := fun x => f x.\n\n#[export] Instance fmon2_mon `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc} (f:Oa -> Ob -m> Oc) :\n       forall x:Oa, monotonic (fun2 f x).\nintros; unfold fun2; auto.\nQed.\n\n#[export] Instance fun2_monotonic `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc}\n         (f:Oa -> Ob -m> Oc) {mf:monotonic f} : monotonic (fun2 f).\nintros;unfold fun2; auto.\nQed.\n#[export] Hint Resolve fun2_monotonic : core.\n\n#[export] Instance fmonotonic2 `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} (f:Oa -m> Ob -m> Oc)\n         : monotonic2 (fun2 f).\nintros;unfold fun2;  apply mon2_intro; auto.\nred; intros.\napply (fmonotonic f x y); trivial .\nQed.\n#[export] Hint Resolve fmonotonic2 : core.\n\nDefinition mfun2 `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} (f:Oa -m> Ob -m> Oc)\n   : Oa-m> (Ob -> Oc) := mon (fun2 f).\n\nLemma mfun2_simpl : forall `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} (f:Oa -m> Ob -m> Oc) x y,\n     mfun2 f x y = f x y.\ntrivial.\nQed.\n\n#[export] Instance mfun2_mon `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc}\n         (f:Oa -m> Ob -m> Oc) x : monotonic (mfun2 f x).\nred; simpl; unfold fun2; intros; auto.\nQed.\n\nLemma mon2_fun2 : forall `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc}\n     (f:Oa -m> Ob -m> Oc), mon2 (fun2 f) == f.\nintros; unfold fun2,mon2; intros x y; auto.\nQed.\n\nLemma fun2_mon2 : forall `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc}\n      (f:Oa -> Ob -> Oc) {mf:monotonic2 f} , fun2 (mon2 f) == f.\nintros; unfold fun2,mon2; intros x y; auto.\nQed.\n#[export] Hint Resolve mon2_fun2 fun2_mon2 : core.\n\n#[export] Instance fstable2 `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} (f:Oa -m> Ob -m> Oc)\n                : stable2 (fun2 f).\nintros; apply monotonic2_stable2; auto.\nQed.\n#[export] Hint Resolve fstable2 : core.\n\nDefinition Imon2 : forall `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc},\n     (Oa -m> Ob -m> Oc) -> (Oa --m> Ob --m-> Oc).\nintros  Oa o1 Ob o2 Oc o3 f.\nexists (fun (x:Oa) => Imon (f x));\nabstract (red; simpl; intros; apply (fmonotonic f); auto).\nDefined.\n\nLemma Imon2_simpl : forall `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc}\n      (f:Oa -m> Ob -m> Oc) (x:Oa) (y: Ob),\n      Imon2 f x y = f x y.\ntrivial.\nQed.\n\nLemma Imonotonic2 `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc}\n      (f:Oa -> Ob -> Oc){mf : monotonic2 f}\n      : monotonic2 (o1:=Iord Oa) (o2:=Iord Ob) (o3:=Iord Oc) f.\nred; simpl; intros; auto.\nQed.\n\n#[export] Hint Extern 2 (@monotonic2 _ (Iord _) _ (Iord _) _ (Iord _)  _) => apply @Imonotonic2\n  : typeclass_instances.\n\nDefinition imon2 `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc}\n      (f:Oa -> Ob -> Oc){mf : monotonic2 f} : Oa --m> Ob --m-> Oc :=\n      mon2 (o1:=Iord Oa) (o2:=Iord Ob) (o3:=Iord Oc) f.\n\nLemma imon2_simpl : forall `{o1: ord Oa} `{o2: ord Ob} `{o3:ord Oc}\n      (f:Oa -> Ob -> Oc){mf : monotonic2 f} (x:Oa) (y:Ob),\n      imon2 f x y = f x y.\ntrivial.\nQed.\n\n(** *** Strict monotonicity *)\n\nLemma inj_strict_mon : forall `{o1: ord Oa} `{o2: ord Ob} (f:Oa -> Ob) {mf:monotonic f},\n      (forall x y, f x == f y -> x == y) -> forall x y, x < y -> f x < f y.\nintros Oa o1 Ob o2 f mf Hinj x y (Hle,Hne); split; auto.\nQed.\n\n\n(** ** Sequences *)\n(** *** Usual order on natural numbers *)\n\n#[export] Program Instance natO : ord nat :=\n    { Oeq := fun n m : nat => n = m;\n       Ole := fun n m : nat => (n <= m)%nat}.\nNext Obligation.\nabstract (apply Build_Order; intros; try lia; auto with arith;\n          red; intros; apply le_trans with y; auto).\nDefined.\n\nLemma le_Ole : forall n m, ((n <= m)%nat)-> n <= m.\nsimpl; auto.\nQed.\n#[export] Hint Resolve le_Ole : core.\n\nLemma nat_monotonic : forall {O} {o:ord O}\n               (f:nat -> O), (forall n, f n <= f (S n)) -> monotonic f.\nred; simpl; intros.\nelim H0; intros; auto.\ntransitivity (f m); trivial.\nQed.\n#[export] Hint Resolve nat_monotonic : core.\n\nLemma nat_monotonic_inv : forall {O} {o:ord O}\n               (f:nat -> O), (forall n, f (S n) <= f n) -> monotonic (o2:=Iord O) f.\nred; simpl; intros.\nelim H0; intros; auto.\ntransitivity (f m); trivial.\nQed.\n#[export] Hint Resolve nat_monotonic_inv : core.\n\nDefinition fnatO_intro : forall {O} {o:ord O} (f:nat -> O), (forall n, f n <= f (S n)) -> nat -m> O.\nintros; exists f; abstract auto.\nDefined.\n\n\nLemma fnatO_elim : forall {O} {o:ord O} (f:nat -m> O) (n:nat), f n <= f (S n).\nintros; apply (fmonotonic f); simpl; auto with arith.\nQed.\n#[export] Hint Resolve fnatO_elim : core.\n\n\n(** - (mseq_lift_left f n) k = f (n+k) *)\n\nDefinition seq_lift_left {O} (f:nat -> O) n := fun k => f (n+k)%nat.\n\n(* d'où venait le n avant que je le mette en forall?? *)\n#[export] Instance mon_seq_lift_left\n  : forall n {O} {o:ord O} (f:nat -> O) {m:monotonic f}, monotonic (seq_lift_left f n).\nred; intros; apply m ; simpl; auto with arith.\nQed.\n\nDefinition mseq_lift_left : forall {O} {o:ord O} (f:nat -m> O) (n:nat), nat -m> O.\nintros; exists (fun k => f (n+k)%nat).\nabstract (red; intros; apply (fmonotonic f); simpl; auto with arith).\nDefined.\n\nLemma mseq_lift_left_simpl : forall {O} {o:ord O} (f:nat -m> O) (n k:nat),\n    mseq_lift_left f n  k = f (n+k)%nat.\ntrivial.\nQed.\n\nLemma mseq_lift_left_le_compat : forall {O} {o:ord O} (f g:nat -m> O) (n:nat),\n             f <= g -> mseq_lift_left f n <= mseq_lift_left g n.\nintros; intro; simpl; auto.\nQed.\n#[export] Hint Resolve mseq_lift_left_le_compat : core.\n\nAdd Parametric Morphism {O} {o:ord O} : (@mseq_lift_left _ o)\n  with signature Oeq  ==> eq ==> Oeq\n  as mseq_lift_left_eq_compat.\nintros; apply Ole_antisym; auto.\nQed.\n#[export] Hint Resolve mseq_lift_left_eq_compat : core.\n\nAdd Parametric Morphism {O} {o:ord O}: (@seq_lift_left O)\n  with signature Oeq  ==> eq ==> Oeq\n  as seq_lift_left_eq_compat.\nsimpl; intros; intro.\nsimpl; apply H; auto.\nQed.\n#[export] Hint Resolve seq_lift_left_eq_compat : core.\n\n\n(** - (mseq_lift_right f n) k = f (k+n) *)\n\nDefinition seq_lift_right {O} (f:nat -> O) n := fun k => f (k+n)%nat.\n\n#[export] Instance mon_seq_lift_right\n   : forall n {O} {o:ord O} (f:nat -> O) {m:monotonic f}, monotonic (seq_lift_right f n).\nred; intros; apply m ; simpl; auto with arith.\nQed.\n\nDefinition mseq_lift_right : forall {O} {o:ord O} (f:nat -m> O) (n:nat), nat -m> O.\nintros; exists (fun k => f (k+n)%nat).\nabstract (red; intros; apply (fmonotonic f); simpl; auto with arith).\nDefined.\n\nLemma mseq_lift_right_simpl : forall {O} {o:ord O} (f:nat -m> O) (n k:nat),\n    mseq_lift_right f n  k = f (k+n)%nat.\ntrivial.\nQed.\n\nLemma mseq_lift_right_le_compat : forall {O} {o:ord O} (f g:nat -m> O) (n:nat),\n             f <= g -> mseq_lift_right f n <= mseq_lift_right g n.\nintros; intro; simpl; auto.\nQed.\n#[export] Hint Resolve mseq_lift_right_le_compat : core.\n\nAdd Parametric Morphism {O} {o:ord O} : (mseq_lift_right (o:=o))\n   with signature Oeq ==> eq ==> Oeq\n   as mseq_lift_right_eq_compat.\nintros; apply Ole_antisym; auto.\nQed.\n\nAdd Parametric Morphism {O} {o:ord O}: (@seq_lift_right O)\n  with signature Oeq  ==> eq ==> Oeq\n  as seq_lift_right_eq_compat.\nsimpl; intros; intro.\nsimpl; apply H; auto.\nQed.\n#[export] Hint Resolve seq_lift_right_eq_compat : core.\n\nLemma mseq_lift_right_left : forall {O} {o:ord O} (f:nat -m> O) n,\n       mseq_lift_left f n  == mseq_lift_right f n.\nunfold mseq_lift_left,mseq_lift_right; intros.\nintro x.\nunfold fmont; replace (n+x)%nat with (x+n)%nat; auto with arith.\nQed.\n\n(** *** Monotonicity and functions *)\n(** -  (shift f x) n = f n x *)\n\n#[export] Instance shift_mon_fun {A} `{o1:ord Oa} `{o2:ord Ob} (f:Oa -m> (A -> Ob)) :\n       forall x:A, monotonic (fun (y:Oa) => f y x).\nred; intros; apply (fmonotonic f); auto.\nQed.\n\nDefinition shift {A} `{o1:ord Oa} `{o2:ord Ob} (f:Oa -m> (A -> Ob)) : A -> Oa -m> Ob\n   := fun x => (mon (fun y => f y x)).\n\n(** printing <o> %\\ensuremath{\\diamond}% # &loz;# *)\nInfix \"<o>\" := shift (at level 30, no associativity) : O_scope.\n\nLemma shift_simpl : forall {A} `{o1:ord Oa} `{o2:ord Ob} (f:Oa -m> (A -> Ob)) x y,\n      (f <o> x) y = f y x.\ntrivial.\nQed.\n\nLemma shift_le_compat : forall {A} `{o1:ord Oa} `{o2:ord Ob} (f g:Oa -m> (A -> Ob)),\n             f <= g -> shift f <= shift g.\nintros; intros x y.\nrepeat rewrite shift_simpl.\napply (H y x); trivial.\nQed.\n#[export] Hint Resolve shift_le_compat : core.\n\nAdd Parametric Morphism {A} `{o1:ord Oa} `{o2:ord Ob}\n    : (shift (A:=A) (Oa:=Oa) (Ob:=Ob)) with signature Oeq ==> eq ==> Oeq\nas shift_eq_compat.\nintros f g H x y.\nrepeat rewrite shift_simpl; auto.\nQed.\n\n#[export] Instance ishift_mon {A} `{o1:ord Oa} `{o2:ord Ob} (f:A -> (Oa -m> Ob)) :\n       monotonic (fun (y:Oa) (x:A) => f x y).\nred; intros; intro z.\napply (fmonotonic (f z)); auto.\nQed.\n\nDefinition ishift {A} `{o1:ord Oa} `{o2:ord Ob} (f:A -> (Oa -m> Ob)) : Oa -m> (A -> Ob)\n   := mon (fun (y:Oa) (x:A) => f x y) (fmonotonic:=ishift_mon f).\n\nLemma ishift_simpl : forall {A} `{o1:ord Oa} `{o2:ord Ob} (f:A -> (Oa -m> Ob)) x y,\n      ishift f x y = f y x.\ntrivial.\nQed.\n\nLemma ishift_le_compat : forall {A} `{o1:ord Oa} `{o2:ord Ob} (f g:A -> (Oa -m> Ob)),\n             f <= g -> ishift f <= ishift g.\nintros; intros x y.\nrepeat rewrite ishift_simpl.\napply (H y x); trivial.\nQed.\n#[export] Hint Resolve ishift_le_compat : core.\n\nAdd Parametric Morphism {A} `{o1:ord Oa} `{o2:ord Ob}\n    : (ishift (A:=A) (Oa:=Oa) (Ob:=Ob)) with signature Oeq ==> eq ==> Oeq\nas ishift_eq_compat.\nintros f g H x y.\nrepeat rewrite ishift_simpl.\napply H.\nQed.\n\n(*\n#[export] Instance shift_mon_mon `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} (f:Oa -m> (Ob -m> Oc))\n     {mf:forall x, monotonic (f x)}, monotonic (f <o> x).\nred; unfold shift; intros; apply m; trivial.\nDefined.\n*)\n\n#[export] Instance shift_fun_mon `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} (f:Oa -m> (Ob -> Oc))\n     {m:forall x, monotonic (f x)} : monotonic (shift f).\nintros x y H z.\nrepeat (rewrite shift_simpl); apply m; trivial.\nQed.\n\n#[export] Instance shift_mon2 `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} (f:Oa -m> Ob -m> Oc)\n     : monotonic2 (fun x y => f y x).\napply mon2_intro.\nintros x y H z; auto.\nintros x z t H; apply (fmonotonic f); trivial.\nQed.\n#[export] Hint Resolve shift_mon_fun shift_fun_mon shift_mon2 : core.\n\nDefinition mshift `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} (f:Oa -m> Ob -m> Oc)\n    : Ob -m> Oa -m> Oc := mon2 (fun x y => f y x).\n\n(** - id c = c *)\n\nDefinition id O {o:ord O} : O -> O := fun x => x.\n\n#[export] Instance mon_id : forall {O:Type} {o:ord O}, monotonic (id O).\nauto.\nQed.\n\n\n(**  - (cte c) n = c *)\n\nDefinition cte A  `{o1:ord Oa} (c:Oa) : A -> Oa := fun x => c.\n\n#[export] Instance mon_cte : forall `{o1:ord Oa} `{o2:ord Ob} (c:Ob), monotonic (cte Oa c).\nauto.\nQed.\n\nDefinition mseq_cte {O} {o:ord O} (c:O) : nat -m> O := mon (cte nat c).\n\nAdd Parametric Morphism `{o1:ord Oa} `{o2:ord Ob} : (@cte Oa  Ob _)\n  with signature Ole  ==>  Ole as cte_le_compat.\nintros c1 c2 H x; simpl; auto.\nQed.\n\nAdd Parametric Morphism `{o1:ord Oa} `{o2:ord Ob} : (@cte Oa  Ob _)\n  with signature Oeq  ==>  Oeq as cte_eq_compat.\nintros c1 c2 H x; simpl; auto.\nQed.\n\n#[export] Instance mon_diag `{o1:ord Oa} `{o2:ord Ob}(f:Oa -m> (Oa -m> Ob))\n     : monotonic (fun x => f x x).\nintros x y H; apply (fmonotonic2 f); auto.\nQed.\n#[export] Hint Resolve mon_diag : core.\n\nDefinition diag `{o1:ord Oa} `{o2:ord Ob}(f:Oa -m> (Oa -m> Ob)) : Oa-m> Ob\n     := mon (fun x => f x x).\n\nLemma fmon_diag_simpl : forall `{o1:ord Oa} `{o2:ord Ob} (f:Oa -m> (Oa -m> Ob)) (x:Oa),\n             diag f x = f x x.\ntrivial.\nQed.\n\nLemma diag_le_compat :  forall `{o1:ord Oa} `{o2:ord Ob} (f g:Oa -m> (Oa -m> Ob)),\n             f <= g -> diag f <= diag g.\nintros; intro; simpl; auto.\napply H.\nQed.\n#[export] Hint Resolve diag_le_compat : core.\n\n\nAdd Parametric Morphism `{o1:ord Oa} `{o2:ord Ob} : (diag (Oa:=Oa) (Ob:=Ob))\n   with signature Oeq ==> Oeq as diag_eq_compat.\nintros; intro; simpl; auto.\napply H.\nQed.\n\nLemma diag_shift : forall `{o1:ord Oa} `{o2:ord Ob} (f: Oa -m> Oa -m> Ob),\n                   diag f == diag (mshift f).\nintros; intro x; unfold mshift,diag; auto.\nQed.\n\n#[export] Hint Resolve diag_shift : core.\n\nLemma mshift_simpl : forall `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc}\n      (h:Oa -m> Ob -m>  Oc) (x : Ob) (y:Oa), mshift h x y = h y x.\ntrivial.\nQed.\n\nLemma mshift_le_compat :  forall `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc}\n      (f g:Oa -m>  Ob -m>  Oc), f <= g -> mshift f <= mshift g.\nintros; intros x y; simpl; unfold mshift; intros.\napply H; auto.\nQed.\n#[export] Hint Resolve mshift_le_compat : core.\n\nAdd Parametric Morphism `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} : (@mshift Oa _ Ob _ Oc _)\n     with signature Oeq  ==> Oeq as mshift_eq_compat.\nintros f g H x y; simpl; unfold mshift; intros.\napply H; auto.\nQed.\n\nLemma mshift2_eq :  forall `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} (h : Oa -m> Ob -m>  Oc),\n             mshift (mshift h) == h.\nintros; intros x y; unfold mshift; auto.\nQed.\n\n(** - (f@g) x = f (g x) *)\n\n#[export] Instance monotonic_comp `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc}\n   (f:Ob -> Oc){mf : monotonic f} (g:Oa -> Ob){mg:monotonic g} : monotonic (fun x => f (g x)).\nintros x y H; auto.\nQed.\n#[export] Hint Resolve monotonic_comp : core.\n\n#[export] Instance monotonic_comp_mon `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc}\n   (f:Ob -m> Oc)(g:Oa -m> Ob) : monotonic (fun x => f (g x)).\nintros x y H; auto.\nQed.\n#[export] Hint Resolve monotonic_comp_mon : core.\n\nDefinition comp `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} (f:Ob -m> Oc) (g:Oa -m> Ob)\n       : Oa -m> Oc := mon (fun x => f (g x)).\n\nInfix \"@\" := comp (at level 35) : O_scope.\n\nLemma comp_simpl : forall `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc}\n      (f:Ob -m> Oc) (g:Oa -m> Ob) (x:Oa), (f@g) x = f (g x).\ntrivial.\nQed.\n\nAdd Parametric Morphism `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc}: (@comp Oa _ Ob _ Oc _)\n    with signature Ole ++> Ole  ++> Ole\n    as comp_le_compat.\nintros f1 f2 H g1 g2 H1 x; unfold comp; simpl; auto.\ntransitivity (f2 (g1 x)); auto.\nQed.\n\n#[export] Hint Immediate comp_le_compat : core.\n\nAdd Parametric Morphism `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} : (@comp Oa _ Ob _ Oc _)\n    with signature Oeq ==> Oeq ==> Oeq\n    as comp_eq_compat.\nintros f1 f2 H g1 g2 H1 x.\nrepeat (rewrite comp_simpl); transitivity (f2 (g1 x)); auto.\nQed.\n\n#[export] Hint Immediate comp_eq_compat : core.\n\n\n(** - (f@2 g) h x = f (g x) (h x) *)\n\n#[export] Instance mon_app2 `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} `{o4:ord Od}\n      (f:Ob -> Oc -> Od) (g:Oa -> Ob) (h:Oa -> Oc)\n      {mf:monotonic2 f}{mg:monotonic g} {mh:monotonic h}\n      : monotonic (fun x => f (g x) (h x)).\nintros x y H; auto.\nQed.\n\n#[export] Instance mon_app2_mon `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} `{o4:ord Od}\n      (f:Ob -m> Oc -m> Od) (g:Oa -m> Ob) (h:Oa -m> Oc)\n      : monotonic (fun x => f (g x) (h x)).\nintros x y H.\napply (fmonotonic2 f); auto.\nQed.\n\nDefinition app2 `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} `{o4:ord Od}\n        (f:Ob -m> Oc -m> Od) (g:Oa -m> Ob) (h:Oa -m> Oc) : Oa -m> Od\n        := mon (fun x => f (g x) (h x)).\n\n(** printing @2 %\\ensuremath{@^2}% #@&sup2;#*)\nInfix \"@2\" := app2 (at level 70) : O_scope.\n\nAdd Parametric Morphism `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} `{o4:ord Od}:\n        (@app2 Oa _ Ob _ Oc _ Od _)\n    with signature Ole ++> Ole  ++> Ole ++> Ole\n    as app2_le_compat.\nintros f1 f2 H g1 g2 H1 h1 h2 H2 x; unfold app2; simpl; auto.\ntransitivity (f2 (g1 x) (h1 x)).\napply H.\napply (fmonotonic2 f2); auto.\nQed.\n\n#[export] Hint Immediate app2_le_compat : core.\n\nAdd Parametric Morphism `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} `{o4:ord Od}:\n        (@app2 Oa _ Ob _ Oc _ Od _)\n    with signature Oeq ==> Oeq  ==> Oeq ==> Oeq\n    as app2_eq_compat.\nintros f1 f2 H g1 g2 H1 h1 h2 H2 x; unfold app2; simpl; auto.\ntransitivity (f2 (g1 x) (h1 x)).\napply H.\napply (fstable2 f2); auto.\nQed.\n\n#[export] Hint Immediate app2_eq_compat : core.\n\n\nLemma app2_simpl :\n    forall `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} `{o4:ord Od}\n            (f:Ob -m> Oc -m> Od) (g:Oa -m> Ob) (h:Oa -m> Oc) (x:Oa),\n    (f@2 g) h x = f (g x) (h x).\ntrivial.\nQed.\n\n\nLemma comp_monotonic_right :\n      forall `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} (f: Ob -m> Oc) (g1 g2:Oa -m> Ob),\n               g1<= g2 -> f @ g1 <= f @ g2.\nauto.\nQed.\n#[export] Hint Resolve comp_monotonic_right : core.\n\nLemma comp_monotonic_left :\n      forall `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} (f1 f2: Ob -m> Oc) (g:Oa -m> Ob),\n               f1<= f2 -> f1 @ g <= f2 @ g.\nauto.\nQed.\n#[export] Hint Resolve comp_monotonic_left : core.\n\n#[export] Instance comp_monotonic2 : forall `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc},\n             monotonic2 (@comp Oa _ Ob _ Oc _).\nred; intros.\napply comp_le_compat; auto.\nQed.\n#[export] Hint Resolve comp_monotonic2 : core.\n\nDefinition fcomp `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} :\n   (Ob -m> Oc) -m> (Oa -m> Ob) -m> (Oa -m> Oc) := mon2 (@comp Oa _ Ob _ Oc _).\n\nArguments fcomp Oa [o1] Ob [o2] Oc {o3}.\n\nLemma fcomp_simpl : forall `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc}\n      (f:Ob -m> Oc) (g:Oa -m> Ob), fcomp _ _ _ f g = f@g.\ntrivial.\nQed.\n\n\nDefinition fcomp2  `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} `{o4:ord Od} :\n        (Oc -m> Od) -m> (Oa -m> Ob -m> Oc) -m> (Oa -m> Ob -m> Od):=\n        (fcomp Oa (Ob -m> Oc) (Ob -m> Od))@(fcomp Ob Oc Od).\n\n\nArguments fcomp2 Oa [o1] Ob [o2] Oc [o3] Od {o4}.\n\nLemma fcomp2_simpl : forall `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} `{o4:ord Od}\n      (f:Oc -m> Od) (g:Oa -m> Ob -m> Oc) (x:Oa)(y:Ob), fcomp2 _ _ _ _ f g x y = f (g x y).\ntrivial.\nQed.\n\nLemma fmon_le_compat2 : forall `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc}\n      (f: Oa -m> Ob -m> Oc) (x y:Oa) (z t:Ob), x<=y -> z <=t -> f x z <= f y t.\nintros; transitivity (f x t).\napply (fmonotonic (f x)); auto.\napply (fmonotonic f); auto.\nQed.\n#[export] Hint Resolve fmon_le_compat2 : core.\n\nLemma fmon_cte_comp : forall `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc}\n      (c:Oc)(f:Oa -m> Ob), (mon (cte Ob c)) @ f == mon (cte Oa c).\nintros; intro x; auto.\nQed.\n\n(** ** Abstract relational notion of lubs *)\nRecord islub O (o:ord O) I (f:I -> O) (x:O) : Prop := mk_islub\n     { le_islub : forall i,  f i <= x;\n       islub_le : forall y, (forall  i,  f i <= y) -> x <= y}.\nArguments islub [O o I] f x.\nArguments le_islub [O o I f x].\nArguments islub_le [O o I f x].\n\nDefinition isglb O (o:ord O) I (f:I -> O) (x:O) : Prop\n     := islub (o:=Iord O) f x.\nArguments isglb [O o I].\n\nLemma le_isglb O (o:ord O) I (f:I -> O) (x:O) :\n         isglb f x -> forall i,  x <= f i.\nintros; exact (le_islub H i).\nQed.\n\nLemma isglb_le O (o:ord O) I (f:I -> O) (x:O) :\n         isglb f x -> forall y, (forall i,  y <= f i) -> y <= x.\nintros; exact (islub_le H y H0).\nQed.\nArguments le_isglb [O o I f x].\nArguments isglb_le [O o I f x].\n\nLemma mk_isglb O (o:ord O) I (f:I -> O) (x:O) :\n      (forall i,  x <= f i) -> (forall y, (forall i,  y <= f i) -> y <= x)\n      -> isglb f x.\nred; intros; apply mk_islub; auto.\nQed.\n\nLemma islub_eq_compat O (o:ord O) I (f g:I -> O) (x y:O):\n      f==g -> x == y -> islub f x -> islub g y.\nintros; destruct H1; split; intros; rewrite <- H0.\nrewrite <- (H i); auto.\napply islub_le0; intros.\nrewrite (H i); auto.\nQed.\n\nLemma islub_eq_compat_left O (o:ord O) I (f g:I -> O) (x:O):\n      f==g -> islub f x -> islub g x.\nintros; apply islub_eq_compat with f x; auto.\nQed.\n\nLemma islub_eq_compat_right O (o:ord O) I (f:I -> O) (x y:O):\n       x == y -> islub f x -> islub f y.\nintros; apply islub_eq_compat with f x; auto.\nQed.\n\nLemma isglb_eq_compat O (o:ord O) I (f g:I -> O) (x y:O):\n      f==g -> x == y -> isglb f x -> isglb g y.\nintros.\napply (islub_eq_compat O (Iord O)) with f x; auto.\nQed.\n\nLemma isglb_eq_compat_left O (o:ord O) I (f g:I -> O) (x:O):\n      f==g -> isglb f x -> isglb g x.\nintros; apply isglb_eq_compat with f x; auto.\nQed.\n\nLemma isglb_eq_compat_right O (o:ord O) I (f:I -> O) (x y:O):\n       x == y -> isglb f x -> isglb f y.\nintros; apply isglb_eq_compat with f x; auto.\nQed.\n\nAdd Parametric Morphism {O} {o:ord O} I : (@islub _ o I)\nwith signature Oeq ==> Oeq ==> iff\nas islub_morphism.\nsplit; eapply islub_eq_compat; auto.\nQed.\n\nAdd Parametric Morphism {O} {o:ord O} I : (@isglb _ o I)\nwith signature Oeq ==> Oeq ==> iff\nas isglb_morphism.\nsplit; eapply isglb_eq_compat; auto.\nQed.\n\nAdd Parametric Morphism {O} {o:ord O} I : (@islub _ o I)\nwith signature (@pointwise_relation I O (@Oeq _ _)) ==> Oeq ==> iff\nas islub_morphism_ext.\nsplit; eapply islub_eq_compat; auto.\nQed.\n\nAdd Parametric Morphism {O} {o:ord O} I : (@isglb _ o I)\nwith signature (@pointwise_relation I O (@Oeq _ _)) ==> Oeq ==> iff\nas isglb_morphism_ext.\nsplit; eapply isglb_eq_compat; auto.\nQed.\n\nLemma islub_incr_ext {O} {o:ord O} (f :nat -> O) (x:O) (n:nat):\n      (forall k, f k <= f (S k)) -> islub f x -> islub (fun k => f (n + k)) x.\nintros HS (H1,H2); split; auto with arith; intros.\napply H2; intros; transitivity (f (n+i)); auto with arith.\nelim n; simpl; auto; intros.\ntransitivity (f (n0 + i)); auto.\nQed.\n\nLemma islub_incr_lift {O} {o:ord O} (f :nat -> O) (x:O) (n:nat):\n      (forall k, f k <= f (S k)) -> islub (fun k => f (n + k)) x -> islub f x.\nintros HS (H1,H2); split; auto with arith; intros.\ntransitivity (f (n+i)); auto with arith.\nelim n; simpl; auto; intros.\ntransitivity (f (n0 + i)); auto.\nQed.\n\nLemma isglb_decr_ext {O} {o:ord O} (f :nat -> O) (x:O) (n:nat):\n      (forall k, f (S k) <= f k) -> isglb f x -> isglb (fun k => f (n + k)) x.\nintros HS (H1,H2); split; auto with arith; intros.\napply H2; intros; transitivity (f (n+i)); auto with arith.\nelim n; simpl; auto; intros.\ntransitivity (f (n0 + i)); auto.\nQed.\n\nLemma isglb_decr_lift {O} {o:ord O} (f :nat -> O) (x:O) (n:nat):\n      (forall k, f (S k) <= f k) -> isglb (fun k => f (n + k)) x -> isglb f x.\nintros HS (H1,H2); split; auto with arith; intros.\ntransitivity (f (n+i)); auto with arith.\nelim n; simpl; auto; intros.\ntransitivity (f (n0 + i)); auto.\nQed.\n\n#[export] Hint Resolve islub_incr_ext isglb_decr_ext : core.\n\nLemma islub_exch {O} {o:ord O} (F :nat -> nat -> O) (f g : nat -> O)(x:O) :\n      (forall m, islub (fun n => F n m) (f m))\n       -> (forall n, islub (F n) (g n)) -> islub f x -> islub g x.\nintros Lf Lg (Lx1,Lx2); split; intros.\napply (islub_le (Lg i)); intros.\ntransitivity (f i0); auto.\napply (le_islub (Lf i0) i); auto.\napply Lx2; intros.\napply (islub_le (Lf i)); intros.\ntransitivity (g i0); auto.\napply (le_islub (Lg i0) i); auto.\nQed.\n\nLemma islub_decr {O} {o:ord O} {I} (f g : I -> O) (x y : O) :\n      (f <= g) -> islub f x -> islub g y -> x <= y.\nintros H (Hf1,Hf2) (Hg1,Hg2).\napply Hf2; intros.\ntransitivity (g i); auto.\nQed.\n\nLemma islub_unique_eq {O} {o:ord O} {I} (f g : I -> O) (x y : O) :\n      (f == g) -> islub f x -> islub g y -> x == y.\nintros; apply Ole_antisym.\napply islub_decr with f g; auto.\napply islub_decr with g f; auto.\nQed.\n\nLemma islub_unique {O} {o:ord O} {I} (f : I -> O) (x y : O) :\n           islub f x -> islub f y -> x == y.\nintros; apply islub_unique_eq with f f; auto.\nQed.\n\nLemma islub_fun_intro O (o:ord O) {I A} (F : I -> A -> O) (f : A -> O) :\n           (forall x, islub (fun i => F i x) (f x)) -> islub F f.\nsplit; intros; intro x.\napply (H x); auto.\napply (H x); auto.\nQed.\n\n(** ** Basic operators of omega-cpos *)\n(** - Constant : [0]\n     - lub : limit of monotonic sequences\n*)\n\nGeneralizable Variables D.\n\n(** *** Definition of cpos *)\nClass cpo  `{o:ord D} : Type := mk_cpo\n  {D0 : D; lub: forall (f:nat -m> D), D;\n   Dbot : forall x:D, D0 <= x;\n   le_lub : forall (f : nat -m> D) (n:nat), f n <= lub f;\n   lub_le : forall (f : nat -m> D) (x:D), (forall n, f n <= x) -> lub f <= x}.\n\nArguments cpo D {o}.\n\nNotation \"0\" := D0 : O_scope.\n\n#[export] Hint Resolve Dbot le_lub lub_le : core.\n\nDefinition mon_ord_equiv : forall `{o:ord D1} `{o1:ord D2} {o2:ord D2},\n      eq_ord o1 o2 -> fmon D1 D2 (o2:=o2) -> fmon D1 D2 (o2:=o1).\nunfold eq_ord, eq_rel; intros D1 o D2 o1 o2 H f; exists (fun x => f x).\nabstract (red; intros; rewrite H; apply (fmonotonic f); auto).\nDefined.\n\nLemma mon_ord_equiv_simpl : forall `{o:ord D1} `{o1:ord D2} {o2:ord D2}\n      (H:eq_ord o1 o2) (f:fmon D1 D2 (o2:=o2)) (x:D1),\n      mon_ord_equiv H f x = f x.\ntrivial.\nQed.\n\nDefinition cpo_ord_equiv `{o1:ord D} (o2:ord D)\n       : eq_ord o1 o2 -> cpo (o:=o1) D -> cpo (o:=o2) D.\nunfold eq_ord, eq_rel; intros H c.\nexists (D0 (cpo:=c)) (fun f : nat -m> D => lub (cpo:=c) (mon_ord_equiv H f)).\nabstract (intros; rewrite <- H; auto).\nabstract (intros; rewrite <- H; apply (le_lub (mon_ord_equiv H f) n)).\nabstract (intros; rewrite <- H; apply lub_le; intros; simpl; rewrite H; auto).\nDefined.\n\n(** *** Least upper bounds *)\n\nAdd Parametric Morphism `{c:cpo D} : (lub (cpo:=c))\n             with signature Ole ++> Ole as lub_le_compat.\nintros f g H; apply lub_le; intros.\ntransitivity (g n); auto.\nQed.\n#[export] Hint Resolve lub_le_compat : core.\n\nAdd Parametric Morphism `{c:cpo D}: (lub (cpo:=c))\n      with signature Oeq ==> Oeq as lub_eq_compat.\nintros; apply Ole_antisym; auto.\nQed.\n#[export] Hint Resolve lub_eq_compat : core.\n\n\nNotation \"'mlub' f\" := (lub (mon f)) (at level 60) : O_scope .\n\nLemma mlub_le_compat : forall `{c:cpo D} (f g:nat -> D) {mf:monotonic f} {mg:monotonic g},\n                f <= g -> mlub f <= mlub g.\nauto.\nQed.\n#[export] Hint Resolve mlub_le_compat : core.\n\nLemma mlub_eq_compat : forall `{c:cpo D} (f g:nat -> D) {mf:monotonic f} {mg:monotonic g},\n                f == g -> mlub f == mlub g.\nauto.\nQed.\n#[export] Hint Resolve mlub_eq_compat : core.\n\nLemma   le_mlub : forall `{c:cpo D} (f:nat -> D) {m:monotonic f} (n:nat), f n <= mlub f.\nintros; apply (le_lub (mon f)); auto.\nQed.\n\nLemma   mlub_le : forall `{c:cpo D}(f:nat -> D) {m:monotonic f}(x:D), (forall n, f n <= x) -> mlub f <= x.\nintros; auto.\nQed.\n#[export] Hint Resolve le_mlub mlub_le : core.\n\nLemma islub_mlub : forall `{c:cpo D}(f:nat -> D) {m:monotonic f},\n            islub f (mlub f).\nsplit; auto.\nQed.\n\nLemma islub_lub : forall `{c:cpo D}(f:nat -m> D),\n            islub f (lub f).\nsplit; auto.\nQed.\n\n#[export] Hint Resolve islub_mlub islub_lub : core.\n\n#[export] Instance lub_mon `{c:cpo D} : monotonic lub.\nintros; exact (lub_le_compat D o c).\nQed.\n\nDefinition Lub `{c:cpo D} : (nat -m> D) -m> D := mon lub.\n\n#[export] Instance monotonic_lub_comp {O} {o:ord O} `{c:cpo D} (f:O -> nat -> D){mf:monotonic2 f}:\n         monotonic (fun x => mlub (f x)).\nintros; auto.\nQed.\n\nLemma lub_cte : forall `{c:cpo D} (d:D), mlub (cte nat d) == d.\nintros; apply Ole_antisym; auto.\napply le_lub with (f:=mon (fun _ => d)) (n:=O); auto.\nQed.\n\n#[export] Hint Resolve lub_cte : core.\n\nLemma mlub_lift_right : forall `{c:cpo D} (f:nat -m> D) n,\n      lub f == mlub (seq_lift_right f n).\nintros; apply Ole_antisym.\napply lub_le_compat; intro.\nunfold seq_lift_right; simpl; auto with arith.\nunfold seq_lift_right; simpl; auto.\nQed.\n#[export] Hint Resolve mlub_lift_right : core.\n\nLemma mlub_lift_left : forall `{c:cpo D} (f:nat -m> D) n,\n      lub f == mlub (seq_lift_left f n).\nintros; apply Ole_antisym.\napply lub_le_compat; intro.\nunfold seq_lift_left; simpl; auto with arith.\nunfold seq_lift_left; auto.\nQed.\n#[export] Hint Resolve mlub_lift_left : core.\n\nLemma lub_lift_right : forall `{c:cpo D} (f:nat -m> D) n,\n      lub f == lub (mseq_lift_right f n).\nintros; transitivity (mlub (seq_lift_right f n)); auto.\napply lub_eq_compat; intro m; auto.\nQed.\n#[export] Hint Resolve lub_lift_right : core.\n\nLemma lub_lift_left : forall `{c:cpo D} (f:nat -m> D) n,\n      lub f == lub (mseq_lift_left f n).\nintros; transitivity (mlub (seq_lift_left f n)); auto.\napply lub_eq_compat; intro m; auto.\nQed.\n#[export] Hint Resolve lub_lift_left : core.\n\nLemma lub_le_lift : forall `{c:cpo D} (f g:nat -m> D)\n      (n:nat), (forall k, n <= k -> f k <= g k) -> lub f <= lub g.\nintros; apply lub_le; intros.\ntransitivity (f (n+n0)); auto with arith.\ntransitivity (g (n+n0)); auto with arith.\nQed.\n\nLemma lub_eq_lift : forall `{c:cpo D} (f g:nat -m> D) {m:monotonic f} {m':monotonic g}\n      (n:nat), (forall k, n <= k -> f k == g k) -> lub f == lub g.\nintros; apply Ole_antisym; apply lub_le_lift with n; intros; auto.\napply Oeq_le_sym; auto.\nQed.\n\nLemma lub_seq_eq : forall `{c:cpo D} (f:nat -> D) (g: nat-m> D) (H:f == g),\n      lub g == lub (mon_fun_subst f g H).\nintros.\napply lub_eq_compat.\napply (mon_fun_eq f g H).\nQed.\n\nLemma lub_Olt : forall `{c:cpo D} (f:nat -m> D) (k:D),\n      k < lub f -> ~ (forall n, f n <= k).\nred; intros.\napply (Ole_not_lt (lub f) k); auto.\nQed.\n\n(** - (lub_fun h) x = lub_n (h n x) *)\nDefinition lub_fun {A} `{c:cpo D} (h : nat -m> (A -> D)) : A -> D\n               := fun x => mlub (h <o> x).\n\n(*\n#[export] Instance lub_fun_mon  {O} {o:ord O} `{c:cpo D} (h : nat -m> (O -> D))\n       {m:forall x, monotonic (h x)} : monotonic (lub_fun h).\nred; unfold lub_fun; intros.\napply mlub_le_compat.\napply (shift_fun_mon h x y); trivial.\nQed.\n#[export] Hint Resolve lub_fun_mon : core.\n*)\n\n#[export] Instance lub_shift_mon  {O} {o:ord O} `{c:cpo D} (h : nat -m> (O -m> D))\n          : monotonic (fun (x:O) => lub (mshift h x)).\nred; auto.\nQed.\n#[export] Hint Resolve lub_shift_mon : core.\n\n\n(** *** Functional cpos *)\n\n#[export] Program Instance fcpo {A: Type} `(c:cpo D) : cpo (A -> D) :=\n  {D0 := fun x:A => (0:D); lub := fun f => lub_fun f}.\nNext Obligation. abstract (intros g; auto). Defined.\nNext Obligation.\nabstract (intros x; unfold lub_fun; apply (le_mlub  (shift f x) n); auto).\nDefined.\nNext Obligation.\nintros y; unfold lub_fun; apply mlub_le; intro n; rewrite shift_simpl; auto.\napply H.\nDefined.\n\n\nLemma fcpo_lub_simpl : forall {A} `{c:cpo D} (h:nat -m> (A -> D))(x:A),\n      (lub h) x = lub (h <o> x).\ntrivial.\nQed.\n\nLemma lub_ishift : forall {A} `{c:cpo D} (h:A -> (nat -m> D)),\n       lub (ishift h) == fun x => lub (h x).\nintros; intro x.\nrewrite fcpo_lub_simpl; apply lub_eq_compat; intro n; auto.\nQed.\n\n(** ** Cpo of monotonic functions *)\n\n\n#[export] Program Instance fmon_cpo {O} {o:ord O} `{c:cpo D} : cpo (O -m> D) :=\n  { D0  := mon (cte O (0:D));\n    lub := fun h:nat -m> (O -m> D) => mon (fun (x:O) => lub (cpo:=c) (mshift h x))}.\nNext Obligation. unfold cte; simpl; auto. Defined.\nNext Obligation. simpl; apply (le_mlub (fun y => f y x) n); auto. Defined.\n\nLemma fmon_lub_simpl : forall {O} {o:ord O} `{c:cpo D}\n      (h:nat -m> (O -m> D))(x:O), (lub h) x = lub (mshift h x).\ntrivial.\nQed.\n#[export] Hint Resolve fmon_lub_simpl : core.\n\n#[export] Instance mon_fun_lub : forall {O} {o:ord O} `{c:cpo D}\n         (h:nat -m> (O -> D)) {mh:forall n, monotonic (h n)}, monotonic (lub h).\nred; intros; simpl; auto.\nunfold lub_fun; apply mlub_le_compat.\napply (shift_fun_mon h x y); trivial.\nQed.\n\n(*\n#[export] Instance mon_lub : forall {O} {o:ord O} `{c:cpo D}\n         (h:nat -m> (O -m> D)), monotonic (mlub h).\nintros; simpl; auto.\nQed.\n*)\n\n(** Link between lubs on ordinary functions and monotonic functions **)\n\nLemma lub_mon_fcpo : forall {O} {o:ord O} `{c:cpo D} (h:nat -m> (O -m> D)),\n      lub h == mon (lub (mfun2 h)).\nintros; intros x.\nrewrite fmon_lub_simpl; rewrite mon_simpl; rewrite fcpo_lub_simpl.\napply lub_eq_compat; intro y; auto.\nQed.\n\nLemma lub_fcpo_mon : forall {O} {o:ord O} `{c:cpo D} (h:nat -m> (O -> D))\n     {mh:forall x, monotonic (h x)}, lub h == lub (mon2 h).\nintros; intro x.\nrewrite fmon_lub_simpl; rewrite fcpo_lub_simpl.\napply lub_eq_compat; intro y; auto.\nQed.\n\nLemma double_lub_diag : forall `{c:cpo D} (h : nat -m> nat -m>  D),\n        lub (lub h) == lub (diag h).\nintros; apply Ole_antisym.\napply lub_le; intros; simpl; apply lub_le; simpl; intros.\ntransitivity (h n0 (n+n0)); auto with arith.\ntransitivity (h (n+n0) (n+n0)).\napply (fmonotonic2 h); simpl; auto with arith.\napply (le_lub (diag h) (n + n0)%nat).\napply lub_le_compat.\nintro n; simpl; unfold diag.\napply (le_mlub (fun y => h y n) n); auto.\nQed.\n#[export] Hint Resolve double_lub_diag : core.\n\n\nLemma double_lub_shift : forall `{c:cpo D} (h : nat -m> nat -m>  D),\n        lub (lub h) == lub (lub (mshift h)).\nintros; transitivity (lub (diag h)); auto.\ntransitivity (lub (diag (mshift h))); auto.\nQed.\n#[export] Hint Resolve double_lub_shift : core.\n\n(*\n#[export] Instance mlub_monotonic `{c:cpo D} (h : nat -> nat ->  D) {m:monotonic2 h}:\n       monotonic (fun m => mlub (h m)).\nred; intros.\napply mlub_le_compat; intro z; auto.\nQed.\n\nLemma doubl_lub_simpl_exch : forall `{c:cpo D} (h : nat -m> nat -m>  D),\n        lub (lub h) == mlub (mon (fun n => mlub (h n))\n                                   (fmonotonic:=mlub_monotonic h)).\nintros.\napply Oeq_trans with (1:= diag h).\n\nQed.\n\n#[export] Instance mlub_shift_monotonic `{c:cpo D} (h : nat -> nat ->  D) {m:monotonic2 h}:\n       monotonic (fun m => mlub (h <o> m)).\nred; intros.\napply mlub_le_compat; intro z.\nunfold shift; auto.\nQed.\n\nLemma doubl_lub_simpl : forall `{c:cpo D} (h : nat -> nat ->  D) {m:monotonic2 h},\n        mlub (mlub h) ==\n        lub (mon (fun m => mlub (h <o> m)) (fmonotonic:=mlub_shift_monotonic h)).\nintros; apply mlub_eq_compat; auto.\nQed.\n\nLemma doubl_lub_simpl : forall `{c:cpo D} (h : nat -> nat ->  D) {m:monotonic2 h},\n        mlub (mlub h) ==\n        lub (mon (fun m => mlub (h <o> m)) (fmonotonic:=mlub_shift_monotonic h)).\nintros; apply mlub_eq_compat; auto.\nQed.\n\n\nLemma double_lub_simpl : forall `{c:cpo D} (h : nat -> nat ->  D) {m:monotonic2 h},\n        mlub (Lub @ (mon_comp h)) == mlub (diag h).\nintros; apply Ole_antisym.\napply mlub_le; simpl; intros.\napply mlub_le; unfold shift; intros.\ntransitivity (h n (n+n0)).\napply m; simpl; auto with arith.\ntransitivity (h (n+n0) (n+n0)).\napply m; simpl; auto with arith.\napply (le_mlub (diag h) (n + n0)%nat).\napply mlub_le_compat; simpl.\nintro x; unfold diag, lub_fun, mon_comp, comp; simpl; auto.\nQed.\n#[export] Hint Resolve double_lub_simpl : core.\n\n\n\nLemma lub_exch_eq : forall `{c:cpo D} (h : nat -> (nat ->  D)) {m:monotonic2 h},\n mlub (Lub @ mon_comp h) == mlub (mlub h).\nintros; transitivity (mlub (diag h)); auto.\nQed.\n\n#[export] Hint Resolve lub_exch_eq : core.\n*)\n\n(** ** Continuity *)\n\nLemma lub_comp_le :\n    forall `{c1:cpo D1} `{c2:cpo D2} (f:D1 -m> D2) (h : nat -m> D1),\n                lub (f @ h) <= f (lub h).\nintros; apply lub_le; unfold comp; intros.\napply (fmonotonic f); auto.\nQed.\n#[export] Hint Resolve lub_comp_le : core.\n\nLemma lub_app2_le : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n        (F:D1 -m> D2 -m> D3) (f : nat -m> D1) (g: nat -m> D2),\n        lub ((F @2 f) g) <= F (lub f) (lub g).\nintros; apply mlub_le; unfold app2; intros.\napply fmonotonic2; auto.\nQed.\n#[export] Hint Resolve lub_app2_le : core.\n\nClass continuous `{c1:cpo D1} `{c2:cpo D2} (f:D1 -m> D2) :=\n    cont_intro : forall (h : nat -m> D1), f (lub h) <= lub (f @ h).\n\n#[export] Typeclasses Opaque continuous.\n\nLemma continuous_eq_compat : forall `{c1:cpo D1} `{c2:cpo D2}(f g:D1 -m> D2),\n                  f == g -> continuous f -> continuous g.\nred; intros.\ntransitivity (f (lub h)).\nassert (g <= f); auto.\ntransitivity (lub (f @ h)); auto.\nQed.\n\nAdd Parametric Morphism `{c1:cpo D1} `{c2:cpo D2} : (@continuous D1 _ _ D2 _ _)\n     with signature Oeq ==> iff\nas continuous_eq_compat_iff.\nsplit; intros.\napply continuous_eq_compat with x; trivial.\napply continuous_eq_compat with y; auto.\nQed.\n\nLemma lub_comp_eq :\n    forall `{c1:cpo D1} `{c2:cpo D2} (f:D1 -m> D2) (h : nat -m> D1),\n             continuous f -> f (lub h) == lub (f @ h).\nintros; apply Ole_antisym; auto.\nQed.\n#[export] Hint Resolve lub_comp_eq : core.\n\n\n(** - mon0 x == 0 *)\n#[export] Instance cont0  `{c1:cpo D1} `{c2:cpo D2} : continuous (mon (cte D1 (0:D2))).\nred; simpl; intros; unfold cte; auto.\nQed.\n\n(** - double_app f g n m = f m (g n) *)\nDefinition double_app `{o1:ord Oa} `{o2:ord Ob} `{o3:ord Oc} `{o4: ord Od}\n      (f:Oa -m> Oc -m> Od) (g:Ob -m> Oc)\n        : Ob -m> (Oa -m> Od) := mon ((mshift f) @ g).\n\n(*\nLemma double_lub_diag : forall `{c:cpo D} (h:nat -> nat -> D) {mh:monotonic2 h},\n             mlub (mlub (fun x => mon (h x))) == mlub (diag h).\nintros; apply Ole_antisym.\napply mlub_le; intros; simpl; apply mlub_le; unfold shift, fun2; simpl; intros.\ntransitivity (h (n+n0) (n+n0)); simpl; auto with arith.\napply (le_mlub (diag h) (n + n0)%nat).\napply mlub_le_compat.\nunfold diag; intro x; simpl; unfold lub_fun, shift; auto.\napply (le_mlub (h <o> x) x); auto.\nQed.\n*)\n\n(** *** Continuity *)\n\nClass continuous2 `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}  (F:D1 -m> D2 -m> D3)  :=\ncontinuous2_intro : forall (f : nat -m> D1) (g :nat -m> D2),\n                 F (lub f) (lub g) <= lub ((F @2 f) g).\n\nLemma continuous2_app : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n            (F : D1 -m> D2 -m> D3) {cF:continuous2 F} (k:D1), continuous (F k).\nred; intros.\ntransitivity  (F (mlub (cte nat k))  (lub h)).\napply fmonotonic2; auto.\ntransitivity (lub ((F @2 (mon (cte nat k))) h)); auto.\napply lub_le_compat; simpl; auto.\nQed.\n\n#[export] Typeclasses Opaque continuous2.\n\nLemma continuous2_eq_compat :\n   forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3} (f g : D1 -m> D2 -m> D3),\n   f == g -> continuous2 f -> continuous2 g.\nred; intros.\ntransitivity (f (lub f0) (lub g0)).\ngeneralize (H (lub f0) (lub (g0))); auto.\ntransitivity (lub ((f @2 f0) g0)); auto.\nQed.\n\nLemma continuous2_continuous : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n           (F : D1 -m> D2 -m> D3), continuous2 F -> continuous F.\nred; intros; intro k.\ntransitivity (F (lub h) (mlub (cte nat k)) ); auto.\ntransitivity (lub ((F @2 h) (mon (cte nat k)))); auto.\nrewrite fmon_lub_simpl.\napply lub_le_compat; simpl; auto.\nQed.\n#[export] Hint Immediate continuous2_continuous : core.\n\nLemma continuous2_left : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n             (F : D1 -m> D2 -m> D3) (h:nat -m> D1) (x:D2),\n             continuous F ->  F (lub h) x <= lub (mshift (F @ h) x).\nintros.\ntransitivity ((mlub (F @ h)) x); auto.\nexact (H h x).\nQed.\n\nLemma continuous2_right : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n             (F : D1 -m> D2 -m> D3) (x:D1)(h:nat -m> D2),\n             continuous2 F ->  F x (lub h) <= lub (F x @ h).\nintros; apply (continuous2_app F x).\nQed.\n\nLemma continuous_continuous2 : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n      (F : D1 -m> D2 -m> D3) (cFr: forall k:D1, continuous (F k)) (cF: continuous F),\n      continuous2 F.\nred; intros.\ntransitivity (lub (F (lub f) @ g)); auto.\napply lub_le; unfold comp; simpl; intros.\ntransitivity ((lub (F@f)) (g n)).\napply cF.\ntransitivity (lub (mshift (F@f) (g n))); auto.\nrewrite (lub_lift_right ((F @2 f) g) n).\napply lub_le_compat.\nunfold seq_lift_right; simpl.\nintro; apply (fmonotonic2 F); auto with arith.\nQed.\n\n#[export] Hint Resolve continuous2_app continuous2_continuous continuous_continuous2 : core.\n\nLemma lub_app2_eq : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n      (F : D1 -m> D2 -m> D3) {cFr:forall k:D1, continuous (F k)} {cF : continuous F},\n      forall (f:nat -m> D1) (g:nat -m> D2),\n      F (lub f) (lub g) == lub ((F@2 f) g).\nintros; apply Ole_antisym; auto.\napply (continuous_continuous2 F); trivial.\nQed.\n\nLemma lub_cont2_app2_eq : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n      (F : D1 -m> D2 -m> D3){cF : continuous2 F},\n      forall (f:nat -m> D1) (g:nat -m> D2),\n      F (lub f) (lub g) == lub ((F@2 f) g).\nintros; apply lub_app2_eq; auto.\nintro; apply (continuous2_app F).\napply continuous2_continuous; trivial.\nQed.\n\nLemma mshift_continuous2 : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n             (F : D1 -m> D2 -m> D3), continuous2 F -> continuous2 (mshift F).\nred; intros; repeat rewrite mshift_simpl; auto.\nrewrite (H g f); auto.\napply lub_le_compat; intro n; auto.\nQed.\n#[export] Hint Resolve mshift_continuous2 : core.\n\nLemma monotonic_sym : forall `{o1:ord D1} `{o2:ord D2} (F : D1 -> D1 -> D2),\n      (forall x y, F x y == F y x) -> (forall k:D1, monotonic (F k)) -> monotonic F.\nred; intros; intro k.\ntransitivity (F k x); auto.\ntransitivity (F k y); auto.\napply H0; trivial.\nQed.\n#[export] Hint Immediate monotonic_sym : core.\n\nLemma monotonic2_sym : forall `{o1:ord D1} `{o2:ord D2} (F : D1 -> D1 -> D2),\n      (forall x y, F x y == F y x) -> (forall k:D1, monotonic (F k)) -> monotonic2 F.\nintros; apply mon2_intro; auto.\nQed.\n#[export] Hint Immediate monotonic2_sym : core.\n\nLemma continuous_sym : forall `{c1:cpo D1} `{c2:cpo D2} (F : D1 -m> D1 -m> D2),\n      (forall x y, F x y == F y x) -> (forall k:D1, continuous (F k)) -> continuous F.\nred; intros; intro k.\ntransitivity (F k (lub h)); auto.\ntransitivity (lub ((F k) @ h)); auto.\nsimpl.\nunfold comp, fun_ext, lub_fun, shift, fun2; simpl; auto.\nQed.\n\nLemma continuous2_sym : forall `{c1:cpo D1} `{c2:cpo D2} (F : D1 -m>D1 -m>D2),\n      (forall x y, F x y == F y x) -> (forall k, continuous (F k)) -> continuous2 F.\nintros; apply continuous_continuous2; auto.\napply continuous_sym; auto.\nQed.\n#[export] Hint Resolve continuous2_sym : core.\n\n(** - continuity is preserved by composition *)\n\nLemma continuous_comp : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n   (f:D2 -m> D3)(g:D1 -m> D2), continuous f -> continuous g -> continuous (mon (f@g)).\nred; intros.\nsimpl; unfold comp at 1; simpl.\ntransitivity (f (lub (g@h))).\napply (fmonotonic f); auto.\ntransitivity (lub (f@(g@h))); auto.\nQed.\n#[export] Hint Resolve continuous_comp : core.\n\nLemma continuous2_comp : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3} `{c4:cpo D4}\n  (f:D1 -m> D2)(g:D2 -m> D3 -m> D4),\n  continuous f -> continuous2 g -> continuous2 (g @ f).\nintros; apply continuous_continuous2.\nred; intros.\nunfold comp at 1; simpl.\napply (continuous2_right g (f k) h); trivial.\napply (continuous_comp g f); auto.\napply continuous2_continuous; trivial.\nQed.\n#[export] Hint Resolve continuous2_comp : core.\n\nLemma continuous2_comp2 : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3} `{c4:cpo D4}\n    (f:D3 -m> D4)(g:D1 -m> D2 -m> D3),\n    continuous f -> continuous2 g -> continuous2 (fcomp2 D1 D2 D3 D4 f g).\nred; intros.\nrewrite fcomp2_simpl.\ntransitivity (f (lub ((g@2 f0) g0))); auto.\ntransitivity (lub (f@((g@2 f0) g0))); auto.\napply lub_le_compat.\nintros x; trivial.\nQed.\n#[export] Hint Resolve continuous2_comp2 : core.\n\nLemma continuous2_app2 : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3} `{c4:cpo D4}\n    (F : D1 -m> D2 -m> D3) (f:D4 -m> D1)(g:D4 -m> D2), continuous2 F ->\n    continuous f -> continuous g -> continuous ((F @2 f) g).\nred; intros.\nrewrite app2_simpl.\ntransitivity (F (lub (f@h)) (lub (g@h))).\napply monotonic2_intro; auto.\nrewrite H.\napply lub_le_compat.\nintros x; trivial.\nQed.\n#[export] Hint Resolve continuous2_app2 : core.\n\n\n(** ** Cpo of continuous functions *)\n\n#[export] Instance lub_continuous `{c1:cpo D1} `{c2:cpo D2}\n     (f:nat -m> (D1 -m> D2)) {cf:forall n, continuous (f n)}\n     : continuous  (lub f).\nred; intros.\ntransitivity (lub (mshift f (lub h))); auto.\napply lub_le; intros.\nrewrite mshift_simpl.\ntransitivity (lub ((f n) @ h)); auto.\nQed.\n\nRecord fcont `{c1:cpo D1} `{c2:cpo D2}: Type\n     := cont {fcontm :> D1 -m> D2; fcontinuous : continuous fcontm}.\n#[export] Existing Instance fcontinuous.\n\n#[export] Hint Resolve fcontinuous : core.\nArguments fcont D1 [o][c1] D2 {o0}{c2}.\nArguments cont [D1][o][c1] [D2][o0][c2] fcontm {fcontinuous}.\n\n(** printing -c> %\\ensuremath{\\stackrel{c}{\\leftarrow}}% #->#*)\n\nInfix \"-c>\" := fcont (at level 30, right associativity) : O_scope.\n\nDefinition fcont_fun `{c1:cpo D1} `{c2:cpo D2} (f:D1 -c> D2) : D1 -> D2 := fun x => f x.\n\n#[export] Program Instance fcont_ord `{c1:cpo D1} `{c2:cpo D2} : ord (D1 -c> D2)\n  := {Oeq := fun f g => forall x, f x == g x; Ole := fun f g =>  forall x, f x <= g x}.\nNext Obligation.\nabstract (split; intuition; red; intros; transitivity (y x0); auto).\nDefined.\n\nLemma fcont_le_intro : forall `{c1:cpo D1} `{c2:cpo D2} (f g : D1 -c> D2),\n    (forall x, f x <= g x) -> f <= g.\ntrivial.\nQed.\n\nLemma fcont_le_elim : forall `{c1:cpo D1} `{c2:cpo D2} (f g : D1 -c> D2),\n     f <= g -> forall x, f x <= g x.\ntrivial.\nQed.\n\nLemma fcont_eq_intro : forall `{c1:cpo D1} `{c2:cpo D2} (f g : D1 -c> D2),\n      (forall x, f x == g x) -> f == g.\nintros; apply Ole_antisym; apply fcont_le_intro; auto.\nQed.\n\nLemma fcont_eq_elim : forall `{c1:cpo D1} `{c2:cpo D2} (f g : D1 -c> D2),\n       f == g -> forall x, f x == g x.\nintros; apply Ole_antisym; apply fcont_le_elim; auto.\nQed.\n\nLemma fcont_le : forall `{c1:cpo D1} `{c2:cpo D2} (f : D1 -c> D2) (x y : D1),\n            x <= y -> f x <= f y.\nintros; apply (fmonotonic (fcontm f) x y H).\nQed.\n#[export] Hint Resolve fcont_le : core.\n\nLemma fcont_eq : forall `{c1:cpo D1} `{c2:cpo D2} (f : D1 -c> D2) (x y : D1),\n            x == y -> f x == f y.\nintros; apply (fmon_eq (fcontm f) x y H).\nQed.\n#[export] Hint Resolve fcont_eq : core.\n\nDefinition fcont0 D1 `{c1:cpo D1} D2 `{c2:cpo D2} : D1 -c> D2 := cont (mon (cte D1 (0:D2))).\n\n#[export] Instance fcontm_monotonic : forall `{c1:cpo D1} `{c2:cpo D2},\n         monotonic (fcontm (D1:=D1) (D2:=D2)).\nintros; auto.\nQed.\n\nDefinition Fcontm D1 `{c1:cpo D1} D2 `{c2:cpo D2} : (D1 -c> D2) -m> (D1 -m> D2) :=\n     mon (fcontm (D1:=D1) (D2:=D2)).\n\n#[export] Instance fcont_lub_continuous :\n    forall `{c1:cpo D1} `{c2:cpo D2} (f:nat -m> (D1 -c> D2)),\n    continuous (lub (D:=D1 -m> D2) (Fcontm D1 D2 @ f)).\nintros; apply lub_continuous.\nintro; simpl; auto.\nQed.\n\nDefinition fcont_lub `{c1:cpo D1} `{c2:cpo D2} : (nat -m> (D1 -c> D2)) -> D1 -c> D2 :=\n     fun f => cont (lub (D:=D1 -m> D2) (Fcontm D1 D2 @ f)).\n\n#[export] Program Instance fcont_cpo `{c1:cpo D1} `{c2:cpo D2} : cpo (D1-c> D2) :=\n  {D0:=fcont0 D1 D2; lub:=fcont_lub (D1:=D1) (D2:=D2)}.\nNext Obligation.\nabstract (intros; simpl; unfold cte; auto). Defined.\nNext Obligation.\nabstract (intros; simpl; intros; apply (le_mlub (fun y : nat => f y x))). Defined.\n\n\n\nDefinition fcont_app {O} {o:ord O} `{c1:cpo D1} `{c2:cpo D2} (f: O -m> D1 -c> D2) (x:D1) : O -m> D2\n         := mshift (Fcontm D1 D2 @ f) x.\n\n(** printing <_> %\\ensuremath{<\\!\\_\\!>}% #&lt;_&gt;# *)\nInfix \"<_>\" := fcont_app (at level 70) : O_scope.\n\nLemma fcont_app_simpl : forall {O} {o:ord O} `{c1:cpo D1} `{c2:cpo D2} (f: O -m> D1 -c> D2)(x:D1)(y:O),\n            (f <_> x) y = f y x.\ntrivial.\nQed.\n\n#[export] Instance ishift_continuous :\n   forall {A:Type} `{c1:cpo D1} `{c2:cpo D2} (f: A -> (D1 -c> D2)),\n          continuous (ishift f).\nred; intros; intro x.\nsimpl.\ntransitivity (lub ((f x) @ h)); auto.\napply lub_le_compat; simpl; trivial.\nQed.\n\nDefinition fcont_ishift {A:Type} `{c1:cpo D1} `{c2:cpo D2} (f: A -> (D1 -c> D2))\n        : D1 -c> (A -> D2) := cont _ (fcontinuous:=ishift_continuous f).\n\n#[export] Instance mshift_continuous : forall {O} {o:ord O} `{c1:cpo D1} `{c2:cpo D2} (f: O -m> (D1 -c> D2)),\n         continuous (mshift (Fcontm D1 D2 @ f)).\nred; intros; intro x.\nsimpl.\nrewrite (fcontinuous (f x) h); auto.\nQed.\n\nDefinition fcont_mshift {O} {o:ord O} `{c1:cpo D1} `{c2:cpo D2} (f: O -m> (D1 -c> D2))\n   : D1 -c> O -m> D2 := cont (mshift (Fcontm D1 D2 @ f)).\n\n\nLemma fcont_app_continuous :\n       forall {O} {o:ord O} `{c1:cpo D1} `{c2:cpo D2} (f: O -m> D1 -c> D2) (h:nat -m> D1),\n            f <_> (lub h) <= lub (D:=O -m> D2) ((fcont_mshift f) @ h).\nintros; intro x.\nrewrite fcont_app_simpl.\nrewrite (fcontinuous (f x) h); simpl; auto.\nQed.\n\nLemma fcont_lub_simpl : forall `{c1:cpo D1} `{c2:cpo D2} (h:nat -m> D1 -c> D2)(x:D1),\n            lub h x = lub (h <_> x).\ntrivial.\nQed.\n\n#[export] Instance cont_app_monotonic : forall `{o1:ord D1} `{c2:cpo D2} `{c3:cpo D3} (f:D1 -m> D2 -m> D3)\n            (p:forall k, continuous (f k)),\n            monotonic (Ob:=D2 -c> D3) (fun (k:D1) => cont _ (fcontinuous:=p k)).\nred; simpl; intros.\napply (fmonotonic f); trivial.\nQed.\n\nDefinition cont_app `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3} (f:D1 -m> D2 -m> D3)\n            (p:forall k, continuous (f k)) : D1 -m> (D2 -c> D3)\n    := mon (fun k => cont (f k) (fcontinuous:=p k)).\n\nLemma cont_app_simpl :\nforall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}(f:D1 -m> D2 -m> D3)(p:forall k, continuous (f k))\n        (k:D1),  cont_app f p k = cont (f k).\ntrivial.\nQed.\n\n#[export] Instance cont2_continuous `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3} (f:D1 -m> D2 -m> D3)\n           (p:continuous2 f) : continuous (cont_app f (continuous2_app f)).\nred; intros; rewrite cont_app_simpl; intro k; simpl.\ntransitivity (lub (D:=D2 -m> D3) (f@h) k).\nassert (continuous f).\napply continuous2_continuous; trivial.\napply H.\nsimpl; auto.\nQed.\n\nDefinition cont2 `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3} (f:D1 -m> D2 -m> D3)\n           {p:continuous2 f} : D1 -c> (D2 -c> D3)\n:= cont (cont_app f (continuous2_app f)).\n\n\n#[export] Instance Fcontm_continuous `{c1:cpo D1} `{c2:cpo D2} : continuous (Fcontm D1 D2).\nred; intros; auto.\nQed.\n#[export] Hint Resolve Fcontm_continuous : core.\n\n#[export] Instance fcont_comp_continuous : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n    (f:D2 -c> D3) (g:D1 -c> D2), continuous (f @ g).\nintros; apply (continuous_comp (fcontm f) (fcontm g)); auto.\nQed.\n\nDefinition fcont_comp `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3} (f:D2 -c> D3) (g:D1 -c> D2)\n   : D1 -c> D3 := cont (f @ g).\n\nInfix \"@_\" := fcont_comp (at level 35) : O_scope.\n\nLemma fcont_comp_simpl : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n       (f:D2 -c> D3)(g:D1 -c> D2) (x:D1), (f @_ g) x = f (g x).\ntrivial.\nQed.\n\nLemma fcontm_fcont_comp_simpl : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n       (f:D2 -c> D3)(g:D1 -c> D2), fcontm (f @_ g) = f @ g.\ntrivial.\nQed.\n\nLemma fcont_comp_le_compat : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n      (f g : D2 -c> D3) (k l :D1 -c> D2),\n      f <= g -> k <= l -> f @_ k <= g @_ l.\nintros; apply fcont_le_intro; intro x.\nrepeat (rewrite fcont_comp_simpl).\ntransitivity (g (k x)); auto.\nQed.\n#[export] Hint Resolve fcont_comp_le_compat : core.\n\nAdd Parametric Morphism `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n    : (@fcont_comp _ _ c1 _ _ c2 _ _ c3)\n      with signature Ole ++> Ole ++> Ole as fcont_comp_le_morph.\nintros.\napply fcont_comp_le_compat; trivial.\nQed.\n\nAdd Parametric Morphism `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n    : (@fcont_comp _ _ c1 _ _ c2 _ _ c3)\n      with signature Oeq ==> Oeq ==> Oeq as fcont_comp_eq_compat.\nintros.\napply Ole_antisym; auto.\nQed.\n\n\nDefinition fcont_Comp D1 `{c1:cpo D1} D2 `{c2:cpo D2} D3 `{c3:cpo D3}\n      : (D2 -c> D3) -m> (D1 -c> D2) -m> D1 -c> D3\n      := mon2 _ (mf:=fcont_comp_le_compat (D1:=D1) (D2:=D2) (D3:=D3)).\n\nLemma fcont_Comp_simpl : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n                        (f:D2 -c> D3) (g:D1 -c> D2), fcont_Comp D1 D2 D3 f g = f @_ g.\ntrivial.\nQed.\n\n#[export] Instance fcont_Comp_continuous2\n   : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}, continuous2 (fcont_Comp D1 D2 D3).\nred; intros.\nchange ((lub  f) @_ (lub g) <= lub (D:=D1 -c> D3) ((fcont_Comp D1 D2 D3 @2 f) g)).\napply fcont_le_intro; intro x; rewrite fcont_comp_simpl.\nrepeat (rewrite fcont_lub_simpl).\nrewrite fcont_app_continuous.\nrewrite double_lub_diag.\napply lub_le_compat; simpl; auto.\nQed.\n\nDefinition fcont_COMP  D1 `{c1:cpo D1} D2 `{c2:cpo D2} D3 `{c3:cpo D3}\n      : (D2 -c> D3) -c> (D1 -c> D2) -c> D1 -c> D3\n      := cont2 (fcont_Comp D1 D2 D3).\n\nLemma fcont_COMP_simpl : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n        (f: D2 -c> D3) (g:D1 -c> D2),\n\tfcont_COMP D1 D2 D3 f g = f @_ g.\ntrivial.\nQed.\n\nDefinition fcont2_COMP D1 `{c1:cpo D1} D2 `{c2:cpo D2} D3 `{c3:cpo D3} D4 `{c4:cpo D4}\n   : (D3 -c> D4) -c> (D1 -c> D2 -c> D3) -c> D1 -c> D2 -c> D4 :=\n     (fcont_COMP D1 (D2 -c> D3) (D2 -c> D4)) @_ (fcont_COMP D2 D3 D4).\n\nDefinition fcont2_comp `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3} `{c4:cpo D4}\n           (f:D3 -c> D4)(F:D1 -c> D2 -c> D3) := fcont2_COMP D1 D2 D3 D4 f F.\n\nInfix \"@@_\" := fcont2_comp (at level 35) : O_scope.\n\nLemma fcont2_comp_simpl : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3} `{c4:cpo D4}\n       (f:D3 -c> D4)(F:D1 -c> D2 -c> D3)(x:D1)(y:D2), (f @@_ F) x y = f (F x y).\ntrivial.\nQed.\n\nLemma fcont_le_compat2 : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3} (f : D1 -c> D2 -c> D3)\n    (x y : D1) (z t : D2), x <= y -> z <= t -> f x z <= f y t.\nintros; transitivity (f y z); auto.\nassert (f x <= f y); auto.\nQed.\n#[export] Hint Resolve fcont_le_compat2 : core.\n\nLemma fcont_eq_compat2 : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3} (f : D1 -c> D2 -c> D3)\n    (x y : D1) (z t : D2), x == y -> z == t -> f x z == f y t.\nintros; apply Ole_antisym; auto.\nQed.\n#[export] Hint Resolve fcont_eq_compat2 : core.\n\nLemma fcont_continuous : forall `{c1:cpo D1} `{c2:cpo D2} (f:D1 -c> D2)(h:nat -m> D1),\n            f (lub h) <= lub (f @ h).\nintros; apply (fcontinuous f h).\nQed.\n#[export] Hint Resolve fcont_continuous : core.\n\n#[export] Instance fcont_continuous2 : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n         (f:D1 -c> D2 -c> D3), continuous2 (Fcontm D2 D3 @ f).\nintros; apply continuous_continuous2; intros.\nchange (continuous (f k)); auto.\napply (continuous_comp (Fcontm D2 D3) (fcontm f)); auto.\nQed.\n#[export] Hint Resolve fcont_continuous2 : core.\n\n#[export] Instance cshift_continuous2 : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n         (f:D1 -c> D2 -c> D3), continuous2 (mshift (Fcontm D2 D3 @ f)).\nintros; auto.\nQed.\n#[export] Hint Resolve cshift_continuous2 : core.\n\nDefinition cshift `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3} (f:D1 -c> D2 -c> D3)\n   : D2 -c> D1 -c> D3 := cont2 (mshift (Fcontm D2 D3 @ f)).\n\nLemma cshift_simpl : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n           (f:D1 -c> D2 -c> D3) (x:D2) (y:D1), cshift f x y = f y x.\ntrivial.\nQed.\n\nDefinition fcont_SEQ  D1 `{c1:cpo D1} D2 `{c2:cpo D2} D3 `{c3:cpo D3}\n   : (D1 -c> D2) -c> (D2 -c> D3) -c> D1 -c> D3 := cshift (fcont_COMP D1 D2 D3).\n\nLemma fcont_SEQ_simpl : forall `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3}\n       (f: D1 -c> D2) (g:D2 -c> D3), fcont_SEQ D1 D2 D3 f g = g @_ f.\ntrivial.\nQed.\n\n(*\n#[export] Instance fcont_comp2_continuous `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3} `{c4:cpo D4}\n                (f: D2 -c> D3 -c> D4) (g:D1 -c> D2) (h:D1 -c> D3)\n     : continuous (((Fcontm D3 D4 @ f) @2 g) h).\nred; intros; simpl.\nchange (f (g (lub h0)) (h (lub h0)) <= lub ((Fcontm D3 D4 @ f @2 g) h @ h0)).\ntransitivity (f (lub (g @ h0)) (lub (h @ h0))); auto.\napply (fcont_continuous2 f (g @ h0) (h @ h0)).\n\n\nDefinition fcont_comp2 `{c1:cpo D1} `{c2:cpo D2} `{c3:cpo D3} `{c4:cpo D4}\n                (f: D2 -c> D3 -c> D4) (g:D1 -c> D2) (h:D1 -c> D3) : D1 -c> D4\n                := cont (((Fcontm D3 D4 @ f) @2 g) h).\n\nintros D1 D2 D3 D4 f g h.\nexists (((Fcontit D3 D4 @fcontit f) @2 fcontit g) (fcontit h)).\nred; intros; simpl.\nchange (f (g (lub h0)) (h (lub h0)) <= lub (c:=D4) ((Fcontit D3 D4 @ fcontit f @2 fcontit g) (fcontit h) @ h0)).\ntransitivity (f (lub (c:=D2) (fcontit g @ h0)) (lub (c:=D3) (fcontit h @ h0))); auto.\napply (fcont_continuous2 f (fcontit g @ h0) (fcontit h @ h0)).\nDefined.\n\nInfix \"@2_\" := fcont_comp2 (at level 35, right associativity) : O_scope.\n\nLemma fcont_comp2_simpl : forall (D1 D2 D3 D4:cpo)\n                (F:D2 -c> D3 -c>D4) (f:D1 -c> D2) (g:D1 -c> D3) (x:D1), (F@2_ f) g x = F (f x) (g x).\ntrivial.\nQed.\n\nAdd Morphism fcont_comp2 with signature Ole++>Ole ++> Ole ++> Ole\nas fcont_comp2_le_morph.\nintros D1 D2 D3 D4 F G HF f1 f2 Hf g1 g2 Hg x.\ntransitivity (fcontit (fcontit G (fcontit f1 x)) (fcontit g1 x)); auto.\nchange (Fcontit D3 D4 (fcontit G (fcontit f1 x)) (fcontit g1 x) <=\n              Fcontit D3 D4 (fcontit G (fcontit f2 x)) (fcontit g2 x)).\napply (fmon_le_compat2 (Fcontit D3 D4)); auto.\nQed.\n\nAdd Morphism fcont_comp2 with signature Oeq ==> Oeq ==> Oeq ==> Oeq as fcont_comp2_eq_compat.\nintros D1 D2 D3 D4 F G (HF1,HF2) f1 f2 (Hf1,Hf2) g1 g2 (Hg1,Hg2).\napply Ole_antisym.\nexact (fcont_comp2_le_morph HF1 Hf1 Hg1).\nexact (fcont_comp2_le_morph HF2 Hf2 Hg2).\nQed.\n\n\n(** - Identity function is continuous *)\n*)\n\n#[export] Instance Id_mon : forall `{o1:ord Oa}, monotonic (fun x:Oa => x).\nred; trivial.\nQed.\n\nDefinition Id Oa {o1:ord Oa} : Oa -m> Oa := mon (fun x => x).\n\nLemma Id_simpl : forall `{o1:ord Oa} (x:Oa), Id Oa x = x.\ntrivial.\nQed.\n\n(*\nDefinition ID : forall D:cpo, D-c>D.\nintros; exists (Id D); red; auto.\nDefined.\n\n\nLemma ID_simpl : forall D x, ID D x = Id D x.\ntrivial.\nQed.\n\nDefinition AP (D1 D2:cpo) : (D1 -c>D2)-c>D1 -c>D2:=ID (D1 -c>D2).\n\nLemma AP_simpl : forall (D1 D2:cpo) (f : D1 -c>D2) (x:D1), AP D1 D2 f x = f x.\ntrivial.\nQed.\n\nDefinition fcont_comp3 (D1 D2 D3 D4 D5:cpo)\n                (F:D2 -c> D3 -c>D4-c>D5)(f:D1 -c> D2)(g:D1 -c> D3)(h:D1 -c>D4): D1 -c>D5\n  := (AP D4 D5 @2_ ((F @2_ f) g)) h.\n\nInfix \"@3_\" := fcont_comp3 (at level 35, right associativity) : O_scope.\n\nLemma fcont_comp3_simpl : forall (D1 D2 D3 D4 D5:cpo)\n                (F:D2 -c> D3 -c>D4-c>D5) (f:D1 -c> D2) (g:D1 -c> D3) (h:D1 -c>D4) (x:D1),\n                (F@3_ f) g h x = F (f x) (g x) (h x).\ntrivial.\nQed.\n\n(** ** Product of two cpos *)\n\nDefinition Oprod : ord -> ord -> ord.\nintros Oa Ob; exists (Oa * Ob)%type (fun (x y:Oa*Ob) => fst x <= fst y /\\ snd x <= snd y); intuition.\ntransitivity a0; trivial.\ntransitivity b0; trivial.\nDefined.\n\nDefinition Fst (Oa Ob : ord) : Oprod Oa Ob -m> Oa.\nintros Oa Ob; exists (fst (A:=Oa) (B:=Ob)); red; simpl; intuition.\nDefined.\n\nDefinition Snd (Oa Ob : ord) : Oprod Oa Ob -m> Ob.\nintros Oa Ob; exists (snd (A:=Oa) (B:=Ob)); red; simpl; intuition.\nDefined.\n\nDefinition Pairr (Oa Ob : ord) : Oa -> Ob -m> Oprod Oa Ob.\nintros Oa Ob x; exists (fun y:Ob => (x,y)); red; auto.\nDefined.\n\nDefinition Pair (Oa Ob : ord) : Oa -m> Ob -m> Oprod Oa Ob.\nintros Oa Ob; exists (Pairr (Oa:=Oa) Ob); red; auto.\nDefined.\n\nLemma Fst_simpl : forall (Oa Ob : ord) (p:Oprod Oa Ob), Fst Oa Ob p = fst p.\ntrivial.\nQed.\n\nLemma Snd_simpl : forall (Oa Ob : ord) (p:Oprod Oa Ob), Snd Oa Ob p = snd p.\ntrivial.\nQed.\n\nLemma Pair_simpl : forall (Oa Ob : ord) (x:Oa)(y:Ob), Pair Oa Ob x y = (x,y).\ntrivial.\nQed.\n\n\nDefinition prod0 (D1 D2:cpo) : Oprod D1 D2 := (0: D1,0: D2).\nDefinition prod_lub (D1 D2:cpo) (f : nat -m> Oprod D1 D2) := (lub (Fst D1 D2@f), lub (Snd D1 D2@f)).\n\nDefinition Dprod : cpo -> cpo -> cpo.\nintros D1 D2; exists (Oprod D1 D2) (prod0 D1 D2) (prod_lub (D1:=D1) (D2:=D2)); unfold prod_lub; intuition.\ntransitivity (fst (fmonot f n), snd (fmonot f n)); simpl; intuition.\napply le_lub with (f:=Fst D1 D2 @ f) (n:=n).\napply le_lub with (f:=Snd D1 D2 @ f) (n:=n).\ntransitivity (fst x, snd x); simpl; intuition.\napply lub_le; simpl; intros.\ncase (H n); auto.\napply lub_le; simpl; intros.\ncase (H n); auto.\nDefined.\n\nLemma Dprod_eq_intro : forall (D1 D2:cpo) (p1 p2: Dprod D1 D2),\n             fst p1 == fst p2 -> snd p1 == snd p2 -> p1 == p2.\nsplit; simpl; auto.\nQed.\n#[export] Hint Resolve Dprod_eq_intro : core.\n\nLemma Dprod_eq_pair : forall (D1 D2:cpo) (x1 y1:D1) (x2 y2:D2),\n             x1==y1 -> x2==y2 -> ((x1,x2):Dprod D1 D2) == (y1,y2).\nauto.\nQed.\n#[export] Hint Resolve Dprod_eq_pair : core.\n\nLemma Dprod_eq_elim_fst : forall (D1 D2:cpo) (p1 p2: Dprod D1 D2),\n             p1==p2 -> fst p1 == fst p2.\nsplit; case H; simpl; intuition.\nQed.\n#[export] Hint Immediate Dprod_eq_elim_fst : core.\n\nLemma Dprod_eq_elim_snd : forall (D1 D2:cpo) (p1 p2: Dprod D1 D2),\n             p1==p2 -> snd p1 == snd p2.\nsplit; case H; simpl; intuition.\nQed.\n#[export] Hint Immediate Dprod_eq_elim_snd : core.\n\nDefinition FST (D1 D2:cpo) : Dprod D1 D2 -c> D1.\nintros; exists (Fst D1 D2); red; intros; auto.\nDefined.\n\nDefinition SND (D1 D2:cpo) : Dprod D1 D2 -c> D2.\nintros; exists (Snd D1 D2); red; intros; auto.\nDefined.\n\nLemma Pair_continuous2 : forall (D1 D2:cpo), continuous2 (D3:=Dprod D1 D2) (Pair D1 D2).\nred; intros; auto.\nQed.\n\nDefinition PAIR (D1 D2:cpo) : D1 -c> D2 -c> Dprod D1 D2\n                := continuous2_cont (Pair_continuous2 (D1:=D1) (D2:=D2)).\n\nLemma FST_simpl : forall (D1 D2 :cpo) (p:Dprod D1 D2), FST D1 D2 p = Fst D1 D2 p.\ntrivial.\nQed.\n\nLemma SND_simpl : forall (D1 D2 :cpo) (p:Dprod D1 D2), SND D1 D2 p = Snd D1 D2 p.\ntrivial.\nQed.\n\nLemma PAIR_simpl : forall (D1 D2 :cpo) (p1:D1) (p2:D2), PAIR D1 D2 p1 p2 = Pair D1 D2 p1 p2.\ntrivial.\nQed.\n\nLemma FST_PAIR_simpl : forall (D1 D2 :cpo) (p1:D1) (p2:D2),\n            FST D1 D2 (PAIR D1 D2 p1 p2) = p1.\ntrivial.\nQed.\n\nLemma SND_PAIR_simpl : forall (D1 D2 :cpo) (p1:D1) (p2:D2),\n            SND D1 D2 (PAIR D1 D2 p1 p2) = p2.\ntrivial.\nQed.\n\nDefinition Prod_map :  forall (D1 D2 D3 D4:cpo)(f:D1 -m>D3)(g:D2 -m>D4) ,\n      Dprod D1 D2 -m> Dprod D3 D4.\nintros; exists (fun p => pair (f (fst p)) (g (snd p))); red; intros.\nsplit; simpl fst; simpl snd; apply fmonotonic.\napply (fmonotonic (Fst D1 D2) H).\napply (fmonotonic (Snd D1 D2) H).\nDefined.\n\n\nLemma Prod_map_simpl : forall (D1 D2 D3 D4:cpo)(f:D1 -m>D3)(g:D2 -m>D4) (p:Dprod D1 D2),\n      Prod_map f g p =  pair (f (fst p)) (g (snd p)).\ntrivial.\nQed.\n\nDefinition PROD_map :  forall (D1 D2 D3 D4:cpo)(f:D1 -c>D3)(g:D2 -c>D4) ,\n      Dprod D1 D2 -c> Dprod D3 D4.\nintros; exists (Prod_map (fcontit f) (fcontit g)); red; intros; rewrite Prod_map_simpl.\nsplit; simpl.\ntransitivity (f (lub (Fst D1 D2 @ h))); trivial.\nrewrite (fcont_continuous f).\napply lub_le_compat; intros; intro; simpl; auto.\ntransitivity (g (lub (Snd D1 D2 @ h))); trivial.\nrewrite (fcont_continuous g).\napply lub_le_compat; intros; intro; simpl; auto.\nDefined.\n\nLemma PROD_map_simpl :  forall (D1 D2 D3 D4:cpo)(f:D1 -c>D3)(g:D2 -c>D4)(p:Dprod D1 D2),\n      PROD_map f g p = pair (f (fst p)) (g (snd p)).\ntrivial.\nQed.\n\nDefinition curry (D1 D2 D3 : cpo) (f:Dprod D1 D2 -c> D3) : D1 -c> (D2 -c>D3) :=\nfcont_COMP D1 (D2 -c>Dprod D1 D2) (D2 -c>D3)\n                          (fcont_COMP D2 (Dprod D1 D2) D3 f) (PAIR D1 D2).\n\nDefinition Curry : forall (D1 D2 D3 : cpo), (Dprod D1 D2 -c> D3) -m> D1 -c> (D2 -c>D3).\n       intros; exists (curry (D1:=D1)(D2:=D2)(D3:=D3)); red; intros; auto.\nDefined.\n\nLemma Curry_simpl : forall (D1 D2 D3 : cpo) (f:Dprod D1 D2 -c> D3) (x:D1) (y:D2),\n       Curry D1 D2 D3 f x y = f (x,y).\ntrivial.\nQed.\n\nDefinition CURRY : forall (D1 D2 D3 : cpo), (Dprod D1 D2 -c> D3) -c> D1 -c> (D2 -c>D3).\n       intros; exists (Curry D1 D2 D3); red; intros; auto.\nDefined.\n\nLemma CURRY_simpl : forall (D1 D2 D3 : cpo) (f:Dprod D1 D2 -c> D3),\n       CURRY D1 D2 D3 f = Curry D1 D2 D3 f.\ntrivial.\nQed.\n\nDefinition uncurry (D1 D2 D3 : cpo) (f:D1 -c> (D2 -c>D3)) : Dprod D1 D2 -c> D3\n      :=  (f @2_ (FST D1 D2)) (SND D1 D2).\n\nDefinition Uncurry : forall (D1 D2 D3 : cpo), (D1 -c> (D2 -c>D3)) -m> Dprod D1 D2 -c> D3.\n       intros; exists (uncurry (D1:=D1)(D2:=D2)(D3:=D3)).\nred; intros.\napply fcont_le_intro; intro z; unfold uncurry.\nrepeat (rewrite fcont_comp2_simpl); auto.\napply (H (FST D1 D2 z) (SND D1 D2 z)).\nDefined.\n\nLemma Uncurry_simpl : forall (D1 D2 D3 : cpo) (f:D1 -c> (D2 -c>D3)) (p:Dprod D1 D2),\n       Uncurry D1 D2 D3 f p = f (fst p) (snd p).\ntrivial.\nQed.\n\nDefinition UNCURRY : forall (D1 D2 D3 : cpo), (D1 -c> (D2 -c>D3)) -c> Dprod D1 D2 -c> D3.\n       intros; exists (Uncurry D1 D2 D3); red; intros; auto.\nDefined.\n\nLemma UNCURRY_simpl : forall (D1 D2 D3 : cpo)  (f:D1 -c> (D2 -c>D3)),\n       UNCURRY D1 D2 D3 f = Uncurry D1 D2 D3 f.\ntrivial.\nQed.\n\n(** ** Indexed product of cpo's *)\n\nDefinition Oprodi (I:Type)(O:I->ord) : ord.\nintros; exists (forall i:I, O i) (fun p1 p2:forall i:I, O i => forall i:I, p1 i <= p2 i); intros; auto.\ntransitivity (y i); trivial.\nDefined.\n\nLemma Oprodi_eq_intro : forall (I:Type)(O:I->ord) (p q : Oprodi O), (forall i, p i == q i) -> p==q.\nintros; apply Ole_antisym; intro i; auto.\nQed.\n\nLemma Oprodi_eq_elim : forall (I:Type)(O:I->ord) (p q : Oprodi O), p==q -> forall i, p i == q i.\nintros; apply Ole_antisym; case H; auto.\nQed.\n\nDefinition Proj (I:Type)(O:I->ord) (i:I) : Oprodi O -m> O i.\nintros; exists (fun x: Oprodi O=> x i); red; intuition.\nDefined.\n\nLemma Proj_simpl : forall  (I:Type)(O:I->ord) (i:I) (x:Oprodi O),\n            Proj O i x = x i.\ntrivial.\nQed.\n\nDefinition Dprodi (I:Type)(D:I->cpo) : cpo.\nintros; exists (Oprodi D) (fun i=>(0:D i)) (fun (f : nat -m> Oprodi D) (i:I) => lub (Proj D i @ f));\nintros; simpl; intros; auto.\napply le_lub with (f:= Proj (fun x : I => D x) i @ f) (n:=n).\napply lub_le; simpl; intros.\napply (H n i).\nDefined.\n\nLemma Dprodi_lub_simpl : forall (I:Type)(Di:I->cpo)(h:nat-m>Dprodi Di)(i:I),\n            lub h i = lub (c:=Di i) (Proj Di i @ h).\ntrivial.\nQed.\n\nLemma Dprodi_continuous : forall `{c:cpo D}(I:Type)(Di:I->cpo)\n    (f:D -m> Dprodi Di), (forall i, continuous (Proj Di i @ f)) ->\n    continuous f.\nred; intros; intro i.\ntransitivity (lub (c:=Di i) ((Proj Di i @ f) @ h)); auto.\nexact (H i h).\nQed.\n\nDefinition Dprodi_lift : forall (I J:Type)(Di:I->cpo)(f:J->I),\n             Dprodi Di -m> Dprodi (fun j => Di (f j)).\nintros; exists (fun (p: Dprodi Di) j => p (f j)); red; auto.\nDefined.\n\nLemma Dprodi_lift_simpl : forall (I J:Type)(Di:I->cpo)(f:J->I)(p:Dprodi Di),\n             Dprodi_lift Di f p = fun j => p (f j).\ntrivial.\nQed.\n\nLemma Dprodi_lift_cont : forall (I J:Type)(Di:I->cpo)(f:J->I),\n             continuous (Dprodi_lift Di f).\nintros; apply Dprodi_continuous; red; simpl; intros; auto.\nQed.\n\nDefinition DLIFTi (I J:Type)(Di:I->cpo)(f:J->I) : Dprodi Di -c> Dprodi (fun j => Di (f j))\n             := mk_fconti (Dprodi_lift_cont (Di:=Di) f).\n\nDefinition Dmapi : forall (I:Type)(Di Dj:I->cpo)(f:forall i, Di i -m> Dj i),\n            Dprodi Di -m> Dprodi Dj.\nintros; exists (fun p i => f i (p i)); red; auto.\nDefined.\n\nLemma Dmapi_simpl : forall (I:Type)(Di Dj:I->cpo)(f:forall i, Di i -m> Dj i) (p:Dprodi Di) (i:I),\nDmapi f p i = f i (p i).\ntrivial.\nQed.\n\nLemma DMAPi : forall (I:Type)(Di Dj:I->cpo)(f:forall i, Di i -c> Dj i),\n            Dprodi Di -c> Dprodi Dj.\nintros; exists (Dmapi (fun i => fcontit (f i))).\nred; intros; intro i; rewrite Dmapi_simpl.\nrepeat (rewrite Dprodi_lub_simpl).\ntransitivity (lub (c:=Dj i) (Fcontit (Di i) (Dj i) (f i) @ (Proj (fun x : I => Di x) i @ h))); auto.\nDefined.\n\nLemma DMAPi_simpl : forall (I:Type)(Di Dj:I->cpo)(f:forall i, Di i -c> Dj i) (p:Dprodi Di) (i:I),\nDMAPi f p i = f i (p i).\ntrivial.\nQed.\n\nLemma Proj_cont : forall (I:Type)(Di:I->cpo) (i:I),\n                    continuous (D1:=Dprodi Di) (D2:=Di i) (Proj Di i).\nred; intros; simpl; trivial.\nQed.\n\nDefinition PROJ (I:Type)(Di:I->cpo) (i:I) : Dprodi Di -c> Di i :=\n      mk_fconti (Proj_cont (Di:=Di) i).\n\nLemma PROJ_simpl : forall (I:Type)(Di:I->cpo) (i:I)(d:Dprodi Di),\n               PROJ Di i d = d i.\ntrivial.\nQed.\n\n(** *** Particular cases with one or two elements *)\n\nSection Product2.\n\nDefinition I2 := bool.\nVariable DI2 : bool -> cpo.\n\nDefinition DP1 := DI2 true.\nDefinition DP2 := DI2 false.\n\nDefinition PI1 : Dprodi DI2 -c> DP1 := PROJ DI2 true.\nDefinition pi1 (d:Dprodi DI2) := PI1 d.\n\nDefinition PI2 : Dprodi DI2 -c> DP2 := PROJ DI2 false.\nDefinition pi2 (d:Dprodi DI2) := PI2 d.\n\nDefinition pair2 (d1:DP1) (d2:DP2) : Dprodi DI2 := bool_rect DI2 d1 d2.\n\nLemma pair2_le_compat : forall (d1 d'1:DP1) (d2 d'2:DP2), d1 <= d'1 -> d2 <= d'2\n            -> pair2 d1 d2 <= pair2 d'1 d'2.\nintros; intro b; case b; simpl; auto.\nQed.\n\nDefinition Pair2 : DP1 -m> DP2 -m> Dprodi DI2 := le_compat2_mon pair2_le_compat.\n\nDefinition PAIR2 : DP1 -c> DP2 -c> Dprodi DI2.\napply continuous2_cont with (D1:=DP1) (D2:=DP2) (D3:=Dprodi DI2) (f:=Pair2).\nred; intros; intro b.\ncase b; simpl; apply lub_le_compat; auto.\nDefined.\n\nLemma PAIR2_simpl : forall (d1:DP1) (d2:DP2), PAIR2 d1 d2 = Pair2 d1 d2.\ntrivial.\nQed.\n\nLemma Pair2_simpl : forall (d1:DP1) (d2:DP2), Pair2 d1 d2 = pair2 d1 d2.\ntrivial.\nQed.\n\nLemma pi1_simpl : forall  (d1: DP1) (d2:DP2), pi1 (pair2 d1 d2) = d1.\ntrivial.\nQed.\n\nLemma pi2_simpl : forall  (d1: DP1) (d2:DP2), pi2 (pair2 d1 d2) = d2.\ntrivial.\nQed.\n\nDefinition DI2_map (f1 : DP1 -c> DP1) (f2:DP2 -c> DP2)\n               : Dprodi DI2 -c> Dprodi DI2 :=\n                 DMAPi (bool_rect (fun b:bool => DI2 b -c>DI2 b) f1 f2).\n\nLemma Dl2_map_eq : forall (f1 : DP1 -c> DP1) (f2:DP2 -c> DP2) (d:Dprodi DI2),\n               DI2_map f1 f2 d == pair2 (f1 (pi1 d)) (f2 (pi2 d)).\nintros; simpl; apply Oprodi_eq_intro; intro b; case b; trivial.\nQed.\nEnd Product2.\n#[export] Hint Resolve Dl2_map_eq : core.\n\nSection Product1.\nDefinition I1 := unit.\nVariable D : cpo.\n\nDefinition DI1 (_:unit) := D.\nDefinition PI : Dprodi DI1 -c> D := PROJ DI1 tt.\nDefinition pi (d:Dprodi DI1) := PI d.\n\nDefinition pair1 (d:D) : Dprodi DI1 := unit_rect DI1 d.\n\nDefinition pair1_simpl : forall (d:D) (x:unit), pair1 d x = d.\ndestruct x; trivial.\nDefined.\n\nDefinition Pair1 : D -m> Dprodi DI1.\nexists pair1; red; intros; intro d.\nrepeat (rewrite pair1_simpl);trivial.\nDefined.\n\n\nLemma Pair1_simpl : forall (d:D), Pair1 d = pair1 d.\ntrivial.\nQed.\n\nDefinition PAIR1 : D -c> Dprodi DI1.\nexists Pair1; red; intros; repeat (rewrite Pair1_simpl).\nintro d; rewrite pair1_simpl.\nrewrite (Dprodi_lub_simpl (Di:=DI1)).\napply lub_le_compat; intros.\nintro x; simpl; rewrite pair1_simpl; auto.\nDefined.\n\nLemma pi_simpl : forall  (d:D), pi (pair1 d) = d.\ntrivial.\nQed.\n\nDefinition DI1_map (f : D -c> D)\n               : Dprodi DI1 -c> Dprodi DI1 :=\n                 DMAPi (fun t:unit => f).\n\nLemma DI1_map_eq : forall (f : D -c> D) (d:Dprodi DI1),\n               DI1_map f d == pair1 (f (pi d)).\nintros; simpl; apply Oprodi_eq_intro; intro b; case b; trivial.\nQed.\nEnd Product1.\n\n#[export] Hint Resolve DI1_map_eq : core.\n*)\n\n(** ** Fixpoints *)\n\nFixpoint iter_ {D} {o} `{c: @cpo D o} (f : D -m> D) n {struct n} : D\n    := match n with O => 0 | S m => f (iter_ f m) end.\n\nLemma iter_incr : forall `{c: cpo D} (f : D -m> D) n, iter_ f n <= f (iter_ f n).\ninduction n; simpl; auto.\nQed.\n#[export] Hint Resolve iter_incr : core.\n\n#[export] Instance iter_mon : forall `{c: cpo D} (f : D -m> D), monotonic (iter_ f).\nred; intros.\ninduction H; simpl; auto.\ntransitivity (iter_ f m); auto.\nQed.\n\nDefinition iter `{c: cpo D} (f : D -m> D) : nat -m> D := mon (iter_ f).\n\nDefinition fixp `{c: cpo D} (f : D -m> D) : D := mlub (iter_ f).\n\nLemma fixp_le : forall `{c: cpo D} (f : D -m> D), fixp f <= f (fixp f).\nintros; unfold fixp.\ntransitivity (lub (f @ (iter f))); auto.\napply lub_le_compat; intro n; simpl.\napply iter_incr.\nQed.\n#[export] Hint Resolve fixp_le : core.\n\nLemma fixp_eq : forall `{c: cpo D} (f : D -m> D) {mf:continuous f},\n      fixp f == f (fixp f).\nintros; apply Ole_antisym; auto.\nunfold fixp.\ntransitivity (lub (f@ (iter f))); auto.\nrewrite (mlub_lift_left (mon (iter_ f)) (S O)); auto.\nQed.\n\nLemma fixp_inv : forall `{c: cpo D} (f : D -m> D) g, f g <= g -> fixp f <= g.\nunfold fixp; intros.\napply lub_le.\ninduction n; intros; simpl; auto.\nsimpl; transitivity (f g); auto.\nQed.\n\n\n\nDefinition fixp_cte : forall `{c:cpo D} (d:D), fixp (mon (cte D d)) == d.\nintros.\napply fixp_eq with (f:=mon (cte D d)); red; intros; simpl; auto.\napply (le_mlub (mon (cte D d) @ h) O).\nQed.\n#[export] Hint Resolve fixp_cte : core.\n\n\nLemma fixp_le_compat : forall `{c:cpo D} (f g : D -m> D),\n      f <= g -> fixp f <= fixp g.\nintros; unfold fixp.\napply mlub_le_compat.\nintro n; induction n; simpl; auto.\ntransitivity (g (iter_ (D:=D) f n)); auto.\nQed.\n#[export] Hint Resolve fixp_le_compat : core.\n\n#[export] Instance fixp_monotonic `{c:cpo D} : monotonic fixp.\nred; auto.\nQed.\n\nAdd Parametric Morphism `{c:cpo D} : (fixp (c:=c))\n    with signature Oeq ==> Oeq as fixp_eq_compat.\nintros; apply Ole_antisym; auto.\nQed.\n#[export] Hint Resolve fixp_eq_compat : core.\n\nDefinition Fixp D `{c:cpo D} : (D -m> D) -m> D := mon fixp.\n\nLemma Fixp_simpl : forall `{c:cpo D} (f:D-m>D), Fixp D f = fixp f.\ntrivial.\nQed.\n\n#[export] Instance iter_monotonic `{c:cpo D} : monotonic iter.\nred; intros f g H.\nintro n; induction n; simpl; intros; auto.\ntransitivity (g (iter_ f n)); auto.\nQed.\n\nDefinition Iter D `{c:cpo D} : (D -m> D) -m> (nat -m> D) := mon iter.\n\nLemma IterS_simpl : forall `{c:cpo D} f n, Iter D f (S n) = f (Iter D f n).\ntrivial.\nQed.\n\nLemma iterO_simpl : forall `{c:cpo D} (f: D-m> D), iter f O = (0:D).\ntrivial.\nQed.\n\nLemma iterS_simpl : forall `{c:cpo D} f n, iter f (S n) = f (iter f n).\ntrivial.\nQed.\n\nLemma iter_continuous : forall `{c:cpo D} (h : nat -m> (D -m> D)),\n       (forall n, continuous (h n)) -> iter (lub h) <= lub (mon iter @ h).\nred; intros; intro k.\ninduction k.\nrewrite iterO_simpl; auto.\nrewrite iterS_simpl.\ntransitivity ((lub h) ((lub (mon iter @ h)) k)); auto.\ntransitivity ((lub h) (lub (mshift (mon iter @ h) k))); auto.\ntransitivity (lub ((lub h) @ (mshift (mon iter @ h) k))).\napply lub_continuous; trivial.\npose (hh:=fun n m: nat => h n (iter (h m) k)).\nassert (monotonic2 hh).\nunfold hh; red; intros n1 n2 m1 m2 H1 H2.\napply (fmonotonic2 h); trivial.\napply iter_monotonic; auto.\ntransitivity (lub (lub (mon2 hh))).\napply lub_le_compat; intro n; unfold hh; simpl; auto.\ntransitivity (lub (diag (mon2 hh))); auto.\ntransitivity (lub (mshift (mon iter @ h) (S k))); auto.\napply lub_le_compat; intro n; simpl; auto.\nQed.\n\n#[export] Hint Resolve iter_continuous : core.\n\nLemma iter_continuous_eq : forall `{c:cpo D} (h : nat -m> (D -m> D)),\n    (forall n, continuous (h n)) -> iter (lub h) == lub (mon iter @ h).\nintros; apply Ole_antisym; auto.\nexact (lub_comp_le (mon iter) h).\nQed.\n\n\nLemma fixp_continuous : forall `{c:cpo D} (h : nat -m> (D -m> D)),\n       (forall n, continuous (h n)) -> fixp (lub h) <= lub (mon fixp @ h).\nintros; unfold fixp.\ntransitivity (lub (lub (mon iter @ h))); auto.\napply lub_le_compat; auto.\nexact (iter_continuous h H).\ntransitivity (lub (lub (mshift (mon iter @ h)))); auto.\napply lub_le_compat; intro n; simpl; auto.\nQed.\n#[export] Hint Resolve fixp_continuous : core.\n\nLemma fixp_continuous_eq : forall `{c:cpo D} (h : nat -m> (D -m> D)),\n       (forall n, continuous (h n)) -> fixp (lub h) == lub (mon fixp @ h).\nintros; apply Ole_antisym; auto.\nexact (lub_comp_le (mon fixp) h).\nQed.\n\nDefinition Fixp_cont D `{c:cpo D} : (D -c> D) -m> D := Fixp D @ (Fcontm D D).\n\nLemma Fixp_cont_simpl : forall `{c:cpo D} (f:D -c> D), Fixp_cont D f = fixp (fcontm f).\ntrivial.\nQed.\n\n\n#[export] Instance Fixp_cont_continuous :  forall D `{c:cpo D}, continuous (Fixp_cont D).\nred; intros.\nrewrite Fixp_cont_simpl.\ntransitivity (fixp (lub (Fcontm D D@h))); auto.\ntransitivity  (lub (Fixp D @ (Fcontm D D@h))); auto.\napply fixp_continuous; intros.\nchange (continuous (D1:=D) (D2:=D) (fcontm (h n))); auto.\napply lub_le_compat; intro n; auto.\nQed.\n\nDefinition FIXP D `{c:cpo D} : (D -c> D) -c> D := cont (Fixp_cont D).\n\nLemma FIXP_simpl : forall `{c:cpo D} (f:D -c> D), FIXP D f = Fixp D (fcontm f).\ntrivial.\nQed.\n\nLemma FIXP_le_compat : forall `{c:cpo D} (f g : D -c> D),\n            f <= g -> FIXP D f <= FIXP D g.\nintros; repeat (rewrite FIXP_simpl); repeat (rewrite Fixp_simpl).\napply fixp_le_compat; auto.\nQed.\n#[export] Hint Resolve FIXP_le_compat : core.\n\nLemma FIXP_eq_compat : forall `{c:cpo D} (f g : D -c> D),\n            f == g -> FIXP D f == FIXP D g.\nintros; apply Ole_antisym; auto.\nQed.\n#[export] Hint Resolve FIXP_eq_compat : core.\n\nLemma FIXP_eq : forall `{c:cpo D} (f:D -c> D), FIXP D f == f (FIXP D f).\nintros; rewrite FIXP_simpl; rewrite Fixp_simpl.\napply (fixp_eq (fcontm f)).\nQed.\n#[export] Hint Resolve FIXP_eq : core.\n\nLemma FIXP_inv : forall `{c:cpo D} (f:D -c> D) (g : D), f g <= g -> FIXP D f <= g.\nintros; rewrite FIXP_simpl; rewrite Fixp_simpl; apply fixp_inv; auto.\nQed.\n\n(** *** Iteration of functional *)\nLemma FIXP_comp_com : forall `{c:cpo D} (f g:D-c>D),\n       g @_ f <= f @_ g-> FIXP D g <= f (FIXP D g).\nintros; apply FIXP_inv.\ntransitivity (f (g (FIXP D g))).\napply (fcont_le_elim _ _ H (FIXP D g)).\napply (fcont_le f).\nrewrite (FIXP_eq g) at 2; trivial.\nQed.\n\nLemma FIXP_comp : forall `{c:cpo D} (f g:D-c>D),\n       g @_ f <= f @_ g -> f (FIXP D g) <= FIXP D g -> FIXP D (f @_ g) == FIXP D g.\nintros; apply Ole_antisym.\n(* fix f @_ g <= fix g *)\napply FIXP_inv.\nrewrite fcont_comp_simpl.\ntransitivity (f (FIXP D g)); auto.\n(* fix g <= fix f @_ g *)\napply FIXP_inv.\nassert (g (f (FIXP D (f @_ g))) <= f (g (FIXP D (f @_ g)))).\napply (H (FIXP D (f @_ g))).\nrewrite (FIXP_eq (f@_g)) at 2.\nrewrite <- H1.\napply fcont_le.\napply FIXP_inv.\nrewrite fcont_comp_simpl.\napply fcont_le.\nrewrite H1; auto.\nrewrite (FIXP_eq (f@_g)) at 2; auto.\nQed.\n\nFixpoint fcont_compn {D} {o} `{c:@cpo D o}(f:D -c> D) (n:nat) {struct n} : D -c> D :=\n             match n with O => f | S p => fcont_compn f p @_ f end.\n\nLemma fcont_compn_Sn_simpl :\n     forall `{c:cpo D}(f:D -c> D) (n:nat), fcont_compn f (S n) = fcont_compn f n @_ f.\ntrivial.\nQed.\n\nLemma fcont_compn_com : forall `{c:cpo D}(f:D-c>D) (n:nat),\n            f @_ (fcont_compn f n) <= fcont_compn f n @_ f.\ninduction n; auto.\nrewrite fcont_compn_Sn_simpl.\ntransitivity ((f @_ fcont_compn (D:=D) f n) @_ f); auto.\nintro k; simpl; auto.\nQed.\n\nLemma FIXP_compn :\n     forall `{c:cpo D} (f:D-c>D) (n:nat), FIXP D (fcont_compn f n) == FIXP D f.\ninduction n; auto.\nsimpl fcont_compn.\napply FIXP_comp.\napply fcont_compn_com.\ntransitivity (fcont_compn (D:=D) f n (FIXP D (fcont_compn (D:=D) f n))); auto.\ntransitivity (FIXP D (fcont_compn (D:=D) f n)); auto.\nQed.\n\nLemma fixp_double : forall `{c:cpo D} (f:D-c>D), FIXP D (f @_ f) == FIXP D f.\nintros; exact (FIXP_compn f (S O)).\nQed.\n\n(*\nLemma FIXP_proj : forall (I:Type)(DI: I -> cpo) (F:Dprodi DI -c> Dprodi DI) (i:I) (fi : DI i -c> DI i),\n                              (forall X : Dprodi DI, F X i == fi (X i)) -> FIXP (Dprodi DI) F i == FIXP (DI i) fi.\nintros; apply Ole_antisym.\n(* fix F i <= fix fi *)\nrewrite FIXP_simpl.\nrewrite Fixp_simpl.\nunfold fixp.\nrewrite Dprodi_lub_simpl.\napply lub_le .\ninduction n; auto.\nrewrite fmon_comp_simpl.\nrewrite (iterS_simpl (fcontit F)).\nrewrite (Proj_simpl (O:=DI) i).\ntransitivity (fi (iter (D:=Dprodi DI) (fcontit F) n i)).\ncase (H (iter (D:=Dprodi DI) (fcontit F) n)); trivial.\ntransitivity (fi (FIXP (DI i) fi)); auto.\n(* fix fi <= fix F i *)\napply FIXP_inv.\ncase (H (FIXP (Dprodi DI) F)); intros.\ntransitivity (1:=H1).\ncase (FIXP_eq F); auto.\nQed.\n*)\n\n(** *** Induction principle *)\nDefinition admissible `{c:cpo D}(P:D->Type) :=\n          forall f : nat -m> D, (forall n, P (f n)) -> P (lub f).\n\nLemma fixp_ind : forall  `{c:cpo D}(F:D -m> D)(P:D->Type),\n       admissible P -> P 0 -> (forall x, P x -> P (F x)) -> P (fixp F).\nintros; unfold fixp.\napply X; intros.\ninduction n; simpl; auto.\nDefined.\n\nDefinition admissible2 `{c1:cpo D1}`{c2:cpo D2}(R:D1 -> D2 -> Type) :=\n    forall (f : nat -m> D1) (g:nat -m> D2), (forall n, R (f n) (g n)) -> R (lub f) (lub g).\n\nLemma fixp_ind_rel : forall  `{c1:cpo D1}`{c2:cpo D2}(F:D1 -m> D1) (G:D2-m> D2)\n       (R:D1 -> D2 -> Type),\n       admissible2 R -> R 0 0 -> (forall x y, R x y -> R (F x) (G y)) -> R (fixp F) (fixp G).\nintros; unfold fixp.\napply X; intros.\ninduction n; simpl; auto.\nDefined.\n\nLemma lub_le_fixp : forall `{c1:cpo D1}`{c2:cpo D2}  (f:D1-m>D2)  (F:D1 -m> D1)\n                                         (s:nat-m> D2),\n          s O <= f 0 -> (forall x n, s n <= f x -> s (S n) <= f (F x))\n          -> lub s <= f (fixp F).\nintros; apply lub_le; intro n.\ntransitivity (f (iter_ F n)); auto.\ninduction n; simpl; auto.\napply fmonotonic; auto.\nunfold fixp; auto.\nQed.\n\nLemma fixp_le_lub : forall `{c1:cpo D1}`{c2:cpo D2}  (f:D1-m>D2)  (F:D1 -m> D1)\n                                         (s:nat-m> D2) {fc:continuous f},\n          f 0 <= s O -> (forall x n, f x <= s n ->  f (F x) <= s (S n)) -> f (fixp F) <= lub s.\nintros; unfold fixp; rewrite fc.\napply lub_le_compat; intro n.\ninduction n; simpl; auto.\nQed.\n\n(*\n(** ** Directed complete partial orders without minimal element *)\n\nRecord dcpo : Type := mk_dcpo\n  {tdcpo:> ord; dlub: (nat -m> tdcpo) -> tdcpo;\n   le_dlub : forall (f : nat -m> tdcpo) (n:nat), f n <= dlub f;\n   dlub_le : forall (f : nat -m> tdcpo) (x:tdcpo), (forall n, f n <= x) -> dlub f <= x}.\n\n#[export] Hint Resolve le_dlub dlub_le : core.\n\nLemma dlub_le_compat : forall (D:dcpo)(f1 f2 : nat -m> D), f1 <= f2 -> dlub f1 <= dlub f2.\nintros; apply dlub_le; intros.\ntransitivity (f2 n); auto.\nQed.\n#[export] Hint Resolve dlub_le_compat : core.\n\nLemma dlub_eq_compat : forall (D:dcpo)(f1 f2 : nat -m> D), f1 == f2 -> dlub f1 == dlub f2.\nintros; apply Ole_antisym; auto.\nQed.\n#[export] Hint Resolve dlub_eq_compat : core.\n\nLemma dlub_lift_right : forall (D:dcpo) (f:nat-m>D) n, dlub f == dlub (mseq_lift_right f n).\nintros; apply Ole_antisym; auto.\napply dlub_le_compat; intro.\nunfold mseq_lift_right; simpl.\napply (fmonotonic f); auto with arith.\nQed.\n#[export] Hint Resolve dlub_lift_right : core.\n\nLemma dlub_cte : forall (D:dcpo) (c:D), dlub (mseq_cte c) == c.\nintros; apply Ole_antisym; auto.\napply le_dlub with (f:=fmon_cte nat c) (n:=O); auto.\nQed.\n\n\n(** *** A cpo is a dcpo *)\n\nDefinition cpo_dcpo : cpo -> dcpo.\nintro D; exists D (lub (c:=D)); auto.\nDefined.\n\n(** ** Setoid type *)\n\nRecord setoid : Type := mk_setoid\n  {tset:>Type; Seq:tset->tset->Prop; Seq_refl : forall x :tset, Seq x x;\n   Seq_sym : forall x y:tset, Seq x y -> Seq y x;\n   Seq_trans : forall x y z:tset, Seq x y -> Seq y z -> Seq x z}.\n\n#[export] Hint Resolve Seq_refl : core.\n#[export] Hint Immediate Seq_sym : core.\n\n(** *** A setoid is an ordered set *)\n\nDefinition setoid_ord : setoid -> ord.\nintro S; exists S (Seq (s:=S)); auto.\nintros; apply Seq_trans with y; trivial.\nDefined.\n\nDefinition ord_setoid : ord -> setoid.\nintro O; exists O (Oeq (O:=O)); auto.\nintros; apply Oeq_trans with y; trivial.\nDefined.\n\n(** *** A Type is an ordered set and a setoid with Leibniz equality *)\n\nDefinition type_ord (X:Type) : ord.\nintro X; exists X (fun x y:X => x = y); intros; auto.\ntransitivity y; trivial.\nDefined.\n\nDefinition type_setoid (X:Type) : setoid.\nintro X; exists X (fun x y:X => x = y); intros; auto.\ntransitivity y; trivial.\nDefined.\n\n(** *** A setoid is a dcpo *)\n\nDefinition lub_eq (S:setoid) (f:nat-m>setoid_ord S) := f O.\n\nLemma le_lub_eq  : forall (S:setoid) (f:nat-m>setoid_ord S) (n:nat), f n <= lub_eq f.\nintros; unfold lub_eq; simpl.\napply Seq_sym; apply (fmonotonic f); simpl; auto with arith.\nQed.\n\nLemma lub_eq_le  : forall (S:setoid) (f:nat-m>setoid_ord S)(x:setoid_ord S),\n                (forall (n:nat), f n <= x) -> lub_eq f <= x.\nintros; unfold lub_eq; simpl; intros.\nexact (H O).\nQed.\n\n#[export] Hint Resolve le_lub_eq lub_eq_le : core.\n\nDefinition setoid_dcpo : setoid -> dcpo.\nintro S; exists (setoid_ord S) (lub_eq (S:=S)); intros; auto.\nDefined.\n\n(** Cpo of arrays seen as functions from nat to D with a bound n *)\n\nDefinition lek {O} {o:ord O} (k:nat) (f g : nat -> O) := forall n, n < k -> f n <= g n.\n#[export] Hint Unfold lek : core.\n\nLemma lek_refl : forall {O} {o:ord O} k (f:nat -> O), lek k f f.\nauto.\nQed.\n#[export] Hint Resolve lek_refl : core.\n\nLemma lek_trans : forall {O} {o:ord O} (k:nat) (f g h: nat -> O), lek k f g -> lek k g h -> lek k f h.\nred; intros.\ntransitivity (g n); auto.\nQed.\n\nDefinition natk_ord : ord -> nat -> ord.\nintros O k; exists (nat->O) (lek (O:=O) k); auto.\nexact (lek_trans (O:=O) (k:=k)).\nDefined.\n\nDefinition norm {O} {o:ord O} (x:O) (k:nat) (f: natk_ord O k) : natk_ord O k :=\n        fun n => if le_lt_dec k n then x else f n.\n\nLemma norm_simpl_lt : forall {O} {o:ord O} (x:O) (k:nat) (f: natk_ord O k) (n:nat),\n       n < k -> norm x f n = f n.\nunfold norm; intros; case (le_lt_dec k n); auto.\nintros; casetype False; omega.\nQed.\n\nLemma norm_simpl_le : forall {O} {o:ord O} (x:O) (k:nat) (f: natk_ord O k) (n:nat),\n       (k <= n)%nat -> norm x f n = x.\nunfold norm; intros; case (le_lt_dec k n); auto.\nintros; casetype False; omega.\nQed.\n\nDefinition natk_mon_shift : forall (Oa Ob : ord)(x:Ob) (k:nat),\n         (Oa -m> natk_ord Ob k) -> natk_ord (Oa -m> Ob) k.\nintros Oa Ob x k f n; exists (fun (y:Oa) => norm x (f y) n).\nred; intros.\ncase (le_lt_dec k n); intro.\nrepeat rewrite norm_simpl_le; auto.\nrepeat rewrite norm_simpl_lt; auto.\napply (fmonotonic f H n); trivial.\nDefined.\n\nLemma natk_mon_shift_simpl\n     : forall (Oa Ob : ord)(x:Ob) (k:nat)(f:Oa -m> natk_ord Ob k) (n:nat) (y:Oa),\n     natk_mon_shift x f n y = norm x (f y) n.\ntrivial.\nQed.\n\nDefinition natk_shift_mon : forall (Oa Ob : ord)(k:nat),\n         (natk_ord (Oa -m> Ob) k) -> Oa -m> natk_ord Ob k.\nintros Oa Ob k f; exists (fun (y:Oa) n => f n y).\nred; intros; intros n H1.\napply (fmonotonic (f n)); auto.\nDefined.\n\nLemma natk_shift_mon_simpl\n     : forall (Oa Ob : ord)(k:nat)(f:natk_ord (Oa -m> Ob) k) (x:Oa)(n:nat),\n     natk_shift_mon f x n = f n x.\ntrivial.\nQed.\n\nDefinition natk0 `{c:cpo D} (k:nat) : natk_ord D k := fun n : nat => (0:D).\n\nDefinition natklub `{c:cpo D} (k:nat) (h:nat-m>natk_ord D k) : natk_ord D k :=\n                            fun n => lub (natk_mon_shift (0:D) h n).\n\nLemma natklub_less : forall `{c:cpo D} (k:nat) (h:nat-m>natk_ord D k) (n:nat),\n                       h n <= natklub h.\nsimpl; red; unfold natklub; intros.\ntransitivity (natk_mon_shift (Oa:=nat) (Ob:=D) 0 (k:=k) h n0 n); auto.\nrewrite natk_mon_shift_simpl.\nrewrite norm_simpl_lt; auto.\nQed.\n\nLemma natklub_least : forall `{c:cpo D} (k:nat) (h:nat-m>natk_ord D k) (p:natk_ord D k),\n                       (forall n:nat, h n <= p) -> natklub h <= p.\nsimpl; red; unfold natklub; intros.\napply lub_le; intros.\nrewrite natk_mon_shift_simpl.\nrewrite norm_simpl_lt; auto.\napply (H n0 n H0).\nQed.\n\nDefinition Dnatk : forall `{c:cpo D} (k:nat), cpo.\nintros; exists (natk_ord D k) (natk0 D k) (natklub (D:=D) (k:=k)).\nunfold natk0; auto.\nexact (natklub_less (D:=D) (k:=k)).\nexact (natklub_least (D:=D) (k:=k)).\nDefined.\n\nNotation \"k --> D\" := (Dnatk D k) (at level 30, right associativity) : O_scope.\n\nDefinition natk_shift_cont : forall (D1 D2 : cpo)(k:nat),\n         (k --> (D1 -c>D2)) -> D1 -c> (k --> D2).\nintros D1 D2 k f; exists (natk_shift_mon (k:=k) (fun n => fcontit (f n))).\nred; intros; intros n H.\nrewrite (natk_shift_mon_simpl (Oa:=D1) (Ob:=D2) (k:=k)).\nsimpl; unfold natklub.\ntransitivity (lub (fcontit (f n) @ h)); auto.\napply lub_le_compat; intro m.\nrewrite fmon_comp_simpl.\nrewrite natk_mon_shift_simpl.\nrewrite norm_simpl_lt; trivial.\nDefined.\n\nLemma natk_shift_cont_simpl\n     : forall (D1 D2:cpo)(k:nat)(f:k --> (D1 -c>D2)) (n:nat) (x:D1),\n     natk_shift_cont f x n = f n x.\ntrivial.\nQed.\n\nLemma natklub_simpl : forall `{c:cpo D} (k:nat) (h:nat -m> k --> D) (n:nat),\n                    lub h n = lub (natk_mon_shift (0:D) h n).\ntrivial.\nQed.\n*)\n\nLtac continuity cont Cont Hcont:=\n  match goal with\n | |- (Ole ?x1 (lub (mon (fun (n:nat) => cont (@?g n))))) =>\n      let f := fresh \"f\" in (\n           pose (f:=g); assert (monotonic f) ;\n                               [auto |  (transitivity (lub (Cont@(mon f))); [rewrite <- Hcont | auto])]\n           )\nend.\n\nLtac gen_monotonic :=\nmatch goal with |- context [(@mon _ _ _ _ ?f ?mf)] => generalize (mf:monotonic f)\nend.\n\nLtac gen_monotonic1 f :=\nmatch goal with |- context [(@mon _ _ _ _ f ?mf)] => generalize (mf:monotonic f)\nend.\n\n(** *** Function for conditionnal choice defined as a morphism *)\n\nDefinition fif {A} (b:bool) : A -> A -> A := fun e1 e2 => if b then e1 else e2.\n\n#[export] Instance fif_mon2 `{o:ord A} (b:bool) : monotonic2 (@fif _ b).\nred; intros; case b; auto.\nQed.\n\nDefinition Fif `{o:ord A} (b:bool) : A -m> A -m> A := mon2 (@fif _ b).\n\nLemma Fif_simpl : forall `{o:ord A} (b:bool) (x y:A), Fif b x y = fif b x y.\ntrivial.\nQed.\n\nLemma Fif_continuous_right `{c:cpo A} (b:bool) (e:A) : continuous (Fif b e).\nred; intros; simpl.\ncase b; simpl @fif.\nrewrite <- (lub_cte e) at 1; auto.\napply mlub_le_compat; auto.\napply lub_le_compat; intro n; auto.\nQed.\n\nLemma  Fif_continuous_left `{c:cpo A} (b:bool) : continuous (Fif (A:=A) b).\nred; intros h e.\ntransitivity (Fif (negb b) e (lub h)).\ndestruct b; trivial.\nrewrite (Fif_continuous_right (negb b) e h).\nrewrite fmon_lub_simpl.\napply lub_le_compat; intro n; case b; auto.\nQed.\n#[export] Hint Resolve Fif_continuous_right Fif_continuous_left : core.\n\nLemma fif_continuous_left `{c:cpo A} (b:bool) (f:nat-m> A):\n    fif b (lub f) == lub (Fif b@f).\nintros; rewrite <- lub_comp_eq; auto.\nQed.\n\nLemma fif_continuous_left2 :\nforall (A : Type) (o : ord A) (c : cpo A) (b : bool) (f : nat -m> A) (g:A),\nfif b (lub f) g == lub (Fif b @ f) g.\nintros; apply fif_continuous_left.\nQed.\n\n\nLemma fif_continuous_right `{c:cpo A} (b:bool) e (f:nat-m> A):\n    fif b e (lub f) == lub (Fif b e@f).\nintros; rewrite <- lub_comp_eq; auto.\nQed.\n\n#[export] Hint Resolve fif_continuous_right fif_continuous_left fif_continuous_left2 : core.\n\n#[export] Instance Fif_continuous2 `{c:cpo A} (b:bool) : continuous2 (Fif (A:=A) b).\napply continuous_continuous2; auto.\nQed.\n\nLemma fif_continuous2 `{c:cpo A} (b:bool) (f g : nat-m> A):\n      fif b (lub f) (lub g) == lub ((Fif b@2 f) g).\nrewrite <- lub_cont2_app2_eq; auto.\nQed.\n\n\nAdd Parametric Morphism `{o:ord A} (b:bool) : (@fif A b)\nwith signature Ole ==> Ole ==> Ole\nas fif_le_compat.\nintros; apply fif_mon2; auto.\nQed.\n\nAdd Parametric Morphism `{o:ord A} (b:bool) : (@fif A b)\nwith signature Oeq ==> Oeq ==> Oeq\nas fif_eq_compat.\nintros; apply (monotonic2_stable2 (@fif A b)); auto.\nQed.\n", "meta": {"author": "math-comp", "repo": "Coq-Combi", "sha": "c6bae09df998f6ebb13637e1fec1a10f87b2f84a", "save_path": "github-repos/coq/math-comp-Coq-Combi", "path": "github-repos/coq/math-comp-Coq-Combi/Coq-Combi-c6bae09df998f6ebb13637e1fec1a10f87b2f84a/3rdparty/ALEA/Ccpo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.6738172715698785}}
{"text": "Require Import Coq.Bool.Bool.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Logic.FunctionalExtensionality.\nImport ListNotations.\nRequire Import Maps.\nRequire Import Imp.\n\nDefinition aequiv (a1 a2 : aexp) : Prop :=\n  forall st : state, aeval st a1 = aeval st a2.\n\nDefinition bequiv (b1 b2 : bexp) : Prop :=\n  forall st : state, beval st b1 = beval st b2.\n\nTheorem aequiv_example :\n  aequiv (AMinus (AId X) (AId X)) (ANum 0).\nProof. intros st. apply Nat.sub_diag. Qed.\n\nTheorem bequiv_example :\n  bequiv (BEq (AMinus (AId X) (AId X)) (ANum 0)) BTrue.\nProof. intros st. simpl. rewrite Nat.sub_diag. reflexivity. Qed.\n\nDefinition cequiv (c1 c2 : com) : Prop :=\n  forall st st' : state,\n    (c1 / st \\\\ st') <-> (c2 / st \\\\ st').\n\nTheorem skip_left : forall c,\n    cequiv (SKIP;; c) c.\nProof. intros c st st'. split; intros H.\n       -inversion H. subst.\n        inversion H2. subst. apply H5.\n       -apply E_Seq with (st' := st). apply E_Skip.\n        apply H.\nQed.\n\nTheorem skip_right : forall c,\n    cequiv (c;; SKIP) c.\nProof. intros c st st'. split; intros H.\n       -inversion H. subst.\n        inversion H5. subst. assumption.\n       -apply E_Seq with (st' := st').\n        apply H. apply E_Skip.\nQed.\n\nTheorem IFB_true_simple : forall c1 c2,\n    cequiv (IFB BTrue THEN c1 ELSE c2 FI) c1.\nProof. intros c1 c2 st st'. split; intros H.\n       -inversion H; subst.\n        +apply H5.\n        +inversion H6.\n       -apply E_IfTrue.\n        +apply H.\n        +reflexivity.\nQed.\n\nTheorem IFB_true : forall c1 c2 b,\n    bequiv b BTrue ->\n    cequiv (IFB b THEN c1 ELSE c2 FI) c1.\nProof. intros c1 c2 b H st st'. split; intros H1.\n       -inversion H1; subst; [assumption |\n        rewrite H in H7; inversion H7].\n       -apply E_IfTrue. apply H1. apply H.\nQed.\n\nTheorem IFB_false : forall c1 c2 b,\n    bequiv b BFalse ->\n    cequiv (IFB b THEN c1 ELSE c2 FI) c2.\nProof. intros c1 c2 b H st st'. split; intros H1.\n       -inversion H1; subst. rewrite H in H7. inversion H7.\n        assumption.\n       -apply E_IfFalse. apply H1. apply H.\nQed.\n\nTheorem swap_if_branches : forall c1 c2 b,\n    cequiv (IFB b THEN c1 ELSE c2 FI) (IFB BNot b THEN c2 ELSE c1 FI).\nProof. intros c1 c2 b st st'. split; intros H.\n       -inversion H; subst; [apply E_IfFalse | apply E_IfTrue]; try assumption;\n        simpl; apply negb_false_iff; try rewrite negb_involutive; assumption.\n       -inversion H; subst; simpl in H6; [apply negb_true_iff in H6 | apply negb_false_iff in H6];\n        [apply E_IfFalse | apply E_IfTrue]; try apply H5; try apply H6.\nQed.\n\nTheorem WHILE_false : forall c b,\n    bequiv b BFalse ->\n    cequiv (WHILE b DO c END) SKIP.\nProof. intros c b H st st'. split; intros H1.\n       -inversion H1; subst; try apply E_Skip.\n        rewrite H in H3. inversion H3.\n       -inversion H1. subst. apply E_WhileEnd.\n        rewrite H. reflexivity.\nQed.\n\nLemma WHILE_true_nonterm : forall b c st st',\n    bequiv b BTrue ->\n    ~( (WHILE b DO c END) / st \\\\ st' ).\nProof. unfold not. intros b c st st' Hb H. remember (WHILE b DO c END) as cw eqn:HH.\n       induction H; try inversion HH. subst. rewrite Hb in H. inversion H.\n       subst. apply IHceval_funR2. reflexivity.\nQed.\n\nTheorem WHILE_true : forall b c,\n    bequiv b BTrue ->\n    cequiv (WHILE b DO c END) (WHILE b DO SKIP END).\nProof. intros b c H. split; intros H1;\n       exfalso; [apply WHILE_true_nonterm with (c:=c) (st:=st) (st':=st') in H |\n                 apply WHILE_true_nonterm with (c:=SKIP) (st:=st) (st':=st') in H ]; \n        apply H; apply H1.\nQed.\n\nTheorem loop_unrolling : forall b c,\n    cequiv (WHILE b DO c END) (IFB b THEN (c ;; WHILE b DO c END) ELSE SKIP FI).\nProof. intros b c. split; intros H.\n       -inversion H; subst.\n        +apply E_IfFalse. apply E_Skip. apply H4.\n        +apply E_IfTrue. apply E_Seq with (st':=st'0). apply H3. apply H6. apply H2.\n       -inversion H; inversion H5. subst.\n        +apply E_WhileLoop with (st':=st'1). apply H6. apply H9. apply H12. \n        +subst. apply E_WhileEnd. apply H6.\nQed.\n\n(* the way this proof worked, I used replace before inversion, I was able to single\none instance of st' to replace. What if c \\ st' / st' were the case instead. Is there\na way to only target the second instance? *)\nTheorem identity_assignment : forall X,\n    cequiv (X ::= AId X) SKIP.\nProof. intros X. split; intros H.\n       -inversion H. subst. simpl. replace (t_update st X (st X)) with st.\n        apply E_Skip. symmetry. apply t_update_same.\n       -replace st' with (t_update st' X (st' X)). inversion H. subst.\n        apply E_Ass. reflexivity. apply t_update_same.\nQed.\n\nTheorem assign_aequiv : forall X e,\n    aequiv (AId X) e ->\n    cequiv SKIP (X ::= e).\nProof. intros X e H. split; intros H1.\n       +unfold aequiv in H. symmetry in H. \n        apply E_Ass with (st:=st') (x:=X) in H. simpl in H.\n        replace st' with (t_update st' X (st' X)).\n        inversion H1. subst. apply H. apply t_update_same.\n       +inversion H1. subst. unfold aequiv in H. rewrite <- H.\n        simpl. rewrite t_update_same. apply E_Skip.\nQed.\n\nLemma refl_aequiv : forall a, aequiv a a.\nProof. unfold aequiv. reflexivity.\nQed.\n\nLemma sym_aequiv : forall a1 a2,\n    aequiv a1 a2 -> aequiv a2 a1.\nProof. intros a1 a2 H. unfold aequiv. unfold aequiv in H.\n       symmetry. apply H.\nQed.\n\nLemma trans_aequiv : forall a1 a2 a3,\n    aequiv a1 a2 -> aequiv a2 a3 -> aequiv a1 a3.\nProof. intros a1 a2 a3 H1 H2. unfold aequiv in H1. unfold aequiv in H2.\n       unfold aequiv. intros st. rewrite <- H2. apply H1.\nQed.\n\nLemma refl_bequiv : forall b, bequiv b b.\nProof. unfold bequiv. reflexivity.\nQed.\n\nLemma sym_bequiv : forall b1 b2,\n    bequiv b1 b2 -> bequiv b2 b1.\nProof. intros b1 b2 H. unfold bequiv. unfold bequiv in H.\n       symmetry. apply H.\nQed.\n\nLemma trans_bequiv : forall b1 b2 b3,\n    bequiv b1 b2 -> bequiv b2 b3 -> bequiv b1 b3.\nProof. intros b1 b2 b3 H1 H2. unfold bequiv in H1. unfold bequiv in H2.\n       unfold bequiv. intros st. rewrite <- H2. apply H1.\nQed.\n\nLemma refl_cequiv : forall c, cequiv c c.\nProof. unfold cequiv. reflexivity.\nQed.\n\nLemma sym_cequiv : forall c1 c2,\n    cequiv c1 c2 -> cequiv c2 c1.\nProof. intros c1 c2 H. unfold cequiv. unfold cequiv in H.\n       symmetry. apply H.\nQed.\n\nLemma iff_trans : forall P1 P2 P3 : Prop,\n    (P1 <-> P2) -> (P2 <-> P3) -> (P1 <-> P3).\nProof. intros P1 P2 P3 H1 H2. rewrite <- H2. apply H1.\nQed.\n\nLemma trans_cequiv : forall c1 c2 c3,\n    cequiv c1 c2 -> cequiv c2 c3 -> cequiv c1 c3.\nProof. intros c1 c2 c3 H1 H2. unfold cequiv in H1. unfold cequiv in H2.\n       unfold cequiv. intros st st'. rewrite <- H2. apply H1.\nQed.\n\nTheorem CAss_congruence : forall i a1 a1',\n    aequiv a1 a1' ->\n    cequiv (i ::= a1) (i ::= a1').\nProof. intros i a1 a1' H. split; intros H1;\n       inversion H1; subst; apply E_Ass; unfold aequiv in H;\n        rewrite H; reflexivity.\nQed.\n\nTheorem CWhile_congruence : forall b b' c c',\n    bequiv b b' ->\n    cequiv c c' ->\n    cequiv (WHILE b DO c END) (WHILE b' DO c' END).\nProof. intros b b' c c' Hb Hc. split; intros H.\n       -remember ((WHILE b DO c END) / st \\\\ st') as Hw.\n        ", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/Equiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.6738172463943585}}
{"text": "Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import choice fintype.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nUnset Printing Implicit.  (* Unset: implicitな引数を表示しない。D:しない。 A:する。*)\nUnset Printing Coercions. (* Unset: コアーションを表示しない。  D:しない。 A:する。*)\nSet Printing Notations.   (* Set: Notation を使って表示する。   D:する。   A:しない。*) \nUnset Printing Universe.  (* Unset: 高階のTypeを表示しない。    D:しない。 A:- *)\n\n(**\n命題4 関数fにおいて、以下は同値である。\n- fは単射\n- g,h : Z -> X について、f・g = f・h ならば g = h\n *)\n\nDefinition c {Z X : Type} (x : X) (_ : Z) := x.\n\nLemma P4 : forall (Z X Y : Type) (f : X -> Y),\n             (forall (x1 x2 : X), f x1 = f x2 -> x1 = x2)\n             <->\n             (forall (g h : Z -> X), (f \\o g) =1 (f \\o h) -> g =1 h).\nProof.\n  move=> Z X Y f.\n  split=> H.\n  - move=> g h H1 z.\n    have H' := H (g z) (h z).\n    by apply/H'/H1.\n\n  - move=> x1 x2 H1.\n    have H' := H (c x1) (c x2).\n    rewrite /eqfun //= in H'.               (* この行は、なくてもよい。 *)\n    apply: H'.\n    + move=> x.\n        (* c x1 x ==> x1, c x2 x ==> x2 より Goal は x1 = f x2 *)\n      by apply: H1.\n    + admit.\n      (* H' の後件 forall x : Z, c x1 x = c x2 x の (x : Z) が使えずに残ってしまう。 *)\nQed.\n\n(**\n命題6'\nX <- Z -> Y の仲介射は、Z = X x Y のとき恒等射(id)である。\n*)\n\nDefinition product {X Y Z : Type} (f : Z -> X) (g : Z -> Y) :=\n  fun (x : Z) => (f x, g x).\n\nNotation \"<< f , g >>\" := (product f g).\n\nCheck <<S, S>> : nat -> nat * nat.\nCheck product S S.\n\nCheck <<S, S>> \\o S.\nCheck <<S \\o S, S \\o S>>.\n\nLemma product_dist {X Y Z W : Type} (f : Z -> X) (g : Z -> Y) (h : W -> Z) :\n  <<f, g>> \\o h =1 <<f \\o h, g \\o h>>.\nProof.\n  done.\nQed.  \n(* 左分配則はなりたたない。 *)\n\n(* 単位元の一意性の証明 *)\n(* f と g が単位元であるとき、f = g である。\n   あるいは、左右単位元が同じ、の証明というべきか。\n *)\nLemma id_uniqness' {X : Type} (f g : X -> X) :\n  (forall h : X -> X, f \\o h =1 h) ->\n  (forall h : X -> X, h \\o g =1 h) ->\n  f =1 g.\nProof.\n  move=> Hf Hg.\n  Check Hf g.                               (* f \\o g =1 g *)\n  Check Hg f.                               (* f \\o g =1 f *)\n  move=> x.\n  have Hf' := Hf g x.                       (* (f \\o g) x = g x *)\n  have Hg' := Hg f x.                       (* (f \\o g) x = f x *)\n  by rewrite -Hf' -Hg'.\nQed.\n\n(* mono または 左キャンセル可能であることの定義 *)\nDefinition mono {X Y Z: Type} (f : X -> Y) (g h : Z -> X) :=\n  f \\o g =1 f \\o h -> g =1 h.\n\nLemma P6' {X Y : Type} (f : X * Y -> X) (g : X * Y -> Y) :\n  mono <<f, g>> <<f, g>> id ->\n            f \\o <<f, g>> =1 f ->\n                      g \\o <<f, g>> =1 g ->\n                                <<f, g>> =1 id.\nProof.\n  move=> Hmono HX HY.\n  apply: Hmono => x.\n  rewrite (product_dist f g <<f, g>> x).\n  rewrite /product /=.\n  rewrite [f (f x, g x)](HX x).\n  rewrite [g (f x, g x)](HY x).\n  by [].\nQed.\n\n(**\n命題10\nPreorder (X, ≦) で圏が定まる。\n反射律(Preorder) <---> 単位律(圏)\n推移律(Preorder) <---> 結合律(圏)\n\nただし、\nf : y < z として g : x < y とするとき、\nf・g : x < y /\\ y < z の意味とする。\n\n *)\n\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/monad/ssr_from_Adventures_of_Categories.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6737193532671802}}
{"text": "Require Import Recdef.\n\nFrom FormalSystems Require Import Base.\n\nInductive AExp : Type :=\n    | AConst : nat -> AExp\n    | Var : Loc -> AExp\n    | Add : AExp -> AExp -> AExp\n    | Sub : AExp -> AExp -> AExp\n    | Mul : AExp -> AExp -> AExp\n    | ACond : BExp -> AExp -> AExp -> AExp\n\nwith BExp : Type :=\n    | BTrue : BExp\n    | BFalse : BExp\n    | Eq : AExp -> AExp -> BExp\n    | Le : AExp -> AExp -> BExp\n    | Not : BExp -> BExp\n    | And : BExp -> BExp -> BExp\n    | Or : BExp -> BExp -> BExp\n    | BCond : BExp -> BExp -> BExp -> BExp.\n\nInductive Com : Type :=\n    | Skip : Com\n    | Asgn : Loc -> AExp -> Com\n    | Seq : Com -> Com -> Com\n    | If : BExp -> Com -> Com -> Com\n    | While : BExp -> Com -> Com.\n\nDefinition State : Type := Loc -> nat.\n\nDefinition initialState : State := fun _ => 0.\n\nDefinition changeState (s : State) (x : Loc) (n : nat) : State :=\n  fun y : Loc => if x =? y then n else s y.\n\nInductive AEval : AExp -> State -> nat -> Prop :=\n    | EvalAConst :\n        forall (n : nat) (s : State), AEval (AConst n) s n\n    | EvalVar :\n        forall (v : Loc) (s : State), AEval (Var v) s (s v)\n    | EvalAdd :\n        forall (a1 a2 : AExp) (s : State) (n1 n2 : nat),\n          AEval a1 s n1 -> AEval a2 s n2 -> AEval (Add a1 a2) s (n1 + n2)\n    | EvalSub :\n        forall (a1 a2 : AExp) (s : State) (n1 n2 : nat),\n          AEval a1 s n1 -> AEval a2 s n2 -> AEval (Sub a1 a2) s (n1 - n2)\n    | EvalMul :\n        forall (a1 a2 : AExp) (s : State) (n1 n2 : nat),\n          AEval a1 s n1 -> AEval a2 s n2 -> AEval (Mul a1 a2) s (n1 * n2)\n    | EvalACondTrue :\n        forall (b : BExp) (s : State) (a1 a2 : AExp) (n : nat),\n          BEval b s true -> AEval a1 s n -> AEval (ACond b a1 a2)s  n\n    | EvalACondFalse :\n        forall (b : BExp) (s : State) (a1 a2 : AExp) (n : nat),\n          BEval b s false -> AEval a2 s n -> AEval (ACond b a1 a2) s n\n\nwith BEval : BExp -> State -> bool -> Prop :=\n    | EvalTrue :\n        forall s : State, BEval BTrue s true\n    | EvalFalse :\n        forall s : State, BEval BFalse s false\n    | EvalEq :\n        forall (a1 a2 : AExp) (s : State) (n m : nat),\n          AEval a1 s n -> AEval a2 s m -> BEval (Eq a1 a2) s (Nat.eqb n m)\n    | EvalLe :\n        forall (a1 a2 : AExp) (s : State) (n m : nat),\n          AEval a1 s n -> AEval a2 s m -> BEval (Le a1 a2) s (Nat.leb n m)\n    | EvalNot :\n        forall (e : BExp) (s : State) (b : bool),\n          BEval e s b -> BEval (Not e) s (negb b)\n    | EvalAnd :\n        forall (e1 e2 : BExp) (s : State) (b1 b2 : bool),\n          BEval e1 s b1 -> BEval e2 s b2 -> BEval (And e1 e2) s (andb b1 b2)\n    | EvalOr :\n        forall (e1 e2 : BExp) (s : State) (b1 b2 : bool),\n          BEval e1 s b1 -> BEval e2 s b2 -> BEval (Or e1 e2) s (orb b1 b2)\n    | EvalBCondTrue :\n        forall (e e1 e2 : BExp) (s : State) (b : bool),\n          BEval e s true -> BEval e1 s b -> BEval (BCond e e1 e2) s b\n    | EvalBCondFalse :\n        forall (e e1 e2 : BExp) (s : State) (b : bool),\n          BEval e s false -> BEval e2 s b -> BEval (BCond e e1 e2) s b.\n\n#[global] Hint Constructors AEval BEval : core.\n\nInductive CEval : Com -> State -> State -> Prop :=\n    | EvalSkip :\n        forall s : State, CEval Skip s s\n    | EvalAsgn :\n        forall (v : Loc) (a : AExp) (s : State) (n : nat),\n          AEval a s n -> CEval (Asgn v a) s (changeState s v n)\n    | EvalSeq :\n        forall (c1 c2 : Com) (s1 s2 s3 : State),\n          CEval c1 s1 s2 -> CEval c2 s2 s3 -> CEval (Seq c1 c2) s1 s3\n    | EvalIfFalse :\n        forall (b : BExp) (c1 c2 : Com) (s1 s2 : State),\n          BEval b s1 false -> CEval c2 s1 s2 -> CEval (If b c1 c2) s1 s2\n    | EvalIfTrue :\n        forall (b : BExp) (c1 c2 : Com) (s1 s2 : State),\n          BEval b s1 true -> CEval c1 s1 s2 -> CEval (If b c1 c2) s1 s2\n    | EvalWhileFalse :\n        forall (b : BExp) (c : Com) (s : State),\n          BEval b s false -> CEval (While b c) s s\n    | EvalWhileTrue :\n        forall (b : BExp) (c : Com) (s1 s2 s3 : State),\n          BEval b s1 true ->\n          CEval c s1 s2 -> CEval (While b c) s2 s3 ->\n            CEval (While b c) s1 s3.\n\n#[global] Hint Constructors CEval : core.\n\nFunction desugara (a : AExp) : AExp :=\nmatch a with\n    | AConst n => AConst n\n    | Var v => Var v\n    | Add a1 a2 =>\n        match desugara a1, desugara a2 with\n            | ACond b1 a11 a12, ACond b2 a21 a22 =>\n                ACond b1 (ACond b2 (Add a11 a21) (Add a11 a22))\n                         (ACond b2 (Add a12 a21) (Add a12 a22))\n            | ACond b1 a11 a12, a2 =>\n                ACond b1 (Add a11 a2) (Add a12 a2)\n            | a1, ACond b2 a21 a22 =>\n                ACond b2 (Add a1 a21) (Add a1 a22)\n            | a1, a2 => Add a1 a2\n        end\n    | Sub a1 a2 => Sub a1 a2\n    | Mul a1 a2 => Mul a1 a2\n    | ACond b1 a1 a2 => ACond (desugarb b1) (desugara a1) (desugara a2)\nend\n\nwith desugarb (b : BExp) : BExp :=\nmatch b with\n    | BTrue => BTrue\n    | BFalse => BFalse\n    | Eq a1 a2 =>\n        match desugara a1, desugara a2 with\n            | ACond b1 a11 a12, ACond b2 a21 a22 =>\n                BCond b1 (BCond b2 (Eq a11 a21) (Eq a11 a22))\n                         (BCond b2 (Eq a12 a21) (Eq a12 a22))\n            | ACond b1 a11 a12, a2 =>\n                BCond b1 (Eq a11 a2) (Eq a12 a2)\n            | a1, ACond b2 a21 a22 =>\n                BCond b2 (Eq a1 a21) (Eq a1 a22)\n            | a1, a2 => Eq a1 a2\n        end\n    | Le a1 a2 => Le a1 a2\n    | Not b' => Not (desugarb b')\n    | And b1 b2 => And (desugarb b1) (desugarb b2)\n    | Or b1 b2 => Or (desugarb b1) (desugarb b2)\n    | BCond b1 b2 b3 => Or (And b1 b2) (And (Not b1) b3)\nend.\n\nLemma AEval_desugara :\n  forall (a : AExp) (s : State) (n : nat),\n    AEval a s n -> AEval (desugara a) s n\n\nwith BEval_desugarb :\n  forall (e : BExp) (s : State) (b : bool),\n    BEval e s b -> BEval (desugarb e) s b.\nProof.\n  intro a. functional induction desugara a; cbn; intros.\n    1-2: assumption.\n    inv H. specialize (IHa0 _ _ H2). rewrite e0 in IHa0. admit.\n    inv H.\n    Ltac wut :=\n    repeat match goal with\n        | IH : forall _ _ , AEval _ _ _ -> _, H : AEval _ _ _ |- _ =>\n            specialize (IH _ _ H)\n        | H : match ?x with _ => _ end |- _ => destruct x\n        | H : AEval (desugara _) _ _, H' : desugara _ = _ |- _ =>\n            rewrite H' in H; inv H; auto\n    end.\n    wut.\n    inv H. wut.\n    inv H.\n    1-2: assumption.\n    inv H; auto.\n  intro e. functional induction desugarb e; cbn; intros; auto.\n    inv H.\n    apply AEval_desugara in H2. rewrite e0 in H2.\n      apply AEval_desugara in H5. rewrite e1 in H5.\n      inv H2; inv H5; auto.\n    admit.\n    admit.\n    inv H. auto.\n    inv H. auto.\n    inv H. auto.\n    inv H. auto.\n    inv H. destruct b; auto.\n\n    repeat match goal with\n        | H : forall _ _ _ , AEval _ _ _ -> _,\n          H' : AEval ?a _ _ |- _ => idtac H; idtac H';\n            is_var a; let H'' := fresh \"H\" in pose (H'' := H _ _ _ H');\n            clearbody H''; clear H'\n        | H : AEval ?a _ _, H' : ?a = _ |- _ =>\n            rewrite H' in H; clear H'; inv H; auto\n    end.\nAbort.", "meta": {"author": "wkolowski", "repo": "FormalSystems", "sha": "f8bc7338315b0b19010952b111924e52bede7920", "save_path": "github-repos/coq/wkolowski-FormalSystems", "path": "github-repos/coq/wkolowski-FormalSystems/FormalSystems-f8bc7338315b0b19010952b111924e52bede7920/Imps/Imp_cond.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.6737193461576519}}
{"text": "(*\n * Taken from https://github.com/jwiegley/coq-lattice\n * Requires the quote library\n *)\n\nRequire Import Coq.Program.Program.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Arith.Bool_nat.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Relations.Relations.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Wellfounded.Lexicographic_Product.\n\nGeneralizable All Variables.\n\nReserved Infix \"⊓\" (at level 40, left associativity).\nReserved Infix \"⊔\" (at level 36, left associativity).\n\nClass Lattice (A : Type) := {\n  meet : A -> A -> A where \"x ⊓ y\" := (meet x y);\n  join : A -> A -> A where \"x ⊔ y\" := (join x y);\n\n  meet_commutative : forall a b, a ⊓ b = b ⊓ a;\n  meet_associative : forall a b c, (a ⊓ b) ⊓ c = a ⊓ (b ⊓ c);\n  meet_absorptive  : forall a b, a ⊓ (a ⊔ b) = a;\n  meet_idempotent  : forall a, a ⊓ a = a;\n\n  join_commutative : forall a b, a ⊔ b = b ⊔ a;\n  join_associative : forall a b c, (a ⊔ b) ⊔ c = a ⊔ (b ⊔ c);\n  join_absorptive  : forall a b, a ⊔ (a ⊓ b) = a;\n  join_idempotent  : forall a, a ⊔ a = a\n}.\n\nInfix \"⊓\" := meet (at level 40, left associativity).\nInfix \"⊔\" := join (at level 36, left associativity).\n\nClass Order (A : Set) := {\n  ord : relation A;\n\n  reflexive :> Reflexive ord;\n  antisymmetric : forall {x y}, ord x y -> ord y x -> x = y;\n  transitive :> Transitive ord\n}.\n\nInfix \"≤\" := ord (at level 50).\n\nClass LOSet {A : Set} `(@Order A) `(@Lattice A) := {\n  meet_consistent : forall a b, a ≤ b <-> a = a ⊓ b;\n  join_consistent : forall a b, a ≤ b <-> b = a ⊔ b\n}.\n\nSection Lattice.\n\nContext `{O : Order A}.\nContext `{L : Lattice A}.\nContext `{@LOSet A O L}.\n\nTheorem meet_is_glb : forall a b : A,\n  forall x, x ≤ a /\\ x ≤ b <-> x ≤ a ⊓ b.\nProof.\n  split; intros.\n    intuition.\n    apply meet_consistent in H1.\n    apply meet_consistent in H2.\n    apply meet_consistent.\n    rewrite <- meet_associative, <- H1.\n    assumption.\n  apply meet_consistent in H0.\n  rewrite H0; clear H0.\n  split; apply meet_consistent.\n    rewrite meet_associative.\n    rewrite (meet_commutative (a ⊓ b) a).\n    rewrite <- (meet_associative a).\n    rewrite meet_idempotent.\n    reflexivity.\n  rewrite meet_associative.\n  rewrite meet_associative.\n  rewrite meet_idempotent.\n  reflexivity.\nQed.\n\nTheorem meet_prime : forall a b : A,\n  forall x, a ≤ x \\/ b ≤ x -> a ⊓ b ≤ x.\nProof.\n  intros.\n  destruct H0;\n  apply meet_consistent in H0;\n  apply meet_consistent; [rewrite meet_commutative|];\n  rewrite meet_associative;\n  rewrite <- H0; reflexivity.\nQed.\n\nTheorem join_is_lub : forall a b : A,\n  forall x, a ≤ x /\\ b ≤ x <-> a ⊔ b ≤ x.\nProof.\n  split; intros.\n    intuition.\n    apply join_consistent in H1.\n    apply join_consistent in H2.\n    apply join_consistent.\n    rewrite join_associative, <- H2.\n    assumption.\n  apply join_consistent in H0.\n  rewrite H0; clear H0.\n  split; apply join_consistent.\n    rewrite <- join_associative.\n    rewrite <- join_associative.\n    rewrite join_idempotent.\n    reflexivity.\n  rewrite (join_commutative a b).\n  rewrite <- join_associative.\n  rewrite <- join_associative.\n  rewrite join_idempotent.\n  reflexivity.\nQed.\n\nTheorem join_prime : forall a b : A,\n  forall x, x ≤ a \\/ x ≤ b -> x ≤ a ⊔ b.\nProof.\n  intros.\n  destruct H0;\n  apply join_consistent in H0;\n  apply join_consistent; [|rewrite join_commutative];\n  rewrite <- join_associative;\n  rewrite <- H0; reflexivity.\nQed.\n\nSet Decidable Equality Schemes.\n\nInductive Term : Set :=\n  | Var  : nat  -> Term\n  | Meet : Term -> Term -> Term\n  | Join : Term -> Term -> Term.\n\nLemma Meet_acc_l x y : Meet x y <> x.\nProof.\n  induction x;\n  unfold not; intros;\n  try discriminate.\n  inversion H0; subst.\n  contradiction.\nQed.\n\nLemma Meet_acc_r x y : Meet x y <> y.\nProof.\n  induction y;\n  unfold not; intros;\n  try discriminate.\n  inversion H0; subst.\n  contradiction.\nQed.\n\nLemma Join_acc_l x y : Join x y <> x.\nProof.\n  induction x;\n  unfold not; intros;\n  try discriminate.\n  inversion H0; subst.\n  contradiction.\nQed.\n\nLemma Join_acc_r x y : Join x y <> y.\nProof.\n  induction y;\n  unfold not; intros;\n  try discriminate.\n  inversion H0; subst.\n  contradiction.\nQed.\n\nFixpoint length (t : Term) : nat :=\n  match t with\n  | Var n => 1\n  | Meet t1 t2 => 1 + length t1 + length t2\n  | Join t1 t2 => 1 + length t1 + length t2\n  end.\n\nFixpoint depth (t : Term) : nat :=\n  match t with\n  | Var n => 0\n  | Meet t1 t2 => 1 + max (depth t1) (depth t2)\n  | Join t1 t2 => 1 + max (depth t1) (depth t2)\n  end.\n\nInductive Subterm : Term -> Term -> Prop :=\n  | Meet1 : forall t1 t2, Subterm t1 (Meet t1 t2)\n  | Meet2 : forall t1 t2, Subterm t2 (Meet t1 t2)\n  | Join1 : forall t1 t2, Subterm t1 (Join t1 t2)\n  | Join2 : forall t1 t2, Subterm t2 (Join t1 t2).\n\nDefinition Subterm_inv_t : forall x y, Subterm x y -> Prop.\nProof.\n  intros [] [] f;\n  match goal with\n  | [ H : Subterm ?X (Meet ?Y ?Z) |- Prop ] =>\n    destruct (Term_eq_dec X Y); subst;\n    [ destruct (Term_eq_dec X Z); subst;\n      [ exact (f = Meet1 _ _ \\/ f = Meet2 _ _)\n      | exact (f = Meet1 _ _) ]\n    | destruct (Term_eq_dec X Z); subst;\n      [ exact (f = Meet2 _ _)\n      | exact False ] ]\n  | [ H : Subterm ?X (Join ?Y ?Z) |- Prop ] =>\n    destruct (Term_eq_dec X Y); subst;\n    [ destruct (Term_eq_dec X Z); subst;\n      [ exact (f = Join1 _ _ \\/ f = Join2 _ _)\n      | exact (f = Join1 _ _) ]\n    | destruct (Term_eq_dec X Z); subst;\n      [ exact (f = Join2 _ _)\n      | exact False ] ]\n  | _ => exact False\n  end.\nDefined.\n\nCorollary Subterm_inv x y f : Subterm_inv_t x y f.\nProof.\n  pose proof Term_eq_dec.\n  destruct f, t1, t2; simpl;\n  repeat destruct (Term_eq_dec _ _); subst;\n  try (rewrite e || rewrite <- e);\n  try (rewrite e0 || rewrite <- e0);\n  try congruence;\n  try rewrite <- Eqdep_dec.eq_rect_eq_dec; eauto; simpl; intuition;\n  try rewrite <- Eqdep_dec.eq_rect_eq_dec; eauto; simpl; intuition;\n\n  repeat destruct (Term_eq_dec _ _); subst;\n  try (rewrite e || rewrite <- e);\n  try (rewrite e0 || rewrite <- e0);\n  try congruence;\n  try rewrite <- Eqdep_dec.eq_rect_eq_dec; eauto; simpl; intuition;\n  try rewrite <- Eqdep_dec.eq_rect_eq_dec; eauto; simpl; intuition.\nQed.\n\nProgram Instance Subterm_Irreflexive : Irreflexive Subterm.\nNext Obligation.\n  repeat intro.\n  pose proof (Subterm_inv _ _ H0).\n  inversion H0; subst; simpl in *.\n  - now apply (Meet_acc_l x t2).\n  - now apply (Meet_acc_r t1 x).\n  - now apply (Join_acc_l x t2).\n  - now apply (Join_acc_r t1 x).\nQed.\n\nLemma Subterm_wf : well_founded Subterm.\nProof.\n  constructor; intros.\n  inversion H0; subst; simpl in *;\n  induction y;\n  induction t1 || induction t2;\n  simpl in *;\n  constructor; intros;\n  inversion H1; subst; clear H1;\n  try (apply IHy1; constructor);\n  try (apply IHy2; constructor).\nDefined.\n\nReserved Notation \"〚 t 〛 env\" (at level 9).\n\nFixpoint eval (t : Term) (env : nat -> A) : A :=\n  match t with\n  | Var n => env n\n  | Meet t1 t2 => 〚t1〛env ⊓ 〚t2〛env\n  | Join t1 t2 => 〚t1〛env ⊔ 〚t2〛env\n  end where \"〚 t 〛 env\" := (eval t env).\n\nDefinition Leq   (s t : Term) : Prop := forall env, 〚s〛env ≤ 〚t〛env.\nArguments Leq _ _ /.\n\n(* Note that Equiv can be computed from Leq. *)\nDefinition Equiv (s t : Term) : Prop := forall env, 〚s〛env = 〚t〛env.\nArguments Equiv _ _ /.\n\nReserved Infix \"≲\" (at level 30).\n\nDefinition R := symprod Term Term Subterm Subterm.\nArguments R /.\n\nOpen Scope lazy_bool_scope.\n\nLtac meets_and_joins leq :=\n  repeat destruct (leq (_, _) _);\n  simpl in *;\n  subst;\n  repeat match goal with\n  | [ H : (_, _) = (_, _) |- _ ] => progress (inversion H; subst)\n  | [ H : bool |- _ ] => destruct H\n  end;\n  try discriminate;\n  simpl in *;\n  repeat match goal with\n  | [ |- _ ⊔ _ ≤ _ ] => apply join_is_lub; split; firstorder idtac\n  | [ |- _ ≤ _ ⊔ _ ] => apply join_prime; firstorder idtac\n  | [ |- _ ≤ _ ⊓ _ ] => apply meet_is_glb; split; firstorder idtac\n  | [ |- _ ⊓ _ ≤ _ ] => apply meet_prime; firstorder idtac\n  end.\n\nLocal Obligation Tactic :=\n  program_simpl; try (constructor; constructor).\n\nSet Transparent Obligations.\n\n(* Whitman's decision procedure. *)\nProgram Fixpoint leq (p : Term * Term) {wf R p} :\n  { b : bool | b = true -> Leq (fst p) (snd p) } :=\n  match p with\n  (* 1. If s = Var i and t = Var j, then s ≲ t holds iff i = j. *)\n  | (Var i, Var j) => nat_eq_bool i j\n\n  (* 2. If s = Join s1 s2, then s ≲ t holds iff s1 ≲ t and s2 ≲ t. *)\n  | (Join s1 s2, t) =>\n    exist _ (proj1_sig (leq (s1, t)) &&& proj1_sig (leq (s2, t))) _\n\n  (* 3. If t = Meet t1 t2, then s ≲ t holds iff s ≲ t1 and s ≲ t2. *)\n  | (s, Meet t1 t2) =>\n    exist _ (proj1_sig (leq (s, t1)) &&& proj1_sig (leq (s, t2))) _\n\n  (* 4. If s = Var i and t = Join t1 t2, then s ≲ t holds iff s ≲ t1 or s ≲ t2. *)\n  | (Var i, Join t1 t2) =>\n    exist _ (proj1_sig (leq (Var i, t1)) ||| proj1_sig (leq (Var i, t2))) _\n\n  (* 5. If s = Meet s1 s2 and t = Var i, then s ≲ t holds iff s1 ≲ t or s2 ≲ t. *)\n  | (Meet s1 s2, Var i) =>\n    exist _ (proj1_sig (leq (s1, Var i)) ||| proj1_sig (leq (s2, Var i))) _\n\n  (* 6. If s = Meet s1 s2 and t = Join t1 t2, then s ≲ t holds iff s1 ≲ t or\n        s2 ≲ t or s ≲ t1 or s ≲ t2. *)\n  | (Meet s1 s2, Join t1 t2) =>\n    exist _ (proj1_sig (leq (s1, Join t1 t2)) |||\n             proj1_sig (leq (s2, Join t1 t2)) |||\n             proj1_sig (leq (Meet s1 s2, t1)) |||\n             proj1_sig (leq (Meet s1 s2, t2))) _\n  end.\nNext Obligation.\n  destruct (nat_eq_bool i j); simpl in *; subst.\n  rewrite y; reflexivity.\nDefined.\nNext Obligation. meets_and_joins leq. Defined.\nNext Obligation. meets_and_joins leq. Defined.\nNext Obligation. meets_and_joins leq. Defined.\nNext Obligation. meets_and_joins leq. Defined.\nNext Obligation.\n  repeat destruct (leq (_, _)); simpl in *.\n  destruct x.  apply meet_prime; left;  apply o;  reflexivity.\n  destruct x0. apply meet_prime; right; apply o0; reflexivity.\n  destruct x1. apply join_prime; left;  apply o1; reflexivity.\n  destruct x2. apply join_prime; right; apply o2; reflexivity.\n  discriminate.\nDefined.\nNext Obligation.\n  apply wf_symprod;\n  apply Subterm_wf.\nDefined.\n\nNotation \"s ≲ t\" := (leq (s, t)) (at level 30).\n\nDefinition leq_correct {t u : Term} (Heq : ` (t ≲ u) = true) :\n  forall env, 〚t〛env ≤ 〚u〛env := proj2_sig (t ≲ u) Heq.\n\nInductive Logic : Set :=\n  | LLe   : Term  -> Term  -> Logic\n  | LAnd  : Logic -> Logic -> Logic\n  | LOr   : Logic -> Logic -> Logic\n  | LImpl : Logic -> Logic -> Logic.\n\nFixpoint logicDenote (t : Logic) (env : nat -> A) : Prop :=\n  match t with\n  | LLe   x y => 〚x〛env ≤ 〚y〛env\n  | LAnd  x y => logicDenote x env /\\ logicDenote y env\n  | LOr   x y => logicDenote x env \\/ logicDenote y env\n  | LImpl x y => logicDenote x env -> logicDenote y env\n  end.\n\nInductive AndOr {A B : Type} : Type :=\n  | AO_Terms : A -> B    -> AndOr\n  | AO_And   : AndOr -> AndOr -> AndOr\n  | AO_Or    : AndOr -> AndOr -> AndOr.\n\nProgram Fixpoint normLe (p : Term * Term) {wf (R) p} : @AndOr Term Term :=\n  match p with\n  | (Meet a b, c) => AO_Or  (normLe (a, c)) (normLe (b, c))\n  | (Join a b, c) => AO_And (normLe (a, c)) (normLe (b, c))\n  | (c, Meet a b) => AO_And (normLe (c, a)) (normLe (c, b))\n  | (c, Join a b) => AO_Or  (normLe (c, a)) (normLe (c, b))\n  | (a, b) => AO_Terms a b\n  end.\nNext Obligation. intuition; inversion H2. Defined.\nNext Obligation. intuition; inversion H2. Defined.\nNext Obligation. intuition; inversion H2. Defined.\nNext Obligation.\n  apply measure_wf.\n  apply wf_symprod;\n  apply Subterm_wf.\nDefined.\n\nFixpoint denoteAndOr (t : @AndOr Term Term) : Logic :=\n  match t with\n  | AO_Terms x y => LLe x y\n  | AO_And   x y => LAnd (denoteAndOr x) (denoteAndOr y)\n  | AO_Or    x y => LOr (denoteAndOr x) (denoteAndOr y)\n  end.\n\nProgram Fixpoint logicNorm (t : Logic) : Logic :=\n  match t with\n  | LLe a b => denoteAndOr (normLe (a, b))\n\n  | LAnd  x y => LAnd (logicNorm x) (logicNorm y)\n  | LOr   x y => LOr  (logicNorm x) (logicNorm y)\n\n  | LImpl x y =>\n    match logicNorm y with\n    | LImpl y z => LImpl (LAnd (logicNorm x) y) z\n    | y => LImpl (logicNorm x) y\n    end\n  end.\n\nTheorem logicNorm_sound : forall x env,\n  logicDenote x env <->\n  logicDenote (logicNorm x) env.\nProof.\nAdmitted.\n\n(*\nDefinition markVars (t : Term) (env : nat -> A) (f : nat -> bool) :\n  nat -> bool :=\n  let fix go t f :=\n      match t with\n      | Var x    => fun n => (x =? n) ||| f n\n      | Meet x y => go x (go y f) (* jww (2017-06-18): correct? *)\n      | Join x y => go x (go y f)\n      end in\n  go t (fun _ => false).\n\nFixpoint markLogic (t : Logic) (env : nat -> A) : Prop :=\n  match t with\n  | LLe   x y => 〚x〛env ≤ 〚y〛env\n  | LAnd  x y => logicDenote x env /\\ logicDenote y env\n  | LOr   x y => logicDenote x env \\/ logicDenote y env\n  | LImpl x y => logicDenote x env -> logicDenote y env\n  end.\n\nFixpoint logicCheck (t : Logic) (env : nat -> A) : Prop :=\n  match t with\n  | LLe   x y => 〚x〛env ≤ 〚y〛env\n  | LAnd  x y => logicDenote x env /\\ logicDenote y env\n  | LOr   x y => logicDenote x env \\/ logicDenote y env\n  | LImpl x y => logicDenote x env -> logicDenote y env\n  end.\n\nProgram Fixpoint determine_truth (t : Logic) {struct t} :\n  { b : bool | b = true -> forall env, logicDenote t env } :=\n  match t with\n  | LLe   x y => leq (x, y)\n  | LAnd  x y => exist _ (` (determine_truth x) &&& ` (determine_truth y)) _\n  | LOr   x y => exist _ (` (determine_truth x) ||| ` (determine_truth y)) _\n  | LImpl x y => exist _ (if ` (determine_truth x)\n                          then ` (determine_truth y)\n                          else false) _\n  end.\nNext Obligation. destruct x0; intuition. Defined.\nNext Obligation. destruct x0; intuition. Defined.\nNext Obligation. destruct x0; intuition. Defined.\n*)\n\nEnd Lattice.\n\nNotation \"〚 t 〛 env\" := (@eval _ _ t env) (at level 9).\nNotation \"s ≲ t\" := (@leq _ _ _ _ (s, t)) (at level 30).\n\nImport ListNotations.\n\nLtac inList x xs :=\n  match xs with\n  | tt => false\n  | (x, _) => true\n  | (_, ?xs') => inList x xs'\n  end.\n\nLtac addToList x xs :=\n  let b := inList x xs in\n  match b with\n  | true => xs\n  | false => constr:((x, xs))\n  end.\n\nLtac allVars xs e :=\n  match e with\n  | ?e1 ⊓ ?e2 =>\n    let xs := allVars xs e1 in\n    allVars xs e2\n  | ?e1 ⊔ ?e2 =>\n    let xs := allVars xs e1 in\n    allVars xs e2\n  | _ => addToList e xs\n  end.\n\nLtac lookup x xs :=\n  match xs with\n  | (x, _) => O\n  | (_, ?xs') =>\n    let n := lookup x xs' in\n    constr:(S n)\n  end.\n\nLtac reifyTerm env t :=\n  match t with\n  | ?X1 ⊓ ?X2 =>\n    let r1 := reifyTerm env X1 in\n    let r2 := reifyTerm env X2 in\n    constr:(Meet r1 r2)\n  | ?X1 ⊔ ?X2 =>\n    let r1 := reifyTerm env X1 in\n    let r2 := reifyTerm env X2 in\n    constr:(Join r1 r2)\n  | ?X =>\n    let n := lookup X env in\n    constr:(Var n)\n  end.\n\nLtac functionalize xs :=\n  let rec loop n xs' :=\n    match xs' with\n    | (?x, tt) => constr:(fun _ : nat => x)\n    | (?x, ?xs'') =>\n      let f := loop (S n) xs'' in\n      constr:(fun m : nat => if m =? n then x else f m)\n    end in\n  loop 0 xs.\n\nLtac reify :=\n  match goal with\n  | [ |- ?S ≤ ?T ] =>\n    let xs  := allVars tt S in\n    let xs' := allVars xs T in\n    let r1  := reifyTerm xs' S in\n    let r2  := reifyTerm xs' T in\n    let env := functionalize xs' in\n    (* pose xs'; *)\n    (* pose env; *)\n    (* pose r1; *)\n    (* pose r2; *)\n    change (〚r1〛env ≤ 〚r2〛env)\n  end.\n\nLtac lattice := reify; apply leq_correct; vm_compute; auto.\n\nExample sample_1 `{LOSet A} : forall a b : A,\n  a ≤ a ⊔ b.\nProof. intros; lattice. Qed.\n\nLemma running_example `{LOSet A} : forall a b : A,\n  a ⊓ b ≤ a ⊔ b.\nProof.\n  intros a b.\n  rewrite meet_consistent.\n  rewrite meet_associative.\n  rewrite join_commutative.\n  rewrite meet_absorptive.\n  reflexivity.\nQed.\n\nLemma running_example' `{LOSet A} : forall a b : A,\n  a ⊓ b ≤ a ⊔ b.\nProof. intros; lattice. Qed.\n\nLemma median_inequality `{LOSet A} : forall x y z : A,\n  (x ⊓ y) ⊔ (y ⊓ z) ⊔ (z ⊓ x) ≤ (x ⊔ y) ⊓ (y ⊔ z) ⊓ (z ⊔ x).\nProof. intros; lattice. Qed.\n\nLtac allVarsLogic xs e :=\n  match e with\n  | ?X1 ≤ ?X2 =>\n    let xs := allVars xs X1 in\n    allVars xs X2\n  | ?X1 /\\ ?X2 =>\n    let xs := allVarsLogic xs X1 in\n    allVarsLogic xs X2\n  | ?X1 \\/ ?X2 =>\n    let xs := allVarsLogic xs X1 in\n    allVarsLogic xs X2\n  | ~ ?X1 =>\n    allVarsLogic xs X1\n  | ?X1 -> ?X2 =>\n    let xs := allVarsLogic xs X1 in\n    allVarsLogic xs X2\n  end.\n\nLtac reifyLogic env t :=\n  match t with\n  | ?X1 ≤ ?X2 =>\n    let r1 := reifyTerm env X1 in\n    let r2 := reifyTerm env X2 in\n    constr:(LLe r1 r2)\n  | ?X1 /\\ ?X2 =>\n    let r1 := reifyLogic env X1 in\n    let r2 := reifyLogic env X2 in\n    constr:(LAnd r1 r2)\n  | ?X1 \\/ ?X2 =>\n    let r1 := reifyLogic env X1 in\n    let r2 := reifyLogic env X2 in\n    constr:(LOr r1 r2)\n  | ?X1 -> ?X2 =>\n    let r1 := reifyLogic env X1 in\n    let r2 := reifyLogic env X2 in\n    constr:(LImpl r1 r2)\n  end.\n\nLtac lattice' :=\n  match goal with\n  | [ |- ?P ] =>\n    let xs := allVarsLogic tt P in\n    let r1 := reifyLogic xs P in\n    let env := functionalize xs in\n    (* pose xs; *)\n    (* pose r1; *)\n    (* pose env; *)\n    change (logicDenote r1 env);\n    apply logicNorm_sound;\n    let p := fresh \"p\" in\n    let Heqp := fresh \"Heqp\" in\n    remember (logicNorm _) as p eqn:Heqp;\n    vm_compute in Heqp;\n    rewrite Heqp; clear Heqp p\n    (* vm_compute; *)\n    (* intuition idtac *)\n  end.\n\nLemma example_3 `{LOSet A} : forall a b c : A,\n  b ≤ a ⊔ b ->\n  a ⊓ c ≤ a ->\n  a ⊓ b ≤ c ->\n  a ⊓ c ≤ b.\nProof.\n  intros a b c.\n  lattice'.\n  simpl.\n  intuition.\nAdmitted.\n\nLemma median_inequality' `{LOSet A} : forall x y z : A,\n  (x ⊓ y) ⊔ (y ⊓ z) ⊔ (z ⊓ x) ≤ (x ⊔ y) ⊓ (y ⊔ z) ⊓ (z ⊔ x).\nProof.\n  intros.\n  lattice'.\n  simpl.\n  intuition.\nAbort.\n", "meta": {"author": "yalhessi", "repo": "verified-verifier", "sha": "6471820d21feeac2766944f506ec9304558442c5", "save_path": "github-repos/coq/yalhessi-verified-verifier", "path": "github-repos/coq/yalhessi-verified-verifier/verified-verifier-6471820d21feeac2766944f506ec9304558442c5/Lattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.673719341436331}}
{"text": "Goal forall (X : Type) (x y : X),\n(forall p : X -> Prop, p x -> p y) -> x = y.\n\nProof.\n  intros X x y A.\n\n  apply (A (fun z => x = z)).\n  reflexivity.\nQed.\n", "meta": {"author": "billwestfall", "repo": "coq_ide", "sha": "a2985a04f37f9c1c6f23799d543fdb862792d54b", "save_path": "github-repos/coq/billwestfall-coq_ide", "path": "github-repos/coq/billwestfall-coq_ide/coq_ide-a2985a04f37f9c1c6f23799d543fdb862792d54b/tutorial03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6737193343543494}}
{"text": "\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Strings.Ascii.\n\nDefinition beq_char (a:ascii) (b:ascii) : bool :=\n  beq_nat (nat_of_ascii a) (nat_of_ascii b).\n\nFixpoint beq_string (str1:string) (str2:string) : bool :=\n  match str1,str2 with\n  | String h1 t1, String h2 t2 => if beq_char h1 h2 then beq_string t1 t2 else false\n  | EmptyString, EmptyString => true\n  | _, _ => false\n  end.\n\nExample beg_string_test1 : (beq_string \"123123\" \"123123\") = true.\nProof.\n  simpl. reflexivity.\nQed.\n\nExample beg_string_test2 : (beq_string \"123123\" \"abcabc\") = false.\nProof.\n  simpl. reflexivity.\nQed.\n \nLemma string_eq_ref : forall s1 s2, beq_string s1 s2 = true -> s1 = s2.\nProof.\n  intros. Admitted.\n\nLemma string_neq_ref : forall s1 s2, beq_string s1 s2 = false -> s1 <> s2.\nProof.\n  intros. Admitted.\n", "meta": {"author": "Stumble", "repo": "TrustCoq", "sha": "90396742e9477c90cf61caa5a32b54969bceaf77", "save_path": "github-repos/coq/Stumble-TrustCoq", "path": "github-repos/coq/Stumble-TrustCoq/TrustCoq-90396742e9477c90cf61caa5a32b54969bceaf77/Strlib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6736561773864428}}
{"text": "Require Export Arith.\nRequire Export ArithRing.\nRequire Export Lia.\nRequire Export log2_it.\n \nInductive log_domain : nat ->  Prop :=\n | log_domain_1: log_domain 1\n | log_domain_2:\n     forall (p : nat), log_domain (S (div2 p)) ->  log_domain (S (S p)) .\n \nTheorem log_domain_non_O: forall (x : nat), log_domain x ->  (x <> 0).\nProof.\n intros x H; case H;  discriminate.\nQed.\n \nTheorem log_domain_inv:\n forall (x p : nat), log_domain x -> x = S (S p) ->  log_domain (S (div2 p)).\nProof.\nintros x p H; case H; (try (intros H'; discriminate H')).\n intros p' H1 H2; injection H2; intros H3; rewrite <- H3; assumption.\nDefined.\n \nFixpoint exp2 (n : nat) : nat :=\n match n with O => 1 | S p => 2 * exp2 p end.\n \nTheorem spec_1:  exp2 0 <= 1 < 2 * exp2 0 .\nProof.\nsimpl; auto with arith.\nQed.\n \nTheorem spec_2:\n forall p v',\n ( exp2 v' <= div2 (S (S p)) < 2 * exp2 v' ) ->\n  ( exp2 (S v') <= S (S p) < 2 * exp2 (S v') ).\nProof.\nintros p v' H; (cbv zeta iota beta delta [exp2]; fold exp2).\nelim (div2_eq (S (S p))); intros; lia.\nQed.\n \nDefinition log_well_spec:\n forall x (h : log_domain x),\n  ({v : nat |  exp2 v <= x < 2 * exp2 v }).\nrefine (fix\n        log_well_spec (x : nat) (h : log_domain x) {struct h} :\n          {v : nat |  exp2 v <= x < 2 * exp2 v } :=\n           match x as y\n           return x = y ->  ({v : nat |  exp2 v <= y < 2 * exp2 v })\n           with\n              0 =>\n                fun h' =>\n                False_rec\n                 ({v : nat |  exp2 v <= 0 < 2 * exp2 v })\n                 (log_domain_non_O x h h')\n             | 1 =>\n                 fun h' =>\n                 exist (fun v =>  exp2 v <= 1 < 2 * exp2 v ) 0 spec_1\n             | S (S p) =>\n                 fun h' =>\n                    match log_well_spec (S (div2 p)) (log_domain_inv x p h h')\n                     with\n                      exist _ v' Hv' =>\n                        exist \n                         (fun v =>  exp2 v <= S (S p) < 2 * exp2 v )\n                         (S v') (spec_2 p v' Hv')\n                    end\n           end (refl_equal x)).\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/ch15_general_recursion/SRC/log_domain_well_spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6736561539991095}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\n\nSet Ltac Profiling.\n\nLemma plus_O : forall n m: nat, n + m = m + n.\nProof.\n  induction n; try done; simpl; intro.\n  rewrite IHn.\n  done.\nQed.\n\nShow Ltac Profile.", "meta": {"author": "ml4tp", "repo": "gamepad", "sha": "7092f50a96eae9a862e72ecb8a55a217fa97723c", "save_path": "github-repos/coq/ml4tp-gamepad", "path": "github-repos/coq/ml4tp-gamepad/gamepad-7092f50a96eae9a862e72ecb8a55a217fa97723c/examples/backtrack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6736561537860516}}
{"text": "Require Import List.\n\n\nInductive Perm (a:Type) : list a -> list a -> Prop :=\n| pRefl   : forall (xs:list a), Perm a xs xs\n| pCons   : forall (x:a)(xs ys:list a), Perm a xs ys -> Perm a (x :: xs) (x :: ys)\n| pAppend : forall (x:a)(xs:list a), Perm a (x :: xs) (xs ++ x :: nil)\n| pTrans  : forall (xs ys zs:list a), Perm a xs ys -> Perm a ys zs -> Perm a xs zs\n.\n\nLtac perm_aux n :=\n    match goal with\n    | |- (Perm _ ?l ?l) => apply pRefl\n    | |- (Perm _ (?x :: ?l1) (?x :: ?l2)) =>\n        let newn := eval compute in (length l1) in\n            (apply pCons; perm_aux newn)\n    | |- (Perm ?a (?x :: ?l1) ?l2) =>\n        match eval compute in n with\n        | 1 => fail\n        | _ =>\n            let l1' := constr:(l1 ++ x :: nil) in\n                (apply (pTrans a (x :: l1) l1' l2);\n                [ apply pAppend | compute; perm_aux (pred n) ])\n        end\n    end.\n\nLtac solve_perm :=\n    match goal with\n    | |- (Perm _ ?l1 ?l2) =>\n        match eval compute in (length l1 = length l2) with\n        | (?n = ?n) => perm_aux n\n        end\n    end.\n\nLemma L1 : Perm nat (1 :: 2 :: 3 :: nil) (3 :: 2 :: 1 :: nil).\nProof. solve_perm. Qed.\n\n\nLemma L2 : Perm nat \n    (0 :: 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: 8 :: 9 :: nil)\n    (0 :: 2 :: 4 :: 6 :: 8 :: 9 :: 7 :: 5 :: 3 :: 1 :: nil).\nProof. solve_perm. Qed.\n    \n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/ref/Permutations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6736561537860516}}
{"text": "(*\n        #####################################################\n        ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n        #####################################################\n*)\n\nSet Default Goal Selector \"!\".\n\nRequire Import Turing.Turing.\nRequire Import Turing.LangRed.\nRequire Import Turing.LangDec.\nRequire Import Turing.Problems.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(* ---------------------------------------------------------------------------*)\n\n(* ------------------------ BEGIN UTILITY RESULTS ---------------------- *)\nLtac invc H := inversion H; subst; clear H.\n\nLemma a_tm_rw:\n  forall M i,\n  A_tm <[ M, i ]> <->\n  Run (Call M i) true.\nProof.\n  unfold A_tm.\n  intros.\n  run_simpl_all.\n  reflexivity.\nQed.\n\n(* -------------------------- END OF UTILITY RESULTS ---------------------- *)\n\n\n\n(**\n\n=== Background information on map-reducibility ===\n\nFirst recall the definition of <=m .\n\n  Notation \"<=m\".\n\noutputs:\n\n  Notation \"x <=m y\" := (Reducible x y) (default interpretation)\n\nSo, what is reducible:\n\n  Print Reducible.\n  \nWhich says:\n\n  Reducible = \n  fun A B : lang => exists f : input -> input, Reduction f A B\n      : lang -> lang -> Prop\n\n  Arguments Reducible A B\n\nThe important bit here is\n\n    exists f, Reduction f A B\n\nAfter `Print Reduction.` we recall that a reduction relates any input i\nin A whenever f(i) is in B.\n\n    forall w, A w <-> B (f w)\n\n=== Actual proof ===\n\nWe will follow the proof of Theorem 5.28 (which redirects to\nthe proof of 5.22).\n\nThis kind of result needs to be proved directly (without the\naid of any theorem, so let us open up both definitions: \n\n    unfold Reducible, Reduction in *.\n\nAt this point, our proof state is as follows:\n\n  H : exists f, forall w : input, A w <-> B (f w)\n  H0 : Recognizable B\n  ______________________________________(1/1)\n  Recognizable A\n\nLet us access the function that maps from A to B with `destruct H as (f, H)`,\nand the program that recognizes B `destruct H0 as (M, H0)`.\n\nThe pen & paper proof says the following:\n\n  On input w:\n  1. Compute f(w).\n  2. Run M on input f(w) and output whatever M outputs    \n\nOur next tactics must be as follows to state that `(fun w => M (f w))`\nrecognizes A.\n\n  exists (fun w => M (f w)).\n\nIn Coq, the high-level description can be state as `(fun w => M (f w))`,\nsince `M` is a program parameterized by an input and\n\"running M on input f(w)\" amounts to calling `M` with argument `f(w)`,\nwritten as `M (f w)`.\n\nNow we apply the theorem `recognizes_def` to show that our program\nrecognizes language `A`. Following we introduce the input as `i`.\n\nOur goal is now to show:\n\n  Run (M (f i)) true <-> A i\n\nRecall that `M` recognizes `B` (assumption `H0`) and\nsince `M (f i)` returns `true`, then we have `B (f i)`;\nusing `rewrite (recognizes_rw H0)` to obtain that fact in the goal\n--- if we use `recognizes_rw` without a parameter Coq will complain\nthat it requires more information.\n\nFinally, we can get rid of `A i` on the right-hand side of the equivalence\nby using our map-reducibly assumption, with `rewrite H`.\n\n\n *)\nTheorem red1:\n  forall A B,\n  A <=m B ->\n  Recognizable B ->\n  Recognizable A.\nProof.\n        intros.\n        unfold Reducible, Reduction in *.\n        destruct H as (f, H).\n        destruct H0 as (M, H0).\n        exists (fun w => M (f w)).\n        apply recognizes_def.\n        intros.\n        rewrite (recognizes_rw H0).\n        rewrite <- H.\n        reflexivity.\nQed.\n\n(**\n\nWe will follow the proof of Theorem 5.22.\n\nFirst, we simplify `Decidable B` as in HW7 and we simplify our\nremaining assumptions as suggested in `red1` until we get the following\nproof state:\n\n  H : forall w, A w <-> B (f w)\n  H0 : Recognizes M B\n  H1 : Decider M\n  ______________________________________(1/1)\n  Decidable A\n\nWe use the same program to decide `A` than we do in exercise `red1`.\nOur proof state is now as follows\n\n  Decides (fun w : input => M (f w)) A\n\nWe use theorem `decides_def` to continue. The first sub-goal proceeds\nexactly like in exercise `red1`.\n\nThe second sub-goal we have the following relevant proof state:\n\n\n  H1: Decider M\n  ______________________________________(1/1)\n  Decider (fun w : input => M (f w))\n\nRecall that a decider halts for all inputs, `f w` is an arbitrary\ninput, thus `M` halts for `f w`. To conclude this goal,\nwrite `unfold Decider in *` and use `H1` to conclude.\n\n\n *)\nTheorem red2:\n  forall A B,\n  A <=m B ->\n  Decidable B ->\n  Decidable A.\nProof.\n        intros.\n        unfold Reducible, Reduction in H.\n        destruct H as (f, H).\n        destruct H0 as (M, H0).\n        destruct H0.\n        exists (fun w => M (f w)).\n        apply decides_def.\n        1: apply recognizes_def.\n        1: intros.\n        1: rewrite (recognizes_rw H0); rewrite <- H; reflexivity.\n        unfold Decider. intros. apply H1.\nQed.\n\n(**\n\nWe will follow Prof. Peter Fejer's proof of problem 5.22:\n\n  https://www.cs.umb.edu/~fejer/cs420/hw11s.pdf\n\nSince our goal is an equivalence, we should start with\n\n  split; intros.\n\nProf. Fejer's proof starts with:\n\n1. \"Let M be a Turing machine that recognizes A.\"\n\nThe first goal, first obtain the parameterized program `p` and\nassumption `H` from `H: Recognizable A`.\n\nWe can convert a parametric program, such as `p`, into an abstract\nTuring machine with\n\n    destruct (code_of p) as (M, Hp).\n\nThis tactics yields an abstract Turing machine `M` and an\nassumption `Hp : CodeOf p M` which establishes the equivalence\nbetween the parametric function `p` and the abstract Turing machine `M`.\n\nWe now have all of the ingredient's to continue Prof. Fejer's proof:\n\n2. \"The function f defined by f (w) =〈M, w〉is a reduction from A to A_tm\"\n\nWe can state that with the tactics:\n\n  apply reducible_iff with (f:=fun i => <[ M, i ]>).\n\nFinally, the last step of Prof. Fejer's proof is as follows:\n\n3. \"because it is obviously computable and we have\"\n\n    \"w ∈ A iff M accepts w iff〈M, w〉 ∈ A_tm iff f (w) ∈ A_tm\"\nWe can show that \"〈M, w〉 ∈ A_tm iff M accepts w\" with rewriting\nwith `a_tm_rw`, since \"M accepts w\" is represented in\nCoq by `Run (Call M w) true`.\n\nWe know that `M` represents function `p`; we replace `Run (Call M w) true`\nby `Run (p w) true` by rewriting with `(code_of_run_rw Hp)`.\n\nFinally, since `p` recognizes `A` we can replace `Run (p w) true` by\n`A w` using `(recognizes_rw H)`.\n\nThe second case is trivial knowing what we proved so far, if you recall\nthat `A_tm` is recognizable, given by a_tm_recognizable. Read Prof. Fejer's\nproof to get the remaining details.\n\n\n *)\nTheorem red3:\n  forall A, Recognizable A <-> A <=m A_tm.\nProof.\n        intros.\n        split.\n        all:intros.\n        1: destruct H as (p, H).\n        1: destruct (code_of p) as (M, Hp).\n        1: apply reducible_iff with (f:=fun i => <[ M, i ]>).\n        1: intros.\n        1: rewrite a_tm_rw.\n        1: rewrite (code_of_run_rw Hp).\n        1: rewrite (recognizes_rw H); reflexivity.\n        Search ( Recognizable).\n        apply red1 with (B:= A_tm) in H.\n        1: assumption.\n        apply a_tm_recognizable.\nQed.\n(**\n\nProve Corollary 5.29.\n\n *)\nTheorem red4:\n  forall A B,\n  A <=m B ->\n  ~ Recognizable A ->\n  ~ Recognizable B.\nProof.\n        intros.\n        intros N.\n        contradict H0.\n        apply red1 in H.\n        1,2: assumption.\nQed.\n\n(**\n\nLet us solve Exercise 5.6 (solution in pp 242).\n\nFirst, we simplify our assumptions to obtain.\n\n  Hab : Reduction f A B\n  Hbc : Reduction g B C\n  ______________________________________(1/1)\n  A <=m C\n\nNow apply reducible_iff and with function `fun w => g (f w))`.\n\nNext, we `unfold Reduction in *`.\n\nThe remainder should be trivial.\n\n\n *)\nTheorem red5:\n  forall A B C,\n  A <=m B ->\n  B <=m C ->\n  A <=m C.\nProof.\n        intros.\n        unfold Reducible, Reduction in *.\n        invc H; invc H0.\n        exists (fun i => x0 (x i)).\n        intros.\n        rewrite <- H.\n        rewrite <- H1.\n        reflexivity.\nQed.\n\n(**\n\nUse theorem `co_red_co_1`, which states\n\n  If A <=m B, then compl A <=m compl B.\n\nand what we have learned so far to prove the following statement.\n\n\n *)\nTheorem red6:\n  forall A B,\n  A <=m B ->\n  Recognizable (compl B) ->\n  Recognizable (compl A).\nProof.\n        intros.\n        apply co_red_co_1 in H.\n        apply red1 in H.\n        all: assumption.\nQed.\n\n(**\n\nUse the theorem `co_red_2`, which states:\n\n  If A <=m compl B, then compl A <=m B\n\nand what we have learned so far to prove the following statement.\n\n\n *)\nTheorem red7:\n  forall A B C,\n  A <=m compl B ->\n  compl B <=m C ->\n  compl A <=m compl C.\nProof.\n        intros.\n        apply co_red_2 in H.\n        apply co_red_co_1 in H0.\n        rewrite co_co_rw in H0.\n        apply red5 with (B:= B).\n        1,2: assumption.\nQed.\n\n(**\n\nUse theorem dec_rec_co_rec which we learned in class and two other\ntheorems we established in this assignment to conclude this proof.\n\n\n *)\nTheorem red8:\n  forall A,\n  Decidable A ->\n  A <=m compl A_tm.\nProof.\n        intros.\n        apply dec_rec_co_rec in H.\n        destruct H.\n        apply red3 in H0.\n        apply co_red_co_1 in H0.\n        rewrite co_co_rw in H0.\n        auto.\nQed.\n\n(**\n\nRecall that A_tm is not recognizable (co_a_tm_not_recognizable).\nShow that if A_tm is map-reducible to A, then the complement of A is not\nrecognizable. Hint use: co_red_co_1.\n\n\n *)\nTheorem red9:\n  forall A,\n  A_tm <=m A ->\n  ~ Recognizable (compl A).\nProof.\n        intros.\n        intros N.\n        apply co_red_co_1 in H.\n        apply red4 in H.\n        1: contradiction.\n        Search A_tm.\n        apply co_a_tm_not_recognizable.\nQed.\n\n(**\n\nShow A_tm is *not* map-reducible to decidable languages.\n\nStart the proof by assuming that A_tm <= A and then reach a contradiction,\nwhich is obtained because we can show that compl A is recognizable and\ncompl A is unrecognizable.\n\n1. We can prove that compl A is recognizable from A decidable.\n2. We can prove that compl A is unrecognizable as follows:\n   We have `compl A_tm <=m compl A_tm` and that `compl A_tm` is unrecognizable,\n   so `compl A` is unrecognizable (which is one of the exercises prove here).\n   The proof is similar to red9. \n\n\n *)\nTheorem red10:\n  forall A,\n  Decidable A ->\n  ~ (A_tm <=m A).\nProof.\n        intros.\n        intros I.\n        apply red9 in I.\n        Search Decidable.\n        apply decidable_to_co_recognizable with (L:= A) in H.\n        contradiction.\nQed.\n\n(**\n\nShow the following trivial statement.\n\n\n *)\nTheorem red11:\n  forall A,\n  Decidable A ->\n  A <=m A_tm.\nProof.\n        intros.\n        Search Decidable.\n        apply decidable_to_recognizable with (L:= A) in H.\n        apply red3 in H.\n        1: assumption.\nQed.\n\n\nTheorem red12:\n  forall A B,\n  Recognizable A ->\n  A_tm <=m B ->\n  A <=m B.\nProof.\n        intros.\n        apply red3 in H.\n        apply red5 with (A:= A) (B:= A_tm) (C:= B) in H.\n        all: auto.\nQed.\n\n(**\n\nWhich language satisfies the following statement?\nAsk for a hint if you are unsure. \n\n\n *)\nTheorem red13:\n  exists A, (A_tm <=m A) /\\ Recognizable A.\nProof.\n        exists A_tm.\n        split.\n        1: unfold Reducible, Reduction.\n        1: exists (fun i=> i).\n        1: intros.\n        1: reflexivity.\n        apply a_tm_recognizable.\nQed.\n\n(**\n\nSolve Exercise 5.7 of the book. The solution given in pp 242 is as follows:\n\n1. Suppose that A <=m compl A. Then compl A <=m A via co_red_2.\n2. Because A is Turing-recognizable, red3 implies that compl A is\n   Turing-recognizable, and then dec_rec_co_rec implies that A is decidable.\n\n\n *)\nTheorem red14:\n  forall A,\n  Recognizable A ->\n  A <=m compl A ->\n  Decidable A.\nProof.\n        intros.\n        apply dec_rec_co_rec.\n        split.\n        1: auto.\n        apply co_red_2 in H0.\n        apply red1 in H0.\n        all: intuition.\nQed.\n\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/hw8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478913248044, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.6736239158768244}}
{"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.\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.\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.", "meta": {"author": "jstzwj", "repo": "LearnCoq", "sha": "2cce1a6d3ac32ef90d1e961a27f6e661cd585646", "save_path": "github-repos/coq/jstzwj-LearnCoq", "path": "github-repos/coq/jstzwj-LearnCoq/LearnCoq-2cce1a6d3ac32ef90d1e961a27f6e661cd585646/bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.6736239133521872}}
{"text": "(**\nプログラミング Coq 証明駆動開発入門(1)\nhttp://www.iij-ii.co.jp/lab/techdoc/coqt/coqt8.html\n\nをSSReflectに書き直した。\nPermutation は SSReflect の相当の補題を使っているため、\n証明の詳細は原著と異なることに注意してください。\n*)\n\n(* ************************************************** *)\n(* nat と ≦ より一般的な、eqType と R で証明を試みる。 *)\n(* ************************************************** *)\n\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Print All.\n\nSection isort.\n  Variables T : eqType.\n  Variables R R' : rel T.\n  Hypothesis complete_conv : forall n m : T, ~ R m n -> R n m.\n\n  (* Permutation, seq.v *)\n  Check perm_eq (1::2::3::nil) (2::1::3::nil).\n  Eval compute in perm_eq (1::2::3::nil) (2::1::3::nil). (* true *)\n  Eval compute in perm_eq nil nil.                       (* true *)\n\n  (* ソート処理の定義 *)\n  Fixpoint insert (a : T) (l : seq T) : seq T :=\n    match l with\n      | nil => a :: nil\n      | x :: xs => if R a x then a :: l else x :: insert a xs\n    end.\n\n  Fixpoint insertion_sort (l : seq T) : seq T :=\n    match l with\n      | nil => nil\n      | x :: xs => insert x (insertion_sort xs)\n    end.\n\n  (* 証明 *)\n  Lemma perm_iff (m n : seq T) :\n    (forall l, perm_eq m l = perm_eq n l) <-> perm_eq m n.\n  Proof.\n    split=> H.\n    - by rewrite H.\n    - by apply/perm_eqlP.\n  Qed.\n\n  Lemma perm_swap : forall (l l' : seq T) (x a : T),\n                      perm_eq [:: x, a & l] l' = perm_eq [:: a, x & l] l'.\n  Proof.\n    move=> l l' x a.\n    apply/perm_iff : l' => //.              (* l' は、perm_iff の左辺の∀のため。 *)\n    rewrite -[[:: x, a & l]]cat1s -[[:: a & l]]cat1s.\n    apply/perm_eqlP.\n      by apply: (perm_catCA [:: x] [:: a] l).\n  Qed.\n\n  Lemma insert_perm : forall (l : seq T) (x : T),\n                        perm_eq (x::l) (insert x l).\n  Proof.\n    elim=> [_ // | a l H x //=].\n    case: (R x a) => [//= |].\n    apply/perm_iff => // l'.\n    rewrite perm_swap => //.\n    apply/perm_iff : l'.\n    by rewrite perm_cons.\n  Qed.\n\n  Theorem isort_permutation : forall (l : seq T),\n                                perm_eq l (insertion_sort l).\n  Proof.\n    elim=> [// | a l H //=].\n    apply: (@perm_eq_trans T (a :: insertion_sort l)).\n(*  apply perm_eq_trans with (y := a :: insertion_sort l). *)\n    + by rewrite perm_cons.\n    + by apply: insert_perm.\n  Qed.\n\n  Inductive LocallySorted : seq T -> Prop :=\n  | LSorted_nil : LocallySorted nil\n  | LSorted_cons1 : forall a : T, LocallySorted (a :: nil)\n  | LSorted_consn : forall (a b : T) (l : seq T),\n                      LocallySorted (b :: l) ->\n                      R a b -> LocallySorted (a :: b :: l).\n  \n  Lemma insert_sorted : forall (a : T) (l : seq T),\n                          LocallySorted l -> LocallySorted (insert a l).\n  Proof.\n    move=> a.\n    elim=> [H //= | a0 l IHl H //=].\n    - by apply: LSorted_cons1.\n    - case Heqb : (R a a0).                 (* remember *)\n      + apply: LSorted_consn.\n        * by [].\n        * by rewrite Heqb.\n(*    + elim: l IHl H => [_ _ |b l0 H1 IHl H]. *)\n      + inversion H.\n        * apply: LSorted_consn.\n          apply: LSorted_cons1.\n          by move: Heqb => /negP /complete_conv.\n        * rewrite -H1 in IHl, H.            (* subst *)\n          rewrite /= in IHl => /=.          (* simpl in IHl; simpl. *)\n          elim H' : (R a b).\n          - apply: LSorted_consn.\n            + by rewrite H' in IHl; apply: IHl. (* apply H2. *)\n            + by move: Heqb => /negP /complete_conv.\n          - apply: LSorted_consn.\n            + by rewrite H' in IHl; apply: IHl. (* apply H2. *)\n            + by [].                            (* apply H3. *)\n  Qed.\n  \n  Theorem isort_sorted : forall (l : seq T),\n                           LocallySorted (insertion_sort l).\n  Proof.\n    elim=> [| a l H //=].\n    - by apply: LSorted_nil.\n    - by apply: insert_sorted.\n  Qed.\n\nEnd isort.\n\nLemma leq_complete_conv : forall n m : nat, ~ (m <= n) -> n <= m.\nProof.\n  move=> n m /negP.\n  rewrite -ltnNge.\n  by apply: ltnW.\nQed.\n\nDefinition nat_isort_sorted := isort_sorted leq_complete_conv.\nCheck nat_isort_sorted :\n  forall l : seq nat, LocallySorted leq (insertion_sort leq l).\n\n(* 以下、参考 *)\nEval compute in insert leq 1 nil.                      (* [:: 1] *)\nEval compute in insert leq 5 [:: 1; 4; 2; 9; 3].       (* [:: 1; 4; 2; 5; 9; 3] *)\nEval compute in insertion_sort leq [:: 2; 4; 1; 5; 3]. (* [:: 1; 2; 3; 4; 5] *)\n\nCheck leq : nat -> nat -> bool.\nCheck leq : nat -> nat -> Prop.\nCheck leq : rel nat : Type.\nCheck le : nat -> nat -> Prop.\nFail Check le : nat -> nat -> bool.\nFail Check le : rel nat.                    (* rel : Type -> Type *)\nCheck LocallySorted leq (1::2::3::nil) : Prop.\nFail Check LocallySorted le (1::2::3::nil) : Prop.\n\nRequire Import path.\n\n(* Sorted, path.v *)\nCheck sorted : forall T : eqType, rel T -> seq T -> bool.\nCheck leq : nat -> nat -> bool.\nCheck leq : nat -> nat -> Prop.\nCheck leq : rel nat : Type.\nCheck le : nat -> nat -> Prop.\nFail Check le : nat -> nat -> bool.\nFail Check le : rel nat.                    (* rel : Type -> Type *)\n\nCheck sorted ltn (1::2::3::nil).\nCheck sorted leq (1::2::3::nil).\nEval compute in sorted leq (1::2::3::nil). (* true *)\nEval compute in sorted leq (3::nil).       (* true *)\nEval compute in sorted leq nil.            (* true *)\nEval compute in sorted leq (2::1::3::nil). (* false *)\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/iii/ssr_isort_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430520409023, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.6736239080599192}}
{"text": "Require Import HoTT.\n(*Require Import Coq.Program.Tactics.*)\n\n\nSection Book_1_4.\nVariable C:Type.\n\n(*Defining the iterator.*)\nFixpoint iter (C:Type) (c0:C) (cs:C->C) (n:nat) : C := \n\tmatch n with\n\t\t|O=>c0\n\t\t|S p => cs (iter C c0 cs p)\nend.\n\n\n(*Make an iterative step function N*C->N*C from the recursive step function cs.*)\nDefinition iter_step (c0:C) (cs : nat->C->C) (p:nat*C) : nat*C :=\n\tmatch p with\n\t\t|(n,c) => (S n, cs n c)\nend.\n\n(*Define recursion in terms of the iterator.*)\nDefinition Rec (c0:C) (cs : nat->C->C) (n:nat) : C :=\n\tsnd (iter (nat*C) (O,c0)  (iter_step c0 cs) n).\n\nLemma iter_formula : forall (n:nat) (c0:C) (cs : nat->C->C), \n  iter (nat*C) (O,c0) (iter_step c0 cs) n = (n, Rec c0 cs n).\nProof.\n  intros n c0 cs.\n  apply equiv_path_prod.\n  simpl.\n  split.\n  * (* First projection *)\n\t\tinduction n.\n\t\t** (*Base case*)\n\t\t\treflexivity.\n\t\t** (*Induction step*)\n\t\t\tsimpl.\n\t\t\trewrite IHn.\n\t\t\treflexivity.\n\t\t\n  * (*Second projection*)\n\t\tinduction n.\n\t\t** (*Base case*)\n\t\t\treflexivity.\n\t\t** (*Induction step*)\n\t\t\tunfold Rec.\n\t\t\treflexivity.\nQed.\n\n(* \n\tinduction n.\n\t* (*base case*) reflexivity.\n\t \n\t* (*step case*)\n\tunfold Rec.\n\tsimpl.\n\trewrite IHn.\n\tsimpl.\n\tunfold iter_step.\n\treflexivity.\nQed.\n *) \nProposition Rec_equals_natrec : forall (c0:C)(cs : nat->C->C)(n:nat), \n  \tRec c0 cs n = nat_rec C c0 cs n.\n\tintros c0 cs.\n\tintro n.\n\t\n\tinduction n.\n\t* reflexivity.\n\t\n\t*\n\tsimpl.\n\trewrite <- IHn.\n\tunfold Rec at 1.\n\tsimpl.\n\trewrite iter_formula.\n\tsimpl.\n\treflexivity.\nQed.\n\n\n(*Alternative way to do it:*)\nLemma step_equation_satisfied : forall (c0:C)(cs : nat->C->C)(n:nat),\n\tRec c0 cs (n.+1) = cs n (Rec c0 cs n).\n\tintros c0 cs n.\n\tunfold Rec at 1.\n\t\n\tsimpl.\n\trewrite (iter_formula).\n\tsimpl.\n\treflexivity.\nQed.\n\nProposition Rec_equals_natrec2 : forall (c0:C)(cs : nat->C->C)(n:nat), \n  \tRec c0 cs n = nat_rec C c0 cs n.\n  \tintros c0 cs n.\n  \tinduction n.\n  \t* reflexivity.\n  \t* \n  \trewrite step_equation_satisfied.\n  \trewrite IHn.\n  \treflexivity.\nQed.\n\nEnd Book_1_4.", "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/exc_1_4_alt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757312, "lm_q2_score": 0.8104789040926009, "lm_q1q2_score": 0.6736239031824954}}
{"text": "(* T1: Programación funcional y métodos elementales de demostración en Coq *)\n\n(* El contenido de la teoría es\n1. Datos y funciones\n   1. Tipos enumerados  \n   2. Booleanos  \n   3. Tipos de las funciones  \n   4. Tipos compuestos  \n   5. Módulos  \n   6. Números naturales  \n2. Métodos elementales de demostración\n   1. Demostraciones por simplificación \n   2. Demostraciones por reescritura \n   3. Demostraciones por análisis de casos *)\n\n(* =====================================================================\n   § 1. Datos y funciones \n   ================================================================== *)\n\n(* =====================================================================\n   §§ 1.1. Tipos enumerados  \n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.1.1. Definir el tipo dia cuyos constructores sean los días\n   de la semana.\n   ------------------------------------------------------------------ *)\n\nInductive dia: Type :=\n  | lunes     : dia\n  | martes    : dia\n  | miercoles : dia\n  | jueves    : dia\n  | viernes   : dia\n  | sabado    : dia\n  | domingo   : dia.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.1.2. Definir la función \n      siguiente_laborable : dia -> dia\n   tal que (siguiente_laborable d) es el día laboral siguiente a d.\n   ------------------------------------------------------------------ *)\n\nDefinition siguiente_laborable (d:dia) : dia:=\n  match d with\n  | lunes     => martes\n  | martes    => miercoles\n  | miercoles => jueves\n  | jueves    => viernes\n  | viernes   => lunes\n  | sabado    => lunes\n  | domingo   => lunes\n  end.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.1.3. Calcular el valor de las siguientes expresiones \n      + siguiente_laborable jueves\n      + siguiente_laborable viernes\n      + siguiente_laborable (siguiente_laborable sabado)\n   ------------------------------------------------------------------ *)\n\nCompute (siguiente_laborable jueves).\n(* ==> viernes : dia *)\n\nCompute (siguiente_laborable viernes).\n(* ==> lunes : dia *)\n\nCompute (siguiente_laborable (siguiente_laborable sabado)).\n(* ==> martes : dia *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.1.4. Demostrar que \n      siguiente_laborable (siguiente_laborable sabado) = martes\n   ------------------------------------------------------------------ *)\n\nExample siguiente_laborable1:\n  siguiente_laborable (siguiente_laborable sabado) = martes.\nProof.\n  simpl.       (* ⊢ martes = martes *)\n  reflexivity. (* ⊢ *)\nQed.\n\n(* =====================================================================\n   §§ 1.2. Booleanos  \n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.2.1. Definir el tipo bool (𝔹) cuyos constructores son true\n   y false. \n   ------------------------------------------------------------------ *)\n\nInductive bool : Type :=\n  | true  : bool\n  | false : bool.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.2.2. Definir la función\n      negacion : bool -> bool\n   tal que (negacion b) es la negacion de b.\n   ------------------------------------------------------------------ *)\n\nDefinition negacion (b:bool) : bool :=\n  match b with\n  | true  => false\n  | false => true\n  end.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.2.3. Definir la función\n      conjuncion : bool -> bool -> bool\n   tal que (conjuncion b1 b2) es la conjuncion de b1 y b2.\n   ------------------------------------------------------------------ *)\n\nDefinition conjuncion (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true  => b2\n  | false => false\n  end.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.2.4. Definir la función\n      disyuncion : bool -> bool -> bool\n   tal que (disyuncion b1 b2) es la disyunción de b1 y b2.\n   ------------------------------------------------------------------ *)\n\nDefinition disyuncion (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true  => true\n  | false => b2\n  end.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.2.5. Demostrar las siguientes propiedades\n      disyuncion true  false = true.\n      disyuncion false false = false.\n      disyuncion false true  = true.\n      disyuncion true  true  = true.\n   ------------------------------------------------------------------ *)\n\nExample disyuncion1: disyuncion true false = true.\nProof. simpl. reflexivity.  Qed.\n\nExample disyuncion2: disyuncion false false = false.\nProof. simpl. reflexivity.  Qed.\n\nExample disyuncion3: disyuncion false true = true.\nProof. simpl. reflexivity.  Qed.\n\nExample disyuncion4: disyuncion true true = true.\nProof. simpl. reflexivity.  Qed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.2.6. Definir los operadores (&&) y (||) como abreviaturas\n   de las funciones conjuncion y disyuncion.\n   ------------------------------------------------------------------ *)\n\nNotation \"x && y\" := (conjuncion x y).\nNotation \"x || y\" := (disyuncion x y).\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.2.7. Demostrar que\n      false || false || true = true.\n   ------------------------------------------------------------------ *)\n\nExample disyuncion5: false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 1.2.1. Definir la función \n      nand : bool -> bool -> bool \n   tal que (nanb x y) se verifica si x e y no son verdaderos.\n\n   Demostrar las siguientes propiedades de nand\n      nand true  false = true.\n      nand false false = true.\n      nand false true  = true.\n      nand true  true  = false.\n   ------------------------------------------------------------------ *)\n\nDefinition nand (b1:bool) (b2:bool) : bool :=\n  negacion (b1 && b2).\n\nExample nand1: nand true false = true.\nProof. simpl. reflexivity. Qed.\n\nExample nand2: nand false false = true.\nProof. simpl. reflexivity. Qed.\n\nExample nand3: nand false true = true.\nProof. simpl. reflexivity. Qed.\n\nExample nand4: nand true true = false.\nProof. simpl. reflexivity. Qed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 1.2.2. Definir la función\n      conjuncion3 : bool -> bool -> bool -> bool\n   tal que (conjuncion3 x y z) se verifica si x, y y z son verdaderos.\n\n   Demostrar las siguientes propiedades de conjuncion3\n      conjuncion3 true  true  true  = true.\n      conjuncion3 false true  true  = false.\n      conjuncion3 true  false true  = false.\n      conjuncion3 true  true  false = false.\n   ------------------------------------------------------------------ *)\n\nDefinition conjuncion3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  b1 && b2 && b3.\n\nExample conjuncion3a: conjuncion3 true true true = true.\nProof. simpl. reflexivity. Qed.\n\nExample conjuncion3b: conjuncion3 false true true = false.\nProof. simpl. reflexivity. Qed.\n\nExample conjuncion3c: conjuncion3 true false true = false.\nProof. simpl. reflexivity. Qed.\n\nExample conjuncion3d: conjuncion3 true true false = false.\nProof. simpl. reflexivity. Qed.\n\n(* =====================================================================\n   §§ 1.3. Tipos de las funciones  \n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.3.1. Calcular el tipo de las siguientes expresiones\n      + true\n      + (negacion true)\n      + negacion\n   ------------------------------------------------------------------ *)\n\nCheck true.\n(* ===> true : bool *)\n\nCheck (negacion true).\n(* ===> negacion true : bool *)\n\nCheck negacion.\n(* ===> negacion : bool -> bool *)\n\n(* =====================================================================\n   §§ 1.4. Tipos compuestos  \n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.4.1. Definir el tipo rva cuyos constructores son rojo, verde\n   y azul. \n   ------------------------------------------------------------------ *)\n\nInductive rva : Type :=\n  | rojo  : rva\n  | verde : rva\n  | azul  : rva.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.4.2. Definir el tipo color cuyos constructores son negro,\n   blanco y primario, donde primario es una función de rva en color.\n   ------------------------------------------------------------------ *)\n\nInductive color : Type :=\n  | negro    : color\n  | blanco   : color\n  | primario : rva -> color.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.4.3. Definir la función\n      monocromático : color -> bool\n   tal que (monocromático c) se verifica si c es monocromático.\n   ------------------------------------------------------------------ *)\n\nDefinition monocromático (c : color) : bool :=\n  match c with\n  | negro      => true\n  | blanco     => true\n  | primario p => false\n  end.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.4.4. Definir la función\n      esRojo : color -> bool\n   tal que (esRojo c) se verifica si c es rojo.\n   ------------------------------------------------------------------ *)\n\nDefinition esRojo (c : color) : bool :=\n  match c with\n  | negro         => false\n  | blanco        => false\n  | primario rojo => true\n  | primario _    => false\n  end.\n\n(* =====================================================================\n   §§ 1.5. Módulos  \n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.5.1. Iniciar el módulo Naturales.\n   ------------------------------------------------------------------ *)\n\nModule Naturales.\n\n(* =====================================================================\n   §§ 1.6. Números naturales  \n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.1. Definir el tipo nat de los números naturales con los\n   constructores 0 (para el 0) y S (para el siguiente).\n   ------------------------------------------------------------------ *)\n  \nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.2. Definir la función\n      pred : nat -> nat\n   tal que (pred n) es el predecesor de n.\n   ------------------------------------------------------------------ *)\n\nDefinition pred (n : nat) : nat :=\n  match n with\n    | O    => O\n    | S n' => n'\n  end.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.3. Finalizar el módulo Naturales.\n   ------------------------------------------------------------------ *)\n\nEnd Naturales.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.4. Calcular el tipo y valor de la expresión \n   (S (S (S (S O)))).\n   ------------------------------------------------------------------ *)\n\nCheck (S (S (S (S O)))).\n(* ===> 4 : nat *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.5. Definir la función\n      menosDos : nat -> nat\n   tal que (menosDos n) es n-2. \n   ------------------------------------------------------------------ *)\n\nDefinition menosDos (n : nat) : nat :=\n  match n with\n    | O        => O\n    | S O      => O\n    | S (S n') => n'\n  end.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.6. Evaluar la expresión (menosDos 4).\n   ------------------------------------------------------------------ *)\n\nCompute (menosDos 4).\n(* ===> 2 : nat *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.7. Calcular et tipo de las funcionse S, pred y menosDos.\n   ------------------------------------------------------------------ *)\n\nCheck S.\n(* ===>  S : nat -> nat *)\n\nCheck pred.\n(* ===> pred : nat -> nat *)\n\nCheck menosDos.\n(* ===> menosDos : nat -> nat *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.8. Definir la función\n      esPar : nat -> bool\n   tal que (esPar n) se verifica si n es par.\n   ------------------------------------------------------------------ *)\n\nFixpoint esPar (n:nat) : bool :=\n  match n with\n  | O        => true\n  | S O      => false\n  | S (S n') => esPar n'\n  end.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.9. Definir la función\n      esImpar : nat -> bool\n   tal que (esImpar n) se verifica si n es impar.\n   ------------------------------------------------------------------ *)\n\nDefinition esImpar (n:nat) : bool :=\n  negacion (esPar n).\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.10. Demostrar que\n      + esImpar 1 = true.\n      + esImpar 4 = false.\n   ------------------------------------------------------------------ *)\n\nExample esImpar1: esImpar 1 = true.\nProof. simpl. reflexivity.  Qed.\n\nExample esImpar2: esImpar 4 = false.\nProof. simpl. reflexivity.  Qed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.12. Iniciar el módulo Naturales2.\n   ------------------------------------------------------------------ *)\n\n(* Module Naturales2. *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.13. Definir la función\n      suma : nat -> nat -> nat \n   tal que (suma n m) es la suma de n y m. Por ejemplo,\n      suma 3 2 = 5\n\n   Nota: Es equivalente a la predefinida plus\n   ------------------------------------------------------------------ *)\n  \nFixpoint suma (n : nat) (m : nat) : nat :=\n  match n with\n    | O    => m\n    | S n' => S (suma n' m)\n  end.\n\nCompute (suma 3 2).\n(* ===> 5: nat *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.14. Definir la función\n      producto : nat -> nat -> nat \n   tal que (producto n m) es el producto de n y m. Por ejemplo,\n      producto 3 2 = 6\n\n   Nota: Es equivalente a la predefinida mult.\n   ------------------------------------------------------------------ *)\n  \nFixpoint producto (n m : nat) : nat :=\n  match n with\n    | O    => O\n    | S n' => suma m (producto n' m)\n  end.\n\nExample producto1: (producto 2 3) = 6.\nProof. simpl. reflexivity.  Qed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.15. Definir la función\n      resta : nat -> nat -> nat \n   tal que (resta n m) es la diferencia de n y m. Por ejemplo,\n      resta 3 2 = 1\n\n   Nota: Es equivalente a la predefinida minus.\n   ------------------------------------------------------------------ *)\n  \nFixpoint resta (n m:nat) : nat :=\n  match (n, m) with\n  | (O   , _)    => O\n  | (S _ , O)    => n\n  | (S n', S m') => resta n' m'\n  end.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.16. Cerrar el módulo Naturales2.\n   ------------------------------------------------------------------ *)\n\n(* End Naturales2. *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.17. Definir la función\n      potencia : nat ->  nat -> nat\n   tal que (potencia x n) es la potencia n-ésima de x. Por ejemplo,\n      potencia 2 3 = 8\n   \n   Nota: En lugar de producto, usar la predefinida mult.\n   ------------------------------------------------------------------ *)\n\nFixpoint potencia (x n : nat) : nat :=\n  match n with\n    | O   => S O\n    | S m => mult x (potencia x m)\n  end.\n\nCompute (potencia 2 3).\n(* ===> 8 : nat *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio 1.6.1. Definir la función\n      factorial : nat -> nat1\n   tal que (factorial n) es el factorial de n. \n      factorial 3 = 6.\n      factorial 5 = mult 10 12\n   ------------------------------------------------------------------ *)\n\nFixpoint factorial (n:nat) : nat := \n  match n with\n  | O    => 1\n  | S n' =>  S n' * factorial n'\n  end.\n\nExample prop_factorial1: factorial 3 = 6.\nProof. simpl. reflexivity.  Qed.\n\nExample prop_factorial2: factorial 5 = mult 10 12.\nProof. simpl. reflexivity.  Qed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.18. Definir los operadores +, - y * como abreviaturas de\n   las funciones plus, rminus y mult.  \n   ------------------------------------------------------------------ *)\n\nNotation \"x + y\" := (plus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x - y\" := (minus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x * y\" := (mult x y)\n                       (at level 40, left associativity)\n                       : nat_scope.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.19. Definir la función\n      iguales_nat : nat -> nat -> bool\n   tal que (iguales_nat n m) se verifica si n y me son iguales.\n   ------------------------------------------------------------------ *)\n\nFixpoint iguales_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' => iguales_nat n' m'\n            end\n  end.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.20. Definir la función\n      menor_o_igual : nat -> nat -> bool\n   tal que (menor_o_igual n m) se verifica si n es menor o igual que m.\n   ------------------------------------------------------------------ *)\n\nFixpoint menor_o_igual (n m : nat) : bool :=\n  match n with\n  | O    => true\n  | S n' => match m with\n            | O    => false\n            | S m' => menor_o_igual n' m'\n            end\n  end.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.6.21. Demostrar las siguientes propiedades\n      + menor_o_igual 2 2 = true.\n      + menor_o_igual 2 4 = true.\n      + menor_o_igual 4 2 = false.\n   ------------------------------------------------------------------ *)\n\nExample menor_o_igual1: menor_o_igual 2 2 = true.\nProof. simpl. reflexivity.  Qed.\n\nExample menor_o_igual2: menor_o_igual 2 4 = true.\nProof. simpl. reflexivity.  Qed.\n\nExample menor_o_igual3: menor_o_igual 4 2 = false.\nProof. simpl. reflexivity.  Qed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 1.6.2. Definir la función\n      menor_nat : nat -> nat -> bool\n   tal que (menor_nat n m) se verifica si n es menor que m.\n\n   Demostrar las siguientes propiedades\n      menor_nat 2 2 = false.\n      menor_nat 2 4 = true.\n      menor_nat 4 2 = false.\n   ------------------------------------------------------------------ *)\n\nDefinition menor_nat (n m : nat) : bool :=\n  negacion (iguales_nat (m-n) 0).\n\nExample menor_nat1: (menor_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\n\nExample menor_nat2: (menor_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\n\nExample menor_nat3: (menor_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\n(* =====================================================================\n   § 2. Métodos elementales de demostración\n   ================================================================== *)\n\n(* =====================================================================\n   § 2.1. Demostraciones por simplificación \n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.1.1. Demostrar que el 0 es el elemento neutro por la\n   izquierda de la suma de los números naturales.\n   ------------------------------------------------------------------ *)\n\n(* 1ª demostración *)\nTheorem suma_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n.    (* n : nat\n                  ============================\n                   0 + n = n *)\n  simpl.       (*  n = n *)\n  reflexivity. \nQed.\n\n(* 2ª demostración *)\nTheorem suma_O_n' : forall n : nat, 0 + n = n.\nProof.\n  intros n.    (* n : nat\n                  ============================\n                  0 + n = n *)\n  reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.1.2. Demostrar que la suma de 1 y n es el siguiente de n.\n   ------------------------------------------------------------------ *)\n\nTheorem suma_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n.     (* n : nat\n                   ============================\n                   1 + n = S n *)\n  simpl.        (* S n = S n *)\n  reflexivity.\nQed.\n\nTheorem suma_1_l' : forall n:nat, 1 + n = S n.\nProof.\n  intros n.     \n  reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.1.3. Demostrar que el producto de 0 por n es 0.\n   ------------------------------------------------------------------ *)\n\nTheorem producto_0_l : forall n:nat, 0 * n = 0.\nProof.\n  intros n.    (* n : nat\n                  ============================\n                  0 * n = 0 *)\n  simpl.       (* 0 = 0 *)\n  reflexivity.\nQed.\n\n(* =====================================================================\n   § 2.2. Demostraciones por reescritura \n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.2.1. Demostrar que si n = m, entonces n + n = m + m.\n   ------------------------------------------------------------------ *)\n\nTheorem suma_iguales : forall n m:nat,\n  n = m ->\n  n + n = m + m.\n\nProof.\n  intros n m.   (* n : nat\n                   m : nat\n                   ============================\n                   n = m -> n + n = m + m *)\n  intros H.     (* n : nat\n                   m : nat\n                   H : n = m\n                   ============================\n                   n + n = m + m *)\n  rewrite H.    (* m + m = m + m *)\n  reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 2.2.1. Demostrar que si n = m y m = o, entonces \n   n + m = m + o.\n   ------------------------------------------------------------------ *)\n\nTheorem suma_iguales_ejercicio : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o H1 H2. (* n : nat\n                         m : nat\n                         o : nat\n                         H1 : n = m\n                         H2 : m = o\n                         ============================\n                         n + m = m + o *)\n  rewrite H1.         (* m + m = m + o *)\n  rewrite H2.         (* o + o = o + o *)\n  reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.2.2. Demostrar que (0 + n) * m = n * m.\n   ------------------------------------------------------------------ *)\n\nTheorem producto_0_mas : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.          (* n : nat\n                          m : nat\n                          ============================\n                         (0 + n) * m = n * m *)\n  rewrite suma_O_n.   (* n * m = n * m *)\n  reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 2.2.2. Demostrar que si m = S n, entonces m * (1 + n) = m * m.\n   ------------------------------------------------------------------ *)\n\nTheorem producto_S_1 : forall n m : nat,\n  m = S n -> m * (1 + n) = m * m.\nProof.\n  intros n m H. (* n : nat\n                   m : nat\n                   H : m = S n\n                   ============================\n                   m * (1 + n) = m * m *)\n  simpl.        (* m * S n = m * m *)\n  rewrite H.    (* S n * S n = S n * S n *)\n  reflexivity.\nQed.\n\n(* =====================================================================\n   § 2.3. Demostraciones por análisis de casos \n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.3.1. Demostrar que n + 1 es distinto de 0.\n   ------------------------------------------------------------------ *)\n\n(* 1º intento *)\nTheorem siguiente_distinto_cero_primer_intento : forall n : nat,\n  iguales_nat (n + 1) 0 = false.\nProof.\n  intros n. (* n : nat\n               ============================\n                iguales_nat (n + 1) 0 = false *)\n  simpl.    (* n : nat\n               ============================\n                iguales_nat (n + 1) 0 = false *)\nAbort.\n\n(* 2º intento *)\nTheorem siguiente_distinto_cero : forall n : nat,\n  iguales_nat (n + 1) 0 = false.\nProof.\n  intros n.             (* n : nat\n                           ============================\n                            iguales_nat (n + 1) 0 = false *)\n  destruct n as [| n']. \n  -                     (*\n                           ============================\n                            iguales_nat (0 + 1) 0 = false *)\n    reflexivity.       \n  -                     (* n' : nat                           \n                           ============================\n                            iguales_nat (S n' + 1) 0 = false *)\n    reflexivity.        \nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.3.2. Demostrar que la negacion es involutiva; es decir, la\n   negacion de la negacion de b es b.\n   ------------------------------------------------------------------ *)\n\nTheorem negacion_involutiva : forall b : bool,\n  negacion (negacion b) = b.\nProof.\n  intros b.      (* \n                    ============================\n                     negacion (negacion b) = b *)\n  destruct b.    \n  -              (* \n                     ============================\n                     negacion (negacion true) = true *)\n    reflexivity.\n  -              (*   \n                    ============================\n                     negacion (negacion false) = false *)   \n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.3.3. Demostrar que la conjuncion es conmutativa.\n   ------------------------------------------------------------------ *)\n\n(* 1ª demostración *)\nTheorem conjuncion_commutativa : forall b c,\n    conjuncion b c = conjuncion c b.\nProof.\n  intros b c.      (* b : bool\n                      c : bool\n                      ============================\n                       b && c = c && b *)\n  destruct b.      \n  -                (* c : bool\n                      ============================\n                       true && c = c && true *)\n    destruct c.    \n    +              (* ============================\n                       true && true = true && true *)\n      reflexivity. \n    +              (* \n                      ============================\n                       true && false = false && true *)\n      reflexivity.\n  -                (* c : bool\n                      ============================\n                       false && c = c && false *)\n    destruct c.    \n    +              (* \n                       ============================\n                       false && true = true && false *)  \n      reflexivity.\n    +              (* \n                      ============================\n                       false && false = false && false *)\n      reflexivity.\nQed.\n\n(* 2ª demostración *)\nTheorem conjuncion_commutativa2 : forall b c,\n    conjuncion b c = conjuncion 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(* ---------------------------------------------------------------------\n   Ejemplo 2.3.4. Demostrar que \n     conjuncion (conjuncion b c) d = conjuncion (conjuncion b d) c.\n   ------------------------------------------------------------------ *)\n\nTheorem conjuncion_intercambio : forall b c d,\n    conjuncion (conjuncion b c) d = conjuncion (conjuncion b d) c.\nProof.\n  intros b c d.\n  destruct b.\n  - destruct c.\n    { destruct d.\n      - reflexivity.   (* (true && true) && true = (true && true) && true *)\n      - reflexivity. } (* (true && true) && false  = (true && false) && true *)\n    { destruct d.      \n      - reflexivity.   (* (true && false) && true = (true && true) && false *)\n      - reflexivity. } (* (true && false) && false = (true && false) && false *)\n  - destruct c.\n    { destruct d.\n      - reflexivity.   (* (false && true) && true = (false && true) && true *)\n      - reflexivity. } (* (false && true) && false = (false && false) && true *)\n    { destruct d.\n      - reflexivity.   (* (false && false) && true = (false && true) && false *)\n      - reflexivity. } (* (false && false) && false = (false && false) && false *)\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.3.5. Demostrar que n + 1 es distinto de 0.\n   ------------------------------------------------------------------ *)\n\nTheorem siguiente_distinto_cero' : forall n : nat,\n  iguales_nat (n + 1) 0 = false.\nProof.\n  intros [|n].\n  - reflexivity. (* iguales_nat (0 + 1) 0 = false *)\n  - reflexivity. (* iguales_nat (S n + 1) 0 = false *)\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.3.6. Demostrar que la conjuncion es conmutativa.\n   ------------------------------------------------------------------ *)\n\nTheorem conjuncion_commutativa'' : forall b c,\n    conjuncion b c = conjuncion c b.\nProof.\n  intros [] [].\n  - reflexivity. (* true  && true  = true  && true *)\n  - reflexivity. (* true  && false = false && true *)\n  - reflexivity. (* false && true  = true  && false *)\n  - reflexivity. (* false && false = false && false *)\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 2.2.3. Demostrar que si \n      conjuncion b c = true, entonces c = true.\n   ------------------------------------------------------------------ *)\n\nTheorem conjuncion_true_elim : forall b c : bool,\n  conjuncion b c = true -> c = true.\nProof.\n  intros b c.      (* b : bool\n                      c : bool\n                      ============================\n                       b && c = true -> c = true *)  \n  destruct c.      \n  -                (* b : bool\n                      ============================\n                       b && true = true -> true = true *)\n    reflexivity.    \n  -                (* b : bool\n                      ============================\n                       b && false = true -> false = true *)\n    destruct b.    \n    +              (* \n                      ============================\n                       true && false = true -> false = true *)\n      simpl.       (*   \n                      ============================\n                       false = true -> false = true *)\n      intros H.    (* H : false = true\n                      ============================\n                       false = true *)\n      rewrite H.   (* H : false = true\n                      ============================\n                       true = true *)\n      reflexivity. \n    +              (* \n                      ============================\n                       false && false = true -> false = true *)\n      simpl.       (* \n                      ============================\n                       false = true -> false = true *)\n      intros H.    (* H : false = true\n                      ============================\n                       false = true *)\n      rewrite H.   (* H : false = true\n                      ============================\n                       true = true *)\n      reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 2.2.4. Demostrar que 0 es distinto de n + 1.\n   ------------------------------------------------------------------ *)\n\nTheorem cero_distinto_mas_uno: forall n : nat,\n  iguales_nat 0 (n + 1) = false.\nProof.\n  intros [| n'].\n  - reflexivity. (* iguales_nat 0 (0 + 1) = false *)\n  - reflexivity. (* iguales_nat 0 (S n' + 1) = false *)\nQed.\n\n(* =====================================================================\n   § 3. Ejercicios complementarios \n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.1. Demostrar que\n      forall (f : bool -> bool),\n        (forall (x : bool), f x = x) -> forall (b : bool), f (f b) = b.\n   ------------------------------------------------------------------ *)\n\nTheorem aplica_dos_veces_la_identidad : forall (f : bool -> bool),\n  (forall (x : bool), f x = x) -> forall (b : bool), f (f b) = b.\nProof.\n  intros f H b. (* f : bool -> bool\n                   H : forall x : bool, f x = x\n                   b : bool\n                   ============================\n                    f (f b) = b *)\n  rewrite H.    (* f b = b *)\n  rewrite H.    (* b = b *)\n  reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.2. Demostrar que\n      forall (b c : bool),\n        (conjuncion b c = disyuncion b c) -> b = c.\n   ------------------------------------------------------------------ *)\n\nTheorem conjuncion_igual_disyuncion: forall (b c : bool),\n  (conjuncion b c = disyuncion b c) -> b = c.\nProof.\n  intros [] c.   \n  -              (* c : bool\n                    ============================\n                     true && c = true || c -> true = c *)\n    simpl.       (* c : bool\n                    ============================\n                     c = true -> true = c *)\n    intros H.    (* c : bool\n                    H : c = true\n                    ============================\n                     true = c *)\n    rewrite H.   (* c : bool\n                    H : c = true\n                    ============================\n                     true = true *)\n    reflexivity. \n  -              (* c : bool\n                    ============================\n                     false && c = false || c -> false = c *)\n    simpl.       (* c : bool\n                    ============================\n                     false = c -> false = c *)\n    intros H.    (* c : bool\n                    H : false = c\n                    ============================\n                     false = c *)\n    rewrite H.   (* c : bool\n                    H : false = c\n                    ============================\n                     c = c *)\n    reflexivity. \nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.3. En este ejercicio se considera la siguiente\n   representación de los números naturales\n      Inductive nat2 : Type :=\n        | C  : nat2\n        | D  : nat2 -> nat2\n        | SD : nat2 -> nat2.\n   donde C representa el cero, D el doble y SD el siguiente del doble.\n\n   Definir la función\n      nat2Anat : nat2 -> nat\n   tal que (nat2Anat x) es el número natural representado por x. \n\n   Demostrar que \n      nat2Anat (SD (SD C))     = 3\n      nat2Anat (D (SD (SD C))) = 6.\n   ------------------------------------------------------------------ *)\n\nInductive nat2 : Type :=\n  | C  : nat2\n  | D  : nat2 -> nat2\n  | SD : nat2 -> nat2.\n \nFixpoint nat2Anat (x:nat2) : nat :=\n  match x with\n  | C    => O\n  | D n  => 2 * nat2Anat n\n  | SD n => (2 * nat2Anat n) + 1\n  end.\n \nExample prop_nat2Anat1: (nat2Anat (SD (SD C))) = 3.\nProof. reflexivity. Qed.\n\nExample prop_nat2Anat2: (nat2Anat (D (SD (SD C)))) = 6.\nProof. reflexivity. Qed.\n\n(* =====================================================================\n   § Bibliografía\n   ================================================================== *)\n\n(*\n + \"Functional programming in Coq\" de Peirce et als. http://bit.ly/2zRCL6t\n *)\n", "meta": {"author": "jaalonso", "repo": "DAOconCoq", "sha": "8546d31ef0827e6191427757737dfca24180f97f", "save_path": "github-repos/coq/jaalonso-DAOconCoq", "path": "github-repos/coq/jaalonso-DAOconCoq/DAOconCoq-8546d31ef0827e6191427757737dfca24180f97f/teorias/T1_PF_en_Coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.6736239016949686}}
{"text": "\nRequire Export Iron.Language.SystemF2Effect.Type.Exp.\nRequire Export Iron.Language.SystemF2Effect.Type.Operator.LiftTT.\nRequire Export Iron.Language.SystemF2Effect.Type.Operator.LowerTT.\nRequire Export Iron.Language.SystemF2Effect.Type.Relation.WfT.\n\n\n(********************************************************************)\n(* Substitution of Types in Types. *)\nFixpoint substTT (d: nat) (u: ty) (tt: ty) : ty \n := match tt with\n    | TVar ix\n    => match nat_compare ix d with\n       | Eq          => u\n       | Gt          => TVar (ix - 1)\n       | _           => TVar  ix\n       end\n\n    |  TForall k t   => TForall k (substTT (S d) (liftTT 1 0 u) t)\n    |  TApp t1 t2    => TApp      (substTT d u t1) (substTT d u t2)\n    |  TSum t1 t2    => TSum      (substTT d u t1) (substTT d u t2)\n    |  TBot k        => TBot k\n\n    | TCon0 tc       => TCon0 tc\n    | TCon1 tc t1    => TCon1 tc  (substTT d u t1)\n    | TCon2 tc t1 t2 => TCon2 tc  (substTT d u t1) (substTT d u t2)\n    | TCap _         => tt\n  end.\n\n\n(********************************************************************)\n(* What might happen when we substitute for a variable.\n   This can be easier use than the raw substTT definition. *)\nLemma substTT_TVar_cases\n :  forall n1 n2 t1\n ,  (substTT n1 t1 (TVar n2) = t1            /\\ n1 = n2)\n \\/ (substTT n1 t1 (TVar n2) = TVar (n2 - 1) /\\ n1 < n2)\n \\/ (substTT n1 t1 (TVar n2) = TVar n2       /\\ n1 > n2).\nProof.\n intros.\n unfold substTT.\n  lift_cases; burn.\nQed. \n\n\nLemma substTT_wfT_above\n :  forall d ix t t2\n ,  WfT d t\n -> substTT (d + ix) t2 t = t.\nProof.\n intros. gen d ix t2.\n induction t; rip; inverts H; simpl; f_equal; burn.\n\n Case \"TVar\".\n  norm; omega.\n  lets D: IHt H1. burn.\nQed.\nHint Resolve substTT_wfT_above.\n\n\nLemma substTT_wfT\n :  forall d ix t1 t2\n ,  ix <= d\n -> WfT (S d) t1\n -> WfT d     t2\n -> WfT d (substTT ix t2 t1).\nProof.\n intros. gen d ix t2.\n induction t1; rip; inverts H0; simpl; snorm.\nQed.\nHint Resolve substTT_wfT.\n\n\n(* Closing substitution of types in types *)\nLemma substTT_closing\n :  forall t1 t2\n ,  WfT 1 t1\n -> ClosedT t2\n -> ClosedT (substTT 0 t2 t1).\nProof. eauto. Qed.\nHint Resolve substTT_closing.\n\n\nLemma substTT_closedT_id\n :  forall d t t2\n ,  ClosedT t\n -> substTT d t2 t = t.\nProof.\n intros. rrwrite (d = d + 0). eauto.\nQed.\nHint Resolve substTT_closedT_id.\n\n\nLemma substTT_liftTT_wfT1\n :  forall t1 t2\n ,  WfT 1 t1\n -> ClosedT t2\n -> substTT 0 t2 t1 = liftTT 1 0 (substTT 0 t2 t1).\nProof.\n intros.\n have    (ClosedT (substTT 0 t2 t1)).\n rrwrite (liftTT 1 0 (substTT 0 t2 t1) = substTT 0 t2 t1).\n trivial.\nQed.\nHint Resolve substTT_liftTT_wfT1.\n\n\n(* Substituting into TBot is still TBot. *)\nLemma substTT_TBot\n : forall d t2 k\n , substTT d t2 (TBot k) = TBot k.\nProof. burn. Qed.\nHint Resolve substTT_TBot.\nHint Rewrite substTT_TBot : global.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Language/SystemF2Effect/Type/Operator/SubstTT/Base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757313, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.6736238993777538}}
{"text": "(** * The category of finite sets\n\nAuthor: Langston Barrett (@siddharthist)\n\n*)\n\n\n(** ** Contents:\n\n- The univalent category [FinSet] of finite sets/types\n- (Co)limits\n  - Colimits\n    - Binary coproducts\n  - Limits\n    - Binary products\n\n*)\n\nRequire Import UniMath.Foundations.PartD.\nRequire Import UniMath.Combinatorics.FiniteSets.\n\n(* Basics *)\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Univalence.\nRequire Import UniMath.CategoryTheory.Core.Functors.\n\n(* HSET *)\nRequire Import UniMath.CategoryTheory.categories.HSET.Core.\nRequire Import UniMath.CategoryTheory.categories.HSET.Limits.\nRequire Import UniMath.CategoryTheory.categories.HSET.Colimits.\nRequire Import UniMath.CategoryTheory.categories.HSET.Univalence.\n\n(* Lemmas about forming (full) subcategories *)\nRequire Import UniMath.CategoryTheory.Subcategory.Core.\nRequire Import UniMath.CategoryTheory.Subcategory.Full.\n\n(* Limits *)\nRequire Import UniMath.CategoryTheory.Subcategory.Limits.\nRequire Import UniMath.CategoryTheory.limits.binproducts.\nRequire Import UniMath.CategoryTheory.limits.bincoproducts.\n\nLocal Open Scope cat.\nLocal Open Scope functions.\n\n(** ** The univalent category [FinSet] of finite sets/types *)\n\n(** This could be defined in three ways:\n    1. as a subcategory of [type_precat],\n    2. as a subcategory of [HSET] (see [isfinite_isaset]), or\n    3. as a regular precategory.\n\n    We choose the second due to the ability to inherit many structures from [HSET].\n *)\nDefinition finite_subtype : hsubtype (ob HSET) := isfinite ∘ pr1hSet.\nDefinition FinSet : univalent_category :=\n  subcategory_univalent HSET_univalent_category finite_subtype.\n\n(** ** (Co)limits *)\n\n(** *** Colimits *)\n\n(** **** Binary coproducts *)\n\n(** The coproduct of finite sets is finite, so the predicate \"is finite\" is closed\n    under the formation of coproducts. Therefore, FinSet inherits coproducts from HSET. *)\nDefinition BinCoproductsFinSet : BinCoproducts FinSet.\nProof.\n  apply (@bin_coproducts_in_full_subcategory HSET_univalent_category\n                                             finite_subtype BinCoproductsHSET).\n  intros; apply isfinitecoprod; assumption.\nDefined.\n\n(** *** Limits *)\n\n(** **** Binary products *)\n\n(** The product of finite sets is finite, so the predicate \"is finite\" is closed\n    under the formation of products. Therefore, FinSet inherits products from HSET. *)\nDefinition BinProductsFinSet : BinProducts FinSet.\nProof.\n  apply (@bin_products_in_full_subcategory HSET_univalent_category\n                                           finite_subtype BinProductsHSET).\n  intros; apply isfinitedirprod; assumption.\nDefined.", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/CategoryTheory/categories/FinSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6736238987199149}}
{"text": "Require Import Coq.Bool.Bool.\nRequire Import Coq.Strings.String.\n\nRequire Import Hapsl.Ascii.Equality.\n\nImport AsciiEqualityNotations.\n\n\n(* Returns true if two strings are equivalent, otherwise returns false. *)\nFixpoint beq_string (s1 s2 : string) : bool :=\n  match s1, s2 with\n  | EmptyString, EmptyString => true\n  | String c1 s1', String c2 s2' => andb (c1 ==_a c2) (beq_string s1' s2')\n  | _, _ => false\n  end.\n\n(* Proves the reflexivity of boolean string equality. *)\nLemma beq_string_reflexive : forall (s : string),\n  beq_string s s = true.\nProof.\n  intros.\n  induction s as [| h tail IH].\n  + reflexivity.\n  + unfold beq_string.\n    rewrite beq_ascii_reflexive.\n    auto.\nQed.\n\n(* TODO: Symmetry of beq_string? *)\n\n(* TODO: Transitivity of beq_string? *)\n\n(* Equality notations module for ASCII strings. *)\nModule StringEqualityNotations.\n\n  (* String equality operator. *)\n  Notation \"a ==_s b\" := (beq_string a b) (at level 30).\n\nEnd StringEqualityNotations.\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/Equality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6736126532605596}}
{"text": "(* BEGIN FIX *)\nRequire Import Coq.Strings.String.\n\nInductive aexp : Type :=\n  | ANum (n : nat)\n  | AVar (x : string)\n  | APlus (a a' : aexp)\n  | AMult (a a' : aexp).\n\nDefinition state : Type := string -> nat.\n\nFixpoint aeval (e : aexp)(s : state) : nat := match e with\n  | ANum n => n\n  | AVar x => s x\n  | APlus a a' => aeval a s + aeval a' s\n  | AMult a a' => aeval a s * aeval a' s\n  end.\n\nInductive zart : aexp -> Prop :=\n  | szam (n : nat) : zart (ANum n)\n  | osszeg (a a' : aexp)(az : zart a)\n           (a'z : zart a') : zart (APlus a a')\n  | szorzat (a a' : aexp)(az : zart a)\n            (a'z : zart a') : zart (AMult a a').\n\nLemma zartPlusMult (e1 e2 : aexp)(p1 : zart e1)(p2 : zart e2) :\n  zart (APlus e1 (AMult e1 e2)).\nProof.\n  exact (osszeg e1 (AMult e1 e2) p1 (szorzat e1 e2 p1 p2)).\nQed.\n(* END FIX *)\n\n(* BEGIN FIX *)\nTheorem evalZart (a : aexp)(q : zart a)(s1 s2 : state) :\n  aeval a s1 = aeval a s2.\nProof.\n  induction q; trivial.\n  simpl. rewrite IHq1. rewrite IHq2. trivial.\n  simpl. rewrite IHq1. rewrite IHq2. trivial.\nQed.\n(* END FIX *)\n\n(* BONUS! use assert and discriminate!\nLemma lem (p : forall e1 e2, aeval e1 empty = aeval e2 empty -> e1 = e2) : False.\n *)", "meta": {"author": "Anabra", "repo": "Formal-Semantics", "sha": "e72f9999aae6ee5cb7eeffc0d8619db7cebecbc1", "save_path": "github-repos/coq/Anabra-Formal-Semantics", "path": "github-repos/coq/Anabra-Formal-Semantics/Formal-Semantics-e72f9999aae6ee5cb7eeffc0d8619db7cebecbc1/kiszh7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6736126504591674}}
{"text": "(* Reference: https://www.cs.umd.edu/~rrand/vqc/Complex.html *)\n\nRequire Import Psatz.\nRequire Import Arith.\nRequire Import Setoid.\nRequire Import Bool.\nRequire Import Program.\nRequire Export Coq.ZArith.ZArith.\n\n(* ZSum and its properties *)\nOpen Scope Z_scope.\n\nFixpoint Zsum (f : nat -> Z) (n : nat) : Z := \n  match n with\n  | O => 0\n  | S n' => Zsum f n' +  f n'\n  end.\n\nLemma Zsum_eq : forall (f g : nat -> Z) (n : nat),\n  (forall x, (x < n)%nat -> f x = g x) ->\n  Zsum f n = Zsum 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 func_shift: forall (f: nat -> Z)(n: nat),\n  exists g, (forall x, (x < n)%nat -> f (x + n)%nat = g x).\nProof.\n  intros.\n  exists (fun x => f (x + n)%nat).\n  tauto.\nQed.  \n\nLemma Zsum_g_g': forall (n : nat) (g g' : nat -> Z),\n  (forall x : nat, (x < n)%nat -> g (S x) = g' x) ->\n  Zsum g (S n) = g 0%nat + Zsum g' n.\nProof.\n  intros.\n  induction n.\n  + simpl. \n    lia.\n  + assert (forall x : nat, (x < n)%nat -> g (S x) = g' x). {\n      intros.\n      assert ((x < S n)%nat). { lia. }\n      pose proof (H x H1). clear H1.\n      tauto.\n    }\n    pose proof (IHn H0).\n    replace (Zsum g (S (S n))) with (Zsum g (S n) + g (S n)) by reflexivity.\n    rewrite H1.\n    simpl.\n    assert ((n < S n)%nat). { lia. }\n    pose proof (H n H2).\n    rewrite H3.\n    lia.\nQed.\n\nLemma Zsum_f_g: forall (n : nat) (f g g' : nat -> Z),\n  (forall x : nat, (x < S n)%nat -> f (x + S n)%nat = g' x) -> \n  (forall x : nat, (x < n)%nat -> f (x + n)%nat = g x) ->\n  Zsum g n + f (2 * n)%nat = f n + Zsum g' n.\nProof.\n  intros.\n  destruct n.\n  + simpl.\n    lia.\n  + replace (Zsum g' (S n)) with (Zsum g' n + g' n) by reflexivity.\n    assert ((n < S (S n))%nat). { lia. }\n    pose proof (H n H1). clear H1.\n    rewrite <- H2.\n    assert ((2 * S n = n + S (S n))%nat). { lia. }\n    rewrite <- H1.\n    assert (forall x : nat, (x < n)%nat -> g (S x) = g' x). {\n      intros.\n      assert ((S x < S n)%nat). { lia. }\n      assert ((x < S (S n))%nat). { lia. }\n      specialize (H x H5).\n      specialize (H0 (S x) H4).\n      rewrite <- H.\n      rewrite <- H0.\n      assert ((S x + S n = x + S (S n))%nat). { lia. }\n      rewrite H6.\n      reflexivity.\n    }\n  pose proof (Zsum_g_g' n g g' H3).\n  rewrite H4.\n  assert ((0 < S n)%nat). { lia. }\n  pose proof (H0 0%nat H5).\n  rewrite <- H6.\n  simpl.\n  lia.\nQed.\n\nLemma Zsum_eq_seg: forall (f: nat -> Z)(n : nat),\n  forall (g: nat -> Z), (forall x, (x < n)%nat -> f (x + n)%nat = g x) ->\n  Zsum f (2 * n) = Zsum f n + Zsum g n.\nProof.\n  intros f n.\n  induction n.\n  + tauto.\n  + intros g' ?. \n    (* Zsum f  (2n + 2) -> Zsum f (2n + 1) + f (2n + 1) *)\n    (* Zsum f  (n + 1)  -> Zsum f n + f n *)\n    (* Zsum g' (n + 1)  -> Zsum g' n + g' n *)\n    simpl.\n    pose proof func_shift f n.\n    destruct H0 as [g ?].\n    specialize (IHn g H0).\n    assert ((n + S (n + 0))%nat = S (2 * n)). {\n      simpl. lia.\n    }\n    rewrite H1. clear H1.\n\n    (* Zsum f (2n + 1) -> Zsum f (2n) + f (2n) *)\n    simpl.\n    assert ((n + (n + 0))%nat = (2 * n)%nat). { lia. }\n    rewrite H1. clear H1.\n\n    (* use IHn: Zsum f (2n) = Zsum f n + Zsum g n *)\n    rewrite IHn.\n    assert ((n < S n)%nat). { lia. }\n    pose proof H n H1.\n    assert ((n + S n)%nat = S (2 * n)). {\n      lia.\n    }\n\n    (* f (2n + 1) = g' n *)\n    assert (f (S (2 * n)) = g' n). {\n      rewrite <- H3.\n      rewrite H2.\n      reflexivity.\n    }\n    rewrite H4. clear H2 H3 H4.\n\n    (* Zsum g n + f (2 * n)%nat = f n + Zsum g' n *)\n    pose proof (Zsum_f_g n f g g' H H0).\n    replace (Zsum f n + Zsum g n + f (2 * n)%nat + g' n) with (Zsum f n + (Zsum g n + f (2 * n)%nat) + g' n).\n    2: { lia. }\n    rewrite H2.\n    lia.\nQed.\n\nLemma Zsum_plus : forall (f g : nat -> Z) (n : nat),\n    Zsum (fun x => f x + g x) n = Zsum f n + Zsum g n.  \nProof. \n  intros f g n.  \n  induction n.  \n  - simpl. lia.  \n  - simpl. rewrite IHn. lia.  \nQed.\n\nLemma Zsum_minus : forall (f g : nat -> Z) (n : nat),\n    Zsum (fun x => f x - g x) n = Zsum f n - Zsum g n.  \nProof. \n  intros f g n.  \n  induction n.  \n  - simpl. lia.  \n  - simpl. rewrite IHn. lia.  \nQed.\n\nLemma Zmult_plus_distr_l : forall c1 c2 c3:Z, c1 * (c2 + c3) = c1 * c2 + c1 * c3.\nProof. intros. lia. Qed.\n\nLemma Zmult_plus_distr_r : forall c1 c2 c3:Z, (c1 + c2) * c3 = c1 * c3 + c2 * c3.\nProof. intros. lia. Qed.\n\nLemma Zmult_minus_distr_l : forall c1 c2 c3:Z, c1 * (c2 - c3) = c1 * c2 - c1 * c3.\nProof. intros. lia. Qed.\n\nLemma Zmult_minus_distr_r : forall c1 c2 c3:Z, (c1 - c2) * c3 = c1 * c3 - c2 * c3.\nProof. intros. lia. Qed.\n\n\nLemma Zsum_mult_l : forall (c : Z) (f : nat -> Z) (n : nat),\n    c * Zsum f n = Zsum (fun x => c * f x) n.  \nProof.  \n  intros c f n.  \n  induction n.  \n  - simpl; lia.  \n  - simpl.  \n    rewrite Zmult_plus_distr_l.  \n    rewrite IHn.  \n    reflexivity.  \nQed.\n\nLemma Zsum_eq_bounded : forall f g n, (forall x, (x < n)%nat -> f x = g x) -> Zsum f n = Zsum 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 Zmult_plus_dist_l (x y z : Z) : x * (y + z) = x * y + x * z.\nProof.\n  lia.\nQed.\n\nLemma Zmult_plus_dist_r (x y z : Z) : (x + y) * z = x * z + y * z.\nProof.\n  lia.\nQed.\n\nLemma Zmult_minus_dist_l (x y z : Z) : x * (y - z) = x * y - x * z.\nProof.\n  lia.\nQed.\n\nLemma Zmult_minus_dist_r (x y z : Z) : (x - y) * z = x * z - y * z.\nProof.\n  lia.\nQed.\n\nClose Scope Z_scope.\n(* End of ZSum *)\n\n(* Haoxuan Xu, Yichen Tao *)\n(* 2021-05-26 14:12 *)", "meta": {"author": "TerryXhx", "repo": "Correctness-of-Strassen-Algorithm", "sha": "b27bf99233a76e4b3b7dbd1936c03243829024ec", "save_path": "github-repos/coq/TerryXhx-Correctness-of-Strassen-Algorithm", "path": "github-repos/coq/TerryXhx-Correctness-of-Strassen-Algorithm/Correctness-of-Strassen-Algorithm-b27bf99233a76e4b3b7dbd1936c03243829024ec/ZSum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.673612650405223}}
{"text": "Require Import HProp HFiber HSet.\nRequire Import PathAny.\nRequire Export Classes.interfaces.abstract_algebra.\nRequire Export Classes.theory.groups.\nRequire Import Pointed.Core.\nRequire Import WildCat.\n\nLocal Set Polymorphic Inductive Cumulativity.\n\nGeneralizable Variables G H A B C f g.\n\nDeclare Scope group_scope.\n\n(** ** Groups *)\n\nLocal Open Scope pointed_scope.\nLocal Open Scope mc_mult_scope.\nLocal Open Scope wc_iso_scope.\n\n(** * Definition of Group *)\n\n(** A group consists of a type, and operation on that type, and unit and an inverse, such that they satisfy the group axioms in IsGroup. *)\nRecord Group := {\n  group_type : Type;\n  group_sgop : SgOp group_type;\n  group_unit : MonUnit group_type;\n  group_inverse : Negate group_type;\n  group_isgroup : IsGroup group_type;\n}.\n\nArguments group_sgop {_}.\nArguments group_unit {_}.\nArguments group_inverse {_}.\nArguments group_isgroup {_}.\n(** We should never need to unfold the proof that something is a group. *)\nGlobal Opaque group_isgroup.\n\n(** We coerce groups back to types. *)\nCoercion group_type : Group >-> Sortclass.\nGlobal Existing Instances group_sgop group_unit group_inverse group_isgroup.\n\nDefinition issig_group : _ <~> Group\n  := ltac:(issig).\n\n(** * Proof automation *)\n(** Many times in group theoretic proofs we want some form of automation for obvious identities. Here we implement such a behaviour. *)\n\n(** We create a database of hints for the group theory library *)\nCreate HintDb group_db.\n\n(** Our group laws can be proven easily with tactics such as [rapply associativity]. However this requires a typeclass search on more general algebraic structures. Therefore we explicitly list many groups laws here so that coq can use them. We also create hints for each law in our groups database. *)\nSection GroupLaws.\n  Context {G : Group} (x y z : G).\n\n  Definition grp_assoc := associativity x y z.\n  Definition grp_unit_l := left_identity x.\n  Definition grp_unit_r := right_identity x.\n  Definition grp_inv_l := left_inverse x.\n  Definition grp_inv_r := right_inverse x.\n\nEnd GroupLaws.\n\n#[export] Hint Immediate grp_assoc  : group_db.\n#[export] Hint Immediate grp_unit_l : group_db.\n#[export] Hint Immediate grp_unit_r : group_db.\n#[export] Hint Immediate grp_inv_l  : group_db.\n#[export] Hint Immediate grp_inv_r  : group_db.\n\n(** Given path types in a product we may want to decompose. *)\n#[export] Hint Extern 5 (@paths (_ * _) _ _) => (apply path_prod) : group_db.\n(** Given path types in a sigma type of a hprop family (i.e. a subset) we may want to decompose. *)\n#[export] Hint Extern 6 (@paths (sig _) _ _) => (rapply path_sigma_hprop) : group_db.\n\n(** We also declare a tactic (notation) for automatically solving group laws *)\n(** TODO: improve this tactic so that it also rewrites and is able to solve basic group lemmas. *)\nTactic Notation \"grp_auto\" := hnf; intros; eauto with group_db.\n\n(** Groups are pointed sets with point the identity. *)\nGlobal Instance ispointed_group (G : Group)\n  : IsPointed G := @mon_unit G _.\n\nDefinition ptype_group : Group -> pType\n  := fun G => [G, _].\nCoercion ptype_group : Group >-> pType.\n\n(** * Some basic properties of groups *)\n\n(** An element acting like the identity is unique. *)\nDefinition identity_unique {A : Type} {Aop : SgOp A}\n  (x y : A) {p : LeftIdentity Aop x} {q : RightIdentity Aop y}\n  : x = y := (q x)^ @ p y.\n\nDefinition identity_unique' {A : Type} {Aop : SgOp A}\n  (x y : A) {p : LeftIdentity Aop x} {q : RightIdentity Aop y}\n  : y = x := (identity_unique x y)^.\n\n(** An element acting like an inverse is unique. *)\nDefinition inverse_unique `{IsMonoid A}\n  (a x y : A) {p : x * a = mon_unit} {q : a * y = mon_unit}\n  : x = y.\nProof.\n  refine ((right_identity x)^ @ ap _ q^ @ _).\n  refine (associativity _ _ _ @ _).\n  refine (ap (fun x => x * y) p @ _).\n  apply left_identity.\nDefined.\n\n(** ** Group homomorphisms *)\n\n(* A group homomorphism consists of a map between groups and a proof that the map preserves the group operation. *)\nRecord GroupHomomorphism (G H : Group) := Build_GroupHomomorphism' {\n  grp_homo_map : G -> H;\n  grp_homo_ishomo :> IsMonoidPreserving grp_homo_map;\n}.\n\n(* We coerce a homomorphism to its underlying map. *)\nCoercion grp_homo_map : GroupHomomorphism >-> Funclass.\nGlobal Existing Instance grp_homo_ishomo.\n\n(* Group homomorphisms are pointed maps *)\nDefinition pmap_GroupHomomorphism {G H : Group} (f : GroupHomomorphism G H) : G ->* H\n  := Build_pMap G H f (@monmor_unitmor _ _ _ _ _ _ _ (@grp_homo_ishomo G H f)).\nCoercion pmap_GroupHomomorphism : GroupHomomorphism >-> pForall.\n\nDefinition issig_GroupHomomorphism (G H : Group) : _ <~> GroupHomomorphism G H\n  := ltac:(issig).\n\nDefinition equiv_path_grouphomomorphism {F : Funext} {G H : Group}\n  {g h : GroupHomomorphism G H} : g == h <~> g = h.\nProof.\n  refine ((equiv_ap (issig_GroupHomomorphism G H)^-1 _ _)^-1 oE _).\n  refine (equiv_path_sigma_hprop _ _ oE _).\n  apply equiv_path_forall.\nDefined.\n\nGlobal Instance ishset_grouphomomorphism {F : Funext} {G H : Group}\n  : IsHSet (GroupHomomorphism G H).\nProof.\n  intros f g; apply (istrunc_equiv_istrunc _ equiv_path_grouphomomorphism).\nDefined.\n\n(** * Some basic properties of group homomorphisms *)\n\n(** Group homomorphisms preserve identities *)\nDefinition grp_homo_unit {G H} (f : GroupHomomorphism G H)\n  : f (mon_unit) = mon_unit.\nProof.\n  apply monmor_unitmor.\nDefined.\n#[export] Hint Immediate grp_homo_unit : group_db.\n\n(** Group homomorphisms preserve group operations *)\nDefinition grp_homo_op {G H} (f : GroupHomomorphism G H)\n  : forall x y : G, f (x * y) = f x * f y.\nProof.\n  apply monmor_sgmor.\nDefined.\n#[export] Hint Immediate grp_homo_op : group_db.\n\n(** Group homomorphisms preserve inverses *)\nDefinition grp_homo_inv {G H} (f : GroupHomomorphism G H)\n  : forall x, f (- x) = -(f x).\nProof.\n  intro x.\n  apply (inverse_unique (f x)).\n  + refine (_ @ grp_homo_unit f).\n    refine ((grp_homo_op f (-x) x)^ @ _).\n    apply ap.\n    apply grp_inv_l.\n  + apply grp_inv_r.\nDefined.\n#[export] Hint Immediate grp_homo_inv : group_db.\n\n(** When building a group homomorphism we only need that it preserves the group operation, since we can prove that the identity is preserved. *)\nDefinition Build_GroupHomomorphism {G H : Group}\n  (f : G -> H) {h : IsSemiGroupPreserving f}\n  : GroupHomomorphism G H.\nProof.\n  srapply (Build_GroupHomomorphism' _ _ f).\n  split.\n  1: exact h.\n  unfold IsUnitPreserving.\n  apply (group_cancelL (f mon_unit)).\n  refine (_ @ (grp_unit_r _)^).\n  refine (_ @ ap _ (monoid_left_id _ mon_unit)).\n  symmetry.\n  apply h.\nDefined.\n\nDefinition grp_homo_id {G : Group} : GroupHomomorphism G G\n  := Build_GroupHomomorphism idmap.\n\nDefinition grp_homo_compose {G H K : Group}\n  : GroupHomomorphism H K -> GroupHomomorphism G H -> GroupHomomorphism G K.\nProof.\n  intros f g.\n  srapply (Build_GroupHomomorphism (f o g)).\nDefined.\n\nDefinition grp_homo_const {G H : Group} : GroupHomomorphism G H.\nProof.\n  snrapply Build_GroupHomomorphism.\n  - exact (fun _ => mon_unit).\n  - intros x y.\n    exact (grp_unit_l mon_unit)^.\nDefined.\n\n(* An isomorphism of groups is a group homomorphism that is an equivalence. *)\nRecord GroupIsomorphism (G H : Group) := Build_GroupIsomorphism {\n  grp_iso_homo : GroupHomomorphism G H;\n  isequiv_group_iso : IsEquiv grp_iso_homo;\n}.\n\n(* We can build an isomorphism from an operation preserving equivalence. *)\nDefinition Build_GroupIsomorphism' {G H : Group}\n  (f : G <~> H) (h : IsSemiGroupPreserving f)\n  : GroupIsomorphism G H.\nProof.\n  srapply Build_GroupIsomorphism.\n  1: srapply Build_GroupHomomorphism.\n  exact _.\nDefined.\n\nCoercion grp_iso_homo : GroupIsomorphism >-> GroupHomomorphism.\nGlobal Existing Instance isequiv_group_iso.\n\nDefinition issig_GroupIsomorphism (G H : Group)\n  : _ <~> GroupIsomorphism G H := ltac:(issig).\n\nDefinition equiv_groupisomorphism {G H : Group}\n  : GroupIsomorphism G H -> G <~> H\n  := fun f => Build_Equiv G H f _.\n\nDefinition pequiv_groupisomorphism {A B : Group}\n  : GroupIsomorphism A B -> (A <~>* B)\n  := fun f => Build_pEquiv _ _ f _.\n\nCoercion equiv_groupisomorphism : GroupIsomorphism >-> Equiv.\n\nDefinition equiv_path_groupisomorphism `{F : Funext} {G H : Group}\n  (f g : GroupIsomorphism G H)\n  : f == g <~> f = g.\nProof.\n  refine ((equiv_ap (issig_GroupIsomorphism G H)^-1 _ _)^-1 oE _).\n  refine (equiv_path_sigma_hprop _ _ oE _).\n  apply equiv_path_grouphomomorphism.\nDefined.\n\nDefinition ishset_groupisomorphism `{F : Funext} {G H : Group}\n  : IsHSet (GroupIsomorphism G H).\nProof.\n  intros f g; apply (istrunc_equiv_istrunc _ (equiv_path_groupisomorphism _ _)).\nDefined.\n\nDefinition grp_iso_id {G : Group} : GroupIsomorphism G G\n  := Build_GroupIsomorphism _ _ grp_homo_id _.\n\nDefinition grp_iso_compose {G H K : Group}\n  (g : GroupIsomorphism H K) (f : GroupIsomorphism G H)\n  : GroupIsomorphism G K\n  := Build_GroupIsomorphism _ _ (grp_homo_compose g f) _.\n\nDefinition grp_iso_inverse {G H : Group}\n  : GroupIsomorphism G H -> GroupIsomorphism H G.\nProof.\n  intros [f e].\n  srapply Build_GroupIsomorphism.\n  - srapply (Build_GroupHomomorphism f^-1).\n  - exact _.\nDefined.\n\n(** Group Isomorphisms are a reflexive relation *)\nGlobal Instance reflexive_groupisomorphism\n  : Reflexive GroupIsomorphism\n  := fun G => grp_iso_id.\n\n(** Group Isomorphisms are a symmetric relation *)\nGlobal Instance symmetric_groupisomorphism\n  : Symmetric GroupIsomorphism\n  := fun G H => grp_iso_inverse.\n\nGlobal Instance transitive_groupisomorphism\n  : Transitive GroupIsomorphism\n  := fun G H K f g => grp_iso_compose g f.\n\n(** Under univalence, equality of groups is equivalent to isomorphism of groups. *)\nDefinition equiv_path_group' {U : Univalence} {G H : Group}\n  : GroupIsomorphism G H <~> G = H.\nProof.\n  refine (equiv_compose'\n    (B := sig (fun f : G <~> H => IsMonoidPreserving f)) _ _).\n  { revert G H; apply (equiv_path_issig_contr issig_group).\n    + intros [G [? [? [? ?]]]].\n      exists 1%equiv.\n      exact _.\n    + intros [G [op [unit [neg ax]]]]; cbn.\n      contr_sigsig G (equiv_idmap G).\n      srefine (Build_Contr _ ((_;(_;(_;_)));_) _); cbn.\n      1: assumption.\n      1: exact _.\n      intros [[op' [unit' [neg' ax']]] eq].\n      apply path_sigma_hprop; cbn.\n      refine (@ap _ _ (fun x : { oun :\n        { oo : SgOp G & { u : MonUnit G & Negate G}}\n        & @IsGroup G oun.1 oun.2.1 oun.2.2}\n        => (x.1.1 ; x.1.2.1 ; x.1.2.2 ; x.2))\n        ((op;unit;neg);ax) ((op';unit';neg');ax') _).\n      apply path_sigma_hprop; cbn.\n      srefine (path_sigma' _ _ _).\n      1: funext x y; apply eq.\n      rewrite transport_const.\n      srefine (path_sigma' _ _ _).\n      1: apply eq.\n      rewrite transport_const.\n      funext x.\n      exact (preserves_negate (f:=idmap) _). }\n  refine (_ oE (issig_GroupIsomorphism G H)^-1).\n  refine (_ oE (equiv_functor_sigma' (issig_GroupHomomorphism G H)\n    (fun f => 1%equiv))^-1).\n  refine (equiv_functor_sigma' (issig_equiv G H) (fun f => 1%equiv) oE _).\n  cbn.\n  refine (\n    equiv_adjointify\n      (fun f => (exist (IsMonoidPreserving o pr1)\n        (exist IsEquiv f.1.1 f.2) f.1.2))\n      (fun f => (exist (IsEquiv o pr1)\n        (exist IsMonoidPreserving f.1.1 f.2) f.1.2))\n       _ _).\n  all: intros [[]]; reflexivity.\nDefined.\n\n(** A version with nicer universe variables. *)\nDefinition equiv_path_group@{u v | u < v} {U : Univalence} {G H : Group@{u}}\n  : GroupIsomorphism G H <~> (paths@{v} G H)\n  := equiv_path_group'.\n\n(** * Simple group equivalences *)\n\n(** Left multiplication is an equivalence *)\nGlobal Instance isequiv_group_left_op {G : Group}\n  : forall (x : G), IsEquiv (x *.).\nProof.\n  intro x.\n  srapply isequiv_adjointify.\n  1: exact (-x *.).\n  all: intro y.\n  all: refine (grp_assoc _ _ _ @ _ @ grp_unit_l y).\n  all: refine (ap (fun x => x * y) _).\n  1: apply grp_inv_r.\n  apply grp_inv_l.\nDefined.\n\n(** Right multiplication is an equivalence *)\nGlobal Instance isequiv_group_right_op (G : Group)\n  : forall (x : G), IsEquiv (fun y => y * x).\nProof.\n  intro x.\n  srapply isequiv_adjointify.\n  1: exact (fun y => y * - x).\n  all: intro y.\n  all: refine ((grp_assoc _ _ _)^ @ _ @ grp_unit_r y).\n  all: refine (ap (y *.) _).\n  1: apply grp_inv_l.\n  apply grp_inv_r.\nDefined.\n\nGlobal Instance isequiv_group_inverse {G : Group}\n  : IsEquiv ((-) : G -> G).\nProof.\n  srapply isequiv_adjointify.\n  1: apply (-).\n  all: intro; apply negate_involutive.\nDefined.\n\n(** ** Working with equations in groups *)\n\nSection GroupEquations.\n\n  Context {G : Group} (x y z : G).\n\n  (** Inverses are involutive *)\n  Definition grp_inv_inv : --x = x := negate_involutive x.\n\n  (** Inverses distribute over the group operation *)\n  Definition grp_inv_op : - (x * y) = -y * -x := negate_sg_op x y.\n\nEnd GroupEquations.\n\n(** ** Cancelation *)\n\n(** Group elements can be cancelled both on the left and the right. *)\nDefinition grp_cancelL {G : Group} {x y : G} z : x = y <~> z * x = z * y\n  := equiv_ap (fun x => z * x) _ _.\nDefinition grp_cancelR {G : Group} {x y : G} z : x = y <~> x * z = y * z\n  := equiv_ap (fun x => x * z) _ _.\n\n(** ** Group movement lemmas *)\n\nSection GroupMovement.\n\n  (** Since left/right multiplication is an equivalence, we can use lemmas about moving equivalences around to prove group movement lemmas. *)\n\n  Context {G : Group} {x y z : G}.\n\n  (** *** Moving group elements *)\n\n  Definition grp_moveL_gM : x * -z = y <~> x = y * z\n    := equiv_moveL_equiv_M (f := fun t => t * z) _ _.\n\n  Definition grp_moveL_Mg : -y * x = z <~> x = y * z\n    := equiv_moveL_equiv_M (f := fun t => y * t) _ _.\n\n  Definition grp_moveR_gM : x = z * -y <~> x * y = z\n    := equiv_moveR_equiv_M (f := fun t => t * y) _ _.\n\n  Definition grp_moveR_Mg : y = -x * z <~> x * y = z\n    := equiv_moveR_equiv_M (f := fun t => x * t) _ _.\n\n  (** *** Moving inverses.*)\n  (** These are the inverses of the previous but are included here for completeness*)\n  Definition grp_moveR_gV : x = y * z <~> x * -z = y\n    := equiv_moveR_equiv_V (f := fun t => t * z) _ _.\n\n  Definition grp_moveR_Vg : x = y * z <~> -y * x = z \n    := equiv_moveR_equiv_V (f := fun t => y * t) _ _.\n\n  Definition grp_moveL_gV :  x * y = z <~> x = z * -y\n    := equiv_moveL_equiv_V (f := fun t => t * y) _ _.\n\n  Definition grp_moveL_Vg :  x * y = z <~> y = -x * z\n    := equiv_moveL_equiv_V (f := fun t => x * t) _ _.\n\n(** We close the section here so the previous lemmas generalise their assumptions. *)\nEnd GroupMovement.\n\nSection GroupMovement.\n\n  Context {G : Group} {x y z : G}.\n\n  (** *** Moving elements equal to unit. *)\n\n  Definition grp_moveL_1M : x * -y = mon_unit <~> x = y\n    := equiv_concat_r (grp_unit_l _) _ oE grp_moveL_gM.\n\n  Definition grp_moveL_M1 : -y * x = mon_unit <~> x = y\n    := equiv_concat_r (grp_unit_r _) _ oE grp_moveL_Mg.\n\n  Definition grp_moveR_1M : mon_unit = y * (-x) <~> x = y\n    := (equiv_concat_l (grp_unit_l _) _)^-1%equiv oE grp_moveR_gM.\n\n  Definition grp_moveR_M1 : mon_unit = -x * y <~> x = y\n    := (equiv_concat_l (grp_unit_r _) _)^-1%equiv oE grp_moveR_Mg.\n\n  (** *** Cancelling elements equal to unit. *)\n\n  Definition grp_cancelL1 : x = mon_unit <~> z * x = z\n    := (equiv_concat_r (grp_unit_r _) _ oE grp_cancelL z).\n\n  Definition grp_cancelR1 : x = mon_unit <~> x * z = z\n    := (equiv_concat_r (grp_unit_l _) _) oE grp_cancelR z.\n\nEnd GroupMovement.\n\n(** Power operation *)\n\nFixpoint grp_pow {G : Group} (g : G) (n : nat) : G :=\n  match n with\n  | 0%nat => mon_unit\n  | m.+1%nat => g * grp_pow g m\n  end.\n\n(** Any homomorphism respects [grp_pow]. *)\nLemma grp_pow_homo {G H : Group} (f : GroupHomomorphism G H)\n  (n : nat) (g : G) : f (grp_pow g n) = grp_pow (f g) n.\nProof.\n  induction n.\n  + cbn. apply grp_homo_unit.\n  + cbn. refine ((grp_homo_op f g (grp_pow g n)) @ _).\n    exact (ap (fun m => f g + m) IHn).\nDefined.\n\n(** The wild cat of Groups *)\nGlobal Instance isgraph_group : IsGraph Group\n  := Build_IsGraph Group GroupHomomorphism.\n\nGlobal Instance is01cat_group : Is01Cat Group :=\n  Build_Is01Cat Group _ (@grp_homo_id) (@grp_homo_compose).\n\nGlobal Instance is2graph_group : Is2Graph Group\n  := fun A B => isgraph_induced (@grp_homo_map A B).\n\nGlobal Instance isgraph_grouphomomorphism {A B : Group} : IsGraph (A $-> B)\n  := isgraph_induced (@grp_homo_map A B).\n\nGlobal Instance is01cat_grouphomomorphism {A B : Group} : Is01Cat (A $-> B)\n  := is01cat_induced (@grp_homo_map A B).\n\nGlobal Instance is0gpd_grouphomomorphism {A B : Group}: Is0Gpd (A $-> B)\n  := is0gpd_induced (@grp_homo_map A B).\n\nGlobal Instance is0functor_postcomp_grouphomomorphism {A B C : Group} (h : B $-> C)\n  : Is0Functor (@cat_postcomp Group _ _ A B C h).\nProof.\n  apply Build_Is0Functor.\n  intros [f ?] [g ?] p a ; exact (ap h (p a)).\nDefined.\n\nGlobal Instance is0functor_precomp_grouphomomorphism\n       {A B C : Group} (h : A $-> B)\n  : Is0Functor (@cat_precomp Group _ _ A B C h).\nProof.\n  apply Build_Is0Functor.\n  intros [f ?] [g ?] p a ; exact (p (h a)).\nDefined.\n\n(** Group forms a 1Cat *)\nGlobal Instance is1cat_group : Is1Cat Group.\nProof.\n  by rapply Build_Is1Cat.\nDefined.\n\nGlobal Instance hasmorext_group `{Funext} : HasMorExt Group.\nProof.\n  srapply Build_HasMorExt.\n  intros A B f g; cbn in *.\n  snrapply @isequiv_homotopic.\n  1: exact (equiv_path_grouphomomorphism^-1%equiv).\n  1: exact _.\n  intros []; reflexivity. \nDefined.\n\nGlobal Instance hasequivs_group\n  : HasEquivs Group.\nProof.\n  unshelve econstructor.\n  + exact GroupIsomorphism.\n  + exact (fun G H f => IsEquiv f).\n  + intros G H f; exact f.\n  + exact Build_GroupIsomorphism.\n  + intros G H; exact grp_iso_inverse.\n  + cbn; exact _.\n  + reflexivity.\n  + intros ????; apply eissect.\n  + intros ????; apply eisretr.\n  + intros G H f g p q.\n    exact (isequiv_adjointify f g p q).\nDefined.\n\nGlobal Instance is1cat_strong `{Funext} : Is1Cat_Strong Group.\nProof.\n  rapply Build_Is1Cat_Strong.\n  all: intros; apply equiv_path_grouphomomorphism; intro; reflexivity.\nDefined.\n\nGlobal Instance is0functor_type_group : Is0Functor group_type.\nProof.\n  apply Build_Is0Functor.\n  rapply @grp_homo_map.\nDefined.\n\nGlobal Instance is0functor_ptype_group : Is0Functor ptype_group.\nProof.\n  apply Build_Is0Functor.\n  rapply @pmap_GroupHomomorphism.\nDefined.\n\n(** Given a group element [a0 : A] over [b : B], multiplication by [a] establishes an equivalence between the kernel and the fiber over [b]. *)\nLemma equiv_grp_hfiber {A B : Group} (f : GroupHomomorphism A B) (b : B)\n  : forall (a0 : hfiber f b), hfiber f b <~> hfiber f mon_unit.\nProof.\n  intros [a0 p].\n  refine (equiv_transport (hfiber f) (right_inverse b) oE _).\n  snrapply Build_Equiv.\n  { srapply (functor_hfiber (h := fun t => t * -a0) (k := fun t => t * -b)).\n    intro a; cbn; symmetry.\n    refine (_ @ ap (fun x => f a * (- x)) p).\n    exact (grp_homo_op f _ _ @ ap (fun x => f a * x) (grp_homo_inv f a0)). }\n  srapply isequiv_functor_hfiber.\nDefined.\n\n(** ** The trivial group *)\n\nDefinition grp_trivial : Group.\nProof.\n  refine (Build_Group Unit (fun _ _ => tt) tt (fun _ => tt) _).\n  repeat split; try exact _; by intros [].\nDefined.\n\n(** Map out of trivial group *)\nDefinition grp_trivial_rec (G : Group) : GroupHomomorphism grp_trivial G.\nProof.\n  snrapply Build_GroupHomomorphism.\n  1: exact (fun _ => group_unit).\n  intros ??; symmetry; apply grp_unit_l.\nDefined.\n\n(** Map into trivial group *)\nDefinition grp_trivial_corec (G : Group) : GroupHomomorphism G grp_trivial.\nProof.\n  snrapply Build_GroupHomomorphism.\n  1: exact (fun _ => tt).\n  intros ??; symmetry; exact (grp_unit_l _).\nDefined.\n\n(** * Direct product of group *)\n\nDefinition grp_prod : Group -> Group -> Group.\nProof.\n  intros G H.\n  srapply (Build_Group (G * H)).\n  (** Operation *)\n  { intros [g1 h1] [g2 h2].\n    exact (g1 * g2, h1 * h2). }\n  (** Unit *)\n  1: exact (mon_unit, mon_unit).\n  (** Inverse *)\n  { intros [g h].\n    exact (-g, -h). }\n  repeat split.\n  1: exact _.\n  all: grp_auto.\nDefined.\n\nProposition grp_prod_corec {G H K : Group}\n            (f : GroupHomomorphism K G)\n            (g : GroupHomomorphism K H)\n  : GroupHomomorphism K (grp_prod G H).\nProof.\n  snrapply Build_GroupHomomorphism.\n  - exact (fun x:K => (f x, g x)).\n  - intros x y.\n    refine (path_prod' _ _ ); try apply grp_homo_op.\nDefined.\n\nDefinition grp_prod_inl {H K : Group}\n  : GroupHomomorphism H (grp_prod H K)\n  := grp_prod_corec grp_homo_id grp_homo_const.\n\nDefinition grp_prod_inr {H K : Group}\n  : GroupHomomorphism K (grp_prod H K)\n  := grp_prod_corec grp_homo_const grp_homo_id.\n\nDefinition grp_iso_prod {A B C D : Group}\n  : A ≅ B -> C ≅ D -> (grp_prod A C) ≅ (grp_prod B D).\nProof.\n  intros f g.\n  srapply Build_GroupIsomorphism'.\n  1: srapply (equiv_functor_prod (f:=f) (g:=g)).\n  simpl.\n  unfold functor_prod.\n  intros x y.\n  apply path_prod.\n  1,2: apply grp_homo_op.\nDefined.\n\nGlobal Instance isembedding_grp_prod_inl {H K : Group}\n  : IsEmbedding (@grp_prod_inl H K).\nProof.\n  apply isembedding_isinj_hset.\n  intros h0 h1 p; cbn in p.\n  exact (fst ((equiv_path_prod _ _)^-1 p)).\nDefined.\n\nGlobal Instance isembedding_grp_prod_inr {H K : Group}\n  : IsEmbedding (@grp_prod_inr H K).\nProof.\n  apply isembedding_isinj_hset.\n  intros k0 k1 q; cbn in q.\n  exact (snd ((equiv_path_prod _ _)^-1 q)).\nDefined.\n\nDefinition grp_prod_pr1 {G H : Group}\n  : GroupHomomorphism (grp_prod G H) G.\nProof.\n  snrapply Build_GroupHomomorphism.\n  1: exact fst.\n  intros ? ?; reflexivity.\nDefined.\n\nDefinition grp_prod_pr2 {G H : Group}\n  : GroupHomomorphism (grp_prod G H) H.\nProof.\n  snrapply Build_GroupHomomorphism.\n  1: exact snd.\n  intros ? ?; reflexivity.\nDefined.\n\nGlobal Instance issurj_grp_prod_pr1 {G H : Group}\n  : IsSurjection (@grp_prod_pr1 G H)\n  := issurj_retr grp_prod_inl (fun _ => idpath).\n\nGlobal Instance issurj_grp_prod_pr2 {G H : Group}\n  : IsSurjection (@grp_prod_pr2 G H)\n  := issurj_retr grp_prod_inr (fun _ => idpath).\n\n(** *** Properties of maps to and from the trivial group *)\n\nGlobal Instance isinitial_grp_trivial : IsInitial grp_trivial.\nProof.\n  intro G.\n  exists (grp_trivial_rec _).\n  intros g [].\n  apply (grp_homo_unit g)^.\nDefined.\n\nGlobal Instance contr_grp_homo_trivial_source `{Funext} G\n  : Contr (GroupHomomorphism grp_trivial G).\nProof.\n  snrapply Build_Contr.\n  1: exact (grp_trivial_rec _).\n  intros g.\n  rapply equiv_path_grouphomomorphism.\n  intros [].\n  symmetry.\n  rapply grp_homo_unit.\nDefined.\n\nGlobal Instance isterminal_grp_trivial : IsTerminal grp_trivial.\nProof.\n  intro G.\n  exists (grp_trivial_corec _).\n  intros g x.\n  apply path_contr.\nDefined.\n\nGlobal Instance contr_grp_homo_trivial_target `{Funext} G\n  : Contr (GroupHomomorphism G grp_trivial).\nProof.\n  snrapply Build_Contr.\n  1: exact (pr1 (isterminal_grp_trivial _)).\n  intros g.\n  rapply equiv_path_grouphomomorphism.\n  intros x.\n  apply path_contr.\nDefined.\n\nGlobal Instance ishprop_grp_iso_trivial `{Univalence} (G : Group)\n  : IsHProp (G ≅ grp_trivial).\nProof.\n  apply equiv_hprop_allpath.\n  intros f g.\n  apply equiv_path_groupisomorphism; intro; apply path_ishprop.\nDefined.\n\n(** ** Free groups *)\n\nDefinition FactorsThroughFreeGroup (S : Type) (F_S : Group)\n  (i : S -> F_S) (A : Group) (g : S -> A) : Type\n  := {f : F_S $-> A & f o i == g}.\n\n(** Universal property of a free group on a set (type). *)\nClass IsFreeGroupOn (S : Type) (F_S : Group) (i : S -> F_S)\n  := contr_isfreegroupon : forall (A : Group) (g : S -> A),\n      Contr (FactorsThroughFreeGroup S F_S i A g).\nGlobal Existing Instance contr_isfreegroupon.\n\n(** A group is free if there exists a generating type on which it is a free group *)\nClass IsFreeGroup (F_S : Group)\n  := isfreegroup : {S : _ & {i : _ & IsFreeGroupOn S F_S i}}.\n\nGlobal Instance isfreegroup_isfreegroupon (S : Type) (F_S : Group) (i : S -> F_S)\n  {H : IsFreeGroupOn S F_S i}\n  : IsFreeGroup F_S\n  := (S; i; H).\n\n(** Characterisation of injective group homomorphisms. *)\nLemma isembedding_grouphomomorphism {A B : Group} (f : A $-> B)\n  : (forall a, f a = group_unit -> a = group_unit) <-> IsEmbedding f.\nProof.\n  split.\n  - intros h b.\n    apply hprop_allpath.\n    intros [a0 p0] [a1 p1].\n    srapply path_sigma_hprop; simpl.\n    apply grp_moveL_1M.\n    apply h.\n    rewrite grp_homo_op, grp_homo_inv.\n    rewrite p0, p1.\n    apply right_inverse.\n  - intros E a p.\n    rapply (isinj_embedding f).\n    exact (p @ (grp_homo_unit f)^).\nDefined.\n\n(** Commutativity can be transferred across isomorphisms. *)\nDefinition commutative_iso_commutative {G H : Group}\n  {C : Commutative (@group_sgop G)} (f : GroupIsomorphism G H)\n  : Commutative (@group_sgop H).\nProof.\n  unfold Commutative.\n  rapply (equiv_ind f); intro g1.\n  rapply (equiv_ind f); intro g2.\n  refine ((preserves_sg_op _ _)^ @ _ @ (preserves_sg_op _ _)).\n  refine (ap f _).\n  apply C.\nDefined.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Algebra/Groups/Group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.673612647549886}}
{"text": "Add LoadPath \"D:\\sfsol\".\nRequire Export Hoare.\n\nInductive hoare_proof : Assertion -> com -> Assertion -> Type :=\n  | H_Skip : forall P,\n      hoare_proof P (SKIP) P\n  | H_Asgn : forall Q V a,\n      hoare_proof (assn_sub V a Q) (V ::= a) Q\n  | H_Seq : forall P c Q d R,\n      hoare_proof P c Q -> hoare_proof Q d R -> hoare_proof P (c;;d) R\n  | H_If : forall P Q b c1 c2,\n    hoare_proof (fun st => P st /\\ bassn b st) c1 Q ->\n    hoare_proof (fun st => P st /\\ ~(bassn b st)) c2 Q ->\n    hoare_proof P (IFB b THEN c1 ELSE c2 FI) Q\n  | H_While : forall P b c,\n    hoare_proof (fun st => P st /\\ bassn b st) c P ->\n    hoare_proof P (WHILE b DO c END) (fun st => P st /\\ ~ (bassn b st))\n  | H_Consequence : forall (P Q P' Q' : Assertion) c,\n    hoare_proof P' c Q' ->\n    (forall st, P st -> P' st) ->\n    (forall st, Q' st -> Q st) ->\n    hoare_proof P c Q.\n\nTactic Notation \"hoare_proof_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"H_Skip\" | Case_aux c \"H_Asgn\" | Case_aux c \"H_Seq\"\n  | Case_aux c \"H_If\" | Case_aux c \"H_While\" | Case_aux c \"H_Consequence\" ].\n\nLemma H_Consequence_pre : forall (P Q P': Assertion) c,\n    hoare_proof P' c Q ->\n    (forall st, P st -> P' st) ->\n    hoare_proof P c Q.\nProof.\n  intros.\n  eapply H_Consequence.\n  apply X. assumption. auto.\n  Qed.\n\nLemma H_Consequence_post : forall (P Q Q': Assertion) c,\n    hoare_proof P c Q' ->\n    (forall st, Q' st -> Q st) ->\n    hoare_proof P c Q.\nProof.\n  intros.\n  eapply H_Consequence.\n  apply X. auto. assumption.\n  Qed.\n\nExample sample_proof\n             : hoare_proof\n                 (assn_sub X (APlus (AId X) (ANum 1))\n                   (assn_sub X (APlus (AId X) (ANum 2))\n                     (fun st => st X = 3) ))\n                 (X ::= APlus (AId X) (ANum 1);; (X ::= APlus (AId X) (ANum 2)))\n                 (fun st => st X = 3).\nProof.\n  eapply H_Seq; apply H_Asgn.\nQed.\n\nTheorem hoare_proof_sound : forall P c Q,\n  hoare_proof P c Q -> {{P}} c {{Q}}.\nProof.\n  intros. induction X.\n  apply hoare_skip.\n  apply hoare_asgn.\n  apply hoare_seq with Q; assumption.\n  apply hoare_if; assumption.\n  apply hoare_while; assumption.\n  eapply hoare_consequence; try apply IHX; try assumption.\n  Qed.\n\nTheorem H_Post_True_deriv:\n  forall c P, hoare_proof P c (fun _ => True).\nProof.\n  intro c.\n  com_cases (induction c) Case; intro P.\n  Case \"SKIP\".\n    eapply H_Consequence.\n    apply H_Skip.\n    intros. apply H.\n    (* Proof of True *)\n    intros. apply I.\n  Case \"::=\".\n    eapply H_Consequence_pre.\n    apply H_Asgn.\n    intros. apply I.\n  Case \";;\".\n    eapply H_Consequence_pre.\n    eapply H_Seq.\n    apply (IHc1 (fun _ => True)).\n    apply IHc2.\n    intros. apply I.\n  Case \"IFB\".\n    apply H_Consequence_pre with (fun _ => True).\n    apply H_If.\n    apply IHc1.\n    apply IHc2.\n    intros. apply I.\n  Case \"WHILE\".\n    eapply H_Consequence.\n    eapply H_While.\n    eapply IHc.\n    intros; apply I.\n    intros; apply I.\nQed.\n\nLemma False_and_P_imp: forall P Q,\n  False /\\ P -> Q.\nProof.\n  intros P Q [CONTRA HP].\n  destruct CONTRA.\nQed.\n\nTactic Notation \"pre_false_helper\" constr(CONSTR) :=\n  eapply H_Consequence_pre;\n    [eapply CONSTR | intros ? CONTRA; destruct CONTRA].\n\nTheorem H_Pre_False_deriv:\n  forall c Q, hoare_proof (fun _ => False) c Q.\nProof.\n  intros c.\n  com_cases (induction c) Case; intro Q.\n  Case \"SKIP\". pre_false_helper H_Skip.\n  Case \"::=\". pre_false_helper H_Asgn.\n  Case \";;\". pre_false_helper H_Seq. apply IHc1. apply IHc2.\n  Case \"IFB\".\n    apply H_If; eapply H_Consequence_pre.\n    apply IHc1. intro. eapply False_and_P_imp.\n    apply IHc2. intro. eapply False_and_P_imp.\n  Case \"WHILE\".\n    eapply H_Consequence_post.\n    eapply H_While.\n    eapply H_Consequence_pre.\n      apply IHc.\n      intro. eapply False_and_P_imp.\n    intro. simpl. eapply False_and_P_imp.\nQed.\n\nDefinition wp (c:com) (Q:Assertion) : Assertion :=\n  fun s => forall s', c / s || s' -> Q s'.\n\nLemma wp_is_precondition: forall c Q,\n  {{wp c Q}} c {{Q}}.\nProof.\n  intros c Q st st' H1 H2.\n  apply H2. assumption.\n  Qed.\n\nLemma wp_is_weakest: forall c Q P',\n   {{P'}} c {{Q}} -> forall st, P' st -> wp c Q st.\nProof.\n  intros c Q P' H st H2. unfold wp. intros s' Hypo.\n  eapply H. apply Hypo. assumption. Qed.\n\nLemma bassn_eval_false : forall b st, ~ bassn b st -> beval st b = false.\nProof.\n  intros b st H. unfold bassn in H. destruct (beval st b).\n    exfalso. apply H. reflexivity.\n    reflexivity.\nQed.\n\nTheorem hoare_proof_complete: forall P c Q,\n  {{P}} c {{Q}} -> hoare_proof P c Q.\nProof.\n  intros P c. generalize dependent P.\n  com_cases (induction c) Case; intros P Q HT.\n  Case \"SKIP\".\n    eapply H_Consequence.\n     eapply H_Skip.\n      intros. eassumption.\n      intro st. apply HT. apply E_Skip.\n  Case \"::=\".\n    eapply H_Consequence.\n      eapply H_Asgn.\n      intro st. apply HT. econstructor. reflexivity.\n      intros; assumption.\n  Case \";;\".\n    apply H_Seq with (wp c2 Q).\n     eapply IHc1.\n       intros st st' E1 H. unfold wp. intros st'' E2.\n         eapply HT. econstructor; eassumption. assumption.\n     eapply IHc2. intros st st' E1 H. apply H; assumption.\n  Case \"IFB\".\n    apply H_If. apply IHc1.\n      intros st st' H [H1 H2].\n      eapply HT. constructor; try apply H2; assumption. assumption.\n      apply IHc2. intros st st' H [H1 H2].\n      eapply HT. apply E_IfFalse; try apply bassn_eval_false; try apply H2; assumption. assumption.\n  Case \"WHILE\".\n    eapply H_Consequence with (P' := wp (WHILE b DO c END) Q).\n      apply H_While.\n      apply IHc. intros st st' H [H2 H3] st'' H4.\n      assert((WHILE b DO c END) / st || st'').\n        eapply E_WhileLoop. apply H3. apply H. apply H4.\n      eapply wp_is_precondition. apply H0. assumption.\n      apply wp_is_weakest. assumption.\n      intros st [H1 H2]. eapply wp_is_precondition.\n      assert((WHILE b DO c END) / st || st).\n        apply E_WhileEnd. apply bassn_eval_false. assumption.\n      apply H. assumption.\n  Qed.", "meta": {"author": "mmalone", "repo": "sfsol", "sha": "5888f4532a1ec1ababa21bef39e25eb26279f0e4", "save_path": "github-repos/coq/mmalone-sfsol", "path": "github-repos/coq/mmalone-sfsol/sfsol-5888f4532a1ec1ababa21bef39e25eb26279f0e4/HoareAsLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6736126461491898}}
{"text": "Require Export D.\n\n\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. induction l. reflexivity.\n  Lemma rev_snoc_lemma : forall n:nat, forall l:natlist,\n    rev (n :: l) = snoc (rev l) n.\n  Proof. intros. reflexivity. Qed.\n  rewrite -> rev_snoc_lemma. simpl.\n  Lemma rev_snoc_lemma2 : forall n:nat, forall l:natlist,\n    rev (snoc l n) = n :: rev l.\n  Proof. intros. induction l. reflexivity.\n  simpl. rewrite -> IHl. simpl. reflexivity. Qed.\n  rewrite -> rev_snoc_lemma2. rewrite -> IHl. reflexivity.\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/03/P04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.798186784940666, "lm_q1q2_score": 0.6735859312700474}}
{"text": "From mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nInductive numeral:  nat -> Type :=\n  | Z: forall n, numeral n.+1\n  | U: forall n, numeral n -> numeral n.+1.\n\nPrint numeral_ind.\n\nDefinition numeral_ind2 \n  (P : forall n : nat, numeral n -> Prop)\n  (fz : forall n : nat, P n.+1 (Z n))\n  (fu : forall (n : nat) (n' : numeral n), P n n' -> P n.+1 (U n'))\n  := \n    fix F (n: nat) (n': numeral n) {struct n'} : P n n' :=  \n      match n' as n2 in (numeral n1) return (P n1 n2) with\n      | Z n1 => fz n1\n      | @U n1 n2 => fu n1 n2 (F n1 n2)\n      end.\n\n\nDefinition P: forall n, numeral n.+1 -> option (numeral n) :=\n  fun n num =>\n    match num with\n    | Z n' => None\n    | U _ n' => Some n'\n    end.\n\nPrint Empty_set.\nPrint void.\nDefinition P': forall n, numeral n -> match n with\n                                      | 0 => void\n                                      | S n' => option (numeral n')\n                                      end :=\n  fun _ num =>\n    match num with\n    | Z n' => None\n    | U _ n' => Some n'\n    end.\n\nDefinition P2: forall n, numeral n.+1 -> option (numeral n) := \n  fun n num => @P' n.+1 num.\n\nDefinition P'': forall n, numeral n.+2 -> numeral n.+1 :=\n  fun n num => \n    match @P' n.+2 num with\n    | Some a => a\n    | None => Z n\n    end.\n\n(* 21.2.1 *)\nLemma constr_disj: forall n (a: numeral n), @Z n <> @U n a.\nProof.\n  by move => n a H.\nQed.\nPrint constr_disj.\n\n(* 21.2.2 *)\nLemma num0: numeral 0 -> void.\nProof.\n  by apply P'.\nQed.\n\n(* 21.2.3 *)\nDefinition num_listing: forall (n: nat), seq (numeral n) :=\n  fix F n :=\n    match n with \n    | 0 => [::]\n    | n'.+1 => [:: Z n' & map (@U n') (F n')]\n    end.\n\nCompute num_listing 6.\n\n\n(* 21.3 Inversion *)\nDefinition num_inv: forall {n} (a: numeral n),\n  match n return numeral n -> Type with\n  | 0 => fun _ => void\n  | S n' => fun a => sum (a = Z n') { a' & a = U a' }\n  end a.\nProof.\n  move => n.\n  case => [a | n' a].\n  - by left.\n  right.\n  by exists a.\nDefined.\n(* ^ see chipala convoy pattern *)\n\nEval cbn in fun n => num_inv (Z n).\nEval cbn in fun n (a: numeral n) => num_inv (U a).\n\n\n\nTheorem inversion: forall n (a: numeral n.+1),\n  { a' & a = @U n a' } + { a = Z n }.\nProof.\n  move => n a.\n  case (@num_inv n.+1 a).\n  - by right.\n  by left.\nDefined.\n\n(* 21.3.1 *)\n\nLemma U_inj: forall n a b, @U n a = @U n b -> a = b.\nProof.\n  move => n a b H.\n  move: ((@f_equal _ _ (@P n) (@U n a) (@U n b)) H).\n  rewrite /P.\n  by case.\nQed.\n  \n\nDefinition dec (X: Type) := sum X (X -> False).\nLemma numeral_decidable:\n  forall n (a b: numeral n), dec (a = b).\nProof.\n  move => n.\n  elim => [n' b | n' b IH b'].\n  - case (@inversion n' b).\n      move => [a' Hb].\n      right.\n      by rewrite Hb.\n    move => ->.\n    by left.\n  case (@inversion n' b').\n    move => [a' ->].\n    case (IH a').\n      move => ->.\n      by left.\n    move => contra.\n    right => H.\n    apply contra.\n    by apply (U_inj H).\n  move => ->.\n  by right.\nQed.\n\n(* 21.3.2 *)\n(* TODO *)\n  \n(* 21.3.3 *)\n(* TODO *)\n  \n(* 21.4 Embedding numerals to numbers *)\nDefinition to_nat: forall n, numeral n -> nat :=\n  fix F n m :=\n    match m with\n    | Z _ => 0\n    | U n' m' => S (F n' m')\n    end.\n\nCompute (to_nat (U (U (Z 3)))).\n\nLemma numeral_upper: forall n (a: numeral n), to_nat a < n.\nProof.\n  move => n.\n  elim => [n' //| n' a' IH].\n  by rewrite /to_nat -/to_nat -addn1 -[n'.+1]addn1 ltn_add2r.\nQed.\n\nLemma to_nat_inj: forall n,\n  injective (@to_nat n).\nProof.\n  move => n.\n  elim => [n' b // | n' a IH b].\n    move: (inversion b) => [[b' -> Contra] | -> //].\n    exfalso. move: Contra.\n    by rewrite /to_nat -/to_nat.\n  move: (inversion b) => [[b' ->] | -> //].\n  rewrite /to_nat -/to_nat.\n  by move /succn_inj /IH ->.\nQed.\n\nFixpoint from_nat k n : numeral n.+1 :=\n  match k, n with\n  | 0, m => Z m\n  | (S k), 0 => Z 0\n  | (S k), (S m) => U (from_nat k m)\n  end.\n\nLemma from_nat_step: forall n m,\n  from_nat m.+1 n.+1 = U (from_nat m n).\nProof.\n  by [].\nQed.\n\nLemma form_to: forall n (a: numeral n.+1), from_nat (to_nat a) n = a.\nProof.\n  move => n a.\n  move: (inversion a) => [[a' ->] | -> //].\n  elim a' => [n'| n' a''].\n    by rewrite /to_nat -/to_nat /from_nat.\n  by rewrite /to_nat -/to_nat from_nat_step => ->.\nQed.\n\nLemma to_from: forall k n, k <= n -> @to_nat n.+1 (from_nat k n) = k.\nProof.\n  elim => [n Hl // | n IH k' Hl].\n  rewrite /from_nat -/from_nat.\n  case E: k'.\n    exfalso. move: E Hl => ->.\n    by rewrite ltn0.\n  move: E Hl => ->.\n  rewrite ltnS => Hl.\n  move: (IH _ Hl).\n  by rewrite {2}/to_nat -/to_nat => ->.\nQed.\n\n(* 21.4.1 *)\nDefinition lift_numeral: forall n (a: numeral n), numeral n.+1 :=\n  fix F n a :=\n    match a with\n    | Z n' => Z n'.+1\n    | @U m k => @U m.+1 (F m k)\n    end.\n\nLemma lift_numeral_inj: forall n,\n  injective (@lift_numeral n).\nProof.\n  move => n.\n  elim => [n' b // |n' a IH b ].\n    move: (inversion b) => [[a' ->] | -> //].\n    rewrite /lift_numeral -/lift_numeral.\n    move => contra. exfalso.\n    by [].\n  move: (inversion b) => [[a' ->] | -> //].\n  by rewrite /lift_numeral -/lift_numeral => /U_inj /IH ->.\nQed.\n  \n(* 21.5 Recursive numeral types *)\nFixpoint finT (n: nat): Type :=\n  match n with\n  | 0 => void\n  | n'.+1 => option (finT n')\n  end.\n\n(* 21.5.1 *)\nDefinition num_fin: forall n (a: numeral n), finT n := \n  fix F n a :=\n    match a with\n    | Z _ => None\n    | U n' a => Some (F n' a)\n    end.\n\nFixpoint fin_num {n} (a: finT n): numeral n :=\n  match n, a with\n  | 0, c => match c with end\n  | S n', None => Z n'\n  | S n', Some a' => U (fin_num a')\n  end.\n\n(* 21.5.2 *)\nLemma finT0: finT 0 -> False.\nProof.\n  by case.\nQed.\n\nLemma finT_inversion: forall n (a: finT n.+1), \n  sum (a = None) { a' & a = Some a' }.\nProof.\n  move => n.\n  elim.\nAdmitted. (*Defined.*)\n\n(* TODO: custom eliminator *)", "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/pt4/ch21_numeral_types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.6735859128487627}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Import NZAxioms.\nRequire Import NZAddOrder.\n\nModule Type NZMulOrderProp (Import NZ : NZOrdAxiomsSig').\nInclude NZAddOrderProp NZ.\n\nTheorem mul_lt_pred :\nforall p q n m, S p == q -> (p * n < p * m <-> q * n + m < q * m + n).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_lt_pred\".  \nintros p q n m H. rewrite <- H. nzsimpl.\nrewrite <- ! add_assoc, (add_comm n m).\nnow rewrite <- add_lt_mono_r.\nQed.\n\nTheorem mul_lt_mono_pos_l : forall p n m, 0 < p -> (n < m <-> p * n < p * m).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_lt_mono_pos_l\".  \nintros p n m Hp. revert n m. apply lt_ind with (4:=Hp). solve_proper.\nintros. now nzsimpl.\nclear p Hp. intros p Hp IH n m. nzsimpl.\nassert (LR : forall n m, n < m -> p * n + n < p * m + m)\nby (intros n1 m1 H; apply add_lt_mono; trivial; now rewrite <- IH).\nsplit; intros H.\nnow apply LR.\ndestruct (lt_trichotomy n m) as [LT|[EQ|GT]]; trivial.\nrewrite EQ in H. order.\napply LR in GT. order.\nQed.\n\nTheorem mul_lt_mono_pos_r : forall p n m, 0 < p -> (n < m <-> n * p < m * p).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_lt_mono_pos_r\".  \nintros p n m.\nrewrite (mul_comm n p), (mul_comm m p). now apply mul_lt_mono_pos_l.\nQed.\n\nTheorem mul_lt_mono_neg_l : forall p n m, p < 0 -> (n < m <-> p * m < p * n).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_lt_mono_neg_l\".  \nnzord_induct p.\norder.\nintros p Hp _ n m Hp'. apply lt_succ_l in Hp'. order.\nintros p Hp IH n m _. apply le_succ_l in Hp.\nle_elim Hp.\nassert (LR : forall n m, n < m -> p * m < p * n).\nintros n1 m1 H. apply (le_lt_add_lt n1 m1).\nnow apply lt_le_incl. rewrite <- 2 mul_succ_l. now rewrite <- IH.\nsplit; intros H.\nnow apply LR.\ndestruct (lt_trichotomy n m) as [LT|[EQ|GT]]; trivial.\nrewrite EQ in H. order.\napply LR in GT. order.\nrewrite (mul_lt_pred p (S p)), Hp; now nzsimpl.\nQed.\n\nTheorem mul_lt_mono_neg_r : forall p n m, p < 0 -> (n < m <-> m * p < n * p).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_lt_mono_neg_r\".  \nintros p n m.\nrewrite (mul_comm n p), (mul_comm m p). now apply mul_lt_mono_neg_l.\nQed.\n\nTheorem mul_le_mono_nonneg_l : forall n m p, 0 <= p -> n <= m -> p * n <= p * m.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_le_mono_nonneg_l\".  \nintros n m p H1 H2. le_elim H1.\nle_elim H2. apply lt_le_incl. now apply mul_lt_mono_pos_l.\napply eq_le_incl; now rewrite H2.\napply eq_le_incl; rewrite <- H1; now do 2 rewrite mul_0_l.\nQed.\n\nTheorem mul_le_mono_nonpos_l : forall n m p, p <= 0 -> n <= m -> p * m <= p * n.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_le_mono_nonpos_l\".  \nintros n m p H1 H2. le_elim H1.\nle_elim H2. apply lt_le_incl. now apply mul_lt_mono_neg_l.\napply eq_le_incl; now rewrite H2.\napply eq_le_incl; rewrite H1; now do 2 rewrite mul_0_l.\nQed.\n\nTheorem mul_le_mono_nonneg_r : forall n m p, 0 <= p -> n <= m -> n * p <= m * p.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_le_mono_nonneg_r\".  \nintros n m p H1 H2;\nrewrite (mul_comm n p), (mul_comm m p); now apply mul_le_mono_nonneg_l.\nQed.\n\nTheorem mul_le_mono_nonpos_r : forall n m p, p <= 0 -> n <= m -> m * p <= n * p.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_le_mono_nonpos_r\".  \nintros n m p H1 H2;\nrewrite (mul_comm n p), (mul_comm m p); now apply mul_le_mono_nonpos_l.\nQed.\n\nTheorem mul_cancel_l : forall n m p, p ~= 0 -> (p * n == p * m <-> n == m).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_cancel_l\".  \nintros n m p Hp; split; intro H; [|now f_equiv].\napply lt_gt_cases in Hp; destruct Hp as [Hp|Hp];\ndestruct (lt_trichotomy n m) as [LT|[EQ|GT]]; trivial.\napply (mul_lt_mono_neg_l p) in LT; order.\napply (mul_lt_mono_neg_l p) in GT; order.\napply (mul_lt_mono_pos_l p) in LT; order.\napply (mul_lt_mono_pos_l p) in GT; order.\nQed.\n\nTheorem mul_cancel_r : forall n m p, p ~= 0 -> (n * p == m * p <-> n == m).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_cancel_r\".  \nintros n m p. rewrite (mul_comm n p), (mul_comm m p); apply mul_cancel_l.\nQed.\n\nTheorem mul_id_l : forall n m, m ~= 0 -> (n * m == m <-> n == 1).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_id_l\".  \nintros n m H.\nstepl (n * m == 1 * m) by now rewrite mul_1_l. now apply mul_cancel_r.\nQed.\n\nTheorem mul_id_r : forall n m, n ~= 0 -> (n * m == n <-> m == 1).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_id_r\".  \nintros n m; rewrite mul_comm; apply mul_id_l.\nQed.\n\nTheorem mul_le_mono_pos_l : forall n m p, 0 < p -> (n <= m <-> p * n <= p * m).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_le_mono_pos_l\".  \nintros n m p H; do 2 rewrite lt_eq_cases.\nrewrite (mul_lt_mono_pos_l p n m) by assumption.\nnow rewrite -> (mul_cancel_l n m p) by\n(intro H1; rewrite H1 in H; false_hyp H lt_irrefl).\nQed.\n\nTheorem mul_le_mono_pos_r : forall n m p, 0 < p -> (n <= m <-> n * p <= m * p).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_le_mono_pos_r\".  \nintros n m p. rewrite (mul_comm n p), (mul_comm m p); apply mul_le_mono_pos_l.\nQed.\n\nTheorem mul_le_mono_neg_l : forall n m p, p < 0 -> (n <= m <-> p * m <= p * n).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_le_mono_neg_l\".  \nintros n m p H; do 2 rewrite lt_eq_cases.\nrewrite (mul_lt_mono_neg_l p n m); [| assumption].\nrewrite -> (mul_cancel_l m n p)\nby (intro H1; rewrite H1 in H; false_hyp H lt_irrefl).\nnow setoid_replace (n == m) with (m == n) by (split; now intro).\nQed.\n\nTheorem mul_le_mono_neg_r : forall n m p, p < 0 -> (n <= m <-> m * p <= n * p).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_le_mono_neg_r\".  \nintros n m p. rewrite (mul_comm n p), (mul_comm m p); apply mul_le_mono_neg_l.\nQed.\n\nTheorem mul_lt_mono_nonneg :\nforall n m p q, 0 <= n -> n < m -> 0 <= p -> p < q -> n * p < m * q.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_lt_mono_nonneg\".  \nintros n m p q H1 H2 H3 H4.\napply le_lt_trans with (m * p).\napply mul_le_mono_nonneg_r; [assumption | now apply lt_le_incl].\napply -> mul_lt_mono_pos_l; [assumption | now apply le_lt_trans with n].\nQed.\n\n\n\nTheorem mul_le_mono_nonneg :\nforall n m p q, 0 <= n -> n <= m -> 0 <= p -> p <= q -> n * p <= m * q.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_le_mono_nonneg\".  \nintros n m p q H1 H2 H3 H4.\nle_elim H2; le_elim H4.\napply lt_le_incl; now apply mul_lt_mono_nonneg.\nrewrite <- H4; apply mul_le_mono_nonneg_r; [assumption | now apply lt_le_incl].\nrewrite <- H2; apply mul_le_mono_nonneg_l; [assumption | now apply lt_le_incl].\nrewrite H2; rewrite H4; now apply eq_le_incl.\nQed.\n\nTheorem mul_pos_pos : forall n m, 0 < n -> 0 < m -> 0 < n * m.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_pos_pos\".  \nintros n m H1 H2. rewrite <- (mul_0_l m). now apply mul_lt_mono_pos_r.\nQed.\n\nTheorem mul_neg_neg : forall n m, n < 0 -> m < 0 -> 0 < n * m.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_neg_neg\".  \nintros n m H1 H2. rewrite <- (mul_0_l m). now apply mul_lt_mono_neg_r.\nQed.\n\nTheorem mul_pos_neg : forall n m, 0 < n -> m < 0 -> n * m < 0.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_pos_neg\".  \nintros n m H1 H2. rewrite <- (mul_0_l m). now apply mul_lt_mono_neg_r.\nQed.\n\nTheorem mul_neg_pos : forall n m, n < 0 -> 0 < m -> n * m < 0.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_neg_pos\".  \nintros; rewrite mul_comm; now apply mul_pos_neg.\nQed.\n\nTheorem mul_nonneg_nonneg : forall n m, 0 <= n -> 0 <= m -> 0 <= n*m.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_nonneg_nonneg\".  \nintros. rewrite <- (mul_0_l m). apply mul_le_mono_nonneg; order.\nQed.\n\nTheorem mul_pos_cancel_l : forall n m, 0 < n -> (0 < n*m <-> 0 < m).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_pos_cancel_l\".  \nintros n m Hn. rewrite <- (mul_0_r n) at 1.\nsymmetry. now apply mul_lt_mono_pos_l.\nQed.\n\nTheorem mul_pos_cancel_r : forall n m, 0 < m -> (0 < n*m <-> 0 < n).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_pos_cancel_r\".  \nintros n m Hn. rewrite <- (mul_0_l m) at 1.\nsymmetry. now apply mul_lt_mono_pos_r.\nQed.\n\nTheorem mul_nonneg_cancel_l : forall n m, 0 < n -> (0 <= n*m <-> 0 <= m).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_nonneg_cancel_l\".  \nintros n m Hn. rewrite <- (mul_0_r n) at 1.\nsymmetry. now apply mul_le_mono_pos_l.\nQed.\n\nTheorem mul_nonneg_cancel_r : forall n m, 0 < m -> (0 <= n*m <-> 0 <= n).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_nonneg_cancel_r\".  \nintros n m Hn. rewrite <- (mul_0_l m) at 1.\nsymmetry. now apply mul_le_mono_pos_r.\nQed.\n\nTheorem lt_1_mul_pos : forall n m, 1 < n -> 0 < m -> 1 < n * m.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.lt_1_mul_pos\".  \nintros n m H1 H2. apply (mul_lt_mono_pos_r m) in H1.\nrewrite mul_1_l in H1. now apply lt_1_l with m.\nassumption.\nQed.\n\nTheorem eq_mul_0 : forall n m, n * m == 0 <-> n == 0 \\/ m == 0.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.eq_mul_0\".  \nintros n m; split.\nintro H; destruct (lt_trichotomy n 0) as [H1 | [H1 | H1]];\ndestruct (lt_trichotomy m 0) as [H2 | [H2 | H2]];\ntry (now right); try (now left).\nexfalso; now apply (lt_neq 0 (n * m)); [apply mul_neg_neg |].\nexfalso; now apply (lt_neq (n * m) 0); [apply mul_neg_pos |].\nexfalso; now apply (lt_neq (n * m) 0); [apply mul_pos_neg |].\nexfalso; now apply (lt_neq 0 (n * m)); [apply mul_pos_pos |].\nintros [H | H]. now rewrite H, mul_0_l. now rewrite H, mul_0_r.\nQed.\n\nTheorem neq_mul_0 : forall n m, n ~= 0 /\\ m ~= 0 <-> n * m ~= 0.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.neq_mul_0\".  \nintros n m; split; intro H.\nintro H1; apply eq_mul_0 in H1. tauto.\nsplit; intro H1; rewrite H1 in H;\n(rewrite mul_0_l in H || rewrite mul_0_r in H); now apply H.\nQed.\n\nTheorem eq_square_0 : forall n, n * n == 0 <-> n == 0.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.eq_square_0\".  \nintro n; rewrite eq_mul_0; tauto.\nQed.\n\nTheorem eq_mul_0_l : forall n m, n * m == 0 -> m ~= 0 -> n == 0.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.eq_mul_0_l\".  \nintros n m H1 H2. apply eq_mul_0 in H1. destruct H1 as [H1 | H1].\nassumption. false_hyp H1 H2.\nQed.\n\nTheorem eq_mul_0_r : forall n m, n * m == 0 -> n ~= 0 -> m == 0.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.eq_mul_0_r\".  \nintros n m H1 H2; apply eq_mul_0 in H1. destruct H1 as [H1 | H1].\nfalse_hyp H1 H2. assumption.\nQed.\n\n\n\nDefinition mul_eq_0 := eq_mul_0.\nDefinition mul_eq_0_l := eq_mul_0_l.\nDefinition mul_eq_0_r := eq_mul_0_r.\n\nTheorem lt_0_mul n m : 0 < n * m <-> (0 < n /\\ 0 < m) \\/ (m < 0 /\\ n < 0).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.lt_0_mul\".  \nsplit; [intro H | intros [[H1 H2] | [H1 H2]]].\ndestruct (lt_trichotomy n 0) as [H1 | [H1 | H1]];\n[| rewrite H1 in H; rewrite mul_0_l in H; false_hyp H lt_irrefl |];\n(destruct (lt_trichotomy m 0) as [H2 | [H2 | H2]];\n[| rewrite H2 in H; rewrite mul_0_r in H; false_hyp H lt_irrefl |]);\ntry (left; now split); try (right; now split).\nassert (H3 : n * m < 0) by now apply mul_neg_pos.\nexfalso; now apply (lt_asymm (n * m) 0).\nassert (H3 : n * m < 0) by now apply mul_pos_neg.\nexfalso; now apply (lt_asymm (n * m) 0).\nnow apply mul_pos_pos. now apply mul_neg_neg.\nQed.\n\nTheorem square_lt_mono_nonneg : forall n m, 0 <= n -> n < m -> n * n < m * m.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.square_lt_mono_nonneg\".  \nintros n m H1 H2. now apply mul_lt_mono_nonneg.\nQed.\n\nTheorem square_le_mono_nonneg : forall n m, 0 <= n -> n <= m -> n * n <= m * m.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.square_le_mono_nonneg\".  \nintros n m H1 H2. now apply mul_le_mono_nonneg.\nQed.\n\n\n\nTheorem square_lt_simpl_nonneg : forall n m, 0 <= m -> n * n < m * m -> n < m.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.square_lt_simpl_nonneg\".  \nintros n m H1 H2. destruct (lt_ge_cases n 0).\nnow apply lt_le_trans with 0.\ndestruct (lt_ge_cases n m) as [LT|LE]; trivial.\napply square_le_mono_nonneg in LE; order.\nQed.\n\nTheorem square_le_simpl_nonneg : forall n m, 0 <= m -> n * n <= m * m -> n <= m.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.square_le_simpl_nonneg\".  \nintros n m H1 H2. destruct (lt_ge_cases n 0).\napply lt_le_incl; now apply lt_le_trans with 0.\ndestruct (le_gt_cases n m) as [LE|LT]; trivial.\napply square_lt_mono_nonneg in LT; order.\nQed.\n\nTheorem mul_2_mono_l : forall n m, n < m -> 1 + 2 * n < 2 * m.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.mul_2_mono_l\".  \nintros n m. rewrite <- le_succ_l, (mul_le_mono_pos_l (S n) m two).\nrewrite two_succ. nzsimpl. now rewrite le_succ_l.\norder'.\nQed.\n\nLemma add_le_mul : forall a b, 1<a -> 1<b -> a+b <= a*b.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.add_le_mul\".  \nassert (AUX : forall a b, 0<a -> 0<b -> (S a)+(S b) <= (S a)*(S b)).\nintros a b Ha Hb.\nnzsimpl. rewrite <- succ_le_mono. apply le_succ_l.\nrewrite <- add_assoc, <- (add_0_l (a+b)), (add_comm b).\napply add_lt_mono_r.\nnow apply mul_pos_pos.\nintros a b Ha Hb.\nassert (Ha' := lt_succ_pred 1 a Ha).\nassert (Hb' := lt_succ_pred 1 b Hb).\nrewrite <- Ha', <- Hb'. apply AUX; rewrite succ_lt_mono, <- one_succ; order.\nQed.\n\n\n\nLemma square_nonneg : forall a, 0 <= a * a.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.square_nonneg\".  \nintros. rewrite <- (mul_0_r a). destruct (le_gt_cases a 0).\nnow apply mul_le_mono_nonpos_l.\napply mul_le_mono_nonneg_l; order.\nQed.\n\nLemma crossmul_le_addsquare : forall a b, 0<=a -> 0<=b -> b*a+a*b <= a*a+b*b.\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.crossmul_le_addsquare\".  \nassert (AUX : forall a b, 0<=a<=b -> b*a+a*b <= a*a+b*b).\nintros a b (Ha,H).\ndestruct (le_exists_sub _ _ H) as (d & EQ & Hd).\nrewrite EQ.\nrewrite 2 mul_add_distr_r.\nrewrite !add_assoc. apply add_le_mono_r.\nrewrite add_comm. apply add_le_mono_l.\napply mul_le_mono_nonneg_l; trivial. order.\nintros a b Ha Hb.\ndestruct (le_gt_cases a b).\napply AUX; split; order.\nrewrite (add_comm (b*a)), (add_comm (a*a)).\napply AUX; split; order.\nQed.\n\nLemma add_square_le : forall a b, 0<=a -> 0<=b ->\na*a + b*b <= (a+b)*(a+b).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.add_square_le\".  \nintros a b Ha Hb.\nrewrite mul_add_distr_r, !mul_add_distr_l.\nrewrite add_assoc.\napply add_le_mono_r.\nrewrite <- add_assoc.\nrewrite <- (add_0_r (a*a)) at 1.\napply add_le_mono_l.\napply add_nonneg_nonneg; now apply mul_nonneg_nonneg.\nQed.\n\nLemma square_add_le : forall a b, 0<=a -> 0<=b ->\n(a+b)*(a+b) <= 2*(a*a + b*b).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.square_add_le\".  \nintros a b Ha Hb.\nrewrite !mul_add_distr_l, !mul_add_distr_r. nzsimpl'.\nrewrite <- !add_assoc. apply add_le_mono_l.\nrewrite !add_assoc. apply add_le_mono_r.\napply crossmul_le_addsquare; order.\nQed.\n\nLemma quadmul_le_squareadd : forall a b, 0<=a -> 0<=b ->\n2*2*a*b <= (a+b)*(a+b).\nProof. hammer_hook \"NZMulOrder\" \"NZMulOrder.NZMulOrderProp.quadmul_le_squareadd\".  \nintros.\nnzsimpl'.\nrewrite !mul_add_distr_l, !mul_add_distr_r.\nrewrite (add_comm _ (b*b)), add_assoc.\napply add_le_mono_r.\nrewrite (add_shuffle0 (a*a)), (mul_comm b a).\napply add_le_mono_r.\nrewrite (mul_comm a b) at 1.\nnow apply crossmul_le_addsquare.\nQed.\n\nEnd NZMulOrderProp.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Numbers/NatInt/NZMulOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764118, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.6735859093340355}}
{"text": "Require Import Coqlibext.\nRequire Import Do_notation.\nRequire Import ClassesAndNotations.\nRequire Import Psatz.\nRequire Import Program.\n\nSet Implicit Arguments.\n\n\nDefinition decidable (P:Prop) := {P} + {~P}.\n\n(* Definition of what a vector is and what multiplication on vectors\n   mean *)\n\nLocal Hint Unfold decidable: pb.\nLocal Ltac un := autounfold with pb in *.\n\n\nSection WITHDIM.\nVariable n: nat.\nDefinition vector := {l:list Z| length l = n}.\nImplicit Type v: vector.\nImplicit Type va: list Z.\nImplicit Type x y z: Z.\n\n\n\nFixpoint prod_vect_aux (va1 va2:list Z) : Z :=\n  match va1, va2 with\n    | nil, _\n    | _, nil => 0\n    | x1 :: va1', x2 :: va2' =>\n      (x1 * x2) + (prod_vect_aux va1' va2')\n  end.\n\nLtac dest_vect v :=\n  let av := fresh \"a\" v in\n  let avLENGTH := fresh av \"LENGTH\" in\n  destruct v as [av avLENGTH].\n\nLtac dest_vects :=\n  repeat\n  match goal with\n    | v : vector |- _ =>\n      dest_vect v\n  end; simpl.\n\nProgram Definition prod_vect v1 v2 : Z :=\n  prod_vect_aux v1 v2.\n\n\nNotation \"v1 <*> v2\" := (prod_vect v1 v2) (at level 69).\n\nInductive cmp := EQ | GE.\n\nRecord constraint := mkConstraint\n  { vect: vector;\n    comp: cmp;\n    val: Z}.\n\n\n\nDefinition satisfy_cmp z1 comp z2 :=\n  match comp with\n    | EQ => z1 = z2\n    | GE => z1 >= z2\n  end.\n\nLocal Hint Unfold satisfy_cmp: pb.\n\nLemma satisfy_cmp_dec: forall z1 comp z2, decidable (satisfy_cmp z1 comp z2).\nProof.\n  intros z1 comp0 z2.\n  un.\n  destruct comp0. apply zeq. apply Z_ge_dec.\nQed.\n\n\nDefinition satisfy_constr v (constr: constraint) :=\n  satisfy_cmp (constr.(vect) <*> v) constr.(comp) constr.(val).\n\nLocal Hint Unfold satisfy_constr: pb.\n\n\nLemma satisfy_constr_dec: forall v constr, decidable (satisfy_constr v constr).\nProof.\n  intros v constr. un.\n  apply satisfy_cmp_dec.\nQed.\n\nFixpoint repeat {A:Type} (m: nat) (a:A) :=\n  match m with\n    | O => nil\n    | S m' => a :: (repeat m' a)\n  end.\n\nLemma repeat_length: forall A m (a:A), \n  length (repeat m a) = m.\nProof.\n  induction m; simpl; intros; auto.\nQed.\n\nProgram Definition repeat_v z : vector:=\n  repeat n z.\nNext Obligation. apply repeat_length. Qed.\n\n\n\nDefinition empty_constr:= mkConstraint (repeat_v 0) GE 1.\nLocal Hint Unfold empty_constr: pb.\nProgram Lemma empty_constr_empty : forall v,\n  ~satisfy_constr v empty_constr.\nProof.\n  intros v.\n  un. simpl.\n\n  assert (forall m av, prod_vect_aux (repeat m 0) av = 0).\n  induction m; destruct av; simpl; intros; auto.\n  assert (repeat_v 0 <*> v = 0).\n  dest_vect v. unfold prod_vect. simpl. auto.\n  rewrite H0. auto.\nQed.\n\n\nDefinition polyhedron := list constraint.\n\nHint Unfold polyhedron: aliases.\n\n\nDefinition In_pol v (pol: polyhedron) :=\n  list_forall (satisfy_constr v) pol.\n\nDefinition empty pol := forall v, ~In_pol v pol.\n\n\nProgram Definition opp_vect v : vector:= List.map Zopp v.\nNext Obligation.\n  dest_vect v. simpl. rewrite map_length. auto.\nQed.\n\nLocal Hint Unfold opp_vect: pb.\n\nNotation \"<~> v\" := (opp_vect v) (at level 42).\n\nLemma opp_vect_correct1:\n  forall v1 v2,  (<~> v1) <*> v2 = - (v1 <*> v2).\nProof.\n  unfold opp_vect, prod_vect. intros. dest_vects. simpl.\n  clear av1LENGTH av2LENGTH.\n  revert av2.\n  induction av1; destruct av2; simpl; intros; auto.\n  rewrite IHav1. lia.\nQed.\n\nLemma opp_vect_correct2:\n  forall v1 v2,  v1 <*> (<~> v2) = - (v1 <*> v2).\nProof.\n  unfold opp_vect, prod_vect. intros. dest_vects.\n  clear av1LENGTH av2LENGTH.\n  revert av1.\n  induction av2; destruct av1; simpl; intros; auto.\n  rewrite IHav2. lia.\nQed.\n\n\n(* canonize_pol removes all equalities *)\nFixpoint canonize_pol pol :=\n  match pol with\n    | nil => nil\n    | constr :: pol' =>\n      match constr.(comp) with\n        | EQ =>\n          (mkConstraint (<~> constr.(vect)) GE (Zopp constr.(val)))::\n          (mkConstraint  constr.(vect) GE constr.(val))::\n          canonize_pol pol'\n        | GE => constr :: canonize_pol pol'\n      end\n  end.\n\nLocal Hint Unfold In_pol: pb.\nLemma canonize_pol_corr1: forall v pol, In_pol v pol ->\n  In_pol v (canonize_pol pol).\nProof.\n  un.\n  induction pol; simpl; intro LF.\n  constructor.\n  inversion LF as [|? ? SATIS LF']. subst. clear LF.\n  destruct a. simpl. destruct comp0; [|constructor; auto].\n\n  unfold satisfy_constr in SATIS. simpl in *.\n\n  unfold satisfy_constr.\n  repeat (constructor; simpl); auto.\n  rewrite opp_vect_correct1. lia.\n  lia.\nQed.\n\nLemma canonize_pol_corr2: forall v pol,\n  In_pol v (canonize_pol pol) -> In_pol v pol.\nProof.\n  un.\n  induction pol; simpl; intro LF.\n  constructor.\n  destruct a. simpl in *. destruct comp0; auto.\n  inv LF. inv H2.\n  constructor; eauto. clear H4 IHpol.\n  unfold satisfy_constr in *; simpl in *.\n  rewrite opp_vect_correct1 in H1. lia.\n  inv LF. constructor; eauto.\nQed.\n\nProgram Definition mult_vect z v : vector:=\n  map (fun z' => z * z') v.\nNext Obligation.\n  dest_vect v.\n  simpl. rewrite map_length. auto.\nQed.\n\nNotation \"z *> v\" := (mult_vect z v) (at level 42).\nLocal Hint Unfold mult_vect prod_vect: pb.\nLemma mult_vect_correct1: forall z v1 v2, \n (z *> v1) <*> v2 = (z * (v1 <*> v2)).\nProof.\n  un.\n  intros z v1 v2. dest_vects.\n  clear. revert av2.\n  induction av1; destruct av2; intros; simpl in *; auto; try lia.\n  rewrite IHav1. lia.\nQed.\n\n\nDefinition mult_constraint z c :=\n  mkConstraint\n    ((Zabs z) *> c.(vect))\n    c.(comp)\n    ((Zabs z) * c.(val)).\n\nLocal Hint Unfold mult_constraint: pb.\n\nLemma mult_constraint_correct: forall v z c,\n  satisfy_constr v c -> satisfy_constr v (mult_constraint z c).\nProof.\n  unfold satisfy_constr, mult_constraint.\n  intros v z c H. simpl.\n  remember (Zabs z) as z'.\n  assert (0 <= z'). rewrite Heqz'. apply Zabs_pos.\n  destruct c.\n  destruct comp0; simpl in *; auto.\n  subst. rewrite mult_vect_correct1. reflexivity.\n  rewrite mult_vect_correct1.\n\n  apply Zmult_ge_compat_l; auto. lia.\nQed.\n\n\nFixpoint add_vect_aux av1 av2 :=\n  match av1, av2 with\n    | nil, _\n    | _, nil => nil\n    | z1::av1', z2::av2' =>\n      (z1 + z2) :: add_vect_aux av1' av2'\n  end.\nProgram Definition add_vect v1 v2 : vector :=\n  add_vect_aux v1 v2.\nNext Obligation.\n  dest_vects.\n  generalize dependent av2. revert av1LENGTH. revert n.\n  induction av1; destruct av2; simpl; intros; auto.\n  simpl in av1LENGTH. destruct n; auto.\nQed.\n\nNotation \"v1 <+> v2\" := (add_vect v1 v2) (at level 42).\n\nLemma add_vect_correct1:\n  forall v3 v1 v2,\n    (v1 <+> v2) <*> v3 = (v1 <*> v3) + (v2 <*> v3).\nProof.\n  intros. unfold add_vect, prod_vect. dest_vects.\n  generalize dependent av2; generalize dependent av1; revert av3LENGTH; revert n.\n  induction av3; intros; destruct av1; destruct av2; simpl in *;subst; auto.\n  inv av1LENGTH; inv av2LENGTH.\n  erewrite IHav3; eauto; try omega. lia.\nQed.\n\n\nDefinition add_constr c1 c2 :=\n  mkConstraint (c1.(vect) <+> c2.(vect)) GE (c1.(val) + c2.(val)).\n\nLemma add_constr_correct : forall v c1 c2,\n  satisfy_constr v c1 -> satisfy_constr v c2 -> satisfy_constr v (add_constr c1 c2).\nProof.\n  unfold satisfy_constr.\n  intros v c1 c2 H H0. destruct c1; destruct c2. simpl in *.\n  rewrite add_vect_correct1.\n  destruct comp0; destruct comp1; simpl in *; subst; lia.\nQed.\n\nFixpoint mult_each_constraint (wit: list Z) (pol: polyhedron) : option polyhedron :=\n  match wit, pol with\n    | nil, nil => Some nil\n    | nil, _\n    | _, nil => None\n    | z :: wit', c::pol' =>\n      do pol'' <- mult_each_constraint wit' pol';\n      Some ((mult_constraint z c) :: pol'')\n  end.\n\nLemma mult_each_constraint_correct: forall v wit pol pol',\n  In_pol v pol -> mult_each_constraint wit pol = Some pol' ->\n  In_pol v pol'.\nProof.\n  induction wit; destruct pol; unfold In_pol in *; intros; simpl in *; auto.\n  inv H0. constructor.\n\n  prog_dos. inv H.\n  constructor; eauto.\n  apply mult_constraint_correct. auto.\nQed.\n\nDefinition colapse_constraints pol :=\n  match pol with\n    | nil => None\n    | c1 :: pol' =>\n      Some (fold_left add_constr pol' c1)\n  end.\n\nLemma colapse_constraints_correct: forall v pol c,\n  colapse_constraints pol = Some c ->\n  In_pol v pol -> satisfy_constr v c.\nProof.\n  intros v pol c.\n  destruct pol; simpl. auto.\n  unfold In_pol. intros HEQ IN. inv HEQ. inv IN.\n\n  generalize dependent c0. generalize dependent pol.\n  induction pol; intros; simpl in *; auto.\n  inv H2.\n  apply IHpol; auto. apply add_constr_correct; auto.\nQed.\n\n\n(* in lib *)\nFixpoint list_forallb {A:Type} f (l: list A) :=\n  match l with\n    | nil => true\n    | x :: l' =>\n      (f x) && (list_forallb f l')\n  end.\n\nLemma list_forallb_correct: forall A f (P: A -> Prop) (l: list A),\n  (forall a, f a = true -> P a) ->\n  list_forallb f l = true -> list_forall P l.\nProof.\n  intros A f P l H H0. \n  induction l; simpl in *; constructor.\n  apply H. destruct (f a); auto.\n  apply IHl. destruct (list_forallb f l); auto.\n  destruct (f a); auto.\nQed.\n\nDefinition is_pos z :=\n  match z with\n    | Zpos _ => true\n    | _ => false\n  end.\n\nProgram Definition check_contradiction (c: constraint) :=\n  (is_pos c.(val)) && (list_forallb (fun z => z == 0) c.(vect)).\n\nLemma check_contradiction_correct:\n  forall c, check_contradiction c = true ->\n    forall v, ~satisfy_constr v c.\nProof.\n  unfold check_contradiction, satisfy_constr; intros c H v H'.\n  destruct c. dest_vects. unfold prod_vect in *; simpl in *.\n  destruct (andb_prop _ _ H). clear H.\n  apply list_forallb_correct with (P := (fun z => z = 0)) in H1.\n\n    Focus 2.\n      intros. dest ==; auto.\n\n  assert (0 >= val0).\n    clear avLENGTH avect0LENGTH.\n    generalize dependent av. revert H1. clear H0. revert val0.\n    induction avect0; intros; destruct comp0; simpl in *; auto; try lia.\n    destruct av; subst; try lia.\n    inv H1. simpl. eauto.\n    destruct av; subst; try lia.\n    inv H1. simpl in H'. eauto.\n\n  unfold is_pos in H0.\n  destruct val0; eauto.\nQed.\n\nProgram Definition\n  check_emtpy (wit: list Z) (pol: polyhedron) : {empty pol} + {True}:=\n  match mult_each_constraint wit pol with\n    | None => right _\n    | Some pol' =>\n      match colapse_constraints pol' with\n        | None => right _\n        | Some c =>\n          match check_contradiction c with\n            | true => left _\n            | false => right _\n          end\n      end\n  end.\nNext Obligation.\n  unfold empty. intros v IN.\n  symmetry in Heq_anonymous. symmetry in Heq_anonymous0. symmetry in Heq_anonymous1.\n  pose proof (mult_each_constraint_correct _ IN Heq_anonymous).\n  apply (colapse_constraints_correct Heq_anonymous0) in H.\n  eapply check_contradiction_correct; eauto.\nQed.\n\n\n(* we now use the emptyness test to build an inclusion test *)\n\nDefinition inv_constr (c: constraint) :=\n  mkConstraint (opp_vect c.(vect)) GE (1 - c.(val)).\n\n\nLemma inv_constr_correct: forall c v,\n  c.(comp) = GE -> ~(satisfy_constr v (inv_constr c)) ->\n  satisfy_constr v c.\nProof.\n  unfold satisfy_constr. unfold inv_constr.\n  intros c v H H0.\n  destruct c. simpl in *. subst.\n  rewrite opp_vect_correct1 in H0.\n  assert (~(- (vect0 <*> v) >= (1 - val0))); auto.\n  simpl. lia.\nQed.\n\n\n(* is_empty is defined in Polyhedra.v *)\nVariable is_empty_canonized : forall (p: polyhedron), {empty p} + {True}.\n\n\nDefinition included p1 p2 :=\n  forall v, In_pol v p1 -> In_pol v p2.\nHint Unfold In_pol included.\n\nDefinition are_included_aux p1 p2 :=\n  list_forallb (fun c => is_empty_canonized ((inv_constr c) :: p1)) (canonize_pol p2).\n\nLemma empty_inv: forall c p, c.(comp) = GE -> empty ((inv_constr c) :: p) ->\n  forall v, (In_pol v p -> satisfy_constr v c).\nProof.\n  unfold empty, In_pol.\n  intros c p H H0 v H1.\n  apply inv_constr_correct; auto.\n  intro SATIS.\n  apply (H0 v).\n  constructor; auto.\nQed.\n\nLemma are_included_aux_correct:\n  forall p1 p2, are_included_aux p1 p2 = true -> included p1 p2.\nProof.\n  unfold included, In_pol, are_included_aux.\n  intros p1 p2 H v H0.\n  apply list_forallb_correct with (P := (fun c=> empty (inv_constr c :: p1))) in H.\n  apply canonize_pol_corr2. unfold In_pol.\n\n  induction p2 as [|c p2]; simpl; try constructor.\n  destruct c; destruct comp0; simpl in *; constructor; inv H; eauto using empty_inv.\n  constructor; inv H4; eauto using empty_inv.\n\n  intros c H1. destruct (is_empty_canonized (inv_constr c :: p1)); simpl in H1; auto.\nQed.\n\nProgram Definition are_included_canonized_part p1 p2 : {included p1 p2} + {True} :=\n  match are_included_aux p1 p2 with\n    | true => left _\n    | false => right _\n  end.\nNext Obligation.\n  auto using are_included_aux_correct.\nQed.\n\nProgram Definition are_included_part p1 p2 : {included p1 p2} + {True} :=\n  match are_included_aux (canonize_pol p1) p2 with\n    | true => left _\n    | false => right _\n  end.\nNext Obligation.\n  unfold included. intros v H. apply canonize_pol_corr1 in H.\n  symmetry in Heq_anonymous. apply are_included_aux_correct in Heq_anonymous.\n  unfold included in Heq_anonymous. eauto.\nQed.\nEnd WITHDIM.\n\n\n\n\n\n\n\nDefinition pseudo_vector := list Z.\n\nRecord pseudo_constraint := mkPseudoConstraint\n  { pvect: pseudo_vector;\n    pcomp: cmp;\n    pval: Z}.\n\nDefinition pseudo_polyhedron := list pseudo_constraint.\n\nFixpoint is_of_length (n: nat) (pv: pseudo_vector) :=\n  match n, pv with\n    | O, nil => true\n    | _, nil\n    | O, _ => false\n    | S n', _ :: pv' => is_of_length n' pv'\n  end.\n\nProgram Definition make_vector n (pv: pseudo_vector) : option (vector n) :=\n  match is_of_length n pv with\n    | true => Some pv\n    | false => None\n  end.\nNext Obligation.\n  generalize dependent pv.\n  induction n; destruct pv; simpl; intro LENGTH; auto.\nQed.\n\nDefinition make_constraint n (pc: pseudo_constraint) : option (constraint n):=\n  do v <- make_vector n pc.(pvect);\n  point (mkConstraint v pc.(pcomp) pc.(pval)).\n\n\n\nDefinition make_polyhedron n (ph : pseudo_polyhedron) : option (polyhedron n):=\n  mmap (make_constraint n) ph.\n\n", "meta": {"author": "pilki", "repo": "s2sLoop", "sha": "821528456333c518788df2834c674e850d7e7291", "save_path": "github-repos/coq/pilki-s2sLoop", "path": "github-repos/coq/pilki-s2sLoop/s2sLoop-821528456333c518788df2834c674e850d7e7291/src/Lin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6735504764307373}}
{"text": "Require Import rt.util.all.\nRequire Import rt.analysis.global.jitter.bertogna_fp_theory.\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq fintype bigop div path.\n\nModule ResponseTimeIterationFP.\n\n  Import ResponseTimeAnalysisFP.\n\n  (* In this section, we define the algorithm of Bertogna and Cirinei's\n     response-time analysis for FP scheduling with release jitter. *)\n  Section Analysis.\n    \n    Context {sporadic_task: eqType}.\n    Variable task_cost: sporadic_task -> time.\n    Variable task_period: sporadic_task -> time.\n    Variable task_deadline: sporadic_task -> time.\n    Variable task_jitter: sporadic_task -> time.\n\n    (* During the iterations of the algorithm, we pass around pairs\n       of tasks and computed response-time bounds. *)\n    Let task_with_response_time := (sporadic_task * time)%type.\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 -> sporadic_task.\n    Variable job_jitter: Job -> time.\n\n    (* Consider a platform with num_cpus processors, ... *)\n    Variable num_cpus: nat.\n\n    (* ..., and priorities based on an FP policy. *)\n    Variable higher_priority: FP_policy sporadic_task.\n\n    (* Next we define the fixed-point iteration for computing\n       Bertogna's response-time bound of a task set. *)\n    \n    (* First, given a sequence of pairs R_prev = <..., (tsk_hp, R_hp)> of\n       response-time bounds for the higher-priority tasks, we define an\n       iteration that computes the response-time bound of the current task:\n\n           R_tsk (0) = task_cost tsk\n           R_tsk (step + 1) =  f (R step),\n\n       where f is the response-time recurrence, step is the number of iterations,\n       and R_tsk (0) is the initial state. *)\n    Definition per_task_rta (tsk: sporadic_task)\n                            (R_prev: seq task_with_response_time) (step: nat) :=\n      iter step\n        (fun t => task_cost tsk +\n                  div_floor\n                    (total_interference_bound_fp task_cost task_period task_jitter tsk  R_prev t)\n                    num_cpus)\n        (task_cost tsk).\n\n    (* To ensure that the iteration converges, we will apply per_task_rta\n       a \"sufficient\" number of times: task_deadline tsk - task_cost tsk + 1.\n       This corresponds to the time complexity of the iteration. *)\n    Definition max_steps (tsk: sporadic_task) := task_deadline tsk - task_cost tsk + 1.\n    \n    (* Next we compute the response-time bounds for the entire task set.\n       Since high-priority tasks may not be schedulable, we allow the\n       computation to fail.\n       Thus, given the response-time bound of previous tasks, we either\n       (a) append the computed response-time bound (tsk, R) of the current task\n           to the list of pairs, or,\n       (b) return None if the response-time analysis failed. *)\n    Definition fp_bound_of_task hp_pairs tsk :=\n      if hp_pairs is Some rt_bounds then\n        let R := per_task_rta tsk rt_bounds (max_steps tsk) in\n          if task_jitter tsk + R <= task_deadline tsk then\n            Some (rcons rt_bounds (tsk, R))\n          else None\n      else None.\n\n    (* The response-time analysis for a given task set is defined\n       as a left-fold (reduce) based on the function above.\n       This either returns a list of task and response-time bounds, or None. *)\n    Definition fp_claimed_bounds (ts: seq sporadic_task) :=\n      foldl fp_bound_of_task (Some [::]) ts.\n\n    (* The schedulability test simply checks if we got a list of\n       response-time bounds (i.e., if the computation did not fail). *)\n    Definition fp_schedulable (ts: seq sporadic_task) :=\n      fp_claimed_bounds ts != None.\n    \n    (* In the following section, we prove several helper lemmas about the\n       list of response-time bounds. The results seem trivial, but must be proven\n       nonetheless since the list of response-time bounds is computed with\n       a specific algorithm and there are no lemmas in the library for that. *)\n    Section SimpleLemmas.\n\n      (* First, we show that the first component of the computed list is the set of tasks. *)\n      Lemma fp_claimed_bounds_unzip :\n        forall ts hp_bounds, \n          fp_claimed_bounds ts = Some hp_bounds ->\n          unzip1 hp_bounds = ts.\n      Proof.\n        unfold fp_claimed_bounds in *; intros ts.\n        induction ts using last_ind; first by destruct hp_bounds.\n        {\n          intros hp_bounds SOME.\n          destruct (lastP hp_bounds) as [| hp_bounds'].\n          {\n            rewrite -cats1 foldl_cat /= in SOME.\n            unfold fp_bound_of_task at 1 in SOME; simpl in *; desf.\n            by destruct l.\n          }\n          rewrite -cats1 foldl_cat /= in SOME.\n          unfold fp_bound_of_task at 1 in SOME; simpl in *; desf.\n          move: H0 => /eqP EQSEQ.\n          rewrite eqseq_rcons in EQSEQ.\n          move: EQSEQ => /andP [/eqP SUBST /eqP EQSEQ]; subst.\n          unfold unzip1; rewrite map_rcons; f_equal.\n          by apply IHts.\n        }\n      Qed.\n\n      (* Next, we show that some properties of the analysis are preserved for the\n         prefixes of the list: (a) the tasks do not change, (b) R <= deadline,\n         (c) R is computed using the response-time equation, ... *) \n      Lemma fp_claimed_bounds_rcons :\n        forall ts' hp_bounds tsk1 tsk2 R,\n          (fp_claimed_bounds (rcons ts' tsk1) = Some (rcons hp_bounds (tsk2, R)) ->\n           (fp_claimed_bounds ts' = Some hp_bounds /\\\n            tsk1 = tsk2 /\\\n            R = per_task_rta tsk1 hp_bounds (max_steps tsk1) /\\\n            task_jitter tsk1 + R <= task_deadline tsk1)).\n      Proof.\n        intros ts hp_bounds tsk tsk' R.\n        rewrite -cats1.\n        unfold fp_claimed_bounds in *.\n        rewrite foldl_cat /=.\n        unfold fp_bound_of_task at 1; simpl; desf.\n        intros EQ; inversion EQ; move: EQ H0 => _ /eqP EQ.\n        rewrite eqseq_rcons in EQ.\n        move: EQ => /andP [/eqP EQ /eqP RESP].\n        by inversion RESP; repeat split; subst.\n      Qed.\n\n      (* ..., which implies that any prefix of the computation is the computation\n         of the prefix. *)\n      Lemma fp_claimed_bounds_take :\n        forall ts hp_bounds i,\n          fp_claimed_bounds ts = Some hp_bounds ->\n          i <= size hp_bounds ->\n          fp_claimed_bounds (take i ts) = Some (take i hp_bounds).\n      Proof.                                                        \n        intros ts hp_bounds i SOME LTi.\n        have UNZIP := fp_claimed_bounds_unzip ts hp_bounds SOME.\n        rewrite <- UNZIP in *.\n        rewrite -[hp_bounds]take_size /unzip1 map_take in SOME.\n        fold (unzip1 hp_bounds) in *; clear UNZIP.\n        rewrite leq_eqVlt in LTi.\n        move: LTi => /orP [/eqP EQ | LTi]; first by subst.\n        remember (size hp_bounds) as len; apply eq_leq in Heqlen.\n        induction len; first by rewrite ltn0 in LTi.\n        {\n          assert (TAKElen: fp_claimed_bounds (take len (unzip1 (hp_bounds))) =\n                             Some (take len (hp_bounds))).\n          {\n            assert (exists p, p \\in hp_bounds).\n            {\n              destruct hp_bounds; first by rewrite ltn0 in Heqlen.\n              by exists t; rewrite in_cons eq_refl orTb.\n            } destruct H as [[tsk R] _].\n             rewrite (take_nth tsk) in SOME; last by rewrite size_map.\n            rewrite (take_nth (tsk,R)) in SOME; last by done.\n            destruct (nth (tsk, R) hp_bounds len) as [tsk_len R_len].\n            by apply fp_claimed_bounds_rcons in SOME; des.\n          }\n          rewrite ltnS leq_eqVlt in LTi.\n          move: LTi => /orP [/eqP EQ | LESS]; first by subst.\n          apply ltnW in Heqlen.\n          by specialize (IHlen Heqlen TAKElen LESS).\n        }\n      Qed.\n      \n      (* If the analysis suceeds, the computed response-time bounds are no larger\n         than the deadlines... *)\n      Lemma fp_claimed_bounds_le_deadline :\n        forall ts' rt_bounds tsk R,\n          fp_claimed_bounds ts' = Some rt_bounds ->\n          (tsk, R) \\in rt_bounds ->\n          task_jitter tsk + R <= task_deadline tsk.\n      Proof.\n        intros ts; induction ts as [| ts' tsk_lst] using last_ind.\n        {\n          intros rt_bounds tsk R SOME IN.\n          by inversion SOME; subst; rewrite in_nil in IN.\n        }\n        {\n          intros rt_bounds tsk_i R SOME IN.\n          destruct (lastP rt_bounds) as [|rt_bounds (tsk_lst', R_lst)];\n            first by rewrite in_nil in IN.\n          rewrite mem_rcons in_cons in IN; move: IN => /orP IN.\n          destruct IN as [LAST | FRONT].\n          {\n            move: LAST => /eqP LAST.\n            rewrite -cats1 in SOME.\n            unfold fp_claimed_bounds in *.\n            rewrite foldl_cat /= in SOME.\n            unfold fp_bound_of_task in SOME.\n            desf; rename H0 into EQ.\n            move: EQ => /eqP EQ.\n            rewrite eqseq_rcons in EQ.\n            move: EQ => /andP [_ /eqP EQ].\n            inversion EQ; subst.\n            by apply Heq0.\n          }\n          {\n            apply IHts with (rt_bounds := rt_bounds); last by ins.\n            by apply fp_claimed_bounds_rcons in SOME; des.\n          }\n        }\n      Qed.\n      \n      (* ... and the computed response-time bounds are no smaller\n         than the task costs. *)\n      Lemma fp_claimed_bounds_ge_cost :\n        forall ts' rt_bounds tsk R,\n          fp_claimed_bounds ts' = Some rt_bounds ->\n          (tsk, R) \\in rt_bounds ->\n          R >= task_cost tsk.\n      Proof.\n        intros ts; induction ts as [| ts' tsk_lst] using last_ind.\n        {\n          intros rt_bounds tsk R SOME IN.\n          by inversion SOME; subst; rewrite in_nil in IN.\n        }\n        {\n          intros rt_bounds tsk_i R SOME IN.\n          destruct (lastP rt_bounds) as [|rt_bounds (tsk_lst', R_lst)];\n            first by rewrite in_nil in IN.\n          rewrite mem_rcons in_cons in IN; move: IN => /orP IN.\n          destruct IN as [LAST | FRONT].\n          {\n            move: LAST => /eqP LAST.\n            rewrite -cats1 in SOME.\n            unfold fp_claimed_bounds in *.\n            rewrite foldl_cat /= in SOME.\n            unfold fp_bound_of_task in SOME.\n            desf; rename H0 into EQ.\n            move: EQ => /eqP EQ.\n            rewrite eqseq_rcons in EQ.\n            move: EQ => /andP [_ /eqP EQ].\n            inversion EQ; subst.\n            by destruct (max_steps tsk_lst');\n              [by apply leqnn | by apply leq_addr].\n          }\n          {\n            apply IHts with (rt_bounds := rt_bounds); last by ins.\n            by apply fp_claimed_bounds_rcons in SOME; des.\n          }\n        }\n      Qed.\n\n      (* Short lemma about unfolding the iteration one step. *)\n      Lemma per_task_rta_fold :\n        forall tsk rt_bounds,\n          task_cost tsk +\n           div_floor (total_interference_bound_fp task_cost task_period task_jitter tsk rt_bounds\n                     (per_task_rta tsk rt_bounds (max_steps tsk))) num_cpus\n          = per_task_rta tsk rt_bounds (max_steps tsk).+1.\n      Proof.\n          by done.\n      Qed.\n\n    End SimpleLemmas.\n\n    (* In this section, we prove that if the task set is sorted by priority,\n       the tasks in fp_claimed_bounds are interfering tasks.  *)\n    Section HighPriorityTasks.\n\n      (* Consider a list of previous tasks and a task tsk to be analyzed. *)\n      Variable ts: taskset_of sporadic_task.\n\n      (* Assume that the task set is sorted by unique priorities, ... *)\n      Hypothesis H_task_set_is_sorted: sorted higher_priority ts.\n      Hypothesis H_task_set_has_unique_priorities:\n        FP_is_antisymmetric_over_task_set higher_priority ts.\n\n      (* ...the priority order is transitive, ...*)\n      Hypothesis H_priority_transitive: FP_is_transitive higher_priority.\n\n      (* ... and that the response-time analysis succeeds. *)\n      Variable hp_bounds: seq task_with_response_time.\n      Variable R: time.\n      Hypothesis H_analysis_succeeds: fp_claimed_bounds ts = Some hp_bounds.\n      \n      (* Let's refer to tasks by index. *)\n      Variable elem: sporadic_task.\n      Let TASK := nth elem ts.\n\n      (* We prove that higher-priority tasks have smaller index. *)\n      Lemma fp_claimed_bounds_hp_tasks_have_smaller_index :\n        forall hp_idx idx,\n          hp_idx < size ts ->\n          idx < size ts ->\n          hp_idx != idx ->\n          higher_priority (TASK hp_idx) (TASK idx) ->\n          hp_idx < idx.\n      Proof.\n        unfold TASK; clear TASK.\n        rename ts into ts'; destruct ts' as [ts UNIQ]; simpl in *.\n        intros hp_idx idx LThp LT NEQ HP.\n        rewrite ltn_neqAle; apply/andP; split; first by done.\n        by apply sorted_rel_implies_le_idx with (leT := higher_priority) (s := ts) (x0 := elem).\n      Qed.\n      \n    End HighPriorityTasks.\n\n    (* In this section, we show that the fixed-point iteration converges. *)\n    Section Convergence.\n\n      (* Consider any set of higher-priority tasks. *)\n      Variable ts_hp: seq sporadic_task.\n\n      (* Assume that the response-time analysis succeeds for the higher-priority tasks. *)\n      Variable rt_bounds: seq task_with_response_time.\n      Hypothesis H_test_succeeds: fp_claimed_bounds ts_hp = Some rt_bounds.\n\n      (* Consider any task tsk to be analyzed, ... *)\n      Variable tsk: sporadic_task.\n\n      (* ... and assume all tasks have valid parameters. *)\n      Hypothesis H_valid_task_parameters:\n        valid_sporadic_taskset task_cost task_period task_deadline (rcons ts_hp tsk).\n\n      (* To simplify, let f denote the fixed-point iteration. *)\n      Let f := per_task_rta tsk rt_bounds.\n\n      (* Assume that f (max_steps tsk) is no larger than the deadline. *)\n      Hypothesis H_no_larger_than_deadline: f (max_steps tsk) <= task_deadline tsk.\n\n      (* First, we show that f is monotonically increasing. *)\n      Lemma bertogna_fp_comp_f_monotonic :\n        forall x1 x2, x1 <= x2 -> f x1 <= f x2.\n      Proof.\n        unfold valid_sporadic_taskset, is_valid_sporadic_task in *.\n        rename H_test_succeeds into SOME,\n               H_valid_task_parameters into VALID.\n        intros x1 x2 LEx; unfold f, per_task_rta.\n        apply fun_mon_iter_mon; [by ins | by ins; apply leq_addr |].\n        clear LEx x1 x2; intros x1 x2 LEx.\n        unfold div_floor, total_interference_bound_fp.\n        rewrite leq_add2l leq_div2r //.\n        rewrite big_seq_cond.\n        rewrite [\\sum_(_ <- _ | true) _]big_seq_cond.\n        apply leq_sum; move => i /andP [IN _].\n        destruct i as [i R].\n        have GE_COST := fp_claimed_bounds_ge_cost ts_hp rt_bounds i R SOME IN.\n        have UNZIP := fp_claimed_bounds_unzip ts_hp rt_bounds SOME.\n        unfold interference_bound_generic; simpl.\n        rewrite leq_min; apply/andP; split.\n        {\n          apply leq_trans with (n := W_jitter task_cost task_period task_jitter i R x1); first by apply geq_minl.\n          apply W_monotonic; try (by done).\n          have INts: i \\in ts_hp by rewrite -UNZIP; apply/mapP; exists (i, R).\n          by exploit (VALID i);\n            [by rewrite mem_rcons in_cons INts orbT | by ins; des].\n        }\n        {\n          apply leq_trans with (n := x1 - task_cost tsk + 1); first by apply geq_minr.\n          by rewrite leq_add2r leq_sub2r //.\n        }\n      Qed.\n\n      (* If the iteration converged at an earlier step, then it remains stable. *)\n      Lemma bertogna_fp_comp_f_converges_early :\n        (exists k, k <= max_steps tsk /\\ f k = f k.+1) ->\n        f (max_steps tsk) = f (max_steps tsk).+1.\n      Proof.\n        by intros EX; des; apply iter_fix with (k := k).\n      Qed.\n\n      (* Else, we derive a contradiction. *)\n      Section DerivingContradiction.\n\n        (* Assume instead that the iteration continued to diverge. *)\n        Hypothesis H_keeps_diverging:\n          forall k,\n            k <= max_steps tsk -> f k != f k.+1.\n\n        (* By monotonicity, it follows that the value always increases. *)\n        Lemma bertogna_fp_comp_f_increases :\n          forall k,\n            k <= max_steps tsk ->\n            f k < f k.+1.\n        Proof.\n          intros k LT.\n          rewrite ltn_neqAle; apply/andP; split.\n            by apply H_keeps_diverging.\n            by apply bertogna_fp_comp_f_monotonic, leqnSn.\n        Qed.\n\n        (* In the end, the response-time bound must exceed the deadline. Contradiction! *)\n        Lemma bertogna_fp_comp_rt_grows_too_much :\n          forall k,\n            k <= max_steps tsk ->\n            f k > k + task_cost tsk - 1.\n        Proof.\n          have INC := bertogna_fp_comp_f_increases.\n          rename H_valid_task_parameters into TASK_PARAMS.\n          unfold valid_sporadic_taskset, is_valid_sporadic_task in *; des.\n          exploit (TASK_PARAMS tsk);\n            [by rewrite mem_rcons in_cons eq_refl orTb | intro PARAMS; des].\n          induction k.\n          {\n            intros _; rewrite add0n -addn1 subh1;\n              first by rewrite -addnBA // subnn addn0 /= leqnn.\n            by apply PARAMS.\n          }\n          {\n            intros LT.\n            specialize (IHk (ltnW LT)).\n            apply leq_ltn_trans with (n := f k);\n              last by apply INC, ltnW.\n            rewrite -addn1 -addnA [1 + _]addnC addnA -addnBA // subnn addn0.\n            rewrite -(ltn_add2r 1) in IHk.\n            rewrite subh1 in IHk;\n              last by apply leq_trans with (n := task_cost tsk);\n                [by apply PARAMS | by apply leq_addl].\n            by rewrite -addnBA // subnn addn0 addn1 ltnS in IHk.\n          }  \n        Qed.\n\n      End DerivingContradiction.\n      \n      (* Using the lemmas above, we prove the convergence of the iteration after max_steps. *)\n      Lemma per_task_rta_converges:\n        f (max_steps tsk) = f (max_steps tsk).+1.\n      Proof.\n        have TOOMUCH := bertogna_fp_comp_rt_grows_too_much.\n        have INC := bertogna_fp_comp_f_increases.\n        rename H_no_larger_than_deadline into LE,\n               H_valid_task_parameters into TASK_PARAMS.\n        unfold valid_sporadic_taskset, is_valid_sporadic_task in *; des.\n       \n        (* Either f converges by the deadline or not. *)\n        destruct ([exists k in 'I_(max_steps tsk).+1, f k == f k.+1]) eqn:EX.\n        {\n          move: EX => /exists_inP EX; destruct EX as [k _ ITERk].\n          apply bertogna_fp_comp_f_converges_early.\n          by exists k; split; [by rewrite -ltnS; apply ltn_ord | by apply/eqP].\n        }\n\n        (* If not, then we reach a contradiction *)\n        apply negbT in EX; rewrite negb_exists_in in EX.\n        move: EX => /forall_inP EX.\n        rewrite leqNgt in LE; move: LE => /negP LE.\n        exfalso; apply LE.\n\n        assert (DIFF: forall k : nat, k <= max_steps tsk -> f k != f k.+1).\n        {\n          intros k LEk; rewrite -ltnS in LEk.\n          by exploit (EX (Ordinal LEk)); [by done | intro DIFF; apply DIFF].\n        }          \n        exploit TOOMUCH; [by apply DIFF | by apply leq_addr |].\n        exploit (TASK_PARAMS tsk);\n          [by rewrite mem_rcons in_cons eq_refl orTb | intro PARAMS; des].\n        rewrite subh1; last by apply PARAMS2.\n        rewrite -addnBA // subnn addn0 subn1 prednK //.\n        intros LT; apply (leq_ltn_trans LT).\n        by rewrite /max_steps [_ - _ + 1]addn1; apply INC, leq_addr.\n      Qed.\n      \n    End Convergence.\n    \n    Section MainProof.\n\n      (* Consider a task set ts. *)\n      Variable ts: taskset_of sporadic_task.\n      \n      (* Assume that all tasks have valid parameters, ... *)\n      Hypothesis H_valid_task_parameters:\n        valid_sporadic_taskset task_cost task_period task_deadline ts.\n\n      (* ...and constrained deadlines.*)\n      Hypothesis H_constrained_deadlines:\n        forall tsk, tsk \\in ts -> task_deadline tsk <= task_period tsk.\n\n       (* Assume that the task set is totally ordered by unique priorities,\n          and that the priority order is transitive. *)\n      Hypothesis H_task_set_is_sorted: sorted higher_priority ts.\n      Hypothesis H_task_set_has_unique_priorities:\n        FP_is_antisymmetric_over_task_set higher_priority ts.\n      Hypothesis H_priority_is_total:\n        FP_is_total_over_task_set higher_priority ts.\n      Hypothesis H_priority_transitive: FP_is_transitive higher_priority.\n\n      (* Next, consider any arrival sequence such that...*)\n      Context {arr_seq: arrival_sequence Job}.\n\n     (* ...all jobs come from task set ts, ...*)\n      Hypothesis H_all_jobs_from_taskset:\n        forall j, arrives_in arr_seq j -> job_task j \\in ts.\n      \n      (* ...they have valid parameters,...*)\n      Hypothesis H_valid_job_parameters:\n        forall j,\n          arrives_in arr_seq j ->\n          valid_sporadic_job_with_jitter task_cost task_deadline task_jitter job_cost\n                                                   job_deadline job_task job_jitter j.\n      \n      (* ... and satisfy the sporadic task model.*)\n      Hypothesis H_sporadic_tasks:\n        sporadic_task_model task_period job_arrival job_task arr_seq.\n      \n      (* Then, consider any schedule of this arrival sequence such that... *)\n      Variable sched: schedule Job num_cpus.\n      Hypothesis H_at_least_one_cpu: num_cpus > 0.\n      Hypothesis H_jobs_come_from_arrival_sequence:\n        jobs_come_from_arrival_sequence sched arr_seq.\n\n      (* ...jobs only execute after jitter and no longer than their execution costs. *)\n      Hypothesis H_jobs_must_arrive_to_execute:\n        jobs_execute_after_jitter job_arrival job_jitter sched.\n      Hypothesis H_completed_jobs_dont_execute:\n        completed_jobs_dont_execute job_cost sched.\n\n      (* Also assume that jobs are sequential (as required by the workload bound). *)\n      Hypothesis H_sequential_jobs: sequential_jobs sched.\n\n      (* Assume that the scheduler is work-conserving and respects the FP policy. *)\n      Hypothesis H_work_conserving: work_conserving job_arrival job_cost job_jitter arr_seq sched.\n      Hypothesis H_respects_FP_policy:\n        respects_FP_policy job_arrival job_cost job_task job_jitter arr_seq sched higher_priority.\n\n      Let no_deadline_missed_by_task (tsk: sporadic_task) :=\n        task_misses_no_deadline job_arrival job_cost job_deadline job_task arr_seq sched tsk.\n      Let no_deadline_missed_by_job :=\n        job_misses_no_deadline job_arrival job_cost job_deadline sched.\n      Let response_time_bounded_by (tsk: sporadic_task) :=\n        is_response_time_bound_of_task job_arrival job_cost job_task arr_seq sched tsk.\n          \n      (* In the following theorem, we prove that any response-time bound contained\n         in fp_claimed_bounds is safe. The proof follows by induction on the task set:\n\n           Induction hypothesis: all higher-priority tasks have safe response-time bounds.\n           Inductive step: We prove that the response-time bound of the current task is safe.\n\n         Note that the inductive step is a direct application of the main Theorem from\n         bertogna_fp_theory.v. *)\n      Theorem fp_analysis_yields_response_time_bounds :\n        forall tsk R,\n          (tsk, R) \\In fp_claimed_bounds ts ->\n          response_time_bounded_by tsk (task_jitter tsk + R).\n      Proof.\n        rename H_valid_job_parameters into JOBPARAMS, H_valid_task_parameters into TASKPARAMS,\n               H_constrained_deadlines into RESTR, H_completed_jobs_dont_execute into COMP,\n               H_jobs_must_arrive_to_execute into MUSTARRIVE,\n               H_all_jobs_from_taskset into ALLJOBS.\n        intros tsk R MATCH.\n        assert (SOME: exists hp_bounds, fp_claimed_bounds ts = Some hp_bounds /\\\n                                        (tsk, R) \\in hp_bounds).\n        {\n          destruct (fp_claimed_bounds ts); last by done.\n          by exists l; split.\n        } clear MATCH; des; rename SOME0 into IN.\n\n        have UNZIP := fp_claimed_bounds_unzip ts hp_bounds SOME.\n        \n        set elem := (tsk,R).\n        move: IN => /(nthP elem) [idx LTidx EQ].\n        set NTH := fun k => nth elem hp_bounds k.\n        set TASK := fun k => (NTH k).1.\n        set RESP := fun k => (NTH k).2.\n        cut (response_time_bounded_by (TASK idx) (task_jitter (TASK idx) + RESP idx));\n          first by unfold TASK, RESP, NTH; rewrite EQ.\n        clear EQ.\n\n        assert (PAIR: forall idx, (TASK idx, RESP idx) = NTH idx).\n        {\n          by intros i; unfold TASK, RESP; destruct (NTH i).\n        }\n\n        assert (SUBST: forall i, i < size hp_bounds -> TASK i = nth tsk ts i).\n        {\n          by intros i LTi; rewrite /TASK /NTH -UNZIP (nth_map elem) //.\n        }\n\n        assert (SIZE: size hp_bounds = size ts).\n        {\n          by rewrite -UNZIP size_map.\n        }\n\n        induction idx as [idx IH'] using strong_ind.\n\n        assert (IH: forall tsk_hp R_hp, (tsk_hp, R_hp) \\in take idx hp_bounds -> response_time_bounded_by tsk_hp (task_jitter tsk_hp + R_hp)).\n        {\n          intros tsk_hp R_hp INhp.\n          move: INhp => /(nthP elem) [k LTk EQ].\n          rewrite size_take LTidx in LTk.\n          rewrite nth_take in EQ; last by done.\n          cut (response_time_bounded_by (TASK k) (task_jitter (TASK k) + RESP k));\n            first by unfold TASK, RESP, NTH; rewrite EQ.\n          by apply IH'; try (by done); apply (ltn_trans LTk).\n        } clear IH'.\n\n        unfold response_time_bounded_by in *.\n\n        exploit (fp_claimed_bounds_rcons (take idx ts) (take idx hp_bounds) (TASK idx) (TASK idx) (RESP idx)).\n        {\n          by rewrite PAIR SUBST // -2?take_nth -?SIZE // (fp_claimed_bounds_take _ hp_bounds).\n        }\n        intros [_ [_ [REC DL]]].\n\n        apply bertogna_cirinei_response_time_bound_fp with\n              (task_cost0 := task_cost) (task_period0 := task_period)\n              (task_deadline0 := task_deadline) (job_deadline0 := job_deadline) (tsk0 := (TASK idx))\n              (job_task0 := job_task) (ts0 := ts) (hp_bounds0 := take idx hp_bounds)\n              (job_jitter0 := job_jitter) (higher_eq_priority := higher_priority); try (by done).\n        {\n          cut (NTH idx \\in hp_bounds = true);\n            [intros IN | by apply mem_nth].\n          by rewrite set_mem -UNZIP; apply/mapP; exists (TASK idx, RESP idx); rewrite PAIR.\n        }\n        {\n          intros hp_tsk IN INTERF.\n          exists (RESP (index hp_tsk ts)).\n          move: (IN) => INDEX; apply nth_index with (x0 := tsk) in INDEX.\n          rewrite -{1}[hp_tsk]INDEX -SUBST; last by rewrite SIZE index_mem.\n          assert (UNIQ: uniq hp_bounds).\n          {\n            apply map_uniq with (f := fst); unfold unzip1 in *; rewrite UNZIP.\n            by destruct ts.\n          }\n          rewrite -filter_idx_lt_take //.\n          {\n            rewrite PAIR mem_filter; apply/andP; split;\n              last by apply mem_nth; rewrite SIZE index_mem.\n            {\n              rewrite /NTH index_uniq; [| by rewrite SIZE index_mem | by done ].\n              {\n                move: INTERF => /andP [HP NEQ].\n                apply fp_claimed_bounds_hp_tasks_have_smaller_index with\n                  (ts := ts) (elem := tsk) (hp_bounds := hp_bounds);\n                  try (by done);\n                  [by rewrite index_mem | by rewrite -SIZE | | by rewrite INDEX -SUBST].\n                apply/eqP; intro BUG; subst idx.\n                rewrite SUBST -{1}INDEX in NEQ;\n                  first by rewrite eq_refl in NEQ.\n                by rewrite SIZE index_mem INDEX.\n              }\n            }\n          }\n        }\n        {\n          intros hp_tsk R_hp IN; apply mem_take in IN.\n          by apply fp_claimed_bounds_ge_cost with (ts' := ts) (rt_bounds := hp_bounds).\n        }\n        {\n          intros hp_tsk R_hp IN; apply mem_take in IN.\n          by apply fp_claimed_bounds_le_deadline with (ts' := ts) (rt_bounds := hp_bounds).\n        }\n        {\n          rewrite REC per_task_rta_fold.\n          apply per_task_rta_converges with (ts_hp := take idx ts);\n            first by apply fp_claimed_bounds_take; try (by apply ltnW).\n          {\n            rewrite SUBST // -take_nth -?SIZE //.\n            by intros i IN; eapply TASKPARAMS, mem_take, IN.\n          }\n          {\n            rewrite -REC.\n            by apply leq_trans with (n := task_jitter (TASK idx) + RESP idx); first by apply leq_addl.\n          }\n        }\n      Qed.\n\n      (* Therefore, if the schedulability test suceeds, ...*)\n      Hypothesis H_test_succeeds: fp_schedulable ts.\n      \n      (*..., no task misses its deadline. *)\n      Theorem taskset_schedulable_by_fp_rta :\n        forall tsk, tsk \\in ts -> no_deadline_missed_by_task tsk.\n      Proof.\n        have RLIST := (fp_analysis_yields_response_time_bounds).\n        have UNZIP := (fp_claimed_bounds_unzip ts).\n        have DL := (fp_claimed_bounds_le_deadline ts).\n        unfold no_deadline_missed_by_task, task_misses_no_deadline,\n               job_misses_no_deadline, completed,\n               fp_schedulable,\n               valid_sporadic_job_with_jitter, valid_sporadic_job in *.\n        rename H_valid_job_parameters into JOBPARAMS.\n        move => tsk INtsk j ARRj JOBtsk.\n        destruct (fp_claimed_bounds ts) as [rt_bounds |]; last by ins.\n        feed (UNZIP rt_bounds); first by done.\n        assert (EX: exists R, (tsk, R) \\in rt_bounds).\n        {\n          rewrite set_mem -UNZIP in INtsk; move: INtsk => /mapP EX.\n          by destruct EX as [p]; destruct p as [tsk' R]; simpl in *; subst tsk'; exists R.\n        } des.\n        exploit (RLIST tsk R); [by done | by apply ARRj | by done | intro COMPLETED].\n        exploit (DL rt_bounds tsk R); [by ins | by ins | clear DL; intro DL].\n        \n        rewrite eqn_leq; apply/andP; split; first by apply cumulative_service_le_job_cost.\n        apply leq_trans with (n := service sched j (job_arrival j + (task_jitter tsk + R)));\n          last first.\n        {\n          unfold valid_sporadic_taskset, is_valid_sporadic_task in *.\n          apply extend_sum; rewrite // leq_add2l.\n          by specialize (JOBPARAMS j ARRj); des; rewrite JOBPARAMS2 JOBtsk.\n        }\n        rewrite leq_eqVlt; apply/orP; left; rewrite eq_sym.\n        by apply COMPLETED.\n      Qed.\n\n      (* For completeness, since all jobs of the arrival sequence\n         are spawned by the task set, we also conclude that no job in\n         the schedule misses its deadline. *)\n      Theorem jobs_schedulable_by_fp_rta :\n        forall j,\n          arrives_in arr_seq j -> no_deadline_missed_by_job j.\n      Proof.\n        intros j ARRj.\n        have SCHED := taskset_schedulable_by_fp_rta.\n        unfold no_deadline_missed_by_task, task_misses_no_deadline in *.\n        apply SCHED with (tsk := job_task j); try (by done).\n        by apply H_all_jobs_from_taskset.\n      Qed.\n      \n    End MainProof.\n\n  End Analysis.\n\nEnd ResponseTimeIterationFP.", "meta": {"author": "cd-public", "repo": "rt-proofs", "sha": "ebef0b65460fe009c51f638fe2b459f16a6d1dd5", "save_path": "github-repos/coq/cd-public-rt-proofs", "path": "github-repos/coq/cd-public-rt-proofs/rt-proofs-ebef0b65460fe009c51f638fe2b459f16a6d1dd5/analysis/global/jitter/bertogna_fp_comp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6735504742887735}}
{"text": "Require Import BinNat.\nRequire Import Omega.\nRequire Import micromega.Lia.\nRequire Import Logic.FunctionalExtensionality.\nRequire Import Program.Basics.\nRequire Import Nnat.\nRequire Import bin_prelims.\nRequire Import bin_repeater.\nRequire Import bin_countdown.\nRequire Import bin_inverse.\nRequire inv_ack.\n\n(*\n==========================================================================\n******* SECTION 13: THE BINARY INVERSE ACKERMANN FUNCTION ****************\n==========================================================================\n *)\n\n(* \n * This section contains the most important application of countdown,\n * the Inverse Ackermann function.\n *\n * We first define an inverse tower for the Ackermann hierarchy, \n * then write a theorem proving its correctness.\n * \n * Then we define a structurally terminating definition for the inverse\n * Ackermann function, and prove its correctness using the above theorem.\n *\n * We digress briefly to state and prove the two-argument inverse \n * Ackermann function, which some authors prefer. Again, inputs are in binary.\n *\n * Finally we state and prove the correctness of the time-bound improvement, \n * which runs in linear time.\n *)\n\nLemma to_nat_diag_ack :\n  (fun n => repeater.ackermann n n) =\n  to_nat_func (fun n : N => bin_ackermann n n).\nProof.\n  apply functional_extensionality. unfold to_nat_func. intro n.\n  rewrite bin_ackermann_correct. repeat rewrite Nat2N.id. trivial.\nQed.\n\n(* Diagonal Strict Increasing *)\nLemma diag_ack_incr : increasing (fun n => bin_ackermann n n).\nProof.\n  rewrite to_nat_func_incr.\n  rewrite <- to_nat_diag_ack. apply inv_ack.diag_ack_incr.\nQed.\n\n\n(* *********** INVERSE ACKERMANN HIERARCHY ******************* *)\n\n(* Definition *)\nFixpoint bin_alpha (m : nat) (x : N) : N :=\n  match m with\n  | 0%nat => x - 1          | 1%nat => x - 2\n  | 2%nat => N.div2 (x - 2) | 3%nat => N.log2 (x + 2) - 2\n  | S m'  => bin_countdown_to (bin_alpha m') 1 (bin_alpha m' x)\n  end.\n\n(* Crucial Lemma to prove the link from level 2 to level 3 *)\nLemma bin_alpha_2_bin_contract :\n    bin_contract_strict_above 1 (bin_alpha 2).\nProof.\n  split; intro n; simpl; rewrite N.div2_div;\n    [apply N.div_le_upper_bound|intro; apply N.div_le_mono]; lia.\nQed.\n\n(* Recursion *)\nTheorem bin_alpha_recursion :\n    forall m, (2 <= m)%nat ->\n              bin_alpha (S m) =\n              compose (bin_countdown_to (bin_alpha m) 1) (bin_alpha m).\nProof.\n  destruct m as [|[|[|m]]]; trivial;\n    [omega | omega | intro]. clear H.\n  apply functional_extensionality; intro n. unfold compose.\n  simpl. rewrite N.div2_div.\n  replace (n - 2) with (n + 2 - 2*2) by lia.\n  rewrite div_sub by lia.\n  replace (N.log2 (n + 2) - 2)\n    with (N.log2 ((n + 2) / 2) - 1)\n    by (rewrite <- N.div2_div, N.div2_spec, N.log2_shiftr; lia).\n  remember ((n + 2) / 2) as m. clear n Heqm.\n  destruct m as [|p]; trivial.\n  induction p; trivial;\n    rewrite bin_countdown_recursion by apply bin_alpha_2_bin_contract;\n    rewrite N.div2_div;\n      [remember (N.pos p~1) as m | remember (N.pos p~0) as m];\n        replace (m - 2 - 2) with (m - 2 * 2) by lia;\n          rewrite div_sub by lia;\n            rewrite <- N.log2_shiftr, <- N.div2_spec, N.div2_div;\n              remember (m - 2 <=? 1) as b;\n                destruct b; symmetry in Heqb.\n  1, 3: rewrite N.leb_le, N.le_sub_le_add_l in Heqb;\n    apply (N.div_le_mono _ _ 2) in Heqb.\n  2, 4: lia.\n  1, 2: unfold N.div at 2 in Heqb; simpl in Heqb;\n    rewrite N.log2_null; trivial.\n  1, 2: replace (Npos p) with (m / 2) in IHp.\n  2: rewrite <- N.div2_succ_double. \n  4: rewrite <- N.div2_double.\n  2, 4: rewrite <- N.div2_div; f_equal; trivial.\n  1, 2: rewrite N.leb_gt in Heqb; rewrite N.add_comm, <- IHp;\n    symmetry; apply N.sub_add;\n      rewrite N.le_ngt, N.lt_1_r, N.log2_null, <- N.lt_succ_r;\n      simpl; rewrite <- N.le_ngt, le_div_mul_N by lia; lia.\nQed.\n\n\n(* ******* CORRECTNESS OF INVERSE ACKERMANN HIERARCHY ************** *)\n\n(* Countdown composed with self preserves binary contractiveness *)\nTheorem countdown_bin_contract : forall f a b,\n    bin_contract_strict_above a f ->\n    bin_contract_strict_above b (compose (bin_countdown_to f a) f).\nProof.\n  intros f a b Haf0. assert (H:=Haf0). destruct H as [Hf Haf].\n  split; intro n; [ |intro Hbn]; unfold compose;\n    rewrite bin_countdown_repeat by assumption; rewrite <- repeat_S_comm;\n      rewrite N.le_ngt; intro;\n        apply (repeat_bin_contract_strict _ _ _ _ Haf0) in H.\n  - specialize (nat_size_contract (n - a)).\n    rewrite N2Nat.inj_sub. omega.\n  - replace (nat_size (n - a)) with\n      (S (nat_size ((n - a) / 2))) in H.\n    + specialize (nat_size_contract ((n - a) / 2)) as H0.\n      simpl in H. rewrite <- Nat.succ_le_mono in H.\n      apply (Nat.le_trans _ _ _ H) in H0.\n      assert (S (N.to_nat (n/2)) <= N.to_nat (n/2))%nat as contra.\n      2: omega.\n      apply (Nat.le_trans _ (S (N.to_nat ((n + b) / 2))) _);\n        [rewrite <- Nat.succ_le_mono |\n         apply (Nat.le_trans _ (N.to_nat ((n - a) / 2)) _)].\n      1,3 : rewrite <- le_N_nat; apply N.div_le_mono; lia.\n      apply (Nat.le_trans _\n            (S (N.to_nat ((n + b) / 2) +\n                nat_size (f (f (repeat f (N.to_nat ((n + b) / 2)) n)) - a)))\n             _);\n        omega. \n    + rewrite <- N.div2_div.\n      destruct (n - a); [simpl in H; omega | induction p; trivial].\nQed.\n\nLemma bin_alpha_2_correct : forall n,\n    bin_alpha 2 n = N.of_nat (inv_ack.alpha 2 (N.to_nat n)).\nProof.\n  intro n. unfold bin_alpha. unfold to_N_func.\n  remember (N.to_nat n) as m.\n  replace (n - 2) with (N.of_nat (m - 2)) by lia.\n  rewrite <- Nat2N.inj_div2. f_equal. clear Heqm. clear n.\n  replace (inv_ack.alpha 2 m) with\n    (countdown.countdown_to (inv_ack.alpha 1) 1 (inv_ack.alpha 1 m))\n      by trivial.\n  rewrite inv_ack.alpha_1.\n  generalize (m - 2)%nat. clear m. intro n.\n  assert (Nat.div2 n =\n          countdown.countdown_to (fun n0 : nat => (n0 - 2)%nat) 1 n\n          /\\ Nat.div2 (S n) =\n             countdown.countdown_to (fun n0 : nat => (n0 - 2)%nat) 1 (S n)).\n  { induction n; split; trivial. apply IHn.\n    destruct (countdown.countdown_recursion 1\n               (fun n0 => (n0-2)%nat) (S(S n))) as [_ H].\n    - split; intro m; omega.\n    - rewrite H by omega. replace (S(S n) - 2)%nat with n by omega.\n      simpl. f_equal. apply IHn. }\n  apply H.\nQed.\n\n(* \n * Every bin_alpha level starting from 2 is strictly binary \n * contracting above 1, so bin_countdown_to to 1 works \n * properly for them. \n *)\nTheorem bin_alpha_contract_strict_above_1 : forall m,\n    (2 <= m)%nat -> bin_contract_strict_above 1 (bin_alpha m).\nProof.\n  destruct m as [|[|m]]; try omega; intro; clear H. induction m.\n  - split; intro n; simpl; rewrite N.div2_div;\n      [apply N.div_le_upper_bound|intro; apply N.div_le_mono]; lia.\n  - rewrite bin_alpha_recursion; [| omega].\n    apply (countdown_bin_contract _ _ _ IHm).\nQed.\n\nTheorem bin_alpha_correct :\n    forall m, bin_alpha m = to_N_func (inv_ack.alpha m).\nProof.\n  induction m as [|[|[|m]]]; apply functional_extensionality;\n    intro n; unfold to_N_func. 2: rewrite inv_ack.alpha_1.\n  1,2: simpl; lia. 1: apply bin_alpha_2_correct.\n  rewrite bin_alpha_recursion by omega. unfold compose.\n  rewrite bin_countdown_correct by\n      (apply bin_alpha_contract_strict_above_1; omega).\n  rewrite IHm. rewrite <- nat_N_func_id.\n  replace (N.to_nat 1) with 1%nat by trivial.\n  unfold to_N_func. f_equal. rewrite Nat2N.id. trivial.\nQed.\n\nCorollary bin_alpha_ackermann :\n    forall m, upp_inv_rel (bin_alpha m) (bin_ackermann (N.of_nat m)).\nProof.\n  intros m n p. rewrite <- (N2Nat.id n). rewrite bin_ackermann_correct.\n  rewrite bin_alpha_correct. unfold to_N_func. rewrite <- le_nat_N.\n  rewrite le_N_nat. repeat rewrite Nat2N.id.\n  destruct (inv_ack.alpha_correct m) as [_ H]. apply H.\nQed.\n\n\n(* ********* TWO PARAMETERS INVERSE ACKERMANN ************* *)\n\n(* Two parameters Binary Inverse Ackerman worker function *)\nFixpoint two_params_bin_inv_ack_wkr (f : N -> N) (n k : N) (b : nat) : N :=\n  match b with\n  | 0%nat => 0\n  | S b'  => if (n <=? k) then 0\n              else let g := (bin_countdown_to f 1) in\n                   N.succ (two_params_bin_inv_ack_wkr (compose g f) (g n) k b')\n  end.\n\n(* Two parameters Binary Inverse Ackermann function *)\nDefinition two_params_bin_inv_ack (m n : N) : N :=\n  let n' := (N.log2_up n) in\n    let m' := m / n in\n      if (n' - 2 <=? m') then 1\n        else if (N.div2 (n' - 2) <=? m') then 2\n          else let f := (fun x => N.log2 (x + 2) - 2) in\n            3 + two_params_bin_inv_ack_wkr f (f n') m' (nat_size n).\n\n(* Correctness proofs begin here *)\n\n(* Small helper lemma - alpha decreases by level *)\nLemma bin_alpha_decr_by_lvl :\n    forall i n, bin_alpha (S i) n <= bin_alpha i n.\nProof.\n  intros i n. repeat rewrite bin_alpha_correct.\n  unfold to_N_func. rewrite <- le_nat_N.\n  apply inv_ack.alpha_decr_by_lvl.\nQed.\n\n(* Lemma about worker function's inner working *)\nLemma two_params_bin_inv_ack_wkr_intermediate :\n    forall i n k b, k < bin_alpha (S (S i)) n -> (i <= b)%nat ->\n      two_params_bin_inv_ack_wkr (bin_alpha 3) (bin_alpha 3 n) k b =\n        N.of_nat i +\n          two_params_bin_inv_ack_wkr\n            (bin_alpha (S (S (S i)))) (bin_alpha (S (S (S i))) n) k (b - i).\nProof.\n  induction i; intros n k b Hin Hib.\n  - rewrite N.add_0_l. f_equal. omega.\n  - rewrite IHi.\n    2: apply (N.lt_le_trans _ (bin_alpha (S (S (S i))) n) _ Hin),\n               bin_alpha_decr_by_lvl. \n    2: omega.\n    unfold two_params_bin_inv_ack_wkr at 1.\n    replace (b - i)%nat with (S (b - (S i)))%nat by omega.\n    rewrite <- N.leb_gt in Hin. rewrite Hin.\n    fold two_params_bin_inv_ack_wkr.\n    rewrite <- N.add_succ_comm. f_equal. lia.\nQed.\n\n(* Correctness theorem for two_params_bin_inv_ack worker *)\nTheorem two_params_bin_inv_ack_upp_inv :\n    forall m n, two_params_bin_inv_ack m n =\n      1 + upp_inv (fun x => bin_ackermann (N.succ x) (m / n)) (N.log2_up n).\nProof.\n  intros m n. unfold two_params_bin_inv_ack.\n  remember (N.log2_up n) as b. remember (m / n) as a.\n  fold (bin_alpha 2 b). fold (bin_alpha 1 b). fold (bin_alpha 3 b).\n  assert (increasing (fun x : N => bin_ackermann (N.succ x) a)) as HF.\n  { unfold increasing. intros x y.\n    repeat rewrite bin_ackermann_correct.\n    rewrite <- lt_nat_N. repeat rewrite N2Nat.inj_succ.\n    rewrite lt_N_nat, Nat.succ_lt_mono. apply inv_ack.ack_incr_by_lvl.\n  }\n  assert (N.to_nat b <= nat_size n)%nat as Hb.\n  { rewrite Heqb, nat_size_log2_up, <- le_N_nat.\n    apply N.log2_up_le_mono. lia. }\n  remember (nat_size n) as t. clear Heqb Heqa Heqt m n.\n  remember (upp_inv (fun x : N => bin_ackermann (N.succ x) a) b) as q.\n  assert (upp_inv_rel (upp_inv (fun x : N => bin_ackermann (N.succ x) a))\n          (fun x : N => bin_ackermann (N.succ x) a)) as HfF.\n  { apply upp_inv_correct, HF. }\n  assert (bin_alpha (S (N.to_nat q)) b <= a) as Hq.\n  { apply bin_alpha_ackermann.\n    replace (N.of_nat _) with (N.succ q) by lia. apply HfF. lia. }\n  remember (N.to_nat q) as p. replace q with (N.of_nat p) in * by lia.\n  clear Heqp q. destruct p.\n  - rewrite <- N.leb_le in Hq. rewrite Hq. trivial.\n  - assert (a < bin_alpha (S p) b) as Hp.\n    { rewrite N.lt_nge, (bin_alpha_ackermann (S p) a b), Nat2N.inj_succ.\n      rewrite <- (HfF (N.of_nat p) b). lia. }\n    destruct p.\n    + rewrite <- N.leb_gt in Hp. rewrite Hp.\n      rewrite <- N.leb_le in Hq. rewrite Hq. trivial.\n    + assert (a < bin_alpha 2 b <= bin_alpha 1 b) as H12.\n      { split; [|apply bin_alpha_decr_by_lvl].\n        apply (N.lt_le_trans _ (bin_alpha (S (S p)) b) _ Hp).\n        clear Hq Hp Heqq. induction p; [lia|].\n        apply (N.le_trans _ (bin_alpha (S (S p)) b) _).\n        apply bin_alpha_decr_by_lvl. apply IHp. }\n      destruct H12 as [H2 H1]. apply (N.lt_le_trans _ _ _ H2) in H1.\n      rewrite <- N.leb_gt in H1. rewrite <- N.leb_gt in H2.\n      rewrite H1, H2. fold (bin_alpha 3).\n      replace (1 + N.of_nat (S (S p))) with (3 + (N.of_nat p)) by lia.\n      f_equal.\n      rewrite (two_params_bin_inv_ack_wkr_intermediate p _ _ _ Hp).\n      * rewrite <- N.add_0_r. f_equal.\n        destruct (t - p)%nat; trivial. rewrite <- N.leb_le in Hq.\n        unfold two_params_bin_inv_ack_wkr. rewrite Hq. trivial.\n      * apply (Nat.le_trans _ (N.to_nat b) _); trivial.\n        rewrite N.lt_nge, (bin_alpha_ackermann (S (S p)) a b),\n          <- N.lt_nge, lt_N_nat in Hp.\n        apply (Nat.le_trans _\n                 (N.to_nat (bin_ackermann (N.of_nat (S (S p))) a)) _);\n        [|lia]. rewrite bin_ackermann_correct. repeat rewrite Nat2N.id.\n        clear Hq Heqq Hp. induction p; [omega|]. rewrite Nat.le_succ_l.\n        apply (Nat.le_lt_trans _ _ _ IHp).\n        apply inv_ack.ack_incr_by_lvl. omega.\nQed.\n\n\n\n(* *********** INVERSE ACKERMANN FUNCTION ******************** *)\n\nFixpoint bin_inv_ack_wkr (f : N -> N) (n k : N) (b : nat) : N :=\n  match b with\n  | 0%nat  => k\n  | S b' =>\n    if n <=? k then k\n    else let g := (bin_countdown_to f 1) in\n         bin_inv_ack_wkr (compose g f) (g n) (N.succ k) b'\n  end.\n\n(* IMPORTANT *)\n(* Definition by hard-coding the second bin_alpha level, runtime O(n) *)\nDefinition bin_inv_ack n :=\n  if (n <=? 1) then 0\n  else if (n <=? 3) then 1\n       else if (n <=? 7) then 2\n            else let f := (fun x => N.log2 (x + 2) - 2) in\n                 bin_inv_ack_wkr f (f n) 3 (nat_size n).\n\n(* Below we give a correctness proof of the above definition. *)\n\n(* Intermediate lemmas about bin_inv_ack_wkr *)\nLemma bin_alpha_contr : forall i n,\n    (S i < N.to_nat (bin_alpha (S i) n))%nat ->\n    (i < N.to_nat (bin_alpha i n))%nat.\nProof.\n  intros i n. specialize (bin_alpha_ackermann i (N.of_nat i) n).\n  specialize (bin_alpha_ackermann (S i) (N.of_nat (S i)) n).\n  specialize (diag_ack_incr (N.of_nat i) (N.of_nat (S i))). lia.\nQed.\n\nLemma bin_inv_ack_wkr_intermediate : forall i n b,\n    (S (S i) < N.to_nat (bin_alpha (S (S i)) n))%nat ->\n    (S (S i) < b)%nat ->\n    bin_inv_ack_wkr (bin_alpha 3) (bin_alpha 3 n) 3 b =\n    bin_inv_ack_wkr (bin_alpha (S (S (S i))))\n                    (bin_alpha (S (S (S i))) n) (N.of_nat (S (S (S i)))) (b - i).\nProof.\n  induction i; intros n b Hn Hib; symmetry;\n    [f_equal; omega | rewrite bin_alpha_recursion by omega].\n  rewrite IHi; [replace (b - i)%nat with (S (b - S i))%nat by omega\n               |apply (bin_alpha_contr _ _ Hn) | omega].\n  rewrite lt_nat_N, N2Nat.id in Hn. rewrite <- N.leb_gt in Hn.\n  unfold bin_inv_ack_wkr at 2. rewrite Hn. rewrite <- Nat2N.inj_succ. trivial.\nQed.\n\n(* Proof that bin_inv_ack_wkr is correct given sufficient budget *)\nLemma bin_inv_ack_wkr_sufficient :\n  forall n b,\n    (8 <= n <= bin_ackermann b b) ->\n      bin_inv_ack_wkr (bin_alpha 3) (bin_alpha 3 n) 3 (N.to_nat b)\n        = upp_inv (fun m => bin_ackermann m m) n.\nProof.\n  assert (Hincr := diag_ack_incr).\n  assert (Hack := upp_inv_correct _ Hincr).\n  unfold upp_inv_rel in Hack. intros n b [Hn Hnb].\n  remember (N.to_nat (upp_inv (fun m : N => bin_ackermann m m) n)) as p.\n  rewrite <- (Nat2N.id p) in Heqp. apply N2Nat.inj in Heqp.\n  assert (n <= bin_ackermann (N.of_nat p) (N.of_nat p)) as Hp0 by\n        (apply Hack; lia).\n  destruct p as [|[|[|p]]].\n  1,2,3 : unfold N.of_nat in Heqp; unfold bin_ackermann in Hp0;\n    simpl in Hp0; lia.\n  assert (bin_ackermann (N.of_nat (S (S p))) (N.of_nat (S (S p))) < n)\n      as Hp1\n      by (rewrite N.lt_nge; rewrite <- Hack; lia).\n  assert (S (S p) < N.to_nat b)%nat as Hpb.\n  { rewrite Nat.lt_nge. intro Hc.\n    inversion Hc as [Hc0|Hc1]. rewrite <- Hc0 in Hp1.\n    rewrite N2Nat.id in Hp1. lia.\n    rewrite prelims.lt_S_le, lt_nat_N, N2Nat.id in H.\n    apply Hincr in H. lia. }\n  rewrite (bin_inv_ack_wkr_intermediate p).\n  - replace (N.to_nat b - p)%nat with\n      (S (N.to_nat b - S p))%nat by omega.\n    unfold bin_inv_ack_wkr.\n    replace (bin_alpha (S (S (S p))) n <=? N.of_nat (S (S (S p))))\n      with true;\n        trivial.\n    symmetry. rewrite N.leb_le.\n    rewrite (bin_alpha_ackermann (S (S (S p))) _ _). apply Hp0.\n  - rewrite lt_nat_N. rewrite N2Nat.id. rewrite N.lt_nge.\n    rewrite (bin_alpha_ackermann (S (S p)) _ _). lia.\n  - apply Hpb.\nQed.\n\n(* Helper lemmas regarding ackermann at level 3 *)\nOpen Scope nat_scope.\n\nLemma ack_2 : forall n, repeater.ackermann 2 n = 2 * n + 3.\nProof.\n  induction n; trivial.\n  replace (repeater.ackermann 2 (S n)) with\n    (repeater.ackermann 1 (repeater.ackermann 2 n)) by trivial.\n  rewrite IHn. rewrite inv_ack.ack_1. omega.\nQed.\n\nLemma ack_3 : forall n, repeater.ackermann 3 n = 2 ^ (n + 3) - 3.\nProof.\n  induction n; trivial.\n  replace (repeater.ackermann 3 (S n)) with\n    (repeater.ackermann 2 (repeater.ackermann 3 n)) by trivial.\n  rewrite IHn. rewrite ack_2.\n  replace (S n + 3) with (S (n + 3)) by trivial.\n  replace (2 ^ (S (n+3))) with (2 * 2 ^ (n+3)) by trivial.\n  assert (3 <= 2 ^ (n+3)).\n  { apply (Nat.le_trans _ (2^3) _); [simpl; omega|].\n    apply Nat.pow_le_mono_r; omega. } omega.\nQed.\n\nClose Scope nat_scope.\n\n(* Proof that bin_inv_ack is correct *)\nTheorem bin_inv_ack_correct : bin_inv_ack = to_N_func (inv_ack.inv_ack).\nProof.\n  apply functional_extensionality. intro n.\n  assert (n = 0 \\/ n = 1 \\/ n = 2 \\/ n = 3 \\/ n = 4 \\/\n          n = 5 \\/ n = 6 \\/ n = 7 \\/ 8 <= n) as Hn by lia.\n  repeat destruct Hn as [Hn|Hn]; try rewrite Hn; trivial.\n  unfold bin_inv_ack.\n  replace (n <=? 1) with false by (symmetry; rewrite N.leb_gt; lia).\n  replace (n <=? 3) with false by (symmetry; rewrite N.leb_gt; lia).\n  replace (n <=? 7) with false by (symmetry; rewrite N.leb_gt; lia).\n  rewrite <- (Nat2N.id (nat_size n)). fold (bin_alpha 3).\n  fold (bin_alpha 3 n). rewrite bin_inv_ack_wkr_sufficient.\n  - unfold upp_inv. f_equal. rewrite <- to_nat_diag_ack. symmetry.\n    apply inverse.upp_inv_unique. apply inv_ack.diag_ack_incr.\n    apply inv_ack.inv_ack_correct.\n  - split; [lia|]. rewrite bin_ackermann_correct. rewrite Nat2N.id.\n    apply (N.le_trans _ (N.of_nat (repeater.ackermann 3 (nat_size n))) _).\n    + clear Hn. rewrite le_N_nat. rewrite Nat2N.id.\n      rewrite ack_3. destruct n; simpl; [lia|].\n      induction p; [| |simpl; lia]; simpl;\n        [rewrite Pos2Nat.inj_xI|rewrite Pos2Nat.inj_xO];\n        assert (3 <=\n          2 ^ ((fix nat_pos_size (x : positive) : nat :=\n                 match x with\n                 | (y~1)%positive | (y~0)%positive => S (nat_pos_size y)\n                 | 1%positive => 1\n                 end) p + 3))%nat\n          by (apply (Nat.le_trans _ (2^3) _); [simpl; omega|];\n              apply Nat.pow_le_mono_r; omega); omega.\n    + rewrite <- le_nat_N. rewrite Nat.le_ngt.\n      assert (H := inv_ack.ack_incr_by_lvl (nat_size n)).\n      apply (increasing_expanding.incr_twoways _ (nat_size n) 3) in H.\n      simpl in *. rewrite <- H. apply nat_size_incr in Hn.\n      simpl in Hn. omega.\nQed.\n\n(* Please see inv_ack_test.v for a demonstration of the runtime of bin_inv_ack *)", "meta": {"author": "inv-ack", "repo": "inv-ack", "sha": "195209ba895061fc51368c3c46c1d8760f05df50", "save_path": "github-repos/coq/inv-ack-inv-ack", "path": "github-repos/coq/inv-ack-inv-ack/inv-ack-195209ba895061fc51368c3c46c1d8760f05df50/bin_inv_ack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6735504717954}}
{"text": "(* This file is generated by Why3's Coq driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import ZArith.\nRequire Import Rbase.\nRequire int.Int.\nRequire real.Real.\nRequire real.RealInfix.\n\nParameter pow2: Z -> R.\n\nAxiom Power_0 : ((pow2 0%Z) = 1%R).\n\nAxiom Power_s : forall (n:Z), (0%Z <= n)%Z ->\n  ((pow2 (n + 1%Z)%Z) = (2%R * (pow2 n))%R).\n\nAxiom Power_p : forall (n:Z), (n <= 0%Z)%Z ->\n  ((pow2 (n - 1%Z)%Z) = ((05 / 10)%R * (pow2 n))%R).\n\nAxiom Power_s_all : forall (n:Z), ((pow2 (n + 1%Z)%Z) = (2%R * (pow2 n))%R).\n\nAxiom Power_p_all : forall (n:Z),\n  ((pow2 (n - 1%Z)%Z) = ((05 / 10)%R * (pow2 n))%R).\n\nAxiom Power_1_2 : ((05 / 10)%R = (Rdiv 1%R 2%R)%R).\n\nAxiom Power_1 : ((pow2 1%Z) = 2%R).\n\nAxiom Power_neg1 : ((pow2 (-1%Z)%Z) = (05 / 10)%R).\n\nAxiom Power_non_null_aux : forall (n:Z), (0%Z <= n)%Z -> ~ ((pow2 n) = 0%R).\n\nAxiom Power_neg_aux : forall (n:Z), (0%Z <= n)%Z ->\n  ((pow2 (-n)%Z) = (Rdiv 1%R (pow2 n))%R).\n\nAxiom Power_non_null : forall (n:Z), ~ ((pow2 n) = 0%R).\n\nAxiom Power_neg : forall (n:Z), ((pow2 (-n)%Z) = (Rdiv 1%R (pow2 n))%R).\n\nOpen Scope Z_scope.\n\n(* Why3 goal *)\nTheorem Power_sum_aux : forall (n:Z) (m:Z), (0%Z <= m)%Z ->\n  ((pow2 (n + m)%Z) = ((pow2 n) * (pow2 m))%R).\n(* YOU MAY EDIT THE PROOF BELOW *)\nintros n m Hmpos.\ncut (0 <= m); auto with zarith.\napply Z_lt_induction with\n  (P:= fun m => \n      0 <= m ->pow2 (n + m) = (pow2 n * pow2 m)%R);\n  auto with zarith.\nintros x Hind Hxpos.\nassert (h:(x = 0 \\/ x > 0)) by omega.\ndestruct h.\nsubst x.\nrewrite Power_0.\nreplace (n+0) with n by omega.\nrewrite Rmult_1_r.\nauto.\nreplace (x) with ((x-1)+1) by omega.\nrewrite Power_s_all;auto with zarith.\nreplace (n + (x-1+1)) with (n+(x-1)+1) by omega.\nrewrite Power_s_all;auto with zarith.\nrewrite Hind;auto with zarith.\nrewrite <-Rmult_assoc.\nrewrite <-Rmult_assoc.\nrewrite Rmult_comm with (r1:=pow2 n)(r2:=2%R).\nauto with zarith.\n\nQed.\n\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/tests/bitvector1/bitvector1_Pow2real_Power_sum_aux_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6735504618219058}}
{"text": "Require Import Problem Omega Znumtheory.\nImport ZArith.Zdiv.\n\nLemma prime_not_0 : forall p, prime p -> p <> 0.\nProof.\n  intros.\n  contradict H.\n  subst p.\n  apply not_prime_0.\nQed.\n\nLemma zero_factor (p a b : Z) : prime p -> (a * b) mod p = 0 -> a mod p = 0 \\/ b mod p = 0.\nProof.\n  intros.\n  assert (p <> 0) by (apply prime_not_0; auto).\n  apply (Zmod_divide (a * b) p H1) in H0; clear H1.\n  apply (prime_mult p H) in H0.\n  destruct H0; apply Zdivide_mod in H0; auto.\nQed.\n\nLemma transpose (p a b : Z) : p > 0 -> a mod p = b mod p -> (a - b) mod p = 0.\nProof.\n  intros.\n  rewrite (Zmod_eq a p H) in H0.\n  rewrite (Zmod_eq b p H) in H0.\n  assert (forall x y z w : Z, x - z = y - w -> x - y = z - w) by (intros; omega).\n  apply (H1 a b (a / p * p) (b / p * p)) in H0; clear H1.\n  rewrite <- Z.mul_sub_distr_r in H0.\n  rewrite H0.\n  apply Z_mod_mult.\nQed.\n\nTheorem solution: task.\nProof.\n  unfold task.\n  intros.\n  destruct H0; destruct H1; destruct H2.\n  apply transpose in H3; [|omega].\n  rewrite <- Z.mul_sub_distr_r in H3.\n  apply zero_factor in H3; [|auto].\n  destruct H3.\n  - assert (0 <= k1 - k2 < p \\/ 0 <= k2 - k1 < p) by omega.\n    destruct H7.\n    * rewrite Zmod_small in H3; omega.\n    * apply Z_mod_zero_opp_full in H3.\n      rewrite Zmod_small in H3; omega.\n  - rewrite Zmod_small in H3; omega.\nQed.\n", "meta": {"author": "tzik", "repo": "top-prover", "sha": "3f92af1e76e437bee6b49152f11a6dfb3b730a61", "save_path": "github-repos/coq/tzik-top-prover", "path": "github-repos/coq/tzik-top-prover/top-prover-3f92af1e76e437bee6b49152f11a6dfb3b730a61/tasks/024/Solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6735241037711578}}
{"text": "(* This file contains lemmas regarding the accuracy of floating point \n  operations such as BPLUS, BFMA, and BMULT. *)\n\nRequire Import vcfloat.VCFloat vcfloat.FPLib.\nFrom vcfloat Require Import IEEE754_extra.\nRequire Import common op_defs.\nRequire Import ZArith.\nLocal Open Scope R.\n\nSection NAN.\n\nDefinition fma_no_overflow (t: type) (x y z: R) : Prop :=\n  (Rabs (rounded t  (x * y + z)) < Raux.bpow Zaux.radix2 (femax t))%R.\n\n\nDefinition Bmult_no_overflow (t: type) (x y: R) : Prop :=\n  (Rabs (rounded t  (x * y)) < Raux.bpow Zaux.radix2 (femax t))%R.\n\n\nLemma generic_round_property:\n  forall (t: type) (x: R),\nexists delta epsilon : R,\n   delta * epsilon = 0 /\\\n  (Rabs delta <= default_rel t)%R /\\\n  (Rabs epsilon <= default_abs t)%R /\\\n   Generic_fmt.round Zaux.radix2\n              (SpecFloat.fexp (fprec t) (femax t))\n              (BinarySingleNaN.round_mode BinarySingleNaN.mode_NE)\n               x = (x * (1+delta)+epsilon)%R.\nProof.\nintros.\ndestruct (Relative.error_N_FLT Zaux.radix2 (SpecFloat.emin (fprec t) (femax t)) (fprec t) \n             (fprec_gt_0 t) (fun x0 : Z => negb (Z.even x0)) x)\n  as [delta [epsilon [? [? [? ?]]]]].\nexists delta, epsilon.\nsplit; [ | split]; auto.\nQed.\n\nLemma fma_accurate {NAN: Nans} : \n   forall (t: type) \n             (x: ftype t) (FINx: finite x) \n             y (FINy: finite y) \n             z (FINz: finite z)\n          (FIN: fma_no_overflow t (FT2R x) (FT2R y) (FT2R z)), \n  exists delta, exists epsilon,\n   delta * epsilon = 0 /\\\n   Rabs delta <= default_rel t /\\\n   Rabs epsilon <= default_abs t /\\ \n   (FT2R (BFMA x y z) = (FT2R x * FT2R y + FT2R z) * (1+delta) + epsilon)%R.\nProof.\nintros.\nrewrite finite_is_finite in FINx.\nrewrite finite_is_finite in FINy.\nrewrite finite_is_finite in FINz.\npose proof (Binary.Bfma_correct  (fprec t) (femax t)  (fprec_gt_0 t) (fprec_lt_femax t) (fma_nan t)\n                      BinarySingleNaN.mode_NE x y z FINx FINy FINz).\nchange (Binary.B2R (fprec t) (femax t) ?x) with (@FT2R t x) in *.\ncbv zeta in H.\npose proof (\n   Raux.Rlt_bool_spec\n        (Rabs\n           (Generic_fmt.round Zaux.radix2\n              (SpecFloat.fexp (fprec t) (femax t))\n              (BinarySingleNaN.round_mode\n                 BinarySingleNaN.mode_NE) (FT2R x * FT2R y + FT2R z)))\n        (Raux.bpow Zaux.radix2 (femax t))).\ndestruct H0.\n-\ndestruct H as [? _].\nfold (@BFMA NAN t) in H.\nrewrite H.\napply generic_round_property.\n-\nred in FIN. unfold rounded in FIN.\nLra.lra.\nQed.\n\nLemma is_finite_fma_no_overflow {NAN: Nans} (t : type) :\n  forall (x y z : ftype t)\n  (HFINb : finite (BFMA x y z)),\n  fma_no_overflow t (FT2R x) (FT2R y) (FT2R z).\nProof.\nintros.\nred. set (ov:= bpow Zaux.radix2 (femax t)).\npose proof Rle_or_lt ov (Rabs (rounded t (FT2R x * FT2R y + FT2R z)))  as Hor;\n  destruct Hor; auto.\napply Rlt_bool_false in H.\ndestruct (BFMA_finite_e _ _ _ HFINb) as (A & B & C).\nunfold rounded, FT2R, ov in H.\nrewrite finite_is_finite in *.\npose proof (Binary.Bfma_correct  (fprec t) (femax t)  \n    (fprec_gt_0 t) (fprec_lt_femax t) (fma_nan t) BinarySingleNaN.mode_NE x y z A B C) as\n  H0.\nsimpl in H0; simpl in H;\nrewrite H in H0. clear H. fold (@BFMA NAN t) in H0.\ndestruct (BFMA x y z); try discriminate.\nQed.\n\nLemma fma_accurate' {NAN: Nans} : \n   forall (t: type) (x y z : ftype t)\n          (FIN: finite (BFMA x y z)), \n  exists delta, exists epsilon,\n   delta * epsilon = 0 /\\\n   Rabs delta <= default_rel t /\\\n   Rabs epsilon <= default_abs t /\\ \n   (FT2R (BFMA x y z) = (FT2R x * FT2R y + FT2R z) * (1+delta) + epsilon)%R.\nProof.\nintros.\ndestruct (BFMA_finite_e _ _ _ FIN) as (A & B & C).\napply fma_accurate; auto.\napply is_finite_fma_no_overflow; auto.\nQed.\n\nLemma BMULT_accurate {NAN: Nans}: \n   forall (t: type) (x y: ftype t) (FIN: Bmult_no_overflow t (FT2R x) (FT2R y)), \n  exists delta, exists epsilon,\n   delta * epsilon = 0 /\\\n   Rabs delta <= default_rel t /\\\n   Rabs epsilon <= default_abs t /\\ \n   (FT2R (BMULT x y) = (FT2R x * FT2R y) * (1+delta) + epsilon)%R.\nProof.\nintros.\npose proof (Binary.Bmult_correct (fprec t) (femax t) (fprec_gt_0 t) (fprec_lt_femax t) \n                (mult_nan t) BinarySingleNaN.mode_NE x y).\nchange (Binary.B2R (fprec t) (femax t) ?x) with (@FT2R t x) in *.\ncbv zeta in H.\npose proof (\n   Raux.Rlt_bool_spec\n        (Rabs\n           (Generic_fmt.round Zaux.radix2\n              (SpecFloat.fexp (fprec t) (femax t))\n              (BinarySingleNaN.round_mode\n                 BinarySingleNaN.mode_NE) (FT2R x * FT2R y)))\n        (Raux.bpow Zaux.radix2 (femax t))).\ndestruct H0.\ndestruct H as [? _].\nunfold BMULT, BINOP.\nrewrite H.\napply generic_round_property.\nred in FIN. unfold rounded in FIN.\nLra.lra.\nQed.\n\nLemma finite_BMULT_no_overflow {NAN: Nans} (t : type) :\n  forall (x y : ftype t) \n  (HFINb :finite (BMULT x y)),\n  Bmult_no_overflow t (FT2R x) (FT2R y).\nProof.\nintros.\nrewrite finite_is_finite in HFINb.\npose proof Rle_or_lt (bpow Zaux.radix2 (femax t)) \n  (Rabs (rounded t (FT2R x * FT2R y)))  as Hor;\n  destruct Hor; auto.\napply Rlt_bool_false in H; red.\nunfold rounded, FT2R  in H.\npose proof (Binary.Bmult_correct  (fprec t) (femax t)  \n    (fprec_gt_0 t) (fprec_lt_femax t) (mult_nan t) BinarySingleNaN.mode_NE x y) as\n  H0.\nsimpl in H0; simpl in H;\nrewrite H in H0.  unfold BMULT, BINOP in HFINb.\ndestruct ((Binary.Bmult (fprec t) (femax t) (fprec_gt_0 t) \n             (fprec_lt_femax t) (mult_nan t) BinarySingleNaN.mode_NE x y));\nsimpl;  try discriminate.\nQed.\n\nLemma BMULT_accurate' {NAN: Nans}: \n  forall (t: type) \n  (x y : ftype t) \n  (FIN: finite (BMULT x y)), \n  exists delta, exists epsilon,\n   delta * epsilon = 0 /\\\n   Rabs delta <= default_rel t /\\\n   Rabs epsilon <= default_abs t /\\ \n   (FT2R (BMULT x y) = (FT2R x * FT2R y) * (1+delta) + epsilon)%R.\nProof.\nintros. \npose proof BMULT_accurate t x y (finite_BMULT_no_overflow t x y FIN); auto.\nQed.\n\n\nDefinition Bplus_no_overflow (t: type) (x y: R) : Prop :=\n  (Rabs ( Generic_fmt.round Zaux.radix2\n              (SpecFloat.fexp (fprec t) (femax t))\n              (BinarySingleNaN.round_mode\n                 BinarySingleNaN.mode_NE)  (x + y )) < Raux.bpow Zaux.radix2 (femax t))%R.\n\nLemma BPLUS_neg_zero {NAN: Nans} (t : type) (a : ftype t) :\n  finite a ->\n  BPLUS a neg_zero = a.\nProof.\ndestruct a; try contradiction; unfold neg_zero; simpl; auto.\ndestruct s; auto.\nQed.\n\nLemma BPLUS_accurate {NAN: Nans} (t : type) :\n forall   (x: ftype t) (FINx: finite x) \n             y (FINy: finite y) \n          (FIN: Bplus_no_overflow t (FT2R x) (FT2R y)), \n  exists delta, \n   Rabs delta <= default_rel t /\\\n   (FT2R (BPLUS x y ) = (FT2R x + FT2R y) * (1+delta))%R.\nProof.\nintros.\nrewrite finite_is_finite in FINx, FINy. \npose proof (Binary.Bplus_correct  (fprec t) (femax t)  (fprec_gt_0 t) (fprec_lt_femax t) (plus_nan t)\n                      BinarySingleNaN.mode_NE x y FINx FINy).\nchange (Binary.B2R (fprec t) (femax t) ?x) with (@FT2R t x) in *.\ncbv zeta in H.\npose proof (\n   Raux.Rlt_bool_spec\n        (Rabs\n           (Generic_fmt.round Zaux.radix2\n              (SpecFloat.fexp (fprec t) (femax t))\n              (BinarySingleNaN.round_mode\n                 BinarySingleNaN.mode_NE) (FT2R x + FT2R y)))\n        (Raux.bpow Zaux.radix2 (femax t))).\ndestruct H0.\n-\ndestruct H as [? _].\nunfold BPLUS, BINOP.\nrewrite H. \nassert (A: Generic_fmt.generic_format Zaux.radix2\n       (FLT.FLT_exp (SpecFloat.emin (fprec t) (femax t)) (fprec t))\n       (FT2R x) ) by (apply Binary.generic_format_B2R).\nassert (B: Generic_fmt.generic_format Zaux.radix2\n       (FLT.FLT_exp (SpecFloat.emin (fprec t) (femax t)) (fprec t))\n       (FT2R y) ) by (apply Binary.generic_format_B2R).\npose proof Plus_error.FLT_plus_error_N_ex   Zaux.radix2 (SpecFloat.emin (fprec t) (femax t))\n (fprec t) (fun x0 : Z => negb (Z.even x0)) (FT2R x) (FT2R y) A B.\nunfold Relative.u_ro in H1. fold (default_rel t) in H1.\ndestruct H1 as (d & Hd & Hd').\n \nassert (  Generic_fmt.round Zaux.radix2 (SpecFloat.fexp (fprec t) (femax t))\n    (BinarySingleNaN.round_mode BinarySingleNaN.mode_NE)\n    (FT2R x + FT2R y)  =  Generic_fmt.round Zaux.radix2\n        (FLT.FLT_exp (SpecFloat.emin (fprec t) (femax t)) (fprec t))\n        (Generic_fmt.Znearest (fun x0 : Z => negb (Z.even x0)))\n        (FT2R x + FT2R y)) by auto.\nrewrite <- H1 in Hd'. clear H1. rewrite Hd'; clear Hd'.\nexists d; split; auto.\neapply Rle_trans; [apply Hd |].\napply Rdiv_le_left.\napply Fourier_util.Rlt_zero_pos_plus1. \napply default_rel_gt_0.\neapply Rle_trans with (default_rel t * 1); try nra.\n-\nred in FIN.\nLra.lra.\nQed.\n\nLemma BPLUS_finite_e {NAN: Nans} (t : type) :\n  forall (x y : ftype t)\n  (FIN: finite (BPLUS x y)), \n  finite x /\\ finite y.\nProof.\nintros.\ndestruct x,y; try contradiction; simpl; auto.\ndestruct s,s0; simpl in FIN; auto.\nQed.\n\nLemma finite_sum_no_overflow {NAN: Nans} (t : type) :\n  forall (x y: ftype t)\n  (HFINb : finite (BPLUS x y)),\n  Bplus_no_overflow t (FT2R x) (FT2R y).\nProof.\nintros.\n destruct (BPLUS_finite_e _ _ _ HFINb) as [A B].\nrewrite finite_is_finite in HFINb.\npose proof Rle_or_lt (bpow Zaux.radix2 (femax t)) (Rabs (rounded t (FT2R x + FT2R y)))  as Hor;\n  destruct Hor; auto.\napply Rlt_bool_false in H.\nunfold rounded, FT2R in H.\nrewrite finite_is_finite in *.\npose proof (Binary.Bplus_correct  (fprec t) (femax t)  \n    (fprec_gt_0 t) (fprec_lt_femax t) (plus_nan t) BinarySingleNaN.mode_NE x y A B) as\n  H0;\nrewrite H in H0;\ndestruct H0 as ( C & _).\nunfold BPLUS, BINOP in HFINb.\ndestruct ((Binary.Bplus (fprec t) (femax t) (fprec_gt_0 t) (fprec_lt_femax t) \n             (plus_nan t) BinarySingleNaN.mode_NE x y));\nsimpl; try discriminate.\nQed.\n\nLemma BPLUS_accurate' {NAN: Nans} (t : type) :\n  forall (x y : ftype t)\n  (FIN: finite (BPLUS x y)), \n  exists delta, \n   Rabs delta <= default_rel t /\\\n   (FT2R (BPLUS x y ) = (FT2R x + FT2R y) * (1+delta))%R.\nProof.\nintros.\ndestruct (BPLUS_finite_e _ _ _ FIN) as [A B].\napply BPLUS_accurate; auto.\napply finite_sum_no_overflow; auto.\nQed.\n\nLemma BDIV_sep_zero' {NAN: Nans} (t : type) :\n  forall (f1 f2 : ftype t)\n  (Hfin: finite (BDIV f1 f2))\n  (Hfin1: Binary.is_finite_strict _ _ f1 = true)\n  (Hfin2: finite f2),\n  Binary.is_finite_strict _ _ f2 = true.\nProof.\nintros ? ?;\ndestruct f2; destruct f1; simpl; try discriminate; auto.\nQed.\n\nLemma fprec_lb {NAN: Nans} (t : type) :\n  (2 <= fprec t)%Z.\nProof. pose proof ( fprec_gt_one t); lia. Qed.\n\nLemma femax_lb {NAN: Nans} (t : type) :\n  (3 <= femax t)%Z.\nProof. \npose proof fprec_lb t;\npose proof fprec_lt_femax t; lia. \nQed.\n\nLemma femax_minus_fprec (t: type): \n  (0 < (femax t - fprec t))%Z.\nProof.\npose proof fprec_lt_femax t; lia. \nQed.\n\nLemma in_fprec_bound1 {NAN: Nans} (t : type) :\n (- 2 ^ fprec t <= 1 <= 2 ^ fprec t)%Z.\nProof.\nsplit. eapply Z.le_trans with (-2 ^ 2)%Z; [|lia].\napply Z.opp_le_mono; rewrite !Z.opp_involutive.\napply Z.pow_le_mono_r; [lia |apply fprec_lb ].\neapply Z.le_trans with (2 ^ 2)%Z; [lia|].\napply Z.pow_le_mono_r; [lia |apply fprec_lb ].\nQed.\n\nLemma in_fprec_bound0 {NAN: Nans} (t : type) :\n (- 2 ^ fprec t <= 0 <= 2 ^ fprec t)%Z.\nProof.\nsplit. eapply Z.le_trans with (-2 ^ 2)%Z; [|lia].\napply Z.opp_le_mono; rewrite !Z.opp_involutive.\napply Z.pow_le_mono_r; [lia |apply fprec_lb ].\neapply Z.le_trans with (2 ^ 2)%Z; [lia|].\napply Z.pow_le_mono_r; [lia |apply fprec_lb ].\nQed.\n\nLemma Bone_strict_finite {NAN: Nans} (t : type) :\n  Binary.is_finite_strict _ _ (Zconst t 1) = true.\nProof.\ndestruct \n  (BofZ_exact (fprec t) (femax t) (Pos2Z.is_pos (fprecp t)) (fprec_lt_femax t) 1 (in_fprec_bound1 t)) \n  as ( A & H & _); fold (Zconst t 1) in *.\ndestruct (Zconst t 1);\n  simpl; simpl in A; try discriminate; auto.\nnra.\nQed.\n\nLemma BDIV_sep_zero1 {NAN: Nans} (t : type) :\n  forall (f1 : ftype t)\n  (Hfin: finite (BDIV (Zconst t 1) f1))\n  (Hfin1: finite f1),\n  f1 <> (Zconst t 0).\nProof.\nintros. intros HF.\npose proof BDIV_sep_zero' t (Zconst t 1) f1 Hfin (Bone_strict_finite t) Hfin1.\ndestruct f1; try discriminate; auto.\nQed.\n\nLemma BDIV_sep_zero2 {NAN: Nans} (t : type) :\n  forall (f1 : ftype t)\n  (Hfin: finite (BDIV (Zconst t 1) f1))\n  (Hfin1: finite f1),\n  f1 <> (neg_zero).\nProof.\nintros. intros HF.\npose proof BDIV_sep_zero' t (Zconst t 1) f1 Hfin (Bone_strict_finite t) Hfin1.\ndestruct f1; try discriminate; auto.\nQed.\n\nLemma BDIV_FT2R_sep_zero {NAN: Nans} (t : type) :\n  forall (f1 : ftype t)\n  (Hfin: finite (BDIV (Zconst t 1) f1))\n  (Hfin1: finite f1),\n  FT2R f1 <> 0.\nProof.\nintros. intros HF.\npose proof BDIV_sep_zero1 t f1 Hfin Hfin1 as H0.\npose proof BDIV_sep_zero2 t f1 Hfin Hfin1 as H1.\npose proof BDIV_sep_zero' t (Zconst t 1) f1 Hfin (Bone_strict_finite t) Hfin1 as HFINx.\nrewrite finite_is_finite in Hfin.\nrewrite finite_is_finite in Hfin1.\npose proof Binary.B2R_Bsign_inj (fprec t) (femax t) f1 neg_zero Hfin1 (eq_refl _) as HA.\npose proof Binary.B2R_Bsign_inj (fprec t) (femax t) f1 (Zconst t 0) Hfin1 (eq_refl _) as HB.\ndestruct f1; try discriminate; auto.\ndestruct s; try discriminate; auto.\nQed. \n\nLemma is_finite_fma_no_overflow' {NAN: Nans} (t : type) :\n  forall (x y z: ftype t)\n  (Hfinx: finite x)\n  (Hfiny: finite y)\n  (Hfinz: finite z)\n  (Hov : fma_no_overflow t (FT2R x) (FT2R y) (FT2R z)),\n finite (BFMA x y z).\nProof.\nintros.\nrewrite finite_is_finite in Hfinx, Hfiny, Hfinz|-*.\npose proof (Binary.Bfma_correct  (fprec t) (femax t)  (fprec_gt_0 t) (fprec_lt_femax t) (fma_nan t)\n                      BinarySingleNaN.mode_NE x y z Hfinx Hfiny Hfinz).\nunfold fma_no_overflow, FT2R, rounded in Hov;\napply Rlt_bool_true in Hov.\ncbv zeta in H.\nrewrite Hov in H; simpl in H; destruct H as (_ & B & _); simpl; auto.\nQed.\n\nLemma finite_BOPP: forall {NAN: Nans} (t: type) (x: ftype t),\n   finite (BOPP x) <-> finite x.\nProof.\nintros.\nunfold BOPP.\nrewrite !finite_is_finite, Binary.is_finite_Bopp.\ntauto.\nQed.\n\nEnd NAN.", "meta": {"author": "VeriNum", "repo": "iterative_methods", "sha": "7507d713cceaf91d9493dab620d3583438b8bc8a", "save_path": "github-repos/coq/VeriNum-iterative_methods", "path": "github-repos/coq/VeriNum-iterative_methods/iterative_methods-7507d713cceaf91d9493dab620d3583438b8bc8a/StationaryMethods/float_acc_lems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6734964182237235}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) : natural := plus Zero lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj15_coqofml_vwsWrX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.673496415990917}}
{"text": "Require Import Coq.Relations.Relation_Operators.\nRequire Import Metalib.Metatheory.\n\nModule Syntax.\n\nInductive channel : Set :=\n| free : atom -> channel\n| bound : nat -> channel\n.\n  \nInductive process : Set :=\n| stop : process \n| input : channel -> process -> process\n| output : channel -> channel -> process -> process\n| compose : process -> process -> process\n| replicate : process -> process.\n\nDefinition fv_channel c :=\n  match c with\n    | free f => singleton f\n    | bound _ => empty\n  end.\n\nFixpoint fv p :=\n  match p with\n    | stop => empty\n    | input c1 p => union (fv p) (fv_channel c1)\n    | output c1 c2 p => union (fv p) (union (fv_channel c1) (fv_channel c2))\n    | compose p1 p2 => union (fv p1) (fv p2) \n    | replicate p => fv p\n  end.\n\nDefinition open_channel n a c :=\n  match c with\n    | free f => free f\n    | bound b => if beq_nat b n then a else bound b\n  end.\n\nFixpoint open_rec n a p :=\n  match p with\n    | stop => stop\n    | input c p =>\n      input (open_channel n a c) (open_rec (S n) a p)\n    | output c1 c2 p =>\n      output (open_channel n a c1) (open_channel n a c2) (open_rec n a p)\n    | replicate p => replicate (open_rec n a p)\n    | compose p1 p2 => compose (open_rec n a p1) (open_rec n a p2)\n  end.\n\nDefinition open a p := open_rec 0 a p.\n\nInductive lc_channel : channel -> Prop :=\n| lc_free : forall a, lc_channel (free a)\n.\n\n(* This is different from local closure of expressions in e.g. System T,\nsince we don't actually care if when we substitute, the name is free\nin the expression we're substituting for.\n*)\nInductive lc : process -> Prop :=\n| lc_replicate : forall p, lc p -> lc (replicate p)\n| lc_compose : forall p1 p2, lc p1 -> lc p2 -> lc (compose p1 p2)\n| lc_stop : lc stop\n| lc_output : forall c1 c2 p, lc p -> lc_channel c1 -> lc_channel c2 -> lc (output c1 c2 p)\n| lc_input : forall c p, lc_channel c -> lc p -> lc (input c p)\n.\n                                                  \nEnd Syntax.\n\nModule Semantics.\n\nImport Syntax.\n\nInductive context : Type :=\n| c_input : channel -> channel -> context -> context\n| c_output : channel -> channel -> context -> context\n| c_replicate : context -> context\n| c_compose_l : context -> process -> context\n| c_compose_r : process -> context -> context\n| c_hole : context\n.\n\nFixpoint fill (c : context) (p : process) : process :=\n  match c with\n    | c_input c1 c2 con => input c1 (fill con p)\n    | c_output c1 c2 con => output c1 c2 (fill con p)\n    | c_hole => p\n    | c_replicate con => replicate (fill con p)\n    | c_compose_l con r => compose (fill con p) r\n    | c_compose_r l con => compose l (fill con p)\n  end.\n\nInductive congruent : process -> process -> Prop :=\n| cong_compose_comm : forall P1 P2, congruent (compose P1 P2) (compose P2 P1)\n| cong_compose_assoc : forall P1 P2 P3, congruent (compose P1 (compose P2 P3)) (compose (compose P1 P2) P3)\n| cong_zero : forall P, congruent (compose P stop) P\n| cong_replicate : forall P, congruent (replicate P) (compose P (replicate P))\n| cong_context : forall c P Q, congruent P Q -> congruent (fill c P) (fill c Q)\n| cong_refl : forall P, congruent P P\n| cong_symm : forall P Q, congruent P Q -> congruent Q P\n| cong_trans : forall P Q R, congruent P Q -> congruent Q R -> congruent P R\n.\n\n(*Definition congruent : process -> process -> Prop :=\n  clos_refl_sym_trans process cong_base.*)\n\nInductive step_process_base : process -> process -> Prop :=\n| step_composition : forall P1 P2 P3, step_process_base P1 P2 -> step_process_base (compose P1 P3) (compose P2 P3)\n| step_communication : forall c z P Q, step_process_base (compose (output c z Q) (input c P)) (compose Q (open z P)).\n\nDefinition step_process P Q : Prop :=\n  exists P' Q', congruent P P' /\\ congruent Q Q' /\\ step_process_base P' Q'.\n\nInductive step_process_cong : process -> process -> Prop :=\n| step_composition_cong : forall P1 P2 P3, step_process_cong P1 P2 -> step_process_cong (compose P1 P3) (compose P2 P3)\n| step_communication_cong : forall c z P Q, step_process_cong (compose (output c z Q) (input c P)) (compose Q (open z P))\n| step_cong : forall P Q P' Q', step_process_cong P Q -> congruent P P' -> congruent Q Q' -> step_process_cong P' Q'.\n\nTheorem cong_end : forall P Q, step_process_cong P Q <-> step_process P Q.\nProof.\n  intros. split.\n  - intros. induction H.\n    + unfold step_process. destruct IHstep_process_cong as [P1'].\n      destruct H0 as [P2'].\n      exists (compose P1' P3). exists (compose P2' P3).\n      destruct H0 as [CP1 H0]. destruct H0 as [CP2 SPB].\n      repeat split.\n      * assert (compose P1 P3 = fill (c_compose_l c_hole P3) P1); eauto.\n        assert (compose P1' P3 = fill (c_compose_l c_hole P3) P1'); eauto.\n        rewrite H0; rewrite H1. eapply cong_context. eapply CP1.\n      * assert (compose P2 P3 = fill (c_compose_l c_hole P3) P2); eauto.\n        assert (compose P2' P3 = fill (c_compose_l c_hole P3) P2'); eauto.\n        rewrite H0; rewrite H1. eapply cong_context. eapply CP2.\n      * constructor. eapply SPB.\n    + unfold step_process.\n      exists (compose (output c z Q) (input c P)).\n      exists (compose Q (open z P)).\n      repeat split; try (eapply cong_refl); constructor.\n    + destruct IHstep_process_cong as [P1].\n      destruct H2 as [Q1]. exists P1. exists Q1.\n      repeat split.\n      * eapply cong_trans. eapply cong_symm; eauto. eapply H2. \n      * eapply cong_trans. eapply cong_symm; eauto. eapply H2. \n      * eapply H2.\n  - intros. destruct H as [P']. destruct H as [Q'].\n    destruct H as [CPP' H]. destruct H as [CQQ' H].\n    apply step_cong with (P := P') (Q := Q').\n    generalize dependent P. generalize dependent Q. induction H.\n    + intros. eapply step_composition_cong. eapply IHstep_process_base.\n      eapply cong_refl. eapply cong_refl.\n    + intros. eapply step_communication_cong.\n    + eapply cong_symm; eauto.\n    + eapply cong_symm; eauto.\nQed.\n\nInductive label :=\n| send_label : channel -> channel -> label\n| recv_label : channel -> channel -> label\n| tau_label : label.\n\nDefinition fv_label l :=\n  match l with\n    | send_label c1 c2 => union (fv_channel c1) (fv_channel c2) \n    | recv_label c1 c2 => union (fv_channel c1) (fv_channel c2)\n    | tau_label => empty\n  end.\n\nDefinition bound_label l :=\n  match l with\n    | recv_label c1 c2 => fv_channel c2\n    | _ => empty\n  end.\n\nLtac gather_atoms ::=\n  let A := gather_atoms_with (fun x : atoms => x) in\n  let B := gather_atoms_with (fun x : atom => singleton x) in\n  let D := gather_atoms_with (fun x : process => fv x) in\n  constr:(A `union` B `union` D).\n\nInductive lts : process -> label -> process -> Prop :=\n| lts_comp_left : forall P P' Q l, lts P l P' -> lts (compose P Q) l (compose P' Q)\n| lts_comp_right : forall P Q Q' l, lts Q l Q' -> lts (compose P Q) l (compose P Q')\n| lts_input : forall P c n, lts (input c P) (recv_label c n) (open n P)\n| lts_output : forall P c c', lts (output c c' P) (send_label c c') P\n| lts_comm_left : forall P P' Q Q' c n, lts P (send_label c n) P' -> lts Q (recv_label c n) Q' -> lts (compose P Q) (tau_label) (compose P' Q')\n| lts_comm_right : forall P P' Q Q' c n, lts P (recv_label c n) P' -> lts Q (send_label c n) Q' -> lts (compose P Q) tau_label (compose P' Q')\n| lts_rep_act : forall P a P', lts P a P' -> lts (replicate P) a (compose P' (replicate P))\n| lts_rep_comm : forall P c n P' P'',\n                   lts P (send_label c n) P' -> lts P (recv_label c n) P'' ->\n                   lts (replicate P) tau_label (compose (compose P' P'') (replicate P))\n.\n\nLemma lts_input_helper :\n  forall P Q c1 c2, lts P (recv_label c1 c2) Q ->\n                exists R S, congruent P (compose (input c1 R) S) /\\\n                            congruent Q (compose (open c2 R) S).\nProof.\n  intros. remember (recv_label c1 c2). induction H; try (inversion Heql; subst).\n  - apply IHlts in H0. destruct H0 as [R]. destruct H0 as [S].\n    exists R. exists (compose S Q).\n    split.\n    + apply cong_trans with (Q := (compose (compose (input c1 R) S) Q)).\n      assert (compose P Q = fill (c_compose_l c_hole Q) P); eauto.\n      assert (compose (compose (input c1 R) S) Q = fill (c_compose_l c_hole Q) (compose (input c1 R) S)); eauto.\n      rewrite H1; rewrite H2; eapply cong_context. eapply H0.\n      eapply cong_symm; eapply cong_compose_assoc.\n    + apply cong_trans with (Q := (compose (compose (open c2 R) S) Q)).\n      assert (compose P' Q = fill (c_compose_l c_hole Q) P'); eauto.\n      assert (compose (compose (open c2 R) S) Q = fill (c_compose_l c_hole Q) (compose (open c2 R) S)); eauto.\n      rewrite H1; rewrite H2; eapply cong_context. eapply H0.\n      eapply cong_symm; eapply cong_compose_assoc.\n  - apply IHlts in H0. destruct H0 as [R]. destruct H0 as [S].\n    exists R. exists (compose P S).\n    split.\n    + eapply cong_trans with (Q := (compose P (compose (input c1 R) S))).\n      assert (compose P Q = fill (c_compose_r P c_hole) Q); eauto.\n      assert (compose P (compose (input c1 R) S) = fill (c_compose_r P c_hole) (compose (input c1 R) S)); eauto.\n      rewrite H1; rewrite H2; eapply cong_context. eapply H0.\n      eapply cong_trans. eapply cong_compose_assoc.\n      eapply cong_trans with (Q := (compose (compose (input c1 R) P) S)).\n      assert (compose (compose P (input c1 R)) S = fill (c_compose_l c_hole S) (compose P (input c1 R))); eauto.\n      assert (compose (compose (input c1 R) P) S = fill (c_compose_l c_hole S) (compose (input c1 R) P)); eauto.\n      rewrite H1; rewrite H2; eapply cong_context.\n      eapply cong_compose_comm. eapply cong_symm; eapply cong_compose_assoc.\n    + apply cong_trans with (Q := (compose P (compose (open c2 R) S))).\n      assert (compose P Q' = fill (c_compose_r P c_hole) Q'); eauto.\n      assert (compose P (compose (open c2 R) S) = fill (c_compose_r P c_hole) (compose (open c2 R) S)); eauto.\n      rewrite H1; rewrite H2; eapply cong_context; eapply H0.\n      eapply cong_trans. eapply cong_compose_assoc.\n      eapply cong_trans.\n      assert (compose (compose P (open c2 R)) S = fill (c_compose_l c_hole S) (compose P (open c2 R))); eauto.\n      rewrite H1; eapply cong_context. eapply cong_compose_comm. simpl.\n      eapply cong_symm; eapply cong_compose_assoc.\n  - inversion Heql; subst. exists P. exists stop.\n    split. eapply cong_symm; eapply cong_zero. eapply cong_symm; eapply cong_zero.\n  - eapply IHlts in H0. destruct H0 as [R]. destruct H0 as [S].\n    exists R. exists (compose S (replicate P)). split.\n    + eapply cong_trans. eapply cong_replicate.\n      eapply cong_trans.\n      assert (compose P (replicate P) = fill (c_compose_l c_hole (replicate P)) P); eauto.\n      rewrite H1. eapply cong_context. eapply H0. simpl.\n      eapply cong_symm. eapply cong_compose_assoc.\n    + eapply cong_trans.\n      assert (compose P' (replicate P) = fill (c_compose_l c_hole (replicate P)) P'); eauto.\n      rewrite H1; eapply cong_context. eapply H0. simpl.\n      eapply cong_symm; eapply cong_compose_assoc.\nQed.\n\nLemma lts_output_helper :\n  forall P Q c1 c2, lts P (send_label c1 c2) Q ->\n                    exists R S, congruent P (compose (output c1 c2 R) S) /\\\n                                congruent Q (compose R S).\nProof.\n  intros. remember (send_label c1 c2). induction H; try (inversion Heql; subst).\n  - apply IHlts in H0. destruct H0 as [R]. destruct H0 as [S].\n    exists R. exists (compose S Q).\n    split.\n    + eapply cong_trans.\n      assert (compose P Q = fill (c_compose_l c_hole Q) P); eauto.\n      rewrite H1. eapply cong_context. eapply H0. simpl.\n      eapply cong_symm; eapply cong_compose_assoc.\n    + eapply cong_trans.\n      assert (compose P' Q = fill (c_compose_l c_hole Q) P'); eauto.\n      rewrite H1. eapply cong_context. eapply H0. simpl.\n      eapply cong_symm; eapply cong_compose_assoc.\n  - apply IHlts in H0. destruct H0 as [R]. destruct H0 as [S].\n    exists R. exists (compose P S).\n    split.\n    + eapply cong_trans.\n      assert (compose P Q = fill (c_compose_r P c_hole) Q); eauto.\n      rewrite H1; eapply cong_context. eapply H0. simpl.\n      eapply cong_trans. eapply cong_compose_assoc.\n      eapply cong_trans.\n      assert (compose (compose P (output c1 c2 R)) S = fill (c_compose_l c_hole S) (compose P (output c1 c2 R))); eauto.\n      rewrite H1; eapply cong_context. eapply cong_compose_comm. simpl.\n      eapply cong_symm; eapply cong_compose_assoc.\n    + eapply cong_trans.\n      assert (compose P Q' = fill (c_compose_r P c_hole) Q'); eauto.\n      rewrite H1; eapply cong_context. eapply H0. simpl.\n      eapply cong_trans. eapply cong_compose_assoc.\n      eapply cong_trans.\n      assert (compose (compose P R) S = fill (c_compose_l c_hole S) (compose P R)); eauto.\n      rewrite H1; eapply cong_context. eapply cong_compose_comm. simpl.\n      eapply cong_symm; eapply cong_compose_assoc.\n  - exists P. exists stop. split. eapply cong_symm; eapply cong_zero.\n    eapply cong_symm; eapply cong_zero.\n  - eapply IHlts in H0. destruct H0 as [R]. destruct H0 as [S].\n    exists R. exists (compose S (replicate P)). split.\n    + eapply cong_trans. eapply cong_replicate.\n      eapply cong_trans.\n      assert (compose P (replicate P) = fill (c_compose_l c_hole (replicate P)) P); eauto.\n      rewrite H1; eapply cong_context. apply H0. simpl.\n      eapply cong_symm; eapply cong_compose_assoc.\n    + eapply cong_trans.\n      assert (compose P' (replicate P) = fill (c_compose_l c_hole (replicate P)) P'); eauto.\n      rewrite H1; eapply cong_context. apply H0. simpl.\n      eapply cong_symm; eapply cong_compose_assoc.\nQed.\n\nDefinition lts_cong P a Q :=\n  exists P' Q', congruent P P' /\\ congruent Q Q' /\\ lts P' a Q'.\n\nTheorem lts_tau_step : forall P Q, step_process P Q -> lts_cong P tau_label Q.\nProof.\n  intros. destruct H as [P']. destruct H as [Q'].\n  destruct H as [CPP' H]; destruct H as [CQQ' S].\n  unfold lts_cong. exists P'. exists Q'. repeat split; eauto.\n  clear CPP'; clear CQQ'.\n  induction S.\n  - eapply lts_comp_left. eapply IHS.\n  - eapply lts_comm_left. constructor. constructor.\nQed.\n\nTheorem tau_lts_comm_step : \n  forall P Q P' Q' c n, lts P (send_label c n) P' ->\n                        lts Q (recv_label c n) Q' ->\n                        step_process (compose P Q) (compose P' Q').\nProof.\n  intros.\n  eapply lts_input_helper in H0.\n  eapply lts_output_helper in H.\n  destruct H as [R]. destruct H as [S]. destruct H.\n  destruct H0 as [R']. destruct H0 as [S']. destruct H0.\n  unfold step_process.\n  exists (compose (compose (output c n R) (input c R')) (compose S S')).\n  exists (compose (compose R (open n R')) (compose S S')).\n  repeat split.\n  + eapply cong_trans. assert (compose P Q = fill (c_compose_l c_hole Q) P); eauto. rewrite H3.\n    eapply cong_context. eapply H. simpl.\n    eapply cong_trans. assert (compose (compose (output c n R) S) Q = fill (c_compose_r (compose (output c n R) S) c_hole) Q); eauto.\n    rewrite H3. eapply cong_context. eapply H0. simpl.\n    eapply cong_trans. eapply cong_symm. eapply cong_compose_assoc.\n    eapply cong_trans.\n    assert (compose (output c n R) (compose S (compose (input c R') S')) = fill (c_compose_r (output c n R) c_hole) (compose S (compose (input c R') S'))); eauto.\n    rewrite H3. eapply cong_context. eapply cong_compose_assoc. simpl.\n    eapply cong_trans.\n    assert (compose (output c n R) (compose (compose S (input c R')) S') = fill (c_compose_r (output c n R) (c_compose_l c_hole S')) (compose S (input c R'))); eauto.\n    rewrite H3. eapply cong_context. eapply cong_compose_comm. simpl.\n    eapply cong_trans.\n    assert (compose (output c n R) (compose (compose (input c R') S) S') = fill (c_compose_r (output c n R) c_hole) (compose (compose (input c R') S) S')); eauto.\n    rewrite H3; eapply cong_context. eapply cong_symm; eapply cong_compose_assoc. simpl.\n    eapply cong_compose_assoc.\n  + eapply cong_trans. assert (compose P' Q' = fill (c_compose_l c_hole Q') P'); eauto. rewrite H3.\n    eapply cong_context. eapply H1. simpl.\n    eapply cong_trans. assert (compose (compose R S) Q' = fill (c_compose_r (compose R S) c_hole) Q'); eauto.\n    rewrite H3. eapply cong_context. eapply H2. simpl.\n    eapply cong_trans. eapply cong_symm. eapply cong_compose_assoc.\n    eapply cong_trans.\n    assert (compose R (compose S (compose (open n R') S')) = fill (c_compose_r R c_hole) (compose S (compose (open n R') S'))); eauto.\n    rewrite H3. eapply cong_context. eapply cong_compose_assoc. simpl.\n    eapply cong_trans.\n    assert (compose R (compose (compose S (open n R')) S') = fill (c_compose_r R (c_compose_l c_hole S')) (compose S (open n R'))); eauto.\n    rewrite H3. eapply cong_context. eapply cong_compose_comm. simpl.\n    eapply cong_trans.\n    assert (compose R (compose (compose (open n R') S) S') = fill (c_compose_r R c_hole) (compose (compose (open n R') S) S')); eauto.\n    rewrite H3; eapply cong_context. eapply cong_symm; eapply cong_compose_assoc. simpl.\n    eapply cong_compose_assoc.\n  + constructor. constructor.\nQed.\n\nTheorem tau_lts_step : forall P Q, lts P tau_label Q -> step_process P Q.\nProof.\n  intros. remember tau_label. induction H; inversion Heql; subst.\n  - unfold step_process. eapply IHlts in H0. destruct H0 as [P0'].\n    destruct H0 as [Q']. exists (compose P0' Q). exists (compose Q' Q).\n    repeat split.\n    + assert (compose P Q = fill (c_compose_l c_hole Q) P); eauto.\n      assert (compose P0' Q = fill (c_compose_l c_hole Q) P0'); eauto.\n      rewrite H1. rewrite H2. eapply cong_context. eapply H0.\n    + assert (compose P' Q = fill (c_compose_l c_hole Q) P'); eauto.\n      assert (compose Q' Q = fill (c_compose_l c_hole Q) Q'); eauto.\n      rewrite H1. rewrite H2. eapply cong_context.  eapply H0.\n    + eapply step_composition. eapply H0.\n  - unfold step_process. eapply IHlts in H0. destruct H0 as [X].\n    destruct H0 as [Y]. exists (compose X P).  exists (compose Y P).\n    repeat split.\n    + eapply cong_trans. apply cong_compose_comm.\n      assert (compose Q P = fill (c_compose_l c_hole P) Q); eauto.\n      assert (compose X P = fill (c_compose_l c_hole P) X); eauto.\n      rewrite H1. rewrite H2. eapply cong_context. eapply H0.\n    + eapply cong_trans. apply cong_compose_comm.\n      assert (compose Q' P = fill (c_compose_l c_hole P) Q'); eauto.\n      assert (compose Y P = fill (c_compose_l c_hole P) Y); eauto.\n      rewrite H1. rewrite H2. eapply cong_context. eapply H0.\n    + eapply step_composition. eapply H0.\n  - eapply tau_lts_comm_step. eapply H. eapply H0. \n  - eapply tau_lts_comm_step in H. destruct H as [P0]. destruct H as [Q0]. \n    exists P0. exists Q0.\n    repeat split; eauto.\n    + eapply cong_trans. eapply cong_compose_comm. eapply H. \n    + eapply cong_trans. eapply cong_compose_comm. eapply H. \n    + eapply H.\n    + eauto.\n  - eapply IHlts in H0. unfold step_process in *. clear IHlts.\n    destruct H0 as [P'0]. destruct H0 as [Q].\n    exists (compose P'0 (replicate P)). exists (compose Q (replicate P)).\n    repeat split.\n    + eapply cong_trans. eapply cong_replicate.\n      assert (compose P (replicate P) = fill (c_compose_l c_hole (replicate P)) P); eauto. rewrite H1. eapply cong_trans. eapply cong_context.\n      eapply H0. simpl. eapply cong_refl.\n    + assert (compose P' (replicate P) = fill (c_compose_l c_hole (replicate P)) P'); eauto. rewrite H1. eapply cong_trans. eapply cong_context.\n      eapply H0. simpl. eapply cong_refl.\n    + eapply step_composition. eapply H0.\n  - eapply tau_lts_comm_step in H; eauto.\n    destruct H as [P0]. destruct H as [P0'].\n    unfold step_process. exists (compose P0 (replicate P)).\n    exists (compose P0' (replicate P)).\n    repeat split.\n    + eapply cong_trans. eapply cong_replicate.\n      eapply cong_trans. assert (compose P (replicate P) = fill (c_compose_r P c_hole) (replicate P)); eauto.\n      rewrite H1; eapply cong_context. eapply cong_replicate. simpl.\n      eapply cong_trans. eapply cong_compose_assoc.\n      eapply cong_trans. assert (compose (compose P P) (replicate P) = fill (c_compose_l c_hole (replicate P)) (compose P P)); eauto.\n      rewrite H1; eapply cong_context. eapply H. simpl; eapply cong_refl.\n    + assert (compose (compose P' P'') (replicate P) = fill (c_compose_l c_hole (replicate P)) (compose P' P'')); eauto.\n      eapply cong_trans. rewrite H1; eapply cong_context. eapply H.\n      simpl. eapply cong_refl.\n    + eapply step_composition. eapply H.\nQed.\n\nEnd Semantics.\n\nModule EarlyBisim.\n\nImport Syntax.\nImport Semantics.\n\nDefinition early_bisimulation (R : process -> process -> Prop) :=\n  (forall P1 P2, R P1 P2 -> R P2 P1) /\\\n  forall P1 P1' P2 l, R P1 P2 ->\n                      lts P1 l P1' ->\n                      exists P2', lts P2 l P2' /\\ R P1' P2'.\n\nDefinition early_bisimilar (p : process) (q : process) :=\n  exists R, early_bisimulation R /\\ R p q.\n\nTheorem early_bisimilarity_symm :\n  forall p q, early_bisimilar p q -> early_bisimilar q p.\nProof.\n  intros. destruct H as [R]. destruct H.\n  unfold early_bisimilar. exists R.\n  split. eauto.\n  unfold early_bisimulation in H.\n  destruct H. apply H. apply H0.\nQed.\n\nTheorem early_bisimilarity_refl :\n  forall p, early_bisimilar p p.\nProof.\n  intros. unfold early_bisimilar.\n  exists (fun p q => p = q). split; eauto.\n  unfold early_bisimulation. split; eauto.\n  intros; subst; eauto.\nQed.\n\nTheorem early_bisimilarity_trans :\n  forall p q r, early_bisimilar p q -> early_bisimilar q r -> early_bisimilar p r.\nProof.\n  intros. unfold early_bisimilar in *. destruct H as [R1]; destruct H0 as [R2].\n  destruct H; destruct H0.\n  exists (clos_trans process (fun p q => (R1 p q \\/ R2 p q))).\n  split.\n  - unfold early_bisimulation in *. split.\n    + intros. induction H3. destruct H3. eapply t_step.\n      left; apply H; eauto.\n      eapply t_step. right; apply H0; eauto.\n      eapply t_trans. eapply IHclos_trans2. eapply IHclos_trans1.\n    + intros. generalize dependent P1'. induction H3.\n      * destruct H3. destruct H. intros. eapply H4 in H5. destruct H5.\n        exists x0. split. destruct H5. apply H5. eapply t_step. destruct H5. left; apply H6. apply H3.\n        intros. eapply H0 in H4. destruct H4. destruct H4.\n        exists x0. split. apply H4. eapply t_step. right; apply H5. apply H3.\n      * intros. apply IHclos_trans1 in H4. destruct H4. destruct H3.\n        apply IHclos_trans2 in H3. destruct H3. destruct H3.\n        exists x1. split. apply H3. eapply t_trans. apply H4. apply H5.\n  - eapply t_trans. eapply t_step. left; apply H1.\n    eapply t_step. right; apply H2.\nQed.\n\nEnd EarlyBisim.\n\nModule Relations.\n\nImport Syntax.\nImport Semantics.\n\nDefinition relation := process -> process -> Prop.\nDefinition symmetric (R : relation) := forall P Q, R P Q -> R Q P.\nDefinition subset (R : relation) (S : relation) := forall P Q, R P Q -> S P Q.\nDefinition reverse (R : relation) := fun P Q => R Q P.\nDefinition r_compose (R : relation) (S: relation) :=\n  fun P Q => exists A, (R P A) /\\ (S A Q).\n\nDefinition progresses (R : relation) S : Prop :=\n  (forall P Q l Q', lts Q l Q' -> R P Q -> exists P', lts P l P' /\\ S P' Q') /\\\n  (forall P Q l P', lts P l P' -> R P Q -> exists Q', lts Q l Q' /\\ S P' Q').\n\nDefinition strongly_safe (F : relation -> relation) : Prop :=\n  forall (R : relation) (S : relation),\n    subset R S -> progresses R S ->\n    (subset (F R) (F S) /\\ progresses (F R) (F S)).\n\nDefinition preserves_symm F : Prop :=\n  forall R, symmetric R -> symmetric (F R).\n\nEnd Relations.\n\nModule EarlyBisimProp.\n\nImport EarlyBisim.\nImport Syntax.\nImport Relations.\n\n(*Theorem progresses_bisim : forall R, progresses R R -> early_bisimulation R.\nProof.\n  intros. unfold progresses in H; unfold early_bisimulation.\n  split. eapply H. intros; eapply H; eauto. \nQed.*)\n(* Need to take symmetric closure here *)\n\nTheorem progresses_subset_left :\n  forall R S T, subset R S -> progresses S T ->\n                progresses R T.\nProof.\n  intros. unfold progresses in *. repeat split; eauto.\n  - destruct H0. intros.  eapply H0 in H2. destruct H2 as [Q'0].\n    exists Q'0. split; eapply H2. apply H. apply H3.\n  - destruct H0. intros. eapply H1 in H2. destruct H2 as [Q'0]. \n    exists Q'0. eapply H2. apply H. apply H3.\nQed.\n\nTheorem progresses_subset_right :\n  forall R S T, subset S T -> progresses R S ->\n                progresses R T.\nProof.\n  intros. unfold progresses in *. repeat split; eauto.\n  - destruct H0. intros. eapply H0 in H2. destruct H2 as [P'].\n    exists P'. split. eapply H2. eapply H. eapply H2. eapply H3.\n  - destruct H0. intros. eapply H1 in H2. destruct H2 as [Q'].\n    exists Q'. split. eapply H2. eapply H. eapply H2. eapply H3.\nQed.\n\nFixpoint apply_n n R (F : relation -> relation) :=\n  match n with\n    | O => R\n    | S n' => fun P Q => apply_n n' R F P Q \\/ F (apply_n n' R F) P Q\n  end.\n\nLemma apply_n_symm :\n  forall n R F, symmetric R -> preserves_symm F ->\n                symmetric (apply_n n R F).\nProof.\n  intros. induction n.\n  - simpl; eauto.\n  - simpl. unfold symmetric. intros.\n    destruct H1. left; eauto. right; eauto. eapply H0 in IHn.\n    eauto.\nQed.\n\nLemma apply_n_subset :\n  forall R F n, subset (apply_n n R F) (apply_n (S n) R F).\nProof.\n  intros. simpl. unfold subset. intros. left; eapply H. \nQed.\n\nLemma progresses_union :\n  forall R1 R2 S, progresses R1 S -> progresses R2 S -> progresses (fun P Q => R1 P Q \\/ R2 P Q) S.\nProof.\n  intros. unfold progresses. repeat split.\n  - intros.\n    destruct H as [H _]. destruct H0 as [H0 _].\n    destruct H2.\n    + eapply H in H1. apply H1. apply H2.\n    + eapply H0 in H1. apply H1. apply H2.\n  - intros.\n    destruct H as [_ H]. destruct H0 as [_ H0].\n    destruct H2.\n    + eapply H in H1. eapply H1. apply H2.\n    + eapply H0 in H1. eapply H1. apply H2.\nQed.\n\nTheorem apply_n_progresses :\n  forall (R : relation) F n, strongly_safe F -> progresses R (F R) ->\n                             progresses (apply_n n R F) (apply_n (S n) R F).\nProof.\n  intros. induction n.\n  - simpl. eapply progresses_subset_right; try (apply H0).\n    unfold subset. intros; eauto.\n  - simpl in *. eapply progresses_union.\n    + eapply progresses_subset_right; try (apply IHn).\n      unfold subset. intros. left. apply H1.\n    + eapply progresses_subset_right with (F (fun P Q => apply_n n R F P Q \\/ F (apply_n n R F) P Q)).\n      unfold symmetric. intros. \n      unfold subset; intros. right; eauto. eapply H in IHn.\n      apply IHn.\n      unfold subset; intros. left; eauto.\nQed.\n\nTheorem strongly_safe_in_bisimulation :\n  forall (R : relation) F, preserves_symm F -> symmetric R -> strongly_safe F -> progresses R (F R) ->\n                           early_bisimulation (fun P Q => exists n, apply_n n R F P Q).\nProof.\n  intros. unfold early_bisimulation. unfold progresses in H2. split.\n  - intros. destruct H3 as [n]. generalize dependent P1. generalize dependent P2.\n    induction n.\n    + intros. simpl in H3. exists 0; simpl; eauto.\n    + intros. simpl in H3. destruct H3.\n      * eapply IHn; eauto.\n      * exists (S n). simpl. right.\n        assert (symmetric (apply_n n R F)).\n        { eapply apply_n_symm. apply H0. apply H. }\n        apply H in H4. apply H4. apply H3.\n  - intros. destruct H3 as [n]. eapply apply_n_progresses in H3; eauto.\n    destruct H3 as [P2']. exists P2'.\n    split. eapply H3.  exists (S n); eapply H3.\nQed.\n\nFixpoint iterate n (F : relation -> relation) (R : relation) :=\n  match n with\n    | O => F R\n    | S n => r_compose (F R) (iterate n F R)\n  end.\n\nTheorem iterate_sum :\n  forall F R P A Q n m, iterate n F R P A -> iterate m F R A Q ->\n                        iterate (S (n + m)) F R P Q.\nProof.\n  intros. generalize dependent P. induction n.\n  - intros. simpl. simpl in H. exists A; eauto.\n  - intros. simpl. simpl in H. simpl in IHn. inversion H; subst.\n    exists x. split. eapply H1. eapply IHn. eapply H1.\nQed.\n\n(*Theorem iterate_symmetric :\n  forall n R F, symmetric R ->\n                (forall f, symmetric f -> symmetric (F f)) ->\n                symmetric (iterate n F R).\nProof.\n  intros. induction n; eauto.\n  simpl. unfold symmetric. intros. inversion H1; subst.\n  - eapply symm_backwards. eapply H2. eapply H3.\n  - eapply symm_forwards. eapply H2. eapply H3.\nQed.*)\n\nDefinition closure F R :=\n  fun P Q => exists n, iterate n F R P Q.\n\nTheorem closure_compose :\n  forall A P Q F R, closure F R P A -> closure F R A Q -> closure F R P Q.\nProof.\n  intros. destruct H. destruct H0.\n  exists (1 + x + x0). eapply iterate_sum. eapply H. eapply H0.\nQed.\n  \n(*Theorem closure_symmetric :\n  forall R F, symmetric R ->\n              (forall f, symmetric f -> symmetric (F f)) ->\n              symmetric (closure F R).\nProof.\n  intros. unfold symmetric. intros. destruct H1 as [n].\n  exists n.\n  eapply iterate_symmetric; eauto.\nQed.*)\n\nTheorem iterate_progresses :\n  forall (R : relation) S F n,\n    (forall f, symmetric f -> symmetric (F f)) ->\n    (forall R S, subset R S -> progresses R S ->\n     (subset (F R) (closure F S) /\\ (progresses (F R) (closure F S)))) ->\n    subset R S -> progresses R S ->\n    (subset (iterate n F R) (closure F S) /\\ (progresses (iterate n F R) (closure F S))).\nProof.\n  intros. generalize dependent R. generalize dependent S. induction n.\n  - intros; split.\n    + simpl. unfold closure. unfold subset. intros.\n      eapply H0; eauto.\n    + simpl. unfold closure. unfold progresses. repeat split.\n      * intros. eapply H0 in H1; eauto. eapply H1. eapply H3. eapply H4.\n      * intros. eapply H0 in H1; eauto. eapply H1. eapply H3. eapply H4.\n  - intros. split.\n    + unfold subset. simpl. intros. destruct H3 as [A]; subst. destruct H3.\n      assert (progresses R S); eauto.\n      apply IHn in H2; eauto. destruct H2 as [H2 H2']. eapply H2 in H4.\n      eapply H0 in H1; eauto. destruct H1. eapply H1 in H3. destruct H3 as [n']. destruct H4 as [n'']. exists (1 + (n' + n'')). eapply iterate_sum; eauto.\n    + repeat split.\n      * intros. simpl in H4. destruct H4 as [A]. destruct H4.\n        assert (subset R S); eauto.\n        eapply IHn in H6; eauto.\n        assert (subset R S); eauto. eapply H0 in H7; eauto.\n        destruct H7.\n        destruct H8 as [H8 _].\n        destruct H6 as [_ H6]. destruct H6 as [H6 _]. eapply H6 in H5.\n        destruct H5. destruct H5.\n        eapply H8 in H4. destruct H4. destruct H4.\n        Focus 2. eapply H5. Focus 2. eapply H3. exists x0.\n        split. eapply H4. eapply closure_compose. eapply H10. eapply H9.\n      * intros. simpl in H4. destruct H4 as [A]. destruct H4.\n        assert (subset R S); eauto.\n        eapply IHn in H6; eauto.\n        assert (subset R S); eauto. eapply H0 in H7; eauto.\n        destruct H7.\n        destruct H8 as [_ H8].\n        destruct H6 as [_ H6]. destruct H6 as [_ H6].\n        eapply H8 in H4. destruct H4. destruct H4.\n        eapply H6 in H5. destruct H5. destruct H5.\n        Focus 2. eapply H4. Focus 2. eapply H3. exists x0.\n        split. eapply H5. eapply closure_compose. eapply H9. eapply H10.\nQed.\n\nTheorem closure_safe :\n  forall F, (forall f, symmetric f -> symmetric (F f)) ->\n            (forall R S, subset R S -> progresses R S ->\n                         subset (F R) (closure F S) /\\ (progresses (F R) (closure F S))) ->\n            strongly_safe (closure F).\nProof.\n  intros.\n  unfold closure. unfold strongly_safe. intros. split.\n  - unfold subset. intros. destruct H3 as [n]. eapply iterate_progresses; eauto.\n  - unfold progresses. repeat split.\n    + intros. destruct H4. eapply iterate_progresses in H1; eauto. eapply H1; eauto.\n    + intros. destruct H4. eapply iterate_progresses in H1; eauto. eapply H1; eauto.\nQed.\n\nEnd EarlyBisimProp.\n\nModule Contexts.\n\nImport Syntax.\nImport Semantics.\nImport EarlyBisimProp.\nImport EarlyBisim.\nImport Relations.\n  \nInductive ni_context : Type :=\n| ni_output : channel -> channel -> ni_context -> ni_context\n| ni_replicate : ni_context -> ni_context\n| ni_compose_l : ni_context -> process -> ni_context\n| ni_compose_r : process -> ni_context -> ni_context\n| ni_hole : ni_context\n.\n\nFixpoint ni_fill (nc : ni_context) (p : process) : process :=\n  match nc with\n    | ni_hole => p\n    | ni_output c1 c2 c => output c1 c2 (ni_fill c p)\n    | ni_replicate nic => replicate (ni_fill nic p)\n    | ni_compose_l nic r => compose (ni_fill nic p) r\n    | ni_compose_r l nic => compose l (ni_fill nic p)\n  end.\n\nFixpoint ni_compose nc1 nc2 :=\n  match nc1 with\n    | ni_hole => nc2\n    | ni_output c1 c2 c => ni_output c1 c2 (ni_compose c nc2)\n    | ni_replicate nic => ni_replicate (ni_compose nic nc2)\n    | ni_compose_l nic r => ni_compose_l (ni_compose nic nc2) r\n    | ni_compose_r l nic => ni_compose_r l (ni_compose nic nc2)\n  end.\n\nTheorem ni_compose_fill :\n  forall nc1 nc2 P,\n    ni_fill nc1 (ni_fill nc2 P) = ni_fill (ni_compose nc1 nc2) P.\nProof.\n  intros. induction nc1; try (simpl; rewrite IHnc1; eauto).\n  - simpl. eauto.\nQed.\n\nDefinition ni_context_relation (R: relation) : relation :=\n  fun P Q => exists (C : ni_context) P' Q',\n               R P' Q' /\\ P = (ni_fill C P') /\\ Q = (ni_fill C Q').\n\nLemma ni_context_helper :\n  forall x R P Q C,\n    iterate x ni_context_relation R P Q ->\n    iterate x ni_context_relation R (ni_fill C P) (ni_fill C Q).\nProof.\n  intros. generalize dependent P. generalize dependent Q. induction x; simpl in *.\n  - intros. destruct H as [C'].  destruct H as [P']. destruct H as [Q'].\n    exists (ni_compose C C'). exists P'. exists Q'.\n    repeat split.\n    + eapply H.\n    + destruct H. destruct H0. rewrite H0. rewrite ni_compose_fill. eauto.\n    + destruct H. destruct H0. rewrite H1. rewrite ni_compose_fill. eauto.\n  - intros. destruct H. destruct H. eapply IHx in H0. destruct H as [C'].\n    destruct H as [P']. destruct H as [Q']. unfold r_compose.\n    exists (ni_fill C x0). split; try (eapply H0).\n    exists (ni_compose C C'). exists P'. exists Q'.\n    repeat split.\n    + eapply H.\n    + destruct H. destruct H1. rewrite H1. rewrite ni_compose_fill. eauto.\n    + destruct H. destruct H1. rewrite H2. rewrite ni_compose_fill. eauto.\nQed.\n \nLemma ni_context_progresses :\n  forall P P' Q C R S l,\n    subset R S -> progresses R S -> lts (ni_fill C P) l P' -> R P Q ->\n    exists Q', lts (ni_fill C Q) l Q' /\\ closure ni_context_relation S P' Q'. \nProof.\n  intros. generalize dependent l. generalize dependent P'. induction C.\n  - intros. simpl in *. inversion H1; subst.\n    exists (ni_fill C Q). split. constructor. exists 0. simpl.\n    exists C. exists P. exists Q. repeat split. eapply H. eapply H2.\n  - intros. simpl in *. inversion H1; subst.\n    + eapply IHC in H4. destruct H4 as [Q']. destruct H3.\n      exists (compose Q' (replicate (ni_fill C Q))). split.\n      * eapply lts_rep_act. eapply H3.\n      * destruct H4.\n        exists (1 + x). simpl.\n        exists (compose P'0 (replicate (ni_fill C Q))).\n        split.\n        exists (ni_compose_r P'0 (ni_replicate C)).\n        exists P. exists Q. repeat split. eauto. \n        apply ni_context_helper with (C := (ni_compose_l ni_hole (replicate (ni_fill C Q)))) in H4. eapply H4.\n    + eapply IHC in H4. eapply IHC in H5. destruct H4. destruct H3.\n      destruct H5. destruct H5.\n      exists (compose (compose x x0) (replicate (ni_fill C Q))).\n      split.\n      * eapply lts_rep_comm. eapply H3. eapply H5.\n      * destruct H4 as [m]. destruct H6 as [m'']. exists (2 + m + m'').\n        simpl. exists (compose (compose P'0 P'') (replicate (ni_fill C Q))).\n        split. exists (ni_compose_r (compose P'0 P'') (ni_replicate C)).\n        exists P. exists Q. repeat split. eauto.\n        eapply iterate_sum.\n        apply ni_context_helper with (C := (ni_compose_l (ni_compose_l ni_hole P'') (replicate (ni_fill C Q)))) in H4. eapply H4.\n        simpl. apply ni_context_helper with (C := (ni_compose_l (ni_compose_r x ni_hole) (replicate (ni_fill C Q)))) in H6. eapply H6.\n  - intros. inversion H1; subst.\n    + eapply IHC in H7. destruct H7. destruct H3. exists (compose x p). split.\n      * simpl. eapply lts_comp_left. eapply H3.\n      * destruct H4. exists (x0).\n        apply ni_context_helper with (C := (ni_compose_l ni_hole p)) in H4. eapply H4.\n    + simpl in *. exists (compose (ni_fill C Q) Q'). split.\n      * eapply lts_comp_right. eapply H7.\n      * exists 0. simpl. exists (ni_compose_l C Q'). exists P. exists Q.\n        repeat split; eauto.\n    + eapply IHC in H5. destruct H5 as [Q0]. destruct H3. simpl.\n      exists (compose Q0 Q'). split.\n      * eapply lts_comm_left. eapply H3. eapply H8.\n      * destruct H4. exists x.\n        apply ni_context_helper with (C := ni_compose_l ni_hole Q') in H4. eapply H4.\n    + eapply IHC in H5. destruct H5 as [Q0].  destruct H3. simpl.\n      exists (compose Q0 Q'). split.\n      * eapply lts_comm_right; eauto.\n      * destruct H4 as [n']. exists n'.\n        apply ni_context_helper with (C := ni_compose_l ni_hole Q') in H4. eapply H4.\n  - intros. inversion H1; subst.\n    + simpl in *. exists (compose P'0 (ni_fill C Q)). split.\n      * eapply lts_comp_left. eapply H7.\n      * exists 0. simpl. exists (ni_compose_r P'0 C). exists P. exists Q.\n        repeat split; eauto.\n    + eapply IHC in H7. destruct H7. destruct H3. exists (compose p x). split.\n      * simpl. eapply lts_comp_right. eapply H3.\n      * destruct H4. exists (x0).\n        apply ni_context_helper with (C := (ni_compose_r p ni_hole)) in H4. eapply H4.\n    + eapply IHC in H8. destruct H8 as [Q0]. destruct H3. simpl.\n      exists (compose P'0 Q0). split.\n      * eapply lts_comm_left. eapply H5. eapply H3.\n      * destruct H4. exists x.\n        apply ni_context_helper with (C := ni_compose_r P'0 ni_hole) in H4. eapply H4.\n    + eapply IHC in H8. destruct H8 as [Q0].  destruct H3. simpl.\n      exists (compose P'0 Q0). split.\n      * eapply lts_comm_right; eauto.\n      * destruct H4 as [n']. exists n'.\n        apply ni_context_helper with (C := ni_compose_r P'0 ni_hole) in H4. eapply H4.\n  - intros. simpl in *. eapply H0 in H1; eauto. destruct H1 as [Q']. exists Q'.\n    split. eapply H1. exists 0. simpl. exists ni_hole. simpl.\n    exists P'. exists Q'. repeat split; eauto. eapply H1.\nQed.\n\nLemma ni_context_progresses' :\n  forall P Q' Q C R S l,\n    subset R S -> progresses R S -> lts (ni_fill C Q) l Q' -> R P Q ->\n    exists P', lts (ni_fill C P) l P' /\\ closure ni_context_relation S P' Q'. \nProof.\n  intros. generalize dependent l. generalize dependent Q'. induction C.\n  - intros. simpl in *. inversion H1; subst.\n    exists (ni_fill C P). split. constructor. exists 0. simpl.\n    exists C. exists P. exists Q. repeat split. eauto.\n  - intros. simpl in *. inversion H1; subst.\n    + eapply IHC in H4. destruct H4 as [Q']. destruct H3.\n      exists (compose Q' (replicate (ni_fill C P))). split.\n      * eapply lts_rep_act. eapply H3.\n      * destruct H4.\n        exists (1 + x). simpl.\n        exists (compose Q' (replicate (ni_fill C Q))).\n        split.\n        exists (ni_compose_r Q' (ni_replicate C)).\n        exists P. exists Q. repeat split. eauto. \n        apply ni_context_helper with (C := (ni_compose_l ni_hole (replicate (ni_fill C Q)))) in H4. eapply H4.\n    + eapply IHC in H4. eapply IHC in H5. destruct H4. destruct H3.\n      destruct H5. destruct H5.\n      exists (compose (compose x x0) (replicate (ni_fill C P))).\n      split.\n      * eapply lts_rep_comm. eapply H3. eapply H5.\n      * destruct H4 as [m]. destruct H6 as [m'']. exists (2 + m + m'').\n        simpl. exists (compose (compose x x0) (replicate (ni_fill C Q))).\n        split. exists (ni_compose_r (compose x x0) (ni_replicate C)).\n        exists P. exists Q. repeat split. eauto.\n        eapply iterate_sum.\n        apply ni_context_helper with (C := (ni_compose_l (ni_compose_l ni_hole x0) (replicate (ni_fill C Q)))) in H4. simpl in H4. eapply H4.\n        simpl. apply ni_context_helper with (C := (ni_compose_l (ni_compose_r P' ni_hole) (replicate (ni_fill C Q)))) in H6. eapply H6.\n  - intros. inversion H1; subst.\n    + eapply IHC in H7. destruct H7. destruct H3. exists (compose x p). split.\n      * simpl. eapply lts_comp_left. eapply H3.\n      * destruct H4. exists (x0).\n        apply ni_context_helper with (C := (ni_compose_l ni_hole p)) in H4. eapply H4.\n    + simpl in *. exists (compose (ni_fill C P) Q'0). split.\n      * eapply lts_comp_right. eapply H7.\n      * exists 0. simpl. exists (ni_compose_l C Q'0). exists P. exists Q.\n        repeat split; eauto.\n    + eapply IHC in H5. destruct H5 as [Q0]. destruct H3. simpl.\n      exists (compose Q0 Q'0). split.\n      * eapply lts_comm_left. eapply H3. eapply H8.\n      * destruct H4. exists x.\n        apply ni_context_helper with (C := ni_compose_l ni_hole Q'0) in H4. eapply H4.\n    + eapply IHC in H5. destruct H5 as [Q0].  destruct H3. simpl.\n      exists (compose Q0 Q'0). split.\n      * eapply lts_comm_right; eauto.\n      * destruct H4 as [n']. exists n'.\n        apply ni_context_helper with (C := ni_compose_l ni_hole Q'0) in H4. eapply H4.\n  - intros. inversion H1; subst.\n    + simpl in *. exists (compose P' (ni_fill C P)). split.\n      * eapply lts_comp_left. eapply H7.\n      * exists 0. simpl. exists (ni_compose_r P' C). exists P. exists Q.\n        repeat split; eauto.\n    + eapply IHC in H7. destruct H7. destruct H3. exists (compose p x). split.\n      * simpl. eapply lts_comp_right. eapply H3.\n      * destruct H4. exists (x0).\n        apply ni_context_helper with (C := (ni_compose_r p ni_hole)) in H4. eapply H4.\n    + eapply IHC in H8. destruct H8 as [Q0]. destruct H3. simpl.\n      exists (compose P' Q0). split.\n      * eapply lts_comm_left. eapply H5. eapply H3.\n      * destruct H4. exists x.\n        apply ni_context_helper with (C := ni_compose_r P' ni_hole) in H4. eapply H4.\n    + eapply IHC in H8. destruct H8 as [Q0].  destruct H3. simpl.\n      exists (compose P' Q0). split.\n      * eapply lts_comm_right; eauto.\n      * destruct H4 as [n']. exists n'.\n        apply ni_context_helper with (C := ni_compose_r P' ni_hole) in H4. eapply H4.\n  - intros. simpl in *. destruct H0. eapply H0 in H1; eauto.\n    destruct H1 as [P']. exists P'.\n    split. eapply H1. exists 0. simpl. exists ni_hole. simpl.\n    exists P'. exists Q'. repeat split; eauto. eapply H1.\nQed.\n\nTheorem strongly_safe_ni_context : strongly_safe (closure ni_context_relation).\n  eapply closure_safe.\n  - intros. unfold symmetric. intros. unfold ni_context_relation.\n    unfold ni_context_relation in H0.  destruct H0 as [C].\n    destruct H0 as [P']. destruct H0 as [Q'].\n    exists C. exists Q'. exists P'.\n    destruct H0. destruct H1.\n    repeat split; eauto.\n  - intros. split.\n    + unfold subset. intros.\n      exists 0. simpl. unfold ni_context_relation in *.\n      destruct H1 as [C]. destruct H1 as [P']. destruct H1 as [Q'].\n      exists C. exists P'. exists Q'.\n      destruct H1. destruct H2.\n      repeat split; eauto.\n    + unfold progresses. split.\n      * intros. destruct H2 as [C]. destruct H2 as [P']. destruct H2 as [Q_fill].\n        destruct H2. destruct H3. subst.\n        eapply ni_context_progresses'; eauto.\n      * intros. destruct H2 as [C]. destruct H2 as [P_fill]. destruct H2 as [Q']. \n        destruct H2. destruct H3. subst.\n        eapply ni_context_progresses; eauto.\nQed.\n\nEnd Contexts.", "meta": {"author": "plclub", "repo": "cis670-16fa", "sha": "e123c26d06a883b599c9bbf2474610ad84975a8c", "save_path": "github-repos/coq/plclub-cis670-16fa", "path": "github-repos/coq/plclub-cis670-16fa/cis670-16fa-e123c26d06a883b599c9bbf2474610ad84975a8c/projects/PiCalculus/pi_calculus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6734964066638114}}
{"text": "(** * Maps: Total and Partial Maps *)\n\n(** Maps (or dictionaries) are ubiquitous data structures, both in\n    software construction generally and in the theory of programming\n    languages in particular; we're going to need them in many places\n    in the coming chapters.  They also make a nice case study using\n    ideas we've seen in previous chapters, including building data\n    structures out of higher-order functions (from [Basics] and\n    [Poly]) and the use of reflection to streamline proofs (from\n    [IndProp]).\n\n    We'll define two flavors of maps: _total_ maps, which include a\n    \"default\" element to be returned when a key being looked up\n    doesn't exist, and _partial_ maps, which return an [option] to\n    indicate success or failure.  The latter is defined in terms of\n    the former, using [None] as the default element. *)\n\n(** HIDE: Recall the type [partial_map] from the [Lists] chapter.  Its\n    basic operations were [empty], the contant empty map, [update],\n    which takes a map and returns a new map with one key bound to a\n    new value, and [find], which looks up a key in a map. *)\n\n(* ###################################################################### *)\n(** * The Coq Standard Library *)\n\n(** One small digression before we start.\n\n    Unlike the chapters we have seen so far, this one does not\n    [Require Import] the chapter before it (and, transitively, all the\n    earlier chapters).  Instead, in this chapter and from now, on\n    we're going to import the definitions and theorems we need\n    directly from Coq's standard library stuff.  You should not notice\n    much difference, though, because we've been careful to name our\n    own definitions and theorems the same as their counterparts in the\n    standard library, wherever they overlap. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(** Documentation for the standard library can be found at\n    #<a href=\"http://coq.inria.fr/library/\">#http://coq.inria.fr/library/#</a>#.  \n\n    The [SearchAbout] command is a good way to look for theorems \n    involving objects of specific types. *)\n\n(* ###################################################################### *)\n(** * Identifiers *)\n\n(** First, we need a type for the keys that we use to index into our\n    maps.  For this purpose, we again use the type [id] from the\n    [Lists] chapter.  To make this chapter self contained, we repeat\n    its definition here, together with the equality comparison\n    function for [id]s and its fundamental property. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id id1 id2 :=\n  match id1,id2 with\n    | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\nTheorem beq_id_refl : forall id, true = beq_id id id.\n(* FOLD *)\nProof.\n  intros [n]. simpl. rewrite <- beq_nat_refl.\n  reflexivity. Qed.\n(* /FOLD *)\n\n(** The following useful property of [beq_id] follows from an\n    analogous lemma about numbers: *)\n\nTheorem beq_id_true_iff : forall id1 id2 : id,\n  beq_id id1 id2 = true <-> id1 = id2.\n(* FOLD *)\nProof.\n   intros [n1] [n2].\n   unfold beq_id.\n   rewrite beq_nat_true_iff.\n   split.\n   - (* -> *) intros H. rewrite H. reflexivity.\n   - (* <- *) intros H. inversion H. reflexivity.\nQed.\n(* /FOLD *)\n\n(** Similarly: *)\n\nTheorem beq_id_false_iff : forall x y : id,\n  beq_id x y = false\n  <-> x <> y.\n(* FOLD *)\nProof.\n  intros x y. rewrite <- beq_id_true_iff.\n  rewrite not_true_iff_false. reflexivity. Qed.\n(* /FOLD *)\n\n(** This useful variant follows just by rewriting: *)\n\nTheorem false_beq_id : forall x y : id,\n   x <> y\n   -> beq_id x y = false.\n(* FOLD *)\nProof.\n  intros x y. rewrite beq_id_false_iff.\n  intros H. apply H. Qed.\n(* /FOLD *)\n\n\n(* ###################################################################### *)\n(** * Total Maps *)\n\n(** Our main job in this chapter will be to build a definition of\n    partial maps that is similar in behavior to the one we saw in the\n    [Lists] chapter, plus accompanying lemmas about their behavior.\n\n    This time around, though, we're going to use _functions_, rather\n    than lists of key-value pairs, to build maps.  The advantage of\n    this representation is that it offers a more _extensional_ view of\n    maps, where two maps that respond to queries in the same way will\n    be represented as literally the same thing (the same function),\n    rather than just \"equivalent\" data structures.  This, in turn,\n    simplifies proofs that use maps.\n\n    We build partial maps in two steps.  First, we define a type of\n    _total maps_ that return a default value when we look up a key\n    that is not present in the map. *)\n\nDefinition total_map (A:Type) := id -> A.\n\n(** Intuitively, a total map over an element type [A] _is_ just a\n    function that can be used to look up [id]s, yielding [A]s.\n\n    The function [t_empty] yields an empty total map, given a default\n    element; this map always returns the default element when applied\n    to any id. *)\n\nDefinition t_empty {A:Type} (v : A) : total_map A :=\n  (fun _ => v).\n\n(** More interesting is the [update] function, which (as before) takes\n    a map [m], a key [x], and a value [v] and returns a new map that\n    takes [x] to [v] and takes every other key to whatever [m] does. *)\n\nDefinition t_update {A:Type} (m : total_map A)\n                    (x : id) (v : A) :=\n  fun x' => if beq_id x x' then v else m x'.\n\n(** This definition is a nice example of higher-order programming.\n    The [t_update] function takes a _function_ [m] and yields a new\n    function [fun x' => ...] that behaves like the desired map.\n\n    For example, we can build a map taking [id]s to [bool]s, where [Id\n    3] is mapped to [true] and every other key is mapped to [false],\n    like this: *)\n\nDefinition examplemap :=\n  t_update (t_update (t_empty false) (Id 1) false)\n           (Id 3) true.\n\n(** This completes the definition of total maps.  Note that we don't\n    need to define a [find] operation because it is just function\n    application! *)\n\n(** TERSE: *** *)\n\nExample update_example1 : examplemap (Id 0) = false.\n(* FOLD *)\nProof. reflexivity. Qed.\n(* /FOLD *)\n\nExample update_example2 : examplemap (Id 1) = false.\n(* FOLD *)\nProof. reflexivity. Qed.\n(* /FOLD *)\n\nExample update_example3 : examplemap (Id 2) = false.\n(* FOLD *)\nProof. reflexivity. Qed.\n(* /FOLD *)\n\nExample update_example4 : examplemap (Id 3) = true.\n(* FOLD *)\nProof. reflexivity. Qed.\n(* /FOLD *)\n\n(** To use maps in later chapters, we'll need several fundamental\n    facts about how they behave.  Even if you don't work the following\n    exercises, make sure you thoroughly understand the statements of\n    the lemmas!  (Some of the proofs require the functional\n    extensionality axiom discussed in the [Logic] chapter, which is\n    also included in the standard library.) *)\n\n(* EX2? (t_update_eq) *)\n(** First, if we update a map [m] at a key [x] with a new value [v]\n    and then look up [x] in the map resulting from the [update], we\n    get back [v]: *)\n\nLemma t_update_eq : forall A (m: total_map A) x v,\n  (t_update m x v) x = v.\nProof.\n  (* ADMITTED *)\n  intros. unfold t_update. rewrite <- beq_id_refl.\n  reflexivity.\nQed.\n(* /ADMITTED *)\n(** [] *)\n\n(* EX2? (t_update_neq) *)\n(** On the other hand, if we update a map [m] at a key [x1] and then\n    look up a _different_ key [x2] in the resulting map, we get the\n    same result that [m] would have given: *)\n\nTheorem t_update_neq : forall (X:Type) v x1 x2\n                         (m : total_map X),\n  x1 <> x2 ->\n  (t_update m x1 v) x2 = m x2.\nProof.\n  (* ADMITTED *)\n  intros X v x1 x2 m.\n  rewrite <- beq_id_false_iff.\n  intros Hneq.\n  unfold t_update.\n  rewrite -> Hneq.\n  reflexivity.  Qed.\n(* /ADMITTED *)\n(** [] *)\n\n(* EX2? (t_update_shadow) *)\n(** If we update a map [m] at a key [x] with a value [v1] and then\n    update again with the same key [x] and another value [v2], the\n    resulting map behaves the same (gives the same result when applied\n    to any key) as the simpler map obtained by performing just\n    the second [update] on [m]: *)\n\nLemma t_update_shadow : forall A (m: total_map A) v1 v2 x,\n    t_update (t_update m x v1) x v2\n  = t_update m x v2.\nProof.\n  (* ADMITTED *)\n  intros A m v1 v2 x1.\n  apply functional_extensionality. intros x2.\n  unfold t_update. destruct (beq_id x1 x2).\n  - reflexivity.\n  - reflexivity.\nQed.\n(* /ADMITTED *)\n(** [] *)\n\n(** For the final two lemmas about total maps, it's convenient to use\n    the reflection idioms introduced in chapter [IndProp].  We begin\n    by proving a fundamental _reflection lemma_ relating the equality\n    proposition on [id]s with the boolean function [beq_id]. *)\n\n(* EX2 (beq_idP) *)\n(** Use the proof of [beq_natP] in chapter [IndProp] as a template to\n    prove the following: *)\n\nLemma beq_idP : forall x y, reflect (x = y) (beq_id x y).\nProof.\n  (* ADMITTED *)\n  intros x y.\n  apply iff_reflect. rewrite beq_id_true_iff.\n  reflexivity.\nQed.\n(* /ADMITTED *)\n(** [] *)\n\n(** Now, given [id]s [x1] and [x2], we can use the [destruct (beq_idP\n    x1 x2)] to simultaneously perform case analysis on the result of\n    [beq_id x1 x2] and generate hypotheses about the equality (in the\n    sense of [=]) of [x1] and [x2]. *)\n\n(* EX2 (t_update_same) *)\n(** Using the example in chapter [IndProp] as a template, use\n    [beq_idP] to prove the following theorem, which states that if we\n    update a map to assign key [x] the same value as it already has in\n    [m], then the result is equal to [m]: *)\n\nTheorem t_update_same : forall X x (m : total_map X),\n  t_update m x (m x) = m.\nProof.\n  (* ADMITTED *)\n  intros X x1 m. apply functional_extensionality. intros x2.\n  unfold t_update.\n  destruct (beq_idP x1 x2) as [H | H].\n  - (* x1 = x2 *)\n    rewrite H. reflexivity.\n  - (* false *)\n    reflexivity.  Qed.\n(* /ADMITTED *)\n(** [] *)\n\n(* EX3! (t_update_permute) *)\n(** Use [beq_idP] to prove one final property of the [update]\n    function: If we update a map [m] at two distinct keys, it doesn't\n    matter in which order we do the updates. *)\n\nTheorem t_update_permute : forall (X:Type) v1 v2 x1 x2\n                             (m : total_map X),\n  x2 <> x1 ->\n    (t_update (t_update m x2 v2) x1 v1)\n  = (t_update (t_update m x1 v1) x2 v2).\nProof.\n  (* ADMITTED *)\n  intros X v1 v2 x1 x2 m H.\n  apply functional_extensionality. intros x3.\n  rewrite <- beq_id_false_iff in H.\n  unfold t_update.\n  destruct (beq_idP x1 x3).\n  - (* beq_id x1 x3 = true *)\n    subst. rewrite H. reflexivity.\n  - (* beq_id x1 x3 = false *) reflexivity.\nQed.\n(* /ADMITTED *)\n(* GRADE_THEOREM 3: t_update_permute *)\n(** [] *)\n\n(* ###################################################################### *)\n(** * Partial maps *)\n\n(** Finally, we define _partial maps_ on top of total maps.  A partial\n    map with elements of type [A] is simply a total map with elements\n    of type [option A] and default element [None]. *)\n\nDefinition partial_map (A:Type) := total_map (option A).\n\nDefinition empty {A:Type} : partial_map A :=\n  t_empty None.\n\n(* HIDE: Notation \"'\\empty'\" := empty. *)\n\nDefinition update {A:Type} (m : partial_map A)\n                  (x : id) (v : A) :=\n  t_update m x (Some v).\n\n(** We can now lift all of the basic lemmas about total maps to\n    partial maps.  *)\n\nLemma update_eq : forall A (m: partial_map A) x v,\n  (update m x v) x = Some v.\n(* FOLD *)\nProof.\n  intros. unfold update. rewrite t_update_eq.\n  reflexivity.\nQed.\n(* /FOLD *)\n\nTheorem update_neq : forall (X:Type) v x1 x2\n                       (m : partial_map X),\n  x2 <> x1 ->\n  (update m x2 v) x1 = m x1.\n(* FOLD *)\nProof.\n  intros X v x1 x2 m H.\n  unfold update. rewrite t_update_neq. reflexivity.\n  apply H. Qed.\n(* /FOLD *)\n\nLemma update_shadow : forall A (m: partial_map A) v1 v2 x,\n  update (update m x v1) x v2 = update m x v2.\n(* FOLD *)\nProof.\n  intros A m v1 v2 x1. unfold update. rewrite t_update_shadow.\n  reflexivity.\nQed.\n(* /FOLD *)\n\nTheorem update_same : forall X v x (m : partial_map X),\n  m x = Some v ->\n  update m x v = m.\n(* FOLD *)\nProof.\n  intros X v x m H. unfold update. rewrite <- H.\n  apply t_update_same.\nQed.\n(* /FOLD *)\n\nTheorem update_permute : forall (X:Type) v1 v2 x1 x2\n                                (m : partial_map X),\n  x2 <> x1 ->\n    (update (update m x2 v2) x1 v1)\n  = (update (update m x1 v1) x2 v2).\n(* FOLD *)\nProof.\n  intros X v1 v2 x1 x2 m. unfold update.\n  apply t_update_permute.\nQed.\n(* /FOLD *)\n\n(** 2016/03/25 12:34:16 *)\n\n(* HIDE *)\n(*\nLocal Variables:\nfill-column: 70\nEnd:\n*)\n(* /HIDE *)\n", "meta": {"author": "pierewoj", "repo": "tspl", "sha": "7b0f7edb08f04469bafdac804f22b347ea5574c4", "save_path": "github-repos/coq/pierewoj-tspl", "path": "github-repos/coq/pierewoj-tspl/tspl-7b0f7edb08f04469bafdac804f22b347ea5574c4/pract3/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943658046609, "lm_q2_score": 0.8887587912826161, "lm_q1q2_score": 0.673496404593327}}
{"text": "(*|\n############################\nHow to make sublists in Coq?\n############################\n\n:Link: https://stackoverflow.com/q/36896291\n|*)\n\n(*|\nQuestion\n********\n\nI'm working in Coq and trying to figure out how to do the next thing:\nIf I have a list of natural numbers and a given number ``n``, I want\nto break my list in what goes before and after each of the ``n``'s. To\nmake it clearer, if I have the list ``[1; 2; 0; 3; 4; 0; 9]`` and the\nnumber ``n = 0``, then I want to have as output the three lists:\n``[1;2]``, ``[3;4]`` and ``[9]``. The main problem I have is that I\ndon't know how to output several elements on a ``Fixpoint``. I think I\nneed to nest ``Fixpoint``\\ s but I just don't see how. As a very raw\nidea with one too many issues I have:\n|*)\n\nRequire Import PeanoNat List. (* .none *)\nImport ListNotations. (* .none *)\nFail Fixpoint SubLists (A : list nat) (m : nat) :=\n  match A with\n  | [] => []\n  | n :: A0 => if n =? m then SubLists L else n :: SubLists L\n  end. (* .fails *)\n\n(*|\nI would very much appreciate your input on how to do this, and how to\nnavigate having an output of several elements.\n|*)\n\n(*|\nAnswer (Arthur Azevedo De Amorim)\n*********************************\n\nYou can do this by combining a few fixpoints:\n|*)\n\nReset Initial. (* .none *)\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nFixpoint prefix n l :=\n  match l with\n  | [] => []\n  | m :: l' => if beq_nat n m then [] else m :: prefix n l'\n  end.\n\nFixpoint suffix n l :=\n  match l with\n  | [] => l\n  | m :: l' => if beq_nat n m then l' else suffix n l'\n  end.\n\nFixpoint split_at n l :=\n  match l with\n  | [] => []\n  | m :: l' => prefix n (m :: l') :: split_at n (suffix n (m :: l'))\n  end.\n\n(*|\nNotice that Coq's termination checker accepts the recursive call to\n``split_at``, even though it is not done syntactically a subterm of\n``l``. The reason for that is that it is able to detect that suffix\nonly outputs subterms of its argument. But in order for this to work,\nwe *must* return ``l``, and not ``[]`` on its first branch (try\nchanging it to see what happens!).\n|*)\n\n(*|\nAnswer (ejgallego)\n******************\n\nIn addition to Arthur's solution, you can use an accumulator, which is\ntypical of Functional Programming style:\n|*)\n\nReset Initial. (* .none *)\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nDefinition add_acc m (s : list (list nat)) :=\n  match s with\n  | []      => [[m]]\n  | s :: ss => (m :: s) :: ss\n  end.\n\nFixpoint split_seq n l acc :=\n  match l with\n  | []      => map (@rev _) (rev acc)\n  | m :: l' => if beq_nat n m\n               then split_seq n l' ([] :: acc)\n               else split_seq n l' (add_acc m acc)\n  end.\n\nCompute (split_seq 0 [1; 2; 0; 3; 4; 0; 9] []).\n\n(*|\nNote that the result is reversed so you need to use ``rev``. A bonus\nexercise is to improve this.\n\nEDIT: Provided second variant that doesn't add ``[]`` for repeated\nseparators.\n|*)\n\nDefinition reset_acc (s : list (list nat)) :=\n  match s with\n  | [] :: ss => [] :: ss\n  | ss       => [] :: ss\n  end.\n\nFixpoint split_seq_nodup n l acc :=\n  match l with\n  | []      => map (@rev _) (rev acc)\n  | m :: l' => if beq_nat n m\n               then split_seq_nodup n l' (reset_acc acc)\n               else split_seq_nodup n l' (add_acc m acc)\n  end.\n\nCompute (split_seq_nodup 0 [1; 2; 0; 3; 4; 0; 9] []).\n\n(*|\n----\n\n**A:** (1) For ``reset_acc``'s body I'd write ``match s with | [] :: _\n=> s | _ => [] :: s`` (2) For novice Coq programmers, not familiar\nwith the `@ syntax\n<https://coq.inria.fr/refman/Reference-Manual004.html#Implicits-explicitation>`__:\nit turns off \"implicitness\", so ``(@rev _)`` stands for ``(@rev\nnat)``. Without ``@``, one could have used eta-expansion: ``map (fun\nxs => rev xs) (rev acc)``.\n|*)\n\n(*|\nAnswer (gallais)\n****************\n\nAn alternative way to tackle this issue is to formally describe the\nproblem you are trying to solve and then either write a\ndependently-typed function proving that this problem can indeed be\nsolved or using tactics to slowly build up your proof.\n\nThis is, if I am not mistaken, a relation describing the relationship\nbetween the outputs ``n`` and ``ns`` you want to pass your function\nand the output ``mss`` you want to get back.\n\nThe ``(* ------- *)`` lines are simple comments used to suggest that\nthese constructors should be seen as `inference rules\n<https://en.wikipedia.org/wiki/Inference_rule>`__: whatever is under\none such line is the conclusion one can make based on the assumptions\nabove it.\n\n.. coq:: none\n|*)\n\nReset Initial.\n\nRequire Import Arith.\nRequire Import List.\nLocal Open Scope list_scope.\n\n(*||*)\n\nInductive SubListsRel (n : nat) :\n  forall (ns : list nat) (mss : list (list nat)), Prop :=\n| base      : SubListsRel n nil (nil :: nil)\n| consEq    : forall ns m mss,\n    n = m -> SubListsRel n ns mss ->\n    (* ------------------------------ *)\n    SubListsRel n (m :: ns) (nil :: mss)\n| consNotEq : forall ns m ms mss,\n    (n <> m) -> SubListsRel n ns (ms :: mss) ->\n    (* -------------------------------------- *)\n    SubListsRel n (m :: ns) ((m :: ms) :: mss).\n\n(*|\nWe can then express your ``Sublists`` problem as being, given inputs\n``n`` and ``ns``, the existence of an output ``mss`` such that\n``SubListsRel n ns mss`` holds:\n|*)\n\nDefinition SubLists (n : nat) (ns : list nat) : Set :=\n  { mss | SubListsRel n ns mss }.\n\n(*|\nUsing tactics we can readily generate such ``Sublists`` for concrete\nexamples in order to sanity-check our specification. We can for\ninstance take the example you had in your original post:\n|*)\n\nExample example1 : SubLists 0 (1 :: 2 :: 0 :: 3 :: 4 :: 0 :: 9 :: nil).\nProof.\n  eexists. repeat econstructor; intro Hf; inversion Hf.\nDefined.\n\n(*|\nAnd check that the output is indeed the list you were expecting:\n|*)\n\nCheck (eq_refl : proj1_sig example1\n                 = ((1 :: 2 :: nil) :: (3 :: 4 :: nil) :: (9 :: nil) :: nil)).\n\n(*|\nNow comes the main part of this post: the proof that ``forall n ns,\nSubLists n ns``. Given that the premise of ``consNotEq`` assumes that\n``mss`` is non-empty, we will actually prove a strengthened statement\nin order to make our life easier:\n|*)\n\nDefinition Strenghtened_SubLists (n : nat) (ns : list nat) : Set :=\n  { mss | SubListsRel n ns mss /\\ mss <> nil }.\n\n(*|\nAnd given that oftentimes we will have goals of the shape\n``something_absurd -> False``, I define a simple tactic to handle\nthese things. It introduces the absurd assumption and inverts it\nimmediately to make the goal disappear:\n|*)\n\nLtac dismiss := intro Hf; inversion Hf.\n\n(*|\nWe can now prove the main statement by proving the strengthened\nversion by induction and deducing it. I guess that here it's better\nfor you to step through it in Coq rather than me trying to explain\nwhat happens. The key steps are the ``cut`` (proving a stronger\nstatement), ``induction`` and the case analysis on ``eq_nat_dec``.\n|*)\n\nLemma subLists : forall n ns, SubLists n ns.\nProof.\n  intros n ns. cut (Strenghtened_SubLists n ns).\n  - intros [mss [Hmss _]]. eexists. eassumption.\n  - induction ns.\n    + eexists. split; [econstructor | dismiss].\n    + destruct IHns as [mss [Hmss mssNotNil]];\n        destruct (eq_nat_dec n a).\n      * eexists. split; [eapply consEq; eassumption | dismiss].\n      * destruct mss; [apply False_rect, mssNotNil; reflexivity |].\n        eexists. split; [eapply consNotEq; eassumption | dismiss].\nDefined.\n\n(*|\nOnce we have this function, we can come back to our example and\ngenerate the appropriate ``Sublists`` this time not by calling tactics\nbut by running the function ``subLists`` we just defined.\n|*)\n\nExample example2 : SubLists 0 (1 :: 2 :: 0 :: 3 :: 4 :: 0 :: 9 :: nil) :=\n  subLists _ _.\n\n(*|\nAnd we can ``Check`` that the computed list is indeed the same as the\none obtained in ``example1``:\n|*)\n\nCheck (eq_refl : proj1_sig example1 = proj1_sig example2).\n\n(*|\n**Nota Bene**: It is paramount here that our proofs are ended with\n``Defined`` rather than ``Qed`` in order for them to be unfolded when\ncomputing with them (which is what we want to do here: they give us\nthe ``list (list nat)`` we are looking for!).\n\n`A gist\n<https://gist.github.com/gallais/e6c7dac6542459037a9b3935f3fd3741>`__\nwith all the code and the right imports.\n|*)\n\n(*|\nAnswer (Anton Trunov)\n*********************\n\nHere is another take, based on the standard library function\n``List.fold_left``. It works by maintaining an accumulator, which is a\npair of the overall *reversed* result (a list of lists) and a current\nsublist (also reversed while accumulating). Once we reach a delimiter,\nwe reverse the current sublist and put it into the resulting list of\nsublists. After executing ``fold_left``, we reverse the result in the\noutermost ``match`` expression.\n|*)\n\nReset Initial. (* .none *)\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nDefinition split_skip_dup_delims (m : nat) (xs : list nat) :=\n  match fold_left\n          (fun (acctup: _ * _) x =>\n             let (acc, rev_subl) := acctup in\n             if beq_nat x m\n             then match rev_subl with (* a delimiter found *)\n                  | [] => (acc, []) (* do not insert empty sublist *)\n                  | _ => (rev rev_subl :: acc, []) end\n             else (acc, x :: rev_subl)) (* keep adding to the current sublist *)\n          xs\n          ([],[]) with\n  | (acc, []) => rev acc        (* list ends with a delimiter *)\n  | (acc, rev_subl) => rev (rev rev_subl :: acc) (* no delimiter at the end *)\n  end.\n\nEval compute in split_skip_dup_delims 0 [1; 2; 0; 0; 0; 3; 4; 0; 9]. (* .unfold *)\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-make-sublists-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.8887587817066391, "lm_q1q2_score": 0.673496392475213}}
{"text": "From Coq Require Import Arith.Arith.\nFrom Coq Require Import Bool.Bool.\nRequire Export Coq.Strings.String.\nFrom Coq Require Import Logic.FunctionalExtensionality.\nFrom Coq Require Import Lists.List.\nImport ListNotations.\nFrom LF Require Export IndProp.\n\n(* Identifiers *)\n\nDefinition eqb_string (x y : string) : bool :=\n  if string_dec x y then true else false.\n\nTheorem eqb_string_refl : forall s : string, true = eqb_string s s.\nintros s.\nunfold eqb_string.\ndestruct (string_dec s s) as [Hs|Hs] eqn: E.\nreflexivity.\nunfold not in Hs.\ndestruct Hs.\nreflexivity.\nQed.\n\nTheorem eqb_string_true_iff : forall x y : string,\n    eqb_string x y = true <-> x = y.\nProof.\nintros x y.\nsplit.\n  - intro H.\n  unfold eqb_string in H.\n  destruct (string_dec x y) eqn: E.\n  assumption.\n  discriminate.\n  - intro H.\n    rewrite H.\n    symmetry.\n    apply eqb_string_refl.\nQed.\n\nTheorem eqb_string_true_iff' : forall x y : string,\n    eqb_string x y = true <-> x = y.\nProof.\n   intros x y.\n   unfold eqb_string.\n   destruct (string_dec x y) as [|Hs].\n   - subst. split. reflexivity. reflexivity.\n   - split.\n     + intros contra. discriminate contra.\n     + intros H. rewrite H in Hs. destruct Hs. reflexivity.\nQed.\n\nTheorem eqb_string_false_iff : forall x y : string,\n    eqb_string x y = false <-> x <> y.\nProof.\nintros x y.\nunfold eqb_string.\ndestruct (string_dec x y) as [|Hs].\n- subst. split.\n  + intro contra. discriminate contra.\n  + intro H. destruct H. reflexivity.\n- split.\n  + intro H. apply Hs.\n  + reflexivity.\nQed.\n\nTheorem false_eqb_string : forall x y : string,\n   x <> y -> eqb_string x y = false.\nProof.\nintros x y.\nunfold eqb_string.\nintro Hxy.\ndestruct (string_dec x y) as [|Hs].\n- destruct Hxy. assumption.\n- reflexivity.\nQed.\n\nTheorem false_eqb_string' : forall x y : string,\n   x <> y -> eqb_string x y = false.\nProof.\n  intros x y. rewrite eqb_string_false_iff.\n  intros H. apply H.\nQed.\n\n(* Total Maps *)\n\nDefinition total_map (A : Type) := string -> A.\n\nDefinition t_empty {A : Type} (v : A) : total_map A :=\n  (fun _ => v).\n\nDefinition t_update {A : Type} (m : total_map A)\n                    (x : string) (v : A) :=\n  fun x' => if eqb_string x x' then v else m x'.\n\nDefinition examplemap :=\n  t_update (t_update (t_empty false) \"foo\" true)\n           \"bar\" true.\n\nNotation \"'_' '!->' v\" := (t_empty v)\n  (at level 100, right associativity).\nExample example_empty := (_ !-> false).\n\nNotation \"x '!->' v ';' m\" := (t_update m x v)\n                              (at level 100, v at next level, right associativity).\n\nDefinition examplemap' :=\n  ( \"bar\" !-> true;\n    \"foo\" !-> true;\n    _ !-> false\n  ).\n\n\nLemma t_apply_empty : forall (A : Type) (x : string) (v : A),\n    (_ !-> v) x = v.\nProof.\nintros A s v. reflexivity.\nQed.\n\nLemma t_update_eq : forall (A : Type) (m : total_map A) x v,\n    (x !-> v ; m) x = v.\nProof.\nintros A m s v.\nunfold t_update.\nrewrite <- eqb_string_refl.\nreflexivity.\nQed.\n\nTheorem t_update_neq : forall (A : Type) (m : total_map A) x1 x2 v,\n    x1 <> x2 ->\n    (x1 !-> v ; m) x2 = m x2.\nProof.\nintros A m s v v0 H.\nunfold t_update.\napply eqb_string_false_iff in H.\nrewrite H.\nreflexivity.\nQed.\n\n\nLemma t_update_shadow : forall (A : Type) (m : total_map A) x v1 v2,\n    (x !-> v2 ; x !-> v1 ; m) = (x !-> v2 ; m).\nProof.\nintros A m x v1 v2.\nunfold t_update.\nSearch \"extensionality\".\nSearch \"f_equal\".\napply functional_extensionality.\nintros x0.\ndestruct (eqb_string x x0).\n- reflexivity.\n- reflexivity.\nQed.\n\nLemma eqb_stringP : forall x y : string,\n    reflect (x = y) (eqb_string x y).\nProof.\nintros x y.\napply iff_reflect.\nrewrite eqb_string_true_iff.\nreflexivity.\nQed.\n\nTheorem t_update_same : forall (A : Type) (m : total_map A) x,\n    (x !-> m x ; m) = m.\nProof.\nintros.\nunfold t_update.\napply functional_extensionality.\nintros.\ndestruct (eqb_stringP x x0).\n- rewrite H. reflexivity.\n- reflexivity.\nQed.\n\n\nTheorem t_update_permute : forall (A : Type) (m : total_map A)\n                                  v1 v2 x1 x2,\n    x2 <> x1 ->\n    (x1 !-> v1 ; x2 !-> v2 ; m)\n    =\n    (x2 !-> v2 ; x1 !-> v1 ; m).\nProof.\nintros A m v1 v2 x1 x2 H.\nunfold t_update.\napply functional_extensionality.\nintros.\ndestruct (eqb_stringP x1 x).\n  - destruct (eqb_stringP x2 x).\n    + rewrite H0 in H.\n      rewrite H1 in H.\n      unfold not in H.\n      assert(H': x = x). { reflexivity. }\n      apply H in H'.\n      destruct H'.\n    + reflexivity.\n  - destruct (eqb_stringP x2 x).\n    + reflexivity.\n    + reflexivity.\nQed.\n\n\n(* Partial maps *)\n\n\nDefinition partial_map (A : Type) := total_map (option A).\n\nDefinition empty {A : Type} : partial_map A :=\n  t_empty None.\n\nDefinition update {A : Type} (m : partial_map A)\n           (x : string) (v : A) :=\n  (x !-> Some v ; m).\n\nNotation \"x '|->' v ';' m\" := (update m x v)\n  (at level 100, v at next level, right associativity).\n\nNotation \"x '|->' v\" := (update empty x v)\n  (at level 100).\n\nExample examplepmap :=\n  (\"Church\" |-> true ; \"Turing\" |-> false).\n\nLemma apply_empty : forall (A : Type) (x : string),\n    @empty A x = None.\nProof.\n  intros. unfold empty. rewrite t_apply_empty.\n  reflexivity.\nQed.\n\nLemma update_eq : forall (A : Type) (m : partial_map A) x v,\n    (x |-> v ; m) x = Some v.\nProof.\n  intros. unfold update. rewrite t_update_eq.\n  reflexivity.\nQed.\n\nTheorem update_neq : forall (A : Type) (m : partial_map A) x1 x2 v,\n    x2 <> x1 ->\n    (x2 |-> v ; m) x1 = m x1.\nProof.\n  intros A m x1 x2 v H.\n  unfold update. rewrite t_update_neq. reflexivity.\n  apply H. Qed.\n\nLemma update_shadow : forall (A : Type) (m : partial_map A) x v1 v2,\n    (x |-> v2 ; x |-> v1 ; m) = (x |-> v2 ; m).\nProof.\n  intros A m x v1 v2. unfold update. rewrite t_update_shadow.\n  reflexivity.\nQed.\n\nTheorem update_same : forall (A : Type) (m : partial_map A) x v,\n    m x = Some v ->\n    (x |-> v ; m) = m.\nProof.\n  intros A m x v H. unfold update. rewrite <- H.\n  apply t_update_same.\nQed.\n\nTheorem update_permute : forall (A : Type) (m : partial_map A)\n                                x1 x2 v1 v2,\n    x2 <> x1 ->\n    (x1 |-> v1 ; x2 |-> v2 ; m) = (x2 |-> v2 ; x1 |-> v1 ; m).\nProof.\n  intros A m x1 x2 v1 v2. unfold update.\n  apply t_update_permute.\nQed.", "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/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6734945259746488}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Well-founded relations                                                  *\n**************************************************************************)\n\nSet Implicit Arguments.\nFrom TLC Require Import LibTactics LibLogic\n LibProd LibSum LibRelation LibNat LibInt.\n\n\n(* ********************************************************************** *)\n(** * Compatibility *)\n\n(** Coq's stdlib Prelude defines:\n\n Inductive Acc A (R:A->A->Prop) (x:A) : Prop :=\n   | Acc_intro : (forall (y:A), R y x -> Acc y) -> Acc x.\n\n Definition well_founded A (R:A->A->Prop) :=\n    forall (x:A), Acc x.\n\n*)\n\n(** TLC introduces [wf] as a shorter name for [well_founded], both\n    for conciseness and for tactics to specifically recognize\n    this symbol. *)\n\nDefinition wf := well_founded.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Tactics *)\n\n(** [auto with wf] attempts to unfold the names of\n    the relations given as argument to [wf]. *)\n\n#[global]\nHint Extern 1 (wf ?R) => progress (unfold R) : wf.\n\n(** [solve_wf] is a shorthand for solving goals using\n    [auto with wf], aimed to prove goals of the form [wf R]. *)\n\nTactic Notation \"solve_wf\" :=\n  solve [ auto with wf ].\n\n\n\n(* ********************************************************************** *)\n(* * Measures *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition *)\n\n(** [measure f] is a well-founded binary relation which\n    relates [x] to [y] when [f x < f y], at type [nat]. *)\n\nDefinition measure A (f:A->nat) : binary A :=\n  fun x1 x2 => (f x1 < f x2).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties *)\n\nSection Measure.\nVariables (A : Type).\nImplicit Type f : A -> nat.\n\nLemma wf_measure : forall f,\n  wf (measure f).\nProof using.\n  intros f a. gen_eq n: (f a). gen a. pattern n.\n  apply peano_induction. clear n. introv IH Eq.\n  apply Acc_intro. introv H. unfolds in H.\n  rewrite <- Eq in H. apply* IH.\nQed.\n\nLemma trans_measure : forall (f : A -> nat),\n  trans (measure f).\nProof using. intros. unfold measure, trans. intros. nat_math. Qed.\n\n(* -- LATER: Lemma order_measure *)\n\nEnd Measure.\n\n#[global]\nHint Resolve wf_measure : wf.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Measure on pairs *)\n\nDefinition measure2 A1 A2 (f : A1 -> A2 -> nat) : binary (A1*A2) :=\n  fun p1 p2 => let (x1,y1) := p1 in\n               let (x2,y2) := p2 in\n               (f x1 y1 < f x2 y2).\n\nLemma wf_measure2 : forall A1 A2 (f:A1->A2->nat),\n  wf (measure2 f).\nProof using.\n  intros A1 A2 f [x1 x2]. apply (@measure_induction _ (uncurry2 f)). clear x1 x2.\n  intros [x1 x2] H. apply Acc_intro. intros [y1 y2] Lt. apply~ H.\nQed.\n\n#[global]\nHint Resolve wf_measure2 : wf.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Extension of LibTactic's [induction_wf] tactic for [measure] *)\n\nLtac induction_wf_process_wf_hyp tt ::= (* original in LibTactics *)\n  match goal with\n  | |- wf _ => auto with wf\n  | |- well_founded _ => change well_founded with wf; auto with wf\n  end.\n\nLtac induction_wf_process_measure E ::= (* original in LibTactics *)\n  applys well_founded_ind (wf_measure E).\n\n\n(* ********************************************************************** *)\n(** * Construction of well-founded relations *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Empty relation *)\n\nLemma wf_empty : forall A,\n  wf (@empty A).\nProof using. intros_all. constructor. introv H. false. Qed.\n\n#[global]\nHint Resolve wf_empty : wf.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inclusion *)\n\n(** Well-foundedness preserved by inclusion *)\n\nLemma wf_of_rel_incl : forall A (R1 R2 : binary A),\n  wf R1 ->\n  rel_incl R2 R1 ->\n  wf R2.\nProof using.\n  introv W1 Inc. intros x.\n  pattern x. apply (well_founded_ind W1). clear x.\n  intros x IH. constructor. intros. apply IH. apply~ Inc.\nQed.\n\n\n(* ********************************************************************** *)\n(* * Classic well-founded relations on [nat] *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** [Peano.lt] on [nat] *)\n\n(** The relation \"less than\" on natural numbers is well_founded. *)\n\nLemma wf_peano_lt : wf Peano.lt.\nProof using.\n  intros x.\n  induction x using peano_induction. apply~ Acc_intro.\n    intros. applys H. math.\nQed.\n\n#[global]\nHint Resolve wf_peano_lt : wf.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** [lt] on [nat] *)\n\n(** The relation \"less than\" on natural numbers is well_founded. *)\n\nLemma wf_lt : @wf nat lt.\nProof using.\n  intros x.\n  induction x using peano_induction. apply~ Acc_intro.\nQed.\n\n#[global]\nHint Resolve wf_lt : wf.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** The relation \"greater than\" on the set of\n       natural number lower than a fixed upper bound. *)\n\nDefinition nat_upto (b:nat) :=\n  fun (n m:nat) => (n <= b)%nat /\\ (m < n)%nat.\n\nLemma nat_upto_eq : forall (b n m:nat),\n  nat_upto b n m = ((n <= b)%nat /\\ (m < n)%nat).\nProof using. auto. Qed.\n\nLemma wf_nat_upto : forall (b:nat),\n  wf (nat_upto b).\nProof using.\n  intros b n.\n  induction_wf IH: (wf_measure (fun n => (b-n)%nat)) n.\n  apply Acc_intro. introv [H1 H2]. apply IH.\n  hnf. nat_math.\nQed.\n\n\n(* ********************************************************************** *)\n(* * Classic well-founded relations on [Z] *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** The relation \"less than\" on the set of\n       integers greater than a fixed lower bound. *)\n\nDefinition downto (b:Z) :=\n  fun (n m:Z) => (b <= n) /\\ (n < m).\n\nLemma downto_eq : forall (b n m:Z),\n  downto b n m = (b <= n /\\ n < m).\nProof using. auto. Qed.\n\nLemma downto_intro : forall (b n m:Z),\n  b <= n ->\n  n < m ->\n  downto b n m.\nProof using. split~. Qed.\n\nLemma wf_downto : forall (b:Z),\n  wf (downto b).\nProof using.\n  intros b n.\n  induction_wf IH: (wf_measure (fun n => Z.abs_nat (n-b))) n.\n  apply Acc_intro. introv [H1 H2]. apply IH.\n  unfolds. applys lt_abs_abs; math.\nQed.\n\n#[global]\nHint Resolve wf_downto : wf.\n#[global]\nHint Unfold downto.\n#[global]\nHint Extern 1 (downto _ _ _) => math : maths.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** The relation \"greater than\" on the set of\n       integers lower than a fixed upper bound. *)\n\nDefinition upto (b:Z) :=\n  fun (n m:Z) => (n <= b) /\\ (m < n).\n\nLemma upto_eq : forall b n m,\n  upto b n m = ((n <= b) /\\ (m < n)).\nProof using. auto. Qed.\n\nLemma upto_intro : forall b n m,\n  n <= b ->\n  m < n ->\n  upto b n m.\nProof using. split~. Qed.\n\nLemma wf_upto : forall n,\n  wf (upto n).\nProof using.\n  intros b n.\n  induction_wf IH: (wf_measure (fun n => Z.abs_nat (b-n))) n.\n  apply Acc_intro. introv [H1 H2]. apply IH.\n  applys lt_abs_abs; math.\nQed.\n\n#[global]\nHint Resolve wf_upto : wf.\n#[global]\nHint Unfold upto.\n#[global]\nHint Extern 1 (upto _ _ _) => math : maths.\n\n\n(* ********************************************************************** *)\n(** * Inverse projections *)\n\nSection UnprojWf.\nVariables (A1 A2 A3 A4 A5 : Type).\n\nLemma wf_unproj21 : forall (R:binary A1),\n  wf R ->\n  wf (unproj21 A2 R).\nProof using.\n  intros R H [x1 x2]. gen x2.\n  induction_wf IH: H x1. constructor. intros [y1 y2]. auto.\nQed.\n\nLemma wf_unproj22 : forall (R:binary A2),\n  wf R ->\n  wf (unproj22 A1 R).\nProof using.\n  intros R H [x1 x2]. gen x1.\n  induction_wf IH: H x2. constructor. intros [y1 y2]. auto.\nQed.\n\nLemma wf_unproj31 : forall (R:binary A1),\n  wf R ->\n  wf (unproj31 A2 A3 R).\nProof using.\n  intros R H [[x1 x2] x3]. gen x2 x3.\n  induction_wf IH: H x1. constructor. intros [[y1 y2] y3]. auto.\nQed.\n\nLemma wf_unproj32 : forall (R:binary A2),\n  wf R ->\n  wf (unproj32 A1 A3 R).\nProof using.\n  intros R H [[x1 x2] x3]. gen x1 x3.\n  induction_wf IH: H x2. constructor. intros [[y1 y2] y3]. auto.\nQed.\n\nLemma wf_unproj33 : forall (R:binary A3),\n  wf R ->\n  wf (unproj33 A1 A2 R).\nProof using.\n  intros R H [[x1 x2] x3]. gen x1 x2.\n  induction_wf IH: H x3. constructor. intros [[y1 y2] y3]. auto.\nQed.\n\nLemma wf_unproj41 : forall (R:binary A1),\n  wf R ->\n  wf (unproj41 A2 A3 A4 R).\nProof using.\n  intros R H [[[x1 x2] x3] x4]. gen x2 x3 x4.\n  induction_wf IH: H x1. constructor. intros [[[y1 y2] y3] y4]. auto.\nQed.\n\nLemma wf_unproj42 : forall (R:binary A2),\n  wf R ->\n  wf (unproj42 A1 A3 A4 R).\nProof using.\n  intros R H [[[x1 x2] x3] x4]. gen x1 x3 x4.\n  induction_wf IH: H x2. constructor. intros [[[y1 y2] y3] y4]. auto.\nQed.\n\nLemma wf_unproj43 : forall (R:binary A3),\n  wf R ->\n  wf (unproj43 A1 A2 A4 R).\nProof using.\n  intros R H [[[x1 x2] x3] x4]. gen x1 x2 x4.\n  induction_wf IH: H x3. constructor. intros [[[y1 y2] y3] y4]. auto.\nQed.\n\nLemma wf_unproj44 : forall (R:binary A4),\n  wf R ->\n  wf (unproj44 A1 A2 A3 R).\nProof using.\n  intros R H [[[x1 x2] x3] x4]. gen x1 x2 x3.\n  induction_wf IH: H x4. constructor. intros [[[y1 y2] y3] y4]. auto.\nQed.\n\nLemma wf_unproj51 : forall (R:binary A1),\n  wf R ->\n  wf (unproj51 A2 A3 A4 A5 R).\nProof using.\n  intros R H [[[[x1 x2] x3] x4] x5]. gen x2 x3 x4 x5.\n  induction_wf IH: H x1. constructor. intros [[[[y1 y2] y3] y4] y5]. auto.\nQed.\n\nEnd UnprojWf.\n\n#[global]\nHint Resolve\n  wf_unproj21 wf_unproj22\n  wf_unproj31 wf_unproj32 wf_unproj33\n  wf_unproj41 wf_unproj42 wf_unproj43 wf_unproj44\n  wf_unproj51 : wf.\n\n\n(* ********************************************************************** *)\n(** * Lexicographical product *)\n\nLemma wf_lexico2 : forall A1 A2\n (R1:binary A1) (R2:binary A2),\n  wf R1 ->\n  wf R2 ->\n  wf (lexico2 R1 R2).\nProof using.\n  introv W1 W2. intros [x1 x2]. gen x2.\n  induction_wf IH1: W1 x1. intros.\n  induction_wf IH2: W2 x2. constructor. intros [y1 y2] H.\n  simpls. destruct H as [H1|[H1 H2]].\n  apply~ IH1. rewrite H1. apply~ IH2.\nQed.\n\nLemma wf_lexico3 : forall A1 A2 A3\n (R1:binary A1) (R2:binary A2) (R3:binary A3),\n  wf R1 ->\n  wf R2 ->\n  wf R3 ->\n  wf (lexico3 R1 R2 R3).\nProof using.\n  intros. apply~ wf_lexico2. apply~ wf_lexico2.\nQed.\n\nLemma wf_lexico4 : forall A1 A2 A3 A4\n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4),\n  wf R1 ->\n  wf R2 ->\n  wf R3 ->\n  wf R4 ->\n  wf (lexico4 R1 R2 R3 R4).\nProof using.\n  intros. apply~ wf_lexico3. apply~ wf_lexico2.\nQed.\n\n#[global]\nHint Resolve wf_lexico2 wf_lexico3 wf_lexico4 : wf.\n\n\n(* ********************************************************************** *)\n(** * Symmetric product *)\n\nLemma wf_prod2_of_wf_1 : forall (A1 A2:Type)\n (R1:binary A1) (R2:binary A2),\n  wf R1 ->\n  wf (prod2 R1 R2).\nProof using.\n  introv W1. intros [x1 x2].\n  gen x2. induction_wf IH: W1 x1. intros.\n  constructor. intros [y1 y2] [E1 E2]. apply~ IH.\nQed.\n\nLemma wf_prod2_of_wf_2 : forall (A1 A2:Type)\n (R1:binary A1) (R2:binary A2),\n  wf R2 ->\n  wf (prod2 R1 R2).\nProof using.\n  introv W2. intros [x1 x2].\n  gen x1. induction_wf IH: W2 x2. intros.\n  constructor. intros [y1 y2] [E1 E2]. apply~ IH.\nQed.\n\nLemma wf_prod3_of_wf_1 : forall (A1 A2 A3:Type)\n (R1:binary A1) (R2:binary A2) (R3:binary A3),\n  wf R1 ->\n  wf (prod3 R1 R2 R3).\nProof using. intros. apply wf_prod2_of_wf_1. apply~ wf_prod2_of_wf_1. Qed.\n\nLemma wf_prod3_of_wf_2 : forall (A1 A2 A3:Type)\n (R1:binary A1) (R2:binary A2) (R3:binary A3),\n  wf R2 ->\n  wf (prod3 R1 R2 R3).\nProof using. intros. apply wf_prod2_of_wf_1. apply~ wf_prod2_of_wf_2. Qed.\n\nLemma wf_prod3_of_wf_3 : forall (A1 A2 A3:Type)\n (R1:binary A1) (R2:binary A2) (R3:binary A3),\n  wf R3 ->\n  wf (prod3 R1 R2 R3).\nProof using. intros. apply~ wf_prod2_of_wf_2. Qed.\n\nLemma wf_prod4_of_wf_1 : forall (A1 A2 A3 A4:Type)\n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4),\n  wf R1 ->\n  wf (prod4 R1 R2 R3 R4).\nProof using. intros. apply wf_prod2_of_wf_1. apply~ wf_prod3_of_wf_1. Qed.\n\nLemma wf_prod4_of_wf_2 : forall (A1 A2 A3 A4:Type)\n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4),\n  wf R2 ->\n  wf (prod4 R1 R2 R3 R4).\nProof using. intros. apply wf_prod2_of_wf_1. apply~ wf_prod3_of_wf_2. Qed.\n\nLemma wf_prod4_of_wf_3 : forall (A1 A2 A3 A4:Type)\n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4),\n  wf R3 ->\n  wf (prod4 R1 R2 R3 R4).\nProof using. intros. apply wf_prod2_of_wf_1. apply~ wf_prod3_of_wf_3. Qed.\n\nLemma wf_prod4_of_wf_4 : forall (A1 A2 A3 A4:Type)\n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4),\n  wf R4 ->\n  wf (prod4 R1 R2 R3 R4).\nProof using. intros. apply~ wf_prod2_of_wf_2. Qed.\n\n#[global]\nHint Resolve\n  wf_prod2_of_wf_1 wf_prod2_of_wf_2\n  wf_prod3_of_wf_1 wf_prod3_of_wf_2 wf_prod3_of_wf_3\n  wf_prod4_of_wf_1 wf_prod4_of_wf_2 wf_prod4_of_wf_3 wf_prod4_of_wf_4 : wf.\n\n\n(* ********************************************************************** *)\n(** * Well-foundedness of a function image *)\n\nLemma wf_rel_preimage : forall A B (R:binary B) (f:A->B),\n  wf R ->\n  wf (rel_preimage R f).\nProof using.\n  introv W. intros x. gen_eq a: (f x). gen x.\n  induction_wf IH: W a. introv E. constructors.\n  intros y Hy. subst a. hnf in Hy. applys* IH.\nQed.\n\n#[global]\nHint Resolve wf_rel_preimage : wf.\n\n\n(* ********************************************************************** *)\n(* ********************************************************************** *)\n(* ********************************************************************** *)\n(* TEMPORARY *)\n\n(* begin hide *)\n\n(* ********************************************************************** *)\n(** * Union *)\n\n(* --TODO..\n\nSection WfUnion.\n  Variables (A : Type).\n  Variables R1 R2 : binary A.\n\n  Notation Union := (union A R1 R2).\n\n  Remark strip_commut :\n    commut A R1 R2 ->\n    forall x y:A,\n      clos_trans A R1 y x ->\n      forall z:A, R2 z y ->  exists2 y' : A, R2 y' x & clos_trans A R1 z y'.\n  Proof using.\n    induction 2 as [x y| x y z H0 IH1 H1 IH2]; intros.\n    elim H with y x z; auto with sets; intros x0 H2 H3.\n    exists x0; auto with sets.\n\n    elim IH1 with z0; auto with sets; intros.\n    elim IH2 with x0; auto with sets; intros.\n    exists x1; auto with sets.\n    apply t_trans with x0; auto with sets.\n  Qed.\n\n\n  Lemma Acc_union :\n    commut A R1 R2 ->\n    (forall x:A, Acc R2 x -> Acc R1 x) -> forall a:A, Acc R2 a -> Acc Union a.\n  Proof using.\n    induction 3 as [x H1 H2].\n    apply Acc_intro; intros.\n    elim H3; intros; auto with sets.\n    cut (clos_trans A R1 y x); auto with sets.\n    elimtype (Acc (clos_trans A R1) y); intros.\n    apply Acc_intro; intros.\n    elim H8; intros.\n    apply H6; auto with sets.\n    apply t_trans with x0; auto with sets.\n\n    elim strip_commut with x x0 y0; auto with sets; intros.\n    apply Acc_inv_trans with x1; auto with sets.\n    unfold union in |- *.\n    elim H11; auto with sets; intros.\n    apply t_trans with y1; auto with sets.\n\n    apply (Acc_clos_trans A).\n    apply Acc_inv with x; auto with sets.\n    apply H0.\n    apply Acc_intro; auto with sets.\n  Qed.\n\n\n  Theorem wf_union :\n    commut A R1 R2 -> well_founded R1 -> well_founded R2 -> well_founded Union.\n  Proof using.\n    unfold well_founded in |- *.\n    intros.\n    apply Acc_union; auto with sets.\n  Qed.\n\nEnd WfUnion.\n\n*)\n\n(* --TODO: Disjoint union, useful? *)\n\n(* end hide *)\n\n(* ********************************************************************** *)\n(** * Transitive closure *)\n\nLemma wf_tclosure : forall A (R:binary A),\n  wf R ->\n  wf (tclosure R).\nProof using.\n  unfold wf, well_founded.\n  introv HAcc. intro a. specializes HAcc a. generalize dependent a.\n  induction 1 as [ a _ IH ].\n  constructor. intros b Hba.\n  generalize a b Hba IH. clear a b Hba IH.\n  induction 1; eauto using Acc_inv.\nQed.\n", "meta": {"author": "charguer", "repo": "tlc", "sha": "590c8c8d80442376b8ac19198b7ed446cebc6934", "save_path": "github-repos/coq/charguer-tlc", "path": "github-repos/coq/charguer-tlc/tlc-590c8c8d80442376b8ac19198b7ed446cebc6934/src/LibWf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6734945251052962}}
{"text": "Require Import Decidable.\nRequire Import Relation_Operators.\nRequire Import Equality.\n\nInductive term : Set :=\n| trueT : term\n| falseT : term\n| if_then_elseT : term -> term -> term -> term.\n\n\nInductive eval1 : term -> term -> Prop :=\n| e_if_true : forall t2 t3, eval1 (if_then_elseT trueT t2 t3) t2\n| e_if_false : forall t2 t3, eval1 (if_then_elseT falseT t2 t3) t3\n| e_if : forall t1 t1' t2 t3,\n    eval1 t1 t1' -> eval1 (if_then_elseT t1 t2 t3) (if_then_elseT t1' t2 t3).\n\nNotation \"t1 --> t2\" := (eval1 t1 t2) (at level 70, no associativity).\n\nTheorem eval1_deterministic : forall t t' t'',\n    t --> t' -> t --> t'' -> t' = t''.\nProof.\n  intros t t' t'' Ht'. generalize dependent t''.\n  induction Ht' as [].\n  - intros t'' Ht''. inversion Ht''. reflexivity.\n    inversion H3.\n  - intros t'' Ht''. inversion Ht''. reflexivity.\n    inversion H3.\n  - intros t'' Ht''. inversion Ht''. rewrite <- H0 in Ht'.\n    inversion Ht'. rewrite <- H0 in Ht'.\n    inversion Ht'. f_equal. apply IHHt'. auto.\nQed.\n\nInductive value : term -> Prop :=\n| value_true : value trueT\n| value_false : value falseT.\n\nLemma value_dec : forall t, decidable (value t).\nProof.\n  unfold decidable. destruct t.\n  - left. apply value_true.\n  - left. apply value_false.\n  - right. intros H. inversion H.\nQed.\n\nDefinition nf (t : term) : Prop := ~ exists t', t --> t'.\n\nTheorem nf_value : forall t, value t <-> nf t.\nProof.\n  intros t. split.\n  - intros Hvt. inversion Hvt; intros [t' Ht']; inversion Ht'.\n  - apply contrapositive. apply value_dec.\n    induction t.\n    + intros Hnv. exfalso. apply Hnv. apply value_true.\n    + intros Hnv. exfalso. apply Hnv. apply value_false.\n    + intros Hnv Hnf. destruct t1.\n      * apply Hnf. exists t2. apply e_if_true.\n      * apply Hnf. exists t3. apply e_if_false.\n      * apply IHt1. intros Hv. inversion Hv.\n        intros [t' Ht']. apply Hnf.\n        exists (if_then_elseT t' t2 t3). apply e_if. auto.\nQed.\n  \nNotation \"t1 -->* t2\" := (clos_refl_trans_1n _ eval1 t1 t2) (at level 70).\n\nTheorem multistep_nf_unique : forall t u u',\n    t -->* u -> nf u -> t -->* u' -> nf u' -> u = u'.\nProof.\n  intros t u u' Hu Hnfu. generalize dependent u'.\n  induction Hu.\n  - intros u' Hu' Hnfu'. inversion Hu'.\n    reflexivity. exfalso. apply Hnfu.\n    exists y. auto.\n  - intros u' Hu' Hnfu'. inversion Hu'.\n    exfalso. apply Hnfu'. exists y. rewrite <- H0. auto.\n    apply IHHu. apply Hnfu.\n    assert (Heq : y0 = y).\n    { apply eval1_deterministic with (t:=x). auto. auto. }\n    rewrite <- Heq. auto. auto.\nQed.\n\nFixpoint size (t : term) :=\n  match t with\n  | trueT => 1\n  | falseT => 1\n  | if_then_elseT t1 t2 t3 => 1 + (size t1) + (size t2) + (size t3)\n  end.\n\nRequire Import PeanoNat.\nRequire Import Operators_Properties.\n\nLemma add_lt_l : forall m n p, m + n < p -> m < p.\nProof.\n  intros m n p H.\n  assert (H'': p <> 0).\n  { unfold lt in H. inversion H. intros E. inversion E.\n    intros E. inversion E. }\n  unfold lt in H. apply Nat.le_succ_le_pred in H.\n  assert (H' : m <= Nat.pred p).\n  { transitivity (Nat.pred p - n).\n    apply Nat.le_add_le_sub_r. apply H.\n    apply Nat.le_sub_l. }\n  unfold lt.\n  rewrite <- (Nat.succ_pred).\n  apply Nat.succ_le_mono in H'. apply H'. auto.\nQed.\n\nLemma multistep_cong_if : forall t1 t1' t2 t3,\n    t1 -->* t1' -> if_then_elseT t1 t2 t3 -->* if_then_elseT t1' t2 t3.\nProof.\n  intros t1 t1' t2 t3 Hev.\n  induction Hev.\n  - apply rt1n_refl.\n  - apply e_if with (t2:=t2) (t3:=t3) in H.\n    apply Relation_Operators.rt1n_trans with (y:=(if_then_elseT y t2 t3)).\n    auto. auto.\nQed.\n\nLemma multistep_transitive : forall t1 t2 t3,\n    t1 -->* t2 -> t2 -->* t3 -> t1 -->* t3.\nProof.\n  intros t1 t2 t3 H12 H23. induction H12.\n  - apply H23.\n  - apply IHclos_refl_trans_1n in H23.\n    apply Relation_Operators.rt1n_trans with (y:=y). auto. auto.\nQed.\n    \nTheorem normalizing : forall t, exists t', nf t' /\\ t -->* t'.\nProof.\n  pose (P:= fun n => forall t, size t = n -> exists t', nf t' /\\ t-->* t').\n  assert (H : forall n, P n).\n  { apply (well_founded_ind Nat.lt_wf_0).\n    unfold P.\n    intros n IH.\n    intros t Ht. destruct t as [].\n    - exists trueT. split. apply nf_value. apply value_true.\n      apply rt1n_refl.\n    - exists falseT. split. apply nf_value. apply value_false.\n      apply rt1n_refl.\n    - simpl in Ht.\n      assert (Hs : size t1 + size t2 + size t3 < n).\n      { unfold lt. rewrite Ht. apply Nat.le_refl. }\n      assert (Hs1: size t1 < n).\n      { rewrite <- Nat.add_assoc in Hs.\n        apply add_lt_l with (n:=(size t2 + size t3)). auto. }\n      assert (Hs2: size t2 < n).\n      { rewrite (Nat.add_comm (size t1)) in Hs.\n        rewrite <- Nat.add_assoc in Hs.\n        apply add_lt_l with (n:=(size t1 + size t3)). auto. }\n      assert (Hs3: size t3 < n).\n      { rewrite (Nat.add_comm _ (size t3)) in Hs.\n        apply add_lt_l with (n:=(size t1 + size t2)). auto. }\n      apply IH with (t:=t1) in Hs1.\n      apply IH with (t:=t2) in Hs2.\n      apply IH with (t:=t3) in Hs3.\n      destruct Hs1 as [t1' [Hnft1' Hevt1']].\n      destruct Hs2 as [t2' [Hnft2' Hevt2']].\n      destruct Hs3 as [t3' [Hnft3' Hevt3']].\n      apply nf_value in Hnft1'.\n      apply multistep_cong_if with (t2:=t2) (t3:=t3) in Hevt1'.\n      destruct Hnft1'.\n      + exists t2'. split. auto.\n        assert (Hevt2'' : if_then_elseT trueT t2 t3 -->* t2').\n        { apply Relation_Operators.rt1n_trans with (y:=t2).\n          apply e_if_true. auto. }\n        apply multistep_transitive with (t2:=if_then_elseT trueT t2 t3).\n        auto. auto.\n      + exists t3'. split. auto.\n        assert (Hevt3'' : if_then_elseT falseT t2 t3 -->* t3').\n        { apply Relation_Operators.rt1n_trans with (y:=t3).\n          apply e_if_false. auto. }\n        apply multistep_transitive with (t2:=if_then_elseT falseT t2 t3).\n        auto. auto.\n      + reflexivity.\n      + reflexivity.\n      + reflexivity. }\n  intros t. unfold P in H. apply H with (n:=size t). reflexivity.\nQed.\n", "meta": {"author": "jzc", "repo": "formalizations", "sha": "f5cd69ec299c0a41bbb34a7e714d81c56d3ca4fb", "save_path": "github-repos/coq/jzc-formalizations", "path": "github-repos/coq/jzc-formalizations/formalizations-f5cd69ec299c0a41bbb34a7e714d81c56d3ca4fb/IfThenElse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7905303162021597, "lm_q1q2_score": 0.6734945179293246}}
{"text": "(** * Merge:  Merge Sort, With Specification and Proof of Correctness*)\n\nRequire Import Le Lt Gt Decidable PeanoNat Recdef.\nFrom Coq Require Import Recdef.  (* needed for [Function] feature *)\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\nNotation  \"a >=? b\" := (Nat.leb b a)\n                          (at level 70) : nat_scope.\nNotation  \"a >? b\"  := (Nat.ltb b a)\n                         (at level 70) : nat_scope.\n\n\nLemma eqb_reflect : forall x y, reflect (x = y) (x =? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.eqb_eq.\nQed.\n\nLemma ltb_reflect : forall x y, reflect (x < y) (x <? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.ltb_lt.\nQed.\n\nLemma leb_reflect : forall x y, reflect (x <= y) (x <=? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.leb_le.\nQed.\n\nLtac bdestruct X :=\n  let H := fresh in let e := fresh \"e\" in\n   evar (e: Prop);\n   assert (H: reflect e X); subst e;\n    [eauto with bdestruct\n    | destruct H as [H|H];\n      [ | try first [apply not_lt in H | apply not_le in H]]].\n\n\nHint Resolve ltb_reflect leb_reflect eqb_reflect : bdestruct.\n\nLtac inv H := inversion H; clear H; subst.\n\nInductive sorted: list nat -> Set :=\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(** Mergesort is a well-known sorting algorithm, normally presented\n    as an imperative algorithm on arrays, that has worst-case\n    O(n log n) execution time and requires O(n) auxiliary space.\n\n    The basic idea is simple: we divide the data to be sorted into two\n    halves, recursively sort each of them, and then\n    merge together the (sorted) results from each half:\n\n    [[\n    mergesort xs =\n      split xs into ys,zs;\n      ys' = mergesort ys;\n      zs' = mergesort zs;\n      return (merge ys' zs')\n    ]]\n\n    (As usual, if you are unfamiliar with mergesort see Wikipedia or\n    your favorite algorithms textbook.)\n\n    Mergesort on lists works essentially the same way: we split the\n    original list into two halves, recursively sort each sublist,\n    and then merge the two sublists together again.  The only \n    difference, compared to the imperative algorithm, is that splitting\n    the list takes O(n) rather than O(1) time; however, that \n    does not affect the asymptotic cost, since the merge step already\n    takes O(n) anyhow. \n*)\n\n(* ================================================================= *)\n(** ** Split and its properties *)\n\n(** Let us try to write down the Gallina code for mergesort.\n    The first step is to write a splitting function. There are\n    several ways to do this, since the exact splitting method does\n    not matter as long as the results are (roughly) equal in size.\n    For example, if we know the length of the list, we could use that to split\n    at the half-way point. But here is an attractive alternative, which simply\n    alternates assigning the elements into left and right sublists:\n*)     \n\nFixpoint split {X:Type} (l:list X) : (list X * list X) :=\n  match l with\n  | [] => ([],[])\n  | [x] => ([x],[])\n  | x1::x2::l' =>\n    let (l1,l2) := split l' in\n    (x1::l1,x2::l2)\n  end.\n\n(** Note: For generality, we made this function polymorphic, since the\n    type of the values in the list is irrelevant to the splitting process. \n\n    While this function is straightforward to define, it can be a bit challenging\n    to work with.  Let's try to prove the following lemma, which is obviously true:\n*)\n\nLemma split_len_first_try: forall {X} (l:list X) (l1 l2: list X),\n    split l = (l1,l2) ->\n    length l1 <= length l /\\\n    length l2 <= length l.\nProof.\n  induction l; intros. \n  - inv H. simpl. lia. \n  - destruct l as [| x l'].\n    + inv H. \n      split; simpl; auto.\n    + inv H. destruct (split l') as [l1' l2'] eqn:E. inv H1. \n      (* We're stuck! The IH talks about [split (x::l')] but we\n         only know aobut [split (a::x::l')]. *)\nAbort.\n\n(** The problem here is that the standard induction principle for lists\n    requires us to show that the property being proved follows for      \n    any non-empty list if it holds for the tail of that list.\n    What we want here is a \"two-step\" induction principle, that instead requires\n    us to show that the property being proved follows for a list of\n    length at least two, if it holds for the tail of the tail of that list.\n    Formally: \n*)\n\nDefinition list_ind2_principle:=\n    forall (A : Type) (P : list A -> Prop),\n      P [] ->\n      (forall (a:A), P [a]) ->\n      (forall (a b : A) (l : list A), P l -> P (a :: b :: l)) ->\n      forall l : list A, P l.\n\n(** If we assume the correctness of this \"non-standard\" induction principle, \n    our [split_len] proof is easy, using a form of the [induction] tactic \n    that lets us specify the induction principle to use: \n*)\n\nLemma split_len': list_ind2_principle -> \n    forall {X} (l:list X) (l1 l2: list X),\n    split l = (l1,l2) ->\n    length l1 <= length l /\\\n    length l2 <= length l.\nProof.\n  unfold list_ind2_principle; intro IP.\n  induction l using IP; intros.\n  - inv H. lia.\n  - inv H. simpl; lia.\n  - inv H. destruct (split l) as [l1' l2']. inv H1. \n    simpl. \n    destruct (IHl l1' l2') as [P1 P2]; auto; lia.\nQed.\n\n(** We still need to prove [list_ind2_principle].  There are several\n    ways to do this, but one direct way is to write an explicit proof\n    term, thus: *)\n\nDefinition list_ind2 :\n  forall (A : Type) (P : list A -> Prop),\n      P [] ->\n      (forall (a:A), P [a]) ->\n      (forall (a b : A) (l : list A), P l -> P (a :: b :: l)) ->\n      forall l : list A, P l :=\n  fun (A : Type)\n      (P : list A -> Prop)\n      (H : P [])\n      (H0 : forall a : A, P [a])\n      (H1 : forall (a b : A) (l : list A), P l -> P (a :: b :: l))  => \n    fix IH (l : list A) :  P l :=\n    match l with\n    | [] => H\n    | [x] => H0 x\n    | x::y::l' => H1 x y l' (IH l')\n    end.\n\n(** Here, the [fix] keyword defines a local recursive function [IH]\n    of type [forall l:list A, P l], which is returned as the overall value of\n    [list_ind2]. As usual, this function must be obviously terminating \n    to Coq (which it is because the recursive call is on a sublist [l'] \n    of the original argument [l]) and the [match] must be exhaustive over\n    all possible lists (which it evidently is). \n*)\n\n(** With our induction principle in hand, we can finally prove \n    [split_len] free and clear: \n*)\n\nLemma split_len: forall {X} (l:list X) (l1 l2: list X),\n    split l = (l1,l2) ->\n    length l1 <= length l /\\\n    length l2 <= length l.\nProof.\n apply (@split_len' list_ind2).\nQed.\n\n(** **** Exercise: 3 stars, standard (split_perm) *)\n\n(** Here's another fact about [split] that we will find useful later on.  \n*)\n\n\nLemma split_perm : forall {X:Type} (l l1 l2: list X),\n    split l = (l1,l2) -> Permutation l (l1 ++ l2).\nProof.\n  induction l as [| x | x1 x2 l1' IHl'] using list_ind2; intros.\n  inv H. simpl. auto.\n  inv H. simpl. auto.\n  inv H.\n  destruct (split l1').\n  inv H1.\n  assert (Permutation l1' (l ++ l0)) .\n  apply (IHl' l l0 ) . auto.\n  simpl.   econstructor.\n  assert (Permutation (x2 :: l1') (x2 :: (l ++ l0))).\n  econstructor. auto.\n  econstructor. apply H0. clear H0.\n  assert (Permutation (x2 :: l ++ l0) (x2 :: l0 ++ l)).\n  econstructor.    apply Permutation_app_comm.\n  econstructor. apply H0.\n  assert ((x2 :: l0 ++ l) = ((x2 :: l0) ++ l )) .\n  auto.\n  rewrite H1.\n  apply Permutation_app_comm.\nQed.\n\n\n\n\n(* ================================================================= *)\n(** ** Defining Merge *)\n\n(** Next, we need a [merge] function, which takes two\n    sorted lists (of naturals) and returns their sorted result.\n    This would seem easy to write:\n\n    [[\n    Fixpoint merge l1 l2 :=\n      match l1, l2 with\n      | [], _ => l2\n      | _, [] => l1\n      | a1::l1', a2::l2' =>\n          if a1 <=? a2 then a1 :: merge l1' l2 else a2 :: merge l1 l2'\n      end.\n    ]]\n\n    But Coq will reject this definition with the message:\n\n    [[\n    Error: Cannot guess decreasing argument of fix.\n    ]]\n\n    Coq insists the every [Fixpoint] definition be structurally recursive\n    on some specified argument, meaning that at each recursive call the\n    callee is passed a value that is a sub-term of the caller's argument value.\n    This check guarantees that every [Fixpoint] is actually terminating.\n\n    It is fairly obvious that this function is in fact terminating, because\n    at each call, either [l1] or [l2] is passed the tail of its original value.\n    But unfortunately, [Fixpoint] recursive calls must always decrease on\n    a _single fixed_ argument -- and neither [l1] nor [l2] will do. (That's\n    why Coq couldn't guess the one to use.)  We might reasonably wish\n    that Coq was a little smarter, but it isn't.\n\n    There are a number of ways to get around the problem of convincing\n    Coq that a function is actually terminating when the \"natural\" [Fixpoint]\n    doesn't work. In this case, a little creativity (or a peek at the Coq\n    library) might lead us to the following definition:\n*)\n\nFixpoint merge l1 l2  {struct l1} :=\n  let fix merge_aux l2 :=\n  match l1, l2 with\n  | [], _ => l2\n  | _, [] => l1\n  | a1::l1', a2::l2' =>\n      if a1 <=? a2 then a1 :: merge l1' l2 else a2 :: merge_aux l2'\n  end\n  in merge_aux l2.\n\n(** Coq accepts the outer definition because it is structurally\n    decreasing on [l1] (we specify that with the [{struct l1}] annotation,\n    although Coq would have guessed this even if we didn't write it), \n    and it accepts the inner definition because it is structurally recursive \n    on its (sole) argument. (Note that [let fix ... in ... end] is just a \n    mechanism for  defining a local recursive function.)  \n\n    This definition will turn out to work pretty well; the only irritation \n    is that simplification will show the definition of [merge_aux], as\n    illustrated by the following examples. \n\n    First, let's remind ourselves that Coq desugars a [match] over multiple \n    arguments into a nested sequence of matches: \n*)\n\nPrint merge.\n\n(** ==> (after a little renaming for clarity)\n\n    [[\n    fix merge (l1 l2 : list nat) {struct l1} : list nat :=\n      let\n        fix merge_aux (l2 : list nat) : list nat :=\n          match l1 with\n          | [] => l2\n          | a1 :: l1' =>\n              match l2 with\n              | [] => l1\n              | a2 :: l2' =>\n                  if a1 <=? a2 then a1 :: merge l1' l2 else a2 :: merge_aux l2'\n              end\n          end in\n      merge_aux l2.\n    ]]\n*)\n\n(** Let's prove the following simple lemmas about [merge]: \n*)\n\nLemma merge2 : forall (x1 x2:nat) r1 r2,\n    x1 <= x2 ->\n    merge (x1::r1) (x2::r2) =\n    x1::merge r1 (x2::r2).\nProof.\n  intros.\n  simpl. (* This blows up in an unpleasant way, but we can\n      still make some sense of it.  Look at the\n      [(fix merge_aux ...)] term. It represents the\n      the local function [merge_aux] after the value of the\n      free variable [l1] has been substituted by [x1::r1],\n      the match over [l1] has been simplified to its\n      second arm (the non-empty case) and [x1] and [r1] have\n      been substituted for the pattern variables [a1] and [l1']. \n      The entire [fix] is applied to [r2], but Coq won't attempt\n      any further simplification until the structure of [r2] \n      is known. *)\n  bdestruct (x1 <=? x2).\n  - auto.\n  - (* Since [H] and [H0] are contradictory, this case follows by [lia].\n       But (ignoring that for the moment), note that we can get further \n       simplification to occur if we give some structure to [l2]: *)\n    simpl. (* does nothing *)\n    destruct r2; simpl.  (* makes some progress *)\n    + lia.\n    + lia. \nQed.  \n\nLemma merge_nil_l : forall l, merge [] l = l. \nProof.\n  intros. simpl.\n  (* Once again, we see a version of [merge_aux] specialized to\n  the value [l1 = nil]. Now we see only the first arm (the\n  empty case) of the [match] expression, which simply returns [l2];\n  in other words, here the [fix] is just the identity function. \n  And once again, the [fix] is applied to [l].  Irritatingly,\n  Coq _still_ refuses to perform the application unless [l]\n  is destructured first (even though the answer is always [l]). *)\n  destruct l.\n  - auto.\n  - auto. \nQed.\n\n(** Morals: \n\n    (1) Even though the proof state involving local recursive\n        functions can can be hard to read, persevere!\n\n    (2) If Coq won't simplify an \"obvious\" application, try destructing\n        the argument.\n\n    We will defer stating and proving other properties of [merge] until later.\n*)\n\n(* ================================================================= *)\n(** ** Defining Mergesort *)\n\n(** Finally, we need to define the main mergesort function itself.\n    Once again, we might hope to write something simple like this:\n\n    [[\n    Fixpoint mergesort (l: list nat) :  list nat :=\n       let (l1,l2) := split l in\n       merge (mergesort l1) (mergesort l2).\n    ]]\n\n    Since this function has only one argument, Coq guesses that it is\n    intended to be structurally decreasing, but still \n    rejects the definition, this time with the complaint:\n\n    [[\n    Recursive call to mergesort has principal argument equal to \n    \"l1\" instead of a subterm of \"l\".\n    ]]\n\n    Again, the problem is that Coq has no way to know that [l1] and [l2]\n    are \"smaller\" than [l].  And this time, it is hard to complain that\n    Coq is being stupid, since the fact that [split] returns smaller\n    lists than it is passed is nontrivial.\n\n    In fact, it isn't true! Consider the behavior of [split] on \n    empty or singleton lists...  This is case where Coq's totality\n    requirements can actually help us correct the definition of \n    our code.  What we really want to write is something more like:\n\n    [[\n    Fixpoint mergesort (l: list nat) :  list nat :=\n        match l with\n        | [] => []\n        | [x] => [x]\n        | _ => let (l1,l2) := split l in merge (mergesort l1) (mergesort l2).\n    ]]\n\n    Now this function really is terminating!  But Coq still won't let us\n    write it with a [Fixpoint].  Instead, we need to use a mechanism \n    (there are several available) for defining functions that accommodates\n    an explicit way to show that the function only calls itself on smaller\n    arguments.   We will use the [Function] command:\n*)\n\nFunction mergesort (l: list nat) {measure length l} :  list nat :=\n  match l with\n  | [] => []\n  | [x] => [x]\n  | _ => let (l1,l2) := split l in\n         merge (mergesort l1) (mergesort l2)\n  end.\n\n(** [Function] is similar to [Fixpoint], but it lets us specify \n    an explicit _measure_ on the function arguments. \n    The annotation [{measure length l}] says that the function \n    [length] applied to argument [l] serves as a decreasing measure.  \n    After processing this definition, Coq enters proof mode and demands \n    proofs that each recursive call is indeed on a shorter list. \n    Happily, we proved that fact already. \n*)\n\nProof.\n  - (* recursive call on l1 *)\n    intros.\n    simpl in *. destruct (split l1) as [l1' l2'] eqn:E. inv teq1. simpl. \n    destruct (split_len _ _ _ E).\n    lia.\n  - (* recursive call on l2 *)\n    intros.\n    simpl in *. destruct (split l1) as [l1' l2'] eqn:E. inv teq1. simpl. \n    destruct (split_len _ _ _ E).\n    lia.\nDefined.\n\n(** Notice that the [Proof] must end with the keyword [Defined] rather\n    than [Qed]; if we don't do this, we won't be able to actually \n    compute with [mergesort]. \n\n    Defining [mergesort] with [Function] rather than [Fixpoint] causes\n    the automatic generation of some useful auxiliary definitions that we \n    will need when working with it. \n    First, we get a lemma [mergesort_equation], which performs a one-level\n    unfolding of the function. *)\n\nCheck mergesort_equation.\n \n(** ==> \n\n    [[\n    mergesort_equation\n     : forall l : list nat,\n       mergesort l =\n       match l with\n       | [] => []\n       | [x] => [x]\n       | x :: _ :: _ =>\n           let (l2, l3) := split l in merge (mergesort l2) (mergesort l3)\n       end\n    ]]\n\n    We should always use [apply mergesort_equation]\n    to simplify a call to [mergesort] rather than trying to [unfold] or [simpl]\n    it, which will lead to ugly or mysterious results.\n\n    Second, we get an induction principle [mergesort_ind]; performing\n    induction using this principle can be much easier than trying to\n    use list induction over the argument [l].  \n*)\n\nCheck mergesort_ind.\n\n(** ==>   \n    [[\n    mergesort_ind\n     : forall P : list nat -> list nat -> Prop,\n       (forall l : list nat, l = [] -> P [] []) ->\n       (forall (l : list nat) (x : nat), l = [x] -> P [x] [x]) ->\n       (forall l _x : list nat,\n        l = _x ->\n        match _x with\n        | _ :: _ :: _ => True\n        | _ => False\n        end ->\n        forall l1 l2 : list nat,\n        split l = (l1, l2) ->\n        P l1 (mergesort l1) ->\n        P l2 (mergesort l2) -> P _x (merge (mergesort l1) (mergesort l2))) ->\n        forall l : list nat, P l (mergesort l)\n    ]]\n*)\n\n(* ================================================================= *)\n(** ** Correctness: Sortedness *)\n\n(** As with insertion sort, our goal is to prove that mergesort produces\n    a sorted list that is a permutation of the original list, i.e. to prove\n    \n    [[\n    is_a_sorting_algorithm mergesort\n    ]] \n  \n    We will start by showing that [mergesort] produces a sorted list.  The key \n    lemma is to show that [merge] of two sorted lists produces a sorted list.\n    It is perhaps easiest to break out a sub-lemma first:\n*)\n\nLemma sorted_inv : forall x l , sorted (x :: l) -> sorted l.\nProof.\n  intros.\n  induction l.\n  constructor.\n  inv H.\n  auto.\nQed.\n\n\n(** **** Exercise: 2 stars, standard (sorted_merge1) *)\nLemma sorted_merge1 : forall x x1 l1 x2 l2,\n    x <= x1 -> x <= x2 -> \n    sorted (merge (x1::l1) (x2::l2)) ->\n    sorted (x :: merge (x1::l1) (x2::l2)).\nProof.\n  firstorder.\n  simpl in *.\n  bdestruct (x2 >=? x1); constructor; auto.\nQed.\n\nLemma sorted_merge2 : forall x l1 l2 ,                                                                                                                                                        \n    sorted (x :: l1) ->\n    sorted (x :: l2) ->\n    sorted (merge l1 l2) ->\n    sorted (x :: merge l1 l2).\nProof.\ndestruct l1; intros.\nrewrite (merge_nil_l l2) in *.\nauto.\ndestruct l2. \nsimpl in *.\nauto.\napply sorted_merge1.\ninv H. auto.\ninv H0. auto.\nauto.\nQed.\n\n\n(** **** Exercise: 4 stars, standard (sorted_merge) *)\nLemma sorted_merge : forall l1, sorted l1 ->\n                     forall l2, sorted l2 ->\n                     sorted (merge l1 l2).\nProof.\n  intro.\n  induction l1.\n  intros.\n  rewrite (merge_nil_l l2).\n  auto.\n  \n  intro.\n  induction l2; intros; simpl.\n\n  auto.\n\n  assert (sorted l1).\n  eapply sorted_inv. apply H.\n  specialize (IHl1 H1).\n  \n  bdestruct (a0 >=? a).\n  apply sorted_merge2.\n  auto.\n  constructor; auto.\n  apply IHl1.   \n  auto.\n\n  assert (sorted (a0 :: merge (a :: l1) l2)). \n  apply sorted_merge2.\n  constructor. lia. auto. auto.\n  apply IHl2.\n  eapply sorted_inv.\n  apply H0.\n\n  exact H3.\n\nQed.\n\n    \n  \n(** **** Exercise: 2 stars, standard (mergesort_sorts) *)\nLemma mergesort_sorts: forall l, sorted (mergesort l).\nProof.\n  intro.\n  functional induction (mergesort l).\n  constructor.\n  constructor.\n  apply sorted_merge; auto.\nQed.  \n\n\n\n(* ================================================================= *)\n(** ** Correctness: Permutation *)\n\n(** Finally, we must show that [mergesort] returns a permutation of its input.\n\n    As usual, the key lemma is for [merge]. \n\n    Incidentally, you are welcome to import the alternative characterizations\n    of permutations as multisets given in [Multiset] or [BagPerm] \n    and use that instead of [Permutation] if you think it will be easier. \n    (I'm not sure!)\n*)\n\n\n(** **** Exercise: 3 stars, advanced (merge_perm) *)\nLemma merge_perm: forall (l1 l2: list nat),\n    Permutation (l1 ++ l2) (merge l1 l2).\nProof.\n    (* Hint: A nested induction on [l2] is required. *)\n  induction l1.\n  intros. rewrite (merge_nil_l l2).\n  simpl in *.\n  auto.\n  \n  induction l2.\n  simpl.\n  assert (a :: l1 ++ [] = a :: l1).\n  f_equal.\n  apply app_nil_r.\n  rewrite H.\n  auto.\n  simpl.\n  bdestruct (a0 >=? a).\n  simpl.\n  econstructor.\n  apply IHl1.\n  assert  (Permutation ((a :: l1) ++ a0 :: l2) ((a0 :: l2) ++ a :: l1)).\n  apply Permutation_app_comm.\n  assert ((a :: l1 ++ a0 :: l2) = ((a :: l1) ++ a0 :: l2)).\n  auto.\n  rewrite H1.\n  econstructor.\n  apply H0.\n  simpl.\n  econstructor.\n  econstructor.\n  apply Permutation_app_comm.\n  exact IHl2.\nQed.\n\n  \n\n(** **** Exercise: 3 stars, advanced (mergesort_perm) *)\nLemma mergesort_perm: forall l, Permutation l (mergesort l).\nProof.\n    apply mergesort_ind; intros.\n    auto.\n    auto.\n    subst _x.\n    econstructor.\n    apply (split_perm l l1 l2 e0).\n    assert (Permutation (l1 ++ l2) ((mergesort l1) ++ (mergesort l2))).\n    apply Permutation_app.\n    auto. auto.\n    econstructor.\n    apply H1.\n    apply merge_perm.\nQed.\n\n(*\n(** Putting it all together: *)\n\nTheorem mergesort_correct:\n  is_a_sorting_algorithm mergesort.\nProof.\n  split.\n  apply mergesort_perm.\n  apply mergesort_sorts.\nQed.\n*)\n(** $Date$ *)\n\n(* 2021-08-11 15:15 *)\n", "meta": {"author": "lengyijun", "repo": "MergeSort", "sha": "6338b5407322ab3d7bd5ef880079d6c26a6bb8be", "save_path": "github-repos/coq/lengyijun-MergeSort", "path": "github-repos/coq/lengyijun-MergeSort/MergeSort-6338b5407322ab3d7bd5ef880079d6c26a6bb8be/coq/recursive-induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.6734945174234723}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Shorthand.\n\n(** Lexicographical ordering on binary lists *)\n\nInductive lex : list bool -> list bool -> Prop :=\n  | nil_lex : forall a, lex nil a\n  | car_lex : forall a b, lex (false :: a) (true :: b)\n  | cdr_lex : forall a b c, lex a b -> lex (c :: a) (c :: b).\n\n(** nil is never larger *)\n\nLemma nnil_lex :  forall b l, ~ lex (b :: l) nil.\nProof.\n  intros b l.\n  induction l.\n  induction b.\n  intros H.\n  inversion H.\n  intros H.\n  inversion H.\n  intros H.\n  inversion H.\nQed.\n\n(** lexicographical ordering is decidable *)\n\nLemma dec_lex: forall a b, (lex a b) + (~ lex a b).\nProof.\n  induction a.\n  intros b.\n  apply inl.\n  apply nil_lex.\n  induction b.\n  apply inr.\n  apply nnil_lex.\n  induction (IHa b).\n  induction a.\n  induction a1.\n  apply inl.\n  apply cdr_lex.\n  apply a2.\n  apply inr.\n  intros q.\n  inversion q.\n  induction a1.\n  apply inl.\n  apply car_lex.\n  apply inl.\n  apply cdr_lex.\n  apply a2.\n  induction a.\n  induction a1.\n  apply inr.\n  contradict b0.\n  inversion  b0.\n  trivial.\n  apply inr.\n  intros.\n  intros U.\n  inversion U.\n  induction a1.\n  apply inl.\n  apply car_lex.\n  apply inr.\n  intros q.\n  inversion q.\n  auto.\nQed.\n\nLemma lex_cdr : forall a b i, lex (i :: a) (i :: b) -> lex a b.\nProof.\n  intros a b i H.  \n  inversion H.\n  trivial.\nQed.\n\nLemma lex_refl : forall a, lex a a.\nProof.\n  induction a.\n  apply nil_lex.\n  apply cdr_lex.\n  auto.\nQed.\n\nLemma lex_nil_is_nil : forall c, lex c nil -> c = nil.\nProof.\n  induction c.\n  auto.\n  intro H.\n  contradict H.\n  apply nnil_lex.\nQed.\n\nTheorem lex_trans : forall a b c, lex a b -> lex b c -> lex a c.\nrefine (fix f (a b c : list bool) : lex a b -> lex b c -> lex a c :=\n          match b with\n              | nil => _\n              | false :: b' => match a with\n                                   | nil => _\n                                   | false :: a' => match c with\n                                                        | nil => _\n                                                        | false :: c' => _\n                                                        | true :: c' => _\n                                                    end\n                                   | true :: a' => _\n                               end\n              | true :: b' => match a with\n                                   | nil => _\n                                   | false :: a' => match c with\n                                                        | nil => _\n                                                        | false :: c' => _\n                                                        | true :: c' => _\n                                                    end\n                                   | true :: a' => match c with\n                                                       | nil => _\n                                                       | false :: c' => _\n                                                       | true :: c' => _\n                                                   end\n                               end\n          end\n ).\n\nintros.\nassert(H1 : a = nil).\napply lex_nil_is_nil.\ntrivial.\nrewrite -> H1.\ntrivial.\n\nintros.\napply nil_lex.\nintros ? J.\ncontradict J.\napply nnil_lex.\n\nintros H H0.\ninversion H.\ninversion H0.\napply cdr_lex.\napply (f a' b' c').\ntrivial.\ntrivial.\n\nintros ? H.\ninversion H.\n\nintros ? H.\ninversion H.\n\nintros.\napply car_lex.\n\nintros ? H0.\ninversion H0.\n\nintros.\napply nil_lex.\nintro H.\ninversion H.\n\nintros ? H.\ninversion H.\n\nintros.\napply car_lex.\n\nintros H H0.\ninversion H.\ninversion H0.\napply cdr_lex.\napply (f _ b').\nauto.\nauto.\nQed.\n\nTheorem lex_antisym : forall a b, lex a b /\\ lex b a -> a = b.\nrefine (fix f a b : lex a b /\\ lex b a -> a = b :=\n          match a with\n              | nil => _\n              | true :: a' => match b with\n                                | nil => _\n                                | false :: b' => _\n                                | true :: b' => _\n                              end\n              | false :: a' => match b with\n                                 | nil => _\n                                 | false :: b' => _\n                                 | true :: b' => _\n                               end\n          end).\n\n(* Todo: make this proof nicer *)\n\nintro H; destruct H as [H0 H1]; apply eq_sym; [apply lex_nil_is_nil; [trivial]].\n\nintro H; destruct H as [H H0]; inversion H.\n\nintro H.\ndestruct H as [H H0].\nassert(H1 : a' = b').\napply f.\nsplit.\napply (lex_cdr _ _ true).\ntrivial.\napply (lex_cdr _ _ true).\ntrivial.\nrewrite -> H1.\nauto.\n\nintro H.\ndestruct H as [H H0].\ninversion H.\n\nintro H.\ndestruct H as [H H0].\ninversion H.\n\nintro H.\ndestruct H as [H H0].\ninversion H0.\n\nintro H.\ndestruct H as [H H0].\nassert(H1 : a'=b').\napply f.\nsplit.\napply (lex_cdr _ _ false).\ntrivial.\napply (lex_cdr _ _ false).\ntrivial.\nrewrite -> H1.\nauto.\nQed.\n\nDefinition lex_total : forall a b, lex a b + lex b a.\nrefine (fix f a b : lex a b + lex b a :=\n          match a with\n              | nil => _\n              | x :: a' => match b with\n                               | nil => _\n                               | y :: b' => _\n                           end\n          end).\n\napply inl.\napply nil_lex.\n\napply inr.\napply nil_lex.\n\ninduction x.\ninduction y.\nassert (lex a' b' + lex b' a').\napply f.\ninduction H.\napply inl.\napply cdr_lex.\ntrivial.\napply inr.\napply cdr_lex.\ntrivial.\napply inr.\napply car_lex.\ninduction y.\napply inl.\napply car_lex.\nassert (lex a' b' + lex b' a').\napply f.\ninduction H.\napply inl.\napply cdr_lex.\ntrivial.\napply inr.\napply cdr_lex.\ntrivial.\nQed.\n\nLemma lex_total_lemma : forall a b, ~ lex a b -> lex b a.\nProof.\n  intros.\n  assert (lex a b + lex b a).\n  apply lex_total.\n  induction H0.\n  contradict a0.\n  trivial.\n  trivial.\nQed.\n\nLemma lex_apprm : forall a b c, lex (a ++ b) (a ++ c) -> lex b c.\nProof.\n  induction a.\n  intros b c.\n  unfold app.\n  auto.\n  intros b c lx.\n  replace ((a :: a0) ++ b) with (a :: a0 ++ b) in lx.\n  replace ((a :: a0) ++ c) with (a :: a0 ++ c) in lx.\n  apply IHa.\n  apply (lex_cdr _ _ a).\n  apply lx.\n  auto.\n  auto.\nQed.", "meta": {"author": "dasuxullebt", "repo": "DampFnudeL", "sha": "6b0496d0ed5af23199bf0a03e04dbb9bb0373873", "save_path": "github-repos/coq/dasuxullebt-DampFnudeL", "path": "github-repos/coq/dasuxullebt-DampFnudeL/DampFnudeL-6b0496d0ed5af23199bf0a03e04dbb9bb0373873/Lex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.6734945086511461}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom Coq Require Import Bool.Bool.\nFrom PLF Require Import Maps.\nFrom PLF Require Import Smallstep.\nFrom PLF Require Import Stlc.\nFrom PLF Require MoreStlc.\nModule STLCTypes.\nExport STLC.\n\nFixpoint eqb_ty (T1 T2:ty) : bool :=\n  match T1,T2 with\n  | Bool, Bool =>\n      true\n  | Arrow T11 T12, Arrow T21 T22 =>\n      andb (eqb_ty T11 T21) (eqb_ty T12 T22)\n  | _,_ =>\n      false\n  end.\n\nLemma eqb_ty_refl : forall T1,\n  eqb_ty T1 T1 = true.\nProof.\n  intros T1. induction T1; simpl.\n    reflexivity.\n    rewrite IHT1_1. rewrite IHT1_2. reflexivity. Qed.\n\n\nLemma eqb_ty__eq : forall T1 T2,\n  eqb_ty T1 T2 = true -> T1 = T2.\nProof with auto.\n  intros T1. induction T1; intros T2 Hbeq; destruct T2; inversion Hbeq.\n  - (* T1=Bool *)\n    reflexivity.\n  - (* T1=Arrow T1_1 T1_2 *)\n    rewrite andb_true_iff in H0. inversion H0 as [Hbeq1 Hbeq2].\n    apply IHT1_1 in Hbeq1. apply IHT1_2 in Hbeq2. subst... Qed.\nEnd STLCTypes.\n\nModule FirstTry.\nImport STLCTypes.\nFixpoint type_check (Gamma : context) (t : tm) : option ty :=\n  match t with\n  | var x =>\n      Gamma x\n  | abs x T11 t12 =>\n      match type_check (update Gamma x T11) t12 with\n      | Some T12 => Some (Arrow T11 T12)\n      | _ => None\n      end\n  | app t1 t2 =>\n      match type_check Gamma t1, type_check Gamma t2 with\n      | Some (Arrow T11 T12),Some T2 =>\n          if eqb_ty T11 T2 then Some T12 else None\n      | _,_ => None\n      end\n  | tru =>\n      Some Bool\n  | fls =>\n      Some Bool\n  | test guard t f =>\n      match type_check Gamma guard with\n      | Some Bool =>\n          match type_check Gamma t, type_check Gamma f with\n          | Some T1, Some T2 =>\n              if eqb_ty T1 T2 then Some T1 else None\n          | _,_ => None\n          end\n      | _ => None\n      end\n  end.\nEnd FirstTry.\n\n\n(* Monadic way *)\n\nNotation \" x <- e1 ;; e2\" := (match e1 with\n                              | Some x => e2\n                              | None => None\n                              end)\n         (right associativity, at level 60).\n\nNotation \" 'return' e \"\n  := (Some e) (at level 60).\nNotation \" 'fail' \"\n  := None.\nModule STLCChecker.\n  Import STLCTypes.\n\nFixpoint type_check (Gamma : context) (t : tm) : option ty :=\n  match t with\n  | var x =>\n      match Gamma x with\n      | Some T => return T\n      | None => fail\n      end\n  | abs x T11 t12 =>\n      T12 <- type_check (update Gamma x T11) t12 ;;\n      return (Arrow T11 T12)\n  | app t1 t2 =>\n      T1 <- type_check Gamma t1 ;;\n      T2 <- type_check Gamma t2 ;;\n      match T1 with \n      | Arrow T11 T12 =>\n          if eqb_ty T11 T2 then return T12 else fail\n      | _ => fail\n      end\n  | tru =>\n      return Bool\n  | fls =>\n      return Bool\n  | test guard t1 t2 =>\n      Tguard <- type_check Gamma guard ;;\n      T1 <- type_check Gamma t1 ;;\n      T2 <- type_check Gamma t2 ;;\n      match Tguard with\n      | Bool =>\n          if eqb_ty T1 T2 then return T1 else fail\n      | _ => fail\n      end\n  end.\n\nTheorem type_checking_sound : forall Gamma t T,\n  type_check Gamma t = Some T -> has_type Gamma t T.\nProof with eauto.\n  intros Gamma t. generalize dependent Gamma.\n  induction t; intros Gamma T Htc; inversion Htc.\n  - (* var *) rename s into x. destruct (Gamma x) eqn:H.\n    rename t into T'. inversion H0. subst. eauto. solve_by_invert.\n  - (* app *)\n    remember (type_check Gamma t1) as TO1.\n    destruct TO1 as [T1|]; try solve_by_invert;\n    destruct T1 as [|T11 T12]; try solve_by_invert; \n    remember (type_check Gamma t2) as TO2;\n    destruct TO2 as [T2|]; try solve_by_invert.\n    destruct (eqb_ty T11 T2) eqn: Heqb.\n    apply eqb_ty__eq in Heqb.\n    inversion H0; subst...\n    inversion H0.\n  - (* abs *)\n    rename s into x. rename t into T1.\n    remember (update Gamma x T1) as G'.\n    remember (type_check G' t0) as TO2.\n    destruct TO2; try solve_by_invert.\n    inversion H0; subst...\n  - (* tru *) eauto.\n  - (* fls *) eauto.\n  - (* test *)\n    remember (type_check Gamma t1) as TOc.\n    remember (type_check Gamma t2) as TO1.\n    remember (type_check Gamma t3) as TO2.\n    destruct TOc as [Tc|]; try solve_by_invert.\n    destruct Tc; try solve_by_invert;\n    destruct TO1 as [T1|]; try solve_by_invert;\n    destruct TO2 as [T2|]; try solve_by_invert.\n    destruct (eqb_ty T1 T2) eqn:Heqb;\n    try solve_by_invert.\n    apply eqb_ty__eq in Heqb.\n    inversion H0. subst. subst...\nQed.\n\nTheorem type_checking_complete : forall Gamma t T,\n  has_type Gamma t T -> type_check Gamma t = Some T.\nProof with auto.\n  intros Gamma t T Hty.\n  induction Hty; simpl.\n  - (* T_Var *) destruct (Gamma x0) eqn:H0; assumption.\n  - (* T_Abs *) rewrite IHHty...\n  - (* T_App *)\n    rewrite IHHty1. rewrite IHHty2.\n    rewrite (eqb_ty_refl T11)...\n  - (* T_True *) eauto.\n  - (* T_False *) eauto.\n  - (* T_If *) rewrite IHHty1. rewrite IHHty2.\n    rewrite IHHty3. rewrite (eqb_ty_refl T)...\nQed.\n\nEnd STLCChecker.\n\n\nModule TypecheckerExtensions.\n\nImport MoreStlc.\nImport STLCExtended.\nFixpoint eqb_ty (T1 T2 : ty) : bool :=\n  match T1,T2 with\n  | Nat, Nat =>\n      true\n  | Unit, Unit =>\n      true\n  | Arrow T11 T12, Arrow T21 T22 =>\n      andb (eqb_ty T11 T21) (eqb_ty T12 T22)\n  | Prod T11 T12, Prod T21 T22 =>\n      andb (eqb_ty T11 T21) (eqb_ty T12 T22)\n  | Sum T11 T12, Sum T21 T22 =>\n      andb (eqb_ty T11 T21) (eqb_ty T12 T22)\n  | List T11, List T21 =>\n      eqb_ty T11 T21\n  | _,_ =>\n      false\n  end.\nLemma eqb_ty_refl : forall T1,\n  eqb_ty T1 T1 = true.\nProof.\n  intros T1.\n  induction T1; simpl;\n    try reflexivity;\n    try (rewrite IHT1_1; rewrite IHT1_2; reflexivity);\n    try (rewrite IHT1; reflexivity). Qed.\nLemma eqb_ty__eq : forall T1 T2,\n  eqb_ty T1 T2 = true -> T1 = T2.\nProof.\n  intros T1.\n  induction T1; intros T2 Hbeq; destruct T2; inversion Hbeq;\n    try reflexivity;\n    try (rewrite andb_true_iff in H0; inversion H0 as [Hbeq1 Hbeq2];\n         apply IHT1_1 in Hbeq1; apply IHT1_2 in Hbeq2; subst; auto);\n    try (apply IHT1 in Hbeq; subst; auto).\n Qed.\nFixpoint type_check (Gamma : context) (t : tm) : option ty :=\n  match t with\n  | var x =>\n      match Gamma x with\n      | Some T => return T\n      | None => fail\n      end\n  | abs x1 T1 t2 =>\n      T2 <- type_check (update Gamma x1 T1) t2 ;;\n      return (Arrow T1 T2)\n  | app t1 t2 =>\n      T1 <- type_check Gamma t1 ;;\n      T2 <- type_check Gamma t2 ;;\n      match T1 with \n      | Arrow T11 T12 =>\n          if eqb_ty T11 T2 then return T12 else fail\n      | _ => fail\n      end\n  | const _ =>\n      return Nat\n  | scc t1 =>\n      T1 <- type_check Gamma t1 ;;\n      match T1 with \n      | Nat => return Nat\n      | _ => fail\n      end\n  | prd t1 =>\n      T1 <- type_check Gamma t1 ;;\n      match T1 with \n      | Nat => return Nat\n      | _ => fail\n      end\n  | mlt t1 t2 =>\n      T1 <- type_check Gamma t1 ;;\n      T2 <- type_check Gamma t2 ;;\n      match T1, T2 with\n      | Nat, Nat => return Nat\n      | _,_ => fail\n      end\n  | test0 guard t f =>\n      Tguard <- type_check Gamma guard ;;\n      T1 <- type_check Gamma t ;;\n      T2 <- type_check Gamma f ;;\n      match Tguard with\n      | Nat => if eqb_ty T1 T2 then return T1 else fail\n      | _ => fail\n      end\n\n  (* Complete the following cases. *)\n  (* sums *)\n  | tinl Tr v =>\n      Tl <- type_check Gamma v ;;\n      return (Sum Tl Tr)\n  | tinr Tl v =>\n      Tr <- type_check Gamma v ;;\n      return (Sum Tl Tr)\n  | tcase t0 y1 t1 y2 t2 =>\n      Ts <- type_check Gamma t0 ;;\n      match Ts with\n      | Sum T1 T2 =>\n          T11 <- type_check (y1 |-> T1; Gamma) t1 ;;\n          T21 <- type_check (y2 |-> T2; Gamma) t2 ;;\n          if eqb_ty T11 T21 then return T11 else fail\n      | _ => fail\n      end\n  (* lists (the tlcase is given for free) *)\n  | tnil T => return (List T)\n  | tcons t1 t2 =>\n      T1 <- type_check Gamma t1 ;;\n      Tl <- type_check Gamma t2 ;;\n      match Tl with\n      | List T2 =>\n          if eqb_ty T1 T2 then return (List T1) else fail\n      | _ => fail\n      end\n  | tlcase t0 t1 x21 x22 t2 =>\n      match type_check Gamma t0 with\n      | Some (List T) =>\n          match type_check Gamma t1,\n                type_check (update (update Gamma x22 (List T)) x21 T) t2 with\n          | Some T1', Some T2' =>\n              if eqb_ty T1' T2' then Some T1' else None\n          | _,_ => None\n          end\n      | _ => None\n      end\n  (* unit *)\n  | unit => return Unit\n  (* pairs *)\n  | pair t1 t2 =>\n      T1 <- type_check Gamma t1 ;;\n      T2 <- type_check Gamma t2 ;;\n      return (Prod T1 T2)\n  | fst t1 =>\n      Tp <- type_check Gamma t1 ;;\n      match Tp with\n      | Prod T11 T12 => return T11\n      | _ => fail\n      end\n  | snd t1 =>\n      Tp <- type_check Gamma t1 ;;\n      match Tp with\n      | Prod T11 T12 => return T12\n      | _ => fail\n      end\n  (* let *)\n  | tlet x t1 t2 =>\n      T1 <- type_check Gamma t1 ;;\n      T2 <- type_check (x |-> T1;Gamma) t2 ;;\n      return T2\n  (* fix *)\n  | tfix t1 =>\n      Tf <- type_check Gamma t1 ;;\n      match Tf with (* pattern match can't match sameness of T1 T2*)\n      | Arrow T1 T2 =>\n          if eqb_ty T1 T2 then return T1 else fail\n      | _ => fail\n      end\n  end.\n\nLtac invert_typecheck Gamma t T :=\n  remember (type_check Gamma t) as TO;\n  destruct TO as [T|]; \n  try solve_by_invert; try (inversion H0; eauto); try (subst; eauto).\nLtac analyze T T1 T2 :=\n  destruct T as [T1 T2| |T1 T2|T1| |T1 T2]; try solve_by_invert.\nLtac fully_invert_typecheck Gamma t T T1 T2 :=\n  let TX := fresh T in\n  remember (type_check Gamma t) as TO;\n  destruct TO as [TX|]; try solve_by_invert;\n  destruct TX as [T1 T2| |T1 T2|T1| |T1 T2];\n  try solve_by_invert; try (inversion H0; eauto); try (subst; eauto).\nLtac case_equality S T :=\n  destruct (eqb_ty S T) eqn: Heqb;\n  inversion H0; apply eqb_ty__eq in Heqb; subst; subst; eauto.\nTheorem type_checking_sound : forall Gamma t T,\n  type_check Gamma t = Some T -> has_type Gamma t T.\nProof with eauto.\n  intros Gamma t. generalize dependent Gamma.\n  induction t; intros Gamma T Htc; inversion Htc.\n  - (* var *) rename s into x. destruct (Gamma x) eqn:H.\n    rename t into T'. inversion H0. subst. eauto. solve_by_invert.\n  - (* app *)\n    invert_typecheck Gamma t1 T1.\n    invert_typecheck Gamma t2 T2.\n    analyze T1 T11 T12.\n    case_equality T11 T2.\n  - (* abs *)\n    rename s into x. rename t into T1.\n    remember (update Gamma x T1) as Gamma'.\n    invert_typecheck Gamma' t0 T0.\n  - (* const *) eauto.\n  - (* scc *)\n    rename t into t1.\n    fully_invert_typecheck Gamma t1 T1 T11 T12.\n  - (* prd *)\n    rename t into t1.\n    fully_invert_typecheck Gamma t1 T1 T11 T12.\n  - (* mlt *)\n    invert_typecheck Gamma t1 T1.\n    invert_typecheck Gamma t2 T2.\n    analyze T1 T11 T12; analyze T2 T21 T22.\n    inversion H0. subst. eauto.\n  - (* test0 *)\n    invert_typecheck Gamma t1 T1.\n    invert_typecheck Gamma t2 T2.\n    invert_typecheck Gamma t3 T3.\n    destruct T1; try solve_by_invert.\n    case_equality T2 T3.\n  - (* tinl *)\n    invert_typecheck Gamma t0 Tl.\n  - (* tinr *)\n    invert_typecheck Gamma t0 Tr.\n  - (* tcase *)\n    fully_invert_typecheck Gamma t1 T1 T11 T12.\n    invert_typecheck (s |-> T11; Gamma) t2 T13.\n    invert_typecheck (s0 |-> T12; Gamma) t3 T21.\n    case_equality T13 T21.\n  - (* tnil *)\n    auto.\n  - (* tcons *)\n    invert_typecheck Gamma t1 T1.\n    invert_typecheck Gamma t2 T2.\n    destruct T2; try solve_by_invert.\n    case_equality T1 T2.\n  - (* tlcase *)\n    rename s into x31. rename s0 into x32.\n    fully_invert_typecheck Gamma t1 T1 T11 T12.\n    invert_typecheck Gamma t2 T2.\n    remember (update (update Gamma x32 (List T11)) x31 T11) as Gamma'2.\n    invert_typecheck Gamma'2 t3 T3.\n    case_equality T2 T3.\n  - (* tunit *)\n    auto.\n  - (* pair *)\n    invert_typecheck Gamma t1 T1.\n    invert_typecheck Gamma t2 T2.\n  - (* fst *)\n    invert_typecheck Gamma t Tp.\n    analyze Tp T11 T12.\n    inversion H0. subst. eauto.\n  - (* snd *)\n    invert_typecheck Gamma t Tp.\n    analyze Tp T11 T12.\n    inversion H0; subst. eauto.\n  - (* tlet *)\n    invert_typecheck Gamma t1 T1.\n    remember (s |-> T1; Gamma) as Gamma2.\n    invert_typecheck Gamma2 t2 T2.\n  - (* tfix *)\n    invert_typecheck Gamma t Tf.\n    analyze Tf T1 T2.\n    case_equality T1 T2.\nQed.\n\nTheorem type_checking_complete : forall Gamma t T,\n  has_type Gamma t T -> type_check Gamma t = Some T.\nProof.\n  intros Gamma t T Hty.\n  induction Hty; simpl;\n    try (rewrite IHHty);\n    try (rewrite IHHty1);\n    try (rewrite IHHty2);\n    try (rewrite IHHty3);\n    try (rewrite (eqb_ty_refl T)); \n    try (rewrite (eqb_ty_refl T1)); \n    try (rewrite (eqb_ty_refl T2)); \n    eauto.\n  - destruct (Gamma x); try solve_by_invert. eauto.\nQed. (* ... and uncomment this one *)\nEnd TypecheckerExtensions.\n\n\n", "meta": {"author": "StarGazerM", "repo": "my-foolish-code", "sha": "2991997f9be4523bf190ef4143df8b0d89e528cf", "save_path": "github-repos/coq/StarGazerM-my-foolish-code", "path": "github-repos/coq/StarGazerM-my-foolish-code/my-foolish-code-2991997f9be4523bf190ef4143df8b0d89e528cf/plf/Typechecking.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7905303112671295, "lm_q1q2_score": 0.6734945077817934}}
{"text": "Theorem Disjunctive_syllogism : \nforall (P Q : Prop), (P \\/ Q) -> ~P -> Q.\nunfold not.\nProof.\n  intros.\n  destruct H.\n  destruct H0.\n  apply H.\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/1/kadai1_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242132, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6734898361105515}}
{"text": "Require Import List.\nImport ListNotations.\n\nRequire Import eq.\nRequire Import utils.\nRequire Import identity.\nRequire Import composition.\nRequire Import injective.\nRequire Import map.\nRequire Import incl.\nRequire Import term.\nRequire Import var.\nRequire Import inj_on_list.\nRequire Import permute.\nRequire Import inj_on_term.\nRequire Import remove.\nRequire Import vmap.\nRequire Import swap.\nRequire Import free.\nRequire Import adpair.\n\n(* This inductive predicate defines alpha-equivalence.          *)\n(* There are four ways of establishing alpha-equivalence:       *)\n(* 1. Given a variable x:v, we always have x ~ x.               *)\n(* 2. t1 ~ t1' and t2 ~ t2' implies t1 t2 ~ t1' t2'             *)\n(* 3. t1 ~ t1' implies Lam x t1 ~ Lam x t1'                     *)\n(* 4. The final and most interesting way relies on [x:y]:       *)\n(* In order to establish the equivalence Lam x t1 ~ Lam y t1'   *)\n(* in the case when x <> y, we need to ensure that y is not     *)\n(* a free variable of t1, and furthermore that t1' ~ t1[x:y]    *)\n(* i.e. that t1' is equivalent to t1 after x and y have been    *)\n(* exchanged for one another. Note that we cannot do away with  *)\n(* the third constructor (by removing condition x <> y in 4.)   *)\n(* Lam x (Var x) ~ Lam x (Var x) cannot be proven simply by     *)\n(* taking x = y in 4. because of the requirement that y not     *)\n(* be a free variable of t1.                         *)\n(*                                                              *)\n(* The definition presented here relies on the permutation      *)\n(* function [x:y] (which permutes x and y while leaving         *)\n(* everything else unchanged). This choice has two benefits:    *)\n(* firstly, [x:y] is an injective function (in fact it is a     *)\n(* bijection with itself as inverse), which is not the case     *)\n(* of [y/x] (which simply replaces x by y). This property       *)\n(* facilitates many of the formal developments. Secondly,       *)\n(* the choice of [x:y] leads to the condition 'y not a free     *)\n(* variable of t1', whereas [y/x] would require the condition   *)\n(* 'y not a variable of t1' or 'y be a variable which can be    *)\n(* substituted for x in t1 without variable capture', and       *)\n(* these conditions make it compulsory to have an infinite      *)\n(* supply of variables. In the extreme case when the variable   *)\n(* type v has only two instances x and y, the usual approach    *)\n(* based on [y/x] makes it impossible to prove the alpha-equi   *)\n(* valence of 'Lam x (Lam y (x y))' and 'Lam y (Lam x (y x))':  *)\n(* When faced with Lam y (x y), the only variable which we      *)\n(* can substitute for x is the variable y, but this would       *)\n(* lead to variable capture, whereas using the permutation      *)\n(* [x:y] (note that y is not free in Lam y (x y)), we obtain    *)\n(* Lam x (y x) very naturally. So the definition below allows   *)\n(* for the development of the theory with finite variable types *)\n\n(* The alpha-equivalence t ~ t' is expressed as -alpha p t t'-  *)\n(* which requires an additional argument 'p', namely a proof    *)\n(* that the variable type v has decidable equality. This 'p'    *)\n(* is needed because it is required by the notion of free       *)\n(* variable on which alpha-equivalence relies. The argument p   *)\n(* cannot be made implicit, because it cannot be inferred by    *)\n(* the knowledge of terms t and t' (unlike v which can be       *)\n(* inferred). Hence we are stuck having to write alpha p t t'   *)\n(* rather than just alpha t t'                                  *)\n\nInductive alpha (v:Type) (p:Eq v) : P v -> P v -> Prop :=\n| AVar  : forall (x:v), alpha v p (Var x) (Var x)\n\n| AApp  : forall (t1 t1' t2 t2':P v), \n    alpha v p t1 t1' -> \n    alpha v p t2 t2' -> \n    alpha v p (App t1 t2) (App t1' t2')\n\n| ALam1 :forall (x:v) (t1 t1':P v), \n    alpha v p t1 t1' -> \n    alpha v p (Lam x t1) (Lam x t1') \n\n| ALam2 : forall (x y:v) (t1 t1':P v),\n    x <> y -> \n    ~In y (Fr p t1) ->                  (* y not free in t1     *) \n    alpha v p t1' (swap p x y t1) ->    (* t1' ~ t1[x:y]        *)\n    alpha v p (Lam x t1) (Lam y t1')    (* Lam x t1 ~ Lam y t1' *)\n.\n\nArguments alpha {v} _ _ _.\n\n(* alpha-equivalent terms have the same free variables.         *)\n(* In fact, this equality holds as lists, not just as sets.     *)\n\nLemma alpha_free : forall (v:Type) (p:Eq v) (t t':P v),\n    alpha p t t' -> Fr p t = Fr p t'.\nProof.\n    intros v p t t' H.\n    induction H.\n    - reflexivity.\n    - simpl.\n        assert (Fr p t1 = Fr p t1') as E1. { assumption. }\n        assert (Fr p t2 = Fr p t2') as E2. { assumption. }\n        rewrite E1, E2. reflexivity.\n    - simpl.\n        assert (Fr p t1 = Fr p t1') as E1. { assumption. }\n        rewrite E1. reflexivity.\n    - simpl. assert (Fr p t1' = Fr p (swap p x y t1)) as E. { assumption. }\n      rewrite E. unfold swap. rewrite (free_vmap_inj v v p p).\n      remember (permute p x y) as f eqn:F.\n      assert (f x = y) as Fx. { rewrite F. apply permute_x. }\n      rewrite <- Fx. rewrite (remove_inj2 v v p p).\n        + symmetry. apply map_invariant. \n            { intros u Hu. rewrite F. apply permute_not_xy.\n                { intros H'. rewrite H' in Hu. revert Hu. apply remove_In. }\n                { intros H'. rewrite H' in Hu. apply H0.\n                    apply (remove_incl v p x). assumption.\n                }\n            }\n        + apply inj_is_inj_on_list. rewrite F. apply permute_injective.\n        + apply inj_is_inj_on_list. apply permute_injective.\nQed.\n\n(* two alpha-equivalent terms are still alpha-equivalent after  *)\n(* injective variable renaming                                  *)\n\nLemma alpha_injective : forall (v w:Type) (p:Eq v) (q:Eq w) (t t':P v) (f:v -> w),\n    injective f ->                      \n    alpha p t t' ->                     (* t ~ t'               *)          \n    alpha q (vmap f t) (vmap f t').     (* f t ~ f t'           *)\nProof.\n    intros v w p q t t' f I H. induction H; simpl.\n    - constructor.\n    - constructor; assumption.\n    - constructor; assumption.\n    - constructor.\n        + intros H'. apply H. apply I. assumption.\n        + rewrite (free_vmap_inj v w p q).\n            { apply injective_not_in.\n                { apply inj_is_inj_on_list. assumption. }\n                { assumption. }\n            }\n            { apply inj_is_inj_on_list. assumption. }\n        + rewrite <- (swap_inj v w p q); assumption.\nQed.\n\n(* A simple application of the previous lemma                   *)\nLemma alpha_injective_swap : forall (v:Type) (p:Eq v) (x y:v) (t t':P v),\n    alpha p t t' <-> alpha p (swap p x y t) (swap p x y t').\nProof.\n    intros v p x y t t'. split; intros H.\n    - unfold swap. apply alpha_injective with p.\n        + apply permute_injective.\n        + assumption.\n    - rewrite <- (swap_involution v p x y t), <- (swap_involution v p x y t').\n        + unfold swap at 1. unfold swap at 2. apply alpha_injective with p.\n            { apply permute_injective. }\n            { assumption. }\nQed.\n\n\n(* alpha-equivalence is a reflexive relation                    *)\n\nLemma alpha_refl : forall (v:Type) (p:Eq v) (t:P v), alpha p t t.\nProof.\n    intros v p t.\n    induction t.\n    - constructor.\n    - constructor; assumption.\n    - constructor; assumption.\nQed.\n\n\n(* alpha-equivalence is a symmetric relation                    *)\n\nLemma alpha_sym : forall (v:Type) (p:Eq v) (t t':P v), \n    alpha p t t' -> alpha p t' t.\nProof.\n    intros v p t t' H. \n    induction H.\n    - constructor.\n    - constructor; assumption.\n    - constructor; assumption.\n    - constructor.\n        + intros E. apply H. symmetry. assumption.\n        + assert (Fr p t1' = Fr p (swap p x y t1)) as H'.\n            { apply alpha_free. assumption. }\n          rewrite H'. clear H'. unfold swap.\n          remember (permute p x y) as f eqn:F.\n          assert (Fr p (vmap f t1) = map f (Fr p t1)) as H'.\n            { apply free_vmap_inj. apply inj_is_inj_on_list. \n              rewrite F. apply permute_injective.\n            }\n          rewrite H'. clear H'.\n          assert (f y = x) as H'.\n            { rewrite F. apply permute_y. }\n          rewrite <- H'. clear H'.\n          apply injective_not_in.\n            { apply inj_is_inj_on_list. rewrite F. apply permute_injective. }\n            { assumption. }\n        + rewrite swap_commute. \n          rewrite <- (swap_involution v p x y t1).\n          apply (alpha_injective v v p p).\n            { apply permute_injective. }\n            { assumption. }\nQed.\n\n\n(* This is motivated by and constitues a generalization of:     *)\n(* t ~ t'[x:y]  <=>   t[x:y] ~ t'                               *)\n(* We are now stating that:                                     *)\n(* t ~ f t'     <=>   g t ~  t'                                 *)\n(* provided f and g are inverses of each other.                 *) \n\nLemma alpha_swap_gen : forall (v:Type) (p:Eq v) (t t':P v) (f g:v -> v),\n    (forall x, g (f x) = x) -> \n    (forall x, f (g x) = x) ->\n    alpha p t (vmap f t') <-> alpha p (vmap g t) t'.\nProof.\n    intros v p t t' f g GF FG. split; intros H'.\n    - rewrite <- (vmap_id v t'). rewrite (vmap_eq v v id (g;f) t').\n        + rewrite vmap_comp. apply alpha_injective with p.\n            { intros x y Hxy. rewrite <- (FG x), <- (FG y), Hxy. reflexivity. }\n            { assumption. }\n        + intros x _. symmetry. apply GF.\n    - rewrite <- (vmap_id v t). rewrite (vmap_eq v v id (f;g) t).\n        + rewrite vmap_comp. apply alpha_injective with p.\n            { intros x y Hxy. rewrite <- (GF x), <- (GF y), Hxy. reflexivity. }\n            { assumption. }\n        + intros x _. symmetry. apply FG.\nQed.\n\n(* We apply the previous lemma to the permutation [x:y]         *)\n\nLemma alpha_swap : forall (v:Type) (p:Eq v) (x y:v) (t t':P v),\n    alpha p t (swap p x y t') <-> alpha p (swap p x y t) t'.\nProof.\n    intros v p x y t t'. unfold swap. apply alpha_swap_gen;\n    intros z; apply permute_involution.\nQed.\n\n(* Simple convenience wrapper                                   *)\n\nLemma alpha_swap_gen' : forall (v:Type) (p:Eq v) (t t' s:P v) (f g:v -> v),\n    adpair p s f g -> \n    alpha p t (vmap f t') <-> alpha p (vmap g t) t'.\nProof. \n    intros v p t t' s f g [GF FG _]. \n    apply alpha_swap_gen; assumption. \nQed.\n\n\n(* If t[x:y] ~ t' then x is not a free variable of t'           *)\n(* if and only if y is not a free variable of t.                *)\n\nLemma alpha_free_swap : forall (v:Type) (p:Eq v) (x y:v) (t t':P v),\n    alpha p (swap p x y t) t' -> \n    ~In y (Fr p t) <-> ~In x (Fr p t'). \nProof.\n    intros v p x y t t' H. split; intros H'.\n    - rewrite (alpha_free v p t' (swap p x y t)).\n        + apply free_swap. assumption.\n        + apply alpha_sym. assumption.\n    - apply alpha_swap in H. rewrite (alpha_free v p t (swap p x y t')).\n        + rewrite swap_commute. apply free_swap. assumption.\n        + assumption.\nQed.\n\n(* This is a very difficult technical lemma, needed to prove    *)\n(* that the alpha-equivalence relation is transitive.           *)\n(* Whenever a function f : v -> v is such that f is injective   *)\n(* and f does not change the free variables of a term t, we can *)\n(* easily believe that 'f t' should be alpha-equivalent to t    *)\n(* i.e. f t ~ t. We have used stronger assumptions here by      *)\n(* assuming that f has an inverse g (so the pair (f,g) is an    *)\n(* 'admissible pair for t'. Furthermore, the lemma proves       *)\n(* a conclusion which is stronger than t ~ f t, namely that     *)\n(* s ~ t => s ~ f t. This distinction will prove important      *)\n(* when establishing the transitivity of alpha-equivalence.     *)\n(* This lemma is only needed in the particular case when        *)\n(* f = [x:y] = g, i.e. we need the implication:                 *)\n(* s ~ t => s ~ t[x:y]                                          *)\n(* whenever it is the case that x,y are not free in t           *)\n(* However, like very often in induction proofs, it is          *)\n(* necessary to strengthen the induction hypothesis, with       *)\n(* general f and g, rather than [x:y]                           *)\n\n\nLemma alpha_adpair : forall (v:Type) (p:Eq v) (f g:v -> v) (t s:P v),\n    adpair p t f g -> alpha p s t -> alpha p s (vmap f t).\nProof.\n    intros v p f g t s A H. revert f g A.\n    induction H; intros f g A; simpl.\n    - rewrite (adpair_invl v p (Var x) f g).\n        + constructor.\n        + assumption.\n        + simpl. left. reflexivity.\n    - constructor.\n        + apply IHalpha1 with g. apply adpair_Appl with t2'. assumption.\n        + apply IHalpha2 with g. apply adpair_Appr with t1'. assumption.\n    - remember (f x) as y eqn:Y. destruct (p y x) as [Hyx|Hyx].\n        + rewrite Hyx. constructor. apply IHalpha with g. constructor.\n            { intros z. apply (adpair_gf v p) with (Lam x t1'). assumption. }\n            { intros z. apply (adpair_fg v p) with (Lam x t1'). assumption. }\n            { intros z Hz. destruct (p x z) as [Hxz|Hxz]; subst.\n                { assumption. }\n                { apply (adpair_invl v p (Lam x t1')) with g.\n                    { assumption. }\n                    { simpl. apply remove_In2; assumption. }\n                }\n            }\n        + constructor.\n            { apply neq_sym. assumption. }\n            { intros H'. apply Hyx. assert (injective f) as I. \n                { apply (adpair_injl v p (Lam x t1')) with g. assumption. }\n              apply I. rewrite <- Y.\n              apply (adpair_invl v p (Lam x t1')) with g.\n                { assumption. }\n                { simpl. apply remove_In2.\n                    { apply neq_sym. assumption. }\n                    { rewrite (alpha_free v p t1' t1).\n                        { assumption. }\n                        { apply alpha_sym. assumption. }\n                    }\n                }\n            }\n            { apply alpha_sym. apply alpha_swap. unfold swap.\n              rewrite <- vmap_comp. apply IHalpha with (g; permute p x y).\n              constructor.\n                { intros z. unfold comp. rewrite permute_involution.\n                  apply (adpair_gf v p (Lam x t1')). assumption.\n                }\n                { intros z. unfold comp.\n                    rewrite (adpair_fg v p (Lam x t1') f g (permute p x y z)).\n                        { apply permute_involution. }\n                        { assumption. }\n                }\n                { intros z Hz. destruct (p z x) as [Hzx|Hzx]; unfold comp.\n                    { rewrite Hzx. rewrite <- Y. apply permute_y. }\n                    { assert (f z = z) as Z.\n                        { apply (adpair_invl v p (Lam x t1')) with g.\n                            { assumption. }\n                            { simpl. apply remove_In2.\n                                { apply neq_sym. assumption. }\n                                { assumption. }\n                            }\n                        }\n                      rewrite Z. apply permute_not_xy.\n                        { assumption. }\n                        { intros H'. apply Hzx. assert (injective f) as I.\n                            { apply (adpair_injl v p (Lam x t1')) with g. \n                              assumption. \n                            }\n                          apply I. rewrite <- Y. rewrite <- H'.\n                          apply (adpair_invl v p (Lam x t1')) with g.\n                            { assumption. }\n                            { simpl. apply remove_In2.\n                                { apply neq_sym. assumption. }\n                                { assumption. }\n                            }\n                        }\n                    }\n                }\n            }\n    - remember (f y) as z eqn:Z. destruct (p x z) as [Hxz|Hxz].\n        + rewrite <- Hxz. constructor. \n          rewrite (alpha_swap_gen' v p t1 t1' (Lam y t1') f g).\n            { apply alpha_sym.\n              rewrite <- (swap_involution v p x y t1).\n              unfold swap at 1.\n              rewrite <- vmap_comp.\n              apply IHalpha with (permute p x y ; f).\n              constructor; generalize A; intros [GF FG _].\n                { intros u. unfold comp. rewrite FG. apply permute_involution. }\n                { intros u. unfold comp. rewrite permute_involution. apply GF. }\n                { intros u Hu. unfold comp. destruct (p u y) as [Huy|Huy].\n                    { rewrite Huy, permute_y, Hxz, Z. apply GF. }\n                    { apply adpair_sym in A. generalize A. intros [_ _ FR].\n                      rewrite permute_not_xy.\n                        { apply FR. simpl. apply remove_In2.\n                            { apply neq_sym. assumption. }\n                            { rewrite (alpha_free v p t1' (swap p x y t1));\n                              assumption.\n                            }\n                        }\n                        { intros Hux. rewrite (free_swap v p x y t1) in H0.\n                          apply H0. rewrite <- Hux at 1. assumption.\n                        }\n                        { assumption. }\n                    }\n                }\n            }\n            { assumption. }\n        + constructor.\n            { assumption. }\n            { intros H'. apply adpair_sym in A. \n              generalize A. intros [FG GF FR]. assert (y = z) as Hyz.\n                { rewrite <- (GF y), <- Z. apply FR. simpl.\n                  apply remove_In2.\n                    { intros Hyz. apply H0. rewrite Hyz. assumption. }\n                    { rewrite (alpha_free v p t1' (swap p x y t1)).\n                        { rewrite free_permute, <- (permute_not_xy v p x y z).\n                            { apply incl_map. assumption. }\n                            { apply neq_sym. assumption. }\n                            { intros Hyz. apply H0. rewrite <- Hyz. assumption. } \n                        }\n                        { assumption. }\n                    } \n                }\n              apply H0. rewrite Hyz. assumption. \n            }\n            { apply alpha_sym. \n              apply (alpha_swap_gen v p (swap p x z t1) t1' f g);\n              generalize A; intros [GF FG _]. \n                { apply GF. }\n                { apply FG. }\n                { apply alpha_sym. \n                  rewrite <- (swap_involution v p x y t1). \n                  unfold swap at 1. rewrite <- vmap_comp. \n                  unfold swap at 1. rewrite <- vmap_comp.\n                  apply IHalpha with ((permute p x y); (permute p x z; f)).\n                  constructor.\n                  { intros u. unfold comp. rewrite FG. \n                    rewrite permute_involution, permute_involution.\n                    reflexivity.\n                  }\n                  { intros u. unfold comp.\n                    rewrite permute_involution, permute_involution, GF.\n                    reflexivity.\n                  }\n                  { intros u Hu. unfold comp. assert (u <> x) as Hux.\n                      { intros Hux. rewrite Hux in Hu. revert Hu.\n                        apply free_swap. assumption.\n                      }\n                    apply adpair_sym in A. generalize A. intros [_ _ FR].\n                    destruct (p u y) as [Huy|Huy].\n                        { rewrite Huy, permute_y, permute_x, Z. apply GF. }\n                        { rewrite permute_not_xy.\n                            { rewrite permute_not_xy; try (assumption).\n                                { apply FR. simpl. apply remove_In2.\n                                    { apply neq_sym. assumption. }\n                                    { rewrite (alpha_free v p t1' (swap p x y t1));\n                                      assumption.\n                                    }\n                                }\n                            } \n                            { rewrite permute_not_xy; assumption. }\n                            { rewrite permute_not_xy; try (assumption).\n                                { intros Huz. apply Huy. rewrite Huz.\n                                  symmetry. rewrite <- (GF y), <- Z.\n                                  apply FR. simpl. apply remove_In2.\n                                    { apply neq_sym. rewrite <- Huz. assumption. }\n                                    { rewrite (alpha_free v p t1' (swap p x y t1)).\n                                        { rewrite <- Huz. assumption. }\n                                        { assumption. }\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\nQed.\n\n\n                           \n\n(* Applying previous lemma in case when f = [x:y] = g, also     *)\n(* establishing equivalence rather than mere implication.       *)\n\nLemma alpha_adpair_swap : forall (v:Type) (p:Eq v) (x y:v) (t s:P v),\n    ~In x (Fr p t)  ->                      \n    ~In y (Fr p t)  ->                      \n    alpha p s t <-> alpha p s (swap p x y t).   \nProof.\n    intros v p x y t s Fx Fy. split; intro H; unfold swap.\n    - apply alpha_adpair with (permute p x y).\n        + constructor.\n            { intros z. apply permute_involution. }\n            { intros z. apply permute_involution. }\n            { intros z Hz. apply permute_not_xy.\n                { intros Hzx. apply Fx. rewrite <- Hzx. assumption. }\n                { intros Hzy. apply Fy. rewrite <- Hzy. assumption. }\n            }\n        + assumption.\n    - rewrite <- (swap_involution v p x y t). unfold swap at 1.\n      apply alpha_adpair with (permute p x y).\n        + constructor.\n            { intros z. apply permute_involution. }\n            { intros z. apply permute_involution. }\n            { intros z Hz. apply permute_not_xy.\n                { intros Hzx. revert Hz. rewrite Hzx. \n                  apply free_swap. assumption.\n                }\n                { intros Hzy. revert Hz. rewrite Hzy. rewrite swap_commute.\n                  apply free_swap. assumption.\n                }\n            }  \n        + assumption.\nQed.\n\n\n(* Attempting to prove the transitivity of alpha-equivalence    *)\n(* directly leads to the common problem of having an induction  *)\n(* hypothesis which is too weak to successfully complete an     *)\n(* induction proof. So we focus on the stronger result below.   *)\n(* The proof fundamentally relies on the alpha_adpair_swap      *)\n(* lemma, which itself relies on alpha_adpair.                  *)\n\nLemma alpha_tran_ : forall (v:Type) (p:Eq v) (t t' s: P v),\n    alpha p t t' -> alpha p t s <-> alpha p t' s.\nProof.\n    intros v p t t' s H. revert s.\n    induction H; intros s.\n    - split; intros H'; assumption.\n    - split; intros H'; inversion H'; constructor; subst.\n        + apply IHalpha1. assumption.\n        + apply IHalpha2. assumption.\n        + apply IHalpha1. assumption.\n        + apply IHalpha2. assumption.\n    - split; intros H'; inversion H'; constructor; subst.\n        + apply IHalpha. assumption.\n        + assumption.\n        + assert (Fr p t1' = Fr p t1) as F.\n            { apply alpha_free. apply IHalpha. apply alpha_refl. }\n          rewrite F. assumption.\n        + apply alpha_swap. apply alpha_sym. apply IHalpha.  \n          apply alpha_sym. apply alpha_swap. assumption.\n        + apply IHalpha. assumption.\n        + assumption.\n        + assert (Fr p t1 = Fr p t1') as F.\n            { apply alpha_free. apply IHalpha. apply alpha_refl. }\n          rewrite F. assumption.\n        + apply alpha_swap. apply alpha_sym. apply IHalpha.  \n          apply alpha_sym. apply alpha_swap. assumption.\n    - split; intros H'; inversion H'; subst.\n        + constructor.\n            { intros E. apply H. symmetry. assumption. }\n            { apply (alpha_free_swap v p x y t1 t1').\n                { apply IHalpha. apply alpha_refl. }\n                { assumption. }\n            }\n            { apply alpha_swap. apply alpha_sym. apply IHalpha.\n              rewrite (swap_commute v p y x). \n              apply (alpha_injective v v p p).\n                { apply permute_injective. }\n                { assumption. }\n            }\n\n        + rename y0 into z. destruct (p y z) as [Hyz|Hyz]; subst.\n            { constructor. apply IHalpha. apply alpha_sym. assumption. }\n            { constructor.\n                { assumption. }\n                { rewrite (alpha_free v p t1' (swap p x y t1)). \n                    { rewrite free_permute.\n                      rewrite <- (permute_not_xy v p x y z).\n                        { apply injective_not_in.\n                            { apply inj_is_inj_on_list.\n                              apply permute_injective.\n                            }\n                            { assumption. }\n                        }\n                        { intros E. apply H4. symmetry. assumption. }\n                        { intros E. apply Hyz. symmetry. assumption. }\n                    }\n                    { assumption. }\n                }\n                { rename t1'0 into t0. rename t1' into t2. \n                  apply alpha_swap. apply alpha_sym.\n                  apply IHalpha. apply alpha_swap.\n                  apply alpha_sym. apply (alpha_adpair_swap v p x y).\n                    { rewrite <- (permute_not_xy v p y z x) at 1.\n                        { rewrite free_permute. \n                          apply injective_not_in. \n                            { apply inj_is_inj_on_list. \n                              apply permute_injective.\n                            }\n                            { apply free_swap. assumption. } \n                        }\n                        { assumption. } \n                        { assumption. }\n                    }\n                    { apply free_swap.\n                      rewrite <- (permute_not_xy v p x y z) at 1.\n                        { rewrite free_permute. \n                          apply injective_not_in.\n                            { apply inj_is_inj_on_list. \n                              apply permute_injective. \n                            } \n                            { assumption. }\n                        }\n                        { apply neq_sym. assumption. }\n                        { apply neq_sym. assumption. }\n                    }\n                    { rewrite swap_thrice; assumption. }\n                }         \n            }\n        + constructor; try (assumption).\n          apply alpha_sym. apply IHalpha. assumption.\n        + rename y0 into z. destruct (p x z) as [Hxz|Hxz]; subst.\n            { constructor. rewrite <- (swap_involution v p z y t1).\n              apply alpha_swap, IHalpha, alpha_sym, alpha_swap.\n              rewrite swap_commute. assumption.\n            }\n            { constructor.\n                { assumption. }\n                { apply alpha_swap in H1.\n                  rewrite <- (alpha_free v p (swap p x y t1') t1).\n                    { rewrite free_permute.\n                      rewrite <- (permute_not_xy v p x y z).\n                        { apply injective_not_in.\n                            { apply inj_is_inj_on_list, permute_injective. }\n                            { assumption. }\n                        }\n                        { apply neq_sym. assumption. }\n                        { apply neq_sym. assumption. }\n                    }\n                   assumption.\n                }\n                { rename t1'0 into t0. rename t1' into t2. \n                  apply alpha_swap. rewrite swap_commute.\n                  apply (alpha_injective_swap v p x y).\n                  apply alpha_sym, IHalpha, alpha_sym.\n                  apply (alpha_adpair_swap v p z x).\n                    { assumption. }\n                    { rewrite (alpha_free v p t2 (swap p x y t1)).\n                        { apply (free_swap v p x y). assumption. }\n                        { assumption. }\n                    }\n                    { apply alpha_swap. rewrite swap_thrice.\n                        { apply alpha_swap. rewrite swap_commute. assumption. }\n                        { apply neq_sym. assumption. }\n                        { assumption. }\n                    }\n                }\n            }  \nQed.\n\n(* The alpha-equivalence relation is transitive                 *)\nLemma alpha_tran : forall (v:Type) (p:Eq v) (t1 t2 t3:P v),\n    alpha p t1 t2 -> alpha p t2 t3 -> alpha p t1 t3.\nProof.\n    intros v p t1 t2 t3 H12 H23. \n    apply (alpha_tran_ v p t1 t2 t3); 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/lam/alpha.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6734898324939373}}
{"text": "Require Import List.\nRequire Import Program.\n\nLemma exists_Forall2_fw A B (R : A -> B -> Prop) x1 l1 l2 : In x1 l1 -> Forall2 (fun x1 x2 => R x1 x2) l1 l2 ->\n    exists x2, R x1 x2 /\\ In x2 l2.\n  revert l2.\n  induction l1.\n    easy.\n  destruct l2.\n    easy.\n  intros.\n  dependent destruction H0.\n  destruct H.\n    exists b.\n    split.\n      rewrite <- H.\n      auto.\n    left.\n    auto.\n  destruct (IHl1 l2); auto.\n  exists x.\n  destruct H2.\n  split.\n    auto.\n  right.\n  auto.\nQed.\n\nLemma exists_Forall2_bw A B (R : A -> B -> Prop) x2 l1 l2 : In x2 l2 -> Forall2 (fun x1 x2 => R x1 x2) l1 l2 ->\n    exists x1, R x1 x2 /\\ In x1 l1.\n  revert l1.\n  induction l2.\n    easy.\n  destruct l1.\n    easy.\n  intros.\n  dependent destruction H0.\n  destruct H.\n    exists a0.\n    split.\n      rewrite <- H.\n      auto.\n    left.\n    auto.\n  destruct (IHl2 l1); auto.\n  exists x.\n  destruct H2.\n  split.\n    auto.\n  right.\n  auto.\nQed.\n\nLemma Forall2_map_com A B C D (R : C -> D -> Prop) (F1 : A -> C) (F2 : B -> D) l1 l2 :\n    Forall2 R (map F1 l1) (map F2 l2) <-> Forall2 (fun x1 x2 => R (F1 x1) (F2 x2)) l1 l2.\n  split; intro.\n    dependent induction H.\n      destruct l1; try easy.\n      destruct l2; try easy.\n    destruct l1; try easy.\n    destruct l2; try easy.\n    simplify_eq x1.\n    simplify_eq x.\n    intros.\n    apply Forall2_cons.\n      rewrite <- H1.\n      rewrite <- H3.\n      auto.\n    auto.\n  dependent induction H.\n    apply Forall2_nil.\n  apply Forall2_cons; auto.\nQed.\n\nLemma Forall2_self A (R : A -> A -> Prop) l : (forall x, In x l -> R x x) -> Forall2 (fun x1 x2 => R x1 x2) l l.\n  rewrite <- Forall_forall.\n  induction 1.\n    easy.\n  apply Forall2_cons; easy.\nQed.\n\nLemma Forall2_map A B C (R : B -> C -> Prop) (F1 : A -> B) (F2 : A -> C) l :\n    (forall x, In x l -> R (F1 x) (F2 x)) -> Forall2 R (map F1 l) (map F2 l).\n  rewrite <- Forall_forall.\n  intro.\n  dependent induction H.\n    apply Forall2_nil.\n  apply Forall2_cons; auto.\nQed.\n\nLemma repeat_app_com A (x : A) n1 n2 : repeat x n1 ++ repeat x n2 = repeat x (n1 + n2).\n  induction n1; auto.\n  simpl.\n  rewrite IHn1.\n  auto.\nQed.\n", "meta": {"author": "pparys", "repo": "ho-transform-sbs", "sha": "89420aee3129b19049c9134bf7b15eb819e80aa0", "save_path": "github-repos/coq/pparys-ho-transform-sbs", "path": "github-repos/coq/pparys-ho-transform-sbs/ho-transform-sbs-89420aee3129b19049c9134bf7b15eb819e80aa0/ListLemmata.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.8333246035907932, "lm_q1q2_score": 0.6733822904085732}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_congruencetransitive.\n\nSection Euclid.\n\nContext `{Ax1:euclidean_neutral}.\n\nLemma lemma_lessthancongruence2 : \n   forall A B C D E F, \n   Lt A B C D -> Cong A B E F ->\n   Lt E F C D.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists G, (BetS C G D /\\ Cong C G A B)) by (conclude_def Lt );destruct Tf as [G];spliter.\nassert (Cong C G E F) by (conclude lemma_congruencetransitive).\nassert (Lt E F C D) by (conclude_def Lt ).\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_lessthancongruence2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7718435083355188, "lm_q1q2_score": 0.673315663281958}}
{"text": "Require Import Coq.NArith.NArith.\nOpen Scope N_scope.\nRequire Import Frap.Frap.\nRequire Import Pset2.\nImport Pset2.Impl.\n\nNotation \"x !\" := (fact x) (at level 12, format \"x !\"). (* local in Pset2 *)\n\n(* This file demonstrates a number of useful Coq tactics.  Step though the\n   examples, and check Coq's reference manual or ask us in office hours if\n   you're confused about any of these tactics.\n\n   There are no exercises to complete in this file, just neat examples; feel\n   free to work on it at your pace over multiple psets and to refer to it at\n   later points; no need to go through it all at once.  *)\n\n(* The tactic we introduce in each example is underlined like this. *)\n                                             (********************)\n\nParameter whatever: Prop.\n\n(* ‘apply’ matches the conclusion of a theorem to the current goal, then\n   replaces it with one subgoal per premise of that theorem: *)\n\nGoal forall (P Q R: Prop) (H1: P) (H2: Q) (IH: P -> Q -> R), R.\nProof.\n  simplify.\n  apply IH.\n (********)\nAbort.\n\n(* Apply works with implications (`A -> B`) but also with equivalences, where\n   it tries to pick the right direction based on the goal: *)\nGoal forall (n m k: N), n = m.\nProof.\n  simplify.\n  Check N.mul_cancel_r.\n\n  (* Careful: apply only works if it's clear how the theorem applies to your goal: *)\n  Fail apply N.mul_cancel_r.\n  (* Here, Coq wants to know the value of ‘p’ before it can apply the lemma; so,\n     we use the ‘with’ for of ‘apply’ to supply it: *)\n  apply N.mul_cancel_r with (p := n - k + 1).\n (****)               (****)\nAbort.\n\n(* Apply also works in hypotheses, where it tuns premises into conclusions: *)\nGoal forall (n m k: N), n = m -> whatever.\nProof.\n  simplify.\n  apply N.mul_cancel_r with (p := n - k + 1) in H.\n (*****)              (****)                (**)\nAbort.\n\nGoal forall (n m k: N), n - k + 1 <> 0 -> n = m -> whatever.\nProof.\n  simplify.\n\n  (* Specifying parameters by hand is not always convenient, so we can ask Coq\n     to create placeholders instead, to be filled later: *)\n  eapply N.mul_cancel_r in H0.\n (******)              (**)\n  2: { (* This ‘2:’ notation means: operate on the second goal *)\n    apply H.\n  } (* … and the curly braces delimit a subproof. *)\nAbort.\n\nGoal forall (P Q R S: Prop), (P -> S) -> (R -> S) -> P \\/ Q \\/ R -> S.\nProof.\n  simplify.\n  cases H1. (* You are familiar with ‘cases’ from pset 1. *)\n (*****)\n  - apply H. apply H1.\n  - admit. (* ‘admit’ is just like ‘Admitted’ but for a single goal *)\n   (*****)\n  - apply H0. apply H1.\nFail Qed. (* But if you use ‘admit’, no ‘Qed’ for you! *)\nAdmitted.\n\n(* Here is a convenient pattern that you will be familiar with from math\n   classes.  It's called a “cut”.  We state an intermediate fact and prove it\n   as part of a larger proof. *)\n\nGoal forall (f : N -> N) (count : N)\n       (IHcount : forall i start : N, i < count ->\n                                 ith i (seq f count start) = f (start + i))\n       (i start : N)\n       (H : i < count + 1),\n  ith i (f start :: seq f count (start + 1)) = f (start + i).\nProof.\n  simplify.\n\n  (* ‘assert’ introduces the fact that we want to prove, then uses *)\n  assert (i = 0 \\/ 0 < i) as A. { (* the ‘as’ clause to name the resulting fact *)\n (******)                (**)\n    linear_arithmetic.          (* The proof of the lemma comes first. *)\n  }\n  cases A.                      (* Then we get to use the lemma itself. *)\n  - subst. (* ‘subst’ rewrites all equalities. *)\n   (*****)  (* or \"subst i\" for just one var *)\n    simplify. admit.\n  - (* Another assertion! This time we fit the whole proof in a ‘by’ clause. *)\n    assert (i = i - 1 + 1) as E by linear_arithmetic.\n   (******)                    (**)\n    rewrite E.\n    unfold_recurse ith (i - 1).\nAbort.\n\nGoal forall (n x0 k: N),\n    0 < k ->\n    k + 1 < n ->\n    n! = x0 * ((n - (k - 1))! * (k - 1)!) ->\n    whatever.\nProof.\n  intros n m.\n (******)\n  (* ‘simplify’ takes care of moving variables into the “context” above the\n     line, but ‘intros’ gives finer grained control and lets you name\n     hypotheses.  Users of Proof General with company-coq can type ‘intros!’ to\n     get names automatically inserted. *)\n  intros. (* A plain ‘intros’ takes care of all remaining variables. *)\n  (******)\n\n  (* Sometimes we want to say “a = b, so replace all ‘a’s with ‘b’s.”.  Replace\n     is the perfect tactic for these cases; it's like ‘assert’ followed by\n     ‘rewrite’. *)\n  replace (n - (k - 1)) with (n - k + 1) in H1 by linear_arithmetic.\n (*******)             (****)           (**)  (**)\n  (* \"in\" and \"by\" are optional *)\n  unfold_recurse fact (n - k).\nAbort.\n\nGoal forall (P Q R: Prop) (H0: Q) (x: N) (H: forall (a b: N), P -> Q -> a < b -> R), whatever.\nProof.\n  simplify.\n  (* Often you have a general hypothesis, and you want to make it more specific\n     to your case.  Then, ‘specialize’ is the tactic you want: *)\n  specialize H with (b := x).\n (**********) (****)\n  assert (3 < x) by admit.\n  specialize H with (2 := H0) (3 := H1).\nAbort.\n\nGoal forall (f : N -> N) (start : N),\n    f start = f (start + 0).\nProof.\n  simplify.\n\n  (* We have seen ‘apply’ earlier, which applies a theorem ending with an\n     implication to a complete goal.  ‘rewrite’ takes theorems ending in an\n     equality and replaces matching subterms of the goal according to that\n     equality: *)\n  rewrite N.add_0_r.\n (*******)\n  (* Options like \"with (a := 2)\", \"in H\", \"by tactic\" also work! *)\n  equality.\nAbort.\n\nGoal forall (f : N -> N) (start : N),\n    f start = f (start + 0).\nProof.\n  simplify.\n  (* Alternatively, sometimes, it helps to apply the principle that, if two\n     function arguments match, then the function calls themselves match: *)\n  f_equal.\n (*******)\n  linear_arithmetic.\nAbort.\n\nGoal forall (f : N -> N) (start : N),\n    f start = f (start + 0).\nProof.\n  simplify.\n  (* How many other ways can we find to deal with this theorem? *)\n  assert (start + 0 = start) as E by linear_arithmetic.\n  rewrite E.\nAbort.\n\nGoal forall (A B: Type) (f: A -> B) (a1 a2 a3: A),\n    Some a1 = Some a2 ->\n    Some a2 = Some a3 ->\n    f a3 = f a1.\nProof.\n  (* ‘simplify’ is a favorite of this class, which does all sorts of small goal\n     reorganization to make things more readable. *)\n  simplify.\n\n  (* ‘invert’ is another favorite: it “replaces hypothesis H with other facts that can be deduced from the structure of H's statement”.\n\n     Specifically, it looks at the structure of the arguments passed to the\n     constructor of inductive types appearing in H and deduces equalities from\n     that and then substitutes the equalities.  It's also particularly useful\n     for inductive ‘Prop’s, which we will see later in this class. *)\n  invert H. (* Watch what happens carefully in this example *)\n (******)\n  invert H0.\n  equality.\nAbort.\n\nGoal forall (A B: Type) (f: A -> B) (a1 a2 a3: A),\n    Some a1 = Some a2 ->\n    Some a2 = Some a3 ->\n    f a3 = f a1.\nProof.\n  simplify.\n  equality. (* Of course, ‘equality’ can do all the work for us here. *)\n (********)\nAbort.\n\nGoal forall (a1 a2 b1 b2: N) (l1 l2: list N),\n    a1 :: b1 :: l1 = a2 :: b2 :: l2 ->\n    a1 = a2 /\\ b1 = b2 /\\ l1 = l2.\nProof.\n  simplify.\n  (* ‘invert’ works at arbitrary depth, btw: *)\n  invert H.\n (******)\nAbort.\n\n(* If you ever end up with contradictory hypotheses, you'll want to apply the\n   pompously named “ex falso quodlibet” principle (also known under the\n   scary-sounding name of “principle of explosion”), through the aptly named\n   ‘exfalso’ tactic: *)\nGoal forall (P: Prop) (a b: N),\n    (a < b -> ~P) ->\n    P ->\n    whatever.\nProof.\n  simplify.\n  assert (a < b \\/ b <= a) as C by linear_arithmetic. cases C.\n  - exfalso.\n   (*******)\n    unfold not in H.\n    apply H.\n    all: assumption.\nAbort.\n\n(* Contradictions can take many forms; a common one is Coq is an impossible equality between two constructors; here the empty list ‘[]’ and a non-empty list ‘a :: l’. *)\nGoal forall (a : N) (l : list N),\n    a :: l = [] ->\n    whatever.\nProof.\n  simplify.\n  discriminate.\n (************)\nAbort.\n\nGoal forall (P Q R S T: Prop), (P \\/ Q -> T) -> (R \\/ S -> T) -> P \\/ S -> T.\nProof.\n  simplify.\n  cases H1.\n  - apply H. left. assumption.\n  - apply H0. right. assumption.\nAbort.\n\n(* Here are some more interesting tactics to look into along your Coq journey.\n   Happy proving!\n\n   - constructor, econstructor\n   - eassumption\n   - eexists\n   - first_order\n   - induct\n   - left, right\n   - trivial\n   - transitivity\n   - symmetry\n*)\n\n(* References:\n\n   - FRAP book Appendix A.2. Tactic Reference (http://adam.chlipala.net/frap/frap_book.pdf)\n   - Coq Reference Manual, Chapter on Tactics (https://coq.inria.fr/refman/proof-engine/tactics.html)\n*)\n", "meta": {"author": "mit-frap", "repo": "spring21", "sha": "20ecdeccfda50653abcdeb253dfc8118099f8c40", "save_path": "github-repos/coq/mit-frap-spring21", "path": "github-repos/coq/mit-frap-spring21/spring21-20ecdeccfda50653abcdeb253dfc8118099f8c40/pset02_BinomialCoefficients/Tips.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435030872967, "lm_q2_score": 0.8723473813156294, "lm_q1q2_score": 0.6733156587036851}}
{"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/cogumbreiro/turing/blob/master/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  - simpl.\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  - simpl.\n    rewrite -> Exists_cons.\n    rewrite <- IHl.\n    split.\n    + simpl.\n      intros.\n      inversion H.\n      * simpl.\n        subst.\n        apply H.\n      * simpl.\n        intuition.\n    + simpl.\n      intros.\n      intuition.\nQed.\n\n(**\n\nCreate an inductive relation that holds if, and only if, element 'x'\nappears before element 'y' in the given list.\nWe can define `succ` inductively as follows:\n\n                                (x, y) succ l\n-----------------------R1     ------------------R2\n(x, y) succ x :: y :: l       (x, y) succ z :: l\n\nRule R1 says that x succeeds y in the list that starts with [x, y].\n\nRule R2 says that if x succeeds y in list l then x succeeds y in a list\nthe list that results from adding z to list l.\n\n\n *)\n\nInductive succ {X : Type} (x:X) (y:X): list X -> Prop :=\n  (* TODO: FILL THIS IN AND REMOVE THIS COMMENT *)\n(*  Lemma nil_not: ~ In [] Vowel.*)\n  | R1 : forall (l: list X), succ x y (x :: y :: l)\n  | R2 : forall (z:X) (l:list X), succ x y l -> succ x y (z::l).\n\n\nTheorem succ1:\n    (* Only one of the following propositions is provable.\n       Replace 'False' by the only provable proposition and then prove it:\n     1) succ 2 3 [1;2;3;4]\n     2) ~ succ 2 3 [1;2;3;4]\n     *)\n    succ 2 3 [1;2;3;4].\nProof.\n  simpl.\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  simpl.\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  simpl.\n  unfold not.\n  intros.\n  inversion H.\n  inversion H1.\n  inversion H4.\n  inversion H7.\n  inversion H10.\nQed.\n\n\nTheorem succ4:\n  forall (X:Type) (x y : Type), succ x y [x;y].\nProof.\n  simpl.\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  simpl.\n  intros.\n  simpl.\n  induction l1.\n  - simpl.\n    induction l2.\n    + simpl.\n      apply R1.\n    + simpl.\n      apply R1.\n  - simpl.\n    apply R2.\n    apply IHl1.\nQed.\n\n\nTheorem ex4:\n  forall (X:Type) (x y:X) (l:list X), succ x y l -> exists l1 l2, l1 ++ (x:: y:: l2) = l.\nProof.\n  simpl.\n  intros.\n  induction H.\n  - simpl.\n    exists [].\n    exists l.\n    simpl.\n    reflexivity.\n  - simpl.\n    inversion IHsucc.\n    inversion H0.\n    + simpl.\n      apply R2.\n      * simpl.\n        intuition.\n      apply R1.\n    destruct H0.\n    subst.\nAdmitted.\n\n\n\n", "meta": {"author": "mansi0312", "repo": "CS420", "sha": "d949dc7ba204b990a4bfe3b616916437f50b0230", "save_path": "github-repos/coq/mansi0312-CS420", "path": "github-repos/coq/mansi0312-CS420/CS420-d949dc7ba204b990a4bfe3b616916437f50b0230/hw2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.8723473697001441, "lm_q1q2_score": 0.6733156543166211}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import Vectors.Vector.\nRequire Import ZArith.\n\n(* * The Bad *)\n\nInductive Bush (A : Type): Type :=\n| leaf : A -> Bush A\n| node : Bush (A * A) -> Bush A.\n\n\n(** Ralf Hinze PNS \"Numerical Representations as Higher-Order Nested Datatypes\" *)\n\nInductive Node23 (T A: Type): Type :=\n| Node2 : T -> A -> T -> Node23 T A\n| Node3 : T -> A -> T -> A -> T -> Node23 T A.\n\nInductive Tree23 (T A: Type): Type := \n| Zero : T -> Tree23 T A\n| Succ : Tree23 (Node23 T A) A -> Tree23 T A.\n\nArguments Zero {_}{_} a.\nArguments Succ {_}{_} t.\n\nDefinition TREE23 := Tree23 unit.\n\nExample t : TREE23 nat :=\n  Succ\n    (Succ \n       (Succ\n          (Zero\n             (Node2\n                (Node2\n                   (Node3 tt 1 tt 2 tt)\n                   3\n                   (Node3 tt 4 tt 5 tt))\n                6\n                (Node3 \n                   (Node2 tt 7 tt)\n                   8\n                   (Node2 tt 9 tt)\n                   10\n                   (Node3 tt 11 tt 12 tt)))))).\n\n\nInductive Node23' (T : Type -> Type)(A : Type) :=\n| Node2' : T A -> A -> T A -> Node23' T A\n| Node3' : T A -> A -> T A -> A -> T A -> Node23' T A.\n\nDefinition unit' (A : Type) := unit.\n\nInductive Tree23' (T : Type -> Type)(A : Type) :=\n| Zero' : T A -> Tree23' T A\n| Succ' : Tree23' (Node23' T) A -> Tree23' T A.\n\nDefinition TREE23' := Tree23' unit'.\n\n\nExample t' : TREE23' nat :=\n  Succ'\n    (Succ' \n       (Succ'\n          (Zero'\n             (Node2'\n                (Node2'\n                   (Node3' tt 1 tt 2 tt)\n                   3\n                   (Node3' tt 4 tt 5 tt))\n                6\n                (Node3' \n                   (Node2' tt 7 tt)\n                   8\n                   (Node2' tt 9 tt)\n                   10\n                   (Node3' tt 11 tt 12 tt)))))).\n\n\n(* * The Ugly *)\n\nInductive BushV (A: Type): nat -> Type :=\n| leafV: forall n, Vector.t A n -> BushV A n\n| nodeV: forall n, BushV A (2 * n) -> BushV A n.\n\n(* This should work because [N.to_nat] is an embedding *)\nInductive BushV' (A: Type): nat -> Type :=\n| leafV': forall n, Vector.t A n -> BushV' A n\n| nodeV': forall n, BushV A (N.to_nat (N.shiftl n 1)) -> BushV' A (N.to_nat n).\n\n(* From 'Equations, reloaded\", Sozeau & Mangin *)\n\nDefinition IsNZ (z: Z): Prop := (z <> 0)%Z.\n\nInductive poly : bool -> nat -> Type :=\n| poly_z : poly true O\n| poly_c z : IsNZ z -> poly false O\n| poly_l {n b}(Q : poly b n) : poly b (S n)\n| poly_s {n b}(P : poly b n)(Q : poly false (S n)) : poly false (S n).\n\nInductive mono : nat -> Type :=\n| mono_z : mono O\n| mono_l {n} : mono n -> mono (S n)\n| mono_s {n} : mono (S n) -> mono (S n).\n\nFixpoint get_coef {n}(m: mono n): forall {b}, poly b n -> Z :=\n  match m with\n  | mono_z =>\n    fun b (p: poly b 0) =>\n      match p in poly _ n return match n with O => Z | S _ => unit end with\n      | poly_z => 0%Z\n      | @poly_c z nz => z\n      | poly_l Q => tt\n      | poly_s P Q => tt\n      end\n  | mono_l m =>\n    fun b p =>\n      match p in poly _ n\n            return match n with\n                   | 0 => unit\n                   | S n => (forall b, poly b n -> Z) -> Z\n                   end\n      with\n      | poly_z => tt\n      | poly_c nz => tt\n      | poly_l Q => fun k => k _ Q\n      | poly_s P Q => fun k => k _ P\n      end (@get_coef _ m)\n  | mono_s m =>\n    fun b p =>\n      match p in poly _ n\n            return match n with\n                   | 0 => unit\n                   | S n => (forall b, poly b (S n) -> Z) -> Z\n                   end\n      with\n      | poly_z => tt\n      | poly_c nz => tt\n      | poly_l Q => fun k => 0%Z\n      | poly_s P Q => fun k => k _ Q\n      end (@get_coef _ m)\n  end.\n\nRecord sig (A: Type)(B: A -> Type): Type :=\n  ex { proj1: A; proj2: B proj1 }.\n\nNotation \"a ; b\" := (@ex _ _ a b) (at level 50).\n\nDefinition transport {A: Type} (P: A -> Type) {x y: A} \n    (p: x = y) (u: P x): P y :=\n  match p with eq_refl => u end.\nNotation \"p # x\" := (transport p x)\n                      (right associativity, at level 65, only parsing).\n\nDefinition ap {A B: Type} (f: A -> B) {x y: A} : x = y -> f x = f y.\n  exact (fun p => match p with eq_refl => eq_refl end).\nDefined.\n\nLemma ap2 {A B C} : forall (f: A -> B -> C), forall a1 a2 b1 b2 (q : a1 = a2)(qb : b1 = b2), f a1 b1 = f a2 b2.\nProof.\n  intros; induction q; induction qb; auto.\nDefined.\n\n\nDefinition sig_path {A}{B : A -> Type} {u v : sig B}(q : v.(proj1) = u.(proj1))(p : u.(proj2) = transport (P := fun x => B (x)) q v.(proj2)): u = v.\n  destruct u, v. simpl in *. destruct q. simpl in *. destruct p. auto.\nDefined.\n\nDefinition proj1_path {A} {B : A -> Type} {u v : sig B} (p : u = v): u.(proj1) = v.(proj1) :=\n  ap (fun x => x.(proj1)) p.\n\nNotation \"p ..1\" := (proj1_path p) (at level 3).\n\nDefinition proj2_path {A} {B : A -> Type} {u v : sig B} (p : u = v): p..1 # u.(proj2) = v.(proj2) := match p with eq_refl => eq_refl end.\n\n\nLemma uip_nat {n : nat}: forall (q: n = n), q = eq_refl.\nAdmitted. (* from Hedberg *)\n\nLemma uip_bool {b : bool}: forall (q: b = b), q = eq_refl.\nAdmitted. (* from Hedberg *)\n\nLemma uip_Z {b : Z}: forall (q: b = b), q = eq_refl.\nAdmitted. (* from Hedberg *)\n\nAxiom HProp_Prop : forall {P : Prop} (p q: P), p = q.\n(* assuming proof irrelevance of Prop *)\n\n\nLemma transp_refl {b n}: forall (q: n = n) (p: poly b n), transport q p = p.\nProof.\nintros q p. rewrite (uip_nat q). auto.\nQed.\n\nDefinition S_inj {m n}: S m = S n -> m = n.\nProof.\nintro q. inversion q. reflexivity.\nDefined.\n\nLemma transp_S {b m n}: forall (q: S m = S n) (p: poly b m), transport q (poly_l p) = poly_l (transport (S_inj q) p).\nProof.\ninversion q. subst. rewrite (uip_nat q). simpl. auto.\nDefined.\n\nLemma transp_S_poly_s {b m n}: forall (Q: S m = S n) (p: poly b m)(q: poly false (S m)),\n    transport Q (poly_s p q) = poly_s (transport (S_inj Q) p) (transport Q q).\nProof.\ninversion Q. subst. rewrite (uip_nat Q). simpl. auto.\nDefined.\n\n\nFixpoint mL {n} (p : poly false n): mono n :=\n  match p in poly b n\n        return match b with\n               | false => mono n\n               | true => unit \n               end\n  with\n  | poly_z => tt\n  | poly_c nz => mono_z\n  | @poly_l _ b q => \n    match b return forall n, poly b n -> if b then unit else mono (S n) with true => fun _ _ => tt | false => fun n q => mono_l (mL q) end _ q\n  | poly_s p q => mono_s (mL q)\n  end.\n\nLemma get_coef_mL {b n}: forall (p: poly b n)(q : b = false), IsNZ (get_coef (mL (transport (P := fun b => poly b n) q p)) p).\nProof.\nintros p q.\ninduction p; simpl; try solve [inversion q]; auto.\n- rewrite (uip_bool q); auto.\n- destruct b; try solve [inversion q]. \n  rewrite (uip_bool q); auto. \n  apply (IHp eq_refl).\n- rewrite (uip_bool q).\n  apply (IHp2 eq_refl).\nQed.\n\nLemma get_coef_eq_1 {n n'} b1 b2 (p1: poly b1 n)(p2: poly b2 n')(q: n' = n):\n  (forall (m: mono n), get_coef m p1 = get_coef m (transport q p2)) ->\n  (b1 ; p1) = (b2 ; transport (P := fun n => poly b2 n) q p2) :> @sig bool (fun b => poly b n).\nProof.\ngeneralize dependent n'. generalize dependent b2.\ninduction p1; intros b2 n' p2.\n- destruct p2; intros q H; try solve [inversion q].\n  + rewrite transp_refl.\n    reflexivity.\n  + rewrite transp_refl in H.\n    specialize (H mono_z).\n    simpl in H. subst.\n    contradiction.\n- destruct p2; intros q H; try solve [inversion q].\n  + rewrite transp_refl in H.\n    specialize (H mono_z).\n    contradiction.\n  + rewrite transp_refl in *.\n    specialize (H mono_z).\n    simpl in H. subst.\n    assert (i = i0) as <- by apply HProp_Prop.\n    reflexivity.\n- destruct p2; intros q H; try solve [inversion q].\n  + rewrite transp_S.\n    assert ((b ; p1) = (b0 ; transport (P := poly b0)(S_inj q) p2) :> @sig bool (fun b => poly b n)).\n    {\n      apply IHp1. intros.\n      specialize (H (mono_l m)).\n      simpl in H.\n      rewrite transp_S in H. assumption.\n    }\n    inversion H0. induction H2.\n    destruct H3.\n    reflexivity.\n  + exfalso.\n    rewrite transp_S_poly_s in H.\n    specialize (H (mono_s (mL (transport q p2_2)))).\n    replace (get_coef (mono_s (mL _)) (poly_l p1)) with 0%Z in H; [|compute; auto].\n    replace (get_coef (mono_s (mL _)) (poly_s (transport (S_inj q) p2_1) (transport q p2_2))) with (get_coef (mL (transport q p2_2)) (transport q p2_2)) in H; [|compute;auto].\n\n    pose proof (@get_coef_mL _ _ (transport (P := poly false) q p2_2)).\n    specialize (H0 eq_refl). simpl in *.\n    rewrite <- H in H0.\n    contradiction.\n- destruct p2; intros q H; try solve [inversion q].\n  + exfalso.\n    rewrite transp_S in H.\n    specialize (H (mono_s (mL p1_2))).\n    replace (get_coef (mono_s (mL _)) (poly_l _)) with 0%Z in H; [|compute; auto].\n    replace (get_coef (mono_s (mL _)) (poly_s p1_1 p1_2)) with (get_coef (mL p1_2) p1_2) in H; [|compute;auto].\n\n    pose proof (@get_coef_mL _ _ p1_2).\n    specialize (H0 eq_refl). simpl in *.\n    rewrite H in H0.\n    contradiction.\n  + rewrite transp_S_poly_s in * |- *.\n    assert ((b ; p1_1) = (b0 ; transport (P := poly b0) (S_inj q) p2_1) :> @sig bool (fun b => poly b n)).\n    {\n      apply IHp1_1.\n      intros.\n      apply (H (mono_l m)).\n    }\n    assert ((false; p1_2) = (false; transport (P := poly false) q p2_2) :> @sig bool (fun b => poly b (S n))).\n    {\n      apply IHp1_2.\n      intros.\n      apply (H (mono_s m)).\n    }\n    pose proof (@sig_path bool (fun b => poly b (S n)) (false; poly_s p1_1 p1_2) (false; poly_s (transport (S_inj q) p2_1) (transport q p2_2)) eq_refl).\n    apply H2.\n    simpl.\n    set (x1 := ((b ; p1_1 : @sig bool (fun b => poly b n)))).\n    set (y1 := ((b0 ; transport (P := poly b0) (S_inj q) p2_1 : @sig bool (fun b => poly b n)))).\n    set (x2 := p1_2).\n    set (y2 := transport (P := poly _) q p2_2).\n    pose proof (ap2 (fun u v => poly_s u.(proj2) v)\n                       (a1 := x1)(a2 := y1)\n                       (b1 := x2)(b2 := y2)).\n    apply H3. subst x1 y1; auto.\n    subst x2 y2.\n    pose proof (proj2_path H1).\n    simpl in *.\n    assert (H1 ..1 = eq_refl) by apply uip_bool.\n    rewrite H5 in H4. simpl in *. auto.\nQed.\n\nFixpoint eval {n b} (p: poly b n): Vector.t Z n -> Z :=\n  match p with\n  | poly_z =>\n    fun (v: Vector.t Z 0) =>\n      match v in Vector.t _ n\n            return match n with 0 => Z | S _ => unit end\n      with\n      | nil _ => 0%Z\n      | cons _ _ _ _ => tt\n      end\n  | @poly_c z nz =>\n    fun (v: Vector.t Z 0) =>\n      match v in Vector.t _ n\n            return match n with 0 => Z | S _ => unit end\n      with\n      | nil _ => z\n      | cons _ _ _ _ => tt\n            end\n  | poly_l Q =>\n    fun v =>\n      match v in Vector.t _ n\n            return match n with\n                   | 0 => unit\n                   | S n => (Vector.t Z n -> Z) -> Z\n                   end\n      with\n      | nil _ => tt\n      | cons _ _ _ xs => fun k => k xs\n      end (@eval _ _ Q)\n  | poly_s P Q =>\n    fun v =>\n      match v in Vector.t _ n\n            return match n with\n                   | 0 => unit\n                   | S n => (Vector.t Z n -> Z) -> (Vector.t Z (S n) -> Z) -> Z\n                         end\n      with\n      | nil _ => tt\n      | cons _ y _ ys => fun kP kQ => (kP ys + y * kQ (cons _ y _ ys))%Z\n      end (@eval _ _ P) (@eval _ _ Q)\n  end.\n\nLemma polyz_eval {n} (p : poly true n) (v: Vector.t Z n) : eval p v = 0%Z.\nProof.\nremember true as b eqn:Hb.\ninduction p; try solve [inversion Hb].\n- case v using case0.\n  auto.\n- unshelve eapply (@caseS _ (fun n' v => forall p' (q: n = n') , transport q p = p' -> eval (poly_l p') v = 0%Z) _  n v p).\n  + simpl. intros. \n    destruct q.\n    simpl in *.\n    destruct H.\n    apply IHp. auto. \n  + auto.\n  + auto.\nQed.  \n\n\n(* * The Good ? *)\n\n(* ** Views *)\n\nInductive ty := Base : ty | Arr : ty -> ty -> ty.\n\nInductive term : Type :=\n| lam : ty -> term -> term\n| app : term -> term -> term\n| var : nat -> term.\n\nInductive In {X} (A : X) : list X -> Type :=\n| here {XS} : In A (A :: XS)\n| there {B XS} : In A XS -> In A (B :: XS).\n\nInductive typing (Gamma: list ty): ty -> Type :=\n| Tlam {A B} : typing (A :: Gamma) B -> typing Gamma (Arr A B)\n| Tapp {A B} : typing Gamma (Arr A B) -> typing Gamma A -> typing Gamma B\n| Tvar {A} : In A Gamma -> typing Gamma A.\n\nFixpoint val_In {X}{A : X}{Gamma: list X} (t: In A Gamma): nat :=\n  match t with\n  | here _ => 0\n  | there t => S (val_In t)\n  end.\n\nFixpoint val_typing {Gamma}{T} (Delta: typing Gamma T): term :=\n  match Delta with\n  | @Tlam _ A _ Delta => lam A (val_typing Delta)\n  | Tapp Delta_f Delta_s => app (val_typing Delta_f) (val_typing Delta_s)\n  | Tvar x => var (val_In x)\n  end.\n\nInductive TC_view (Gamma: list ty) : term -> Type := \n| yes {T} : forall (Delta : typing Gamma T), TC_view Gamma (val_typing Delta)\n| no {t} : TC_view Gamma t.\n\nFixpoint tc (Gamma: list ty)(t: term): TC_view Gamma t.\nAdmitted. (* XXX: probably a hell to implement in Coq w/o Equation *)\n\n(* ** SSR's tuple *)\n\nSection Tuple.\n\nVariable (A: Type).\n\nInductive list: Type :=\n| nil: list\n| cons: A -> list -> list.\n\nInductive vec: nat -> Type :=\n| vnil: vec 0\n| vcons: forall {n}, A -> vec n -> vec (S n).\n\n(* XXX: this follows from hprop-ness: *)\n\n(* XXX: [vec_inj] is not useful because we are bound to use it with\n[xs, ys] having the same index. [vec_JMEq] is morally equivalent but\nmore useful. *)\n\nAxiom val_vec: forall {n}, vec n -> list.\nAxiom vec_inj: forall {n} (xs ys: vec n), val_vec xs = val_vec ys -> xs = ys. \nAxiom vec_JMEq: forall {m} (xs : vec m) (P : forall {k}, vec k -> Type), P xs -> forall {n} (ys : vec n), val_vec xs = val_vec ys -> P ys.\n\nAxiom val_vec_vnil: val_vec vnil = nil.\nAxiom val_vec_vcons: forall n (a : A) (xs: vec n), val_vec (vcons a xs) = cons a (val_vec xs).\n\n(* *** Definitions & Specifications *)\n\nFixpoint behead {n}(t: vec (S n)): vec n :=\n  match t with\n  | vcons x t => t\n  end.\n\n(* Factories *)\n\nFixpoint ncons {m} n x (xs: vec m): vec (n+m) :=\n  match n with\n  | 0 => xs\n  | S n => vcons x (ncons n x xs)\n  end.\n\n(* FAILED(compositionality): [n + 0 != n] *)\nFail Definition nseq n x: vec n := ncons n x vnil.\n\nFixpoint nseq (n: nat)(x: A): vec n :=\n  match n with\n  | 0 => vnil\n  | S n => vcons x (nseq n x)\n  end.\n\n(* Sequence catenation \"cat\". *)\n\nFixpoint cat {n m} (t: vec n): vec m -> vec (n+m) :=\n  match t in vec n return vec m -> vec (n+m) with\n  | vnil => fun u => u\n  | vcons x t => fun u => vcons x (cat t u)\n  end.\n\nDefinition val_cat {n m} (t: vec n)(u: vec m): list := val_vec (cat t u).\nArguments val_cat /.\n\nLemma val_cat_vnil: forall n (xs: vec n), val_cat vnil xs = val_vec xs.\nProof. reflexivity. Qed.\n\nLemma val_cat_vcons: forall m n x (t: vec n)(u : vec m), val_cat (vcons x t) u = cons x (val_cat t u).\nProof. intros; unfold val_cat; simpl. rewrite val_vec_vcons. reflexivity. Qed.\n\n\nLemma cat0s n (s: vec n) : cat vnil s = s.\nProof. reflexivity. Qed.\nLemma cat1s n x (s: vec n) : cat (vcons x vnil) s = vcons x s.\nProof. reflexivity. Qed.\nLemma cat_cons m n x (s1: vec m)(s2: vec n) : cat (vcons x s1) s2 = vcons x (cat s1 s2).\nProof. reflexivity. Qed.\n\nLemma cat_nseq m n x (s: vec m) : cat (nseq n x) s = ncons n x s.\nProof. induction n; auto; simpl. rewrite IHn; auto. Qed.\n\n(* FAILED(heterogeneity): [m + 0 != m] *)\nFail Lemma cats0 n (s: vec n) : cat s vnil = s.\n\nLemma val_cats0 n (s: vec n) : val_cat s vnil = val_vec s.\nProof.\ninduction s; auto.\nsimpl in *; rewrite !val_vec_vcons; congruence.\nQed.\n\n(* FAILED(heterogeneity): [(m + n) + o != m + (n + o)] *)\nFail Lemma catA m n o (s1: vec m)(s2: vec n)(s3: vec o) :\n  cat s1 (cat s2 s3) = cat (cat s1 s2) s3.\n\nLemma val_catA m n o (s1: vec m)(s2: vec n)(s3: vec o) :\n  val_cat s1 (cat s2 s3) = val_cat (cat s1 s2) s3.\nProof.\ninduction s1; auto.\nsimpl in *. rewrite !val_vec_vcons. congruence.\nQed.\n\n(* last, belast, rcons, and last induction. *)\n\nFixpoint rcons {n} (s: vec n)(z: A): vec (S n) :=\n  match s with\n  | vcons x s' => vcons x (rcons s' z)\n  | vnil => vcons z vnil\n  end.\n\nDefinition val_rcons  {n} (s: vec n)(z: A): list := val_vec (rcons s z).\nArguments val_rcons /.\n\nLemma val_rcons_vcons : forall n (s: vec n) x z,\n    val_rcons (vcons x s) z = cons x (val_rcons s z).\nProof. intros; simpl; rewrite !val_vec_vcons; reflexivity. Qed.\n\nLemma val_rcons_vnil : forall n (s: vec n) z,\n    val_rcons vnil z = cons z nil.\nProof. intros; simpl; rewrite !val_vec_vcons, !val_vec_vnil; reflexivity. Qed.\n\nLemma rcons_cons n x (s: vec n) z : rcons (vcons x s) z = vcons x (rcons s z).\nProof. reflexivity. Qed.\n\n(* FAILED(heterogeneity): [S n != n + 1] *)\nFail Lemma cats1 n (s: vec n) z : cat s (vcons z vnil) = rcons s z.\n\nLemma val_cats1 n (s: vec n) z : val_cat s (vcons z vnil) = val_rcons s z.\nProof.\ninduction s.\n- auto.\n- rewrite val_cat_vcons, val_rcons_vcons; congruence.\nQed.\n\n\nFixpoint last' {n} (a: A)(t: vec n) : A :=\n  match t with\n  | vnil => a\n  | vcons a xs => last' a xs\n  end.\n\nDefinition last {n}(t: vec (S n)): A :=\n  match t with\n  | vcons a xs => last' a xs\n  end.\n\nFixpoint belast {n}(x: A)(t: vec n): vec n :=\n  match t in vec n return vec n with\n  | vcons x' t => vcons x (belast x' t)\n  | vnil => vnil\n  end.\n\nLemma lastI n x (s: vec n) : vcons x s = rcons (belast x s) (last' x s).\nProof.\ngeneralize x. induction s; intros; auto.\nsimpl. rewrite IHs at 1. auto.\nQed.\n\nLemma last_cons n x y (s: vec n) : last' x (vcons y s) = last' y s.\nProof. reflexivity. Qed.\n\nLemma last_cat m n x (s1: vec m)(s2: vec n) : last' x (cat s1 s2) = last' (last' x s1) s2.\nProof.\ngeneralize x.\ninduction s1; intros; auto; simpl.\nrewrite IHs1. auto.\nQed.\n\n(* FAILED(rewriting): [rcons s x !== cat s (vcons x vnil)] *)\nLemma last_rcons n x (s: vec n) z : last' x (rcons s z) = z.\nProof. generalize x; induction s; intros; auto; simpl. rewrite IHs. auto. Qed.\n(* by rewrite -cats1 last_cat. *)\n\nLemma belast_cat m n x (s1: vec m)(s2: vec n) :\n  belast x (cat s1 s2) = cat (belast x s1) (belast (last' x s1) s2).\nProof. generalize x. induction s1; intros; auto; simpl. rewrite IHs1; auto. Qed.\n\nLemma belast_rcons n x (s: vec n) z : belast x (rcons s z) = vcons x s.\nProof.\n  generalize x. induction s; auto. intro. rewrite rcons_cons. simpl; rewrite IHs. auto.\nQed.\n\n(* FAILED(heterogeneity): [m + S n != S m + n] *)\nFail Lemma cat_rcons m n x (s1: vec m)(s2: vec n) : cat (rcons s1 x) s2 = cat s1 (vcons x s2).\n\nLemma val_cat_rcons m n x (s1: vec m)(s2: vec n) : val_cat (rcons s1 x) s2 = val_cat s1 (vcons x s2).\nProof.\n(* XXX: How could I exploit the following lemmas: *)\nCheck val_cats1.\nCheck val_catA.\n(* rewrite -cats1 -catA.  *)\nAbort.\n\n(* FAILED(heterogeneity): [m + S n != S (m + n)] *)\nFail Lemma rcons_cat m n x (s1: vec m)(s2: vec n) : rcons (cat s1 s2) x = cat s1 (rcons s2 x).\n\nCoInductive last_spec : forall n, vec n -> Type :=\n  | LastNil        : last_spec vnil\n  | LastRcons n (s: vec n) x  : last_spec (rcons s x).\n\nLemma lastP n (s: vec n) : last_spec s.\nProof. case s; [ left | ]. intros; rewrite lastI; constructor. Qed.\n\n\nLemma last_ind (P: forall n, vec n -> Type) :\n  P _ vnil -> (forall n (s: vec n) x, P _ s -> P _ (rcons s x)) -> forall n (s: vec n), P _ s.\nProof.\nintros Hnil Hlast n s.\nrewrite <-(cat0s s).\nAdmitted.\n(* XXX: the generalization is not sufficient in the dependently-typed case *)\n(*\nelim: s [::] Hnil => [|x s2 IHs] s1 Hs1; first by rewrite cats0.\nby rewrite -cat_rcons; auto.\nQed. *)\n\n(* Surgery: drop, take, rot, rotr.                                        *)\n\n(* FAILED(typing): [n - 0 != n] *)\nFail Fixpoint drop {n} (m: nat): vec n -> vec (n - m) :=\n  match m return vec n -> vec (n - m) with\n  | 0 => fun t => t\n  | S n => fun t => match t with\n                | vnil => vnil\n                | vcons s t => drop n t\n                end\n  end.\n\n(* FAILED(typing): [Nat.min m 0 !== 0] *)\nFail Fixpoint take {n} (m: nat)(t: vec n) {struct t}: vec (Nat.min m n) :=\n  match t, n with\n  | vcons x s', S n => vcons x (take n s')\n  | _, _ => vnil\n  end.\n\n(* reversal *)\n\n(* FAILED(typing): [n + 0 != n] *)\nFail Fixpoint catrev {m}{n} (s1: vec m)(s2: vec n): vec (n + m) :=\n  match s1 with\n  | vcons x s1' => catrev s1' (vcons x s2)\n  | vnil => s2\n  end.\nFail Definition rev {n} (s : vec n) := catrev s vnil.\n\n(* XXX: inefficient implementation *)\nFixpoint rev {n} (t: vec n): vec n :=\n  match t with\n  | vnil => vnil\n  | vcons x xs => rcons (rev xs) x\n  end.\n\nLemma rev_cons n x (s: vec n) : rev (vcons x s) = rcons (rev s) x.\nProof. reflexivity. (* works because of inefficient implem *) Qed.\n\n(* FAILED(heterogeneity): [m + n != n + m] *)\nFail Lemma rev_cat m n (s: vec m)(t: vec n) : rev (cat s t) = cat (rev t) (rev s).\n\nLemma rev_rcons n (s: vec n) x : rev (rcons s x) = vcons x (rev s).\nProof. induction s; auto; simpl. rewrite IHs. auto. Qed.\n\nEnd Tuple.\n\nSection PolyTuple.\n\nVariable (A B C: Type).\n\nFixpoint map {n} (f: A -> B)(t: vec A n): vec B n :=\n  match t with\n  | vnil _ => vnil _\n  | vcons x xs => vcons (f x) (map f xs)\n  end.\n\nLemma map_cons n (f: A -> B) x (s: vec A n) : map f (vcons x s) = vcons (f x) (map f s).\nProof. reflexivity. Qed.\n\nLemma map_nseq (f: A -> B) n0 x : map f (nseq n0 x) = nseq n0 (f x).\nProof. induction n0; auto; simpl. rewrite IHn0. auto. Qed.\n\nLemma map_cat m n (f : A -> B) (s1: vec A m)(s2: vec A n) : map f (cat s1 s2) = cat (map f s1) (map f s2).\nProof. induction s1; auto; simpl. rewrite IHs1. auto. Qed.\n\n(* XXX: Painful (inversion of [vec A (S n)] *)\nLemma behead_map n (f: A -> B) (s: vec A (S n)) : behead (map f s) = map f (behead s).\nAdmitted.\n\n(* FAILED(rewriting): [rcons s x != cat s (vcons x vnil)] *)\nLemma map_rcons n (f: A -> B) (s: vec A n) x : map f (rcons s x) = rcons (map f s) (f x).\nProof. induction s; auto; simpl. rewrite IHs. auto. Qed.\n\nLemma last_map n (f: A -> B)(s: vec A n) x : last' (f x) (map f s) = f (last' x s).\nProof. generalize x. induction s; auto; simpl; intros. rewrite IHs. auto. Qed.\n\nLemma belast_map n (f: A -> B)(s: vec A n) x : belast (f x) (map f s) = map f (belast x s).\nProof. generalize x. induction s; auto; simpl; intros. rewrite IHs. auto. Qed.\n\nLemma map_rev n (f: A -> B)(s: vec A n) : map f (rev s) = rev (map f s).\nProof.\n  induction s; auto; simpl; intros.\n  rewrite map_rcons. rewrite IHs. auto.\nQed.\n\nFixpoint pairmap {n} (f: A -> A -> A)(a : A)(t: vec A n): vec A n :=\n  match t with\n  | vnil _ => vnil _\n  | vcons x xs => vcons (f a x) (pairmap f x xs)\n  end.\n\nLemma pairmap_cat m n (f: A -> A -> A) x (s1: vec A m)(s2: vec A n) :\n  pairmap f x (cat s1 s2) = cat (pairmap f x s1) (pairmap f (last' x s1) s2).\nProof. generalize x. induction s1; intros; auto; simpl. rewrite IHs1. auto. Qed.\n\nFixpoint scanl {n} (f: A -> B -> A)(a: A)(t: vec B n): vec A n :=\n  match t with\n  | vnil _ => vnil _\n  | vcons x xs =>\n    let fx := f a x in\n    vcons fx (scanl f fx xs)\n  end.\n\nEnd PolyTuple.\n\nSection PolyTuple'.\n\nVariable (A B C: Type).\n\nFixpoint zip {m n} (t1: vec A m)(t2: vec B n): vec (A * B) (Nat.min m n) :=\n  match t1, t2 with\n  | vnil _, _ => vnil _\n  | _, vnil _ => vnil _\n  | vcons x1 xs1, vcons x2 xs2 => vcons (x1, x2) (zip xs1 xs2)\n  end.\n\n(* XXX: this redundancy is annoying. *)\nFixpoint zip' {n} (t1: vec A n) {struct t1}: vec B n -> vec (A * B) n :=\n  match t1 with\n  | vnil _ => fun _ => vnil _\n  | vcons x1 xs1 =>\n    fun xs =>\n      match xs in vec _ n\n            return match n with\n                   | 0 => unit\n                   | S n => (vec B n -> vec (A * B) n) -> vec (A * B) (S n)\n                   end with\n      | vcons x2 xs2 => fun zip => vcons (x1, x2) (zip xs2)\n      | vnil _ => tt\n      end (zip' xs1)\n  end.\n\nDefinition unzip1 n := @map _ _ n (@fst A B).\nDefinition unzip2 n := @map _ _ n (@snd A B).\n\n(* FAILED(heterogeneity): [Nat.min n n != n] *)\nFail Lemma zip_unzip s : zip (unzip1 s) (unzip2 s) = s.\n\nLemma zip_unzip n (s: vec (A * B) n) : zip' (unzip1 s) (unzip2 s) = s.\nProof.\n  induction s; auto; simpl. unfold unzip1, unzip2 in IHs.\n  rewrite IHs. rewrite <- surjective_pairing. auto.\nQed.\n\n(* FAILED(heterogeneity): [Nat.min m n !== m] under [m <= n] *)\nFail Lemma unzip1_zip m n (s: vec A m)(t: vec B n) : m <= n -> unzip1 (zip s t) = s.\n\n(* FAILED(heterogeneity): [Nat.min m n !== n] under [n <= m] *)\nFail Lemma unzip2_zip m n (s: vec A m)(t: vec B n) : m <= n -> unzip2 (zip s t) = t.\n\n(* FAILED(heterogeneity): [Nat.min m m + Nat.min k l != Nat.min (m + k) (m + l)] *)\nFail Lemma zip_cat m k l (s1: vec A m)(s2: vec A k)(t1: vec B m)(t2: vec B l) :\n  zip (cat s1 s2) (cat t1 t2) = cat (zip s1 t1) (zip s2 t2).\n\n(* FAILED(rewriting): [rcons x s != cat s (vcons x vnil)] *)\nLemma zip_rcons n (s1: vec A n)(s2: vec B n) z1 z2 :\n  zip (rcons s1 z1) (rcons s2 z2) = rcons (zip s1 s2) (z1, z2).\nProof.\nAdmitted. (* XXX: looks painful *)\n\n(* FAILED(rewriting): [rev xs != catrev xs vnil] *)\nLemma rev_zip n (s1: vec A n)(s2: vec B n) :\n  rev (zip s1 s2) = zip (rev s1) (rev s2).\nProof.\ngeneralize s2. induction s1; intros; auto.\n(* XXX: do inversion on s0 *)\nAdmitted.\n(* by rewrite !rev_cons zip_rcons ?IHs ?size_rev. *)\n\nFixpoint iota (m n: nat): vec nat n :=\n  match n with\n  | S n => vcons m (iota (S m) n)\n  | 0 => vnil _\n  end.\n\nLemma iota_add m n1 n2 : iota m (n1 + n2) = cat (iota m n1) (iota (m + n1) n2).\nProof.\ngeneralize m. induction n1; intros; auto; simpl.\n- rewrite <- plus_n_O. auto.\n- rewrite IHn1.\n  rewrite plus_Snm_nSm.\n  auto.\nQed.\n\nEnd PolyTuple'.\n\nSection PolyTuple2.\n\nVariable (A B C: Type).\n\nDefinition uncurry (f: A -> B -> C)(ab: A * B): C :=\n  let (a, b) := ab in f a b.\n\nFixpoint allpairs {m n} (f: A -> B -> C)(s: vec A n)(t: vec B m): vec C (n * m) :=\n  match s with\n  | vnil _ => vnil _\n  | vcons a s => cat (map (uncurry f) (zip' (nseq m a) t)) (allpairs f s t)\n  end.\n\n(* FAILED(heterogeneity): [m * k + n * k != (m + n) * k] *)\nFail Lemma allpairs_cat m n (f: A -> B -> C) (s1: vec A m)(s2: vec A n) t :\n  allpairs f (cat s1 s2) t = cat (allpairs f s1 t) (allpairs f s2 t).\n\n\nEnd PolyTuple2.\n\n(* TODO: implement [nth], [rot], [rotr] *)\n", "meta": {"author": "CoqHott", "repo": "inductive-families-extraction", "sha": "dc64e0e2db5d69728e314048d4cf5eb84f3d1193", "save_path": "github-repos/coq/CoqHott-inductive-families-extraction", "path": "github-repos/coq/CoqHott-inductive-families-extraction/inductive-families-extraction-dc64e0e2db5d69728e314048d4cf5eb84f3d1193/good_bad_ugly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6733156515638877}}
{"text": "Require Import Coq.omega.Omega.\n\nLemma strong_induction {P: nat -> Prop}:\n  (forall n, (forall m, m < n -> P m) -> P n) ->\n  (forall n, P n).\nProof.\n  intros ?.\n  assert (forall n, (forall m, m < n -> P m)).\n  + intro n; induction n.\n    - intros; omega.\n    - intros.\n      destruct (lt_dec m n).\n      * apply IHn; auto.\n      * assert (m = n) by omega; subst m.\n        apply H; auto.\n  + intros.\n    apply (H0 (S n)).\n    constructor.\nQed.\n\nLtac strong_induction n :=\n  revert dependent n;\n  intro n;\n  pattern n;\n  revert n;\n  apply strong_induction;\n  intros ?n ?IH.\n", "meta": {"author": "QinxiangCao", "repo": "UnifySL", "sha": "cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d", "save_path": "github-repos/coq/QinxiangCao-UnifySL", "path": "github-repos/coq/QinxiangCao-UnifySL/UnifySL-cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d/lib/StrongInduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6733156444240901}}
{"text": "From Undecidability.L Require Import Datatypes.LNat Tactics.LTactics.\n\n(* ** Computability of Ackermann *)\n\nFixpoint ackermann n : nat -> nat :=\n  match n with\n    0 => S\n  | S n => fix ackermann_Sn m : nat :=\n            match m with\n              0 => (fun _ => ackermann n 1)\n            | S m => (fun _ => ackermann n (ackermann_Sn m))\n            end true\n  end.\n\nLemma term_ackermann : computable ackermann.\nProof.\n  extract.\nQed.  \n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/L/Functions/Ackermann.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6733156347227675}}
{"text": "Inductive 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\nRequire  Export Bool.\n\n\nFixpoint L_value (l : L): bool :=\n match l with\n | L_true => true\n | L_false => false\n | L_disj l1 l2 => orb (L_value l1) (L_value l2)\n | L_conj l1 l2 => andb (L_value l1) (L_value l2)\n | L_impl l1 l2 => implb (L_value l1) (L_value l2)\n | L_not l1 => negb (L_value l1)\n end.\n\n\n(* infix notations *)\n\nNotation \"A * B\"  := (L_conj A B) : prop_scope.\n\nNotation \"A + B\"  := (L_disj A B) : prop_scope.\n\nNotation \"A <= B\" := (L_impl A B) : prop_scope.\n\nNotation \"'tt'\" := L_true : prop_scope.\n\nNotation \"'ff'\" := L_false : prop_scope.\n\nNotation \"- A\" := (L_not A) : prop_scope.\n\nOpen Scope prop_scope.\n\nEval compute in (L_value (tt * ff)).\n\nEval compute in (L_value (tt * ff + (tt <= ff))).\n\nEval compute in (L_value (- (tt * ff + (tt <= ff)))).\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/propositional.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.6733026647175171}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf1 : natural) : natural :=\n  plus (Succ x) Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj258_coqofml_Qhs0n8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.6733026571718904}}
{"text": "Require Export Ensembles.\nRequire Import EnsemblesImplicit.\n\nInductive characteristic_function_abstraction {X:Type} (P:X->Prop) (x:X) : Prop :=\n  | intro_characteristic_sat: P x ->\n    In (characteristic_function_abstraction P) x.\n\nDefinition characteristic_function_to_ensemble {X:Type} (P:X->Prop) : Ensemble X :=\n  characteristic_function_abstraction P.\n\nNotation \"[ x : X | P ]\" :=\n  (characteristic_function_to_ensemble (fun x:X => P))\n  (x ident).\n\nLemma characteristic_function_to_ensemble_is_identity:\n  forall {X:Type} (P:X->Prop),\n    [ x:X | P x ] = P.\nProof.\nintros.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H.\nexact H.\nconstructor.\nexact H.\nQed.\n\n(*\nDefinition even_example : Ensemble nat :=\n  [ n:nat | exists m:nat, n=2*m ].\n\nLemma even_example_result: forall n:nat, In even_example n ->\n  In even_example (n+2).\nProof.\nintros.\ndestruct H.\nconstructor.\ndestruct H as [m].\nexists (m + 1).\nrewrite H.\nRequire Import Arith.\nring.\nQed.\n*)\n", "meta": {"author": "dschepler", "repo": "coq-zorns-lemma", "sha": "4ad354c50f73758c094f43da5fc0f2c6dd8e3da2", "save_path": "github-repos/coq/dschepler-coq-zorns-lemma", "path": "github-repos/coq/dschepler-coq-zorns-lemma/coq-zorns-lemma-4ad354c50f73758c094f43da5fc0f2c6dd8e3da2/EnsemblesSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684336, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6733026449783115}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrbool ssrfun ssrnat eqtype seq choice div fintype.\nRequire Import path bigop finset prime ssralg poly polydiv mxpoly.\nRequire Import generic_quotient countalg ssrnum ssrint rat intdiv.\nRequire Import algebraics_fundamentals.\n\n(******************************************************************************)\n(* This file provides an axiomatic construction of the algebraic numbers.     *)\n(* The construction only assumes the existence of an algebraically closed     *)\n(* filed with an automorphism of order 2; this amounts to the purely          *)\n(* algebraic contents of the Fundamenta Theorem of Algebra.                   *)\n(*       algC == the closed, countable field of algebraic numbers.            *)\n(*  algCeq, algCring, ..., algCnumField == structures for algC.               *)\n(*        z^* == the complex conjugate of z (:= conjC z).                     *)\n(*    sqrtC z == a nonnegative square root of z, i.e., 0 <= sqrt x if 0 <= x. *)\n(*  n.-root z == more generally, for n > 0, an nth root of z, chosen with a   *)\n(*               minimal non-negative argument for n > 1 (i.e., with a        *)\n(*               maximal real part subject to a nonnegative imaginary part).  *)\n(*               Note that n.-root (-1) is a primitive 2nth root of unity,    *)\n(*               an thus not equal to -1 for n odd > 1 (this will be shown in *)\n(*               file cyclotomic.v).                                          *)\n(* The ssrnum interfaces are implemented for algC as follows:                 *)\n(*     x <= y <=> (y - x) is a nonnegative real                               *)\n(*      x < y <=> (y - x) is a (strictly) positive real                       *)\n(*       `|z| == the complex norm of z, i.e., sqrtC (z * z^* ).               *)\n(*      Creal == the subset of real numbers (:= Num.real for algC).           *)\n(* In addition, we provide:                                                   *)\n(*         'i == the imaginary number (:= sqrtC (-1)).                        *)\n(*      'Re z == the real component of z.                                     *)\n(*      'Im z == the imaginary component of z.                                *)\n(*       Crat == the subset of rational numbers.                              *)\n(*       Cint == the subset of integers.                                      *)\n(*       Cnat == the subset of natural integers.                              *)\n(*  getCrat z == some a : rat such that ratr a = z, provided z \\in Crat.      *)\n(*   floorC z == for z \\in Creal, an m : int s.t. m%:~R <= z < (m + 1)%:~R.   *)\n(*   truncC z == for z >= 0, an n : nat s.t. n%:R <= z < n.+1%:R, else 0%N.   *)\n(* minCpoly z == the minimal (monic) polynomial over Crat with root z.        *)\n(* algC_invaut nu == an inverse of nu : {rmorphism algC -> algC}.             *)\n(*         (x %| y)%C <=> y is an integer (Cint) multiple of x; if x or y are *)\n(*        (x %| y)%Cx     of type nat or int they are coerced to algC here.   *)\n(*                        The (x %| y)%Cx display form is a workaround for    *)\n(*                        design limitations of the Coq Notation facilities.  *)\n(* (x == y %[mod z])%C <=> x and y differ by an integer (Cint) multiple of z; *)\n(*                as above, arguments of type nat or int are cast to algC.    *)\n(* (x != y %[mod z])%C <=> x and y do not differ by an integer multiple of z. *)\n(* Note that in file algnum we give an alternative definition of divisibility *)\n(* based on algebraic integers, overloading the notation in the %A scope.     *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory Num.Theory.\nLocal Open Scope ring_scope.\n\n(* The Num mixin for an algebraically closed field with an automorphism of    *)\n(* order 2, making it into a field of complex numbers.                        *)\nLemma ComplexNumMixin (L : closedFieldType) (conj : {rmorphism L -> L}) :\n    involutive conj -> ~ conj =1 id ->\n  {numL | forall x : NumDomainType L numL, `|x| ^+ 2 = x * conj x}.\nProof.\nmove=> conjK conj_nt.\nhave nz2: 2%:R != 0 :> L.\n  apply/eqP=> char2; apply: conj_nt => e; apply/eqP/idPn=> eJ.\n  have opp_id x: - x = x :> L.\n    by apply/esym/eqP; rewrite -addr_eq0 -mulr2n -mulr_natl char2 mul0r.\n  have{char2} char2: 2 \\in [char L] by apply/eqP.\n  without loss{eJ} eJ: e / conj e = e + 1.\n    move/(_ (e / (e + conj e))); apply.\n    rewrite fmorph_div rmorphD conjK -{1}[conj e](addNKr e) mulrDl.\n    by rewrite opp_id (addrC e) divff // addr_eq0 opp_id.\n  pose a := e * conj e; have aJ: conj a = a by rewrite rmorphM conjK mulrC.\n  have [w Dw] := @solve_monicpoly _ 2 (nth 0 [:: e * a; - 1]) isT.\n  have{Dw} Dw: w ^+ 2 + w = e * a.\n    by rewrite Dw !big_ord_recl big_ord0 /= mulr1 mulN1r addr0 subrK.\n  pose b := w + conj w; have bJ: conj b = b by rewrite rmorphD conjK addrC.\n  have Db2: b ^+ 2 + b = a.\n    rewrite -Frobenius_autE // rmorphD addrACA Dw /= Frobenius_autE -rmorphX.\n    by rewrite -rmorphD Dw rmorphM aJ eJ -mulrDl -{1}[e]opp_id addKr mul1r.\n  have /eqP[] := oner_eq0 L; apply: (addrI b); rewrite addr0 -{2}bJ.\n  have: (b + e) * (b + conj e) == 0.\n    rewrite mulrDl 2!mulrDr -/a addrA addr_eq0 opp_id (mulrC e) -addrA.\n    by rewrite -mulrDr eJ addrAC -{2}[e]opp_id subrr add0r mulr1 Db2.\n  rewrite mulf_eq0 !addr_eq0 !opp_id => /pred2P[] -> //.\n  by rewrite {2}eJ rmorphD rmorph1.\nhave mul2I: injective (fun z : L => z *+ 2).\n  by move=> x y; rewrite /= -mulr_natl -(mulr_natl y) => /mulfI->.\npose sqrt x : L := sval (sig_eqW (@solve_monicpoly _ 2 (nth 0 [:: x]) isT)).\nhave sqrtK x: sqrt x ^+ 2 = x.\n  rewrite /sqrt; case: sig_eqW => /= y ->.\n  by rewrite !big_ord_recl big_ord0 /= mulr1 mul0r !addr0.\nhave sqrtE x y: y ^+ 2 = x -> {b : bool | y = (-1) ^+ b * sqrt x}.\n  move=> Dx; exists (y != sqrt x); apply/eqP; rewrite mulr_sign if_neg.\n  by case: ifPn => //; apply/implyP; rewrite implyNb -eqf_sqr Dx sqrtK.\npose i := sqrt (- 1).\nhave sqrMi x: (i * x) ^+ 2 = - x ^+ 2 by rewrite exprMn sqrtK mulN1r.\nhave iJ : conj i = - i.\n  have /sqrtE[b]: conj i ^+ 2 = - 1 by rewrite -rmorphX sqrtK rmorphN1.\n  rewrite mulr_sign -/i; case: b => // Ri.\n  case: conj_nt => z; wlog zJ: z / conj z = - z.\n    move/(_ (z - conj z)); rewrite !rmorphB conjK opprB => zJ.\n    by apply/mul2I/(canRL (subrK _)); rewrite -addrA zJ // addrC subrK.\n  have [-> | nz_z] := eqVneq z 0; first exact: rmorph0.\n  have [u Ru [v Rv Dz]]:\n    exists2 u, conj u = u & exists2 v, conj v = v & (u + z * v) ^+ 2 = z.\n  - pose y := sqrt z; exists ((y + conj y) / 2%:R).\n      by rewrite fmorph_div rmorphD conjK addrC rmorph_nat.\n    exists ((y - conj y) / (z *+ 2)).\n      rewrite fmorph_div rmorphMn zJ mulNrn invrN mulrN -mulNr rmorphB opprB.\n      by rewrite conjK.\n    rewrite -(mulr_natl z) invfM (mulrC z) !mulrA divfK // -mulrDl addrACA.\n    by rewrite subrr addr0 -mulr2n -mulr_natr mulfK ?Neq0 ?sqrtK.\n  suffices u0: u = 0 by rewrite -Dz u0 add0r rmorphX rmorphM Rv zJ mulNr sqrrN.\n  suffices [b Du]: exists b : bool, u = (-1) ^+ b * i * z * v.\n    apply: mul2I; rewrite mul0rn mulr2n -{2}Ru.\n    by rewrite Du !rmorphM rmorph_sign Rv Ri zJ !mulrN mulNr subrr.\n  have/eqP:= zJ; rewrite -addr_eq0 -{1 2}Dz rmorphX rmorphD rmorphM Ru Rv zJ.\n  rewrite mulNr sqrrB sqrrD addrACA (addrACA (u ^+ 2)) addNr addr0 -!mulr2n.\n  rewrite -mulrnDl -(mul0rn _ 2) (inj_eq mul2I) /= -[rhs in _ + rhs]opprK.\n  rewrite -sqrMi subr_eq0 eqf_sqr -mulNr !mulrA.\n  by case/pred2P=> ->; [exists false | exists true]; rewrite mulr_sign.\npose norm x := sqrt x * conj (sqrt x).\nhave normK x : norm x ^+ 2 = x * conj x by rewrite exprMn -rmorphX sqrtK.\nhave normE x y : y ^+ 2 = x -> norm x = y * conj y.\n  rewrite /norm => /sqrtE[b /(canLR (signrMK b)) <-].\n  by rewrite !rmorphM rmorph_sign mulrACA -mulrA signrMK.\nhave norm_eq0 x : norm x = 0 -> x = 0.\n  by move/eqP; rewrite mulf_eq0 fmorph_eq0 -mulf_eq0 -expr2 sqrtK => /eqP.\nhave normM x y : norm (x * y) = norm x * norm y.\n  by rewrite mulrACA -rmorphM; apply: normE; rewrite exprMn !sqrtK.\nhave normN x : norm (- x) = norm x.\n  by rewrite -mulN1r normM {1}/norm iJ mulrN -expr2 sqrtK opprK mul1r.\npose le x y := norm (y - x) == y - x; pose lt x y := (y != x) && le x y.\nhave posE x: le 0 x = (norm x == x) by rewrite /le subr0.\nhave leB x y: le x y = le 0 (y - x) by rewrite posE.\nhave posP x : reflect (exists y, x = y * conj y) (le 0 x).\n  rewrite posE; apply: (iffP eqP) => [Dx | [y {x}->]]; first by exists (sqrt x).\n  by rewrite (normE _ _ (normK y)) rmorphM conjK (mulrC (conj _)) -expr2 normK.\nhave posJ x : le 0 x -> conj x = x.\n  by case/posP=> {x}u ->; rewrite rmorphM conjK mulrC.\nhave pos_linear x y : le 0 x -> le 0 y -> le x y || le y x.\n  move=> pos_x pos_y; rewrite leB -opprB orbC leB !posE normN -eqf_sqr.\n  by rewrite normK rmorphB !posJ ?subrr.\nhave sposDl x y : lt 0 x -> le 0 y -> lt 0 (x + y).\n  have sqrtJ z : le 0 z -> conj (sqrt z) = sqrt z.\n    rewrite posE -{2}[z]sqrtK -subr_eq0 -mulrBr mulf_eq0 subr_eq0.\n    by case/pred2P=> ->; rewrite ?rmorph0.\n  case/andP=> nz_x /sqrtJ uJ /sqrtJ vJ. \n  set u := sqrt x in uJ; set v := sqrt y in vJ; pose w := u + i * v.\n  have ->: x + y = w * conj w.\n    rewrite rmorphD rmorphM iJ uJ vJ mulNr mulrC -subr_sqr sqrMi opprK.\n    by rewrite !sqrtK.\n  apply/andP; split; last by apply/posP; exists w.\n  rewrite -normK expf_eq0 //=; apply: contraNneq nz_x => /norm_eq0 w0.\n  rewrite -[x]sqrtK expf_eq0 /= -/u -(inj_eq mul2I) !mulr2n -{2}(rmorph0 conj).\n  by rewrite -w0 rmorphD rmorphM iJ uJ vJ mulNr addrACA subrr addr0.\nhave sposD x y : lt 0 x -> lt 0 y -> lt 0 (x + y).\n  by move=> x_gt0 /andP[_]; apply: sposDl.\nhave normD x y : le (norm (x + y)) (norm x + norm y).\n  have sposM u v: lt 0 u -> le 0 (u * v) -> le 0 v.\n    by rewrite /lt !posE normM andbC => /andP[/eqP-> /mulfI/inj_eq->].\n  have posD u v: le 0 u -> le 0 v -> le 0 (u + v).\n    have [-> | nz_u u_ge0 v_ge0] := eqVneq u 0; first by rewrite add0r.\n    by have /andP[]: lt 0 (u + v) by rewrite sposDl // /lt nz_u.\n  have le_sqr u v: conj u = u -> le 0 v -> le (u ^+ 2) (v ^+ 2) -> le u v.\n    move=> Ru v_ge0; have [-> // | nz_u] := eqVneq u 0.\n    have [u_gt0 | u_le0 _] := boolP (lt 0 u).    \n      by rewrite leB (leB u) subr_sqr mulrC addrC; apply: sposM; apply: sposDl.\n    rewrite leB posD // posE normN -addr_eq0; apply/eqP.\n    rewrite /lt nz_u posE -subr_eq0 in u_le0; apply: (mulfI u_le0).\n    by rewrite mulr0 -subr_sqr normK Ru subrr.\n  have pos_norm z: le 0 (norm z) by apply/posP; exists (sqrt z).\n  rewrite le_sqr ?posJ ?posD // sqrrD !normK -normM rmorphD mulrDl !mulrDr.\n  rewrite addrA addrC !addrA -(addrC (y * conj y)) !addrA.\n  move: (y * _ + _) => u; rewrite -!addrA leB opprD addrACA {u}subrr add0r -leB.\n  rewrite {}le_sqr ?posD //.\n    by rewrite rmorphD !rmorphM !conjK addrC mulrC (mulrC y).\n  rewrite -mulr2n -mulr_natr exprMn normK -natrX mulr_natr sqrrD mulrACA.\n  rewrite -rmorphM (mulrC y x) addrAC leB mulrnA mulr2n opprD addrACA.\n  rewrite  subrr addr0 {2}(mulrC x) rmorphM mulrACA -opprB addrAC -sqrrB -sqrMi.\n  apply/posP; exists (i * (x * conj y - y * conj x)); congr (_ * _).\n  rewrite !(rmorphM, rmorphB) iJ !conjK mulNr -mulrN opprB.\n  by rewrite (mulrC x) (mulrC y).\nby exists (Num.Mixin normD sposD norm_eq0 pos_linear normM (rrefl _) (rrefl _)).\nQed.\n\nModule Algebraics.\n\nModule Type Specification.\n\nParameter type : Type.\n\nParameter eqMixin : Equality.class_of type.\nCanonical eqType := EqType type eqMixin.\n\nParameter choiceMixin : Choice.mixin_of type.\nCanonical choiceType := ChoiceType type choiceMixin.\n\nParameter countMixin : Countable.mixin_of type.\nCanonical countType := CountType type countMixin.\n\nParameter zmodMixin : GRing.Zmodule.mixin_of type.\nCanonical zmodType := ZmodType type zmodMixin.\nCanonical countZmodType := [countZmodType of type].\n\nParameter ringMixin : GRing.Ring.mixin_of zmodType.\nCanonical ringType := RingType type ringMixin.\nCanonical countRingType := [countRingType of type].\n\nParameter unitRingMixin : GRing.UnitRing.mixin_of ringType.\nCanonical unitRingType := UnitRingType type unitRingMixin.\n\nAxiom mulC : @commutative ringType ringType *%R.\nCanonical comRingType := ComRingType type mulC.\nCanonical comUnitRingType := [comUnitRingType of type].\n\nAxiom idomainAxiom : GRing.IntegralDomain.axiom ringType.\nCanonical idomainType := IdomainType type idomainAxiom.\n\nAxiom fieldMixin : GRing.Field.mixin_of unitRingType.\nCanonical fieldType := FieldType type fieldMixin.\n\nParameter decFieldMixin : GRing.DecidableField.mixin_of unitRingType.\nCanonical decFieldType := DecFieldType type decFieldMixin.\n\nAxiom closedFieldAxiom : GRing.ClosedField.axiom ringType.\nCanonical closedFieldType := ClosedFieldType type closedFieldAxiom.\n\nParameter numMixin : Num.mixin_of ringType.\nCanonical numDomainType := NumDomainType type numMixin.\nCanonical numFieldType := [numFieldType of type].\n\nParameter conj : {rmorphism type -> type}.\nAxiom conjK : involutive conj.\nAxiom normK : forall x, `|x| ^+ 2 = x * conj x.\n\nAxiom algebraic : integralRange (@ratr unitRingType).\n\nEnd Specification.\n\nModule Implementation : Specification.\n\nDefinition L := tag Fundamental_Theorem_of_Algebraics.\n\nDefinition conjL : {rmorphism L -> L} :=\n  s2val (tagged Fundamental_Theorem_of_Algebraics).\n\nFact conjL_K : involutive conjL.\nProof. exact: s2valP (tagged Fundamental_Theorem_of_Algebraics). Qed.\n\nFact conjL_nt : ~ conjL =1 id.\nProof. exact: s2valP' (tagged Fundamental_Theorem_of_Algebraics). Qed.\n\nDefinition LnumMixin := ComplexNumMixin conjL_K conjL_nt.\nDefinition Lnum := NumDomainType L (sval LnumMixin).\n\nDefinition QtoL := [rmorphism of @ratr [numFieldType of Lnum]].\nNotation pQtoL := (map_poly QtoL).\n\nDefinition rootQtoL p_j :=\n  if p_j.1 == 0 then 0 else\n  (sval (closed_field_poly_normal (pQtoL p_j.1)))`_p_j.2.\n\nDefinition eq_root p_j q_k := rootQtoL p_j == rootQtoL q_k.\nFact eq_root_is_equiv : equiv_class_of eq_root.\nProof. by rewrite /eq_root; split=> [ ? | ? ? | ? ? ? ] // /eqP->. Qed.\nCanonical eq_root_equiv := EquivRelPack eq_root_is_equiv.\nDefinition type : Type := {eq_quot eq_root}%qT.\n\nDefinition eqMixin : Equality.class_of type := EquivQuot.eqMixin _.\nCanonical eqType := EqType type eqMixin.\n\nDefinition choiceMixin : Choice.mixin_of type := EquivQuot.choiceMixin _.\nCanonical choiceType := ChoiceType type choiceMixin.\n\nDefinition countMixin : Countable.mixin_of type := CanCountMixin (@reprK _ _).\nCanonical countType := CountType type countMixin.\n\nDefinition CtoL (u : type) := rootQtoL (repr u).\n\nFact CtoL_inj : injective CtoL.\nProof. by move=> u v /eqP eq_uv; rewrite -[u]reprK -[v]reprK; apply/eqmodP. Qed.\n\nFact CtoL_P u : integralOver QtoL (CtoL u).\nProof.\nrewrite /CtoL /rootQtoL; case: (repr u) => p j /=.\ncase: (closed_field_poly_normal _) => r Dp /=.\ncase: ifPn => [_ | nz_p]; first exact: integral0.\nhave [/(nth_default 0)-> | lt_j_r] := leqP (size r) j; first exact: integral0.\napply/integral_algebraic; exists p; rewrite // Dp -mul_polyC rootM orbC.\nby rewrite root_prod_XsubC mem_nth.\nQed.\n\nFact LtoC_subproof z : integralOver QtoL z -> {u | CtoL u = z}.\nProof.\ncase/sig2_eqW=> p mon_p pz0; rewrite /CtoL.\npose j := index z (sval (closed_field_poly_normal (pQtoL p))).\npose u := \\pi_type%qT (p, j); exists u; have /eqmodP/eqP-> := reprK u.\nrewrite /rootQtoL -if_neg monic_neq0 //; apply: nth_index => /=.\ncase: (closed_field_poly_normal _) => r /= Dp.\nby rewrite Dp (monicP _) ?(monic_map QtoL) // scale1r root_prod_XsubC in pz0.\nQed.\n\nDefinition LtoC z Az := sval (@LtoC_subproof z Az).\nFact LtoC_K z Az : CtoL (@LtoC z Az) = z.\nProof. exact: (svalP (LtoC_subproof Az)). Qed.\n\nFact CtoL_K u : LtoC (CtoL_P u) = u.\nProof. by apply: CtoL_inj; rewrite LtoC_K. Qed.\n\nDefinition zero := LtoC (integral0 _).\nDefinition add u v := LtoC (integral_add (CtoL_P u) (CtoL_P v)).\nDefinition opp u := LtoC (integral_opp (CtoL_P u)).\n\nFact addA : associative add.\nProof. by move=> u v w; apply: CtoL_inj; rewrite !LtoC_K addrA. Qed.\n\nFact addC : commutative add.\nProof. by move=> u v; apply: CtoL_inj; rewrite !LtoC_K addrC. Qed.\n\nFact add0 : left_id zero add.\nProof. by move=> u; apply: CtoL_inj; rewrite !LtoC_K add0r. Qed.\n\nFact addN : left_inverse zero opp add.\nProof. by move=> u; apply: CtoL_inj; rewrite !LtoC_K addNr. Qed.\n\nDefinition zmodMixin := ZmodMixin addA addC add0 addN.\nCanonical zmodType := ZmodType type zmodMixin.\nCanonical countZmodType := [countZmodType of type].\n\nFact CtoL_is_additive : additive CtoL.\nProof. by move=> u v; rewrite !LtoC_K. Qed.\nCanonical CtoL_additive := Additive CtoL_is_additive.\n\nDefinition one := LtoC (integral1 _).\nDefinition mul u v := LtoC (integral_mul (CtoL_P u) (CtoL_P v)).\nDefinition inv u := LtoC (integral_inv (CtoL_P u)).\n\nFact mulA : associative mul.\nProof. by move=> u v w; apply: CtoL_inj; rewrite !LtoC_K mulrA. Qed.\n\nFact mulC : commutative mul.\nProof. by move=> u v; apply: CtoL_inj; rewrite !LtoC_K mulrC. Qed.\n\nFact mul1 : left_id one mul.\nProof. by move=> u; apply: CtoL_inj; rewrite !LtoC_K mul1r. Qed.\n\nFact mulD : left_distributive mul +%R.\nProof. by move=> u v w; apply: CtoL_inj; rewrite !LtoC_K mulrDl. Qed.\n\nFact one_nz : one != 0 :> type.\nProof. by rewrite -(inj_eq CtoL_inj) !LtoC_K oner_eq0. Qed.\n\nDefinition ringMixin := ComRingMixin mulA mulC mul1 mulD one_nz.\nCanonical ringType := RingType type ringMixin.\nCanonical comRingType := ComRingType type mulC.\nCanonical countRingType := [countRingType of type].\n\nFact CtoL_is_multiplicative : multiplicative CtoL.\nProof. by split=> [u v|]; rewrite !LtoC_K. Qed.\nCanonical CtoL_rmorphism := AddRMorphism CtoL_is_multiplicative.\n\nFact mulVf : GRing.Field.axiom inv.\nProof.\nmove=> u; rewrite -(inj_eq CtoL_inj) rmorph0 => nz_u.\nby apply: CtoL_inj; rewrite !LtoC_K mulVf.\nQed.\nFact inv0 : inv 0 = 0. Proof. by apply: CtoL_inj; rewrite !LtoC_K invr0. Qed.\n\nDefinition unitRingMixin := FieldUnitMixin mulVf inv0.\nCanonical unitRingType := UnitRingType type unitRingMixin.\nCanonical comUnitRingType := [comUnitRingType of type].\n\nDefinition fieldMixin := @FieldMixin _ _ mulVf inv0.\nDefinition idomainAxiom := FieldIdomainMixin fieldMixin.\nCanonical idomainType := IdomainType type idomainAxiom.\nCanonical fieldType := FieldType type fieldMixin.\n\nFact closedFieldAxiom : GRing.ClosedField.axiom ringType.\nProof.\nmove=> n a n_gt0; pose p := 'X^n - \\poly_(i < n) CtoL (a i).\nhave Ap: {in p : seq L, integralRange QtoL}.\n  move=> _ /(nthP 0)[j _ <-]; rewrite coefB coefXn coef_poly.\n  apply: integral_sub; first exact: integral_nat.\n  by case: ifP => _; [apply: CtoL_P | apply: integral0].\nhave sz_p: size p = n.+1.\n  by rewrite size_addl size_polyXn // size_opp ltnS size_poly.\nhave [z pz0]: exists z, root p z by apply/closed_rootP; rewrite sz_p eqSS -lt0n.\nhave Az: integralOver ratr z.\n  by apply: integral_root Ap; rewrite // -size_poly_gt0 sz_p.\nexists (LtoC Az); apply/CtoL_inj; rewrite -[CtoL _]subr0 -(rootP pz0).\nrewrite rmorphX /= LtoC_K hornerD hornerXn hornerN opprD addNKr opprK.\nrewrite horner_poly rmorph_sum; apply: eq_bigr => k _.\nby rewrite rmorphM rmorphX /= LtoC_K.\nQed.\n\nDefinition decFieldMixin := closed_field.closed_fields_QEMixin closedFieldAxiom.\nCanonical decFieldType := DecFieldType type decFieldMixin.\nCanonical closedFieldType := ClosedFieldType type closedFieldAxiom.\n\nFact conj_subproof u : integralOver QtoL (conjL (CtoL u)).\nProof.\nhave [p mon_p pu0] := CtoL_P u; exists p => //.\nrewrite -(fmorph_root conjL) conjL_K map_poly_id // => _ /(nthP 0)[j _ <-].\nby rewrite coef_map fmorph_rat.\nQed.\nFact conj_is_rmorphism : rmorphism (fun u => LtoC (conj_subproof u)).\nProof.\ndo 2?split=> [u v|]; apply: CtoL_inj; last by rewrite !LtoC_K rmorph1.\n- by rewrite LtoC_K 3!{1}rmorphB /= !LtoC_K.\nby rewrite LtoC_K 3!{1}rmorphM /= !LtoC_K.\nQed.\nDefinition conj : {rmorphism type -> type} := RMorphism conj_is_rmorphism.\nLemma conjK : involutive conj.\nProof. by move=> u; apply: CtoL_inj; rewrite !LtoC_K conjL_K. Qed.\n\nFact conj_nt : ~ conj =1 id.\nProof. \nhave [i i2]: exists i : type, i ^+ 2 = -1.\n  have [i] := @solve_monicpoly _ 2 (nth 0 [:: -1 : type]) isT.\n  by rewrite !big_ord_recl big_ord0 /= mul0r mulr1 !addr0; exists i.\nmove/(_ i)/(congr1 CtoL); rewrite LtoC_K => iL_J.\nhave/ltr_geF/idP[] := @ltr01 Lnum; rewrite -oppr_ge0 -(rmorphN1 CtoL_rmorphism).\nrewrite -i2 rmorphX /= expr2 -{2}iL_J -(svalP LnumMixin).\nby rewrite exprn_ge0 ?normr_ge0.\nQed.\n\nDefinition numMixin := sval (ComplexNumMixin conjK conj_nt).\nCanonical numDomainType := NumDomainType type numMixin.\nCanonical numFieldType := [numFieldType of type].\n\nLemma normK u : `|u| ^+ 2 = u * conj u.\nProof. exact: svalP (ComplexNumMixin conjK conj_nt) u. Qed.\n\nLemma algebraic : integralRange (@ratr unitRingType).\nProof.\nmove=> u; have [p mon_p pu0] := CtoL_P u; exists p => {mon_p}//.\nrewrite -(fmorph_root CtoL_rmorphism) -map_poly_comp; congr (root _ _): pu0.\nby apply/esym/eq_map_poly; apply: fmorph_eq_rat.\nQed.\n\nEnd Implementation.\n\nDefinition divisor := Implementation.type.\n\nModule Internals.\n\nImport Implementation.\n\nLocal Notation algC := type.\nLocal Notation \"z ^*\" := (conj z) (at level 2, format \"z ^*\") : ring_scope.\nLocal Notation QtoC := (ratr : rat -> algC).\nLocal Notation QtoCm := [rmorphism of QtoC].\nLocal Notation pQtoC := (map_poly QtoC).\nLocal Notation ZtoQ := (intr : int -> rat).\nLocal Notation ZtoC := (intr : int -> algC).\nLocal Notation Creal := (Num.real : qualifier 0 algC).\n\nFact algCi_subproof : {i : algC | i ^+ 2 = -1}.\nProof. exact: imaginary_exists. Qed.\n\nLet Re2 z := z + z^*.\nDefinition nnegIm z := 0 <= sval algCi_subproof * (z^* - z).\nDefinition argCle y z := nnegIm z ==> nnegIm y && (Re2 z <= Re2 y).\n\nCoInductive rootC_spec n (x : algC) : Type :=\n  RootCspec (y : algC) of if (n > 0)%N then y ^+ n = x else y = 0\n                        & forall z, (n > 0)%N -> z ^+ n = x -> argCle y z.\n\nFact rootC_subproof n x : rootC_spec n x.\nProof.\nhave realRe2 u : Re2 u \\is Creal.\n  rewrite realEsqr expr2 {2}/Re2 -{2}[u]conjK addrC -rmorphD -normK.\n  by rewrite exprn_ge0 ?normr_ge0.\nhave argCtotal : total argCle.\n  move=> u v; rewrite /total /argCle.\n  by do 2!case: (nnegIm _) => //; rewrite ?orbT //= real_leVge.\nhave argCtrans : transitive argCle.\n  move=> u v w /implyP geZuv /implyP geZvw; apply/implyP.\n  by case/geZvw/andP=> /geZuv/andP[-> geRuv] /ler_trans->.\npose p := 'X^n - (x *+ (n > 0))%:P; have [r0 Dp] := closed_field_poly_normal p.\nhave sz_p: size p = n.+1.\n  rewrite size_addl ?size_polyXn // ltnS size_opp size_polyC mulrn_eq0.\n  by case: posnP => //; case: negP.\npose r := sort argCle r0; have r_arg: sorted argCle r by apply: sort_sorted.\nhave{Dp} Dp: p = \\prod_(z <- r) ('X - z%:P).\n  rewrite Dp lead_coefE sz_p coefB coefXn coefC -mulrb -mulrnA mulnb lt0n andNb.\n  rewrite subr0 eqxx scale1r; apply: eq_big_perm.\n  by rewrite perm_eq_sym perm_sort.\nhave mem_rP z: (n > 0)%N -> reflect (z ^+ n = x) (z \\in r).\n  move=> n_gt0; rewrite -root_prod_XsubC -Dp rootE !hornerE hornerXn n_gt0.\n  by rewrite subr_eq0; apply: eqP.\nexists r`_0 => [|z n_gt0 /(mem_rP z n_gt0) r_z].\n  have sz_r: size r = n by apply: succn_inj; rewrite -sz_p Dp size_prod_XsubC.\n  case: posnP => [n0 | n_gt0]; first by rewrite nth_default // sz_r n0.\n  by apply/mem_rP=> //; rewrite mem_nth ?sz_r.\ncase: {Dp mem_rP}r r_z r_arg => // y r1; rewrite inE => /predU1P[-> _|r1z].\n  by apply/implyP=> ->; rewrite lerr.\nby move/(order_path_min argCtrans)/allP->.\nQed.\n\nCoInductive getCrat_spec : Type := GetCrat_spec CtoQ of cancel QtoC CtoQ.\n\nFact getCrat_subproof : getCrat_spec.\nProof.\nhave isQ := rat_algebraic_decidable algebraic.\nexists (fun z => if isQ z is left Qz then sval (sig_eqW Qz) else 0) => a.\ncase: (isQ _) => [Qa | []]; last by exists a.\nby case: (sig_eqW _) => b /= /fmorph_inj.\nQed.\n\nFact floorC_subproof x : {m | x \\is Creal -> ZtoC m <= x < ZtoC (m + 1)}.\nProof.\nhave [Rx | _] := boolP (x \\is Creal); last by exists 0.\nwithout loss x_ge0: x Rx / x >= 0.\n  have [x_ge0 | /ltrW x_le0] := real_ger0P Rx; first exact.\n  case/(_ (- x)) => [||m /(_ isT)]; rewrite ?rpredN ?oppr_ge0 //.\n  rewrite ler_oppr ltr_oppl -!rmorphN opprD /= ltr_neqAle ler_eqVlt.\n  case: eqP => [-> _ | _ /and3P[lt_x_m _ le_m_x]].\n    by exists (- m) => _; rewrite lerr rmorphD ltr_addl ltr01.\n  by exists (- m - 1); rewrite le_m_x subrK.\nhave /ex_minnP[n lt_x_n1 min_n]: exists n, x < n.+1%:R.\n  have [n le_x_n] := rat_algebraic_archimedean algebraic x.\n  by exists n; rewrite -(ger0_norm x_ge0) (ltr_trans le_x_n) ?ltr_nat.\nexists n%:Z => _; rewrite addrC -intS lt_x_n1 andbT.\ncase Dn: n => // [n1]; rewrite -Dn.\nhave [||//|] := @real_lerP _ n%:R x; rewrite ?rpred_nat //.\nby rewrite Dn => /min_n; rewrite Dn ltnn.\nQed.\n\nFact minCpoly_subproof (x : algC) :\n  {p | p \\is monic & forall q, root (pQtoC q) x = (p %| q)%R}.\nProof.\nhave isQ := rat_algebraic_decidable algebraic.\nhave [p [mon_p px0 irr_p]] := minPoly_decidable_closure isQ (algebraic x).\nexists p => // q; apply/idP/idP=> [qx0 | /dvdpP[r ->]]; last first.\n  by rewrite rmorphM rootM px0 orbT.\nsuffices /eqp_dvdl <-: gcdp p q %= p by apply: dvdp_gcdr.\nrewrite irr_p ?dvdp_gcdl ?gtn_eqF // -(size_map_poly QtoCm) gcdp_map /=.\nrewrite (@root_size_gt1 _ x) ?root_gcd ?px0 //.\nby rewrite gcdp_eq0 negb_and map_poly_eq0 monic_neq0.\nQed.\n\nDefinition algC_divisor (x : algC) := x : divisor.\nDefinition int_divisor m := m%:~R : divisor.\nDefinition nat_divisor n := n%:R : divisor.\n\nEnd Internals.\n\nModule Import Exports.\n\nImport Implementation Internals.\n\nNotation algC := type.\nNotation conjC := conj.\nDelimit Scope C_scope with C.\nDelimit Scope C_core_scope with Cc.\nDelimit Scope C_expanded_scope with Cx.\nOpen Scope C_core_scope.\nNotation \"x ^*\" := (conjC x) (at level 2, format \"x ^*\") : C_core_scope.\nNotation \"x ^*\" := x^* (only parsing) : C_scope.\n\nCanonical eqType.\nCanonical choiceType.\nCanonical countType.\nCanonical zmodType.\nCanonical countZmodType.\nCanonical ringType.\nCanonical countRingType.\nCanonical unitRingType.\nCanonical comRingType.\nCanonical comUnitRingType.\nCanonical idomainType.\nCanonical numDomainType.\nCanonical fieldType.\nCanonical numFieldType.\nCanonical decFieldType.\nCanonical closedFieldType.\n\nNotation algCeq := eqType.\nNotation algCzmod := zmodType.\nNotation algCring := ringType.\nNotation algCuring := unitRingType.\nNotation algCnum := numDomainType.\nNotation algCfield := fieldType.\nNotation algCnumField := numFieldType.\n\nDefinition rootC n x := let: RootCspec y _ _ := rootC_subproof n x in y.\nNotation \"n .-root\" := (rootC n) (at level 2, format \"n .-root\") : C_core_scope.\nNotation \"n .-root\" := (rootC n) (only parsing) : C_scope.\nNotation sqrtC := 2.-root.\n\nDefinition algCi := sqrtC (-1).\nNotation \"'i\" := algCi (at level 0) : C_core_scope.\nNotation \"'i\" := 'i (only parsing) : C_scope.\n\nDefinition algRe x := (x + x^*) / 2%:R.\nDefinition algIm x := 'i * (x^* - x) / 2%:R.\nNotation \"'Re z\" := (algRe z) (at level 10, z at level 8) : C_core_scope.\nNotation \"'Im z\" := (algIm z) (at level 10, z at level 8) : C_core_scope.\nNotation \"'Re z\" := ('Re z) (only parsing) : C_scope.\nNotation \"'Im z\" := ('Im z) (only parsing) : C_scope.\n\nNotation Creal := (@Num.Def.Rreal numDomainType).\n\nDefinition getCrat := let: GetCrat_spec CtoQ _ := getCrat_subproof in CtoQ.\nDefinition Crat : pred_class := fun x : algC => ratr (getCrat x) == x.\n\nDefinition floorC x := sval (floorC_subproof x).\nDefinition Cint : pred_class := fun x : algC => (floorC x)%:~R == x.\n\nDefinition truncC x := if x >= 0 then `|floorC x|%N else 0%N.\nDefinition Cnat : pred_class := fun x : algC => (truncC x)%:R == x.\n\nDefinition minCpoly x : {poly algC} :=\n  let: exist2 p _ _ := minCpoly_subproof x in map_poly ratr p.\n\nCoercion nat_divisor : nat >-> divisor.\nCoercion int_divisor : int >-> divisor.\nCoercion algC_divisor : algC >-> divisor.\n\nLemma nCdivE (p : nat) : p = p%:R :> divisor. Proof. by []. Qed.\nLemma zCdivE (p : int) : p = p%:~R :> divisor. Proof. by []. Qed.\nDefinition CdivE := (nCdivE, zCdivE).\n\nDefinition dvdC (x : divisor) : pred_class :=\n   fun y : algC => if x == 0 then y == 0 else y / x \\in Cint.\nNotation \"x %| y\" := (y \\in dvdC x) : C_expanded_scope.\nNotation \"x %| y\" := (@in_mem divisor y (mem (dvdC x))) : C_scope.\n\nDefinition eqCmod (e x y : divisor) := (e %| x - y)%C.\n\nNotation \"x == y %[mod e ]\" := (eqCmod e x y) : C_scope.\nNotation \"x != y %[mod e ]\" := (~~ (x == y %[mod e])%C) : C_scope.\n\nEnd Exports.\n\nEnd Algebraics.\n\nExport Algebraics.Exports.\n\nSection AlgebraicsTheory.\n\nImplicit Types (x y z : algC) (n : nat) (m : int) (b : bool).\nImport Algebraics.Internals.\n\nLocal Notation ZtoQ := (intr : int -> rat).\nLocal Notation ZtoC := (intr : int -> algC).\nLocal Notation QtoC := (ratr : rat -> algC).\nLocal Notation QtoCm := [rmorphism of QtoC].\nLocal Notation CtoQ := getCrat.\nLocal Notation intrp := (map_poly intr).\nLocal Notation pZtoQ := (map_poly ZtoQ).\nLocal Notation pZtoC := (map_poly ZtoC).\nLocal Notation pQtoC := (map_poly ratr).\nLocal Hint Resolve (@intr_inj _ : injective ZtoC).\n\n(* Specialization of a few basic ssrnum order lemmas. *)\n\nDefinition eqC_nat n p : (n%:R == p%:R :> algC) = (n == p) := eqr_nat _ n p.\nDefinition leC_nat n p : (n%:R <= p%:R :> algC) = (n <= p)%N := ler_nat _ n p.\nDefinition ltC_nat n p : (n%:R < p%:R :> algC) = (n < p)%N := ltr_nat _ n p.\nDefinition Cchar : [char algC] =i pred0 := @char_num _.\n\n(* This can be used in the converse direction to evaluate assertions over     *)\n(* manifest rationals, such as 3%:R^-1 + 7%:%^-1 < 2%:%^-1 :> algC.           *)\n(* Missing norm and integer exponent, due to gaps in ssrint and rat.          *)\nDefinition CratrE :=\n  let CnF := Algebraics.Implementation.numFieldType in\n  let QtoCm := ratr_rmorphism CnF in\n  ((rmorph0 QtoCm, rmorph1 QtoCm, rmorphMn QtoCm, rmorphN QtoCm, rmorphD QtoCm),\n   (rmorphM QtoCm, rmorphX QtoCm, fmorphV QtoCm),\n   (rmorphMz QtoCm, rmorphXz QtoCm, @ratr_norm CnF, @ratr_sg CnF),\n   =^~ (@ler_rat CnF, @ltr_rat CnF, (inj_eq (fmorph_inj QtoCm)))).\n\nDefinition CintrE :=\n  let CnF := Algebraics.Implementation.numFieldType in\n  let ZtoCm := intmul1_rmorphism CnF in\n  ((rmorph0 ZtoCm, rmorph1 ZtoCm, rmorphMn ZtoCm, rmorphN ZtoCm, rmorphD ZtoCm),\n   (rmorphM ZtoCm, rmorphX ZtoCm),\n   (rmorphMz ZtoCm, @intr_norm CnF, @intr_sg CnF),\n   =^~ (@ler_int CnF, @ltr_int CnF, (inj_eq (@intr_inj CnF)))).\n\nLet nz2 : 2%:R != 0 :> algC. Proof. by rewrite -!CintrE. Qed.\n\n(* Conjugation and norm. *)\n\nDefinition conjCK : involutive conjC := Algebraics.Implementation.conjK.\nDefinition normCK x : `|x| ^+ 2 = x * x^* := Algebraics.Implementation.normK x.\nDefinition algC_algebraic x := Algebraics.Implementation.algebraic x.\n\nLemma normCKC x : `|x| ^+ 2 = x^* * x. Proof. by rewrite normCK mulrC. Qed.\n\nLemma mul_conjC_ge0 x : 0 <= x * x^*.\nProof. by rewrite -normCK exprn_ge0 ?normr_ge0. Qed.\n\nLemma mul_conjC_gt0 x : (0 < x * x^*) = (x != 0).\nProof. \nhave [->|x_neq0] := altP eqP; first by rewrite rmorph0 mulr0.\nby rewrite -normCK exprn_gt0 ?normr_gt0.\nQed.\n\nLemma mul_conjC_eq0 x : (x * x^* == 0) = (x == 0).\nProof. by rewrite -normCK expf_eq0 normr_eq0. Qed.\n\nLemma conjC_ge0 x : (0 <= x^*) = (0 <= x).\nProof.\nwlog suffices: x / 0 <= x -> 0 <= x^*.\n  by move=> IH; apply/idP/idP=> /IH; rewrite ?conjCK.\nrewrite le0r => /predU1P[-> | x_gt0]; first by rewrite rmorph0.\nby rewrite -(pmulr_rge0 _ x_gt0) mul_conjC_ge0.\nQed.\n\nLemma conjC_nat n : (n%:R)^* = n%:R. Proof. exact: rmorph_nat. Qed.\nLemma conjC0 : 0^* = 0. Proof. exact: rmorph0. Qed.\nLemma conjC1 : 1^* = 1. Proof. exact: rmorph1. Qed.\nLemma conjC_eq0 x : (x^* == 0) = (x == 0). Proof. exact: fmorph_eq0. Qed.\n\nLemma invC_norm x : x^-1 = `|x| ^- 2 * x^*.\nProof.\nhave [-> | nx_x] := eqVneq x 0; first by rewrite conjC0 mulr0 invr0.\nby rewrite normCK invfM divfK ?conjC_eq0.\nQed.\n\n(* Real number subset. *)\n\nLemma Creal0 : 0 \\is Creal. Proof. exact: rpred0. Qed.\nLemma Creal1 : 1 \\is Creal. Proof. exact: rpred1. Qed.\nHint Resolve Creal0 Creal1. (* Trivial cannot resolve a general real0 hint. *)\n\nLemma CrealE x : (x \\is Creal) = (x^* == x).\nProof.\nrewrite realEsqr ger0_def normrX normCK.\nby have [-> | /mulfI/inj_eq-> //] := eqVneq x 0; rewrite rmorph0 !eqxx.\nQed.\n\nLemma CrealP {x} : reflect (x^* = x) (x \\is Creal).\nProof. by rewrite CrealE; apply: eqP. Qed.\n\nLemma conj_Creal x : x \\is Creal -> x^* = x.\nProof. by move/CrealP. Qed.\n\nLemma conj_normC z : `|z|^* = `|z|.\nProof. by rewrite conj_Creal ?normr_real. Qed.\n\nLemma geC0_conj x : 0 <= x -> x^* = x.\nProof. by move=> /ger0_real/CrealP. Qed.\n\nLemma geC0_unit_exp x n : 0 <= x -> (x ^+ n.+1 == 1) = (x == 1).\nProof. by move=> x_ge0; rewrite pexpr_eq1. Qed.\n\n(* Elementary properties of roots. *)\n\nLtac case_rootC := rewrite /rootC; case: (rootC_subproof _ _).\n\nLemma root0C x : 0.-root x = 0. Proof. by case_rootC. Qed.\n\nLemma rootCK n : (n > 0)%N -> cancel n.-root (fun x => x ^+ n).\nProof. by case: n => //= n _ x; case_rootC. Qed.\n\nLemma root1C x : 1.-root x = x. Proof. exact: (@rootCK 1). Qed.\n\nLemma rootC0 n : n.-root 0 = 0.\nProof.\nhave [-> | n_gt0] := posnP n; first by rewrite root0C.\nby have /eqP := rootCK n_gt0 0; rewrite expf_eq0 n_gt0 /= => /eqP.\nQed.\n\nLemma rootC_inj n : (n > 0)%N -> injective n.-root.\nProof. by move/rootCK/can_inj. Qed.\n\nLemma eqr_rootC n : (n > 0)%N -> {mono n.-root : x y / x == y}.\nProof. by move/rootC_inj/inj_eq. Qed.\n\nLemma rootC_eq0 n x : (n > 0)%N -> (n.-root x == 0) = (x == 0).\nProof. by move=> n_gt0; rewrite -{1}(rootC0 n) eqr_rootC. Qed.\n\n(* Rectangular coordinates. *)\n\nLemma sqrCi : 'i ^+ 2 = -1. Proof. exact: rootCK. Qed.\n\nLemma nonRealCi : 'i \\isn't Creal.\nProof. by rewrite realEsqr sqrCi oppr_ge0 ltr_geF ?ltr01. Qed.\n\nLemma neq0Ci : 'i != 0.\nProof. by apply: contraNneq nonRealCi => ->; apply: real0. Qed.\n\nLemma normCi : `|'i| = 1.\nProof.\napply/eqP; rewrite -(@pexpr_eq1 _ _ 2) ?normr_ge0 //.\nby rewrite -normrX sqrCi normrN1.\nQed.\n\nLemma invCi : 'i^-1 = - 'i.\nProof. by rewrite -div1r -[1]opprK -sqrCi mulNr mulfK ?neq0Ci. Qed.\n\nLemma conjCi : 'i^* = - 'i.\nProof. by rewrite -invCi invC_norm normCi expr1n invr1 mul1r. Qed.\n\nLemma algCrect x : x = 'Re x + 'i * 'Im x.\nProof. \nrewrite 2!mulrA -expr2 sqrCi mulN1r opprB -mulrDl addrACA subrr addr0.\nby rewrite -mulr2n -mulr_natr mulfK.\nQed.\n\nLemma Creal_Re x : 'Re x \\is Creal.\nProof. by rewrite CrealE fmorph_div rmorph_nat rmorphD conjCK addrC. Qed.\n\nLemma Creal_Im x : 'Im x \\is Creal.\nProof.\nrewrite CrealE fmorph_div rmorph_nat rmorphM rmorphB conjCK.\nby rewrite conjCi -opprB mulrNN.\nQed.\nHint Resolve Creal_Re Creal_Im.\n\nFact algRe_is_additive : additive algRe.\nProof. by move=> x y; rewrite /algRe rmorphB addrACA -opprD mulrBl. Qed.\nCanonical algRe_additive := Additive algRe_is_additive.\n\nFact algIm_is_additive : additive algIm.\nProof.\nby move=> x y; rewrite /algIm rmorphB opprD addrACA -opprD mulrBr mulrBl.\nQed.\nCanonical algIm_additive := Additive algIm_is_additive.\n\nLemma Creal_ImP z : reflect ('Im z = 0) (z \\is Creal).\nProof.\nrewrite CrealE -subr_eq0 -(can_eq (mulKf neq0Ci)) mulr0.\nby rewrite -(can_eq (divfK nz2)) mul0r; apply: eqP.\nQed.\n\nLemma Creal_ReP z : reflect ('Re z = z) (z \\in Creal).\nProof.\nrewrite (sameP (Creal_ImP z) eqP) -(can_eq (mulKf neq0Ci)) mulr0.\nby rewrite -(inj_eq (addrI ('Re z))) addr0 -algCrect eq_sym; apply: eqP.\nQed.\n\nLemma algReMl : {in Creal, forall x, {morph algRe : z / x * z}}.\nProof.\nby move=> x Rx z /=; rewrite /algRe rmorphM (conj_Creal Rx) -mulrDr -mulrA.\nQed.\n\nLemma algReMr : {in Creal, forall x, {morph algRe : z / z * x}}.\nProof. by move=> x Rx z /=; rewrite mulrC algReMl // mulrC. Qed.\n\nLemma algImMl : {in Creal, forall x, {morph algIm : z / x * z}}.\nProof.\nby move=> x Rx z; rewrite /algIm rmorphM (conj_Creal Rx) -mulrBr mulrCA !mulrA.\nQed.\n\nLemma algImMr : {in Creal, forall x, {morph algIm : z / z * x}}.\nProof. by move=> x Rx z /=; rewrite mulrC algImMl // mulrC. Qed.\n\nLemma algRe_i : 'Re 'i = 0. Proof. by rewrite /algRe conjCi subrr mul0r. Qed.\n\nLemma algIm_i : 'Im 'i = 1.\nProof.\nrewrite /algIm conjCi -opprD mulrN -mulr2n mulrnAr ['i * _]sqrCi.\nby rewrite mulNrn opprK divff.\nQed.\n\nLemma algRe_conj z : 'Re z^* = 'Re z.\nProof. by rewrite /algRe addrC conjCK. Qed.\n\nLemma algIm_conj z : 'Im z^* = - 'Im z.\nProof. by rewrite /algIm -mulNr -mulrN opprB conjCK. Qed.\n\nLemma algRe_rect : {in Creal &, forall x y, 'Re (x + 'i * y) = x}.\nProof.\nmove=> x y Rx Ry; rewrite /= raddfD /= (Creal_ReP x Rx).\nby rewrite algReMr // algRe_i mul0r addr0.\nQed.\n\nLemma algIm_rect : {in Creal &, forall x y, 'Im (x + 'i * y) = y}.\nProof.\nmove=> x y Rx Ry; rewrite /= raddfD /= (Creal_ImP x Rx) add0r.\nby rewrite algImMr // algIm_i mul1r.\nQed.\n\nLemma conjC_rect : {in Creal &, forall x y, (x + 'i * y)^* = x - 'i * y}.\nProof.\nby move=> x y Rx Ry; rewrite /= rmorphD rmorphM conjCi mulNr !conj_Creal.\nQed.\n\nLemma addC_rect x1 y1 x2 y2 :\n  (x1 + 'i * y1) + (x2 + 'i * y2) = x1 + x2 + 'i * (y1 + y2).\nProof. by rewrite addrACA -mulrDr. Qed.\n\nLemma oppC_rect x y : - (x + 'i * y)  = - x + 'i * (- y).\nProof. by rewrite mulrN -opprD. Qed.\n\nLemma subC_rect x1 y1 x2 y2 :\n  (x1 + 'i * y1) - (x2 + 'i * y2) = x1 - x2 + 'i * (y1 - y2).\nProof. by rewrite oppC_rect addC_rect. Qed.\n\nLemma mulC_rect x1 y1 x2 y2 :\n  (x1 + 'i * y1) * (x2 + 'i * y2)\n      = x1 * x2 - y1 * y2 + 'i * (x1 * y2 + x2 * y1).\nProof.\nrewrite mulrDl !mulrDr mulrCA -!addrA mulrAC -mulrA; congr (_ + _).\nby rewrite mulrACA -expr2 sqrCi mulN1r addrA addrC. \nQed.\n\nLemma normC2_rect :\n  {in Creal &, forall x y, `|x + 'i * y| ^+ 2 = x ^+ 2 + y ^+ 2}.\nProof.\nmove=> x y Rx Ry; rewrite /= normCK rmorphD rmorphM conjCi !conj_Creal //.\nby rewrite mulrC mulNr -subr_sqr exprMn sqrCi mulN1r opprK.\nQed.\n\nLemma normC2_Re_Im z : `|z| ^+ 2 = 'Re z ^+ 2 + 'Im z ^+ 2.\nProof. by rewrite -normC2_rect -?algCrect. Qed.\n\nLemma invC_rect :\n  {in Creal &, forall x y, (x + 'i * y)^-1  = (x - 'i * y) / (x ^+ 2 + y ^+ 2)}.\nProof.\nby move=> x y Rx Ry; rewrite /= invC_norm conjC_rect // mulrC normC2_rect.\nQed.\n\nLemma lerif_normC_Re_Creal z : `|'Re z| <= `|z| ?= iff (z \\is Creal).\nProof.\nrewrite -(mono_in_lerif ler_sqr); try by rewrite qualifE normr_ge0.\nrewrite normCK conj_Creal // normC2_Re_Im -expr2.\nrewrite addrC -lerif_subLR subrr (sameP (Creal_ImP _) eqP) -sqrf_eq0 eq_sym.\nby apply: lerif_eq; rewrite -realEsqr.\nQed.\n\nLemma lerif_Re_Creal z : 'Re z <= `|z| ?= iff (0 <= z).\nProof.\nhave ubRe: 'Re z <= `|'Re z| ?= iff (0 <= 'Re z).\n  by rewrite ger0_def eq_sym; apply/lerif_eq/real_ler_norm.\ncongr (_ <= _ ?= iff _): (lerif_trans ubRe (lerif_normC_Re_Creal z)).\napply/andP/idP=> [[zRge0 /Creal_ReP <- //] | z_ge0].\nby have Rz := ger0_real z_ge0; rewrite (Creal_ReP _ _).\nQed.\n\n(* Equality from polar coordinates, for the upper plane. *)\nLemma eqC_semipolar x y :\n  `|x| = `|y| -> 'Re x = 'Re y -> 0 <= 'Im x * 'Im y -> x = y.\nProof.\nmove=> eq_norm eq_Re sign_Im.\nrewrite [x]algCrect [y]algCrect eq_Re; congr (_ + 'i * _).\nhave /eqP := congr1 (fun z => z ^+ 2) eq_norm.\nrewrite !normC2_Re_Im eq_Re (can_eq (addKr _)) eqf_sqr => /pred2P[] // eq_Im.\nrewrite eq_Im mulNr -expr2 oppr_ge0 real_exprn_even_le0 //= in sign_Im.\nby rewrite eq_Im (eqP sign_Im) oppr0.\nQed.\n\n(* Nth roots. *)\n\nLet argCleP y z :\n  reflect (0 <= 'Im z -> 0 <= 'Im y /\\ 'Re z <= 'Re y) (argCle y z).\nProof.\nsuffices dIm x: nnegIm x = (0 <= 'Im x).\n  rewrite /argCle !dIm ler_pmul2r ?invr_gt0 ?ltr0n //.\n  by apply: (iffP implyP) => geZyz /geZyz/andP.\nrewrite /('Im x) pmulr_lge0 ?invr_gt0 ?ltr0n //; congr (0 <= _ * _).\ncase Du: algCi_subproof => [u u2N1] /=.\nhave/eqP := u2N1; rewrite -sqrCi eqf_sqr => /pred2P[] //.\nhave:= conjCi; rewrite /'i; case_rootC => /= v v2n1 min_v conj_v Duv.\nhave{min_v} /idPn[] := min_v u isT u2N1; rewrite negb_imply /nnegIm Du /= Duv.\nrewrite rmorphN conj_v opprK -opprD mulrNN mulNr -mulr2n mulrnAr -expr2 v2n1.\nby rewrite mulNrn opprK ler0n oppr_ge0 (leC_nat 2 0).\nQed.\n\nLemma rootC_Re_max n x y :\n  (n > 0)%N -> y ^+ n = x -> 0 <= 'Im y -> 'Re y <= 'Re (n.-root%C x).\nProof.\nby move=> n_gt0 yn_x leI0y; case_rootC=> z /= _ /(_ y n_gt0 yn_x)/argCleP[].\nQed.\n\nLet neg_unity_root n : (n > 1)%N -> exists2 w : algC, w ^+ n = 1 & 'Re w < 0.\nProof.\nmove=> n_gt1; have [|w /eqP pw_0] := closed_rootP (\\poly_(i < n) (1 : algC)) _.\n  by rewrite size_poly_eq ?oner_eq0 // -(subnKC n_gt1).\nrewrite horner_poly (eq_bigr _ (fun _ _ => mul1r _)) in pw_0.\nhave wn1: w ^+ n = 1 by apply/eqP; rewrite -subr_eq0 subrX1 pw_0 mulr0.\nsuffices /existsP[i ltRwi0]: [exists i : 'I_n, 'Re (w ^+ i) < 0].\n  by exists (w ^+ i) => //; rewrite exprAC wn1 expr1n.\napply: contra_eqT (congr1 algRe pw_0); rewrite negb_exists => /forallP geRw0.\nrewrite raddf_sum raddf0 /= (bigD1 (Ordinal (ltnW n_gt1))) //=.\nrewrite (Creal_ReP _ _) ?rpred1 // gtr_eqF ?ltr_paddr ?ltr01 //=.\nby apply: sumr_ge0 => i _; rewrite real_lerNgt.\nQed.\n\nLemma Im_rootC_ge0 n x : (n > 1)%N -> 0 <= 'Im (n.-root x).\nProof.\nset y := n.-root x => n_gt1; have n_gt0 := ltnW n_gt1.\napply: wlog_neg; rewrite -real_ltrNge // => ltIy0.\nsuffices [z zn_x leI0z]: exists2 z, z ^+ n = x & 'Im z >= 0.\n  by rewrite /y; case_rootC => /= y1 _ /(_ z n_gt0 zn_x)/argCleP[].\nhave [w wn1 ltRw0] := neg_unity_root n_gt1.\nwlog leRI0yw: w wn1 ltRw0 / 0 <= 'Re y * 'Im w. \n  move=> IHw; have: 'Re y * 'Im w \\is Creal by rewrite rpredM.\n  case/real_ger0P=> [|/ltrW leRIyw0]; first exact: IHw.\n  apply: (IHw w^*); rewrite ?algRe_conj ?algIm_conj ?mulrN ?oppr_ge0 //.\n  by rewrite -rmorphX wn1 rmorph1.\nexists (w * y); first by rewrite exprMn wn1 mul1r rootCK. \nrewrite [w]algCrect [y]algCrect mulC_rect.\nby rewrite algIm_rect ?rpredD ?rpredN 1?rpredM // addr_ge0 // ltrW ?nmulr_rgt0.\nQed.\n\nLemma rootC_lt0 n x : (1 < n)%N -> (n.-root x < 0) = false.\nProof.\nset y := n.-root x => n_gt1; have n_gt0 := ltnW n_gt1.\napply: negbTE; apply: wlog_neg => /negbNE lt0y; rewrite ler_gtF //.\nhave Rx: x \\is Creal by rewrite -[x](rootCK n_gt0) rpredX // ltr0_real.\nhave Re_y: 'Re y = y by apply/Creal_ReP; rewrite ltr0_real.\nhave [z zn_x leR0z]: exists2 z, z ^+ n = x & 'Re z >= 0.\n  have [w wn1 ltRw0] := neg_unity_root n_gt1.\n  exists (w * y); first by rewrite exprMn wn1 mul1r rootCK. \n  by rewrite algReMr ?ltr0_real // ltrW // nmulr_lgt0.\nwithout loss leI0z: z zn_x leR0z / 'Im z >= 0.\n  move=> IHz; have: 'Im z \\is Creal by [].\n  case/real_ger0P=> [|/ltrW leIz0]; first exact: IHz.\n  apply: (IHz z^*); rewrite ?algRe_conj ?algIm_conj ?oppr_ge0 //.\n  by rewrite -rmorphX zn_x conj_Creal.\nby apply: ler_trans leR0z _; rewrite -Re_y ?rootC_Re_max ?ltr0_real.\nQed.\n\nLemma rootC_ge0 n x : (n > 0)%N -> (0 <= n.-root x) = (0 <= x).\nProof.\nset y := n.-root x => n_gt0.\napply/idP/idP=> [/(exprn_ge0 n) | x_ge0]; first by rewrite rootCK.\nrewrite -(ger_lerif (lerif_Re_Creal y)).\nhave Ray: `|y| \\is Creal by apply: normr_real.\nrewrite -(Creal_ReP _ Ray) rootC_Re_max ?(Creal_ImP _ Ray) //.\nby rewrite -normrX rootCK // ger0_norm.\nQed.\n\nLemma rootC_gt0 n x : (n > 0)%N -> (n.-root x > 0) = (x > 0).\nProof. by move=> n_gt0; rewrite !lt0r rootC_ge0 ?rootC_eq0. Qed.\n\nLemma rootC_le0 n x : (1 < n)%N -> (n.-root x <= 0) = (x == 0).\nProof.\nby move=> n_gt1; rewrite ler_eqVlt rootC_lt0 // orbF rootC_eq0 1?ltnW.\nQed.\n\nLemma ler_rootCl n : (n > 0)%N -> {in Num.nneg, {mono n.-root : x y / x <= y}}.\nProof.\nmove=> n_gt0 x x_ge0 y; have [y_ge0 | not_y_ge0] := boolP (0 <= y).\n  by rewrite -(ler_pexpn2r n_gt0) ?qualifE ?rootC_ge0 ?rootCK.\nrewrite (contraNF (@ler_trans _ _ 0 _ _)) ?rootC_ge0 //.\nby rewrite (contraNF (ler_trans x_ge0)).\nQed.\n\nLemma ler_rootC n : (n > 0)%N -> {in Num.nneg &, {mono n.-root : x y / x <= y}}.\nProof. by move=> n_gt0 x y x_ge0 _; apply: ler_rootCl. Qed.\n\nLemma ltr_rootCl n : (n > 0)%N -> {in Num.nneg, {mono n.-root : x y / x < y}}.\nProof. by move=> n_gt0 x x_ge0 y; rewrite !ltr_def ler_rootCl ?eqr_rootC. Qed.\n\nLemma ltr_rootC n : (n > 0)%N -> {in Num.nneg &, {mono n.-root : x y / x < y}}.\nProof. by move/ler_rootC/lerW_mono_in. Qed.\n\nLemma exprCK n x : (0 < n)%N -> 0 <= x -> n.-root (x ^+ n) = x.\nProof.\nmove=> n_gt0 x_ge0; apply/eqP.\nby rewrite -(eqr_expn2 n_gt0) ?rootC_ge0 ?exprn_ge0 ?rootCK.\nQed.\n\nLemma norm_rootC n x : `|n.-root x| = n.-root `|x|.\nProof.\nhave [-> | n_gt0] := posnP n; first by rewrite !root0C normr0.\napply/eqP; rewrite -(eqr_expn2 n_gt0) ?rootC_ge0 ?normr_ge0 //.\nby rewrite -normrX !rootCK.\nQed.\n\nLemma rootCX n x k : (n > 0)%N -> 0 <= x -> n.-root (x ^+ k) = n.-root x ^+ k.\nProof.\nmove=> n_gt0 x_ge0; apply/eqP.\nby rewrite -(eqr_expn2 n_gt0) ?(exprn_ge0, rootC_ge0) // 1?exprAC !rootCK.\nQed.\n\nLemma rootC1 n : (n > 0)%N -> n.-root 1 = 1.\nProof. by move/(rootCX 0)/(_ ler01). Qed.\n\nLemma rootCpX n x k : (k > 0)%N -> 0 <= x -> n.-root (x ^+ k) = n.-root x ^+ k.\nProof.\nby case: n => [|n] k_gt0; [rewrite !root0C expr0n gtn_eqF | apply: rootCX].\nQed.\n\nLemma rootCV n x : (n > 0)%N -> 0 <= x -> n.-root x^-1 = (n.-root x)^-1.\nProof.\nmove=> n_gt0 x_ge0; apply/eqP.\nby rewrite -(eqr_expn2 n_gt0) ?(invr_ge0, rootC_ge0) // !exprVn !rootCK.\nQed.\n\nLemma rootC_eq1 n x : (n > 0)%N -> (n.-root x == 1) = (x == 1).\nProof. by move=> n_gt0; rewrite -{1}(rootC1 n_gt0) eqr_rootC. Qed.\n\nLemma rootC_ge1 n x : (n > 0)%N -> (n.-root x >= 1) = (x >= 1).\nProof.\nby move=> n_gt0; rewrite -{1}(rootC1 n_gt0) ler_rootCl // qualifE ler01.\nQed.\n\nLemma rootC_gt1 n x : (n > 0)%N -> (n.-root x > 1) = (x > 1).\nProof. by move=> n_gt0; rewrite !ltr_def rootC_eq1 ?rootC_ge1. Qed.\n\nLemma rootC_le1 n x : (n > 0)%N -> 0 <= x -> (n.-root x <= 1) = (x <= 1).\nProof. by move=> n_gt0 x_ge0; rewrite -{1}(rootC1 n_gt0) ler_rootCl. Qed.\n\nLemma rootC_lt1 n x : (n > 0)%N -> 0 <= x -> (n.-root x < 1) = (x < 1).\nProof. by move=> n_gt0 x_ge0; rewrite !ltr_neqAle rootC_eq1 ?rootC_le1. Qed.\n\nLemma rootCMl n x z : 0 <= x -> n.-root (x * z) = n.-root x * n.-root z.\nProof.\nrewrite le0r => /predU1P[-> | x_gt0]; first by rewrite !(mul0r, rootC0).\nhave [| n_gt1 | ->] := ltngtP n 1; last by rewrite !root1C.\n  by case: n => //; rewrite !root0C mul0r.\nhave [x_ge0 n_gt0] := (ltrW x_gt0, ltnW n_gt1).\nhave nx_gt0: 0 < n.-root x by rewrite rootC_gt0.\nhave Rnx: n.-root x \\is Creal by rewrite ger0_real ?ltrW.\napply: eqC_semipolar; last 1 first; try apply/eqP.\n- by rewrite algImMl // !(Im_rootC_ge0, mulr_ge0, rootC_ge0).\n- by rewrite -(eqr_expn2 n_gt0) ?normr_ge0 // -!normrX exprMn !rootCK.\nrewrite eqr_le; apply/andP; split; last first.\n  rewrite rootC_Re_max ?exprMn ?rootCK ?algImMl //.\n  by rewrite mulr_ge0 ?Im_rootC_ge0 ?ltrW.\nrewrite -[n.-root _](mulVKf (negbT (gtr_eqF nx_gt0))) !(algReMl Rnx) //.\nrewrite ler_pmul2l // rootC_Re_max ?exprMn ?exprVn ?rootCK ?mulKf ?gtr_eqF //.\nby rewrite algImMl ?rpredV // mulr_ge0 ?invr_ge0 ?Im_rootC_ge0 ?ltrW.\nQed.\n\nLemma rootCMr n x z : 0 <= x -> n.-root (z * x) = n.-root z * n.-root x.\nProof. by move=> x_ge0; rewrite mulrC rootCMl // mulrC. Qed.\n\n(* More properties of n.-root will be established in cyclotomic.v. *)\n\n(* The proper form of the Arithmetic - Geometric Mean inequality. *)\n\nLemma lerif_rootC_AGM (I : finType) (A : pred I) (n := #|A|) E :\n    {in A, forall i, 0 <= E i} ->\n  n.-root (\\prod_(i in A) E i) <= (\\sum_(i in A) E i) / n%:R\n                             ?= iff [forall i in A, forall j in A, E i == E j].\nProof.\nmove=> Ege0; have [n0 | n_gt0] := posnP n.\n  rewrite n0 root0C invr0 mulr0; apply/lerif_refl/forall_inP=> i.\n  by rewrite (card0_eq n0).\nrewrite -(mono_in_lerif (ler_pexpn2r n_gt0)) ?rootCK //=; first 1 last.\n- by rewrite qualifE rootC_ge0 // prodr_ge0.\n- by rewrite rpred_div ?rpred_nat ?rpred_sum.\nexact: lerif_AGM.\nQed.\n\n(* Square root. *)\n\nLemma sqrtC0 : sqrtC 0 = 0. Proof. exact: rootC0. Qed.\nLemma sqrtC1 : sqrtC 1 = 1. Proof. exact: rootC1. Qed.\nLemma sqrtCK x : sqrtC x ^+ 2 = x. Proof. exact: rootCK. Qed.\nLemma sqrCK x : 0 <= x -> sqrtC (x ^+ 2) = x. Proof. exact: exprCK. Qed.\n\nLemma sqrtC_ge0 x : (0 <= sqrtC x) = (0 <= x). Proof. exact: rootC_ge0. Qed.\nLemma sqrtC_eq0 x : (sqrtC x == 0) = (x == 0). Proof. exact: rootC_eq0. Qed.\nLemma sqrtC_gt0 x : (sqrtC x > 0) = (x > 0). Proof. exact: rootC_gt0. Qed.\nLemma sqrtC_lt0 x : (sqrtC x < 0) = false. Proof. exact: rootC_lt0. Qed.\nLemma sqrtC_le0 x : (sqrtC x <= 0) = (x == 0). Proof. exact: rootC_le0. Qed.\n\nLemma ler_sqrtC : {in Num.nneg &, {mono sqrtC : x y / x <= y}}.\nProof. exact: ler_rootC. Qed.\nLemma ltr_sqrtC : {in Num.nneg &, {mono sqrtC : x y / x < y}}.\nProof. exact: ltr_rootC. Qed.\nLemma eqr_sqrtC : {mono sqrtC : x y / x == y}.\nProof. exact: eqr_rootC. Qed.\nLemma sqrtC_inj : injective sqrtC.\nProof. exact: rootC_inj. Qed.\nLemma sqrtCM : {in Num.nneg &, {morph sqrtC : x y / x * y}}.\nProof. by move=> x y _; apply: rootCMr. Qed.\n\nLemma sqrCK_P x : reflect (sqrtC (x ^+ 2) = x) ((0 <= 'Im x) && ~~ (x < 0)).\nProof.\napply: (iffP andP) => [[leI0x not_gt0x] | <-]; last first.\n  by rewrite sqrtC_lt0 Im_rootC_ge0.\nhave /eqP := sqrtCK (x ^+ 2); rewrite eqf_sqr => /pred2P[] // defNx.\napply: sqrCK; rewrite -real_lerNgt // in not_gt0x; apply/Creal_ImP/ler_anti; \nby rewrite leI0x -oppr_ge0 -raddfN -defNx Im_rootC_ge0.\nQed.\n\nLemma normC_def x : `|x| = sqrtC (x * x^*).\nProof. by rewrite -normCK sqrCK ?normr_ge0. Qed.\n\nLemma norm_conjC x : `|x^*| = `|x|.\nProof. by rewrite !normC_def conjCK mulrC. Qed.\n\nLemma normC_rect :\n  {in Creal &, forall x y, `|x + 'i * y| = sqrtC (x ^+ 2 + y ^+ 2)}.\nProof. by move=> x y Rx Ry; rewrite /= normC_def -normCK normC2_rect. Qed.\n\nLemma normC_Re_Im z : `|z| = sqrtC ('Re z ^+ 2 + 'Im z ^+ 2).\nProof. by rewrite normC_def -normCK normC2_Re_Im. Qed.\n\n(* Norm sum (in)equalities. *)\n\nLemma normC_add_eq x y :\n    `|x + y| = `|x| + `|y| ->\n  {t : algC | `|t| == 1 & (x, y) = (`|x| * t, `|y| * t)}.\nProof.\nmove=> lin_xy; apply: sig2_eqW; pose u z := if z == 0 then 1 else z / `|z|.\nhave uE z: (`|u z| = 1) * (`|z| * u z = z).\n  rewrite /u; have [->|nz_z] := altP eqP; first by rewrite normr0 normr1 mul0r.\n  by rewrite normf_div normr_id mulrCA divff ?mulr1 ?normr_eq0.\nhave [->|nz_x] := eqVneq x 0; first by exists (u y); rewrite uE ?normr0 ?mul0r.\nexists (u x); rewrite uE // /u (negPf nz_x); congr (_ , _).\nhave{lin_xy} def2xy: `|x| * `|y| *+ 2 = x * y ^* + y * x ^*.\n  apply/(addrI (x * x^*))/(addIr (y * y^*)); rewrite -2!{1}normCK -sqrrD.\n  by rewrite addrA -addrA -!mulrDr -mulrDl -rmorphD -normCK lin_xy.\nhave def_xy: x * y^* = y * x^*.\n  apply/eqP; rewrite -subr_eq0 -[_ == 0](@expf_eq0 _ _ 2).\n  rewrite (canRL (subrK _) (subr_sqrDB _ _)) opprK -def2xy exprMn_n exprMn.\n  by rewrite mulrN mulrAC mulrA -mulrA mulrACA -!normCK mulNrn addNr.\nhave{def_xy def2xy} def_yx: `|y * x| = y * x^*.\n  by apply: (mulIf nz2); rewrite !mulr_natr mulrC normrM def2xy def_xy.\nrewrite -{1}(divfK nz_x y) invC_norm mulrCA -{}def_yx !normrM invfM.\nby rewrite mulrCA divfK ?normr_eq0 // mulrAC mulrA.\nQed.\n\nLemma normC_sum_eq (I : finType) (P : pred I) (F : I -> algC) :\n     `|\\sum_(i | P i) F i| = \\sum_(i | P i) `|F i| ->\n   {t : algC | `|t| == 1 & forall i, P i -> F i = `|F i| * t}.\nProof.\nhave [i /andP[Pi nzFi] | F0] := pickP [pred i | P i & F i != 0]; last first.\n  exists 1 => [|i Pi]; first by rewrite normr1.\n  by case/nandP: (F0 i) => [/negP[]// | /negbNE/eqP->]; rewrite normr0 mul0r.\nrewrite !(bigD1 i Pi) /= => norm_sumF; pose Q j := P j && (j != i).\nrewrite -normr_eq0 in nzFi; set c := F i / `|F i|; exists c => [|j Pj].\n  by rewrite normrM normfV normr_id divff.\nhave [Qj | /nandP[/negP[]// | /negbNE/eqP->]] := boolP (Q j); last first.\n  by rewrite mulrC divfK.\nhave: `|F i + F j| = `|F i| + `|F j|.\n  do [rewrite !(bigD1 j Qj) /=; set z := \\sum_(k | _) `|_|] in norm_sumF.\n  apply/eqP; rewrite eqr_le ler_norm_add -(ler_add2r z) -addrA -norm_sumF addrA.\n  by rewrite (ler_trans (ler_norm_add _ _)) // ler_add2l ler_norm_sum.\nby case/normC_add_eq=> k _ [/(canLR (mulKf nzFi)) <-]; rewrite -(mulrC (F i)).\nQed.\n\nLemma normC_sum_eq1 (I : finType) (P : pred I) (F : I -> algC) :\n    `|\\sum_(i | P i) F i| = (\\sum_(i | P i) `|F i|) ->\n     (forall i, P i -> `|F i| = 1) ->\n   {t : algC | `|t| == 1 & forall i, P i -> F i = t}.\nProof.\ncase/normC_sum_eq=> t t1 defF normF.\nby exists t => // i Pi; rewrite defF // normF // mul1r.\nQed.\n\nLemma normC_sum_upper (I : finType) (P : pred I) (F G : I -> algC) :\n     (forall i, P i -> `|F i| <= G i) ->\n     \\sum_(i | P i) F i = \\sum_(i | P i) G i ->\n   forall i, P i -> F i = G i.\nProof.\nset sumF := \\sum_(i | _) _; set sumG := \\sum_(i | _) _ => leFG eq_sumFG.\nhave posG i: P i -> 0 <= G i by move/leFG; apply: ler_trans; apply: normr_ge0.\nhave norm_sumG: `|sumG| = sumG by rewrite ger0_norm ?sumr_ge0.\nhave norm_sumF: `|sumF| = \\sum_(i | P i) `|F i|.\n  apply/eqP; rewrite eqr_le ler_norm_sum eq_sumFG norm_sumG -subr_ge0 -sumrB.\n  by rewrite sumr_ge0 // => i Pi; rewrite subr_ge0 ?leFG.\nhave [t _ defF] := normC_sum_eq norm_sumF.\nhave [/(psumr_eq0P posG) G0 i Pi | nz_sumG] := eqVneq sumG 0.\n  by apply/eqP; rewrite G0 // -normr_eq0 eqr_le normr_ge0 -(G0 i Pi) leFG.\nhave t1: t = 1.\n  apply: (mulfI nz_sumG); rewrite mulr1 -{1}norm_sumG -eq_sumFG norm_sumF.\n  by rewrite mulr_suml -(eq_bigr _ defF).\nhave /psumr_eq0P eqFG i: P i -> 0 <= G i - F i.\n  by move=> Pi; rewrite subr_ge0 defF // t1 mulr1 leFG.\nmove=> i /eqFG/(canRL (subrK _))->; rewrite ?add0r //.\nby rewrite sumrB -/sumF eq_sumFG subrr.\nQed.\n\nLemma normC_sub_eq x y :\n  `|x - y| = `|x| - `|y| -> {t | `|t| == 1 & (x, y) = (`|x| * t, `|y| * t)}.\nProof.\nrewrite -{-1}(subrK y x) => /(canLR (subrK _))/esym-Dx; rewrite Dx.\nby have [t ? [Dxy Dy]] := normC_add_eq Dx; exists t; rewrite // mulrDl -Dxy -Dy.\nQed.\n\n(* Integer subset. *)\n\n(* Not relying on the undocumented interval library, for now. *)\nLemma floorC_itv x : x \\is Creal -> (floorC x)%:~R <= x < (floorC x + 1)%:~R.\nProof. by rewrite /floorC => Rx; case: (floorC_subproof x) => //= m; apply. Qed.\n\nLemma floorC_def x m : m%:~R <= x < (m + 1)%:~R -> floorC x = m.\nProof.\ncase/andP=> lemx ltxm1; apply/eqP; rewrite eqr_le -!ltz_addr1.\nhave /floorC_itv/andP[lefx ltxf1]: x \\is Creal.\n  by rewrite -[x](subrK m%:~R) rpredD ?realz ?ler_sub_real.\nby rewrite -!(ltr_int [numFieldType of algC]) 2?(@ler_lt_trans _ x).\nQed.\n\nLemma intCK : cancel intr floorC.\nProof.\nby move=> m; apply: floorC_def; rewrite ler_int ltr_int ltz_addr1 lerr.\nQed.\n\nLemma floorCK : {in Cint, cancel floorC intr}. Proof. by move=> z /eqP. Qed.\n\nLemma floorC0 : floorC 0 = 0. Proof. exact: (intCK 0). Qed.\nLemma floorC1 : floorC 1 = 1. Proof. exact: (intCK 1). Qed.\nHint Resolve floorC0 floorC1.\n\nLemma floorCpK (p : {poly algC}) :\n  p \\is a polyOver Cint -> map_poly intr (map_poly floorC p) = p.\nProof.\nmove/(all_nthP 0)=> Zp; apply/polyP=> i.\nrewrite coef_map coef_map_id0 //= -[p]coefK coef_poly.\nby case: ifP => [/Zp/floorCK // | _]; rewrite floorC0.\nQed.\n\nLemma floorCpP (p : {poly algC}) :\n  p \\is a polyOver Cint -> {q | p = map_poly intr q}.\nProof. by exists (map_poly floorC p); rewrite floorCpK. Qed.\n\nLemma Cint_int m : m%:~R \\in Cint.\nProof. by rewrite unfold_in intCK. Qed.\n\nLemma CintP x : reflect (exists m, x = m%:~R) (x \\in Cint).\nProof.\nby apply: (iffP idP) => [/eqP<-|[m ->]]; [exists (floorC x) | apply: Cint_int].\nQed.\n\nLemma floorCD : {in Cint & Creal, {morph floorC : x y / x + y}}.\nProof.\nmove=> _ y /CintP[m ->] Ry; apply: floorC_def.\nby rewrite -addrA 2!rmorphD /= intCK ler_add2l ltr_add2l floorC_itv.\nQed.\n\nLemma floorCN : {in Cint, {morph floorC : x / - x}}.\nProof. by move=> _ /CintP[m ->]; rewrite -rmorphN !intCK. Qed.\n\nLemma floorCM : {in Cint &, {morph floorC : x y / x * y}}.\nProof. by move=> _ _ /CintP[m1 ->] /CintP[m2 ->]; rewrite -rmorphM !intCK. Qed.\n\nLemma floorCX n : {in Cint, {morph floorC : x / x ^+ n}}.\nProof. by move=> _ /CintP[m ->]; rewrite -rmorphX !intCK. Qed.\n\nLemma rpred_Cint S (ringS : subringPred S) (kS : keyed_pred ringS) x :\n  x \\in Cint -> x \\in kS.\nProof. by case/CintP=> m ->; apply: rpred_int. Qed.\n\nLemma Cint0 : 0 \\in Cint. Proof. exact: (Cint_int 0). Qed.\nLemma Cint1 : 1 \\in Cint. Proof. exact: (Cint_int 1). Qed.\nHint Resolve Cint0 Cint1.\n\nFact Cint_key : pred_key Cint. Proof. by []. Qed.\nFact Cint_subring : subring_closed Cint.\nProof.\nby split=> // _ _ /CintP[m ->] /CintP[p ->];\n    rewrite -(rmorphB, rmorphM) Cint_int.\nQed.\nCanonical Cint_keyed := KeyedPred Cint_key.\nCanonical Cint_opprPred := OpprPred Cint_subring.\nCanonical Cint_addrPred := AddrPred Cint_subring.\nCanonical Cint_mulrPred := MulrPred Cint_subring.\nCanonical Cint_zmodPred := ZmodPred Cint_subring.\nCanonical Cint_semiringPred := SemiringPred Cint_subring.\nCanonical Cint_smulrPred := SmulrPred Cint_subring.\nCanonical Cint_subringPred := SubringPred Cint_subring.\n\nLemma Creal_Cint : {subset Cint <= Creal}.\nProof. by move=> _ /CintP[m ->]; apply: realz. Qed.\n\nLemma conj_Cint x : x \\in Cint -> x^* = x.\nProof. by move/Creal_Cint/conj_Creal. Qed.\n\nLemma Cint_normK x : x \\in Cint -> `|x| ^+ 2 = x ^+ 2.\nProof. by move/Creal_Cint/real_normK. Qed.\n\nLemma CintEsign x : x \\in Cint -> x = (-1) ^+ (x < 0)%C * `|x|.\nProof. by move/Creal_Cint/realEsign. Qed.\n\n(* Natural integer subset. *)\n\nLemma truncC_itv x : 0 <= x -> (truncC x)%:R <= x < (truncC x).+1%:R.\nProof.\nmove=> x_ge0; have /andP[lemx ltxm1] := floorC_itv (ger0_real x_ge0).\nrewrite /truncC x_ge0 -addn1 !pmulrn PoszD gez0_abs ?lemx //.\nby rewrite -ltz_addr1 -(ltr_int [numFieldType of algC]) (ler_lt_trans x_ge0).\nQed.\n\nLemma truncC_def x n : n%:R <= x < n.+1%:R -> truncC x = n.\nProof.\nmove=> ivt_n_x; have /andP[lenx _] := ivt_n_x.\nby rewrite /truncC (ler_trans (ler0n _ n)) // (@floorC_def _ n) // addrC -intS.\nQed.\n\nLemma natCK n : truncC n%:R = n.\nProof. by apply: truncC_def; rewrite lerr ltr_nat /=. Qed.\n\nLemma CnatP x : reflect (exists n, x = n%:R) (x \\in Cnat).\nProof.\nby apply: (iffP eqP) => [<- | [n ->]]; [exists (truncC x) | rewrite natCK].\nQed.\n\nLemma truncCK : {in Cnat, cancel truncC (GRing.natmul 1)}.\nProof. by move=> x /eqP. Qed.\n\nLemma truncC_gt0 x : (0 < truncC x)%N = (1 <= x).\nProof.\napply/idP/idP=> [m_gt0 | x_ge1].\n  have /truncC_itv/andP[lemx _]: 0 <= x.\n    by move: m_gt0; rewrite /truncC; case: ifP.\n  by apply: ler_trans lemx; rewrite ler1n.\nhave /truncC_itv/andP[_ ltxm1]:= ler_trans ler01 x_ge1.\nby rewrite -ltnS -ltC_nat (ler_lt_trans x_ge1).\nQed.\n\nLemma truncC0Pn x : reflect (truncC x = 0%N) (~~ (1 <= x)).\nProof. by rewrite -truncC_gt0 -eqn0Ngt; apply: eqP. Qed.\n\nLemma truncC0 : truncC 0 = 0%N. Proof. exact: (natCK 0). Qed.\nLemma truncC1 : truncC 1 = 1%N. Proof. exact: (natCK 1). Qed.\n\nLemma truncCD :\n  {in Cnat & Num.nneg, {morph truncC : x y / x + y >-> (x + y)%N}}.\nProof.\nmove=> _ y /CnatP[n ->] y_ge0; apply: truncC_def.\nby rewrite -addnS !natrD !natCK ler_add2l ltr_add2l truncC_itv.\nQed.\n\nLemma truncCM : {in Cnat &, {morph truncC : x y / x * y >-> (x * y)%N}}.\nProof. by move=> _ _ /CnatP[n1 ->] /CnatP[n2 ->]; rewrite -natrM !natCK. Qed.\n\nLemma truncCX n : {in Cnat, {morph truncC : x / x ^+ n >-> (x ^ n)%N}}.\nProof. by move=> _ /CnatP[n1 ->]; rewrite -natrX !natCK. Qed.\n\nLemma rpred_Cnat S (ringS : semiringPred S) (kS : keyed_pred ringS) x :\n  x \\in Cnat -> x \\in kS.\nProof. by case/CnatP=> n ->; apply: rpred_nat. Qed.\n\nLemma Cnat_nat n : n%:R \\in Cnat. Proof. by apply/CnatP; exists n. Qed.\nLemma Cnat0 : 0 \\in Cnat. Proof. exact: (Cnat_nat 0). Qed.\nLemma Cnat1 : 1 \\in Cnat. Proof. exact: (Cnat_nat 1). Qed.\nHint Resolve Cnat_nat Cnat0 Cnat1.\n\nFact Cnat_key : pred_key Cnat. Proof. by []. Qed.\nFact Cnat_semiring : semiring_closed Cnat.\nProof.\nby do 2![split] => //= _ _ /CnatP[n ->] /CnatP[m ->]; rewrite -(natrD, natrM).\nQed.\nCanonical Cnat_keyed := KeyedPred Cnat_key.\nCanonical Cnat_addrPred := AddrPred Cnat_semiring.\nCanonical Cnat_mulrPred := MulrPred Cnat_semiring.\nCanonical Cnat_semiringPred := SemiringPred Cnat_semiring.\n\nLemma Cnat_ge0 x : x \\in Cnat -> 0 <= x.\nProof. by case/CnatP=> n ->; apply: ler0n. Qed.\n\nLemma Cnat_gt0 x : x \\in Cnat -> (0 < x) = (x != 0).\nProof. by case/CnatP=> n ->; rewrite pnatr_eq0 ltr0n lt0n. Qed.\n\nLemma conj_Cnat x : x \\in Cnat -> x^* = x.\nProof. by case/CnatP=> n ->; apply: rmorph_nat. Qed.\n\nLemma norm_Cnat x : x \\in Cnat -> `|x| = x.\nProof. by move/Cnat_ge0/ger0_norm. Qed.\n\nLemma Creal_Cnat : {subset Cnat <= Creal}.\nProof. by move=> z /conj_Cnat/CrealP. Qed.\n\nLemma Cnat_sum_eq1 (I : finType) (P : pred I) (F : I -> algC) :\n     (forall i, P i -> F i \\in Cnat) -> \\sum_(i | P i) F i = 1 ->\n   {i : I | [/\\ P i, F i = 1 & forall j, j != i -> P j -> F j = 0]}.\nProof.\nmove=> natF sumF1; pose nF i := truncC (F i).\nhave{natF} defF i: P i -> F i = (nF i)%:R by move/natF/eqP.\nhave{sumF1} /eqP sumF1: (\\sum_(i | P i) nF i == 1)%N.\n  by rewrite -eqC_nat natr_sum -(eq_bigr _ defF) sumF1.\nhave [i Pi nZfi]: {i : I | P i & nF i != 0%N}.\n  by apply/sig2W/exists_inP; rewrite -negb_forall_in -sum_nat_eq0 sumF1.\nhave F'ge0 := (leq0n _, etrans (eq_sym _ _) (sum_nat_eq0 (predD1 P i) nF)).\nrewrite -lt0n in nZfi; have [_] := (leqif_add (leqif_eq nZfi) (F'ge0 _)).\nrewrite /= big_andbC -bigD1 // sumF1 => /esym/andP/=[/eqP Fi1 /forall_inP Fi'0].\nexists i; split=> // [|j neq_ji Pj]; first by rewrite defF // -Fi1.\nby rewrite defF // (eqP (Fi'0 j _)) // neq_ji.\nQed.\n\nLemma Cnat_mul_eq1 x y :\n  x \\in Cnat -> y \\in Cnat -> (x * y == 1) = (x == 1) && (y == 1).\nProof. by do 2!move/truncCK <-; rewrite -natrM !pnatr_eq1 muln_eq1. Qed.\n\nLemma Cnat_prod_eq1 (I : finType) (P : pred I) (F : I -> algC) :\n    (forall i, P i -> F i \\in Cnat) -> \\prod_(i | P i) F i = 1 ->\n  forall i, P i -> F i = 1.\nProof.\nmove=> natF prodF1; apply/eqfun_inP; rewrite -big_andE.\nmove: prodF1; elim/(big_load (fun x => x \\in Cnat)): _.\nelim/big_rec2: _ => // i all1x x /natF N_Fi [Nx x1all1].\nby split=> [|/eqP]; rewrite ?rpredM ?Cnat_mul_eq1 // => /andP[-> /eqP].\nQed.\n\n(* Relating Cint and Cnat. *)\n\nLemma Cint_Cnat : {subset Cnat <= Cint}.\nProof. by move=> _ /CnatP[n ->]; rewrite pmulrn Cint_int. Qed.\n\nLemma CintE x : (x \\in Cint) = (x \\in Cnat) || (- x \\in Cnat).\nProof.\napply/idP/idP=> [/CintP[[n | n] ->] | ]; first by rewrite Cnat_nat.\n  by rewrite NegzE opprK Cnat_nat orbT.\nby case/pred2P=> [<- | /(canLR (@opprK _)) <-]; rewrite ?rpredN rpred_nat.\nQed.\n\nLemma Cnat_norm_Cint x : x \\in Cint -> `|x| \\in Cnat.\nProof.\ncase/CintP=> [m ->]; rewrite [m]intEsign rmorphM rmorph_sign.\nby rewrite normrM normr_sign mul1r normr_nat rpred_nat.\nQed.\n\nLemma CnatEint x : (x \\in Cnat) = (x \\in Cint) && (0 <= x).\nProof.\napply/idP/andP=> [Nx | [Zx x_ge0]]; first by rewrite Cint_Cnat ?Cnat_ge0.\nby rewrite -(ger0_norm x_ge0) Cnat_norm_Cint.\nQed.\n\nLemma CintEge0 x : 0 <= x -> (x \\in Cint) = (x \\in Cnat).\nProof. by rewrite CnatEint andbC => ->. Qed.\n\nLemma Cnat_exp_even x n : ~~ odd n -> x \\in Cint -> x ^+ n \\in Cnat.\nProof.\nrewrite -dvdn2 => /dvdnP[m ->] Zx; rewrite mulnC exprM -Cint_normK ?rpredX //.\nexact: Cnat_norm_Cint.\nQed.\n\nLemma norm_Cint_ge1 x : x \\in Cint -> x != 0 -> 1 <= `|x|.\nProof.\nrewrite -normr_eq0 => /Cnat_norm_Cint/CnatP[n ->].\nby rewrite pnatr_eq0 ler1n lt0n.\nQed.\n\nLemma sqr_Cint_ge1 x : x \\in Cint -> x != 0 -> 1 <= x ^+ 2.\nProof.\nby move=> Zx nz_x; rewrite -Cint_normK // expr_ge1 ?normr_ge0 ?norm_Cint_ge1.\nQed.\n\nLemma Cint_ler_sqr x : x \\in Cint -> x <= x ^+ 2.\nProof.\nmove=> Zx; have [-> | nz_x] := eqVneq x 0; first by rewrite expr0n.\napply: ler_trans (_ : `|x| <= _); first by rewrite real_ler_norm ?Creal_Cint.\nby rewrite -Cint_normK // ler_eexpr // norm_Cint_ge1.\nQed.\n\n(* Integer divisibility. *)\n\nLemma dvdCP x y : reflect (exists2 z, z \\in Cint & y = z * x) (x %| y)%C.\nProof.\nrewrite unfold_in; have [-> | nz_x] := altP eqP.\n  by apply: (iffP eqP) => [-> | [z _ ->]]; first exists 0; rewrite ?mulr0.\napply: (iffP idP) => [Zyx | [z Zz ->]]; last by rewrite mulfK.\nby exists (y / x); rewrite ?divfK.\nQed.\n\nLemma dvdCP_nat x y : 0 <= x -> 0 <= y -> (x %| y)%C -> {n | y = n%:R * x}.\nProof.\nmove=> x_ge0 y_ge0 x_dv_y; apply: sig_eqW.\ncase/dvdCP: x_dv_y => z Zz -> in y_ge0 *; move: x_ge0 y_ge0 Zz.\nrewrite ler_eqVlt => /predU1P[<- | ]; first by exists 22; rewrite !mulr0.\nby move=> /pmulr_lge0-> /CintEge0-> /CnatP[n ->]; exists n.\nQed.\n\nLemma dvdC0 x : (x %| 0)%C.\nProof. by apply/dvdCP; exists 0; rewrite ?mul0r. Qed.\n\nLemma dvd0C x : (0 %| x)%C = (x == 0).\nProof. by rewrite unfold_in eqxx. Qed.\n\nLemma dvdC_mull x y z : y \\in Cint -> (x %| z)%C -> (x %| y * z)%C.\nProof.\nmove=> Zy /dvdCP[m Zm ->]; apply/dvdCP.\nby exists (y * m); rewrite ?mulrA ?rpredM.\nQed.\n\nLemma dvdC_mulr x y z : y \\in Cint -> (x %| z)%C -> (x %| z * y)%C.\nProof. by rewrite mulrC; apply: dvdC_mull. Qed.\n\nLemma dvdC_mul2r x y z : y != 0 -> (x * y %| z * y)%C = (x %| z)%C.\nProof.\nmove=> nz_y; rewrite !unfold_in !(mulIr_eq0 _ (mulIf nz_y)).\nby rewrite mulrAC invfM mulrA divfK.\nQed.\n\nLemma dvdC_mul2l x y z : y != 0 -> (y * x %| y * z)%C = (x %| z)%C.\nProof. by rewrite !(mulrC y); apply: dvdC_mul2r. Qed.\n\nLemma dvdC_trans x y z : (x %| y)%C -> (y %| z)%C -> (x %| z)%C.\nProof. by move=> x_dv_y /dvdCP[m Zm ->]; apply: dvdC_mull. Qed.\n\nLemma dvdC_refl x : (x %| x)%C.\nProof. by apply/dvdCP; exists 1; rewrite ?mul1r. Qed.\nHint Resolve dvdC_refl.\n\nFact dvdC_key x : pred_key (dvdC x). Proof. by []. Qed.\nLemma dvdC_zmod x : zmod_closed (dvdC x).\nProof.\nsplit=> [| _ _ /dvdCP[y Zy ->] /dvdCP[z Zz ->]]; first exact: dvdC0.\nby rewrite -mulrBl dvdC_mull ?rpredB.\nQed.\nCanonical dvdC_keyed x := KeyedPred (dvdC_key x).\nCanonical dvdC_opprPred x := OpprPred (dvdC_zmod x).\nCanonical dvdC_addrPred x := AddrPred (dvdC_zmod x).\nCanonical dvdC_zmodPred x := ZmodPred (dvdC_zmod x).\n\nLemma dvdC_nat (p n : nat) : (p %| n)%C = (p %| n)%N.\nProof.\nrewrite unfold_in CintEge0 ?divr_ge0 ?invr_ge0 ?ler0n // !pnatr_eq0.\nhave [-> | nz_p] := altP eqP; first by rewrite dvd0n.\napply/CnatP/dvdnP=> [[q def_q] | [q ->]]; exists q.\n  by apply/eqP; rewrite -eqC_nat natrM -def_q divfK ?pnatr_eq0. \nby rewrite [num in num / _]natrM mulfK ?pnatr_eq0.\nQed.\n\nLemma dvdC_int (p : nat) x : x \\in Cint -> (p %| x)%C = (p %| `|floorC x|)%N.\nProof.\nmove=> Zx; rewrite -{1}(floorCK Zx) {1}[floorC x]intEsign.\nby rewrite rmorphMsign rpredMsign dvdC_nat.\nQed.\n\n(* Elementary modular arithmetic. *)\n\nLemma eqCmod_refl e x : (x == x %[mod e])%C.\nProof. by rewrite /eqCmod subrr rpred0. Qed.\n\nLemma eqCmodm0 e : (e == 0 %[mod e])%C. Proof. by rewrite /eqCmod subr0. Qed.\nHint Resolve eqCmod_refl eqCmodm0.\n\nLemma eqCmod0 e x : (x == 0 %[mod e])%C = (e %| x)%C.\nProof. by rewrite /eqCmod subr0. Qed.\n\nLemma eqCmod_sym e x y : ((x == y %[mod e]) = (y == x %[mod e]))%C.\nProof. by rewrite /eqCmod -opprB rpredN. Qed.\n\nLemma eqCmod_trans e y x z :\n  (x == y %[mod e] -> y == z %[mod e] -> x == z %[mod e])%C.\nProof. by move=> Exy Eyz; rewrite /eqCmod -[x](subrK y) -addrA rpredD. Qed.\n\nLemma eqCmod_transl e x y z :\n  (x == y %[mod e])%C -> (x == z %[mod e])%C = (y == z %[mod e])%C.\nProof. by move/(sym_left_transitive (eqCmod_sym e) (@eqCmod_trans e)). Qed.\n\nLemma eqCmod_transr e x y z :\n  (x == y %[mod e])%C -> (z == x %[mod e])%C = (z == y %[mod e])%C.\nProof. by move/(sym_right_transitive (eqCmod_sym e) (@eqCmod_trans e)). Qed.\n\nLemma eqCmodN e x y : (- x == y %[mod e])%C = (x == - y %[mod e])%C.\nProof. by rewrite eqCmod_sym /eqCmod !opprK addrC. Qed.\n\nLemma eqCmodDr e x y z : (y + x == z + x %[mod e])%C = (y == z %[mod e])%C.\nProof. by rewrite /eqCmod addrAC opprD !addrA subrK. Qed.\n\nLemma eqCmodDl e x y z : (x + y == x + z %[mod e])%C = (y == z %[mod e])%C.\nProof. by rewrite !(addrC x) eqCmodDr. Qed.\n\nLemma eqCmodD e x1 x2 y1 y2 :\n  (x1 == x2 %[mod e] -> y1 == y2 %[mod e] -> x1 + y1 == x2 + y2 %[mod e])%C.\nProof.\nby rewrite -(eqCmodDl e x2 y1) -(eqCmodDr e y1); apply: eqCmod_trans.\nQed.\n\nLemma eqCmod_nat (e m n : nat) : (m == n %[mod e])%C = (m == n %[mod e]).\nProof.\nwithout loss lenm: m n / (n <= m)%N.\n  by move=> IH; case/orP: (leq_total m n) => /IH //; rewrite eqCmod_sym eq_sym.\nby rewrite /eqCmod -natrB // dvdC_nat eqn_mod_dvd.\nQed.\n\nLemma eqCmod0_nat (e m : nat) : (m == 0 %[mod e])%C = (e %| m)%N.\nProof. by rewrite eqCmod0 dvdC_nat. Qed.\n\nLemma eqCmodMr e :\n  {in Cint, forall z x y, x == y %[mod e] -> x * z == y * z %[mod e]}%C.\nProof. by move=> z Zz x y; rewrite /eqCmod -mulrBl => /dvdC_mulr->. Qed.\n\nLemma eqCmodMl e :\n  {in Cint, forall z x y, x == y %[mod e] -> z * x == z * y %[mod e]}%C.\nProof. by move=> z Zz x y Exy; rewrite !(mulrC z) eqCmodMr. Qed.\n\nLemma eqCmodMl0 e : {in Cint, forall x, x * e == 0 %[mod e]}%C.\nProof. by move=> x Zx; rewrite -(mulr0 x) eqCmodMl. Qed.\n\nLemma eqCmodMr0 e : {in Cint, forall x, e * x == 0 %[mod e]}%C.\nProof. by move=> x Zx; rewrite /= mulrC eqCmodMl0. Qed.\n\nLemma eqCmod_addl_mul e : {in Cint, forall x y, x * e + y == y %[mod e]}%C.\nProof. by move=> x Zx y; rewrite -{2}[y]add0r eqCmodDr eqCmodMl0. Qed.\n\nLemma eqCmodM e : {in Cint & Cint, forall x1 y2 x2 y1,\n  x1 == x2 %[mod e] -> y1 == y2 %[mod e] -> x1 * y1 == x2 * y2 %[mod e]}%C.\nProof.\nmove=> x1 y2 Zx1 Zy2 x2 y1 eq_x /(eqCmodMl Zx1)/eqCmod_trans-> //.\nexact: eqCmodMr.\nQed.\n\n(* Rational number subset. *)\n\nLemma ratCK : cancel QtoC CtoQ.\nProof. by rewrite /getCrat; case: getCrat_subproof. Qed.\n\nLemma getCratK : {in Crat, cancel CtoQ QtoC}.\nProof. by move=> x /eqP. Qed.\n\nLemma Crat_rat (a : rat) : QtoC a \\in Crat.\nProof. by rewrite unfold_in ratCK. Qed.\n\nLemma CratP x : reflect (exists a, x = QtoC a) (x \\in Crat).\nProof.\nby apply: (iffP eqP) => [<- | [a ->]]; [exists (CtoQ x) | rewrite ratCK].\nQed.\n\nLemma Crat0 : 0 \\in Crat. Proof. by apply/CratP; exists 0; rewrite rmorph0. Qed.\nLemma Crat1 : 1 \\in Crat. Proof. by apply/CratP; exists 1; rewrite rmorph1. Qed.\nHint Resolve Crat0 Crat1.\n\nFact Crat_key : pred_key Crat. Proof. by []. Qed.\nFact Crat_divring_closed : divring_closed Crat.\nProof.\nsplit=> // _ _ /CratP[x ->] /CratP[y ->].\n  by rewrite -rmorphB Crat_rat.\nby rewrite -fmorph_div Crat_rat.\nQed.\nCanonical Crat_keyed := KeyedPred Crat_key.\nCanonical Crat_opprPred := OpprPred Crat_divring_closed.\nCanonical Crat_addrPred := AddrPred Crat_divring_closed.\nCanonical Crat_mulrPred := MulrPred Crat_divring_closed.\nCanonical Crat_zmodPred := ZmodPred Crat_divring_closed.\nCanonical Crat_semiringPred := SemiringPred Crat_divring_closed.\nCanonical Crat_smulrPred := SmulrPred Crat_divring_closed.\nCanonical Crat_divrPred := DivrPred Crat_divring_closed.\nCanonical Crat_subringPred := SubringPred Crat_divring_closed.\nCanonical Crat_sdivrPred := SdivrPred Crat_divring_closed.\nCanonical Crat_divringPred := DivringPred Crat_divring_closed.\n\nLemma rpred_Crat S (ringS : divringPred S) (kS : keyed_pred ringS) :\n  {subset Crat <= kS}.\nProof. by move=> _ /CratP[a ->]; apply: rpred_rat. Qed.\n\nLemma conj_Crat z : z \\in Crat -> z^* = z.\nProof. by move/getCratK <-; rewrite fmorph_div !rmorph_int. Qed.\n\nLemma Creal_Crat : {subset Crat <= Creal}.\nProof. by move=> x /conj_Crat/CrealP. Qed.\n\nLemma Cint_rat a : (QtoC a \\in Cint) = (a \\in Qint).\nProof.\napply/idP/idP=> [Za | /numqK <-]; last by rewrite rmorph_int Cint_int.\napply/QintP; exists (floorC (QtoC a)); apply: (can_inj ratCK).\nby rewrite rmorph_int floorCK.\nQed.\n\nLemma minCpolyP x :\n   {p | minCpoly x = pQtoC p /\\ p \\is monic\n      & forall q, root (pQtoC q) x = (p %| q)%R}.\nProof. by rewrite /minCpoly; case: (minCpoly_subproof x) => p; exists p. Qed.\n\nLemma minCpoly_monic x : minCpoly x \\is monic.\nProof. by have [p [-> mon_p] _] := minCpolyP x; rewrite map_monic. Qed.\n\nLemma minCpoly_eq0 x : (minCpoly x == 0) = false.\nProof. exact/negbTE/monic_neq0/minCpoly_monic. Qed.\n\nLemma root_minCpoly x : root (minCpoly x) x.\nProof. by have [p [-> _] ->] := minCpolyP x. Qed.\n\nLemma size_minCpoly x : (1 < size (minCpoly x))%N.\nProof. by apply: root_size_gt1 (root_minCpoly x); rewrite ?minCpoly_eq0. Qed.\n\n(* Basic properties of automorphisms. *)\nSection AutC.\n\nImplicit Type nu : {rmorphism algC -> algC}.\n\nLemma aut_Cnat nu : {in Cnat, nu =1 id}.\nProof. by move=> _ /CnatP[n ->]; apply: rmorph_nat. Qed.\n\nLemma aut_Cint nu : {in Cint, nu =1 id}.\nProof. by move=> _ /CintP[m ->]; apply: rmorph_int. Qed.\n\nLemma aut_Crat nu : {in Crat, nu =1 id}.\nProof. by move=> _ /CratP[a ->]; apply: fmorph_rat. Qed.\n\nLemma Cnat_aut nu x : (nu x \\in Cnat) = (x \\in Cnat).\nProof.\nby do [apply/idP/idP=> Nx; have:= aut_Cnat nu Nx] => [/fmorph_inj <- | ->].\nQed.\n\nLemma Cint_aut nu x : (nu x \\in Cint) = (x \\in Cint).\nProof. by rewrite !CintE -rmorphN !Cnat_aut. Qed.\n\nLemma Crat_aut nu x : (nu x \\in Crat) = (x \\in Crat).\nProof.\napply/idP/idP=> /CratP[a] => [|->]; last by rewrite fmorph_rat Crat_rat.\nby rewrite -(fmorph_rat nu) => /fmorph_inj->; apply: Crat_rat.\nQed.\n\nLemma algC_invaut_subproof nu x : {y | nu y = x}.\nProof.\nhave [r Dp] := closed_field_poly_normal (minCpoly x).\nsuffices /mapP/sig2_eqW[y _ ->]: x \\in map nu r by exists y.\nrewrite -root_prod_XsubC; congr (root _ x): (root_minCpoly x).\nhave [q [Dq _] _] := minCpolyP x; rewrite Dq -(eq_map_poly (fmorph_rat nu)).\nrewrite (map_poly_comp nu) -{q}Dq Dp (monicP (minCpoly_monic x)) scale1r.\nrewrite rmorph_prod big_map; apply: eq_bigr => z _.\nby rewrite rmorphB /= map_polyX map_polyC.\nQed.\nDefinition algC_invaut nu x := sval (algC_invaut_subproof nu x).\n\nLemma algC_invautK nu : cancel (algC_invaut nu) nu.\nProof. by move=> x; rewrite /algC_invaut; case: algC_invaut_subproof. Qed.\n\nLemma algC_autK nu : cancel nu (algC_invaut nu).\nProof. exact: inj_can_sym (algC_invautK nu) (fmorph_inj nu). Qed.\n\nFact algC_invaut_is_rmorphism nu : rmorphism (algC_invaut nu).\nProof. exact: can2_rmorphism (algC_autK nu) (algC_invautK nu). Qed.\nCanonical algC_invaut_additive nu := Additive (algC_invaut_is_rmorphism nu).\nCanonical algC_invaut_rmorphism nu := RMorphism (algC_invaut_is_rmorphism nu).\n\nLemma minCpoly_aut nu x : minCpoly (nu x) = minCpoly x.\nProof.\nwlog suffices dvd_nu: nu x / (minCpoly x %| minCpoly (nu x))%R.\n  apply/eqP; rewrite -eqp_monic ?minCpoly_monic //; apply/andP; split=> //.\n  by rewrite -{2}(algC_autK nu x) dvd_nu.\nhave [[q [Dq _] min_q] [q1 [Dq1 _] _]] := (minCpolyP x, minCpolyP (nu x)).\nrewrite Dq Dq1 dvdp_map -min_q -(fmorph_root nu) -map_poly_comp.\nby rewrite (eq_map_poly (fmorph_rat nu)) -Dq1 root_minCpoly.\nQed.\n\nEnd AutC.\n\nSection AutLmodC.\n\nVariables (U V : lmodType algC) (f : {additive U -> V}).\n\nLemma raddfZ_Cnat a u : a \\in Cnat -> f (a *: u) = a *: f u. \nProof. by case/CnatP=> n ->; apply: raddfZnat. Qed.\n\nLemma raddfZ_Cint a u : a \\in Cint -> f (a *: u) = a *: f u. \nProof. by case/CintP=> m ->; rewrite !scaler_int raddfMz. Qed.\n\nEnd AutLmodC.\n\nSection PredCmod.\n\nVariable V : lmodType algC.\n\nLemma rpredZ_Cnat S (addS : @addrPred V S) (kS : keyed_pred addS) :\n  {in Cnat & kS, forall z u, z *: u \\in kS}.\nProof. by move=> _ u /CnatP[n ->]; apply: rpredZnat. Qed.\n\nLemma rpredZ_Cint S (subS : @zmodPred V S) (kS : keyed_pred subS) :\n  {in Cint & kS, forall z u, z *: u \\in kS}.\nProof. by move=> _ u /CintP[m ->]; apply: rpredZint. Qed.\n\nEnd PredCmod.\n\nEnd AlgebraicsTheory.\nHint Resolve Creal0 Creal1 Cnat_nat Cnat0 Cnat1 Cint0 Cint1 floorC0 Crat0 Crat1.\nHint Resolve dvdC0 dvdC_refl eqCmod_refl eqCmodm0.\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/theories/algC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6732415329140468}}
{"text": "(*|\n############################################################\nExistential quantifier in Coq impredicative logic (System F)\n############################################################\n\n:Link: https://stackoverflow.com/q/19083196\n|*)\n\n(*|\nQuestion\n********\n\nI was trying to code into Coq logical connectives encoded in lambda\ncalculus with type à la System F. Here is the bunch of code I wrote\n(standard things, I think)\n|*)\n\nDefinition True := forall X : Prop, X -> X.\n\nLemma I : True.\nProof.\n  unfold True. intros. apply H.\nQed.\n\nSection s.\n  Variables A B : Prop.\n\n  (* conjunction *)\n\n  Definition and := forall X : Prop, (A -> B -> X) -> X.\n  Infix \"/\\\" := and.\n\n  Lemma and_intro : A -> B -> A /\\ B.\n  Proof using A B.\n    intros HA HB. split.\n    - apply HA.\n    - apply HB.\n  Qed.\n\n  Lemma and_elim_l : A /\\ B -> A.\n  Proof using A B.\n    intros H. destruct H as [HA HB]. apply HA.\n  Qed.\n\n  Lemma and_elim_r : A /\\ B -> B.\n  Proof using A B.\n    intros H. destruct H as [HA HB]. apply HB.\n  Qed.\n\n  (* disjunction *)\n\n  Definition or := forall X : Prop, (A -> X) -> (B -> X) -> X.\n  Infix \"\\/\" := or.\n\n  Lemma or_intro_l : A -> A \\/ B.\n  Proof using A B.\n    intros HA. left. apply HA.\n  Qed.\n\n  Lemma or_elim : forall C : Prop, A \\/ B -> (A -> C) -> (B -> C) -> C.\n  Proof using A B.\n    intros C HOR HAC HBC. destruct HOR.\n    apply (HAC H).\n    apply (HBC H).\n  Qed.\n\n  (* falsity *)\n\n  Definition False := forall Y : Prop, Y.\n\n  Lemma false_elim : False -> A.\n  Proof using A.\n    unfold False. intros. apply (H A).\n  Qed.\n\nEnd s.\n\n(*|\nBasically, I wrote down the elimination and introduction laws for\nconjunction, disjunction, true and false. I am not sure of having done\nthing correctly, but I think that things should work that way. Now I\nwould like to define the existential quantification, but I have no\nidea of how to proceed. Does anyone have a suggestion?\n|*)\n\n(*|\nAnswer\n******\n\nExistential quantification is just a generalization of conjunction,\nwhere the type of the second component of the pair depends on the\nvalue of the first component. When there's no dependency they're\nequivalent:\n|*)\n\nGoal forall P1 P2 : Prop, (exists _ : P1, P2) <-> P1 /\\ P2.\nProof. split; intros [H1 H2]; eauto. Qed.\n\n(*|\n`Coq'Art <http://www.labri.fr/perso/casteran/CoqArt/index.html>`__ has\na section on impredicativity starting at page 130.\n|*)\n\nPrint ex. (* .unfold .messages *)\n\nLocate \"exists\". (* .unfold .messages *)\n\n(*|\nThe problem with impredicative definitions (unless I'm mistaken) is\nthat there's no dependent elimination. It's possible prove\n|*)\n\nGoal forall (A : Type) (P : A -> Prop) (Q : Prop),\n    (forall x : A, P x -> Q) -> (exists x, P x) -> Q.\nAdmitted. (* .none *)\n\n(*| but not |*)\n\nGoal forall (A : Type) (P : A -> Prop) (Q : (exists x, P x) -> Prop),\n    (forall (x : A) (H : P x), Q (ex_intro P x H)) ->\n    forall H : exists x, P x, Q H.\nAbort. (* .none *)\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/existential-quantifier-in-coq-impredicative-logic-system-f.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.673151190084964}}
{"text": "Require Import Arith.\nRequire Import fol.\nRequire Import primRec.\nRequire Import Coq.Lists.List.\n\nInductive LNTFunction : Set :=\n  | Plus : LNTFunction\n  | Times : LNTFunction\n  | Succ : LNTFunction\n  | Zero : LNTFunction.\n\nInductive LNNRelation : Set :=\n    LT : LNNRelation.\n\nDefinition LNTFunctionArity (x : LNTFunction) : nat :=\n  match x with\n  | Plus => 2\n  | Times => 2\n  | Succ => 1\n  | Zero => 0\n  end.\n\nDefinition LNTArity (x : Empty_set + LNTFunction) : nat :=\n  match x return nat with\n  | inl bot => Empty_set_rec (fun _ => nat) bot\n  | inr y => LNTFunctionArity y\n  end.\n\nDefinition LNNArity (x : LNNRelation + LNTFunction) : nat :=\n  match x return nat with\n  | inl y => match y with\n             | LT => 2\n             end\n  | inr y => LNTFunctionArity y\n  end.\n\nDefinition LNT : Language := language Empty_set LNTFunction LNTArity.\n\nDefinition LNN : Language := language LNNRelation LNTFunction LNNArity.\n\nDefinition codeLNTFunction (f : LNTFunction) : nat :=\n  match f with\n  | Plus => 0\n  | Times => 1\n  | Succ => 2\n  | Zero => 3\n  end.\n\nDefinition codeLNTRelation (R : Empty_set) : nat :=\n  match R return nat with\n  end.\n\nDefinition codeLNNRelation (R : LNNRelation) : nat := 0.\n\nLemma codeLNTFunctionInj :\n forall f g : LNTFunction, codeLNTFunction f = codeLNTFunction g -> f = g.\nProof.\nintros.\ndestruct f; destruct g; reflexivity || discriminate H.\nQed.\n\nLemma codeLNTRelationInj :\n forall R S : Empty_set, codeLNTRelation R = codeLNTRelation S -> R = S.\nProof.\nintros.\ndestruct R; destruct S; reflexivity || discriminate H.\nQed.\n\nLemma codeLNNRelationInj :\n forall R S : LNNRelation, codeLNNRelation R = codeLNNRelation S -> R = S.\nProof.\nintros.\ndestruct R; destruct S; reflexivity || discriminate H.\nQed.\n\nDefinition codeArityLNNR (r : nat) := switchPR r 0 3.\n\nLemma codeArityLNNRIsPR : isPR 1 codeArityLNNR.\nProof.\nunfold codeArityLNNR in |- *.\napply\n compose1_3IsPR\n  with\n    (f1 := fun r : nat => r)\n    (f2 := fun r : nat => 0)\n    (f3 := fun r : nat => 3).\napply idIsPR.\napply const1_NIsPR.\napply const1_NIsPR.\napply switchIsPR.\nQed.\n\nLemma codeArityLNNRIsCorrect1 :\n forall r : Relations LNN,\n codeArityLNNR (codeLNNRelation r) = S (arity LNN (inl _ r)).\nProof.\nintros.\ninduction r.\nsimpl in |- *.\nreflexivity.\nQed.\n\nLemma codeArityLNNRIsCorrect2 :\n forall n : nat,\n codeArityLNNR n <> 0 -> exists r : Relations LNN, codeLNNRelation r = n.\nProof.\nintros.\ndestruct n.\nexists LT.\nreflexivity.\nelim H.\nreflexivity.\nQed.\n\nDefinition codeArityLNTR (r : nat) := 0.\n\nLemma codeArityLNTRIsPR : isPR 1 codeArityLNTR.\nProof.\nunfold codeArityLNTR in |- *.\napply const1_NIsPR.\nQed.\n\nLemma codeArityLNTRIsCorrect1 :\n forall r : Relations LNT,\n codeArityLNTR (codeLNTRelation r) = S (arity LNT (inl _ r)).\nProof.\nsimple induction r.\nQed.\n\nLemma codeArityLNTRIsCorrect2 :\n forall n : nat,\n codeArityLNTR n <> 0 -> exists r : Relations LNT, codeLNTRelation r = n.\nProof.\nintros.\nelim H.\nreflexivity.\nQed.\n\nDefinition codeArityLNTF (f : nat) :=\n  switchPR f\n    (switchPR (pred f)\n       (switchPR (pred (pred f)) (switchPR (pred (pred (pred f))) 0 1) 2) 3)\n    3.\n\nLemma codeArityLNTFIsPR : isPR 1 codeArityLNTF.\nProof.\nset\n (f :=\n  list_rec (fun _ => nat -> nat -> nat) (fun _ _ : nat => 0)\n    (fun (a : nat) (l : list nat) (rec : nat -> nat -> nat) (n f : nat) =>\n     switchPR (iterate pred n f) (rec (S n) f) a)) \n in *.\nassert (forall (l : list nat) (n : nat), isPR 1 (f l n)). \nintro.\ninduction l as [| a l Hrecl]; intros.\nsimpl in |- *.\napply const1_NIsPR.\nsimpl in |- *.\napply\n compose1_3IsPR\n  with\n    (f1 := fun f0 : nat => iterate pred n f0)\n    (f2 := fun f0 : nat => f l (S n) f0)\n    (f3 := fun f0 : nat => a).\napply iterateIsPR with (g := pred) (n := n).\napply predIsPR.\napply Hrecl with (n := S n).\napply const1_NIsPR.\napply switchIsPR.\napply (H (3 :: 3 :: 2 :: 1 :: nil) 0).\nQed.\n\nLemma codeArityLNTFIsCorrect1 :\n forall f : Functions LNT,\n codeArityLNTF (codeLNTFunction f) = S (arity LNT (inr _ f)).\nProof.\nintros.\ninduction f; reflexivity.\nQed.\n\nLemma codeArityLNNFIsCorrect1 :\n forall f : Functions LNN,\n codeArityLNTF (codeLNTFunction f) = S (arity LNN (inr _ f)).\nProof.\napply codeArityLNTFIsCorrect1.\nQed.\n\nLemma codeArityLNTFIsCorrect2 :\n forall n : nat,\n codeArityLNTF n <> 0 -> exists f : Functions LNT, codeLNTFunction f = n.\nProof.\nintros.\ndestruct n.\nexists Plus.\nreflexivity.\ndestruct n.\nexists Times.\nreflexivity.\ndestruct n.\nexists Succ.\nreflexivity.\ndestruct n.\nexists Zero.\nreflexivity.\nelim H.\nreflexivity.\nQed.\n\nLemma codeArityLNNFIsCorrect2 :\n forall n : nat,\n codeArityLNTF n <> 0 -> exists f : Functions LNN, codeLNTFunction f = n.\nProof.\napply codeArityLNTFIsCorrect2.\nQed.\n\n\n\n\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/goedel/Languages.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245617, "lm_q2_score": 0.7956581097540518, "lm_q1q2_score": 0.6730809575393295}}
{"text": "From Coq Require Import Bool Setoid List NArith.\nFrom Coq Require ListSet.\nFrom Coq Require Import FSets.FSetAVL FSetFacts.\nFrom Coq Require String.\n\nRequire Import ListSet2 StringCmp.\n\n(** A finite set class.\n    These axioms require convertibility to lists.\n    (see theories/Lists/ListSet.v from a Coq distribution).\n    See theories/MSet/MSetInterface.v for a module-based interface.\n *)\nClass class {M: Type} (E: forall x y: M, {x = y} + {x <> y}) (S: Type) := {\n  (** Convert a set to a list. The order may be arbitrary. *)\n  to_list: S -> list M;\n  (** A list produced by set_to_list may only include each element once. *)\n  to_list_nodup (s: S): NoDup (to_list s);\n  (** Build a set from a list. The list may contain duplicates. *)\n  from_list: list M -> S;\n\n  (** Membership test. *) \n  has: S -> M -> bool;\n\n  (** [has] may be computed from [to_list]. *) \n  has_to_list (x: M) (s: S):\n    has s x = ListSet.set_mem E x (to_list s);\n\n  (** A set obtained from [from_list] has the same members as the list. *)\n  has_from_list (x: M) (l: list M):\n    has (from_list l) x = ListSet.set_mem E x l;\n\n  (** An empty set. Could work faster than [from_list nil].\n      Note that there may be different empty sets even though they are all equivalent.\n      In particular, it might happen that that [empty <> from_list nil].\n   *)\n  empty: S;\n  empty_to_list: to_list empty = nil;\n\n  (** A set with a single element. Could work faster than [set_from_list (x :: nil)]. *)\n  singleton: M -> S;\n  singleton_to_list (x: M): to_list (singleton x) = x :: nil;\n\n  (** The number of elements in a set. Could work faster than [length (set_to_list s)]. *)\n  size_nat: S -> nat;\n  size_nat_to_list (s: S): size_nat s = length (to_list s); \n\n  (** A test for empty set. Could work faster than [set_size_nat =? 0]. *)\n  is_empty: S -> bool;\n  is_empty_to_list (s: S): is_empty s = true <-> to_list s = nil;\n\n  (** The number of elements in a set, the version with N.\n      Could work faster than [N_of_nat (set_size_nat _)].\n   *)\n  size: S -> N;\n  size_ok (s: S): size s = N_of_nat (size_nat s);\n\n  (** Add an item to a set. *)\n  add: S -> M -> S;\n  add_ok (s: S) (x: M) (y: M):\n    has (add s x) y = if E x y then true else has s y;\n\n  (** Remove an item from a set. *)\n  remove: S -> M -> S;\n  remove_ok (s: S) (x: M) (y: M):\n    has (remove s x) y = if E x y then false else has s y;\n\n  union: S -> S -> S;\n  union_ok (a b: S): \n    forall x: M,\n      has (union a b) x\n       =\n      orb (has a x) (has b x);\n  inter: S -> S -> S;\n  inter_ok (a b: S): \n    forall x: M,\n      has (inter a b) x\n       =\n      andb (has a x) (has b x);\n  diff: S -> S -> S;\n  diff_ok (a b: S): \n    forall x: M,\n      has (diff a b) x\n       =\n      andb (has a x) (negb (has b x));\n\n  for_all: S -> (M -> bool) -> bool;\n  for_all_ok (s: S) (p: M -> bool):\n    for_all s p = true\n     <->\n    forall x: M,\n      has s x = true -> p x = true;\n\n  (** A test for being a subset. *)\n  is_subset: S -> S -> bool;\n  is_subset_ok (little big: S):\n    is_subset little big = true \n     <->\n    forall x: M,\n      orb (negb (has little x)) (has big x) = true;\n\n  (** A test for set equality.\n      Note that two set_eq sets may not be equal in the sense of Coq's equality,\n      for example: when lists are used as sets, [0, 1] and [1, 0] are set_eq but not eq.\n    *)\n  equal: S -> S -> bool;\n  equal_ok (a b: S):\n    equal a b = true \n     <->\n    forall x: M,\n      has a x = has b x;\n}.\n\nDefinition lists_as_sets {M: Type} (E: forall x y: M, {x = y} + {x <> y})\n: class E {l: list M | NoDup l}\n:= {|\n      to_list s := proj1_sig s;\n      to_list_nodup s := proj2_sig s;\n      from_list (l: list M) := exist _ (nodup E l) (NoDup_nodup E l);\n      has s x := nodup_list_in E x s;\n      has_to_list x l := eq_refl;\n      has_from_list := set_mem_nodup E;\n      empty := exist _ nil (NoDup_nil M);\n      empty_to_list := eq_refl;\n      singleton (x: M) := exist _ (x :: nil) (NoDup_cons x (@in_nil _ x) (NoDup_nil M));\n      singleton_to_list (x: M) := eq_refl;\n      size_nat s := length (proj1_sig s);\n      size_nat_to_list s := eq_refl;\n      is_empty s := list_is_empty (proj1_sig s);\n      is_empty_to_list s := list_is_empty_ok (proj1_sig s);\n      size s := N.of_nat (length (proj1_sig s));\n      size_ok s := eq_refl;\n      add s x := nodup_list_add E x s;\n      add_ok s x := nodup_list_add_ok E x s;\n      remove s x := nodup_list_remove E x s;\n      remove_ok s x := nodup_list_remove_ok E x s;\n      union := nodup_list_union E;\n      union_ok := nodup_list_union_ok E;\n      inter := nodup_list_inter E;\n      inter_ok := nodup_list_inter_ok E;\n      diff := nodup_list_diff E;\n      diff_ok := nodup_list_diff_ok E;\n      for_all := nodup_list_forall;\n      for_all_ok := nodup_list_forall_ok E;\n      is_subset := nodup_list_subset E;\n      is_subset_ok := nodup_list_subset_ok E;\n      equal := nodup_list_set_eq E;\n      equal_ok := nodup_list_set_eq_ok E;\n   |}.\n\n(****************************************************************************************)\n\n(* A set of strings based on FSetAVL. *)\n\nModule StringAVLSet := FSetAVL.Make StringLexicalOrder.\nDefinition string_avl_set := StringAVLSet.t.\n\nLemma ina_in {A} (l: list A) (x: A):\n  SetoidList.InA eq x l <-> In x l.\nProof.\ninduction l; split; intro H; inversion H; subst; clear H; cbn; try tauto.\n{ now constructor. }\nrewrite<- IHl in *.\nnow apply SetoidList.InA_cons_tl.\nQed.\n\nLemma nodupa_nodup {A} (l: list A):\n  SetoidList.NoDupA eq l <-> NoDup l.\nProof.\ninduction l; split; intro H; inversion H; subst; clear H; cbn; try tauto; constructor.\n{ rewrite<- ina_in. assumption. }\n{ tauto. }\n{ rewrite ina_in. assumption. }\n{ tauto. }\nQed.\n\nLemma string_avl_set_to_list_nodup (s: string_avl_set):\n  NoDup (StringAVLSet.elements s).\nProof.\nrewrite<- nodupa_nodup.\napply StringAVLSet.elements_3w.\nQed.\n\nLemma string_avl_set_in_to_list x l:\n  StringAVLSet.mem x l = ListSet.set_mem String.string_dec x (StringAVLSet.elements l).\nProof.\nremember (StringAVLSet.mem x l) as m. destruct m; symmetry in Heqm; symmetry.\n{\n  rewrite set_mem_true. rewrite<- ina_in. \n  apply StringAVLSet.elements_1.\n  now apply StringAVLSet.mem_2.\n}\nrewrite set_mem_false. rewrite<- ina_in. \nintro H. apply StringAVLSet.elements_2 in H.\napply StringAVLSet.mem_1 in H.\nrewrite Heqm in H. discriminate.\nQed.\n\nLemma string_avl_set_in_from_list x l:\n  StringAVLSet.mem x\n    (fold_right StringAVLSet.add StringAVLSet.empty l) \n   =\n  ListSet.set_mem String.string_dec x l.\nProof.\ninduction l. { trivial. }\nremember (ListSet.set_mem _ _ _) as m.\nsymmetry in Heqm. destruct m.\n{\n  apply StringAVLSet.mem_2 in IHl.\n  apply set_mem_true in Heqm.\n  assert (T: ListSet.set_mem String.string_dec x (a :: l) = true).\n  {\n    rewrite set_mem_true.\n    cbn. now right.\n  }\n  rewrite T. clear T.\n  apply StringAVLSet.mem_1.\n  cbn.\n  now apply StringAVLSet.add_2.\n}\nrewrite set_mem_false in Heqm.\nmatch goal with\n|- ?lhs = ?rhs => remember lhs as p\nend.\ncbn.\ndestruct String.string_dec as [EQ|NE].\n{ subst. apply StringAVLSet.mem_1. now apply StringAVLSet.add_1. }\nassert (F: p = false).\n{\n  destruct p; trivial.\n  symmetry in Heqp.\n  apply StringAVLSet.mem_2 in Heqp.\n  cbn in Heqp.\n  apply StringAVLSet.add_3 in Heqp.\n  {\n    apply StringAVLSet.mem_1 in Heqp.\n    rewrite<- Heqp. rewrite<- IHl. trivial.\n  }\n  intro H.\n  symmetry in H.\n  contradiction.\n}\nrewrite F. symmetry. now apply set_mem_false.\nQed.\n\nLemma string_avl_set_empty_to_list s:\n  StringAVLSet.is_empty s = true <-> StringAVLSet.elements s = nil.\nProof.\nsplit; intro H.\n{\n  apply StringAVLSet.is_empty_2 in H.\n  unfold StringAVLSet.Empty in H.\n  remember (StringAVLSet.elements s) as e.\n  destruct e as [| h ]. { trivial. }\n  assert (Q: StringAVLSet.In h s).\n  {\n    apply StringAVLSet.elements_2.\n    rewrite ina_in.\n    rewrite<- Heqe.\n    now constructor.\n  }\n  exfalso. exact (H h Q).\n}\napply StringAVLSet.is_empty_1.\nunfold StringAVLSet.Empty.\nintros x J. apply StringAVLSet.elements_1 in J. rewrite ina_in in J.\nrewrite H in J. cbn in J. exact J.\nQed.\n\nLemma string_avl_set_add_ok x s y:\n  StringAVLSet.mem y (StringAVLSet.add x s)\n   =\n  if String.string_dec x y then true else StringAVLSet.mem y s.\nProof.\ndestruct (String.string_dec x y) as [EQ|NE].\n{\n  apply StringAVLSet.mem_1.\n  apply StringAVLSet.add_1.\n  assumption.\n}\nremember (StringAVLSet.mem y s) as y_in.\nsymmetry in Heqy_in.\ndestruct y_in.\n{\n  apply StringAVLSet.mem_2 in Heqy_in.\n  apply StringAVLSet.mem_1.\n  apply StringAVLSet.add_2.\n  assumption.\n}\nremember (StringAVLSet.mem y (StringAVLSet.add x s)) as f.\nsymmetry in Heqf. destruct f; trivial.\napply StringAVLSet.mem_2 in Heqf.\nassert (J := StringAVLSet.add_3 NE Heqf).\napply StringAVLSet.mem_1 in J.\nrewrite<- Heqy_in. rewrite<- J.\ntrivial.\nQed.\n\nLemma string_avl_set_remove_ok x s y:\n  StringAVLSet.mem y (StringAVLSet.remove x s) \n   =\n  if String.string_dec x y then false else StringAVLSet.mem y s.\nProof.\ndestruct (String.string_dec x y) as [EQ|NE].\n{\n  remember (StringAVLSet.mem y _) as f. symmetry in Heqf. destruct f; trivial.\n  apply StringAVLSet.mem_2 in Heqf.\n  apply (StringAVLSet.remove_1 EQ) in Heqf.\n  contradiction.\n}\nremember (StringAVLSet.mem y s) as y_in.\nsymmetry in Heqy_in.\ndestruct y_in.\n{\n  apply StringAVLSet.mem_2 in Heqy_in.\n  apply StringAVLSet.mem_1.\n  exact (StringAVLSet.remove_2 NE Heqy_in).\n}\nremember (StringAVLSet.mem y (StringAVLSet.remove x s)) as f.\nsymmetry in Heqf. destruct f; trivial.\napply StringAVLSet.mem_2 in Heqf.\nassert (J := StringAVLSet.remove_3 Heqf).\napply StringAVLSet.mem_1 in J.\nrewrite<- Heqy_in. rewrite<- J.\ntrivial.\nQed.\n\nLemma string_avl_set_union_ok a b x:\n  StringAVLSet.mem x (StringAVLSet.union a b) = StringAVLSet.mem x a || StringAVLSet.mem x b.\nProof.\nremember (StringAVLSet.mem x (StringAVLSet.union a b)) as in_ab.\nremember (StringAVLSet.mem x a) as in_a.\nremember (StringAVLSet.mem x b) as in_b.\nsymmetry in Heqin_ab. symmetry in Heqin_a. symmetry in Heqin_b.\ndestruct in_ab; destruct in_a; destruct in_b; cbn; trivial; exfalso;\n  try apply StringAVLSet.mem_2 in Heqin_ab;\n  try apply StringAVLSet.mem_2 in Heqin_a;\n  try apply StringAVLSet.mem_2 in Heqin_b.\n{\n  apply StringAVLSet.union_1 in Heqin_ab.\n  case Heqin_ab; intro H; apply StringAVLSet.mem_1 in H; rewrite H in *; easy.\n}\n{ now rewrite (StringAVLSet.mem_1 (StringAVLSet.union_2 b Heqin_a)) in Heqin_ab. }\n{ now rewrite (StringAVLSet.mem_1 (StringAVLSet.union_2 b Heqin_a)) in Heqin_ab. }\nnow rewrite (StringAVLSet.mem_1 (StringAVLSet.union_3 a Heqin_b)) in Heqin_ab.\nQed.\n\nLemma string_avl_set_inter_ok a b x:\n  StringAVLSet.mem x (StringAVLSet.inter a b) = StringAVLSet.mem x a && StringAVLSet.mem x b.\nProof.\nremember (StringAVLSet.mem x (StringAVLSet.inter a b)) as in_ab.\nremember (StringAVLSet.mem x a) as in_a.\nremember (StringAVLSet.mem x b) as in_b.\nsymmetry in Heqin_ab. symmetry in Heqin_a. symmetry in Heqin_b.\ndestruct in_ab; destruct in_a; destruct in_b; cbn; trivial; exfalso;\n  try apply StringAVLSet.mem_2 in Heqin_ab;\n  try apply StringAVLSet.mem_2 in Heqin_a;\n  try apply StringAVLSet.mem_2 in Heqin_b.\n{\n  apply StringAVLSet.inter_2 in Heqin_ab.\n  apply StringAVLSet.mem_1 in Heqin_ab.\n  rewrite Heqin_ab in Heqin_b. discriminate.\n}\n{\n  apply StringAVLSet.inter_1 in Heqin_ab.\n  apply StringAVLSet.mem_1 in Heqin_ab.\n  rewrite Heqin_ab in Heqin_a. discriminate.\n}\n{\n  apply StringAVLSet.inter_1 in Heqin_ab.\n  apply StringAVLSet.mem_1 in Heqin_ab.\n  rewrite Heqin_ab in Heqin_a. discriminate.\n}\nnow rewrite (StringAVLSet.mem_1 (StringAVLSet.inter_3 Heqin_a Heqin_b)) in Heqin_ab.\nQed.\n\nLemma string_avl_set_diff_ok a b x:\n  StringAVLSet.mem x (StringAVLSet.diff a b) = StringAVLSet.mem x a && negb (StringAVLSet.mem x b).\nProof.\nremember (StringAVLSet.mem x (StringAVLSet.diff a b)) as in_ab.\nremember (StringAVLSet.mem x a) as in_a.\nremember (StringAVLSet.mem x b) as in_b.\nsymmetry in Heqin_ab. symmetry in Heqin_a. symmetry in Heqin_b.\ndestruct in_ab; destruct in_a; destruct in_b; cbn; trivial;\n  try apply StringAVLSet.mem_2 in Heqin_ab;\n  try apply StringAVLSet.mem_2 in Heqin_a;\n  try apply StringAVLSet.mem_2 in Heqin_b.\n{ now apply StringAVLSet.diff_2 in Heqin_ab. }\n{\n  apply StringAVLSet.diff_1 in Heqin_ab.\n  apply StringAVLSet.mem_1 in Heqin_ab.\n  rewrite Heqin_ab in Heqin_a. discriminate.\n}\n{\n  apply StringAVLSet.diff_1 in Heqin_ab.\n  apply StringAVLSet.mem_1 in Heqin_ab.\n  rewrite Heqin_ab in Heqin_a. discriminate.\n}\napply StringAVLSet.diff_3 with (s' := b) in Heqin_a.\n{\n  apply StringAVLSet.mem_1 in Heqin_a.\n  rewrite Heqin_ab in Heqin_a. discriminate.\n}\nintro H. apply StringAVLSet.mem_1 in H.\nrewrite H in Heqin_b. discriminate.\nQed.\n\nLemma string_avl_set_forall_ok s (p: String.string -> bool):\n  StringAVLSet.for_all p s = true \n   <->\n  forall x,\n    StringAVLSet.mem x s = true -> p x = true.\nProof.\nsplit; intro H.\n{\n  apply StringAVLSet.for_all_2 in H.\n  {\n    intros x XIn.\n    unfold StringAVLSet.For_all in H.\n    apply StringAVLSet.mem_2 in XIn.\n    exact (H x XIn).\n  }\n  intros x y E. now subst.\n}\napply StringAVLSet.for_all_1.\n{ intros x y E. now subst. }\nintros x XIn.\napply H.\nnow apply StringAVLSet.mem_1.\nQed.\n\nLemma string_avl_set_subset_ok a b:\n StringAVLSet.subset a b = true \n  <->\n forall x,\n   negb (StringAVLSet.mem x a) || StringAVLSet.mem x b = true.\nProof.\nsplit; intro H.\n{\n  apply StringAVLSet.subset_2 in H.\n  unfold StringAVLSet.Subset in H.\n  intro x.\n  remember (StringAVLSet.mem x a) as in_a.\n  remember (StringAVLSet.mem x b) as in_b.\n  symmetry in Heqin_a. symmetry in Heqin_b.\n  destruct in_a; destruct in_b; cbn; trivial;\n    try apply StringAVLSet.mem_2 in Heqin_a;\n    try apply StringAVLSet.mem_2 in Heqin_b.\n  now rewrite (StringAVLSet.mem_1 (H _ Heqin_a)) in Heqin_b.\n}\napply StringAVLSet.subset_1.\nintros x InA.\napply StringAVLSet.mem_1 in InA.\napply StringAVLSet.mem_2.\nassert (Q := H x).\nrewrite InA in Q.\nremember (StringAVLSet.mem x b) as in_b.\nsymmetry in Heqin_b. destruct in_b; trivial.\nQed.\n\nLemma string_avl_set_eq_ok a b:\n  StringAVLSet.equal a b = true \n   <->\n  forall x,\n    StringAVLSet.mem x a = StringAVLSet.mem x b.\nProof.\nsplit; intro H.\n{\n  intro x.\n  apply StringAVLSet.equal_2 in H.\n  unfold StringAVLSet.Equal in H.\n  remember (StringAVLSet.mem x a) as in_a.\n  remember (StringAVLSet.mem x b) as in_b.\n  symmetry. symmetry in Heqin_a. symmetry in Heqin_b.\n  destruct in_a; destruct in_b; cbn; trivial;\n    try apply StringAVLSet.mem_2 in Heqin_a;\n    try apply StringAVLSet.mem_2 in Heqin_b;\n    try discriminate.\n  { \n    rewrite (H x) in Heqin_a;\n    rewrite (StringAVLSet.mem_1 Heqin_a) in Heqin_b.\n    discriminate.\n  }\n  rewrite<- (H x) in Heqin_b.\n  rewrite (StringAVLSet.mem_1 Heqin_b) in Heqin_a.\n  discriminate.\n}\napply StringAVLSet.equal_1.\nunfold StringAVLSet.Equal.\nintro x.\nremember (StringAVLSet.mem x a) as in_a.\nremember (StringAVLSet.mem x b) as in_b.\nsymmetry. symmetry in Heqin_a. symmetry in Heqin_b.\ndestruct in_a; destruct in_b; cbn; trivial;\n  try (rewrite (H x) in Heqin_a; rewrite Heqin_a in Heqin_b; discriminate);\n  try apply StringAVLSet.mem_2 in Heqin_a;\n  try apply StringAVLSet.mem_2 in Heqin_b;\n  try tauto.\nsplit; intro Z; apply StringAVLSet.mem_1 in Z; rewrite Z in *; discriminate.\nQed.\n\nInstance string_avl_set_impl: class String.string_dec string_avl_set\n:= {|\n      to_list := StringAVLSet.elements;\n      to_list_nodup := string_avl_set_to_list_nodup;\n      from_list l := fold_right StringAVLSet.add StringAVLSet.empty l;\n      has s x := StringAVLSet.mem x s;\n      has_to_list := string_avl_set_in_to_list;\n      has_from_list := string_avl_set_in_from_list;\n      empty := StringAVLSet.empty;\n      empty_to_list := eq_refl;\n      singleton := StringAVLSet.singleton;\n      singleton_to_list s := eq_refl;\n      size_nat := StringAVLSet.cardinal;\n      size_nat_to_list := StringAVLSet.cardinal_1;\n      is_empty := StringAVLSet.is_empty;\n      is_empty_to_list := string_avl_set_empty_to_list;\n      size s := N.of_nat (StringAVLSet.cardinal s);\n      size_ok s := eq_refl;\n      add s x := StringAVLSet.add x s;\n      add_ok s x := string_avl_set_add_ok x s;\n      remove s x := StringAVLSet.remove x s;\n      remove_ok s x := string_avl_set_remove_ok x s;\n      union := StringAVLSet.union;\n      union_ok := string_avl_set_union_ok;\n      inter := StringAVLSet.inter;\n      inter_ok := string_avl_set_inter_ok;\n      diff := StringAVLSet.diff;\n      diff_ok := string_avl_set_diff_ok;\n      for_all s p := StringAVLSet.for_all p s;\n      for_all_ok := string_avl_set_forall_ok;\n      is_subset := StringAVLSet.subset;\n      is_subset_ok := string_avl_set_subset_ok;\n      equal := StringAVLSet.equal;\n      equal_ok := string_avl_set_eq_ok;\n   |}.\n\n(****************************************************************************************)\n\n\nSection SetFacts.\n\nContext {M: Type} {E: forall x y: M, {x = y} + {x <> y}} {S: Type} {C: class E S}.\n\nLemma empty_ok (x: M):\n  has empty x = false.\nProof.\nrewrite has_to_list.\nrewrite empty_to_list; auto.\nQed.\n\nLemma singleton_ok (x y: M):\n  has (singleton x) y = true <-> x = y.\nProof.\nrewrite has_to_list.\nrewrite singleton_to_list.\ncbn.\ndestruct E as [EQ|NE]. { symmetry in EQ. tauto. }\nsplit; intro H. { congruence. }\nsymmetry in H. contradiction.\nQed.\n\nLemma is_empty_true (a: S) (H: is_empty a = true) (x: M):\n  has a x = false.\nProof.\nrewrite has_to_list. rewrite is_empty_to_list in H. \nrewrite H. trivial.\nQed.\n\nLemma is_empty_false (a: S) (H: is_empty a = false):\n  exists x: M,\n    has a x = true.\nProof.\nremember (to_list a) as l.\ndestruct l.\n{\n  symmetry in Heql. rewrite<- is_empty_to_list in Heql. \n  rewrite Heql in H. congruence.\n}\nexists m.\nrewrite has_to_list.\nrewrite<- Heql.\ncbn. now destruct E.\nQed.\n\nLemma add_has (x: M) (s: S):\n  has (add s x) x = true.\nProof.\nrewrite add_ok. now destruct E.\nQed.\n\nLemma is_subset_refl (a: S):\n  is_subset a a = true.\nProof.\nrewrite is_subset_ok. intro x.\nbool. destruct has; tauto.\nQed.\n\nLemma is_subset_equal (a b: S) (Eq: equal a b = true):\n  is_subset a b = true.\nProof.\nrewrite is_subset_ok. rewrite equal_ok in Eq. intro x.\nrewrite (Eq x).\ndestruct has; tauto.\nQed.\n\nLemma is_subset_trans {a b c: S}\n                      (AB: is_subset a b = true)\n                      (BC: is_subset b c = true):\n  is_subset a c = true.\nProof.\nrewrite is_subset_ok in *. intro x.\nassert (ABx := AB x).\nassert (BCx := BC x).\nbool.\ndestruct has; destruct has; destruct has; tauto.\nQed.\n\nLemma is_subset_antisym {a b: S}\n                        (AB: is_subset a b = true)\n                        (BC: is_subset b a = true):\n  equal a b = true.\nProof. \nrewrite is_subset_ok in AB.\nrewrite is_subset_ok in BC.\nrewrite equal_ok. intro x.\nassert (ABx := AB x).\nassert (BCx := BC x).\nbool.\ndestruct has; destruct has; trivial; case ABx; case BCx; try tauto; \n  intros; try tauto; symmetry; tauto.\nQed.\n\nLemma add_subset (x: M) (s: S):\n  is_subset s (add s x) = true.\nProof.\nrewrite is_subset_ok. intro y.\nrewrite add_ok. bool. destruct (E x y); try tauto.\ndestruct has; tauto.\nQed.\n\nLemma union_subset_l (a b: S):\n  is_subset a (union a b) = true.\nProof.\nrewrite is_subset_ok. intro x.\nrewrite union_ok.\ndestruct has; now destruct has.\nQed.\n\nLemma union_subset_r (a b: S):\n  is_subset b (union a b) = true.\nProof.\nrewrite is_subset_ok. intro x.\nrewrite union_ok.\ndestruct has; now destruct has.\nQed.\n\nLemma inter_subset_l (a b: S):\n  is_subset (inter a b) a = true.\nProof.\nrewrite is_subset_ok. intro x.\nrewrite inter_ok.\ndestruct has; now destruct has.\nQed.\n\nLemma inter_subset_r (a b: S):\n  is_subset (inter a b) b = true.\nProof.\nrewrite is_subset_ok. intro x.\nrewrite inter_ok.\ndestruct has; now destruct has.\nQed.\n\nLemma union_monotonic_l (a b c: S)\n                        (H: is_subset a b = true):\n  is_subset (union a c) (union b c) = true.\nProof.\nrewrite is_subset_ok in *. intro x.\nrepeat rewrite union_ok.\nassert (Hx := H x). clear H.\ndestruct (has a x); destruct (has b x); destruct (has c x); tauto.\nQed.\n\nLemma union_monotonic_r (a b c: S)\n                        (H: is_subset b c = true):\n  is_subset (union a b) (union a c) = true.\nProof.\nrewrite is_subset_ok in *. intro x.\nrepeat rewrite union_ok.\nassert (Hx := H x). clear H.\ndestruct (has a x); destruct (has b x); destruct (has c x); tauto.\nQed.\n\nLemma inter_monotonic_l (a b c: S)\n                        (H: is_subset a b = true):\n  is_subset (inter a c) (inter b c) = true.\nProof.\nrewrite is_subset_ok in *. intro x.\nrepeat rewrite inter_ok.\nassert (Hx := H x). clear H.\ndestruct (has a x); destruct (has b x); destruct (has c x); tauto.\nQed.\n\nLemma inter_monotonic_r (a b c: S)\n                        (H: is_subset b c = true):\n  is_subset (inter a b) (inter a c) = true.\nProof.\nrewrite is_subset_ok in *. intro x.\nrepeat rewrite inter_ok.\nassert (Hx := H x). clear H.\ndestruct (has a x); destruct (has b x); destruct (has c x); tauto.\nQed.\n\nEnd SetFacts.\n", "meta": {"author": "formalize", "repo": "coq-yul", "sha": "1433d729982f1b18e381dbfef64df4961e2f30b1", "save_path": "github-repos/coq/formalize-coq-yul", "path": "github-repos/coq/formalize-coq-yul/coq-yul-1433d729982f1b18e381dbfef64df4961e2f30b1/FSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.6730809565627981}}
{"text": "(*|\n##############################################################\nProving uniqueness of an instance of an indexed inductive type\n##############################################################\n\n:Link: https://proofassistants.stackexchange.com/q/1246\n|*)\n\n(*|\nQuestion\n********\n\nConsider the simple indexed inductive type\n|*)\n\nInductive Single : nat -> Set :=\n| single_O : Single O\n| single_S {n} : Single n -> Single (S n).\n\n(*|\nIntuitively, I thought that ``Single n`` has a unique value for each\n``n : nat``. I started by trying to prove that ``forall s : Single O,\ns = single_O``. However, the usual tactics ``inversion``,\n``destruct``, and ``induction`` did not work:\n|*)\n\nLemma single_O_unique (s : Single O) : s = single_O.\n  inversion s. (* No effect *)\n  Fail destruct s.\n  Fail induction s.\n\n(*| The error messages were: |*)\n\n  Fail destruct s. (* .unfold .messages *)\n\n(*| So I resorted to a manual ``match`` expression: |*)\n\n  refine match s with\n         | single_O => _\n         | single_S _ => _\n         end.\n\n(*| Resulting in the following proof context: |*)\n\n  Show. (* .unfold .messages *)\n\n(*| which was puzzling, but easy to prove: |*)\n\n  - reflexivity.\n  - exact idProp.\nQed.\n\n(*|\nQuestions:\n\n- Why was ``inversion`` unable to recognize that ``s`` could only be\n  ``single_O`` and substitute accordingly?\n- Why did the ``refine`` tactic produce the subgoal ``IDProp``?\n- Is there a way to get ``inversion`` or ``destruct`` to work in this\n  case? Or, what would a better way to prove ``s = single_O``?\n\nFull example:\n|*)\n\nReset Initial. (* .none *)\nInductive Single : nat -> Set :=\n| single_O : Single O\n| single_S {n} : Single n -> Single (S n).\n\nLemma single_O_unique (s : Single O) : s = single_O.\n  inversion s.  (* No effect *)\n  Fail destruct s.\n  Fail induction s.\n  refine match s with\n         | single_O => _\n         | single_S _ => _\n         end.\n  - reflexivity.\n  - exact idProp.\nQed.\n\n(*|\nAnswer (gallais)\n****************\n\n    Or, what would a better way to prove ``s = single_O``?\n\nI would define a function that, given a nat ``n``, computes the\ncanonical proof ``Single n``.\n|*)\n\nReset single_O_unique. (* .none *)\nFixpoint Canonical (n : nat) : Single n :=\n  match n with\n  | O => single_O\n  | S n => single_S (Canonical n)\n  end.\n\n(*|\nYou can then easily prove that any ``Single n`` proof is equal to the\ncanonical one by induction. Here the abstraction won't fail because\nthe equality is already generic over ``n``.\n|*)\n\nLemma single_canonical (n : nat) (s : Single n) : s = Canonical n.\nProof.\n  induction s.\n  - reflexivity.\n  - simpl. f_equal. assumption.\nQed.\n\n(*| Your original lemma is then a direct corollary. |*)\n\nLemma single_O_unique (s : Single O) : s = single_O.\n  apply single_canonical with (n := O).\nQed.\n\n(*|\nAnswer (Meven Lennon-Bertrand)\n******************************\n\nRegarding ``IDProp``, this is the pattern-matching compilation of Coq\nat work. Basically, because you scrutinee has a type that can only\ncorrespond to the ``single_O`` branch, Coq was smart enough to craft a\nreturn predicate that gave you an interesting goal only in that\nbranch, the other being replaced by the trivially inhabited ``IDProp``\n(as you noticed in your proof). So ``match`` was smart enough \"to\nrecognize that ``s`` could only be ``single_O``\". If you wish to see\nwhat exactly happened, you can use the ``Show Proof.`` command.\n\nI'm a bit suprised that ``destruct``, ``inversion`` and friends, which\nare supposed to be built on top of pattern-matching, were not able to\nsucceed where the simpler ``refine (match …)`` was. In such cases with\ncomplex dependencies, ``dependent inversion`` works better than\n``inversion``, but it still fails here, sadly.\n\nIf you wish to have ``inversion`` work here, you'd have to replace\n``single_O`` by something generic enough. Using gallais' solution, you\ncan do\n|*)\n\nReset Canonical. (* .none *)\nFixpoint Canonical (n : nat) : Single n :=\n  match n with\n  | O => single_O\n  | S n => single_S (Canonical n)\n  end.\n\nLemma single_O_can (s : Single 0) : s = single_O.\nProof.\n  change single_O with (Canonical 0).\n  dependent inversion s.\n  reflexivity.\nQed.\n\n(*|\nNow ``dependent inversion`` succeeds because ``Canonical 0`` can\nsuccessfully be abstracted over ``0``, while ``single_O`` could not.\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/proving-uniqueness-of-an-instance-of-an-indexed-inductive-type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.8459424314825852, "lm_q1q2_score": 0.6730809559941803}}
{"text": "Inductive Ty: Set :=\n  ty_o: Ty | ty_arr: Ty -> Ty -> Ty.\n\nInductive Con: Set :=\n  con_empty: Con | con_cons: Con -> Ty -> Con.\n\nInductive Var: Con -> Ty -> Set :=\n  | var_zero: forall g s, Var (con_cons g s) s\n  | var_suc: forall g t s, Var g s -> Var (con_cons g t) s.\n\nInductive Tm: Con -> Ty -> Set :=\n  | tm_var: forall g s, Var g s -> Tm g s\n  | tm_app: forall g s t, Tm g (ty_arr s t) -> Tm g s -> Tm g t\n  | tm_lam: forall g s t, Tm (con_cons g s) t -> Tm g (ty_arr s t).", "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/STLC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100817, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.673055654744137}}
{"text": "Require Import Omega.\n\nLocal Open Scope nat_scope.\n\nInductive period : Type :=\n| Period (a b : nat).\n\nDefinition pstart (p : period) : nat :=\n  match p with | Period a b => a end.\n\nDefinition pend (p : period) : nat :=\n  match p with | Period a b => b end.\n\nInductive periodR : period -> Prop :=\n| PeriodR : forall p,\n    (* By definition, a period's end tstamp is strictly greater than its start. *)\n    pstart p < pend p ->\n    periodR p.\n\nInductive overlapsTeradataR : period -> period -> Prop :=\n| TeradataSGt : forall p1 p2,\n    periodR p1 ->\n    periodR p2 ->\n    (pstart p1) > (pstart p2) ->\n    ~ (pstart p1 >= pend p2 /\\ pend p1 >= pend p2) ->\n    (overlapsTeradataR p1 p2)\n| TeradataSLt : forall p1 p2,\n    periodR p1 ->\n    periodR p2 ->\n    (pstart p2) > (pstart p1) ->\n    ~ (pstart p2 >= pend p1 /\\ pend p2 >= pend p1) ->\n    (overlapsTeradataR p1 p2)\n| TeradataSEq : forall p1 p2,\n    periodR p1 ->\n    periodR p2 ->\n    pstart p1 = pstart p2 ->\n    (pend p1 = pend p2 \\/ pend p1 <> pend p2) ->\n    (overlapsTeradataR p1 p2).\n\nInductive overlapsBigQueryR : period -> period -> Prop :=\n| BigQuery : forall p1 p2,\n    periodR p1 ->\n    periodR p2 ->\n    max (pstart p1) (pstart p2) < min (pend p1) (pend p2) ->\n    (overlapsBigQueryR p1 p2).\n\nTheorem overlaps_Teradata_BigQuery_equiv : forall p1 p2 : period,\n    overlapsTeradataR p1 p2 <-> overlapsBigQueryR p1 p2.\nProof.  \n  split.\n  - intros H. inversion H; subst;\n    inversion H0; inversion H1; subst; apply BigQuery; try assumption;\n      try (apply Decidable.not_and in H3; try apply dec_ge);\n      destruct H3 as [|].\n      * rewrite max_l.\n        + apply not_le in H3. apply Nat.min_glb_lt; assumption.\n        + apply not_ge in H3. rewrite Nat.lt_eq_cases. left. assumption.\n      * rewrite min_l; apply not_ge in H3.\n        + rewrite max_l. assumption.\n          rewrite Nat.lt_eq_cases. left. assumption.\n        + rewrite Nat.lt_eq_cases. left. assumption.\n      * rewrite max_r.\n        + apply not_ge in H3. apply Nat.min_glb_lt; assumption.\n        + rewrite Nat.lt_eq_cases. left. assumption.\n      * rewrite max_r.\n        + rewrite min_r. assumption.\n          rewrite Nat.lt_eq_cases. apply not_ge in H3. left. assumption.\n        + rewrite Nat.lt_eq_cases. left. assumption.\n      * rewrite max_r.\n        + rewrite min_r. assumption.\n          rewrite Nat.lt_eq_cases. right. symmetry. assumption.\n        + rewrite Nat.lt_eq_cases. right. assumption.\n      * rewrite max_r.\n        + rewrite H2 in H4. apply Nat.min_glb_lt; assumption.\n        + rewrite Nat.lt_eq_cases. right. assumption.\n  - intros H. inversion H. subst.\n    apply Nat.max_lub_lt_iff in H2.\n    destruct H2 as [H3 H4].\n    apply Nat.min_glb_lt_iff in H3.\n    apply Nat.min_glb_lt_iff in H4.\n    destruct H3. destruct H4.\n    assert (HMQ:=Nat.max_spec (pstart p1) (pstart p2)).\n    destruct HMQ as [|]; destruct H6 as [].\n    * apply TeradataSLt.\n      apply PeriodR. assumption. assumption. assumption.\n      unfold not. intros. destruct H8 as []. intuition.\n    * rewrite Nat.lt_eq_cases in H6. destruct H6 as [|].\n      + apply TeradataSGt.\n        apply PeriodR. assumption. assumption. assumption.\n        unfold not. intros. destruct H8 as []. intuition.\n      + apply TeradataSEq.\n        apply PeriodR. assumption. assumption. auto.\n        decide equality.\nQed.\n", "meta": {"author": "mattjquinn", "repo": "teradata-overlaps-proof", "sha": "34bb8ad9d7a402fa2879b44f591070a4c7858224", "save_path": "github-repos/coq/mattjquinn-teradata-overlaps-proof", "path": "github-repos/coq/mattjquinn-teradata-overlaps-proof/teradata-overlaps-proof-34bb8ad9d7a402fa2879b44f591070a4c7858224/overlaps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6729787898533803}}
{"text": "\nTheorem ExF002 {X : Type} (P Q : X -> Prop) (a : X): (forall x, P x -> Q x) -> P a -> Q a.\nProof.\n  intros.\n  specialize (H a).\n  apply H.\n  exact H0.\nQed.\n\n\n", "meta": {"author": "SvenWille", "repo": "CoqLogicExercises", "sha": "b4c1aea30abb95dc7ba81fa42ccb914d534d65e5", "save_path": "github-repos/coq/SvenWille-CoqLogicExercises", "path": "github-repos/coq/SvenWille-CoqLogicExercises/CoqLogicExercises-b4c1aea30abb95dc7ba81fa42ccb914d534d65e5/src/FOL/ExF002.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.6729787891127037}}
{"text": "Require Coq.Setoids.Setoid.\n(*\n\tThe following axiom systems are used to formalize\n\tEuclid's proofs of Euclid's Elements.OriginalProofs.statements.\n*)\n\n(*\n\tFirst, we define an axiom system for neutral geometry,\n\ti.e. geometry without continuity axioms nor parallel postulate.\n*)\n\nClass euclidean_neutral :=\n{\n\tPoint : Type;\n\tCircle : Type;\n\tCong : Point -> Point -> Point -> Point -> Prop;\n\tBetS : Point -> Point -> Point -> Prop;\n\t(* TODO: rename to Circle *)\n\tCI : Circle -> Point -> Point -> Point -> Prop;\n\teq := @eq Point;\n\tneq A B := ~ eq A B;\n\tnCol A B C := neq A B /\\ neq A C /\\ neq B C /\\ ~ BetS A B C /\\ ~ BetS A C B /\\ ~ BetS B A C;\n\tCol A B C := (eq A B \\/ eq A C \\/ eq B C \\/ BetS B A C \\/ BetS A B C \\/ BetS A C B);\n\t(* C and D are on opposite sides of AB *)\n\t(* TODO: rename to OppositeSides *)\n\tOS P A B Q := exists X, BetS P X Q /\\ Col A B X /\\ nCol A B P;\n\tTriangle A B C := nCol A B C;\n\n\n\tOnCirc B J := exists X Y U, CI J U X Y /\\ Cong U B X Y;\n\tInCirc P J := exists X Y U V W, CI J U V W /\\ (eq P U \\/ (BetS U Y X /\\ Cong U X V W /\\ Cong U P U Y));\n\tOutCirc P J := exists X U V W, CI J U V W /\\ BetS U X P /\\ Cong U X V W;\n\n\tcn_congruencetransitive :\n\t\tforall A B C D E F, Cong A B C D -> Cong A B E F -> Cong C D E F;\n\tcn_congruencereflexive :\n\t\tforall A B, Cong A B A B;\n\t(* Originally known as cn_equalityreverse *)\n\tcn_congruencereverse :\n\t\tforall A B, Cong A B B A;\n\tcn_sumofparts :\n\t\tforall A B C a b c,\n\t\t\tCong A B a b -> Cong B C b c -> BetS A B C -> BetS a b c -> Cong A C a c;\n\n\n\taxiom_circle_center_radius :\n\t\tforall A B C J P, CI J A B C -> OnCirc P J -> Cong A P B C;\n\taxiom_betweennessidentity :\n\t\tforall A B, ~ BetS A B A;\n\taxiom_betweennesssymmetry :\n\t\tforall A B C, BetS A B C -> BetS C B A;\n\t(* Originally known as axiom_innertransitivity *)\n\taxiom_orderofpoints_ABD_BCD_ABC :\n\t\tforall A B C D,\n\t\t\tBetS A B D -> BetS B C D -> BetS A B C;\n\taxiom_connectivity :\n\t\tforall A B C D,\n\t\t\tBetS A B D -> BetS A C D -> ~ BetS A B C -> ~ BetS A C B ->\n\t\t\teq B C;\n\n\n\n\taxiom_nocollapse :\n\t\tforall A B C D, neq A B -> Cong A B C D -> neq C D;\n\t(* 6.4 Five-line axiom *)\n\t(* Called Five Segment in Tarski *)\n\t(*\n\t\tThe order and list of antecedents is changed to make the axiom easier to remember.\n\n\t\t0.\tNot stated: ∃ △ABD , △abd , △DBC , △dbc , possibly degenerate.\n\n\t\t1.\t△ABD ≅ △abd by SSS congruence.\n\n\t\t2.\t(B(A,B,C) /\\ B(a,b,c)) implies that\n\t\t\t∠ABD is supplement to ∠DBC and ∠abd is supplement to ∠dbc .\n\t\t3.\t#1 implies that ∠ABD ≅ ∠abd .\n\t\t4.\t#2 and #3 imply that ∠DBC ≅ ∠dbc .\n\n\t\t5.\t(DB ≅ db /\\ ∠DBC ≅ ∠dbc (from #4) /\\ BC ≅ bc) implies that\n\t\t\t△DBC ≅ △dbc by SAS congruence.\n\t*)\n\t(*\n\t\tAdding lemma_5_line_degenerate would make it obvious when degenerate triangles are used.\n\t\tThis is not done, since axiom_5_line is commonly used to help prove betweenness or equality,\n\t\twhich are needed to show that the triangles used are in fact degenerate.\n\t*)\n\taxiom_5_line :\n\t\tforall A B C D a b c d,\n\t\t\tCong A B a b ->\n\t\t\tCong B D b d ->\n\t\t\tCong D A d a ->\n\n\t\t\tBetS A B C ->\n\t\t\tBetS a b c ->\n\n\t\t\tCong D B d b ->\n\t\t\tCong B C b c ->\n\n\t\t\tCong C D c d;\n\n\n\tpostulate_Pasch_inner :\n\t\tforall A B C P Q,\n\t\t\tBetS A P C -> BetS B Q C -> nCol A C B ->\n\t\t\texists X, BetS A X Q /\\ BetS B X P;\n\tpostulate_Pasch_outer :\n\t\tforall A B C P Q,\n\t\t\tBetS A P C -> BetS B C Q -> nCol B Q A ->\n\t\t\texists X, BetS A X Q /\\ BetS B P X;\n\n\tpostulate_Euclid2 : forall A B, neq A B -> exists X, BetS A B X;\n\tpostulate_Euclid3 : forall A B, neq A B -> exists X, CI X A A B;\n}.\n\n(*\n\tSecond, we enrich the axiom system with line-circle\n\tand circle-circle continuity axioms.\n\tThose two axioms state that we allow ruler and compass constructions.\n*)\n\nClass euclidean_neutral_ruler_compass `(Ax : euclidean_neutral) :=\n{\n\tpostulate_line_circle :\n\t\tforall A B C K P Q,\n\t\t\tCI K C P Q -> InCirc B K -> neq A B ->\n\t\t\texists X Y, Col A B X /\\ BetS A B Y /\\ OnCirc X K /\\ OnCirc Y K /\\ BetS X B Y;\n\tpostulate_circle_circle :\n\t\tforall C D F G J K P Q R S,\n\t\t\tCI J C R S -> InCirc P J ->\n\t\t\tOutCirc Q J -> CI K D F G ->\n\t\t\tOnCirc P K -> OnCirc Q K ->\n\t\t\texists X, OnCirc X J /\\ OnCirc X K\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/euclidean_axioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6729787891127035}}
{"text": "Require Import Coq.Classes.Equivalence.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.QArith.QArith.\nRequire Import Coq.QArith.Qminmax.\nRequire Import Coq.Relations.Relations.\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Unicode.Utf8.\nRequire Import Iteration.Lattice.\n\n(* Rationals with ±+∞ *)\n\nReserved Notation \"+∞\" (at level 0).\nReserved Notation \"-∞\" (at level 0).\n\nDeclare Scope QInf_scope.\nDelimit Scope QInf_scope with QInf.\n\nModule QInf.\n\n  Local Open Scope Q_scope.\n  Local Open Scope QInf_scope.\n\n  Inductive t :=\n    NegInf : t \n  | PosInf : t \n  | Fin : Q → t.\n\n  Coercion Fin : Q >-> t.\n\n  Notation \"+∞\" := PosInf : QInf_scope.\n  Notation \"-∞\" := NegInf : QInf_scope.\n\n  Definition eqb n m :=\n    match n, m with\n    | +∞, +∞ => true\n    | -∞, -∞ => true\n    | Fin n, Fin m => Qeq_bool n m\n    | _, _ => false\n    end.\n\n  Definition eq n m := eqb n m = true.\n\n  Infix \"==\" := eq : QInf_scope.\n  \n  Hint Unfold eq eqb : core.\n\n  Lemma eq_refl : Reflexive eq.\n  Proof.\n    intros x.\n    destruct x; try reflexivity.\n    apply Qeq_bool_refl.\n  Qed.\n\n  Lemma eq_sym : Symmetric eq.\n  Proof.\n    intros x y H.\n    destruct x; destruct y; inversion H; try reflexivity.\n    apply Qeq_bool_sym.\n    assumption.\n  Qed.\n\n  Lemma eq_trans : Transitive eq.\n  Proof.\n    intros x y z P Q.\n    destruct x; destruct y; destruct z; inversion P; inversion Q; try reflexivity.\n    apply (Qeq_bool_trans _ _ _ P Q).\n  Qed.\n\n  Lemma eq_Qeq : ∀ x y, (x == y)%Q → (x == y)%QInf.\n  Proof.\n    intros x y.\n    apply Qeq_bool_iff.\n  Qed.\n\n  Global Instance Equivalence_eq : Equivalence eq := {|\n    Equivalence_Reflexive := eq_refl;\n    Equivalence_Symmetric := eq_sym;\n    Equivalence_Transitive := eq_trans;\n  |}.\n\n  Add Relation t eq\n    reflexivity proved by eq_refl\n    symmetry proved by eq_sym\n    transitivity proved by eq_trans\n    as eq_qinf_rel.\n\n  Definition leb n m :=\n    match n, m with\n    | +∞, +∞ => true\n    | +∞, _ => false\n    | _, +∞ => true\n    | -∞, _ => true\n    | _, -∞ => false\n    | Fin n, Fin m => Qle_bool n m\n    end.\n\n  Definition le n m := leb n m = true.\n\n  Infix \"<=\" := le : QInf_scope.\n  Infix \"≤\" := le : QInf_scope.\n\n  Hint Unfold le leb : core.\n\n  Lemma le_refl : Reflexive le.\n  Proof.\n    intros x.\n    destruct x; try reflexivity.\n    unfold le, leb.\n    rewrite Qle_bool_iff.\n    apply Qle_refl.\n  Qed.\n\n  Lemma le_trans : Transitive le.\n  Proof.\n    intros x y z P Q.\n    destruct x; destruct y; destruct z; inversion P; inversion Q; try reflexivity.\n    unfold le, leb in *.\n    rewrite Qle_bool_iff in *.\n    apply (Qle_trans _ _ _ P Q).\n  Qed.\n\n  Global Instance PreOrder_le : PreOrder le := {|\n    PreOrder_Reflexive := le_refl;\n    PreOrder_Transitive := le_trans;\n  |}.\n\n  Global Instance PartialOrder_eq_le : PartialOrder eq le.\n  Proof.\n    intros x y.\n    split.\n    - intros H.\n      split;\n        destruct x; destruct y; inversion H; try reflexivity;\n        apply Qle_bool_iff;\n        apply Qeq_bool_eq in H1;\n        rewrite H1;\n        apply Qle_refl.\n    - intros H.\n      destruct H as [P Q].\n      destruct x; destruct y; inversion P; inversion Q; try reflexivity.\n      apply Qeq_eq_bool.\n      apply Qle_bool_iff in H0.\n      apply Qle_bool_iff in H1.\n      apply (Qle_antisym _ _ H0 H1).\n  Qed.\n\n  Add Morphism le with\n    signature eq ==> eq ==> iff as le_mor.\n  Proof.\n    intros x y P z w Q.\n    split.\n    - intros H.\n      destruct x; destruct y; destruct z; destruct w;\n      inversion P; inversion Q; inversion H; try reflexivity.\n      apply Qle_bool_iff.\n      apply Qeq_bool_eq in H1.\n      apply Qeq_bool_eq in H2.\n      apply Qle_bool_iff in H3.\n      rewrite H2 in H3.\n      rewrite H1 in H3.\n      assumption.\n    - intros H.\n      destruct x; destruct y; destruct z; destruct w;\n      inversion P; inversion Q; inversion H; unfold le, leb; try reflexivity.\n      apply Qle_bool_iff.\n      apply Qeq_bool_eq in H1.\n      apply Qeq_bool_eq in H2.\n      apply Qle_bool_iff in H3.\n      rewrite <- H2 in H3.\n      rewrite <- H1 in H3.\n      assumption.\n  Qed.\n\n  Definition add n m :=\n    match n with\n    | -∞ => -∞\n    | +∞ => +∞\n    | Fin n => n + m\n    end.\n\n  Infix \"+\" := add : QInf_scope.\n\n  Add Morphism add with\n    signature eq ==> Qeq ==> eq as add_mor.\n  Proof.\n    intros x y P z w Q.\n    destruct x; destruct y; destruct z; destruct w;\n    inversion P; inversion Q; try reflexivity.\n    clear H1.\n    remember (Qnum # Qden) as x.\n    remember (Qnum0 # Qden0) as y.\n    unfold add, eq, eqb in *.\n    apply Qeq_bool_iff.\n    apply Qeq_bool_iff in P.\n    rewrite P.\n    rewrite Q.\n    reflexivity.\n  Qed.\n\n  Definition sub n m :=\n    match n with\n    | -∞ => -∞\n    | +∞ => +∞\n    | Fin n => n - m\n    end.\n\n  Infix \"-\" := sub : QInf_scope.\n\n  Add Morphism sub with\n    signature eq ==> Qeq ==> eq as sub_mor.\n  Proof.\n    intros x y P z w Q.\n    destruct x; destruct y; destruct z; destruct w;\n    inversion P; inversion Q; try reflexivity.\n    clear H1.\n    remember (Qnum # Qden) as x.\n    remember (Qnum0 # Qden0) as y.\n    unfold sub, eq, eqb in *.\n    apply Qeq_bool_iff.\n    apply Qeq_bool_iff in P.\n    rewrite P.\n    rewrite Q.\n    reflexivity.\n  Qed.\n\n  Definition min n m :=\n    match n, m with\n    | -∞, _ => -∞\n    | _, -∞ => -∞\n    | +∞, m => m\n    | n, +∞ => n\n    | Fin n, Fin m => Qmin n m\n    end.\n\n  Lemma min_comm : ∀ n m, (min n m == min m n)%QInf.\n  Proof.\n    intros n m.\n    destruct n; destruct m; try reflexivity.\n    apply Qeq_bool_iff.\n    apply Q.min_comm.\n  Qed.\n\n  Lemma min_id : ∀ n, (min n n == n)%QInf.\n  Proof.\n    intros n.\n    destruct n; try reflexivity.\n    apply Qeq_bool_iff.\n    apply Q.min_id.\n  Qed.\n\n  Lemma min_posinf : ∀ n, (min n +∞ == n)%QInf.\n  Proof.\n    intros n. destruct n; reflexivity.\n  Qed.\n\n  Lemma min_assoc : ∀ m n p, (min m (min n p) == min (min m n) p)%QInf.\n  Proof.\n    intros m n p.\n    destruct m; destruct n; destruct p; try reflexivity.\n    apply Qeq_bool_iff.\n    apply Q.min_assoc.\n  Qed.\n\n  Add Morphism min with\n    signature eq ==> eq ==> eq as min_mor.\n  Proof.\n    intros x y P z w Q.\n    destruct x; destruct y; destruct z; destruct w;\n    inversion P; inversion Q; try reflexivity;\n    unfold eq, eqb in *; simpl;\n    apply Qeq_bool_iff.\n    apply Qeq_bool_iff in Q.\n    assumption.\n    apply Qeq_bool_iff in P.\n    assumption.\n    apply Qeq_bool_iff in Q.\n    apply Qeq_bool_iff in P.\n    rewrite P.\n    rewrite Q.\n    reflexivity.\n  Qed.\n\n  Definition max n m :=\n    match n, m with\n    | +∞, _ => +∞\n    | _, +∞ => +∞\n    | -∞, m => m\n    | n, -∞ => n\n    | Fin n, Fin m => Qmax n m\n    end.\n\n  Lemma max_comm : ∀ n m, (max n m == max m n)%QInf.\n  Proof.\n    intros n m.\n    destruct n; destruct m; try reflexivity.\n    apply Qeq_bool_iff.\n    apply Q.max_comm.\n  Qed.\n\n  Lemma max_id : ∀ n, (max n n == n)%QInf.\n  Proof.\n    intros n.\n    destruct n; try reflexivity.\n    apply Qeq_bool_iff.\n    apply Q.max_id.\n  Qed.\n\n  Lemma max_neginf : ∀ n, (max n -∞ == n)%QInf.\n  Proof.\n    intros n. destruct n; reflexivity.\n  Qed.\n\n  Lemma max_assoc : ∀ m n p, (max m (max n p) == max (max m n) p)%QInf.\n  Proof.\n    intros m n p.\n    destruct m; destruct n; destruct p; try reflexivity.\n    apply Qeq_bool_iff.\n    apply Q.max_assoc.\n  Qed.\n\n  Add Morphism max with\n    signature eq ==> eq ==> eq as max_mor.\n  Proof.\n    intros x y P z w Q.\n    destruct x; destruct y; destruct z; destruct w;\n    inversion P; inversion Q; try reflexivity;\n    unfold eq, eqb in *; simpl;\n    apply Qeq_bool_iff.\n    apply Qeq_bool_iff in Q.\n    assumption.\n    apply Qeq_bool_iff in P.\n    assumption.\n    apply Qeq_bool_iff in Q.\n    apply Qeq_bool_iff in P.\n    rewrite P.\n    rewrite Q.\n    reflexivity.\n  Qed.\n\n  Lemma min_max_absorption : ∀ n m, (max n (min n m) == n)%QInf.\n  Proof.\n    intros n m.\n    destruct n; destruct m; try reflexivity; apply Qeq_bool_iff.\n    - apply Q.max_id.\n    - apply Q.min_max_absorption.\n  Qed.\n\n  Lemma max_min_absorption : ∀ n m, (min n (max n m) == n)%QInf.\n  Proof.\n    intros n m.\n    destruct n; destruct m; try reflexivity; apply Qeq_bool_iff.\n    - apply Q.max_id.\n    - apply Q.max_min_absorption.\n  Qed.\n\n  Global Instance Lattice_QInf : Lattice t := {|\n    meet := min;\n    join := max;\n    top := +∞;\n    bot := -∞;\n\n    meet_commutative := min_comm;\n    meet_idempotent := min_id;\n    meet_associative := min_assoc;\n    meet_id := min_posinf;\n\n    join_commutative := max_comm;\n    join_idempotent := max_id;\n    join_associative := max_assoc;\n    join_id := max_neginf;\n\n    meet_join_absorptive := max_min_absorption;\n    join_meet_absorptive := min_max_absorption;\n\n    meet_respectful := min_mor;\n    join_respectful := max_mor;\n  |}.\n\nEnd QInf.\n\nCoercion QInf.Fin : Q >-> QInf.t.\nNotation \"+∞\" := QInf.PosInf : QInf_scope.\nNotation \"-∞\" := QInf.NegInf : QInf_scope.\nInfix \"==\" := QInf.eq : QInf_scope.\nInfix \"<=\" := QInf.le : QInf_scope.\nInfix \"≤\" := QInf.le : QInf_scope.\nInfix \"+\" := QInf.add : QInf_scope.\nInfix \"-\" := QInf.sub : QInf_scope.\n\n\n", "meta": {"author": "Skyb0rg007", "repo": "Policy-Iteration-Coq", "sha": "687dcdc869f3c51f430d4adeaa9fcc7a8da86115", "save_path": "github-repos/coq/Skyb0rg007-Policy-Iteration-Coq", "path": "github-repos/coq/Skyb0rg007-Policy-Iteration-Coq/Policy-Iteration-Coq-687dcdc869f3c51f430d4adeaa9fcc7a8da86115/theories/QInf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6729787834421732}}
{"text": "(** * Tactics: More Basic Tactics *)\n\n\n(** This chapter introduces several more proof strategies and\n    tactics that allow us to prove more interesting properties of\n    functional programs.  We will see:\n\n    - how to use auxiliary lemmas in both \"forward-style\" and\n      \"backward-style\" proofs;\n    - how to reason about data constructors (in particular, how to use\n      the fact that they are injective and disjoint);\n    - how to create a strong induction hypothesis (and when such\n      strengthening is required); and\n    - more details on how to reason by case analysis. *)\n\nRequire Export Poly.\n\n(* ################################################################# *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    exactly the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n\n(** At this point, we could finish with \"[rewrite -> eq2.\n    reflexivity.]\" as we have done several times before.  We can\n    achieve the same effect in a single step by using the [apply]\n    tactic instead: *)\n\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** You may find it instructive to experiment with this proof\n    and see if there is a way to complete it using just [rewrite]\n    instead of [apply]. *)\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] that binds some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex)  *)\n(** Complete the following proof without using [simpl]. *)\n\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 3 = true ->\n     oddb 4 = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal exactly -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  simpl.\n  (* Here we cannot use [apply] directly *)\nAbort.\n\n(** In this case we can use the [symmetry] tactic, which switches the\n    left and right sides of an equality in the goal. *)\n\nTheorem silly3 : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  symmetry.\n  simpl. (* Actually, this [simpl] is unnecessary, since\n            [apply] will perform simplification first. *)\n  apply H.  Qed.\n\n(** **** Exercise: 3 stars (apply_exercise1)  *)\n(** (_Hint_: You can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [SearchAbout] is\n    your friend.) *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (apply_rewrite)  *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  What are the situations where both can usefully be\n    applied?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(* ################################################################# *)\n(** * The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might like to pull it out\n    as a lemma recording, once and for all, the fact that equality is\n    transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to prove the above\n    example.  However, to do this we need a slight refinement of the\n    [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n\n(** If we simply tell Coq [apply trans_eq] at this point, it can\n    tell (by matching the goal against the conclusion of the lemma)\n    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and\n    [o] with [[e,f]].  However, the matching process doesn't determine\n    an instantiation for [m]: we have to supply one explicitly by\n    adding [with (m:=[c,d])] to the invocation of [apply]. *)\n\n  apply trans_eq with (m:=[c;d]). apply eq1. apply eq2.   Qed.\n\n(** Actually, we usually don't have to include the name [m] in\n    the [with] clause; Coq is often smart enough to figure out which\n    instantiation we're giving. We could instead write: [apply\n    trans_eq with [c;d]]. *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * The [inversion] Tactic *)\n\n(** Recall the definition of natural numbers:\n\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n\n    It is obvious from this definition that every number has one of\n    two forms: either it is the constructor [O] or it is built by\n    applying the constructor [S] to another number.  But there is more\n    here than meets the eye: implicit in the definition (and in our\n    informal understanding of how datatype declarations work in other\n    programming languages) are two more facts:\n\n    - The constructor [S] is _injective_.  That is, if [S n = S m], it\n      must be the case that [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n]. *)\n\n(** Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor\n    is injective and [nil] is different from every non-empty list.\n    For booleans, [true] and [false] are different.  (Since neither\n    [true] nor [false] take any arguments, their injectivity is not an\n    issue.)  And so on. *)\n\n(** Coq provides a tactic called [inversion] that allows us to\n    exploit these principles in proofs. To see how to use it, let's\n    show explicitly that the [S] constructor is injective: *)\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n\n(** By writing [inversion H] at this point, we ask Coq to\n    generate all equations that it can infer from [H] as additional\n    hypotheses, replacing variables in the goal as it goes. In the\n    present example, this amounts to adding a new hypothesis [H1 : n =\n    m] and replacing [n] by [m] in the goal. *)\n\n  inversion H. reflexivity.  Qed.\n\n(** Here's a more interesting example that shows how multiple\n    equations can be derived at once. *)\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity. Qed.\n\n(** It is possible to name the equations that [inversion]\n    generates with an [as ...] clause: *)\n\nTheorem inversion_ex2 : forall (n m : nat),\n  [n] = [m] ->\n  n = m.\nProof.\n  intros n o H. inversion H as [Hno]. reflexivity.  Qed.\n\n(** **** Exercise: 1 star (inversion_ex3)  *)\nExample inversion_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** While the injectivity of constructors allows us to reason\n    that [forall (n m : nat), S n = S m -> n = m], the converse of\n    this implication is an instance of a more general fact about\n    constructors and functions, which we will find useful below: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.\n\n(** When used on a hypothesis involving an equality between\n    _different_ constructors (e.g., [S n = O]), [inversion] solves the\n    goal immediately. To see why this makes sense, consider the\n    following proof: *)\n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  intros n.\n\n(** We can proceed by case analysis on [n]. The first case is\n    trivial. *)\n\n  destruct n as [| n'].\n  - (* n = 0 *)\n    intros H. reflexivity.\n\n(** However, the second one doesn't look so simple: assuming\n    [beq_nat 0 (S n') = true], we must show [S n' = 0], but the latter\n    clearly contradictory!  The way forward lies in the assumption.\n    After simplifying the goal state, we see that [beq_nat 0 (S n') =\n    true] has become [false = true]: *)\n\n  - (* n = S n' *)\n    simpl.\n\n(** If we use [inversion] on this hypothesis, Coq notices that\n    the subgoal we are working on is impossible, and therefore removes\n    it from further consideration. *)\n\n    intros H. inversion H. Qed.\n\n(** This is an instance of a general logical principle known as\n    the _principle of explosion_, which asserts that a contradiction\n    entails anything, even false things.  For instance: *)\n\nTheorem inversion_ex4 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem inversion_ex5 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. inversion contra. Qed.\n\n(** If you find the principle of explosion confusing, remember\n    that these proofs are not actually showing that the conclusion of\n    the statement holds.  Rather, they are arguing that the situation\n    described by the premise can never arise, so the implication is\n    vacuous.  We'll explore the principle of explosion of more detail\n    in the next chapter. *)\n\n(** **** Exercise: 1 star (inversion_ex6)  *)\nExample inversion_ex6 : forall (X : Type)\n                          (x y z : X) (l j : list X),\n  x :: y :: l = [] ->\n  y :: l = z :: j ->\n  x = z.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** To summarize this discussion, suppose [H] is a hypothesis in the\n    context or a previously proven lemma of the form\n\n      c a1 a2 ... an = d b1 b2 ... bm\n\n    for some constructors [c] and [d] and arguments [a1 ... an] and\n    [b1 ... bm].  Then [inversion H] has the following effect:\n\n    - If [c] and [d] are the same constructor, then, by the\n      injectivity of this constructor, we know that [a1 = b1], [a2 =\n      b2], etc.; [inversion H] adds these facts to the context, and\n      tries to use them to rewrite the goal.\n\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory, and the current goal doesn't have to be\n      considered. In this case, [inversion H] marks the current goal\n      as completed and pops it off the goal stack. *)\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, [apply L in H] matches some conditional statement\n    [L] (of the form [L1 -> L2], say) against a hypothesis [H] in the\n    context.  However, unlike ordinary [apply] (which rewrites a goal\n    matching [L2] into a subgoal [L1]), [apply L in H] matches [H]\n    against [L1] and, if successful, replaces it with [L2].\n\n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\": from [L1 -> L2] and a hypothesis matching [L1], it\n    produces a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\": it says that if we know [L1->L2] and we are\n    trying to prove [L2], it suffices to prove [L1].\n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\nTheorem silly3' : forall (n : nat),\n  (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->\n  true = beq_nat n 5  ->\n  true = beq_nat (S (S n)) 7.\nProof.\n  intros n eq H.\n  symmetry in H. apply eq in H. symmetry in H.\n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, idiomatic use of Coq tends to favor backward reasoning,\n    but in some situations the forward style can be easier to think\n    about.  *)\n\n(** **** Exercise: 3 stars, recommended (plus_n_n_injective)  *)\n(** Practice using \"in\" variants in this exercise.  (Hint: use\n    [plus_n_Sm].) *)\n\nTheorem plus_n_n_injective : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Varying the Induction Hypothesis *)\n\n(** Sometimes it is important to control the exact form of the\n    induction hypothesis when carrying out inductive proofs in Coq.\n    In particular, we need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose\n    we want to show that the [double] function is injective -- i.e.,\n    that it always maps different arguments to different results:\n\n    Theorem double_injective: forall n m, \n      double n = double m -> n = m.\n\n    The way we _start_ this proof is a bit delicate: if we begin with\n\n      intros n. induction n.\n\n    all is well.  But if we begin it with\n\n      intros n m. induction n.\n\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  - (* n = O *) simpl. intros eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n  - (* n = S n' *) intros eq. destruct m as [| m'].\n    + (* m = O *) inversion eq.\n    + (* m = S m' *)  apply f_equal.\n\n(** At this point, the induction hypothesis, [IHn'], does not give us\n    [n' = m'] -- there is an extra [S] in the way -- so the goal is\n    not provable. *)\n\n      Abort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context --\n    intuitively, we have told Coq, \"Let's consider some particular [n]\n    and [m]...\" and we now have to prove that, if [double n = double\n    m] for _these particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove, for\n    _all_ [n], that the proposition\n\n      - [P n] = \"if [double n = double m], then [n = m]\"\n\n    holds, by showing\n\n      - [P O]\n\n         (i.e., \"if [double O = double m] then [O = m]\") and\n\n      - [P n -> P (S n)]\n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: it says that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help at all with proving\n    [R]!  (If we tried to prove [R] from [Q], we would start with\n    something like \"Suppose [double (S n) = 10]...\" but then we'd be\n    stuck: knowing that [double (S n)] is [10] tells us nothing about\n    whether [double n] is [10], so [Q] is useless.) *)\n\n(** 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    then trying to prove a relation involving _every_ [n] but just a\n    _single_ [m]. *)\n\n(** The good proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  - (* n = O *) simpl. intros m eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n\n  - (* n = S n' *) simpl.\n\n(** Notice that both the goal and the induction hypothesis are\n    different this time: the goal asks us to prove something more\n    general (i.e., to prove the statement for _every_ [m]), but the IH\n    is correspondingly more flexible, allowing us to choose any [m] we\n    like when we apply the IH. *)\n\n    intros m eq.\n\n(** Now we've chosen a particular [m] and introduced the assumption\n    that [double n = double m].  Since we are doing a case analysis on\n    [n], we also need a case analysis on [m] to keep the two \"in sync.\" *)\n\n    destruct m as [| m'].\n    + (* m = O *) simpl.\n\n(** The 0 case is trivial: *)\n\n      inversion eq.\n\n    + (* m = S m' *)\n      apply f_equal.\n\n(** At this point, since we are in the second branch of the [destruct\n    m], the [m'] mentioned in the context is the predecessor of the\n    [m] we started out talking about.  Since we are also in the [S]\n    branch of the induction, this is perfect: if we instantiate the\n    generic [m] in the IH with the current [m'] (this instantiation is\n    performed automatically by the [apply] in the next step), then\n    [IHn'] gives us exactly what we need to finish the proof. *)\n\n      apply IHn'. inversion eq. reflexivity. Qed.\n\n(** What you should take away from all this is that we need to be\n    careful about using induction to try to prove something too\n    specific: If we're proving a property of [n] and [m] by induction\n    on [n], we may need to leave [m] generic. *)\n\n(** The following exercise requires the same pattern. *)\n\n(** **** Exercise: 2 stars (beq_nat_true)  *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (beq_nat_true_informal)  *)\n(** Give a careful informal proof of [beq_nat_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** The strategy of doing fewer [intros] before an [induction] to\n    obtain a more general IH doesn't always work by itself; sometimes\n    a little _rearrangement_ of quantified variables is needed.\n    Suppose, for example, that we wanted to prove [double_injective]\n    by induction on [m] instead of [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  - (* m = O *) simpl. intros eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *)  apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem here 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 twist 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 quantified\n    variables and then _re-generalize_ one or more of them,\n    selectively taking variables out of the context and putting them\n    back at the beginning of the goal.  The [generalize dependent]\n    tactic does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m.\n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros n eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *) apply f_equal.\n      apply IHm'. inversion eq. reflexivity. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n    _Theorem_: For any nats [n] and [m], if [double n = double m], then\n      [n = m].\n\n    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n      any [n], if [double n = double m] then [n = m].\n\n      - First, suppose [m = 0], and suppose [n] is a number such\n        that [double n = double m].  We must show that [n = 0].\n\n        Since [m = 0], by the definition of [double] we have [double n =\n        0].  There are two cases to consider for [n].  If [n = 0] we are\n        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']\n        for some [n'], we derive a contradiction: by the definition of\n        [double], we can calculate [double n = S (S (double n'))], but\n        this contradicts the assumption that [double n = 0].\n\n      - Second, suppose [m = S m'] and that [n] is again a number such\n        that [double n = double m].  We must show that [n = S m'], with\n        the induction hypothesis that for every number [s], if [double s =\n        double m'] then [s = m'].\n\n        By the fact that [m = S m'] and the definition of [double], we\n        have [double n = S (S (double m'))].  There are two cases to\n        consider for [n].\n\n        If [n = 0], then by definition [double n = 0], a contradiction.\n\n        Thus, we may assume that [n = S n'] for some [n'], and again by\n        the definition of [double] we have [S (S (double n')) =\n        S (S (double m'))], which implies by inversion that [double n' =\n        double m'].  Instantiating the induction hypothesis with [n'] thus\n        allows us to conclude that [n' = m'], and it follows immediately\n        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just\n        what we wanted to show. [] *)\n\n(** Before we close this section and move on to some exercises, let's\n    digress briefly and use [beq_nat_true] to prove a similar property\n    about identifiers that we'll need in later chapters: *) \n\nTheorem beq_id_true : forall x y,\n  beq_id x y = true -> x = y.\nProof.\n  intros [m] [n]. simpl. intros H.\n  assert (H' : m = n). { apply beq_nat_true. apply H. }\n  rewrite H'. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, recommended (gen_dep_practice)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     nth_error l n = None.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (app_length_cons)  *)\n(** Prove this by induction on [l1], without using [app_length]\n    from [Lists]. *)\n\nTheorem app_length_cons : forall (X : Type) (l1 l2 : list X)\n                                  (x : X) (n : nat),\n     length (l1 ++ (x :: l2)) = n ->\n     S (length (l1 ++ l2)) = n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (app_length_twice)  *)\n(** Prove this by induction on [l], without using [app_length] from [Lists]. *)\n\nTheorem app_length_twice : forall (X:Type) (n:nat) (l:list X),\n     length l = n ->\n     length (l ++ l) = n + n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (double_induction)  *)\n(** Prove the following principle of induction over two naturals. *)\n\nTheorem double_induction: forall (P : nat -> nat -> Prop),\n  P 0 0 ->\n  (forall m, P m 0 -> P (S m) 0) ->\n  (forall n, P 0 n -> P 0 (S n)) ->\n  (forall m n, P m n -> P (S m) (S n)) ->\n  forall m n, P m n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Unfolding Definitions *)\n\n(** It sometimes happens that we need to manually unfold a Definition\n    so that we can manipulate its right-hand side.  For example, if we\n    define... *)\n\nDefinition square n := n * n.\n\n(** ... and try to prove a simple fact about [square]... *)\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\n  simpl.\n\n(** ... we get stuck: [simpl] doesn't simplify anything at this point,\n    and since we haven't proved any other facts about [square], there\n    is nothing we can [apply] or [rewrite] with.\n\n    To make progress, we can manually [unfold] the definition of\n    [square]: *)\n\n  unfold square.\n\n(** Now we have plenty to work with: both sides of the equality are\n    expressions involving multiplication, and we have lots of facts\n    about multiplication at our disposal.  In particular, we know that\n    it is commutative and associative, and from these facts it is not\n    hard to finish the proof. *)\n  \n  rewrite mult_assoc.\n  assert (H : n * m * n = n * n * m).\n  { rewrite mult_comm. apply mult_assoc. }\n  rewrite H. rewrite mult_assoc. reflexivity.\nQed.\n\n(** At this point, a deeper discussion of unfolding and simplification\n    is in order.\n\n    You may already have observed that tactics like [simpl],\n    [reflexivity], and [apply] will often unfold the definitions of\n    functions automatically when it 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 finish the proof is to explicitly\n    tell Coq to unfold [bar]. *)\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n\n(** Now it is apparent that we are stuck on the [match] expressions on\n    both sides of the [=], and we can use [destruct] to finish the\n    proof without thinking too hard. *)\n\n  destruct m.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where [destruct] is used to\n    perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (beq_nat n 3).\n    - (* beq_nat n 3 = true *) reflexivity.\n    - (* beq_nat n 3 = false *) destruct (beq_nat n 5).\n      + (* beq_nat n 5 = true *) reflexivity.\n      + (* beq_nat n 5 = false *) reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (beq_nat n 3) then ... else ...].  But either\n    [n] is equal to [3] or it isn't, so we can use [destruct (beq_nat\n    n 3)] to let us reason about the two cases.\n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c]. *)\n\n(** **** Exercise: 3 stars, optional (combine_split)  *)\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** However, [destruct]ing compound expressions requires a bit of\n    care, as such [destruct]s can sometimes erase information we need\n    to complete a proof. *)\n(** For example, suppose we define a function [sillyfun1] like\n    this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** Now suppose that we want to convince Coq of the (rather\n    obvious) fact that [sillyfun1 n] yields [true] only when [n] is\n    odd.  By analogy with the proofs we did with [sillyfun] above, it\n    is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAbort.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution performed by [destruct] is too brutal -- it threw\n    away every occurrence of [beq_nat n 3], but we need to keep some\n    memory of this expression and how it was destructed, because we\n    need to be able to reason that, since [beq_nat n 3 = true] in this\n    branch of the case analysis, it must be that [n = 3], from which\n    it follows that [n] is odd.\n\n    What we would really like is to substitute away all existing\n    occurences of [beq_nat n 3], but at the same time add an equation\n    to the context that records which case we are in.  The [eqn:]\n    qualifier allows us to introduce such an equation, giving it a\n    name that we choose. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got\n     stuck above, except that the context contains an extra\n     equality assumption, which is exactly what we need to\n     make progress. *)\n    - (* e3 = true *) apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    - (* e3 = false *)\n     (* When we come to the second equality test in the body\n        of the function we are reasoning about, we can use\n        [eqn:] again in the same way, allow us to finish the\n        proof. *)\n      destruct (beq_nat n 5) eqn:Heqe5.\n        + (* e5 = true *)\n          apply beq_nat_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + (* e5 = false *) inversion eq.  Qed.\n\n(** **** Exercise: 2 stars (destruct_eqn_practice)  *)\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Review *)\n\n(** We've now seen many of Coq's most fundamental tactics.  We'll\n    introduce a few more in the coming chapters, and later on we'll\n    see some more powerful _automation_ tactics that make Coq help us\n    with low-level details.  But basically we've got what we need to\n    get work done.\n\n    Here are the ones we've seen:\n\n      - [intros]: move hypotheses/variables from goal to context\n\n      - [reflexivity]: finish the proof (when the goal looks like [e =\n        e])\n\n      - [apply]: prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: apply a hypothesis, lemma, or constructor to\n        a hypothesis in the context (forward reasoning)\n\n      - [apply... with...]: explicitly specify values for variables\n        that cannot be determined by pattern matching\n\n      - [simpl]: simplify computations in the goal\n\n      - [simpl in H]: ... or a hypothesis\n\n      - [rewrite]: use an equality hypothesis (or lemma) to rewrite\n        the goal\n\n      - [rewrite ... in H]: ... or a hypothesis\n\n      - [symmetry]: changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]: changes a hypothesis of the form [t=u] into\n        [u=t]\n\n      - [unfold]: replace a defined constant by its right-hand side in\n        the goal\n\n      - [unfold... in H]: ... or a hypothesis\n\n      - [destruct... as...]: case analysis on values of inductively\n        defined types\n\n      - [destruct... eqn:...]: specify the name of an equation to be\n        added to the context, recording the result of the case\n        analysis\n\n      - [induction... as...]: induction on values of inductively\n        defined types\n\n      - [inversion]: reason by injectivity and distinctness of\n        constructors\n\n      - [assert (e) as H]: introduce a \"local lemma\" [e] and call it\n        [H]\n\n      - [generalize dependent x]: move the variable [x] (and anything\n        else that depends on it) from the context back to an explicit\n        hypothesis in the goal formula *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (beq_nat_sym)  *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Proof:\n   (* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine)  *)\n(** We proved, in an exercise above, that for all lists of pairs,\n    [combine] is the inverse of [split].  How would you formalize the\n    statement that [split] is the inverse of [combine]?  When is this\n    property true?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?)  *)\n\nDefinition split_combine_statement : Prop \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *) . Admitted.\n\nTheorem split_combine : split_combine_statement.\nProof.\n(* FILL IN HERE *) Admitted.\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise)  *)\n(** This one is a bit challenging.  Pay attention to the form of your\n    induction hypothesis. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge)  *)\n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n\n      forallb evenb [0;2;4;5] = false\n\n      forallb (beq_nat 5) [] = true\n\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n\n      existsb (beq_nat 5) [0;2;3;6] = false\n\n      existsb (andb true) [true;true;false] = true\n\n      existsb oddb [1;0;0;0;0;3] = true\n\n      existsb evenb [] = false\n\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n\n    Finally, prove a theorem [existsb_existsb'] stating that\n    [existsb'] and [existsb] have the same behavior. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** $Date: 2016-07-14 17:02:35 -0400 (Thu, 14 Jul 2016) $ *)\n\n\n", "meta": {"author": "coqoon", "repo": "Software-Foundations", "sha": "a327b63aa8ff8543ae2cedee7a5960da05bbfaa7", "save_path": "github-repos/coq/coqoon-Software-Foundations", "path": "github-repos/coq/coqoon-Software-Foundations/Software-Foundations-a327b63aa8ff8543ae2cedee7a5960da05bbfaa7/Software Foundations/src/SF/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.9019206712569267, "lm_q1q2_score": 0.6729581814452623}}
{"text": "Require Import Maps.\nRequire Import Imp.\n\nDefinition aequiv (a1 a2 : aexp) : Prop :=\n  forall (st:state),\n    aeval st a1 = aeval st a2.\n\nDefinition bequiv (b1 b2 : bexp) : Prop :=\n  forall (st:state),\n    beval st b1 = beval st b2.\n\nDefinition cequiv (c1 c2 : com) : Prop :=\n  forall (st st' : state),\n    (ceval c1 st st') <-> (ceval c2 st  st').\n\nTheorem aequiv_example:\n  aequiv (AMinus (AId \"X\") (AId \"X\")) (ANum 0).\nunfold aequiv.\nintro st.\nsimpl.\ninduction (st \"X\"%string).\nsimpl. reflexivity.\nsimpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem bequiv_example:\n  bequiv (BEq (AMinus (AId \"X\") (AId \"X\")) (ANum 0)) BTrue.\nunfold bequiv.\nintro st.\nsimpl.\ninduction (st \"X\"%string).\nsimpl. reflexivity.\nsimpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem skip_left: forall c, cequiv (CSeq CSkip c) c.\nintro c.\nunfold cequiv.\nintros src dst.\nsplit.\nintro h.\ninversion h as [ | | com1 com2 srcx tmp dstx youpi yapla com1eq srceq dsteq\n| | | | ].\n", "meta": {"author": "xavierdpt", "repo": "adventures", "sha": "038a17cf71d8f9690ad168b2592b12e61d2e6c32", "save_path": "github-repos/coq/xavierdpt-adventures", "path": "github-repos/coq/xavierdpt-adventures/adventures-038a17cf71d8f9690ad168b2592b12e61d2e6c32/trove/SF/V2/Equiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.7826624840223699, "lm_q1q2_score": 0.6728265776540523}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\nRequire Export BinNums.\nRequire Import BinPos.\n\nLocal Open Scope N_scope.\n\n(**********************************************************************)\n(** * Binary natural numbers, definitions of operations *)\n(**********************************************************************)\n\nModule N.\n\nDefinition t := N.\n\n(** ** Nicer name [N.pos] for contructor [Npos] *)\n\nNotation pos := Npos.\n\n(** ** Constants *)\n\nDefinition zero := 0.\nDefinition one := 1.\nDefinition two := 2.\n\n(** ** Operation [x -> 2*x+1] *)\n\nDefinition succ_double x :=\n  match x with\n  | 0 => 1\n  | pos p => pos p~1\n  end.\n\n(** ** Operation [x -> 2*x] *)\n\nDefinition double n :=\n  match n with\n  | 0 => 0\n  | pos p => pos p~0\n  end.\n\n(** ** Successor *)\n\nDefinition succ n :=\n  match n with\n  | 0 => 1\n  | pos p => pos (Pos.succ p)\n  end.\n\n(** ** Predecessor *)\n\nDefinition pred n :=\n  match n with\n  | 0 => 0\n  | pos p => Pos.pred_N p\n  end.\n\n(** ** The successor of a [N] can be seen as a [positive] *)\n\nDefinition succ_pos (n : N) : positive :=\n match n with\n   | 0 => 1%positive\n   | pos p => Pos.succ p\n end.\n\n(** ** Addition *)\n\nDefinition add n m :=\n  match n, m with\n  | 0, _ => m\n  | _, 0 => n\n  | pos p, pos q => pos (p + q)\n  end.\n\nInfix \"+\" := add : N_scope.\n\n(** Subtraction *)\n\nDefinition sub n m :=\nmatch n, m with\n| 0, _ => 0\n| n, 0 => n\n| pos n', pos m' =>\n  match Pos.sub_mask n' m' with\n  | IsPos p => pos p\n  | _ => 0\n  end\nend.\n\nInfix \"-\" := sub : N_scope.\n\n(** Multiplication *)\n\nDefinition mul n m :=\n  match n, m with\n  | 0, _ => 0\n  | _, 0 => 0\n  | pos p, pos q => pos (p * q)\n  end.\n\nInfix \"*\" := mul : N_scope.\n\n(** Order *)\n\nDefinition compare n m :=\n  match n, m with\n  | 0, 0 => Eq\n  | 0, pos m' => Lt\n  | pos n', 0 => Gt\n  | pos n', pos m' => (n' ?= m')%positive\n  end.\n\nInfix \"?=\" := compare (at level 70, no associativity) : N_scope.\n\n(** Boolean equality and comparison *)\n\nFixpoint eqb n m :=\n  match n, m with\n    | 0, 0 => true\n    | pos p, pos q => Pos.eqb p q\n    | _, _ => false\n  end.\n\nDefinition leb x y :=\n match x ?= y with Gt => false | _ => true end.\n\nDefinition ltb x y :=\n match x ?= y with Lt => true | _ => false end.\n\nInfix \"=?\" := eqb (at level 70, no associativity) : N_scope.\nInfix \"<=?\" := leb (at level 70, no associativity) : N_scope.\nInfix \"<?\" := ltb (at level 70, no associativity) : N_scope.\n\n(** Min and max *)\n\nDefinition min n n' := match n ?= n' with\n | Lt | Eq => n\n | Gt => n'\n end.\n\nDefinition max n n' := match n ?= n' with\n | Lt | Eq => n'\n | Gt => n\n end.\n\n(** Dividing by 2 *)\n\nDefinition div2 n :=\n  match n with\n  | 0 => 0\n  | 1 => 0\n  | pos (p~0) => pos p\n  | pos (p~1) => pos p\n  end.\n\n(** Parity *)\n\nDefinition even n :=\n  match n with\n    | 0 => true\n    | pos (xO _) => true\n    | _ => false\n  end.\n\nDefinition odd n := negb (even n).\n\n(** Power *)\n\nDefinition pow n p :=\n  match p, n with\n    | 0, _ => 1\n    | _, 0 => 0\n    | pos p, pos q => pos (q^p)\n  end.\n\nInfix \"^\" := pow : N_scope.\n\n(** Square *)\n\nDefinition square n :=\n  match n with\n    | 0 => 0\n    | pos p => pos (Pos.square p)\n  end.\n\n(** Base-2 logarithm *)\n\nDefinition log2 n :=\n match n with\n   | 0 => 0\n   | 1 => 0\n   | pos (p~0) => pos (Pos.size p)\n   | pos (p~1) => pos (Pos.size p)\n end.\n\n(** How many digits in a number ?\n    Number 0 is said to have no digits at all.\n*)\n\nDefinition size n :=\n match n with\n  | 0 => 0\n  | pos p => pos (Pos.size p)\n end.\n\nDefinition size_nat n :=\n match n with\n  | 0 => O\n  | pos p => Pos.size_nat p\n end.\n\n(** Euclidean division *)\n\nFixpoint pos_div_eucl (a:positive)(b:N) : N * N :=\n  match a with\n    | xH =>\n       match b with 1 => (1,0) | _ => (0,1) end\n    | xO a' =>\n       let (q, r) := pos_div_eucl a' b in\n       let r' := double r in\n       if b <=? r' then (succ_double q, r' - b)\n        else (double q, r')\n    | xI a' =>\n       let (q, r) := pos_div_eucl a' b in\n       let r' := succ_double r in\n       if b <=? r' then (succ_double q, r' - b)\n        else  (double q, r')\n  end.\n\nDefinition div_eucl (a b:N) : N * N :=\n  match a, b with\n   | 0,  _ => (0, 0)\n   | _, 0  => (0, a)\n   | pos na, _ => pos_div_eucl na b\n  end.\n\nDefinition div a b := fst (div_eucl a b).\nDefinition modulo a b := snd (div_eucl a b).\n\nInfix \"/\" := div : N_scope.\nInfix \"mod\" := modulo (at level 40, no associativity) : N_scope.\n\n(** Greatest common divisor *)\n\nDefinition gcd a b :=\n match a, b with\n  | 0, _ => b\n  | _, 0 => a\n  | pos p, pos q => pos (Pos.gcd p q)\n end.\n\n(** Generalized Gcd, also computing rests of [a] and [b] after\n    division by gcd. *)\n\nDefinition ggcd a b :=\n match a, b with\n  | 0, _ => (b,(0,1))\n  | _, 0 => (a,(1,0))\n  | pos p, pos q =>\n     let '(g,(aa,bb)) := Pos.ggcd p q in\n     (pos g, (pos aa, pos bb))\n end.\n\n(** Square root *)\n\nDefinition sqrtrem n :=\n match n with\n  | 0 => (0, 0)\n  | pos p =>\n    match Pos.sqrtrem p with\n     | (s, IsPos r) => (pos s, pos r)\n     | (s, _) => (pos s, 0)\n    end\n end.\n\nDefinition sqrt n :=\n match n with\n  | 0 => 0\n  | pos p => pos (Pos.sqrt p)\n end.\n\n(** Operation over bits of a [N] number. *)\n\n(** Logical [or] *)\n\nDefinition lor n m :=\n match n, m with\n   | 0, _ => m\n   | _, 0 => n\n   | pos p, pos q => pos (Pos.lor p q)\n end.\n\n(** Logical [and] *)\n\nDefinition land n m :=\n match n, m with\n  | 0, _ => 0\n  | _, 0 => 0\n  | pos p, pos q => Pos.land p q\n end.\n\n(** Logical [diff] *)\n\nFixpoint ldiff n m :=\n match n, m with\n  | 0, _ => 0\n  | _, 0 => n\n  | pos p, pos q => Pos.ldiff p q\n end.\n\n(** [xor] *)\n\nDefinition lxor n m :=\n  match n, m with\n    | 0, _ => m\n    | _, 0 => n\n    | pos p, pos q => Pos.lxor p q\n  end.\n\n(** Shifts *)\n\nDefinition shiftl_nat (a:N) := nat_rect _ a (fun _ => double).\nDefinition shiftr_nat (a:N) := nat_rect _ a (fun _ => div2).\n\nDefinition shiftl a n :=\n  match a with\n    | 0 => 0\n    | pos a => pos (Pos.shiftl a n)\n  end.\n\nDefinition shiftr a n :=\n  match n with\n    | 0 => a\n    | pos p => Pos.iter div2 a p\n  end.\n\n(** Checking whether a particular bit is set or not *)\n\nDefinition testbit_nat (a:N) :=\n  match a with\n    | 0 => fun _ => false\n    | pos p => Pos.testbit_nat p\n  end.\n\n(** Same, but with index in N *)\n\nDefinition testbit a n :=\n  match a with\n    | 0 => false\n    | pos p => Pos.testbit p n\n  end.\n\n(** Translation from [N] to [nat] and back. *)\n\nDefinition to_nat (a:N) :=\n  match a with\n    | 0 => O\n    | pos p => Pos.to_nat p\n  end.\n\nDefinition of_nat (n:nat) :=\n  match n with\n    | O => 0\n    | S n' => pos (Pos.of_succ_nat n')\n  end.\n\n(** Iteration of a function *)\n\nDefinition iter (n:N) {A} (f:A->A) (x:A) : A :=\n  match n with\n    | 0 => x\n    | pos p => Pos.iter f x p\n  end.\n\n(** Conversion with a decimal representation for printing/parsing *)\n\nDefinition of_uint (d:Decimal.uint) := Pos.of_uint d.\n\nDefinition of_int (d:Decimal.int) :=\n  match Decimal.norm d with\n  | Decimal.Pos d => Some (Pos.of_uint d)\n  | Decimal.Neg _ => None\n  end.\n\nDefinition to_uint n :=\n  match n with\n  | 0 => Decimal.zero\n  | pos p => Pos.to_uint p\n  end.\n\nDefinition to_int n := Decimal.Pos (to_uint n).\n\nEnd 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/NArith/BinNatDef.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6728265620400711}}
{"text": "(* week-15_a-commutative-diagram.v *)\n(* YSC3236 2017-2018, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Spelled-out version of Sun 26 Nov 2017 *)\n(* was: *)\n(* Version of Sat 25 Nov 2017 *)\n\n(* ********** *)\n\n(*\n   name: Oishik Ganguly\n   student ID number: A0138306J\n   e-mail address: oishik.ganguly@u.yale-nus.edu.sg\n*)\n\n(* ********** *)\n(*\n\nThe goal of this term project is to prove the following theorem:\n\n  Theorem the_commutative_diagram :\n    forall sp : source_program,\n      interpret sp = run (compile sp).\n\nfor\n\n* a source language of arithmetic expressions:\n\n    Inductive arithmetic_expression : Type :=\n    | Literal : nat -> arithmetic_expression\n    | Plus : arithmetic_expression -> arithmetic_expression -> arithmetic_expression\n    | Minus : arithmetic_expression -> arithmetic_expression -> arithmetic_expression.\n    \n    Inductive source_program : Type :=\n    | Source_program : arithmetic_expression -> source_program.\n\n* a target language of byte-code instructions:\n\n    Inductive byte_code_instruction : Type :=\n    | PUSH : nat -> byte_code_instruction\n    | ADD : byte_code_instruction\n    | SUB : byte_code_instruction.\n    \n    Inductive target_program : Type :=\n    | Target_program : list byte_code_instruction -> target_program.\n\n* a semantics of expressible values:\n\n    Inductive expressible_value : Type :=\n    | Expressible_nat : nat -> expressible_value\n    | Expressible_msg : string -> expressible_value.\n\nThe source for errors is subtraction,\nsince subtracting two natural numbers does not always yield a natural number:\nfor example, 3 - 2 is defined but not 2 - 3.\n\nYou are expected, at the very least:\n\n* to implement a source interpreter\n  and to verify that it satisfies its specification\n\n* to implement a target interpreter (i.e., a virtual machine)\n  and to verify that it satisfies its specification\n\n* to implement a compiler\n  and to verify that it satisfies its specification\n\n* to prove that the diagram commutes, i.e., to show that\n  interpreting any given expression\n  gives the same result as\n  compiling this expression and then running the resulting compiled program\n  (to this end, the injection tactic illustrated in Lemma new_and_useful just below will come handy)\n\nBeyond this absolute minimum, in decreasing importance, it would be good:\n\n* to write an accumulator-based compiler and to prove that it satisfies the specification\n\n* to investigate byte-code verification\n\n* to revisit good old Magritte\n\n* to write a continuation-based interpreter and to prove that it satisfies the specification\n\n* to prove that each of the specifications specifies a unique function\n\n*)\n\n(* ********** *)\n\nLemma new_and_useful :\n  forall i j : nat,\n    Some i = Some j -> i = j.\nProof. \n  intros i j H_Some.\n  injection H_Some as H_i_j.  (* <--[new and useful]-- *)\n  exact H_i_j.\nQed.\n\n(* ********** *)\n\nLtac unfold_tactic name :=\n  intros;\n  unfold name; (* fold name; *)\n  reflexivity.\n  \nRequire Import Arith Bool List String.\n\n(* n2 > n1 ? *)\nFixpoint ltb (n1 n2 : nat) : bool :=\n  match n1 with\n  | O =>\n    match n2 with\n    | O =>\n      false\n    | S n2' =>\n      true\n    end\n  | S n1' =>\n    match n2 with\n    | O =>\n      false\n    | S n2' =>\n      ltb n1' n2'\n    end\n  end.\n\n    \n           \n\n\n\n\n\nNotation \"A =n= B\" := (beq_nat A B) (at level 70, right associativity).\n\n\n\n(* ********** *)\n\n(* Arithmetic expressions: *)\n\nInductive arithmetic_expression : Type :=\n| Literal : nat -> arithmetic_expression\n| Plus : arithmetic_expression -> arithmetic_expression -> arithmetic_expression\n| Minus : arithmetic_expression -> arithmetic_expression -> arithmetic_expression.\n\n(* Source programs: *)\n\nInductive source_program : Type :=\n| Source_program : arithmetic_expression -> source_program.\n\n(* ********** *)\n\n(* Semantics: *)\n\nInductive expressible_value : Type :=\n| Expressible_msg : string -> expressible_value\n| Expressible_nat : nat -> expressible_value.\n\n\n(* ********** *)\n\n(* Task 1: \n   prove that each of the definitions below specifies a unique function,\n   implement these two functions,\n   and verify that each of your functions satisfies its specification.\n *)\n\n(* We first define a notion of equality for expressible values *)\n\nDefinition expressible_val_eq (e1 : expressible_value) (e2 : expressible_value) :=\n  match e1 with\n  | Expressible_nat n1 =>\n    match e2 with\n    | Expressible_nat n2 =>\n      n1 =n= n2\n    | _ =>\n      false\n    end\n  | Expressible_msg _ =>\n    match e2 with\n    | Expressible_msg _ =>\n      true\n    | _ =>\n      false\n    end\n  end.\n\nNotation \"A =e= B\" := (expressible_val_eq A B) (at level 70, right associativity).\n\n\nDefinition specification_of_evaluate (evaluate : arithmetic_expression -> expressible_value) :=\n  (forall n : nat,\n      (* specification for literals *)\n     evaluate (Literal n) = Expressible_nat n)\n  /\\\n  ((forall (ae1 ae2 : arithmetic_expression)\n           (s1 : string),\n       evaluate ae1 = Expressible_msg s1 -> \n       evaluate (Plus ae1 ae2) = Expressible_msg s1)\n   /\\\n   (forall (ae1 ae2 : arithmetic_expression)\n           (n1 : nat)\n           (s2 : string),\n       evaluate ae1 = Expressible_nat n1 ->\n       evaluate ae2 = Expressible_msg s2 ->\n       evaluate (Plus ae1 ae2) = Expressible_msg s2)\n   /\\\n   (forall (ae1 ae2 : arithmetic_expression)\n           (n1 n2 : nat),\n       evaluate ae1 = Expressible_nat n1 ->\n       evaluate ae2 = Expressible_nat n2 ->\n       evaluate (Plus ae1 ae2) = Expressible_nat (n1 + n2)))\n  /\\\n  ((forall (ae1 ae2 : arithmetic_expression)\n           (s1 : string),\n       evaluate ae1 = Expressible_msg s1 ->\n       evaluate (Minus ae1 ae2) = Expressible_msg s1)\n   /\\\n   (forall (ae1 ae2 : arithmetic_expression)\n           (n1 : nat)\n           (s2 : string),\n       evaluate ae1 = Expressible_nat n1 ->\n       evaluate ae2 = Expressible_msg s2 ->\n       evaluate (Minus ae1 ae2) = Expressible_msg s2)\n   /\\\n   (forall (ae1 ae2 : arithmetic_expression)\n           (n1 n2 : nat),\n       evaluate ae1 = Expressible_nat n1 ->\n       evaluate ae2 = Expressible_nat n2 ->\n       ltb n1 n2 = true ->\n       evaluate (Minus ae1 ae2) = Expressible_msg \"numerical underflow\")\n   /\\\n   (forall (ae1 ae2 : arithmetic_expression)\n           (n1 n2 : nat),\n       evaluate ae1 = Expressible_nat n1 ->\n       evaluate ae2 = Expressible_nat n2 ->\n       ltb n1 n2 = false ->\n       evaluate (Minus ae1 ae2) = Expressible_nat (n1 - n2))).\n\n\n(* Proving that specification_of_evaluate is sound *)\nTheorem specification_of_evaluate_is_sound :\n  forall (ev1 ev2 : arithmetic_expression -> expressible_value),\n    specification_of_evaluate ev1 ->\n    specification_of_evaluate ev2 ->\n    forall (ae : arithmetic_expression),\n      ev1 ae = ev2 ae.\nProof.\n  intros ev1 ev2.\n  unfold specification_of_evaluate.\n  intros\n    [ev1_lit [[ev1_add_err_arg1 [ev1_add_err_arg2 ev1_add_eval]]\n                [ev1_sub_err_arg1 [ev1_sub_err_arg2 [ev1_sub_err_ufl ev1_sub_eval]]]]]\n    [ev2_lit [[ev2_add_err_arg1 [ev2_add_err_arg2 ev2_add_eval]]\n                [ev2_sub_err_arg1 [ev2_sub_err_arg2 [ev2_sub_err_ufl ev2_sub_eval]]]]].\n  intro ae.\n  (* our proof will proceed by structural induction over arithmetic expressions *)\n  induction ae as [ n' | e1 IH_e1 e2 IH_e2 | e1 IH_e1 e2 IH_e2].\n\n  (* proof for literals *)\n  rewrite -> (ev1_lit n').\n  rewrite -> (ev2_lit n').\n  reflexivity.\n\n  (* proof for addition expressions *)\n  (* we consider all possible evaluations of the subexpression e1 and e2 *)\n  (* case 1: e1 evaluates to a string *)\n  case (ev2 e1) as [str_val_e1 | nat_val_e1] eqn : e1_eval_case.\n  rewrite -> (ev1_add_err_arg1 e1 e2 str_val_e1 IH_e1).\n  rewrite -> (ev2_add_err_arg1 e1 e2 str_val_e1 e1_eval_case).\n  reflexivity.\n  (* case 2: e1 is a natural value, and e2 evaluates to a string *)\n  case (ev2 e2) as [str_val_e2 | nat_val_e2] eqn : e2_eval_case.\n  rewrite -> (ev1_add_err_arg2 e1 e2 nat_val_e1 str_val_e2 IH_e1 IH_e2).\n  rewrite -> (ev2_add_err_arg2 e1 e2 nat_val_e1 str_val_e2 e1_eval_case e2_eval_case).\n  reflexivity.\n  (* case 3: both e1, e2 evaluate to natural values *)\n  rewrite -> (ev1_add_eval e1 e2 nat_val_e1 nat_val_e2 IH_e1 IH_e2).\n  rewrite -> (ev2_add_eval e1 e2 nat_val_e1 nat_val_e2 e1_eval_case e2_eval_case).\n  reflexivity.\n\n  (* proof for subtraction expressions; once again, consider all possible evaluated\n   * cases of the expression e1 and e2 *)\n  (* case 1: e1 evaluates to a string *)\n  case (ev2 e1) as [str_val_e1 | nat_val_e1] eqn : e1_eval_case.\n  rewrite -> (ev1_sub_err_arg1 e1 e2 str_val_e1 IH_e1).\n  rewrite -> (ev2_sub_err_arg1 e1 e2 str_val_e1 e1_eval_case).\n  reflexivity.\n  (* case 2: e1 is a natural value, and e2 evaluates to a string *)\n  case (ev2 e2) as [str_val_e2 | nat_val_e2] eqn : e2_eval_case.\n  rewrite -> (ev1_sub_err_arg2 e1 e2 nat_val_e1 str_val_e2 IH_e1 IH_e2).\n  rewrite -> (ev2_sub_err_arg2 e1 e2 nat_val_e1 str_val_e2 e1_eval_case e2_eval_case).\n  reflexivity.\n  (* case 3: both e1 and e2 are natural values, but n1 < n2 *)\n  case (ltb nat_val_e1 nat_val_e2) eqn : ltb_bool_val.\n  rewrite -> (ev1_sub_err_ufl e1 e2 nat_val_e1 nat_val_e2 IH_e1 IH_e2 ltb_bool_val).\n  rewrite -> (ev2_sub_err_ufl e1 e2 nat_val_e1 nat_val_e2 e1_eval_case e2_eval_case\n                              ltb_bool_val).\n  reflexivity.\n  (* case 4: both e1 and e2 and natural values, and n1 > n2 *)\n  rewrite -> (ev1_sub_eval e1 e2 nat_val_e1 nat_val_e2 IH_e1 IH_e2).\n  rewrite -> (ev2_sub_eval e1 e2 nat_val_e1 nat_val_e2 e1_eval_case e2_eval_case).\n  reflexivity.\n  exact ltb_bool_val.\n  exact ltb_bool_val.\nQed.\n\n(* Implement unit tests for evaluators *)\nDefinition unit_test_for_evaluate\n           (evaluate : arithmetic_expression -> expressible_value) : bool :=\n  (evaluate\n     (Plus (Literal 2)\n           (Literal 3)) =e= Expressible_nat 5)\n    &&\n    (evaluate\n       (Minus (Literal 7)\n              (Plus (Literal 5)\n                    (Minus (Literal 5) (Literal 4))\n              )\n       ) =e= Expressible_nat 1)\n    &&\n    (evaluate\n       ( Plus (Literal 5)\n              (Plus (Literal 6)\n                    (Minus (Literal 4) (Literal 6))\n              )\n       ) =e= Expressible_msg \"numerical underflow\")\n    &&\n    (evaluate\n        ( Minus (Literal 21)\n                (Plus (Literal 4)\n                      (Minus\n                         (Plus (Literal 14)\n                               (Literal 1)\n                         )\n                         (Literal 10)\n                      )\n                )\n        ) =e= Expressible_nat 12)\n    &&\n    (evaluate\n       (Plus\n          (Plus (Literal 3)\n                (Minus (Literal 6)\n                       (Literal 7)\n                )\n          )\n          (Literal 3)\n       ) =e= Expressible_msg \"numerical underflow\").\n       \n\n(* Naive recursive implementation of evaluate *)\nFixpoint evaluate_v0 (ae : arithmetic_expression) : expressible_value :=\n  match ae with\n  | Literal n =>\n    Expressible_nat n\n  | Plus e1 e2 =>\n    (* evaluate the first expression *)\n    match (evaluate_v0 e1) with\n    | Expressible_msg s =>\n      Expressible_msg s\n    (* If the first expression is a natural value, evaluate the second expression **)\n    | Expressible_nat n1 =>\n      match (evaluate_v0 e2) with\n      | Expressible_msg s =>\n        Expressible_msg s\n      | Expressible_nat n2 =>\n        Expressible_nat (n1 + n2)\n      end\n    end\n  | Minus e1 e2 =>\n    match (evaluate_v0 e1) with\n    | Expressible_msg s =>\n      Expressible_msg s\n    | Expressible_nat n1 =>\n      match (evaluate_v0 e2) with\n      | Expressible_msg s =>\n        Expressible_msg s\n      | Expressible_nat n2 =>\n        (* now check whether n1 < n2 *)\n        if (ltb n1 n2)\n        then Expressible_msg \"numerical underflow\"\n        else Expressible_nat (n1 - n2)\n      end\n    end\n  end.\n\n(* Unit test *)\nCompute (unit_test_for_evaluate (evaluate_v0)).\n\n(* Standard unfold lemmas *)\nLemma unfold_evaluate_v0_literal :\n  forall (n : nat),\n    evaluate_v0 (Literal n) = Expressible_nat n.\nProof.\n  unfold_tactic evaluate_v0.\nQed.    \n\n\nLemma unfold_evaluate_v0_plus : \n  forall (e1 e2 : arithmetic_expression),\n    evaluate_v0 (Plus e1 e2) =\n    (match (evaluate_v0 e1) with\n    | Expressible_msg s =>\n      Expressible_msg s\n    | Expressible_nat n1 =>\n      match (evaluate_v0 e2) with\n      | Expressible_msg s =>\n        Expressible_msg s\n      | Expressible_nat n2 =>\n        Expressible_nat (n1 + n2)\n      end\n    end).\nProof.\n  unfold_tactic evaluate_v0.\nQed.    \n\nLemma unfold_evaluate_v0_minus :\n  forall (e1 e2 : arithmetic_expression),\n    evaluate_v0 (Minus e1 e2) =\n    (match (evaluate_v0 e1) with\n    | Expressible_msg s =>\n      Expressible_msg s\n    | Expressible_nat n1 =>\n      match (evaluate_v0 e2) with\n      | Expressible_msg s =>\n        Expressible_msg s\n      | Expressible_nat n2 =>\n        (* now check whether n1 < n2 *)\n        if (ltb n1 n2)\n        then Expressible_msg \"numerical underflow\"\n        else Expressible_nat (n1 - n2)\n      end\n     end).\nProof.\n  unfold_tactic evaluate_v0.\nQed.\n\n\n    \n(* Proving that evaluate_v0 meets the specification_of_evaluate, thereby proving\n * that specification_of_evaluate is complete *)\nTheorem evaluate_v0_meets_the_specification_of_evaluate :\n  specification_of_evaluate evaluate_v0.\nProof.\n  unfold specification_of_evaluate.\n\n  (* literal *)\n  split.\n  intro n.\n  exact (unfold_evaluate_v0_literal n).\n\n  (* Plus : error on arg 1 *)\n  split.\n  split.\n  intros ae1 ae2 s1 H_about_ae1.\n  (* use any value to instantiate the natural values in the unfold lemma *)\n  rewrite -> (unfold_evaluate_v0_plus ae1 ae2).\n  rewrite -> H_about_ae1.\n  reflexivity.\n  \n  (* Plus : error on arg 2 *)\n  split.\n  intros ae1 ae2 n1 s2 H_about_ae1 H_about_ae2.\n  rewrite -> (unfold_evaluate_v0_plus ae1 ae2).\n  rewrite -> H_about_ae1 ; rewrite -> H_about_ae2.\n  reflexivity.\n\n  (* Plus : both args evaluate to expressible nats *)\n  intros ae1 ae2 n1 n2 H_about_ae1 H_about_ae2.\n  rewrite -> (unfold_evaluate_v0_plus ae1 ae2).\n  rewrite -> H_about_ae1 ; rewrite -> H_about_ae2.\n  reflexivity.\n\n  (* Minus : error on arg 1 *)\n  split.\n  intros ae1 ae2 s1 H_about_ae1.\n  (* use any value to instantiate the natural values in the unfold lemma *)\n  rewrite -> (unfold_evaluate_v0_minus ae1 ae2).\n  rewrite -> H_about_ae1.\n  reflexivity.\n\n  (* Minus : error on arg 2 *)\n  split.\n  intros ae1 ae2 n1 s2 H_about_ae1 H_about_ae2.\n  rewrite -> (unfold_evaluate_v0_minus ae1 ae2).\n  rewrite -> H_about_ae1 ; rewrite -> H_about_ae2.\n  reflexivity.\n\n  (* Minus : both args are expressible nats, but n1 < n2 (underflow *)\n  split.\n  (* note : we name the variables m1 and m2 to avoid clashed with the names in \n   * the unfold lemma. Coq automatically modifies the variable names, but we \n   * would rather be in control *)\n  intros ae1 ae2 m1 m2 H_about_ae1 H_about_ae2 H_about_n1_and_n2.\n  rewrite -> (unfold_evaluate_v0_minus ae1 ae2).\n  rewrite -> H_about_ae1 ; rewrite -> H_about_ae2;\n    rewrite -> H_about_n1_and_n2.\n  reflexivity.\n\n  (* Minus : both args are expressible nats, and there is no underflow *)\n  intros ae1 ae2 n1 n2 H_about_ae1 H_about_ae2 H_about_n1_and_n2.\n  rewrite -> (unfold_evaluate_v0_minus ae1 ae2).\n  rewrite -> H_about_ae1 ; rewrite -> H_about_ae2 ;\n    rewrite -> H_about_n1_and_n2.\n  reflexivity.\nQed.\n\n\n(* We have thus shown that the specification_of_evaluate is sound and complete, and\n * also defined a function that evaluates a given arithmetic_expression *)\n\nDefinition specification_of_interpret (interpret : source_program -> expressible_value) :=\n  forall evaluate : arithmetic_expression -> expressible_value,\n    specification_of_evaluate evaluate ->\n    forall ae : arithmetic_expression,\n      interpret (Source_program ae) = evaluate ae.\n\n(* Theorem to prove soundness of the specification_of_interpret *)\nTheorem specification_of_interpret_is_sound :\n  forall (i1 i2 : source_program -> expressible_value),\n    specification_of_interpret i1 ->\n    specification_of_interpret i2 ->\n    forall (ae : arithmetic_expression),\n      i1 (Source_program ae) = i2 (Source_program ae).\nProof.\n  intros i1 i2.\n  unfold specification_of_interpret.\n  intros H1 H2 ae.\n  (* since evaluate_v0 is a function of type of arithmetic_expression ->\n   * expressible_value, and it meets the specification_of_evaluate, \n   * we may use it to instantiate the evaluate variable in the hypotheses *)\n  rewrite -> (H1 evaluate_v0 evaluate_v0_meets_the_specification_of_evaluate ae).\n  rewrite -> (H2 evaluate_v0 evaluate_v0_meets_the_specification_of_evaluate ae).\n  reflexivity.\nQed.\n\n(* implementation of interpret *)\nDefinition interpret_v0 (sp : source_program ) : expressible_value :=\n  match sp with\n  | Source_program ae =>\n    evaluate_v0 ae\n  end.\n\n(* interpret_v0 meets the specification of interpret *)\nTheorem interpret_v0_meets_the_specification_of_interpret :\n  specification_of_interpret interpret_v0.\nProof.\n  unfold specification_of_interpret.\n  intros evaluate_var H_about_evaluate_var.\n  intro ae.\n  unfold interpret_v0.\n  rewrite ->\n          (specification_of_evaluate_is_sound\n          evaluate_var\n          evaluate_v0\n          H_about_evaluate_var\n          evaluate_v0_meets_the_specification_of_evaluate\n          ae).\n  reflexivity.\nQed.\n\n(* ********** *)\n\n(* Task 2 (if there is time):\n   Define an interpreter with a function in continuation-passing style\n   that satisfies the specification above,\n   and that only apply the current continuation to the result of evaluating\n   an expression if evaluating this expression did not yield an error.\n*)\n\n(* ********** *)\n\n(* Byte-code instructions: *)\n\nInductive byte_code_instruction : Type :=\n| PUSH : nat -> byte_code_instruction\n| ADD : byte_code_instruction\n| SUB : byte_code_instruction.\n\n(* Target programs: *)\n\nInductive target_program : Type :=\n| Target_program : list byte_code_instruction -> target_program.\n\n(* Data stack: *)\n\nDefinition data_stack := list nat.\n\n(* ********** *)\n\nInductive result_of_decoding_and_execution : Type :=\n| OK : data_stack -> result_of_decoding_and_execution\n| KO : string -> result_of_decoding_and_execution.\n\nDefinition specification_of_decode_execute (decode_execute : byte_code_instruction -> data_stack -> result_of_decoding_and_execution) :=\n  (* pushing natural value onto the data stack (or the operation stack) *)\n  (forall (n : nat)\n          (ds : data_stack),\n     decode_execute (PUSH n) ds = OK (n :: ds))\n  /\\\n  (* pushing an ADD instruction onto the stack; only if the stack has at least two \n   * natural values can the addition be performed *)\n  ((decode_execute ADD nil = KO \"ADD: stack underflow\")\n   /\\\n   (forall (n2 : nat),\n       decode_execute ADD (n2 :: nil) = KO \"ADD: stack underflow\")\n   /\\\n   (forall (n1 n2 : nat)\n           (ds : data_stack),\n       decode_execute ADD (n2 :: n1 :: ds) = OK ((n1 + n2) :: ds)))\n  /\\\n  (* likewise for the SUB instruction *)\n  ((decode_execute SUB nil = KO \"SUB: stack underflow\")\n   /\\\n   (forall (n2 : nat),\n       decode_execute SUB (n2 :: nil) = KO \"SUB: stack underflow\")\n   /\\\n   (forall (n1 n2 : nat)\n           (ds : data_stack),\n       ltb n1 n2 = true ->\n       decode_execute SUB (n2 :: n1 :: ds) = KO \"numerical underflow\")\n   /\\\n   (forall (n1 n2 : nat)\n           (ds : data_stack),\n       ltb n1 n2 = false ->\n       decode_execute SUB (n2 :: n1 :: ds) = OK ((n1 - n2) :: ds))).\n\n(* Task 3:\n   prove that the definition above specifies a unique function,\n   implement this function,\n   and verify that your function satisfies the specification.\n *)\n\n(* proving that specification_of_decode_execute is sound *)\nTheorem specification_of_decode_execute_is_sound :\n  forall (de1 de2 : byte_code_instruction -> data_stack ->\n                    result_of_decoding_and_execution),\n    specification_of_decode_execute de1 ->\n    specification_of_decode_execute de2 ->\n    forall (bcis : byte_code_instruction) (ds :data_stack),\n      de1 bcis ds = de2 bcis ds.\nProof.\n  intros de1 de2.\n  unfold specification_of_decode_execute.\n  intros [de1_push [[de1_add_err1 [de1_add_err2 de1_add_eval]]\n                      [de1_sub_err1 [de1_sub_err2 [de1_sub_err_ufl de1_sub_eval]]]]]\n         [de2_push [[de2_add_err1 [de2_add_err2 de2_add_eval]]\n                      [de2_sub_err1 [de2_sub_err2 [de2_sub_err_ufl de2_sub_eval]]]]].\n  intros bcis ds.\n\n  (* we now consider all possible bcis on a case by case basis *)\n  case bcis as [ n'| | ].\n\n  (* PUSH *)\n  rewrite -> (de1_push n' ds); rewrite -> (de2_push n' ds); reflexivity.\n\n  (* ADD *)\n  (* now consider different cases of ds *)\n  case ds as [ | n' ds'].\n  \n  (* case 1: ds is NIL, stack underflow *)\n  rewrite -> de1_add_err1 ; rewrite -> de2_add_err1; reflexivity.\n\n  (* case 2: ds is of the form n'::ds' ; we now consider two case for ds'; \n   * when ds' is NIL, we still have a stack underflow *)\n  case ds' as [ |n'' ds''].\n  rewrite -> (de1_add_err2 n'); rewrite -> (de2_add_err2 n'); reflexivity.\n\n  (* case 3 : ds is of the form n' :: (n'' :: ds'') *)\n  rewrite -> (de1_add_eval n'' n' ds''); rewrite -> (de2_add_eval n'' n' ds'');\n    reflexivity.\n\n  (* SUB *)\n  (* now consider different cases of ds *)\n  case ds as [ | n' ds'].\n  \n  (* case 1: ds is NIL, stack underflow *)\n  rewrite -> de1_sub_err1 ; rewrite -> de2_sub_err1; reflexivity.\n\n  (* case 2: ds is of the form n'::ds' ; we now consider two case for ds'; \n   * when ds' is NIL, we still have a stack underflow *)\n  case ds' as [ |n'' ds''].\n  rewrite -> (de1_sub_err2 n'); rewrite -> (de2_sub_err2 n'); reflexivity.\n\n  (* case 3: ds is of the form n'::n''::ds'' ; now we consider cases of numerical\n   * underflow *)\n  case (ltb n'' n') as [ | ] eqn : val_of_ltb_n''_n'.\n  rewrite -> (de1_sub_err_ufl n'' n' ds'' val_of_ltb_n''_n');\n    rewrite -> (de2_sub_err_ufl n'' n' ds'' val_of_ltb_n''_n');\n    reflexivity.\n\n  (* case 4: no numerical underflow *)\n  rewrite -> (de1_sub_eval n'' n' ds'' val_of_ltb_n''_n');\n    rewrite -> (de2_sub_eval n'' n' ds'' val_of_ltb_n''_n');\n    reflexivity.\nQed.\n  \n\n\nDefinition decode_execute (bcis : byte_code_instruction) (ds : data_stack) : result_of_decoding_and_execution :=\n  match bcis with\n  | PUSH n =>\n  OK (n::ds) \n  | ADD =>\n    match ds with\n    | nil =>\n      KO \"ADD: stack underflow\"\n    | n':: nil =>\n      KO \"ADD: stack underflow\"\n    | n2 :: n1 :: ds'' =>\n      OK ( (n1 + n2) :: ds'' )\n    end\n  |SUB =>\n    match ds with\n    | nil =>\n      KO \"SUB: stack underflow\"\n    | n':: nil =>\n      KO \"SUB: stack underflow\"\n    | n2 :: n1 :: ds'' =>\n      if (ltb n1 n2)\n      then KO \"numerical underflow\"\n      else OK ( (n1 - n2) :: ds'' )\n    end\n  end.\n\n(* the implementtation of decode_execute satisfies the specification 8*)\nTheorem decode_execute_satisfies_the_specification_of_decode_execute :\n  specification_of_decode_execute decode_execute.\nProof.\n  unfold specification_of_decode_execute.\n\n  (* PUSH *)\n  split.\n  intros n ds.\n  unfold decode_execute.\n  reflexivity.\n\n  (* ADD *)\n  split.\n  split.\n  unfold decode_execute.\n  reflexivity.\n\n  split.\n  intro n2.\n  unfold decode_execute.\n  reflexivity.\n\n  intros n1 n2 ds.\n  unfold decode_execute.\n  reflexivity.\n\n  (* SUB *)\n  split.\n  unfold decode_execute.\n  reflexivity.\n\n  split.\n  intro n2.\n  unfold decode_execute.\n  reflexivity.\n\n  (* killing two birds with one do *)\n  do 2 (split;\n  intros n1 n2 ds H_about_n1_and_n2;\n  unfold decode_execute;\n  rewrite -> H_about_n1_and_n2;\n  reflexivity).\nQed.\n\n\n(* ********** *)\n\n(* Specification of the virtual machine: *)\n\nDefinition specification_of_fetch_decode_execute_loop (fetch_decode_execute_loop : list byte_code_instruction -> data_stack -> result_of_decoding_and_execution) :=\n  forall decode_execute : byte_code_instruction -> data_stack -> result_of_decoding_and_execution,\n    specification_of_decode_execute decode_execute ->\n    (forall ds : data_stack,\n        fetch_decode_execute_loop nil ds = OK ds)\n    /\\\n    (forall (bci : byte_code_instruction)\n            (bcis' : list byte_code_instruction)\n            (ds ds' : data_stack),\n        decode_execute bci ds = OK ds' ->\n        fetch_decode_execute_loop (bci :: bcis') ds =\n        fetch_decode_execute_loop bcis' ds')\n    /\\\n    (forall (bci : byte_code_instruction)\n            (bcis' : list byte_code_instruction)\n            (ds : data_stack)\n            (s : string),\n        decode_execute bci ds = KO s ->\n        fetch_decode_execute_loop (bci :: bcis') ds =\n        KO s).\n\n(* Task 4:\n   prove that the definition above specifies a unique function,\n   implement this function,\n   and verify that your function satisfies the specification.\n *)\n\n(* specification_of_fetch_decode_execute_loop is sound *)\nTheorem specification_of_fetch_decode_execute_loop_is_sound :\n  forall (fdel1 fdel2 : list byte_code_instruction -> data_stack ->\n                        result_of_decoding_and_execution),\n    specification_of_fetch_decode_execute_loop fdel1 ->\n    specification_of_fetch_decode_execute_loop fdel2 ->\n    forall (bcis : list byte_code_instruction)\n           (ds : data_stack),\n      fdel1 bcis ds = fdel2 bcis ds.\nProof.\n  intros fdel1 fdel2.\n  unfold specification_of_fetch_decode_execute_loop.\n  (* to obtain the hypotheses for the conjunctive branches of the specificaiton,\n   * we must use destruct *)\n  intros H1 H2.\n  destruct  (H1 decode_execute\n            decode_execute_satisfies_the_specification_of_decode_execute) as\n      [fdel1_completion [fdel1_execution fdel1_error]].\n  destruct  (H2 decode_execute\n                decode_execute_satisfies_the_specification_of_decode_execute) as\n      [fdel2_completion [fdel2_execution fdel2_error]].\n  (* don't introduce ds, we will use this parameterize our induction proof *)\n  intros bcis.\n  (* induct over the list of byte code instructions *)\n  induction bcis as [ | i' i's IH_i'].\n  \n  (* case 1: the bci list is empty *)\n  intro ds.\n  rewrite -> (fdel1_completion ds).\n  rewrite -> (fdel2_completion ds).\n  reflexivity.\n\n  (* case 2: the bci list is of the form bci'::bcis';  we must now consider \n   * the evaluation of the bci at the head of the list ; first condier the\n   * situation where it evaluates to OK (ds) *)\n  intro ds.\n  case (decode_execute i' ds) as [new_ds | error_string]\n                                   eqn : decode_execute_value_for_i'.\n  rewrite -> (fdel1_execution i' i's ds new_ds decode_execute_value_for_i').\n  rewrite -> (fdel2_execution i' i's ds new_ds decode_execute_value_for_i').\n  rewrite -> (IH_i' new_ds).\n  reflexivity.\n\n  (* case 3: the bci' evaluates to KO (s) *)\n  rewrite -> (fdel1_error i' i's ds error_string decode_execute_value_for_i').\n  rewrite -> (fdel2_error i' i's ds error_string decode_execute_value_for_i').\n  reflexivity.\nQed.\n\n\n(* implementation of the specification_of_fetch_decode_execute_loop *)\nFixpoint fetch_decode_execute_loop\n         (insts : list byte_code_instruction)\n         (ds : data_stack) : result_of_decoding_and_execution :=\n  match insts with\n  | nil =>\n    OK ds\n  | inst :: inst' =>\n    match (decode_execute inst ds) with\n    | OK new_ds =>\n      fetch_decode_execute_loop inst' new_ds\n    | KO s =>\n      KO s\n    end\n  end.\n\n(* Standard unfold lemmas *)\nLemma unfold_fetch_decode_execute_loop_nil :\n  forall (ds : data_stack),\n    fetch_decode_execute_loop nil ds = OK ds.\nProof.\n  unfold_tactic fetch_decode_execute_loop.\nQed.\n\nLemma unfold_fetch_decode_execute_loop_bcis : \n  forall (inst : byte_code_instruction)\n         (inst' : list byte_code_instruction)\n         (ds : data_stack),\n    fetch_decode_execute_loop (inst :: inst') ds =\n    match (decode_execute inst ds) with\n    | OK new_ds =>\n      fetch_decode_execute_loop inst' new_ds\n    | KO s =>\n      KO s\n     end.\nProof.\n  unfold_tactic fetch_decode_execute_loop.\nQed.\n\n(* Now we prove that the implementation of fetch_decode_execute_loop satifies the \n * specification *)\nTheorem fetch_decode_execute_loop_satisfies_the_specification :\n  specification_of_fetch_decode_execute_loop fetch_decode_execute_loop.\nProof.\n  unfold specification_of_fetch_decode_execute_loop.\n  intros decode_execute_var H_about_decode_execute_var.\n  \n  (* nil case *)\n  split.\n  intro ds.\n  exact (unfold_fetch_decode_execute_loop_nil ds).\n\n  (* cons case with continued execution *)\n  split.\n  intros bci bcis' ds ds' H_about_decode_execute_bci.\n  rewrite -> (unfold_fetch_decode_execute_loop_bcis\n                bci bcis' ds).\n  (* use the soundness of the specification_of_decode_execute to replace \n   * decode_execute_var with decode_execute *)\n  rewrite ->\n          (specification_of_decode_execute_is_sound\n             decode_execute_var\n             decode_execute\n             H_about_decode_execute_var\n             decode_execute_satisfies_the_specification_of_decode_execute\n             bci ds) in H_about_decode_execute_bci.\n  rewrite -> H_about_decode_execute_bci.\n  reflexivity.\n\n  (* cons case with error *)\n  intros bci bcis' ds s H_about_decode_execute_bci.\n  rewrite ->\n          (specification_of_decode_execute_is_sound\n             decode_execute_var\n             decode_execute\n             H_about_decode_execute_var\n             decode_execute_satisfies_the_specification_of_decode_execute\n             bci ds) in H_about_decode_execute_bci.\n  (* note: we will not be needing the new_ds variable; thus we may pass any \n   * value of the type list nat. *)\n  rewrite -> (unfold_fetch_decode_execute_loop_bcis\n                bci bcis' ds).\n  rewrite -> H_about_decode_execute_bci.\nreflexivity.  \nQed.\n\n(* ********** *)\n\nLemma unfold_append_nil :\n  forall bcis2 : list byte_code_instruction,\n    nil ++ bcis2 = bcis2.\nProof.\n  unfold_tactic List.app.\nQed.\n\nLemma unfold_append_cons :\n  forall (bci1 : byte_code_instruction)\n         (bci1s bci2s : list byte_code_instruction),\n    (bci1 :: bci1s) ++ bci2s =\n    bci1 :: (bci1s ++ bci2s).\nProof.\n  unfold_tactic List.app.\nQed.\n\n(* Task 5:\n   Prove that for any lists of byte-code instructions bcis1 and bcis2,\n   and for any data stack ds,\n   executing the concatenation of bcis1 and bcis2 (i.e., bcis1 ++ bcis2) with ds\n   gives the same result as\n   (1) executing bcis1 with ds, and then\n   (2) executing bcis2 with the resulting data stack, if there exists one.\n*)\n\n\nTheorem relation_between_execution_of_two_bcis_and_their_appended_version :\n  forall (bci1s bci2s : list byte_code_instruction),\n    (forall (ds : data_stack)\n            (ds_new : data_stack),\n        fetch_decode_execute_loop bci1s ds = OK ds_new ->\n        fetch_decode_execute_loop (bci1s ++ bci2s) ds =\n        fetch_decode_execute_loop (bci2s) ds_new) /\\\n    (forall (ds : data_stack) (s : string),\n        fetch_decode_execute_loop bci1s ds = KO s ->\n        fetch_decode_execute_loop (bci1s ++ bci2s) ds = KO s).\nProof.\n  intros bci1s bci2s.\n\n  (* consider the first conjunctive clause *)\n  split.\n  induction bci1s as [ | i' is' IH_is'].\n\n  (* base case *)\n  intros ds ds_new H_when_bcis_is_nil.\n  rewrite -> unfold_append_nil.\n  rewrite -> (unfold_fetch_decode_execute_loop_nil) in H_when_bcis_is_nil.\n  injection H_when_bcis_is_nil as H_about_ds_and_ds_new.\n  rewrite -> H_about_ds_and_ds_new.\n  reflexivity.\n\n  (* inductive case *)\n  intros ds ds_new H_when_bcis_is_cons.\n  rewrite -> unfold_append_cons.\n  case (decode_execute i' ds) as [ ds_after_de_i' | s] eqn : value_of_de_i'.\n  (* rewrite the goal for when (decode_execute i') = OK _ *)\n  rewrite -> (unfold_fetch_decode_execute_loop_bcis i' (is' ++ bci2s) ds).\n  rewrite -> value_of_de_i'.\n  (* rewrite H_when_bcis_is_cons *)\n  rewrite -> (unfold_fetch_decode_execute_loop_bcis i' is' ds) in H_when_bcis_is_cons.\n  rewrite -> value_of_de_i' in H_when_bcis_is_cons.\n  Check (IH_is' ds_after_de_i' ds_new).\n  apply (IH_is' ds_after_de_i' ds_new) in H_when_bcis_is_cons.\n  rewrite -> H_when_bcis_is_cons.\n  reflexivity.\n\n  (* now consider the case where (decode_execute i') = KO _; clearly this gives\n   * rise to an absurd situation, so we use the discriminate tactic *)\n  rewrite ->  (unfold_fetch_decode_execute_loop_bcis i' is' ds) \n                                                    in H_when_bcis_is_cons.\n  rewrite -> value_of_de_i' in H_when_bcis_is_cons.\n  discriminate.\n\n  (* consider the second conjunctive clause *)\n  induction bci1s as [ | i' is'  IH_is'].\n  intros ds s H_about_bcis_nil.\n\n  (* base case *)\n  rewrite -> unfold_fetch_decode_execute_loop_nil in H_about_bcis_nil.\n  discriminate.\n\n  (* inductive case *)\n  intros ds s H_about_bcis_cons.\n  rewrite -> unfold_append_cons.\n  (* once again, consider the cases of decode_execute i' *)\n  case (decode_execute i' ds) as [ds_returned | error_msg] eqn : value_of_de_i'.\n\n  (* case 1: decode_execute i' = OK _ *)\n  (* modify H_about_bcis_cons *)\n  rewrite -> (unfold_fetch_decode_execute_loop_bcis i' is' ds)\n                                                    in H_about_bcis_cons.\n  rewrite -> value_of_de_i' in H_about_bcis_cons.\n  apply (IH_is' ds_returned s) in H_about_bcis_cons.\n  rewrite <- H_about_bcis_cons.\n  (* modify the goal *)\n  rewrite ->\n          (unfold_fetch_decode_execute_loop_bcis i' (is' ++ bci2s) ds).\n  rewrite -> value_of_de_i'.\n  reflexivity.\n\n  (* case 2: decode_execute i' = KO _ *)\n  (* modify H_about_bcis_cons *)\n  rewrite -> (unfold_fetch_decode_execute_loop_bcis i' is' ds)\n    in H_about_bcis_cons.\n  rewrite -> value_of_de_i' in H_about_bcis_cons.\n  (* modify the goal *)\n  rewrite -> (unfold_fetch_decode_execute_loop_bcis i' (is' ++ bci2s) ds).\n  rewrite -> value_of_de_i'.\n  exact H_about_bcis_cons.\n  (* note : since the loop stops executing the remaining instructions in bci1s as soon\n   * as an error message is encountered, we did not need the induction hypothesis *)\nQed.  \n\n\n(* ********** *)\n\nDefinition specification_of_run (run : target_program -> expressible_value) :=\n  forall fetch_decode_execute_loop : list byte_code_instruction -> data_stack -> result_of_decoding_and_execution,\n    specification_of_fetch_decode_execute_loop fetch_decode_execute_loop ->\n    (forall (bcis : list byte_code_instruction),\n       fetch_decode_execute_loop bcis nil = OK nil ->\n       run (Target_program bcis) = Expressible_msg \"no result on the data stack\")\n    /\\\n    (forall (bcis : list byte_code_instruction)\n            (n : nat),\n       fetch_decode_execute_loop bcis nil = OK (n :: nil) ->\n       run (Target_program bcis) = Expressible_nat n)\n    /\\\n    (forall (bcis : list byte_code_instruction)\n            (n n' : nat)\n            (ds'' : data_stack),\n       fetch_decode_execute_loop bcis nil = OK (n :: n' :: ds'') ->\n       run (Target_program bcis) = Expressible_msg \"too many results on the data stack\")\n    /\\\n    (forall (bcis : list byte_code_instruction)\n            (s : string),\n       fetch_decode_execute_loop bcis nil = KO s ->\n       run (Target_program bcis) = Expressible_msg s).\n\n(* Task 6:\n   prove that the definition above specifies a unique function,\n   implement this function,\n   and verify that your function satisfies the specification.\n *)\n\n(* the specification_of_run is sound *)\nTheorem specification_of_run_is_sound :\n  forall (run1 run2 : target_program -> expressible_value),\n    specification_of_run run1 ->\n    specification_of_run run2 ->\n    forall (bcis : list byte_code_instruction),\n      run1 (Target_program bcis) = run2 (Target_program bcis).\nProof.\n  intros run1 run2.\n  unfold specification_of_run.\n  intros H1 H2.\n  destruct (H1 fetch_decode_execute_loop\n               fetch_decode_execute_loop_satisfies_the_specification)\n    as [ run1_no_result [run1_one_result [run1_too_many_results\n                                             run1_error_message ]]].\n  destruct (H2 fetch_decode_execute_loop\n               fetch_decode_execute_loop_satisfies_the_specification)\n    as [ run2_no_result [run2_one_result [run2_too_many_results\n                                             run2_error_message ]]].\n  intro bcis.\n  (* now consider the multiple cases of applying the fetch_decode_execute_loop to\n   * bcis and nil *)\n  case (fetch_decode_execute_loop bcis nil) as [ return_ds | runtime_error_msg]\n                                                 eqn : value_of_bcis_execution.\n  (* for the case where a data stack is returned, consider the 3 cases of no results,\n   * one result, and too many results *)\n  case return_ds as [ | d1 [ | d2 ds']] eqn : value_of_return_ds.\n  \n  (* case 1: no result on stack *)\n  rewrite -> (run1_no_result bcis value_of_bcis_execution);\n    rewrite -> (run2_no_result bcis value_of_bcis_execution);\n    reflexivity.\n\n  (* case 2: one result on stack *)\n  rewrite -> (run1_one_result bcis d1 value_of_bcis_execution);\n    rewrite -> (run2_one_result bcis d1 value_of_bcis_execution);\n    reflexivity.\n\n  (* case 3 : too many results on stack *)\n  rewrite -> (run1_too_many_results bcis d1 d2 ds' value_of_bcis_execution);\n    rewrite -> (run2_too_many_results bcis d1 d2 ds' value_of_bcis_execution);\n    reflexivity.\n\n  (* case 4 : run time error *)\n  rewrite -> (run1_error_message bcis runtime_error_msg value_of_bcis_execution);\n  rewrite -> (run2_error_message bcis runtime_error_msg value_of_bcis_execution);\n  reflexivity.\nQed.\n\n(* Implementation of the specification_of_run *)\n\nDefinition run (prog : target_program) : expressible_value :=\n  match prog with\n  |Target_program bcis =>\n   match (fetch_decode_execute_loop bcis nil) with\n   | OK nil =>\n     Expressible_msg \"no result on the data stack\"\n   | OK (n :: nil) =>\n     Expressible_nat n\n   | OK (n :: n' :: ds) =>\n     Expressible_msg \"too many results on the data stack\"\n   | KO error_msg =>\n     Expressible_msg error_msg\n   end\n  end.\n\n\n(* proof that this implementation satisfies the given specification *)\nTheorem run_satisfies_the_specification_of_run :\n  specification_of_run run.\nProof.\n  unfold specification_of_run.\n  intros fetch_decode_execute_loop_var H_about_fetch_decode_execute_loop_var.\n  \n  split.\n  intros bcis H_about_evaluation_of_bcis.\n  (* we would like to replace fetch_decode_execute_loop_var with\n   * fetch_decode_execute_loop, since run uses this function *)\n  rewrite ->\n          (specification_of_fetch_decode_execute_loop_is_sound\n          fetch_decode_execute_loop_var\n          fetch_decode_execute_loop\n          H_about_fetch_decode_execute_loop_var\n          fetch_decode_execute_loop_satisfies_the_specification\n          bcis nil) in H_about_evaluation_of_bcis.\n  unfold run.\n  rewrite -> H_about_evaluation_of_bcis.\n  reflexivity.\n\n  (* the proofs for the remaining three cases is similar to the case above ; \n   * the only different is in the values that require to be introed *)\n  split.\n  intros bcis n H_about_evaluation_of_bcis.\n  rewrite ->\n          (specification_of_fetch_decode_execute_loop_is_sound\n          fetch_decode_execute_loop_var\n          fetch_decode_execute_loop\n          H_about_fetch_decode_execute_loop_var\n          fetch_decode_execute_loop_satisfies_the_specification\n          bcis nil) in H_about_evaluation_of_bcis.\n  unfold run.\n  rewrite -> H_about_evaluation_of_bcis.\n  reflexivity.\n\n  split.\n  intros bcis n n' ds'' H_about_evaluation_of_bcis.\n  rewrite ->\n          (specification_of_fetch_decode_execute_loop_is_sound\n          fetch_decode_execute_loop_var\n          fetch_decode_execute_loop\n          H_about_fetch_decode_execute_loop_var\n          fetch_decode_execute_loop_satisfies_the_specification\n          bcis nil) in H_about_evaluation_of_bcis.\n  unfold run.\n  rewrite -> H_about_evaluation_of_bcis.\n  reflexivity.\n\n  intros bcis s H_about_evaluation_of_bcis.\n  unfold run.\n  rewrite ->\n          (specification_of_fetch_decode_execute_loop_is_sound\n          fetch_decode_execute_loop_var\n          fetch_decode_execute_loop\n          H_about_fetch_decode_execute_loop_var\n          fetch_decode_execute_loop_satisfies_the_specification\n          bcis nil) in H_about_evaluation_of_bcis.\n  rewrite -> H_about_evaluation_of_bcis.\n  reflexivity.\nQed.\n\n(* ********** *)\n\nDefinition specification_of_compile_aux (compile_aux : arithmetic_expression -> list byte_code_instruction) :=\n  (forall n : nat,\n     compile_aux (Literal n) = PUSH n :: nil)\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     compile_aux (Plus ae1 ae2) = (compile_aux ae1) ++ (compile_aux ae2) ++ (ADD :: nil))\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     compile_aux (Minus ae1 ae2) = (compile_aux ae1) ++ (compile_aux ae2) ++ (SUB :: nil)).\n\n(* Task 6:\n   prove that the definition above specifies a unique function,\n   implement this function using list concatenation, i.e., ++,\n   and verify that your function satisfies the specification.\n *)\n\n(* the specification_of_compile_aux is sound *)\nTheorem specification_of_compile_aux_is_sound :\n  forall (compile_aux_1 compile_aux_2 : arithmetic_expression ->\n                                        list byte_code_instruction),\n    specification_of_compile_aux compile_aux_1 ->\n    specification_of_compile_aux compile_aux_2 ->\n    forall (ae : arithmetic_expression),\n      compile_aux_1 ae = compile_aux_2 ae.\nProof.\n  intros compile_aux_1 compile_aux_2.\n  unfold specification_of_compile_aux.\n  intros [compile_aux_1_push [compile_aux_1_add compile_aux_1_sub]]\n         [compile_aux_2_push [compile_aux_2_add compile_aux_2_sub]].\n  intro ae.\n  (* now consider and induction over ae *)\n  induction ae as [ n | exp1 IH_exp1_add exp2 IH_exp2_add\n                    | exp1 IH_exp1_sub exp2 IH_exp2_sub].\n\n  (* case 1 : Literal *)\n  rewrite -> (compile_aux_1_push n) ; rewrite -> (compile_aux_2_push n) ;\n    reflexivity.\n\n  (* case 2 : Addition of expressions *)\n  rewrite -> (compile_aux_1_add exp1 exp2); rewrite -> (compile_aux_2_add exp1 exp2).\n  rewrite -> IH_exp1_add; rewrite -> IH_exp2_add.\n  reflexivity.\n\n  (* case 3: subtraction of expressions *)\n  rewrite -> (compile_aux_1_sub exp1 exp2); rewrite -> (compile_aux_2_sub exp1 exp2).\n  rewrite -> IH_exp1_sub; rewrite -> IH_exp2_sub.\n  reflexivity.\nQed.\n\n(* implementation of compilation using concatenation of bci lists *)\nFixpoint compile_aux_v0 (ae : arithmetic_expression) : list byte_code_instruction :=\n  match ae with\n  | Literal n =>\n    (PUSH n) :: nil\n  | Plus ae1 ae2 =>\n    (compile_aux_v0 ae1) ++ (compile_aux_v0 ae2) ++ (ADD :: nil)\n  | Minus ae1 ae2 =>\n    (compile_aux_v0 ae1) ++ (compile_aux_v0 ae2) ++ (SUB :: nil)\n  end.\n\n(* standard unfold lemmas *)\nLemma unfold_compile_aux_v0_literal :\n  forall (n : nat),\n    compile_aux_v0 (Literal n) = (PUSH n) :: nil.\nProof.\n  unfold_tactic compile_aux_v0.\nQed.\n\n\nLemma unfold_compile_aux_v0_plus :\n  forall (ae1 ae2 : arithmetic_expression),\n    compile_aux_v0 (Plus ae1 ae2)  =\n    (compile_aux_v0 ae1) ++ (compile_aux_v0 ae2) ++ (ADD :: nil).\nProof.\n  unfold_tactic compile_aux_v0.\nQed.\n\n\nLemma unfold_compile_aux_v0_minus :\n  forall (ae1 ae2 : arithmetic_expression),\n    compile_aux_v0 (Minus ae1 ae2)  =\n    (compile_aux_v0 ae1) ++ (compile_aux_v0 ae2) ++ (SUB :: nil).\nProof.\n  unfold_tactic compile_aux_v0.\nQed.\n\n\n(* proof that compile_aux_v0 meets the specification *)\nTheorem compile_aux_v0_meets_specification_of_compile_aux :\n  specification_of_compile_aux compile_aux_v0.\nProof.\n  unfold specification_of_compile_aux.\n  \n  split.\n  intro n.\n  rewrite -> (unfold_compile_aux_v0_literal n).\n  reflexivity.\n\n  split.\n  intros ae1 ae2.\n  rewrite -> (unfold_compile_aux_v0_plus ae1 ae2).\n  reflexivity.\n\n  intros ae1 ae2.\n  rewrite -> (unfold_compile_aux_v0_minus ae1 ae2).\n  reflexivity.\nQed.\n\n\n\nDefinition specification_of_compile (compile : source_program -> target_program) :=\n  forall compile_aux : arithmetic_expression -> list byte_code_instruction,\n    specification_of_compile_aux compile_aux ->\n    forall ae : arithmetic_expression,\n      compile (Source_program ae) = Target_program (compile_aux ae).\n\n(* Task 7:\n   prove that the definition above specifies a unique function,\n   implement this function,\n   and verify that your function satisfies the specification.\n *)\n(* the specification_of_compile is sound *)\nTheorem specification_of_compile_is_sound :\n  forall (compiler1 compiler2 : source_program -> target_program),\n    specification_of_compile compiler1 ->\n    specification_of_compile compiler2 ->\n    forall (ae : arithmetic_expression),\n      compiler1 (Source_program ae) =\n      compiler2 (Source_program ae).\nProof.\n  intros compiler1 compiler2.\n  unfold specification_of_compile.\n  intros H1 H2.\n  intro ae.\n  rewrite -> (H1 compile_aux_v0 compile_aux_v0_meets_specification_of_compile_aux ae).\n  rewrite -> (H2 compile_aux_v0 compile_aux_v0_meets_specification_of_compile_aux ae).\n  reflexivity.\nQed.\n\n(* implementation of the specification_of_compile *)\nDefinition compile_v0 (sp : source_program) : target_program :=\n  match sp with\n  | Source_program sp =>\n    Target_program (compile_aux_v0 sp)\n  end.\n\n(* Proof that compile_v0 meets the specification_of_compile *)\nTheorem compile_v0_meets_the_specification_of_compile :\n  specification_of_compile compile_v0.\nProof.\n  unfold specification_of_compile.\n  intros compile_aux_var H_about_compile_aux_var.\n  intro ae.\n  unfold compile_v0.\n  rewrite ->\n          (specification_of_compile_aux_is_sound\n          compile_aux_var\n          compile_aux_v0\n          H_about_compile_aux_var\n          compile_aux_v0_meets_specification_of_compile_aux\n          ae).\n  reflexivity.\nQed.\n\n\n(* Task 8:\n   implement an alternative compiler\n   using an auxiliary function with an accumulator\n   and that does not use ++ but :: instead,\n   and prove that it satisfies the specification.\n *)\n\n(* auxiliary compile function implemented with accumulator *)\nFixpoint compile_aux_v1 (ae : arithmetic_expression)\n         (acc : list byte_code_instruction) : list byte_code_instruction :=\n  match ae with\n  | Literal n =>\n    (PUSH n) :: acc\n  | Plus ae1 ae2 =>\n    compile_aux_v1 ae1 (compile_aux_v1 ae2 (ADD :: acc))\n  | Minus ae1 ae2 =>\n    compile_aux_v1 ae1 (compile_aux_v1 ae2 (SUB :: acc))\n  end.\n\n(* unfold lemmas *)\nLemma unfold_compile_aux_v1_literal :\n  forall (n : nat)\n         (acc : list byte_code_instruction),\n    compile_aux_v1 (Literal n) acc = (PUSH n) :: acc.\nProof.\n  unfold_tactic compile_aux_v1.\nQed.\n\n\nLemma unfold_compile_aux_v1_plus :\n  forall (ae1 ae2 : arithmetic_expression)\n         (acc :list byte_code_instruction),\n    compile_aux_v1 (Plus ae1 ae2) acc =\n    compile_aux_v1 ae1 (compile_aux_v1 ae2 (ADD :: acc)).\nProof.\n  unfold_tactic compile_aux_v1.\nQed.\n\nLemma unfold_compile_aux_v1_minus :\n  forall (ae1 ae2 : arithmetic_expression)\n         (acc :list byte_code_instruction),\n    compile_aux_v1 (Minus ae1 ae2) acc =\n    compile_aux_v1 ae1 (compile_aux_v1 ae2 (SUB :: acc)).\nProof.\n  unfold_tactic compile_aux_v1.\nQed.\n\n(* Master lemma concerning the relation between compile_aux_v1 and compile_aux_v0 *)\nLemma master_lemma_about_compile_aux_v1 :\n  forall (ae : arithmetic_expression)\n         (acc : list byte_code_instruction),\n    compile_aux_v1 ae acc =  (compile_aux_v0 ae) ++ acc.\nProof.\n  intros ae.\n  induction ae as [ n | exp1 IH_exp1_add exp2 IH_exp2_add |\n                    exp1 IH_exp1_sub exp2 IH_exp2_sub ].\n\n  (* literals *)\n  intro acc.\n  rewrite -> (unfold_compile_aux_v1_literal n acc).\n  rewrite -> (unfold_compile_aux_v0_literal n).\n  Search (_ ++ _ = _).\n  rewrite -> (unfold_append_cons (PUSH n) nil acc).\n  rewrite -> (unfold_append_nil).\n  reflexivity.\n\n  (* plus *)\n  intro acc.\n  rewrite -> (unfold_compile_aux_v1_plus exp1 exp2 acc).\n  rewrite -> (unfold_compile_aux_v0_plus exp1 exp2).\n  rewrite -> (IH_exp2_add (ADD :: acc)).\n  rewrite -> (IH_exp1_add (compile_aux_v0 exp2 ++ ADD :: acc)).\n  Search (_ ++ _ = _).\n  rewrite -> app_assoc_reverse.\n  rewrite -> app_assoc_reverse.\n  rewrite -> unfold_append_cons.\n  rewrite -> unfold_append_nil.\n  reflexivity.\n\n  (* the proof for minus will be very similar *)\n  intro acc.\n  rewrite -> (unfold_compile_aux_v1_minus exp1 exp2 acc).\n  rewrite -> (unfold_compile_aux_v0_minus exp1 exp2).\n  rewrite -> (IH_exp2_sub (SUB :: acc)).\n  rewrite -> (IH_exp1_sub (compile_aux_v0 exp2 ++ SUB :: acc)).\n  Search (_ ++ _ = _).\n  rewrite -> app_assoc_reverse.\n  rewrite -> app_assoc_reverse.\n  rewrite -> unfold_append_cons.\n  rewrite -> unfold_append_nil.\n  reflexivity.\nQed.\n\n\n\n(* compiler implementation that uses an accumulator based auxiliary function *)\nDefinition compile_v1 (sp : source_program) : target_program :=\n  match sp with\n  | Source_program sp =>\n    Target_program (compile_aux_v1 sp nil)\n  end.\n\n\n(* Proof that compile_v1 meets the specification_of_compile *)\nTheorem compile_v1_meets_the_specification_of_compile :\n  specification_of_compile compile_v1.\nProof.\n  unfold specification_of_compile.\n  intros compile_aux_var H_about_compile_aux_var.\n  intro ae.\n  unfold compile_v1.\n  rewrite -> (master_lemma_about_compile_aux_v1 ae nil).\n  Search ( _ ++ _ = _).\n  rewrite -> app_nil_r.\n  rewrite ->\n          (specification_of_compile_aux_is_sound\n          compile_aux_var\n          compile_aux_v0\n          H_about_compile_aux_var\n          compile_aux_v0_meets_specification_of_compile_aux\n          ae).\n  reflexivity.\nQed.\n\n\n(* ********** *)\n\n\n\n(* Task 9 (the capstone):\n   Prove that interpreting an arithmetic expression gives the same result\n   as first compiling it and then executing the compiled program.\n *)\n\nLemma master_lemma_for_commutative_diagram :\n  forall (ae : arithmetic_expression)\n         (ds : data_stack),\n      fetch_decode_execute_loop (compile_aux_v0 ae) ds =     \n      match (evaluate_v0 ae) with\n      | Expressible_nat num =>\n       OK (num :: ds)\n      | Expressible_msg err_msg =>\n        KO err_msg\n      end.  \nProof.\n  (* we will prove this lemma by induction over arithmetic expressions *)\n  induction ae as [ nat_val | e1 IH_e1_plus e2 IH_e2_plus |\n                    e1 IH_e1_minus e2 IH_e2_minus].\n\n  (* literals *)\n  intro ds_for_lemma.\n  (* unfold L.H.S. *)\n  rewrite -> unfold_compile_aux_v0_literal.\n  rewrite ->\n          (unfold_fetch_decode_execute_loop_bcis (PUSH nat_val) nil ds_for_lemma).\n  unfold decode_execute.\n  rewrite -> unfold_fetch_decode_execute_loop_nil.\n  (* unfold R.H.S. *)\n  rewrite -> unfold_evaluate_v0_literal.\n  reflexivity.\n\n  (* plus expressions *)\n  intro ds_for_lemma.\n  (* unfold R.H.S and L.H.S. expressions *)\n  rewrite -> (unfold_evaluate_v0_plus e1 e2).\n  rewrite -> (unfold_compile_aux_v0_plus e1 e2).\n  (* consider cases of evaluate_v0 first *)\n  case (evaluate_v0 e1) as [err_msg_e1 | nat_val_e1] eqn : val_of_eval_v0_e1.\n\n  (* evaluate_v0 e1 = Expressible_msg _ *)\n  (* introduce lemma we proved about running the append of two bci lists *)\n  Check (relation_between_execution_of_two_bcis_and_their_appended_version).\n  destruct (relation_between_execution_of_two_bcis_and_their_appended_version\n              (compile_aux_v0 e1)\n              (compile_aux_v0 e2 ++ ADD :: nil)) as [H_OK H_KO].\n  (* use the introduced hypotheses to modify the induction hypotheses, and use this\n   * to prove the goal *)\n  apply (H_KO ds_for_lemma err_msg_e1) in IH_e1_plus.\n  rewrite -> IH_e1_plus. \n  reflexivity.\n\n  (* evaluate_v0 e1 = Expressible_nat _ *)\n  (* once again, introduce this hypothesis *)\n  destruct (relation_between_execution_of_two_bcis_and_their_appended_version\n              (compile_aux_v0 e1)\n              (compile_aux_v0 e2 ++ ADD :: nil)) as [H_OK H_KO]. \n  apply (H_OK ds_for_lemma (nat_val_e1 :: ds_for_lemma)) in IH_e1_plus.\n  rewrite -> IH_e1_plus.\n  clear H_OK H_KO.\n  (* now consider cases of (evaluate_v0 e2) *)\n  case (evaluate_v0 e2) as [err_msg_e2 | nat_val_e2] eqn : val_of_eval_v0_e2.\n\n  (* evaluate_v0 e2 = Expressible_msg _ *)\n  destruct (relation_between_execution_of_two_bcis_and_their_appended_version\n              (compile_aux_v0 e2)\n              (ADD :: nil)) as [H_OK H_KO].\n  apply (H_KO (nat_val_e1 :: ds_for_lemma) err_msg_e2) in IH_e2_plus.\n  rewrite -> IH_e2_plus.\n  reflexivity.\n\n  (* evaluate_v0 e2 = Expressible_msg _ *)\n  destruct (relation_between_execution_of_two_bcis_and_their_appended_version\n              (compile_aux_v0 e2)\n              (ADD :: nil)) as [H_OK H_KO].\n   apply (H_OK (nat_val_e1 :: ds_for_lemma)\n              (nat_val_e2 :: nat_val_e1 :: ds_for_lemma)) in\n            IH_e2_plus.\n   rewrite -> IH_e2_plus.\n   rewrite -> (unfold_fetch_decode_execute_loop_bcis ADD nil).\n   unfold decode_execute.\n   rewrite -> unfold_fetch_decode_execute_loop_nil.\n   reflexivity.\n\n   (* minus *)\n   (* the structure of this section of the proof is very simlar to that of plus *)\n   intro ds_for_lemma.\n  (* unfold R.H.S and L.H.S. expressions *)\n  rewrite -> (unfold_evaluate_v0_minus e1 e2).\n  rewrite -> (unfold_compile_aux_v0_minus e1 e2).\n  (* consider cases of evaluate_v0 first *)\n  case (evaluate_v0 e1) as [err_msg_e1 | nat_val_e1] eqn : val_of_eval_v0_e1.\n\n  (* evaluate_v0 e1 = Expressible_msg _ *)\n  (* introduce lemma we proved about running the append of two bci lists *)\n  Check (relation_between_execution_of_two_bcis_and_their_appended_version).\n  destruct (relation_between_execution_of_two_bcis_and_their_appended_version\n              (compile_aux_v0 e1)\n              (compile_aux_v0 e2 ++ SUB :: nil)) as [H_OK H_KO].\n  (* use the introduced hypotheses to modify the induction hypotheses, and use this\n   * to prove the goal *)\n  apply (H_KO ds_for_lemma err_msg_e1) in IH_e1_minus.\n  rewrite -> IH_e1_minus. \n  reflexivity.\n\n  (* evaluate_v0 e1 = Expressible_nat _ *)\n  (* once again, introduce this hypothesis *)\n  destruct (relation_between_execution_of_two_bcis_and_their_appended_version\n              (compile_aux_v0 e1)\n              (compile_aux_v0 e2 ++ SUB :: nil)) as [H_OK H_KO]. \n  apply (H_OK ds_for_lemma (nat_val_e1 :: ds_for_lemma)) in IH_e1_minus.\n  rewrite -> IH_e1_minus.\n  clear H_OK H_KO.\n  (* now consider cases of (evaluate_v0 e2) *)\n  case (evaluate_v0 e2) as [err_msg_e2 | nat_val_e2] eqn : val_of_eval_v0_e2.\n\n  (* evaluate_v0 e2 = Expressible_msg _ *)\n  destruct (relation_between_execution_of_two_bcis_and_their_appended_version\n              (compile_aux_v0 e2)\n              (SUB :: nil)) as [H_OK H_KO].\n  apply (H_KO (nat_val_e1 :: ds_for_lemma) err_msg_e2) in IH_e2_minus.\n  rewrite -> IH_e2_minus.\n  reflexivity.\n\n  (* evaluate_v0 e2 = Expressible_msg _ *)\n  (* now we consider the cases of ltb nat_val_e1 and nat_val_e2 *)\n  case (ltb nat_val_e1 nat_val_e2) eqn : value_of_ltb_nat_val_e1_nat_val_e2.\n\n  (* ltb nat_val_e1 nat_val_e2 = true *)\n  destruct (relation_between_execution_of_two_bcis_and_their_appended_version\n              (compile_aux_v0 e2)\n              (SUB :: nil)) as [H_OK H_KO].\n  apply (H_OK (nat_val_e1 :: ds_for_lemma)\n              (nat_val_e2 :: nat_val_e1 :: ds_for_lemma)) in\n      IH_e2_minus.\n  rewrite -> IH_e2_minus.\n  rewrite -> (unfold_fetch_decode_execute_loop_bcis SUB nil).\n  unfold decode_execute.\n  rewrite -> value_of_ltb_nat_val_e1_nat_val_e2.\n  reflexivity.\n\n  (* ltb nat_val_e1 nat_val_e2 = false *)\n  destruct (relation_between_execution_of_two_bcis_and_their_appended_version\n              (compile_aux_v0 e2)\n              (SUB :: nil)) as [H_OK H_KO].\n  apply (H_OK (nat_val_e1 :: ds_for_lemma)\n              (nat_val_e2 :: nat_val_e1 :: ds_for_lemma)) in\n      IH_e2_minus.\n  rewrite -> IH_e2_minus.\n  rewrite -> (unfold_fetch_decode_execute_loop_bcis SUB nil).\n  unfold decode_execute.\n  rewrite -> value_of_ltb_nat_val_e1_nat_val_e2.\n  rewrite -> unfold_fetch_decode_execute_loop_nil.\n  reflexivity.\nQed.  \n\n\nTheorem the_commutative_diagram :\n    forall sp : source_program,\n      interpret_v0 sp = run (compile_v0 sp).\nProof.\n  intro sp.\n  case sp as [ae].\n  unfold interpret_v0; unfold compile_v0; unfold run.\n  (* Use master lemma to finish off the proof *)\n  Check (master_lemma_for_commutative_diagram).\n  Check (master_lemma_for_commutative_diagram ae nil).\n  rewrite ->\n          (master_lemma_for_commutative_diagram ae nil).\n  case (evaluate_v0 ae) as [err_msg | nat_val].\n  reflexivity.\n  reflexivity.\nQed.\n\n\n\n\n\n\n(* ********** *)\n\n(* Task 10 (if there is time):\n\n   a. Write a Magritte interpreter for the source language\n      that does not operate on natural numbers\n      but on syntactic representations of natural numbers.\n\n   b. Write a Magritte interpreter for the target language\n      that does not operate on natural numbers\n      but on syntactic representations of natural numbers.\n\n   c. Prove that interpreting an arithmetic expression with the Magritte source interpreter\n      gives the same result as first compiling it and then executing the compiled program\n      with the Magritte target interpreter over an empty data stack.\n\n   d. Prove that the Magritte target interpreter is (essentially)\n      a left inverse of the compiler, i.e., it is a decompiler.\n*)\n\n(* ********** *)\n\n(* Byte-code verification:\n   the following verifier symbolically executes a byte-code program\n   to check whether no underflow occurs during execution\n   and whether when the program completes,\n   there is one and one only natural number on top of the stack.\n   The second argument of verify_aux is a natural number\n   that represents the size of the stack.\n*)\n\nFixpoint verify_aux (bcis : list byte_code_instruction) (n : nat) : option nat :=\n  match bcis with\n    | nil =>\n      Some n\n    | bci :: bcis' =>\n      match bci with\n        | PUSH _ =>\n          verify_aux bcis' (S n)\n        | _ =>\n          match n with\n            | S (S n') =>\n              verify_aux bcis' (S n')\n            | _ =>\n              None\n          end\n      end\n  end.\n\n(* Unfold Lemmas *)\nLemma unfold_verify_aux_nil :\n  forall (n : nat),\n    verify_aux nil n = Some n.\nProof.\n  unfold_tactic verify_aux.\nQed.\n\nLemma unfold_verify_aux_cons :\n  forall (bci : byte_code_instruction)\n         (bcis : list byte_code_instruction)\n         (n : nat),\n    verify_aux (bci :: bcis) n =\n    match bci with\n        | PUSH _ =>\n          verify_aux bcis (S n)\n        | _ =>\n          match n with\n            | S (S n') =>\n              verify_aux bcis (S n')\n            | _ =>\n              None\n          end\n      end.\nProof.\n  unfold_tactic verify_aux.\nQed.\n\n\n\nDefinition verify (p : target_program) : bool :=\n  match p with\n  | Target_program bcis =>\n    match verify_aux bcis 0 with\n    | Some n =>\n      match n with\n      | 1 =>\n        true\n      | _ =>\n        false\n      end\n    | _ =>\n      false\n    end\n  end.\n\n(* Task 11:\n   Prove that the compiler emits code\n   that is accepted by the verifier.\n*)\n\n    \n\nLemma relation_between_bcis_and_verify_aux:\n  forall (bci1s bci2s: list byte_code_instruction),\n    (forall (n n': nat),\n    verify_aux bci1s n = Some n' ->\n    verify_aux (bci1s ++ bci2s) n = verify_aux (bci2s) n') /\\\n    (forall (n : nat),\n        verify_aux bci1s n = None ->\n        verify_aux (bci1s ++ bci2s) n = None).\nProof.\n  Admitted.\n\n\nTheorem the_compiler_emits_well_behaved_code :\n  forall ae : arithmetic_expression,\n    verify (compile_v0 (Source_program ae)) = true.\nProof.\n  Abort.\n\n\n\n\n\n(* What are the consequences of this theorem? *)\n\n(* ********** *)\n\n(* end of week-15_a-commutative-diagram.v *)\n", "meta": {"author": "oishikg", "repo": "fpp-final-project", "sha": "89e8da3968b44013eb3048922524bd894520b674", "save_path": "github-repos/coq/oishikg-fpp-final-project", "path": "github-repos/coq/oishikg-fpp-final-project/fpp-final-project-89e8da3968b44013eb3048922524bd894520b674/week-15_a-commutative-diagram.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624738835052, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.6728265576820638}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_collinearorder.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral}.\n\nLemma lemma_parallelNC : \n   forall A B C D, \n   Par A B C D ->\n   nCol A B C /\\ nCol A C D /\\ nCol B C D /\\ nCol A B D.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists M a b c d, (neq A B /\\ neq C D /\\ Col A B a /\\ Col A B b /\\ neq a b /\\ Col C D c /\\ Col C D d /\\ neq c d /\\ ~ Meet A B C D /\\ BetS a M d /\\ BetS c M b)) by (conclude_def Par );destruct Tf as [M[a[b[c[d]]]]];spliter.\nassert (~ Col A C D).\n {\n intro.\n assert (Col C D A) by (forward_using lemma_collinearorder).\n assert (eq A A) by (conclude cn_equalityreflexive).\n assert (Col A B A) by (conclude_def Col ).\n assert (Meet A B C D) by (conclude_def Meet ).\n contradict.\n }\nassert (~ Col A B C).\n {\n intro.\n assert (eq C C) by (conclude cn_equalityreflexive).\n assert (Col C D C) by (conclude_def Col ).\n assert (Meet A B C D) by (conclude_def Meet ).\n contradict.\n }\nassert (~ Col B C D).\n {\n intro.\n assert (Col C D B) by (forward_using lemma_collinearorder).\n assert (eq B B) by (conclude cn_equalityreflexive).\n assert (Col A B B) by (conclude_def Col ).\n assert (Meet A B C D) by (conclude_def Meet ).\n contradict.\n }\nassert (~ Col A B D).\n {\n intro.\n assert (eq D D) by (conclude cn_equalityreflexive).\n assert (Col C D D) by (conclude_def Col ).\n assert (Meet A B C D) by (conclude_def Meet ).\n contradict.\n }\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_parallelNC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6728265520540766}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import String.\nOpen Scope string_scope.\nRequire Import Bool.\nRequire Import Sumbool.\n\nSection LambdaChurch.\n\n(* Syntax *)\n\nDefinition var_L := string.\n\nInductive type_L : Type :=\n| T_bool : type_L\n| T_func : type_L -> type_L -> type_L.\n\nNotation \"'Bool'\" := T_bool (at level 70).\nNotation \"t ~> u\" := (T_func t u) (right associativity, at level 60).\n\nInductive expr_L : Type :=\n| E_true : expr_L\n| E_false : expr_L\n| E_var : var_L -> expr_L\n| E_lambda : var_L -> type_L -> expr_L -> expr_L\n| E_app : expr_L -> expr_L -> expr_L\n| E_if : expr_L -> expr_L -> expr_L -> expr_L.\n\nNotation \"'TRUE'\" := E_true (at level 50).\nNotation \"'FALSE'\" := E_false (at level 50).\nNotation \"% v\" := (E_var v) (at level 50).\nNotation \"p $ q\" := (E_app p q) (left associativity, at level 40).\nNotation \"\\ x 'AT' t 'IS' e\" := (E_lambda x t e) (at level 30).\nNotation \"'WHEN' b 'THEN' p 'ELSE' q\" := (E_if b p q) (at level 20).\n\n(* Context *)\n\nDefinition context_L := var_L -> option type_L.\n\nFixpoint add_ctx (ctx : context_L) (v : var_L) (t : type_L) : context_L := \nfun v' => if string_dec v v' then Some t else ctx v'.\n\n(* Typing rules *)\n\nInductive typing (c : context_L) : expr_L -> type_L -> Prop :=\n| Type_true : typing c E_true T_bool\n| Type_false : typing c E_false T_bool\n| Type_var v : forall t : type_L, c v = Some t -> typing c (E_var v) t\n| Type_lambda v t e : forall u : type_L, typing (add_ctx c v t) e u\n                        -> typing c (E_lambda v t e) (T_func t u)\n| Type_app e1 e2 : forall (t u : type_L), typing c e1 (T_func t u)\n                     -> typing c e2 t -> typing c (E_app e1 e2) u\n| Type_if b e1 e2 : forall (t : type_L), typing c b T_bool -> typing c e1 t\n                      -> typing c e2 t -> typing c (E_if b e1 e2) t.\n\nFixpoint eq_type (t u : type_L) : bool :=\nmatch t, u with\n| T_bool, T_bool => true\n| T_func t1 t2, T_func u1 u2 => eq_type t1 u1 && eq_type t2 u2\n| _, _ => false\nend.\n\nFixpoint do_infer (c : context_L) (exp : expr_L) : option type_L :=\nmatch exp with\n| E_true => Some T_bool\n| E_false => Some T_bool\n| E_var v => c v\n| E_lambda v t e => match do_infer (add_ctx c v t) e with\n                    | Some u => Some (T_func t u)\n                    | None => None\n                    end\n| E_app e1 e2 => match do_infer c e1 with\n                 | Some (T_func t u) => if do_check c e2 t then Some u else None\n                 | _ => None\n                 end\n| E_if b e1 e2 => if do_check c b T_bool\n                  then match do_infer c e1 with\n                       | Some t => if do_check c e2 t then Some t else None\n                       | None => None\n                       end\n                  else None\nend\nwith do_check (c : context_L) (exp : expr_L) (tp : type_L) : bool :=\nmatch exp with\n| E_true | E_false => match tp with\n                      | T_bool => true\n                      | _ => false\n                      end\n| E_var v => match c v with\n             | Some t' => eq_type t' tp\n             | None => false\n             end\n| E_lambda v t e => match tp with\n                    | T_func t' u' => eq_type t' t\n                                      && do_check (add_ctx c v t) e u'\n                    | _ => false\n                    end\n| E_app e1 e2 => match do_infer c e1 with\n                 | Some (T_func t' u') => eq_type u' tp && do_check c e2 t'\n                 | _ => false\n                 end\n| E_if b e1 e2 => do_check c b T_bool && do_check c e1 tp && do_check c e2 tp\nend.\n\n(* Lemmas *)\n\nLtac rewrite_refl H := rewrite H ; reflexivity.\n\nLtac rewrite_refl_2 H1 H2 := rewrite H1 ; rewrite H2 ; reflexivity.\n\nLemma eq_type_eq :\nforall (t0 t1 : type_L), eq_type t0 t1 = true <-> t0 = t1.\nProof.\ninduction t0 ; destruct t1 ; split ; intros ; try reflexivity\n; try solve [inversion H].\n* inversion H.\n  apply andb_true_iff in H1.\n  destruct H1 as [G G0].\n  destruct (IHt0_1 t1_1) as [IHt0_1L IHt0_1P].\n  destruct (IHt0_2 t1_2) as [IHt0_2L IHt0_2P].\n  rewrite_refl_2 (IHt0_1L G) (IHt0_2L G0).\n* simpl.\n  destruct (IHt0_1 t1_1) as [IHt0_1L IHt0_1P].\n  destruct (IHt0_2 t1_2) as [IHt0_2L IHt0_2P].\n  rewrite IHt0_1P\n  ; try rewrite IHt0_2P\n  ; inversion H\n  ; reflexivity.\nQed.\n\nLemma andb_true :\nforall a b, andb a b = true <-> a = true /\\ b = true.\nProof.\nsplit.\n* destruct a ; destruct b ; intros ; simpl in * ; try discriminate ; split\n  ; assumption.\n* intros.\n  destruct H.\n  rewrite_refl_2 H H0.\nQed.\n\nLemma context_var_dec :\nforall (c : context_L) (v : var_L),\n  {t : type_L | c v = Some t} + {c v = None}.\nProof.\nintros.\ndestruct (c v).\n* left.\n  exists t.\n  reflexivity.\n* right.\n  reflexivity.\nQed.\n\nLtac split_andb H := apply andb_true in H\n                     ; let g0 := fresh \"G\" in\n                       let g1 := fresh \"G\" in\n                       destruct H as [g0 g1].\n\nLtac eq H := apply eq_type_eq in H ; subst.\n\nLtac eq_reflexivity H := eq H ; reflexivity.\n\nLtac eq_type_and_true := apply andb_true_iff\n                         ; split\n                         ; try apply eq_type_eq\n                         ; reflexivity.\n\n(* Equivalence proofs *)\n\nLemma do_check_is_do_infer :\nforall (e : expr_L) (c : context_L) (t : type_L),\n  do_check c e t = true -> do_infer c e = Some t.\nProof.\ninduction e ; intros.\n* destruct t ; simpl in * ; [reflexivity | discriminate].\n* destruct t ; simpl in * ; [reflexivity | discriminate].\n* simpl in *.\n  destruct (c v) ; [eq_reflexivity H | discriminate].\n* simpl in H.\n  destruct t0 ; try discriminate.\n  split_andb H.\n  eq G.\n  specialize (IHe (add_ctx c v t) t0_2 G0).\n  simpl.\n  rewrite_refl IHe.\n* simpl in *.\n  destruct (do_infer c e1) ; try destruct t0 ; try discriminate.\n  split_andb H.\n  rewrite G0.\n  eq_reflexivity G.\n* simpl in H.\n  split_andb H.\n  split_andb G.\n  simpl.\n  rewrite G1.\n  rewrite_refl_2 (IHe2 c t G2) G0.\nQed.\n\nLemma do_infer_is_do_check :\nforall (e : expr_L) (c : context_L) (t : type_L),\n  do_infer c e = Some t -> do_check c e t = true.\nProof.\ninduction e ; intros ; simpl in *.\n* inversion H.\n  reflexivity.\n* inversion H.\n  reflexivity.\n* rewrite H.\n  apply eq_type_eq.\n  reflexivity.\n* remember (do_infer (add_ctx c v t) e) as I.\n  destruct I ; try discriminate.\n  destruct t0 ; try inversion H.\n  subst.\n  symmetry in HeqI.\n  apply IHe in HeqI.\n  rewrite HeqI.\n  eq_type_and_true.\n* destruct (do_infer c e1) ; try discriminate.\n  destruct t0 ; try discriminate.\n  destruct (do_check c e2 t0_1) ; try discriminate.\n  inversion H.\n  subst.\n  eq_type_and_true.\n* destruct (do_check c e1 T_bool) ; try discriminate.\n  simpl.\n  remember (do_infer c e2) as I.\n  destruct I ; try discriminate.\n  symmetry in HeqI.\n  apply IHe2 in HeqI.\n  destruct (sumbool_of_bool (eq_type t0 t)).\n** eq e.\n   rewrite HeqI.\n   simpl.\n   destruct (do_check c e3 t) ; [reflexivity | discriminate].\n** apply not_true_iff_false in e.\n   destruct (do_check c e3 t0) ; try discriminate.\n   inversion H.\n   eq H1.\n   contradiction.\nQed.\n\nLemma typing_is_do_infer :\nforall (e : expr_L) (c : context_L) (t : type_L),\n  typing c e t -> do_infer c e = Some t.\nProof.\ninduction 1 ; intros ; simpl.\n* reflexivity.\n* reflexivity.\n* assumption.\n* rewrite_refl IHtyping.\n* rewrite IHtyping1.\n  apply do_infer_is_do_check in IHtyping2.\n  rewrite_refl IHtyping2.\n* apply do_infer_is_do_check in IHtyping1.\n  rewrite IHtyping1.\n  rewrite IHtyping2.\n  apply do_infer_is_do_check in IHtyping3.\n  rewrite_refl IHtyping3.\nQed.\n\nLemma do_infer_is_typing :\nforall (e : expr_L) (c : context_L) (t : type_L),\n  do_infer c e = Some t -> typing c e t.\nProof.\ninduction e ; intros ; simpl in H.\n* inversion H.\n  subst.\n  constructor.\n* inversion H.\n  subst.\n  constructor.\n* constructor.\n  assumption.\n* remember (do_infer (add_ctx c v t) e) as I.\n  destruct I ; try discriminate.\n  inversion H.\n  subst.\n  constructor.\n  apply IHe.\n  symmetry.\n  assumption.\n* remember (do_infer c e1) as I1.\n  destruct I1 ; try destruct t0 ; try discriminate.\n  remember (do_check c e2 t0_1) as I2.\n  destruct I2 ; try discriminate.\n  inversion H.\n  subst.\n  apply Type_app with (t:=t0_1)\n  ; [apply IHe1 | apply IHe2 ; apply do_check_is_do_infer] ; symmetry\n  ; assumption.\n* simpl in H.\n  remember (do_check c e1 T_bool) as I1.\n  remember (do_infer c e2) as I2.\n  destruct I1 ; try destruct t0 ; try destruct I2 ; try discriminate.\n  remember (do_check c e3 t0) as I3.\n  destruct I3 ; try discriminate.\n  inversion H.\n  subst.\n  constructor ; [apply IHe1 ; apply do_check_is_do_infer\n                | apply IHe2\n                | apply IHe3 ; apply do_check_is_do_infer]\n  ; symmetry ; assumption.\nQed.\n\n(* Typing proof *)\n\nTheorem make_typecheck_1 :\nforall (e : expr_L) (c : context_L), option {t : type_L | typing c e t}.\nProof.\ninduction e ; intros.\n* refine (Some (exist _ T_bool _)).\n  constructor.\n* refine (Some (exist _ T_bool _)).\n  constructor.\n* destruct (context_var_dec c v).\n** destruct s.\n   refine (Some (exist _ x _)).\n   constructor.\n   assumption.\n** refine None.\n* destruct (IHe (add_ctx c v t)).\n** destruct s.\n   refine (Some (exist _ (T_func t x) _)).\n   constructor.\n   assumption.\n** refine None.\n* destruct (IHe2 c).\n** destruct s.\n   destruct (IHe1 c).\n*** destruct s.\n    destruct x0.\n**** refine None.\n**** destruct (sumbool_of_bool (eq_type x x0_1)).\n***** apply eq_type_eq in e.\n      subst.\n      refine (Some (exist _ x0_2 _)).\n      apply Type_app with (t:=x0_1) ; assumption.\n***** refine None.\n*** refine None.\n** refine None.\n* destruct (IHe1 c).\n** destruct s.\n   destruct x.\n*** destruct (IHe2 c).\n**** destruct s.\n     destruct (IHe3 c).\n***** destruct s.\n      destruct (sumbool_of_bool (eq_type x x0)).\n****** apply eq_type_eq in e.\n       subst.\n       refine (Some (exist _ x0 _)).\n       constructor ; assumption.\n****** refine None.\n***** refine None.\n**** refine None.\n*** refine None.\n** refine None.\nQed.\n\nTheorem make_typecheck_2 :\nforall (e : expr_L) (c : context_L), option {t : type_L | typing c e t}.\nProof.\nrefine (\n  fix tp (ex : expr_L) (ct : context_L) :=\n    match ex with\n    | E_true => Some (exist _ T_bool _)\n    | E_false => Some (exist _ T_bool _)\n    | E_var v => match context_var_dec ct v with\n                 | inleft (exist _ t d) => Some (exist _ t _)\n                 | inright _ => None\n                 end\n    | E_lambda v t e0 => match tp e0 (add_ctx ct v t) with\n                         | Some (exist _ u d) =>\n                           Some (exist _ (T_func t u) _)\n                         | None => None\n                         end\n    | E_app e1 e2 => match tp e1 ct, tp e2 ct with\n                     | Some d1, Some d2 => _\n                     | _, _ => None\n                     end\n    | E_if b e1 e2 => match tp b ct, tp e1 ct, tp e2 ct with\n                      | Some (exist _ tb db), Some d1, Some d2 => _\n                      | _, _, _ => None\n                      end\n    end).\n* constructor.\n* constructor.\n* constructor.\n  assumption.\n* constructor.\n  assumption.\n* destruct d1.\n  destruct x.\n** refine None.\n** destruct d2.\n   destruct (sumbool_of_bool (eq_type x x1)).\n*** apply eq_type_eq in e.\n    subst.\n    refine (Some (exist _ x2 _)).\n    apply Type_app with (t:=x1) ; assumption.\n*** refine None.\n* destruct tb.\n** destruct d1.\n   destruct d2.\n   destruct (sumbool_of_bool (eq_type x x0)).\n*** apply eq_type_eq in e.\n    subst.\n    refine (Some (exist _ x0 _)).\n    constructor ; assumption.\n*** refine None.\n** refine None.\nQed.\n\nEnd LambdaChurch.", "meta": {"author": "ref-humbold", "repo": "Lambda-Check", "sha": "dbb2ae53f684663641932a661b7734405816a65e", "save_path": "github-repos/coq/ref-humbold-Lambda-Check", "path": "github-repos/coq/ref-humbold-Lambda-Check/Lambda-Check-dbb2ae53f684663641932a661b7734405816a65e/LambdaChurch_bidir.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.672824509448206}}
{"text": "(*\n  Copyright 2022 ZhengPu Shi\n  This file is part of CoqMatrix. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : Vector theory on real numbers\n  author    : ZhengPu Shi\n  date      : 2021.12\n  \n  ref:\n  1. 《高等数学学习手册》徐小湛，p173\n  2. Vector Calculus - Michael Corral\n  3. https://github.com/coq/coq/blob/master/test-suite/success/Nsatz.v\n     注意，这里有Coq库中定义的几何学形式化内容，包括点，平行，共线等。\n*)\n\nRequire Export Vector.\nRequire Export RMatrix.\n\nOpen Scope R.\nOpen Scope mat_scope.\n\n(* ======================================================================= *)\n(** ** 从向量理论 导出的 实数域向量理论 *)\n\nDefinition vec := vec (A:=R).\n\nDefinition v2f {n} (v : vec n) := v2f v.\n\nDefinition f2v {n} f : vec n := f2v n f.\n\nDefinition vnth {n} (v : vec n) i := vnth v i.\n\nDefinition veq {n} (v1 v2 : vec n) := veq v1 v2.\nGlobal Infix \"==\" := veq : vec_scope.\n\nLemma veq_refl : forall {n} (v : vec n), v == v.\nProof. intros. apply veq_refl. Qed.\n\nLemma veq_sym : forall {n} (v1 v2 : vec n), v1 == v2 -> v2 == v1.\nProof. intros. apply veq_sym; auto. Qed.\n\nLemma veq_trans : forall {n} (v1 v2 v3 : vec n),\n    v1 == v2 -> v2 == v3 -> v1 == v3.\nProof. intros. apply veq_trans with v2; auto. Qed.\n\nHint Resolve veq_refl : vec.\nHint Resolve veq_sym : vec.\nHint Resolve veq_trans : vec.\n\nLemma veq_dec : forall {n} (v1 v2 : vec n), {v1 == v2} + {~(v1 == v2)}.\nProof. intros. apply veq_dec. Qed.\n\nDefinition t2v_2 (t : T2) : vec 2 := t2v_2 (A0:=0) t.\n\nDefinition v2t_2 (v : vec 2) : T2 := v2t_2 v.\n\nDefinition t2v_3 (t : T3) : vec 3 := t2v_3 (A0:=0) t.\n\nDefinition v2t_3 (v : vec 3) : T3 := v2t_3 v.\n\nDefinition t2v_4 (t : T4) : vec 4 := t2v_4 (A0:=0) t.\n\nDefinition v2t_4 (v : vec 4) : T4 := v2t_4 v.\n\nLemma v2t_t2v_id_2 : forall (t : T2), v2t_2 (t2v_2 t) = t.\nProof. intros. apply v2t_t2v_id_2. Qed.\n\nLemma t2v_v2t_id_2 : forall (v : vec 2), t2v_2 (v2t_2 v) == v.\nProof. intros. apply t2v_v2t_id_2. Qed.\n\nDefinition v2l {n} (v : vec n) := v2l v.\n\nDefinition l2v n l : vec n := l2v (A0:=0) l.\n\nLemma v2l_length : forall {n} (v : vec n), length (v2l v) = n.\nProof. intros. apply v2l_length. Qed.\n\nLemma v2l_l2v_id : forall {n} l, length l = n -> v2l (l2v n l) = l.\nProof. intros. apply v2l_l2v_id; auto. Qed.\n\nLemma l2v_v2l_id : forall {n} (v : vec n), l2v _ (v2l v) == v.\nProof. intros. apply l2v_v2l_id. Qed.\n\nDefinition vec0 n : vec n := vec0 (A0:=0).\n\nDefinition vzero {n} (v : vec n) := vzero (A0:=0) v.\n\nDefinition vnonzero {n} (v : vec n) := vnonzero (A0:=0) v.\n\nLemma vec0_eq_mat0 : forall {n}, vec0 n == mat0 n 1.\nProof. apply vec0_eq_mat0. Qed.\n\nLemma vzero_dec : forall {n} (v : vec n), {vzero v} + {vnonzero v}.\nProof. intros. apply vzero_dec. Qed.\n\nDefinition vmap {n} (v : vec n) f : vec n := vmap v f.\n\nDefinition vmap2 {n} (v1 v2 : vec n) f : vec n := vmap2 v1 v2 f.\n\nDefinition vdot {n} (v1 v2 : vec n) :=\n  vdot v1 v2 (add0:=Rplus) (zero0:=0) (mul0:=Rmult).\n\nDefinition vlen_sqr {n} (v : vec n) : R := vdot (n:=n) v v.\n\nDefinition vadd {n} (v1 v2 : vec n) : vec n := vadd v1 v2 (add0:=Rplus).\nGlobal Infix \"+\" := vadd : vec_scope.\n\nLemma vadd_comm : forall {n} (v1 v2 : vec n), v1 + v2 == v2 + v1.\nProof. intros. apply vadd_comm. Qed.\n\nLemma vadd_assoc : forall {n} (v1 v2 v3 : vec n),\n    (v1 + v2) + v3 == v1 + (v2 + v3).\nProof. intros. apply vadd_assoc. Qed.\n\nLemma vadd_0_l : forall {n} (v : vec n), (vec0 n) + v == v.\nProof. intros. apply vadd_0_l. Qed.\n\nLemma vadd_0_r : forall {n} (v : vec n), v + (vec0 n) == v.\nProof. intros. apply vadd_0_r. Qed.\n\nDefinition vopp {n} (v : vec n) : vec n := vopp v (opp:=Ropp).\nGlobal Notation \"- v\" := (vopp v) : vec_scope.\n\nLemma vadd_vopp : forall {n} (v : vec n), v + (-v) == (vec0 n).\nProof. intros. apply vadd_opp. Qed.\n\nDefinition vsub {n} (v1 v2 : vec n) := vsub v1 v2 (add0:=Rplus) (opp:=Ropp).\nGlobal Infix \"-\" := vsub : vec_scope.\n\nDefinition vcmul {n} a (v : vec n) := vcmul a v (mul0:=Rmult).\nGlobal Infix \"c*\" := vcmul : vec_scope.\n\nDefinition vmulc {n} (v : vec n) a := vmulc v a (mul0:=Rmult).\nGlobal Infix \"*c\" := vmulc : vec_scope.\n\nLemma vmulc_eq_vcmul : forall {n} a (v : vec n), v *c a == a c* v.\nProof. intros. apply vmulc_eq_vcmul. Qed.\n\nLemma vcmul_assoc : forall {n} a b (v : vec n), (a * b)%R c* v == a c* (b c* v).\nProof. intros. apply vcmul_assoc. Qed.\n\nLemma vcmul_perm : forall {n} a b (v : vec n), a c* (b c* v) == b c* (a c* v).\nProof. intros. apply vcmul_perm. Qed.\n\nLemma vcmul_add_distr_l : forall {n} a (v1 v2 : vec n),\n    a c* (v1 + v2) == a c* v1 + a c* v2.\nProof. intros. apply vcmul_add_distr_l. Qed.\n\nLemma vcmul_add_distr_r : forall {n} a b (v : vec n),\n    (a + b) c* v == a c* v + b c* v.\nProof. intros. apply vcmul_add_distr_r. Qed.\n\nLemma vcmul_1_l : forall {n} (v : vec n), 1 c* v == v.\nProof. intros. apply vcmul_1_l. Qed.\n\nLemma vcmul_0_l : forall {n} (v : vec n), 0 c* v == vec0 n.\nProof. intros. apply vcmul_0_l. Qed.\n\nLemma vec_eq_vcmul_imply_coef_neq0 : forall {n} (v1 v2 : vec n) k,\n    vnonzero v1 -> vnonzero v2 -> v1 == k c* v2 -> k <> 0.\nProof. intros. apply vec_eq_vcmul_imply_coef_neq0 with v1 v2; auto. Qed.\n\n\n(* ======================================================================= *)\n(** ** 新增的 实数域向量理论 *)\n\n(** 向量的长度，模，范数（欧几里得范数）。存在性的构造，适合证明 *)\nDefinition vlen {n} (v : vec n) : R := sqrt (vlen_sqr v).\n\n(** 非零向量的单位化 *)\n\n(* 旧的定义，提供 v 非零的证明。修改原因：在定义中没必要提及性质 *)\nDefinition vnormalize' {n} (v : vec n) (H : vnonzero (n:=n) v) : vec n :=\n  let k := 1 / (vlen v) in\n  vcmul k v.\nDefinition vnormalize {n} (v : vec n) : vec n :=\n  let k := 1 / (vlen v) in\n  vcmul k v.\n\n(** 长度为0的向量具有唯一性 *)\n(* Lemma vec_len0_is_vec0 : forall v : vec 0, v == vec0 0. *)\nLemma vec_len0_uniq : forall v : vec 0, v == vec0 0.\nProof.\n  intros. apply meq_iff. intro. intros. easy.\nQed.\n\n(** 非零向量v的k倍等于0，则k必为0 *)\nLemma vcmul_nonzero_eq0_imply_k0 : forall {n} (v : vec n) k,\n    vnonzero v -> k c* v == vec0 n -> k = 0.\nProof.\n  intros. destruct v as [g].\n  unfold vnonzero,vzero,vec0,mat0 in *.\n  unfold veq in *. meq_simp.\n  (* 思路：特例化 H0，导出矛盾 *)\n  (* 判断 k 是否为0 *)\n  destruct (Req_EM_T k 0); auto.\n  (* 先看n是否为零，分两种情况 *)\n  destruct n.\n  - cbv in H.\n    exfalso. apply H. intros. lia.\n  - exfalso. cbv in H. cbv in H0.\n    apply H. intros. apply (H0 i j H1) in H2.\n    (* k<>0 /\\ k * (g i j) = 0 -> g i j = 0 *)\n    apply Rmult_integral in H2. destruct H2; try easy.\nQed.\n\n(** 向量平行（共线）：零向量与任何向量平行，或者非零向量是k倍的关系\n    定义：u和v中，一个是另一个的数乘。 \n    平行：parallel\n    共线：colinear\n    \n    遗留问题：主流做法是零向量与任何向量都平行、都垂直。\n    是否可以：仅考虑非零向量的平行，零向量不考虑。\n    一个原因是：考虑零向量后，平行传递性不完美了。\n *)\n\n(* 关于零向量的平行？ \n    1. https://www.zhihu.com/question/489006373\n    两个方面:\n    a. “平行”或“不平行”是对两个可以被识别的方向的比较，对于零向量，“方向”是不可\n      识别的，或说，是不确定的。从这个角度讲，“平行”这个概念不该被用到评价两个\n      零向量的关系上的。\n    b. 不过，两个零向量是“相等”的，对于向量而言，“相等”这件事包含了大小和方向\n      的相等，这么说来，说两个零向量“方向”相等，也就是“平行”或也是说得通的。\n *)\n\n(* 定义1：v1是v2的k倍，或者 v2是v1的k倍。*)\nDefinition vparallel_ver1 {n} (v1 v2 : vec n) : Prop :=\n  exists k, (v1 == k c* v2 \\/ v2 == k c* v1).\n\n(* 定义2：v1 是 0，或者 v2 是 0，或者 v1 是 v2 的 k 倍 *)\nDefinition vparallel_ver2 {n} (v1 v2 : vec n) : Prop :=\n  (vzero v1) \\/ (vzero v2) \\/ (exists k, v1 == k c* v2).\n\n(* 证明这两个定义等价 *)\nLemma vparallel_ver1_eq_ver2 : forall {n} (v1 v2 : vec n),\n    vparallel_ver1 v1 v2 <-> vparallel_ver2 v1 v2.\nProof.\n  intros. unfold vparallel_ver1, vparallel_ver2.\n  unfold vzero, vnonzero. split; intros.\n  - destruct H. destruct H.\n    + right. right. exists x. auto.\n    + destruct (veq_dec v1 (vec0 n)); auto.\n      destruct (veq_dec v2 (vec0 n)); auto.\n      right. right. exists (R1/x). rewrite H.\n      apply meq_iff.\n      intros i j Hi Hj. destruct v1 as [g1], v2 as [g2]. simpl in *.\n      field.\n      apply vec_eq_vcmul_imply_coef_neq0 in H; auto.\n  - destruct H as [H1 | [H2 | H3]].\n    + exists R0. left. cbv in *. intros. rewrite H1; auto. ring.\n    + exists R0. right. cbv in *. intros. rewrite H2;auto. ring.\n    + destruct H3. exists x. left; auto.\nQed.\n\n(** 向量平行谓词的定义 *)\nDefinition vparallel {n} (v0 v1 : vec n) : Prop :=\n  vparallel_ver2 v0 v1.\n\nNotation \"v0 // v1\" := (vparallel (v0) (v1)) (at level 70) : vec_scope.\n\n\n(** * 向量平行的性质 *)\n\n(** 向量平行是等价关系 *)\n\n(** 自反性 *)\nLemma vparallel_refl : forall {n} (v : vec n), v // v.\nProof.\n  intros. unfold vparallel,vparallel_ver2. right. right. exists 1.\n  rewrite mcmul_1_l. easy.\nQed.\n\n(** 对称性 *)\nLemma vparallel_sym : forall {n} (v0 v1 : vec n), v0 // v1 -> v1 // v0.\nProof.\n  intros. unfold vparallel,vparallel_ver2 in *.\n  assert ({vzero v0} + {vnonzero v0}). apply meq_dec.\n  assert ({vzero v1} + {vnonzero v1}). apply meq_dec.\n  destruct H0.\n  - right; left; auto.\n  - destruct H1.\n    + left; auto.\n    + destruct H; auto. destruct H; auto. destruct H.\n      right; right. exists (1/x). rewrite H.\n      rewrite <- vcmul_assoc.\n      replace (1/x * x)%R with 1.\n      rewrite vcmul_1_l; auto with vec.\n      field.\n      apply (vec_eq_vcmul_imply_coef_neq0 v0 v1); auto.\nQed.\n\n(** 传递性 *)\n(* 要求v1是非零向量。因为若v1为0，v0//v1, v1//v2, 但 v0,v2 不平行 *)\nLemma vparallel_trans : forall {n} (v0 v1 v2 : vec n), \n    vnonzero v1 -> v0 // v1 -> v1 // v2 -> v0 // v2.\nProof.\n  intros. unfold vparallel, vparallel_ver2 in *.\n  assert ({vzero v0} + {vnonzero v0}). apply meq_dec.\n  assert ({vzero v1} + {vnonzero v1}). apply meq_dec.\n  assert ({vzero v2} + {vnonzero v2}). apply meq_dec.\n  destruct H2.\n  - left; auto.\n  - destruct H4.\n    + right; left; auto.\n    + right; right.\n      destruct H3.\n      * destruct H0; try contradiction.\n      * destruct H0,H1; try contradiction.\n        destruct H0,H1; try contradiction.\n        destruct H0,H1. \n        exists (x*x0)%R. rewrite H0,H1. apply mcmul_assoc.\nQed.\n\n(** 数乘非零向量得到非零向量，则该系数必不为 0 *)\nLemma vcmul_vnonzero_neq0_imply_k_neq0 : \n  forall {n} (v : vec n) (H : vnonzero v) k, ~(k c* v == vec0 n) -> k <> 0.\nProof.\n  intros. intro. subst. rewrite vcmul_0_l in H0. destruct H0. easy.\nQed.\n\n(** 两个非零向量k倍相等，k唯一 *)\nLemma vcmul_vnonzero_eq_iff_unique_k : \n  forall {n} (v : vec n) (H : vnonzero v) k1 k2, \n    k1 c* v == k2 c* v -> k1 = k2.\nProof.\n  intros. destruct v as [g].\n  cbv in H. cbv in H0.\n  (* ∀i(f(i)=0 /\\ k1*f(i) = k2*f(i)) -> k1 = k2 *)\n  destruct (Req_EM_T k1 k2); auto.\n  destruct H. intros. (* 消去了全称量词 *)\n  specialize (H0 i j H H1).\n  ra.\nQed.\n\n(** 非零向量k倍相等于自己，则k为1 *)\nLemma vcmul_vnonzero_eq_self_iff_k1 : \n  forall {n} (v : vec n) (H : vnonzero v) k, \n    k c* v == v -> k = 1.\nProof.\n  intros. destruct v as [g]. cbv in H,H0.\n  (* 证明 k = 1，老的方法，先得到 k <> 1 的前提，然后消去全称量词 *)\n  destruct (Req_EM_T k 1); auto.\n  destruct H. intros. (* 消去了全称量词 *)\n  specialize (H0 i j H H1).\n  (* forall k, (forall x, k * x = x -> x = 0 \\/ (x <> 0 /\\ k = 1)). *)\n  ra.\nQed.\n\n(** 非零向量平行，则存在唯一比例系数k *)\nLemma vparallel_vnonezero_imply_unique_k :\n  forall {n} (v1 v2 : vec n) (H1 : vnonzero v1) (H2 : vnonzero v2),\n    v1 // v2 -> (exists ! k, v1 == k c* v2).\nProof.\n  intros.\n  destruct H; try contradiction.\n  destruct H; try contradiction.\n  destruct H. exists x. unfold unique. split; auto.\n  intros. apply vcmul_vnonzero_eq_iff_unique_k with (v:=v2); auto.\n  rewrite <- H,H0. easy.\nQed.\n\n(** 给定 向量v1，v2，\n    v1<>0 /\\ v1//v2 <=> 存在唯一实数 a 使得 v2 = a * v1 *)\nLemma vparallel_iff1 : forall {n} (v1 v2 : vec n) (H : vnonzero v1),\n    (v1 // v2) <-> (exists ! a, v2 == a c* v1).\nProof.\n  intros.\n  split; intros.\n  - destruct (veq_dec v2 (vec0 n)).\n    + exists 0. split.\n      * rewrite m. rewrite vcmul_0_l. auto with vec.\n      * intros. rewrite m in H1.\n        apply eq_sym. apply veq_sym in H1.\n        apply vcmul_nonzero_eq0_imply_k0 in H1; auto.\n    + unfold vparallel,vparallel_ver2 in *.\n      destruct H0; try easy. destruct H0; try easy.\n      destruct H0. exists (1/x). split.\n      * rewrite H0. intros i j Hi Hj. simpl. field.\n        apply vcmul_vnonzero_neq0_imply_k_neq0 with (v2); auto.\n        rewrite <- H0. auto.\n      * intros. rewrite H0 in H1.\n        rewrite <- vcmul_assoc in H1.\n        apply veq_sym in H1.\n        apply vcmul_vnonzero_eq_self_iff_k1 in H1; auto.\n        rewrite <- H1. field.\n        apply vcmul_vnonzero_neq0_imply_k_neq0 with (v2); auto.\n        rewrite <- H0. auto.\n  - destruct H0. destruct H0. apply vparallel_sym.\n    unfold vparallel, vparallel_ver2.\n    right. right. exists x. auto.\nQed.\n\n\n(* ======================================================================= *)\n(** *** 3-dim vector operations *)\n\n(** V3斜对称矩阵 *)\nDefinition skew_sym_mat_of_v3 (v : vec 3) : mat 3 3 :=\n  let '(x,y,z) := v2t_3 v in \n  mk_mat_3_3\n    0    (-z)  y\n    z     0    (-x)\n    (-y)  x     0.\n\n(** V3叉乘，向量积 *)\nDefinition vcross3 (v1 v2 : vec 3) : vec 3 := ((skew_sym_mat_of_v3 v1) * v2).\n\n(** 矩阵是否为SO3（李群，旋转群） *)\nDefinition so3 (m : mat 3 3) : Prop := \n  let so3_mul_unit : Prop := ((m ') * m) = mat1 3 in\n  let so3_det : Prop := (det3 m) = 1 in\n  so3_mul_unit /\\ so3_det.\n\n(** 计算两个向量的夹角 *)\nDefinition vangle3 (v0 v1 : vec 3) : R := \n  acos (m2t_1x1 (v0 ᵀ * v1)).\n\n(** (1,0,0) 和 (1,1,0) 的夹角是 45度，即 π/4 *)\nExample vangle3_ex1 : vangle3 (l2v 3 [1;0;0]) (l2v 3 [1;1;0]) = PI/4.\nProof.\n  compute.\n      (* Search acos. *)\nAbort. (* 暂不知哪里错了，要去查叉乘的意义 *)\n\n(** 根据两个向量来计算旋转轴 *)\nDefinition rot_axis_by_twovec (v0 v1 : vec 3) : vec 3 :=\n  let s : R := (vlen v0 * vlen v1)%R in\n  s c* (vcross3 v0 v1).\n\n(* 谓词：两向量不共线（不平行的） *)\n(* Definition v3_non_colinear (v0 v1 : V3) : Prop :=\n    v0 <> v1 /\\ v0 <> (-v1)%M.\n *)\n", "meta": {"author": "zhengpushi", "repo": "CoqMatrix", "sha": "28fa5f96e38a07659cfd373e09b0e75c24c22bfd", "save_path": "github-repos/coq/zhengpushi-CoqMatrix", "path": "github-repos/coq/zhengpushi-CoqMatrix/CoqMatrix-28fa5f96e38a07659cfd373e09b0e75c24c22bfd/Matrix_deprecated_code/RVector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912749233991, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6728244977309967}}
{"text": "Require Import XR_Rmin.\nRequire Import XR_Rle_dec.\nRequire Import XR_Rle_trans.\nRequire Import XR_Rnot_le_lt.\n\nLocal Open Scope R_scope.\n\nLemma Rle_min_compat_r : forall x y z, x <= y -> Rmin x z <= Rmin y z.\nProof.\n  intros x y z.\n  intro h.\n  unfold Rmin.\n  destruct (Rle_dec x z) as [ hminxl | hminxr ] ;\n  destruct (Rle_dec y z) as [ hminyl | hminyr ].\n  { exact h. }\n  { exact hminxl. }\n  {\n    apply Rle_trans with x.\n    {\n      left.\n      apply Rnot_le_lt.\n      exact hminxr.\n    }\n    { exact h. }\n  }\n  {\n    right.\n    reflexivity.\n  }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rle_min_compat_r.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.6728244921556051}}
{"text": "Require Import Ensembles Relations.\nSet Implicit Arguments.\nImplicit Arguments In [U].\n\nDefinition var := nat.\nInductive formula : Set :=\n| Atom : var -> formula\n| Bot : formula\n| And : formula -> formula -> formula\n| Or : formula -> formula -> formula\n| Imp : formula -> formula -> formula\n| Box : formula -> formula\n| Dia : formula -> formula.\nInfix \"'->\" := Imp (at level 70, right associativity).\nInfix \"'\\/\" := Or (at level 60).\nInfix \"'/\\\" := And (at level 50).\nNotation \"[]\" := Box.\nNotation \"<>\" := Dia.\n(* Definition Not f := f '-> Bot.  *)\n(* Definition Top := Bot '-> Bot. *)\nCoercion Atom : var >-> formula.\n\nInductive provable : Ensemble formula -> formula -> Prop :=\n| By_axiom : forall fs f, In fs f -> provable fs f\n| By_K : forall fs f g, provable fs (f '-> g '-> f)\n| By_S : forall fs f g h,\n  provable fs ((f '-> g '-> h) '-> (f '-> g) '-> (f '-> h))\n| By_proj1 : forall fs f g, provable fs (f '/\\ g '-> f)\n| By_proj2 : forall fs f g, provable fs (f '/\\ g '-> g)\n| By_conj : forall fs f g, provable fs (f '-> g '-> f '/\\ g)\n| By_in1 : forall fs f g, provable fs (f '-> f '\\/ g)\n| By_in2 : forall fs f g, provable fs (g '-> f '\\/ g)\n| By_case : forall fs f g h,\n  provable fs ((f '-> h) '-> (g '-> h) '-> (f '\\/ g '-> h))\n| By_exfalso : forall fs f, provable fs (Bot '-> f)\n| By_KBox : forall fs f g, provable fs ([](f '-> g) '-> []f '-> []g)\n| By_KDia : forall fs f g, provable fs ([](f '-> g) '-> <>f '-> <>g)\n| By_NDia : forall fs, provable fs (<>Bot '-> Bot)\n| By_MP : forall fs f g,\n  provable fs (f '-> g) -> provable fs f -> provable fs g\n| By_Nec : forall fs f, provable (Empty_set _) f -> provable fs ([] f).\n\nHint Constructors provable.\n\nModule Type KRIPKE_MODEL.\n  Parameter W : Type.\n  Parameter R Ri : relation W.\n  Axiom Ri_refl : reflexive _ Ri.\n  Axiom Ri_trans : transitive _ Ri.\n  Infix \"<=\" := Ri.\n  Parameter V : W -> var -> Prop.\n  Axiom monotone : forall x y p, V x p -> x <= y -> V y p.\nEnd KRIPKE_MODEL.\n\nModule Kripke_Semantics (K : KRIPKE_MODEL).\n  Import K.\n\n  Fixpoint satisfies x f :=\n    match f with\n      | Atom p => V x p\n      | Bot => False\n      | And f f' => satisfies x f /\\ satisfies x f'\n      | Or f f' => satisfies x f \\/ satisfies x f'\n      | Imp f f' => forall y, x <= y -> satisfies y f -> satisfies y f'\n      | Box f => forall y z, x <= y -> R y z -> satisfies z f\n      | Dia f => forall y, x <= y -> exists z, R y z /\\ satisfies z f\n    end.\n\n  Hint Resolve Ri_trans Ri_refl monotone.\n  Lemma hereditary : forall f x y, \n    satisfies x f -> x <= y -> satisfies y f.\n    induction f; simpl; intuition eauto.\n  Qed.\n\n  Hint Extern 0 =>\n    match goal with [ H : In (Empty_set _) _ |- _ ] => inversion H end.\n  Theorem soundness : forall fs f, provable fs f ->\n    forall x, (forall g, In fs g -> satisfies x g) -> satisfies x f.\n    induction 1; simpl in *; intuition; eauto using hereditary.\n    destruct (H3 y1); intuition eauto.\n\n    destruct (H1 y); intuition.\n  Qed.\n\nEnd Kripke_Semantics.\n\nLemma deduction_theorem' : forall fs fs' f g,\n  provable fs' g -> fs' = Add _ fs f -> provable fs (f '-> g).\n  induction 1; intro; subst; [| eauto ..].\n  inversion H; try inversion H0; subst; eauto.\n  Existential 1 := Bot.\n  Existential 1 := Bot.\n  Existential 1 := Bot.\nQed.\n\nLemma deduction_theorem : forall fs f g,\n  provable (Add _ fs f) g -> provable fs (f '-> g).\n  eauto using deduction_theorem'.\nQed.\n\nLemma weakening : forall fs f g, provable fs f -> provable (Add _ fs g) f.\n  induction 1; solve [repeat constructor; auto | eauto]. \nQed.\n\nHint Constructors Union Singleton.\nHint Extern 1 (provable (Add _ _ _) _) => unfold Add.\n\nLemma converse_deduction_theorem :\n  forall fs f g, provable fs (f '-> g) -> provable (Add _ fs f) g.\n  intros; apply (@By_MP _ f g); auto using weakening.\nQed.\n\nModule Canonical_Model <: KRIPKE_MODEL.\n  Definition prime fs :=\n    forall f g, provable fs (f '\\/ g) -> provable fs f \\/ provable fs g.\n  Definition consistent fs := ~provable fs Bot.\n\n  Definition W := { P : Ensemble formula * formula |\n    prime (fst P) /\\ consistent (fst P) /\\ ~provable (fst P) (<> (snd P)) }.\n\n  Definition Ri (T U : W) :=\n    forall f, provable (fst (proj1_sig T)) f -> provable (fst (proj1_sig U)) f.\n  Definition R (T U : W) :=\n    (forall f, provable (fst (proj1_sig T)) ([]f) ->\n      provable (fst (proj1_sig U)) f) /\\\n    ~provable (fst (proj1_sig U)) (snd (proj1_sig T)).\n\n  Hint Unfold R Ri Included.\n  Infix \"<=\" := Ri.\n  Lemma Ri_refl : forall T, T <= T.\n    auto.\n  Qed.\n  Lemma Ri_trans : forall T U V, T <= U -> U <= V -> T <= V.\n    auto.\n  Qed.\n  Definition V (T : W) (p : var) := provable (fst (proj1_sig T)) p.\n  Hint Unfold V.\n  Lemma monotone : forall x y p, V x p -> x <= y -> V y p.\n    intuition.\n  Qed.\nEnd Canonical_Model.\n\nModule Canonical_Model_facts.\n  Module M := Kripke_Semantics Canonical_Model.\n  \n  Import Canonical_Model M.\n\n  Definition boxinv fs f := provable fs ([] f).\n\n  Lemma boxinv_closed : forall fs f,\n    provable (boxinv fs) f ->  In (boxinv fs) f.\n    intros fs f; generalize (refl_equal (boxinv fs));\n      generalize (boxinv fs) at -1.\n    induction 2; intuition; unfold In; subst; unfold boxinv; eauto 3.\n  Qed.\n\n  Axiom prime_extension : forall fs f, ~provable fs f ->\n    exists fs', prime fs' /\\ ~provable fs' f /\\\n      forall h, provable fs h -> provable fs' h.\n  Axiom pr_decidable : forall fs f, provable fs f \\/ ~provable fs f.\n\n  Ltac assert_pt z x f :=\n    let H := fresh in\n      assert(H : prime x /\\ consistent x /\\ ~provable x (<> f))\n        by (intuition; eauto);\n        set (z := exist _ (x, f) H : W).\n\n  Hint Unfold consistent.\n\n  Lemma prime_lemma : forall fs f,\n    (forall x : W, (forall g, provable fs g -> provable (fst (proj1_sig x)) g) ->\n      provable (fst (proj1_sig x)) f) ->\n    provable fs f.\n    intros fs f H; assert (~~provable fs f);\n      [ | case (pr_decidable fs f)]; intuition.\n    destruct (prime_extension H0) as [T [? [? ?]]].\n    assert_pt y T Bot.\n    specialize (H y).\n    auto.\n    Existential 1 := Bot.\n  Qed.\n\n  Ltac destruct_iff :=\n    match goal with\n      [ H : forall _, _ <-> _ |- _] =>\n      pose proof (fun x => proj1 (H x));\n        pose proof (fun x => proj2 (H x));\n          clear H\n    end.\n\n  Lemma equivalence : forall f x, provable (fst (proj1_sig x)) f <-> satisfies x f.\n    induction f;\n      intro x; destruct x as [T [p [con mcon]]];\n        simpl in *; intuition; repeat destruct_iff.\n\n    apply H2; eauto.\n\n    apply H0; eauto.\n\n    assert (provable (fst T) f1 /\\ provable (fst T) f2) by firstorder.\n    intuition; eauto 3.\n\n    assert (provable (fst T) f1 \\/ provable (fst T) f2) by auto; intuition. \n\n    assert (provable (fst T) f1) by firstorder.\n    eauto 3.\n\n    assert (provable (fst T) f2) by firstorder.\n    eauto.\n\n    eauto.\n\n    apply deduction_theorem.\n    apply prime_lemma.\n    auto 8 using weakening.\n\n    destruct H1.\n    eauto.\n\n    assert (In (boxinv (fst T)) f); [| eauto].\n    apply boxinv_closed.\n    apply prime_lemma.\n    intros.\n    assert_pt x' (fst T) Bot.\n    specialize (H x').\n    apply H1; apply H; intuition.\n\n    unfold R.\n    intuition.\n\n    destruct x; simpl in *; intuition.\n\n    destruct y as [[T' g] [? [? mcon']]]; simpl in *.\n    destruct (@prime_extension (Add _ (boxinv T') f) g); intuition.\n    apply mcon'.\n    assert (provable (boxinv T') (f '-> g))\n      by auto using deduction_theorem.\n    assert (provable T' ([] (f '-> g))) by\n      (specialize (boxinv_closed H4); auto).\n    eauto 4.\n\n    assert_pt x1 x0 Bot.\n    exists x1; intuition.\n    unfold R; intuition.\n    apply H1; auto.\n\n    destruct T as [x' ?]; simpl in *.\n    assert (~~provable x' (<> f)); intuition.\n    assert_pt z x' f.\n    destruct (H z).\n    auto.\n\n    intuition.\n    destruct H5.\n    subst; simpl in *; auto.\n\n    case (pr_decidable x' (<> f)); intuition.\n\n    Existential 1 := Bot.\n    Existential 1 := Bot.\n  Qed.\n\n  Hint Resolve (fun f x => proj1 (equivalence f x)).\n  Hint Resolve (fun f x => proj2 (equivalence f x)).\n\n  Theorem completeness : forall fs f,\n    (forall T, (forall g, In fs g -> satisfies T g) -> satisfies T f) ->\n    provable fs f.\n    auto 7 using prime_lemma.\n  Qed.\nEnd Canonical_Model_facts.\n", "meta": {"author": "kozima", "repo": "completenessproofs", "sha": "fe99b9f41e7dfdba14fabbe7849f0edada605872", "save_path": "github-repos/coq/kozima-completenessproofs", "path": "github-repos/coq/kozima-completenessproofs/completenessproofs-fe99b9f41e7dfdba14fabbe7849f0edada605872/im_Kripke.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694177, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.6728244908325605}}
{"text": "Require Import List.\nRequire Import Classical.\n\nSection election_spec.\n  (** For this section, we hold the set of candidates abstract,\n      and define ballots and some properties of ballots irrespective\n      of how candidates are defined.\n   *)\n  Variable candidate:Set.\n\n  (** Voters cast votes, which consist of a sequence of rank positions.\n      For each rank position, a voter selects 0 or more candidates.\n      A properly cast vote will have (1) no more than one candidate selected\n      at each rank, (2) each candidate selected at most once, and (3) no\n      candidate selected at a rank position later than a rank position with\n      zero candidates.  However, voters do not always follow the rules;\n      voters may select more than one candidate at a given rank, may select\n      the same candidate more than once, or may skip rankings.\n\n      The vote tabulation system must handle these cases.\n   *)\n  Definition rankSelection := list candidate.\n  Definition ballot := list rankSelection.\n  Definition election := list ballot.\n  Definition contestants := list candidate.\n  \n  Section ballot_properties.\n    (**  At any given round of a tabulation, some collection of candidates\n         have been eliminated.  The following definitions are all defined\n         with respect to the candidates that have been eliminated thus far.\n         The abstract 'eliminated' predicate indicates which candidates are\n         already eliminated.\n      *)\n\n    Variable eliminated : candidate -> Prop.\n\n    (**  One condition for a ballot to be exhausted is that it\n         all the candidates it selects have already been eliminated.\n         This vacuously covers the case of an empty ballot.\n     *)  \n    Definition no_viable_candidates (b:ballot) :=\n      forall rank, In rank b ->\n        forall candidate, In candidate rank ->\n          eliminated candidate.\n    \n    (**  From a given ballot, find the first rank selection\n         (if it exists) which contains at least one\n         continuing candidate.\n      *)\n    Definition overvote (r : rankSelection) := \n       exists c1 c2, In c1 r /\\ In c2 r /\\ c1 <> c2.\n\n    Inductive next_ranking : ballot -> rankSelection -> Prop :=\n    | next_ranking_eliminated : forall b r r', \n        Forall eliminated r' ->\n        ~overvote r' ->\n        next_ranking b r ->\n        next_ranking (r' :: b) r\n    | next_ranking_valid : forall b r c,\n        In c r  ->\n        (overvote r \\/ ~eliminated c) ->\n        next_ranking (r :: b) r.\n\n    Definition properly_selects r c :=\n      Forall (eq c) r /\\ In c r /\\ ~eliminated c.\n\n    Definition does_not_select r :=\n      r = nil \\/ (exists c, Forall (eq c) r /\\ In c r /\\ eliminated c).\n\n    Lemma not_overvote_cons :\n      forall h t,\n        ~overvote (h :: t) ->\n        Forall (eq h) t /\\ ~overvote t.\n    Proof.\n      induction t; intros.\n      - split. \n        + constructor.\n        + intro. unfold overvote in H0.\n          destruct H0. destruct H0.\n          intuition.\n      -split.\n        + constructor.\n          destruct (classic (h = a)).\n          * auto.\n          * exfalso.\n            apply H.\n            unfold overvote.\n            exists h. exists a. intuition.\n          * unfold overvote in H.\n            apply IHt.\n            intro.\n            apply H.\n            clear H.\n            destruct H0.\n            destruct H.\n            exists x. exists x0.\n            simpl in *. intuition.\n        + intuition.\n          apply H; clear H.\n          unfold overvote in H0.\n          destruct H0.\n          destruct H.\n          destruct H.\n          destruct H0.\n          unfold overvote.\n          exists x. exists x0.\n          intuition.\n    Qed.\n\n    Lemma not_overvote_all_same :\n      forall r c,\n        ~overvote r ->\n        In c r ->\n        Forall (eq c) r.\n    Proof.\n      induction r; intros.\n      - inversion H0.\n      - apply not_overvote_cons in H.\n        intuition. destruct H0. subst.\n        rewrite Forall_forall. intros. simpl in *.\n        intuition. assert (In x r) by auto.\n        eapply IHr in H0; eauto.\n        rewrite Forall_forall in *.\n        specialize (H0 x).\n        specialize (H1 x). intuition.\n        constructor; intuition.\n        rewrite Forall_forall in H1. specialize (H1 c).\n        intuition. \n    Qed.\n\n    Lemma ranking_cases : forall r,\n    overvote r \\/ (exists c, properly_selects r c) \\/ does_not_select r.\n    intros.\n    destruct r. \n    - right. right. left. auto.\n    - destruct (classic (overvote (c :: r))).\n      + auto.\n      + right. destruct (classic (eliminated c)).\n        * right. right. exists c. simpl. intuition.\n          apply not_overvote_all_same; simpl; auto.\n        * left. exists c. repeat split; auto.\n          apply not_overvote_all_same; simpl; auto.\n          simpl; auto.\n    Qed.\n\n    Lemma next_ranking_not_not_selects : forall b r,\n        next_ranking b r ->\n        ~does_not_select r.\n    Proof.\n      intros. \n      induction H. \n      - auto.\n      - intro.\n        unfold does_not_select in *.\n        destruct H1. subst. elim H.\n        destruct H1.\n        destruct H1.\n        rewrite Forall_forall in H1.\n        apply H1 in H. subst. intuition.\n        unfold overvote in *.\n        destruct H2. destruct H0. intuition. apply H5. transitivity c; eauto. \n        symmetry. eauto.\n    Qed.\n\n    Lemma next_ranking_spec : forall b r,\n        next_ranking b r -> \n        overvote r \\/ (exists c, properly_selects r c).\n    Proof.\n      intros.\n      destruct (ranking_cases r); intuition.\n      apply next_ranking_not_not_selects in H.\n      intuition.\n    Qed. \n      \n    (**  TODO: Do we need a notion of overvote for a ballot any more?\n         A ballot is an overvote if its next ranking contains\n         two distinct candidates.\n      *)\n   (* Definition overvote (b:ballot) : Prop :=\n      exists r, next_ranking b r /\\\n         exists c1 c2, In c1 r /\\ In c2 r /\\ c1 <> c2.*)\n\n    (**  A ballot is exhausted if it selects no vaiable candidates\n         or is an overvote \n      *)\n\n    Definition exhausted_ballot (b:ballot) :=\n      (~ exists r, next_ranking b r ) \\/ \n      (exists r, next_ranking b r /\\ overvote r). \n    \n    Ltac inv H := inversion H; subst; clear H.\n    Lemma next_ranking_unique : forall b r1 r2,\n        next_ranking b r1 ->\n        next_ranking b r2 ->\n        r1= r2.\n    Proof. \n      intros.\n      induction b.\n      inversion H.\n      inv H; inv H0; try rewrite Forall_forall in *; firstorder.\n    Qed. \n\n    Lemma exhausted_ballot_next_ranking_iff : forall (b : ballot),\n          exhausted_ballot b <-> forall r, next_ranking b r -> overvote r.\n    Proof. \n      intros.\n      split; intros.\n      - unfold exhausted_ballot in H.\n        intuition. exfalso.\n        apply H1. exists r. auto.\n        destruct H1. destruct H. eapply next_ranking_unique in H0; eauto.\n        subst; auto.\n      - unfold exhausted_ballot.\n        destruct (classic (exists r, next_ranking b r)).\n        destruct H0. right.\n        exists x. auto.\n        left. auto.\n    Qed.\n          \n\n    Definition continuing_ballot (b:ballot) :=\n      ~exhausted_ballot b.\n \n    (**  A ballot selects a particular candidate iff it is a\n         continuing ballot and its next ranking contains that\n         candidate.\n      *)\n    Definition selected_candidate (b:ballot) (c:candidate) :=\n      continuing_ballot b /\\\n      exists r, next_ranking b r /\\ In c r.\n\n\n    (** If a candidate receives a majority of the first choices, that\ncandidate shall be declared elected.*)\n\n    Inductive first_choices (c : candidate) : election ->  nat -> Prop :=\n    | first_choices_nil : first_choices c nil 0\n    | first_choices_selected : forall h t n', selected_candidate h c ->\n                                              first_choices c t n' ->\n                                              first_choices c (h::t) (S n')\n    | first_choices_not_selected : forall h t n, ~selected_candidate h c ->\n                                                 first_choices c t n ->\n                                                 first_choices c (h::t) n.\n\n\n    Lemma sf_first_choices_unique : forall e c n1 n2,\n        first_choices c e n1 ->\n        first_choices c e n2 ->\n        n1 = n2.\n    Proof.\n      induction e.\n      * intros. inversion H. inversion H0. auto.\n      * intros.\n        inversion H; clear H; subst;\n        inversion H0; clear H0; subst; try contradiction.\n        f_equal; eauto.\n        eauto.\n    Qed.\n\n    Lemma sf_first_choices_total : forall e c, exists n,\n        first_choices c e n.\n    Proof.\n      induction e.\n      * intros. exists 0. apply first_choices_nil.\n      * intros.\n        destruct (IHe c) as [n ?].\n        destruct (classic (selected_candidate a c)).\n        exists (S n). apply first_choices_selected; auto.\n        exists n. apply first_choices_not_selected; auto.\n    Qed.\n\n   \n    Inductive total_selected : election -> nat -> Prop :=\n    | total_nil : total_selected nil 0\n    | total_continuing : forall b e' n, continuing_ballot b ->\n                                        total_selected e' n ->\n                                        total_selected (b :: e') (S n)\n    | total_exhausted : forall b e' n, exhausted_ballot b ->\n                                       total_selected e' n ->\n                                       total_selected (b :: e') (n).\n\n    Lemma total_selected_total : forall e,\n        exists n, total_selected e n.\n    Proof. \n      induction e; intros.\n      - exists 0; constructor.\n      - destruct IHe.\n        destruct (classic (exhausted_ballot a)).\n        + exists x; constructor; auto. \n        + exists (S x). apply total_continuing; auto.\n    Qed.\n\n    Definition majority (e : election) (winner : candidate) :=\n      forall total_votes winner_votes, \n        total_selected e total_votes ->\n        first_choices winner e winner_votes ->\n        (winner_votes * 2) > total_votes.\n\n    (** If no candidate receives a\nmajority, the candidate who received the fewest first choices shall be\neliminated and each vote cast for that candidate shall be transferred to\nthe next ranked candidate on that voter's ballot. *)\n\n    Definition participates (c:candidate) (e:election) :=\n      exists b, In b e /\\ exists r, In r b /\\ In c r.\n\n    Definition viable_candidate (e:election) (c:candidate) :=\n      ~eliminated c /\\ participates c e.\n\n    Definition is_loser (e:election) (loser:candidate) :=\n      viable_candidate e loser /\\\n      forall c' n m,\n        viable_candidate e c' ->\n        first_choices loser e n ->\n        first_choices c' e m ->\n        n <= m.\n\n    Definition no_majority (e : election) :=\n      ~(exists c, majority e c).\n\n\n    (**  Every ballot selects at most one candidate.\n     *)\n    Lemma selected_candidate_unique (b:ballot) (c1 c2:candidate) :\n      selected_candidate b c1 ->\n      selected_candidate b c2 ->\n      c1 = c2.\n    Proof.\n      unfold selected_candidate.\n      intros [Hb [r1 [??]]].\n      intros [_ [r2 [??]]].\n      assert (r1 = r2) by (apply (next_ranking_unique b); auto).\n      subst r2.\n      destruct (classic (c1=c2)); auto.\n      elim Hb. red. right. firstorder.\n    Qed.\n\n    (**\nWhat to do if a ballot has multiple choices for a rank, but all\nhave already been eliminated?  Shall the ballot be deemed exhausted,\nor will we continue to consider later choices?\n\nE.g.,\n\n     A\n     B, C\n     D\n\nSuppose both B and C were eliminated in earlier rounds, but\nA is not eliminated.  We should count this ballot as a vote\nfor A.  Suppose, in a subsequent round, A is also eliminated.\nNow, should this ballot be considered an overvote and removed;\nor should it count as a vote for D?  The statue language is\nunclear.\n\nHowever, actual practice seems to be that a ballot is decared an overvote\nas soon as the first ranking with more than one selection becomse relevant;\ni.e., when all properly-selected candidates above it have been eliminated.\nIn other words, the ballot is considered to be truncated at the position\nof the first ranking with more than one selection.\n\nThe formal specification above follows suit, and counts this situation\nas an overvote as soon as A is eliminated.\n*)\n\n    (**  Whenever a ballot selects a candidate, that candidate is not eliminated.\n      *)\n    Lemma selected_candidate_not_eliminated (b:ballot) :\n      forall c, selected_candidate b c -> ~eliminated c.\n    Proof.\n      induction b.\n      unfold selected_candidate. intros c [Hc [r [??]]]. inv H.\n      unfold selected_candidate. intros c [Hc [r [??]]]. inv H.\n      * apply IHb. split; eauto.\n        red; intro.\n        apply Hc.\n        destruct H.\n        elim H; eauto.\n        destruct H as [r' [??]].\n        right. exists r'. split; auto.\n        apply next_ranking_eliminated; auto.\n      * intro Helim.\n        elim Hc. red.\n        right. exists r. split; auto.\n        eapply next_ranking_valid; eauto.\n        destruct H5; auto.\n        red. exists c. exists c0. intuition.\n        subst c0. contradiction.\n    Qed.\n\n    (* The next ranking for a ballot is in the ballot. *)\n    Lemma next_ranking_in_ballot (b:ballot) :\n      forall r, next_ranking b r -> In r b.\n    Proof.\n      intros r H. induction H; intuition; eauto.\n    Qed.\n\n  End ballot_properties.\n\n  Definition update_eliminated (eliminated : candidate -> Prop) (c : candidate) :=\n    fun cs => eliminated cs \\/ c = cs.\n  \n  Inductive winner : \n    election -> (candidate -> Prop) -> candidate -> Prop :=\n  | winner_now : forall election winning_candidate eliminated, \n      majority eliminated election winning_candidate ->\n      winner election eliminated winning_candidate\n  | winner_elimination : forall election winning_candidate eliminated loser,\n      no_majority eliminated election ->\n      is_loser eliminated election loser ->\n      let eliminated' := update_eliminated eliminated loser in\n      winner election eliminated' winning_candidate ->\n      winner election eliminated winning_candidate.      \n\nEnd election_spec. \n\n(**\nSAN FRANCISCO CHARTER\n\n[Obtained from-- http://www.amlegal.com/library/ca/sfrancisco.shtml on\nJune 13, 2015.]\n\nARTICLE XIII: ELECTIONS\n\nSEC. 13.102. INSTANT RUNOFF ELECTIONS.\n\n(a) For the purposes of this section: (1) a candidate shall be deemed\n\"continuing\" if the candidate has not been eliminated; (2) a ballot\nshall be deemed \"continuing\" if it is not exhausted; and (3) a ballot\nshall be deemed \"exhausted,\" and not counted in further stages of the\ntabulation, if all of the choices have been eliminated or there are no\nmore choices indicated on the ballot. If a ranked-choice ballot gives\nequal rank to two or more candidates, the ballot shall be declared\nexhausted when such multiple rankings are reached. If a voter casts a\nranked-choice ballot but skips a rank, the voter's vote shall be\ntransferred to that voter's next ranked choice.\n\n(b) The Mayor, Sheriff, District Attorney, City Attorney, Treasurer,\nAssessor-Recorder, Public Defender, and members of the Board of\nSupervisors shall be elected using a ranked-choice, or \"instant runoff,\"\nballot. The ballot shall allow voters to rank a number of choices in\norder of preference equal to the total number of candidates for each\noffice; provided, however, if the voting system, vote tabulation system\nor similar or related equipment used by the City and County cannot\nfeasibly accommodate choices equal to the total number of candidates\nrunning for each office, then the Director of Elections may limit the\nnumber of choices a voter may rank to no fewer than three. The ballot\nshall in no way interfere with a voter's ability to cast a vote for a\nwrite-in candidate.\n\n(c) If a candidate receives a majority of the first choices, that\ncandidate shall be declared elected. If no candidate receives a\nmajority, the candidate who received the fewest first choices shall be\neliminated and each vote cast for that candidate shall be transferred to\nthe next ranked candidate on that voter's ballot. If, after this\ntransfer of votes, any candidate has a majority of the votes from the\ncontinuing ballots, that candidate shall be declared elected.\n\n(d) If no candidate receives a majority of votes from the continuing\nballots after a candidate has been eliminated and his or her votes have\nbeen transferred to the next-ranked candidate, the continuing candidate\nwith the fewest votes from the continuing ballots shall be eliminated.\nAll votes cast for that candidate shall be transferred to the next-\nranked continuing candidate on each voter's ballot. This process of\neliminating candidates and transferring their votes to the next-ranked\ncontinuing candidates shall be repeated until a candidate receives a\nmajority of the votes from the continuing ballots.\n\n(e) If the total number of votes of the two or more candidates credited\nwith the lowest number of votes is less than the number of votes\ncredited to the candidate with the next highest number of votes, those\ncandidates with the lowest number of votes shall be eliminated\nsimultaneously and their votes transferred to the next-ranked continuing\ncandidate on each ballot in a single counting operation.\n\n(f) A tie between two or more candidates shall be resolved in accordance\nwith State law.\n\n(g) The Department of Elections shall conduct a voter education campaign\nto familiarize voters with the ranked-choice or, \"instant runoff,\"\nmethod of voting.\n\n(h) Any voting system, vote tabulation system, or similar or related\nequipment acquired by the City and County shall have the capability to\naccommodate this system of ranked-choice, or \"instant runoff,\"\nballoting.\n\n(i) Ranked choice, or \"instant runoff,\" balloting shall be used for the\ngeneral municipal election in November 2002 and all subsequent\nelections. If the Director of Elections certifies to the Board of\nSupervisors and the Mayor no later than July 1, 2002 that the Department\nwill not be ready to implement ranked-choice balloting in November 2002,\nthen the City shall begin using ranked-choice, or \"instant runoff,\"\nballoting at the November 2003 general municipal election.\n\nIf ranked-choice, or \"instant runoff,\" balloting is not used in November\nof 2002, and no candidate for any elective office of the City and\nCounty, except the Board of Education and the Governing Board of the\nCommunity College District, receives a majority of the votes cast at an\nelection for such office, the two candidates receiving the most votes\nshall qualify to have their names placed on the ballot for a runoff\nelection held on the second Tuesday in December of 2002.\n *)\n", "meta": {"author": "FreeAndFair", "repo": "formal-rcv", "sha": "d97e525ad7724384f891ab53d235c95892e59594", "save_path": "github-repos/coq/FreeAndFair-formal-rcv", "path": "github-repos/coq/FreeAndFair-formal-rcv/formal-rcv-d97e525ad7724384f891ab53d235c95892e59594/src/sf_spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.6728244804383952}}
{"text": "From mathcomp Require Import ssreflect.\nFrom Category.Base Require Import Logic Category Functor NatTran.\n\nSet Universe Polymorphism.\n\nProgram Definition ConstFunctor {D : Category} (C : Category) (a : Obj D) : Functor C D :=\n  {|\n    FApp := fun X => a;\n    FAppH := fun X Y => fun f => \\Id a\n  |}.\nNext Obligation.\nProof.\n  rewrite Hom_IdL.\n  reflexivity.\nQed.\n\nProgram Definition IdFunctor (C : Category) : Functor C C :=\n  {|\n    FApp := fun X => X;\n    FAppH := fun X Y => fun f => f\n  |}.\n\nProgram Definition Functor_Comp {C1 C2 C3 : Category} (F : Functor C2 C3) (G : Functor C1 C2) : Functor C1 C3 :=\n  {|\n    FApp := fun (X : Obj C1) => FApp F (FApp G X : Obj _);\n    FAppH := fun (X Y : Obj C1) => fun (f : Hom X Y) => FAppH F (FAppH G f)\n  |}.\nNext Obligation.\n  rewrite FAppH_comp_eq.\n  rewrite FAppH_comp_eq.\n  reflexivity.\nQed.\nNext Obligation.\n  rewrite Functor_id_eq.\n  rewrite Functor_id_eq.\n  reflexivity.\nQed.\n\nLemma Functor_Comp_assoc : forall {C1 C2 C3 C4 : Category} (F1 : Functor C3 C4) (F2 : Functor C2 C3) (F3 : Functor C1 C2),\n    Functor_Comp (Functor_Comp F1 F2) F3 = Functor_Comp F1 (Functor_Comp F2 F3).\nProof.\n  move => C1 C2 C3 C4 F1 F2 F3.\n  apply: ToFunctorEq => X Y f /=.\n  exact: Hom_eq'_refl.\nQed.\n\nLemma Functor_Comp_IdL :\n  forall {C D : Category} (F : Functor C D),\n    Functor_Comp (IdFunctor D) F = F.\nProof.\n  move => C D F.\n  apply: ToFunctorEq => X Y f /=.\n  exact: Hom_eq'_refl.\nQed.\n\nLemma Functor_Comp_IdR :\n  forall {C D : Category} (F : Functor C D),\n    Functor_Comp F (IdFunctor C) = F.\nProof.\n  move => C D F.\n  apply: ToFunctorEq => X Y f /=.\n  exact: Hom_eq'_refl.\nQed.\n\n", "meta": {"author": "k27c8ff627uxz", "repo": "category_theory", "sha": "d5568b2ba04120a4f0e5bc7f2d61297c3cf42b9e", "save_path": "github-repos/coq/k27c8ff627uxz-category_theory", "path": "github-repos/coq/k27c8ff627uxz-category_theory/category_theory-d5568b2ba04120a4f0e5bc7f2d61297c3cf42b9e/src/Instances/Univ/FunctorComp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.6728244783122217}}
{"text": "Require Import eq.\nRequire Import utils.\nRequire Import injective.\n\n(* defines a map v -> v which permutes x and y                      *)\nDefinition permute (v:Type) (p:Eq v) (x y:v) (u:v) : v :=\n    match p u x with\n    | left  _       => y        (* if u = x return y    *)\n    | right _       =>\n        match p u y with\n        | left  _   => x        (* if u = y return x    *)\n        | right _   => u        (* otherwise return u   *)\n        end\n     end.\n\nArguments permute {v} _ _ _ _.\n\nLemma permute_x : forall (v:Type) (p:Eq v) (x y:v), permute p x y x = y.\nProof.\n    intros v p x y. unfold permute. destruct (p x x) as [H|H].\n    - reflexivity.\n    - exfalso. apply H. reflexivity.\nQed.\n\nLemma permute_y : forall (v:Type) (p: Eq v) (x y:v), permute p x y y = x.\nProof.\n    intros v p x y. unfold permute.\n    destruct (p y x) as [H0|H0].\n    - assumption.\n    - destruct (p y y) as [H1|H1].\n        + reflexivity.\n        + exfalso. apply H1. reflexivity.\nQed.\n\nLemma permute_not_xy : forall (v:Type) (p:Eq v) (x y z:v),\n    z <> x -> z <> y -> permute p x y z = z.\nProof.\n    intros v p x y z Hx Hy. unfold permute. \n    destruct (p z x) as [H0|H0].\n    - exfalso. apply Hx. assumption.\n    - destruct (p z y) as [H1|H1].\n        + exfalso. apply Hy. assumption.\n        + reflexivity.\nQed.\n\nLemma permute_inv : forall (v:Type) (p:Eq v) (x y:v), permute p x x y = y.\nProof.\n    intros v p x y. unfold permute. destruct (p y x) as [H|H]; subst; \n    reflexivity.\nQed.\n\n\nLemma permute_injective : forall (v:Type) (p:Eq v) (x y:v),\n    injective (permute p x y).\nProof.\n    intros v p x y s t. unfold permute.\n    destruct    (p s x) as [Hsx|Hsx], \n                (p t x) as [Htx|Htx]; subst; intros H'.\n    - reflexivity.\n    - destruct (p t y) as [Hty|Hty]; subst.\n        + reflexivity.\n        + exfalso. apply Hty. reflexivity.\n    - destruct (p s y) as [Hsy|Hsy]; subst.\n        + reflexivity.\n        + exfalso. apply Hsy. reflexivity.\n    - destruct (p s y) as [Hsy|Hsy], (p t y) as [Hty|Hty]; subst.\n        + reflexivity.\n        + exfalso. apply Htx. reflexivity.\n        + exfalso. apply Hsx. reflexivity.\n        + reflexivity.\nQed.\n\nLemma permute_comp : forall (v w:Type) (p:Eq v) (q:Eq w) (x y u:v) (f:v -> w),\n    injective f -> f (permute p x y u) = permute q (f x) (f y) (f u).\nProof.\n    intros v w p q x y u f I. unfold permute.\n    destruct    (p u x) as [Hux|Hux], \n                (p u y) as [Huy|Huy]; subst.\n    - destruct (q (f y) (f y)) as [Fyy|Fyy]; reflexivity.\n    - destruct (q (f x) (f x)) as [Fxx|Fxx].\n        + reflexivity.\n        + destruct (q (f x) (f y)) as [Fxy|Fxy].\n            { rewrite Fxy. reflexivity. }\n            { exfalso. apply Fxx. reflexivity. }\n    - destruct (q (f y) (f x)) as [Fyx|Fyx].\n        + rewrite Fyx. reflexivity.\n        + destruct (q (f y) (f y)) as [Fyy|Fyy].\n            { reflexivity. }\n            { exfalso. apply Fyy. reflexivity. }\n    - destruct (q (f u) (f x)) as [Fux|Fux].\n        + exfalso. apply Hux. apply I. assumption.\n        + destruct (q (f u) (f y)) as [Fuy|Fuy].\n            { exfalso. apply Huy. apply I. assumption. }\n            { reflexivity. }\nQed.\n\nLemma permute_commute : forall (v:Type) (p:Eq v) (x y u:v),\n    permute p x y u = permute p y x u.\nProof.\n    intros v p x y u. unfold permute.\n    destruct (p u x) as [Hx|Hx], (p u y) as [Hy|Hy]; \n    try (reflexivity).\n    rewrite <- Hx, <- Hy. reflexivity.\nQed.\n\n\nLemma permute_involution : forall (v:Type) (p:Eq v) (x y z:v),\n    permute p x y (permute p x y z) = z.\nProof.\n    intros v p x y z. unfold permute at 2.\n    destruct (p z x) as [Hzx|Hzx], (p z y) as [Hzy|Hzy]; subst.\n    - apply permute_x. \n    - apply permute_y.\n    - apply permute_x.\n    - apply permute_not_xy; assumption.\nQed.\n\n\nLemma permute_thrice : forall (v:Type) (p:Eq v) (x y z u:v),\n    x <> z  ->\n    y <> z  ->\n    permute p x y (permute p y z (permute p x y u)) = permute p x z u.\nProof.  \n    intros v p x y z u Hxz Hyz.\n    unfold permute at 3. destruct (p u x) as [Hux|Hux].\n    - rewrite permute_x, Hux, permute_x. apply permute_not_xy;\n      apply neq_sym; assumption.\n    - destruct (p u y) as [Huy|Huy]; subst.\n        + destruct (p x y) as [Hxy|Hxy]; subst.\n            { apply permute_inv. }\n            { rewrite (permute_not_xy v p y z x); try (assumption).\n              rewrite permute_x. symmetry. apply permute_not_xy; assumption.\n            }\n        + destruct (p x y) as [Hxy|Hxy]; subst.\n            { apply permute_inv. }\n            { destruct (p u z) as [Huz|Huz]; subst.\n                { rewrite permute_y, permute_y, permute_y. reflexivity. }\n                { rewrite (permute_not_xy v p y z u); try (assumption).\n                  rewrite (permute_not_xy v p x z u); try (assumption).\n                  apply permute_not_xy; assumption.\n                }\n            }\nQed.\n                        \n\n(*\n    intros v p x y z u Hxy Hxz Hyz.\n    unfold permute at 3. destruct (p u x) as [Hux|Hux].\n    - rewrite permute_x. rewrite Hux. rewrite permute_x. apply permute_not_xy.\n        + apply neq_sym. assumption.\n        + apply neq_sym. assumption.\n    - destruct (p u y) as [Huy|Huy] eqn:Puy.\n        + rewrite (permute_not_xy v p y z x); try (assumption).\n            { rewrite permute_x, Huy. symmetry. apply permute_not_xy.\n                { apply neq_sym. assumption. }\n                { assumption. }\n            }\n        + unfold permute at 2. rewrite Puy. destruct (p u z) as [Huz|Huz]. \n            { rewrite permute_y, Huz, permute_y. reflexivity. }\n            { rewrite permute_not_xy; try (assumption).\n              rewrite permute_not_xy; try (assumption). reflexivity.\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/lam/permute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.6727544228236687}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\n(**************************************************************************)\n(* This file deals with divisibility for natural numbers.                 *)\n(* It contains the definitions of:                                        *)\n(*      edivn m d   == the pair composed of the quotient and remainder    *)\n(*                     of the euclidian division of m by d                *)\n(*          m %/ d  == quotient of m by d                                 *)\n(*          m %% d  == remainder of m dy d                                *)\n(*  m = n %[mod d]  <=> m equals n modulo d                               *)\n(*  m == n %[mod d] <=> m equals n modulo d (boolean version)             *)\n(*  m <> n %[mod d] <=> m differs from n modulo d                         *)\n(*  m != n %[mod d] <=> m differs from n modulo d (boolean version)       *)\n(*           d %| m <=> d divides m                                       *)\n(*         gcdn m n == the GCD of m and n                                 *)\n(*        egcdn m n == the extended GCD of m and n                        *)\n(*         lcmn m n == the LCM of m and n                                 *)\n(*      coprime m n <=> m and n are coprime                               *)\n(*  chinese m n r s == witness of the chinese remainder theorem           *)\n(**************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(** Euclidian division *)\n\nDefinition edivn_rec d := fix loop (m q : nat) {struct m} :=\n  if m - d is m'.+1 then loop m' q.+1 else (q, m).\n\nDefinition edivn m d := if d > 0 then edivn_rec d.-1 m 0 else (0, m).\n\nCoInductive edivn_spec (m d : nat) : nat * nat -> Type :=\n  EdivnSpec q r of m = q * d + r & (d > 0) ==> (r < d) : edivn_spec m d (q, r).\n\nLemma edivnP : forall m d, edivn_spec m d (edivn m d).\nProof.\nrewrite /edivn => m [|d] //=; rewrite -{1}[m]/(0 * d.+1 + m).\nelim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //=; rewrite ltnS => le_mn.\nrewrite subn_if_gt; case: ltnP => [// | le_dm].\nrewrite -{1}(subnKC le_dm) -addSn addnA -mulSnr; apply: IHn.\napply: leq_trans le_mn; exact: leq_subr.\nQed.\n\nLemma edivn_eq : forall d q r, r < d -> edivn (q * d + r) d = (q, r).\nProof.\nmove=> d q r lt_rd; have d_gt0: 0 < d by exact: leq_trans lt_rd.\ncase: edivnP lt_rd => q' r'; rewrite d_gt0 /=.\nwlog: q q' r r' / q <= q' by case (ltnP q q'); last symmetry; eauto.\nrewrite leq_eqVlt; case: eqP => [-> _|_] /=; first by move/addnI->.\nrewrite -(leq_pmul2r d_gt0); move/leq_add=> Hqr Eqr _; move/Hqr {Hqr}.\nby rewrite addnS ltnNge mulSn -addnA Eqr addnCA addnA leq_addr.\nQed.\n\nDefinition divn m d := (edivn m d).1.\n\nNotation \"m %/ d\" := (divn m d) (at level 40, no associativity) : nat_scope.\n\n(* We redefine modn so that it is structurally decreasing. *)\n\nDefinition modn_rec d := fix loop (m : nat) :=\n  if m - d is m'.+1 then loop m' else m.\n\nDefinition modn m d := if d > 0 then modn_rec d.-1 m else m.\n\nNotation \"m %% d\" := (modn m d) (at level 40, no associativity) : nat_scope.\nNotation \"m = n %[mod d ]\" := (m %% d = n %% d)\n  (at level 70, n at next level,\n   format \"'[hv ' m '/'  =  n '/'  %[mod  d ] ']'\") : nat_scope.\nNotation \"m == n %[mod d ]\" := (m %% d == n %% d)\n  (at level 70, n at next level,\n   format \"'[hv ' m '/'  ==  n '/'  %[mod  d ] ']'\") : nat_scope.\nNotation \"m <> n %[mod d ]\" := (m %% d <> n %% d)\n  (at level 70, n at next level,\n   format \"'[hv ' m '/'  <>  n '/'  %[mod  d ] ']'\") : nat_scope.\nNotation \"m != n %[mod d ]\" := (m %% d != n %% d)\n  (at level 70, n at next level,\n   format \"'[hv ' m '/'  !=  n '/'  %[mod  d ] ']'\") : nat_scope.\n\nLemma modn_def : forall m d, m %% d = (edivn m d).2.\nProof.\nrewrite /modn /edivn => m [|d] //=.\nelim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //=.\nrewrite ltnS !subn_if_gt; case: (d <= m) => // le_mn.\nby apply: IHn; apply: leq_trans le_mn; exact: leq_subr.\nQed.\n\nLemma edivn_def : forall m d, edivn m d = (m %/ d, m %% d).\nProof. by move=> m d; rewrite /divn modn_def; case edivn. Qed.\n\nLemma divn_eq : forall m d, m = m %/ d * d + m %% d.\nProof. by move=> m d; rewrite /divn modn_def; case edivnP. Qed.\n\nLemma div0n : forall d, 0 %/ d = 0. Proof. by case. Qed.\nLemma divn0 : forall m, m %/ 0 = 0. Proof.  by []. Qed.\nLemma mod0n :  forall d, 0 %% d = 0. Proof. by case. Qed.\nLemma modn0 :  forall m, m %% 0 = m. Proof. by []. Qed.\n\nLemma divn_small : forall m d, m < d -> m %/ d = 0.\nProof. by move=> m d lt_md; rewrite /divn (edivn_eq 0). Qed.\n\nLemma divn_addl_mul : forall q m d, 0 < d -> (q * d + m) %/ d = q + m %/ d.\nProof.\nmove=> q m d d_gt0; rewrite {1}(divn_eq m d) addnA -muln_addl.\nby rewrite /divn edivn_eq // modn_def; case: edivnP; rewrite d_gt0.\nQed.\n\nLemma mulnK : forall m d, 0 < d -> m * d %/ d = m.\nProof.\nby move=> m d d_gt0; rewrite -[m * d]addn0 divn_addl_mul // div0n addn0.\nQed.\n\nLemma mulKn : forall m d, 0 < d -> d * m %/ d = m.\nProof. by move=> *; rewrite mulnC mulnK. Qed.\n\nLemma modn1 : forall m, m %% 1 = 0.\nProof. by move=> m; rewrite modn_def; case: edivnP => ? []. Qed.\n\nLemma divn1 : forall m, m %/ 1 = m.\nProof. by move=> m; rewrite {2}(@divn_eq m 1) // modn1 addn0 muln1. Qed.\n\nLemma divnn : forall d, d %/ d = (0 < d).\nProof. by case=> // d; rewrite -{1}[d.+1]muln1 mulKn. Qed.\n\nLemma divn_pmul2l : forall p m d, p > 0 -> p * m %/ (p * d) = m %/ d.\nProof.\nmove=> p m d p_gt0; case: (posnP d) => [-> | d_gt0]; first by rewrite muln0.\nrewrite {2}/divn; case: edivnP; rewrite d_gt0 /= => q r ->{m} lt_rd.\nrewrite muln_addr mulnCA divn_addl_mul; last by rewrite muln_gt0 p_gt0.\nby rewrite addnC divn_small // ltn_pmul2l.\nQed.\nImplicit Arguments divn_pmul2l [p m d].\n\nLemma divn_pmul2r : forall p m d, p > 0 -> m * p %/ (d * p) = m %/ d.\nProof. by move=> p m d p_gt0; rewrite -!(mulnC p) divn_pmul2l. Qed.\nImplicit Arguments divn_pmul2r [p m d].\n\nLemma ltn_mod : forall m d, (m %% d < d) = (0 < d).\nProof. by move=> m [|d] //; rewrite modn_def; case: edivnP. Qed.\n\nLemma ltn_pmod : forall m d, 0 < d -> m %% d < d.\nProof. by move=> m d; rewrite ltn_mod. Qed.\n\nLemma leq_floor : forall m d, m %/ d * d <= m.\nProof. by move=> m d; rewrite {2}(divn_eq m d) leq_addr. Qed.\n\nLemma leq_mod : forall m d, m %% d  <= m.\nProof. by move=> m d; rewrite {2}(divn_eq m d) leq_addl. Qed.\n\nLemma leq_div : forall m d, m %/ d <= m.\nProof. move=> m [|d] //; exact: leq_trans (leq_pmulr _ _) (leq_floor _ _). Qed.\n\nLemma ltn_ceil : forall m d, 0 < d -> m < (m %/ d).+1 * d.\nProof.\nby move=> m d ? /=; rewrite {1}(divn_eq m d) -addnS mulSnr leq_add2l ltn_mod.\nQed.\n\nLemma ltn_divl : forall m n d, d > 0 -> (m %/ d < n) = (m < n * d).\nProof.\nmove=> m n d d_gt0; apply/idP/idP.\n  rewrite -(leq_pmul2r d_gt0); exact: leq_trans (ltn_ceil _ _).\nrewrite !ltnNge -(@leq_pmul2r d n) //; apply: contra => le_nd_floor.\nexact: leq_trans le_nd_floor (leq_floor _ _).\nQed.\n\nLemma leq_divr : forall m n d, d > 0 -> (m <= n %/ d) = (m * d <= n).\nProof. by move=> m n d d_gt0; rewrite leqNgt ltn_divl // -leqNgt. Qed.\n\nLemma ltn_Pdiv : forall m d, 1 < d -> 0 < m -> m %/ d < m.\nProof. by move=> m d d_gt1 m_gt0; rewrite ltn_divl ?ltn_Pmulr // ltnW. Qed.\n\nLemma divn_gt0 : forall d m, 0 < d -> (0 < m %/ d) = (d <= m).\nProof. by move=> d m d_gt0; rewrite leq_divr ?mul1n. Qed.\n\nLemma divn_divl : forall m n p, m %/ n %/ p = m %/ (n * p).\nProof.\nmove=> m [|n] [|p]; rewrite ?muln0 ?div0n //.\nrewrite {1}(divn_eq m (n.+1 * p.+1)) mulnA mulnAC !divn_addl_mul //.\nby rewrite addnC divn_small // ltn_divl // mulnC ltn_mod.\nQed.\n\nLemma divnAC : forall m n p, m %/ n %/ p =  m %/ p %/ n.\nProof. by move=> m n p; rewrite !divn_divl mulnC. Qed.\n\nLemma modn_small : forall m d, m < d -> m %% d = m.\nProof. by move=> m d lt_md; rewrite {2}(divn_eq m d) divn_small. Qed.\n\nLemma modn_mod : forall m d, m %% d = m %[mod d].\nProof. by move=> m [|d] //; apply: modn_small; rewrite ltn_mod. Qed.\n\nLemma modn_addl_mul : forall p m d, p * d + m = m %[mod d].\nProof.\nmove=> p m d; case: (posnP d) => [-> | d_gt0]; first by rewrite muln0.\nby rewrite {1}(divn_eq m d) addnA -muln_addl modn_def edivn_eq // ltn_mod.\nQed.\n\nLemma modn_pmul2l : forall p m d, 0 < p -> p * m %% (p * d) = p * (m %% d).\nProof.\nmove=> p m d p_gt0; apply: (@addnI (p * (m %/ d * d))).\nby rewrite -muln_addr -divn_eq mulnCA -(divn_pmul2l p_gt0) -divn_eq.\nQed.\nImplicit Arguments modn_pmul2l [p m d].\n\nLemma modn_addl : forall m d, d + m = m %[mod d].\nProof. by move=> m d; rewrite -{1}[d]mul1n modn_addl_mul. Qed.\n\nLemma modn_addr : forall m d, m + d = m %[mod d].\nProof. by move=> *; rewrite addnC modn_addl. Qed.\n\nLemma modnn : forall d, d %% d = 0.\nProof. by move=> d; rewrite -{1}[d]addn0 modn_addl mod0n. Qed.\n\nLemma modn_mull : forall p d, p * d %% d = 0.\nProof. by move=> p d; rewrite -[p * d]addn0 modn_addl_mul mod0n. Qed.\n\nLemma modn_mulr : forall p d, d * p %% d = 0.\nProof. by move=> p d; rewrite mulnC modn_mull. Qed.\n\nLemma modn_addml : forall m n d, m %% d + n = m + n %[mod d].\nProof. by move=> m n d; rewrite {2}(divn_eq m d) -addnA modn_addl_mul. Qed.\n\nLemma modn_addmr : forall m n d, m + n %% d = m + n %[mod d].\nProof. by move=> m n d; rewrite !(addnC m) modn_addml. Qed.\n\nLemma modn_add2m : forall m n d, m %% d  + n %% d = m + n %[mod d].\nProof. by move=> m n d; rewrite modn_addml modn_addmr. Qed.\n\nLemma modn_add2l : forall p m n d,\n  (p + m == p + n %[mod d]) = (m == n %[mod d]).\nProof.\nmove=> p m n [|d]; first by rewrite !modn0 eqn_addl.\napply/eqP/eqP=> eq_mn; last by rewrite -modn_addmr eq_mn modn_addmr.\nrewrite -(modn_addl_mul p m) -(modn_addl_mul p n) !mulnSr -!addnA.\nby rewrite -modn_addmr eq_mn modn_addmr.\nQed.\n\nLemma modn_add2r : forall p m n d,\n  (m + p == n + p %[mod d]) = (m == n %[mod d]).\nProof. by move=> p *; rewrite -!(addnC p) modn_add2l. Qed.\n\nLemma modn_mulml : forall m n d, m %% d * n = m * n %[mod d].\nProof.\nby move=> m n d; rewrite {2}(divn_eq m d) muln_addl mulnAC modn_addl_mul.\nQed.\n\nLemma modn_mulmr : forall m n d, m * (n %% d) = m * n %[mod d].\nProof. by move=> m n d; rewrite !(mulnC m) modn_mulml. Qed.\n\nLemma modn_mul2m : forall m n d, m %% d * (n %% d) = m * n %[mod d].\nProof. by move=> m n d; rewrite modn_mulml modn_mulmr. Qed.\n\nLemma modn2 : forall m, m %% 2 = odd m.\nProof. by elim=> //= m IHm; rewrite -addn1 -modn_addml IHm; case odd. Qed.\n\nLemma divn2 : forall m, m %/ 2 = m./2.\nProof.\nby move=> m; rewrite {2}(divn_eq m 2) modn2 muln2 addnC half_bit_double.\nQed.\n\nLemma odd_mod : forall m d, odd d = false -> odd (m %% d) = odd m.\nProof.\nby move=> m d d_even; rewrite {2}(divn_eq m d) odd_add odd_mul d_even andbF.\nQed.\n\nLemma modn_exp : forall m n a, (a %% n) ^ m = a ^ m %[mod n].\nProof.\nby elim=> // m Hrec n a; rewrite !expnS -modn_mulmr Hrec modn_mulml modn_mulmr.\nQed.\n\n(** Divisibility **)\n\nDefinition dvdn d m := m %% d == 0.\n\nNotation \"m %| d\" := (dvdn m d) (at level 70, no associativity) : nat_scope.\n\nDefinition multn := [rel m d | d %| m].\n\nLemma dvdn2 : forall n, (2 %| n) = ~~ odd n.\nProof. by move=> n; rewrite /dvdn modn2; case (odd n). Qed.\n\nLemma dvdnP : forall d m, reflect (exists k, m = k * d) (d %| m).\nProof.\nmove=> d m; apply: (iffP eqP) => [Hm | [k ->]]; last by rewrite modn_mull.\nby exists (m %/ d); rewrite {1}(divn_eq m d) Hm addn0.\nQed.\nImplicit Arguments dvdnP [d m].\nPrenex Implicits dvdnP.\n\nLemma dvdn0 : forall d, d %| 0.\nProof. by case. Qed.\n\nLemma dvd0n : forall n, (0 %| n) = (n == 0).\nProof. by case. Qed.\n\nLemma dvdn1 : forall d, (d %| 1) = (d == 1).\nProof. by case=> [|[|n]] //; rewrite /dvdn modn_small. Qed.\n\nLemma dvd1n : forall m, 1 %| m.\nProof. by move=> m; rewrite /dvdn modn1. Qed.\n\nLemma dvdn_gt0 : forall d m, m > 0 -> d %| m -> d > 0.\nProof. by do 2!case. Qed.\n\nLemma dvdnn : forall m, m %| m.\nProof. by move=> m; rewrite /dvdn modnn. Qed.\n\nLemma dvdn_mull : forall d m n, d %| n -> d %| m * n.\nProof. by move=> d m n; case/dvdnP=> n' ->; rewrite /dvdn mulnA modn_mull. Qed.\n\nLemma dvdn_mulr : forall d m n, d %| m -> d %| m * n.\nProof. by move=> d m n d_m; rewrite mulnC dvdn_mull. Qed.\n\nHint Resolve dvdn0 dvd1n dvdnn dvdn_mull dvdn_mulr.\n\nLemma dvdn_mul : forall d1 d2 m1 m2, d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2.\nProof.\nmove=> d1 d2 m1 m2; case/dvdnP=> q1 ->; case/dvdnP=> q2 ->.\nby rewrite mulnCA -mulnA 2?dvdn_mull.\nQed.\n\nLemma dvdn_trans : forall n d m, d %| n -> n %| m -> d %| m.\nProof. move=> n d m Hn; move/dvdnP => [n1 ->]; exact: dvdn_mull. Qed.\n\nLemma dvdn_eq : forall d m, (d %| m) = (m %/ d * d == m).\nProof.\nmove=> d m; apply/eqP/eqP=> [modm0 | <-]; last exact: modn_mull.\nby rewrite {2}(divn_eq m d) modm0 addn0.\nQed.\n\nLemma divnK : forall d m, d %| m -> m %/ d * d = m.\nProof. by move=> m d; rewrite dvdn_eq; move/eqP. Qed.\n\nLemma leq_divl : forall d m n, d %| m -> (m %/ d <= n) = (m <= n * d).\nProof. by case=> [[]//|d] m n dv_d_m; rewrite -(@leq_pmul2r d.+1) ?divnK. Qed.\n\nLemma ltn_divr : forall d m n, d %| m -> (n < m %/ d) = (n * d < m).\nProof. by move=> d m n dv_d_m; rewrite !ltnNge leq_divl. Qed.\n\nLemma eqn_div : forall d m n, d > 0 -> d %| m -> (n == m %/ d) = (n * d == m).\nProof. by move=> d m n d_gt0 dv_d_m; rewrite -(eqn_pmul2r d_gt0) divnK. Qed.\n\nLemma eqn_mul : forall d m n, d > 0 -> d %| m -> (m == n * d) = (m %/ d == n).\nProof. by move=> d m n d_gt0 dv_d_m; rewrite eq_sym -eqn_div // eq_sym. Qed.\n\nLemma divn_mulAC : forall d m n, d %| m -> m %/ d * n = m * n %/ d.\nProof.\ncase=> [[]//|d] m n dv_d_m; apply/eqP.\nby rewrite eqn_div ?dvdn_mulr // mulnAC divnK.\nQed.\n\nLemma divn_mulA : forall d m n, d %| n -> m * (n %/ d) = m * n %/ d.\nProof. by move=> d m n dv_d_m; rewrite !(mulnC m) divn_mulAC. Qed.\n\nLemma divn_mulCA : forall d m n,\n  d %| m -> d %| n -> m * (n %/ d) = n * (m %/ d).\nProof. by move=> d m n dv_d_m dv_d_n; rewrite mulnC divn_mulAC ?divn_mulA. Qed.\n\nLemma divn_divr : forall m n p, p %| n -> m %/ (n %/ p) = m * p %/ n.\nProof. by move=> m n [|p] dv_n; rewrite -{2}(divnK dv_n) // divn_pmul2r. Qed.\n\nLemma modn_dvdm : forall m n d, d %| m -> n %% m = n %[mod d].\nProof.\nmove=> m n d; case/dvdnP=> q def_m.\nby rewrite {2}(divn_eq n m) {3}def_m mulnA modn_addl_mul.\nQed.\n\nLemma dvdn_leq : forall d m, 0 < m -> d %| m -> d <= m.\nProof.\nby move=> d m m_gt0; case/dvdnP=> [[|k] Dm]; rewrite Dm // leq_addr in m_gt0 *.\nQed.\n\nLemma gtnNdvd : forall n d, 0 < n -> n < d -> (d %| n) = false.\nProof. by move=> n d n_gt0 ltnd; rewrite /dvdn eqn0Ngt modn_small ?n_gt0. Qed.\n\nLemma eqn_dvd : forall m n, (m == n) = (m %| n) && (n %| m).\nProof.\ncase=> [|m] [|n] //; apply/idP/andP; first by move/eqP->; auto.\nrewrite eqn_leq => [[Hmn Hnm]]; apply/andP; have:= dvdn_leq; auto.\nQed.\n\nLemma dvdn_pmul2l : forall p d m, 0 < p -> (p * d %| p * m) = (d %| m).\nProof. by case=> // p d m _; rewrite /dvdn modn_pmul2l // muln_eq0. Qed.\nImplicit Arguments dvdn_pmul2l [p m d].\n\nLemma dvdn_pmul2r : forall p d m, 0 < p -> (d * p %| m * p) = (d %| m).\nProof. by move=> n d m Hn; rewrite -!(mulnC n) dvdn_pmul2l. Qed.\nImplicit Arguments dvdn_pmul2r [p m d].\n\nLemma dvdn_exp2l : forall p m n, m <= n -> p ^ m %| p ^ n.\nProof. by move=> p m n; move/subnK <-; rewrite expn_add dvdn_mull. Qed.\n\nLemma dvdn_Pexp2l : forall p m n, p > 1 -> (p ^ m %| p ^ n) = (m <= n).\nProof.\nmove=> p m n p_gt1; case: leqP => [|gt_n_m]; first exact: dvdn_exp2l.\nby rewrite gtnNdvd ?ltn_exp2l ?expn_gt0 // ltnW.\nQed.\n\nLemma dvdn_exp2r : forall m n k, m %| n -> m ^ k %| n ^ k.\nProof. by move=> m n k; case/dvdnP=> q ->; rewrite expn_mull dvdn_mull. Qed.\n\nLemma dvdn_addr : forall m d n, d %| m -> (d %| m + n) = (d %| n).\nProof. by move=> n d m; move/dvdnP=> [k ->]; rewrite /dvdn modn_addl_mul. Qed.\n\nLemma dvdn_addl : forall n d m, d %| n -> (d %| m + n) = (d %| m).\nProof. by move=> n d m; rewrite addnC; exact: dvdn_addr. Qed.\n\nLemma dvdn_add : forall d m n, d %| m -> d %| n -> d %| m + n.\nProof. by move=> n d m; move/dvdn_addr->. Qed.\n\nLemma dvdn_add_eq : forall d m n, d %| m + n -> (d %| m) = (d %| n).\nProof. by move=> *; apply/idP/idP; [move/dvdn_addr <-| move/dvdn_addl <-]. Qed.\n\nLemma dvdn_subr : forall d m n, n <= m -> d %| m -> (d %| m - n) = (d %| n).\nProof. by move=> d m n le_n_m dv_d_m; apply: dvdn_add_eq; rewrite subnK. Qed.\n\nLemma dvdn_subl : forall d m n, n <= m -> d %| n -> (d %| m - n) = (d %| m).\nProof. by move=> d m n le_n_m dv_d_m; rewrite -(dvdn_addl _ dv_d_m) subnK. Qed.\n\nLemma dvdn_sub : forall d m n, d %|m -> d %| n -> d %| m - n.\nProof.\nmove=> d n m; case: (leqP m n) => Hm; first by move/dvdn_subr <-.\nby rewrite (eqnP (ltnW Hm)) dvdn0.\nQed.\n\nLemma dvdn_exp : forall k d m, 0 < k -> d %| m -> d %| (m ^ k).\nProof. by case=> // *; rewrite expnS dvdn_mulr. Qed.\n\nHint Resolve dvdn_add dvdn_sub dvdn_exp.\n\nLemma eqn_mod_dvd : forall d m n, n <= m -> (m == n %[mod d]) = (d %| m - n).\nProof.\nby move=> d m n le_mn; rewrite -{1}[n]add0n -{1}(subnK le_mn) modn_add2r mod0n.\nQed.\n\nLemma divn_addl : forall m n d, d %| m -> (m + n) %/ d = m %/ d + n %/ d.\nProof. by move=> m n [//|d] dv_m; rewrite -{1}(divnK dv_m) divn_addl_mul. Qed.\n\nLemma divn_addr : forall m n d, d %| n -> (m + n) %/ d = m %/ d + n %/ d.\nProof. by move=> m n d dv_n; rewrite addnC divn_addl // addnC. Qed.\n\n(***********************************************************************)\n(*   A function that computes the gcd of 2 numbers                     *)\n(***********************************************************************)\n\nFixpoint gcdn_rec (m n : nat) {struct m} :=\n  let n' := n %% m in if n' is 0 then m else\n  if m - n'.-1 is m'.+1 then gcdn_rec (m' %% n') n' else n'.\n\nDefinition gcdn := nosimpl gcdn_rec.\n\nLemma gcdnE : forall m n, gcdn m n = if m == 0 then n else gcdn (n %% m) m.\nProof.\nrewrite /gcdn => m; elim: m {-2}m (leqnn m) => [|s IHs] [|m] le_ms [|n] //=.\ncase def_n': (_ %% _) => // [n'].\nhave{def_n'} lt_n'm: n' < m by rewrite -def_n' -ltnS ltn_pmod.\nrewrite {}IHs ?(leq_trans lt_n'm) // subn_if_gt ltnW //=; congr gcdn_rec.\nby rewrite -{2}(subnK (ltnW lt_n'm)) -addnS modn_addr.\nQed.\n\nLemma gcdnn : idempotent gcdn.\nProof. by case=> // n; rewrite gcdnE modnn. Qed.\n\nLemma gcdnC : commutative gcdn.\nProof.\nmove=> m n; wlog lt_nm: m n / n < m.\n  by case: (ltngtP n m) => [||->]; [|symmetry|rewrite gcdnn]; auto.\nby rewrite gcdnE -{1}(ltn_predK lt_nm) modn_small.\nQed.\n\nLemma gcd0n : left_id 0 gcdn. Proof. by case. Qed.\nLemma gcdn0 : right_id 0 gcdn. Proof. by case. Qed.\n\nLemma gcd1n : left_zero 1 gcdn.\nProof. by move=> n; rewrite gcdnE modn1. Qed.\n\nLemma gcdn1 : right_zero 1 gcdn.\nProof. by move=> n; rewrite gcdnC gcd1n. Qed.\n\nLemma dvdn_gcdr : forall m n, gcdn m n %| n.\nProof.\nmove=> m; elim: m {-2}m (leqnn m) => [|s IHs] [|m] le_ms [|n] //.\nrewrite gcdnE; case def_n': (_ %% _) => [|n']; first by rewrite /dvdn def_n'.\nhave lt_n's: n' < s by rewrite -ltnS (leq_trans _ le_ms) // -def_n' ltn_pmod.\nrewrite /= (divn_eq n.+1 m.+1) def_n' dvdn_addr ?dvdn_mull //; last exact: IHs.\nby rewrite gcdnE /= IHs // (leq_trans _ lt_n's) // ltnW // ltn_pmod.\nQed.\n\nLemma dvdn_gcdl : forall m n, gcdn m n %| m.\nProof. by move=> m n; rewrite gcdnC dvdn_gcdr. Qed.\n\nLemma gcdn_gt0 : forall m n, (0 < gcdn m n) = (0 < m) || (0 < n).\nProof.\nmove=> [|m] [|n] //; apply: (@dvdn_gt0 _ m.+1) => //; exact: dvdn_gcdl.\nQed.\n\nLemma gcdn_addl_mul : forall k m n, gcdn m (k * m + n) = gcdn m n.\nProof. by move=> k m n; rewrite !(gcdnE m) modn_addl_mul mulnC; case: m. Qed.\n\nLemma gcdn_addl : forall m n, gcdn m (m + n) = gcdn m n.\nProof. by move => m n; rewrite -{2}(mul1n m) gcdn_addl_mul. Qed.\n\nLemma gcdn_addr : forall m n, gcdn m (n + m) = gcdn m n.\nProof. by move=> m n; rewrite addnC gcdn_addl. Qed.\n\nLemma gcdn_mull : forall n m, gcdn n (m * n) = n.\nProof. by move=> n m; rewrite gcdnE modn_mull gcd0n; case defn:n=> /=. Qed.\n\nLemma gcdn_mulr : forall n m, gcdn n (n * m) = n.\nProof. by move=> n m; rewrite mulnC gcdn_mull. Qed.\n\n(* Extended gcd, which computes Bezout coefficients. *)\n\nFixpoint bezout_rec (km kn : nat) (qs : seq nat) {struct qs} :=\n  if qs is q :: qs' then bezout_rec kn (NatTrec.add_mul q kn km) qs'\n  else (km, kn).\n\nFixpoint egcdn_rec (m n s : nat) (qs : seq nat) {struct s} :=\n  if s is s'.+1 then\n    let: (q, r) := edivn m n in\n    if r > 0 then egcdn_rec n r s' (q :: qs) else\n    if odd (size qs) then qs else q.-1 :: qs\n  else [::0].\n\nDefinition egcdn m n := bezout_rec 0 1 (egcdn_rec m n n [::]).\n\nCoInductive egcdn_spec (m n : nat) : nat * nat -> Type :=\n  EgcdnSpec km kn of km * m = kn * n + gcdn m n & kn * gcdn m n < m :\n    egcdn_spec m n (km, kn).\n\nLemma egcd0n : forall n, egcdn 0 n = (1, 0).\nProof. by case. Qed.\n\nLemma egcdnP : forall m n, m > 0 -> egcdn_spec m n (egcdn m n).\nProof.\nrewrite /egcdn => m0 n0; have: (n0, m0) = bezout_rec n0 m0 [::] by [].\ncase: (posnP n0) => [-> /=|]; first by split; rewrite // mul1n gcdn0.\nelim: {1 4}n0 {1 3 5 7}n0 {-1 4}m0 [::] (ltnSn n0) => [[]//|s IHs] n m qs /=.\nmove=> le_ns n_gt0 def_mn0 m_gt0.\ncase: edivnP => q r def_m; rewrite n_gt0 /= => lt_rn.\ncase: posnP => [r0 {s le_ns IHs lt_rn}|r_gt0]; last first.\n  by apply: IHs => //=; [rewrite (leq_trans lt_rn) | rewrite natTrecE -def_m].\nrewrite {r}r0 addn0 in def_m; set b := odd _; pose d := gcdn m n.\npose km := ~~ b : nat; pose kn := if b then 1 else q.-1.\nrewrite (_ : bezout_rec _ _ _ = bezout_rec km kn qs); last first.\n  by rewrite /kn /km; case b => //=; rewrite natTrecE addn0 muln1.\nhave def_d: d = n by rewrite /d def_m gcdnC gcdnE modn_mull gcd0n -[n]prednK.\nhave: km * m + 2 * b * d = kn * n + d.\n  rewrite {}/kn {}/km def_m def_d -mulSnr; case: b; rewrite //= addn0 mul1n.\n  by rewrite prednK //; apply: dvdn_gt0 m_gt0 _; rewrite def_m dvdn_mulr.\nhave{def_m}: kn * d <= m.\n  have q_gt0 : 0 < q by rewrite def_m muln_gt0 n_gt0 ?andbT in m_gt0.\n  by rewrite /kn; case b; rewrite def_d def_m leq_pmul2r // leq_pred.\nhave{def_d}: km * d <= n by rewrite -[n]mul1n def_d leq_pmul2r // leq_b1.\nmove: km {q}kn m_gt0 n_gt0 def_mn0; rewrite {}/d {}/b.\nelim: qs m n => [|q qs IHq] n r kn kr n_gt0 r_gt0 /=.\n  case=> -> -> {m0 n0}; rewrite !addn0 => le_kn_r _ def_d; split=> //.\n  have d_gt0: 0 < gcdn n r by rewrite gcdn_gt0 n_gt0.\n  have: 0 < kn * n by rewrite def_d addn_gt0 d_gt0 orbT.\n  rewrite muln_gt0 n_gt0 andbT; move/ltn_pmul2l <-.\n  by rewrite def_d -addn1 leq_add // mulnCA leq_mul2l le_kn_r orbT.\nrewrite !natTrecE; set m:= _ + r; set km := _ * _ + kn; pose d := gcdn m n.\nhave ->: gcdn n r = d by rewrite [d]gcdnC gcdn_addl_mul.\nhave m_gt0: 0 < m by rewrite addn_gt0 r_gt0 orbT.\nhave d_gt0: 0 < d by rewrite gcdn_gt0 m_gt0.\nmove/IHq=> {IHq} IHq le_kn_r le_kr_n def_d; apply: IHq => //; rewrite -/d.\n  by rewrite muln_addl leq_add // -mulnA leq_mul2l le_kr_n orbT.\napply: (@addIn d); rewrite -!addnA addnn addnCA muln_addr -addnA addnCA.\nrewrite /km muln_addl mulnCA mulnA -addnA; congr (_ + _).\nby rewrite -def_d addnC -addnA -muln_addl -muln_addr addn_negb -mul2n.\nQed.\n\nLemma bezoutl : forall m n, m > 0 -> {a | a < m & m %| gcdn m n + a * n}.\nProof.\nmove=> m n m_gt0; case: (egcdnP n m_gt0) => km kn def_d lt_kn_m.\nexists kn; last by rewrite addnC -def_d dvdn_mull.\napply: leq_ltn_trans lt_kn_m.\nby rewrite -{1}[kn]muln1 leq_mul2l gcdn_gt0 m_gt0 orbT.\nQed.\n\nLemma bezoutr : forall m n, n > 0 -> {a | a < n & n %| gcdn m n + a * m}.\nProof. by move=> m n; rewrite gcdnC; exact: bezoutl. Qed.\n\n(* Back to the gcd. *)\n\nLemma dvdn_gcd : forall p m n, p %| gcdn m n = (p %| m) && (p %| n).\nProof.\nmove=> p m n; apply/idP/andP=> [dv_pmn | [dv_pm dv_pn]].\n  by rewrite ?(dvdn_trans dv_pmn) ?dvdn_gcdl ?dvdn_gcdr.\ncase (posnP n) => [->|n_gt0]; first by rewrite gcdn0.\ncase: (bezoutr m n_gt0) => // km _; move/(dvdn_trans dv_pn).\nby rewrite dvdn_addl // dvdn_mull.\nQed.\n\nLemma gcdn_mul2l : forall p m n, gcdn (p * m) (p * n) = p * gcdn m n.\nProof.\nmove=> p m n; case: (posnP p) => [-> //| p_gt0].\nelim: {m}m.+1 {-2}m n (ltnSn m) => // s IHs m n; rewrite ltnS => le_ms.\nrewrite gcdnE (gcdnE m) muln_eq0 modn_pmul2l // eqn0Ngt p_gt0.\ncase: posnP => // m_gt0; apply: IHs; apply: leq_trans le_ms.\nexact: ltn_pmod.\nQed.\n\nLemma gcdn_modr : forall m n, gcdn m (n %% m) = gcdn m n.\nProof. by move=> m n; rewrite {2}(divn_eq n m) gcdn_addl_mul. Qed.\n\nLemma gcdn_modl : forall m n, gcdn (m %% n) n = gcdn m n.\nProof. by move=> m n; rewrite !(gcdnC _ n) gcdn_modr. Qed.\n\nLemma gcdnAC : right_commutative gcdn.\nProof.\nsuff dvd: forall m n p, gcdn (gcdn m n) p %| gcdn (gcdn m p) n.\n  by move=> m n p; apply/eqP; rewrite eqn_dvd !dvd.\nmove=> m n p; rewrite !dvdn_gcd dvdn_gcdr.\nby rewrite !(dvdn_trans (dvdn_gcdl _ p)) ?dvdn_gcdl ?dvdn_gcdr.\nQed.\n\nLemma gcdnA : associative gcdn.\nProof. by move=> m n p; rewrite !(gcdnC m) gcdnAC. Qed.\n\nLemma gcdnCA : left_commutative gcdn.\nProof. by move=> m n p; rewrite !gcdnA (gcdnC m). Qed.\n\nLemma muln_gcdl : left_distributive muln gcdn.\nProof. by move=> m n p; rewrite -!(mulnC p) gcdn_mul2l. Qed.\n\nLemma muln_gcdr : right_distributive muln gcdn.\nProof. by move=> m n p; rewrite gcdn_mul2l. Qed.\n\nLemma gcdn_def : forall d m n,\n    d %| m -> d %| n -> (forall d', d' %| m -> d' %| n -> d' %| d)\n  -> gcdn m n = d.\nProof.\nmove=> d m n dv_dm dv_dn gdv_d; apply/eqP.\nby rewrite eqn_dvd dvdn_gcd dv_dm dv_dn gdv_d ?dvdn_gcdl ?dvdn_gcdr.\nQed.\n\nLemma gcdn_divnC : forall n m, n * (m %/ gcdn n m)  = m * (n %/ gcdn n m).\nProof. by move=> n m; rewrite divn_mulCA ?dvdn_gcdl ?dvdn_gcdr. Qed.\n\n(* We derive the lcm directly. *)\n\nDefinition lcmn m n := m * n %/ gcdn m n.\n\nLemma lcmnC : commutative lcmn.\nProof. by move=> m n; rewrite /lcmn mulnC gcdnC. Qed.\n\nLemma lcm0n : left_zero 0 lcmn. Proof. move=> n; exact: div0n. Qed.\nLemma lcmn0 : right_zero 0 lcmn. Proof. by move=> n; rewrite lcmnC lcm0n. Qed.\n\nLemma lcm1n : left_id 1 lcmn.\nProof. by move=> n; rewrite /lcmn gcd1n mul1n divn1. Qed.\n\nLemma lcmn1 : right_id 1 lcmn.\nProof. by move=> n; rewrite lcmnC lcm1n. Qed.\n\nLemma muln_lcm_gcd : forall m n, lcmn m n * gcdn m n = m * n.\nProof. by move=> m n; apply/eqP; rewrite divnK ?dvdn_mull ?dvdn_gcdr. Qed.\n\nLemma lcmn_gt0 : forall m n, (0 < lcmn m n) = (0 < m) && (0 < n).\nProof. by move=> m n; rewrite -muln_gt0 ltn_divr ?dvdn_mull ?dvdn_gcdr. Qed.\n\nLemma muln_lcmr : right_distributive muln lcmn.\nProof.\ncase=> // m n p; rewrite /lcmn -muln_gcdr -!mulnA divn_pmul2l // mulnCA.\nby rewrite divn_mulA ?dvdn_mull ?dvdn_gcdr.\nQed.\n\nLemma muln_lcml : left_distributive muln lcmn.\nProof. by move=> m n p; rewrite -!(mulnC p) muln_lcmr. Qed.\n\nLemma lcmnA : associative lcmn.\nProof.\nmove=> m n p; rewrite {1 3}/lcmn mulnC !divn_mulAC ?dvdn_mull ?dvdn_gcdr //.\nrewrite !divn_divl ?dvdn_mulr ?dvdn_gcdl // mulnC mulnA !muln_gcdr.\nby rewrite ![_ * lcmn _ _]mulnC !muln_lcm_gcd !muln_gcdl -!(mulnC m) gcdnA.\nQed.\n\nLemma dvdn_lcml : forall d1 d2, d1 %| lcmn d1 d2.\nProof. by move=> d1 d2; rewrite /lcmn -divn_mulA ?dvdn_gcdr ?dvdn_mulr. Qed.\n\nLemma dvdn_lcmr : forall d1 d2, d2 %| lcmn d1 d2.\nProof. by move=> d1 d2; rewrite lcmnC dvdn_lcml. Qed.\n\nLemma dvdn_lcm : forall d1 d2 m, lcmn d1 d2 %| m = (d1 %| m) && (d2 %| m).\nProof.\ncase=> [|d1] [|d2] m; try by case: m => [|m]; rewrite ?lcmn0 ?andbF.\nrewrite -(@dvdn_pmul2r (gcdn d1.+1 d2.+1)) ?gcdn_gt0 // muln_lcm_gcd.\nby rewrite muln_gcdr dvdn_gcd {1}mulnC andbC !dvdn_pmul2r.\nQed.\n\n(* Coprime factors *)\n\nDefinition coprime m n := gcdn m n == 1.\n\nLemma coprime1n : forall n, coprime 1 n.\nProof. by move=> n; rewrite /coprime gcd1n. Qed.\n\nLemma coprimen1 : forall n, coprime n 1.\nProof. by move=> n; rewrite /coprime gcdn1. Qed.\n\nLemma coprime_sym : forall m n, coprime m n = coprime n m.\nProof. by move => m n; rewrite /coprime gcdnC. Qed.\n\nLemma coprime_modl : forall m n, coprime (m %% n) n = coprime m n.\nProof. by move=> m n; rewrite /coprime gcdn_modl. Qed.\n\nLemma coprime_modr : forall m n, coprime m (n %% m) = coprime m n.\nProof. by move=> m n; rewrite /coprime gcdn_modr. Qed.\n\nLemma coprimeP : forall n m, n > 0 ->\n  reflect (exists u, u.1 * n - u.2 * m = 1) (coprime n m).\nProof.\nmove=> n m n_gt0; apply: (iffP eqP) => [<-| [[kn km] /= kn_km_1]].\n  by have [kn km kg _] := egcdnP m n_gt0; exists (kn, km); rewrite kg addKn.\napply gcdn_def; rewrite ?dvd1n // => d dv_d_n dv_d_m.\nby rewrite -kn_km_1 dvdn_subr ?dvdn_mull // ltnW // -subn_gt0 kn_km_1.\nQed.\n\nLemma modn_coprime : forall k n, O < k ->\n  (exists u, (k * u) %% n = 1%N) -> coprime k n.\nProof.\nmove=> k n Hpos [u Hu]; apply/coprimeP; first by [].\nby exists (u, k * u %/ n); rewrite /= mulnC {1}(divn_eq (k * u) n) addKn.\nQed.\n\nLemma gauss_inv : forall m n p,\n  coprime m n -> (m * n %| p) = (m %| p) && (n %| p).\nProof.\nby move=> m n p co_mn; rewrite -muln_lcm_gcd (eqnP co_mn) muln1 dvdn_lcm.\nQed.\n\nLemma gauss : forall m n p, coprime m n -> (m %| n * p) = (m %| p).\nProof.\nmove=> m [|n] p co_mn; first by case: m co_mn => [|[]] // _; rewrite !dvd1n.\nby symmetry; rewrite mulnC -(@dvdn_pmul2r n.+1) ?gauss_inv // andbC dvdn_mull.\nQed.\n\nLemma gauss_gcdr : forall p m n, coprime p m -> gcdn p (m * n) = gcdn p n.\nProof.\nmove=> p m n co_pm; apply/eqP; rewrite eqn_dvd !dvdn_gcd !dvdn_gcdl /=.\nrewrite andbC dvdn_mull ?dvdn_gcdr //= -(@gauss _ m) ?dvdn_gcdr //.\nby rewrite /coprime gcdnAC (eqnP co_pm) gcd1n.\nQed.\n\nLemma gauss_gcdl : forall p m n, coprime p n -> gcdn p (m * n) = gcdn p m.\nProof. by move=> *; rewrite mulnC gauss_gcdr. Qed.\n\nLemma coprime_mulr : forall p m n,\n  coprime p (m * n) = coprime p m && coprime p n.\nProof.\nmove=> p m n.\ncase co_pm: (coprime p m) => /=; first by rewrite /coprime gauss_gcdr.\napply/eqP=> co_p_mn; case/eqnP: co_pm; apply gcdn_def => // d dv_dp dv_dm.\nby rewrite -co_p_mn dvdn_gcd dv_dp dvdn_mulr.\nQed.\n\nLemma coprime_mull : forall p m n,\n  coprime (m * n) p = coprime m p && coprime n p.\nProof. move=> p m n; rewrite !(coprime_sym _ p); exact: coprime_mulr. Qed.\n\nLemma coprime_pexpl : forall k m n, 0 < k -> coprime (m ^ k) n = coprime m n.\nProof.\ncase=> // k m n _; elim: k => [|k IHk]; first by rewrite expn1.\nby rewrite expnS coprime_mull -IHk; case coprime.\nQed.\n\nLemma coprime_pexpr : forall k m n, 0 < k -> coprime m (n ^ k) = coprime m n.\nProof. by move=> k m n k_gt0; rewrite !(coprime_sym m) coprime_pexpl. Qed.\n\nLemma coprime_expl : forall k m n, coprime m n -> coprime (m ^ k) n.\nProof. by case=> [|k] p m co_pm; rewrite ?coprime1n // coprime_pexpl. Qed.\n\nLemma coprime_expr : forall k m n, coprime m n -> coprime m (n ^ k).\nProof. by move=> k m n; rewrite !(coprime_sym m); exact: coprime_expl. Qed.\n\nLemma coprime_dvdl : forall m n p, m %| n -> coprime n p -> coprime m p.\nProof.\nby move=> m n p; case/dvdnP=> d ->; rewrite coprime_mull; case/andP.\nQed.\n\nLemma coprime_dvdr : forall m n p, m %| n -> coprime p n -> coprime p m.\nProof. by move=> m n p; rewrite !(coprime_sym p); exact: coprime_dvdl. Qed.\n\nLemma coprime_egcdn : forall n m, n > 0 ->\n    coprime (egcdn n m).1 (egcdn n m).2.\nProof.\nmove=> n m n_gt0; case: (egcdnP m n_gt0) => kn km /=; move/eqP.\nhave [u defn] := dvdnP (dvdn_gcdl n m); have [v defm] := dvdnP (dvdn_gcdr n m).\nrewrite -[gcdn n m]mul1n {1}defm {1}defn !mulnA -muln_addl addnC.\nrewrite eqn_pmul2r ?gcdn_gt0 ?n_gt0 //; move/eqP; case: kn => // kn def_knu _.\nby apply/coprimeP=> //; exists (u, v); rewrite mulnC def_knu mulnC addnK.\nQed.\n\nLemma dvdn_pexp2r : forall m n k, k > 0 -> (m ^ k %| n ^ k) = (m %| n).\nProof.\nmove=> m n k k_gt0; apply/idP/idP=> [dv_mn_k|]; last exact: dvdn_exp2r.\ncase: (posnP n) => [-> | n_gt0]; first by rewrite dvdn0.\nhave [n' def_n] := dvdnP (dvdn_gcdr m n); set d := gcdn m n in def_n.\nhave [m' def_m] := dvdnP (dvdn_gcdl m n); rewrite -/d in def_m.\nhave d_gt0: d > 0 by rewrite gcdn_gt0 n_gt0 orbT.\nrewrite def_m def_n !expn_mull dvdn_pmul2r ?expn_gt0 ?d_gt0 // in dv_mn_k.\nhave: coprime (m' ^ k) (n' ^ k).\n  rewrite coprime_pexpl // coprime_pexpr // /coprime -(eqn_pmul2r d_gt0) mul1n.\n  by rewrite muln_gcdl -def_m -def_n.\nrewrite /coprime -gcdn_modr (eqnP dv_mn_k) gcdn0 -(exp1n k).\nby rewrite (inj_eq (expIn k_gt0)) def_m; move/eqP->; rewrite mul1n dvdn_gcdr.\nQed.\n\nSection Chinese.\n\n(***********************************************************************)\n(*   The chinese remainder theorem                                     *)\n(***********************************************************************)\n\nVariables m1 m2 : nat.\nHypothesis co_m12 : coprime m1 m2.\n\nLemma chinese_remainder : forall x y,\n  (x == y %[mod m1 * m2]) = (x == y %[mod m1]) && (x == y %[mod m2]).\nProof.\nmove=> x y; wlog le_yx : x y / y <= x.\n  by case/orP: (leq_total y x); last rewrite !(eq_sym (x %% _)); auto.\nby rewrite !eqn_mod_dvd // gauss_inv.\nQed.\n\n(***********************************************************************)\n(*   A function that solves the chinese remainder problem              *)\n(***********************************************************************)\n\nDefinition chinese r1 r2 :=\n  r1 * m2 * (egcdn m2 m1).1 + r2 * m1 * (egcdn m1 m2).1.\n\nLemma chinese_modl : forall r1 r2, chinese r1 r2 = r1 %[mod m1].\nProof.\nrewrite /chinese; case: (posnP m2) co_m12 => [->|m2_gt0 _].\n  by move/eqnP; rewrite gcdn0 => -> r1 r2 ; rewrite !modn1.\ncase: egcdnP=> // k2 k1 def_m1 _ r1 r2.\nrewrite mulnAC -mulnA def_m1 gcdnC (eqnP co_m12) muln_addr mulnA muln1.\nby rewrite addnAC (mulnAC _ m1) -muln_addl modn_addl_mul.\nQed.\n\nLemma chinese_modr : forall r1 r2, chinese r1 r2 = r2 %[mod m2].\nProof.\nrewrite /chinese; case: (posnP m1) co_m12 => [->|m1_gt0 _].\n  by move/eqnP; rewrite gcd0n => -> r1 r2 ; rewrite !modn1.\ncase: (egcdnP m2) => // k1 k2 def_m2 _ r1 r2.\nrewrite addnC mulnAC -mulnA def_m2 (eqnP co_m12) muln_addr mulnA muln1.\nby rewrite addnAC (mulnAC _ m2) -muln_addl modn_addl_mul.\nQed.\n\nLemma chinese_modlr : forall x, x = chinese (x %% m1) (x %% m2) %[mod m1 * m2].\nProof.\nmove=> x; apply/eqP.\nby rewrite chinese_remainder // chinese_modl chinese_modr !modn_mod !eqxx.\nQed.\n\nEnd Chinese.\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/ssreflect/attic/ssreflect12_trunk/theories/div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.6727544123660502}}
{"text": "Definition identity0 (x:nat) :=x.\nDefinition identity (A:Type) (x:A) :=x.\nDefinition identity3 {A:Type} (x:A) :=x.\nDefinition apply {A:Type} {B:Type} (f:A->B) (x:A) := f x.\nDefinition add x := fst x + snd x.\nEval compute in apply add (1,2).\nOpen Scope list_scope.\nNotation \"[a; .. ;b ]\" := (a :: .. (b :: nil) .. ).\nFixpoint map {A:Type} {B:Type} (f:A->B) (x:list A) :=\n match x with\n |nil =>nil\n |(h::t) => (f h)::(map f t)\nend.\n\nCheck map.\n\nEval compute in map add [(1,2); (3,4); (5,6)].\nEval compute in map (fun n => n+1) [1;2;3].\n\nDefinition compose {A B C:Type} (f:B->C) (g:A->B) :=\n (fun x=> f (g,x)).\n\nDefinition cool := compose (fun n=> n+1) (fun n => n*2).\n\nEval compute in cool 10.\n\nDefinition addx x := (fun y => x+y).\n\nEval compute in addx 3.\nEval compute in (addx 3) 4.\nEval compute in addx 3,4.\n\nDefinition someadd x y := x+y.\n\nEval compute in someadd 3.", "meta": {"author": "rabimba", "repo": "coq", "sha": "8824a3701f961f56a5d8747f0d561871184f26aa", "save_path": "github-repos/coq/rabimba-coq", "path": "github-repos/coq/rabimba-coq/coq-8824a3701f961f56a5d8747f0d561871184f26aa/2nd day.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6727544013165502}}
{"text": "(** * Matrices\n\nOperations on vectors and matrices.\n\nAuthor: Langston Barrett (@siddharthist) (March 2018)\n*)\n\nRequire Import UniMath.Foundations.PartA.\nRequire Import UniMath.MoreFoundations.PartA.\nRequire Import UniMath.Combinatorics.FiniteSequences.\nRequire Import UniMath.Algebra.BinaryOperations.\nRequire Import UniMath.Algebra.IteratedBinaryOperations.\n\nRequire Import UniMath.Algebra.RigsAndRings.\n\n(** ** Contents\n\n - Vectors\n   - Standard conditions on one binary operation\n   - Standard conditions on a pair of binary operations\n   - Structures\n - Matrices\n   - Standard conditions on one binary operation\n   - Structures\n   - Matrix rig\n*)\n\n(** ** Vectors *)\n\nDefinition pointwise {X : UU} (n : nat) (op : binop X) : binop (Vector X n) :=\n  λ v1 v2 i, op (v1 i) (v2 i).\n\n(** *** Standard conditions on one binary operation *)\n\n(** Most features of binary operations (associativity, unity, etc) carry over to\n    pointwise operations. *)\nSection OneOp.\n  Context {X : UU} {n : nat} {op : binop X}.\n\n  Definition pointwise_assoc (assocax : isassoc op) : isassoc (pointwise n op).\n  Proof.\n    intros ? ? ?; apply funextfun; intro; apply assocax.\n  Defined.\n\n  Definition pointwise_lunit (lun : X) (lunax : islunit op lun) :\n    islunit (pointwise n op) (const_vec lun).\n  Proof.\n    intros ?; apply funextfun; intro; apply lunax.\n  Defined.\n\n  Definition pointwise_runit (run : X) (runax : isrunit op run) :\n    isrunit (pointwise n op) (const_vec run).\n  Proof.\n    intros ?; apply funextfun; intro; apply runax.\n  Defined.\n\n  Definition pointwise_unit (un : X) (unax : isunit op un) :\n    isunit (pointwise n op) (const_vec un).\n  Proof.\n    use make_isunit.\n    - apply pointwise_lunit; exact (pr1 unax).\n    - apply pointwise_runit; exact (pr2 unax).\n  Defined.\n\n  Definition pointwise_comm (commax : iscomm op) : iscomm (pointwise n op).\n  Proof.\n    intros ? ?; apply funextfun; intro; apply commax.\n  Defined.\n\n  Definition pointwise_monoidop (monoidax : ismonoidop op) :\n    ismonoidop (pointwise n op).\n  Proof.\n    use make_ismonoidop.\n    - apply pointwise_assoc, assocax_is; assumption.\n    - use make_isunital.\n      + apply (const_vec (unel_is monoidax)).\n      + apply pointwise_unit, unax_is.\n  Defined.\n\n  Definition pointwise_abmonoidop (abmonoidax : isabmonoidop op) :\n    isabmonoidop (pointwise n op).\n  Proof.\n    use make_isabmonoidop.\n    - apply pointwise_monoidop; exact (pr1isabmonoidop _ _ abmonoidax).\n    - apply pointwise_comm; exact (pr2 abmonoidax).\n  Defined.\n\nEnd OneOp.\n\n(** *** Standard conditions on a pair of binary operations *)\n\nSection TwoOps.\n  Context {X : UU} {n : nat} {op : binop X} {op' : binop X}.\n\n  Definition pointwise_ldistr (isldistrax : isldistr op op') :\n    isldistr (pointwise n op) (pointwise n op').\n  Proof.\n    intros ? ? ?; apply funextfun; intro; apply isldistrax.\n  Defined.\n\n  Definition pointwise_rdistr (isrdistrax : isrdistr op op') :\n    isrdistr (pointwise n op) (pointwise n op').\n  Proof.\n    intros ? ? ?; apply funextfun; intro; apply isrdistrax.\n  Defined.\n\n  Definition pointwise_distr (isdistrax : isdistr op op') :\n    isdistr (pointwise n op) (pointwise n op').\n  Proof.\n    use make_dirprod.\n    - apply pointwise_ldistr; apply (dirprod_pr1 isdistrax).\n    - apply pointwise_rdistr; apply (dirprod_pr2 isdistrax).\n  Defined.\n\nEnd TwoOps.\n\n(** *** Structures *)\n\nSection Structures.\n\n  Definition pointwise_hSet (X : hSet) (n : nat) : hSet.\n  Proof.\n    use make_hSet.\n    - exact (Vector X n).\n    - change isaset with (isofhlevel 2).\n      apply vector_hlevel, setproperty.\n  Defined.\n\n  Definition pointwise_setwithbinop (X : setwithbinop) (n : nat) : setwithbinop.\n  Proof.\n    use make_setwithbinop.\n    - apply pointwise_hSet; [exact X|assumption].\n    - exact (pointwise n op).\n  Defined.\n\n  Definition pointwise_setwith2binop (X : setwith2binop) (n : nat) : setwith2binop.\n  Proof.\n    use make_setwith2binop.\n    - apply pointwise_hSet; [exact X|assumption].\n    - split.\n      + exact (pointwise n op1).\n      + exact (pointwise n op2).\n  Defined.\n\n  Definition pointwise_monoid (X : monoid) (n : nat) : monoid.\n  Proof.\n    use make_monoid.\n    - apply pointwise_setwithbinop; [exact X|assumption].\n    - apply pointwise_monoidop; exact (pr2 X).\n  Defined.\n\n  Definition pointwise_abmonoid (X : abmonoid) (n : nat) : abmonoid.\n  Proof.\n    use make_abmonoid.\n    - apply pointwise_setwithbinop; [exact X|assumption].\n    - apply pointwise_abmonoidop; exact (pr2 X).\n  Defined.\n\nEnd Structures.\n\n(** ** Matrices *)\n\nDefinition entrywise {X : UU} (n m : nat) (op : binop X) : binop (Matrix X n m) :=\n  λ mat1 mat2 i, pointwise _ op (mat1 i) (mat2 i).\n\n(** *** Standard conditions on one binary operation *)\n\nSection OneOpMat.\n  Context {X : UU} {n m : nat} {op : binop X}.\n\n  Definition entrywise_assoc (assocax : isassoc op) : isassoc (entrywise n m op).\n  Proof.\n    intros ? ? ?; apply funextfun; intro; apply pointwise_assoc, assocax.\n  Defined.\n\n  Definition entrywise_lunit (lun : X) (lunax : islunit op lun) :\n    islunit (entrywise n m op) (const_matrix lun).\n  Proof.\n    intros ?; apply funextfun; intro; apply pointwise_lunit, lunax.\n  Defined.\n\n  Definition entrywise_runit (run : X) (runax : isrunit op run) :\n    isrunit (entrywise n m op) (const_matrix run).\n  Proof.\n    intros ?; apply funextfun; intro; apply pointwise_runit, runax.\n  Defined.\n\n  Definition entrywise_unit (un : X) (unax : isunit op un) :\n    isunit (entrywise n m op) (const_matrix un).\n  Proof.\n    use make_isunit.\n    - apply entrywise_lunit; exact (pr1 unax).\n    - apply entrywise_runit; exact (pr2 unax).\n  Defined.\n\n  Definition entrywise_comm (commax : iscomm op) : iscomm (entrywise n m op).\n  Proof.\n    intros ? ?; apply funextfun; intro; apply pointwise_comm, commax.\n  Defined.\n\n  Definition entrywise_monoidop (monoidax : ismonoidop op) :\n    ismonoidop (entrywise n m op).\n  Proof.\n    use make_ismonoidop.\n    - apply entrywise_assoc, assocax_is; assumption.\n    - use make_isunital.\n      + apply (const_matrix (unel_is monoidax)).\n      + apply entrywise_unit, unax_is.\n  Defined.\n\n  Definition entrywise_abmonoidop (abmonoidax : isabmonoidop op) :\n    isabmonoidop (entrywise n m op).\n  Proof.\n    use make_isabmonoidop.\n    - apply entrywise_monoidop; exact (pr1isabmonoidop _ _ abmonoidax).\n    - apply entrywise_comm; exact (pr2 abmonoidax).\n  Defined.\n\nEnd OneOpMat.\n\n(** It is uncommon to consider two entrywise binary operations on matrices,\n    so we don't derive \"standard conditions on a pair of binar operations\"\n    for matrices. *)\n\n(** *** Structures *)\n\n(** *** Matrix rig *)\n\nSection MatrixMult.\n\n  Context {R : rig}.\n\n  (** Summation and pointwise multiplication *)\n  Local Notation Σ := (iterop_fun rigunel1 op1).\n  Local Notation \"R1 ^ R2\" := ((pointwise _ op2) R1 R2).\n\n  (** If A is m × n (so B is n × p),\n<<\n        AB(i, j) = A(i, 1) * B(1, j) + A(i, 2) * B(2, j) + ⋯ + A(i, n) * B(n, j)\n>>\n      The order of the arguments allows currying the first matrix.\n  *)\n  Definition matrix_mult {m n : nat} (mat1 : Matrix R m n)\n                         {p : nat} (mat2 : Matrix R n p) : (Matrix R m p) :=\n    λ i j, Σ ((row mat1 i) ^ (col mat2 j)).\n\n  Local Notation \"A ** B\" := (matrix_mult A B) (at level 80).\n\n  Lemma identity_matrix {n : nat} : (Matrix R n n).\n  Proof.\n    intros i j.\n    induction (stn_eq_or_neq i j).\n    - exact (rigunel2). (* The multiplicative identity *)\n    - exact (rigunel1). (* The additive identity *)\n  Defined.\n\nEnd MatrixMult.\n\nLocal Notation Σ := (iterop_fun rigunel1 op1).\nLocal Notation \"R1 ^ R2\" := ((pointwise _ op2) R1 R2).\nLocal Notation \"A ** B\" := (matrix_mult A B) (at level 80).\n\n(** The following is based on \"The magnitude of metric spaces\" by Tom Leinster\n    (arXiv:1012.5857v3). *)\nSection Weighting.\n\n  Context {R : rig}.\n\n  (** Definition 1.1.1 in arXiv:1012.5857v3 *)\n  Definition weighting {m n : nat} (mat : Matrix R m n) : UU :=\n    ∑ vec : Vector R n, (mat ** (col_vec vec)) = col_vec (const_vec (1%rig)).\n\n  Definition coweighting {m n : nat} (mat : Matrix R m n) : UU :=\n    ∑ vec : Vector R m, ((row_vec vec) ** mat) = row_vec (const_vec (1%rig)).\n\n  Lemma matrix_mult_vectors {n : nat} (vec1 vec2 : Vector R n) :\n    ((row_vec vec1) ** (col_vec vec2)) = weq_matrix_1_1 (Σ (vec1 ^ vec2)).\n  Proof.\n    apply funextfun; intro i; apply funextfun; intro j; reflexivity.\n  Defined.\n\n  (** Multiplying a column vector by the identity row vector is the same as\n      taking the sum of its entries. *)\n  Local Lemma sum_entries1 {n : nat} (vec : Vector R n) :\n    weq_matrix_1_1 (Σ vec) = ((row_vec (const_vec (1%rig))) ** (col_vec vec)).\n  Proof.\n    refine (_ @ !matrix_mult_vectors _ _).\n    do 2 apply maponpaths.\n    apply pathsinv0.\n    refine (pointwise_lunit 1%rig _ vec).\n    apply riglunax2.\n  Defined.\n\n  Local Lemma sum_entries2 {n : nat} (vec : Vector R n) :\n      weq_matrix_1_1 (Σ vec) = (row_vec vec ** col_vec (const_vec 1%rig)).\n  Proof.\n    refine (_ @ !matrix_mult_vectors _ _).\n    do 2 apply maponpaths.\n    apply pathsinv0.\n    refine (pointwise_runit 1%rig _ vec).\n    apply rigrunax2.\n  Defined.\n\n  (** TODO: prove this so that the below isn't hypothetical *)\n  Definition matrix_mult_assoc_statement : UU :=\n    ∏ (m n : nat) (mat1 : Matrix R m n)\n      (p : nat) (mat2 : Matrix R n p)\n      (q : nat) (mat3 : Matrix R p q),\n    ((mat1 ** mat2) ** mat3) = (mat1 ** (mat2 ** mat3)).\n\n  (** Lemma 1.1.2 in arXiv:1012.5857v3 *)\n  Lemma weighting_coweighting_sum {m n : nat} (mat : Matrix R m n)\n        (wei : weighting mat) (cowei : coweighting mat)\n        (assocax : matrix_mult_assoc_statement) :\n    Σ (pr1 wei) = Σ (pr1 cowei).\n  Proof.\n    apply (invmaponpathsweq weq_matrix_1_1).\n    intermediate_path ((row_vec (const_vec (1%rig))) ** (col_vec (pr1 wei))).\n    - apply sum_entries1.\n    - refine (!maponpaths (λ z, z ** _) (pr2 cowei) @ _).\n      refine (assocax _ _ _ _ _ _ _ @ _).\n      refine (maponpaths (λ z, _ ** z) (pr2 wei) @ _).\n      apply pathsinv0, sum_entries2 .\n  Defined.\n\n  (** Definition 1.1.3 in arXiv:1012.5857v3 *)\n  Definition has_magnitude {n m : nat} (mat : Matrix R m n) : UU :=\n    (weighting mat) × (coweighting mat).\n\n  Definition magnitude {n m : nat} (m : Matrix R m n) (has : has_magnitude m) : R :=\n    Σ (pr1 (dirprod_pr1 has)).\n\nEnd Weighting.\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/Matrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.67275438819515}}
{"text": "Require Import\n  Coq.setoid_ring.Ring MathClasses.interfaces.abstract_algebra MathClasses.interfaces.integers\n  MathClasses.theory.integers MathClasses.theory.ring_ideals.\n\nDefinition is_multiple `{Equiv Z} `{Mult Z} (b x : Z) := ∃ k, x = b * k.\nNotation Mod b := (Factor _ (is_multiple b)).\n\nSection modular_ring.\n  Context `{Ring Z} {b : Z}.\n  Add Ring R : (rings.stdlib_ring_theory Z).\n\n  Global Instance: RingIdeal Z (is_multiple b).\n  Proof.\n    unfold is_multiple. split.\n        solve_proper.\n       split. exists 0, 0. ring.\n      intros x y [k1 E1] [k2 E2]. exists (k1 - k2). rewrite E1, E2. ring.\n     intros x y [k E]. exists (y * k). rewrite E. ring.\n    intros x y [k E]. exists (x * k). rewrite E. ring.\n  Qed.\n\n  Lemma modular_ring_eq (x y : Mod b) : x = y ↔ ∃ k, 'x = 'y + b * k.\n  Proof. split; intros [k E]; exists k. rewrite <-E. ring. rewrite E. ring. Qed.\nEnd modular_ring.\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/modular_ring.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895028, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6727525547308968}}
{"text": "Require Import GeoCoq.Axioms.tarski_axioms.\nRequire Import GeoCoq.Axioms.continuity_axioms.\nRequire Import GeoCoq.Meta_theory.Continuity.completeness.\nRequire Import GeoCoq.Meta_theory.Continuity.dedekind_completeness.\nRequire Import GeoCoq.Meta_theory.Continuity.archimedes_cantor_dedekind.\n\nSection Cantor_completeness.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma cantor__completeness : (archimedes_axiom \\/ ~ archimedes_axiom) -> cantor_s_axiom ->\n  line_completeness.\nProof.\n  intros [archi|anarchy] cantor.\n    apply dedekind_variant__completeness, (archimedes_cantor__dedekind_variant archi cantor).\n    apply (not_archimedes__line_completeness anarchy).\nQed.\n\nEnd Cantor_completeness.\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/Continuity/cantor_completeness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6726097600596466}}
{"text": "Require Export Modal at_pv.\nRequire Export SecOrder at_pred.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.EqNat. \nRequire Import Coq.Init.Nat.\n\n(* Definition of the standard translation from modal to SOL. *)\nFixpoint ST (phi: Modal) (x:FOvariable) : SecOrder :=\n  match phi with\n    atom (pv n) => predSO (Pred n) x\n  | mneg psi => negSO (ST psi x)\n  | mconj psi1 psi2 => conjSO (ST psi1 x) (ST psi2 x)\n  | mdisj psi1 psi2 => disjSO (ST psi1 x) (ST psi2 x)\n  | mimpl psi1 psi2 => implSO (ST psi1 x) (ST psi2 x)\n  | box psi => \n      match x with\n        Var n => allFO (Var (n+1)) (implSO (relatSO (Var n) (Var (n+1))) (ST psi (Var (n+1))))\n      end  \n  | diam psi =>\n      match x with\n        Var n => exFO (Var (n+1)) (conjSO (relatSO (Var n) (Var (n+1))) (ST psi (Var (n+1))))\n      end\n  end.\n\nDefinition ST_pv (p : propvar) : predicate :=\n  match p with\n    pv n => Pred n\n  end.\n\nLemma ST_pv_P : forall n : nat,\n  Pred n = ST_pv (pv n).\nProof.\n  intros n; reflexivity.\nQed.\n\nDefinition ST_pred (P : predicate) : propvar :=\n  match P with\n    Pred n => pv n\n  end.\n\n(* Converts modal valuation to SO interpretation on predicates. *)\nFixpoint V_to_Ip (W:Set) (V: propvar -> W -> Prop) (P: predicate) (w:W) : Prop :=\n  match P with \n    Pred n => V (pv n) w\n  end.\n\n(* Converts SO interpretation on predicates to modal valuation. *)\nFixpoint Ip_to_V (W:Set) (Ip: predicate -> W -> Prop) (p: propvar) (w:W) : Prop :=\n  match p with \n    pv n => Ip (Pred n) w\n  end.\n\n(* Lemmas that show going from V to Ip and back to V is just the same as V.\n   And for Ip to V to Ip. *)\nLemma V_Ip_V: forall (W:Set) (V: propvar -> W -> Prop),\n  Ip_to_V W (V_to_Ip W V) = V.\nProof.\n  intros.\n  apply functional_extensionality.\n  intros p.\n  apply functional_extensionality.\n  intros w.\n  destruct p.\n  unfold V_to_Ip.\n  unfold Ip_to_V.\n  reflexivity.\nQed.\n\nLemma Ip_V_Ip: forall (W:Set) (Ip: predicate -> W -> Prop),\n  V_to_Ip W (Ip_to_V W Ip) = Ip.\nProof.\n  intros.\n  apply functional_extensionality.\n  intros p.\n  apply functional_extensionality.\n  intros w.\n  destruct p.\n  unfold V_to_Ip.\n  unfold Ip_to_V.\n  reflexivity.\nQed.\n\n(*--------------------------------------------------------------------------------*)\n\n(* \"By definition\" lemmas of ST *)\n\nLemma ST_box_phi : forall (phi:Modal) (x:FOvariable), (ST (box phi) x) = \n      match x with\n        Var n => allFO (Var (n+1)) (implSO (relatSO (Var n) (Var (n+1))) (ST phi (Var (n+1))))\n      end.\nProof.\n  simpl; reflexivity.\nQed.\n\nLemma ST_diam : forall (phi:Modal) (x:FOvariable), (ST (diam phi) x) =\n      match x with\n        Var n => exFO (Var (n+1)) (conjSO (relatSO (Var n) (Var (n+1))) (ST phi (Var (n+1))))\n      end.\nProof.\n  simpl; reflexivity.\nQed.\n\nLemma ST_conj: forall (psi_1 psi_2: Modal) (x:FOvariable), \n                   ST (mconj psi_1 psi_2) x = conjSO (ST psi_1 x) (ST psi_2 x).\nProof.\n  simpl; reflexivity.\nQed.\n\n(*--------------------------------------------------------------------------------*)\n\nLemma simpl_alt_l : forall (W:Set) (u v:W) (Iv: FOvariable -> W) (Ip: predicate -> W -> Prop)\n                  (xn: nat), \n                      (alt_Iv (alt_Iv Iv u (Var xn)) v (Var (xn+1))) (Var xn) = u.\nProof.\n  intros W u v Iv Ip xn.\n  unfold alt_Iv.\n  assert (EqNat.beq_nat (xn+1) xn = false).\n    induction xn.\n      simpl; reflexivity.\n\n      simpl; exact IHxn.\n\n    rewrite H.\n    rewrite <- EqNat.beq_nat_refl; reflexivity.\nQed.\n\nLemma simpl_alt_r : forall (W:Set) (u v:W) (Iv: FOvariable -> W) (Ip: predicate -> W -> Prop)\n                  (xn: nat), \n                      (alt_Iv (alt_Iv Iv u (Var xn)) v (Var (xn+1))) (Var (xn+1)) = v.\nProof.\n  intros W u v Iv Ip xn.\n  unfold alt_Iv.\n  rewrite <- EqNat.beq_nat_refl; reflexivity.\nQed.\n\n(*-----------------------------------------------------------------------------------------*)\n\nLemma R_relatSO : forall (W:Set) (R: W -> W -> Prop) (u v:W) (Iv: FOvariable -> W) \n                         (Ip: predicate -> W -> Prop) (xn:nat),\n       (R u v)\n     <-> (SOturnst W (alt_Iv (alt_Iv Iv u (Var xn)) v (Var (xn+1))) Ip R (relatSO (Var xn) (Var (xn+1)))).\nProof.\n  intros W R u v Iv Ip xn.\n  unfold SOturnst.\n  rewrite simpl_alt_l.\n    rewrite simpl_alt_r.\n      unfold iff; apply conj; intro H; exact H.\n\n    exact Ip.\n  exact Ip.\nQed.\n\n\n(* ---------------------------------------------------------------------------------------- *)\n\n\nLemma preds_in_ST_FOv : forall (phi : Modal) (x y : FOvariable),\n  preds_in (ST phi x) = preds_in (ST phi y).\nProof.\n  induction phi; intros x y;\n    try (simpl;\n    rewrite (IHphi1 x y);\n    rewrite (IHphi2 x y);\n    reflexivity);\n    try (simpl; destruct x as [xn]; destruct y as [ym];\n    simpl;\n    rewrite (IHphi (Var (xn + 1)) (Var (ym + 1)));\n    reflexivity).\n\n    destruct p as [n]; destruct x; destruct y;\n    reflexivity.\n\n    simpl; apply IHphi.\nQed.\n\n\n\nLemma pv_in__preds_in : forall (phi : Modal) ( x : FOvariable),\n  length (pv_in phi) = length (preds_in (ST phi x)).\nProof.\n  induction phi; intros x;\n    try destruct p; destruct x;\n    try (simpl;\n    do 2  rewrite app_length;\n    rewrite <- IHphi1;\n    rewrite <- IHphi2;\n    reflexivity);\n    try (simpl;\n    rewrite <- IHphi;\n    reflexivity;\n    simpl; apply IHphi);\n    try reflexivity.\nQed.\n\nLemma at_pv_ST_conjSO : forall (phi1 phi2 : Modal) ( x : FOvariable) (i : nat),\n  (forall (x : FOvariable) (i : nat),\n         match at_pv (pv_in phi1) i with\n         | pv n => match at_pred (preds_in (ST phi1 x)) i with\n                     | Pred m => n = m\n                     end\n         end) ->\n  (forall (x : FOvariable) (i : nat),\n         match at_pv (pv_in phi2) i with\n         | pv n => match at_pred (preds_in (ST phi2 x)) i with\n                     | Pred m => n = m\n                     end\n         end) ->\n  match at_pv (pv_in (mconj phi1 phi2)) i with\n  | pv n => match at_pred (preds_in (ST (mconj phi1 phi2) x)) i with\n            | Pred m => n = m\n            end\n  end.\nProof.\n  intros phi1 phi2 x i IHphi1 IHphi2;  simpl.\n  case_eq (leb i (length (pv_in phi1))); intro Hleb.\n    rewrite at_pv_app_l; try assumption.\n    case_eq (leb i (length (preds_in (ST phi1 x)))); intros Hleb2.\n      rewrite at_pred_app_l; try assumption.\n      apply IHphi1.\n\n(* \n  destruct (PeanoNat.Nat.le_ge_cases i (length (pv_in phi1)))\n    as [Hleb | Hleb].\n    rewrite at_pv_app_l; try assumption.\n    destruct (PeanoNat.Nat.le_ge_cases i (length (preds_in (ST phi1 x))))\n      as [Hleb2 | Hleb2].\n *)\n(*       rewrite at_pred_app_l; try assumption.\n      apply IHphi1.\n\nSearch le not.\n\n *)\n(* PeanoNat.Nat.leb_nle *)\n      apply PeanoNat.Nat.leb_le. assumption.\n\n       rewrite <- pv_in__preds_in in Hleb2.\n      rewrite Hleb2 in Hleb; discriminate.\n      apply PeanoNat.Nat.leb_le. assumption.\n\n    case_eq (leb i (length (preds_in (ST phi1 x)))); intros Hleb2.\n      rewrite <- pv_in__preds_in in Hleb2.\n      rewrite Hleb2 in Hleb; discriminate.\n      apply PeanoNat.Nat.leb_nle in Hleb.\n      apply PeanoNat.Nat.nle_gt in Hleb.\n      apply PeanoNat.Nat.lt_le_incl in Hleb.\n      apply Minus.le_plus_minus in Hleb.\n\n      rewrite Hleb.\n      rewrite at_pv_app_r; try assumption.\n      rewrite pv_in__preds_in with (x := x).\n      rewrite at_pred_app_r; try assumption.\n      apply IHphi2.\n        apply PeanoNat.Nat.eqb_neq. intros H.\n        rewrite Hleb in Hleb2.\n        rewrite <- pv_in__preds_in in *. rewrite H in *.\n        rewrite <- plus_n_O in Hleb2.\n        rewrite PeanoNat.Nat.leb_refl in Hleb2. discriminate.\n\n        apply PeanoNat.Nat.eqb_neq. intros H.\n        rewrite Hleb in Hleb2.\n        rewrite <- pv_in__preds_in in *. rewrite H in *.\n        rewrite <- plus_n_O in Hleb2.\n        rewrite PeanoNat.Nat.leb_refl in Hleb2. discriminate.\nQed.\n\n(*\nSearch leb true.\nSearch plus 0.\n        simpl in Hleb2.\nSearch eqb false.\nadmit.\nadmit.\n\n      destruct \nSearchAbout le .\n(*       apply PeanoNat.Nat.leb_nle in Hleb.\nSearch leb false. *)\n      apply PeanoNat.Nat.leb_nle in Hleb.\nSearch not le.\nSearch leb false.\n      apply leb_nat_switch in Hleb.\n      pose proof (leb_nat_ex _ _ Hleb) as H.\n      destruct H as [j H].\n      case_eq (beq_nat j 0); intros Hbeq.\n        rewrite (beq_nat_true _ _ Hbeq) in *.\n        rewrite plus_zero in H.\n        rewrite <- H in *.\n        rewrite <- pv_in__preds_in in Hleb2.\n        rewrite leb_nat_refl in Hleb2.\n        discriminate.\n      rewrite <- H.\n      rewrite at_pv_app_r; try assumption.\n      rewrite pv_in__preds_in with (x := x).\n      rewrite at_pred_app_r; try assumption.\n      apply IHphi2.\nQed. *)\n\nLemma at_pv_ST : forall (phi : Modal) ( x : FOvariable) (i : nat),\n  match at_pv (pv_in phi) i, at_pred (preds_in (ST phi x)) i with\n   | pv n, Pred m => n = m\n  end.\nProof.\n  induction phi; intros x i.\n    destruct p as [pn]; destruct x as [xn];\n    simpl; case i; [reflexivity|];\n      intros i2; case i2; reflexivity.\n\n    simpl; apply IHphi.\n    apply at_pv_ST_conjSO; assumption.\n    apply at_pv_ST_conjSO; assumption.\n    apply at_pv_ST_conjSO; assumption.\n\n    destruct x as [n];\n    simpl; apply IHphi.\n\n    destruct x as [n];\n    simpl; apply IHphi.\nQed.\n\nLemma ST_pred_p : forall n : nat,\n  pv n = ST_pred (Pred n).\nProof.\n  intros n; reflexivity.\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/ST_setup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523327, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6725385664371031}}
{"text": "Require Export Arith.\nRequire Export Omega.\nRequire Export ArithRing.\n \nLemma sub_decrease : forall b n m:nat, n <= S b -> 0 < m -> n - m <= b.\nintros; omega.\nQed.\n\nLtac remove_minus :=\n  match goal with\n  |  |- context [(?X1 - ?X2 + ?X3)] =>\n      rewrite <- (plus_comm X3); remove_minus\n  |  |- context [(?X1 + (?X2 - ?X3) + ?X4)] =>\n      rewrite (plus_assoc_reverse X1 (X2 - X3)); remove_minus\n  |  |- context [(?X1 + (?X2 + (?X3 - ?X4)))] =>\n      rewrite (plus_assoc X1 X2 (X3 - X4))\n  |  |- (_ = ?X1 + (?X2 - ?X3)) =>\n      apply (fun n m p:nat => plus_reg_l m p n) with X3;\n       try rewrite (plus_permute X3 X1 (X2 - X3)); \n       rewrite le_plus_minus_r\n  end.\n \nDefinition bdivspec :\n  forall b n m:nat,\n    n <= b -> 0 < m -> {q : nat &  {r : nat | n = m * q + r /\\ r < m}}.\n fix 1.\n intros b; case b.\n intros n m Hle Hlt; rewrite <- (le_n_O_eq _ Hle);\n   exists 0; exists 0; split;\n   auto with arith.\n ring.\n intros b' n m Hle Hlt.\n case (le_gt_dec m n).\n intros Hle';\n  generalize (bdivspec b' (n - m) m (sub_decrease b' n m Hle Hlt) Hlt).\n intros [q' [r [Heq Hlt']]].\n exists (S q'); exists r; split; auto with arith.\n replace (m * S q' + r) with (m * q' + r + m).\n rewrite <- Heq.\n remove_minus; trivial.\n ring.\n intros Hgt; exists 0; exists n; split; auto with arith.\n ring.\nQed.\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/gen-rec/SRC/bdivspec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6725385619734774}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type :=  Nil : lst | Cons : natural -> lst -> lst .\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint 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. lfind.  reflexivity. \nAdmitted.\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\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal80_rev_append_44_append_assoc/goal80.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6725385556317344}}
{"text": "(* Examples *)\nRequire Import ZArith Reals List QFourier.\n\nFrom mathcomp Require Import all_ssreflect all_algebra.\n\nImport GRing.Theory Num.Theory.\nOpen Scope ring_scope.\n\n\n(* Examples *)\nLemma ex1: forall x1 x2 x3: rat,\n  x1 <= x2 -> x1 <= x3 -> x2 + 1%:R * x3 <= x1 -> x3 < 1.\nProof. qfourier. Qed.\n\nLemma ex2: forall x1 x2 x3: rat,\n  3%:R / 4%:R * x1 + 10%:R <= 3%:R / 4%:R * x2 + 10%:R -> 1/2%:R * x2  = 1/2%:R * x3 -> x1 <= x3.\nProof. qfourier. Qed.\n", "meta": {"author": "thery", "repo": "Fourier", "sha": "6fa6a74940c5c8289f770910a6eea5f40cc0ab4c", "save_path": "github-repos/coq/thery-Fourier", "path": "github-repos/coq/thery-Fourier/Fourier-6fa6a74940c5c8289f770910a6eea5f40cc0ab4c/Examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6725356774072069}}
{"text": "(* Exercise 18 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\n(* Double negation *)\n\nTheorem exercise_018 : (~~(A->B) -> (A->B)).\nProof.\nimp_i a1.\nneg_e' (~(A -> B)) a2.\nhyp a1.\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_prop018.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.7401743735019594, "lm_q1q2_score": 0.6725356752885923}}
{"text": "Require Import option.\n\nInductive exp : Set :=\n| Nat  : nat  -> exp\n| Bool : bool -> exp\n| Plus : exp  -> exp -> exp\n| And  : exp  -> exp -> exp\n.\n\nInductive type : Set := \n| TNat  : type  \n| TBool : type\n.\n\nInductive hasType : exp -> type -> Prop :=\n| HtNat  : forall (n:nat),  hasType (Nat n) TNat\n| HtBool : forall (b:bool), hasType (Bool b) TBool\n| HtPlus : forall (e1 e2:exp), \n    hasType e1 TNat -> \n    hasType e2 TNat -> \n    hasType (Plus e1 e2) TNat \n| HtAnd  : forall (e1 e2:exp),\n    hasType e1 TBool -> \n    hasType e2 TBool -> \n    hasType (And e1 e2) TBool\n.\n\n(* The lazy way                                                                 *)\nDefinition eq_type_dec : forall (t t':type), {t = t'} + {t <> t'}.\n    decide equality.\nDefined.\n\n(*\nPrint eq_type_dec.\n*)\n\n(* The usual way                                                                *)\nDefinition eq_type_dec' : forall (t t':type), {t = t'} + {t <> t'}.\n    intros t t'. destruct t, t'.\n    - left. reflexivity.\n    - right. intros H. inversion H.\n    - right. intros H. inversion H.\n    - left. reflexivity.\nDefined.\n\n(*\nPrint eq_type_dec'.\n*)\n\nDefinition nat_not_bool : TNat <> TBool := fun p =>\n    match p with end.\n\nDefinition bool_not_nat : TBool <> TNat := fun p =>\n    match p with end.\n\n(* The hand-crafted way                                                         *)\nDefinition eq_type_dec'' (t t':type) : {t = t'} + {t <> t'} :=\n    match t as s return {s = t'} + {s <> t'} with\n    | TNat  =>\n        match t' as s' return {TNat = s'} + {TNat <> s'} with\n        | TNat  => left eq_refl\n        | TBool => right nat_not_bool\n        end\n    | TBool =>\n        match t' as s' return {TBool = s'} + {TBool <> s'} with\n        | TNat  => right bool_not_nat\n        | TBool => left eq_refl\n        end\n    end.\n\n(*\nPrint eq_type_dec''.\n*)\n\n(* Hoping to turn 'Typ' into a monad - ish                                      *)\nDefinition Typ (e:exp) : Type := option {t:type | hasType e t}.\n\nDefinition return_ (e:exp) (t:type) (p:hasType e t) : Typ e := \n    Some (exist _ t p).\n\n(* This signature looks very good in that it seems to guarantee correctness     *)\n(* since if it returns a type t, this type will be accompanied by a proof of    *)\n(* hasType e t. Unfortunately, this is only half of a correctness proof:        *)\n(* We have to guarantee that if hasType e t holds, typeCheck is not None        *)\n(* Proving correctness and reasoning about typeCheck appears to be difficult    *)\n(* It would be better to design a new signature which ensures correctness       *)\nDefinition typeCheck : forall (e:exp), option {t:type | hasType e t}.\n    refine (fix F (e:exp) : option {t:type | hasType e t} :=\n        match e as e' return option {t:type | hasType e' t} with\n        | Nat _      => Some (exist _ TNat (HtNat _))\n        | Bool _     => Some (exist _ TBool (HtBool _))\n        | Plus e1 e2 => \n            match (F e1) with \n            | None  => None\n            | Some (exist _ t1 p1) => \n                match (F e2) with\n                | None  => None\n                | Some (exist _ t2 p2) =>\n                    match eq_type_dec t1 TNat with\n                    | right _  => None\n                    | left  _  =>\n                        match eq_type_dec t2 TNat with\n                        | right _  => None\n                        | left _   => Some (exist _ TNat (HtPlus _ _ _ _))\n                        end \n                    end\n\n                end\n            end\n        | And e1 e2  => \n            match (F e1) with \n            | None  => None\n            | Some (exist _ t1 p1)  =>\n                match (F e2) with\n                | None  => None\n                | Some (exist _ t2 p2)  =>\n                    match eq_type_dec t1 TBool with\n                    | right _  => None\n                    | left _   =>\n                        match eq_type_dec t2 TBool with\n                        | right _  => None\n                        | left _   => Some (exist _ TBool (HtAnd _ _ _ _))\n                        end\n                    end\n                end\n            end\n        end).\n    - simpl in p1. subst. assumption.\n    - simpl in p2. subst. assumption. \n    - simpl in p1. subst. assumption.\n    - simpl in p2. subst. assumption.\nDefined.\n\n(*\nPrint typeCheck.\n*)\n\nDefinition isNat (e:exp)(t' : {t:type | hasType e t}) : bool :=\n    match t' with\n    | exist _ t _   =>\n        match eq_type_dec t TNat with\n        | right _   => false\n        | left  _   => true\n        end\n    end.\n\nArguments isNat {e} _.\n\n\nLemma isNatHasTypeNat : forall (e:exp) (t' : {t:type | hasType e t}),\n    isNat t' = true -> hasType e TNat.\nProof.\n    intros e [t p]. simpl. destruct (eq_type_dec t) as [H|H].\n    - rewrite H in p. intros. assumption.\n    - intros H'. inversion H'.\nQed.\n\nDefinition isBool (e:exp)(t' : {t:type | hasType e t}) : bool :=\n    match t' with\n    | exist _ t _   =>\n        match eq_type_dec t TBool with\n        | right _   => false\n        | left  _   => true\n        end\n    end.\n\nArguments isBool {e} _.\n\nLemma isBoolHasTypeBool : forall (e:exp) (t' : {t:type | hasType e t}),\n    isBool t' = true -> hasType e TBool.\nProof.\n    intros e [t p]. simpl. destruct (eq_type_dec t) as [H|H].\n    - rewrite H in p. intros. assumption.\n    - intros H'. inversion H'.\nQed.\n\n(* This is a lot more readable than the initial typeCheck implementation        *)\nDefinition typeCheck' : forall (e:exp), option {t:type | hasType e t}.\n    refine (fix F (e:exp) : option {t:type | hasType e t} :=\n        match e as e' return option {t:type | hasType e' t} with\n        | Nat _      => Some (exist _ TNat (HtNat _))\n        | Bool _     => Some (exist _ TBool (HtBool _))\n        | Plus e1 e2 => \n            t1 <- F e1 ;\n            t2 <- F e2 ;\n            p1  <- guard (isNat t1) ; \n            p2  <- guard (isNat t2) ;\n            Some (exist _ TNat (HtPlus _ _ _ _))\n        | And e1 e2  =>\n            t1 <- F e1 ;\n            t2 <- F e2 ;\n            p1 <- guard (isBool t1) ;\n            p2 <- guard (isBool t2) ;\n            Some (exist _ TBool (HtAnd _ _ _ _))\n        end). \n    - apply isNatHasTypeNat   with t1. assumption.\n    - apply isNatHasTypeNat   with t2. assumption.\n    - apply isBoolHasTypeBool with t1. assumption.\n    - apply isBoolHasTypeBool with t2. assumption.\nDefined. (* not 'Qed' which would make function opaque                          *)\n\n(* Throws away the proof element                                                *)\nDefinition typeOf (e:exp) (t':{t:type | hasType e t}) : type :=\n    match t' with\n    | exist _ t _  => t\n    end.\n\nArguments typeOf {e} _.\n\n(*\nCompute typeOf <$> (typeCheck (Nat 5)).\nCompute typeOf <$> (typeCheck (Bool true)).\nCompute typeOf <$> (typeCheck (Plus (Nat 5) (Plus (Nat 6) (Nat 0)))).\nCompute typeOf <$> (typeCheck (And (Bool true) (Bool false))).\nCompute typeOf <$> (typeCheck (Plus (Bool true) (Nat 5))).\nCompute typeOf <$> (typeCheck' (Nat 5)).\nCompute typeOf <$> (typeCheck' (Bool true)).\nCompute typeOf <$> (typeCheck' (Plus (Nat 5) (Plus (Nat 6) (Nat 0)))).\nCompute typeOf <$> (typeCheck' (And (Bool true) (Bool false))).\nCompute typeOf <$> (typeCheck' (Plus (Bool true) (Nat 5))).\n*)\n\nLemma hasType_unique : forall (e:exp) (t t':type),\n    hasType e t -> hasType e t' -> t = t'.\nProof.\n    destruct e as [n|b|e1 e2|e1i e2]; \n    intros t t' H H'; \n    inversion H; inversion H'; \n    reflexivity.\nQed.\n\n(* This correctness result is pretty much guaranteed by the type system         *)\nLemma typeCheck_correct1 : forall (e:exp) (t:type),\n    typeOf <$> typeCheck e = Some t -> hasType e t.\nProof.\n    intros e t H. destruct (typeCheck e) as [[t' H']|];\n    simpl in H; inversion H. subst. assumption.\nQed.\n\n(* Identical proof, all coming from the type signature of typeCheck             *)\nLemma typeCheck_correct1' : forall (e:exp) (t:type),\n    typeOf <$> typeCheck' e = Some t -> hasType e t.\nProof.\n    intros e t H. destruct (typeCheck' e) as [[t' H']|];\n    simpl in H; inversion H. subst. assumption.\nQed.\n\n(*\nLemma typeCheck_correct2 : forall (e:exp) (t:type),\n    hasType e t -> typeOf <$> typeCheck e = Some t.\nProof.\n    intros e t H. induction H as [n|b|e1 e2 H1 IH1 H2 IH2|e1 e2 H1 IH1 H2 IH2].\n    - reflexivity.\n    - reflexivity.\n    - simpl. destruct (typeCheck e1) as [|t1 p1] eqn:E1, (typeCheck e2) as [|t2 p2] eqn:E2.\n        + simpl in IH1. inversion IH1. subst.\n\nShow.\n*)\n\n\n\n(*\n(* It is all very nice to define typeCheck with 'do' notations, but correct?    *)\nLemma typeCheck_correct : forall (e:exp),\n    typeOf <$> typeCheck e = typeOf <$> typeCheck' e.\nProof.    \n    induction e as [n|b|e1 IH1 e2 IH2|e1 IH1 e2 IH2].\n    - simpl. reflexivity.\n    - simpl. reflexivity.\n    -    \nShow.\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/type_check.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6725356599524707}}
{"text": "(* This file is distributed under the terms of the MIT License, also\n   known as the X11 Licence.  A copy of this license is in the README\n   file that accompanied the original distribution of this file.\n\n   Based on code written by:\n     Brian Aydemir\n     Arthur Charg\\'eraud *)\n\n(** Lemmas and tactics for working with and solving goals related to\n    non-membership in finite sets.  The main tactic of interest here\n    is [solve_notin].\n\n    Implicit arguments are declared by default in this library. *)\n\nRequire Import Coq.FSets.FSetInterface.\n\nRequire Import CoqFSetDecide.\n\n\n(* *********************************************************************** *)\n(** * Implementation *)\n\nModule Notin_fun\n  (E : DecidableType) (Import X : FSetInterface.WSfun E).\n\nModule Import D := CoqFSetDecide.WDecide_fun E X.\n\n\n(* *********************************************************************** *)\n(** * Facts about set non-membership *)\n\nSection Lemmas.\n\nVariables x y  : elt.\nVariable  s s' : X.t.\n\nLemma notin_empty_1 :\n  ~ In x empty.\nProof. fsetdec. Qed.\n\nLemma notin_add_1 :\n  ~ In y (add x s) ->\n  ~ E.eq x y.\nProof. fsetdec. Qed.\n\nLemma notin_add_1' :\n  ~ In y (add x s) ->\n  x <> y.\nProof. fsetdec. Qed.\n\nLemma notin_add_2 :\n  ~ In y (add x s) ->\n  ~ In y s.\nProof. fsetdec. Qed.\n\nLemma notin_add_3 :\n  ~ E.eq x y ->\n  ~ In y s ->\n  ~ In y (add x s).\nProof. fsetdec. Qed.\n\nLemma notin_singleton_1 :\n  ~ In y (singleton x) ->\n  ~ E.eq x y.\nProof. fsetdec. Qed.\n\nLemma notin_singleton_1' :\n  ~ In y (singleton x) ->\n  x <> y.\nProof. fsetdec. Qed.\n\nLemma notin_singleton_2 :\n  ~ E.eq x y ->\n  ~ In y (singleton x).\nProof. fsetdec. Qed.\n\nLemma notin_remove_1 :\n  ~ In y (remove x s) ->\n  E.eq x y \\/ ~ In y s.\nProof. fsetdec. Qed.\n\nLemma notin_remove_2 :\n  ~ In y s ->\n  ~ In y (remove x s).\nProof. fsetdec. Qed.\n\nLemma notin_remove_3 :\n  E.eq x y ->\n  ~ In y (remove x s).\nProof. fsetdec. Qed.\n\nLemma notin_remove_3' :\n  x = y ->\n  ~ In y (remove x s).\nProof. fsetdec. Qed.\n\nLemma notin_union_1 :\n  ~ In x (union s s') ->\n  ~ In x s.\nProof. fsetdec. Qed.\n\nLemma notin_union_2 :\n  ~ In x (union s s') ->\n  ~ In x s'.\nProof. fsetdec. Qed.\n\nLemma notin_union_3 :\n  ~ In x s ->\n  ~ In x s' ->\n  ~ In x (union s s').\nProof. fsetdec. Qed.\n\nLemma notin_inter_1 :\n  ~ In x (inter s s') ->\n  ~ In x s \\/ ~ In x s'.\nProof. fsetdec. Qed.\n\nLemma notin_inter_2 :\n  ~ In x s ->\n  ~ In x (inter s s').\nProof. fsetdec. Qed.\n\nLemma notin_inter_3 :\n  ~ In x s' ->\n  ~ In x (inter s s').\nProof. fsetdec. Qed.\n\nLemma notin_diff_1 :\n  ~ In x (diff s s') ->\n  ~ In x s \\/ In x s'.\nProof. fsetdec. Qed.\n\nLemma notin_diff_2 :\n  ~ In x s ->\n  ~ In x (diff s s').\nProof. fsetdec. Qed.\n\nLemma notin_diff_3 :\n  In x s' ->\n  ~ In x (diff s s').\nProof. fsetdec. Qed.\n\nEnd Lemmas.\n\n\n(* *********************************************************************** *)\n(** * Hints *)\n\nHint Resolve\n  @notin_empty_1 @notin_add_3 @notin_singleton_2 @notin_remove_2\n  @notin_remove_3 @notin_remove_3' @notin_union_3 @notin_inter_2\n  @notin_inter_3 @notin_diff_2 @notin_diff_3.\n\n\n(* *********************************************************************** *)\n(** * Tactics for non-membership *)\n\n(** [destruct_notin] decomposes all hypotheses of the form [~ In x s]. *)\n\nLtac destruct_notin :=\n  match goal with\n    | H : In ?x ?s -> False |- _ =>\n      change (~ In x s) in H;\n      destruct_notin\n    | |- In ?x ?s -> False =>\n      change (~ In x s);\n      destruct_notin\n    | H : ~ In _ empty |- _ =>\n      clear H;\n      destruct_notin\n    | H : ~ In ?y (add ?x ?s) |- _ =>\n      let J1 := fresh \"NotInTac\" in\n      let J2 := fresh \"NotInTac\" in\n      pose proof H as J1;\n      pose proof H as J2;\n      apply notin_add_1 in H;\n      apply notin_add_1' in J1;\n      apply notin_add_2 in J2;\n      destruct_notin\n    | H : ~ In ?y (singleton ?x) |- _ =>\n      let J := fresh \"NotInTac\" in\n      pose proof H as J;\n      apply notin_singleton_1 in H;\n      apply notin_singleton_1' in J;\n      destruct_notin\n    | H : ~ In ?y (remove ?x ?s) |- _ =>\n      let J := fresh \"NotInTac\" in\n      apply notin_remove_1 in H;\n      destruct H as [J | J];\n      destruct_notin\n    | H : ~ In ?x (union ?s ?s') |- _ =>\n      let J := fresh \"NotInTac\" in\n      pose proof H as J;\n      apply notin_union_1 in H;\n      apply notin_union_2 in J;\n      destruct_notin\n    | H : ~ In ?x (inter ?s ?s') |- _ =>\n      let J := fresh \"NotInTac\" in\n      apply notin_inter_1 in H;\n      destruct H as [J | J];\n      destruct_notin\n    | H : ~ In ?x (diff ?s ?s') |- _ =>\n      let J := fresh \"NotInTac\" in\n      apply notin_diff_1 in H;\n      destruct H as [J | J];\n      destruct_notin\n    | _ =>\n      idtac\n  end.\n\n(** [solve_notin] decomposes hypotheses of the form [~ In x s] and\n    then tries some simple heuristics for solving the resulting\n    goals. *)\n\nLtac solve_notin :=\n  intros;\n  destruct_notin;\n  repeat first [ apply notin_union_3\n               | apply notin_add_3\n               | apply notin_singleton_2\n               | apply notin_empty_1\n               ];\n  auto;\n  try tauto;\n  fail \"Not solvable by [solve_notin]; try [destruct_notin]\".\n\n\n(* *********************************************************************** *)\n(** * Examples and test cases *)\n\n(** These examples and test cases are not meant to be exhaustive. *)\n\nLemma test_solve_notin_1 : forall x E F G,\n  ~ In x (union E F) ->\n  ~ In x G ->\n  ~ In x (union E G).\nProof. solve_notin. Qed.\n\nLemma test_solve_notin_2 : forall x y E F G,\n  ~ In x (union E (union (singleton y) F)) ->\n  ~ In x G ->\n  ~ In x (singleton y) /\\ ~ In y (singleton x).\nProof. split. solve_notin. solve_notin. Qed.\n\nLemma test_solve_notin_3 : forall x y,\n  ~ E.eq x y ->\n  ~ In x (singleton y) /\\ ~ In y (singleton x).\nProof. split. solve_notin. solve_notin. Qed.\n\nLemma test_solve_notin_4 : forall x y E F G,\n  ~ In x (union E (union (singleton x) F)) ->\n  ~ In y G.\nProof. solve_notin. Qed.\n\nLemma test_solve_notin_5 : forall x y E F,\n  ~ In x (union E (union (singleton y) F)) ->\n  ~ In y E ->\n  ~ E.eq y x /\\ ~ E.eq x y.\nProof. split. solve_notin. solve_notin. Qed.\n\nLemma test_solve_notin_6 : forall x y E,\n  ~ In x (add y E) ->\n  ~ E.eq x y /\\ ~ In x E.\nProof. split. solve_notin. solve_notin. Qed.\n\nLemma test_solve_notin_7 : forall x,\n  ~ In x (singleton x) ->\n  False.\nProof. solve_notin. Qed.\n\nEnd Notin_fun.\n", "meta": {"author": "spire", "repo": "replib", "sha": "f296898c5a7c89787935095e116890725d0d16f3", "save_path": "github-repos/coq/spire-replib", "path": "github-repos/coq/spire-replib/replib-f296898c5a7c89787935095e116890725d0d16f3/meta/metatheory/FSetWeakNotin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6725282877703749}}
{"text": "(**\n  This library is concerned with finiteness of a set under some\n  projection operation. The motivation is to deal with types that\n  contain some sort of propositional part. That is, you might have a\n  set that would be represented in normal maths as $A = \\{ x \\,|\\, P\\,\n  x \\}$.\n\n  This set is represented by a Coq sigma types of the form [sig\n  P]. However finiteness of [sig P] isn't really very interesting: You\n  care about the number of the elements, x, but don't care about how\n  many proofs of P x there are.\n\n  We will work by talking about finiteness of the image of some\n  projection operation [p : A -> B]. Maybe [A] is a sigma type like\n  above and [p] is projection onto the first coordinate. We carefully\n  _don't_ construct the type that is the image of [p]: that would have\n  exactly the same problems as the original type (two apparently\n  identical elements are different because we don't have proof\n  irrelevance).\n\n *)\n\nRequire Import Lists.List.\nRequire Import Program.Basics.\nRequire Import Logic.FinFun.\n\nRequire Import Top.FinSet.ProjSet.\nRequire Import Top.FinSet.NatMap.\n\nSet Implicit Arguments.\n\n(** * The disjoint sum of two finite sets is finite\n\n   With projections, this might mean an internal or external sum (is\n   the target [B + B'] or just [B]?). We'll prove the external version\n   here and then use a surjectivity result to prove the internal\n   version as a corollary later% (see section\n   \\ref{sec:int-sum-finite})%.\n\n   To prove this, you take a list for each projection, map the\n   elements into an option type and then join the two resulting lists\n   together. The new projection we need is a map [A + A' -> B + B']\n   which is constructed with [sumf], defined below (it's just the\n   external sum of two maps).\n\n *)\nLemma finite_sum {A A' B B': Type} (p : A -> B) (p' : A' -> B')\n      : FiniteProj p -> FiniteProj p' -> FiniteProj (sumf p p').\nProof.\n  (* Unfold finiteness and then unpack the assumptions *)\n  unfold FiniteProj.\n  intros exP exP'.\n  destruct exP as [ la fpA ].\n  destruct exP' as [ la' fpA' ].\n  (* The full element will be map inl la + map inr la' *)\n  exists ((map inl la) ++ (map inr la')).\n  unfold FullProj. intro aa.\n  (* Proceed by case analysis: is aa in A or A'? *)\n  destruct aa as [ a | a' ].\n  - clear fpA'.\n    apply in_proj_or_app; left.\n    apply (in_proj_map (nat_map_inl p p')).\n    unfold FullProj in fpA. apply fpA.\n  - clear fpA.\n    apply in_proj_or_app; right.\n    apply (in_proj_map (nat_map_inr p' p)).\n    unfold FullProj in fpA'. apply fpA'.\nQed.\n\n(** * The surjective image of a finite set is finite.\n\n   Here, we have to be a little careful with what we mean by\n   \"surjective\". Remember that our projection [p: A -> B] needn't\n   itself be surjective: we're only interested in the image of [p] as\n   a subset of [B] (onto which p is obviously surjective).\n\n   So we define a [SurjectiveProj] predicate. For the usual natural\n   square% (see equation \\ref{eq:natsq})%, saying that it is\n   [SurjectiveProj] means that [g] restricted to the image of [p]\n   surjects onto the image of [p']. We define this explicitly, rather\n   than with Coq's builtin [Surjective] predicate (because we don't\n   want to talk about the image of [p] as a type in itself).\n\n   Note that this surjectivity definition doesn't imply that the upper\n   map, f, is surjective. That's a good thing, because in the\n   motivating sigma type example, we definitely don't want to claim\n   that we can map to every proof \"upstairs\".\n\n*)\n\nDefinition SurjectiveProj\n           {A B A' B' : Type} (p : A -> B) (p' : A' -> B') (m : nat_map p p') :=\n  forall a' : A', exists a : A, nm_bot m (p a) = p' a'.\n\nLemma finite_surj\n      {A A' B B' : Type} (p : A -> B) (p' : A' -> B') (m : nat_map p p')\n  : FiniteProj p -> SurjectiveProj m -> FiniteProj p'.\nProof.\n  unfold FiniteProj.\n  intros fullP surjH.\n  destruct fullP as [l fullH].\n  exists (map (nm_top m) l).\n  unfold FullProj; intro a'.\n  unfold SurjectiveProj in surjH.\n  destruct (surjH a') as [ a aH ]; clear surjH.\n  rewrite <- aH.\n  apply in_proj_map.\n  unfold FullProj in fullH.\n  apply fullH.\nQed.\n\n(** There's a degenerate case of [finite_surj], where we actually just\n   have a second (surjective) projection to apply after [p]. Note that\n   this asks for a genuine surjection from [B] to [B']. You could\n   weaken this slightly, but at that point you may as well just use\n   [finite_surj] explicitly.  *)\n\nLemma finite_surj_vert {A B B' : Type} (p : A -> B) (q : B -> B')\n  : FiniteProj p -> Surjective q -> FiniteProj (compose q p).\nProof.\n  intros fpH surjH.\n  set (m0 := nat_map_v p).\n  set (m1 := nat_map_diag id q).\n  assert (midH : forall b : B, nm_top m1 b = nm_bot m0 b); auto.\n  apply (finite_surj (m := nat_map_comp_v m0 m1 midH)); auto.\n  unfold SurjectiveProj, compose; simpl.\n  intro a. exists a. auto.\nQed.\n\n(** ** Finiteness of an internal sum %\\label{sec:int-sum-finite}%\n\n  Now for the promised internal sum version of [finite_sum]. The proof\n  of this just goes by composing the external sum with a folding\n  operation, [codiag: A + A -> A], defined in the obvious way.\n\n *)\nDefinition codiag {A : Type} (a : A + A) : A :=\n  match a with\n  | inl a => a\n  | inr a => a\n  end.\n\nLemma surj_codiag A : Surjective (@codiag A).\nProof.\n  unfold Surjective.\n  intro a.\n  exists (inl a).\n  unfold codiag.\n  exact eq_refl.\nQed.\n\nDefinition internal_sumf {A A' B} (f : A -> B) (g : A' -> B) : A + A' -> B :=\n  compose codiag (sumf f g).\n\nLemma finite_sum_internal {A A' B} (p : A -> B) (p' : A' -> B)\n  : FiniteProj p -> FiniteProj p' -> FiniteProj (internal_sumf p p').\nProof.\n  unfold internal_sumf.\n  intros fpH fpH'.\n  apply finite_surj_vert.\n  - exact (finite_sum fpH fpH').\n  - exact (@surj_codiag B).\nQed.\n\n(** * Finiteness with injections\n\n   Now we want to prove something related to the basic result from\n   maths that if I have an injection [f : X -> Y] and know that [Y] is\n   finite, then [X] must be finite too.\n\n   To prove finiteness in Coq, you need to build some form of a\n   listing of [X]. Merely knowing that [f] is injective isn't going to\n   be enough to construct this from a listing of [Y]: we'd need some\n   non-constructive choice axiom to pick elements of [X] in the\n   inverse image. In classical maths, a map [f] is injective if and\n   only if it has a left inverse [g] (so $g \\circ f =\n   \\mathrm{id}$). We'll ask to be given this map, which does the \"find\n   something in the inverse image\" operation for us.\n\n   In practice, that's a pain to produce, so we'll actually ask for a\n   map [g : Y -> option X], satisfying [g (f a) = Some a]. Note that\n   this implies that no element in the image of [f] gets mapped to\n   [None], so in a non-constructive setting we could extend [g] to a\n   map [Y -> X] by mapping [None] to some arbitrary element of [X].\n\n   ** Mapping and filtering\n\n   If we start with a listing of the image of [p'], we can apply our\n   partial inverse to each element to get a list of [option\n   A]'s. Filtering out the [None]'s gives a list of elements of [A],\n   which generate our listing of the image of [p].\n*)\n\nSection map_filter.\n  Variables (A A' : Type).\n  Variable (h : A' -> option A).\n\n  Fixpoint map_filter (l : list A') : list A :=\n    match l with\n    | nil => nil\n    | cons a' l' => match h a' with\n                    | Some a => a :: map_filter l'\n                    | None => map_filter l'\n                    end\n    end.\n\n  Lemma map_filter_inv a' l\n    : map_filter (a' :: l) = match h a' with\n                                | Some a => a :: map_filter l\n                                | None => map_filter l\n                                end.\n  Proof. reflexivity. Qed.\n\n  (**\n\n     We want to precisely characterise when an element is in the image\n     of [map_filter]. To make sense of this, we need to do a little\n     more setup. The commutative diagram we're interested in is:\n     % \\begin{equation}\n       \\begin{tikzcd}\n         A' \\arrow[r, \"h\"] \\arrow[d, \"p'\"] &\n         \\mathrm{option}\\,A \\arrow[d] &\n         A \\arrow[l, \"\\mathrm{Some}\"'] \\arrow[d, \"p\"]\n         \\\\\n         B' \\arrow[r, \"k\"] &\n         \\mathrm{option}\\,B &\n         B\n         \\arrow[l, \"\\mathrm{Some}\"']\n       \\end{tikzcd}\n     \\end{equation} %\n     where the vertical map in the middle is [option_map p]. The right hand\n     square commutes for free by the definition of [option_map]. Commutativity\n     of the left hand square is the [natH] hypothesis below.\n\n   *)\n\n  Variables (B B' : Type).\n  Variable (k : B' -> option B).\n  Variable (p : A -> B).\n  Variable (p' : A' -> B').\n  Hypothesis (natH: forall a', option_map p (h a') = k (p' a')).\n\n  Lemma in_proj_map_filter l a\n    : (exists a', k (p' a') = Some (p a) /\\ InProj p' (p' a') l) ->\n      InProj p (p a) (map_filter l).\n  Proof.\n    intros H; destruct H as [ a' H ]; destruct H as [ mapH inH ].\n    induction l as [ | x' l IH ].\n    - contradiction inH.\n    - destruct (in_proj_inv inH); clear inH.\n      + clear IH.\n        (* This is the case where we're supposed to get a hit at the\n           start of the list. We have some x' where p' x' = p' a' (both\n           elements of B'). *)\n        rewrite <- H in mapH; clear H.\n        rewrite <- (natH x') in mapH; clear natH.\n        (* Now mapH says that option_map p (h x') = Some (p a).\n           That must mean h x is Some something (by looking at the\n           definition of option_map) *)\n        case_eq (h x');\n          try (intro U; rewrite U in mapH; discriminate mapH).\n        intros x hx'H.\n        (* Now we can do a little unpacking to conclude that p x\n           equals p a. *)\n        assert (p_eq_H: p x = p a);\n          try (rewrite hx'H in mapH; inversion mapH; exact eq_refl).\n        rewrite map_filter_inv, hx'H.\n        apply in_proj_eq.\n        exact p_eq_H.\n      + (* This is the easier case, where we just pass stuff through\n           induction. *)\n        enough (InProj p (p a) (map_filter l)) as Hrst.\n        * rewrite map_filter_inv.\n          destruct (h x'); try (apply in_proj_cons); exact Hrst.\n        * apply IH. exact H.\n  Qed.\n\n  Lemma full_proj_map_filter l\n    : (forall a, exists a' : A', k (p' a') = Some (p a) /\\ InProj p' (p' a') l) ->\n      FullProj p (map_filter l).\n  Proof.\n    intro H; unfold FullProj; intro a.\n    apply in_proj_map_filter, H.\n  Qed.\n\n  Variable f : A -> A'.\n  Variable g : B -> B'.\n  Hypothesis natfgH: forall a, p' (f a) = g (p a).\n  Hypothesis kleftH: forall a, k (g (p a)) = Some (p a).\n\n  (** We finally get to the full lemma. The big commutative diagram\n     can be drawn as:\n     % \\begin{equation}\n       \\begin{tikzcd}\n         A \\arrow[rr, \"f\"] \\arrow[dr, hookrightarrow] \\arrow[ddd, \"p\"'] &\n         &\n         A' \\arrow[ld, \"h\"] \\arrow[ddd, \"p'\"]\n         \\\\\n           & \\mathrm{option}\\,A \\arrow[d, \"\\mathrm{option\\_map}(p)\"'] &\n         \\\\\n           & \\mathrm{option}\\,B &\n         \\\\\n         B \\arrow[ur, hookrightarrow] \\arrow[rr, \"g\"]& & B' \\arrow[ul, \"k\"']\n       \\end{tikzcd}\n     \\end{equation} %\n\n\n     The left hand square commutes by definition of [option_map]. The outer\n     square commutes, by the hypothesis [natfgH]. The bottom left half of the\n     diagram commutes by the hypothesis [kleftH] (because\n     [option_map p (Some a) = Some (p a)]).\n\n     The point is that the existence of [k], which acts as (almost) the left\n     inverse of the restriction of [g] to the image of [p] is equivalent to\n     injectivity of [g] on the image of [p] in a non-constructive setting.\n   *)\n\n  Lemma finite_left_inverse : FiniteProj p' -> FiniteProj p.\n  Proof.\n    unfold FiniteProj.\n    destruct 1 as [ l' l'H ].\n    exists (map_filter l').\n    apply full_proj_map_filter.\n    intro a.\n    unfold FullProj in l'H.\n    exists (f a).\n    rewrite (natfgH a).\n    rewrite kleftH; clear kleftH.\n    constructor; try exact eq_refl.\n    enough (H: g (p a) = p' (f a)).\n    - rewrite H. apply l'H.\n    - rewrite natfgH; exact eq_refl.\n  Qed.\nEnd map_filter.\n\n(** * Finiteness of option types\n\n     This section shows that a type is finite if and only if the\n     corresponding option type is. Use [finite_option_intro] to infer\n     that an option type is finite. More usefully,\n     [finite_option_elim] allows you to prove finiteness of an option\n     type in order to conclude finiteness of the underlying type.\n\n*)\n\nSection finite_option.\n  Variables (A B : Type).\n  Variable (p : A -> B).\n\n  Lemma finite_option_intro : FiniteProj p -> FiniteProj (option_map p).\n  Proof.\n    unfold FiniteProj.\n    intro finP.\n    destruct finP as [ l fullL ].\n    exists (cons None (map Some l)).\n    unfold FullProj.\n    intro x; destruct x as [ a | ].\n    - apply in_proj_cons.\n      apply (in_proj_map (nat_map_some p)).\n      unfold FullProj in fullL. apply fullL.\n    - apply in_proj_eq; reflexivity.\n  Qed.\n\n  Lemma finite_option_elim : FiniteProj (option_map p) -> FiniteProj p.\n  Proof.\n    assert (H0: (forall a' : option A,\n                    option_map p (id a') = id (option_map p a')));\n      try reflexivity.\n    assert (H1: forall a : A, option_map p (Some a) = Some (p a));\n      try reflexivity.\n    assert (H2: forall a : A, id (Some (p a)) = Some (p a));\n      try reflexivity.\n    apply (finite_left_inverse id id p H0 Some Some H1 H2).\n  Qed.\nEnd finite_option.\n\n(** * An easier way to prove finiteness with surjectivity\n\n    The [finite_surj] lemma is all very well, but it's sometimes a bit\n    difficult to construct exactly the map you want. When trying to\n    define a surjection from [p : A -> B] to [p' : A' -> B'], there\n    might be some elements, [a], that we don't care about and just\n    want to map to [None]. In this section, we do the leg-work to make\n    this approach work properly.\n\n*)\nModule surj_finite_option.\n  Definition lift_opt {A B : Type} (f : A -> option B) (oa : option A)\n  : option B :=\n    match oa with\n    | Some a => f a\n    | None => None\n    end.\n\n  Section surj_finite_option.\n    Variables A A' B B' : Type.\n    Variable p: A -> B.\n    Variable p': A' -> B'.\n    Variable f: A -> option A'.\n    Variable g: B -> option B'.\n\n    Hypothesis finP : FiniteProj p.\n    Hypothesis natH : forall a, option_map p' (f a) = g (p a).\n    Hypothesis surjH : forall a' : A', exists a : A, g (p a) = Some (p' a').\n\n    Local Definition xp := option_map p.\n    Local Definition xp' := option_map p'.\n    Local Definition xf := lift_opt f.\n    Local Definition xg := lift_opt g.\n\n    Local Lemma OfinP : FiniteProj xp.\n    Proof.\n      exact (finite_option_intro finP).\n    Qed.\n\n    Local Lemma OnatH: is_nat_map xp xp' (xf, xg).\n    Proof.\n      unfold is_nat_map. intro a; destruct a; simpl; auto.\n    Qed.\n\n    Local Lemma OsurjH : SurjectiveProj (exist _ (xf, xg) OnatH).\n    Proof.\n      unfold SurjectiveProj; intro x'; destruct x' as [ a' | ].\n      - specialize (surjH a').\n        destruct surjH as [ a H ]; clear surjH.\n        exists (Some a).\n        auto.\n      - exists None.\n        auto.\n    Qed.\n\n    Lemma finite_surj_option : FiniteProj p'.\n    Proof.\n      apply finite_option_elim.\n      apply (finite_surj OfinP OsurjH).\n    Qed.\n  End surj_finite_option.\nEnd surj_finite_option.\n\nImport surj_finite_option.\nExport surj_finite_option.\n\nLocal Lemma decompose_pair_eq {A B : Type} (a a' : A) (b b' : B)\n  : (a, b) = (a', b') -> a = a' /\\ b = b'.\nProof.\n  intro H; constructor.\n  - pose proof (f_equal fst H) as Ha; simpl in Ha. assumption.\n  - pose proof (f_equal snd H) as Hb; simpl in Hb. assumption.\nQed.\n\nLemma in_proj_neq {A B : Type} (p : A -> B) b a l\n  : p a <> b -> InProj p b (a :: l) -> InProj p b l.\nProof.\n  intros neq consH.\n  destruct (in_proj_inv consH); tauto.\nQed.\n\n(** * Sections of projections\n\n    It isn't the case that we can always make a section for a\n    projection (as defined in this theory) - the whole point is that\n    [p : A -> B] probably isn't surjective. However, if we are given\n    some element of A then we can map elements of B that we don't care\n    about to that point. If [l] is nonempty, we could just use the\n    first element of the list, but I think it's cleaner to pass in\n    this element explicitly (which punts on the problems you get\n    otherwise when [A] is empty).\n *)\nSection proj_section.\n  Variables A B : Type.\n  Hypothesis decB : forall x y : B, {x = y} + {x <> y}.\n  Variable p : A -> B.\n  Variable a0 : A.\n\n  Fixpoint proj_section (b : B) (l : list A) : A :=\n    match l with\n    | nil => a0\n    | a :: l' => match decB (p a) b with\n                 | left eqH => a\n                 | right neH => proj_section b l'\n                 end\n    end.\n\n  Lemma proj_section_if_in b l\n    : In b (map p l) -> p (proj_section b l) = b.\n  Proof.\n    induction l as [ | a l IH ]; try contradiction.\n    unfold proj_section; fold proj_section.\n    destruct (decB (p a) b) as [ | neH ]; auto.\n    destruct 1 as [ | inH ]; tauto.\n  Qed.\n\n  Lemma full_proj_section_is_section l\n    : FullProj p l ->\n      forall a : A, p (proj_section (p a) l) = p a.\n  Proof.\n    intros.\n    apply proj_section_if_in.\n    unfold FullProj, InProj in *; auto.\n  Qed.\nEnd proj_section.\n\n(** * Inverses of surjective natural maps\n\n  *)\nLemma map_compose\n      {A B C : Type}\n      (f : A -> B) (g : B -> C) (l : list A)\n  : map (compose g f) l = map g (map f l).\nProof.\n  induction l as [ | a l IH ]; auto.\n  rewrite map_cons, map_cons, map_cons.\n  unfold compose at 1.\n  apply f_equal; auto.\nQed.\n\nSection surj_map_is_invertible.\n  Variables A B C D : Type.\n  Hypothesis decB : forall x y : B, {x = y} + {x <> y}.\n  Hypothesis decD : forall x y : D, {x = y} + {x <> y}.\n  Variable p : A -> B.\n  Variable q : C -> D.\n  Variable f : nat_map p q.\n\n  Variable a0 : A.\n\n  Local Fixpoint bot_map (l : list A) (d : D) : B :=\n    match l with\n    | nil => p a0\n    | a :: l' => match decD (nm_bot f (p a)) d with\n                 | left _ => p a\n                 | right _ => bot_map l' d\n                 end\n    end.\n\n  Local Lemma bot_map_if_in d l\n    : In d (map (compose (nm_bot f) p) l) ->\n      nm_bot f (bot_map l d) = d.\n  Proof.\n    induction l as [ | a l IH ]; try contradiction.\n    unfold bot_map; fold bot_map.\n    destruct (decD (nm_bot f (p a)) d); auto.\n    rewrite map_cons.\n    destruct 1; tauto.\n  Qed.\n\n  Local Lemma in_map_compose_if c l\n    : SurjectiveProj f -> FullProj p l ->\n      In (q c) (map (compose (nm_bot f) p) l).\n  Proof.\n    intros surjH fullH.\n    specialize (surjH c).\n    destruct surjH as [ a natH ]; rewrite <- natH; clear natH c.\n    (* So we need to use fullness of l wrt p. This gives us some\n       element of l that maps down to the same element as [a] does.\n     *)\n    specialize (fullH a); unfold InProj in fullH.\n    rewrite in_map_iff in fullH.\n    destruct fullH as [ a' H ]; destruct H as [ peqH inH ].\n    rewrite map_compose.\n    apply in_map.\n    rewrite <- peqH.\n    apply in_map; assumption.\n  Qed.\n\n  Local Definition top_map (l : list A) (c : C) : A :=\n    proj_section decB p a0 (bot_map l (q c)) l.\n\n  Local Lemma bot_map_in_proj (l : list A) d\n    : In d (map (compose (nm_bot f) p) l) ->\n      InProj p (bot_map l d) l.\n  Proof.\n    induction l as [ | a l IH ]; auto.\n    unfold bot_map; fold bot_map.\n    intro inH.\n    unfold InProj in *; rewrite map_cons.\n    destruct (decD (nm_bot f (p a)) d) as [ <- | neH ].\n    - apply in_eq.\n    - destruct inH as [ | inH ]; try tauto.\n      apply in_cons; auto.\n  Qed.\n\n  Variable l : list A.\n  Hypothesis surjH : SurjectiveProj f.\n  Hypothesis fullH : FullProj p l.\n\n  Local Lemma bot_map_exists_lift c\n    : exists a, p a = bot_map l (q c) /\\ In a l.\n  Proof.\n    rewrite <- in_map_iff.\n    apply bot_map_in_proj.\n    apply in_map_compose_if; auto.\n  Qed.\n\n  Local Lemma inv_is_nat_map : is_nat_map q p (top_map l, bot_map l).\n  Proof.\n    intros c; simpl.\n    unfold top_map.\n    destruct (bot_map_exists_lift c) as [ a H ].\n    destruct H as [ <- inH ].\n    apply full_proj_section_is_section; auto.\n  Qed.\n\n  Definition surj_nat_map_right_inverse : nat_map q p :=\n    exist _ (top_map l, bot_map l) inv_is_nat_map.\n\n  Lemma surj_map_is_invertible c\n    : nm_bot (nat_map_comp_h surj_nat_map_right_inverse f) (q c) = q c.\n  Proof.\n    simpl; unfold compose.\n    apply bot_map_if_in.\n    apply in_map_compose_if; auto.\n  Qed.\n\nEnd surj_map_is_invertible.\n", "meta": {"author": "rswarbrick", "repo": "eder84", "sha": "682fa4d81ba690a88ea9b6eedee655901c8189b6", "save_path": "github-repos/coq/rswarbrick-eder84", "path": "github-repos/coq/rswarbrick-eder84/eder84-682fa4d81ba690a88ea9b6eedee655901c8189b6/FinSet/FinSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.793105941403651, "lm_q1q2_score": 0.6725282733825243}}
{"text": "Require Import Arith.\nRequire Import NatIntf CanonicalNatImpl CommutingNatIntf.\n\n(* Compose a function with itself `n` times *)\nFixpoint iterate A (n:nat) (f:A -> A) (x:A) : A :=\n  match n with\n  | 0 => x\n  | S n' => f (iterate A n' f x)\n  end.\n\n(* An extension of CommutingNaturalInterface that includes various correctness\n * properties that correct implementations of the natural numbers should\n * satisfy. *)\nModule Type VerifiedNatInterface <: CommutingNatInterface.\n  Parameter N : Type.\n\n  Parameter zero : N.\n  Parameter succ : N -> N.\n  Parameter pred : N -> N.\n  Parameter add : N -> N -> N.\n  Parameter sub : N -> N -> N.\n  Parameter comp : N -> N -> comparison.\n  Parameter convert : N -> nat.\n\n  Axiom convert_injective : forall n n' : N, convert n = convert n' -> n = n'.\n  Axiom zero_commutes : convert zero = CanonicalNat.zero.\n  Axiom succ_commutes : forall n : N,\n    convert (succ n) = CanonicalNat.succ (convert n).\n  Axiom pred_commutes : forall n : N,\n    convert (pred n) = CanonicalNat.pred (convert n).\n  Axiom add_commutes : forall n n' : N,\n    convert (add n n') = CanonicalNat.add (convert n) (convert n').\n  Axiom sub_commutes : forall n n' : N,\n    convert (sub n n') = CanonicalNat.sub (convert n) (convert n').\n  Axiom comp_commutes : forall n n' : N,\n    comp n n' = CanonicalNat.comp (convert n) (convert n').\n\n  (* Correctness properties for nat implementations *)\n  Axiom unary_repr : forall (n:N),\n    iterate _ (convert n) succ zero = n.\n\n  Axiom pos_succ : forall (n:N), comp n zero = Gt -> exists n', n = succ n'.\n  Axiom pred_succ : forall (n:N), pred (succ n) = n.\n\n  Axiom add_zero : forall (n:N), add zero n = n.\n  Axiom add_succ : forall (m n:N), add (succ m) n = succ (add m n).\n  Axiom add_succ_right : forall (m n:N), add m (succ n) = add (succ m) n.\n\n  Axiom sub_zero : forall (n:N), sub n zero = n.\n  Axiom sub_succ : forall (m n:N), sub (succ m) (succ n) = sub m n.\n  Axiom sub_pred : forall (m n:N), sub (pred m) n = sub m (succ n).\n\n  Axiom comp_zero : forall (n:N), comp n zero <> Lt.\n  Axiom comp_succ : forall (m n:N), comp (succ m) (succ n) = comp m n.\n  Axiom comp_eq : forall (m n:N), comp m n = Eq <-> m = n.\n  Axiom comp_zero_succ : forall (n:N), comp zero (succ n) = Lt.\nEnd VerifiedNatInterface.\n\n(* A functor which produces an implementation of VerifedNatInterface from an\n * implementation of CommutingNatInterface. *)\nModule VerifiedCommutingNat (C : CommutingNatInterface)\n    : VerifiedNatInterface.\n  Definition N := C.N.\n  Definition zero := C.zero.\n  Definition succ := C.succ.\n  Definition pred := C.pred.\n  Definition add := C.add.\n  Definition sub := C.sub.\n  Definition comp := C.comp.\n  Definition convert := C.convert.\n  Definition convert_injective := C.convert_injective.\n  Definition zero_commutes := C.zero_commutes.\n  Definition succ_commutes := C.succ_commutes.\n  Definition pred_commutes := C.pred_commutes.\n  Definition add_commutes := C.add_commutes.\n  Definition sub_commutes := C.sub_commutes.\n  Definition comp_commutes := C.comp_commutes.\n\n  Lemma unary_repr' : forall (u:nat) (n:N),\n      C.convert n = u -> iterate _ u C.succ C.zero = n.\n    intros u.\n    induction u;\n        intros n Heqn; simpl; apply convert_injective.\n      (* 0 *)\n      rewrite zero_commutes.\n      rewrite Heqn.\n      auto.\n      (* S u *)\n      rewrite succ_commutes.\n      rewrite Heqn.\n      assert (C.convert (C.pred n) = u) as Heqn'.\n        rewrite pred_commutes.\n        rewrite Heqn.\n        auto.\n      rewrite (IHu _ Heqn').\n      rewrite pred_commutes.\n      rewrite Heqn.\n      auto.\n  Defined.\n\n  Lemma unary_repr : forall (n:N),\n      iterate _ (C.convert n) C.succ C.zero = n.\n    intros n.\n    apply (unary_repr' (C.convert n) n); trivial.\n  Defined.\n\n  Lemma pos_succ : forall (n:N),\n      comp n C.zero = Gt -> exists n', n = succ n'.\n    intros n.\n    rewrite comp_commutes.\n    rewrite zero_commutes.\n    remember (C.convert n) as m.\n    destruct m;\n        symmetry in Heqm; simpl.\n      (* 0 *)\n      congruence.\n      (* S m *)\n      intros _.\n      refine (ex_intro _ (pred n) _).\n        apply C.convert_injective.\n        rewrite succ_commutes.\n        rewrite pred_commutes.\n        rewrite Heqm.\n        simpl.\n        reflexivity.\n  Defined.\n\n  Lemma pred_succ : forall (n:N), pred (succ n) = n.\n    intros n.\n    apply C.convert_injective.\n    rewrite C.pred_commutes.\n    rewrite C.succ_commutes.\n    auto.\n  Defined.\n\n  Lemma add_zero : forall (n:N), add C.zero n = n.\n    intros n.\n    apply C.convert_injective.\n    rewrite (C.add_commutes _ _).\n    rewrite (C.zero_commutes).\n    auto.\n  Defined.\n\n  Lemma add_succ : forall (m n : N), add (succ m) n = succ (add m n).\n    intros m n.\n    apply C.convert_injective.\n    rewrite (C.add_commutes _ _).\n    rewrite (C.succ_commutes _).\n    rewrite (C.succ_commutes _).\n    rewrite (C.add_commutes _ _).\n    simpl.\n    reflexivity.\n  Defined.\n\n  Lemma add_succ_right : forall (m n : N),\n      add m (succ n) = add (succ m) n.\n    intros m n.\n    apply C.convert_injective.\n    rewrite (C.add_commutes _ _).\n    rewrite (C.succ_commutes _).\n    rewrite (C.add_commutes _ _).\n    rewrite (C.succ_commutes _).\n    rewrite plus_Snm_nSm.\n    reflexivity.\n  Defined.\n\n  Lemma sub_zero : forall (n : N), sub n C.zero = n.\n    intros n.\n    apply C.convert_injective.\n    rewrite (C.sub_commutes _ _).\n    rewrite C.zero_commutes.\n    destruct (C.convert n); auto.\n  Defined.\n\n  Lemma sub_succ : forall (m n:N), sub (succ m) (succ n) = sub m n.\n    intros m n.\n    apply C.convert_injective.\n    rewrite C.sub_commutes.\n    rewrite C.sub_commutes.\n    rewrite C.succ_commutes.\n    rewrite C.succ_commutes.\n    auto.\n  Defined.\n\n  Lemma sub_pred : forall (m n:N), sub (pred m) n = sub m (succ n).\n    intros m n.\n    apply C.convert_injective.\n    rewrite C.sub_commutes.\n    rewrite C.sub_commutes.\n    rewrite C.pred_commutes.\n    rewrite C.succ_commutes.\n    destruct (C.convert m);\n      simpl; reflexivity.\n  Defined.\n\n  Lemma comp_zero :forall (n:N), comp n C.zero <> Lt.\n    intros n.\n    rewrite C.comp_commutes.\n    rewrite C.zero_commutes.\n    destruct (C.convert n);\n      simpl; congruence.\n  Defined.\n\n  Lemma comp_succ : forall (m n:N), comp (succ m) (succ n) = comp m n.\n    intros m n.\n    rewrite C.comp_commutes.\n    rewrite C.comp_commutes.\n    rewrite C.succ_commutes.\n    rewrite C.succ_commutes.\n    auto.\n  Defined.\n\n  Lemma comp_eq : forall (m n:N), comp m n = Eq <-> m = n.\n    intros m n.\n    refine (conj _ _).\n      (* -> *)\n      rewrite (C.comp_commutes _ _).\n      intros Hcomp.\n      apply C.convert_injective.\n      apply (CanonicalNatImpl.comp_eq).\n      assumption.\n      (* <- *)\n      intros Heq.\n      rewrite Heq.\n      rewrite (C.comp_commutes _ _).\n      apply (CanonicalNatImpl.comp_eq).\n      reflexivity.\n  Defined.\n\n  Lemma comp_zero_succ : forall (n:N), comp C.zero (succ n) = Lt.\n    intros n.\n    rewrite (C.comp_commutes _ _).\n    rewrite C.zero_commutes.\n    rewrite (C.succ_commutes _).\n    simpl.\n    reflexivity.\n  Defined.\nEnd VerifiedCommutingNat.", "meta": {"author": "ethantkoenig", "repo": "CS-4860-Project", "sha": "708f349803867e9cf216cfaea7776deeb6122d04", "save_path": "github-repos/coq/ethantkoenig-CS-4860-Project", "path": "github-repos/coq/ethantkoenig-CS-4860-Project/CS-4860-Project-708f349803867e9cf216cfaea7776deeb6122d04/naturals/VerifiedNatIntf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6724742727622689}}
{"text": "Require Import PPS.Env.\n\nSet Implicit Arguments.\n\nInductive AExp : Type :=\n| AVar   : nat    -> AExp\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| BLess  : AExp -> AExp -> BExp.\n\nNotation \"e1 :<: e2\" := (BLess e1 e2) (at level 40, left associativity).\nNotation \"e1 :+: e2\" := (APlus e1 e2) (at level 40, left associativity).\nNotation \"e1 :-: e2\" := (AMinus e1 e2) (at level 40, left associativity).\nNotation \"e1 :*: e2\" := (AMult e1 e2) (at level 40, left associativity).\n\nDefinition Env := listMap nat nat.\n\nFixpoint aeval (e : AExp) (Sigma : Env) : option nat :=\n  match e with\n  | ANum n       => Some n\n  | AVar ident   => lookup Nat.eqb Sigma ident\n  | APlus e1 e2  =>\n    match aeval e1 Sigma, aeval e2 Sigma with\n    | Some v1, Some v2 => Some (v1 + v2)\n    | _, _ => None\n    end\n  | AMinus e1 e2 =>\n    match aeval e1 Sigma, aeval e2 Sigma with\n    | Some v1, Some v2 => Some (v1 - v2)\n    | _, _ => None\n    end\n  | AMult e1 e2  =>\n    match aeval e1 Sigma, aeval e2 Sigma with\n    | Some v1, Some v2 => Some (v1 * v2)\n    | _, _ => None\n    end\n  end.\n\nFixpoint beval (e : BExp) (Sigma : Env) : option bool :=\n  match e with\n  | BTrue       => Some true\n  | BFalse      => Some false\n  | BLess e1 e2 =>\n    match aeval e1 Sigma, aeval e2 Sigma with\n    | Some v1, Some v2 => Some (Nat.leb v1 v2)\n    | _, _ => None\n    end\n  end.\n", "meta": {"author": "nbun", "repo": "pps-coq", "sha": "4b7aa1a37e7fb80549d3d3e32b6f37a1c239660f", "save_path": "github-repos/coq/nbun-pps-coq", "path": "github-repos/coq/nbun-pps-coq/pps-coq-4b7aa1a37e7fb80549d3d3e32b6f37a1c239660f/src/Exercises/S0/Exp_2_Var.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6724742656710665}}
{"text": "Require Import rt.util.all.\nRequire Import rt.model.basic.job rt.model.basic.arrival_sequence rt.model.basic.schedule\n               rt.model.basic.platform rt.model.basic.priority.\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat fintype bigop seq path.\n\nModule ConcreteScheduler.\n\n  Import Job ArrivalSequence Schedule Platform Priority.\n  \n  Section Implementation.\n    \n    Context {Job: eqType}.\n    Variable job_cost: Job -> time.\n\n    (* Let num_cpus denote the number of processors, ...*)\n    Variable num_cpus: nat.\n\n    (* ... and let arr_seq be any arrival sequence.*)\n    Variable arr_seq: arrival_sequence Job.\n\n    (* Assume a JLDP policy is given. *)\n    Variable higher_eq_priority: JLDP_policy arr_seq.\n\n    (* Consider the list of pending jobs at time t. *)\n    Definition jobs_pending_at (sched: schedule num_cpus arr_seq) (t: time) :=\n      [seq j <- jobs_arrived_up_to arr_seq t | pending job_cost sched j t].\n\n    (* Next, we sort this list by priority. *)\n    Definition sorted_pending_jobs (sched: schedule num_cpus arr_seq) (t: time) :=\n      sort (higher_eq_priority t) (jobs_pending_at sched t).\n\n    (* Starting from the empty schedule as a base, ... *)\n    Definition empty_schedule : schedule num_cpus arr_seq :=\n      fun t cpu => None.\n\n    (* ..., we redefine the mapping of jobs to processors at any time t as follows.\n       The i-th job in the sorted list is assigned to the i-th cpu, or to None\n       if the list is short. *)\n    Definition update_schedule (prev_sched: schedule num_cpus arr_seq)\n                               (t_next: time) : schedule num_cpus arr_seq :=\n      fun cpu t =>\n        if t == t_next then\n          nth_or_none (sorted_pending_jobs prev_sched t) cpu\n        else prev_sched cpu t.\n    \n    (* The schedule is iteratively constructed by applying assign_jobs at every time t, ... *)\n    Fixpoint schedule_prefix (t_max: time) : schedule num_cpus arr_seq := \n      if t_max is t_prev.+1 then\n        (* At time t_prev + 1, schedule jobs that have not completed by time t_prev. *)\n        update_schedule (schedule_prefix t_prev) t_prev.+1\n      else\n        (* At time 0, schedule any jobs that arrive. *)\n        update_schedule empty_schedule 0.\n\n    Definition scheduler (cpu: processor num_cpus) (t: time) := (schedule_prefix t) cpu t.\n\n  End Implementation.\n\n  Section Proofs.\n\n    Context {Job: eqType}.\n    Variable job_cost: Job -> time.\n\n    (* Assume a positive number of processors. *)\n    Variable num_cpus: nat.\n    Hypothesis H_at_least_one_cpu: num_cpus > 0.\n\n    (* Let arr_seq be any arrival sequence of jobs where ...*)\n    Variable arr_seq: arrival_sequence Job.\n    (* ...jobs have positive cost and...*)\n    Hypothesis H_job_cost_positive:\n      forall (j: JobIn arr_seq), job_cost_positive job_cost j.\n    (* ... at any time, there are no duplicates of the same job. *)\n    Hypothesis H_arrival_sequence_is_a_set :\n      arrival_sequence_is_a_set arr_seq.\n\n    (* Consider any JLDP policy higher_eq_priority that is transitive and total. *)\n    Variable higher_eq_priority: JLDP_policy arr_seq.\n    Hypothesis H_priority_transitive: forall t, transitive (higher_eq_priority t).\n    Hypothesis H_priority_total: forall t, total (higher_eq_priority t).\n\n    (* Let sched denote our concrete scheduler implementation. *)\n    Let sched := scheduler job_cost num_cpus arr_seq higher_eq_priority.\n\n    (* Next, we provide some helper lemmas about the scheduler construction. *)\n    Section HelperLemmas.\n      \n      (* First, we show that the scheduler preserves its prefixes. *)\n      Lemma scheduler_same_prefix :\n        forall t t_max cpu,\n          t <= t_max ->\n          schedule_prefix job_cost num_cpus arr_seq higher_eq_priority t_max cpu t =\n          scheduler job_cost num_cpus arr_seq higher_eq_priority cpu t.\n      Proof.\n        intros t t_max cpu LEt.\n        induction t_max.\n        {\n          by rewrite leqn0 in LEt; move: LEt => /eqP EQ; subst.\n        }\n        {\n          rewrite leq_eqVlt in LEt.\n          move: LEt => /orP [/eqP EQ | LESS]; first by subst.\n          {\n            feed IHt_max; first by done.\n            unfold schedule_prefix, update_schedule at 1.\n            assert (FALSE: t == t_max.+1 = false).\n            {\n              by apply negbTE; rewrite neq_ltn LESS orTb.\n            } rewrite FALSE.\n            by rewrite -IHt_max.\n          }\n        }\n      Qed.\n\n      (* With respect to the sorted list of pending jobs, ...*)\n      Let sorted_jobs (t: time) :=\n        sorted_pending_jobs job_cost num_cpus arr_seq higher_eq_priority sched t.\n\n      (* ..., we show that a job is mapped to a processor based on that list, ... *)\n      Lemma scheduler_nth_or_none_mapping :\n        forall t cpu x,\n          sched cpu t = x ->\n          nth_or_none (sorted_jobs t) cpu = x.\n      Proof.\n        intros t cpu x SCHED.\n        unfold sched, scheduler, schedule_prefix in *.\n        destruct t.\n        {\n          unfold update_schedule in SCHED; rewrite eq_refl in SCHED.\n          rewrite -SCHED; f_equal.\n          unfold sorted_jobs, sorted_pending_jobs; f_equal.\n          unfold jobs_pending_at; apply eq_filter; red; intro j'.\n          unfold pending; f_equal; f_equal.\n          unfold completed, service.\n          by rewrite big_geq // big_geq //.\n        }\n        {\n          unfold update_schedule at 1 in SCHED; rewrite eq_refl in SCHED.\n          rewrite -SCHED; f_equal.\n          unfold sorted_jobs, sorted_pending_jobs; f_equal.\n          unfold jobs_pending_at; apply eq_filter; red; intro j'.\n          unfold pending; f_equal; f_equal.\n          unfold completed, service; f_equal.\n          apply eq_big_nat; move => t0 /andP [_ LT].\n          unfold service_at; apply eq_bigl; red; intros cpu'.\n          fold (schedule_prefix job_cost num_cpus arr_seq higher_eq_priority).\n          by rewrite /scheduled_on 2?scheduler_same_prefix ?leqnn //.\n        }\n      Qed.\n      \n      (* ..., a scheduled job is mapped to a cpu corresponding to its position, ... *)\n      Lemma scheduler_nth_or_none_scheduled :\n        forall j t,\n          scheduled sched j t ->\n          exists (cpu: processor num_cpus),\n            nth_or_none (sorted_jobs t) cpu = Some j. \n      Proof.\n        intros j t SCHED.\n        move: SCHED => /existsP [cpu /eqP SCHED]; exists cpu.\n        by apply scheduler_nth_or_none_mapping.\n      Qed.\n\n      (* ..., and that a backlogged job has a position larger than or equal to the number\n         of processors. *)\n      Lemma scheduler_nth_or_none_backlogged :\n        forall j t,\n          backlogged job_cost sched j t ->\n          exists i,\n            nth_or_none (sorted_jobs t) i = Some j /\\ i >= num_cpus.\n      Proof.\n        intros j t BACK.\n        move: BACK => /andP [PENDING /negP NOTCOMP].\n        assert (IN: j \\in sorted_jobs t).\n        {\n          rewrite mem_sort mem_filter PENDING andTb.\n          move: PENDING => /andP [ARRIVED _].\n          by rewrite JobIn_has_arrived.\n        }\n        apply nth_or_none_mem_exists in IN; des.\n        exists n; split; first by done.\n        rewrite leqNgt; apply/negP; red; intro LT.\n        apply NOTCOMP; clear NOTCOMP PENDING.\n        apply/existsP; exists (Ordinal LT); apply/eqP.\n        unfold sorted_jobs in *; clear sorted_jobs.\n        unfold sched, scheduler, schedule_prefix in *; clear sched.\n        destruct t. \n        {\n          unfold update_schedule; rewrite eq_refl.\n          rewrite -IN; f_equal.\n          fold (schedule_prefix job_cost num_cpus arr_seq higher_eq_priority).\n          unfold sorted_pending_jobs; f_equal.\n          apply eq_filter; red; intros x.\n          unfold pending; f_equal; f_equal.\n          unfold completed; f_equal.\n          by unfold service; rewrite 2?big_geq //.\n        }\n        {\n          unfold update_schedule at 1; rewrite eq_refl.\n          rewrite -IN; f_equal.\n          unfold sorted_pending_jobs; f_equal.\n          apply eq_filter; red; intros x.\n          unfold pending; f_equal; f_equal.\n          unfold completed; f_equal.\n          unfold service; apply eq_big_nat; move => i /andP [_ LTi].\n          unfold service_at; apply eq_bigl; red; intro cpu.\n          unfold scheduled_on; f_equal.\n          fold (schedule_prefix job_cost num_cpus arr_seq higher_eq_priority).\n          by rewrite scheduler_same_prefix.\n        }\n      Qed.\n\n    End HelperLemmas.\n\n    (* Now, we prove the important properties about the implementation. *)\n    \n    (* Jobs do not execute before they arrive, ...*)\n    Theorem scheduler_jobs_must_arrive_to_execute:\n      jobs_must_arrive_to_execute sched.\n    Proof.\n      unfold jobs_must_arrive_to_execute.\n      intros j t SCHED.\n      move: SCHED => /existsP [cpu /eqP SCHED].\n      unfold sched, scheduler, schedule_prefix in SCHED.\n      destruct t.\n      {\n        rewrite /update_schedule eq_refl in SCHED.\n        apply (nth_or_none_mem _ cpu j) in SCHED.\n        rewrite mem_sort mem_filter in SCHED.\n        move: SCHED => /andP [_ ARR].\n        by apply JobIn_has_arrived in ARR.\n      }\n      {\n        unfold update_schedule at 1 in SCHED; rewrite eq_refl /= in SCHED.\n        apply (nth_or_none_mem _ cpu j) in SCHED.\n        rewrite mem_sort mem_filter in SCHED.\n        move: SCHED => /andP [_ ARR].\n        by apply JobIn_has_arrived in ARR.\n      }\n    Qed.\n\n    (* ..., jobs are sequential, ... *)\n    Theorem scheduler_sequential_jobs: sequential_jobs sched.\n    Proof.\n      unfold sequential_jobs, sched, scheduler, schedule_prefix.\n      intros j t cpu1 cpu2 SCHED1 SCHED2.\n      destruct t; rewrite /update_schedule eq_refl in SCHED1 SCHED2;\n      have UNIQ := nth_or_none_uniq _ cpu1 cpu2 j _ SCHED1 SCHED2; (apply ord_inj, UNIQ);\n      rewrite sort_uniq filter_uniq //;\n      by apply JobIn_uniq.\n    Qed.\n               \n    (* ... and jobs do not execute after completion. *)\n    Theorem scheduler_completed_jobs_dont_execute:\n      completed_jobs_dont_execute job_cost sched.\n    Proof.\n      rename H_job_cost_positive into GT0.\n      unfold completed_jobs_dont_execute, service.\n      intros j t.\n      induction t; first by rewrite big_geq.\n      {\n        rewrite big_nat_recr // /=.\n        rewrite leq_eqVlt in IHt; move: IHt => /orP [/eqP EQ | LESS]; last first.\n        {\n          destruct (job_cost j); first by rewrite ltn0 in LESS.\n          rewrite -addn1; rewrite ltnS in LESS.\n          apply leq_add; first by done.\n          by apply service_at_most_one, scheduler_sequential_jobs.\n        }\n        rewrite EQ -{2}[job_cost j]addn0; apply leq_add; first by done.\n        destruct t.\n        {\n          rewrite big_geq // in EQ.\n          specialize (GT0 j); unfold job_cost_positive in *.\n          by rewrite -EQ ltn0 in GT0.\n        }\n        {\n          unfold service_at; rewrite big_mkcond.\n          apply leq_trans with (n := \\sum_(cpu < num_cpus) 0);\n            last by rewrite big_const_ord iter_addn mul0n addn0.\n          apply leq_sum; intros cpu _; desf.\n          move: Heq => /eqP SCHED.\n          unfold scheduler, schedule_prefix in SCHED.\n          unfold sched, scheduler, schedule_prefix, update_schedule at 1 in SCHED.\n          rewrite eq_refl in SCHED.\n          apply (nth_or_none_mem _ cpu j) in SCHED.\n          rewrite mem_sort mem_filter in SCHED.\n          fold (update_schedule job_cost num_cpus arr_seq higher_eq_priority) in SCHED.\n          move: SCHED => /andP [/andP [_ /negP NOTCOMP] _].\n          exfalso; apply NOTCOMP; clear NOTCOMP.\n          unfold completed; apply/eqP.\n          unfold service; rewrite -EQ.\n          rewrite big_nat_cond [\\sum_(_ <= _ < _ | true)_]big_nat_cond.\n          apply eq_bigr; move => i /andP [/andP [_ LT] _].\n          apply eq_bigl; red; ins.\n          unfold scheduled_on; f_equal.\n          fold (schedule_prefix job_cost num_cpus arr_seq higher_eq_priority).\n          by rewrite scheduler_same_prefix.\n        }\n      }\n    Qed.\n\n    (* In addition, the scheduler is work conserving ... *)\n    Theorem scheduler_work_conserving:\n      work_conserving job_cost sched.\n    Proof.\n      unfold work_conserving; intros j t BACK cpu.\n      set jobs := sorted_pending_jobs job_cost num_cpus arr_seq higher_eq_priority sched t.\n      destruct (sched cpu t) eqn:SCHED; first by exists j0; apply/eqP.\n      apply scheduler_nth_or_none_backlogged in BACK.\n      destruct BACK as [cpu_out [NTH GE]].\n      exfalso; rewrite leqNgt in GE; move: GE => /negP GE; apply GE.\n      apply leq_ltn_trans with (n := cpu); last by done.\n      apply scheduler_nth_or_none_mapping in SCHED.\n      apply nth_or_none_size_none in SCHED.\n      apply leq_trans with (n := size jobs); last by done.\n      by apply nth_or_none_size_some in NTH; apply ltnW.\n    Qed.\n\n    (* ... and enforces the JLDP policy. *)\n    Theorem scheduler_enforces_policy :\n      enforces_JLDP_policy job_cost sched higher_eq_priority.\n    Proof.\n      unfold enforces_JLDP_policy; intros j j_hp t BACK SCHED.\n      set jobs := sorted_pending_jobs job_cost num_cpus arr_seq higher_eq_priority sched t.\n      apply scheduler_nth_or_none_backlogged in BACK.\n      destruct BACK as [cpu_out [SOME GE]].\n      apply scheduler_nth_or_none_scheduled in SCHED.\n      destruct SCHED as [cpu SCHED].\n      have EQ1 := nth_or_none_nth jobs cpu j_hp j SCHED.\n      have EQ2 := nth_or_none_nth jobs cpu_out j j SOME.\n      rewrite -EQ1 -{2}EQ2.\n      apply sorted_lt_idx_implies_rel; [by done | by apply sort_sorted | |].\n      - by apply leq_trans with (n := num_cpus).\n      - by apply nth_or_none_size_some in SOME.\n    Qed.\n\n  End Proofs.\n    \nEnd ConcreteScheduler.", "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/implementation/basic/schedule.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6724520657132057}}
{"text": "Section Definitions.\nRequire Import ZArith.\nOpen Scope Z_scope.\n\n(* Values (reused) *)\nInductive Value : Set := \n    | VInt  : Z -> Value\n    | VBool : bool -> Value.\n\n(* Variables at p.71 *)\nInductive Var : Set :=\n    | VId : nat -> Var.\n\n(* Decidability of Var *)\nLemma Var_eq_dec :\n    forall x y : Var, {x = y} + {x <> y}.\nProof.\n    intros x y.\n    destruct x as [i].\n    destruct y as [j].\n    destruct (eq_nat_dec i j) as [D | D].\n\n        (* Case : i = j *)\n        left.\n        subst.\n        reflexivity.\n\n        (* Case : i <> j *)\n        right.\n        intro H.\n        apply D.\n        inversion H as [H'].\n        reflexivity.\nQed.\n\n(* Environments at p.71 *)\nInductive Env : Set :=\n    | ENil  : Env \n    | ECons : Env -> Var -> Value -> Env.\n\n(* Definition at p.71 *)\nInductive Exp : Set :=\n    | EValue : Value -> Exp\n    | EVar   : Var -> Exp\n    | EPlus  : Exp -> Exp -> Exp\n    | EMinus : Exp -> Exp -> Exp\n    | ETimes : Exp -> Exp -> Exp\n    | ELt    : Exp -> Exp -> Exp\n    | EIf    : Exp -> Exp -> Exp -> Exp\n    | ELet   : Var -> Exp -> Exp -> Exp.\n\n(* Definitions at pp.56-57 (reused) *)\nInductive Plus : Z -> Z -> Z -> Prop :=\n    | B_Plus : forall i1 i2 i3 : Z, i3 = i1 + i2 -> Plus i1 i2 i3.\nInductive Minus : Z -> Z -> Z -> Prop :=\n    | B_Minus : forall i1 i2 i3 : Z, i3 = i1 - i2 -> Minus i1 i2 i3.\nInductive Times : Z -> Z -> Z -> Prop :=\n    | B_Times : forall i1 i2 i3 : Z, i3 = i1 * i2 -> Times i1 i2 i3.\nInductive Lt : Z -> Z -> bool -> Prop :=\n    | B_Lt : forall (i1 i2 : Z) (b3 : bool), b3 = (i1 <? i2) -> Lt i1 i2 b3.\n\nLemma Plus_uniq :\n    forall i1 i2 i3 i4 : Z, Plus i1 i2 i3 -> Plus i1 i2 i4 -> i3 = i4.\nProof.\n    intros i1 i2 i3 i4 H3 H4.\n    inversion H3; subst.\n    inversion H4; subst.\n    reflexivity.\nQed.\n\nLemma Minus_uniq :\n    forall i1 i2 i3 i4 : Z, Minus i1 i2 i3 -> Minus i1 i2 i4 -> i3 = i4.\nProof.\n    intros i1 i2 i3 i4 H3 H4.\n    inversion H3; subst.\n    inversion H4; subst.\n    reflexivity.\nQed.\n\nLemma Times_uniq :\n    forall i1 i2 i3 i4 : Z, Times i1 i2 i3 -> Times i1 i2 i4 -> i3 = i4.\nProof.\n    intros i1 i2 i3 i4 H3 H4.\n    inversion H3; subst.\n    inversion H4; subst.\n    reflexivity.\nQed.\n\nLemma Lt_uniq :\n    forall (i1 i2 : Z) (b1 b2 : bool), Lt i1 i2 b1 -> Lt i1 i2 b2 -> b1 = b2.\nProof.\n    intros i1 i2 i3 i4 H3 H4.\n    inversion H3; subst.\n    inversion H4; subst.\n    reflexivity.\nQed.\n\n(* Fig 4.1 *)\nInductive EvalTo : Env -> Exp -> Value -> Prop :=\n    | E_Int   : forall (E : Env) (i : Z),\n                EvalTo E (EValue (VInt i)) (VInt i)\n    | E_Bool  : forall (E : Env) (b : bool),\n                EvalTo E (EValue (VBool b)) (VBool b)\n    | E_Var1  : forall (E : Env) (x : Var) (v : Value),\n                EvalTo (ECons E x v) (EVar x) v\n    | E_Var2  : forall (E : Env) (x y : Var) (v1 v2 : Value),\n                x <> y -> EvalTo E (EVar x) v2 ->\n                EvalTo (ECons E y v1) (EVar x) v2\n    | E_Plus  : forall (E : Env) (e1 e2 e3 : Exp) (i1 i2 i3 : Z),\n                EvalTo E e1 (VInt i1) -> EvalTo E e2 (VInt i2) ->\n                Plus i1 i2 i3 ->\n                EvalTo E (EPlus e1 e2) (VInt i3)\n    | E_Minus : forall (E : Env) (e1 e2 e3 : Exp) (i1 i2 i3 : Z),\n                EvalTo E e1 (VInt i1) -> EvalTo E e2 (VInt i2) ->\n                Minus i1 i2 i3 ->\n                EvalTo E (EMinus e1 e2) (VInt i3)\n    | E_Times : forall (E : Env) (e1 e2 e3 : Exp) (i1 i2 i3 : Z),\n                EvalTo E e1 (VInt i1) -> EvalTo E e2 (VInt i2) ->\n                Times i1 i2 i3 ->\n                EvalTo E (ETimes e1 e2) (VInt i3)\n    | E_Lt    : forall (E : Env) (e1 e2 : Exp) (i1 i2 : Z) (b3 : bool),\n                EvalTo E e1 (VInt i1) -> EvalTo E e2 (VInt i2) ->\n                Lt i1 i2 b3 ->\n                EvalTo E (ELt e1 e2) (VBool b3)\n    | E_IfT   : forall (E : Env) (e1 e2 e3 : Exp) (v : Value),\n                EvalTo E e1 (VBool true) -> EvalTo E e2 v ->\n                EvalTo E (EIf e1 e2 e3) v\n    | E_IfF   : forall (E : Env) (e1 e2 e3 : Exp) (v : Value),\n                EvalTo E e1 (VBool false) -> EvalTo E e3 v ->\n                EvalTo E (EIf e1 e2 e3) v\n    | E_Let   : forall (E : Env) (e1 e2 : Exp) (x : Var) (v1 v : Value),\n                EvalTo E e1 v1 -> EvalTo (ECons E x v1) e2 v ->\n                EvalTo E (ELet x e1 e2) v.\n\n(* Lemma 4.2 *)\nLemma EvalTo_Var_uniq :\n    forall (E : Env) (x : Var) (v v' : Value),\n    EvalTo E (EVar x) v -> EvalTo E (EVar x) v' -> v = v'.\nProof.\n    induction E as [| E0 H0 x0 v0].\n\n        (* Case : E = ENil *)\n        intros x v v' H H'.\n        inversion H.\n\n        (* Case : E = ECons E0 x0 v0 *)\n        intros x v v' H H'.\n        inversion H; subst.\n\n            (* Case : H is from E_Var1 *)\n            inversion H'; subst.\n\n                (* Case : H' is from E_Var1 *)\n                reflexivity.\n\n                (* Case : H' is from E_Var2 *)\n                contradict H6.\n                reflexivity.\n\n            (* Case : H' is from E_Var2 *)\n            inversion H'; subst.\n\n                (* Case : H' is from E_Var1 *)\n                contradict H6.\n                reflexivity.\n\n                (* Case : H' is from E_Var2 *)\n                apply (H0 _ _ _ H7 H9).\nQed.\n\n(* Theorem 4.1 *)\nTheorem EvalTo_uniq :\n    forall (E : Env) (e : Exp) (v v' : Value),\n    EvalTo E e v -> EvalTo E e v' -> v = v'.\nProof.\n    intros E e.\n    generalize dependent E.\n    induction e as [[i | b] | x |\n                    e1 He1 e2 He2 | e1 He1 e2 He2 | e1 He1 e2 He2 |\n                    e1 He1 e2 He2 | e1 He1 e2 He2 e3 He3 | x e1 He1 e2 He2 ].\n\n        (* Case : e = VInt i *)\n        intros E v1 v2 H1 H2.\n        inversion H1; subst.\n        inversion H2; subst.\n        reflexivity.\n\n        (* Case : e = VBool b *)\n        intros E v1 v2 H1 H2.\n        inversion H1; subst.\n        inversion H2; subst.\n        reflexivity.\n\n        (* Case : e = EVar x *)\n        intros E v1 v2 H1 H2.\n        apply (EvalTo_Var_uniq _ _ _ _ H1 H2).\n\n        (* Case : e = EPlus e1 e2 *)\n        intros E v1 v2 H1 H2.\n        inversion H1; subst.\n        inversion H2; subst.\n        assert (VInt i1 = VInt i0) as Hi1 by apply (He1 _ _ _ H3 H4).\n        inversion Hi1; subst; clear Hi1.\n        assert (VInt i2 = VInt i4) as Hi2 by apply (He2 _ _ _ H5 H8).\n        inversion Hi2; subst; clear Hi2.\n        assert (i3 = i5) by apply (Plus_uniq _ _ _ _ H7 H10); subst.\n        reflexivity.\n\n        (* Case : e = EMinus e1 e2 *)\n        intros E v1 v2 H1 H2.\n        inversion H1; subst.\n        inversion H2; subst.\n        assert (VInt i1 = VInt i0) as Hi1 by apply (He1 _ _ _ H3 H4).\n        inversion Hi1; subst; clear Hi1.\n        assert (VInt i2 = VInt i4) as Hi2 by apply (He2 _ _ _ H5 H8).\n        inversion Hi2; subst; clear Hi2.\n        assert (i3 = i5) by apply (Minus_uniq _ _ _ _ H7 H10); subst.\n        reflexivity.\n\n        (* Case : e = ETimes e1 e2 *)\n        intros E v1 v2 H1 H2.\n        inversion H1; subst.\n        inversion H2; subst.\n        assert (VInt i1 = VInt i0) as Hi1 by apply (He1 _ _ _ H3 H4).\n        inversion Hi1; subst; clear Hi1.\n        assert (VInt i2 = VInt i4) as Hi2 by apply (He2 _ _ _ H5 H8).\n        inversion Hi2; subst; clear Hi2.\n        assert (i3 = i5) by apply (Times_uniq _ _ _ _ H7 H10); subst.\n        reflexivity.\n\n        (* Case : e = ELt e1 e2 *)\n        intros E v1 v2 H1 H2.\n        inversion H1; subst.\n        inversion H2; subst.\n        assert (VInt i1 = VInt i0) as Hi1 by apply (He1 _ _ _ H3 H4).\n        inversion Hi1; subst; clear Hi1.\n        assert (VInt i2 = VInt i3) as Hi2 by apply (He2 _ _ _ H5 H8).\n        inversion Hi2; subst; clear Hi2.\n        assert (b3 = b0) by apply (Lt_uniq _ _ _ _ H7 H10); subst.\n        reflexivity.\n\n        (* Case : e = EIf e1 e2 e3 *)\n        intros E v1 v2 H1 H2.\n        inversion H1; subst.\n\n            (* Case : EvalTo e1 (VBool true) *)\n            inversion H2; subst.\n\n                (* Case : EvalTo e2 (VBool true) *)\n                apply (He2 _ _ _ H7 H9).\n\n                (* Case : EvalTo e2 (VBool false) *)\n                discriminate (He1 _ _ _ H6 H8).\n\n            (* Case : EvalTo e1 (VBool false) *)\n            inversion H2; subst.\n\n                (* Case : EvalTo e2 (VBool true) *)\n                discriminate (He1 _ _ _ H6 H8).\n\n                (* Case : EvalTo e2 (VBool false) *)\n                apply (He3 _ _ _ H7 H9).\n\n        (* Case : e = ELet x e1 e2 *)\n        intros E v1 v2 H1 H2.\n        inversion H1; subst.\n        inversion H2; subst.\n        assert (v0 = v3) by apply (He1 _ _ _ H6 H8) ; subst.\n        apply (He2 _ _ _ H7 H9).\nQed.\n\n(* Free variables at p.72 *)\nInductive is_FV : Exp -> Var -> Prop :=\n    | FV_Var     : forall x : Var, is_FV (EVar x) x\n    | FV_Plus_l  : forall (e1 e2 : Exp) (x : Var),\n                   is_FV e1 x -> is_FV (EPlus e1 e2) x\n    | FV_Plus_r  : forall (e1 e2 : Exp) (x : Var),\n                   is_FV e2 x -> is_FV (EPlus e1 e2) x\n    | FV_Minus_l : forall (e1 e2 : Exp) (x : Var),\n                   is_FV e1 x -> is_FV (EMinus e1 e2) x\n    | FV_Minus_r : forall (e1 e2 : Exp) (x : Var),\n                   is_FV e2 x -> is_FV (EMinus e1 e2) x\n    | FV_Times_l : forall (e1 e2 : Exp) (x : Var),\n                   is_FV e1 x -> is_FV (ETimes e1 e2) x\n    | FV_Times_r : forall (e1 e2 : Exp) (x : Var),\n                   is_FV e2 x -> is_FV (ETimes e1 e2) x\n    | FV_Lt_l    : forall (e1 e2 : Exp) (x : Var),\n                   is_FV e1 x -> is_FV (ELt e1 e2) x\n    | FV_Lt_r    : forall (e1 e2 : Exp) (x : Var),\n                   is_FV e2 x -> is_FV (ELt e1 e2) x\n    | FV_If      : forall (e1 e2 e3 : Exp) (x : Var),\n                   is_FV e1 x -> is_FV (EIf e1 e2 e3) x\n    | FV_IfT     : forall (e1 e2 e3 : Exp) (x : Var),\n                   is_FV e2 x -> is_FV (EIf e1 e2 e3) x\n    | FV_IfF     : forall (e1 e2 e3 : Exp) (x : Var),\n                   is_FV e3 x -> is_FV (EIf e1 e2 e3) x\n    | FV_Let1    : forall (e1 e2 : Exp) (x y : Var),\n                   is_FV e1 x -> is_FV (ELet y e1 e2) x\n    | FV_Let2    : forall (e1 e2 : Exp) (x y : Var),\n                   is_FV e2 x -> x <> y -> is_FV (ELet y e1 e2) x.\n\n(* Domains at p.73 *)\nInductive in_dom : Env -> Var -> Prop :=\n    | Dom_ECons1 : forall (E : Env) (x : Var) (v : Value),\n                   in_dom (ECons E x v) x\n    | Dom_ECons2 : forall (E : Env) (x y : Var) (v : Value),\n                   in_dom E x -> in_dom (ECons E y v) x.\n\n(* Errors at p.75 *)\nInductive Error : Env -> Exp -> Prop :=\n    | E_IfInt       : forall (E : Env) (e1 e2 e3 : Exp) (i : Z),\n                      EvalTo E e1 (VInt i) -> Error E (EIf e1 e2 e3)\n    | E_PlusBoolL   : forall (E : Env) (e1 e2 : Exp) (b : bool),\n                      EvalTo E e1 (VBool b) -> Error E (EPlus e1 e2)\n    | E_PlusBoolR   : forall (E : Env) (e1 e2 : Exp) (b : bool),\n                      EvalTo E e2 (VBool b) -> Error E (EPlus e1 e2)\n    | E_MinusBoolL  : forall (E : Env) (e1 e2 : Exp) (b : bool),\n                      EvalTo E e1 (VBool b) -> Error E (EMinus e1 e2)\n    | E_MinusBoolR  : forall (E : Env) (e1 e2 : Exp) (b : bool),\n                      EvalTo E e2 (VBool b) -> Error E (EMinus e1 e2)\n    | E_TimesBoolL  : forall (E : Env) (e1 e2 : Exp) (b : bool),\n                      EvalTo E e1 (VBool b) -> Error E (ETimes e1 e2)\n    | E_TimesBoolR  : forall (E : Env) (e1 e2 : Exp) (b : bool),\n                      EvalTo E e2 (VBool b) -> Error E (ETimes e1 e2)\n    | E_LtBoolL     : forall (E : Env) (e1 e2 : Exp) (b : bool),\n                      EvalTo E e1 (VBool b) -> Error E (ELt e1 e2)\n    | E_LtBoolR     : forall (E : Env) (e1 e2 : Exp) (b : bool),\n                      EvalTo E e2 (VBool b) -> Error E (ELt e1 e2)\n    | E_IfError     : forall (E : Env) (e1 e2 e3 : Exp),\n                      Error E e1 -> Error E (EIf e1 e2 e3)\n    | E_IfTError    : forall (E : Env) (e1 e2 e3 : Exp),\n                      EvalTo E e1 (VBool true) -> Error E e2 ->\n                      Error E (EIf e1 e2 e3)\n    | E_IfFError    : forall (E : Env) (e1 e2 e3 : Exp),\n                      EvalTo E e1 (VBool false) -> Error E e3 ->\n                      Error E (EIf e1 e2 e3)\n    | E_PlusErrorL  : forall (E : Env) (e1 e2 : Exp),\n                      Error E e1 -> Error E (EPlus e1 e2)\n    | E_PlusErrorR  : forall (E : Env) (e1 e2 : Exp),\n                      Error E e2 -> Error E (EPlus e1 e2)\n    | E_MinusErrorL : forall (E : Env) (e1 e2 : Exp),\n                      Error E e1 -> Error E (EMinus e1 e2)\n    | E_MinusErrorR : forall (E : Env) (e1 e2 : Exp),\n                      Error E e2 -> Error E (EMinus e1 e2)\n    | E_TimesErrorL : forall (E : Env) (e1 e2 : Exp),\n                      Error E e1 -> Error E (ETimes e1 e2)\n    | E_TimesErrorR : forall (E : Env) (e1 e2 : Exp),\n                      Error E e2 -> Error E (ETimes e1 e2)\n    | E_LtErrorL    : forall (E : Env) (e1 e2 : Exp),\n                      Error E e1 -> Error E (ELt e1 e2)\n    | E_LtErrorR    : forall (E : Env) (e1 e2 : Exp),\n                      Error E e2 -> Error E (ELt e1 e2)\n    | E_LetError1   : forall (E : Env) (x : Var) (e1 e2 : Exp),\n                      Error E e1 -> Error E (ELet x e1 e2)\n    | E_LetError2   : forall (E : Env) (x : Var) (v : Value) (e1 e2 : Exp),\n                      EvalTo E e1 v -> Error (ECons E x v) e2 ->\n                      Error E (ELet x e1 e2).\n\n(* Theorem 4.3 *)\nTheorem EvalTo_Error_total :\n    forall (E : Env) (e : Exp),\n    (forall x : Var, is_FV e x -> in_dom E x) ->\n    (exists v : Value, EvalTo E e v) \\/ Error E e.\nProof.\n    intros E e.\n    generalize dependent E.\n    induction e as [[i | b] | x |\n                    e1 He1 e2 He2 | e1 He1 e2 He2 | e1 He1 e2 He2 |\n                    e1 He1 e2 He2 | e1 He1 e2 He2 e3 He3 | x e1 He1 e2 He2].\n\n        (* Case : e = VInt i *)\n        intros E H.\n        left.\n        exists (VInt i).\n        apply E_Int.\n\n        (* Case : e = VBool b *)\n        intros E H.\n        left.\n        exists (VBool b).\n        apply E_Bool.\n\n        (* Case : e = EVar x *)\n        intros E H.\n        specialize (H x (FV_Var _)).\n        induction H as [E0 x v | E0 x y v H0 H].\n\n            (* Case : E = ECons E0 x v *)\n            left.\n            exists v.\n            apply E_Var1.\n\n            (* Case : in_dom E0 x *)\n            destruct (Var_eq_dec x y) as [D | D].\n\n                (* Case : x = y *)\n                subst.\n                left.\n                exists v.\n                apply E_Var1.\n\n                (* Case : x <> y *)\n                destruct H as [[v' H] | H].\n\n                    (* Case : EvalTo E0 (EVar x) v' *)\n                    left.\n                    exists v'.\n                    apply (E_Var2 E0 _ _ _ _ D H).\n\n                    (* Case : Error E0 (EVar x) *)\n                    inversion H.\n\n        (* Case : e = EPlus e1 e2 *)\n        intros E H.\n        assert (forall x : Var, is_FV e1 x -> in_dom E x) as HFV1.\n\n            (* Proof of the assertion *)\n            intros x Hx.\n            apply H.\n            apply (FV_Plus_l _ _ _ Hx).\n\n        assert (forall x : Var, is_FV e2 x -> in_dom E x) as HFV2.\n\n            (* Proof of the assertion *)\n            intros x Hx.\n            apply H.\n            apply (FV_Plus_r _ _ _ Hx).\n\n        specialize (He1 E HFV1); clear HFV1.\n        specialize (He2 E HFV2); clear HFV2.\n        destruct He1 as [[[i1 | b1] He1] | He1].\n\n            (* Case : EvalTo E e1 (VInt i1) *)\n            destruct He2 as [[[i2 | b2] He2] | He2].\n\n                (* Case : EvalTo E e2 (VInt i2) *)\n                left.\n                exists (VInt (i1 + i2)).\n                apply (E_Plus _ _ _ (EValue (VInt (i1 + i2))) _ _ _ He1 He2).\n                apply B_Plus.\n                reflexivity.\n\n                (* Case : EvalTo E e2 (VBool b2) *)\n                right.\n                apply (E_PlusBoolR _ _ _ _ He2).\n\n                (* Case : Error E e2 *)\n                right.\n                apply (E_PlusErrorR _ _ _ He2).\n\n            (* Case : EvalTo E e1 (VBool b1) *)\n            right.\n            apply (E_PlusBoolL _ _ _ _ He1).\n\n            (* Case : Error E e1 *)\n            right.\n            apply (E_PlusErrorL _ _ _ He1).\n\n        (* Case : e = EMinus e1 e2 *)\n        intros E H.\n        assert (forall x : Var, is_FV e1 x -> in_dom E x) as HFV1.\n\n            (* Proof of the assertion *)\n            intros x Hx.\n            apply H.\n            apply (FV_Minus_l _ _ _ Hx).\n\n        assert (forall x : Var, is_FV e2 x -> in_dom E x) as HFV2.\n\n            (* Proof of the assertion *)\n            intros x Hx.\n            apply H.\n            apply (FV_Minus_r _ _ _ Hx).\n\n        specialize (He1 E HFV1); clear HFV1.\n        specialize (He2 E HFV2); clear HFV2.\n        destruct He1 as [[[i1 | b1] He1] | He1].\n\n            (* Case : EvalTo E e1 (VInt i1) *)\n            destruct He2 as [[[i2 | b2] He2] | He2].\n\n                (* Case : EvalTo E e2 (VInt i2) *)\n                left.\n                exists (VInt (i1 - i2)).\n                apply (E_Minus _ _ _ (EValue (VInt (i1 - i2))) _ _ _ He1 He2).\n                apply B_Minus.\n                reflexivity.\n\n                (* Case : EvalTo E e2 (VBool b2) *)\n                right.\n                apply (E_MinusBoolR _ _ _ _ He2).\n\n                (* Case : Error E e2 *)\n                right.\n                apply (E_MinusErrorR _ _ _ He2).\n\n            (* Case : EvalTo E e1 (VBool b1) *)\n            right.\n            apply (E_MinusBoolL _ _ _ _ He1).\n\n            (* Case : Error E e1 *)\n            right.\n            apply (E_MinusErrorL _ _ _ He1).\n\n        (* Case : e = ETimes e1 e2 *)\n        intros E H.\n        assert (forall x : Var, is_FV e1 x -> in_dom E x) as HFV1.\n\n            (* Proof of the assertion *)\n            intros x Hx.\n            apply H.\n            apply (FV_Times_l _ _ _ Hx).\n\n        assert (forall x : Var, is_FV e2 x -> in_dom E x) as HFV2.\n\n            (* Proof of the assertion *)\n            intros x Hx.\n            apply H.\n            apply (FV_Times_r _ _ _ Hx).\n\n        specialize (He1 E HFV1); clear HFV1.\n        specialize (He2 E HFV2); clear HFV2.\n        destruct He1 as [[[i1 | b1] He1] | He1].\n\n            (* Case : EvalTo E e1 (VInt i1) *)\n            destruct He2 as [[[i2 | b2] He2] | He2].\n\n                (* Case : EvalTo E e2 (VInt i2) *)\n                left.\n                exists (VInt (i1 * i2)).\n                apply (E_Times _ _ _ (EValue (VInt (i1 * i2))) _ _ _ He1 He2).\n                apply B_Times.\n                reflexivity.\n\n                (* Case : EvalTo E e2 (VBool b2) *)\n                right.\n                apply (E_TimesBoolR _ _ _ _ He2).\n\n                (* Case : Error E e2 *)\n                right.\n                apply (E_TimesErrorR _ _ _ He2).\n\n            (* Case : EvalTo E e1 (VBool b1) *)\n            right.\n            apply (E_TimesBoolL _ _ _ _ He1).\n\n            (* Case : Error E e1 *)\n            right.\n            apply (E_TimesErrorL _ _ _ He1).\n\n        (* Case : e = ELt e1 e2 *)\n        intros E H.\n        assert (forall x : Var, is_FV e1 x -> in_dom E x) as HFV1.\n\n            (* Proof of the assertion *)\n            intros x Hx.\n            apply H.\n            apply (FV_Lt_l _ _ _ Hx).\n\n        assert (forall x : Var, is_FV e2 x -> in_dom E x) as HFV2.\n\n            (* Proof of the assertion *)\n            intros x Hx.\n            apply H.\n            apply (FV_Lt_r _ _ _ Hx).\n\n        specialize (He1 E HFV1); clear HFV1.\n        specialize (He2 E HFV2); clear HFV2.\n        destruct He1 as [[[i1 | b1] He1] | He1].\n\n            (* Case : EvalTo E e1 (VInt i1) *)\n            destruct He2 as [[[i2 | b2] He2] | He2].\n\n                (* Case : EvalTo E e2 (VInt i2) *)\n                left.\n                exists (VBool (i1 <? i2)).\n                apply (E_Lt _ _ _ _ _ _ He1 He2).\n                apply B_Lt.\n                reflexivity.\n\n                (* Case : EvalTo E e2 (VBool b2) *)\n                right.\n                apply (E_LtBoolR _ _ _ _ He2).\n\n                (* Case : Error E e2 *)\n                right.\n                apply (E_LtErrorR _ _ _ He2).\n\n            (* Case : EvalTo E e1 (VBool b1) *)\n            right.\n            apply (E_LtBoolL _ _ _ _ He1).\n\n            (* Case : Error E e1 *)\n            right.\n            apply (E_LtErrorL _ _ _ He1).\n\n        (* Case : e = EIf e1 e2 e3 *)\n        intros E H.\n        assert (forall x : Var, is_FV e1 x -> in_dom E x) as HFV1.\n\n            (* Proof of the assertion *)\n            intros x Hx.\n            apply H.\n            apply (FV_If _ _ _ _ Hx).\n\n        assert (forall x : Var, is_FV e2 x -> in_dom E x) as HFV2.\n\n            (* Proof of the assertion *)\n            intros x Hx.\n            apply H.\n            apply (FV_IfT _ _ _ _ Hx).\n\n        assert (forall x : Var, is_FV e3 x -> in_dom E x) as HFV3.\n\n            (* Proof of the assertion *)\n            intros x Hx.\n            apply H.\n            apply (FV_IfF _ _ _ _ Hx).\n\n        specialize (He1 E HFV1); clear HFV1.\n        specialize (He2 E HFV2); clear HFV2.\n        specialize (He3 E HFV3); clear HFV3.\n        destruct He1 as [[[i | [|]] He1]| He1].\n\n            (* Case : EvalTo E e1 (VInt i) *)\n            right.\n            apply (E_IfInt _ _ _ _ _ He1).\n\n            (* Case : EvalTo E e1 (VBool true *)\n            destruct He2 as [[v He2] | He2].\n\n                (* Case : EvalTo E e2 v *)\n                left.\n                exists v.\n                apply (E_IfT _ _ _ _ _ He1 He2).\n\n                (* Case : Error E e2 *)\n                right. Print E_IfTError.\n                apply (E_IfTError _ _ _ _ He1 He2).\n\n            (* Case : EvalTo E e1 (VBool false) *)\n            destruct He3 as [[v He3] | He3].\n\n                (* Case : EvalTo E e3 v *)\n                left.\n                exists v.\n                apply (E_IfF _ _ _ _ _ He1 He3).\n\n                (* Case : Error E e3 *)\n                right.\n                apply (E_IfFError _ _ _ _ He1 He3).\n\n            (* Case : Error E e1 *)\n            right.\n            apply (E_IfError _ _ _ _ He1).\n\n        (* Case : e = ELet v e1 e2 *)\n        intros E H.\n        assert (forall x : Var, is_FV e1 x -> in_dom E x) as HFV1.\n\n            (* Proof of the assertion *)\n            intros x0 Hx0.\n            apply H.\n            apply (FV_Let1 _ _ _ _ Hx0).\n\n        specialize (He1 E HFV1); clear HFV1.\n        destruct He1 as [[v He1] | He1].\n\n            (* Case : EvalTo E e1 v *)\n            assert (forall x0 : Var,\n                    is_FV e2 x0 -> in_dom (ECons E x v) x0) as HFV2.\n\n                (* Proof of the assertion *)\n                intros y Hy.\n                destruct (Var_eq_dec y x) as [D | D].\n\n                    (* Case : y = x *)\n                    subst.\n                    apply Dom_ECons1.\n\n                    (* Case : y <> x *)\n                    apply Dom_ECons2.\n                    apply H.\n                    apply (FV_Let2 _ _ _ _ Hy D).\n\n                specialize (He2 (ECons E x v) HFV2); clear HFV2.\n                destruct He2 as [[v' He2]| He2].\n\n                    (* Case : EvalTo (ECons E x v) e2 v' *)\n                    left.\n                    exists v'.\n                    apply (E_Let _ _ _ _ _ _ He1 He2).\n\n                    (* Case : Error (ECons E x v) e2 *)\n                    right.\n                    apply (E_LetError2 _ _ _ _ _ He1 He2).\n\n            (* Case : Error E e1 *)\n            right.\n            apply (E_LetError1 _ _ _ _ He1).\nQed.\n\nEnd Definitions.\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/Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.6724450685697082}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(* ** Object-level encoding of exponential *)\n\nRequire Import Arith ZArith List.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac sums rel_iter gcd.\n\nFrom Undecidability.H10.Matija \n  Require Import alpha expo_diophantine.\n\nFrom Undecidability.H10.Dio \n  Require Import dio_logic.\n\nSet Implicit Arguments.\n\nLocal Notation power := (mscal mult 1).\nLocal Notation expo := (mscal mult 1).\n\n(* Here one can witness how workable is automation of recognition\n    of Diophantine shapes.\n\n    Notice that alpha_conditions below could probably be optimized\n    from the new Diophantine shapes that include Diophantine\n    functions. *)\n\nLocal Notation \"x ≐ ⌞ n ⌟\" := (df_cst x n) \n      (at level 49, no associativity, format \"x  ≐  ⌞ n ⌟\").\nLocal Notation \"x ≐ y\" := (df_eq x y) \n      (at level 49, no associativity, format \"x  ≐  y\").\nLocal Notation \"x ≐ y ⨢ z\" := (df_add x y z) \n      (at level 49, no associativity, y at next level, format \"x  ≐  y  ⨢  z\").\nLocal Notation \"x ≐ y ⨰ z\" := (df_mul x y z) \n      (at level 49, no associativity, y at next level, format \"x  ≐  y  ⨰  z\").\n\nTheorem dio_rel_alpha a b c : 𝔻F a -> 𝔻F b -> 𝔻F c\n                           -> 𝔻R (fun ν => 3 < b ν /\\ a ν = alpha_nat (b ν) (c ν)).\nProof.\n  dio by lemma (fun v => alpha_diophantine (a v) (b v) (c v)).\nDefined.\n\n#[export] Hint Resolve dio_rel_alpha : dio_rel_db.\n\nLocal Fact dio_rel_alpha_example : 𝔻R (fun ν => 3 < ν 1 /\\ ν 0 = alpha_nat (ν 1) (ν 2)).\nProof. dio auto. Defined.\n\n(* Eval compute in df_size_Z (proj1_sig dio_rel_alpha_example). *)\n\nFact dio_rel_alpha_size : df_size_Z (proj1_sig dio_rel_alpha_example) = 1445%Z.\nProof. reflexivity. Qed.\n\n(* This is Matiyasevich theorem stating that q^r is a Diophantine function. \n    \n    Notice that expo_conditions below could also probably be optimized *)\n\nTheorem dio_fun_expo q r : 𝔻F q -> 𝔻F r -> 𝔻F (fun ν => expo (r ν) (q ν)).\nProof.\n  dio by lemma (fun v => expo_diophantine (v 0) (q v⭳) (r v⭳)).\nDefined.\n\n#[export] Hint Resolve dio_fun_expo : dio_fun_db.\n\nLocal Fact dio_fun_expo_example : 𝔻F (fun ν => expo (ν 0) (ν 1)).\nProof. dio auto. Defined.\n\n(* Eval compute in df_size_Z (proj1_sig dio_fun_expo_example). *)\n\n(* The new Diophantine shapes (w/o build-in polynimoals) \n   build formulas that are a bit bigger ... *)\n\nLocal Fact dio_fun_expo_example_size : df_size_Z (proj1_sig dio_fun_expo_example) = 4903%Z.\nProof. reflexivity. Qed.\n\n(* We use the exponantial to characterize digits *)\n\n(* The is_digit c q i y relation stating that \n     \n       \"y is the i-th digit of c is base q\" \n *)\n\nLocal Fact is_digit_eq c q i y : \n            is_digit c q i y \n        <-> y < q\n         /\\ exists a b p, c = (a*q+y)*p+b \n                       /\\ b < p\n                       /\\ p = power i q.\nProof.\n  split; intros (H1 & a & b & H2).\n  + split; auto; exists a, b, (power i q); repeat split; tauto.\n  + destruct H2 as (p & H2 & H3 & H4).\n    split; auto; exists a, b; subst; auto.\nQed.\n\nLemma dio_rel_is_digit c q i y : 𝔻F c -> 𝔻F q -> 𝔻F i -> 𝔻F y\n                              -> 𝔻R (fun ν => is_digit (c ν) (q ν) (i ν) (y ν)).\nProof.\n  dio by lemma (fun ν => is_digit_eq (c ν) (q ν) (i ν) (y ν)).\nDefined.\n\n#[export] Hint Resolve dio_rel_is_digit : dio_rel_db.\n\nLocal Fact dio_rel_is_digit_example : 𝔻R (fun ν => is_digit (ν 0) (ν 1) (ν 2) (ν 3)).\nProof. dio auto. Defined.\n\n(* Check dio_rel_is_digit_example. *)\n(* Eval compute in df_size_Z (proj1_sig dio_rel_is_digit_example). *)\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/H10/Dio/dio_expo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6724450613002854}}
{"text": "From Coq Require Import Lists.List.\nFrom Coq Require Import omega.Omega.\nImport ListNotations.\n\n(* Useful Lemmas on lists *)\nLemma app_singleton : forall {X : Type} (A B : X) l1 l2,\n    [A] = l1 ++ [B] ++ l2 -> l1 = [] /\\ l2 = [] /\\ A = B.\nProof.\n  intros. \n  destruct l1.\n  - simpl in *. \n    injection H.\n    intros.\n    subst.\n    auto.\n  - injection H.\n    intros.\n    destruct l1.\n    + simpl in *.\n      discriminate.\n    + simpl in *.\n      discriminate.\nQed.\n\nProposition same_length :\n  forall {X : Type} (l1 l2 l3 l4 : list X),\n    length l1 = length l3 ->\n    l1 ++ l2 = l3 ++ l4 ->\n    l1 = l3.\nProof.\n  intros X l1.\n  induction l1.\n  - simpl in *.\n    intros.\n    assert (0 = (length l3) -> length l3 = 0) by omega.\n    apply H1 in H.\n    apply length_zero_iff_nil in H.\n    auto.\n  - intros.\n    simpl in *.\n    destruct l3.\n    * simpl in *.\n      discriminate.\n    * simpl in *.\n      injection H.\n      intros.\n      specialize (IHl1 l2 l3 l4 H1).\n      injection H0.\n      intros.\n      specialize (IHl1 H2).\n      subst.\n      auto.\nQed. \n      \n\nLemma element_in_app :\n  forall {X : Type} (l1 l2 l3 l4 : list X) A,\n    l1 ++ l2 = l3 ++ [A] ++ l4\n    ->\n    (In A l1 /\\ length l3 < length l1 /\\\n     exists l, l1 = l3 ++ [A] ++ l)\n    \\/ \n    (In A l2 /\\ length l1 <= length l3 /\\\n     exists l,  l2 = l ++ [A] ++ l4).\nProof.\n  intros X l1 l2 l3 l4 A H.\n  assert (either:\n            length l1 = length l3 \\/\n            length l3 < length l1 \\/\n            length l1 < length l3)\n         by omega.\n  destruct  either.\n\n  (* length l1 = length l3 *)\n  - inversion H.\n    apply (same_length l1 l2 l3 (A::l4) H0) in H2.\n    subst.\n    apply app_inv_head in H.\n    subst.\n    right.\n    split.\n    + simpl.\n      left.\n      auto.\n    + split.\n      * omega.\n      * exists [].\n        reflexivity.\n\n      \n  (* remaining cases *) \n  - destruct H0.\n\n    (* length l1 > length l3, hence A is in l1 *)\n    + left.\n      generalize dependent l4.\n      generalize dependent l3.\n      generalize dependent l2.\n      {\n        induction l1.\n        -  intros.\n           simpl in *.\n           omega.\n        - intros.\n          destruct l3.\n          * simpl in *.\n            inversion H.\n            subst.\n            split.\n            + left; auto.\n            + split. omega. exists l1. auto.\n          * simpl in *.\n            inversion H.\n            subst.\n            apply lt_S_n in H0.\n            specialize (IHl1 l2 l3 H0 l4 H3).\n            destruct IHl1.\n            split.\n            + right; auto.\n            + {\n                split.\n                - omega.\n                - destruct H2 as [eq1 [l eq2]].\n                  subst.\n                  injection H.\n                  intros Hyp1.\n                  rewrite <- app_assoc in Hyp1.\n                  apply app_inv_head in Hyp1.\n                  inversion Hyp1.\n                  subst.\n                  assert (eq: (x :: (l3 ++ A :: l)) ++ l2 =\n                              (x :: l3 ++ A :: l) ++ l2)\n                    by auto.\n                  apply app_inv_tail in eq.\n                  exists l.\n                  auto.\n              }\n      }\n      \n    (* length l3 > length l1, hence A is in l2 *)\n    + right.\n      generalize dependent l4.\n      generalize dependent l3.\n      generalize dependent l2.\n      {\n        induction l1.\n        - intros.\n          simpl in *.\n          subst.\n          split.\n          * apply in_or_app.\n            right.\n            simpl.\n            left.\n            auto.\n          * split.\n            omega.\n            exists l3.\n            auto.\n            \n        - destruct l3.\n          * intros.\n            simpl in *.\n            omega.\n          * intros.\n            simpl in *.\n            injection H.\n            intros.\n            subst.\n            apply lt_S_n in H0.\n            specialize (IHl1 l2 l3 H0 l4 H1 ).\n            destruct IHl1.\n            split.\n            + auto.\n            + split.\n              omega.\n              destruct H3.\n              destruct H4.\n              exists x0.\n              subst.\n              auto.\n      }\nQed. \n\nLemma element_in_app_head :\n  forall {X : Type} (l2 l3 l4 : list X) A B,\n    A :: l2 = l3 ++ [B] ++ l4\n    ->\n    l3 = [] /\\ A=B /\\ l2 = l4\n    \\/ \n    exists l,  l2 = l ++ [B] ++ l4.\nProof.\n  intros.\n  assert (H': [A] ++ l2 = l3 ++ [B] ++ l4) by auto.\n  apply element_in_app in H'.\n  destruct H' as [Left | Right].\n  - destruct Left as [ _ [ _ [l H']]].\n    apply app_singleton in H'.\n    destruct H' as [t1 [t2 t3]].\n    left.\n    subst.\n    inversion H.\n    subst.\n    auto.\n  - destruct Right as [_ [ _ [ l H']]].\n    subst.\n    right.\n    assert (eq: (A :: l) ++ [B] ++ l4 = l3 ++ [B] ++ l4)\n      by auto.\n    apply app_inv_tail in eq.\n    subst.\n    exists l; auto.\nQed. \n\nLemma elements_in_app :\n  forall {X : Type} (l1 l2 l3 l4 : list X) A B C,\n    l1 ++ [A] ++ [B] ++ l2 = l3 ++ [C] ++ l4\n    ->\n    (In C l1 /\\ exists l, l1 = l3 ++ [C] ++ l)\n    \\/ \n    (C = A /\\ l1 = l3 /\\ [B] ++ l2 = l4)\n    \\/\n    (C = B /\\ l1 ++ [A] = l3 /\\ l2 = l4)\n    \\/\n    (In C l2 /\\ exists l, l2 = l ++ [C] ++ l4).\nProof.\n  intros.\n\n  assert (either:\n            length l3 < length l1 \\/\n            length l1 = length l3 \\/\n            length l1 + 1 = length l3 \\/\n            length l1 + 2 <= length l3)\n    by omega.\n  \n  destruct  either.\n\n  (* Case in which |l3| < |l1| *)\n  - left. \n    generalize dependent l4.\n    generalize dependent l3.\n    generalize dependent l2.\n    {\n      induction l1.\n      -  intros.\n         simpl in *.\n         omega.\n      - intros.\n        destruct l3.\n        * simpl in *.\n          injection H.\n          intros.\n          subst.\n          split.\n          + left. auto.\n          + exists l1. auto.\n        * simpl in *.\n          injection H.\n          intros.\n          subst.\n          apply lt_S_n in H0.\n          specialize (IHl1 l2 l3 H0 l4 H1 ).\n          destruct IHl1.\n          split.\n          + right. auto.\n          + destruct H3.\n            exists x0.\n            subst.\n            auto.\n    }\n\n    \n  (* remaining cases *)\n  - { destruct H0.\n      \n      (* Case in which |l1| = |l3| *)\n      - inversion H.\n        apply (same_length l1 (A::B::l2) l3 (C::l4) H0) in H2.\n        subst.\n        apply app_inv_head in H.\n        simpl in *.\n        injection H.\n        intros.\n        subst. \n        right. left.\n        split; auto.\n        \n      (* remaining cases *)\n      - { destruct H0.\n\n          (* Case in whcih |l1| + 1 = |l3| *)\n          - inversion H.\n            assert (length (l1 ++ [A]) = length l3).\n            { rewrite app_length.\n              simpl.\n              auto.\n            }\n            right. right. left.\n            rewrite app_assoc in H.\n            apply\n              (same_length (l1 ++ [A]) (B::l2) l3 (C::l4) H1)\n              in H.\n            subst.\n            rewrite <- app_assoc in H2.\n            apply app_inv_head in H2.\n            simpl in *.\n            injection H2.\n            intros.\n            subst.\n            split; auto.\n\n          (* Case in whcih |l1| + 2 <= |l3| *)\n          - right. right. right.\n            rewrite app_assoc in H.\n            rewrite app_assoc in H.\n            apply\n              (element_in_app\n                 ((l1 ++ [A]) ++ [B])\n                 l2\n                 l3\n                 l4\n                 C) in H.\n            destruct H.\n            + destruct H.\n              destruct H1. \n              repeat rewrite app_length in H1.\n              simpl in *.\n              omega.\n              \n            + destruct H.\n              destruct H1.\n              split.\n              * auto.\n              * destruct H2.\n                exists x.\n                auto.\n        }\n    }\nQed. \n\n\n\nLemma tail_list :\n  forall {X : Type} (l : list X),\n    l = []\n    \\/\n    exists l' A,  l = l' ++ [A].\nProof.\n  induction l.\n  - left. auto.\n  - right.\n    destruct IHl.\n    * subst.\n      exists [].\n      exists a.\n      auto.\n    * destruct H.\n      destruct H.\n      subst.\n      exists (a :: x).\n      exists x0.\n      auto.\nQed.\n\n", "meta": {"author": "carbonem", "repo": "ILL_by_beginner", "sha": "179f8b12a5da3613f3d362f41d1d2aa62881c43b", "save_path": "github-repos/coq/carbonem-ILL_by_beginner", "path": "github-repos/coq/carbonem-ILL_by_beginner/ILL_by_beginner-179f8b12a5da3613f3d362f41d1d2aa62881c43b/MyLists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6724450613002853}}
{"text": "Require Export ProjectiveGeometry.Dev.matroid_properties.\nRequire Export ProjectiveGeometry.Dev.projective_space_or_higher_rank_axioms.\n\n(*****************************************************************************)\n(** Rank space or higher properties **)\n\n\nSection s_rankProperties_1.\n\nContext `{M : RankProjectiveSpaceOrHigher}.\nContext `{EP : EqDecidability Point}.\n\n\nLemma rk_singleton : forall p : Point, rk (singleton p) = 1.\nProof.\nintros.\nassert (rk (singleton p)<= 1).\napply (rk_singleton_le);auto.\nassert (rk (singleton p)>= 1).\napply (rk_singleton_ge);auto.\nomega.\nQed.\n\nLemma rk_couple1 : forall p q : Point,~ p [==] q -> rk(couple p q)=2.\nProof.\nintros.\nassert (rk(couple p q)<=2).\napply (rk_couple_2).\nassert (rk(couple p q)>=2).\napply (rk_couple_ge);auto.\nomega.\nQed.\n\nLemma couple_rk1 : forall p q : Point, rk(couple p q) = 2 -> ~ p [==] q.\nProof.\nintros.\nunfold not;intro.\nassert (rk (couple p q) = 1).\nsetoid_replace (couple p q) with (singleton p).\napply rk_singleton.\nrewrite H1.\nclear H0 H1.\nfsetdecide.\nrewrite H0 in H2.\ninversion H2.\nQed.\n\nLemma couple_rk2 : forall p q : Point, rk (couple p q) = 1 -> p [==] q.\nProof.\nintros.\ncase_eq(eq_dec p q).\nintros.\nassumption.\nintro.\nassert (rk(couple p q)=2).\napply rk_couple1;assumption.\nrewrite H0 in H1.\nassert False.\nintuition.\nintuition.\nQed.\n\nLemma rk_couple2 : forall p q : Point, p [==] q -> rk(couple p q) = 1.\nProof.\nintros.\nsetoid_replace (couple p q) with (singleton p).\napply (rk_singleton).\nrewrite H0.\nfsetdecide.\nQed.\n\nLemma rk_couple_1 : forall p q, 1 <= rk (couple p q).\nProof.\nintros.\ncase_eq(eq_dec p q).\nintro.\nrewrite rk_couple2.\nomega.\nassumption.\nintro.\nrewrite rk_couple1.\nomega.\nassumption.\nQed.\n\nLemma couple_rk_degen : forall p, rk (couple p p) = 2 -> False.\nProof.\nintros.\nassert (rk (couple p p) = 1).\nsetoid_replace (couple p p) with (singleton p).\napply rk_singleton.\nfsetdecide.\nintuition.\nQed.\n\nHint Resolve rk_singleton rk_couple1 rk_couple2 couple_rk1 couple_rk2 couple_rk_degen : rk.\n\nLemma base_points_distinct_1 : ~ P0 [==] P1.\nProof.\nassert (T:= rk_lower_dim).\nunfold not;intro.\nrewrite H0 in T.\nsetoid_replace (quadruple P1 P1 P2 P3) with (triple P1 P2 P3) in T by fsetdecide.\nassert (rk (triple P1 P2 P3) <= 3).\napply rk_triple_le.\nomega.\nQed.\n\nLemma base_points_distinct_2 : ~ P2 [==] P3.\nProof.\nassert (T:= rk_lower_dim).\nunfold not;intro.\nrewrite H0 in T.\nsetoid_replace (quadruple P0 P1 P3 P3) with (triple P0 P1 P3) in T by fsetdecide.\nassert (rk (triple P0 P1 P3) <= 3).\napply rk_triple_le.\nomega.\nQed.\n\nLemma rk_lemma_1 : forall A B P Q,\nrk (couple A B) = 2 ->\nrk (triple A B P) = 2 ->\nrk (triple A B Q) = 2 ->\nrk (quadruple A B P Q) = 2.\nProof.\nintros.\nassert (rk (union (triple A B P) (triple A B Q)) + rk (couple A B) <=\n           rk (triple A B P) + rk (triple A B Q)).\napply (matroid3_useful (triple A B P) (triple A B Q) (couple A B)).\nclear_all;fsetdecide.\n\nassert (rk (union (triple A B P) (triple A B Q)) <= 2).\nomega.\nsetoid_replace (union (triple A B P) (triple A B Q)) with (quadruple A B P Q) in H4.\napply le_antisym.\nauto.\ncut (rk (couple A B) <= rk (quadruple A B P Q)).\nomega.\napply matroid2.\nclear_all;fsetdecide.\nclear_all;fsetdecide.\nQed.\n\nEnd s_rankProperties_1.\n\n\nSection s_rankProperties_2.\n\nContext `{M : RankProjectiveSpaceOrHigher}.\nContext `{EP : EqDecidability Point}.\n\nLemma col_trans : forall A B C D:Point, \nrk (triple A C D) = 2 -> rk (triple B C D) = 2 -> rk (couple C D) = 2 -> rk(triple A B C) <= 2.\nProof.\nintros A B C D HACD HBCD HCD.\ncase_eq(eq_dec A B).\nintros.\nrewrite e.\nsetoid_replace (triple B B C) with (couple B C).\napply rk_couple_2.\nclear_all;fsetdecide.\n\nintros.\ngeneralize (matroid3 (triple A C D) (triple B C D)).\nrewrite HACD.\nrewrite HBCD.\nsetoid_replace (inter (triple A  C D) (triple B C D)) with (couple C D).\nrewrite HCD.\nintros.\nassert (rk (union (triple A C D) (triple B C D))<=2).\nomega.\nassert (Hsubset : Subset (triple A B C) (union (triple A C D) (triple B C D))).\nclear_all;fsetdecide.\ngeneralize (matroid2  (triple A B C) (union (triple A C D) (triple B C D)) Hsubset).\nomega.\napply inter_fsetdecide_1.\nassumption.\nassumption.\nQed.\n\nLemma rk_triple_ABC_couple_AB : forall A B C, rk(triple A B C) = 3 -> rk(couple A B) = 2.\nProof.\nintros A0 B0 C0 rABC0.\nassert (rk(couple A0 B0)=1\\/rk(couple A0 B0)=2).\nassert (rk (couple A0 B0) <= 2).\napply (rk_couple_2 A0 B0).\nassert (1 <= rk (couple A0 B0)).\napply (rk_couple_1 A0 B0).\nomega.\nelim H0.\n2:auto.\nintros H'.\nrewrite (couple_rk2 A0 B0 H') in rABC0.\nsetoid_replace (triple B0 B0 C0) with (couple B0 C0) in rABC0.\nassert (rk (couple B0 C0) <= 2).\napply (rk_couple_2 B0 C0).\nomega.\nclear_all;fsetdecide.\nQed.\n\nLemma rk_triple_ABC_couple_BC :  forall A B C, rk(triple A B C)=3 -> rk(couple B C)=2.\nProof.\nintros.\neapply rk_triple_ABC_couple_AB with (C:=A).\nsetoid_replace (triple B C A) with (triple A B C).\nassumption.\nclear_all;fsetdecide.\nQed.\n\nLemma rk_triple_ABC_couple_AC :  forall A B C, rk(triple A B C)=3 -> rk(couple A C)=2.\nProof.\nintros.\neapply rk_triple_ABC_couple_AB with (C:=B).\nsetoid_replace (triple A C B) with (triple A B C).\nassumption.\nclear_all;fsetdecide.\nQed.\n\nHint Resolve rk_triple_ABC_couple_AB rk_triple_ABC_couple_BC rk_triple_ABC_couple_AC : rk.\n\nLemma rk_triple_singleton :forall (x y z a:Point),\nrk(triple x y z)=3 /\\ rk(couple x a)=2 /\\ rk(triple y z a)=2\n-> rk(union (triple x y z) (singleton a))=3.\nProof.\nintros a b c alpha H0.\nelim H0;clear H0;intros rabc H0.\nelim H0;clear H0;intros ranalpha rbcalpha.\n\nassert (rab : rk (couple a b) =2).\neauto with rk.\nassert (rac : rk (couple a c) =2).\neauto with rk.\nassert (rbc : rk (couple b c) =2).\neauto with rk.\n\napply le_antisym.\n(* <= *)\nassert (T: rk (union (triple a b c) (triple b c alpha)) + rk (couple b c) <=\n    rk (triple a b c) + rk (triple b c alpha)).\napply (matroid3_useful (triple a b c) (triple b c alpha) (couple b c)).\nclear_all;fsetdecide.\nsetoid_replace  (union (triple a b c) (triple b c alpha))\n                 with (union (triple a b c) (singleton alpha)) in T.\nomega.\nclear_all;fsetdecide.\n\n(* >= *)\nassert (Hsubset : (Subset (triple a b c) (union (triple a b c) (singleton alpha)))).\nclear_all;fsetdecide.\ngeneralize (matroid2 (triple a b c) (union (triple a b c) (singleton alpha)) Hsubset).\nrewrite rabc.\nauto.\nQed.\n\nHint Resolve  rk_triple_singleton : rk.\n\nLemma rk_couple_not_zero : forall A B, (rk (couple A B) = 0) -> False.\nProof.\nunfold not; intros.\nelim (eq_dec A B);intros.\ngeneralize (rk_couple2 A B).\nintuition.\ngeneralize (rk_couple1 A B).\nintuition.\nQed.\n\nHint Resolve rk_couple_not_zero : rk.\n\nLemma L1beta_gen : forall A B C beta, \nrk(triple A C beta) = 2  -> \nrk (triple A B C) = 3 -> \nrk(union (triple A B C) (singleton beta))=3.\nProof.\nintros  A B C beta.\nintro rACbeta.\nintro rABC.\napply le_antisym.\nassert (T : rk (union (triple A B C) (triple A C beta)) + rk (couple A C) <=\n       rk (triple A B C) + rk (triple A C beta)).\napply (matroid3_useful (triple A B C) (triple A C beta) (couple A C)).\nclear_all;fsetdecide.\nsetoid_replace (union(triple A B C)(triple A C beta)) with (union(triple A B C)(singleton beta)) in T.\nassert (HrAC : rk (couple A C) = 2) by eauto with rk.\nomega.\nclear_all;fsetdecide.\n\n(*>=*)\nassert( Hsubset : (Subset (triple A B C) (union (triple A B C) (singleton beta)))).\nclear_all;fsetdecide.\ngeneralize (matroid2 (triple A B C) (union (triple A B C) (singleton beta)) Hsubset).\nrewrite rABC.\nauto.\nQed.\n\nLemma L1gamma_gen : forall A B C gamma, \nrk (triple A B C) = 3 ->\nrk (triple A B gamma) = 2 ->\nrk(union (triple A B C) (singleton gamma))=3.\nProof.\nintros.\nsetoid_replace (union (triple A B C) (singleton gamma)) \nwith (union (triple A C B) (singleton gamma)).\napply L1beta_gen.\nassumption.\nsetoid_replace (triple A B C) with (triple A C B) in H0.\nassumption.\nclear_all;fsetdecide.\nclear_all;fsetdecide.\nQed.\n\nLemma coplanar : forall O A B C A' B' C' : Point,\nrk (triple A B C ) = 3 ->\nrk (couple A' B) = 2 ->\nrk (couple C' B) = 2 ->\nrk (couple A B') = 2 ->\nrk (couple B' C) = 2 ->\nrk (triple A' B' C' ) = 3 ->\nrk (triple O B B')  = 2 ->\nrk (union (couple O A) (triple C A' C')) = 2 ->\nrk (union (triple A B C) (triple A' B' C')) <> 4.\nProof.\nintros O A B C A' B' C'.\nintro rABC.\nintro rA'B.\nintro rC'B.\nintro rAB'.\nintro rB'C.\nintro rA'B'C'.\nintro rOBB'.\nintro rOACA'C'.\nunfold not.\nintro.\nassert (T: rk (union (triple O B B') (union (couple O A) (triple C A' C'))) +\n      rk (singleton O) <=\n      rk (triple O B B') + rk (union (couple O A) (triple C A' C'))).\napply (matroid3_useful  (triple O B B') (union (couple O A) (triple C A' C')) (singleton O)).\nclear_all;fsetdecide.\nrewrite rOBB' in T.\nrewrite rOACA'C' in T.\nrewrite rk_singleton in T.\nassert (rk (union (triple A B C) (triple A' B' C')) <=\n    rk (union (singleton O) (union (triple A B C) (triple A' B' C')))).\napply matroid2.\nclear_all;fsetdecide.\nsetoid_replace ((union (singleton O) (union (triple A B C) (triple A' B' C')))) with (union (triple O B B') (union (couple O A) (triple C A' C'))) in H1.\nomega.\nunfold Equal; split.\nclear_all;fsetdecide.\nclear_all;fsetdecide.\nQed.\n\nLemma rk_quadruple_ABCD_couple_AB :  \nforall A B C D, rk(add D (triple A B C))>=4 -> rk(couple A B)=2.\nProof.\nintros A0 B0 C0 D0 rABCD0.\nassert (rk(couple A0 B0)=1\\/rk(couple A0 B0)=2).\n\nassert (rk (couple A0 B0) <= 2).\napply (rk_couple_2 A0 B0).\nassert (1 <= rk (couple A0 B0)).\napply (rk_couple_1 A0 B0).\nomega.\nelim H0.\n2:auto.\nintros H'.\nrewrite (couple_rk2 A0 B0 H') in rABCD0.\nsetoid_replace (add D0 (triple B0 B0 C0)) with (triple B0 C0 D0) in rABCD0.\nassert (rk (triple B0 C0 D0) <= 3) by apply (rk_triple_le B0 C0 D0).\nomega.\nclear_all;fsetdecide.\nQed.\n\nLemma rk_quadruple_ABCD_couple_AC :  \nforall A B C D, rk(add D (triple A B C))>=4 -> rk(couple A C)=2.\nProof.\nintros A0 B0 C0 D0 rABCD0.\neapply (rk_quadruple_ABCD_couple_AB A0 C0 B0 D0).\nsetoid_replace (add D0 (triple A0 C0 B0)) with (add D0 (triple A0 B0 C0)) by (clear_all;fsetdecide).\nassumption.\nQed.\n\nLemma rk_quadruple_ABCD_couple_AD :  \nforall A B C D, rk(add D (triple A B C))>=4 -> rk(couple A D)=2.\nProof.\nintros A0 B0 C0 D0 rABCD0.\neapply (rk_quadruple_ABCD_couple_AB A0 D0 B0 C0).\nsetoid_replace (add C0 (triple A0 D0 B0)) with (add D0 (triple A0 B0 C0)) by (clear_all;fsetdecide).\nassumption.\nQed.\n\nLemma rk_quadruple_ABCD_couple_BC :  \nforall A B C D, rk(add D (triple A B C))>=4 -> rk(couple B C)=2.\nProof.\nintros A0 B0 C0 D0 rABCD0.\neapply (rk_quadruple_ABCD_couple_AB B0 C0 D0 A0).\nsetoid_replace (add D0 (triple A0 B0 C0)) with (add A0 (triple B0 C0 D0)) in rABCD0 by (clear_all;fsetdecide).\nassumption.\nQed.\n\nLemma rk_quadruple_ABCD_couple_BD :  \nforall A B C D, rk(add D (triple A B C))>=4 -> rk(couple B D)=2.\nProof.\nintros A0 B0 C0 D0 rABCD0.\neapply (rk_quadruple_ABCD_couple_AB B0 D0 C0 A0).\nsetoid_replace (add A0 (triple B0 D0 C0)) with (add D0 (triple A0 B0 C0)) by (clear_all;fsetdecide).\nassumption.\nQed.\n\nLemma rk_quadruple_ABCD_couple_CD :  \nforall A B C D, rk(add D (triple A B C))>=4 -> rk(couple C D)=2.\nProof.\nintros A0 B0 C0 D0 rABCD0.\neapply (rk_quadruple_ABCD_couple_AB C0 D0 A0 B0).\nsetoid_replace (add B0 (triple C0 D0 A0)) with (add D0 (triple A0 B0 C0)) by (clear_all;fsetdecide).\nassumption.\nQed.\n\nLemma rk_quadruple_ABCD_triple_ABC :  \nforall A B C D, rk(add D (triple A B C))>=4 -> rk(triple A B C)=3.\nProof.\nintros A0 B0 C0 D0 rABCD0.\napply le_antisym.\napply rk_triple_le.\nassert (rk (triple A0 B0 C0) <=\n             rk (add D0 (triple A0 B0 C0)) <=\n             rk (triple A0 B0 C0) + 1).\napply matroid2';auto.\nintuition.\nQed.\n\nLemma intersecting_lines_rank_3 : forall A B C D I,\nrk (triple A B I) <= 2 ->\nrk (triple C D I) <= 2 ->\nrk (union (singleton I) (quadruple A B C D)) <= 3.\nProof.\nintros.\nassert (rk (union (triple A B I) (triple C D I)) +\n       rk (singleton I) <=\n       rk (triple A B I) + rk (triple C D I)).\napply (matroid3_useful (triple A B I) (triple C D I) (singleton I)).\nfsetdecide.\nrewrite rk_singleton in H2.\nsetoid_replace (union (triple A B I) (triple C D I)) \nwith (union (singleton I) (quadruple A B C D)) in H2.\nomega.\nunfold Equal; split;clear_all;fsetdecide.\nQed.\n\n(** Uniqueness of inter *)\nLemma uniq_inter : \nforall A B C D P Q, \nrk(couple A B)=2 -> \nrk(couple C D) = 2 ->\nrk(triple A B P) <= 2 -> \nrk(triple C D P) <= 2 -> \nrk(triple A B Q) <= 2 ->\nrk(triple C D Q) <= 2 -> \nrk(quadruple A B C D) >= 3 -> \nrk(couple P Q) = 1.\nProof.\nintros A B C D P Q rAB rCD rABM rCDM rABP rCDP rABCD.\napply le_antisym.\n\nassert (rk(add Q (triple A B P))<=2).\ngeneralize (matroid3 (triple A B P) (triple A B Q)).\nsetoid_replace (union (triple A B P) (triple A B Q)) \nwith (add Q (triple A B P)).\nassert (rk (inter (triple A B P) (triple A B Q))>=rk(couple A B)).\napply matroid2.\nclear_all;fsetdecide.\nomega.\nclear_all;fsetdecide.\nassert (rk(add Q (triple C D P))<=2).\ngeneralize (matroid3 (triple C D P) (triple C D Q)).\nsetoid_replace (union (triple C D P) (triple C D Q)) \nwith (add Q (triple C D P)).\nassert (rk (inter (triple C D P) (triple C D Q))>=rk(couple C D)).\napply matroid2.\nclear_all;fsetdecide.\nomega.\nclear_all;fsetdecide.\nassert(rk(union (triple A B C) (triple D P Q))>=3).\nassert(rk (quadruple A B C D) <= 3).\nassert (rk (union (singleton P) (quadruple A B C D)) <= 3).\napply (intersecting_lines_rank_3 A B C D P);auto.\nassert (rk (quadruple A B C D) <=\n       rk (union (singleton P) (quadruple A B C D))).\napply matroid2.\nclear_all;fsetdecide.\nomega.\nassert (rABCD' : rk (quadruple A B C D) = 3).\nomega.\nrewrite <- rABCD'.\napply matroid2.\nclear_all;fsetdecide.\n\ngeneralize (matroid3 (add Q (triple A B P))  (add Q (triple C D P))).\nsetoid_replace (union (add Q (triple A B P)) (add Q (triple C D P))) with\n(union (triple A B C) (triple D P Q)).\nassert (rk((inter (add Q (triple A B P)) (add Q (triple C D P))))>=rk(couple P Q)).\napply matroid2.\nclear_all;fsetdecide.\nomega.\nclear_all;fsetdecide.\napply rk_couple_1.\nQed.\n\nLemma uniq_inter_spec : forall gamma a b B,\nrk (triple a b gamma) <= 2 ->\nrk (triple a B gamma) <= 2 ->\nrk (triple a b B) >= 3 ->\nrk (couple a gamma) = 1.\nProof.\nintros.\ncase_eq (eq_dec a gamma).\nintros.\nrewrite e.\nsetoid_replace (couple gamma gamma) with (singleton gamma).\napply rk_singleton.\nclear_all;fsetdecide.\nintros.\nassert(rk(couple a gamma)=2).\napply rk_couple1.\nassumption.\nassert (rk (union (triple a b gamma) (triple a B gamma)) + rk (couple a gamma) <=\n       rk (triple a b gamma) + rk (triple a B gamma)).\napply matroid3_useful.\nclear_all;fsetdecide.\nassert (rk (quadruple a b B gamma) <= 2).\nsetoid_replace (quadruple a b B gamma) with  (union (triple a b gamma) (triple a B gamma)).\nomega.\nclear_all;fsetdecide.\nassert (rk (triple a b B)  <= rk (quadruple a b B gamma)).\napply matroid2.\nclear_all;fsetdecide.\nomega.\nQed.\n\nLemma uniq_inter_spec_bis : forall gamma a b B,\nrk (triple a b gamma) <= 2 ->\nrk (triple a B gamma) <= 2 ->\nrk (couple a gamma) = 1 \\/  rk (triple a b B) <= 2.\nProof.\nintros.\nassert (rk (triple a b B) <= 2 \\/ rk (triple a b B) >= 3).\nomega.\nelim H2;intro.\nright; auto.\nleft.\neapply (uniq_inter_spec).\napply H0.\napply H1.\nauto.\nQed.\n\nLemma stays_in_plane : forall E a b x, rk(E)<=3 -> In a E -> In b E -> \nrk(couple a b)=2->\nrk(triple a b x)=2 -> \nrk(add x E)<=3.\nProof.\nintros E m n x.\nintros.\ngeneralize (matroid3 E (triple m n x)).\nassert (rk (union E (triple m n x))>=rk (add x E)).\napply matroid2.\nclear_all;fsetdecide.\nassert (rk(inter E (triple m n x))>=rk(couple m n)).\napply matroid2.\nclear_all;fsetdecide.\nomega.\nQed.\n\nLemma stays_in_the_plane : forall R N P Q,\nrk(triple R N P) = 3 -> rk(triple R N Q) = 2 -> rk(add Q (triple R N P)) = 3.\nProof.\nintros R N P Q rRNP rRNQ.\nassert (rk(couple R N) = 2).\neapply rk_triple_ABC_couple_AB.\neassumption.\napply le_antisym.\ngeneralize (matroid3 (triple R N P) (triple R N Q)).\nsetoid_replace (union (triple R N P) (triple R N Q)) \nwith (add Q (triple R N P)).\nassert (rk(inter (triple R N P) (triple R N Q))>=rk(couple R N)).\napply matroid2.\nclear_all;fsetdecide.\nomega.\nclear_all;fsetdecide.\nrewrite <- rRNP.\napply matroid2.\nclear_all;fsetdecide.\nQed.\n\n(** How to remove a point from a flat of 4 points whose rank is 3 ? *) \nLemma rk2_3 : forall P Q R S, \nrk(add S (triple P Q R)) = 3->\nrk(triple P Q R)=2->\nrk(couple P Q)=2 ->\nrk(couple R S)=2 ->\nrk(triple P Q S)=3.\nProof.\nintros X Y Z T HXYZT HXYZ HXY HZT.\napply le_antisym.\napply rk_triple_le.\ngeneralize (matroid3 (triple X Y Z) (triple X Y T)).\nsetoid_replace (union (triple X Y Z) (triple X Y T)) with (add T (triple X Y Z)).\nrewrite HXYZT.\nassert (rk  (inter (triple X Y Z) (triple X Y T))>=rk (couple X Y)).\napply matroid2.\nclear_all;fsetdecide.\nomega.\nclear_all;fsetdecide.\nQed.\n\n(** changing one of the points defining a plane in a 3D figure *)\nLemma rk3_4 : forall A B C M P,\nrk(add M (triple A B C)) = 3 ->\nrk(triple B C M) = 3 -> \nrk(add P (triple A B C)) >= 4 ->\nrk(add P (triple M B C)) >= 4.\nProof.\nintros A B C Q P rABCQ rBCQ rABCP.\ngeneralize (matroid3 (add P (triple Q B C)) (add Q (triple A B C))).\nsetoid_replace  (union (add P (triple Q B C)) (add Q (triple A B C))) with\n(union (triple A B C) (couple Q P)).\nassert  (rk (inter (add  P (triple Q B C)) (add Q (triple A B C)))>= rk (triple B C Q)).\napply matroid2.\nclear_all;fsetdecide.\nassert (rk(union (triple A B C) (couple Q P)) >= rk(add P (triple A B C))).\napply matroid2.\nclear_all;fsetdecide.\nomega.\nclear_all;fsetdecide.\nQed.\n\nLemma rank_not_empty : forall E, (exists x, In x E) -> rk E > 0.\nProof.\nintros.\nelim H0; intros x H2; clear H0.\nassert (Subset (singleton x) E) by fsetdecide.\nassert (rk (singleton x) <= rk E) by (apply matroid2; fsetdecide).\nrewrite rk_singleton in H1.\nomega.\nQed.\n\nLemma double_flag : forall  x A B, \nrk (add x A) <= 2 ->\nrk (add x B) <= 2 ->\nrk (add x (union A B)) <= 3.\nProof.\nintros.\nassert (rk (union (add x A) (add x B)) + rk (singleton x) <=\n       rk (add x A) + rk (add x B)).\napply (matroid3_useful).\nfsetdecide.\nrewrite rk_singleton in H2.\nsetoid_replace (add x (union A B))  with (union (add x A) (add x B)) by fsetdecide.\nomega.\nQed.\n\nLemma construction : \n forall n , forall E, rk E = n -> n<=3 -> exists P, rk (add P E) = n+1.\nProof.\nintros.\nassert (T:= rk_lower_dim).\nassert (rk (quadruple P0 P1 P2 P3) = 4).\napply le_antisym.\napply rk_quadruple_le.\nauto.\nclear H2.\nassert (n=0 \\/ n=1 \\/ n=2 \\/ n=3) by omega.\n\n(** Case n=0 *)\nintuition.\nsubst.\nrewrite H3.\nassert (rk (add P0 E) = 0 \\/ rk (add P0 E) = 1).\nassert (rk E <= rk (add P0 E) <= rk E + 1) by apply matroid2'.\nomega.\nassert (rk (add P1 E) = 0 \\/ rk (add P1 E) = 1).\nassert (rk E <= rk (add P1 E) <= rk E + 1) by apply matroid2'.\nomega.\nassert (rk (add P2 E) = 0 \\/ rk (add P2 E) = 1).\nassert (rk E <= rk (add P2 E) <= rk E + 1) by apply matroid2'.\nomega.\nassert (rk (add P3 E) = 0 \\/ rk (add P3 E) = 1).\nassert (rk E <= rk (add P3 E) <= rk E + 1) by apply matroid2'.\nomega.\n\nelim H0;intro;[idtac|firstorder];clear H0.\nelim H2;intro;[idtac|firstorder];clear H2.\nelim H4;intro;[idtac|firstorder];clear H4.\nelim H5;intro;[idtac|firstorder];clear H5.\nassert (rk E = rk (union E (couple P0 P1))).\neapply matroid3';solve[intuition]. \n\nrewrite H3 in H5.\nassert (rk (couple P0 P1) <= rk  (union E (couple P0 P1))).\napply matroid2;fsetdecide.\nassert (rk (couple P0 P1) <= 0) by omega.\nassert (rk (couple P0 P1) >= 1).\napply rk_couple_1.\ncut False;intuition.\n\n(** Case n=1 *)\nsubst.\nrewrite H2.\nassert (rk (add P0 E) = 1 \\/ rk (add P0 E) = 2).\nassert (rk E <= rk (add P0 E) <= rk E + 1) by apply matroid2'.\nomega.\nassert (rk (add P1 E) = 1 \\/ rk (add P1 E) = 2).\nassert (rk E <= rk (add P1 E) <= rk E + 1) by apply matroid2'.\nomega.\nassert (rk (add P2 E) = 1 \\/ rk (add P2 E) = 2).\nassert (rk E <= rk (add P2 E) <= rk E + 1) by apply matroid2'.\nomega.\nassert (rk (add P3 E) = 1 \\/ rk (add P3 E) = 2).\nassert (rk E <= rk (add P3 E) <= rk E + 1) by apply matroid2'.\nomega.\nelim H0;intro;[idtac|firstorder];clear H0.\nelim H4;intro;[idtac|firstorder];clear H4.\nelim H3;intro;[idtac|firstorder];clear H3.\nelim H5;intro;[idtac|firstorder];clear H5.\nassert (rk E = rk (union E (couple P0 P1))).\neapply matroid3';solve[intuition]. \n\nassert (rk E = rk (union E (couple P2 P3))).\napply matroid3';solve[intuition].\n\nassert (rk (union E (union (couple P0 P1) (couple P2 P3))) =rk E).\napply (matroid3'_gen E (couple P0 P1) (couple P2 P3));symmetry;auto.\nrewrite H2 in H8.\nassert (rk (quadruple P0 P1 P2 P3) <= rk (union E (union (couple P0 P1) (couple P2 P3)))).\napply (matroid2).\nclear_all;fsetdecide.\ncut False;intuition.\n\nsubst.\nrewrite H3.\nassert (rk (add P0 E) = 2 \\/ rk (add P0 E) = 3).\nassert (rk E <= rk (add P0 E) <= rk E + 1) by apply matroid2'.\nomega.\nassert (rk (add P1 E) = 2 \\/ rk (add P1 E) = 3).\nassert (rk E <= rk (add P1 E) <= rk E + 1) by apply matroid2'.\nomega.\nassert (rk (add P2 E) = 2 \\/ rk (add P2 E) = 3).\nassert (rk E <= rk (add P2 E) <= rk E + 1) by apply matroid2'.\nomega.\nassert (rk (add P3 E) = 2 \\/ rk (add P3 E) = 3).\nassert (rk E <= rk (add P3 E) <= rk E + 1) by apply matroid2'.\nomega.\nelim H0;intro;[idtac|firstorder];clear H0.\nelim H2;intro;[idtac|firstorder];clear H2.\nelim H4;intro;[idtac|firstorder];clear H4.\nelim H5;intro;[idtac|firstorder];clear H5.\n\nassert (rk E = rk (union E (couple P0 P1))).\neapply matroid3';solve[intuition].\n\nassert (rk E = rk (union E (couple P2 P3))).\napply matroid3';solve[intuition].\n\nassert (rk (union E (union (couple P0 P1) (couple P2 P3))) =rk E).\napply (matroid3'_gen E (couple P0 P1) (couple P2 P3));symmetry;auto.\nrewrite H3 in H8.\nassert (rk (quadruple P0 P1 P2 P3) <= rk (union E (union (couple P0 P1) (couple P2 P3)))).\napply (matroid2).\nclear_all;fsetdecide.\ncut False;intuition.\n\nsubst.\nrewrite H3.\nassert (rk (add P0 E) = 3 \\/ rk (add P0 E) = 4).\nassert (rk E <= rk (add P0 E) <= rk E + 1) by apply matroid2'.\nomega.\nassert (rk (add P1 E) = 3 \\/ rk (add P1 E) = 4).\nassert (rk E <= rk (add P1 E) <= rk E + 1) by apply matroid2'.\nomega.\nassert (rk (add P2 E) = 3 \\/ rk (add P2 E) = 4).\nassert (rk E <= rk (add P2 E) <= rk E + 1) by apply matroid2'.\nomega.\nassert (rk (add P3 E) = 3 \\/ rk (add P3 E) = 4).\nassert (rk E <= rk (add P3 E) <= rk E + 1) by apply matroid2'.\nomega.\nelim H0;intro;[idtac|firstorder];clear H0.\nelim H2;intro;[idtac|firstorder];clear H2.\nelim H4;intro;[idtac|firstorder];clear H4.\nelim H5;intro;[idtac|firstorder];clear H5.\n\nassert (rk E = rk (union E (couple P0 P1))).\napply matroid3';solve[intuition].\n\nassert (rk E = rk (union E (couple P2 P3))).\napply matroid3';solve[intuition]. \n\nassert (rk (union E (union (couple P0 P1) (couple P2 P3))) =rk E).\napply (matroid3'_gen E (couple P0 P1) (couple P2 P3));symmetry;auto.\nrewrite H3 in H8.\nassert (rk (quadruple P0 P1 P2 P3) <= rk (union E (union (couple P0 P1) (couple P2 P3)))).\napply (matroid2).\nclear_all;fsetdecide.\ncut False;intuition.\nQed.\n\nEnd s_rankProperties_2.\n\nHint Resolve rk_singleton rk_couple1 rk_couple2 couple_rk1 couple_rk2 couple_rk_degen : rk_base.", "meta": {"author": "ProjectiveGeometry", "repo": "ProjectiveGeometry", "sha": "4f7f4e6c14580833c91fdef38d048259fb454b88", "save_path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry", "path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry/ProjectiveGeometry-4f7f4e6c14580833c91fdef38d048259fb454b88/Dev/rank_space_or_higher_properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6724450544774374}}
{"text": "(** * Ideals\n\nAuthor: Langston Barrett (@siddharthist)\n*)\n\n(** ** Contents\n\n- Definitions\n  - Left ideals ([lideal])\n  - Right ideals ([rideal])\n  - Two-sided ideals ([ideal])\n  - The above notions coincide for commutative rigs\n- Kernel ideal\n- Unit ideal\n- Prime ideal\n- Localization at a prime ideal\n *)\n\nRequire Import UniMath.Algebra.RigsAndRings.\nRequire Import UniMath.MoreFoundations.Notations.\n\nLocal Open Scope logic.\nLocal Open Scope ring.\nLocal Open Scope rig.\n\nSection Definitions.\n  Context {R : rig}.\n\n  (** *** Left ideals ([lideal]) *)\n\n  Definition is_lideal (S : subabmonoid (rigaddabmonoid R)) : hProp :=\n    ∀ r s : R, S s ⇒ S (r * s).\n\n  Definition lideal : UU := ∑ S : subabmonoid (rigaddabmonoid R), is_lideal S.\n\n  Definition make_lideal :\n    ∏ (S : subabmonoid (rigaddabmonoid R)), is_lideal S → lideal := tpair _.\n\n  (** *** Right ideals ([rideal]) *)\n\n  Definition is_rideal (S : subabmonoid (rigaddabmonoid R)) : hProp :=\n    ∀ r s : R, S s ⇒ S (s * r).\n\n  Definition rideal : UU := ∑ S : subabmonoid (rigaddabmonoid R), is_rideal S.\n\n  Definition make_rideal :\n    ∏ (S : subabmonoid (rigaddabmonoid R)), is_rideal S → rideal := tpair _.\n\n  (** *** Two-sided ideals ([ideal]) *)\n\n  Definition is_ideal (S : subabmonoid (rigaddabmonoid R)) : hProp :=\n    hconj (is_lideal S) (is_rideal S).\n\n  Definition ideal : UU := ∑ S : subabmonoid (rigaddabmonoid R), is_ideal S.\n\n  Definition make_ideal (S : subabmonoid (rigaddabmonoid R))\n             (isl : is_lideal S) (isr : is_rideal S) : ideal :=\n    tpair _ S (make_dirprod isl isr).\n\n  Definition ideal_subabmonoid (I : ideal) : subabmonoid (rigaddabmonoid R) :=\n    pr1 I.\n  Coercion ideal_subabmonoid : ideal >-> subabmonoid.\n\n  Definition ideal_isl (I : ideal) : is_lideal I := pr12 I.\n\n  Definition ideal_isr (I : ideal) : is_rideal I := pr22 I.\n\n  Lemma isaset_ideal : isaset ideal.\n  Proof.\n    apply isaset_total2.\n    - apply isaset_submonoid.\n    - intro S. apply isasetaprop, propproperty.\n  Defined.\nEnd Definitions.\n\nArguments lideal _ : clear implicits.\nArguments rideal _ : clear implicits.\nArguments ideal _ : clear implicits.\nArguments isaset_ideal _ : clear implicits.\n\n(** *** The above notions for commutative rigs *)\n\nLemma commrig_ideals (R : commrig) (S : subabmonoid (rigaddabmonoid  R)) :\n  is_lideal S ≃ is_rideal S.\nProof.\n  apply weqimplimpl.\n  - intros islid r s ss.\n    use transportf.\n    + exact (S (r * s)).\n    + exact (maponpaths S (rigcomm2 _ _ _)).\n    + apply (islid r s ss).\n  - intros isrid r s ss.\n    use transportf.\n    + exact (S (s * r)).\n    + exact (maponpaths S (rigcomm2 _ _ _)).\n    + apply (isrid r s ss).\n  - apply propproperty.\n  - apply propproperty.\nDefined.\n\nCorollary commrig_ideals' (R : commrig) : lideal R ≃ rideal R.\nProof.\n  apply weqfibtototal; intro; apply commrig_ideals.\nDefined.\n\n(** ** Kernel ideal *)\n\n(** The kernel of a rig homomorphism is a two-sided ideal. *)\nDefinition kernel_ideal {R S : rig} (f : rigfun R S) : @ideal R.\nProof.\n  use make_ideal.\n  - use make_submonoid.\n    + exact (@monoid_kernel_hsubtype (rigaddabmonoid R) (rigaddabmonoid S)\n                                      (rigaddfun f)).\n    + (** This does, in fact, describe a submonoid *)\n      apply kernel_issubmonoid.\n  - (** It's closed under × from the left *)\n    intros r s ss; cbn in *.\n    refine (monoidfunmul (rigmultfun f) _ _ @ _); cbn.\n    refine (maponpaths _ ss @ _).\n    refine (rigmultx0 _ (pr1 f r) @ _).\n    reflexivity.\n  - intros r s ss; cbn in *.\n    refine (monoidfunmul (rigmultfun f) _ _ @ _); cbn.\n    abstract (rewrite ss; refine (rigmult0x _ (pr1 f r) @ _); reflexivity).\nDefined.\n\n(** ** Unit ideal *)\n\nLemma ideal_rigunel2 {R : rig} (I : ideal R) : I 1 -> forall x, I x.\nProof.\n  intros H x.\n  apply (transportf (λ x, I x) (rigrunax2 _ x)).\n  exact (ideal_isl _ _ _ H).\nQed.\n\n(** ** Prime ideal *)\n\nSection prime.\n  Context {R : commring}.\n\n  Definition is_prime (I : ideal R) : hProp :=\n    (∀ a b, I (a * b) ⇒ I a ∨ I b) ∧ (¬ I 1).\n\n  Definition prime_ideal : UU := ∑ p : ideal R, is_prime p.\n\n  Definition make_prime_ideal (p : ideal R) (H1 : ∀ a b, p (a * b) ⇒ p a ∨ p b) (H2 : ¬ p 1) :\n    prime_ideal := p ,, H1 ,, H2.\n\n  Definition prime_ideal_ideal (p : prime_ideal) : ideal R := pr1 p.\n  Coercion prime_ideal_ideal : prime_ideal >-> ideal.\n\n  Definition prime_ideal_ax1 (p : prime_ideal) : ∀ a b, p (a * b) ⇒ p a ∨ p b := pr12 p.\n\n  Definition prime_ideal_ax2 (p : prime_ideal) : ¬ p 1 := pr22 p.\nEnd prime.\n\nArguments prime_ideal _ : clear implicits.\n\nSection prime_facts.\n  Context {R : commring} (p : prime_ideal R).\n\n  Lemma isaset_prime_ideal : isaset (prime_ideal R).\n  Proof.\n    apply isaset_total2.\n    - apply isaset_ideal.\n    - intro I. apply isasetaprop, propproperty.\n  Qed.\n\n  Lemma prime_ideal_ax1_contraposition :\n    ∀ a b : R, ¬ p a ⇒ ¬ p b ⇒ ¬ p (a * b).\n  Proof.\n    intros a b Ha Hb.\n    apply (negf (prime_ideal_ax1 p a b)), toneghdisj.\n    exact (make_dirprod Ha Hb).\n  Qed.\nEnd prime_facts.\n\n(** ** Localization at a prime ideal *)\n\nSection localization.\n  Context {R : commring}.\n\n  Definition prime_ideal_complement (p : prime_ideal R) :\n    subabmonoid (ringmultabmonoid R).\n  Proof.\n    use make_submonoid.\n    - intro x. exact (¬ p x).\n    - use make_issubmonoid.\n      + intros a b.\n        exact (prime_ideal_ax1_contraposition _ _ _ (pr2 a) (pr2 b)).\n      + exact (prime_ideal_ax2 p).\n  Defined.\n\n  Definition localization_at (p : prime_ideal R) : commring :=\n    commringfrac _ (prime_ideal_complement p).\n\n  Definition quotient {p : prime_ideal R} (a : R) (b : prime_ideal_complement p) :\n    localization_at p := prcommringfrac _ _ a b.\nEnd localization.\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/RigsAndRings/Ideals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.884039278690883, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6724450543285793}}
{"text": "From Coq Require Import ssreflect ssrbool ssrfun.\nFrom mathcomp Require Import eqtype order ssrnat seq.\nFrom Foata Require Import sseq traces.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection NF.\nContext {disp : unit} {A : orderType disp}.\nVariable (ind : rel A) (ind_irr : irreflexive ind) (ind_sym : symmetric ind).\n\nDefinition step : Type := sseq A.\n\nDefinition foata : Type := sseq step.\n\nDefinition fstring : Type := seq (@string disp A).\n\nDefinition emb' (ss : foata) : fstring := to_seq (smap to_seq ss).\n\nDefinition emb (ss : foata) : string := flatten (emb' ss).\n\nLemma emb_cat' xs ys : emb' (scat xs ys) = emb' xs ++ emb' ys.\nProof.\nelim: ys=>[|s IH a] /=.\n- by rewrite /emb' /= cats0.\nby rewrite /emb' /= in IH *; rewrite IH rcons_cat.\nQed.\n\nLemma emb_cat xs ys : emb (scat xs ys) = emb xs ++ emb ys.\nProof.\nelim: ys=>[|s IH a] /=.\n- by rewrite /emb /= cats0.\nrewrite /emb /emb' /= in IH *.\nby rewrite !flatten_rcons IH catA.\nQed.\n\n(* independence from step elements decider *)\nDefinition si_dec (s : step) (a : A) : bool := all_ind ind a s.\n\nEnd NF.\n\n", "meta": {"author": "clayrat", "repo": "coq-foata", "sha": "258b72f74505e9c2441b4c4b2b6a3dbbf9fb9479", "save_path": "github-repos/coq/clayrat-coq-foata", "path": "github-repos/coq/clayrat-coq-foata/coq-foata-258b72f74505e9c2441b4c4b2b6a3dbbf9fb9479/theories/nf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.67244505170696}}
{"text": "Require Import MathClasses.theory.fields.\nRequire Import MathClasses.interfaces.canonical_names.\nRequire Import MathClasses.interfaces.abstract_algebra.\n\nLemma equal_quotientsl `{Field A}\n(a c: A) b : a = c * `b ↔ a // b = c.\nProof.\n  intros.\n  pose proof (fields.reciperse_alt (1:A)) as Hh.\n  simpl in Hh.\n  specialize (Hh (@field_nontrivial A _ _ _ _ _ _ _ _ _)).\n  rewrite <- (rings.mult_1_r c) at 2.\n  rewrite <- Hh.\n  rewrite (@simple_associativity _ _ mult _ _).\n  rewrite rings.mult_1_r.\n  rewrite <- fields.equal_quotients.\n  simpl. rewrite rings.mult_1_r.\n  tauto.\nQed.\n\nLemma reciperse_altL `{Field F} (x : F) Px : (// x↾Px) * x = 1.\nProof using. \n  rewrite commutativity.\n  now rewrite <-(recip_inverse (x↾Px)). \nQed.\n\n\nSection FieldProps.\nContext `{Field A}.\nAdd Ring tempRing : (stdlib_ring_theory A).\nRequire Import MathClasses.interfaces.orders.\n\nContext `{Le A}\n    `{@orders.SemiRingOrder A equiv plus mult zero one le}.\n    \nContext `{Lt A} {FPSRO:@FullPseudoSemiRingOrder A \nequiv apart plus mult zero one le lt}.\n\nRequire Import MathClasses.interfaces.orders.\nRequire Import MCMisc.rings.\nRequire Import Ring.\n\nLemma FieldLeRecipMultIff : forall \n  (a b k kinv : A),\n  0 < k\n  → kinv*k =1\n  → (k*a ≤ b ↔ a ≤ kinv*b).\nProof using All.\n  intros.\n  apply RingLeRecipMultIff; eauto.\nQed.\n\nDefinition posrecip (k:A) (p:0<k): A.\n  apply recip.\n  exists k.\n  apply apart_iff_total_lt.\n  right. assumption.\nDefined.\n\nLemma FieldLeRecipMultIff2 : forall \n  (a b k : A)\n  (p:0 < k),\n  let kinv := posrecip k p in\n  (k*a ≤ b ↔ a ≤ kinv*b).\nProof using All.\n  intros.\n  apply FieldLeRecipMultIff; auto.\n  apply reciperse_altL.\nQed.\n\n\nEnd FieldProps.\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/fields.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6724048984799547}}
{"text": "(**************************************************************************)\n(*           *                                                            *)\n(*     _     *   The Coccinelle Library / Evelyne Contejean               *)\n(*    <o>    *          CNRS-LRI-Universite Paris Sud                     *)\n(*  -/@|@\\-  *                   A3PAT Project                            *)\n(*  -@ | @-  *                                                            *)\n(*  -\\@|@/-  *      This file is distributed under the terms of the       *)\n(*    -v-    *      CeCILL-C licence                                      *)\n(*           *                                                            *)\n(**************************************************************************)\n\n(**  *Dickson Lemma: the multiset extension of a well-founded ordering is well-founded.\n *)\n\nSet Implicit Arguments. \n\nRequire Export Setoid.\nRequire Import Relations.\nRequire Import List.\nRequire Import more_list.\nRequire Import Multiset.\nRequire Import list_permut.\nRequire Import ordered_set.\nRequire Import Arith.\nRequire Import closure.\nRequire Import FunInd.\n\nLtac dummy a b a_eq_b :=\nassert (Dummy : a = b); [exact a_eq_b | clear a_eq_b; rename Dummy into a_eq_b].\n\nModule Type D.\n\n  Declare Module Import DS : decidable_set.S.\n  Declare Module Import LP : list_permut.S with Definition EDS.A := DS.A \n                                                                  with Definition EDS.eq_A := (@eq DS.A).\n\n(** ** Definition of the multiset extension of a relation. *)\nInductive multiset_extension_step (R : relation A) : list A -> list A -> Prop :=\n  | rmv_case : \n     forall l1 l2 l la a, (forall b, mem EDS.eq_A b la -> R b a) -> \n      permut l1 (la ++ l) -> permut l2 (a :: l) ->\n      multiset_extension_step R l1 l2.\n\n(** [multiset_extension_step] is compatible with permutation. *)\nParameter list_permut_multiset_extension_step_1 :\n  forall R l1 l2 l, permut l1 l2 -> \n  multiset_extension_step R l1 l -> multiset_extension_step R l2 l.\n\nParameter list_permut_multiset_extension_step_2 :\n  forall R l1 l2 l, permut l1 l2 -> \n  multiset_extension_step R l l1 -> multiset_extension_step R l l2.\n\nAdd Parametric Morphism (R : relation A) : (multiset_extension_step R)\n  with signature  permut ==> permut ==> iff \n  as mult_morph.\nAdmitted.\n(** *** Accessibility lemmata. *)\nParameter list_permut_acc :\n  forall R l1 l2, permut l2 l1 -> \n  Acc (multiset_extension_step R) l1 -> Acc (multiset_extension_step R) l2.\n\n(** Main lemma. *)\nParameter dickson : \n  forall R, well_founded R -> well_founded (multiset_extension_step R).\n\nParameter dickson_strong : \n  forall R l, (forall a, In a l -> Acc R a) -> Acc (multiset_extension_step R) l.\n\nParameter context_trans_clos_multiset_extension_step_app1 :\n  forall R l1 l2 l, trans_clos (multiset_extension_step R) l1 l2 ->\n                         trans_clos (multiset_extension_step R) (l ++ l1) (l ++ l2).\n\nFunction consn (ll : list (A * list A)) : list A :=\n  match ll with \n  | nil => nil\n  | (e,_) :: ll => e:: (consn ll)\n  end.\n\nFunction appendn (ll : list (A * list A)) : list A :=\n  match ll with \n  | nil => nil\n  | (_,l) :: ll => l ++ (appendn ll)\n  end.\n\nParameter multiset_closure :\n  forall R, (forall x y, {R x y}+{~R x y}) -> transitive _ R ->\n  forall p q, trans_clos (multiset_extension_step R) p q ->\n  exists l, exists pq,\n  permut p ((appendn l) ++ pq) /\\\n  permut q ((consn l) ++ pq) /\\\n  l <> nil /\\\n  (forall a, forall la, In (a,la) l -> forall b, mem EDS.eq_A b la -> R b a) /\\\n  ((forall a, ~R a a) -> forall a, mem EDS.eq_A a (consn l) -> mem EDS.eq_A a (appendn l) -> False).\n\nEnd D.\n\nModule Make (DS1 : decidable_set.S).\n\nModule Import DS := decidable_set.Convert (DS1).\nModule Import LP := list_permut.Make (DS).\n\n\n\n\n(** ** Definition of the multiset extension of a relation. *)\nInductive multiset_extension_step (R : relation A) : list A -> list A -> Prop :=\n  | rmv_case : \n     forall l1 l2 l la a, (forall b, mem EDS.eq_A b la -> R b a) -> \n      permut l1 (la ++ l) -> permut l2 (a :: l) ->\n      multiset_extension_step R l1 l2.\n\n(** [multiset_extension_step] is compatible with permutation. *)\nLemma list_permut_multiset_extension_step_1 :\n  forall R l1 l2 l, permut l1 l2 -> \n  multiset_extension_step R l1 l -> multiset_extension_step R l2 l.\nProof.\nintros R l1 l2 l P M1; inversion M1 as [ k1 k l1' la a la_R_a P1 P2]; subst.\napply (rmv_case (l1:=l2) (l2:=l) (l:=l1') R la la_R_a); trivial.\napply permut_trans with l1.\napply permut_sym; assumption.\nassumption.\nQed.\n\nLemma list_permut_multiset_extension_step_2 :\n  forall R l1 l2 l, permut l1 l2 -> \n  multiset_extension_step R l l1 -> multiset_extension_step R l l2.\nProof.\nintros R l1 l2 l P M1; inversion M1 as [ k1 k l1' la a la_R_a P1 P2]; subst.\napply (rmv_case (l1:=l) (l2:=l2) (l:=l1') R la la_R_a); trivial.\napply permut_trans with l1.\napply permut_sym; assumption.\nassumption.\nDefined.\n\nAdd Parametric Morphism (R : relation A) : (multiset_extension_step R)\n  with signature  permut ==> permut ==> iff \n  as mult_morph.\nProof.\nintros l1 l2 P12 l3 l4 P34; split; [intro R13 | intro R24].\napply list_permut_multiset_extension_step_2 with l3; trivial.\napply list_permut_multiset_extension_step_1 with l1; trivial.\napply list_permut_multiset_extension_step_2 with l4; auto;\napply list_permut_multiset_extension_step_1 with l2; auto.\nQed.\n\n(** If n << {a} U m, then \n      either, there exists n' such that n = {a} U n' and n' << m,\n      or, there exists k, such that n = k U m, and k << {a}. *)\nLemma two_cases :\n forall R a m n, \n multiset_extension_step R n (a :: m) ->\n (exists n', permut n (a :: n') /\\ \n             multiset_extension_step R n' m) \\/\n (exists k, (forall b, mem EDS.eq_A b k -> R b a) /\\ \n            permut n (k ++ m)).\nProof.\nintros R a m n M; inversion_clear M as [x1 x2 l la b H H0 H1];\ngeneralize (eq_bool_ok a b); case (DS1.eq_bool a b); [intro a_eq_b; subst b | intro a_diff_b].\nrewrite <- permut_cons in H1; [idtac | apply (equiv_refl _ _ eq_proof)].\nright; exists la; split; trivial.\napply permut_trans with (la ++ l).\nassumption.\nrewrite <- permut_app1; auto.\n\nleft; generalize (remove_is_sound b m); case (@remove A eq_bool b m).\nintros m' P; exists (la ++ m'); split.\nrefine (permut_trans H0 _).\napply permut_trans with (la ++ a :: m').\nrefine (proj1 (permut_app1 _ _ _) _).\napply permut_sym.\nrewrite (@permut_cons b b (a :: m') l).\napply permut_trans with (a :: m).\napply permut_sym; rewrite <- (permut_cons_inside (e1 := a) (e2 := a) m (b :: nil) m').\nassumption.\napply (equiv_refl _ _ eq_proof).\nassumption.\napply (equiv_refl _ _ eq_proof).\napply permut_sym; rewrite <- (permut_cons_inside (e1 := a) (e2 := a) (la ++ m') la m').\napply permut_refl.\napply (equiv_refl _ _ eq_proof).\napply (rmv_case (l1:=la ++ m') (l2:= m) (l:= m') R la H); auto; \napply permut_sym; rewrite <- permut_cons_inside; auto.\nintro b_not_mem_m; apply False_rec.\nassert (b_mem_am : mem EDS.eq_A b (a :: m)).\nrewrite (mem_permut_mem b H1); left.\napply (equiv_refl _ _ eq_proof).\nsimpl in b_mem_am; case b_mem_am; clear b_mem_am.\nintro; apply a_diff_b; apply sym_eq; assumption.\nexact b_not_mem_m.\nQed.\n\n\n(** *** Accessibility lemmata. *)\nLemma list_permut_acc :\n  forall R l1 l2, permut l2 l1 -> \n  Acc (multiset_extension_step R) l1 -> Acc (multiset_extension_step R) l2.\nProof.\nintros R l1 l2 Meq A1; apply Acc_intro; intros l M2;\ninversion A1; apply H; subst.\napply list_permut_multiset_extension_step_2 with l2; assumption.\nDefined.\n\n(*\nAdd Parametric Morphism (R : relation A) : \n             Acc (multiset_extension_step R)) : acc_morph.\nProof.\nintros R l1 l2 P; split; [intro A1 | intro A2].\napply list_permut_acc with l1; trivial; rewrite <- P; auto.\napply list_permut_acc with l2; trivial.\nQed.\n*)\n\nLemma dickson_aux1 :\nforall (R : relation A) a,\n (forall b, R b a -> \n  forall m, Acc (multiset_extension_step R) m -> \n            Acc (multiset_extension_step R) (b :: m)) ->\n forall m, Acc (multiset_extension_step R) m -> \n (forall m', (multiset_extension_step R) m' m -> \n             Acc (multiset_extension_step R) (a :: m')) ->\n Acc (multiset_extension_step R) (a :: m).\nProof. \nintros R a IH2_a m Acc_m IHa_M; apply Acc_intro;\nintros n H; elim (two_cases H); clear H.\nintros [n' [P M]]; refine (list_permut_acc P _); apply IHa_M; trivial.\nintros [k [M P]]; refine (list_permut_acc P _); clear P; induction k; trivial; simpl;\napply IH2_a.\napply M; left.\napply (equiv_refl _ _ eq_proof).\napply IHk; intros; apply M; right; trivial.\nDefined.\n\nLemma dickson_aux2 :\nforall R m,\n  Acc (multiset_extension_step R) m ->\n  forall a, (forall b, R b a -> \n             forall m, Acc (multiset_extension_step R) m -> \n                       Acc (multiset_extension_step R) (b :: m)) ->\n   Acc (multiset_extension_step R) (a :: m). \nProof.\nintros R m Acc_m a IH2_a;\napply (Acc_iter  (R:= multiset_extension_step R)\n(fun m => Acc (multiset_extension_step R) m -> \nAcc (multiset_extension_step R) (a :: m))); trivial;\nclear m Acc_m;\nintros m H Acc_m; apply dickson_aux1; trivial;\nintros; apply H; trivial;\napply Acc_inv with m; trivial.\nDefined.\n\nLemma dickson_aux3 :\nforall R a, Acc R a -> forall m, Acc (multiset_extension_step R) m ->\nAcc (multiset_extension_step R) (a :: m).\nProof.\nintros R a Acc_a;\napply (Acc_iter  (R:= R)\n(fun a => Acc R a -> forall m, Acc (multiset_extension_step R) m -> \nAcc (multiset_extension_step R) (a :: m))); trivial;\nclear a Acc_a;\nintros a H Acc_a m Acc_m; apply dickson_aux2; trivial;\nintros; apply H; trivial;\napply Acc_inv with a; trivial.\nDefined.\n\n(** Main lemma. *)\nLemma dickson : \n  forall R, well_founded R -> well_founded (multiset_extension_step R).\nProof.\nintros R Wf_R; unfold well_founded in *;\nintros m; induction m as [ | a m].\napply Acc_intro; intros m H; inversion_clear H;\nabsurd (a :: l = nil).\ndiscriminate.\napply (permut_nil (R := eq_A)).\napply permut_sym; trivial.\napply dickson_aux3; trivial.\nDefined.\n\nLemma dickson_strong : \n  forall R l, (forall a, In a l -> Acc R a) -> Acc (multiset_extension_step R) l.\nProof.\nintros R m; induction m as [ | a m].\nintros _; apply Acc_intro; intros m H; inversion_clear H;\nabsurd (a :: l = nil).\ndiscriminate.\napply (permut_nil (R := eq_A)).\napply permut_sym; trivial.\nintros; apply dickson_aux3.\napply H; left; trivial.\napply IHm; intros; apply H; right; trivial.\nQed.\n\n(** ** More results on transitive closure of mult_step *)\n\nLemma list_permut_trans_clos_multiset_extension_step_1 :\n  forall R l1 l2 l, permut l1 l2 -> \n  (trans_clos (multiset_extension_step R)) l1 l -> \n  (trans_clos (multiset_extension_step R)) l2 l.\nProof.\nintros R l1 l1' l P H; induction H as [ l1 l2 H | l1 l2 l3 H1 H2 H3].\napply t_step; apply list_permut_multiset_extension_step_1 with l1; trivial.\napply t_trans with l2; trivial; apply list_permut_multiset_extension_step_1 with l1; trivial.\nQed.\n\nLemma list_permut_trans_clos_multiset_extension_step_2 :\n  forall R l1 l2 l, permut l1 l2 -> \n  (trans_clos (multiset_extension_step R)) l l1 -> \n  (trans_clos (multiset_extension_step R)) l l2.\nProof.\nintros R l1 l3 l P H; induction H as [ l1 l2 H | l1 l2 l3' H1 H2 H3].\napply t_step; apply list_permut_multiset_extension_step_2 with l2; trivial.\napply t_trans with l2; trivial; apply H3; trivial.\nQed.\n\nLemma context_multiset_extension_step_app1 :\n  forall R l1 l2 l, multiset_extension_step R l1 l2 ->\n                         multiset_extension_step R (l ++ l1) (l ++ l2).\nProof.\nintros R l1 l2 l H; destruct H as [l1 l2 l12 la a H P1 P2].\napply (@rmv_case R (l++l1) (l++l2) (l++l12) la a); trivial.\napply permut_trans with (l ++ la ++ l12).\nrewrite <- permut_app1; trivial.\ndo 2 rewrite <- app_ass; rewrite <- permut_app2; trivial.\napply list_permut_app_app.\napply permut_trans with (l ++ a :: l12).\nrewrite <- permut_app1; trivial.\napply permut_sym; rewrite <- permut_cons_inside.\napply permut_refl.\napply (equiv_refl _ _ eq_proof).\nQed.\n\nLemma context_trans_clos_multiset_extension_step_app1 :\n  forall R l1 l2 l, trans_clos (multiset_extension_step R) l1 l2 ->\n                         trans_clos (multiset_extension_step R) (l ++ l1) (l ++ l2).\nProof.\nintros R l1 l2 l H; induction H.\napply t_step; apply context_multiset_extension_step_app1; trivial.\napply t_trans with (l ++ y); trivial.\napply context_multiset_extension_step_app1; trivial.\nQed.\n\nLemma context_multiset_extension_step_cons :\n  forall R, (forall a, ~R a a) -> \n  forall a l1 l2, multiset_extension_step R (a :: l1) (a :: l2) ->\n                         multiset_extension_step R l1 l2.\nProof.\nintros R irrefl_R a l1 l2 H;\ninversion H as [a_l1 a_l2 lc lb b H' P1 P2 H2 H3]; subst.\nassert (a_mem_blc : mem EDS.eq_A a (b :: lc)).\napply cons_permut_mem with l2 a; trivial.\napply (equiv_refl _ _ eq_proof).\nsimpl in a_mem_blc; destruct a_mem_blc as [a_eq_b | a_mem_lc].\ndummy a b a_eq_b;\nsubst b; assert (a_mem_lb_lc : mem EDS.eq_A a (lb ++ lc)).\napply cons_permut_mem with l1 a; trivial.\napply (equiv_refl _ _ eq_proof).\nrewrite <- mem_or_app in a_mem_lb_lc.\ndestruct a_mem_lb_lc as [a_mem_lb | a_mem_lc].\nabsurd (R a a); [apply (irrefl_R a) | apply H'; trivial].\ngeneralize (mem_split_set _ _ eq_bool_ok _ _ a_mem_lc).\nintros [a' [lc' [lc'' [a_eq_a' [H'' _]]]]]; \ndummy a a' a_eq_a';\nsubst a' lc; apply (rmv_case R (l1:=l1) (l2:= l2) (l:=lc' ++ lc'') lb (a:=a)); trivial.\nrewrite <- app_ass in P1; rewrite <- (permut_cons_inside) in P1.\nrewrite <- ass_app in P1; trivial.\napply (equiv_refl _ _ eq_proof).\nrewrite app_comm_cons in P2; rewrite <- (permut_cons_inside) in P2; trivial.\napply (equiv_refl _ _ eq_proof).\n\ngeneralize (mem_split_set _ _ eq_bool_ok _ _ a_mem_lc).\nintros [a' [lc' [lc'' [a_eq_a' [H'' _]]]]]; \ndummy a a' a_eq_a';\nsubst a' lc; apply (rmv_case R (l1:=l1) (l2:= l2) (l:=lc' ++ lc'') lb (a:=b)); trivial.\nrewrite <- app_ass in P1; rewrite <- (permut_cons_inside) in P1.\nrewrite <- ass_app in P1; trivial.\napply (equiv_refl _ _ eq_proof).\nrewrite app_comm_cons in P2; rewrite <- (permut_cons_inside) in P2.\nsimpl  in P2; trivial.\napply (equiv_refl _ _ eq_proof).\nQed.\n\nLemma remove_context_multiset_extension_step_app1 :\n  forall R,  (forall a, ~R a a) -> \n  forall l1 l2 l, multiset_extension_step R (l ++ l1) (l ++ l2) ->\n                         multiset_extension_step R l1 l2.\nProof.\nintros R irrefl_R l1 l2 l; generalize l1 l2; clear l1 l2; \ninduction l as [ | a l]; trivial.\nintros l1 l2 H; \nassert (H' : multiset_extension_step R (a :: l1) (a :: l2)).\napply IHl.\napply list_permut_multiset_extension_step_2 with ((a :: l) ++ l2).\nsimpl; rewrite <- permut_cons_inside; auto.\napply (equiv_refl _ _ eq_proof).\napply list_permut_multiset_extension_step_1 with ((a :: l) ++ l1); trivial.\nsimpl; rewrite <- permut_cons_inside; auto.\napply (equiv_refl _ _ eq_proof).\napply context_multiset_extension_step_cons with a; trivial.\nQed.\n\nLemma context_multiset_extension_step_app2 :\n  forall R l1 l2 l, multiset_extension_step R l1 l2 ->\n                         multiset_extension_step R (l1 ++ l) (l2 ++ l).\nProof.\nintros R l1 l2 l H; destruct H as [l1 l2 l12 la a H P1 P2].\napply (@rmv_case R (l1++l) (l2++l) (l12++l) la a); trivial.\nrewrite <- app_ass; rewrite <- permut_app2; trivial.\nrewrite app_comm_cons; rewrite <- permut_app2; trivial.\nQed.\n\nFunction consn (ll : list (A * list A)) : list A :=\n  match ll with \n  | nil => nil\n  | (e,_) :: ll => e:: (consn ll)\n  end.\n\nLemma mem_consn : \n  forall a ll, mem EDS.eq_A a (consn ll) <-> exists la, In (a,la) ll.\nProof.\nintros a ll; split; intro H;\nfunctional induction (consn ll) \n   as [ | H1 b lb ll H2 IH].\ncontradiction.\nsimpl in H; destruct H as [a_eq_b | a_in_cnsl].\ndummy a b a_eq_b;\nexists lb; subst; left; trivial.\ndestruct (IH a_in_cnsl) as [la H].\nexists la; right; trivial.\ndestruct H; contradiction.\ndestruct H as [la [ala_eq_blb | ala_in_ll]].\ninjection ala_eq_blb; intros; subst; left; apply (equiv_refl _ _ eq_proof); trivial.\nright; apply IH; exists la; trivial.\nQed.\n\nLemma consn_app :\n forall ll1 ll2, consn (ll1 ++ ll2) = consn ll1 ++ consn ll2.\nProof.\nintros ll1; induction ll1 as [ | [a la] ll1]; simpl; trivial; simpl; \nintros; rewrite IHll1; trivial.\nQed.\n\nFunction appendn (ll : list (A * list A)) : list A :=\n  match ll with \n  | nil => nil\n  | (_,l) :: ll => l ++ (appendn ll)\n  end.\n\nLemma appendn_app :\n forall ll1 ll2, appendn (ll1 ++ ll2) = appendn ll1 ++ appendn ll2.\nProof.\nintros ll1; induction ll1 as [ | [a la] ll1]; simpl; trivial; simpl; \nintros; rewrite IHll1; rewrite ass_app; trivial.\nQed.\n\nLemma in_appendn : \n  forall a ll, mem EDS.eq_A a (appendn ll) -> exists b, exists lb, In (b,lb) ll /\\ mem EDS.eq_A a lb.\nProof.\nintros a ll H; \nfunctional induction (appendn ll) \n   as [ | H1 b lb ll H2 IH].\ncontradiction.\nrewrite <- mem_or_app in H; destruct H as [a_mem_lb | a_mem_appl].\nexists b; exists lb; split; trivial; left; trivial.\ndestruct (IH a_mem_appl) as [c [lc [H1 H2]]]; \nexists c; exists lc; split; trivial; right; trivial.\nQed.\n\nLemma multiset_closure_aux :\n  forall (R : relation A) p q l pq, \n  permut p ((appendn l) ++ pq) ->\n  permut q ((consn l) ++ pq) ->\n  l <> nil ->\n  (forall a, forall la, In (a,la) l -> forall b, mem EDS.eq_A b la -> R b a) ->\n  trans_clos (multiset_extension_step R) p q.\nProof.\nintros R p q l; generalize p q; clear p q; induction l as [ | [x lx] l].\nsimpl; intros p q pq Pp Pq H; absurd (@nil (A * list A) = nil); trivial.\nsimpl; intros p q pq Pp Pq _ H.\nassert (lx_lt_x : forall b, mem EDS.eq_A b lx -> R b x).\napply H; left; trivial.\ndestruct l as [ | [y ly] l]; simpl in *.\nrewrite <- app_nil_end in Pp.\nsimpl in Pq; apply t_step. \nexact (rmv_case R lx lx_lt_x Pp Pq).\napply t_trans with (x :: ly ++ (appendn l) ++ pq).\ndo 2 rewrite app_ass in Pp;\nrefine (rmv_case R lx lx_lt_x Pp (permut_refl _)).\nrefine (list_permut_trans_clos_multiset_extension_step_2  \n                      (permut_sym Pq) _).\napply (@context_trans_clos_multiset_extension_step_app1 R\n            (ly ++ appendn l ++ pq) (y :: consn l ++ pq) (x :: nil)); \napply (@IHl (ly ++ appendn l ++ pq) (y :: consn l ++ pq) pq); auto.\nrewrite ass_app; auto.\ndiscriminate.\nintros a la H1 b b_in_la; apply (H a la); trivial; right; trivial.\nQed.\n\nLemma multiset_closure_aux2 :\n  forall (R : relation A) p q le l pq, \n  permut p ((appendn l) ++ pq) ->\n  permut q (le ++ (consn l) ++ pq) ->\n  l <> nil \\/ le <> nil ->\n  (forall a, forall la, In (a,la) l -> forall b, mem EDS.eq_A b la -> R b a) ->\n  trans_clos (multiset_extension_step R) p q.\nProof.\nintros R p q le l pq Pp Pq H H';\napply (@multiset_closure_aux R p q ((map (fun x => (x, @nil A)) le) ++ l) pq).\napply permut_trans with (appendn l ++ pq).\nassumption.\nrewrite <- permut_app2;\nrewrite appendn_app; clear Pq H; induction le as [ | e le]; simpl; auto.\napply permut_trans with (le ++ consn l ++ pq).\nassumption.\nrewrite ass_app; rewrite <- permut_app2;\nrewrite consn_app; clear Pq H; induction le as [ | e le]; simpl; auto.\nrewrite <- permut_cons; trivial.\napply (equiv_refl _ _ eq_proof).\nintro H''; destruct (app_eq_nil _ _ H'') as [ l_eq_nil le_eq_nil];\ndestruct H as [le_diff_nil | l_diff_nil].\nabsurd (l = nil); trivial.\ndestruct le as [ | e le].\nabsurd (@nil A = nil); trivial.\ndiscriminate.\nclear Pq H; induction le as [ | e le]; simpl; trivial.\nintros a la [H | H] b b_in_la; \n[injection H; intros; subst; contradiction | apply (IHle a la); trivial].\nQed.\n\n\nModule LDS.\n\nDefinition A := (A * (list A))%type.\nDefinition eq_A := @eq A.\n\nLemma eq_proof : equivalence A eq_A.\nunfold eq_A; split.\nintro n; apply refl_equal.\nintros a1 a2 a3 H1 H2; rewrite H1; assumption.\nintros a1 a2 H; rewrite H; apply refl_equal.\nQed.\n\n  Add Relation A eq_A \n  reflexivity proved by (Relation_Definitions.equiv_refl _ _ eq_proof)\n    symmetry proved by (Relation_Definitions.equiv_sym _ _ eq_proof)\n      transitivity proved by (Relation_Definitions.equiv_trans _ _ eq_proof) as EQA.\n\nFixpoint eq_bool_list l1 l2: bool :=\n     match l1, l2 with\n     | nil, nil => true\n     | nil, (_ :: _) => false\n     | (a1 :: l1), nil => false\n     | (a1 :: l1), (a2 :: l2) => if DS1.eq_bool a1 a2 then eq_bool_list l1 l2 else false\n     end.\n\nDefinition eq_bool al1 al2 : bool :=  \n  match al1, al2 with\n  | (e1,l1), (e2,l2) => if DS1.eq_bool e1 e2 then eq_bool_list l1 l2 else false\n  end.\n\nLemma eq_bool_ok : forall al1 al2, match eq_bool al1 al2 with true => al1 = al2 | false => ~al1 = al2 end.\nProof.\nintros [e1 l1] [e2 l2]; simpl.\ngeneralize (DS1.eq_bool_ok e1 e2); case (DS1.eq_bool e1 e2); [intros e1_eq_e2 | intros e1_diff_e2].\nrevert l1 l2.\nassert (H :  forall l1 l2, match eq_bool_list l1 l2 with true => l1 = l2 | false => ~l1 = l2 end).\nfix eq_bool_ok0 1.\nintros [ | a1 l1] [ | a2 l2]; simpl.\napply refl_equal.\ndiscriminate.\ndiscriminate.\ngeneralize (DS1.eq_bool_ok a1 a2); case (DS1.eq_bool a1 a2); [intros a1_eq_a2 | intros a1_diff_a2].\ngeneralize (eq_bool_ok0 l1 l2); case (eq_bool_list l1 l2); [intro l1_eq_l2 | intro l1_diff_l2].\nsubst; apply refl_equal.\nintro E; apply l1_diff_l2; injection E; intros; subst; apply refl_equal.\nintro E; apply a1_diff_a2; injection E; intros; subst; apply refl_equal.\nintros l1 l2; generalize (H l1 l2).\ncase (eq_bool_list l1 l2); [intro l1_eq_l2 | intro l1_diff_l2].\nsubst; apply (equiv_refl _ _ eq_proof).\nintro E; apply l1_diff_l2; injection E; intros; subst; apply refl_equal.\nintro E; apply e1_diff_e2; injection E; intros; subst; apply refl_equal.\nDefined.\n\nEnd LDS.\n\nModule LEDS := decidable_set.Convert(LDS).\nModule LLP := list_permut.Make (LEDS).\n\nLemma permut_consn :\n forall ll1 ll2, LLP.permut ll1 ll2 -> permut (consn ll1) (consn ll2).\nProof.\nintros ll1; induction ll1 as [ | [a la] ll1]; simpl; intros ll2 P.\nrewrite (permut_nil (LLP.permut_sym P)); simpl; auto.\nassert (ala_in_ll2 : In (a,la) ll2).\nrewrite <- (in_permut_in P); left; trivial.\ndestruct (In_split _ _ ala_in_ll2) as [ll2' [ll2'' H]]; subst.\nrewrite <- LLP.permut_cons_inside in P.\nrewrite consn_app; simpl; rewrite <- permut_cons_inside.\nrewrite <- consn_app; apply IHll1; trivial.\napply (equiv_refl _ _ eq_proof).\napply (equiv_refl _ _ LEDS.eq_proof).\nQed.\n\nLemma permut_appendn :\n forall ll1 ll2, LLP.permut ll1 ll2 -> permut (appendn ll1) (appendn ll2).\nProof.\nintros ll1; induction ll1 as [ | [a la] ll1]; simpl; intros ll2 P.\nrewrite (permut_nil (LLP.permut_sym P)); simpl; auto.\nassert (ala_in_ll2 : In (a,la) ll2).\nrewrite <- (in_permut_in P); left; trivial.\ndestruct (In_split _ _ ala_in_ll2) as [ll2' [ll2'' H]]; subst.\nrewrite appendn_app; simpl.\nrefine (permut_trans _ (list_permut_app_app _ _)).\nrewrite <- ass_app.\nrewrite <- permut_app1.\nrefine (permut_trans _ (list_permut_app_app _ _)).\nrewrite <- appendn_app; apply IHll1; trivial.\nrewrite <- LLP.permut_cons_inside in P; trivial.\napply (equiv_refl _ _ LEDS.eq_proof).\nQed.\n\nLemma multiset_closure_aux3 :\n  forall l lc cns, permut (consn l) (lc ++ cns) ->\n               exists ll, exists ll',  LLP.permut l (ll ++ ll') /\\ \n                                           permut (consn ll)  lc /\\ \n                                           permut (consn ll') cns.\nProof.\nassert (H : forall consnl lccns, permut consnl lccns -> \n               forall l lc cns ,  consnl = consn l -> lccns = lc ++ cns ->\n               exists ll, exists ll',  LLP.permut l (ll ++ ll') /\\ \n                                           permut (consn ll)  lc /\\ \n                                           permut (consn ll') cns).\nintros consnl lccns P; induction P as [ | a1 a1' consnl k1 k2 H P].\nintros [ | [a1 l1] l].\nintros [ | c lc].\nintros [ | c' cns] H1 H2.\nexists (@nil (A * list A)); exists (@nil (A * list A)); simpl; repeat split; auto.\ndiscriminate.\nintros cns _ H2; discriminate.\nintros lc cns H1; discriminate.\nintros [ | [b1 l1] l] lc cns H1 H2.\ndiscriminate.\ninjection H1; clear H1; intros; subst.\ngeneralize (split_list _ _ _ _ H2); clear H2; intros [[k [H3 H4]] | [k [H3 H4]]]; subst.\ngeneralize (IHP l lc (k ++ k2) (refl_equal _)); rewrite ass_app.\nintro IH; generalize (IH (refl_equal _)); clear IH.\nintros [ll [ll' [Q1 [Q2 Q3]]]].\nexists ll; exists ((b1,l1) :: ll'); simpl; repeat split; trivial.\nrewrite <- LLP.permut_cons_inside; [assumption | apply refl_equal].\nrewrite <- permut_cons_inside; assumption.\nrevert H4; case k; [idtac | intros a k']; intro H4.\nsimpl in H4; subst.\ngeneralize (IHP l k1 k2 (refl_equal _) (refl_equal _)).\nintros [ll [ll' [Q1 [Q2 Q3]]]].\nexists ll; exists ((b1,l1) :: ll'); repeat split.\nrewrite <- LLP.permut_cons_inside; [assumption | apply refl_equal].\nrewrite <- app_nil_end; assumption.\nsimpl; rewrite <- permut_cons; assumption.\ninjection H4; clear H4; intros; subst a k2.\nassert (IH := IHP l (k1 ++ k') cns (refl_equal _)).\nrewrite ass_app in IH.\ngeneralize (IH (refl_equal _)); clear IH; intros [ll [ll' [Q1 [Q2 Q3]]]].\nexists ((b1, l1) :: ll); exists ll'; repeat split.\nsimpl; rewrite <- LLP.permut_cons; [assumption | apply refl_equal].\nsimpl; rewrite <- permut_cons_inside; assumption.\nassumption.\nintros l lc cns P; apply (H (consn l) (lc ++ cns) P _ _ _ (refl_equal _) (refl_equal _)).\nQed.\n\nLemma multiset_closure :\n  forall R, transitive _ R ->\n  forall p q, trans_clos (multiset_extension_step R) p q ->\n  exists l, exists pq,\n  permut p ((appendn l) ++ pq) /\\\n  permut q ((consn l) ++ pq) /\\\n  l <> nil /\\\n  (forall a, forall la, In (a,la) l -> forall b, mem EDS.eq_A b la -> R b a) /\\\n  ((forall a, ~R a a) -> forall a, mem EDS.eq_A a (consn l) -> mem EDS.eq_A a (appendn l) -> False).\nProof.\nintros R trans_R p q p_lt_q; induction p_lt_q as [p q p_lt_q | p q r p_lt_q q_lt_r].\n(* R_step *)\ndestruct p_lt_q as [p q pq la a la_lt_a Pp Pq].\nexists ((a,la) :: nil); exists pq; simpl; repeat split; auto.\nrewrite <- app_nil_end; auto.\ndiscriminate.\nintros x lx [H | H] b b_in_lx; \n[injection H; intros; subst; apply la_lt_a; trivial | contradiction].\nrewrite <- app_nil_end; intros irrefl_R b [a_eq_b | Abs] b_in_la.\ndummy b a a_eq_b;\nsubst b; apply (irrefl_R a); apply la_lt_a; trivial.\ncontradiction.\n\n(* Transitive step *)\ndestruct p_lt_q as [p q pq la a la_lt_a Pp Pq].\ndestruct IHq_lt_r as [l [qr [Pq' [Pr [l_diff_nil [app_lt_cns app_disj_cns]]]]]].\nassert (a_in_appl_qr : mem EDS.eq_A a ((appendn l) ++ qr)).\napply (proj1 (mem_permut_mem a Pq')).\napply (proj1 (mem_permut_mem a (permut_sym Pq))).\nleft; apply (equiv_refl _ _ eq_proof).\nrewrite <- mem_or_app in a_in_appl_qr.\ngeneralize (mem_bool_ok _ _ EDS.eq_bool_ok a (appendn l)).\ncase (mem_bool EDS.eq_bool a (appendn l)); [intro a_in_appl | intro a_not_in_appl].\ndestruct (in_appendn _ _ a_in_appl) as [x [lx [xlx_in_l a_in_lx]]].\ndestruct (mem_split_set _ _ eq_bool_ok _ _ a_in_lx) as [a' [lx' [lx'' [a_eq_a' [H _]]]]].\nsimpl in a_eq_a'; simpl in H; subst lx.\ndestruct (In_split _ _  xlx_in_l) as [l' [l'' H]]; subst l.\nrewrite appendn_app in Pq'; simpl in Pq'; do 3 rewrite <-  ass_app in Pq'.\nsimpl in Pq'; rewrite ass_app in Pq'.\ngeneralize (permut_trans (permut_sym Pq) Pq'); clear Pq'; intro Pq'.\nrewrite <- permut_cons_inside in Pq'.\nrewrite <- ass_app in Pq'.\ngeneralize (remove_equiv_is_sound (consn (l' ++ l'')) la).\ndestruct (@remove_equiv A eq_bool  (consn (l' ++ l'')) la) as [cns la'].\nintros [lc [Pcns [Pla cns_disj_la']]];\ndestruct (multiset_closure_aux3 (l' ++ l'') lc cns Pcns) as [ll [ll' [P' [H1 H2]]]];\nexists ((x, lx' ++ lx'' ++ la' ++ (appendn ll)) :: ll'); exists (lc ++ qr); split.\napply permut_trans with (la ++ pq).\nassumption.\napply permut_trans with ((lc ++ la') ++ pq).\nrewrite <- permut_app2; trivial.\napply permut_trans with ((lc ++ la') ++ (appendn l' ++ lx' ++ lx'' ++ appendn l'' ++ qr)).\nrewrite <- permut_app1; trivial.\nsimpl; do 5 rewrite ass_app; rewrite <- permut_app2.\nrefine (permut_trans _ (list_permut_app_app _ _)).\ndo 5 rewrite <- ass_app; rewrite <- permut_app1.\nrewrite ass_app.\nrefine (permut_trans (list_permut_app_app _ _) _).\ndo 3 rewrite <- ass_app; do 2 rewrite <- permut_app1.\nrefine (permut_trans (list_permut_app_app _ _) _).\ndo 2 rewrite <- ass_app; rewrite <- permut_app1.\ndo 2 rewrite <- appendn_app; apply permut_appendn; trivial.\nsplit.\nrewrite ass_app.\napply permut_trans with (consn (l' ++ (x, lx' ++ a' :: lx'') :: l'') ++ qr).\nassumption.\nrewrite <- permut_app2;\nrewrite consn_app; simpl; apply permut_sym; \nrewrite <- permut_cons_inside.\napply permut_trans with (cns ++ lc).\nrewrite <- permut_app2; assumption.\nrefine (permut_trans (list_permut_app_app _ _) _).\napply permut_trans with  (consn (l' ++ l'')).\napply permut_sym; assumption.\nrewrite consn_app; auto.\napply (equiv_refl _ _ eq_proof).\nsplit.\ndiscriminate.\nsplit.\nsimpl; intros y ly [yly_eq_xly | yly_in_ll''] b b_in_ly.\ninjection yly_eq_xly; intros; subst y ly; clear yly_eq_xly.\nrewrite ass_app in b_in_ly;\nrewrite <- mem_or_app in b_in_ly.\ndestruct b_in_ly as [b_in_lx | b_in_la_app].\napply (app_lt_cns x (lx' ++ a' :: lx'')); trivial.\napply mem_insert; trivial.\nrewrite <- mem_or_app in b_in_la_app.\ndestruct b_in_la_app as [b_in_la | b_in_app].\napply trans_R with a.\napply la_lt_a.\nrewrite (mem_permut_mem b Pla); rewrite <- mem_or_app; right; trivial.\napply (app_lt_cns x (lx' ++ a' :: lx'')); trivial.\ndestruct (in_appendn _ _ b_in_app) as [y [ly [yly_in_ll b_in_ly]]].\napply trans_R with y.\napply (app_lt_cns y ly); trivial; apply in_insert.\nrewrite (list_permut.in_permut_in P'); apply in_or_app; left; trivial.\nassert (y_in_lc : mem eq_A y lc).\nrewrite <- (mem_permut_mem y H1).\nrewrite mem_consn; exists ly; trivial.\napply trans_R with a.\napply la_lt_a; rewrite (mem_permut_mem y Pla); rewrite <- mem_or_app; left; trivial.\napply (app_lt_cns x (lx' ++ a' :: lx'')).\napply in_or_app; right; left; apply refl_equal.\nrewrite <- mem_or_app; right; left; trivial.\napply (app_lt_cns y ly); trivial; apply in_insert; trivial.\nrewrite (list_permut.in_permut_in P').\napply in_or_app; right; trivial.\nsimpl; intros irrefl_R b [x_eq_b | b_in_cns] b_in_lx_la_app;\ndo 3 rewrite <- ass_app in b_in_lx_la_app; do 2 rewrite ass_app in b_in_lx_la_app.\ndummy b x x_eq_b;\nsubst b; rewrite <- mem_or_app in b_in_lx_la_app.\ndestruct b_in_lx_la_app as [b_in_lx_la | b_in_app].\nrewrite <- mem_or_app in b_in_lx_la.\ndestruct b_in_lx_la as [b_in_lx | b_in_la].\napply (irrefl_R x); apply (app_lt_cns x (lx' ++ a' :: lx'')).\napply in_or_app; right; left; apply refl_equal.\napply mem_insert; trivial.\napply (irrefl_R x); apply trans_R with a.\napply la_lt_a; rewrite (mem_permut_mem x Pla); rewrite <- mem_or_app; right; trivial.\napply (app_lt_cns x (lx' ++ a' :: lx'')).\napply in_or_app; right; left; apply refl_equal.\nrewrite <- mem_or_app; right; left; trivial.\napply (app_disj_cns irrefl_R x).\nrewrite consn_app; rewrite <- mem_or_app; right; left.\napply (equiv_refl _ _ eq_proof).\nrewrite <- appendn_app in b_in_app.\nrewrite <- (mem_permut_mem x (permut_appendn P')) in b_in_app.\nrewrite appendn_app; rewrite <- mem_or_app.\nrewrite appendn_app in b_in_app; rewrite <- mem_or_app in b_in_app.\ndestruct b_in_app as [b_in_app | b_in_app].\nleft; trivial.\nright; simpl; rewrite <- mem_or_app; right; trivial.\nsimpl; rewrite <- mem_or_app in b_in_lx_la_app.\ndestruct b_in_lx_la_app as [b_in_lx_la | b_in_app].\nsimpl; rewrite <- mem_or_app in b_in_lx_la.\ndestruct b_in_lx_la as [b_in_lx | b_in_la].\napply (app_disj_cns irrefl_R b).\nrewrite consn_app; simpl; apply mem_insert; rewrite <- consn_app. \nrewrite (mem_permut_mem b (permut_consn P'));\nrewrite consn_app; rewrite <- mem_or_app; right; trivial.\nrewrite appendn_app; rewrite <- mem_or_app; right;\nsimpl; rewrite <- mem_or_app; left; apply mem_insert; trivial.\napply (cns_disj_la' b); trivial.\nrewrite <- (mem_permut_mem b H2); trivial.\napply (app_disj_cns irrefl_R b).\nrewrite consn_app; simpl; apply mem_insert;\nrewrite <- consn_app; rewrite (mem_permut_mem b (permut_consn P'));\nrewrite consn_app; rewrite <- mem_or_app; right; trivial.\nrewrite <- appendn_app in b_in_app;\nrewrite <- (mem_permut_mem b (permut_appendn P')) in b_in_app.\nrewrite appendn_app; rewrite <- mem_or_app;\nrewrite appendn_app in b_in_app. \nrewrite <- mem_or_app in b_in_app; \ndestruct b_in_app as [b_in_app | b_in_app];\n[left | simpl; right; rewrite <- mem_or_app; right]; trivial.\ntrivial.\nassert (a_in_qr : mem eq_A a qr).\ndestruct a_in_appl_qr as [a_in_appl | a_in_qr]; trivial.\nabsurd (mem eq_A a (appendn l)); trivial.\ndestruct (mem_split_set _ _ eq_bool_ok _ _ a_in_qr) as [a' [qr' [qr'' [a_eq_a' [H _]]]]]; subst qr.\ngeneralize (permut_trans (permut_sym Pq) Pq'); clear Pq'; intro Pq'.\nrewrite ass_app in Pq';\nrewrite <- permut_cons_inside in Pq'; rewrite <- ass_app in Pq'.\ngeneralize (remove_equiv_is_sound (consn l) la);\ndestruct (@remove_equiv A eq_bool (consn l) la) as [cns la'];\nintros [lc [Pcns [Pla cns_disj_la']]];\ndestruct (multiset_closure_aux3 l lc cns Pcns) as [ll [ll' [P' [H1 H2]]]].\nexists ((a, la' ++ (appendn ll)) :: ll'); exists (lc ++ (qr' ++ qr'')); split.\nsimpl; apply permut_trans with (la ++ pq).\nassumption.\napply permut_trans with (la ++ (appendn l ++ qr' ++ qr'')).\nrewrite <- permut_app1.\nassumption.\ndo 4 rewrite ass_app; do 2 rewrite <- permut_app2.\napply permut_trans with ((lc ++ la') ++ appendn l).\nrewrite <- permut_app2; assumption.\nrewrite <- ass_app; refine (permut_trans (list_permut_app_app _ _) _);\nrewrite <- permut_app2; rewrite <- ass_app;\nrewrite <- appendn_app; rewrite <- permut_app1.\napply permut_appendn; assumption.\nsplit.\napply permut_trans with (consn l ++ qr' ++ a' :: qr'').\nassumption.\nsimpl; rewrite ass_app; apply permut_sym; \nrewrite <- permut_cons_inside; trivial.\ndo 2 rewrite ass_app;\ndo 2 rewrite <- permut_app2.\napply permut_trans with (consn ll' ++ consn ll).\nrewrite <- permut_app1; apply permut_sym; assumption.\nrewrite <- consn_app; apply permut_consn.\napply LLP.permut_trans with (ll ++ ll').\napply LLP.list_permut_app_app.\napply LLP.permut_sym; assumption.\nsplit.\ndiscriminate.\nsplit.\nintros y ly [yly_eq_aly | yly_in_ll'] b b_in_ly.\ninjection yly_eq_aly; intros; subst y ly; clear yly_eq_aly.\nrewrite <- mem_or_app in b_in_ly.\ndestruct b_in_ly as [b_in_la' | b_in_app].\napply la_lt_a.\nrewrite (mem_permut_mem b Pla).\nrewrite <- mem_or_app; right; trivial.\ndestruct (in_appendn _ _ b_in_app) as [z [lz [zlz_in_ll b_in_lz]]].\napply trans_R with z.\napply (app_lt_cns z lz); trivial.\nrewrite (list_permut.in_permut_in P').\napply in_or_app; left; trivial.\napply la_lt_a; rewrite (mem_permut_mem z Pla); rewrite <- mem_or_app; left.\nrewrite <- (mem_permut_mem z H1).\nrewrite mem_consn; exists lz; trivial.\napply (app_lt_cns y ly); trivial; \nrewrite (list_permut.in_permut_in P'); apply in_or_app; right; trivial.\nintros irrefl_R; simpl; rewrite <- ass_app; rewrite ass_app;\nintros b b_in_a_cns b_in_la_app.\nrewrite <- mem_or_app in b_in_la_app.\ndestruct b_in_la_app as [b_in_la | b_in_app].\ndestruct b_in_a_cns as [b_eq_a | b_in_cns].\nrewrite <- mem_or_app in b_in_la.\ndestruct b_in_la as [b_in_la' | b_in_app].\napply (irrefl_R a); apply la_lt_a; rewrite (mem_permut_mem a Pla); \nrewrite <- mem_or_app; right; \ndummy b a b_eq_a;\nsubst; trivial.\ndestruct (in_appendn _ _ b_in_app) as [z [lz [zlz_in_ll b_in_lz]]].\napply (irrefl_R a); apply trans_R with z.\napply (app_lt_cns z lz); subst; trivial.\nrewrite (list_permut.in_permut_in P').\napply in_or_app; left; trivial.\napply (mem_eq_mem eq_proof) with b; assumption.\napply la_lt_a; rewrite (mem_permut_mem z Pla); \nrewrite <- mem_or_app; left; rewrite <- (mem_permut_mem z H1).\nrewrite mem_consn; exists lz; trivial.\nrewrite <- mem_or_app in b_in_la.\ndestruct b_in_la as [b_in_la' | b_in_app].\napply (cns_disj_la' b); trivial; rewrite <- (mem_permut_mem b H2); trivial.\napply (app_disj_cns irrefl_R b).\nrewrite (mem_permut_mem b (permut_consn P')); rewrite consn_app; \nrewrite <- mem_or_app; right; trivial.\nrewrite (mem_permut_mem b (permut_appendn P')); rewrite appendn_app; \nrewrite <- mem_or_app; left; trivial.\ndestruct b_in_a_cns as [b_eq_a | b_in_cns].\ndummy b a b_eq_a;\nsubst b.\napply a_not_in_appl;\nrewrite (mem_permut_mem a (permut_appendn P'));\nrewrite appendn_app; rewrite <- mem_or_app; right; trivial.\napply (app_disj_cns irrefl_R b).\nrewrite (mem_permut_mem b (permut_consn P')); rewrite consn_app; \nrewrite <- mem_or_app; right; trivial.\nrewrite (mem_permut_mem b (permut_appendn P')); rewrite appendn_app; \nrewrite <- mem_or_app; right; trivial.\nsimpl; trivial.\nQed.\n\nLemma context_trans_clos_multiset_extension_step_cons :\n  forall R, transitive _ R -> (forall a, ~R a a) -> \n  forall a l1 l2, trans_clos (multiset_extension_step R) (a :: l1) (a :: l2) ->\n                         trans_clos (multiset_extension_step R) l1 l2.\nProof.\nintros R trans_R irrefl_R a l1 l2 H.\ndestruct (multiset_closure trans_R H)\n    as [ll [q [P1 [P2 [p_diff_nil [app_lt_cns cns_disj_app]]]]]].\ngeneralize (mem_bool_ok _ _ eq_bool_ok a q).\ncase (mem_bool DS1.eq_bool a q); [intro a_in_q | intro a_not_in_q].\ndestruct (mem_split_set _ _ eq_bool_ok _ _ a_in_q) as [a' [q' [q'' [a_eq_a' [H' _]]]]]; \nsimpl in a_eq_a'; simpl in H'; subst q.\nrewrite ass_app in P1; rewrite <- permut_cons_inside in P1; \nrewrite <- ass_app in P1.\nrewrite ass_app in P2; rewrite <- permut_cons_inside in P2; \nrewrite <- ass_app in P2.\napply (multiset_closure_aux R (q' ++ q'') P1 P2 p_diff_nil).\nintros a'' la ala'_in_ll; apply app_lt_cns; trivial.\ntrivial.\ntrivial.\napply False_rec; apply (cns_disj_app irrefl_R a).\nassert (a_in_cns_ll_q : mem eq_A a (consn ll ++ q)).\nrewrite <- (mem_permut_mem a P2); left; trivial.\napply (equiv_refl _ _ eq_proof).\nrewrite <- mem_or_app in a_in_cns_ll_q.\ndestruct a_in_cns_ll_q as [a_in_cns_ll | a_in_q]; \n[trivial | absurd (mem eq_A a q); trivial; intro].\nassert (a_in_app_ll_q : mem eq_A a (appendn ll ++ q)).\nrewrite <- (mem_permut_mem a P1); left; trivial.\napply (equiv_refl _ _ eq_proof).\nrewrite <- mem_or_app in a_in_app_ll_q.\ndestruct a_in_app_ll_q as [a_in_app_ll | a_in_q]; \n[trivial | absurd (mem eq_A a q); trivial].\nQed.\n\nLemma remove_context_trans_clos_multiset_extension_step_app1 :\n  forall R, transitive _ R -> (forall a, ~R a a) -> \n  forall l1 l2 l, trans_clos (multiset_extension_step R) (l ++ l1) (l ++ l2) ->\n                         trans_clos (multiset_extension_step R) l1 l2.\nProof.\nintros R trans_R irrefl_R l1 l2 l; generalize l1 l2; clear l1 l2; \ninduction l as [ | a l]; trivial.\nintros l1 l2 H; apply IHl;\napply context_trans_clos_multiset_extension_step_cons with a; trivial.\nQed.\n\nLemma nil_is_the_smallest :\n  forall R e l, trans_clos (multiset_extension_step R) nil (e :: l).\nProof.\nintros R e' l; generalize e'; clear e'; induction l as [ | e l].\nintros e; apply t_step; refine (@rmv_case _ _ _ nil nil e _ _ _); auto; contradiction.\nintros e'; apply trans_clos_is_trans with (e' :: l); trivial.\napply t_step; refine (@rmv_case _ _ _ (e' :: l) nil e _ _ _); auto.\ncontradiction.\nrewrite <- (permut_cons_inside (e1 := e') (e2 := e') (e :: l) (e :: nil) l).\nauto.\napply (equiv_refl _ _ eq_proof).\nQed.\n\nSection Mult.\n\nVariable R : relation A.\nVariable R_bool : A -> A -> bool.\nVariable R_bool_ok : \n   forall a1 a2, \n   match R_bool a1 a2 with\n   | true => R a1 a2\n   | false => ~ R a1 a2\n   end.\n\nDefinition mult (l1 l2 : list A) : comp :=\n  match remove_equiv eq_bool l1 l2 with\n    | (nil, nil) => Equivalent\n    | (l1, l2) => \n\tmatch list_forall (fun t2 => list_exists (fun t1 => R_bool t2 t1) l1) l2 with\n        | true => Greater_than\n\t| false =>\n\t  match list_forall (fun t1 => list_exists (fun t2 => R_bool t1 t2) l2) l1 with\n\t  | true => Less_than\n\t  | false => Uncomparable\n          end\n     end\nend.\n\nLemma greater_case :\n   forall l1 l2, (forall a, mem eq_A a l1 -> mem eq_A a l2 -> False) ->\n  list_forall (fun t2 => list_exists (fun t1 => R_bool t2 t1) l1) l2 = true ->\n   exists le, exists ll, permut l1 (consn ll ++ le) /\\\n                              permut  l2 (appendn ll) /\\\n                              (forall a la, In (a,la) ll -> forall b, mem eq_A b la -> R b a).\nProof. \nintros l1 l2; revert l2 l1.\nfix greater_case 1.\nintros [ | a2 l2].\nintros [ | a1 l1]; simpl.\nintros _ _; exists (@nil A);  exists (@nil (A * list A)); simpl; intuition.\nintros _ _; exists (a1 :: l1); exists (@nil (A * list A)); simpl; intuition.\nintros l1 E; simpl.\ngeneralize (list_exists_is_sound (fun t1 : A => R_bool a2 t1) l1);\ncase (list_exists (fun t1 : A => R_bool a2 t1) l1).\nintro H; generalize (proj1 H (refl_equal _)); clear H; \nintros [a1 [a1_in_l1 a2_R_a1]].\nassert (a2_R_a1' : R a2 a1).\ngeneralize (R_bool_ok a2 a1); rewrite a2_R_a1; trivial.\nassert (E' : forall x : A, mem eq_A x l1 -> mem eq_A x l2 -> False).\nintros x x_in_l1 x_in_l2; apply (E x); [idtac | right]; assumption.\ngeneralize (greater_case l2 l1 E'); simpl.\ncase (list_forall (fun t2 : A => list_exists (fun t1 : A => R_bool t2 t1) l1) l2).\ncase_eq l1; [intros l1_eq_nil | intros b1 k1 H]; subst l1.\ncontradiction.\nintros H1 H2; generalize (H1 H2); clear H1 H2; intros [le [ll [P1 [P2 app_lt_cns]]]].\nassert (a1_mem_cns_ll_le : mem eq_A a1 (consn ll ++ le)).\nrewrite <- (mem_permut_mem a1 P1); apply in_impl_mem; trivial.\nintro; apply (equiv_refl _ _ eq_proof).\nrewrite <- mem_or_app in a1_mem_cns_ll_le.\ncase a1_mem_cns_ll_le; [intro a1_mem_cns_ll | intro a1_mem_le].\ngeneralize (proj1 (mem_consn _ _) a1_mem_cns_ll); intros [la ala_in_ll].\ngeneralize (In_split _ _ ala_in_ll); intros [ll' [ll'' H]]; subst ll.\nexists le; exists (ll' ++ (a1, a2 :: la) :: ll''); split.\nrewrite consn_app; simpl; rewrite consn_app in P1; simpl in P1; trivial.\nsplit.\nrewrite appendn_app; simpl; rewrite <- permut_cons_inside;\nrewrite appendn_app in P2; simpl in P2; trivial.\napply (equiv_refl _ _ eq_proof).\nintros x lx xlx_in_ll b b_in_lx;\ncase (in_app_or _ _ _ xlx_in_ll); [intros xlx_ll' | intros [xlx_eq_a1la | xlx_in_ll'']].\napply (app_lt_cns x lx); trivial; apply in_or_app; left; trivial.\ninjection xlx_eq_a1la; intros; subst x lx.\ncase b_in_lx; [intros b_eq_a2 | intros b_in_la];\n [dummy b a2 b_eq_a2; subst b | apply (app_lt_cns a1 la)]; trivial.\napply (app_lt_cns x lx); trivial; apply in_or_app; do 2 right; trivial.\n\ngeneralize (mem_split_set _ _ eq_bool_ok _ _ a1_mem_le); intros [a1' [le' [le'' [a1_eq_a1' [H _]]]]]; \nsimpl in a1_eq_a1'; simpl in H; subst le.\nexists (le' ++ le''); exists ((a1, a2 :: nil) :: ll); split.\nsimpl.\napply permut_trans with (consn ll ++ le' ++ a1' :: le'').\nassumption.\nrewrite ass_app; apply permut_sym;\nrewrite <- permut_cons_inside; trivial.\nrewrite ass_app; auto.\nsplit.\nsimpl; rewrite <- permut_cons; trivial.\napply (equiv_refl _ _ eq_proof).\nintros x lx [xlx_eq_a1_e2 | xlx_in_ll] b b_in_lx.\ninjection xlx_eq_a1_e2; intros; subst x lx;\ncase b_in_lx; [intros b_eq_e2 | intros Abs]; \n[dummy b a2 b_eq_e2; subst b; trivial | contradiction].\napply (app_lt_cns x lx); trivial; right; trivial.\nintros _.\ncase (list_forall\n      (fun t1 : A =>\n       Bool.ifb (R_bool t1 a2) true\n         (list_exists (fun t2 : A => R_bool t1 t2) l2)) l1); case l1; intros; discriminate.\n\nintros _; simpl.\ncase (list_forall\n         (fun t1 : A =>\n          Bool.ifb (R_bool t1 a2) true\n            (list_exists (fun t2 : A => R_bool t1 t2) l2)) l1); case l1; intros; discriminate.\nQed.\n\nLemma mult_is_sound :\n forall l1 l2,\n  match mult l1 l2 with\n  | Equivalent => permut l1 l2\n  | Less_than => trans_clos (multiset_extension_step R) l1 l2\n  | Greater_than => trans_clos (multiset_extension_step R) l2 l1\n  | _ => True\n  end.\nProof.\nintros l1 l2; unfold mult; \ngeneralize (remove_equiv_is_sound l1 l2).\nunfold A in *.\ncase (@remove_equiv DS1.A eq_bool l1 l2); intros k1 k2 [l [P1 [P2 E]]].\nrevert P1 P2 E; case k1; [ idtac| intros e1' l1']; (case k2; [ idtac | intros e2' l2']); intros P1 P2 E.\napply permut_trans with (l ++ nil).\nassumption.\napply permut_sym; assumption.\nsimpl; rewrite <- app_nil_end in P1;\napply (multiset_closure_aux2 R (p := l1) (q := l2) \n                      (le := e2' :: l2') (l := nil) l); simpl; auto.\napply permut_trans with (l ++ e2' :: l2').\nassumption.\nrewrite app_comm_cons; apply list_permut_app_app.\nright; discriminate.\nintros; contradiction.\nsimpl; rewrite <- app_nil_end in P2;\napply (multiset_closure_aux2 R (p := l2) (q := l1) \n                      (le := e1' :: l1') (l := nil) l); simpl; auto.\napply permut_trans with (l ++ e1' :: l1').\nassumption.\nrewrite app_comm_cons; apply list_permut_app_app.\nright; discriminate.\nintros; contradiction.\ngeneralize (greater_case (e1' :: l1') (e2' :: l2') E); unfold A in *.\ncase (list_forall (fun t2 : DS1.A => list_exists (fun t1 : DS1.A => R_bool t2 t1) (e1' :: l1')) (e2' :: l2')).\nintro H; generalize (H (refl_equal _)); clear H; intros [le [ll [P1' [P2' app_lt_cns]]]].\napply (multiset_closure_aux2 R (p := l2) (q := l1) (le := le)  (l := ll) l); simpl; auto.\napply permut_trans with (l ++ e2' :: l2').\nassumption.\napply permut_trans with (l ++ appendn ll).\nrewrite <- permut_app1; assumption.\napply list_permut_app_app.\napply permut_trans with (l ++ e1' :: l1').\nassumption.\napply permut_trans with (l ++ consn ll ++ le).\nrewrite <- permut_app1; assumption.\napply permut_trans with (l ++ le ++ consn ll).\nrewrite <- permut_app1; apply list_permut_app_app.\nrewrite (ass_app le); apply list_permut_app_app.\ndestruct ll as [ | [x lx] ll].\ndestruct le as [ | e le].\ngeneralize (permut_length P1'); simpl; intro; \nabsurd (S (length l1') = 0); trivial; discriminate.\nright; discriminate.\nleft; discriminate.\nassert (E' : forall x : DS1.A, mem eq_A x (e2' :: l2') -> mem eq_A x (e1' :: l1') -> False).\nintros x H2 H1; apply (E x H1 H2).\nintros _; generalize (greater_case (e2' :: l2') (e1' :: l1') E'); unfold A in *;\ncase (list_forall (fun t1 : DS1.A => list_exists (fun t2 : DS1.A => R_bool t1 t2) (e2' :: l2')) (e1' :: l1')).\nintro H; generalize (H (refl_equal _)); clear H; intros [le [ll [P2' [P1' app_lt_cns]]]].\napply (multiset_closure_aux2 R (p := l1) (q := l2) (le := le)  (l := ll) l); simpl; auto.\napply permut_trans with (l ++ e1' :: l1').\nassumption.\napply permut_trans with (l ++ appendn ll).\nrewrite <- permut_app1; assumption.\napply list_permut_app_app.\napply permut_trans with (l ++ e2' :: l2').\nassumption.\napply permut_trans with (l ++ consn ll ++ le).\nrewrite <- permut_app1; assumption.\napply permut_trans with (l ++ le ++ consn ll).\nrewrite <- permut_app1; apply list_permut_app_app.\nrewrite (ass_app le); apply list_permut_app_app.\ndestruct ll as [ | [x lx] ll].\ndestruct le as [ | e le].\ngeneralize (permut_length P2'); simpl; intro; \nabsurd (S (length l2') = 0); trivial; discriminate.\nright; discriminate.\nleft; discriminate.\ntrivial.\nDefined.\n\nLemma mult_is_complete_equiv :\n forall l1 l2, permut l1 l2 -> mult l1 l2 = Equivalent.\nProof.\nintros l1 l2 P; \nassert (P1 : permut l1 (l1 ++ nil)).\nrewrite <- app_nil_end; apply permut_refl.\nassert (P2 : permut l2 (l1 ++ nil)).\nrewrite <- app_nil_end; apply permut_sym; assumption.\nassert (E : forall x : A, mem eq_A x nil -> mem eq_A x nil -> False).\nintros; contradiction.\ngeneralize (@remove_equiv_is_complete l1 l2 l1 nil nil P1 P2 E).\nunfold mult; unfold A in *; case (@remove_equiv DS1.A eq_bool l1 l2); intros k1 k2 [Q1 Q2].\nsimpl in Q1; rewrite (permut_nil Q1).\nsimpl in Q2; rewrite (permut_nil Q2).\napply refl_equal.\nDefined.\n\nLemma mult_is_complete_greater_aux :\n transitive _ R -> (forall a, ~ R a a) ->\n forall l l1 l2, (forall a, mem eq_A a l1 -> mem eq_A a l2 -> False) ->\n   trans_clos (multiset_extension_step R) (l ++ l2) (l ++ l1) -> \n\t(list_forall (fun t2 => list_exists (fun t1 => R_bool t2 t1) l1) l2) = true.\nProof.\nintros trans_R irrefl_R l l1 l2 l2_disj_l1 ll2_lt_ll1.\nassert (l2_lt_l1 := remove_context_trans_clos_multiset_extension_step_app1 trans_R irrefl_R l2 l1 l ll2_lt_ll1).\nclear l ll2_lt_ll1.\ngeneralize (multiset_closure trans_R l2_lt_l1).\nintros [ll [lc [P2 [P1 [ll_diff_nil [app_lt_cns cns_disj_app]]]]]].\ngeneralize (cns_disj_app irrefl_R); clear cns_disj_app; intro cns_disj_app.\nassert (lc_eq_nil : lc = nil).\nrevert P2 P1 cns_disj_app.\ncase lc; clear lc; [intros _ _ _; apply refl_equal | intros c lc P2 P1 cns_disj_app].\napply False_rec.\napply (l2_disj_l1 c).\nrewrite (mem_permut_mem c P1); rewrite <- mem_or_app; right; left; apply (equiv_refl _ _ eq_proof).\nrewrite (mem_permut_mem c P2); rewrite <- mem_or_app; right; left; apply (equiv_refl _ _ eq_proof).\nsubst lc; rewrite <- app_nil_end in P1; rewrite <- app_nil_end in P2.\nassert (Compat : forall ta ta' tb tb' : A, eq_A ta tb -> eq_A ta' tb' -> R_bool ta ta' = R_bool tb tb').\nunfold eq_A; intros a a' b b' a_eq_a' b_eq_b'; subst; apply refl_equal.\nrewrite (permut_list_forall_exists R_bool R_bool Compat P2 P1); \nclear Compat cns_disj_app P1 P2 ll_diff_nil; induction ll as [ | [a la] ll]; simpl; trivial.\nrewrite list_forall_app; rewrite Bool.andb_true_iff; split.\ngeneralize la (app_lt_cns a la (or_introl _ (refl_equal _)));\nclear la app_lt_cns; intros la la_lt_a; induction la as [ | b la]; trivial.\nsimpl; generalize (R_bool_ok b a); case (R_bool b a); [intro b_R_a | intro not_b_R_a]; simpl.\napply IHla; intros; apply la_lt_a; right; assumption.\napply False_rec; apply not_b_R_a; apply la_lt_a; left; apply (equiv_refl _ _ eq_proof).\nrewrite (list_forall_impl (fun t1 : A => list_exists (fun t2 : A => R_bool t1 t2) (consn ll))\n                                        (fun t1 : A =>  Bool.ifb (R_bool t1 a) true\n                                                                             (list_exists (fun t2 : A => R_bool t1 t2) (consn ll)))\n                                        (appendn ll)).\napply refl_equal.\nintros b b_in_all H; case (R_bool b a); simpl; [apply refl_equal | assumption].\napply IHll; intros b lb blb_in_ll; apply app_lt_cns; right; assumption.\nQed.\n\nLemma mult_irrefl :\n transitive _ R -> (forall a, ~ R a a) -> forall l, trans_clos (multiset_extension_step R) l l -> False.\nProof.\nintros trans_R irrefl_R l l_lt_l.\nrewrite (app_nil_end l) in l_lt_l.\nassert (nil_lt_nil := remove_context_trans_clos_multiset_extension_step_app1 trans_R irrefl_R nil nil l l_lt_l).\nclear l l_lt_l.\nassert (H : forall l1 l2, trans_clos (multiset_extension_step R) l1 l2 -> l2 = nil -> False).\nintros l1 l2 T; induction T as [k1 k2 H | k1 k2 k3 H1 H2]; intros; subst.\ninversion H as [l1 l2 l la a la_lt_a P1 P2]; subst.\ngeneralize (permut_length P2); simpl; discriminate.\napply IHH2; apply refl_equal.\napply (H _ _ nil_lt_nil); apply refl_equal.\nQed.\n\nLemma mult_is_complete_greater :\n transitive _ R -> (forall a, ~ R a a) ->\n   forall l1 l2, trans_clos (multiset_extension_step R) l2 l1 -> mult l1 l2 = Greater_than.\nProof.\nintros trans_R irrefl_R l1 l2 l2_lt_l1.\ngeneralize (remove_equiv_is_sound l1 l2); unfold mult; unfold A in *; case_eq (remove_equiv eq_bool l1 l2); \nintros k1 k2 H [l [P1 [P2 k1_disj_k2]]].\nassert (lk2_lt_lk1 : trans_clos (multiset_extension_step R) (l ++ k2) (l ++ k1)).\napply list_permut_trans_clos_multiset_extension_step_1 with l2; [assumption | idtac].\napply list_permut_trans_clos_multiset_extension_step_2 with l1; assumption.\nassert (Dummy := @mult_is_complete_greater_aux trans_R irrefl_R l _ _ k1_disj_k2 lk2_lt_lk1).\nunfold A in Dummy; rewrite Dummy; clear Dummy.\nrevert lk2_lt_lk1; case k1; [idtac | intros _ _ _; apply refl_equal].\ncase k2; [idtac | intros _ _ _; apply refl_equal].\nintro T; apply False_rec.\napply (mult_irrefl trans_R irrefl_R T).\nQed.\n\nLemma mult_is_complete_less_than :\n transitive _ R -> (forall a, ~ R a a) ->\n   forall l1 l2, trans_clos (multiset_extension_step R) l1 l2 -> mult l1 l2 = Less_than.\nProof.\nintros trans_R irrefl_R l1 l2 l1_lt_l2.\ngeneralize (multiset_closure trans_R l1_lt_l2).\nintros [ll [lc [P1 [P2 [ll_diff_nil [app_lt_cns disj]]]]]].\nassert (cns_disj_app := disj irrefl_R); clear disj.\nassert (Q1 : permut l1 (lc ++ appendn ll)).\napply permut_trans with (appendn ll ++ lc).\nassumption.\napply permut_swapp; apply permut_refl.\nassert (Q2 : permut l2 (lc ++ consn ll)).\napply permut_trans with (consn ll ++ lc).\nassumption.\napply permut_swapp; apply permut_refl.\nassert (app_disj_cns : forall x : A, mem eq_A x (appendn ll) -> mem eq_A x (consn ll) -> False).\nintros x x_in_app x_in_cns; apply (cns_disj_app x); assumption.\ngeneralize (remove_equiv_is_complete _ _ _ Q1 Q2 app_disj_cns) (mult_is_sound l1 l2).\nunfold mult; unfold A in *; case (@remove_equiv DS1.A eq_bool l1 l2); simpl; intros k1 k2 [Q1' Q2'].\nassert (Dummy := mult_is_complete_greater_aux trans_R irrefl_R lc k2 k1).\nunfold A in Dummy; rewrite Dummy; clear Dummy.\nrevert ll_diff_nil Q1' Q2'; case k1.\ncase k2.\ncase ll.\nintro ll_diff_nil; apply False_rec; apply ll_diff_nil; apply refl_equal.\nintros [a la] ll' _ _ Q2'; apply False_rec.\nassert (L := permut_length Q2'); discriminate.\nintros; apply refl_equal.\nclear k1; intros a1 k1 ll_diff_nil Q1' Q2'.\ncase (list_forall (fun t2 : DS1.A => list_exists (fun t1 : DS1.A => R_bool t2 t1) (a1 :: k1)) k2).\nintro l2_lt_l1; apply False_rec.\napply (@mult_irrefl trans_R irrefl_R l1).\napply trans_clos_is_trans with l2; assumption.\nintros; apply refl_equal.\n\nintros x x_in_k2 x_in_k1; apply (cns_disj_app x).\nrewrite <- (mem_permut_mem x Q2'); assumption.\nrewrite <- (mem_permut_mem x Q1'); assumption.\napply list_permut_trans_clos_multiset_extension_step_1 with l1.\napply permut_trans with (k1 ++ lc).\napply permut_trans with (appendn ll ++ lc).\nassumption.\nrewrite <- permut_app2; apply permut_sym; assumption.\napply permut_swapp; apply permut_refl.\napply list_permut_trans_clos_multiset_extension_step_2 with l2.\napply permut_trans with (k2 ++ lc).\napply permut_trans with (consn ll ++ lc).\nassumption.\nrewrite <- permut_app2; apply permut_sym; assumption.\napply permut_swapp; apply permut_refl.\nassumption.\nDefined.\n\nLemma mult_is_complete : \n transitive _ R -> (forall a, ~ R a a) ->\n forall l1 l2,\n  match mult l1 l2 with\n  | Uncomparable => ~ permut l1 l2 /\\\n                                      ~trans_clos (multiset_extension_step R) l1 l2 /\\ \n                                      ~trans_clos (multiset_extension_step R) l2 l1\n  | _ => True\n  end.\nProof.\nintros trans_R irrefl_R l1 l2.\ngeneralize (mult_is_sound l1 l2) (@mult_is_complete_equiv l1 l2) \n                    (@mult_is_complete_greater trans_R irrefl_R l1 l2) (@mult_is_complete_less_than trans_R irrefl_R l1 l2).\ncase (mult l1 l2); trivial.\nintros _ H1 H2 H3; repeat split; intro H.\ngeneralize (H1 H); discriminate.\ngeneralize (H3 H); discriminate.\ngeneralize (H2 H); discriminate.\nQed.\n\nEnd Mult.\n\nEnd Make.\n\nModule NatMul := Make (ordered_set.Nat).\n\n(* \n*** Local Variables: ***\n*** coq-prog-name: \"coqtop\" ***\n*** coq-prog-args: (\"-emacs-U\" \"-I\" \"../basis/\") ***\n*** End: ***\n *)\n", "meta": {"author": "sorinica", "repo": "spike-prover", "sha": "f2d6dd0bcebb647e09dd23048753075551da27eb", "save_path": "github-repos/coq/sorinica-spike-prover", "path": "github-repos/coq/sorinica-spike-prover/spike-prover-f2d6dd0bcebb647e09dd23048753075551da27eb/Coccinelle/Coq8.15/dickson.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6724048935694137}}
{"text": "(* Copyright 2012-2015 by Adam Petcher.\t\t\t\t*\n * Use of this source code is governed by the license described\t*\n * in the LICENSE file at the root of the source tree.\t\t*)\n\n(* A denotational semantics for computations that relates every computation to a denotation. *)\n\nSet Implicit Arguments.\n\nRequire Export fcf.Comp.\nRequire Export fcf.Rat.\nRequire Import fcf.Fold.\nRequire Import List.\nRequire Import fcf.Blist.\nRequire Import Omega.\nRequire Import fcf.StdNat.\nRequire Import fcf.NotationV1.\n \n \nLocal Open Scope list_scope.\nLocal Open Scope rat_scope.\n\nLtac simp_in_support := \n  unfold setLet in *;\n  match goal with\n    | [H : In _ (getSupport (Bind _ _)) |- _ ] =>\n      apply getSupport_Bind_In in H; destruct_exists; intuition\n    | [H : In _ (getSupport (if ?t then _ else _)) |- _ ] => let x := fresh \"x\" in remember t as x; destruct x\n    | [H : In _ (getSupport (ret _)) |- _ ] => apply getSupport_In_Ret in H; try pairInv; subst\n(*     | [H : false = inRange _ _ |- _] => symmetry in H *)\n    | [H : true = negb ?t |- _ ] => let x := fresh \"x\" in remember t as x; destruct x; simpl in H; try discriminate\n  end.\n\n(* evalDist is a denotational semantics that produces a distribution instead of a value. *)\n\nDefinition Distribution(A : Set) := A -> Rat.\n\nDefinition indicator(A : Set)(P : A -> bool) :=\n  fun a => if (P a) then rat1 else rat0.\n\nFixpoint evalDist(A : Set)(c : Comp A) : Distribution A :=\n  match c with\n    | Ret eqd a => fun a' => if (eqd a a') then 1 else 0\n    | Bind c1 c2 => fun a => \n      sumList (getSupport c1) (fun b => (evalDist c1 b) * (evalDist (c2 b) a))\n    | Rnd n => fun v => 1 / (expnat 2 n)\n    | Repeat c P => fun a => (indicator P a) * (ratInverse (sumList (filter P (getSupport c)) (evalDist c))) * (evalDist c a)\n  end.\n\nDefinition dist_sem_eq(A : Set)(c1 c2 : Comp A) :=\n  forall a, (evalDist c1 a) == (evalDist c2 a).\n\nDefinition Support(A : Set)(ls : list A)(d : Distribution A) :=\n  NoDup ls /\\\n  (forall a, In a ls <-> ~((d a) == 0)).\n\nLemma getSupport_NoDup : forall (A : Set)(c : Comp A),\n  NoDup (getSupport c).\n\n  destruct c; intuition; simpl in *.\n\n  econstructor.\n  apply in_nil.\n  econstructor.\n\n  eapply getUnique_NoDup.\n\n  eapply getAllBvectors_NoDup.\n\n  eapply filter_NoDup.\n  eapply getSupport_NoDup.\n\nQed.\n\nLemma filter_not_In : forall (A : Set)(ls : list A)(P : A -> bool) a,\n                        (~In a ls) \\/ P a = false <->\n                        ~In a (filter P ls).\n  \n    intuition.\n    eapply H1.\n    eapply filter_In; eauto.\n    assert (P a = true -> False).\n    intuition.\n    congruence.\n    eapply H.\n    eapply filter_In; eauto.\n    \n    case_eq (P a); intuition.\n    left.\n    intuition.\n    eapply H.\n    eapply filter_In; eauto.\n    \nQed.\n\nTheorem getSupport_In_evalDist : forall (A : Set)(c : Comp A)(a : A),\n  In a (getSupport c) <-> ~(evalDist c a == 0).\n\n  induction c; simpl in *; intuition.\n  subst.\n  destruct (e a0 a0).\n  eapply rat1_ne_rat0.\n  trivial.\n  congruence.\n\n  destruct (e a a0); subst.\n  intuition.\n  right.\n  intuition.\n\n  apply in_getUnique_if in H0.\n  apply in_flatten in H0.\n\n  destruct H0.\n  intuition.\n  apply in_map_iff in H2.\n  destruct H2.\n  intuition.\n\n  eapply sumList_0 in H1; eauto.\n  apply ratMult_0 in H1; intuition.\n  eapply IHc; eauto.\n  subst.\n  eapply H; eauto.\n\n  apply (in_getUnique (flatten (map (fun b : B => getSupport (c0 b)) (getSupport c)))).\n  apply in_flatten.\n  apply sumList_nz in H0.\n  destruct H0.\n  intuition.\n  apply ratMult_nz in H2.\n  intuition.\n  econstructor.\n  split.\n  eapply in_map_iff.\n  econstructor.\n  split.\n  eapply eq_refl.\n  eapply H1.\n  eapply H.\n  eauto.\n\n  eapply in_getAllBvectors.\n\n  apply ratMult_0 in H0.\n  intuition.\n  apply ratMult_0 in H1.\n  intuition.\n  unfold indicator in *.\n  case_eq (b a); intuition.\n  rewrite H1 in H0.\n  eapply rat1_ne_rat0.\n  trivial.\n\n  eapply filter_not_In.\n  eauto.\n  eauto.\n\n  eapply ratInverse_nz; eauto.\n  eapply IHc.\n  eapply filter_In.\n  eauto.\n  trivial.\n\n  apply ratMult_nz in H.\n  intuition.\n  apply ratMult_nz in H0.\n  intuition.\n  unfold indicator in *.\n  case_eq (b a); intuition;\n  rewrite H0 in H.\n  eapply filter_In.\n  intuition.\n  eapply IHc.\n  trivial.\n  exfalso.\n  intuition.\n\nQed.\n\nTheorem getSupport_not_In_evalDist : forall (A : Set)(c : Comp A)(a : A),\n  ~In a (getSupport c) <-> (evalDist c a == 0).\n\n  intuition.\n\n  Theorem getSupport_not_In_evalDist_h : forall (A : Set)(c : Comp A)(a : A),\n  ~In a (getSupport c) -> (evalDist c a == 0).\n\n    induction c; intuition; simpl in *.\n    intuition.\n    destruct (e a a0); subst;\n    intuition.\n\n    eapply sumList_0.\n    intuition.\n    eapply ratMult_0.\n    right.\n    eapply H.\n    intuition.\n    eapply H0.\n    eapply (in_getUnique (flatten (map (fun b : B => getSupport (c0 b)) (getSupport c)))).\n    eapply in_flatten.\n    exists (getSupport (c0 a0)).\n    intuition.\n    eapply in_map_iff.\n    exists a0.\n    intuition.\n\n    exfalso.\n    eapply H.\n    eapply in_getAllBvectors.\n\n    apply filter_not_In in H.\n    intuition.\n    \n    eapply ratMult_0.\n    right.\n    eauto.\n    \n    eapply ratMult_0.\n    left.\n    unfold indicator.\n    rewrite H0.\n    rewrite ratMult_0_l.\n    intuition.\n    \n  Qed.\n\n  eapply getSupport_not_In_evalDist_h.\n  intuition.\n\n  eapply getSupport_In_evalDist; eauto.\n\nQed.\n\nTheorem getSupport_correct : forall (A : Set)(c : Comp A),\n  Support (getSupport c)(evalDist c).\n\n  intuition.\n  econstructor.\n  eapply getSupport_NoDup.\n  \n  apply getSupport_In_evalDist.\n  \nQed.\n\n\n(* We use evalDist as the probability measure.  Instead of supplying an event on the return type, we expect the computation to test for the occurrence of the event.  *)\nNotation \"'Pr' [ c  ] \" := (evalDist c true) (at level 20).\n\n\nLemma evalDist_sum_bind_eq : forall (A B : Set)(eqdb : eq_dec B)(eqda : eq_dec A)(c1 : Comp B)(c2 : B -> Comp A),\n  sumList (getSupport (Bind c1 c2)) (evalDist (Bind c1 c2)) ==\n  sumList (getSupport c1) (fun b => evalDist c1 b * (sumList (getSupport (c2 b)) (evalDist (c2 b)))).\n  \n  intuition. simpl.\n  eapply eqRat_trans.\n  eapply sumList_comm.\n  eapply sumList_body_eq; intuition.\n  \n  eapply eqRat_trans.\n  eapply sumList_factor_constant_l.\n  eapply ratMult_eqRat_compat; intuition.\n  \n  eapply eqRat_symm.\n  eapply sumList_subset; intuition.\n  eapply getSupport_NoDup.\n  eapply getUnique_NoDup.\n  eapply (in_getUnique (flatten (map (fun b : B => getSupport (c2 b)) (getSupport c1)))).\n  eapply in_flatten.\n  econstructor.\n  split.\n  eapply in_map_iff.\n  econstructor.\n  split.\n  eapply eq_refl.\n  eauto.\n  eauto.\n  \n  eapply getSupport_not_In_evalDist.\n  eauto.\nQed.\n  \n(*\nLemma evalDist_sum_repeat_eq : forall (A : Set)(eqda : eq_dec A)(c : Comp A) P,\n  let scale := (ratInverse (sumList (filter P (getSupport c)) (evalDist c))) in \n  sumList (getSupport (Repeat c P)) (evalDist (Repeat c P)) ==\n  sumList (filter P (getSupport c1)) (fun b => scale * evalDist c1 b * (sumList (getSupport (c2 b)) (evalDist (c2 b)))).\n\n  intuition. simpl.\n  eapply eqRat_trans.\n  eapply sumList_comm.\n  eapply sumList_body_eq; intuition.\n  \n  eapply eqRat_trans.\n  eapply sumList_factor_constant_l.\n  eapply ratMult_eqRat_compat; intuition.\n  \n  eapply eqRat_symm.\n  eapply sumList_subset; intuition.\n  eapply getSupport_NoDup.\n  eapply getUnique_NoDup.\n  eapply in_getUnique.\n  eapply in_flatten.\n  econstructor.\n  split.\n  eapply in_map_iff.\n  econstructor.\n  split.\n  eapply eq_refl.\n  eauto.\n  eauto.\n  \n  eapply getSupport_not_In_evalDist.\n  eauto.\n\nQed.\n*)\n\nLemma ratInverse_scale_sum_1 : forall (A : Set)(ls : list A)(f : A -> Rat),\n  (forall a, In a ls -> ~f a == 0) ->\n  length ls > O ->\n  sumList ls (fun a => (ratInverse (sumList ls f)) * (f a)) == 1.\n  \n  intuition.\n  rewrite sumList_factor_constant_l.\n  eapply ratInverse_prod_1.\n  intuition.\n  destruct ls; simpl in *.\n  omega.\n  eapply sumList_0 in H1.\n  eapply H.\n  eauto.\n  eauto.\n  simpl.\n  eauto.\n  \nQed.\n\nLemma evalDist_lossless : forall (A : Set)(c : Comp A),\n  well_formed_comp c ->\n  sumList (getSupport c) (evalDist c) == 1.\n  \n  induction 1; intuition; simpl in *.\n  unfold sumList; simpl in *.\n  destruct (pf a a); intuition.\n  rewrite <- ratAdd_0_l.\n  intuition.    \n  \n  eapply eqRat_trans.\n  apply evalDist_sum_bind_eq.\n  eapply comp_eq_dec; eauto.\n  eapply bind_eq_dec; eauto.\n  eapply eqRat_trans.\n  eapply sumList_body_eq.\n  intuition.\n  apply ratMult_eqRat_compat.\n  apply eqRat_refl.\n  apply H1.\n  trivial.\n  eapply eqRat_trans.\n  eapply sumList_body_eq; intuition.\n  apply ratMult_1_r.\n  trivial.\n \n  rewrite sumList_body_const.\n  rewrite getAllBvectors_length.\n  rewrite <- ratMult_num_den.\n  rewrite mult_1_l.\n  eapply num_dem_same_rat1.\n\n  rewrite posnatMult_1_r.\n  unfold posnatToNat, natToPosnat.\n  trivial.\n\n  eapply eqRat_trans.\n  eapply sumList_body_eq.\n  intuition.\n  eapply ratMult_eqRat_compat.\n  assert (P a = true).\n  eapply filter_In; eauto.\n  unfold indicator.\n  rewrite H2.\n  eapply ratMult_1_l.\n  eapply eqRat_refl.\n  eapply ratInverse_scale_sum_1.\n  intuition.\n  eapply getSupport_In_evalDist.\n  eapply filter_In.\n  eapply H1.\n  trivial.\n  destruct (filter P (getSupport c)); simpl in *; intuition.\n\nQed.\n\nLemma sumList_filter_evalDist_le_1 : forall (A : Set)(c : Comp A)(P : A -> bool) a,\n  well_formed_comp c ->\n  In a (filter P (getSupport c)) ->\n  1 <= sumList (filter (fun a' => negb (P a')) (getSupport c)) (evalDist c) ->\n  False.\n  \n  intuition.\n  assert (sumList (filter (fun a0 : A => negb (P a0)) (getSupport c)) (evalDist c) == 1).\n  eapply leRat_impl_eqRat; trivial.\n  eapply leRat_trans.\n  eapply sumList_filter_le.\n  rewrite evalDist_lossless.\n  intuition.\n  trivial.\n  \n  rewrite <- evalDist_lossless in H2; eauto.\n  rewrite (sumList_filter_partition P (getSupport c)) in H2.\n  symmetry in H2.\n  rewrite ratAdd_comm in H2.\n  apply ratAdd_arg_0 in H2.\n  eapply sumList_0 in H2; eauto.\n  eapply getSupport_In_evalDist.\n  eapply filter_In; eauto.\n  trivial.\nQed.\n\n\nTheorem sumList_support_bool : \n  forall (c : Comp bool),\n    sumList (getSupport c) (evalDist c) ==\n    evalDist c true + evalDist c false.\n  \n  intuition.\n  rewrite (sumList_filter_partition (eqb true)).\n  eapply ratAdd_eqRat_compat.\n  \n  destruct (eq_Rat_dec (Pr[c]) 0).\n  rewrite e.\n  eapply sumList_0.\n  intuition.\n  apply filter_In in H.\n  intuition.\n  rewrite eqb_leibniz in H1.\n  subst.\n  trivial.\n  \n  eapply sumList_exactly_one.\n  eapply filter_NoDup.\n  eapply getSupport_NoDup.\n  eapply filter_In.\n  intuition.\n  eapply getSupport_In_evalDist.\n  intuition.\n  eapply eqb_leibniz.\n  trivial.\n  intuition.\n  eapply filter_In in H.\n  intuition.\n  rewrite eqb_leibniz in H2.\n  subst.\n  intuition.\n  \n  destruct (eq_Rat_dec (evalDist c false) 0).\n  rewrite e.\n  eapply sumList_0.\n  intuition.\n  eapply filter_In in H.\n  intuition.\n  destruct a.\n  rewrite eqb_refl in H1.\n  simpl in *.\n  discriminate.\n  trivial.\n  \n  eapply sumList_exactly_one.\n  eapply filter_NoDup.\n  eapply getSupport_NoDup.\n  eapply filter_In.\n  intuition.\n  eapply getSupport_In_evalDist.\n  intuition.\n  case_eq (eqb true false); intuition.\n  rewrite eqb_leibniz in H.\n  discriminate.\n  \n  intuition.\n  eapply filter_In in H.\n  intuition.\n  destruct b.\n  rewrite eqb_refl in H2.\n  simpl in *.\n  discriminate.\n  intuition.\nQed.\n  \n\nLemma evalDist_sum_le_1 : forall (A : Set)(c : Comp A),\n  sumList (getSupport c) (evalDist c) <= 1.\n \n  induction c; intuition; simpl in *.\n  unfold sumList; simpl in *.\n  destruct (e a a); intuition.\n  rewrite <- ratAdd_0_l.\n  intuition.    \n  \n  eapply leRat_trans.\n  eapply eqRat_impl_leRat.\n  apply evalDist_sum_bind_eq.\n  eapply comp_eq_dec; eauto.\n  eapply bind_eq_dec; eauto.\n  eapply leRat_trans.\n  eapply sumList_le.\n  intuition.\n  apply ratMult_leRat_compat.\n  apply leRat_refl.\n  apply H.\n  eapply leRat_trans.\n  eapply sumList_le; intuition.\n  eapply eqRat_impl_leRat.\n  eapply ratMult_1_r.\n  trivial.\n \n  rewrite sumList_body_const.\n  rewrite getAllBvectors_length.\n  rewrite <- ratMult_num_den.\n  rewrite mult_1_l.\n  eapply eqRat_impl_leRat.\n  eapply num_dem_same_rat1.\n\n  rewrite posnatMult_1_r.\n  unfold posnatToNat, natToPosnat.\n  trivial.\n\n  destruct (gt_dec (length (filter b (getSupport c))) 0).\n\n  eapply leRat_trans.\n  eapply eqRat_impl_leRat.\n  eapply sumList_body_eq.\n  intuition.\n  eapply ratMult_eqRat_compat.\n  assert (b a = true).\n  eapply filter_In; eauto.\n\n  unfold indicator.\n  rewrite H0.\n  eapply ratMult_1_l.\n  eapply eqRat_refl.\n  eapply leRat_trans.\n  eapply eqRat_impl_leRat.\n  eapply ratInverse_scale_sum_1.\n  intuition.\n  eapply getSupport_In_evalDist.\n  eapply filter_In.\n  eapply H.\n  trivial.\n  trivial.\n  intuition.\n\n  destruct (filter b (getSupport c)); simpl in *.\n  unfold sumList.\n  simpl.\n  eapply rat0_le_all.\n\n  omega.\nQed.\n\nLemma evalDist_le_1 : forall (A : Set)(c : Comp A) a,\n  evalDist c a <= 1.\n\n  intuition.\n  eapply leRat_trans.\n  Focus 2.\n  eapply (@evalDist_sum_le_1 _ c).\n  pose proof (comp_EqDec c).\n  destruct (in_dec (EqDec_dec _) a (getSupport c)).\n  eapply leRat_trans.\n  Focus 2.\n  eapply eqRat_impl_leRat.\n  symmetry.\n  rewrite (sumList_partition (eqb a)).\n  eapply ratAdd_eqRat_compat.\n  eapply sumList_exactly_one.\n  eapply getSupport_NoDup.\n  eauto.\n  intuition.\n  case_eq (eqb a b); intuition.\n  exfalso.\n  eapply H1.\n  eapply eqb_leibniz.\n  trivial.\n  eapply ratMult_0_r.\n  eapply eqRat_refl.\n  \n  eapply leRat_trans.\n  eapply eqRat_impl_leRat.\n  eapply ratAdd_0_r.\n  eapply ratAdd_leRat_compat.\n  rewrite eqb_refl.\n  \n  eapply leRat_trans.\n  Focus 2.\n  eapply eqRat_impl_leRat.\n  symmetry.\n  eapply ratMult_1_r.\n  intuition.\n  \n  eapply rat0_le_all.\n  \n  apply getSupport_not_In_evalDist in n.\n  rewrite n.\n  eapply rat0_le_all.\nQed.\n\nTheorem evalDist_complement : \n  forall (c : Comp bool),\n    well_formed_comp c ->\n    evalDist c false == ratSubtract 1 (Pr[c]).\n  \n  intuition.\n  eapply (@ratAdd_add_same_l _ (Pr[c])).\n  rewrite ratSubtract_ratAdd_inverse_2.\n  rewrite <- sumList_support_bool.\n  eapply evalDist_lossless.\n  trivial.\n  \n  eapply evalDist_le_1.\nQed.\n\n\nTheorem evalDist_le_1_gen : \n  forall (A : Set)(eqd : EqDec A)(c : Comp A)(ls : list A),\n    NoDup ls ->\n    sumList ls (evalDist c) <= 1.\n  \n  intuition.\n  eapply leRat_trans.\n  eapply eqRat_impl_leRat.\n  eapply (sumList_filter_partition (fun a => if (in_dec (EqDec_dec _) a (getSupport c)) then true else false)).\n  \n  eapply leRat_trans.\n  Focus 2.\n  eapply eqRat_impl_leRat.\n  symmetry.\n  eapply ratAdd_0_r.\n  eapply ratAdd_leRat_compat.\n  \n  eapply leRat_trans.\n  eapply sumList_subset_le.\n  intuition.\n  eapply filter_NoDup.\n  trivial.\n  eapply (getSupport_NoDup c).\n  intuition.\n  eapply filter_In in H0.\n  intuition.\n  destruct (in_dec (EqDec_dec eqd) a (getSupport c)); intuition.\n  discriminate.\n  eapply evalDist_sum_le_1.\n\n  eapply eqRat_impl_leRat.\n  eapply sumList_0.\n  intuition.\n  eapply filter_In in H0.\n  intuition.\n  destruct (in_dec (EqDec_dec eqd) a (getSupport c)).\n  simpl in *.\n  discriminate.\n  eapply getSupport_not_In_evalDist.\n  trivial.\n  \nQed.\n\nTheorem evalDist_1_0 : \n  forall (A : Set){eqd : EqDec A}(c : Comp A) a,\n    well_formed_comp c ->\n    evalDist c a == 1 ->\n      (forall b, b <> a -> evalDist c b == 0).\n  \n  intuition.\n  eapply leRat_impl_eqRat.\n  \n  eapply (leRat_ratAdd_same_r (evalDist c a)).\n  eapply leRat_trans.\n  Focus 2.\n  eapply eqRat_impl_leRat.\n  rewrite H0.\n  eapply ratAdd_0_l.\n  \n  assert ( evalDist c b + evalDist c a ==\n    sumList (a :: b :: nil)%list (evalDist c)).\n  repeat rewrite sumList_cons.\n  rewrite ratAdd_comm.\n  eapply ratAdd_eqRat_compat; intuition.\n  rewrite ratAdd_0_r at 1.\n  eapply ratAdd_eqRat_compat; intuition.\n  unfold sumList; simpl; intuition.\n  \n  rewrite H2.\n  eapply evalDist_le_1_gen; intuition.\n  econstructor.\n  simpl; intuition.\n  econstructor; simpl; intuition.\n  econstructor.\n  \n  eapply rat0_le_all.\n  \nQed.\n   \nLocal Open Scope comp_scope.\n\nTheorem EqDec_pair_l \n  : forall (A B : Set)(eqd : EqDec (A * B))(b : B),\n    EqDec A.\n\n  intuition.\n  exists (fun a1 a2 => eqb (a1, b) (a2, b)).\n  intuition.\n  rewrite eqb_leibniz in H.\n  inversion H; intuition.\n  subst.\n  eapply eqb_refl.\nQed.\n\nFixpoint evalDist_OC(A B C: Set)(c : OracleComp A B C): forall(S : Set), EqDec S -> (S -> A -> Comp (B * S)) -> S -> Comp (C * S) :=\n  match c in (OracleComp A B C) return (forall(S : Set), EqDec S -> (S -> A -> Comp (B * S)) -> S -> Comp (C * S))\n    with\n    | @OC_Query A' B' a => \n      fun (S : Set)(eqds : EqDec S)(o : S -> A' -> Comp (B' * S))(s : S) =>  \n        o s a\n    | @OC_Run A'' B'' C' A' B' S' eqds' eqda'' eqdb'' c' o' s' =>\n      fun (S : Set)(eqds : EqDec S)(o : S -> A' -> Comp (B' * S))(s : S) =>\n      p <-$ evalDist_OC c' (pair_EqDec eqds' eqds) (fun x y => p <-$ evalDist_OC (o' (fst x) y) _ o (snd x); ret (fst (fst p), (snd (fst p), snd p))) (s', s);\n      Ret \n      (EqDec_dec (pair_EqDec (pair_EqDec \n        (oc_EqDec c' (fun x => fst (oc_base_exists (o' s' x) (fun y => fst (comp_base_exists (o s y))))) (fun x => EqDec_pair_l (oc_EqDec (o' s' x) (fun y => fst (comp_base_exists (o s y))) (fun y => EqDec_pair_l (comp_EqDec (o s y)) s)) s' ))\n        _) _ ))\n      (fst p, fst (snd p), snd (snd p))\n\n    | @OC_Ret A' B' C' c => \n      fun (S : Set)(eqds : EqDec S)(o : S -> A' -> Comp (B' * S))(s : S) =>\n      x <-$ c; Ret \n      (EqDec_dec (pair_EqDec (comp_EqDec c) _ ))\n      (x, s)\n    | @OC_Bind A' B' C' C'' c' f' =>\n      fun (S : Set)(eqds : EqDec S)(o : S -> A' -> Comp (B' * S))(s : S) =>\n      [z, s'] <-$2 evalDist_OC c' _ o s;\n      evalDist_OC (f' z) _ o s'\n  end.\n\nCoercion evalDist_OC : OracleComp >-> Funclass.\n\n\nInductive well_formed_oc : forall (A B C : Set), OracleComp A B C -> Prop :=\n| well_formed_OC_Query :\n  forall (A B : Set)(a : A),\n    well_formed_oc (OC_Query B a)\n| well_formed_OC_Run : \n  forall (A B C A' B' S : Set)\n  (eqds : EqDec S)(eqdb : EqDec B)(eqda : EqDec A)(c : OracleComp A B C)\n  (o : S -> A -> OracleComp A' B' (B * S))(s : S),\n  well_formed_oc c ->\n  (forall s a, well_formed_oc (o s a)) ->\n  well_formed_oc (OC_Run eqds eqdb eqda c o s)\n| well_formed_OC_Ret : \n  forall (A B C : Set)(c : Comp C),\n      well_formed_comp c ->\n      well_formed_oc (OC_Ret A B c)\n| well_formed_OC_Bind : \n  forall (A B C C' : Set)(c : OracleComp A B C)(f : C -> OracleComp A B C'),\n    well_formed_oc c ->\n    (forall c, well_formed_oc (f c)) ->\n    well_formed_oc (OC_Bind c f).\n\nLocal Open Scope nat_scope.\n\nDefinition in_oc_support(A B C : Set)(x : C)(c : OracleComp A B C) :=\n  exists (S : Set)(eqds : EqDec S)(o : S -> A -> Comp (B * S))(s s' : S),\n    In (x, s') (getSupport (c _ _ o s)).\n\nInductive queries_at_most : forall (A B C : Set), OracleComp A B C -> nat -> Prop :=\n| qam_Bind : \n  forall (A B C C' : Set)(c : OracleComp A B C')(f : C' -> OracleComp A B C) q1 q2,\n    queries_at_most c q1 ->\n    (forall c',\n      in_oc_support c' c ->\n       queries_at_most (f c') q2) ->\n    queries_at_most (OC_Bind c f) (q1 + q2)\n| qam_Query : \n  forall (A B : Set)(a : A),\n  queries_at_most (OC_Query B a) 1\n| qam_Ret : \n  forall (A B C : Set)(c : Comp C),\n    queries_at_most (OC_Ret A B c) 0\n| qam_Run :\n  forall (A A' B B' C S : Set)(eqds : EqDec S)(eqda : EqDec A)(eqdb : EqDec B)\n    (c : OracleComp A B C)(oc : S -> A -> OracleComp A' B' (B * S)) s q1 q2,\n    queries_at_most c q1 ->\n    (forall s a, queries_at_most (oc s a) q2) ->\n    queries_at_most (OC_Run _ _ _ c oc s) (q1 * q2)\n| qam_le : \n  forall (A B C : Set)(c : OracleComp A B C) q1 q2,\n    queries_at_most c q1 ->\n    q1 <= q2 ->\n    queries_at_most c q2.\n\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/fcf/DistSem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6724048866580947}}
{"text": "(** * Generation of Hoare proof obligations in partial correctness\n\n This file is part of the \"Tutorial on Hoare Logic\".\n For an introduction to this Coq library,\n see README #or <a href=index.html>index.html</a>#.\n\n This file gives a syntactic definition of the weakest liberal precondition [wlp]\n introduced in #<a href=hoarelogicsemantics.html>#[hoarelogicsemantics]#</a>#.\n*)\n\nGlobal Set Asymmetric Patterns.\nSet Implicit Arguments.\nRequire Export hoarelogicsemantics.\n\nModule PartialHoareLogic (HD: HoareLogicDefs).\n\nExport HD.\nModule HLD:=HD.\n\nDefinition sem_wp := wlp.\n\n(** * Syntactic definition of the weakest liberal precondition.\n\n In the following, we show that this definition is logically \n equivalent to [wlp].\n *)\nFixpoint synt_wp (prog: ImpProg) : Pred -> Pred \n := fun post e =>\n  match prog with\n  | Iskip => post e\n  | (Iset A x expr) => post (E.upd x (E.eval expr e) e)\n  | (Iif cond p1 p2) =>\n          ((E.eval cond e)=true -> (synt_wp p1 post e))\n       /\\ ((E.eval cond e)=false -> (synt_wp p2 post e))\n  | (Iseq p1 p2) => synt_wp p1 (synt_wp p2 post) e\n  | (Iwhile cond p) =>  \n        exists inv:Pred, \n             (inv e)\n          /\\ (forall e', (inv e') \n                  -> (E.eval cond e')=false -> (post e'))\n          /\\ (forall e', (inv e') \n                  -> (E.eval cond e')=true -> (synt_wp p inv e'))\n  end.\n\n(** This property is also trivially satisfied by [wlp]. \n    We need it here to prove the soundness.\n*)\nLemma synt_wp_monotonic: \n  forall (p: ImpProg) (post1 post2: Pred),\n   (post1 |= post2) -> (synt_wp p post1) |= (synt_wp p post2).\nProof.\n  induction p; simpl; firstorder eauto with hoare.\nQed.\n\nGlobal Hint Resolve synt_wp_monotonic: hoare.\n\n(** * Soundness\n  \n    The proof of soundness proceeds by induction over the derivation\n    [exec ... prog ...] in implicit hypothesis induced by [wlp] definition.\n\n    Please, notice that coq performs the [exec_Iwhile] case alone (that's where \n    monotonicity is used). Unfortunately, the case [exec_Iif] which seems\n    trivial to a human is not discharged by Coq.\n*)\nLemma wp_sound: forall prog post, synt_wp prog post |= prog{=post=}.\nProof.\n intros prog post e H0 e' H; generalize post H0; clear H0 post.\n elim H; clear H e' e prog; simpl; try ((firstorder eauto 20 with hoare); fail).\n (** - case [exec_Iif] *)\n intros e cond p1 p2 e'.\n case (E.eval cond e); simpl; firstorder auto.\nQed.\n\n(** * Completeness\n \n    The proof of completeness proceeds by induction over [prog] syntax.\n\n    Please, notice that coq performs this proof almost alone. The only\n    hint given here is the invariant.\n*)\nLemma wp_complete: forall prog post, prog{=post=} |= (synt_wp prog post).\nProof.\n unfold wlp; intros prog; elim prog; clear prog; simpl;\n try ((firstorder auto with hoare); fail).\n (** - case [Iseq] *)\n eauto with hoare.\n (** - case [Iwhile]: I provide the invariant below *)\n  intros.\n  constructor 1 with (x:=wlp (Iwhile cond p) post).\n  unfold wlp; intuition eauto 20 with hoare.\nQed.\n\n(** * Combining the previous results with transitivity of [ |= ] *)\n\nGlobal Hint Resolve wp_complete wp_sound: hoare.\n\nTheorem soundness: forall pre p post, pre |= (synt_wp p post) -> pre |= p {=post=}.\nProof.\n auto with hoare.\nQed.\n\nTheorem completeness: forall pre p post, pre |= p {=post=} -> pre |= (synt_wp p post).\nProof.\n  intuition auto with hoare.\nQed.\n\n\nEnd PartialHoareLogic.\n\n(** \"Tutorial on Hoare Logic\" Library. Copyright 2007 Sylvain Boulme.\n\nThis file is distributed under the terms of the \n \"GNU LESSER GENERAL PUBLIC LICENSE\" version 3.  \n*)\n", "meta": {"author": "coq-community", "repo": "hoare-tut", "sha": "66dfb255c9e8bb49269d83b3577b285288f39928", "save_path": "github-repos/coq/coq-community-hoare-tut", "path": "github-repos/coq/coq-community-hoare-tut/hoare-tut-66dfb255c9e8bb49269d83b3577b285288f39928/partialhoarelogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339797047029, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6723682814377621}}
{"text": "Require Import Utf8.\n\n(* Set definition *)\n(* In this file, a set is represented by its \ncharacteristic function. *)\nDefinition Ens {E : Type} := E -> Prop.\nDefinition In {E : Type} (A :@Ens E) (x:E) := A x.\nNotation \"x ∈ A\" := (In A x) (at level 60).\nLocal Hint Unfold In.\n\n(* Inclusion relation *)\nDefinition incl {E: Type} (A B: Ens) :=\n  ∀ x: E, x ∈ A → x ∈ B.\nNotation \"A ⊆ B\" := (incl A B) (at level 80).\n\n(* Image of a set by a function *)\nDefinition im {E F: Type} (f: E → F) (A: Ens): Ens :=\n  fun (y: F) => ∃ x, x ∈ A ∧ y = f x.\n\n(* Inverse image of a set by a function *)\nDefinition pre {E F: Type} (f: E → F) (B: Ens): Ens :=\n  fun (x: E) => f x ∈ B.\n\n(* Injective function *)\nDefinition injective {E F: Type} (f: E -> F) :=\n  ∀ (x x': E), f x = f x' → x = x'.\n\n\nTheorem direct_inclusion :\n  forall {E F: Type} (f: E → F),\n    ∀ A, A ⊆ pre f (im f A).\nProof.\n  intros E F f A. (* This automatically introduces four universal quantifiers, calling E, F, f and A the introduced objects. *)\n  unfold incl.    (* Unfold the definition of inclusion. This is possible by matching A and B in the definition with A and pre (im A). *)\n  intros x Hx.    (* introduction of universal quantifier and implication *)\n  unfold pre.     (* unfolding the definition of pre. *)\n  unfold In.      (* unfolding the definition of Im. *)\n  unfold im.      (* unfolding the definition of Image *)\n  exists x.       (* introduction of existential quantifier *)\n  split; trivial. (* introduction of conjunction and resolving trivial goals *)\nQed.\n\nTheorem reverse_inclusion :\n  forall {E F: Type} (f: E -> F),\n    injective f -> \n      forall A, incl (pre f (im f A)) A.\nProof.\n  intros.                     (* introduction of universal quantifiers and of implication *)\n  unfold incl.                (* unfolding the definition of inclusion *)\n  intros.                     (* introduction of universal quantifiers and of implication *)\n  unfold pre, In in H0.       (* unfolding the definition of Preimage in hypothesis H0 *)\n  unfold im in H0.            (* unfolding the definition of Image in hypothesis H0 *)\n  destruct H0 as [x1 [Hx1 Heq]].      (* elimination of conjuction and of existential quantifier in H0 *)\n  apply H in Heq.              (* unfolding the definition of injectivity in hypothesis H3 *)\n  rewrite Heq.                 (* rewrite H3 in the conclusion *)\n  assumption.                 (* resolve a trivial goal *)\nQed.", "meta": {"author": "jnarboux", "repo": "PA_a_priori_analysis", "sha": "c18d834186695ad09f266d7eb069bda780248e48", "save_path": "github-repos/coq/jnarboux-PA_a_priori_analysis", "path": "github-repos/coq/jnarboux-PA_a_priori_analysis/PA_a_priori_analysis-c18d834186695ad09f266d7eb069bda780248e48/Coq/case_study.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830606, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.672368279008658}}
{"text": "Require Export Iron.Language.SystemF2Effect.Type.Exp.\nRequire Export Iron.Language.SystemF2Effect.Type.Relation.KindT.\nRequire Export Iron.Language.SystemF2Effect.Type.Operator.LiftTT.\n\n(********************************************************************)\n(* Region identifier is not mentioned in the given type. *)\nFixpoint FreshT (p : nat) (tt : ty) : Prop :=\n match tt with\n | TVar _               => True\n | TForall k t          => FreshT p t\n | TApp t1 t2           => FreshT p t1 /\\ FreshT p t2\n | TSum t1 t2           => FreshT p t1 /\\ FreshT p t2\n | TBot _               => True\n | TCon0 _              => True\n | TCon1 tc t1          => FreshT p t1\n | TCon2 tc t1 t2       => FreshT p t1 /\\ FreshT p t2\n | TCap (TyCapRegion n) => ~(n = p)\n end.\n\n\n(********************************************************************)\nLemma freshT_kind\n :  forall ke sp t k p\n ,  ~(In (SRegion p) sp)\n -> KindT  ke sp t k\n -> FreshT p t.\nProof.\n intros; gen ke k.\n induction t; snorm; inverts_kind; eauto 2.\n - unfold not in H.\n   have HP: (p = p0 \\/ not (p = p0)).\n   destruct HP; subst; auto.\nQed.\nHint Resolve freshT_kind.\n\n\nLemma freshT_liftTT\n :  forall p n d t\n ,  FreshT p t\n =  FreshT p (liftTT n d t).\nProof.\n intros. gen n d.\n induction t; intros; espread; snorm; espread; eauto.\nQed.\nHint Resolve freshT_liftTT.\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/FreshT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6723186589209473}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq             *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later            *)\nFrom mathcomp Require Import all_ssreflect ssralg fingroup finalg matrix.\nRequire Import Reals Lra.\nFrom mathcomp Require Import Rstruct.\nRequire Import ssrR Reals_ext logb Rbigop.\nRequire Import fdist proba entropy aep.\n\n(******************************************************************************)\n(*                            Typical Sequences                               *)\n(*                                                                            *)\n(* Definitions:                                                               *)\n(*   `TS P n epsilon == epsilon-typical sequence of size n given an input     *)\n(*                      distribution P                                        *)\n(*   TS_0            == the typical sequence of index 0                       *)\n(*                                                                            *)\n(* Lemmas:                                                                    *)\n(*   TS_sup           == the total number of typical sequences is             *)\n(*                       upper-bounded by 2 ^ (k * (H P + e))                 *)\n(*   set_typ_seq_not0 == for k big enough, the set of typical sequences is    *)\n(*                       not empty                                            *)\n(*   TS_inf           == the total number of typical sequences is             *)\n(*                       lower-bounded by (1 - e) * 2 ^ (k * (H P - e))       *)\n(*                       for k big enough                                     *)\n(*                                                                            *)\n(* For details, see Reynald Affeldt, Manabu Hagiwara, and Jonas Sénizergues.  *)\n(* Formalization of Shannon's theorems. Journal of Automated Reasoning,       *)\n(* 53(1):63--103, 2014                                                        *)\n(******************************************************************************)\n\nDeclare Scope typ_seq_scope.\nReserved Notation \"'`TS'\".\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope R_scope.\nLocal Open Scope fdist_scope.\nLocal Open Scope proba_scope.\nLocal Open Scope entropy_scope.\n\nSection typical_sequence_definition.\n\nVariables (A : finType) (P : fdist A) (n : nat) (epsilon : R).\n\nDefinition typ_seq (t : 'rV[A]_n) :=\n  exp2 (- n%:R * (`H P + epsilon)) <b= P `^ n t <b= exp2 (- n%:R * (`H P - epsilon)).\n\nDefinition set_typ_seq := [set ta | typ_seq ta].\n\nEnd typical_sequence_definition.\n\nNotation \"'`TS'\" := (set_typ_seq) : typ_seq_scope.\n\nLocal Open Scope typ_seq_scope.\n\nLemma set_typ_seq_incl A (P : fdist A) n epsilon : 0 <= epsilon -> forall r, 1 <= r ->\n  `TS P n (epsilon / 3) \\subset `TS P n epsilon.\nProof.\nmove=> e0 r r1.\napply/subsetP => /= x.\nrewrite !inE /typ_seq => /andP[/leRP H2 /leRP H3] [:Htmp].\napply/andP; split; apply/leRP.\n- apply/(leR_trans _ H2)/Exp_le_increasing => //.\n  rewrite !mulNR leR_oppr oppRK; apply leR_wpmul2l; first exact/leR0n.\n  apply/leR_add2l.\n  abstract: Htmp.\n  rewrite leR_pdivr_mulr; [apply leR_pmulr => //|]; lra.\n- apply/(leR_trans H3)/Exp_le_increasing => //.\n  rewrite !mulNR leR_oppr oppRK; apply leR_wpmul2l; first exact/leR0n.\n  apply leR_add2l; rewrite leR_oppr oppRK; exact Htmp.\nQed.\n\nSection typ_seq_prop.\n\nVariables (A : finType) (P : fdist A) (epsilon : R) (n : nat).\n\nLemma TS_sup : #| `TS P n epsilon |%:R <= exp2 (n%:R * (`H P + epsilon)).\nProof.\nsuff Htmp : #| `TS P n epsilon |%:R * exp2 (- n%:R * (`H P + epsilon)) <= 1.\n  by rewrite -(mulR1 (exp2 _)) mulRC -leR_pdivr_mulr // /Rdiv -exp2_Ropp -mulNR.\nrewrite -(FDist.f1 (P `^ n)).\nrewrite (_ : _ * _ = \\sum_(x in `TS P n epsilon) (exp2 (- n%:R * (`H P + epsilon)))); last first.\n  by rewrite big_const iter_addR.\nby apply/leR_sumRl => //= i; rewrite inE; case/andP => /leRP.\nQed.\n\nLemma typ_seq_definition_equiv x : x \\in `TS P n epsilon ->\n  exp2 (- n%:R * (`H P + epsilon)) <= P `^ n x <= exp2 (- n%:R * (`H P - epsilon)).\nProof. by rewrite inE /typ_seq => /andP[? ?]; split; apply/leRP. Qed.\n\nLemma typ_seq_definition_equiv2 x : x \\in `TS P n.+1 epsilon ->\n  `H P - epsilon <= - (1 / n.+1%:R) * log (P `^ n.+1 x) <= `H P + epsilon.\nProof.\nrewrite inE /typ_seq.\ncase/andP => H1 H2; split;\n  apply/leRP; rewrite -(leR_pmul2l' n.+1%:R) ?ltR0n' //;\n  rewrite div1R mulRA mulRN mulRV ?INR_eq0' // mulN1R; apply/leRP.\n- rewrite leR_oppr.\n  apply/(@Exp_le_inv 2) => //.\n  rewrite LogK //; last by apply/(ltR_leR_trans (exp2_gt0 _)); apply/leRP: H1.\n  apply/leRP; by rewrite -mulNR.\n- rewrite leR_oppl.\n  apply/(@Exp_le_inv 2) => //.\n  rewrite LogK //; last by apply/(ltR_leR_trans (exp2_gt0 _)); apply/leRP: H1.\n  apply/leRP; by rewrite -mulNR.\nQed.\n\nEnd typ_seq_prop.\n\nSection typ_seq_more_prop.\n\nVariables (A : finType) (P : fdist A) (epsilon : R) (n : nat).\n\nHypothesis He : 0 < epsilon.\n\nLemma Pr_TS_1 : aep_bound P epsilon <= n.+1%:R ->\n  1 - epsilon <= Pr (P `^ n.+1) (`TS P n.+1 epsilon).\nProof.\nmove=> k0_k.\nhave -> : Pr P `^ n.+1 (`TS P n.+1 epsilon) =\n  Pr P `^ n.+1 [set i | (i \\in `TS P n.+1 epsilon) && (0 <b P `^ n.+1 i)].\n  congr Pr; apply/setP => /= t; rewrite !inE.\n  apply/idP/andP => [H|]; [split => // | by case].\n  case/andP : H => /leRP H _; exact/ltRP/(ltR_leR_trans (exp2_gt0 _) H).\nset p := [set _ | _].\nrewrite Pr_to_cplt leR_add2l leR_oppl oppRK.\nhave -> : Pr P `^ n.+1 (~: p) =\n  Pr P `^ n.+1 [set x | P `^ n.+1 x == 0] +\n  Pr P `^ n.+1 [set x | (0 <b P `^ n.+1 x) &&\n                (`| - (1 / n.+1%:R) * log (P `^ n.+1 x) - `H P | >b epsilon)].\n  have -> : ~: p =\n    [set x | P `^ n.+1 x == 0 ] :|:\n    [set x | (0 <b P `^ n.+1 x) &&\n             (`| - (1 / n.+1%:R) * log (P `^ n.+1 x) - `H P | >b epsilon)].\n    apply/setP => /= i; rewrite !inE negb_and orbC.\n    apply/idP/idP => [/orP[/ltRP|]|].\n    - by rewrite -fdist_gt0 => /negP; rewrite negbK => ->.\n    - rewrite /typ_seq negb_and => /orP[|] LHS.\n      + case/boolP : (P `^ n.+1 i == 0) => /= H1; first by [].\n        have {}H1 : 0 < P `^ n.+1 i.\n          apply/ltRP; rewrite ltR_neqAle' eq_sym H1; exact/leRP.\n        apply/andP; split; first exact/ltRP.\n        move: LHS; rewrite -ltRNge' => /ltRP/(@Log_increasing 2 _ _ Rlt_1_2 H1).\n        rewrite /exp2 ExpK // mulRC mulRN -mulNR -ltR_pdivr_mulr; last exact/ltR0n.\n        rewrite /Rdiv mulRC ltR_oppr => /ltRP; rewrite mulNR -ltR_subRL' => LHS.\n        rewrite mul1R geR0_norm //; by move/ltRP : LHS; move/(ltR_trans He)/ltRW.\n      + move: LHS; rewrite leRNgt' negbK => /ltRP LHS.\n        apply/orP; right; apply/andP; split; first exact/ltRP/(ltR_trans (exp2_gt0 _) LHS).\n        move/(@Log_increasing 2 _ _ Rlt_1_2 (exp2_gt0 _)) : LHS.\n        rewrite /exp2 ExpK // mulRC mulRN -mulNR -ltR_pdivl_mulr; last exact/ltR0n.\n        rewrite oppRD oppRK => LHS.\n        have H2 : forall a b c, - a + b < c -> - c - a < - b by move=> *; lra.\n        move/H2 in LHS.\n        rewrite div1R mulRC mulRN -/(Rdiv _ _) leR0_norm.\n        * apply/ltRP; by rewrite ltR_oppr.\n        * apply: (leR_trans (ltRW LHS)); lra.\n    - rewrite -negb_and; apply: contraTN.\n      rewrite negb_or /typ_seq => /andP[H1 /andP[/leRP H2 /leRP H3]].\n      apply/andP; split; first exact/gtR_eqF/ltRP.\n      rewrite negb_and H1 /= -leRNgt'.\n      move/(@Log_increasing_le 2 _ _ Rlt_1_2 (exp2_gt0 _)) : H2.\n      rewrite /exp2 ExpK // mulRC mulRN -mulNR -leR_pdivl_mulr ?oppRD; last exact/ltR0n.\n      move => H2.\n      have /(_ _ _ _ H2) {}H2 : forall a b c, - a + - b <= c -> - c - a <= b.\n        by move=> *; lra.\n      move/ltRP in H1.\n      move/(@Log_increasing_le 2 _ _ Rlt_1_2 H1) : H3.\n      rewrite /exp2 ExpK //.\n      rewrite mulRC mulRN -mulNR -leR_pdivr_mulr; last exact/ltR0n.\n      rewrite oppRD oppRK div1R mulRC mulRN => H3.\n      have /(_ _ _ _ H3) {}H3 : forall a b c, a <= - c + b -> - b <= - a - c.\n        by move=> *; lra.\n      rewrite leR_Rabsl; apply/andP; split; exact/leRP.\n  rewrite Pr_union_disj // disjoints_subset; apply/subsetP => /= i.\n  rewrite !inE /= => /eqP Hi; by rewrite negb_and Hi ltRR'.\nrewrite {1}/Pr (eq_bigr (fun=> 0)); last by move=> /= v; rewrite inE => /eqP.\nrewrite big_const iter_addR mulR0 add0R.\napply/(leR_trans _ (aep He k0_k))/Pr_incl/subsetP => /= t.\nrewrite !inE /= => /andP[-> /= H3]; apply/ltRW'.\nby rewrite /log_RV /= /scalel_RV /= mulRN -mulNR.\nQed.\n\nVariable He1 : epsilon < 1.\n\nLemma set_typ_seq_not0 : aep_bound P epsilon <= n.+1%:R ->\n  #| `TS P n.+1 epsilon | <> O.\nProof.\nmove/Pr_TS_1 => H.\ncase/boolP : (#| `TS P n.+1 epsilon | == O) => [|Heq]; last by apply/eqP.\nrewrite cards_eq0 => /eqP Heq.\nrewrite Heq Pr_set0 in H.\nlra.\nQed.\n\nDefinition TS_0 (H : aep_bound P epsilon <= n.+1%:R) : [finType of 'rV[A]_n.+1].\napply (@enum_val _ (pred_of_set (`TS P n.+1 epsilon))).\nhave -> : #| `TS P n.+1 epsilon| = #| `TS P n.+1 epsilon|.-1.+1.\n  rewrite prednK //.\n  move/set_typ_seq_not0 in H.\n  rewrite lt0n; by apply/eqP.\nexact ord0.\nDefined.\n\nLemma TS_0_is_typ_seq (k_k0 : aep_bound P epsilon <= n.+1%:R) :\n  TS_0 k_k0 \\in `TS P n.+1 epsilon.\nProof. rewrite /TS_0. apply/enum_valP. Qed.\n\nLemma TS_inf : aep_bound P epsilon <= n.+1%:R ->\n  (1 - epsilon) * exp2 (n.+1%:R * (`H P - epsilon)) <= #| `TS P n.+1 epsilon |%:R.\nProof.\nmove=> k0_k.\nhave H1 : 1 - epsilon <= Pr (P `^ n.+1) (`TS P n.+1 epsilon) <= 1.\n  split; by [apply Pr_TS_1 | apply Pr_1].\nhave H2 : (forall x, x \\in `TS P n.+1 epsilon ->\n  exp2 (- n.+1%:R * (`H P + epsilon)) <= P `^ n.+1 x <= exp2 (- n.+1%:R * (`H P - epsilon))).\n  by move=> x; rewrite inE /typ_seq => /andP[/leRP ? /leRP].\nmove: (wolfowitz (exp2_gt0 _) (exp2_gt0 _) H1 H2).\nby rewrite mulNR exp2_Ropp {1}/Rdiv invRK ?gtR_eqF //; case.\nQed.\n\nEnd typ_seq_more_prop.\n", "meta": {"author": "affeldt-aist", "repo": "infotheo", "sha": "5f9efb859dbadcbcae2330e2e21e76f9b632d879", "save_path": "github-repos/coq/affeldt-aist-infotheo", "path": "github-repos/coq/affeldt-aist-infotheo/infotheo-5f9efb859dbadcbcae2330e2e21e76f9b632d879/information_theory/typ_seq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715777, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6723073437175647}}
{"text": "Require Import Ssreflect.ssreflect.\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", "meta": {"author": "ilyasergey", "repo": "pnp", "sha": "dc32861434e072ed825ba1952cbb7acc4a3a4ce0", "save_path": "github-repos/coq/ilyasergey-pnp", "path": "github-repos/coq/ilyasergey-pnp/pnp-dc32861434e072ed825ba1952cbb7acc4a3a4ce0/docs/test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6723073340110173}}
{"text": "Inductive even : nat -> Prop :=\n    | ev_0 : even 0\n    | ev_SS : forall n, even n -> even (S (S n)).\n\nTheorem ev_8 : even 8.\nProof.\napply ev_SS.\napply ev_SS.\napply ev_SS.\napply ev_SS.\napply ev_0.\nQed.", "meta": {"author": "xidulu", "repo": "coq_last_hw", "sha": "57a6a8cbeb17c5bea0837d4a187f28e1adb744c6", "save_path": "github-repos/coq/xidulu-coq_last_hw", "path": "github-repos/coq/xidulu-coq_last_hw/coq_last_hw-57a6a8cbeb17c5bea0837d4a187f28e1adb744c6/task1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.67227673632509}}
{"text": "Require Import Frap.\n\nTheorem another_important_theorem : length [1; 2; 3] = 1 + length [4; 5].\nProof.\n  simplify.\n  equality.\nQed.\n\nTheorem length_concat : forall A (xs ys : list A), length (xs ++ ys) = length xs + length ys.\nProof.\n  induct xs.\n  induct ys.\n  simplify.\n  equality.\n\n  simplify.\n  equality.\n\n  simplify.\n  f_equal.\n  rewrite IHxs.\n  equality.\nQed.\n\nTheorem length_rev : forall A (xs : list A), length xs = length (rev xs).\nProof.\n  induct xs.\n  simplify.\n  equality.\n  simplify.\n  rewrite length_concat.\n  simplify.\n  linear_arithmetic.\nQed.", "meta": {"author": "emzhang", "repo": "887psets", "sha": "7b5c19f2eb0b0e549f10fa7bcbb1c873e5a77918", "save_path": "github-repos/coq/emzhang-887psets", "path": "github-repos/coq/emzhang-887psets/887psets-7b5c19f2eb0b0e549f10fa7bcbb1c873e5a77918/pset0/Pset0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6722355322842416}}
{"text": "Require Import BinNums Nat List.\nRequire Import Omega.\n\nRequire Import LibUtils Isomorphism.\nImport ListNotations.\n\nModule Internal.\nInductive BinaryDigit\n  := | bin_digit0 | bin_digit1.\n\nFixpoint pos_to_digits (p:positive) : list BinaryDigit\n  := match p with\n     | xI p' => bin_digit1 :: (pos_to_digits p')\n     | xO p' => bin_digit0 :: (pos_to_digits p')\n     | xH => [bin_digit1]\n     end.\n\nDefinition N_to_digits (n:N) : list BinaryDigit\n  := match n with\n     | N0 => nil\n     | Npos p => pos_to_digits p\n     end.\n\nFixpoint digits_to_pos (l:list BinaryDigit) : positive\n  := match l with\n     | nil => xH\n     | [ _ ] => xH\n     | bin_digit0 :: l' => xO (digits_to_pos l')\n     | bin_digit1 :: l' => xI (digits_to_pos l')\n     end.\n\nFixpoint cleanup_zeros (l:list BinaryDigit) : list BinaryDigit\n  := match l with\n     | nil => nil\n     | bin_digit0 :: l => cleanup_zeros l\n     | _ => l\n     end.\n\nDefinition fixup_trailing_zeros l\n  := (rev (cleanup_zeros (rev l))).\n\nLemma cleanup_zeros_app_middle l1 l2 : cleanup_zeros (l1 ++ bin_digit1::l2) = (cleanup_zeros l1 ++ bin_digit1::l2).\nProof.\n  revert l2.\n  induction l1; simpl; trivial; intros.\n  destruct a; eauto.\nQed.\n\nLemma fixup_trailing_zeros_app_middle l1 l2 : fixup_trailing_zeros (l1 ++ bin_digit1::l2) = (l1 ++ bin_digit1::fixup_trailing_zeros l2).\nProof.\n unfold fixup_trailing_zeros.\n rewrite rev_app_distr.\n simpl.\n rewrite app_ass; simpl.\n rewrite cleanup_zeros_app_middle.\n rewrite rev_app_distr.\n simpl.\n rewrite rev_involutive.\n rewrite <- app_assoc.\n simpl.\n reflexivity.\nQed.\n\nLemma fixup_trailing_zeros_end0 l1 : fixup_trailing_zeros (l1 ++ [bin_digit0]) = fixup_trailing_zeros l1.\nProof.\n  unfold fixup_trailing_zeros.\n  rewrite rev_app_distr.\n  simpl; trivial.\nQed.\n\nLemma fixup_trailing_zeros_end1 l1 : fixup_trailing_zeros (l1 ++ [bin_digit1]) = l1 ++ [bin_digit1].\nProof.\n  unfold fixup_trailing_zeros.\n  rewrite rev_app_distr.\n  simpl.\n  rewrite rev_involutive.\n  trivial.\nQed.\n\nDefinition digits_to_N (l:list BinaryDigit) : N\n       := let l_clean := fixup_trailing_zeros l in\n          match l_clean with\n          | nil => N0\n          | _ => Npos (digits_to_pos l_clean)\n          end.\n\nLemma pos_to_digits_nnil p : pos_to_digits p <> nil.\nProof.\n  destruct p; simpl; congruence.\nQed.\n\nDefinition canon_digits digits := { ld | digits = ld ++ [bin_digit1] }.\n\nLemma canon_digits_dec digits : canon_digits digits + {last digits bin_digit0 = bin_digit0}.\nProof.\n  unfold canon_digits.\n  induction digits; simpl.\n  - right; trivial.\n  - destruct IHdigits.\n    + destruct s as [ld pf].\n      left.\n      rewrite pf.\n      exists (a::ld); simpl.\n      trivial.\n    + destruct digits.\n      * destruct a; simpl; [eauto | ].\n        left; exists nil; simpl.\n        trivial.\n      * right; trivial.\nQed.\n\nLemma cleanup_zeros_form l :\n  {l1 |\n       l = l1 ++ cleanup_zeros l\n       /\\ (forall x, In x l1 -> x = bin_digit0)\n       /\\ (forall a l2, cleanup_zeros l = a::l2 -> a = bin_digit1)}.\nProof.\n  induction l.\n  - exists nil; simpl.\n    intuition congruence.\n  - destruct IHl as [l1 [H1 [H2 H3]]].\n    destruct a.\n    + exists (bin_digit0 :: l1).\n      simpl.\n      rewrite <- H1.\n      intuition.\n    + exists nil; simpl; intuition congruence.\nQed.\n\nLemma cleanup_zeros_zero digits :\n  cleanup_zeros digits = nil <-> Forall (eq bin_digit0) digits.\nProof.\n  rewrite Forall_forall.\n  induction digits; simpl.\n  - intuition.\n  - destruct a; simpl.\n    + intuition.\n    + split; intros HH.\n      * discriminate.\n      * specialize (HH bin_digit1).\n        { cut_to HH.\n          - discriminate.\n          - eauto.\n        } \nQed.\n              \nLemma fixup_trailing_zeros_canon digits :\n  canon_digits (fixup_trailing_zeros digits) +\n  {Forall (eq bin_digit0) digits}.\nProof.\n  unfold canon_digits, fixup_trailing_zeros.\n  case_eq (cleanup_zeros (rev digits)); intros eqq.\n  - destruct (cleanup_zeros_zero (rev digits)).\n    specialize (H eqq).\n    right.\n    rewrite Forall_forall in *.\n    intros x xin.\n    apply H.\n    apply -> in_rev.\n    trivial.\n  - intros.\n    destruct (cleanup_zeros_form (rev digits))\n      as [l1 [H1 [H2 H3]]].\n    left.\n    rewrite (H3 _ _ H).\n    simpl.\n    eauto.\nQed.\n\nLemma fixup_trailing_zeros_canon_if digits :\n  ~ Forall (eq bin_digit0) digits ->\n  canon_digits (fixup_trailing_zeros digits).\nProof.\n  intros.\n  destruct (fixup_trailing_zeros_canon digits); tauto.\nQed.\n\nLemma fixup_trailing_zeros_of_canon digits :\n  canon_digits digits ->\n  fixup_trailing_zeros digits = digits.\nProof.\n  intros [l leq].\n  unfold fixup_trailing_zeros.\n  rewrite leq.\n  rewrite rev_app_distr.\n  simpl.\n  rewrite rev_involutive.\n  reflexivity.\nQed.\n\nLemma Forall_rev {A} P (l:list A) : Forall P l <-> Forall P (rev l).\nProof.\n  repeat rewrite Forall_forall.\n  intuition.\n  - eapply H.\n    apply in_rev; trivial.\n  - eapply H.\n    apply in_rev; trivial.\n    rewrite rev_involutive; trivial.\nQed.\n\nLemma fixup_trailing_zeros_zero digits :\n  fixup_trailing_zeros digits = nil <-> Forall (eq bin_digit0) digits.\nProof.\n  unfold fixup_trailing_zeros.\n  split; intros.\n  - assert (rr: rev (rev (cleanup_zeros (rev digits))) = rev []) by congruence.\n    rewrite rev_involutive in rr.\n    simpl in rr.\n    apply cleanup_zeros_zero in rr.\n    apply Forall_rev; trivial.\n  - apply Forall_rev in H.\n    apply cleanup_zeros_zero in H.\n    rewrite H.\n    reflexivity.\nQed.\n\nLemma pos_to_digits_canon p : canon_digits (pos_to_digits p).\nProof.\n  induction p; simpl.\n  - destruct IHp.\n    rewrite e.\n    exists (bin_digit1 :: x).\n    reflexivity.\n  - destruct IHp.\n    rewrite e.\n    exists (bin_digit0 :: x).\n    reflexivity.\n  - exists nil.\n    reflexivity.\nQed.\n\nLemma digits_to_pos_to_digits p : digits_to_pos (pos_to_digits p) = p.\nProof.\n  induction p; simpl.\n  - rewrite IHp.\n    generalize (pos_to_digits_nnil p).\n    destruct (pos_to_digits p); intuition.\n  - generalize (pos_to_digits_nnil p).\n    rewrite IHp.\n    destruct (pos_to_digits p); intuition.\n  - trivial.\nQed.\n\nLemma digits_to_N_to_digits n : digits_to_N (N_to_digits n) = n.\nProof.\n  destruct n; simpl; trivial.\n  unfold digits_to_N.\n  rewrite fixup_trailing_zeros_of_canon.\n  - rewrite digits_to_pos_to_digits.\n    generalize (pos_to_digits_nnil p).\n    destruct (pos_to_digits p); intuition.\n  - apply pos_to_digits_canon.\nQed.\n\n\nLemma cleanup_zeros_app_repeat l d : cleanup_zeros ((repeat bin_digit0 d) ++ l) = cleanup_zeros l.\nProof.\n  induction d; simpl; trivial.\nQed.\n\nLemma repeat_plus_app  {A} (d:A) n1 n2 : repeat d (n1+n2) = repeat d n1 ++ repeat d n2.\nProof.\n  revert n2.\n  induction n1; simpl; trivial; intros.\n  rewrite IHn1; trivial.\nQed.\n\nLemma repeat_rev {A} (d:A) n : rev (repeat d n) = repeat d n.\nProof.\n  induction n; trivial.\n  transitivity (repeat d (n + 1)).\n  - rewrite repeat_plus_app.\n    simpl.\n    rewrite IHn.\n    trivial.\n  - f_equal.\n    omega.\nQed.\n  \nLemma fixup_trailing_zeros_app_repeat x d : fixup_trailing_zeros (x ++ repeat bin_digit0 d) = fixup_trailing_zeros x.\nProof.\n unfold fixup_trailing_zeros.\n rewrite rev_app_distr.\n rewrite repeat_rev.\n rewrite cleanup_zeros_app_repeat.\n trivial.\nQed.\n\nLemma digits_to_N_to_digits_rep n x : digits_to_N (N_to_digits n ++ repeat bin_digit0 x) = n.\nProof.\n  unfold digits_to_N.\n  rewrite fixup_trailing_zeros_app_repeat.\n  apply digits_to_N_to_digits.\nQed.\n\nLemma digits_to_N_pos_to_digits_rep p x : digits_to_N (pos_to_digits p ++ repeat bin_digit0 x) = Npos p.\nProof.\n  generalize (digits_to_N_to_digits_rep (Npos p) x).\n  simpl; trivial.\nQed.\n\nLemma pos_to_digits_to_pos digits :\n  canon_digits digits ->\n  pos_to_digits (digits_to_pos digits) = digits.\nProof.\n  induction digits; simpl.\n  - intros [? ?].\n    symmetry in e.\n    apply app_eq_nil in e.\n    destruct e.\n    discriminate.\n  - intros [ld eqq].\n    destruct ld; simpl in eqq; inversion eqq; clear eqq.\n    + reflexivity.\n    + subst.\n      cut_to IHdigits; [ | eauto].\n      destruct b; simpl.\n      * destruct (ld ++ [bin_digit1]); simpl in *; congruence.\n      * destruct (ld ++ [bin_digit1]); simpl in *; congruence.\n      * eexists; reflexivity.\nQed.\n\nLemma N_to_digits_to_N_fixup digits :\n  N_to_digits (digits_to_N digits) = fixup_trailing_zeros digits.\nProof.\n  intros.\n  unfold N_to_digits, digits_to_N.\n  generalize (fixup_trailing_zeros_canon digits); intros.\n  destruct H.\n  - destruct (fixup_trailing_zeros digits); trivial.\n    apply pos_to_digits_to_pos; trivial.\n  - apply fixup_trailing_zeros_zero in f.\n    rewrite f; trivial.\nQed.\n\nLemma N_to_digits_to_N digits :\n  canon_digits digits ->\n  N_to_digits (digits_to_N digits) = digits.\nProof.\n  intros.\n  unfold N_to_digits, digits_to_N.\n  rewrite fixup_trailing_zeros_of_canon by trivial.\n  destruct digits; trivial.\n  apply pos_to_digits_to_pos; trivial.\nQed.\n\nFixpoint interleave {A:Type} (l1 l2 : list A) {struct l1} : list A\n  := match l1, l2 with\n     | nil, l2 => l2\n     | l1, nil => l1\n     | x::l1', y::l2' => x::y::(interleave l1' l2')\n     end.\n\n\nLemma interleave_length_eq {A:Type} (l1 l2 : list A) :\n  length (interleave l1 l2) = length l1 + length l2.\nProof.\n  revert l2.\n  induction l1; destruct l2; simpl in *; trivial.\n  - auto.\n  - rewrite IHl1.\n    omega.\nQed.\n\nFixpoint uninterleave {A:Type} (l : list A) : (list A*list A)\n  := match l with\n     | x::y::l' => let (l1,l2) := uninterleave l' in\n                   (x::l1,y::l2)\n     | _ => (nil, nil)\n     end.\n\nLemma uninterleave_interleave {A:Type} (l1 l2:list A) :\n  length l1 = length l2 ->\n  (uninterleave (interleave l1 l2)) = (l1, l2).\nProof.\n  revert l2.\n  induction l1; destruct l2; simpl; trivial; intros eqq; try discriminate.\n  inversion eqq; clear eqq.\n  rewrite (IHl1 _ H0).\n  trivial.\nQed.\n\nLemma uninterleave_unfold {A:Type} (l:list A) a b :\n  (uninterleave (a::b::l)) = (a::(fst (uninterleave l)), b::(snd (uninterleave l))).\nProof.\n  simpl.\n  destruct (uninterleave l); simpl; trivial.\nQed.\n\nProgram Fixpoint EvenList_ind {A:Type} (P:list A->Prop)\n    (pfnil:P nil)\n    (pfconscons:forall a b l, P l -> P (a::b::l)) l {struct l} :\n  Nat.Even (length l) -> P l\n  := fun pfl =>\n       match l with\n       | nil => pfnil\n       | x::y::l => pfconscons x y l (EvenList_ind P pfnil pfconscons l _)\n       | _::_ => _\n       end.\nNext Obligation.\n  destruct pfl as [n npf].\n  simpl in npf.\n  exists (n-1).\n  destruct n; simpl; [omega | ].\n  destruct n; simpl; [omega | ].\n  simpl in npf.\n  inversion npf.\n  omega.\nQed.\nNext Obligation.\n  destruct (wildcard'0); simpl in *.\n  - destruct pfl as [? ?]; omega.\n  - elim (H _ _ _ (eq_refl _)).\nQed.\n\nLemma uninterleave_odd_skip {A:Type} (l:list A) a :\n  Nat.Even (length l) ->\n  (uninterleave (l ++ [a])) = uninterleave l.\nProof.\n  intros pfeven.\n  revert a.\n  pattern l.\n  revert l pfeven.\n  apply EvenList_ind.\n  - simpl; trivial.\n  - intros.\n    replace ((a :: b :: l) ++ [a0]) with (a :: b :: (l ++ [a0])) by reflexivity.\n    repeat rewrite uninterleave_unfold.\n    rewrite H.\n    trivial.\nQed.\n\nLemma uninterleave_even_end {A:Type} (l:list A) a b :\n  Nat.Even (length l) ->\n  (uninterleave (l ++ [a;b])) = (fst (uninterleave l) ++ [a], snd (uninterleave l) ++ [b]).\nProof.\n  intros pfeven.\n  revert a b.\n  pattern l.\n  revert l pfeven.\n  apply EvenList_ind.\n  - simpl; trivial.\n  - intros.\n    replace ((a :: b :: l) ++ [a0; b0]) with (a :: b :: (l ++ [a0; b0])) by reflexivity.\n    repeat rewrite uninterleave_unfold.\n    rewrite H.\n    trivial.\nQed.\n\nLemma interleave_uninterleave {A:Type} (l:list A) :\n  Nat.Even (length l) ->\n  (interleave (fst (uninterleave l)) (snd (uninterleave l))) = l.\nProof.\n  revert l.\n  apply EvenList_ind; simpl; trivial.\n  intros.\n  destruct (uninterleave l); simpl in *.\n  congruence.\nQed.\n\nDefinition interleave_with_end_padding {A:Type} (l1:list A) (def1:A) (l2:list A) (def2:A) : list A\n := interleave (l1 ++ repeat def1 (length l2 - length l1)) (l2 ++ repeat def2 (length l1 - length l2)).\n\nLemma interleave_with_end_padding_ge {A:Type} (l1:list A) (def1:A) (l2:list A) (def2:A) :\n  length l1 >= length l2 ->\n  interleave_with_end_padding l1 def1 l2 def2 = interleave l1 (l2 ++ repeat def2 (length l1 - length l2)).\nProof.\n  unfold interleave_with_end_padding.\n  intros.\n  f_equal.\n  replace (length l2 - length l1) with 0 by omega.\n  simpl.\n  rewrite <- app_nil_end; trivial.\nQed.\n\nLemma interleave_with_end_padding_le {A:Type} (l1:list A) (def1:A) (l2:list A) (def2:A) :\n  length l1 <= length l2 ->\n  interleave_with_end_padding l1 def1 l2 def2 = interleave (l1 ++ repeat def1 (length l2 - length l1)) l2.\nProof.\n  unfold interleave_with_end_padding.\n  intros.\n  f_equal.\n  replace (length l1 - length l2) with 0 by omega.\n  simpl.\n  rewrite <- app_nil_end; trivial.\nQed.\n\nLemma interleave_with_end_padding_eq {A:Type} (l1:list A) (def1:A) (l2:list A) (def2:A) :\n  length l1 = length l2 ->\n  interleave_with_end_padding l1 def1 l2 def2 = interleave l1 l2.\nProof.\n  intros.\n  unfold interleave_with_end_padding.\n  intros.\n  replace (length l1 - length l2) with 0 by omega.\n  replace (length l2 - length l1) with 0 by omega.\n  simpl.\n  repeat rewrite <- app_nil_end; trivial.\nQed.\n\nDefinition encode_digits_pair (x y : list BinaryDigit) : list BinaryDigit\n  := interleave_with_end_padding x bin_digit0 y bin_digit0.\n\nDefinition decode_digits_pair (xy : list BinaryDigit) : (list BinaryDigit * list BinaryDigit)\n  := uninterleave xy.\n\nDefinition encode_pair (x:N) (y:N) : N\n  := digits_to_N (encode_digits_pair (N_to_digits x) (N_to_digits y)).\n\nDefinition make_even_digits digits\n  := if Nat.even (length digits) then digits else (digits ++ [bin_digit0]).\n\nDefinition decode_pair_to_digits (xy:N) : (list BinaryDigit)*(list BinaryDigit)\n  :=  let digits := N_to_digits xy in\n       let digits' := make_even_digits digits in\n       decode_digits_pair digits'.\n\nDefinition decode_pair (xy:N) : N*N\n  := if N.eq_dec xy 0 then (0,0)%N else\n       let xypair := decode_pair_to_digits xy in\n       (digits_to_N (fst xypair), digits_to_N (snd xypair)).\n\n(* Definition canon_digits digits := { ld | digits = ld ++ [bin_digit1] }. *)\n\nLemma decode_pair_to_digits_digits_to_N digits :\n  canon_digits digits ->\n  decode_pair_to_digits (digits_to_N digits) = uninterleave (make_even_digits digits).\nProof.\n  intros canon.\n  unfold decode_pair_to_digits.\n  rewrite N_to_digits_to_N; trivial.\nQed.\n  \nLemma interleave_in1 {A} (l1 l2:list A) :\n  forall x,\n  In x l1 ->\n  In x (interleave l1 l2).\nProof.\n  revert l2.\n  induction l1; simpl.\n  - intuition.\n  - intros l2 x [eqq |inx].\n    + subst.\n      destruct l2; simpl; tauto.\n    + destruct l2; simpl; eauto.\nQed.\n\nLemma interleave_in2 {A} (l1 l2:list A) :\n  forall x,\n  In x l2 ->\n  In x (interleave l1 l2).\nProof.\n  revert l2.\n  induction l1; simpl.\n  - intuition.\n  - intros l2 x eqq.\n    destruct l2; simpl in *; intuition eauto.\nQed.\n\nLemma in_interleave  {A} (l1 l2:list A) :\n  forall x,\n    In x (interleave l1 l2) ->\n    In x l1 \\/ In x l2.\nProof.\n  revert l2.\n  induction l1; simpl; [ eauto | ].\n  destruct l2; simpl; [eauto | ].\n  intuition subst.\n  destruct (IHl1 _ _ H); tauto.\nQed.\n  \n  \nLemma interleave_with_end_padding_in1 {A} (l1 l2:list A) def1 def2:\n  forall x,\n  In x l1 ->\n  In x (interleave_with_end_padding l1 def1 l2 def2).\nProof.\n  unfold interleave_with_end_padding.\n  intros.\n  apply interleave_in1.\n  rewrite in_app_iff.\n  eauto.\nQed.\n\nLemma interleave_with_end_padding_in2 {A} (l1 l2:list A) def1 def2:\n  forall x,\n  In x l2 ->\n  In x (interleave_with_end_padding l1 def1 l2 def2).\nProof.\n  unfold interleave_with_end_padding.\n  intros.\n  apply interleave_in2.\n  rewrite in_app_iff.\n  eauto.\nQed.\n\nLemma in_interleave_with_end_padding {A} (l1 l2:list A) def1 def2:\n  forall x,\n    In x (interleave_with_end_padding l1 def1 l2 def2) ->\n    In x l1 \\/ In x l2 \\/ x = def1 \\/ x = def2.\nProof.\n  Hint Resolve repeat_spec : list.\n  intros.\n  destruct (in_interleave _ _ x H)\n  ; rewrite in_app_iff in *\n  ; intuition eauto with list.\nQed.\n  \nLemma encode_digits_pair0 l1 l2 :\n  Forall (eq bin_digit0) (encode_digits_pair l1 l2) <->\n  Forall (eq bin_digit0) l1 /\\\n  Forall (eq bin_digit0) l2.\nProof.\n  unfold encode_digits_pair.\n  repeat rewrite Forall_forall.\n  split; intros HH.\n  - intuition eauto using interleave_with_end_padding_in1,interleave_with_end_padding_in2.\n  - intros ? inn.\n    apply in_interleave_with_end_padding in inn.\n    intuition eauto.\nQed.\n\n\nLemma N_to_digits0 n : Forall (eq bin_digit0) (N_to_digits n) <-> n = 0%N.\nProof.\n  rewrite Forall_forall.\n  destruct n; simpl; [tauto | ].\n  split; intros.\n  - specialize (H bin_digit1).\n    destruct (pos_to_digits_canon p) as [? eqq].\n    cut_to H; [discriminate | ].\n    rewrite eqq, in_app_iff.\n    simpl.\n    eauto.\n  - discriminate.\nQed.\n\nLemma digits_to_N_fixup_encode_0 n1 n2 :\n  digits_to_N (encode_digits_pair (N_to_digits n1) (N_to_digits n2)) = 0%N ->\n  n1 = 0%N /\\ n2 = 0%N.\nProof.\n  intros HH.\n  unfold digits_to_N in HH.\n  destruct (fixup_trailing_zeros_canon (encode_digits_pair (N_to_digits n1) (N_to_digits n2))).\n  - destruct c as [? eqq].\n    rewrite eqq in HH.\n    unfold digits_to_N in HH.\n    destruct x; simpl in *; discriminate.\n  - apply encode_digits_pair0 in f.\n    destruct f as [f1 f2].\n    apply N_to_digits0 in f1.\n    apply N_to_digits0 in f2.\n    eauto.\nQed.\n\nLemma interleave_decompose {A} (digits1 digits2:list A) :\n  digits1 <> nil ->\n  length digits1 = length digits2 ->\n exists (l : list A),\n    forall d1 d2 : A,\n    interleave digits1 digits2 =\n    l ++ [last digits1 d1; last digits2 d2].\nProof.\n  revert digits2.\n  induction digits1; [intuition | ].\n  destruct digits2; simpl; intros; [discriminate | ].\n  destruct digits1; simpl.\n  - destruct digits2; simpl in *; [ | omega].\n    exists nil; simpl; trivial.\n  - destruct digits2; simpl in *; try discriminate.\n    inversion H0.\n    specialize (IHdigits1 (a2::digits2)).\n    simpl in IHdigits1.\n    destruct IHdigits1 as [l leq]\n    ; intuition (try congruence).\n    exists (a::a0::l).\n    intros d1 d2.\n    rewrite (leq d1 d2).\n    simpl; trivial.\nQed.\n\n\nLemma last_app_nnil {A:Type} (l1 l2:list A) (d:A) :\n  l2 <> nil ->\n  last (l1 ++ l2) d = last l2 d.\nProof.\n  intros.\n  induction l1; simpl; trivial.\n  rewrite IHl1.\n  assert (l1 ++ l2 <> nil).\n  { intros eqq. apply app_eq_nil in eqq. intuition. }\n  destruct (l1 ++ l2); congruence.\nQed.\n\nLemma last_repeat_nzero {A:Type} (a:A) n d : n > 0 -> last (repeat a n) d = a.\nProof.\n  induction n; [omega | ].\n  simpl.\n  destruct n; simpl in *; trivial.\n  intuition.\nQed.\n\nLemma last_repeat_same {A:Type} (a:A) n : last (repeat a n) a = a.\nProof.\n  destruct n.\n  - reflexivity.\n  - rewrite last_repeat_nzero; trivial.\n    omega.\nQed.\n\nLemma interleave_with_end_padding_decompose_eq {A} (digits1:list A) defA digits2 defB :\n  digits1 <> nil ->\n  length digits1 = length digits2 ->\n  exists l,\n  forall d1 d2,\n    interleave_with_end_padding digits1 defA digits2 defB = l ++ [last digits1 d1; last digits2 d2].\nProof.\n  intros.\n  rewrite interleave_with_end_padding_eq by omega.\n  destruct (interleave_decompose digits1 digits2)\n    as [l eql]; trivial.\n  eauto.\nQed.\n                                                        \nLemma interleave_with_end_padding_decompose_gt {A} (digits1:list A) defA digits2 defB :\n  length digits1 > length digits2 ->\n  exists l,\n  forall d,\n    interleave_with_end_padding digits1 defA digits2 defB = l ++ [last digits1 d; defB].\nProof.\n  intros.\n  rewrite interleave_with_end_padding_ge by omega.\n  destruct (interleave_decompose digits1 (digits2 ++ repeat defB (length digits1 - length digits2)))\n    as [l eql].\n  - destruct digits1; simpl in *; try congruence.\n    omega.\n  - rewrite app_length, repeat_length.\n    omega.\n  - exists l.\n    intros d.\n    rewrite (eql d defB); simpl.\n    rewrite last_app_nnil.\n    + rewrite last_repeat_same; trivial.\n    + assert ((length digits1 - length digits2) <> 0) by omega.\n      destruct (length digits1 - length digits2); simpl; intros; congruence.\nQed.\n\nLemma interleave_with_end_padding_decompose_lt {A} (digits1:list A) defA digits2 defB :\n  length digits1 < length digits2 ->\n  exists l,\n  forall d,\n    interleave_with_end_padding digits1 defA digits2 defB = l ++ [defA ; last digits2 d].\nProof.\n  intros.\n  rewrite interleave_with_end_padding_le by omega.\n  destruct (interleave_decompose (digits1 ++ repeat defA (length digits2 - length digits1)) digits2)\n           as [l eql].\n  - intros ?; subst.\n    destruct digits2; simpl in *.\n    + omega.\n    + destruct digits1; try discriminate.\n  - rewrite app_length, repeat_length.\n    omega.\n  - exists l.\n    intros d.\n    rewrite (eql defA d); simpl.\n    rewrite last_app_nnil.\n    + rewrite last_repeat_same; trivial.\n    + assert ((length digits2 - length digits1) <> 0) by omega.\n      destruct (length digits2 - length digits1); simpl; intros; congruence.\nQed.\n\n\nLemma is_nil {A:Type} (l:list A) : {l = nil} + {l <> nil}.\nProof.\n  destruct l.\n  - left; trivial.\n  - right; intro; discriminate.\nDefined.\n\n\nLemma interleave_with_end_padding_Even {A:Type} (l1:list A) (def1:A) (l2:list A) (def2:A) :\n  Nat.Even (length (interleave_with_end_padding l1 def1 l2 def2)).\nProof.\n  unfold interleave_with_end_padding.\n  rewrite interleave_length_eq.\n  repeat rewrite app_length, repeat_length.\n  destruct (Nat.lt_trichotomy (length l1) (length l2))\n    as [nlt | [neq | ngt]].\n  - exists (length l2); omega.\n  - exists (length l2); omega.\n  - exists (length l1); omega.\nQed.\n\nLemma interleave_with_end_padding_even {A:Type} (l1:list A) (def1:A) (l2:list A) (def2:A) :\n  Nat.even (length (interleave_with_end_padding l1 def1 l2 def2)) = true.\nProof.\n  apply Nat.even_spec.\n  apply interleave_with_end_padding_Even.\nQed.\n\n\n\nLemma fixup_trailing_zeros_app_two x d : fixup_trailing_zeros (x ++ [d; bin_digit1]) = (x ++ [d; bin_digit1]).\nProof.\n unfold fixup_trailing_zeros.\n rewrite rev_app_distr.\n simpl.\n rewrite rev_involutive.\n rewrite <- app_assoc.\n simpl.\n reflexivity.\nQed.\n\nDefinition padded_interleave_result n1 n2 :\n  n1 <> 0%N \\/ n2 <> 0%N ->\n  (exists l, (interleave_with_end_padding (N_to_digits n1) bin_digit0 (N_to_digits n2) bin_digit0) = l ++ [bin_digit1]) \\/\n  (exists l, (interleave_with_end_padding (N_to_digits n1) bin_digit0 (N_to_digits n2) bin_digit0) = l ++ [bin_digit1 ; bin_digit0]).\nProof.\n  simpl.\n  destruct (Nat.lt_trichotomy (length (N_to_digits n1)) (length (N_to_digits n2)))\n           as [n1lt | [n1eq | n1gt]].\n  - destruct (interleave_with_end_padding_decompose_lt (N_to_digits n1) bin_digit0 (N_to_digits n2) bin_digit0); trivial.\n    destruct n2; simpl.\n    + simpl in n1lt.\n      omega.\n    + specialize (H bin_digit0).\n      destruct (pos_to_digits_canon p) as [l leq].\n      simpl in *.\n      rewrite leq in *.\n      rewrite last_app_nnil in H by discriminate.\n      simpl in H.\n      left; exists (x++ [bin_digit0]).\n      rewrite app_ass; simpl.\n      eauto.\n  - destruct n1; simpl in *.\n    + destruct n2; simpl in n1eq.\n      * intuition congruence.\n      * intros.\n        destruct p; simpl in *; discriminate.\n    + destruct (interleave_with_end_padding_decompose_eq (pos_to_digits p) bin_digit0 (N_to_digits n2) bin_digit0); trivial.\n      * apply pos_to_digits_nnil.\n      * intros.\n        rewrite (H bin_digit0 bin_digit0).\n        left.\n        exists (x ++ [last (pos_to_digits p) bin_digit0]).\n        rewrite app_ass; simpl.\n        { destruct n2.\n          - destruct p; simpl in n1eq; discriminate.\n          - simpl.\n            destruct (pos_to_digits_canon p0) as [l leq].\n            simpl in *.\n            rewrite leq.\n            rewrite last_app_nnil by discriminate.\n            simpl.\n            reflexivity.\n        } \n  - destruct (interleave_with_end_padding_decompose_gt (N_to_digits n1) bin_digit0 (N_to_digits n2) bin_digit0); trivial.\n    destruct n1; simpl.\n    + simpl in n1gt.\n      omega.\n    + specialize (H bin_digit0).\n      destruct (pos_to_digits_canon p) as [l leq].\n      simpl in *.\n      rewrite leq in *.\n      rewrite last_app_nnil in H by discriminate.\n      simpl in H.\n      eauto.\nQed.\n\nLemma make_even_digits_fixup_trailing_zeros n1 n2 :\n(make_even_digits\n   (fixup_trailing_zeros\n      (interleave_with_end_padding (N_to_digits n1) bin_digit0 (N_to_digits n2) bin_digit0)))\n= interleave_with_end_padding (N_to_digits n1) bin_digit0 (N_to_digits n2) bin_digit0.\nProof.\n  generalize (interleave_with_end_padding_even (N_to_digits n1) bin_digit0 (N_to_digits n2) bin_digit0)\n  ; intros is_even.\n  assert (HH:n1 = 0%N /\\ n2 = 0%N \\/ (n1 <> 0%N \\/ n2 <> 0%N)).\n  { destruct n1; destruct n2; simpl; intuition congruence. }\n  destruct HH.\n  - destruct H; subst.\n    reflexivity.\n  - destruct (padded_interleave_result n1 n2) as [[l Hl] | [l Hl]]; trivial\n    ; rewrite Hl in *.\n    + rewrite fixup_trailing_zeros_end1.\n      unfold make_even_digits.\n      rewrite is_even; trivial.\n    + generalize (fixup_trailing_zeros_end0 (l ++ [bin_digit1])); intros HH.\n      rewrite app_ass in HH; simpl in HH.\n      rewrite HH.\n      rewrite fixup_trailing_zeros_end1.\n      unfold make_even_digits.\n      rewrite app_length in *.\n      simpl in *.\n      replace (length l + 2) with (S (S (length l))) in is_even by omega.\n      rewrite Nat.even_succ_succ in is_even.\n      replace (length l + 1) with (S (length l)) by omega.\n      rewrite Nat.even_succ.\n      rewrite <- Nat.negb_even.\n      rewrite is_even.\n      simpl.\n      rewrite app_ass; simpl.\n      reflexivity.\nQed.\n\nLemma decode_encode_pair (n1 n2:N) :\n  decode_pair (encode_pair n1 n2) = (n1, n2).\nProof.\n  unfold decode_pair, encode_pair.\n  destruct (N.eq_dec (digits_to_N (encode_digits_pair (N_to_digits n1) (N_to_digits n2))) 0).\n  - apply digits_to_N_fixup_encode_0 in e.\n    intuition congruence.\n  - unfold decode_pair_to_digits.\n    rewrite N_to_digits_to_N_fixup.\n    unfold encode_digits_pair.\n    rewrite make_even_digits_fixup_trailing_zeros.\n    unfold decode_digits_pair.\n    unfold interleave_with_end_padding.\n    rewrite uninterleave_interleave.\n    + simpl.\n      repeat rewrite digits_to_N_to_digits_rep.\n      trivial.\n    + repeat rewrite app_length.\n      repeat rewrite repeat_length.\n      omega.\nQed.\n\nLemma canon_digits_even_break digits :\n  canon_digits digits ->\n  Nat.even (length digits) = true ->\n  { ld & {a | digits = ld ++ [a; bin_digit1] }}.\nProof.\n  intros [l lpf] ev.\n  rewrite lpf.\n  assert (lcons: l <> nil).\n  { intros ?; subst.\n    simpl in *.\n    discriminate.\n  }\n  destruct (exists_last lcons) as [x [a pf]].\n  subst.\n  rewrite app_ass; simpl.\n  eauto.\nQed.\n\nLemma fixup_canon_uninterleave_even_snd digits : \n  canon_digits digits ->\n  Nat.even (length digits) = true ->\n  fixup_trailing_zeros (snd (uninterleave digits)) = snd (uninterleave digits).\nProof.\n  intros is_canon is_even.\n  destruct (canon_digits_even_break digits is_canon is_even)\n    as [l [a eqq]].\n  rewrite eqq in *; simpl in *.\n  rewrite uninterleave_even_end.\n  - simpl.\n    rewrite fixup_trailing_zeros_end1.\n    trivial.\n  - apply Nat.even_spec; trivial.\n    rewrite app_length in is_even; simpl in is_even.\n    replace (length l + 2) with (2 + length l) in is_even by omega.\n    simpl in is_even; trivial.\nQed.\n\nLemma fixup_canon_uninterleave_odd_fst digits a : \n  canon_digits digits ->\n  Nat.even (length digits) = false ->\n  fixup_trailing_zeros (fst (uninterleave (digits ++ [a]))) = fst (uninterleave (digits ++ [a])).\nProof.\n  intros is_canon is_even.\n  destruct is_canon as [a' eqq1].\n  rewrite eqq1 in *.\n  rewrite <- app_assoc.\n  simpl.\n  rewrite uninterleave_even_end.\n  - simpl.\n    rewrite fixup_trailing_zeros_end1; trivial.\n  - apply Nat.even_spec.\n    rewrite app_length in is_even.\n    simpl in is_even.\n    replace (length a' + 1) with (S (length a')) in is_even by omega.\n    rewrite Nat.even_succ in is_even.\n    rewrite <- Nat.negb_odd.\n    rewrite is_even; reflexivity.\nQed.\n\nLemma uninterleave_length_eq_even {A} (l:list A) :\n  Nat.even (length l) = true ->\n  length (fst (uninterleave l)) = length (snd (uninterleave l)).\nProof.\n  intros is_even.\n  apply Nat.even_spec in is_even.\n  revert l is_even.\n  apply EvenList_ind; simpl; trivial.\n  intros.\n  destruct (uninterleave l); simpl in *.\n  congruence.\nQed.\n\nLemma uninterleave_length_eq_odd {A} (l:list A) :\n  Nat.odd (length l) = true ->\n  length (fst (uninterleave l)) = length (snd (uninterleave l)).\nProof.\n  intros is_odd.\n  destruct l.\n  - vm_compute in is_odd; discriminate.\n  - simpl in is_odd.\n    rewrite Nat.odd_succ in is_odd.\n    destruct (@exists_last _ (a::l))\n    as [l' [a' eqq]]; [simpl; congruence | ].\n    rewrite eqq.\n    assert (eqlen1:length (a :: l) = length (l' ++ [a'])) by congruence.\n    rewrite app_length in eqlen1; simpl in eqlen1.\n    assert (eqlen2:length l = length l') by omega.\n    rewrite uninterleave_odd_skip.\n    + apply uninterleave_length_eq_even; trivial.\n      congruence.\n    + apply Nat.even_spec; trivial.\n      congruence.\nQed.\n    \nLemma uninterleave_length_eq {A} (l:list A) :\n  length (fst (uninterleave l)) = length (snd (uninterleave l)).\nProof.\n  case_eq (Nat.even (length l)); intros is_even.\n  - apply uninterleave_length_eq_even; trivial.\n  - apply uninterleave_length_eq_odd; trivial.\n    rewrite <- Nat.negb_even.\n    rewrite is_even.\n    reflexivity.\nQed.\n\nLemma cleanup_zeros_repeat_form l :\n  exists n,\n    l = repeat bin_digit0 n ++ cleanup_zeros l.\nProof.\n  induction l; simpl.\n  - exists 0.\n    simpl; trivial.\n  - destruct IHl as [n eqq].\n    destruct a.\n    + exists (S n); simpl.\n      rewrite <- eqq.\n      trivial.\n    + exists 0.\n      simpl; trivial.\nQed.\n\nLemma fixup_trailing_zeros_repeat_form l :\n  exists n,\n    l = fixup_trailing_zeros l ++ repeat bin_digit0 n.\nProof.\n  destruct (cleanup_zeros_repeat_form (rev l)) as [n eqq].\n  generalize (f_equal (@rev BinaryDigit) eqq); intros eqq2.\n  rewrite rev_involutive in eqq2.\n  rewrite rev_app_distr in eqq2.\n  rewrite repeat_rev in eqq2.\n  unfold fixup_trailing_zeros.\n  eauto.\nQed.\n\nLemma interleave_with_end_padding_fixup_uninterleave_make_even digits :\n  canon_digits digits ->\n  (interleave_with_end_padding\n     (fixup_trailing_zeros (fst (uninterleave (make_even_digits digits)))) bin_digit0\n     (fixup_trailing_zeros (snd (uninterleave (make_even_digits digits)))) bin_digit0)\n  = digits\n  \\/\n  (interleave_with_end_padding\n     (fixup_trailing_zeros (fst (uninterleave (make_even_digits digits)))) bin_digit0\n     (fixup_trailing_zeros (snd (uninterleave (make_even_digits digits)))) bin_digit0)\n  = digits ++ [bin_digit0].\nProof.\n  intros is_canon.\n  unfold make_even_digits.\n  case_eq (Nat.even (length digits)); intros is_even.\n  - left.\n    rewrite fixup_canon_uninterleave_even_snd by trivial.\n    destruct (fixup_trailing_zeros_repeat_form (fst (uninterleave digits)))\n      as [n eqq].\n    unfold interleave_with_end_padding.\n    generalize (uninterleave_length_eq digits); intros leneqq.\n    rewrite <- leneqq.\n    replace ((length (fst (uninterleave digits)) - length (fixup_trailing_zeros (fst (uninterleave digits))))) with n.\n    + rewrite <- eqq.\n      replace ((length (fixup_trailing_zeros (fst (uninterleave digits))) - length (fst (uninterleave digits)))) with 0.\n      * simpl.\n        rewrite app_nil_r.\n        apply interleave_uninterleave.\n        apply Nat.even_spec.\n        trivial.\n      * rewrite eqq at 2.\n        rewrite app_length.\n        rewrite repeat_length.\n        omega.\n    + rewrite eqq at 1.\n      rewrite app_length.\n      rewrite repeat_length.\n      omega.\n  - right.\n    rewrite fixup_canon_uninterleave_odd_fst by trivial.\n    destruct (fixup_trailing_zeros_repeat_form (snd (uninterleave (digits ++ [bin_digit0]))))\n      as [n eqq].\n    unfold interleave_with_end_padding.\n    generalize (uninterleave_length_eq (digits ++ [bin_digit0])); intros leneqq.\n    rewrite leneqq.\n      replace ((length (fixup_trailing_zeros (snd (uninterleave (digits ++ [bin_digit0])))) -\n                length (snd (uninterleave (digits ++ [bin_digit0]))))) with\n                                                                      0.\n    + replace ((length (snd (uninterleave (digits ++ [bin_digit0]))) -\n                length (fixup_trailing_zeros (snd (uninterleave (digits ++ [bin_digit0]))))))\n        with n.\n      * simpl.\n        rewrite app_nil_r.\n        rewrite <- eqq.\n        rewrite interleave_uninterleave; trivial.\n        apply Nat.even_spec.\n        rewrite app_length.\n        simpl.\n        replace (length digits + 1) with (S (length digits)) by omega.\n        rewrite Nat.even_succ.\n        rewrite <- Nat.negb_even.\n        rewrite is_even; reflexivity.\n      * rewrite eqq at 1.\n        rewrite app_length.\n        rewrite repeat_length.\n        omega.\n    + rewrite eqq at 2.\n      rewrite app_length.\n      omega.\nQed.\n\n\nLemma interleave_with_end_padding_fixup_uninterleave_make_even_repeat digits :\n  canon_digits digits ->\n  exists n, \n  (interleave_with_end_padding\n     (fixup_trailing_zeros (fst (uninterleave (make_even_digits digits)))) bin_digit0\n     (fixup_trailing_zeros (snd (uninterleave (make_even_digits digits)))) bin_digit0)\n  = digits ++ repeat bin_digit0 n.\nProof.\n  intros is_canon.\n  destruct (interleave_with_end_padding_fixup_uninterleave_make_even digits is_canon).\n  - exists 0.\n    simpl.\n    rewrite app_nil_r.\n    eauto.\n  - exists 1.\n    simpl.\n    eauto.\nQed.\nLemma encode_decode_pair (n:N) :\n  encode_pair (fst (decode_pair n)) (snd (decode_pair n)) = n.\nProof.\n  unfold decode_pair, encode_pair.\n  destruct n.\n  - reflexivity.\n  - simpl.\n    repeat rewrite N_to_digits_to_N_fixup.\n    unfold decode_pair_to_digits.\n    unfold decode_digits_pair.\n    simpl.\n    unfold encode_digits_pair.\n    destruct (interleave_with_end_padding_fixup_uninterleave_make_even_repeat (pos_to_digits p))\n    as [n neqq].\n    + apply pos_to_digits_canon.\n    + rewrite neqq.\n      apply (digits_to_N_pos_to_digits_rep p n).\nQed.\n\nEnd Internal.\n\nProgram Instance N_pair_encoder : Isomorphism (N*N) N\n  := {\n      iso_f '(x,y) := Internal.encode_pair x y ;\n      iso_b xy := Internal.decode_pair xy\n    }.\nNext Obligation.\n    generalize (@Internal.encode_decode_pair b); intros HH.\n    destruct (Internal.decode_pair b); simpl in *.\n    trivial.\nQed.\nNext Obligation.\n  apply Internal.decode_encode_pair.\nQed.\n\nGlobal Instance pair_encoder {A} (iso:Isomorphism A N) : Isomorphism (A*A) A\n  := Isomorphism_trans (Isomorphism_trans (Isomorphism_prod iso iso) N_pair_encoder) (Isomorphism_symm iso).\n\nGlobal Instance nat_pair_encoder : Isomorphism (nat*nat) nat := pair_encoder nat_to_N_iso.\n", "meta": {"author": "CertRL", "repo": "CertRLanon", "sha": "ba50abfb13c9c49abda8ffaad23fe76dcd4bf6ec", "save_path": "github-repos/coq/CertRL-CertRLanon", "path": "github-repos/coq/CertRL-CertRLanon/CertRLanon-ba50abfb13c9c49abda8ffaad23fe76dcd4bf6ec/coq/utils/PairEncoding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.7690802264851918, "lm_q1q2_score": 0.672235512940628}}
{"text": "\nTheorem Ex034 (A B C D : Prop) : (A \\/ ((B -> C) /\\ D)) -> ((B \\/ A) \\/ (~C -> D)).\nProof.\n  intros.\n  destruct H.\n  + left. right. exact H.\n  + destruct H.\n    right. intro. exact H0.\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/Ex034.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6722180870853668}}
{"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 Coq.omega.Omega.\nRequire Import Rsequence_def Rsequence_base_facts Rsequence_cv_facts Rsequence_rewrite_facts.\nRequire Import Rpser_def Rpser_def_simpl.\nRequire Import MyRIneq MyNat Lra.\n\nOpen Scope R_scope.\nOpen Scope Rseq_scope.\n\n(** * Rseq_sum properties *)\n\n(** Basic properties *)\n\nLemma Rseq_sum_ext_strong : forall Un Vn n,\n  (forall p, (p <= n)%nat -> Un p = Vn p) ->\n  Rseq_sum Un n = Rseq_sum Vn n.\nProof.\nintros Un Vn n ; induction n ; intro Heq.\n simpl ; apply Heq ; trivial.\n do 2 rewrite Rseq_sum_simpl ; rewrite IHn, Heq.\n  reflexivity.\n  trivial.\n  intros ; apply Heq ; auto.\nQed.\n\nLemma Rseq_sum_ext : forall Un Vn,\n  Un == Vn -> Rseq_sum Un == Rseq_sum Vn.\nProof.\nintros Un Vn Heq n ; apply Rseq_sum_ext_strong ; trivial.\nQed.\n\nLemma Rseq_sum_scal_compat_l : forall (l : R) Un,\n  Rseq_sum (l * Un) == l * (Rseq_sum Un).\nProof.\nintros l Un n ; induction n.\n reflexivity.\n simpl ; rewrite IHn ;\n  unfold Rseq_mult, Rseq_constant ;\n  simpl ; ring.\nQed.\n\n(** Compatibility with common operations *)\n\nLemma Rseq_sum_constant_compat: forall (l : R) n,\n  (Rseq_sum l n = INR (S n) * l)%R.\nProof.\nintros l n ; induction n.\n simpl ; symmetry ; apply Rmult_1_l.\n rewrite Rseq_sum_simpl, S_INR, IHn ; unfold Rseq_constant ; ring.\nQed.\n\nLemma Rseq_sum_scal_compat_r : forall (l : R) Un,\n  Rseq_sum (Un * l) == Rseq_sum Un * l.\nProof.\nintros l Un n ; induction n.\n reflexivity.\n simpl ; rewrite IHn ;\n  unfold Rseq_mult, Rseq_constant ;\n  simpl ; ring.\nQed.\n\nLemma Rseq_sum_opp_compat : forall Un,\n  Rseq_sum (- Un) == - Rseq_sum Un.\nProof.\nintros Un n ; induction n.\n reflexivity.\n simpl ; rewrite IHn ;\n  unfold Rseq_opp ;\n  simpl ; ring.\nQed.\n\nLemma Rseq_sum_plus_compat : forall Un Vn,\n  Rseq_sum (Un + Vn) == Rseq_sum Un + Rseq_sum Vn.\nProof.\nintros Un Vn n ; induction n.\n reflexivity.\n simpl ; rewrite IHn ;\n  unfold Rseq_plus ; simpl ;\n  ring.\nQed.\n\nLemma Rseq_sum_minus_compat : forall Un Vn,\n  Rseq_sum (Un - Vn) == Rseq_sum Un - Rseq_sum Vn.\nProof.\nintros Un Vn n ; rewrite Rseq_sum_ext with (Un - Vn) (Un + (- Vn)) _,\n Rseq_sum_plus_compat.\n unfold Rseq_plus, Rseq_minus ; rewrite Rseq_sum_opp_compat ; reflexivity.\n unfold Rseq_minus ; intro ; reflexivity.\nQed.\n\nLemma Rseq_sum_shift_compat : forall Un n,\n  Rseq_sum (Rseq_shift Un) n = (Rseq_shift (Rseq_sum Un) n - Un O)%R.\nProof.\nintros Un n ; induction n ;\n [| simpl ; rewrite IHn] ;\n unfold Rseq_shift, Rseq_minus ; simpl ; ring.\nQed.\n\nLemma Rseq_sum_shifts_compat : forall Un k n,\n  Rseq_sum (Rseq_shifts Un (S k)) n = (Rseq_shifts (Rseq_sum Un) (S k) n - Rseq_sum Un k)%R.\nProof.\nintros Un k n ; induction n.\n unfold Rseq_shifts, Rseq_minus ; simpl ; rewrite plus_0_r ; ring.\n simpl ; rewrite IHn ; unfold Rseq_minus, Rseq_shifts ;\n  simpl ; rewrite <- (plus_n_Sm k n) ; simpl ; ring.\nQed.\n\nLemma Rseq_sum_split_compat : forall Un k n, (k < n)%nat ->\n  (Rseq_sum Un n = Rseq_sum Un k + Rseq_sum (Rseq_shifts Un (S k)) (n - S k))%R.\nProof.\nintros Un k n kltn ; rewrite Rseq_sum_shifts_compat ; ring_simplify.\n unfold Rseq_shifts ; rewrite le_plus_minus_r ; [reflexivity | omega].\nQed.\n\nLemma Rseq_sum_reindex_compat : forall Un n,\n  Rseq_sum Un n = Rseq_sum (fun i => Un (n - i)%nat) n.\nProof.\nintros Un n ; revert Un ; induction n ; intro Un.\n reflexivity.\n do 2 rewrite Rseq_sum_simpl.\n rewrite (IHn (fun i => Un (S n - i)%nat)), minus_diag.\n rewrite (Rseq_sum_ext_strong (fun i => Un (S n - (n - i))%nat) (Rseq_shift Un)).\n rewrite Rseq_sum_shift_compat ; unfold Rseq_shift ; simpl ; ring.\n intros m m_bd ; unfold Rseq_shift ; replace (S n - (n - m))%nat with (S m) by omega ;\n reflexivity.\nQed.\n\nLemma Rseq_prod_comm: forall An Bn, (An # Bn == Bn # An)%Rseq.\nProof.\nintros An Bn n ; unfold Rseq_prod, Rseq_mult ;\n rewrite Rseq_sum_reindex_compat ; apply Rseq_sum_ext_strong ;\n intros p p_ub ; replace (n - (n - p))%nat with p by omega ;\n ring.\nQed.\n\nLemma Rseq_sum_prod_compat: forall An Bn n,\n  Rseq_sum (An # Bn) n =\n  Rseq_sum (fun i => (Rseq_sum Bn i) * An (n - i)%nat)%R n.\nProof.\nintros An Bn n ; induction n.\n unfold Rseq_prod, Rseq_mult ; simpl ; apply Rmult_comm.\n transitivity (Rseq_sum ((fun i => (An i * (Rseq_sum Bn (n - i)%nat))%R) +\n  (fun i => (An i * Bn (S (n - i))%nat))%R)%Rseq n + An (S n) * Bn O)%R.\n rewrite Rseq_sum_plus_compat, Rseq_sum_simpl, IHn ; unfold Rseq_plus ;\n rewrite Rplus_assoc ; apply Rplus_eq_compat.\n rewrite Rseq_sum_reindex_compat ; apply Rseq_sum_ext_strong ;\n  intros p p_ub ; replace (n - (n - p))%nat with p by omega ; apply Rmult_comm.\n replace O with ((S n) - S n)%nat by omega ; unfold Rseq_prod ;\n  rewrite Rseq_sum_simpl ; apply Rplus_eq_compat_r ; apply Rseq_sum_ext_strong ;\n  intros p p_ub ; unfold Rseq_mult ; replace (S n - p)%nat with (S (n - p)) by omega ;\n  reflexivity.\n transitivity (Rseq_sum (fun i => (An i * (Rseq_sum Bn (S n - i)))%R) (S n)).\n rewrite Rseq_sum_simpl, minus_diag ; apply Rplus_eq_compat ; [| trivial].\n apply Rseq_sum_ext_strong ; intros p p_ub ; unfold Rseq_plus ;\n replace (S n - p)%nat with (S (n - p)) by omega ; rewrite Rseq_sum_simpl ; ring.\n rewrite Rseq_sum_reindex_compat ; apply Rseq_sum_ext_strong ; intros p p_ub ;\n replace (S n - (S n - p))%nat with p by omega ; apply Rmult_comm.\nQed.\n\nLemma two_Sn : forall n, (2 * S n = S (S (2 * n)))%nat.\nProof.\nintro n ; ring.\nQed.\n\nLemma Rseq_sum_zip_compat_odd : forall An Bn n,\n  (Rseq_sum (Rseq_zip An Bn) (S (2 * n)) = Rseq_sum An n + Rseq_sum Bn n)%R.\nProof.\nintros An Bn ; induction n.\n unfold Rseq_zip ; simpl.\n  case (n_modulo_2 0) ; intros [p Hp] ; [| apply False_ind ; omega].\n  case (n_modulo_2 1) ; intros [q Hq] ; [apply False_ind ; omega |].\n  assert (Hp' : p = O) by omega ; assert (Hq' : q = O) by omega ; subst ; reflexivity.\n rewrite two_Sn ; do 2 rewrite Rseq_sum_simpl ; rewrite IHn ; do 2 rewrite Rseq_sum_simpl.\n  repeat rewrite Rplus_assoc ; apply Rplus_eq_compat_l.\n  rewrite (Rplus_comm (An (S n))), Rplus_assoc ; apply Rplus_eq_compat_l.\n  rewrite Rplus_comm, <- two_Sn ; apply Rplus_eq_compat ; unfold Rseq_zip ;\n   [ case (n_modulo_2 (S (2 * S n))) ; intros [p Hp] ; [apply False_ind ; omega |] |\n     case (n_modulo_2 (2 * S n)) ; intros [p Hp] ; [| apply False_ind ; omega] ] ;\n   assert (Hp' : p = S n) by omega ; subst ; reflexivity.\nQed.\n\nLemma Rseq_sum_zip_compat_even : forall An Bn n,\n  (Rseq_sum (Rseq_zip An Bn) (2 * S n) = Rseq_sum An (S n) + Rseq_sum Bn n)%R.\nProof.\nintros An Bn n ; rewrite two_Sn, Rseq_sum_simpl, Rseq_sum_zip_compat_odd,\n Rseq_sum_simpl, <- two_Sn ; unfold Rseq_zip.\n case (n_modulo_2 (2 * S n)) ; intros [p Hp] ; [| apply False_ind ; omega].\n assert (Hp' : p = S n) by omega ; subst ; ring.\nQed.\n\n(** Compatibility with the orders *)\n\nLemma Rseq_sum_pos_strong : forall An n,\n  (forall p, (p <= n)%nat -> 0 <= An p) ->\n  0 <= Rseq_sum An n.\nProof.\nintros An n ; induction n ; intro Hpos.\n simpl ; apply Hpos ; trivial.\n rewrite Rseq_sum_simpl ; apply Rplus_le_le_0_compat ;\n [apply IHn ; intros p p_bd |] ; apply Hpos ; omega.\nQed.\n\nLemma Rseq_sum_pos: forall An n,\n (forall n, 0 <= An n) ->  0 <= Rseq_sum An n.\nProof.\nintros ; apply Rseq_sum_pos_strong ; trivial.\nQed.\n\nLemma Rseq_sum_le_compat_strong: forall An Bn n,\n (forall p, (p <= n)%nat -> An p <= Bn p) ->\n Rseq_sum An n <= Rseq_sum Bn n.\nProof.\nintros An Bn n Hle ; induction n.\n simpl ; apply Hle ; trivial.\n simpl ; transitivity (Rseq_sum Bn n + An (S n))%R.\n  apply Rplus_le_compat_r ; apply IHn ; auto.\n  apply Rplus_le_compat_l ; apply Hle ; trivial.\nQed.\n\nLemma Rseq_sum_le_compat: forall An Bn n,\n (forall n, An n <= Bn n) -> Rseq_sum An n <= Rseq_sum Bn n.\nProof.\nintros ; apply Rseq_sum_le_compat_strong ; trivial.\nQed.\n\nLemma Rseq_sum_lt_compat_strong: forall An Bn n,\n (forall p, (p <= n)%nat -> An p < Bn p) ->\n Rseq_sum An n < Rseq_sum Bn n.\nProof.\nintros An Bn n Hlt ; induction n.\n simpl ; apply Hlt ; trivial.\n simpl ; transitivity (Rseq_sum Bn n + An (S n))%R.\n  apply Rplus_lt_compat_r ; apply IHn ; auto.\n  apply Rplus_lt_compat_l ; apply Hlt ; trivial.\nQed.\n\nLemma Rseq_sum_lt_compat: forall An Bn n,\n (forall n, An n < Bn n) -> Rseq_sum An n < Rseq_sum Bn n.\nProof.\nintros ; apply Rseq_sum_lt_compat_strong ; trivial.\nQed.\n\nLemma Rseq_sum_triang: forall An n,\n  Rabs (Rseq_sum An n) <= Rseq_sum (| An |) n.\nProof.\nintros An n ; induction n.\n unfold Rseq_abs ; simpl ; reflexivity.\n do 2 rewrite Rseq_sum_simpl ; eapply Rle_trans ;\n [eapply Rabs_triang |] ; apply Rplus_le_compat ;\n [assumption | reflexivity].\nQed.\n\nLemma Rseq_sum_lower_bound : forall An n lb,\n  (forall m, (m <= n)%nat -> lb <= An m) ->\n  INR (S n) * lb <= Rseq_sum An n.\nProof.\nintros An n lb HAn ; induction n.\n simpl ; rewrite Rmult_1_l ; apply HAn ; reflexivity.\n rewrite S_INR, Rmult_plus_distr_r, Rmult_1_l, Rseq_sum_simpl ;\n  apply Rplus_le_compat ; [apply IHn | apply HAn ; reflexivity].\n  intros m m_lb ; apply HAn ; omega.\nQed.\n\nLemma Rseq_sum_upper_bound : forall An n ub,\n  (forall m, (m <= n)%nat -> An m <= ub) ->\n  Rseq_sum An n <= INR (S n) * ub.\nProof.\nintros An n ub HAn ; induction n.\n simpl ; rewrite Rmult_1_l ; apply HAn ; reflexivity.\n rewrite S_INR, Rmult_plus_distr_r, Rmult_1_l, Rseq_sum_simpl ;\n  apply Rplus_le_compat ; [apply IHn | apply HAn ; reflexivity].\n  intros m m_lb ; apply HAn ; omega.\nQed.\n\n(** Convergence to infinity *)\n\nLemma Rseq_cv_pos_infty_criteria : forall An d, 0 < d ->\n  (forall n, 0 <= An n) ->\n  (forall M, exists N, (N >= M)%nat /\\ d <= Rseq_sum (Rseq_shifts An M) (N - M)) ->\n  Rseq_cv_pos_infty (Rseq_sum An).\nProof.\nintros An d d_pos An_pos HAn.\n assert (HAn' : forall M, exists N, forall n, (N < n)%nat -> INR M * d <= Rseq_sum An n).\n  intro M ; induction M.\n   destruct (HAn O) as [N [_ HN]] ; exists N.\n   intros n n_lb ; simpl ; rewrite Rmult_0_l.\n    rewrite (Rseq_sum_split_compat _ _ _ n_lb) ; apply Rplus_le_le_0_compat.\n     transitivity d.\n      left ; assumption.\n      rewrite (minus_n_O N) ;  erewrite Rseq_sum_ext ;\n       [| symmetry ; eapply Rseq_shifts_0 ] ; assumption.\n     apply Rseq_sum_pos ; intros ; apply An_pos.\n    destruct IHM as [N HN] ; destruct (HAn (S (S N))) as [N' [N'_lb HN']] ; exists N' ;\n     assert (N'_lb' : (S N < N')%nat) by omega.\n    intros n n_lb ; rewrite S_INR, Rmult_plus_distr_r, Rmult_1_l,\n     (Rseq_sum_split_compat _ _ _ n_lb), (Rseq_sum_split_compat _ _ _ N'_lb'),\n     Rplus_assoc.\n    apply Rplus_le_compat.\n     apply HN ; auto.\n     rewrite <- (Rplus_0_r d) ; apply Rplus_le_compat.\n      apply HN'.\n      apply Rseq_sum_pos ; intros ; apply An_pos.\n intro B ; pose (M := up (Rabs B / d)) ; destruct (archimed (Rabs B / d)) as [HB _].\n  assert (M_pos : (0 <= M)%Z).\n   apply le_IZR ; simpl ; eapply Rle_trans ; [| left ; eassumption].\n   apply Rle_mult_inv_pos ; [apply Rabs_pos | assumption].\n  destruct (IZN _ M_pos) as [M' HM'] ; destruct (HAn' M') as [N HN] ; exists (S N) ; intros n n_lb.\n   apply Rlt_le_trans with (INR M' * d)%R ; [| apply HN ; omega].\n   apply Rle_lt_trans with (Rabs B) ; [apply Rle_abs |].\n   rewrite <- (Rmult_1_r (Rabs B)), <- (Rinv_l d), <- Rmult_assoc, INR_IZR_INZ, <- HM'.\n   apply Rmult_lt_compat_r ; [assumption | apply HB].\n   apply Rgt_not_eq ; assumption.\nQed.\n\nLemma Rseq_cv_neg_infty_criteria : forall An d, d < 0 ->\n  (forall n, An n <= 0) ->\n  (forall M, exists N, (N >= M)%nat /\\ Rseq_sum (Rseq_shifts An M) (N - M) <= d) ->\n  Rseq_cv_neg_infty (Rseq_sum An).\nProof.\nintros An d d_neg An_neg HAn ; apply Rseq_cv_neg_infty_eq_compat with (- Rseq_sum (- An)).\n intro n ; unfold Rseq_opp at 1 ; rewrite Rseq_sum_opp_compat ; unfold Rseq_opp ;\n apply Ropp_involutive.\n apply Rseq_cv_pos_infty_opp_compat, Rseq_cv_pos_infty_criteria with (- d)%R.\n  lra.\n  intro n ; unfold Rseq_opp ; pose (An_neg n) ; lra.\n  intro M ; destruct (HAn M) as [N [N_lb HN]] ; exists N ; split.\n   assumption.\n   rewrite Rseq_sum_ext with (Vn := - Rseq_shifts An M).\n    rewrite Rseq_sum_opp_compat ; apply Ropp_le_contravar, HN.\n    apply Rseq_shifts_opp_compat.\nQed.\n\n(** Partition *)\n\nLemma Rseq_sum_even_odd_split : forall (An : Rseq) n,\n  (Rseq_sum (fun i => An (2 * i)%nat) n +\n  Rseq_sum (fun i => An (S (2 * i))%nat) n\n  = Rseq_sum An (S (2 * n)))%R.\nProof.\nintros An n ; induction n.\n reflexivity.\n replace (2 * (S n))%nat with (S (S (2 * n))) by ring.\n do 4 rewrite Rseq_sum_simpl.\n replace (2 * (S n))%nat with (S (S (2 * n))) by ring.\n rewrite <- IHn ; ring.\nQed.\n\nLemma Rseq_sum_even_odd_split' : forall An n,\n  (Rseq_sum (fun i => An (2 * i)%nat) (S n) +\n  Rseq_sum (fun i => An (S (2 * i))) n\n  = Rseq_sum An (2 * (S n)))%R.\nProof.\nintros An n ; replace (2 * S n)%nat with (S (S (2 * n))) by ring ;\n do 2 rewrite Rseq_sum_simpl ; rewrite <- Rseq_sum_even_odd_split ;\n replace (2 * S n)%nat with (S (S (2 * n))) by ring ; ring.\nQed.\n\n(** * Rseq_pps : compatibility with common operations. *)\n\nSection Rseq_pps_facts.\n\nLemma Rseq_pps_simpl : forall An x n,\n  Rseq_pps An x (S n) = (Rseq_pps An x n + (An (S n) * pow x (S n)))%R.\nProof.\nintros ; reflexivity.\nQed.\n\nLemma Rseq_pps_0_simpl : forall An n,\n Rseq_pps An 0 n = An O.\nProof.\nintros An n ; induction n.\n unfold Rseq_pps, gt_pser, Rseq_mult ; simpl ;\n  rewrite Rmult_1_r ; reflexivity.\n rewrite Rseq_pps_simpl, IHn, pow_i ; [ring | omega].\nQed.\n\nLemma Rseq_pps_O_simpl : forall An x,\n  Rseq_pps An x O = An O.\nProof.\nintros An x ; unfold Rseq_pps ; apply gt_pser_0.\nQed.\n\nLemma Rseq_pps_ext : forall An Bn x,\n  (An == Bn)%Rseq ->\n  (Rseq_pps An x == Rseq_pps Bn x)%Rseq.\nProof.\nintros An Bn x Hext ; apply Rseq_sum_ext ;\n intro n ; unfold gt_pser, Rseq_mult ; rewrite Hext ;\n reflexivity.\nQed.\n\nLemma Rseq_pps_scal_compat_l : forall (l : R) An x,\n  (Rseq_pps (l * An) x == l * Rseq_pps An x)%Rseq.\nProof.\nintros l An x n ; unfold Rseq_pps ;\n rewrite Rseq_sum_ext with _ (l * (An * (pow x)))%Rseq _.\n apply Rseq_sum_scal_compat_l.\n clear ; intro n ; unfold gt_pser, Rseq_mult, Rseq_constant ;\n  ring.\nQed.\n\nLemma Rseq_pps_scal_compat_r : forall (l : R) An x,\n  (Rseq_pps (An * l) x == Rseq_pps An x * l)%Rseq.\nProof.\nintros l An x n ; unfold Rseq_pps ;\n rewrite Rseq_sum_ext with _ ((An * (pow x)) * l)%Rseq _.\n apply Rseq_sum_scal_compat_r.\n clear ; intro n ; unfold gt_pser, Rseq_mult, Rseq_constant ;\n  ring.\nQed.\n\nLemma Rseq_pps_opp_compat : forall An x,\n  (Rseq_pps (- An) x == - Rseq_pps An x)%Rseq.\nProof.\nintros An x n ; unfold Rseq_pps ;\n rewrite Rseq_sum_ext with _ (- (An * (pow x))) _.\n apply Rseq_sum_opp_compat.\n clear ; intro n ; unfold gt_pser, Rseq_mult, Rseq_opp ;\n  ring.\nQed.\n\nLemma Rseq_pps_plus_compat : forall An Bn x,\n  Rseq_pps (An + Bn) x == Rseq_pps An x + Rseq_pps Bn x.\nProof.\nintros An Bn x n ; unfold Rseq_pps ;\n rewrite Rseq_sum_ext with _ ((An * (pow x)) + (Bn * (pow x))) _.\n apply Rseq_sum_plus_compat.\n clear ; intro n ; unfold gt_pser, Rseq_mult, Rseq_plus ;\n  ring.\nQed.\n\nLemma Rseq_pps_abs_unfold : forall An x,\n  Rseq_pps_abs An x == Rseq_pps (| An |) (Rabs x).\nProof.\nintros An x ; apply Rseq_sum_ext ; apply gt_abs_pser_unfold.\nQed.\n\nLemma Rseq_pps_prod_unfold: forall An Bn x,\n  Rseq_pps (An # Bn) x == Rseq_sum (gt_pser An x # (gt_pser Bn x)).\nProof.\nintros An Bn x n ; induction n.\n unfold Rseq_pps, gt_pser, Rseq_prod, Rseq_mult ; simpl ; ring.\n rewrite Rseq_sum_simpl, Rseq_pps_simpl, IHn ; apply Rplus_eq_compat_l.\n etransitivity.\n symmetry ; eapply (Rseq_sum_scal_compat_r _ _ (S n)).\n apply Rseq_sum_ext_strong ; fold (pow x (S n)) ; intros p p_lb ;\n unfold gt_pser, Rseq_mult, Rseq_constant.\n replace (S n) with (p + (S n - p))%nat by omega ; rewrite pow_add ;\n replace (p + (S n - p) -p)%nat with (S n - p)%nat by omega ; ring.\nQed.\n\nLemma Rseq_pps_zip_compat_odd : forall An Bn x n,\n  (Rseq_pps (Rseq_zip An Bn) x (S (2 * n)) =\n  Rseq_pps An (x ^ 2) n + x * Rseq_pps Bn (x ^ 2) n)%R.\nProof.\nintros An Bn x n ; unfold Rseq_pps ; erewrite Rseq_sum_ext ; [| eapply gt_pser_zip_compat] ;\n rewrite Rseq_sum_zip_compat_odd, Rseq_sum_scal_compat_l ; reflexivity.\nQed.\n\nLemma Rseq_pps_zip_compat_even : forall An Bn x n,\n  (Rseq_pps (Rseq_zip An Bn) x (2 * S n) =\n  Rseq_pps An (x ^ 2) (S n) + x * Rseq_pps Bn (x ^ 2) n)%R.\nProof.\nintros An Bn x n ; unfold Rseq_pps ; erewrite Rseq_sum_ext ; [| eapply gt_pser_zip_compat] ;\n rewrite Rseq_sum_zip_compat_even, Rseq_sum_scal_compat_l ; reflexivity.\nQed.\n\nLemma unfold_Ropp : forall x, (- x = - 1 * x)%R.\nProof.\nintros ; ring.\nQed.\n\nLemma Rseq_pps_alt_compat : forall An x,\n  Rseq_pps (Rseq_alt An) x == Rseq_pps An (- x).\nProof.\nintros An x n ; induction n.\n do 2 rewrite Rseq_pps_O_simpl ; unfold Rseq_alt, Rseq_mult, Rseq_pow ;\n  apply Rmult_1_l.\n do 2 rewrite Rseq_pps_simpl ; rewrite IHn ; apply Rplus_eq_compat_l.\n  unfold Rseq_alt, Rseq_mult, Rseq_pow ;\n  rewrite (unfold_Ropp x), Rpow_mult_distr ; ring.\nQed.\n\n(** * Rpser_abs, Rpser *)\n\nLemma Rpser_abs_unfold : forall An r l,\n  Rpser_abs An r l <-> Rpser (| An |) (Rabs r) l.\nProof.\nintros An r l ; split ; intro Hyp ; unfold Rpser, Rpser_abs ;\nassert (tmp := Rseq_pps_abs_unfold An r) ; eapply Rseq_cv_eq_compat ;\neauto ; symmetry ; assumption.\nQed.\n\nEnd Rseq_pps_facts.\n", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/src/Reals/Rsequence/Rsequence_sums_facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.6722008548428131}}
{"text": "(* This file presents Coq formalisation of \nexamples of proofs in higher-order Hereditary Harrop Clause logic with Cofix rule (CoHOHH)\ngiven in the paper ``Structural Resolution: a framework for coinductive proof search \nand proof construction in Horn Clause Logic''  by E.Komendantskaya, P.Johann, and M.Schmidt \n*)\n\n\n\n\n(*Coinductive Types and Corecursive Functions*)\n\nSection Coinduction.\n\nVariable A : Set.\n\nCoInductive Stream : Set :=\n    Cons : A -> Stream -> Stream.\n\nCoInductive Streamnat : Set :=\n    ConsStreamnat : nat -> Streamnat -> Streamnat.\n\n\nSet Implicit Arguments.\n\n\n(*----------------Decomposition lemmas--------------------------*)\n(* the lemmas mimic lazy beta reduction on the corecursive functions *)\n\nDefinition Streamnat_decompose (s: Streamnat) : Streamnat :=\nmatch s with\n| ConsStreamnat n s' => ConsStreamnat n s'\nend.\n\nTheorem Snat_decomposition_lemma :\nforall s, s = Streamnat_decompose s.\nProof.\nintros; case s. \nintros.\nunfold Streamnat_decompose.\ntrivial.\nQed.\n\nLtac Snat_unfold term :=\napply trans_equal with (1 := Snat_decomposition_lemma term).\n\n(*------------------------------------------*)\n\nSection SuggestedAutomation.\n\n(* This is the general tactic for automation of proofs by coinduction in Horn clause logic*)\n\n\nLtac LP_Coind  lp_cons :=\ncofix H; try intros; \ntry rewrite Snat_decomposition_lemma; simpl;\ntry apply lp_cons;\ntry apply H.\n\n(* Note the above tactic takes as an argument the name of the coinductive clause from the\ncoinductive logic program in question. *)\n\nSection RegularProofs.\n(*Proofs in Horn clause Logic for regular corecursion *)\n\n\n(* Logic program zeros, computing the stream of 0: *)\n\nCoInductive zeros:  Streamnat -> Prop :=\n  | zeros_cons: forall (y: Streamnat), zeros y  -> zeros (ConsStreamnat 0 y).\n\n(* First-order Definition of the stream in question *)\n\nCoFixpoint zerostr : Streamnat :=\nConsStreamnat 0 (zerostr).\n\n(* First-order coinductive lemma in Horn clause syntax, note the use of general tactic: *)\n\nLemma zerosQ: zeros (zerostr).\n(*\ncofix H.\nrewrite Snat_decomposition_lemma. simpl.\napply zeros_cons.\napply H.*)\nLP_Coind zeros_cons.\nQed.\n\n(* A logic program query*)\n\nLemma zerosQ2: exists x, zeros x.\nexists zerostr; apply zerosQ.\nQed.\n\n\n\nSection IrregularProofs.\n\n(*In this section, I am assuming one works with stream of natural numbers, \nwith usual pattern-matching available on both data structures -- nat and Streamnat *)\n\n(*Below is our running example program from:*)\n\nCoInductive from:  nat -> Streamnat -> Prop :=\n  | from_cons: forall (x : nat) (y: Streamnat),  from (S x) y  -> from x (ConsStreamnat x y).\n\n\n(* in LP, we make a query \"from 0 y\", which in Coq woudl mean exists y, from 0 y. \nThis will not work, as coinductive hypotheses cannot be formed with existentials \n(i.e. in negative position). *)\n\n(*So we need to provide the term for this existetial first*)\n\nCoFixpoint fromstr (n:nat) : Streamnat :=\nConsStreamnat n (fromstr (S n)).\n\n(* Because of the above definition, we need higher-order logic to \nexpress the recursive scheme. It is no longer first-order Horn clause logic  *)\n\n(*Now our LP query still cannot be proven directly by coinduction, we need a \nmore general form:  \n\n\n The query  Lemma fromQ1: exists x, from 0 x. cannot be proven directly, \nas \"from 0 fromstr 0\" will not give a \nusable coinductive hypothesis.\n\n\nThis leads us to extend from Horn clauses to Hereditary Harrop clauses, to allow\nuniversal quantification on the goals:\n*)\n\nLemma fromQ: forall x, from x (fromstr x).\ncofix H.\nintros.\nrewrite Snat_decomposition_lemma; simpl.\n(*the above is just a forced pattern matching on stream*)\napply from_cons.\n(*the above is one resolution step*)\napply H.\n(*the last step applies coinductve hypothesis*)\nQed.\n\n\n\n(* So the following goes through, using my general automated tactic instead of \nthe manual tactic application as above *)\nLemma fromQ2: forall x, from x (fromstr x).\nLP_Coind from_cons.\nQed. \n\n\n\n(*Essential thing to know in order to apply the tactic is the constructor of the coinductive type in question --\nin LP terms it is the clause that defines the coinductive behaviour. *)\n\n(*Now our initial LP query goes through as a particular case of more general lemma: *)\nLemma fromQ1: exists x, from 0 x.\nexists (fromstr 0).\napply fromQ.\nQed.\n\n(* Note that when reasoning with from, we did not need to know about \nthe inductive structure of nat. \n But we needed lazy beta-reduction (or case reasoning ) \non constructor of Streamnat via Decomposition lemmas. *)\n\n\n\nSection FibonacciLP.\n\n\n(* Fibonacci, like from, requires second-order recursive scheme and on top, \nHereditary Harrop clause syntax and\ninductive reasoning, too:. The three Horn clause of the logic \nprogram Fibs are given below. *)\n\nInductive addp: nat -> nat -> nat -> Prop :=\n| addp_0: forall y, addp 0 y y \n| addp_S: forall x y z, addp x y z -> addp (S x) y (S z).\n\nCoInductive fibs:  nat -> nat -> Streamnat -> Prop :=\n  | fibs_cons: forall (x y : nat) (s: Streamnat),  (exists z, addp x y z  /\\  fibs y z s)  \n                                           -> fibs x y  (ConsStreamnat x s).\n\n\n(*For the above program, we may have a query in LP like exists x, fibs(0, s(0), x)?*)\n\n(*So we need to provide the term for this existetial first*)\n\nCoFixpoint fibstr (n m :nat) : Streamnat :=\nConsStreamnat n (fibstr m (n+m)).\n\n(* Because of the above definition, we need higher-order logic to express the \nrecursive schemes  *)\n\n(*Unlike the example of \"from\", we need reasoning \"modulo some theory\" above: \nas n+m is pre-defined in the theory. \nSo, not only the use of natural numbers is important for pattern-matching on \ninductive constructors, \nbut also the presence of some theory.*)\n\n\n(*Now our LP query still cannot be proven directly by coinduction, \nwe need a more general form:  *)\n\n(* The tactic LP_Coind fibs_cons. will no longer work, as essential here is reasoning on add, \nnatural numbers and modulo theory *)\n\nLemma fibQ: forall x y, fibs x y (fibstr x y).\ncofix H.\nintros x y.\nrewrite Snat_decomposition_lemma; simpl.\n(*the above is just a forced pattern matching on stream*)\napply fibs_cons.\n(*the above is one resolution step. Up to this step, my old tactic works, but now \nthere is an existential proof for exists z : nat, add x y z /\\ fibs y z (fibstr y (x + y))*)\nexists (x+y).\napply conj.\n(*apply nat_ind.*)\ninduction x.\nsimpl; apply addp_0.\nsimpl; apply addp_S.\napply IHx.\n(*the above two lines take reasoning on add and nat*)\napply H.\n(*the last step applies coinductve hypothesis*)\nQed.\n\n\n(*So the tactic for more complex proof automation could  be:*)\n\nLtac LP_Coind2  lp_cons ipred icons1 icons2:=\ncofix H; try intro x; try intro y;\ntry rewrite Snat_decomposition_lemma; simpl; try apply lp_cons;\nrepeat match goal with \n| [ x: nat , y: nat  |- exists _ , _   ] => exists (x+y) end;\ntry apply conj;\nrepeat match goal with \n| [ IHx: _ |- ipred ?x _  _ ] => try induction x; simpl; try apply icons1; try apply icons2; try apply IHx; auto end;\ntry apply H.\n\n(*Testing the above tactic, all three previous lemmas are proven: *)\nLemma fibQ1: forall x y, fibs x y (fibstr x y).\nLP_Coind2 fibs_cons addp addp_0 addp_S.\nQed.\n\nLemma zerosQ1: zeros (zerostr).\nLP_Coind2 zeros_cons nat nat nat.\nQed.\n\nLemma fromQ4: forall x, from x (fromstr x).\nLP_Coind2 from_cons nat nat nat.\nQed.\n\n(*Now our initial LP query goes through as a particular case of more general lemma: *)\nLemma fromQ3: exists x, fibs 0 (S 0) x.\nexists (fibstr 0 (S 0)).\napply fibQ.\nQed.\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": "coalp", "repo": "Coq", "sha": "f3c499b82e72677a0948a1369eb67dd65d5c03ab", "save_path": "github-repos/coq/coalp-Coq", "path": "github-repos/coq/coalp-Coq/Coq-f3c499b82e72677a0948a1369eb67dd65d5c03ab/CoIndProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.6722008479034827}}
{"text": "(** * Some useful bounds N.\n\n*)\n\nRequire Export BinNat.\nRequire Export NArith.\nHint Resolve N.le_refl\n       N.le_le_succ_r\n       N.lt_succ_diag_r\n       N.lt_lt_succ_r\n       N.size_gt\n       N.le_trans\n       N.lt_le_trans\n       N.le_lt_trans\n       N.le_0_l\n       N.pow_nonzero\n       N.add_le_mono\n       N.add_lt_mono\n       N.mul_le_mono\n       N.mul_lt_mono\n       N.pow_le_mono_r  : Nfacts.\n\nHint Rewrite\n     N.sub_0_r N.sub_diag N.mod_0_l N.mod_mod\n     N.div2_succ_double N.div2_double\n     N.add_1_r N.add_1_l\n     N.add_0_r N.add_0_l\n     N.pow_add_r\n     N.pow_succ_r\n     N.add_sub\n  : Nrewrites.\n\n\n\nLtac crush :=\n  repeat (\n      try intros;\n      eauto with Nfacts;\n      autorewrite with Nrewrites;\n      try (simpl; f_equal);\n      match goal with\n      | [ _ : ?P |- ?P ] => assumption\n      | [ |- (?n + ?p < ?m + ?q)%N ] => apply (N.add_lt_mono n m p q)\n      | [ |- (?n * ?p < ?m * ?q)%N ] => apply (N.mul_lt_mono n m p q)\n      | [ |- positive -> _ ] => let p := fresh \"p\" in intro p\n      | [ |- N -> _ ] => let n := fresh \"n\" in intro n\n      | [ p : positive |- _ ] => induction p\n      | _ => idtac\n      end; eauto with Nfacts).\n\nLemma of_nat_le_mono: forall a b, a <= b -> (N.of_nat a <= N.of_nat b)%N.\nProof.\n  intros a b aleb.\n  Hint Rewrite Nat2N.inj_succ : Nrewrites.\n  induction aleb; crush.\nQed.\n\nHint Resolve of_nat_le_mono : Nfacts.\n\nLemma inj_size : forall x, N.of_nat (N.size_nat x) = N.size x.\nProof.\n  intro x; induction x;\n    assert (forall p, Pos.of_succ_nat (Pos.size_nat p) = Pos.succ (Pos.size p));\n  crush.\nQed.\n\nLemma N_2_neq_0 : (2 <> 0)%N.\nProof.\n  intro Hyp; inversion Hyp.\nQed.\n\nHint Resolve N_2_neq_0 : Nfacts.\n\nLemma N_pow_2_neq_0 : forall n, (2^n <> 0)%N.\nProof.\n  crush.\nQed.\n\nLemma Npow_2_le_mono : forall a b, (a <= b -> 2^a <= 2^b)%N.\nProof.\n  crush.\nQed.\n\nLemma Npow_2_le_mono_nat : forall a b, a <= b -> (2^(N.of_nat a) <= 2^(N.of_nat b))%N.\nProof.\n  crush.\nQed.\n\nHint Resolve Npow_2_le_mono : Nfacts.\n\nLemma Nsize_pow_2 n x : (N.size x <= n -> x < 2^n)%N.\nProof.\n  intros; assert (2^N.size x <= 2^n)%N;assert (x < 2^ N.size x)%N; crush.\nQed.\n\nHint Resolve Nsize_pow_2 : Nfacts.\n\nLemma Nsize_nat_pow_2  n x : N.size_nat x <= n -> (x < 2^(N.of_nat n))%N.\nProof.\n  intros; assert (N.size x <= N.of_nat n)%N;\n  try (rewrite <- inj_size);\n  crush.\nQed.\n\nHint Resolve Nsize_nat_pow_2 : Nfacts.\n\nLemma Ndouble_twice : forall (x : N),  (x + x = 2 *x)%N.\n  intro;\n    apply N2Nat.inj.\n  autorewrite with Nnat.\n  crush.\nQed.\n\n\nLemma Nadd_bound n a b :  (N.size a <= n -> N.size b <= n\n                           -> (a + b) < 2^(1+n))%N.\nProof.\n  intros.\n  Hint Resolve N.add_le_mono : Nfacts.\n  autorewrite with Nrewrites.\n  rewrite <- Ndouble_twice.\n  crush.\nQed.\n\nLemma Nadd_bound_gen n m a b :  (n < m -> N.size a <= n -> N.size b <= n\n                            -> (a + b) < 2^m)%N.\nProof.\n  intros.\n  Hint Resolve Npow_2_le_mono : Nfacts.\n  Hint Resolve N.le_succ_l : Nfacts.\n  Hint Resolve Nadd_bound : Nfacts.\n  assert (a + b  < 2^(1+n))%N by eauto with Nfacts.\n  assert (1+n <= m)%N by (crush; now apply N.le_succ_l).\n  assert (2^(1+n) <= 2^m)%N by now apply (Npow_2_le_mono (1+n) m)%N.\n  crush.\nQed.\n\nLemma Nadd_bound_nat n a b : N.size_nat a <= n -> N.size_nat b <= n\n                               -> ((a + b) < 2^(N.of_nat (S n)))%N.\nProof.\n  autorewrite with Nrewrites;\n  try (rewrite <- Ndouble_twice);\n  crush.\nQed.\n\n\nLemma Nadd_bound_nat_gen n m a b : n < m -> N.size_nat a <= n -> N.size_nat b <= n\n                               -> ((a + b) < 2^(N.of_nat m))%N.\nProof.\n  intros.\n  Hint Resolve Npow_2_le_mono_nat : Nfacts.\n  Hint Resolve Nadd_bound_nat : Nfacts.\n  assert(a+b < 2^N.of_nat (S n))%N; crush.\nQed.\n\nLemma Nmul_bound n0 n1 a b :  (N.size a <= n0 -> N.size b <= n1\n                               -> (a * b) < 2^(n0 + n1))%N.\nProof.\n  crush.\nQed.\n\nLemma Nmul_bound_nat n0 n1 a b :  N.size_nat a <= n0 -> N.size_nat b <= n1\n                               -> ((a * b) < 2^(N.of_nat (n0 + n1)))%N.\nProof.\n  Hint Rewrite Nat2N.inj_add : Nrewrites.\n  crush.\nQed.\n\nLemma div_mod_sub : forall a b, b <> 0%N ->  (a / b * b = a - a mod b)%N.\n  intros a b Hbnz.\n  rewrite N.mul_comm.\n  set (lhs:= (b*(a/b))%N).\n  set (amb := (a mod b)%N).\n  rewrite (N.div_mod a b); trivial.\n  crush.\nQed.\n\nLemma divide_add_mod_multiple : forall x m n p : N, n <> 0%N -> (n | m)%N ->  (x mod n = (m * p + x) mod n )%N.\nProof.\n    intros x m n p.\n    intro HnNz.\n    intro HnDm.\n    rewrite N.add_mod; trivial.\n    rewrite N.mul_mod; trivial.\n    assert (Hmnz : (m mod n = 0)%N) by (rewrite (N.mod_divide m n HnNz); trivial).\n    rewrite Hmnz.\n    crush.\nQed.\n\nLemma divide_mod_mod : forall (x m n : N), m <> 0%N ->  n <> 0%N -> (n | m)%N ->  ( (x mod m ) mod n = x mod n)%N.\n  intros x m n.\n  intros HmnZ HnnZ.\n  intro HnDm.\n  rewrite (divide_add_mod_multiple (x mod m) m n (x / m)); trivial.\n  rewrite <- N.div_mod; trivial.\nQed.\n\n(*\nHint Rewrite divide_mod_mod : localdb.\n*)\n\nLemma divide_mod_le : forall (x m n : N), m <> 0%N -> n <> 0%N -> (n | m)%N  -> (n < m)%N ->  (x mod n <= x mod m)%N.\n  intros x m n.\n  intros HmNz HnNz HnDm HnLTm.\n  rewrite <- (divide_mod_mod x m n); trivial.\n  apply (N.mod_le (x mod m) n); trivial.\nQed.\n\nLemma add_sub_le : forall a b : N, (a <= b)%N -> (a + (b - a) = b)%N.\n  intros a b HaLeB.\n  rewrite N.add_sub_assoc; eauto.\n  rewrite N.add_comm.\n  apply N.add_sub.\nQed.\n", "meta": {"author": "raaz-crypto", "repo": "verse-coq", "sha": "621f86f4adc3bad53458186f0272425db13d2db7", "save_path": "github-repos/coq/raaz-crypto-verse-coq", "path": "github-repos/coq/raaz-crypto-verse-coq/verse-coq-621f86f4adc3bad53458186f0272425db13d2db7/src/Verse/NFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.6722008477185909}}
{"text": "Require Import Arith.\nRequire Import List.\nImport ListNotations.\nRequire Import StructTact.StructTactics.\n\nSet Implicit Arguments.\n\nLemma leb_false_lt : forall m n, leb m n = false -> n < m.\nProof.\n  induction m; intros.\n  - discriminate.\n  - simpl in *. break_match; subst; auto with arith.\nQed.\n\nLemma leb_true_le : forall m n, leb m n = true -> m <= n.\nProof.\n  induction m; intros.\n  - auto with arith.\n  - simpl in *. break_match; subst; auto with arith.\n    discriminate.\nQed.\n\nLemma ltb_false_le : forall m n, m <? n = false -> n <= m.\nProof.\n  induction m; intros; destruct n; try discriminate; auto with arith.\nQed.\n\nLemma ltb_true_lt : forall m n, m <? n = true -> m < n.\n  induction m; intros; destruct n; try discriminate; auto with arith.\nQed.\n\nLtac do_bool :=\n  repeat match goal with\n    | [ H : beq_nat _ _ = true |- _ ] => apply beq_nat_true in H\n    | [ H : beq_nat _ _ = false |- _ ] => apply beq_nat_false in H\n    | [ H : andb _ _ = true |- _ ] => apply Bool.andb_true_iff in H\n    | [ H : andb _ _ = false |- _ ] => apply Bool.andb_false_iff in H\n    | [ H : orb _ _ = true |- _ ] => apply Bool.orb_prop in H\n    | [ H : negb _ = true |- _ ] => apply Bool.negb_true_iff in H\n    | [ H : negb _ = false |- _ ] => apply Bool.negb_false_iff in H\n    | [ H : PeanoNat.Nat.ltb _ _ = true |- _ ] => apply ltb_true_lt in H\n    | [ H : PeanoNat.Nat.ltb _ _ = false |- _ ] => apply ltb_false_le in H\n    | [ H : leb _ _ = true |- _ ] => apply leb_true_le in H\n    | [ H : leb _ _ = false |- _ ] => apply leb_false_lt in H\n    | [ |- andb _ _ = true ]=> apply Bool.andb_true_iff\n    | [ |- andb _ _ = false ] => apply Bool.andb_false_iff\n    | [ |- leb _ _ = true ] => apply leb_correct\n    | [ |-  _ <> false ] => apply Bool.not_false_iff_true\n    | [ |- beq_nat _ _ = false ] => apply beq_nat_false_iff\n    | [ |- beq_nat _ _ = true ] => apply beq_nat_true_iff\n  end.\n\nDefinition null {A : Type} (xs : list A) : bool :=\n  match xs with\n    | [] => true\n    | _ => false\n  end.\n\nLemma null_sound :\n  forall A (l : list A),\n    null l = true -> l = [].\nProof.\n  destruct l; simpl in *; auto; discriminate.\nQed.\n\nLemma null_false_neq_nil :\n  forall A (l : list A),\n    null l = false -> l <> [].\nProof.\n  destruct l; simpl in *; auto; discriminate.\nQed.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/StructTact/BoolUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.6722008459375354}}
{"text": "(* Exercise done by David Braun under the supervision of Nicolas Magaud, cleaned up by Julien Narboux. *)\n\nRequire Export GeoCoq.Tarski_dev.Annexes.midpoint_theorems.\nSection T_42.\n\nContext `{TE:Tarski_euclidean}.\n\nLemma midpoint_thales : forall O A B C : Tpoint,\n   ~ Col A B C ->\n   Midpoint O A B ->\n   Cong O A O C ->\n   Per A C B.\nProof.\nintros.\nName X the midpoint of C and A.\nassert (Par_strict O X B C)\n by perm_apply (triangle_mid_par_strict_cong_simp C B A O X).\nassert(Per O X A)\n by (exists C;split;finish).\nassert_diffs.\nassert_cols.\nassert(Hid2 : Perp O X C A)\n by perm_apply (col_per_perp O X A C).\nassert (Perp B C C A).\n apply (cop_par_perp__perp O X B C C A);finish.\napply perp_per_1;Perp.\nQed.\n\n(* TODO cleanup *)\n\nLemma midpoint_thales_reci :\n  forall a b c o: Tpoint,\n   Per a c b ->\n   Midpoint o a b ->\n   Cong o a o b /\\ Cong o b o c.\nProof.\nintros.\n\ninduction (col_dec a b c).\n\ninduction (l8_9 a c b H);\ntreat_equalities;assert_congs_perm;try split;finish.\nassert_diffs.\n(* Demonstration Cong o a o b *)\nassert_congs_perm.\nsplit.\nCong.\n(* Demonstration Cong o b o c *)\nassert(Hmid := midpoint_existence a c).\n(* Soit x Le milieu de a c *)\ndestruct Hmid.\n(* Demonstration o x parallele à b c *)\nassert(Hpar : Par c b x o).\napply (triangle_mid_par c b a o x);finish.\n(* On doit effectuer Le changement d'angle perpendiculaire en appliquant par_perp_perp*)\n(* Demonstration du sous but Perp pour appliquer par_perp_perp *)\nassert(Hper : Perp c b c a)\n by (apply perp_left_comm;apply per_perp;Perp).\n(* Demonstratin du sous but Cop pour appliquer par_perp_perp *)\nassert(Hcop : Coplanar x o c a) by Cop.\n(* Application de par_perp_perp *)\nassert(HH := cop_par_perp__perp c b x o c a Hpar Hper).\nassert(Hper2 : Perp c x o x).\n  apply (perp_col c a o x x).\n  assert_diffs.\n  finish.\n  Perp.\n  assert_cols;Col.\n(*Transformation de Perp c x o x en Per *)\nassert_diffs.\nassert (Per o x c)\n by (apply perp_per_2;Perp).\n\n(* Depliage de Per pour obtenir Cong o b o c *)\nunfold Per in H8.\ndestruct H8.\nspliter.\napply l7_2 in H8.\nassert(HmidU := l7_9 a x0 x c H2 H8).\nsubst.\nunfold Midpoint in H2.\nspliter.\neCong.\nQed.\n\nEnd T_42.\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/Highschool/midpoint_thales.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219505, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.6722008404094765}}
{"text": "(*\n        #####################################################\n        ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n        #####################################################\n*)\nRequire Import Coq.Lists.List.\nRequire Import Coq.Strings.Ascii.\nRequire Import Turing.Lang.\nRequire Import Turing.Regular.\nRequire Import Turing.Regex.\nRequire Import Turing.Util.\nRequire Import Omega.\nImport ListNotations.\nImport RegexNotations.\nImport Lang.LangNotations.\nOpen Scope char_scope.\nOpen Scope lang_scope.\nOpen Scope regex_scope.\n\n(* ---------------------- END OF PREAMBLE ------------------ *)\n\n(**\n\n  The objective of this homework assignment is to prove that\n  language L5 is not regular, where L5 is a^n b^m where n < m.\n\n\n  WARNING: DO NOT CHANGE DEFINITION L5, otherwise you will get 0 points for\n  this assignment.\n\n*)\nDefinition L5 : language := fun w => exists n m, w = pow1 \"a\" n ++ (pow1 \"b\" ((S m) + n)).\n\nLemma pow1_app_cons_inv_eq_1:\nforall {T} (a b:T),\na <> b ->\nforall x y v w,\npow1 a x ++ b :: y = pow1 a v ++ b :: w ->\nx = v.\nProof.\nintros ? a b.\ninduction x; intros. {\n    simpl in *.\n    destruct v; auto.\n    simpl in *.\n    inversion H0.\n    subst.\n    contradiction.\n}\nsimpl in *.\ndestruct v; simpl in *. {\n    inversion H0.\n    subst.\n    contradiction.\n}\ninversion H0; subst; clear H0.\napply IHx in H2.\nsubst; reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------------*)\n\n\n\n\n(**\n\nEasy. Show that the word that clogs is in L5.\n\n *)\nTheorem l5_not_regular_1:\n  forall p, In (pow1 \"a\" p ++ pow1 \"b\" (S p)) L5.\nProof.\n  simpl.\n  intros N.\n  unfold In.\n  unfold L5.\n  exists N.\n  exists 0.\n  simpl.\n  reflexivity.\nQed.\n\n(**\n\nEasy. Show that the clogged word has at least p-characters.\n\n *)\nTheorem l5_not_regular_2:\n  forall p, length (pow1 \"a\" p ++ pow1 \"b\" (S p)) >= p.\nProof.\n  simpl.\n  intros N.\n  induction N.\n  - simpl.\n    intuition.\n  - simpl.\n    rewrite -> app_length.\n    rewrite -> pow1_length.\n    omega.\nQed.\n\n(**\n\nDifficult. The proof for Regular.Examples.l4_not_regular_alt is similar to what you should be doing. The only theorem you need to use is Regular.Examples.xyz_rw_ex.\n\n\n *)\nTheorem l5_not_regular_4_1:\n  forall p x y z n m, p >= 1 -> y <> [] -> pow1 \"a\" p ++ \"b\" :: pow1 \"b\" p = x ++ y ++ z -> length (x ++ y) <= p -> x ++ (y ++ y) ++ z = pow1 \"a\" n ++ pow1 \"b\" (S m + n) -> exists nx ny o,\n    ny <> 0 /\\\n    pow1 \"a\" nx ++\n    (pow1 \"a\" ny ++ pow1 \"a\" ny) ++\n    pow1 \"a\" o ++\n    \"b\" :: pow1 \"b\" (length (pow1 \"a\" nx ++ pow1 \"a\" ny) + o)\n    =\n    pow1 \"a\" n ++ pow1 \"b\" (S m + n).\nProof.\n  simpl.\n  intros N.\n  intros M.\n  intros O.\n  intros P.\n  intros Q.\n  intros R.\n  intros S.\n  intros T.\n  intros V.\n  intros W.\n  intros X.\n  apply Regular.Examples.xyz_rw_ex in V.\n  destruct V.\n  destruct H.\n  destruct H0.\n  destruct H1.\n  destruct H2.\n  rewrite -> H1 in X.\n  rewrite -> H2 in X.\n  rewrite -> H3 in X.\n  rewrite -> H in X.\n  repeat rewrite app_assoc in *. (* l4_not_regular *)\n  repeat rewrite pow1_plus in *.\n  exists (length M), (length O), x.\n  split.\n  - simpl.\n    intros Y.\n    destruct O.\n    + simpl.\n      contradiction T.\n    + simpl.\n      inversion Y.\n  - simpl.\n    repeat rewrite app_assoc in *.\n    repeat rewrite pow1_plus in *.\n    rewrite -> pow1_length.\n    rewrite -> app_length in X.\n    rewrite -> X.\n    simpl.\n    reflexivity.\n  - simpl.\n    assumption.\nQed.\n\n\n(**\n\nEasy. Use rewriting rules (eg, app_assoc).\n\n *)\nTheorem l5_not_regular_4_2:\n  forall nx ny n m o, pow1 \"a\" nx ++ (pow1 \"a\" ny ++ pow1 \"a\" ny) ++ pow1 \"a\" o ++ \"b\" :: pow1 \"b\" (length (pow1 \"a\" nx ++ pow1 \"a\" ny) + o) = pow1 \"a\" n ++ pow1 \"b\" (S m + n) -> pow1 \"a\" (nx + ny + ny + o) ++ \"b\" :: pow1 \"b\" (nx + ny + o) = pow1 \"a\" n ++ \"b\" :: pow1 \"b\" (m + n).\nProof.\n  simpl.\n  intros N.\n  intros M.\n  intros O.\n  intros P.\n  intros Q.\n  intros R.\n  repeat rewrite app_assoc in R.\n  repeat rewrite pow1_plus in R.\n  repeat rewrite pow1_length in R.\n  assumption.\nQed.\n\n(**\n\nHard. This is the final step of the proof. You want to start by showing that the powers of \"a\" are equal (for which you'll need pow1_app_cons_inv_eq_1). After that you want to remove the left-hand side of the equality with app_inv_head. Your final step should be to conclude that both powers must be equal. Once you have an equality over naturals, then use `omega` to conclude.\n\n\n *)\nTheorem l5_not_regular_4_3:\n  forall nx ny o n m, ny <> 0 -> pow1 \"a\" (nx + ny + ny + o) ++ \"b\" :: pow1 \"b\" (nx + ny + o) <>\n    pow1 \"a\" n ++ \"b\" :: pow1 \"b\" (m + n).\nProof.\n  simpl.\n  intros N.\n  intros O.\n  intros P.\n  intros Q.\n  intros R.\n  intros S.\n  intros T.\n  inversion T.\n  apply pow1_app_cons_inv_eq_1 in H0.\n  - simpl.\n    rewrite -> H0 in T.\n    apply app_inv_head in T.\n    inversion T.\n    apply pow1_inv_eq in H1. \n    omega.\n  - simpl.\n    intros V.\n    inversion V.\nQed.\n\n(**\n\nEasy. Use the lemmas that start with l5_not_regular_4_\n\n *)\nTheorem l5_not_regular_4:\n  forall p m n x y z, p >= 1 -> y <> [] -> pow1 \"a\" p ++ \"b\" :: pow1 \"b\" p = x ++ y ++ z -> length (x ++ y) <= p -> x ++ (y ++ y) ++ z <> pow1 \"a\" n ++ pow1 \"b\" (S m + n).\nProof.\n  simpl.\n  intros N.\n  intros O.\n  intros P.\n  intros Q.\n  intros R.\n  intros S.\n  intros T.\n  intros V.\n  intros W.\n  intros X.\n  intros Y.\n  apply l5_not_regular_4_1 with (p:= N) in Y.\n  - simpl.\n    destruct Y.\n    destruct H.\n    destruct H.\n    destruct H.\n    apply l5_not_regular_4_2 in H0.\n    apply l5_not_regular_4_3 in H0.\n    + simpl.\n      assumption.\n    + simpl.\n      assumption.\n  - simpl.\n    omega.\n  - simpl.\n    assumption.\n  - simpl.\n    assumption.\n  - simpl.\n    assumption.\nQed.\n\n(**\n\nEasy. Show that a^p b^(p+1) clogs L5. Conclude the proof using Lemma l5_not_regular_4 to conclude.\n\n\n *)\nTheorem l5_not_regular_3:\n  forall p, p >= 1 -> In (pow1 \"a\" p ++ pow1 \"b\" (S p)) (Clogs L5 p).\nProof.\n  - simpl.\n    unfold In, Clogs.\n    intros N.\n    intros O.\n    intros P.\n    intros Q.\n    intros R.\n    intros S.\n    intros T.\n    intros V.\n    exists 2.\n    intros W.\n    unfold In in W.\n    unfold L5 in W.\n    destruct W.\n    destruct H.\n    simpl in H.\n    rewrite app_nil_r in H.\n    apply l5_not_regular_4 with (p:=N) in H.\n    + simpl.\n      apply H.\n    + simpl.\n      assumption.\n    + simpl.\n      assumption.\n    + simpl.\n      assumption.\n    + simpl.\n      assumption.\nQed.\n\n\n(**\n\nEasy. Show that L5 is not regular.\n\n *)\nTheorem l5_not_regular:\n  ~ Regular L5.\nProof.\n  simpl.\n  unfold L5.\n  apply not_regular.\n  intros N.\n  intros O.\n  apply clogged_def with (w:=(pow1 \"a\" N ++ pow1 \"b\" (1 + N)) % list).\n  - simpl.\n    unfold In.\n    unfold L5.\n    exists N.\n    exists 0.\n    simpl.\n    reflexivity.\n  - simpl.\n    induction N.\n    + simpl.\n      intuition.\n    + simpl.\n      rewrite -> app_length.\n      rewrite -> pow1_length.\n      omega.\n  - simpl.\n    unfold In, Clogs.\n    intros P.\n    intros Q.\n    intros R.\n    intros S.\n    intros T.\n    intros V.\n    exists 2.\n    intros W.\n    unfold In in W.\n    unfold L5 in W.\n    destruct W.\n    destruct H.\n    simpl in H.\n    rewrite app_nil_r in H.\n    apply l5_not_regular_4 with (p:=N) in H.\n    + simpl.\n      apply H.\n    + simpl.\n      assumption.\n    + simpl.\n      assumption.\n    + simpl.\n      assumption.\n    + simpl.\n      assumption.\nQed.\n\n\n\n\n", "meta": {"author": "mansi0312", "repo": "CS420", "sha": "d949dc7ba204b990a4bfe3b616916437f50b0230", "save_path": "github-repos/coq/mansi0312-CS420", "path": "github-repos/coq/mansi0312-CS420/CS420-d949dc7ba204b990a4bfe3b616916437f50b0230/hw6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.6721281500967046}}
{"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: Sorted.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\n(* Made by Hugo Herbelin *)\n\n(** This file defines two notions of sorted list:\n\n  - a list is locally sorted if any element is smaller or equal than\n    its successor in the list\n  - a list is sorted if any element coming before another one is\n    smaller or equal than this other element\n\n  The two notions are equivalent if the order is transitive.\n*)\n\nRequire Import List Relations Relations_1.\n\n(** Preambule *)\n\nSet Implicit Arguments.\nLocal Notation \"[ ]\" := nil (at level 0).\nLocal Notation \"[ a ; .. ; b ]\" := (a :: .. (b :: []) ..) (at level 0).\nImplicit Arguments Transitive [U].\n\nSection defs.\n\n  Variable A : Type.\n  Variable R : A -> A -> Prop.\n\n  (** Locally sorted: consecutive elements of the list are ordered *)\n\n  Inductive LocallySorted : list A -> Prop :=\n    | LSorted_nil : LocallySorted []\n    | LSorted_cons1 a : LocallySorted [a]\n    | LSorted_consn a b l :\n        LocallySorted (b :: l) -> R a b -> LocallySorted (a :: b :: l).\n\n  (** Alternative two-step definition of being locally sorted *)\n\n  Inductive HdRel a : list A -> Prop :=\n    | HdRel_nil : HdRel a []\n    | HdRel_cons b l : R a b -> HdRel a (b :: l).\n\n  Inductive Sorted : list A -> Prop :=\n    | Sorted_nil : Sorted []\n    | Sorted_cons a l : Sorted l -> HdRel a l -> Sorted (a :: l).\n\n  Lemma HdRel_inv : forall a b l, HdRel a (b :: l) -> R a b.\n  Proof.\n    inversion 1; auto.\n  Qed.\n\n  Lemma Sorted_inv :\n    forall a l, Sorted (a :: l) -> Sorted l /\\ HdRel a l.\n  Proof.\n    intros a l H; inversion H; auto.\n  Qed.\n\n  Lemma Sorted_rect :\n    forall P:list A -> Type,\n      P [] ->\n      (forall a l, Sorted l -> P l -> HdRel a l -> P (a :: l)) ->\n      forall l:list A, Sorted l -> P l.\n  Proof.\n    induction l; firstorder using Sorted_inv.\n  Qed.\n\n  Lemma Sorted_LocallySorted_iff : forall l, Sorted l <-> LocallySorted l.\n  Proof.\n    split; [induction 1 as [|a l [|]]| induction 1];\n      auto using Sorted, LocallySorted, HdRel.\n    inversion H1; subst; auto using LocallySorted.\n  Qed.\n\n  (** Strongly sorted: elements of the list are pairwise ordered *)\n\n  Inductive StronglySorted : list A -> Prop :=\n    | SSorted_nil : StronglySorted []\n    | SSorted_cons a l : StronglySorted l -> Forall (R a) l -> StronglySorted (a :: l).\n\n  Lemma StronglySorted_inv : forall a l, StronglySorted (a :: l) ->\n    StronglySorted l /\\ Forall (R a) l.\n  Proof.\n    intros; inversion H; auto.\n  Defined.\n\n  Lemma StronglySorted_rect :\n    forall P:list A -> Type,\n      P [] ->\n      (forall a l, StronglySorted l -> P l -> Forall (R a) l -> P (a :: l)) ->\n      forall l, StronglySorted l -> P l.\n  Proof.\n    induction l; firstorder using StronglySorted_inv.\n  Defined.\n\n  Lemma StronglySorted_rec :\n    forall P:list A -> Type,\n      P [] ->\n      (forall a l, StronglySorted l -> P l -> Forall (R a) l -> P (a :: l)) ->\n      forall l, StronglySorted l -> P l.\n  Proof.\n    firstorder using StronglySorted_rect.\n  Qed.\n\n  Lemma StronglySorted_Sorted : forall l, StronglySorted l -> Sorted l.\n  Proof.\n    induction 1 as [|? ? ? ? HForall]; constructor; trivial.\n    destruct HForall; constructor; trivial.\n  Qed.\n\n  Lemma Sorted_extends :\n    Transitive R -> forall a l, Sorted (a::l) -> Forall (R a) l.\n  Proof.\n    intros. change match a :: l with [] => True | a :: l => Forall (R a) l end.\n    induction H0 as [|? ? ? ? H1]; [trivial|].\n    destruct H1; constructor; trivial.\n    eapply Forall_impl; [|eassumption].\n    firstorder.\n  Qed.\n\n  Lemma Sorted_StronglySorted :\n    Transitive R -> forall l, Sorted l -> StronglySorted l.\n  Proof.\n    induction 2; constructor; trivial.\n    apply Sorted_extends; trivial.\n    constructor; trivial.\n  Qed.\n\nEnd defs.\n\nHint Constructors HdRel.\nHint Constructors Sorted.\n\n(* begin hide *)\n(* Compatibility with deprecated file Sorting.v *)\nNotation lelistA := HdRel (only parsing).\nNotation nil_leA := HdRel_nil (only parsing).\nNotation cons_leA := HdRel_cons (only parsing).\n\nNotation sort := Sorted (only parsing).\nNotation nil_sort := Sorted_nil (only parsing).\nNotation cons_sort := Sorted_cons (only parsing).\n\nNotation lelistA_inv := HdRel_inv (only parsing).\nNotation sort_inv := Sorted_inv (only parsing).\nNotation sort_rect := Sorted_rect (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/Sorting/Sorted.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.6721281467653798}}
{"text": "Require Import Coq.Classes.SetoidClass.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.Arith.Peano_dec.\nRequire Import NatList.\nRequire Import MyInductions.\nRequire Setoid.\n(*Require PeanoNat Le Gt Minus Bool Lt.*)\nRequire Init.Datatypes.\nRequire Import PartialMap.\n\n\nOpen Scope list_scope.\n\n\nModule ProgrammingWithPropositions.\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\nFixpoint In {A : Type} (x : A) (l : PartialMap.list A)  :=\n  match l with\n  | PartialMap.nil => False\n  | (PartialMap.cons x' l') => (x' = x) \\/ (In x l')\n  end.\n\nDefinition l := (PartialMap.cons 2 (PartialMap.cons 4 PartialMap.nil)).\n\nExample In_Example_1 : In 4 l.\nProof.\n  simpl.\n  right.\n  left.\n  reflexivity.\nQed.\n\nCheck l.\n\nExample In_example_2 : forall n, In n l -> 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 : PartialMap.list A) ( x : A),\n    In x l -> In (f x) (PartialMap.map f l).\nProof.\n  intros A B f l x.\n  induction l as [|x' l' IHl'].\n  - simpl. intros. assumption.\n  - simpl. intros [H | H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed.\n\nLemma In_map_iff : forall (A B : Type) ( f : A -> B) (l : PartialMap.list A) (y : B),\n    In y (PartialMap.map f l) <-> exists x, f x = y /\\ In x l.\nProof.\n  intros.\n  ", "meta": {"author": "NickFromNormandy", "repo": "ProofsWithCoq", "sha": "5c6c356bce4087b342106a172807bf4ae3dad493", "save_path": "github-repos/coq/NickFromNormandy-ProofsWithCoq", "path": "github-repos/coq/NickFromNormandy-ProofsWithCoq/ProofsWithCoq-5c6c356bce4087b342106a172807bf4ae3dad493/ProgrammingWithPropositions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.7853085909370423, "lm_q1q2_score": 0.67210725827671}}
{"text": "(**\nプログラミング Coq 証明駆動開発入門(1)\nhttp://www.iij-ii.co.jp/lab/techdoc/coqt/coqt8.html\n\nをSSReflectに書き直した。\nPermutation は SSReflect の相当の補題を使っているため、\n証明の詳細は原著と異なることに注意してください。\n*)\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Print All.\n\n(* Permutation, seq.v *)\nCheck perm_eq (1::2::3::nil) (2::1::3::nil).\nEval compute in perm_eq (1::2::3::nil) (2::1::3::nil). (* true *)\nEval compute in perm_eq nil nil.                       (* true *)\n\n(* ソート処理の定義 *)\nFixpoint insert (a : nat)(l : seq nat) : seq nat :=\n  match l with\n  | nil => a :: nil\n  | x :: xs => if leq a x then a :: l else x :: insert a xs\n  end.\n\nFixpoint insertion_sort (l : seq nat) : seq nat :=\n  match l with\n  | nil => nil\n  | x :: xs => insert x (insertion_sort xs)\n  end.\n\nEval compute in insert 1 nil.                      (* [:: 1] *)\nEval compute in insert 5 [:: 1; 4; 2; 9; 3].       (* [:: 1; 4; 2; 5; 9; 3] *)\nEval compute in insertion_sort [:: 2; 4; 1; 5; 3]. (* [:: 1; 2; 3; 4; 5] *)\n\n(* 証明 *)\nLemma perm_iff : forall (m n : seq nat),\n                   (forall l, perm_eq m l = perm_eq n l) <-> perm_eq m n.\nProof.\n  move=> m n.\n  split=> H.\n  - by rewrite H.\n  - by apply/perm_eqlP.\nQed.\n\nLemma perm_swap : forall (l l' : seq nat) (x a : nat),\n                    perm_eq [:: x, a & l] l' = perm_eq [:: a, x & l] l'.\nProof.\n  move=> l l' x a.\n  apply perm_iff.\n  Check cat1s.\n  rewrite -[[:: x, a & l]]cat1s.\n  rewrite -[[:: a & l]]cat1s.\n  rewrite -[[:: a, x & l]]cat1s.\n  rewrite -[[:: x & l]]cat1s.\n  apply/perm_eqlP.\n  by apply (perm_catCA [:: x] [:: a] l).\nQed.\n\nLemma insert_perm : forall (l : seq nat) (x : nat),\n                      perm_eq (x::l) (insert x l).\nProof.\n  elim=> [x | a l H x //=].\n  - by [].\n  - case: (x <= a) => [//= |].\n    + apply perm_iff => l'.\n      rewrite perm_swap.\n      apply perm_iff.\n      rewrite perm_cons.\n      by [].\nQed.\n\nTheorem isort_permutation : forall (l : seq nat), perm_eq l (insertion_sort l).\nProof.\n  elim=> [| a l H //=].\n  - by [].\n  - apply perm_eq_trans with (a :: insertion_sort l).\n    + by rewrite perm_cons.\n    + by apply insert_perm.\nQed.\n\n(*\nRequire Import path.\n\n(* Sorted, path.v *)\nCheck sorted : forall T : eqType, rel T -> seq T -> bool.\nCheck leq : nat -> nat -> bool.\nCheck leq : nat -> nat -> Prop.\nCheck leq : rel nat : Type.\nCheck le : nat -> nat -> Prop.\nFail Check le : nat -> nat -> bool.\nFail Check le : rel nat.                    (* rel : Type -> Type *)\n\nCheck sorted ltn (1::2::3::nil).\nCheck sorted leq (1::2::3::nil).\nEval compute in sorted leq (1::2::3::nil). (* true *)\nEval compute in sorted leq (3::nil).       (* true *)\nEval compute in sorted leq nil.            (* true *)\nEval compute in sorted leq (2::1::3::nil). (* false *)\n*)\n\nInductive LocallySorted (T : eqType) (R : rel T) : seq T -> Prop :=\n| LSorted_nil : LocallySorted R nil\n| LSorted_cons1 : forall a : T, LocallySorted R (a :: nil)\n| LSorted_consn : forall (a b : T) (l : seq T),\n                    LocallySorted R (b :: l) ->\n                    R a b -> LocallySorted R (a :: b :: l).\n\nCheck leq : nat -> nat -> bool.\nCheck leq : nat -> nat -> Prop.\nCheck leq : rel nat : Type.\nCheck le : nat -> nat -> Prop.\nFail Check le : nat -> nat -> bool.\nFail Check le : rel nat.                    (* rel : Type -> Type *)\nCheck LocallySorted leq (1::2::3::nil) : Prop.\nFail Check LocallySorted le (1::2::3::nil) : Prop.\n\nLemma complete_conv : forall n m : nat, leq m n = false -> leq n m.\nProof.\n  move=> n m.\n  move/negbT.    \n  rewrite -ltnNge => H.\n  by apply ltnW.\nQed.\n\nLemma insert_sorted : forall (a : nat) (l : seq nat),\n                        LocallySorted leq l -> LocallySorted leq (insert a l).\nProof.\n  move=> a.\n  elim=> [H //= | a0 l IHl H //=].\n  - by apply LSorted_cons1.\n  - case Heqb : (leq a a0).                 (* remember *)\n    + apply LSorted_consn.\n      * by apply H.\n      * by rewrite Heqb.\n    + inversion H.\n      * apply LSorted_consn.\n        apply LSorted_cons1.\n        by apply complete_conv.\n      * subst; simpl in *.\n        case H' : (leq a b).\n        - apply LSorted_consn.\n          + by rewrite H' in IHl; apply IHl. (* apply H2. *)\n          + by apply complete_conv.\n        - apply LSorted_consn.\n          + by rewrite H' in IHl; apply IHl. (* apply H2. *)\n          + by [].                           (* apply H3. *)\nQed.\n\nTheorem isort_sorted : forall (l : seq nat),\n                         LocallySorted leq (insertion_sort l).\nProof.\n  elim=> [| a l H //=].\n  - by apply LSorted_nil.\n  - by apply insert_sorted.\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/iii/ssr_isort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.7853085834000791, "lm_q1q2_score": 0.6721072576008973}}
{"text": "(** Support for atoms, i.e., objects with decidable equality.  We\n    provide here the ability to generate an atom fresh for any finite\n    collection, i.e., the lemma [atom_fresh_for_set].\n\n    Original authors: Arthur Chargueraud and Brian Aydemir.\n*)\n\nRequire Import List.\nRequire Import Max.\nRequire Import Le.\nRequire Peano_dec.\n\n(* ********************************************************************** *)\n(** * Definition *)\n\n(** Atoms are structureless objects such that we can always generate\n    one fresh from a finite collection.  Equality on atoms is [eq] and\n    decidable.  We use Coq's module system to make abstract the\n    implementation of atoms.  The [Export AtomImpl] line below allows\n    us to refer to the type [atom] and its properties without having\n    to qualify everything with \"[AtomImpl.]\". *)\n\nModule Type ATOM.\n\n  Parameter atom : Set.\n\n  Parameter atom_fresh_for_list :\n    forall (xs : list atom), {x : atom | ~ List.In x xs}.\n\n  Parameter eq_atom_dec : forall x y : atom, {x = y} + {x <> y}.\n\nEnd ATOM.\n\n(** The implementation of the above interface is hidden for\n    documentation purposes. *)\n\nModule AtomImpl : ATOM.\n\n  (* begin hide *)\n\n  Definition atom := nat.\n\n  Lemma max_lt_r : forall x y z,\n    x <= z -> x <= max y z.\n  Proof.\n    intros. apply le_trans with (1:=H). apply le_max_r.\n  Qed.\n\n  Lemma nat_list_max : forall (xs : list nat),\n    { n : nat | forall x, In x xs -> x <= n }.\n  Proof.\n    induction xs as [ | x xs [y H] ].\n    (* case: nil *)\n    exists 0. inversion 1.\n    (* case: cons x xs *)\n    exists (max x y). intros z J. simpl in J. destruct J as [K | K].\n      subst. apply le_max_l.\n      apply max_lt_r. auto.\n  Qed.\n\n  Lemma atom_fresh_for_list :\n    forall (xs : list nat), { n : nat | ~ List.In n xs }.\n  Proof.\n    intros xs. destruct (nat_list_max xs) as [x H].\n    exists (S x). intros J. specialize (H (S x) J).\n    apply n_Sn with (n:=x).\n    apply le_antisym. apply le_n_Sn. assumption.\n  Qed.\n\n  Definition eq_atom_dec := Peano_dec.eq_nat_dec.\n\n  (* end hide *)\n\nEnd AtomImpl.\n\nExport AtomImpl.\n\n", "meta": {"author": "tbelaire", "repo": "FJ-Formalization", "sha": "3ba3f992665d4a3639cb5a13c271039a37871d50", "save_path": "github-repos/coq/tbelaire-FJ-Formalization", "path": "github-repos/coq/tbelaire-FJ-Formalization/FJ-Formalization-3ba3f992665d4a3639cb5a13c271039a37871d50/Atom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973932, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6721072540377314}}
{"text": "Load FJ_tactics.\nRequire Import List.\nRequire Import FunctionalExtensionality.\n\nSection Folds.\n  \n  (* ============================================== *)\n  (* ALGEBRAS AND FOLDS                             *)\n  (* ============================================== *)\n\n  (* Ordinary Algebra *)\n  Definition Algebra (F: Set -> Set) (A : Set) :=\n    F A -> A.\n\n  (* Mixin Algebra *)\n  Definition Mixin (T: Set) (F: Set -> Set) (A : Set) :=\n    (T -> A) -> F T -> A.\n\n  (* Mendler Algebra *)\n  Definition MAlgebra (F: Set -> Set) (A : Set) :=\n    forall (R : Set), Mixin R F A.\n\n   Definition Fix (F : Set -> Set) : Set := \n    forall (A : Set), MAlgebra F A -> A.\n\n  Definition mfold {F : Set -> Set} : forall {A : Set}\n    (f : MAlgebra F A), Fix F -> A:= fun A f e => e A f.\n\n  Class Functor (F : Set -> Set) :=\n    {fmap : \n      forall {A B : Set} (f : A -> B), F A -> F B;\n      fmap_fusion : \n        forall (A B C: Set) (f : A -> B) (g : B -> C) (a : F A),\n          fmap g (fmap f a) = fmap (fun e => g (f e)) a;\n      fmap_id : \n        forall (A : Set) (a : F A),\n          fmap (@id A) a = a\n    }.\n\n  Definition in_t {F} : F (Fix F) -> Fix F :=\n    fun F_e A f => f _ (mfold _ f) F_e.\n  \n  Definition fold_ {F : Set -> Set} {functor : Functor F} : \n    forall (A : Set) (f : Algebra F A), Fix F -> A :=\n      fun A f e => mfold _ (fun r rec fa => f (fmap rec fa)) e.  \n\n  Definition out_t {F : Set -> Set} {fun_F : Functor F} : Fix F -> F (Fix F) :=\n    @fold_ F fun_F _ (fmap in_t).\n  \n  Fixpoint boundedFix {A: Set} \n    {Exp: Set -> Set} \n    {fun_F: Functor Exp} \n    (n : nat) \n    (fM: Mixin (Fix Exp) Exp A) \n    (default: A) \n    (e: Fix Exp): A :=\n    match n with\n      | 0   => default \n      | S n => fM (boundedFix n fM default) (out_t e)\n    end.\n\n    (* Indexed Algebra *)\n  Definition iAlgebra {I : Set} (F : (I -> Prop) -> I -> Prop) (A : I -> Prop) :=\n    forall i, F A i -> A i.\n  \n    (* Indexed Mendler Algebra *)\n  Definition iMAlgebra {I : Set} (F : (I -> Prop) -> I -> Prop) (A : I -> Prop) :=\n    forall i (R : I -> Prop), (forall i, R i -> A i) -> F R i -> A i.\n  \n  Definition iFix {I : Set} (F : (I -> Prop) -> I -> Prop) (i : I) : Prop :=\n    forall (A : I -> Prop), iMAlgebra F A -> A i.\n  \n  Definition imfold {I : Set} (F : (I -> Prop) -> I -> Prop) : \n    forall {A : I -> Prop} (f : iMAlgebra F A) {i : I},\n      iFix F i -> A i := fun A f i e => e A f.\n  \n  Class iFunctor {I : Set} (F : (I -> Prop) -> I -> Prop) :=\n    {ifmap : \n      forall {A B : I -> Prop} i (f : forall i, A i -> B i), F A i -> F B i;\n      ifmap_fusion : \n        forall (A B C: I -> Prop) i (f : forall i, A i -> B i) (g : forall i, B i -> C i) (a : F A i),\n          ifmap i g (ifmap i f a) = ifmap i (fun i e => g _ (f i e)) a;\n      ifmap_id : \n        forall (A : I -> Prop) i (a : F A i),\n          ifmap i (fun _ => id) a = a\n    }.\n\n  Definition in_ti {I : Set} {F} : forall i : I, F (iFix F) i -> iFix F i :=\n    fun i F_e A f => f _ _ (imfold _ _ f) F_e.\n  \n  Definition ifold_ {I : Set} (F : (I -> Prop) -> I -> Prop) {iFun_F : iFunctor F} : \n    forall {A : I -> Prop} (f : iAlgebra F A) {i : I},\n      iFix F i -> A i := fun A f i e => imfold _ _ (fun i' r rec fa => f i' (ifmap i' rec fa)) i e.\n\n  Definition out_ti {I : Set} {F} {fun_F : iFunctor F} : forall i : I, iFix F i -> F (iFix F) i :=\n    @ifold_ I F fun_F _ (fun i => ifmap i in_ti).\n  \n  (* Universal Property of Mendler Folds *)\n\n  Lemma Universal_Property (F : Set -> Set) (A : Set)\n    (f : MAlgebra F A) : \n      forall (h : Fix F -> A), \n        h = mfold _ f -> forall e, h (in_t e) = f _ h e.\n  Proof.\n    intros; rewrite H. unfold in_t. unfold mfold.\n    reflexivity.\n  Qed.\n\n  Class Universal_Property' {F} {Fun_F : Functor F} (e : Fix F) :=\n    {E_UP' : forall (A : Set) (f : MAlgebra F A)\n      (h : Fix F -> A), \n      (forall e, h (in_t e) = f _ h e) -> \n      h e = mfold _ f e}. \n\n  Lemma Fix_id F {fun_F : Functor F} e {UP' : Universal_Property' e} : \n    mfold _ (fun _ rec x => in_t (fmap rec x)) e = e.\n  Proof.\n    intros; apply sym_eq.    \n    fold (id e); unfold id at 2; apply (E_UP'); intros.\n    unfold id.\n    unfold in_t.\n    eapply (@functional_extensionality_dep Set).\n    intros; eapply @functional_extensionality_dep; intros.\n    rewrite fmap_id.\n    reflexivity.\n  Defined.\n \n  Definition MAlg_to_Alg {F : Set -> Set} {A : Set} :\n    MAlgebra F A -> Algebra F A := fun MAlg f => MAlg A id f.\n\n  (* Universal Property of regular folds. *)\n\n  Lemma Universal_Property_fold (F : Set -> Set) {fun_F : Functor F} (B : Set)\n    (f : Algebra F B) : forall (h : Fix F -> B), h = fold_ _ f -> \n      forall e, h (in_t e) = f (fmap h e).\n    intros; rewrite H; reflexivity.\n  Qed.\n    \n  Class Universal_Property'_fold {F} {fun_F : Functor F} (e : Fix F) :=\n    {E_fUP' : forall (B : Set) (f : Algebra F B) (h : Fix F -> B), \n      (forall e, h (in_t e) = f (fmap h e)) -> \n      h e = fold_ _ f e\n    }.\n    \n  Lemma Fix_id_fold F {fun_F : Functor F} e {UP' : Universal_Property'_fold e} : \n    fold_ _ (@in_t F) e = e.\n    intros; apply sym_eq.\n    fold (id e); unfold id at 2; apply (E_fUP'); intros.\n    rewrite fmap_id.\n    unfold id.\n    reflexivity.\n  Qed.\n\n  Lemma Fusion F {fun_F : Functor F} e {e_UP' : Universal_Property'_fold e} : \n    forall (A B : Set) (h : A -> B) (f : Algebra F A) (g : Algebra F B), \n      (forall a, h (f a) = g (fmap h a)) -> \n      (fun e' => h (fold_ _ f e')) e = fold_ _ g e.\n    intros; eapply E_fUP'; try eassumption; intros.\n    rewrite (Universal_Property_fold F _ f _ (refl_equal _)).\n    rewrite H.\n    rewrite fmap_fusion; reflexivity.\n  Qed.\n  \n  Lemma in_out_inverse : forall (F : Set -> Set) (Fun_F : Functor F) (e : Fix F)\n    {fUP' : Universal_Property'_fold e},\n    in_t (out_t e) = e.\n    intros.\n    rewrite <- (@Fix_id_fold _ _ e fUP') at -1.\n    eapply E_fUP' with (h := fun e => in_t (out_t e)).\n    intro.\n    cut (out_t (in_t e0) = fmap (fun e1 => in_t (out_t e1)) e0); intros.\n    rewrite H; reflexivity.\n    unfold out_t. \n    rewrite Universal_Property with (f := (fun (R : Set) (rec : R -> F (Fix F)) (fp : F R) =>\n      fmap (fun r : R => in_t (rec r)) fp)); eauto.\n    unfold fold_; unfold mfold.\n    eapply functional_extensionality; intro.\n    cut ((fun (r : Set) (rec : r -> F (Fix F)) (fa : F r) =>\n      fmap in_t (fmap rec fa)) = \n      fun (R : Set) (rec : R -> F (Fix F)) (fp : F R) =>\n      fmap (fun r : R => in_t (rec r)) fp).\n    intro; rewrite H; reflexivity.\n    eapply (@functional_extensionality_dep Set); intro.\n    eapply functional_extensionality_dep; intro.\n    eapply functional_extensionality_dep; intro.\n    rewrite fmap_fusion; reflexivity.\n  Qed.\n\n  Definition in_t_UP' : forall (F : Set -> Set) \n    (Fun_F : Functor F),\n    F (sig (@Universal_Property'_fold F Fun_F)) -> \n    sig (@Universal_Property'_fold F Fun_F).\n    intros F Fun_F e.\n    intros; constructor 1 with (x := in_t (fmap (@proj1_sig _ _) e)).\n    constructor; intros.\n    rewrite H.\n    unfold fold_, mfold.\n    unfold in_t.\n    repeat rewrite fmap_fusion.\n    assert ((fun e0 : sig Universal_Property'_fold => h (proj1_sig e0)) =\n      (fun e0 : sig Universal_Property'_fold =>\n         mfold B (fun (r : Set) (rec : r -> B) (fa : F r) => f (fmap rec fa))\n           (proj1_sig e0))) by \n    (eapply @functional_extensionality_dep; intros e'; destruct e' as [e' e'_UP'];\n      simpl; eapply E_fUP'; eauto).\n    rewrite H0; reflexivity.\n  Defined.\n\n  Definition out_t_UP' : \n    forall (F : Set -> Set) \n      (Fun_F : Functor F) \n      (e : Fix F),\n      F (sig (@Universal_Property'_fold F Fun_F)).\n    intros.\n    eapply fold_; try assumption.\n    unfold Algebra; intros.\n    eapply fmap.\n    apply in_t_UP'.\n    assumption.\n  Defined.\n  \n  Lemma out_in_inverse : forall (F : Set -> Set) \n    (Fun_F : Functor F) \n    (e : F (sig (@Universal_Property'_fold F Fun_F))),\n    out_t (in_t (fmap (@proj1_sig _ _) e)) = fmap (@proj1_sig _ _) e.\n    intros.\n    unfold out_t. \n    erewrite Universal_Property_fold; try reflexivity.\n    rewrite fmap_fusion.\n    rewrite fmap_fusion.\n    assert ((fun e0 : sig Universal_Property'_fold =>\n      in_t (fold_ (F (Fix F)) (fmap in_t) (proj1_sig e0))) = \n    @proj1_sig _ _) by \n    (eapply functional_extensionality; intros;\n      fold (out_t (proj1_sig x));\n        rewrite in_out_inverse; destruct x; simpl; eauto).\n    rewrite H; reflexivity.\n  Qed.\n\n  Lemma in_t_UP'_inject : forall (F : Set -> Set) \n    (Fun_F : Functor F) \n    (e e' : F (sig (@Universal_Property'_fold F Fun_F))),\n    in_t (fmap (@proj1_sig _ _) e) = in_t (fmap (@proj1_sig _ _) e') -> \n    fmap (@proj1_sig _ _) e = fmap (@proj1_sig _ _) e'.\n    intros; apply (f_equal out_t) in H; \n      repeat rewrite out_in_inverse in H; eauto.\n  Qed.\n\n  Lemma in_out_UP'_inverse : forall (H : Set -> Set)\n    (Fun_H : Functor H)\n    (h : Fix H),\n    Universal_Property'_fold h -> \n    proj1_sig (in_t_UP' H Fun_H (out_t_UP' H Fun_H h)) = h.\n    intros; simpl.\n    assert ((fmap (@proj1_sig _ _) (out_t_UP' H Fun_H h)) = out_t h).\n    unfold out_t.\n    eapply E_fUP' with (h0 := fun e => fmap (@proj1_sig _ _) (out_t_UP' H Fun_H e)).\n    intros.\n    rewrite fmap_fusion.\n    assert (out_t_UP' H Fun_H (in_t e) = \n      fmap (fun e => in_t_UP' _ _ (out_t_UP' _ _ e)) e).\n    unfold out_t_UP' at 1.\n    erewrite Universal_Property_fold with \n      (f := (fun H2 : H (H (sig Universal_Property'_fold)) =>\n        fmap (in_t_UP' H Fun_H) H2)) (fun_F := Fun_H); eauto.\n    rewrite fmap_fusion; reflexivity.\n    rewrite H1; rewrite fmap_fusion; simpl; reflexivity.\n    rewrite H1.\n    rewrite in_out_inverse; unfold mfold; eauto.\n  Qed.\n    \n  Lemma out_in_fmap : forall (F : Set -> Set)\n    (Fun_F : Functor F)\n    (e : F (Fix F)),\n    out_t_UP' F _ (in_t e) = \n    fmap (fun e => in_t_UP' _ _ (out_t_UP' _ _ e)) e.\n    intros; unfold out_t_UP' at 1.\n    erewrite Universal_Property_fold with \n    (f := (fun H2 : F (F (sig Universal_Property'_fold)) =>\n      fmap (in_t_UP' F Fun_F) H2)) (fun_F := Fun_F); eauto.\n    rewrite fmap_fusion; reflexivity.\n  Qed. \n\n  Definition UP'_P {F : Set -> Set} {Fun_F : Functor F} \n    (P : forall e : Fix F, Universal_Property'_fold e -> Prop) (e : Fix F) := \n    sigT (P e).\n\n  Definition UP'_P2 {F F' : Set -> Set}\n    {Fun_F : Functor F} {Fun_F' : Functor F'}\n    (P : forall e : (Fix F) * (Fix F'), \n      Universal_Property'_fold (fst e) /\\ Universal_Property'_fold (snd e) -> Prop)\n    (e : (Fix F) * (Fix F')) := sig (P e).\n\n  Definition UP'_F (F : Set -> Set) {Fun_F : Functor F} := \n    sig (Universal_Property'_fold (F := F)).\n\n  Fixpoint boundedFix_UP {A: Set} \n    {Exp: Set -> Set} \n    {fun_F: Functor Exp} \n    (n : nat) \n    (fM: Mixin (UP'_F Exp) Exp A) \n    (default: A) \n    (e: UP'_F Exp): A :=\n    match n with\n      | 0   => default \n      | S n => fM (boundedFix_UP n fM default) (out_t_UP' _ _ (proj1_sig e))\n    end.\n\n  Lemma bF_UP_in_out : forall {A: Set} \n    {Exp: Set -> Set} \n    {fun_F: Functor Exp} \n    (n : nat) \n    (fM: Mixin (UP'_F Exp) Exp A) \n    (default: A) \n    (e: Fix Exp) \n    (e_UP' : Universal_Property'_fold e),\n    boundedFix_UP n fM default (in_t_UP' _ _ (out_t_UP' _ _ e)) = \n    boundedFix_UP n fM default (exist _ e e_UP').\n  Proof.\n    induction n; simpl; intros; eauto.\n    generalize in_out_UP'_inverse as H0; intro; simpl in H0; rewrite H0; auto.\n  Qed.\n\n  (* ============================================== *)\n  (* FUNCTOR COMPOSITION                            *)\n  (* ============================================== *)\n\n  Definition inj_Functor {F G : Set -> Set} {A : Set} : Set := sum (F A) (G A).\n\n  Notation \"A :+: B\"  := (@inj_Functor A B) (at level 80, right associativity).\n\n  Global Instance Functor_Plus G H {fun_G : Functor G} {fun_H : Functor H} : Functor (G :+: H).\n    econstructor 1 with (fmap := \n      fun (A B : Set) (f : A -> B) (a : (G :+: H) A) =>\n        match a with \n          | inl G' => inl _ (fmap f G')\n          | inr H' => inr _ (fmap f H')\n        end).\n    (* fmap_fusion *)\n    intros; destruct a; \n    rewrite fmap_fusion; reflexivity.\n    (* fmap_id *)\n    intros; destruct a;\n    rewrite fmap_id; reflexivity.\n  Defined.\n\n  Class Sub_Functor (sub_F sub_G : Set -> Set) : Set := \n    { inj : forall {A : Set}, sub_F A -> sub_G A;\n      prj : forall {A : Set}, sub_G A -> option (sub_F A);\n      inj_prj : forall {A : Set} (ga : sub_G A) (fa : sub_F A), \n        prj ga = Some fa -> ga = inj fa;\n      prj_inj : forall {A : Set} (fa : sub_F A), \n        prj (inj fa) = Some fa\n    }.\n\n  Notation \"A :<: B\"  := (Sub_Functor A B) (at level 80, right associativity).\n  \n  (* Need the 'Global' modifier so that the instance survives the Section.*)\n  Global Instance Sub_Functor_inl (F G H : Set -> Set) (sub_F_G : F :<: G) : \n    F :<: (G :+: H) := \n    {| inj :=  (fun (A : Set) (e : F A) => inl _ (@inj F G sub_F_G _ e));\n       prj := fun (A: Set) (e : (G :+: H) A) =>\n        match e with\n         | inl e' => prj e'\n         | inr _  => None\n        end  \n     |}.\n    intros; destruct ga; [rewrite (inj_prj _ _ H0); reflexivity | discriminate].\n    intros; simpl; rewrite prj_inj; reflexivity.\n  Defined.\n  \n  Global Instance Sub_Functor_inr (F G H : Set -> Set) (sub_F_H : F :<: H) :\n    F :<: (G :+: H) :=\n    {| inj := fun (A : Set) (e : F A) => inr _ (@inj F H sub_F_H _ e);\n       prj := fun (A : Set) (e : (G :+: H) A) =>\n        match e with\n         | inl _  => None\n         | inr e' => prj e'\n        end\n     |}.\n    intros; destruct ga; [discriminate | rewrite (inj_prj _ _ H0); reflexivity ].\n    intros; simpl; rewrite prj_inj; reflexivity.\n  Defined.\n  \n  Global Instance Sub_Functor_id {F : Set -> Set} : F :<: F :=\n    {| inj := fun A => @id (F A);\n       prj := fun A => @Some (F A) |}.\n    unfold id; congruence.\n    reflexivity.\n  Defined.\n\n  (* ============================================== *)\n  (* WELL-FORMEDNESS OF FUNCTORS                    *)\n  (* ============================================== *)\n    \n  Class WF_Functor (F G: Set -> Set)\n    (subfg: F :<: G)\n    (Fun_F: Functor F)\n    (Fun_G: Functor G): Set :=\n    { wf_functor :\n      forall (A B : Set) (f : A -> B) (fa: F A) ,\n        fmap f (inj fa) (F := G) = inj (fmap f fa) }.\n  \n  Global Instance WF_Functor_id {F : Set -> Set} {Fun_F : Functor F} :\n    WF_Functor F F Sub_Functor_id _ _.\n    econstructor; intros; reflexivity.\n  Defined.\n    \n  Global Instance WF_Functor_plus_inl {F G H : Set -> Set} \n    {Fun_F : Functor F}\n    {Fun_G : Functor G} \n    {Fun_H : Functor H} \n    {subfg : F :<: G} \n    {WF_Fun_F : WF_Functor F _ subfg Fun_F Fun_G} \n    :\n    WF_Functor F (G :+: H) (Sub_Functor_inl F G H _ ) _ (Functor_Plus G H).\n    econstructor; intros. \n    simpl; rewrite wf_functor; reflexivity.\n  Defined.\n    \n  Global Instance WF_Functor_plus_inr {F G H : Set -> Set} \n    {Fun_F : Functor F}\n    {Fun_G : Functor G} \n    {Fun_H : Functor H} \n    {subfh : F :<: H} \n    {WF_Fun_F : WF_Functor F _ subfh Fun_F Fun_H} \n    :\n    WF_Functor F (G :+: H) (Sub_Functor_inr F G H _ ) _ (Functor_Plus G H).\n    econstructor; intros. \n    simpl; rewrite wf_functor; reflexivity.\n  Defined.\n\n  (* ============================================== *)\n  (* INJECTION + PROJECTION                         *)\n  (* ============================================== *)\n  \n  \n  Definition inject' {F G: Set -> Set} {Fun_F : Functor F} {subGF: G :<: F} : \n    G (sig (@Universal_Property'_fold F Fun_F)) -> (sig (@Universal_Property'_fold F Fun_F)) :=\n    fun gexp => in_t_UP' _ _ (inj gexp).\n\n  Definition inject {F G: Set -> Set} {Fun_F : Functor F} {subGF: G :<: F} : \n    G (sig (@Universal_Property'_fold F Fun_F)) -> Fix F :=\n      fun gexp => proj1_sig (in_t_UP' _ _ (inj gexp)).\n\n  Definition project {F G: Set -> Set} {Fun_F: Functor F} {subGF : G :<: F } : \n    Fix F -> option (G (sig (@Universal_Property'_fold F Fun_F))) :=\n      fun exp => prj (out_t_UP' _ _ exp).\n\n  Lemma project_inject : forall (G H : Set -> Set)\n    (Fun_G : Functor G)\n    (Fun_H : Functor H)\n    (sub_G_H : G :<: H)\n    (h : Fix H) (g : G (sig (@Universal_Property'_fold H Fun_H))),\n    Universal_Property'_fold h -> \n    project h = Some g -> h = inject g.\n    intros.\n    apply inj_prj in H1.\n    unfold inject; rewrite <- H1.\n    erewrite in_out_UP'_inverse; eauto.\n  Qed.\n\n  Lemma inject_project : forall (F G  : Set -> Set)\n    (Fun_F : Functor F)\n    (Fun_G : Functor G)\n    (sub_G_F : G :<: F)\n    (g : G (sig (@Universal_Property'_fold F Fun_F))),\n    fmap (@proj1_sig _ _) (out_t_UP' _ _ (inject g)) = \n    (fmap (@proj1_sig _ _) (inj g)).\n    unfold inject; intros; simpl.\n    rewrite out_in_fmap.\n    rewrite fmap_fusion.\n    assert (forall e : sig Universal_Property'_fold,\n      proj1_sig (in_t_UP' F Fun_F (out_t_UP' F Fun_F (proj1_sig e))) = proj1_sig e).\n    intros; eapply in_out_UP'_inverse.\n    intros; destruct e as [e e_UP']; eassumption.\n    rewrite fmap_fusion.\n    rewrite (functional_extensionality _ _ H).\n    reflexivity.\n  Qed.\n\n  Class Distinct_Sub_Functor {F G H : Set -> Set} \n    (Fun_H : Functor H)\n    (sub_F_H : F :<: H) \n    (sub_G_H : G :<: H)\n    : Set := \n    {inj_discriminate : forall A f g, \n      inj (Sub_Functor := sub_F_H) (A := A) f <> inj (Sub_Functor := sub_G_H) (A := A) g}.\n  \n  Global Instance Distinct_Sub_Functor_plus \n    (F G H I : Set -> Set) \n    (Fun_G : Functor G)\n    (Fun_I : Functor I)\n    (sub_F_G : F :<: G)\n    (sub_H_I : H :<: I)\n    : \n    @Distinct_Sub_Functor F H (G :+: I) _ _ _.\n    econstructor; intros.\n    unfold not; simpl; unfold id; intros.\n    discriminate.\n  Defined.\n\n  Global Instance Distinct_Sub_Functor_plus'\n    (F G H I : Set -> Set) \n    (Fun_G : Functor G)\n    (Fun_I : Functor I)\n    (sub_F_G : F :<: G)\n    (sub_H_I : H :<: I)\n    : \n    @Distinct_Sub_Functor F H (I :+: G) _ _ _.\n    econstructor; intros.\n    unfold not; simpl; unfold id; intros.\n    discriminate.\n  Defined.\n\n  Global Instance Distinct_Sub_Functor_inl\n    (F G H I : Set -> Set) \n    (Fun_G : Functor G)\n    (Fun_I : Functor I)\n    (sub_F_G : F :<: G)\n    (sub_H_G : H :<: G)\n    (Dist_inl : @Distinct_Sub_Functor F H G Fun_G sub_F_G sub_H_G)\n    : \n    @Distinct_Sub_Functor F H (G :+: I) _ _ _.\n    econstructor; intros.\n    unfold not; intros.\n    simpl in H0; injection H0; intros.\n    eapply (inj_discriminate (Distinct_Sub_Functor := Dist_inl) _ f g H1).\n  Defined.\n\n  Global Instance Distinct_Sub_Functor_inr\n    (F G H I : Set -> Set) \n    (Fun_G : Functor G)\n    (Fun_I : Functor I)\n    (sub_F_G : F :<: G)\n    (sub_H_G : H :<: G)\n    (Dist_inl : @Distinct_Sub_Functor F H G Fun_G sub_F_G sub_H_G)\n    : \n    @Distinct_Sub_Functor F H (I :+: G) _ _ _.\n    econstructor; intros.\n    unfold not; intros.\n    simpl in H0; injection H0; intros.\n    eapply (inj_discriminate (Distinct_Sub_Functor := Dist_inl) _ f g H1).\n  Defined.\n\n  Lemma inject_discriminate : forall {F G H : Set -> Set} \n    {Fun_F : Functor F}\n    {Fun_G : Functor G}\n    {Fun_H : Functor H}\n    {sub_F_H : F :<: H}\n    {sub_G_H : G :<: H}\n    {WF_F : WF_Functor _ _ sub_F_H Fun_F Fun_H} \n    {WF_G : WF_Functor _ _ sub_G_H Fun_G Fun_H}, \n    Distinct_Sub_Functor Fun_H sub_F_H sub_G_H -> \n    forall f g, inject (subGF := sub_F_H) f <> inject (subGF := sub_G_H) g.\n    unfold inject; simpl; intros.\n    unfold not; intros H3; apply in_t_UP'_inject in H3.\n    repeat rewrite wf_functor in H3.\n    eapply (inj_discriminate _ _ _ H3).\n  Qed.\n\n  (* ============================================== *)\n  (* INDEXED FUNCTOR COMPOSITION                    *)\n  (* ============================================== *)\n\n  Definition inj_iFunctor {I : Set} {F G : (I -> Prop) -> I -> Prop} {A : I -> Prop} : I -> Prop := \n    fun i => or (F A i) (G A i).\n\n  Notation \"A ::+:: B\"  := (@inj_iFunctor _ A B) (at level 80, right associativity).\n\n  Global Instance iFunctor_Plus {I : Set} (G H : (I -> Prop) -> I -> Prop) \n    {fun_G : iFunctor G} {fun_H : iFunctor H} : iFunctor (G ::+:: H).\n    econstructor 1 with (ifmap :=\n      fun (A B : I -> Prop) (i : I) (f : forall i, A i -> B i) (a : (G ::+:: H) A i) =>\n        match a with \n          | or_introl G' => or_introl _ (ifmap i f G')\n          | or_intror H' => or_intror _ (ifmap i f H')\n        end).\n    (* ifmap_fusion *)\n    intros; destruct a; \n    rewrite ifmap_fusion; reflexivity.\n    (* ifmap_id *)\n    intros; destruct a;\n    rewrite ifmap_id; reflexivity.\n  Defined.\n\n  Class Sub_iFunctor {I : Set} (sub_F sub_G : (I -> Prop) -> I -> Prop) : Prop := \n    { inj_i : forall {A : I -> Prop} i, sub_F A i -> sub_G A i;\n         prj_i : forall {A : I -> Prop} i, sub_G A i -> (sub_F A i) \\/ True\n    }.\n\n  Notation \"A ::<:: B\"  := (Sub_iFunctor A B) (at level 80, right associativity).\n  \n  (* Need the 'Global' modifier so that the instance survives the Section.*)\n\n  Global Instance Sub_iFunctor_inl {I' : Set} (F G H : (I' -> Prop) -> I' -> Prop) (sub_F_G : F ::<:: G) : \n    F ::<:: (G ::+:: H) := \n    {| inj_i :=  (fun (A : I' -> Prop) i (e : F A i) => \n      or_introl _ (@inj_i _ F G sub_F_G _ _ e));\n    prj_i := fun (A: I' -> Prop) i (e : (G ::+:: H) A i) =>\n      match e with\n        | or_introl e' => prj_i _ e'\n        | or_intror _  => or_intror _ I\n      end  \n    |}.\n  \n  Global Instance Sub_iFunctor_inr {I' : Set} (F G H : (I' -> Prop) -> I' -> Prop) (sub_F_H : F ::<:: H) : \n    F ::<:: (G ::+:: H) := \n    {| inj_i :=  (fun (A : I' -> Prop) i (e : F A i) => \n      or_intror _ (@inj_i _ F H sub_F_H _ _ e));\n    prj_i := fun (A: I' -> Prop) i (e : (G ::+:: H) A i) =>\n      match e with\n        | or_intror e' => prj_i _ e'\n        | or_introl _  => or_intror _ I\n      end  \n    |}.\n  \n  Global Instance Sub_iFunctor_id {I : Set} {F : (I -> Prop) -> I -> Prop} : F ::<:: F :=\n    {| inj_i := fun A i e => e;\n       prj_i := fun A i e => or_introl _ e |}.\n  \n  Definition inject_i {I : Set} {F G: (I -> Prop) -> I -> Prop} {subGF: Sub_iFunctor G F} : \n    forall i, G (iFix F) i -> iFix F i:=\n    fun i gexp => in_ti i (inj_i i gexp).\n  \n  Definition project_i {I : Set} {F G: (I -> Prop) -> I -> Prop} \n    {fun_F: iFunctor F}\n    {subGF: Sub_iFunctor G F} : \n    forall i, iFix F i -> (G (iFix F) i) \\/ True :=\n      fun i fexp => prj_i i (out_ti i fexp).\n  \nEnd Folds.\n\nNotation \"A :+: B\"  := (@inj_Functor A B) (at level 80, right associativity).\nNotation \"A :<: B\"  := (Sub_Functor A B) (at level 80, right associativity).\nNotation \"A ::+:: B\"  := (@inj_iFunctor _ A B) (at level 80, right associativity).\nNotation \"A ::<:: B\"  := (Sub_iFunctor _ A B) (at level 80, right associativity).\n\nDefinition inj'' {F G : Set -> Set} (sub_F_G: F :<: G) {A : Set} := @inj F G sub_F_G A.\n\nSection FAlgebra.\n\n  (* ============================================== *)\n  (* OPERATIONS INFRASTRUCTURE                      *)\n  (* ============================================== *)\n\n  Class FAlgebra (Name : Set) (T: Set) (A: Set) (F: Set -> Set) : Set :=\n    { f_algebra : Mixin T F A }.\n\n  (* Definition FAlgebra_Plus (Name: Set) (T: Set) (A : Set) (F G : Set -> Set)\n    {falg: FAlgebra Name T A F} {galg: FAlgebra Name T A G} :\n    FAlgebra Name T A (F :+: G) := \n    Build_FAlgebra Name T A _ \n    (fun f fga =>\n      (match fga with\n         | inl fa => f_algebra f fa\n         | inr ga => f_algebra f ga\n       end)). *)\n\n  Global Instance FAlgebra_Plus (Name: Set) (T: Set) (A : Set) (F G : Set -> Set)\n    {falg: FAlgebra Name T A F} {galg: FAlgebra Name T A G} :\n    FAlgebra Name T A (F :+: G) | 6 :=\n    {| f_algebra := fun f fga=>\n         (match fga with\n           | inl fa => f_algebra f fa\n           | inr ga => f_algebra f ga\n          end) |}.\n\n  (* The | 6 gives the generated Hint a priority of 6. If this is\n     less than that of other instances for FAlgebra, the \n     typeclass inference algorithm will loop. \n     *)\n\n  Class WF_FAlgebra (Name T A: Set) (F G: Set -> Set)\n    (subfg: F :<: G)\n    (falg: FAlgebra Name T A F)\n    (galg: FAlgebra Name T A G): Set :=\n    { wf_algebra :\n      forall rec (fa: F T),\n        @f_algebra Name T A G galg rec (@inj F G subfg T fa) = @f_algebra Name T A F falg rec fa }.\n\n  Global Instance WF_FAlgebra_id {Name T A : Set} {F} {falg: FAlgebra Name T A F}:\n    WF_FAlgebra Name T A F F Sub_Functor_id falg falg.\n      econstructor. intros. \n      unfold inj.\n      unfold Sub_Functor_id.\n      unfold id.\n      reflexivity.\n  Defined.  \n\n  Global Instance WF_FAlgebra_inl\n    {Name A T : Set}\n    {F G H} \n    {falg: FAlgebra Name T A F}\n    {galg: FAlgebra Name T A G}\n    {halg: FAlgebra Name T A H}\n    {sub_F_G: F :<: G}\n    {wf_F_G: WF_FAlgebra Name T A F G sub_F_G falg galg}\n    : \n    WF_FAlgebra Name T A F (G :+: H) (Sub_Functor_inl F G H sub_F_G) falg (@FAlgebra_Plus Name T A G H galg halg). \n      econstructor. intros.\n      unfold inj. unfold Sub_Functor_inl.\n      simpl.\n      rewrite (wf_algebra rec fa).\n      reflexivity.\n  Defined.  \n\n  Global Instance WF_FAlgebra_inr\n    {Name T A : Set}\n    {F G H}\n    {falg: FAlgebra Name T A F}\n    {galg: FAlgebra Name T A G}\n    {halg: FAlgebra Name T A H}\n    {sub_F_H: F :<: H}\n    {wf_G_H: WF_FAlgebra Name T A F H sub_F_H falg halg}\n    :\n    WF_FAlgebra Name T A F (G :+: H) (Sub_Functor_inr F G H sub_F_H) falg (@FAlgebra_Plus Name T A G H galg halg).\n      econstructor. intros. \n      unfold inj.\n      unfold Sub_Functor_inr.\n      simpl.\n      rewrite (wf_algebra rec fa).\n      reflexivity.\n    Defined. \n\nEnd FAlgebra.\n\n  (* ============================================== *)\n  (* INDUCTION PRINCIPLES INFRASTRUCTURE            *)\n  (* ============================================== *)\n\nSection WF_Ind_FAlgebras.\n\n  Class PAlgebra (Name : Set) (A: Set) (F: Set -> Set) : Set :=\n    { p_algebra : Algebra F A}.\n\n  (* Definition PAlgebra_Plus (Name: Set) (A : Set) (F G : Set -> Set)\n    {falg: PAlgebra Name A F} {galg: PAlgebra Name A G} :\n    PAlgebra Name A (F :+: G) :=\n    Build_PAlgebra Name A _ \n    (fun fga =>\n      (match fga with\n         | inl fa => p_algebra fa\n         | inr ga => p_algebra ga\n       end)). *)\n\n  Global Instance PAlgebra_Plus (Name: Set) (A : Set) (F G : Set -> Set)\n    {falg: PAlgebra Name A F} {galg: PAlgebra Name A G} :\n    PAlgebra Name A (F :+: G) | 6 :=\n    {| p_algebra := fun fga =>\n         (match fga with\n           | inl fa => p_algebra fa\n           | inr ga => p_algebra ga\n          end) |}. \n\n  Class WF_Ind {E F: Set -> Set} {Name : Set} {Fun_E : Functor E} {Fun_F : Functor F} \n    {P : Fix E -> Prop} {sub_F_E : F :<: E}\n    (F_Alg : PAlgebra Name (sig P) F) :=\n    {proj_eq : forall e, proj1_sig (p_algebra (PAlgebra := F_Alg) e) = \n      in_t (inj (Sub_Functor := sub_F_E) (fmap (@proj1_sig _ _) e))}.\n\n  Definition Sub_Functor_inl' (F G H : Set -> Set) (sub_F_G : (F :+: G) :<: H) : \n    F :<: H. \n    econstructor 1 with \n      (inj := fun (A : Set) (e : F A) => (@inj _ _ sub_F_G A (inl _ e)))\n      (prj := fun (A : Set) (ha : H A) =>\n        match @prj _ _ sub_F_G A ha with\n          | Some (inl f) => Some f\n          | Some (inr g) => None\n          | None => None\n        end).\n    intros until fa; caseEq (prj ga);\n      [rewrite (inj_prj _ _ H0); destruct i; congruence | discriminate].\n    intros; rewrite prj_inj; reflexivity.\n  Defined.\n\n  Definition Sub_Functor_inr' (F G H : Set -> Set) (sub_F_G : (F :+: G) :<: H) : \n    G :<: H.\n    econstructor 1 with \n      (inj := fun (A : Set) (e : G A) => (@inj _ _ sub_F_G A (inr _ e)))\n      (prj := fun (A : Set) (H0 : H A) =>\n          match @prj _ _ sub_F_G A H0 with\n            | Some (inl f) => None\n            | Some (inr g) => Some g\n            | None => None\n          end).\n    intros until fa; caseEq (prj ga);\n      [rewrite (inj_prj _ _ H0); destruct i; congruence | discriminate].\n    intros; rewrite prj_inj; reflexivity.\n  Defined.\n\n  Global Instance WF_Ind_Plus_split {F G H} \n    {Fun_F : Functor F}\n    {Fun_G : Functor G}\n    {Fun_H : Functor H}\n    {sub_F_G_H : (F :+: G) :<: H}\n    {Name : Set}\n    {P : Fix H -> Prop} \n    {F_Alg: PAlgebra Name (sig P) F}\n    {G_Alg: PAlgebra Name (sig P) G}\n    (WF_falg : @WF_Ind H F Name Fun_H Fun_F _ (Sub_Functor_inl' _ _ _ sub_F_G_H)\n      F_Alg)\n    (WF_falg : @WF_Ind H G Name Fun_H Fun_G _ (Sub_Functor_inr' _ _ _ sub_F_G_H)\n      G_Alg)\n    : \n    @WF_Ind H (F :+: G) _ _ _ P _ (PAlgebra_Plus Name _ F G) | 0.\n      econstructor; intros. \n      destruct e; simpl. \n      rewrite (proj_eq (sub_F_E := Sub_Functor_inl' _ _ _ sub_F_G_H)); simpl; \n        reflexivity.\n      rewrite (proj_eq (sub_F_E := Sub_Functor_inr' _ _ _ sub_F_G_H)); simpl; \n        reflexivity.      \n    Defined.\n\n    (* The key reasoning lemma. *)\n    Lemma Ind {F : Set -> Set}\n      {Fun_F : Functor F}\n      {P : Fix F -> Prop}\n      {N : Set}\n      {Ind_Alg : PAlgebra N (sig P) F}\n      {WF_Ind_Alg : WF_Ind Ind_Alg} \n      :\n      forall (f : Fix F) \n        (fUP' : Universal_Property'_fold f),\n        P f.\n      intros.\n      cut (proj1_sig (fold_ _(@p_algebra _ _ _ Ind_Alg) f) = id f).\n      unfold id.\n      intro f_eq; rewrite <- f_eq.\n      eapply (proj2_sig (fold_ _ (@p_algebra _ _ _ Ind_Alg) f)).\n      erewrite (@Fusion _ Fun_F f fUP' _ _ (@proj1_sig (Fix F) P)\n        (@p_algebra _ _ _ Ind_Alg) in_t).\n      eapply Fix_id_fold; unfold id; assumption.\n      intros; rewrite (proj_eq (WF_Ind := WF_Ind_Alg)).\n      simpl; unfold id; reflexivity.\n    Defined.\n\n  Class WF_Ind2 {E E' F: Set -> Set} {Name : Set} \n    {Fun_E : Functor E} {Fun_E : Functor E'} {Fun_F : Functor F} \n    {P : (Fix E) * (Fix E') -> Prop} {sub_F_E : F :<: E} {sub_F_E' : F :<: E'}\n    (F_Alg : PAlgebra Name (sig P) F) :=\n    {proj1_eq : forall e, fst (proj1_sig (p_algebra (PAlgebra := F_Alg) e)) = \n      in_t (inj (Sub_Functor := sub_F_E) (fmap (fun e => fst (proj1_sig e)) e));\n      proj2_eq : forall e, snd (proj1_sig (p_algebra (PAlgebra := F_Alg) e)) = \n        in_t (inj (Sub_Functor := sub_F_E') (fmap (fun e => snd (proj1_sig e)) e))\n    }.\n    \n  Global Instance WF_Ind2_Plus_split {F G H H'} \n    {Fun_F : Functor F}\n    {Fun_G : Functor G}\n    {Fun_H : Functor H}\n    {Fun_H' : Functor H'}\n    {sub_F_G_H : (F :+: G) :<: H}\n    {sub_F_G_H' : (F :+: G) :<: H'}\n    {Name : Set}\n    {P : (Fix H) * (Fix H') -> Prop} \n    {F_Alg: PAlgebra Name (sig P) F}\n    {G_Alg: PAlgebra Name (sig P) G}\n    (WF_falg : @WF_Ind2 H H' F Name Fun_H Fun_H' Fun_F _ \n      (Sub_Functor_inl' _ _ _ sub_F_G_H) (Sub_Functor_inl' _ _ _ sub_F_G_H')\n      F_Alg)\n    (WF_falg : @WF_Ind2 H H' G Name Fun_H Fun_H' Fun_G _ \n      (Sub_Functor_inr' _ _ _ sub_F_G_H) (Sub_Functor_inr' _ _ _ sub_F_G_H')\n      G_Alg)\n    : \n    @WF_Ind2 H H' (F :+: G) _ _ _ _ P _ _ (PAlgebra_Plus Name _ F G) | 0.\n      econstructor; intros; destruct e; simpl. \n      rewrite (proj1_eq (sub_F_E := Sub_Functor_inl' _ _ _ sub_F_G_H)\n        (sub_F_E' := Sub_Functor_inl' _ _ _ sub_F_G_H')); simpl; \n        reflexivity.\n      rewrite (proj1_eq (sub_F_E := Sub_Functor_inr' _ _ _ sub_F_G_H)\n        (sub_F_E' := Sub_Functor_inr' _ _ _ sub_F_G_H')); simpl; \n        reflexivity.      \n      rewrite (proj2_eq (sub_F_E := Sub_Functor_inl' _ _ _ sub_F_G_H)\n        (sub_F_E' := Sub_Functor_inl' _ _ _ sub_F_G_H')); simpl; \n        reflexivity.\n      rewrite (proj2_eq (sub_F_E := Sub_Functor_inr' _ _ _ sub_F_G_H)\n        (sub_F_E' := Sub_Functor_inr' _ _ _ sub_F_G_H')); simpl; \n        reflexivity.      \n    Defined.\n\n    Lemma Ind2 {F : Set -> Set}\n      {Fun_F : Functor F}\n      {P : (Fix F) * (Fix F) -> Prop}\n      {N : Set}\n      {Ind_Alg : PAlgebra N (sig P) F}\n      {WF_Ind_Alg : WF_Ind2 Ind_Alg} \n      :\n      forall (f : Fix F) \n        (fUP' : Universal_Property'_fold f),\n        P (f, f).\n      intros.\n      cut (fst (proj1_sig (fold_ _(@p_algebra _ _ _ Ind_Alg) f)) = f).\n      cut (snd (proj1_sig (fold_ _(@p_algebra _ _ _ Ind_Alg) f)) = f).\n      intros f2_eq f1_eq; rewrite <- f1_eq at 1; rewrite <- f2_eq at -1.      \n      generalize (proj2_sig (fold_ _ (@p_algebra _ _ _ Ind_Alg) f)).\n      destruct (proj1_sig (fold_ (sig P) p_algebra f)); simpl; auto.\n      erewrite (@Fusion _ Fun_F f fUP' _ _ (fun e => snd (proj1_sig e))\n        (@p_algebra _ _ _ Ind_Alg) in_t).\n      eapply Fix_id_fold; unfold id; assumption.\n      intros; rewrite (proj2_eq (WF_Ind2 := WF_Ind_Alg)).\n      simpl; unfold id; reflexivity.\n      erewrite (@Fusion _ Fun_F f fUP' _ _ (fun e => fst (proj1_sig e))\n        (@p_algebra _ _ _ Ind_Alg) in_t).\n      eapply Fix_id_fold; unfold id; assumption.\n      intros; rewrite (proj1_eq (WF_Ind2 := WF_Ind_Alg)).\n      simpl; unfold id; reflexivity.\n    Defined.\n\n    Class iPAlgebra (Name : Set) {I : Set} (A : I -> Prop) (F: (I -> Prop) -> I -> Prop) : Prop :=\n    { ip_algebra : iAlgebra F A}.\n\n    (* Definition iPAlgebra_Plus (Name: Set) {I : Set} (A : I -> Prop)\n      (F G : (I -> Prop) -> I -> Prop)\n      {falg: iPAlgebra Name A F} {galg: iPAlgebra Name A G} :\n      iPAlgebra Name A (F ::+:: G) :=\n        Build_iPAlgebra Name _ A _ \n        (fun f fga =>\n          (match fga with\n             | or_introl fa => ip_algebra f fa\n             | or_intror ga => ip_algebra f ga\n           end)). *)\n\n    Global Instance iPAlgebra_Plus (Name: Set) {I : Set} (A : I -> Prop)\n      (F G : (I -> Prop) -> I -> Prop)\n      {falg: iPAlgebra Name A F} {galg: iPAlgebra Name A G} :\n      iPAlgebra Name A (F ::+:: G) | 6 :=\n        {| ip_algebra := fun f fga =>\n          (match fga with\n             | or_introl fa => ip_algebra f fa\n             | or_intror ga => ip_algebra f ga\n           end) |}. \n\n  Class iWF_Ind {I : Set} {E F: (I -> Prop) -> I -> Prop} {Name : Set} \n    {Fun_E : iFunctor E} {Fun_F : iFunctor F} \n    {P : forall i, iFix E i -> Prop} {sub_F_E : Sub_iFunctor F E}\n    (F_Alg : iPAlgebra Name (fun i => sig (P i)) F) :=\n    {iproj_eq : forall i e, proj1_sig (ip_algebra (iPAlgebra := F_Alg) i e) = \n      in_ti i (inj_i (Sub_iFunctor := sub_F_E) i (ifmap i (fun i => proj1_sig (P := P i)) e))}.\n\n  Definition Sub_iFunctor_inl' {I' : Set} (F G H : (I' -> Prop) -> I' -> Prop)\n    (isub_F_G : Sub_iFunctor (F ::+:: G) H) : \n    Sub_iFunctor F H :=\n    {| inj_i := fun (A : I' -> Prop) (i : I') (fai : F A i) =>\n      @inj_i _ _ _ isub_F_G _ _ (or_introl (G A i) fai);\n      prj_i := fun (A : I' -> Prop) (i : I') (hai : H A i) =>\n        let o := prj_i i hai in\n          match o with\n            | or_introl (or_introl H2) => or_introl True H2\n            | or_introl (or_intror _) => or_intror (F A i) I\n            | or_intror H1 => or_intror (F A i) H1\n          end |}.\n\n  Definition Sub_iFunctor_inr' {I' : Set} (F G H : (I' -> Prop) -> I' -> Prop)\n    (isub_F_G : Sub_iFunctor (F ::+:: G) H) : \n    Sub_iFunctor G H :=\n    {| inj_i := fun (A : I' -> Prop) (i : I') (gai : G A i) =>\n      @inj_i _ _ _ isub_F_G _ _ (or_intror _ gai);\n      prj_i := fun (A : I' -> Prop) (i : I') (hai : H A i) =>\n        let o := prj_i i hai in\n          match o with\n            | or_introl (or_intror H2) => or_introl True H2\n            | or_introl (or_introl _) => or_intror _ I\n            | or_intror H1 => or_intror _ H1\n          end |}.\n\n  Global Instance iWF_Ind_Plus_split {I : Set} \n    {F G H : (I -> Prop) -> I -> Prop} \n    {Fun_F : iFunctor F}\n    {Fun_G : iFunctor G}\n    {Fun_H : iFunctor H}\n    {sub_F_G_H : Sub_iFunctor (F ::+:: G) H}\n    {Name : Set}\n    {P : forall i, iFix H i -> Prop} \n    {F_Alg: iPAlgebra Name (fun i => sig (P i)) F}\n    {G_Alg: iPAlgebra Name (fun i => sig (P i)) G}\n    {WF_falg : @iWF_Ind _ H F Name Fun_H Fun_F _ (Sub_iFunctor_inl' _ _ _ sub_F_G_H)\n      F_Alg}\n    {WF_falg : @iWF_Ind _ H G Name Fun_H Fun_G _ (Sub_iFunctor_inr' _ _ _ sub_F_G_H)\n      G_Alg}\n    : \n    @iWF_Ind _ H (F ::+:: G) _ _ _ P _ (iPAlgebra_Plus Name _ F G) | 0.\n      econstructor; intros. \n      destruct e; simpl. \n      rewrite (iproj_eq (sub_F_E := @Sub_iFunctor_inl' _ _ _ _ sub_F_G_H)); simpl; \n        reflexivity.\n      rewrite (iproj_eq (sub_F_E := @Sub_iFunctor_inr' _ _ _ _ sub_F_G_H)); simpl; \n        reflexivity.      \n    Defined.\n\nEnd WF_Ind_FAlgebras.\n\n(* ============================================== *)\n(* ADDTIONAL MENDLER ALGEBRA INFRASTRUCTURE       *)\n(* ============================================== *)\n\nSection WF_MAlgebras.\n\n  Class WF_MAlgebra {Name : Set} {F : Set -> Set} {A : Set} \n    {Fun_F : Functor F}(MAlg : forall R, FAlgebra Name R A F) :=\n    {wf_malgebra : forall (T T' : Set) (f : T' -> T) (rec : T -> A) (ft : F T'),\n      f_algebra (FAlgebra := MAlg T) rec (fmap f ft) = \n      f_algebra (FAlgebra := MAlg T') (fun ft' => rec (f ft')) ft}.\n  \n  Global Instance WF_MAlgebra_Plus {Name : Set} {F G : Set -> Set} {A : Set} \n    {Fun_F : Functor F} \n    {Fun_G : Functor G} \n    (MAlg_F : forall R, FAlgebra Name R A F)\n    (MAlg_G : forall R, FAlgebra Name R A G) \n    {WF_MAlg_F : WF_MAlgebra MAlg_F}\n    {WF_MAlg_G : WF_MAlgebra MAlg_G}\n    :\n    @WF_MAlgebra Name (F :+: G) A _ (fun R => FAlgebra_Plus Name R A F G).\n  Proof.\n    constructor; intros.\n    destruct ft; simpl; apply wf_malgebra.\n  Qed.\n    \nEnd WF_MAlgebras.\n\nDefinition Smarked (S: Set) : Set := S.\n\nLtac Smark H :=\n  let t := type of H in\n  let n:= fresh in\n    (assert (n:Smarked t); [exact H | clear H; rename n into H]).\n\nLtac unSmark H := unfold Smarked in H.\n\nLtac unSmark_all := unfold Smarked in *|-.\n\nLtac WF_Falg_rewrite' :=\n  match goal with \n    | H : WF_FAlgebra _ _ _ _ _ _ _ |- _ => \n      try rewrite (wf_algebra (WF_FAlgebra := H)); Smark H; WF_Falg_rewrite'\n    | _ => simpl\n  end;\n  unSmark_all.\n\nLtac WF_Falg_rewrite := unfold inject, in_t; WF_Falg_rewrite'.\n\nLtac fold_ind := eapply Ind.\n\nHint Extern 0 (FAlgebra _ _ _ (_ :+: _)) =>\n  apply FAlgebra_Plus; eauto with typeclass_instances : typeclass_instances.\n\nHint Extern 0 (forall _, FAlgebra _ _ _ _) =>\n  intros; eauto with typeclass_instances : typeclass_instances.\n\nHint Extern 0 (forall _, PAlgebra _ _ _) =>\n  intros; eauto with typeclass_instances : typeclass_instances.\n\nHint Extern 0 (PAlgebra _ _ (_ :+: _)) =>\n  apply PAlgebra_Plus; eauto with typeclass_instances : typeclass_instances.\n\nHint Extern 0 (iPAlgebra _ _ (_ :+: _)) =>\n  apply iPAlgebra_Plus; eauto with typeclass_instances : typeclass_instances.\n\nHint Extern 0 (WF_Ind _) =>\n  let e := fresh in \n    constructor; intro e; destruct e; reflexivity : typeclass_instances.\n\nHint Extern 0 (WF_Ind2 _) =>\n  let e := fresh in \n    constructor; intro e; destruct e; reflexivity : typeclass_instances.\n\nHint Extern 0 (WF_MAlgebra _) =>\n  let T := fresh in \n    let T' := fresh in\n      let f' := fresh in\n        let rec' := fresh in \n          let ft := fresh in \n            constructor; intros T T' f' rec' ft; destruct ft;\n              simpl; auto; fail : typeclass_instances.\n\n(*\n*** Local Variables: ***\n*** coq-prog-args: (\"-emacs-U\" \"-impredicative-set\") ***\n*** End: ***\n*) \n", "meta": {"author": "luminousfennell", "repo": "mtc-smallstep", "sha": "457ea953ae6defa1dd2675e516011b6c0ec66709", "save_path": "github-repos/coq/luminousfennell-mtc-smallstep", "path": "github-repos/coq/luminousfennell-mtc-smallstep/mtc-smallstep-457ea953ae6defa1dd2675e516011b6c0ec66709/Functors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439708, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6721072482630257}}
{"text": "Require Export XR_R1.\nRequire Export XR_Rmult.\n\nLocal Open Scope R_scope.\n\nFixpoint pow (r:R) (n:nat) : R := match n with\n| O => R1\n| S n => Rmult r (pow r n)\nend.\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_pow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6720964589302985}}
{"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 Rbase.\nRequire Import Rfunctions.\nRequire Import Rseries.\nRequire Import PartSum.\nOpen Local Scope R_scope.\n\nSet Implicit Arguments.\n\nSection Sigma.\n\n  Variable f : nat -> R.\n\n  Definition sigma (low high:nat) : R :=\n    sum_f_R0 (fun k:nat => f (low + k)) (high - low).\n\n  Theorem sigma_split :\n    forall low high k:nat,\n      (low <= k)%nat ->\n      (k < high)%nat -> sigma low high = sigma low k + sigma (S k) high.\n  Proof.\n    intros; induction  k as [| k Hreck].\n    cut (low = 0%nat).\n    intro; rewrite H1; unfold sigma in |- *; rewrite <- minus_n_n;\n      rewrite <- minus_n_O; simpl in |- *; replace (high - 1)%nat with (pred high).\n    apply (decomp_sum (fun k:nat => f k)).\n    assumption.\n    apply pred_of_minus.\n    inversion H; reflexivity.\n    cut ((low <= k)%nat \\/ low = S k).\n    intro; elim H1; intro.\n    replace (sigma low (S k)) with (sigma low k + f (S k)).\n    rewrite Rplus_assoc;\n      replace (f (S k) + sigma (S (S k)) high) with (sigma (S k) high).\n    apply Hreck.\n    assumption.\n    apply lt_trans with (S k); [ apply lt_n_Sn | assumption ].\n    unfold sigma in |- *; replace (high - S (S k))%nat with (pred (high - S k)).\n    pattern (S k) at 3 in |- *; replace (S k) with (S k + 0)%nat;\n      [ idtac | ring ].\n    replace (sum_f_R0 (fun k0:nat => f (S (S k) + k0)) (pred (high - S k))) with\n    (sum_f_R0 (fun k0:nat => f (S k + S k0)) (pred (high - S k))).\n    apply (decomp_sum (fun i:nat => f (S k + i))).\n    apply lt_minus_O_lt; assumption.\n    apply sum_eq; intros; replace (S k + S i)%nat with (S (S k) + i)%nat.\n    reflexivity.\n    ring.\n    replace (high - S (S k))%nat with (high - S k - 1)%nat.\n    apply pred_of_minus.\n    omega.\n    unfold sigma in |- *; replace (S k - low)%nat with (S (k - low)).\n    pattern (S k) at 1 in |- *; replace (S k) with (low + S (k - low))%nat.\n    symmetry  in |- *; apply (tech5 (fun i:nat => f (low + i))).\n    omega.\n    omega.\n    rewrite <- H2; unfold sigma in |- *; rewrite <- minus_n_n; simpl in |- *;\n      replace (high - S low)%nat with (pred (high - low)).\n    replace (sum_f_R0 (fun k0:nat => f (S (low + k0))) (pred (high - low))) with\n    (sum_f_R0 (fun k0:nat => f (low + S k0)) (pred (high - low))).\n    apply (decomp_sum (fun k0:nat => f (low + k0))).\n    apply lt_minus_O_lt.\n    apply le_lt_trans with (S k); [ rewrite H2; apply le_n | assumption ].\n    apply sum_eq; intros; replace (S (low + i)) with (low + S i)%nat.\n    reflexivity.\n    ring.\n    omega.\n    inversion H; [ right; reflexivity | left; assumption ].\n  Qed.\n\n  Theorem sigma_diff :\n    forall low high k:nat,\n      (low <= k)%nat ->\n      (k < high)%nat -> sigma low high - sigma low k = sigma (S k) high.\n  Proof.\n    intros low high k H1 H2; symmetry  in |- *; rewrite (sigma_split H1 H2); ring.\n  Qed.\n\n  Theorem sigma_diff_neg :\n    forall low high k:nat,\n      (low <= k)%nat ->\n      (k < high)%nat -> sigma low k - sigma low high = - sigma (S k) high.\n  Proof.\n    intros low high k H1 H2; rewrite (sigma_split H1 H2); ring.\n  Qed.\n\n  Theorem sigma_first :\n    forall low high:nat,\n      (low < high)%nat -> sigma low high = f low + sigma (S low) high.\n  Proof.\n    intros low high H1; generalize (lt_le_S low high H1); intro H2;\n      generalize (lt_le_weak low high H1); intro H3;\n        replace (f low) with (sigma low low).\n    apply sigma_split.\n    apply le_n.\n    assumption.\n    unfold sigma in |- *; rewrite <- minus_n_n.\n    simpl in |- *.\n    replace (low + 0)%nat with low; [ reflexivity | ring ].\n  Qed.\n\n  Theorem sigma_last :\n    forall low high:nat,\n      (low < high)%nat -> sigma low high = f high + sigma low (pred high).\n  Proof.\n    intros low high H1; generalize (lt_le_S low high H1); intro H2;\n      generalize (lt_le_weak low high H1); intro H3;\n        replace (f high) with (sigma high high).\n    rewrite Rplus_comm; cut (high = S (pred high)).\n    intro; pattern high at 3 in |- *; rewrite H.\n    apply sigma_split.\n    apply le_S_n; rewrite <- H; apply lt_le_S; assumption.\n    apply lt_pred_n_n; apply le_lt_trans with low; [ apply le_O_n | assumption ].\n    apply S_pred with 0%nat; apply le_lt_trans with low;\n      [ apply le_O_n | assumption ].\n    unfold sigma in |- *; rewrite <- minus_n_n; simpl in |- *;\n      replace (high + 0)%nat with high; [ reflexivity | ring ].\n  Qed.\n\n  Theorem sigma_eq_arg : forall low:nat, sigma low low = f low.\n  Proof.\n    intro; unfold sigma in |- *; rewrite <- minus_n_n.\n    simpl in |- *; replace (low + 0)%nat with low; [ reflexivity | ring ].\n  Qed.\n\nEnd Sigma.\n", "meta": {"author": "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/Reals/Rsigma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.8128673155708976, "lm_q1q2_score": 0.6720070002675359}}
{"text": "\n(* week-04_programming-and-proving.v *)\n(* YSC3236 2017-2018, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 05 Sep 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\nDefinition beq_nat_nat A B :=\n  match A, B with\n    (a1, b1), (a2, b2) =>\n    (a1 =n= a2) && (b1 =n= b2)\n  end.\n                           \n\nNotation \"A =nn= B\" :=\n  (beq_nat_nat A B) (at level 70, right associativity).\n\n(* ********** *)\n\nDefinition test_add (candidate: nat -> nat -> nat) :=\n  (candidate 0 0 =n= 0)\n  &&\n  (candidate 0 1 =n= 1)\n  &&\n  (candidate 1 0 =n= 1)\n  &&\n  (candidate 1 1 =n= 2)\n  &&\n  (candidate 1 2 =n= 3)\n  &&\n  (candidate 2 1 =n= 3)\n  &&\n  (candidate 2 2 =n= 4)\n  .\n\nFixpoint add_v1 (i j : nat) : nat :=\n  match i with\n  | O => j\n  | S i' => S (add_v1 i' j)\n  end.\n\nCompute (test_add add_v1).\n\n(* Canonical unfold lemmas for recursive definitions: *)\n\nLemma unfold_add_v1_0 :\n  forall j : nat,\n    add_v1 0 j = j.\nProof.\n  unfold_tactic add_v1.\nQed.\n\nLemma unfold_add_v1_S :\n  forall i' j : nat,\n    add_v1 (S i') j = S (add_v1 i' j).\nProof.\n  unfold_tactic add_v1.\nQed.\n\nProposition add_v1_0_n :\n  forall n : nat,\n    add_v1 0 n = n.\nProof.\n  intro n.\n  Check (unfold_add_v1_0).\n  apply unfold_add_v1_0.\n\n  Restart.\n  apply unfold_add_v1_0.\nQed.\n  \nLemma add_v1_n_0 :\n  forall n : nat,\n    add_v1 n 0 = n.\nProof.\n  intro i.\n  induction i as [  | i' IH_i']. \n\n  Check (unfold_add_v1_0 0).\n  (* apply (unfold_add_v1_0 0). *)\n  rewrite (unfold_add_v1_0 0).\n  reflexivity.\n\n  Check (unfold_add_v1_S i' 0).\n  rewrite -> (unfold_add_v1_S i' 0).\n  Check (IH_i').\n  rewrite -> IH_i'.\n  reflexivity.\nQed. \nLemma add_v1_assoc :\n  forall x y z : nat,\n    add_v1 x (add_v1 y z) =\n    add_v1 (add_v1 x y) z.\nProof.\n  intro x.\n  induction x as [ | x' IHx'].\n\n  intros y z.\n  rewrite -> (unfold_add_v1_0 (add_v1 y z)).\n  rewrite -> (unfold_add_v1_0 y).\n  reflexivity.\n\n  intros y z.\n  rewrite -> (unfold_add_v1_S x' (add_v1 y z)).\n  rewrite -> (unfold_add_v1_S x' y).\n  rewrite -> (unfold_add_v1_S (add_v1 x' y)).\n  rewrite -> (IHx' y z).\n  reflexivity.\nQed.\n\n(* ***** *)\n\nFixpoint add_v2 (i j : nat) : nat :=\n  match i with\n  | O => j\n  | S i' => add_v2 i' (S j)\n  end.\n\nCompute (test_add add_v2).\n\n(* Canonical unfold lemmas for recursive definitions: *)\n\nLemma unfold_add_v2_0 :\n  forall j : nat,\n    add_v2 0 j = j.\nProof.\n  unfold_tactic add_v2.\nQed.\n\nLemma unfold_add_v2_S :\n  forall i' j : nat,\n    add_v2 (S i') j = add_v2 i' (S j).\nProof.\n  unfold_tactic add_v2.\nQed.\n\n(* ***** *)\n\n\nProposition equivalence_of_add_v1_and_add_v2 :\n  forall i j : nat,\n    add_v1 i j = add_v2 i j.\nProof.\nAdmitted.\n\nProposition add_v2_0_n :\n  forall n : nat,\n    add_v2 0 n = n.\nProof.\n  intro n.\n  Check (equivalence_of_add_v1_and_add_v2).\n  rewrite <- (equivalence_of_add_v1_and_add_v2 0 n).\n  apply unfold_add_v1_0. \nQed.\nProposition add_v2_n_0 :\n  forall n : nat,\n    add_v2 n 0 = n.\nProof.\n  intro n.\n  Check (equivalence_of_add_v1_and_add_v2).\n  rewrite <- (equivalence_of_add_v1_and_add_v2 n 0).\n  Check (add_v1_n_0).\n  rewrite -> add_v1_n_0.\n  reflexivity.\nQed.\n\nLemma add_v2_assoc :\n  forall x y z : nat,\n    add_v2 x (add_v2 y z) =\n    add_v2 (add_v2 x y) z.\nProof.\nAbort.\n\n(* ********** *)  \n\nDefinition test_min (candidate : nat -> nat -> nat) : bool :=\n  (candidate 0 3 =n= 0)\n  &&\n  (candidate 3 0 =n= 0)\n  &&\n  (candidate 2 3 =n= 2)\n  &&\n  (candidate 3 2 =n= 2)\n  &&\n  (candidate 3 3 =n= 3)\n  .\n\n(* ***** *)\n\n(* Lambda-dropped version of min_v1: *)\n\nFixpoint visit_min_v1 (m_init n_init m n : nat) : nat :=\n  match m with\n  | 0 => m_init\n  | S m' => match n with\n            | 0 => n_init\n            | S n' => visit_min_v1 m_init n_init m' n'\n            end\n  end.\n\nDefinition min_v1 (m_init n_init : nat) : nat :=\n  visit_min_v1 m_init n_init m_init n_init.\n\nCompute (test_min min_v1).\n\nFixpoint min_v2 (m n : nat) : nat :=\n  match m with\n  | 0 => 0\n  | S m' => match n with\n            | 0 => 0\n            | S n' => S (min_v2 m' n')\n            end\n  end.\n\nCompute (test_min min_v2).\n\n(* ***** *)\n\n(* Canonical unfold lemmas for recursive definitions: *)\n\nLemma unfold_visit_min_v1_0 :\n  forall m_init n_init n : nat,\n    visit_min_v1 m_init n_init 0 n = m_init.\nProof.\n  unfold_tactic visit_min_v1.\nQed.\n\nLemma unfold_visit_min_v1_S :\n  forall m_init n_init m' n : nat,\n    visit_min_v1 m_init n_init (S m') n =\n    match n with\n    | 0 => n_init\n    | S n' => visit_min_v1 m_init n_init m' n'\n    end.\nProof.\n  unfold_tactic visit_min_v1.\nQed.\n\nLemma unfold_min_v2_0 :\n  forall n : nat,\n    min_v2 0 n = 0.\nProof.\n  unfold_tactic min_v2.\nQed.\n\nLemma unfold_min_v2_S :\n  forall m' n : nat,\n    min_v2 (S m') n =\n    match n with\n    | 0 => 0\n    | S n' => S (min_v2 m' n')\n    end.\nProof.\n  unfold_tactic min_v2.\nQed.\n\n(* ***** *)\n\nLemma succ_visit_min_v1 :\n  forall m n m' n' : nat,\n    visit_min_v1 (S m) (S n) m' n' =\n    S (visit_min_v1 m n m' n').\nProof.\n  intros m n m'.\n  induction m' as [ | m'' IHm''].\n  \n  intro n'.\n  Check (unfold_visit_min_v1_0 (S m) (S n) n').\n  rewrite -> (unfold_visit_min_v1_0 (S m) (S n) n').\n  Check (unfold_visit_min_v1_0 m n n').\n  rewrite -> (unfold_visit_min_v1_0 m n n').\n  reflexivity.\n\n  intros [ | n'].\n  Check (unfold_visit_min_v1_S (S m) (S n) m'' 0).\n  rewrite -> (unfold_visit_min_v1_S (S m) (S n) m'' 0).\n  rewrite -> (unfold_visit_min_v1_S m n m'' 0).\n  reflexivity.\n\n  Check (unfold_visit_min_v1_S (S m) (S n) m'' (S n')).\n  rewrite -> (unfold_visit_min_v1_S (S m) (S n) m'' (S n')).\n  Check (IHm'' n').\n  rewrite -> (IHm'' n').\n  Check (unfold_visit_min_v1_S m n m'' (S n')).\n  rewrite -> (unfold_visit_min_v1_S m n m'' (S n')).\n  reflexivity.\n Qed.\n  \n  Proposition equivalence_of_min_v1_and_min_v2 :\n  forall m n : nat,\n    min_v1 m n = min_v2 m n.\nProof.\n  unfold min_v1.\n  intro m.\n  induction m as [ |m' IHm'].\n\n  intro n.\n  Check (unfold_visit_min_v1_0 0 n).\n  rewrite -> (unfold_visit_min_v1_0 0 n).\n  Check (unfold_min_v2_0).\n  rewrite -> (unfold_min_v2_0 n).\n  reflexivity.\n\n  intros [ | n'].\n  Check (unfold_visit_min_v1_S (S m') 0 m' 0).\n  rewrite -> (unfold_visit_min_v1_S (S m') 0 m' 0). \n  Check (unfold_min_v2_S m' 0).\n  rewrite -> (unfold_min_v2_S m' 0).\n  reflexivity.\n\n  Check (unfold_visit_min_v1_S (S m') (S n') m' (S n')).\n  rewrite -> (unfold_visit_min_v1_S (S m') (S n') m' (S n')).\n  Check (unfold_min_v2_S m' (S n')).\n  rewrite -> (unfold_min_v2_S m' (S n')).\n  Check (IHm' n'). \n  rewrite <- (IHm' n').\n\n  Check (succ_visit_min_v1 m' n' m' n').\n  apply (succ_visit_min_v1 m' n' m' n').\nQed. \n\n(* ********** *)\n\nDefinition test_evenp (candidate : nat -> bool) : bool :=\n  (eqb (candidate 0) true)\n  &&\n  (eqb (candidate 1) false)\n  &&\n  (eqb (candidate 7) false)\n  &&\n  (eqb (candidate 8) true)\n  &&\n  (eqb (candidate 17) false)\n  .\n\nFixpoint evenp_v1 (n : nat) : bool :=\n  match n with\n  | 0 => true\n  | S n' => match n' with\n            | 0 => false\n            | S n'' => evenp_v1 n''\n            end\n  end.\n\nCompute (test_evenp evenp_v1).\n\n(* With an inherited attribute, lambda-lifted: *)\n\nFixpoint visit_evenp_v2 (n : nat) (a : bool) : bool :=\n  match n with\n  | 0 => a\n  | S n' => visit_evenp_v2 n' (negb a)\n  end.\n\nDefinition evenp_v2 (n : nat) : bool :=\n  visit_evenp_v2 n true.\n\nCompute (test_evenp evenp_v2).\n\nFixpoint evenp_v3 (n : nat) : bool :=\n  match n with\n  | 0 => true\n  | S n' => negb (evenp_v3 n')\n  end.\n\nCompute (test_evenp evenp_v3).\n\n(********************************************************************************)\nLemma unfold_evenp_v1_0 :\n    evenp_v1 0 = true.\nProof.\n  unfold_tactic evenp_v1.\nQed.\n\nLemma unfold_evenp_v1_S :\n  forall n' : nat,\n    evenp_v1 (S n') =\n    match n' with\n            | 0 => false\n            | S n'' => evenp_v1 n''\n    end.\nProof.\n  unfold_tactic evenp_v1.\nQed.\n\nLemma unfold_visit_evenp_v2_0 :\n  forall (a : bool),\n   visit_evenp_v2 0 a = a.\nProof.\n  unfold_tactic visit_evenp_v2.\nQed.\n\nLemma unfold_visit_evenp_v2_S :\n  forall (n' : nat) (a : bool),\n    visit_evenp_v2 (S n') a = visit_evenp_v2 n' (negb a).\nProof.\n  unfold_tactic visit_evenp_v2.\nQed.\n\nLemma unfold_evenp_v3_0 :\n    evenp_v3 0 = true.\nProof.\n  unfold_tactic evenp_v3.\nQed.\n\nLemma unfold_evenp_v3_S :\n  forall n' : nat,\n    evenp_v3 (S n') = negb (evenp_v3 n').\nProof.\n  unfold_tactic evenp_v3.\nQed.\n\n(********************************************************************************)\n\n   \nLemma about_visit_evenp_v2:\n  forall (n : nat) (b: bool),\n    visit_evenp_v2 n (negb b) = negb (visit_evenp_v2 n b).\n  intro n.\n  induction n as [ | n' IHn'].\n  intro b.\n  Check (unfold_visit_evenp_v2_0 (negb b)).\n  rewrite -> (unfold_visit_evenp_v2_0 (negb b)).\n  Check (unfold_visit_evenp_v2_0 b).\n  rewrite -> (unfold_visit_evenp_v2_0 b).\n  reflexivity.\n\n  intro b.\n  Check (unfold_visit_evenp_v2_S n' (negb b)).\n  rewrite -> (unfold_visit_evenp_v2_S n' (negb b)).\n    \n  Check (unfold_visit_evenp_v2_S n' b).\n  rewrite -> (unfold_visit_evenp_v2_S n' b).\n\n  rewrite <- (IHn').\n  reflexivity.\nQed.  \n\nLemma about_evenp_v1:\n  forall n : nat,\n    negb (evenp_v1 (S n)) = (evenp_v1 n).\n\n  intro n''.\n  induction n'' as [ | n'' IHn''].\n\n  Check (unfold_evenp_v1_S 0).\n  rewrite -> (unfold_evenp_v1_S 0).\n  Check (unfold_evenp_v1_0).\n  rewrite -> unfold_evenp_v1_0. \n  unfold negb.\n  reflexivity.\n\n  Check (unfold_evenp_v1_S (S n'')).\n  rewrite -> (unfold_evenp_v1_S (S n'')).\n  Check IHn''.\n  rewrite <- IHn''. \n  Search (negb (negb _) = _).\n  apply negb_involutive.\nQed.\n   \nProposition equivalence_of_evenp_v1_and_evenp_v2 :\n  forall n : nat,\n    evenp_v1 n = evenp_v2 n.\nProof.\n   unfold evenp_v2.\n   intros [ | n'].\n   Check (unfold_evenp_v1_0).\n   rewrite -> (unfold_evenp_v1_0).\n   Check (unfold_visit_evenp_v2_0 true).\n   rewrite -> (unfold_visit_evenp_v2_0 true).\n   reflexivity.\n   \n   induction n' as [ | n'' IHn''].\n   Check (unfold_evenp_v1_S 0).\n   rewrite -> (unfold_evenp_v1_S 0).\n   Check (unfold_visit_evenp_v2_S 0 true).\n   rewrite -> (unfold_visit_evenp_v2_S 0 true).\n   \n   Check (unfold_visit_evenp_v2_0 (negb true)).\n   rewrite -> (unfold_visit_evenp_v2_0 ).\n   unfold negb.\n   reflexivity.   \n\n   Check (unfold_evenp_v1_S (S n'')).\n   rewrite -> (unfold_evenp_v1_S (S n'')).\n   Check (about_evenp_v1 n'').\n   rewrite <- (about_evenp_v1 n'').\n  \n   rewrite IHn''.\n\n   Check (unfold_visit_evenp_v2_S (S n'') true).\n   rewrite -> (unfold_visit_evenp_v2_S (S n'') true).\n\n   Check (about_visit_evenp_v2 (S n'') true).\n   rewrite -> (about_visit_evenp_v2 (S n'') true).\n   reflexivity. \nQed. \n   \nProposition equivalence_of_evenp_v2_and_evenp_v3 :\n  forall n : nat,\n    evenp_v2 n = evenp_v3 n.\nProof.\n  unfold evenp_v2.\n  intro n.\n  induction n as [ | n'].\n  \n  rewrite -> (unfold_visit_evenp_v2_0 true).\n  rewrite -> (unfold_evenp_v3_0).\n  reflexivity.\n\n  Check (unfold_evenp_v3_S n').\n  rewrite -> (unfold_evenp_v3_S n').\n  rewrite <- IHn'.\n\n  Check (unfold_visit_evenp_v2_S n' true).\n  rewrite -> (unfold_visit_evenp_v2_S n' true).\n  Check (about_visit_evenp_v2 n' true).\n  rewrite -> (about_visit_evenp_v2 n' true).\n  reflexivity.\nQed.  \n  \nProposition equivalence_of_evenp_v1_and_evenp_v3 :\n  forall n : nat,\n    evenp_v1 n = evenp_v3 n.\nProof.\n  intros [ | n'].\n\n  rewrite -> unfold_evenp_v1_0.\n  rewrite -> unfold_evenp_v3_0.\n  reflexivity.\n\n  induction n' as [ | n' IHn'].\n  Check unfold_evenp_v1_S 0.\n  rewrite -> (unfold_evenp_v1_S 0).\n  Check unfold_evenp_v3_S 0.\n  rewrite -> (unfold_evenp_v3_S 0).\n  rewrite -> (unfold_evenp_v3_0).\n  unfold negb.\n  reflexivity.\n\n  Check (unfold_evenp_v3_S (S n')).\n  rewrite -> (unfold_evenp_v3_S (S n')).\n  Check (IHn').\n  rewrite <- IHn'.\n  Check (about_evenp_v1 n').\n  rewrite -> (about_evenp_v1 n'). \n\n  Check (unfold_evenp_v1_S (S n')).\n  rewrite -> (unfold_evenp_v1_S (S n')).\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\nFixpoint fac_v1 (n : nat) : nat :=\n  match n with\n  | 0 => 1\n  | S n' =>  n * (fac_v1 n')\n  end.\n\nCompute (test_fac fac_v1).\n\nFixpoint visit_fac_v2 (n a : nat) : nat :=\n  match n with\n  | 0 => a\n  | S n' => (visit_fac_v2 n' (n * a))\n  end.\n\nDefinition fac_v2 (n : nat) : nat :=\n  visit_fac_v2 n 1.\n\nCompute (test_fac fac_v2).\n\n(********************************)\n\nLemma unfold_fac_v1_0 :\n    fac_v1 0 = 1.\nProof.\n  unfold_tactic fac_v1.\nQed.\n\nLemma unfold_fac_v1_S :\n  forall (n' : nat),\n  fac_v1 (S n') = (S n') * (fac_v1 n').\nProof.\n  unfold_tactic fac_v1.\nQed.\n\nLemma unfold_visit_fac_v2_0 :\n  forall (a : nat),\n   visit_fac_v2 0 a = a.\nProof.\n  unfold_tactic visit_fac_v2.\nQed.\n\nLemma unfold_visit_fac_v2_S :\n  forall (n' a : nat),\n    visit_fac_v2 (S n') a = visit_fac_v2 n' ((S n') * a).\nProof.\n  unfold_tactic visit_fac_v2.\nQed.\n\n(********************************)\n\nLemma about_visit_fac_v2:\n    forall (n a1 a2 : nat),\n      visit_fac_v2 n (a1 * a2) = a1 * visit_fac_v2 n a2.\nProof.\n  intro n.\n  induction n as [ | n' IHn'].\n\n  intros a1 a2.\n  rewrite -> (unfold_visit_fac_v2_0 (a1 * a2)).\n  rewrite -> (unfold_visit_fac_v2_0 a2).\n  reflexivity.\n\n  intros a1 a2.\n  rewrite -> (unfold_visit_fac_v2_S n' (a1 * a2)).\n  rewrite -> (unfold_visit_fac_v2_S n' a2).\n  Check (IHn' a1 (S n' * a2)). \n  rewrite <- (IHn' a1 (S n' * a2)).\n\n (* Nat.mul_shuffle3: forall n m p : nat, n * (m * p) = m * (n * p)*)\n  rewrite -> (Nat.mul_shuffle3 (S n') a1 a2).\n  reflexivity.\nQed.\n  \nProposition equivalence_of_fac_v1_and_fac_v2 :\n  forall n : nat,\n    fac_v1 n = fac_v2 n.\nProof.\n  unfold fac_v2.\n  induction n as [ | n' IHn'].\n\n  Check unfold_fac_v1_0. \n  rewrite -> unfold_fac_v1_0.\n  Check (unfold_visit_fac_v2_0 1).\n  rewrite -> (unfold_visit_fac_v2_0 1).\n  reflexivity.\n  \n  Check (IHn').\n  rewrite -> (unfold_fac_v1_S n').\n  rewrite -> (IHn').\n  rewrite -> (unfold_visit_fac_v2_S n').\n\n  rewrite <- (about_visit_fac_v2 n' (S n') 1).\n  reflexivity.\nQed.\n\n(* ********** *)\n\nDefinition test_fib (candidate: nat -> nat) : bool :=\n  (candidate 0 =n= 0)\n  && \n  (candidate 1 =n= 1)\n  && \n  (candidate 2 =n= 1)\n  && \n  (candidate 3 =n= 2)\n  && \n  (candidate 4 =n= 3)\n  && \n  (candidate 5 =n= 5)\n  && \n  (candidate 6 =n= 8)\n  && \n  (candidate 7 =n= 13)\n  && \n  (candidate 8 =n= 21)\n  .\n\nFixpoint fib_v1 (n : nat) : nat :=\n  match n with\n  | 0 => O\n  | S n' => match n' with\n            | O => 1\n            | S n'' => (fib_v1 n') + (fib_v1 n'')\n            end\n  end.\n\nCompute (test_fib fib_v1).\n\nFixpoint visit_fib_v2 (n a1 a2 : nat) : nat :=\n  match n with\n  | 0 => a1\n  | S n' => (visit_fib_v2 n' a2 (a1 + a2))\n  end.\n\nDefinition fib_v2 (n : nat) : nat :=\n  visit_fib_v2 n 0 1.\n\nCompute (test_fib fib_v2).\n\nFixpoint visit_fib_v3 (n : nat) : nat * nat :=\n  match n with\n  | 0 => (0, 1)\n  | S n' => match visit_fib_v3 n' with\n              | (a1, a2) => (a2, a1 + a2)\n            end\n  end.\n\nDefinition fib_v3 (n : nat) : nat :=\n  match visit_fib_v3 n with\n    | (a1, a2) => a1\n  end.\n\nCompute (test_fib fib_v3).\n\n(****************************************)\n\nDefinition test_visit_fib_v2 (f : nat -> nat -> nat -> nat) :=\n  (f 0 0 1 =n= 0)&&\n  (f 1 0 1 =n= 1)&&               \n  (f 2 0 1 =n= 1)&&\n  (f 3 0 1 =n= 2)&&\n  (f 4 0 1 =n= 3)&&\n  (f 5 0 1 =n= 5)&&\n  (f 6 0 1 =n= 8)&&\n  (f 7 0 1 =n= 13).\n\nCompute test_visit_fib_v2 visit_fib_v2.\n\nDefinition test_visit_fib_v3 (f : nat -> nat * nat) :=\n  (f 0 =nn= (0, 1))&&\n  (f 1 =nn= (1, 1))&&\n  (f 2 =nn= (1, 2))&&\n  (f 2 =nn= (2, 3))&&                \n  (f 4 =nn= (3, 5))&&\n  (f 5 =nn= (5, 8))&&\n  (f 6 =nn= (8, 13))&&\n  (f 7 =nn= (13, 21)).\n\nCompute test_visit_fib_v2 visit_fib_v2.\n\n\n\n(****************************************)\n\nLemma unfold_fib_v1_0 :\n    fib_v1 0 = 0.\nProof.\n  unfold_tactic fib_v1.\nQed.\n\nLemma unfold_fib_v1_1 :\n    fib_v1 1 = 1.\nProof.\n  unfold_tactic fib_v1.\nQed.\n\nLemma unfold_fib_v1_S :\n  forall (n'' : nat),\n  fib_v1 (S (S n'')) = (fib_v1 (S n'')) + (fib_v1 n'').\nProof.\n  unfold_tactic fib_v1.\nQed.\n\n(*\nLemma unfold_fib_v1_S' :\n  forall (n'' : nat),\n   fib_v1 (S n'') = fib_v1 (S (S n'')) - (fib_v1 n'').\nProof.\n  unfold_tactic fib_v1.\nQed.\n*)\n\nLemma unfold_visit_fib_v2_0 :\n  forall (a1 a2: nat),\n   visit_fib_v2 0 a1 a2 = a1.\nProof.\n  unfold_tactic visit_fib_v2.\nQed.\n\nLemma unfold_visit_fib_v2_S :\n  forall (n' a1 a2: nat),\n   visit_fib_v2 (S n') a1 a2 = visit_fib_v2 n' a2 (a1 + a2).\nProof.\n  unfold_tactic visit_fib_v2.\nQed.\n\n\nLemma unfold_visit_fib_v3_0 :\n   visit_fib_v3 0 = (0, 1).\nProof.\n  unfold_tactic visit_fib_v3.\nQed.\n\nLemma unfold_visit_fib_v3_S :\n  forall (n': nat),\n   visit_fib_v3 (S n') = match visit_fib_v3 n' with\n                         | (a1, a2) => (a2, a1 + a2)\n                         end.\nProof.\n  unfold_tactic visit_fib_v3.\nQed.\n\n\n(****************************************)\nLemma about_visit_fib_v2:\n  forall (n : nat),\n    visit_fib_v2 (S (S n)) 0 1 = (visit_fib_v2 (S n) 0 1) + (visit_fib_v2 n 0 1).\nAdmitted.\n\nLemma about_visit_fib_v2':\n  forall (n : nat),\n    visit_fib_v2 (S (S n)) 0 1 = visit_fib_v2 (S n) 0 1 + visit_fib_v2 n 0 1.\nAdmitted.\n\n\nProposition equivalence_of_fib_v1_and_fib_v2 :\n  forall n : nat,\n    fib_v1 n = fib_v2 n.\nProof.\n  unfold fib_v2.\n  induction n as [ | n']. \n\n  rewrite -> (unfold_fib_v1_0).\n  rewrite -> (unfold_visit_fib_v2_0 0 1).\n  reflexivity.\n\n  induction n' as [ | n'' IHn''].\n  unfold fib_v1.\n  unfold visit_fib_v2.\n  reflexivity.\n\n  rewrite -> (unfold_fib_v1_S).\n  rewrite -> (about_visit_fib_v2 n'').\n\n   \n  Check (IHn'' (S n'')).\n  Check (unfold_visit_fib_v2_S n'' 0 1).\n  assert (IHn_new := IHn'). \n  apply IHn_new in IHn''.\n  \n  destruct IHn'.\n  apply IHn' in IHn''.\n\nAbort.\n\nProposition equivalence_of_fib_v1_and_fib_v3 :\n  forall n : nat,\n    fib_v1 n = fib_v3 n.\nProof.\n  unfold fib_v3.\n  intro n.\n  induction n as [ | n' IHn'].\n\n  rewrite -> (unfold_fib_v1_0).\n  rewrite -> (unfold_visit_fib_v3_0).\n  reflexivity.\n\n  Check (unfold_fib_v1_S).\n  assert (H_unfold_fib_v1_S := unfold_fib_v1_S).\n\n  Search (_ = _ + _ -> _ = _ - _). \n  (*plus_minus: forall n m p : nat, n = m + p -> p = n - m*)\n  Check (unfold_visit_fib_v3_S n').\n  rewrite -> (unfold_visit_fib_v3_S n').\n  \n  \nAbort.\n\n(* ********** *)\n\nInductive list_nat : Type :=\n  nil_nat : list_nat\n| cons_nat : nat -> list_nat -> list_nat.\n\nFixpoint beq_list_nat (xs ys : list_nat) : bool :=\n  match xs with\n    nil_nat =>\n    match ys with\n      nil_nat =>\n      true\n    | cons_nat y ys' =>\n      false\n    end\n  | cons_nat x xs' =>\n    match ys with\n      nil_nat =>\n      false\n    | cons_nat y ys' =>\n      (x =n= y) && beq_list_nat xs' ys'\n    end\n  end.\n\nNotation \"A =ns= B\" :=\n  (beq_list_nat A B) (at level 70, right associativity).\n\n(* ***** *)\n\nDefinition test_append_list_nat (candidate: list_nat -> list_nat -> list_nat) :=\n  (candidate nil_nat nil_nat =ns= nil_nat)\n  &&\n  (candidate nil_nat (cons_nat 10 nil_nat) =ns= (cons_nat 10 nil_nat))\n  &&\n  (candidate (cons_nat 1 nil_nat) (cons_nat 10 nil_nat) =ns= (cons_nat 1 (cons_nat 10 nil_nat)))\n  (* etc. *)\n  .\n\nFixpoint append_list_nat (xs ys : list_nat) : list_nat :=\n  match xs with\n  | nil_nat =>\n    ys\n  | cons_nat x xs' =>\n    cons_nat x (append_list_nat xs' ys)\n  end.\n\nCompute (test_append_list_nat append_list_nat).\n\n(* Canonical unfold lemmas for recursive definitions: *)\n\nLemma unfold_append_list_nat_nil_nat :\n  forall ys : list_nat,\n    append_list_nat nil_nat ys = ys.\nProof.\n  unfold_tactic append_list_nat.\nQed.\n\nLemma unfold_append_list_nat_cons_nat :\n  forall (x : nat) (xs' ys : list_nat),\n    append_list_nat (cons_nat x xs') ys =\n    cons_nat x (append_list_nat xs' ys).\nProof.\n  unfold_tactic append_list_nat.\nQed.\n\nLemma append_nil_nat_ys :\n  forall ys : list_nat,\n    append_list_nat nil_nat ys = ys.\nProof.\nAbort.\n\nLemma append_ys_nil_nat :\n  forall xs : list_nat,\n    append_list_nat xs nil_nat = xs.\nProof.\nAbort.\n\nLemma append_list_nat_assoc :\n  forall xs ys zs : list_nat,\n    append_list_nat xs (append_list_nat ys zs) =\n    append_list_nat (append_list_nat xs ys) zs.\nProof.\nAbort.\n\n(* ***** *)\n\nDefinition test_length_list_nat (candidate: list_nat -> nat) :=\n  (candidate nil_nat =n= 0)\n  &&\n  (candidate (cons_nat 1 nil_nat) =n= 1)\n  &&\n  (candidate (cons_nat 2 (cons_nat 1 nil_nat)) =n= 2)\n  (* etc. *)\n  .\n\nFixpoint length_list_nat_v1 (xs : list_nat) : nat :=\n  match xs with\n  | nil_nat =>\n    0\n  | cons_nat x xs' =>\n    S (length_list_nat_v1 xs')\n  end.\n\nCompute (test_length_list_nat length_list_nat_v1).\n\nFixpoint visit_length_list_nat_v2 (xs : list_nat) (a : nat) : nat :=\n  match xs with\n  | nil_nat =>\n    a\n  | cons_nat x xs' =>\n    visit_length_list_nat_v2 xs' (S a)\n  end.\n\nDefinition length_list_nat_v2 (xs : list_nat) : nat :=\n  visit_length_list_nat_v2 xs 0.\n\nCompute (test_length_list_nat length_list_nat_v2).\n\nProposition equivalence_of_length_list_nat_v1_and_length_list_nat_v2 :\n  forall xs : list_nat,\n    length_list_nat_v1 xs = length_list_nat_v2 xs.\nProof.\nAbort.\n\n(* ********** *)\n\nProposition append_and_length_commute_with_each_other :\n  forall xs ys : list_nat,\n    length_list_nat_v1 (append_list_nat xs ys) =\n    (length_list_nat_v1 xs) + (length_list_nat_v1 ys).\nProof.\nAbort.\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_v1 (t : binary_tree) : nat :=\n  match t with\n    Leaf n =>\n    1\n  | Node t1 t2 =>\n    (number_of_leaves_v1 t1) + (number_of_leaves_v1 t2)\n  end.\n\nCompute (test_number_of_leaves number_of_leaves_v1).\n\nFixpoint visit_number_of_leaves_v2 (t : binary_tree) (a : nat) : nat :=\n  match t with\n    Leaf n =>\n    S a\n  | Node t1 t2 =>\n    visit_number_of_leaves_v2 t1 (visit_number_of_leaves_v2 t2 a)\n  end.\n\nDefinition number_of_leaves_v2 (t : binary_tree) : nat :=\n  visit_number_of_leaves_v2 t 0.\n\nCompute (test_number_of_leaves number_of_leaves_v1).\n\nProposition equivalence_of_number_of_leaves_v1_and_number_of_leaves_v2 :\n  forall t : binary_tree,\n    number_of_leaves_v1 t = number_of_leaves_v2 t.\nProof.\nAbort.\n\n(* ********** *)\n\n(* end of week-04_programming-and-proving.v *)\n", "meta": {"author": "jeremyyew", "repo": "ync-capstone", "sha": "496ea60a2fe1e4bdd36ae9b2a8be1f7338c3823b", "save_path": "github-repos/coq/jeremyyew-ync-capstone", "path": "github-repos/coq/jeremyyew-ync-capstone/ync-capstone-496ea60a2fe1e4bdd36ae9b2a8be1f7338c3823b/misc/coq-samples/fpp-2017/jeremy_week-04_programming-and-proving_210917.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401362, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.6720069965197604}}
{"text": "Require Import Coq.Program.Equality.\nRequire Import Language.\nRequire Import Value.\n\n(** * Definition *)\n\nInductive ptype : term -> type -> Prop :=\n| Pt_Int : forall n,\n    ptype (Lit n) Int\n| Pt_Arr : forall e A B,\n    lc (Lam A e B) ->\n    ptype (Lam A e B) (Arr A B)\n| Pt_Ann : forall e A,\n    lc e ->\n    ptype (Ann e A) A\n| Pt_Mrg : forall e1 e2 A B,\n    ptype e1 A ->\n    ptype e2 B ->\n    ptype (Mrg e1 e2) (And A B).\n\nHint Constructors ptype : core.\n\n(** * Properties *)\n\n(** ** Determinism *)\n\nLemma ptype_determinism :\n  forall e A B,\n    ptype e A -> ptype e B ->\n    A = B.\nProof.\n  intros * Pt1 Pt2. generalize dependent B.\n  induction Pt1; eauto; intros;\n    try solve [dependent destruction Pt2; eauto].\n  - dependent destruction Pt2; eauto.\n    pose proof (IHPt1_1 _ Pt2_1).\n    pose proof (IHPt1_2 _ Pt2_2).\n    congruence.\nQed.\n\n(** unify ptype varialbes *)\n\nLtac subst_ptype :=\n  match goal with\n  | [H1: ptype ?v ?A1, H2: ptype ?v ?A2 |- _] =>\n      (pose proof (ptype_determinism _ _ _ H1 H2) as Eqs; subst; clear H2)\n  end.\n", "meta": {"author": "juniorxxue", "repo": "applicative-intersection", "sha": "6b6f8fc3d78657e5a527e60b97465a2f96bcc606", "save_path": "github-repos/coq/juniorxxue-applicative-intersection", "path": "github-repos/coq/juniorxxue-applicative-intersection/applicative-intersection-6b6f8fc3d78657e5a527e60b97465a2f96bcc606/archive2/core+bidir+nodisjoint/Proof/PrincipalTyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6719936899200545}}
{"text": "Require Import Coq.Classes.Morphisms.\nRequire Import Crypto.Util.Tactics.\nRequire Import Crypto.Algebra.\n\nSection Monoid.\n  Context {T eq op id} {monoid:@monoid T eq op id}.\n  Local Infix \"=\" := eq : type_scope. Local Notation \"a <> b\" := (not (a = b)) : type_scope.\n  Local Infix \"*\" := op.\n  Local Infix \"=\" := eq : eq_scope.\n  Local Open Scope eq_scope.\n\n  Lemma cancel_right z iz (Hinv:op z iz = id) :\n    forall x y, x * z = y * z <-> x = y.\n  Proof.\n    split; intros.\n    { assert (op (op x z) iz = op (op y z) iz) as Hcut by (rewrite_hyp ->!*; reflexivity).\n      rewrite <-associative in Hcut.\n      rewrite <-!associative, !Hinv, !right_identity in Hcut; exact Hcut. }\n    { rewrite_hyp ->!*. reflexivity. }\n  Qed.\n\n  Lemma cancel_left z iz (Hinv:op iz z = id) :\n    forall x y, z * x = z * y <-> x = y.\n  Proof.\n    split; intros.\n    { assert (op iz (op z x) = op iz (op z y)) as Hcut by (rewrite_hyp ->!*; reflexivity).\n      rewrite !associative, !Hinv, !left_identity in Hcut; exact Hcut. }\n    { rewrite_hyp ->!*; reflexivity. }\n  Qed.\n\n  Lemma inv_inv x ix iix : ix*x = id -> iix*ix = id -> iix = x.\n  Proof.\n    intros Hi Hii.\n    assert (H:op iix id = op iix (op ix x)) by (rewrite Hi; reflexivity).\n    rewrite associative, Hii, left_identity, right_identity in H; exact H.\n  Qed.\n\n  Lemma inv_op x y ix iy : ix*x = id -> iy*y = id -> (iy*ix)*(x*y) =id.\n  Proof.\n    intros Hx Hy.\n    cut (iy * (ix*x) * y = id); try intro H.\n    { rewrite <-!associative; rewrite <-!associative in H; exact H. }\n    rewrite Hx, right_identity, Hy. reflexivity.\n  Qed.\n\nEnd Monoid.\n\nSection Homomorphism.\n  Context {T  EQ OP ID} {monoidT:  @monoid T  EQ OP ID }.\n  Context {T' eq op id} {monoidT': @monoid T' eq op id }.\n  Context {phi:T->T'}.\n  Local Infix \"=\" := eq. Local Infix \"=\" := eq : type_scope.\n  Class is_homomorphism :=\n    {\n      homomorphism : forall a b,  phi (OP a b) = op (phi a) (phi b);\n\n      is_homomorphism_phi_proper : Proper (respectful EQ eq) phi\n    }.\n  Global Existing Instance is_homomorphism_phi_proper.\nEnd Homomorphism.", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_crypto_defined/src/Algebra/Monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.7799929053683039, "lm_q1q2_score": 0.6719936882869493}}
{"text": "Require Import eqtype seq path ssrfun.\nRequire Import Basics Commons Tree OtDef ListTools Comp.\nImport Bool.\n\nDefinition asymmetric {T} (R : rel T) := (forall x y : T, R x y = ~~(R y x)).\n\nDefinition order {T} (R : rel T) := total R /\\ irreflexive R /\\ asymmetric R /\\ transitive R.\n\nLtac expand_order X := move: X; repeat (let HN := fresh in move => [] HN); let HN := fresh in move => HN.\nLtac mf := (let f := fresh in move => f).\n\nLemma order_irr {T : eqType} {R} {x y : T} (Rord : order R): R x y -> (x == y) = false.\nexpand_order Rord. by move: (H0 x); case: eqP => // -> ->. Qed.\n\nSection InsertRaw.\n\nContext {X : eqType} {R : rel X} (Rord : order R).\n\nFixpoint g_insert x xs : seq X :=\n match xs with\n | xh :: xt => if x == xh then xs else if R x xh then x :: xs else xh :: g_insert x xt\n | _ => [:: x] end.\n\nLemma g_insert_ind1 x x0 xs: g_insert x (x0 :: xs) = \n      match x0 == x, R x0 x with \n       | true, _ => x0 :: xs\n       | _, true => x0 :: (g_insert x xs) \n       | _, _    => x :: x0 :: xs end.\nexpand_order Rord => /=. rewrite H1 eq_sym.\ncase A0: (x0 == x). move: A0 => /eqP -> //. by case: (R x0 x) => /=. Qed.\n\nLemma g_insert_insert {x y xs} :\n  g_insert x (g_insert y xs) = g_insert y (g_insert x xs).\n\nexpand_order Rord. elim: xs x y => [| x0 xs IH] x y.\n + by rewrite /= eq_sym H1; case A0: eq_op; case: (R _ _) A0 => // /eqP ->.\n + rewrite ?g_insert_ind1; case A0: (x0 == x); case A1: (x0 == y) => //=; rewrite ?g_insert_ind1.\n  * by move: A0 A1 => /eqP -> /eqP ->.\n  * move: A0 => /eqP <-. rewrite eq_sym A1 H1. by case A2: (R y x0); rewrite /= eq_refl ?A1 // H1 A2.\n  * move: A1 => /eqP <-. rewrite eq_sym A0 H1. by case A2: (R x0 x); rewrite /= eq_refl ?A0 // A2.\n  * by case A2: (R x0 y); case A3: (R x0 x); rewrite ?g_insert_ind1 A0 A1 A2 A3; \n    [rewrite IH // |\n     have: (R x y) by apply (H2 x0 x y) => //; rewrite H1 A3 |\n     have: (R y x) by apply (H2 x0 y x) => //; rewrite H1 A2 |\n     rewrite eq_sym H1; (case: eqP => [->| _]); case: (R x y) => //];  \n     move => A4; rewrite A4 (order_irr Rord). Qed.\n\nLemma path_g_insert x c cs: path R x (g_insert c cs) = path R x cs && R x c.\nexpand_order Rord. elim: cs c x => [|c' cs IH] c x//=. by rewrite andb_true_r. case A0: (eq_op).\n + move: A0 => /eqP -> /=. by rewrite andb_comm -andb_assoc andb_diag.\n + case A1: (R c c') => /=; \n     [rewrite A1 andb_true_l; case A2: (R x c) => //|\n      rewrite IH; rewrite H1 in A1; apply negb_false_iff in A1; rewrite A1; case A2: (R x c')];\n   try (by rewrite (H2 _ _ _ A2 A1) ?andb_true_l andb_true_r);\n        by rewrite andb_false_l ?andb_false_r. Qed.\n\nLemma g_insert_path {x xs} : path R x xs -> g_insert x xs = x :: xs.\nexpand_order Rord. case: xs => // xh xt /=. case E: (x == xh).\n + by move /eqP in E; rewrite -E (H0 x).\n + by move /andP => [-> _]. Qed.\n\nLocal Notation \"x <<: y\" := (path R x y) (at level 70).\n\nLemma path_trans {x y xt} : R x y -> y <<: xt -> x <<: xt.\nexpand_order Rord. by case: xt => //= xth [|xtth xttt] H3 /andP [] G; rewrite /= (H2 _ _ _ H3 G). Qed.\n\nLemma g_filter_insert {p x xs} (P : p x = true) : sorted R xs\n  -> g_insert x (filter p xs) = filter p (g_insert x xs). \nelim: xs => [|xh xt IHxs].\n+ by rewrite /= P.\n+ move => /=; case E: (x == xh).\n  * by move /eqP in E; rewrite -E P /= eq_refl P.\n  * by move => S; move: (S) => H; apply path_sorted, IHxs in H;\n    case G: (p xh) => /=; case J: (R x xh);\n    rewrite /= ?E ?P G // H // (g_insert_path (path_trans J S)) /= P. Qed.\n\nEnd InsertRaw.\n\nSection SortedTree.\n\nContext {T : eqType} (R : rel T) (Rord : order R).\n\nFixpoint is_tree_sorted t := match t with Node _ cs => sorted R (map value cs) && all is_tree_sorted  cs end.\n\nStructure sorted_tree : Type := STree {\n  treeOf :> tree T;\n  stp    : is_tree_sorted treeOf}.\n\nDefinition SNode (t : T) : sorted_tree. by apply (@STree (Node t [::])). Defined.\n\nCanonical  sorted_tree_subType := Eval hnf in [subType for treeOf].\nDefinition sorted_tree_eqMixin := Eval hnf in [eqMixin of sorted_tree by <:].\nCanonical  sorted_tree_eqType  := Eval hnf in  EqType (sorted_tree) sorted_tree_eqMixin.\n\nRequire Import ProofIrrelevance.\n\nLemma st_eq (t1 t2 : sorted_tree): t1 = t2 <-> treeOf t1 = treeOf t2.\n split. \n + by move: t1 t2 => [t1 ?] [t2 ?] [].\n + case: t1 t2 => [t1 S1] [t2 S2] /= A0. subst.\n   by move: (proof_irrelevance _ S1 S2) => ->. Qed.\n\nCorollary opt_eq (t1 t2 : option sorted_tree): t1 = t2 <-> (fmap treeOf) t1 = (fmap treeOf) t2.\ncase: t1 t2 => [t1|] [t2|] //=. by split; case => /st_eq ->. Qed.\n\nDefinition treeR (x y : tree T) := R (value x) (value y).\n\nLemma treeR_order: order treeR.\n expand_order Rord. rewrite /order /total /transitive /irreflexive /asymmetric.\n by repeat (split; repeat (case; mf; mf)); rewrite /treeR /=; \n  [apply H | apply H0 | apply H1|move: H9 H10; rewrite /treeR /=; apply H2]. Qed.\n\nCorollary sorted_tree_uniq v ls: is_tree_sorted (Node v ls) -> uniq (map value ls).\nexpand_order Rord. rewrite /= andb_comm => /andP [] _. by apply sorted_uniq. Qed.\n\nLemma path_compatibility xs x: path R (value x) (map value xs) = path treeR x xs.\nelim: xs x => [|x' xs IH] //= x. by rewrite IH /treeR. Qed.\n\nCorollary sorted_compatibility xs: sorted R (map value xs) = sorted treeR xs.\ncase: xs => [|x xs] //=. apply path_compatibility. Qed.\n\nDefinition by_value v : tree T -> bool := eq_op v \\o value.\n\nLemma by_diff_values  {vx vy} : (vx == vy) = false -> negb \\o (by_value vx) --- by_value vy.\n move => Eq [v cs]; rewrite /by_value /comp /negb /=.\n case H: (vx == v) => //.\n by move /eqP in H; rewrite H eq_sym in Eq. Qed.\n\n(* Insert operation *)\n\nDefinition insert := @g_insert _ treeR.\n\nCorollary insert_insert xt yt xs : insert xt (insert yt xs) = insert yt (insert xt xs).\nrewrite /insert. rewrite g_insert_insert //. apply treeR_order. Qed.\n\nCorollary filter_insert {p x xs} : p x = true -> sorted treeR xs -> \n   insert x (filter p xs) = filter p (insert x xs). \nrewrite /insert. by apply (@g_filter_insert _ _ treeR_order). Qed.\n\nLemma find_insert_t {xs p x}: p x = true -> has p xs = false -> find p (insert x xs) = Some x.\nby elim: xs x => [|x0 xs IH] x /= A0;\n [intros; rewrite A0| move => A1; case A2: eq_op; [move: A2 A0 A1 => /eqP -> -> |\n   case A3: (treeR _ _) => /=; [rewrite A0 | move: A1 => /orb_false_iff [] -> ?; apply IH]]]. Qed. \n\nCorollary find_insert_f {xs p x}: p x = false -> find p (insert x xs) = find p xs.\n elim: xs => [/= -> |xh xt IHxs] //= H; case A0: (x == xh) => /=.\n   + by rewrite -(eqP A0) H.\n   + by case A1: (treeR x xh) => /=; rewrite ?H ?(IHxs H). Qed.\n\nLemma has_insert f s cs: has f (insert s cs) = has f cs || (f s).\nrewrite /insert; elim: cs => /= [| a cs IHa].\n + by rewrite orb_false_r.\n + case A0: eq_op => /=. move: A0 => /eqP ->. \n   by rewrite orb_comm -orb_assoc orb_diag.\n   case: (treeR s a) => /=.\n     by rewrite orb_comm.\n     by rewrite IHa orb_assoc. Qed.\n\nCorollary insert_has_f {p} x {xs} : p x = false -> has p (insert x xs) = has p xs.\n by rewrite has_insert => ->; rewrite orb_false_r. Qed.\n\nCorollary insert_has_t {p} x {xs} : p x = true -> has p (insert x xs) = true.\n by rewrite has_insert => ->; rewrite orb_true_r. Qed.\n\nCorollary insert_has_absent {p x xs} : has p (insert x xs) = false -> has p xs = false.\n by rewrite has_insert; move: p (has p) => [] []. Qed.\n\nLemma insert_sorted c cs: sorted treeR cs -> sorted treeR (insert c cs).\ncase: cs => [|c' cs] //= A0.\ncase A1: (eq_op) => //. expand_order treeR_order.\ncase A2: (treeR c' c); move: A2; rewrite H1.\n + move => /negb_true_iff A2. rewrite A2 /= /insert path_g_insert.\n   by rewrite (H1 c' c) A2 A0. apply treeR_order.\n + move => /negb_false_iff A2. by rewrite A2 /= A0 A2. Qed.\n\nLemma find_by_value {v v' xs ys} : find (by_value v) xs = Some (Node v' ys) -> v = v'.\nby elim: xs v => [|[xv xl] xs IHx] v //=;  rewrite /by_value /=; case: eqP => [-> [] //| _ /IHx]. Qed.\n\nLemma insert_all c cs p: all p (insert c cs) = all p cs && (p c).\nelim: cs c => [|c' cs IH] c /=. by rewrite andb_true_r.\ncase A0: eq_op => [].\n + by move: A0 => /eqP -> /=; rewrite andb_comm -andb_assoc andb_diag.\n + case: (treeR _ _) => [] /=.\n  * by rewrite andb_comm.\n  * by rewrite IH andb_assoc. Qed.\n\n(* Without operation *)\n\nDefinition without v := filter (negb \\o (by_value v)).\nDefinition without' := locked without.\n\nLemma without_has v xs: has (by_value v) (without v xs) = false.\nby elim: xs => [|[v1 xs'] xs IH]; rewrite /without -?lock //=; rewrite /by_value /=;\n case A0: eq_op => /=; rewrite ?A0 ?orb_false_l ?IH. Qed.\n\nLemma without_has' v v' xs: (v' == v) = false -> has (by_value v) (without v' xs) = has (by_value v) xs.\nmove => A0. by apply has_filter, by_diff_values. Qed.\n\nLemma without_find' v v' xs: (v' == v) = false -> find (by_value v) (without v' xs) = find (by_value v) xs.\nmove => A0. by apply find_filter, by_diff_values. Qed.\n\nCorollary without_has_false v v' xs: has (by_value v) xs = false -> has (by_value v) (without v' xs) = false.\ncase A0: (v' == v).\n + move: A0 => /eqP ->. by rewrite without_has.\n + by rewrite without_has'. Qed.\n\nLemma without_inv v xs: without v (without v xs) = without v xs.\nby elim: xs => [|x xs IH] //=; case A0: (by_value _ _); rewrite /= ?A0 /= IH. Qed.\n\nLemma without_without v v' xs: without v (without v' xs) = without v' (without v xs).\nelim: xs => [|x xs IH] //=; case A0: by_value => //=; case A1: by_value => //=.\n + by rewrite A0. + by rewrite A0 /= IH. Qed.\n\nLemma without_path v c cs: path treeR c cs -> path treeR c (without v cs).\nelim: cs v c => [|x cs IH] v c //= /andP [] A0 A1. rewrite /by_value /=. case A2: eq_op => /=.\n + apply IH. apply path_trans with (y := x) => //. apply treeR_order.\n + rewrite A0 /=. by apply IH. Qed.\n\nLemma without_insert_i t1 cs vt: value t1 = vt -> \n   without vt (insert t1 cs) = without vt cs.\nelim: cs t1 vt => [|c cs IH] t1 vt //=; rewrite /by_value /=.\n + by move => ->; rewrite eq_refl /=.\n + move => <-. \n   by case A0: eq_op; [move: A0 => /eqP -> /= |\n   case A1: eq_op; case: (treeR _ _) => /=; rewrite /by_value /= A1 ?eq_refl //= ?IH]. Qed.\n\nLemma without_insert t1 v2 cs: sorted treeR cs -> (value t1 != v2) ->\n insert t1 (without (v2) cs) = without (v2) (insert t1 cs).\nelim: cs => [|c cs IH] /=. \n + intros ?. by rewrite /by_value /= eq_sym => ->.\n + move => H0 A0. rewrite /by_value /=.\n   case A1: eq_op => /=; case A2: eq_op => /=; rewrite /by_value /=.\n  * move: A2 A1 A0 => /eqP <-. by rewrite eq_sym => ->.\n  * case A3: treeR => /=; rewrite /by_value /= ?A1 /=.\n   + rewrite eq_sym A0. apply path_trans with (x:= t1), (without_path (v2)), g_insert_path in H0;\n      (try by apply treeR_order). rewrite /insert H0 //. apply A3.\n   + rewrite IH => //. by move: H0 => /path_sorted.\n  * by rewrite A1 /=.\n  * case: (treeR t1 c) => /=; rewrite /by_value /= ?A1 /=.\n   + by rewrite eq_sym A0.\n   + rewrite IH => //. by move: H0 => /path_sorted. Qed.\n\nLemma without_first: forall cs c v w cw, path treeR c cs -> without v cs = w :: cw -> treeR c w.\nelim => [|c' cs' IH] c v w cw //= /andP [] A0 A1; case (by_value _) => /=.\n + move => A2. apply (IH c') in A2; [|done]. expand_order treeR_order. by apply (H2 c' c w).\n + by case => [] <-. Qed.\n\nLemma without_sorted cs v: sorted treeR cs -> sorted treeR (without v cs).\nelim: cs => [|c cs IH] //= A0.\n case A1: (by_value v c) => /=.\n + by move: A0 => /path_sorted /IH.\n + assert (A0' := A0). move: A0 => /path_sorted /IH.\n   case A2: (without _ _) => [| w cw] //= ->. rewrite andb_true_r. \n   move: A0' A2. apply /without_first. Qed.\n\nLemma has_without v cs: has (by_value v) cs = false -> without v cs = cs.\nelim: cs v => [|c cs IH] v //=. by case A0: (by_value v c) => //= /IH ->. Qed.\n\nLemma has_path c cs: path treeR c cs -> has (by_value (value c)) cs = false.\nelim: cs c => [|c' cs IH] c //= /andP [] A0 A1. have: (path treeR c cs) by move: A0 A1; apply path_trans, treeR_order.\nmove => /IH => ->. move: A0. by rewrite orb_false_r /by_value /treeR /= => /(order_irr Rord). Qed. \n\nCorollary path_without vc vcs cs: path treeR (Node vc vcs) cs -> without vc cs = cs.\nmove => /has_path. apply has_without. Qed.\n\nLemma path_find t t' cs v: path treeR t cs -> find (by_value v) cs = Some t' -> R (value t) (value t').\nelim: cs t t' v => [|[vc vcs] cs IH] t t' v //= /andP [] A0 A1. rewrite /by_value /=. case A2: (v == vc).\n + case => <- /=. by move: A0; rewrite /treeR.\n + apply IH. clear IH. case: cs A1 => [|[vc0 vcs0] cs] //= /andP [] A1 ->. rewrite andb_true_r.\n   case: t A0 A1 => [vt vts]; rewrite /treeR /=. expand_order Rord. apply H2. Qed.\n\nLemma path_has x xs: path treeR x xs -> has (by_value (value x)) xs = false.\nexpand_order Rord. elim: xs x => [|x' xs IH] //= x /andP []; rewrite /by_value /=. case A0: (eq_op).\n + by move: A0 => /eqP /=; rewrite /treeR => ->; rewrite H0.\n + move => A1 A2; rewrite IH //. move: A1 A2. apply path_trans, treeR_order. Qed.\n\nLemma insert_same v a cs: sorted treeR cs -> find (by_value v) cs = Some a -> insert a (without v cs) = cs.\nelim: cs a v => [|[vc vcs] cs IH] a v //=; rewrite /by_value /=. case A0: (v == vc) => /= A1 [].\n + rewrite /insert => <-. move: A0 => /eqP ->. assert (A1':=A1). move: A1' => /path_without ->.\n   by rewrite g_insert_path; try apply treeR_order.\n + move => A2. case A3: (eq_op _ _) => /=. move: A3 A2 => /eqP -> /find_pred /=. by rewrite A0. \n   case A4: (treeR a _). have: (treeR (Node vc vcs) a) by move: A1 A2; apply /path_find.\n   expand_order treeR_order. by rewrite H1 A4.\n + rewrite IH => //. by apply path_sorted in A1. Qed.\n\n(* Open operation *)\n\nDefinition label_preserving (f : tree T -> option (tree T)) := \n forall t', match f t' with Some t => value t = value t' | _ => True end.\n\nDefinition open (f : tree T -> option (tree T)) (vo : T) (t : tree T) := \n match t with Node v cs => \n   match (bind f) (find (by_value vo) cs) with \n     Some fch => Some (Node v (insert fch (without vo cs)))\n     | _ => None end end.\n\nLemma find_sorted v p cs t: is_tree_sorted (Node v cs) -> find p cs = Some t -> is_tree_sorted t.\nelim: cs v => [|c' cs IH] v //= /andP [] A0 /andP [] A1 A2; case: (p c').\n + by case => <-.\n + apply (IH v). by move: A0 => /path_sorted /= -> /=. Qed.\n\nLemma all_without p v cs: all p cs -> all p (without v cs).\nelim: cs => [|c cs IH] //= /andP []; case A0: by_value => /=; [intros ?|move => -> /=]; apply IH. Qed.\n\nEnd SortedTree.\n\nImplicit Arguments treeOf [[T] [R]].\nImplicit Arguments without_insert [[T] [R]].\n\n(* find/has simplification tactics *)\n\nLtac use_sortedness S := repeat first [apply without_sorted | apply insert_sorted | by (move: S; rewrite /is_tree_sorted => /andP []; rewrite sorted_compatibility)].\n\nLtac sop_simpl :=\nlet fi_t := rewrite find_insert_t //=; (try subst); \n            try (by rewrite ?/by_value /= eq_refl); try (by apply without_has) in\nlet fi_f := rewrite find_insert_f; [| by rewrite /by_value /= // eq_sym //] in\nlet wf' := rewrite without_find'; [| by rewrite // eq_sym] in\nlet wh' := rewrite without_has'; [| by rewrite // eq_sym] in\n(subst; repeat first [rewrite eq_refl /= | rewrite /without' -lock | \nrewrite without_has | rewrite without_inv | match goal with\n | [ H : has (by_value ?v) ?cs = false |- context [without ?v ?cs] ] => rewrite (has_without _ _ H)\n | [ |- context [find (by_value (value ?v1)) (insert _ ?v1 _)] ]   => fi_t\n | [ |- context [find (by_value ?v1) (insert _ (Node ?v1 _) _) ] ] => fi_t\n | [ |- context [find (by_value ?v1) (insert _ ?v2 _)] ] => fi_f\n | [ |- context [without _ (insert _ _ _)]] => rewrite without_insert_i; [| by done]\n | [ H : (?v1 == ?v2) = false |- context [find (by_value ?v1) (without ?v2 _)]] => wf'\n | [ H : (?v2 == ?v1) = false |- context [find (by_value ?v1) (without ?v2 _)]] => wf'\n | [ H : (?v1 == ?v2) = false |- context [has (by_value ?v1) (without ?v2 _)]] => wh'\n | [ H : (?v2 == ?v1) = false |- context [has (by_value ?v1) (without ?v2 _)]] => wh'\nend]).", "meta": {"author": "JetBrains", "repo": "ot-coq", "sha": "8228355a42bdbc51d0824c2fa4f1569dc182d11e", "save_path": "github-repos/coq/JetBrains-ot-coq", "path": "github-repos/coq/JetBrains-ot-coq/ot-coq-8228355a42bdbc51d0824c2fa4f1569dc182d11e/SortedTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656671, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6719936739288557}}
{"text": "Require Import Monads.OuputMonad.\nRequire Import Monads.FunctorApplicativeMonad.\nRequire Import NPeano Arith Bool String List.\n\nNotation \"x <- c1 ;; c2\" := (bind c1 (fun x => c2)) \n                             (right associativity, at level 84, c1 at next level).\n\nNotation \"c1 ;; c2\" := (bind c1 (fun _ => c2)) (at level 100, right associativity).\n\n\nClass Show(A:Type) := {\n  show : A -> string\n}.\n\nDefinition digit2string(d:nat) : string := \n  match d with \n    | 0 => \"0\" | 1 => \"1\" | 2 => \"2\" | 3 => \"3\"\n    | 4 => \"4\" | 5 => \"5\" | 6 => \"6\" | 7 => \"7\"\n    | 8 => \"8\" | _ => \"9\"\n  end %string.\n  \nFixpoint digits'(fuel n:nat) (accum : string) : string := \n  match fuel with \n    | 0 => accum\n    | S fuel' => \n      match n with \n        | 0 => accum\n        | _ => let d := digit2string(n mod 10) in \n               digits' fuel' (n / 10) (d ++ accum)\n      end\n  end.\n\nDefinition digits (n:nat) : string := \n  match digits' n n \"\" with \n    | \"\" => \"0\"\n    | ds => ds\n  end %string.\n  \nInstance natShow : Show nat := { \n  show := digits\n}.\n\nInductive tm := \n| Con : nat -> tm\n| Div : tm -> tm -> tm.\n\nExample answer: tm := (Div (Div (Con 1972 ) (Con 2 )) (Con 23 )).\nExample error: tm := (Div (Con 1)(Con 0)).\n\n\nInstance expShow : Show tm := {\n  show := fix show_exp (t:tm) : string := \n              match t with \n                | Con n => \"(Con \"++ show n ++\")\"\n                | Div t1 t2 => \"(Div \" ++ (show_exp t1) ++ (show_exp t2) ++ \")\"\n              end %string\n}.\n\nDefinition line(t:tm) (n:nat):string:=\n(append (append \"eval\"%string (show (t))) (append \"<=\"%string (append (show n ) \"\n      \"%string))).\n\nFixpoint eval_output (t:tm) : output nat  := \n  match t with \n  | Con n =>   (line (Con n) n, n)\n  | Div t1 t2  => \n      n1 <- eval_output t1 ;; \n      n2 <- eval_output t2 ;; \n      (line (Div t1 t2) (n1/n2), n1/n2 ) end.\n      \nCompute eval_output answer . \n\n(* = = (\"eval(Con 1972)<=1972\n      eval(Con 2)<=2\n      eval(Div (Con 1972)(Con 2))<=986\n      eval(Con 23)<=23\n      eval(Div (Div (Con 1972)(Con 2))(Con 23))<=42\n      \"%string,\n       42)\n     : output_comp nat *)\n\n", "meta": {"author": "ATirelli", "repo": "monads-coq", "sha": "af1f7a745384b81f1975d51d0bd96cb621dcf9f3", "save_path": "github-repos/coq/ATirelli-monads-coq", "path": "github-repos/coq/ATirelli-monads-coq/monads-coq-af1f7a745384b81f1975d51d0bd96cb621dcf9f3/src/OuputMonadApplications.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382004, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6719648557922752}}
{"text": "Add LoadPath \"..\".\nRequire Export Shared.\n\nInductive vctx_LF :=\n| bctx: nat -> vctx_LF\n| cctx: ctx_LF -> vctx_LF\n.\n\nInductive te_LF :=\n| hyp_LF: vte -> te_LF\n| lam_LF: ty -> te_LF -> te_LF\n| appl_LF: te_LF -> te_LF -> te_LF\n| box_LF: te_LF -> te_LF\n| unbox_LF: te_LF -> te_LF\n| here_LF: te_LF -> te_LF\n| letdia_LF: ty -> te_LF -> te_LF -> te_LF\n.\n\nInductive lc_t_n_LF : nat -> te_LF -> Prop :=\n | lc_t_hyp_bte_LF: forall v n, n > v -> lc_t_n_LF n (hyp_LF (bte v))\n | lc_t_hyp_fte_LF: forall v n, lc_t_n_LF n (hyp_LF (fte v))\n | lc_t_lam_LF: forall M t n,\n     lc_t_n_LF (S n) M ->\n     lc_t_n_LF n (lam_LF t M)\n | lc_t_appl_LF: forall M N n,\n     lc_t_n_LF n M -> lc_t_n_LF n N ->\n     lc_t_n_LF n (appl_LF M N)\n | lc_t_box_LF: forall M n,\n     lc_t_n_LF n M ->\n     lc_t_n_LF n (box_LF M)\n | lc_t_unbox_LF: forall M n,\n     lc_t_n_LF n M ->\n     lc_t_n_LF n (unbox_LF M)\n | lc_t_here_LF: forall M n,\n     lc_t_n_LF n M ->\n     lc_t_n_LF n (here_LF M)\n | lc_t_letdia_LF: forall M N t n,\n     lc_t_n_LF (S n) N -> lc_t_n_LF n M ->\n     lc_t_n_LF n (letdia_LF t M N)\n.\n\nDefinition lc_t_LF := lc_t_n_LF 0.\n\nFixpoint used_vars_te_LF (M: te_LF) : fset var :=\nmatch M with\n| hyp_LF (fte v) => \\{v}\n| hyp_LF (bte _) => \\{}\n| lam_LF _ M => used_vars_te_LF M\n| appl_LF M N => used_vars_te_LF M \\u used_vars_te_LF N\n| box_LF M => used_vars_te_LF M\n| unbox_LF M => used_vars_te_LF M\n| here_LF M => used_vars_te_LF M\n| letdia_LF _ M N => used_vars_te_LF M \\u used_vars_te_LF N\nend.\n\nLemma closed_t_succ_LF:\nforall M n,\n  lc_t_n_LF n M -> lc_t_n_LF (S n) M.\nintros; generalize dependent n;\ninduction M; intros; inversion H; subst;\neauto using lc_t_n_LF.\nQed.\n\nLemma closed_t_addition_LF:\nforall M n m,\n  lc_t_n_LF n M -> lc_t_n_LF (n + m) M.\nintros; induction m;\n[ replace (n+0) with n by auto |\n  replace (n + S m) with (S (n+m)) by auto] ;\ntry apply closed_t_succ_LF;\nassumption.\nQed.\n", "meta": {"author": "Ayertienna", "repo": "IS5", "sha": "3bfd1b8510f269071d59d77818f8936d194364bc", "save_path": "github-repos/coq/Ayertienna-IS5", "path": "github-repos/coq/Ayertienna-IS5/IS5-3bfd1b8510f269071d59d77818f8936d194364bc/src/LF-Church/LF_Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7718435030872967, "lm_q1q2_score": 0.6719648454265408}}
{"text": "\nTheorem Ex014 (A B : Prop) : A /\\ B -> B /\\ A.\nProof.\n  intro.\n  destruct H.\n  split.\n  + exact H0.\n  + exact H.\nQed.\n\n", "meta": {"author": "SvenWille", "repo": "CoqLogicExercises", "sha": "b4c1aea30abb95dc7ba81fa42ccb914d534d65e5", "save_path": "github-repos/coq/SvenWille-CoqLogicExercises", "path": "github-repos/coq/SvenWille-CoqLogicExercises/CoqLogicExercises-b4c1aea30abb95dc7ba81fa42ccb914d534d65e5/src/propLogic/Ex014.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6719648396298932}}
{"text": "\nRequire Import Iron.Language.Simple.Step.\nRequire Import Iron.Language.Simple.SubstExpExp.\nRequire Import Iron.Language.Simple.Ty.\n\n\n(* If a closed, well typed expression takes an evaluation step \n   then the result has the same type as before. *)\nTheorem preservation\n :  forall x x' t\n ,  TYPE nil x  t\n -> STEP x x'\n -> TYPE nil x' t.\nProof.\n intros x x' t HT HS. gen t.\n induction HS; rip.\n\n  destruct H; inverts_type; burn.\n\n  inverts_type.\n  burn using subst_exp_exp.\nQed.\n\n\n(* If a closed, well typed expression takes several evaluation steps\n   then the result has the same type as before. *)\nLemma preservation_steps\n :  forall x1 t1 x2\n ,  TYPE nil x1 t1\n -> STEPS    x1 x2\n -> TYPE nil x2 t1.\nProof.\n intros x1 t1 x2 HT HS.\n induction HS; burn using preservation.\nQed.\n\n\n(* If a closed, well typed expression takes several evaluation steps\n   then the result has the same type as before. \n   Usses the left linearised version of steps judement. *)\nLemma preservation_stepsl\n :  forall x1 t1 x2\n ,  TYPE nil x1 t1\n -> STEPSL   x1 x2\n -> TYPE nil x2 t1.\nProof.\n intros x1 t1 x2 HT HS.\n induction HS; burn using preservation.\nQed.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Language/Simple/Preservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6719648356745855}}
{"text": "Require Import Coq.Unicode.Utf8_core.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Arith.Arith.\n\n\nInductive varAssign : Type :=\n| VA_Empty : varAssign\n| VA_Var   : nat -> bool -> varAssign -> varAssign.\n\nFixpoint lookup (va:varAssign) (n:nat) : option bool :=\nmatch va with\n| VA_Empty        => None\n| VA_Var m b rest => if (beq_nat n m) then Some b else lookup rest n\nend.\n\nInductive assigns : varAssign -> nat -> bool -> Prop :=\n| assigns_var  : forall n b rest, assigns (VA_Var n b rest) n b\n| assigns_rest : forall n1 n2 b1 b2 rest, not (n1 = n2) ->\n                                          assigns rest n1 b1 ->\n                                          assigns (VA_Var n2 b2 rest) n1 b1.\n\n\n\n", "meta": {"author": "SHoltzen", "repo": "verified-sdd", "sha": "d400630db6526997226d6723ff8aedc0f1466901", "save_path": "github-repos/coq/SHoltzen-verified-sdd", "path": "github-repos/coq/SHoltzen-verified-sdd/verified-sdd-d400630db6526997226d6723ff8aedc0f1466901/coq/VarAssign.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6719648259226301}}
{"text": "(************************************************************************)\n(* Copyright 2006 Milad Niqui                                           *)\n(* This file is distributed under the terms of the                      *)\n(* GNU Lesser General Public License Version 2.1                        *)\n(* A copy of the license can be found at                                *)\n(*                  <http://www.gnu.org/licenses/lgpl-2.1.html>         *)\n(************************************************************************)\n\nFrom QArithSternBrocot Require Export Qsyntax.\nFrom QArithSternBrocot Require Export Field_Theory_Q.\nFrom QArithSternBrocot Require Export Q_ordered_field_properties.\n\nLemma Qpositive_in_Q_Archimedean_inf:forall qp:Qpositive, {z:Z | (Qpos qp)<=z /\\ (z-(Qpos qp))<= Qone}.\nProof.\n induction qp as [qp [z [Hz1 Hz2]]|qp [z [Hz1 Hz2]]|]; simpl.\n  exists (z+1)%Z; split;rewrite Qpos_nR; rewrite Z_to_Qplus; qZ_numerals.\n   apply Qle_plus_plus; trivial.\n   stepl (z-Qpos qp); [assumption|ring].\n\n  exists (1)%Z; split; rewrite Qpos_dL; fold (Qdiv (Qpos qp) (Qpos qp + Qone)); qZ_numerals.\n   apply Qmult_pos_Qdiv_Qle; auto; stepr (Qpos qp+Qone); [|ring]; apply Qle_Zero_Qminus; stepr Qone; [auto|ring].\n   stepl (Qone/(Qpos qp + Qone)); [|field; auto];\n    apply Qmult_pos_Qdiv_Qle; auto;  stepr (Qpos qp+Qone); [|ring]; apply Qle_Zero_Qminus;  stepr (Qpos qp); [auto|ring].\n   \n exists (1)%Z; split; auto.\nQed.\n\n\nTheorem Q_Archimedean_inf:forall q:Q, {z:Z | q<=z /\\ (z-q)<= Qone}.\nProof.\n intros [|qp|qp].  \n (* 0 *)\n exists (0)%Z; split; auto.\n (* Qpos *)\n destruct (Qpositive_in_Q_Archimedean_inf qp) as [z Hz]; exists z; assumption.\n (* Qneg *)  \n destruct (Qpositive_in_Q_Archimedean_inf qp) as [z [Hz1 Hz2]]; exists (-(z-1))%Z; rewrite Z_to_Qopp;\n           rewrite (Z_to_Qminus); qZ_numerals; split; apply Qle_opp; apply Qle_Zero_Qminus; rewrite Qopp_Qpos.\n  stepr (Qone-(z - Qpos qp)); [|ring]; apply Qle_Qminus_Zero; assumption.\n  stepr (z-(Qpos qp));[|ring]; apply Qle_Qminus_Zero; assumption.\nQed.\n\nDefinition up_Q q:= proj1_sig (Q_Archimedean_inf q).\n\nDefinition up_Q_property q := proj2_sig (Q_Archimedean_inf q):  q <= (up_Q q) /\\ (up_Q q) - q <= Qone.\n\nLemma Q_Archimedean_nat_inf:forall q:Q, {n:nat | q<=n }.\nProof.\n intro q.\n destruct (Q_le_lt_dec q Zero).\n  exists O; qnat_zero.\n  exists (Z.abs_nat (up_Q q)).\n  destruct (up_Q_property q) as [H1 H2].  \n  stepr (up_Q q); trivial.\n   assert (H3:(0<=(up_Q q))%Z).\n    assert (H4:Zero<Z_to_Q (up_Q q));[apply Qlt_le_trans with q; auto|];\n    generalize (Q_to_Z_monotone _ _ H4); simpl; rewrite Q_to_Z_to_Q; trivial.\n   rewrite (Z_of_nat_Zabs_nat_pos _ H3); reflexivity.\nQed.\n", "meta": {"author": "coq-community", "repo": "qarith-stern-brocot", "sha": "a36a01526e76f4ef92bc87445da33dfb025e2db4", "save_path": "github-repos/coq/coq-community-qarith-stern-brocot", "path": "github-repos/coq/coq-community-qarith-stern-brocot/qarith-stern-brocot-a36a01526e76f4ef92bc87445da33dfb025e2db4/theories/Q_Archimedean.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.6719279882639626}}
{"text": "Require Import\n  HoTT.Classes.interfaces.abstract_algebra\n  HoTT.HProp HoTT.TruncType\n  HoTT.Types.Universe HoTT.Types.Prod.\n\n(** Demonstrate the [hProp] is a (bounded) lattice w.r.t. the logical\noperations. This requires Univalence. *)\nInstance join_hor : Join hProp := hor.\nDefinition hand (X Y : hProp) : hProp := BuildhProp (X * Y).\nInstance meet_hprop : Meet hProp := hand.\nInstance bottom_hprop : Bottom hProp := False_hp.\nInstance top_hprop : Top hProp := Unit_hp.\n\nSection contents.\n  Context `{Univalence}.\n\n  (* We use this notation because [hor] can accept arguments of type [Type], which leads to minor confusion in the instances below *)\n  Notation lor := (hor : hProp -> hProp -> hProp).\n\n  (* This tactic attempts to destruct a truncated sum (disjunction) *)\n  Local Ltac hor_intros :=\n    let x := fresh in\n    intro x; repeat (strip_truncations; destruct x as [x | x]).\n\n  Instance commutative_hor : Commutative lor.\n  Proof.\n    intros ??.\n    apply path_iff_hprop; hor_intros; apply tr; auto.\n  Defined.\n\n  Instance commutative_hand : Commutative hand.\n  Proof.\n    intros ??.\n    apply path_hprop.\n    apply equiv_prod_symm.\n  Defined.\n\n  Instance associative_hor : Associative lor.\n  Proof.\n    intros ???.\n    apply path_iff_hprop;\n    hor_intros; apply tr;\n    ((by auto) || (left; apply tr) || (right; apply tr));\n    auto.\n  Defined.\n\n  Instance associative_hand : Associative hand.\n  Proof.\n    intros ???.\n    apply path_hprop.\n    apply equiv_prod_assoc.\n  Defined.\n\n  Instance idempotent_hor : BinaryIdempotent lor.\n  Proof.\n    intros ?. compute.\n    apply path_iff_hprop; hor_intros; auto.\n    by apply tr, inl.\n  Defined.\n\n  Instance idempotent_hand : BinaryIdempotent hand.\n  Proof.\n    intros ?.\n    apply path_iff_hprop.\n    - intros [a _] ; apply a.\n    - intros a; apply (pair a a).\n  Defined.\n\n  Instance leftidentity_hor : LeftIdentity lor False_hp.\n  Proof.\n    intros ?.\n    apply path_iff_hprop; hor_intros; try contradiction || assumption.\n    by apply tr, inr.\n  Defined.\n\n  Instance rightidentity_hor : RightIdentity lor False_hp.\n  Proof.\n    intros ?.\n    apply path_iff_hprop; hor_intros; try contradiction || assumption.\n    by apply tr, inl.\n  Defined.\n\n  Instance leftidentity_hand : LeftIdentity hand Unit_hp.\n  Proof.\n    intros ?.\n    apply path_trunctype, prod_unit_l.\n  Defined.\n\n  Instance rightidentity_hand : RightIdentity hand Unit_hp.\n  Proof.\n    intros ?.\n    apply path_trunctype, prod_unit_r.\n  Defined.\n\n  Instance absorption_hor_hand : Absorption lor hand.\n  Proof.\n    intros ??.\n    apply path_iff_hprop.\n    - intros X; strip_truncations.\n      destruct X as [? | [? _]]; assumption.\n    - intros ?. by apply tr, inl.\n  Defined.\n\n  Instance absorption_hand_hor : Absorption hand lor.\n  Proof.\n    intros ??.\n    apply path_iff_hprop.\n    - intros [? _]; assumption.\n    - intros ?.\n      split.\n      * assumption.\n      * by apply tr, inl.\n  Defined.\n\n  Global Instance boundedlattice_hprop : IsBoundedLattice hProp.\n  Proof. repeat split; apply _. Defined.\nEnd contents.\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/Classes/implementations/hprop_lattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6719203939914878}}
{"text": "(* comatrices *)\n\nSet Nested Proofs Allowed.\nSet Implicit Arguments.\n\nRequire Import Utf8 Arith.\nImport List List.ListNotations.\n\nRequire Import Misc RingLike IterAdd IterMul Pigeonhole.\nRequire Import PermutationFun SortingFun SortRank.\nRequire Import Matrix PermutSeq Signature Determinant.\nRequire Import MyVector.\nImport matrix_Notations.\n\nSection a.\n\nContext {T : Type}.\nContext (ro : ring_like_op T).\nContext (rp : ring_like_prop T).\n\nDefinition com (M : matrix T) : matrix T :=\n  mk_mat\n    (map\n      (λ i,\n       map (λ j, (minus_one_pow (i + j) * det (subm i j M))%L)\n         (seq 1 (mat_ncols M)))\n      (seq 1 (mat_nrows M))).\n\nArguments com M%M.\n\nTheorem mat_swap_same_rows : ∀ (M : matrix T) i,\n  mat_swap_rows i i M = M.\nProof.\nintros.\ndestruct M as (ll); cbn.\nunfold mat_swap_rows; f_equal.\ncbn - [ list_swap_elem ].\nrewrite (List_map_nth_seq ll (nth i ll [])) at 2.\nunfold list_swap_elem.\napply map_ext_in.\nintros j Hj; apply in_seq in Hj.\nrewrite transposition_id.\nnow apply nth_indep.\nQed.\n\nTheorem mat_swap_rows_comm : ∀ (M : matrix T) p q,\n  mat_swap_rows p q M = mat_swap_rows q p M.\nProof.\nintros.\nunfold mat_swap_rows; f_equal; cbn.\nunfold list_swap_elem.\napply map_ext_in.\nintros i Hi; apply in_seq in Hi.\nnow rewrite transposition_comm.\nQed.\n\nTheorem subm_mat_swap_rows_lt_lt : ∀ (M : matrix T) p q r j,\n  p < q < r\n  → subm r j (mat_swap_rows p q M) = mat_swap_rows p q (subm r j M).\nProof.\nintros * (Hpq, Hq).\ndestruct M as (ll); cbn.\nunfold subm, mat_swap_rows; cbn; f_equal.\nrewrite map_length.\nrewrite butn_length.\nrewrite <- map_butn, map_map.\nrewrite map_butn_seq.\nrewrite Nat.add_0_l.\napply map_ext_in.\nintros i Hi; apply in_seq in Hi.\nunfold Nat.b2n.\nrewrite if_leb_le_dec.\ndestruct Hi as (_, Hi).\ndestruct (le_dec (r - 1) i) as [Hir| Hir]. 2: {\n  apply Nat.nle_gt in Hir.\n  rewrite Nat.add_0_r.\n  destruct (Nat.eq_dec i (p - 1)) as [Hip| Hip]. {\n    subst i; clear Hir.\n    rewrite transposition_1.\n    destruct (lt_dec (q - 1) (length (butn (r - 1) ll))) as [Hqrl| Hqrl]. {\n      rewrite (List_map_nth' []); [ | easy ].\n      rewrite nth_butn_after; [ easy | flia Hpq Hq ].\n    }\n    apply Nat.nlt_ge in Hqrl.\n    symmetry.\n    rewrite nth_overflow; [ | now rewrite map_length ].\n    rewrite butn_length in Hqrl.\n    destruct (le_dec (length ll) (q - 1)) as [Hlq| Hlq]. {\n      rewrite nth_overflow; [ | easy ].\n      now rewrite butn_nil.\n    }\n    apply Nat.nle_gt in Hlq.\n    unfold Nat.b2n in Hi, Hqrl.\n    rewrite if_ltb_lt_dec in Hi, Hqrl.\n    destruct (lt_dec (r - 1) (length ll)) as [Hrl| Hrl]; [ | flia Hqrl Hlq ].\n    flia Hq Hrl Hi Hqrl.\n  }\n  destruct (Nat.eq_dec i (q - 1)) as [Hiq| Hiq]. {\n    subst i; clear Hir.\n    rewrite transposition_2.\n    destruct (lt_dec (p - 1) (length (butn (r - 1) ll))) as [Hprl| Hprl]. {\n      rewrite (List_map_nth' []); [ | easy ].\n      rewrite nth_butn_after; [ easy | flia Hpq Hq ].\n    }\n    apply Nat.nlt_ge in Hprl.\n    rewrite butn_length in Hprl.\n    flia Hpq Hi Hprl.\n  }\n  unfold transposition.\n  do 2 rewrite if_eqb_eq_dec.\n  destruct (Nat.eq_dec i (p - 1)) as [H| H]; [ easy | clear H ].\n  destruct (Nat.eq_dec i (q - 1)) as [H| H]; [ easy | clear H ].\n  rewrite map_butn.\n  rewrite nth_butn_after; [ | easy ].\n  rewrite (List_map_nth' []); [ easy | flia Hi ].\n}\nunfold transposition.\ndo 4 rewrite if_eqb_eq_dec.\ndestruct (Nat.eq_dec i (p - 1)) as [H| H]; [ flia Hpq Hq Hir H | clear H ].\ndestruct (Nat.eq_dec i (q - 1)) as [H| H]; [ flia Hpq Hq Hir H | clear H ].\ndestruct (Nat.eq_dec (i + 1) (p - 1)) as [H| H]; [ flia Hpq Hq Hir H | clear H ].\ndestruct (Nat.eq_dec (i + 1) (q - 1)) as [H| H]; [ flia Hq Hir H | clear H ].\nrewrite map_butn.\nrewrite nth_butn_before; [ | easy ].\nrewrite (List_map_nth' []); [ easy | ].\nunfold Nat.b2n in Hi.\nrewrite if_ltb_lt_dec in Hi.\ndestruct (lt_dec (r - 1) (length ll)) as [Hrl| Hrl]; [ flia Hi Hir | ].\nflia Hrl Hi Hir.\nQed.\n\nTheorem subm_mat_swap_rows_lt : ∀ (M : matrix T) p q r j,\n  p < r\n  → q < r\n  → subm r j (mat_swap_rows p q M) = mat_swap_rows p q (subm r j M).\nProof.\nintros * Hp Hq.\ndestruct (lt_dec p q) as [Hpq| Hpq]; [ now apply subm_mat_swap_rows_lt_lt | ].\ndo 2 rewrite mat_swap_rows_comm with (p := p).\ndestruct (lt_dec q p) as [Hqp| Hqp]; [ now apply subm_mat_swap_rows_lt_lt | ].\nreplace q with p by flia Hpq Hqp.\nnow do 2 rewrite mat_swap_same_rows.\nQed.\n\nTheorem mat_el_mat_swap_rows : ∀ (M : matrix T) p q j,\n  1 ≤ q ≤ mat_nrows M\n  → mat_el (mat_swap_rows p q M) q j = mat_el M p j.\nProof.\nintros * Hql; cbn.\ndestruct M as (ll); cbn in Hql |-*.\nf_equal; clear j.\nrewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hql ].\nrewrite seq_nth; [ | flia Hql ].\nrewrite Nat.add_0_l.\nnow rewrite transposition_2.\nQed.\n\nTheorem length_fold_left_map_transp : ∀ A (ll : list A) sta len f g d,\n  length\n    (fold_left\n       (λ ll' k,\n        map (λ i, nth (transposition (f k) (g k) i) ll' d)\n          (seq 0 (length ll')))\n       (seq sta len) ll) = length ll.\nProof.\nintros.\ninduction len; [ easy | ].\nrewrite seq_S.\nrewrite fold_left_app; cbn.\nrewrite List_map_seq_length.\napply IHlen.\nQed.\n\nTheorem mat_nrows_fold_left_swap : ∀ (M : matrix T) p q f g,\n  mat_nrows (fold_left (λ M' k, mat_swap_rows (f k) (g k) M') (seq p q) M) =\n  mat_nrows M.\nProof.\nintros.\nunfold mat_nrows.\nrewrite fold_left_mat_fold_left_list_list.\napply length_fold_left_map_transp.\nQed.\n\nTheorem nth_fold_left_map_transp_1 : ∀ A (la : list A) i sta len d,\n  i < length la\n  → i < sta ∨ sta + len < i\n  → nth i\n      (fold_left\n         (λ la' k,\n            map (λ j, nth (transposition k (k + 1) j) la' d)\n              (seq 0 (length la')))\n         (seq sta len) la) d =\n    nth i la d.\nProof.\nintros * Hi Hip.\ninduction len; [ easy | ].\nrewrite seq_S; cbn.\nrewrite fold_left_app; cbn.\nrewrite (List_map_nth' 0). 2: {\n  rewrite seq_length.\n  now rewrite length_fold_left_map_transp.\n}\nrewrite seq_nth. 2: {\n  now rewrite length_fold_left_map_transp.\n}\nrewrite Nat.add_0_l.\nunfold transposition.\ndo 2 rewrite if_eqb_eq_dec.\ndestruct (Nat.eq_dec i (sta + len)) as [His| His]; [ flia His Hip | ].\ndestruct (Nat.eq_dec i (sta + len + 1)) as [Hip1| Hip1]; [ flia Hip Hip1 | ].\napply IHlen.\nflia Hip His.\nQed.\n\nTheorem nth_fold_left_seq_gen : ∀ A (u : list A) i d n sta,\n  sta + n ≤ length u\n  → sta ≤ i < sta + n - 1\n  → nth i\n      (fold_left\n         (λ la' k,\n            map (λ j, nth (transposition k (k + 1) j) la' d)\n              (seq 0 (length la')))\n         (seq sta n) u) d =\n     nth (i + 1) u d.\nProof.\nintros * Hn Hi.\nrevert i Hi.\ninduction n; intros; [ flia Hi  | ].\nassert (H : sta + n ≤ length u) by flia Hn.\nspecialize (IHn H); clear H.\nrewrite <- Nat.add_sub_assoc in Hi; [ | flia ].\nrewrite Nat_sub_succ_1 in Hi.\nrewrite seq_S.\nrewrite fold_left_app.\ndestruct (Nat.eq_dec i (sta + n - 1)) as [Hin| Hin]. {\n  subst i.\n  rewrite Nat.sub_add; [ | flia Hi ].\n  cbn.\n  rewrite length_fold_left_map_transp.\n  rewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hn ].\n  rewrite seq_nth; [ | flia Hn ].\n  rewrite transposition_out; [ cbn | flia Hi | flia ].\n  destruct n; [ flia Hi | ].\n  rewrite <- Nat.add_sub_assoc; [ | flia ].\n  rewrite Nat_sub_succ_1.\n  rewrite seq_S; cbn.\n  rewrite fold_left_app; cbn.\n  rewrite length_fold_left_map_transp.\n  rewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hn ].\n  rewrite seq_nth; [ | flia Hn ].\n  rewrite transposition_1.\n  rewrite Nat.add_1_r.\n  rewrite nth_fold_left_map_transp_1; [ | flia Hn | right; flia ].\n  now rewrite <- Nat.add_succ_comm.\n}\ncbn.\nrewrite length_fold_left_map_transp.\nrewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hn Hi ].\nrewrite seq_nth; [ | flia Hn Hi ].\nrewrite transposition_out; [ cbn | flia Hi | flia Hi Hin ].\napply IHn.\nflia Hi Hin.\nQed.\n\nTheorem nth_fold_left_map_transp : ∀ A (la : list A) i sta len d,\n  nth i\n    (fold_left\n       (λ la' k,\n          map (λ j, nth (transposition k (k + 1) j) la' d)\n            (seq 0 (length la')))\n       (seq sta len) la) d =\n  if le_dec (length la) i then d\n  else if Nat.eq_dec i (sta + len) then nth sta la d\n  else if le_dec (length la) sta then nth i la d\n  else if le_dec (length la) (sta + len) then\n    nth i\n      (fold_left\n         (λ la' k,\n          map (λ j, nth (transposition k (k + 1) j) la' d)\n            (seq 0 (length la)))\n         (seq sta (length la - sta)) la) d\n  else\n    nth (i + Nat.b2n ((sta <=? i) && (i <=? sta + len))) la d.\nProof.\nintros.\ndestruct (le_dec (length la) i) as [Hi| Hi]. {\n  rewrite nth_overflow; [ easy | ].\n  now rewrite length_fold_left_map_transp.\n}\napply Nat.nle_gt in Hi.\ndestruct (Nat.eq_dec i (sta + len)) as [Hisl| Hisl]. {\n  subst i.\n  revert la sta d Hi.\n  induction len; intros. {\n    rewrite Nat.add_0_r in Hi |-*.\n    now destruct la.\n  }\n  cbn.\n  rewrite <- Nat.add_succ_comm in Hi.\n  rewrite <- Nat.add_succ_comm.\n  rewrite IHlen; [ | now rewrite List_map_seq_length ].\n  rewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hi ].\n  rewrite seq_nth; [ | flia Hi ].\n  rewrite Nat.add_0_l, Nat.add_1_r.\n  now rewrite transposition_2.\n}\nunfold Nat.b2n, \"&&\", negb.\ndestruct (le_dec (length la) sta) as [Hsla| Hsla]. {\n  rewrite List_fold_left_map_nth_len.\n  erewrite List_fold_left_ext_in. 2: {\n    intros j v Hj; apply in_seq in Hj.\n    erewrite map_ext_in. 2: {\n      intros k Hk; apply in_seq in Hk.\n      rewrite transposition_out; [ | flia Hsla Hj Hk | flia Hsla Hj Hk ].\n      easy.\n    }\n    easy.\n  }\n  specialize (List_seq_shift' sta 0 len) as H1; rewrite Nat.add_0_r in H1.\n  rewrite <- H1. clear H1.\n  rewrite List_fold_left_map.\n  rewrite <- List_fold_left_map_nth_len.\n  rewrite List_fold_left_nop_r.\n  rewrite seq_length.\n  rewrite repeat_apply_id. 2: {\n    intros u.\n    symmetry; apply List_map_nth_seq.\n  }\n  easy.\n}\napply Nat.nle_gt in Hsla.\ndestruct (le_dec (length la) (sta + len)) as [Hsl| Hsl]. {\n  replace len with (length la - sta + (sta + len - length la)) at 1\n    by flia Hsla Hsl.\n  rewrite seq_app.\n  rewrite fold_left_app.\n  rewrite Nat.add_comm, Nat.sub_add; [ | flia Hsla ].\n  rewrite List_fold_left_map_nth_len.\n  erewrite List_fold_left_ext_in. 2: {\n    intros j v Hj; apply in_seq in Hj.\n    erewrite map_ext_in. 2: {\n      intros k Hk; apply in_seq in Hk.\n      rewrite length_fold_left_map_transp in Hk.\n      rewrite transposition_out; [ | flia Hsla Hj Hk | flia Hsla Hj Hk ].\n      easy.\n    }\n    easy.\n  }\n  rewrite <- List_fold_left_map_nth_len.\n  rewrite List_fold_left_nop_r.\n  rewrite seq_length.\n  rewrite repeat_apply_id. 2: {\n    intros u.\n    symmetry; apply List_map_nth_seq.\n  }\n  now rewrite <- List_fold_left_map_nth_len.\n}\napply Nat.nle_gt in Hsl.\nrewrite if_leb_le_dec.\ndestruct (le_dec sta i) as [Hip| Hip]. 2: {\n  apply Nat.nle_gt in Hip.\n  rewrite Nat.add_0_r.\n  apply nth_fold_left_map_transp_1; [ easy | now left ].\n}\nrewrite if_leb_le_dec.\ndestruct (le_dec i (sta + len)) as [Hip'| Hip']. 2: {\n  apply Nat.nle_gt in Hip'.\n  rewrite Nat.add_0_r.\n  apply nth_fold_left_map_transp_1; [ easy | now right ].\n}\nassert (H : i < sta + len) by flia Hisl Hip'.\nclear Hisl Hip'; rename H into Hisl.\ndestruct (Nat.eq_dec i (length la - 1)) as [Hila| Hila]. {\n  flia Hsl Hisl Hila.\n}\ndestruct (Nat.eq_dec i (sta + len - 1)) as [Hisl1| Hisl1]. 2: {\n  rewrite nth_fold_left_seq_gen; [ easy | flia Hsl | flia Hip Hisl Hisl1 ].\n}\nrewrite Hisl1.\nrewrite Nat.sub_add; [ | flia Hisl ].\ndestruct len; [ flia Hip Hisl | ].\nrewrite seq_S.\nrewrite fold_left_app; cbn.\nrewrite <- Nat.add_sub_assoc; [ | flia ].\nrewrite Nat_sub_succ_1.\nrewrite length_fold_left_map_transp.\nrewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hsl ].\nrewrite seq_nth; [ | flia Hsl ].\nrewrite transposition_1.\nrewrite <- Nat.add_assoc, Nat.add_1_r.\napply nth_fold_left_map_transp_1; [ easy | right; flia ].\nQed.\n\nTheorem nth_fold_left_map_transp' : ∀ A (la : list A) i len d,\n  i + 1 < length la\n  → i < len\n  → nth i\n      (fold_left\n         (λ la' k,\n            map (λ j, nth (transposition k (k + 1) j) la' d)\n              (seq 0 (length la'))) \n         (seq 0 len) la) d =\n    nth (i + 1) la d.\nProof.\nintros * Hi Hpi.\nrewrite nth_fold_left_map_transp; cbn.\nrewrite Nat.sub_0_r.\ndestruct (le_dec (length la) i) as [H| H]; [ flia Hi H | clear H ].\ndestruct (Nat.eq_dec i len) as [H| H]; [ flia Hpi H | clear H ].\ndestruct (le_dec (length la) 0) as [H| H]; [ flia Hi H | clear H ].\ndestruct (le_dec (length la) len) as [Hll| Hll]. 2: {\n  apply Nat.nle_gt in Hll.\n  unfold Nat.b2n.\n  rewrite if_leb_le_dec.\n  destruct (le_dec i len) as [H| H]; [ easy | flia Hpi H ].\n}\nclear len Hpi Hll.\nrewrite <- List_fold_left_map_nth_len.\nrewrite nth_fold_left_seq_gen; [ easy | easy | flia Hi ].\nQed.\n\nTheorem subm_mat_swap_rows_circ : ∀ (M : matrix T) p q,\n  1 ≤ p ≤ mat_nrows M\n  → subm 1 q (mat_swap_rows 1 p M) =\n    subm p q\n      (fold_left (λ M' k, mat_swap_rows (k + 1) (k + 2) M')\n         (seq 0 (p - 2)) M).\nProof.\nintros * Hp.\ndestruct M as (ll); cbn in Hp |-*.\nunfold subm; f_equal.\ncbn - [ butn ].\nf_equal; clear q.\nrewrite fold_left_mat_fold_left_list_list.\ncbn - [ butn ].\nrewrite List_map_nth_seq with (d := []); symmetry.\nrewrite List_map_nth_seq with (d := []); symmetry.\nrewrite butn_length, map_length, seq_length.\nrewrite butn_length.\nrewrite length_fold_left_map_transp.\nunfold Nat.b2n.\ndo 2 rewrite if_ltb_lt_dec.\ndestruct (lt_dec 0 (length ll)) as [H| H]; [ clear H | flia H Hp ].\ndestruct (lt_dec (p - 1) (length ll)) as [H| H]; [ clear H | flia H Hp ].\napply map_ext_in.\nintros i Hi; apply in_seq in Hi.\ncbn in Hi.\nrewrite <- map_butn.\nrewrite (List_map_nth' 0). 2: {\n  rewrite butn_length, seq_length.\n  unfold Nat.b2n.\n  rewrite if_ltb_lt_dec.\n  destruct (lt_dec 0 (length ll)) as [H| H]; [ easy | flia Hp H ].\n}\nrewrite nth_butn_before; [ | flia ].\nrewrite seq_nth; [ cbn | flia Hi ].\nerewrite List_fold_left_ext_in. 2: {\n  intros j ll' Hj.\n  erewrite map_ext_in. 2: {\n    intros k Hk.\n    now rewrite Nat.add_sub, Nat.add_succ_r, Nat_sub_succ_1.\n  }\n  easy.\n}\ndestruct (le_dec (p - 1) i) as [Hpi| Hpi]. 2: {\n  apply Nat.nle_gt in Hpi.\n  rewrite nth_butn_after; [ | easy ].\n  rewrite nth_fold_left_map_transp; cbn.\n  rewrite Nat.sub_0_r.\n  destruct (le_dec (length ll) i) as [H| H]; [ flia Hi H | clear H ].\n  destruct (Nat.eq_dec i (p - 2)) as [Hip1| Hip1]. {\n    rewrite Hip1.\n    replace (p - 2 + 1) with (p - 1) by flia Hpi.\n    now rewrite transposition_2.\n  }\n  destruct (le_dec (length ll) 0) as [H| H]; [ flia Hp H | clear H ].\n  destruct (le_dec (length ll) (p - 2)) as [H| H]; [ flia Hp H | clear H ].\n  unfold transposition.\n  unfold Nat.b2n.\n  do 2 rewrite if_eqb_eq_dec.\n  rewrite if_leb_le_dec.\n  rewrite Nat.add_1_r.\n  destruct (Nat.eq_dec (S i) 0) as [H| H]; [ easy | clear H ].\n  destruct (Nat.eq_dec (S i) (p - 1)) as [H| H]; [ flia Hip1 H | clear H ].\n  destruct (le_dec i (p - 2)) as [H| H]; [ | flia Hpi H ].\n  now rewrite Nat.add_1_r.\n}\nrewrite transposition_out; [ | flia | flia Hpi ].\nrewrite nth_butn_before; [ | easy ].\nsymmetry.\nrewrite nth_fold_left_map_transp; cbn; rewrite Nat.sub_0_r.\ndestruct (le_dec (length ll) (i + 1)) as [H| H]; [ flia Hi H | clear H ].\ndestruct (Nat.eq_dec (i + 1) (p - 2)) as [H| H]; [ flia Hpi H | clear H ].\ndestruct (le_dec (length ll) 0) as [H| H]; [ flia Hp H | clear H ].\ndestruct (le_dec (length ll) (p - 2)) as [H| H]; [ flia Hp H | clear H ].\nunfold Nat.b2n.\nrewrite if_leb_le_dec.\ndestruct (le_dec (i + 1) (p - 2)) as [H| H]; [ flia Hpi H | clear H ].\nnow rewrite Nat.add_0_r.\nQed.\n\nTheorem subm_fold_left_lt : ∀ (M : matrix T) i j m,\n  m < i - 1\n  → subm i j\n      (fold_left (λ M' k, mat_swap_rows (k + 1) (k + 2) M')\n         (seq 0 m) M) =\n    fold_left\n      (λ M' k, mat_swap_rows (k + 1) (k + 2) M')\n      (seq 0 m) (subm i j M).\nProof.\nintros * Hmi.\nrevert i Hmi.\ninduction m; intros; [ easy | ].\nrewrite seq_S; cbn.\ndo 2 rewrite fold_left_app; cbn.\nrewrite <- IHm; [ | flia Hmi ].\napply subm_mat_swap_rows_lt; flia Hmi.\nQed.\n\nTheorem determinant_circular_shift_rows :\n  rngl_mul_is_comm = true →\n  rngl_has_opp = true →\n  ∀ (M : matrix T) i,\n  i < mat_nrows M\n  → is_square_matrix M = true\n  → det (fold_left (λ M' k, mat_swap_rows (k + 1) (k + 2) M') (seq 0 i) M) =\n    (minus_one_pow i * det M)%L.\nProof.\nintros Hic Hop * Hin Hsm.\nremember (mat_nrows M) as n eqn:Hr; symmetry in Hr.\nrevert M Hsm Hr.\ninduction i; intros; [ now cbn; rewrite rngl_mul_1_l | ].\nassert (H : i < n) by flia Hin.\nspecialize (IHi H); clear H.\nrewrite seq_S; cbn.\nrewrite fold_left_app; cbn - [ det ].\nrewrite determinant_alternating; [ | easy | easy | flia | | | ]; cycle 1. {\n  rewrite mat_nrows_fold_left_swap, Hr; flia Hin.\n} {\n  rewrite mat_nrows_fold_left_swap, Hr; flia Hin.\n} {\n  specialize (squ_mat_ncols _ Hsm) as Hc1.\n  apply is_scm_mat_iff.\n  apply is_scm_mat_iff in Hsm.\n  destruct Hsm as (Hcr & Hc).\n  rewrite Hr in Hc1.\n  rewrite mat_nrows_fold_left_swap.\n  split. {\n    intros Hc'.\n    unfold mat_ncols in Hc'.\n    rewrite fold_left_mat_fold_left_list_list in Hc'.\n    cbn in Hc'.\n    erewrite List_fold_left_ext_in in Hc'. 2: {\n      intros j ll' Hj.\n      erewrite map_ext_in. 2: {\n        intros k Hk.\n        now rewrite Nat.add_sub, Nat.add_succ_r, Nat_sub_succ_1.\n      }\n      easy.\n    }\n    apply length_zero_iff_nil in Hc'.\n    rewrite List_hd_nth_0 in Hc'.\n    rewrite nth_fold_left_map_transp in Hc'.\n    rewrite fold_mat_nrows in Hc'.\n    do 2 rewrite Nat.add_0_l in Hc'.\n    destruct (le_dec (mat_nrows M) 0) as [Hlz| Hlz]. {\n      now apply Nat.le_0_r in Hlz.\n    }\n    apply Nat.nle_gt in Hlz.\n    destruct (Nat.eq_dec 0 i) as [Hiz| Hiz]. {\n      subst i.\n      apply Hcr.\n      unfold mat_ncols.\n      rewrite List_hd_nth_0.\n      now rewrite Hc'.\n    }\n    rewrite Nat.sub_0_r in Hc'.\n    destruct (le_dec (mat_nrows M) i) as [Hri| Hri]. {\n      unfold mat_nrows in Hc'.\n      rewrite <- List_fold_left_map_nth_len in Hc'.\n      rewrite nth_fold_left_map_transp' in Hc'; cycle 1. {\n        rewrite fold_mat_nrows.\n        flia Hin Hr.\n      } {\n        now rewrite fold_mat_nrows.\n      }\n      cbn in Hc'.\n      apply (f_equal length) in Hc'.\n      rewrite Hc in Hc'. 2: {\n        apply nth_In.\n        rewrite fold_mat_nrows.\n        flia Hr Hin.\n      }\n      easy.\n    }\n    apply Nat.nle_gt in Hri.\n    cbn in Hc'.\n    apply (f_equal length) in Hc'.\n    rewrite Hc in Hc'. 2: {\n      apply nth_In.\n      rewrite fold_mat_nrows.\n      flia Hr Hin.\n    }\n    easy.\n  }\n  intros la Hla.\n  rewrite fold_left_mat_fold_left_list_list in Hla.\n  cbn in Hla.\n  apply In_nth with (d := []) in Hla.\n  rewrite length_fold_left_map_transp, fold_mat_nrows in Hla.\n  destruct Hla as (j & Hj & Hla).\n  erewrite List_fold_left_ext_in in Hla. 2: {\n    intros k ll' Hk.\n    erewrite map_ext_in. 2: {\n      intros l Hl.\n      now rewrite Nat.add_sub, Nat.add_succ_r, Nat_sub_succ_1.\n    }\n    easy.\n  }\n  rewrite nth_fold_left_map_transp in Hla.\n  rewrite fold_mat_nrows in Hla.\n  rewrite Nat.add_0_l in Hla.\n  destruct (le_dec (mat_nrows M) j) as [H| H]; [ flia Hj H | clear H ].\n  destruct (Nat.eq_dec j i) as [Hji| Hji]. {\n    subst la.\n    apply Hc, nth_In.\n    rewrite fold_mat_nrows; flia Hj.\n  }\n  destruct (le_dec (mat_nrows M) 0) as [H| H]; [ flia Hj H | clear H ].\n  destruct (le_dec (mat_nrows M) i) as [H| H]; [ flia Hin Hr H | clear H ].\n  subst la.\n  unfold Nat.b2n.\n  rewrite Bool.andb_if.\n  do 2 rewrite if_leb_le_dec.\n  destruct (le_dec 0 j) as [Hjz| Hjz]. {\n    destruct (le_dec j i) as [Hji'| Hji']. {\n      apply Hc, nth_In.\n      rewrite fold_mat_nrows.\n      rewrite Hr in Hj |-*.\n      flia Hji' Hin.\n    }\n    apply Nat.nle_gt in Hji'.\n    rewrite Nat.add_0_r.\n    apply Hc, nth_In.\n    now rewrite fold_mat_nrows.\n  }\n  now apply Nat.nle_gt in Hjz.\n}\nrewrite IHi; [ | easy | easy ].\nrewrite minus_one_pow_succ; [ | easy ].\nnow symmetry; apply rngl_mul_opp_l.\nQed.\n\nTheorem determinant_subm_mat_swap_rows_0_i :\n  rngl_mul_is_comm = true →\n  rngl_has_opp = true →\n  ∀ (M : matrix T) i j,\n  is_square_matrix M = true\n  → 1 < i ≤ mat_nrows M\n  → 1 ≤ j ≤ mat_nrows M\n  → det (subm 1 j (mat_swap_rows 1 i M)) =\n    (minus_one_pow i * det (subm i j M))%L.\nProof.\nintros Hic Hop * Hsm (Hiz, Hin) Hjn.\nrewrite subm_mat_swap_rows_circ. 2: {\n  split; [ flia Hiz | easy ].\n}\ndestruct i; [ flia Hiz | ].\nrewrite (minus_one_pow_succ Hop).\nreplace (S i - 2) with (i - 1) by flia.\nrewrite subm_fold_left_lt; [ | flia Hiz ].\nrewrite determinant_circular_shift_rows; [ | easy | easy | | ]. {\n  destruct i; [ flia Hiz | ].\n  rewrite Nat_sub_succ_1.\n  rewrite minus_one_pow_succ; [ | easy ].\n  now rewrite rngl_opp_involutive.\n} {\n  rewrite mat_nrows_subm.\n  generalize Hin; intros H.\n  apply Nat.leb_le in H; rewrite H; clear H; cbn.\n  flia Hin Hiz.\n}\napply is_squ_mat_subm; [ flia Hin | flia Hjn | easy ].\nQed.\n\n(* Laplace formulas *)\n\nTheorem laplace_formula_on_rows :\n  rngl_has_opp = true →\n  rngl_mul_is_comm = true →\n  ∀ (M : matrix T) i,\n  is_square_matrix M = true\n  → 1 ≤ i ≤ mat_nrows M\n  → det M = ∑ (j = 1, mat_ncols M), mat_el M i j * mat_el (com M) i j.\nProof.\nintros Hop Hic * Hsm Hlin.\nspecialize (squ_mat_ncols M Hsm) as Hc.\nrewrite Hc.\nspecialize (proj1 (is_scm_mat_iff _ M) Hsm) as H1.\ndestruct H1 as (Hcr & Hc').\ndestruct (Nat.eq_dec (mat_nrows M) 0) as [Hnz| Hnz]. {\n  rewrite Hnz in Hlin; flia Hlin.\n}\ndestruct (Nat.eq_dec i 1) as [Hi1| Hi1]. {\n  subst i; cbn.\n  symmetry.\n  unfold det.\n  replace (mat_nrows M) with (S (mat_nrows M - 1)) by flia Hnz.\n  cbn - [ butn ].\n  apply rngl_summation_eq_compat.\n  intros j Hj.\n  rewrite rngl_mul_comm; [ | easy ].\n  rewrite rngl_mul_mul_swap; [ | easy ].\n  rewrite (List_map_nth' 0); [ | rewrite seq_length, Hc; flia Hj Hnz ].\n  rewrite seq_nth; [ | rewrite Hc; flia Hj Hnz ].\n  rewrite map_length.\n  cbn - [ butn ].\n  rewrite <- Nat.sub_succ_l; [ | easy ].\n  rewrite Nat_sub_succ_1.\n  f_equal; f_equal.\n  rewrite butn_length, fold_mat_nrows.\n  apply Nat.neq_0_lt_0, Nat.ltb_lt in Hnz.\n  now rewrite Hnz.\n}\nunfold det.\nreplace (mat_nrows M) with (S (mat_nrows M - 1)) by flia Hnz.\nrewrite <- Nat.sub_succ_l; [ | flia Hnz ].\nrewrite Nat_sub_succ_1.\nsymmetry.\nerewrite rngl_summation_eq_compat. 2: {\n  intros j Hj.\n  cbn.\n  rewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hlin ].\n  rewrite (List_map_nth' 0); [ | rewrite seq_length, Hc; flia Hj Hnz ].\n  rewrite seq_nth; [ | flia Hlin ].\n  rewrite seq_nth; [ | flia Hj Hc Hnz ].\n  rewrite (Nat.add_comm 1), Nat.sub_add; [ | flia Hlin ].\n  rewrite (Nat.add_comm 1), Nat.sub_add; [ | easy ].\n  rewrite rngl_mul_comm; [ | easy ].\n  rewrite rngl_mul_mul_swap; [ | easy ].\n  easy.\n}\ncbn.\nrename i into p.\nremember (mat_swap_rows 1 p M) as M'.\nerewrite rngl_summation_eq_compat. 2: {\n  intros j Hj.\n  rewrite map_length, butn_length, fold_mat_nrows.\n  rewrite rngl_mul_mul_swap; [ | easy ].\n  rewrite Nat.add_comm.\n  rewrite minus_one_pow_add; [ | easy ].\n  do 2 rewrite <- rngl_mul_assoc.\n  rewrite rngl_mul_comm; [ | easy ].\n  rewrite rngl_mul_assoc.\n  specialize (determinant_subm_mat_swap_rows_0_i Hic Hop) as H1.\n  specialize (H1 M p j Hsm).\n  cbn - [ butn ] in H1.\n  rewrite map_length, map_butn, butn_length in H1.\n  rewrite list_swap_elem_length, fold_mat_nrows in H1.\n  rewrite butn_length, map_length, fold_mat_nrows in H1.\n  apply Nat.neq_0_lt_0, Nat.ltb_lt in Hnz.\n  rewrite Hnz in H1; cbn - [ \"<?\" ] in H1.\n  apply Nat.ltb_lt in Hnz.\n  rewrite <- H1; [ | flia Hi1 Hlin | flia Hj Hnz ].\n  clear H1.\n  rewrite rngl_mul_comm; [ | easy ].\n  rewrite rngl_mul_assoc, rngl_mul_mul_swap; [ | easy ].\n  replace (mat_el M p j) with (mat_el (mat_swap_rows 1 p M) 0 j). 2: {\n    unfold mat_swap_rows.\n    cbn; unfold list_swap_elem.\n    rewrite fold_mat_nrows.\n    rewrite (List_map_nth' 0); [ | now rewrite seq_length ].\n    rewrite seq_nth; [ | easy ].\n    rewrite Nat.add_0_r, transposition_1.\n    easy.\n  }\n  rewrite <- HeqM'.\n  easy.\n}\ncbn.\nsubst M'.\nrewrite <- rngl_opp_involutive; [ | easy ].\nrewrite fold_det.\nassert (H1 : 1 ≠ p) by flia Hlin Hi1.\nassert (H2 : p - 1 < mat_nrows M) by flia Hlin.\napply Nat.neq_0_lt_0 in Hnz.\nrewrite <- (determinant_alternating Hic Hop M H1); [ | easy | easy | easy ].\nunfold det.\nrewrite mat_swap_rows_nrows.\nremember (determinant_loop (mat_nrows M)) as x eqn:Hx.\nreplace (mat_nrows M) with (S (mat_nrows M - 1)) in Hx by flia Hlin.\nsubst x.\nrewrite determinant_succ.\nrewrite <- Nat.sub_succ_l; [ | flia Hnz ].\nrewrite Nat_sub_succ_1.\nrewrite rngl_opp_summation; [ | easy ].\napply rngl_summation_eq_compat.\nintros i Hi.\nrewrite <- rngl_mul_opp_l; [ | easy ].\nrewrite <- rngl_mul_opp_l; [ | easy ].\nrewrite minus_one_pow_succ; [ | easy ].\nrewrite rngl_opp_involutive; [ | easy ].\neasy.\nQed.\n\nTheorem map_permut_seq_permut_seq_with_len : ∀ n σ,\n  permut_seq_with_len n σ\n  → permut_seq_with_len n (map (λ i, nth i σ 0) (seq 0 n)).\nProof.\nintros * Hσ.\nsplit; [ | now rewrite List_map_seq_length ].\napply permut_seq_iff.\nsplit. {\n  intros i Hi.\n  apply in_map_iff in Hi.\n  destruct Hi as (j & Hji & Hj).\n  apply in_seq in Hj.\n  rewrite List_map_seq_length.\n  rewrite <- Hji.\n  destruct Hσ as (H1, H2).\n  rewrite <- H2 in Hj |-*.\n  apply permut_seq_ub; [ easy | now apply nth_In ].\n} {\n  apply (NoDup_map_iff 0).\n  rewrite seq_length.\n  intros i j Hi Hj Hij.\n  rewrite seq_nth in Hij; [ | easy ].\n  rewrite seq_nth in Hij; [ | easy ].\n  do 2 rewrite Nat.add_0_l in Hij.\n  destruct Hσ as (Hσa, Hσl).\n  apply permut_seq_iff in Hσa.\n  destruct Hσa as (Hσa, Hσn).\n  apply (NoDup_nat _ Hσn); [ congruence | congruence | easy ].\n}\nQed.\n\n(* https://proofwiki.org/wiki/Permutation_of_Determinant_Indices *)\n\nTheorem comatrix_nrows : ∀ M, mat_nrows (com M) = mat_nrows M.\nProof.\nintros.\nunfold com; cbn.\nnow rewrite List_map_seq_length.\nQed.\n\nTheorem comatrix_ncols : ∀ M, mat_ncols (com M) = mat_ncols M.\nProof.\nintros.\nunfold com.\nunfold mat_ncols; cbn.\ndestruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]. {\n  rewrite Hrz; cbn.\n  unfold mat_nrows in Hrz.\n  now apply length_zero_iff_nil in Hrz; rewrite Hrz.\n}\napply Nat.neq_0_lt_0 in Hrz.\nrewrite (List_map_hd 0); [ | now rewrite seq_length ].\nnow rewrite List_map_seq_length.\nQed.\n\nTheorem comatrix_is_square : ∀ M,\n  is_square_matrix M = true\n  → is_square_matrix (com M) = true.\nProof.\nintros * Hsm.\nspecialize (squ_mat_ncols _ Hsm) as Hc.\napply is_scm_mat_iff in Hsm.\napply is_scm_mat_iff.\nrewrite comatrix_ncols.\nrewrite comatrix_nrows.\nsplit; [ easy | ].\nintros l Hl.\napply in_map_iff in Hl.\ndestruct Hl as (i & Hil & Hi).\nnow rewrite <- Hil; rewrite List_map_seq_length.\nQed.\n\nTheorem comatrix_is_correct : ∀ M,\n  is_correct_matrix M = true\n  → is_correct_matrix (com M) = true.\nProof.\nintros * Hsm.\napply is_scm_mat_iff in Hsm.\napply is_scm_mat_iff.\nrewrite comatrix_ncols.\nrewrite comatrix_nrows.\nsplit; [ easy | ].\nintros l Hl.\napply in_map_iff in Hl.\ndestruct Hl as (i & Hil & Hi).\nnow rewrite <- Hil; rewrite List_map_seq_length.\nQed.\n\nTheorem comatrix_transpose :\n  rngl_mul_is_comm = true →\n  rngl_has_opp = true →\n  rngl_characteristic ≠ 1 →\n  ∀ M,\n  is_square_matrix M = true\n  → com M⁺ = (com M)⁺%M.\nProof.\nintros Hic Hop H10 * Hsm.\ndestruct (Nat.eq_dec (mat_ncols M) 0) as [Hcz| Hcz]. {\n  unfold mat_transp, com; cbn - [ det ].\n  rewrite Hcz; cbn.\n  unfold mat_ncols; cbn.\n  destruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]; [ now rewrite Hrz | ].\n  now replace (mat_nrows M) with (S (mat_nrows M - 1)) by flia Hrz.\n}\ndestruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]. {\n  unfold mat_ncols in Hcz.\n  unfold mat_nrows in Hrz.\n  apply length_zero_iff_nil in Hrz.\n  now rewrite Hrz in Hcz.\n}\napply Nat.neq_0_lt_0 in Hcz, Hrz.\nunfold mat_transp, com, mat_ncols; cbn - [ det ].\nf_equal.\nrewrite (List_map_hd 0); [ | now rewrite seq_length ].\nrewrite (List_map_hd 0); [ | now rewrite seq_length ].\ndo 4 rewrite map_length.\ndo 2 rewrite seq_length.\nrewrite fold_mat_ncols.\napply map_ext_in.\nintros i Hi; apply in_seq in Hi.\nassert (H : 1 ≤ i ≤ mat_ncols M) by flia Hi.\nclear Hi; rename H into Hi.\napply map_ext_in.\nintros j Hj; apply in_seq in Hj.\nassert (H : 1 ≤ j ≤ mat_nrows M) by flia Hj.\nclear Hj; rename H into Hj.\nassert (Hi' : i - 1 < mat_ncols M) by flia Hi.\nassert (Hj' : j - 1 < mat_nrows M) by flia Hj.\nmove j before i.\nrewrite (List_map_nth' 0); [ | now rewrite seq_length ].\nrewrite (List_map_nth' 0); [ | now rewrite seq_length ].\nrewrite seq_nth; [ | easy ].\nrewrite seq_nth; [ | easy ].\nrewrite (Nat.add_comm 1 (j - 1)), Nat.sub_add; [ | easy ].\nrewrite (Nat.add_comm 1 (i - 1)), Nat.sub_add; [ | easy ].\nrewrite Nat.add_comm; f_equal; symmetry.\nspecialize (@fold_mat_transp T ro M) as H1.\nnow apply det_subm_transp.\nQed.\n\nTheorem laplace_formula_on_cols :\n  rngl_has_opp = true →\n  rngl_mul_is_comm = true →\n  rngl_characteristic ≠ 1 →\n  ∀ (M : matrix T) j,\n  is_square_matrix M = true\n  → 1 ≤ j ≤ mat_ncols M\n  → det M = ∑ (i = 1, mat_nrows M), mat_el M i j * mat_el (com M) i j.\nProof.\nintros Hop Hic H10 * Hsm Hj.\nrewrite <- (determinant_transpose Hic Hop H10); [ | easy ].\nerewrite rngl_summation_eq_compat. 2: {\n  intros i Hi.\n  rewrite <- mat_transp_el; [ | | flia Hj | flia Hi ]. 2: {\n    now apply squ_mat_is_corr.\n  }\n  easy.\n}\ncbn - [ det mat_el ].\nspecialize (@laplace_formula_on_rows Hop Hic (M⁺)%M j) as H1.\nassert (H : is_square_matrix M⁺ = true) by now apply mat_transp_is_square.\nspecialize (H1 H); clear H.\nrewrite mat_transp_nrows in H1.\nrewrite mat_transp_ncols in H1.\nrewrite if_eqb_eq_dec in H1.\ndestruct (Nat.eq_dec (mat_ncols M) 0) as [Hcz| Hcz]. {\n  rewrite Hcz in Hj; flia Hj.\n}\nspecialize (H1 Hj).\nrewrite H1.\napply rngl_summation_eq_compat.\nintros i Hi.\nf_equal.\nsymmetry.\nrewrite (comatrix_transpose Hic Hop H10); [ | easy ].\nsymmetry.\napply mat_transp_el; [ | flia Hj | flia Hi ].\napply comatrix_is_correct.\nnow apply squ_mat_is_corr.\nQed.\n\n(*\nThe following two theorems, \"determinant_with_row\" and determinant_with_bad_row\nhave some similitudes.\n  The theorem \"determinant_with_row\" says that we can compute the determinant\nby going through any row (not necessarily the 0th one). Here, row \"i\".\n  The theorem \"determinant_with_bad_row\" says that if we go through another\nrow \"k\" different from \"i\", the same formula (where \"M i j\" is replaced\nwith \"M k j\") returns 0. It is what I call a \"bad determinant formula\".\n\ndeterminant_with_row\n  ∀ (i n : nat) (M : matrix (S n) (S n) T),\n  i ≤ n\n  → ∑ (j = 1, n), minus_one_pow (i + j) * M i j * det (subm M i j) = det M\n\ndeterminant_with_bad_row\n  ∀ (i k n : nat) (M : matrix (S n) (S n) T),\n  i ≤ n → k ≤ n → i ≠ k\n  → ∑ (j = 1, n), minus_one_pow (i + j) * M k j * det (subm M i j) = 0%L\n*)\n\nTheorem determinant_with_row :\n  rngl_has_opp = true →\n  rngl_mul_is_comm = true →\n  ∀ i (M : matrix T),\n  is_square_matrix M = true\n  → 1 ≤ i ≤ mat_nrows M\n  → det M =\n    ∑ (j = 1, mat_nrows M),\n    minus_one_pow (i + j) * mat_el M i j * det (subm i j M).\nProof.\nintros Hop Hic * Hsm Hir.\ndestruct (Nat.eq_dec i 1) as [Hi1| Hi1]. {\n  subst i; cbn - [ det ].\n  unfold det.\n  erewrite rngl_summation_eq_compat. 2: {\n    intros i Hi.\n    rewrite mat_nrows_subm.\n    easy.\n  }\n  cbn.\n  replace (mat_nrows M) with (S (mat_nrows M - 1)) by flia Hir.\n  rewrite determinant_succ.\n  now cbn; rewrite Nat.sub_0_r.\n}\napply rngl_opp_inj; [ easy | ].\nrewrite <- (determinant_alternating Hic Hop M Hi1); [ | easy | flia Hir | easy ].\nunfold det at 1.\nrewrite mat_swap_rows_nrows.\nreplace (mat_nrows M) with (S (mat_nrows M - 1)) at 1 by flia Hir.\nrewrite determinant_succ.\nrewrite <- Nat.sub_succ_l; [ | flia Hir ].\nrewrite Nat_sub_succ_1.\nrewrite rngl_opp_summation; [ | easy ].\napply rngl_summation_eq_compat.\nintros j Hj.\nrewrite <- rngl_mul_assoc; symmetry.\nrewrite <- rngl_mul_opp_r; [ | easy ].\nrewrite (Nat.add_comm i j).\nrewrite minus_one_pow_add; [ | easy ].\nrewrite rngl_mul_opp_r; [ | easy ].\nrewrite <- rngl_mul_opp_l; [ | easy ].\nrewrite <- rngl_mul_opp_l; [ | easy ].\nrewrite <- rngl_mul_opp_l; [ | easy ].\ndo 2 rewrite <- rngl_mul_assoc.\nrewrite minus_one_pow_succ; [ | easy ].\nf_equal.\nrewrite (minus_one_pow_mul_comm Hop).\nrewrite <- rngl_mul_assoc.\nrewrite mat_el_mat_swap_rows; [ | flia Hj ].\nf_equal.\nrewrite <- (minus_one_pow_mul_comm Hop).\nsymmetry.\nrewrite mat_swap_rows_comm.\nrewrite <- determinant_subm_mat_swap_rows_0_i; try easy; [ | flia Hir Hi1 ].\nunfold det.\nrewrite mat_nrows_subm.\nrewrite mat_swap_rows_nrows.\nassert (H : 1 ≤ mat_nrows M) by flia Hir.\nnow apply Nat.leb_le in H; rewrite H.\nQed.\n\nTheorem determinant_with_bad_row :\n  rngl_has_opp = true →\n  rngl_mul_is_comm = true →\n  rngl_characteristic = 0 →\n  (rngl_is_integral || rngl_has_inv_or_quot)%bool = true →\n  ∀ i k (M : matrix T),\n  is_square_matrix M = true\n  → 1 ≤ i ≤ mat_nrows M\n  → 1 ≤ k ≤ mat_nrows M\n  → i ≠ k\n  → ∑ (j = 1, mat_nrows M),\n    minus_one_pow (i + j) * mat_el M k j * det (subm i j M) = 0%L.\nProof.\nintros Hop Hic Hch Hii * Hsm Hir Hkr Hik.\nspecialize (squ_mat_ncols _ Hsm) as Hc.\nremember\n  (mk_mat\n     (map\n        (λ p,\n         map (λ q, mat_el M (if p =? i then k else p) q)\n           (seq 1 (mat_ncols M)))\n        (seq 1 (mat_nrows M))))\n  as A eqn:HA.\nassert (Hasm : is_square_matrix A = true). {\n  subst A.\n  apply is_scm_mat_iff; cbn.\n  unfold mat_ncols; cbn.\n  rewrite List_map_seq_length.\n  rewrite (List_map_hd 0); [ | rewrite seq_length; flia Hir ].\n  rewrite List_map_seq_length.\n  rewrite fold_mat_ncols.\n  apply is_scm_mat_iff in Hsm.\n  split; [ easy | ].\n  intros l Hl.\n  apply in_map_iff in Hl.\n  destruct Hl as (j & Hjl & Hj).\n  apply in_seq in Hj.\n  now rewrite <- Hjl, List_map_seq_length.\n}\nassert (Hira : mat_nrows A = mat_nrows M). {\n  now subst A; cbn; rewrite List_map_seq_length.\n}\nassert (H1 : det A = 0%L). {\n  apply (determinant_same_rows Hic Hop Hch Hii) with (p := i) (q := k). {\n    easy.\n  } {\n    easy.\n  } {\n    now rewrite Hira.\n  } {\n    now rewrite Hira.\n  }\n  intros j; subst A; cbn.\n  rewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hir ].\n  symmetry.\n  rewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hkr ].\n  f_equal.\n  apply map_ext_in.\n  intros u Hu; apply in_seq in Hu.\n  rewrite seq_nth; [ | flia Hkr ].\n  rewrite seq_nth; [ | flia Hir ].\n  rewrite Nat.add_comm, Nat.sub_add; [ | easy ].\n  rewrite Nat.add_comm, Nat.sub_add; [ | easy ].\n  cbn; rewrite Nat.eqb_refl.\n  apply Nat.neq_sym, Nat.eqb_neq in Hik.\n  now rewrite Hik.\n}\nrewrite (determinant_with_row Hop Hic) with (i := i) in H1; [ | easy | ]. 2: {\n  now rewrite Hira.\n}\nrewrite <- H1 at 2.\nrewrite Hira.\napply rngl_summation_eq_compat.\nintros j Hj.\ndo 2 rewrite <- rngl_mul_assoc.\nf_equal; f_equal. {\n  rewrite HA; cbn.\n  rewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hir ].\n  rewrite (List_map_nth' 0); [ | rewrite seq_length, Hc; flia Hj Hir ].\n  rewrite seq_nth; [ | flia Hir ].\n  rewrite seq_nth; [ | rewrite Hc; flia Hj Hir ].\n  rewrite Nat.add_comm, Nat.sub_add; [ | easy ].\n  rewrite Nat.add_comm, Nat.sub_add; [ | easy ].\n  now rewrite Nat.eqb_refl.\n}\n(* oops... complicated from now! doing a lemma, perhaps? *)\nunfold subm; cbn.\ndo 2 rewrite map_length.\ndo 2 rewrite butn_length.\ndo 2 rewrite fold_mat_nrows.\nrewrite Hira.\nf_equal; f_equal; f_equal.\nrewrite HA; cbn.\ndestruct M as (ll); cbn in Hir, Hj |-*.\nunfold mat_ncols; cbn.\nremember (seq 1 (length (hd [] ll))) as x eqn:Hx.\nrewrite List_seq_cut3 with (i := i); [ subst x | apply in_seq; flia Hir ].\nrewrite Nat.sub_succ.\ndo 2 rewrite map_app; cbn.\nrewrite Nat.eqb_refl.\nerewrite map_ext_in. 2: {\n  intros u Hu; apply in_seq in Hu.\n  replace (u =? i) with false. 2: {\n    symmetry; apply Nat.eqb_neq; flia Hu.\n  }\n  easy.\n}\nerewrite map_ext_in with (l := seq (S i) _). 2: {\n  intros u Hu; apply in_seq in Hu.\n  replace (u =? i) with false. 2: {\n    symmetry; apply Nat.eqb_neq; flia Hu.\n  }\n  easy.\n}\nrewrite List_map_nth_seq with (la := ll) (d := []) at 1.\nrewrite List_seq_cut3 with (i := i - 1); [ | apply in_seq; flia Hir ].\nrewrite <- Nat.sub_succ_l; [ | easy ].\nrewrite Nat_sub_succ_1, Nat.add_0_l, Nat.sub_0_r.\ndo 2 rewrite map_app.\ndo 3 rewrite butn_app.\ndo 2 rewrite List_map_seq_length.\nrewrite Nat.ltb_irrefl.\nrewrite Nat.sub_diag.\nrewrite map_length.\nreplace (0 <? length [i - 1]) with true by easy.\nrewrite <- map_butn.\nrewrite app_nil_l.\nremember (butn 0 _) as x; cbn in Heqx; subst x.\nf_equal. {\n  rewrite <- (seq_shift (i - 1)), map_map.\n  apply map_ext_in.\n  intros u Hu; apply in_seq in Hu.\n  rewrite Nat_sub_succ_1.\n  rewrite List_map_nth_seq with (d := 0%L) (la := nth u ll []).\n  apply is_scm_mat_iff in Hsm.\n  destruct Hsm as (Hcr, Hcl).\n  cbn in Hcl.\n  rewrite List_hd_nth_0.\n  rewrite Hcl; [ | apply nth_In; flia Hu Hir ].\n  rewrite Hcl; [ | apply nth_In; flia Hu Hir ].\n  rewrite <- (seq_shift (length ll) 0), map_map.\n  apply map_ext_in.\n  intros v Hv; apply in_seq in Hv.\n  rewrite Nat_sub_succ_1.\n  rewrite List_map_nth_seq with (la := nth u ll []) (d := 0%L) at 1.\n  f_equal; f_equal; f_equal.\n  apply Hcl, nth_In; flia Hu Hir.\n} {\n  rewrite <- (seq_shift _ i), map_map.\n  apply map_ext_in.\n  intros u Hu; apply in_seq in Hu.\n  rewrite Nat_sub_succ_1.\n  rewrite List_map_nth_seq with (d := 0%L) (la := nth u ll []).\n  apply is_scm_mat_iff in Hsm.\n  destruct Hsm as (Hcr, Hcl).\n  cbn in Hcl.\n  rewrite List_hd_nth_0.\n  rewrite Hcl; [ | apply nth_In; flia Hu ].\n  rewrite Hcl; [ | apply nth_In; flia Hu ].\n  rewrite <- (seq_shift _ 0), map_map.\n  apply map_ext_in.\n  intros v Hv; apply in_seq in Hv.\n  rewrite Nat_sub_succ_1.\n  rewrite List_map_nth_seq with (la := nth u ll []) (d := 0%L) at 1.\n  f_equal; f_equal; f_equal.\n  apply Hcl, nth_In; flia Hu.\n}\nQed.\n\nTheorem matrix_comatrix_transp_mul :\n  rngl_has_opp = true →\n  rngl_mul_is_comm = true →\n  rngl_characteristic = 0 →\n  (rngl_is_integral || rngl_has_inv_or_quot)%bool = true →\n  ∀ (M : matrix T),\n  is_square_matrix M = true\n  → (M * (com M)⁺ = det M × mI (mat_nrows M))%M.\nProof.\nintros Hop Hic Hch Hii * Hsm.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\ndestruct M as (ll); cbn - [ det ].\nunfold \"*\"%M, \"×\"%M, mat_nrows; cbn - [ det ]; f_equal.\nrewrite map_map.\nrewrite <- (seq_shift (length ll)).\nrewrite map_map.\napply map_ext_in.\nintros i Hi; apply in_seq in Hi.\nassert (Hll : 0 < length ll) by flia Hi.\nrewrite laplace_formula_on_rows with (i := S i); try easy. 2: {\n  cbn; flia Hi.\n}\ncbn - [ mat_el ].\nrewrite mat_transp_ncols.\nrewrite comatrix_nrows, comatrix_ncols.\nunfold mat_ncols.\ncbn - [ mat_el mat_nrows com ].\napply is_scm_mat_iff in Hsm.\ndestruct Hsm as (Hcr, Hcl).\ncbn in Hcl.\nrewrite Hcl; [ | now apply List_hd_in ].\napply Nat.neq_0_lt_0 in Hll.\napply Nat.eqb_neq in Hll; rewrite Hll.\napply Nat.eqb_neq in Hll.\napply Nat.neq_0_lt_0 in Hll.\nrewrite map_map.\nrewrite <- seq_shift, map_map.\napply map_ext_in.\nintros j Hj; apply in_seq in Hj.\nmove j before i.\nerewrite rngl_summation_eq_compat. 2: {\n  intros k Hk.\n  assert (Hkc : k - 1 < mat_ncols {| mat_list_list := ll |}). {\n    unfold mat_ncols; cbn.\n    rewrite Hcl; [ flia Hk Hll | ].\n    now apply List_hd_in.\n  }\n  cbn - [ det ].\n  rewrite Nat.sub_0_r.\n  rewrite (List_map_nth' 0); [ | now rewrite seq_length ].\n  rewrite (List_map_nth' 0); [ | now rewrite seq_length ].\n  rewrite seq_nth; [ | easy ].\n  rewrite seq_nth; [ | easy ].\n  rewrite (Nat.add_comm 1 (k - 1)).\n  rewrite Nat.sub_add; [ | easy ].\n  rewrite rngl_mul_assoc.\n  easy.\n}\ncbn - [ det ].\ndestruct (Nat.eq_dec i j) as [Hij| Hij]. {\n  (* diagonal *)\n  subst j; rewrite δ_diag, rngl_mul_1_r.\n  unfold mat_mul_el.\n  unfold mat_ncols.\n  rewrite Hcl; [ | now apply List_hd_in ].\n  apply rngl_summation_eq_compat.\n  intros k Hk.\n  unfold mat_el.\n  rewrite Nat_sub_succ_1.\n  rewrite <- rngl_mul_assoc; f_equal.\n  cbn - [ det ].\n  rewrite List_map_seq_length.\n  rewrite (List_map_nth' 0). 2: {\n    rewrite seq_length.\n    unfold mat_ncols; cbn.\n    rewrite (List_map_hd 0); [ | now rewrite seq_length ].\n    rewrite List_map_seq_length.\n    unfold mat_ncols.\n    rewrite Hcl; [ flia Hk Hll | ].\n    now apply List_hd_in.\n  }\n  rewrite (List_map_nth' 0); [ | now rewrite seq_length ].\n  rewrite seq_nth. 2: {\n    rewrite comatrix_ncols.\n    unfold mat_ncols; cbn.\n    rewrite Hcl; [ flia Hk Hll | ].\n    now apply List_hd_in.\n  }\n  rewrite (List_map_nth' 0). 2: {\n    rewrite seq_length, seq_nth; [ | easy ].\n    now rewrite Nat.add_comm, Nat.add_sub.\n  }\n  rewrite Nat.add_comm, Nat.add_sub.\n  rewrite (List_map_nth' 0). 2: {\n    unfold mat_ncols.\n    rewrite seq_length; cbn.\n    rewrite Hcl; [ flia Hk Hll | ].\n    now apply List_hd_in.\n  }\n  rewrite seq_nth. 2: {\n    rewrite seq_nth; [ | easy ].\n    now rewrite Nat.add_comm, Nat.add_sub.\n  }\n  rewrite seq_nth; [ | easy ].\n  rewrite seq_nth. 2: {\n    unfold mat_ncols; rewrite Hcl; [ flia Hk Hll | ].\n    now apply List_hd_in.\n  }\n  rewrite (Nat.add_comm 1 i), Nat.add_sub.\n  now rewrite (Nat.add_comm 1 (k - 1)), Nat.sub_add.\n} {\n  (* not on diagonal: zeroes *)\n  rewrite δ_ndiag; [ | easy ].\n  rewrite rngl_mul_0_r; [ | easy ].\n  unfold mat_transp.\n  unfold mat_mul_el.\n  cbn - [ com ].\n  erewrite rngl_summation_eq_compat. 2: {\n    intros k Hk.\n    unfold mat_ncols in Hk; cbn in Hk.\n    rewrite Hcl in Hk; [ | now apply List_hd_in ].\n    rewrite (List_map_nth' 0). 2: {\n      rewrite seq_length, comatrix_ncols.\n      unfold mat_ncols.\n      rewrite Hcl; [ flia Hk Hi | ].\n      now apply List_hd_in.\n    }\n    do 2 rewrite Nat.sub_0_r.\n    rewrite (List_map_nth' 0). 2: {\n      now rewrite comatrix_nrows, seq_length.\n    }\n    rewrite seq_nth; [ | now rewrite comatrix_nrows ].\n    rewrite seq_nth. 2: {\n      rewrite comatrix_ncols; unfold mat_ncols; cbn.\n      rewrite Hcl; [ flia Hk Hi | now apply List_hd_in ].\n    }\n    cbn - [ com ].\n    easy.\n  }\n  cbn - [ com ].\n  unfold mat_ncols.\n  rewrite Hcl; [ | now apply List_hd_in ].\n  remember (mk_mat ll) as M eqn:HM.\n  erewrite rngl_summation_eq_compat. 2: {\n    intros k Hk.\n    rewrite HM at 1.\n    cbn - [ det ].\n    do 2 rewrite Nat.sub_0_r.\n    rewrite (List_map_nth' 0); [ | now rewrite seq_length ].\n    rewrite (List_map_nth' 0). 2: {\n      rewrite seq_length; unfold mat_ncols.\n      rewrite Hcl; [ flia Hk Hll | ].\n      now apply List_hd_in.\n    }\n    rewrite seq_nth; [ | easy ].\n    rewrite seq_nth. 2: {\n      unfold mat_ncols.\n      rewrite Hcl; [ flia Hk Hll | ].\n      now apply List_hd_in.\n    }\n    cbn - [ det ].\n    rewrite rngl_mul_comm; [ | easy ].\n    rewrite rngl_mul_mul_swap; [ | easy ].\n    replace ll with (mat_list_list M) at 1 by now rewrite HM.\n    rewrite fold_mat_el.\n    rewrite <- HM.\n    easy.\n  }\n  cbn - [ det ].\n  replace (length ll) with (mat_nrows M) in Hi, Hj, Hcl |-* by now rewrite HM.\n  apply Nat.neq_sym in Hij.\n  erewrite rngl_summation_eq_compat. 2: {\n    intros k Hk.\n    rewrite <- Nat.sub_succ_l; [ | easy ].\n    now rewrite Nat_sub_succ_1.\n  }\n  cbn - [ det ].\n  specialize (determinant_with_bad_row Hop Hic Hch Hii) as H1.\n  specialize (H1 (S j) (S i) M).\n  apply H1; [ | flia Hj | flia Hi | flia Hij ].\n  apply is_scm_mat_iff; cbn.\n  split; [ easy | ].\n  intros l Hl; rewrite HM in Hl; cbn in Hl.\n  now apply Hcl.\n}\nQed.\n\nTheorem comatrix_transp_matrix_mul :\n  rngl_has_opp = true →\n  rngl_mul_is_comm = true →\n  rngl_characteristic = 0 →\n  (rngl_is_integral || rngl_has_inv_or_quot)%bool = true →\n  ∀ (M : matrix T),\n  is_square_matrix M = true\n  → ((com M)⁺ * M = det M × mI (mat_nrows M))%M.\nProof.\nintros Hop Hic Hch Hii * Hsm.\nassert (H10 : rngl_characteristic ≠ 1) by now rewrite Hch.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\ndestruct M as (ll); cbn - [ det ].\ndestruct (Nat.eq_dec (length ll) 0) as [Hlz| Hlz]. {\n  apply length_zero_iff_nil in Hlz; subst ll; cbn.\n  unfold \"*\"%M, mI; cbn; symmetry.\n  apply mat_mul_scal_1_l.\n}\napply Nat.neq_0_lt_0 in Hlz.\ndestruct (Nat.eq_dec (length ll) 1) as [Hl1| Hl1]. {\n  destruct ll as [| l]; [ easy | ].\n  destruct ll; [ clear Hl1 | easy ].\n  apply is_scm_mat_iff in Hsm.\n  unfold mat_ncols in Hsm; cbn - [ In ] in Hsm.\n  destruct Hsm as (_, Hcl).\n  unfold \"*\"%M, \"×\"%M, mat_transp, mat_mul_el, com; cbn.\n  rewrite Hcl; [ cbn | now left ].\n  do 2 rewrite rngl_summation_only_one; cbn.\n  do 2 rewrite rngl_mul_1_l.\n  now do 2 rewrite rngl_mul_1_r.\n}\nunfold \"*\"%M, \"×\"%M, mat_nrows; cbn - [ det ]; f_equal.\nrewrite map_map.\nrewrite List_map_seq_length.\nrewrite comatrix_ncols.\ngeneralize Hsm; intros Hsm_v.\napply is_scm_mat_iff in Hsm.\ncbn in Hsm.\ndestruct Hsm as (Hcr, Hcl).\nunfold mat_ncols at 2.\nrewrite Hcl; [ | now apply List_hd_in ].\nrewrite <- (seq_shift (length ll)), map_map.\napply map_ext_in.\nintros i Hi; apply in_seq in Hi.\nunfold mat_ncols.\nrewrite Hcl; [ | now apply List_hd_in ].\nrewrite map_map.\nrewrite <- seq_shift, map_map.\napply map_ext_in.\nintros j Hj; apply in_seq in Hj.\nmove j before i.\nrewrite laplace_formula_on_cols with (j := S j); try easy. 2: {\n  rewrite squ_mat_ncols; [ cbn | easy ].\n  flia Hj.\n}\nunfold mat_mul_el.\nrewrite mat_transp_ncols.\nrewrite comatrix_ncols.\nunfold mat_ncols.\nrewrite Hcl; [ | now apply List_hd_in ].\nrewrite comatrix_nrows.\ncbn - [ mat_el com ].\napply Nat.neq_0_lt_0 in Hlz.\napply Nat.eqb_neq in Hlz; rewrite Hlz.\napply Nat.eqb_neq, Nat.neq_0_lt_0 in Hlz.\ndestruct (Nat.eq_dec i j) as [Hij| Hij]. {\n  (* diagonal *)\n  subst j; rewrite δ_diag, rngl_mul_1_r.\n  erewrite rngl_summation_eq_compat. 2: {\n    intros k Hk.\n    rewrite rngl_mul_comm; [ | easy ].\n    easy.\n  }\n  cbn - [ mat_el com ].\n  apply rngl_summation_eq_compat.\n  intros k Hk.\n  symmetry; f_equal; rewrite mat_transp_el; [ easy | | easy | flia Hk ].\n  apply squ_mat_is_corr.\n  now apply comatrix_is_square.\n} {\n  (* not on diagonal: zeroes *)\n  rewrite δ_ndiag; [ | easy ].\n  rewrite rngl_mul_0_r; [ | easy ].\n  unfold mat_transp.\n  cbn - [ com ].\n  erewrite rngl_summation_eq_compat. 2: {\n    intros k Hk.\n    rewrite (List_map_nth' 0). 2: {\n      rewrite seq_length, comatrix_ncols.\n      unfold mat_ncols.\n      rewrite Hcl; [ flia Hk Hi | ].\n      now apply List_hd_in.\n    }\n    rewrite (List_map_nth' 0). 2: {\n      rewrite seq_length, comatrix_nrows; cbn.\n      flia Hk Hlz.\n    }\n    rewrite seq_nth; [ | rewrite comatrix_nrows; cbn; flia Hk Hlz ].\n    rewrite seq_nth. 2: {\n      rewrite comatrix_ncols; unfold mat_ncols; cbn.\n      rewrite Hcl; [ flia Hk Hi | now apply List_hd_in ].\n    }\n    cbn - [ com ].\n    easy.\n  }\n  cbn - [ com ].\n  remember (mk_mat ll) as M eqn:HM.\n  erewrite rngl_summation_eq_compat. 2: {\n    intros k Hk.\n    do 2 rewrite Nat.sub_0_r.\n    rewrite <- Nat.sub_succ_l; [ | easy ].\n    rewrite Nat_sub_succ_1.\n    rewrite HM at 1.\n    cbn - [ det ].\n    rewrite Nat.sub_0_r.\n    rewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hk Hlz ].\n    rewrite (List_map_nth' 0). 2: {\n      rewrite seq_length; unfold mat_ncols.\n      rewrite Hcl; [ easy | ].\n      now apply List_hd_in.\n    }\n    rewrite seq_nth; [ | flia Hk Hlz ].\n    rewrite (Nat.add_comm 1 (k - 1)), Nat.sub_add; [ | easy ].\n    rewrite seq_nth. 2: {\n      unfold mat_ncols.\n      rewrite Hcl; [ easy | ].\n      now apply List_hd_in.\n    }\n    cbn - [ det ].\n    rewrite rngl_mul_mul_swap; [ | easy ].\n    replace ll with (mat_list_list M) at 1 by now rewrite HM.\n    rewrite fold_mat_el.\n    rewrite <- HM.\n    easy.\n  }\n  cbn - [ det ].\n  replace (length ll) with (mat_nrows M) in Hi, Hj, Hcl |-* by now rewrite HM.\n  destruct Hi as (_, Hi); cbn in Hi.\n  destruct Hj as (_, Hj); cbn in Hj.\n  (* perhaps all of this below would be a \"determinant_with_bad_col\":\n     perhaps a cool lemma to do? *)\n  specialize (determinant_with_bad_row Hop Hic Hch Hii) as H1.\n  specialize (H1 (S i) (S j) (M⁺)%M).\n  assert (Hsmt : is_square_matrix M⁺ = true). {\n    now apply mat_transp_is_square.\n  }\n  specialize (H1 Hsmt).\n  rewrite mat_transp_nrows in H1.\n  rewrite squ_mat_ncols in H1; [ | easy ].\n  assert (H : 1 ≤ S i ≤ mat_nrows M) by flia Hi.\n  specialize (H1 H); clear H.\n  assert (H : 1 ≤ S j ≤ mat_nrows M) by flia Hj.\n  specialize (H1 H); clear H.\n  assert (H : S i ≠ S j) by flia Hij.\n  specialize (H1 H); clear H.\n  erewrite rngl_summation_eq_compat in H1. 2: {\n    intros k Hk.\n    rewrite <- determinant_transpose; [ | easy | easy | easy | ]. 2: {\n      apply is_squ_mat_subm. {\n        rewrite mat_transp_nrows, squ_mat_ncols; [ | easy ].\n        flia Hk Hi.\n      } {\n        rewrite mat_transp_nrows, squ_mat_ncols; [ | easy ].\n        flia Hk Hi.\n      }\n      now apply mat_transp_is_square.\n    }\n    rewrite mat_subm_transp; cycle 1. {\n      now apply mat_transp_is_square.\n    } {\n      rewrite mat_transp_ncols.\n      assert (H : (mat_ncols M =? 0) = false). {\n        rewrite squ_mat_ncols; [ | easy ].\n        apply Nat.eqb_neq; flia Hi.\n      }\n      now rewrite H.\n    } {\n      rewrite mat_transp_nrows.\n      split; [ flia | ].\n      rewrite squ_mat_ncols; [ | easy ].\n      flia Hi.\n    }\n    rewrite mat_transp_involutive. 2: {\n      now apply squ_mat_is_corr.\n    } \n    rewrite mat_transp_el; [ | now apply squ_mat_is_corr | easy | flia Hk ].\n    rewrite Nat.add_comm.\n    easy.\n  }\n  cbn - [ det ] in H1.\n  erewrite rngl_summation_eq_compat. 2: {\n    intros k Hk.\n    rewrite <- Nat.sub_succ_l; [ | easy ].\n    now rewrite Nat_sub_succ_1.\n  }\n  easy.\n}\nQed.\n\nDefinition mat_inv (M : matrix T) := ((det M)⁻¹ × (com M)⁺)%M.\n\nTheorem mat_mul_inv_r : in_charac_0_field →\n  ∀ (M : matrix T),\n  is_square_matrix M = true\n  → det M ≠ 0%L\n  → (M * mat_inv M = mI (mat_nrows M))%M.\nProof.\nintros Hif * Hsm Hdz.\ndestruct Hif as (Hic, Hop, Hin, Hit, Hde, Hch).\ndestruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]. {\n  rewrite Hrz; cbn.\n  unfold mat_nrows in Hrz.\n  apply length_zero_iff_nil in Hrz.\n  now destruct M as (ll); cbn in Hrz; subst ll.\n}\nunfold mat_inv.\nrewrite (mat_mul_mul_scal_l Hop Hic); cycle 1. {\n  apply squ_mat_is_corr.\n  apply mat_transp_is_square.\n  now apply comatrix_is_square.\n} {\n  apply is_scm_mat_iff in Hsm.\n  destruct Hsm as (Hcr, Hcl).\n  now intros H; apply Hrz, Hcr.\n} {\n  rewrite mat_transp_nrows; symmetry.\n  apply comatrix_ncols.\n}\nrewrite (matrix_comatrix_transp_mul Hop Hic Hch); [ | | easy ]. 2: {\n  now apply Bool.orb_true_iff; left.\n}\nrewrite mat_mul_scal_l_mul_assoc.\nrewrite rngl_mul_inv_l; [ | easy | easy ].\nnow apply mat_mul_scal_1_l.\nQed.\n\nTheorem mat_mul_inv_l : in_charac_0_field →\n  ∀ (M : matrix T),\n  is_square_matrix M = true\n  → det M ≠ 0%L\n  → (mat_inv M * M = mI (mat_nrows M))%M.\nProof.\nintros Hif * Hsm Hdz.\ndestruct Hif as (Hic, Hop, Hin, Hit, Hde, Hch).\nunfold mat_inv.\nrewrite mat_mul_scal_l_mul; [ | easy | ]. 2: {\n  apply squ_mat_is_corr.\n  apply mat_transp_is_square.\n  now apply comatrix_is_square.\n}\nrewrite (comatrix_transp_matrix_mul Hop Hic Hch); [ | | easy ]. 2: {\n  now apply Bool.orb_true_iff; left.\n}\nrewrite mat_mul_scal_l_mul_assoc.\nrewrite rngl_mul_inv_l; [ | easy | easy ].\nnow apply mat_mul_scal_1_l.\nQed.\n\nNotation \"A ⁻¹\" := (mat_inv A) (at level 1, format \"A ⁻¹\") : M_scope.\n\nTheorem mat_inv_ncols : ∀ M,\n  mat_ncols M⁻¹ = if mat_ncols M =? 0 then 0 else mat_nrows M.\nProof.\nintros.\nunfold mat_inv.\nrewrite mat_mul_scal_l_ncols.\nrewrite mat_transp_ncols.\nnow rewrite comatrix_ncols, comatrix_nrows.\nQed.\n\nTheorem mat_inv_is_corr : ∀ M,\n  is_correct_matrix M = true\n  → is_correct_matrix M⁻¹ = true.\nProof.\nintros * Hcm.\nunfold mat_inv.\napply is_correct_matrix_mul_scal_l.\napply mat_transp_is_corr.\nnow apply comatrix_is_correct.\nQed.\n\nTheorem mat_inv_det_comm : in_charac_0_field →\n  ∀ M,\n  is_square_matrix M = true\n  → det M ≠ 0%L\n  → (M⁻¹ = (1%L / det M) × (com M)⁺)%M.\nProof.\nintros Hif * Hsm Hmz.\ngeneralize Hif; intros H.\ndestruct H as (Hic, Hop, Hin, Hit, Hde, Hch).\nspecialize (matrix_comatrix_transp_mul Hop Hic Hch) as H1.\nspecialize (H1 (proj2 (Bool.orb_true_iff _ _) (or_introl Hit))).\nspecialize (H1 M Hsm).\nspecialize (mat_mul_inv_l Hif M Hsm Hmz) as H3.\napply (f_equal (mat_mul M⁻¹)) in H1.\ndestruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]. {\n  destruct M as (ll).\n  cbn in Hrz.\n  apply length_zero_iff_nil in Hrz; subst ll.\n  cbn.\n  unfold mat_transp, mat_inv, com; cbn.\n  unfold mat_transp; cbn.\n  rewrite rngl_inv_1; [ | easy | now rewrite Hch ].\n  rewrite rngl_div_1_r; cycle 1. {\n    now apply rngl_has_inv_or_quot_iff; left.\n  } {\n    now rewrite Hch.\n  }\n  easy.\n}\nassert (Hcz : mat_ncols M ≠ 0). {\n  now rewrite (squ_mat_ncols _ Hsm).\n}\nrewrite mat_mul_assoc in H1; [ | easy | easy | easy | ]. 2: {\n  rewrite mat_inv_ncols.\n  rewrite if_eqb_eq_dec.\n  now destruct (Nat.eq_dec _ _).\n}\nrewrite H3 in H1.\nrewrite mat_mul_1_l in H1; [ | easy | | ]; cycle 1. {\n  apply mat_transp_is_corr.\n  apply comatrix_is_correct.\n  now apply squ_mat_is_corr.\n} {\n  rewrite mat_transp_nrows.\n  rewrite comatrix_ncols.\n  symmetry; apply (squ_mat_ncols _ Hsm).\n}\nrewrite (mat_mul_mul_scal_l Hop Hic) in H1; cycle 1. {\n  apply mI_is_correct_matrix.\n} {\n  rewrite mat_inv_ncols.\n  rewrite if_eqb_eq_dec.\n  now destruct (Nat.eq_dec _ _).\n} {\n  rewrite mat_inv_ncols.\n  rewrite mI_nrows.\n  rewrite if_eqb_eq_dec.\n  now destruct (Nat.eq_dec _ _).\n}\nrewrite (mat_mul_1_r Hop) in H1; cycle 1. {\n  apply mat_inv_is_corr.\n  now apply squ_mat_is_corr.\n} {\n  rewrite mat_inv_ncols.\n  rewrite if_eqb_eq_dec.\n  now destruct (Nat.eq_dec _ _).\n}\nrewrite H1.\nrewrite mat_mul_scal_l_mul_assoc.\nrewrite rngl_div_1_l; [ | easy ].\nrewrite rngl_mul_inv_l; [ | easy | easy ].\nsymmetry; apply mat_mul_scal_1_l.\nQed.\n\nTheorem vect_el_mul_scal_l : ∀ μ V i,\n  1 ≤ i ≤ vect_size V\n  → vect_el (μ × V) i = (μ * vect_el V i)%L.\nProof.\nintros * Hi; cbn.\napply (List_map_nth' 0%L).\nrewrite fold_vect_size.\nflia Hi.\nQed.\n\nTheorem vect_size_mat_mul_vect_r : ∀ A V, vect_size (A • V) = mat_nrows A.\nProof.\nintros; cbn.\nnow rewrite map_length.\nQed.\n\n(*\nTheorem firstn_map2 : ∀ A B C (f : A → B → C) la lb i,\n  firstn i (map2 f la lb) = map2 f (firstn i la) (firstn i lb).\nProof.\nintros.\nrevert i lb.\ninduction la as [| a]; intros; cbn. {\n  now do 2 rewrite firstn_nil.\n}\ndestruct lb as [| b]. {\n  do 2 rewrite firstn_nil.\n  now rewrite map2_nil_r.\n}\ndestruct i; [ easy | cbn; f_equal ].\napply IHla.\nQed.\n*)\n\nTheorem butn_map2 : ∀ A B C (f : A → B → C) la lb i,\n  butn i (map2 f la lb) = map2 f (butn i la) (butn i lb).\nProof.\nintros.\nrevert i lb.\ninduction la as [| a]; intros; cbn. {\n  now do 2 rewrite butn_nil.\n}\ndestruct lb as [| b]. {\n  do 2 rewrite butn_nil.\n  now rewrite map2_nil_r.\n}\ndestruct i; [ easy | cbn; f_equal ].\napply IHla.\nQed.\n\nTheorem det_mat_repl_vect :\n  rngl_has_opp = true →\n  rngl_mul_is_comm = true →\n  rngl_characteristic ≠ 1 →\n  ∀ M V,\n  is_square_matrix M = true\n  → vect_size V = mat_nrows M\n  → ∀ k, 1 ≤ k ≤ mat_ncols M\n  → det (mat_repl_vect k M V) = vect_el ((com M)⁺ • V) k.\nProof.\nintros Hop Hic H10 * Hsm Hvm * Hk.\nspecialize (squ_mat_is_corr _ Hsm) as Hcm.\nmove Hcm before Hsm.\nassert (Hk' : k - 1 < mat_ncols M) by flia Hk.\nrewrite laplace_formula_on_cols with (j := k); [ | easy | easy | easy | | ];\n    cycle 1. {\n  now apply mat_repl_vect_is_square.\n} {\n  rewrite <- (squ_mat_ncols _ Hsm) in Hvm.\n  now rewrite mat_repl_vect_ncols.\n}\nrewrite mat_repl_vect_nrows; [ | easy ].\nerewrite rngl_summation_eq_compat. 2: {\n  intros j Hj.\n  rewrite mat_el_repl_vect; [ | easy | now rewrite Hvm | easy | easy | easy ].\n  now rewrite <- if_eqb_eq_dec, Nat.eqb_refl.\n}\ncbn - [ mat_el vect_el ].\nunfold mat_mul_vect_r.\ncbn - [ mat_el com ].\nrewrite comatrix_ncols.\nrewrite (List_map_nth' []); [ | now rewrite List_map_seq_length ].\nunfold vect_dot_mul.\ncbn - [ mat_el com ].\nrewrite (List_map_nth' 0); [ | now rewrite seq_length ].\nrewrite map2_map_l.\nrewrite map2_map2_seq_l with (d := 0).\nrewrite map2_map2_seq_r with (d := 0%L).\nrewrite seq_length.\nrewrite fold_vect_size, Hvm.\nrewrite comatrix_nrows.\nrewrite map2_diag.\nrewrite rngl_summation_list_map.\nrewrite rngl_summation_seq_summation. 2: {\n  rewrite <- (squ_mat_ncols _ Hsm); flia Hk.\n}\nsymmetry.\nrewrite rngl_summation_rshift.\nrewrite Nat.add_0_l.\nrewrite <- Nat_succ_sub_succ_r. 2: {\n  rewrite <- (squ_mat_ncols _ Hsm); flia Hk.\n}\nrewrite Nat.sub_0_r.\napply rngl_summation_eq_compat.\nintros i Hi.\nassert (Hi' : i - 1 < mat_nrows M) by flia Hi.\nrewrite fold_vect_el.\nrewrite <- Nat_succ_sub_succ_r; [ | flia Hi ].\nrewrite Nat.sub_0_r.\nrewrite rngl_mul_comm; [ | easy ].\nf_equal.\nunfold com.\ncbn - [ det ].\nrewrite seq_nth; [ | easy ].\nrewrite Nat.add_comm, Nat.sub_add; [ | easy ].\nrewrite (seq_nth _ _ Hi').\nrewrite Nat.add_comm, Nat.sub_add; [ | easy ].\nrewrite (List_map_nth' 0); [ | now rewrite seq_length ].\nrewrite (seq_nth _ _ Hi').\nrewrite (List_map_nth' 0); [ | now rewrite seq_length ].\nrewrite (seq_nth _ _ Hk').\nrewrite (List_map_nth' 0). 2: {\n  rewrite seq_length, map2_length.\n  rewrite fold_mat_nrows, fold_vect_size, Hvm.\n  now rewrite Nat.min_id.\n}\nrewrite seq_nth. 2: {\n  rewrite map2_length.\n  rewrite fold_mat_nrows, fold_vect_size, Hvm.\n  now rewrite Nat.min_id.\n}\nrewrite (List_map_nth' 0). 2: {\n  rewrite seq_length, mat_repl_vect_ncols; [ easy | easy | ].\n  now rewrite (squ_mat_ncols _ Hsm).\n}\nrewrite seq_nth. 2: {\n  rewrite mat_repl_vect_ncols; [ easy | easy | ].\n  now rewrite (squ_mat_ncols _ Hsm).\n}\nf_equal.\nrewrite (Nat.add_comm _ (i - 1)), Nat.sub_add; [ | easy ].\nrewrite (Nat.add_comm _ (k - 1)), Nat.sub_add; [ | easy ].\nunfold mat_repl_vect.\nunfold subm.\ncbn - [ det ].\nrewrite map_butn.\nrewrite map_butn.\nrewrite map_map2.\nrewrite map2_map2_seq_l with (d := []).\nrewrite map2_map2_seq_r with (d := 0%L).\nrewrite fold_mat_nrows.\nrewrite fold_vect_size.\nrewrite Hvm.\nrewrite map2_diag.\nsymmetry.\nerewrite map_ext_in. 2: {\n  intros j Hj.\n  apply in_seq in Hj.\n  unfold replace_at.\n  rewrite butn_app.\n  rewrite firstn_length.\n  rewrite fold_corr_mat_ncols; [ | easy | easy ].\n  rewrite min_l; [ | flia Hk ].\n  rewrite Nat.ltb_irrefl.\n  rewrite Nat.sub_diag.\n  rewrite butn_0_cons.\n  now rewrite fold_butn.\n}\nnow rewrite <- List_map_map_seq.\nQed.\n\n(* Cramer's rule *)\n\nTheorem cramer's_rule_by_mul :\n  rngl_has_opp = true →\n  rngl_mul_is_comm = true →\n  rngl_characteristic = 0 →\n  (rngl_is_integral || rngl_has_inv_or_quot)%bool = true →\n  ∀ (M : matrix T) (U V : vector T),\n  is_square_matrix M = true\n  → vect_size U = mat_nrows M\n  → (M • U)%V = V\n  → ∀ i, 1 ≤ i ≤ mat_nrows M →\n  (det M * vect_el U i)%L = det (mat_repl_vect i M V).\nProof.\nintros Hop Hic Hch Hii * Hsm Hum Hmuv k Hk.\nassert (H10 : rngl_characteristic ≠ 1) by now rewrite Hch.\nassert (Huv : vect_size V = vect_size U). {\n  rewrite <- Hmuv; cbn.\n  now rewrite map_length.\n}\nrewrite <- (squ_mat_ncols _ Hsm) in Hk.\nrewrite (det_mat_repl_vect Hop Hic H10); [ | easy | congruence | easy ].\nrewrite <- Hmuv.\nrewrite (mat_vect_mul_assoc Hop); cycle 1. {\n  apply mat_transp_is_corr.\n  apply comatrix_is_correct.\n  now apply squ_mat_is_corr.\n} {\n  now apply squ_mat_is_corr.\n} {\n  symmetry.\n  rewrite mat_transp_ncols.\n  rewrite comatrix_ncols.\n  rewrite comatrix_nrows.\n  rewrite squ_mat_ncols; [ | easy ].\n  rewrite if_eqb_eq_dec.\n  now destruct (Nat.eq_dec _ _).\n} {\n  rewrite squ_mat_ncols; [ congruence | easy ].\n}\nrewrite (comatrix_transp_matrix_mul Hop Hic Hch Hii); [ | easy ].\nrewrite <- (mat_mul_scal_vect_assoc Hop); cycle 1. {\n  apply mI_is_correct_matrix.\n} {\n  rewrite mI_ncols; congruence.\n}\nrewrite vect_el_mul_scal_l. 2: {\n  split; [ easy | ].\n  rewrite vect_size_mat_mul_vect_r.\n  rewrite mI_nrows.\n  now rewrite <- squ_mat_ncols.\n}\nf_equal.\nnow rewrite mat_vect_mul_1_l.\nQed.\n\nTheorem cramer's_rule :\n  rngl_has_opp = true →\n  rngl_mul_is_comm = true →\n  rngl_has_inv_or_quot = true →\n  rngl_characteristic = 0 →\n  ∀ (M : matrix T) (U V : vector T),\n  is_square_matrix M = true\n  → vect_size U = mat_nrows M\n → det M ≠ 0%L\n  → (M • U)%V = V\n  → ∀ i, 1 ≤ i ≤ mat_nrows M →\n  vect_el U i = (det (mat_repl_vect i M V) / det M)%L.\nProof.\nintros Hop Hic Hiq Hch * Hsm Hum Hmz Hmuv k Hk.\nassert (Hii : (rngl_is_integral || rngl_has_inv_or_quot)%bool = true). {\n  rewrite Hiq.\n  now apply Bool.orb_true_iff; right.\n}\nrewrite <- (cramer's_rule_by_mul Hop Hic Hch Hii Hsm Hum Hmuv Hk).\nrewrite (rngl_mul_comm Hic).\nsymmetry.\napply (rngl_mul_div Hiq _ _ Hmz).\nQed.\n\nEnd a.\n\nArguments com {T}%type {ro} M%M.\nArguments cramer's_rule {T ro rp} Hop Hic Hiq Hch [M%M U%V V%V].\nArguments laplace_formula_on_cols {T ro rp} Hop Hic H10 M%M [j]%nat.\nArguments laplace_formula_on_rows {T}%type {ro rp} Hop Hic M%M [i]%nat.\nArguments mat_inv {T}%type {ro} M%M.\nArguments mat_mul_inv_r {T}%type {ro rp} Hof M%L.\n\nNotation \"A ⁻¹\" := (mat_inv A) (at level 1, format \"A ⁻¹\") : M_scope.\n\n(* tests\nRequire Import RnglAlg.Qrl.\nRequire Import RnglAlg.Rational.\nImport Q.Notations.\nOpen Scope Q_scope.\nCompute 3.\nCompute (let M := mk_mat [[3;7;4;1];[0;6;2;7];[1;3;1;1];[18;3;2;1]] in (det M, mat_inv M)).\nCompute (let M := mk_mat [[3;7;4;1];[0;6;2;7];[1;3;1;1];[18;3;2;1]] in (M * mat_inv M)%M).\nCompute (let M := mk_mat [[3;7;4;1];[0;6;2;7];[1;3;1;1];[18;3;2;1]] in (mat_inv M * M)%M).\nCompute (let M := mk_mat [[3;0;0;1];[0;0;2;7];[1;0;1;1];[18;0;2;1]] in (det M, com M)).\nCompute (let M := mk_mat [[3;0;0;1];[0;0;2;7];[1;0;1;1];[18;0;2;1]] in (det M, (M * com M)%M, (com M * M)%M)).\n*)\n", "meta": {"author": "roglo", "repo": "coq_sensitivity", "sha": "398291aa86a447f0f35b4918043e94d9eb703c12", "save_path": "github-repos/coq/roglo-coq_sensitivity", "path": "github-repos/coq/roglo-coq_sensitivity/coq_sensitivity-398291aa86a447f0f35b4918043e94d9eb703c12/main/Comatrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388125473629, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.6718374298398363}}
{"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\nSection Exponentiation.\n\n(* Why3 goal *)\nVariable t : Type.\nHypothesis t_WhyType : WhyType t.\nExisting Instance t_WhyType.\n\n(* Why3 goal *)\nVariable one: t.\n\n(* Why3 goal *)\nVariable infix_as: t -> t -> t.\n\n(* Why3 goal *)\nHypothesis Assoc :\nforall (x:t) (y:t) (z:t),\n ((infix_as (infix_as x y) z) = (infix_as x (infix_as y z))).\n\n(* Why3 goal *)\nHypothesis Unit_def_l :\nforall (x:t), ((infix_as one x) = x).\n\n(* Why3 goal *)\nHypothesis Unit_def_r :\nforall (x:t), ((infix_as x one) = x).\n\n(* Why3 goal *)\nDefinition power: t -> Z -> t.\nintros x n.\nexact (iter_nat (Zabs_nat n) t (fun acc => infix_as x acc) one).\nDefined.\n\n(* Why3 goal *)\nLemma Power_0 :\nforall (x:t), ((power x 0%Z) = one).\nProof.\neasy.\nQed.\n\n(* Why3 goal *)\nLemma Power_s :\nforall (x:t) (n:Z),\n (0%Z <= n)%Z -> ((power x (n + 1%Z)%Z) = (infix_as x (power x n))).\nProof.\nintros x n h1.\nunfold power.\nfold (Zsucc n).\nnow rewrite Zabs_nat_Zsucc.\nQed.\n\n(* Why3 goal *)\nLemma Power_s_alt :\nforall (x:t) (n:Z),\n (0%Z < n)%Z -> ((power x n) = (infix_as x (power x (n - 1%Z)%Z))).\nProof.\nintros x n h1.\nrewrite <- Power_s; auto with zarith.\nf_equal; omega.\nQed.\n\n(* Why3 goal *)\nLemma Power_1 :\nforall (x:t), ((power x 1%Z) = x).\nProof.\nexact Unit_def_r.\nQed.\n\n(* Why3 goal *)\nLemma Power_sum :\nforall (x:t) (n:Z) (m:Z),\n (0%Z <= n)%Z ->\n ((0%Z <= m)%Z -> ((power x (n + m)%Z) = (infix_as (power x n) (power x m)))).\nProof.\nintros x n m Hn Hm.\nrevert n Hn.\napply natlike_ind.\napply sym_eq, Unit_def_l.\nintros n Hn IHn.\nreplace (Zsucc n + m)%Z with ((n + m) + 1)%Z by ring.\nrewrite Power_s by auto with zarith.\nrewrite IHn.\nnow rewrite <- Assoc, <- Power_s.\nQed.\n\n(* Why3 goal *)\nLemma Power_mult :\nforall (x:t) (n:Z) (m:Z),\n (0%Z <= n)%Z ->\n ((0%Z <= m)%Z -> ((power x (n * m)%Z) = (power (power x n) m))).\nProof.\nintros x n m Hn Hm.\nrevert m Hm.\napply natlike_ind.\nnow rewrite Zmult_0_r, 2!Power_0.\nintros m Hm IHm.\nreplace (n * Zsucc m)%Z with (n + n * m)%Z by ring.\nrewrite Power_sum by auto with zarith.\nrewrite IHm.\nnow rewrite <- Power_s.\nQed.\n\n(* Why3 goal *)\nLemma Power_comm1 :\nforall (x:t) (y:t),\n ((infix_as x y) = (infix_as y x)) ->\n forall (n:Z),\n  (0%Z <= n)%Z -> ((infix_as (power x n) y) = (infix_as y (power x n))).\nProof.\nintros x y comm.\napply natlike_ind.\nnow rewrite Power_0, Unit_def_r, Unit_def_l.\nintros n Hn IHn.\nunfold Zsucc.\nrewrite (Power_s _ _ Hn).\nrewrite Assoc.\nrewrite IHn.\nrewrite <- Assoc.\nrewrite <- Assoc.\nnow rewrite comm.\nQed.\n\n(* Why3 goal *)\nLemma Power_comm2 :\nforall (x:t) (y:t),\n ((infix_as x y) = (infix_as y x)) ->\n forall (n:Z),\n  (0%Z <= n)%Z ->\n  ((power (infix_as x y) n) = (infix_as (power x n) (power y n))).\nProof.\nintros x y comm.\napply natlike_ind.\nrewrite 3!Power_0.\nnow rewrite Unit_def_r.\nintros n Hn IHn.\nunfold Zsucc.\nrewrite 3!(Power_s _ _ Hn).\nrewrite IHn.\nrewrite <- Assoc.\nrewrite (Assoc x).\nrewrite <- (Power_comm1 _ _ comm _ Hn).\nnow rewrite <- 2!Assoc.\nQed.\n\nEnd Exponentiation.\n", "meta": {"author": "florianschanda", "repo": "why3", "sha": "dc0d2720d58c6d130b9c3e1db820a07275a133eb", "save_path": "github-repos/coq/florianschanda-why3", "path": "github-repos/coq/florianschanda-why3/why3-dc0d2720d58c6d130b9c3e1db820a07275a133eb/lib/coq/int/Exponentiation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6717799240845204}}
{"text": "From Test Require Import tactic.\n\nSection FOFProblem.\n\nVariable Universe : Set.\nVariable UniverseElement : Universe.\n\nVariable col_ : Universe -> Universe -> Universe -> Prop.\nVariable betS_ : Universe -> Universe -> Universe -> Prop.\n\n\nVariable defcollinear_1 : (forall A B C : Universe, (col_ A B C -> (A = B \\/ (A = C \\/ (B = C \\/ (betS_ B A C \\/ (betS_ A B C \\/ betS_ A C B))))))).\nVariable defcollinear2a_2 : (forall A B C : Universe, (A = B -> col_ A B C)).\nVariable defcollinear2b_3 : (forall A B C : Universe, (A = C -> col_ A B C)).\nVariable defcollinear2c_4 : (forall A B C : Universe, (B = C -> col_ A B C)).\nVariable defcollinear2d_5 : (forall A B C : Universe, (betS_ B A C -> col_ A B C)).\nVariable defcollinear2e_6 : (forall A B C : Universe, (betS_ A B C -> col_ A B C)).\nVariable defcollinear2f_7 : (forall A B C : Universe, (betS_ A C B -> col_ A B C)).\nVariable lemma_collinearorder_8 : (forall A B C : Universe, (col_ A B C -> (col_ B A C /\\ (col_ B C A /\\ (col_ C A B /\\ (col_ A C B /\\ col_ C B A)))))).\nVariable lemma_3_5b_9 : (forall A B C D : Universe, ((betS_ A B D /\\ betS_ B C D) -> betS_ A C D)).\nVariable lemma_outerconnectivity_10 : (forall A B C D : Universe, ((betS_ A B C /\\ (betS_ A B D /\\ (~(betS_ B C D) /\\ ~(betS_ B D C)))) -> C = D)).\nVariable axiom_betweennesssymmetry_11 : (forall A B C : Universe, (betS_ A B C -> betS_ C B A)).\nVariable lemma_3_7b_12 : (forall A B C D : Universe, ((betS_ A B C /\\ betS_ B C D) -> betS_ A B D)).\nVariable lemma_3_6b_13 : (forall A B C D : Universe, ((betS_ A B C /\\ betS_ A C D) -> betS_ A B D)).\nVariable lemma_3_7a_14 : (forall A B C D : Universe, ((betS_ A B C /\\ betS_ B C D) -> betS_ A C D)).\nVariable lemma_3_6a_15 : (forall A B C D : Universe, ((betS_ A B C /\\ betS_ A C D) -> betS_ B C D)).\nVariable axiom_connectivity_16 : (forall A B C D : Universe, ((betS_ A B D /\\ (betS_ A C D /\\ (~(betS_ A B C) /\\ ~(betS_ A C B)))) -> B = C)).\n\nTheorem lemma_collinear4_17 : (forall A B C D : Universe, ((col_ A B C /\\ (col_ A B D /\\ A <> B)) -> col_ B C D)).\nProof.\n  time tac.\nQed.\n\nEnd FOFProblem.\n", "meta": {"author": "janicicpredrag", "repo": "Larus", "sha": "a095ca588fbb0e4a64a26d92946485bbf85e1e08", "save_path": "github-repos/coq/janicicpredrag-Larus", "path": "github-repos/coq/janicicpredrag-Larus/Larus-a095ca588fbb0e4a64a26d92946485bbf85e1e08/benchmarks/coq-problems/euclid/lemma_collinear4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6716466598586069}}
{"text": "(*\n\nIf you have programs that don't terminate,\n\nan _interpreter_ will not be able to prove all of its semantics.\n\nInstead, we can use _transisition systems_.\n\n*)\n\n(********************** Begin: FRAP Preamble **********************)\nRequire Import Frap.\n\nSet Implicit Arguments.\n\nFixpoint fact (n : nat) : nat :=\n  match n with\n  | O => 1\n  | S n' => fact n' * S n'\n  end.\n\nInductive fact_state :=\n| AnswerIs (answer : nat)\n| WithAccumulator (input accumulator : nat).\n\nInductive fact_init (original_input : nat) : fact_state -> Prop :=\n| FactInit : fact_init original_input (WithAccumulator original_input 1).\n\nInductive fact_final : fact_state -> Prop :=\n| FactFinal : forall ans, fact_final (AnswerIs ans).\n\nInductive fact_step : fact_state -> fact_state -> Prop :=\n| FactDone : forall acc,\n  fact_step (WithAccumulator O acc) (AnswerIs acc)\n| FactStep : forall n acc,\n  fact_step (WithAccumulator (S n) acc) (WithAccumulator n (acc * S n)).\n\nInductive trc {A} (R : A -> A -> Prop) : A -> A -> Prop :=\n| TrcRefl : forall x, trc R x x\n| TrcFront : forall x y z,\n  R x y\n  -> trc R y z\n  -> trc R x z.\n\nSet Warnings \"-notation-overridden\".\nNotation \"R ^*\" := (trc R) (at level 0).\n\nExample factorial_3 : fact_step^* (WithAccumulator 3 1) (AnswerIs 6).\nProof.\nAdmitted.\n\nRecord trsys state := {\n  Initial : state -> Prop;\n  Step : state -> state -> Prop\n}.\n\nDefinition factorial_sys (original_input : nat) : trsys fact_state := {|\n  Initial := fact_init original_input;\n  Step := fact_step\n|}.\n\nInductive reachable {state} (sys : trsys state) (st : state) : Prop :=\n| Reachable : forall st0,\n  sys.(Initial) st0\n  -> sys.(Step)^* st0 st\n  -> reachable sys st.\n(********************** End: FRAP Preamble **********************)\n\n(*\nQ: why is sys.(Initial) s necessary in `forall s, sys.(Initial) s` ?\nA: look at its definition, this means `forall s that is an initial state of sys`\n   so altogether, this is the statement:\n   \"forall initial states s of sys,\n     forall states s' reachable from s,\n      invariant holds for s'\"\n*)\nDefinition invariantFor {state} (sys : trsys state) (invariant : state -> Prop) :=\n  forall s, sys.(Initial) s\n            -> forall s', sys.(Step)^* s s'\n                          -> invariant s'.\n\n(********************** Begin: FRAP Preamble **********************)\nLemma use_invariant' : forall {state} (sys : trsys state)\n  (invariant : state -> Prop) s s',\n  invariantFor sys invariant\n  -> sys.(Initial) s\n  -> sys.(Step)^* s s'\n  -> invariant s'.\nProof.\n  unfold invariantFor.\n  simplify.\n  eapply H.\n  eassumption.\n  assumption.\nQed.\n\nTheorem use_invariant : forall {state} (sys : trsys state)\n  (invariant : state -> Prop) s,\n  invariantFor sys invariant\n  -> reachable sys s\n  -> invariant s.\nProof.\n  simplify.\n  invert H0.\n  eapply use_invariant'.\n  eassumption.\n  eassumption.\n  assumption.\nQed.\n\nLemma invariant_induction' : forall {state} (sys : trsys state)\n  (invariant : state -> Prop),\n  (forall s, invariant s -> forall s', sys.(Step) s s' -> invariant s')\n  -> forall s s', sys.(Step)^* s s'\n     -> invariant s\n     -> invariant s'.\nProof.\n  induct 2; propositional.\n  apply IHtrc.\n  eapply H.\n  eassumption.\n  assumption.\nQed.\n\nTheorem invariant_induction : forall {state} (sys : trsys state)\n  (invariant : state -> Prop),\n  (forall s, sys.(Initial) s -> invariant s)\n  -> (forall s, invariant s -> forall s', sys.(Step) s s' -> invariant s')\n  -> invariantFor sys invariant.\nProof.\n  unfold invariantFor; intros.\n  eapply invariant_induction'.\n  eassumption.\n  eassumption.\n  apply H.\n  assumption.\nQed.\n\nDefinition fact_invariant (original_input : nat) (st : fact_state) : Prop :=\n  match st with\n  | AnswerIs n => fact original_input = n\n  | WithAccumulator n acc => fact original_input = acc * fact n\n  end.\n(********************** End: FRAP Preamble **********************)\n\n(*\nInvert is very similar to cases or destruct, but it is smarter\nin that it can look backwards, looking at constraints in the type signature:\n\n\"s is Initial => s was made with fact_init => s looks like WithAccumulator\"\n*)\nTheorem fact_invariant_ok : forall original_input,\n  invariantFor (factorial_sys original_input) (fact_invariant original_input).\nProof.\n  intros.\n  apply invariant_induction; simplify.\n  - invert H. simplify. auto.\n  - invert H0; simplify; linear_arithmetic.\nQed.\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/04-lecture-07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.808067208930584, "lm_q1q2_score": 0.6716194361453084}}
{"text": "Module PNPEX.\n  \nFrom mathcomp.ssreflect\nRequire Import ssreflect ssrfun eqtype ssrnat ssrbool seq.\n\nSection Chapter2.\n\n(* Exercise 2.1 *)\n\nFixpoint alternate (s1 : seq nat) (s2 : seq nat) : seq nat :=\n  match s1, s2 with\n    | nil, nil => nil\n    | nil, _   => s2\n    | _  , nil => s1\n    | h1 :: t1, h2 :: t2 => h1 :: h2 :: alternate t1 t2\n  end.\n                   \n\nCompute alternate [:: 1;2;3] [:: 4;5;6] = [:: 1;4;2;5;3;6].\nCompute alternate [:: 1] [:: 4;5;6] = [:: 1;4;5;6].\nCompute alternate [:: 1;2;3] [:: 4] = [:: 1;4;2;3].\n\nEnd Chapter2.\n\nSection Chapter3.\n  \n(* Exercise 3.1 *)\n\nTheorem all_imp_ist A (P Q: A -> Prop): \n  (forall x: A, P x -> Q x) -> (forall y, P y) -> forall z, Q z. \nProof.\n  move=> H1 H2 z.\n  by apply H1.\nQed.\n\nInductive my_ex A (S: A -> Prop) : Prop := my_ex_intro x of S x.\n\nTheorem ex_imp_ex A (S T: A -> Prop):\n  (exists a: A, S a) -> (forall x: A, S x -> T x) -> exists b: A, T b.\nProof.\n  case=> a Hs Hst.\n  exists a.\n  apply Hst.\n  apply Hs.\nQed.\n\n(* Exercise 3.2 *)\n\nGoal forall A (S: A -> Prop), my_ex A S <-> exists y: A, S y.\nProof.\n  firstorder.\nQed.\n\n(* Exercise 3.3 *)\n\nRequire Import Classical_Prop.\n\nDefinition peirce_law := forall P Q: Prop, ((P -> Q) -> P) -> P.\nDefinition peirce := peirce_law.\nDefinition double_neg := forall P: Prop, ~ ~ P -> P.\nDefinition excluded_middle := forall P: Prop, P \\/ ~P.\nDefinition de_morgan_not_and_not := forall P Q: Prop, ~ ( ~P /\\ ~Q) -> P \\/ Q.\nDefinition implies_to_or := forall P Q: Prop, (P -> Q) -> (~P \\/ Q).\n\nLemma peirce_dn: peirce -> double_neg.\nProof.\n  rewrite /peirce /double_neg /peirce_law.\n  firstorder.\n  apply H with (Q := P).\n  move=> H1.\n  suff: P.\n  exact H1.\n  apply NNPP.\n  exact H0.\nQed.\n\nLemma dn_em : double_neg -> excluded_middle.\nProof.\n  rewrite /double_neg /excluded_middle.\n  (* firstorder. *)\n  (* apply classic. *)\n  compute.\n  intros.\n  apply H.\n  intuition.\nQed.\n\nLemma em_dmnan: excluded_middle -> de_morgan_not_and_not.\nProof.\n  rewrite /excluded_middle /de_morgan_not_and_not.\n  compute.\n  intros.\n  specialize (H (P \\/ Q)).\n  inversion H.\n  done.\n  intuition.\nQed.\n\nLemma dmnan_ito : de_morgan_not_and_not -> implies_to_or.\nProof.\n  rewrite /de_morgan_not_and_not /implies_to_or.\n  compute.\n  intros.\n  specialize (H (P -> False) Q).\n  intuition.\nQed.\n\nLemma ito_peirce : implies_to_or -> peirce.\nProof.\n  rewrite /implies_to_or /peirce.\n  compute.\n  intros.\n  specialize (H P P).\n  intuition.\nQed.\n\nEnd Chapter3.\n\nSection Chapter4.\n  \n(* Exercise 4.1 *)\n\nSet Implicit Arguments.\nInductive my_eq (A : Type) (x : A) : A -> Prop :=  my_eq_refl : my_eq x x.\nNotation \"x === y\" := (my_eq x y) (at level 70).\n\nLemma disaster2: 1 === 2 -> False.\nProof.\n  move=> H.\n  pose D x := if x is 1 then False else True.\n  have D2: D 2.\n  by [].\n  case: H D2.\n  move=> /=.\n  done.\nQed.\n\n(* Exercise 4.2 *)\n\n(** the best refernce is the source code https://github.com/math-comp/math-comp/blob/master/mathcomp/ssreflect/ssrnat.v *)\n\nDefinition maxn m n := if m < n then n else m.\n\nLemma max_l m n: n <= m -> maxn m n = m.\nProof.\n  rewrite /maxn.\n  case: leqP=>//.\nQed.\n\nLemma max_is_max m n: n <= maxn m n /\\ m <= maxn m n.\nProof.\n  rewrite /maxn.\n  case leqP=>//.\n  move=>H.\n  split.\n  by apply leqnn.\n  rewrite ltn_neqAle in H.\n  by case /andP: H.\nQed.\n\nLemma maxnE m n : maxn m n = m + (n - m).\nProof. by rewrite /maxn addnC; case: leqP => [/eqnP-> | /ltnW/subnK]. Qed.\n\nLemma succ_max_distr_r n m : (maxn n m).+1 = maxn (n.+1) (m.+1).\nProof.\n  rewrite !maxnE.\n  rewrite addSn.\n  done.\nQed.\n\nLemma plus_max_distr_l m n p: maxn (p + n) (p + m) = p + maxn n m.\nProof.\n  rewrite !maxnE.\n  rewrite subnDl.\n  rewrite addnA.\n  done.\nQed.\n\n(* Exercice 4.3 *)\n\nInductive nat_rels m n : bool -> bool -> bool -> Set :=\n  | CompareNatLt of m < n : nat_rels m n true false false\n  | CompareNatGt of m > n : nat_rels m n false true false\n  | CompareNatEq of m = n : nat_rels m n false false true.\n\nLemma natrelP m n : nat_rels m n (m < n) (n < m) (m == n).\nProof.\n  rewrite ltn_neqAle eqn_leq.\n  case: ltnP; first by constructor.\n  by rewrite leq_eqVlt orbC; case: leqP; constructor; first exact/eqnP.\nQed.\n\n(* Exercise 4.4 *)\n\nDefinition minn m n := if m < n then m else n.\n\nLemma addn_min_max m n : minn m n + maxn m n = m + n.\nProof.\n  rewrite /minn /maxn.\n  case: ltngtP => // [_|->] //.\n  apply: addnC.\nQed.\n\nEnd Chapter4.\n\nEnd PNPEX.\n", "meta": {"author": "zjhmale", "repo": "MFCS", "sha": "e82b0e2425b4988ce8dfc558901ae2e76e1b23f1", "save_path": "github-repos/coq/zjhmale-MFCS", "path": "github-repos/coq/zjhmale-MFCS/MFCS-e82b0e2425b4988ce8dfc558901ae2e76e1b23f1/pnp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.8670357615200474, "lm_q1q2_score": 0.6715914943502097}}
{"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.\nFrom Undecidability.Shared.Libs.PSL Require Import Vectors.VectorDupfree.\nImport VectorNotations2.\nFrom Undecidability.Shared.Libs.PSL Require Import FiniteTypes.Cardinality.\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  eapply 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\nImport VecToListCoercion.\n\n#[global]\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.\nDefined.\n\n#[export] Hint Extern 4 (finTypeC (EqType (Fin.t _))) => eapply Fin_finTypeC : typeclass_instances.\n\nLemma Fin_cardinality n : Cardinality (finType_CS (Fin.t n)) = n.\nProof.\n  unfold Cardinality, elem, enum. cbn. unfold Fin_initVect. now rewrite vector_to_list_length. \nQed.\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 (undup ((Vector_pow (elem A) n))). cbn in *.\n  intros v. eapply dupfreeCount.\n  - eapply dupfree_undup.\n  - rewrite undup_id_equi. induction v; cbn.\n    + eauto.\n    + eapply in_concat_iff. eexists; split.\n      2:eapply in_map_iff. 2:eexists.\n      2:split. 2:reflexivity.\n      eapply in_map_iff. eauto.\n      eapply elem_spec.\nDefined.\n      \n#[export] Hint Extern 4 (finTypeC (EqType (Vector.t _ _))) => eapply Vector_finTypeC : typeclass_instances.\n\n\nLemma ProdCount (T1 T2: eqType) (A: list T1) (B: list T2) (a:T1) (b:T2)  :\n  FinTypesDef.count (prodLists A B) (a,b) =  FinTypesDef.count A a * FinTypesDef.count B b .\nProof.\n  induction A.\n  - reflexivity.\n  - cbn. rewrite <- countSplit. decide (a = a0) as [E | E].\n    + cbn. f_equal. subst a0. apply countMap. eauto.\n    + rewrite <- plus_O_n. f_equal. now apply countMapZero. eauto.\nQed.\n\nLemma prod_enum_ok (T1 T2: finType) (x: T1 * T2):\n  FinTypesDef.count (prodLists (elem T1) (elem T2)) x = 1.\nProof.\n  destruct x as [x y]. rewrite ProdCount. unfold elem.\n  now repeat rewrite enum_ok.\nQed.\n\nGlobal\nInstance finTypeC_Prod (F1 F2: finType) : finTypeC (EqType (F1 * F2)).\nProof.\n  econstructor.  apply prod_enum_ok.\nDefined.\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/PSL/FiniteTypes/VectorFin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.6714519803127245}}
{"text": "(** * H4: Nierówność i różność [TODO] *)\n\nSet Universe Polymorphism.\n\nRequire Import Arith.\nRequire Import Bool.\nRequire Import Equality.\nRequire Import FunctionalExtensionality.\n\nRequire Import List.\nImport ListNotations.\n\nFrom Typonomikon Require Import H1.\nFrom Typonomikon Require Import D5.\n\n(** * Różność *)\n\n(** ** Nierówność liczb naturalnych - rekurencyjnie *)\n\nModule nat_neq_rec.\n\n(** A co to znaczy, że liczby naturalne nie są równe? *)\n\n(** Powinien być tylko jeden dowód na nierówność. *)\n\nFixpoint code (n m : nat) : Type :=\nmatch n, m with\n| 0, 0 => False\n| 0, S _ => True\n| S _, 0 => True\n| S n', S m' => code n' m'\nend.\n\nLemma isProp_code :\n  forall {n m : nat} (c1 c2 : code n m), c1 = c2.\n(* begin hide *)\nProof.\n  induction n as [| n'], m as [| m']; cbn.\n    1-3: destruct c1, c2; reflexivity.\n    apply IHn'.\nQed.\n(* end hide *)\n\nFixpoint encode {n m : nat} {struct n} : n <> m -> code n m.\n(* begin hide *)\nProof.\n  destruct n as [| n'], m as [| m']; cbn; intro p.\n    apply p. reflexivity.\n    exact I.\n    exact I.\n    apply encode. intro q. apply p. f_equal. exact q.\nDefined.\n(* end hide *)\n\nFixpoint decode {n m : nat} : code n m -> n <> m.\n(* begin hide *)\nProof.\n  destruct n as [| n'], m as [| m']; cbn; intro p.\n    contradiction.\n    inversion 1.\n    inversion 1.\n    intro q. apply (decode _ _ p). inversion q. reflexivity.\nDefined.\n(* end hide *)\n\nLemma encode_decode :\n  forall {n m : nat} (p : n <> m),\n    decode (encode p) = p.\nProof.\n  intros.\n  apply functional_extensionality.\n  destruct x.\n  contradiction.\nQed.\n\nLemma decode_encode :\n  forall {n m : nat} (c : code n m),\n    encode (decode c) = c.\nProof.\n  intros.\n  apply isProp_code.\nQed.\n\nEnd nat_neq_rec.\n\n(** ** Nierówność liczb naturalnych - induktywnie *)\n\nModule nat_neq_ind.\n\nInductive nat_neq : nat -> nat -> Prop :=\n| ZS : forall n : nat, nat_neq 0 (S n)\n| SZ : forall n : nat, nat_neq (S n) 0\n| SS : forall n m : nat, nat_neq n m -> nat_neq (S n) (S m).\n\nArguments ZS {n}.\nArguments SZ {n}.\nArguments SS {n m} _.\n\nScheme nat_neq_ind' := Induction for nat_neq Sort Prop.\n\nLemma isProp_nat_neq :\n  forall {n m : nat} (p q : nat_neq n m), p = q.\n(* begin hide *)\nProof.\n  induction p using nat_neq_ind';\n  dependent destruction q.\n    reflexivity.\n    reflexivity.\n    apply f_equal, IHp.\nQed.\n(* end hide *)\n\nFixpoint encode {n m : nat} : n <> m -> nat_neq n m :=\nmatch n, m with\n| 0, 0       => fun p => match p eq_refl with end\n| 0, S m'    => fun _ => @ZS m'\n| S n', 0    => fun _ => @SZ n'\n| S n', S m' => fun p => SS (@encode n' m' (fun p' => p (f_equal S p')))\nend.\n\nFixpoint decode {n m : nat} (c : nat_neq n m) : n <> m.\nProof.\n  destruct c.\n    inversion 1.\n    inversion 1.\n    inversion 1. apply (decode _ _ c). assumption.\nDefined.\n\nLemma encode_decode :\n  forall {n m : nat} (p : n <> m),\n    decode (encode p) = p.\n(* begin hide *)\nProof.\n  induction n as [| n'];\n  destruct  m as [| m'];\n  cbn; intros.\n    contradiction.\n    apply functional_extensionality. inversion x.\n    apply functional_extensionality. inversion x.\n    apply functional_extensionality. intro. contradiction.\nQed.\n(* end hide *)\n\nLemma decode_encode :\n  forall {n m : nat} (c : nat_neq n m),\n    encode (decode c) = c.\n(* begin hide *)\nProof.\n  induction c using nat_neq_ind'; cbn.\n    1-2: reflexivity.\n    f_equal. rewrite <- IHc. f_equal.\n      apply functional_extensionality.\n      destruct x. cbn. rewrite IHc. reflexivity.\nQed.\n(* end hide *)\n\nEnd nat_neq_ind.\n\nModule nat_eq_neq.\n\nImport nat_eq_ind nat_neq_ind.\n\nLemma nat_eq_dec :\n  forall n m : nat, nat_eq n m + nat_neq n m.\n(* begin hide *)\nProof.\n  induction n as [| n']; destruct m as [| m'].\n  - left. constructor.\n  - right. constructor.\n  - right. constructor.\n  - destruct (IHn' m').\n    + left. constructor. assumption.\n    + right. constructor. assumption.\nQed.\n(* end hide *)\n\nEnd nat_eq_neq.\n\n(** ** Nierówność list - rekursywnie *)\n\nFixpoint list_neq_rec {A : Type} (l1 l2 : list A) : Prop :=\nmatch l1, l2 with\n| [], [] => False\n| [], _ => True\n| _, [] => True\n| h1 :: t1, h2 :: t2 => h1 <> h2 \\/ list_neq_rec t1 t2\nend.\n\nLemma list_neq_rec_spec :\n  forall (A : Type) (l1 l2 : list A),\n    list_neq_rec l1 l2 -> l1 <> l2.\n(* begin hide *)\nProof.\n  induction l1 as [| h1 t1];\n  destruct l2 as [| h2 t2];\n  cbn; intros.\n    contradiction.\n    congruence.\n    congruence.\n    inversion 1; subst. destruct H.\n      contradiction.\n      apply (IHt1 _ H). reflexivity.\nQed.\n(* end hide *)\n\n(** ** Nierówność list - induktywnie *)\n\nInductive list_neq_ind {A : Type} : list A -> list A -> Prop :=\n| nil_cons : forall h t, list_neq_ind nil (cons h t)\n| cons_nil : forall h t, list_neq_ind (cons h t) nil\n| cons_cons1 :\n    forall h1 h2 t1 t2,\n      h1 <> h2 -> list_neq_ind (cons h1 t1) (cons h2 t2)\n| cons_cons2 :\n    forall h1 h2 t1 t2,\n      list_neq_ind t1 t2 -> list_neq_ind (cons h1 t1) (cons h2 t2).\n\nLemma list_neq_ind_spec :\n  forall {A : Type} (l1 l2 : list A),\n    list_neq_ind l1 l2 -> l1 <> l2.\nProof.\n  induction 1; cbn; congruence.\nQed.\n\nLemma list_neq_ind_list_neq_rec :\n  forall {A : Type} (l1 l2 : list A),\n    list_neq_ind l1 l2 -> list_neq_rec l1 l2.\nProof.\n  induction l1 as [| h1 t1]; destruct l2 as [| h2 t2]; cbn; inversion_clear 1.\n  1-2: trivial.\n  - left. assumption.\n  - right. apply IHt1. assumption.\nQed.\n\n(** ** Różność (słaby apartheid) list - rekursywnie *)\n\nFixpoint list_apart_rec\n  {A : Type} (R : A -> A -> Prop) (l1 l2 : list A) : Prop :=\nmatch l1, l2 with\n| [], [] => False\n| h1 :: t1, h2 :: t2 => R h1 h2 \\/ list_apart_rec R t1 t2\n| _, _ => True\nend.\n\nLemma list_apart_list_neq_rec :\n  forall {A : Type} (R : A -> A -> Prop) (l1 l2 : list A),\n    (forall x y : A, R x y -> x <> y) ->\n      list_apart_rec R l1 l2 -> list_neq_rec l1 l2.\nProof.\n  induction l1 as [| h1 t1 IH]; destruct l2 as [| h2 t2]; cbn; firstorder.\nQed.\n\n(** ** Różność (silny apartheid) list - rekursywnie *)\n\nFixpoint list_strong_apart_rec\n  {A : Type} (R : A -> A -> Type) (l1 l2 : list A) : Type :=\nmatch l1, l2 with\n| [], [] => False\n| h1 :: t1, h2 :: t2 => R h1 h2 + list_strong_apart_rec R t1 t2\n| _, _ => True\nend.\n\nLemma list_strong_apart_rec_list_apart :\n  forall {A : Type} (R : A -> A -> Prop) (l1 l2 : list A),\n    (forall x y : A, R x y -> x <> y) ->\n      list_strong_apart_rec R l1 l2 -> list_apart_rec R l1 l2.\nProof.\n  induction l1 as [| h1 t1 IH]; destruct l2 as [| h2 t2]; cbn; firstorder.\nQed.\n\n(** ** Różność list - induktywnie *)\n\nModule list_neq_ind.\n\nInductive list_neq\n  {A : Type} (R : A -> A -> Type) : list A -> list A -> Type :=\n| nc  : forall (h : A) (t : list A), list_neq R [] (h :: t)\n| cn  : forall (h : A) (t : list A), list_neq R (h :: t) []\n| cc1 : forall (h1 h2 : A) (t1 t2 : list A),\n          R h1 h2 -> list_neq R (h1 :: t1) (h2 :: t2)\n| cc2 : forall (h1 h2 : A) (t1 t2 : list A),\n          list_neq R t1 t2 -> list_neq R (h1 :: t1) (h2 :: t2).\n\n#[global] Hint Constructors list_neq : core.\n\nLemma list_neq_irrefl_aux :\n  forall {A : Type} {R : A -> A -> Prop} (l1 l2 : list A),\n    (forall x : A, R x x -> False) ->\n      list_neq R l1 l2 -> l1 <> l2.\n(* begin hide *)\nProof.\n  induction 2; inversion 1; subst.\n    apply (H _ r).\n    apply IHX. reflexivity.\nDefined.\n(* end hide *)\n\nLemma list_neq_irrefl_sym :\n  forall {A : Type} {R : A -> A -> Prop} (l1 l2 : list A),\n    (forall x y : A, R x y -> R y x) ->\n      list_neq R l1 l2 -> list_neq R l2 l1.\n(* begin hide *)\nProof.\n  induction 2.\n    1-3: constructor. apply H. assumption.\n    constructor 4. assumption.\nDefined.\n(* end hide *)\n\nLemma list_neq_cotrans :\n  forall {A : Type} {R : A -> A -> Prop} (l1 l3 : list A),\n    (forall x y z : A, R x z -> R x y + R y z) ->\n      list_neq R l1 l3 -> forall l2 : list A,\n        list_neq R l1 l2 + list_neq R l2 l3.\n(* begin hide *)\nProof.\n  induction 2; intros.\n    destruct l2; [right | left]; constructor.\n    destruct l2; [left | right]; constructor.\n    destruct l2 as [| h t].\n      left. constructor.\n      destruct (X _ h _ r).\n        left. constructor. assumption.\n        right. constructor. assumption.\n    destruct l2 as [| h t].\n      left. constructor.\n      destruct (IHX0 t).\n        left. constructor 4. assumption.\n        right. constructor 4. assumption.\nDefined.\n(* end hide *)\n\nInductive Exists2\n  {A : Type} (R : A -> A -> Type) : list A -> list A -> Type :=\n| E2_here :\n    forall {h1 h2 : A} (t1 t2 : list A),\n      R h1 h2 -> Exists2 R (h1 :: t1) (h2 :: t2)\n| E2_there :\n    forall {h1 h2 : A} {t1 t2 : list A},\n      Exists2 R t1 t2 -> Exists2 R (h1 :: t1) (h2 :: t2).\n\nLemma Exists2_list_neq :\n  forall {A : Type} {R : A -> A -> Prop} {l1 l2 : list A},\n    Exists2 R l1 l2 -> list_neq R l1 l2.\n(* begin hide *)\nProof.\n  induction 1.\n    constructor. assumption.\n    constructor 4. assumption.\nQed.\n(* end hide *)\n\nInductive DifferentStructure\n  {A : Type} : list A -> list A -> Type :=\n| DS_nc :\n    forall (h : A) (t : list A),\n      DifferentStructure [] (h :: t)\n| DS_cn :\n    forall (h : A) (t : list A),\n      DifferentStructure (h :: t) []\n| DS_cc :\n    forall (h1 h2 : A) {t1 t2 : list A},\n      DifferentStructure t1 t2 ->\n        DifferentStructure (h1 :: t1) (h2 :: t2).\n\n(** Insajt, że o ja pierdole: [list_neq] to w sumie [Exists2] lub\n    [DifferentStructure], czyli listy różnią się, gdy różnią się\n    na którymś elemencie lub mają różną długość. *)\n\nLemma lnE2 :\n  forall {A : Type} {R : A -> A -> Prop} {l1 l2 : list A},\n    list_neq R l1 l2 -> Exists2 R l1 l2 + DifferentStructure l1 l2.\n(* begin hide *)\nProof.\n  induction 1.\n    right. constructor.\n    right. constructor.\n    left. constructor. assumption.\n    destruct IHX.\n      left. constructor 2. assumption.\n      right. constructor. assumption.\nDefined.\n(* end hide *)\n\nLemma lnE2_conv :\n  forall {A : Type} {R : A -> A -> Prop} {l1 l2 : list A},\n    Exists2 R l1 l2 + DifferentStructure l1 l2 -> list_neq R l1 l2.\n(* begin hide *)\nProof.\n  destruct 1.\n    induction e.\n      constructor. assumption.\n      constructor 4. assumption.\n    induction d.\n      constructor.\n      constructor.\n      constructor 4. assumption.\nDefined.\n(* end hide *)\n\nLemma okurwa :\n  forall\n    (A : Type) (R : A -> A -> Type) (h1 h2 : A) (t1 t2 : list A)\n    (r1 : R h1 h2) (r2 : R h1 h2),\n      @inl _\n        (DifferentStructure (h1 :: t1) (h2 :: t2))\n        (E2_here R t1 t2 r1)\n      =\n      inl (E2_here R t1 t2 r2) ->\n        r1 = r2.\n(* begin hide *)\nProof.\n  assert (forall (A B : Type) (x y : A), @inl A B x = inl y -> x = y).\n    inversion 1. reflexivity.\n  intros. apply H in H0.\n  apply (f_equal\n    (fun x : Exists2 R (h1 :: t1) (h2 :: t2) =>\n      match x with\n      | E2_here _ _ _ r => Some r\n      | _             => None\n      end))\n  in H0.\n  inversion H0. reflexivity.\nQed.\n(* end hide *)\n\nLemma lnE2_lnE2_conv :\n  forall\n    {A : Type} {R : A -> A -> Prop} {l1 l2 : list A}\n    (c : list_neq R l1 l2),\n      lnE2_conv (lnE2 c) = c.\n(* begin hide *)\nProof.\n  induction c; cbn.\n    1-3: reflexivity.\n    destruct (list_neq_rect A R _) eqn: Heq.\n      cbn. f_equal. induction e; cbn in *.\n        dependent destruction c; cbn in *.\n          f_equal. symmetry. apply okurwa in Heq. assumption.\n          cbn in *. rewrite Heq in IHc. cbn in IHc. inversion IHc.\n        dependent destruction c.\n          cbn in *. inversion Heq.\n          cbn in *. rewrite Heq in IHc. cbn in IHc. assumption.\n      cbn. f_equal. dependent destruction c; cbn in *.\n        inversion Heq; subst; cbn. reflexivity.\n        inversion Heq; subst; cbn. reflexivity.\n        inversion Heq.\n        rewrite Heq in IHc. cbn in IHc. assumption.\nQed.\n(* end hide *)\n\nLemma lnE2_conv_lnE2 :\n  forall\n    {A : Type} {R : A -> A -> Prop} {l1 l2 : list A}\n    (x : Exists2 R l1 l2 + DifferentStructure l1 l2),\n      lnE2 (lnE2_conv x) = x.\n(* begin hide *)\nProof.\n  destruct x.\n    induction e; cbn in *.\n      reflexivity.\n      destruct (list_neq_rect A R _); inversion IHe. reflexivity.\n    induction d; cbn in *.\n      reflexivity.\n      reflexivity.\n      destruct (list_neq_rect A R _); inversion IHd. reflexivity.\nQed.\n(* end hide *)\n\nInductive DifferentStructure'\n  {A : Type} : list A -> list A -> SProp :=\n| DS'_nc :\n    forall (h : A) (t : list A),\n      DifferentStructure' [] (h :: t)\n| DS'_cn :\n    forall (h : A) (t : list A),\n      DifferentStructure' (h :: t) []\n| DS'_cc :\n    forall (h1 h2 : A) {t1 t2 : list A},\n      DifferentStructure' t1 t2 ->\n        DifferentStructure' (h1 :: t1) (h2 :: t2).\n\nLemma DS_DS' :\n  forall {A : Type} {l1 l2 : list A},\n    DifferentStructure l1 l2 -> DifferentStructure' l1 l2.\n(* begin hide *)\nProof.\n  induction 1; constructor; assumption.\nQed.\n(* end hide *)\n\nInductive sEmpty : SProp := .\n\nLemma sEmpty_rec' :\n  forall A : Type, sEmpty -> A.\n(* begin hide *)\nProof.\n  destruct 1.\nQed.\n(* end hide *)\n\nLemma DS'_spec :\n  forall {A : Type} {l1 l2 : list A},\n    DifferentStructure' l1 l2 -> l1 <> l2.\n(* begin hide *)\nProof.\n  induction l1 as [| h1 t1];\n  destruct l2 as [| h2 t2];\n  cbn; intros H Heq; inv Heq.\n    apply sEmpty_rec'. inv H.\n    apply (IHt1 t2).\n      inv H. assumption.\n      reflexivity.\nDefined.\n(* end hide *)\n\nLemma DS'_DS :\n  forall {A : Type} {l1 l2 : list A},\n    DifferentStructure' l1 l2 -> DifferentStructure l1 l2.\n(* begin hide *)\nProof.\n  induction l1 as [| h1 t1];\n  destruct l2 as [| h2 t2];\n  cbn; intros; try constructor.\n    apply sEmpty_rec'. inv H.\n    apply IHt1. inv H. assumption.\nDefined.\n(* end hide *)\n\nLemma isProp_DS :\n  forall\n    {A : Type} {l1 l2 : list A}\n    (p q : DifferentStructure l1 l2),\n      p = q.\n(* begin hide *)\nProof.\n  induction p; intro q.\n    refine (match q with DS_nc _ _   => _ end). reflexivity.\n    refine (match q with DS_cn _ _   => _ end). reflexivity.\n    dependent destruction q. f_equal. apply IHp.\nQed.\n(* end hide *)\n\nLemma DS_DS'_DS :\n  forall {A : Type} {l1 l2 : list A} (p : DifferentStructure l1 l2),\n    DS'_DS (DS_DS' p) = p.\n(* begin hide *)\nProof.\n  intros. apply isProp_DS.\nQed.\n(* end hide *)\n\nLemma DS'_DS_DS' :\n  forall {A : Type} {l1 l2 : list A} (p : DifferentStructure' l1 l2),\n    DS_DS' (DS'_DS p) = p.\nProof.\n  reflexivity.\nAbort.\n\nInductive sor (A : Type) (B : SProp) : Type :=\n| sinl : A -> sor A B\n| sinr : B -> sor A B.\n\nArguments sinl {A B} _.\nArguments sinr {A B} _.\n\nLemma lnE2' :\n  forall {A : Type} {R : A -> A -> Prop} {l1 l2 : list A},\n    list_neq R l1 l2 -> sor (Exists2 R l1 l2) (DifferentStructure' l1 l2).\n(* begin hide *)\nProof.\n  induction 1.\n    right. constructor.\n    right. constructor.\n    left. constructor. assumption.\n    destruct IHX.\n      left. constructor 2. assumption.\n      right. constructor. assumption.\nDefined.\n(* end hide *)\n\nLemma lnE2'_conv :\n  forall {A : Type} {R : A -> A -> Prop} {l1 l2 : list A},\n    sor (Exists2 R l1 l2) (DifferentStructure' l1 l2) -> list_neq R l1 l2.\n(* begin hide *)\nProof.\n  destruct 1.\n    induction e.\n      constructor. assumption.\n      constructor 4. assumption.\n    revert l2 d.\n    induction l1 as [| h1 t1]; destruct l2 as [| h2 t2]; cbn; intro.\n      apply sEmpty_rec'. inv d.\n      constructor.\n      constructor.\n      constructor 4. apply IHt1. inv d. assumption.\nDefined.\n(* end hide *)\n\nLemma okurwa' :\n  forall\n    (A : Type) (R : A -> A -> Type) (h1 h2 : A) (t1 t2 : list A)\n    (r1 : R h1 h2) (r2 : R h1 h2),\n      @sinl _\n        (DifferentStructure' (h1 :: t1) (h2 :: t2))\n        (E2_here R t1 t2 r1)\n      =\n      sinl (E2_here R t1 t2 r2) ->\n        r1 = r2.\n(* begin hide *)\nProof.\n  assert (forall A B (x y : A), @sinl A B x = sinl y -> x = y).\n    inversion 1. reflexivity.\n  intros. apply H in H0.\n  apply (f_equal\n    (fun x : Exists2 R (h1 :: t1) (h2 :: t2) =>\n      match x with\n      | E2_here _ _ _ r => Some r\n      | _             => None\n      end))\n  in H0.\n  inversion H0. reflexivity.\nQed.\n(* end hide *)\n\nLemma lnE2'_lnE2'_conv :\n  forall\n    {A : Type} {R : A -> A -> Prop} {l1 l2 : list A}\n    (c : list_neq R l1 l2),\n      lnE2'_conv (lnE2' c) = c.\n(* begin hide *)\nProof.\n  induction c; cbn.\n    1-3: reflexivity.\n    destruct (list_neq_rect A R _) eqn: Heq.\n      cbn. f_equal. induction e; cbn in *.\n        dependent destruction c; cbn in *.\n          f_equal. symmetry. apply okurwa' in Heq. assumption.\n          cbn in *. rewrite Heq in IHc. cbn in IHc. inversion IHc.\n        dependent destruction c.\n          cbn in *. inversion Heq.\n          cbn in *. rewrite Heq in IHc. cbn in IHc. assumption.\n      cbn. f_equal. dependent destruction c; cbn in *.\n        inversion Heq; subst; cbn. reflexivity.\n        inversion Heq; subst; cbn. reflexivity.\n        inversion Heq.\n        rewrite Heq in IHc. cbn in IHc. assumption.\nQed.\n(* end hide *)\n\nLemma lnE2'_conv_lnE2' :\n  forall\n    {A : Type} {R : A -> A -> Prop} {l1 l2 : list A}\n    (x : sor (Exists2 R l1 l2) (DifferentStructure' l1 l2)),\n      lnE2' (lnE2'_conv x) = x.\nProof.\n  destruct x.\n    induction e; cbn in *.\n      reflexivity.\n      destruct (list_neq_rect A R _); inversion IHe. reflexivity.\n    revert l2 d.\n    induction l1 as [| h1 t1]; destruct l2 as [| h2 t2]; cbn; intro.\n      apply sEmpty_rec. inv d.\n      reflexivity.\n      reflexivity.\nAbort.\n\n(** Wnioski: próba użycia tutaj [SProp] jest bardzo poroniona. *)\n\nEnd list_neq_ind.\n\n(** ** Nierówność liczb konaturalnych - induktywnie *)\n\nFrom Typonomikon Require F2.\n\nModule conat_neq.\n\nImport F3.\n\nInductive conat_neq : conat -> conat -> Prop :=\n| cnzs :\n    forall c : conat, conat_neq zero (succ c)\n| cnsz :\n    forall c : conat, conat_neq (succ c) zero\n| cnss :\n    forall n m : conat, conat_neq n m -> conat_neq (succ n) (succ m).\n\nLemma conat_neq_spec :\n  forall n m : conat,\n    conat_neq n m -> n <> m.\n(* begin hide *)\nProof.\n  induction 1; intro Heq; inversion Heq; congruence.\nQed.\n(* end hide *)\n\nLemma conat_neq_irrefl :\n  forall n : conat, ~ conat_neq n n.\n(* begin hide *)\nProof.\n  intros n Hneq. eapply conat_neq_spec; eauto.\nQed.\n(* end hide *)\n\nEnd conat_neq.\n\n(** ** Nierówność strumieni *)\n\nFrom Typonomikon Require F3.\n\nModule Stream_neq.\n\nImport F2.\n\nInductive Stream_neq\n  {A : Type} : Stream A -> Stream A -> Type :=\n| Stream_apart_hd' :\n    forall t1 t2 : Stream A,\n      hd t1 <> hd t2 -> Stream_neq t1 t2\n| Stream_apart_tl' :\n    forall t1 t2 : Stream A,\n      Stream_neq (tl t1) (tl t2) -> Stream_neq t1 t2.\n\nLemma Stream_neq_not_sim :\n  forall {A : Type} {s1 s2 : Stream A},\n    Stream_neq s1 s2 -> ~ sim s1 s2.\n(* begin hide *)\nProof.\n  induction 1; intros []; contradiction.\nQed.\n(* end hide *)\n\nLemma Stream_neq_neq :\n  forall {A : Type} {s1 s2 : Stream A},\n    Stream_neq s1 s2 -> s1 <> s2.\n(* begin hide *)\nProof.\n  induction 1; intros ->; contradiction.\nQed.\n(* end hide *)\n\nEnd Stream_neq.\n\n(** ** Różność (słaby apartheid) strumieni - induktywnie *)\n\nFrom Typonomikon Require F3.\n\nModule Stream_apart.\n\nImport F2 Stream_neq.\n\nInductive Stream_apart\n  {A : Type} (R : A -> A -> Prop) : Stream A -> Stream A -> Type :=\n| Stream_apart_hd :\n    forall (h1 h2 : A) (t1 t2 : Stream A),\n      R h1 h2 -> Stream_apart R (scons h1 t1) (scons h2 t2)\n| Stream_apart_tl :\n    forall (h1 h2 : A) (t1 t2 : Stream A),\n      Stream_apart R t1 t2 -> Stream_apart R (scons h1 t1) (scons h2 t2).\n\nLemma Stream_apart_not_sim :\n  forall {A : Type} {R : A -> A -> Prop} {s1 s2 : Stream A},\n    (forall x : A, ~ R x x) ->\n      Stream_apart R s1 s2 -> ~ sim s1 s2.\n(* begin hide *)\nProof.\n  induction 2; intros Hsim; inversion Hsim; cbn in *; subst; clear Hsim.\n  - apply (H h2). assumption.\n  - contradiction.\nQed.\n(* end hide *)\n\nLemma Stream_neq_Stream_apart :\n  forall {A : Type} {s1 s2 : Stream A},\n    Stream_neq s1 s2 ->\n      Stream_apart (fun x y => x <> y) s1 s2.\n(* begin hide *)\nProof.\n  induction 1.\nAdmitted.\n(*\n  - destruct t1, t2. cbn in *. left. assumption.\n  - destruct t1, t2. cbn in *. right. assumption.\nQed.\n*)\n(* end hide *)\n\nLemma Stream_apart_Stream_neq :\n  forall {A : Type} {R : A -> A -> Prop} {s1 s2 : Stream A},\n    (forall x : A, ~ R x x) ->\n      Stream_apart R s1 s2 -> Stream_neq s1 s2.\n(* begin hide *)\nProof.\n  induction 2.\n  - left. cbn. intro. subst. apply (H _ r).\n  - right. cbn. assumption.\nQed.\n(* end hide *)\n\nEnd Stream_apart.\n\n(** ** Różność (silny apartheid) strumieni - induktywnie *)\n\nFrom Typonomikon Require F3.\n\nModule Stream_strong_apart.\n\nImport F2 Stream_apart.\n\nInductive Stream_strong_apart\n  {A : Type} (R : A -> A -> Type) : Stream A -> Stream A -> Type :=\n| Stream_strong_apart_hd :\n    forall s1 s2 : Stream A,\n      R (hd s1) (hd s2) -> Stream_strong_apart R s1 s2\n| Stream_strong_apart_tl :\n    forall s1 s2 : Stream A,\n      Stream_strong_apart R (tl s1) (tl s2) -> Stream_strong_apart R s1 s2.\n\nLemma Stream_strong_apart_spec :\n  forall {A : Type} {R : A -> A -> Prop} {s1 s2 : Stream A},\n    (forall x : A, ~ R x x) ->\n      Stream_strong_apart R s1 s2 -> Stream_apart R s1 s2.\n(* begin hide *)\nProof.\n  intros A R s1 s2 HR HSsa; induction HSsa.\nAdmitted.\n(* end hide *)\n\nEnd Stream_strong_apart.\n\n(** ** Różność kolist *)\n\nFrom Typonomikon Require F4.\n\nModule CoList_apart.\n\nImport F4.\n\nInductive CoList_apart {A : Type} (R : A -> A -> Type) (l1 l2 : CoList A) : Type :=\n| CLa_nil_cons :\n    uncons l1 = NilF -> uncons l2 <> NilF -> CoList_apart R l1 l2\n| CLa_cons_nil :\n    uncons l1 <> NilF -> uncons l2 = NilF -> CoList_apart R l1 l2\n| CLa_head :\n    forall\n      {h1 : A} {t1 : CoList A} (Hu1 : uncons l1 = ConsF h1 t1)\n      {h2 : A} {t2 : CoList A} (Hu2 : uncons l2 = ConsF h2 t2),\n        R h1 h2 -> CoList_apart R l1 l2\n| CLa_tail :\n    forall\n      {h1 : A} {t1 : CoList A} (Hu1 : uncons l1 = ConsF h1 t1)\n      {h2 : A} {t2 : CoList A} (Hu2 : uncons l2 = ConsF h2 t2),\n        CoList_apart R t1 t2 -> CoList_apart R l1 l2.\n\nLemma CoList_apart_spec :\n  forall {A : Type} {R : A -> A -> Type} {l1 l2 : CoList A},\n    (forall x : A, R x x -> False) ->\n      CoList_apart R l1 l2 -> ~ lsim l1 l2.\n(* begin hide *)\nProof.\n  intros A R l1 l2 HR; induction 1; intros [Hlsim].\n  - inversion Hlsim; subst; clear Hlsim; congruence.\n  - inversion Hlsim; subst; clear Hlsim; congruence.\n  - inversion Hlsim; subst; clear Hlsim.\n    + congruence.\n    + apply (HR h3). congruence.\n  - inversion Hlsim; subst; clear Hlsim; congruence.\nQed.\n(* end hide *)\n\nEnd CoList_apart.\n\n(** ** Różność funkcji *)\n\n(** Funkcje są różne (w silnym sensie), gdy różnią się dla jakiegoś\n    argumentu. *)\n\nInductive fun_apart\n  {A B : Type} (R : B -> B -> Type) (f g : A -> B) : Type :=\n| fun_apart' : forall {x : A}, R (f x) (g x) -> fun_apart R f g.\n\nLemma fun_apart_spec :\n  forall {A B : Type} (R : B -> B -> Type) (f g : A -> B),\n    (forall x : B, R x x -> False) ->\n      fun_apart R f g -> f <> g.\n(* begin hide *)\nProof.\n  intros A B R f g HR [x r] ->.\n  apply (HR (g x)). apply r.\nQed.\n(* end hide *)\n\nLemma fun_apart_spec' :\n  forall {A B : Type} (R : B -> B -> Type) (f g : A -> B),\n    (forall x : B, R x x -> False) ->\n      fun_apart R f g -> ~ (forall x : A, f x = g x).\n(* begin hide *)\nProof.\n  intros A B R f g HR [x r] Hext.\n  apply (HR (g x)). rewrite <- Hext at 1. assumption.\nQed.\n(* end hide *)\n\nInductive dep_fun_apart\n  {A : Type} {B : A -> Type}\n  (R : forall x : A, B x -> B x -> Type)\n  (f g : forall x : A, B x) : Type :=\n| dep_fun_apart' : forall {x : A}, R x (f x) (g x) -> dep_fun_apart R f g.\n\nLemma dep_fun_apart_spec :\n  forall\n    {A : Type} {B : A -> Type}\n    (R : forall x : A, B x -> B x -> Type)\n    (f g : forall x : A, B x)\n    (HR : forall {x : A} (y : B x), R x y y -> False),\n      dep_fun_apart R f g -> f <> g.\n(* begin hide *)\nProof.\n  intros A B R f g HR [x r] ->.\n  apply (HR _ (g x)). apply r.\nQed.\n(* end hide *)\n\nLemma dep_fun_apart_spec' :\n  forall\n    {A : Type} {B : A -> Type}\n    (R : forall x : A, B x -> B x -> Type)\n    (f g : forall x : A, B x)\n    (HR : forall {x : A} (y : B x), R x y y -> False),\n      dep_fun_apart R f g -> ~ (forall x : A, f x = g x).\n(* begin hide *)\nProof.\n  intros A B R f g HR [x r] Hext.\n  apply (HR _ (g x)). rewrite <- Hext at 1. assumption.\nQed.\n(* end hide *)\n\n(** * Protokoły różnicowe *)\n\nModule DiffProtocols.\n\n(** [list_neq_ind.list_neq] to pokazanie na odpowiadające sobie miejsca w\n    dwóch listach, które różnią się znajdującym się tam elementem. *)\n\nInductive ListDiffProtocol\n  {A : Type} (R : A -> A -> Type) : list A -> list A -> Type :=\n| nn'  : ListDiffProtocol R [] []\n| nc'  : forall (h : A) (t : list A), ListDiffProtocol R [] (h :: t)\n| cn'  : forall (h : A) (t : list A), ListDiffProtocol R (h :: t) []\n| cc1' :\n  forall (h1 h2 : A) (t1 t2 : list A),\n    R h1 h2 -> ListDiffProtocol R t1 t2 ->\n      ListDiffProtocol R (h1 :: t1) (h2 :: t2)\n| cc2' :\n  forall (h : A) (t1 t2 : list A),\n    ListDiffProtocol R t1 t2 ->\n      ListDiffProtocol R (h :: t1) (h :: t2).\n\n(** [ListDiffProtocol] to sprawozdanie mówiące, w których miejscach listy\n    się różnią, a w których są takie same (i od którego miejsca jedna jest\n    dłuższa od drugiej).\n\n    Spróbujmy udowodnić, że jeżeli elementy mogą się różnić tylko na\n    jeden sposób, to protokół jest unikalny. *)\n\nLemma isProp_ListDiffProtocol :\n  forall {A : Type} {R : A -> A -> Prop} {l1 l2 : list A},\n    (forall (x y : A) (p q : R x y), p = q) ->\n    (forall x : A, ~ R x x) ->\n      forall p q : ListDiffProtocol R l1 l2, p = q.\nProof.\n  induction p; dependent destruction q; try reflexivity; f_equal.\n    apply H.\n    apply IHp.\n    destruct (H0 _ r).\n    destruct (H0 _ r).\n    apply IHp.\nQed.\n\n(** Protokoły są zwrotne i symetryczne, ale niekoniecznie przechodnie. *)\n\nLemma proto_refl :\n  forall {A : Type} {R : A -> A -> Type} (l : list A),\n    ListDiffProtocol R l l.\n(* begin hide *)\nProof.\n  induction l as [| h t]; cbn.\n    constructor.\n    constructor 5. assumption.\nQed.\n(* end hide *)\n\nLemma proto_sym :\n  forall {A : Type} {R : A -> A -> Type} {l1 l2 : list A},\n    (forall x y : A, R x y -> R y x) ->\n      ListDiffProtocol R l1 l2 -> ListDiffProtocol R l2 l1.\n(* begin hide *)\nProof.\n  induction 2.\n    1-4: constructor.\n      apply X. assumption.\n      assumption.\n    constructor 5. assumption.\nQed.\n(* end hide *)\n\n#[global] Hint Constructors ListDiffProtocol : core.\n\nLemma proto_trans :\n  forall {A : Type} {R : A -> A -> Type} {l1 l2 l3 : list A},\n    (forall x y z : A, R x y -> R y z -> R x z) ->\n      ListDiffProtocol R l1 l2 -> ListDiffProtocol R l2 l3 ->\n        ListDiffProtocol R l1 l3.\nProof.\n  intros * H HLDP. revert l3.\n  induction HLDP; inversion 1; subst; auto.\n    admit.\nAbort.\n\n(** Protokół różnicowy dla funkcji mówi, dla których argumentów wyniki\n    są takie same, a dla których są różne. *)\n\nDefinition FunDiffProtocol\n  {A B : Type} (R : B -> B -> Prop) (f g : A -> B) : Type :=\n    forall x : A, f x = g x \\/ R (f x) (g x).\n\nEnd DiffProtocols.", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/book/H4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.6714519751444109}}
{"text": "Require Import Arith Coq.Lists.List Setoid Coq.Lists.SetoidList Omega.\nRequire Export Infra.Option EqDec AutoIndTac Util Get Drop.\n\nSet Implicit Arguments.\n\nFixpoint take n X (L:list X) :=\n  match n, L with\n    | S n, x::L => x::take n L\n    | _, _ => nil\n  end.\n\nLemma take_nil (X:Type) n\n  : @take n X nil = nil.\nProof.\n  destruct n; eauto.\nQed.\n\nLemma get_take_lt k X (L:list X) n x\n: get (take k L) n x -> n < k.\nProof.\n  intros. general induction k; destruct L; simpl in *; isabsurd.\n  - inv H; eauto; try omega.\n    + exploit IHk; eauto. omega.\nQed.\n\nLemma get_take_get k X (L:list X) n x\n: get (take k L) n x -> get L n x.\nProof.\n  intros. general induction k; destruct L; simpl in *; isabsurd.\n  inv H; eauto using get.\nQed.\n\nLemma take_length_le X (L:list X) n\n  : n <= length L -> length (take n L) = n.\nProof.\n  intros. general induction L; destruct n; simpl in *; try omega; eauto.\n  rewrite IHL; eauto; omega.\nQed.\n\n\nLemma take_length_ge X (L:list X) n\n  : n >= length L -> length (take n L) = length L.\nProof.\n  intros. general induction L; destruct n; simpl in *; try omega; eauto.\n  rewrite IHL; eauto; omega.\nQed.\n\nLemma take_length X (L:list X) n\n  : length (take n L) = min (length L) n.\nProof.\n  decide (n < length L).\n  - rewrite take_length_le; try omega.\n    rewrite min_r; omega.\n  - eapply not_lt in n0.\n    rewrite min_l; try omega.\n    eapply take_length_ge; eauto.\nQed.\n\nLemma take_get X (L:list X) n k x\n  : get (take k L) n x -> get L n x /\\ n < k.\nProof.\n  intros.\n  general induction H ; destruct k, L; simpl in *; inv Heql.\n  - split; eauto using get; omega.\n  - exploit IHget; eauto; dcr.\n    split; eauto using get; omega.\nQed.\n\nLemma get_take X (L:list X) n k x\n  : n < k\n    -> get L n x\n    -> get (take k L) n x.\nProof.\n  intros LE GET.\n  general induction GET; destruct k; simpl; eauto using get; try now (exfalso; omega).\n  - econstructor.\n    eapply IHGET. omega.\nQed.\n\n Lemma map_take X Y (f:X -> Y) (L:list X) n\n  : f ⊝ take n L = take n (f ⊝ L).\nProof.\n  general induction n; simpl; eauto.\n  destruct L; simpl; eauto.\n  f_equal; eauto.\nQed.\n\nLemma take_app_le n X (L L':list X)\n  : n <= length L\n    -> take n (L ++ L') = take n L.\nProof.\n  intros. general induction n; simpl; eauto.\n  destruct L; isabsurd; simpl.\n  rewrite IHn; eauto. simpl in *; omega.\nQed.\n\nLemma take_app_ge n X (L L':list X)\n  : n >= length L\n    -> take n (L ++ L') = L ++ take (n - length L) L'.\nProof.\n  intros. general induction n; simpl; eauto.\n  - destruct L; simpl in *; eauto. exfalso; omega.\n  - destruct L; simpl in *; eauto.\n    rewrite IHn; eauto. omega.\nQed.\n\nLemma take_eq_ge n X (L:list X)\n  : n >= ❬L❭ -> take n L = L.\nProof.\n  intros. general induction n; destruct L; simpl in *; eauto.\n  - exfalso; omega.\n  - rewrite IHn; eauto. omega.\nQed.\n\n\nLemma take_app_eq n X (L L':list X)\n  : n = length L\n    -> take n (L ++ L') = L.\nProof.\n  intros. subst. general induction L; simpl; eauto.\n  f_equal; eauto.\nQed.\n\n\nLemma drop_rev X (L:list X) k\n  : drop k L = rev (take (❬L❭ - k) (rev L)).\nProof.\n  general induction k.\n  - simpl. rewrite take_eq_ge; eauto.\n    rewrite rev_rev; eauto. rewrite rev_length; omega.\n  - simpl. rewrite IHk.\n    f_equal. destruct L. simpl; eauto.\n    simpl.\n    rewrite !take_app_le. reflexivity.\n    rewrite rev_length. omega.\nQed.\n\n\nLemma take_take_lt X (L:list X) n m\n  : n < m\n    -> take n L = take n (take m L).\nProof.\n  intros. general induction n; destruct L, m; simpl; eauto.\n  - omega.\n  - erewrite IHn; eauto. omega.\nQed.\nLemma take_take_app X (L:list X) n m\n  : n < m\n    -> take m L = take n L ++ take (m - n) (drop n L).\nProof.\n  intros. general induction n; destruct L, m; simpl; eauto; try omega.\n  - rewrite drop_nil, take_nil; eauto.\n  - rewrite IHn; eauto. omega.\nQed.\n\nLemma take_one X (L:list X) x k\n  : k > 0\n    -> take k (x::L) = x :: take (k - 1) L.\nProof.\n  intros; destruct k; simpl.\n  - omega.\n  - f_equal. f_equal. omega.\nQed.\n\nLemma take_InA A (R:A->A->Prop) L n x\n  : InA R x (take n L)\n    -> InA R x L.\nProof.\n  general induction n; destruct L; simpl in *; isabsurd.\n  invt InA; eauto using InA.\nQed.\n\nLemma nodup_take A (R:A->A->Prop) L n\n  : NoDupA R L\n    -> NoDupA R (take n L).\nProof.\n  intros. general induction n; invt NoDupA; simpl; eauto using NoDupA.\n  econstructor; eauto. intro. eapply take_InA in H2; eauto.\nQed.\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Infra/Take.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.6714519750304108}}
{"text": "Require Import Setoid.\nRequire Import Morphisms.\nRequire Import Coq.Program.Basics.\n\nUnset Printing Records.\n\nFrom Ordinal Require Import Defs.\nFrom Ordinal Require Import Operators.\nFrom Ordinal Require Import Arith.\n\n\nInductive countableOrd : Set :=\n| czero  : countableOrd\n| climit : (nat -> countableOrd) -> countableOrd.\n\nFixpoint countableToOrd (x:countableOrd) : Ord :=\n  match x with\n  | czero => zeroOrd\n  | climit f => ord nat (fun i => countableToOrd (f i))\n  end.\n\nCanonical Structure Ω := ord countableOrd countableToOrd.\n\nDefinition Ωc := ord { o:countableOrd | complete (sz o) } (fun o => countableToOrd (proj1_sig o)).\n\nLemma countable_zero_dec (x:Ω) : x <= zeroOrd \\/ zeroOrd < x.\nProof.\n  destruct x; simpl; auto with ord.\n  right.\n  rewrite ord_lt_unfold. simpl. exists 0%nat.\n  apply zero_least.\nQed.\n\nParameter nat_sum : nat -> nat + nat.\nParameter nat_unsum : nat + nat -> nat.\n\nHypothesis nat_sum_inv : forall n, nat_unsum (nat_sum n) = n.\nHypothesis nat_unsum_inv : forall xy, nat_sum (nat_unsum xy) = xy.\n\nParameter nat_prod : nat -> nat * nat.\nParameter nat_unprod : nat * nat -> nat.\n\nHypothesis nat_prodinv : forall n, nat_unprod (nat_prod n) = n.\nHypothesis nat_unprod_inv : forall xy, nat_prod (nat_unprod xy) = xy.\n\nDefinition club (x y : Ω) :=\n  match x, y with\n  | czero, _ => y\n  | _, czero => x\n  | climit fx, climit fy =>\n    climit (fun i => match nat_sum i with\n                     | inl a => fx a\n                     | inr b => fy b\n                     end)\n  end.\n\nLemma club_eq : forall x y:Ω, club x y ≈ x ⊔ y.\nProof.\n  split.\n  - destruct x; destruct y; simpl.\n    + apply zero_least.\n    + rewrite ord_le_unfold; simpl; intro i.\n      rewrite ord_lt_unfold; simpl. exists (inr i).\n      reflexivity.\n    + rewrite ord_le_unfold; simpl; intro i.\n      rewrite ord_lt_unfold; simpl. exists (inl i).\n      reflexivity.\n    + rewrite ord_le_unfold; simpl; intro i.\n      rewrite ord_lt_unfold; simpl.\n      exists (nat_sum i).\n      destruct (nat_sum i); simpl; reflexivity.\n  - destruct x; destruct y; simpl.\n    + rewrite ord_le_unfold; simpl; intro.\n      destruct a; exfalso; auto.\n    + rewrite ord_le_unfold; simpl; intro.\n      destruct a. exfalso; auto.\n      rewrite ord_lt_unfold; exists n; reflexivity.\n    + rewrite ord_le_unfold; simpl; intro.\n      destruct a. \n      rewrite ord_lt_unfold; exists n; reflexivity.\n      exfalso; auto.\n    + rewrite ord_le_unfold; simpl; intro.\n      rewrite ord_lt_unfold; simpl.\n      exists (nat_unsum a).\n      rewrite nat_unsum_inv.\n      destruct a; simpl; reflexivity.\nQed.\n\n\nFixpoint club' (x y:countableOrd) : countableOrd :=\n  match x, y with\n  | czero, _ => y\n  | _, czero => x\n  | climit fx, climit fy =>\n    climit (fun i => let (j,k) := nat_prod i in\n                      club' (fx j) (fy k))\n  end.\n\n\nLemma club'_le1 : forall (x y:countableOrd), countableToOrd x <= countableToOrd (club' x y).\nProof.\n  simpl in *.\n  induction x as [|f Hx].\n  - intros. simpl. apply zero_least.\n  - intros [|g].\n    + simpl. reflexivity.\n    + simpl. rewrite ord_le_unfold.\n      intro i. simpl.\n      rewrite ord_lt_unfold; simpl.\n      exists (nat_unprod (i, 0%nat)).\n      rewrite nat_unprod_inv.\n      apply Hx.\nQed.\n\nLemma club'_le2 : forall (x y:countableOrd), countableToOrd y <= countableToOrd (club' x y).\nProof.\n  simpl in *.\n  intros x y; revert x.\n  induction y as [|g Hy].\n  - intros. simpl. apply zero_least.\n  - intros [|f].\n    + simpl. reflexivity.\n    + simpl. rewrite ord_le_unfold.\n      intro i. simpl.\n      rewrite ord_lt_unfold; simpl.\n      exists (nat_unprod (0%nat, i)).\n      rewrite nat_unprod_inv.\n      apply Hy.\nQed.\n\nLemma club'_least : forall (x y z:countableOrd),\n  complete (sz z) ->\n  sz x <= sz z ->\n  sz y <= sz z ->\n  sz (club' x y) <= sz z.\nProof.\n  induction x as [|f Hx].\n  { simpl; intros; auto. }\n  intros [|g].\n  { simpl; intros; auto. }\n  simpl; intros.\n  destruct z as [|h].\n  { simpl in H0. destruct (ord_le_subord _ _ H0 0%nat) as [[] _]. }\n\n  rewrite ord_le_unfold; simpl; intro i.\n  set (j := fst (nat_prod i)).\n  set (k := snd (nat_prod i)).\n  destruct (ord_le_subord _ _ H0 j) as [j' Hj]. simpl in Hj.\n  destruct (ord_le_subord _ _ H1 k) as [k' Hk]. simpl in Hk.\n  destruct (complete_directed _ H j' k') as [l [Hj' Hk']].\n  rewrite ord_lt_unfold. simpl. exists l.\n  destruct (nat_prod i).\n  apply Hx; auto.\n  apply H.\n  apply ord_le_trans with (sz (h j')); auto.\n  apply ord_le_trans with (sz (h k')); auto.\nQed.\n\nLemma club'_complete : forall (x y:countableOrd),\n  complete (sz x) -> complete (sz y) -> complete (sz (club' x y)).\nProof.\n  induction x as [|f Hx].\n  { simpl; intros; auto. }\n  destruct y as [|g].\n  { simpl; intros; auto. }\n  intros. simpl.\n  repeat split.\n  - intros a b. \n    set (xa := fst (nat_prod a)).\n    set (ya := snd (nat_prod a)).\n    set (xb := fst (nat_prod b)).\n    set (yb := snd (nat_prod b)).\n    destruct (complete_directed _ H xa xb) as [x' [??]].\n    destruct (complete_directed _ H0 ya yb) as [y' [??]].\n    exists (nat_unprod (x', y')).\n    rewrite nat_unprod_inv.\n    destruct (nat_prod a).\n    destruct (nat_prod b).\n    split.\n    + apply club'_least. apply Hx.\n      apply H. apply H0.\n      unfold xa, ya, xb, yb in *. simpl in *.\n      rewrite H1. apply club'_le1.\n      unfold xa, ya, xb, yb in *. simpl in *.\n      rewrite H3. apply club'_le2.\n    + apply club'_least. apply Hx.\n      apply H. apply H0.\n      unfold xa, ya, xb, yb in *. simpl in *.\n      rewrite H2. apply club'_le1.\n      unfold xa, ya, xb, yb in *. simpl in *.\n      rewrite H4. apply club'_le2.\n  - left. exact (inhabits 0%nat).\n  - intro i.\n    destruct (nat_prod i).\n    apply Hx. apply H. apply H0.\nQed.\n\nLemma Ωc_complete : complete Ωc.\nProof.\n  simpl. repeat split.\n  - intros [o1 Ho1] [o2 Ho2]. simpl.\n    exists (exist _ (club' o1 o2) (club'_complete o1 o2 Ho1 Ho2)).\n    simpl. split; [ apply club'_le1 | apply club'_le2 ].\n  - left. exact (inhabits (exist _ czero zero_complete)).\n  - intros [o H]. simpl. auto.\nQed.\n", "meta": {"author": "robdockins", "repo": "ordinals", "sha": "063164521baddfc99ab8c2d222cb01637e8833e1", "save_path": "github-repos/coq/robdockins-ordinals", "path": "github-repos/coq/robdockins-ordinals/ordinals-063164521baddfc99ab8c2d222cb01637e8833e1/Ordinal/Countable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485603, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6714511182361637}}
{"text": "Section ml.\nVariables A B:Prop.\nTheorem Dm_nore: not (or A B) <-> and (not A) (not B).\nProof.\n    split.\n    intro H0; split.\n    intro Ha; elim H0.\n    left; assumption.\n    intro Hb; elim H0.\n    right; assumption.\n    intro H1.\n    intro H2.\n    elim H1; intros Na Nb.\n    elim H2; assumption.\nQed.\nEnd ml.\n\nCheck Dm_nore.", "meta": {"author": "ya0201", "repo": "mycoq-learning", "sha": "cc25eeeb8ef82917af329d69c4ea079935155005", "save_path": "github-repos/coq/ya0201-mycoq-learning", "path": "github-repos/coq/ya0201-mycoq-learning/mycoq-learning-cc25eeeb8ef82917af329d69c4ea079935155005/acintui/Dm_nore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6713704442195865}}
{"text": "(** * Poly: Polymorphism and Higher-Order Functions *)\n\n(* Final reminder: Please do not put solutions to the exercises in\n   publicly accessible places.  Thank you!! *)\n\n(* Suppress some annoying warnings from Coq: *)\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Lists.\n\n(* ################################################################# *)\n(** * Polymorphism *)\n\n(** In this chapter we continue our development of basic\n    concepts of functional programming.  The critical new ideas are\n    _polymorphism_ (abstracting functions over the types of the data\n    they manipulate) and _higher-order functions_ (treating functions\n    as data).  We begin with polymorphism. *)\n\n(* ================================================================= *)\n(** ** Polymorphic Lists *)\n\n(** For the last chapter, we've been working just\n    with lists of numbers.  Obviously, interesting programs also need\n    to be able to manipulate lists with elements from other types --\n    lists of strings, lists of booleans, lists of lists, etc.  We\n    _could_ just define a new inductive datatype for each of these,\n    for example... *)\n\nInductive boollist : Type :=\n  | bool_nil\n  | bool_cons (b : bool) (l : boollist).\n\n(** ... but this would quickly become tedious, partly because we\n    have to make up different constructor names for each datatype, but\n    mostly because we would also need to define new versions of all\n    our list manipulating functions ([length], [rev], etc.) and all\n    their properties ([rev_length], [app_assoc], etc.) for each\n    new datatype definition. *)\n\n(** To avoid all this repetition, Coq supports _polymorphic_\n    inductive type definitions.  For example, here is a _polymorphic\n    list_ datatype. *)\n\nInductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\n(** This is exactly like the definition of [natlist] from the\n    previous chapter, except that the [nat] argument to the [cons]\n    constructor has been replaced by an arbitrary type [X], a binding\n    for [X] has been added to the header, and the occurrences of\n    [natlist] in the types of the constructors have been replaced by\n    [list X].  (We can re-use the constructor names [nil] and [cons]\n    because the earlier definition of [natlist] was inside of a\n    [Module] definition that is now out of scope.)\n\n    What sort of thing is [list] itself?  One good way to think\n    about it is that [list] is a _function_ from [Type]s to\n    [Inductive] definitions; or, to put it another way, [list] is a\n    function from [Type]s to [Type]s.  For any particular type [X],\n    the type [list X] is an [Inductive]ly defined set of lists whose\n    elements are of type [X]. *)\n\nCheck list.\n(* ===> list : Type -> Type *)\n\n(** The parameter [X] in the definition of [list] automatically\n    becomes a parameter to the constructors [nil] and [cons] -- that\n    is, [nil] and [cons] are now polymorphic constructors; when we use\n    them, we must now provide a first argument that is the type of the\n    list they are building. For example, [nil nat] constructs the\n    empty list of type [nat]. *)\n\nCheck (nil nat).\n(* ===> nil nat : list nat *)\n\n(** Similarly, [cons nat] adds an element of type [nat] to a list of\n    type [list nat]. Here is an example of forming a list containing\n    just the natural number 3. *)\n\nCheck (cons nat 3 (nil nat)).\n(* ===> cons nat 3 (nil nat) : list nat *)\n\n(** What might the type of [nil] be? We can read off the type [list X]\n    from the definition, but this omits the binding for [X] which is\n    the parameter to [list]. [Type -> list X] does not explain the\n    meaning of [X]. [(X : Type) -> list X] comes closer. Coq's\n    notation for this situation is [forall X : Type, list X]. *)\n\nCheck nil.\n(* ===> nil : forall X : Type, list X *)\n\n(** Similarly, the type of [cons] from the definition looks like\n    [X -> list X -> list X], but using this convention to explain the\n    meaning of [X] results in the type [forall X, X -> list X -> list\n    X]. *)\n\nCheck cons.\n(* ===> cons : forall X : Type, X -> list X -> list X *)\n\n(** (Side note on notation: In .v files, the \"forall\" quantifier\n    is spelled out in letters.  In the generated HTML files and in the\n    way various IDEs show .v files (with certain settings of their\n    display controls), [forall] is usually typeset as the usual\n    mathematical \"upside down A,\" but you'll still see the spelled-out\n    \"forall\" in a few places.  This is just a quirk of typesetting:\n    there is no difference in meaning.) *)\n\n(** Having to supply a type argument for each use of a list\n    constructor may seem an awkward burden, but we will soon see\n    ways of reducing that burden. *)\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\n(** (We've written [nil] and [cons] explicitly here because we haven't\n    yet defined the [ [] ] and [::] notations for the new version of\n    lists.  We'll do that in a bit.) *)\n\n(** We can now go back and make polymorphic versions of all the\n    list-processing functions that we wrote before.  Here is [repeat],\n    for example: *)\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\n(** As with [nil] and [cons], we can use [repeat] by applying it\n    first to a type and then to an element of this type (and a number): *)\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity. Qed.\n\n(** To use [repeat] to build other kinds of lists, we simply\n    instantiate it with an appropriate type parameter: *)\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity. Qed.\n\n\n(** **** Exercise: 2 stars, standard (mumble_grumble)  \n\n    Consider the following two inductively defined types. *)\n\nModule MumbleGrumble.\n\nInductive mumble : Type :=\n  | a\n  | b (x : mumble) (y : nat)\n  | c.\n\nInductive grumble (X:Type) : Type :=\n  | d (m : mumble)\n  | e (x : X).\n\n(** Which of the following are well-typed elements of [grumble X] for\n    some type [X]?  (Add YES or NO to each line.)\n      - [d (b a 5)]\n      - [d mumble (b a 5)]\n      - [d bool (b a 5)]\n      - [e bool true]\n      - [e mumble (b c 0)]\n      - [e bool (b c 0)]\n      - [c]  *)\n(* SOLUTION: \n\n      - [d mumble (b a 5)]\n      - [d bool (b a 5)]\n      - [e bool true]\n      - [e mumble (b c 0)]  *)\nEnd MumbleGrumble.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_mumble_grumble : option (nat*string) := None.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Annotation Inference *)\n\n(** Let's write the definition of [repeat] again, but this time we\n    won't specify the types of any of the arguments.  Will Coq still\n    accept it? *)\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0        => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\n(** Indeed it will.  Let's see what type Coq has assigned to [repeat']: *)\n\nCheck repeat'.\n(* ===> forall X : Type, X -> nat -> list X *)\nCheck repeat.\n(* ===> forall X : Type, X -> nat -> list X *)\n\n(** It has exactly the same type as [repeat].  Coq was able\n    to use _type inference_ to deduce what the types of [X], [x], and\n    [count] must be, based on how they are used.  For example, since\n    [X] is used as an argument to [cons], it must be a [Type], since\n    [cons] expects a [Type] as its first argument; matching [count]\n    with [0] and [S] means it must be a [nat]; and so on.\n\n    This powerful facility means we don't always have to write\n    explicit type annotations everywhere, although explicit type\n    annotations are still quite useful as documentation and sanity\n    checks, so we will continue to use them most of the time.  You\n    should try to find a balance in your own code between too many\n    type annotations (which can clutter and distract) and too\n    few (which forces readers to perform type inference in their heads\n    in order to understand your code). *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Argument Synthesis *)\n\n(** To use a polymorphic function, we need to pass it one or\n    more types in addition to its other arguments.  For example, the\n    recursive call in the body of the [repeat] function above must\n    pass along the type [X].  But since the second argument to\n    [repeat] is an element of [X], it seems entirely obvious that the\n    first argument can only be [X] -- why should we have to write it\n    explicitly?\n\n    Fortunately, Coq permits us to avoid this kind of redundancy.  In\n    place of any type argument we can write a \"hole\" [_], which can be\n    read as \"Please try to figure out for yourself what belongs here.\"\n    More precisely, when Coq encounters a [_], it will attempt to\n    _unify_ all locally available information -- the type of the\n    function being applied, the types of the other arguments, and the\n    type expected by the context in which the application appears --\n    to determine what concrete type should replace the [_].\n\n    This may sound similar to type annotation inference -- indeed, the\n    two procedures rely on the same underlying mechanisms.  Instead of\n    simply omitting the types of some arguments to a function, like\n\n      repeat' X x count : list X :=\n\n    we can also replace the types with [_]\n\n      repeat' (X : _) (x : _) (count : _) : list X :=\n\n    to tell Coq to attempt to infer the missing information.\n\n    Using holes, the [repeat] function can be written like this: *)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n(** In this instance, we don't save much by writing [_] instead of\n    [X].  But in many cases the difference in both keystrokes and\n    readability is nontrivial.  For example, suppose we want to write\n    down a list containing the numbers [1], [2], and [3].  Instead of\n    writing this... *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...we can use holes to write this: *)\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ----------------------------------------------------------------- *)\n(** *** Implicit Arguments *)\n\n(** We can go further and even avoid writing [_]'s in most cases by\n    telling Coq _always_ to infer the type argument(s) of a given\n    function.\n\n    The [Arguments] directive specifies the name of the function (or\n    constructor) and then lists its argument names, with curly braces\n    around any arguments to be treated as implicit.  (If some\n    arguments of a definition don't have a name, as is often the case\n    for constructors, they can be marked with a wildcard pattern\n    [_].) *)\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\n(** Now, we don't have to supply type arguments at all: *)\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\n(** Alternatively, we can declare an argument to be implicit\n    when defining the function itself, by surrounding it in curly\n    braces instead of parens.  For example: *)\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0        => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n(** (Note that we didn't even have to provide a type argument to the\n    recursive call to [repeat''']; indeed, it would be invalid to\n    provide one!)\n\n    We will use the latter style whenever possible, but we will\n    continue to use explicit [Argument] declarations for [Inductive]\n    constructors.  The reason for this is that marking the parameter\n    of an inductive type as implicit causes it to become implicit for\n    the type itself, not just for its constructors.  For instance,\n    consider the following alternative definition of the [list]\n    type: *)\n\nInductive list' {X:Type} : Type :=\n  | nil'\n  | cons' (x : X) (l : list').\n\n(** Because [X] is declared as implicit for the _entire_ inductive\n    definition including [list'] itself, we now have to write just\n    [list'] whether we are talking about lists of numbers or booleans\n    or anything else, rather than [list' nat] or [list' bool] or\n    whatever; this is a step too far. *)\n\n(** Let's finish by re-implementing a few other standard list\n    functions on our new polymorphic lists... *)\n\nFixpoint app {X : Type} (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity. Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Supplying Type Arguments Explicitly *)\n\n(** One small problem with declaring arguments [Implicit] is\n    that, occasionally, Coq does not have enough local information to\n    determine a type argument; in such cases, we need to tell Coq that\n    we want to give the argument explicitly just this time.  For\n    example, suppose we write this: *)\n\nFail Definition mynil := nil.\n\n(** (The [Fail] qualifier that appears before [Definition] can be\n    used with _any_ command, and is used to ensure that that command\n    indeed fails when executed. If the command does fail, Coq prints\n    the corresponding error message, but continues processing the rest\n    of the file.)\n\n    Here, Coq gives us an error because it doesn't know what type\n    argument to supply to [nil].  We can help it by providing an\n    explicit type declaration (so that Coq has more information\n    available when it gets to the \"application\" of [nil]): *)\n\nDefinition mynil : list nat := nil.\n\n(** Alternatively, we can force the implicit arguments to be explicit by\n   prefixing the function name with [@]. *)\n\nCheck @nil.\n(* ===> @nil : forall X : Type, list X *)\n\nDefinition mynil' := @nil nat.\n\n(** Using argument synthesis and implicit arguments, we can\n    define convenient notation for lists, as before.  Since we have\n    made the constructor type arguments implicit, Coq will know to\n    automatically infer these when we use the notations. *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** Now lists can be written just the way we'd hope: *)\n\nDefinition list123''' := [1; 2; 3].\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, standard, optional (poly_exercises)  \n\n    Here are a few simple exercises, just like ones in the [Lists]\n    chapter, for practice with polymorphism.  Complete the proofs below. *)\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  (* SOLUTION: *)\n  intros X l. induction l as [|x l' IH].\n  - reflexivity.\n    - simpl. rewrite IH. reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  (* SOLUTION: *)\n  intros A l m n.\n  induction l as [|a l' IH].\n  - reflexivity.\n  - simpl. rewrite IH. reflexivity.\nQed.\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  (* SOLUTION: *)\n  intros X l1. induction l1 as [|x l1'].\n  - (* l1 = nil *) reflexivity.\n  - (* l1 = x::l1' *) intros l2.  simpl. rewrite -> IHl1'. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (more_poly_exercises)  \n\n    Here are some slightly more interesting ones... *)\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  (* SOLUTION: *)\n  intros X l1 l2. induction l1 as [|x1 l1' IH].\n  - simpl. rewrite app_nil_r. reflexivity.\n  - simpl. rewrite IH. rewrite app_assoc. reflexivity. Qed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  (* SOLUTION: *)\n  intros X l. induction l as [| n l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> rev_app_distr. rewrite -> IHl'. reflexivity.  Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Pairs *)\n\n(** Following the same pattern, the type definition we gave in\n    the last chapter for pairs of numbers can be generalized to\n    _polymorphic pairs_, often called _products_: *)\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\n\nArguments pair {X} {Y} _ _.\n\n(** As with lists, we make the type arguments implicit and define the\n    familiar concrete notation. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** We can also use the [Notation] mechanism to define the standard\n    notation for product _types_: *)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** (The annotation [: type_scope] tells Coq that this abbreviation\n    should only be used when parsing types.  This avoids a clash with\n    the multiplication symbol.) *)\n\n(** It is easy at first to get [(x,y)] and [X*Y] confused.\n    Remember that [(x,y)] is a _value_ built from two other values,\n    while [X*Y] is a _type_ built from two other types.  If [x] has\n    type [X] and [y] has type [Y], then [(x,y)] has type [X*Y]. *)\n\n(** The first and second projection functions now look pretty\n    much as they would in any functional programming language. *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\n(** The following function takes two lists and combines them\n    into a list of pairs.  In other functional languages, it is often\n    called [zip]; we call it [combine] for consistency with Coq's\n    standard library. *)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\n(** **** Exercise: 1 star, standard, optional (combine_checks)  \n\n    Try answering the following questions on paper and\n    checking your answers in Coq:\n    - What is the type of [combine] (i.e., what does [Check\n      @combine] print?)\n    - What does\n\n        Compute (combine [1;2] [false;false;true;true]).\n\n      print? \n\n    [] *)\n\n(** **** Exercise: 2 stars, standard, recommended (split)  \n\n    The function [split] is the right inverse of [combine]: it takes a\n    list of pairs and returns a pair of lists.  In many functional\n    languages, it is called [unzip].\n\n    Fill in the definition of [split] below.  Make sure it passes the\n    given unit test. *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y)\n  (* SOLUTION: *) :=\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\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof.\n(* SOLUTION: *)\n  reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Options *)\n\n(** One last polymorphic type for now: _polymorphic options_,\n    which generalize [natoption] from the previous chapter.  (We put\n    the definition inside a module because the standard library\n    already defines [option] and it's this one that we want to use\n    below.) *)\n\nModule OptionPlayground.\n\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\n\nArguments Some {X} _.\nArguments None {X}.\n\nEnd OptionPlayground.\n\n(** We can now rewrite the [nth_error] function so that it works\n    with any type of lists. *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if n =? O then Some a else nth_error l' (pred n)\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, standard, optional (hd_error_poly)  \n\n    Complete the definition of a polymorphic version of the\n    [hd_error] function from the last chapter. Be sure that it\n    passes the unit tests below. *)\n\nDefinition hd_error {X : Type} (l : list X) : option X\n  (* SOLUTION: *) :=\n  match l with\n  | [] => None\n  | a :: l' => Some a\n  end.\n\n(** Once again, to force the implicit arguments to be explicit,\n    we can use [@] before the name of the function. *)\n\nCheck @hd_error.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\n (* SOLUTION: *)\nProof. reflexivity.  Qed.\n Example test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\n (* SOLUTION: *)\nProof. reflexivity.  Qed.\n (** [] *)\n\n(* ################################################################# *)\n(** * Functions as Data *)\n\n(** Like many other modern programming languages -- including\n    all functional languages (ML, Haskell, Scheme, Scala, Clojure,\n    etc.) -- Coq treats functions as first-class citizens, allowing\n    them to be passed as arguments to other functions, returned as\n    results, stored in data structures, etc. *)\n\n(* ================================================================= *)\n(** ** Higher-Order Functions *)\n\n(** Functions that manipulate other functions are often called\n    _higher-order_ functions.  Here's a simple one: *)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\n(** The argument [f] here is itself a function (from [X] to\n    [X]); the body of [doit3times] applies [f] three times to some\n    value [n]. *)\n\nCheck @doit3times.\n(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity. Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\n\n(* ================================================================= *)\n(** ** Filter *)\n\n(** Here is a more useful higher-order function, taking a list\n    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])\n    and \"filtering\" the list, returning a new list containing just\n    those elements for which the predicate returns [true]. *)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | []     => []\n  | h :: t => if test h then h :: (filter test t)\n                        else       filter test t\n  end.\n\n(** For example, if we apply [filter] to the predicate [evenb]\n    and a list of numbers [l], it returns a list containing just the\n    even members of [l]. *)\n\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity. Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  (length l) =? 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\n(** We can use [filter] to give a concise version of the\n    [countoddmembers] function from the [Lists] chapter. *)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity. Qed.\n\n(* ================================================================= *)\n(** ** Anonymous Functions *)\n\n(** It is arguably a little sad, in the example just above, to\n    be forced to define the function [length_is_1] and give it a name\n    just to be able to pass it as an argument to [filter], since we\n    will probably never use it again.  Moreover, this is not an\n    isolated example: when using higher-order functions, we often want\n    to pass as arguments \"one-off\" functions that we will never use\n    again; having to give each of these functions a name would be\n    tedious.\n\n    Fortunately, there is a better way.  We can construct a function\n    \"on the fly\" without declaring it at the top level or giving it a\n    name. *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity. Qed.\n\n(** The expression [(fun n => n * n)] can be read as \"the function\n    that, given a number [n], yields [n * n].\" *)\n\n(** Here is the [filter] example, rewritten to use an anonymous\n    function. *)\n\nExample test_filter2':\n    filter (fun l => (length l) =? 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, standard (filter_even_gt7)  \n\n    Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat\n  (* SOLUTION: *) :=\n  filter (fun n => andb (evenb n) (ltb 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].\n (* SOLUTION: *)\nProof. reflexivity. Qed.\n \nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\n (* SOLUTION: *)\nProof. reflexivity. Qed.\n (** [] *)\n\n(** **** Exercise: 3 stars, standard (partition)  \n\n    Use [filter] to write a Coq function [partition]:\n\n      partition : forall X : Type,\n                  (X -> bool) -> list X -> list X * list X\n\n   Given a set [X], a test function of type [X -> bool] and a [list\n   X], [partition] should return a pair of lists.  The first member of\n   the pair is the sublist of the original list containing the\n   elements that satisfy the test, and the second is the sublist\n   containing those that fail the test.  The order of elements in the\n   two sublists should be the same as their order in the original\n   list. *)\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X\n  (* SOLUTION: *) :=\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]).\n(* SOLUTION: *)\nProof. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\n(* SOLUTION: *)\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Map *)\n\n(** Another handy higher-order function is called [map]. *)\n\nFixpoint map {X Y: Type} (f:X->Y) (l:list X) : (list Y) :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]\n    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has\n    been applied to each element of [l] in turn.  For example: *)\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\n(** The element types of the input and output lists need not be\n    the same, since [map] takes _two_ type arguments, [X] and [Y]; it\n    can thus be applied to a list of numbers and a function from\n    numbers to booleans to yield a list of booleans: *)\n\nExample test_map2:\n  map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity. Qed.\n\n(** It can even be applied to a list of numbers and\n    a function from numbers to _lists_ of booleans to\n    yield a _list of lists_ of booleans: *)\n\nExample test_map3:\n    map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 3 stars, standard (map_rev)  \n\n    Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\nTheorem map_app : forall (A B : Type) (f : A -> B) (l l' : list A),\n  map f (l ++ l') = map f l ++ map f l'.\nProof.\n  intros A B f l l'. induction l as [|x l1 IH].\n  - reflexivity.\n  - simpl. rewrite IH. reflexivity.\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  (* SOLUTION: *)\n  intros X Y f l. induction l as [| v l' IHl'].\n  - (* l = [] *)\n    reflexivity.\n  - (* l = v :: l' *)\n    simpl. rewrite -> map_app. rewrite -> IHl'. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, recommended (flat_map)  \n\n    The function [map] maps a [list X] to a [list Y] using a function\n    of type [X -> Y].  We can define a similar function, [flat_map],\n    which maps a [list X] to a [list Y] using a function [f] of type\n    [X -> list Y].  Your definition should work by 'flattening' the\n    results of [f], like so:\n\n        flat_map (fun n => [n;n+1;n+2]) [1;5;10]\n      = [1; 2; 3; 5; 6; 7; 10; 11; 12].\n*)\n\nFixpoint flat_map {X Y: Type} (f: X -> list Y) (l: list X)\n                   : (list Y)\n  (* SOLUTION: *) :=\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].\n (* SOLUTION: *)\nProof. reflexivity.  Qed.\n (** [] *)\n\n(** Lists are not the only inductive type for which [map] makes sense.\n    Here is a [map] for the [option] type: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\n(** **** Exercise: 2 stars, standard, optional (implicit_args)  \n\n    The definitions and uses of [filter] and [map] use implicit\n    arguments in many places.  Replace the curly braces around the\n    implicit arguments with parentheses, and then fill in explicit\n    type parameters where necessary and use Coq to check that you've\n    done so correctly.  (This exercise is not to be turned in; it is\n    probably easiest to do it on a _copy_ of this file that you can\n    throw away afterwards.)\n\n    [] *)\n\n(* ================================================================= *)\n(** ** Fold *)\n\n(** An even more powerful higher-order function is called\n    [fold].  This function is the inspiration for the \"[reduce]\"\n    operation that lies at the heart of Google's map/reduce\n    distributed programming framework. *)\n\nFixpoint fold {X Y: Type} (f: X->Y->Y) (l: list X) (b: Y)\n                         : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(** Intuitively, the behavior of the [fold] operation is to\n    insert a given binary operator [f] between every pair of elements\n    in a given list.  For example, [ fold plus [1;2;3;4] ] intuitively\n    means [1+2+3+4].  To make this precise, we also need a \"starting\n    element\" that serves as the initial second input to [f].  So, for\n    example,\n\n       fold plus [1;2;3;4] 0\n\n    yields\n\n       1 + (2 + (3 + (4 + 0))).\n\n    Some more examples: *)\n\nCheck (fold andb).\n(* ===> fold andb : list bool -> bool -> bool *)\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, advanced (fold_types_different)  \n\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(* SOLUTION: \n\n    There are many.  For example, we could use [fold] to count the\n    number of [true] elements in a list of booleans.  Here [X] would\n    be [bool] and [Y] would be [nat]. *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_types_different : option (nat*string) := None.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Functions That Construct Functions *)\n\n(** Most of the higher-order functions we have talked about so\n    far take functions as arguments.  Let's look at some examples that\n    involve _returning_ functions as the results of other functions.\n    To begin, here is a function that takes a value [x] (drawn from\n    some type [X]) and returns a function from [nat] to [X] that\n    yields [x] whenever it is called, ignoring its [nat] argument. *)\n\nDefinition constfun {X: Type} (x: X) : nat->X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** In fact, the multiple-argument functions we have already\n    seen are also examples of passing functions as data.  To see why,\n    recall the type of [plus]. *)\n\nCheck plus.\n(* ==> nat -> nat -> nat *)\n\n(** Each [->] in this expression is actually a _binary_ operator\n    on types.  This operator is _right-associative_, so the type of\n    [plus] is really a shorthand for [nat -> (nat -> nat)] -- i.e., it\n    can be read as saying that \"[plus] is a one-argument function that\n    takes a [nat] and returns a one-argument function that takes\n    another [nat] and returns a [nat].\"  In the examples above, we\n    have always applied [plus] to both of its arguments at once, but\n    if we like we can supply just the first.  This is called _partial\n    application_. *)\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity. Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity. Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity. Qed.\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\nModule Exercises.\n\n(** **** Exercise: 2 stars, standard (fold_length)  \n\n    Many common functions on lists can be implemented in terms of\n    [fold].  For example, here is an alternative definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length].  (Hint: It may help to\n    know that [reflexivity] simplifies expressions a bit more\n    aggressively than [simpl] does -- i.e., you may find yourself in a\n    situation where [simpl] does nothing but [reflexivity] solves the\n    goal.) *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n(* SOLUTION: *)\n  induction l as [| x l' IHl'].\n  - (* l = [] *) reflexivity.\n  - (* l = x :: l' *) simpl.\n    rewrite <- IHl'.\n    reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (fold_map)  \n\n    We can also define [map] in terms of [fold].  Finish [fold_map]\n    below. *)\n\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y\n  (* SOLUTION: *) :=\n  fold (fun x l' => f x :: l') l nil.\n\n(** Write down a theorem [fold_map_correct] in Coq stating that\n   [fold_map] is correct, and prove it.  (Hint: again, remember that\n   [reflexivity] simplifies expressions a bit more aggressively than\n   [simpl].) *)\n\n(* SOLUTION: *)\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 as [| x l' IHl'].\n  - (* l = [] *) reflexivity.\n  - (* l = x :: l' *) simpl.\n    rewrite <- IHl'.\n    reflexivity.  Qed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_map : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (currying)  \n\n    In Coq, a function [f : A -> B -> C] really has the type [A\n    -> (B -> C)].  That is, if you give [f] a value of type [A], it\n    will give you function [f' : B -> C].  If you then give [f'] a\n    value of type [B], it will return a value of type [C].  This\n    allows for partial application, as in [plus3].  Processing a list\n    of arguments with functions that return functions is called\n    _currying_, in honor of the logician Haskell Curry.\n\n    Conversely, we can reinterpret the type [A -> B -> C] as [(A *\n    B) -> C].  This is called _uncurrying_.  With an uncurried binary\n    function, both arguments must be given at once as a pair; there is\n    no partial application. *)\n\n(** We can define currying as follows: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** As an exercise, define its inverse, [prod_uncurry].  Then prove\n    the theorems below to show that the two are inverses. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z\n  (* SOLUTION: *) :=\n    match p with\n      | (x,y) => f x y\n    end.\n\n(** As a (trivial) example of the usefulness of currying, we can use it\n    to shorten one of the examples that we saw above: *)\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\n(** Thought exercise: before running the following commands, can you\n    calculate the types of [prod_curry] and [prod_uncurry]? *)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  (* SOLUTION: *)\n  intros X Y Z f x y.\n  reflexivity.  Qed.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  (* SOLUTION: *)\n  intros X Y Z f p.\n  destruct p as [x y].\n  reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (nth_error_informal)  \n\n    Recall the definition of the [nth_error] function:\n\n   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n     match l with\n     | [] => None\n     | a :: l' => if n =? O then Some a else nth_error l' (pred n)\n     end.\n\n   Write an informal proof of the following theorem:\n\n   forall X l n, length l = n -> @nth_error X l n = None\n*)\n(* SOLUTION: \n\n    Theorem: For all types [X], lists [l], and natural numbers [n],\n    if [length l = n] then [nth_error X l n = None].\n\n    Proof: By induction on [l]. There are two cases to consider:\n\n      - If [l = nil], we must show [nth_error [] n = None].  This follows\n        immediately from the definition of [nth_error].\n\n      - Otherwise, [l = x :: l'] for some [x] and [l'], and the\n        induction hypothesis tells us that [length l' = n' => nth_error l'\n        n' = None] for any [n'].\n\n        Let [n] be a number such that [length l = n].  We must show\n        that [nth_error (x :: l') n = None].\n\n        But we know that [n = length l = length (x :: l') = S (length l')].\n        So it's enough to show [nth_error l' (length l') = None], which\n        follows directly from the induction hypothesis, picking [length l']\n        for [n']. *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_proof : option (nat*string) := None.\n(** [] *)\n\n(** The following exercises explore an alternative way of defining\n    natural numbers, using the so-called _Church numerals_, named\n    after mathematician Alonzo Church.  We can represent a natural\n    number [n] as a function that takes a function [f] as a parameter\n    and returns [f] iterated [n] times. *)\n\nModule Church.\nDefinition cnat := forall X : Type, (X -> X) -> X -> X.\n\n(** Let's see how to write some numbers with this notation. Iterating\n    a function once should be the same as just applying it.  Thus: *)\n\nDefinition one : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** Similarly, [two] should apply [f] twice to its argument: *)\n\nDefinition two : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** Defining [zero] is somewhat trickier: how can we \"apply a function\n    zero times\"?  The answer is actually simple: just return the\n    argument untouched. *)\n\nDefinition zero : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(** More generally, a number [n] can be written as [fun X f x => f (f\n    ... (f x) ...)], with [n] occurrences of [f].  Notice in\n    particular how the [doit3times] function we've defined previously\n    is actually just the Church representation of [3]. *)\n\nDefinition three : cnat := @doit3times.\n\n(** Complete the definitions of the following functions. Make sure\n    that the corresponding unit tests pass by proving them with\n    [reflexivity]. *)\n\n(** **** Exercise: 1 star, advanced (church_succ)  *)\n\n(** Successor of a natural number: given a Church numeral [n],\n    the successor [succ n] is a function that iterates its\n    argument once more than [n]. *)\nDefinition succ (n : cnat) : cnat\n  (* SOLUTION: *) :=\n  fun X f x => f (n X f x).\n  \nExample succ_1 : succ zero = one.\nProof. (* SOLUTION: *) reflexivity. Qed. \nExample succ_2 : succ one = two.\nProof. (* SOLUTION: *) reflexivity. Qed. \nExample succ_3 : succ two = three.\nProof. (* SOLUTION: *) reflexivity. Qed. \n(** [] *)\n\n(** **** Exercise: 1 star, advanced (church_plus)  *)\n\n(** Addition of two natural numbers: *)\nDefinition plus (n m : cnat) : cnat\n  (* SOLUTION: *) :=\n  fun X f x => n X f (m X f x).\n  \nExample plus_1 : plus zero one = one.\nProof. (* SOLUTION: *) reflexivity. Qed. \nExample plus_2 : plus two three = plus three two.\nProof. (* SOLUTION: *) reflexivity. Qed. \nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. (* SOLUTION: *) reflexivity. Qed. \n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (church_mult)  *)\n\n(** Multiplication: *)\nDefinition mult (n m : cnat) : cnat\n  (* SOLUTION: *) :=\n  fun X f x => n X (m X f) x.\n  \nExample mult_1 : mult one one = one.\nProof. (* SOLUTION: *) reflexivity. Qed. \nExample mult_2 : mult zero (plus three three) = zero.\nProof. (* SOLUTION: *) reflexivity. Qed. \nExample mult_3 : mult two three = plus three three.\nProof. (* SOLUTION: *) reflexivity. Qed. \n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (church_exp)  *)\n\n(** Exponentiation: *)\n\n(** (_Hint_: Polymorphism plays a crucial role here.  However,\n    choosing the right type to iterate over can be tricky.  If you hit\n    a \"Universe inconsistency\" error, try iterating over a different\n    type.  Iterating over [cnat] itself is usually problematic.) *)\n\nDefinition exp (n m : cnat) : cnat\n  (* SOLUTION: *) :=\n  fun X f x => m (X -> X) (n X) f x.\n  \nExample exp_1 : exp two two = plus two two.\nProof. (* SOLUTION: *) reflexivity. Qed. \nExample exp_2 : exp three zero = one.\nProof. (* SOLUTION: *) reflexivity. Qed. \nExample exp_3 : exp three two = plus (mult two (mult two two)) one.\nProof. (* SOLUTION: *) reflexivity. Qed. \n(** [] *)\n\nEnd Church.\n\nEnd Exercises.\n\n\n(* Wed 28 Aug 2019 06:48:48 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/Poly_Solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321843145404, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.6713531189664885}}
{"text": "From mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Usage :\n\nrewrite (ACl operator reordering)\n\n- operator must be a (canonical) Monoid.com_law\n- reordering is expressed using the syntax\n  s := n | s + s' (where \"+\" is purely formal)\n  where n is a nat\n- we assume the lhs is associated to the left\n  (use !opA before ACl if required)\n\nExamples of syntax :\n- (0 + 1) + 2 is the identity\n- (0 + 2) + 1 correspond to opAC\n- 0 + (1 + 2) is the same as chaining -opA and opCA\n...\n*)\n\nDelimit Scope AC_scope with ac.\n\nSection AC.\n\nInductive syntax := Leaf of nat | Op of syntax & syntax.\nDefinition seqtax :=\n  (fix aux (acc : seq nat) (s : syntax) := match s with\n               | Leaf n => n :: acc\n               | Op s s' => (aux^~ s (aux^~ s' acc))\n               end) [::].\n\nDefinition sfoldl R (d : R) f (s : seq R) :=\n  if s is a::s then foldl f a s else d.\nDefinition sfoldr R (d : R) f (s : seq R) :=\n  if s is a::s then foldr f a s else d.\n\nVariables (T : Type) (default : T) (env : seq T) (op : Monoid.com_law default).\n\nLocal Notation \"x + y\" := (op x y).\n\nDefinition desyntax :=\n  fix aux (s : syntax)  := match s with\n               | Leaf n => nth default env n\n               | Op s s' => aux s + aux s'\n               end.\n\nLemma ACl_def s :\n  let st := seqtax s in let sst := size st in let isst := iota 0 sst in\n                                              perm_eq st isst ->\n  sfoldl default op (map (nth default env) isst) = desyntax s.\nProof.\nhave seqtax_Op s1 s2 : seqtax (Op s1 s2) = seqtax s1 ++ seqtax s2.\n  rewrite /seqtax; set aux := (X in X [::]); rewrite -/aux.\n  elim: s1 (aux [::] s2) => [n|s11 IHs1 s12 IHs2] //= l.\n  by rewrite IHs1 [in RHS]IHs1 IHs2 catA.\nmove=> st sst isst pst.\ntransitivity (\\big[op/default]_(i <- isst) nth default env i).\n  case: isst {pst} => [|x l /=]; rewrite (big_nil, big_cons) //=.\n  elim: l (nth _ _ _) => [|y l IHl] x0.\n    by rewrite big_nil ?Monoid.mulm1.\n  by rewrite big_cons /= IHl Monoid.mulmA.\nelim: s => [n|s IHs s' IHs'] //= in st sst (isst) pst *.\n  have [/perm_eq_size {pst}] := (pst, pst).\n  case: isst => // m [|//] _ /perm_eqP/(_ (pred1 m)) => /=.\n  by rewrite eqxx; case: eqP => //= ->; rewrite big_cons big_nil Monoid.mulm1.\nhave /(eq_big_perm _) <- := pst.\nby rewrite [st]seqtax_Op big_cat IHs ?IHs' //.\nQed.\n\nEnd AC.\n\nCoercion Leaf : nat >-> syntax.\nBind Scope AC_scope with syntax.\nNotation \"0\" := 0%N : AC_scope.\nNotation \"1\" := 1%N : AC_scope.\nNotation \"x * y\" := (Op x%ac y%ac) : AC_scope.\n\nDefinition type_of T (x : T) := T.\nArguments type_of / T x.\nDefinition lhs T a b (e : a = b :> T) := a.\nArguments lhs / T a b e.\nDefinition rhs T a b (e : a = b :> T) := b.\nArguments rhs / T a b e.\n\nImport Classes.Init.\nClass envn T (n : nat) := Envn : seq T.\nInstance envn0 T : envn T 0 := nil.\nDefinition consn T n x {s : envn T n} : envn T n.+1 := x :: s.\nHint Extern 0 (envn _ (S _)) =>\n  match goal with |- envn ?T (S ?n) =>\n                  let x := fresh \"x\" in\n                  evar (x : T); apply (@consn _ _ x _)\n  end : typeclass_instances.\n\nClass compute T x y := Compute : x = y :> T.\nHint Extern 0 (@compute _ _ _) => compute; reflexivity : typeclass_instances.\nClass simpl T x y := Simpl : x = y :> T.\nHint Extern 0 (@simpl _ _ _) => simpl; reflexivity : typeclass_instances.\n\nDefinition ACl_auto T default (law : Monoid.com_law default) (s : syntax)\n   {peq : compute (perm_eq (seqtax s) (iota 0 (size (seqtax s)))) true}\n   {sst} {_ : compute (size (seqtax s)) sst}\n   {env : envn T sst}\n   (use := @ACl_def T default env law s peq)\n   {lhs'} {elhs : simpl (lhs use) lhs'}\n   {rhs'} {erhs : simpl (rhs use) rhs'}\n   : lhs' = rhs' :=\n  (match elhs with erefl =>\n    (match erhs with erefl => use end) end).\n\nNotation ACl_of f s := (@ACl_auto _ _ [com_law of f] s%ac\n                                isT _ _ _ _ _ _ _).\nNotation ACl f s := (ACl_of f s%ac : f%function _ _ = _).\n\nSection Tests.\n\nLemma test_orb (a b c d : bool) : (a || b) || (c || d) = (a || c) || (b || d).\nProof.\nrewrite !orbA.\nrewrite (ACl orb ((0 * 2) * (1 * 3))).\nby rewrite !orbA.\nQed.\n\nLemma test_addn (a b c d : nat) : (a + b + c + d = a + c + b + d)%N.\nProof.\nby rewrite (ACl addn (0 * 2 * 1 * 3)).\nQed.\n\nEnd Tests.", "meta": {"author": "CohenCyril", "repo": "ssrAC", "sha": "641986e125ff5f7375e0048c22679dd1e26af6a9", "save_path": "github-repos/coq/CohenCyril-ssrAC", "path": "github-repos/coq/CohenCyril-ssrAC/ssrAC-641986e125ff5f7375e0048c22679dd1e26af6a9/ssrAC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245911726382, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.6713531164627663}}
{"text": "Require Export Undecidability.Shared.Libs.PSL.FiniteTypes.\nRequire Import Undecidability.Shared.Libs.PSL.Vectors.Vectors.\n\nLemma dupfree_elements (X: finType) : NoDup (elem X).\nProof.\n  apply (NoDup_count_occ' (@eqType_dec X)). intros x H.\n  rewrite <- count_count_occ.\n  apply enum_ok.\nQed.\n\n(* From PSL/Lists/BaseLists.v *)\nLemma map_repeat (X Y : Type) (f : X -> Y) (n : nat) (a : X) :\n  map f (repeat a n) = repeat (f a) n.\nProof.\n  induction n as [|n IHn].\n  - reflexivity.\n  - cbn. now rewrite IHn.\nQed.\n\nDefinition equi X (A B : list X) : Prop := incl A B /\\ incl B A.\nNotation \"A === B\" := (equi A B) (at level 70).\n\n#[global]\nInstance equi_Equivalence X :\n  Equivalence (@equi X).\nProof.\n  constructor; hnf; firstorder.\nQed.\n\n#[global]\nInstance in_equi_proper X x :\n  Proper (@equi X ==> iff) (@In X x).\nProof.\n  intros ???. firstorder.\nQed.\n\n(* from PSL/Vectors/Vectors.v *)\nLemma vector_to_list_inj (X : Type) (n : nat) (xs ys : Vector.t X n) :\n  Vector.to_list xs = Vector.to_list ys -> xs = ys.\nProof.\n  revert ys. induction xs as [ | x n xs IH]; intros; cbn in *.\n  - destruct_vector. reflexivity.\n  - destruct_vector. cbn in *. inv H. f_equal. auto.\nQed.\n\n(* From TM/Util/VectorPrelim.v *)\nLemma nth_error_inj X (xs ys : list X) :\n  (forall n, nth_error xs n = nth_error ys n) -> xs = ys.\nProof.\n  induction xs in ys|-*;destruct ys;cbn;intros H. 1:easy. 1-2:now specialize (H 0).\n  generalize (H 0).  intros [= ->]. erewrite IHxs. easy. intros n'. now specialize (H (S n')).\nQed.\n\nLemma vector_nth_error_nat X n' i (xs : Vector.t X n') :\n  nth_error (Vector.to_list xs) i = match lt_dec i n' with\n                                      Specif.left H => Some (Vector.nth xs (Fin.of_nat_lt H))\n                                    | _ => None\n                                    end.\nProof.\n  clear. induction xs in i|-*. now destruct i.\n  cbn in *. destruct i;cbn. easy. rewrite IHxs. do 2 destruct lt_dec. 4:easy. now symmetry;erewrite Fin.of_nat_ext. all:exfalso;Lia.nia.\nQed.\n\nLemma vector_to_list_cast (X : Type) (n1 n2 : nat) (H : n1 = n2) (v : Vector.t X n1) :\n  Vector.to_list (Vector.cast v H) = Vector.to_list v.\nProof. subst. rename n2 into n. induction v as [ | x n v IH]; cbn; f_equal; auto. Qed.\n\n(* From PSL/FiniteTypes/VectorFin.v *)\nLemma Fin_cardinality n : | elem (finType_CS (Fin.t n)) | = n.\nProof.\n  apply VectorSpec.length_to_list.\nQed.\n\n(* from PSL/FiniteTypes/FinTypes.v *)\nLemma index_leq (A:finType) (x:A): index x <= length (elem A).\nProof. apply Nat.lt_le_incl, index_le. Qed.\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/Libs/PSLCompat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.6713531161857331}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_s_ncol_n_col :\n\tforall A B C,\n\tnCol A B C ->\n\t~ Col A B C.\nProof.\n\tintros A B C.\n\tintros nCol_A_B_C.\n\n\tassert (~ Col A B C) as n_Col_a_b_c.\n\t{\n\t\tintros Col_A_B_C.\n\n\t\tunfold nCol in nCol_A_B_C.\n\t\tunfold Col in Col_A_B_C.\n\t\tdestruct nCol_A_B_C as (\n\t\t\tneq_A_B & neq_A_C & neq_B_C & nBetS_A_B_C & nBetS_A_C_B & nBetS_B_A_C\n\t\t).\n\t\tdestruct Col_A_B_C as [\n\t\t\teq_A_B | [eq_A_C | [eq_B_C | [BetS_B_A_C | [BetS_A_B_C | BetS_A_C_B]]]]\n\t\t].\n\n\t\tcontradict eq_A_B.\n\t\texact neq_A_B.\n\t\tcontradict eq_A_C .\n\t\texact neq_A_C .\n\t\tcontradict eq_B_C .\n\t\texact neq_B_C .\n\t\tcontradict BetS_B_A_C .\n\t\texact nBetS_B_A_C .\n\t\tcontradict BetS_A_B_C.\n\t\texact nBetS_A_B_C.\n\t\tcontradict BetS_A_C_B .\n\t\texact nBetS_A_C_B .\n\t}\n\texact n_Col_a_b_c.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_s_ncol_n_col.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338727, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6713429314979752}}
{"text": "(* Various definitions and lemmas involving binary trees *)\n\nRequire Import Arith List.\nRequire Import VerifiedNatIntf ArrayIntf CanonicalArrImpl.\nRequire Import Cpdt.CpdtTactics.\n\nImport ListNotations.\nSet Implicit Arguments.\n\nModule TreeDefns (Natl : VerifiedNatInterface).\n\n  Definition one := Natl.succ Natl.zero.\n\n  Inductive tree (A : Type) : Type :=\n    | Empty : tree A\n    | Leaf : A -> tree A\n    | Node : Natl.N -> Natl.N -> tree A -> tree A -> tree A.\n\n  Definition T := tree.\n\n  Fixpoint add A (x : A) (t : tree A) : tree A :=\n    match t with\n    | Empty => Leaf x\n    | Leaf y => Node one one (Leaf x) (Leaf y)\n    | Node nl nr l r =>\n        match Natl.comp nl nr with\n        | Lt => Node (Natl.succ nl) nr (add x l) r\n        | Eq\n        | Gt => Node nl (Natl.succ nr) l (add x r)\n        end\n    end.\n\n  Fixpoint make A (m : nat) (x : A) : tree A :=\n    match m with\n    | O => Empty A\n    | S m' => add x (make m' x)\n    end.\n\n  Definition len A (t : tree A) : Natl.N :=\n    match t with\n    | Empty => Natl.zero\n    | Leaf _ => Natl.succ Natl.zero\n    | Node nl nr _ _ => Natl.add nl nr\n    end.\n\n  Fixpoint get A (t : tree A) (index : Natl.N) : option A :=\n    match t, index with\n    | Empty, _ => None\n    | Leaf x, _ =>\n        match Natl.comp index Natl.zero with\n        | Lt\n        | Eq => Some x\n        | Gt => None\n        end\n    | Node nl nr l r, i =>\n        match Natl.comp i nl with\n        | Lt => get l i\n        | Eq\n        | Gt => get r (Natl.sub i nl)\n        end\n    end.\n\n  Fixpoint set A (t : tree A) (index : Natl.N) (x : A) : tree A :=\n    match t, index with\n    | Empty, _ => Empty A\n    | Leaf y, _ =>\n        match Natl.comp index Natl.zero with\n        | Lt\n        | Eq => Leaf x\n        | Gt => Leaf y\n        end\n    | Node nl nr l r, i =>\n        match Natl.comp i nl with\n        | Lt => Node nl nr (set l i x) r\n        | Eq\n        | Gt => Node nl nr l (set r (Natl.sub i nl) x)\n        end\n    end.\n\n  Definition concat A (t1 t2 : tree A) : tree A :=\n    match t1, t2 with\n    | Empty, _ => t2\n    | _, Empty => t1\n    | _, _ => Node (len t1) (len t2) t1 t2\n    end.\n\n  (** Properties and lemmas **)\n\n  Fixpoint count A (t : tree A) : Natl.N :=\n    match t with\n    | Empty => Natl.zero\n    | Leaf _ => Natl.succ (Natl.zero)\n    | Node _ _ l r => Natl.add (count l) (count r)\n    end.\n\n  Fixpoint well_formed A (t : tree A) :=\n    match t with\n    | Empty => True\n    | Leaf _ => True\n    | Node nl nr l r => (count l = nl) /\\ (count r = nr) /\\ well_formed l /\\ well_formed r\n    end.\n\n  Lemma add_inc : forall A (x:A) (t:tree A),\n      count (add x t) = Natl.succ (count t).\n    intros A x t.\n    induction t as [| | nl nr l IHl r IHr ]; simpl; auto.\n      (* Leaf *)\n      rewrite Natl.add_succ; rewrite Natl.add_zero; reflexivity.\n      (* Node *)\n      remember (Natl.comp nl nr) as clr.\n      Hint Resolve Natl.add_succ_right.\n      destruct clr; simpl; rewrite <- Natl.add_succ; crush.\n  Defined.\n\n  Lemma add_preserves : forall A (x : A) (t : tree A),\n      well_formed t -> well_formed (add x t).\n    intros A x t.\n    induction t as [| |nl nr l IHl r IHr]; simpl; auto.\n      (* Node *)\n      intros Hwf.\n      Hint Resolve add_inc.\n      destruct (Natl.comp nl nr); crush.\n  Defined.\n\n  Lemma make_wf : forall A n (x:A), well_formed (make n x).\n    intros A m x.\n    Hint Resolve add_preserves.\n    induction m; crush.\n  Defined.\n\n  Lemma len_wf : forall A (t:tree A), well_formed t -> len t = count t.\n    intros A t.\n    destruct t; crush.\n  Defined.\n\n  Lemma set_count : forall A (t:tree A) i x,\n      count (set t i x) = count t.\n    intros A t.\n    induction t as [| | nl nr l IHl r IHr ];\n        intros i x; auto; simpl.\n      (* Leaf _ *)\n      destruct (Natl.comp i Natl.zero); auto.\n      (* Node *)\n      destruct (Natl.comp i nl); simpl.\n        rewrite (IHr (Natl.sub i nl) x); reflexivity.\n        rewrite (IHl i x); reflexivity.\n        rewrite (IHr (Natl.sub i nl) x); reflexivity.\n  Defined.\n\n  Lemma set_wf : forall A (t:tree A) i x,\n      well_formed t -> well_formed (set t i x).\n    intros A t.\n    induction t as [| | nl nr l IHl r IHr ];\n        intros i x; simpl.\n      (* Empty *)\n      auto.\n      (* Leaf *)\n      destruct (Natl.comp i Natl.zero); auto.\n      (* Node *)\n      intros Hwf.\n      destruct Hwf as (Hcr & Hcl & Hwfl & Hwfr).\n      destruct (Natl.comp i nl);\n          simpl;\n          rewrite (set_count _ _ _).\n        pose (IHr (Natl.sub i nl) x); auto.\n        pose (IHl i x Hwfl); auto.\n        pose (IHr (Natl.sub i nl) x); auto.\n  Defined.\n\n  Lemma concat_wf : forall A (t1 t2 : tree A),\n      well_formed t1 -> well_formed t2 -> well_formed (concat t1 t2).\n    intros A t1 t2.\n    destruct t1; destruct t2; crush.\n  Defined.\n\nEnd TreeDefns.\n", "meta": {"author": "ethantkoenig", "repo": "CS-4860-Project", "sha": "708f349803867e9cf216cfaea7776deeb6122d04", "save_path": "github-repos/coq/ethantkoenig-CS-4860-Project", "path": "github-repos/coq/ethantkoenig-CS-4860-Project/CS-4860-Project-708f349803867e9cf216cfaea7776deeb6122d04/arrays/Trees.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6713429157667155}}
{"text": "\nTheorem Ex020 (A B C : Prop): A \\/ (B /\\ C) <-> (A \\/ B) /\\ (A \\/ C).\nProof.\n  split.\n  + intro.\n    split.\n    - destruct H.\n      * left. exact H.\n      * destruct H. right. exact H.\n    - destruct H.\n      * left. exact H.\n      * destruct H. right. exact H0.\n  + intro.\n    destruct H.\n    destruct H.\n    - destruct H0.\n      * left. exact H.\n      * left.  exact H.\n    - destruct H0. \n      * left. exact H0.\n      * right. split.\n        ++ exact H.\n        ++ exact H0.\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/Ex020.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6712993567873123}}
{"text": "Inductive listn : nat -> Set :=\n  | niln : listn 0\n  | consn : forall n : nat, nat -> listn n -> listn (S n).\n\nInductive empty : forall n : nat, listn n -> Prop :=\n    intro_empty : empty 0 niln.\n\nParameter\n  inv_empty : forall (n a : nat) (l : listn n), ~ empty (S n) (consn n a l).\n\nType\n  (fun (n : nat) (l : listn n) =>\n   match l in (listn n) return (empty n l \\/ ~ empty n l) with\n   | niln => or_introl (~ empty 0 niln) intro_empty\n   | consn n O y as b => or_intror (empty (S n) b) (inv_empty n 0 y)\n   | consn n a y as b => or_intror (empty (S n) b) (inv_empty n a y)\n   end).\n\n\nType\n  (fun (n : nat) (l : listn n) =>\n   match l in (listn n) return (empty n l \\/ ~ empty n l) with\n   | niln => or_introl (~ empty 0 niln) intro_empty\n   | consn n O y => or_intror (empty (S n) (consn n 0 y)) (inv_empty n 0 y)\n   | consn n a y => or_intror (empty (S n) (consn n a y)) (inv_empty n a y)\n   end).\n\nType\n  (fun (n : nat) (l : listn n) =>\n   match l in (listn n) return (empty n l \\/ ~ empty n l) with\n   | niln => or_introl (~ empty 0 niln) intro_empty\n   | consn O a y as b => or_intror (empty 1 b) (inv_empty 0 a y)\n   | consn n a y as b => or_intror (empty (S n) b) (inv_empty n a y)\n   end).\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/ideal-features/Case4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6712993529178658}}
{"text": "Theorem plus_id_exercise : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m.\n  intros o.\n  \n  intros H.\n  intros I.\n  \n  rewrite -> H.\n  rewrite -> I.\n  reflexivity.\nQed.", "meta": {"author": "Asap7772", "repo": "coq_softwarefoundations", "sha": "a7a58d9f82aed0966d8a2fcd2fc3be1d4b7b1f0d", "save_path": "github-repos/coq/Asap7772-coq_softwarefoundations", "path": "github-repos/coq/Asap7772-coq_softwarefoundations/coq_softwarefoundations-a7a58d9f82aed0966d8a2fcd2fc3be1d4b7b1f0d/chapter1/plusID.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6712993387719138}}
{"text": "Require Import Coq.Init.Datatypes.\nRequire Import Coq.Program.Tactics.\nImport Coq.Init.Notations.\nNotation \"A -> B\" := (forall (_ : A), B) : type_scope.\nRequire Import propositionsSets.\n\nSection equivalencesDefinitions.\n\nInductive Qinv {X Y:Type} (f:X->Y):=\n|qinv \n  (g:Y->X)\n  (n:forall x:X, Id (g(f(x))) x)\n  (e:forall y:Y, Id (f(g(y))) y).\n\nInductive HalfAdjointEquiv {X Y:Type} (f:X->Y):=\n|halfAdjointEquiv \n  (g:Y->X)\n  (n:forall x:X, Id (g(f(x))) x)\n  (e:forall y:Y, Id (f(g(y))) y)\n  (t:forall x:X, Id (appl f (n x)) (e (f x))).\n\nInductive Biinv {X Y:Type} (f:X->Y):=\n|biinv  (g h:Y->X)\n        (n:forall x:X, Id (g(f(x))) x)\n        (e:forall y:Y, Id (f(h(y))) y).\n  \nInductive Fibre {X Y:Type} (f:X->Y) (y:Y):=\n|fibre\n  (x:X)\n  (H:Id (f(x)) y).\n\nInductive IsContractibleMap {X Y:Type} (f:X->Y):=\n|isContractibleMap\n  (H:forall y:Y, IsContractible(Fibre f y)).\n\nEnd equivalencesDefinitions.", "meta": {"author": "mwpb", "repo": "introduction-univalence-coq", "sha": "106643b5aea0937740e5ea51993a21da117dca2a", "save_path": "github-repos/coq/mwpb-introduction-univalence-coq", "path": "github-repos/coq/mwpb-introduction-univalence-coq/introduction-univalence-coq-106643b5aea0937740e5ea51993a21da117dca2a/equivalencesDefinitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067260443809, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6712836299075167}}
{"text": "From ZornsLemma Require Import EnsemblesImplicit InverseImage.\n\nDefinition EnsembleProduct {X Y : Type} (SX : Ensemble X) (SY : Ensemble Y) : Ensemble (X * Y) :=\n  fun p => In SX (fst p) /\\ In SY (snd p).\n\nLemma EnsembleProduct_Full {X Y : Type} :\n  @EnsembleProduct X Y Full_set Full_set = Full_set.\nProof.\n  apply Extensionality_Ensembles; split; red; intros.\n  - constructor.\n  - destruct x.\n    split.\n    all: constructor.\nQed.\n\nLemma EnsembleProduct_Empty_l {X Y : Type} V :\n  @EnsembleProduct X Y Empty_set V = Empty_set.\nProof.\n  apply Extensionality_Ensembles; split; red; intros.\n  - destruct x. destruct H. destruct H.\n  - destruct H.\nQed.\n\nLemma EnsembleProduct_Empty_r {X Y : Type} U :\n  @EnsembleProduct X Y U Empty_set = Empty_set.\nProof.\n  apply Extensionality_Ensembles; split; red; intros.\n  - destruct x. destruct H. destruct H0.\n  - destruct H.\nQed.\n\nLemma EnsembleProduct_Union {X Y : Type} (U0 U1 : Ensemble X) (V0 V1 : Ensemble Y) :\n  Included (Union (EnsembleProduct U0 V0) (EnsembleProduct U1 V1))\n           (EnsembleProduct (Union U0 U1) (Union V0 V1)).\nProof.\n  intros x H.\n  destruct H as [|]; destruct x; destruct H.\n  - split; left; assumption.\n  - split; right; assumption.\nQed.\n\nLemma EnsembleProduct_Intersection {X Y : Type} (U0 U1 : Ensemble X) (V0 V1 : Ensemble Y) :\n  Intersection (EnsembleProduct U0 V0) (EnsembleProduct U1 V1) =\n  EnsembleProduct (Intersection U0 U1) (Intersection V0 V1).\nProof.\n  apply Extensionality_Ensembles; split; red; intros.\n  - destruct H. destruct x. destruct H, H0.\n    split; split; assumption.\n  - destruct H.\n    inversion H; subst; clear H.\n    inversion H0; subst; clear H0.\n    split; constructor; assumption.\nQed.\n\nLemma inverse_image_fst {X Y : Type} (U : Ensemble X) :\n  inverse_image fst U = EnsembleProduct U (@Full_set Y).\nProof.\n  apply Extensionality_Ensembles; split; red; intros.\n  - do 2 red. destruct H. auto with sets.\n  - destruct H. constructor. auto.\nQed.\n\nLemma inverse_image_snd {X Y : Type} (V : Ensemble Y) :\n  inverse_image snd V = EnsembleProduct (@Full_set X) V.\nProof.\n  apply Extensionality_Ensembles; split; red; intros.\n  - do 2 red. destruct H. auto with sets.\n  - destruct H. constructor. auto.\nQed.\n\nLemma EnsembleProduct_proj {X Y : Type} (U : Ensemble X) (V : Ensemble Y) :\n  EnsembleProduct U V = Intersection (inverse_image fst U)\n                                     (inverse_image snd V).\nProof.\n  apply Extensionality_Ensembles; split; red; intros.\n  - destruct x. destruct H.\n    split; constructor; assumption.\n  - destruct H. inversion H. inversion H0.\n    destruct x. split; assumption.\nQed.\n\nLemma EnsembleProduct_Included {X Y : Type} (U0 U1 : Ensemble X) (V0 V1 : Ensemble Y) :\n  Included U0 U1 -> Included V0 V1 ->\n  Included (EnsembleProduct U0 V0) (EnsembleProduct U1 V1).\nProof.\n  intros. red; intros.\n  destruct x; destruct H1.\n  split; auto.\nQed.\n\nLemma EnsembleProduct_Complement {X Y : Type} (U : Ensemble X) (V : Ensemble Y) :\n  Complement (EnsembleProduct U V) =\n  Union (EnsembleProduct Full_set (Complement V))\n        (EnsembleProduct (Complement U) Full_set).\nProof.\n  apply Extensionality_Ensembles; split; red; intros.\n  - red in H. red in H.\n    apply not_and_or in H.\n    destruct x as [x y].\n    destruct H.\n    + right. split; [assumption|constructor].\n    + left. split; [constructor|assumption].\n  - destruct H.\n    + destruct x, H.\n      cbv. intros. intuition.\n    + destruct x, H. cbv. intuition.\nQed.\n\nLemma EnsembleProduct_Union_dist {X Y : Type} (U : Ensemble X) (V0 V1 : Ensemble Y) :\n  Union (EnsembleProduct U V0) (EnsembleProduct U V1) =\n  EnsembleProduct U (Union V0 V1).\nProof.\n  apply Extensionality_Ensembles; split; red; intros.\n  - destruct H.\n    + destruct H. split; try assumption.\n      left. assumption.\n    + destruct H. split; try assumption.\n      right. assumption.\n  - destruct H.\n    inversion H0; subst; clear H0.\n    + left. split; assumption.\n    + right. split; assumption.\nQed.\n\nLemma EnsembleProduct_Intersection_dist {X Y : Type} (U : Ensemble X) (V0 V1 : Ensemble Y) :\n  Intersection (EnsembleProduct U V0) (EnsembleProduct U V1) =\n  EnsembleProduct U (Intersection V0 V1).\nProof.\n  apply Extensionality_Ensembles; split; red; intros.\n  - destruct H. destruct H, H0.\n    split; try assumption; split; assumption.\n  - destruct H. inversion H0; subst; clear H0.\n    split; split; assumption.\nQed.\n", "meta": {"author": "coq-community", "repo": "topology", "sha": "f784257d0b9c316601440e4f02256bd6068e4f94", "save_path": "github-repos/coq/coq-community-topology", "path": "github-repos/coq/coq-community-topology/topology-f784257d0b9c316601440e4f02256bd6068e4f94/theories/ZornsLemma/EnsembleProduct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.671280203014159}}
{"text": "Require Import Reals.\nRequire Import Rinterval.\nRequire Import Lra.\n\nRequire Import Rpser_def Rpser_base_facts Rpser_cv_facts.\n\n(** In this library, we define the sum of a power serie with respect to the\n3 notions of convergence radius that we used until now.\n\n- weaksum_r sums a power serie on a disk that is smaller than the maximal\nconvergence disk\n- sum_r sums a power serie on its (finite) convergence disk\n- sum sums a power serie on its (infinite) convergence disk\n\nIn all the cases, the function outputed is proved to be unique and is\nexactly the one that equals the sum of the power serie inside the cv disk\nand is equal to 0 outside. *)\n\n(** * Definition of weaksum_r *)\n\nLocal Open Scope R_scope.\n\nDefinition weaksum_r : forall (An : nat -> R) (r : R) (Pr : Cv_radius_weak An r), R -> R.\nProof.\nintros An r Rho x.\n case (Rlt_le_dec (Rabs x) r) ; intro x_bd.\n elim (Rpser_abel _ _ Rho _ x_bd) ; intros y Hy ; exact y.\n exact 0.\nDefined.\n\n(** Proof that it is really the sum *)\n\nLemma weaksum_r_sums : forall (An : nat -> R) (r : R) (Pr : Cv_radius_weak An r) (x : R),\n      Rabs x < r -> Rpser An x (weaksum_r An r Pr x).\nProof.\nintros An r Pr x x_bd.\n unfold weaksum_r ; case (Rlt_le_dec (Rabs x) r) ; intro s.\n destruct (Rpser_abel An r Pr x s) as (l,Hl) ; simpl ; assumption.\n apply False_ind ; lra.\nQed.\n\n(** Proof that the sum is unique *)\n\nLemma weaksum_r_unique : forall (An : nat -> R) (r : R) (Pr1 Pr2 : Cv_radius_weak An r) (x : R),\n     Rabs x < r -> weaksum_r An r Pr1 x = weaksum_r An r Pr2 x.\nProof.\nintros An r Pr1 Pr2 x x_bd ;\n assert (T1 := weaksum_r_sums _ _ Pr1 _ x_bd) ;\n assert (T2 := weaksum_r_sums _ _ Pr2 _ x_bd) ;\n eapply Rpser_unique ; eassumption.\nQed.\n\nLemma weaksum_r_unique_strong : forall (An : nat -> R) (r1 r2 : R) (Pr1 : Cv_radius_weak An r1)\n     (Pr2 : Cv_radius_weak An r2) (x : R), Rabs x < r1 -> Rabs x < r2 ->\n     weaksum_r An r1 Pr1 x = weaksum_r An r2 Pr2 x.\nProof.\nintros An r1 r2 Pr1 Pr2 x x_bd1 x_bd2.\n  assert (T1 := weaksum_r_sums _ _ Pr1 _ x_bd1) ;\n  assert (T2 := weaksum_r_sums _ _ Pr2 _ x_bd2) ;\n eapply Rpser_unique ; eassumption.\nQed.\n\n(** * Definition of sum_r *)\n\nDefinition sum_r : forall (An : nat -> R) (r : R) (Pr : finite_cv_radius An r), R -> R.\nProof.\nintros An r Pr x.\n case (Rlt_le_dec (Rabs x) r) ; intro x_bd.\n  assert (rho : Cv_radius_weak An (middle (Rabs x) r)).\n  apply Pr; split.\n  apply Rle_trans with (Rabs x).\n   apply Rabs_pos.\n   left ; apply (proj1 (middle_is_in_the_middle _ _ x_bd)).\n   apply (proj2 (middle_is_in_the_middle _ _ x_bd)).\n apply (weaksum_r An (middle (Rabs x) r) rho x).\n exact 0.\nDefined.\n\n(** Proof that it is really the sum *)\n\nLemma sum_r_sums : forall  (An : nat -> R) (r : R) (Pr : finite_cv_radius An r),\n      forall x, Rabs x < r -> Rpser An x (sum_r An r Pr x).\nProof.\nintros An r Pr x x_ub.\n unfold sum_r ; destruct (Rlt_le_dec (Rabs x) r) as [x_bd | x_nbd].\n apply weaksum_r_sums.\n apply (proj1 (middle_is_in_the_middle _ _ x_bd)).\n  apply False_ind ; lra.\nQed.\n\n(** Proof that the sum is unique *)\n\nLemma sum_r_unique : forall (An : nat -> R) (r : R) (Pr1 Pr2 : finite_cv_radius An r) (x : R),\n     Rabs x < r -> sum_r An r Pr1 x = sum_r An r Pr2 x.\nProof.\nintros An r Pr1 Pr2 x x_bd ;\n assert (T1 := sum_r_sums _ _ Pr1 _ x_bd) ;\n assert (T2 := sum_r_sums _ _ Pr2 _ x_bd) ;\n eapply Rpser_unique ; eassumption.\nQed.\n\nLemma sum_r_unique_strong : forall (An : nat -> R) (r1 r2 : R) (Pr1 : finite_cv_radius An r1)\n     (Pr2 : finite_cv_radius An r2) (x : R), Rabs x < r1 -> Rabs x < r2 ->\n     sum_r An r1 Pr1 x = sum_r An r2 Pr2 x.\nProof.\nintros An r1 r2 Pr1 Pr2 x x_bd1 x_bd2 ;\n assert (T1 := sum_r_sums _ _ Pr1 _ x_bd1) ;\n assert (T2 := sum_r_sums _ _ Pr2 _ x_bd2) ;\n eapply Rpser_unique ; eassumption.\nQed.\n\n(** * Definition of sum *)\n\nDefinition sum : forall (An : nat -> R) (Pr : infinite_cv_radius An), R -> R.\nProof.\nintros An Pr r.\n apply (weaksum_r An (Rabs r +1) (Pr (Rabs r + 1)) r).\nDefined.\n\n(** Proof that it is really the sum *)\n\nLemma sum_sums : forall  (An : nat -> R) (Pr : infinite_cv_radius An),\n      forall x, Rpser An x (sum An Pr x).\nProof.\nintros An Pr x.\n apply weaksum_r_sums ; intuition.\nQed.\n\n(** Proof that the sum is unique *)\n\nLemma sum_unique : forall (An : nat -> R) (Pr1 Pr2 : infinite_cv_radius An) (x : R),\n      sum An Pr1 x = sum An Pr2 x.\nProof.\nintros An Pr1 Pr2 x ;\n assert (T1 := sum_sums  _ Pr1 x) ;\n assert (T2 := sum_sums  _ Pr2 x) ;\n eapply Rpser_unique ; eassumption.\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/Reals/Rpser/Rpser_sums.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.6712801920074986}}
{"text": "(* ***************************************************************** *)\n(*                                                                   *)\n(* Released: 2021/02/24.                                             *)\n(* Due: 2021/02/28, 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 (Assignment1.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 \"Assignment1.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 PL.Imp.\n\n(** The command [Admitted] can be used as a placeholder for an\n    incomplete proof or an in complete definition.  We'll use it in\n    exercises, to indicate the parts that we're leaving for you --\n    i.e., your job is to replace [Admitted]s with real proofs and/or\n    definitions. *)\n\n(* ################################################################# *)\n(** * Task 1 *)\n\n(** Equalities are symmetric and transive. Prove it in Coq. You should\nfill in your proof scripts and replace \"Admitted\" with \"Qed\".  *)\n\n(** **** Exercise: 1 star, standard *)\nTheorem eq_sym: forall (A: Type) (x y: A), x = y -> y = x.\nProof.\n  intros.\n  rewrite <- H.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard *)\nTheorem eq_trans: forall (A: Type) (x y z: A), x = y -> y = z -> x = z.\nProof.\n  intros.\n  rewrite H.\n  rewrite H0.\n  reflexivity.\nQed.\n(** [] *)\n\n(** The following example is an special instance of congruence properties.\nThat is, equalities between integers are preserved by addition. *)\n\n(** **** Exercise: 1 star, standard *)\nTheorem Zplus_add: forall x1 x2 y1 y2: Z,\n  x1 = y1 -> x2 = y2 -> x1 + x2 = y1 + y2.\nProof.\n  intros.\n  rewrite H.\n  rewrite H0.\n  reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Task 2 *)\n\n(** Read the following pairs of English descriptions and Hoare triples.\nDetermine whether they express equivalent meaning. *)\n\nModule Task2_Example.\n\n(**\nHoare triple: {{ True }} c {{ {[X]} <= 3 AND 3 <= {[X]} }}.\nInformal description: the program [c] will turn the value of [X] into [3].\nDo they express equivalent meaning? 1: Yes. 2: No.\n*)\n\nDefinition my_choice: Z := 1.\n\nEnd Task2_Example.\n\n(** **** Exercise: 1 star, standard *)\nModule Task2_1.\n\n(**\nHoare triple: {{ {[X]} <= {[Y]} }} c {{ {[Y]} <= {[X]} }}.\nInformal description: the program [c] will swap the values of [X] and [Y].\nDo they express equivalent meaning? 1: Yes. 2: No.\n\nRemove \"[Admitted.]\" and write down your choice.\n*)\n\nDefinition my_choice: Z := 2.\n(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n\nEnd Task2_1.\n(** [] *)\n\n(** **** Exercise: 1 star, standard *)\nModule Task2_2.\n\n(**\nHoare triple: {{ EXISTS k. {[X]} = 2 * k }} c {{ {[Y]} = 0 }}.\nInformal description: the program [c] will test whether [X] is an even\nnumber (偶数); if yes, [0] will be assigned into [Y].\nDo they express equivalent meaning? 1: Yes. 2: No.\n*)\n\nDefinition my_choice: Z := 2.\n(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n(* Note that the program [c] doesn't necessarily test [X]. *)\n\nEnd Task2_2.\n(** [] *)\n\n(** **** Exercise: 1 star, standard *)\nModule Task2_3.\n\n(**\nHoare triple: {{ True }} c {{ False }}.\nInformal description: the program [c] will never terminate.\nDo they express equivalent meaning? 1: Yes. 2: No.\n*)\n\nDefinition my_choice: Z := 1.\n(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n\nEnd Task2_3.\n(** [] *)\n\n(** **** Exercise: 1 star, standard *)\nModule Task2_4.\n\n(**\nHoare triple: {{ True }} c {{ True }}.\nInformal description: any program [c].\nDo they express equivalent meaning? 1: Yes. 2: No.\n*)\n\nDefinition my_choice: Z := 1.\n(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n\nEnd Task2_4.\n(** [] *)\n\n(** **** Exercise: 1 star, standard *)\nModule Task2_5.\n\n(**\nHoare triple: for any m, {{ {[X]} + {[Y]} = m }} c {{ {[X]} + {[Y]} = m }}.\nInformal description: the program [c] will not change the sum of [X] and [Y].\nDo they express equivalent meaning? 1: Yes. 2: No.\n*)\n\nDefinition my_choice: Z := 1.\n(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n\nEnd Task2_5.\n(** [] *)\n\n(* ################################################################# *)\n(** * Task 3 *)\n\n(** **** Exercise: 3 stars, standard (swapping_by_arith) *)\n\nModule swapping_by_arith.\nImport Concrete_Pretty_Printing.\nImport Axiomatic_semantics.\n\n(** Prove the following swapping programs correct. Hoare triples about single\nassignment commands are provided as hypothese.\n\n       X ::= X + Y;;\n       Y ::= X - Y;;\n       X ::= X - Y\n*)\n\nLocal Instance X: var := new_var().\nLocal Instance Y: var := new_var().\n\n(** Here are three hypothese. *)\n\nHypothesis triple1: forall x y: Z,\n  {{ {[X]} = x AND {[Y]} = y }}\n  X ::= X + Y\n  {{ {[X]} = x + y AND {[Y]} = y }}.\n\nHypothesis triple2: forall x y: Z,\n  {{ {[X]} = x + y AND {[Y]} = y }}\n  Y ::= X - Y\n  {{ {[X]} = x + y AND {[Y]} = x }}.\n\nHypothesis triple3: forall x y: Z,\n  {{ {[X]} = x + y AND {[Y]} = x }}\n  X ::= X - Y\n  {{ {[X]} = y AND {[Y]} = x }}.\n\n(** Now, prove the following Hoare triple by Hoare logic axioms. *)\n\nFact swapping_by_arith_correct:\n  forall x y: Z,\n       {{ {[X]} = x AND {[Y]} = y }}\n       X ::= X + Y;;\n       Y ::= X - Y;;\n       X ::= X - Y\n       {{ {[X]} = y AND {[Y]} = x }}.\nProof.\n  intros.\n  apply hoare_seq with ({[X]} = x + y AND {[Y]} = y)%assert.\n  apply triple1.\n  apply hoare_seq with ({[X]} = x + y AND {[Y]} = x)%assert.\n  apply triple2.\n  apply triple3.\nQed.\n(** [] *)\nEnd swapping_by_arith.\n\n(* ################################################################# *)\n(** * Task 4: Using [apply] in more Coq proofs *)\n\n(** A binary relation [R] is called a pre-order if it is reflexive and\ntransitive. Here is a very simple property about pre-orders. Try to prove\nit in Coq. *)\n\nSection PreOrder.\n\nVariable A: Type.\nVariable R: A -> A -> Prop.\nHypothesis R_refl: forall a, R a a.\nHypothesis R_trans: forall a b c, R a b -> R b c -> R a c.\n\n(** **** Exercise: 1 star, standard *)\nFact R_trans5: forall a b c d e, R a b -> R b c -> R c d -> R d e -> R a e.\nProof.\n  intros.\n  apply R_trans with (b := b).\n  apply H.\n  apply R_trans with (b := c).\n  apply H0.\n  apply R_trans with (b := d).\n  apply H1.\n  apply H2.\nQed.\n(** [] *)\n\nEnd PreOrder.\n\n\n\n(* 2021-02-23 23:55 *)\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/Assignment1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.6712801884053106}}
{"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     : Block is a fixed length array\n  author      : Zhengpu Shi\n  date        : 2022.05\n  \n  remark      :\n  1. it is a simple but more general implementation inspired from our team.\n  2. main idea of the work\n  (1). block\n    Record Block A n := {data : list A; Bcond : |data| = n}\n  (2). downgrade the block problem to list problem by remove the Bcond \n    condition with UIP (Uniqueness of Indentity Proofs).\n  (3). construct any-dim-array by repeat use block structure.\n*)\n\n\nRequire Import Coq.Logic.Eqdep.\n        Import EqdepTheory.   (* UIP *)\n\nFrom MyStdLibExt \nRequire Export ListExt.General.   (* List extension *)\n\n\n\n(* ######################################################################### *)\n(** * Definition and basic properties of block *)\nSection Def.\n  \n  (* ======================================================================= *)\n  (** ** Definitions and properties *)\n  Section Defs.\n  \n    Variable A : Type.\n    Variable n : nat.\n    \n    (** A block is consists of a list and a limit on the length of that list. *)\n    Record Block := mkBlock {\n      Bdata : list A;\n      Bcond : length Bdata = n\n    }.\n    \n    (** Length of Bdata is stable *)\n    Lemma Bdata_length : forall (b : Block), length (Bdata b) = n.\n    Proof. intros [l H]. auto. Qed.\n    \n    (** Block equal iff its data equal *)\n    Lemma beq_iff : forall (b1 b2 : Block), \n      Bdata b1 = Bdata b2 <-> b1 = b2.\n    Proof.\n      intros [l1 H1] [l2 H2]; simpl. split; intros.\n      - subst. f_equal. apply UIP.\n      - injection H; auto.\n    Qed.\n\n    (** Block not equal iff its data not equal *)\n    Lemma beq_iff_not : forall (b1 b2 : Block), \n      Bdata b1 <> Bdata b2 <-> b1 <> b2.\n    Proof.\n      intros. split; intros; intro H1; apply beq_iff in H1; auto.\n    Qed.\n  \n  End Defs.\n\n  Global Arguments Block {A n}.\n  Global Arguments mkBlock {A n}.\n  Global Arguments Bdata {A n}.\n  Global Arguments Bcond {A n}.\n  \nEnd Def.\n\n\n\n(* ######################################################################### *)\n(* * Conversion between block and other data type *)\nSection Conversion.\n\n\n  (* ======================================================================= *)\n  (** ** Create a empty block *)\n  Section CreateEmpty.\n    \n    Definition bzero {A} (A0 : A) (n : nat) : @Block A n :=\n      mkBlock (repeat A0 n) (repeat_length A0 n).\n    \n  End CreateEmpty.\n\n  Global Arguments bzero {A}.\n  \n  \n  (* ======================================================================= *)\n  (** ** Create block with a list *)\n  Section CreateWithList.\n  \n    (** Create a block by a list and the length of the list. *)\n    Definition l2b {A} (l : list A) : @Block A (length l) :=\n      mkBlock l (eq_refl).\n    \n    (** Coercion from list to Block is convenient *)\n    Coercion l2b : list >-> Block.\n    \n  End CreateWithList.\n  \n  Global Arguments l2b {A}.\n  \n  Section test.\n    \n    Let b1 : Block := [1;2].\n    Let b21 : Block := [l2b [1;2]; l2b [3;4]].\n    Let b22 : Block := [l2b [5;6]; l2b [7;8]].\n    Let b3 : Block := l2b [b21;b22].\n\n    Compute b1.\n    Compute Bdata b1.\n\n    Compute b21.\n    Compute Bdata b21.\n    Compute Bdata (hd _ (Bdata b21)).\n    \n    Compute b3.\n    Compute Bdata b3.\n    Compute Bdata (hd _ (Bdata b3)).\n    Compute hd _ (Bdata (hd _ (Bdata b3))).\n    Compute Bdata (hd _ (Bdata (hd _ (Bdata b3)))).\n\n  End test.\n  \n  \n  (* ======================================================================= *)\n  (** ** Create block with Coq.Vectors.VectorDef.t *)\n  Section CreateWithCoqVector.\n    \n    Import VectorDef.\n    \n    (** Create a block by Vector.t *)\n    Fixpoint coqvec2b {A} {n} (v : Vector.t A n) : @Block A n.\n      refine (mkBlock (VectorDef.to_list v) _).\n      induction v; auto.\n      assert (to_list (Vector.cons A h n v) = h :: to_list v); auto.\n      rewrite H. simpl. rewrite IHv. auto.\n    Defined.\n    \n  End CreateWithCoqVector.\n  \n  Global Arguments coqvec2b {A n}.\n  \n  Section test.\n    Import VectorDef.\n    Import VectorNotations.\n    \n    Compute coqvec2b [1;2;3].\n    \n  End test.\n  \nEnd Conversion.\n\n\n\n(* ######################################################################### *)\n(* * Get element of block *)\nSection GetElement.\n\n  (* ======================================================================= *)\n  (** ** Get element with index *)\n  Section ByIndex.\n\n    Variable A : Type.\n    Variable A0 : A.\n    Variable n : nat.\n    \n    (** Get element with index, if the index out-of-bounds then return A0 *)\n    Definition bget (b : @Block A n) (i : nat) : A := \n      nth i (Bdata b) A0.\n    \n    (** Block equal iff every visit with valid index get same result *)\n    Lemma beq_iff_bget : forall (b1 b2 : @Block A n),\n      b1 = b2 <-> (forall (i : nat) (Hi : i < n), bget b1 i = bget b2 i).\n    Proof.\n      intros [l1 H1] [l2 H2]. split; intros.\n      - f_equal. auto.\n      - apply beq_iff; simpl.\n        rewrite (list_eq_iff_nth A0 n); auto.\n    Qed.\n\n  End ByIndex.\n\n  Global Arguments bget {A} _ {n}.\n  \n  \n  (* ======================================================================= *)\n  (* test *)\n  Section test.\n\n    Compute bget 0 [1;2;3] 0.\n    Compute bget 0 [1;2;3] 1.\n\n  End test.\n\nEnd GetElement.\n\n\n\n(* ######################################################################### *)\n(* * Set element of block *)\nSection SetElement.\n\n  (* ======================================================================= *)\n  (** ** Set element by index *)\n  Section ByIndex.\n\n    Variable A : Type.\n    Variable n : nat.\n    \n    (** Set element by index with a constant value. *)\n    Definition bset (b : @Block A n) (i : nat) (x : A) : @Block A n :=\n      let 'mkBlock l H := b in\n        mkBlock (lst_chg l i x) (lst_chg_height l i n x H).\n    \n    (** Set element by index with a function. *)\n    Definition bsetf (b : @Block A n) (i : nat) (f : nat -> A) : @Block A n :=\n      let 'mkBlock l H := b in\n        mkBlock (lst_chgf l i f) (lst_chgf_height l n i f H).\n     \n  End ByIndex.\n\n  Global Arguments bset {A n}.\n  Global Arguments bsetf {A n}.\n  \n  (* ======================================================================= *)\n  (* test *)\n  Section test.\n  \n    Compute bset [1;2;3] 1 9.\n    Compute bsetf [1;2;3] 1 (fun i => i + 10).\n\n  End test.\n\nEnd SetElement.\n\n\n\n(* ######################################################################### *)\n(* * Mapping of block *)\nSection Mapping.\n\n  (* ======================================================================= *)\n  (** ** Mapping of one block *)\n  Section Map1.\n    \n    Variable A B : Type.\n    Variable n : nat.\n    Variable f : A -> B.\n    \n    Definition bmap (b : @Block A n) : @Block B n.\n      refine (mkBlock (map f (Bdata b)) _).\n      rewrite map_length. apply Bdata_length.\n    Defined.\n\n  End Map1.\n  \n  Global Arguments bmap {A B n}.\n  \n  \n  (* ======================================================================= *)\n  (* test *)\n  Section test.\n    \n    Compute bmap (fun i => Nat.even i) [1;2;3].\n\n  End test.\n  \n  \n  (* ======================================================================= *)\n  (** ** Mapping of two blocks *)\n  Section Map2.\n    \n    Variable A B C : Type.\n    Variable n : nat.\n    Variable f : A -> B -> C.\n    \n    Definition bmap2 (b1 : @Block A n) (b2 : @Block B n) : @Block C n.\n      refine (mkBlock (map2 f (Bdata b1) (Bdata b2)) _).\n      rewrite (map2_length) with (n:=n); auto. all: apply Bdata_length.\n    Defined.\n    \n  End Map2.\n  \n  Global Arguments bmap2 {A B C n}.\n  \n\n  (* ======================================================================= *)\n  (* test *)\n  Section test.\n    \n    Compute bmap2 (fun i j => i + j) [1;2;3] [4;5;6].\n\n  End test.\n  \n  \n  (* ======================================================================= *)\n  (** ** Properties when mapping of two blocks with same base type *)\n  Section Map2_sametype.\n\n    Variable A : Type.\n    Variable n : nat.\n    Variable f : A -> A -> A.\n    Variable f_comm : forall a b, f a b = f b a.\n    Variable f_assoc : forall a b c, f a (f b c) = f (f a b) c.\n\n    Lemma bmap2_comm : forall (b1 b2 : @Block A n),\n      bmap2 f b1 b2 = bmap2 f b2 b1.\n    Proof.\n      intros [l1 H1] [l2 H2]. apply beq_iff; simpl. \n      apply map2_comm; auto.\n    Qed.\n    \n    Lemma bmap2_assoc : forall (b1 b2 b3 : @Block A n),\n      bmap2 f (bmap2 f b1 b2) b3 = bmap2 f b1 (bmap2 f b2 b3).\n    Proof.\n      intros [l1 H1] [l2 H2] [l3 H3]. apply beq_iff; simpl.\n      apply map2_assoc; auto.\n    Qed.\n    \n  End Map2_sametype.\n\nEnd Mapping.\n\n\n\n", "meta": {"author": "zhengpushi", "repo": "coq-matrix", "sha": "b0f5a3463d7f1973fd29be8b6b85e4a700297a34", "save_path": "github-repos/coq/zhengpushi-coq-matrix", "path": "github-repos/coq/zhengpushi-coq-matrix/coq-matrix-b0f5a3463d7f1973fd29be8b6b85e4a700297a34/MatrixComparison/src/Matrix/MultiDimMat/v2/Block.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.6712801865242213}}
{"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.\nRequire Import Coq.Logic.FunctionalExtensionality.\nImport ListNotations.\n\nAxiom admit: forall {X},  X.\n\nReserved Notation \"c1 '/' st '\\\\' st'\"\n                  (at level 40, st at level 39).\n\n(** Dans cet exercice, nous étendons la sémantique du langage Imp\n    étudié en cours, étendons sa logique de programme et vérifions la\n    correction d'un programme écrit dans ce système. *)\n\n(** * Variables *)\n\n(** Comme en cours, nous modélisons les variables du langage par un\n    type [id] dont nous nommons (arbitrairement) 3 éléments [X], [Y]\n    et [Z]. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition X : id := Id 0.\nDefinition Y : id := Id 1.\nDefinition Z : id := Id 2.\n\nDefinition beq_id x1 x2 :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\n\nTheorem beq_id_refl : forall x, beq_id x x = true.\nProof. now intros; destruct x; simpl; rewrite <- beq_nat_refl. Qed.\n\n(** QUESTION [difficulté [*] / longueur [*]]\n\n    [X] et [Y] étant définis, les lemmes suivants sont prouvables par\n    simple _calcul_.  *)\n\nRemark rq1: beq_id X X = true.\nProof. \n  apply beq_id_refl.\nQed.\n\nRemark rq2: beq_id X Y = false.\nProof.\n  simpl.\n  auto.\nQed.\n\n(** * Mémoire *)\n\n(** Comme en cours, nous modélisons la mémoire par une fonction des\n    identifiants vers les entiers. On accède donc au contenu de la\n    mémoire [s] à l'adresse [x] par application [s x]. *)\n\nDefinition state := id -> nat.\n\nDefinition empty_state: state := fun _ => 0.\n\nDefinition update (s: state)(x: id)(n: nat) :=\n  fun y => if beq_id x y then n else s y.\n\n(** QUESTION [difficulté [**] / longueur [*]]\n\n    Prouver les identités suivantes reliant l'extension de la mémoire\n    et l'accès à la mémoire: *)\n\n\nLemma update_eq : forall s x v,\n    update s x v x = v.\nProof. \n  intros. induction v;\n  unfold update; rewrite beq_id_refl; reflexivity.\nQed.\n\nLemma update_shadow : forall s v1 v2 x,\n    update (update s x v1) x v2\n  = update s x v2.\nProof.\n  intros. unfold update; simpl.\n  apply functional_extensionality.\n  intro x0.\n  case (beq_id x x0); auto.\nQed.\n\n(** * Expressions booléennes *)\n\n(** Les expressions booléennes permettent d'écrire des formules\n    booléennes (avec [BTrue], [BFalse], [BNot] et [BAnd]) ainsi que\n    des tests sur le contenu des variables ([BEq] et [BLe]). *)\n\nInductive bexp : Type :=\n  | BTrue  : bexp\n  | BFalse : bexp\n  | BNot   : bexp -> bexp\n  | BAnd   : bexp -> bexp -> bexp\n  | BEq    : id -> nat -> bexp\n  | BLe    : id -> nat -> bexp.\n\nFixpoint beval (st: state)(b : bexp) : bool :=\n  match b with\n  | BTrue      => true\n  | BFalse     => false\n  | BNot b1    => negb (beval st b1)\n  | BAnd b1 b2 => andb (beval st b1) (beval st b2)\n  | BEq x n    => beq_nat (st x) n\n  | BLe x n    => leb (st x) n\n  end.\n\n(** QUESTION [difficulté [*] / longueur [*]]\n\n    Dériver le \"ou logique\" [BOr] à partir de [BNot] et [BAnd]\n    (suivant la loi de De Morgan) puis prouver que sa sémantique est\n    conforme à [orb], l'implémentation du \"ou logique\" en Coq.  *)\n\n\nDefinition BOr (b1 b2: bexp): bexp :=\n  BNot (BAnd (BNot b1) (BNot b2)).\n\nLemma bor_correct: forall st b1 b2, \n    beval st (BOr b1 b2) = orb (beval st b1) (beval st b2).\nProof.\n  intros. simpl. \n  SearchAbout \"negb\".\n  rewrite negb_andb.\n  rewrite negb_involutive.\n  rewrite negb_involutive.\n  reflexivity.\nQed.\n\n(** QUESTION [difficulté [**] / longueur [***]]\n\n    Prouver que la sémantique de [BLe'] défini ci-dessous est conforme\n    à [leb], l'implémentation de la comparaison d'entiers dans Coq. *)\n\nDefinition BLe' (m: nat)(x: id): bexp :=\n  BOr (BNot (BLe x m)) (BEq x m).\n\nLemma ble'_correct: forall st m x, beval st (BLe' m x) = leb m (st x).\nProof.\n  intros.\n  unfold BLe'.\n  rewrite bor_correct.\n  simpl.\n  remember (leb m (st x)).\n  destruct b.\n  - apply orb_true_iff.\n    symmetry in Heqb.\n    apply leb_iff, le_lt_or_eq in Heqb.\n    destruct Heqb.\n    + left.\n      now apply negb_true_iff, leb_correct_conv.\n    + right.\n      now apply beq_nat_true_iff.\n  - apply orb_false_iff.\n    symmetry in Heqb.\n    apply leb_complete_conv in Heqb.\n    split.\n    + apply negb_false_iff. apply leb_correct.\n      omega.\n    + SearchAbout \"beq_nat_fa\".\n      apply beq_nat_false_iff. \n      omega.\nQed.\n\n(** * Commandes *)\n\n(** Nous considérons le langage des commandes habituelles ([CSkip],\n    [CSeq], [CWhile]) étendu avec une commande décrémentant une\n    variable ([CDecr]). *)\n\nInductive com : Type :=\n  | CSkip : com\n  | CSeq : com -> com -> com\n  | CWhile : bexp -> com -> com\n  | CDecr : id -> com.\n\nNotation \"'SKIP'\" :=\n  CSkip.\nNotation \"x '--'\" :=\n  (CDecr x) (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).\n\n(** QUESTION [difficulté [***] / longueur [*]]\n\n    Compléter la sémantique du langage de commandes ci-dessous avec la\n    sémantique de [CDecr]. *)\n\nInductive ceval : com -> state -> state -> Prop :=\n  | E_Skip : forall st,\n\n  (*--------------------------------------*)\n      SKIP / st \\\\ st\n\n  | E_Seq : forall c1 c2 st st' st'',\n\n      c1 / st  \\\\ st' ->\n      c2 / st' \\\\ st'' ->\n  (*--------------------------------------*)\n      (c1 ;; c2) / st \\\\ st''\n  | E_WhileEnd : forall b st c,\n\n      beval st b = false ->\n  (*--------------------------------------*)\n      (WHILE b DO c END) / st \\\\ st\n  | E_WhileLoop : forall st st' st'' b c,\n\n      beval st b = true ->\n      c / st \\\\ st' ->\n      (WHILE b DO c END) / st' \\\\ st'' ->\n  (*--------------------------------------*)\n      (WHILE b DO c END) / st \\\\ st''\n\n                         \n  | E_DECR : forall st st' x,\n      update st x (st x - 1) = st' ->     \n      (x--) / st \\\\ update st x (st x - 1)\n      \n      \n  where \"c1 '/' st '\\\\' st'\" := (ceval c1 st st').\n\n(** Dans ce langage, on peut ainsi écrire le programme suivant, qui\n    teste la parité du contenu de la variable [X]: *)\n\nDefinition PARITY :=\n WHILE (BLe' 2 X) DO\n       X-- ;; X--\n END.\n\n(** QUESTION [difficulté [*] / longueur [*]]\n\n    Prouver que, à partir d'un état mémoire où [X = 4], le résultat de la commande [X--]\n    retourne un état où [X = 3]. *)\n\nExample Decr_test: \n  X-- / update empty_state X 4 \\\\ update empty_state X 3.\nProof.\n  set (m := update empty_state X 4).\n  replace (update empty_state X 3) with (update m X (m X - 1)).\n  - apply E_DECR with (update m X (m X - 1)). reflexivity.\n  - \n    subst m. simpl.\n    apply update_shadow.\nQed.\n\n(** QUESTION [difficulté [**] / longueur [***]]\n\n    Prouver que, à partir d'un état mémoire où [X = 4], le test de\n    parité retourne [X = 0]. *)\n\nExample PARITY_test: \n  PARITY / update empty_state X 4 \\\\ update empty_state X 0.\nProof.\n  unfold PARITY.  \n  apply E_WhileLoop with (update (update (update empty_state X 4) X 3) X 2).\n  - easy.\n  - apply E_Seq with (update (update empty_state X 4) X 3).\n    + apply E_DECR with (update (update empty_state X 4) X 3).\n      easy.\n    + apply E_DECR with (update (update (update empty_state X 4) X 3) X 2).\n      easy.\n  - replace (update (update (update empty_state X 4) X 3) X 2) with\n      (update empty_state X 2).\n    apply E_WhileLoop with (update (update (update empty_state X 2) X 1)  X 0).\n    + easy.\n    + apply E_Seq with (update (update empty_state X 2) X 1).\n      * apply E_DECR with (update (update empty_state X 2) X 1).\n        easy.\n      * apply E_DECR with (update (update (update empty_state X 2) X 1) X 0).\n        easy.\n    + replace (update (update (update empty_state X 2) X 1) X 0) with\n      (update empty_state X 0).\n      apply E_WhileEnd.\n      easy.\n      replace (update empty_state X 0) with\n      (update (update empty_state X 1) X 0).\n      apply eq_sym. f_equal. apply update_shadow. apply update_shadow.\n    + replace (update empty_state X 2) with\n      (update (update empty_state X 3) X 2).\n      apply eq_sym. f_equal. apply update_shadow. apply update_shadow.\nQed.\n\n(** * Logique de Hoare *)\n\n(** Nous obtenons une logique de programme par la construction\n    usuelle. *)\n\nDefinition Assertion := state -> Prop.\n\nDefinition assert_implies (P Q : Assertion) : Prop :=\n  forall st, P st -> Q st.\n\nNotation \"P ->> Q\" := (assert_implies P Q)\n                      (at level 80).\n\nDefinition hoare_triple\n           (P:Assertion) (c:com) (Q:Assertion) : Prop :=\n  forall st st',\n     c / st \\\\ st'  ->\n     P st  -> Q st'.\n\nNotation \"{{ P }}  c  {{ Q }}\" := (hoare_triple P c Q)\n    (at level 90, c at next level).\n\n(** À partir de ces définitions, nous pouvons spécifier le\n    comportement des commandes grâce à la logique de programme. Pour\n    [SKIP], [;;] et [WHILE], cela se traduit par les spécifications\n    suivantes: *)\n\nAxiom hoare_consequence_pre : forall (P P' Q : Assertion) c,\n  {{P'}} c {{Q}} -> P ->> P' ->\n  {{P}} c {{Q}}.\n\nAxiom hoare_consequence_post : forall (P Q Q' : Assertion) c,\n  {{P}} c {{Q'}} -> Q' ->> Q ->\n  {{P}} c {{Q}}.\n\nAxiom hoare_skip : forall P,\n     {{P}} SKIP {{P}}.\n\nAxiom hoare_seq : forall P Q R c1 c2,\n     {{Q}} c2 {{R}} -> {{P}} c1 {{Q}} ->\n     {{P}} c1;;c2 {{R}}.\n\nDefinition bassn b : Assertion :=\n  fun st => (beval st b = true).\n\nAxiom hoare_while : forall P b c,\n  {{fun st => P st /\\ bassn b st}} c {{P}} ->\n  {{P}} WHILE b DO c END {{fun st => P st /\\ ~ (bassn b st)}}.\n\n(** QUESTION [difficulté [***] / longueur [*]]\n\n    Sur le modèle de l'assignation (vu en cours), donner et prouver la\n    spécification la plus précise possible pour l'opération de\n    décrémentation. *)\n\nDefinition assn_sub X P : Assertion := \n  fun (st : state) => P (update st X (st X - 1)).\n\nNotation \"P '[' X '--]'\" := (assn_sub X P) (at level 10).\n\nTheorem hoare_decr : forall Q X,\n    {{Q [X --]}}  X--  {{Q}}.\n\nProof.\n  unfold hoare_triple.\n  intros Q X st st' HE HQ.\n  inversion HE. subst.\n  unfold assn_sub in HQ.\n  assumption.\nQed.\n\n(** * Preuve de correction *)\n\n(** Nous souhaitons désormais prouver la correction du programme\n    [PARITY] introduit précédemment. Pour cela, il nous faut traduire\n    la spécification informelle de [PARITY] par une définition\n    formelle dans Coq. *)\n\n(** QUESTION {BONUS} [difficulté [*] / longueur [*]]\n\n    Implémenter la fonction [parity] ci-dessous qui doit retourner [0]\n    si son argument est pair et [1] si son argument est impaire. *)\n\nSearchAbout \"mod\".\n\nFixpoint parity (x: nat): nat :=\n  match x with\n  | 0 => 0\n  | 1 => 1\n  | S (S n) => parity n\n  end.\n\nEval compute in parity 3.\nEval compute in parity 8.\n\n(** QUESTION {BONUS} [difficulté [**] / longueur [**]]\n\n    Afin de prouver la correction de [PARITY] vis-à-vis de [parity],\n    nous aurons besoin des deux lemmes techniques suivants. *)\n\nLemma parity_ge_2 : forall x,\n  2 <= x ->\n  parity (x - 2) = parity x.\nProof.\n  intros.\n  induction x.\n  - easy.\n  - SearchPattern (_ <= _ -> _).\n    admit.    \nQed.\n\n\nLemma parity_lt_2 : forall x,\n  not (2 <= x) ->\n  parity x = x.\nProof.\n  intros.\n  induction x.\n  + easy.\n  + admit. \nQed.\n\n(** QUESTION {BONUS} [difficulté [***] / longueur [***]]\n\n    À l'aide de ces résultats et des opérations de la logique de\n    programme, prouver la correction de [PARITY]. *)\n\nTheorem parity_correct : forall m,\n    {{ fun st => st X = m }}\n      PARITY\n    {{ fun st => st X = parity m }}.\nProof.\n  intros.\n  apply hoare_consequence_pre \n      with (P' := fun st => parity (st X) = parity m).\n  apply hoare_consequence_post\n      with (Q' := fun st => parity (st X) = parity m /\\ st X < 2).\n  - (* Prove: {{ parity X = parity m }} PARITY {{ parity X = parity m /\\ X < 2 }} *)\n    unfold PARITY.\n    admit.\n  - (* Prove: parity X = parity m /\\ X < 2 -> st X = parity m *)    \n    unfold assert_implies.\n    intros.\n    destruct H as [H1 H2].\n    rewrite <- H1.\n    apply eq_sym.\n    apply parity_lt_2.\n    SearchPattern (~ _ <= _).\n    apply lt_not_le. assumption.\n  - (* Prove: X = m -> parity X = parity m *)\n    unfold assert_implies.\n    intros.\n    rewrite <- H.\n    reflexivity.\nQed.\n", "meta": {"author": "infou012", "repo": "Verification", "sha": "14ddcb52ab106d6b5b50c2b76b64f6908491dac3", "save_path": "github-repos/coq/infou012-Verification", "path": "github-repos/coq/infou012-Verification/Verification-14ddcb52ab106d6b5b50c2b76b64f6908491dac3/dm_2_paritystudent_issa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.6712801810008375}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra.\nImport GRing.\nImport FracField.\n\nSection q_tools.\nLocal Open Scope ring_scope.\n\nVariable (R : rcfType) (q : R).\nHypothesis Hq : q - 1 != 0.\n\nNotation \"f ** g\" := (fun x => f x * g x) (at level 40).\nNotation \"f // g\" := (fun x => f x / g x) (at level 40).\nNotation \"a */ f\" := (fun x => a * (f x)) (at level 40).\n\n(* tools *)\n(* -の分配則*)\nLemma negdistr {V : zmodType} (a b : V) : - (a + b) = - a - b.\nProof.\n  have -> : - (a + b) = - a + a - (a + b).\n    rewrite [- a + a] addrC.\n    rewrite -{2}(add0r a) addrK.\n    by rewrite sub0r.\n  by rewrite addrKA.\nQed.\n\nLemma halfdistr m n : ~ odd m ->\n  ((m + n)./2 = m./2 + n./2)%N.\nProof.\n  move=> em.\n  rewrite halfD.\n  by case Hm : (odd m).\nQed.\n\nLemma half_add n : (n.+1 + (n.+1 * n)./2 = (n.+2 * (n.+1))./2)%N.\nProof.\n  rewrite -{1}(doubleK n.+1) -halfdistr.\n    by rewrite -muln2 -mulnDr addnC addn2 mulnC.\n  by rewrite odd_double.\nQed.\n\nLemma Negz_add m n : Negz (m.+1 + n) = Negz m + Negz n.\nProof. by rewrite !NegzE -addnS (negdistr (Posz m.+1) n.+1)%N. Qed.\n\nLemma Negz_addK m n : Negz (m + n) + n = Negz m.\nProof.\n  rewrite !NegzE addrC -addn1.\n  rewrite (_ : Posz (m + n + 1)%N = Posz m + n + 1) //.\n  rewrite -[Posz m + n + 1] addrA.\n  rewrite [Posz m + (Posz n + 1)] addrC.\n  rewrite -[Posz n + 1 + m] addrA.\n  rewrite -{1}(add0r (Posz n)).\n  by rewrite addrKA -addn1 sub0r addnC.\nQed.\n\nLemma NegzK n : Posz n.+1 + Negz n = 0.\nProof. by rewrite NegzE addrN. Qed.\n\nLemma NegzS n : Negz n.+1 + 1 = Negz n.\nProof. by rewrite -addn1 Negz_addK. Qed.\n\nLemma opp_oppE (x : R) : - - x = x.\nProof. by rewrite -(sub0r x) (opprB 0) subr0. Qed.\n\nLemma opp_oppE' (x y : R) : - x * - y = x * y.\nProof. by rewrite mulrN mulNr opp_oppE. Qed.\n\nLemma eq_int_to_nat (m n : nat): m = n:> int -> m = n.\nProof.\n  move /eqP.\n  rewrite -(eqr_int R) Num.Theory.eqr_nat.\n  by move/eqP.\nQed.\n\nLemma eq_nat_to_int (m n : nat): m = n -> m = n:> int.\nProof. by move=> ->. Qed.\n\nLemma eq_nat_to_R (m n : nat) : m = n -> (m = n)%R.\nProof. by move=> ->. Qed.\n\nLemma mulnon0 (a b : R) : a * b != 0 -> a != 0.\nProof.\n  move/eqP.\n  case_eq (a == 0) => //.\n  move/eqP ->.\n  by rewrite mul0r.\nQed.\n\nLemma mulrC23 {V : comRingType} (a b c d : V) :\n  a * b * c * d = a * c * b * d.\nProof.\n  f_equal.\n  by rewrite -!mulrA [b * c]mulrC.\nQed.\n\nLemma exp0rz' n : (GRing.zero R) ^ (Posz n.+1) = 0.\nProof. by rewrite exprSz mul0r. Qed.\n\nLemma expnon0 (x : R) (n : nat) : x != 0 -> x ^ n != 0.\nProof.\n  move=> Hx.\n  elim: n => [|n IH].\n  - by rewrite expr0z oner_neq0.\n  - by rewrite exprSz mulf_neq0.\nQed.\n\nLemma exp_gt1 (x : R) (n : nat) : x > 1 -> x ^ n.+1 > 1.\nProof.\n  elim: n => [|n IH] Ix //=.\n  rewrite exprSz.\n  by apply /Num.Theory.mulr_egt1 /IH.\nQed.\n\n(* R上の　add cancel *)\nLemma addrK' {V : zmodType} (a : V) : a - a = 0.\nProof. by rewrite -{1}(add0r a) addrK. Qed.\n\n(* Rの移項 *)\nLemma rtransposition (a b c : R) : a + b = c -> a = c - b.\nProof. by move=> <-; rewrite addrK. Qed.\n\n(* intの移項 *)\nLemma itransposition (l m n : int) : l + m = n -> l = n - m.\nProof. by move=> <-; rewrite addrK. Qed.\n\n\nLemma Negz_transp m n l : m + Negz n = l -> m = l + n.+1.\nProof. rewrite NegzE; apply itransposition. Qed.\n\nLemma same_addl {V : zmodType} {a b} (c : V) : c + a = c + b -> a = b.\nProof.\n  move=> H.\n  rewrite -(addr0 a) -(addrK' c) addrA [a + c] addrC H.\n  by rewrite [c + b] addrC -addrA addrK' addr0.\nQed.\n\n(* 両辺にかける *)\nLemma same_prod {a b} (c : R) : c != 0 -> a * c = b * c -> a = b.\nProof.\n  move=> Hc.\n  by rewrite -{2}(mulr1 a) -{2}(mulr1 b)\n     -(@divff _ c) // !mulrA => ->.\nQed.\n\nLemma denomK (x y : R) : y != 0 ->\n  (x / y) * y = x.\nProof.\n  move=> Hy.\n  by rewrite -mulrA mulVf // mulr1.\nQed.\n\n(* 右側約分 *)\nLemma red_frac_r (x y z : R) : z != 0 ->\n  x * z / (y * z) = x / y.\nProof.\n  move=> Hz.\n  by rewrite -mulf_div divff // mulr1.\nQed.\n\n(* 左側約分 *)\nLemma red_frac_l (x y z : R) : z != 0 ->\n  z * x / (z * y) = x / y.\nProof.\n  move=> Hz.\n  by rewrite [z * x] mulrC [z * y] mulrC red_frac_r.\nQed.\n\nLemma opp_frac (x y : R) : - x / - y = x / y.\nProof. by rewrite -mulrN1 -(mulrN1 y) red_frac_r ?oppr_eq0 ?oner_neq0. Qed.\n\nLemma inv_invE (x : R) : 1 / (1 / x) = x.\nProof. by rewrite divKf // oner_neq0. Qed.\n\n(* 分母共通の和 *)\nLemma add_div (x y z : R) : z != 0 ->\n  x / z + y / z = (x + y) / z.\nProof.\n  move=> nz0.\n  by rewrite addf_div // -mulrDl red_frac_r.\nQed.\n\n(* 頻出分母が0でない *)\nLemma denom_is_nonzero x : x != 0 -> q * x - x != 0.\nProof.\n  move=> Hx.\n  rewrite -{2}(mul1r x) -mulrBl.\n  by apply mulf_neq0.\nQed.\n\nLemma denom_comm (x y z : R) : x / y / z = x / z / y.\nProof. by rewrite -mulrA [y^-1 / z] mulrC mulrA. Qed.\n\nLemma sumW {V : zmodType} n (F : nat -> V) :\n  \\sum_(i < n) F i = \\sum_(0 <= i < n) F i.\nProof. by rewrite big_mkord. Qed.\n\nLemma sum_add {V : zmodType} n (F G : nat -> V) :\n  \\sum_(0 <= i < n) (F i) + \\sum_(0 <= i < n) (G i) =\n  \\sum_(0 <= i < n) (F i + G i).\nProof.\n  elim: n => [|n IH].\n  - by rewrite !big_nil addr0.\n  - rewrite !(@big_cat_nat _ _ _ n 0 n.+1) //= !big_nat1.\n    rewrite -IH -!addrA.\n    congr (_ + _).\n    by rewrite addrC -addrA [G n + F n]addrC.\nQed.\n\nLemma sum_sub {V : zmodType} n (F G : nat -> V) :\n  \\sum_(0 <= i < n) (F i) - \\sum_(0 <= i < n) (G i) =\n  \\sum_(0 <= i < n) (F i - G i).\nProof.\n  elim: n => [|n IH].\n  - by rewrite !big_nil subr0.\n  - rewrite !(@big_cat_nat _ _ _ n 0 n.+1) //= !big_nat1.\n    rewrite -IH -!addrA.\n    congr (_ + _).\n    by rewrite addrC addrA negdistr -addrA [- G n + F n]addrC addrA.\nQed.\n\nLemma sum_distr {V : comRingType} n (F : nat -> V) (a : V) :\n  \\sum_(0 <= i < n) (F i * a) = a * \\sum_(0 <= i < n) F i.\nProof.\n  elim: n => [|n IH].\n  - by rewrite !big_nil mulr0.\n  - rewrite !(@big_cat_nat _ _ _ n 0 n.+1) //=.\n    by rewrite !big_nat1 mulrDr IH [F n * a]mulrC.\nQed.\n\nLemma hornersumD m n P (a : R) :\n  (\\sum_(m <= j < n.+1) P j).[a] = (\\sum_(m <= j < n.+1) (P j).[a]).\nProof.\n  have -> : (m = 0 + m)%N by [].\n  rewrite !big_addn.\n  elim: (n.+1 - m)%N => {n} [|n IH] //=.\n  - by rewrite !big_nil horner0.\n  - rewrite (@big_cat_nat _ _ _ n) //= big_nat1.\n    rewrite hornerD IH.\n    by rewrite [RHS] (@big_cat_nat _ _ _ n) //= big_nat1.\nQed.\n\nLemma sum_poly_div n F (P : nat -> {poly R}) C x :\n  \\sum_(0 <= i < n.+1) (F i * (P i).[x] / C i) =\n  \\sum_(0 <= i < n.+1) (F i * (P i / (C i)%:P).[x]) .\nProof.\n  elim: n => [|n IH].\n  - by rewrite !big_nat1 hornerM polyCV hornerC mulrA.\n  - rewrite !(@big_cat_nat _ _ _ n.+1 0 n.+2) //= IH.\n    by rewrite !big_nat1 hornerM polyCV hornerC mulrA.\nQed.\n\nLemma divpsum n P (d : {poly R}) :\n  (\\sum_(0 <= i < n) P i) %/ d = \\sum_(0 <= i < n) (P i %/ d).\nProof.\nelim: n => [|n IH].\n- by rewrite !big_nil div0p.\n- by rewrite !(@big_cat_nat _ _ _ n 0 n.+1) //= !big_nat1 divpD IH.\nQed.\n\nLemma polyW (p : {poly R}) n (a : nat -> R) : ((size p) <= n)%N ->\n  \\poly_(i < size p) (a i * p`_i.+1) =\n  \\sum_(0 <= i < n) (a i * p`_i.+1) *: 'X^i.\nProof.\n  move=> H.\n  rewrite poly_def.\n  rewrite (@big_cat_nat _ _ _ (size p)) //= big_mkord big_nat -[LHS]addr0.\n  f_equal.\n  rewrite big1 // => i /andP [Hi _].\n  move/leq_sizeP : Hi -> => //.\n  by rewrite mulr0 scale0r.\nQed.\n\nLemma polyW' (p : {poly R}) n (a : nat -> R) : ((size p) <= n)%N ->\n  \\poly_(i < size p) (a i * p`_i) =\n  \\sum_(0 <= i < n) (a i * p`_i) *: 'X^i.\nProof.\n  move=> H.\n  rewrite poly_def.\n  rewrite (@big_cat_nat _ _ _ (size p)) //= big_mkord big_nat -[LHS]addr0.\n  congr (_ + _).\n  rewrite big1 // => i /andP [Hi _].\n  move/leq_sizeP : Hi -> => //.\n  by rewrite mulr0 scale0r.\nQed.\n\nLemma size_N0_lt (p : {poly R}) : (size p == 0%N) = false -> (0 < size p)%N.\nProof.\n  move=> Hsize.\n  rewrite ltn_neqAle.\n  apply /andP; split => //.\n  move: Hsize.\n  by rewrite eq_sym => ->.\nQed.\n\nLemma scale_constpoly (a c : R) : a *: c%:P = (a * c)%:P.\nProof.\n  apply polyP => i.\n  rewrite coefZ !coefC.\n  case : (i == 0%N) => //.\n  by rewrite mulr0.\nQed.\n\nLemma polyX_div n : (polyX R) ^ n.+1 %/ (polyX R) = (polyX R) ^ n.\nProof.\n  by rewrite exprSzr mulpK ?polyX_eq0.\nQed.\n\nLemma scalerAr' c d (p : {poly R}) j : c * (d *: p)`_j = d * (c * p`_j).\nProof.\n  rewrite mulrA (mulrC d) -mulrA.\n  f_equal.\n  by rewrite coefZ.\nQed.\n\nLemma scale_div c d (p p' : {poly R}) : d != 0 ->\n  (c *: p) %/ (d *: p') = (c / d) *: (p %/ p').\nProof.\n  move=> Hd.\n  by rewrite divpZl divpZr // scalerA.\nQed.\n\nLocal Notation tofrac := (@tofrac [idomainType of {poly R}]).\nLocal Notation \"x %:F\" := (tofrac x).\n\nLemma frac_same_prod (a b c : {fraction [idomainType of {poly R}]}) :\n  c != 0 -> a * c = b * c -> a = b.\nProof.\n  move=> Hc.\n  by rewrite -{2}(mulr1 a) -{2}(mulr1 b)\n     -(@divff _ c) // !mulrA => ->.\nQed.\nEnd q_tools.", "meta": {"author": "nakamurakaoru", "repo": "q-analogue", "sha": "ee9af7a058e4449335c77ed744a061e38f6b19ac", "save_path": "github-repos/coq/nakamurakaoru-q-analogue", "path": "github-repos/coq/nakamurakaoru-q-analogue/q-analogue-ee9af7a058e4449335c77ed744a061e38f6b19ac/q_tools.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.6712801695538749}}
{"text": "Set Implicit Arguments.\nRequire Import TLC.LibLN.\nRequire Import GStlc.\n\n(* \n\nRS is the declarative specification of subtyping, which\nincludes the built-in Sym rule.\n\n*)\n\nInductive RS : Mode -> typ -> typ -> Prop :=\n| RSInt : forall m, RS m typ_int typ_int\n| RSTB1 : forall A m, RS m A (mode_to_sub m)\n| RSFun : forall A B C D m, RS (flip m) A C -> RS m B D -> RS m (typ_arrow A B) (typ_arrow C D)\n| RSSym : forall m A B, RS (flip m) B A -> RS m A B.\n\nHint Constructors RS.\n    \nLemma sound : forall m A B, R m A B -> RS m A B.\n  intros.\n  induction H; eauto.\nDefined.\n\nLemma complete : forall m A B, RS m A B -> R m A B.\n  intros.\n  induction H; eauto.\n  apply sym2.\n  auto.\nDefined.\n\n(* \n\nR2 an algorithmic version that exploits duality for economy \nof code. \n\n*)\n\nInductive R2 : bool -> Mode -> typ -> typ -> Prop :=\n| R2Int : forall b m, R2 b m typ_int typ_int\n| R2TB1 : forall b A m, R2 b m A (mode_to_sub m)\n| R2Fun : forall b A B C D m,\n    R2 true (flip m) A C ->\n    R2 true m B D ->\n    R2 b m (typ_arrow A B) (typ_arrow C D)\n| R2Sym : forall m A B,\n    R2 false (flip m) B A -> R2 true m A B.\n\nHint Constructors R2.\n\n(* Soundness of R2 *)\n\nLemma completeR : forall m A B, R m A B -> R2 true m A B.\n  intros.\n  induction H; eauto.\nDefined.\n\nLemma soundR : forall m b A B, R2 b m A B -> R m A B.\n  intros.\n  induction H; eauto.\n  apply sym2. auto.\nDefined.\n", "meta": {"author": "baberrehman", "repo": "coq-duotyping", "sha": "dc80486014fedbc2cd54cdb0104aa8e60af7d81e", "save_path": "github-repos/coq/baberrehman-coq-duotyping", "path": "github-repos/coq/baberrehman-coq-duotyping/coq-duotyping-dc80486014fedbc2cd54cdb0104aa8e60af7d81e/coq/DuoTyping/GStlcExtra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.671219342050956}}
{"text": "(* リレー回路 *)\n(* 全加算器 Zuseの回路 の正しさの証明 *)\n(*\n   Prologと違って、autoのときにバックトラックが起きないから、\n   正しい項を指定する必要がある。\n   Coqの不得意とする問題だろうか。\n*)\n\n\n(*\n   rly(S, S, C, C, _) :- !.\n   rly(_, _, C, _, C).\n*)\n\n\nInductive Sig : Set :=\n| H : Sig\n| L : Sig\n| O : Sig.\n\n\nInductive rly : Sig -> Sig -> Sig -> Sig -> Sig -> Prop :=\n| off0 : forall   c no, rly L L c c no\n| off1 : forall   c no, rly H H c c no\n| off2 : forall s c no, rly O s c c no\n| off3 : forall s c no, rly s O c c no\n| on0  : forall   c nc, rly H L c nc c\n| on1  : forall   c nc, rly L H c nc c.\nHint Resolve off0 off1 off2 off3 on0 on1 : relay.\n\n\n(* AND回路 *)\nInductive and_c (x y z : Sig) : Prop :=\n  and_c0 : forall u v w,\n    rly x L H v u -> rly y L u w z -> and_c x y z.\n\n\nCheck and_c H H H.\n\n\nGoal and_c H H H.\nProof.\n  eapply and_c0.\n  apply (on0 H H).\n  apply (on0 H H).\nQed.\n\n\nGoal and_c H H H.\nProof.\n  eapply and_c0.\n  apply (on0 _ H).\n  apply (on0 _ H).\nQed.\n\n\nGoal and_c H L H.                           (* zはopenなので、Hでも可能 *)\nProof.\n  eapply and_c0.\n  apply (on0 H H).\n  apply (off0 H H).\nQed.\n\n\nGoal (and_c H L H /\\ and_c H L L).\nProof.\n  split.\n  eapply and_c0.\n  apply (on0 H H).\n  apply (off0 H H).\n\n\n  eapply and_c0.\n  apply (on0 H H).\n  apply (off0 H L).\nQed.\n\n\n(* 出力もOPENだが、Lを加えればLになってしまう。 *)\nGoal and_c O O L.\nProof.\n  eapply and_c0.\n  apply (off2 L H O).\n  apply (off2 L O L).\nQed.\n\n\n(*\n%%\n%% Zuseの回路 (dual-rail-carry full adder)\n%%\nfa(InA, InB, InC, InNotC, OutS, OutC, OutNotC) :-\n        rly(InA, 0, OutNotC, I, H),\n        rly(InA, 0, InNotC,  K, J),\n        rly(InA, 0, InC,     J, K),\n        rly(InA, 0, OutC,    N, L),\n        rly(InB, 0, InNotC,  H, I),\n        rly(InB, 0, OutS,    J, K), \n        rly(InB, 0, 1,       I, L),\n        rly(InB, 0, InC,     L, N).\n*)\n\n\nInductive fa (InA InB InC InNotC OutS OutC OutNotC : Sig ) : Prop :=\n  fa0 : forall i j k l n h,\n    rly InA L OutNotC i h ->\n    rly InA L InNotC  k j ->\n    rly InA L InC     j k ->\n    rly InA L OutC    n l ->\n    rly InB L InNotC  h i ->\n    rly InB L OutS    j k -> \n    rly InB L H       i l ->\n    rly InB L InC     l n ->\n    fa InA InB InC InNotC (**) OutS OutC OutNotC.\n\n\nGoal fa L H L H (**)  H L H.\nProof.\n  eapply fa0.\n  intros.\n  apply (off0 H H).\n  apply (off0 H L).\n  apply (off0 L H).\n  apply (off0 L H).\n  apply (on0  H H).\n  apply (on0  H L).\n  apply (on0  H H).\n  apply (on0  L H).\nQed.\n\n\nGoal fa L H L H (**)  H L H.\nProof.\n  eapply fa0.\n  intros.\n  apply (off0 _ H).\n  apply (off0 _ L).\n  apply (off0 _ _).\n  apply (off0 _ H).\n  apply (on0  _ _).\n  apply (on0  _ _).\n  apply (on0  _ _).\n  apply (on0  _ _).\nQed.\n\n\n(* テストケースを生成する *)\nInductive gen : Sig -> Sig -> Sig -> Sig -> Sig -> Sig -> Sig -> Prop :=\n(*             入力     出力 *)\n| gen000 : gen L L L H  L L H\n| gen001 : gen L L H L  H L H\n| gen010 : gen L H L H  H L H\n| gen011 : gen L H H L  L H L\n| gen100 : gen H L L H  H L H\n| gen101 : gen H L H L  L H L\n| gen110 : gen H H L H  L H L\n| gen111 : gen H H H L  H H L.\n\n\nGoal forall (InA InB InC InNotC OutS OutC OutNotC : Sig),\n  gen InA InB InC InNotC OutS OutC OutNotC -> fa InA InB InC InNotC OutS OutC OutNotC.\nProof.\n  intros.\n  inversion H0.\n  (* induction H0 でも同じ。*)\n  \n  eapply fa0.                               (* L L L *)\n  intros.\n  apply (off0 _ H).\n  apply (off0 _ L).\n  apply (off0 _ _).\n  apply (off0 _ L).\n  apply (off0 _ _).\n  apply (off0 _ _).\n  apply (off0 _ _).\n  apply (off0 _ _).\n\n\n  eapply fa0.                               (* L L H *)\n  intros.\n  apply (off0 _ L).\n  apply (off0 _ H).\n  apply (off0 _ _).\n  apply (off0 _ H).\n  apply (off0 _ _).\n  apply (off0 _ _).\n  apply (off0 _ _).\n  apply (off0 _ _).\n\n\n  eapply fa0.                               (* L H L *)\n  intros.\n  apply (off0 _ H).\n  apply (off0 _ L).\n  apply (off0 _ _).\n  apply (off0 _ H).\n  apply (on0  _ _).\n  apply (on0  _ _).\n  apply (on0  _ _).\n  apply (on0  _ _).\n\n\n  eapply fa0.                               (* L H H *)\n  intros.\n  apply (off0 _ L).\n  apply (off0 _ H).\n  apply (off0 _ _).\n  apply (off0 _ H).\n  apply (on0  _ _).\n  apply (on0  _ _).\n  apply (on0  _ _).\n  apply (on0  _ _).\n\n\n  eapply fa0.                               (* H L L *)\n  intros.\n  apply (on0  _ H).\n  apply (on0  _ L).\n  apply (on0  _ _).\n  apply (on0  _ L).\n  apply (off0 _ _).\n  apply (off0 _ _).\n  apply (off0 _ _).\n  apply (off0 _ _).\n\n\n  eapply fa0.                               (* H L H *)\n  intros.\n  apply (on0  _ H).\n  apply (on0  _ H).\n  apply (on0  _ _).\n  apply (on0  _ L).\n  apply (off0 _ _).\n  apply (off0 _ _).\n  apply (off0 _ _).\n  apply (off0 _ _).\n\n\n  eapply fa0.                               (* H H L *)\n  intros.\n  apply (on0 _ H).\n  apply (on0 _ L).\n  apply (on0 _ _).\n  apply (on0 _ L).\n  apply (on0 _ _).\n  apply (on0 _ _).\n  apply (on0 _ _).\n  apply (on0 _ _).\n\n\n  eapply fa0.                               (* H H H *)\n  intros.\n  apply (on0 _ L).\n  apply (on0 _ H).\n  apply (on0 _ _).\n  apply (on0 _ H).\n  apply (on0 _ _).\n  apply (on0 _ _).\n  apply (on0 _ _).\n  apply (on0 _ _).\nQed.\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_relay.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6712193302914529}}
{"text": "Require Export LaugwitzSchmieden.\n\nModule LSw <: Num_w.\n\nInclude LS. \n(* Definitions in LS are available here thanks to the module type declaration for LS - see above - *)\n\nParameter w: nat->Z.\nAxiom ANS3 : ~lim w.\nAxiom Aw : 0<A w.\n\nAxiom lim_lt_w : forall a, lim a/\\ leA 0 a -> ltA a w.\n\nLemma div_modw2 : forall a, w*(a/w) =A a + - (a mod% w).\nProof.\nintros a; apply div_mod2.\nleft; apply Aw.\nQed.\n\nLemma div_modw3 : forall a, |(a mod% w)| <A w.\nProof.\nintros a; apply div_mod3.\napply Aw.\nQed.\n\nEnd LSw.\n\n\n", "meta": {"author": "magaud", "repo": "HR", "sha": "18ef55bf254bffed6af7c6024986665924e770e4", "save_path": "github-repos/coq/magaud-HR", "path": "github-repos/coq/magaud-HR/HR-18ef55bf254bffed6af7c6024986665924e770e4/w.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6712142924448342}}
{"text": "Require Import Reals.\nRequire Import Coquelicot.Coquelicot.\nRequire Import Psatz.\nRequire Import Bool.\nRequire Import network_calculus_def.\n\nLocal Open Scope R_scope.\nLocal Open Scope Rbar_scope.\n\nDefinition pseudo_inv_inf (f : ndf_Rbar_Rbar) (y : Rbar) :=\n  Rbar_glb (fun x => y <= (f x)).\n\nDefinition pseudo_inv_sup (f : ndf_Rbar_Rbar) (y : Rbar) :=\n  Rbar_lub (fun x => (f x) <= y).\n\nTheorem pseudo_inv_inf_non_decreasing (f : ndf_Rbar_Rbar) (x y : Rbar) :\n  x <= y -> pseudo_inv_inf f x <= pseudo_inv_inf f y.\nProof.\nintros H_xy.\nassert (H_fxy' := ndf_Rbar_Rbar_prop f _ _ H_xy).\nunfold pseudo_inv_inf; set (Ex := fun _ => Rbar_le x _); set (Ey := fun _ => _).\nassert (Hx := proj2_sig (Rbar_ex_glb Ex)).\nassert (Hy := proj2_sig (Rbar_ex_glb Ey)).\nnow apply (Rbar_is_glb_subset Ex Ey); [intro x'; apply Rbar_le_trans| |].\nQed.\n\nLemma Non_decr_recipr (f : ndf_Rbar_Rbar) (x y : Rbar) :\n  (f x) < (f y) -> x < y.\nProof.\nintro H_fx_fy; apply Rbar_not_le_lt; intro H_xy.\nnow apply (Rbar_lt_not_le _ _ H_fx_fy), (ndf_Rbar_Rbar_prop f).\nQed.\n\n\nLemma ex_el_between x y :\n  Rbar_lt x y -> {z : Rbar | Rbar_lt x z /\\ Rbar_lt z y}.\nProof.\ncase x; [intro rx|now exists p_infty|];\n  (case y; [intro ry| |now exists m_infty]); intro H_xy.\n{ exists ((rx + ry) / 2); revert H_xy; simpl; lra. }\n{ exists (rx + 1); simpl; lra. }\n{ exists (ry - 1); simpl; lra. }\nnow exists 0.\nQed.\n\nLemma alt_def_pseudo_inv_inf (f : ndf_Rbar_Rbar) (y : Rbar) :\n  pseudo_inv_inf f y = Rbar_lub (fun x => (f x) < y).\nProof.\napply Rbar_is_glb_unique.\nset (Ele := fun x => _ y _); set (Elt := fun x => _).\ndestruct (Rbar_ex_lub Elt) as [l Hl]; rewrite (Rbar_is_lub_unique _ _ Hl).\nsplit.\n{ intros x H_x; apply (proj2 Hl); intros z Hz.\n  now apply Rbar_lt_le, (Non_decr_recipr f), (Rbar_lt_le_trans _ _ _ Hz). }\nintros b Hb; apply Rbar_not_lt_le; intro H_lb.\ndestruct (ex_el_between _ _ H_lb) as [m [H_ml H_mb]].\ncase (Rbar_le_lt_dec y (f m)); intro H_m.\n{ now apply (Rbar_lt_not_le _ _ H_mb), Hb. }\nnow apply (Rbar_lt_not_le _ _ H_ml), (proj1 Hl).\nQed.\n\nLemma alt_def_pseudo_inv_sup (f : ndf_Rbar_Rbar) (y : Rbar) :\n  pseudo_inv_sup f y = Rbar_glb (fun x => y < (f x)).\nProof.\napply Rbar_is_lub_unique.\nset (Ele := fun x => _ y _); set (Elt := fun x => _).\ndestruct (Rbar_ex_glb Ele) as [l Hl]; rewrite (Rbar_is_glb_unique _ _ Hl).\nsplit.\n{ intros x H_x; apply (proj2 Hl); intros z Hz.\n  now apply Rbar_lt_le, (Non_decr_recipr f), (Rbar_le_lt_trans _ _ _ H_x). }\nintros b Hb; apply Rbar_not_lt_le; intro H_lb.\ndestruct (ex_el_between _ _ H_lb) as [m [H_mb H_ml]].\ncase (Rbar_le_lt_dec (f m) y); intro H_m.\n{ now apply (Rbar_lt_not_le _ _ H_mb), Hb. }\nnow apply (Rbar_lt_not_le _ _ H_ml), (proj1 Hl).\nQed.\n\nLemma P4 (f : ndf_Rbar_Rbar) (y : Rbar) :\n  (pseudo_inv_inf f y) <= (pseudo_inv_sup f y).\nProof.\n  rewrite alt_def_pseudo_inv_inf.\n  apply Rbar_lub_subset.\n  intros x H_x.\n  now apply Rbar_lt_le.\nQed.\n\nLemma P5 (f : ndf_Rbar_Rbar) (y y' : Rbar) :\n  y < y' -> (pseudo_inv_sup f y) <= (pseudo_inv_inf f y').\nProof.\n  intros H_yy'.\n  rewrite alt_def_pseudo_inv_inf.\n  apply Rbar_lub_subset.\n  intros x H_x.\n  now apply (Rbar_le_lt_trans (f x) y y').\nQed.\n\nLemma P6 (f : ndf_Rbar_Rbar) (x y : Rbar) :\n  (f x) <= y -> x <= (pseudo_inv_sup f y).\nProof.\n  intros H.\n  destruct (proj2_sig (Rbar_ex_lub (fun x => Rbar_le (f x) y)))as [H_ub _].\n  now apply H_ub.\nQed.\n\nLemma P7 (f : ndf_Rbar_Rbar) (x y : Rbar) :\n  y <= (f x) -> (pseudo_inv_inf f y) <= x.\nProof.\n  intros H.\n  destruct (proj2_sig (Rbar_ex_glb (fun x => Rbar_le y (f x))))as [H_ub _].\n  now apply H_ub.\nQed.\n\nLemma P8 (f : ndf_Rbar_Rbar) (x y : Rbar) :\n  (f x) < y -> x <= (pseudo_inv_inf f y).\nProof.\n  intros H.\n  rewrite alt_def_pseudo_inv_inf.\n  destruct (proj2_sig (Rbar_ex_lub (fun x => Rbar_lt (f x) y)))as [H_ub _].\n  now apply H_ub.\nQed.\n\nLemma P9 (f : ndf_Rbar_Rbar) (x y : Rbar) :\n  y < (f x) -> (pseudo_inv_sup f y) <= x.\nProof.\n  intros H.\n  rewrite alt_def_pseudo_inv_sup.\n  destruct (proj2_sig (Rbar_ex_glb (fun x => Rbar_lt y (f x))))as [H_lb _].\n  now apply H_lb.\nQed.\n\nLemma P10 (f : ndf_Rbar_Rbar) (x y : Rbar) :\n  (pseudo_inv_inf f y) < x -> y <= (f x).\nProof.\n  rewrite alt_def_pseudo_inv_inf.\n  set (Elt := fun _ => _).\n  intro H.\n  apply Rbar_not_lt_le.\n  intro H0.\n  destruct (proj2_sig (Rbar_ex_lub Elt)) as [H_ub _].\n  exact ((Rbar_lt_not_le _ _ H) (H_ub _ H0)).\nQed.\n\nLemma P11 (f : ndf_Rbar_Rbar) (x y : Rbar) :\n  x < (pseudo_inv_sup f y) -> (f x) <= y.\nProof.\n  rewrite alt_def_pseudo_inv_sup.\n  set (Elt := fun _ => _).\n  intro H.\n  apply Rbar_not_lt_le.\n  intro H0.\n  destruct (proj2_sig (Rbar_ex_glb Elt)) as [H_lb _].\n  exact ((Rbar_lt_not_le _ _ H) (H_lb _ H0)).\nQed.\n\nLemma P12 (f : ndf_Rbar_Rbar) (x y : Rbar) :\n  (pseudo_inv_sup f y) < x -> y < (f x).\nProof.\n  unfold pseudo_inv_sup; set (Ele := fun _ => _).\n  intro H.\n  apply Rbar_not_le_lt.\n  intro H0.\n  destruct (proj2_sig (Rbar_ex_lub Ele)) as [H_ub _].\n  exact ((Rbar_lt_not_le _ _ H) (H_ub _ H0)).\nQed.\n\nLemma P14 (f : ndf_Rbar_Rbar) (x y : Rbar) :\n  x < (pseudo_inv_inf f y) -> (f x) < y.\nProof.\n  unfold pseudo_inv_inf; set (Ele := fun _ => _).\n  intro H.\n  apply Rbar_not_le_lt.\n  intro H0.\n  destruct (proj2_sig (Rbar_ex_glb Ele)) as [H_lb _].\n  exact ((Rbar_lt_not_le _ _ H) (H_lb _ H0)).\nQed.", "meta": {"author": "Remjez", "repo": "Network_calculus_coq", "sha": "98fe1c6faa49f82e3c116d030ce596e76d47d0d4", "save_path": "github-repos/coq/Remjez-Network_calculus_coq", "path": "github-repos/coq/Remjez-Network_calculus_coq/Network_calculus_coq-98fe1c6faa49f82e3c116d030ce596e76d47d0d4/pseudo_inv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.7634837689358858, "lm_q1q2_score": 0.6712142899234935}}
{"text": "Require Import Coq.Setoids.Setoid.\nRequire Import New.Ring.\nRequire Import New.RingTheorems.\nRequire Import New.Field.\n\n(* Basic complex operations *)\nClass ComplexOps A := {\n  complex_conj : A -> A\n}.\n\n(* Unorthodox notation *)\nNotation \"~ x\" := (complex_conj x).\n\nClass ComplexProps A {cops : ComplexOps A} := {\n  complex_conj_inv : forall (x : A), (~ (~ x)) = x;\n  complex_conj_ext : forall a b : A, a = b <-> (~ a) = (~ b)\n}.\n\nClass ComplexSemiRingProps A {cops : ComplexOps A} {srops : SemiRingOps A} := {\n  conj_sum : forall a b : A, (~ (a + b)) = (~ a) + (~ b);\n  conj_mul : forall a b : A, (~ (a * b)) = (~ b) * (~ a);\n  zero_self_conj : (~ 0) = 0\n}.\n\n\n(* Type which builds complex numbers out of an underlying type *)\nRecord Complex A := {\n  real_part : A;\n  imaginary_part : A\n}.\n\nFunction complex_conj_impl {A} {rops : RingOps A} (x : Complex A) :=\n  {| real_part := real_part A x; imaginary_part := - imaginary_part A x |}.\n\nInstance ComplexImplOps A {rops : RingOps A} {ra : Ring A} :\n  ComplexOps (Complex A) := {\n  complex_conj := complex_conj_impl\n}.\n\nLemma complex_conj_impl_inv {A} {rops : RingOps A} {ra : Ring A} :\n  forall a : Complex A, complex_conj_impl (complex_conj_impl a) = a.\nProof.\n  intros.\n  unfold complex_conj_impl.\n  elim a.\n  intros.\n  f_equal.\n  unfold imaginary_part.\n  rewrite neg_inv.\n  reflexivity.\nQed.\n\nLemma complex_conj_impl_ext {A} {rops : RingOps A} {ra : Ring A} :\n  forall a b : Complex A, a = b <-> (complex_conj_impl a) = (complex_conj_impl b).\nProof.\n  intros.\n  unfold complex_conj_impl.\n  elim a.\n  elim b.\n  unfold real_part.\n  unfold imaginary_part.\n  intros.\n  unfold iff.\n  split.\n  intro.\n  injection H.\n  intros.\n  f_equal.\n  assumption.\n  f_equal.\n  assumption.\n  intro.\n  injection H.\n  intros.\n  f_equal.\n  assumption.\n  rewrite <- neg_inv.\n  rewrite <- neg_inv at 1.\n  f_equal.\n  assumption.\nQed.\n\nInstance ComplexImplProps A {rops : RingOps A} {ra : Ring A} :\n  ComplexProps (Complex A) := {\n  complex_conj_inv := complex_conj_impl_inv;\n  complex_conj_ext := complex_conj_impl_ext\n}.\n\nDefinition complex_zero {A} {rops : RingOps A} : Complex A :=\n  {| real_part := 0; imaginary_part := 0 |}.\n\nDefinition complex_one {A} {rops : RingOps A} : Complex A :=\n  {| real_part := 1; imaginary_part := 0 |}.\n\nLemma complex_zero_self_conj {A} {rops : RingOps A} {rna : Ring A} :\n  (complex_conj_impl complex_zero) = complex_zero.\nProof.\n  unfold complex_conj_impl.\n  unfold complex_zero.\n  unfold imaginary_part.\n  f_equal.\n  apply zero_self_inv.\nQed.\n\nFunction complex_add {A} {rops : SemiRingOps A} (x y : Complex A) :=\n  {| real_part := real_part A x + real_part A y;\n     imaginary_part := imaginary_part A x + imaginary_part A y |}.\n\nLemma conj_impl_sum {A} {rops : RingOps A} {rna : Ring A} :\n  forall a b : Complex A, complex_conj_impl (complex_add a b) =\n                          complex_add (complex_conj_impl a) (complex_conj_impl b).\nProof.\n  intros.\n  unfold complex_conj_impl.\n  unfold complex_add.\n  elim a.\n  elim b.\n  unfold real_part.\n  unfold imaginary_part.\n  intros.\n  f_equal.\n  apply neg_add.\nQed.\n\nFunction complex_mul {A} {rops : RingOps A} (x y : Complex A) :=\n  {| real_part := real_part A x * real_part A y -\n                  imaginary_part A x * imaginary_part A y;\n     imaginary_part := real_part A x * imaginary_part A y +\n                       imaginary_part A x * real_part A y |}.\n\nLemma conj_impl_mul {A} {rops : RingOps A} {rna : Ring A} :\n  forall a b : Complex A, (complex_conj_impl (complex_mul a b)) =\n                          complex_mul (complex_conj_impl b) (complex_conj_impl a).\nProof.\n  intros.\n  unfold complex_conj_impl.\n  unfold complex_mul.\n  elim a.\n  elim b.\n  unfold real_part.\n  unfold imaginary_part.\n  intros.\n  f_equal.\n  rewrite mul_comm.\n  rewrite 2! sub_def.\n  apply add_extensional.\n  reflexivity.\n  rewrite <- neg_mul.\n  rewrite neg_inv.\n  rewrite mul_comm.\n  apply neg_mul_left.\n  rewrite <- neg_mul.\n  rewrite <- neg_mul_left.\n  rewrite neg_add.\n  rewrite add_comm.\n  rewrite mul_comm.\n  apply add_extensional.\n  reflexivity.\n  rewrite mul_comm.\n  reflexivity.\nQed.\n\nInstance ComplexSemiRingOps A {rops : RingOps A} : SemiRingOps (Complex A) := {\n  zero := complex_zero;\n  one := complex_one;\n  add := complex_add;\n  mul := complex_mul\n}.\n\nInstance ComplexImplSemiRingProps {A}\n  {rops : RingOps A}\n  {rna : Ring A} :\n  ComplexSemiRingProps (Complex A) := {\n  conj_sum := conj_impl_sum;\n  conj_mul := conj_impl_mul;\n  zero_self_conj := complex_zero_self_conj\n}.\n\nFunction complex_sub {A} {rops : RingOps A} (x y : Complex A) :=\n  {| real_part := real_part A x - real_part A y;\n     imaginary_part := imaginary_part A x - imaginary_part A y |}.\n\nFunction complex_neg {A} {rops : RingOps A} (x : Complex A) :=\n  {| real_part := - real_part A x; imaginary_part := - imaginary_part A x |}.\n\nLemma complex_sub_def {A} {rops : RingOps A} :\n  forall (x y : Complex A), complex_sub x y = complex_add x (complex_neg y).\nProof.\n  intros.\n  unfold complex_add.\n  unfold complex_neg.\n  unfold complex_sub.\n  elim x.\n  elim y.\n  unfold real_part.\n  unfold imaginary_part.\n  intros.\n  f_equal.\n  apply sub_def.\n  apply sub_def.\nQed.\n\nLemma complex_sub_zero {A} {rops : RingOps A} :\n  forall (x : Complex A), complex_sub x x = zero.\nProof.\n  intro.\n  unfold complex_sub.\n  elim x.\n  unfold real_part.\n  unfold imaginary_part.\n  intros.\n  rewrite 2! sub_zero.\n  reflexivity.\nQed.\n\nInstance ComplexRingOps A {rops : RingOps A} : RingOps (Complex A) := {\n  rops := ComplexSemiRingOps A;\n  sub := complex_sub;\n  neg := complex_neg;\n  sub_def := complex_sub_def;\n  sub_zero := complex_sub_zero\n}.\n\nLemma complex_add_extensional {A} {rops : RingOps A} :\n  forall x1 x2 y1 y2 : (Complex A),\n    x1 = x2 -> y1 = y2 -> complex_add x1 y1 = complex_add x2 y2.\nProof.\n  intros.\n  unfold complex_add.\n  rewrite H.\n  rewrite H0.\n  reflexivity.\nQed.\n\nLemma complex_mul_extensional {A} {rops : RingOps A} :\n  forall x1 x2 y1 y2 : (Complex A),\n    x1 = x2 -> y1 = y2 -> complex_mul x1 y1 = complex_mul x2 y2.\nProof.\n  intros.\n  unfold complex_mul.\n  rewrite H.\n  rewrite H0.\n  reflexivity.\nQed.\n\nLemma complex_add_comm {A} {rops : RingOps A} {sring : SemiRingNoAssoc A} :\n  forall a b : (Complex A), complex_add a b = complex_add b a.\nProof.\n  intros.\n  unfold complex_add.\n  elim a.\n  elim b.\n  intros.\n  f_equal.\n  apply add_comm.\n  apply add_comm.\nQed.\n\nLemma complex_mul_comm {A} {rops : RingOps A} {sring : SemiRingNoAssoc A} :\n  forall a b : (Complex A), complex_mul a b = complex_mul b a.\nProof.\n  intros.\n  unfold complex_mul.\n  elim a.\n  elim b.\n  intros.\n  f_equal.\n  rewrite 2! sub_def.\n  apply add_extensional.\n  apply mul_comm.\n  rewrite mul_comm.\n  reflexivity.\n  rewrite add_comm.\n  apply add_extensional.\n  apply mul_comm.\n  apply mul_comm.\nQed.\n\nLemma complex_add_mul_dist {A} {rops : RingOps A} {ring : Ring A} :\n  forall a b c : (Complex A),\n    complex_mul a (complex_add b c) =\n    complex_add (complex_mul a b) (complex_mul a c).\nProof.\n  intros.\n  unfold complex_mul.\n  unfold complex_add.\n  elim a.\n  elim b.\n  elim c.\n  unfold real_part.\n  unfold imaginary_part.\n  intros.\n  f_equal.\n  rewrite 2! add_mul_dist.\n  rewrite 3! sub_def.\n  rewrite neg_add.\n  rewrite 2! add_assoc.\n  apply add_extensional.\n  rewrite add_comm.\n  rewrite add_assoc.\n  apply add_extensional.\n  apply add_comm.\n  reflexivity.\n  reflexivity.\n  rewrite 2! add_mul_dist.\n  rewrite 2! add_assoc.\n  apply add_extensional.\n  rewrite add_comm.\n  rewrite add_assoc.\n  apply add_extensional.\n  apply add_comm.\n  reflexivity.\n  reflexivity.\nQed.\n\nLemma complex_add_zero {A} {rops : RingOps A} {sring : SemiRingNoAssoc A} :\n  forall a : (Complex A), complex_add a complex_zero = a.\nProof.\n  intros.\n  unfold complex_add.\n  unfold complex_zero.\n  elim a.\n  unfold real_part.\n  unfold imaginary_part.\n  intros.\n  f_equal.\n  apply add_zero_right.\n  apply add_zero_right.\nQed.\n\nLemma complex_mul_zero {A} {rops : RingOps A} {sring : SemiRingNoAssoc A} :\n  forall a : (Complex A), complex_mul a complex_zero = complex_zero.\nProof.\n  intros.\n  unfold complex_mul.\n  unfold complex_zero.\n  elim a.\n  unfold real_part.\n  unfold imaginary_part.\n  intros.\n  f_equal.\n  rewrite 2! mul_zero_right.\n  apply sub_zero.\n  rewrite 2! mul_zero_right.\n  apply add_zero_right.\nQed.\n\nLemma complex_mul_one {A} {rops : RingOps A} {ring : RingNoAssoc A} :\n  forall a : (Complex A), complex_mul a complex_one = a.\nProof.\n  intros.\n  unfold complex_mul.\n  unfold complex_one.\n  elim a.\n  unfold real_part.\n  unfold imaginary_part.\n  intros.\n  f_equal.\n  rewrite mul_zero_right.\n  rewrite sub_def.\n  rewrite zero_self_inv.\n  rewrite add_zero_right.\n  apply mul_one_right.\n  rewrite mul_zero_right.\n  rewrite add_comm.\n  rewrite add_zero_right.\n  apply mul_one_right.\nQed.\n\nInstance ComplexSemiRingNoAssoc A\n  {rops : RingOps A}\n  {ring : Ring A} :\n  SemiRingNoAssoc (Complex A) := {\n  add_extensional := complex_add_extensional;\n  mul_extensional := complex_mul_extensional;\n  add_comm := complex_add_comm;\n  mul_comm := complex_mul_comm;\n  add_mul_dist := complex_add_mul_dist;\n  add_zero_right := complex_add_zero;\n  mul_zero_right := complex_mul_zero;\n  mul_one_right := complex_mul_one\n}.\n\nLemma complex_neg_add {A}\n  {rops : RingOps A}\n  {ring : RingNoAssoc A} :\n    forall a b : (Complex A),\n      complex_neg (complex_add a b) = complex_add (complex_neg a) (complex_neg b).\nProof.\n  intros.\n  unfold complex_neg.\n  unfold complex_add.\n  elim a.\n  elim b.\n  unfold real_part.\n  unfold imaginary_part.\n  intros.\n  f_equal.\n  apply neg_add.\n  apply neg_add.\nQed.\n\nLemma complex_neg_mul {A}\n  {rops : RingOps A}\n  {ring : RingNoAssoc A} :\n    forall a b : (Complex A),\n      complex_neg (complex_mul a b) = complex_mul a (complex_neg b).\nProof.\n  intros.\n  unfold complex_neg.\n  unfold complex_mul.\n  elim a.\n  elim b.\n  unfold real_part.\n  unfold imaginary_part.\n  intros.\n  f_equal.\n  rewrite <- 2! neg_mul.\n  apply neg_sub.\n  rewrite <- 2! neg_mul.\n  apply neg_add.\nQed.\n\nLemma complex_neg_add_inv {A} {rops : RingOps A} {ring : RingNoAssoc A} :\n  forall a : (Complex A), complex_add (complex_neg a) a = complex_zero.\nProof.\n  intro.\n  unfold complex_add.\n  unfold complex_neg.\n  unfold complex_zero.\n  elim a.\n  unfold real_part.\n  unfold imaginary_part.\n  intros.\n  f_equal.\n  rewrite add_comm.\n  rewrite <- sub_def.\n  apply sub_zero.\n  rewrite add_comm.\n  rewrite <- sub_def.\n  apply sub_zero.\nQed.\n\n\nInstance ComplexRingNoAssoc A\n  {rops : RingOps A}\n  {ring : Ring A} :\n  RingNoAssoc (Complex A) := {\n  semiring_no_assoc_r := ComplexSemiRingNoAssoc A;\n  neg_add := complex_neg_add;\n  neg_mul := complex_neg_mul;\n  neg_add_inv := complex_neg_add_inv\n}.\n\nLemma complex_add_assoc {A} {rops : RingOps A} {sring : SemiRing A} :\n  forall a b c : (Complex A),\n    complex_add a (complex_add b c) = complex_add (complex_add a b) c.\nProof.\n  intros.\n  unfold complex_add.\n  elim a.\n  elim b.\n  elim c.\n  intros.\n  f_equal.\n  apply add_assoc.\n  apply add_assoc.\nQed.\n\nLemma complex_mul_assoc {A} {rops : RingOps A} {ring : Ring A} :\n  forall a b c : (Complex A),\n    complex_mul a (complex_mul b c) = complex_mul (complex_mul a b) c.\nProof.\n  intros.\n  unfold complex_mul.\n  elim a.\n  elim b.\n  elim c.\n  unfold real_part.\n  unfold imaginary_part.\n  intros.\n  f_equal.\n  rewrite add_mul_dist.\n  rewrite sub_mul_dist.\n  rewrite 4! mul_assoc at 1.\n  rewrite 2! sub_def at 1.\n  rewrite neg_add.\n  rewrite add_assoc.\n  rewrite add_comm.\n  rewrite <- add_assoc.\n  rewrite <- neg_add.\n  rewrite <- add_mul_dist_right.\n  rewrite add_assoc.\n  rewrite <- sub_def.\n  rewrite add_comm.\n  rewrite <- sub_def.\n  rewrite <- sub_mul_dist_right.\n  reflexivity.\n  rewrite add_mul_dist.\n  rewrite sub_mul_dist.\n  rewrite 4! mul_assoc at 1.\n  rewrite sub_def at 1.\n  rewrite add_assoc.\n  rewrite add_comm.\n  rewrite <- add_assoc.\n  rewrite <- add_mul_dist_right.\n  rewrite add_assoc.\n  apply add_extensional.\n  rewrite add_comm.\n  rewrite <- sub_def.\n  rewrite <- sub_mul_dist_right.\n  reflexivity.\n  reflexivity.\nQed.\n\nInstance ComplexSemiRing A\n  {rops : RingOps A}\n  {ring : Ring A} :\n  SemiRing (Complex A) := {\n  semiring_no_assoc_s := ComplexSemiRingNoAssoc A;\n  add_assoc := complex_add_assoc;\n  mul_assoc := complex_mul_assoc\n}.\n\nInstance ComplexRing A\n  {rops : RingOps A}\n  {ring : Ring A} :\n  Ring (Complex A) := {\n  semiring_r := ComplexSemiRing A;\n  ring_noassoc := ComplexRingNoAssoc A\n}.\n\nFunction complex_recip {A} {rops : FieldOps A} (x : (Complex A)) :=\n  {| real_part :=\n       real_part A x / (real_part A x * real_part A x +\n                        imaginary_part A x *imaginary_part A x);\n     imaginary_part :=\n       - imaginary_part A x / (real_part A x * real_part A x +\n                               imaginary_part A x *imaginary_part A x) |}.\n\nFunction complex_div {A} {rops : FieldOps A} (x y : (Complex A)) :=\n  {| real_part :=\n       (real_part A x * real_part A y +\n        imaginary_part A x * imaginary_part A y) /\n       (real_part A y * real_part A y +\n        imaginary_part A y *imaginary_part A y);\n     imaginary_part :=\n       (real_part A y * imaginary_part A x -\n        real_part A x * imaginary_part A y) /\n       (real_part A y * real_part A y +\n        imaginary_part A y *imaginary_part A y) |}.\n\nInstance ComplexFieldOps A\n  {rops : FieldOps A} :\n  FieldOps (Complex A) := {\n  rops := ComplexRingOps A;\n  div := complex_div;\n  recip := complex_recip\n}.\n\nLemma complex_div_def {A} {rops : FieldOps A} {field : Field A} :\n  forall (x y : Complex A), complex_div x y = complex_mul x (complex_recip y).\nProof.\n  intros.\n  unfold complex_div.\n  unfold complex_recip.\n  unfold complex_mul.\n  elim x.\n  elim y.\n  unfold real_part.\n  unfold imaginary_part.\n  intros.\n  f_equal.\n  rewrite 3! div_def.\n  rewrite 2! mul_assoc.\n  rewrite <- sub_mul_dist_right.\n  rewrite <- neg_mul.\n  rewrite sub_def.\n  rewrite neg_inv.\n  reflexivity.\n  rewrite 3! div_def.\n  rewrite 2! mul_assoc.\n  rewrite <- add_mul_dist_right.\n  f_equal.\n  rewrite add_comm.\n  rewrite <- neg_mul.\n  rewrite mul_comm at 1.\n  apply sub_def.\nQed.\n\nLemma complex_recip_mul_inv {A} {rops : FieldOps A} {field : Field A} :\n  forall a : (Complex A), complex_mul (complex_recip a) a = complex_one.\nProof.\n  intros.\n  rewrite complex_mul_comm.\n  rewrite <- complex_div_def.\n  unfold complex_div.\n  unfold complex_one.\n  elim a.\n  unfold real_part.\n  unfold imaginary_part.\n  intros.\n  f_equal.\n  rewrite div_def.\n  rewrite mul_comm.\n  apply recip_mul_inv.\n  rewrite sub_zero.\n  rewrite div_def.\n  apply mul_zero_left.\nQed.\n\nInstance ComplexFieldAxioms A\n  {rops : FieldOps A}\n  {field : Field A} :\n  FieldAxioms (Complex A) := {\n  div_def := complex_div_def;\n  recip_mul_inv := complex_recip_mul_inv\n}.\n\nInstance ComplexFieldNoAssoc A\n  {fops : FieldOps A}\n  {field : Field A} :\n  FieldNoAssoc (Complex A) := {\n  ring_no_assoc_fna := ComplexRingNoAssoc A;\n  axioms_fna := ComplexFieldAxioms A\n}.\n\nInstance ComplexField A\n  {fops : FieldOps A}\n  {field : Field A} :\n  Field (Complex A) := {\n  ring_f := ComplexRing A;\n  axioms_f := ComplexFieldAxioms A\n}.\n", "meta": {"author": "emc2", "repo": "state-space-model", "sha": "d4d34e8c5cb2e93bfe141313f1c7f8a94805dfb6", "save_path": "github-repos/coq/emc2-state-space-model", "path": "github-repos/coq/emc2-state-space-model/state-space-model-d4d34e8c5cb2e93bfe141313f1c7f8a94805dfb6/New/Complex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6712142876098003}}
{"text": "From QuickChick Require Import QuickChick GenLow GenHigh.\nRequire Import NPeano Omega.\n\nFrom mathcomp Require Import ssreflect ssrnat ssrbool eqtype.\n\nFrom QuickChick.RedBlack Require Import redblack.\n\nRequire Import List String.\nImport ListNotations.\n\nOpen Scope string.\n\nOpen Scope Checker_scope.\n\n(* Red-Black Tree invariant: executable definition *)\n\nFixpoint black_height_bool (t: tree) : option nat :=\n  match t with\n    | Leaf => Some 0\n    | Node c tl _ tr =>\n      let h1 := black_height_bool tl in\n      let h2 := black_height_bool tr in\n      match h1, h2 with\n        | Some n1, Some n2 =>\n          if n1 == n2 then\n            match c with\n              | Black => Some (S n1)\n              | Red => Some n1\n            end\n          else None\n        | _, _ => None\n      end\n  end.\n\nDefinition is_black_balanced (t : tree) : bool :=\n  isSome (black_height_bool t).\n\nFixpoint has_no_red_red (c : color) (t : tree) : bool :=\n  match t with\n    | Leaf => true\n    | Node Red t1 _ t2 =>\n      match c with\n        | Red => false\n        | Black => has_no_red_red Red t1 && has_no_red_red Red t2\n      end\n    | Node Black t1 _ t2 =>\n      has_no_red_red Black t1 && has_no_red_red Black t2\n  end.\n\n(* begin is_redblack_bool *)\nDefinition is_redblack_bool (t : tree) : bool :=\n  is_black_balanced t && has_no_red_red Red t.\n(* end is_redblack_bool *)\n\nFixpoint showColor (c : color) :=\n  match c with\n    | Red => \"Red\"\n    | Black => \"Black\"\n  end.\n\nFixpoint tree_to_string (t : tree) :=\n  match t with\n    | Leaf => \"Leaf\"\n    | Node c l x r => \"Node \" ++ showColor c ++ \" \"\n                            ++ \"(\" ++ tree_to_string l ++ \") \"\n                            ++ show x ++ \" \"\n                            ++ \"(\" ++ tree_to_string r ++ \")\"\n  end.\n\nInstance showTree {A : Type} `{_ : Show A} : Show tree :=\n  {|\n    show t := \"\" (* CH: tree_to_string t causes a 9x increase in runtime *)\n  |}.\n\n(* begin insert_preserves_redblack_checker *)\nDefinition insert_preserves_redblack_checker (genTree : G tree) : Checker :=\n  forAll arbitrary (fun n => forAll genTree (fun t =>\n    is_redblack_bool t ==> is_redblack_bool (insert n t))).\n(* end insert_preserves_redblack_checker *)\n\nImport QcDefaultNotation. Open Scope qc_scope.\n\n(* begin genAnyTree *)\nDefinition genColor := elems [Red; Black].\nFixpoint genAnyTree_depth (d : nat) : G tree :=\n  match d with \n    | 0 => returnGen Leaf\n    | S d' => freq [(1, returnGen Leaf);\n                    (9, liftGen4 Node genColor (genAnyTree_depth d')\n                                     arbitrary (genAnyTree_depth d'))]\n  end.\nDefinition genAnyTree : G tree := sized genAnyTree_depth.\n(* end genAnyTree *)\n\nExtract Constant defSize => \"10\".\n\nDefinition test_naive :=\n  insert_preserves_redblack_checker genAnyTree.\n(* begin QC_naive *)\n(*! QuickChick test_naive. *)\n(* end QC_naive *)\n\n(* gathering some size statistics *)\nFixpoint tree_size (t : tree) : nat :=\n  match t with\n    | Leaf => 1\n    | Node c tl _ tr => 1 + (tree_size tl) + (tree_size tr)\n  end.\n\nDefinition insert_preserves_redblack_checker_size (genTree : G tree) : Checker :=\n  forAll arbitrary (fun n => forAll genTree (fun t =>\n    collect (append \"size \" (show (tree_size t)))\n    (is_redblack_bool t ==> is_redblack_bool (insert n t)))).\n\n(*\nExtract Constant Test.defNumTests => \"100000\".\nQuickChick (insert_preserves_redblack_checker_size genAnyTree).\n*)\n\nModule DoNotation.\nImport ssrfun.\nNotation \"'do!' X <- A ; B\" :=\n  (bindGen A (fun X => B))\n  (at level 200, X ident, A at level 100, B at level 200).\nEnd DoNotation.\nImport DoNotation.\n\nRequire Import Relations Wellfounded Lexicographic_Product.\n\nDefinition ltColor (c1 c2: color) : Prop :=\n  match c1, c2 with\n    | Red, Black => True\n    | _, _ => False\n  end.\n\nLemma well_foulded_ltColor : well_founded ltColor.\nProof.\n  unfold well_founded.\n  intros c; destruct c;\n  repeat (constructor; intros c ?; destruct c; try now (exfalso; auto)).\nQed.\n\nDefinition sigT_of_prod {A B : Type} (p : A * B) : {_ : A & B} :=\n  let (a, b) := p in existT (fun _ : A => B) a b.\n\nDefinition prod_of_sigT {A B : Type} (p : {_ : A & B}) : A * B :=\n  let (a, b) := p in (a, b).\n\n\nDefinition wf_hc (c1 c2 : (nat * color)) : Prop :=\n  lexprod nat (fun _ => color) lt (fun _ => ltColor) (sigT_of_prod c1) (sigT_of_prod c2).\n\nLemma well_founded_hc : well_founded wf_hc.\nProof.\n  unfold wf_hc. apply wf_inverse_image.\n  apply wf_lexprod. now apply Wf_nat.lt_wf. intros _; now apply well_foulded_ltColor.\nQed.\n\nRequire Import Program.Wf. Import WfExtensionality.\nRequire Import FunctionalExtensionality.\n\n(* begin genRBTree_height *)\nProgram Fixpoint genRBTree_height (hc : nat*color) {wf wf_hc hc} : G tree :=\n  match hc with\n  | (0, Red) => returnGen Leaf\n  | (0, Black) => oneOf [returnGen Leaf;\n                    (do! n <- arbitrary; returnGen (Node Red Leaf n Leaf))]\n  | (S h, Red) => liftGen4 Node (returnGen Black) (genRBTree_height (h, Black))\n                                        arbitrary (genRBTree_height (h, Black))\n  | (S h, Black) => do! c' <- genColor;\n                    let h' := match c' with Red => S h | Black => h end in\n                    liftGen4 Node (returnGen c') (genRBTree_height (h', c'))\n                                       arbitrary (genRBTree_height (h', c')) end.\n(* end genRBTree_height *)\nNext Obligation.\n  unfold wf_hc; simpl; left; omega.\nQed.\nNext Obligation.\n  unfold wf_hc; simpl; left; omega.\nQed.\nNext Obligation.\n  unfold wf_hc; simpl; destruct c'; [right; apply I | left; omega].\nQed.\nNext Obligation.\n  unfold wf_hc; simpl; destruct c'; [right; apply I | left; omega].\nQed.\nNext Obligation.\n  abstract (apply well_founded_hc).\nDefined.\n\nLemma genRBTree_height_eq (hc : nat*color) :\n  genRBTree_height hc =\n  match hc with\n  | (0, Red) => returnGen Leaf\n  | (0, Black) => oneOf [returnGen Leaf;\n                    (do! n <- arbitrary; returnGen (Node Red Leaf n Leaf))]\n  | (S h, Red) => liftGen4 Node (returnGen Black) (genRBTree_height (h, Black))\n                                        arbitrary (genRBTree_height (h, Black))\n  | (S h, Black) => do! c' <- genColor;\n                    let h' := match c' with Red => S h | Black => h end in\n                    liftGen4 Node (returnGen c') (genRBTree_height (h', c'))\n                                       arbitrary (genRBTree_height (h', c')) end.\nProof.\n  unfold_sub genRBTree_height (genRBTree_height hc).\n  f_equal. destruct hc as [[|h] [|]]; try reflexivity.\n  f_equal. apply functional_extensionality => [[|]]; reflexivity.\nQed.\n\n(* Hope that this is enough for preventing unfolding genRBTree_height *)\nGlobal Opaque genRBTree_height.\n\n\n(* begin genRBTree *)\nDefinition genRBTree := bindGen arbitrary (fun h => genRBTree_height (h, Red)).\n(* end genRBTree *)\n\nDefinition showDiscards (r : Result) :=\n  match r with\n  | Success ns nd _ _ => \"Success: number of successes \" ++ show (ns-1) ++ newline ++\n                         \"         number of discards \"  ++ show nd ++ newline\n  | _ => show r\n  end.\n\nDefinition testInsert :=\n  showDiscards (quickCheck (insert_preserves_redblack_checker genRBTree)).\n\nExtract Constant defSize => \"10\".\nDefinition test_smart :=\n  (insert_preserves_redblack_checker genRBTree). \n(* begin QC_good *)\n(*! QuickChick test_smart. *)\n(* end QC_good *)\n\n(* gathering some size statistics\nExtract Constant Test.defNumTests => \"100000\".\nQuickChick (insert_preserves_redblack_checker_size genRBTree).\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/QuickChick/examples/RedBlack/testing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6712142876098003}}
{"text": "(************************************************************************\n\n Limits and colimits in the iso-comma category\n\n Contents\n 1. Terminal objects\n 2. Products\n 3. Pullbacks\n 4. Initial objects\n 5. Coproducts\n\n ************************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.CategoryTheory.IsoCommaCategory.\nRequire Import UniMath.CategoryTheory.limits.terminal.\nRequire Import UniMath.CategoryTheory.limits.binproducts.\nRequire Import UniMath.CategoryTheory.limits.pullbacks.\nRequire Import UniMath.CategoryTheory.limits.initial.\nRequire Import UniMath.CategoryTheory.limits.bincoproducts.\nRequire Import UniMath.CategoryTheory.limits.Preservation.\n\nLocal Open Scope cat.\n\nSection IsoCommaLimits.\n  Context {C₁ C₂ C₃ : category}\n          (F : C₁ ⟶ C₃)\n          (G : C₂ ⟶ C₃).\n\n  (**\n   1. Terminal objects\n   *)\n  Section TerminalObject.\n    Context (HF : preserves_terminal F)\n            (HG : preserves_terminal G).\n\n    Definition isTerminal_iso_comma\n               (x : iso_comma F G)\n               (H₁ : isTerminal C₁ (pr11 x))\n               (H₂ : isTerminal C₂ (pr21 x))\n      : isTerminal (iso_comma F G) x.\n    Proof.\n      intros w.\n      use iscontraprop1.\n      - abstract\n          (use invproofirrelevance ;\n           intros φ₁ φ₂ ;\n           use eq_iso_comma_mor ;\n           [ apply (@TerminalArrowEq _ (make_Terminal _ H₁))\n           | apply (@TerminalArrowEq _ (make_Terminal _ H₂)) ]).\n      - refine ((TerminalArrow (_ ,, H₁) (pr11 w)\n                   ,,\n                   TerminalArrow (_ ,, H₂) (pr21 w))\n                  ,,\n                  _).\n        apply (@TerminalArrowEq _ (make_Terminal _ (HG _ H₂))).\n    Defined.\n\n    Definition terminal_category_iso_comma\n               (T₁ : Terminal C₁)\n               (T₂ : Terminal C₂)\n      : Terminal (iso_comma F G).\n    Proof.\n      simple refine (_ ,, _).\n      - refine ((pr1 T₁ ,, pr1 T₂) ,, _) ; cbn.\n        exact (z_iso_Terminals\n                 (make_Terminal _ (HF _ (pr2 T₁)))\n                 (make_Terminal _ (HG _ (pr2 T₂)))).\n      - apply isTerminal_iso_comma.\n        + exact (pr2 T₁).\n        + exact (pr2 T₂).\n    Defined.\n\n    Definition iso_comma_pr1_preserves_terminal\n               (T₁ : Terminal C₁)\n               (T₂ : Terminal C₂)\n      : preserves_terminal (iso_comma_pr1 F G).\n    Proof.\n      apply (preserves_terminal_if_preserves_chosen\n               (terminal_category_iso_comma T₁ T₂)\n               (iso_comma_pr1 F G)).\n      exact (pr2 T₁).\n    Defined.\n\n    Definition iso_comma_pr2_preserves_terminal\n               (T₁ : Terminal C₁)\n               (T₂ : Terminal C₂)\n      : preserves_terminal (iso_comma_pr2 F G).\n    Proof.\n      apply (preserves_terminal_if_preserves_chosen\n               (terminal_category_iso_comma T₁ T₂)\n               (iso_comma_pr2 F G)).\n      exact (pr2 T₂).\n    Defined.\n\n    Definition iso_comma_ump1_preserves_terminal\n               {C₀ : category}\n               (H₁ : C₀ ⟶ C₁)\n               (HH₁ : preserves_terminal H₁)\n               (H₂ : C₀ ⟶ C₂)\n               (HH₂ : preserves_terminal H₂)\n               (α : nat_z_iso (H₁ ∙ F) (H₂ ∙ G))\n      : preserves_terminal (iso_comma_ump1 F G H₁ H₂ α).\n    Proof.\n      intros x Hx.\n      apply isTerminal_iso_comma.\n      - apply HH₁.\n        exact Hx.\n      - apply HH₂.\n        exact Hx.\n    Defined.\n  End TerminalObject.\n\n  (**\n   2. Products\n   *)\n  Section Product.\n    Context (HF : preserves_binproduct F)\n            (HG : preserves_binproduct G).\n\n    Section IsProductInIsoComma.\n      Context {x y z : iso_comma F G}\n              (p₁ : z --> x)\n              (p₂ : z --> y)\n              (H₁ : isBinProduct _ (pr11 x) (pr11 y) (pr11 z) (pr11 p₁) (pr11 p₂))\n              (H₂ : isBinProduct _ (pr21 x) (pr21 y) (pr21 z) (pr21 p₁) (pr21 p₂)).\n\n      Let P₁ : BinProduct C₁ (pr11 x) (pr11 y) := make_BinProduct _ _ _ _ _ _ H₁.\n      Let P₂ : BinProduct C₂ (pr21 x) (pr21 y) := make_BinProduct _ _ _ _ _ _ H₂.\n\n      Section UMP.\n        Context {w : iso_comma F G}\n                (f : w --> x)\n                (g : w --> y).\n\n        Definition isBinProduct_in_iso_comma_unique\n          : isaprop (∑ (fg : w --> z), fg · p₁ = f × fg · p₂ = g).\n        Proof.\n          use invproofirrelevance.\n          intros φ₁ φ₂.\n          use subtypePath.\n          {\n            intro.\n            apply isapropdirprod ; apply homset_property.\n          }\n          use eq_iso_comma_mor.\n          - use (BinProductArrowsEq _ _ _ P₁).\n            + exact (maponpaths (λ z, pr11 z) (pr12 φ₁)\n                     @ !(maponpaths (λ z, pr11 z) (pr12 φ₂))).\n            + exact (maponpaths (λ z, pr11 z) (pr22 φ₁)\n                     @ !(maponpaths (λ z, pr11 z) (pr22 φ₂))).\n          - use (BinProductArrowsEq _ _ _ P₂).\n            + exact (maponpaths (λ z, dirprod_pr2 (pr1 z)) (pr12 φ₁)\n                     @ !(maponpaths (λ z, dirprod_pr2 (pr1 z)) (pr12 φ₂))).\n            + exact (maponpaths (λ z, dirprod_pr2 (pr1 z)) (pr22 φ₁)\n                     @ !(maponpaths (λ z, dirprod_pr2 (pr1 z)) (pr22 φ₂))).\n        Qed.\n\n        Definition isBinProduct_in_iso_comma_ump\n          : w --> z.\n        Proof.\n          simple refine ((_ ,, _) ,, _) ; cbn.\n          - exact (BinProductArrow _ P₁ (pr11 f) (pr11 g)).\n          - exact (BinProductArrow _ P₂ (pr21 f) (pr21 g)).\n          - use (BinProductArrowsEq\n                   _ _ _\n                   (make_BinProduct _ _ _ _ _ _ (HG _ _ _ _ _ (pr2 P₂)))) ; cbn.\n            + abstract\n                (rewrite !assoc' ;\n                 rewrite <- functor_comp ;\n                 rewrite (BinProductPr1Commutes _ _ _ P₂) ;\n                 refine (_ @ pr2 f) ;\n                 refine (!(maponpaths (λ z, _ · z) (pr2 p₁)) @ _) ;\n                 rewrite !assoc ;\n                 rewrite <- functor_comp ;\n                 rewrite (BinProductPr1Commutes _ _ _ P₁) ;\n                 apply idpath).\n            + abstract\n                (rewrite !assoc' ;\n                 rewrite <- functor_comp ;\n                 rewrite (BinProductPr2Commutes _ _ _ P₂) ;\n                 refine (_ @ pr2 g) ;\n                 refine (!(maponpaths (λ z, _ · z) (pr2 p₂)) @ _) ;\n                 rewrite !assoc ;\n                 rewrite <- functor_comp ;\n                 rewrite (BinProductPr2Commutes _ _ _ P₁) ;\n                 apply idpath).\n        Defined.\n\n        Definition isBinProduct_in_iso_comma_ump_pr1\n          : isBinProduct_in_iso_comma_ump · p₁ = f.\n        Proof.\n          use eq_iso_comma_mor ; cbn.\n          - apply (BinProductPr1Commutes _ _ _ P₁).\n          - apply (BinProductPr1Commutes _ _ _ P₂).\n        Qed.\n\n        Definition isBinProduct_in_iso_comma_ump_pr2\n          : isBinProduct_in_iso_comma_ump · p₂ = g.\n        Proof.\n          use eq_iso_comma_mor ; cbn.\n          - apply (BinProductPr2Commutes _ _ _ P₁).\n          - apply (BinProductPr2Commutes _ _ _ P₂).\n        Qed.\n      End UMP.\n\n      Definition isBinProduct_in_iso_comma\n        : isBinProduct (iso_comma F G) x y z p₁ p₂.\n      Proof.\n        intros w f g.\n        use iscontraprop1.\n        - exact (isBinProduct_in_iso_comma_unique f g).\n        - simple refine (_ ,, _ ,, _).\n          + exact (isBinProduct_in_iso_comma_ump f g).\n          + exact (isBinProduct_in_iso_comma_ump_pr1 f g).\n          + exact (isBinProduct_in_iso_comma_ump_pr2 f g).\n      Defined.\n    End IsProductInIsoComma.\n\n    Definition binproducts_in_iso_comma\n               (HC₁ : BinProducts C₁)\n               (HC₂ : BinProducts C₂)\n      : BinProducts (iso_comma F G).\n    Proof.\n      intros x y.\n      pose (FP := make_BinProduct\n                    _ _ _ _ _ _\n                    (HF (pr11 x) (pr11 y)\n                       _\n                       (BinProductPr1 _ (HC₁ (pr11 x) (pr11 y)))\n                       (BinProductPr2 _ (HC₁ (pr11 x) (pr11 y)))\n                       (isBinProduct_BinProduct _ (HC₁ (pr11 x) (pr11 y))))).\n      pose (GP := make_BinProduct\n                    _ _ _ _ _ _\n                    (HG (pr21 x) (pr21 y)\n                       _\n                       (BinProductPr1 _ (HC₂ (pr21 x) (pr21 y)))\n                       (BinProductPr2 _ (HC₂ (pr21 x) (pr21 y)))\n                       (isBinProduct_BinProduct _ (HC₂ (pr21 x) (pr21 y))))).\n      use make_BinProduct.\n      - simple refine ((_ ,, _) ,, _).\n        + exact (BinProductObject _ (HC₁ (pr11 x) (pr11 y))).\n        + exact (BinProductObject _ (HC₂ (pr21 x) (pr21 y))).\n        + exact (binproduct_of_z_iso FP GP (pr2 x) (pr2 y)).\n      - simple refine ((_ ,, _) ,, _).\n        + exact (BinProductPr1 _ (HC₁ (pr11 x) (pr11 y))).\n        + exact (BinProductPr1 _ (HC₂ (pr21 x) (pr21 y))).\n        + exact (!(BinProductOfArrowsPr1 _ GP FP (pr12 x) (pr12 y))).\n      - simple refine ((_ ,, _) ,, _).\n        + exact (BinProductPr2 _ (HC₁ (pr11 x) (pr11 y))).\n        + exact (BinProductPr2 _ (HC₂ (pr21 x) (pr21 y))).\n        + exact (!(BinProductOfArrowsPr2 _ GP FP (pr12 x) (pr12 y))).\n      -  use isBinProduct_in_iso_comma.\n         + apply isBinProduct_BinProduct.\n         + apply isBinProduct_BinProduct.\n    Defined.\n\n    Definition iso_comma_pr1_preserves_binproduct\n               (HC₁ : BinProducts C₁)\n               (HC₂ : BinProducts C₂)\n      : preserves_binproduct (iso_comma_pr1 F G).\n    Proof.\n      use preserves_binproduct_if_preserves_chosen.\n      - apply binproducts_in_iso_comma.\n        + exact HC₁.\n        + exact HC₂.\n      - intros x y.\n        cbn.\n        apply isBinProduct_BinProduct.\n    Defined.\n\n    Definition iso_comma_pr2_preserves_binproduct\n               (HC₁ : BinProducts C₁)\n               (HC₂ : BinProducts C₂)\n      : preserves_binproduct (iso_comma_pr2 F G).\n    Proof.\n      use preserves_binproduct_if_preserves_chosen.\n      - apply binproducts_in_iso_comma.\n        + exact HC₁.\n        + exact HC₂.\n      - intros x y.\n        cbn.\n        apply isBinProduct_BinProduct.\n    Defined.\n\n    Definition iso_comma_ump1_preserves_binproduct\n               {C₀ : category}\n               (H₁ : C₀ ⟶ C₁)\n               (HH₁ : preserves_binproduct H₁)\n               (H₂ : C₀ ⟶ C₂)\n               (HH₂ : preserves_binproduct H₂)\n               (α : nat_z_iso (H₁ ∙ F) (H₂ ∙ G))\n      : preserves_binproduct (iso_comma_ump1 F G H₁ H₂ α).\n    Proof.\n      intros x y z π₁ π₂ Hx.\n      apply isBinProduct_in_iso_comma.\n      - apply HH₁.\n        exact Hx.\n      - apply HH₂.\n        exact Hx.\n    Defined.\n  End Product.\n\n  (**\n   3. Pullbacks\n   *)\n  Section Pullbacks.\n    Context (HF : preserves_pullback F)\n            (HG : preserves_pullback G).\n\n    Section IsPullbackIsoComma.\n      Context {pb x y z : iso_comma F G}\n              (f : x --> z)\n              (g : y --> z)\n              (π₁ : pb --> x)\n              (π₂ : pb --> y)\n              (sqr₁ : pr11 π₁ · pr11 f = pr11 π₂ · pr11 g)\n              (H₁ : isPullback sqr₁)\n              (sqr₂ : pr21 π₁ · pr21 f = pr21 π₂ · pr21 g)\n              (H₂ : isPullback sqr₂)\n              (sqr₃ : π₁ · f = π₂ · g).\n\n      Let P₁ : Pullback (pr11 f) (pr11 g) := make_Pullback _ H₁.\n      Let P₂ : Pullback (pr21 f) (pr21 g) := make_Pullback _ H₂.\n\n      Section UMP.\n        Context {w : iso_comma F G}\n                (h₁ : w --> x)\n                (h₂ : w --> y)\n                (p : h₁ · f = h₂ · g).\n\n        Definition isPullback_iso_comma_unique\n          : isaprop (∑ (hk : w --> pb), hk · π₁ = h₁ × hk · π₂ = h₂).\n        Proof.\n          use invproofirrelevance.\n          intros φ₁ φ₂.\n          use subtypePath.\n          {\n            intro.\n            apply isapropdirprod ; apply homset_property.\n          }\n          use eq_iso_comma_mor.\n          - use (MorphismsIntoPullbackEqual H₁).\n            + refine (maponpaths (λ z, pr11 z) (pr12 φ₁) @ _).\n              exact (!(maponpaths (λ z, pr11 z) (pr12 φ₂))).\n            + refine (maponpaths (λ z, pr11 z) (pr22 φ₁) @ _).\n              exact (!(maponpaths (λ z, pr11 z) (pr22 φ₂))).\n          - use (MorphismsIntoPullbackEqual H₂).\n            + refine (maponpaths (λ z, dirprod_pr2 (pr1 z)) (pr12 φ₁) @ _).\n              exact (!(maponpaths (λ z, dirprod_pr2 (pr1 z)) (pr12 φ₂))).\n            + refine (maponpaths (λ z, dirprod_pr2 (pr1 z)) (pr22 φ₁) @ _).\n              exact (!(maponpaths (λ z, dirprod_pr2 (pr1 z)) (pr22 φ₂))).\n        Qed.\n\n        Definition isPullback_iso_comma_mor\n          : w --> pb.\n        Proof.\n          simple refine ((_ ,, _) ,, _).\n          - refine (PullbackArrow P₁ _ (pr11 h₁) (pr11 h₂) _).\n            abstract (exact (maponpaths (λ z, pr11 z) p)).\n          - refine (PullbackArrow P₂ _ (pr21 h₁) (pr21 h₂) _).\n            abstract (exact (maponpaths (λ z, dirprod_pr2 (pr1 z)) p)).\n          - use (MorphismsIntoPullbackEqual (HG _ _ _ _ _ _ _ _ _ _ (pr22 P₂))).\n            + abstract\n                (rewrite <- !functor_comp ;\n                 apply maponpaths ;\n                 exact (PullbackSqrCommutes P₂)).\n            + abstract\n                (cbn ;\n                 rewrite !assoc' ;\n                 rewrite <- !functor_comp ;\n                 rewrite (PullbackArrow_PullbackPr1 P₂) ;\n                 refine (_ @ pr2 h₁) ;\n                 rewrite <- (pr2 π₁) ;\n                 rewrite !assoc ;\n                 apply maponpaths_2 ;\n                 rewrite <- !functor_comp ;\n                 apply maponpaths ;\n                 apply (PullbackArrow_PullbackPr1 P₁)).\n            + abstract\n                (cbn ;\n                 rewrite !assoc' ;\n                 rewrite <- !functor_comp ;\n                 rewrite (PullbackArrow_PullbackPr2 P₂) ;\n                 refine (_ @ pr2 h₂) ;\n                 rewrite <- (pr2 π₂) ;\n                 rewrite !assoc ;\n                 apply maponpaths_2 ;\n                 rewrite <- !functor_comp ;\n                 apply maponpaths ;\n                 apply (PullbackArrow_PullbackPr2 P₁)).\n        Defined.\n\n        Definition isPullback_iso_comma_mor_pr1\n          : isPullback_iso_comma_mor · π₁ = h₁.\n        Proof.\n          use eq_iso_comma_mor.\n          - apply (PullbackArrow_PullbackPr1 P₁).\n          - apply (PullbackArrow_PullbackPr1 P₂).\n        Qed.\n\n        Definition isPullback_iso_comma_mor_pr2\n          : isPullback_iso_comma_mor · π₂ = h₂.\n        Proof.\n          use eq_iso_comma_mor.\n          - apply (PullbackArrow_PullbackPr2 P₁).\n          - apply (PullbackArrow_PullbackPr2 P₂).\n        Qed.\n      End UMP.\n\n      Definition isPullback_iso_comma\n        : isPullback sqr₃.\n      Proof.\n        intros w h₁ h₂ p.\n        use iscontraprop1.\n        - apply isPullback_iso_comma_unique.\n        - simple refine (_ ,, _ ,, _).\n          + exact (isPullback_iso_comma_mor h₁ h₂ p).\n          + exact (isPullback_iso_comma_mor_pr1 h₁ h₂ p).\n          + exact (isPullback_iso_comma_mor_pr2 h₁ h₂ p).\n      Defined.\n    End IsPullbackIsoComma.\n\n    Definition pullbacks_in_iso_comma\n               (HC₁ : Pullbacks C₁)\n               (HC₂ : Pullbacks C₂)\n      : Pullbacks (iso_comma F G).\n    Proof.\n      intros z x y f g.\n      simple refine ((_ ,, _ ,, _) ,, (_ ,, _)).\n      - simple refine ((_ ,, _) ,, _).\n        + exact (PullbackObject (HC₁ _ _ _ (pr11 f) (pr11 g))).\n        + exact (PullbackObject (HC₂ _ _ _ (pr21 f) (pr21 g))).\n        + use (iso_between_pullbacks\n                 _ _\n                 (HF _ _ _ _ _ _ _ _ _ _\n                    (isPullback_Pullback (HC₁ _ _ _ (pr11 f) (pr11 g))))\n                 (HG _ _ _ _ _ _ _ _ _ _\n                    (isPullback_Pullback (HC₂ _ _ _ (pr21 f) (pr21 g))))).\n          * abstract\n              (rewrite <- !functor_comp ;\n               apply maponpaths ;\n               apply PullbackSqrCommutes).\n          * abstract\n              (rewrite <- !functor_comp ;\n               apply maponpaths ;\n               apply PullbackSqrCommutes).\n          * exact (pr2 x).\n          * exact (pr2 y).\n          * exact (pr2 z).\n          * exact (!(pr2 f)).\n          * exact (!(pr2 g)).\n      - simple refine ((_ ,, _) ,, _).\n        + apply PullbackPr1.\n        + apply PullbackPr1.\n        + abstract\n            (cbn ; unfold iso_between_pullbacks_map ;\n             refine (!_) ;\n             apply (PullbackArrow_PullbackPr1\n                      (make_Pullback\n                         _\n                         (HG _ _ _ _ _ _ _ _ _ _\n                            (isPullback_Pullback (HC₂ _ _ _ (pr21 f) (pr21 g))))))).\n      - simple refine ((_ ,, _) ,, _).\n        + apply PullbackPr2.\n        + apply PullbackPr2.\n        + abstract\n            (cbn ; unfold iso_between_pullbacks_map ;\n             refine (!_) ;\n             apply (PullbackArrow_PullbackPr2\n                      (make_Pullback\n                         _\n                         (HG _ _ _ _ _ _ _ _ _ _\n                            (isPullback_Pullback (HC₂ _ _ _ (pr21 f) (pr21 g))))))).\n      - abstract\n          (use eq_iso_comma_mor ; cbn ;\n           [ apply PullbackSqrCommutes\n           | apply PullbackSqrCommutes ]).\n      - use isPullback_iso_comma.\n        + apply PullbackSqrCommutes.\n        + apply isPullback_Pullback.\n        + apply PullbackSqrCommutes.\n        + apply isPullback_Pullback.\n    Defined.\n\n    Definition iso_comma_pr1_preserves_pullback\n               (HC₁ : Pullbacks C₁)\n               (HC₂ : Pullbacks C₂)\n      : preserves_pullback (iso_comma_pr1 F G).\n    Proof.\n      use preserves_pullback_if_preserves_chosen.\n      - apply pullbacks_in_iso_comma.\n        + exact HC₁.\n        + exact HC₂.\n      - intros x y z f g.\n        cbn.\n        apply isPullback_Pullback.\n    Defined.\n\n    Definition iso_comma_pr2_preserves_pullback\n               (HC₁ : Pullbacks C₁)\n               (HC₂ : Pullbacks C₂)\n      : preserves_pullback (iso_comma_pr2 F G).\n    Proof.\n      use preserves_pullback_if_preserves_chosen.\n      - apply pullbacks_in_iso_comma.\n        + exact HC₁.\n        + exact HC₂.\n      - intros x y z f g.\n        cbn.\n        apply isPullback_Pullback.\n    Defined.\n\n    Definition iso_comma_ump1_preserves_pullback\n               {C₀ : category}\n               (H₁ : C₀ ⟶ C₁)\n               (HH₁ : preserves_pullback H₁)\n               (H₂ : C₀ ⟶ C₂)\n               (HH₂ : preserves_pullback H₂)\n               (α : nat_z_iso (H₁ ∙ F) (H₂ ∙ G))\n      : preserves_pullback\n          (iso_comma_ump1 F G H₁ H₂ α).\n    Proof.\n      intros w x y z f g π₁ π₂ p₁ p₂ H.\n      use isPullback_iso_comma ; cbn.\n      - abstract\n          (rewrite <- !functor_comp ;\n           apply maponpaths ;\n           exact p₁).\n      - exact (HH₁ _ _ _ _ _ _ _ _ _ _ H).\n      - abstract\n          (rewrite <- !functor_comp ;\n           apply maponpaths ;\n           exact p₁).\n      - exact (HH₂ _ _ _ _ _ _ _ _ _ _ H).\n    Defined.\n  End Pullbacks.\n\n  (**\n   4. Initial objects\n   *)\n  Section InitialObject.\n    Context (HF : preserves_initial F)\n            (HG : preserves_initial G).\n\n    Definition isInitial_iso_comma\n               (x : iso_comma F G)\n               (H₁ : isInitial C₁ (pr11 x))\n               (H₂ : isInitial C₂ (pr21 x))\n      : isInitial (iso_comma F G) x.\n    Proof.\n      intros w.\n      use iscontraprop1.\n      - abstract\n          (use invproofirrelevance ;\n           intros φ₁ φ₂ ;\n           use eq_iso_comma_mor ;\n           [ apply (@InitialArrowEq _ (make_Initial _ H₁))\n           | apply (@InitialArrowEq _ (make_Initial _ H₂)) ]).\n      - refine ((InitialArrow (_ ,, H₁) (pr11 w)\n                 ,,\n                 InitialArrow (_ ,, H₂) (pr21 w))\n                ,,\n                _).\n        apply (@InitialArrowEq _ (make_Initial _ (HF _ H₁))).\n    Defined.\n\n    Definition initial_category_iso_comma\n               (I₁ : Initial C₁)\n               (I₂ : Initial C₂)\n      : Initial (iso_comma F G).\n    Proof.\n      simple refine (_ ,, _).\n      - refine ((pr1 I₁ ,, pr1 I₂) ,, _) ; cbn.\n        exact (ziso_Initials\n                 (make_Initial _ (HF _ (pr2 I₁)))\n                 (make_Initial _ (HG _ (pr2 I₂)))).\n      - apply isInitial_iso_comma.\n        + exact (pr2 I₁).\n        + exact (pr2 I₂).\n    Defined.\n\n    Definition iso_comma_pr1_preserves_initial\n               (I₁ : Initial C₁)\n               (I₂ : Initial C₂)\n      : preserves_initial (iso_comma_pr1 F G).\n    Proof.\n      apply (preserves_initial_if_preserves_chosen\n               (initial_category_iso_comma I₁ I₂)\n               (iso_comma_pr1 F G)).\n      exact (pr2 I₁).\n    Defined.\n\n    Definition iso_comma_pr2_preserves_initial\n               (I₁ : Initial C₁)\n               (I₂ : Initial C₂)\n      : preserves_initial (iso_comma_pr2 F G).\n    Proof.\n      apply (preserves_initial_if_preserves_chosen\n               (initial_category_iso_comma I₁ I₂)\n               (iso_comma_pr2 F G)).\n      exact (pr2 I₂).\n    Defined.\n\n    Definition iso_comma_ump1_preserves_initial\n               {C₀ : category}\n               (H₁ : C₀ ⟶ C₁)\n               (HH₁ : preserves_initial H₁)\n               (H₂ : C₀ ⟶ C₂)\n               (HH₂ : preserves_initial H₂)\n               (α : nat_z_iso (H₁ ∙ F) (H₂ ∙ G))\n      : preserves_initial (iso_comma_ump1 F G H₁ H₂ α).\n    Proof.\n      intros x Hx.\n      apply isInitial_iso_comma.\n      - apply HH₁.\n        exact Hx.\n      - apply HH₂.\n        exact Hx.\n    Defined.\n  End InitialObject.\n\n  (**\n   5. Coproducts\n   *)\n  Section Coproduct.\n    Context (HF : preserves_bincoproduct F)\n            (HG : preserves_bincoproduct G).\n\n    Section IsCoproductInIsoComma.\n      Context {x y z : iso_comma F G}\n              (i₁ : x --> z)\n              (i₂ : y --> z)\n              (H₁ : isBinCoproduct _ (pr11 x) (pr11 y) (pr11 z) (pr11 i₁) (pr11 i₂))\n              (H₂ : isBinCoproduct _ (pr21 x) (pr21 y) (pr21 z) (pr21 i₁) (pr21 i₂)).\n\n      Let P₁ : BinCoproduct (pr11 x) (pr11 y) := make_BinCoproduct _ _ _ _ _ _ H₁.\n      Let P₂ : BinCoproduct (pr21 x) (pr21 y) := make_BinCoproduct _ _ _ _ _ _ H₂.\n\n      Section UMP.\n        Context {w : iso_comma F G}\n                (f : x --> w)\n                (g : y --> w).\n\n        Definition isBinCoproduct_in_iso_comma_unique\n          : isaprop (∑ (fg : z --> w), i₁ · fg = f × i₂ · fg = g).\n        Proof.\n          use invproofirrelevance.\n          intros φ₁ φ₂.\n          use subtypePath.\n          {\n            intro.\n            apply isapropdirprod ; apply homset_property.\n          }\n          use eq_iso_comma_mor.\n          - use (BinCoproductArrowsEq _ _ _ P₁).\n            + exact (maponpaths (λ z, pr11 z) (pr12 φ₁)\n                     @ !(maponpaths (λ z, pr11 z) (pr12 φ₂))).\n            + exact (maponpaths (λ z, pr11 z) (pr22 φ₁)\n                     @ !(maponpaths (λ z, pr11 z) (pr22 φ₂))).\n          - use (BinCoproductArrowsEq _ _ _ P₂).\n            + exact (maponpaths (λ z, dirprod_pr2 (pr1 z)) (pr12 φ₁)\n                     @ !(maponpaths (λ z, dirprod_pr2 (pr1 z)) (pr12 φ₂))).\n            + exact (maponpaths (λ z, dirprod_pr2 (pr1 z)) (pr22 φ₁)\n                     @ !(maponpaths (λ z, dirprod_pr2 (pr1 z)) (pr22 φ₂))).\n        Qed.\n\n        Definition isBinCoproduct_in_iso_comma_ump\n          : z --> w.\n        Proof.\n          simple refine ((_ ,, _) ,, _) ; cbn.\n          - exact (BinCoproductArrow P₁ (pr11 f) (pr11 g)).\n          - exact (BinCoproductArrow P₂ (pr21 f) (pr21 g)).\n          - use (BinCoproductArrowsEq\n                     _ _ _\n                     (make_BinCoproduct _ _ _ _ _ _ (HF _ _ _ _ _ (pr2 P₁)))) ; cbn.\n            + abstract\n                (rewrite !assoc ;\n                 rewrite <- functor_comp ;\n                 rewrite (BinCoproductIn1Commutes _ _ _ P₁) ;\n                 refine (pr2 f @ _) ;\n                 refine (_ @ maponpaths (λ z, z · _) (!(pr2 i₁))) ;\n                 rewrite !assoc' ;\n                 apply maponpaths ;\n                 rewrite <- functor_comp ;\n                 apply maponpaths ;\n                 refine (!_) ;\n                 apply (BinCoproductIn1Commutes _ _ _ P₂)).\n            + abstract\n                (rewrite !assoc ;\n                 rewrite <- functor_comp ;\n                 rewrite (BinCoproductIn2Commutes _ _ _ P₁) ;\n                 refine (pr2 g @ _) ;\n                 refine (_ @ maponpaths (λ z, z · _) (!(pr2 i₂))) ;\n                 rewrite !assoc' ;\n                 apply maponpaths ;\n                 rewrite <- functor_comp ;\n                 apply maponpaths ;\n                 refine (!_) ;\n                 apply (BinCoproductIn2Commutes _ _ _ P₂)).\n        Defined.\n\n        Definition isBinCoproduct_in_iso_comma_ump_in1\n          : i₁ · isBinCoproduct_in_iso_comma_ump = f.\n        Proof.\n          use eq_iso_comma_mor ; cbn.\n          - apply (BinCoproductIn1Commutes _ _ _ P₁).\n          - apply (BinCoproductIn1Commutes _ _ _ P₂).\n        Qed.\n\n        Definition isBinCoproduct_in_iso_comma_ump_in2\n          : i₂ · isBinCoproduct_in_iso_comma_ump  = g.\n        Proof.\n          use eq_iso_comma_mor ; cbn.\n          - apply (BinCoproductIn2Commutes _ _ _ P₁).\n          - apply (BinCoproductIn2Commutes _ _ _ P₂).\n        Qed.\n      End UMP.\n\n      Definition isBinCoproduct_in_iso_comma\n        : isBinCoproduct (iso_comma F G) x y z i₁ i₂.\n      Proof.\n        intros w f g.\n        use iscontraprop1.\n        - exact (isBinCoproduct_in_iso_comma_unique f g).\n        - simple refine (_ ,, _ ,, _).\n          + exact (isBinCoproduct_in_iso_comma_ump f g).\n          + exact (isBinCoproduct_in_iso_comma_ump_in1 f g).\n          + exact (isBinCoproduct_in_iso_comma_ump_in2 f g).\n      Defined.\n    End IsCoproductInIsoComma.\n\n    Definition bincoproducts_in_iso_comma\n               (HC₁ : BinCoproducts C₁)\n               (HC₂ : BinCoproducts C₂)\n      : BinCoproducts (iso_comma F G).\n    Proof.\n      intros x y.\n      pose (FP := make_BinCoproduct\n                    _ _ _ _ _ _\n                    (HF (pr11 x) (pr11 y)\n                       _\n                       (BinCoproductIn1 (HC₁ (pr11 x) (pr11 y)))\n                       (BinCoproductIn2 (HC₁ (pr11 x) (pr11 y)))\n                       (isBinCoproduct_BinCoproduct _ (HC₁ (pr11 x) (pr11 y))))).\n      pose (GP := make_BinCoproduct\n                    _ _ _ _ _ _\n                    (HG (pr21 x) (pr21 y)\n                       _\n                       (BinCoproductIn1 (HC₂ (pr21 x) (pr21 y)))\n                       (BinCoproductIn2 (HC₂ (pr21 x) (pr21 y)))\n                       (isBinCoproduct_BinCoproduct _ (HC₂ (pr21 x) (pr21 y))))).\n      use make_BinCoproduct.\n      - simple refine ((_ ,, _) ,, _).\n        + exact (BinCoproductObject (HC₁ (pr11 x) (pr11 y))).\n        + exact (BinCoproductObject (HC₂ (pr21 x) (pr21 y))).\n        + exact (bincoproduct_of_z_iso FP GP (pr2 x) (pr2 y)).\n      - simple refine ((_ ,, _) ,, _).\n        + exact (BinCoproductIn1 (HC₁ (pr11 x) (pr11 y))).\n        + exact (BinCoproductIn1 (HC₂ (pr21 x) (pr21 y))).\n        + exact ((BinCoproductOfArrowsIn1 _ FP GP (pr12 x) (pr12 y))).\n      - simple refine ((_ ,, _) ,, _).\n        + exact (BinCoproductIn2 (HC₁ (pr11 x) (pr11 y))).\n        + exact (BinCoproductIn2 (HC₂ (pr21 x) (pr21 y))).\n        + exact ((BinCoproductOfArrowsIn2 _ FP GP (pr12 x) (pr12 y))).\n      -  use isBinCoproduct_in_iso_comma.\n         + apply isBinCoproduct_BinCoproduct.\n         + apply isBinCoproduct_BinCoproduct.\n    Defined.\n\n    Definition iso_comma_pr1_preserves_bincoproduct\n               (HC₁ : BinCoproducts C₁)\n               (HC₂ : BinCoproducts C₂)\n      : preserves_bincoproduct (iso_comma_pr1 F G).\n    Proof.\n      use preserves_bincoproduct_if_preserves_chosen.\n      - apply bincoproducts_in_iso_comma.\n        + exact HC₁.\n        + exact HC₂.\n      - intros x y.\n        cbn.\n        apply isBinCoproduct_BinCoproduct.\n    Defined.\n\n    Definition iso_comma_pr2_preserves_bincoproduct\n               (HC₁ : BinCoproducts C₁)\n               (HC₂ : BinCoproducts C₂)\n      : preserves_bincoproduct (iso_comma_pr2 F G).\n    Proof.\n      use preserves_bincoproduct_if_preserves_chosen.\n      - apply bincoproducts_in_iso_comma.\n        + exact HC₁.\n        + exact HC₂.\n      - intros x y.\n        cbn.\n        apply isBinCoproduct_BinCoproduct.\n    Defined.\n\n    Definition iso_comma_ump1_preserves_bincoproduct\n               {C₀ : category}\n               (H₁ : C₀ ⟶ C₁)\n               (HH₁ : preserves_bincoproduct H₁)\n               (H₂ : C₀ ⟶ C₂)\n               (HH₂ : preserves_bincoproduct H₂)\n               (α : nat_z_iso (H₁ ∙ F) (H₂ ∙ G))\n      : preserves_bincoproduct (iso_comma_ump1 F G H₁ H₂ α).\n    Proof.\n      intros x y z π₁ π₂ Hx.\n      apply isBinCoproduct_in_iso_comma.\n      - apply HH₁.\n        exact Hx.\n      - apply HH₂.\n        exact Hx.\n    Defined.\n  End Coproduct.\nEnd IsoCommaLimits.\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/limits/Examples/IsoCommaLimits.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6712142852961068}}
{"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\nDefinition app_split { X : Type } (l1 l2 r1 r2 : list X) : \n   l1++r1 = l2++r2 -> (exists m, l2 = l1++m /\\ r1 = m++r2) \n                   \\/ (exists m, l1 = l2++m /\\ r2 = m++r1).\nProof.\n  revert l2 r1 r2.\n  induction l1 as [ | x l1 Hl1 ].\n  left; exists l2; auto.\n  intros [ | y l2 ] r1 r2 H.\n  right; exists (x::l1); auto.\n  simpl in H; injection H; clear H; intros H ?; subst.\n  apply Hl1 in H.\n  destruct H as [ (m & H1 & H2) | (m & H1 & H2) ].\n  left; exists m; subst; auto.\n  right; exists m; subst; auto.\nQed.\n", "meta": {"author": "DmxLarchey", "repo": "PC19", "sha": "0481befc4f7b57679000a0d6ae29940532f55026", "save_path": "github-repos/coq/DmxLarchey-PC19", "path": "github-repos/coq/DmxLarchey-PC19/PC19-0481befc4f7b57679000a0d6ae29940532f55026/utils/list_app.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.671214282774766}}
{"text": "Require Import ssreflect ssrfun ssrbool eqtype seq.\nRequire Import FunctionalExtensionality.\nRequire Import Coq.Logic.ProofIrrelevance.\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits. \n\n(** * Basic Category Theory *)\n\n(*************************************************)\n(** ** Categories                                *)\n(*************************************************)\n\nModule Category.\n\nSection RawMixin.\n\n(** ** A category over objects of type 'T'. *)\n\nRecord mixin_of (T : Type) := Mixin {\n  mx_hom : forall a b : T, Type;    (** hom-sets *)\n  (** we have an identity arrow at all types*)\n  mx_id : forall a : T, mx_hom a a; \n  (** composition of arrows *)\n  mx_comp : forall a b c (f : mx_hom b c) (g : mx_hom a b), mx_hom a c;\n  _ : forall a b (g : mx_hom a b), mx_comp (mx_id b) g = g;\n  _ : forall a b (f : mx_hom a b), mx_comp f (mx_id a) = f;\n  _ : forall a b c d (f : mx_hom c d) (g : mx_hom b c) (h : mx_hom a b),\n        mx_comp f (mx_comp g h) = mx_comp (mx_comp f g) h\n}.\n\nEnd RawMixin.\n\nSection ClassDef.\nLocal Notation tp := Type.\n\nRecord class_of T := Class {mixin : mixin_of T}.\n\nStructure type : Type := Pack {sort : tp; _ : class_of sort; _ : tp}.\nLocal Coercion sort : type >-> Sortclass.\n\nVariables (T : tp) (cT : type).\nDefinition class := let: Pack _ c _ as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c T.\n\n(* produce a category type out of the mixin *)\n(* equalize m0 and m by means of a phantom *)\nDefinition pack (m0 : mixin_of T) := \n  fun m & phant_id m0 m => Pack (@Class T m) T.\n\nDefinition hom := mx_hom (mixin class).\nDefinition ida := mx_id (mixin class).\nDefinition comp := @mx_comp cT (mixin class).\n\nEnd ClassDef.\n\nModule Exports.\nCoercion sort : type >-> Sortclass.\nNotation category := Category.type.\nNotation CategoryMixin := Category.Mixin.\nNotation Category T m := (@pack T _ m id).\n\nNotation \"[ 'category' 'of' T 'for' cT ]\" := (@clone T cT _ id)\n  (at level 0, format \"[ 'category'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'category' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'category'  'of'  T ]\") : form_scope.\n\nNotation hom := Category.hom.\nNotation ida := Category.ida.\nNotation comp := Category.comp.\n\nArguments Category.hom [cT] a b.\nArguments Category.ida [cT a].\nArguments Category.comp [cT a b c] _ _.\nPrenex Implicits Category.comp Category.ida Category.hom.\n\nSection Laws.\nVariable C : category.\n\nLemma id_left (a b : C) (g : hom a b) : comp ida g = g.\nProof. by case: C a b g=> ?; case; case. Qed.\n\nLemma id_right (a b : C) (f : hom a b) : comp f ida = f.\nProof. by case: C a b f=> ?; case; case. Qed.\n\nLemma comp_assoc (a b c d : C) (f : hom c d) (g : hom b c) (h : hom a b) :\n  comp f (comp g h) = comp (comp f g) h.\nProof. by case: C a b c d f g h=> ?; case; case. Qed.\n\nEnd Laws.\n\nHint Resolve id_left id_right comp_assoc.\n\nEnd Exports.\n\nEnd Category.\n\nExport Category.Exports.\n\n(*************************************************)\n(** ** Some Categories                           *)\n(*************************************************)\n\n(** *** Category of Coq [Type]s *)\n\nSection Coq.\nNotation tp := (Type).\nProgram Definition coqCategoryMixin := \n  @Category.Mixin tp (fun A B => A -> B)\n      (fun A (a : A) => a) \n      (fun A B C (f : B -> C) (g : A -> B) => f \\o g)\n      _ _ _.\nDefinition Coq : category := \n  Eval hnf in Category tp coqCategoryMixin.\nEnd Coq.\n\n(*************************************************)\n(** ** Functors                                  *)\n(*************************************************)\n\nModule Functor.\n\nSection RawMixin.\n\nRecord mixin_of (C D : category) := Mixin {\n  mx_fobj : forall a : C, D;\n  mx_fmap : forall (a b : C) (f : hom a b), hom (mx_fobj a) (mx_fobj b);\n  _ : forall a : C, mx_fmap (ida (a:=a)) = ida (a:=mx_fobj a);\n  _ : forall (a b c : C) (f : hom b c) (g : hom a b),\n        mx_fmap (comp f g) = comp (mx_fmap f) (mx_fmap g)\n}.\n\nEnd RawMixin.\n\nSection ClassDef.\n\nVariables C D : category.\n\nRecord class_of C D := Class {mixin : mixin_of C D}.\n\nStructure type : Type := Pack {_ : class_of C D}.\n\nVariables cT : type.\nDefinition class := let: Pack c := cT return class_of C D in c.\nDefinition clone c of phant_id class c := @Pack c.\n\nDefinition pack (m0 : mixin_of C D) := \n  fun m & phant_id m0 m => Pack (@Class C D m).\n\nDefinition fobj := mx_fobj (mixin class).\nDefinition fmap := mx_fmap (mixin class).\n\nEnd ClassDef.\n\nModule Exports.\nNotation functor := Functor.type.\nNotation FunctorMixin := Functor.Mixin.\nNotation Functor C D m := (@pack C D _ m id).\n\nNotation \"[ 'functor' 'of' C D 'for' cT ]\" := (@clone C D cT _ id)\n  (at level 0, format \"[ 'functor'  'of'  C  D  'for'  cT ]\") : form_scope.\nNotation \"[ 'functor' 'of' C D ]\" := (@clone C D _ _ id)\n  (at level 0, format \"[ 'functor'  'of'  C  D ]\") : form_scope.\n\nNotation fobj := Functor.fobj.\nNotation fmap := Functor.fmap.\n\nArguments Functor.fobj [C D] cT _.\nArguments Functor.fmap [C D] cT [a b] _.\n\nSection Laws.\nVariables C D : category.\nVariable F : functor C D.\n\nLemma fmap_id (a : C) : fmap F (ida (a:=a)) = ida.\nProof. by case: F; case; case. Qed.\n\nLemma fmap_assoc (a b c : C) (f : hom b c) (g : hom a b) :\n  fmap F (comp f g) = comp (fmap F f) (fmap F g).\nProof. by case: F; case; case. Qed.\n \nEnd Laws.\n\nHint Resolve fmap_id fmap_assoc.\n\nEnd Exports.\n\nEnd Functor.\n\nExport Functor.Exports.\n\n(*************************************************)\n(** ** Some Functors                             *)\n(*************************************************)\n\n(** *** T -> Option T *)\n\nSection OptionFunctor.\nNotation tp := (option).\nProgram Definition optionFunctorMixin := \n  @Functor.Mixin Coq Coq tp \n    (fun _ _ f o => if o is Some v then Some (f v)\n                    else None) _ _.\nNext Obligation. by extensionality x; case: x. Qed.\nNext Obligation. by extensionality x; case: x. Qed.\nCanonical optionFunctor : functor Coq Coq := \n  Eval hnf in Functor Coq Coq optionFunctorMixin.\nEnd OptionFunctor.\n\n(** *** T -> List T *)\n\nSection ListFunctor.\nNotation tp := (list).\nProgram Definition listFunctorMixin := \n  @Functor.Mixin Coq Coq tp (fun _ _ f l => map f l) _ _.\nNext Obligation. by extensionality x; elim: x=> // ? l /= ->. Qed.\nNext Obligation. by extensionality x; elim: x=> // ? l /= ->. Qed.\nCanonical listFunctor : functor Coq Coq := \n  Eval hnf in Functor Coq Coq listFunctorMixin.\nEnd ListFunctor.\n\n(** *** hom(A,--) *)\n\nSection HomFunctor.\nVariable C : category.\nVariable a : C.\nNotation tp := (fun r => hom a r).\nProgram Definition homFunctorMixin := \n  @Functor.Mixin C Coq tp (fun _ _ f g => comp f g) _ _.\nNext Obligation. by extensionality x; rewrite id_left. Qed.\nNext Obligation. by extensionality x; rewrite -comp_assoc. Qed.\nCanonical homFunctor : functor C Coq := \n  Eval hnf in Functor C Coq homFunctorMixin.\n\nLemma hom_fmap (b c : C) (f : hom b c) (g : fobj homFunctor b) : \n  fmap homFunctor f g = comp f g.\nProof. by rewrite /homFunctor /= /homFunctorMixin /Functor.fmap. Qed.\n\nEnd HomFunctor.\n\nArguments homFunctor [C] _.\n\nNotation \"a '==>' '?'\" := (homFunctor a)\n  (at level 50, format \"a  '==>'  '?'\") : form_scope.\n\n(*************************************************)\n(** ** Natural Transformations                   *)\n(*************************************************)\n\nModule Natural.\n\nSection RawMixin.\nVariables C D : category.\nVariables F G : functor C D.\n\nRecord mixin_of := Mixin {\n  mx_phi : forall a : C, hom (fobj F a) (fobj G a);\n  _ : forall (a b : C) (f : hom a b),\n        comp (mx_phi b) (fmap F f) = comp (fmap G f) (mx_phi a)\n}.\n\nEnd RawMixin.\n\nSection ClassDef.\nVariables C D : category.\nVariables F G : functor C D.\n\nRecord class_of C D (F G : functor C D) := Class {mixin : mixin_of F G}.\n\nStructure type : Type := Pack {_ : class_of F G}.\n\nVariable cT : type.\nDefinition class := let: Pack c as cT' := cT return class_of F G in c.\nDefinition clone c of phant_id class c := @Pack c.\n\nDefinition pack (m0 : mixin_of F G) := \n  fun m & phant_id m0 m => Pack (@Class C D F G m).\n\nDefinition phi := mx_phi (mixin class).\n\nEnd ClassDef.\n\nModule Exports.\nCoercion phi : type >-> Funclass.\nNotation natural := Natural.type.\nNotation NaturalMixin := Natural.Mixin.\nNotation Natural F G m := (@pack _ _ F G _ m id).\n\nNotation \"[ 'natural' 'of' F G 'for' cT ]\" := (@clone F G cT _ id)\n  (at level 0, format \"[ 'natural'  'of'  F  G  'for'  cT ]\") : form_scope.\nNotation \"[ 'natural' 'of' F G ]\" := (@clone F G _ _ id)\n  (at level 0, format \"[ 'natural'  'of'  F  G ]\") : form_scope.\nNotation \"F ~~> G\" := (natural F G)\n  (at level 60, format \"F  '~~>'  G\") : form_scope.\n\nNotation phi := Natural.phi.\n\nArguments Natural.phi [C D] F G [cT] _.\n\nSection Laws.\nVariables C D : category.\nVariables F G : functor C D.\nVariable phi : F ~~> G.\n\nLemma phi_natural (a b : C) (f : hom a b) :\n  comp (phi b) (fmap F f) = comp (fmap G f) (phi a).\nProof. by case: phi=> [][][]. Qed.\n\nEnd Laws.\n\nSection Extensionality.\nVariables C D : category.\nVariables F G : functor C D.\nVariable phi1 phi2 : natural F G.\n\nLemma phi_extensionality : (forall r, phi1 r = phi2 r) -> phi1 = phi2.\nProof.\nmove=> H; destruct phi1, phi2.\ndestruct c, c0; destruct mixin0, mixin1; f_equal; f_equal.\nhave Heq: mx_phi0 = mx_phi1.\n{ by extensionality r; apply: (H r). }\nby subst; f_equal; apply proof_irrelevance.\nQed.\n\nEnd Extensionality.  \n\nHint Resolve phi_natural.\n\nEnd Exports.\n\nEnd Natural.\n\nExport Natural.Exports.\n\n(*************************************************)\n(** ** Cones                                     *)\n(*************************************************)\n\nModule Cone.\n\nSection RawMixin.\nVariables J C : category.\nVariable F : functor J C.\n\nRecord mixin_of := Mixin {\n  mx_cone : C;\n  mx_mor : forall j : J, hom mx_cone (fobj F j);\n  _ : forall (j k : J) (f : hom (fobj F j) (fobj F k)), \n        comp f (mx_mor j) = mx_mor k\n}.\n\nEnd RawMixin.\n\nSection ClassDef.\n\nVariables J C : category.\n\nVariable F : functor J C.\n\nRecord class_of (J C : category) (F : functor J C) := \n  Class {mixin : mixin_of F}.\n\nStructure type : Type := Pack {_ : class_of F}.\n\nVariables cT : type.\nDefinition class := let: Pack c := cT return class_of F in c.\nDefinition clone c of phant_id class c := @Pack c.\n\nDefinition pack (m0 : mixin_of F) := \n  fun m & phant_id m0 m => Pack (@Class J C F m).\n\nDefinition cone := mx_cone (mixin class).\nDefinition mor := mx_mor (mixin class).\n\nEnd ClassDef.\n\nModule Exports.\nCoercion cone : type >-> Category.sort.\nNotation cone := Cone.type.\nNotation ConeMixin := Cone.Mixin.\nNotation Cone J C F m := (@pack J C F _ m id).\n\nNotation \"[ 'cone' 'of' J C F 'for' cT ]\" := (@clone J C F cT _ id)\n  (at level 0, format \"[ 'cone'  'of'  J  C  F  'for'  cT ]\") : form_scope.\nNotation \"[ 'cone' 'of' J C F ]\" := (@clone J C F _ _ id)\n  (at level 0, format \"[ 'cone'  'of'  J  C  F ]\") : form_scope.\n\nNotation cone_head := Cone.cone.\nNotation cone_mor := Cone.mor.\n\nArguments Cone.cone [J C F] cT.\nArguments Cone.mor [J C F] cT j.\n\nSection Laws.\nVariables J C : category.\nVariable F : functor J C.\nVariable Con : cone F.\n\nLemma cone_commutes (j k : J) (f : hom (fobj F j) (fobj F k)) :\n  comp f (cone_mor Con j) = cone_mor Con k.\nProof. by case: Con; case; case. Qed.\n \nEnd Laws.\n\nHint Resolve cone_commutes.\n\nEnd Exports.\n\nEnd Cone.\n\nExport Cone.Exports.\n\n(*************************************************)\n(** ** Limits                                    *)\n(*************************************************)\n\nModule Limit.\n\nSection RawMixin.\nVariables J C : category.\nVariable F : functor J C.\n\nRecord mixin_of := Mixin {\n  mx_lim : cone F;\n  _ : forall Con : cone F, \n        exists! f : hom Con mx_lim, \n        forall j : J, comp (cone_mor mx_lim j) f = cone_mor Con j\n}.\n\nEnd RawMixin.\n\nSection ClassDef.\n\nVariables J C : category.\n\nVariable F : functor J C.\n\nRecord class_of (J C : category) (F : functor J C) := \n  Class {mixin : mixin_of F}.\n\nStructure type : Type := Pack {_ : class_of F}.\n\nVariable cT : type.\nDefinition class := let: Pack c := cT return class_of F in c.\nDefinition clone c of phant_id class c := @Pack c.\n\nDefinition pack (m0 : mixin_of F) := \n  fun m & phant_id m0 m => Pack (@Class J C F m).\n\nDefinition lim := mx_lim (mixin class).\n\nEnd ClassDef.\n\nModule Exports.\nCoercion lim : type >-> Cone.type.\nNotation limit := Limit.type.\nNotation LimitMixin := Limit.Mixin.\nNotation Limit J C F m := (@pack J C F _ m id).\n\nNotation \"[ 'lim' 'of' J C F 'for' cT ]\" := (@clone J C F cT _ id)\n  (at level 0, format \"[ 'lim'  'of'  J  C  F  'for'  cT ]\") : form_scope.\nNotation \"[ 'lim' 'of' J C F ]\" := (@clone J C F _ _ id)\n  (at level 0, format \"[ 'lim'  'of'  J  C  F ]\") : form_scope.\n\nNotation lim := Limit.lim.\n\nArguments Limit.lim [J C F] cT.\n\nSection Laws.\nVariables J C : category.\nVariable F : functor J C.\nVariable Lim : limit F.\n\nLemma limit_universal (Con : cone F) :\n  exists! f : hom Con Lim,\n  forall j : J, comp (cone_mor Lim j) f = cone_mor Con j.\nProof. by case: Lim; case; case. Qed.\n \nEnd Laws.\n\nHint Resolve limit_universal.\n\nEnd Exports.\n\nEnd Limit.\n\nExport Limit.Exports.\n\n(*************************************************)\n(** ** Isomorphisms                              *)\n(*************************************************)\n\nModule Iso.\n\nSection RawMixin.\n\nRecord mixin_of (T U : Type) := Mixin {\n  mx_f : T -> U;\n  mx_g : U -> T;\n  _ : forall t, (mx_g \\o mx_f) t = t;\n  _ : forall u, (mx_f \\o mx_g) u = u\n}.\n\nEnd RawMixin.\n\nSection ClassDef.\n\nVariables T U : Type.\n\nRecord class_of T U := Class {mixin : mixin_of T U}.\n\nStructure type : Type := Pack {_ : class_of T U}.\n\nVariable cT : type.\nDefinition class := let: Pack c as cT' := cT return class_of T U in c.\nDefinition clone c of phant_id class c := @Pack c.\n\n(* produce a natural type out of the mixin *)\n(* equalize m0 and m by means of a phantom *)\nDefinition pack (m0 : mixin_of T U) := \n  fun m & phant_id m0 m => Pack (@Class T U m).\n\nDefinition iso_f := mx_f (mixin class).\nDefinition iso_g := mx_g (mixin class).\n\nEnd ClassDef.\n\nModule Exports.\nNotation iso := Iso.type.\nNotation IsoMixin := Iso.Mixin.\nNotation Iso T U m := (@pack T U _ m id).\n\nNotation \"[ 'iso' 'of' T U 'for' cT ]\" := (@clone T U cT _ id)\n  (at level 0, format \"[ 'iso'  'of'  T  U  'for'  cT ]\") : form_scope.\nNotation \"[ 'iso' 'of' T U ]\" := (@clone T U _ _ id)\n  (at level 0, format \"[ 'iso'  'of'  T  U ]\") : form_scope.\nNotation \"T ~= U\" := (iso T U)\n  (at level 60, format \"T  '~='  U\") : form_scope.\n\nNotation iso_f := Iso.iso_f.\nNotation iso_g := Iso.iso_g.\n\nArguments Iso.iso_f [T U] cT t.\nArguments Iso.iso_g [T U] cT u.\n\nSection Laws.\nVariables T U : Type.\nVariable iso : iso T U.\n\nLemma iso_gf (t : T) : (iso_g iso \\o iso_f iso) t = t.\nProof. by case: iso=> [][][]. Qed.\n\nLemma iso_fg (u : U) : (iso_f iso \\o iso_g iso) u = u.\nProof. by case: iso=> [][][]. Qed.\n\nEnd Laws.\n\nHint Resolve iso_gf iso_fg.\n\nEnd Exports.\n\nEnd Iso.\n\nExport Iso.Exports.\n\n(*************************************************)\n(** ** Yoneda                                    *)\n(*************************************************)\n \nSection Yoneda.\nVariable C : category.\nVariable F : functor C Coq.\n\nDefinition Y (a : C) := (a ==> ?) ~~> F.\n\nDefinition uncheck a (y : Y a) : fobj F a := y a ida.\n\nSection check.\n  Variables (a : C) (x : fobj F a).\n  Definition check_phi (r : C) (f : fobj (a ==> ?) r) := fmap F f x.\n\n  Lemma check_phi_natural (r b : C) (f : hom r b) :\n    check_phi (r:=b) \\o fmap (a ==> ?) f = fmap F f \\o check_phi (r:=r).\n  Proof. by extensionality y; rewrite /check_phi /= hom_fmap fmap_assoc. Qed.\n\n  Definition checkNaturalMixin := \n    @Natural.Mixin C Coq (a ==> ?) F check_phi check_phi_natural.\n  Definition check : Y a := \n    Eval hnf in Natural (a ==> ?) F checkNaturalMixin.\nEnd check.\n\nLemma checkP a r (x : fobj F a) (f : fobj (a ==> ?) r) :\n  check x _ f = fmap F f x.\nProof. by []. Qed.\n\nLemma uncheck_check a x : uncheck (a:=a) (check (a:=a) x) = id x.\nProof. by rewrite /uncheck /funcomp checkP fmap_id. Qed.\n\nLemma check_uncheck' A (y : Y A) R g : check (uncheck y) R g = y R g.\nProof.\nrewrite checkP /uncheck.\nsuff: (comp (fmap F g) (y A)) ida = y R g => //.\nrewrite -phi_natural.\nsuff: (y R \\o fmap (A ==> ?) g) ida = y R g=> //=.\nby rewrite hom_fmap id_right.\nQed.\n\nLemma check_uncheck A (y : Y A) : check (uncheck y) = y.\nProof. \nby apply: phi_extensionality=> r; extensionality x; apply: check_uncheck'. \nQed.\n\nEnd Yoneda. \n\n(*\nSection YonedaIso.\nVariable C : category.\nVariable F : functor C Coq.\nSet Printing Universes.\n\n(** Can't typecheck the following due to a universe inconsistency: \n  Don't know that univ(Y F a) <= univ(T) in IsoMixin T U ...*)\n\nDefinition YonedaIsoMixin (a : C) := \n  @IsoMixin (Y F a) (fobj F a) (@uncheck _ F a) (@check _ F a) \n            (@check_uncheck _ F a) (@uncheck_check _ F a).\nCanonical YonedaIso a := @Iso (Y F a) (F a) (YonedaIsoMixin a).\n\nEnd YonedaIso.\n*)\n\n\n", "meta": {"author": "gstew5", "repo": "yoneda", "sha": "56e82cf60f4aa29705ea07d90963c622a917dcd2", "save_path": "github-repos/coq/gstew5-yoneda", "path": "github-repos/coq/gstew5-yoneda/yoneda-56e82cf60f4aa29705ea07d90963c622a917dcd2/Yoneda.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6712142781473794}}
{"text": "(***************************************************************************\n\n Monoidal categories\n\n In this file, we define the notion of monoidal category. In addition, we\n prove the important laws for monoidal categories.\n\n The main definition in this file, takes a so-called displayed approach.\n More specifically, we define the notion of a monoidal structure on a\n category. For this notion, we define suitable accessors and we prove the\n laws. Finally, we also provide a bundled notion of monoidal category, which\n is a category together with a monoidal structure for it. The necessary\n accessors and laws are derived from the other notion.\n\n In this file, we use a whiskered approach. This means that we have two\n operations to tensor with morphisms: a left and a right whiskering. Both of\n these take an object and a morphism as input and they return a morphism as\n output.\n\n Contents\n 1. Monoidal structures\n 2. Opposite monoidal category\n 3. Equivalences from the tensor and unit\n 4. The unitors coincide\n 5. Swapping the tensor\n 6. More monoidal laws\n 7. Bundled approach to monoidal categories\n\nNote: after refactoring on March 10, 2023, the prior Git history of this development is found via\ngit log -- UniMath/CategoryTheory/Monoidal/MonoidalCategoriesWhiskered.v\n\n ***************************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.Notations.\nRequire Import UniMath.MoreFoundations.PartA.\n\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.PrecategoryBinProduct.\nRequire Import UniMath.CategoryTheory.Monoidal.WhiskeredBifunctors.\n\nRequire Import UniMath.CategoryTheory.Adjunctions.Core.\nRequire Import UniMath.CategoryTheory.Equivalences.Core.\nRequire Import UniMath.CategoryTheory.Equivalences.FullyFaithful.\nRequire Import UniMath.CategoryTheory.opp_precat.\n\nLocal Open Scope cat.\n\nImport BifunctorNotations.\n\n(**\n 1. Monoidal structures\n *)\nSection A.\n\n(** Data **)\nDefinition tensor_data (C : category) : UU :=\n  bifunctor_data C C C.\nIdentity Coercion tensorintobifunctor : tensor_data >-> bifunctor_data.\n\nDefinition leftunitor_data\n           {C : category}\n           (T : tensor_data C)\n           (I : C)\n  : UU\n  := ∏ (x : C), C⟦I ⊗_{T} x, x⟧.\n\nDefinition leftunitorinv_data\n           {C : category}\n           (T : tensor_data C)\n           (I : C)\n  : UU\n  := ∏ (x : C), C⟦x, I ⊗_{T} x⟧.\n\nDefinition rightunitor_data\n           {C : category}\n           (T : tensor_data C)\n           (I : C)\n  : UU\n  := ∏ (x : C), C⟦x ⊗_{T} I, x⟧.\n\nDefinition rightunitorinv_data\n           {C : category}\n           (T : tensor_data C)\n           (I : C)\n  : UU\n  := ∏ (x : C), C⟦x, x ⊗_{T} I⟧.\n\nDefinition associator_data\n           {C : category}\n           (T : tensor_data C)\n  : UU\n  := ∏ (x y z : C), C ⟦(x ⊗_{T} y) ⊗_{T} z, x ⊗_{T} (y ⊗_{T} z)⟧.\n\nDefinition associatorinv_data\n           {C : category}\n           (T : tensor_data C)\n  : UU\n  := ∏ (x y z : C), C ⟦x ⊗_{T} (y ⊗_{T} z), (x ⊗_{T} y) ⊗_{T} z⟧.\n\nDefinition monoidal_data (C : category): UU :=\n    ∑ (T : tensor_data C) (I : C),\n    (leftunitor_data T I) × (leftunitorinv_data T I) ×\n    (rightunitor_data T I) × (rightunitorinv_data T I) ×\n    (associator_data T) × (associatorinv_data T).\n\nDefinition make_monoidal_data\n           {C : category}\n           {T : tensor_data C}\n           {I : C}\n           (lu : leftunitor_data T I)\n           (luinv : leftunitorinv_data T I)\n           (ru : rightunitor_data T I)\n           (ruinv : rightunitorinv_data T I)\n           (α : associator_data T)\n           (αinv : associatorinv_data T)\n  : monoidal_data C\n  := (T,,I,,lu,,luinv,,ru,,ruinv,,α,,αinv).\n\nDefinition monoidal_tensor_data {C : category} (MD : monoidal_data C) : tensor_data C := pr1 MD.\nCoercion monoidal_tensor_data : monoidal_data >-> tensor_data.\n\nDefinition monoidal_unit {C : category} (MD : monoidal_data C) : C := pr12 MD.\nNotation \"I_{ MD }\" := (monoidal_unit MD).\n\nDefinition monoidal_leftunitordata\n           {C : category}\n           (MD : monoidal_data C)\n  : leftunitor_data MD I_{MD}\n  := pr1 (pr22 MD).\nNotation \"lu_{ MD }\" := (monoidal_leftunitordata MD).\n\nDefinition monoidal_leftunitorinvdata\n           {C : category}\n           (MD : monoidal_data C)\n  : leftunitorinv_data MD I_{MD}\n  := pr12 (pr22 MD).\nNotation \"luinv_{ MD }\" := (monoidal_leftunitorinvdata MD).\n\nDefinition monoidal_rightunitordata\n           {C : category}\n           (MD : monoidal_data C)\n  : rightunitor_data MD I_{MD}\n  := pr122 (pr22 MD).\nNotation \"ru_{ MD }\" := (monoidal_rightunitordata MD).\n\nDefinition monoidal_rightunitorinvdata\n           {C : category}\n           (MD : monoidal_data C)\n  : rightunitorinv_data MD I_{MD}\n  := pr1 (pr222 (pr22 MD)).\nNotation \"ruinv_{ MD }\" := (monoidal_rightunitorinvdata MD).\n\nDefinition monoidal_associatordata\n           {C : category}\n           (MD : monoidal_data C)\n  : associator_data MD\n  := pr12 (pr222 (pr22 MD)).\nNotation \"α_{ MD }\" := (monoidal_associatordata MD).\n\nDefinition monoidal_associatorinvdata\n           {C : category}\n           (MD : monoidal_data C)\n  : associatorinv_data MD\n  := pr22 (pr222 (pr22 MD)).\nNotation \"αinv_{ MD }\" := (monoidal_associatorinvdata MD).\n\n(** Axioms **)\nDefinition leftunitor_nat\n           {C : category}\n           {T : tensor_data C}\n           {I : C}\n           (lu : leftunitor_data T I)\n  : UU\n  := ∏ (x y : C), ∏ (f : C ⟦x,y⟧),  I ⊗^{ T}_{l} f · lu y = lu x · f.\n\nDefinition leftunitorinv_nat\n           {C : category}\n           {T : tensor_data C}\n           {I : C}\n           (luinv : leftunitorinv_data T I)\n  : UU\n  := ∏ (x y : C), ∏ (f : C ⟦x,y⟧),  luinv x · I ⊗^{ T}_{l} f = f · luinv y.\n\nDefinition leftunitor_iso_law\n           {C : category}\n           {T : tensor_data C}\n           {I : C}\n           (lu : leftunitor_data T I)\n           (luinv : leftunitorinv_data T I)\n  : UU\n  := ∏ (x : C), is_inverse_in_precat (lu x) (luinv x).\n\nDefinition leftunitor_law\n           {C : category}\n           {T : tensor_data C}\n           {I : C}\n           (lu : leftunitor_data T I)\n           (luinv : leftunitorinv_data T I)\n  : UU\n  := leftunitor_nat lu × leftunitor_iso_law lu luinv.\n\nDefinition leftunitorlaw_nat\n            {C : category}\n            {T : tensor_data C}\n            {I : C}\n            {lu : leftunitor_data T I}\n            {luinv : leftunitorinv_data T I}\n            (lu_law : leftunitor_law lu luinv)\n  : leftunitor_nat lu\n  := pr1 lu_law.\n\nDefinition leftunitorlaw_iso_law\n           {C : category}\n           {T : tensor_data C}\n           {I : C}\n           {lu : leftunitor_data T I}\n           {luinv : leftunitorinv_data T I}\n           (lu_law : leftunitor_law lu luinv)\n  : leftunitor_iso_law lu luinv\n  := pr2 lu_law.\n\nDefinition rightunitor_nat\n           {C : category}\n           {T : tensor_data C}\n           {I : C}\n           (ru : rightunitor_data T I)\n  : UU\n  := ∏ (x y : C), ∏ (f : C ⟦x,y⟧),  f ⊗^{ T}_{r} I · ru y = ru x · f.\n\nDefinition rightunitorinv_nat\n           {C : category}\n           {T : tensor_data C}\n           {I : C}\n           (ruinv : rightunitorinv_data T I)\n  : UU\n  := ∏ (x y : C), ∏ (f : C ⟦x,y⟧),  ruinv x · f ⊗^{ T}_{r} I = f · ruinv y.\n\nDefinition rightunitor_iso_law\n           {C : category}\n           {T : tensor_data C}\n           {I : C}\n           (ru : rightunitor_data T I)\n           (ruinv : rightunitorinv_data T I)\n  : UU\n  := ∏ (x : C), is_inverse_in_precat (ru x) (ruinv x).\n\nDefinition rightunitor_law\n           {C : category}\n           {T : tensor_data C}\n           {I : C}\n           (ru : rightunitor_data T I)\n           (ruinv : rightunitorinv_data T I)\n  : UU\n  := rightunitor_nat ru × rightunitor_iso_law ru ruinv.\n\nDefinition rightunitorlaw_nat\n           {C : category}\n           {T : tensor_data C}\n           {I : C}\n           {ru : rightunitor_data T I}\n           {ruinv : rightunitorinv_data T I}\n           (rul : rightunitor_law ru ruinv)\n  : rightunitor_nat ru\n  := pr1 rul.\n\nDefinition rightunitorlaw_iso_law\n           {C : category}\n           {T : tensor_data C}\n           {I : C}\n           {ru : rightunitor_data T I}\n           {ruinv : rightunitorinv_data T I}\n           (rul : rightunitor_law ru ruinv)\n  : rightunitor_iso_law ru ruinv\n  := pr2 rul.\n\nDefinition associator_nat_leftwhisker\n           {C : category}\n           {T : tensor_data C}\n           (α : associator_data T)\n  : UU\n  := ∏ (x y z z' : C) (h : C⟦z,z'⟧),\n     (α x y z) · (x ⊗^{ T}_{l} (y ⊗^{ T}_{l} h))\n     =\n     ((x ⊗_{ T} y) ⊗^{ T}_{l} h) · (α x y z').\n\nDefinition associator_nat_rightwhisker\n           {C : category}\n           {T : tensor_data C}\n           (α : associator_data T)\n  : UU\n  := ∏ (x x' y z : C) (f : C⟦x,x'⟧),\n     (α x y z) · (f ⊗^{ T}_{r} (y ⊗_{ T} z))\n     =\n     ((f ⊗^{ T}_{r} y) ⊗^{ T}_{r} z) · (α x' y z).\n\nDefinition associator_nat_leftrightwhisker\n           {C : category}\n           {T : tensor_data C}\n           (α : associator_data T)\n  : UU\n  := ∏ (x y y' z : C) (g : C⟦y,y'⟧),\n     (α x y z) · (x ⊗^{ T}_{l} (g ⊗^{ T}_{r} z))\n     =\n     ((x ⊗^{ T}_{l} g) ⊗^{ T}_{r} z) · (α x y' z).\n\nDefinition associator_iso_law\n           {C : category}\n           {T : tensor_data C}\n           (α : associator_data T)\n           (αinv : associatorinv_data T)\n  : UU\n  := ∏ (x y z : C), is_inverse_in_precat (α x y z) (αinv x y z).\n\nDefinition associator_law\n           {C : category}\n           {T : tensor_data C}\n           (α : associator_data T)\n           (αinv : associatorinv_data T)\n  : UU\n  := (associator_nat_leftwhisker α) × (associator_nat_rightwhisker α) ×\n     (associator_nat_leftrightwhisker α) × (associator_iso_law α αinv).\n\nDefinition associatorlaw_natleft\n           {C : category}\n           {T : tensor_data C}\n           {α : associator_data T}\n           {αinv : associatorinv_data T}\n           (αl : associator_law α αinv)\n  : associator_nat_leftwhisker α\n  := pr1 αl.\n\nDefinition associatorlaw_natright\n           {C : category}\n           {T : tensor_data C}\n           {α : associator_data T}\n           {αinv : associatorinv_data T}\n           (αl : associator_law α αinv)\n  : associator_nat_rightwhisker α\n  := pr1 (pr2 αl).\n\nDefinition associatorlaw_natleftright\n           {C : category}\n           {T : tensor_data C}\n           {α : associator_data T}\n           {αinv : associatorinv_data T}\n           (αl : associator_law α αinv)\n  : associator_nat_leftrightwhisker α\n  := pr1 (pr2 (pr2 αl)).\n\nDefinition associatorlaw_iso_law\n           {C : category}\n           {T : tensor_data C}\n           {α : associator_data T}\n           {αinv : associatorinv_data T}\n           (αl : associator_law α αinv)\n  : associator_iso_law α αinv\n  := pr2 (pr2 (pr2 αl)).\n\nDefinition triangle_identity\n           {C : category}\n           {T : tensor_data C}\n           {I : C}\n           (lu : leftunitor_data T I)\n           (ru : rightunitor_data T I)\n           (α : associator_data T)\n  : UU\n  := ∏ (x y : C), α x I y · x ⊗^{T}_{l} (lu y) = ru x ⊗^{T}_{r} y.\n\n(** more triangle laws that are redundant in the axiomatisation *)\nDefinition triangle_identity'\n           {C : category}\n           {T : tensor_data C}\n           {I : C}\n           (lu : leftunitor_data T I)\n           (α : associator_data T)\n  : UU\n  := ∏ (x y : C), α I x y · lu (x ⊗_{T} y) = lu x ⊗^{T}_{r} y.\n\nDefinition triangle_identity''\n           {C : category}\n           {T : tensor_data C}\n           {I : C}\n           (ru : rightunitor_data T I)\n           (α : associator_data T)\n  : UU\n  := ∏ (x y : C), α x y I · x ⊗^{T}_{l} (ru y) = ru (x ⊗_{T} y).\n\nDefinition pentagon_identity\n           {C : category}\n           {T : tensor_data C}\n           (α : associator_data T)\n  : UU\n  := ∏ (w x y z : C),\n     ((α w x y) ⊗^{T}_{r} z) · (α w (x⊗_{T} y) z) · (w ⊗^{T}_{l} (α x y z))\n     =\n     (α (w⊗_{T}x) y z) · (α w x (y ⊗_{T} z)).\n\nDefinition monoidal_laws\n           {C : category}\n           (MD : monoidal_data C)\n  : UU\n  := is_bifunctor MD\n     × (leftunitor_law lu_{MD} luinv_{MD})\n     × (rightunitor_law ru_{MD} ruinv_{MD})\n     × (associator_law α_{MD} αinv_{MD})\n     × (triangle_identity lu_{MD} ru_{MD} α_{MD})\n     × (pentagon_identity α_{MD}).\n\nDefinition monoidal (C : category) : UU :=\n  ∑ (MD : monoidal_data C), (monoidal_laws MD).\n\nDefinition monoidal_mondata {C : category} (M : monoidal C) : monoidal_data C := pr1 M.\nCoercion monoidal_mondata : monoidal >-> monoidal_data.\n\nDefinition monoidal_monlaws {C : category} (M : monoidal C) : monoidal_laws M := pr2 M.\n\nDefinition monoidal_tensor_is_bifunctor\n           {C : category}\n           (M : monoidal C)\n  : is_bifunctor M\n  := pr12 M.\n\nCoercion monoidal_tensor\n         {C : category}\n         (M : monoidal C)\n  : bifunctor C C C\n  := _ ,, monoidal_tensor_is_bifunctor M.\n\nDefinition monoidal_leftunitorlaw\n           {C : category}\n           (M : monoidal C)\n  : leftunitor_law lu_{M} luinv_{M}\n  := pr12 (monoidal_monlaws M).\n\nDefinition monoidal_leftunitornat\n           {C : category}\n           (M : monoidal C)\n  : leftunitor_nat lu_{M}\n  := leftunitorlaw_nat (monoidal_leftunitorlaw M).\n\nDefinition monoidal_leftunitorisolaw\n           {C : category}\n           (M : monoidal C)\n  : leftunitor_iso_law lu_{M} luinv_{M}\n  := leftunitorlaw_iso_law (monoidal_leftunitorlaw M).\n\nLemma monoidal_leftunitorinvnat\n      {C : category}\n      (M : monoidal C)\n  : leftunitorinv_nat luinv_{M}.\nProof.\n  intros x y f.\n  apply (z_iso_inv_on_right _ _ _ (_,,_,,monoidal_leftunitorisolaw M x)).\n  cbn.\n  rewrite assoc.\n  apply (z_iso_inv_on_left _ _ _ _ (_,,_,,monoidal_leftunitorisolaw M y)).\n  apply pathsinv0, monoidal_leftunitornat.\nQed.\n\nDefinition monoidal_rightunitorlaw\n           {C : category}\n           (M : monoidal C)\n  : rightunitor_law ru_{M} ruinv_{M}\n  := pr122 (monoidal_monlaws M).\n\nDefinition monoidal_rightunitornat\n           {C : category}\n           (M : monoidal C)\n  : rightunitor_nat ru_{M}\n  := rightunitorlaw_nat (monoidal_rightunitorlaw M).\n\nDefinition monoidal_rightunitorisolaw\n           {C : category}\n           (M : monoidal C)\n  : rightunitor_iso_law ru_{M} ruinv_{M}\n  := rightunitorlaw_iso_law (monoidal_rightunitorlaw M).\n\nLemma monoidal_rightunitorinvnat\n      {C : category}\n      (M : monoidal C)\n  : rightunitorinv_nat ruinv_{M}.\nProof.\n  intros x y f.\n  apply (z_iso_inv_on_right _ _ _ (_,,_,,monoidal_rightunitorisolaw M x)).\n  cbn.\n  rewrite assoc.\n  apply (z_iso_inv_on_left _ _ _ _ (_,,_,,monoidal_rightunitorisolaw M y)).\n  apply pathsinv0, monoidal_rightunitornat.\nQed.\n\nDefinition monoidal_associatorlaw\n           {C : category}\n           (M : monoidal C)\n  : associator_law α_{M} αinv_{M}\n  := pr1 (pr222 (monoidal_monlaws M)).\n\nDefinition monoidal_associatornatleft\n           {C : category}\n           (M : monoidal C)\n  : associator_nat_leftwhisker α_{M}\n  := associatorlaw_natleft (monoidal_associatorlaw M).\n\nDefinition monoidal_associatornatright\n           {C : category}\n           (M : monoidal C)\n  : associator_nat_rightwhisker α_{M}\n  := associatorlaw_natright (monoidal_associatorlaw M).\n\nDefinition monoidal_associatornatleftright\n           {C : category}\n           (M : monoidal C)\n  : associator_nat_leftrightwhisker α_{M}\n  := associatorlaw_natleftright (monoidal_associatorlaw M).\n\nDefinition monoidal_associatorisolaw\n           {C : category}\n           (M : monoidal C)\n  : associator_iso_law α_{M} αinv_{M}\n  := associatorlaw_iso_law (monoidal_associatorlaw M).\n\nLemma associator_nat1\n      {C : category}\n      (M : monoidal C)\n      {x x' y y' z z' : C}\n      (f : C⟦x,x'⟧) (g : C⟦y,y'⟧) (h : C⟦z,z'⟧)\n  : (monoidal_associatordata M x y z)\n    · ((f ⊗^{M}_{r} (y ⊗_{M} z))\n    · (x' ⊗^{M}_{l} ((g ⊗^{M}_{r} z) · (y' ⊗^{M}_{l} h))))\n    =\n    (((f ⊗^{M}_{r} y)\n    · (x' ⊗^{M}_{l} g))  ⊗^{M}_{r} z)\n      · ((x' ⊗_{M} y') ⊗^{M}_{l} h) · (monoidal_associatordata M x' y' z').\nProof.\n  rewrite assoc.\n  rewrite (monoidal_associatornatright M).\n  rewrite assoc'.\n  etrans. {\n    apply cancel_precomposition.\n    rewrite (bifunctor_leftcomp M).\n    rewrite assoc.\n    rewrite (monoidal_associatornatleftright M).\n    apply idpath.\n  }\n\n  etrans. {\n    apply cancel_precomposition.\n    rewrite assoc'.\n    apply cancel_precomposition.\n    apply (monoidal_associatornatleft M).\n  }\n  rewrite assoc.\n  rewrite assoc.\n  apply cancel_postcomposition.\n  apply pathsinv0.\n  rewrite (bifunctor_rightcomp M).\n  apply idpath.\nQed.\n\nLemma associator_nat2\n      {C : category}\n      (M : monoidal C)\n      {x x' y y' z z' : C} (f : C⟦x,x'⟧)\n      (g : C⟦y,y'⟧) (h : C⟦z,z'⟧)\n  : (monoidal_associatordata M x y z) · (f ⊗^{M} (g ⊗^{M} h))\n    =\n    ((f ⊗^{M} g) ⊗^{M} h) · (monoidal_associatordata M x' y' z').\nProof.\n  intros.\n  unfold functoronmorphisms1.\n  exact (associator_nat1 M f g h).\nQed.\n\nDefinition monoidal_triangleidentity\n           {C : category}\n           (M : monoidal C)\n  : triangle_identity lu_{M} ru_{M} α_{M}\n  := pr12 (pr222 (monoidal_monlaws M)).\n\nDefinition monoidal_pentagonidentity\n           {C : category}\n           (M : monoidal C)\n  : pentagon_identity α_{M}\n  := pr22 (pr222 (monoidal_monlaws M)).\n\nLemma isaprop_monoidal_laws {C : category} (M : monoidal_data C)\n  : isaprop (monoidal_laws M).\nProof.\n  repeat (apply isapropdirprod)\n  ; repeat (apply impred ; intro)\n  ; repeat (try apply C)\n  ; repeat (apply isaprop_is_inverse_in_precat).\nQed.\n\n(** Some additional data and properties which one deduces from monoidal categories **)\n(* Not the best name though, but here my creativity fails *)\nLemma swap_nat_along_zisos\n      {C : category} {x1 x2 y1 y2 : C}\n      (p1 : z_iso x1 y1) (p2 : z_iso x2 y2)\n  : ∏ (f: C⟦x1,x2⟧) (g : C⟦y1,y2⟧),\n    (pr1 p1) · g = f · (pr1 p2) -> g · (inv_from_z_iso p2) = (inv_from_z_iso p1) · f.\nProof.\n  intros f g p.\n  apply pathsinv0.\n  apply z_iso_inv_on_right.\n  rewrite assoc.\n  apply z_iso_inv_on_left.\n  apply p.\nQed.\n\nLemma leftunitor_nat_z_iso {C : category} (M : monoidal C)\n  : nat_z_iso\n      (leftwhiskering_functor M I_{M})\n      (functor_identity C).\nProof.\n  use make_nat_z_iso.\n  - use make_nat_trans.\n    + exact (λ x, lu_{M} x).\n    + exact (λ x y f, monoidal_leftunitornat M x y f).\n  - intro x. exists (luinv_{M} x).\n    apply (monoidal_leftunitorisolaw M x).\nDefined.\n\nDefinition rightunitor_nat_z_iso {C : category} (M : monoidal C)\n  : nat_z_iso\n      (rightwhiskering_functor M I_{M})\n      (functor_identity C).\nProof.\n  use make_nat_z_iso.\n  - use make_nat_trans.\n    + exact (λ x, ru_{M} x).\n    + exact (λ x y f, monoidal_rightunitornat M x y f).\n  - intro x. exists (ruinv_{M} x).\n    apply (monoidal_rightunitorisolaw M x).\nDefined.\n\nDefinition z_iso_from_associator_iso\n           {C : category} (M : monoidal C) (x y z : C)\n  : z_iso ((x ⊗_{ M} y) ⊗_{ M} z) (x ⊗_{ M} (y ⊗_{ M} z))\n  := make_z_iso\n       (α_{M} x y z)\n       (αinv_{M} x y z)\n       (monoidal_associatorisolaw M x y z).\n\nDefinition monoidal_associatorinvnatleft\n           {C : category}\n           (M : monoidal C)\n  : ∏ (x y z z' : C) (h : C⟦z,z'⟧),\n    (x ⊗^{M}_{l} (y ⊗^{M}_{l} h)) · (αinv_{M} x y z')\n    =\n    (αinv_{M} x y z) · ((x ⊗_{M} y) ⊗^{M}_{l} h) .\nProof.\n  intros x y z z' h.\n  apply (swap_nat_along_zisos (z_iso_from_associator_iso M x y z) (z_iso_from_associator_iso M x y z')).\n  apply monoidal_associatornatleft.\nQed.\n\nDefinition monoidal_associatorinvnatright\n           {C : category}\n           (M : monoidal C)\n  : ∏ (x x' y z: C) (f : C⟦x,x'⟧),\n    (f ⊗^{M}_{r} (y ⊗_{M} z)) · (αinv_{M} x' y z)\n    =\n    (αinv_{M} x y z) · ((f ⊗^{M}_{r} y) ⊗^{M}_{r} z).\nProof.\n  intros x x' y z f.\n  apply (swap_nat_along_zisos (z_iso_from_associator_iso M x y z) (z_iso_from_associator_iso M x' y z)).\n  apply monoidal_associatornatright.\nQed.\n\nDefinition monoidal_associatorinvnatleftright\n           {C : category}\n           (M : monoidal C)\n  : ∏ (x y y' z : C) (g : C⟦y,y'⟧),\n    (x ⊗^{M}_{l} (g ⊗^{M}_{r} z)) · (αinv_{M} x y' z)\n    =\n    (αinv_{M} x y z) · ((x ⊗^{M}_{l} g) ⊗^{M}_{r} z).\nProof.\n  intros x y y' z g.\n  apply (swap_nat_along_zisos (z_iso_from_associator_iso M x y z) (z_iso_from_associator_iso M x y' z)).\n  apply monoidal_associatornatleftright.\nQed.\n\nDefinition monoidal_associatorinv_nat1\n           {C : category}\n           (M : monoidal C)\n           {x x' y y' z z' : C}\n           (f : C⟦x,x'⟧)\n           (g : C⟦y,y'⟧)\n           (h : C⟦z,z'⟧)\n  : ((f ⊗^{M}_{r} (y ⊗_{M} z))\n    · (x' ⊗^{M}_{l} ((g ⊗^{M}_{r} z) · (y' ⊗^{M}_{l} h))))\n    · (αinv_{M} x' y' z')\n    =\n    (αinv_{M} x y z)\n    · ((((f ⊗^{M}_{r} y)\n    · (x' ⊗^{M}_{l} g))  ⊗^{M}_{r} z)\n    · ((x' ⊗_{M} y') ⊗^{ M}_{l} h)).\nProof.\n  apply (swap_nat_along_zisos\n           (z_iso_from_associator_iso M x y z)\n           (z_iso_from_associator_iso M x' y' z')\n        ).\n  unfold z_iso_from_associator_iso.\n  unfold make_z_iso.\n  unfold make_is_z_isomorphism.\n  unfold pr1.\n  apply associator_nat1.\nQed.\n\nLemma monoidal_associatorinv_nat2\n      {C : category}\n      (M : monoidal C)\n      {x x' y y' z z' : C}\n      (f : C⟦x,x'⟧) (g : C⟦y,y'⟧) (h : C⟦z,z'⟧)\n  : (f ⊗^{M} (g ⊗^{M} h)) · (αinv_{M} x' y' z')\n    =\n    (αinv_{M} x y z) · ((f ⊗^{M} g) ⊗^{M} h).\nProof.\n  intros.\n  unfold functoronmorphisms1.\n  apply monoidal_associatorinv_nat1.\nQed.\n\nLemma monoidal_triangle_identity_inv\n      {C : category}\n      (M : monoidal C)\n      (x y : C)\n  : x ⊗^{M}_{l} luinv_{M} y · αinv_{M} x I_{ M} y = ruinv_{M} x ⊗^{ M}_{r} y.\nProof.\n  apply pathsinv0.\n  apply (z_iso_inv_on_left _ _ _ _ ((z_iso_from_associator_iso M _ _ _))).\n  cbn.\n  set (luiy := make_z_iso _ _ (monoidal_leftunitorisolaw M y)).\n  set (luixy := functor_on_z_iso (leftwhiskering_functor M x) luiy).\n  set (ruix := make_z_iso _ _ (monoidal_rightunitorisolaw M x)).\n  set (ruixy := functor_on_z_iso (rightwhiskering_functor M y) ruix).\n  apply pathsinv0.\n  apply (z_iso_inv_on_right _ _ _ ruixy).\n  apply (z_iso_inv_on_left _ _ _ _ luixy).\n  exact (! (monoidal_triangleidentity M) x y).\nQed.\n\n(* another proof of the same law - could be deleted in some future: *)\nLemma monoidal_triangle_identity_inv_alt\n      {C : category}\n      (M : monoidal C)\n      (x y : C)\n  : x ⊗^{M}_{l} (luinv_{M} y) · αinv_{M} x I_{M} y  = (ruinv_{M} x) ⊗^{M}_{r} y.\nProof.\n  transparent assert (auxiso1 : (z_iso (x ⊗_{ M} y) (x ⊗_{ M} (I_{ M} ⊗_{ M} y)))).\n  { exists (x ⊗^{M}_{l} (luinv_{M} y)).\n    apply (is_z_iso_leftwhiskering_z_iso M).\n    exists (lu_{ M} y).\n    split; apply monoidal_leftunitorisolaw. }\n  transparent assert (auxiso2 : (z_iso (x ⊗_{ M} y) ((x ⊗_{ M} I_{ M}) ⊗_{ M} y))).\n  { exists (ruinv_{ M} x ⊗^{ M}_{r} y).\n    apply (is_z_iso_rightwhiskering_z_iso M).\n    exists (ru_{ M} x).\n    split; apply monoidal_rightunitorisolaw. }\n  apply pathsinv0, (z_iso_inv_on_left _ _ _ _ (z_iso_from_associator_iso M _ _ _)).\n  apply (z_iso_inv_to_left _ _ _ auxiso2).\n  apply (z_iso_inv_to_right _ _ _ _ auxiso1).\n  apply pathsinv0, monoidal_triangleidentity.\nQed.\n\nLemma monoidal_pentagon_identity_inv\n      {C : category}\n      (M : monoidal C)\n      (w x y z : C)\n  : w ⊗^{ M}_{l} (αinv_{M} x y z)\n    · αinv_{M} w (x ⊗_{ M} y) z\n    · αinv_{M} w x y ⊗^{ M}_{r} z\n    =\n    αinv_{M} w x (y ⊗_{ M} z)\n    · αinv_{M} (w ⊗_{ M} x) y z.\nProof.\n  apply pathsinv0.\n  apply (z_iso_inv_on_right _ _ _ (z_iso_from_associator_iso M _ _ _)).\n  unfold z_iso_from_associator_iso.\n  unfold make_z_iso.\n  unfold make_is_z_isomorphism.\n  etrans. { apply (pathsinv0 (id_right _)). }\n  apply (z_iso_inv_on_right _ _ _ (z_iso_from_associator_iso M _ _ _)).\n  cbn.\n  apply pathsinv0.\n  etrans. {\n   rewrite assoc.\n   apply cancel_postcomposition.\n   apply (pathsinv0 (monoidal_pentagonidentity M w x y z)).\n  }\n  etrans. {\n    rewrite assoc.\n    rewrite assoc.\n    apply cancel_postcomposition.\n    apply cancel_postcomposition.\n    rewrite assoc'.\n    apply cancel_precomposition.\n    apply (pathsinv0 (bifunctor_leftcomp M _ _ _ _ _ _)).\n  }\n  etrans. {\n    apply cancel_postcomposition.\n    apply cancel_postcomposition.\n    apply cancel_precomposition.\n    apply maponpaths.\n    apply (pr2 (z_iso_from_associator_iso M x y z)).\n  }\n  etrans. {\n    apply cancel_postcomposition.\n    apply cancel_postcomposition.\n    apply cancel_precomposition.\n    apply (bifunctor_leftid M).\n  }\n  etrans. {\n    apply cancel_postcomposition.\n    apply cancel_postcomposition.\n    apply id_right.\n  }\n  etrans. {\n    apply cancel_postcomposition.\n    rewrite assoc'.\n    apply cancel_precomposition.\n    apply (pr2 (z_iso_from_associator_iso M w (x⊗_{M}y) z)).\n  }\n  etrans. {\n    apply cancel_postcomposition.\n    apply id_right.\n  }\n  etrans. {\n    apply (pathsinv0 (bifunctor_rightcomp M _ _ _ _ _ _)).\n  }\n  etrans. {\n    apply maponpaths.\n    apply (pr2 (pr2 (z_iso_from_associator_iso M w x y))).\n  }\n  apply (bifunctor_rightid M).\nQed.\n\nEnd A.\n\nModule MonoidalNotations.\n  Notation \"I_{ M }\" := (monoidal_unit M) : cat.\n  Notation \"lu_{ M }\" := (monoidal_leftunitordata M) : cat.\n  Notation \"luinv_{ M }\" := (monoidal_leftunitorinvdata M) : cat.\n  Notation \"ru_{ M }\" := (monoidal_rightunitordata M) : cat.\n  Notation \"ruinv_{ M }\" := (monoidal_rightunitorinvdata M) : cat.\n  Notation \"α_{ M }\" := (monoidal_associatordata M) : cat.\n  Notation \"αinv_{ M }\" := (monoidal_associatorinvdata M) : cat.\n  Notation \"lu^{ M }_{ x }\" := (monoidal_leftunitordata M x ) : cat.\n  Notation \"ru^{ M }_{ x }\" := ( monoidal_rightunitordata M x ) : cat.\n  Notation \"α^{ M }_{ x , y , z }\" := (monoidal_associatordata M x y z) : cat.\n  Notation \"luinv^{ M }_{ x }\" := (monoidal_leftunitorinvdata M x ) : cat.\n  Notation \"ruinv^{ M }_{ x }\" := ( monoidal_rightunitorinvdata M x ) : cat.\n  Notation \"αinv^{ M }_{ x , y , z }\" := (monoidal_associatorinvdata M x y z) : cat.\nEnd MonoidalNotations.\n\n(**\n 2. Opposite monoidal category\n *)\nSection OppositeMonoidal.\n  Context {C : category} (M : monoidal C).\n\n  Import MonoidalNotations.\n\n  Definition monoidal_opp_tensor_data : bifunctor_data C^op C^op C^op.\n  Proof.\n    exists (pr11 (monoidal_tensor M)).\n    exists (λ x _ _ g, x ⊗^{M}_{l} g).\n    exact (λ x _ _ f, f ⊗^{M}_{r} x).\n  Defined.\n\n  Lemma monoidal_opp_is_tensor : is_bifunctor monoidal_opp_tensor_data.\n  Proof.\n    repeat split ; (try (intro ; intros) ; try apply (pr2 (monoidal_tensor M))).\n    exact (! bifunctor_equalwhiskers M a2 a1 b2 b1 f g).\n  Qed.\n\n  Definition monoidal_opp_tensor : bifunctor C^op C^op C^op\n    := monoidal_opp_tensor_data ,, monoidal_opp_is_tensor.\n\n  Definition monoidal_opp_data : monoidal_data C^op.\n  Proof.\n    exists monoidal_opp_tensor_data.\n    exists I_{M}.\n    exists luinv_{M}.\n    exists lu_{M}.\n    exists ruinv_{M}.\n    exists ru_{M}.\n    exists αinv_{M}.\n    exact α_{M}.\n  Defined.\n\n  Definition monoidal_opp_laws : monoidal_laws monoidal_opp_data.\n  Proof.\n    repeat split.\n    - intro ; intros.\n      apply (bifunctor_leftid M).\n    - intro ; intros.\n      apply (bifunctor_rightid M).\n    - intro ; intros.\n      apply (bifunctor_leftcomp M).\n    - intro ; intros.\n      apply (bifunctor_rightcomp M).\n    - intro ; intros.\n      exact (!(bifunctor_equalwhiskers M _ _ _ _ f g)).\n    - intro ; intros ; apply monoidal_leftunitorinvnat.\n    - apply (monoidal_leftunitorisolaw M).\n    - apply (monoidal_leftunitorisolaw M).\n    - intro ; intros ; apply monoidal_rightunitorinvnat.\n    - apply (monoidal_rightunitorisolaw M).\n    - apply (monoidal_rightunitorisolaw M).\n    - intro ; intros ; apply monoidal_associatorinvnatleft.\n    - intro ; intros ; apply monoidal_associatorinvnatright.\n    - intro ; intros ; apply monoidal_associatorinvnatleftright.\n    - apply (monoidal_associatorisolaw M).\n    - apply (monoidal_associatorlaw M).\n    - intro ; intros ; apply monoidal_triangle_identity_inv.\n    - intros w x y z.\n      refine (_ @ monoidal_pentagon_identity_inv M w x y z).\n      simpl ; apply assoc.\n  Qed.\n\n  Definition monoidal_opp : monoidal C^op\n    := monoidal_opp_data ,, monoidal_opp_laws.\nEnd OppositeMonoidal.\n\n(**\n 3. Equivalences from the tensor and unit\n *)\nSection EquivalenceFromTensorWithUnit.\n  Context {C : category} (M : monoidal C).\n\n  Import MonoidalNotations.\n\n  Definition ladjunction_data_from_tensor_with_unit\n    : adjunction_data C C.\n  Proof.\n    exists (leftwhiskering_functor M I_{M}).\n    exists (functor_identity C).\n    use tpair.\n    - apply (nat_z_iso_inv (leftunitor_nat_z_iso M)).\n    - apply (leftunitor_nat_z_iso M).\n  Defined.\n\n  Definition lequivalence_from_tensor_with_unit\n    : equivalence_of_cats C C.\n  Proof.\n    exists ladjunction_data_from_tensor_with_unit.\n    split.\n    - intro ; apply (nat_z_iso_inv (leftunitor_nat_z_iso M)).\n    - intro ; apply (leftunitor_nat_z_iso M).\n  Defined.\n\n  Definition radjunction_data_from_tensor_with_unit\n    : adjunction_data C C.\n  Proof.\n    exists (rightwhiskering_functor M I_{M}).\n    exists (functor_identity C).\n    use tpair.\n    - apply (nat_z_iso_inv (rightunitor_nat_z_iso M)).\n    - apply (rightunitor_nat_z_iso M).\n  Defined.\n\n  Definition requivalence_from_tensor_with_unit\n    : equivalence_of_cats C C.\n  Proof.\n    exists radjunction_data_from_tensor_with_unit.\n    split.\n    - intro ; apply (nat_z_iso_inv (rightunitor_nat_z_iso M)).\n    - intro ; apply (rightunitor_nat_z_iso M).\n  Defined.\n\n  Lemma leftwhiskering_fullyfaithful\n    : fully_faithful (leftwhiskering_functor M I_{M}).\n  Proof.\n    apply fully_faithful_from_equivalence.\n    exact (adjointificiation lequivalence_from_tensor_with_unit).\n  Defined.\n\n  Lemma rightwhiskering_fullyfaithful\n    : fully_faithful (rightwhiskering_functor M I_{M}).\n  Proof.\n    apply fully_faithful_from_equivalence.\n    exact (adjointificiation requivalence_from_tensor_with_unit).\n  Defined.\n\n  Lemma leftwhiskering_faithful\n    : faithful (leftwhiskering_functor M I_{M}).\n  Proof.\n    exact (pr2 (fully_faithful_implies_full_and_faithful _ _ _ leftwhiskering_fullyfaithful)).\n  Defined.\n\n  Lemma rightwhiskering_faithful\n    : faithful (rightwhiskering_functor M I_{M}).\n  Proof.\n    exact (pr2 (fully_faithful_implies_full_and_faithful _ _ _ rightwhiskering_fullyfaithful)).\n  Defined.\nEnd EquivalenceFromTensorWithUnit.\n\n(**\n 4. The unitors coincide\n *)\nSection UnitorsCoincide.\n  Context {C : category} (M : monoidal C).\n\n  Import MonoidalNotations.\n\n  Local Lemma lemma0 (x y : C) :\n    ((α_{M} I_{M} I_{M} x) ⊗^{M}_{r} y) · ((I_{M} ⊗^{M}_{l} lu_{M} x) ⊗^{M}_{r} y) =\n    (ru_{M} I_{M} ⊗^{M}_{r} x) ⊗^{M}_{r} y.\n  Proof.\n    refine (! bifunctor_rightcomp M _ _ _ _ _ _ @ _).\n    apply maponpaths.\n    apply (monoidal_triangleidentity M I_{M} x).\n  Qed.\n\n  Local Lemma lemma1 (x y : C) :\n    α_{M} I_{M} (I_{M} ⊗_{M} x) y · (I_{M} ⊗^{M}_{l} (lu_{M} x ⊗^{M}_{r} y)) =\n      ((I_{M} ⊗^{M}_{l} lu_{M} x) ⊗^{M}_{r} y) · α_{M} I_{M} x y.\n  Proof.\n    apply monoidal_associatornatleftright.\n  Qed.\n\n  Local Lemma lemma2 (x y : C) :\n    I_{M} ⊗^{M}_{l} (lu_{M} x ⊗^{M}_{r} y) = αinv_{M} I_{M} (I_{M} ⊗_{M} x) y · (((I_{M} ⊗^{M}_{l} lu_{M} x) ⊗^{M}_{r} y) · α_{M} I_{M} x y).\n  Proof.\n    set (αiso := make_z_iso _ _ (monoidal_associatorisolaw M  I_{ M} (I_{ M} ⊗_{ M} x) y)).\n    apply pathsinv0.\n    apply (z_iso_inv_on_right _ _ _ αiso).\n    apply pathsinv0.\n    apply lemma1.\n  Qed.\n\n  Local Lemma lemma2' (x y : C) :\n    (I_{M} ⊗^{M}_{l} lu_{M} x) ⊗^{M}_{r} y =\n      ((αinv_{M} I_{M} I_{M} x) ⊗^{M}_{r} y) · (ru_{M} I_{M} ⊗^{M}_{r} x) ⊗^{M}_{r} y.\n  Proof.\n    apply pathsinv0.\n    set (αiso := make_z_iso _ _ (monoidal_associatorisolaw M  I_{ M} I_{ M} x)).\n    set (αisor := functor_on_z_iso (rightwhiskering_functor M y) αiso).\n    apply (z_iso_inv_on_right _ _ _ αisor).\n    apply pathsinv0.\n    apply lemma0.\n  Qed.\n\n  Local Lemma lemma3 (x y : C) :\n    I_{M} ⊗^{M}_{l} (lu_{M} x ⊗^{M}_{r} y) =\n      αinv_{M} I_{M} (I_{M} ⊗_{M} x) y\n        · ((((αinv_{M} I_{M} I_{M} x) ⊗^{M}_{r} y)\n        · (ru_{M} I_{M} ⊗^{M}_{r} x) ⊗^{M}_{r} y)\n        · α_{M} I_{M} x y).\n  Proof.\n    refine (lemma2 x y @ _).\n    apply maponpaths.\n    apply maponpaths_2.\n    apply lemma2'.\n  Qed.\n\n  Local Lemma right_whisker_with_lunitor' (x y : C)\n    : I_{M} ⊗^{M}_{l} (lu_{M} x ⊗^{M}_{r} y)\n      =\n      I_{M} ⊗^{M}_{l} (α_{M} I_{M} x y · lu_{M} (x ⊗_{M} y)).\n  Proof.\n    refine (lemma3 x y @ _).\n    set (αiso := make_z_iso _ _ (monoidal_associatorisolaw M  I_{ M} (I_{ M} ⊗_{M} x) y)).\n    apply (z_iso_inv_on_right _ _ _ αiso).\n    set (αiso' := make_z_iso _ _ (monoidal_associatorisolaw M  I_{ M} I_{ M} x)).\n    set (αisor := functor_on_z_iso (rightwhiskering_functor M y) αiso').\n    etrans. { apply assoc'. }\n    apply (z_iso_inv_on_right _ _ _ αisor).\n    apply pathsinv0.\n    simpl.\n\n    etrans. { apply assoc. }\n    etrans.\n    {\n      apply maponpaths.\n      apply (bifunctor_leftcomp M _ _ _ _ _ _).\n    }\n\n    etrans. { apply assoc. }\n    etrans. {\n      apply maponpaths_2.\n      apply (monoidal_pentagonidentity M I_{M} I_{M} x y).\n    }\n\n    etrans.\n    2: {\n      apply (associatorlaw_natright (monoidal_associatorlaw M)).\n    }\n\n    etrans. { apply assoc'. }\n    apply maponpaths.\n    apply monoidal_triangleidentity.\n  Qed.\n\n  Lemma right_whisker_with_lunitor : triangle_identity' lu_{M} α_{M}.\n  Proof.\n    intros x y.\n    use faithful_reflects_commutative_triangle.\n    3: { apply leftwhiskering_faithful. }\n    apply pathsinv0.\n    refine (right_whisker_with_lunitor' _ _ @ _).\n    apply (bifunctor_leftcomp (monoidal_tensor M)).\n  Qed.\n\n  Definition monoidal_triangleidentity' := right_whisker_with_lunitor.\n\n  Lemma monoidal_triangle_identity'_inv (x y : C)\n  : luinv_{M} (x ⊗_{M} y) · αinv_{M} I_{M} x y = luinv_{M} x ⊗^{M}_{r} y.\n  Proof.\n    apply pathsinv0.\n    apply (z_iso_inv_on_left _ _ _ _ ((z_iso_from_associator_iso M _ _ _))).\n    cbn.\n    set (luix := make_z_iso _ _ (monoidal_leftunitorisolaw M x)).\n    set (luixy := functor_on_z_iso (rightwhiskering_functor M y) luix).\n    set (luipxy := make_z_iso _ _ (monoidal_leftunitorisolaw M (x ⊗_{ M} y))).\n    apply pathsinv0.\n    apply (z_iso_inv_on_right _ _ _ luixy).\n    apply (z_iso_inv_on_left _ _ _ _ luipxy).\n    exact (! monoidal_triangleidentity' x y).\n  Qed.\n\n  Lemma lunitor_preserves_leftwhiskering_with_unit\n    : lu^{M}_{I_{ M} ⊗_{M} I_{M}} = I_{M} ⊗^{ M}_{l} lu^{M}_{I_{ M}}.\n  Proof.\n    apply pathsinv0.\n    set (lun := monoidal_leftunitornat M _ _ (lu_{M} (I_{M}))).\n    etrans. { apply (! id_right _). }\n    etrans.\n    2: { apply id_right. }\n\n    etrans. {\n      apply maponpaths.\n      exact (! pr1 (monoidal_leftunitorisolaw M I_{ M})).\n    }\n    etrans. { apply assoc. }\n    etrans. { apply maponpaths_2 ; exact lun. }\n    etrans. { apply assoc'. }\n    apply maponpaths.\n    apply monoidal_leftunitorisolaw.\n  Qed.\n\n  Lemma unitors_coincide_on_unit'\n    : lu_{M} I_{M} ⊗^{M}_{r} I_{M} = ru_{M} I_{M} ⊗^{M}_{r} I_{M}.\n  Proof.\n    refine (! right_whisker_with_lunitor I_{M} I_{M} @ _).\n    refine (_ @ monoidal_triangleidentity M I_{M} I_{M}).\n    apply maponpaths.\n    apply lunitor_preserves_leftwhiskering_with_unit.\n  Qed.\n\n  Lemma unitors_coincide_on_unit\n    : lu_{M} I_{M} = ru_{M} I_{M}.\n  Proof.\n    refine (! id_right _ @ _).\n    use faithful_reflects_commutative_triangle.\n    3: { apply rightwhiskering_faithful. }\n    refine (_ @ unitors_coincide_on_unit').\n    etrans. {\n      apply maponpaths.\n      apply bifunctor_rightid.\n    }\n    apply id_right.\n  Qed.\n\n  Corollary unitorsinv_coincide_on_unit\n    : luinv_{M} I_{M} = ruinv_{M} I_{M}.\n  Proof.\n    apply (cancel_z_iso _ _ (lu_{M} I_{M},,(luinv_{M} I_{M},,monoidal_leftunitorisolaw M I_{M}))).\n    cbn.\n    etrans.\n    2: { rewrite unitors_coincide_on_unit.\n         apply pathsinv0, (monoidal_rightunitorisolaw M I_{M}). }\n    apply (monoidal_leftunitorisolaw M I_{M}).\n  Qed.\nEnd UnitorsCoincide.\n\n(* Using the lemma for a different category, hence outside of the section. *)\n\nSection UnitorsCoincideAlternative.\n  Import MonoidalNotations.\n\n  Lemma unitorsinv_coincide_on_unit_alt {C : category} (M : monoidal C)\n    : luinv_{M} I_{M} = ruinv_{M} I_{M}.\n  Proof.\n    exact (unitors_coincide_on_unit (monoidal_opp M)).\n  Qed.\nEnd UnitorsCoincideAlternative.\n\n(**\n 5. Swapping the tensor\n *)\nSection MonoidalSwapped.\n  Import MonoidalNotations.\n\n  Definition tensor_swapped {V : category} (Mon_V : monoidal V)\n    : tensor_data V.\n  Proof.\n    repeat (use tpair).\n    - intros v w.\n      exact (w ⊗_{Mon_V} v).\n    - intros v w1 w2 f.\n      exact (f ⊗^{Mon_V}_{r} v).\n    - intros v w1 w2 f.\n      exact (v ⊗^{Mon_V}_{l} f).\n  Defined.\n\n  Definition monoidal_swapped_data {V : category} (Mon_V : monoidal V)\n    : monoidal_data V.\n  Proof.\n    exists (tensor_swapped Mon_V).\n    exists I_{Mon_V}.\n    exists (λ v, ru_{Mon_V} v).\n    exists (λ v, ruinv_{Mon_V} v).\n    exists (λ v, lu_{Mon_V} v).\n    exists (λ v, luinv_{Mon_V} v).\n    exists (λ v1 v2 v3, αinv_{Mon_V} v3 v2 v1).\n    exact (λ v1 v2 v3, α_{Mon_V} v3 v2 v1).\n  Defined.\n\n  Lemma monoidal_swapped_laws {V : category} (Mon_V : monoidal V)\n    : monoidal_laws (monoidal_swapped_data Mon_V).\n  Proof.\n    repeat split.\n    - intro ; intro ; apply (bifunctor_rightid Mon_V).\n    - intro ; intro ; apply (bifunctor_leftid Mon_V).\n    - intro ; intros ; apply (bifunctor_rightcomp Mon_V).\n    - intro ; intros ; apply (bifunctor_leftcomp Mon_V).\n    - intro ; intros ; apply (! bifunctor_equalwhiskers Mon_V _ _ _ _ _ _).\n    - intro ; intros ; apply monoidal_rightunitornat.\n    - apply monoidal_rightunitorisolaw.\n    - apply monoidal_rightunitorisolaw.\n    - intro ; intros ; apply monoidal_leftunitornat.\n    - apply monoidal_leftunitorisolaw.\n    - apply monoidal_leftunitorisolaw.\n    - intro ; intros ; apply (! monoidal_associatorinvnatright Mon_V _ _ _ _ _).\n    - intro ; intros ; apply (! monoidal_associatorinvnatleft Mon_V _ _ _ _ _).\n    - intro ; intros ; apply (! monoidal_associatorinvnatleftright Mon_V _ _ _ _ _).\n    - apply monoidal_associatorisolaw.\n    - apply monoidal_associatorisolaw.\n    - intro ; intros.\n      cbn.\n      rewrite (! monoidal_triangleidentity Mon_V _ _).\n      rewrite assoc.\n      rewrite (pr2 (monoidal_associatorisolaw Mon_V _ _ _)).\n      apply id_left.\n    - intro ; intros ; apply monoidal_pentagon_identity_inv.\n  Qed.\n\n  Definition monoidal_swapped {V : category} (Mon_V : monoidal V)\n    : monoidal V\n    := monoidal_swapped_data Mon_V ,, monoidal_swapped_laws Mon_V.\nEnd MonoidalSwapped.\n\n(**\n 6. More monoidal laws\n *)\nSection MonoidalLaws.\n  Import MonoidalNotations.\n\n  Lemma left_whisker_with_runitor {C : category} (M : monoidal C)\n    : triangle_identity'' ru_{M} α_{M}.\n  Proof.\n    red; intros x y.\n    assert (aux := right_whisker_with_lunitor (monoidal_swapped M) y x).\n    cbn in aux.\n    rewrite <- aux.\n    rewrite assoc.\n    etrans.\n    { apply cancel_postcomposition.\n      apply monoidal_associatorisolaw. }\n    apply id_left.\n  Qed.\n\n  Lemma monoidal_triangle_identity''_inv {C : category} (M : monoidal C) (x y : C)\n    : x ⊗^{M}_{l} (ruinv_{M} y) · αinv_{M} x y I_{M} = ruinv_{M} (x ⊗_{M} y).\n  Proof.\n    apply pathsinv0.\n    apply (z_iso_inv_on_left _ _ _ _ ((z_iso_from_associator_iso M _ _ _))).\n    cbn.\n    set (ruiy := make_z_iso _ _ (monoidal_rightunitorisolaw M y)).\n    set (ruiyx := functor_on_z_iso (leftwhiskering_functor M x) ruiy).\n    set (ruipxy := make_z_iso _ _ (monoidal_rightunitorisolaw M (x ⊗_{ M} y))).\n    apply pathsinv0.\n    apply (z_iso_inv_on_right _ _ _ ruipxy).\n    apply (z_iso_inv_on_left _ _ _ _ ruiyx).\n    exact (! (left_whisker_with_runitor M) x y).\n  Qed.\nEnd MonoidalLaws.\n\n(**\n 7. Bundled approach to monoidal categories\n *)\n(** Accessors and notations for monoidal categories *)\nDeclare Scope moncat.\nLocal Open Scope moncat.\n\nDefinition monoidal_cat : UU := ∑ (C : category), monoidal C.\n\nCoercion monoidal_cat_to_cat (V : monoidal_cat) : category := pr1 V.\nCoercion monoidal_cat_to_monoidal (V : monoidal_cat) : monoidal V := pr2 V.\n\nDefinition monoidal_cat_tensor_pt\n           {V : monoidal_cat}\n           (x y : V)\n  : V\n  := x ⊗_{ pr2 V } y.\n\nNotation \"x ⊗ y\" :=  (monoidal_cat_tensor_pt x y) : moncat.\n\nDefinition monoidal_cat_tensor_mor\n           {V : monoidal_cat}\n           {x₁ x₂ y₁ y₂ : V}\n           (f : x₁ --> x₂)\n           (g : y₁ --> y₂)\n  : x₁ ⊗ y₁ --> x₂ ⊗ y₂\n  := f ⊗^{ pr2 V } g.\n\nNotation \"f #⊗ g\" := (monoidal_cat_tensor_mor f g) (at level 31) : moncat.\n\nSection MonoidalCatAccessors.\n  Context {V : monoidal_cat}.\n\n  Import MonoidalNotations.\n\n  Definition tensor_id_id\n             (x y : V)\n    : identity x #⊗ identity y = identity (x ⊗ y).\n  Proof.\n    apply bifunctor_distributes_over_id.\n    - apply (bifunctor_leftid V).\n    - apply (bifunctor_rightid V).\n  Qed.\n\n  Definition tensor_comp_mor\n             {x₁ x₂ x₃ y₁ y₂ y₃ : V}\n             (f : x₁ --> x₂) (f' : x₂ --> x₃)\n             (g : y₁ --> y₂) (g' : y₂ --> y₃)\n    : (f · f') #⊗ (g · g') = f #⊗ g · f' #⊗ g'.\n  Proof.\n    use bifunctor_distributes_over_comp.\n    - apply (bifunctor_leftcomp V).\n    - apply (bifunctor_rightcomp V).\n    - apply (bifunctor_equalwhiskers V).\n  Qed.\n\n  Definition tensor_comp_id_l\n             {x y₁ y₂ y₃ : V}\n             (g : y₁ --> y₂) (g' : y₂ --> y₃)\n    : (identity x) #⊗ (g · g') = (identity x) #⊗ g · (identity x) #⊗ g'.\n  Proof.\n    rewrite <- tensor_comp_mor.\n    rewrite id_left.\n    apply idpath.\n  Qed.\n\n  Definition tensor_comp_l_id_l\n             {x₁ x₂ y₁ y₂ y₃ : V}\n             (f : x₁ --> x₂)\n             (g : y₁ --> y₂) (g' : y₂ --> y₃)\n    : f #⊗ (g · g') = (identity _) #⊗ g · f #⊗ g'.\n  Proof.\n    rewrite <- tensor_comp_mor.\n    rewrite id_left.\n    apply idpath.\n  Qed.\n\n  Definition tensor_comp_l_id_r\n             {x₁ x₂ y₁ y₂ y₃ : V}\n             (f : x₁ --> x₂)\n             (g : y₁ --> y₂) (g' : y₂ --> y₃)\n    : f #⊗ (g · g') = f #⊗ g · (identity _) #⊗ g'.\n  Proof.\n    rewrite <- tensor_comp_mor.\n    rewrite id_right.\n    apply idpath.\n  Qed.\n\n  Definition tensor_comp_id_r\n             {x₁ x₂ x₃ y : V}\n             (f : x₁ --> x₂) (f' : x₂ --> x₃)\n    : (f · f') #⊗ (identity y) = f #⊗ (identity y) · f' #⊗ (identity y).\n  Proof.\n    rewrite <- tensor_comp_mor.\n    rewrite id_left.\n    apply idpath.\n  Qed.\n\n  Definition tensor_comp_r_id_l\n             {x₁ x₂ x₃ y₁ y₂ : V}\n             (f : x₁ --> x₂) (f' : x₂ --> x₃)\n             (g : y₁ --> y₂)\n    : (f · f') #⊗ g = f #⊗ (identity _) · f' #⊗ g.\n  Proof.\n    rewrite <- tensor_comp_mor.\n    rewrite id_left.\n    apply idpath.\n  Qed.\n\n  Definition tensor_comp_r_id_r\n             {x₁ x₂ x₃ y₁ y₂ : V}\n             (f : x₁ --> x₂) (f' : x₂ --> x₃)\n             (g : y₁ --> y₂)\n    : (f · f') #⊗ g = f #⊗ g · f' #⊗ (identity _).\n  Proof.\n    rewrite <- tensor_comp_mor.\n    rewrite id_right.\n    apply idpath.\n  Qed.\n\n  Definition tensor_split\n             {x₁ x₂ y₁ y₂ : V}\n             (f : x₁ --> x₂)\n             (g : y₁ --> y₂)\n    : f #⊗ g = identity _ #⊗ g · f #⊗ identity _.\n  Proof.\n    refine (_ @ tensor_comp_mor _ _ _ _).\n    rewrite id_left, id_right.\n    apply idpath.\n  Qed.\n\n  Definition tensor_split'\n             {x₁ x₂ y₁ y₂ : V}\n             (f : x₁ --> x₂)\n             (g : y₁ --> y₂)\n    : f #⊗ g = f #⊗ identity _ · identity _ #⊗ g.\n  Proof.\n    refine (_ @ tensor_comp_mor _ _ _ _).\n    rewrite id_left, id_right.\n    apply idpath.\n  Qed.\n\n  Definition tensor_swap\n             {x₁ x₂ y₁ y₂ : V}\n             (f : x₁ --> x₂)\n             (g : y₁ --> y₂)\n    : f #⊗ identity _ · identity _ #⊗ g = identity _ #⊗ g · f #⊗ identity _.\n  Proof.\n    rewrite <- tensor_split, <- tensor_split'.\n    apply idpath.\n  Qed.\n\n  Definition tensor_swap'\n             {x₁ x₂ y₁ y₂ : V}\n             (f : x₁ --> x₂)\n             (g : y₁ --> y₂)\n    : identity _ #⊗ g · f #⊗ identity _ = f #⊗ identity _ · identity _ #⊗ g.\n  Proof.\n    rewrite <- tensor_split, <- tensor_split'.\n    apply idpath.\n  Qed.\n\n  Definition mon_lunitor\n             (x : V)\n    : I_{V} ⊗ x --> x\n    := monoidal_leftunitordata V x.\n\n  Definition tensor_lunitor\n             {x y : V}\n             (f : x --> y)\n    : identity _ #⊗ f · mon_lunitor y\n      =\n      mon_lunitor x · f.\n  Proof.\n    refine (_ @ pr1 (monoidal_leftunitorlaw V) x y f).\n    apply maponpaths_2.\n    unfold monoidal_cat_tensor_mor.\n    unfold functoronmorphisms1.\n    refine (_ @ id_left _).\n    apply maponpaths_2.\n    apply (bifunctor_rightid V).\n  Qed.\n\n  Definition mon_linvunitor\n             (x : V)\n    : x --> I_{V} ⊗ x\n    := monoidal_leftunitorinvdata V x.\n\n  Definition tensor_linvunitor\n             {x y : V}\n             (f : x --> y)\n    : f · mon_linvunitor y\n      =\n      mon_linvunitor x · identity _ #⊗ f.\n  Proof.\n    refine (!(monoidal_leftunitorinvnat V x y f) @ _).\n    apply maponpaths.\n    unfold monoidal_cat_tensor_mor.\n    unfold functoronmorphisms1.\n    refine (!(id_left _) @ _).\n    apply maponpaths_2.\n    refine (!_).\n    apply (bifunctor_rightid V).\n  Qed.\n\n  Definition mon_lunitor_linvunitor\n             (x : V)\n    : mon_lunitor x · mon_linvunitor x = identity _.\n  Proof.\n    exact (pr1 (monoidal_leftunitorisolaw V x)).\n  Qed.\n\n  Definition mon_linvunitor_lunitor\n             (x : V)\n    : mon_linvunitor x · mon_lunitor x = identity _.\n  Proof.\n    exact (pr2 (monoidal_leftunitorisolaw V x)).\n  Qed.\n\n  Definition mon_runitor\n             (x : V)\n    : x ⊗ I_{V} --> x\n    := monoidal_rightunitordata V x.\n\n  Definition tensor_runitor\n             {x y : V}\n             (f : x --> y)\n    : f #⊗ identity _ · mon_runitor y\n      =\n      mon_runitor x · f.\n  Proof.\n    refine (_ @ pr1 (monoidal_rightunitorlaw V) x y f).\n    apply maponpaths_2.\n    unfold monoidal_cat_tensor_mor.\n    unfold functoronmorphisms1.\n    refine (_ @ id_right _).\n    apply maponpaths.\n    apply (bifunctor_leftid V).\n  Qed.\n\n  Definition mon_rinvunitor\n             (x : V)\n    : x --> x ⊗ I_{V}\n    := monoidal_rightunitorinvdata V x.\n\n  Definition tensor_rinvunitor\n             {x y : V}\n             (f : x --> y)\n    : f · mon_rinvunitor y\n      =\n      mon_rinvunitor x · f #⊗ identity _.\n  Proof.\n    refine (!(monoidal_rightunitorinvnat V x y f) @ _).\n    apply maponpaths.\n    unfold monoidal_cat_tensor_mor.\n    unfold functoronmorphisms1.\n    refine (!(id_right _) @ _).\n    apply maponpaths.\n    refine (!_).\n    apply (bifunctor_leftid V).\n  Qed.\n\n  Definition mon_runitor_rinvunitor\n             (x : V)\n    : mon_runitor x · mon_rinvunitor x = identity _.\n  Proof.\n    exact (pr1 (monoidal_rightunitorisolaw V x)).\n  Qed.\n\n  Definition mon_rinvunitor_runitor\n             (x : V)\n    : mon_rinvunitor x · mon_runitor x = identity _.\n  Proof.\n    exact (pr2 (monoidal_rightunitorisolaw V x)).\n  Qed.\n\n  Definition mon_lassociator\n             (x y z : V)\n    : (x ⊗ y) ⊗ z --> x ⊗ (y ⊗ z)\n    := α_{ V } x y z.\n\n  Definition tensor_lassociator\n             {x₁ x₂ y₁ y₂ z₁ z₂ : V}\n             (f : x₁ --> x₂)\n             (g : y₁ --> y₂)\n             (h : z₁ --> z₂)\n    : (f #⊗ g) #⊗ h · mon_lassociator _ _ _\n      =\n      mon_lassociator _ _ _ · f #⊗ (g #⊗ h).\n  Proof.\n    refine (!_).\n    apply associator_nat2.\n  Qed.\n\n  Definition mon_rassociator\n             (x y z : V)\n    : x ⊗ (y ⊗ z) --> (x ⊗ y) ⊗ z\n    := αinv_{ V } x y z.\n\n  Definition tensor_rassociator\n             {x₁ x₂ y₁ y₂ z₁ z₂ : V}\n             (f : x₁ --> x₂)\n             (g : y₁ --> y₂)\n             (h : z₁ --> z₂)\n    : f #⊗ (g #⊗ h) · mon_rassociator _ _ _\n      =\n      mon_rassociator _ _ _ · (f #⊗ g) #⊗ h.\n  Proof.\n    exact (monoidal_associatorinv_nat2 V f g h).\n  Qed.\n\n  Definition mon_lassociator_rassociator\n             (x y z : V)\n    : mon_lassociator x y z · mon_rassociator x y z = identity _.\n  Proof.\n    exact (pr1 (monoidal_associatorisolaw V x y z)).\n  Qed.\n\n  Definition mon_rassociator_lassociator\n             (x y z : V)\n    : mon_rassociator x y z · mon_lassociator x y z = identity _.\n  Proof.\n    exact (pr2 (monoidal_associatorisolaw V x y z)).\n  Qed.\n\n  Definition mon_triangle\n             (x y : V)\n    : mon_runitor x #⊗ identity y\n      =\n      mon_lassociator x I_{V} y · (identity x #⊗ mon_lunitor y).\n  Proof.\n    refine (_ @ !(monoidal_triangleidentity V x y) @ _).\n    - unfold monoidal_cat_tensor_mor.\n      unfold functoronmorphisms1.\n      refine (_ @ id_right _).\n      apply maponpaths.\n      apply (bifunctor_leftid V).\n    - apply maponpaths.\n      unfold monoidal_cat_tensor_mor.\n      unfold functoronmorphisms1.\n      refine (!(id_left _) @ _).\n      apply maponpaths_2.\n      refine (!_).\n      apply (bifunctor_rightid V).\n  Qed.\n\n  Definition mon_inv_triangle\n             (x y : V)\n    : identity x #⊗ mon_linvunitor y\n      =\n      mon_rinvunitor x #⊗ identity y · mon_lassociator x (I_{V}) y.\n  Proof.\n    refine (!_).\n    etrans.\n    {\n      apply maponpaths_2.\n      refine (_ @ !(monoidal_triangle_identity_inv V x y)).\n      unfold monoidal_cat_tensor_mor.\n      unfold functoronmorphisms1.\n      refine (_ @ id_right _).\n      apply maponpaths.\n      apply (bifunctor_leftid V).\n    }\n    rewrite !assoc'.\n    etrans.\n    {\n      apply maponpaths.\n      apply mon_rassociator_lassociator.\n    }\n    unfold monoidal_cat_tensor_mor.\n    unfold functoronmorphisms1.\n    rewrite (whiskerscommutes V).\n    - apply maponpaths.\n      refine (!_).\n      apply (bifunctor_rightid V).\n    - apply (bifunctor_equalwhiskers V).\n  Qed.\n\n  Definition mon_lunitor_triangle\n             (x y : V)\n    : mon_lassociator (I_{V}) x y · mon_lunitor (x ⊗ y)\n      =\n      mon_lunitor x #⊗ identity y.\n  Proof.\n    refine (right_whisker_with_lunitor V x y @ _).\n    unfold monoidal_cat_tensor_mor.\n    unfold functoronmorphisms1.\n    refine (!(id_right _) @ _).\n    apply maponpaths.\n    refine (!_).\n    apply (bifunctor_leftid V).\n  Qed.\n\n  Definition mon_linvunitor_triangle\n             (x y : V)\n    : mon_linvunitor x #⊗ identity y · mon_lassociator (I_{V}) x y\n      =\n      mon_linvunitor (x ⊗ y).\n  Proof.\n    refine (!(id_right _) @ _).\n    etrans.\n    {\n      apply maponpaths.\n      exact (!(mon_lunitor_linvunitor _)).\n    }\n    rewrite !assoc'.\n    etrans.\n    {\n      apply maponpaths.\n      rewrite !assoc.\n      apply maponpaths_2.\n      apply mon_lunitor_triangle.\n    }\n    rewrite !assoc.\n    refine (_ @ id_left _).\n    apply maponpaths_2.\n    rewrite <- tensor_comp_id_r.\n    rewrite mon_linvunitor_lunitor.\n    apply tensor_id_id.\n  Qed.\n\n  Definition mon_runitor_triangle\n             (x y : V)\n    : mon_rassociator x y (I_{V}) · mon_runitor (x ⊗ y)\n      =\n      identity x #⊗ mon_runitor y.\n  Proof.\n    etrans.\n    {\n      apply maponpaths.\n      exact (!(left_whisker_with_runitor V x y)).\n    }\n    rewrite !assoc.\n    etrans.\n    {\n      apply maponpaths_2.\n      apply mon_rassociator_lassociator.\n    }\n    rewrite id_left.\n    unfold monoidal_cat_tensor_mor.\n    unfold functoronmorphisms1.\n    refine (!(id_left _) @ _).\n    apply maponpaths_2.\n    refine (!_).\n    apply (bifunctor_rightid V).\n  Qed.\n\n  Definition mon_rinvunitor_triangle\n             (x y : V)\n    : identity x #⊗ mon_rinvunitor y · mon_rassociator x y (I_{V})\n      =\n      mon_rinvunitor (x ⊗ y).\n  Proof.\n    refine (!(id_right _) @ _).\n    etrans.\n    {\n      apply maponpaths.\n      exact (!(mon_runitor_rinvunitor _)).\n    }\n    rewrite !assoc'.\n    etrans.\n    {\n      apply maponpaths.\n      rewrite !assoc.\n      apply maponpaths_2.\n      apply mon_runitor_triangle.\n    }\n    rewrite !assoc.\n    refine (_ @ id_left _).\n    apply maponpaths_2.\n    rewrite <- tensor_comp_id_l.\n    rewrite mon_rinvunitor_runitor.\n    apply tensor_id_id.\n  Qed.\n\n  Definition mon_runitor_I_mon_lunitor_I\n    : mon_runitor (I_{V}) = mon_lunitor (I_{V}).\n  Proof.\n    refine (!_).\n    apply unitors_coincide_on_unit.\n  Qed.\n\n  Definition mon_lunitor_I_mon_runitor_I\n    : mon_lunitor (I_{V}) = mon_runitor (I_{V}).\n  Proof.\n    rewrite mon_runitor_I_mon_lunitor_I.\n    apply idpath.\n  Qed.\n\n  Definition mon_rinvunitor_I_mon_linvunitor_I\n    : mon_rinvunitor (I_{V}) = mon_linvunitor (I_{V}).\n  Proof.\n    cbn.\n    refine (!_).\n    apply unitorsinv_coincide_on_unit.\n  Qed.\n\n  Definition mon_linvunitor_I_mon_rinvunitor_I\n    : mon_linvunitor (I_{V}) = mon_rinvunitor (I_{V}).\n  Proof.\n    rewrite mon_rinvunitor_I_mon_linvunitor_I.\n    apply idpath.\n  Qed.\n\n  Proposition mon_lassociator_lassociator\n              {w x y z : V}\n    : mon_lassociator (w ⊗ x) y z\n      · mon_lassociator w x (y ⊗ z)\n      =\n      mon_lassociator w x y #⊗ identity z\n      · mon_lassociator w (x ⊗ y) z\n      · identity w #⊗ mon_lassociator x y z.\n  Proof.\n    refine (!(monoidal_pentagonidentity V w x y z) @ _).\n    unfold monoidal_cat_tensor_mor.\n    unfold functoronmorphisms1.\n    rewrite (bifunctor_rightid V).\n    rewrite (bifunctor_leftid V).\n    rewrite !id_left, id_right.\n    apply idpath.\n  Qed.\n\n  Proposition mon_rassociator_rassociator\n              {w x y z : V}\n    : mon_rassociator w x (y ⊗ z)\n      · mon_rassociator (w ⊗ x) y z\n      =\n      identity w #⊗ mon_rassociator x y z\n      · mon_rassociator w (x ⊗ y) z\n      · mon_rassociator w x y #⊗ identity z.\n  Proof.\n    refine (!(monoidal_pentagon_identity_inv V w x y z) @ _).\n    unfold monoidal_cat_tensor_mor.\n    unfold functoronmorphisms1.\n    rewrite (bifunctor_rightid V).\n    rewrite (bifunctor_leftid V).\n    rewrite !id_left, id_right.\n    apply idpath.\n  Qed.\n\n  Definition monoidal_left_tensor_data\n             (x : V)\n    : functor_data V V.\n  Proof.\n    use make_functor_data.\n    - exact (λ y, x ⊗ y).\n    - exact (λ y₁ y₂ f, identity x #⊗ f).\n  Defined.\n\n  Proposition is_functor_monoidal_left_tensor\n              (x : V)\n    : is_functor (monoidal_left_tensor_data x).\n  Proof.\n    split.\n    - intros y ; cbn.\n      apply tensor_id_id.\n    - intros y₁ y₂ y₃ f g ; cbn.\n      apply tensor_comp_id_l.\n  Qed.\n\n  Definition monoidal_left_tensor\n             (x : V)\n    : V ⟶ V.\n  Proof.\n    use make_functor.\n    - exact (monoidal_left_tensor_data x).\n    - exact (is_functor_monoidal_left_tensor x).\n  Defined.\n\n  Definition monoidal_right_tensor_data\n             (y : V)\n    : functor_data V V.\n  Proof.\n    use make_functor_data.\n    - exact (λ x, x ⊗ y).\n    - exact (λ x₁ x₂ f, f #⊗ identity y).\n  Defined.\n\n  Proposition is_functor_monoidal_right_tensor\n              (y : V)\n    : is_functor (monoidal_right_tensor_data y).\n  Proof.\n    split.\n    - intros x ; cbn.\n      apply tensor_id_id.\n    - intros x₁ x₂ x₃ f g ; cbn.\n      apply tensor_comp_id_r.\n  Qed.\n\n  Definition monoidal_right_tensor\n             (y : V)\n    : V ⟶ V.\n  Proof.\n    use make_functor.\n    - exact (monoidal_right_tensor_data y).\n    - exact (is_functor_monoidal_right_tensor y).\n  Defined.\nEnd MonoidalCatAccessors.\n\nDefinition monoidal_cat_tensor_data\n           (V : monoidal_cat)\n  : functor_data (category_binproduct V V) V.\nProof.\n  use make_functor_data.\n  - exact (λ x, pr1 x ⊗ pr2 x).\n  - exact (λ x y f, pr1 f #⊗ pr2 f).\nDefined.\n\nProposition is_functor_monoidal_cat_tensor\n            (V : monoidal_cat)\n  : is_functor (monoidal_cat_tensor_data V).\nProof.\n  split.\n  - intro x ; cbn.\n    apply tensor_id_id.\n  - intros x y z f g ; cbn.\n    apply tensor_comp_mor.\nQed.\n\nDefinition monoidal_cat_tensor\n           (V : monoidal_cat)\n  : category_binproduct V V ⟶ V.\nProof.\n  use make_functor.\n  - exact (monoidal_cat_tensor_data V).\n  - exact (is_functor_monoidal_cat_tensor V).\nDefined.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/CategoryTheory/Monoidal/Categories.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6711265530149726}}
{"text": "Require Export Coq.Sorting.Permutation. \nRequire Export Omega.   \nRequire Export List. \nExport ListNotations. \nRequire Export hetList. \nRequire Import ZArith.\nOpen Scope Z_scope.\n\n(*looks nicer in unicode*)\nDefinition int := Z. \n\nFixpoint sum (l : list int) : int := \n  match l with\n      |hd::tl => hd + sum tl\n      |List.nil => 0\n  end. \n\n(*split L l1 l2: L is composed of l1 and l2*)\nInductive split : list int -> list int -> list int -> Prop :=\n|splitNil : split nil nil nil\n|splitConsL : forall a x b1 b2 c,\n                split a (b1++b2) c ->\n                split (x::a) (b1++x::b2) c\n|splitConsR : forall a x b c1 c2,\n                split a b (c1++c2) ->\n                split (x::a) b (c1++x::c2). \n\nInductive partition (k:int) (l:list int) : Prop :=\n|partition_ : forall (l1 l2 : list int), \n                sum l = k * 2 -> split l l1 l2 ->\n                sum l1 = k -> sum l2 = k -> partition k l. \n\n(*triple of integers*)\nDefinition vote : Type := prod (prod int int) int. \n\nDefinition add_votes v1 v2 :=\n  match v1, v2 with\n      |(a,b,c), (d,e,f) => (a+d,b+e,c+f)\n  end. \n\nFixpoint score_votes vs :=\n  match vs with\n      |v::vs => add_votes v (score_votes vs)\n      |nil => (0,0,0)\n  end. \n\n(*The convention here is that the first position corresponds to the \n**candidate the manipulators want to win << p, a, b >> *)\nInductive p_wins : vote -> Prop :=\n|p_wins_ : forall p a b, p > a -> p > b -> p_wins(p, a, b). \n\n(*make a vote of weight 6k*)\nInductive mkVote k : vote -> Prop :=\n|favor_a : mkVote k (k*12, k*6, 0)\n|favor_b : mkVote k (k*12, 0, k*6).\n\n(*construct a list of votes given a list of weights*)\nInductive mkVotes : list int -> list vote -> Prop :=\n|mkVotesNil : mkVotes nil nil\n|mkVotesNonNil : forall ks vs k v, \n                   mkVotes ks vs -> mkVote k v ->\n                   mkVotes (k::ks) (v::vs). \n\n(*base_vote is the vote of the non manipulator.  \n**weights are the weights of the manipulators*)\nInductive manipulate (base_vote : vote) (weights : list int) : Prop := \n|manipulate_ : forall votes, \n                 mkVotes weights votes -> \n                 p_wins (score_votes (base_vote::votes)) ->\n                 manipulate base_vote weights. \n\nDefinition reduce k (l:list int) := ((0,k*18-3,k*18-3), l). \n\nLtac inv H := inversion H; subst; clear H. \n\nLtac copy H :=\n  match type of H with\n      |?x => assert(x) by auto\n  end. \n\nLtac invertHyp := \n  match goal with\n      |H:exists x, ?P |- _ => inv H; try invertHyp \n      |H:?A /\\ ?B |- _ => inv H; try invertHyp\n  end. \n\nTheorem sumRemoveMid : forall a b c k, sum (a++b::c) = k -> \n                                  sum (a++c) = k - b. \nProof.\n  induction a; intros. \n  {simpl in *. symmetry in H. apply Zplus_minus_eq in H. auto. }\n  {simpl in *. symmetry in H. apply Zplus_minus_eq in H. eapply IHa in H. \n   rewrite H. rewrite Z.add_sub_assoc. rewrite Zplus_minus. auto. }\nQed. \n\nLtac votesEq :=\n  match goal with\n      | |- (?a,?b,?c)=(?a,?b,?f) =>\n        let n := fresh \n        in assert(n:c=f) by omega; rewrite n; try votesEq\n      | |- (?a,?b,?c)=(?a,?e,?f) =>\n        let n := fresh \n        in assert(n:b=e) by omega; rewrite n; try votesEq\n      | |- (?a,?b,?c)=(?d,?e,?f) =>\n        let n := fresh \n        in assert(n:a=d) by omega; rewrite n; try votesEq\n      | |- _ => eauto\n  end. \n\nTheorem mkVotesSum : forall weights l1 l2 k1 k2,\n                       sum l1 = k1 -> sum l2 = k2 -> split weights l1 l2 ->\n                       exists vs, mkVotes weights vs /\\ \n                             score_votes vs = ((k1+k2)*12, k2*6, k1*6). \nProof.\n  intros. genDeps {{ k1; k2 }}. induction H1; intros. \n  {simpl in *. subst. exists nil. simpl. repeat constructor. }\n  {apply sumRemoveMid in H. eapply IHsplit in H; eauto. invertHyp.\n   exists ((x*12,0,x*6)::x0). split. constructor. auto. constructor.\n   simpl. rewrite H0. votesEq. }\n  {apply sumRemoveMid in H0. eapply IHsplit in H0; eauto. invertHyp.\n   exists ((x*12,x*6,0)::x0). split. constructor. auto. constructor.\n   simpl. rewrite H0. votesEq. }\nQed. \n\nTheorem score_votes_total : forall vs, \n                              exists s1 s2 s3, score_votes vs = (s1,s2,s3). \nProof.\n  induction vs.\n  {exists 0. exists 0. exists 0. simpl. auto. }\n  {destruct a. destruct p. invertHyp. repeat econstructor. \n   simpl. rewrite H. auto. }\nQed. \n\nTheorem add_votesSub : forall k1 k2 k3 vs s1 s2 s3, \n                         add_votes (k1,k2,k3) vs = (s1,s2,s3) ->\n                         vs = (s1-k1,s2-k2,s3-k3). \nProof.\n  intros. simpl in *. destruct vs. destruct p. inv H. \n  repeat (rewrite <- Z.add_sub_assoc; rewrite Zplus_minus). auto. \nQed. \n\nDefinition multOf x k := exists y, y * k = x. \n\nTheorem mustBe24K : forall weights k votes s1 s2 s3, \n                 sum weights = k  ->\n                 mkVotes weights votes -> \n                 score_votes votes = (s1,s2,s3) -> \n                 s1  = k * 12 /\\ (s2 + s3) * 2 = s1 /\\ multOf s2 6 /\\ multOf s3 6. \nProof.\n  intros. genDeps {{ k; s1; s2; s3 }}. induction H0; intros. \n  {simpl in *. inv H1. split; auto. split; auto. unfold multOf.\n   split; exists 0; auto. }\n  {simpl in *. symmetry in H2. apply Zplus_minus_eq in H2. inv H.\n   {apply add_votesSub in H1. eapply IHmkVotes in H1; eauto. invertHyp. \n    unfold multOf in *. invertHyp. split. omega. split. omega. split. \n    exists (x0+k). omega. exists x. omega. }\n   {apply add_votesSub in H1. eapply IHmkVotes in H1; eauto. split. omega. split. \n    omega. unfold multOf in *. invertHyp. split. exists x0. omega. exists (x+k). omega. }\n  }\nQed. \n\nLtac solveByInv := \n  match goal with\n      |H:_ |- _ => solve[inv H]\n  end. \n\nTheorem weightsToVotes : forall votes weights s1 s2 s3, \n                  mkVotes weights votes ->\n                  score_votes votes = (s1,s2,s3) ->\n                  exists l1 l2, split weights l1 l2 /\\ sum l1 * 6 = s2 /\\ sum l2 * 6 = s3. \nProof.\n  intros. genDeps {{ s1; s2; s3 }}. induction H; intros. \n  {simpl in H0. inv H0. exists nil. exists nil. split. constructor. auto. }\n  {simpl in H1. inv H0. \n   {apply add_votesSub in H1. eapply IHmkVotes in H1. invertHyp. \n    exists (nil++k::x). exists x0. split. constructor. simpl. auto. simpl. \n    split; omega. }\n   {apply add_votesSub in H1. eapply IHmkVotes in H1. invertHyp. \n     exists x. exists (nil++k::x0). split. constructor. simpl. auto. simpl. \n    split; omega. }\n  }\nQed. \n\nTheorem veto_npc : forall l k nonManipVote weights,\n                     reduce k l = (nonManipVote, weights) -> sum l = k*2 ->\n                     (partition k l <-> manipulate nonManipVote weights). \nProof.\n  intros. split; intros. \n  {unfold reduce in H. inv H. inversion H1. eapply mkVotesSum in H2; eauto. \n   invertHyp. econstructor. eauto. simpl. rewrite H3. constructor; omega. }\n  {unfold reduce in *. inv H. inv H1.  \n   assert(exists s1 s2 s3, score_votes votes = (s1,s2,s3)). apply score_votes_total. \n   invertHyp. simpl in H2. rewrite H3 in H2. inv H2. copy H0. \n   eapply mustBe24K in H1; eauto. invertHyp. unfold multOf in *. invertHyp.  \n   assert(x1 <= k). omega. assert(x <= k). omega. rewrite <- Z.mul_assoc in H1. \n   simpl in H1. assert((x1+x) = k * 2). omega. assert(x1=k /\\ x=k). omega. invertHyp.\n   eapply weightsToVotes in H; eauto. invertHyp. econstructor; eauto. \n   erewrite Z.mul_cancel_r in H; auto.  omega. erewrite Z.mul_cancel_r in H10; auto. \n   omega. }\nQed. \n\n\n\n\n\n\n", "meta": {"author": "lexxx320", "repo": "TheoryThinkTank", "sha": "e55c332cecaebf0c7556ca5a7ff74768254db389", "save_path": "github-repos/coq/lexxx320-TheoryThinkTank", "path": "github-repos/coq/lexxx320-TheoryThinkTank/TheoryThinkTank-e55c332cecaebf0c7556ca5a7ff74768254db389/case_study/borda_3_npc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6711141741178405}}
{"text": "Require Import Basic_Notations_Set.\nRequire Import Basic_Lemmas.\nRequire Import Relation_Properties.\nRequire Import Logic.FunctionalExtensionality.\n\nModule main (def : Relation).\nImport def.\nModule Basic_Lemmas := Basic_Lemmas.main def.\nModule Relation_Properties := Relation_Properties.main def.\nImport Basic_Lemmas Relation_Properties.\n\n(** %\n\\section{全域性, 一価性, 写像に関する補題}\n\\begin{screen}\n\\begin{lemma}[id\\_function]\n$id_A :A \\rel A$ is a function.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma id_function {A : eqType}: function_r (Id A).\nProof.\nrewrite /function_r/total_r/univalent_r.\nrewrite inv_id comp_id_l.\nsplit.\napply inc_refl.\napply inc_refl.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[unit\\_function]\n$\\nabla_{AI} :A \\rel I$ is a function.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma unit_function {A : eqType}: function_r (∇ A i).\nProof.\nrewrite /function_r/total_r/univalent_r.\nrewrite inv_universal lemma_for_tarski2 unit_identity_is_universal.\nsplit.\napply inc_alpha_universal.\napply inc_alpha_universal.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[total\\_comp]\nLet $\\alpha :A \\rel B$ and $\\beta :B \\rel C$ be total relations, then $\\alpha \\cdot \\beta$ is also a total relation.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma total_comp {A B C : eqType} {alpha : Rel A B} {beta : Rel B C}:\n total_r alpha -> total_r beta -> total_r (alpha ・ beta).\nProof.\nrewrite /total_r.\nmove => H H0.\nrewrite comp_inv comp_assoc -(@comp_assoc _ _ _ _ beta).\napply (@inc_trans _ _ _ _ _ H).\napply comp_inc_compat_ab_ab'.\napply comp_inc_compat_b_ab.\napply H0.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[univalent\\_comp]\nLet $\\alpha :A \\rel B$ and $\\beta :B \\rel C$ be univalent relations, then $\\alpha \\cdot \\beta$ is also a univalent relation.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma univalent_comp {A B C : eqType} {alpha : Rel A B} {beta : Rel B C}:\n univalent_r alpha -> univalent_r beta -> univalent_r (alpha ・ beta).\nProof.\nrewrite /univalent_r.\nmove => H H0.\nrewrite comp_inv comp_assoc -(@comp_assoc _ _ _ _ (alpha #)).\napply (fun H' => @inc_trans _ _ _ _ _ H' H0).\napply comp_inc_compat_ab_ab'.\napply comp_inc_compat_ab_b.\napply H.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[function\\_comp]\nLet $\\alpha :A \\to B$ and $\\beta :B \\to C$ be functions, then $\\alpha \\cdot \\beta$ is also a function.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma function_comp {A B C : eqType} {alpha : Rel A B} {beta : Rel B C}:\n function_r alpha -> function_r beta -> function_r (alpha ・ beta).\nProof.\nelim => H H0.\nelim => H1 H2.\nsplit.\napply (total_comp H H1).\napply (univalent_comp H0 H2).\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[total\\_comp2]\nLet $\\alpha :A \\rel B$, $\\beta :B \\rel C$ and $\\alpha \\cdot \\beta$ be a total relation, then $\\alpha$ is also a total relation.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma total_comp2 {A B C : eqType} {alpha : Rel A B} {beta : Rel B C}:\n total_r (alpha ・ beta) -> total_r alpha.\nProof.\nmove => H.\napply inc_def1 in H.\nrewrite comp_inv cap_comm comp_assoc in H.\nrewrite /total_r.\nrewrite H.\napply (@inc_trans _ _ _ _ _ (@dedekind _ _ _ _ _ _)).\napply comp_inc_compat.\napply cap_l.\nrewrite comp_id_r.\napply cap_r.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[univalent\\_comp2]\nLet $\\alpha :A \\rel B$, $\\beta :B \\rel C$, $\\alpha \\cdot \\beta$ be a univalent relation and $\\alpha^\\sharp$ be a total relation, then $\\beta$ is a univalent relation.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma univalent_comp2 {A B C : eqType} {alpha : Rel A B} {beta : Rel B C}:\n univalent_r (alpha ・ beta) -> total_r (alpha #) -> univalent_r beta.\nProof.\nmove => H H0.\napply (fun H' => @inc_trans _ _ _ _ _ H' H).\nrewrite comp_inv comp_assoc -(@comp_assoc _ _ _ _ _ alpha).\napply comp_inc_compat_ab_ab'.\nrewrite /total_r in H0.\nrewrite inv_invol in H0.\napply (comp_inc_compat_b_ab H0).\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[total\\_inc]\nLet $\\alpha :A \\rel B$ be a total relation and $\\alpha \\sqsubseteq \\beta$, then $\\beta$ is also a total relation.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma total_inc {A B : eqType} {alpha beta : Rel A B}:\n total_r alpha -> alpha ⊆ beta -> total_r beta.\nProof.\nmove => H H0.\napply (@inc_trans _ _ _ _ _ H).\napply comp_inc_compat.\napply H0.\napply (@inc_inv _ _ _ _ H0).\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[univalent\\_inc]\nLet $\\alpha :A \\rel B$ be a univalent relation and $\\beta \\sqsubseteq \\alpha$, then $\\beta$ is also a univalent relation.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma univalent_inc {A B : eqType} {alpha beta : Rel A B}:\n univalent_r alpha -> beta ⊆ alpha -> univalent_r beta.\nProof.\nmove => H H0.\napply (fun H' => @inc_trans _ _ _ _ _ H' H).\napply comp_inc_compat.\napply (@inc_inv _ _ _ _ H0).\napply H0.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[function\\_inc]\nLet $\\alpha , \\beta :A \\to B$ be functions and $\\alpha \\sqsubseteq \\beta$. Then,\n$$\n\\alpha = \\beta.\n$$\n\\end{lemma}\n\\end{screen}\n% **)\nLemma function_inc {A B : eqType} {alpha beta : Rel A B}:\n function_r alpha -> function_r beta -> alpha ⊆ beta -> alpha = beta.\nProof.\nmove => H H0 H1.\napply inc_antisym.\napply H1.\napply (@inc_trans _ _ _ ((alpha ・ alpha #) ・ beta)).\napply comp_inc_compat_b_ab.\napply H.\nmove : (@inc_inv _ _ _ _ H1) => H2.\napply (@inc_trans _ _ _ ((alpha ・ beta #) ・ beta)).\napply comp_inc_compat_ab_a'b.\napply comp_inc_compat_ab_ab'.\napply H2.\nrewrite comp_assoc.\napply comp_inc_compat_ab_a.\napply H0.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[total\\_universal]\nIf $\\nabla_{IB}$ be a total relation, then\n$$\n\\nabla_{AB} \\cdot \\nabla_{BC} = \\nabla_{AC}.\n$$\n\\end{lemma}\n\\end{screen}\n% **)\nLemma total_universal {A B C : eqType}:\n total_r (∇ i B) -> ∇ A B ・ ∇ B C = ∇ A C.\nProof.\nmove => H.\nrewrite -(@lemma_for_tarski2 A B) -(@lemma_for_tarski2 B C).\nrewrite comp_assoc -(@comp_assoc _ _ _ _ (∇ i B)).\nreplace (∇ i B ・ ∇ B i) with (Id i).\nrewrite comp_id_l.\napply lemma_for_tarski2.\napply inc_antisym.\nrewrite /total_r in H.\nrewrite inv_universal in H.\napply H.\nrewrite unit_identity_is_universal.\napply inc_alpha_universal.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[function\\_rel\\_inv\\_rel]\nLet $\\alpha :A \\to B$ be function. Then,\n$$\n\\alpha \\cdot \\alpha^\\sharp \\cdot \\alpha = \\alpha.\n$$\n\\end{lemma}\n\\end{screen}\n% **)\nLemma function_rel_inv_rel {A B : eqType} {alpha : Rel A B}:\n function_r alpha -> (alpha ・ alpha #) ・ alpha = alpha.\nProof.\nmove => H.\napply inc_antisym.\nrewrite comp_assoc.\napply comp_inc_compat_ab_a.\napply H.\napply comp_inc_compat_b_ab.\napply H.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[function\\_capP\\_distr]\nLet $f:A \\to B,g:D \\to C$ be functions, $\\theta :(E \\rel F) \\to (B \\rel C)$ and $P$ : predicate. Then,\n$$\nf \\cdot (\\sqcap_{P(\\theta)} \\theta(\\alpha)) \\cdot g^\\sharp = \\sqcap_{P(\\alpha)} (f \\cdot \\theta(\\alpha) \\cdot g^\\sharp).\n$$\n\\end{lemma}\n\\end{screen}\n% **)\nLemma function_capP_distr {A B C D E F : eqType}\n {f : Rel A B} {g : Rel D C} {theta : Rel E F -> Rel B C} {P : Rel E F -> Prop}:\n function_r f -> function_r g ->\n (f ・ (∩_{P} theta)) ・ g # =\n ∩_{P} (fun alpha : Rel E F => (f ・ theta alpha) ・ g #).\nProof.\nelim => H H0.\nelim => H1 H2.\napply inc_antisym.\napply comp_capP_distr.\napply (@inc_trans _ _ _ (((f ・ f #) ・ ∩_{P} (fun alpha : Rel E F => (f ・ theta alpha) ・ g #)) ・ (g ・ g #))).\napply (@inc_trans _ _ _ ((f ・ f #) ・ (∩_{P} (fun alpha : Rel E F => (f ・ theta alpha) ・ g #)))).\napply (comp_inc_compat_b_ab H).\napply (comp_inc_compat_a_ab H1).\nrewrite (@comp_assoc _ _ _ _ _ (f #)) comp_assoc -(@comp_assoc _ _ _ _ _ g) -comp_assoc.\napply comp_inc_compat_ab_a'b.\napply comp_inc_compat_ab_ab'.\napply (@inc_trans _ _ _ (∩_{P} (fun alpha : Rel E F => (f # ・ ((f ・ theta alpha) ・ g #)) ・ g))).\napply comp_capP_distr.\nreplace (fun alpha : Rel E F => (f # ・ ((f ・ theta alpha) ・ g #)) ・ g) with (fun alpha : Rel E F => ((f # ・ f) ・ theta alpha) ・ (g # ・ g)).\napply inc_capP.\nmove => beta H3.\napply (@inc_trans _ _ _ ((f # ・ f) ・ theta beta)).\napply (@inc_trans _ _ _ (((f # ・ f) ・ theta beta) ・ (g # ・ g))).\nmove : beta H3.\napply inc_capP.\napply inc_refl.\napply (comp_inc_compat_ab_a H2).\napply (comp_inc_compat_ab_b H0).\napply functional_extensionality.\nmove => x.\nby [rewrite comp_assoc comp_assoc comp_assoc comp_assoc comp_assoc].\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[function\\_cap\\_distr, function\\_cap\\_distr\\_l, function\\_cap\\_distr\\_r]\nLet $f:A \\to B,g:D \\to C$ be functions and $\\alpha, \\beta :B \\rel C$. Then,\n$$\nf \\cdot (\\alpha \\sqcap \\beta) \\cdot g^\\sharp = (f \\cdot \\alpha \\cdot g^\\sharp) \\sqcap (f \\cdot \\beta \\cdot g^\\sharp).\n$$\n\\end{lemma}\n\\end{screen}\n% **)\nLemma function_cap_distr\n {A B C D : eqType} {f : Rel A B} {alpha beta : Rel B C} {g : Rel D C}:\n function_r f -> function_r g ->\n (f ・ (alpha ∩ beta)) ・ g # = ((f ・ alpha) ・ g #) ∩ ((f ・ beta) ・ g #).\nProof.\nrewrite (@cap_to_capP _ _ _ _ _ _ id) (@cap_to_capP _ _ _ _ _ _ (fun x => (f ・ x) ・ g #)).\napply function_capP_distr.\nQed.\n\nLemma function_cap_distr_l\n {A B C : eqType} {f : Rel A B} {alpha beta : Rel B C}:\n function_r f ->\n f ・ (alpha ∩ beta) = (f ・ alpha) ∩ (f ・ beta).\nProof.\nmove : (@id_function C) => H.\nmove => H0.\napply (@function_cap_distr _ _ _ _ f alpha beta) in H.\nrewrite inv_id comp_id_r comp_id_r comp_id_r in H.\napply H.\napply H0.\nQed.\n\nLemma function_cap_distr_r\n {B C D : eqType} {alpha beta : Rel B C} {g : Rel D C}:\n function_r g ->\n (alpha ∩ beta) ・ g # = (alpha ・ g #) ∩ (beta ・ g #).\nProof.\nmove : (@id_function B) => H.\nmove => H0.\napply (@function_cap_distr _ _ _ _ _ alpha beta g) in H.\nrewrite comp_id_l comp_id_l comp_id_l in H.\napply H.\napply H0.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[function\\_move1]\nLet $\\alpha :A \\to B$ be a function, $\\beta :B \\rel C$ and $\\gamma :A \\rel C$. Then,\n$$\n\\gamma \\sqsubseteq \\alpha \\cdot \\beta \\Leftrightarrow \\alpha^\\sharp \\cdot \\gamma \\sqsubseteq \\beta.\n$$\n\\end{lemma}\n\\end{screen}\n% **)\nLemma function_move1 {A B C : eqType} {alpha : Rel A B} {beta : Rel B C} {gamma : Rel A C}:\n function_r alpha -> (gamma ⊆ (alpha ・ beta) <-> (alpha # ・ gamma) ⊆ beta).\nProof.\nmove => H.\nsplit; move => H0.\napply (@inc_trans _ _ _ ((alpha # ・ alpha) ・ beta)).\nrewrite comp_assoc.\napply (comp_inc_compat_ab_ab' H0).\napply comp_inc_compat_ab_b.\napply H.\napply (@inc_trans _ _ _ ((alpha ・ alpha #) ・ gamma)).\napply comp_inc_compat_b_ab.\napply H.\nrewrite comp_assoc.\napply (comp_inc_compat_ab_ab' H0).\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[function\\_move2]\nLet $\\beta :B \\to C$ be a function, $\\alpha :A \\rel B$ and $\\gamma :A \\rel C$. Then,\n$$\n\\alpha \\cdot \\beta \\sqsubseteq \\gamma \\Leftrightarrow \\alpha \\sqsubseteq \\gamma \\cdot \\beta^\\sharp.\n$$\n\\end{lemma}\n\\end{screen}\n% **)\nLemma function_move2 {A B C : eqType} {alpha : Rel A B} {beta : Rel B C} {gamma : Rel A C}:\n function_r beta -> ((alpha ・ beta) ⊆ gamma <-> alpha ⊆ (gamma ・ beta #)).\nProof.\nmove => H.\nsplit; move => H0.\napply (@inc_trans _ _ _ ((alpha ・ beta) ・ beta #)).\nrewrite comp_assoc.\napply comp_inc_compat_a_ab.\napply H.\napply (comp_inc_compat_ab_a'b H0).\napply (@inc_trans _ _ _ ((gamma ・ beta #) ・ beta)).\napply (comp_inc_compat_ab_a'b H0).\nrewrite comp_assoc.\napply comp_inc_compat_ab_a.\napply H.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[function\\_rpc\\_distr]\nLet $f:A \\to B,g:D \\to C$ be functions and $\\alpha, \\beta :B \\rel C$. Then,\n$$\nf \\cdot (\\alpha \\Rightarrow \\beta) \\cdot g^\\sharp = (f \\cdot \\alpha \\cdot g^\\sharp) \\Rightarrow (f \\cdot \\beta \\cdot g^\\sharp).\n$$\n\\end{lemma}\n\\end{screen}\n% **)\nLemma function_rpc_distr\n {A B C D : eqType} {f : Rel A B} {alpha beta : Rel B C} {g : Rel D C}:\n function_r f -> function_r g ->\n (f ・ (alpha >> beta)) ・ g # = ((f ・ alpha) ・ g #) >> ((f ・ beta) ・ g #).\nProof.\nmove => H H0.\napply inc_lower.\nmove => gamma.\nsplit; move => H1.\napply inc_rpc.\napply (function_move2 H0).\napply (function_move1 H).\napply (@inc_trans _ _ _ (((f # ・ gamma) ・ g) ∩ ((f # ・ ((f ・ alpha) ・ g #)) ・ g))).\nrewrite -comp_assoc.\napply (fun H' => @inc_trans _ _ _ _ _ H' (@comp_cap_distr_r _ _ _ _ _ _)).\napply comp_inc_compat_ab_a'b.\napply comp_cap_distr_l.\napply (function_move2 H0) in H1.\napply (function_move1 H) in H1.\nrewrite -inc_rpc comp_assoc.\napply (@inc_trans _ _ _ _ _ H1).\napply rpc_inc_compat_r.\nrewrite comp_assoc comp_assoc comp_assoc -comp_assoc.\napply (@inc_trans _ _ _ (alpha ・ (g # ・ g))).\napply comp_inc_compat_ab_b.\napply H.\napply comp_inc_compat_ab_a.\napply H0.\napply (function_move2 H0).\napply (function_move1 H).\napply inc_rpc.\napply (@inc_trans _ _ _ _ _ (@dedekind _ _ _ _ _ _)).\napply (@inc_trans _ _ _ (f # ・ ((gamma ・ g) ∩ ((f #) # ・ alpha)))).\napply comp_inc_compat_ab_a'b.\napply cap_l.\nrewrite inv_invol.\napply (@inc_trans _ _ _ ((f # ・ (gamma ∩ ((f ・ alpha) ・ g #))) ・ g)).\nrewrite comp_assoc.\napply comp_inc_compat_ab_ab'.\napply (@inc_trans _ _ _ _ _ (@dedekind _ _ _ _ _ _)).\napply comp_inc_compat_ab_ab'.\napply cap_l.\napply (function_move2 H0).\napply (function_move1 H).\nrewrite -inc_rpc -comp_assoc.\napply H1.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[function\\_inv\\_rel1, function\\_inv\\_rel2]\nLet $f:A \\to B$ be a function. Then,\n$$\nf^\\sharp \\cdot f = id_B \\sqcap f^\\sharp \\cdot \\nabla_{AA} \\cdot f = id_B \\sqcap \\nabla_{BA} \\cdot f.\n$$\n\\end{lemma}\n\\end{screen}\n% **)\nLemma function_inv_rel1 {A B : eqType} {f : Rel A B}:\n function_r f -> f # ・ f = Id B ∩ ((f # ・ ∇ A A) ・ f).\nProof.\nmove => H.\napply inc_antisym.\napply inc_cap.\nsplit.\napply H.\napply comp_inc_compat_ab_a'b.\napply comp_inc_compat_a_ab.\napply inc_alpha_universal.\napply (@inc_trans _ _ _ (Id B ∩ (∇ B A ・ f))).\napply cap_inc_compat_l.\napply comp_inc_compat_ab_a'b.\napply inc_alpha_universal.\nrewrite cap_comm.\napply (@inc_trans _ _ _ _ _ (@dedekind _ _ _ _ _ _)).\nrewrite comp_id_l comp_id_r cap_comm inv_universal.\nrewrite cap_universal cap_universal.\napply inc_refl.\nQed.\n\nLemma function_inv_rel2 {A B : eqType} {f : Rel A B}:\n function_r f -> f # ・ f = Id B ∩ (∇ B A ・ f).\nProof.\nmove => H.\napply inc_antisym.\nrewrite (@function_inv_rel1 _ _ _ H).\napply cap_inc_compat_l.\napply comp_inc_compat_ab_a'b.\napply inc_alpha_universal.\nrewrite cap_comm.\napply (@inc_trans _ _ _ _ _ (@dedekind _ _ _ _ _ _)).\nrewrite comp_id_l comp_id_r cap_comm inv_universal.\nrewrite cap_universal cap_universal.\napply inc_refl.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[function\\_dedekind1, function\\_dedekind2]\nLet $f:A \\to B$ be a function, $\\mu :C \\rel A$ and $\\rho :C \\rel B$. Then,\n$$\n(\\mu \\sqcap \\rho \\cdot f^\\sharp) \\cdot f = \\mu \\cdot f \\sqcap \\rho \\land \\rho \\cdot f^\\sharp \\cdot f = \\nabla_{CA} \\cdot f \\sqcap \\rho.\n$$\n\\end{lemma}\n\\end{screen}\n% **)\nLemma function_dedekind1\n {A B C : eqType} {f : Rel A B} {mu : Rel C A} {rho : Rel C B}:\n function_r f -> (mu ∩ (rho ・ f #)) ・ f = (mu ・ f) ∩ rho.\nProof.\nmove => H.\napply inc_antisym.\napply (@inc_trans _ _ _ _ _ (comp_cap_distr_r)).\napply cap_inc_compat_l.\nrewrite comp_assoc.\napply comp_inc_compat_ab_a.\napply H.\napply (@inc_trans _ _ _ _ _ (@dedekind _ _ _ _ _ _)).\napply comp_inc_compat_ab_ab'.\napply cap_l.\nQed.\n\nLemma function_dedekind2 {A B C : eqType} {f : Rel A B} {rho : Rel C B}:\n function_r f -> (rho ・ f #) ・ f = (∇ C A ・ f) ∩ rho.\nProof.\nmove => H.\nmove : (@function_dedekind1 _ _ _ f (∇ C A) rho H) => H0.\nrewrite cap_comm cap_universal in H0.\napply H0.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[square\\_diagram]\nIn below figure,\n$$\nf \\cdot x = g \\cdot y \\Leftrightarrow f^\\sharp \\cdot g \\sqsubseteq x \\cdot y^\\sharp.\n$$\n$$\n\\xymatrix{\nX \\ar@{->}[r]^f \\ar@{->}[d]_g & A \\ar@{->}[d]^x \\\\\nB \\ar@{->}[r]_y & D\n}\n$$\n\\end{lemma}\n\\end{screen}\n% **)\nLemma square_diagram {X A B D : eqType}\n {f : Rel X A} {g : Rel X B} {x : Rel A D} {y : Rel B D}:\n function_r f -> function_r g -> function_r x -> function_r y ->\n (f ・ x = g ・ y <-> (f # ・ g) ⊆ (x ・ y #)).\nProof.\nmove => H H0 H1 H2.\nsplit; move => H3.\nrewrite -(function_move1 H) -comp_assoc -(function_move2 H2) H3.\napply inc_refl.\napply Logic.eq_sym.\napply function_inc.\napply (function_comp H0 H2).\napply (function_comp H H1).\nrewrite (function_move2 H2) comp_assoc (function_move1 H).\napply H3.\nQed.\n\n(** %\n\\section{全射, 単射に関する補題}\n\\begin{screen}\n\\begin{lemma}[surjection\\_comp]\nLet $\\alpha :A \\rel B$ and $\\beta :B \\rel C$ be surjections, then $\\alpha \\cdot \\beta$ is also a surjection.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma surjection_comp {A B C : eqType} {alpha : Rel A B} {beta : Rel B C}:\n surjection_r alpha -> surjection_r beta -> surjection_r (alpha ・ beta).\nProof.\nrewrite /surjection_r.\nelim => H H0.\nelim => H1 H2.\nsplit.\napply (function_comp H H1).\nrewrite comp_inv.\napply (total_comp H2 H0).\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[injection\\_comp]\nLet $\\alpha :A \\rel B$ and $\\beta :B \\rel C$ be injections, then $\\alpha \\cdot \\beta$ is also an injection.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma injection_comp {A B C : eqType} {alpha : Rel A B} {beta : Rel B C}:\n injection_r alpha -> injection_r beta -> injection_r (alpha ・ beta).\nProof.\nrewrite /injection_r.\nelim => H H0.\nelim => H1 H2.\nsplit.\napply (function_comp H H1).\nrewrite comp_inv.\napply (univalent_comp H2 H0).\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[bijection\\_comp]\nLet $\\alpha :A \\rel B$ and $\\beta :B \\rel C$ be bijections, then $\\alpha \\cdot \\beta$ is also a bijection.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma bijection_comp {A B C : eqType} {alpha : Rel A B} {beta : Rel B C}:\n bijection_r alpha -> bijection_r beta -> bijection_r (alpha ・ beta).\nProof.\nrewrite /bijection_r.\nelim => H.\nelim => H0 H1.\nelim => H2.\nelim => H3 H4.\nsplit.\napply (function_comp H H2).\nrewrite comp_inv.\nsplit.\napply (total_comp H3 H0).\napply (univalent_comp H4 H1).\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[surjection\\_unique1]\nLet $e:A \\twoheadrightarrow B$ be a surjection, $f:A \\to C$ be a function and $e \\cdot e^\\sharp \\sqsubseteq f \\cdot f^\\sharp$, then there exists a unique function $g:B \\to C$ s.t. $f=eg$.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma surjection_unique1 {A B C : eqType} {e : Rel A B} {f : Rel A C}:\n surjection_r e -> function_r f -> (e ・ e #) ⊆ (f ・ f #) ->\n (exists! g : Rel B C, function_r g /\\ f = e ・ g).\nProof.\nrewrite /surjection_r/function_r/total_r/univalent_r.\nelim.\nelim => H H0 H1.\nelim => H2 H3 H4.\nexists (e # ・ f).\nrepeat split.\nrewrite comp_inv comp_assoc -(@comp_assoc _ _ _ _ f).\napply (@inc_trans _ _ _ _ _ H1).\napply comp_inc_compat_ab_ab'.\napply comp_inc_compat_b_ab.\napply H2.\nrewrite comp_inv inv_invol comp_assoc -(@comp_assoc _ _ _ _ e).\napply (@inc_trans _ _ _ (f # ・ ((f ・ f #) ・ f))).\napply comp_inc_compat_ab_ab'.\napply (comp_inc_compat_ab_a'b H4).\nrewrite comp_assoc -comp_assoc.\napply (fun H' => @inc_trans _ _ _ _ _ H' H3).\napply (comp_inc_compat_ab_a H3).\napply function_inc.\nsplit.\napply H2.\napply H3.\nsplit.\nrewrite /total_r.\nrewrite comp_inv comp_inv inv_invol.\nrewrite -(@comp_assoc _ _ _ _ e) (@comp_assoc _ _ _ _ _ e) (@comp_assoc _ _ _ _ _ f) -(@comp_assoc _ _ _ _ f).\napply (@inc_trans _ _ _ _ _ H).\napply comp_inc_compat_a_ab.\napply (@inc_trans _ _ _ _ _ H2).\napply (comp_inc_compat_a_ab H).\nrewrite /univalent_r.\nrewrite comp_inv comp_inv inv_invol.\nrewrite (@comp_assoc _ _ _ _ _ e) -(@comp_assoc _ _ _ _ e) comp_assoc -(@comp_assoc _ _ _ _ _ _ f).\napply (@inc_trans _ _ _ (f # ・ (((f ・ f #) ・ (f ・ f #)) ・ f))).\napply comp_inc_compat_ab_ab'.\napply comp_inc_compat_ab_a'b.\napply comp_inc_compat.\napply H4.\napply H4.\nrewrite comp_assoc (@comp_assoc _ _ _ _ _ _ f) -(@comp_assoc _ _ _ _ (f #)) -(@comp_assoc _ _ _ _ (f #)) (@comp_assoc _ _ _ _ _ (f #)) -(@comp_assoc _ _ _ _ (f #)).\napply (fun H' => @inc_trans _ _ _ _ _ H' H3).\napply comp_inc_compat_ab_a.\napply (fun H' => @inc_trans _ _ _ _ _ H' H3).\napply (comp_inc_compat_ab_a H3).\nrewrite -comp_assoc.\napply (comp_inc_compat_b_ab H).\nmove => g.\nelim.\nelim => H5 H6 H7.\nreplace g with (e # ・ (e ・ g)).\napply f_equal.\napply H7.\nrewrite -comp_assoc.\napply inc_antisym.\napply (comp_inc_compat_ab_b H0).\nrewrite inv_invol in H1.\napply (comp_inc_compat_b_ab H1).\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[surjection\\_unique2]\nLet $e:A \\twoheadrightarrow B$ be a surjection, $f:A \\to C$ be a function and $e \\cdot e^\\sharp = f \\cdot f^\\sharp$, then function $e^\\sharp f$ is an injection.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma surjection_unique2 {A B C : eqType} {e : Rel A B} {f : Rel A C}:\n surjection_r e -> function_r f -> (e ・ e #) = (f ・ f #) -> injection_r (e # ・ f).\nProof.\nrewrite /surjection_r/injection_r/function_r/total_r/univalent_r.\nelim.\nelim => H H0 H1.\nelim => H2 H3 H4.\nrepeat split.\nrewrite comp_inv comp_assoc -(@comp_assoc _ _ _ _ f).\napply (@inc_trans _ _ _ _ _ H1).\napply comp_inc_compat_ab_ab'.\napply comp_inc_compat_b_ab.\napply H2.\nrewrite comp_inv inv_invol comp_assoc -(@comp_assoc _ _ _ _ e).\nrewrite H4.\nrewrite comp_assoc -comp_assoc.\napply (fun H' => @inc_trans _ _ _ _ _ H' H3).\napply (comp_inc_compat_ab_a H3).\nrewrite inv_invol comp_inv inv_invol comp_assoc -(@comp_assoc _ _ _ _ f).\nrewrite -H4.\nrewrite comp_assoc -comp_assoc.\napply (fun H' => @inc_trans _ _ _ _ _ H' H0).\napply comp_inc_compat_ab_a.\napply H0.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[injection\\_unique1]\nLet $m:B \\rightarrowtail A$ be an injection, $f:C \\to A$ be a function and $f^\\sharp \\cdot f \\sqsubseteq m^\\sharp \\cdot m$, then there exists a unique function $g:C \\to B$ s.t. $f=gm$.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma injection_unique1 {A B C : eqType} {m : Rel B A} {f : Rel C A}:\n injection_r m -> function_r f -> (f # ・ f) ⊆ (m # ・ m) ->\n (exists! g : Rel C B, function_r g /\\ f = g ・ m).\nProof.\nrewrite /injection_r/function_r/total_r/univalent_r.\nelim.\nelim => H H0 H1.\nelim => H2 H3 H4.\nexists (f ・ m #).\nrepeat split.\nrewrite comp_inv inv_invol comp_assoc -(@comp_assoc _ _ _ _ _ m).\napply (@inc_trans _ _ _ (f ・ ((f # ・ f) ・ f #))).\nrewrite comp_assoc -comp_assoc.\napply (@inc_trans _ _ _ _ _ H2).\napply (comp_inc_compat_a_ab H2).\napply comp_inc_compat_ab_ab'.\napply (comp_inc_compat_ab_a'b H4).\nrewrite comp_inv comp_assoc -(@comp_assoc _ _ _ _ _ f).\napply (fun H' => @inc_trans _ _ _ _ _ H' H1).\napply comp_inc_compat_ab_ab'.\napply (comp_inc_compat_ab_b H3).\nrewrite comp_assoc.\napply Logic.eq_sym.\napply function_inc.\nsplit.\nrewrite /total_r.\nrewrite comp_inv comp_inv inv_invol.\napply (@inc_trans _ _ _ _ _ H2).\napply comp_inc_compat.\napply (@inc_trans _ _ _ (f ・ (f # ・ f))).\nrewrite -comp_assoc.\napply (comp_inc_compat_b_ab H2).\napply (comp_inc_compat_ab_ab' H4).\napply (@inc_trans _ _ _ ((f # ・ f) ・ f #)).\nrewrite comp_assoc.\napply (comp_inc_compat_a_ab H2).\napply (comp_inc_compat_ab_a'b H4).\nrewrite /univalent_r.\nrewrite comp_inv comp_inv inv_invol comp_assoc -(@comp_assoc _ _ _ _ _ f).\napply (fun H' => @inc_trans _ _ _ _ _ H' H0).\napply comp_inc_compat_ab_a.\napply (fun H' => @inc_trans _ _ _ _ _ H' H3).\napply (comp_inc_compat_ab_a H0).\nsplit.\napply H2.\napply H3.\napply (comp_inc_compat_ab_a H0).\nmove => g.\nelim.\nelim => H5 H6 H7.\nrewrite H7 comp_assoc.\napply inc_antisym.\nrewrite inv_invol in H1.\napply (comp_inc_compat_ab_a H1).\napply (comp_inc_compat_a_ab H).\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[injection\\_unique2]\nLet $m:B \\rightarrowtail A$ be an injection, $f:C \\to A$ be a function and $f^\\sharp \\cdot f = m^\\sharp \\cdot m$, then function $f \\cdot m^\\sharp$ is a surjection.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma injection_unique2 {A B C : eqType} {m : Rel B A} {f : Rel C A}:\n injection_r m -> function_r f -> (f # ・ f) = (m # ・ m) -> surjection_r (f ・ m #).\nProof.\nrewrite /surjection_r/injection_r/function_r/total_r/univalent_r.\nelim.\nelim => H H0 H1.\nelim => H2 H3 H4.\nrepeat split.\nrewrite comp_inv inv_invol comp_assoc -(@comp_assoc _ _ _ _ _ m).\napply (@inc_trans _ _ _ (f ・ ((f # ・ f) ・ f #))).\nrewrite comp_assoc -comp_assoc.\napply (@inc_trans _ _ _ _ _ H2).\napply (comp_inc_compat_a_ab H2).\napply comp_inc_compat_ab_ab'.\nrewrite H4.\napply inc_refl.\nrewrite comp_inv comp_assoc -(@comp_assoc _ _ _ _ _ f).\napply (fun H' => @inc_trans _ _ _ _ _ H' H1).\napply comp_inc_compat_ab_ab'.\napply (comp_inc_compat_ab_b H3).\nrewrite inv_invol comp_inv inv_invol comp_assoc -(@comp_assoc _ _ _ _ _ f).\napply (@inc_trans _ _ _ _ _ H).\napply comp_inc_compat_ab_ab'.\nrewrite H4 comp_assoc.\napply (comp_inc_compat_a_ab H).\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[bijection\\_inv]\nLet $\\alpha :A \\rel B$, $\\beta :B \\rel A$, $\\alpha \\cdot \\beta = id_A$ and $\\beta \\cdot \\alpha = id_B$, then $\\alpha$ and $\\beta$ are bijections and $\\beta = \\alpha^\\sharp$.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma bijection_inv {A B : eqType} {alpha : Rel A B} {beta : Rel B A}:\n alpha ・ beta = Id A -> beta ・ alpha = Id B -> bijection_r alpha /\\ bijection_r beta /\\ beta = alpha #.\nProof.\nmove => H H0.\nmove : (@id_function A) => H1.\nmove : (@id_function B) => H2.\nassert (bijection_r alpha /\\ bijection_r beta).\nassert (total_r alpha /\\ total_r (alpha #) /\\ total_r beta /\\ total_r (beta #)).\nrepeat split.\napply (@total_comp2 _ _ _ _ beta).\nrewrite H.\napply H1.\napply (@total_comp2 _ _ _ _ (beta #)).\nrewrite -comp_inv H0 inv_id.\napply H2.\napply (@total_comp2 _ _ _ _ alpha).\nrewrite H0.\napply H2.\napply (@total_comp2 _ _ _ _ (alpha #)).\nrewrite -comp_inv H inv_id.\napply H1.\nrepeat split.\napply H3.\napply (@univalent_comp2 _ _ _ beta).\nrewrite H0.\napply H2.\napply H3.\napply H3.\napply (@univalent_comp2 _ _ _ (beta #)).\nrewrite -comp_inv H inv_id.\napply H1.\nrewrite inv_invol.\napply H3.\napply H3.\napply (@univalent_comp2 _ _ _ alpha).\nrewrite H.\napply H1.\napply H3.\napply H3.\napply (@univalent_comp2 _ _ _ (alpha #)).\nrewrite -comp_inv H0 inv_id.\napply H2.\nrewrite inv_invol.\napply H3.\nsplit.\napply H3.\nsplit.\napply H3.\nrewrite -(@comp_id_r _ _ beta) -(@comp_id_l _ _ (alpha #)).\nrewrite -H0 comp_assoc.\napply f_equal.\napply inc_antisym.\napply H3.\nrewrite comp_inv_inv -inv_inc_move inv_id.\napply H3.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[bijection\\_inv\\_corollary]\nLet $\\alpha :A \\rel B$ be a bijection, then $\\alpha^\\sharp$ is also a bijection.\n\\end{lemma}\n\\end{screen}\n% **)\nLemma bijection_inv_corollary {A B : eqType} {alpha : Rel A B}:\n bijection_r alpha -> bijection_r (alpha #).\nProof.\nmove : (@bijection_inv _ _ alpha (alpha #)) => H.\nmove => H0.\nrewrite /bijection_r/function_r/total_r/univalent_r in H0.\nrewrite inv_invol in H0.\napply H.\napply inc_antisym.\napply H0.\napply H0.\napply inc_antisym.\napply H0.\napply H0.\nQed.\n\n(** %\n\\section{有理性から導かれる系}\n\\begin{screen}\n\\begin{lemma}[rationality\\_corollary1]\nLet $u :A \\rel A$ and $u \\sqsubseteq id_A$. Then,\n$$\n\\exists R, \\exists j:R \\rightarrowtail A, u = j^\\sharp \\cdot j.\n$$\n\\end{lemma}\n\\end{screen}\n% **)\nLemma rationality_corollary1 {A : eqType} {u : Rel A A}:\n u ⊆ Id A -> exists (R : eqType)(j : Rel R A), injection_r j /\\ u = j # ・ j.\nProof.\nmove : (rationality _ _ u).\nelim => R.\nelim => f.\nelim => g.\nelim => H.\nelim => H0.\nelim => H1 H2 H3.\nexists R.\nexists f.\nassert (g = f).\napply (function_inc H0 H).\napply (@inc_trans _ _ _ ((f ・ f #) ・ g)).\napply comp_inc_compat_b_ab.\napply H.\nrewrite comp_assoc -H1.\napply (comp_inc_compat_ab_a H3).\nrewrite H4 in H1.\nrewrite H4 cap_idem in H2.\nsplit.\nsplit.\napply H.\nrewrite /univalent_r.\nrewrite inv_invol H2.\napply inc_refl.\napply H1.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[rationality\\_corollary2]\nLet $f :A \\to B$ be a function. Then,\n$$\n\\exists e:A \\twoheadrightarrow R, \\exists m:R \\rightarrowtail B, f = e \\cdot m.\n$$\n\\end{lemma}\n\\end{screen}\n% **)\nLemma rationality_corollary2 {A B : eqType} {f : Rel A B}:\n function_r f -> exists (R : eqType)(e : Rel A R)(m : Rel R B), surjection_r e /\\ injection_r m.\nProof.\nelim => H H0.\nmove : (@rationality_corollary1 _ (f # ・ f) H0).\nelim => R.\nelim => m.\nelim => H1 H2.\nexists R.\nexists (f ・ m #).\nexists m.\nsplit.\napply (injection_unique2 H1 (conj H H0) H2).\napply H1.\nQed.\n\n(** %\n\\begin{screen}\n\\begin{lemma}[axiom\\_of\\_subobjects]\nLet $u :A \\rel A$ and $u \\sqsubseteq id_A$. Then,\n$$\n\\exists R, \\exists j:R \\to A, j^\\sharp \\cdot j = u \\land j \\cdot j^\\sharp = id_R.\n$$\n\\end{lemma}\n\\end{screen}\n% **)\nLemma axiom_of_subobjects {A : eqType} {u : Rel A A}:\n u ⊆ Id A -> exists (R : eqType)(j : Rel R A), j # ・ j = u /\\ j ・ j # = Id R.\nProof.\nmove => H.\nelim (rationality_corollary1 H) => R.\nelim => j H0.\nexists R.\nexists j.\nsplit.\napply Logic.eq_sym.\napply H0.\napply inc_antisym.\nreplace (j ・ j #) with ((j #) # ・ j #).\napply H0.\nby [rewrite inv_invol].\napply H0.\nQed.\n\nEnd main.", "meta": {"author": "KyushuUniversityMathematics", "repo": "RelationalCalculus", "sha": "cf744dd53cb810ecadfa7d8a04b1f534b40f794b", "save_path": "github-repos/coq/KyushuUniversityMathematics-RelationalCalculus", "path": "github-repos/coq/KyushuUniversityMathematics-RelationalCalculus/RelationalCalculus-cf744dd53cb810ecadfa7d8a04b1f534b40f794b/Functions_Mappings.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6711141676429251}}
{"text": "(* ea *)\n\nInductive Z_3 : Set :=\n  | n : Z_3 \n  | a : Z_3\n  | b : Z_3.\n\nDefinition ope (x:Z_3) (y:Z_3) :=\n  match x , y with\n  | n , y => y\n  | x , n => x\n  | a , b => n\n  | b , a => n \n  | a , a => b\n  | b , b => a\n  end.\n\nDefinition inve (x:Z_3) :=\n  match x with\n  | n => n\n  | a => b\n  | b => a\n  end.\n\nTheorem Z_3_eq_dec_mod : forall (x y: Z_3), x = y \\/ x <> y.\nProof. \n  induction x, y.\n  left. \n  reflexivity. \n  right. \n  discriminate.\n\n  right. \n  discriminate.\n  right. \n  discriminate.\n  left. \n  reflexivity. \n  right. \n  discriminate.\n  right. \n  discriminate.\n  right. \n  discriminate.\n  left. \n  reflexivity. \nQed.\n\n\n(* hf *)\n\nTheorem Z_3_eq_dec_mod_v2 : forall (x y: Z_3), x = y \\/ x <> y.\nProof. \n  induction x, y; auto.\n  right; discriminate.\n  right; discriminate.\n  right; discriminate.\n  right; discriminate.\n  right; discriminate.\n  right; discriminate.\nQed.\n", "meta": {"author": "mozow01", "repo": "bizcoq2021", "sha": "f98f22ba3ce80899bc88605ce3193d8972102c92", "save_path": "github-repos/coq/mozow01-bizcoq2021", "path": "github-repos/coq/mozow01-bizcoq2021/bizcoq2021-f98f22ba3ce80899bc88605ce3193d8972102c92/hallgatoi/gabormarton/bizcoq_2_hf_1_a.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6711100046916004}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint drop (drop_arg0 : natural) (drop_arg1 : lst) : lst\n           := match drop_arg0, drop_arg1 with\n              | x, Nil => Nil\n              | Zero, x => x\n              | Succ x, Cons y z => drop x z\n              end.\n\nTheorem drop_Nil: forall (x: natural), drop x Nil = Nil.\nProof.\n  induction x ; simpl; reflexivity.\nQed.\n\nTheorem drop_Cons: forall (x n: natural) (l: lst), drop (Succ x) (Cons n l) = drop x l.\nProof.  induction l; induction x; simpl; reflexivity.\nQed.\n\nTheorem drop_Cons_assoc: forall (x1 x2 x3: natural) (l: lst),\n    drop x1 (drop x2 (Cons x3 l)) = drop x2 (drop x1 (Cons x3 l)).\nProof.\n  induction x1; induction x2; try (simpl; reflexivity).\n  + induction l.\n    * \n      rewrite 2 drop_Cons. rewrite <- IHx1.\n      rewrite IHx2. rewrite 2 drop_Cons.\n      induction l.\n      - rewrite IHx1. reflexivity. \n      - \n        rewrite 3 drop_Nil. reflexivity. \n    * simpl. lfind.  reflexivity.  \nAdmitted.\n\nTheorem theorem0 : forall (x : natural) (y : natural) (z : lst), eq (drop x (drop y z)) (drop y (drop x z)).\nProof.\n  induction z.\n  + \n    rewrite 2 drop_Cons_assoc. reflexivity. \n  + \n    rewrite 3 drop_Nil. reflexivity. \nQed.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal8_drop_Cons_assoc_39_drop_Nil/goal8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6711100019128586}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\nRequire Import Arith Lia Wellfounded List Extraction.\n\nFrom Undecidability.Shared.Libs.DLW.Wf Require Import acc_irr.\n\nSet Implicit Arguments.\n\nSection measure_rect.\n\n  Variable (X : Type) (m : X -> nat) (P : X -> Type).\n\n  Hypothesis F : forall x, (forall x', m x' < m x -> P x') -> P x.\n\n  Arguments F : clear implicits.\n\n  Let R x y := m x < m y.\n\n  (* R is WF when all elements are accessible *)\n\n  Let Rwf : forall x : X, Acc R x.\n  Proof.\n    apply wf_inverse_image with (f := m), lt_wf.\n  Qed.\n\n  (* Structural decrease on the Acc predicate and no \n      singleton elimination here because the Acc predicated\n      is pattern matched (by destruct) in Prop context *)\n\n  Let Fix_F : forall x : X, Acc R x -> P x.\n  Proof.\n    refine(\n      fix Fix_F x (H : Acc R x) { struct H } := \n         F x (fun x' (H' : R x' x) => Fix_F x' _)\n    ).\n    destruct H as [ G ].\n    apply G. (* structural decrease here *)\n    trivial. \n  Defined.\n\n  (* To evaluate @Fix_F x A, the recursive argument must reduce to a\n      term headed with an inductive constructor *)\n\n  Let Fix_F_fix x A :\n        @Fix_F x A = F x (fun y H => Fix_F (Acc_inv A H)).\n  Proof. destruct A; reflexivity. Qed.\n\n  Definition measure_rect x : P x := Fix_F (Rwf x).\n\n  (* To establish the fixpoint equation for measure_rect, we need\n      to assume that the functional F is extensional because we do not\n      use the FunExt axiom *)\n\n  Hypothesis F_ext : forall x f g, (forall y H, f y H = g y H) -> F x f = F x g.\n\n  (* Another proof method here that in StdLib, using the characterisation\n      of Acc irrelevant functionals *)\n\n  Let Fix_F_Acc_irr : forall x f g, @Fix_F x f = Fix_F g.\n  Proof.\n    apply Acc_irrelevance.\n    intros; apply F_ext; auto.\n  Qed.\n\n  Theorem measure_rect_fix x : \n          measure_rect x = @F x (fun y _ => measure_rect y).\n  Proof.\n    unfold measure_rect; rewrite Fix_F_fix.\n    apply F_ext.\n    intros; apply Fix_F_Acc_irr.\n  Qed.\n\nEnd measure_rect.\n\nTactic Notation \"induction\" \"on\" hyp(x) \"as\" ident(IH) \"with\" \"measure\" uconstr(f) :=\n   pattern x; revert x; apply measure_rect with (m := fun x => f); intros x IH.\n\nExtraction Inline measure_rect.\n\nSection measure_double_rect.\n\n  Variable (X Y : Type) (m : X -> Y -> nat) (P : X -> Y -> Type).\n\n  Hypothesis F : (forall x y, (forall x' y', m x' y' < m x y -> P x' y') -> P x y).\n\n  Let m' (c : X * Y) := match c with (x,y) => m x y end.\n\n  Let R c d := m' c < m' d.\n\n  Let Rwf : well_founded R.\n  Proof.\n    apply wf_inverse_image with (f := m'), lt_wf.\n  Qed.\n\n  Section measure_double_rect_paired.\n\n    Let Q c := match c with (x,y) => P x y end.\n\n    Theorem measure_double_rect_paired x y : P x y.\n    Proof.\n      change (Q (x,y)).\n      generalize (x,y); clear x y; intros c.\n\n      induction on c as IH with measure (m' c).\n      destruct c as (x,y); apply F.\n      intros ? ?; apply (IH (_,_)). \n    Defined.\n\n  End measure_double_rect_paired.\n\n  Section measure_double_rect.\n\n    Let Fix_F_2 : forall x y, Acc R (x,y) -> P x y.\n    Proof.\n      refine (fix Fix_F_2 x y H { struct H } := \n           @F x y (fun x' y' H' => Fix_F_2 x' y' _)\n      ).\n      destruct H as [ H ]; unfold R in H at 1. \n      apply H. (* structural decrease here *)\n      apply H'. \n    Defined.\n\n    Let Fix_F_2_fix x y H :\n        @Fix_F_2 x y H = F (fun x' y' H' => Fix_F_2 (@Acc_inv _ _ _ H (x',y') H')).\n    Proof. destruct H; reflexivity. Qed.\n\n    Definition measure_double_rect x y : P x y := Fix_F_2 (Rwf (_,_)).\n\n    Hypothesis F_ext : forall x y f g, (forall x' y' H, f x' y' H = g x' y' H) \n                                      -> @F x y f = F g.\n\n    Let Fix_F_2_paired c (A : Acc R c) : P (fst c) (snd c).\n    Proof. destruct c; simpl; apply Fix_F_2; trivial. Defined.\n\n    Let Fix_F_2_paired_Acc_irr : forall c f g, @Fix_F_2_paired c f \n                                              = Fix_F_2_paired   g.\n    Proof.\n       apply Acc_irrelevance.\n       intros (x,y) f g IH; apply F_ext.\n       intros x' y' ?; apply (@IH (x',y')).\n    Qed.\n\n    Let Fix_F_2_Acc_irr x y f g : @Fix_F_2 x y f = Fix_F_2 g.\n    Proof.\n      intros; apply (@Fix_F_2_paired_Acc_irr (x,y)); trivial.\n    Qed.\n\n    Theorem measure_double_rect_fix x y : \n             measure_double_rect x y = @F x y (fun x' y' _ => measure_double_rect x' y').\n    Proof.\n      unfold measure_double_rect; rewrite Fix_F_2_fix.\n      apply F_ext.\n      intros; apply Fix_F_2_Acc_irr.\n    Qed.\n\n  End measure_double_rect.\n\nEnd measure_double_rect.\n\nTactic Notation \"paired\" \"induction\" \"on\" hyp(x) hyp(y) \"as\" ident(IH) \"with\" \"measure\" uconstr(f) :=\n   pattern x, y; revert x y; apply measure_double_rect_paired with (m := fun x y => f); intros x y IH.\n\nTactic Notation \"induction\" \"on\" hyp(x) hyp(y) \"as\" ident(IH) \"with\" \"measure\" uconstr(f) :=\n   pattern x, y; revert x y; apply measure_double_rect with (m := fun x y => f); intros x y IH.\n\nExtraction Inline measure_double_rect measure_double_rect_paired.\n", "meta": {"author": "uds-psl", "repo": "coq-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/Wf/measure_ind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7662936324115012, "lm_q1q2_score": 0.671109995048646}}
{"text": "\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nFixpoint qreva (qreva_arg0 : lst) (qreva_arg1 : lst) : lst\n           := match qreva_arg0, qreva_arg1 with\n              | Nil, x => x\n              | Cons z x, y => qreva x (Cons z y)\n              end.\n\nTheorem append_nil: forall (l: lst), append l Nil = l.\nProof.\n   induction l.\n   { simpl. f_equal. assumption. }\n   { simpl. reflexivity. }\nQed.\n\nTheorem append_assoc:\n   forall (l1 l2 l3: lst), append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\n   induction l1; induction l2; induction l3; try (simpl; reflexivity).\n   { simpl. rewrite <- IHl1. f_equal. }\n   { simpl. rewrite 2 append_nil. reflexivity. }\n   { simpl. rewrite append_nil.  reflexivity. }\n   { simpl. rewrite 2 append_nil. reflexivity. }\nQed.\n\nTheorem qreva_append : forall (x y : lst), (qreva x y) = (append (rev x) y).\nProof.\n   induction x; induction y; simpl; try reflexivity.\n   { rewrite IHx.\n   rewrite <- append_assoc.\n   f_equal. }\n   { rewrite IHx.\n   rewrite append_nil.\n   reflexivity. }\nQed.\n\nTheorem theorem0 : forall (x : lst), eq (rev x) (qreva x Nil).\nProof.\n   intros.\n   rewrite qreva_append.\n   rewrite append_nil.\n   reflexivity.\nQed.\n\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/goal27.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.6710384908692262}}
{"text": "From Undecidability.TM.Code Require Import ProgrammingTools.\nFrom Undecidability Require Import TM.Code.CaseNat.\n\n\n(* * Machines that compte natural functions *)\n\n(* Don't simplify [skipn (S n) xs]; only, if the number and the lists are constructors *)\nLocal Arguments skipn { A } !n !l.\n\nLocal Arguments Encode_nat : simpl never.\n\n\n(*\nLemma nat_encode_length (n : nat) :\n| encode n : list bool | = S n.\nProof. induction n; cbn; auto. Qed.\n\n\nLemma max_plus_minus_le (m n : nat) :\n  n + (m - n) <= max m n.\nProof.\n  assert (m <= n \\/ n <= m) as [H|H] by lia.\n  - rewrite <- Nat.le_max_r. lia.\n  - rewrite <- Nat.le_max_l. lia.\nQed.\n\nLemma max_max_le (m n : nat) :\n  max (max m n) n = max m n.\nProof.\n  assert (m <= n \\/ n <= m) as [H|H] by lia.\n  - erewrite Nat.max_r.\n    + symmetry. now eapply max_r.\n    + eapply Nat.eq_le_incl. now eapply max_r.\n  - erewrite Nat.max_l.\n    + reflexivity.\n    + apply Nat.le_max_r.\nQed.\n*)\n\n\n(* ** Addition *)\n\n\n(*\n * Step machine\n *\n * if (b--) {\n *   a++;\n *   continue;\n * } else {\n *   break;\n * }\n *\n * Tapes:\n * t0: a\n * t1: b\n *)\nDefinition Add_Step : pTM sigNat^+ (option unit) 2 :=\n  If (LiftTapes CaseNat [|Fin1|])\n     (Return (LiftTapes Constr_S [|Fin0|]) None)\n     (Return Nop (Some tt)).\n\n\nDefinition Add_Loop : pTM sigNat^+ unit 2 := While Add_Step.\n\n(*\n * Full machine in pseudocode:\n * a := n\n * b := m\n * while (b--) { // Loop\n *   a++;\n * }\n * reset b;\n * return a;\n *\n * Tapes:\n * INP t0: m\n * INP t1: n\n * OUT t2: a\n * INT t3: b\n *)\n(* Everything, but not reset *)\nDefinition Add_Main : pTM sigNat^+ unit 4 :=\n  LiftTapes (CopyValue _) [|Fin1; Fin2|];; (* copy n to a *)\n  LiftTapes (CopyValue _) [|Fin0; Fin3|];; (* copy m to b *)\n  LiftTapes Add_Loop [|Fin2; Fin3|]. (* Main loop *)\n\n\n(*\n * Finally, reset tape b.\n * For technical reasons, it is convienient to define the machine for this last step seperately,\n * because it makes prooving the termination easier.\n *)\nDefinition Add :=\n  Add_Main;; (* Initialisation and main loop *)\n  LiftTapes (Reset _) [|Fin3|]. (* Reset b *)\n\n\n(* *** Correctness of [Add] *)\n\nDefinition Add_Step_Rel : pRel sigNat^+ (option unit) 2 :=\n  fun tin '(yout, tout) =>\n    forall a b sa sb,\n      tin [@Fin0] ≃(;sa) a ->\n      tin [@Fin1] ≃(;sb) b ->\n      match yout, b with\n      | Some tt, O => (* break *)\n        tout[@Fin0] ≃(;sa) a /\\\n        tout[@Fin1] ≃(;sb) b\n      | None, S b' =>\n        tout[@Fin0] ≃(;pred sa) S a /\\\n        tout[@Fin1] ≃(;S sb) b'\n      | _, _ => False\n      end.\n\nLemma Add_Step_Sem : Add_Step ⊨c(9) Add_Step_Rel.\nProof.\n  eapply RealiseIn_monotone.\n  {\n    unfold Add_Step. TM_Correct.\n  }\n  { cbn. reflexivity. }\n  {\n    intros tin (yout, tout) H. cbn. intros a b sa sb HEncA HEncB. cbn in *.\n    destruct H; TMSimp; clear_trivial_eqs.\n    - modpon H. destruct b; auto.\n    - modpon H. destruct b; auto.\n  }\nQed.\n\n\nDefinition Add_Loop_Rel : pRel sigNat^+ unit 2 :=\n  ignoreParam (\n      fun tin tout =>\n        forall a b sa sb,\n          tin [@Fin0] ≃(;sa) a ->\n          tin [@Fin1] ≃(;sb) b ->\n          tout[@Fin0] ≃(;sa-b) b + a /\\\n          tout[@Fin1] ≃(;sb+b) 0\n    ).\n\nLemma Add_Loop_Realise : Add_Loop ⊨ Add_Loop_Rel.\nProof.\n  eapply Realise_monotone.\n  { unfold Add_Loop. TM_Correct. eapply RealiseIn_Realise. apply Add_Step_Sem. }\n  {\n    apply WhileInduction; intros; intros a b sa sb HEncA HEncB; cbn in *; destruct_unit.\n    - modpon HLastStep. destruct b; auto; modpon HLastStep. auto.\n    - modpon HStar. destruct b; auto. destruct HStar as (HStar1&HStar2).\n      modpon HLastStep. split; auto. contains_ext. f_equal. lia.\n  }\nQed.\n\n\n\n(* Everything, but reset *)\nDefinition Add_Main_Rel : pRel sigNat^+ unit 4 :=\n  ignoreParam (\n      fun tin tout =>\n        forall m n sm sn s2 s3,\n          tin [@Fin0] ≃(;sm) m ->\n          tin [@Fin1] ≃(;sn) n ->\n          isVoid_size tin[@Fin2] s2 ->\n          isVoid_size tin[@Fin3] s3 ->\n          tout[@Fin0] ≃(;sm) m /\\\n          tout[@Fin1] ≃(;sn) n /\\\n          tout[@Fin2] ≃(; s2 - (S (size n)) - m) m + n /\\\n          tout[@Fin3] ≃(; s3 - (2 + m) + m) 0\n    ).\n\n\nLemma Add_Main_Realise : Add_Main ⊨ Add_Main_Rel.\nProof.\n  eapply Realise_monotone.\n  {\n    unfold Add_Main. TM_Correct.\n    - apply Add_Loop_Realise.\n  }\n  {\n    intros tin ((), tout) H. cbn. intros m n sm sn s2 s3 HEncM HEncN HOut HInt.\n    TMSimp.\n    modpon H. modpon H0. modpon H2.\n    repeat split; auto.\n    { contains_ext. unfold CopyValue_size. rewrite Encode_nat_hasSize. lia. }\n  }\nQed.\n\n\nGoal forall (x m : nat), x - m + m >= x. Proof. intros. lia. Qed.\n\nDefinition Add_space2 (m n : nat) (so : nat) := so + m - n - 2.\nDefinition Add_space3 (m : nat) (s3 : nat) := 2 + (s3 - (2 + m) + m).\n\nDefinition Add_Rel : pRel sigNat^+ unit 4 :=\n  ignoreParam\n    (fun tin tout =>\n       forall (m : nat) (n : nat) (sx sy so s3 : nat),\n         tin[@Fin0] ≃(;sx) m ->\n         tin[@Fin1] ≃(;sy) n ->\n         isVoid_size tin[@Fin2] so ->\n         isVoid_size tin[@Fin3] s3 ->\n         tout[@Fin0] ≃(;sx) m /\\ (* First input value stayes unchanged *)\n         tout[@Fin1] ≃(;sy) n /\\ (* Second input value stayes unchanged *)\n         tout[@Fin2] ≃(;Add_space2 m n so) (m + n) /\\\n         isVoid_size tout[@Fin3] (Add_space3 m s3)\n    ).\n\nLemma Add_Computes : Add ⊨ Add_Rel.\nProof.\n  eapply Realise_monotone.\n  {\n    unfold Add. TM_Correct.\n    - apply Add_Main_Realise.\n  }\n  {\n    intros tin ((), tout) H. intros m n sx sy so s3 HEncM HEncN HOut HRight3. TMSimp.\n    unfold Add_space2, Add_space3.\n    rename H into HMain, H0 into HReset.\n    modpon HMain. modpon HReset.\n    repeat split; eauto.\n    contains_ext. rewrite Encode_nat_hasSize. lia.\n  }\nQed.\n\n\n(* *** Termination of [Add] *)\n\nLocal Arguments plus : simpl never.\nLocal Arguments mult : simpl never.\n\nDefinition Add_Loop_steps b := 9 + 10 * b.\n\nLemma Add_Loop_Terminates :\n  projT1 Add_Loop ↓\n         (fun tin i => exists (a b:nat),\n              tin[@Fin0] ≃ a /\\\n              tin[@Fin1] ≃ b /\\\n              Add_Loop_steps b <= i).\nProof.\n  eapply TerminatesIn_monotone.\n  { unfold Add_Loop. TM_Correct.\n    - eapply RealiseIn_Realise. apply Add_Step_Sem.\n    - eapply RealiseIn_TerminatesIn. apply Add_Step_Sem. }\n  {\n    unfold Add_Loop_steps. apply WhileCoInduction. intros tin i (a&b&HEncA&HEncB&Hi).\n    destruct b.\n    (* (* In case I want to use the [WhileInduction] principle without [match] *)\n    - exists 11. repeat split.\n      + lia.\n      + intros () ? _. lia.\n      + intros tmid H. cbn in *. specialize (H _ _ HEncA HEncB). cbn in *. auto.\n    - exists 11. repeat split.\n      + lia.\n      + intros () tmid H. cbn in H. specialize (H _ _ HEncA HEncB). now cbn in *.\n      + intros tmid H. cbn in H. specialize (H _ _ HEncA HEncB). cbn in *. destruct H as (H1&H2).\n        exists (11 + b * 12). repeat split.\n        * exists (S a), b. repeat split; eauto. lia.\n        * lia.\n        *)\n    - exists 9. repeat split.\n      + lia.\n      + intros o tmid H. cbn in H. modpon H;[]. destruct o; auto.\n    - exists 9. repeat split.\n      + lia.\n      + intros o tmid H. cbn in H. modpon H. cbn -[plus mult] in *.\n        destruct o as [ () | ]; auto. destruct H.\n        exists (9 + b * 10). repeat split.\n        * do 2 eexists. repeat split; eauto. lia.\n        * lia.\n  }\nQed.\n\n\nDefinition Add_Main_steps m n := 85 + 12 * n + 22 * m.\n(* [37 + 12 * n] for [CopyValue] (n) *)\n(* [37 + 12 * m] for [CopyValue] (m) *)\n(* [9 + 10 * m] for [Add_Loop] *)\n\nDefinition Add_Main_T : tRel sigNat^+ 4 := fun tin k => exists m n, tin[@Fin0] ≃ m /\\ tin[@Fin1] ≃ n /\\ isVoid tin[@Fin2] /\\ isVoid tin[@Fin3] /\\ Add_Main_steps m n <= k.\n\nLemma Add_Main_Terminates :\n  projT1 Add_Main ↓ Add_Main_T.\nProof.\n  unfold Add_Main, Add_Main_steps. eapply TerminatesIn_monotone.\n  {\n    TM_Correct.\n    - apply Add_Loop_Terminates.\n  }\n  {\n    intros tin k (m&n&HEncM&HEncN&HOut&HRight3&Hk).\n    unfold Add_Main_steps in *.\n    exists (37 + 12 * n), (47 + 22 * m). repeat split; cbn.\n    - cbn. exists n. split; eauto. unfold CopyValue_steps. rewrite Encode_nat_hasSize. lia.\n    - lia.\n    - intros tmid ymid. intros (H1&H2). TMSimp.\n      modpon H1.\n      exists (37 + 12 * m), (Add_Loop_steps m). repeat split.\n      + exists m. split. eauto. unfold CopyValue_steps. rewrite Encode_nat_hasSize. lia.\n      + unfold Add_Loop_steps. lia.\n      + intros tmid2_ () (HComp & HInj). TMSimp.\n        modpon HComp.\n        do 2 eexists; repeat split; eauto; do 2 eexists; eassumption.\n  }\nQed.\n\n\nDefinition Add_steps m n := 98 + 12 * n + 22 * m.\n(* Additional [12] steps for [Reset], and [1] for [Seq] *)\n\nDefinition Add_T : tRel sigNat^+ 4 := fun tin k => exists m n, tin[@Fin0] ≃ m /\\ tin[@Fin1] ≃ n /\\ isVoid tin[@Fin2] /\\ isVoid tin[@Fin3] /\\ Add_steps m n <= k.\n\nLemma Add_Terminates :\n  projT1 Add ↓ Add_T.\nProof.\n  unfold Add, Add_steps. eapply TerminatesIn_monotone.\n  {\n    TM_Correct.\n    - apply Add_Main_Realise.\n    - apply Add_Main_Terminates.\n  }\n  {\n    intros tin k (m&n&HEncM&HEncN&HOut&HInt&Hk).\n    exists (Add_Main_steps m n), 12. repeat split.\n    - cbn. exists m, n. repeat split; eauto.\n    - unfold Add_Main_steps. unfold Add_steps in *. lia.\n    - intros tmid () HComp. cbn in *.\n      modpon HComp.\n      exists 0. split. eauto. unfold MoveRight_steps. cbn. auto.\n  }\nQed.\n\n\n\n(* ** Multiplication *)\n\n\n(*\n * Complete Machine:\n *\n * INP t0: m\n * INP t1: n  (for Add: INP t0)\n * OUT t2: c  (for Add: INP t1)\n * INT t3: c' (for Add: OUT t2)\n * INT t4:    (for Add: INT t3)\n * INT t5: m' (copy of m)\n *\n * Pseudocode:\n * c := 0\n * while (m--) {\n *   ADD(n, c, c')\n *   Reset c\n *   c := c'\n *   Reset c'\n * }\n * Reset m'\n *)\n\n(*\n * Step-Machine:\n * (Note that it only accesses the copy of m)\n *\n * t0: m' (counter)\n * t1: n  (for Add: INP t0)\n * t2: c  (for Add: INP t1)\n * t3: c' (for Add: OUT t2)\n * t4:    (for Add: INT t3)\n *\n * if (m'--) {\n *   Add(n, c, c')\n *   c := c\n *   reset c'\n *   continue\n * } else {\n *   break\n * }\n *)\nDefinition Mult_Step : pTM sigNat^+ (option unit) 5 :=\n  If (LiftTapes CaseNat [|Fin0|])\n     (Return (\n          LiftTapes Add [|Fin1; Fin2; Fin3; Fin4|];; (* Add(n, c, c') *)\n          LiftTapes (MoveValue _) [|Fin3; Fin2|]\n        ) (None)) (* continue *)\n     (Return Nop (Some tt)). (* break *)\n\n\nDefinition Mult_Loop := While Mult_Step.\n\n\n(*\n * INP t0: m\n * INP t1: n  (for Mult_Loop: t1)\n * OUT t2: c  (for Mult_Loop: t2)\n * INT t3: c' (for Mult_Loop: t3)\n * INT t4:    (for Mult_Loop: t4)\n * INT t5: m' (for Mult_Loop: t0)\n *)\nDefinition Mult_Main : pTM sigNat^+ unit 6 :=\n  LiftTapes (CopyValue _) [|Fin0; Fin5|];; (* m' := m *)\n  LiftTapes (Constr_O) [|Fin2|];; (* c := 0 *)\n  LiftTapes Mult_Loop [|Fin5; Fin1; Fin2; Fin3; Fin4|]. (* Main loop *)\n\n\nDefinition Mult : pTM sigNat^+ unit 6 :=\n  Mult_Main;;\n  LiftTapes (Reset _) [|Fin5|]. (* Reset m' *)\n\n\n(* *** Correctness of [Mult] *)\n\nDefinition Mult_Step_Rel : pRel sigNat^+ (option unit) 5 :=\n  fun tin '(yout, tout) =>\n    forall (c m' n : nat) (sm sn sc s3 s4 : nat),\n      tin[@Fin0] ≃(;sm) m' ->\n      tin[@Fin1] ≃(;sn) n ->\n      tin[@Fin2] ≃(;sc) c ->\n      isVoid_size tin[@Fin3] s3 ->\n      isVoid_size tin[@Fin4] s4 ->\n      match yout, m' with\n      | (Some tt), O => (* return *)\n        tout[@Fin0] ≃(;sm) m' /\\\n        tout[@Fin1] ≃(;sn) n /\\\n        tout[@Fin2] ≃(;sc) c /\\\n        isVoid_size tout[@Fin3] s3 /\\\n        isVoid_size tout[@Fin4] s4\n      | None, S m'' => (* continue *)\n        tout[@Fin0] ≃(;S sm) m'' /\\\n        tout[@Fin1] ≃(;sn) n /\\\n        tout[@Fin2] ≃(;sc-n) n + c /\\\n        isVoid_size tout[@Fin3] (2 + n + c + Add_space2 n c s3)  /\\\n        isVoid_size tout[@Fin4] (Add_space3 n s4)\n      | _, _ => False\n      end.\n\nLemma Mult_Step_Realise : Mult_Step ⊨ Mult_Step_Rel.\nProof.\n  eapply Realise_monotone.\n  {\n    unfold Mult_Step. TM_Correct.\n    - apply Add_Computes.\n  }\n  {\n    intros tin (yout, tout) H. intros c m' n sm sn sc s3 s4 HEncM' HEncN HEncC HInt3 HInt4. TMSimp.\n    destruct H; TMSimp.\n    - rename H into HCaseNat, H1 into HAdd, H3 into HMove.\n      modpon HCaseNat.\n      destruct m' as [ | m']; auto.\n      modpon HAdd. modpon HMove.\n      repeat split; auto.\n      + contains_ext. unfold MoveValue_size_y. rewrite !Encode_nat_hasSize. lia.\n      + isVoid_mono. unfold Add_space2. unfold MoveValue_size_x. rewrite Encode_nat_hasSize. lia.\n    - modpon H. destruct m' as [ | m']; auto.\n  }\nQed.\n\n\nFixpoint Mult_Loop_space34 (m' n c : nat) (s3 s4 : nat) { struct m' } : Vector.t nat 2 :=\n  match m' with\n  | 0 => [| s3; s4 |]\n  | S m'' => Mult_Loop_space34 m'' n (n + c) (2 + n + c + Add_space2 n c s3) (Add_space3 n s4)\n  end.\n\n\nDefinition Mult_Loop_Rel : pRel sigNat^+ unit 5 :=\n  ignoreParam (\n      fun tin tout =>\n        forall c m' n sm sn sc s3 s4,\n          tin[@Fin0] ≃(;sm) m' ->\n          tin[@Fin1] ≃(;sn) n ->\n          tin[@Fin2] ≃(;sc) c ->\n          isVoid_size tin[@Fin3] s3 ->\n          isVoid_size tin[@Fin4] s4 ->\n          tout[@Fin0] ≃(;sm+m') 0 /\\\n          tout[@Fin1] ≃(;sn) n /\\\n          tout[@Fin2] ≃(;sc-m'*n) m' * n + c /\\\n          isVoid_size tout[@Fin3] (Mult_Loop_space34 m' n c s3 s4)[@Fin0] /\\\n          isVoid_size tout[@Fin4] (Mult_Loop_space34 m' n c s3 s4)[@Fin1]\n    ).\n\n\nLemma Mult_Loop_Realise :\n  Mult_Loop ⊨ Mult_Loop_Rel.\nProof.\n  eapply Realise_monotone.\n  {\n    unfold Mult_Loop. TM_Correct. eapply Mult_Step_Realise.\n  }\n  {\n    eapply WhileInduction; intros; intros c m' n sm sn sc s3 s4 HEncM' HEncN HEncC HInt3 HInt4; TMSimp.\n    - modpon HLastStep. destruct m' as [ | m']; auto. modpon HLastStep. auto.\n    - modpon HStar.\n      destruct m' as [ | m']; auto. destruct HStar as (HStar1&HStar2&HStar3&HStar4&HStar5).\n      modpon HLastStep.\n      rewrite Nat.add_assoc in *. replace (n + m' * n + c) with (m' * n + n + c) by lia.\n      repeat split; auto. contains_ext. f_equal. now rewrite Nat.mul_succ_l.\n  }\nQed.\n\n(*\n * Complete Machine:\n *\n * INP t0: m\n * INP t1: n  (from Add: INP t0)\n * OUT t2: c  (from Add: INP t1)\n * INT t3: c' (from Add: OUT t2)\n * INT t4:    (from Add: INT t3)\n * INT t5: m' (copy of m)\n *\n * Pseudocode:\n * c := 0\n * m' := m\n * while (m--) {\n *   ADD(n, c, c')\n *   c := c'\n *   reset c'\n * }\n * reset m'\n *)\n\nDefinition Mult_Main_Rel : pRel sigNat^+ unit 6 :=\n  ignoreParam (\n      fun tin tout =>\n        forall (m n : nat) (sm sn so s3 s4 s5 : nat),\n          tin[@Fin0] ≃(;sm) m ->\n          tin[@Fin1] ≃(;sn) n ->\n          isVoid_size tin[@Fin2] so ->\n          isVoid_size tin[@Fin3] s3 ->\n          isVoid_size tin[@Fin4] s4 ->\n          isVoid_size tin[@Fin5] s5 ->\n          tout[@Fin0] ≃(;sm) m /\\\n          tout[@Fin1] ≃(;sn) n /\\\n          tout[@Fin2] ≃(;so-m*n) m * n /\\\n          isVoid_size tout[@Fin3] ((Mult_Loop_space34 m n 0 s3 s4)[@Fin0]) /\\\n          isVoid_size tout[@Fin4] ((Mult_Loop_space34 m n 0 s3 s4)[@Fin1]) /\\\n          tout[@Fin5] ≃(;s5+m) 0\n    ).\n\nLemma Mult_Main_Realise :\n  Mult_Main ⊨ Mult_Main_Rel.\nProof.\n  eapply Realise_monotone.\n  {\n    unfold Mult_Main. TM_Correct.\n    - apply Mult_Loop_Realise.\n  }\n  {\n    intros tin ((), tout) H. intros m n sm sn s0 s3 s4 s5 HEncM HEncN Hout HInt3 HInt4 HInt5.\n    TMSimp.\n    modpon H. modpon H0. modpon H2. rewrite Nat.add_0_r in H4.\n    repeat split; eauto.\n    { contains_ext. unfold CopyValue_size, Constr_O_size. cbn. lia. }\n    { contains_ext. unfold CopyValue_size, Constr_O_size. cbn. lia. }\n  }\nQed.\n\n\nDefinition Mult_Rel : pRel sigNat^+ unit 6 :=\n  ignoreParam\n    (fun tin tout =>\n       forall (m : nat) (n : nat) (sm sn so s3 s4 s5 : nat),\n         tin[@Fin0] ≃(;sm) m ->\n         tin[@Fin1] ≃(;sn) n ->\n         isVoid_size tin[@Fin2] so ->\n         isVoid_size tin[@Fin3] s3 ->\n         isVoid_size tin[@Fin4] s4 ->\n         isVoid_size tin[@Fin5] s5 ->\n         tout[@Fin0] ≃(;sm) m /\\\n         tout[@Fin1] ≃(;sn) n /\\\n         tout[@Fin2] ≃(;so-m*n) m * n /\\\n         isVoid_size tout[@Fin3] ((Mult_Loop_space34 m n 0 s3 s4)[@Fin0]) /\\\n         isVoid_size tout[@Fin4] ((Mult_Loop_space34 m n 0 s3 s4)[@Fin1]) /\\\n         isVoid_size tout[@Fin5] (S (S (m + s5)))\n    ).\n\n\nLemma Mult_Computes :\n  Mult ⊨ Mult_Rel.\nProof.\n  eapply Realise_monotone.\n  {\n    unfold Mult. TM_Correct.\n    - eapply Mult_Main_Realise.\n  }\n  {\n    intros tin ((), tout) H. cbn. intros m n sm sn so s3 s4 s5 HEncM HEncN HOut HInt3 HInt4 HInt5. TMSimp.\n    rename H into HMain, H0 into HReset.\n    modpon HMain. modpon HReset.\n    repeat split; auto.\n    {  isVoid_mono. unfold Reset_size. rewrite !Encode_nat_hasSize. cbn. lia. }\n  }\nQed.\n\n\n(* *** Termination of Mult *)\n\nDefinition Mult_Step_steps m' n c :=\n  match m' with\n  | O => 6\n  | _ => 168 + 33 * c + 39 * n\n  end.\n(* [5] for [If] and [1] for [CaseNat] *)\n(* [98+12*n+22*c] for [Add] *)\n(* [12+c] for [Reset] (c) *)\n(* [36+12*(c+n)] for [CopyValue] (c' = c + n) *)\n(* [12 + (c+n)] for [Reset] (c' = c + n) *)\n\nLemma Mult_Step_Terminates :\n  projT1 Mult_Step ↓\n         (fun tin k => exists m' n c,\n              tin[@Fin0] ≃ m' /\\\n              tin[@Fin1] ≃ n /\\\n              tin[@Fin2] ≃ c /\\\n              isVoid tin[@Fin3] /\\\n              isVoid tin[@Fin4] /\\\n              Mult_Step_steps m' n c <= k).\nProof.\n  eapply TerminatesIn_monotone.\n  {\n    unfold Mult_Step. TM_Correct.\n    - apply Add_Computes.\n    - apply Add_Terminates.\n  }\n  {\n    intros tin k. intros (m'&n&c&HEncM'&HEncN&HEncC&HInt3&HInt4&Hk).\n    destruct m' as [ | m']; cbn.\n    - exists 5, 0. cbn in *; repeat split; eauto.\n      intros tmid y (HComp&HInj). TMSimp.\n      modpon HComp. destruct y; auto.\n    - exists 5, (162 + 33 * c + 39 * n); cbn in *; repeat split; eauto.\n      intros tmid y (HComp&HInj). TMSimp.\n      modpon HComp. cbn in *. destruct y; auto.\n      exists (Add_steps n c), (63 + 21 * c + 17 * n); cbn in *; repeat split.\n      do 2 eexists. repeat split; eauto.\n      unfold Add_steps. lia.\n      intros tmid0_ () (HComp2&HInj). TMSimp.\n      modpon HComp2.\n      do 2 eexists. repeat split; eauto. unfold MoveValue_steps. rewrite !Encode_nat_hasSize. lia.\n  }\nQed.\n\n\nFixpoint Mult_Loop_steps m' n c :=\n  match m' with\n  | O => S (Mult_Step_steps m' n c)\n  | S m'' => S (Mult_Step_steps m' n c) + Mult_Loop_steps m'' n (n + c)\n  end.\n\n\nLemma Mult_Loop_Terminates :\n  projT1 Mult_Loop ↓\n         (fun tin i => exists m' n c,\n              tin[@Fin0] ≃ m' /\\\n              tin[@Fin1] ≃ n /\\\n              tin[@Fin2] ≃ c /\\\n              isVoid tin[@Fin3] /\\\n              isVoid tin[@Fin4] /\\\n              Mult_Loop_steps m' n c <= i).\nProof.\n  eapply TerminatesIn_monotone.\n  { unfold Mult_Loop. TM_Correct.\n    - apply Mult_Step_Realise.\n    - apply Mult_Step_Terminates. }\n  {\n    apply WhileCoInduction. intros tin k (m'&n&c&HEncM'&HEncN&HEncC&HRight3&HRight4&Hk).\n    destruct m' as [ | m''] eqn:E; cbn in *; exists (Mult_Step_steps m' n c).\n    {\n      repeat split.\n      - do 3 eexists. repeat split; eauto. cbn. unfold Mult_Step_steps. destruct m'; lia.\n      - intros o tmid H1.\n        modpon H1.\n        destruct o as [ () | ]; auto. destruct H1 as (HComp1&HComp2&HComp3&HComp4&HComp5).\n        subst. cbn. lia.\n    }\n    {\n      repeat split.\n      - do 3 eexists. repeat split; eauto. cbn. unfold Mult_Step_steps. destruct m'; lia.\n      - intros o tmid H1.\n        modpon H1.\n        destruct o as [ () | ]; auto. destruct H1 as (HComp1&HComp2&HComp3&HComp4&HComp5).\n        cbn. eexists. repeat split.\n        + do 3 eexists. repeat split; eauto.\n        + cbn. rewrite <- Hk. subst. clear_all. unfold Mult_Step_steps. lia.\n    }\n  }\nQed.\n\n\nDefinition Mult_Main_steps m n := 44 + 12 * m + Mult_Loop_steps m n 0.\n(* [2] steps for [Seq], in total *)\n(* [37+12*m] for [CopyValue] (m) *)\n(* [Mult_Loop_steps m n 0] for [Mult_Loop] *)\n\n\n\nDefinition Mult_Main_T : tRel sigNat^+ 6 := fun tin k => exists m n, tin[@Fin0] ≃ m /\\ tin[@Fin1] ≃ n /\\ isVoid tin[@Fin2] /\\ (forall i : Fin.t 3, isVoid tin[@FinR 3 i]) /\\ Mult_Main_steps m n <= k.\n  \nLemma Mult_Main_Terminates : projT1 Mult_Main ↓ Mult_Main_T.\nProof.\n  eapply TerminatesIn_monotone.\n  { unfold Mult_Main. TM_Correct.\n    - apply Mult_Loop_Terminates.\n  }\n  {\n    intros tin k (m&n&HEncM&HEncN&HOut&HInt&Hk). cbn in *. unfold Mult_Main_steps in Hk.\n    specializeFin HInt; clear HInt.\n    exists (37 + 12 * m), (6 + Mult_Loop_steps m n 0). repeat split; try lia.\n    { eexists. repeat split; eauto. unfold CopyValue_steps. rewrite Encode_nat_hasSize; cbn. lia. }\n    intros tmid () (H1&H2); TMSimp. modpon H1.\n    exists 5, (Mult_Loop_steps m n 0). repeat split; try lia.\n    { unfold Constr_O_steps. lia. }\n    intros tmid2 () (H2&HInj2); TMSimp. modpon H2.\n    do 3 eexists. repeat split; eauto.\n  }\nQed.\n\n\nDefinition Mult_steps m n := 13 + Mult_Main_steps m n.\n\nDefinition Mult_T : tRel sigNat^+ 6 := fun tin k => exists m n, tin[@Fin0] ≃ m /\\ tin[@Fin1] ≃ n /\\ isVoid tin[@Fin2] /\\ (forall i : Fin.t 3, isVoid tin[@FinR 3 i]) /\\ Mult_steps m n <= k.\n  \nLemma Mult_Terminates : projT1 Mult ↓ Mult_T.\nProof.\n  eapply TerminatesIn_monotone.\n  { unfold Mult. TM_Correct.\n    - apply Mult_Main_Realise.\n    - apply Mult_Main_Terminates.\n  }\n  {\n    intros tin k (m&n&HEncM&HEncN&HOut&HInt&Hk). cbn in *. unfold Mult_steps in Hk.\n    exists (Mult_Main_steps m n), 12. repeat split; try lia.\n    do 2 eexists; repeat split; eauto.\n    intros tmid () H1; TMSimp.\n    specialize (HInt Fin0) as HInt0. specialize (HInt Fin1) as HInt4. specialize (HInt Fin2) as HInt5.\n    modpon H1.\n    exists 0. split; auto.\n  }\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/TM/Code/NatTM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.6710384882252894}}
{"text": "(************************************************************************)\n(* Copyright (c) 2017, Ajay Kumar Eeralla <ae266@mail.missouri.edu>     *)\n(*                   University of Missouri-Columbia.                   *)\n(*                                                                      *)\n(*                                                                      *)\n(*                                                                      *)\n(************************************************************************)\n\nLoad \"ex5_4_IFMORPH\".\n(** * [andB] properties *)\n\n(** This library defines some of the properties of [andB]. *)\n\n(** [FAlse] if one of them is [FAlse]. *)\nLemma andB_FAlse_intro1 : forall b1 b2 : Bool, b1 ## FAlse -> b1 & b2 ## FAlse.\nProof.\nintros.\nunfold andB .\nrewrite H.\napply IFFALSE_B. \nQed.\n\nLemma andB_FAlse_intro2 : forall b1 b2:Bool, b2 ## FAlse -> b1 & b2 ## FAlse.\nProof. intros. unfold andB. rewrite H. apply IFSAME_B. Qed.\n\nLemma andB_FAlse_r :  forall b:Bool, b & FAlse ## FAlse.\nProof. intros.  unfold andB. apply IFSAME_B. Qed.\n\nLemma andB_FAlse_l : forall b: Bool, FAlse & b ## FAlse.\nProof. intros. unfold andB. apply IFFALSE_B. Qed.\n\nLemma andB_diag : forall n, (Bvar n) & (Bvar n) ## (Bvar n).\nProof.  intros. unfold andB. rewrite IFEVAL_B. simpl. \nrewrite <- beq_nat_refl.\n rewrite IFTF.\nreflexivity.\nQed.\n\n(** Invariant under [TRue]. *)\n\nLemma andB_TRue_r : forall b:Bool, b & TRue ## b.\n\nProof.  intros. unfold andB.\npose proof (IFTF 1).\napply Forall_ELM_EVAL_B with (n :=1)(b:=b) in H.\nsimpl in H.\napply H.  Qed.  \n\nLemma andB_TRue_l : forall b:Bool,  TRue & b ## b.\n\nProof.  intros. unfold andB.\napply IFTRUE_B.\n   Qed.           \n\nLemma andB_notb_r : forall n, (Bvar n) & (notb (Bvar n)) ## FAlse.\n\nProof. intros. unfold andB .  unfold notb.  rewrite IFEVAL_B. simpl. rewrite <- beq_nat_refl. \nrewrite IFTRUE_B. rewrite IFSAME_B. reflexivity. Qed.\n\n(** [andB] is commutative. *)\n\nLemma andB_comm1: forall n1 n2 , ( (Bvar n1) & (Bvar n2))  ## ( (Bvar n2) & (Bvar n1)).\n\nProof. intros. unfold andB.  rewrite <- IFTF with (n:= n2) at 1 . \n\nrewrite IFMORPH_B1 with (n1:= n2) (n2:=n1). rewrite IFTF with (n:= n1). rewrite IFSAME_B. reflexivity. Qed.\n\nAxiom andB_comm: forall (b1 b2: Bool), (b1 & b2) ## (b2 & b1).\n\n(** [andB] is associative *)\n\nLemma andB_assoc1 : forall n1 n2 n3, (Bvar n1) & ((Bvar n2) & (Bvar n3)) ##( ((Bvar n1) & (Bvar n2)) & (Bvar n3)).\n\nProof. intros. unfold andB.\npose proof(andB_comm1).\nunfold andB in H.\npose proof (IFMORPH_B1).\n rewrite IFMORPH_B1 with (n1:= n2) (n2:= n1).\nrewrite H with (n1:=n1) (n2:= n2).\nrewrite IFMORPH_B2.\nrewrite IFSAME_B.\nrewrite IFFALSE_B.\nreflexivity.\nQed.\n \nAxiom andB_assoc: forall (b1 b2 b3: Bool), (b1 & b2) & b3 ## b1 & (b2 & b3).\nAxiom andB_prop : forall a b:Bool, (andB a b) ## TRue -> (a ## TRue) /\\ (b ## TRue).\n\nLemma andB_TRue_intro : forall b1 b2:Bool, b1 ## TRue /\\ b2 ## TRue -> (andB b1 b2) ## TRue.\nProof. intros.\ninversion H.\nunfold andB.\nrewrite H0.\nrewrite IFTRUE_B.\nassumption.\nQed.\n\nLemma andB_TRue_iff :  forall n1 n2, (Bvar n1) & (Bvar n2) ## TRue <-> (Bvar n1) ## TRue /\\ (Bvar n2) ## TRue.\nProof. split.\napply andB_prop.\napply andB_TRue_intro.\nQed.\n\n(** [notb] properties *)\n\nLemma notB_involutive : forall n, (notb (notb (Bvar n))) ## (Bvar n).\n\nProof. intros. unfold notb. \n\n rewrite IFMORPH_B2. rewrite IFFALSE_B. rewrite IFTRUE_B.\nrewrite IFTF. reflexivity. Qed.\n\n\nLemma notB_TRue_iff : forall n, ( notb (Bvar n)) ## TRue <-> (Bvar n) ## FAlse.\nProof.\nintros. split.\nintros.\nrewrite <- notB_involutive.\nrewrite H.\nunfold notb .\nrewrite IFTRUE_B.\nreflexivity.\nintros.\nrewrite H.\nunfold notb.\nrewrite IFFALSE_B.\nreflexivity.\nQed.\n\nLemma notb_FAlse_iff : forall n, (notb (Bvar n)) ## FAlse <-> (Bvar n) ## TRue.\n\nProof. intros. split.\n\nintros.  rewrite <- notB_involutive. rewrite H. unfold notb. rewrite IFFALSE_B.  reflexivity.\n\nintros. rewrite H. unfold notb.\n\nrewrite IFTRUE_B. reflexivity. Qed.\n\n\n(** [andB] complement *)\n\n\n\nLemma and_notB_r : forall n, (Bvar n) & (notb (Bvar n)) ## FAlse.\nProof. intros. unfold  andB.\nunfold notb. rewrite IFMORPH_B1. \nrewrite IFIDEMP_B. rewrite IFSAME_B. reflexivity. Qed.\n\nLemma and_notB_l : forall n, (notb (Bvar n)) & (Bvar n) ## FAlse.\nProof. intros. unfold  andB.\nunfold notb. rewrite IFMORPH_B2. \nrewrite IFFALSE_B, IFTRUE_B.\nrewrite IFEVAL_B.\nsimpl.\nrewrite <- beq_nat_refl.\nrewrite IFSAME_B.\nreflexivity. Qed.\n\nTheorem b1_notb2 : forall (n1 : nat) , (Bvar n1) &(notb (Bvar (n1+1))) ##\n(ifb (Bvar (n1+1)) FAlse (Bvar n1)) .\n\nProof.\n intros.\nunfold notb, andB.\nrewrite <- IFSAME_B with (b:= (Bvar (n1+1))) (b1:= (ifb (Bvar n1) (ifb (Bvar (n1 + 1)) FAlse TRue) FAlse)).\nrewrite IFEVAL_B with (n := (n1+1)).\n simpl.\nrewrite <- beq_nat_refl.\nrewrite IFFALSE_B.\nrewrite IFTRUE_B.\nrewrite IFSAME_B.\n(*************)\nassert(H: beq_nat n1 (n1 + 1) = false).\ninduction n1.\nreflexivity. \nsimpl.\nassumption.\n(************)\nrewrite H.\nrewrite IFTF.\nreflexivity.\nQed.\n\n\n\n", "meta": {"author": "ajayeeralla", "repo": "real-or-random-auth-proofs-coq", "sha": "0aca7baa8647c1e9aaafb359978d46b1952000f5", "save_path": "github-repos/coq/ajayeeralla-real-or-random-auth-proofs-coq", "path": "github-repos/coq/ajayeeralla-real-or-random-auth-proofs-coq/real-or-random-auth-proofs-coq-0aca7baa8647c1e9aaafb359978d46b1952000f5/andbprops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.6710384875791429}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Import PeanoNat.\n\nLocal Open Scope nat_scope.\n\n\n\nNotation le_refl := Nat.le_refl (compat \"8.4\").\nNotation le_trans := Nat.le_trans (compat \"8.4\").\nNotation le_antisym := Nat.le_antisymm (compat \"8.4\").\n\nHint Resolve le_trans: arith.\nHint Immediate le_antisym: arith.\n\n\n\nNotation le_0_n := Nat.le_0_l (compat \"8.4\").\nNotation le_Sn_0 := Nat.nle_succ_0 (compat \"8.4\").\n\nLemma le_n_0_eq n : n <= 0 -> 0 = n.\nProof. hammer_hook \"Le\" \"Le.le_n_0_eq\".  \nintros. symmetry. now apply Nat.le_0_r.\nQed.\n\n\n\n\n\nTheorem le_n_S : forall n m, n <= m -> S n <= S m.\nProof. hammer_hook \"Le\" \"Le.le_n_S\".  exact (Peano.le_n_S). Qed.\n\nTheorem le_S_n : forall n m, S n <= S m -> n <= m.\nProof. hammer_hook \"Le\" \"Le.le_S_n\".  exact (Peano.le_S_n). Qed.\n\nNotation le_n_Sn := Nat.le_succ_diag_r (compat \"8.4\").\nNotation le_Sn_n := Nat.nle_succ_diag_l (compat \"8.4\").\n\nTheorem le_Sn_le : forall n m, S n <= m -> n <= m.\nProof. hammer_hook \"Le\" \"Le.le_Sn_le\".  exact (Nat.lt_le_incl). Qed.\n\nHint Resolve le_0_n le_Sn_0: arith.\nHint Resolve le_n_S le_n_Sn le_Sn_n : arith.\nHint Immediate le_n_0_eq le_Sn_le le_S_n : arith.\n\n\n\nNotation le_pred_n := Nat.le_pred_l (compat \"8.4\").\nNotation le_pred := Nat.pred_le_mono (compat \"8.4\").\n\nHint Resolve le_pred_n: arith.\n\n\n\nLemma le_elim_rel :\nforall P:nat -> nat -> Prop,\n(forall p, P 0 p) ->\n(forall p (q:nat), p <= q -> P p q -> P (S p) (S q)) ->\nforall n m, n <= m -> P n m.\nProof. hammer_hook \"Le\" \"Le.le_elim_rel\".  \nintros P H0 HS.\ninduction n; trivial.\nintros m Le. elim Le; auto with arith.\nQed.\n\n\nNotation le_O_n := le_0_n (only parsing).\nNotation le_Sn_O := le_Sn_0 (only parsing).\nNotation le_n_O_eq := le_n_0_eq (only parsing).\n\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Arith/Le.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.6710384793539346}}
{"text": "(* ***************************************************************** *)\n(*                                                                   *)\n(* Released: 2020/04/17.                                             *)\n(* Due: 2019/04/21, 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 (Assignment5.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 \"Assignment5.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 PL.Imp3 PL.ImpExt4 PL.ImpExt5.\n\n(* ################################################################# *)\n(** * Task 1: Understanding Steps *)\n\n(** Prove the following step relations. *)\n\n(** **** Exercise: 1 star, standard: (step_sample1)  *)\n\nModule Task1.\nImport Abstract_Pretty_Printing.\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;[apply AH_num|].\n  rewrite <- H.\n  apply AS_Id.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard: (step_sample1)  *)\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;[apply AH_num|].\n  apply AS_Mult1.\n  apply AS_Plus.\nQed.\n\nEnd Task1.\n\n(* ################################################################# *)\n(** * Task 2: Alternative Small Step Semantics *)\n\nModule Task2.\nImport Abstract_Pretty_Printing.\nLocal Open Scope imp.\n\n(** Alice wrote an alternative definition of [cstep] as follows. Her purpose\n    is to avoid administrative steps, i.e. the step from [Skip;; c] to [c]. *)\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\n(** But she is not sure, on what extent this [cstep'] is a well-defined\n    semantics. Your task is to give her an answer using the following\n    examples. *)\n\n(** **** Exercise: 1 star, standard  *)\n\nDefinition claim1: Prop := forall (st: state) (X Y: var),\n  st X = 1 ->\n  cstep' (Skip;; Y ::= X, st) (Y ::= 1, st).\n\nFact claim1_veri : claim1.\nProof. hnf.\n  intros.\n  apply CS_Seq'.\n  apply CS_AssStep'.\n  rewrite <- H.\n  apply AS_Id.\nQed.\n\n(** Does [cstep'] satisfy this claim? 1: Yes. 2: No. *)\n\nDefinition my_choice1: Z := 1.\n(** [] *)\n\n(** **** Exercise: 1 star, standard  *)\n\nDefinition claim2: Prop := forall (st: state) (X: var),\n  st X = 0 ->\n  cstep' ((Skip;; Skip);; X ::= 0, st) (Skip, st).\n\n(** Does [cstep'] satisfy this claim? 1: Yes. 2: No. *)\n\nDefinition my_choice2: Z := 2.\n(** [] *)\n\n(** **** Exercise: 1 star, standard  *)\n\nDefinition claim3: Prop := forall (st: state) (X: var),\n  st X = 0 ->\n  cstep' (Skip;; Skip;; X ::= 0, st) (Skip, st).\n\nFact claim3_veri : claim3.\nProof.\n  hnf. intros.\n  apply CS_Seq'.\n  apply CS_Seq'.\n  apply CS_Ass';[apply H|].\n  intros. reflexivity.\nQed.\n(** Does [cstep'] satisfy this claim? 1: Yes. 2: No. *)\n\nDefinition my_choice3: Z := 1.\n(** [] *)\n\n(** **** Exercise: 1 star, standard  *)\n\nDefinition claim4: Prop := forall (st: state),\n  cstep' (Skip;; Skip;; Skip, st) (Skip, st).\n\n\n(** Does [cstep'] satisfy this claim? 1: Yes. 2: No. *)\n\nDefinition my_choice4: Z := 2.\n(** [] *)\n\nEnd Task2.\n\n(* ################################################################# *)\n(** * Task 3: Middle Step Relation *)\n\nModule Task3.\nImport Abstract_Pretty_Printing.\nLocal Open Scope imp.\n\n(** Between denotational semantics (also called big step semantics) and small\n   step semantics, there could be other choices. The famous certified compiler\n   CompCert formalizes the program semantics of C using \"middle step semantics\".\n   Here is a similar version for [IMP]. *)\n\nInductive mstep : (com * state) -> (com * state) -> Prop :=\n  | MS_Ass : forall st1 st2 X E,\n      st2 X = aeval E st1 ->\n      (forall Y, X <> Y -> st1 Y = st2 Y) ->\n      mstep (CAss X E, st1) (Skip, st2)\n  | MS_SeqStep : forall st c1 c1' st' c2,\n      mstep (c1, st) (c1', st') ->\n      mstep (c1 ;; c2 , st) (c1' ;; c2, st')\n  | MS_Seq : forall st c2,\n      mstep (Skip ;; c2, st) (c2, st)\n  | MS_IfTrue : forall st b c1 c2,\n      beval b st ->\n      mstep (If b Then c1 Else c2 EndIf, st) (c1, st)\n  | MS_IfFalse : forall st b c1 c2,\n      ~ beval b st ->\n      mstep (If b Then c1 Else c2 EndIf, st) (c2, st)\n  | MS_WhileTrue : forall st b c,\n      beval b st ->\n      mstep\n        (While b Do c EndWhile, st)\n        (c;; While b Do c EndWhile, st)\n  | MS_WhileFalse : forall st b c,\n      ~ beval b st ->\n      mstep (While b Do c EndWhile, st) (Skip, st).\n\nDefinition multi_mstep := clos_refl_trans mstep.\n\n(** Your task is to prove half of the semantic equivalence between this\n    middle step semantics and small step semantics. Specifically, your\n    eventual goal is:\n\n    Theorem Multi_MidStep_To_SmallStep: forall c st1 st2,\n      multi_mstep (c, st1) (Skip, st2) ->\n      multi_cstep (c, st1) (Skip, st2).\n\nTo prove this theorem, the main idea is to discover the relation between middle\nsteps [mstep] and small steps [cstep]. It is critical to see the following\nobservation: every middle step can be represented by finite small steps. In your\nproof, you can freely use the following theorems, which we have demostrated in\nclass. *)\n\nCheck semantic_equiv_aexp1.\n\n(* semantic_equiv_aexp1: forall st a n,\n  aeval a st = n -> multi_astep st a (ANum n). *)\n\nCheck semantic_equiv_bexp1.\n\n(* semantic_equiv_bexp1: forall st b,\n  (beval b st -> multi_bstep st b BTrue) /\\\n  (~ beval b st -> multi_bstep st b BFalse). *)\n\nCheck multi_congr_CAss.\n\n(* multi_congr_CAss: forall st X a a',\n  multi_astep st a a' ->\n  multi_cstep (CAss X a, st) (CAss X a', st). *)\n\nCheck multi_congr_CSeq.\n\n(* multi_congr_CSeq: forall st1 c1 st1' c1' c2,\n  multi_cstep (c1, st1) (c1', st1') ->\n  multi_cstep (CSeq c1 c2, st1) (CSeq c1' c2, st1'). *)\n\nCheck multi_congr_CIf.\n\n(* multi_congr_CIf: forall st b b' c1 c2,\n  multi_bstep st b b' ->\n  multi_cstep (CIf b c1 c2, st) (CIf b' c1 c2, st). *)\n\n(** **** Exercise: 4 stars, standard (One_MidStep_To_SmallStep)  *)\n\n(** Hint: In the following lemma, [a] and [b] are pairs of program commands and\n    program states. You may use tactics like [ destruct a as [c1 st1] ] so that\n    a real pair is demonstrated in the proof goal. But, you are the one to\n    choose between destructing them and not destructing them, depending on\n    which way is more convenient for building a Coq proof. *)\n\nLemma One_MidStep_To_SmallStep: forall a b,\n  mstep a b -> multi_cstep a b.\nProof.\n  intros.\n  induction H.\n  - symmetry in H. apply semantic_equiv_aexp1 in H.\n    apply multi_congr_CAss with (X:=X)  in H.\n    transitivity_n1 (X ::= st2 X, st1);auto.\n    apply CS_Ass;auto.\n  - apply multi_congr_CSeq. auto.\n  - transitivity_n1 (Skip;; c2, st);[reflexivity|].\n    apply CS_Seq.\n  - apply (proj1 (semantic_equiv_bexp1 _ _)) in H.\n    transitivity_n1 (If BTrue Then c1 Else c2 EndIf, st).\n    + apply multi_congr_CIf. auto.\n    + apply CS_IfTrue.\n  - apply (proj2 (semantic_equiv_bexp1 _ _)) in H.\n    transitivity_n1 (If BFalse Then c1 Else c2 EndIf, st).\n    + apply multi_congr_CIf. auto.\n    + apply CS_IfFalse.\n  - apply (proj1 (semantic_equiv_bexp1 _ _)) in H.\n    transitivity_1n (If b Then (c;; While b Do c EndWhile) Else Skip EndIf, st).\n    + apply CS_While.\n    + transitivity_n1 (If BTrue Then c;; While b Do c EndWhile Else Skip EndIf, st).\n      * apply multi_congr_CIf. auto.\n      * apply CS_IfTrue.\n  - apply (proj2 (semantic_equiv_bexp1 _ _)) in H.\n    transitivity_1n (If b Then (c;; While b Do c EndWhile) Else Skip EndIf, st).\n    + apply CS_While.\n    + transitivity_n1 (If BFalse Then c;; While b Do c EndWhile Else Skip EndIf, st).\n      * apply multi_congr_CIf. auto.\n      * apply CS_IfFalse.\nQed.\n\n(** Now, from this conclusion above to our final target, we only need two\n    properties about reflexive transitive closures. *)\n\n(** **** Exercise: 2 stars, standard (rt_idempotent)  *)\nTheorem rt_idempotent : forall (X: Type) (R: X -> X -> Prop) (x y: X),\n  clos_refl_trans (clos_refl_trans R) x y <-> clos_refl_trans R x y.\nProof.\n  intros. split;intro.\n  - induction H.\n    + auto.\n    + reflexivity.\n    + transitivity y;auto.\n  - apply rt_step. auto.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (rt_mono)  *)\nTheorem rt_mono : forall (X: Type) (R1 R2: X -> X -> Prop),\n  (forall x y, R1 x y -> R2 x y) ->\n  (forall x y, clos_refl_trans R1 x y -> clos_refl_trans R2 x y).\nProof.\n  intros.\n  induction_n1 H0.\n  - reflexivity.\n  - transitivity_n1 y;auto.\nQed.\n(** [] *)\n\n(** Here is our final target! *)\n\n(** **** Exercise: 2 stars, standard (Multi_MidStep_To_SmallStep)  *)\n\nTheorem Multi_MidStep_To_SmallStep: forall c st1 st2,\n  multi_mstep (c, st1) (Skip, st2) ->\n  multi_cstep (c, st1) (Skip, st2).\nProof.\n  intros.\n  induction H.\n  + apply One_MidStep_To_SmallStep in H. auto.\n  + reflexivity.\n  + apply (rt_mono _ _ _ One_MidStep_To_SmallStep) in H.\n    apply (rt_mono _ _ _ One_MidStep_To_SmallStep) in H0.\n    apply rt_idempotent.\n    transitivity y;auto.\nQed.\n(** [] *)\n\nEnd Task3.\n\n(* Fri Apr 17 00:44:35 CST 2020 *)\n", "meta": {"author": "ltzone", "repo": "2020Spring", "sha": "bc7fdf60850c81d77825cdcc77a1ad265da98f11", "save_path": "github-repos/coq/ltzone-2020Spring", "path": "github-repos/coq/ltzone-2020Spring/2020Spring-bc7fdf60850c81d77825cdcc77a1ad265da98f11/CS263/Assignment5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.6710384764165996}}
{"text": "Set Implicit Arguments.\nRequire Import List Lia std axioms.\nImport ListNotations.\n\n(** ** Multiplication Motivation  *)\nSection Motivation.\n\n  Variable (a b m n p: nat).\n\n  Definition succ '(a, b) := (n + a, 1 + b).\n  Definition ith i := (i * n + a, i + b).\n\n\n  Section Streams.\n\n    Implicit Type (X Y: nat -> (nat * nat)).\n\n    Definition charac {A: Type} (X: nat -> A) (a: A) (Y: nat -> A) :=\n      X 0 = a /\\ forall n, X (S n) = Y n.\n\n    Notation \"X ≈ Y ⟶ Z\" := (charac X Y Z) (at level 60).\n\n\n    Definition Succ X  := X >> succ.\n\n    Let X := ith. \n\n    Lemma X_satisfies:\n      X ≈ (a, b) ⟶ Succ X.\n    Proof.\n      split; unfold X, ith; cbn; intros; f_equal; lia. \n    Qed.\n\n    Lemma X_unique Y:\n      (Y ≈ (a, b) ⟶ Succ Y) -> forall i, Y i = X i.\n    Proof.\n      intros H; induction i.\n      - destruct H as [H _]. rewrite H. unfold X, ith. now simplify.\n      - destruct H as [_ H]. unfold Succ, funcomp in *.\n        rewrite H, IHi. unfold X, ith; cbn; f_equal; lia.\n    Qed.\n\n  End Streams.\n\n\n  Section FiniteSequences.\n    Implicit Type (X Y: list (nat * nat)).\n    \n    Notation succ' X := (map succ X).\n    \n    Lemma forward: p = m * n -> exists X, (a,b) :: succ' X = X ++ [(p + a, m + b)].\n    Proof.\n      intros ->. exists (tab ith m). \n      rewrite tab_map. change (tab _ _ ++ _) with (tab ith (S m)).\n      rewrite tab_S. unfold ith, succ. cbn. rewrite !tab_map_nats.\n      f_equal. eapply map_ext. intros i. f_equal; lia.\n    Qed.\n\n\n    Lemma backward' X x:\n      (a, b) :: succ' X = X ++ [x] -> x = ith (length X).\n    Proof.\n      unfold ith. induction X as [|[l r] X IH] in a, b, x |-*; eauto.\n      - cbn; simplify. intuition congruence. \n      - simplify. intros [= -> -> H]. eapply IH in H; subst.\n        cbn; simplify; f_equal; lia.\n    Qed.\n\n\n  \n    Lemma backward X:\n      (a,b) :: succ' X = X ++ [(p + a, m + b)] -> m * n = p.\n    Proof.\n      intros H % backward'. injection H.\n      intros; assert (m = |X|) as -> by lia. lia. \n    Qed.\n  End FiniteSequences.\n\n  \nEnd Motivation.\n\n", "meta": {"author": "uds-psl", "repo": "higher-order-unification-undecidability", "sha": "c1772adedca22d74f8c8d94b8610c31d22d46c7a", "save_path": "github-repos/coq/uds-psl-higher-order-unification-undecidability", "path": "github-repos/coq/uds-psl-higher-order-unification-undecidability/higher-order-unification-undecidability-c1772adedca22d74f8c8d94b8610c31d22d46c7a/coq/second_order/goldfarb/motivation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6710384737726628}}
{"text": "(** * 6.822 Formal Reasoning About Programs, Spring 2021 - Pset 3 *)\n\nRequire Import Frap.Frap.\n\n(* three-way comparisions, and [cases] support for them *)\nNotation Lt := (inleft (left _)) (only parsing).\nNotation Eq := (inleft (right _)) (only parsing).\nNotation Gt := (inright _) (only parsing).\nNotation compare := Compare_dec.lt_eq_lt_dec.\n\nModule Type S.\n  Inductive tree {A} :=\n  | Leaf\n  | Node (l : tree) (d : A) (r : tree).\n  Arguments tree : clear implicits.\n\n  Fixpoint flatten {A} (t : tree A) : list A :=\n    match t with\n    | Leaf => []\n    | Node l d r => flatten l ++ d :: flatten r\n    end.\n\n  Definition either {A} (xo yo : option A) : option A :=\n    match xo with\n    | None => yo\n    | Some x => Some x\n    end.\n\n\n  (* 1a) HOFs: id and compose *)\n\n  Definition id {A : Type} (x : A) : A := x.\n  Definition compose {A B C : Type} (g : B -> C) (f : A -> B) (x : A) : C := g (f x).\n\n  (*[0.5%]*)\n  Parameter compose_id_l : forall (A B : Type) (f : A -> B), compose id f = f.\n\n  (*[0.5%]*)\n  Parameter compose_id_r : forall (A B : Type) (f : A -> B), compose f id = f.\n\n  (*[1%]*)\n  Parameter compose_assoc :\n    forall (A B C D : Type) (f : A -> B) (g : B -> C) (h : C -> D),\n      compose h (compose g f) = compose (compose h g) f.\n\n  Fixpoint selfCompose{A: Type}(f: A -> A)(n: nat): A -> A :=\n    match n with\n    | O => id\n    | S n' => compose f (selfCompose f n')\n    end.\n\n  Parameter exp : nat -> nat -> nat.\n  (*[0.25%]*)\n  Parameter test_exp_3_2 : exp 3 2 = 9.\n  (*[0.25%]*)\n  Parameter test_exp_4_1 : exp 4 1 = 4.\n  (*[0.25%]*)\n  Parameter test_exp_5_0 : exp 5 0 = 1.\n  (*[0.25%]*)\n  Parameter test_exp_1_3 : exp 1 3 = 1.\n\n  (* 1b) HOFs: Left inverses *)\n\n  Definition left_inverse{A B: Type}(f: A -> B)(g: B -> A): Prop := compose g f = id.\n\n  (*[1%]*)\n  Parameter plus2minus2 : left_inverse (fun x : nat => x + 2) (fun x : nat => x - 2).\n\n  (*[2.5%]*)\n  Parameter minus2plus2 : ~ left_inverse (fun x : nat => x - 2) (fun x : nat => x + 2).\n\n  (*[4%]*)\n  Parameter left_invertible_injective:\n    forall {A} (f g: A -> A),\n      left_inverse f g ->\n      (forall x y, f x = f y -> x = y).\n\n  (*[0.25%]*)\n  Parameter left_inverse_id : forall {A : Type}, left_inverse (@id A) (@id A).\n\n  (*[8%]*)\n  Parameter invert_selfCompose :\n    forall {A : Type} (f g : A -> A) (n : nat), left_inverse f g -> left_inverse (selfCompose f n) (selfCompose g n).\n\n  (* 2a) Simple containers *)\n\n  (*[0.25%]*)\n  Parameter either_None_right : forall {A : Type} (xo : option A), either xo None = xo.\n\n  (*[0.5%]*)\n  Parameter either_assoc :\n    forall {A : Type} (xo yo zo : option A), either (either xo yo) zo = either xo (either yo zo).\n\n  Parameter head : forall {A : Type}, list A -> option A.\n\n  (*[1%]*)\n  Parameter head_example : head (1 :: 2 :: 3 :: nil) = Some 1.\n\n  (*[1%]*)\n  Parameter either_app_head :\n    forall {A : Type} (xs ys : list A), head (xs ++ ys) = either (head xs) (head ys).\n\n  Parameter leftmost_Node : forall {A : Type}, tree A -> option A.\n\n  (*[1%]*)\n  Parameter leftmost_Node_example : leftmost_Node (Node (Node Leaf 2 (Node Leaf 3 Leaf)) 1 Leaf) = Some 2.\n\n  (*[4%]*)\n  Parameter leftmost_Node_head : forall {A : Type} (t : tree A), leftmost_Node t = head (flatten t).\n\n\n  (* 2b) bitwise tries *)\n\n  Definition bitwise_trie A := tree (option A).\n\n  Parameter lookup : forall {A : Type}, list bool -> bitwise_trie A -> option A.\n\n  (*[1%]*)\n  Parameter lookup_example1 : lookup nil (Node Leaf (None : option nat) Leaf) = None.\n\n  (*[1%]*)\n  Parameter lookup_example2 :\n    lookup (false :: true :: nil)\n           (Node (Node Leaf (Some 2) Leaf) None (Node (Node Leaf (Some 1) Leaf) (Some 3) Leaf)) =\n    Some 1.\n\n  (*[1%]*)\n  Parameter lookup_empty : forall {A : Type} (k : list bool), lookup k (Leaf : bitwise_trie A) = None.\n\n  Parameter insert : forall {A : Type}, list bool -> option A -> bitwise_trie A -> bitwise_trie A.\n\n  (*[1%]*)\n  Parameter insert_example1 : lookup nil (insert nil None (Node Leaf (Some 0) Leaf)) = None.\n\n  (*[1%]*)\n  Parameter insert_example2 :\n    lookup nil (insert (true :: nil) (Some 2) (Node Leaf (Some 0) Leaf)) = Some 0.\n\n  (*[8%]*)\n  Parameter lookup_insert :\n    forall {A : Type} (k : list bool) (v : option A) (t : bitwise_trie A), lookup k (insert k v t) = v.\n\n  (*[2%]*)\n  Parameter map_id : forall {A : Type} (xs : list A), List.map id xs = xs.\n\n  (*[3%]*)\n  Parameter map_compose :\n    forall (A B C : Type) (g : B -> C) (f : A -> B) (xs : list A),\n      List.map (compose g f) xs = List.map g (List.map f xs).\n\n  (*[4%]*)\n  Parameter invert_map :\n    forall (A B : Type) (f : A -> B) (g : B -> A), left_inverse f g -> left_inverse (List.map f) (List.map g).\n\n  (* 2c) HOFs: tree_map *)\n\n  Parameter tree_map : forall {A B : Type}, (A -> B) -> tree A -> tree B.\n\n  (*[1%]*)\n  Parameter tree_map_example :\n    tree_map (fun x : nat => x + 1) (Node (Node Leaf 1 Leaf) 2 (Node Leaf 3 (Node Leaf 4 Leaf))) =\n    Node (Node Leaf 2 Leaf) 3 (Node Leaf 4 (Node Leaf 5 Leaf)).\n\n  (*[8%]*)\n  Parameter tree_map_flatten :\n    forall (A B : Type) (f : A -> B) (t : tree A), flatten (tree_map f t) = List.map f (flatten t).\n\n  Fixpoint tree_forall {A} (P: A -> Prop) (tr: tree A) :=\n    match tr with\n    | Leaf => True\n    | Node l d r => tree_forall P l /\\ P d /\\ tree_forall P r\n    end.\n\n  Parameter tree_exists : forall {A: Type}, (A -> Prop) -> tree A -> Prop.\n\n  (*[0.5%]*)\n  Parameter tree_exists_Leaf :\n    forall (A : Type) (P : A -> Prop), ~ tree_exists P Leaf.\n  (*[3%]*)\n  Parameter tree_forall_exists :\n    forall (A : Type) (P : A -> Prop) (tr : tree A),\n      tr <> Leaf -> tree_forall P tr -> tree_exists P tr.\n\n  (*[2%]*)\n  (* Explain what tree_forall_sound means *)\n\n  (*[3%]*)\n  Parameter tree_forall_sound :\n    forall (A : Type) (P : A -> Prop) (tr : tree A),\n      tree_forall P tr -> forall d : A, tree_exists (fun d' : A => d' = d) tr -> P d.\n\n  (* 2d) Binary search trees *)\n\n  Fixpoint listset (l: list nat) (s: nat -> Prop) :=\n    match l with\n    | [] =>\n      (* An empty list represents an empty set *)\n      forall x, ~ s x\n    | hd :: tl =>\n      (* Note how we remove an element from the propositional set: *)\n      s hd /\\ listset tl (fun x => x <> hd /\\ s x)\n    end.\n\n  Fixpoint list_member (a: nat) (l: list nat) :=\n    match l with\n    | [] => false\n    | hd :: tl =>\n      if a ==n hd then true else list_member a tl\n    end.\n\n  (*[4%]*)\n  Parameter list_member_lset: forall l s a,\n      listset l s ->\n      list_member a l = true <-> s a.\n\n  (*[3%]*)\n  Parameter list_member_lset': forall l s a,\n      listset l s ->\n      list_member a l = false <-> ~ (s a).\n\n  Definition list_insert (a: nat) (l: list nat) :=\n    if list_member a l then l else a :: l.\n\n  (*[8%]*)\n  Parameter list_insert_listset : forall l s a,\n      listset l s ->\n      listset (list_insert a l)\n              (fun x => s x \\/ x = a).\n\n  Fixpoint bst (tr : tree nat) (s : nat -> Prop) :=\n    match tr with\n    | Leaf => forall x, not (s x) (* s is empty set *)\n    | Node l d 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  (*[3%]*)\n  Parameter bst_implies :\n    forall (tr : tree nat) (s : nat -> Prop), bst tr s -> tree_forall s tr.\n\n  (*[1%]*)\n  Parameter bst_node_ordered :\n    forall (l : tree nat) (d : nat) (r : tree nat) (s : nat -> Prop),\n      bst (Node l d r) s ->\n      tree_forall (fun x : nat => x < d) l /\\ tree_forall (fun x : nat => x > d) r.\n\n  (*[5%]*)\n  Parameter bst_iff :\n    forall (tr : tree nat) (P Q : nat -> Prop),\n      bst tr P -> (forall x : nat, P x <-> Q x) -> bst tr Q.\n\n  Fixpoint bst_member (a: nat) (tr: tree nat) : bool :=\n    match tr with\n    | Leaf => false\n    | Node lt v rt =>\n      match compare a v with\n      | Lt => bst_member a lt\n      | Eq => true\n      | Gt => bst_member a rt\n      end\n    end.\n\n  (*[10%]*)\n  Parameter member_bst :\n    forall (tr : tree nat) (s : nat -> Prop) (a : nat),\n      bst tr s -> bst_member a tr = true <-> s a.\nEnd S.\n\n(* Here's a technical note on why this pset overrides a Frap tactic.\n   There's no need to understand this at all.\n\n   The \"simplify\" tactic provided by the Frap library is not quite suitable for this\n   pset, because it does \"autorewrite with core in *\" (which we commented out below),\n   and there's a Hint in Coq.Program.Combinators\n\n        Hint Rewrite <- @compose_assoc : core.\n\n   which causes \"autorewrite with core in *.\" to have the\n   same effect as\n\n   rewrite <-? Combinators.compose_assoc.\n\n   and apparently, rewrite does not just syntactic matching,\n   but matching modulo unification, so it will replace\n   our \"compose\" by \"Basics.compose\", and rewrite using\n   associativity of \"compose\" as many times as it can.\n   It's confusing to have \"Basics.compose\" appear in our goals,\n   and rewriting with associativity is something we want to teach in this\n   pset, so we redefine \"simplify\" to not use \"autorewrite\": *)\nLtac simplify ::=\n  repeat (unifyTails; pose proof I); repeat match goal with\n                                            | H:True |- _ => clear H\n                                            end;\n   repeat progress (simpl in *; intros(*; try autorewrite with core in * *); simpl_maps);\n   repeat normalize_set || doSubtract.\n\nLtac cases E :=\n  (is_var E; destruct E) ||\n    match type of E with\n    | sumor (sumbool _ _) _ => destruct E as [[]|]\n    | {_} + {_} => destruct E\n    | _ => let Heq := fresh \"Heq\" in\n           destruct E eqn:Heq\n    end;\n   repeat\n    match goal with\n    | H:_ = left _ |- _ => clear H\n    | H:_ = right _ |- _ => clear H\n    | H:_ = inleft _ |- _ => clear H\n    | H:_ = inright _ |- _ => clear H\n    end.\n", "meta": {"author": "mit-frap", "repo": "spring21", "sha": "20ecdeccfda50653abcdeb253dfc8118099f8c40", "save_path": "github-repos/coq/mit-frap-spring21", "path": "github-repos/coq/mit-frap-spring21/spring21-20ecdeccfda50653abcdeb253dfc8118099f8c40/pset03_ContainersAndHOFs/Pset3Sig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.6710384718045479}}
{"text": "(* Copyright 2012-2015 by Adam Petcher.\t\t\t\t*\n * Use of this source code is governed by the license described\t*\n * in the LICENSE file at the root of the source tree.\t\t*)\n\n\n(* Sampling an element from a finite cyclic group *)\nRequire Import fcf.FCF.\nRequire Export fcf.GroupTheory.\n\nLocal Open Scope group_scope.\n\nDefinition RndGrpElem`{FCG : FiniteCyclicGroup}{eqd : EqDec GroupElement} :=\n    n <-$ [0 .. order);\n    ret (g^n).\n\nSection RndGrpElem.\n\n  Context`{FCG : FiniteCyclicGroup}.\n  Hypothesis GroupElement_EqDec : EqDec GroupElement. \n\n  Theorem RndGrpElem_wf : well_formed_comp RndGrpElem.\n\n    unfold RndGrpElem.\n    wftac.\n\n  Qed.\n\n  Theorem groupExp_closed : forall k,\n    In (g^k) (getSupport RndGrpElem).\n\n    intuition.\n    erewrite groupExp_mod.\n    simpl.\n    eapply in_getUnique.\n    eapply in_flatten.\n    econstructor.\n    split.\n    eapply in_map_iff.\n    econstructor.\n    split.\n    eauto.\n    eapply filter_In.\n    split.\n    eapply in_getUnique.\n    eapply in_flatten.\n    econstructor.\n    split.\n    eapply in_map_iff.\n    econstructor.\n    split.\n    eapply eq_refl.\n    eapply in_getAllBvectors.\n    simpl.\n    left.\n    eapply eq_refl.\n    Focus 2.\n    rewrite bvToNat_natToBv_inverse.\n    simpl.\n    left.\n    eapply eq_refl.\n    eapply lognat_monotonic.\n    eapply modNat_lt.\n    rewrite bvToNat_natToBv_inverse.\n    unfold ltNatBool.\n    destruct (lt_dec (modNat k order) order); trivial.\n    exfalso.\n    eapply n.\n    eapply modNat_lt.\n    eapply lognat_monotonic.\n    eapply modNat_lt.\n\n    apply g_generator.\n  Qed.\n\n  Theorem RndGrpElem_uniform : forall x y,\n    evalDist RndGrpElem x == evalDist RndGrpElem y.\n\n    intuition.\n    unfold RndGrpElem.\n\n    eapply (evalDist_iso \n              (fun z => (modNat (z + (modNatAddInverse (groupLog g y) order) + (groupLog g x))) order) \n              (fun z => (modNat (z + (groupLog g y) + (modNatAddInverse (groupLog g x) order)) order))); intuition.\n\n    rewrite <- plus_assoc.\n    rewrite <- modNat_plus.\n    assert ((x0 + groupLog g y + modNatAddInverse (groupLog g x) order +\n      (modNatAddInverse (groupLog g y) order + groupLog g x)) = \n    ((groupLog g y + modNatAddInverse (groupLog g y) order) + \n      (groupLog g x + modNatAddInverse (groupLog g x) order +\n      x0)))%nat.\n    omega.\n    rewrite H0.\n    rewrite modNat_plus.\n    rewrite modNatAddInverse_correct.\n    rewrite plus_0_l.\n    rewrite modNat_plus.\n    rewrite modNatAddInverse_correct.\n    rewrite plus_0_l.\n    eapply modNat_eq.\n    eapply RndNat_support_lt.\n    trivial.\n\n    rewrite <- plus_assoc.\n    rewrite <- modNat_plus.\n    assert ((x0 + modNatAddInverse (groupLog g y) order + groupLog g x +\n      (groupLog g y + modNatAddInverse (groupLog g x) order)) = \n    (groupLog g x + modNatAddInverse (groupLog g x) order + \n      (groupLog g y + modNatAddInverse (groupLog g y) order + x0)))%nat.\n    omega.\n    rewrite H0.\n    rewrite modNat_plus.\n    rewrite modNatAddInverse_correct.\n    rewrite plus_0_l.\n    rewrite modNat_plus.\n    rewrite modNatAddInverse_correct.\n    rewrite plus_0_l.\n    eapply modNat_eq.\n    eapply RndNat_support_lt.\n    trivial.\n\n    eapply in_getSupport_RndNat.\n    eapply modNat_lt.\n\n    eapply RndNat_uniform.\n    eapply modNat_lt.\n\n    eapply RndNat_support_lt.\n    trivial.\n\n    subst.\n    rewrite <- groupExp_mod.\n    simpl.\n    destruct (EqDec_dec GroupElement_EqDec (groupExp g x0) y); subst.\n    rewrite groupExp_mod.\n    rewrite modNat_plus.\n    rewrite modNatAddInverse_correct_gen.\n    rewrite plus_0_l.\n    rewrite <- groupExp_mod.\n    rewrite group_cyclic.\n    destruct (EqDec_dec GroupElement_EqDec x x).\n    intuition.\n    congruence.\n    apply g_generator.\n    apply g_generator.\n\n    symmetry.\n    eapply groupLog_correct.\n    apply g_generator.\n    apply g_generator.\n\n    destruct (EqDec_dec GroupElement_EqDec\n         (groupExp g (x0 + modNatAddInverse (groupLog g y) order + groupLog g x)) x); intuition.\n    exfalso.\n    eapply n.\n    rewrite groupExp_plus in e.\n    rewrite group_cyclic in e.\n    eapply ident_l_unique in e.\n    rewrite <- (@groupIdent _ _ _ _ _ _ _ _ FCG g) in e.\n    eapply groupExp_eq in e.\n    rewrite (@modNat_eq order 0) in e.\n    eapply modNatAddInverse_sum_0 in e.\n    rewrite groupExp_mod.\n    rewrite e.\n    rewrite <- groupExp_mod.\n    rewrite group_cyclic.\n    trivial.\n    apply g_generator.\n    apply g_generator.\n    apply g_generator.\n\n    eapply posnat_pos.\n\n    apply g_generator.\n    apply g_generator.\n    apply g_generator.\n    apply g_generator.\n  Qed. \n\n  Theorem RndGrpElem_spec : \n    forall x y,\n      comp_spec (fun a b => a = x <-> b = y) RndGrpElem RndGrpElem.\n\n    intuition.\n    eapply eq_impl_comp_spec; eauto using RndGrpElem_wf.\n    eapply RndGrpElem_uniform.\n\n  Qed.\n\nEnd RndGrpElem.\n\nNotation \"'RndG'\" := (RndGrpElem)\n  (right associativity, at level 75) : comp_scope.", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/fcf/RndGrpElem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6709373369145418}}
{"text": "Inductive day : Type :=\n    | mon\n    | tue\n    | wed\n    | thu\n    | fri\n    | sat\n    | sun.\n\nDefinition nextday (d: day) : day :=\n    match d with\n    | mon => tue\n    | tue => wed\n    | wed => thu\n    | thu => fri\n    | fri => sat\n    | sat => sun\n    | sun => mon\n    end.\n\nCompute (nextday fri).\nCompute (nextday (nextday sun)).\n\nExample testnext:\n    (nextday (nextday sat)) = mon.\n\nProof. simpl. reflexivity. Qed.\n\nInductive bool: Type :=\n    | true\n    | false.\n\nDefinition negb (b: bool) : bool :=\n    match b with\n    | true => false\n    | false => true\n    end.\n\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    negb (andb b1 b2).\n\n\nExample test1: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\n\n(* Example test2: (andb true false) = true.\nProof. simpl. reflexivity. Qed. *)\n\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nCompute (true && false).\n\nExample test3: false || true || false = true.\nProof. simpl. reflexivity. Qed.\n\nExample test4: nandb true true = false.\nProof. simpl. reflexivity. Qed.\n\nCheck true.\nCheck negb.\n\nInductive rgb: Type :=\n    | red\n    | green\n    | blue.\n\nInductive color: Type :=\n    | black\n    | white\n    | primary (p: rgb).\n\nDefinition monochrome (c: color) : bool :=\n    match c with\n    | black => true\n    | white => true\n    | primary 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\n\nCompute (monochrome (primary red)).\nCompute (isred (primary red)).\n\nCheck primary.\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\nDefinition allzero (nb: nybble) : bool :=\n    match nb with\n    | (bits B0 B0 B0 B0) => true\n    | _ => false\n    end.\n\nCompute (allzero (bits B1 B0 B1 B0)).\nCompute (allzero (bits B0 B0 B0 B0)).\n", "meta": {"author": "Meowcolm024", "repo": "sf", "sha": "8ec734274600d60b0b7e905bb3d861779031bee8", "save_path": "github-repos/coq/Meowcolm024-sf", "path": "github-repos/coq/Meowcolm024-sf/sf-8ec734274600d60b0b7e905bb3d861779031bee8/lf/days.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.6709219777354475}}
{"text": "(* week-06_soundness-and-completeness-of-equality-predicates.v *)\n(* FPP 2020 - YSC3236 2020-2021, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 20 Sep 2020 *)\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\nCheck Bool.eqb. (* : bool -> bool -> bool *)\n\nCheck eqb. (* : bool -> bool -> bool *)\n\nSearch (eqb _ _ = true -> _ = _).\n(* eqb_prop: forall a b : bool, eqb a b = true -> a = b *)\n\nSearch (eqb _ _ = true).\n(* eqb_reflx: forall b : bool, eqb b b = true *)\n\nTheorem soundness_of_equality_over_booleans :\n  forall b1 b2 : bool,\n    eqb b1 b2 = true -> b1 = b2.\nProof.\n  exact eqb_prop.\n\n  Restart.\n\n  intros [ | ] [ | ].\n  - intros _.\n    reflexivity.\n  - unfold eqb.\n    intro H_absurd.\n    discriminate H_absurd.\n  - unfold eqb.\n    intro H_absurd.\n    exact H_absurd.\n  - intros _.\n    reflexivity.\nQed.\n\nTheorem completeness_of_equality_over_booleans :\n  forall b1 b2 : bool,\n    b1 = b2 -> eqb b1 b2 = true.\nProof.\n  intros b1 b2 H_b1_b2.\n  rewrite <- H_b1_b2.\n  Search (eqb _ _ = true).\n  Check (eqb_reflx b1).\n  exact (eqb_reflx b1).\n\n  Restart.\n\n  intros [ | ] [ | ].\n  - intros _.\n    unfold eqb.\n    reflexivity.\n  - intros H_absurd.\n    discriminate H_absurd.\n  - intros H_absurd.\n    discriminate H_absurd.\n  - intros _.\n    unfold eqb.\n    reflexivity.\nQed.\n\nCorollary soundness_of_equality_over_booleans_the_remaining_case :\n  forall b1 b2 : bool,\n    eqb b1 b2 = false -> b1 <> b2.\nProof.\n  intros b1 b2 H_eqb_b1_b2.\n  unfold not.\n  intros H_eq_b1_b2.\n  Check (completeness_of_equality_over_booleans b1 b2 H_eq_b1_b2).\n  rewrite -> (completeness_of_equality_over_booleans b1 b2 H_eq_b1_b2) in H_eqb_b1_b2.\n  discriminate H_eqb_b1_b2.\nQed.\n\nCorollary completeness_of_equality_over_booleans_the_remaining_case :\n  forall b1 b2 : bool,\n    b1 <> b2 -> eqb b1 b2 = false.\nProof.\n  intros b1 b2 H_neq_b1_b2.\n  unfold not in H_neq_b1_b2.\n  Search (not (_ = true) -> _ = false).\n  Check (not_true_is_false (eqb b1 b2)).\n  apply (not_true_is_false (eqb b1 b2)).\n  unfold not.\n  intro H_eqb_b1_b2.\n  Check (soundness_of_equality_over_booleans b1 b2 H_eqb_b1_b2).\n  Check (H_neq_b1_b2 (soundness_of_equality_over_booleans b1 b2 H_eqb_b1_b2)).\n  contradiction (H_neq_b1_b2 (soundness_of_equality_over_booleans b1 b2 H_eqb_b1_b2)).\n(* Or alternatively:\n  exact (H_neq_b1_b2 (soundness_of_equality_over_booleans b1 b2 H_eqb_b1_b2)).\n*)\nQed. \n\nCheck Bool.eqb_eq.\n(* eqb_eq : forall x y : bool, Is_true (eqb x y) -> x = y *)\n\nSearch (eqb _ _ = true).\n(* eqb_true_iff: forall a b : bool, eqb a b = true <-> a = b *)\n\nTheorem soundness_and_completeness_of_equality_over_booleans :\n  forall b1 b2 : bool,\n    eqb b1 b2 = true <-> b1 = b2.\nProof.\n  exact eqb_true_iff.\n\n  Restart.\n\n  intros b1 b2.\n  split.\n  - exact (soundness_of_equality_over_booleans b1 b2).\n  - exact (completeness_of_equality_over_booleans b1 b2).\nQed.\n\n(* ********** *)\n\nCheck Nat.eqb. (* : nat -> nat -> bool *)\n\nCheck beq_nat. (* : nat -> nat -> bool *)\n\nSearch (beq_nat _ _ = true -> _ = _).\n(* beq_nat_true: forall n m : nat, (n =? m) = true -> n = m *)\n\nSearch (beq_nat _ _ = true).\n\n(* Nat.eqb_eq: forall n m : nat, (n =? m) = true <-> n = m *)\n\nTheorem soundness_and_completeness_of_equality_over_natural_numbers :\n  forall n1 n2 : nat,\n    n1 =? n2 = true <-> n1 = n2.\nProof.\n  exact Nat.eqb_eq.\nQed.\n\n(* ********** *)\n\nTheorem soundness_and_completeness_of_equality_over_natural_numbers_the_remaining_case :\n  forall n1 n2 : nat,\n    n1 =? n2 = false <-> n1 <> n2.\nProof.\n  intros n1 n2.\n  unfold not.\n  split.\n  - intros H_eqb H_eq.\n    Check (soundness_and_completeness_of_equality_over_natural_numbers n1 n2).\n    destruct (soundness_and_completeness_of_equality_over_natural_numbers n1 n2) as [_ C_eqb_nat].\n    rewrite -> (C_eqb_nat H_eq) in H_eqb.\n    discriminate H_eqb.\n  - intros H_eq.\n    Search (_ <> true -> _ = false).\n    apply (not_true_is_false (n1 =? n2)).\n    unfold not.\n    intro H_eqb.\n    destruct (soundness_and_completeness_of_equality_over_natural_numbers n1 n2) as [C_eqb_nat _].\n    contradiction (H_eq (C_eqb_nat H_eqb)).\nQed.\n\nLemma from_one_equivalence_to_two_implications :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool),\n    (forall v1 v2 : V,\n        eqb_V v1 v2 = true <-> v1 = v2) ->\n    (forall v1 v2 : V,\n        eqb_V v1 v2 = true -> v1 = v2)\n    /\\\n    (forall v1 v2 : V,\n        v1 = v2 -> eqb_V v1 v2 = true).\nProof.\n  intros V eqb_V H_eqv.\n  split.\n  - intros v1 v2 H_eqb.\n    destruct (H_eqv v1 v2) as [H_key _].\n    exact (H_key H_eqb).\n  - intros v1 v2 H_eq.\n    destruct (H_eqv v1 v2) as [_ H_key].\n    exact (H_key H_eq).\nQed.\n\n(* ********** *)\n\nDefinition eqb_option (V : Type) (eqb_V : V -> V -> bool) (ov1 ov2 : option V) : bool :=\n  match ov1 with\n  | Some v1 =>\n    match ov2 with\n    | Some v2 =>\n      eqb_V v1 v2\n    | None =>\n      false\n    end\n  | None =>\n    match ov2 with\n    | Some v2 =>\n      false\n    | None =>\n      true\n    end\n  end.\n\nTheorem soundness_of_equality_over_optional_values :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool),\n    (forall v1 v2 : V,\n        eqb_V v1 v2 = true -> v1 = v2) ->\n    forall ov1 ov2 : option V,\n      eqb_option V eqb_V ov1 ov2 = true ->\n      ov1 = ov2.\nProof.\n  intros V eqb_V S_eqb_V [v1 | ] [v2 | ] H_eqb.\n  - unfold eqb_option in H_eqb.\n    Check (S_eqb_V v1 v2 H_eqb).\n    rewrite -> (S_eqb_V v1 v2 H_eqb).\n    reflexivity.\n  - unfold eqb_option in H_eqb.\n    discriminate H_eqb.\n  - unfold eqb_option in H_eqb.\n    discriminate H_eqb.\n  - reflexivity.\nQed.\n\nTheorem completeness_of_equality_over_optional_values :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool),\n    (forall v1 v2 : V,\n        v1 = v2 -> eqb_V v1 v2 = true) ->\n    forall ov1 ov2 : option V,\n      ov1 = ov2 ->\n      eqb_option V eqb_V ov1 ov2 = true.\nProof.\n  intros V eqb_V C_eqb_V ov1 ov2 H_eq.\n  rewrite -> H_eq.\n  case ov1 as [v1 | ].\n  - case ov2 as [v2 | ].\n    -- unfold eqb_option.\n       Check (eq_refl v2).\n       Check (C_eqb_V v2 v2 (eq_refl v2)).\n       exact (C_eqb_V v2 v2 (eq_refl v2)).\n    -- discriminate H_eq.\n  - case ov2 as [v2 | ].\n    -- discriminate H_eq.\n    -- unfold eqb_option.\n       reflexivity.\nQed.\n\nTheorem soundness_and_completeness_of_equality_over_optional_values :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool),\n    (forall v1 v2 : V,\n        eqb_V v1 v2 = true <-> v1 = v2) ->\n    forall ov1 ov2 : option V,\n      eqb_option V eqb_V ov1 ov2 = true <-> ov1 = ov2.\nProof.\n  intros V eqb_V SC_eqb_V.\n  Check (from_one_equivalence_to_two_implications V eqb_V SC_eqb_V).\n  destruct (from_one_equivalence_to_two_implications V eqb_V SC_eqb_V) as [S_eqb_V C_eqb_V].\n  intros ov1 ov2.\n  split.\n  - exact (soundness_of_equality_over_optional_values V eqb_V S_eqb_V ov1 ov2).\n  - exact (completeness_of_equality_over_optional_values V eqb_V C_eqb_V ov1 ov2).\nQed.\n\n(*** Exercise 7 *)\n(* ... *)\n\n(* ********** *)\n\nDefinition eqb_pair (V : Type) (eqb_V : V -> V -> bool) (W : Type) (eqb_W : W -> W -> bool) (p1 p2 : V * W) : bool :=\n  let (v1, w1) := p1 in\n  let (v2, w2) := p2 in\n  eqb_V v1 v2 && eqb_W w1 w2.\n\nTheorem soundness_of_equality_over_pairs :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool),\n    (forall v1 v2 : V,\n        eqb_V v1 v2 = true -> v1 = v2) ->\n    forall (W : Type)\n           (eqb_W : W -> W -> bool),\n      (forall w1 w2 : W,\n          eqb_W w1 w2 = true -> w1 = w2) ->\n      forall p1 p2 : V * W,\n        eqb_pair V eqb_V W eqb_W p1 p2 = true ->\n        p1 = p2.\nProof.\n  intros V eqb_V S_eqb_V W eqb_W S_eqb_W [v1 w1] [v2 w2] H_eqb.\n  unfold eqb_pair in H_eqb.\n  Search (_ && _ = true -> _ /\\ _).\n  Check (andb_prop (eqb_V v1 v2) (eqb_W w1 w2)).\n  Check (andb_prop (eqb_V v1 v2) (eqb_W w1 w2) H_eqb).\n  destruct (andb_prop (eqb_V v1 v2) (eqb_W w1 w2) H_eqb) as [H_eqb_V H_eqb_W].\n  Check (S_eqb_V v1 v2 H_eqb_V).\n  rewrite -> (S_eqb_V v1 v2 H_eqb_V).\n  rewrite -> (S_eqb_W w1 w2 H_eqb_W).\n  reflexivity.\nQed.\n\nTheorem completeness_of_equality_over_pairs :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool),\n    (forall v1 v2 : V,\n        v1 = v2 -> eqb_V v1 v2 = true) ->\n    forall (W : Type)\n           (eqb_W : W -> W -> bool),\n      (forall w1 w2 : W,\n          w1 = w2 -> eqb_W w1 w2 = true) ->\n      forall p1 p2 : V * W,\n        p1 = p2 ->\n        eqb_pair V eqb_V W eqb_W p1 p2 = true.\nProof.\n  intros V eqb_V S_eqb_V W eqb_W S_eqb_W [v1 w1] [v2 w2] H_eq.\n  unfold eqb_pair.\n  injection H_eq as H_eq_V H_eq_W.\n  Check (S_eqb_V v1 v2 H_eq_V).\n  rewrite -> (S_eqb_V v1 v2 H_eq_V).\n  rewrite -> (S_eqb_W w1 w2 H_eq_W).\n  unfold andb.\n  reflexivity.\nQed.\n\nTheorem soundness_and_completeness_of_equality_over_pairs :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool),\n    (forall v1 v2 : V,\n        eqb_V v1 v2 = true <-> v1 = v2) ->\n    forall (W : Type)\n           (eqb_W : W -> W -> bool),\n      (forall w1 w2 : W,\n          eqb_W w1 w2 = true <-> w1 = w2) ->\n      forall p1 p2 : V * W,\n        eqb_pair V eqb_V W eqb_W p1 p2 = true <-> p1 = p2.\nProof.\n  intros V eqb_V SC_eqb_V.\n  Check (from_one_equivalence_to_two_implications V eqb_V SC_eqb_V).\n  destruct (from_one_equivalence_to_two_implications V eqb_V SC_eqb_V) as [S_eqb_V C_eqb_V].\n  intros W eqb_W SC_eqb_W.\n  Check (from_one_equivalence_to_two_implications W eqb_W SC_eqb_W).\n  destruct (from_one_equivalence_to_two_implications W eqb_W SC_eqb_W) as [S_eqb_W C_eqb_W].\n  intros p1 p2.\n  split.\n  - exact (soundness_of_equality_over_pairs V eqb_V S_eqb_V W eqb_W S_eqb_W p1 p2).\n  - exact (completeness_of_equality_over_pairs V eqb_V C_eqb_V W eqb_W C_eqb_W p1 p2).\nQed.\n\n(* ********** *)\n\nInductive binary_tree (V : Type) : Type :=\n| Leaf : V -> binary_tree V\n| Node : binary_tree V -> binary_tree V -> binary_tree V.\n\nFixpoint eqb_binary_tree (V : Type) (eqb_V : V -> V -> bool) (t1 t2 : binary_tree V) : bool :=\n  match t1 with\n  | Leaf _ v1 =>\n    match t2 with\n    | Leaf _ v2 =>\n      eqb_V v1 v2\n    | Node _ t11 t12 =>\n      false\n    end\n  | Node _ t11 t12 =>\n    match t2 with\n    | Leaf _ v2 =>\n      false\n    | Node _ t21 t22 =>\n      eqb_binary_tree V eqb_V t11 t21\n      &&\n      eqb_binary_tree V eqb_V t12 t22\n    end\n  end.\n\nLemma fold_unfold_eqb_binary_tree_Leaf :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool)\n         (v1 : V)\n         (t2 : binary_tree V),\n    eqb_binary_tree V eqb_V (Leaf V v1) t2 =\n    match t2 with\n    | Leaf _ v2 =>\n      eqb_V v1 v2\n    | Node _ t11 t12 =>\n      false\n    end.\nProof.\n  fold_unfold_tactic eqb_binary_tree.\nQed.\n\nLemma fold_unfold_eqb_binary_tree_Node :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool)\n         (t11 t12 t2 : binary_tree V),\n    eqb_binary_tree V eqb_V (Node V t11 t12) t2 =\n    match t2 with\n    | Leaf _ v2 =>\n      false\n    | Node _ t21 t22 =>\n      eqb_binary_tree V eqb_V t11 t21\n      &&\n      eqb_binary_tree V eqb_V t12 t22\n    end.\nProof.\n  fold_unfold_tactic eqb_binary_tree.\nQed.\n\nTheorem soundness_of_equality_over_binary_trees :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool),\n    (forall v1 v2 : V,\n        eqb_V v1 v2 = true -> v1 = v2) ->\n    forall t1 t2 : binary_tree V,\n      eqb_binary_tree V eqb_V t1 t2 = true ->\n      t1 = t2.\nProof.\n  intros V eqb_V C_eqb_V t1.\n  induction t1 as [v1 | t11 IHt11 t12 IHt12].\n  - intros [v2 | t21 t22] H_eqb.\n    -- rewrite -> (fold_unfold_eqb_binary_tree_Leaf V eqb_V v1 (Leaf V v2)) in H_eqb.\n       Check (C_eqb_V v1 v2 H_eqb).\n       rewrite -> (C_eqb_V v1 v2 H_eqb).\n       reflexivity.\n    -- rewrite -> (fold_unfold_eqb_binary_tree_Leaf V eqb_V v1 (Node V t21 t22)) in H_eqb.\n       discriminate H_eqb.\n  - intros [v2 | t21 t22] H_eqb.\n    -- rewrite -> (fold_unfold_eqb_binary_tree_Node V eqb_V t11 t12 (Leaf V v2)) in H_eqb.\n       discriminate H_eqb.\n    -- rewrite -> (fold_unfold_eqb_binary_tree_Node V eqb_V t11 t12 (Node V t21 t22)) in H_eqb.\n       Search (_ && _ = true -> _ /\\ _).\n       Check (andb_prop (eqb_binary_tree V eqb_V t11 t21) (eqb_binary_tree V eqb_V t12 t22)).\n       Check (andb_prop (eqb_binary_tree V eqb_V t11 t21) (eqb_binary_tree V eqb_V t12 t22) H_eqb).\n       destruct (andb_prop (eqb_binary_tree V eqb_V t11 t21) (eqb_binary_tree V eqb_V t12 t22) H_eqb) as [H_eqb_1 H_eqb_2].\n       Check (IHt11 t21 H_eqb_1).\n       rewrite -> (IHt11 t21 H_eqb_1).\n       rewrite -> (IHt12 t22 H_eqb_2).\n       reflexivity.\nQed.\n\nTheorem completeness_of_equality_over_binary_trees :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool),\n    (forall v1 v2 : V,\n        v1 = v2 -> eqb_V v1 v2 = true) ->\n    forall t1 t2 : binary_tree V,\n      t1 = t2 ->\n      eqb_binary_tree V eqb_V t1 t2 = true.\nProof.\n  intros V eqb_V C_eqb_V t1.\n  induction t1 as [v1 | t11 IHt11 t12 IHt12].\n  - intros [v2 | t21 t22] H_eq.\n    -- rewrite -> (fold_unfold_eqb_binary_tree_Leaf V eqb_V v1 (Leaf V v2)).\n       injection H_eq as H_eq_V.\n       Check (C_eqb_V v1 v2).\n       Check (C_eqb_V v1 v2 H_eq_V).\n       exact (C_eqb_V v1 v2 H_eq_V).\n    -- discriminate H_eq.\n  - intros [v2 | t21 t22] H_eq.\n    -- discriminate H_eq.\n    -- rewrite -> (fold_unfold_eqb_binary_tree_Node V eqb_V t11 t12 (Node V t21 t22)).\n       injection H_eq as H_eq_1 H_eq_2.\n       Check (IHt11 t21 H_eq_1).\n       rewrite -> (IHt11 t21 H_eq_1).\n       rewrite -> (IHt12 t22 H_eq_2).\n       unfold andb.\n       reflexivity.\nQed.\n\nTheorem soundness_and_completeness_of_equality_over_binary_trees :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool),\n    (forall v1 v2 : V,\n        eqb_V v1 v2 = true <-> v1 = v2) ->\n    forall t1 t2 : binary_tree V,\n      eqb_binary_tree V eqb_V t1 t2 = true <-> t1 = t2.\nProof.\n  intros V eqb_V SC_eqb_V t1 t2.\n  Check (from_one_equivalence_to_two_implications V eqb_V SC_eqb_V).\n  destruct (from_one_equivalence_to_two_implications V eqb_V SC_eqb_V) as [S_eqb_V C_eqb_V].\n  split.\n  - exact (soundness_of_equality_over_binary_trees V eqb_V S_eqb_V t1 t2).\n  - exact (completeness_of_equality_over_binary_trees V eqb_V C_eqb_V t1 t2).\n\n  Restart.\n\n  intros V eqb_V SC_eqb_V t1.\n  induction t1 as [v1 | t11 IHt11 t12 IHt12].\n  - intros [v2 | t21 t22].\n    + rewrite -> (fold_unfold_eqb_binary_tree_Leaf V eqb_V v1 (Leaf V v2)).\n      split.\n      * intro H_eqb_V.\n        destruct (from_one_equivalence_to_two_implications V eqb_V SC_eqb_V) as [S_eqb_V _].\n        rewrite -> (S_eqb_V v1 v2 H_eqb_V).\n        reflexivity.\n      * intro H_eq.\n        injection H_eq as H_eq.\n        destruct (from_one_equivalence_to_two_implications V eqb_V SC_eqb_V) as [_ C_eqb_V].\n        exact (C_eqb_V v1 v2 H_eq).\n    + rewrite -> (fold_unfold_eqb_binary_tree_Leaf V eqb_V v1 (Node V t21 t22)).\n      split.\n      * intro H_absurd.\n        discriminate H_absurd.\n      * intro H_absurd.\n        discriminate H_absurd.\n  - intros [v2 | t21 t22].\n    + rewrite -> (fold_unfold_eqb_binary_tree_Node V eqb_V t11 t12 (Leaf V v2)).\n      split.\n      * intro H_absurd.\n        discriminate H_absurd.\n      * intro H_absurd.\n        discriminate H_absurd.\n    + rewrite -> (fold_unfold_eqb_binary_tree_Node V eqb_V t11 t12 (Node V t21 t22)).\n      split.\n      * intro H_eqb.\n        destruct (andb_prop (eqb_binary_tree V eqb_V t11 t21) (eqb_binary_tree V eqb_V t12 t22) H_eqb) as [H_eqb_1 H_eqb_2].\n        destruct (IHt11 t21) as [H_key1 _].\n        destruct (IHt12 t22) as [H_key2 _].\n        rewrite -> (H_key1 H_eqb_1).\n        rewrite -> (H_key2 H_eqb_2).\n        reflexivity.\n      * intro H_eq.\n        injection H_eq as H_eq_1 H_eq_2.\n        destruct (IHt11 t21) as [_ H_key1].\n        destruct (IHt12 t22) as [_ H_key2].\n        rewrite -> (H_key1 H_eq_1).\n        rewrite -> (H_key2 H_eq_2).\n        unfold andb.\n        reflexivity.\nQed.        \n\n(* ********** *)\n\n(* end of week-06_soundness-and-completeness-of-equality-predicates.v *)\n\n", "meta": {"author": "soedirgo", "repo": "fpp", "sha": "5a43df151c5c8bc3f49d449ffd6f3eac67a16eab", "save_path": "github-repos/coq/soedirgo-fpp", "path": "github-repos/coq/soedirgo-fpp/fpp-5a43df151c5c8bc3f49d449ffd6f3eac67a16eab/w06/week-06_soundness-and-completeness-of-equality-predicates.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059462938815, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.670921977251722}}
{"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 path div fintype.\nFrom mathcomp\nRequire Import finfun bigop finset prime binomial fingroup morphism perm.\nFrom mathcomp\nRequire Import automorphism action quotient gfunctor gproduct ssralg finalg.\nFrom mathcomp\nRequire Import zmodp cyclic pgroup gseries nilpotent sylow.\n\n(******************************************************************************)\n(* Constructions based on abelian groups and their structure, with some       *)\n(* emphasis on elementary abelian p-groups.                                   *)\n(*          'Ldiv_n() == the set of all x that satisfy x ^+ n = 1, or,        *)\n(*                       equivalently the set of x whose order divides n.     *)\n(*         'Ldiv_n(G) == the set of x in G that satisfy x ^+ n = 1.           *)\n(*                    := G :&: 'Ldiv_n() (pure Notation)                      *)\n(*         exponent G == the exponent of G: the least e such that x ^+ e = 1  *)\n(*                       for all x in G (the LCM of the orders of x \\in G).   *)\n(*                       If G is nilpotent its exponent is reached. Note that *)\n(*                       `exponent G %| m' reads as `G has exponent m'.       *)\n(*              'm(G) == the generator rank of G: the size of a smallest      *)\n(*                       generating set for G (this is a basis for G if G     *)\n(*                       abelian).                                            *)\n(*     abelian_type G == the abelian type of G : if G is abelian, a lexico-   *)\n(*                       graphically maximal sequence of the orders of the    *)\n(*                       elements of a minimal basis of G (if G is a p-group  *)\n(*                       this is the sequence of orders for any basis of G,   *)\n(*                       sorted in decending order).                          *)\n(*       homocyclic G == G is the direct product of cycles of equal order,    *)\n(*                       i.e., G is abelian with constant abelian type.       *)\n(*        p.-abelem G == G is an elementary abelian p-group, i.e., it is      *)\n(*                       an abelian p-group of exponent p, and thus of order  *)\n(*                       p ^ 'm(G) and rank (logn p #|G|).                    *)\n(*        is_abelem G == G is an elementary abelian p-group for some prime p. *)\n(*            'E_p(G) == the set of elementary abelian p-subgroups of G.      *)\n(*                    := [set E : {group _} | p.-abelem E & E \\subset G]      *)\n(*          'E_p^n(G) == the set of elementary abelian p-subgroups of G of    *)\n(*                       order p ^ n (or, equivalently, of rank n).           *)\n(*                    := [set E in 'E_p(G) | logn p #|E| == n]                *)\n(*                    := [set E in 'E_p(G) | #|E| == p ^ n]%N if p is prime   *)\n(*           'E*_p(G) == the set of maximal elementary abelian p-subgroups    *)\n(*                       of G.                                                *)\n(*                    := [set E | [max E | E \\in 'E_p(G)]]                    *)\n(*            'E^n(G) == the set of elementary abelian subgroups of G that    *)\n(*                       have gerank n (i.e., p-rank n for some prime p).     *)\n(*                    := \\bigcup_(0 <= p < #|G|.+1) 'E_p^n(G)                 *)\n(*            'r_p(G) == the p-rank of G: the maximal rank of an elementary   *)\n(*                       subgroup of G.                                       *)\n(*                    := \\max_(E in 'E_p(G)) logn p #|E|.                     *)\n(*              'r(G) == the rank of G.                                       *)\n(*                    := \\max_(0 <= p < #|G|.+1) 'm_p(G).                     *)\n(* Note that 'r(G) coincides with 'r_p(G) if G is a p-group, and with 'm(G)   *)\n(* if G is abelian, but is much more useful than 'm(G) in the proof of the    *)\n(* Odd Order Theorem.                                                         *)\n(*          'Ohm_n(G) == the group generated by the x in G with order p ^ m   *)\n(*                       for some prime p and some m <= n. Usually, G will be *)\n(*                       a p-group, so 'Ohm_n(G) will be generated by         *)\n(*                       'Ldiv_(p ^ n)(G), set of elements of G of order at   *)\n(*                       most p ^ n. If G is also abelian then 'Ohm_n(G)      *)\n(*                       consists exactly of those element, and the abelian   *)\n(*                       type of G can be computed from the orders of the     *)\n(*                       'Ohm_n(G) subgroups.                                 *)\n(*          'Mho^n(G) == the group generated by the x ^+ (p ^ n) for x a      *)\n(*                       p-element of G for some prime p. Usually G is a      *)\n(*                       p-group, and 'Mho^n(G) is generated by all such      *)\n(*                       x ^+ (p ^ n); it consists of exactly these if G is   *)\n(*                       also abelian.                                        *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GroupScope.\n\nSection AbelianDefs.\n\n(* We defer the definition of the functors ('Omh_n(G), 'Mho^n(G)) because     *)\n(* they must quantify over the finGroupType explicitly.                       *)\n\nVariable gT : finGroupType.\nImplicit Types (x : gT) (A B : {set gT}) (pi : nat_pred) (p n : nat).\n\nDefinition Ldiv n := [set x : gT | x ^+ n == 1].\n\nDefinition exponent A := \\big[lcmn/1%N]_(x in A) #[x].\n\nDefinition abelem p A := [&& p.-group A, abelian A & exponent A %| p].\n\nDefinition is_abelem A := abelem (pdiv #|A|) A.\n\nDefinition pElem p A := [set E : {group gT} | E \\subset A & abelem p E].\n\nDefinition pnElem p n A := [set E in pElem p A | logn p #|E| == n].\n\nDefinition nElem n A :=  \\bigcup_(0 <= p < #|A|.+1) pnElem p n A.\n\nDefinition pmaxElem p A := [set E | [max E | E \\in pElem p A]].\n\nDefinition p_rank p A := \\max_(E in pElem p A) logn p #|E|.\n\nDefinition rank A := \\max_(0 <= p < #|A|.+1) p_rank p A.\n\nDefinition gen_rank A := #|[arg min_(B < A | <<B>> == A) #|B|]|.\n\n(* The definition of abelian_type depends on an existence lemma. *)\n(* The definition of homocyclic depends on abelian_type. *)\n\nEnd AbelianDefs.\n\nArguments exponent {gT} A%g.\nArguments abelem {gT} p%N A%g.\nArguments is_abelem {gT} A%g.\nArguments pElem {gT} p%N A%g.\nArguments pnElem {gT} p%N n%N A%g.\nArguments nElem {gT} n%N A%g.\nArguments pmaxElem {gT} p%N A%g.\nArguments p_rank {gT} p%N A%g.\nArguments rank {gT} A%g.\nArguments gen_rank {gT} A%g.\n\nNotation \"''Ldiv_' n ()\" := (Ldiv _ n)\n  (at level 8, n at level 2, format \"''Ldiv_' n ()\") : group_scope.\n\nNotation \"''Ldiv_' n ( G )\" := (G :&: 'Ldiv_n())\n  (at level 8, n at level 2, format \"''Ldiv_' n ( G )\") : group_scope.\n\nPrenex Implicits exponent.\n\nNotation \"p .-abelem\" := (abelem p)\n  (at level 2, format \"p .-abelem\") : group_scope.\n\nNotation \"''E_' p ( G )\" := (pElem p G)\n  (at level 8, p at level 2, format \"''E_' p ( G )\") : group_scope.\n\nNotation \"''E_' p ^ n ( G )\" := (pnElem p n G)\n  (at level 8, p, n at level 2, format \"''E_' p ^ n ( G )\") : group_scope.\n\nNotation \"''E' ^ n ( G )\" := (nElem n G)\n  (at level 8, n at level 2, format \"''E' ^ n ( G )\") : group_scope.\n\nNotation \"''E*_' p ( G )\" := (pmaxElem p G)\n  (at level 8, p at level 2, format \"''E*_' p ( G )\") : group_scope.\n\nNotation \"''m' ( A )\" := (gen_rank A)\n  (at level 8, format \"''m' ( A )\") : group_scope.\n\nNotation \"''r' ( A )\" := (rank A)\n  (at level 8, format \"''r' ( A )\") : group_scope.\n\nNotation \"''r_' p ( A )\" := (p_rank p A)\n  (at level 8, p at level 2, format \"''r_' p ( A )\") : group_scope.\n\nSection Functors.\n\n(* A functor needs to quantify over the finGroupType just beore the set. *)\n\nVariables (n : nat) (gT : finGroupType) (A : {set gT}).\n\nDefinition Ohm := <<[set x in A | x ^+ (pdiv #[x] ^ n) == 1]>>.\n\nDefinition Mho := <<[set x ^+ (pdiv #[x] ^ n) | x in A & (pdiv #[x]).-elt x]>>.\n\nCanonical Ohm_group : {group gT} := Eval hnf in [group of Ohm].\nCanonical Mho_group : {group gT} := Eval hnf in [group of Mho].\n\nLemma pdiv_p_elt (p : nat) (x : gT) : p.-elt x -> x != 1 -> pdiv #[x] = p.\nProof.\nmove=> p_x; rewrite /order -cycle_eq1.\nby case/(pgroup_pdiv p_x)=> p_pr _ [k ->]; rewrite pdiv_pfactor.\nQed.\n\nLemma OhmPredP (x : gT) :\n  reflect (exists2 p, prime p & x ^+ (p ^ n) = 1) (x ^+ (pdiv #[x] ^ n) == 1).\nProof.\nhave [-> | nt_x] := eqVneq x 1.\n  by rewrite expg1n eqxx; left; exists 2; rewrite ?expg1n.\napply: (iffP idP) => [/eqP | [p p_pr /eqP x_pn]].\n  by exists (pdiv #[x]); rewrite ?pdiv_prime ?order_gt1.\nrewrite (@pdiv_p_elt p) //; rewrite -order_dvdn in x_pn.\nby rewrite [p_elt _ _](pnat_dvd x_pn) // pnat_exp pnat_id.\nQed.\n\nLemma Mho_p_elt (p : nat) x : x \\in A -> p.-elt x -> x ^+ (p ^ n) \\in Mho.\nProof.\nmove=> Ax p_x; case: (eqVneq x 1) => [-> | ntx]; first by rewrite groupX.\nby apply: mem_gen; apply/imsetP; exists x; rewrite ?inE ?Ax (pdiv_p_elt p_x).\nQed.\n\nEnd Functors.\n\nArguments Ohm n%N {gT} A%g.\nArguments Ohm_group n%N {gT} A%g.\nArguments Mho n%N {gT} A%g.\nArguments Mho_group n%N {gT} A%g.\nArguments OhmPredP {n gT x}.\n\nNotation \"''Ohm_' n ( G )\" := (Ohm n G)\n  (at level 8, n at level 2, format \"''Ohm_' n ( G )\") : group_scope.\nNotation \"''Ohm_' n ( G )\" := (Ohm_group n G) : Group_scope.\n\nNotation \"''Mho^' n ( G )\" := (Mho n G)\n  (at level 8, n at level 2, format \"''Mho^' n ( G )\") : group_scope.\nNotation \"''Mho^' n ( G )\" := (Mho_group n G) : Group_scope.\n\nSection ExponentAbelem.\n\nVariable gT : finGroupType.\nImplicit Types (p n : nat) (pi : nat_pred) (x : gT) (A B C : {set gT}).\nImplicit Types E G H K P X Y : {group gT}.\n\nLemma LdivP A n x : reflect (x \\in A /\\ x ^+ n = 1) (x \\in 'Ldiv_n(A)).\nProof. by rewrite !inE; apply: (iffP andP) => [] [-> /eqP]. Qed.\n\nLemma dvdn_exponent x A : x \\in A -> #[x] %| exponent A.\nProof. by move=> Ax; rewrite (biglcmn_sup x). Qed.\n\nLemma expg_exponent x A : x \\in A -> x ^+ exponent A = 1.\nProof. by move=> Ax; apply/eqP; rewrite -order_dvdn dvdn_exponent. Qed.\n\nLemma exponentS A B : A \\subset B -> exponent A %| exponent B.\nProof.\nby move=> sAB; apply/dvdn_biglcmP=> x Ax; rewrite dvdn_exponent ?(subsetP sAB).\nQed.\n\nLemma exponentP A n :\n  reflect (forall x, x \\in A -> x ^+ n = 1) (exponent A %| n).\nProof.\napply: (iffP (dvdn_biglcmP _ _ _)) => eAn x Ax.\n  by apply/eqP; rewrite -order_dvdn eAn.\nby rewrite order_dvdn eAn.\nQed.\nArguments exponentP {A n}.\n\nLemma trivg_exponent G : (G :==: 1) = (exponent G %| 1).\nProof.\nrewrite -subG1.\nby apply/subsetP/exponentP=> trG x /trG; rewrite expg1 => /set1P.\nQed.\n\nLemma exponent1 : exponent [1 gT] = 1%N.\nProof. by apply/eqP; rewrite -dvdn1 -trivg_exponent eqxx. Qed.\n\nLemma exponent_dvdn G : exponent G %| #|G|.\nProof. by apply/dvdn_biglcmP=> x Gx; apply: order_dvdG. Qed.\n\nLemma exponent_gt0 G : 0 < exponent G.\nProof. exact: dvdn_gt0 (exponent_dvdn G). Qed.\nHint Resolve exponent_gt0 : core.\n\nLemma pnat_exponent pi G : pi.-nat (exponent G) = pi.-group G.\nProof.\ncongr (_ && _); first by rewrite cardG_gt0 exponent_gt0.\napply: eq_all_r => p; rewrite !mem_primes cardG_gt0 exponent_gt0 /=.\napply: andb_id2l => p_pr; apply/idP/idP=> pG.\n  exact: dvdn_trans pG (exponent_dvdn G).\nby case/Cauchy: pG => // x Gx <-; apply: dvdn_exponent.\nQed.\n\nLemma exponentJ A x : exponent (A :^ x) = exponent A.\nProof.\nrewrite /exponent (reindex_inj (conjg_inj x)).\nby apply: eq_big => [y | y _]; rewrite ?orderJ ?memJ_conjg.\nQed.\n\nLemma exponent_witness G : nilpotent G -> {x | x \\in G & exponent G = #[x]}.\nProof.\nmove=> nilG; have [//=| /= x Gx max_x] := @arg_maxP _ 1 (mem G) order.\nexists x => //; apply/eqP; rewrite eqn_dvd dvdn_exponent // andbT.\napply/dvdn_biglcmP=> y Gy; apply/dvdn_partP=> //= p.\nrewrite mem_primes => /andP[p_pr _]; have p_gt1: p > 1 := prime_gt1 p_pr.\nrewrite p_part pfactor_dvdn // -(leq_exp2l _ _ p_gt1) -!p_part.\nrewrite -(leq_pmul2r (part_gt0 p^' #[x])) partnC // -!order_constt.\nrewrite -orderM ?order_constt ?coprime_partC // ?max_x ?groupM ?groupX //.\ncase/dprodP: (nilpotent_pcoreC p nilG) => _ _ cGpGp' _.\nhave inGp := mem_normal_Hall (nilpotent_pcore_Hall _ nilG) (pcore_normal _ _).\nby red; rewrite -(centsP cGpGp') // inGp ?p_elt_constt ?groupX.\nQed.\n\nLemma exponent_cycle x : exponent <[x]> = #[x].\nProof. by apply/eqP; rewrite eqn_dvd exponent_dvdn dvdn_exponent ?cycle_id. Qed.\n\nLemma exponent_cyclic X : cyclic X -> exponent X = #|X|.\nProof. by case/cyclicP=> x ->; apply: exponent_cycle. Qed.\n\nLemma primes_exponent G : primes (exponent G) = primes (#|G|).\nProof.\napply/eq_primes => p; rewrite !mem_primes exponent_gt0 cardG_gt0 /=.\nby apply: andb_id2l => p_pr; apply: negb_inj; rewrite -!p'natE // pnat_exponent.\nQed.\n\nLemma pi_of_exponent G : \\pi(exponent G) = \\pi(G).\nProof. by rewrite /pi_of primes_exponent. Qed.\n\nLemma partn_exponentS pi H G :\n  H \\subset G -> #|G|`_pi %| #|H| -> (exponent H)`_pi = (exponent G)`_pi.\nProof.\nmove=> sHG Gpi_dvd_H; apply/eqP; rewrite eqn_dvd.\nrewrite partn_dvd ?exponentS ?exponent_gt0 //=; apply/dvdn_partP=> // p.\nrewrite pi_of_part ?exponent_gt0 // => /andP[_ /= pi_p].\nhave sppi: {subset (p : nat_pred) <= pi} by move=> q /eqnP->.\nhave [P sylP] := Sylow_exists p H; have sPH := pHall_sub sylP.\nhave{sylP} sylP: p.-Sylow(G) P.\n  rewrite pHallE (subset_trans sPH) //= (card_Hall sylP) eqn_dvd andbC.\n  by rewrite -{1}(partn_part _ sppi) !partn_dvd ?cardSg ?cardG_gt0.\nrewrite partn_part ?partn_biglcm //.\napply: (@big_ind _ (dvdn^~ _)) => [|m n|x Gx]; first exact: dvd1n.\n  by rewrite dvdn_lcm => ->.\nrewrite -order_constt; have p_y := p_elt_constt p x; set y := x.`_p in p_y *.\nhave sYG: <[y]> \\subset G by rewrite cycle_subG groupX.\nhave [z _ Pyz] := Sylow_Jsub sylP sYG p_y.\nrewrite (bigD1 (y ^ z))  ?(subsetP sPH) -?cycle_subG ?cycleJ //=.\nby rewrite orderJ part_pnat_id ?dvdn_lcml // (pi_pnat p_y).\nQed.\n\nLemma exponent_Hall pi G H : pi.-Hall(G) H -> exponent H = (exponent G)`_pi.\nProof.\nmove=> hallH; have [sHG piH _] := and3P hallH.\nrewrite -(partn_exponentS sHG) -?(card_Hall hallH) ?part_pnat_id //.\nby apply: pnat_dvd piH; apply: exponent_dvdn.\nQed.\n\nLemma exponent_Zgroup G : Zgroup G -> exponent G = #|G|.\nProof.\nmove/forall_inP=> ZgG; apply/eqP; rewrite eqn_dvd exponent_dvdn.\napply/(dvdn_partP _ (cardG_gt0 _)) => p _.\nhave [S sylS] := Sylow_exists p G; rewrite -(card_Hall sylS).\nhave /cyclicP[x defS]: cyclic S by rewrite ZgG ?(p_Sylow sylS).\nby rewrite defS dvdn_exponent // -cycle_subG -defS (pHall_sub sylS).\nQed.\n\nLemma cprod_exponent A B G :\n  A \\* B = G -> lcmn (exponent A) (exponent B) = (exponent G).\nProof.\ncase/cprodP=> [[K H -> ->{A B}] <- cKH].\napply/eqP; rewrite eqn_dvd dvdn_lcm !exponentS ?mulG_subl ?mulG_subr //=.\napply/exponentP=> _ /imset2P[x y Kx Hy ->].\nrewrite -[1]mulg1 expgMn; last by red; rewrite -(centsP cKH).\ncongr (_ * _); apply/eqP; rewrite -order_dvdn.\n  by rewrite (dvdn_trans (dvdn_exponent Kx)) ?dvdn_lcml.\nby rewrite (dvdn_trans (dvdn_exponent Hy)) ?dvdn_lcmr.\nQed.\n\nLemma dprod_exponent A B G :\n  A \\x B = G -> lcmn (exponent A) (exponent B) = (exponent G).\nProof.\ncase/dprodP=> [[K H -> ->{A B}] defG cKH _].\nby apply: cprod_exponent; rewrite cprodE.\nQed.\n\nLemma sub_LdivT A n : (A \\subset 'Ldiv_n()) = (exponent A %| n).\nProof. by apply/subsetP/exponentP=> eAn x /eAn; rewrite inE => /eqP. Qed.\n\nLemma LdivT_J n x : 'Ldiv_n() :^ x = 'Ldiv_n().\nProof.\napply/setP=> y; rewrite !inE mem_conjg inE -conjXg.\nby rewrite (canF_eq (conjgKV x)) conj1g.\nQed.\n\nLemma LdivJ n A x : 'Ldiv_n(A :^ x) = 'Ldiv_n(A) :^ x.\nProof. by rewrite conjIg LdivT_J. Qed.\n\nLemma sub_Ldiv A n : (A \\subset 'Ldiv_n(A)) = (exponent A %| n).\nProof. by rewrite subsetI subxx sub_LdivT. Qed.\n\nLemma group_Ldiv G n : abelian G -> group_set 'Ldiv_n(G).\nProof.\nmove=> cGG; apply/group_setP.\nsplit=> [|x y]; rewrite !inE ?group1 ?expg1n //=.\ncase/andP=> Gx /eqP xn /andP[Gy /eqP yn].\nby rewrite groupM //= expgMn ?xn ?yn ?mulg1 //; apply: (centsP cGG).\nQed.\n\nLemma abelian_exponent_gen A : abelian A -> exponent <<A>> = exponent A.\nProof.\nrewrite -abelian_gen; set n := exponent A; set G := <<A>> => cGG.\napply/eqP; rewrite eqn_dvd andbC exponentS ?subset_gen //= -sub_Ldiv.\nrewrite -(gen_set_id (group_Ldiv n cGG)) genS // subsetI subset_gen /=.\nby rewrite sub_LdivT.\nQed.\n\nLemma abelem_pgroup p A : p.-abelem A -> p.-group A.\nProof. by case/andP. Qed.\n\nLemma abelem_abelian p A : p.-abelem A -> abelian A.\nProof. by case/and3P. Qed.\n\nLemma abelem1 p : p.-abelem [1 gT].\nProof. by rewrite /abelem pgroup1 abelian1 exponent1 dvd1n. Qed.\n\nLemma abelemE p G : prime p -> p.-abelem G = abelian G && (exponent G %| p).\nProof.\nmove=> p_pr; rewrite /abelem -pnat_exponent andbA -!(andbC (_ %| _)).\nby case: (dvdn_pfactor _ 1 p_pr) => // [[k _ ->]]; rewrite pnat_exp pnat_id.\nQed.\n\nLemma abelemP p G :\n    prime p ->\n  reflect (abelian G /\\ forall x, x \\in G -> x ^+ p = 1) (p.-abelem G).\nProof.\nby move=> p_pr; rewrite abelemE //; apply: (iffP andP) => [] [-> /exponentP].\nQed.\n\nLemma abelem_order_p p G x : p.-abelem G -> x \\in G -> x != 1 -> #[x] = p.\nProof.\ncase/and3P=> pG _ eG Gx; rewrite -cycle_eq1 => ntX.\nhave{ntX} [p_pr p_x _] := pgroup_pdiv (mem_p_elt pG Gx) ntX.\nby apply/eqP; rewrite eqn_dvd p_x andbT order_dvdn (exponentP eG).\nQed.\n\nLemma cyclic_abelem_prime p X : p.-abelem X -> cyclic X -> X :!=: 1 -> #|X| = p.\nProof.\nmove=> abelX cycX; case/cyclicP: cycX => x -> in abelX *.\nby rewrite cycle_eq1; apply: abelem_order_p abelX (cycle_id x).\nQed.\n\nLemma cycle_abelem p x : p.-elt x || prime p -> p.-abelem <[x]> = (#[x] %| p).\nProof.\nmove=> p_xVpr; rewrite /abelem cycle_abelian /=.\napply/andP/idP=> [[_ xp1] | x_dvd_p].\n  by rewrite order_dvdn (exponentP xp1) ?cycle_id.\nsplit; last exact: dvdn_trans (exponent_dvdn _) x_dvd_p.\nby case/orP: p_xVpr => // /pnat_id; apply: pnat_dvd.\nQed.\n\nLemma exponent2_abelem G : exponent G %| 2 -> 2.-abelem G.\nProof.\nmove/exponentP=> expG; apply/abelemP=> //; split=> //.\napply/centsP=> x Gx y Gy; apply: (mulIg x); apply: (mulgI y).\nby rewrite -!mulgA !(mulgA y) -!(expgS _ 1) !expG ?mulg1 ?groupM.\nQed.\n\nLemma prime_abelem p G : prime p -> #|G| = p -> p.-abelem G.\nProof.\nmove=> p_pr oG; rewrite /abelem -oG exponent_dvdn.\nby rewrite /pgroup cyclic_abelian ?prime_cyclic ?oG ?pnat_id.\nQed.\n\nLemma abelem_cyclic p G : p.-abelem G -> cyclic G = (logn p #|G| <= 1).\nProof.\nmove=> abelG; have [pG _ expGp] := and3P abelG.\ncase: (eqsVneq G 1) => [-> | ntG]; first by rewrite cyclic1 cards1 logn1.\nhave [p_pr _ [e oG]] := pgroup_pdiv pG ntG; apply/idP/idP.\n  case/cyclicP=> x defG; rewrite -(pfactorK 1 p_pr) dvdn_leq_log ?prime_gt0 //.\n  by rewrite defG order_dvdn (exponentP expGp) // defG cycle_id.\nby rewrite oG pfactorK // ltnS leqn0 => e0; rewrite prime_cyclic // oG (eqP e0).\nQed.\n\nLemma abelemS p H G : H \\subset G -> p.-abelem G -> p.-abelem H.\nProof.\nmove=> sHG /and3P[cGG pG Gp1]; rewrite /abelem.\nby rewrite (pgroupS sHG) // (abelianS sHG) // (dvdn_trans (exponentS sHG)).\nQed.\n\nLemma abelemJ p G x : p.-abelem (G :^ x) = p.-abelem G.\nProof. by rewrite /abelem pgroupJ abelianJ exponentJ. Qed.\n\nLemma cprod_abelem p A B G :\n  A \\* B = G -> p.-abelem G = p.-abelem A && p.-abelem B.\nProof.\ncase/cprodP=> [[H K -> ->{A B}] defG cHK].\napply/idP/andP=> [abelG | []].\n  by rewrite !(abelemS _ abelG) // -defG (mulG_subl, mulG_subr).\ncase/and3P=> pH cHH expHp; case/and3P=> pK cKK expKp.\nrewrite -defG /abelem pgroupM pH pK abelianM cHH cKK cHK /=.\napply/exponentP=> _ /imset2P[x y Hx Ky ->].\nrewrite expgMn; last by red; rewrite -(centsP cHK).\nby rewrite (exponentP expHp) // (exponentP expKp) // mul1g.\nQed.\n\nLemma dprod_abelem p A B G :\n  A \\x B = G -> p.-abelem G = p.-abelem A && p.-abelem B.\nProof.\nmove=> defG; case/dprodP: (defG) => _ _ _ tiHK.\nby apply: cprod_abelem; rewrite -dprodEcp.\nQed.\n\nLemma is_abelem_pgroup p G : p.-group G -> is_abelem G = p.-abelem G.\nProof.\nrewrite /is_abelem => pG.\ncase: (eqsVneq G 1) => [-> | ntG]; first by rewrite !abelem1.\nby have [p_pr _ [k ->]] := pgroup_pdiv pG ntG; rewrite pdiv_pfactor.\nQed.\n\nLemma is_abelemP G : reflect (exists2 p, prime p & p.-abelem G) (is_abelem G).\nProof.\napply: (iffP idP) => [abelG | [p p_pr abelG]].\n  case: (eqsVneq G 1) => [-> | ntG]; first by exists 2; rewrite ?abelem1.\n  by exists (pdiv #|G|); rewrite ?pdiv_prime // ltnNge -trivg_card_le1.\nby rewrite (is_abelem_pgroup (abelem_pgroup abelG)).\nQed.\n\nLemma pElemP p A E : reflect (E \\subset A /\\ p.-abelem E) (E \\in 'E_p(A)).\nProof. by rewrite inE; apply: andP. Qed.\nArguments pElemP {p A E}.\n\nLemma pElemS p A B : A \\subset B -> 'E_p(A) \\subset 'E_p(B).\nProof.\nby move=> sAB; apply/subsetP=> E; rewrite !inE => /andP[/subset_trans->].\nQed.\n\nLemma pElemI p A B : 'E_p(A :&: B) = 'E_p(A) :&: subgroups B.\nProof. by apply/setP=> E; rewrite !inE subsetI andbAC. Qed.\n\nLemma pElemJ x p A E : ((E :^ x)%G \\in 'E_p(A :^ x)) = (E \\in 'E_p(A)).\nProof. by rewrite !inE conjSg abelemJ. Qed.\n\nLemma pnElemP p n A E :\n  reflect [/\\ E \\subset A, p.-abelem E & logn p #|E| = n] (E \\in 'E_p^n(A)).\nProof. by rewrite !inE -andbA; apply: (iffP and3P) => [] [-> -> /eqP]. Qed.\nArguments pnElemP {p n A E}.\n\nLemma pnElemPcard p n A E :\n  E \\in 'E_p^n(A) -> [/\\ E \\subset A, p.-abelem E & #|E| = p ^ n]%N.\nProof.\nby case/pnElemP=> -> abelE <-; rewrite -card_pgroup // abelem_pgroup.\nQed.\n\nLemma card_pnElem p n A E : E \\in 'E_p^n(A) -> #|E| = (p ^ n)%N.\nProof. by case/pnElemPcard. Qed.\n\nLemma pnElem0 p G : 'E_p^0(G) = [set 1%G].\nProof.\napply/setP=> E; rewrite !inE -andbA; apply/and3P/idP=> [[_ pE] | /eqP->].\n  apply: contraLR; case/(pgroup_pdiv (abelem_pgroup pE)) => p_pr _ [k ->].\n  by rewrite pfactorK.\nby rewrite sub1G abelem1 cards1 logn1.\nQed.\n\nLemma pnElem_prime p n A E : E \\in 'E_p^n.+1(A) -> prime p.\nProof. by case/pnElemP=> _ _; rewrite lognE; case: prime. Qed.\n\nLemma pnElemE p n A :\n  prime p -> 'E_p^n(A) = [set E in 'E_p(A) | #|E| == (p ^ n)%N].\nProof.\nmove/pfactorK=> pnK; apply/setP=> E; rewrite 3!inE.\ncase: (@andP (E \\subset A)) => //= [[_]] /andP[/p_natP[k ->] _].\nby rewrite pnK (can_eq pnK).\nQed.\n\nLemma pnElemS p n A B : A \\subset B -> 'E_p^n(A) \\subset 'E_p^n(B).\nProof.\nmove=> sAB; apply/subsetP=> E.\nby rewrite !inE -!andbA => /andP[/subset_trans->].\nQed.\n\nLemma pnElemI p n A B : 'E_p^n(A :&: B) = 'E_p^n(A) :&: subgroups B.\nProof. by apply/setP=> E; rewrite !inE subsetI -!andbA; do !bool_congr. Qed.\n\nLemma pnElemJ x p n A E : ((E :^ x)%G \\in 'E_p^n(A :^ x)) = (E \\in 'E_p^n(A)).\nProof. by rewrite inE pElemJ cardJg !inE. Qed.\n\nLemma abelem_pnElem p n G :\n  p.-abelem G -> n <= logn p #|G| -> exists E, E \\in 'E_p^n(G).\nProof.\ncase: n => [|n] abelG lt_nG; first by exists 1%G; rewrite pnElem0 set11.\nhave p_pr: prime p by move: lt_nG; rewrite lognE; case: prime.\ncase/(normal_pgroup (abelem_pgroup abelG)): lt_nG => // E [sEG _ oE].\nby exists E; rewrite pnElemE // !inE oE sEG (abelemS sEG) /=.\nQed.\n\nLemma card_p1Elem p A X : X \\in 'E_p^1(A) -> #|X| = p.\nProof. exact: card_pnElem. Qed.\n\nLemma p1ElemE p A : prime p -> 'E_p^1(A) = [set X in subgroups A | #|X| == p].\nProof.\nmove=> p_pr; apply/setP=> X; rewrite pnElemE // !inE -andbA; congr (_ && _).\nby apply: andb_idl => /eqP oX; rewrite prime_abelem ?oX.\nQed.\n\nLemma TIp1ElemP p A X Y :\n  X \\in 'E_p^1(A) -> Y \\in 'E_p^1(A) -> reflect (X :&: Y = 1) (X :!=: Y).\nProof.\nmove=> EpX EpY; have p_pr := pnElem_prime EpX.\nhave [oX oY] := (card_p1Elem EpX, card_p1Elem EpY).\nhave [<- |] := altP eqP.\n  by right=> X1; rewrite -oX -(setIid X) X1 cards1 in p_pr.\nby rewrite eqEcard oX oY leqnn andbT; left; rewrite prime_TIg ?oX.\nQed.\n\nLemma card_p1Elem_pnElem p n A E :\n  E \\in 'E_p^n(A) -> #|'E_p^1(E)| = (\\sum_(i < n) p ^ i)%N.\nProof.\ncase/pnElemP=> _ {A} abelE dimE; have [pE cEE _] := and3P abelE.\nhave [E1 | ntE] := eqsVneq E 1.\n  rewrite -dimE E1 cards1 logn1 big_ord0 eq_card0 // => X.\n  by rewrite !inE subG1 trivg_card1; case: eqP => // ->; rewrite logn1 andbF.\nhave [p_pr _ _] := pgroup_pdiv pE ntE; have p_gt1 := prime_gt1 p_pr.\napply/eqP; rewrite -(@eqn_pmul2l (p - 1)) ?subn_gt0 // subn1 -predn_exp.\nhave groupD1_inj: injective (fun X => (gval X)^#).\n  apply: can_inj (@generated_group _) _ => X.\n  by apply: val_inj; rewrite /= genD1 ?group1 ?genGid.\nrewrite -dimE -card_pgroup // (cardsD1 1 E) group1 /= mulnC.\nrewrite -(card_imset _ groupD1_inj) eq_sym.\napply/eqP; apply: card_uniform_partition => [X'|].\n  case/imsetP=> X; rewrite pnElemE // expn1 => /setIdP[_ /eqP <-] ->.\n  by rewrite (cardsD1 1 X) group1.\napply/and3P; split; last 1 first.\n- apply/imsetP=> [[X /card_p1Elem oX X'0]].\n  by rewrite -oX (cardsD1 1) -X'0 group1 cards0 in p_pr.\n- rewrite eqEsubset; apply/andP; split.\n    by apply/bigcupsP=> _ /imsetP[X /pnElemP[sXE _ _] ->]; apply: setSD.\n  apply/subsetP=> x /setD1P[ntx Ex].\n  apply/bigcupP; exists <[x]>^#; last by rewrite !inE ntx cycle_id.\n  apply/imsetP; exists <[x]>%G; rewrite ?p1ElemE // !inE cycle_subG Ex /=.\n  by rewrite -orderE (abelem_order_p abelE).\napply/trivIsetP=> _ _ /imsetP[X EpX ->] /imsetP[Y EpY ->]; apply/implyP.\nrewrite (inj_eq groupD1_inj) -setI_eq0 -setDIl setD_eq0 subG1.\nby rewrite (sameP eqP (TIp1ElemP EpX EpY)) implybb.\nQed.\n\nLemma card_p1Elem_p2Elem p A E : E \\in 'E_p^2(A) -> #|'E_p^1(E)| = p.+1.\nProof. by move/card_p1Elem_pnElem->; rewrite big_ord_recl big_ord1. Qed.\n\nLemma p2Elem_dprodP p A E X Y :\n    E \\in 'E_p^2(A) -> X \\in 'E_p^1(E) -> Y \\in 'E_p^1(E) ->\n  reflect (X \\x Y = E) (X :!=: Y).\nProof.\nmove=> Ep2E EpX EpY; have [_ abelE oE] := pnElemPcard Ep2E.\napply: (iffP (TIp1ElemP EpX EpY)) => [tiXY|]; last by case/dprodP.\nhave [[sXE _ oX] [sYE _ oY]] := (pnElemPcard EpX, pnElemPcard EpY).\nrewrite dprodE ?(sub_abelian_cent2 (abelem_abelian abelE)) //.\nby apply/eqP; rewrite eqEcard mul_subG //= TI_cardMg // oX oY oE.\nQed.\n\nLemma nElemP n G E : reflect (exists p, E \\in 'E_p^n(G)) (E \\in 'E^n(G)).\nProof.\nrewrite ['E^n(G)]big_mkord.\napply: (iffP bigcupP) => [[[p /= _] _] | [p]]; first by exists p.\ncase: n => [|n EpnE]; first by rewrite pnElem0; exists ord0; rewrite ?pnElem0.\nsuffices lepG: p < #|G|.+1  by exists (Ordinal lepG).\nhave:= EpnE; rewrite pnElemE ?(pnElem_prime EpnE) // !inE -andbA ltnS.\ncase/and3P=> sEG _ oE; rewrite dvdn_leq // (dvdn_trans _ (cardSg sEG)) //.\nby rewrite (eqP oE) dvdn_exp.\nQed.\nArguments nElemP {n G E}.\n\nLemma nElem0 G : 'E^0(G) = [set 1%G].\nProof.\napply/setP=> E; apply/nElemP/idP=> [[p] |]; first by rewrite pnElem0.\nby exists 2; rewrite pnElem0.\nQed.\n\nLemma nElem1P G E :\n  reflect (E \\subset G /\\ exists2 p, prime p & #|E| = p) (E \\in 'E^1(G)).\nProof.\napply: (iffP nElemP) => [[p pE] | [sEG [p p_pr oE]]].\n  have p_pr := pnElem_prime pE; rewrite pnElemE // !inE -andbA in pE.\n  by case/and3P: pE => -> _ /eqP; split; last exists p.\nexists p; rewrite pnElemE // !inE sEG oE eqxx abelemE // -oE exponent_dvdn.\nby rewrite cyclic_abelian // prime_cyclic // oE.\nQed.\n\nLemma nElemS n G H : G \\subset H -> 'E^n(G) \\subset 'E^n(H).\nProof.\nmove=> sGH; apply/subsetP=> E /nElemP[p EpnG_E].\nby apply/nElemP; exists p; rewrite // (subsetP (pnElemS _ _ sGH)).\nQed.\n\nLemma nElemI n G H : 'E^n(G :&: H) = 'E^n(G) :&: subgroups H.\nProof.\napply/setP=> E; apply/nElemP/setIP=> [[p] | []].\n  by rewrite pnElemI; case/setIP; split=> //; apply/nElemP; exists p.\nby case/nElemP=> p EpnG_E sHE; exists p; rewrite pnElemI inE EpnG_E.\nQed.\n\nLemma def_pnElem p n G : 'E_p^n(G) = 'E_p(G) :&: 'E^n(G).\nProof.\napply/setP=> E; rewrite inE in_setI; apply: andb_id2l => /pElemP[sEG abelE].\napply/idP/nElemP=> [|[q]]; first by exists p; rewrite !inE sEG abelE.\nrewrite !inE -2!andbA => /and4P[_ /pgroupP qE _].\ncase: (eqVneq E 1%G) => [-> | ]; first by rewrite cards1 !logn1.\ncase/(pgroup_pdiv (abelem_pgroup abelE)) => p_pr pE _.\nby rewrite (eqnP (qE p p_pr pE)).\nQed.\n\nLemma pmaxElemP p A E :\n  reflect (E \\in 'E_p(A) /\\ forall H, H \\in 'E_p(A) -> E \\subset H -> H :=: E)\n          (E \\in 'E*_p(A)).\nProof. by rewrite [E \\in 'E*_p(A)]inE; apply: (iffP maxgroupP). Qed.\n\nLemma pmaxElem_exists p A D :\n  D \\in 'E_p(A) -> {E | E \\in 'E*_p(A) & D \\subset E}.\nProof.\nmove=> EpD; have [E maxE sDE] := maxgroup_exists (EpD : mem 'E_p(A) D).\nby exists E; rewrite // inE.\nQed.\n\nLemma pmaxElem_LdivP p G E :\n  prime p -> reflect ('Ldiv_p('C_G(E)) = E) (E \\in 'E*_p(G)).\nProof.\nmove=> p_pr; apply: (iffP (pmaxElemP p G E)) => [[] | defE].\n  case/pElemP=> sEG abelE maxE; have [_ cEE eE] := and3P abelE.\n  apply/setP=> x; rewrite !inE -andbA; apply/and3P/idP=> [[Gx cEx xp] | Ex].\n    rewrite -(maxE (<[x]> <*> E)%G) ?joing_subr //.\n      by rewrite -cycle_subG joing_subl.\n    rewrite inE join_subG cycle_subG Gx sEG /=.\n    rewrite (cprod_abelem _ (cprodEY _)); last by rewrite centsC cycle_subG.\n    by rewrite cycle_abelem ?p_pr ?orbT // order_dvdn xp.\n  by rewrite (subsetP sEG) // (subsetP cEE) // (exponentP eE).\nsplit=> [|H]; last first.\n  case/pElemP=> sHG /abelemP[// | cHH Hp1] sEH.\n  apply/eqP; rewrite eqEsubset sEH andbC /= -defE; apply/subsetP=> x Hx.\n  by rewrite 3!inE (subsetP sHG) // Hp1 ?(subsetP (centsS _ cHH)) /=.\napply/pElemP; split; first by rewrite -defE -setIA subsetIl.\napply/abelemP=> //; rewrite /abelian -{1 3}defE setIAC subsetIr.\nby split=> //; apply/exponentP; rewrite -sub_LdivT setIAC subsetIr.\nQed.\n\nLemma pmaxElemS p A B :\n  A \\subset B -> 'E*_p(B) :&: subgroups A \\subset 'E*_p(A).\nProof.\nmove=> sAB; apply/subsetP=> E; rewrite !inE.\ncase/andP=> /maxgroupP[/pElemP[_ abelE] maxE] sEA.\napply/maxgroupP; rewrite inE sEA; split=> // D EpD.\nby apply: maxE; apply: subsetP EpD; apply: pElemS.\nQed.\n\nLemma pmaxElemJ p A E x : ((E :^ x)%G \\in 'E*_p(A :^ x)) = (E \\in 'E*_p(A)).\nProof.\napply/pmaxElemP/pmaxElemP=> [] [EpE maxE].\n  rewrite pElemJ in EpE; split=> //= H EpH sEH; apply: (act_inj 'Js x).\n  by apply: maxE; rewrite ?conjSg ?pElemJ.\nrewrite pElemJ; split=> // H; rewrite -(actKV 'JG x H) pElemJ conjSg => EpHx'.\nby move/maxE=> /= ->.\nQed.\n\nLemma grank_min B : 'm(<<B>>) <= #|B|.\nProof.\nby rewrite /gen_rank; case: arg_minP => [|_ _ -> //]; rewrite genGid.\nQed.\n\nLemma grank_witness G : {B | <<B>> = G & #|B| = 'm(G)}.\nProof.\nrewrite /gen_rank; case: arg_minP => [|B defG _]; first by rewrite genGid.\nby exists B; first apply/eqP.\nQed.\n\nLemma p_rank_witness p G : {E | E \\in 'E_p^('r_p(G))(G)}.\nProof.\nhave [E EG_E mE]: {E | E \\in 'E_p(G) & 'r_p(G) = logn p #|E| }.\n  by apply: eq_bigmax_cond; rewrite (cardD1 1%G) inE sub1G abelem1.\nby exists E; rewrite inE EG_E -mE /=.\nQed.\n\nLemma p_rank_geP p n G : reflect (exists E, E \\in 'E_p^n(G)) (n <= 'r_p(G)).\nProof.\napply: (iffP idP) => [|[E]]; last first.\n  by rewrite inE => /andP[Ep_E /eqP <-]; rewrite (bigmax_sup E).\nhave [D /pnElemP[sDG abelD <-]] := p_rank_witness p G.\nby case/abelem_pnElem=> // E; exists E; apply: (subsetP (pnElemS _ _ sDG)).\nQed.\n\nLemma p_rank_gt0 p H : ('r_p(H) > 0) = (p \\in \\pi(H)).\nProof.\nrewrite mem_primes cardG_gt0 /=; apply/p_rank_geP/andP=> [[E] | [p_pr]].\n  case/pnElemP=> sEG _; rewrite lognE; case: and3P => // [[-> _ pE] _].\n  by rewrite (dvdn_trans _ (cardSg sEG)).\ncase/Cauchy=> // x Hx ox; exists <[x]>%G; rewrite 2!inE [#|_|]ox cycle_subG.\nby rewrite Hx (pfactorK 1) ?abelemE // cycle_abelian -ox exponent_dvdn.\nQed.\n\nLemma p_rank1 p : 'r_p([1 gT]) = 0.\nProof. by apply/eqP; rewrite eqn0Ngt p_rank_gt0 /= cards1. Qed.\n\nLemma logn_le_p_rank p A E : E \\in 'E_p(A) -> logn p #|E| <= 'r_p(A).\nProof. by move=> EpA_E; rewrite (bigmax_sup E). Qed.\n\nLemma p_rank_le_logn p G : 'r_p(G) <= logn p #|G|.\nProof.\nhave [E EpE] := p_rank_witness p G.\nby have [sEG _ <-] := pnElemP EpE; apply: lognSg.\nQed.\n\nLemma p_rank_abelem p G : p.-abelem G -> 'r_p(G) = logn p #|G|.\nProof.\nmove=> abelG; apply/eqP; rewrite eqn_leq andbC (bigmax_sup G) //.\n  by apply/bigmax_leqP=> E; rewrite inE => /andP[/lognSg->].\nby rewrite inE subxx.\nQed.\n\nLemma p_rankS p A B : A \\subset B -> 'r_p(A) <= 'r_p(B).\nProof.\nmove=> sAB; apply/bigmax_leqP=> E /(subsetP (pElemS p sAB)) EpB_E.\nby rewrite (bigmax_sup E).\nQed.\n\nLemma p_rankElem_max p A : 'E_p^('r_p(A))(A) \\subset 'E*_p(A).\nProof.\napply/subsetP=> E /setIdP[EpE dimE].\napply/pmaxElemP; split=> // F EpF sEF; apply/eqP.\nhave pF: p.-group F by case/pElemP: EpF => _ /and3P[].\nhave pE: p.-group E by case/pElemP: EpE => _ /and3P[].\nrewrite eq_sym eqEcard sEF dvdn_leq // (card_pgroup pE) (card_pgroup pF).\nby rewrite (eqP dimE) dvdn_exp2l // logn_le_p_rank.\nQed.\n\nLemma p_rankJ p A x : 'r_p(A :^ x) = 'r_p(A).\nProof.\nrewrite /p_rank (reindex_inj (act_inj 'JG x)).\nby apply: eq_big => [E | E _]; rewrite ?cardJg ?pElemJ.\nQed.\n\nLemma p_rank_Sylow p G H : p.-Sylow(G) H -> 'r_p(H) = 'r_p(G).\nProof.\nmove=> sylH; apply/eqP; rewrite eqn_leq (p_rankS _ (pHall_sub sylH)) /=.\napply/bigmax_leqP=> E; rewrite inE => /andP[sEG abelE].\nhave [P sylP sEP] := Sylow_superset sEG (abelem_pgroup abelE).\nhave [x _ ->] := Sylow_trans sylP sylH.\nby rewrite p_rankJ -(p_rank_abelem abelE) (p_rankS _ sEP).\nQed.\n\nLemma p_rank_Hall pi p G H : pi.-Hall(G) H -> p \\in pi -> 'r_p(H) = 'r_p(G).\nProof.\nmove=> hallH pi_p; have [P sylP] := Sylow_exists p H.\nby rewrite -(p_rank_Sylow sylP) (p_rank_Sylow (subHall_Sylow hallH pi_p sylP)).\nQed.\n\nLemma p_rank_pmaxElem_exists p r G :\n  'r_p(G) >= r -> exists2 E, E \\in 'E*_p(G) & 'r_p(E) >= r.\nProof.\ncase/p_rank_geP=> D /setIdP[EpD /eqP <- {r}].\nhave [E EpE sDE] := pmaxElem_exists EpD; exists E => //.\ncase/pmaxElemP: EpE => /setIdP[_ abelE] _.\nby rewrite (p_rank_abelem abelE) lognSg.\nQed.\n\nLemma rank1 : 'r([1 gT]) = 0.\nProof. by rewrite ['r(1)]big1_seq // => p _; rewrite p_rank1. Qed.\n\nLemma p_rank_le_rank p G : 'r_p(G) <= 'r(G).\nProof.\ncase: (posnP 'r_p(G)) => [-> //|]; rewrite p_rank_gt0 mem_primes.\ncase/and3P=> p_pr _ pG; have lepg: p < #|G|.+1 by rewrite ltnS dvdn_leq.\nby rewrite ['r(G)]big_mkord (bigmax_sup (Ordinal lepg)).\nQed.\n\nLemma rank_gt0 G : ('r(G) > 0) = (G :!=: 1).\nProof.\ncase: (eqsVneq G 1) => [-> |]; first by rewrite rank1 eqxx.\ncase: (trivgVpdiv G) => [-> | [p p_pr]]; first by case/eqP.\ncase/Cauchy=> // x Gx oxp ->; apply: leq_trans (p_rank_le_rank p G).\nhave EpGx: <[x]>%G \\in 'E_p(G).\n  by rewrite inE cycle_subG Gx abelemE // cycle_abelian -oxp exponent_dvdn.\nby apply: leq_trans (logn_le_p_rank EpGx); rewrite -orderE oxp logn_prime ?eqxx.\nQed.\n\nLemma rank_witness G : {p | prime p & 'r(G) = 'r_p(G)}.\nProof.\nhave [p _ defmG]: {p : 'I_(#|G|.+1) | true & 'r(G) = 'r_p(G)}.\n  by rewrite ['r(G)]big_mkord; apply: eq_bigmax_cond; rewrite card_ord.\ncase: (eqsVneq G 1) => [-> | ]; first by exists 2; rewrite // rank1 p_rank1.\nby rewrite -rank_gt0 defmG p_rank_gt0 mem_primes; case/andP; exists p.\nQed.\n\nLemma rank_pgroup p G : p.-group G -> 'r(G) = 'r_p(G).\nProof.\nmove=> pG; apply/eqP; rewrite eqn_leq p_rank_le_rank andbT.\nrewrite ['r(G)]big_mkord; apply/bigmax_leqP=> [[q /= _] _].\ncase: (posnP 'r_q(G)) => [-> // |]; rewrite p_rank_gt0 mem_primes.\nby case/and3P=> q_pr _ qG; rewrite (eqnP (pgroupP pG q q_pr qG)).\nQed.\n\nLemma rank_Sylow p G P : p.-Sylow(G) P -> 'r(P) = 'r_p(G).\nProof.\nmove=> sylP; have pP := pHall_pgroup sylP.\nby rewrite -(p_rank_Sylow sylP) -(rank_pgroup pP).\nQed.\n\nLemma rank_abelem p G : p.-abelem G -> 'r(G) = logn p #|G|.\nProof.\nby move=> abelG; rewrite (rank_pgroup (abelem_pgroup abelG)) p_rank_abelem.\nQed.\n\nLemma nt_pnElem p n E A : E \\in 'E_p^n(A) -> n > 0 -> E :!=: 1.\nProof. by case/pnElemP=> _ /rank_abelem <- <-; rewrite rank_gt0. Qed.\n\nLemma rankJ A x : 'r(A :^ x) = 'r(A).\nProof. by rewrite /rank cardJg; apply: eq_bigr => p _; rewrite p_rankJ. Qed.\n\nLemma rankS A B : A \\subset B -> 'r(A) <= 'r(B).\nProof.\nmove=> sAB; rewrite /rank !big_mkord; apply/bigmax_leqP=> p _.\nhave leAB: #|A| < #|B|.+1 by rewrite ltnS subset_leq_card.\nby rewrite (bigmax_sup (widen_ord leAB p)) // p_rankS.\nQed.\n\nLemma rank_geP n G : reflect (exists E, E \\in 'E^n(G)) (n <= 'r(G)).\nProof.\napply: (iffP idP) => [|[E]].\n  have [p _ ->] := rank_witness G; case/p_rank_geP=> E.\n  by rewrite def_pnElem; case/setIP; exists E.\ncase/nElemP=> p; rewrite inE => /andP[EpG_E /eqP <-].\nby rewrite (leq_trans (logn_le_p_rank EpG_E)) ?p_rank_le_rank.\nQed.\n\nEnd ExponentAbelem.\n\nArguments LdivP {gT A n x}.\nArguments exponentP {gT A n}.\nArguments abelemP {gT p G}.\nArguments is_abelemP {gT G}.\nArguments pElemP {gT p A E}.\nArguments pnElemP {gT p n A E}.\nArguments nElemP {gT n G E}.\nArguments nElem1P {gT G E}.\nArguments pmaxElemP {gT p A E}.\nArguments pmaxElem_LdivP {gT p G E}.\nArguments p_rank_geP {gT p n G}.\nArguments rank_geP {gT n G}.\n\nSection MorphAbelem.\n\nVariables (aT rT : finGroupType) (D : {group aT}) (f : {morphism D >-> rT}).\nImplicit Types (G H E : {group aT}) (A B : {set aT}).\n\nLemma exponent_morphim G : exponent (f @* G) %| exponent G.\nProof.\napply/exponentP=> _ /morphimP[x Dx Gx ->].\nby rewrite -morphX // expg_exponent // morph1.\nQed.\n\nLemma morphim_LdivT n : f @* 'Ldiv_n() \\subset 'Ldiv_n().\nProof.\napply/subsetP=> _ /morphimP[x Dx xn ->]; rewrite inE in xn.\nby rewrite inE -morphX // (eqP xn) morph1.\nQed.\n\nLemma morphim_Ldiv n A : f @* 'Ldiv_n(A) \\subset 'Ldiv_n(f @* A).\nProof.\nby apply: subset_trans (morphimI f A _) (setIS _ _); apply: morphim_LdivT.\nQed.\n\nLemma morphim_abelem p G : p.-abelem G -> p.-abelem (f @* G).\nProof.\ncase: (eqsVneq G 1) => [-> | ntG] abelG; first by rewrite morphim1 abelem1.\nhave [p_pr _ _] := pgroup_pdiv (abelem_pgroup abelG) ntG.\ncase/abelemP: abelG => // abG elemG; apply/abelemP; rewrite ?morphim_abelian //.\nby split=> // _ /morphimP[x Dx Gx ->]; rewrite -morphX // elemG ?morph1.\nQed.\n\nLemma morphim_pElem p G E : E \\in 'E_p(G) -> (f @* E)%G \\in 'E_p(f @* G).\nProof.\nby rewrite !inE => /andP[sEG abelE]; rewrite morphimS // morphim_abelem.\nQed.\n\nLemma morphim_pnElem p n G E :\n  E \\in 'E_p^n(G) -> {m | m <= n & (f @* E)%G \\in 'E_p^m(f @* G)}.\nProof.\nrewrite inE => /andP[EpE /eqP <-].\nby exists (logn p #|f @* E|); rewrite ?logn_morphim // inE morphim_pElem /=.\nQed.\n\nLemma morphim_grank G : G \\subset D -> 'm(f @* G) <= 'm(G).\nProof.\nhave [B defG <-] := grank_witness G; rewrite -defG gen_subG => sBD.\nby rewrite morphim_gen ?morphimEsub ?(leq_trans (grank_min _)) ?leq_imset_card.\nQed.\n\n(* There are no general morphism relations for the p-rank. We later prove     *)\n(* some relations for the p-rank of a quotient in the QuotientAbelem section. *)\n\nEnd MorphAbelem.\n\nSection InjmAbelem.\n\nVariables (aT rT : finGroupType) (D G : {group aT}) (f : {morphism D >-> rT}).\nHypotheses (injf : 'injm f) (sGD : G \\subset D).\nLet defG : invm injf @* (f @* G) = G := morphim_invm injf sGD.\n\nLemma exponent_injm : exponent (f @* G) = exponent G.\nProof. by apply/eqP; rewrite eqn_dvd -{3}defG !exponent_morphim. Qed.\n\nLemma injm_Ldiv n A : f @* 'Ldiv_n(A) = 'Ldiv_n(f @* A).\nProof.\napply/eqP; rewrite eqEsubset morphim_Ldiv.\nrewrite -[f @* 'Ldiv_n(A)](morphpre_invm injf).\nrewrite -sub_morphim_pre; last by rewrite subIset ?morphim_sub.\nrewrite injmI ?injm_invm // setISS ?morphim_LdivT //.\nby rewrite sub_morphim_pre ?morphim_sub // morphpre_invm.\nQed.\n\nLemma injm_abelem p : p.-abelem (f @* G) = p.-abelem G.\nProof. by apply/idP/idP; first rewrite -{2}defG; apply: morphim_abelem. Qed.\n\nLemma injm_pElem p (E : {group aT}) :\n  E \\subset D -> ((f @* E)%G \\in 'E_p(f @* G)) = (E \\in 'E_p(G)).\nProof.\nmove=> sED; apply/idP/idP=> EpE; last exact: morphim_pElem.\nby rewrite -defG -(group_inj (morphim_invm injf sED)) morphim_pElem.\nQed.\n\nLemma injm_pnElem p n (E : {group aT}) :\n  E \\subset D -> ((f @* E)%G \\in 'E_p^n(f @* G)) = (E \\in 'E_p^n(G)).\nProof. by move=> sED; rewrite inE injm_pElem // card_injm ?inE. Qed.\n\nLemma injm_nElem n (E : {group aT}) :\n  E \\subset D -> ((f @* E)%G \\in 'E^n(f @* G)) = (E \\in 'E^n(G)).\nProof.\nmove=> sED; apply/nElemP/nElemP=> [] [p EpE];\n by exists p; rewrite injm_pnElem in EpE *.\nQed.\n\nLemma injm_pmaxElem p (E : {group aT}) :\n  E \\subset D -> ((f @* E)%G \\in 'E*_p(f @* G)) = (E \\in 'E*_p(G)).\nProof.\nmove=> sED; have defE := morphim_invm injf sED.\napply/pmaxElemP/pmaxElemP=> [] [EpE maxE].\n  split=> [|H EpH sEH]; first by rewrite injm_pElem in EpE.\n  have sHD: H \\subset D by apply: subset_trans (sGD); case/pElemP: EpH.\n  by rewrite -(morphim_invm injf sHD) [f @* H]maxE ?morphimS ?injm_pElem.\nrewrite injm_pElem //; split=> // fH Ep_fH sfEH; have [sfHG _] := pElemP Ep_fH.\nhave sfHD : fH \\subset f @* D by rewrite (subset_trans sfHG) ?morphimS.\nrewrite -(morphpreK sfHD); congr (f @* _).\nrewrite [_ @*^-1 fH]maxE -?sub_morphim_pre //.\nby rewrite -injm_pElem ?subsetIl // (group_inj (morphpreK sfHD)).\nQed.\n\nLemma injm_grank : 'm(f @* G) = 'm(G).\nProof. by apply/eqP; rewrite eqn_leq -{3}defG !morphim_grank ?morphimS. Qed.\n\nLemma injm_p_rank p : 'r_p(f @* G) = 'r_p(G).\nProof.\napply/eqP; rewrite eqn_leq; apply/andP; split.\n  have [fE] := p_rank_witness p (f @* G); move: 'r_p(_) => n Ep_fE.\n  apply/p_rank_geP; exists (f @*^-1 fE)%G.\n  rewrite -injm_pnElem ?subsetIl ?(group_inj (morphpreK _)) //.\n  by case/pnElemP: Ep_fE => sfEG _ _; rewrite (subset_trans sfEG) ?morphimS.\nhave [E] := p_rank_witness p G; move: 'r_p(_) => n EpE.\napply/p_rank_geP; exists (f @* E)%G; rewrite injm_pnElem //.\nby case/pnElemP: EpE => sEG _ _; rewrite (subset_trans sEG).\nQed.\n\nLemma injm_rank : 'r(f @* G) = 'r(G).\nProof.\napply/eqP; rewrite eqn_leq; apply/andP; split.\n  by have [p _ ->] := rank_witness (f @* G); rewrite injm_p_rank p_rank_le_rank.\nby have [p _ ->] := rank_witness G; rewrite -injm_p_rank p_rank_le_rank.\nQed.\n\nEnd InjmAbelem.\n\nSection IsogAbelem.\n\nVariables (aT rT : finGroupType) (G : {group aT}) (H : {group rT}).\nHypothesis isoGH : G \\isog H.\n\nLemma exponent_isog : exponent G = exponent H.\nProof. by case/isogP: isoGH => f injf <-; rewrite exponent_injm. Qed.\n\nLemma isog_abelem p : p.-abelem G = p.-abelem H.\nProof. by case/isogP: isoGH => f injf <-; rewrite injm_abelem. Qed.\n\nLemma isog_grank : 'm(G) = 'm(H).\nProof. by case/isogP: isoGH => f injf <-; rewrite injm_grank. Qed.\n\nLemma isog_p_rank p : 'r_p(G) = 'r_p(H).\nProof. by case/isogP: isoGH => f injf <-; rewrite injm_p_rank. Qed.\n\nLemma isog_rank : 'r(G) = 'r(H).\nProof. by case/isogP: isoGH => f injf <-; rewrite injm_rank. Qed.\n\nEnd IsogAbelem.\n\nSection QuotientAbelem.\n\nVariables (gT : finGroupType) (p : nat).\nImplicit Types E G K H : {group gT}.\n\nLemma exponent_quotient G H : exponent (G / H) %| exponent G.\nProof. exact: exponent_morphim. Qed.\n\nLemma quotient_LdivT n H : 'Ldiv_n() / H \\subset 'Ldiv_n().\nProof. exact: morphim_LdivT. Qed.\n\nLemma quotient_Ldiv n A H : 'Ldiv_n(A) / H \\subset 'Ldiv_n(A / H).\nProof. exact: morphim_Ldiv. Qed.\n\nLemma quotient_abelem G H : p.-abelem G -> p.-abelem (G / H).\nProof. exact: morphim_abelem. Qed.\n\nLemma quotient_pElem G H E : E \\in 'E_p(G) -> (E / H)%G \\in 'E_p(G / H).\nProof. exact: morphim_pElem. Qed.\n\nLemma logn_quotient G H : logn p #|G / H| <= logn p #|G|.\nProof. exact: logn_morphim. Qed.\n\nLemma quotient_pnElem G H n E :\n  E \\in 'E_p^n(G) -> {m | m <= n & (E / H)%G \\in 'E_p^m(G / H)}.\nProof. exact: morphim_pnElem. Qed.\n\nLemma quotient_grank G H : G \\subset 'N(H) -> 'm(G / H) <= 'm(G).\nProof. exact: morphim_grank. Qed.\n\nLemma p_rank_quotient G H : G \\subset 'N(H) -> 'r_p(G) - 'r_p(H) <= 'r_p(G / H).\nProof.\nmove=> nHG; rewrite leq_subLR.\nhave [E EpE] := p_rank_witness p G; have{EpE} [sEG abelE <-] := pnElemP EpE.\nrewrite -(LagrangeI E H) lognM ?cardG_gt0 //.\nrewrite -card_quotient ?(subset_trans sEG) // leq_add ?logn_le_p_rank // !inE.\n  by rewrite subsetIr (abelemS (subsetIl E H)).\nby rewrite quotientS ?quotient_abelem.\nQed.\n\nLemma p_rank_dprod K H G : K \\x H = G -> 'r_p(K) + 'r_p(H) = 'r_p(G).\nProof.\nmove=> defG; apply/eqP; rewrite eqn_leq -leq_subLR andbC.\nhave [_ defKH cKH tiKH] := dprodP defG; have nKH := cents_norm cKH.\nrewrite {1}(isog_p_rank (quotient_isog nKH tiKH)) /= -quotientMidl defKH.\nrewrite p_rank_quotient; last by rewrite -defKH mul_subG ?normG.\nhave [[E EpE] [F EpF]] := (p_rank_witness p K, p_rank_witness p H).\nhave [[sEK abelE <-] [sFH abelF <-]] := (pnElemP EpE, pnElemP EpF).\nhave defEF: E \\x F = E <*> F.\n  by rewrite dprodEY ?(centSS sFH sEK) //; apply/trivgP; rewrite -tiKH setISS.\napply/p_rank_geP; exists (E <*> F)%G; rewrite !inE (dprod_abelem p defEF).\nrewrite -lognM ?cargG_gt0 // (dprod_card defEF) abelE abelF eqxx.\nby rewrite -(genGid G) -defKH genM_join genS ?setUSS.\nQed.\n\nLemma p_rank_p'quotient G H :\n  (p : nat)^'.-group H -> G \\subset 'N(H) -> 'r_p(G / H) = 'r_p(G).\nProof.\nmove=> p'H nHG; have [P sylP] := Sylow_exists p G.\nhave [sPG pP _] := and3P sylP; have nHP := subset_trans sPG nHG.\nhave tiHP: H :&: P = 1 := coprime_TIg (p'nat_coprime p'H pP).\nrewrite -(p_rank_Sylow sylP) -(p_rank_Sylow (quotient_pHall nHP sylP)).\nby rewrite (isog_p_rank (quotient_isog nHP tiHP)).\nQed.\n\nEnd QuotientAbelem.\n\nSection OhmProps.\n\nSection Generic.\n\nVariables (n : nat) (gT : finGroupType).\nImplicit Types (p : nat) (x : gT) (rT : finGroupType).\nImplicit Types (A B : {set gT}) (D G H : {group gT}).\n\nLemma Ohm_sub G : 'Ohm_n(G) \\subset G.\nProof. by rewrite gen_subG; apply/subsetP=> x /setIdP[]. Qed.\n\nLemma Ohm1 : 'Ohm_n([1 gT]) = 1. Proof. exact: (trivgP (Ohm_sub _)). Qed.\n\nLemma Ohm_id G : 'Ohm_n('Ohm_n(G)) = 'Ohm_n(G).\nProof.\napply/eqP; rewrite eqEsubset Ohm_sub genS //.\nby apply/subsetP=> x /setIdP[Gx oxn]; rewrite inE mem_gen // inE Gx.\nQed.\n\nLemma Ohm_cont rT G (f : {morphism G >-> rT}) :\n  f @* 'Ohm_n(G) \\subset 'Ohm_n(f @* G).\nProof.\nrewrite morphim_gen ?genS //; last by rewrite -gen_subG Ohm_sub.\napply/subsetP=> fx /morphimP[x Gx]; rewrite inE Gx /=.\ncase/OhmPredP=> p p_pr xpn_1 -> {fx}.\nrewrite inE morphimEdom mem_imset //=; apply/OhmPredP; exists p => //.\nby rewrite -morphX // xpn_1 morph1.\nQed.\n\nLemma OhmS H G : H \\subset G -> 'Ohm_n(H) \\subset 'Ohm_n(G).\nProof.\nmove=> sHG; apply: genS; apply/subsetP=> x; rewrite !inE => /andP[Hx ->].\nby rewrite (subsetP sHG).\nQed.\n\nLemma OhmE p G : p.-group G -> 'Ohm_n(G) = <<'Ldiv_(p ^ n)(G)>>.\nProof.\nmove=> pG; congr <<_>>; apply/setP=> x; rewrite !inE; apply: andb_id2l => Gx.\ncase: (eqVneq x 1) => [-> | ntx]; first by rewrite !expg1n.\nby rewrite (pdiv_p_elt (mem_p_elt pG Gx)).\nQed.\n\nLemma OhmEabelian p G :\n  p.-group G -> abelian 'Ohm_n(G) -> 'Ohm_n(G) = 'Ldiv_(p ^ n)(G).\nProof.\nmove=> pG; rewrite (OhmE pG) abelian_gen => cGGn; rewrite gen_set_id //.\nrewrite -(setIidPr (subset_gen 'Ldiv_(p ^ n)(G))) setIA.\nby rewrite [_ :&: G](setIidPl _) ?gen_subG ?subsetIl // group_Ldiv ?abelian_gen.\nQed.\n\nLemma Ohm_p_cycle p x :\n  p.-elt x -> 'Ohm_n(<[x]>) = <[x ^+ (p ^ (logn p #[x] - n))]>.\nProof.\nmove=> p_x; apply/eqP; rewrite (OhmE p_x) eqEsubset cycle_subG mem_gen.\n  rewrite gen_subG andbT; apply/subsetP=> y /LdivP[x_y ypn].\n  case: (leqP (logn p #[x]) n) => [|lt_n_x].\n    by rewrite -subn_eq0 => /eqP->.\n  have p_pr: prime p by move: lt_n_x; rewrite lognE; case: (prime p).\n  have def_y: <[y]> = <[x ^+ (#[x] %/ #[y])]>.\n    apply: congr_group; apply/set1P.\n    by rewrite -cycle_sub_group ?cardSg ?inE ?cycle_subG ?x_y /=.\n  rewrite -cycle_subG def_y cycle_subG -{1}(part_pnat_id p_x) p_part.\n  rewrite -{1}(subnK (ltnW lt_n_x)) expnD -muln_divA ?order_dvdn ?ypn //.\n  by rewrite expgM mem_cycle.\nrewrite !inE mem_cycle -expgM -expnD addnC -maxnE -order_dvdn.\nby rewrite -{1}(part_pnat_id p_x) p_part dvdn_exp2l ?leq_maxr.\nQed.\n\nLemma Ohm_dprod A B G : A \\x B = G -> 'Ohm_n(A) \\x 'Ohm_n(B) = 'Ohm_n(G).\nProof.\ncase/dprodP => [[H K -> ->{A B}]] <- cHK tiHK.\nrewrite dprodEY //; last first.\n- by apply/trivgP; rewrite -tiHK setISS ?Ohm_sub.\n- by rewrite (subset_trans (subset_trans _ cHK)) ?centS ?Ohm_sub.\napply/eqP; rewrite -(cent_joinEr cHK) eqEsubset join_subG /=.\nrewrite !OhmS ?joing_subl ?joing_subr //= cent_joinEr //= -genM_join genS //.\napply/subsetP=> _ /setIdP[/imset2P[x y Hx Ky ->] /OhmPredP[p p_pr /eqP]].\nhave cxy: commute x y by red; rewrite -(centsP cHK).\nrewrite ?expgMn // -eq_invg_mul => /eqP def_x.\nhave ypn1: y ^+ (p ^ n) = 1.\n  by apply/set1P; rewrite -[[set 1]]tiHK inE -{1}def_x groupV !groupX.\nhave xpn1: x ^+ (p ^ n) = 1 by rewrite -[x ^+ _]invgK def_x ypn1 invg1.\nby rewrite mem_mulg ?mem_gen // inE (Hx, Ky); apply/OhmPredP; exists p.\nQed.\n\nLemma Mho_sub G : 'Mho^n(G) \\subset G.\nProof.\nrewrite gen_subG; apply/subsetP=> _ /imsetP[x /setIdP[Gx _] ->].\nexact: groupX.\nQed.\n\nLemma Mho1 : 'Mho^n([1 gT]) = 1. Proof. exact: (trivgP (Mho_sub _)). Qed.\n\nLemma morphim_Mho rT D G (f : {morphism D >-> rT}) :\n  G \\subset D -> f @* 'Mho^n(G) = 'Mho^n(f @* G).\nProof.\nmove=> sGD; have sGnD := subset_trans (Mho_sub G) sGD.\napply/eqP; rewrite eqEsubset {1}morphim_gen -1?gen_subG // !gen_subG.\napply/andP; split; apply/subsetP=> y.\n  case/morphimP=> xpn _ /imsetP[x /setIdP[Gx]].\n  set p := pdiv _ => p_x -> -> {xpn y}; have Dx := subsetP sGD x Gx.\n  by rewrite morphX // Mho_p_elt ?morph_p_elt ?mem_morphim.\ncase/imsetP=> _ /setIdP[/morphimP[x Dx Gx ->]].\nset p := pdiv _ => p_fx ->{y}; rewrite -(constt_p_elt p_fx) -morph_constt //.\nby rewrite -morphX ?mem_morphim ?Mho_p_elt ?groupX ?p_elt_constt.\nQed.\n\nLemma Mho_cont rT G (f : {morphism G >-> rT}) :\n  f @* 'Mho^n(G) \\subset 'Mho^n(f @* G).\nProof. by rewrite morphim_Mho. Qed.\n\nLemma MhoS H G : H \\subset G -> 'Mho^n(H) \\subset 'Mho^n(G).\nProof.\nmove=> sHG; apply: genS; apply: imsetS; apply/subsetP=> x.\nby rewrite !inE => /andP[Hx]; rewrite (subsetP sHG).\nQed.\n\nLemma MhoE p G : p.-group G -> 'Mho^n(G) = <<[set x ^+ (p ^ n) | x in G]>>.\nProof.\nmove=> pG; apply/eqP; rewrite eqEsubset !gen_subG; apply/andP.\ndo [split; apply/subsetP=> xpn; case/imsetP=> x] => [|Gx ->]; last first.\n  by rewrite Mho_p_elt ?(mem_p_elt pG).\ncase/setIdP=> Gx _ ->; have [-> | ntx] := eqVneq x 1; first by rewrite expg1n.\nby rewrite (pdiv_p_elt (mem_p_elt pG Gx) ntx) mem_gen //; apply: mem_imset.\nQed.\n\nLemma MhoEabelian p G :\n  p.-group G -> abelian G -> 'Mho^n(G) = [set x ^+ (p ^ n) | x in G].\nProof.\nmove=> pG cGG; rewrite (MhoE pG); rewrite gen_set_id //; apply/group_setP.\nsplit=> [|xn yn]; first by apply/imsetP; exists 1; rewrite ?expg1n.\ncase/imsetP=> x Gx ->; case/imsetP=> y Gy ->.\nby rewrite -expgMn; [apply: mem_imset; rewrite groupM | apply: (centsP cGG)].\nQed.\n\nLemma trivg_Mho G : 'Mho^n(G) == 1 -> 'Ohm_n(G) == G.\nProof.\nrewrite -subG1 gen_subG eqEsubset Ohm_sub /= => Gp1.\nrewrite -{1}(Sylow_gen G) genS //; apply/bigcupsP=> P.\ncase/SylowP=> p p_pr /and3P[sPG pP _]; apply/subsetP=> x Px.\nhave Gx := subsetP sPG x Px; rewrite inE Gx //=.\nrewrite (sameP eqP set1P) (subsetP Gp1) ?mem_gen //; apply: mem_imset.\nby rewrite inE Gx; apply: pgroup_p (mem_p_elt pP Px).\nQed.\n\nLemma Mho_p_cycle p x : p.-elt x -> 'Mho^n(<[x]>) = <[x ^+ (p ^ n)]>.\nProof.\nmove=> p_x.\napply/eqP; rewrite (MhoE p_x) eqEsubset cycle_subG mem_gen; last first.\n  by apply: mem_imset; apply: cycle_id.\nrewrite gen_subG andbT; apply/subsetP=> _ /imsetP[_ /cycleP[k ->] ->].\nby rewrite -expgM mulnC expgM mem_cycle.\nQed.\n\nLemma Mho_cprod A B G : A \\* B = G -> 'Mho^n(A) \\* 'Mho^n(B) = 'Mho^n(G).\nProof.\ncase/cprodP => [[H K -> ->{A B}]] <- cHK; rewrite cprodEY //; last first.\n  by rewrite (subset_trans (subset_trans _ cHK)) ?centS ?Mho_sub.\napply/eqP; rewrite -(cent_joinEr cHK) eqEsubset join_subG /=.\nrewrite !MhoS ?joing_subl ?joing_subr //= cent_joinEr // -genM_join.\napply: genS; apply/subsetP=> xypn /imsetP[_ /setIdP[/imset2P[x y Hx Ky ->]]].\nmove/constt_p_elt; move: (pdiv _) => p <- ->.\nhave cxy: commute x y by red; rewrite -(centsP cHK).\nrewrite consttM // expgMn; last exact: commuteX2.\nby rewrite mem_mulg ?Mho_p_elt ?groupX ?p_elt_constt.\nQed.\n\nLemma Mho_dprod A B G : A \\x B = G -> 'Mho^n(A) \\x 'Mho^n(B) = 'Mho^n(G).\nProof.\ncase/dprodP => [[H K -> ->{A B}]] defG cHK tiHK.\nrewrite dprodEcp; first by apply: Mho_cprod; rewrite cprodE.\nby apply/trivgP; rewrite -tiHK setISS ?Mho_sub.\nQed.\n\nEnd Generic.\n\nCanonical Ohm_igFun i := [igFun by Ohm_sub i & Ohm_cont i].\nCanonical Ohm_gFun i := [gFun by Ohm_cont i].\nCanonical Ohm_mgFun i := [mgFun by OhmS i].\n\nCanonical Mho_igFun i := [igFun by Mho_sub i & Mho_cont i].\nCanonical Mho_gFun i := [gFun by Mho_cont i].\nCanonical Mho_mgFun i := [mgFun by MhoS i].\n\nSection char.\n\nVariables (n : nat) (gT rT : finGroupType) (D G : {group gT}).\n\nLemma Ohm_char : 'Ohm_n(G) \\char G. Proof. exact: gFchar. Qed.\nLemma Ohm_normal : 'Ohm_n(G) <| G. Proof. exact: gFnormal. Qed.\n\nLemma Mho_char : 'Mho^n(G) \\char G. Proof. exact: gFchar. Qed.\nLemma Mho_normal : 'Mho^n(G) <| G. Proof. exact: gFnormal. Qed.\n\nLemma morphim_Ohm (f : {morphism D >-> rT}) :\n  G \\subset D -> f @* 'Ohm_n(G) \\subset 'Ohm_n(f @* G).\nProof. exact: morphimF. Qed.\n\nLemma injm_Ohm (f : {morphism D >-> rT}) :\n  'injm f -> G \\subset D -> f @* 'Ohm_n(G) = 'Ohm_n(f @* G).\nProof. by move=> injf; apply: injmF. Qed.\n\nLemma isog_Ohm (H : {group rT}) : G \\isog H -> 'Ohm_n(G) \\isog 'Ohm_n(H).\nProof. exact: gFisog. Qed.\n\nLemma isog_Mho (H : {group rT}) : G \\isog H -> 'Mho^n(G) \\isog 'Mho^n(H).\nProof. exact: gFisog. Qed.\n\nEnd char.\n\nVariable gT : finGroupType.\nImplicit Types (pi : nat_pred) (p : nat).\nImplicit Types (A B C : {set gT}) (D G H E : {group gT}).\n\nLemma Ohm0 G : 'Ohm_0(G) = 1.\nProof.\napply/trivgP; rewrite /= gen_subG.\nby apply/subsetP=> x /setIdP[_]; rewrite inE.\nQed.\n\nLemma Ohm_leq m n G : m <= n -> 'Ohm_m(G) \\subset 'Ohm_n(G).\nProof.\nmove/subnKC <-; rewrite genS //; apply/subsetP=> y.\nby rewrite !inE expnD expgM => /andP[-> /eqP->]; rewrite expg1n /=.\nQed.\n\nLemma OhmJ n G x : 'Ohm_n(G :^ x) = 'Ohm_n(G) :^ x.\nProof.\nrewrite -{1}(setIid G) -(setIidPr (Ohm_sub n G)).\nby rewrite -!morphim_conj injm_Ohm ?injm_conj.\nQed.\n\nLemma Mho0 G : 'Mho^0(G) = G.\nProof.\napply/eqP; rewrite eqEsubset Mho_sub /=.\napply/subsetP=> x Gx; rewrite -[x]prod_constt group_prod // => p _.\nexact: Mho_p_elt (groupX _ Gx) (p_elt_constt _ _).\nQed.\n\nLemma Mho_leq m n G : m <= n -> 'Mho^n(G) \\subset 'Mho^m(G).\nProof.\nmove/subnKC <-; rewrite gen_subG //.\napply/subsetP=> _ /imsetP[x /setIdP[Gx p_x] ->].\nby rewrite expnD expgM groupX ?(Mho_p_elt _ _ p_x).\nQed.\n\nLemma MhoJ n G x : 'Mho^n(G :^ x) = 'Mho^n(G) :^ x.\nProof.\nby rewrite -{1}(setIid G) -(setIidPr (Mho_sub n G)) -!morphim_conj morphim_Mho.\nQed.\n\nLemma extend_cyclic_Mho G p x :\n    p.-group G -> x \\in G -> 'Mho^1(G) = <[x ^+ p]> -> \n  forall k, k > 0 -> 'Mho^k(G) = <[x ^+ (p ^ k)]>.\nProof.\nmove=> pG Gx defG1 [//|k _]; have pX := mem_p_elt pG Gx.\napply/eqP; rewrite eqEsubset cycle_subG (Mho_p_elt _ Gx pX) andbT.\nrewrite (MhoE _ pG) gen_subG; apply/subsetP=> ypk; case/imsetP=> y Gy ->{ypk}.\nhave: y ^+ p \\in <[x ^+ p]> by rewrite -defG1 (Mho_p_elt 1 _ (mem_p_elt pG Gy)).\nrewrite !expnS /= !expgM => /cycleP[j ->].\nby rewrite -!expgM mulnCA mulnC expgM mem_cycle.\nQed.\n\nLemma Ohm1Eprime G : 'Ohm_1(G) = <<[set x in G | prime #[x]]>>.\nProof.\nrewrite -['Ohm_1(G)](genD1 (group1 _)); congr <<_>>.\napply/setP=> x; rewrite !inE andbCA -order_dvdn -order_gt1; congr (_ && _).\napply/andP/idP=> [[p_gt1] | p_pr]; last by rewrite prime_gt1 ?pdiv_id.\nset p := pdiv _ => ox_p; have p_pr: prime p by rewrite pdiv_prime.\nby have [_ dv_p] := primeP p_pr; case/pred2P: (dv_p _ ox_p) p_gt1 => ->.\nQed.\n\nLemma abelem_Ohm1 p G : p.-group G -> p.-abelem 'Ohm_1(G) = abelian 'Ohm_1(G).\nProof.\nmove=> pG; rewrite /abelem (pgroupS (Ohm_sub 1 G)) //.\ncase abG1: (abelian _) => //=; apply/exponentP=> x.\nby rewrite (OhmEabelian pG abG1); case/LdivP.\nQed.\n\nLemma Ohm1_abelem p G : p.-group G -> abelian G -> p.-abelem ('Ohm_1(G)).\nProof. by move=> pG cGG; rewrite abelem_Ohm1 ?(abelianS (Ohm_sub 1 G)). Qed.\n\nLemma Ohm1_id p G : p.-abelem G -> 'Ohm_1(G) = G.\nProof.\ncase/and3P=> pG cGG /exponentP Gp.\napply/eqP; rewrite eqEsubset Ohm_sub (OhmE 1 pG) sub_gen //.\nby apply/subsetP=> x Gx; rewrite !inE Gx Gp /=.\nQed.\n\nLemma abelem_Ohm1P p G :\n  abelian G -> p.-group G -> reflect ('Ohm_1(G) = G) (p.-abelem G).\nProof.\nmove=> cGG pG.\nby apply: (iffP idP) => [| <-]; [apply: Ohm1_id | apply: Ohm1_abelem].\nQed.\n\nLemma TI_Ohm1 G H : H :&: 'Ohm_1(G) = 1 -> H :&: G = 1.\nProof.\nmove=> tiHG1; case: (trivgVpdiv (H :&: G)) => // [[p pr_p]].\ncase/Cauchy=> // x /setIP[Hx Gx] ox.\nsuffices x1: x \\in [1] by rewrite -ox (set1P x1) order1 in pr_p.\nby rewrite -{}tiHG1 inE Hx Ohm1Eprime mem_gen // inE Gx ox.\nQed.\n\nLemma Ohm1_eq1 G : ('Ohm_1(G) == 1) = (G :==: 1).\nProof.\napply/idP/idP => [/eqP G1_1 | /eqP->]; last by rewrite -subG1 Ohm_sub.\nby rewrite -(setIid G) TI_Ohm1 // G1_1 setIg1.\nQed.\n\nLemma meet_Ohm1 G H : G :&: H != 1 -> G :&: 'Ohm_1(H) != 1.\nProof. by apply: contraNneq => /TI_Ohm1->. Qed.\n\nLemma Ohm1_cent_max G E p : E \\in 'E*_p(G) -> p.-group G -> 'Ohm_1('C_G(E)) = E.\nProof.\nmove=> EpmE pG; have [G1 | ntG]:= eqsVneq G 1.\n  case/pmaxElemP: EpmE; case/pElemP; rewrite G1 => /trivgP-> _ _.\n  by apply/trivgP; rewrite cent1T setIT Ohm_sub.\nhave [p_pr _ _] := pgroup_pdiv pG ntG.\nby rewrite (OhmE 1 (pgroupS (subsetIl G _) pG)) (pmaxElem_LdivP _ _) ?genGid.\nQed.\n\nLemma Ohm1_cyclic_pgroup_prime p G :\n  cyclic G -> p.-group G -> G :!=: 1 -> #|'Ohm_1(G)| = p.\nProof.\nmove=> cycG pG ntG; set K := 'Ohm_1(G).\nhave abelK: p.-abelem K by rewrite Ohm1_abelem ?cyclic_abelian.\nhave sKG: K \\subset G := Ohm_sub 1 G.\ncase/cyclicP: (cyclicS sKG cycG) => x /=; rewrite -/K => defK.\nrewrite defK -orderE (abelem_order_p abelK) //= -/K ?defK ?cycle_id //.\nrewrite -cycle_eq1 -defK -(setIidPr sKG).\nby apply: contraNneq ntG => /TI_Ohm1; rewrite setIid => ->.\nQed.\n\nLemma cyclic_pgroup_dprod_trivg p A B C :\n    p.-group C -> cyclic C -> A \\x B = C ->\n  A = 1 /\\ B = C \\/ B = 1 /\\ A = C.\nProof.\nmove=> pC cycC; case/cyclicP: cycC pC => x ->{C} pC defC.\ncase/dprodP: defC => [] [G H -> ->{A B}] defC _ tiGH; rewrite -defC.\ncase: (eqVneq <[x]> 1) => [|ntC].\n  move/trivgP; rewrite -defC mulG_subG => /andP[/trivgP-> _].\n  by rewrite mul1g; left.\nhave [pr_p _ _] := pgroup_pdiv pC ntC; pose K := 'Ohm_1(<[x]>).\nhave prK : prime #|K| by rewrite (Ohm1_cyclic_pgroup_prime _ pC) ?cycle_cyclic.\ncase: (prime_subgroupVti G prK) => [sKG |]; last first.\n  move/TI_Ohm1; rewrite -defC (setIidPl (mulG_subl _ _)) => ->.\n  by left; rewrite mul1g.\ncase: (prime_subgroupVti H prK) => [sKH |]; last first.\n  move/TI_Ohm1; rewrite -defC (setIidPl (mulG_subr _ _)) => ->.\n  by right; rewrite mulg1.\nhave K1: K :=: 1 by apply/trivgP; rewrite -tiGH subsetI sKG.\nby rewrite K1 cards1 in prK.\nQed.\n\nLemma piOhm1 G : \\pi('Ohm_1(G)) = \\pi(G).\nProof.\napply/eq_piP => p; apply/idP/idP; first exact: (piSg (Ohm_sub 1 G)).\nrewrite !mem_primes !cardG_gt0 => /andP[p_pr /Cauchy[] // x Gx oxp].\nby rewrite p_pr -oxp order_dvdG //= Ohm1Eprime mem_gen // inE Gx oxp.\nQed.\n\nLemma Ohm1Eexponent p G :\n  prime p -> exponent 'Ohm_1(G) %| p -> 'Ohm_1(G) = 'Ldiv_p(G).\nProof.\nmove=> p_pr expG1p; have pG: p.-group G.\n  apply: sub_in_pnat (pnat_pi (cardG_gt0 G)) => q _.\n  rewrite -piOhm1 mem_primes; case/and3P=> q_pr _; apply: pgroupP q_pr.\n  by rewrite -pnat_exponent (pnat_dvd expG1p) ?pnat_id.\napply/eqP; rewrite eqEsubset {2}(OhmE 1 pG) subset_gen subsetI Ohm_sub.\nby rewrite sub_LdivT expG1p.\nQed.\n\nLemma p_rank_Ohm1 p G : 'r_p('Ohm_1(G)) = 'r_p(G).\nProof.\napply/eqP; rewrite eqn_leq p_rankS ?Ohm_sub //.\napply/bigmax_leqP=> E /setIdP[sEG abelE].\nby rewrite (bigmax_sup E) // inE -{1}(Ohm1_id abelE) OhmS.\nQed.\n\nLemma rank_Ohm1 G : 'r('Ohm_1(G)) = 'r(G).\nProof.\napply/eqP; rewrite eqn_leq rankS ?Ohm_sub //.\nby have [p _ ->] := rank_witness G; rewrite -p_rank_Ohm1 p_rank_le_rank.\nQed.\n\nLemma p_rank_abelian p G : abelian G -> 'r_p(G) = logn p #|'Ohm_1(G)|.\nProof.\nmove=> cGG; have nilG := abelian_nil cGG; case p_pr: (prime p); last first.\n  by apply/eqP; rewrite lognE p_pr eqn0Ngt p_rank_gt0 mem_primes p_pr.\ncase/dprodP: (Ohm_dprod 1 (nilpotent_pcoreC p nilG)) => _ <- _ /TI_cardMg->.\nrewrite mulnC logn_Gauss; last first.\n  rewrite prime_coprime // -p'natE // -/(pgroup _ _).\n  exact: pgroupS (Ohm_sub _ _) (pcore_pgroup _ _).\nrewrite -(p_rank_Sylow (nilpotent_pcore_Hall p nilG)) -p_rank_Ohm1.\nrewrite p_rank_abelem // Ohm1_abelem ?pcore_pgroup //.\nexact: abelianS (pcore_sub _ _) cGG.\nQed.\n\nLemma rank_abelian_pgroup p G :\n  p.-group G -> abelian G -> 'r(G) = logn p #|'Ohm_1(G)|.\nProof. by move=> pG cGG; rewrite (rank_pgroup pG) p_rank_abelian. Qed.\n\nEnd OhmProps.\n\nSection AbelianStructure.\n\nVariable gT : finGroupType.\nImplicit Types (p : nat) (G H K E : {group gT}).\n\nLemma abelian_splits x G :\n  x \\in G -> #[x] = exponent G -> abelian G -> [splits G, over <[x]>].\nProof.\nmove=> Gx ox cGG; apply/splitsP; move: {2}_.+1 (ltnSn #|G|) => n.\nelim: n gT => // n IHn aT in x G Gx ox cGG *; rewrite ltnS => leGn.\nhave: <[x]> \\subset G by [rewrite cycle_subG]; rewrite subEproper.\ncase/predU1P=> [<-|]; first by exists 1%G; rewrite inE -subG1 subsetIr mulg1 /=.\ncase/properP=> sxG [y]; elim: {y}_.+1 {-2}y (ltnSn #[y]) => // m IHm y.\nrewrite ltnS => leym Gy x'y; case: (trivgVpdiv <[y]>) => [y1 | [p p_pr p_dv_y]].\n  by rewrite -cycle_subG y1 sub1G in x'y.\ncase x_yp: (y ^+ p \\in <[x]>); last first.\n  apply: IHm (negbT x_yp); rewrite ?groupX ?(leq_trans _ leym) //.\n  by rewrite orderXdiv // ltn_Pdiv ?prime_gt1.\nhave{x_yp} xp_yp: (y ^+ p \\in <[x ^+ p]>).\n  have: <[y ^+ p]>%G \\in [set <[x ^+ (#[x] %/ #[y ^+ p])]>%G].\n    by rewrite -cycle_sub_group ?order_dvdG // inE cycle_subG x_yp eqxx.\n  rewrite inE -cycle_subG -val_eqE /=; move/eqP->.\n  rewrite cycle_subG orderXdiv // divnA // mulnC ox.\n  by rewrite -muln_divA ?dvdn_exponent ?expgM 1?groupX ?cycle_id.\nhave: p <= #[y] by rewrite dvdn_leq.\nrewrite leq_eqVlt; case/predU1P=> [{xp_yp m IHm leym}oy | ltpy]; last first.\n  case/cycleP: xp_yp => k; rewrite -expgM mulnC expgM => def_yp.\n  suffices: #[y * x ^- k] < m.\n    by move/IHm; apply; rewrite groupMr // groupV groupX ?cycle_id.\n  apply: leq_ltn_trans (leq_trans ltpy leym).\n  rewrite dvdn_leq ?prime_gt0 // order_dvdn expgMn.\n    by rewrite expgVn def_yp mulgV.\n  by apply: (centsP cGG); rewrite ?groupV ?groupX.\npose Y := <[y]>; have nsYG: Y <| G by rewrite -sub_abelian_normal ?cycle_subG.\nhave [sYG nYG] := andP nsYG; have nYx := subsetP nYG x Gx.\nhave GxY: coset Y x \\in G / Y by rewrite mem_morphim.\nhave tiYx: Y :&: <[x]> = 1 by rewrite prime_TIg ?indexg1 -?[#|_|]oy ?cycle_subG.\nhave: #[coset Y x] = exponent (G / Y).\n  apply/eqP; rewrite eqn_dvd dvdn_exponent //.\n  apply/exponentP=> _ /morphimP[z Nz Gz ->].\n  rewrite -morphX // ((z ^+ _ =P 1) _) ?morph1 //.\n  rewrite orderE -quotient_cycle ?card_quotient ?cycle_subG // -indexgI /=.\n  by rewrite setIC tiYx indexg1 -orderE ox -order_dvdn dvdn_exponent.\ncase/IHn => // [||Hq]; first exact: quotient_abelian.\n  apply: leq_trans leGn; rewrite ltn_quotient // cycle_eq1.\n  by apply: contra x'y; move/eqP->; rewrite group1.\ncase/complP=> /= ti_x_Hq defGq.\nhave: Hq \\subset G / Y by rewrite -defGq mulG_subr.\ncase/inv_quotientS=> // H defHq sYH sHG; exists H.\nhave nYX: <[x]> \\subset 'N(Y) by rewrite cycle_subG.\nrewrite inE -subG1 eqEsubset mul_subG //= -tiYx subsetI subsetIl andbT.\nrewrite -{2}(mulSGid sYH) mulgA (normC nYX) -mulgA -quotientSK ?quotientMl //.\nrewrite -quotient_sub1 ?(subset_trans (subsetIl _ _)) // quotientIG //= -/Y.\nby rewrite -defHq quotient_cycle // ti_x_Hq defGq !subxx.\nQed.\n\nLemma abelem_splits p G H : p.-abelem G -> H \\subset G -> [splits G, over H].\nProof.\nelim: {G}_.+1 {-2}G H (ltnSn #|G|) => // m IHm G H.\nrewrite ltnS => leGm abelG sHG; case: (eqsVneq H 1) => [-> | ].\n  by apply/splitsP; exists G; rewrite inE mul1g -subG1 subsetIl /=.\ncase/trivgPn=> x Hx ntx; have Gx := subsetP sHG x Hx.\nhave [_ cGG eGp] := and3P abelG.\nhave ox: #[x] = exponent G.\n  by apply/eqP; rewrite eqn_dvd dvdn_exponent // (abelem_order_p abelG).\ncase/splitsP: (abelian_splits Gx ox cGG) => K; case/complP=> tixK defG.\nhave sKG: K \\subset G by rewrite -defG mulG_subr.\nhave ltKm: #|K| < m.\n  rewrite (leq_trans _ leGm) ?proper_card //; apply/properP; split=> //.\n  exists x => //; apply: contra ntx => Kx; rewrite -cycle_eq1 -subG1 -tixK.\n  by rewrite subsetI subxx cycle_subG.\ncase/splitsP: (IHm _ _ ltKm (abelemS sKG abelG) (subsetIr H K)) => L.\ncase/complP=> tiHKL defK; apply/splitsP; exists L; rewrite inE.\nrewrite -subG1 -tiHKL -setIA setIS; last by rewrite subsetI -defK mulG_subr /=.\nby rewrite -(setIidPr sHG) -defG -group_modl ?cycle_subG //= setIC -mulgA defK.\nQed.\n\nFact abelian_type_subproof G :\n  {H : {group gT} & abelian G -> {x | #[x] = exponent G & <[x]> \\x H = G}}.\nProof.\ncase cGG: (abelian G); last by exists G.\nhave [x Gx ox] := exponent_witness (abelian_nil cGG).\ncase/splitsP/ex_mingroup: (abelian_splits Gx (esym ox) cGG) => H.\ncase/mingroupp/complP=> tixH defG; exists H => _.\nexists x; rewrite ?dprodE // (sub_abelian_cent2 cGG) ?cycle_subG //.\nby rewrite -defG mulG_subr.\nQed.\n\nFixpoint abelian_type_rec n G :=\n  if n is n'.+1 then if abelian G && (G :!=: 1) then\n    exponent G :: abelian_type_rec n' (tag (abelian_type_subproof G))\n  else [::] else [::].\n\nDefinition abelian_type (A : {set gT}) := abelian_type_rec #|A| <<A>>.\n\nLemma abelian_type_dvdn_sorted A : sorted [rel m n | n %| m] (abelian_type A).\nProof.\nset R := SimplRel _; pose G := <<A>>%G.\nsuffices: path R (exponent G) (abelian_type A) by case: (_ A) => // m t /andP[].\nrewrite /abelian_type -/G; elim: {A}#|A| G {2 3}G (subxx G) => // n IHn G M sGM.\nsimpl; case: ifP => //= /andP[cGG ntG]; rewrite exponentS ?IHn //=.\ncase: (abelian_type_subproof G) => H /= [//| x _] /dprodP[_ /= <- _ _].\nexact: mulG_subr.\nQed.\n\nLemma abelian_type_gt1 A : all [pred m | m > 1] (abelian_type A).\nProof.\nrewrite /abelian_type; elim: {A}#|A| <<A>>%G => //= n IHn G.\ncase: ifP => //= /andP[_ ntG]; rewrite {n}IHn.\nby rewrite ltn_neqAle exponent_gt0 eq_sym -dvdn1 -trivg_exponent ntG.\nQed.\n\nLemma abelian_type_sorted A : sorted geq (abelian_type A).\nProof.\nhave:= abelian_type_dvdn_sorted A; have:= abelian_type_gt1 A.\ncase: (abelian_type A) => //= m t; elim: t m => //= n t IHt m /andP[].\nby move/ltnW=> m_gt0 t_gt1 /andP[n_dv_m /IHt->]; rewrite // dvdn_leq.\nQed.\n\nTheorem abelian_structure G :\n    abelian G ->\n  {b | \\big[dprod/1]_(x <- b) <[x]> = G & map order b = abelian_type G}.\nProof.\nrewrite /abelian_type genGidG.\nelim: {G}#|G| {-2 5}G (leqnn #|G|) => /= [|n IHn] G leGn cGG.\n  by rewrite leqNgt cardG_gt0 in leGn.\nrewrite {1}cGG /=; case: ifP => [ntG|/eqP->]; last first.\n  by exists [::]; rewrite ?big_nil.\ncase: (abelian_type_subproof G) => H /= [//|x ox xdefG]; rewrite -ox.\nhave [_ defG cxH tixH] := dprodP xdefG.\nhave sHG: H \\subset G by rewrite -defG mulG_subr.\ncase/IHn: (abelianS sHG cGG) => [|b defH <-].\n  rewrite -ltnS (leq_trans _ leGn) // -defG TI_cardMg // -orderE.\n  rewrite ltn_Pmull ?cardG_gt0 // ltn_neqAle order_gt0 eq_sym -dvdn1.\n  by rewrite ox -trivg_exponent ntG.\nby exists (x :: b); rewrite // big_cons defH xdefG.\nQed.\n\nLemma count_logn_dprod_cycle p n b G :\n    \\big[dprod/1]_(x <- b) <[x]> = G ->\n  count [pred x | logn p #[x] > n] b = logn p #|'Ohm_n.+1(G) : 'Ohm_n(G)|.\nProof.\nhave sOn1 := @Ohm_leq gT _ _ _ (leqnSn n).\npose lnO i (A : {set gT}) := logn p #|'Ohm_i(A)|.\nhave lnO_le H: lnO n H <= lnO n.+1 H.\n  by rewrite dvdn_leq_log ?cardG_gt0 // cardSg ?sOn1.\nhave lnOx i A B H: A \\x B = H -> lnO i A + lnO i B = lnO i H.\n  move=> defH; case/dprodP: defH (defH) => {A B}[[A B -> ->]] _ _ _ defH.\n  rewrite /lnO; case/dprodP: (Ohm_dprod i defH) => _ <- _ tiOAB.\n  by rewrite TI_cardMg ?lognM.\nrewrite -divgS //= logn_div ?cardSg //= -/(lnO _ _) -/(lnO _ _).\nelim: b G => [_ <-|x b IHb G] /=.\n  by rewrite big_nil /lnO !(trivgP (Ohm_sub _ _)) subnn.\nrewrite /= big_cons => defG; rewrite -!(lnOx _ _ _ _ defG) subnDA.\ncase/dprodP: defG => [[_ H _ defH] _ _ _] {G}; rewrite defH (IHb _ defH).\nsymmetry; do 2!rewrite addnC -addnBA ?lnO_le //; congr (_ + _).\npose y := x.`_p; have p_y: p.-elt y by rewrite p_elt_constt.\nhave{lnOx} lnOy i: lnO i <[x]> = lnO i <[y]>.\n  have cXX := cycle_abelian x.\n  have co_yx': coprime #[y] #[x.`_p^'] by rewrite !order_constt coprime_partC.\n  have defX: <[y]> \\x <[x.`_p^']> = <[x]>.\n    rewrite dprodE ?coprime_TIg //.\n      by rewrite -cycleM ?consttC //; apply: (centsP cXX); apply: mem_cycle.\n    by apply: (sub_abelian_cent2 cXX); rewrite cycle_subG mem_cycle.\n  rewrite -(lnOx i _ _ _ defX) addnC {1}/lnO lognE.\n  case: and3P => // [[p_pr _ /idPn[]]]; rewrite -p'natE //.\n  exact: pgroupS (Ohm_sub _ _) (p_elt_constt _ _).\nrewrite -logn_part -order_constt -/y !{}lnOy /lnO !(Ohm_p_cycle _ p_y).\ncase: leqP => [| lt_n_y].\n  by rewrite -subn_eq0 -addn1 subnDA => /eqP->; rewrite subnn.\nrewrite -!orderE -(subSS n) subSn // expnSr expgM.\nhave p_pr: prime p by move: lt_n_y; rewrite lognE; case: prime.\nset m := (p ^ _)%N; have m_gt0: m > 0 by rewrite expn_gt0 prime_gt0.\nsuffices p_ym: p %| #[y ^+ m].\n  rewrite -logn_div ?orderXdvd // (orderXdiv p_ym) divnA // mulKn //.\n  by rewrite logn_prime ?eqxx.\nrewrite orderXdiv ?pfactor_dvdn ?leq_subr // -(dvdn_pmul2r m_gt0).\nby rewrite -expnS -subSn // subSS divnK pfactor_dvdn ?leq_subr.\nQed.\n\nLemma perm_eq_abelian_type p b G :\n    p.-group G -> \\big[dprod/1]_(x <- b) <[x]> = G -> 1 \\notin b ->\n  perm_eq (map order b) (abelian_type G).\nProof.\nmove: b => b1 pG defG1 ntb1.\nhave cGG: abelian G.\n  elim: (b1) {pG}G defG1 => [_ <-|x b IHb G]; first by rewrite big_nil abelian1.\n  rewrite big_cons; case/dprodP=> [[_ H _ defH]] <-; rewrite defH => cxH _.\n  by rewrite abelianM cycle_abelian IHb.\nhave p_bG b: \\big[dprod/1]_(x <- b) <[x]> = G -> all (p_elt p) b.\n  elim: b {defG1 cGG}G pG => //= x b IHb G pG; rewrite big_cons.\n  case/dprodP=> [[_ H _ defH]]; rewrite defH andbC => defG _ _.\n  by rewrite -defG pgroupM in pG; case/andP: pG => p_x /IHb->.\nhave [b2 defG2 def_t] := abelian_structure cGG.\nhave ntb2: 1 \\notin b2.\n  apply: contraL (abelian_type_gt1 G) => b2_1.\n  rewrite -def_t -has_predC has_map.\n  by apply/hasP; exists 1; rewrite //= order1.\nrewrite -{}def_t; apply/allP=> m; rewrite -map_cat => /mapP[x b_x def_m].\nhave{ntb1 ntb2} ntx: x != 1.\n  by apply: contraL b_x; move/eqP->; rewrite mem_cat negb_or ntb1 ntb2.\nhave p_x: p.-elt x by apply: allP (x) b_x; rewrite all_cat !p_bG.\nrewrite -cycle_eq1 in ntx; have [p_pr _ [k ox]] := pgroup_pdiv p_x ntx.\napply/eqnP; rewrite {m}def_m orderE ox !count_map.\npose cnt_p k := count [pred x : gT | logn p #[x] > k].\nhave cnt_b b: \\big[dprod/1]_(x <- b) <[x]> = G ->\n  count [pred x | #[x] == p ^ k.+1]%N b = cnt_p k b - cnt_p k.+1 b.\n- move/p_bG; elim: b => //= _ b IHb /andP[/p_natP[j ->] /IHb-> {IHb}].\n  rewrite eqn_leq !leq_exp2l ?prime_gt1 // -eqn_leq pfactorK //.\n  case: ltngtP => // _ {j}; rewrite subSn // add0n; elim: b => //= y b IHb.\n  by rewrite leq_add // ltn_neqAle; case: (~~ _).\nby rewrite !cnt_b // /cnt_p !(@count_logn_dprod_cycle _ _ _ G).\nQed.\n\nLemma size_abelian_type G : abelian G -> size (abelian_type G) = 'r(G).\nProof.\nmove=> cGG; have [b defG def_t] := abelian_structure cGG.\napply/eqP; rewrite -def_t size_map eqn_leq andbC; apply/andP; split.\n  have [p p_pr ->] := rank_witness G; rewrite p_rank_abelian //.\n  by rewrite -indexg1 -(Ohm0 G) -(count_logn_dprod_cycle _ _ defG) count_size.\ncase/lastP def_b: b => // [b' x]; pose p := pdiv #[x].\nhave p_pr: prime p.\n  have:= abelian_type_gt1 G; rewrite -def_t def_b map_rcons -cats1 all_cat.\n  by rewrite /= andbT => /andP[_]; apply: pdiv_prime.\nsuffices: all [pred y | logn p #[y] > 0] b.\n  rewrite all_count (count_logn_dprod_cycle _ _ defG) -def_b; move/eqP <-.\n  by rewrite Ohm0 indexg1 -p_rank_abelian ?p_rank_le_rank.\napply/allP=> y; rewrite def_b mem_rcons inE /= => b_y.\nrewrite lognE p_pr order_gt0 (dvdn_trans (pdiv_dvd _)) //.\ncase/predU1P: b_y => [-> // | b'_y].\nhave:= abelian_type_dvdn_sorted G; rewrite -def_t def_b.\ncase/splitPr: b'_y => b1 b2; rewrite -cat_rcons rcons_cat map_cat !map_rcons.\nrewrite headI /= cat_path -(last_cons 2) -headI last_rcons.\ncase/andP=> _ /order_path_min min_y.\napply: (allP (min_y _)) => [? ? ? ? dv|]; first exact: (dvdn_trans dv).\nby rewrite mem_rcons mem_head.\nQed.\n\nLemma mul_card_Ohm_Mho_abelian n G :\n  abelian G -> (#|'Ohm_n(G)| * #|'Mho^n(G)|)%N = #|G|.\nProof.\ncase/abelian_structure => b defG _.\nelim: b G defG => [_ <-|x b IHb G].\n  by rewrite !big_nil (trivgP (Ohm_sub _ _)) (trivgP (Mho_sub _ _)) !cards1.\nrewrite big_cons => defG; rewrite -(dprod_card defG).\nrewrite -(dprod_card (Ohm_dprod n defG)) -(dprod_card (Mho_dprod n defG)) /=.\nrewrite mulnCA -!mulnA mulnCA mulnA; case/dprodP: defG => [[_ H _ defH] _ _ _].\nrewrite defH {b G defH IHb}(IHb H defH); congr (_ * _)%N => {H}.\nelim: {x}_.+1 {-2}x (ltnSn #[x]) => // m IHm x; rewrite ltnS => lexm.\ncase p_x: (p_group <[x]>); last first.\n  case: (eqVneq x 1) p_x => [-> |]; first by rewrite cycle1 p_group1.\n  rewrite -order_gt1 /p_group -orderE; set p := pdiv _ => ntx p'x.\n  have def_x: <[x.`_p]> \\x <[x.`_p^']> = <[x]>.\n    have ?: coprime #[x.`_p] #[x.`_p^'] by rewrite !order_constt coprime_partC.\n    have ?: commute x.`_p x.`_p^' by apply: commuteX2.\n    rewrite dprodE ?coprime_TIg -?cycleM ?consttC //.\n    by rewrite cent_cycle cycle_subG; apply/cent1P.\n  rewrite -(dprod_card (Ohm_dprod n def_x)) -(dprod_card (Mho_dprod n def_x)).\n  rewrite mulnCA -mulnA mulnCA mulnA.\n  rewrite !{}IHm ?(dprod_card def_x) ?(leq_trans _ lexm) {m lexm}//.\n    rewrite /order -(dprod_card def_x) -!orderE !order_constt ltn_Pmull //.\n    rewrite p_part -(expn0 p) ltn_exp2l 1?lognE ?prime_gt1 ?pdiv_prime //.\n    by rewrite order_gt0 pdiv_dvd.\n  rewrite proper_card // properEneq cycle_subG mem_cycle andbT.\n  by apply: contra (negbT p'x); move/eqP <-; apply: p_elt_constt.\ncase/p_groupP: p_x => p p_pr p_x.\nrewrite (Ohm_p_cycle n p_x) (Mho_p_cycle n p_x) -!orderE.\nset k := logn p #[x]; have ox: #[x] = (p ^ k)%N by rewrite -card_pgroup.\ncase: (leqP k n) => [le_k_n | lt_n_k].\n  rewrite -(subnKC le_k_n) subnDA subnn expg1 expnD expgM -ox.\n  by rewrite expg_order expg1n order1 muln1.\nrewrite !orderXgcd ox -{-3}(subnKC (ltnW lt_n_k)) expnD.\nrewrite gcdnC gcdnMl gcdnC gcdnMr.\nby rewrite mulnK ?mulKn ?expn_gt0 ?prime_gt0.\nQed.\n\nLemma grank_abelian G : abelian G -> 'm(G) = 'r(G).\nProof.\nmove=> cGG; apply/eqP; rewrite eqn_leq; apply/andP; split.\n  rewrite -size_abelian_type //; case/abelian_structure: cGG => b defG <-.\n  suffices <-: <<[set x in b]>> = G.\n    by rewrite (leq_trans (grank_min _)) // size_map cardsE card_size.\n  rewrite -{G defG}(bigdprodWY defG).\n  elim: b => [|x b IHb]; first by rewrite big_nil gen0.\n  by rewrite big_cons -joingE -joing_idr -IHb joing_idl joing_idr set_cons.\nhave [p p_pr ->] := rank_witness G; pose K := 'Mho^1(G).\nhave ->: 'r_p(G) = logn p #|G / K|.\n  rewrite p_rank_abelian // card_quotient /= ?gFnorm // -divgS ?Mho_sub //.\n  by rewrite -(mul_card_Ohm_Mho_abelian 1 cGG) mulnK ?cardG_gt0.\ncase: (grank_witness G) => B genB <-; rewrite -genB.\nhave: <<B>> \\subset G by rewrite genB.\nelim: {B genB}_.+1 {-2}B (ltnSn #|B|) => // m IHm B; rewrite ltnS.\ncase: (set_0Vmem B) => [-> | [x Bx]].\n  by rewrite gen0 quotient1 cards1 logn1.\nrewrite (cardsD1 x) Bx -{2 3}(setD1K Bx); set B' := B :\\ x => ltB'm.\nrewrite -joingE -joing_idl -joing_idr -/<[x]> join_subG => /andP[Gx sB'G].\nrewrite cent_joinEl ?(sub_abelian_cent2 cGG) //.\nhave nKx: x \\in 'N(K) by rewrite -cycle_subG (subset_trans Gx) ?gFnorm.\nrewrite quotientMl ?cycle_subG // quotient_cycle //= -/K.\nhave le_Kxp_1: logn p #[coset K x] <= 1.\n  rewrite -(dvdn_Pexp2l _ _ (prime_gt1 p_pr)) -p_part -order_constt.\n  rewrite order_dvdn -morph_constt // -morphX ?groupX //= coset_id //.\n  by rewrite Mho_p_elt ?p_elt_constt ?groupX -?cycle_subG.\napply: leq_trans (leq_add le_Kxp_1 (IHm _ ltB'm sB'G)).\nby rewrite -lognM ?dvdn_leq_log ?muln_gt0 ?cardG_gt0 // mul_cardG dvdn_mulr.\nQed.\n\nLemma rank_cycle (x : gT) : 'r(<[x]>) = (x != 1).\nProof.\nhave [->|ntx] := altP (x =P 1); first by rewrite cycle1 rank1.\napply/eqP; rewrite eqn_leq rank_gt0 cycle_eq1 ntx andbT.\nby rewrite -grank_abelian ?cycle_abelian //= -(cards1 x) grank_min.\nQed.\n\nLemma abelian_rank1_cyclic G : abelian G -> cyclic G = ('r(G) <= 1).\nProof.\nmove=> cGG; have [b defG atypG] := abelian_structure cGG.\napply/idP/idP; first by case/cyclicP=> x ->; rewrite rank_cycle leq_b1.\nrewrite -size_abelian_type // -{}atypG -{}defG unlock.\nby case: b => [|x []] //= _; rewrite ?cyclic1 // dprodg1 cycle_cyclic.\nQed.\n\nDefinition homocyclic A := abelian A && constant (abelian_type A).\n\nLemma homocyclic_Ohm_Mho n p G :\n  p.-group G -> homocyclic G -> 'Ohm_n(G) = 'Mho^(logn p (exponent G) - n)(G).\nProof.\nmove=> pG /andP[cGG homoG]; set e := exponent G.\nhave{pG} p_e: p.-nat e by apply: pnat_dvd pG; apply: exponent_dvdn.\nhave{homoG}: all (pred1 e) (abelian_type G).\n  move: homoG; rewrite /abelian_type -(prednK (cardG_gt0 G)) /=.\n  by case: (_ && _) (tag _); rewrite //= genGid eqxx.\nhave{cGG} [b defG <-] := abelian_structure cGG.\nmove: e => e in p_e *; elim: b => /= [|x b IHb] in G defG *.\n  by rewrite -defG big_nil (trivgP (Ohm_sub _ _)) (trivgP (Mho_sub _ _)).\ncase/andP=> /eqP ox e_b; rewrite big_cons in defG.\nrewrite -(Ohm_dprod _ defG) -(Mho_dprod _ defG).\ncase/dprodP: defG => [[_ H _ defH] _ _ _]; rewrite defH IHb //; congr (_ \\x _).\nby rewrite -ox in p_e *; rewrite (Ohm_p_cycle _ p_e) (Mho_p_cycle _ p_e).\nQed.\n\nLemma Ohm_Mho_homocyclic (n p : nat) G :\n    abelian G -> p.-group G -> 0 < n < logn p (exponent G) ->\n  'Ohm_n(G) = 'Mho^(logn p (exponent G) - n)(G) -> homocyclic G.\nProof.\nset e := exponent G => cGG pG /andP[n_gt0 n_lte] eq_Ohm_Mho.\nsuffices: all (pred1 e) (abelian_type G).\n  by rewrite /homocyclic cGG; apply: all_pred1_constant.\ncase/abelian_structure: cGG (abelian_type_gt1 G) => b defG <-.\nelim: b {-3}G defG (subxx G) eq_Ohm_Mho => //= x b IHb H.\nrewrite big_cons => defG; case/dprodP: defG (defG) => [[_ K _ defK]].\nrewrite defK => defHm cxK; rewrite setIC; move/trivgP=> tiKx defHd.\nrewrite -{1}defHm {defHm} mulG_subG cycle_subG ltnNge -trivg_card_le1.\ncase/andP=> Gx sKG; rewrite -(Mho_dprod _ defHd) => /esym defMho /andP[ntx ntb].\nhave{defHd} defOhm := Ohm_dprod n defHd.\napply/andP; split; last first.\n  apply: (IHb K) => //; have:= dprod_modr defMho (Mho_sub _ _).\n  rewrite -(dprod_modr defOhm (Ohm_sub _ _)).\n  rewrite !(trivgP (subset_trans (setIS _ _) tiKx)) ?Ohm_sub ?Mho_sub //.\n  by rewrite !dprod1g.\nhave:= dprod_modl defMho (Mho_sub _ _).\nrewrite -(dprod_modl defOhm (Ohm_sub _ _)) .\nrewrite !(trivgP (subset_trans (setSI _ _) tiKx)) ?Ohm_sub ?Mho_sub //.\nmove/eqP; rewrite eqEcard => /andP[_].\nhave p_x: p.-elt x := mem_p_elt pG Gx.\nhave [p_pr p_dv_x _] := pgroup_pdiv p_x ntx.\nrewrite !dprodg1 (Ohm_p_cycle _ p_x) (Mho_p_cycle _ p_x) -!orderE.\nrewrite orderXdiv ?leq_divLR ?pfactor_dvdn ?leq_subr //.\nrewrite orderXgcd divn_mulAC ?dvdn_gcdl // leq_divRL ?gcdn_gt0 ?order_gt0 //.\nrewrite leq_pmul2l //; apply: contraLR.\nrewrite eqn_dvd dvdn_exponent //= -ltnNge => lt_x_e.\nrewrite (leq_trans (ltn_Pmull (prime_gt1 p_pr) _)) ?expn_gt0 ?prime_gt0 //.\nrewrite -expnS dvdn_leq // ?gcdn_gt0 ?order_gt0 // dvdn_gcd.\nrewrite pfactor_dvdn // dvdn_exp2l.\n  by rewrite -{2}[logn p _]subn0 ltn_sub2l // lognE p_pr order_gt0 p_dv_x.\nrewrite ltn_sub2r // ltnNge -(dvdn_Pexp2l _ _ (prime_gt1 p_pr)) -!p_part.\nby rewrite !part_pnat_id // (pnat_dvd (exponent_dvdn G)).\nQed.\n\nLemma abelem_homocyclic p G : p.-abelem G -> homocyclic G.\nProof.\nmove=> abelG; have [_ cGG _] := and3P abelG.\nrewrite /homocyclic cGG (@all_pred1_constant _ p) //.\ncase/abelian_structure: cGG (abelian_type_gt1 G) => b defG <- => b_gt1.\napply/allP=> _ /mapP[x b_x ->] /=; rewrite (abelem_order_p abelG) //.\n  rewrite -cycle_subG -(bigdprodWY defG) ?sub_gen //.\n  by rewrite bigcup_seq (bigcup_sup x).\nby rewrite -order_gt1 [_ > 1](allP b_gt1) ?map_f.\nQed.\n\nLemma homocyclic1 : homocyclic [1 gT].\nProof. exact: abelem_homocyclic (abelem1 _ 2). Qed.\n\nLemma Ohm1_homocyclicP p G : p.-group G -> abelian G ->\n  reflect ('Ohm_1(G) = 'Mho^(logn p (exponent G)).-1(G)) (homocyclic G).\nProof.\nmove=> pG cGG; set e := logn p (exponent G); rewrite -subn1.\napply: (iffP idP) => [homoG | ]; first exact: homocyclic_Ohm_Mho.\ncase: (ltnP 1 e) => [lt1e | ]; first exact: Ohm_Mho_homocyclic.\nrewrite -subn_eq0 => /eqP->; rewrite Mho0 => <-.\nexact: abelem_homocyclic (Ohm1_abelem pG cGG).\nQed.\n\nLemma abelian_type_homocyclic G :\n  homocyclic G -> abelian_type G = nseq 'r(G) (exponent G).\nProof.\ncase/andP=> cGG; rewrite -size_abelian_type // /abelian_type.\nrewrite -(prednK (cardG_gt0 G)) /=; case: andP => //= _; move: (tag _) => H.\nby move/all_pred1P->; rewrite genGid size_nseq.\nQed.\n\nLemma abelian_type_abelem p G : p.-abelem G -> abelian_type G = nseq 'r(G) p.\nProof.\nmove=> abelG; rewrite (abelian_type_homocyclic (abelem_homocyclic abelG)).\ncase: (eqVneq G 1%G) => [-> | ntG]; first by rewrite rank1.\ncongr nseq; apply/eqP; rewrite eqn_dvd; have [pG _ ->] := and3P abelG.\nhave [p_pr] := pgroup_pdiv pG ntG; case/Cauchy=> // x Gx <- _.\nexact: dvdn_exponent.\nQed.\n\nLemma max_card_abelian G :\n  abelian G -> #|G| <= exponent G ^ 'r(G) ?= iff homocyclic G.\nProof.\nmove=> cGG; have [b defG def_tG] := abelian_structure cGG.\nhave Gb: all (mem G) b.\n  apply/allP=> x b_x; rewrite -(bigdprodWY defG); have [b1 b2] := splitPr b_x.\n  by rewrite big_cat big_cons /= mem_gen // setUCA inE cycle_id.\nhave ->: homocyclic G = all (pred1 (exponent G)) (abelian_type G).\n  rewrite /homocyclic cGG /abelian_type; case: #|G| => //= n.\n  by move: (_ (tag _)) => t; case: ifP => //= _; rewrite genGid eqxx.\nrewrite -size_abelian_type // -{}def_tG -{defG}(bigdprod_card defG) size_map.\nrewrite unlock; elim: b Gb => //= x b IHb; case/andP=> Gx Gb.\nhave eGgt0: exponent G > 0 := exponent_gt0 G.\nhave le_x_G: #[x] <= exponent G by rewrite dvdn_leq ?dvdn_exponent.\nhave:= leqif_mul (leqif_eq le_x_G) (IHb Gb).\nby rewrite -expnS expn_eq0 eqn0Ngt eGgt0.\nQed.\n\nLemma card_homocyclic G : homocyclic G -> #|G| = (exponent G ^ 'r(G))%N.\nProof.\nby move=> homG; have [cGG _] := andP homG; apply/eqP; rewrite max_card_abelian.\nQed.\n\nLemma abelian_type_dprod_homocyclic p K H G :\n    K \\x H = G -> p.-group G -> homocyclic G ->\n     abelian_type K = nseq 'r(K) (exponent G)\n  /\\ abelian_type H = nseq 'r(H) (exponent G).\nProof.\nmove=> defG pG homG; have [cGG _] := andP homG.\nhave /mulG_sub[sKG sHG]: K * H = G by case/dprodP: defG.\nhave [cKK cHH] := (abelianS sKG cGG, abelianS sHG cGG).\nsuffices: all (pred1 (exponent G)) (abelian_type K ++ abelian_type H).\n  rewrite all_cat => /andP[/all_pred1P-> /all_pred1P->].\n  by rewrite !size_abelian_type.\nsuffices def_atG: abelian_type K ++ abelian_type H =i abelian_type G.\n  rewrite (eq_all_r def_atG); apply/all_pred1P.\n  by rewrite size_abelian_type // -abelian_type_homocyclic.\nhave [bK defK atK] := abelian_structure cKK.\nhave [bH defH atH] := abelian_structure cHH.\napply: perm_eq_mem; rewrite -atK -atH -map_cat.\napply: (perm_eq_abelian_type pG); first by rewrite big_cat defK defH.\nhave: all [pred m | m > 1] (map order (bK ++ bH)).\n  by rewrite map_cat all_cat atK atH !abelian_type_gt1.\nby rewrite all_map (eq_all (@order_gt1 _)) all_predC has_pred1.\nQed.\n\nLemma dprod_homocyclic p K H G :\n  K \\x H = G -> p.-group G -> homocyclic G -> homocyclic K /\\ homocyclic H.\nProof.\nmove=> defG pG homG; have [cGG _] := andP homG.\nhave /mulG_sub[sKG sHG]: K * H = G by case/dprodP: defG.\nhave [abtK abtH] := abelian_type_dprod_homocyclic defG pG homG.\nby rewrite /homocyclic !(abelianS _ cGG) // abtK abtH !constant_nseq.\nQed.\n\nLemma exponent_dprod_homocyclic p K H G :\n    K \\x H = G -> p.-group G -> homocyclic G -> K :!=: 1 ->\n  exponent K = exponent G.\nProof.\nmove=> defG pG homG ntK; have [homK _] := dprod_homocyclic defG pG homG.\nhave [] := abelian_type_dprod_homocyclic defG pG homG.\nby rewrite abelian_type_homocyclic // -['r(K)]prednK ?rank_gt0 => [[]|].\nQed.\n\nEnd AbelianStructure.\n\nArguments abelian_type {gT} A%g.\nArguments homocyclic {gT} A%g.\n\nSection IsogAbelian.\n\nVariables aT rT : finGroupType.\nImplicit Type (gT : finGroupType) (D G : {group aT}) (H : {group rT}).\n\nLemma isog_abelian_type G H : isog G H -> abelian_type G = abelian_type H.\nProof.\npose lnO p n gT (A : {set gT}) := logn p #|'Ohm_n.+1(A) : 'Ohm_n(A)|.\npose lni i p gT (A : {set gT}) := \\max_(e < logn p #|A| | i < lnO p e _ A) e.+1.\nsuffices{G} nth_abty gT (G : {group gT}) i:\n    abelian G -> i < size (abelian_type G) ->\n  nth 1%N (abelian_type G) i = (\\prod_(p < #|G|.+1) p ^ lni i p _ G)%N.\n- move=> isoGH; case cGG: (abelian G); last first.\n    rewrite /abelian_type -(prednK (cardG_gt0 G)) -(prednK (cardG_gt0 H)) /=.\n    by rewrite {1}(genGid G) {1}(genGid H) -(isog_abelian isoGH) cGG.\n  have cHH: abelian H by rewrite -(isog_abelian isoGH).\n  have eq_sz: size (abelian_type G) = size (abelian_type H).\n    by rewrite !size_abelian_type ?(isog_rank isoGH).\n  apply: (@eq_from_nth _ 1%N) => // i lt_i_G; rewrite !nth_abty // -?eq_sz //.\n  rewrite /lni (card_isog isoGH); apply: eq_bigr => p _; congr (p ^ _)%N.\n  apply: eq_bigl => e; rewrite /lnO -!divgS ?(Ohm_leq _ (leqnSn _)) //=.\n  by have:= card_isog (gFisog _ isoGH) => /= eqF; rewrite !eqF.\nmove=> cGG.\nhave (p): path leq 0 (map (logn p) (rev (abelian_type G))).\n  move: (abelian_type_gt1 G) (abelian_type_dvdn_sorted G).\n  case: abelian_type => //= m t; rewrite rev_cons map_rcons.\n  elim: t m => //= n t IHt m /andP[/ltnW m_gt0 nt_gt1].\n  rewrite -cats1 cat_path rev_cons map_rcons last_rcons /=.\n  by case/andP=> /dvdn_leq_log-> // /IHt->.\nhave{cGG} [b defG <- b_sorted] := abelian_structure cGG.\nrewrite size_map => ltib; rewrite (nth_map 1 _ _ ltib); set x := nth 1 b i.\nhave Gx: x \\in G.\n  have: x \\in b by rewrite mem_nth.\n  rewrite -(bigdprodWY defG); case/splitPr=> bl br.\n  by rewrite mem_gen // big_cat big_cons !inE cycle_id orbT.\nhave lexG: #[x] <= #|G| by rewrite dvdn_leq ?order_dvdG.\nrewrite -[#[x]]partn_pi // (widen_partn _ lexG) big_mkord big_mkcond.\napply: eq_bigr => p _; transitivity (p ^ logn p #[x])%N.\n  by rewrite -logn_gt0; case: posnP => // ->.\nsuffices lti_lnO e: (i < lnO p e _ G) = (e < logn p #[x]).\n  congr (p ^ _)%N; apply/eqP; rewrite eqn_leq andbC; apply/andP; split.\n    by apply/bigmax_leqP=> e; rewrite lti_lnO.\n  case: (posnP (logn p #[x])) => [-> // | logx_gt0].\n  have lexpG: (logn p #[x]).-1 < logn p #|G|.\n    by rewrite prednK // dvdn_leq_log ?order_dvdG.\n  by rewrite (@bigmax_sup _ (Ordinal lexpG)) ?(prednK, lti_lnO).\nrewrite /lnO -(count_logn_dprod_cycle _ _ defG).\ncase: (ltnP e _) (b_sorted p) => [lt_e_x | le_x_e].\n  rewrite -(cat_take_drop i.+1 b) -map_rev rev_cat !map_cat cat_path.\n  case/andP=> _ ordb; rewrite count_cat ((count _ _ =P i.+1) _) ?leq_addr //.\n  rewrite -{2}(size_takel ltib) -all_count.\n  move: ordb; rewrite (take_nth 1 ltib) -/x rev_rcons all_rcons /= lt_e_x.\n  case/andP=> _ /=; move/(order_path_min leq_trans); apply: contraLR.\n  rewrite -!has_predC !has_map; case/hasP=> y b_y /= le_y_e; apply/hasP.\n  by exists y; rewrite ?mem_rev //=; apply: contra le_y_e; apply: leq_trans.\nrewrite -(cat_take_drop i b) -map_rev rev_cat !map_cat cat_path.\ncase/andP=> ordb _; rewrite count_cat -{1}(size_takel (ltnW ltib)) ltnNge.\nrewrite addnC ((count _ _ =P 0) _) ?count_size //.\nrewrite eqn0Ngt -has_count; apply/hasPn=> y b_y /=; rewrite -leqNgt.\napply: leq_trans le_x_e; have ->: x = last x (rev (drop i b)).\n  by rewrite (drop_nth 1 ltib) rev_cons last_rcons.\nrewrite -mem_rev in b_y; case/splitPr: (rev _) / b_y ordb => b1 b2.\nrewrite !map_cat cat_path last_cat /=; case/and3P=> _ _.\nmove/(order_path_min leq_trans); case/lastP: b2 => // b3 x'.\nby move/allP; apply; rewrite ?map_f ?last_rcons ?mem_rcons ?mem_head.\nQed.\n\nLemma eq_abelian_type_isog G H :\n  abelian G -> abelian H -> isog G H = (abelian_type G == abelian_type H).\nProof.\nmove=> cGG cHH; apply/idP/eqP; first exact: isog_abelian_type.\nhave{cGG} [bG defG <-] := abelian_structure cGG.\nhave{cHH} [bH defH <-] := abelian_structure cHH.\nelim: bG bH G H defG defH => [|x bG IHb] [|y bH] // G H.\n  rewrite !big_nil => <- <- _.\n  by rewrite isog_cyclic_card ?cyclic1 ?cards1.\nrewrite !big_cons => defG defH /= [eqxy eqb].\napply: (isog_dprod defG defH).\n  by rewrite isog_cyclic_card ?cycle_cyclic -?orderE ?eqxy /=.\ncase/dprodP: defG => [[_ G' _ defG]] _ _ _; rewrite defG.\ncase/dprodP: defH => [[_ H' _ defH]] _ _ _; rewrite defH.\nexact: IHb eqb.\nQed.\n\nLemma isog_abelem_card p G H :\n  p.-abelem G -> isog G H = p.-abelem H && (#|H| == #|G|).\nProof.\nmove=> abelG; apply/idP/andP=> [isoGH | [abelH eqGH]].\n  by rewrite -(isog_abelem isoGH) (card_isog isoGH).\nrewrite eq_abelian_type_isog ?(@abelem_abelian _ p) //.\nby rewrite !(@abelian_type_abelem _ p) ?(@rank_abelem _ p) // (eqP eqGH).\nQed.\n\nVariables (D : {group aT}) (f : {morphism D >-> rT}).\n\nLemma morphim_rank_abelian G : abelian G -> 'r(f @* G) <= 'r(G).\nProof.\nmove=> cGG; have sHG := subsetIr D G; apply: leq_trans (rankS sHG).\nrewrite -!grank_abelian ?morphim_abelian ?(abelianS sHG) //=.\nby rewrite -morphimIdom morphim_grank ?subsetIl.\nQed.\n\nLemma morphim_p_rank_abelian p G : abelian G -> 'r_p(f @* G) <= 'r_p(G).\nProof.\nmove=> cGG; have sHG := subsetIr D G; apply: leq_trans (p_rankS p sHG).\nhave cHH := abelianS sHG cGG; rewrite -morphimIdom /=; set H := D :&: G.\nhave sylP := nilpotent_pcore_Hall p (abelian_nil cHH).\nhave sPH := pHall_sub sylP.\nhave sPD: 'O_p(H) \\subset D by rewrite (subset_trans sPH) ?subsetIl.\nrewrite -(p_rank_Sylow (morphim_pHall f sPD sylP)) -(p_rank_Sylow sylP) //.\nrewrite -!rank_pgroup ?morphim_pgroup ?pcore_pgroup //.\nby rewrite morphim_rank_abelian ?(abelianS sPH).\nQed.\n\nLemma isog_homocyclic G H : G \\isog H -> homocyclic G = homocyclic H.\nProof.\nmove=> isoGH.\nby rewrite /homocyclic (isog_abelian isoGH) (isog_abelian_type isoGH).\nQed.\n\nEnd IsogAbelian.\n\nSection QuotientRank.\n\nVariables (gT : finGroupType) (p : nat) (G H : {group gT}).\nHypothesis cGG : abelian G.\n\nLemma quotient_rank_abelian : 'r(G / H) <= 'r(G).\nProof. exact: morphim_rank_abelian. Qed.\n\nLemma quotient_p_rank_abelian : 'r_p(G / H) <= 'r_p(G).\nProof. exact: morphim_p_rank_abelian. Qed.\n\nEnd QuotientRank.\n\nSection FimModAbelem.\n\nImport GRing.Theory FinRing.Theory.\n\nLemma fin_lmod_char_abelem p (R : ringType) (V : finLmodType R):\n  p \\in [char R]%R -> p.-abelem [set: V].\nProof.\ncase/andP=> p_pr /eqP-pR0; apply/abelemP=> //.\nby split=> [|v _]; rewrite ?zmod_abelian // zmodXgE -scaler_nat pR0 scale0r.\nQed.\n\nLemma fin_Fp_lmod_abelem p (V : finLmodType 'F_p) :\n  prime p -> p.-abelem [set: V].\nProof. by move/char_Fp/fin_lmod_char_abelem->. Qed.\n\nLemma fin_ring_char_abelem p (R : finRingType) :\n  p \\in [char R]%R -> p.-abelem [set: R].\nProof. exact: fin_lmod_char_abelem [finLmodType R of R^o]. Qed.\n\nEnd FimModAbelem.\n\n", "meta": {"author": "palmskog", "repo": "mathcomp-experiment", "sha": "67a6e83c025784b1e6f646a30dde38e0f33060eb", "save_path": "github-repos/coq/palmskog-mathcomp-experiment", "path": "github-repos/coq/palmskog-mathcomp-experiment/mathcomp-experiment-67a6e83c025784b1e6f646a30dde38e0f33060eb/solvable/abelian.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6709051400645177}}
{"text": "(* prelude : add some result to the module Rstar *)\n\nRequire Import Relations List.\nRequire Import Operators_Properties.\nImport Relations.\n\n\nSection perms.\nVariable A : Type.\n\n Inductive 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  .\n\nDefinition perm := clos_refl_trans _ transpose.\n\nLemma transpose_sym : forall l l':list A, transpose l l' -> transpose l' l.\nProof.\n intros l l' H; elim H; [ left | right; auto ].\nQed.\n\nTheorem equivalence_perm : equivalence _ perm.\nProof.\nsplit.\n- intro x;constructor 2.\n- intros x y z;constructor 3 with y;auto.\n- intros x y H; induction H.\n +  constructor 1;apply transpose_sym;assumption.\n +  constructor 2.\n +  constructor 3 with y;auto.\nQed.\n\nEnd perms.\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/perms2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6709051349598091}}
{"text": "Require Import ZArith.\nRequire Import FunInd.\n\nInductive lambda_term : Set :=\n| variable : nat -> lambda_term  (* variables libres *)\n| reference : nat -> lambda_term (* variables liées *)\n| abstraction : lambda_term -> lambda_term\n| application : lambda_term -> lambda_term -> lambda_term.\n\nNotation \"'var' t\" := (variable t) (at level 80, right associativity).\nNotation \"'ref' t\" := (reference t) (at level 85, right associativity).\nNotation \"'λ' t\" := (abstraction t) (at level 99, right associativity).\nNotation \"'lapp'\" := application (at level 79).\n\n(**** Well-formedness ****)\n\nInductive well_formed_count : nat -> lambda_term -> Prop :=\n| reference_wf : forall (n m : nat), m < n -> well_formed_count n (reference m)\n| abstraction_wf : forall (n : nat) (t : lambda_term), well_formed_count (S n) t -> well_formed_count n (λ t)\n| application_wf : forall (n : nat) (t1 t2 : lambda_term), well_formed_count n t1 -> well_formed_count n t2 ->\n  well_formed_count n (lapp t1 t2).\n\nDefinition well_formed (t : lambda_term) := well_formed_count 0 t.\n\nAxiom well_formed_app : forall (t1 t2 : lambda_term),\n  well_formed (lapp t1 t2) -> well_formed t1 /\\ well_formed t2.\n\nFixpoint br_fix (n : nat) (t u : lambda_term) : lambda_term :=\n  match t with\n  (* variable libre *)\n  | var x => var x\n  (* on remplace si c'est le bon indice *)\n  | ref m =>\n       match (eq_nat_dec n m) with\n       | left _ => u\n       | _ => ref m\n       end\n  (* on passe un lambda donc on incrémente l'indice *)\n  | λ x => λ (br_fix (n + 1) x u)\n  (* on passe au contexte *)\n  | lapp t1 t2 => lapp (br_fix n t1 u) (br_fix n t2 u)\n  end.\n\nFixpoint beta_reduction_fix (t u : lambda_term) : option lambda_term :=\n    match t with\n    | var _ => None\n    | ref _ => None\n    | λ x => Some (br_fix 0 x u)\n    | lapp _ _ => None\n    end.\n\nFixpoint get_redex (t u : lambda_term) : lambda_term :=\n    match (beta_reduction_fix t u) with\n    | Some t' => t'\n    | None => (lapp t u)\n  end.\n\nInductive br : nat -> lambda_term -> lambda_term -> lambda_term -> Prop :=\n| br_variable : forall (n x : nat) (u : lambda_term),\n\tbr n (var x) u (var x)\n| br_reference : forall (n : nat) (t : lambda_term),\n\tbr n (ref n) t t\n| br_reference_2 : forall (n m : nat) (u : lambda_term),\n\tn <> m -> br n (ref m) u (ref m)\n| br_abstraction : forall (n : nat) (t t' u : lambda_term),\n\tbr (n + 1) t u t' -> br n (λ t) u (λ t')\n| br_application : forall (n : nat) (t1 t2 t1' t2' u : lambda_term),\n\tbr n t1 u t1' -> br n t2 u t2' -> br n (lapp t1 t2) u (lapp t1' t2').\n\nInductive beta_reduction : lambda_term -> lambda_term -> Prop :=\n| Beta_redex : forall (t t' u : lambda_term),\n  br 0 t u t' -> beta_reduction (lapp (λ t) u) t'.\n\nLtac remove_br :=\n  repeat\n  match goal with\n  | |- context[br _ (var ?x) _ (var ?x)] => apply br_variable\n  | |- context[br ?n (ref ?n) ?u ?u] => apply br_reference\n  | |- context[br ?n (ref ?m) _ (ref ?m)] => apply br_reference_2; auto\n  | |- context[br _ (λ ?t) _ (λ ?t')] => apply br_abstraction; simpl\n  | |- context[br _ (lapp ?t1 ?t2) _ (lapp ?t1' ?t2')] => apply br_application\n  end.\n\nFunctional Scheme br_fix_ind := Induction for br_fix Sort Prop.\n\nLemma correction_br : forall (n : nat) (l u : lambda_term), br n l u (br_fix n l u).\nProof.\nintros.\nfunctional induction (br_fix n l u).\nremove_br.\nremove_br.\nremove_br.\nremove_br. apply IHl0.\nremove_br. apply IHl0. apply IHl1.\nQed.\n\nLemma correction_beta_reduction : forall t u t' : lambda_term,  Some t' = (beta_reduction_fix (λ t) u) -> beta_reduction (lapp (λ t) u) t'.\nProof.\nintros.\ninversion H.\napply Beta_redex. apply correction_br.\nQed.\n\nInductive beta_ref_trans : lambda_term -> lambda_term -> Prop :=\n| Beta_redex_ref_trans : forall (t u : lambda_term),\n\tbeta_reduction t u -> beta_ref_trans t u\n| Beta_ref : forall (t : lambda_term),\n\tbeta_ref_trans t t\n| Beta_trans : forall (u t v : lambda_term),\n\tbeta_ref_trans t u -> beta_ref_trans u v -> beta_ref_trans t v\n| Beta_cong_lambda : forall (t t': lambda_term), beta_ref_trans t t' ->\n  beta_ref_trans (λ t) (λ t')\n| Beta_cong_app : forall (t u t' u': lambda_term), beta_ref_trans t t' ->\n  beta_ref_trans u u' -> beta_ref_trans (lapp t u) (lapp t' u').\n\nInductive beta_sym : lambda_term -> lambda_term -> Prop :=\n| Beta_redex_sym : forall (t u : lambda_term),\n\tbeta_ref_trans t u -> beta_sym t u\n| Beta_sym : forall (v t u : lambda_term),\n\tbeta_sym t v -> beta_sym u v -> beta_sym t u.\n\nNotation \"t '->β' u\" := (beta_reduction t u) (at level 86, no associativity).\nNotation \"t '->*β' u\" := (beta_ref_trans t u) (at level 87, no associativity).\nNotation \"t '=β' u\" := (beta_sym t u) (at level 88, no associativity).\n\n(**** Examples ****)\n\nDefinition id := (λ (ref 0)). (* x -> x *)\nDefinition vrai := (λ (λ (ref 1))). (* x,y -> x *)\nDefinition faux := (λ (λ (ref 0))). (* x,y -> y *)\nDefinition ifthenelse := (λ (λ (λ (lapp (lapp (ref 2) (ref 1))) (ref 0)))).\n(* b,x,y -> b(x,y) *)\nDefinition x := (var 0).\nDefinition y := (var 1).\n\n\nLemma vrai_wf : well_formed vrai.\nProof.\n  unfold well_formed, vrai.\n  apply abstraction_wf.\n  apply abstraction_wf.\n  apply reference_wf.\n  auto.\nQed.\n\nLemma identity : forall t : lambda_term, lapp id t ->β t.\nProof.\nintros.\napply Beta_redex.\napply correction_br.\nQed.\n\nLemma if_vrai : forall t t' : lambda_term, br 0 t t' t -> lapp (lapp (lapp ifthenelse vrai) t) t' ->*β t.\nProof.\nintros.\napply (Beta_trans (lapp (λ t) t')).\napply (Beta_trans (lapp (lapp vrai t) t')).\napply Beta_cong_app.\napply (Beta_trans (lapp (λ (λ (lapp (lapp vrai (ref 1)) (ref 0)))) t)).\napply Beta_cong_app.\napply Beta_redex_ref_trans; apply Beta_redex; apply correction_br.\napply Beta_ref.\napply Beta_cong_app.\napply Beta_cong_lambda.\napply Beta_cong_lambda.\napply (Beta_trans (lapp (λ (ref 1)) (ref 0))).\napply Beta_cong_app.\napply Beta_redex_ref_trans; apply Beta_redex; apply correction_br.\napply Beta_ref.\napply Beta_redex_ref_trans; apply Beta_redex; apply correction_br.\napply Beta_ref.\napply Beta_ref.\napply Beta_cong_app.\napply Beta_redex_ref_trans; apply Beta_redex; apply correction_br.\napply Beta_ref.\napply Beta_redex_ref_trans; apply Beta_redex.\napply H.\nQed.\n\nDefinition Y := λ (lapp (λ (lapp (ref 1) (lapp (ref 0) (ref 0)))) (λ (lapp (ref 1) (lapp (ref 0) (ref 0))))).\n\nLemma point_fixe_Y : forall (g:lambda_term) (x:nat), g = (var x) -> (lapp Y g) =β (lapp g (lapp Y g)).\nProof.\nintros.\napply (Beta_sym (lapp g (lapp (λ (lapp g (lapp (ref 0) (ref 0)))) (λ (lapp g (lapp (ref 0) (ref 0))))))).\napply (Beta_sym  (lapp (λ (lapp g (lapp (ref 0) (ref 0)))) (λ (lapp g (lapp (ref 0) (ref 0)))))).\napply Beta_redex_sym; apply Beta_redex_ref_trans; apply Beta_redex; apply correction_br.\napply (Beta_sym (lapp g (lapp (λ (lapp g (lapp (ref 0) (ref 0)))) (λ (lapp g (lapp (ref 0) (ref 0))))))); apply Beta_redex_sym.\napply Beta_ref.\napply Beta_redex_ref_trans; apply Beta_redex.\nrewrite H; apply correction_br.\napply Beta_redex_sym; apply Beta_cong_app.\napply Beta_ref. apply Beta_redex_ref_trans; apply Beta_redex; apply correction_br.\nQed.\n\nDefinition Θ := (lapp (λ (λ (lapp (ref 0) (lapp (lapp (ref 1) (ref 1)) (ref 0))))) (λ (λ (lapp (ref 0) (lapp (lapp (ref 1) (ref 1)) (ref 0)))))).\n\nLemma point_fixe_Θ : forall (g : lambda_term) (x : nat), g = (var x) -> (lapp Θ g) ->*β (lapp g (lapp Θ g)).\nProof.\nintros.\napply (Beta_trans (lapp (λ (lapp (ref 0) (lapp (lapp ((λ (λ (lapp (ref 0) (lapp (lapp (ref 1) (ref 1)) (ref 0)))))) ((λ (λ (lapp (ref 0) (lapp (lapp (ref 1) (ref 1)) (ref 0))))))) (ref 0)))) g)).\napply Beta_cong_app.\napply Beta_redex_ref_trans; apply Beta_redex; apply correction_br.\napply Beta_ref.\napply Beta_redex_ref_trans; apply Beta_redex; apply correction_br.\nQed.\n\nDefinition itere := λ (λ (λ (lapp (lapp (ref 2) (ref 1)) (ref 0)))).\nDefinition l_0 := λ (λ (ref 0)).\nDefinition l_1 := λ (λ (lapp (ref 1) (ref 0))).\nDefinition l_2 := λ (λ (lapp (ref 1) (lapp (ref 1) (ref 0)))).\nDefinition l_3 := λ (λ (lapp (ref 1) (lapp (ref 1) (lapp (ref 1) (ref 0))))).\nDefinition l_4 := λ (λ (lapp (ref 1) (lapp (ref 1) (lapp (ref 1) (lapp (ref 1) (ref 0)))))).\nDefinition l_5 := λ (λ (lapp (ref 1) (lapp (ref 1) (lapp (ref 1) (lapp (ref 1) (lapp (ref 1) (ref 0))))))).\nDefinition l_6 := λ (λ (lapp (ref 1) (lapp (ref 1) (lapp (ref 1) (lapp (ref 1) (lapp (ref 1) (lapp (ref 1) (ref 0)))))))).\nDefinition succ := λ (λ (λ (lapp (ref 1) (lapp (lapp (ref 2) (ref 1)) (ref 0))))).\nDefinition add := λ (λ (lapp itere (lapp (ref 1) (lapp succ (ref 0))))).\nDefinition fact := λ (lapp (ref 0) (λ λ λ (lapp (lapp (ref 0) (λ λ (lapp (ref 1) (lapp (lapp (ref 3) (ref 1)) (ref 0))))) (λ (lapp (ref 3) (lapp (ref 2) (ref 0))))))).\n\nGoal (lapp succ l_0) ->*β l_1.\nProof.\napply (Beta_trans (λ (λ (lapp (ref 1) (lapp (lapp l_0 (ref 1)) (ref 0)))))).\napply Beta_redex_ref_trans; apply Beta_redex; apply correction_br.\napply Beta_cong_lambda; apply Beta_cong_lambda; apply Beta_cong_app.\napply Beta_ref.\napply (Beta_trans (lapp (λ (ref 0)) (ref 0))).\napply Beta_cong_app. apply Beta_redex_ref_trans; apply Beta_redex; apply correction_br.\napply Beta_ref.\napply Beta_redex_ref_trans; apply Beta_redex; apply correction_br.\nQed.\n\n(**** Innermost strategy ****)\n\n(*Inductive innermost_strategy : lambda_term -> lambda_term -> Prop :=\n| in_lambda : forall t : lambda_term, innermost_strategy (λ t) (λ t)\n| in_variable : forall n : nat, innermost_strategy (var n) (var n)\n| in_app1 : forall t1 t2 t1' t3 : lambda_term, innermost_strategy t1 t1' -> t1' <> (λ t3) -> innermost_strategy (lapp t1 t2) (lapp t1' t2)\n| in_app2 : forall t1 t2 t1' t2' t3 t4 t4': lambda_term, innermost_strategy t1 t1' ->\n  innermost_strategy t2 t2' -> t1' = (λ t3) -> (beta_reduction (lapp t1' t2') t4) ->\n  innermost_strategy t4 t4' ->\n  innermost_strategy (lapp t1 t2) t4'.*)\n\nInductive innermost_strategy : lambda_term -> lambda_term -> Prop :=\n| in_lambda : forall t : lambda_term, innermost_strategy (λ t) (λ t)\n| in_app2 : forall t1 t2 t1' t2' t3 t4 t4': lambda_term, innermost_strategy t1 t1' ->\n  innermost_strategy t2 t2' -> t1' = (λ t3) -> ((lapp t1' t2') ->β t4) -> innermost_strategy t4 t4' ->\n  innermost_strategy (lapp t1 t2) t4'.\n\nLemma test0 : innermost_strategy (lapp id id) id.\nProof.\n  unfold id.\n  eapply in_app2.\n  apply in_lambda.\n  apply in_lambda.\n  auto.\n  apply Beta_redex.\n  apply br_reference.\n  apply in_lambda.\nQed.\n\n(*Lemma test0 : innermost_strategy (lapp id x) x.\nProof.\n  unfold id, x.\n  eapply in_app2.\n  apply in_lambda.\n  apply in_variable.\n  auto.\n  apply Beta_redex.\n  apply br_reference.\n  apply in_variable.\nQed.*)\n\nAxiom wf_abstraction : forall (t : lambda_term) (n : nat), well_formed_count n t -> well_formed_count n (λ t).\n(*\tProof.\n\tintros.\n\tapply abstraction_wf.\n\tinduction t.\n\tapply variable_wf.\n\tinversion H. apply reference_wf. apply le_S. apply H2.\n\tinversion H. apply abstraction_wf.\n\tadmit.\n\tinversion H.\n\tapply application_wf.\n\tapply IHt1. apply H3.\n\tapply IHt2. apply H4.\n\tAdmitted.*)\n\nLemma wf_succ : forall (t1 : lambda_term) (n : nat), well_formed_count n t1 -> well_formed_count (S n) t1.\n\tProof.\n\tinduction t1; intros.\n\tinversion H.\n\tapply reference_wf.\n\tinversion H; auto.\n\tapply abstraction_wf.\n\tapply (IHt1 (S n)).\n\tinversion H; auto.\n  apply application_wf; inversion H.\n  apply (IHt1_1 n); auto.\n  apply (IHt1_2 n); auto.\nQed.\n\nAxiom redex_well_formed : forall (t1 t2 : lambda_term), well_formed t1 -> t1 ->*β t2 -> well_formed t2.\n(*Proof.\nAdmitted.*)\n\nAxiom innermost_strategy_well_formed : forall (t1 t2 : lambda_term),\n  well_formed t1 -> innermost_strategy t1 t2 -> well_formed t2.\n(*  Proof.\n  unfold well_formed.\n  intros.\n  induction t1.\n  inversion H0. apply variable_wf.\n  inversion H. inversion H3.\n  inversion H0. apply H.\n  inversion H0.\n  inversion H.\n  Admitted.*)", "meta": {"author": "rsidhoum", "repo": "comp_cert_lambda_cam", "sha": "8042865498accd77fd0f747baac737de449ae342", "save_path": "github-repos/coq/rsidhoum-comp_cert_lambda_cam", "path": "github-repos/coq/rsidhoum-comp_cert_lambda_cam/comp_cert_lambda_cam-8042865498accd77fd0f747baac737de449ae342/Lambda_Calcul.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6709051267006966}}
{"text": "(** This file is part of CoqEAL, the Coq Effective Algebra Library.\n(c) Copyright INRIA and University of Gothenburg, see LICENSE *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div seq.\nFrom mathcomp Require Import zmodp path choice fintype tuple finset ssralg.\nFrom mathcomp Require Import bigop poly polydiv.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope ring_scope.\n\nImport GRing.Theory Pdiv.Ring Pdiv.CommonRing Pdiv.RingMonic.\n\nSection karatsuba.\n\nVariable R : ringType.\nDefinition split_poly n (p : {poly R}) := (rdivp p 'X^n, rmodp p 'X^n).\nDefinition shift_poly n : {poly R} -> {poly R} := *%R^~ 'X^n.\nDefinition normalize (p : {poly R}) := p.\n\nFixpoint karatsuba_rec (n : nat) (p q : {poly R}) :=\n  if n is n'.+1 then\n    let np := normalize p in  let nq := normalize q in\n    let sp := size p in let sq := size q in\n    if (sp <= 2) || (sq <= 2) then p * q else\n      let m       := minn sp./2 sq./2 in\n      let (p1,p2) := split_poly m p in\n      let (q1,q2) := split_poly m q in\n      let p1q1    := karatsuba_rec n' p1 q1 in\n      let p2q2    := karatsuba_rec n' p2 q2 in\n      let p12     := p1 + p2 in\n      let q12     := q1 + q2 in\n      let p12q12  := karatsuba_rec n' p12 q12 in\n      shift_poly (2 * m)%N p1q1 +\n       shift_poly m (p12q12 - p1q1 - p2q2) +\n       p2q2\n  else p * q.\n\nDefinition karatsuba (p q : {poly R}) :=\n  karatsuba_rec (maxn (size p) (size q)) p q.\n\nLemma karatsuba_recE n (p q : {poly R}) : karatsuba_rec n p q = p * q.\nProof.\nelim: n=> //= n ih in p q *; case: ifP=> // _; set m := minn _ _.\nrewrite [p in RHS](rdivp_eq (monicXn _ m)) [q in RHS](rdivp_eq (monicXn _ m)).\nset dp := rdivp p _; set dq := rdivp q _; set rp := rmodp p _; set rq := rmodp q _.\nrewrite /shift_poly /split_poly !ih !(mulrDr, mulrDl, mulNr) mulnC exprM.\nrewrite -[_ - _ - _]addrA [_ + _ + (- _ - _)]addrACA [_ + _ - _]addrAC.\nby rewrite subrr add0r addrK !(commr_polyXn, mulrA, addrA).\nQed.\n\nLemma karatsubaE (p q : {poly R}) : karatsuba p q = p * q.\nProof. exact: karatsuba_recE. Qed.\n\nEnd karatsuba.\n", "meta": {"author": "coq-community", "repo": "coqeal", "sha": "1063846268eb2c51fd0e8363dee9a247e3f70c7c", "save_path": "github-repos/coq/coq-community-coqeal", "path": "github-repos/coq/coq-community-coqeal/coqeal-1063846268eb2c51fd0e8363dee9a247e3f70c7c/theory/karatsuba.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033682, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6709051108989944}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Crypto.Util.Tuple.\nRequire Import Crypto.Util.ZRange.\nRequire Import Crypto.Util.FixedWordSizes.\n\nDefinition BoundedWord n (bitwidth : nat)\n           (bounds : tuple zrange n) : Type :=\n  { x : tuple (wordT (Nat.log2 bitwidth)) n\n  | is_bounded_by None bounds\n                  (map wordToZ x)}.\n\nDefinition BoundedWordToZ n w b (BW :BoundedWord n w b)\n  : tuple Z n :=  map wordToZ (proj1_sig BW).\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_crypto_defined/src/Util/BoundedWord.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.67086952412418}}
{"text": "Inductive List (A : Set) : Set :=\n  | Nil : List A\n  | Cons : A -> List A -> List A.\n\nInductive eqlong : List nat -> List nat -> Prop :=\n  | eql_cons :\n      forall (n m : nat) (x y : List nat),\n      eqlong x y -> eqlong (Cons nat n x) (Cons nat m y)\n  | eql_nil : eqlong (Nil nat) (Nil nat).\n\n\nParameter V1 : eqlong (Nil nat) (Nil nat) \\/ ~ eqlong (Nil nat) (Nil nat).\nParameter\n  V2 :\n    forall (a : nat) (x : List nat),\n    eqlong (Nil nat) (Cons nat a x) \\/ ~ eqlong (Nil nat) (Cons nat a x).\nParameter\n  V3 :\n    forall (a : nat) (x : List nat),\n    eqlong (Cons nat a x) (Nil nat) \\/ ~ eqlong (Cons nat a x) (Nil nat).\nParameter\n  V4 :\n    forall (a : nat) (x : List nat) (b : nat) (y : List nat),\n    eqlong (Cons nat a x) (Cons nat b y) \\/\n    ~ eqlong (Cons nat a x) (Cons nat b y).\n\nParameter\n  nff :\n    forall (n m : nat) (x y : List nat),\n    ~ eqlong x y -> ~ eqlong (Cons nat n x) (Cons nat m y).\nParameter\n  inv_r : forall (n : nat) (x : List nat), ~ eqlong (Nil nat) (Cons nat n x).\nParameter\n  inv_l : forall (n : nat) (x : List nat), ~ eqlong (Cons nat n x) (Nil nat).\n\nFixpoint eqlongdec (x y : List nat) {struct x} :\n eqlong x y \\/ ~ eqlong x y :=\n  match x, y return (eqlong x y \\/ ~ eqlong x y) with\n  | Nil _, Nil _ => or_introl (~ eqlong (Nil nat) (Nil nat)) eql_nil\n  | Nil _, Cons _ a x as L => or_intror (eqlong (Nil nat) L) (inv_r a x)\n  | Cons _ a x as L, Nil _ => or_intror (eqlong L (Nil nat)) (inv_l a x)\n  | Cons _ a x as L1, Cons _ b y as L2 =>\n      match eqlongdec x y return (eqlong L1 L2 \\/ ~ eqlong L1 L2) with\n      | or_introl h => or_introl (~ eqlong L1 L2) (eql_cons a b x y h)\n      | or_intror h => or_intror (eqlong L1 L2) (nff a b x y h)\n      end\n  end.\n\n\nType\n  match Nil nat as x, Nil nat as y return (eqlong x y \\/ ~ eqlong x y) with\n  | Nil _, Nil _ => or_introl (~ eqlong (Nil nat) (Nil nat)) eql_nil\n  | Nil _, Cons _ a x as L => or_intror (eqlong (Nil nat) L) (inv_r a x)\n  | Cons _ a x as L, Nil _ => or_intror (eqlong L (Nil nat)) (inv_l a x)\n  | Cons _ a x as L1, Cons _ b y as L2 =>\n      match eqlongdec x y return (eqlong L1 L2 \\/ ~ eqlong L1 L2) with\n      | or_introl h => or_introl (~ eqlong L1 L2) (eql_cons a b x y h)\n      | or_intror h => or_intror (eqlong L1 L2) (nff a b x y h)\n      end\n  end.\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/Case9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6708695150147903}}
{"text": "From QuickChick Require Import QuickChick Generators.\nRequire Import NPeano Lia.\n\nFrom mathcomp Require Import ssreflect ssrnat ssrbool eqtype.\n\nFrom QuickChick.RedBlack Require Import redblack.\n\nRequire Import List String.\nImport ListNotations.\n\nOpen Scope string.\n\nOpen Scope Checker_scope.\n\n(* Red-Black Tree invariant: executable definition *)\n\nFixpoint black_height_bool (t: tree) : option nat :=\n  match t with\n    | Leaf => Some 0\n    | Node c tl _ tr =>\n      let h1 := black_height_bool tl in\n      let h2 := black_height_bool tr in\n      match h1, h2 with\n        | Some n1, Some n2 =>\n          if n1 == n2 then\n            match c with\n              | Black => Some (S n1)\n              | Red => Some n1\n            end\n          else None\n        | _, _ => None\n      end\n  end.\n\nDefinition is_black_balanced (t : tree) : bool :=\n  isSome (black_height_bool t).\n\nFixpoint has_no_red_red (c : color) (t : tree) : bool :=\n  match t with\n    | Leaf => true\n    | Node Red t1 _ t2 =>\n      match c with\n        | Red => false\n        | Black => has_no_red_red Red t1 && has_no_red_red Red t2\n      end\n    | Node Black t1 _ t2 =>\n      has_no_red_red Black t1 && has_no_red_red Black t2\n  end.\n\n(* begin is_redblack_bool *)\nDefinition is_redblack_bool (t : tree) : bool :=\n  is_black_balanced t && has_no_red_red Red t.\n(* end is_redblack_bool *)\n\nFixpoint showColor (c : color) :=\n  match c with\n    | Red => \"Red\"\n    | Black => \"Black\"\n  end.\n\nFixpoint tree_to_string (t : tree) :=\n  match t with\n    | Leaf => \"Leaf\"\n    | Node c l x r => \"Node \" ++ showColor c ++ \" \"\n                            ++ \"(\" ++ tree_to_string l ++ \") \"\n                            ++ show x ++ \" \"\n                            ++ \"(\" ++ tree_to_string r ++ \")\"\n  end.\n\nInstance showTree {A : Type} `{_ : Show A} : Show tree :=\n  {|\n    show t := \"\" (* CH: tree_to_string t causes a 9x increase in runtime *)\n  |}.\n\n(* begin insert_preserves_redblack_checker *)\nDefinition insert_preserves_redblack_checker (genTree : G tree) : Checker :=\n  forAll arbitrary (fun n => forAll genTree (fun t =>\n    is_redblack_bool t ==> is_redblack_bool (insert n t))).\n(* end insert_preserves_redblack_checker *)\n\nImport QcDefaultNotation. Open Scope qc_scope.\n\n(* begin genAnyTree *)\nDefinition genColor := elems [Red; Black].\nFixpoint genAnyTree_depth (d : nat) : G tree :=\n  match d with \n    | 0 => returnGen Leaf\n    | S d' => freq [(1, returnGen Leaf);\n                    (9, liftGen4 Node genColor (genAnyTree_depth d')\n                                     arbitrary (genAnyTree_depth d'))]\n  end.\nDefinition genAnyTree : G tree := sized genAnyTree_depth.\n(* end genAnyTree *)\n\nExtract Constant defSize => \"10\".\n\nDefinition test_naive :=\n  insert_preserves_redblack_checker genAnyTree.\n(* begin QC_naive *)\n(*! QuickChick test_naive. *)\n(* end QC_naive *)\n\n(* gathering some size statistics *)\nFixpoint tree_size (t : tree) : nat :=\n  match t with\n    | Leaf => 1\n    | Node c tl _ tr => 1 + (tree_size tl) + (tree_size tr)\n  end.\n\nDefinition insert_preserves_redblack_checker_size (genTree : G tree) : Checker :=\n  forAll arbitrary (fun n => forAll genTree (fun t =>\n    collect (append \"size \" (show (tree_size t)))\n    (is_redblack_bool t ==> is_redblack_bool (insert n t)))).\n\n(*\nExtract Constant Test.defNumTests => \"100000\".\nQuickChick (insert_preserves_redblack_checker_size genAnyTree).\n*)\n\nModule DoNotation.\nImport ssrfun.\nNotation \"'do!' X <- A ; B\" :=\n  (bindGen A (fun X => B))\n  (at level 200, X ident, A at level 100, B at level 200).\nEnd DoNotation.\nImport DoNotation.\n\nRequire Import Relations Wellfounded Lexicographic_Product.\n\nDefinition ltColor (c1 c2: color) : Prop :=\n  match c1, c2 with\n    | Red, Black => True\n    | _, _ => False\n  end.\n\nLemma well_foulded_ltColor : well_founded ltColor.\nProof.\n  unfold well_founded.\n  intros c; destruct c;\n  repeat (constructor; intros c ?; destruct c; try now (exfalso; auto)).\nQed.\n\nDefinition sigT_of_prod {A B : Type} (p : A * B) : {_ : A & B} :=\n  let (a, b) := p in existT (fun _ : A => B) a b.\n\nDefinition prod_of_sigT {A B : Type} (p : {_ : A & B}) : A * B :=\n  let (a, b) := p in (a, b).\n\n\nDefinition wf_hc (c1 c2 : (nat * color)) : Prop :=\n  lexprod nat (fun _ => color) lt (fun _ => ltColor) (sigT_of_prod c1) (sigT_of_prod c2).\n\nLemma well_founded_hc : well_founded wf_hc.\nProof.\n  unfold wf_hc. apply wf_inverse_image.\n  apply wf_lexprod. now apply Wf_nat.lt_wf. intros _; now apply well_foulded_ltColor.\nQed.\n\nRequire Import Program.Wf. Import WfExtensionality.\nRequire Import FunctionalExtensionality.\n\n(* begin genRBTree_height *)\nProgram Fixpoint genRBTree_height (hc : nat*color) {wf wf_hc hc} : G tree :=\n  match hc with\n  | (0, Red) => returnGen Leaf\n  | (0, Black) => oneOf [returnGen Leaf;\n                    (do! n <- arbitrary; returnGen (Node Red Leaf n Leaf))]\n  | (S h, Red) => liftGen4 Node (returnGen Black) (genRBTree_height (h, Black))\n                                        arbitrary (genRBTree_height (h, Black))\n  | (S h, Black) => do! c' <- genColor;\n                    let h' := match c' with Red => S h | Black => h end in\n                    liftGen4 Node (returnGen c') (genRBTree_height (h', c'))\n                                       arbitrary (genRBTree_height (h', c')) end.\n(* end genRBTree_height *)\nNext Obligation.\n  unfold wf_hc; simpl; left; lia.\nQed.\nNext Obligation.\n  unfold wf_hc; simpl; left; lia.\nQed.\nNext Obligation.\n  unfold wf_hc; simpl; destruct c'; [right; apply I | left; lia].\nQed.\nNext Obligation.\n  unfold wf_hc; simpl; destruct c'; [right; apply I | left; lia].\nQed.\nNext Obligation.\n  abstract (apply well_founded_hc).\nDefined.\n\nLemma genRBTree_height_eq (hc : nat*color) :\n  genRBTree_height hc =\n  match hc with\n  | (0, Red) => returnGen Leaf\n  | (0, Black) => oneOf [returnGen Leaf;\n                    (do! n <- arbitrary; returnGen (Node Red Leaf n Leaf))]\n  | (S h, Red) => liftGen4 Node (returnGen Black) (genRBTree_height (h, Black))\n                                        arbitrary (genRBTree_height (h, Black))\n  | (S h, Black) => do! c' <- genColor;\n                    let h' := match c' with Red => S h | Black => h end in\n                    liftGen4 Node (returnGen c') (genRBTree_height (h', c'))\n                                       arbitrary (genRBTree_height (h', c')) end.\nProof.\n  unfold_sub genRBTree_height (genRBTree_height hc).\n  f_equal. destruct hc as [[|h] [|]]; try reflexivity.\n  f_equal. apply functional_extensionality => [[|]]; reflexivity.\nQed.\n\n(* Hope that this is enough for preventing unfolding genRBTree_height *)\nGlobal Opaque genRBTree_height.\n\n\n(* begin genRBTree *)\nDefinition genRBTree := bindGen arbitrary (fun h => genRBTree_height (h, Red)).\n(* end genRBTree *)\n\nDefinition showDiscards (r : Result) :=\n  match r with\n  | Success ns nd _ _ => \"Success: number of successes \" ++ show (ns-1) ++ newline ++\n                         \"         number of discards \"  ++ show nd ++ newline\n  | _ => show r\n  end.\n\nDefinition testInsert :=\n  showDiscards (quickCheck (insert_preserves_redblack_checker genRBTree)).\n\nExtract Constant defSize => \"10\".\nDefinition test_smart :=\n  (insert_preserves_redblack_checker genRBTree). \n(* begin QC_good *)\n(*! QuickChick test_smart. *)\n(* end QC_good *)\n\n(* gathering some size statistics\nExtract Constant Test.defNumTests => \"100000\".\nQuickChick (insert_preserves_redblack_checker_size genRBTree).\n*)\n", "meta": {"author": "mpstepan", "repo": "QC-631-Final", "sha": "4cbf25da5bd57252767e13c43cb20acb324178ee", "save_path": "github-repos/coq/mpstepan-QC-631-Final", "path": "github-repos/coq/mpstepan-QC-631-Final/QC-631-Final-4cbf25da5bd57252767e13c43cb20acb324178ee/examples/RedBlack/testing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605411, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.670869507922314}}
{"text": "Set Automatic Introduction.\n\nInductive even : nat -> Prop :=\n| even_0 : even 0\n| even_odd : forall n, odd n -> even (S n)\nwith odd : nat -> Prop :=\n| odd_1 : odd 1\n| odd_even : forall n, even n -> odd (S n).\n\nLemma foo {n : nat} (E : even n) : even (S (S n))\nwith bar {n : nat} (O : odd n) : odd (S (S n)).\nProof. destruct E. constructor. constructor. apply even_odd. apply (bar _ H).\n  destruct O. repeat constructor. apply odd_even. apply (foo _ H).\nDefined.\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/autointros.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.670817302673203}}
{"text": "Require Import Arith. \n\nStructure poset := {\nposet_carrier:> Set;\nposet_relation:> poset_carrier -> poset_carrier -> Prop;\nrefl: forall x , poset_relation x x ;\ntransivity: forall x  y z , poset_relation x y /\\ poset_relation y z\n -> poset_relation x z;\nanti_symmetry: forall x y, poset_relation x y /\\ poset_relation y x -> x = y;\n}.\n\nNotation \"x <= y\" := (poset_relation x y) (at level 70, no associativity).\n\nInductive two := a | b.\n\n\n\nDefinition ftwo(x y:two):Prop:=\nmatch x with\n    |a => True\n    | b => (match y with\n | b => True\n| a => False\nend\n)\nend.\nEval compute in (ftwo b a).\n\nDefinition two_poset : poset.\nProof.\nrefine {| poset_carrier := two; poset_relation := ftwo |}.\n-intros. induction x.\n   +  simpl. trivial.\n   +  simpl. trivial.\n- intros. rename H into Hypoth. induction x.\n   ++ simpl. trivial.\n   ++ destruct Hypoth.\n     *** induction y.\n         -- elim H.\n         -- apply H0.\n- intros. destruct H. induction x.\n   + induction y.\n     --- trivial.\n    --- elim H0.\n   + induction y. elim H. trivial.\nQed.\n\nInductive LiftedBool := T | F | B.\n\nDefnition LiftedBoolRel (x y : LiftedBool): Prop := \nmatch x with \n    |T => ( match y with \n          |T => True\n          |F => False\n          |B => False \n           end)\n    |F => ( match y with \n          |T => False\n          |F => True\n          |B => False \n           end)\n    |B => True\nend\n\nEval compute in LiftedBoolRel T F\nDefinition \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/Poset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.6707477875999774}}
{"text": "\nTheorem Ex041 (A B C : Prop) :  B /\\ B -> A -> ((C \\/ ~B) \\/ A <-> A /\\ ~(B -> ~A)).\nProof.\n  intro.\n  destruct H.\n  split.\n  + intro.\n    split.\n    - exact H1.\n    - intro. apply H3.\n      * exact H.\n      * exact H1.\n  + intro.\n    right.\n    exact H1.\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/Ex041.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7341195210831258, "lm_q1q2_score": 0.6707477717933826}}
{"text": "Require Import Coq.Classes.Morphisms.\nRequire Import Relation_Definitions.\nRequire Import Wellfounded.\nImport Basics.\nImport Relation_Operators.\n\nRequire Import compcert.lib.Coqlib.\n\n\n\n     (*  The order on the lists is not lexicographic!\n         It's Every element is smaller or equal.\n         ALSO : surprisingly, we don't need transitivity.       \n         \n       *)\n      Inductive list_ord {A} (ord: A -> A -> Prop): list A -> list A -> Prop:=\n      | lt_head: forall x y ls, ord x y -> list_ord ord (x::ls) (y::ls)\n      | lt_tail: forall x ls ls', list_ord ord ls ls' ->\n                             list_ord ord (x::ls) (x::ls').\n      Inductive list_ord_part {A}\n                (list_ord: list A -> list A -> Prop)\n                (ord: A -> A -> Prop): list A -> list A -> Prop:=\n      | lt_head_part: forall x y ls, ord x y ->\n                                list_ord_part list_ord ord (x::ls) (y::ls)\n      | lt_tail_part: forall x ls ls', list_ord ls ls' ->\n                                  list_ord_part list_ord ord (x::ls) (x::ls').\n      \n      Inductive list_ord_trans {A} (ord: A -> A -> Prop): list A -> list A -> Prop:=\n      | lt_head_trans: forall x y ls, ord x y -> list_ord_trans ord (x::ls) (y::ls)\n      | lt_tail_trans: forall x ls ls', list_ord_trans ord ls ls' ->\n                             list_ord_trans ord (x::ls) (x::ls')\n      | lt_all: forall x y ls ls', ord x y ->\n                              list_ord_trans ord ls ls' ->\n                              list_ord_trans ord (x::ls) (y::ls').\n      Instance list_ord_is_trans {A} (ord: relation A):\n        Transitive ord -> Transitive (list_ord_trans ord).\n      Proof.\n        intros Trans ?? z H1; revert z.\n        induction H1; intros z Hz; inv Hz;\n          first [constructor 1|\n                 constructor 2|\n                 constructor 3]; eauto.\n      Qed. \n\n      Definition trans_symprod {A B} ltA ltB : relation (A * B):=\n        Relation_Operators.clos_trans _ (@Relation_Operators.symprod A B ltA ltB).\n      Lemma trans_symprod_wf:\n         forall {A B} (leA : relation A) (leB : relation B),\n       well_founded leA -> well_founded leB -> \n       well_founded (trans_symprod leA leB).\n      Proof. intros; apply wf_clos_trans, wf_symprod; eauto. Qed.\n      \n      Definition ord_union_intersection {A B} ltA ltB : relation (A * B):=\n        Relation_Operators.clos_trans _ (@Relation_Operators.symprod A B ltA ltB).\n      \n      Lemma list_order_as_pair:\n        forall {A} ord (a b:A) lsa lsb,\n          list_ord ord (a::lsa) (b::lsb) <->\n          symprod _ _ ord (list_ord ord) (a,lsa) (b,lsb).\n      Proof.\n        split; intros **. \n        - inv H.\n          + left; assumption.\n          + right; assumption.\n        - remember (a,lsa) as alsa.\n          remember (b,lsb) as blsb.\n          set (listify:= fun a_lsa: (A * list A)=> (fst a_lsa) :: (snd a_lsa)). \n          replace (a::lsa) with (listify alsa) by\n           (unfold listify; subst; reflexivity).\n          replace (b::lsb) with (listify blsb) by\n              (unfold listify; subst; reflexivity).\n          clear Heqalsa Heqblsb.\n          induction H.\n          + apply lt_head; assumption.\n          + apply lt_tail; assumption.\n      Qed.\n      Lemma list_order_part_as_pair:\n        forall {A} list_ord ord (a b:A) lsa lsb,\n          list_ord_part list_ord ord (a::lsa) (b::lsb) <->\n          symprod _ _ ord list_ord (a,lsa) (b,lsb).\n      Proof.\n        split; intros **. \n        - inv H.\n          + left; assumption.\n          + right; assumption.\n        - remember (a,lsa) as alsa.\n          remember (b,lsb) as blsb.\n          set (listify:= fun a_lsa: (A * list A)=> (fst a_lsa) :: (snd a_lsa)). \n          replace (a::lsa) with (listify alsa) by\n           (unfold listify; subst; reflexivity).\n          replace (b::lsb) with (listify blsb) by\n              (unfold listify; subst; reflexivity).\n          clear Heqalsa Heqblsb.\n          induction H.\n          + apply lt_head_part; assumption.\n          + apply lt_tail_part; assumption.\n      Qed.   \n      \n      Lemma list_order_trans_as_pair:\n        forall {A} ord (a b:A) lsa lsb,\n          Transitive ord ->\n          list_ord_trans ord (a::lsa) (b::lsb) <->\n          trans_symprod ord (list_ord_trans ord) (a,lsa) (b,lsb).\n      Proof.\n        split; intros **. \n        - inv H0.\n          + eapply t_step; left; assumption.\n          + eapply t_step; right; assumption.\n          + eapply Relation_Operators.t_trans.\n            * eapply Relation_Operators.t_step.\n              left; eassumption.\n            * eapply Relation_Operators.t_step.\n              right; eassumption.\n        - remember (a,lsa) as alsa.\n          remember (b,lsb) as blsb.\n          set (listify:= fun a_lsa: (A * list A)=> (fst a_lsa) :: (snd a_lsa)). \n          replace (a::lsa) with (listify alsa) by\n           (unfold listify; subst; reflexivity).\n          replace (b::lsb) with (listify blsb) by\n              (unfold listify; subst; reflexivity).\n          clear Heqalsa Heqblsb.\n          induction H0. inv H0.\n          + apply lt_head_trans; assumption.\n          + apply lt_tail_trans; assumption.\n          + eapply list_ord_is_trans; eauto.\n      Qed.\n\n      (* List order annotated with length. *)\n      Definition ln_ord {A} (ord: (list A) -> (list A) -> Prop) n:=\n        fun ls1 ls2 =>\n          length ls1 = n /\\ length ls2 = n /\\ ord ls1 ls2.\n      \n      Lemma well_founded_by_length:\n        forall {A} (ord: relation A) ,\n        (forall n, forall x, length x = n ->\n              Acc (list_ord ord) x) ->\n        well_founded (list_ord ord).\n      Proof. intros ** ?; eapply H; reflexivity. Qed.\n        \n\n      Lemma list_ord_length:\n        forall {A} (ord: relation A) y x,\n          list_ord ord y x ->\n          length y = length x.\n      Proof.\n        intros. revert y H.\n        induction x; intros; inv H.\n        all: simpl; f_equal; eauto.\n      Qed.\n      \n      Lemma ln_ord_inversion:\n        forall {A} (ord: relation A) n y x,\n          length x = n ->\n          list_ord ord y x ->\n          ln_ord (list_ord ord) n y x.\n      Proof.\n        repeat split; auto.\n        - erewrite list_ord_length; eauto.\n      Qed.\n      \n      Lemma wf_list_helper:\n        forall {A} (ord: relation A) n,\n          (forall x : list A, Acc (ln_ord (list_ord ord) n) x) ->\n          forall x : list A,\n            Datatypes.length x = n -> Acc (list_ord ord) x.\n      Proof.\n        intros ? ? ? ? x.\n        eapply (@Acc_ind _ (ln_ord (list_ord ord) n)\n                         (fun x => length x = n -> Acc (list_ord ord) x) \n                         \n               ); eauto.\n        clear x; intros.\n        econstructor; intros.\n        eapply H1.\n        - apply ln_ord_inversion; eauto.\n        - erewrite list_ord_length; eauto.\n      Qed.\n\n        \n      Lemma wf_list_ord_n:\n        forall {A} (ord:A -> A -> Prop),\n        (forall n, well_founded (ln_ord (list_ord ord) n)) ->\n        well_founded (list_ord ord).\n      Proof.\n        intros ** ?.\n        eapply wf_list_helper; try reflexivity. eapply H.\n      Qed.\n          \n      Local Instance well_founded_subrelation {A}\n        : Proper (flip subrelation ==> impl) (@well_founded A).\n      Proof.\n        intros R R' HR Rwf a.\n        induction (Rwf a) as [a Ra R'a].\n        constructor; intros y Hy.\n        apply R'a, HR, Hy.\n      Qed.\n\n      Definition pair_to_list {A} (als: A *list A ): list A :=\n        match als with | (a, ls) => a:: ls end.\n      Definition comp_ord {A B} (ord:relation A) (f: B -> A): relation B:=\n        fun b1 b2 => ord (f b1) (f b2).\n      Lemma trans_symprod_length:\n        forall {A} (ord: relation A) x y,\n          trans_symprod ord (list_ord ord) x y ->\n          length (pair_to_list y) = length (pair_to_list x).\n      Proof.\n        intros.\n        induction H. inv H.\n        - reflexivity.\n        - simpl. eapply list_ord_length in H0; eauto.\n        - etransitivity; eauto.\n      Qed.\n      Lemma comp_ord_subrelation:\n        forall {A} ls_ord (ord: relation A),\n          (relation_equivalence)\n            (symprod _ _ ord (ls_ord))\n            (comp_ord (list_ord_part ls_ord ord) pair_to_list).\n      Proof.\n        intros ** [] []; split; intros H. \n        - inv H; constructor; auto.\n        - inv H; constructor; auto.\n      Qed.\n      \n      Lemma rel_equiv:\n        forall {A} (ord: relation A) n,\n          (flip subrelation)\n            (symprod _ _ ord (ln_ord (list_ord ord) n))\n            (comp_ord (ln_ord (list_ord ord) (S n)) pair_to_list).\n      Proof.\n        intros ** [] []; simpl. \n        - intros (?&?&?).\n          eapply list_order_as_pair in H1.\n          induction H1. \n          + constructor; auto.\n          + constructor.\n            repeat (split; eauto).\n      Qed.\n      Lemma wf_comp_ord_filter:\n        forall {A B} (ord:relation A) (f: B -> A) (P: A -> Prop),\n          (forall a, P a -> exists b, f b = a) ->\n          well_founded (comp_ord ord f) ->\n          (forall a b, ord a b -> P a) ->\n          (forall a b, ord a b -> P b) ->\n          well_founded ord.\n      Proof.\n        intros ?? ord f P H Hwf ? ? a.\n        econstructor; intros.\n        pose proof (H0 _ _ H2) as Py.\n        destruct (H y Py) as (b & fb); rewrite <- fb.\n        clear Py fb a y H2.\n        eapply (@Acc_ind _ (comp_ord ord f)\n                         (fun b => Acc ord (f b))); eauto.\n        - intros.\n          econstructor; intros.\n          pose proof (H0 _ _ H4) as Py.\n          destruct (H y Py) as (b' & fb'); rewrite <- fb' in *.\n          eapply H3; eauto.\n      Qed.\n\n      \n      Lemma pair_to_list_pimg:\n          forall A (a : list A), a <> nil ->\n                        exists b : A * list A, pair_to_list b = a.\n      Proof.\n        intros. destruct a; try (contradict H; reflexivity).\n        exists (a,a0); reflexivity.\n      Qed.\n      Lemma list_ord_wf:\n        forall {A} (ord:A->A->Prop),\n          well_founded ord ->\n          well_founded (list_ord ord).\n      Proof.\n        intros.\n        eapply wf_list_ord_n.\n        induction n.\n        - intros ** a. destruct a.\n          + constructor; intros ? (?&?&?). inv H2.\n          + constructor; intros ? (?&?&?). inv H1.\n        - eapply wf_comp_ord_filter;\n            try apply pair_to_list_pimg.\n          \n          + erewrite <- rel_equiv; eapply wf_symprod; auto.\n          + intros ?? (?&?&?) ?; subst; simpl in *;congruence.\n          + intros ?? (?&?&?) ?; subst; simpl in *;congruence.\n      Qed.\n\n      Lemma list_ord_part_wf:\n        forall {A} list_ord (ord:A->A->Prop),\n          well_founded ord ->\n          well_founded list_ord ->\n          well_founded (list_ord_part list_ord ord).\n      Proof.\n        intros.\n        eapply wf_comp_ord_filter;\n          try apply pair_to_list_pimg.\n        - erewrite <- comp_ord_subrelation; apply wf_symprod; assumption.\n        - intros ** Heq; subst; simpl in *. inv H1.\n        - intros ** Heq; subst; simpl in *. inv H1.\n      Qed.\n\n      \n      ", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/concurrency/compiler/list_order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6707453819881217}}
{"text": "Require Import Arith.\nRequire Import List.\nRequire Import Lang.\n\nLemma idx_length : forall (s : Set) (A : s) G n, idx n G = Some A -> length G > n.\nProof.\n  induction G ; intros ; simpl. \n  destruct n. \n  (* zero *)\n  simpl in H.  inversion H.\n  simpl in H. inversion H.\n  (* succ *)\n  intros. simpl. \n  case_eq n. intros. subst. auto with arith.\n  intros. apply gt_n_S. apply IHG. subst. simpl in H. auto.\nDefined.\n\nLemma idx_at : forall (S : Set) (Ξ Γ : list S) (A : S), idx (length Ξ) (Ξ++A::Γ) = Some A.\nProof.\n  induction Ξ. simpl. intros. auto.\n  intros. simpl. apply IHΞ.\nDefined.\n \nLemma hole_at_i : forall i j k,\n  shiftat j (v i) = (v k) -> (~ j = k).\nProof.\n  intros. simpl in *.\n  case_eq (le_lt_dec j i).\n  intros. rewrite H0 in H. clear H0.\n  unfold not. intros. rewrite <- H0 in H. \n  inversion H. \n  apply (le_Sn_n i). rewrite H2. auto.\n  intros. rewrite H0 in H. clear H0.\n  inversion H. \n  unfold not. intros. rewrite H1 in l. rewrite H0 in l.\n  apply (lt_irrefl k). auto.\nDefined. \n\nLemma idx_shift_le : forall (s : Set) \n  Ξ Γ i (A : s) B,  length Ξ <= i -> \n  idx i (Ξ ++ Γ) = Some B ->\n  idx (S i) (Ξ ++ A :: Γ) = Some B.\nProof.\n  induction Ξ ; intros. \n  simpl in * ; auto.\n  simpl ; destruct i. \n   (* 0 *) simpl in H ; inversion H.  \n   (* S i *) apply IHΞ ; eauto with arith.\nDefined. \n\nLemma idx_shift_lt : forall (s : Set) \n  Ξ Γ i (A : s) B,  i < length Ξ -> \n  idx i (Ξ ++ Γ) = Some B ->\n  idx i (Ξ ++ A :: Γ) = Some B.\nProof.\n  induction Ξ ; intros. \n  simpl in *. inversion H. \n  simpl ; destruct i. \n   (* 0 *) simpl in * ; auto.\n   (* S i *) simpl in *. apply IHΞ ; eauto with arith.\nDefined. \n\nDefinition weaken_var_lt : forall Ξ Γ i A B,\n  i < length Ξ -> \n  (Ξ ++ Γ ⊢ v i @ B) ->\n  (Ξ ++ A :: Γ ⊢ v i @ B).\nProof. \n  intros.\n  apply VarIntro. \n  inversion H0. subst. apply idx_shift_lt ; auto.\nDefined. \n \nDefinition weaken_var_gt : forall Ξ Γ i A B,\n  length Ξ < (S i) -> \n  (Ξ ++ Γ ⊢ v i @ B) ->\n  (Ξ ++ A :: Γ ⊢ v (S i) @ B).\nProof. \n  intros.\n  apply VarIntro.\n  inversion H0. subst.\n  apply idx_shift_le; auto with arith.  \nDefined.\n\nLemma weaken_var : forall Ξ Γ i A B, \n  (Ξ ++ Γ ⊢ v i @ B) -> \n  (Ξ ++ A :: Γ ⊢ shiftat (length Ξ) (v i) @ B).\nProof. \n  intros.\n  simpl.\n  case (le_lt_dec (length Ξ) i). intros.\n  apply weaken_var_gt; auto with arith.\n  intros. \n  apply weaken_var_lt; auto with arith.\nDefined.  \n\nLemma weaken : forall Ξ Γ t A B, \n  (Ξ ++ Γ ⊢ t @ B) -> \n  (Ξ ++ A :: Γ ⊢ shiftat (length Ξ) t @ B).\nProof.\n  refine \n    (fix weaken (Ξ Γ : Ctx) (t : Term) (A B : Ty) \n      (d : (Ξ ++ Γ ⊢ t @ B)) {struct t} : (Ξ ++ A :: Γ ⊢ shiftat (length Ξ) t @ B) := \n      (match t as t' \n         return (t = t' -> (Ξ ++ A :: Γ ⊢ shiftat (length Ξ) t @ B))\n        with \n         | v i => _ \n         | ƛ ty r => _ \n         | r · s => _\n       end) (refl_equal t))  ; intros ; subst.\n\n  (* var *) \n  intros. apply weaken_var. auto.\n  (* lam *)\n  simpl.\n  inversion d. subst.  \n  apply ImpIntro.\n  change (S (length Ξ)) with (length (ty::Ξ)).\n  change (ty :: Ξ ++ A :: Γ) with ((ty :: Ξ) ++ A :: Γ).\n  apply weaken. auto.\n\n  (* app *) \n  simpl.\n  inversion d. subst.  \n  apply ImpElim with (A:=A0).\n  apply weaken. auto.\n  apply weaken. auto.\nDefined.\n\nRequire Import Omega.\n\nLemma shift_invariance : forall t Γ i A, i >= length Γ -> (Γ ⊢ t @ A) -> shiftat i t = t.\nProof. \n  induction t ; intros ; simpl ; auto. \n\n  (* v *)\n  inversion H0. subst. apply idx_length in H3. \n  simpl. case (le_lt_dec i n) ; intros. apply False_rec. omega. auto.\n  \n  (* lam *) \n  inversion H0 ; subst.\n  rewrite IHt with (Γ:=t::Γ) (A:=B). auto. simpl. auto with arith. \n  inversion H0 ; subst.  auto.\n\n  (* app *) \n  inversion H0. subst.\n  rewrite IHt1 with (Γ:=Γ) (A:=A0 ⇒ A).\n  rewrite IHt2 with (Γ:=Γ) (A:=A0).\n  auto. auto. auto. auto. auto.\nDefined.\n\nLemma closed_shift_invariant : forall t A i, ([] ⊢ t @ A) -> shiftat i t = t.\nProof. \n  intros. \n  apply shift_invariance with (Γ:=[]) (A :=A). simpl. auto with arith. auto.\nDefined.\n\nLemma weaken_closed_one : forall Γ t A B, ([] ⊢ t @ A) -> (Γ ⊢ t @ A) -> (B::Γ ⊢ t @ A).\nProof.\n  induction Γ ; intros.\n\n  (* [] *)\n  apply closed_shift_invariant with (i:=0) in H. \n  rewrite <- H.\n  change [B] with ([]++B::[]). \n  apply weaken. simpl. auto.\n  intros.\n  \n  (* a::Γ *)\n  apply closed_shift_invariant with (i:=0) in H.\n  rewrite <- H.\n  change (B::a::Γ) with ([]++B::(a::Γ)). \n  apply weaken. simpl.  auto.\nDefined.\n\nLemma weaken_closed : forall Γ t A, ([] ⊢ t @ A) -> (Γ ⊢ t @ A).\nProof.\n  induction Γ. \n  intros. auto. intros. apply weaken_closed_one. auto. apply IHΓ. auto.\nDefined.\n\nLemma idx_sameR : forall (A : Set) i a (Γ Ξ:list A), \n  length Ξ < S i -> \n  idx (S i) (Ξ++a::Γ) = idx i (Ξ++Γ).\nProof.\n  refine\n    (fix idx_sameR (A : Set) i a (Γ Ξ:list A) (H: length Ξ < S i) {struct Ξ} : idx (S i) (Ξ++(a::Γ)) = idx i (Ξ++Γ) := \n      (match Ξ as Ξ' return (Ξ = Ξ' -> idx (S i) (Ξ++(a::Γ)) = idx i (Ξ++Γ)) with \n         | nil => _\n         | cons a g => _\n       end) (refl_equal Ξ)).\n  intros. subst. simpl. auto.\n  intros ; subst. simpl. simpl in H. \n  destruct i.  apply le_S_n in H. apply le_n_O_eq in H.\n  inversion H.  \n  apply idx_sameR. auto with arith.  \nDefined.  \n\nLemma idx_sameL : forall (s : Set) (Γ Ξ:list s) i A, \n  i < length Ξ -> \n  idx i (Ξ++A::Γ) = idx i (Ξ++Γ).\nProof. \n  induction Ξ ; intros ; simpl in *.\n  unfold lt in H. apply le_n_O_eq in H. inversion H.\n  destruct i. simpl. auto.   \n  simpl. apply IHΞ. eauto with arith.\nDefined.     \n\nLemma strengthen_gt : forall Ξ Γ i A B, \n  length Ξ < S i -> \n  (Ξ ++ A :: Γ ⊢ v (S i) @ B) -> \n  (Ξ ++ Γ ⊢ v i @ B).\nProof.\n  intros. \n  inversion H0 ; subst ; auto.\n  apply VarIntro. \n  rewrite <- idx_sameR with (a:=A) ; auto.\nDefined. \n\nLemma strengthen_lt : forall Ξ Γ i A B, \n  i < length Ξ -> \n  (Ξ ++ A :: Γ ⊢ v i @ B) -> \n  (Ξ ++ Γ ⊢ v i @ B).\nProof.\n  intros. inversion H0. subst. \n  apply VarIntro.\n  rewrite <- idx_sameL with (A:=A) ; auto. \nDefined.\n", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/ApplicativeBisim/Context.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.6706756114124309}}
{"text": "Definition tautology : forall P : Prop, P -> P\n:= (fun (P : Prop) (H : P)=> H).\n\nDefinition Modus_tollens : forall P Q : Prop, ~Q /\\ (P -> Q) -> ~P :=\n  (fun (P Q : Prop) (H : ~Q /\\ (P -> Q)) =>\n     match H with\n       | conj H0 H1 => (fun (H2 : P) => H0 (H1 H2))\n     end).\n\nDefinition Diojunctive_syllogism : forall P Q : Prop, (P \\/ Q) -> ~P -> Q\n  :=(fun (P Q : Prop) (H0 : P \\/ Q) (H1 : ~P) =>\n       match H0 with\n         | or_introl H2 => match H1 H2 return Q with end\n         | or_intror H2 => H2\n       end\n    )\n.\n\nDefinition tautology_on_Set : forall A : Set, A -> A\n  := (fun (A : Set) (B : A) => B)\n.\n\nDefinition Modus_tollens_on_Set : forall A B : Set, (B -> Empty_set) * (A -> B) -> (A -> Empty_set)\n  := (fun (A B : Set) (H : (B -> Empty_set) * (A -> B)) (H0 : A) =>\n        let (a, b) := H in\n        a (b H0)\n     )\n.\n\nDefinition Diojunctive_syllogism_on_Set : forall A B : Set, (A + B) -> (A -> Empty_set) -> B\n  := (fun (A B : Set) (C : A + B) (H : A -> Empty_set) =>\n        match C with\n          | inr b => b\n          | inl a => match H a return B with\n                     end\n        end\n     )\n.\n", "meta": {"author": "KeenS", "repo": "coqex", "sha": "325a48569d54a8925e41f757cbb4c3c74443c5a3", "save_path": "github-repos/coq/KeenS-coqex", "path": "github-repos/coq/KeenS-coqex/coqex-325a48569d54a8925e41f757cbb4c3c74443c5a3/4/16.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6706716890252019}}
{"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 Bool Lia Eqdep_dec.\n\nFrom Undecidability.Shared.Libs.DLW.Utils\n  Require Import utils_tac utils_list utils_nat finite.\n\nFrom Undecidability.Shared.Libs.DLW.Vec \n  Require Import pos vec.\n\nFrom Undecidability.FOL.TRAKHTENBROT\n  Require Import notations fol_ops fo_sig fo_terms fo_logic fo_sat.\n\nImport fol_notations.\n\nSet Implicit Arguments.\n\n(* * From binary singleton to n-ary singleton with n >= 2 *)\n\nLocal Notation ø := vec_nil.\n\n(* The reduction could be made to work for (infinite) SAT only *)\n\nSection Sig2_Sig_n_encoding.\n\n  Variable (n : nat).\n\n  Notation Σ2 := (Σrel 2).\n  Notation Σn := (Σrel (S (S n))).\n\n  (* The encoding is trivial here : replace R2(x,y) with Rn(x,y,...,y) *)\n\n  Fixpoint Σ2_Σn (A : fol_form Σ2) : fol_form Σn :=\n    match A with\n      | ⊥              => ⊥\n      | fol_atom   _ v => let x := Σrel_var (vec_head v)            in\n                          let y := Σrel_var (vec_head (vec_tail v)) \n                          in  @fol_atom Σn tt (£x##vec_set_pos (fun _ => £y))\n      | fol_bin b A B  => fol_bin b (Σ2_Σn A) (Σ2_Σn B)\n      | fol_quant q A  => fol_quant q (Σ2_Σn A)\n     end.\n\n  Section correctness.\n\n    Variable (X : Type) (M2 : fo_model Σ2 X) (Mn : fo_model Σn X).\n\n    Notation \"⟪ A ⟫\" := (fun ψ => fol_sem M2 ψ A).\n    Notation \"⟪ A ⟫'\" := (fun φ => fol_sem Mn φ A) (at level 1, format \"⟪ A ⟫'\").\n\n    Let P2 a b := fom_rels M2 tt (a##b##ø).\n    Let Pn a b := fom_rels Mn tt (a##vec_set_pos (fun _ => b)).\n\n    Hypothesis HP : forall x y, P2 x y <-> Pn x y.\n\n    Lemma Σ2_Σn_correct (A : fol_form Σ2) φ : ⟪ A ⟫ φ <-> ⟪Σ2_Σn A⟫' φ.\n    Proof using HP.\n      revert φ.\n      induction A as [ | [] v | b A HA B HB | q A HA ]; intros phi.\n      + simpl; tauto.\n      + vec split v with a; vec split v with b; vec nil v; clear v; revert a b.\n        intros [ a | [] ] [ b | [] ]; unfold Σ2_Σn; simpl; rew fot.\n        rewrite vec_map_set_pos; apply HP.\n      + simpl; apply fol_bin_sem_ext; auto.\n      + simpl; apply fol_quant_sem_ext; intro; auto.\n    Qed.\n\n  End correctness.\n\n  Variable (A : fol_form Σ2).\n\n  Section soundness.\n\n    Variables (X : Type)\n              (M2 : fo_model Σ2 X)\n              (H1 : finite_t X)\n              (H2 : fo_model_dec M2)\n              (phi : nat -> X)\n              (H3 : fol_sem M2 phi A).\n\n    Let Mn : fo_model Σn X.\n    Proof.\n      exists.\n      + intros [].\n      + intros []; simpl.\n        intros v.\n        exact (fom_rels M2 tt (vec_head v##vec_head (vec_tail v)##ø)).\n    Defined.\n \n    Local Lemma Σ2_Σn_sound_loc : fo_form_fin_dec_SAT (Σ2_Σn A).\n    Proof using All.\n      exists X, Mn, H1.\n      exists. { intros [] ?; apply H2. }\n      exists phi.\n      revert H3. \n      apply Σ2_Σn_correct; simpl; tauto.\n    Qed.\n\n  End soundness.\n \n  Lemma Σ2_Σn_soundness : \n        fo_form_fin_dec_SAT A\n     -> fo_form_fin_dec_SAT (Σ2_Σn A).\n  Proof.\n    intros (X & M2 & H1 & H2 & phi & H3).\n    apply Σ2_Σn_sound_loc with (M2 := M2) (phi := phi); auto.\n  Qed.\n\n  Section completeness.\n\n    Variables (X : Type)\n              (Mn : fo_model Σn X)\n              (H1 : finite_t X)\n              (H2 : fo_model_dec Mn)\n              (phi : nat -> X)\n              (H3 : fol_sem Mn phi (Σ2_Σn A)).\n\n    Let M2 : fo_model Σ2 X.\n    Proof.\n      exists.\n      + intros [].\n      + intros []; simpl.\n        intros v.\n        exact (fom_rels Mn tt (vec_head v##vec_set_pos (fun _ => vec_head (vec_tail v)))).\n    Defined.\n \n    Local Lemma Σ2_Σn_complete_loc : fo_form_fin_dec_SAT A.\n    Proof using All.\n      exists X, M2, H1.\n      exists. { intros [] ?; apply H2. }\n      exists phi.\n      revert H3. \n      apply Σ2_Σn_correct; simpl; tauto.\n    Qed.\n\n  End completeness.\n \n  Lemma Σ2_Σn_completeness : \n        fo_form_fin_dec_SAT (Σ2_Σn A)\n     -> fo_form_fin_dec_SAT A.\n  Proof.\n    intros (X & Mn & H1 & H2 & phi & H3).\n    apply Σ2_Σn_complete_loc with (Mn := Mn) (phi := phi); auto.\n  Qed.\n\nEnd Sig2_Sig_n_encoding.\n\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/FOL/TRAKHTENBROT/Sig2_Sign.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642804, "lm_q2_score": 0.7520125793176223, "lm_q1q2_score": 0.670653131030847}}
{"text": "(* Calculation for a language with interrupts (using the same compiler\nand VM as Hutton and Wright). *)\n\nRequire Import List.\nRequire Import Tactics.\n\nRequire Import ZArith.\nLocal Open Scope Z_scope.\n\nInductive Expr : Set := Val (n : Z) | Add (e1 e2 : Expr) | Throw | Catch (e h : Expr) \n                      | Seqn (e1 e2 : Expr) | Block (e : Expr) | Unblock (e : Expr).\n\nReserved Notation \"x ⇓[ i ] y\" (at level 70, no associativity).\nInductive Status : Set := B | U.\n\n\nInductive eval : Expr -> Status -> option Z -> Prop :=\n| eval_val n i : Val n ⇓[i] Some n\n| eval_throw i : Throw ⇓[i] None\n| eval_add1 x y n m i : x ⇓[i] Some n -> y ⇓[i] Some m -> Add x y ⇓[i] Some (n + m)\n| eval_add2 x y i : x ⇓[i] None -> Add x y ⇓[i] None\n| eval_add3 x y n i : x ⇓[i] Some n -> y ⇓[i] None -> Add x y ⇓[i] None\n| eval_seq1 x y n v i : x ⇓[i] Some n -> y ⇓[i] v -> Seqn x y ⇓[i] v\n| eval_seq2  x y i : x ⇓[i] None -> Seqn x y ⇓[i] None\n| eval_catch1 x y n i : x ⇓[i] Some n -> Catch x y ⇓[i] Some n\n| eval_catch2 x y v i : x ⇓[i] None -> y ⇓[i] v -> Catch x y ⇓[i] v\n| eval_block x v i : x ⇓[B] v -> Block x ⇓[i] v\n| eval_unblock x v i : x ⇓[U] v -> Unblock x ⇓[i] v\n| eval_int x : x ⇓[U] None\nwhere \"x ⇓[ i ] y\" := (eval x i y).\n\nHint Constructors eval.\n\nInductive Instr : Set := PUSH (n : Z) | ADD | THROW | UNMARK | MARK (h : list Instr) \n                       | POP | RESET | SET (i : Status).\n\nDefinition Code := list Instr.\n\nImport ListNotations.\n\nFixpoint comp' (e : Expr) (c : Code) : Code :=\n  match e with\n    | Val n => PUSH n :: c\n    | Add x y => comp' x (comp' y (ADD :: c))\n    | Throw => THROW :: c\n    | Catch e1 e2 => MARK (comp' e2 c) :: comp' e1 (UNMARK :: c)\n    | Seqn e1 e2 => comp' e1 (POP :: comp' e2 c)\n    | Block e => SET B :: comp' e (RESET :: c)\n    | Unblock e => SET U :: comp' e (RESET :: c)\n  end.\n\nDefinition comp (e : Expr) : Code := comp' e nil.\n\nInductive Elem : Set := VAL (n : Z) | HAN (c : Code) | INT (s  : Status).\n\nDefinition Stack : Set := list Elem.\n\nInductive Conf : Set := conf (c : Code) (s : Stack) (i : Status)\n                      | fail (s : Stack) (i : Status).\n\nNotation \"⟨ c , s , i ⟩\" := (conf c s i).\nNotation \"⟪ s , i ⟫\" := (fail s i ).\n\nReserved Notation \"x ==> y\" (at level 80, no associativity).\nInductive VM : Conf -> Conf -> Prop :=\n | vm_push n c s i : ⟨PUSH n :: c, s, i⟩ ==> ⟨ c , VAL n :: s, i ⟩ \n | vm_throw c s i : ⟨ THROW :: c, s, i⟩ ==> ⟪s, i⟫ \n | vm_add c s m n i : ⟨ADD :: c, VAL m :: VAL n :: s, i⟩ ==> ⟨c, VAL (n + m) :: s, i⟩ \n | vm_pop c n s i : ⟨POP :: c, VAL n :: s, i⟩ ==> ⟨c, s, i⟩\n | vm_mark h c s i : ⟨MARK h :: c, s, i⟩ ==> ⟨c, HAN h :: s, i⟩ \n | vm_unmark c n h s i : ⟨UNMARK :: c, VAL n :: HAN h :: s, i⟩ ==> ⟨c, VAL n :: s, i⟩ \n | vm_set c s i j : ⟨SET j :: c, s, i⟩ ==> ⟨c, INT i :: s, j⟩\n | vm_reset c s n i j : ⟨RESET :: c, VAL n :: INT i :: s, j⟩ ==> ⟨c, VAL n :: s, i⟩\n\n | vm_fail_val  m s i : ⟪VAL m :: s, i⟫ ==> ⟪s, i⟫\n | vm_fail_han s h i : ⟪HAN h :: s, i⟫ ==> ⟨h,s,i⟩\n | vm_fail_int i j s : ⟪INT i :: s, j⟫ ==> ⟪s,i⟫\n\n | vm_int c op s : ⟨op :: c, s, U⟩ ==> ⟪s, U⟫\nwhere \"x ==> y\" := (VM x y).\n\nHint Constructors VM.\n\n(* Boilerplate to import calculation tactics *)\nModule VM <: Machine.\nDefinition Conf := Conf.\nDefinition Rel := VM.\nEnd VM.\nModule VMCalc := Calculation VM.\nImport VMCalc.\n\nLtac by_eval := eval_inv (eval).\n\nTheorem spec e P c :  { s i, ⟨comp' e c , s, i⟩ | P s i} =|>\n                        { s i n, ⟨c , VAL n :: s, i⟩ | e ⇓[i] Some n /\\ P s i}\n                        ∪ { s i, ⟪s, i⟫ | e ⇓[i] None /\\ P s i}.\nProof.\n  intros.\n  generalize dependent c.\n  generalize dependent P.\n  induction e;intros.\n   \n   begin\n    ({ s i n', ⟨c, VAL n' :: s, i⟩ | Val n ⇓[i] Some n' /\\ P s i} ∪ \n     { s i, ⟪s, i⟫ | Val n ⇓[i] None /\\ P s i }).\n   = {by_eval}\n    ({ s i , ⟨c, VAL n :: s, i⟩ |  P s i} ∪\n     { s , ⟪s, U⟫ | P s U }).\n  <== {apply vm_push}\n    ({ s i, ⟨ PUSH n :: c, s, i⟩ | P s i } ∪\n     { s , ⟪s, U⟫ | P s U }).\n  <== {apply vm_int}\n    ({ s i, ⟨ PUSH n :: c, s, i⟩ | P s i } ∪\n     { s, ⟨ PUSH n :: c, s, U⟩ | P s U }).\n  = {auto}\n    ({ s i, ⟨ PUSH n :: c, s, i⟩ | P s i }).\n  [].\n\n  begin\n    ({s i n, ⟨c, VAL n :: s, i⟩ | Add e1 e2 ⇓[i] Some n /\\ P s i } ∪ \n       { s i , ⟪s, i⟫ | Add e1 e2 ⇓[i] None /\\ P s i }) .\n  = {by_eval}\n  ({s i n m, ⟨c, VAL (n + m) :: s, i⟩ | e1 ⇓[i] Some n /\\ e2 ⇓[i] Some m /\\ P s i} ∪ \n   { s i n , ⟪s, i⟫ | e1 ⇓[i] Some n /\\ e2 ⇓[i] None /\\ P s i } ∪ \n   { s i , ⟪s, i⟫ | e1 ⇓[i] None /\\ P s i }).\n  <== {apply vm_add}\n  ({ s i n m, ⟨ADD :: c, VAL m :: VAL n :: s, i⟩ | e1 ⇓[i] Some n /\\ e2 ⇓[i] Some m /\\ P s i} ∪\n   { s i n , ⟪ s, i ⟫ | e1 ⇓[i] Some n /\\ e2 ⇓[i] None /\\ P s i }\n   ∪ { s i, ⟪s, i⟫ | e1 ⇓[i] None /\\ P s i }).\n  <== {apply vm_fail_val}\n  ({ s i n m, ⟨ADD :: c, VAL m :: VAL n :: s, i⟩ | e1 ⇓[i] Some n /\\ e2 ⇓[i] Some m /\\ P s i} ∪\n   { s i n , ⟪ VAL n :: s, i ⟫ | e1 ⇓[i] Some n /\\ e2 ⇓[i] None /\\ P s i }\n   ∪ { s i, ⟪s, i⟫ | e1 ⇓[i] None /\\ P s i }).\n  = { auto }\n  ({ s' i m, ⟨ADD :: c, VAL m :: s', i⟩ | e2 ⇓[i] Some m /\\ (exists n s, s' = VAL n :: s \n                                                        /\\ e1 ⇓[i] Some n /\\ P s i)} ∪\n   { s' i, ⟪s', i⟫ | e2 ⇓[i] None /\\ (exists n s, s' = VAL n :: s /\\ e1 ⇓[i] Some n /\\ P s i) } ∪ \n   { s i, ⟪s, i⟫ | e1 ⇓[i] None /\\ P s i }).\n  <|= {apply IHe2}\n  ({ s' i, ⟨comp' e2 (ADD :: c), s', i⟩ | (exists n s, s' = VAL n :: s /\\ e1 ⇓[i] Some n /\\ P s i)} \n     ∪ { s i, ⟪s, i⟫ | e1 ⇓[i] None /\\ P s i }).\n  = { auto }\n  ({ s i n, ⟨comp' e2 (ADD :: c), VAL n :: s, i⟩ | e1 ⇓[i] Some n /\\ P s i} \n     ∪ { s i , ⟪s, i⟫ | e1 ⇓[i] None /\\ P s i }).\n  <|= { apply IHe1 }\n  ({ s i, ⟨comp' e1 (comp' e2 (ADD :: c)), s, i⟩ | P s i}).\n  [].\n\n  begin\n    ({s i n, ⟨c, VAL n :: s, i⟩ | Throw ⇓[i] Some n /\\ P s i} ∪ \n    { s i , ⟪s, i⟫ | Throw ⇓[i] None /\\ P s i}).\n  = {by_eval}\n    ({ s i , ⟪s, i⟫ | P s i}).\n  <== {apply vm_throw}\n    ({ s i , ⟨THROW :: c, s, i⟩ | P s i}).\n  [].\n\n  begin\n    ({s i n, ⟨c, VAL n :: s, i⟩ | Catch e1 e2 ⇓[i] Some n /\\ P s i } ∪ \n    { s i , ⟪s, i⟫ | Catch e1 e2 ⇓[i] None /\\ P s i }).\n  = {by_eval}\n    ({s i n, ⟨c, VAL n :: s, i⟩ | e1 ⇓[i] Some n /\\ P s i } ∪ \n    {s i n, ⟨c, VAL n :: s, i⟩ | e1 ⇓[i] None /\\ e2 ⇓[i] Some n /\\ P s i } ∪ \n    { s i , ⟪s, i⟫ | e1 ⇓[i] None /\\ e2 ⇓[i] None /\\ P s i } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  = {auto}\n    ({s i n, ⟨c, VAL n :: s, i⟩ | e1 ⇓[i] Some n /\\ P s i } ∪ \n    ({s i n, ⟨c, VAL n :: s, i⟩ | e2 ⇓[i] Some n /\\ (e1 ⇓[i] None /\\ P s i) } ∪ \n     { s i , ⟪s, i⟫ | e2 ⇓[i] None /\\ (e1 ⇓[i] None /\\ P s i) }) ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  <|= { apply IHe2 }\n    ({s i n, ⟨c, VAL n :: s, i⟩ | e1 ⇓[i] Some n /\\ P s i } ∪ \n    {s i, ⟨comp' e2 c, s, i⟩ | e1 ⇓[i] None /\\ P s i } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  <== { apply vm_fail_han }\n    ({s i n, ⟨c, VAL n :: s, i⟩ | e1 ⇓[i] Some n /\\ P s i } ∪ \n    {s i, ⟪HAN (comp' e2 c) :: s, i⟫ | e1 ⇓[i] None /\\ P s i } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  <== { apply vm_unmark }\n    ({s i n, ⟨UNMARK :: c, VAL n :: HAN (comp' e2 c) :: s, i⟩ | e1 ⇓[i] Some n /\\ P s i } ∪ \n    {s i, ⟪HAN (comp' e2 c) :: s, i⟫ | e1 ⇓[i] None /\\ P s i } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  = { auto }\n    ({s' i n, ⟨UNMARK :: c, VAL n :: s', i⟩ | e1 ⇓[i] Some n /\\ (exists s, s' = HAN (comp' e2 c) :: s /\\ P s i )} ∪ \n    {s' i, ⟪s', i⟫ | e1 ⇓[i] None /\\ (exists s, s' = HAN (comp' e2 c) :: s /\\ P s i ) } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  <|= {apply IHe1}\n    ({s' i, ⟨comp' e1 (UNMARK :: c), s', i⟩ | (exists s, s' = HAN (comp' e2 c) :: s /\\ P s i ) } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  = {auto}\n    ({s i, ⟨comp' e1 (UNMARK :: c), HAN (comp' e2 c) :: s, i⟩ | P s i } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  <== {apply vm_mark}\n    ({s i, ⟨MARK (comp' e2 c) :: comp' e1 (UNMARK :: c), s, i⟩ | P s i } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  <== {apply vm_int}\n    ({s i, ⟨MARK (comp' e2 c) :: comp' e1 (UNMARK :: c), s, i⟩ | P s i } ∪ \n    { s , ⟨MARK (comp' e2 c) :: comp' e1 (UNMARK :: c), s, U⟩ | P s U }).\n  = {auto}\n    ({s i, ⟨MARK (comp' e2 c) :: comp' e1 (UNMARK :: c), s, i⟩ | P s i }).\n  [].\n\n  begin\n    ({s i n, ⟨c, VAL n :: s, i⟩ | Seqn e1 e2 ⇓[i] Some n /\\ P s i } ∪ \n    { s i , ⟪s, i⟫ | Seqn e1 e2 ⇓[i] None /\\ P s i }).\n  = {by_eval}\n    ({s i n, ⟨c, VAL n :: s, i⟩ | e2 ⇓[i] Some n /\\ (exists m, e1 ⇓[i] Some m) /\\ P s i } ∪ \n    {s i, ⟪s, i⟫ | e2 ⇓[i] None /\\ (exists m, e1 ⇓[i] Some m) /\\ P s i } ∪ \n    { s i , ⟪s, i⟫ | e1 ⇓[i] None /\\ P s i }).\n  <|= {apply IHe2}\n    ({s i, ⟨comp' e2 c, s, i⟩ | (exists m, e1 ⇓[i] Some m) /\\ P s i } ∪ \n    { s i , ⟪s, i⟫ | e1 ⇓[i] None /\\ P s i }).\n  = {eauto}\n    ({s i m, ⟨comp' e2 c, s, i⟩ | e1 ⇓[i] Some m /\\ P s i } ∪ \n    { s i , ⟪s, i⟫ | e1 ⇓[i] None /\\ P s i }).\n  <== {apply vm_pop}\n    ({s i m, ⟨POP :: comp' e2 c, VAL m :: s, i⟩ | e1 ⇓[i] Some m /\\ P s i } ∪ \n    { s i , ⟪s, i⟫ | e1 ⇓[i] None /\\ P s i }).\n  <|= {apply IHe1}\n    ({s i, ⟨comp' e1 (POP :: comp' e2 c), s, i⟩ | P s i }).\n  [].\n  \n  begin\n    ({s i n, ⟨c, VAL n :: s, i⟩ | Block e ⇓[i] Some n /\\ P s i } ∪ \n    { s i, ⟪s, i⟫ | Block e ⇓[i] None /\\ P s i }).\n  = {by_eval}\n    ({s i n, ⟨c, VAL n :: s, i⟩ | e ⇓[B] Some n /\\ P s i } ∪ \n    { s i, ⟪s, i⟫ | e ⇓[B] None /\\ P s i } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  <== {apply vm_reset}\n    ({s i n, ⟨RESET :: c, VAL n :: INT i :: s, B⟩ | e ⇓[B] Some n /\\ P s i } ∪ \n    { s i, ⟪s, i⟫ | e ⇓[B] None /\\ P s i } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  <== {apply vm_fail_int}\n    ({s i n, ⟨RESET :: c, VAL n :: INT i :: s, B⟩ | e ⇓[B] Some n /\\ P s i } ∪ \n    { s i, ⟪INT i :: s, B⟫ | e ⇓[B] None /\\ P s i } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  = {auto}\n    ({s' i' n, ⟨RESET :: c, VAL n :: s', i'⟩ | e ⇓[i'] Some n /\\ \n                                             (i' = B /\\ exists s i, s' = INT i :: s /\\ P s i) } ∪ \n    { s' i', ⟪s', i'⟫ | e ⇓[i'] None /\\ (i' = B /\\ exists s i, s' = INT i :: s /\\ P s i) } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  <|= {apply IHe}\n    ({s' i', ⟨comp' e (RESET :: c), s', i'⟩ | i' = B /\\ exists s i, s' = INT i :: s /\\ P s i } ∪\n    { s , ⟪s, U⟫ | P s U }).\n  = {auto}\n    ({s i, ⟨comp' e (RESET :: c), INT i :: s, B⟩ | P s i } ∪\n    { s , ⟪s, U⟫ | P s U }).\n  <== {apply vm_set}\n    ({s i, ⟨SET B :: comp' e (RESET :: c), s, i⟩ | P s i } ∪\n    { s , ⟪s, U⟫ | P s U }).\n  <== {apply vm_int}\n    ({s i, ⟨SET B :: comp' e (RESET :: c), s, i⟩ | P s i } ∪\n    {s, ⟨SET B :: comp' e (RESET :: c), s, U⟩ | P s U }).\n  = {auto}\n    ({s i, ⟨SET B :: comp' e (RESET :: c), s, i⟩ | P s i }).\n  [].\n  \n  begin\n    ({s i n, ⟨c, VAL n :: s, i⟩ | Unblock e ⇓[i] Some n /\\ P s i } ∪ \n    { s i, ⟪s, i⟫ | Unblock e ⇓[i] None /\\ P s i }).\n  = {by_eval}\n    ({s i n, ⟨c, VAL n :: s, i⟩ | e ⇓[U] Some n /\\ P s i } ∪ \n    { s i, ⟪s, i⟫ | e ⇓[U] None /\\ P s i } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  <== {apply vm_reset}\n    ({s i n, ⟨RESET :: c, VAL n :: INT i :: s, U⟩ | e ⇓[U] Some n /\\ P s i } ∪ \n    { s i, ⟪s, i⟫ | e ⇓[U] None /\\ P s i } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  <== {apply vm_fail_int}\n    ({s i n, ⟨RESET :: c, VAL n :: INT i :: s, U⟩ | e ⇓[U] Some n /\\ P s i } ∪ \n    { s i, ⟪INT i :: s, U⟫ | e ⇓[U] None /\\ P s i } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  = {auto}\n    ({s' i' n, ⟨RESET :: c, VAL n :: s', i'⟩ | e ⇓[i'] Some n /\\ \n                                             (i' = U /\\ exists s i, s' = INT i :: s /\\ P s i) } ∪ \n    { s' i', ⟪s', i'⟫ | e ⇓[i'] None /\\ (i' = U /\\ exists s i, s' = INT i :: s /\\ P s i) } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  <|= {apply IHe}\n    ({s' i', ⟨comp' e (RESET :: c), s', i'⟩ | i' = U /\\ exists s i, s' = INT i :: s /\\ P s i } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  = {auto}\n    ({s i, ⟨comp' e (RESET :: c), INT i :: s, U⟩ | P s i } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  <== {apply vm_set}\n    ({s i, ⟨SET U :: comp' e (RESET :: c), s, i⟩ | P s i } ∪ \n    { s , ⟪s, U⟫ | P s U }).\n  <== {apply vm_int}\n    ({s i, ⟨SET U :: comp' e (RESET :: c), s, i⟩ | P s i } ∪ \n    { s , ⟨SET U :: comp' e (RESET :: c), s, U⟩ | P s U }).\n  = {auto}\n    ({s i, ⟨SET U :: comp' e (RESET :: c), s, i⟩ | P s i }).\n  [].\nQed.\n", "meta": {"author": "pa-ba", "repo": "calc-comp-rel", "sha": "2ffe6e4601e15ec926e1953dc5bf8793d37397aa", "save_path": "github-repos/coq/pa-ba-calc-comp-rel", "path": "github-repos/coq/pa-ba-calc-comp-rel/calc-comp-rel-2ffe6e4601e15ec926e1953dc5bf8793d37397aa/HuttonWright.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6706531146306631}}
{"text": "Require Import Rbase Ranalysis.\nRequire Import Rinterval Rfunctions Rfunction_def Rfunction_facts.\nRequire Import Ranalysis_def Ranalysis_def_simpl.\nRequire Import MyRIneq MyR_dist Lra.\n\nRequire Import Ass_handling.\n\nLocal Open Scope R_scope.\n\n(** stricly_whatever implies whatever *)\n\nLemma strictly_increasing_in_increasing_in : forall D f,\n  strictly_increasing_in D f -> increasing_in D f.\nProof.\nintros D f f_incr x y Dx Dy [Hlt | Heq].\n left ; apply f_incr ; assumption.\n subst ; reflexivity.\nQed.\n\nLemma strictly_decreasing_in_decreasing_in : forall D f,\n  strictly_decreasing_in D f -> decreasing_in D f.\nProof.\nintros D f f_decr x y Dx Dy [Hlt | Heq].\n left ; apply f_decr ; assumption.\n subst ; reflexivity.\nQed.\n\nLemma strictly_monotonous_in_monotonous_in : forall D f,\n strictly_monotonous_in D f -> monotonous_in D f.\nProof.\nintros D f [Hd | Hi] ;\n [left ; apply strictly_decreasing_in_decreasing_in |\n right ; apply strictly_increasing_in_increasing_in] ; assumption.\nQed.\n\nLemma strictly_increasing_increasing f : strictly_increasing f -> increasing f.\nProof.\n  apply strictly_increasing_in_increasing_in.\nQed.\n\nLemma strictly_decreasing_decreasing f : strictly_decreasing f -> decreasing f.\nProof.\n  apply strictly_decreasing_in_decreasing_in.\nQed.\n\nLemma strictly_monotonous_monotonous f : strictly_monotonous f -> monotonous f.\nProof.\n  apply strictly_monotonous_in_monotonous_in.\nQed.\n\n(** Strict monotonicity implies injectivity *)\n\nLemma strictly_increasing_in_injective_in : forall D f,\n  strictly_increasing_in D f -> injective_in D f.\nProof.\nintros D f f_inc x y x_in y_in feq ; destruct (Rtotal_order x y) as [Hlt | [Heq | Hgt]].\n destruct (Rlt_irrefl (f y)) ; apply Rle_lt_trans with (f x).\n  rewrite feq ; reflexivity.\n  apply f_inc ; assumption.\n assumption.\n destruct (Rlt_irrefl (f x)) ; apply Rle_lt_trans with (f y).\n  rewrite feq ; reflexivity.\n  apply f_inc ; assumption.\nQed.\n\nLemma strictly_decreasing_in_injective_in : forall D f,\n  strictly_decreasing_in D f -> injective_in D f.\nProof.\nintros D f f_dec x y x_in y_in feq ; destruct (Rtotal_order x y) as [Hlt | [Heq | Hgt]].\n destruct (Rlt_irrefl (f x)) ; apply Rle_lt_trans with (f y).\n  rewrite feq ; reflexivity.\n  apply f_dec ; assumption.\n assumption.\n destruct (Rlt_irrefl (f y)) ; apply Rle_lt_trans with (f x).\n  rewrite feq ; reflexivity.\n  apply f_dec ; assumption.\nQed.\n\nLemma strictly_monotonous_in_injective_in : forall D f,\n  strictly_monotonous_in D f -> injective_in D f.\nProof.\nintros D f [f_dec | f_inc] ;\n [apply strictly_decreasing_in_injective_in |\n  apply strictly_increasing_in_injective_in] ; assumption.\nQed.\n\nLemma strictly_increasing_injective f : strictly_increasing f -> injective f.\nProof.\n  apply strictly_increasing_in_injective_in.\nQed.\n\nLemma strictly_decreasing_injective f : strictly_decreasing f -> injective f.\nProof.\n  apply strictly_decreasing_in_injective_in.\nQed.\n\nLemma strictly_monotonous_injective f : strictly_monotonous f -> injective f.\nProof.\n  apply strictly_monotonous_in_injective_in.\nQed.\n\n(** It also helps simplify Rmin / Rmax statements *)\n\nLemma increasing_in_Rmin_simpl :\n  forall D f, increasing_in D f ->\n  forall x y, D x -> D y -> x <= y -> Rmin (f x) (f y) = f x.\nProof.\nintros D f f_inc x y Dx Dy Hxy ;\n assert (flb_lt_fub : f x <= f y) by (apply f_inc ; assumption) ;\n unfold Rmin ; destruct (Rle_dec (f x) (f y)) ; intuition.\nQed.\n\nLemma increasing_in_Rmax_simpl :\n  forall D f, increasing_in D f ->\n  forall x y, D x -> D y -> x <= y -> Rmax (f x) (f y) = f y.\nProof.\nintros D f f_inc x y Dx Dy Hxy ;\n assert (flb_lt_fub : f x <= f y) by (apply f_inc ; assumption) ;\n unfold Rmax ; destruct (Rle_dec (f x) (f y)) ; intuition.\nQed.\n\nLemma decreasing_in_Rmin_simpl :\n  forall D f, decreasing_in D f ->\n  forall x y, D x -> D y -> x <= y -> Rmin (f x) (f y) = f y.\nProof.\nintros D f f_dec x y Dx Dy Hxy ;\n assert (flb_lt_fub : f y <= f x) by (apply f_dec ; assumption) ;\n unfold Rmin ; destruct (Rle_dec (f x) (f y)) ; intuition.\nQed.\n\nLemma decreasing_in_Rmax_simpl :\n  forall D f, decreasing_in D f ->\n  forall x y, D x -> D y -> x <= y -> Rmax (f x) (f y) = f x.\nProof.\nintros D f f_dec x y Dx Dy Hxy ;\n assert (flb_lt_fub : f y <= f x) by (apply f_dec ; assumption) ;\n unfold Rmax ; destruct (Rle_dec (f x) (f y)) ; intuition.\nQed.\n\n(** Image of an interval throught a monotonous function *)\n\nLemma increasing_interval_image : forall f lb ub x,\n  increasing_interval lb ub f -> interval lb ub x ->\n  interval (f lb) (f ub) (f x).\nProof.\nintros f lb ub x Hf x_in ; assert (lb_le_ub : lb <= ub) by\n (eapply interval_inhabited ; eassumption) ; split ; apply Hf.\n apply interval_l ; assumption.\n assumption.\n apply x_in.\n assumption.\n apply interval_r ; assumption.\n apply x_in.\nQed. \n\nLemma decreasing_interval_image : forall f lb ub x,\n  decreasing_interval lb ub f -> interval lb ub x ->\n  interval (f ub) (f lb) (f x).\nProof.\nintros f lb ub x Hf x_in ; assert (lb_le_ub : lb <= ub) by\n (eapply interval_inhabited ; eassumption) ; split ; apply Hf.\n assumption.\n apply interval_r ; assumption.\n apply x_in.\n apply interval_l ; assumption.\n assumption.\n apply x_in.\nQed.\n\nLemma monotonous_interval_image : forall f lb ub x,\n  monotonous_interval lb ub f -> interval lb ub x ->\n  interval (Rmin (f lb) (f ub)) (Rmax (f lb) (f ub)) (f x).\nProof.\nintros f lb ub x [f_dec | f_inc] x_in ;\n assert (lbub : lb <= ub) by (eapply interval_inhabited, x_in).\n erewrite decreasing_in_Rmax_simpl, decreasing_in_Rmin_simpl ; try eassumption.\n  apply decreasing_interval_image ; assumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\n erewrite increasing_in_Rmax_simpl, increasing_in_Rmin_simpl ; try eassumption.\n  apply increasing_interval_image ; assumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\nQed.\n\nLemma strictly_increasing_interval_image : forall f lb ub x,\n  strictly_increasing_interval lb ub f -> open_interval lb ub x ->\n  open_interval (f lb) (f ub) (f x).\nProof.\nintros f lb ub x Hf x_in ; assert (lb_le_ub : lb <= ub) by\n (left ; eapply open_interval_inhabited ; eassumption) ; split ; apply Hf.\n apply interval_l ; assumption.\n apply open_interval_interval ; assumption.\n apply x_in.\n apply open_interval_interval ; assumption.\n apply interval_r ; assumption.\n apply x_in.\nQed. \n\nLemma strictly_decreasing_interval_image : forall f lb ub x,\n  strictly_decreasing_interval lb ub f -> open_interval lb ub x ->\n  open_interval (f ub) (f lb) (f x).\nProof.\nintros f lb ub x Hf x_in ; assert (lb_le_ub : lb <= ub) by\n (left ; eapply open_interval_inhabited ; eassumption) ; split ; apply Hf.\n apply open_interval_interval ; assumption.\n apply interval_r ; assumption.\n apply x_in.\n apply interval_l ; assumption.\n apply open_interval_interval ; assumption.\n apply x_in.\nQed.\n\nLemma strictly_monotonous_interval_image : forall f lb ub x,\n  strictly_monotonous_interval lb ub f -> open_interval lb ub x ->\n  open_interval (Rmin (f lb) (f ub)) (Rmax (f lb) (f ub)) (f x).\nProof.\nintros f lb ub x [f_dec | f_inc] x_in ;\n assert (lbub : lb <= ub) by (left ; eapply open_interval_inhabited, x_in).\n erewrite decreasing_in_Rmax_simpl, decreasing_in_Rmin_simpl.\n  apply strictly_decreasing_interval_image ; assumption.\n  apply strictly_decreasing_in_decreasing_in ; eassumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\n  assumption.\n  apply strictly_decreasing_in_decreasing_in ; eassumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\n  assumption.\n erewrite increasing_in_Rmax_simpl, increasing_in_Rmin_simpl.\n  apply strictly_increasing_interval_image ; assumption.\n  apply strictly_increasing_in_increasing_in ; eassumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\n  assumption.\n  apply strictly_increasing_in_increasing_in ; eassumption.\n  apply interval_l ; assumption.\n  apply interval_r ; assumption.\n  assumption.\nQed.\n\n(** Compatibility of variations with operations *)\n\nLemma increasing_in_opp : forall D f,\n  increasing_in D f -> decreasing_in D (-f)%F.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_le_contravar, Hf ; assumption.\nQed.\n\nLemma increasing_in_opp_rev : forall D f,\n  increasing_in D (- f)%F -> decreasing_in D f.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_le_cancel, Hf ; assumption.\nQed.\n\nLemma strictly_increasing_in_opp : forall D f,\n  strictly_increasing_in D f -> strictly_decreasing_in D (-f)%F.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_lt_contravar, Hf ; assumption.\nQed.\n\nLemma strictly_increasing_in_opp_rev : forall D f,\n  strictly_increasing_in D (- f)%F -> strictly_decreasing_in D f.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_lt_cancel, Hf ; assumption.\nQed.\n\nLemma decreasing_in_opp : forall D f,\n  decreasing_in D f -> increasing_in D (-f)%F.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_le_contravar, Hf ; assumption.\nQed.\n\nLemma decreasing_in_opp_rev : forall D f,\n  decreasing_in D (- f)%F -> increasing_in D f.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_le_cancel, Hf ; assumption.\nQed.\n\nLemma strictly_decreasing_in_opp : forall D f,\n  strictly_decreasing_in D f -> strictly_increasing_in D (-f)%F.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_lt_contravar, Hf ; assumption.\nQed.\n\nLemma strictly_decreasing_in_opp_rev : forall D f,\n  strictly_decreasing_in D (- f)%F -> strictly_increasing_in D f.\nProof.\nintros D f Hf x y Dx Dy Hxy ; unfold opp_fct ;\n apply Ropp_lt_cancel, Hf ; assumption.\nQed.\n\n(* TODO: more generic lemmas like these ones *)\n\nLemma increasing_in_plus : forall D f g,\n  increasing_in D f -> increasing_in D g -> increasing_in D (f + g)%F.\nProof.\nintros D f g Hf Hg x y Dx Dy Hxy ; unfold plus_fct ;\n apply Rplus_le_compat ; [apply Hf | apply Hg] ; assumption.\nQed.\n\nLemma increasing_in_minus : forall D f g,\n  increasing_in D f -> decreasing_in D g -> increasing_in D (f - g)%F.\nProof.\nintros D f g Hf Hg x y Dx Dy Hxy ; unfold plus_fct ;\n apply Rplus_le_compat ; [apply Hf | apply Ropp_le_contravar, Hg] ; assumption.\nQed.\n\n\nLemma strictly_increasing_strictly_decreasing_interval2 : forall f lb ub,\n  strictly_increasing_interval lb ub f ->\n  strictly_decreasing_interval (- ub) (- lb) (fun x => f(-x)).\nProof.\nintros f c r f_incr ; intros x y x_in_B y_in_B x_lt_y.\n apply f_incr ; unfold interval in * ; try split ; intuition ; lra.\nQed.\n\nLemma strictly_decreasing_strictly_increasing_interval2 : forall f lb ub,\n  strictly_decreasing_interval lb ub f ->\n  strictly_increasing_interval (-ub) (-lb) (fun x => f(-x)).\nProof.\nintros f c r f_decr ; intros x y x_in_B y_in_B x_lt_y.\n apply f_decr ; unfold interval in * ; try split ; intuition ; lra.\nQed.\n\nLemma strictly_increasing_reciprocal_interval_compat : forall f g lb ub,\n  strictly_increasing_interval lb ub f ->\n  reciprocal_interval (f lb) (f ub) f g ->\n  (forall x, interval (f lb) (f ub) x -> interval lb ub (g x)) ->\n  strictly_increasing_interval (f lb) (f ub) g.\nProof.\nintros f g lb ub f_incr f_recip_g g_ok x y x_in_I y_in_I x_lt_y.\n destruct (Rlt_le_dec (g x) (g y)) as [T | F].\n  assumption.\n  destruct F as [F | F].\n   assert (Hf : y < x).\n    unfold reciprocal_interval, id in f_recip_g ; rewrite <- f_recip_g.\n    apply Rgt_lt ; rewrite <- f_recip_g.\n    unfold comp ; apply f_incr ; [apply g_ok | apply g_ok |] ; assumption.\n    assumption.\n    assumption.\n   apply False_ind ; apply Rlt_irrefl with x ; apply Rlt_trans with y ; assumption.\n   assert (Hf : x = y).\n    unfold reciprocal_interval, id in f_recip_g ; rewrite <- f_recip_g.\n    symmetry ; rewrite <- f_recip_g.\n    unfold comp ; rewrite F ; reflexivity.\n    assumption.\n    assumption.\n   rewrite Hf in x_lt_y ; elim (Rlt_irrefl _ x_lt_y).\nQed.\n\nLemma strictly_increasing_reciprocal_interval_comm: forall f g lb ub,\n  (forall x, interval (f lb) (f ub) x -> interval lb ub (g x)) ->\n  strictly_increasing_interval lb ub f ->\n  reciprocal_interval (f lb) (f ub) f g ->\n  reciprocal_interval lb ub g f.\nProof.\nintros f g lb ub g_ok f_sinc Hfg x x_in ;\n assert (f_inc : increasing_interval lb ub f).\n  apply strictly_increasing_in_increasing_in ; assumption.\n destruct (Req_dec (g (f x)) x) as [Heq | Hneq].\n  assumption.\n  destruct (Rlt_irrefl (f x)).\n  destruct (Rdichotomy _ _ Hneq) as [Hlt | Hlt].\n  apply Rle_lt_trans with (f (g (f x))).\n   right ; rewrite Hfg.\n    reflexivity.\n    apply increasing_interval_image ; [apply strictly_increasing_in_increasing_in |] ; assumption.\n   apply f_sinc ; [apply g_ok, increasing_interval_image | |] ; assumption.\n  apply Rlt_le_trans with (f (g (f x))).\n   apply f_sinc ; [| apply g_ok, increasing_interval_image |] ; assumption.\n  right ; rewrite Hfg.\n   reflexivity.\n   apply increasing_interval_image ; assumption.\nQed.\n\nLemma strictly_decreasing_reciprocal_interval_comm: forall f g lb ub,\n  (forall x, interval (f ub) (f lb) x -> interval lb ub (g x)) ->\n  strictly_decreasing_interval lb ub f ->\n  reciprocal_interval (f ub) (f lb) f g ->\n  reciprocal_interval lb ub g f.\nProof.\nintros f g lb ub g_ok f_sdec Hfg x x_in ;\n assert (f_dec : decreasing_interval lb ub f).\n  apply strictly_decreasing_in_decreasing_in ; assumption.\n destruct (Req_dec (g (f x)) x) as [Heq | Hneq].\n  assumption.\n  destruct (Rlt_irrefl (f x)).\n  destruct (Rdichotomy _ _ Hneq) as [Hlt | Hlt].\n  apply Rlt_le_trans with (f (g (f x))).\n   apply f_sdec ; [apply g_ok, decreasing_interval_image | |] ; assumption.\n  right ; rewrite Hfg.\n   reflexivity.\n   apply decreasing_interval_image ; assumption.\n  apply Rle_lt_trans with (f (g (f x))).\n   right ; rewrite Hfg.\n    reflexivity.\n    apply decreasing_interval_image ; assumption.\n   apply f_sdec ; [| apply g_ok, decreasing_interval_image |] ; assumption.\nQed.\n\n(** Knowing f's variations and the ordering of f a and f b we can deduce a and b's ordering *)\n\nLemma strictly_increasing_open_interval_order : forall f lb ub a b,\n  open_interval lb ub a -> open_interval lb ub b ->\n  strictly_increasing_open_interval lb ub f ->\n  f a < f b -> a < b.\nProof.\nintros f lb ub a b a_in b_in Hf Hfafb ; destruct (Rlt_le_dec a b) as [altb | blea].\n assumption.\n destruct blea as [blta | beqa].\n  destruct (Rlt_irrefl (f a)) ; transitivity (f b).\n   assumption.\n   apply Hf ; assumption.\n  rewrite beqa in Hfafb ; destruct (Rlt_irrefl _ Hfafb).\nQed.\n\nLemma strictly_increasing_interval_order : forall f lb ub a b,\n  open_interval lb ub a -> open_interval lb ub b ->\n  strictly_increasing_open_interval lb ub f ->\n  f a <= f b -> a <= b.\nProof.\nintros f lb ub a b a_in b_in Hf Hfafb ; destruct (Rle_lt_dec a b) as [aleb | blta].\n assumption.\n destruct (Rlt_irrefl (f a)) ; apply Rle_lt_trans with (f b).\n  assumption.\n  apply Hf ; assumption.\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/Reals/Ranalysis/Ranalysis_monotonicity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6705983149721616}}
{"text": "\nRequire Import Arith.\nRequire Export Compare_dec.\nRequire Export Relations.\n\nHint Resolve t_step rt_step rt_refl: core.\nHint Unfold transp: core.\n\nSection Termes.\n\n  Inductive sort : Set :=\n    | kind : sort\n    | prop : sort.\n\n  Inductive term : Set :=\n    | Srt : sort -> term\n    | Ref : nat -> term\n    | Abs : term -> term -> term\n    | App : term -> term -> term\n    | Prod : term -> term -> term.\n\n  Fixpoint lift_rec (n : nat) (t : term) (k : nat) {struct t} : term :=\n    match t with\n    | Srt s => Srt s\n    | Ref i =>\n        match le_gt_dec k i with\n        | left _ => Ref (n + i)\n        | right _ => Ref i\n        end\n    | Abs T M => Abs (lift_rec n T k) (lift_rec n M (S k))\n    | App u v => App (lift_rec n u k) (lift_rec n v k)\n    | Prod A B => Prod (lift_rec n A k) (lift_rec n B (S k))\n    end.\n\n  Definition lift n t := lift_rec n t 0.\n\n  Fixpoint subst_rec (N M : term) (k : nat) {struct M} : term :=\n    match M with\n    | Srt s => Srt s\n    | Ref i =>\n        match lt_eq_lt_dec k i with\n        | inleft (left _) => Ref (pred i)\n        | inleft (right _) => lift k N\n        | inright _ => Ref i\n        end\n    | Abs A B => Abs (subst_rec N A k) (subst_rec N B (S k))\n    | App u v => App (subst_rec N u k) (subst_rec N v k)\n    | Prod T U => Prod (subst_rec N T k) (subst_rec N U (S k))\n    end.\n\n  Definition subst N M := subst_rec N M 0.\n\n\n  Inductive subterm : term -> term -> Prop :=\n    | sbtrm_abs_l : forall A B, subterm A (Abs A B)\n    | sbtrm_abs_r : forall A B, subterm B (Abs A B)\n    | sbtrm_app_l : forall A B, subterm A (App A B)\n    | sbtrm_app_r : forall A B, subterm B (App A B)\n    | sbtrm_prod_l : forall A B, subterm A (Prod A B)\n    | sbtrm_prod_r : forall A B, subterm B (Prod A B).\n\n  Inductive mem_sort (s : sort) : term -> Prop :=\n    | mem_eq : mem_sort s (Srt s)\n    | mem_prod_l : forall u v, mem_sort s u -> mem_sort s (Prod u v)\n    | mem_prod_r : forall u v, mem_sort s v -> mem_sort s (Prod u v)\n    | mem_abs_l : forall u v, mem_sort s u -> mem_sort s (Abs u v)\n    | mem_abs_r : forall u v, mem_sort s v -> mem_sort s (Abs u v)\n    | mem_app_l : forall u v, mem_sort s u -> mem_sort s (App u v)\n    | mem_app_r : forall u v, mem_sort s v -> mem_sort s (App u v).\n\nEnd Termes.\n\n  Hint Constructors subterm.\n  Hint Constructors mem_sort.\n\n\nSection Beta_Reduction.\n\n  Inductive red1 : term -> term -> Prop :=\n    | beta : forall M N T, red1 (App (Abs T M) N) (subst N M)\n    | abs_red_l :\n        forall M M', red1 M M' -> forall N, red1 (Abs M N) (Abs M' N)\n    | abs_red_r :\n        forall M M', red1 M M' -> forall N, red1 (Abs N M) (Abs N M')\n    | app_red_l :\n        forall M1 N1, red1 M1 N1 -> forall M2, red1 (App M1 M2) (App N1 M2)\n    | app_red_r :\n        forall M2 N2, red1 M2 N2 -> forall M1, red1 (App M1 M2) (App M1 N2)\n    | prod_red_l :\n        forall M1 N1, red1 M1 N1 -> forall M2, red1 (Prod M1 M2) (Prod N1 M2)\n    | prod_red_r :\n        forall M2 N2, red1 M2 N2 -> forall M1, red1 (Prod M1 M2) (Prod M1 N2).\n\n  Inductive red (M : term) : term -> Prop :=\n    | refl_red : red M M\n    | trans_red : forall P N, red M P -> red1 P N -> red M N.\n\n  Inductive conv (M : term) : term -> Prop :=\n    | refl_conv : conv M M\n    | trans_conv_red : forall P N, conv M P -> red1 P N -> conv M N\n    | trans_conv_exp : forall P N, conv M P -> red1 N P -> conv M N.\n\n  Inductive par_red1 : term -> term -> Prop :=\n    | par_beta :\n        forall M M' N N' T,\n        par_red1 M M' ->\n        par_red1 N N' -> par_red1 (App (Abs T M) N) (subst N' M')\n    | sort_par_red : forall s, par_red1 (Srt s) (Srt s)\n    | ref_par_red : forall n, par_red1 (Ref n) (Ref n)\n    | abs_par_red :\n        forall M M' T T',\n        par_red1 M M' -> par_red1 T T' -> par_red1 (Abs T M) (Abs T' M')\n    | app_par_red :\n        forall M M' N N',\n        par_red1 M M' -> par_red1 N N' -> par_red1 (App M N) (App M' N')\n    | prod_par_red :\n        forall M M' N N',\n        par_red1 M M' -> par_red1 N N' -> par_red1 (Prod M N) (Prod M' N').\n\n  Definition par_red := clos_trans term par_red1.\n\nEnd Beta_Reduction.\n\n\n  Hint Constructors red1: coc.\n  Hint Constructors par_red1: coc.\n  Hint Resolve refl_red refl_conv: coc.\n  Hint Unfold par_red: coc.\n\n\nSection Normalisation_Forte.\n\n  Definition normal t := forall u, ~ red1 t u.\n\n  Definition sn := Acc (transp _ red1).\n\nEnd Normalisation_Forte.\n\n  Hint Unfold sn: coc.\n\n  Lemma eqterm : forall u v : term, {u = v} + {u <> v}.\nProof.\ndecide equality.\ndecide equality.\n\napply eq_nat_dec.\nQed.\n\n  Lemma inv_lift_sort :  forall s n t k, lift_rec n t k = Srt s -> t = Srt s.\nintros.\ndestruct t; try  discriminate H.\n auto.\n unfold lift_rec in H.\n   destruct (le_gt_dec k n0);  discriminate H.\nQed.\n\n  Lemma inv_subst_sort :\n    forall s x t k, subst_rec x t k = Srt s -> t = Srt s \\/ x = Srt s.\nintros.\ndestruct t; try  discriminate H.\n auto.\n unfold subst_rec in H.\n   destruct (lt_eq_lt_dec k n) as [[fv| eqv]| bv]; try  discriminate H.\n   right.\n   unfold lift in H.\n   apply inv_lift_sort with (1 := H).\nQed.\n\n\n  Lemma lift_ref_ge :\n   forall k n p, p <= n -> lift_rec k (Ref n) p = Ref (k + n).\nintros; simpl in |- *.\nelim (le_gt_dec p n); auto with arith.\nintro; absurd (p <= n); auto with arith.\nQed.\n\n\n  Lemma lift_ref_lt : forall k n p, p > n -> lift_rec k (Ref n) p = Ref n.\nintros; simpl in |- *.\nelim (le_gt_dec p n); auto with arith.\nintro; absurd (p <= n); auto with arith.\nQed.\n\n\n  Lemma subst_ref_lt : forall u n k, k > n -> subst_rec u (Ref n) k = Ref n.\nsimpl in |- *; intros.\nelim (lt_eq_lt_dec k n); intros; auto with arith.\nelim a; intros.\nabsurd (k <= n); auto with arith.\n\ninversion_clear b in H.\nelim gt_irrefl with n; auto with arith.\nQed.\n\n\n  Lemma subst_ref_gt :\n   forall u n k, n > k -> subst_rec u (Ref n) k = Ref (pred n).\nsimpl in |- *; intros.\nelim (lt_eq_lt_dec k n); intros.\nelim a; intros; auto with arith.\ninversion_clear b in H.\nelim gt_irrefl with n; auto with arith.\n\nabsurd (k <= n); auto with arith.\nQed.\n\n\n  Lemma subst_ref_eq : forall u n, subst_rec u (Ref n) n = lift n u.\nintros; simpl in |- *.\nelim (lt_eq_lt_dec n n); intros.\nelim a; intros; auto with coc.\nelim lt_irrefl with n; auto with coc.\n\nelim gt_irrefl with n; auto with coc.\nQed.\n\n\n\n  Lemma lift_rec0 : forall M k, lift_rec 0 M k = M.\nsimple induction M; simpl in |- *; intros; auto with coc.\nelim (le_gt_dec k n); auto with coc.\n\nrewrite H; rewrite H0; auto with coc.\n\nrewrite H; rewrite H0; auto with coc.\n\nrewrite H; rewrite H0; auto with coc.\nQed.\n\n\n  Lemma lift0 : forall M, lift 0 M = M.\nintros; unfold lift in |- *.\napply lift_rec0; auto with coc.\nQed.\n\n\n  Lemma simpl_lift_rec :\n   forall M n k p i,\n   i <= k + n ->\n   k <= i -> lift_rec p (lift_rec n M k) i = lift_rec (p + n) M k.\nsimple induction M; simpl in |- *; intros; auto with coc.\nelim (le_gt_dec k n); intros.\nrewrite lift_ref_ge; auto with coc.\nrewrite plus_assoc; auto with coc.\n\nrewrite plus_comm.\napply le_trans with (k + n0); auto with arith.\n\nrewrite lift_ref_lt; auto with arith.\napply le_gt_trans with k; auto with arith.\n\nrewrite H; auto with arith; rewrite H0; simpl in |- *; auto with arith.\n\nrewrite H; auto with arith; rewrite H0; simpl in |- *; auto with arith.\n\nrewrite H; auto with arith; rewrite H0; simpl in |- *; auto with arith.\nQed.\n\n\n  Lemma simpl_lift : forall M n, lift (S n) M = lift 1 (lift n M).\nintros; unfold lift in |- *.\nrewrite simpl_lift_rec; auto with arith.\nQed.\n\n\n  Lemma permute_lift_rec :\n   forall M n k p i,\n   i <= k ->\n   lift_rec p (lift_rec n M k) i = lift_rec n (lift_rec p M i) (p + k).\nsimple induction M; simpl in |- *; intros; auto with coc.\nelim (le_gt_dec k n); elim (le_gt_dec i n); intros.\nrewrite lift_ref_ge; auto with arith.\nrewrite lift_ref_ge; auto with arith.\nelim plus_assoc_reverse with p n0 n.\nelim plus_assoc_reverse with n0 p n.\nelim plus_comm with p n0; auto with arith.\n\napply le_trans with n; auto with arith.\n\nabsurd (i <= n); auto with arith.\napply le_trans with k; auto with arith.\n\nrewrite lift_ref_ge; auto with arith.\nrewrite lift_ref_lt; auto with arith.\n\nrewrite lift_ref_lt; auto with arith.\nrewrite lift_ref_lt; auto with arith.\napply le_gt_trans with k; auto with arith.\n\nrewrite H; auto with arith; rewrite H0; auto with arith.\nrewrite plus_n_Sm; auto with arith.\n\nrewrite H; auto with arith; rewrite H0; auto with arith.\n\nrewrite H; auto with arith; rewrite H0; auto with arith.\nrewrite plus_n_Sm; auto with arith.\nQed.\n\n\n  Lemma permute_lift :\n   forall M k, lift 1 (lift_rec 1 M k) = lift_rec 1 (lift 1 M) (S k).\nintros.\nchange (lift_rec 1 (lift_rec 1 M k) 0 = lift_rec 1 (lift_rec 1 M 0) (1 + k))\n in |- *.\napply permute_lift_rec; auto with arith.\nQed.\n\n\n  Lemma simpl_subst_rec :\n   forall N M n p k,\n   p <= n + k ->\n   k <= p -> subst_rec N (lift_rec (S n) M k) p = lift_rec n M k.\nsimple induction M; simpl in |- *; intros; auto with arith.\nelim (le_gt_dec k n); intros.\nrewrite subst_ref_gt; auto with arith.\nred in |- *; red in |- *.\napply le_trans with (S (n0 + k)); auto with arith.\n\nrewrite subst_ref_lt; auto with arith.\napply le_gt_trans with k; auto with arith.\n\nrewrite H; auto with arith; rewrite H0; auto with arith.\nelim plus_n_Sm with n k; auto with arith.\n\nrewrite H; auto with arith; rewrite H0; auto with arith.\n\nrewrite H; auto with arith; rewrite H0; auto with arith.\nelim plus_n_Sm with n k; auto with arith.\nQed.\n\n\n  Lemma simpl_subst :\n   forall N M n p, p <= n -> subst_rec N (lift (S n) M) p = lift n M.\nintros; unfold lift in |- *.\napply simpl_subst_rec; auto with arith.\nQed.\n\n\n  Lemma commut_lift_subst_rec :\n   forall M N n p k,\n   k <= p ->\n   lift_rec n (subst_rec N M p) k = subst_rec N (lift_rec n M k) (n + p).\nsimple induction M; intros; auto with arith.\nunfold subst_rec at 1, lift_rec at 2 in |- *.\nelim (lt_eq_lt_dec p n); elim (le_gt_dec k n); intros.\nelim a0.\ncase n; intros.\ninversion_clear a1.\n\nunfold pred in |- *.\nrewrite lift_ref_ge; auto with arith.\nrewrite subst_ref_gt; auto with arith.\nelim plus_n_Sm with n0 n1.\nauto with arith.\n\napply le_trans with p; auto with arith.\n\nsimple induction 1.\nrewrite subst_ref_eq.\nunfold lift in |- *.\nrewrite simpl_lift_rec; auto with arith.\n\nabsurd (k <= n); auto with arith.\napply le_trans with p; auto with arith.\nelim a; auto with arith.\nsimple induction 1; auto with arith.\n\nrewrite lift_ref_ge; auto with arith.\nrewrite subst_ref_lt; auto with arith.\n\nrewrite lift_ref_lt; auto with arith.\nrewrite subst_ref_lt; auto with arith.\napply le_gt_trans with p; auto with arith.\n\nsimpl in |- *.\nrewrite plus_n_Sm.\nrewrite H; auto with arith; rewrite H0; auto with arith.\n\nsimpl in |- *; rewrite H; auto with arith; rewrite H0; auto with arith.\n\nsimpl in |- *; rewrite plus_n_Sm.\nrewrite H; auto with arith; rewrite H0; auto with arith.\nQed.\n\n\n  Lemma commut_lift_subst :\n   forall M N k, subst_rec N (lift 1 M) (S k) = lift 1 (subst_rec N M k).\nintros; unfold lift in |- *.\nrewrite commut_lift_subst_rec; auto with arith.\nQed.\n\n\n  Lemma distr_lift_subst_rec :\n   forall M N n p k,\n   lift_rec n (subst_rec N M p) (p + k) =\n   subst_rec (lift_rec n N k) (lift_rec n M (S (p + k))) p.\nsimple induction M; intros; auto with arith.\nunfold subst_rec at 1 in |- *.\nelim (lt_eq_lt_dec p n); intro.\nelim a.\ncase n; intros.\ninversion_clear a0.\n\nunfold pred, lift_rec at 1 in |- *.\nelim (le_gt_dec (p + k) n1); intro.\nrewrite lift_ref_ge; auto with arith.\nelim plus_n_Sm with n0 n1.\nrewrite subst_ref_gt; auto with arith.\nred in |- *; red in |- *; apply le_n_S.\napply le_trans with (n0 + (p + k)); auto with arith.\napply le_trans with (p + k); auto with arith.\n\nrewrite lift_ref_lt; auto with arith.\nrewrite subst_ref_gt; auto with arith.\n\nsimple induction 1.\nunfold lift in |- *.\nrewrite <- permute_lift_rec; auto with arith.\nrewrite lift_ref_lt; auto with arith.\nrewrite subst_ref_eq; auto with arith.\n\nrewrite lift_ref_lt; auto with arith.\nrewrite lift_ref_lt; auto with arith.\nrewrite subst_ref_lt; auto with arith.\n\nsimpl in |- *; replace (S (p + k)) with (S p + k); auto with arith.\nrewrite H; rewrite H0; auto with arith.\n\nsimpl in |- *; rewrite H; rewrite H0; auto with arith.\n\nsimpl in |- *; replace (S (p + k)) with (S p + k); auto with arith.\nrewrite H; rewrite H0; auto with arith.\nQed.\n\n\n  Lemma distr_lift_subst :\n   forall M N n k,\n   lift_rec n (subst N M) k = subst (lift_rec n N k) (lift_rec n M (S k)).\nintros; unfold subst in |- *.\npattern k at 1 3 in |- *.\nreplace k with (0 + k); auto with arith.\napply distr_lift_subst_rec.\nQed.\n\n\n  Lemma distr_subst_rec :\n   forall M N P n p,\n   subst_rec P (subst_rec N M p) (p + n) =\n   subst_rec (subst_rec P N n) (subst_rec P M (S (p + n))) p.\nsimple induction M; auto with arith; intros.\nunfold subst_rec at 2 in |- *.\nelim (lt_eq_lt_dec p n); intro.\nelim a.\ncase n; intros.\ninversion_clear a0.\n\nunfold pred, subst_rec at 1 in |- *.\nelim (lt_eq_lt_dec (p + n0) n1); intro.\nelim a1.\ncase n1; intros.\ninversion_clear a2.\n\nrewrite subst_ref_gt; auto with arith.\nrewrite subst_ref_gt; auto with arith.\napply gt_le_trans with (p + n0); auto with arith.\n\nsimple induction 1.\nrewrite subst_ref_eq; auto with arith.\nrewrite simpl_subst; auto with arith.\n\nrewrite subst_ref_lt; auto with arith.\nrewrite subst_ref_gt; auto with arith.\n\nsimple induction 1.\nrewrite subst_ref_lt; auto with arith.\nrewrite subst_ref_eq.\nunfold lift in |- *.\nrewrite commut_lift_subst_rec; auto with arith.\n\ndo 3 (rewrite subst_ref_lt; auto with arith).\n\nsimpl in |- *; replace (S (p + n)) with (S p + n); auto with arith.\nrewrite H; auto with arith; rewrite H0; auto with arith.\n\nsimpl in |- *; rewrite H; rewrite H0; auto with arith.\n\nsimpl in |- *; replace (S (p + n)) with (S p + n); auto with arith.\nrewrite H; rewrite H0; auto with arith.\nQed.\n\n\n  Lemma distr_subst :\n   forall P N M k,\n   subst_rec P (subst N M) k = subst (subst_rec P N k) (subst_rec P M (S k)).\nintros; unfold subst in |- *.\npattern k at 1 3 in |- *.\nreplace k with (0 + k); auto with arith.\napply distr_subst_rec.\nQed.\n\n\n\n  Lemma one_step_red : forall M N, red1 M N -> red M N.\nintros.\napply trans_red with M; auto with coc.\nQed.\n\n  Hint Resolve one_step_red: coc.\n\n\n  Lemma red1_red_ind :\n   forall N P,\n   (P:term -> Prop) N ->\n   (forall M R, red1 M R -> red R N -> P R -> P M) ->\n   forall M, red M N -> P M.\ncut\n (forall M N,\n  red M N ->\n  forall P : term -> Prop,\n  P N -> (forall M R, red1 M R -> red R N -> P R -> P M) -> P M).\nintros.\napply (H M N); auto with coc.\n\nsimple induction 1; intros; auto with coc.\napply H1; auto with coc.\napply H4 with N0; auto with coc.\n\nintros.\napply H4 with R; auto with coc.\napply trans_red with P; auto with coc.\nQed.\n\n\n  Lemma trans_red_red : forall M N P, red M N -> red N P -> red M P.\nintros.\ngeneralize H0 M H.\nsimple induction 1; auto with coc.\nintros.\napply trans_red with P0; auto with coc.\nQed.\n \n\n  Lemma red_red_app :\n   forall u u0 v v0, red u u0 -> red v v0 -> red (App u v) (App u0 v0).\nsimple induction 1.\nsimple induction 1; intros; auto with coc.\napply trans_red with (App u P); auto with coc.\n\nintros.\napply trans_red with (App P v0); auto with coc.\nQed.\n\n\n  Lemma red_red_abs :\n   forall u u0 v v0, red u u0 -> red v v0 -> red (Abs u v) (Abs u0 v0).\nsimple induction 1.\nsimple induction 1; intros; auto with coc.\napply trans_red with (Abs u P); auto with coc.\n\nintros.\napply trans_red with (Abs P v0); auto with coc.\nQed.\n\n\n  Lemma red_red_prod :\n   forall u u0 v v0, red u u0 -> red v v0 -> red (Prod u v) (Prod u0 v0).\nsimple induction 1.\nsimple induction 1; intros; auto with coc.\napply trans_red with (Prod u P); auto with coc.\n\nintros.\napply trans_red with (Prod P v0); auto with coc.\nQed.\n\n  Hint Resolve red_red_app red_red_abs red_red_prod: coc.\n\n\n\n  Lemma red1_lift :\n   forall n u v, red1 u v -> forall k, red1 (lift_rec n u k) (lift_rec n v k).\nsimple induction 1; simpl in |- *; intros; auto with coc.\nrewrite distr_lift_subst; auto with coc.\nQed.\n\n  Hint Resolve red1_lift: coc.\n\n\n  Lemma red1_subst_r :\n   forall a t u,\n   red1 t u -> forall k, red1 (subst_rec a t k) (subst_rec a u k).\nsimple induction 1; simpl in |- *; intros; auto with coc.\nrewrite distr_subst; auto with coc.\nQed.\n\n\n  Lemma red1_subst_l :\n   forall t u,\n   red1 t u -> forall a k, red (subst_rec t a k) (subst_rec u a k).\nsimple induction a; simpl in |- *; auto with coc.\nintros.\nelim (lt_eq_lt_dec k n); intros; auto with coc.\nelim a0; auto with coc.\nunfold lift in |- *; auto with coc.\nQed.\n\n  Hint Resolve red1_subst_l red1_subst_r: coc.\n\n\n  Lemma red_prod_prod :\n   forall u v t,\n   red (Prod u v) t ->\n   forall P : Prop,\n   (forall a b, t = Prod a b -> red u a -> red v b -> P) -> P.\nsimple induction 1; intros.\napply H0 with u v; auto with coc.\n\napply H1; intros.\ninversion_clear H4 in H2.\ninversion H2.\napply H3 with N1 b; auto with coc.\napply trans_red with a; auto with coc.\n\napply H3 with a N2; auto with coc.\napply trans_red with b; auto with coc.\nQed.\n\n\n  Lemma red_sort_sort : forall s t, red (Srt s) t -> t <> Srt s -> False.\nsimple induction 1; intros; auto with coc.\napply H1.\ngeneralize H2.\ncase P; intros; try discriminate.\ninversion_clear H4.\nQed.\n\n\n\n  Lemma one_step_conv_exp : forall M N, red1 M N -> conv N M.\nintros.\napply trans_conv_exp with N; auto with coc.\nQed.\n\n\n  Lemma red_conv : forall M N, red M N -> conv M N.\nsimple induction 1; auto with coc.\nintros; apply trans_conv_red with P; auto with coc.\nQed.\n\n  Hint Resolve one_step_conv_exp red_conv: coc.\n\n\n  Lemma sym_conv : forall M N, conv M N -> conv N M.\nsimple induction 1; auto with coc.\nsimple induction 2; intros; auto with coc.\napply trans_conv_red with P0; auto with coc.\n\napply trans_conv_exp with P0; auto with coc.\n\nsimple induction 2; intros; auto with coc.\napply trans_conv_red with P0; auto with coc.\n\napply trans_conv_exp with P0; auto with coc.\nQed.\n\n  Hint Immediate sym_conv: coc.\n\n\n  Lemma trans_conv_conv : forall M N P, conv M N -> conv N P -> conv M P.\nintros.\ngeneralize M H; elim H0; intros; auto with coc.\napply trans_conv_red with P0; auto with coc.\n\napply trans_conv_exp with P0; auto with coc.\nQed.\n\n\n  Lemma conv_conv_prod :\n   forall a b c d, conv a b -> conv c d -> conv (Prod a c) (Prod b d).\nintros.\napply trans_conv_conv with (Prod a d).\nelim H0; intros; auto with coc.\napply trans_conv_red with (Prod a P); auto with coc.\n\napply trans_conv_exp with (Prod a P); auto with coc.\n\nelim H; intros; auto with coc.\napply trans_conv_red with (Prod P d); auto with coc.\n\napply trans_conv_exp with (Prod P d); auto with coc.\nQed.\n\n\n  Lemma conv_conv_lift :\n   forall a b n k, conv a b -> conv (lift_rec n a k) (lift_rec n b k).\nintros.\nelim H; intros; auto with coc.\napply trans_conv_red with (lift_rec n P k); auto with coc.\n\napply trans_conv_exp with (lift_rec n P k); auto with coc.\nQed.\n \n\n  Lemma conv_conv_subst :\n   forall a b c d k,\n   conv a b -> conv c d -> conv (subst_rec a c k) (subst_rec b d k).\nintros.\napply trans_conv_conv with (subst_rec a d k).\nelim H0; intros; auto with coc.\napply trans_conv_red with (subst_rec a P k); auto with coc.\n\napply trans_conv_exp with (subst_rec a P k); auto with coc.\n\nelim H; intros; auto with coc.\napply trans_conv_conv with (subst_rec P d k); auto with coc.\n\napply trans_conv_conv with (subst_rec P d k); auto with coc.\napply sym_conv; auto with coc.\nQed.\n\n  Hint Resolve conv_conv_prod conv_conv_lift conv_conv_subst: coc.\n\n\n  Lemma refl_par_red1 : forall M, par_red1 M M.\nsimple induction M; auto with coc.\nQed.\n\n  Hint Resolve refl_par_red1: coc.\n\n\n  Lemma red1_par_red1 : forall M N, red1 M N -> par_red1 M N.\nsimple induction 1; auto with coc; intros.\nQed.\n\n  Hint Resolve red1_par_red1: coc.\n\n\n  Lemma red_par_red : forall M N, red M N -> par_red M N.\nred in |- *; simple induction 1; intros; auto with coc.\napply t_trans with P; auto with coc.\nQed.\n\n\n  Lemma par_red_red : forall M N, par_red M N -> red M N.\nsimple induction 1.\nsimple induction 1; intros; auto with coc.\napply trans_red with (App (Abs T M') N'); auto with coc.\n\nintros.\napply trans_red_red with y; auto with coc.\nQed.\n\n  Hint Resolve red_par_red par_red_red: coc.\n\n\n  Lemma par_red1_lift :\n   forall n a b,\n   par_red1 a b -> forall k, par_red1 (lift_rec n a k) (lift_rec n b k).\nsimple induction 1; simpl in |- *; auto with coc.\nintros.\nrewrite distr_lift_subst; auto with coc.\nQed.\n\n\n  Lemma par_red1_subst :\n   forall a b c d,\n   par_red1 a b ->\n   par_red1 c d -> forall k, par_red1 (subst_rec a c k) (subst_rec b d k).\nsimple induction 2; simpl in |- *; auto with coc; intros.\nrewrite distr_subst; auto with coc.\n\nelim (lt_eq_lt_dec k n); auto with coc; intros.\nelim a0; intros; auto with coc.\nunfold lift in |- *.\napply par_red1_lift; auto with coc.\nQed.\n\n\n  Lemma inv_par_red_abs :\n   forall (P : Prop) T U x,\n   par_red1 (Abs T U) x ->\n   (forall T' U', x = Abs T' U' -> par_red1 U U' -> P) -> P.\ndo 5 intro.\ninversion_clear H; intros.\napply H with T' M'; auto with coc.\nQed.\n\n  Hint Resolve par_red1_lift par_red1_subst: coc.\n\n\n\n  Lemma mem_sort_lift :\n   forall t n k s, mem_sort s (lift_rec n t k) -> mem_sort s t.\nsimple induction t; simpl in |- *; intros; auto with coc.\ngeneralize H; elim (le_gt_dec k n); intros; auto with coc.\ninversion_clear H0.\n\ninversion_clear H1.\napply mem_abs_l; apply H with n k; auto with coc.\n\napply mem_abs_r; apply H0 with n (S k); auto with coc.\n\ninversion_clear H1.\napply mem_app_l; apply H with n k; auto with coc.\n\napply mem_app_r; apply H0 with n k; auto with coc.\n\ninversion_clear H1.\napply mem_prod_l; apply H with n k; auto with coc.\n\napply mem_prod_r; apply H0 with n (S k); auto with coc.\nQed.\n\n\n  Lemma mem_sort_subst :\n   forall b a n s,\n   mem_sort s (subst_rec a b n) -> mem_sort s a \\/ mem_sort s b.\nsimple induction b; simpl in |- *; intros; auto with coc.\ngeneralize H; elim (lt_eq_lt_dec n0 n); intro.\nelim a0; intros.\ninversion_clear H0.\n\nleft.\napply mem_sort_lift with n0 0; auto with coc.\n\nintros.\ninversion_clear H0.\n\ninversion_clear H1.\nelim H with a n s; auto with coc.\n\nelim H0 with a (S n) s; auto with coc.\n\ninversion_clear H1.\nelim H with a n s; auto with coc.\n\nelim H0 with a n s; auto with coc.\n\ninversion_clear H1.\nelim H with a n s; auto with coc.\n\nelim H0 with a (S n) s; intros; auto with coc.\nQed.\n\n  Lemma exp_sort_mem : forall s t u, red1 t u -> mem_sort s u -> mem_sort s t.\ninduction 1; intros; try inversion_clear H0; auto.\napply mem_sort_subst in H; destruct H; auto.\nQed.\n\n\n  Lemma red_sort_mem : forall t s, red t (Srt s) -> mem_sort s t.\nintros.\npattern t in |- *.\napply red1_red_ind with (Srt s); auto with coc.\ndo 4 intro.\nelim H0; intros.\nelim mem_sort_subst with M0 N 0 s; intros; auto with coc.\n\ninversion_clear H4; auto with coc.\n\ninversion_clear H4; auto with coc.\n\ninversion_clear H4; auto with coc.\n\ninversion_clear H4; auto with coc.\n\ninversion_clear H4; auto with coc.\n\ninversion_clear H4; auto with coc.\nQed.\n\n\n\n  Lemma red_normal : forall u v, red u v -> normal u -> u = v.\nsimple induction 1; auto with coc; intros.\nabsurd (red1 u N); auto with coc.\nabsurd (red1 P N); auto with coc.\nelim (H1 H3).\nunfold not in |- *; intro; apply (H3 N); auto with coc.\nQed.\n\n\n\n  Lemma sn_red_sn : forall a b, sn a -> red a b -> sn b.\nunfold sn in |- *.\nsimple induction 2; intros; auto with coc.\napply Acc_inv with P; auto with coc.\nQed.\n\n\n  Lemma commut_red1_subterm : commut _ subterm (transp _ red1).\nred in |- *.\nsimple induction 1; intros.\nexists (Abs z B); auto with coc.\n\nexists (Abs A z); auto with coc.\n\nexists (App z B); auto with coc.\n\nexists (App A z); auto with coc.\n\nexists (Prod z B); auto with coc.\n\nexists (Prod A z); auto with coc.\nQed.\n\n\n  Lemma subterm_sn : forall a, sn a -> forall b, subterm b a -> sn b.\nunfold sn in |- *.\nsimple induction 1; intros.\napply Acc_intro; intros.\nelim commut_red1_subterm with x b y; intros; auto with coc.\napply H1 with x0; auto with coc.\nQed.\n\n\n  Lemma sn_prod : forall A, sn A -> forall B, sn B -> sn (Prod A B).\nunfold sn in |- *.\nsimple induction 1.\nsimple induction 3; intros.\napply Acc_intro; intros.\ninversion_clear H5; auto with coc.\napply H1; auto with coc.\napply Acc_intro; auto with coc.\nQed.\n\n\n  Lemma sn_subst : forall T M, sn (subst T M) -> sn M.\nintros.\ncut (forall t, sn t -> forall m, t = subst T m -> sn m).\nintros.\napply H0 with (subst T M); auto with coc.\n\nunfold sn in |- *.\nsimple induction 1; intros.\napply Acc_intro; intros.\napply H2 with (subst T y); auto with coc.\nrewrite H3.\nunfold subst in |- *; auto with coc.\nQed.\n", "meta": {"author": "barras", "repo": "cic-model", "sha": "dcc38f3104048aa50d230f819085131b16702d3d", "save_path": "github-repos/coq/barras-cic-model", "path": "github-repos/coq/barras-cic-model/cic-model-dcc38f3104048aa50d230f819085131b16702d3d/Term.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346598, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6705983006094747}}
{"text": "Require Import ssreflect ssrfun ssrbool.\nRequire Import Setoid.\n\n(** some simple lemmas about bool *)\n\nLemma degen_bool : forall P, is_true false -> P.\nProof.\n  intros; discriminate.\nQed.\n\n(* AND *)\nLemma foo : forall a b:bool, a -> b -> a && b. \nProof.\n  intros a b; case a; case b; solve [reflexivity | discriminate].\nQed.\n\nLemma and_bool_lr : forall a b, a && b -> a /\\ b.\nProof.\n  intros a b; case a; case b; intros H; inversion H; split; assumption.\nQed.\n\nLemma and_bool : forall a b, a && b <-> a /\\ b.\nProof.\n  intros a b; split.\n  apply and_bool_lr.\n  case a;case b; intros (ha,hb); solve [inversion ha | inversion hb | reflexivity].\nQed.\n\nLemma ab5_bool : forall a b c d e, a && b && c && d && e <-> a /\\ b /\\ c /\\ d /\\ e. \n  intros a b c d e; split.\n  repeat rewrite -> and_bool; intros; tauto.\n  case a; case b; case c; case d; case e; intros ; solve [reflexivity | decompose [and] H; discriminate].\nQed.\n\nLemma circ2 : forall a b, a&&b -> b&&a.\nProof.\n  intros a b; destruct a; destruct b; intros H;inversion H; assumption.\nQed.\n\nLemma circ3: forall A B C: bool, B && C && A -> A && B &&C.\nProof.\n  intros a b c; case a; case b; case c; intros; assumption.\nQed.\n\nLemma circ6: forall A B C D E F : bool,\n       B && C && D && E &&F && A -> A && B && C && D && E && F.\nProof.\n  intros a b c d e f; case a; case b; case c; case d; case e; case f; intros; assumption.\nQed.\n\nLemma bool6 : forall a b c d e f, a && b && c && d && e && f -> a && e && d && c && b && f.\nProof.\n  intros a b c d e f; case a; case b; case c; case d; case e; case f; intros; assumption.\nQed.\n\nLemma comm12L: forall A B C:bool, B && A && C -> A && B && C.\n   Proof.\n     intros a b c; case a; case b; case c; intros; assumption.\n   Qed.\n   \nLemma comm12P: forall A B C D E F :bool,\n       B && A && C && D &&E && F -> A && B && C && D && E && F.\nProof.\n  intros a b c d e f; case a; case b; case c; case d; case e; case f; intros; assumption.\nQed.\n\n(* OR *)\nLemma or_bool : forall a b : bool, a || b <-> a \\/ b.\nProof.\n  intros a b; destruct a; destruct b; split; intuition.\nQed.  \n\n", "meta": {"author": "magaud", "repo": "PG3q", "sha": "d34bc2a8b4f42610952a65840b724a69f5a926a1", "save_path": "github-repos/coq/magaud-PG3q", "path": "github-repos/coq/magaud-PG3q/PG3q-d34bc2a8b4f42610952a65840b724a69f5a926a1/generic/lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522815, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.670598296621328}}
{"text": "(***************************************************************************\n* Safety for Simply Typed Lambda Calculus (CBV) - Definitions              *\n* Extented from \"Type Safety for STLC\" by                                  *\n* Brian Aydemir & Arthur Charguéraud & Stephanie Weirich,                  *\n* July 2007, Coq v8.1                                                      *\n***************************************************************************)\n\nSet Implicit Arguments.\nRequire Import Metatheory.\n\n(** Grammar of types. *)\n\nInductive typ : Set :=\n  | typ_var   : var -> typ\n  | typ_arrow : typ -> typ -> typ.\n\n(** Grammar of pre-terms. *)\n\nInductive trm : Set :=\n  | trm_bvar : nat -> trm\n  | trm_fvar : var -> trm\n  | trm_abs  : trm -> trm\n  | trm_app  : typ -> trm -> trm -> trm.\n\n(** Opening up abstractions *)\n\nFixpoint open_rec (k : nat) (u : trm) (t : trm) {struct t} : trm :=\n  match t with\n  | trm_bvar i      => if k === i then u else (trm_bvar i)\n  | trm_fvar x      => trm_fvar x\n  | trm_abs t1      => trm_abs (open_rec (S k) u t1)\n  | trm_app U t1 t2 => trm_app U (open_rec k u t1) (open_rec k u t2)\n  end.\n\nDefinition open t u := open_rec 0 u t.\n\nNotation \"{ k ~> u } t\" := (open_rec k u t) (at level 67).\nNotation \"t ^^ u\" := (open t u) (at level 67).\nNotation \"t ^ x\" := (open t (trm_fvar x)).\n\n(** Terms are locally-closed pre-terms *)\n\nInductive term : trm -> Prop :=\n  | term_var : forall x,\n      term (trm_fvar x)\n  | term_abs : forall L t1,\n      (forall x, x \\notin L -> term (t1 ^ x)) ->\n      term (trm_abs t1)\n  | term_app : forall t1 t2 T,\n      term t1 ->\n      term t2 ->\n      term (trm_app T t1 t2).\n\n(** Environment is an associative list mapping variables to types. *)\n\nDefinition env := Env.env typ.\n\n(** Typing relation *)\n\nReserved Notation \"E |= t ~: T\" (at level 69).\n\nInductive typing : env -> trm -> typ -> Prop :=\n  | typing_var : forall E x T,\n      ok E ->\n      binds x T E ->\n      E |= (trm_fvar x) ~: T\n  | typing_abs : forall L E U T t1,\n      (forall x, x \\notin L ->\n        (E & x ~ U) |= t1 ^ x ~: T) ->\n      E |= (trm_abs t1) ~: (typ_arrow U T)\n  | typing_app : forall S T E t1 t2,\n      E |= t1 ~: (typ_arrow S T) ->\n      E |= t2 ~: S ->\n      E |= (trm_app S t1 t2) ~: T\n\nwhere \"E |= t ~: T\" := (typing E t T).\n\n(** Definition of values (only abstractions are values) *)\n\nInductive value : trm -> Prop :=\n  | value_abs : forall t1,\n      term (trm_abs t1) -> value (trm_abs t1).\n\n(** Reduction relation - one step in call-by-value *)\n\nInductive red : trm -> trm -> Prop :=\n  | red_beta : forall t1 t2 T,\n      term (trm_abs t1) ->\n      value t2 ->\n      red (trm_app T (trm_abs t1) t2) (t1 ^^ t2)\n  | red_app_1 : forall t1 t1' t2 T,\n      term t2 ->\n      red t1 t1' ->\n      red (trm_app T t1 t2) (trm_app T t1' t2)\n  | red_app_2 : forall t1 t2 t2' T,\n      value t1 ->\n      red t2 t2' ->\n      red (trm_app T t1 t2) (trm_app T t1 t2').\n\nNotation \"t --> t'\" := (red t t') (at level 68).\n\n(** Goal is to prove preservation and progress *)\n\nDefinition preservation := forall E t t' T,\n  E |= t ~: T ->\n  t --> t' ->\n  E |= t' ~: T.\n\nDefinition progress := forall t T,\n  empty |= t ~: T ->\n     value t\n  \\/ exists t', t --> t'.\n\n", "meta": {"author": "spl", "repo": "formal_binders", "sha": "392d6e5c52d54d9b0bddc22f9ccbd2a0d765acbb", "save_path": "github-repos/coq/spl-formal_binders", "path": "github-repos/coq/spl-formal_binders/formal_binders-392d6e5c52d54d9b0bddc22f9ccbd2a0d765acbb/STLC_Dec_Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6705982946830801}}
{"text": "(***********************************************************************************)\n(*  Poly Logique et demonstration automatique                                      *)\n(*  P140,Exercice 97.6                                                             *)\n(*                                                                                 *)\n(*  (forall x, P x -> Q x) /\\ (exists x, P x) -> (exists x, Q x)                   *)\n(*                                                                                 *)\n(*  contexte | no  | ligne                                        | regle          *)\n(*  1        | 1   | Sup (forall x, P x => Q x)/\\(exists x, P x)  | hyp            *)\n(*  1        | 2   | forall x, P x => Q x                         | /\\E1,1         *)\n(*  1        | 3   | exists x, P x                                | /\\E2,1         *)\n(*  1,4      | 4   | P x /\\ Q x                                   | forallE,2      *)\n(*  1,4,6    | 5   | Sup P x                                      | hyp            *)\n(*  1,4,6    | 6   | Q x                                          | =>E,4 5        *)\n(*  1,4,6    | 7   | exists x, Q x                                | existsI,6      *)\n(*  1,4      | 8   | Donc P x => exists x, Q x                    | =>I,5 7        *)\n(*  1,4      | 9   | exists x, Q x                                | existsE,8 3    *)\n(*  1,4      | 10  | Donc cqfd                                    | =>I,1 9        *)\n(*                                                                                 *)\n(***********************************************************************************)\n\n\nRequire Import Classical.\n\n\nSection Declaration.\n\nVariable D : Set.\nVariable P : D -> Prop.\nVariable Q : D -> Prop.\n\n\nSection Preuve. \n\nLemma ex976 : (forall x : D, P x -> Q x) /\\ (exists x : D, P x) -> (exists x : D, Q x).\n\nintro H0.\nelim H0.\nintros H0_decomp_G H0_decomp_D.\nelim H0_decomp_D.\nintros x0 P_x0.\nexists x0.\napply H0_decomp_G.\nexact P_x0.\n\nQed.\n\nEnd Preuve.\nEnd Declaration.\n\nCheck ex976.\n\nQuit.\n", "meta": {"author": "LoukaSoret", "repo": "Stage2017_COQ", "sha": "6641adbaf139a51478460e28c94591fff407d7d4", "save_path": "github-repos/coq/LoukaSoret-Stage2017_COQ", "path": "github-repos/coq/LoukaSoret-Stage2017_COQ/Stage2017_COQ-6641adbaf139a51478460e28c94591fff407d7d4/Preuve_tactique_classique/ex97_6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.670598292744832}}
{"text": "Require Import String ZArith Lia.\nRequire Import lang.\nRequire Import logic.\nRequire Import pretty.\n\nFixpoint fib (n : nat) :=\n  (match n with\n  | 0 => 0\n  | S k =>\n    match k with\n    | 0 => 1\n    | S l => fib k + fib l\n    end\n  end)%nat.\n\n\nDefinition fib_imp : insn :=\n  (\"x\" :== 0;\n  \"y\" :== 1;\n  While (1 <= \"input\") Do\n        (\"sum\" :== \"x\" + \"y\";\n        \"x\" :== \"y\";\n        \"y\" :== \"sum\";\n        \"input\" :== \"input\" - 1)\n        Done;\n  \"output\" :== \"sum\").\n\nSearch (nat -> Z).\n\n(* Idea: automatically prove a correspondance between tail-recursive\n   function and while loops. *)\nTheorem fib_imp_correct : forall n : nat,\n    hoare (fun f => f \"input\" = Z.of_nat n)\n          fib_imp\n          (fun g => g \"output\" = Z.of_nat (fib n)).\nProof.\n  intros.\nAbort.\n", "meta": {"author": "codyroux", "repo": "hoare-toy", "sha": "47b6a1ee12f96c61fe1ef4226bea21d97cc9d0c7", "save_path": "github-repos/coq/codyroux-hoare-toy", "path": "github-repos/coq/codyroux-hoare-toy/hoare-toy-47b6a1ee12f96c61fe1ef4226bea21d97cc9d0c7/fib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6705904429525698}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom mathcomp Require Import all_algebra.\nFrom mathcomp Require Import all_real_closed.\nFrom CoqEAL Require Import ssrcomplements.\n\n(******************************************************************************)\n(*                                                                            *)\n(*  This file contains theory about polynomials with coefficients             *)\n(*  in a closed field.                                                        *)\n(*                                                                            *)\n(*  In follow we pose p = (X - r1)^+a1 * (X - r2)^+a2 * ... * (X - rn)^+an    *)\n(*                                                                            *)\n(*            root_seq p == the sequence of all roots of polynomial p.        *)\n(*       root_seq_uniq p == the sequence of all distinct roots of             *)\n(*                          polynomial p (i.e the sequence [:: r1; ...; rn])  *)\n(*         root_mu_seq p == the sequence of pair off the roots and            *)\n(*                          its multiplicity of polynomial p.                 *)\n(*                          (i.e the sequence [:: (r1,a1); ... ; (rn,an)])    *)\n(*       root_seq_poly s == the concatenation of the sequences root_mu_seq p  *)\n(*                          for all polynomials p in the sequence s.          *)\n(*   linear_factor_seq p == the sequence of linear factor tha appear of the   *)\n(*                          decompositionof polynomial p. (i.e the sequence   *)\n(*                          [:: (X - r1)^+a1; ... ; (X - rn)^+an])            *)\n(*                                                                            *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection poly_closedFieldType.\n\nVariable F : closedFieldType.\nImport GRing.Theory.\n\nLocal Open Scope ring_scope.\n\nDefinition root_seq : {poly F} -> seq F :=\n  let fix loop (p : {poly F}) (n : nat) :=\n    if n is n.+1 then\n      if (size p != 1%N) =P true is ReflectT p_neq0\n        then let x := projT1 (sigW (closed_rootP p p_neq0)) in\n          x :: loop (p %/ ('X - x%:P)) n\n        else [::]\n      else [::]\n  in fun p => loop p (size p).\n\nLemma root_root_seq (p : {poly F}) x : p != 0 -> x \\in root_seq p = root p x.\nProof.\nrewrite /root_seq; set loop := fix loop p n := if n is _.+1 then _ else _.\nelim: size {-2 5}p (erefl (size p))=> /= {p} [|n ihn] p /=.\n  by move/eqP; rewrite size_poly_eq0 => /eqP->; rewrite eqxx.\ncase: eqP=> /= [sp_neq1 sp_eqn|/negP]; last first.\n  rewrite negbK=> /size_poly1P [c c_neq0 ->] _ _.\n  by rewrite rootC (negPf c_neq0).\ncase: sigW => z /= rpz p_neq0.\nrewrite in_cons; have [->|neq_xz] //= := altP eqP.\nmove: rpz sp_eqn => /factor_theorem [q ->].\nrewrite mulpK ?polyXsubC_eq0 // rootM root_XsubC (negPf neq_xz) orbF.\nhave [->|q_neq0] := eqVneq q 0; first by rewrite mul0r size_poly0.\nrewrite size_mul ?polyXsubC_eq0 // size_XsubC addn2.\nby case=> /ihn /(_ q_neq0).\nQed.\n\nLemma root_seq_cons (p : {poly F}) x s : root_seq p = x :: s ->\n  s = root_seq (p %/ ('X - x%:P)).\nProof.\nrewrite /root_seq; set loop := fix loop p n := if n is _.+1 then _ else _.\ncase H: (size p)=> [|n] //=; case: eqP=> // Hp.\nmove/eqP; rewrite eqseq_cons; case/andP=> /eqP {1}<- /eqP <-.\nsuff ->: n = size (p %/ ('X - x%:P))=> //.\nby rewrite size_divp ?polyXsubC_eq0 // size_XsubC subn1 H.\nQed.\n\nLemma root_seq_eq (p : {poly F}) :\n  p = lead_coef p *: \\prod_(x <- root_seq p) ('X - x%:P).\nProof.\nmove: {2}(root_seq p) (erefl (root_seq p))=> s.\nelim: s p=> [p | x s IHp p H].\n  rewrite /root_seq; set loop := fix loop p n := if n is _.+1 then _ else _.\n  case H: (size p)=> [|n].\n    move/eqP: H; rewrite size_poly_eq0=> /eqP ->.\n    by rewrite lead_coef0 scale0r.\n  case: n H => [H | n H] /=; case: eqP => //.\n    move=> _ _; rewrite big_nil.\n    move/eqP: H => /size_poly1P [c H] ->.\n    by rewrite lead_coefC alg_polyC.\n  by move/negP; rewrite negbK H.\nrewrite H big_cons (root_seq_cons H) mulrC scalerAl.\nhave Hfp : p = p %/ ('X - x%:P) * ('X - x%:P).\n  apply/eqP; rewrite -dvdp_eq dvdp_XsubCl -root_root_seq.\n    by rewrite H mem_head.\n  move: H; rewrite /root_seq.\n  set loop := fix loop p n := if n is _.+1 then _ else _.\n  by apply: contraPneq => ->; rewrite size_poly0.\nsuff -> : lead_coef p = lead_coef (p %/ ('X - x%:P)).\n  by rewrite -IHp ?(root_seq_cons H).\nby rewrite {1}Hfp lead_coef_Mmonic // monicXsubC.\nQed.\n\nLemma root_seq0 : root_seq 0 = [::].\nProof. by rewrite /root_seq size_poly0. Qed.\n\nLemma size_root_seq p : size (root_seq p) = (size p).-1.\nProof.\nhave [-> | p0] := eqVneq p 0; first by rewrite root_seq0 size_poly0.\nrewrite {2}[p]root_seq_eq size_scale ?lead_coef_eq0 //.\nrewrite (big_nth 0) big_mkord size_prod.\n  rewrite (eq_bigr (fun=> (1 + 1)%N)).\n    by rewrite big_split sum1_card /= subSKn addnK card_ord.\n  by move=> i _; rewrite size_XsubC.\nby move=> i _; rewrite polyXsubC_eq0.\nQed.\n\nLemma root_seq_nil (p : {poly F}) :\n  (size p <= 1)%N = ((root_seq p) == [::]).\nProof. by rewrite -subn_eq0 subn1 -size_root_seq size_eq0. Qed.\n\nLemma sub_root_div (p q : {poly F}) (Hq : q != 0) :\n  p %| q -> {subset (root_seq p) <= (root_seq q)} .\nProof.\ncase: (eqVneq p 0) => [->|p0]; first by rewrite root_seq0.\nby case/dvdpP => x Hx y; rewrite !root_root_seq // Hx rootM orbC=> ->.\nQed.\n\nDefinition root_seq_uniq p := undup (root_seq p).\n\nLemma prod_XsubC_count (p : {poly F}):\n   p = (lead_coef p) *:\n   \\prod_(x <- root_seq_uniq p) ('X - x%:P)^+ (count_mem x (root_seq p)).\nProof.\nby rewrite {1}[p]root_seq_eq (prod_seq_count (root_seq p)).\nQed.\n\nLemma count_root_seq p x : count_mem x (root_seq p) = \\mu_x p.\nProof.\nhave [-> | Hp] := eqVneq p 0; first by rewrite root_seq0 mu0.\napply/eqP; rewrite -muP //.\ncase/boolP: (x \\in root_seq p) => [|H].\n  rewrite -mem_undup => H.\n  move: (prod_XsubC_count p).\n  rewrite (bigD1_seq x) //= ?undup_uniq //.\n  set b:= \\big[_/_]_(_ <- _ | _) _ => Hpq.\n  apply/andP; split; apply/dvdpP.\n    by exists (lead_coef p *: b); rewrite -scalerAl mulrC.\n  case=> q Hq.\n  have H1: ~~ (('X - x%:P) %| b).\n    rewrite dvdp_XsubCl; apply/rootP.\n    rewrite horner_prod; apply/eqP.\n    rewrite (big_nth 0) big_mkord.\n    apply/prodf_neq0=> i Hix.\n    by rewrite horner_exp hornerXsubC expf_neq0 // subr_eq0 eq_sym.\n  have H2: (('X - x%:P) %| b).\n    apply/dvdpP; exists ((lead_coef p)^-1 *: q).\n    apply: (@scalerI _ _ (lead_coef p)); first by rewrite lead_coef_eq0.\n    rewrite -scalerAl scalerA mulrV ?unitfE ?lead_coef_eq0 // scale1r.\n    have HX: (('X - x%:P)^+ (count_mem x (root_seq p))) != 0.\n      by apply: expf_neq0; rewrite -size_poly_eq0 size_XsubC.\n    rewrite -(mulpK (_ *: b) HX) -(mulpK (q * _) HX).\n    by rewrite -scalerAl mulrC -Hpq -mulrA -exprS -Hq.\n  by rewrite H2 in H1.\nhave->: count_mem x (root_seq p) = 0%N by apply/count_memPn.\nby rewrite dvd1p /= dvdp_XsubCl -root_root_seq.\nQed.\n\nDefinition root_mu_seq p := [seq (x,(\\mu_x p)) | x <- (root_seq_uniq p)].\n\nLemma root_mu_seq_pos x p : p != 0 -> x \\in root_mu_seq p -> (0 < x.2)%N.\nProof.\nmove=> Hp H.\nhave Hr: size (root_seq_uniq p) = size (root_mu_seq p) by rewrite size_map.\nhave Hs: (index x (root_mu_seq p) < size (root_seq_uniq p))%N.\n  by rewrite Hr index_mem.\nrewrite -(nth_index (0,0%N) H) // (nth_map 0) // mu_gt0 //.\nby rewrite -root_root_seq // -mem_undup mem_nth.\nQed.\n\nDefinition root_seq_poly (s : seq {poly F}) := flatten (map root_mu_seq s).\n\nLemma root_seq_poly_pos x s : (forall p , p \\in s -> p !=0) ->\n  x \\in root_seq_poly s -> (0 < x.2)%N.\nProof.\nelim : s=> [|p l IHl H]; first by rewrite in_nil.\nrewrite mem_cat.\ncase/orP; first by apply: root_mu_seq_pos; apply: H; rewrite mem_head.\nby apply: IHl=> q Hq; apply: H; rewrite in_cons Hq orbT.\nQed.\n\nDefinition linear_factor_seq p :=\n   [seq ('X - x.1%:P)^+x.2 | x <- (root_mu_seq p)].\n\nLemma monic_linear_factor_seq p : forall q, q \\in linear_factor_seq p ->\n  q \\is monic.\nProof.\nmove=> q Hq; rewrite -(nth_index 0 Hq) (nth_map (0,0%N)).\napply: monic_exp; first by apply: monicXsubC.\nby rewrite -index_mem size_map in Hq.\nQed.\n\nLemma size_linear_factor_leq1 p : forall q, q \\in linear_factor_seq p ->\n  (1 < size q)%N.\nProof.\nmove=> q; have [-> | Hp Hq] := eqVneq p 0.\n  rewrite /linear_factor_seq /root_mu_seq.\n  by rewrite /root_seq_uniq /root_seq size_poly0.\nrewrite -(nth_index 0 Hq) (nth_map (0,0%N)); last first.\n  by rewrite -index_mem size_map in Hq.\nrewrite size_exp_XsubC (nth_map 0); last first.\n  by rewrite -index_mem !size_map in Hq.\nrewrite -(@prednK (\\mu_ _ _)) // mu_gt0 // -root_root_seq //.\nrewrite -mem_undup mem_nth //.\nby rewrite -index_mem !size_map in Hq.\nQed.\n\nLemma coprimep_linear_factor_seq p :\n  forall (i j : 'I_(size (linear_factor_seq p))),\n  i != j ->\n  coprimep (linear_factor_seq p)`_i (linear_factor_seq p)`_j.\nProof.\nmove=> [i +] [j +]; rewrite !size_map=> Hi Hj Hij.\nrewrite !(nth_map (0,0%N)) ?size_map //.\napply/coprimep_expl/coprimep_expr/coprimep_factor.\nby rewrite unitfE subr_eq0 !(nth_map 0) //= nth_uniq // ?undup_uniq // eq_sym.\nQed.\n\nLemma prod_XsubC_mu (p : {poly F}):\n   p = (lead_coef p) *: \\prod_(x <- root_seq_uniq p) ('X - x%:P)^+(\\mu_x p).\nProof.\nrewrite {1}[p]prod_XsubC_count.\nby congr GRing.scale; apply: eq_bigr => i _; rewrite count_root_seq.\nQed.\n\nLemma monic_prod_XsubC p :\n   p \\is monic -> p = \\prod_(x <- root_seq_uniq p) ('X - x%:P)^+(\\mu_x p).\nProof.\nby move/monicP=> H; rewrite {1}[p]prod_XsubC_mu H scale1r.\nQed.\n\nLemma prod_factor (p : {poly F}):\n   p = (lead_coef p) *: \\prod_(x <- linear_factor_seq p) x.\nProof.\nby rewrite !big_map {1}[p]prod_XsubC_mu.\nQed.\n\nLemma monic_prod_factor p :\n   p \\is monic -> p = \\prod_(x <- linear_factor_seq p) x.\nProof.\nby move/monicP=> H; rewrite {1}[p]prod_factor H scale1r.\nQed.\n\nLemma uniq_root_mu_seq (p : {poly F}) : uniq (root_seq p) ->\n  forall x, x \\in root_mu_seq p -> x.2 = 1%N.\nProof.\nmove=> H x /(nthP (0,0%N)) [] i; rewrite size_map=> Hi.\nrewrite (nth_map 0) // => <- /=; move: Hi.\nrewrite /root_seq_uniq undup_id // -count_root_seq => Hi.\nby rewrite count_uniq_mem // (mem_nth 0 Hi).\nQed.\n\nLemma uniq_root_dvdp p q : q != 0 ->\n  (uniq (root_seq q)) -> p %| q -> (uniq (root_seq p)).\nProof.\nmove=> Hq Hq2 Hpq.\napply: count_mem_uniq=> x.\nhave Hc:= count_uniq_mem x Hq2.\nhave Hle: (count_mem x (root_seq p) <= count_mem x (root_seq q))%N.\n  rewrite !count_root_seq; case/dvdpP: Hpq => r Hr.\n  by rewrite Hr mu_mul -?Hr // leq_addl.\nhave: (count_mem x (root_seq p) <= 1)%N.\n  by rewrite (leq_trans Hle) // Hc; case: (x \\in root_seq q).\nrewrite leq_eqVlt ltnS leqn0.\ncase Hp: (x \\in root_seq p).\n  rewrite -has_pred1 has_count in Hp.\n  by rewrite (eqn_leq _ 0%N) leqNgt Hp orbF => /eqP ->.\nby rewrite eqn_leq -has_count has_pred1 Hp andbF orFb => /eqP ->.\nQed.\n\nLemma root_root_mu_seq p : [seq x.1 | x <- root_mu_seq p] = root_seq_uniq p.\nProof.\napply: (@eq_from_nth _ 0)=>[|i]; rewrite !size_map //.\nby move=> Hi; rewrite (nth_map (0,0%N)) ?size_map // (nth_map 0) //.\nQed.\n\nEnd poly_closedFieldType.\n", "meta": {"author": "coq-community", "repo": "coqeal", "sha": "1063846268eb2c51fd0e8363dee9a247e3f70c7c", "save_path": "github-repos/coq/coq-community-coqeal", "path": "github-repos/coq/coq-community-coqeal/coqeal-1063846268eb2c51fd0e8363dee9a247e3f70c7c/theory/closed_poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.670590441073762}}
{"text": "From mathcomp Require Import ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nRequire Import class_set.\n\nSection Class_Set_Theories.\n\n  Variable U:Type.\n\n  Theorem union_comm:\n    forall (X Y:Ensemble U), X ∪ Y = Y ∪ X.\n  Proof.\n    move => X Y.\n    apply /Extensionality_Ensembles.\n    +split => x; case => x0 H.\n     ++right.\n       apply H.\n       left.\n       apply H.\n     ++right.\n       apply H.\n       left.\n       apply H.\n  Qed.\n\n  Theorem union_assoc:\n    forall (X Y Z:Ensemble U), (X ∪ Y) ∪ Z = X ∪ Y ∪ Z.\n  Proof.\n    move => X Y Z.\n    apply /Extensionality_Ensembles.\n    +split => x.\n     apply.\n     apply.\n  Qed.\n\n  Lemma noone_in_complement: forall (x:U) (X:Ensemble U), x ∈ X <-> (x ∈ (X^c) -> False).\n  Proof.\n    move => x X.\n    rewrite /iff.\n    split => H.\n    +move => H0.\n     move: H.\n     apply H0.\n    +rewrite -(Complement_Complement U X).\n     move => H0.\n     move: H0.\n     apply H.\n  Qed.\n\n  Lemma include_contrapositive:\n    forall (X Y:Ensemble U), X ⊂ Y <-> (Y^c) ⊂ (X^c).\n  Proof.\n    move => X Y.\n    rewrite /iff.\n    split.\n    +apply contrapositive.\n     apply classic.\n     move => H.\n     unfold Included.\n     move => H0.\n     apply H.\n     unfold Included.\n     move => x.\n     apply contrapositive.\n     apply classic.\n     rewrite -noone_in_complement.\n     rewrite -noone_in_complement.\n     apply H0.\n    +unfold Included.\n     move => H x.\n     apply contrapositive.\n     apply classic.\n     rewrite noone_in_complement.\n     rewrite (noone_in_complement x X).\n     rewrite not_not_iff.\n     rewrite not_not_iff.\n     apply H.\n     apply classic.\n     apply classic.\n  Qed.\n\n  Proposition double_setminus:\n    forall (X Y:Ensemble U), X ⊂ Y -> Y \\ (Y \\ X) = X.\n  Proof.\n    move => X Y H.\n    apply /Extensionality_Ensembles.\n    split => a H'.\n    inversion H'.\n    apply NNPP.\n    move => HF.\n    apply H1.\n    split.\n    apply H0.\n    done.\n    split.\n    apply H.\n    apply H'.\n    move => H0.\n    inversion H0.\n    apply H2.\n    done.\n  Qed.\n\n  Proposition complement_set_is_eq:\n    forall (A B:Ensemble U), A ^c = B ^c <-> A = B.\n  Proof.\n    move => A B.\n    rewrite /iff.\n    split => H.\n    apply Extension in H.\n    inversion H.\n    apply include_contrapositive in H0.\n    apply include_contrapositive in H1.\n    apply /Extensionality_Ensembles.\n    split.\n    apply H1.\n    apply H0.\n    rewrite H.\n    reflexivity.\n  Qed.\n\n  Lemma de_morgen_union_intersection_in_set:\n    forall (A B:Ensemble U),\n      (A ∪ B) ^c = A ^c ∩ B ^c.\n  Proof.\n    move => A B.\n    apply Extensionality_Ensembles.\n    split => x H.\n    have L1: (~ x ∈ A) /\\ (~ x ∈ B).\n    split; move => H'; apply H;[left|right];done.\n    inversion L1.\n    split; done.\n    inversion H.\n    move => HF.\n    inversion HF; [apply H0|apply H1]; done.\n  Qed.\n\n  Lemma de_morgen_intersection_union_in_set:\n    forall (A B:Ensemble U),\n      (A ∩ B) ^c = A ^c ∪ B ^c.\n  Proof.\n    move => A B.\n    have L1: ((A ^c ∪ B ^c) ^c) ^c = (A ^c ∪ B ^c).\n    apply Complement_Complement.\n    rewrite -L1.\n    rewrite de_morgen_union_intersection_in_set.\n    rewrite Complement_Complement.\n    rewrite Complement_Complement.\n    reflexivity.\n  Qed.\n\n  Lemma de_morgen_union_intersection_in_setminus:\n    forall (A B X:Ensemble U),\n      X \\ (A ∪ B) = (X \\ A) ∩ (X \\ B).\n  Proof.\n    move => A B X.\n    apply Extensionality_Ensembles.\n    split => x H.\n    inversion H.\n    have L1: (~ x ∈ A) /\\ (~ x ∈ B).\n    split; move => H2;apply H1;[left|right];done.\n    inversion L1.\n    split;split;done.\n    inversion H.\n    inversion H0.\n    inversion H1.\n    split.\n    apply H3.\n    move => HF.\n    inversion HF.\n    apply H4.\n    apply H7.\n    apply H6.\n    done.\n  Qed.\n\n  Lemma de_morgen_and_intersection_union_setminus:\n    forall (A B X:Ensemble U),\n      A ⊂ X /\\ B ⊂ X -> X \\ (A ∩ B) = (X \\ A) ∪ (X \\ B).\n  Proof.\n    move => A B X [HA HB].\n    have L1: ((X \\ A) ∪ (X \\ B)) ⊂ X.\n    move => x.\n    case => x';case => H HF;done.\n    have L2: X \\ (X \\ ((X \\ A) ∪ (X \\ B))) = (X \\ A) ∪ (X \\ B).\n    rewrite (double_setminus L1).\n    reflexivity.\n    rewrite -L2.\n    rewrite de_morgen_union_intersection_in_setminus.\n    rewrite (double_setminus HA).\n    rewrite (double_setminus HB).\n    reflexivity.\n  Qed.\n\nEnd Class_Set_Theories.\n\nExport class_set.\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/class_set_theories.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6705850252717243}}
{"text": "Require Import HoTT.\n\n(** A few lemmas and definitions regarding path types we didn't find in the HoTT library. *)\n\n(** A couple auxiliary lemmas we need  *)\nDefinition ap011_pp_pp {A B C : Type} (f : A -> B -> C) {x x' x'' : A} {y y' y'' : B}\n           (p : x = x') (p' : x' = x'') (q : y = y') (q' : y' = y'') :\n  ap011 f (p @ p') (q @ q') = ap011 f p q @ ap011 f p' q'.\nProof.\n    by path_induction.\nQed.\n\nLemma ap011_VV\n  : forall {A B C: Type} (f : A -> B -> C)\n           {a0 a1 : A} {b0 b1 : B}\n           (p : a0 = a1) (q : b0 = b1),\n    (ap011 f p q)^ = ap011 f p^ q^.\nProof.\n  intros. destruct p. destruct q. reflexivity.\nDefined.\n\nDefinition double_pathover {A B : Type} (P : A -> B -> Type)\n           {a a' : A} (p : a = a')\n           {b b' : B} (q : b = b')\n           (c : P a b) (c' : P a' b') : Type.\nProof.\n  destruct p,q. exact (c = c').\nDefined.\n\nDefinition double_pathover_to_path {A B : Type} (P : A -> B -> Type)\n           {a a' : A} (p : a = a')\n           {b b' : B} (q : b = b')\n           (c : P a b) (c' : P a' b')\n  : double_pathover P p q c c' ->\n    transport (uncurry P) (path_prod (a,b) (a',b') p q) c = c'.\nProof.\n  destruct p, q. exact idmap.\nDefined.\n\nDefinition path_to_double_pathover {A B : Type} (P : A -> B -> Type)\n           {a a' : A} (p : a = a')\n           {b b' : B} (q : b = b') (c : P a b) (c' : P a' b')\n  : transport (uncurry P) (path_prod (a, b) (a', b') p q) c = c' ->\n    double_pathover P p q c c'.\nProof.\n  destruct p. destruct q. exact idmap.\nDefined.\n\n\nLemma path_arrow_V {A B : Type} {f g : A -> B} (H : f == g) :\n  path_arrow g f (fun a => (H a)^) = (path_arrow f g H)^.\nProof.\n  transitivity (path_arrow f g (ap10 (path_forall _ _ H)))^.\n  - transitivity (path_arrow g f (fun a => (ap10 (path_forall _ _ H) a)^)).\n    + apply (ap (path_arrow g f)). apply path_forall.\n      intro a. apply (ap inverse). apply inverse. apply (ap10_path_arrow).\n    +  destruct (path_forall f g H). simpl.\n       destruct (path_forall _ _ (ap10_1 (f:= f)))^.\n       destruct (path_arrow_1 f)^. reflexivity.\n  - apply (ap inverse). apply (ap (path_arrow f g)). apply (path_forall _ _ (ap10_path_arrow f g H)).\nDefined.\n\nDefinition path_prod_VV {A B : Type} (z z' : A*B) (p1 : fst z = fst z') (p2 : snd z = snd z') :\n  path_prod z' z p1^ p2^ = (path_prod z z' p1 p2)^.\nProof.\n  destruct z as [z1 z2]. destruct z' as [z1' z2']. simpl in *. destruct p1, p2. reflexivity.\nDefined.\n\n\n\nDefinition path_triple_prod {A B C : Type} (a1 a2 : A * (B * C)) :\n  (fst a1 = fst a2) * ((fst (snd a1) = fst (snd a2)) * (snd (snd a1) = snd (snd a2))) -> a1 = a2.\nProof.\n  intros [p [q r]].\n  apply (path_prod a1 a2 p (path_prod (_,_) (_,_) q r)).\nDefined.\n\nDefinition equiv_path_triple_prod {A B C : Type} (a1 a2 : A * (B * C)) :\n  (fst a1 = fst a2) * ((fst (snd a1) = fst (snd a2)) * (snd (snd a1) = snd (snd a2))) <~> a1 = a2.\nProof.\n  srapply (@equiv_adjointify _ _ (path_triple_prod a1 a2)).\n  - intro p.\n    exact (ap fst p, (ap fst (ap snd p), (ap snd (ap snd p)))).\n  - intros []. reflexivity.\n  - intros [p [q r]].\n    destruct a2 as [a2 [b2 c2]]. simpl in *.\n    destruct p,q,r. reflexivity.\nDefined.\n\n\n\n", "meta": {"author": "kalfsvag", "repo": "group_completions", "sha": "cc65e902a68dbb6dc05315651dce3064704a9815", "save_path": "github-repos/coq/kalfsvag-group_completions", "path": "github-repos/coq/kalfsvag-group_completions/group_completions-cc65e902a68dbb6dc05315651dce3064704a9815/path_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6705850223521721}}
{"text": "(* http://www.cse.chalmers.se/research/group/logic/TypesSS05/resources/coq/CoqArt/contents.html *)\n\n(* Chapter 3 *)\n(* Section 3.1 *)\n\nRequire Import Arith.\nRequire Import ZArith.\nRequire Import Bool.\n\nSection Minimal_propositional_logic.\n\n  Variables P Q R T : Prop.\n\n  Theorem imp_trans_auto : (P -> Q) -> (Q -> R) -> P -> R.\n  Proof.\n    auto.\n  Qed.\n\n  Theorem imp_trans : (P -> Q) -> (Q -> R) -> P -> R.\n  Proof.\n    intros H H' p.\n    apply H'.\n    apply H.\n    exact p.\n  Qed.\n\n  Print imp_trans_auto.\n  Print imp_trans.\n\n(* Section 3.2 *)\n\n  Section example_of_assumption.\n    Hypothesis H : P -> Q -> R.\n\n    Lemma L1 : P -> Q -> R.\n    Proof.\n      assumption.\n    Qed.\n  End example_of_assumption.\n\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\n  Theorem delta2 : (P -> P -> Q) -> P -> Q.\n  Proof (fun (H : P -> P -> Q) (p:P) => H p p).\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_auto : (P -> Q -> R) -> (P -> Q) -> (P -> R).\n  Proof.\n    auto.\n  Qed.\n  Print imp_dist_auto.\n\n  Theorem imp_dist : (P -> Q -> R) -> (P -> Q) -> (P -> R).\n  Proof.\n    intros H H' p.\n    apply H.\n    - exact p.\n    - exact (H' p).\n  Qed.\n  \n  Theorem K : P -> Q -> P.\n  Proof.\n    intros p q.\n    exact p.\n  Qed.\n\n(* Section 3.3 *)\n\n(* Exercise 3.2 *)\n\n  Lemma id_P : P -> P.\n  Proof.\n    intro p.\n    exact p.\n  Qed.\n  \n  Lemma id_PP : (P -> P) -> (P -> P).\n  Proof.\n    intro p.\n    exact p.\n  Qed.\n\n  Lemma imp_trans' : (P -> Q) -> (Q -> R) -> P -> R.\n  Proof.\n    intros Hpq Hqr p.\n    apply Hqr.\n    apply Hpq.\n    exact p.\n  Qed.\n\n  Lemma imp_perm : (P -> Q -> R) -> (Q -> P -> R).\n  Proof.\n    intros Hpqr q p.\n    apply Hpqr.\n    - exact p.\n    - exact q.\n  Qed.\n\n  Lemma ignore_Q : (P -> R) -> P -> Q -> R.\n  Proof.\n    intros Hpr p q.\n    apply Hpr.\n    exact p.\n  Qed.\n\n  Lemma delta_imp : (P -> P -> Q) -> P -> Q.\n  Proof.\n    intros Hppq p.\n    apply Hppq.\n    - exact p.\n    - exact p.\n  Qed.\n\n  Lemma delta_impR : (P -> Q) -> (P -> P -> Q).\n  Proof.\n    intros Hpq p1 p2.\n    apply Hpq.\n    exact p1.\n  Qed.\n\n  Lemma diamond : (P -> Q) -> (P -> R) -> (Q -> R -> T) -> P -> T.\n  Proof.\n    intros Hpq Hpr Hqrt p.\n    apply Hqrt.\n    - apply Hpq.\n      exact p.\n    - apply Hpr.\n      exact p.\n  Qed.\n\n  Lemma weak_peirce : ((((P -> Q) -> P) -> P) -> Q) -> Q.\n  Proof.\n    intro H0.\n    apply H0.\n    intro H1.\n    apply H1.\n    intro p.\n    apply H0.\n    intro H2.\n    exact p.\n  Qed.\n    \n\n(* Section 3.4*)\n\n  Definition unreliable : (nat -> bool) -> (nat -> bool) -> nat -> bool.\n    intros f1 f2.\n    assumption.\n  Defined.\n  Print unreliable.\n  Eval compute in (unreliable (fun n => true) (fun n => false) 45).\n  Opaque unreliable.\n  Eval compute in (unreliable (fun n => true) (fun n => false) 45).\n\n(* Section 3.5 *)\n\n  Section proof_of_triple_impl.\n    Hypothesis H : ((P -> Q) -> Q) -> Q.\n    Hypothesis p : P.\n\n    Lemma Rem : (P -> Q) -> Q.\n    Proof (fun H0 : P -> Q => H0 p).\n\n    Theorem triple_impl : Q.\n    Proof (H Rem).\n  End proof_of_triple_impl.\n  Print Rem.\n  Print triple_impl.\n\n(* Section 3.6 *)\n\n  Theorem then_example : P -> Q -> (P -> Q -> R) -> R.\n  Proof.\n    intros p q Hpq.\n    apply Hpq; assumption.\n  Qed.\n\n  Theorem triple_impl_one_go : (((P -> Q) -> Q) -> Q) -> P -> Q.\n  Proof.\n    intros H p; apply H; intro H0; apply H0; assumption.\n  Qed.\n\n  Theorem compose_example : (P -> Q -> R) -> (P -> Q) -> P -> R.\n  Proof.\n    intros Hpqr Hpq p.\n    apply Hpqr; [assumption | apply Hpq; assumption].\n  Qed.\n\n  Theorem orelse_example : (P -> Q) -> R -> ((P -> Q) -> R -> (T -> Q) -> T) -> T.\n  Proof.\n    intros Hpq r H.\n    apply H;(assumption || intro H1).\n  Abort.\n\n(* Exercise 3.3 - TODO *)\n\nLemma id_P_1 : P -> P.\nProof.\n  intros p; assumption.\nQed.\n\nLemma id_PP_1 : (P -> P) -> (P -> P).\nProof.\n  intros Hpp p; assumption.\nQed.\n\nLemma imp_trans_1 : (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n  intros Hpq Hqr p; apply Hqr; apply Hpq; assumption.\nQed.\n\nLemma imp_perm_1 : (P -> Q -> R) -> (Q -> P -> R).\nProof.\n  intros Hpqr q p; apply Hpqr; assumption.\nQed.\n\nLemma ignore_Q_1 : (P -> R) -> P -> Q -> R.\nProof.\n  intros Hpr p q; apply Hpr; assumption.\nAbort.\n\nLemma delta_imp_1 : (P -> P -> Q) -> P -> Q.\nProof.\n  intros Hppq p; apply Hppq; assumption.\nQed.\n\nLemma delta_impR_1 : (P -> Q) -> (P -> P -> Q).\nProof.\n  intros Hpq p0 p1; apply Hpq; assumption.\nQed.\n\nLemma diamond_1 : (P -> Q) -> (P -> R) -> (Q -> R -> T) -> P -> T.\nProof.\n  intros Hpq Hpr Hqrt p; apply Hqrt; (apply Hpr || apply Hpq); assumption.\nQed.\n\nLemma weak_peirce_1 : ((((P -> Q) -> P) -> P) -> Q) -> Q.\nProof.\n  auto. (*TODO*)\nQed.\n\n(* Section 3.7 *)\n\n  Section section_for_cut_example.\n    Hypotheses\n      (H : P -> Q)\n      (H0 : Q -> R)\n      (H1 : (P -> R) -> T -> Q)\n      (H2 : (P -> R) -> T).\n    Theorem cut_example : Q.\n    Proof.\n      cut (P -> R).\n      intro H3.\n      - apply H1; [assumption | apply H2; assumption ].\n      - intro p.\n        apply H0.\n        apply H.\n        exact p.\n    Qed. \n    Print cut_example.\n  End section_for_cut_example.\n\n(* Exercise 3.5 *)\n\nEnd Minimal_propositional_logic.\n\n(* Section 3.9 *)\n\nPrint imp_dist.\n\nSection using_imp_dict.\n  Variables (P1 P2 P3 : Prop).\n  Check (imp_dist P1 P2 P3).\nEnd using_imp_dict.\n\n", "meta": {"author": "andorp", "repo": "LearningCoq", "sha": "5a1f7582853ec033f952a710017e5888b1edea89", "save_path": "github-repos/coq/andorp-LearningCoq", "path": "github-repos/coq/andorp-LearningCoq/LearningCoq-5a1f7582853ec033f952a710017e5888b1edea89/CoqArt/Chapter3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.6705850122224617}}
{"text": "Require Import Coq.Strings.String.\n\nInductive exp : Type :=\n  | num : nat -> exp\n  | var : string -> exp\n  | plus : exp -> exp -> exp\n  | minus : exp -> exp -> exp.\n\nDefinition state : Type := string -> nat.\n\nFixpoint eval (s : state) (e : exp) : nat := \n  match e with\n  | num n => n\n  | var v => s v\n  | plus lhs rhs => eval s lhs + eval s rhs\n  | minus lhs rhs => eval s lhs - eval s rhs\n  end.\n\nDefinition empty : state := fun v => 0.\n\nDefinition update (v : string) (n : nat) (s : state) : state :=\n  fun v' => if eqb v v' then n else s v.\n\nTheorem putGet (v : string) (n : nat) (s : state) : (update v n s) v = n.\nProof.\n  unfold update. rewrite eqb_refl. trivial.\nQed.\n\nTheorem getPut (v : string) (s : state) : (update v (s v) s) v = (s v).\nProof.\n  unfold update. rewrite eqb_refl. trivial.\nQed.\n\nTheorem putPut (v : string) (n1 : nat) (n2 : nat) (s : state) \n  : (update v n2 (update v n1 s)) v = n2.\nProof.\n  unfold update. rewrite eqb_refl. trivial.\nQed.\n\nInductive even : nat -> Prop :=\n  | ev0 : even 0\n  | evS (n : nat) (H : even n) : even (S (S n)).\n\nExample even4 :\n  even 4.\nProof.\n  apply evS.\n  apply evS.\n  apply ev0.\nQed.", "meta": {"author": "Anabra", "repo": "Formal-Semantics", "sha": "e72f9999aae6ee5cb7eeffc0d8619db7cebecbc1", "save_path": "github-repos/coq/Anabra-Formal-Semantics", "path": "github-repos/coq/Anabra-Formal-Semantics/Formal-Semantics-e72f9999aae6ee5cb7eeffc0d8619db7cebecbc1/exp_op_sem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.6705850036412494}}
{"text": "Require Import Arith List.\nRequire Import CpdtTactics.\nRequire Import MoreSpecif.\n\nLocal Open Scope specif.\n\nModule P1.\n  Definition compare : forall n m : nat, {n <= m} + {n > m}.\n  Proof.\n    refine (fix cmp (n m : nat) : {n <= m} + {n > m} :=\n              match n with\n              | O => Yes\n              | S n' => match m with\n                        | O => No\n                        | S m' => Reduce (cmp n' m')\n                        end\n              end); omega.\n  Defined.\nEnd P1.\n\nModule P2.\n  Definition var := nat.\n\n  Inductive prop : Set :=\n  | Var : var -> prop\n  | Not : prop -> prop\n  | Conj : prop -> prop -> prop\n  | Disj : prop -> prop -> prop.\n\n  Fixpoint denote (U : var -> bool) (e : prop) : Prop :=\n    match e with\n    | Var x => if U x then True else False\n    | Not p => ~ denote U p\n    | Conj p1 p2 => denote U p1 /\\ denote U p2\n    | Disj p1 p2 => denote U p1 \\/ denote U p2\n    end.\n\n  Definition bool_true_dec : forall b, {b = true} + {b = true -> False}.\n  Proof.\n    refine (fun b => match b with\n                     | true => Yes\n                     | false => No\n                     end); crush.\n  Defined.\n\n  Definition decide : forall (U : var -> bool) (p : prop), {denote U p} + {~ denote U p}.\n  Proof.\n    induction p; crush.\n    destruct (U v); crush.\n  Defined.\n\n  Definition negate : forall p, {p' | forall U, denote U p <-> ~ denote U p'}.\n  Proof.\n    refine (fix neg p : {p' | forall U, denote U p <-> ~ denote U p'} :=\n              match p with\n              | Var x => [Not (Var x)]\n              | Not p' => [p']\n              | Conj p1 p2 => (p1' <== neg p1;\n                               p2' <== neg p2;\n                               [Disj p1' p2'])\n              | Disj p1 p2 => (p1' <== neg p1;\n                               p2' <== neg p2;\n                               [Conj p1' p2'])\n              end); intros; simpl.\n    destruct (U x); crush.\n    crush.\n    rewrite _H. rewrite _H0.\n    intuition.\n    rewrite _H. rewrite _H0.\n    intuition.\n    destruct (decide U p1'); intuition.\n  Defined.\nEnd P2.\n", "meta": {"author": "eldargab", "repo": "cpdt", "sha": "a7b41081e90e245014b4f4918c0a3837864bec56", "save_path": "github-repos/coq/eldargab-cpdt", "path": "github-repos/coq/eldargab-cpdt/cpdt-a7b41081e90e245014b4f4918c0a3837864bec56/Subset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145053, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6705316279921368}}
{"text": "Require Import Vector.\nRequire Import Arith.\nRequire Import Bool.Bvector.\n(* Try to represent bool function as list of result, \nfor example conj will represent like {0, 0, 0, 1} *)\n\nDefinition BoolFunN (n: nat) := t Prop (2^n).\n\nInductive closClass (n: nat): Type := \n| PreservesFalse (x: BoolFunN n)\n| PreservesTrue (x: BoolFunN n)\n| SelfDual (x: BoolFunN n)\n| Monotonous (x: BoolFunN n)\n| Linear (x: BoolFunN n) .\n\nDefinition сompose {BoolFun} (f : BoolFun -> BoolFun) (g: BoolFun -> BoolFun) :=\n  fun x: BoolFun => g (f x).\n\nDefinition BoolFun2 (x: t Prop 4) := BoolFunN 2.\n\nCheck BoolFun2.\n\nCheck t Prop.\n\nDefinition conj := BoolFun2 ([False ; False ; False ; True ]).\n\nCheck [False ; False ; False ; True ].\n\nCheck conj.\n\nDefinition IsPreservesFalseFunc (n: nat) (f : (BoolFunN n)): Prop :=\n  match f with\n    | True :: t => False\n    | _ => True\n    (*| False :: t => True*)\nend.\n\nEval compute in (IsPreservesFalseFunc 2 [False ; False ; False ; True ]).\n\n\n\nDefinition IsPreservesTrueFunc (n: nat) (f : (BoolFunN n)): Prop :=\n  match f with\n    | [] => False (* Strange case*)\n    | h::t => if List.last (to_list t) false then True else False\nend.\n\nImport Lists.List.\n\nFixpoint IsListSelfDual(v p : list bool): Prop :=  \n  match v, p with \n  | Lists.List.nil, Lists.List.nil => True\n  | h::t, f::g => if eqb h f then False else  IsListSelfDual t g\n  | _, _ => False\nend.\n\nDefinition IsSelfDualFunc (n: nat) (f : (BoolFunN n)) : Prop := let x := to_list f in IsListSelfDual x (rev x).\n\n\nDefinition getComparableSet (n: nat) : list (nat * nat) :=\n  match n with\n  | 1 => (cons (0 , 1) nil)\n  | 2 => (cons (0 , 1) (cons (1 , 2)  (cons (2 , 3) nil) ))\n  | 3 => (cons (0 , 1) (cons (0 , 2)  (cons (0 , 4) ( cons (1 ,3) ( cons (1,5) \n( cons (2, 3) ( cons (2, 6) ( cons (3, 7)( cons (4 ,5)( cons (4, 6) \n(cons (5,7) ( cons (6, 7) nil))))))) )))))\n  | _ => nil\n  end.\n\nDefinition leBool (a b : bool) : bool :=\n  match a, b with\n  | true, false => false\n  | _, _ => true\n  end.\n\n\nFixpoint isMonotoniusFuncHelp {n: nat} (f : (BoolFunN n)) ( comparation: list (nat * nat)) : Prop :=\n  let fl := to_list f in match comparation with\n  | List.nil => True\n  | h::t => if  leBool (nth (fst h) fl false) (nth (snd h) fl false)  then isMonotoniusFuncHelp f t  else False\n  end.\n\nDefinition isMonotoniusFunc (n: nat) (f : (BoolFunN n)) : Prop := isMonotoniusFuncHelp f (getComparableSet n).\n \nEval compute in (IsPreservesFalseFunc 2 conj).\n(* \nКак применять эти функции????\nCheck isMonotoniusFunc 2 conj - не работает.\nОпределит линейность, ввести понятие системы функций, \nнаписать проверки на на не принадлежность к классам для системы функций,\nтогда теорема о полноте: T0 -> T1 -> S -> M -> L -> Full.\nА проверка конкретной системы будет ??????*)\n\n", "meta": {"author": "psttf", "repo": "dm-ml-coq", "sha": "83df1e9482bfadbca8ac0a34117f78ce43f90742", "save_path": "github-repos/coq/psttf-dm-ml-coq", "path": "github-repos/coq/psttf-dm-ml-coq/dm-ml-coq-83df1e9482bfadbca8ac0a34117f78ce43f90742/mainv2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.6705030766490923}}
{"text": "(** * Encoding terms, formulas and proofs *)\n\nRequire Import Arith.\nRequire Import fol.\nRequire Import folProof.\nRequire Import cPair.\n\nSection Code_Term_Formula_Proof.\n\nVariable L : Language.\nVariable codeF : Functions L -> nat.\nVariable codeR : Relations L -> nat.\nHypothesis codeFInj : \n  forall f g : Functions L, codeF f = codeF g -> f = g.\nHypothesis codeRInj :\n  forall R S : Relations L, codeR R = codeR S -> R = S.\n\nLet Formula := Formula L.\nLet Formulas := Formulas L.\nLet System := System L.\nLet Term := Term L.\nLet Terms := Terms L.\nLet Prf := Prf L.\nLet SysPrf := SysPrf L.\n\nFixpoint codeTerm (t : Term) : nat :=\n  match t with\n  | var n => cPair 0 n\n  | apply f ts => cPair (S (codeF f)) (codeTerms _ ts)\n  end\n \n with codeTerms (n : nat) (ts : Terms n) {struct ts} : nat :=\n  match ts with\n  | Tnil => 0\n  | Tcons n t ss => S (cPair (codeTerm t) (codeTerms n ss))\n  end.\n\nLemma codeTermInj : \n  forall t s : Term, codeTerm t = codeTerm s -> t = s.\nProof.\n  intro t; elim t using Term_Terms_ind\n    with (P0 := fun (n : nat) (ts : fol.Terms L n) =>\n                  forall ss : Terms n, \n                    codeTerms n ts = codeTerms n ss -> ts = ss).\n  - (* variables *) intros n s H; destruct s.\n    + simpl in H; apply cPairInj2 in H; now subst. \n    + simpl in H.\n      assert (H0: 0 = S (codeF f)) by (eapply cPairInj1; apply H). \n      discriminate H0.\n  - (* applications *) intros f t0 H s H0; destruct s.\n    + simpl in H0.\n      assert (H1: S (codeF f) = 0) by (eapply cPairInj1; apply H0).\n      discriminate H1.\n    + simpl in H0; assert (H1: f = f0). \n       { apply codeFInj, eq_add_S; eapply cPairInj1; apply H0. }\n       cut\n         (cPair (S (codeF f)) (codeTerms (arityF L f) t0) =\n            cPair (S (codeF f0)) \n              (codeTerms (arityF L f0) t1)).\n       * generalize t1; rewrite <- H1; clear H1 H0 t1.\n         intros t1 H0; rewrite (H t1).\n         -- reflexivity.\n         -- eapply cPairInj2.\n            apply H0.\n       * apply H0.\n  - (* empty sequence *)  intros ss H; rewrite <- nilTerms; reflexivity.\n  - (* non-empty sequence *)\n    intros n t0 H t1 H0 ss H1; induction (consTerms L n ss).\n    destruct x as (a, b); simpl in p; rewrite <- p.\n    rewrite <- p in H1; simpl in H1; rewrite (H a).\n    + rewrite (H0 b).\n      * reflexivity.\n      * eapply cPairInj2; apply eq_add_S, H1. \n    + eapply cPairInj1.\n      apply eq_add_S, H1.\nQed.\n\nLemma codeTermsInj :\n forall (n : nat) (ts ss : Terms n),\n codeTerms n ts = codeTerms n ss -> ts = ss.\nProof.\n  intros n ts; induction ts as [| n t ts Hrects].\n  - intros ss H; now rewrite <- (nilTerms L ss).\n  - intros ss H.\n    destruct (consTerms L n ss) as [(a,b) p].\n    simpl in p; rewrite <- p in H |- *. \n    rewrite (Hrects b).\n    + rewrite (codeTermInj t a).\n      * reflexivity.\n      * eapply cPairInj1.\n        apply eq_add_S, H. \n    + eapply cPairInj2.\n      apply eq_add_S, H. \nQed.\n\nFixpoint codeFormula (f : Formula) : nat :=\n  match f with\n  | equal t1 t2 => cPair 0 (cPair (codeTerm t1) (codeTerm t2))\n  | impH f1 f2 => cPair 1 (cPair (codeFormula f1) (codeFormula f2))\n  | notH f1 => cPair 2 (codeFormula f1)\n  | forallH n f1 => cPair 3 (cPair n (codeFormula f1))\n  | atomic R ts => cPair (4+(codeR R)) (codeTerms _ ts)\n  end.\n\n\nLemma codeFormulaInj :\n  forall f g : Formula, codeFormula f = codeFormula g -> f = g.\nProof.\n  intro f; \n    induction f as [t t0| r t| f1 Hrecf1 f0 Hrecf0| f Hrecf| n f Hrecf]; intros;\n    [ destruct g as [t1 t2| r t1| f f0| f| n f]\n    | destruct g as [t0 t1| r0 t0| f f0| f| n f]\n    | destruct g as [t t0| r t| f f2| f| n f]\n    | destruct g as [t t0| r t| f0 f1| f0| n f0]\n    | destruct g as [t t0| r t| f0 f1| f0| n0 f0] ];\n    (simpl in H;\n     try\n       match goal with\n       | h:(cPair ?X1 ?X2 = cPair ?X3 ?X4) |- _ =>\n           assert  False by ( cut (X1 = X3);\n           [ discriminate | eapply cPairInj1; apply h ]); \n           contradiction\n       end).\n  - (* equality between terms *) \n    rewrite (codeTermInj t t1).\n    + rewrite (codeTermInj t0 t2).\n      * reflexivity.\n      * eapply cPairInj2.\n        eapply cPairInj2.\n        apply H.\n    + eapply cPairInj1.\n      eapply cPairInj2.\n      apply H.\n  - (* atomic formulas *) assert (r = r0).\n    { apply codeRInj.\n      do 4 apply eq_add_S.\n      eapply cPairInj1.\n      apply H.\n    } \n    cut  (cPair (S (S (S (S (codeR r)))))\n            (codeTerms (arityR L r) t) =\n            cPair (S (S (S (S (codeR r0)))))\n              (codeTerms (arityR L r0) t0)).\n    + generalize t0; rewrite <- H0; clear H0 H t0.\n      intros t0 H; rewrite (codeTermsInj _ t t0).\n      * reflexivity.\n      * eapply cPairInj2; apply H.\n    + apply H.\n  - (* implication *)\n    rewrite (Hrecf1 f).\n    + rewrite (Hrecf0 f2).\n      * reflexivity.\n      * eapply cPairInj2.\n        eapply cPairInj2.\n        apply H.\n    + eapply cPairInj1.\n      eapply cPairInj2; apply H.\n  - (* negation *) rewrite (Hrecf f0).\n    reflexivity.\n    eapply cPairInj2.\n    apply H.\n  - (* universal quantification *) \n    rewrite (Hrecf f0).\n    + replace n0 with n.\n      * reflexivity.\n      * eapply cPairInj1.\n        eapply cPairInj2.\n        apply H.\n    + eapply cPairInj2.\n      eapply cPairInj2.\n      apply H.\nQed.\n\nFixpoint codePrf (Z : Formulas) (f : Formula) (prf : Prf Z f) {struct prf} :\n nat :=\n  match prf with\n  | AXM A => cPair 0 (codeFormula A)\n  | MP Axm1 Axm2 A B rec1 rec2 =>\n      cPair 1\n        (cPair\n           (cPair (cPair 1 (cPair (codeFormula A) (codeFormula B)))\n              (codePrf _ _ rec1)) (cPair (codeFormula A) (codePrf _ _ rec2)))\n  | GEN Axm A v _ rec =>\n      cPair 2 (cPair v (cPair (codeFormula A) (codePrf _ _ rec)))\n  | IMP1 A B => cPair 3 (cPair (codeFormula A) (codeFormula B))\n  | IMP2 A B C =>\n      cPair 4 (cPair (codeFormula A) (cPair (codeFormula B) (codeFormula C)))\n  | CP A B => cPair 5 (cPair (codeFormula A) (codeFormula B))\n  | FA1 A v t => cPair 6 (cPair (codeFormula A) (cPair v (codeTerm t)))\n  | FA2 A v _ => cPair 7 (cPair (codeFormula A) v)\n  | FA3 A B v => cPair 8 (cPair (codeFormula A) (cPair (codeFormula B) v))\n  | EQ1 => cPair 9 0\n  | EQ2 => cPair 10 0\n  | EQ3 => cPair 11 0\n  | EQ4 r => cPair 12 (codeR r)\n  | EQ5 f => cPair 13 (codeF f)\n  end.\n\nLemma codePrfInjAxm :\n forall (a b : Formula) (A B : Formulas) (p : Prf A a) (q : Prf B b),\n codePrf A a p = codePrf B b q -> A = B.\nProof.\n  intros a b A B p; generalize B b; clear B b.\n  induction p\n    as\n    [A|\n      Axm1 Axm2 A B p1 Hrecp1 p0 Hrecp0|\n      Axm A v n p Hrecp|\n      A B|\n      A B C|\n      A B|\n      A v t|\n      A v n|\n      A B v|\n    |\n    |\n    |\n      R|\n      f]; intros;\n    [ destruct q\n      as\n      [A0|\n        Axm1 Axm2 A0 B p p0|\n        Axm A0 v n p|\n        A0 B|\n        A0 B C|\n        A0 B|\n        A0 v t|\n        A0 v n|\n        A0 B v|\n      |\n      |\n      |\n        R|\n        f]\n    | destruct q\n      as\n      [A0|\n        Axm0 Axm3 A0 B0 p p2|\n        Axm A0 v n p|\n        A0 B0|\n        A0 B0 C|\n        A0 B0|\n        A0 v t|\n        A0 v n|\n        A0 B0 v|\n      |\n      |\n      |\n        R|\n        f]\n    | destruct q\n      as\n      [A0|\n        Axm1 Axm2 A0 B p0 p1|\n        Axm0 A0 v0 n0 p0|\n        A0 B|\n        A0 B C|\n        A0 B|\n        A0 v0 t|\n        A0 v0 n0|\n        A0 B v0|\n      |\n      |\n      |\n        R|\n        f]\n    | destruct q\n      as\n      [A0|\n        Axm1 Axm2 A0 B0 p p0|\n        Axm A0 v n p|\n        A0 B0|\n        A0 B0 C|\n        A0 B0|\n        A0 v t|\n        A0 v n|\n        A0 B0 v|\n      |\n      |\n      |\n        R|\n        f]\n    | destruct q\n      as\n      [A0|\n        Axm1 Axm2 A0 B0 p p0|\n        Axm A0 v n p|\n        A0 B0|\n        A0 B0 C0|\n        A0 B0|\n        A0 v t|\n        A0 v n|\n        A0 B0 v|\n      |\n      |\n      |\n        R|\n        f]\n    | destruct q\n      as\n      [A0|\n        Axm1 Axm2 A0 B0 p p0|\n        Axm A0 v n p|\n        A0 B0|\n        A0 B0 C|\n        A0 B0|\n        A0 v t|\n        A0 v n|\n        A0 B0 v|\n      |\n      |\n      |\n        R|\n        f]\n    | destruct q\n      as\n      [A0|\n        Axm1 Axm2 A0 B p p0|\n        Axm A0 v0 n p|\n        A0 B|\n        A0 B C|\n        A0 B|\n        A0 v0 t0|\n        A0 v0 n|\n        A0 B v0|\n      |\n      |\n      |\n        R|\n        f]\n    | destruct q\n      as\n      [A0|\n        Axm1 Axm2 A0 B p p0|\n        Axm A0 v0 n0 p|\n        A0 B|\n        A0 B C|\n        A0 B|\n        A0 v0 t|\n        A0 v0 n0|\n        A0 B v0|\n      |\n      |\n      |\n        R|\n        f]\n    | destruct q\n      as\n      [A0|\n        Axm1 Axm2 A0 B0 p p0|\n        Axm A0 v0 n p|\n        A0 B0|\n        A0 B0 C|\n        A0 B0|\n        A0 v0 t|\n        A0 v0 n|\n        A0 B0 v0|\n      |\n      |\n      |\n        R|\n        f]\n    | destruct q\n      as\n      [A|\n        Axm1 Axm2 A B p p0|\n        Axm A v n p|\n        A B|\n        A B C|\n        A B|\n        A v t|\n        A v n|\n        A B v|\n      |\n      |\n      |\n        R|\n        f]\n    | destruct q\n      as\n      [A|\n        Axm1 Axm2 A B p p0|\n        Axm A v n p|\n        A B|\n        A B C|\n        A B|\n        A v t|\n        A v n|\n        A B v|\n      |\n      |\n      |\n        R|\n        f]\n    | destruct q\n      as\n      [A|\n        Axm1 Axm2 A B p p0|\n        Axm A v n p|\n        A B|\n        A B C|\n        A B|\n        A v t|\n        A v n|\n        A B v|\n      |\n      |\n      |\n        R|\n        f]\n    | destruct q\n      as\n      [A|\n        Axm1 Axm2 A B p p0|\n        Axm A v n p|\n        A B|\n        A B C|\n        A B|\n        A v t|\n        A v n|\n        A B v|\n      |\n      |\n      |\n        R0|\n        f]\n    | destruct q\n      as\n      [A|\n        Axm1 Axm2 A B p p0|\n        Axm A v n p|\n        A B|\n        A B C|\n        A B|\n        A v t|\n        A v n|\n        A B v|\n      |\n      |\n      |\n        R|\n        f0] ];\n    (simpl in H;\n     try\n       match goal with\n       | h:(cPair ?X1 ?X2 = cPair ?X3 ?X4) |- _ =>\n           assert False by (cut (X1 = X3);\n           [ discriminate | eapply cPairInj1; apply h ]); contradiction\n       end); try reflexivity.\n  - replace A0 with A.\n    + reflexivity.\n    + apply codeFormulaInj; eapply cPairInj2, H.\n  - replace Axm0 with Axm1.\n    + replace Axm3 with Axm2.\n      * reflexivity.\n      * eapply Hrecp0 with A0 p2.\n        do 3 eapply cPairInj2.\n        apply H.\n    + eapply Hrecp1 with (impH  A0 B0) p.\n      eapply cPairInj2.\n      eapply cPairInj1.\n      eapply cPairInj2.\n      apply H.\n  - eapply Hrecp with A0 p0.\n    do 3 eapply cPairInj2.\n    apply H.\nQed.\n\nDefinition codeImp (a b : nat) := cPair 1 (cPair a b).\n\nLemma codeImpCorrect :\n forall a b : Formula,\n codeImp (codeFormula a) (codeFormula b) = codeFormula (impH a b).\nProof. intros; reflexivity. Qed.\n\nDefinition codeNot (a : nat) := cPair 2 a.\n\nLemma codeNotCorrect :\n forall a : Formula, codeNot (codeFormula a) = codeFormula (notH a).\nProof. intros; reflexivity. Qed.\n\nDefinition codeForall (n a : nat) := cPair 3 (cPair n a).\n\nLemma codeForallCorrect :\n forall (n : nat) (a : Formula),\n codeForall n (codeFormula a) = codeFormula (forallH n a).\nProof.\n intros; reflexivity. Qed.\n\nDefinition codeOr (a b : nat) := codeImp (codeNot a) b.\n\nLemma codeOrCorrect :\n forall a b : Formula,\n codeOr (codeFormula a) (codeFormula b) = codeFormula (orH a b).\nProof. intros; reflexivity. Qed. \n\nDefinition codeAnd (a b : nat) := codeNot (codeOr (codeNot a) (codeNot b)).\n\nLemma codeAndCorrect :\n forall a b : Formula,\n codeAnd (codeFormula a) (codeFormula b) = codeFormula (andH a b).\nProof. intros; reflexivity. Qed. \n\nDefinition codeIff (a b : nat) := codeAnd (codeImp a b) (codeImp b a).\n\nLemma codeIffCorrect :\n forall a b : Formula,\n codeIff (codeFormula a) (codeFormula b) = codeFormula (iffH a b).\nProof. intros; reflexivity. Qed.\n\nEnd Code_Term_Formula_Proof.\n", "meta": {"author": "coq-community", "repo": "hydra-battles", "sha": "2d211e0b5030d5f77aaaf6366b01fc64ed998c61", "save_path": "github-repos/coq/coq-community-hydra-battles", "path": "github-repos/coq/coq-community-hydra-battles/hydra-battles-2d211e0b5030d5f77aaaf6366b01fc64ed998c61/theories/ordinals/Ackermann/code.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.670344228529152}}
{"text": "Require Import ZArith Lia Basics RelationClasses Program.\nRequire Import Flocq.IEEE754.Binary Flocq.Core.Defs Flocq.Core.Zaux.\nRequire Import ExtLib.Structures.Monads ExtLib.Data.Monads.OptionMonad.\nRequire Import Floats.\n\n\nOpen Scope Z.\n\n(* a basic float - a pair of two integers - mantissa and exponent *)\nDefinition bfloat := Flocq.Core.Defs.float radix2.\nDefinition BFloat := Flocq.Core.Defs.Float radix2.\n\n(** * converting between floats in the same cohort *)\n\n(* increase a given float's exponent by [de] *)\nDefinition inc_e (f : bfloat) (de : positive) : option bfloat :=\n  let '(m, e) := (Fnum f, Fexp f) in\n  let rm := two_power_pos de in\n  if (Zmod m rm =? 0)\n  then Some (BFloat (m / two_power_pos de) (e + Z.pos de))\n  else None.\n\n(* decrese a given float's exponent by [de] *)\nDefinition dec_e (f : bfloat) (de : positive) : bfloat :=\n  let '(m, e) := (Fnum f, Fexp f) in\n  let rm := two_power_pos de in\n  BFloat (m * two_power_pos de) (e - Z.pos de).\n\n(* shift (up or down) the exponent by [de] *)\nDefinition shift_e (f : bfloat) (de : Z) : option bfloat :=\n  match de with\n  | Z0 => Some f\n  | Z.pos pde => inc_e f pde\n  | Z.neg nde => Some (dec_e f nde)\n  end.\n\n(* set exponent to a given one *)\nDefinition set_e (f : bfloat) (e : Z) : option bfloat :=\n  shift_e f (e - Fexp f).\n\n(* binary length of a number *)\nDefinition Zdigits (m : Z) := Z.log2 (Z.abs m) + 1.\n\n(* shifting the binary length of the mantissa - *)\nDefinition inc_digits_m := dec_e.\nDefinition dec_digits_m := inc_e.\nDefinition shift_digits_m (f : bfloat) (ddm : Z) := shift_e f (- ddm).\nDefinition set_digits_m (f : bfloat) (dm : Z) := shift_digits_m f (dm - Zdigits (Fnum f)).\n\n(** * normalization *)\nDefinition normalize_float (prec emax : Z) (f : bfloat)\n  : option bfloat :=\n  let emin := 3 - emax - prec in\n  match set_e f emin with\n    | None => None\n    | Some f1 => if Zdigits (Fnum f1) <=? prec\n                 then Some f1\n                 else match set_digits_m f prec with\n                     | None => None\n                     | Some f2 => if andb\n                                       (emin <=? Fexp f2)\n                                       (Fexp f2 <=? emax - prec)\n                                  then Some f2\n                                  else None\n                     end\n  end.\n\n(* check if a mantissa-exponent pair is represntable in a format given by prec, emax *)\nDefinition can_convert_exactly (prec__target emax__target : Z) (m : positive) (e : Z) : bool :=\n  let f := BFloat (Z.pos m) e in\n  match normalize_float prec__target emax__target f with\n  | Some _ => true\n  | None => false\n  end.\n\nDefinition can_convert_float_to_float32 (v : float) : bool :=\n  match v with\n  | B754_finite _ m e _ => can_convert_exactly 24 128 m e\n  | _ => true\n  end.\n\nDefinition can_convert_float_to_float64 (v : float) : bool :=\n  match v with\n  | B754_finite _ m e _ => can_convert_exactly 53 1024 m e\n  | _ => true\n  end.\n\nSection Correctness.\n\n  (*\n   * Inspired by StructTact\n   * Source: github.com/uwplse/StructTact\n   *\n   * [break_match] looks for a [match] construct in the goal or some hypothesis,\n   * and destructs the discriminee, while retaining the information about\n   * the discriminee's value leading to the branch being taken. \n   *)\n  Ltac break_match :=\n    match goal with\n      | [ |- context [ match ?X with _ => _ end ] ] =>\n        match type of X with\n          | sumbool _ _ => destruct X\n          | _ => destruct X eqn:?\n        end\n      | [ H : context [ match ?X with _ => _ end ] |- _] =>\n        match type of X with\n          | sumbool _ _ => destruct X\n          | _ => destruct X eqn:?\n        end\n    end.\n\n  (* binary length of a positive number *)\n  Let digits := compose Z.succ log_inf.\n\n  (* closed form for Flocq's [digits2_pos] *)\n  Lemma digits2_pos_digits (m : positive) :\n    Z.pos (Digits.digits2_pos m) = digits m.\n  Proof.\n    induction m; simpl;\n      try rewrite Pos2Z.inj_succ, IHm; reflexivity.\n  Qed.\n  \n  (** ** Flocq's Binary.bounded rewritten in a form close to IEEE-754 *)\n  Lemma bounded_closed_form (prec emax : Z)\n        (prec_gt_0 : Flocq.Core.FLX.Prec_gt_0 prec) (Hmax : (prec < emax)%Z)\n        (m : positive) (e : Z) :\n    bounded prec emax m e = true\n    <->\n    or\n      (digits m < prec /\\ e = 3 - emax - prec)\n      (digits m = prec /\\ 3 - emax - prec <= e <= emax - prec).\n  Proof.\n    unfold FLX.Prec_gt_0, bounded, canonical_mantissa, FLT.FLT_exp in *.\n    rewrite Bool.andb_true_iff, Z.leb_le, <-Zeq_is_eq_bool, digits2_pos_digits.\n    remember (3 - emax - prec) as emin.\n    split; intro.\n    all: destruct (Z_lt_le_dec (digits m + e - prec) emin).\n    all: try rewrite Z.max_r in * by lia.\n    all: try rewrite Z.max_l in * by lia.\n    all: lia.\n  Qed.\n\n  Definition valid_float (prec emax : Z) (f : bfloat) :=\n    match (Fnum f) with\n    | Z0 => true\n    | Z.pos m => bounded prec emax m (Fexp f)\n    | Z.neg m => bounded prec emax m (Fexp f)\n    end.\n  \n  (** ** equality on floats with no jumps to Real *)\n  Definition float_eq (f1 : bfloat) (f2 : bfloat) : Prop :=\n    let '(m1, e1) := (Fnum f1, Fexp f1) in\n    let '(m2, e2) := (Fnum f2, Fexp f2) in\n    or\n      (e2 <= e1 /\\ m2 = m1 * 2 ^ (e1 - e2))\n      (e1 <= e2 /\\ m1 = m2 * 2 ^ (e2 - e1)).\n\n  Lemma float_eq_refl : Reflexive float_eq.\n  Proof.\n    unfold Reflexive; intro f.\n    unfold float_eq; left.\n    replace (Fexp f - Fexp f) with 0.\n    all: lia.\n  Qed.\n\n  Lemma float_eq_sym : Symmetric float_eq.\n  Proof.\n    unfold Symmetric, float_eq.\n    intros; destruct H; auto.\n  Qed.\n\n  Lemma Zpow_divide (b p1 p2 : Z) :\n    0 < b ->\n    0 <= p1 <= p2 ->\n    (b ^ p1 | b ^ p2).\n  Proof.\n    intros B P.\n    rewrite <-Z.mod_divide by (apply Z.pow_nonzero; lia).\n    replace p2 with ((p2 - p1) + p1) by lia.\n    rewrite Z.pow_add_r by lia.\n    apply Z_mod_mult.\n  Qed.\n\n  Lemma float_eq_trans : Transitive float_eq.\n  Proof.\n    unfold Transitive.\n    destruct x as [mx ex], y as [my ey], z as [mz ez].\n    unfold float_eq.\n    simpl.\n    intros XY YZ.\n    destruct XY as [XY | XY]; destruct YZ as [YZ | YZ].\n    all: destruct XY as [EXY MXY]; destruct YZ as [EYZ MYZ]; subst.\n    - left; split; [lia |].\n      rewrite <-Z.mul_assoc.\n      rewrite <-Z.pow_add_r; try lia.\n      replace (ex - ey + (ey - ez)) with (ex - ez) by lia.\n      reflexivity.\n    - destruct (Z.eq_dec ex ez); subst.\n      + (* ex = ez *)\n        apply Z.mul_reg_r in MYZ.\n        subst; left; split; [lia |].\n        rewrite Z.sub_diag; lia.\n        generalize (Z.pow_pos_nonneg 2 (ez - ey)); lia.\n      + destruct (Z_lt_le_dec ex ez).\n        * (* ex < ez *)\n          rename MYZ into H.\n          assert (H1 : ey <= ex < ez) by lia; clear EXY EYZ n l.\n          right; split; [lia |].\n          apply f_equal with (f := fun x => Z.div x (2 ^ (ex - ey))) in H.\n          rewrite Z_div_mult in H;\n            [| generalize (Z.pow_pos_nonneg 2 (ex - ey)); lia].\n          subst.\n          rewrite Z.divide_div_mul_exact;\n            [| apply Z.pow_nonzero; lia | apply Zpow_divide; lia].\n          replace (ez - ey) with ((ez - ex) + (ex - ey)) by lia.\n          rewrite Z.pow_add_r by lia.\n          rewrite Z.div_mul by (apply Z.pow_nonzero; lia).\n          reflexivity.\n        * (* ez < ex *)\n          rename MYZ into H.\n          assert (H1: ey <= ez < ex) by lia; clear EXY EYZ n l.\n          left; split; [lia |].\n          apply f_equal with (f := fun x => Z.div x (2 ^ (ez - ey))) in H.\n          rewrite Z_div_mult in H;\n            [| generalize (Z.pow_pos_nonneg 2 (ez - ey)); lia].\n          subst.\n          rewrite Z.divide_div_mul_exact;\n            [| apply Z.pow_nonzero; lia | apply Zpow_divide; lia].\n          replace (ex - ey) with ((ex - ez) + (ez - ey)) 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 ex ez); subst.\n      + (* ex = ez *)\n        left; split; [lia |].\n        rewrite Z.sub_diag; lia.\n      + destruct (Z_lt_le_dec ex ez).\n        * (* ex < ez *)\n          assert (H : ex < ez <= ey) by lia; clear EXY EYZ n l.\n          right; split; [lia |].\n          rewrite <-Z.mul_assoc.\n          rewrite <-Z.pow_add_r by lia.\n          replace (ey - ez + (ez - ex)) with (ey - ex) by lia.\n          reflexivity.\n        * (* ez < ex *)\n          assert (H: ez < ex <= ey) by lia; clear EXY EYZ n l.\n          left; split; [lia |].\n          rewrite <-Z.mul_assoc.\n          rewrite <-Z.pow_add_r by lia.\n          replace (ey - ex + (ex - ez)) with (ey - ez) by lia.\n          reflexivity.\n    - right; split; [lia |].\n      rewrite <-Z.mul_assoc.\n      rewrite <-Z.pow_add_r; try lia.\n      replace (ez - ey + (ey - ex)) with (ez - ex) by lia.\n      reflexivity.\n  Qed.\n\n  Definition float_eq_equivalence :=\n    Build_Equivalence float_eq float_eq_refl float_eq_sym float_eq_trans.\n\n  Definition not_zero (f : bfloat) := (Fnum f) <> 0.\n\n  Lemma not_zero_Zpos (m : positive) (e : Z) :\n    not_zero (BFloat (Z.pos m) e).\n  Proof. unfold not_zero. simpl. discriminate. Qed.\n\n  Lemma not_zero_eq (f1 f2 : bfloat) :\n    not_zero f1 ->\n    float_eq f1 f2 ->\n    not_zero f2.\n  Proof.\n    unfold not_zero, float_eq.\n    destruct f1 as [m1 e1], f2 as [m2 e2]; simpl.\n    intros NZ1 H.\n    destruct H; destruct H as [H1 H2]; subst.\n    - assert (0 < 2 ^ (e1 - e2)) by (apply Z.pow_pos_nonneg; lia).\n      apply Z.neq_mul_0.\n      lia.\n    - intros H; contradict NZ1.\n      subst; reflexivity.\n  Qed.\n\n  (** shifting the exponent results in a shifted exponent as expected *)\n  Lemma inc_e_correct (f1 : bfloat) (de : positive) {f2 : bfloat} :\n    inc_e f1 de = Some f2 ->\n    Fexp f2 = Fexp f1 + Z.pos de.\n  Proof.\n    unfold inc_e.\n    intro; break_match; inversion H; clear H.\n    reflexivity.\n  Qed.\n\n  Lemma dec_e_correct (f : bfloat) (de : positive) :\n    Fexp (dec_e f de) = Fexp f - Z.pos de.\n  Proof. reflexivity. Qed.\n\n  Lemma shift_e_correct (f1 : bfloat) (de : Z) {f2 : bfloat} :\n    shift_e f1 de = Some f2 ->\n    Fexp f2 = Fexp f1 + de.\n  Proof.\n    unfold shift_e; intro; break_match; inversion H; clear H.\n    lia.\n    apply inc_e_correct; assumption.\n    apply dec_e_correct.\n  Qed.\n\n  Lemma set_e_correct (f1 : bfloat) (e : Z) {f2 : bfloat} :\n    set_e f1 e = Some f2 ->\n    Fexp f2 = e.\n  Proof.\n    unfold set_e.\n    intro H.\n    apply shift_e_correct in H.\n    lia.\n  Qed.\n\n  (** shifting the exponent preserves the float's value *)\n  Lemma inc_e_eq (f1 : bfloat) (de : positive) {f2 : bfloat} :\n    inc_e f1 de = Some f2 ->\n    float_eq f1 f2.\n  Proof.\n    intros.\n    destruct f1 as [m1 e1], f2 as [m2 e2].\n    unfold inc_e in H; break_match; inversion H; clear H.\n    unfold float_eq.\n    simpl in *.\n    right.\n    replace (e1 + Z.pos de - e1) with (Z.pos de) by lia.\n    rewrite <-two_power_pos_equiv.\n    remember (two_power_pos de) as rm.\n    rewrite Z.eqb_eq in Heqb.\n    rewrite Z.mul_comm.\n    rewrite <-Z_div_exact_2 with (b := rm); try auto.\n    rewrite two_power_pos_equiv in Heqrm.\n    assert (0 < 2 ^ Z.pos de).\n    apply Z.pow_pos_nonneg.\n    all: try lia.\n    subst rm.\n    rewrite two_power_pos_equiv.\n    generalize (Z.pow_pos_nonneg 2 (Z.pos de)).\n    lia.\n  Qed.\n\n  Lemma dec_e_eq (f : bfloat) (de : positive) :\n    float_eq f (dec_e f de).\n  Proof.\n    destruct f as [m e].\n    unfold dec_e, float_eq.\n    simpl.\n    left.\n    replace (e - (e - Z.pos de)) with (Z.pos de) by lia.\n    rewrite two_power_pos_equiv.\n    split.\n    lia.\n    reflexivity.\n  Qed.\n\n  Lemma shift_e_eq (f1 : bfloat) (de : Z) {f2 : bfloat} :\n    shift_e f1 de = Some f2 ->\n    float_eq f1 f2.\n  Proof.\n    destruct de; simpl.\n    - intro H; inversion H; apply float_eq_refl.\n    - apply inc_e_eq.\n    - intro H; inversion H; apply dec_e_eq.\n  Qed.\n\n  Lemma set_e_eq (f1 : bfloat) (e : Z) {f2 : bfloat} :\n    set_e f1 e = Some f2 ->\n    float_eq f1 f2.\n  Proof.\n    unfold set_e.\n    apply shift_e_eq.\n  Qed.\n\n  Lemma Zdigits_mul_pow2 (m : Z) (d : positive) :\n    m <> 0 -> Zdigits (m * two_power_pos d) = Zdigits m + Z.pos d.\n  Proof.\n    intro.\n    rewrite two_power_pos_equiv.\n    unfold Zdigits.\n    rewrite Z.abs_mul, Z.abs_pow.\n    replace (Z.abs 2) with 2 by reflexivity.\n    remember (Z.abs m) as pm; remember (Z.pos d) as pd.\n    rewrite Z.log2_mul_pow2.\n    all: lia.\n  Qed.\n\n  Lemma Zabs_div_exact (a b : Z) :\n    b <> 0 ->\n    a mod b = 0 ->\n    Z.abs (a / b) = Z.abs a / Z.abs b.\n  Proof.\n    intros B AMB.\n    apply Zmod_divides in AMB; [| assumption ].\n    destruct AMB as [c AMB].\n    rewrite AMB at 1.\n    apply f_equal with (f := Z.abs) in AMB.\n    rewrite Z.abs_mul in AMB.\n    rewrite AMB.\n    rewrite Z.mul_comm. rewrite Z.div_mul.\n    rewrite Z.mul_comm. rewrite Z.div_mul.\n    all: lia.\n  Qed.\n\n  Lemma Zdigits_div_pow2 (m : Z) (d : positive) :\n    m <> 0 ->\n    m mod two_power_pos d = 0 ->\n    Zdigits (m / two_power_pos d) = Zdigits m - Z.pos d.\n  Proof.\n    intros M H.\n    unfold Zdigits.\n    rewrite Zabs_div_exact.\n    rewrite two_power_pos_equiv in *.\n    rewrite Z.abs_pow.\n    remember (Z.abs m) as pm; remember (Z.pos d) as pd.\n    apply Zmod_divides in H; destruct H.\n    subst m.\n    rewrite Z.abs_mul, Z.abs_pow in Heqpm.\n    replace (Z.abs 2) with 2 in * by reflexivity.\n    subst pm.\n    remember (Z.abs x) as px.\n    rewrite Z.mul_comm.\n    rewrite Z.div_mul.\n    rewrite Z.log2_mul_pow2.\n    all: subst.\n    all: try lia.\n    destruct (Z.eq_dec x 0); subst; lia.\n    destruct (Z.eq_dec (2 ^ Z.pos d) 0); [ rewrite e in M; lia | assumption ].\n    assert (m mod 2 ^ Z.pos d < 2 ^ Z.pos d); try lia.\n    apply Zmod_pos_bound.\n    apply Z.pow_pos_nonneg; lia.\n    rewrite two_power_pos_equiv; generalize (Z.pow_pos_nonneg 2 (Z.pos d)); lia.\n  Qed.\n\n  (** changing the mantissa's binary length results in an expected number of digits *)\n  Lemma inc_digits_m_correct (f : bfloat) (ddm : positive) :\n    not_zero f ->\n    Zdigits (Fnum (inc_digits_m f ddm)) = Zdigits (Fnum f) + Z.pos ddm.\n  Proof.\n    unfold inc_digits_m, dec_e; simpl.\n    apply Zdigits_mul_pow2.\n  Qed.\n\n  Lemma dec_digits_m_correct (f1 : bfloat) (ddm : positive) {f2 : bfloat} :\n    not_zero f1 ->\n    dec_digits_m f1 ddm = Some f2 ->\n    Zdigits (Fnum f2) = Zdigits (Fnum f1) - Z.pos ddm.\n  Proof.\n    destruct f1 as [m1 e1], f2 as [m2 e2].\n    unfold dec_digits_m, inc_e.\n    simpl; intros M H.\n    break_match; inversion H; clear H.\n    rewrite Z.eqb_eq in Heqb.\n    apply Zdigits_div_pow2; assumption.\n  Qed.\n\n  Lemma shift_digits_m_correct (f1 : bfloat) (ddm : Z) {f2 : bfloat} :\n    Fnum f1 <> 0 ->\n    shift_digits_m f1 ddm = Some f2 ->\n    Zdigits (Fnum f2) = Zdigits (Fnum f1) + ddm.\n  Proof.\n    unfold shift_digits_m, shift_e.\n    simpl; intros M H.\n    break_match; inversion H; clear H; subst.\n    - lia.\n    - replace inc_e with dec_digits_m in H1 by reflexivity.\n      replace ddm with (Z.neg p) by lia.\n      apply dec_digits_m_correct; assumption.\n    - replace dec_e with inc_digits_m in Heqz by reflexivity.\n      replace ddm with (Z.pos p) by lia.\n      apply inc_digits_m_correct; assumption.\n  Qed.\n\n  Lemma set_digits_m_correct (f1 : bfloat) (dm : Z) {f2 : bfloat} :\n    not_zero f1 ->\n    set_digits_m f1 dm = Some f2 ->\n    Zdigits (Fnum f2) = dm.\n  Proof.\n    intros M H.\n    unfold set_digits_m in H.\n    apply shift_digits_m_correct in H; [| assumption].\n    rewrite H.\n    lia.\n  Qed.\n\n  (** changing the binary length of the mantissa preserves the float's value *)\n  Lemma inc_digits_m_eq (f : bfloat) (ddm : positive) :\n    float_eq f (inc_digits_m f ddm).\n  Proof.\n    unfold inc_digits_m.\n    apply dec_e_eq.\n  Qed.\n\n  Lemma dec_digits_m_eq (f1 : bfloat) (ddm : positive) {f2 : bfloat} :\n    dec_digits_m f1 ddm = Some f2 ->\n    float_eq f1 f2.\n  Proof.\n    unfold dec_digits_m.\n    apply inc_e_eq.\n  Qed.\n\n  Lemma shift_digits_m_eq (f1 : bfloat) (ddm : Z) {f2 : bfloat} :\n    shift_digits_m f1 ddm = Some f2 ->\n    float_eq f1 f2.\n  Proof.\n    unfold shift_digits_m.\n    apply shift_e_eq.\n  Qed.\n\n  Lemma set_digits_m_eq (f1 : bfloat) (dm : Z) {f2 : bfloat} :\n    set_digits_m f1 dm = Some f2 ->\n    float_eq f1 f2.\n  Proof.\n    unfold set_digits_m.\n    apply shift_digits_m_eq.\n  Qed.\n\n  (** two equal floats with the same exponent are exactly the same *)\n  Lemma exponent_unique_fnum (f1 f2 : bfloat) :\n    float_eq f1 f2 ->\n    Fexp f1 = Fexp f2 ->\n    Fnum f1 = Fnum f2.\n  Proof.\n    unfold float_eq.\n    destruct f1 as [m1 e1], f2 as [m2 e2].\n    simpl; intros H E; destruct H; destruct H as [T H]; clear T; subst.\n    all: rewrite Z.sub_diag; simpl; lia.\n  Qed.\n\n  Lemma exponent_unique (f1 f2 : bfloat) :\n    float_eq f1 f2 ->\n    Fexp f1 = Fexp f2 ->\n    f1 = f2.\n  Proof.\n    intros.\n    pose proof exponent_unique_fnum f1 f2 H H0.\n    destruct f1, f2; simpl in *.\n    subst; reflexivity.\n  Qed.\n\n  (** two equal floats with the same mantissa length are exactly the same *)\n  Lemma Zdigits_m_unique_fexp (f1 f2 : bfloat) :\n    not_zero f1 ->\n    float_eq f1 f2 ->\n    Zdigits (Fnum f1) = Zdigits (Fnum f2) ->\n    Fexp f1 = Fexp f2.\n  Proof.\n    intros NZ1 H.\n    assert (NZ2 : not_zero f2) by apply (not_zero_eq f1 f2 NZ1 H).\n    unfold float_eq in *.\n    destruct f1 as [m1 e1], f2 as [m2 e2].\n    simpl in *; intro DM; destruct H; destruct H as [H1 H2]; subst.\n    all: destruct (Z.eq_dec e1 e2); try assumption.\n    - assert (e2 < e1) by lia; clear H1 n.\n      apply Zcompare_Gt in H.\n      apply Zcompare_Gt_spec in H; destruct H as [de H].\n      replace (e1 - e2) with (Z.pos de) in DM by lia.\n      rewrite <-two_power_pos_equiv in DM.\n      rewrite Zdigits_mul_pow2 in DM by assumption.\n      contradict DM; lia.\n    - assert (e1 < e2) by lia; clear H1 n.\n      apply Zcompare_Gt in H.\n      apply Zcompare_Gt_spec in H; destruct H as [de H].\n      replace (e2 - e1) with (Z.pos de) in DM by lia.\n      rewrite <-two_power_pos_equiv in DM.\n      rewrite Zdigits_mul_pow2 in DM by assumption.\n      contradict DM; lia.\n  Qed.\n\n  Lemma Zdigits_m_unique (f1 f2 : bfloat) :\n    not_zero f1 ->\n    float_eq f1 f2 ->\n    Zdigits (Fnum f1) = Zdigits (Fnum f2) ->\n    f1 = f2.\n  Proof.\n    intros.\n    pose proof Zdigits_m_unique_fexp f1 f2 H H0 H1.\n    apply exponent_unique; assumption.\n  Qed.\n\n  Fact Zdigits_Zpos_log_inf (p : positive) :\n  Zdigits (Z.pos p) = Z.succ (log_inf p).\n  Proof.\n    unfold Zdigits, Z.abs.\n    rewrite <-Zlog2_log_inf.\n    reflexivity.\n  Qed.\n\n  Fact Zdigits_Zneg_log_inf (p : positive) :\n  Zdigits (Z.neg p) = Z.succ (log_inf p).\n  Proof.\n    unfold Zdigits, Z.abs.\n    rewrite <-Zlog2_log_inf.\n    reflexivity.\n  Qed.\n    \n  (* similar to [bounded_closed_form] *)\n  Lemma valid_float_closed_form (prec emax : Z) (f : bfloat) (NZ : not_zero f)\n        (prec_gt_0 : FLX.Prec_gt_0 prec) (Hmax : prec < emax) :\n    let emin := 3 - emax - prec in\n    let '(m, e) := (Fnum f, Fexp f) in\n      valid_float prec emax f = true\n      <->\n      or\n        (Zdigits m < prec /\\ e = emin)\n        (Zdigits m = prec /\\ emin <= e <= emax - prec).\n  Proof.\n    destruct f as [m e].\n    intro.\n    unfold FLX.Prec_gt_0 in prec_gt_0.\n    unfold valid_float.\n    simpl.\n    destruct m.\n    - (* Z0 *)\n      unfold not_zero in NZ; simpl in NZ.\n      contradict NZ.\n      reflexivity.\n    - (* Zpos *)\n      rewrite bounded_closed_form by assumption;\n        rewrite Zdigits_Zpos_log_inf;\n        unfold compose.\n      split; intros H; destruct H; auto.\n    - (* Zneg *)\n      rewrite bounded_closed_form by assumption.\n        rewrite Zdigits_Zneg_log_inf;\n        unfold compose.\n      split; intros H; destruct H; auto.\n  Qed.\n\n  Lemma not_None_iff_exists_Some {A : Type} {x : option A} :\n    x <> None <-> exists y, x = Some y.\n  Proof.\n    split; intro.\n    - destruct x.\n      + exists a; reflexivity.\n      + contradict H; reflexivity.\n    - destruct H; subst; discriminate.\n  Qed.\n\n  Lemma float_eq_trans_l (f1 f2 f3 : bfloat) :\n    float_eq f1 f2 ->\n    float_eq f1 f3 ->\n    float_eq f2 f3.\n  Proof.\n    intros EQ12 EQ13.\n    apply float_eq_sym in EQ12.\n    apply float_eq_trans with (y := f1);\n      assumption.\n  Qed.\n\n  Lemma float_eq_set_e (f1 f2 : bfloat) :\n    float_eq f1 f2 ->\n    set_e f1 (Fexp f2) = Some f2.\n  Proof.\n    intro.\n    destruct set_e as [f |] eqn:SE.\n    - (* if successful, then equal *)\n      pose proof set_e_eq f1 (Fexp f2) SE; rename H0 into H1.\n      apply set_e_correct in SE.\n      apply (float_eq_trans_l f1 f f2 H1) in H.\n      apply (exponent_unique f f2 H) in SE.\n      subst; reflexivity.\n    - (* always successful *)\n      exfalso.\n      unfold float_eq, set_e, shift_e, inc_e, dec_e in *.\n      destruct f1 as [m1 e1], f2 as [m2 e2]; simpl in *.\n      repeat break_match; try discriminate.\n      clear SE; rename Heqb into H1.\n      apply Z.eqb_neq in H1.\n      destruct H; destruct H as [E M]; [lia |]; subst.\n      rewrite two_power_pos_equiv in H1.\n      rewrite Z.mod_mul in H1; auto.\n      generalize (Z.pow_pos_nonneg 2 (Z.pos p)); lia.\n  Qed.\n\n  Lemma float_eq_set_digits_m (f1 f2 : bfloat) :\n    not_zero f1 ->\n    float_eq f1 f2 ->\n    set_digits_m f1 (Zdigits (Fnum f2)) = Some f2.\n  Proof.\n    intros NZ1 H.\n    assert (NZ2 : not_zero f2) by apply (not_zero_eq f1 f2 NZ1 H).\n    destruct set_digits_m as [f |] eqn:SDM.\n    - (* if successful, then equal *)\n      pose proof set_digits_m_eq f1 (Zdigits (Fnum f2)) SDM; rename H0 into H1.\n      apply set_digits_m_correct in SDM; auto.\n      apply (float_eq_trans_l f1 f f2 H1) in H.\n      assert (NZ: not_zero f) by (apply not_zero_eq with (f1 := f1); assumption).\n      apply (Zdigits_m_unique f f2 NZ H) in SDM.\n      subst; reflexivity.\n    - (* always successful *)\n      exfalso.\n      unfold float_eq, set_digits_m, shift_digits_m, shift_e, inc_e, dec_e in *.\n      destruct f1 as [m1 e1], f2 as [m2 e2]; simpl in *.\n      repeat break_match; try discriminate.\n      clear SDM; rename Heqb into H1.\n      apply Z.eqb_neq in H1.\n      destruct H; destruct H as [E M]; subst.\n      + destruct (Z.eq_dec e1 e2).\n        replace (e1 - e2) with 0 in Heqz by lia;\n          rewrite Z.mul_1_r in Heqz; lia.\n        assert (e2 < e1) by lia; clear E n.\n        apply Zcompare_Gt in H.\n        apply Zcompare_Gt_spec in H; destruct H.\n        replace (e1 - e2) with (Z.pos x) in *.\n        rewrite <-two_power_pos_equiv in *.\n        rewrite Zdigits_mul_pow2 in Heqz.\n        lia.\n        auto.\n      + destruct (Z.eq_dec e1 e2).\n        replace (e2 - e1) with 0 in Heqz by lia;\n          rewrite Z.mul_1_r in Heqz; lia.\n        assert (e1 < e2) by lia; clear E n.\n        apply Zcompare_Gt in H.\n        apply Zcompare_Gt_spec in H; destruct H.\n        replace (e2 - e1) with (Z.pos x) in *.\n        rewrite <-two_power_pos_equiv in *.\n        rewrite Zdigits_mul_pow2 in Heqz.\n        assert (x = p) by lia; subst.\n        rewrite two_power_pos_equiv in H1.\n        rewrite Z.mod_mul in H1; auto.\n        generalize (Z.pow_pos_nonneg 2 (Z.pos p)); lia.\n        auto.\n  Qed.\n\n  (** ** declarative definition of `set_e` *)\n  Lemma set_e_definition (f1 : bfloat) (e : Z) {f2 : bfloat} :\n    set_e f1 e = Some f2 <->\n    float_eq f1 f2 /\\ Fexp f2 = e.\n  Proof.\n    split; intro.\n    - split.\n      apply (set_e_eq f1 e H). apply (set_e_correct f1 e H).\n    - destruct H as [EQ FEXP].\n      subst.\n      apply (float_eq_set_e f1 f2 EQ).\n  Qed.\n\n  (** ** declarative definition of `set_digits_m` *)\n  Lemma set_digits_m_definition (f1 : bfloat) (dm : Z) {f2 : bfloat} :\n    not_zero f1 ->\n    set_digits_m f1 dm = Some f2 <->\n    float_eq f1 f2 /\\ Zdigits (Fnum f2) = dm.\n  Proof.\n    intros NZ1.\n    split; intro.\n    - split.\n      apply (set_digits_m_eq f1 dm H).\n      apply (set_digits_m_correct f1 dm NZ1 H).\n    - destruct H as [EQ FEXP].\n      subst.\n      apply (float_eq_set_digits_m f1 f2 NZ1 EQ).\n  Qed.\n\n  Lemma normalize_correct' (prec emax : Z) (f : bfloat) (NZ : not_zero f)\n        (prec_gt_0 : FLX.Prec_gt_0 prec) (Hmax : prec < emax) :\n    match (normalize_float prec emax f) with\n    | Some nf => (float_eq f nf) /\\ (valid_float prec emax nf = true)\n    | None => forall (xf : bfloat),\n        float_eq f xf -> valid_float prec emax xf = false\n    end.\n  Proof.\n    unfold FLX.Prec_gt_0 in prec_gt_0.\n    break_match. rename b into nf.\n    - (* successful normalization - equal and valid? *)\n      unfold normalize_float in Heqo.\n      repeat break_match; inversion Heqo; subst.\n      + (* subnormal *)\n        split.\n        * (* same float? *)\n          apply set_e_eq with (e := 3 - emax - prec).\n          assumption.\n        * (* valid float? *)\n          apply Z.leb_le in Heqb0.\n          rewrite valid_float_closed_form.\n          apply set_e_correct in Heqo0.\n          lia.\n          apply not_zero_eq with (f1 := f). assumption.\n          apply set_e_eq in Heqo0. assumption.\n          unfold FLX.Prec_gt_0; lia.\n          assumption.\n      + (* normal *)\n        split.\n        * (* same float? *)\n          apply set_digits_m_eq with (dm := prec).\n          assumption.\n        * (* valid float? *)\n          apply andb_prop in Heqb1; destruct Heqb1 as [H1 H2].\n          apply Z.leb_le in H1; apply Z.leb_le in H2.\n          rewrite valid_float_closed_form.\n          right.\n          apply set_e_correct in Heqo0.\n          apply set_digits_m_correct in Heqo1.\n          lia.\n          assumption.\n          apply not_zero_eq with (f1 := f). assumption.\n          apply set_digits_m_eq in Heqo1. assumption.\n          unfold FLX.Prec_gt_0; lia.\n          assumption.\n    - (* unsuccesful normalization - impossible to normalize? *)\n      intros xf H.\n      apply Bool.not_true_is_false.\n      intros V.\n      assert (XNZ: not_zero xf) by apply (not_zero_eq f xf NZ H).\n      rewrite valid_float_closed_form in V by assumption.\n      destruct V as [V | V]; destruct V as [D E].\n      + (* xf is subnormal *)\n        unfold normalize_float in Heqo.\n        repeat break_match; try discriminate; clear Heqo.\n        all: rewrite <-E in Heqo0.\n        all: rewrite float_eq_set_e in Heqo0 by assumption.\n        all: inversion Heqo0; subst.\n        all: rewrite Z.leb_gt in Heqb0; lia.\n      + (* xf is normal *)\n        unfold normalize_float in Heqo.\n        repeat break_match; try discriminate; clear Heqo.\n        * rewrite <-D in Heqo1.\n          rewrite float_eq_set_digits_m in Heqo1 by assumption.\n          inversion Heqo1; subst; clear Heqo1.\n          apply Bool.andb_false_elim in Heqb1; destruct Heqb1.\n          all: rewrite Z.leb_gt in e; lia.\n        * rewrite <-D in Heqo1.\n          rewrite float_eq_set_digits_m in Heqo1 by assumption.\n          inversion Heqo1.\n        * unfold set_e, shift_e, inc_e, dec_e in Heqo0.\n          repeat break_match; try discriminate; clear Heqo0.\n          remember (3 - emax - prec) as emin.\n          rewrite Z.eqb_neq in Heqb.\n          destruct f as [m e], xf as [xm xe].\n          unfold float_eq, not_zero in *.\n          simpl in *.\n          destruct H; destruct H as [EXP NUM].\n          -- lia.\n          -- subst m.\n             replace (xe - e) with ((xe - emin) + Z.pos p) in Heqb by lia.\n             rewrite Z.pow_add_r in Heqb by lia.\n             rewrite Z.mul_assoc in Heqb.\n             rewrite two_power_pos_equiv in Heqb.\n             rewrite Z.mod_mul in Heqb.\n             contradict Heqb; reflexivity.\n             pose proof Z.add_assoc.\n             generalize (Z.pow_pos_nonneg 2 (Z.pos p)); lia.\n  Qed.\n\n  Theorem normalize_correct (prec emax : Z) (f : bfloat) (NZ : not_zero f)\n        (prec_gt_0 : FLX.Prec_gt_0 prec) (Hmax : prec < emax) {nf : bfloat} :\n    normalize_float prec emax f = Some nf\n    <->\n    (float_eq f nf) /\\ (valid_float prec emax nf = true).\n  Proof.\n    pose proof normalize_correct' prec emax f NZ prec_gt_0 Hmax.\n    split; intro.\n    - rewrite H0 in H; clear H0; assumption.\n    - break_match; try discriminate.\n      + destruct H, H0.\n        rename b into f1, nf into f2.\n        pose proof float_eq_trans_l f f1 f2 H H0 as EQ.\n        pose proof not_zero_eq f f1 NZ H as NZ1.\n        pose proof not_zero_eq f f2 NZ H0 as NZ2.\n        clear H H0 NZ f Heqo.\n        apply valid_float_closed_form in H1; try assumption.\n        apply valid_float_closed_form in H2; try assumption.\n        f_equal.\n        destruct H1 as [H1 | H1], H2 as [H2 | H2];\n          destruct H1 as [M1 E1], H2 as [M2 E2].\n        * apply exponent_unique; try assumption.\n          rewrite E1, E2; reflexivity.\n        * exfalso. unfold float_eq in EQ.\n          destruct EQ as [EQ | EQ]; destruct EQ as [E M].\n          -- rewrite M in M2.\n             replace (Fexp f1 - Fexp f2) with 0 in M2 by lia.\n             simpl in M2; rewrite Z.mul_1_r in M2.\n             rewrite M2 in M1.\n             lia.\n          -- rewrite M in M1.\n             destruct (Fexp f2 - Fexp f1) eqn:T; try lia.\n             simpl in M1; rewrite Z.mul_1_r in M1.\n             rewrite M2 in M1.\n             lia.\n             rewrite <-two_power_pos_equiv in M1.\n             rewrite Zdigits_mul_pow2 in M1.\n             lia.\n             unfold not_zero in NZ2; assumption.\n        * exfalso. unfold float_eq in EQ.\n          destruct EQ as [EQ | EQ]; destruct EQ as [E M].\n          -- rewrite M in M2.\n             destruct (Fexp f1 - Fexp f2) eqn:T; try lia.\n             simpl in M2; rewrite Z.mul_1_r in M2.\n             rewrite M1 in M2.\n             lia.\n             rewrite <-two_power_pos_equiv in M2.\n             rewrite Zdigits_mul_pow2 in M2.\n             lia.\n             unfold not_zero in NZ2; assumption.\n          -- rewrite M in M1.\n             replace (Fexp f2 - Fexp f1) with 0 in M1 by lia.\n             simpl in M1; rewrite Z.mul_1_r in M1.\n             rewrite M1 in M2.\n             lia.\n        * apply Zdigits_m_unique; try assumption.\n          rewrite M1, M2; reflexivity.\n      + destruct H0;\n        apply H in H0.\n        rewrite H0 in H1.\n        inversion H1.\n  Qed.\n\nEnd Correctness.\n", "meta": {"author": "amuppal18", "repo": "test", "sha": "4f6663f47786843480790e1b754ea117de435ff3", "save_path": "github-repos/coq/amuppal18-test", "path": "github-repos/coq/amuppal18-test/test-4f6663f47786843480790e1b754ea117de435ff3/src/coq/ParserHelper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.847967769904032, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6703442271791012}}
{"text": "(*\n  Copyright 2022 ZhengPu Shi\n  This file is part of CoqMatrix. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : test for Vector\n  author    : ZhengPu Shi\n  date      : 2021.01\n*)\n\nFrom FCS Require Import DepPair.Vector.\n\n\n(** ** Definition of vector *)\n\nExample vec_ex0 : @vec nat 0 := tt.\nExample vec_ex1 : vec 3 := [1;2;3].\nExample vec_ex2 : vec 3 := [4;5;6].\n\n\n(** ** Construct a vector with same element *)\n\nCompute vrepeat 5 3.\n\n\n(** ** vec0, its elements is 0 *)\n\nCompute vec0 0 3.\n\n\n(** ** Get head element *)\n\nCompute vhd 0 vec_ex1.\n\n\n(** ** Get tail vector *)\n\nCompute vtl vec_ex1.\nCompute vtl (vtl vec_ex1).\n\n\n(** ** Get last element *)\n\nCompute vlast vec_ex1.\n\n\n(** Construct a vector with a function *)\n\nCompute vmake_old 5 (fun i : nat => i).\nCompute vmake 5 (fun i => 3).\nCompute vmake 5 (fun i : nat => i).\n\n\n(** ** Append two vectors *)\n\nCompute vapp vec_ex1 vec_ex2.\n\n\n(** Get n-th element of a vector *)\n\nCompute vnth 99 2 vec_ex1.\nCompute vnth 99 5 vec_ex1.\n\n\n(** ** Get top k element of a vector *)\n\nCompute vfirstn 99 5 vec_ex1.\n\n\n(** Get remain (n-k) elements of a vector *)\n\nCompute vskipn 1 vec_ex1.\n\n\n(** ** Maping a vector to another *)\n\nCompute vmap (S) vec_ex1.\n\n\n(** Mapping two vectors to another vector *)\n\nCompute vmap2 Nat.add vec_ex1 vec_ex2.\n\n\n(** ** Vector addition *)\n\nCompute vadd Nat.add vec_ex1 vec_ex1.\n\n\n(** ** Vector substraction *)\n\nCompute vopp Nat.succ vec_ex1.\nCompute vsub Nat.sub vec_ex1 vec_ex1.\n\n\n(** ** Vector constant multiplication *)\n\nCompute vcmul Nat.mul 3 vec_ex1.\nCompute vmulc Nat.mul vec_ex1 3.\n\n\n(** ** Fold a vector to an element *)\n\nCompute vfoldl Nat.add 0 vec_ex1.\nCompute vfoldr Nat.add 0 vec_ex1.\n\n\n(** ** Dot product of two vectors *)\n\nCompute vdot 0 Nat.add Nat.mul vec_ex1 vec_ex1.\n\n\n(** ** Concatenation a nested vector to a plain vector *)\n\nCompute vvflat ([[1;2];[3;4];[5;6]] : @vec (vec 2) 3).\n", "meta": {"author": "zhengpushi", "repo": "CoqMatrix", "sha": "28fa5f96e38a07659cfd373e09b0e75c24c22bfd", "save_path": "github-repos/coq/zhengpushi-CoqMatrix", "path": "github-repos/coq/zhengpushi-CoqMatrix/CoqMatrix-28fa5f96e38a07659cfd373e09b0e75c24c22bfd/CoqMatrix/DepPair/Vector_test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6703442264367788}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n\n(****************************************************************************)\n(* This contribution was updated for Coq V5.10 by the COQ workgroup.        *)\n(* January 1995                                                             *)\n(****************************************************************************)\n(*                                                                          *)\n(*        Initial Version: Frederic Prost, July 1993                        *)\n(*        Revised Version: Gilles Kahn, September 1993                      *)\n(*        Revised for a tutorial on Coq:  Gilles Kahn, March 1994           *)\n(*                                     INRIA Sophia-Antipolis, FRANCE       *)\n(*                                                                          *)\n(****************************************************************************)\n(*                              Relations_1.v                               *)\n(****************************************************************************)\n\nSection Relations_1.\n   Variable U : Type.\n   \n   Definition Relation := U -> U -> Prop.\n   Variable R : Relation.\n   \n   Definition Reflexive : Prop := forall x : U, R x x.\n   \n   Definition Transitive : Prop := forall x y z : U, R x y -> R y z -> R x z.\n   \n   Definition Symmetric : Prop := forall x y : U, R x y -> R y x.\n   \n   Definition Antisymmetric : Prop :=\n     forall x y : U, R x y -> R y x -> x = y :>U.\n   \n   Definition contains (R R' : Relation) : Prop :=\n     forall x y : U, R' x y -> R x y.\n   \n   Definition same_relation (R R' : Relation) : Prop :=\n     contains R R' /\\ contains R' R.\n   \n   Inductive Preorder : Prop :=\n       Definition_of_preorder : Reflexive -> Transitive -> Preorder.\n   \n   Inductive Order : Prop :=\n       Definition_of_order :\n         Reflexive -> Transitive -> Antisymmetric -> Order.\n   \n   Inductive Equivalence : Prop :=\n       Definition_of_equivalence :\n         Reflexive -> Transitive -> Symmetric -> Equivalence.\n   \n   Inductive PER : Prop :=\n       Definition_of_PER : Symmetric -> Transitive -> PER.\n   \nEnd Relations_1.\nHint Unfold Reflexive.\nHint Unfold Transitive.\nHint Unfold Antisymmetric.\nHint Unfold Symmetric.\nHint Unfold contains.\nHint Unfold same_relation.\nHint Resolve Definition_of_preorder.\nHint Resolve Definition_of_order.\nHint Resolve Definition_of_equivalence.\nHint Resolve Definition_of_PER.", "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/Relations_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6703442243444055}}
{"text": "Require Export Wellfounded.Transitive_Closure.\nRequire Export Relations.\nRequire Export Relation_Operators.\nRequire Export List.\nRequire Import Setoid.\n\nLtac isda := intros; simpl in *; try discriminate; auto.\n\nSection tcl.\n\nVariable A : Type.\nVariable R : relation A.\n\nNotation trans_clos := (clos_trans A R).\nNotation trans_clos_l := (clos_trans_1n A R).\nNotation trans_clos_r := (clos_trans_n1 A R).\n\nLemma exl : forall x y, trans_clos x y -> R x y \\/ exists z, R x z /\\ trans_clos z y.\nProof with auto.\n  induction 1.\n  left...\n  right; clear IHclos_trans2; destruct IHclos_trans1 as [H1 | [u [H1 H2]]].\n  exists y...\n  exists u; split; [ assumption | econstructor 2; eauto].\nQed.\n\nLemma exr : forall x y, trans_clos x y -> R x y \\/ exists z, R z y /\\ trans_clos x z.\nProof with auto.\n  induction 1.\n  left...\n  right; clear IHclos_trans1; destruct IHclos_trans2 as [H1 | [u [H1 H2]]].\n  exists y...\n  exists u; split; [ assumption | econstructor 2; eauto].\nQed.\n\nLemma tcl_l_h : forall x y z, trans_clos x y -> trans_clos_l y z -> trans_clos_l x z.\nProof with eauto.\n  induction 1; intros...\n  econstructor 2...\nQed.\n\nLemma tcl_l : forall x y, trans_clos x y <-> trans_clos_l x y.\nProof with eauto.\n  split; induction 1; intros...\n  constructor...\n  eapply tcl_l_h...\n  constructor...\n  econstructor 2...\n  constructor...\nQed.\n\nLemma tcl_r_h : forall x y z, trans_clos y z -> trans_clos_r x y -> trans_clos_r x z.\nProof with eauto.\n  induction 1; intros...\n  econstructor 2...\nQed.\n\nLemma tcl_r : forall x y, trans_clos x y <-> trans_clos_r x y.\nProof with eauto.\n  split; induction 1; intros.\n  constructor...\n  eapply tcl_r_h...\n  constructor...\n  econstructor 2...\n  constructor...\nQed.\n\nLemma Acc_tcl_l : forall x, Acc trans_clos x -> Acc trans_clos_l x.\nProof with auto.\n  induction 1.\n  constructor; intros.\n  apply H0; rewrite tcl_l...\nQed.\n\nTheorem wf_clos_trans_l : well_founded R -> well_founded trans_clos_l.\nProof with auto.\n  intros H a; apply Acc_tcl_l; apply wf_clos_trans...\nQed.\n\nLemma Acc_tcl_r : forall x, Acc trans_clos x -> Acc trans_clos_r x.\nProof with auto.\n  induction 1.\n  constructor; intros.\n  apply H0; rewrite tcl_r...\nQed.\n\nTheorem wf_clos_trans_r : well_founded R -> well_founded trans_clos_r.\nProof with auto.\n  intros H a; apply Acc_tcl_r; apply wf_clos_trans...\nQed.\n\nEnd tcl.\n\nDefinition opt_to_list {T} (o : option T) : list T :=\n  match o with\n  | None => nil\n  | Some x => x :: nil\n  end.\n\nSection map_injective.\n\n  Variables A B : Set.\n  Variable f : A -> B.\n  Hypothesis f_injective : forall a a0 : A, f a = f a0 -> a = a0.\n\n  Lemma map_injective : forall l l0, map f l = map f l0 -> l = l0.\n  Proof.\n    induction l; destruct l0; intro H; inversion H; f_equal; auto.\n  Qed.\n\nEnd map_injective.\n\nSection streams.\n\n  Variable A : Set.\n\n  CoInductive stream :=\n  | s_nil : stream\n  | s_cons : A -> stream -> stream.\n\n  CoInductive bisim_stream : stream -> stream -> Prop :=\n  | b_nil : bisim_stream s_nil s_nil\n  | b_cons : forall (x : A) (s0 s1 : stream), bisim_stream s0 s1 -> bisim_stream (s_cons x s0) (s_cons x s1).\n\nEnd streams.\n\nImplicit Arguments s_nil [A].\nImplicit Arguments s_cons [A].\nImplicit Arguments bisim_stream [A].\nImplicit Arguments b_nil [A].\nImplicit Arguments b_cons [A x s0 s1].\n", "meta": {"author": "fsieczkowski", "repo": "Refocusing", "sha": "52bd620d5179cf660aa2c84ae7a8593927ab85ee", "save_path": "github-repos/coq/fsieczkowski-Refocusing", "path": "github-repos/coq/fsieczkowski-Refocusing/Refocusing-52bd620d5179cf660aa2c84ae7a8593927ab85ee/utils/Util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.670344222454608}}
{"text": "Require Import List.\n\nRequire Import CpdtTactics.\n(*\nDefinition bad : unit := tt.\n*)\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\n\n\nSection stream.\n  Variable A : Type.\n\n  CoInductive stream : Type :=\n  | Cons : A -> stream -> stream.\nEnd stream.\n\nCoFixpoint zeroes : stream nat := Cons 0 zeroes.\n\n\nCoFixpoint trues_falses : stream bool := Cons true falses_trues\nwith falses_trues : stream bool := Cons false trues_falses.\n\nFixpoint take A (n : nat) (s : stream A) : list A :=\n  match n with\n    | O => nil\n    | S n' =>\n      match s with\n        | Cons h t => h :: take n' t\n      end\n  end.\n\nEval simpl in take 10 zeroes.\nEval simpl in take 10 trues_falses.\n\n\nSection map.\n  Variables A B : Type.\n  Variable f : A -> B.\n\n  CoFixpoint map (s : stream A) : stream B :=\n    match s with\n      | Cons h t => Cons (f h) (map t)\n    end.\nEnd map.\n\nSection interleave.\n  Variable A : Type.\n\n  CoFixpoint interleave (s1 s2 : stream A) : stream A :=\n    match s1, s2 with\n      | Cons h1 t1, Cons h2 t2 => Cons h1 (Cons h2 (interleave t1 t2))\n    end.\nEnd interleave.\n\n(*\nSection map'.\n  Variables A B : Type.\n  Variable f : A -> B.\n  CoFixpoint map' (s : stream A) : stream B :=\n    match s with\n      | Cons h t => interleave (Cons (f h) (map' t)) (Cons (f h) (map' t))\n    end.\nEnd map'.\n*)\n\nDefinition tail A (s : stream A) : stream A :=\n  match s with\n    | Cons _ s' => s'\n  end.\n\n\nCoFixpoint ones : stream nat := Cons 1 ones.\n\nDefinition ones' := map S zeroes.\n\nTheorem ones_eq : ones = ones'.\nAbort.\n\n\nSection stream_eq.\n  Variable A : Type.\n\n  CoInductive stream_eq : stream A -> stream A -> Prop :=\n  | Stream_eq : forall h t1 t2, stream_eq t1 t2 -> stream_eq (Cons h t1)(Cons h t2).\nEnd stream_eq.\n\n\nTheorem ones_eq : stream_eq ones ones'.\n  cofix.\n  assumption.\n  Undo.\n  simpl.\nAbort.\n\nDefinition frob A (s : stream A) : stream A :=\n  match s with\n    | Cons h t => Cons h t\n  end.\n\nTheorem frob_eq : forall A (s : stream A), s = frob s.\n  destruct s.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem ones_eq : stream_eq ones ones'.\n  cofix.\n  rewrite (frob_eq ones).\n  rewrite (frob_eq ones').\n  simpl.\n  constructor.\n  fold (map S).\n  fold ones'.\n  assumption.\nQed.\n\nDefinition head A (s : stream A) : A :=\n  match s with\n    | Cons x _ => x\n  end.\n\n\nSection stream_eq_coind.\n  Variable A : Type.\n  Variable R : stream A -> stream A -> Prop.\n\n\n  Hypothesis Cons_case_hd : forall s1 s2, R s1 s2 -> head s1 = head s2.\n  Hypothesis Cons_case_tl : forall s1 s2, R s1 s2 -> R (tail s1) (tail s2).\n\n  \n  Theorem stream_eq_coind : forall s1 s2, R s1 s2 -> stream_eq s1 s2.\n    cofix.\n    destruct s1.\n    destruct s2.\n    intro.\n    generalize (Cons_case_hd H).\n    intro Heq.\n    simpl in Heq.\n    rewrite Heq.\n    constructor.\n    apply stream_eq_coind.\n    apply (Cons_case_tl H).\n  Qed.\nEnd stream_eq_coind.\n\nPrint stream_eq_coind. \n\n\nTheorem ones_eq'' : stream_eq ones ones'.\n  apply (stream_eq_coind (fun s1 s2 => s1 = ones /\\ s2 = ones')); crush.\nQed.\n\n\n\nSection stream_eq_loop.\n  Variable A : Type.\n  Variables s1 s2 : stream A.\n\n  Hypothesis Cons_case_hd : head s1 = head s2.\n  Hypothesis loop1 : tail s1 = s1.\n  Hypothesis loop2 : tail s2 = s2.\n  \n  Theorem stream_eq_loop : stream_eq s1 s2.\n    apply (stream_eq_coind (fun s1' s2' => s1' = s1 /\\ s2' = s2)); crush.\n  Qed.\n\nEnd stream_eq_loop.\n\n\nRequire Import Arith.\nPrint fact.\n\n\nCoFixpoint fact_slow' (n : nat) := Cons (fact n) (fact_slow' (S n)).\nDefinition fact_slow := fact_slow' 1.\n\n\nCoFixpoint fact_iter' (cur acc : nat) := Cons acc (fact_iter' (S cur) (acc * cur)).\nDefinition fact_iter := fact_iter' 2 1.\n\nEval simpl in take 5 fact_slow.\nEval simpl in take 5 fact_iter.\n\n\nLemma fact_recur : forall n,\n  fact n * S n = fact (S n).\n  intro n.\n  induction n.\n  simpl.\n  reflexivity.\n  unfold fact.\n  ring.\nQed.\n\n\nLemma fact_def : forall x n,\n  fact_iter' x (fact n * S n) = fact_iter' x (fact (S n)).\n  intros. \n  rewrite fact_recur.\n  reflexivity.\nQed.\n\nHint Resolve fact_def.\n\nLemma fact_eq' : forall n, stream_eq (fact_iter' (S n) (fact n)) (fact_slow' n).\n  intro n.\n  apply(stream_eq_coind (fun s1 s2 => \n    exists n, s1 = fact_iter' (S n) (fact n) /\\ s2 = fact_slow' n)); crush; eauto.\nQed.\n\nTheorem fact_eq : stream_eq fact_iter fact_slow.\n  apply fact_eq'.\nQed.\n\nSection stream_eq_onequant.\n  Variables A B : Type.\n \n  Variables f g : A -> stream B.\n\n\n  Hypothesis Cons_case_hd : forall x, head (f x) = head (g x).\n  Hypothesis Cons_case_tl : forall x, exists y,tail (f x) = f y /\\ tail (g x) = g y.\n  \n  Theorem stream_eq_onequant : forall x, stream_eq (f x) (g x).\n    intro; apply (stream_eq_coind (fun s1 s2 => \n      exists x, s1 = f x /\\ s2 = g x)); crush; eauto.\n  Qed.\nEnd stream_eq_onequant.\n\n\nLemma fact_eq'' : forall n, stream_eq (fact_iter' (S n) (fact n)) (fact_slow' n).\n  apply stream_eq_onequant.\n  simpl.\n  reflexivity.\n  simpl.\n  eauto.\nQed.\n\n\nDefinition var := nat.\n\nDefinition environment := var -> nat.\n\n\nDefinition set (env : environment) (v : var) (n : nat) : environment :=\n  fun v' => if beq_nat v v' then n else env v'.\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Var : var -> exp\n| Plus : exp -> exp -> exp.\n\nFixpoint evalExp (e : exp) (env : environment) : nat :=\n  match e with\n    | Const n => n\n    | Var v => env v\n    | Plus e1 e2 => evalExp e1 env + evalExp e2 env\n  end.\n\nInductive cmd : Set :=\n| Assign : var -> exp -> cmd\n| Seq : cmd -> cmd -> cmd\n| While : exp -> cmd -> cmd.\n\nCoInductive evalCmd : environment -> cmd -> environment -> Prop :=\n| EvalAssign : forall env v e, evalCmd env (Assign v e) (set env v (evalExp e env))\n| EvalSeq : forall env1 env2 env3 c1 c2, evalCmd env1 c1 env2\n  -> evalCmd env2 c2 env3 -> evalCmd env1 (Seq c1 c2) env3\n| EvalWhileFalse : forall env e c, evalExp e env = 0\n  -> evalCmd env (While e c) env\n| EvalWhileTrue : forall env1 env2 env3 e c, evalExp e env1 <> 0\n  -> evalCmd env1 c env2\n  -> evalCmd env2 (While e c) env3\n  -> evalCmd env1 (While e c) env3.\n\nSection evalCmd_coind.\n  Variable R : environment -> cmd -> environment -> Prop.\n\n\n  Hypothesis AssignCase : forall env1 env2 v e, \n    R env1 (Assign v e) env2 -> env2 = set env2 v (evalExp e env1).\n\n\n  Hypothesis SeqCase : forall env1 env3 c1 c2, \n    R env1 (Seq c1 c2) env3 -> exists env2, R env1 c1 env2 /\\ R env2 c2 env3.\n\n  Hypothesis WhileCase : forall env1 env3 e c, \n    R env1 (While e c) env3 -> (evalExp e env1 = 0 /\\ env3 = env1)\n    \\/ exists env2,evalExp e env1 <> 0 /\\ R env1 c env2 /\\ R env2 (While e c) env3.\n\n  Theorem evalCmd_coind : forall env1 c env2, R env1 c env2 -> evalCmd env1 c env2.\n  Admitted.\n\nEnd evalCmd_coind.\n\nFixpoint optExp (e : exp) : exp :=\n  match e with\n    | Plus (Const 0) e => optExp e\n    | Plus e1 e2 => Plus (optExp e1) (optExp e2)\n    | _ => e\n  end.\n\nFixpoint optCmd (c : cmd) : cmd :=\n  match c with\n    | Assign v e => Assign v (optExp e)\n    | Seq c1 c2 => Seq (optCmd c1) (optCmd c2)\n    | While e c => While (optExp e) (optCmd c)\n  end.\n\n\nLemma optExp_correct : forall env e, evalExp (optExp e) env = evalExp e env.\n  induction e.\n  simpl.\n  reflexivity.\n  simpl.\n  reflexivity.\n  simpl.\n  crush.\n  repeat (match goal with\n           | [ |- context[match ?E with Const _ => _ | _ => _ end] ] => destruct E\n               | [ |- context[match ?E with O => _ | S _ => _ end] ] => destruct E\n            end; crush).\nQed.\n\nHint Rewrite optExp_correct.\n\nLtac finisher := match goal with\n                   | [ H : evalCmd _ _ _ |- _ ] => ((inversion H; [])\n                     || (inversion H; [|])); subst\n                 end; crush; eauto 10.\n\nLemma optCmd_correct1 : forall vs1 c vs2, evalCmd vs1 c vs2\n  -> evalCmd vs1 (optCmd c) vs2.\n  intros; apply (evalCmd_coind (fun vs1 c' vs2 => exists c, evalCmd vs1 c vs2\n    /\\ c' = optCmd c)); eauto; crush;\n    match goal with\n      | [ H : _ = optCmd ?E |- _ ] => destruct E; simpl in *; discriminate\n        || injection H; intros; subst\n    end; finisher.\nQed.\n\n\nLemma optCmd_correct2 : forall env1 c env2, evalCmd env1 (optCmd c) env2\n  -> evalCmd env1 c env2.\n  intros; apply (evalCmd_coind (fun vs1 c vs2 => evalCmd vs1 (optCmd c) vs2));\n    crush; finisher.\nQed.\n\nTheorem optCmd_correct : forall env1 c env2, evalCmd env1 (optCmd c) env2\n  <-> evalCmd env1 c env2.\n  intuition; apply optCmd_correct1 || apply optCmd_correct2; assumption.\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/Coinductive-test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744806385543, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.670323868288521}}
{"text": "Welcome to Coq 8.4pl6 (January 2017)\n\nCoq < Inductive natoption : Type := | Some : nat -> natoption | None : natoption.\nnatoption is defined\nnatoption_rect is defined\nnatoption_ind is defined\nnatoption_rec is defined\n\nCoq < Inductive natlist : Type := | nil : natlist | cons : nat -> natlist -> natlist.\nnatlist is defined\nnatlist_rect is defined\nnatlist_ind is defined\nnatlist_rec is defined\n\nCoq < Notation \"[ ]\" := nil.\nSetting notation at level 0.\n\nCoq < Notation \"x ++ y\" := (app x y) (right associativity, at level 60).\n\nCoq < Notation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\nSetting notation at level 0.\n\nCoq < Notation \"x :: l\" := (cons x l) (at level 60, right associativity).\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 recursively defined (decreasing on 1st argument)\n\nCoq < Fixpoint nth_error (l:natlist) (n:nat) : natoption := match l with | nil => None | a :: l' => match beq_nat n O with | true => Some a | false => nth_error l' (pred n) end end.\nnth_error is recursively defined (decreasing on 1st argument)\n\nCoq < Example test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\n1 subgoal\n  \n  ============================\n   nth_error (4 :: 5 :: 6 :: 7 :: []) 0 = Some 4\n\ntest_nth_error1 < info_auto.\n(* info auto : *)\n apply @eq_refl.\nNo more subgoals.\n\ntest_nth_error1 < Qed.\ninfo_auto.\n\ntest_nth_error1 is defined\n\nCoq < Example test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\n1 subgoal\n  \n  ============================\n   nth_error (4 :: 5 :: 6 :: 7 :: []) 3 = Some 7\n\ntest_nth_error2 < info_auto.\n(* info auto : *)\n apply @eq_refl.\nNo more subgoals.\n\ntest_nth_error2 < Qed.\ninfo_auto.\n\ntest_nth_error2 is defined\n\nCoq < Example test_nth_error3 : nth_error [4;5;6;7] 9 = None.\n1 subgoal\n  \n  ============================\n   nth_error (4 :: 5 :: 6 :: 7 :: []) 9 = None\n\ntest_nth_error3 < info_auto.\n(* info auto : *)\n apply @eq_refl.\nNo more subgoals.\n\ntest_nth_error3 < Qed.\ninfo_auto.\n\ntest_nth_error3 is defined\n", "meta": {"author": "billwestfall", "repo": "coq_ide", "sha": "a2985a04f37f9c1c6f23799d543fdb862792d54b", "save_path": "github-repos/coq/billwestfall-coq_ide", "path": "github-repos/coq/billwestfall-coq_ide/coq_ide-a2985a04f37f9c1c6f23799d543fdb862792d54b/foundations/lists/lists004.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.6703238664431825}}
{"text": "(**\n「同値関係の保存」をSSReflectでやってみる。\nProper ==> は、SSReflect とは同居できないようだ。\n\n@suharahiromichi\n2015_05_03\n*)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n(*\nたぶん、SSReflectとは同居できない。\nRequire Import Basics Tactics Coq.Setoids.Setoid Morphisms.\n*)\nRequire Import ssreflect ssrbool ssrnat eqtype seq ssrfun.\n\nDefinition lsum := seq nat.\n\n(* ****************************** *)\n(* 同値関係                        *)\n(* ****************************** *)\nDefinition lsum_equiv : lsum -> lsum -> bool :=\n  fun r r' => sumn r == sumn r'.\nInfix \"=s=\" := lsum_equiv (at level 70) : type_scope.\n\nGoal 1::2::3::nil =s= 6::nil.\nProof.\n  by [].\nQed.\n\nLemma lsum_equiv_refl : reflexive lsum_equiv.\nProof.\n  rewrite /reflexive /lsum_equiv.\n  by [].\nQed.\n\nLemma lsum_equiv_sym : symmetric lsum_equiv.\nProof.\n  rewrite /symmetric /lsum_equiv.\n  by [].\nQed.\n\nLemma lsum_equiv_trans : transitive lsum_equiv.\nProof.\n  rewrite /transitive /lsum_equiv.\n  move=> y x z.\n  move/eqP => H1.\n  move/eqP => H2.\n  apply/eqP.\n  by rewrite H1 H2.\nQed.\n\n(* ****************************** *)\n(* cons n に対してプロパーである。 *)\n(* ****************************** *)\n(*  Proper (lsum_equiv ==> lsum_equiv) (cons n) . *)\nLemma cons_lsum_Proper (n : nat) :\n  forall r r', r =s= r' -> n :: r =s= n :: r'.\nProof.\n  intros r r'.\n  rewrite /lsum_equiv.\n  move/eqP => H.\n  apply/eqP => /=.\n  by rewrite H.\nQed.\n\nGoal forall r r' : lsum,\n       r =s= r' -> 4 :: r =s= 4 :: r'.\nProof.\n  move=> r r' H.\n  apply cons_lsum_Proper.\n  by rewrite H.\nQed.\n\n(* ****************************** *)\n(* append に対してプロパーである。 *)\n(* ****************************** *)\n(* Proper (route_equiv ==> route_equiv ==> route_equiv) append *)\nLemma append_route_Proper (r r' r'' r''' : lsum) :\n    r =s= r'' -> r' =s= r''' -> r ++ r' =s= r'' ++ r'''.\nProof.\n  move/eqP => H1.\n  move/eqP => H2.\n  apply/eqP.\n  do 2 rewrite sumn_cat.\n  by rewrite H1 H2.\nQed.\n\nGoal forall r r' : lsum,\n       r =s= r' -> 1::2::nil ++ r =s= 1::2::nil ++ r'.\nProof.\n  move=> r r' H.\n  apply append_route_Proper.\n  - by [].\n  - by [].\nQed.\n\nGoal forall r r' : lsum,\n       r =s= r' -> r ++ 1::2::nil =s= r' ++ 1::2::nil.\nProof.\n  move=> r r' H.\n  apply append_route_Proper.\n  - by [].\n  - by [].\nQed.\n\nGoal forall r r' : lsum,\n       r =s= r' ->\n       1::nil ++ r ++ 2::3::nil =s= 1::nil ++ r' ++ 2::3::nil.\nProof.\n  move=> r r' H.\n  apply append_route_Proper.\n  - by [].\n  - apply append_route_Proper.\n    + by [].\n    + by [].\nQed.\n\n(* ******************************** *)\n(* ********EqMixin***************** *)\n(* ********説明のための例*********** *)\n(* ******************************** *)\n\n(* SSReflect (EqType) でできること。 *)\n(* jssst31/ssr_jsst2014_eqtype_example.v *)\nLemma lsum_equivP : Equality.axiom lsum_equiv.\nProof.\n  move=> r r'.\n  rewrite /lsum_equiv.\n  apply: (iffP idP).\n(* これは成立しないが、説明のために仮におく。 *)\n  - admit.\n  - move=> <-.\n    by apply: lsum_equiv_refl.\nQed.\n\nCompute 1::2::3::nil == 6::nil :> seq nat.  (* false *)\nCompute 1::2::3::nil == 6::nil :> lsum.     (* false *)\n\nCanonical lsum_eqMixin := EqMixin lsum_equivP.\nCanonical lsum_eqType := EqType lsum lsum_eqMixin.\n(* Canonical lsum_eqType := Eval hnf in EqType lsum lsum_eqMixin. *)\nPrint Canonical Projections.\n(*\nlsum_equiv <- Equality.op ( lsum_eqMixin )\nlsum <- Equality.sort ( lsum_eqType )\nが追加になる。\n*)\n\nCompute 1::2::3::nil == 6::nil :> seq nat.  (* false *)\nCompute 1::2::3::nil == 6::nil :> lsum.     (* true *)\n(* lsum 型の世界で、== が使えるようになる。 *)\n\n(* ******** *)\nLemma lsum_irrelevance (x y : lsum) (E E' : x = y) : E = E'.\nProof. by apply: eq_irrelevance. Qed.\n(* ******* *)\n\nGoal 1::2::3::nil == 6::nil :> lsum.\nProof.\n  by [].\nQed.\n\n(** 証明 *)\nGoal forall r r' : lsum, r == r' <-> r = r'.\nProof.\n  move=> r r'.\n  by split; move/lsum_equivP.\nQed.\n\n(** リフレクションと書き換えができる。  *)\nGoal forall r r' l : nat, r == r' -> r' == l -> r == l.\nProof.\n  move=> r r' l Hrr' Hr'l.\n  apply/eqP.                                (* r = l *)\n  Undo 1.\n  rewrite (eqP Hrr').                       (* r' == l *)\n  by [].\nQed.\n\n(* END *)\n\n(* SSReflect の部分の参考：\nhttp://d.hatena.ne.jp/kikx/20111213 *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/gitcrc/ssr_proper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.6703238664431824}}
{"text": "Require Import Classical_Prop.\n\nLemma double_negation_elimination: \nforall a: Prop, ~~a->a.\nintros A DNA.\ntauto.\nQed.\n\nTheorem com: forall P Q, \nP\\/Q -> Q\\/P.\nProof.\nintros P Q [HP | HQ].\n-right.\napply HP.\n-left.\napply HQ.\nQed.\n\nTheorem exer1: forall p,\np->p.\nintros P HP.\napply HP.\nQed.\n\nTheorem exer2: forall p q:\nProp, p->q->p.\nintros. \nexact H.\nQed.\n\nTheorem exer3: forall p q:\nProp, ~p ->p->q.\nintros.\ncontradiction.\nQed.\n\nTheorem exer4: forall p q r:\nProp, (p->(q/\\r))->(p->q).\nintros.\napply H in H0 as  H1.\ndestruct H1.\napply H1.\nQed.\n\nTheorem exer5: forall p q:\nProp, (p/\\(q->~p))->(p/\\~q).\nintros.\ndestruct H.\nsplit.\napply H.\nunfold not.\nintro.\napply H0 in H1 as H2.\napply H2.\nexact H.\nQed.\n\nTheorem exer6: forall p q r:\nProp, p\\/q->p\\/r->p\\/(q/\\r).\nintros.\ndestruct H.\n+left.\napply H.\n+destruct H0.\n-left.\napply H0.\n-right.\nsplit.\napply H.\napply H0.\nQed.\n\nTheorem exer7: forall p q:\nProp, ((p->q)->p)->p.\nintros.\ndestruct (classic p).\n+apply H0.\n+apply H.\nintro.\ncontradiction.\nQed.\n\nRequire Import Classical.\nTheorem exer8: forall p q:\nProp, ~(p/\\q)->~p\\/~q.\nintros.\n(*tauto.*)\ndestruct(classic (~p\\/~q)).\n+ apply H0.\n+ right.\ndestruct(classic (~p)).\n-intro.\napply H0.\nleft.\napply H1.\n-apply NNPP in H1.\nintro.\napply H.\nsplit.\napply H1.\napply H2.\nQed.\n\nRequire Import Classical.\nTheorem exer9: forall p q r:\nProp, ~r->p\\/((p\\/r)->q).\nintros.\napply NNPP.\nintro.\napply H0.\nright.\napply NNPP.\nintro.\napply H1.\nintro.\ndestruct H2.\n+exfalso.\napply H0.\nleft.\napply H2.\n+exfalso.\napply H.\napply H2.\nQed.\n\nTheorem exer11: forall p q:\nProp, (p/\\~p)->q.\nintros.\ndestruct H.\nexfalso.\napply H0.\napply H.\nQed.\n\nTheorem exer12: forall p q:\nProp, p->p\\/q.\nintros.\nleft.\napply H.\nQed.\n\nTheorem exer13: forall p q:\nProp, (p->q)->(~q->~p).\nintros.\nintro.\napply H0.\napply H.\napply H1.\nQed.\n\nTheorem exer14: forall p q:\nProp, p/\\q ->q/\\p.\nintros.\ndestruct H.\nsplit.\napply H0.\napply H.\nQed.\n\n\nTheorem exer15: forall p q:\nProp, p/\\q->p->p/\\q.\nintros.\ndestruct H.\nsplit.\napply H.\napply H1.\nQed.\n\nTheorem exer22: forall p q r:\nProp, (p->q)->(p->q->r)->(p->r).\nintros.\napply H0 in H.\napply H.\napply H1.\napply H1.\nQed.\n\nTheorem exer22_2: forall p q r:\nProp, (p->q)->(p->q->r)->(p->r).\nintros.\napply H0.\napply H1.\napply H.\nexact H1.\nQed.\n\nTheorem exer29: forall p q r:\nProp, (p->q)->(r->~q)->(p->~r).\nintros.\nintro.\napply H0.\nexact H2.\napply H.\nexact H1.\nQed.\n\nTheorem exer36: forall p q:\nProp, (p->q)->p->q.\nintros.\napply H.\nexact H0.\nQed.\n\nTheorem exer37: forall p q r:\nProp, p\\/q->~p\\/~r->r->q.\nintros.\ndestruct H.\n+destruct H0.\n-contradiction.\n-contradiction.\n+exact H.\nQed.\nRequire Import Coq.Logic.Classical_Prop.\nLemma HS1 : forall p q r : \nProp, (q -> r) -> ((p -> q) -> (p -> r)).\nintros.\napply H.\napply H0.\nexact H1.\n(*\napply H0 in H1.\napply H in H1.\nexact H1.\n*)\nQed.\nLemma HS2 : forall p q r : \nProp, (p -> q) -> ((q -> r) -> (p -> r)).\nProof.\nintros.\napply H0.\napply H.\nexact H1.\nQed.\n\nLemma proj1: forall p q:\nProp, p/\\q->q.\nProof.\nintros.\ndestruct H.\nexact H0.\nQed.\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q -> Q \\/ P.\nProof.\nintros P Q [HP | HQ].\n-right.\napply HP.\n-left.\napply HQ.\n\n\n\n\n\n\n\n", "meta": {"author": "JoanDaniel18", "repo": "Coq_Test-Projects", "sha": "56142f09f040332abe1d4462488a1a389fd412ab", "save_path": "github-repos/coq/JoanDaniel18-Coq_Test-Projects", "path": "github-repos/coq/JoanDaniel18-Coq_Test-Projects/Coq_Test-Projects-56142f09f040332abe1d4462488a1a389fd412ab/coqprojects/ExercisestoPracticeQuiz.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.6703238629146405}}
{"text": "Require Import Coquelicot.Coquelicot.\nRequire Import Reals.\nRequire Import LibUtils List Permutation RealAdd ClassicUtils ELim_Seq ListAdd Sums CoquelicotAdd Isomorphism PairEncoding.\nRequire Import Reals Psatz Morphisms.\n\nRequire Import Classical_Prop Classical_Pred_Type.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nLocal Open Scope R_scope.\n\nSection sums.\n\n  Local Existing Instance Rbar_le_pre.\n  Local Existing Instance Rbar_le_part.\n\n  Definition list_Rbar_sum (l : list Rbar) : Rbar\n    := fold_right Rbar_plus (Finite 0) l.\n               \n  Lemma list_Rbar_sum_const_mulR {A : Type} f (l : list A) :\n    forall (r:R), list_Rbar_sum (map (fun x => Rbar_mult r (f x)) l)  =\n              Rbar_mult r (list_Rbar_sum (map (fun x => f x) l)).\n  Proof.\n    intro r.\n    induction l; simpl.\n    - f_equal; lra.\n    - rewrite IHl.\n      now rewrite Rbar_mult_r_plus_distr.\n  Qed.\n\n  Definition sum_Rbar_n (f:nat->Rbar) (n:nat) : Rbar\n    := list_Rbar_sum (map f (seq 0 n)).\n\n  Global Instance sum_Rbar_n_proper : Proper (pointwise_relation _ eq ==> eq ==> eq) sum_Rbar_n.\n  Proof.\n    intros ??????.\n    unfold sum_Rbar_n.\n    f_equal; subst.\n    now apply map_ext; intros.\n  Qed.\n  \n  Instance fold_right_plus_le_proper :\n    Proper (Rbar_le ==> Forall2 Rbar_le ==> Rbar_le) (fold_right Rbar_plus).\n  Proof.\n    intros a b eqq1 x y eqq2.\n    revert a b eqq1.\n    induction eqq2; simpl; trivial; intros.\n    apply Rbar_plus_le_compat; trivial.\n    now apply IHeqq2.\n  Qed.\n\n  Lemma Rbar_plus_nneg_compat (a b : Rbar) :\n    Rbar_le 0 a ->\n    Rbar_le 0 b ->\n    Rbar_le 0 (Rbar_plus a b).\n  Proof.\n    generalize (Rbar_plus_le_compat  0 a 0 b); intros HH.\n    rewrite Rbar_plus_0_r in HH.\n    auto.\n  Qed.\n\n  Lemma Rbar_mult_nneg_compat (a b : Rbar) :\n    Rbar_le 0 a ->\n    Rbar_le 0 b ->\n    Rbar_le 0 (Rbar_mult a b).\n  Proof.\n    destruct a; destruct b; simpl; rbar_prover.\n    intros.\n    generalize (Rmult_le_compat  0 r 0 r0); intros HH.\n    rewrite Rmult_0_r in HH.\n    apply HH; lra.\n  Qed.\n\n  Lemma Rbar_mult_0_lt (a b : Rbar) :\n      Rbar_lt 0 a ->\n      Rbar_lt 0 b ->\n      Rbar_lt 0 (Rbar_mult a b).\n    Proof.\n      intros.\n      destruct a; destruct b; try now simpl in *.\n      - simpl in *.\n        now apply Rmult_lt_0_compat.\n      - simpl in H.\n        now rewrite Rbar_mult_comm, Rbar_mult_p_infty_pos.\n      - simpl in H0.\n        now rewrite Rbar_mult_p_infty_pos.\n    Qed.\n\n  Lemma Rbar_le_incr0 (f : nat -> Rbar) :\n    (forall n, Rbar_le (f n) (f (S n))) ->\n    forall n k, (Rbar_le (f n) (f (n + k)%nat)).\n  Proof.\n    intros.\n    induction k.\n    - replace (n + 0)%nat with n by lia.\n      apply Rbar_le_refl.\n    - eapply Rbar_le_trans.\n      apply IHk.\n      replace (n + S k)%nat with (S (n + k)%nat) by lia.\n      apply H.\n  Qed.\n\n  Lemma Rbar_le_incr (f : nat -> Rbar) :\n    (forall n, Rbar_le (f n) (f (S n))) ->\n    forall n m, (n<=m)%nat -> Rbar_le (f n) (f m).\n  Proof.\n    intros.\n    replace (m) with (n + (m-n))%nat by lia.\n    now apply Rbar_le_incr0.\n  Qed.\n\n  Lemma sum_Rbar_n_pos_incr (f : nat -> Rbar) :\n    (forall i : nat, Rbar_le 0 (f i)) ->\n    forall n : nat, Rbar_le (sum_Rbar_n f n) (sum_Rbar_n f (S n)).\n  Proof.\n    unfold sum_Rbar_n, list_Rbar_sum; intros.\n    rewrite seq_Sn, map_app, fold_right_app.\n    apply fold_right_plus_le_proper; try reflexivity.\n    simpl.\n    apply Rbar_plus_nneg_compat; trivial.\n    reflexivity.\n  Qed.\n\n  Lemma list_Rbar_sum_nneg_nneg (l:list Rbar) :\n    (forall x, In x l -> Rbar_le 0 x) ->\n    Rbar_le 0 (list_Rbar_sum l).\n  Proof.\n    intros.\n    induction l; [reflexivity |].\n    simpl list_Rbar_sum.\n    apply Rbar_plus_nneg_compat.\n    - apply H; simpl; tauto.\n    - apply IHl; intros.\n      apply H; simpl; tauto.\n  Qed.\n\n  Lemma sum_Rbar_n_nneg_nneg (f : nat -> Rbar) n :\n    (forall i : nat, (i <= n)%nat -> Rbar_le 0 (f i)) ->\n    Rbar_le 0 (sum_Rbar_n f n).\n  Proof.\n    intros.\n    apply list_Rbar_sum_nneg_nneg; intros.\n    apply in_map_iff in H0.\n    destruct H0 as [? [??]]; subst.\n    apply in_seq in H1.\n    apply H; lia.\n  Qed.\n\n  Lemma nneg_fold_right_Rbar_plus_nneg l :\n        Forall (Rbar_le 0) l ->\n        Rbar_le 0 (fold_right Rbar_plus 0 l).\n  Proof.\n    induction l.\n    - simpl; reflexivity.\n    -  simpl map; simpl fold_right.\n       intros HH; invcs HH.\n       apply Rbar_plus_nneg_compat; auto.\n  Qed.\n\n  Lemma list_Rbar_sum_nneg_perm (l1 l2:list Rbar) :\n    Forall (Rbar_le 0) l1 ->\n    Forall (Rbar_le 0) l2 ->\n    Permutation l1 l2 ->\n    list_Rbar_sum l1 = list_Rbar_sum l2.\n  Proof.\n    intros.\n    unfold list_Rbar_sum.\n    induction H1; simpl; trivial.\n    - invcs H; invcs H0; now rewrite IHPermutation.\n    - invcs H; invcs H0; invcs H4; invcs H5.\n      repeat rewrite <- Rbar_plus_assoc\n      ; try apply ex_Rbar_plus_pos; trivial\n      ; try apply nneg_fold_right_Rbar_plus_nneg\n      ; trivial.\n      f_equal.\n      now rewrite Rbar_plus_comm.\n    - assert (Forall (Rbar_le 0) l')\n        by now rewrite <- H1_.\n      now rewrite IHPermutation1, IHPermutation2.\n  Qed.\n\n  Lemma nneg_fold_right_Rbar_plus_acc l acc :\n    Rbar_le 0 acc ->\n    Forall (Rbar_le 0) l ->    \n    fold_right Rbar_plus acc l = Rbar_plus acc (fold_right Rbar_plus (Finite 0) l).\n  Proof.\n    intros pos1 pos2; revert pos1.\n    induction pos2; intros.\n    - now rewrite Rbar_plus_0_r.\n    - simpl.\n      rewrite IHpos2; trivial.\n      repeat rewrite <- Rbar_plus_assoc_nneg; trivial\n      ; try now apply nneg_fold_right_Rbar_plus_nneg.\n      f_equal.\n      apply Rbar_plus_comm.\n  Qed.\n\n  Lemma list_Rbar_sum_nneg_plus (l1 l2 : list Rbar) :\n    Forall (Rbar_le 0) l1 ->\n    Forall (Rbar_le 0) l2 ->\n    list_Rbar_sum (l1 ++ l2) =\n      Rbar_plus (list_Rbar_sum l1) (list_Rbar_sum l2).\n  Proof.\n    intros.\n    unfold list_Rbar_sum.\n    rewrite fold_right_app.\n    rewrite nneg_fold_right_Rbar_plus_acc; trivial\n    ; try now apply nneg_fold_right_Rbar_plus_nneg.\n    now rewrite Rbar_plus_comm.\n  Qed.    \n\n  Lemma sum_Rbar_n_nneg_plus (f g:nat->Rbar) (n:nat) :\n    (forall x, (x < n)%nat -> Rbar_le 0 (f x)) ->\n    (forall x, (x < n)%nat -> Rbar_le 0 (g x)) ->\n      sum_Rbar_n (fun x => Rbar_plus (f x) (g x)) n =\n        Rbar_plus (sum_Rbar_n f n) (sum_Rbar_n g n).\n  Proof.\n    unfold sum_Rbar_n; intros.\n    induction n; [simpl; f_equal; lra | ].\n    rewrite seq_Sn.\n    rewrite plus_0_l.\n\n    repeat rewrite map_app.\n    repeat rewrite list_Rbar_sum_nneg_plus; simpl\n    ; try solve [apply Forall_forall; intros ? HH\n                 ; apply in_map_iff in HH\n                 ; destruct HH as [? [? HH]]; subst\n                 ; apply in_seq in HH\n                 ; try apply Rbar_plus_nneg_compat\n                 ; try (apply H || apply H0); lia\n                |\n                  repeat constructor\n                  ; try apply Rbar_plus_nneg_compat\n                  ; try (apply H || apply H0); lia].\n    rewrite IHn\n    ; intros; try solve [(apply H || apply H0); lia].\n    repeat rewrite Rbar_plus_0_r.\n    repeat rewrite <- Rbar_plus_assoc_nneg\n    ; trivial\n    ; try apply Rbar_plus_nneg_compat\n    ; (try solve [\n            try (apply list_Rbar_sum_nneg_nneg\n                 ; intros ? HH\n                 ; apply in_map_iff in HH\n                 ; destruct HH as [? [? HH]]; subst\n                 ; apply in_seq in HH)\n            ; try (apply H || apply H0); lia]).\n    f_equal.\n    repeat rewrite Rbar_plus_assoc_nneg\n    ; trivial\n    ; (try solve [\n            try (apply list_Rbar_sum_nneg_nneg\n                 ; intros ? HH\n                 ; apply in_map_iff in HH\n                 ; destruct HH as [? [? HH]]; subst\n                 ; apply in_seq in HH)\n            ; try (apply H || apply H0); lia]).\n    f_equal.\n    apply Rbar_plus_comm.\n  Qed.      \n\n  Lemma fold_right_Rbar_plus_const {A} c (l:list A) :\n    fold_right Rbar_plus 0 (map (fun _ => c) l) = (Rbar_mult (INR (length l)) c).\n  Proof.\n    induction l; intros.\n    - simpl.\n      now rewrite Rbar_mult_0_l.\n    - simpl length.\n      rewrite S_INR; simpl.\n      rewrite IHl.\n      generalize (pos_INR (length l)); intros HH.\n      destruct c; simpl; rbar_prover.\n  Qed.\n\n  Lemma seq_sum_list_sum {T}\n        (f:T -> Rbar) (B:list T) d :\n    f d = 0 ->\n    ELim_seq (fun i : nat => sum_Rbar_n (fun n : nat => f (nth n B d)) i) = list_Rbar_sum (map f B).\n  Proof.\n    intros.\n    rewrite (ELim_seq_ext_loc _ (fun _ => sum_Rbar_n (fun n : nat => f (nth n B d)) (length B))).\n    - rewrite ELim_seq_const.\n      unfold sum_Rbar_n.\n      f_equal.\n      now rewrite <- map_map, <- list_as_nthseq.\n    - exists (length B); intros.\n      unfold sum_Rbar_n.\n      replace n with (length B + (n - length B))%nat by lia.\n      rewrite seq_plus.\n      unfold list_Rbar_sum.\n      rewrite map_app, fold_right_app.\n      f_equal.\n      rewrite (seq_shiftn_map (length B)).\n      rewrite map_map.\n      rewrite (map_ext\n                 (fun x : nat => f (nth (length B + x) B d ))\n                 (fun x : nat => 0)).\n      + rewrite fold_right_Rbar_plus_const.\n        now rewrite Rbar_mult_0_r.\n      + intros ?.\n        rewrite nth_overflow; trivial.\n        lia.\n  Qed.\n\n    Global Instance list_Rbar_sum_monotone : Proper (Forall2 Rbar_le ==> Rbar_le) list_Rbar_sum.\n  Proof.\n    intros ???.\n    induction H; simpl.\n    - reflexivity.\n    - now apply Rbar_plus_le_compat.\n  Qed.\n    \n  Global Instance sum_Rbar_n_monotone : Proper (pointwise_relation _ Rbar_le ==> eq ==> Rbar_le) sum_Rbar_n.\n  Proof.\n    intros ??????; subst.\n    apply list_Rbar_sum_monotone.\n    apply Forall2_map_f.\n    apply Forall2_refl_in.\n    apply Forall_forall; intros.\n    apply H.\n  Qed.\n\n  Lemma list_Rbar_sum_map_finite (l:list R) : list_Rbar_sum (map Finite l) = list_sum l.\n  Proof.\n    unfold list_Rbar_sum.\n    induction l; simpl; trivial.\n    now rewrite IHl; simpl.\n  Qed.\n\nEnd sums.\n\nSection rbar_empty_props.\n  Local Existing Instance Rbar_le_pre.\n  Local Existing Instance Rbar_le_part.\n\n    (** * Extended Emptiness is decidable *)\n\n  Definition Rbar_Empty (E : Rbar -> Prop) :=\n    Rbar_glb (fun x => x = 0 \\/ E x) = Rbar_lub (fun x => x = 0 \\/ E x)\n    /\\ Rbar_glb (fun x => x = 1 \\/ E x) = Rbar_lub (fun x => x = 1 \\/ E x).\n\n  Lemma Rbar_Empty_correct_1 (E : Rbar -> Prop) :\n    Rbar_Empty E -> forall x, ~ E x.\n  Proof.\n    intros.\n    unfold Rbar_Empty, Rbar_glb, Rbar_lub, proj1_sig in *.\n    repeat match_destr_in H.\n    destruct H; subst.\n    unfold Rbar_is_glb, Rbar_is_lub in *.\n    intuition.\n    assert (x1 = 0)\n      by (apply Rbar_le_antisym; eauto).\n    assert (x3 = 1)\n      by (apply Rbar_le_antisym; eauto).\n    subst.\n    specialize (H2 x).\n    cut_to H2; [| tauto].\n    specialize (H4 x).\n    cut_to H4; [| tauto].\n    generalize (Rbar_le_trans _ _ _ H4 H2); simpl; lra.\n  Qed.\n\n  Lemma Rbar_Empty_correct_2 (E : Rbar -> Prop) :\n    (forall x, ~ E x) -> Rbar_Empty E.\n  Proof.\n    intros H.\n    unfold Rbar_Empty, Rbar_glb, Rbar_lub, proj1_sig in *.\n    repeat match_destr.\n    unfold Rbar_is_glb, Rbar_is_lub in *.\n    destruct r; destruct r0; destruct r1; destruct r2.\n    assert (x = Finite 0).\n    {\n      apply Rbar_le_antisym; eauto 3.\n      apply H1; intros ?[]; subst; [reflexivity | eelim H; eauto].\n    }\n    assert (x0 = Finite 0).\n    {\n      apply Rbar_le_antisym; eauto 3.\n      apply H3; intros ?[]; subst; [reflexivity | eelim H; eauto].\n    } \n    assert (x1 = Finite 1).\n    {\n      apply Rbar_le_antisym; eauto 3.\n      apply H5; intros ?[]; subst; [reflexivity | eelim H; eauto].\n    } \n    assert (x2 = Finite 1).\n    {\n      apply Rbar_le_antisym; eauto 3.\n      apply H7; intros ?[]; subst; [reflexivity | eelim H; eauto].\n    }\n    split; congruence.\n  Qed.\n\n  Lemma Rbar_Empty_dec (E : Rbar -> Prop) :\n    {~Rbar_Empty E}+{Rbar_Empty E}.\n  Proof.\n    unfold Rbar_Empty.\n    destruct (Rbar_eq_dec (Rbar_glb (fun x => x = 0 \\/ E x)) (Rbar_lub (fun x => x = 0 \\/ E x))).\n    - destruct (Rbar_eq_dec (Rbar_glb (fun x => x = 1 \\/ E x)) (Rbar_lub (fun x => x = 1 \\/ E x))).\n      + right; tauto.\n      + left; tauto.\n    - left; tauto.\n  Defined.\n\n  Lemma not_Rbar_Empty_dec (E : Rbar -> Prop) : (Decidable.decidable (exists x, E x)) ->\n                                        {(exists x, E x)} + {(forall x, ~ E x)}.\n  Proof.\n    intros.\n    destruct (Rbar_Empty_dec E).\n    - left.\n      destruct H; trivial.\n      contradict n.\n      apply Rbar_Empty_correct_2; intros ??.\n      apply H; eauto.\n    - right; intros.\n      now apply Rbar_Empty_correct_1.\n  Qed.      \n\n  Lemma Rbar_uniqueness_dec P : (exists ! x : Rbar, P x) -> {x : Rbar | P x}.\n  Proof.\n    intros HH.\n    exists (Rbar_lub P).\n    destruct HH as [? [??]].\n    replace (Rbar_lub P) with x; trivial.\n    apply sym_eq, Rbar_is_lub_unique.\n    split.\n    - intros ??.\n      rewrite (H0 _ H1); apply Rbar_le_refl.\n    - firstorder.\n  Qed.\n\nEnd rbar_empty_props.\n\nSection rbar_props.\n  \n  Lemma is_finite_dec (a:Rbar) : {is_finite a} + {~ is_finite a}.\n  Proof.\n    unfold is_finite; destruct a; simpl; intuition congruence.\n  Qed.\n\n(*\n  Lemma Rle_forall_le: forall a b : R, (forall eps : posreal, a <= b + eps) -> a <= b.\n  Proof.\n    intros.\n    apply Rlt_forall_le; intros.\n    specialize (H (pos_div_2 eps)).\n    simpl in H.\n    eapply Rle_lt_trans; try eapply H.\n    destruct eps; simpl.\n    lra.\n  Qed.\n\n  Lemma Rbar_le_forall_Rbar_le: forall a b : Rbar, (forall eps : posreal, Rbar_le a (Rbar_plus b eps)) -> Rbar_le a b.\n  Proof.\n    intros [] []; simpl; intros HH; trivial\n    ; try (apply HH; exact posreal1).\n    now apply Rle_forall_le.\n  Qed.\n\n *)\n  Lemma Rbar_glb_ge (E:Rbar->Prop) c :\n    (forall x, E x -> Rbar_le c x) ->\n    Rbar_le c (Rbar_glb E).\n  Proof.\n    unfold Rbar_glb, proj1_sig; match_destr; intros.\n    apply r; intros ??.\n    now apply H.\n  Qed.\n\nEnd rbar_props.\n\nSection glb_props.\n\n  Lemma Rbar_is_glb_fin_close_classic {E a} (eps:posreal):\n    Rbar_is_glb E (Finite a) -> exists x, E x /\\ Rbar_le x (a + eps).\n  Proof.\n    intros HH1.\n    apply NNPP; intros HH2.\n    generalize (not_ex_all_not _ _ HH2); intros HH3.\n    assert (Rbar_is_glb E (Finite (a + eps))).\n    {\n      destruct HH1.\n      split.\n      - intros ??.\n        specialize (H _ H1).\n        specialize (HH3 x).\n        intuition.\n        apply Rbar_not_le_lt in H3.\n        now apply Rbar_lt_le.\n      - intros.\n        eapply Rbar_le_trans; try now eapply H0.\n        simpl.\n        destruct eps; simpl; lra.\n    }\n    apply Rbar_is_glb_unique in HH1.\n    apply Rbar_is_glb_unique in H.\n    rewrite H in HH1.\n    invcs HH1.\n    destruct eps; simpl in *; lra.\n  Qed.\n\nEnd glb_props.\n  \nSection elim_seq_props.\n  Local Existing Instance Rbar_le_pre.\n  Local Existing Instance Rbar_le_part.\n\n  Lemma ELim_seq_nneg (f : nat -> Rbar) :\n    (forall n, Rbar_le 0 (f n)) ->\n    Rbar_le 0 (ELim_seq f).\n  Proof.\n    intros.\n    generalize (ELim_seq_le (fun _ => 0) f); intros.\n    rewrite ELim_seq_const in H0.\n    now apply H0.\n  Qed.\n\n    Lemma Elim_seq_sum_pos_fin_n_fin f r :\n    (forall n, Rbar_le 0 (f n)) ->\n    ELim_seq\n        (fun i : nat => sum_Rbar_n f i) = Finite r ->\n    forall n, is_finite (f n).\n  Proof.\n    intros.\n    generalize (ELim_seq_nneg _ H); intros nneglim.\n    case_eq (f n); intros; simpl; [reflexivity |..].\n    - assert (HH:Rbar_le (ELim_seq (fun _ => sum_Rbar_n f (S n))) (ELim_seq (fun i : nat => sum_Rbar_n f i))).\n      {\n        apply ELim_seq_le_loc.\n        exists (S n); intros.\n        apply (le_ind (S n) (fun x => Rbar_le (sum_Rbar_n f (S n)) (sum_Rbar_n f x))); trivial.\n        - reflexivity.\n        - intros.\n          eapply Rbar_le_trans; try eapply H4.\n          apply sum_Rbar_n_pos_incr; trivial.\n      }\n      rewrite ELim_seq_const in HH.\n      rewrite H0 in HH.\n      \n      unfold sum_Rbar_n in HH.\n      rewrite seq_Sn, map_app in HH; simpl in HH.\n      rewrite H1 in HH.\n      erewrite list_Rbar_sum_nneg_perm in HH\n      ; try eapply Permutation_app_comm.\n      + simpl in HH.\n        unfold Rbar_plus in HH; simpl in HH.\n        assert (Rbar_le 0 (list_Rbar_sum (map f (seq 0 n)))).\n        {\n          apply list_Rbar_sum_nneg_nneg; intros.\n          apply in_map_iff in H2.\n          now destruct H2 as [?[??]]; subst.\n        }\n        destruct (list_Rbar_sum (map f (seq 0 n))); simpl in HH\n        ; try contradiction.\n      + apply List.Forall_app; split.\n        * apply Forall_map; apply Forall_forall; intros; trivial.\n        * repeat constructor.\n      + apply List.Forall_app; split.\n        * repeat constructor.\n        * apply Forall_map; apply Forall_forall; intros; trivial.\n    - specialize (H n).\n      rewrite H1 in H.\n      simpl in H.\n      contradiction.\n  Qed.\n\n  Lemma Lim_seq_sum_2n2 : Lim_seq (fun n : nat => list_sum (map (fun x : nat => / 2 ^ x) (seq 0 n))) = 2.\n  Proof.\n    generalize (is_series_geom (1/2))\n    ; intros HH.\n    cut_to HH; [| rewrite Rabs_pos_eq; lra].\n    apply is_series_Reals in HH.\n    apply infinite_sum_is_lim_seq in HH.\n    replace (/ (1 - 1 / 2)) with 2 in HH by lra.\n    apply is_lim_seq_unique in HH.\n    erewrite Lim_seq_ext in HH\n    ; [| intros; rewrite <- sum_f_R0_sum_f_R0'; reflexivity].\n    erewrite Lim_seq_ext in HH\n    ; [| intros; rewrite <- sum_f_R0'_list_sum; reflexivity].\n    rewrite <- Lim_seq_incr_1.\n    rewrite <- HH.\n    apply Lim_seq_ext; intros.\n    f_equal.\n    apply map_ext; intros.\n    replace (1/2) with (/2) by lra.\n    rewrite Rinv_pow; try lra.\n  Qed.\n\n  Lemma Lim_seq_sum_2n : Lim_seq (fun n : nat => list_sum (map (fun x : nat => / 2 ^ (S x)) (seq 0 n))) = 1.\n  Proof.\n    transitivity (Lim_seq (fun n : nat => list_sum (map (fun x : nat => / 2 ^ x) (seq 1 n)))).\n    - apply Lim_seq_ext; intros.\n      now rewrite <- seq_shift, map_map.\n    - generalize (Lim_seq_sum_2n2); intros HH.\n      rewrite <- Lim_seq_incr_1 in HH.\n      erewrite Lim_seq_ext in HH\n      ; [| intros; rewrite <- cons_seq; simpl; reflexivity].\n      rewrite Lim_seq_plus in HH.\n      + rewrite Lim_seq_const in HH.\n        rewrite Rinv_1 in HH.\n        destruct (Lim_seq (fun n : nat => list_sum (map (fun x : nat => / 2 ^ x) (seq 1 n)))); simpl in *\n        ; invcs HH; try lra.\n        f_equal; lra.\n      + apply ex_lim_seq_const.\n      + apply ex_lim_seq_incr; intros.\n        rewrite seq_Sn, map_app, list_sum_cat.\n        simpl.\n        assert (0 < (/ (2 * 2 ^ n))).\n        {\n          intros.\n          apply Rinv_pos.\n          generalize (pow_lt 2 n); lra.\n        }\n        lra.\n      + apply ex_Rbar_plus_pos.\n        * rewrite Lim_seq_const; simpl; lra.\n        * apply Lim_seq_pos; intros.\n          apply list_sum_pos_pos'.\n          apply Forall_map.\n          apply Forall_forall; intros.\n          left.\n          apply Rinv_pos.\n          apply pow_lt; lra.\n  Qed.\n\n  Lemma ELim_seq_sum_2n : ELim_seq (fun n : nat => list_sum (map (fun x : nat => / 2 ^ (S x)) (seq 0 n))) = 1.\n  Proof.\n    rewrite Elim_seq_fin.\n    apply Lim_seq_sum_2n.\n  Qed.\n\n\n  Lemma ELim_seq_Rbar_sum_2n :\n    ELim_seq (sum_Rbar_n (fun x : nat => Finite (/ 2 ^ (S x)))) = 1.\n  Proof.\n    unfold sum_Rbar_n.\n    erewrite ELim_seq_ext\n    ; [| intros ?; rewrite <- map_map; rewrite list_Rbar_sum_map_finite; reflexivity].\n    apply ELim_seq_sum_2n.\n  Qed.\n    \n  Lemma ELim_seq_sum_eps2n f eps :\n    (0 <= eps) ->\n    (forall x, Rbar_le 0 (f x)) ->\n    ELim_seq (fun i => sum_Rbar_n (fun a => Rbar_plus (f a) (eps / 2 ^ (S a))) i) =\n      Rbar_plus (ELim_seq (fun i => sum_Rbar_n f i)) eps.\n  Proof.\n    intros.\n    assert (epsdivpos:forall i, 0 <= (eps / (2 * 2 ^ i))).\n    {\n      intros.\n      apply Rdiv_le_0_compat; trivial.\n      apply Rmult_lt_0_compat; try lra.\n      apply pow_lt; lra.\n    } \n\n    erewrite ELim_seq_ext\n    ; [| intros; rewrite sum_Rbar_n_nneg_plus; [reflexivity |..]]\n    ; trivial.\n    - rewrite ELim_seq_plus.\n      + f_equal.\n        rewrite (ELim_seq_ext _ (sum_Rbar_n (fun x : nat => Rbar_mult eps (/ 2 ^ (S x))))) by reflexivity.\n        unfold sum_Rbar_n.\n        erewrite ELim_seq_ext\n        ; [| intros; apply list_Rbar_sum_const_mulR].\n        generalize ELim_seq_Rbar_sum_2n.\n        unfold sum_Rbar_n; intros HH.\n        rewrite ELim_seq_scal_l.\n        * rewrite HH.\n          now rewrite Rbar_mult_1_r.\n        * now rewrite HH.\n      + apply ex_Elim_seq_incr; intros.\n        now apply sum_Rbar_n_pos_incr.\n      + apply ex_Elim_seq_incr; intros.\n        apply sum_Rbar_n_pos_incr; intros; simpl; trivial.\n      + apply ex_Rbar_plus_pos\n        ; apply ELim_seq_nneg\n        ; intros\n        ; apply sum_Rbar_n_nneg_nneg\n        ; intros\n        ; trivial\n        ; simpl\n        ; trivial.\n    - intros; simpl; trivial.\n  Qed.\n\n  Lemma ELim_seq_sup_incr (f : nat -> Rbar) :\n    (forall n, Rbar_le (f n) (f (S n))) ->\n    ELim_seq f = ELimSup_seq f.\n  Proof.\n    intros.\n    unfold ELim_seq.\n    apply ex_Elim_seq_incr in H.\n    unfold ex_Elim_seq in H.\n    rewrite <- H.\n    destruct (ELimSup_seq f); simpl; try congruence.\n    apply Rbar_finite_eq.\n    lra.\n  Qed.\n\n  Lemma Elim_seq_le_bound (f : nat -> Rbar) (B:Rbar) :\n    (forall n, Rbar_le (f n) B) ->\n    Rbar_le (ELim_seq f) B.\n  Proof.\n    intros.\n    replace B with (ELim_seq (fun _ => B)).\n    now apply ELim_seq_le.\n    apply ELim_seq_const.\n  Qed.\n\n  Lemma sum_Rbar_n_Sn (f : nat -> Rbar) (n : nat) :\n    (forall n, Rbar_le 0 (f n)) ->\n    sum_Rbar_n f (S n) = Rbar_plus (sum_Rbar_n f n) (f n).\n  Proof.\n    intros.\n    unfold sum_Rbar_n.\n    rewrite seq_Sn; simpl.\n    rewrite map_app.\n    rewrite list_Rbar_sum_nneg_plus.\n    - simpl.\n      now rewrite Rbar_plus_0_r.\n    - now apply Forall_map; apply Forall_forall; intros.\n    - now apply Forall_map; apply Forall_forall; intros.\n  Qed.\n  \n  Lemma sum_Rbar_n_pos_Sn (f : nat -> Rbar) (n : nat) :\n    (forall n, Rbar_le 0 (f n)) ->\n    Rbar_le (sum_Rbar_n f n) (sum_Rbar_n f (S n)).\n  Proof.\n    intros.\n    replace (sum_Rbar_n f n) with (Rbar_plus (sum_Rbar_n f n) 0).\n    - rewrite sum_Rbar_n_Sn; trivial.\n      apply Rbar_plus_le_compat.\n      + apply Rbar_le_refl.\n      + apply H.\n    - now rewrite Rbar_plus_0_r.\n  Qed.\n\nEnd elim_seq_props.\n\nSection lim_sum.\n\n    Lemma list_Rbar_sum_cat (l1 l2 : list Rbar) :\n    (forall x1, In x1 l1 -> Rbar_le 0 x1) ->\n    (forall x2, In x2 l2 -> Rbar_le 0 x2) ->    \n    list_Rbar_sum (l1 ++ l2) = Rbar_plus (list_Rbar_sum l1) (list_Rbar_sum l2).\n  Proof.\n    induction l1.\n    * simpl.\n      now rewrite Rbar_plus_0_l.\n    * intros.\n      simpl.\n      rewrite IHl1; trivial.\n      -- rewrite Rbar_plus_assoc_nneg; trivial.\n         ++ apply H.\n            simpl.\n            now left.\n         ++ apply list_Rbar_sum_nneg_nneg.\n            intros.\n            apply H.\n            now apply in_cons.\n         ++ apply list_Rbar_sum_nneg_nneg.\n            intros.\n            now apply H0.\n      -- intros; apply H.\n         now apply in_cons.\n   Qed.\n\n  \n Lemma list_Rbar_sum_nneg_nested_prod {A B:Type} (X:list A) (Y:list B) (f:A->B->Rbar) :\n    (forall x y, In x X -> In y Y -> Rbar_le 0 (f x y)) ->\n    list_Rbar_sum (map (fun x => list_Rbar_sum (map (fun y => f x y) Y)) X) =\n    list_Rbar_sum (map (fun xy => f (fst xy) (snd xy)) (list_prod X Y)).\n   Proof.\n     intros.\n     induction X.\n     - simpl.\n       induction Y.\n       + now simpl.\n       + reflexivity.\n     - simpl.\n       rewrite IHX, map_app, list_Rbar_sum_cat.\n       + f_equal.\n         now rewrite map_map.\n       + intros.\n         rewrite in_map_iff in H0.\n         destruct H0 as [[? ?] [? ?]].\n         rewrite <- H0.\n         apply in_map_iff in H1.\n         destruct H1 as [? [? ?]].\n         inversion H1.\n         apply H.\n         * simpl; now left.\n         * now rewrite <- H5.\n       + intros.\n         rewrite in_map_iff in H0.\n         destruct H0 as [[? ?] [? ?]].\n         rewrite <- H0.\n         rewrite in_prod_iff in H1.\n         apply H.\n         * now apply in_cons.\n         * easy.\n       + intros.\n         apply H; trivial.\n         now apply in_cons.\n    Qed.\n\n   Lemma list_Rbar_sum_nest_prod (f : nat -> nat -> Rbar ) (l1 l2 : list nat) :\n    (forall a b, Rbar_le 0 (f a b)) ->\n     list_Rbar_sum\n       (map (fun i : nat => list_Rbar_sum (map (fun j : nat => f i j) l2)) l1) =\n     list_Rbar_sum (map (fun '(a, b) => f a b) (list_prod l1 l2)).\n   Proof.\n     intros.\n     induction l1.\n     - simpl.\n       induction l2.\n       + now simpl.\n       + reflexivity.\n     - simpl.\n       rewrite IHl1, map_app, list_Rbar_sum_cat.\n       + f_equal.\n         now rewrite map_map.\n       + intros.\n         rewrite in_map_iff in H0.\n         destruct H0 as [[? ?] [? ?]].\n         now rewrite <- H0.\n       + intros.\n         rewrite in_map_iff in H0.\n         destruct H0 as [[? ?] [? ?]].\n         now rewrite <- H0.\n    Qed.\n\n   Lemma sum_Rbar_n_pair_list_sum (f : nat -> nat -> Rbar ) (n m : nat) :\n    (forall a b, Rbar_le 0 (f a b)) ->\n     sum_Rbar_n (fun x0 => sum_Rbar_n (fun n1 => f x0 n1) m) n = \n     list_Rbar_sum (map (fun '(a, b) => f a b) (list_prod (seq 0 n) (seq 0 m))).\n   Proof.\n     intros.\n     unfold sum_Rbar_n.\n     apply list_Rbar_sum_nest_prod.\n     apply H.\n   Qed.\n\nLemma list_Rbar_sum_pos_sublist_le (l1 l2 : list Rbar) :\n  (forall x, In x l2 -> Rbar_le 0 x) ->\n  sublist l1 l2 ->\n  Rbar_le (list_Rbar_sum l1) (list_Rbar_sum l2).\nProof.\n  intros pos subl.\n  induction subl.\n  - simpl.\n    lra.\n  - simpl.\n    apply Rbar_plus_le_compat.\n    + apply Rbar_le_refl.\n    + apply IHsubl.\n      intros.\n      apply pos.\n      simpl; now right.\n  - simpl.\n    replace (list_Rbar_sum l1) with (Rbar_plus 0 (list_Rbar_sum l1)) by now rewrite Rbar_plus_0_l.\n    apply Rbar_plus_le_compat.\n    + apply pos.\n      simpl.\n      now left.\n    + eapply IHsubl.\n      intros.\n      apply pos.\n      simpl; now right.\nQed.\n\n  Lemma bound_iso_f_pairs_sum_Rbar (f :nat -> nat -> Rbar) (n0 n : nat) :\n    (forall a b, Rbar_le 0 (f a b)) ->\n    exists (x : nat),\n      Rbar_le (sum_Rbar_n (fun x0 : nat => sum_Rbar_n (fun n1 : nat => f x0 n1) n0) n)\n              (sum_Rbar_n (fun n1 : nat => let '(a, b) := iso_b n1 in f a b) x).\n  Proof.\n    intros.\n    destruct (pair_encode_contains_square (max n0 n)).    \n    exists (S x).\n    rewrite sum_Rbar_n_pair_list_sum; trivial.\n\n    assert (subl:exists l, Permutation (list_prod (seq 0 n) (seq 0 n0)) l /\\\n                        sublist l (map iso_b (seq 0 (S x)))).\n    {\n      apply incl_NoDup_sublist_perm.\n      - apply NoDup_prod\n        ; apply seq_NoDup.\n      - intros [??] ?.\n        apply in_prod_iff in H1.\n        apply in_map_iff.\n        exists (iso_f (n1,n2)).\n        split.\n        + now rewrite iso_b_f.\n        + apply in_seq.\n          split; [lia |].\n          rewrite plus_0_l.\n          apply le_lt_n_Sm.\n          destruct H1.\n          apply in_seq in H1.\n          apply in_seq in H2.\n          apply H0; lia.\n    } \n\n    destruct subl as [?[??]].\n    apply (Permutation_map (fun '(a, b) => f a b)) in H1.\n    apply (sublist_map (fun '(a, b) => f a b)) in H2.\n\n    rewrite (list_Rbar_sum_nneg_perm\n               (map (fun '(a, b) => f a b) (list_prod (seq 0 n) (seq 0 n0)))\n               (map (fun '(a, b) => f a b) x0)); trivial.\n    - apply list_Rbar_sum_pos_sublist_le.\n      + intros.\n        apply in_map_iff in H3.\n        destruct H3 as [?[??]].\n        subst.\n        match_destr.\n      + now rewrite map_map in H2.\n    - apply Forall_map.\n      now apply Forall_forall; intros [??] ?.\n    - apply Forall_map.\n      now apply Forall_forall; intros [??] ?.\n  Qed.\n        \n  Lemma bound_pair_iso_b_sum_Rbar (f : nat -> nat -> Rbar) (x : nat) :\n\n    (forall a b, Rbar_le 0 (f a b)) ->\n    exists (n : nat),\n      Rbar_le (sum_Rbar_n (fun n1 : nat => let '(a, b) := iso_b n1 in f a b) x)\n              (sum_Rbar_n (fun x0 : nat => sum_Rbar_n (fun n1 : nat => f x0 n1) n) n).\n  Proof.\n    intros.\n    destruct (square_contains_pair_encode x) as [n ?].\n    exists (S n).\n    rewrite sum_Rbar_n_pair_list_sum; trivial.\n    unfold sum_Rbar_n.\n\n    assert (subl:exists l, Permutation (map iso_b (seq 0 x)) l /\\\n                        sublist l (list_prod (seq 0 (S n)) (seq 0 (S n)))).\n    {\n      apply incl_NoDup_sublist_perm.\n      - apply iso_b_nodup.\n        apply seq_NoDup.\n      - intros [??] ?.\n        apply in_map_iff in H1.\n        apply in_prod_iff.\n        destruct H1 as [?[??]].\n        apply in_seq in H2.\n        specialize (H0 x0).\n        cut_to H0; try lia.\n        rewrite H1 in H0.\n        split; apply in_seq; lia.\n    } \n\n    destruct subl as [?[??]].\n    apply (Permutation_map (fun '(a, b) => f a b)) in H1.\n    apply (sublist_map (fun '(a, b) => f a b)) in H2.\n\n    rewrite (list_Rbar_sum_nneg_perm\n               (map (fun n1 : nat => let '(a, b) := iso_b n1 in f a b) (seq 0 x))\n               (map (fun '(a, b) => f a b) x0)\n             ); trivial.\n    - apply list_Rbar_sum_pos_sublist_le; trivial.\n      intros.\n      apply in_map_iff in H3.\n      destruct H3 as [?[??]].\n      subst.\n      match_destr.\n    - apply Forall_map.\n      apply Forall_forall; intros; match_destr.\n    - apply Forall_map.\n      apply Forall_forall; intros; match_destr.\n    - rewrite <- H1.\n      now rewrite map_map.\n  Qed.\n\n  Lemma Elim_seq_incr_elem (f : nat -> Rbar) :\n    (forall n, Rbar_le (f n) (f (S n))) ->\n    forall n, Rbar_le (f n) (ELim_seq f).\n  Proof.\n    intros.\n    replace (f n) with (ELim_seq (fun _ => f n)) by now rewrite ELim_seq_const.\n    apply ELim_seq_le_loc.\n    exists n.\n    intros.\n    pose (h := (n0-n)%nat).\n    replace (n0) with (h + n)%nat by lia.\n    induction h.\n    - replace (0 + n)%nat with n by lia.\n      apply Rbar_le_refl.\n    - eapply Rbar_le_trans.\n      + apply IHh.\n      + replace (S h + n)%nat with (S (h+n))%nat by lia.\n        apply H.\n  Qed.\n\n  (* Fubini for nonnegative extended reals *)\n  Lemma ELim_seq_Elim_seq_pair (f:nat->nat->Rbar) :\n    (forall a b, Rbar_le 0 (f a b)) ->\n    ELim_seq\n      (fun i : nat =>\n         sum_Rbar_n (fun x0 : nat => ELim_seq (fun i0 : nat => sum_Rbar_n (fun n : nat => (f x0 n)) i0)) i) =\n      ELim_seq (fun i : nat => sum_Rbar_n (fun n : nat => let '(a, b) := iso_b (Isomorphism:=nat_pair_encoder) n in (f a b)) i).\n  Proof.\n    intros.\n    apply Rbar_le_antisym.\n    - apply Elim_seq_le_bound; intros.\n      replace (sum_Rbar_n\n                 (fun x0 : nat =>\n                    ELim_seq \n                      (fun i0 : nat => sum_Rbar_n (fun n0 : nat => f x0 n0) i0)) n)\n              with\n                (ELim_seq (fun i0 =>\n                             (sum_Rbar_n (fun x0 =>\n                                            (sum_Rbar_n (fun n0 => f x0 n0) i0)) n))).\n      + apply Elim_seq_le_bound; intros.\n        destruct (bound_iso_f_pairs_sum_Rbar f n0 n).\n        apply H.\n        eapply Rbar_le_trans.\n        * apply H0.\n        * apply Elim_seq_incr_elem; intros.\n          apply sum_Rbar_n_pos_Sn; intros.\n          now destruct (iso_b n2).\n      + symmetry.\n        induction n.\n        * unfold sum_Rbar_n.\n          simpl.\n          now rewrite ELim_seq_const.\n        * rewrite sum_Rbar_n_Sn.\n          rewrite IHn.\n          rewrite <- ELim_seq_plus.\n          -- apply ELim_seq_ext; intros.\n             rewrite sum_Rbar_n_Sn; trivial; intros.\n             now apply sum_Rbar_n_nneg_nneg.\n          -- apply ex_Elim_seq_incr; intros.\n             apply sum_Rbar_n_monotone; trivial; intros ?.\n             now apply sum_Rbar_n_pos_Sn.\n          -- apply ex_Elim_seq_incr; intros.\n             now apply sum_Rbar_n_pos_Sn.\n          -- apply ex_Rbar_plus_pos.\n             ++ apply ELim_seq_nneg; intros.\n                apply sum_Rbar_n_nneg_nneg; intros.\n                now apply sum_Rbar_n_nneg_nneg.\n             ++ apply ELim_seq_nneg; intros.\n                now apply sum_Rbar_n_nneg_nneg.\n          -- intros.\n             apply ELim_seq_nneg; intros.\n             now apply sum_Rbar_n_nneg_nneg; intros.\n    - apply Elim_seq_le_bound; intros.\n      destruct (bound_pair_iso_b_sum_Rbar f n).\n      apply H.\n      eapply Rbar_le_trans.\n      + apply H0.\n      + apply Rbar_le_trans with\n            (y := sum_Rbar_n (fun x1 : nat => ELim_seq (fun i0 : nat => sum_Rbar_n (fun n0 : nat => f x1 n0) i0)) x).\n        * apply sum_Rbar_n_monotone; trivial; intros ?.\n          apply Elim_seq_incr_elem; intros.\n          now apply sum_Rbar_n_pos_Sn.\n        * apply Elim_seq_incr_elem; intros.\n          apply sum_Rbar_n_pos_Sn; intros.\n          apply ELim_seq_nneg; intros.\n          now apply sum_Rbar_n_nneg_nneg.\n  Qed.\n\n(*\n  (* Fubini for nonnegative reals *)\n  Lemma Series_Series_seq_pair (f:nat->nat->R) :\n    (forall a b, 0 <= (f a b)) ->\n    Series (fun i : nat => Series (fun j : nat => f i j)) = \n    Series (fun i : nat => let '(a, b) := iso_b (Isomorphism:=nat_pair_encoder) i in (f a b)).\n  Proof.\n    intros.\n    apply Rle_antisym.\n*)\n(*\n    - apply Elim_seq_le_bound; intros.\n      replace (sum_Rbar_n\n                 (fun x0 : nat =>\n                    ELim_seq \n                      (fun i0 : nat => sum_Rbar_n (fun n0 : nat => f x0 n0) i0)) n)\n              with\n                (ELim_seq (fun i0 =>\n                             (sum_Rbar_n (fun x0 =>\n                                            (sum_Rbar_n (fun n0 => f x0 n0) i0)) n))).\n      + apply Elim_seq_le_bound; intros.\n        destruct (bound_iso_f_pairs_sum_Rbar f n0 n).\n        apply H.\n        eapply Rbar_le_trans.\n        * apply H0.\n        * apply Elim_seq_incr_elem; intros.\n          apply sum_Rbar_n_pos_Sn; intros.\n          now destruct (iso_b n2).\n      + symmetry.\n        induction n.\n        * unfold sum_Rbar_n.\n          simpl.\n          now rewrite ELim_seq_const.\n        * rewrite sum_Rbar_n_Sn.\n          rewrite IHn.\n          rewrite <- ELim_seq_plus.\n          -- apply ELim_seq_ext; intros.\n             rewrite sum_Rbar_n_Sn; trivial; intros.\n             now apply sum_Rbar_n_nneg_nneg.\n          -- apply ex_Elim_seq_incr; intros.\n             apply sum_Rbar_n_monotone; trivial; intros ?.\n             now apply sum_Rbar_n_pos_Sn.\n          -- apply ex_Elim_seq_incr; intros.\n             now apply sum_Rbar_n_pos_Sn.\n          -- apply ex_Rbar_plus_pos.\n             ++ apply ELim_seq_nneg; intros.\n                apply sum_Rbar_n_nneg_nneg; intros.\n                now apply sum_Rbar_n_nneg_nneg.\n             ++ apply ELim_seq_nneg; intros.\n                now apply sum_Rbar_n_nneg_nneg.\n          -- intros.\n             apply ELim_seq_nneg; intros.\n             now apply sum_Rbar_n_nneg_nneg; intros.\n    - apply Elim_seq_le_bound; intros.\n      destruct (bound_pair_iso_b_sum_Rbar f n).\n      apply H.\n      eapply Rbar_le_trans.\n      + apply H0.\n      + apply Rbar_le_trans with\n            (y := sum_Rbar_n (fun x1 : nat => ELim_seq (fun i0 : nat => sum_Rbar_n (fun n0 : nat => f x1 n0) i0)) x).\n        * apply sum_Rbar_n_monotone; trivial; intros ?.\n          apply Elim_seq_incr_elem; intros.\n          now apply sum_Rbar_n_pos_Sn.\n        * apply Elim_seq_incr_elem; intros.\n          apply sum_Rbar_n_pos_Sn; intros.\n          apply ELim_seq_nneg; intros.\n          now apply sum_Rbar_n_nneg_nneg.\n  Qed.\n*)\n\n Lemma list_Rbar_sum_nneg_nested_prod_swap {A B:Type} (X:list A) (Y:list B) (f:A->B->Rbar) :\n   (forall x y, In x X -> In y Y -> Rbar_le 0 (f x y)) ->\n   list_Rbar_sum (map (fun xy => f (fst xy) (snd xy)) (list_prod X Y)) =\n   list_Rbar_sum (map (fun yx => f (snd yx) (fst yx)) (list_prod Y X)).\n   Proof.\n     intros.\n     apply list_Rbar_sum_nneg_perm.\n     - apply Forall_forall.\n       intros.\n       rewrite in_map_iff in H0.\n       destruct H0 as [? [? ?]].\n       rewrite <- H0.\n       destruct x0.\n       apply H; now apply in_prod_iff in H1.\n     - apply Forall_forall.\n       intros.\n       rewrite in_map_iff in H0.       \n       destruct H0 as [? [? ?]].\n       rewrite <- H0.\n       destruct x0.\n       apply H; now apply in_prod_iff in H1.\n     - generalize (list_prod_swap X Y); intros.\n       replace (map (fun yx : B * A => f (snd yx) (fst yx)) (list_prod Y X)) with\n           (map (fun xy : A * B => f (fst xy) (snd xy))\n                (map swap (list_prod Y X))).\n       + apply Permutation_map.\n         apply H0.\n       + unfold swap.\n         rewrite map_map.\n         apply map_ext.\n         intros.\n         now simpl.\n   Qed.\n\n Lemma list_Rbar_sum_nneg_nested_swap {A B:Type} (X:list A) (Y:list B) (f:A->B->Rbar) :\n    (forall x y, In x X -> In y Y -> Rbar_le 0 (f x y)) ->\n    list_Rbar_sum (map (fun x => list_Rbar_sum (map (fun y => f x y) Y)) X) =\n      list_Rbar_sum (map (fun y => list_Rbar_sum (map (fun x => f x y) X)) Y).\n Proof.\n   intros.\n   rewrite list_Rbar_sum_nneg_nested_prod.\n   - rewrite list_Rbar_sum_nneg_nested_prod.\n     + now apply list_Rbar_sum_nneg_nested_prod_swap.\n     + intros.\n       now apply H.\n   - intros.\n     now apply H.\n Qed.\n\n\n Lemma list_Rbar_sum_const c l : list_Rbar_sum (map (fun _ : nat => c) l) = Rbar_mult c (INR (length l)).\n Proof.\n   induction l.\n   - now rewrite Rbar_mult_0_r.\n   - simpl length.\n     rewrite S_INR.\n     simpl.\n     rewrite IHl.\n     replace (Finite (INR (length l) + 1)) with (Rbar_plus (INR (length l)) 1) by reflexivity.\n     rewrite Rbar_mult_plus_distr_l; simpl.\n     + rewrite Rbar_mult_1_r.\n       now rewrite Rbar_plus_comm.\n     + apply pos_INR.\n     + lra.\n Qed.\n\n Lemma sum_Rbar_n0 n : sum_Rbar_n (fun _ : nat => 0) n = 0.\n Proof.\n   unfold sum_Rbar_n.\n   rewrite list_Rbar_sum_const.\n   now rewrite Rbar_mult_0_l.\n Qed.   \n   \n Lemma Elim_seq_sum0 : ELim_seq (sum_Rbar_n (fun _ : nat => 0)) = 0.\n Proof.\n   rewrite (ELim_seq_ext _ (fun _ => 0)).\n   + apply ELim_seq_const.\n   + intros.\n     apply sum_Rbar_n0.\n Qed.\n\n Lemma list_Rbar_ELim_seq_nneg_nested_swap {A:Type} (X:list A) (f:A->nat->Rbar) :\n   (forall a b, In a X -> Rbar_le 0 (f a b)) ->\n   list_Rbar_sum (map (fun x => (ELim_seq (sum_Rbar_n (fun j : nat => (f x j))))) X) =\n     ELim_seq\n        (sum_Rbar_n (fun i : nat => list_Rbar_sum (map (fun x => f x i) X))).\n Proof.\n   symmetry.\n   induction X.\n   - simpl.\n     now rewrite Elim_seq_sum0.\n   - simpl.\n     rewrite <- IHX by firstorder.\n     rewrite <- ELim_seq_plus.\n     + apply ELim_seq_ext; intros.\n       rewrite sum_Rbar_n_nneg_plus; trivial.\n       * firstorder.\n       * intros.\n         apply list_Rbar_sum_nneg_nneg; intros.\n         apply in_map_iff in H1.\n         destruct H1 as [?[??]]; subst.\n         firstorder.\n     + apply ex_Elim_seq_incr; intros.\n       apply sum_Rbar_n_pos_incr; firstorder.\n     + apply ex_Elim_seq_incr; intros.\n       apply sum_Rbar_n_pos_incr; intros.\n       apply list_Rbar_sum_nneg_nneg; intros.\n         apply in_map_iff in H0.\n         destruct H0 as [?[??]]; subst.\n         firstorder.\n     + apply ex_Rbar_plus_pos.\n       * apply ELim_seq_nneg; intros.\n         apply sum_Rbar_n_nneg_nneg; intros.\n         firstorder.\n       * apply ELim_seq_nneg; intros.\n         apply sum_Rbar_n_nneg_nneg; intros.\n         apply list_Rbar_sum_nneg_nneg; intros.\n         apply in_map_iff in H1.\n         destruct H1 as [?[??]]; subst.\n         firstorder.\n Qed.\n\n  Definition swap_num_as_pair (n:nat) :=\n    let '(a, b) := iso_b (Isomorphism:=nat_pair_encoder) n in\n    iso_f (b,a).\n\n  Lemma sum_Rbar_n_iso_swap (f:nat->nat->Rbar) (n : nat) :\n    (forall a b, Rbar_le 0 (f a b)) ->\n    exists (m : nat),\n      Rbar_le\n        (sum_Rbar_n (fun n0 : nat => let '(a, b) := iso_b n0 in f a b) n)\n        (sum_Rbar_n (fun n0 : nat => let '(a, b) := iso_b n0 in f b a) m).\n  Proof.\n    intros.\n    exists (S (list_max (map swap_num_as_pair (seq 0 n)))).\n    unfold sum_Rbar_n.\n    assert (subl:exists l,\n               Permutation (map iso_b (seq 0 n)) l /\\\n               sublist l \n                       (map swap (map iso_b\n                                      (seq 0 (S (list_max\n                                                (map swap_num_as_pair (seq 0 n)))))))).\n    {\n      apply incl_NoDup_sublist_perm.\n      - apply iso_b_nodup.\n        apply seq_NoDup.\n      - intros [??] ?.\n        apply in_map_iff in H0.\n        destruct H0 as [?[??]].\n        rewrite in_map_iff.\n        exists (n1,n0).\n        split.\n        + now unfold swap; simpl.\n        + rewrite in_map_iff.\n          exists (iso_f (n1, n0)).\n          split.\n          * now rewrite iso_b_f.\n          * rewrite in_seq.\n            split.\n            -- lia.\n            -- unfold swap_num_as_pair.\n               assert (iso_f (n1, n0) <=\n                       (list_max\n                          (map (fun n2 : nat => let '(a, b) := iso_b n2 in iso_f (b, a)) (seq 0 n))))%nat.\n               {\n                 generalize (list_max_upper\n                               (map (fun n2 : nat => let '(a, b) := iso_b n2 in iso_f (b, a)) (seq 0 n)))%nat; intros.\n                 rewrite Forall_forall in H2.\n                 apply H2.\n                 rewrite in_map_iff.\n                 exists x.\n                 split; trivial.\n                 destruct (iso_b x).\n                 now inversion H0.\n               }\n               lia.\n    }\n    destruct subl as [? [? ?]].\n    apply (Permutation_map (fun '(a, b) => f a b)) in H0.\n    apply (sublist_map (fun '(a, b) => f a b)) in H1.\n    rewrite (list_Rbar_sum_nneg_perm\n               (map (fun n1 : nat => let '(a, b) := iso_b n1 in f a b) (seq 0 n))\n               (map (fun '(a, b) => f a b) x)\n             ); trivial.\n    - apply list_Rbar_sum_pos_sublist_le; trivial.\n      + intros.\n        rewrite in_map_iff in H2.\n        destruct H2 as [? [? ?]].\n        rewrite <- H2.\n        now destruct (iso_b x1).\n      + unfold swap in H1.\n        rewrite map_map, map_map in H1.\n        rewrite map_ext with\n            (g :=  (fun x : nat => f (snd (iso_b x)) (fst (iso_b x)))).\n        * apply H1.\n        * intros.\n          destruct (iso_b a).\n          now simpl.\n    - rewrite Forall_map, Forall_forall.\n      intros.\n      now destruct (iso_b x0).\n    - rewrite Forall_map, Forall_forall.\n      intros.\n      now destruct x0.\n    - now rewrite map_map in H0.\n    Qed.\n\n  Lemma ELim_seq_sum_nneg_nested_swap (f:nat->nat->Rbar) :\n    (forall a b, Rbar_le 0 (f a b)) ->\n    ELim_seq\n      (sum_Rbar_n (fun i : nat => ELim_seq (sum_Rbar_n (fun j : nat => (f i j))))) =\n      ELim_seq\n        (sum_Rbar_n (fun i : nat => ELim_seq (sum_Rbar_n (fun j : nat => (f j i))))).\n  Proof.\n    intros.\n    rewrite ELim_seq_Elim_seq_pair.\n    rewrite ELim_seq_Elim_seq_pair.\n    - apply Rbar_le_antisym.\n      + apply Elim_seq_le_bound; intros.\n        destruct (sum_Rbar_n_iso_swap f n H).\n        eapply Rbar_le_trans.\n        * apply H0.\n        * apply Elim_seq_incr_elem; intros.\n          apply sum_Rbar_n_pos_Sn; intros.\n          now destruct (iso_b n1).\n      + apply Elim_seq_le_bound; intros.\n        destruct (sum_Rbar_n_iso_swap (fun a b => f b a) n).\n        * now intros.\n        * eapply Rbar_le_trans.\n          -- apply H0.\n          -- apply Elim_seq_incr_elem; intros.\n             apply sum_Rbar_n_pos_Sn; intros.\n             now destruct (iso_b n1).\n    - now intros.\n    - now intros.\n  Qed.\n  \n  Lemma is_finite_witness (x : Rbar) :\n    is_finite x ->\n    exists (r:R), x = Finite r.\n  Proof.\n    intros.\n    unfold is_finite in H.\n    now exists (real x).\n  Qed.\n\n  Lemma is_finite_Elim_seq_nneg_nested (f:nat->nat->Rbar) :\n    (forall a b, Rbar_le 0(f a b)) ->\n    is_finite (ELim_seq\n      (sum_Rbar_n (fun i : nat => ELim_seq (sum_Rbar_n (fun j : nat => (f i j)))))) ->\n    forall i, is_finite (ELim_seq (sum_Rbar_n (fun j : nat => (f i j)))).\n  Proof.\n    intros.\n    apply is_finite_witness in H0.\n    destruct H0.\n    generalize (Elim_seq_sum_pos_fin_n_fin (fun i : nat => ELim_seq (sum_Rbar_n (fun j : nat => (f i j)))) x); intros.\n    apply H1; trivial.\n    intros.\n    replace (Finite 0) with (ELim_seq (fun _ => 0)).\n    + apply ELim_seq_le; intros.\n      apply sum_Rbar_n_nneg_nneg; intros.\n      apply H.\n    + apply ELim_seq_const.\n  Qed.\n    \n  Lemma ELim_seq_Lim_seq_Rbar (f : nat -> Rbar) :\n    (forall n, is_finite (f n)) ->\n    ELim_seq f = Lim_seq f.\n  Proof.\n    intros.\n    generalize (Elim_seq_fin f); intros.\n    rewrite ELim_seq_ext with (v := fun n => Finite (real (f n))); trivial.\n    intros.\n    now rewrite H.\n  Qed.\n\n  Lemma sum_Rbar_n_finite_sum_n f n:\n    sum_Rbar_n (fun x => Finite (f x)) (S n) = Finite (sum_n f n).\n  Proof.\n    rewrite sum_n_fold_right_seq.\n    unfold sum_Rbar_n, list_Rbar_sum.\n    generalize (0).\n    induction n; trivial; intros.\n    rewrite seq_Sn.\n    repeat rewrite map_app.\n    repeat rewrite fold_right_app.\n    now rewrite <- IHn.\n  Qed.\n\n  Lemma Lim_seq_sum_Elim f :\n    Lim_seq (sum_n f) = ELim_seq (sum_Rbar_n (fun x => Finite (f x))).\n  Proof.\n    rewrite <- ELim_seq_incr_1.\n    rewrite <- Elim_seq_fin.\n    apply ELim_seq_ext; intros.\n    now rewrite sum_Rbar_n_finite_sum_n.\n  Qed.    \n\n  Lemma Series_nneg_nested_swap (f:nat->nat->R) :\n    (forall a b, 0 <= (f a b)) ->\n    is_finite (ELim_seq \n      (sum_Rbar_n (fun i : nat => ELim_seq (sum_Rbar_n (fun j : nat => (f i j)))))) ->\n    Series (fun i : nat => Series (fun j : nat => (f i j))) =\n    Series (fun i : nat => Series (fun j : nat => (f j i))).\n  Proof.\n    intros.\n    unfold Series.\n    generalize (is_finite_Elim_seq_nneg_nested f); intros.\n    cut_to H1; trivial.\n    f_equal.\n    generalize (ELim_seq_sum_nneg_nested_swap f); intros.\n    cut_to H2; try now simpl.\n    generalize (is_finite_Elim_seq_nneg_nested (fun i j => f j i)); intros.          \n    cut_to H3; trivial; try (intros; now simpl).\n    - do 2 rewrite Lim_seq_sum_Elim.\n      rewrite ELim_seq_ext with\n          (v :=  (sum_Rbar_n\n                    (fun i : nat =>\n                       ELim_seq (sum_Rbar_n (fun j : nat => Finite (f i j)))))).\n      symmetry.\n      rewrite ELim_seq_ext with\n          (v := (sum_Rbar_n\n                   (fun i : nat =>\n                      ELim_seq (sum_Rbar_n (fun j : nat => Finite (f j i)))))).\n      symmetry; trivial.\n      + intros.\n        apply sum_Rbar_n_proper; trivial.\n        unfold pointwise_relation; simpl; intros.\n        rewrite Lim_seq_sum_Elim.\n        now rewrite H3.\n      + intros.\n        apply sum_Rbar_n_proper; trivial.\n        unfold pointwise_relation; simpl; intros.\n        rewrite Lim_seq_sum_Elim.\n        now rewrite H1.        \n   - now rewrite <- H2.\n  Qed.\n\n  Lemma lim_seq_sum_singleton_is_one f :\n    (forall n1 n2, n1 <> n2 -> f n1 = 0 \\/ f n2 = 0) ->\n    exists n, Lim_seq (sum_n f) = f n.\n  Proof.\n    intros.\n    destruct (classic (exists m, f m <> 0)%type) as [[n ?]|].\n    - rewrite <- (Lim_seq_incr_n _ n).\n      assert (eqq:forall x,\n                 sum_n f (x + n) =\n                   f n).\n      {\n        intros.\n        induction x; simpl.\n        - destruct n.\n          + now rewrite sum_O.\n          + rewrite sum_Sn.\n            erewrite sum_n_ext_loc; try rewrite sum_n_zero.\n            * unfold plus; simpl; lra.\n            * intros ??; simpl.\n              destruct (H (S n) n0); try lra.\n              lia.\n        - rewrite sum_Sn, IHx.\n          unfold plus; simpl.\n          destruct (H n (S (x + n))); try lra.\n          lia.\n      }\n      rewrite (Lim_seq_ext _ _ eqq).\n      rewrite Lim_seq_const.\n      eauto.\n    - assert (eqq:forall x,\n                 sum_n f x = 0).\n      {\n        intros.\n        erewrite sum_n_ext; try eapply sum_n_zero.\n        intros ?; simpl.\n        destruct (Req_EM_T (f n) 0); trivial.\n        elim H0; eauto.\n      }\n      rewrite (Lim_seq_ext _ _ eqq).\n      rewrite Lim_seq_const.\n      exists (0%nat).\n      f_equal; symmetry.\n      destruct (Req_EM_T (f 0%nat) 0); trivial.\n      elim H0; eauto.\n  Qed.\n\n  Lemma lim_seq_sum_singleton_finite f :\n    (forall n1 n2, n1 <> n2 -> f n1 = 0 \\/ f n2 = 0) ->\n    is_finite (Lim_seq (sum_n f)).\n  Proof.\n    intros.\n    destruct (lim_seq_sum_singleton_is_one f H).\n    now rewrite H0.\n  Qed.\n\nEnd lim_sum.\n\nSection Rmax_list.\n\n  Lemma Rmax_list_lim_Sup_seq (a : nat -> R) (N : nat) :\n    Lim_seq (fun M => Rmax_list (map a (seq N M))) = Sup_seq (fun n0 : nat => a (n0 + N)%nat).\n  Proof.\n    rewrite <- Elim_seq_fin.\n    rewrite <- ELim_seq_incr_1.\n    apply is_Elim_seq_unique.\n    apply is_Elim_seq_fin.\n    apply lim_seq_is_lub_incr.\n    - intros.\n      rewrite (seq_Sn _ (S n)).\n      rewrite Rmax_list_app.\n      + apply Rmax_l.\n      + simpl; congruence.\n    - split.\n      + intros n [??]; subst.\n        generalize (Rmax_list_In (map a (seq N (S x)))); intros HH.\n        cut_to HH; [| simpl; congruence].\n        apply in_map_iff in HH.\n        destruct HH as [?[??]].\n        rewrite <- H.\n        apply in_seq in H0.\n        apply (Sup_seq_minor_le _ _ (x0-N)).\n        replace (x0 - N + N)%nat with x0 by lia.\n        apply Rbar_le_refl.\n      + intros ??.\n        red in H.\n        unfold Sup_seq, proj1_sig.\n        match_destr.\n        destruct x; simpl in i.\n        * apply Rbar_le_forall_Rbar_le; intros eps.\n          destruct (i eps) as [?[??]].\n          specialize (H (Rmax_list (map a (seq N (S x))))).\n          cut_to H; [| eauto].\n          generalize (@Rmax_spec (map a (seq N (S x))) (a (x+N)%nat)); intros HH.\n          cut_to HH.\n          -- destruct b; simpl in *; lra.\n          -- apply in_map.\n             apply in_seq.\n             lia.\n        * destruct b; simpl; trivial.\n          -- destruct (i r).\n             specialize (H (Rmax_list (map a (seq N (S x))))).\n             cut_to H; [| eauto].\n             generalize (@Rmax_spec (map a (seq N (S x))) (a (x+N)%nat)); intros HH.\n             cut_to HH.\n             ++ simpl in *; lra.\n             ++ apply in_map.\n                apply in_seq.\n                lia.\n          -- apply (H (a N)).\n             exists 0%nat.\n             reflexivity.\n        * now simpl.\n  Qed.\n\n  Lemma Rmax_list_Sup_seq (a : nat -> R) (N M : nat) :\n    Rbar_le (Rmax_list (map a (seq N (S M)))) (Sup_seq (fun n0 : nat => a (n0 + N)%nat)).\n  Proof.\n    rewrite <- Rmax_list_lim_Sup_seq.\n    rewrite <- Elim_seq_fin.\n    rewrite <- ELim_seq_incr_1.\n    apply (Elim_seq_incr_elem (fun x : nat => Rmax_list (map a (seq N (S x))))); intros.\n    rewrite (seq_Sn _ (S n)).\n    rewrite Rmax_list_app.\n    - simpl.\n      apply Rmax_l.\n    - simpl; congruence.\n  Qed.\n\nEnd Rmax_list.\n\nSection zeroprop.\n\n  Definition zerotails_prop a ϵ n : Prop :=\n  forall N, (n <= N)%nat -> Rabs (Series (fun k => a (S (N+k)%nat))) < ϵ.\n\nLemma zerotails_witness_pack (a : nat -> R) :\n  ex_series a -> forall (ϵ:posreal), { n : nat | zerotails_prop a ϵ n  /\\ forall n', zerotails_prop a ϵ n' -> (n <= n')%nat }.\nProof.\n  intros.\n  case_eq (classic_min_of (zerotails_prop a ϵ)).\n  - intros.\n    exists n.\n    split.\n    + now apply classic_min_of_some in H0.\n    + intros.\n      apply NPeano.Nat.nlt_ge; intros nlt.\n      eapply classic_min_of_some_first in H0; try apply nlt.\n      tauto.\n  - intros.\n    generalize (classic_min_of_none _ H0); intros.\n    apply zerotails in H.\n    apply is_lim_seq_spec in H.\n    simpl in H.\n    elimtype False.\n    destruct (H ϵ) as [N ?].\n    elim (H1 N).\n    red; intros.\n    specialize (H2 _ H3).\n    now rewrite Rminus_0_r in H2.\nQed.\n\nDefinition zerotails_witness (a : nat -> R)\n           (pf:ex_series a) (ϵ:posreal) : nat\n  := proj1_sig (zerotails_witness_pack a pf ϵ).\n\nLemma zerotails_witness_prop (a : nat -> R) (pf:ex_series a) (ϵ:posreal) :\n  forall N, ((zerotails_witness a pf ϵ) <= N)%nat -> Rabs (Series (fun k => a (S N + k)%nat)) < ϵ.\nProof.\n  unfold zerotails_witness, proj1_sig.\n  match_destr.\n  tauto.\nQed.\n\nLemma zerotails_prop_nondecr a ϵ1 ϵ2 n :\n    ϵ1 <= ϵ2 ->\n    zerotails_prop a ϵ1 n -> zerotails_prop a ϵ2 n.\nProof.\n  unfold zerotails_prop; intros.\n  eapply Rlt_le_trans; try apply H.\n  now apply H0.\nQed.  \n\nLemma zerotails_witness_min (a : nat -> R) (pf:ex_series a) (ϵ:posreal) :\n  forall n', (forall N, (n' <= N)%nat -> Rabs (Series (fun k => a (S N + k)%nat)) < ϵ) ->\n        ((zerotails_witness a pf ϵ) <= n')%nat.\nProof.\n  unfold zerotails_witness, proj1_sig.\n  match_destr.\n  tauto.\nQed.\n\nLemma zerotails_witness_nondecr (a : nat -> R) (pf:ex_series a) (ϵ1 ϵ2:posreal) :\n  ϵ2 <= ϵ1 ->\n  (zerotails_witness a pf ϵ1 <= zerotails_witness a pf ϵ2)%nat.\nProof.\n  intros.\n  unfold zerotails_witness, proj1_sig; repeat match_destr.\n  apply a0.\n  eapply zerotails_prop_nondecr; try apply H.\n  tauto.\nQed.\n\nDefinition zerotails_eps2k_fun' (a : nat -> R) (pf:ex_series a) (k:nat) : nat\n  := zerotails_witness a pf (inv_2_pow_posreal k).\n\nDefinition zerotails_eps2k_fun (a : nat -> R) (pf:ex_series a) (k:nat) : nat\n  := zerotails_eps2k_fun' a pf k + k.\n\nLemma zerotails_eps2k_fun_shifted_bound (a : nat -> R) (pf:ex_series a) (k:nat)\n  : Rabs (Series (fun x => a (S (x+ (zerotails_eps2k_fun a pf k)%nat)))) < (/ (2 ^ k)).\nProof.\n  unfold zerotails_eps2k_fun.\n  unfold zerotails_eps2k_fun'.\n  unfold zerotails_witness, proj1_sig.\n  match_destr.\n  destruct a0 as [r _].\n  simpl in r.\n  specialize (r (x+k)%nat).\n  eapply Rle_lt_trans; try apply r; try lia.\n  right; f_equal.\n  apply Series_ext; intros.\n  f_equal; lia.\nQed.\n\nLemma zerotails_eps2k_double_sum_ex (a : nat -> R) (pf:ex_series a) :\n  ex_series (fun k => Series (fun x => a (S (x+ (zerotails_eps2k_fun a pf k)%nat)))).\nProof.\n  eapply (@ex_series_le R_AbsRing R_CompleteNormedModule _ (fun k =>  (/ (2 ^ k)))).\n  - intros.\n    left.\n    apply zerotails_eps2k_fun_shifted_bound.\n  - generalize (ex_series_geom (1/2)); intros HH.\n    cut_to HH.\n    + revert HH.\n      apply ex_series_ext; intros.\n      rewrite Rinv_pow; try lra.\n      f_equal.\n      lra.\n    + rewrite Rabs_right; lra.\nQed.\n\nLemma zerotails_eps2k_fun'_nondecr a pf n :\n  ((zerotails_eps2k_fun' a pf n) <= (zerotails_eps2k_fun'  a pf (S n)))%nat.\nProof.\n  unfold zerotails_eps2k_fun'.\n  apply zerotails_witness_nondecr.\n  simpl.\n  assert (0 < 2) by lra.\n  assert (0 < 2 ^ n).\n  {\n    apply pow_lt; lra.\n  }\n  rewrite <- (Rmult_1_l (/ 2 ^ n)).\n  rewrite Rinv_mult_distr.\n  - apply Rmult_le_compat_r; try lra.\n    left.\n    apply Rinv_0_lt_compat.\n    apply pow_lt; lra.\n  - lra.\n  - apply pow_nzero; lra.\nQed.\n\nLemma zerotails_incr_mult_strict_incr a pf n :\n  ((zerotails_eps2k_fun a pf n) < (zerotails_eps2k_fun a pf (S n)))%nat.\nProof.\n  unfold zerotails_eps2k_fun.\n  generalize (zerotails_eps2k_fun'_nondecr a pf n); lia.\nQed.\n\nLemma zerotails_incr_mult_strict_incr_lt a pf m n :\n  (m < n)%nat ->\n  ((zerotails_eps2k_fun a pf m) < (zerotails_eps2k_fun a pf n))%nat.\nProof.\n  intros.\n  induction H.\n  - apply zerotails_incr_mult_strict_incr.\n  - rewrite IHle.\n    apply  zerotails_incr_mult_strict_incr.\nQed.\n\nDefinition zerotails_incr_mult (a : nat -> R) (pf:ex_series a) n : R\n  := Series (fun n0 : nat => if le_dec (S (zerotails_eps2k_fun a pf n0)) n then 1 else 0).\n\nLemma zerotails_incr_mult_ex (a : nat -> R) (pf:ex_series a) n :\n  ex_series (fun n0 : nat => if le_dec (S (zerotails_eps2k_fun a pf n0)) n then 1 else 0).\nProof.\n  apply (ex_series_incr_n _ n).\n  apply (ex_series_ext (fun _ => 0)).\n  - intros.\n    match_destr.\n    unfold zerotails_eps2k_fun in *; lia.\n  - exists 0.\n    apply is_series_Reals.\n    apply infinite_sum_infinite_sum'.\n    apply infinite_sum'0.\nQed.\n\nLemma zerotails_incr_mult_trunc  (a : nat -> R) (pf:ex_series a) n :\n  zerotails_incr_mult a pf n = sum_n (fun n0 : nat => if le_dec (S (zerotails_eps2k_fun a pf n0)) n then 1 else 0) n.\nProof.\n  unfold zerotails_incr_mult.\n  apply is_series_unique.\n  apply -> series_is_lim_seq.\n  apply is_lim_seq_spec.\n  simpl; intros.\n  exists n; intros.\n  generalize (sum_n_m_sum_n (fun n1 : nat => if le_dec (S (zerotails_eps2k_fun a pf n1)) n then 1 else 0) n n0).\n  match goal with\n    [|- context [minus ?x ?y]] => replace (minus x y) with (x - y) by reflexivity\n  end; simpl.\n  intros HH;  rewrite <- HH; trivial.\n  erewrite (sum_n_m_ext_loc _ (fun _ => zero)).\n  - rewrite sum_n_m_const_zero.\n    unfold zero; simpl.\n    rewrite Rabs_R0.\n    now destruct eps.\n  - intros.\n    match_destr.\n    unfold zerotails_eps2k_fun in l; lia.\nQed.\n  \nLemma zerotails_eps2k_fun_unbounded a pf :\n  forall m, exists k, (m < (zerotails_eps2k_fun a pf k))%nat.\nProof.\n  unfold zerotails_eps2k_fun; intros.\n  exists (S m).\n  lia.\nQed.\n\nLemma zerotails_incr_mult_incr a pf n :\n  exists m, (n < m)%nat /\\\n         zerotails_incr_mult a pf n + 1 <= zerotails_incr_mult a pf m.\nProof.\n  destruct (zerotails_eps2k_fun_unbounded a pf (zerotails_eps2k_fun a pf (S n))) as [m HH].\n  exists ((n + S (zerotails_eps2k_fun a pf m))%nat).\n  assert (nlt:(n < n + zerotails_eps2k_fun a pf m)%nat).\n  {\n    lia.\n  } \n  split; try lia.\n  repeat rewrite zerotails_incr_mult_trunc.\n  repeat rewrite sum_n_Reals.\n  rewrite (sum_f_R0_split _ (n + S (zerotails_eps2k_fun a pf m)) n).\n  - apply Rplus_le_compat.\n    + apply sum_growing; intros.\n      repeat match_destr; try lra; try lia.\n    + replace ((n + S (zerotails_eps2k_fun a pf m) - S n))%nat with (zerotails_eps2k_fun a pf m) by lia.\n      rewrite sum_f_R0_sum_f_R0'.\n      replace (S (zerotails_eps2k_fun a pf m)) with (1+ (zerotails_eps2k_fun a pf m))%nat by lia.\n      rewrite sum_f_R0'_plus_n.\n      simpl.\n      rewrite Rplus_0_l.\n      assert (0 <=  sum_f_R0'\n    (fun x : nat =>\n     if\n      le_dec (S (zerotails_eps2k_fun a pf (S (x + S n))))\n        (n + S (zerotails_eps2k_fun a pf m))\n     then 1\n     else 0) (zerotails_eps2k_fun a pf m)\n             ).\n      {\n        apply sum_f_R0'_le; intros.\n        match_destr; lra.\n      }\n      match_destr; try lra.\n      lia.\n  - lia.\nQed.\n\n\nLemma zerotails_incr_mult_unbounded_nat a pf M :\n  exists m, (INR M <= zerotails_incr_mult a pf m).\nProof.\n  induction M.\n  - exists 0%nat.\n    simpl.\n    unfold zerotails_incr_mult.\n    apply Series_nonneg.\n    + intros.\n      match_destr; lra.\n  - destruct IHM.\n    destruct (zerotails_incr_mult_incr a pf x) as [? [??]].\n    exists x0.\n    rewrite S_INR.\n    lra.\nQed.\n\nLemma zerotails_incr_mult_incr_incr a pf x n :\n  (x <= n)%nat ->\n  ((zerotails_incr_mult a pf x) <= (zerotails_incr_mult a pf n)).\nProof.\n  intros.\n  unfold zerotails_incr_mult.\n  apply Series_le.\n  - intros.\n    repeat match_destr; try lra.\n    lia.\n  - apply zerotails_incr_mult_ex.\nQed.\n\nLemma zerotails_incr_mult_unbounded (a : nat -> R) (pf:ex_series a) :\n  is_lim_seq (zerotails_incr_mult a pf) p_infty.\nProof.\n  apply is_lim_seq_spec; simpl.\n  intros.\n  red.\n  destruct (zerotails_incr_mult_unbounded_nat a pf (Z.to_nat (up (Rmax M 0)))).\n  exists x; intros.\n\n  assert (le1:((zerotails_incr_mult a pf x) <= (zerotails_incr_mult a pf n))).\n  {\n    now apply zerotails_incr_mult_incr_incr.\n  } \n\n  eapply Rlt_le_trans; try eapply le1.\n  eapply Rlt_le_trans; try eapply H.\n  destruct (archimed (Rmax M 0)).\n  rewrite INR_up_pos.\n  - apply Rgt_lt in H1.\n    eapply Rle_lt_trans; try eapply H1.\n    apply Rmax_l.\n  - apply Rle_ge.\n    apply Rmax_r.\nQed.\n\nLemma zerotails_eps2k_double_sum_finite  (a : nat -> R) (pf:ex_series a) {anneg: forall x, 0 <= a x}:\n  is_finite\n    (ELim_seq\n       (sum_Rbar_n\n          (fun i : nat =>\n             ELim_seq\n               (sum_Rbar_n\n                  (fun x : nat => a (S (x+ (zerotails_eps2k_fun a pf i)%nat))))))).\n  Proof.\n    generalize (zerotails_eps2k_fun_shifted_bound a pf); intros.\n    generalize (zerotails_eps2k_double_sum_ex a pf); intros.\n    rewrite <- ex_finite_lim_series in H0.\n    rewrite ex_finite_lim_seq_correct in H0.\n    destruct H0.\n    rewrite <- ELim_seq_incr_1.\n    rewrite ELim_seq_ext with\n        (v := fun n => Finite (sum_n  (fun k : nat => Series (fun x : nat => a (S (x + zerotails_eps2k_fun a pf k)))) n)).\n    now rewrite Elim_seq_fin.\n    intros.\n    rewrite <- sum_Rbar_n_finite_sum_n.\n    apply sum_Rbar_n_proper; trivial.\n    unfold pointwise_relation; intros.\n    rewrite <- ex_series_Lim_seq.\n    - rewrite <- ELim_seq_incr_1.\n      rewrite ELim_seq_ext with\n          (v := fun n => Finite (sum_n (fun x : nat => a (S (x + zerotails_eps2k_fun a pf a0))) n)).\n      + now rewrite Elim_seq_fin.\n      + intros.\n        now rewrite sum_Rbar_n_finite_sum_n.\n    - generalize (ex_series_incr_n a); intros.\n      apply (ex_series_ext \n          (fun x : nat => a (S (zerotails_eps2k_fun a pf a0) + x)%nat)).\n      + intros.\n        f_equal.\n        lia.\n      + now apply ex_series_incr_n.\n  Qed.\n\nLemma zerotails_eps2k_double_sum_eq (a : nat -> R) (pf:ex_series a) {anneg: forall x, 0 <= a x}:\n  Series (fun k => Series (fun x => a (S (x+ (zerotails_eps2k_fun a pf k)%nat)))) =\n    Series (fun n => zerotails_incr_mult a pf n * (a n)).\nProof.\n  transitivity (\n      Series (fun k : nat => Series (fun n : nat =>\n                                  a n *\n                                    if le_dec (S (zerotails_eps2k_fun a pf k)) n \n                                    then 1 else 0))).\n  {\n    apply Series_ext; intros.\n    rewrite (Series_incr_n_aux\n               (fun n0 : nat =>\n                  a n0 * (if le_dec (S (zerotails_eps2k_fun a pf n))%nat n0 then 1 else 0))\n               (S (zerotails_eps2k_fun a pf n))).\n    - apply Series_ext; intros.\n      match_destr.\n      + field_simplify.\n        f_equal.\n        lia.\n      + elim n1.\n        lia.\n    - intros.\n      match_destr; try lra.\n      unfold zerotails_eps2k_fun in *.\n      lia.\n  } \n  transitivity (Series\n    (fun n : nat =>\n     Series\n       (fun k : nat =>\n        a n * (if le_dec (S (zerotails_eps2k_fun a pf k)) n then 1 else 0)))).\n  {\n    apply Series_nneg_nested_swap.\n    - intros.\n      apply Rmult_le_pos; trivial.\n      match_destr; lra.\n    - rewrite ELim_seq_ext with\n          (v :=  (sum_Rbar_n\n                    (fun i : nat =>\n                       ELim_seq\n                         (sum_Rbar_n\n                            (fun x : nat => a (S (x+ (zerotails_eps2k_fun a pf i)%nat))))))).\n      + apply zerotails_eps2k_double_sum_finite; trivial.\n      + intros.\n        apply sum_Rbar_n_proper; trivial.\n        unfold pointwise_relation; simpl; intros.\n        rewrite <- ELim_seq_incr_1.\n        rewrite ELim_seq_ext with\n            (v := (fun n => Finite (sum_n (fun j : nat => a j * (if le_dec (S (zerotails_eps2k_fun a pf a0)) j then 1 else 0)) n))).\n        rewrite Elim_seq_fin.\n        rewrite <- ELim_seq_incr_1.        \n        rewrite ELim_seq_ext with\n            (v := (fun n => Finite (sum_n (fun x : nat => a (S (x + zerotails_eps2k_fun a pf a0))) n))).\n        rewrite Elim_seq_fin.\n        * rewrite ex_series_Lim_seq.\n          rewrite ex_series_Lim_seq.\n          -- rewrite (Series_incr_n_aux\n                        (fun n0 : nat =>\n                           a n0 * (if le_dec (S (zerotails_eps2k_fun a pf a0))%nat n0 then 1 else 0))\n                        (S (zerotails_eps2k_fun a pf a0))).\n             ++ apply Rbar_finite_eq.\n                apply Series_ext; intros.\n                match_destr.\n                ** field_simplify.\n                   f_equal.\n                   lia.\n                ** elim n1.\n                   lia.\n             ++ intros.\n                match_destr; try lra.\n                unfold zerotails_eps2k_fun in *.\n                lia.\n          -- apply (ex_series_ext \n                      (fun x => a ((S (zerotails_eps2k_fun a pf a0)) + x)%nat)).\n             ++ intros; f_equal; lia.\n             ++ now apply ex_series_incr_n.\n          -- apply (ex_series_le (fun j : nat => a j * (if le_dec (S (zerotails_eps2k_fun a pf a0)) j then 1 else 0)) a); trivial.\n             intros.\n             unfold norm; simpl.\n             unfold abs; simpl.\n             rewrite Rabs_right.\n             ++ replace (a n0) with ((a n0) * 1) at 2 by lra.\n                apply Rmult_le_compat_l; trivial.\n                match_destr; lra.\n             ++ apply Rle_ge, Rmult_le_pos; trivial.\n                match_destr; lra.\n        * intros; now rewrite sum_Rbar_n_finite_sum_n.\n        * intros; now rewrite sum_Rbar_n_finite_sum_n.          \n  }\n  apply Series_ext; intros.\n  rewrite Series_scal_l.\n  now rewrite Rmult_comm.\n Qed.\n\nEnd zeroprop.\n\nLemma ELimSup_ELim_seq_le f : Rbar_le (ELim_seq f) (ELimSup_seq f).\nProof.\n  unfold ELim_seq.\n  generalize (ELimSup_ELimInf_seq_le f).\n  destruct (ELimInf_seq f)\n  ; destruct (ELimSup_seq f)\n  ; simpl; try lra.\nQed.\n\nLemma ELimInf_ELim_seq_le f : Rbar_le (ELimInf_seq f) (ELim_seq f).\nProof.\n  unfold ELim_seq.\n  generalize (ELimSup_ELimInf_seq_le f).\n  destruct (ELimInf_seq f)\n  ; destruct (ELimSup_seq f)\n  ; simpl; try lra.\nQed.\n\n  Lemma is_ELim_seq_sup_seq_incr_R (f : nat -> Rbar) (l : R) :\n    (forall n, Rbar_le (f n) (f (S n))) ->\n    (is_ELimSup_seq f l) <-> is_sup_seq f l.\n  Proof.\n    intros.\n    unfold is_ELimSup_seq, is_sup_seq.\n    split; intros; destruct (H0 eps); split; generalize (cond_pos eps); intros eps_pos.\n    - intros.\n      simpl.\n      destruct H2.\n      destruct (le_dec x n).\n      + now apply H2.\n      + specialize (H2 x).\n        cut_to H2; try lia; simpl in H2.\n        assert (n <= x)%nat by lia.\n        assert (Rbar_le (f n) (f x)) by now apply Rbar_le_incr.\n        eapply Rbar_le_lt_trans.\n        * apply H4.\n        * apply H2.\n    - destruct (H1 0%nat) as [? [? ?]].\n      now exists x.\n    - intros.\n      destruct H2.\n      exists (max x N).\n      split; try lia.\n      assert (Rbar_le (f x) (f (Init.Nat.max x N))).\n      {\n        destruct (le_dec N x).\n        - rewrite Nat.max_l; try lia.\n          apply Rbar_le_refl.\n        - rewrite Nat.max_r; try lia.\n          assert (x <= N)%nat by lia.\n          now apply Rbar_le_incr.\n      }\n      eapply Rbar_lt_le_trans.\n      * apply H2.\n      * apply H3.\n    - exists (0%nat).\n      intros.\n      apply H1.\n   Qed.\n\n  Lemma is_ELim_seq_sup_seq_incr (f : nat -> Rbar) (l : Rbar) :\n    (forall n, Rbar_le (f n) (f (S n))) ->\n    (is_ELimSup_seq f l) <-> is_sup_seq f l.\n  Proof.\n    intros.\n    destruct l.\n    - now apply is_ELim_seq_sup_seq_incr_R.\n    - unfold is_ELimSup_seq, is_sup_seq.\n      split; intros.\n      + destruct (H0 M 0%nat) as [? [? ?]].\n        now exists x.\n      + destruct (H0 M).\n        exists (max x N).\n        split; try lia.\n        assert (Rbar_le (f x) (f (Init.Nat.max x N))).\n        {\n          destruct (le_dec N x).\n          - rewrite Nat.max_l; try lia.\n            apply Rbar_le_refl.\n          - rewrite Nat.max_r; try lia.\n            assert (x <= N)%nat by lia.\n            now apply Rbar_le_incr.\n        }\n      eapply Rbar_lt_le_trans.\n      * apply H1.\n      * apply H2.\n    - unfold is_ELimSup_seq, is_sup_seq.\n      split; intros.\n      + destruct (H0 M).\n        destruct (le_dec x n).\n        * now apply H1.\n        * assert (n <= x)%nat by lia.\n          apply Rbar_le_lt_trans with (y := f x).\n          -- now apply Rbar_le_incr.\n          -- apply H1; try lia.\n      + exists (0%nat).\n        intros.\n        apply H0.\n   Qed.        \n\n", "meta": {"author": "IBM", "repo": "FormalML", "sha": "e399d096f1ad572420dbd1c638d593eee2129cbe", "save_path": "github-repos/coq/IBM-FormalML", "path": "github-repos/coq/IBM-FormalML/FormalML-e399d096f1ad572420dbd1c638d593eee2129cbe/coq/utils/RbarAdd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.6703238556259354}}
{"text": "Inductive List (A : Set) : Set :=\n  | Nil : List A\n  | Cons : A -> List A -> List A.\n\nInductive eqlong : List nat -> List nat -> Prop :=\n  | eql_cons :\n      forall (n m : nat) (x y : List nat),\n      eqlong x y -> eqlong (Cons nat n x) (Cons nat m y)\n  | eql_nil : eqlong (Nil nat) (Nil nat).\n\n\nParameter V1 : eqlong (Nil nat) (Nil nat) \\/ ~ eqlong (Nil nat) (Nil nat).\nParameter\n  V2 :\n    forall (a : nat) (x : List nat),\n    eqlong (Nil nat) (Cons nat a x) \\/ ~ eqlong (Nil nat) (Cons nat a x).\nParameter\n  V3 :\n    forall (a : nat) (x : List nat),\n    eqlong (Cons nat a x) (Nil nat) \\/ ~ eqlong (Cons nat a x) (Nil nat).\nParameter\n  V4 :\n    forall (a : nat) (x : List nat) (b : nat) (y : List nat),\n    eqlong (Cons nat a x) (Cons nat b y) \\/\n    ~ eqlong (Cons nat a x) (Cons nat b y).\n\nParameter\n  nff :\n    forall (n m : nat) (x y : List nat),\n    ~ eqlong x y -> ~ eqlong (Cons nat n x) (Cons nat m y).\nParameter\n  inv_r : forall (n : nat) (x : List nat), ~ eqlong (Nil nat) (Cons nat n x).\nParameter\n  inv_l : forall (n : nat) (x : List nat), ~ eqlong (Cons nat n x) (Nil nat).\n\nFixpoint eqlongdec (x y : List nat) {struct x} :\n eqlong x y \\/ ~ eqlong x y :=\n  match x, y return (eqlong x y \\/ ~ eqlong x y) with\n  | Nil, Nil => or_introl (~ eqlong (Nil nat) (Nil nat)) eql_nil\n  | Nil, Cons a x as L => or_intror (eqlong (Nil nat) L) (inv_r a x)\n  | Cons a x as L, Nil => or_intror (eqlong L (Nil nat)) (inv_l a x)\n  | Cons a x as L1, Cons b y as L2 =>\n      match eqlongdec x y return (eqlong L1 L2 \\/ ~ eqlong L1 L2) with\n      | or_introl h => or_introl (~ eqlong L1 L2) (eql_cons a b x y h)\n      | or_intror h => or_intror (eqlong L1 L2) (nff a b x y h)\n      end\n  end.\n\n\nType\n  match Nil nat as x, Nil nat as y return (eqlong x y \\/ ~ eqlong x y) with\n  | Nil, Nil => or_introl (~ eqlong (Nil nat) (Nil nat)) eql_nil\n  | Nil, Cons a x as L => or_intror (eqlong (Nil nat) L) (inv_r a x)\n  | Cons a x as L, Nil => or_intror (eqlong L (Nil nat)) (inv_l a x)\n  | Cons a x as L1, Cons b y as L2 =>\n      match eqlongdec x y return (eqlong L1 L2 \\/ ~ eqlong L1 L2) with\n      | or_introl h => or_introl (~ eqlong L1 L2) (eql_cons a b x y h)\n      | or_intror h => or_intror (eqlong L1 L2) (nff a b x y h)\n      end\n  end.\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/Case9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6702785982333196}}
{"text": "(****************************************************************************\n                                                                             \n          IEEE754  :  ClosestPlus                                                   \n                                                                             \n          Laurent Thery, Sylvie Boldo                                                      \n                                                                             \n  ******************************************************************************)\n\nRequire Export FroundPlus.\nRequire Export ClosestProp.\nSection ClosestP.\nVariable b : Fbound.\nVariable radix : Z.\nVariable precision : nat.\n \nLet FtoRradix := FtoR radix.\nLocal Coercion FtoRradix : float >-> R.\n\nHypothesis radixMoreThanOne : (1 < radix)%Z.\n \nLet radixMoreThanZERO := Zlt_1_O _ (Zlt_le_weak _ _ radixMoreThanOne).\nHint Resolve radixMoreThanZERO: zarith.\nHypothesis precisionGreaterThanOne : 1 < precision.\nHypothesis pGivesBound : Zpos (vNum b) = Zpower_nat radix precision.\n \nTheorem errorBoundedPlusLe :\n forall p q pq : float,\n Fbounded b p ->\n Fbounded b q ->\n (Fexp p <= Fexp q)%Z ->\n Closest b radix (p + q) pq ->\n exists error : float,\n   error = Rabs (p + q - pq) :>R /\\\n   Fbounded b error /\\ Fexp error = Zmin (Fexp p) (Fexp q).\nintros p q pq H' H'0 H'1 H'2.\ncut (ex (fun m : Z => pq = Float m (Fexp (Fplus radix p q)) :>R)).\n2: unfold FtoRradix in |- *;\n    apply\n     RoundedModeRep\n      with (b := b) (precision := precision) (P := Closest b radix); \n    auto.\n2: apply ClosestRoundedModeP with (precision := precision); auto.\n2: rewrite (Fplus_correct radix); auto with arith.\nintros H'3; elim H'3; intros m E; clear H'3.\nexists\n (Fabs (Fminus radix q (Fminus radix (Float m (Fexp (Fplus radix p q))) p))).\ncut (forall A B : Prop, A -> (A -> B) -> A /\\ B);\n [ intros tmp; apply tmp; clear tmp | auto ].\nunfold FtoRradix in |- *; rewrite Fabs_correct; auto with arith.\ncut (forall p q : R, p = q -> Rabs p = Rabs q);\n [ intros tmp; apply tmp; clear tmp | intros p' q' H; rewrite H; auto ].\nunfold FtoRradix in |- *; repeat rewrite Fminus_correct; auto with arith.\nunfold FtoRradix in E; rewrite E; auto.\nring.\nintros H'4.\ncut (Rabs (pq - (p + q)) <= Rabs (q - (p + q)))%R.\n2: elim H'2; auto.\nreplace (q - (p + q))%R with (- FtoRradix p)%R.\n2: ring.\nrewrite Rabs_Ropp.\nunfold FtoRradix in |- *; rewrite <- Fabs_correct; auto with arith.\nrewrite <- Rabs_Ropp; rewrite Ropp_minus_distr.\nunfold FtoRradix in H'4; rewrite <- H'4.\nsimpl in |- *.\nrewrite Zmin_le1; auto.\ngeneralize H'1 H'; case p; case q; unfold Fabs, Fminus, Fopp, Fplus in |- *;\n simpl in |- *; clear H'1 H'.\nintros Fnum1 Fexp1 Fnum2 Fexp2 H'5 H'6.\nrepeat rewrite Zmin_n_n; auto.\nrepeat rewrite (Zmin_le2 _ _ H'5); auto with zarith.\nreplace (Zabs_nat (Fexp2 - Fexp2)) with 0.\nrewrite Zpower_nat_O.\ncut (forall z : Z, (z * 1%nat)%Z = z);\n [ intros tmp; repeat rewrite tmp; clear tmp | auto with zarith ].\nunfold FtoRradix, FtoR in |- *; simpl in |- *.\nintros H'.\nrepeat split; simpl in |- *.\nrewrite (fun x => Zabs_eq (Zabs x)); auto with zarith.\napply Zle_lt_trans with (Zabs Fnum2); auto.\napply le_IZR.\napply (Rle_monotony_contra_exp radix) with (z := Fexp2); auto.\ncase H'6; auto.\ncase H'6; auto.\nintros; simpl in |- *; ring.\nreplace (Fexp2 - Fexp2)%Z with 0%Z; simpl in |- *; auto with zarith.\nQed.\n \nTheorem errorBoundedPlusAbs :\n forall p q pq : float,\n Fbounded b p ->\n Fbounded b q ->\n Closest b radix (p + q) pq ->\n exists error : float,\n   error = Rabs (p + q - pq) :>R /\\\n   Fbounded b error /\\ Fexp error = Zmin (Fexp p) (Fexp q).\nintros p q pq H' H'0 H'1.\ncase (Zle_or_lt (Fexp p) (Fexp q)); intros H'2.\napply errorBoundedPlusLe; auto.\nreplace (p + q)%R with (q + p)%R; [ idtac | ring ].\nreplace (Zmin (Fexp p) (Fexp q)) with (Zmin (Fexp q) (Fexp p));\n [ idtac | apply Zmin_sym ].\napply errorBoundedPlusLe; auto.\nauto with zarith.\napply (ClosestCompatible b radix (p + q)%R (q + p)%R pq); auto.\nring.\ncase H'1; auto.\nQed.\n \nTheorem errorBoundedPlus :\n forall p q pq : float,\n (Fbounded b p) ->\n (Fbounded b q) ->\n (Closest b radix (p + q) pq) ->\n exists error : float,\n   error = (p + q - pq)%R :>R /\\\n   (Fbounded b error) /\\ (Fexp error) = (Zmin (Fexp p) (Fexp q)).\nintros p q pq H' H'0 H'1.\ncase (errorBoundedPlusAbs p q pq); auto.\nintros x H'2; elim H'2; intros H'3 H'4; elim H'4; intros H'5 H'6;\n clear H'4 H'2.\ngeneralize H'3; clear H'3.\nunfold Rabs in |- *; case (Rcase_abs (p + q - pq)).\nintros H'2 H'3; exists (Fopp x); split; auto.\nunfold FtoRradix in |- *; rewrite Fopp_correct; auto.\nunfold FtoRradix in H'3; rewrite H'3; ring.\nsplit.\napply oppBounded; auto.\nrewrite <- H'6; auto.\nintros H'2 H'3; exists x; split; auto.\nQed.\n \nTheorem plusExact1 :\n forall p q r : float,\n Fbounded b p ->\n Fbounded b q ->\n Closest b radix (p + q) r ->\n (Fexp r <= Zmin (Fexp p) (Fexp q))%Z -> r = (p + q)%R :>R.\nintros p q r H' H'0 H'1 H'2.\ncut\n (2%nat * Rabs (FtoR radix (Fplus radix p q) - FtoR radix r) <=\n  Float 1%nat (Fexp r))%R;\n [ rewrite Fplus_correct; auto with zarith; intros Rl1 | idtac ].\ncase errorBoundedPlus with (p := p) (q := q) (pq := r); auto.\nintros x H'3; elim H'3; intros H'4 H'5; elim H'5; intros H'6 H'7;\n clear H'5 H'3.\nunfold FtoRradix in H'4; rewrite <- H'4 in Rl1.\n2: apply Rle_trans with (Fulp b radix precision r); auto.\n2: apply (ClosestUlp b radix precision); auto.\n2: rewrite Fplus_correct; auto with zarith.\n2: unfold FtoRradix in |- *; apply FulpLe; auto.\n2: apply\n    RoundedModeBounded\n     with (radix := radix) (P := Closest b radix) (r := (p + q)%R); \n    auto.\n2: apply ClosestRoundedModeP with (precision := precision); auto.\ncut (x = 0%R :>R); [ unfold FtoRradix in |- *; intros Eq1 | idtac ].\nreplace (FtoR radix r) with (FtoR radix r + 0)%R; [ idtac | ring ].\nrewrite <- Eq1.\nrewrite H'4; ring.\napply (is_Fzero_rep1 radix).\ncase (Z_zerop (Fnum x)); simpl in |- *; auto.\nintros H'3; Contradict Rl1.\napply Rgt_not_le.\nred in |- *; apply Rle_lt_trans with (Rabs (FtoR radix x)).\nunfold FtoRradix, FtoR in |- *; simpl in |- *; auto.\nrewrite Rabs_mult.\napply Rmult_le_compat; auto with real arith.\ngeneralize H'3; case (Fnum x); simpl in |- *; auto with real zarith.\nintros H'5; case H'5; auto.\nintros p0 H'5; rewrite Rabs_right; auto with real.\nreplace 1%R with (INR 1); unfold IZR; repeat rewrite <- INR_IPR; auto with real arith.\nintros p0 H'5; rewrite Faux.Rabsolu_left1; auto.\nunfold IZR; rewrite Ropp_involutive.\nrepeat rewrite <- INR_IPR; simpl; replace 1%R with (INR 1); auto with real arith.\nunfold IZR; repeat rewrite <- INR_IPR; replace 0%R with (- 0%nat)%R; auto with real.\nrewrite Rabs_right; auto with real arith.\napply Rle_powerRZ; auto with real arith.\nauto with zarith.\napply Rle_ge; cut (1 < radix)%Z; auto with float real zarith.\ncut (forall r : R, (2%nat * r)%R = (r + r)%R);\n [ intros tmp; rewrite tmp; clear tmp | intros f; simpl in |- *; ring ].\npattern (Rabs (FtoR radix x)) at 1 in |- *;\n replace (Rabs (FtoR radix x)) with (Rabs (FtoR radix x) + 0)%R;\n [ idtac | ring ].\napply Rplus_lt_compat_l; auto.\ncase (Rabs_pos (FtoR radix x)); auto.\nrewrite <- Fabs_correct; auto with arith.\nintros H'5; Contradict H'3.\ncut (Fnum (Fabs x) = 0%Z).\nunfold Fabs in |- *; simpl in |- *; case (Fnum x); simpl in |- *; auto;\n intros; discriminate.\nchange (is_Fzero (Fabs x)) in |- *.\napply (is_Fzero_rep2 radix); auto with arith.\nQed.\n \nTheorem plusExact1bis :\n forall p q r : float,\n Fbounded b p ->\n Fbounded b q ->\n Closest b radix (p + q) r ->\n r <> (p + q)%R :>R -> (Zmin (Fexp p) (Fexp q) < Fexp r)%Z.\nintros p0 q0 r0 H' H'0 H'1 H'2;\n case (Zle_or_lt (Fexp r0) (Zmin (Fexp p0) (Fexp q0))); \n auto.\nintros H'3; Contradict H'2.\napply plusExact1; auto.\nQed.\n \nTheorem plusExact2Aux :\n forall p q r : float,\n (0 <= p)%R ->\n Fcanonic radix b p ->\n Fbounded b q ->\n Closest b radix (p + q) r ->\n (Fexp r < Zpred (Fexp p))%Z -> r = (p + q)%R :>R.\nintros p q r H' H'0 H'1 H'2 H'3.\napply plusExact1; auto.\napply FcanonicBound with (1 := H'0); auto.\ncase (Zle_or_lt (Fexp p) (Fexp q)); intros Zl1.\nrewrite Zmin_le1; auto with zarith.\napply Zle_trans with (Zpred (Fexp p)); auto with zarith.\nunfold Zpred in |- *; auto with zarith.\nrewrite Zmin_le2; auto with zarith.\ncase (Zlt_next _ _ Zl1); intros Zl2.\nrewrite Zl2 in H'3.\nreplace (Fexp q) with (Zpred (Zsucc (Fexp q))); auto with zarith;\n unfold Zpred, Zsucc in |- *; ring.\ncase H'0; clear H'0; intros H'0.\nabsurd (r < Float (nNormMin radix precision) (Zpred (Fexp p)))%R.\napply Rle_not_lt; auto.\nunfold FtoRradix in |- *;\n apply\n  (ClosestMonotone b radix\n     (Float (nNormMin radix precision) (Zpred (Fexp p))) (\n     p + q)%R); auto; auto.\ncut (Float (nNormMin radix precision) (Fexp p) <= p)%R;\n [ intros Eq1 | idtac ].\ncase (Rle_or_lt 0 q); intros Rl1.\napply Rlt_le_trans with (FtoRradix p).\napply\n Rlt_le_trans with (FtoRradix (Float (nNormMin radix precision) (Fexp p)));\n auto.\nunfold FtoRradix, FtoR in |- *; simpl in |- *; auto.\napply Rmult_lt_compat_l; auto with real arith.\nreplace 0%R with (IZR 0%nat); auto with real; auto with real float arith.\napply Rlt_IZR; apply nNormPos; auto with zarith.\nunfold Zpred in |- *; auto with real float zarith arith.\npattern (FtoRradix p) at 1 in |- *; replace (FtoRradix p) with (p + 0)%R;\n auto with real.\napply Rplus_lt_reg_l with (r := (- q)%R); auto.\nreplace (- q + (p + q))%R with (FtoRradix p); [ idtac | ring ].\napply\n Rlt_le_trans with (FtoRradix (Float (nNormMin radix precision) (Fexp p)));\n auto.\napply\n Rlt_le_trans\n  with (2%nat * Float (nNormMin radix precision) (Zpred (Fexp p)))%R; \n auto.\ncut (forall r : R, (2%nat * r)%R = (r + r)%R);\n [ intros tmp; rewrite tmp; clear tmp | intros; simpl in |- *; ring ].\nrewrite (Rplus_comm (- q)).\napply Rplus_lt_compat_l.\nrewrite <- Faux.Rabsolu_left1; auto.\nrewrite <- (Fabs_correct radix); auto with arith.\nunfold FtoRradix in |- *; apply maxMaxBis with (b := b); auto with zarith.\napply Rlt_le; auto.\napply\n Rle_trans with (radix * Float (nNormMin radix precision) (Zpred (Fexp p)))%R.\napply Rmult_le_compat_r; auto.\napply (LeFnumZERO radix); simpl in |- *; auto with arith.\napply Zlt_le_weak; apply nNormPos; auto with zarith.\nrewrite INR_IZR_INZ; apply Rle_IZR; simpl in |- *; cut (1 < radix)%Z;\n auto with real zarith.\npattern (Fexp p) at 2 in |- *; replace (Fexp p) with (Zsucc (Zpred (Fexp p)));\n [ idtac | unfold Zsucc, Zpred in |- *; ring ].\nunfold FtoRradix, FtoR in |- *; simpl in |- *.\nrewrite powerRZ_Zs; auto with real zarith.\nrepeat rewrite <- Rmult_assoc.\nrewrite (Rmult_comm radix); auto with real.\nunfold FtoRradix, FtoR in |- *; simpl in |- *; auto.\napply Rmult_le_compat_r; auto with real zarith.\napply Rle_IZR.\nrewrite <- (Zabs_eq (Fnum p)); auto with zarith.\napply pNormal_absolu_min with (b := b); auto with arith.\nunfold FtoRradix, FtoR in |- *; simpl in |- *; auto.\napply (LeR0Fnum radix); auto with arith.\napply (RoundedModeProjectorIdem b radix (Closest b radix)); auto.\napply ClosestRoundedModeP with (precision := precision); auto.\nrepeat split; simpl in |- *.\nrewrite Zabs_eq; auto with zarith.\napply ZltNormMinVnum; auto with arith.\napply Zlt_le_weak; apply nNormPos; auto with zarith.\napply Zle_trans with (Fexp q); auto with float zarith.\ncase (Rle_or_lt 0 r); intros Rl1.\nrewrite <- (Rabs_right r); auto with real.\nrewrite <- (Fabs_correct radix); auto with arith.\nunfold FtoRradix in |- *; apply maxMaxBis with (b := b); auto with zarith.\napply\n RoundedModeBounded\n  with (radix := radix) (P := Closest b radix) (r := (p + q)%R); \n auto.\napply ClosestRoundedModeP with (precision := precision); auto with real.\napply Rlt_le_trans with 0%R; auto.\napply (LeFnumZERO radix); simpl in |- *; auto with arith.\napply Zlt_le_weak; apply nNormPos; auto with zarith.\nabsurd (- dExp b <= Fexp q)%Z; auto with float.\napply Zlt_not_le.\ncase H'0; intros Z1 (Z2, Z3); rewrite <- Z2; auto with zarith.\nQed.\n \nTheorem plusExact2 :\n forall p q r : float,\n Fcanonic radix b p ->\n Fbounded b q ->\n Closest b radix (p + q) r ->\n (Fexp r < Zpred (Fexp p))%Z -> r = (p + q)%R :>R.\nintros p q r H' H'0 H'1 H'2.\ncase (Rle_or_lt 0 p); intros Rl1.\napply plusExact2Aux; auto.\nreplace (p + q)%R with (- (Fopp p + Fopp q))%R.\nrewrite <- (plusExact2Aux (Fopp p) (Fopp q) (Fopp r)); auto.\nunfold FtoRradix in |- *; rewrite Fopp_correct; ring.\nunfold FtoRradix in |- *; rewrite Fopp_correct.\napply Rlt_le; replace 0%R with (-0)%R; auto with real.\napply FcanonicFopp; auto with arith.\napply oppBounded; auto.\nreplace (Fopp p + Fopp q)%R with (- (p + q))%R.\napply ClosestOpp; auto.\nunfold FtoRradix in |- *; repeat rewrite Fopp_correct; ring.\nunfold FtoRradix in |- *; repeat rewrite Fopp_correct; ring.\nQed.\n \nTheorem plusExactR0 :\n forall p q r : float,\n Fbounded b p ->\n Fbounded b q ->\n Closest b radix (p + q) r -> r = 0%R :>R -> r = (p + q)%R :>R.\nintros p q r H' H'0 H'1 H'2.\ncut (r = FtoRradix (Fzero (- dExp b)) :>R);\n [ intros Eq1; rewrite Eq1\n | rewrite H'2; apply sym_eq; unfold FtoRradix in |- *; apply FzeroisZero ].\napply plusExact1; auto.\napply (ClosestCompatible b radix (p + q)%R (p + q)%R r); auto.\napply FboundedFzero; auto.\nsimpl in |- *; auto.\nunfold Zmin in |- *; case (Fexp p ?= Fexp q)%Z; auto with float.\nQed.\n \nTheorem plusErrorBound1 :\n forall p q r : float,\n Fbounded b p ->\n Fbounded b q ->\n Closest b radix (p + q) r ->\n ~ is_Fzero r ->\n (Rabs (r - (p + q)) < Rabs r * / 2%nat * (radix * / pPred (vNum b)))%R.\nintros p q r H' H'0 H'1 H'2.\ncut (Fcanonic radix b (Fnormalize radix b precision r));\n [ intros tmp; Casec tmp; intros Fs | idtac ].\n3: apply FnormalizeCanonic; auto with arith.\n3: apply\n    RoundedModeBounded\n     with (radix := radix) (P := Closest b radix) (r := (p + q)%R); \n    auto.\n3: apply ClosestRoundedModeP with (precision := precision); auto.\n2: rewrite <- (plusExact1 p q (Fnormalize radix b precision r)); auto.\n2: unfold FtoRradix in |- *; rewrite FnormalizeCorrect; auto with arith.\n2: replace (FtoR radix r - FtoR radix r)%R with 0%R; [ idtac | ring ].\n2: rewrite Rabs_R0.\n2: replace 0%R with (0 * (radix * / pPred (vNum b)))%R;\n    [ apply Rmult_lt_compat_r | ring ].\n2: replace 0%R with (0 * / pPred (vNum b))%R;\n    [ apply Rmult_lt_compat_r | ring ].\n2: apply Rinv_0_lt_compat; replace 0%R with (IZR 0); auto with real zarith.\n2: apply Rlt_IZR; unfold pPred in |- *; apply Zlt_succ_pred; simpl in |- *.\n2: apply vNumbMoreThanOne with (radix := radix) (precision := precision);\n    auto with real zarith.\n2: cut (1 < radix)%Z; auto with real zarith.\n2: replace 0%R with (0 * / 2%nat)%R; [ apply Rmult_lt_compat_r | ring ];\n    auto with real.\n2: case (Rabs_pos (FtoR radix r)); auto.\n2: intros H'3; Contradict H'2.\n2: apply is_Fzero_rep2 with (radix := radix); auto with real arith.\n2: generalize H'3; fold FtoRradix in |- *; unfold Rabs in |- *;\n    case (Rcase_abs r); auto.\n2: intros r0 H'2; replace 0%R with (-0)%R; [ rewrite H'2 | idtac ]; ring.\n2: apply (ClosestCompatible b radix (p + q)%R (p + q)%R r); auto.\n2: apply sym_eq; apply FnormalizeCorrect; auto.\n2: apply FnormalizeBounded; auto with arith.\n2: apply\n    RoundedModeBounded\n     with (radix := radix) (P := Closest b radix) (r := (p + q)%R); \n    auto.\n2: apply ClosestRoundedModeP with (precision := precision); auto.\n2: replace (Fexp (Fnormalize radix b precision r)) with (- dExp b)%Z.\n2: unfold Zmin in |- *; case (Fexp p ?= Fexp q)%Z; auto with float.\n2: apply sym_equal; case Fs; intros H1 H2; case H2; auto.\napply Rle_lt_trans with (/ 2%nat * Fulp b radix precision r)%R.\napply Rmult_le_reg_l with (r := INR 2); auto with real.\nrewrite <- Rmult_assoc; rewrite Rinv_r; auto with real; rewrite Rmult_1_l.\nunfold FtoRradix in |- *; rewrite <- Rabs_Ropp; rewrite Ropp_minus_distr;\n rewrite <- (Fplus_correct radix); auto with zarith.\napply ClosestUlp; auto.\nrewrite Fplus_correct; auto with arith.\nreplace (Rabs r * / 2%nat * (radix * / pPred (vNum b)))%R with\n (/ 2%nat * (Rabs r * (radix * / pPred (vNum b))))%R;\n [ apply Rmult_lt_compat_l; auto with real | ring ].\nreplace (Fulp b radix precision r) with\n (Float (pPred (vNum b)) (Zpred (Fexp (Fnormalize radix b precision r))) *\n  (radix * / pPred (vNum b)))%R.\napply Rmult_lt_compat_r.\nreplace 0%R with (radix * 0)%R; [ apply Rmult_lt_compat_l | ring ];\n auto with real arith.\napply Rinv_0_lt_compat; replace 0%R with (IZR 0%nat); auto with real arith;\n apply Rlt_IZR.\nunfold pPred in |- *; apply Zlt_succ_pred;\n apply (vNumbMoreThanOne radix) with (precision := precision);\n auto with zarith.\nunfold FtoRradix in |- *;\n rewrite <- (FnormalizeCorrect _ radixMoreThanOne b precision r).\nrewrite <- (Fabs_correct radix); auto with arith.\napply FnormalBoundAbs; auto with zarith.\nunfold Fulp, FtoRradix, FtoR in |- *; simpl in |- *.\napply\n trans_eq\n  with\n    (pPred (vNum b) * / pPred (vNum b) *\n     (radix * powerRZ radix (Zpred (Fexp (Fnormalize radix b precision r)))))%R;\n [ ring | idtac ]; auto.\nrewrite Rinv_r; auto with real arith.\nrewrite <- powerRZ_Zs; auto with real.\ncut (forall r : Z, Zsucc (Zpred r) = r);\n [ intros Er; rewrite Er | intros r'; unfold Zsucc, Zpred in |- * ]; \n ring.\napply Rlt_dichotomy_converse; right; red in |- *.\nreplace 0%R with (IZR 0); cut (1 < radix)%Z; auto with real zarith.\napply Rlt_dichotomy_converse; right; red in |- *.\nreplace 0%R with (IZR 0); auto with real zarith.\nunfold pPred in |- *; apply Rlt_IZR; apply Zlt_succ_pred; simpl in |- *.\napply vNumbMoreThanOne with (radix := radix) (precision := precision);\n auto with real arith.\nQed.\n \nTheorem plusErrorBound1bis :\n forall p q r : float,\n Fbounded b p ->\n Fbounded b q ->\n Closest b radix (p + q) r ->\n ~ is_Fzero r ->\n (Rabs (r - (p + q)) <= Rabs r * / 2%nat * (radix * / Zpos (vNum b)))%R.\nintros p q r H' H'0 H'1 H'2.\ncut (Fcanonic radix b (Fnormalize radix b precision r));\n [ intros tmp; Casec tmp; intros Fs | idtac ].\n3: apply FnormalizeCanonic; auto with arith.\n3: apply\n    RoundedModeBounded\n     with (radix := radix) (P := Closest b radix) (r := (p + q)%R); \n    auto.\n3: apply ClosestRoundedModeP with (precision := precision); auto.\n2: rewrite <- (plusExact1 p q (Fnormalize radix b precision r)); auto.\n2: unfold FtoRradix in |- *; rewrite FnormalizeCorrect; auto.\n2: replace (FtoR radix r - FtoR radix r)%R with 0%R; [ idtac | ring ].\n2: rewrite Rabs_R0.\n2: replace 0%R with (0 * (radix * / Zpos (vNum b)))%R;\n    [ apply Rmult_le_compat_r | ring ]; auto with real zarith.\n2: replace 0%R with (0 * / Zpos (vNum b))%R;\n    [ apply Rmult_le_compat_r | ring ]; auto with real zarith.\n2: replace 0%R with (0 * / 2%nat)%R; [ apply Rmult_le_compat_r | ring ];\n    auto with real zarith.\n2: apply (ClosestCompatible b radix (p + q)%R (p + q)%R r); auto.\n2: apply sym_eq; apply FnormalizeCorrect; auto.\n2: apply FnormalizeBounded; auto with arith.\n2: apply\n    RoundedModeBounded\n     with (radix := radix) (P := Closest b radix) (r := (p + q)%R); \n    auto.\n2: apply ClosestRoundedModeP with (precision := precision); auto.\n2: replace (Fexp (Fnormalize radix b precision r)) with (- dExp b)%Z.\n2: unfold Zmin in |- *; case (Fexp p ?= Fexp q)%Z; intuition.\n2: case Fs; intros H1 (H2, H3); auto.\napply Rle_trans with (/ 2%nat * Fulp b radix precision r)%R.\nreplace (Rabs (FtoRradix r - (FtoRradix p + FtoRradix q))) with\n (/ 2%nat * (2%nat * Rabs (FtoRradix r - (FtoRradix p + FtoRradix q))))%R;\n [ idtac | rewrite <- Rmult_assoc; rewrite Rinv_l; auto with real ].\napply Rmult_le_compat_l; auto with real.\nreplace (FtoRradix r - (FtoRradix p + FtoRradix q))%R with\n (- (FtoRradix p + FtoRradix q - FtoRradix r))%R;\n [ rewrite Rabs_Ropp | ring ].\napply (ClosestUlp b radix); auto.\nreplace (Rabs r * / 2%nat * (radix * / Zpos (vNum b)))%R with\n (/ 2%nat * (Rabs r * (radix * / Zpos (vNum b))))%R;\n [ apply Rmult_le_compat_l; auto with real | ring ].\nreplace (Fulp b radix precision r) with\n (Zpos (vNum b) *\n  FtoR radix (Float 1%nat (Zpred (Fexp (Fnormalize radix b precision r)))) *\n  (radix * / Zpos (vNum b)))%R.\napply Rmult_le_compat_r.\nreplace 0%R with (radix * 0)%R; [ apply Rmult_le_compat_l | ring ];\n apply Rlt_le; auto with real arith;\nrewrite INR_IZR_INZ; apply Rlt_IZR; simpl in |- *; apply Zlt_1_O;\n apply Zlt_le_weak;\n apply (vNumbMoreThanOne radix) with (precision := precision);\n auto with zarith.\nunfold FtoRradix in |- *;\n rewrite <- (FnormalizeCorrect _ radixMoreThanOne b precision r).\nrewrite <- (Fabs_correct radix); auto with arith.\napply FnormalBoundAbs2 with precision; auto with arith.\nunfold Fulp, FtoRradix, FtoR in |- *; simpl in |- *.\napply\n trans_eq\n  with\n    (nat_of_P (vNum b) * / nat_of_P (vNum b) *\n     (radix * powerRZ radix (Zpred (Fexp (Fnormalize radix b precision r)))))%R;\n [ unfold IZR at 1 5; repeat rewrite <- INR_IPR; ring | idtac].\nrewrite Rinv_r; auto with real arith.\nrewrite <- powerRZ_Zs; auto with real zarith.\nrewrite <- Zsucc_pred; ring.\nQed.\n \nTheorem plusErrorBound1withZero :\n forall p q r : float,\n Fbounded b p ->\n Fbounded b q ->\n Closest b radix (p + q) r ->\n (Rabs (r - (p + q)) <= Rabs r * / 2%nat * (radix * / pPred (vNum b)))%R.\nintros p q r H H0 H1.\ncase (Req_dec r 0); intros Hr.\nreplace (Rabs (r - (p + q))) with (Rabs r * / 2%nat * 0)%R.\napply Rmult_le_compat_l.\nreplace 0%R with (Rabs r * 0)%R; [ apply Rmult_le_compat_l | ring ];\n auto with real arith.\nreplace 0%R with (radix * 0)%R; [ apply Rmult_le_compat_l | ring ];\n auto with real arith.\napply Rlt_le; apply Rinv_0_lt_compat; auto with real arith.\nreplace 0%R with (IZR 0%nat); auto with real zarith; apply Rlt_IZR.\napply Zle_lt_trans with (nNormMin radix precision).\napply Zlt_le_weak; apply nNormPos; auto with real zarith.\napply nNormMimLtvNum; auto with real zarith.\nrewrite <- plusExactR0 with (3 := H1); auto with real zarith.\nrewrite Hr; repeat rewrite Rabs_R0 || (rewrite Rminus_diag_eq; auto); ring.\napply Rlt_le; apply plusErrorBound1; auto.\nContradict Hr; unfold FtoRradix in |- *; apply is_Fzero_rep1; auto.\nQed.\n \nTheorem pPredMoreThanOne : (0 < pPred (vNum b))%Z.\nunfold pPred in |- *; apply Zlt_succ_pred; simpl in |- *.\napply (vNumbMoreThanOne radix) with (precision := precision);\n auto with zarith.\nQed.\n \nTheorem pPredMoreThanRadix : (radix < pPred (vNum b))%Z.\napply Zle_lt_trans with (nNormMin radix precision).\npattern radix at 1 in |- *; rewrite <- (Zpower_nat_1 radix);\n unfold nNormMin in |- *; auto with zarith.\napply nNormMimLtvNum; auto with zarith.\nQed.\n \nTheorem RoundBound :\n forall x y p : float,\n Fbounded b x ->\n Fbounded b y ->\n Fbounded b p ->\n Closest b radix (x + y) p ->\n (radix < 2%nat * pPred (vNum b))%Z ->\n (Rabs p <=\n  Rabs (x + y) *\n  (2%nat * pPred (vNum b) * / (2%nat * pPred (vNum b) - radix)))%R.\nintros x y p H H0 H1 H2 H3.\ncut (0 < 2%nat * pPred (vNum b))%Z;\n [ intros NZ1 | apply Zlt_trans with radix; auto with zarith ].\ncut (0 < 2%nat * pPred (vNum b))%R;\n [ intros NZ1'\n | rewrite INR_IZR_INZ; rewrite <- Rmult_IZR; auto with real zarith ].\ncut (radix < 2%nat * pPred (vNum b))%R;\n [ intros NZ2\n | rewrite INR_IZR_INZ; rewrite <- Rmult_IZR; auto with real zarith ].\nreplace (Rabs p) with\n (Rabs p * ((2%nat * pPred (vNum b) - radix) * / (2%nat * pPred (vNum b))) *\n  (2%nat * pPred (vNum b) * / (2%nat * pPred (vNum b) - radix)))%R.\n2: replace\n    (Rabs p * ((2%nat * pPred (vNum b) - radix) * / (2%nat * pPred (vNum b))) *\n     (2%nat * pPred (vNum b) * / (2%nat * pPred (vNum b) - radix)))%R with\n    (Rabs p *\n     ((2%nat * pPred (vNum b) - radix) * / (2%nat * pPred (vNum b) - radix)) *\n     (2%nat * pPred (vNum b) * / (2%nat * pPred (vNum b))))%R;\n    [ idtac | ring ].\n2: repeat rewrite Rinv_r; auto with real zarith; try ring.\napply Rmult_le_compat_r.\nreplace 0%R with (2%nat * pPred (vNum b) * 0)%R;\n [ apply Rmult_le_compat_l | ring ]; auto with real zarith.\nreplace ((2%nat * pPred (vNum b) - radix) * / (2%nat * pPred (vNum b)))%R\n with (1 - radix * / (2%nat * pPred (vNum b)))%R.\n2: unfold Rminus in |- *; rewrite Rmult_plus_distr_r; rewrite Rinv_r;\n    auto with real.\nreplace (Rabs p * (1 - radix * / (2%nat * pPred (vNum b))))%R with\n (Rabs p - Rabs p * (radix * / (2%nat * pPred (vNum b))))%R;\n [ idtac | ring; ring ].\napply Rplus_le_reg_l with (Rabs p * (radix * / (2%nat * pPred (vNum b))))%R.\nreplace\n (Rabs (FtoRradix p) * (radix * / (2%nat * pPred (vNum b))) +\n  (Rabs (FtoRradix p) -\n   Rabs (FtoRradix p) * (radix * / (2%nat * pPred (vNum b)))))%R with\n (Rabs p); [ idtac | ring ].\napply Rle_trans with (Rabs (p - (x + y)) + Rabs (x + y))%R.\npattern (FtoRradix p) at 1 in |- *;\n replace (FtoRradix p) with (p - (x + y) + (x + y))%R;\n [ apply Rabs_triang | ring ].\nrewrite (Rplus_comm (Rabs (p - (x + y))) (Rabs (x + y)));\n rewrite\n  (Rplus_comm (Rabs p * (radix * / (2%nat * pPred (vNum b)))) (Rabs (x + y)))\n  ; apply Rplus_le_compat_l.\nreplace (Rabs p * (radix * / (2%nat * pPred (vNum b))))%R with\n (Rabs p * / 2%nat * (radix * / pPred (vNum b)))%R;\n [ apply plusErrorBound1withZero | idtac ]; auto.\nrewrite (Rinv_mult_distr 2%nat (pPred (vNum b))); auto with real zarith.\nring.\napply NEq_IZRO; auto with real zarith.\ngeneralize pPredMoreThanOne; auto with zarith.\nQed.\n \nTheorem plusExactExp :\n forall p q pq : float,\n Fbounded b p ->\n Fbounded b q ->\n Closest b radix (p + q) pq ->\n ex\n   (fun r : float =>\n    ex\n      (fun s : float =>\n       Fbounded b r /\\\n       Fbounded b s /\\\n       s = pq :>R /\\\n       r = (p + q - s)%R :>R /\\\n       Fexp r = Zmin (Fexp p) (Fexp q) :>Z /\\\n       (Fexp r <= Fexp s)%Z /\\ (Fexp s <= Zsucc (Zmax (Fexp p) (Fexp q)))%Z)).\nintros p q pq H H0 H1.\ncase (plusExpBound b radix precision) with (P := Closest b radix) (5 := H1);\n auto with zarith.\napply (ClosestRoundedModeP b radix precision); auto with zarith.\nintros r (H2, (H3, (H4, H5))); fold FtoRradix in H3.\ncase (Req_dec (p + q - pq) 0); intros Hr.\ncut (Fbounded b (Fzero (Zmin (Fexp p) (Fexp q)))); [ intros Fbs | idtac ].\nexists (Fzero (Zmin (Fexp p) (Fexp q))); exists r; repeat (split; auto).\nrewrite (FzeroisReallyZero radix); rewrite <- Hr; rewrite <- H3; auto.\ncase (Zmin_or (Fexp p) (Fexp q)); intros Hz; rewrite Hz;\n apply FboundedZeroSameExp; auto.\ncase (errorBoundedPlus p q pq); auto.\nintros error (H6, (H7, H8)).\nexists error; exists r; repeat (split; auto).\nrewrite H3; auto.\nrewrite H8; auto.\nQed.\n \nTheorem plusExactExpCanonic :\n forall c d p q : float,\n Fbounded b c ->\n Fbounded b d ->\n Fbounded b p ->\n Fbounded b q ->\n Closest b radix (c + d) p ->\n q = (c + d - p)%R :>R ->\n q <> 0%R :>R ->\n ex\n   (fun r : float =>\n    ex\n      (fun s : float =>\n       Fcanonic radix b s /\\\n       Fbounded b r /\\\n       s = p :>R /\\\n       r = (c + d - s)%R :>R /\\\n       Fexp r = Zmin (Fexp c) (Fexp d) :>Z /\\\n       (Fexp r < Fexp s)%Z /\\ (Fexp s <= Zsucc (Zmax (Fexp c) (Fexp d)))%Z)).\nintros c d p q H H0 H1 H2 H3 H4 H5.\ncase (plusExactExp c d p); auto.\nintros r (s, (H6, (H7, (H8, (H9, (H10, (H11, H12))))))).\nexists r; exists (Fnormalize radix b precision s).\nrepeat (split; auto with float).\napply FnormalizeCanonic; auto with arith.\nrewrite <- H8; apply (FnormalizeCorrect radix); auto with zarith.\nrewrite (FnormalizeCorrect radix); auto with zarith.\napply\n ClosestErrorExpStrict\n  with (radix := radix) (b := b) (precision := precision) (x := (c + d)%R);\n auto with float.\napply FnormalizeBounded; auto with arith.\napply (ClosestCompatible b radix (c + d)%R (c + d)%R p); auto.\nrewrite (FnormalizeCorrect radix); auto with zarith.\napply FnormalizeBounded; auto with arith.\nrewrite (FnormalizeCorrect radix); auto with zarith.\nfold FtoRradix in |- *; rewrite H9; rewrite H8; rewrite <- H4; auto.\napply Zle_trans with (Fexp s); auto.\napply FcanonicLeastExp with radix b precision; auto with arith.\napply sym_eq; apply FnormalizeCorrect; auto with real.\napply FnormalizeCanonic; auto with arith.\nQed.\nEnd ClosestP.\n", "meta": {"author": "coq-contribs", "repo": "float", "sha": "b3bfbd67f7be553f169a5b257a848ea13654bbb3", "save_path": "github-repos/coq/coq-contribs-float", "path": "github-repos/coq/coq-contribs-float/float-b3bfbd67f7be553f169a5b257a848ea13654bbb3/ClosestPlus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.670275349588829}}
{"text": "Require Import Omega.\nRequire Import List.\n\nRequire Import ext.\n\n(** This file defines some lemmas for [list]s.\n*)\n\nLemma cut_length : forall A i (xys : list A) j, length xys = i + j -> exists xs ys,\n  xys = xs ++ ys /\\ length xs = i /\\ length ys = j.\nProof.\ninduction i; simpl; intros xys j l; [exists nil, xys; auto|].\ndestruct xys as [|x xys]; inversion l.\ndestruct IHi with (j := j) (xys := xys) as [? [? [? [? ?]]]]; auto.\nexists (x :: x0), x1; simpl; split; [|split]; auto.\nrewrite H; auto.\nQed.\n\nLemma Forall_nth : forall A P xs (y : A) n, Forall P xs -> P y -> P (nth n xs y).\nProof. induction xs; intros y [|n] Pxs Py; inversion Pxs; simpl in *; auto. Qed.\n\nLemma Forall_app : forall A C (xs ys : list A), Forall C (xs ++ ys) <-> Forall C xs /\\ Forall C ys.\nProof.\ninduction xs; simpl; split; intros Cxys;\nrepeat (simpl; match goal with\n  | H : _ /\\ _ |- _ => destruct H\n  | H : Forall _ (_ :: _) |- _ => inversion H; clear H\n  | |- _ /\\ _ => split\n  | |- Forall _ nil => constructor\n  | |- Forall _ (_ :: _) => constructor\n  | H : Forall _ (?xs ++ ?ys) |- Forall _ ?xs => apply (IHxs ys)\n  | H : Forall _ (?xs ++ ?ys) |- Forall _ ?ys => apply (IHxs ys)\n  | |- Forall _ (_ ++ ?ys) => apply (IHxs ys)\nend; auto).\nQed.\n\nLemma Forall_map : forall A B (h : A -> Prop) f (g : B -> Prop), (forall x, g (f x) = h x) ->\n  forall xs, Forall g (map f xs) = Forall h xs.\nProof.\ninduction xs; intros; simpl; apply propositional_extensionality; split; constructor; inversion H0; subst.\nrewrite H in H3; auto.\nrewrite IHxs in H4; auto.\nrewrite <- H in H3; auto.\nrewrite <- IHxs in H4; auto.\nQed.\n\nLemma Forall_map_impl : forall A B (h : A -> Prop) f (g : B -> Prop), (forall x, h x -> g (f x)) ->\n  forall xs, Forall h xs -> Forall g (map f xs).\nProof. induction xs; intros; simpl; constructor; inversion H0; subst; auto. Qed.\n\nLemma replicate : forall A (a : A) n, exists xs, length xs = n /\\ forall i, nth i xs a = a.\nProof.\ninduction n.\n(* 2: 0 *)\n  exists nil; split; auto.\n  intros i; destruct i; auto.\n(* 1: 1+ *)\n  destruct IHn as [xs [? ?]].\n  exists (cons a xs).\n  split; simpl; try omega.\n  intros i; destruct i; auto.\nQed.\n\nLemma skipn_overflow : forall A d h, length h < d -> skipn d h = @nil A.\nProof.\ninduction d; destruct h; simpl; intros; auto.\ninversion H.\napply IHd.\nomega.\nQed.\n\nLemma skipn_app_length : forall A (h2 h1 : list A),\n  skipn (length h1) (h1 ++ h2) = h2.\nProof. induction h1; simpl; auto. Qed.\n", "meta": {"author": "ia0", "repo": "fcc", "sha": "52e9a746273f6770ee575d0a45f25a94c58e1c38", "save_path": "github-repos/coq/ia0-fcc", "path": "github-repos/coq/ia0-fcc/fcc-52e9a746273f6770ee575d0a45f25a94c58e1c38/coq/list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893520001, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.6702752986973807}}
{"text": "\nAdd LoadPath \"/Users/Harry/Documents/Fall 2016/CSC 495/Software Foundations - Code\".\n(**` * Basics: Functional Programming in Coq *)\n\n(* REMINDER:\n\n          #####################################################\n          ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n          #####################################################\n\n   (See the [Preface] for why.) \n\n*)\n\n(* [Admitted] is Coq's \"escape hatch\" that says accept this definition\n   without proof.  We use it to mark the 'holes' in the development\n   that should be completed as part of your homework exercises.  In\n   practice, [Admitted] is useful when you're incrementally developing\n   large proofs. *)\nDefinition admit {T: Type} : T.  Admitted.\n\n(* ################################################################# *)\n(** * Introduction *)\n\n(** The functional programming style brings programming closer to\n    simple, everyday mathematics: 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 in this way enables a host of useful and powerful\n    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 shares all of these features.\n\n    The first half of this chapter introduces the most essential\n    elements of Coq's functional programming language.  The second\n    half introduces some basic _tactics_ that can be used to prove\n    simple properties of Coq programs. *)\n\n(* ################################################################# *)\n(** * Enumerated Types *)\n\n(** One unusual aspect of Coq is that its set of built-in\n    features is _extremely_ small.  For example, instead of providing\n    the usual palette of atomic data types (booleans, integers,\n    strings, etc.), Coq offers a powerful mechanism for defining new\n    data types from scratch, from which all these familiar types arise\n    as instances.\n\n    Naturally, the Coq distribution comes with an extensive standard\n    library providing definitions of booleans, numbers, and many\n    common data structures like lists and hash tables.  But there is\n    nothing magic or primitive about these library definitions.  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    To see how this definition mechanism works, let's start with a\n    very simple example. *)\n\n(* ================================================================= *)\n(** ** Days of the Week *)\n\n(** The following declaration tells Coq that we are defining\n    a new set of data values -- a _type_. *)\n\nInductive day : Type :=\n  | monday : day\n  | tuesday : day\n  | wednesday : day\n  | thursday : day\n  | friday : day\n  | saturday : day\n  | sunday : day.\n\n(** The type is called [day], and its members are [monday],\n    [tuesday], etc.  The second 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\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 performs\n    _type inference_ -- but we'll 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.\n\n    First, we can use the command [Compute] to evaluate a compound\n    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 accompanying Coq sources, find the above example,\n    submit it to 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.\n\n    Having made the assertion, we can also ask Coq to verify it, like\n    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 in its standard\n    library, together with a multitude of useful functions and\n    lemmas.  (Take a look at [Coq.Init.Datatypes] in the Coq library\n    documentation if you're interested.)  Whenever possible, we'll\n    name our own definitions and theorems so that they exactly\n    coincide with the ones in the standard library.\n\n    Functions over booleans can be defined in the same way as\n    above: *)\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\nDefinition orb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\n\n(** The last two illustrate Coq's syntax for multi-argument\n    function definitions.  The corresponding multi-argument\n    application syntax is illustrated by the following four \"unit\n    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 new,\n    infix 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 to\n    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 special phrases [Admitted] and [admit] can be used as a\n    placeholder for an incomplete definition or proof.  We'll use them\n    in exercises, to indicate the parts that we're leaving for you --\n    i.e., your job is to replace [admit] or [Admitted] with real\n    definitions or 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\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\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\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\n\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\n(** For example, the type of [negb true] is [bool]. *)\n\nCheck true.\n(* ===> true : bool *)\nCheck (negb true).\n(* ===> negb true : bool *)\n\n(** Functions like [negb] itself are also data values, just like\n    [true] and [false].  Their types are called _function types_, and\n    they are written with arrows. *)\n\nCheck negb.\n(* ===> negb : bool -> bool *)\n\n(** The type of [negb], written [bool -> bool] and pronounced\n    \"[bool] arrow [bool],\" can be read, \"Given an input of type\n    [bool], this function produces an output of type [bool].\"\n    Similarly, the type of [andb], written [bool -> bool -> bool], can\n    be read, \"Given two inputs, both of type [bool], this function\n    produces an output of type [bool].\" *)\n\n(* ================================================================= *)\n(** ** 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].  Here, we 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 comes with a bit of special notational\n    magic.  *)\n\nModule Playground1.\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 the natural numbers as follows: *)\n\nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\n(** The clauses of this definition can be read:\n      - [O] is a natural number (note that this is the letter \"[O],\"\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_.  The definition of [nat] says how\n    expressions in the set [nat] can be constructed:\n\n    - the expression [O] belongs to the set [nat];\n    - if [n] is an expression belonging to the set [nat], then [S n]\n      is also an expression belonging to the set [nat]; and\n    - expressions formed in these two ways are the only ones belonging\n      to the set [nat].\n\n    The same rules apply for our definitions of [day] and [bool]. The\n    annotations we used for their constructors are analogous to the\n    one for the [O] constructor, indicating that they don't take any\n    arguments.\n\n    These three 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 like\n    [true], [andb true false], and [S (S false)] do not.\n\n    We can write simple functions that pattern match on natural\n    numbers just as we did above -- for example, 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 Playground1.\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n    | O => O\n    | S O => O\n    | S (S n') => n'\n  end.\n\n(** Because natural numbers are such a pervasive form of data,\n    Coq provides a tiny bit of built-in magic for parsing and printing\n    them: ordinary arabic numerals can be used as an alternative to\n    the \"unary\" notation defined by the constructors [S] and [O].  Coq\n    prints numbers in arabic form by default: *)\n\nCheck (S (S (S (S O)))).\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!\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 that is a bit easier to work with: *)\n\nDefinition oddb (n:nat) : bool   :=   negb (evenb n).\n\nExample test_oddb1:    oddb 1 = true.\nProof.  reflexivity.  Qed.\nExample test_oddb2:    oddb 4 = false.\nProof. 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 Playground2.\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\n(** Adding three to two now gives us five, as we'd expect. *)\n\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 bogus\n    variable name. *)\n\nEnd Playground2.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n    | O => S O\n    | S p => mult base (exp base p)\n  end.\n\n(** **** Exercise: 1 star (factorial)  *)\n(** Recall the standard 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 => O\n    | S O => S O\n    | S n' => mult n (factorial n')\n  end.\n\n\nExample test_factorial1: (factorial 3) = 6.\nProof. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. reflexivity. Qed.\n\n(** We can make numerical expressions a little easier to read and\n    write by introducing _notations_ for addition, multiplication, and\n    subtraction. *)\n\nNotation \"x + y\" := (plus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x - y\" := (minus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x * y\" := (mult x y)\n                       (at level 40, left associativity)\n                       : nat_scope.\n\nCheck ((0 + 1) + 1).\n\n(** (The [level], [associativity], and [nat_scope] annotations\n    control how these notations are treated by Coq's parser.  The\n    details are not important, but interested readers can refer to the\n    optional \"More on Notation\" section at the end of 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\n    operation! *)\n\n(** The [beq_nat] function tests [nat]ural numbers for [eq]uality,\n    yielding a [b]oolean.  Note the use of nested [match]es (we could\n    also have used a simultaneous match, as we did in [minus].)  *)\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\n(** 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  negb (leb 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\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   x 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.\nintros n. \nreflexivity. \nQed.\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\n    almost exactly the same as the simpler examples we saw earlier;\n    there are 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.\nintros n. \nreflexivity. \nQed.\n\nTheorem mult_0_l : forall n:nat, 0 * n = 0.\nProof.\nintros n. \nreflexivity. \nQed.\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. *)\n(** You may want to add calls to [simpl] before [reflexivity] to\n    see the simplifications that Coq performs on the terms before\n    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! *) Abort.\n\n(** (Can you explain why this happens?  Step through both proofs\n    with Coq and notice how the goal and context change.)\n\n    When stuck in the middle of a proof, we can use the [Abort]\n    command to give up on it for the moment. *)\n\n\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.\n  intros H H1.\n  rewrite H.\n  rewrite H1.\n  reflexivity.  Qed.\n\n(** [] *)\n\n(** The [Admitted] command tells Coq that we want to skip trying\n    to prove this theorem and just accept it as a given.  This can be\n    useful for developing longer proofs, since we can state subsidiary\n    lemmas that we believe will be useful for making some larger\n    argument, use [Admitted] to accept them on faith for the moment,\n    and continue working on the main argument until we are sure it\n    makes sense; then we can go back and fill in the proofs we\n    skipped.  Be careful, though: every time you say [Admitted] (or\n    [admit]) you are leaving a door open for total nonsense to enter\n    Coq's nice, 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.\nintros n m.\nintros H. \nrewrite -> H.\nsimpl.\nreflexivity.\nQed.\n\n(** [] *)\n\n\n(* ################################################################# *)\n(** * Proof by Case Analysis *)\n\n(** Of course, not everything can be proved by simple\n    calculation and rewriting: In general, unknown, hypothetical\n    values (arbitrary numbers, booleans, lists, etc.) can block\n    simplification.  For example, if we try to prove the following\n    fact using the [simpl] tactic as above, we get stuck. *)\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\n    c] line right above it.  Besides [-] and [+], Coq proofs can also\n    use [*] (asterisk) as a third kind of bullet. If we ever encounter\n    a proof that generates more than three levels of subgoals, we can\n    also enclose individual subgoals in curly braces ([{ ... }]): *)\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. \n 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.\nintros b c H.\ndestruct c.\nreflexivity.\nrewrite <- H.\ndestruct b.\nsimpl.\nreflexivity.\nreflexivity.\nQed.\n\n(** **** Exercise: 1 star (zero_nbeq_plus_1)  *)\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\nintros n.\ndestruct n.\nsimpl.\nreflexivity.\nreflexivity.\nQed.\n\n\n\n(* ================================================================= *)\n(** ** More on Notation (Optional) *)\n\n(** (In general, sections marked Optional are not needed to follow the\n    rest of the book, except possibly other Optional sections.  On a\n    first reading, you might want to skim these sections so that you\n    know what's there for future reference.)\n\n    Recall the notation definitions for infix plus and times: *)\n\nNotation \"x + y\" := (plus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x * y\" := (mult x y)\n                       (at level 40, left associativity)\n                       : nat_scope.\n\n(** For each notation symbol in Coq, we can specify its _precedence\n    level_ and its _associativity_.  The precedence level [n] is\n    specified by writing [at level n]; this helps Coq parse compound\n    expressions.  The associativity setting helps to disambiguate\n    expressions containing multiple occurrences of the same\n    symbol. For example, the parameters specified above for [+] and\n    [*] say that the expression [1+2*3*4] is shorthand for\n    [(1+((2*3)*4))]. Coq uses precedence levels from 0 to 100, and\n    _left_, _right_, or _no_ associativity.  We will see more examples\n    of this later, e.g., in the [Lists]\n    chapter.\n\n    Each notation symbol is also associated with a _notation scope_.\n    Coq tries to guess what scope is meant from context, so when it\n    sees [S(O*O)] it guesses [nat_scope], but when it sees the\n    cartesian product (tuple) type [bool*bool] it guesses\n    [type_scope].  Occasionally, it is necessary to help it out with\n    percent-notation by writing [(x*y)%nat], and sometimes in what Coq\n    prints it will use [%nat] to indicate what scope a notation is in.\n\n    Notation scopes also apply to numeral notation ([3], [4], [5],\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(* ================================================================= *)\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(** * 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.\nintros.\nrewrite -> H.\nrewrite -> H.\nsimpl.\nreflexivity.\nQed.\n(** Now state and prove a theorem [negation_fn_applied_twice] similar\n    to the previous one but where the second hypothesis says that the\n    function [f] has the property that [f x = negb x].*)\n\n(* FILL IN HERE *)\n(** [] *)\n\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.\nintros b c.\ndestruct b.\ndestruct c.\ncompute.\nreflexivity.\ncompute.\nintro H.\nrewrite -> H.\nreflexivity.\ndestruct c.\ncompute.\nintro H.\nrewrite -> H.\nreflexivity.\ncompute.\nsimpl.\nreflexivity.\nQed.\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] from class,\n\n         Inductive nat : Type :=\n           | O : nat\n           | 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 numbers.\n\n    (c) Write five unit tests [test_bin_incr1], [test_bin_incr2], etc.\n        for your increment and binary-to-unary functions. Notice that\n        incrementing a binary number and then converting it to unary\n        should yield the same result as first converting it to unary and\n        then incrementing.\n*)\n\n\nInductive bin : Type :=\n| X : bin\n| Y : bin -> bin\n| Z : bin -> bin.\n\nFixpoint incr (b: bin) : bin :=\n  match b with\n    | X => Z X\n    | Y b' => Z b'\n    | Z b' => Y (incr b')\n  end.\n\nFixpoint bin_to_nat (b: bin) : nat :=\n  match b with\n    | X => O\n    | Y b' => 2 * (bin_to_nat b')\n    | Z b' => 1 + 2 * (bin_to_nat b')\n  end.\n\n\n\n(** $Date: 2016-05-26 16:17:19 -0400 (Thu, 26 May 2016) $ *)\n\n", "meta": {"author": "hpbrown92", "repo": "Coq-Solutions", "sha": "2467e185261bfe2dc043b2a49e353c8a9217b75e", "save_path": "github-repos/coq/hpbrown92-Coq-Solutions", "path": "github-repos/coq/hpbrown92-Coq-Solutions/Coq-Solutions-2467e185261bfe2dc043b2a49e353c8a9217b75e/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.670275291593566}}
{"text": "(* lt_dec : forall n m : nat, {n < m} + {~ n < m} *)\nRequire Import Arith.\n\n\n\n(* Lemma even_odd_dec : forall n, n -> {even n} + {odd n}. *)\n\nDefinition max m n :=\n  if lt_dec m n then n else m.\n\n(*\n unfold は値の定義を展開\n destruct は型の定義を展開\n *)\n\nTheorem max_lv : forall m n, m <= max m n.\nProof.\n  intros m n.\n  unfold max.\n  destruct (lt_dec m n) as [ l | _ ].\n  (* destruct lt_dec. *)\n\n  apply lt_le_weak.\n  apply l.\n\n  apply le_refl.\nQed.\n\n(* < の bool 版 *)\nFixpoint lt_bool m n :=\n  match m, n with\n    | _, 0   => false\n    | 0, S _ => true\n    | S m', S n' => lt_bool m' n'\n  end.\n\n(* lt_bool と < が同値であることを証明 *)\nLemma lt_bool_spec : forall m n, m < n <-> lt_bool m n = true.\nProof.\n  induction m; destruct n.\n\n  (* case: 0, 0 *)\n  split.\n  intro H. inversion H.\n  discriminate.\n\n  (* case: 0, S _ *)\n  split.\n  reflexivity.\n\n  intros _. apply lt_0_Sn.\n\n  (* case: S _, 0 *)\n  split.\n  intro H. inversion H.\n\n  discriminate.\n\n  (* case: S _, S _ *)\n  split.\n  simpl. intro H. apply lt_S_n in H. apply IHm. apply H.\n\n  simpl. intro H. apply IHm in H. apply lt_n_S. apply H.\nQed.\n\nDefinition max' m n := if lt_bool m n then n else m.\n\nTheorem max'_le : forall m n, m <= max' m n.\nProof.\n  intros m n; unfold max'.\n  case_eq (lt_bool m n); auto.\n  intro H.\n  apply lt_bool_spec in H.\n  apply lt_le_weak.\n  apply H.\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/s2.2.1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.6702645546168886}}
{"text": "Module FOL.\n\nParameter T : Set.\n\nParameter T_dec : forall x y : T, { x = y } + { x <> y }.\n\nParameter IsVariable : T -> Prop.\n\nDefinition Var : Set := { x : T & (IsVariable x) }.\n\nDefinition Substitution := Var -> T.\n\nParameter Apply : Substitution -> T -> T.\n\nParameter Update : Substitution -> Var -> T -> Substitution.\n\nInductive Formula : Set :=\n  | Equals : T -> T -> Formula\n  | And  : Formula -> Formula -> Formula\n  | Not : Formula -> Formula\n  | Forall : Var  -> Formula -> Formula.\n\nDefinition Valuation := Substitution.\n\nDefinition coerce (v : Var) := projS1 v.\n\nParameter Satisfies : Valuation -> Formula -> Prop.\n\nAxiom SatEquals : forall rho : Valuation, forall t t' : T,\n  Apply rho t = Apply rho t'\n  <->\n  Satisfies rho (Equals t t').\n\nAxiom SatForall : forall rho : Valuation, forall x : Var, forall phi : Formula,\n  (forall t : T, Satisfies (Update rho x t) phi)\n  <->\n  Satisfies rho (Forall x phi).\n\nAxiom SatAnd : forall rho : Valuation, forall phi phi' : Formula,\n  (Satisfies rho phi /\\ Satisfies rho phi')\n  <->\n  Satisfies rho (And phi phi').\n\nAxiom SatNot : forall rho : Valuation, forall phi : Formula,\n  (~Satisfies rho phi)\n  <->\n  Satisfies rho (Not phi).\n\nFixpoint SatisfiesF (rho : Valuation) (phi : Formula) : Prop :=\n  match phi with\n    | Equals t1 t2 => (Apply rho t1 = Apply rho t2)\n    | Forall v phi' => forall (s : T), SatisfiesF (Update rho v s) phi'\n    | And phi1 phi2 => SatisfiesF rho phi1 /\\ SatisfiesF rho phi2\n    | Not phi' => ~SatisfiesF rho phi'\n  end.\n\nRequire Import Setoid.\n\nTheorem sameThing : forall (rho : Valuation) (phi : Formula),\n  SatisfiesF rho phi <-> Satisfies rho phi.\n  intros. generalize dependent rho.\n  induction phi. intros. apply SatEquals.\n  intros. simpl. rewrite IHphi1. rewrite IHphi2. apply SatAnd.\n  intros. simpl. rewrite IHphi. apply SatNot.\n  intros. simpl. split.\n  rewrite <- SatForall. intros. apply IHphi. apply H.\n  rewrite <- SatForall. intros. apply IHphi. apply H.\nQed.\n\nInductive SatI : Valuation -> Formula -> Prop :=\n  | SatIEquals : forall rho : Valuation, forall t t' : T,\n                  (Apply rho t = Apply rho t') ->\n                    SatI rho (Equals t t')\n  | SatIForall : forall rho : Valuation, forall x : Var, forall phi : Formula,\n                  (forall t : T, SatI (Update rho x t) phi) ->\n                        SatI rho (Forall x phi)\n  | SatIAnd : forall rho : Valuation, forall phi phi' : Formula,\n               SatI rho phi ->\n                 SatI rho phi' ->\n                   SatI rho (And phi phi')\n  | SatINot : forall rho : Valuation, forall phi : Formula,\n               (SatNI rho phi) ->\n                 SatI rho (Not phi)\nwith SatNI : Valuation -> Formula -> Prop :=\n  | SatNIEquals : forall rho : Valuation, forall t t' : T,\n                  (Apply rho t <> Apply rho t') ->\n                    SatNI rho (Equals t t')\n  | SatNIForall : forall rho : Valuation, forall x : Var, forall phi : Formula, forall t : T,\n    (SatI (Update rho x t) phi -> SatNI rho (Forall x phi))\n  | SatNIAnd : forall rho : Valuation, forall phi phi' : Formula,\n               (SatNI rho phi \\/ SatNI rho phi') ->\n                   SatNI rho (And phi phi')\n  | SatNINot : forall rho : Valuation, forall phi : Formula,\n               (SatI rho phi) ->\n                 SatNI rho (Not phi).\n\n(*Require Import Classical.\n\nTheorem deMorgan : forall p q,\n  ~ (p /\\ q) <-> ~ p \\/ ~ q.\n  intros.\n  apply NNPP. tauto.\nQed.\n\nTheorem sameThing' : forall (rho : Valuation) (phi : Formula),\n  (SatisfiesF rho phi <-> SatI rho phi) /\\ ((~SatisfiesF rho phi) <-> SatNI rho phi).\n  intros. generalize dependent rho.\n  induction phi.\n  intros.\n     (* equals *)\n    split.\n      simpl. split. apply SatIEquals. intros. inversion H. assumption.\n      simpl. split. intros. apply SatNIEquals. assumption. intros. inversion H. assumption.\n      (* and *)\n    split.\n      simpl. split. intros. inversion H. constructor. apply IHphi1. assumption. apply IHphi2. assumption.\n      simpl. split. inversion H. apply IHphi1. assumption. apply IHphi2. inversion H. assumption.\n      simpl. setoid_replace (SatNI rho (And phi1 phi2)) with (~ SatisfiesF rho phi1 \\/ ~ SatisfiesF rho phi2).\n      apply deMorgan. setoid_replace (~ SatisfiesF rho phi1) with (SatNI rho phi1).\n      setoid_replace (~ SatisfiesF rho phi2) with (SatNI rho phi2). split.\n      inversion 1. assumption. intros. constructor. assumption.\n      decompose [and] (IHphi1 rho). decompose [and] (IHphi2 rho).\n      assumption. decompose [and] (IHphi1 rho). decompose [and] (IHphi2 rho).\n      assumption.\n      (* not *)\n      intros. decompose [and] (IHphi rho).\n      split. simpl. rewrite H0. split. intros. constructor. assumption.\n      inversion 1. assumption.\n      split. simpl. intros. constructor. apply H. apply NNPP. assumption.\n      intros. inversion H1. simpl. tauto.\n      (* forall *)\n      intros.\n      split. split.\n      simpl. intros. constructor. intro. apply IHphi. apply H.\n      simpl. intros. apply IHphi. inversion H. apply H2.\n      split. unfold SatisfiesF. fold SatisfiesF. unfold not. intros.\n      admit. admit.\nQed.\n*)\nRequire Import Classical.\n\nTheorem EM : forall (p : Prop), p \\/ ~ p.\n  intros.\n  tauto.\nQed.\n\nTheorem belea : forall D, forall P : D -> Prop,\n  ~(forall x : D, P x) <-> (exists x : D, ~ P x).\n  intros; split; intros.\n  \n  \nTheorem sameThing'' : forall (t : T) (rho : Valuation) (phi : Formula),\n  (Satisfies rho phi <-> SatI rho phi) /\\ (~ Satisfies rho phi <-> SatNI rho phi).\n  intros. generalize dependent rho.  generalize dependent t. induction phi.\n  intros; split; split.\n  (* equals *)\n  simpl. rewrite <- SatEquals. intros. constructor. assumption.\n  simpl. inversion 1. apply SatEquals. assumption.\n  simpl. rewrite <- SatEquals. intros. econstructor. assumption.\n  simpl. inversion 1. unfold not. rewrite <- SatEquals. intros. apply H2. assumption.\n  (* and *)\n  simpl; intros; split; split; decompose [and] (IHphi1 t rho); decompose [and] (IHphi2 t rho);\n  intros. rewrite <- SatAnd in H3. decompose [and] H3. constructor. apply H. assumption. apply H1. assumption. apply SatAnd. split. inversion H3. apply H. assumption. apply H1. inversion H3. assumption.\n  constructor. unfold not in H3. rewrite <- H0. rewrite <- H2. unfold not. rewrite <- SatAnd in H3.\n  tauto. unfold not. intros. rewrite <- SatAnd in H4. inversion H3. rewrite <- H0 in H7. rewrite <- H2 in H7. tauto.\n  (* not *)\n  simpl; intros; split; split; decompose [and] (IHphi t rho); intros.\n  rewrite <- SatNot in H1. constructor. tauto.\n  inversion H1. apply SatNot. tauto.\n  constructor. rewrite <- SatNot in H1. tauto.\n  rewrite <- SatNot. inversion H1. tauto.\n  (* forall *)\n  intro.\n  assert (forall rho : Valuation,\n          (Satisfies rho phi <-> SatI rho phi)).\n  apply IHphi.\n  apply t.\n  assert (forall rho : Valuation,\n          (~Satisfies rho phi <-> SatNI rho phi)).\n  apply IHphi.\n  apply t.\n  simpl; intros; split; split; intros.\n  constructor. rewrite <- SatForall in H1. intros. apply H. apply H1.\n  rewrite <- SatForall. inversion H1. intros. apply H. apply H4.\n  rewrite <- SatForall in H1.\n  apply SatNIForall with (t := t).\n  setoid_rewrite <- H.\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/fol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029117, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6701882015169384}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_extension.\n\nSection Euclid.\nContext `{Ax:euclidean_neutral_ruler_compass}.\nLemma lemma_interior5 : \n   forall A B C D a b c d, \n   BetS A B C -> BetS a b c -> Cong A B a b -> Cong B C b c -> Cong A D a d -> Cong C D c d ->\n   Cong B D b d.\nProof.\nintros.\nassert (neq B C) by (forward_using lemma_betweennotequal).\nassert (neq A C) by (forward_using lemma_betweennotequal).\nassert (~ eq C A).\n {\n intro.\n assert (eq A C) by (conclude lemma_equalitysymmetric).\n contradict.\n }\nlet Tf:=fresh in\nassert (Tf:exists M, (BetS C A M /\\ Cong A M B C)) by (conclude lemma_extension);destruct Tf as [M];spliter.\nassert (Cong A M M A) by (conclude cn_equalityreverse).\nassert (Cong M A A M) by (conclude lemma_congruencesymmetric).\nassert (Cong M A B C) by (conclude lemma_congruencetransitive).\nassert (neq b c) by (conclude axiom_nocollapse).\nassert (neq a c) by (forward_using lemma_betweennotequal).\nassert (~ eq c a).\n {\n intro.\n assert (eq a c) by (conclude lemma_equalitysymmetric).\n contradict.\n }\nlet Tf:=fresh in\nassert (Tf:exists m, (BetS c a m /\\ Cong a m b c)) by (conclude lemma_extension);destruct Tf as [m];spliter.\nassert (Cong m a a m) by (conclude cn_equalityreverse).\nassert (Cong m a b c) by (conclude lemma_congruencetransitive).\nassert (Cong b c m a) by (conclude lemma_congruencesymmetric).\nassert (Cong B C m a) by (conclude lemma_congruencetransitive).\nassert (Cong M A m a) by (conclude lemma_congruencetransitive).\nassert (Cong A C a c) by (conclude cn_sumofparts).\nassert (Cong c a C A) by (forward_using lemma_doublereverse).\nassert (Cong C A c a) by (conclude lemma_congruencesymmetric).\nassert (BetS C B A) by (conclude axiom_betweennesssymmetry).\nassert (BetS B A M) by (conclude lemma_3_6a).\nassert (BetS c b a) by (conclude axiom_betweennesssymmetry).\nassert (BetS b a m) by (conclude lemma_3_6a).\nassert (Cong A M a m) by (forward_using lemma_congruenceflip).\nassert (Cong D M d m) by (conclude axiom_5_line).\nassert (BetS m a b) by (conclude axiom_betweennesssymmetry).\nassert (BetS M A B) by (conclude axiom_betweennesssymmetry).\nassert (Cong M D m d) by (forward_using lemma_congruenceflip).\nassert (Cong D B d b) by (conclude axiom_5_line).\nassert (Cong B D b d) by (forward_using lemma_congruenceflip).\nclose.\nQed.\n\nEnd Euclid.\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_interior5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.670178149146558}}
{"text": "(*\nCopyright © 2006-2008 Russell O’Connor\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis proof and associated documentation files (the \"Proof\"), to deal in\nthe Proof without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Proof, and to permit persons to whom the Proof is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Proof.\n\nTHE PROOF IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE PROOF OR THE USE OR OTHER DEALINGS IN THE PROOF.\n*)\nSet Firstorder Depth 5.\n\nRequire Export CoRN.order.PartialOrder.\n\nLocal Open Scope po_scope.\n\n(**\n* SemiLattice\nA (meet) semi lattice augments a partial order with a greatest lower bound\noperator.\n*)\n\n(*Should I take a PartialOrder parameter, or just a type and an inequality relation? *)\nRecord is_SemiLattice (po : PartialOrder) (meet : po -> po -> po) : Prop :=\n{ sl_meet_lb_l : forall x y, meet x y <= x (*left lower bound*)\n; sl_meet_lb_r : forall x y, meet x y <= y (*right lower bound*)\n; sl_meet_glb : forall x y z, z <= x -> z <= y -> z <= meet x y (*greatest lower bound *)\n}.\n\nRecord SemiLattice : Type :=\n{ po :> PartialOrder\n; meet : po -> po -> po\n; sl_proof : is_SemiLattice po meet\n}.\n\n(* begin hide *)\nArguments meet [s].\n\nAdd Parametric Morphism (X:SemiLattice) : (@meet X) with signature (@st_eq X) ==> (@st_eq X) ==> (@st_eq X)  as meet_compat.\nProof.\n assert (forall x1 x2 : X, x1 == x2 -> forall x3 x4 : X, x3 == x4 -> meet x1 x3 <= meet x2 x4).\n  intros.\n  revert H H0; do 2 rewrite -> equiv_le_def; intros.\n  pose (le_trans X).\n  destruct (sl_proof X).\n  apply sl_meet_glb0; firstorder.\n intros.\n pose (Seq_sym X _ (po_st (po_proof X))).\n apply le_antisym; firstorder.\nQed.\n(* end hide *)\n\nSection Meet.\n\nVariable X : SemiLattice.\n\nDefinition makeSemiLattice po meet p1 p2 p3 :=\n@Build_SemiLattice po meet\n(@Build_is_SemiLattice po meet p1 p2 p3).\n\n(** The axioms and basic properties of a semi lattice *)\nLemma meet_lb_l : forall x y : X, meet x y <= x.\nProof (sl_meet_lb_l _ _ (sl_proof X)).\n\nLemma meet_lb_r : forall x y : X, meet x y <= y.\nProof (sl_meet_lb_r _ _ (sl_proof X)).\n\nLemma meet_glb : forall x y z : X, z <= x -> z <= y -> z <= meet x y.\nProof (sl_meet_glb _ _ (sl_proof X)).\n\n(** commutativity of meet *)\nLemma meet_comm : forall x y:X, meet x y == meet y x.\nProof.\n assert (forall x y : X, meet x y <= meet y x).\n  intros.\n  destruct X.\n  simpl in *.\n  firstorder.\n intros; apply le_antisym; firstorder.\nQed.\n\n(** associativity of meet *)\nLemma meet_assoc : forall x y z:X, meet x (meet y z) == meet (meet x y) z.\nProof.\n assert (forall x y z : X, meet x (meet y z) <= meet (meet x y) z).\n  intros.\n  apply meet_glb; [apply meet_glb|]; firstorder using meet_lb_l, meet_lb_r, le_trans.\n intros.\n apply le_antisym.\n  apply H.\n rewrite -> meet_comm.\n rewrite -> (meet_comm x (meet y z)).\n rewrite -> (meet_comm x y).\n rewrite -> (meet_comm y z).\n apply H.\nQed.\n\n(** idempotency of meet *)\nLemma meet_idem : forall x:X, meet x x == x.\nProof.\n intros.\n apply le_antisym; firstorder using meet_lb_l, meet_glb, le_refl.\nQed.\n\nLemma le_meet_l : forall x y : X, x <= y <-> meet x y == x.\nProof.\n intros.\n split; intros.\n  apply le_antisym.\n   apply meet_lb_l.\n  apply meet_glb.\n   apply le_refl.\n  assumption.\n rewrite <- H.\n apply meet_lb_r.\nQed.\n\nLemma le_meet_r : forall x y : X, y <= x <-> meet x y == y.\nProof.\n intros.\n rewrite -> meet_comm.\n apply le_meet_l.\nQed.\n\n(** monotonicity of meet *)\nLemma meet_monotone_r : forall a : X, monotone X (meet a).\nProof.\n intros.\n rewrite -> monotone_def.\n intros.\n revert H;rewrite -> le_meet_l, meet_comm; intro.\n rewrite <- H.\n rewrite -> meet_assoc.\n apply meet_lb_l.\nQed.\n\nLemma meet_monotone_l : forall a : X, monotone X (fun x => meet x a).\nProof.\n intros.\n assert (A:=meet_monotone_r a).\n revert A; do 2 rewrite -> monotone_def;intros.\n rewrite -> (meet_comm x), (meet_comm y);auto.\nQed.\n\nLemma meet_le_compat : forall w x y z : X, w<=y -> x<=z -> meet w x <= meet y z.\nProof.\n intros.\n apply le_trans with (y:=meet y x).\n  firstorder using meet_monotone_l, monotone_def.\n firstorder using meet_monotone_r, monotone_def.\nQed.\n\nEnd Meet.\n", "meta": {"author": "coq-community", "repo": "corn", "sha": "cfbf6b297643935f0fe7e22d2b14b462bf7e3095", "save_path": "github-repos/coq/coq-community-corn", "path": "github-repos/coq/coq-community-corn/corn-cfbf6b297643935f0fe7e22d2b14b462bf7e3095/order/SemiLattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789040926009, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.6700324705889822}}
{"text": "(*\n  Copyright 2022 ZhengPu Shi\n  This file is part of CoqMatrix. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : Matrix implemented with Function.\n  author    : ZhengPu Shi\n  date      : 2021.12\n *)\n\n\nRequire Export MatrixTheory.\nRequire Import Sequence NatFun.Matrix.\n\n\n(* ######################################################################### *)\n(** * Basic matrix theory implemented with NatFun *)\n\nModule BasicMatrixTheoryNF (E : ElementType) <: BasicMatrixTheory E.\n\n  (** Basic library *)\n  Export BasicConfig TupleExt SetoidListListExt HierarchySetoid.\n\n  (* ==================================== *)\n  (** ** Matrix element type *)\n  Export E.\n\n  Global Infix \"==\" := Aeq : A_scope.\n  Global Infix \"==\" := (eqlistA (eqlistA Aeq)) : dlist_scope.\n\n  Open Scope nat_scope.\n  Open Scope A_scope.\n  Open Scope mat_scope.\n\n  (* ==================================== *)\n  (** ** Matrix type and basic operations *)\n  \n  (** We define a _matrix_ as a simple function from two nats\n      (corresponding to a row and a column) to a value. \n      Note that, r and c are dummy parameters, it is designed to\n      represent shape of matrix. *)\n  Definition mat (r c : nat) := @mat A r c.\n\n  (* (** matrix equality *) *)\n  Definition meq {r c : nat} (m1 m2 : mat r c) : Prop := @meq A Aeq r c m1 m2.\n  Global Infix \"==\" := meq : mat_scope.\n\n  Lemma meq_equiv : forall {r c}, Equivalence (meq (r:=r) (c:=c)).\n  Proof. \n    intros. apply meq_equiv.\n  Qed.\n\n  Global Existing Instance meq_equiv.\n\n  (** Get n-th element of a matrix *)  \n  Definition mnth {r c} (m : mat r c) (ri ci : nat) := @mnth A r c m ri ci.\n  Notation \"m ! i ! j\" := (mnth m i j).\n\n  (** meq and mnth should satisfy this constraint *)\n  Lemma meq_iff_mnth : forall {r c : nat} (m1 m2 : mat r c),\n      m1 == m2 <-> (forall ri ci, ri < r -> ci < c -> (m1!ri!ci == m2!ri!ci)%A).\n  Proof.\n    intros. apply meq_iff_mnth.\n  Qed.\n  \n  (* ==================================== *)\n  (** ** Convert between list list and matrix *)\n\n  (** *** list list to mat *)\n  \n  Definition l2m {r c} (dl : list (list A)) : mat r c := @l2m A A0 r c dl.\n\n  (** l2m is a proper morphism *)\n  Lemma l2m_aeq_mor : forall r c, Proper (eqlistA (eqlistA Aeq) ==> meq) (@l2m r c).\n  Proof.\n    Admitted.\n\n  Global Existing Instance l2m_aeq_mor.\n  \n  Lemma l2m_inj : forall {r c} (d1 d2 : list (list A)),\n      length d1 = r -> width d1 c -> \n      length d2 = r -> width d2 c -> \n      ~(d1 == d2)%dlist -> ~(@l2m r c d1 == l2m d2).\n  Proof.\n    intros. apply l2m_inj; auto.\n  Qed.\n  \n  Lemma l2m_surj : forall {r c} (m : mat r c), \n      (exists d, l2m d == m).\n  Proof.\n    intros. apply l2m_surj.\n  Qed.\n\n  \n  (** *** mat to list list *)\n  Definition m2l {r c} (m : mat r c) : list (list A) := @m2l A r c m.\n\n  (** m2l is a proper morphism *)\n  Lemma m2l_aeq_mor : forall r c, Proper (meq ==> eqlistA (eqlistA Aeq)) (@m2l r c).\n  Proof.\n    Admitted.\n\n  Global Existing Instance m2l_aeq_mor.\n\n  Lemma m2l_length : forall {r c} (m : mat r c), length (m2l m) = r.\n  Proof.\n    intros. apply m2l_length.\n  Qed.\n\n  Global Hint Resolve m2l_length : mat.\n  \n  Lemma m2l_width : forall {r c} (m : mat r c), width (m2l m) c.\n  Proof.\n    intros. apply m2l_width.\n  Qed.\n\n  Global Hint Resolve m2l_width : mat.\n  \n  Lemma m2l_l2m_id : forall {r c} (dl : list (list A)) (H1 : length dl = r)\n                       (H2 : width dl c), (@m2l r c (l2m dl) == dl)%dlist.\n  Proof.\n    intros. apply m2l_l2m_id; auto.\n  Qed.\n  \n  Lemma l2m_m2l_id : forall {r c} (m : mat r c), l2m (m2l m) == m. \n  Proof.\n    intros. apply l2m_m2l_id; auto.\n  Qed.\n  \n  Lemma m2l_inj : forall {r c} (m1 m2 : mat r c),\n      ~(m1 == m2) -> ~(m2l m1 == m2l m2)%dlist.\n  Proof.\n    intros. apply (m2l_inj (A0:=A0)). easy.\n  Qed.\n  \n  Lemma m2l_surj : forall {r c} (d : list (list A)), \n      length d = r -> width d c -> \n      (exists m, @m2l r c m == d)%dlist.\n  Proof.\n    intros. apply (m2l_surj (A0:=A0)); auto.\n  Qed.\n  \n  (* ==================================== *)\n  (** ** Specific matrix *)\n\n  Definition mk_mat_1_1 (a11 : A) : mat 1 1 := mk_mat_1_1 (A0:=A0) a11.\n\n  Definition mk_mat_3_1 (a1 a2 a3 : A) : mat 3 1 := mk_mat_3_1 (A0:=A0) a1 a2 a3.\n\n  Definition mk_mat_4_1 (a1 a2 a3 a4 : A) : mat 4 1 :=\n    mk_mat_4_1 (A0:=A0) a1 a2 a3 a4.\n\n  Definition mk_mat_3_3 (a11 a12 a13 a21 a22 a23 a31 a32 a33 : A) : mat 3 3 \n    := mk_mat_3_3 (A0:=A0) a11 a12 a13 a21 a22 a23 a31 a32 a33.\n\n  Definition mk_mat_4_4 (a11 a12 a13 a14 a21 a22 a23 a24\n                           a31 a32 a33 a34 a41 a42 a43 a44 : A) : mat 4 4 \n    := mk_mat_4_4 (A0:=A0)\n         a11 a12 a13 a14 a21 a22 a23 a24\n         a31 a32 a33 a34 a41 a42 a43 a44.\n  \n  Definition mk_mat_2_2 (a11 a12 a21 a22 : A) : mat 2 2\n    := mk_mat_2_2 (A0:=A0) a11 a12 a21 a22.\n\n  (* ==================================== *)\n  (** ** Convert between tuples and matrix *)\n  \n  (** tuple_3x3 -> mat_3x3 *)\n  Definition t2m_3x3 (t : @T_3x3 A) : mat 3 3 := t2m_3x3 (A0:=A0) t.\n  \n  (** mat_3x3 -> tuple_3x3 *)\n  Definition m2t_3x3 (m : mat 3 3) : @T_3x3 A := m2t_3x3 m.\n  \n  (** m[0,0] : mat_1x1 -> A *)\n  Definition scalar_of_mat (m : mat 1 1) := m!0!0.\n\n  (* ==================================== *)\n  (** ** Matrix transposition *)\n  \n  Definition mtrans {r c} (m : mat r c): mat c r :=\n    @mtrans A r c m.\n  \n  Global Notation \"m \\T\" := (mtrans m) : mat_scope.\n  \n  Lemma mtrans_trans : forall {r c} (m : mat r c), mtrans (mtrans m) == m.\n  Proof.\n    intros. apply mtrans_trans.\n  Qed.\n  \n  (* ==================================== *)\n  (** ** Mapping of matrix *)\n\n  (** Mapping of a matrix *)\n  Definition mmap {r c} (f : A -> A) (m : mat r c) : mat r c := @mmap A r c f m.\n  \n  Definition mmap2 {r c} (f: A -> A -> A) (m1 m2: mat r c) : mat r c :=\n    @mmap2 A r c f m1 m2.\n  \n  Lemma mmap2_comm : forall {r c} (f : A -> A -> A)\n                       (f_comm : forall a b : A, (f a b == f b a)%A)\n                       (m1 m2 : mat r c), \n      mmap2 f m1 m2 == mmap2 f m2 m1.\n  Proof.\n    (* lma. (* this tactic is enough too. *) *)\n    intros. apply mmap2_comm. auto.\n  Qed.\n  \n  Lemma mmap2_assoc : forall {r c} (f : A -> A -> A)\n                        (f_assoc : forall a b c, (f (f a b) c == f a (f b c))%A)\n                        (m1 m2 m3 : mat r c), \n      mmap2 f (mmap2 f m1 m2) m3 == mmap2 f m1 (mmap2 f m2 m3).\n  Proof.\n    intros. apply mmap2_assoc. auto.\n  Qed.\n\n  (** Auto unfold these definitions *)\n  Global Hint Unfold meq mmap mmap2 : mat.\n\n  (** linear matrix arithmetic tactic for equation: split goal to every element *)\n  Global Ltac lma :=\n    autounfold with mat;\n    Matrix.lma.\n\nEnd BasicMatrixTheoryNF.\n\n\n(* ######################################################################### *)\n(** * Decidable matrix theory implemented with NatFun *)\n\nModule DecidableMatrixTheoryNF (E : DecidableElementType) <: DecidableMatrixTheory E.\n\n  (* Export E. *)\n  Include BasicMatrixTheoryNF E.\n\n  (** linear matrix arithmetic tactic for equation: split goal to every element *)\n\n  (** meq is decidable *)\n  Lemma meq_dec : forall {r c}, Decidable (meq (r:=r)(c:=c)).\n  Proof.\n    intros. apply @meq_dec. apply Dec_Aeq.\n  Qed.\n\nEnd DecidableMatrixTheoryNF.\n\n\n(* ######################################################################### *)\n(** * Ring matrix theory implemented with NatFun *)\n\nModule RingMatrixTheoryNF (E : RingElementType) <: RingMatrixTheory E.\n\n  (* Export E. *)\n  Include BasicMatrixTheoryNF E.\n\n  Add Ring ring_thy_inst : Ring_thy.\n\n  (** Zero matrix *)\n  Definition mat0 r c : mat r c := @mat0 A A0 r c.\n\n  (** Unit matrix *)\n  Definition mat1 n : mat n n := @mat1 A A0 A1 n.\n\n  (** *** Addition of matrix *)\n\n  (** Tips, we must write the full signature, especially the explicit parameter {r c} \n      and the return type {mat r c}, to maintain a type inference relation.\n      Because only {m1 m2 : mat r c} havn't any information of {r} and {c}.\n      Otherwise, the \"+\" notation will useless.\n   *)\n  Definition madd {r c} (m1 m2 : mat r c) : mat r c := @madd A Aadd r c m1 m2.\n  Infix \"+\" := madd : mat_scope.\n  \n  (** m1 + m2 = m2 + m1 *)\n  Lemma madd_comm : forall {r c} (m1 m2 : mat r c), m1 + m2 == m2 + m1.\n  Proof.\n    intros. apply madd_comm.\n  Qed.\n  \n  (** (m1 + m2) + m3 = m1 + (m2 + m3) *)\n  Lemma madd_assoc : forall {r c} (m1 m2 m3 : mat r c), (m1 + m2) + m3 == m1 + (m2 + m3).\n  Proof.\n    intros. apply madd_assoc.\n  Qed.\n  \n  (** 0 + m = m *)\n  Lemma madd_0_l : forall {r c} (m : mat r c), (mat0 r c) + m == m.\n  Proof.\n    intros. apply madd_0_l.\n  Qed.\n  \n  (** m + 0 = m *)\n  Lemma madd_0_r : forall {r c} (m : mat r c), m + (mat0 r c) == m.\n  Proof.\n    intros. apply madd_0_r.\n  Qed.\n  \n\n  (** *** Opposite of matrix *)\n  \n  Definition mopp {r c} (m : mat r c) : mat r c := @mopp A Aopp r c m.\n  Global Notation \"- m\" := (mopp m) : mat_scope.\n\n  (** - - m = m *)\n  Lemma mopp_opp : forall {r c} (m : mat r c), - - m == m.\n  Proof.\n    intros. apply mopp_opp.\n  Qed.\n\n  (** m + (-m) = 0 *)\n  Lemma madd_opp : forall {r c} (m : mat r c), m + (-m) == mat0 r c.\n  Proof.\n    intros. apply madd_opp.\n  Qed.\n  \n  \n  (** *** Subtraction of matrix *)\n\n  Definition msub {r c} (m1 m2 : mat r c) : mat r c := @msub A Aadd Aopp r c m1 m2.\n  Infix \"-\" := msub : mat_scope.\n\n  (** m1 - m2 = - (m2 - m1) *)\n  Lemma msub_comm : forall {r c} (m1 m2 : mat r c), m1 - m2 == - (m2 - m1).\n  Proof.\n    intros. apply msub_comm.\n  Qed.\n  (** (m1 - m2) - m3 = m1 - (m2 + m3) *)\n  Lemma msub_assoc : forall {r c} (m1 m2 m3 : mat r c), (m1 - m2) - m3 == m1 - (m2 + m3).\n  Proof.\n    intros. apply msub_assoc.\n  Qed.\n\n  (** 0 - m = - m *)\n  Lemma msub_0_l : forall {r c} (m : mat r c), (mat0 r c) - m == - m.\n  Proof.\n    intros. apply msub_0_l.\n  Qed.\n  \n  (** m - 0 = m *)\n  Lemma msub_0_r : forall {r c} (m : mat r c), m - (mat0 r c) == m.\n  Proof.\n    intros. apply msub_0_r.\n  Qed.\n  \n  (** m - m = 0 *)\n  Lemma msub_self : forall {r c} (m : mat r c), m - m == (mat0 r c).\n  Proof.\n    intros. apply msub_self.\n  Qed.\n\n  \n  (** *** Scalar multiplication of matrix *)\n  \n  (** Left scalar multiplication of matrix *)\n  Definition mcmul {r c} (a : A) (m : mat r c) : mat r c :=\n    @mcmul A Amul r c a m.\n  Notation \"a c* m\" := (mcmul a m) : mat_scope.\n\n  (** Right scalar multiplication of matrix *)\n  Definition mmulc {r c} (m : mat r c) (a : A) : mat r c :=\n    @mmulc A Amul r c m a.\n  Notation \"m *c a\" := (mmulc m a) : mat_scope.\n  \n  (** m *c a = a c* m *)\n  Lemma mmulc_eq_mcmul : forall {r c} (a : A) (m : mat r c), m *c a == a c* m.\n  Proof.\n    intros. apply mmulc_eq_mcmul.\n  Qed.\n  \n  (** a * (b * m) = (a * b) * m *)\n  Lemma mcmul_assoc : forall {r c} (a b : A) (m : mat r c), a c* (b c* m) == (a * b)%A c* m.\n  Proof.\n    intros. apply mcmul_assoc.\n  Qed.\n  \n  (** a * (b * m) = b * (a * m) *)\n  Lemma mcmul_perm : forall {r c} (a b : A) (m : mat r c), a c* (b c* m) == b c* (a c* m).\n  Proof.\n    intros. apply mcmul_perm.\n  Qed.\n  \n  (** a * (m1 + m2) = (a * m1) + (a * m2) *)\n  Lemma mcmul_add_distr_l : forall {r c} (a : A) (m1 m2 : mat r c),\n      a c* (m1 + m2) == (a c* m1) + (a c* m2).\n  Proof.\n    intros. apply mcmul_add_distr_l.\n  Qed.\n  \n  (** (a + b) * m = (a * m) + (b * m) *)\n  Lemma mcmul_add_distr_r : forall {r c} (a b : A) (m : mat r c),\n      (a + b)%A c* m == (a c* m) + (b c* m).\n  Proof.\n    intros. apply mcmul_add_distr_r.\n  Qed.\n  \n  (** 0 * m = 0 *)\n  Lemma mcmul_0_l : forall {r c} (m : mat r c), A0 c* m == mat0 r c.\n  Proof.\n    intros. apply mcmul_0_l.\n  Qed.\n  \n  (** 1 * m = m *)\n  Lemma mcmul_1_l : forall {r c} (m : mat r c), A1 c* m == m.\n  Proof.\n    intros. apply mcmul_1_l.\n  Qed.\n\n\n  (** *** Multiplication of matrix *)\n  \n  Definition mmul {r c s} (m1 : mat r c) (m2 : mat c s) : mat r s :=\n    @mmul A Aadd A0 Amul r c s m1 m2.\n\n  Global Infix \"*\" := mmul : mat_scope.\n  \n  (** m1 * (m2 + m3) = (m1 * m2) + (m1 * m3) *)\n  Lemma mmul_add_distr_l : forall {r c s} (m1 : mat r c) (m2 m3 : mat c s),\n      m1 * (@madd c s m2 m3) == @madd r s (m1 * m2) (m1 * m3).\n  Proof.\n    intros. apply mmul_add_distr_l.\n  Qed.\n  \n  (** (m1 + m2) * m3 = (m1 * m3) + (m2 * m3) *)\n  Lemma mmul_add_distr_r : forall {r c s} (m1 m2 : mat r c) (m3 : mat c s),\n      (@madd r c m1 m2) * m3 == @madd r s (m1 * m3) (m2 * m3).\n  Proof.\n    intros. apply mmul_add_distr_r.\n  Qed.\n  \n  (** (m1 * m2) * m3 = m1 * (m2 * m3) *)\n  Lemma mmul_assoc : forall {r c s t} (m1 : mat r c) (m2 : mat c s) (m3 : mat s t),\n      (m1 * m2) * m3 == m1 * (m2 * m3).\n  Proof.\n    intros. apply mmul_assoc.\n  Qed.\n  \n  (** mat0 * m = mat0 *)\n  Lemma mmul_0_l : forall {r c s} (m : mat c s), (mat0 r c) * m == mat0 r s.\n  Proof.\n    intros. apply mmul_0_l.\n  Qed.\n  \n  (** m * mat0 = mat0 *)\n  Lemma mmul_0_r : forall {r c s} (m : mat r c), m * (mat0 c s) == mat0 r s.\n  Proof.\n    intros. apply mmul_0_r.\n  Qed.\n  \n  (** mat1 * m = m *)\n  Lemma mmul_1_l : forall {r c} (m : mat r c), (mat1 r) * m == m.\n  Proof.\n    intros. apply mmul_1_l.\n  Qed.\n  \n  (** m * mat1 = m *)\n  Lemma mmul_1_r : forall {r c} (m : mat r c), m * (mat1 c) == m.\n  Proof.\n    intros. apply mmul_1_r.\n  Qed.\n  \n  (** Auto unfold these definitions *)\n  Global Hint Unfold madd mopp msub mcmul mmul : mat.\n\nEnd RingMatrixTheoryNF.\n\n\n(* ######################################################################### *)\n(** * Decidable Field matrix theory implemented with NatFun *)\n\nModule DecidableFieldMatrixTheoryNF (E : DecidableFieldElementType)\n<: DecidableFieldMatrixTheory E.\n\n  (* Export E. *)\n  Include RingMatrixTheoryNF E.\n  (* Module Export DecMT := DecidableMatrixTheoryNF E. *)\n\n  (** meq is decidable *)\n  Lemma meq_dec : forall (r c : nat), Decidable (meq (r:=r) (c:=c)).\n  Proof.\n    intros. apply meq_dec.\n  Qed.\n    \n  (** ** matrix theory *)\n  \nEnd DecidableFieldMatrixTheoryNF.\n\n\n(** Test *)\nModule Test.\n  (* Export QArith. *)\n  Module Export MatrixQ := RingMatrixTheoryNF RingElementTypeQ.\n  Open Scope Q.\n  Open Scope mat_scope.\n\n  Definition m3 := mk_mat_3_3 1 2 3 4 5 6 7 8 9.\n  (* Compute m2l (m3 + m3). *)\n  (* Compute m2l (m3 * m3). *)\n\nEnd Test.\n\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/NatFun/MatrixTheoryNF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.6700324688588273}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Export basics.\n\nSection enat.\n\nLtac G x := generalize x.\n\nLtac BAD := intros BAD; inversion BAD.\n\n(*\n * extended nat\n *)\nInductive inat :=\n | Fix : nat -> inat\n | Inf : inat\n.\n\nLemma not_inf_eq_fix x : (Inf = Fix x) <-> False.\nsplit; [BAD|tauto].\nQed.\n\nLemma eq_fix x y: (Fix x)=(Fix y) <-> x=y.\nsplit; auto.\nintros EQ; inversion EQ; auto.\nQed.\n\nLemma fix_eq_fix x y : (Fix x)=(Fix y) <-> (x=y).\nsplit; intros EQ; inversion EQ; auto.\nQed.\n\nLemma contra_inf x : ~(exists t, x=(Fix t)) -> x=Inf.\napply contra.\nrewrite not_not.\ncase x; [|intros BAD;exfalso; apply BAD; auto].\nintros n _; exists n; auto.\nQed.\n\n(* ilt *)\nDefinition ilt (x y : inat) : Prop := match x,y with\n | (Fix n),(Fix m) => n<m\n | (Fix n),Inf => True\n | Inf,_ => False\nend.\n\nLemma inat_compare x y : (ilt x y) \\/ (x=y) \\/ (ilt y x).\ncase x; case y; intros; simpl; auto.\nG (nat_compare n0 n); intros [LT|[EQ|GT]].\n- left; auto.\n- right; left; auto.\n- right; right; auto.\nQed.\n\nLemma ilt__0 (x:inat) : ~(ilt x (Fix 0)).\ncase x as [x|]; simpl; [auto with arith|auto].\nQed.\n\nLemma ilt_left_is_fix x y :  (ilt x y) -> (exists n, x=(Fix n)).\ncase x;[intros n _|BAD].\nexists n; auto.\nQed.\n\nLemma ilt__inf x : (ilt (Fix x) Inf).\nsimpl; auto.\nQed.\n\nLemma not_ilt_inf_left x : ~(ilt Inf x).\ncase x; auto.\nQed.\n\nLemma ilt_irrefl x : ~(ilt x x).\ncase x; [apply lt_irrefl|auto].\nQed.\n\nLemma ilt_asym x y : (ilt x y) -> (ilt y x) -> False.\ncase x as [x |]; case y as [y |]; simpl; auto.\napply lt_asym.\nQed.\n\nLemma lt_ilt x y : (x < y) -> (ilt (Fix x) (Fix y)).\nauto.\nQed.\n\nLemma lt_0ilt x y : (x < y) -> (ilt (Fix 0) (Fix y)).\nintros LT.\napply (lt_ilt (lt_0lt LT)).\nQed.\n\n(* ile *)\nDefinition ile (x y : inat) : Prop := (ilt x y) \\/ (x=y).\n\nLemma ile__not_ilt x y : (ile x y) <-> ~(ilt y x).\nunfold ile; case x as [x|]; case y as [y|]; simpl; auto; try tauto.\n- rewrite eq_fix, <- le_fix_def.\n  apply le__not_lt.\n- rewrite not_inf_eq_fix; tauto.\nQed.\n\nLemma ile0 (x:inat) : (ile (Fix 0) x).\ncase x as [n|]; [|left;simpl;auto].\ncase n; [right|left];simpl;[auto|auto with arith].\nQed.\n\nLemma ile_inf x : (ile x Inf).\nunfold ile.\ncase x as [|x];[left | right]; simpl; auto.\nQed.\n\nLemma ile_refl x : (ile x x).\nunfold ile; case x as [n|]; simpl; auto.\nQed.\n\nLemma ile_antisym x y : (ile x y) -> (ile y x) -> x=y.\nunfold ile.\nintros [LT1 | EQ1] [LT2|EQ2]; auto.\nexfalso; apply (ilt_asym LT1 LT2).\nQed.\n\nLemma eq_ile x y : (x=y) -> (ile x y).\nintros EQ; rewrite EQ; apply ile_refl.\nQed.\n\nLemma eq_ile2 x y : (y=x) -> (ile x y).\nintros EQ; rewrite EQ; apply ile_refl.\nQed.\n\nLemma ile_fix x y : (ile (Fix x) (Fix y)) <-> (x<=y).\nunfold ile. simpl. \nrewrite fix_eq_fix, le_fix_def; tauto.\nQed.\n\nLemma ilt_ile x y : (ilt x y) -> (ile x y).\nunfold ile; auto.\nQed.\n\nLemma ilt__not_ile x y : (ilt x y) <-> ~(ile y x).\nrewrite ile__not_ilt, not_not; tauto.\nQed.\n\nLemma not_ile_inf_left x : ~ (ile Inf (Fix x)).\nunfold ile.\nintros [LT|EQ]; auto.\ninversion EQ.\nQed.\n\nLemma diff_ile_ilt x y :\n (y<>x) ->\n (ile x y) ->\n (ilt x y).\nunfold ile. intros DI [LT|EQ]; [auto|exfalso]; auto.\nQed.\n\nLemma inat_compare_lt_le x y : (ilt x y) \\/ (ile y x).\nG (inat_compare x y);intros [LT|[EQ|GT]];\n[left|right;rewrite EQ;apply ile_refl|right;apply ilt_ile]; auto.\nQed.\n\nLemma ilt_ileS x y : (ilt (Fix x) y) -> (ile (Fix (S x)) y).\nunfold ile; case y as [y|]; simpl; auto.\nrewrite eq_fix.\nrewrite <- le_fix_def.\nauto with arith.\nQed.\n\nLemma ilt_succ (x:nat) (y:inat) : (ilt (Fix (S x)) y) -> (ilt (Fix x) y).\ncase y as [y|]; auto; simpl; auto with arith.\nQed.\n\nLemma ilt_trans  x y z : (ilt x y) -> (ilt y z) -> (ilt x z).\ncase x; case y; case z; simpl; auto; intros a b c.\n- apply lt_trans.\n- BAD.\nQed.\n\nLemma ile_trans x y z : (ile x y) -> (ile y z) -> (ile x z).\nunfold ile.\nintros [LT1 | EQ1] [LT2 | EQ2];[left|left|left|right].\n- apply (ilt_trans LT1 LT2).\n- rewrite <- EQ2; auto.\n- rewrite EQ1; auto.\n- rewrite EQ1; auto.\nQed.\n\nLemma ile_ilt_trans x y z : (ile x y) -> (ilt y z) -> (ilt x z).\nunfold ile.\nintros [LT | EQ].\n- apply ilt_trans; auto.\n- rewrite EQ; auto.\nQed.\n\nLemma le_ilt_trans x y z : (x <= y) -> (ilt (Fix y) z) -> (ilt (Fix x) z).\nunfold ilt.\ncase z; auto.\napply le_lt_trans.\nQed.\n\nLemma lt_ilt_trans x y z : (x<y) -> (ilt (Fix y) z) -> (ilt (Fix x) z).\ncase z as [z|]; [apply lt_trans | auto].\nQed.\n\nLemma le_ile_trans x y z : (le x y) -> (ile (Fix y) z) -> (ile (Fix x) z).\nunfold ile; rewrite le_fix_def.\nintros [LT1 | EQ1] [LT2 | EQ2];[left|left|left|right].\n- apply (lt_ilt_trans LT1 LT2).\n- rewrite <- EQ2; auto.\n- rewrite EQ1; auto.\n- rewrite EQ1; auto.\nQed.\n\nLemma ilt_ile_trans x y z : (ilt x y) -> (ile y z) -> (ilt x z).\nunfold ile.\nintros LT1 [LT | EQ].\n- apply (ilt_trans LT1 LT); auto.\n- rewrite <- EQ; auto.\nQed.\n\nLemma lt_iltS_trans x y z :\n(x < y) ->\n(y < z) ->\n(ilt (Fix (S x)) (Fix z)).\nsimpl.\nintros LT1 LT2.\napply (le_lt_trans (lt_leS LT1) LT2).\nQed.\n\n(* fiadd *)\nDefinition fiadd (x:nat) (y:inat) := match y with\n | (Fix y) => (Fix (x+y))\n | Inf => Inf\nend.\n\nEnd enat.\n", "meta": {"author": "NicVolanschi", "repo": "Allen", "sha": "daf340d71f26f7fd589b46125853407b89280160", "save_path": "github-repos/coq/NicVolanschi-Allen", "path": "github-repos/coq/NicVolanschi-Allen/Allen-daf340d71f26f7fd589b46125853407b89280160/proof/enat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.6700324657226642}}
{"text": "Definition T := nat.\n\nDefinition le := le.\n\nHint Unfold le.\n\nLemma le_refl : forall n : nat, le n n.\n  auto.\nQed.\n\nRequire Import Le.\n\nLemma le_trans : forall n m k : nat, le n m -> le m k -> le n k.\n   eauto with arith.\nQed.\n\nLemma le_antis : forall n m : nat, le n m -> le m n -> n = m.\n   eauto with arith.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/modules/Nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6699788770003566}}
{"text": "From Ordinal Require Import sflib Basics.\nFrom Ordinal Require Import ClassicalOrdinal WfRel.\nFrom Ordinal Require Export Ordinal.\n\nRequire Import FunctionalExtensionality PropExtensionality.\nRequire Import Program. (* Axiom K *)\n\nSet Implicit Arguments.\nSet Primitive Projections.\n\nModule ToSet.\n  Definition union_set (A: Type) (Ts: A -> Type): Type := @sigT A (fun a => option (Ts a)).\n\n  Inductive union_rel (A: Type)\n            (Ts: A -> Type) (R: forall a, Ts a -> Ts a -> Prop):\n    union_set Ts -> union_set Ts -> Prop :=\n  | union_rel_top\n      a x\n    :\n      union_rel R (existT _ a (Some x)) (existT _ a None)\n  | union_rel_normal\n      a x0 x1\n      (LT: R a x0 x1)\n    :\n      union_rel R (existT _ a (Some x0)) (existT _ a (Some x1))\n  .\n\n  (* TODO: axiom K necessary? *)\n  Lemma union_rel_well_founded (A: Type) (Ts: A -> Type)\n        (R: forall a, Ts a -> Ts a -> Prop)\n        (WF: forall a, well_founded (R a))\n    :\n      well_founded (union_rel R).\n  Proof.\n    assert (forall a x, Acc (union_rel R) (existT _ a (Some x))).\n    { intros a. eapply (well_founded_induction (WF a)); auto.\n      i. econs. i. dependent destruction H0. eapply H; eauto. }\n    ii. destruct a as [a [x|]]; eauto.\n    econs. i. inv H0; eauto.\n  Qed.\n\n  Lemma from_wf_union (A: Type) (Ts: A -> Type)\n        (R: forall a, Ts a -> Ts a -> Prop)\n        (WF: forall a, well_founded (R a))\n        (a: A) (x: Ts a)\n    :\n      Ord.eq (Ord.from_wf (WF a) x)\n             (Ord.from_wf (union_rel_well_founded R WF) (existT _ a (Some x))).\n  Proof.\n    revert x. eapply (well_founded_induction (WF a)).\n    i. split.\n    { eapply Ord.from_wf_supremum. i. specialize (H _ LT). inv H.\n      eapply Ord.le_lt_lt; eauto. eapply Ord.lt_from_wf. econs; eauto. }\n    { eapply Ord.from_wf_supremum. i. dependent destruction LT.\n      specialize (H _ LT). inv H.\n      eapply Ord.le_lt_lt; eauto. eapply Ord.lt_from_wf. auto. }\n  Qed.\n\n  Lemma from_wf_set_union (A: Type) (Ts: A -> Type)\n        (R: forall a, Ts a -> Ts a -> Prop)\n        (WF: forall a, well_founded (R a))\n    :\n      Ord.eq (@Ord.build A (fun a => Ord.from_wf_set (WF a)))\n             (Ord.from_wf_set (union_rel_well_founded R WF)).\n  Proof.\n    Local Transparent Ord.from_wf_set.\n    split.\n    { econs. i. exists (existT _ a0 None). eapply Ord.build_supremum. i.\n      eapply (@Ord.le_lt_lt (Ord.from_wf (union_rel_well_founded R WF) (existT _ a0 (Some a)))).\n      { eapply from_wf_union. }\n      { eapply Ord.lt_from_wf. econs. }\n    }\n    { econs. i. destruct a0 as [a0 [x|]].\n      { exists a0. transitivity (Ord.from_wf (WF a0) x).\n        { eapply from_wf_union. }\n        { eapply Ord.lt_le. eapply Ord.from_wf_set_upperbound. }\n      }\n      { exists a0. eapply Ord.from_wf_supremum. i.\n        dependent destruction LT.\n        eapply (@Ord.le_lt_lt (Ord.from_wf (WF a0) x)).\n        { eapply from_wf_union. }\n        { eapply Ord.from_wf_set_upperbound. }\n      }\n    }\n  Qed.\n\n  Fixpoint to_set (o: Ord.t): @sigT Type (fun A => A -> A -> Prop) :=\n    match o with\n    | @Ord.build A os => existT\n                           _\n                           (union_set (fun a => projT1 (to_set (os a))))\n                           (union_rel (fun a => projT2 (to_set (os a))))\n    end.\n\n  Lemma to_set_well_founded: forall o, well_founded (projT2 (to_set o)).\n  Proof.\n    induction o. ss. eapply union_rel_well_founded; auto.\n  Defined.\n\n  Lemma to_set_eq o:\n    Ord.eq o (Ord.from_wf_set (to_set_well_founded o)).\n  Proof.\n    induction o. etransitivity.\n    2: { eapply from_wf_set_union. }\n    split.\n    { econs. i. exists a0. eapply H. }\n    { econs. i. exists a0. eapply H. }\n  Qed.\n\n  Section TOTALIFY.\n    Variable A: Type.\n    Variable R: A -> A -> Prop.\n    Hypothesis WF: well_founded R.\n\n    Definition equiv_class: Type :=\n      @sig (A -> Prop) (fun s => (exists a, s a) /\\\n                                 (forall a0 a1 (IN0: s a0), s a1 <-> Ord.eq (Ord.from_wf WF a0) (Ord.from_wf WF a1))).\n\n    Lemma equiv_class_same_ord (s: equiv_class) (a0 a1: A)\n          (IN0: proj1_sig s a0) (IN1: proj1_sig s a1)\n      :\n        Ord.eq (Ord.from_wf WF a0) (Ord.from_wf WF a1).\n    Proof.\n      destruct s. ss. des. eapply a2; auto.\n    Qed.\n\n    Program Definition to_equiv_class (a0: A): equiv_class :=\n      exist _ (fun a1 => Ord.eq (Ord.from_wf WF a0) (Ord.from_wf WF a1)) _.\n    Next Obligation.\n      split.\n      { exists a0. reflexivity. }\n      { i. split; i.\n        - transitivity (Ord.from_wf WF a0); eauto. symmetry. auto.\n        - transitivity (Ord.from_wf WF a1); eauto.\n      }\n    Qed.\n\n    Let to_equiv_class_equiv a (s: equiv_class) (IN: proj1_sig s a):\n      s = to_equiv_class a.\n    Proof.\n      destruct s. ss. unfold to_equiv_class.\n      assert (x = (fun a1 : A => Ord.eq (Ord.from_wf WF a) (Ord.from_wf WF a1))).\n      { extensionality a1. eapply propositional_extensionality. des. split.\n        { i. eapply a2; eauto. }\n        { i. eapply a2; eauto. }\n      }\n      subst. f_equal. eapply proof_irrelevance.\n    Qed.\n\n    Definition equiv_class_rel: equiv_class -> equiv_class -> Prop :=\n      fun s0 s1 => exists a0 a1, (proj1_sig s0) a0 /\\ (proj1_sig s1) a1 /\\ Ord.lt (Ord.from_wf WF a0) (Ord.from_wf WF a1).\n\n    Lemma to_equiv_class_preserve a0 a1 (LT: R a0 a1):\n      equiv_class_rel (to_equiv_class a0) (to_equiv_class a1).\n    Proof.\n      exists a0, a1. ss. splits.\n      - reflexivity.\n      - reflexivity.\n      - eapply Ord.lt_from_wf; auto.\n    Qed.\n\n    Lemma equiv_class_rel_trans s0 s1 s2\n          (LT0: equiv_class_rel s0 s1) (LT1: equiv_class_rel s1 s2)\n      :\n        equiv_class_rel s0 s2.\n    Proof.\n      unfold equiv_class_rel in *. des. esplits; eauto.\n      transitivity (Ord.from_wf WF a3); auto.\n      eapply Ord.eq_lt_lt; eauto.\n      eapply equiv_class_same_ord; eauto.\n    Qed.\n\n    Let _equiv_class_extensional s0 s1\n          (EXT: forall s, equiv_class_rel s s0 <-> equiv_class_rel s s1)\n          a\n          (IN: proj1_sig s0 a)\n      :\n        proj1_sig s1 a.\n    Proof.\n      Local Transparent Ord.from_wf.\n      assert (exists a', proj1_sig s1 a').\n      { eapply (proj2_sig s1). }\n      des. eapply (proj2_sig s1); eauto.\n      eapply Ord.eq_ext. i. split.\n      { i. unfold Ord.from_wf in H0. destruct (WF a').\n        eapply Ord.lt_proj in H0. des. ss. destruct a1; ss.\n        hexploit to_equiv_class_preserve; eauto. i.\n        assert (equiv_class_rel (to_equiv_class x) s0).\n        { eapply EXT. replace s1 with (to_equiv_class a'); auto.\n          apply to_equiv_class_equiv in H. auto. }\n        unfold equiv_class_rel in H2. des. ss.\n        eapply Ord.lt_eq_lt.\n        { eapply (proj2_sig s0); eauto. }\n        eapply Ord.le_lt_lt; eauto.\n        eapply Ord.le_lt_lt; eauto.\n        eapply Ord.le_eq_le.\n        { symmetry. eauto. }\n        eapply Ord.same_acc_le.\n      }\n      { i. unfold Ord.from_wf in H0. destruct (WF a).\n        eapply Ord.lt_proj in H0. des. ss. destruct a1; ss.\n        hexploit to_equiv_class_preserve; eauto. i.\n        assert (equiv_class_rel (to_equiv_class x) s1).\n        { eapply EXT. replace s0 with (to_equiv_class a); auto.\n          apply to_equiv_class_equiv in IN. auto. }\n        unfold equiv_class_rel in H2. des. ss.\n        eapply Ord.lt_eq_lt.\n        { eapply (proj2_sig s1); eauto. }\n        eapply Ord.le_lt_lt; eauto.\n        eapply Ord.le_lt_lt; eauto.\n        eapply Ord.le_eq_le.\n        { symmetry. eauto. }\n        eapply Ord.same_acc_le.\n      }\n    Qed.\n\n    Lemma equiv_class_extensional s0 s1\n          (EXT: forall s, equiv_class_rel s s0 <-> equiv_class_rel s s1)\n      :\n        s0 = s1.\n    Proof.\n      assert (proj1_sig s0 = proj1_sig s1).\n      { extensionality a. eapply propositional_extensionality. split; i.\n        - eapply _equiv_class_extensional; eauto.\n        - eapply _equiv_class_extensional; eauto.\n          i. symmetry. auto.\n      }\n      destruct s0, s1. ss. subst. f_equal. eapply proof_irrelevance.\n    Qed.\n\n    Lemma equiv_class_well_founded: well_founded equiv_class_rel.\n    Proof.\n      assert (forall (o: Ord.t), forall (s: equiv_class) a0 (IN: proj1_sig s a0) (LT: Ord.lt (Ord.from_wf WF a0) o), Acc equiv_class_rel s).\n      { eapply (well_founded_induction Ord.lt_well_founded (fun o => forall (s: equiv_class) a0 (IN: proj1_sig s a0) (LT: Ord.lt (Ord.from_wf WF a0) o), Acc equiv_class_rel s)).\n        i. econs. i. unfold equiv_class_rel in H0. des.\n        hexploit (proj2 (proj2_sig s) a0 a2); auto. i. dup H1.\n        eapply H3 in H4. clear H3. eapply (H (Ord.from_wf WF a0)); eauto.\n        eapply Ord.lt_eq_lt; eauto.\n      }\n      ii. hexploit (proj2_sig a); eauto. i. des.\n      hexploit (H (Ord.S (Ord.from_wf WF a0))); eauto. eapply Ord.S_lt.\n    Qed.\n\n    Lemma to_equiv_class_eq a:\n      Ord.eq (Ord.from_wf WF a) (Ord.from_wf equiv_class_well_founded (to_equiv_class a)).\n    Proof.\n      assert (forall (o: Ord.t), forall a (LT: Ord.lt (Ord.from_wf WF a) o), Ord.eq (Ord.from_wf WF a) (Ord.from_wf equiv_class_well_founded (to_equiv_class a))).\n      { eapply (well_founded_induction Ord.lt_well_founded (fun o => forall a (LT: Ord.lt (Ord.from_wf WF a) o), Ord.eq (Ord.from_wf WF a) (Ord.from_wf equiv_class_well_founded (to_equiv_class a)))).\n        i. split.\n        { eapply Ord.from_wf_supremum. i. dup LT0. eapply (Ord.lt_from_wf WF) in LT0; eauto.\n          hexploit H; eauto. i. eapply Ord.le_lt_lt; [eapply H0|].\n          eapply Ord.lt_from_wf. eapply to_equiv_class_preserve. auto.\n        }\n        { eapply Ord.from_wf_supremum. i. unfold equiv_class_rel in LT0. des. ss.\n          hexploit (H _ LT a2).\n          { eapply Ord.lt_eq_lt; eauto. } i.\n          eapply Ord.lt_eq_lt; eauto. eapply Ord.le_lt_lt; eauto.\n          etransitivity; [|eapply H0].\n          eapply to_equiv_class_equiv in LT0. subst. reflexivity.\n        }\n      }\n      eapply (H (Ord.S (Ord.from_wf WF a))). eapply Ord.S_lt.\n    Qed.\n\n    Lemma from_wf_set_equiv_class:\n      Ord.eq (Ord.from_wf_set WF) (Ord.from_wf_set equiv_class_well_founded).\n    Proof.\n      split.\n      { eapply Ord.build_supremum. i. eapply Ord.eq_lt_lt.\n        { eapply to_equiv_class_eq. }\n        { eapply Ord.from_wf_set_upperbound. }\n      }\n      { eapply Ord.build_supremum. i. hexploit (proj2_sig a). i. des.\n        eapply to_equiv_class_equiv in H. subst.\n        eapply Ord.eq_lt_lt.\n        { symmetry. eapply to_equiv_class_eq. }\n        { eapply Ord.from_wf_set_upperbound. }\n      }\n    Qed.\n\n    Lemma equiv_class_total:\n      forall s0 s1, equiv_class_rel s0 s1 \\/ s0 = s1 \\/ equiv_class_rel s1 s0.\n    Proof.\n      i. hexploit (proj2_sig s0). i. des. hexploit (proj2_sig s1). i. des.\n      destruct (ClassicOrd.trichotomy (Ord.from_wf WF a) (Ord.from_wf WF a0)) as [|[]].\n      - left. unfold equiv_class_rel. esplits; eauto.\n      - right. left. assert (proj1_sig s0 = proj1_sig s1).\n        { extensionality x. eapply propositional_extensionality. split; i.\n          - eapply H2; eauto. transitivity (Ord.from_wf WF a); eauto.\n            + symmetry. auto.\n            + eapply (H0 a x); auto.\n          - eapply H0; eauto. transitivity (Ord.from_wf WF a0); eauto.\n            eapply (H2 a0 x); auto.\n        }\n        destruct s0, s1. ss. subst. f_equal. eapply proof_irrelevance.\n      - right. right. unfold equiv_class_rel. esplits; eauto.\n    Qed.\n  End TOTALIFY.\n\n  Definition to_total_set (o: Ord.t): Type := equiv_class (to_set_well_founded o).\n  Definition to_total_rel (o: Ord.t): (to_total_set o) -> (to_total_set o) -> Prop :=\n    @equiv_class_rel _ _ (to_set_well_founded o).\n  Arguments to_total_rel: clear implicits.\n\n  Lemma to_total_well_founded (o: Ord.t): well_founded (to_total_rel o).\n  Proof.\n    eapply equiv_class_well_founded.\n  Defined.\n  Arguments to_total_well_founded: clear implicits.\n\n  Lemma to_total_eq (o: Ord.t):\n    Ord.eq o (Ord.from_wf_set (@to_total_well_founded o)).\n  Proof.\n    etransitivity.\n    - eapply to_set_eq.\n    - eapply (from_wf_set_equiv_class (@to_set_well_founded o)).\n  Qed.\n\n  Lemma to_total_total (o: Ord.t):\n    forall (x0 x1: to_total_set o), to_total_rel o x0 x1 \\/ x0 = x1 \\/ to_total_rel o x1 x0.\n  Proof.\n    eapply equiv_class_total.\n  Qed.\n\n  Lemma to_total_exists (o: Ord.t):\n    exists (A: Type) (R: A -> A -> Prop) (WF: well_founded R),\n      Ord.eq o (Ord.from_wf_set WF) /\\\n      (forall a0 a1, R a0 a1 \\/ a0 = a1 \\/ R a1 a0).\n  Proof.\n    eexists _, _, (to_total_well_founded o). splits.\n    { eapply to_total_eq. }\n    { eapply to_total_total. }\n  Qed.\nEnd ToSet.\n", "meta": {"author": "minkiminki", "repo": "Ordinal", "sha": "225f2f2b18ec8d65a637d964839528eeeb1829ce", "save_path": "github-repos/coq/minkiminki-Ordinal", "path": "github-repos/coq/minkiminki-Ordinal/Ordinal-225f2f2b18ec8d65a637d964839528eeeb1829ce/src/ToSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6699788698788472}}
{"text": "From algebra Require Import preamble semigroup.\nFrom HB Require Import structures.\nFrom Coq Require Import ZArith.\n\nHB.mixin Record semigroup_is_monoid M of is_semigroup M :=\n  { zero  : M;\n    add0r : left_id zero add;\n    addr0 : right_id zero add }.\n\nHB.factory Record is_monoid M :=\n  { zero  : M;\n    add   : M -> M -> M;\n    addrA : associative add;\n    add0r : left_id zero add;\n    addr0 : right_id zero add }.\n\nHB.builders Context (M : Type) of is_monoid M.\n  HB.instance Definition _ := is_semigroup.Build M add addrA.\n  HB.instance Definition _ := semigroup_is_monoid.Build M zero add0r addr0.\nHB.end.\n\nHB.structure Definition Monoid := { M of is_monoid M }.\n\nHB.mixin Record subsemigroup_is_submonoid (M : Monoid.type) S of Subsemigroup M S :=\n  { has_zero : S zero }.\n\nHB.structure Definition Submonoid (M : Monoid.type) := {S of subsemigroup_is_submonoid M S &}.\n\nSection Submonoid.\n  Context (M : Monoid.type) (S : Submonoid.type M).\n\n  Definition zero' : {x : M | S x}.\n  Proof. by esplit; apply: has_zero. Defined.\n\n  Fact add0r' : left_id zero' add.\n  Proof.\n    move=> u; apply: sigE=> //=.\n    by rewrite add0r.\n  Qed.\n\n  Fact addr0' : right_id zero' add.\n  Proof.\n    move=> u; apply: sigE=> //=.\n    by rewrite addr0.\n  Qed.\n\n  HB.instance Definition _ := semigroup_is_monoid.Build {x : M | S x} zero' add0r' addr0'.\nEnd Submonoid.\n\nHB.instance Definition _ := semigroup_is_monoid.Build Z 0%Z  Z.add_0_l Z.add_0_r.\n", "meta": {"author": "jonsterling", "repo": "coq-algebra", "sha": "3a755dbc58d1c1b20281084b5bdb0027122dba9e", "save_path": "github-repos/coq/jonsterling-coq-algebra", "path": "github-repos/coq/jonsterling-coq-algebra/coq-algebra-3a755dbc58d1c1b20281084b5bdb0027122dba9e/theories/monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6699392946454582}}
{"text": "(*\n  This file proves that the width used by the\n  rem register in Hausner's implementation if\n  large enough to store any intermediate value\n  that may result while computing the square\n  root of a floating point binary number having\n  an even exponent.\n*)\n\nRequire Import base.\nRequire Import aux.\nRequire Import Reals.\nRequire Import micromega.Lra.\n\nOpen Scope R_scope.\n\nAxiom lt_sqrt_div_3_2 : sqrt 2 < 3 / 2.\n\n(**\n  Represents the mantissa of the number that we\n  are computing the square root of.\n*)\nParameter a : R.\n\n(**\n  We require that [a] correspond to a binary\n  floating point number of the form 1.b1b2...bn,\n  where bi represents an arbitrary bit. For\n  example: 1.01011.\n\n  Accordingly, the smallest possible value\n  that [a] can represent is 1. The largest is\n  infinitesimally less than 2.\n*)\nAxiom a_lower_bound : 1 <= a. \nAxiom a_upper_bound : a < 2.\n\n(**\n  Accepts a natural number, [n], and returns the\n  value of the n-th bit in our approximation of\n  the square root of [a].\n*)\nParameter b : nat -> R.\n\n(** Asserts that b returns a binary value. *)\nAxiom b_is_bit : forall n : nat, {b n = 0}+{b n = 1}.\n\n(**\n  Accepts a natural number, [n], and returns our\n  n-th approximation of the square root of [a].\n*)\nParameter approx : nat -> R.\n\n(**\n  Asserts that our initial approximation of the\n  square root of [a] is 0.\n*)\nAxiom approx_0 : approx 0 = 0.\n\n(**\n  Asserts that we generate the n-th approximation\n  by appending the n-th bit onto our previous\n  approximation.\n*)\nAxiom approx_Sn : forall n : nat, approx (S n) = approx n + (b n)/(2^n).\n\n(**\n  Accepts a natural number, [n], and returns\n  the difference between [a] and the square of\n  our n-th approximation.\n*)\nParameter error : nat -> R.\n\n(** Asserts that the error is always positive. *)\nAxiom error_is_positive : forall n : nat, 0 <= error (n).\n\n(**\n  Asserts the relationship between [a], our\n  approximation for the square root of [a],\n  and the discrepancy between the square of our\n  approximation and [a].\n*)\nAxiom spec : forall n : nat, a = (approx n)^2 + error n.\n\n(**\n  Proves that the discrepancy between the square\n  of our initial approximation and [a] equals\n  [a].\n*)\nLemma error_0\n  :  error 0 = a.\nProof.\n  exact\n    (eq_sym\n      (spec 0\n        || a = (X)^2 + error 0 @X by <- approx_0\n        || a = X + error 0 @X by <- Rmult_0_l (0 * 1)\n        || a = X @X by <- Rplus_0_l (error 0))).\nQed.\n \n(**\n  Represents [error] in terms of [a] and\n  [approx].\n*)\nLemma error_n \n  :  forall n : nat, a - (approx n)^2 = error n.\nProof.\n  exact\n    (fun n\n      => Rplus_eq_compat_r (- (approx n)^2) a ((approx n)^2 + (error n)) (spec n)\n           || a - (approx n)^2 = X                @X by <- Rplus_assoc ((approx n)^2) (error n) (- (approx n)^2)\n           || a - (approx n)^2 = (approx n)^2 + X @X by <- Rplus_comm (error n) (- (approx n)^2)\n           || a - (approx n)^2 = X                @X by Rplus_assoc ((approx n)^2) (- (approx n)^2) (error n)\n           || a - (approx n)^2 = X + error n      @X by <- Rplus_opp_r ((approx n)^2)\n           || a - (approx n)^2 = X                @X by <- Rplus_0_l (error n)).\nQed.\n\n(**\n  Provides an algebraic expansion for [error].\n*)\nLemma error_Sn\n  :  forall n : nat, error (S n) = error n - (b n)/(2^n) * (2 * approx n + (b n)/(2^n)).\nProof.\n  exact\n    (fun n =>\n      eq_sym (error_n (S n))\n      || error (S n) = a - X^2 @X by <- approx_Sn n\n      || _ = a - (approx n + b n/2^n) * X @X by <- Rmult_1_r (approx n + b n/2^n)\n      || _ = _ - X @X by <- Rmult_plus_distr_r (approx n) ((b n)/(2^n)) (approx n + b n/2^n)\n      || _ = _ - (X + _) @X by <- Rmult_plus_distr_l (approx n) (approx n) (b n/2^n)\n      || _ = _ - (_ + X) @X by <- Rmult_plus_distr_l (b n/2^n) (approx n) (b n/2^n)\n      || _ = _ - ((X + _) + _) @X by pow2 (approx n)\n      || _ = _ - X @X by Rplus_assoc ((approx n)^2 + approx n * (b n/2^n)) (b n/2^n * approx n) ((b n/2^n) * (b n/2^n))\n      || _ = _ - (X + _) @X by <- Rplus_assoc ((approx n)^2) (approx n * (b n/2^n)) (b n/2^n * approx n)\n      || _ = _ - (_ + (_ + X) + _) @X by <- Rmult_comm (b n/2^n) (approx n)\n      || _ = _ - (_ + X + _) @X by double (approx n * (b n/2^n))\n      || _ = _ - X @X by <- Rplus_assoc ((approx n)^2) (2 * ((approx n) * (b n/2^n))) ((b n/2^n)*(b n/2^n))\n      || _ = _ + X @X by <- Ropp_plus_distr ((approx n)^2) (2 * (approx n * (b n/2^n)) + (b n/2^n)*(b n/2^n))\n      || _ = X @X by Rplus_assoc a (- (approx n)^2) (- (2*(approx n * (b n/2^n)) + (b n/2^n)*(b n/2^n)))\n      || _ = X + _ @X by <- error_n n\n      || _ = _ - (X + _) @X by Rmult_assoc 2 (approx n) (b n/2^n)\n      || _ = _ - X @X by Rmult_plus_distr_r (2 * (approx n)) (b n/2^n) (b n/2^n)\n      || _ = _ - X @X by <- Rmult_comm (2 * approx n + b n/2^n) (b n/2^n)).\nQed.\n\n(*\n  In each iteration [n], we try to append a 1\n  bit onto [approx]. If the result is larger than\n  [a], we append a 0 instead.\n*)\nAxiom bn : forall n : nat, (approx n + 1/2^n)^2 > a <-> b n = 0.\n\n(*\n  Asserts bounds for [error] and [approx] based\n  on the value of a given bit.\n\n  a < (approx (n) + 1/2^n)^2\n  approx (n)^2 + error (n) < (apporx (n) + 1/2^n)^2\n  approx (n)^2 + error (n) < approx (n)^2 + 1/2^n (2 approx (n) + 1/2^n)\n  error (n) < approx (n)^2 + 1/2^n (2 approx (n) + 1/2^n)\n*)\nLemma b_0 : forall n : nat, b n = 0 -> error n < 1/2^n * (2 * approx n + 1/2^n).\nProof.\n  exact\n    (fun n H =>\n      Rplus_lt_compat_l\n        (- (approx n)^2)\n        ((approx n)^2 + error n)\n        ((approx n)^2 + (1/2^n * (2 * approx n + 1/2^n)))\n        (Rgt_lt _ _ (proj2 (bn n) H)\n          || X < (approx n + 1/2^n)^2 @X by <- spec n\n          || _ < X @X by <- sqr_expand (approx n) (1/2^n))\n      || X < _ @X by Rplus_assoc (- (approx n)^2) ((approx n)^2) (error n)\n      || _ < X @X by Rplus_assoc (- (approx n)^2) ((approx n)^2) (1/2^n * (2 * approx n + 1/2^n))\n      || X + _ < _ @X by <- Rplus_opp_l ((approx n)^2)\n      || X < _ @X by <- Rplus_0_l (error n)\n      || _ < X + _ @X by <- Rplus_opp_l ((approx n)^2)\n      || _ < X @X by <- Rplus_0_l _).\nQed.\n\n(*\n  0 <= error (n + 1)\n  0 <= error (n) + b (n)/2^n (2 approx (n) + b (n)/2^n)\n  b (n)/2^n (2 approx (n) + b (n)/2^n) <= error (n)\n*)\nLemma b_1 : forall n : nat, b n = 1 -> 1/2^n * (2 * approx n + 1/2^n) <= error n.\nProof.\n  exact\n    (fun n H =>\n      Rplus_le_compat_r\n        (b n/2^n * (2 * approx n + b n/2^n)) 0\n        (error n - b n/2^n * (2 * approx n + b n/2^n))\n        (error_is_positive (S n)\n         || 0 <= X @X by <- error_Sn n)\n      || X <= _ @X by <- Rplus_0_l (b n/2^n * (2 * approx n + b n/2^n))\n      || _ <= X @X by <-\n        Rplus_assoc (error n)\n          (- (b n/2^n * (2 * approx n + b n/2^n)))\n          (b n/2^n * (2 * approx n + b n/2^n))\n      || _ <= _ + X @X by <- Rplus_opp_l (b n / 2 ^ n * (2 * approx n + b n / 2 ^ n))\n      || _ <= X @X by <- Rplus_0_r (error n)\n      || X @X by ltac:(rewrite H; reflexivity)).\nQed.\n\n(*\n  Proves that every bit is greater than or equal\n  to 0.\n*)\nLemma b_lower_bound\n  :  forall n : nat, 0 <= b n.\nProof.\n  exact\n    (fun n\n      => sumbool_ind\n           (fun _ => 0 <= b n)\n           (fun H : b n = 0\n             => Req_le_sym 0 (b n) H)\n           (fun H : b n = 1\n             => Rle_0_1 || 0 <= X @X by H)\n           (b_is_bit n)).\nQed.\n\n(**\n  Proves that [approx] is always positive.\n*)\nLemma approx_is_positive\n  :  forall n : nat, 0 <= approx n.\nProof.\n  induction n as [|m H].\n  + exact (Req_le_sym 0 (approx 0) approx_0).\n  + rewrite (approx_Sn m).\n    apply (Rle_trans 0 (approx m + 0) (approx m + (b m)/(2^m))).\n    - rewrite (Rplus_0_r (approx m)); assumption.\n    - apply (Rplus_le_compat_l (approx m) 0 ((b m)/(2^m))).\n      rewrite <- (Rmult_0_l (/2^m)).\n      apply (Rmult_le_compat_r (/2^m) 0 (b m)).\n      * exact (Rlt_le 0 (/(2^m)) (Rinv_0_lt_compat (2^m) (pow_lt 2 m Rlt_0_2))).\n      * exact (b_lower_bound m).\nQed.\n\n(**\n  Expresses the square of [approx] in terms of\n  [a] and [error].\n*)\nLemma approx_n_sqr\n  :  forall n : nat, a - error n = (approx n)^2.\nProof.\n  exact\n    (fun n\n      => Rplus_eq_compat_r (- error n) a ((approx n)^2 + error n) (spec n)\n           || a - error n = X                @X by <- Rplus_assoc ((approx n)^2) (error n) (- (error n))\n           || a - error n = (approx n)^2 + X @X by <- Rplus_opp_r (error n)\n           || a - error n = X                @X by <- Rplus_0_r ((approx n)^2)).\nQed.\n\n(**\n  Represents the [approx] in terms of [a] and\n  [error].\n*)\nLemma approx_n\n  :  forall n : nat, sqrt (a - error n) = approx n.\nProof.\n  exact\n    (fun n\n      => f_equal sqrt (approx_n_sqr n)\n           || sqrt (a - error n) = X @X by <- sqrt_pow2 (approx n) (approx_is_positive n)).\nQed.\n\nLemma approx_sqr_is_positive_alt\n  :  forall n : nat, 0 <= a - error n.\nProof.\n  exact\n    (fun n\n      => pow_le (approx n) 2 (approx_is_positive n)\n           || 0 <= X @X by approx_n_sqr n).\nQed.\n\nLemma approx_sqr_is_positive : forall n : nat, 0 <= (approx n)^2.\nProof.\n  intro n.\n  apply (pow_le (approx n) 2 (approx_is_positive n)).\nQed.\n\nLemma error_upper_bound_a : forall n : nat, error n <= a.\nProof.\n  intro n.\n  apply (le_eq ((approx n)^2) (error n) a (approx_sqr_is_positive n)).\n  exact (eq_sym (spec n)).\nQed.\n\n(**\n  Asserts a weak constant upper bound for\n  [approx].\n\n  approx n = sqrt(a - error n) < sqrt(2)\n*)\nLemma approx_upper_bound\n  :  forall n : nat, approx n < sqrt 2.\nProof.\n  intro n.\n  rewrite <- (sqrt_square (approx n) (approx_is_positive n)).\n  rewrite <- (pow2 (approx n)).\n  apply (sqrt_lt_1_alt ((approx n)^2) 2).\n  split.\n  + exact (approx_sqr_is_positive n).\n  + refine (Rle_lt_trans ((approx n)^2) a 2 _ a_upper_bound).\n    apply (le_eq_comm ((approx n)^2) (error n) a (error_is_positive n) (eq_sym (spec n))).\nQed.\n\nLemma a_upper_bound_0\n  : forall n : nat, approx n + 1/2^n + 1/2^n = approx n + 2/2^n.\nProof.\n  intro n.\n  rewrite (Rplus_assoc (approx n) (1/2^n) (1/2^n)).\n  unfold Rdiv.\n  rewrite <- (Rmult_plus_distr_r 1 1 (/2^n)).\n  reflexivity.\nQed.\n\nLemma a_upper_bound_1\n  : forall n : nat, 2/2^(S n) = 1/2^n.\nProof.\n  intro n.\n  simpl.\n  unfold Rdiv.\n  rewrite (Rinv_mult_distr 2 (2^n) neq_2_0 (pow_nonzero 2 n neq_2_0)).\n  rewrite <- (Rmult_assoc 2 (/2) (/2^n)).\n  rewrite (Rinv_r_simpl_r 2 (/2^n) neq_2_0).\n  exact (eq_sym (Rmult_1_l (/2^n))).\nQed.\n\nLemma b_is_positive : forall n : nat, 0 <= b n.\nProof.\n  intro n.\n  destruct (b_is_bit n) as [H|H]; rewrite H.\n  + exact (Rle_refl 0).  \n  + exact Rle_0_1.\nQed.\n\n(* Proves that [approx] is monotonically increasing. *)\nLemma approx_inc : forall n : nat, approx n <= approx (S n).\nProof.\n  intro n.\n  exact\n    (le_eq_comm (approx n) (b n/2^n) (approx (S n))\n      (Rle_mult_inv_pos (b n) (2^n) (b_is_positive n) (pow_lt 2 n Rlt_0_2))\n      (eq_sym (approx_Sn n))).\nQed.\n\n(*\n  (approx n + 1/2^n)^2 <= (approx (S n) + 1/2^n)^2\n                       <= (approx n + b n/2^n + 1/2^n)^2\n  b n = 0\n                       <= (approx n + 1/2^n)^2\n                       reflexivity\n  b n = 1\n                       <= (approx n + 1/2^n + 1/2^n)^2\n                       trivial \n*)\nLemma a_upper_bound_2\n  : forall n : nat, (approx n + 1/2^n)^2 <= (approx (S n) + 2/2^(S n))^2.\nProof.\n  intro n.\n  rewrite (a_upper_bound_1 n).\n  rewrite (approx_Sn n).\n  destruct (b_is_bit n) as [H|H]; rewrite H.\n  + unfold Rdiv; rewrite (Rmult_0_l (/2^n)); rewrite (Rplus_0_r (approx n));\n    exact (Rle_refl ((approx n + 1/2^n)^2)).\n  + rewrite (a_upper_bound_0 n).\n    apply (pow_incr (approx n + 1/2^n) (approx n + 2/2^n) 2).\n    split.\n    - apply (Rplus_le_le_0_compat (approx n) (1/2^n)).\n      * exact (approx_is_positive n).\n      * exact (Rle_mult_inv_pos 1 (2^n) Rle_0_1 (pow_lt 2 n Rlt_0_2)).\n    - apply (Rplus_le_compat_l (approx n) (1/2^n) (2/2^n)).\n      unfold Rdiv.\n      apply (Rmult_le_compat_r (/2^n) 1 2).\n      * rewrite <- (Rmult_1_l (/2^n)).\n        exact (Rle_mult_inv_pos 1 (2^n) Rle_0_1 (pow_lt 2 n Rlt_0_2)).\n      * exact (le_1_2).\nQed.\n\nTheorem a_upper_bound_approx\n  :  forall n : nat, a < (approx n + 2/2^n)^2.\nProof.\n  exact\n    (nat_ind _\n      ((Rlt_trans a 2 4\n        a_upper_bound\n        (ltac:(lra)))\n        || a < X @X by (ltac:(field) : (0 + 2/2^0)^2 = 4)\n        || a < (X + 2/2^0)^2 @X by approx_0)\n      (fun n (H : a < (approx n + 2/2^n)^2)\n        => sumbool_ind\n             (fun _ => a < (approx (S n) + 2/2^(S n))^2)\n             (fun H0 : b n = 0\n               => Rlt_le_trans a\n                    ((approx n + 1/2^n)^2)\n                    ((approx (S n) + 2/2^(S n))^2)\n                    (Rle_lt_trans a\n                      ((approx n)^2 + error n)\n                      ((approx n)^2 + 1/2^n*(2*approx (n) + 1/2^n))\n                      (Req_le a\n                        ((approx n)^2 + error n)\n                        (spec n))\n                      (Rplus_lt_compat_l\n                        ((approx n)^2)\n                        (error n)\n                        (1/2^n*(2*approx (n) + 1/2^n))\n                        (b_0 n H0))\n                      || a < X @X by (ltac:(ring) : ((approx (n) + 1/2^n)^2) = (approx (n)^2 + 1/2^n*(2*approx (n) + 1/2^n))))\n                    (a_upper_bound_2 n))\n             (fun H0 : b n = 1\n               => let H1\n                    :  approx (S n) = approx n + 1/2^n\n                    := approx_Sn n\n                         || approx (S n) = approx n + (X/2^n) @X by <- H0 in\n                  H\n                  || a < X^2 @X by a_upper_bound_0 n\n                  || a < (X + 1/2^n)^2 @X by H1\n                  || a < (approx (S n) + X)^2 @X by a_upper_bound_1 n)\n             (b_is_bit n))).\nQed.\n\nLemma error_Sn_plus\n  :  forall n : nat, error (S n) + (b n/2^n) * (2 * approx n + (b n/2^n)) = error n.\nProof.\n  intro n.\n  rewrite (error_Sn n).\n  unfold Rminus.\n  rewrite\n    (Rplus_assoc\n      (error n)\n      (- ((b n/2^n) * (2 * approx n + (b n/2^n))))\n         ((b n/2^n) * (2 * approx n + (b n/2^n)))).\n  rewrite (Rplus_opp_l ((b n/2^n) * (2 * approx n + (b n/2^n)))).\n  exact (Rplus_0_r (error n)).\nQed.\n\nLemma error_upper_bound_const_0\n  : forall n : nat, - ((b n)/(2^n) * (2 * approx n + (b n)/(2^n))) <= 0.\nProof.\n  intro n.\n  apply (Rle_minus_0 ((b n/2^n) * (2 * approx n + (b n/2^n)))).\n  destruct (b_is_bit n) as [H|H]; rewrite H; unfold Rdiv.\n  + rewrite (Rmult_0_l (/2^n)).\n    rewrite (Rmult_0_l (2 * approx n + 0)).\n    exact (Rle_refl 0).\n  + rewrite (Rmult_1_l (/2^n)).\n    apply (Rmult_le_pos (/2^n) (2 * approx n + /2^n) (Rle_inv_2n n)).\n    refine (Rplus_le_le_0_compat (2 * approx n) (/2^n) _ (Rle_inv_2n n)).\n    exact (Rmult_le_pos 2 (approx n) le_0_2 (approx_is_positive n)).\nQed.\n\n(** Proves that [error] is always less than 4. *)\nTheorem error_upper_bound_const\n  :  forall n : nat, error n < 4.\nProof.\n  exact\n    (nat_ind _\n      (Rlt_trans\n        (error 0) 2 4\n        (a_upper_bound\n          || X < 2 @X by error_0)\n        (ltac:(lra) : 2 < 4))\n      (fun n (H : error n < 4)\n        => Rlt_le_trans\n             (error (S n))\n             (4 - ((b n)/(2^n) * (2 * approx n + (b n)/(2^n))))\n             (4 + 0)\n             ((Rplus_lt_compat_r\n               (- ((b n)/(2^n) * (2 * approx n + (b n)/(2^n))))\n               (error n)\n               4\n               H)\n               || X < 4 - ((b n)/(2^n) * (2 * approx n + (b n)/(2^n))) @X by error_Sn n)\n             (Rplus_le_compat_l\n               4\n               (- ((b n)/(2^n) * (2 * approx n + (b n)/(2^n))))\n               0\n               (error_upper_bound_const_0 n))\n           || error (S n) < X @X by <- Rplus_0_r 4)).\nQed.\n\nLemma error_upper_bound_approx_0\n  :  forall n : nat, (approx n)^2 + (4/2^n)*(approx n + 1/2^n) = (approx n + 2/2^n)^2.\nProof.\n  intro n.\n  rewrite (sqr_expand (approx n) (2/2^n)).\n  unfold Rdiv.\n  rewrite <- (Rmult_1_r 2) at 6.\n  rewrite (Rmult_assoc 2 1 (/2^n)).\n  rewrite <- (Rmult_plus_distr_l 2 (approx n) (1 * /2^n)).\n  rewrite (Rmult_assoc 2 (/2^n) _).\n  rewrite <- (Rmult_assoc (/2^n) 2 (approx n + (1 * /2^n))).\n  rewrite (Rmult_comm (/2^n) 2).\n  rewrite (Rmult_assoc 2 (/2^n) (approx n + (1 * /2^n))).\n  rewrite <- (Rmult_assoc 2 2 (/2^n * (approx n + (1 * /2^n)))).\n  rewrite eq_2_2_4.\n  rewrite <- (Rmult_assoc 4 (/2^n) (approx n + 1 * /2^n)).\n  reflexivity.\nQed.\n\n(**\n  Proves a significant constraint on [error]\n  and [approx].\n*)\nTheorem error_upper_bound_approx\n  :  forall n : nat, error n < (4/2^n)*(approx n + 1/2^n).\nProof.\n  exact\n    (fun n\n      => Rplus_lt_compat_r\n           (- ((approx n)^2))\n           a\n           ((4/2^n)*(approx n + 1/2^n) + (approx n)^2)\n           (a_upper_bound_approx n \n             || a < X @X by error_upper_bound_approx_0 n\n             || a < X @X by <- Rplus_comm ((approx n)^2) ((4/2^n)*(approx n + 1/2^n)))\n         || X < ((4/2^n)*(approx n + 1/2^n) + (approx n)^2) - ((approx n)^2) @X by <- error_n n\n         || error n < X                              @X by <- Rplus_assoc ((4/2^n)*(approx n + 1/2^n)) ((approx n)^2) (- ((approx n)^2))\n         || error n < (4/2^n)*(approx n + 1/2^n) + X @X by <- Rplus_opp_r ((approx n)^2)\n         || error n < X                              @X by <- Rplus_0_r ((4/2^n)*(approx n + 1/2^n))).\nQed.\n\nLemma rem_register_even_exp_0\n  :  forall n : nat, (4/2^n)*(approx n + 1/2^n) < (4/2^n)*(sqrt 2 + 1/2^n).\nProof.\n  intro n.\n  apply (Rmult_lt_compat_l (4/2^n) (approx n + 1/2^n) (sqrt 2 + 1/2^n)).\n  + unfold Rdiv.\n    apply (Rlt_mult_inv_pos 4 (2^n) lt_0_4 (pow_lt 2 n Rlt_0_2)).\n  + apply (Rplus_lt_compat_r (1/2^n) (approx n) (sqrt 2) (approx_upper_bound n)).\nQed.\n    \n\n(**\n  Is equivalent to:\n  1/2^(n+1) + sqrt(2) < 2\n  1/2^(n+1) + sqrt(2) < 1/2^(n+1) + 1.5 <= 2\n                        1/2^(n+1)       <= 2 - 1.5\n                        1/2^(n+1)       <= 1/2\n  \n*)\nLemma rem_register_even_exp_1\n  :  forall n : nat, (4/2^(S n))*(sqrt 2 + 1/2^(S n)) < 8/2^(S n).\nProof.\n  intro n.\n  unfold Rdiv.\n  simpl.\n  rewrite (Rinv_mult_distr 2 (2^n) neq_2_0 (pow_nonzero 2 n neq_2_0)).\n  rewrite <- (Rmult_assoc 4 (/2) (/2^n)). fold (Rdiv 4 2). rewrite div_eq_4_2.\n  rewrite <- (Rmult_assoc 8 (/2) (/2^n)). fold (Rdiv 8 2). rewrite div_eq_8_2.\n  rewrite (Rmult_assoc 2 (/2^n) (sqrt 2 + 1 * (/2 * /2^n))).\n  rewrite (Rmult_comm (/2^n) (sqrt 2 + 1 * (/2 * /2^n))).\n  rewrite <- (Rmult_assoc 2 (sqrt 2 + 1 * (/2 * /2^n)) (/2^n)).\n  apply (Rmult_lt_compat_r (/2^n) (2 * (sqrt 2 + 1 * (/2 * /2^n))) 4).\n  + exact (Rlt_inv_2n n).\n  + rewrite <- eq_2_2_4.\n    apply (Rmult_lt_compat_l 2 (sqrt 2 + 1 * (/2 * /2^n)) 2).\n    - exact lt_0_2.\n    - refine\n        (Rlt_le_trans\n          (sqrt 2 + 1 * (/2 * /2^n))\n          (3/2 + 1 * (/2 * /2^n))\n          2 _ _). \n      * apply (Rplus_lt_compat_r (1 * (/2 * /2^n))).\n        exact (lt_sqrt_div_3_2).\n      * rewrite (Rmult_1_l (/2 * /2^n)).\n        rewrite <- (Rmult_1_l (/2)).\n        unfold Rdiv.\n        induction n as [m|m].\n        ** rewrite (pow_O 2).\n           rewrite Rinv_1.\n           rewrite (Rmult_1_r (1 * /2)).\n           rewrite <- (Rmult_plus_distr_r 3 1 (/2)).\n           rewrite eq_3_1_4.\n           fold (Rdiv 4 2).\n           rewrite div_eq_4_2.\n           exact (Rle_refl 2).\n        ** simpl.\n           apply\n             (Rle_trans\n               (3 * / 2 + 1 * / 2 * / (2 * 2 ^ m))\n               (3 * / 2 + 1 * / 2 * / 2 ^ m)\n               2).\n           *** apply\n                 (Rplus_le_compat_l\n                   (3*/2)\n                   (1 * /2 * /(2 * 2^m))\n                   (1 * /2 * /2^m)).\n               rewrite (Rmult_1_l (/2)).\n               apply (Rmult_le_compat_l (/2) (/(2 * 2 ^ m)) (/2^m)).\n               apply (neq_inv_2_0).\n               rewrite (Rinv_mult_distr 2 (2^m) neq_2_0 (pow_nonzero 2 m neq_2_0)).\n               rewrite <- (Rmult_1_l (/2^m)) at 2.\n               refine (Rmult_le_compat_r (/2^m) (/2) 1 (Rle_inv_2n m) _).\n               apply (Rmult_le_reg_l 2 (/2) 1).\n               **** exact lt_0_2.\n               **** rewrite (Rinv_r 2); [rewrite (Rmult_1_r 2); exact le_1_2|exact neq_2_0].\n           *** assumption.\nQed.\n  \n(**\n  Proves that the width used to store\n  intermediate error values is large enough to\n  accomodate every possible value without a loss\n  of precision.\n*)\nTheorem rem_register_even_exp\n  :  forall n : nat, error n < 8/2^n.\nProof.\n  exact\n    (nat_ind _\n      (Rlt_trans\n        (error 0)\n        4\n        (8/2^0)\n        (error_upper_bound_const 0)\n        ((ltac:(lra) : 4 < 8)\n          || 4 < X @X by (ltac:(field) : 8/2^0 = 8)))\n      (fun n (H : error n < 8/2^n)\n        => Rlt_trans\n             (error (S n))\n             ((4/2^(S n))*(approx (S n) + 1/2^(S n)))\n             (8/2^(S n))\n             (error_upper_bound_approx (S n))\n             (Rlt_trans\n               ((4/2^(S n))*(approx (S n) + 1/2^(S n)))\n               ((4/2^(S n))*(sqrt 2 + 1/2^(S n)))\n               (8/2^(S n))\n               (rem_register_even_exp_0 (S n))\n               (rem_register_even_exp_1 n)))).\nQed.\n\nClose Scope R_scope.\n", "meta": {"author": "llee454", "repo": "FPU-Verification", "sha": "c8bbb7b9dd08b6f0a054463f7737aac77c4e144c", "save_path": "github-repos/coq/llee454-FPU-Verification", "path": "github-repos/coq/llee454-FPU-Verification/FPU-Verification-c8bbb7b9dd08b6f0a054463f7737aac77c4e144c/verification/sqrt_even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.669939292199191}}
{"text": "Require Import bbv.Word.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Arith.Lt.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.Structures.OrderedType.\nRequire Import Coq.Numbers.NatInt.NZLog.\nRequire Import Coq.ZArith.Wf_Z.\nRequire Export FMapAVL.\nRequire Export Coq.Structures.OrderedTypeEx.\nRequire Import Lia.\nModule M := FMapAVL.Make(N_as_OT).\n\n\n(* Compute (wordToNat (wplus (natToWord 32 10) (natToWord 32 20))). *)\nDefinition WLen: nat := 256. \nDefinition bigNum: N := wordToN (wlshift' (natToWord 257 1) 256).\nDefinition EVMWord:= word WLen.\nDefinition ByteLen: nat := 8.\nDefinition Byte := word ByteLen.\nDefinition StackLen := 1024.\nDefinition WZero: EVMWord  := natToWord WLen 0.\nDefinition WTrue: EVMWord  := natToWord WLen 1. \nDefinition WFalse: EVMWord := natToWord WLen 0. \nDefinition ZeroBit: word _ := natToWord 1 0. \nDefinition W0xFF: EVMWord := natToWord WLen 255.\nDefinition boolToWord(b: bool): EVMWord := \n  match b with \n  | true  => WTrue \n  | false => WFalse\n  end.\n\n(* Compute W0xFF. *)\nDefinition wgtbWorToUZ{sz: nat}(w: word sz): Z := wordToZ(bbv.Word.combine w ZeroBit).\nDefinition wugtb{sz: nat}(l r: word sz): bool := Z.gtb (wgtbWorToUZ l) (wgtbWorToUZ r).\nDefinition wultb{sz: nat}(l r: word sz): bool := Z.ltb (wgtbWorToUZ l) (wgtbWorToUZ r).\nDefinition wsgtb{sz: nat}(l r: word sz): bool := Z.gtb (wordToZ l) (wordToZ r).\nDefinition wsltb{sz: nat}(l r: word sz): bool := Z.ltb (wordToZ l) (wordToZ r).\nDefinition withbyte(w: EVMWord)(i: nat): EVMWord := wand (wrshift' w (248%nat - (i * 8))) W0xFF.\nDefinition Wones: EVMWord := wones WLen.\nDefinition pushMask(bytes: nat): EVMWord := wnot (wlshift' Wones (bytes * 8)).\nDefinition pushWordPass(w: EVMWord)(bytes: nat): EVMWord := wand (pushMask bytes) w.\n(* Compute whd W0xFF. *)\nDefinition sextWordBytes(w: EVMWord)(bytes: nat): EVMWord := \n  match whd (wlshift' w (256 - (bytes * 8))) with \n  | true  => wor (wlshift' Wones (bytes * 8)) (pushMask bytes)\n  | false => pushMask bytes\n  end. \n\nDefinition bytetoEWMword(w: word 8): EVMWord. Proof.\napply (Word.combine w (wzero' 248)).\nDefined.\nCompute wordToN (bytetoEWMword (natToWord 8 1)).\nDefinition wordSubModulus(a b: EVMWord): EVMWord := \n  if N.ltb (wordToN a) (wordToN b) \n  then NToWord WLen (bigNum - ((wordToN b) - (wordToN a)))\n  else wminus a b\n.\nDefinition map_n_evmword := M.t EVMWord.\nDefinition find {V: Type}(k: EVMWord)(m: M.t V) := M.find (wordToN k) m.\nDefinition update (p: EVMWord * EVMWord) (m: map_n_evmword) :=\n  M.add (wordToN (fst p)) (snd p) m.\nDefinition mapLength {V: Type}(m: M.t V): nat :=\n  length (M.elements m).\nFixpoint wordmsb {sz: nat}(bitnum aux: nat)(w: word sz): nat :=\n  match w with \n  | WO => aux\n  | WS b w1 => \n    match b with \n    | true  => wordmsb (S bitnum) bitnum w1\n    | false => wordmsb (S bitnum) aux w1\n    end \n  end.\n\nDefinition log2Orzero {sz} (w: word sz): nat := wordmsb 0 0 w.\n(* aux parameter required to ensure termnation checker, for words we will have at most 256 iterations *)\nFixpoint effExpAux(a b: N)(aux: nat){struct aux}: N  := \n  match aux with \n  | O => 0 \n  | S p =>\n    match N.eqb b 0 with\n    | true  => 1\n    | false => \n      match N.eqb (N.modulo b 2) 1 with\n      | true  => a * (effExpAux a (b - 1) p)\n      | false => (effExpAux a (b / 2) p ) * (effExpAux a (b / 2) p)\n      end\n    end\n  end. \n\nFixpoint expmodAux (a b m: N)(aux: nat): N:=\n  match N.eqb m 1 with \n  | true  => 0 \n  | false =>\n    match aux with \n    | 0 => 0\n    | S p => \n      match N.eqb b 0 with \n      | true  => 1\n      | false => \n        match N.eqb (N.modulo b 2) 1 with\n        | true  => N.modulo (a * (effExpAux a (b - 1) p)) m\n        | false =>  let presq := (effExpAux a (b / 2) p ) in N.modulo (presq * presq) m\n        end\n      end\n    end\n  end.\n\nDefinition effExp(a b: N): N := effExpAux a b 512%nat.\nDefinition expmod(a b m: N): N := expmodAux a b m 512%nat.\n(* Compute let maxword := (effExp 2 256) in let mwm1 \n:= N.sub maxword 1 in effExp mwm1 mwm1. *)\nDefinition wordModulus := effExp 2 256.\n\nNotation \"k |-> v\" := (pair k v) (at level 60).\nNotation \"k |-> v\" := (pair k v) (at level 60).\nNotation \"[ ]\" := (M.empty nat).\nNotation \"[ p1 , .. , pn ]\" := (update p1 .. (update pn (M.empty nat)) .. ).\n\nCompute pushWordPass Wones 32.\n\nCompute NToWord 8 1.\n\nDefinition combine {A B C: Type}(f: A -> B)(g: B -> C): A -> C := \nfun a => g (f a).\n\nNotation \"f1 * f2\" := (combine f1 f2).\n\nDefinition map{L R R1: Type}(s: L + R)(f: R -> R1): L + R1 := \n  match s with \n  | inl l => inl l\n  | inr r => inr (f r)\n  end.\n\nDefinition flatMap{L R R1: Type}(s: L + R)(f: R -> L + R1): L + R1 := \n  match s with \n  | inl l => inl l\n  | inr r => f r\n  end.\n\n\nDefinition flatMapT(L R R1: Type)(s: L + R)(f: R -> L + R1): L + R1 := \n  match s with \n  | inl l => inl l\n  | inr r => f r\n  end.\n\nDefinition leftMap{L1 L2 R: Type}(s: L1+R)(f: L1 -> L2): L2 + R := \n  match s with \n  | inl l => inl (f l)\n  | inr r => inr r\n  end.\n\n(* end straightforward either impl*)\n\n(* very util functions*) \n\nFixpoint compareNatsAndAct{T: Set}(a b: nat)(ifAgreaterOrEqualToB ifBgreater: T): T:= \n  match (a, b) with \n   | (O, O)            => ifAgreaterOrEqualToB \n   | (S _, O)          => ifAgreaterOrEqualToB\n   | (O, S _)          => ifBgreater\n   | (S predA,S predB) => compareNatsAndAct predA predB ifAgreaterOrEqualToB ifBgreater\n  end.\n\nFixpoint gtb(a b: nat): bool := \n  match (a,b) with \n  | (O, O) => false\n  | (S _, O) => true\n  | (O, S _) => false\n  | (S predA, S predB) => gtb predA predB\n  end.\nDefinition mapO{A B: Type}(o: option A)(f: A -> B): option B := \n  match o with \n  | Some a => Some (f a)\n  | None   => None\n  end. \nDefinition flatMapO{A B: Type}(o: option A)(f: A -> option B): option B := \n  match o with \n  | Some a => f a\n  | None   => None\n  end. \n(* Compute let pos := 4 in let l := 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: nil in skipn 1 (firstn (pos - 1) l).\nCompute let pos := 4 in let l := 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: nil in skipn pos l. *)\n(* TODO: proofs  \n *)\nDefinition listSwapWithHead{A: Set}(l: list A)(pos: nat): option (list A) := \n  flatMapO\n  (hd_error l) \n  (fun head => \n    flatMapO \n    (nth_error l pos)\n    (fun item => \n      let middle := skipn 1 (firstn (pos) l) in\n      let rest   := skipn (pos + 1) l in\n      Some ((item :: middle) ++ (head :: rest))\n    )\n  ).\n\nDefinition getSliceFromList{T: Type}(l: list T)(offset length: nat): option (list T) := \n  match Nat.ltb (offset+ length) (List.length l) with\n  | true  => Some (firstn length (skipn offset l))\n  | false => None\n  end.\n\nCompute let offset := 35 in let length := 3 in let l := 0 :: 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: nil in getSliceFromList l offset length.\n\nCompute let pos := 4 in let l := 0 :: 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: nil in listSwapWithHead l pos.\n(* end very util functions *) \n(* execution 'monad' and error codes*)\nInductive Log: Type := \n| Log0: list EVMWord -> Log\n| Log1: EVMWord -> list EVMWord -> Log\n| Log2: EVMWord -> EVMWord -> list EVMWord -> Log\n| Log3: EVMWord -> EVMWord -> EVMWord -> list EVMWord -> Log\n| Log4: EVMWord -> EVMWord -> EVMWord -> EVMWord -> list EVMWord -> Log.\n\nInductive ExecutionState: Type := \n| ExecutionStateMk: list (EVMWord) -> map_n_evmword -> map_n_evmword -> (M.t (list (word 8))) -> nat -> (list Log) -> ExecutionState. (* pc stack memory storage contracts logs*)\n\nDefinition getLog_ES es := \nmatch es with \n| ExecutionStateMk _ _ _ _ _ logs => logs\nend.\n\nDefinition setLog_ES es logs := \nmatch es with \n| ExecutionStateMk stack memory storage contractMap pc _ => ExecutionStateMk stack memory storage contractMap pc logs\nend.\n\nDefinition getPc_ES es := \nmatch es with\n| ExecutionStateMk _ _ _ _ pc _ => pc\nend.\n\nDefinition setPc_ES es pc := \nmatch es with\n| ExecutionStateMk stack memory storage contractMap _ logs => ExecutionStateMk stack memory storage contractMap pc logs\nend.\n\nDefinition getStack_ES es := \nmatch es with\n| ExecutionStateMk stack _ _ _ _ _ => stack\nend.\n\nDefinition getMemory_ES es := \nmatch es with\n| ExecutionStateMk _ memory _ _ _ _ => memory\nend.\n\nDefinition setStack_ES es stack := \nmatch es with\n| ExecutionStateMk _ memory storage contractMap pc logs => ExecutionStateMk stack memory storage contractMap pc logs \nend.\n\nDefinition setMemory_ES es memory := \nmatch es with\n| ExecutionStateMk stack _ storage contractMap pc logs => ExecutionStateMk stack memory storage contractMap pc logs\nend.\n\nDefinition getStorage_ES es := \nmatch es with\n| ExecutionStateMk _ _ storage _ _ _ => storage\nend.\n\nDefinition setStorage_ES es storage := \nmatch es with\n| ExecutionStateMk stack memory _ contractMap pc logs => ExecutionStateMk stack memory storage contractMap pc logs\nend.\n\nDefinition getContractMap_ES es := \nmatch es with\n| ExecutionStateMk _ _ _ contractMap _ _ => contractMap\nend.\n\nDefinition setContractMap_ES es contractMap := \nmatch es with\n| ExecutionStateMk stack memory storage _ pc logs => ExecutionStateMk stack memory storage contractMap pc logs\nend.\n\nInductive SuccessfulExecutionResult: Type := \n| SuccessfulExecutionResultMk: ExecutionState -> SuccessfulExecutionResult\n| SuccessfulExecutionResultMkWithData: ExecutionState -> list EVMWord -> SuccessfulExecutionResult\n.\n\nInductive ErrorCode: Set := \n| OutOfGas: ErrorCode\n| InvalidOpcode: ErrorCode\n| InvalidJumpDest: ErrorCode\n| StackUnderflow: ErrorCode\n| StackOverflow: ErrorCode\n| BadWordAsByte: ErrorCode\n| BadSigExtendWord: ErrorCode\n| BadByteArgI: ErrorCode\n| BadShlArgI: ErrorCode\n| BadShrArgI: ErrorCode\n| BadCallDataLoadArgI: ErrorCode\n| BadPeekArg: ErrorCode\n| NonexistentAddress: ErrorCode\n| NonexistentContract: ErrorCode\n| NonexistentMemoryCell: ErrorCode\n| NonexistentStorageCell: ErrorCode\n| NonexistentCallDataCell : ErrorCode\n| NotImplemented : ErrorCode\n.\n\nInductive ErrorneousExecutionResult: Type := \n| ErrorneousExecutionResultMk: ErrorCode -> ExecutionState -> ErrorneousExecutionResult.\n\nDefinition ExecutionResult: Type := ErrorneousExecutionResult + SuccessfulExecutionResult.\n\nDefinition OpcodeApplicationResult: Type := ExecutionResult + ExecutionState.\n\nDefinition ExecutionResultOr T : Type := ExecutionResult + T.\n\n(* end execution 'monad' and error codes*)\n(* handy constructors *) \n\nDefinition stopExecutionWithSuccess(es: ExecutionState): OpcodeApplicationResult := \n  inl (inr (SuccessfulExecutionResultMk es)).\n\nDefinition failWithErrorCode{T: Type}(es: ExecutionState)(errorCode: ErrorCode): ExecutionResultOr T :=\n  inl ( inl (ErrorneousExecutionResultMk errorCode es)). \n\n(* Definition runningExecutionWithState es: OpcodeApplicationResult := inr es. *)\n\nDefinition runningExecutionWithState {T: Type}(t: T): ExecutionResultOr T := inr t.\n(* end handy constructors *) \n(* program counter operations *)\n\nDefinition setProgramCounter(es: ExecutionState)(programLength newPc: nat): OpcodeApplicationResult := \n    match Nat.leb programLength newPc with\n    | true  => runningExecutionWithState es\n    | false => failWithErrorCode es InvalidJumpDest\n    end.\n(* end program counter opertaions*)\n\nDefinition attach{T: Type}(o: OpcodeApplicationResult)(t: T): ExecutionResultOr (ExecutionState *T) := \n  map \n  o \n  (fun es => (es,t)).\n\n(* stack operations *)\nDefinition pushItemToExecutionStateStack es item: OpcodeApplicationResult :=\n  if(length (getStack_ES es) <? 1024)\n  then runningExecutionWithState (setStack_ES es (item :: (getStack_ES es)))\n  else failWithErrorCode es StackOverflow.\n\nDefinition removeAndDropFromStackOneItem es := \n  let stack := getStack_ES es in \n    match stack with \n      | head :: tail => runningExecutionWithState (setStack_ES es tail)\n      | nil => failWithErrorCode es StackUnderflow\n    end.\n\nDefinition removeAndReturnFromStackOneItem es: (ExecutionResultOr (ExecutionState * EVMWord)) := \n  let stack := getStack_ES es in  \n    match stack with \n      | head1 :: tail => \n          runningExecutionWithState ((setStack_ES es tail), head1)\n      | nil => failWithErrorCode es StackUnderflow\n    end.\n\nDefinition removeAndReturnFromStackTwoItems es: (ExecutionResultOr (ExecutionState * EVMWord * EVMWord)) := \n  let stack := getStack_ES es in \n    match stack with \n      | head1 :: head2 :: tail => \n          runningExecutionWithState\n            ((setStack_ES es tail), head1, head2)\n      | nil | _ :: nil => failWithErrorCode es StackUnderflow\n    end.\n\nDefinition removeAndReturnFromStackTwoItemsEnder es: (ErrorneousExecutionResult + (ExecutionState * EVMWord * EVMWord)) := \n  let stack := getStack_ES es in \n    match stack with \n      | head1 :: head2 :: tail => \n          inr ((setStack_ES es tail), head1, head2)\n      | nil | _ :: nil => inl (ErrorneousExecutionResultMk StackUnderflow es)\n    end.\n\nDefinition removeAndReturnFromStackThreeItems es: (ExecutionResultOr (ExecutionState * EVMWord * EVMWord * EVMWord)) := \n  let stack := getStack_ES es in \n    match stack with \n      | head1 :: head2 :: head3:: tail => \n          runningExecutionWithState\n            ((setStack_ES es tail), head1, head2, head3)\n      | nil | _ :: nil | _ :: _ :: nil => failWithErrorCode es StackUnderflow\n    end.\n\nDefinition removeAndReturnFromStackFourItems es: (ExecutionResultOr (ExecutionState * EVMWord * EVMWord * EVMWord * EVMWord)) := \n  let stack := getStack_ES es in \n    match stack with \n      | head1 :: head2 :: head3 :: head4 :: tail => \n          runningExecutionWithState\n            ((setStack_ES es tail), head1, head2, head3, head4)\n      | nil | _ :: nil | _ :: _ :: nil | _ :: _ :: _ :: nil=> failWithErrorCode es StackUnderflow\n    end.\n\nDefinition removeAndReturnFromStackFiveItems es: (ExecutionResultOr (ExecutionState * EVMWord * EVMWord * EVMWord * EVMWord * EVMWord)) := \n  let stack := getStack_ES es in \n    match stack with \n      | head1 :: head2 :: head3 :: head4 :: head5 :: tail => \n          runningExecutionWithState\n            ((setStack_ES es tail), head1, head2, head3, head4, head5)\n      | nil | _ :: nil | _ :: _ :: nil | _ :: _ :: _ :: nil | _ :: _ :: _ :: _ :: nil => failWithErrorCode es StackUnderflow\n    end.\n\nDefinition removeAndReturnFromStackSixItems es: (ExecutionResultOr (ExecutionState * EVMWord * EVMWord * EVMWord * EVMWord * EVMWord * EVMWord)) := \n  let stack := getStack_ES es in \n    match stack with \n      | head1 :: head2 :: head3 :: head4 :: head5 :: head6 :: tail => \n          runningExecutionWithState\n            ((setStack_ES es tail), head1, head2, head3, head4, head5, head6)\n      | nil | _ :: nil | _ :: _ :: nil | _ :: _ :: _ :: nil | _ :: _ :: _ :: _ :: nil | _ :: _ :: _ :: _ :: _ :: nil => failWithErrorCode es StackUnderflow\n    end.\n\nDefinition peekNthItemFromStack es (n: nat): (ExecutionResultOr EVMWord):= \n  let stack := getStack_ES es in\n    match nth_error stack n with \n      | Some item => runningExecutionWithState item\n      | None      => failWithErrorCode es BadPeekArg\n    end.\n(* end stack operations *)\n\nFixpoint insertItemsIntoMemoryAux(es: ExecutionState)(acc offset: nat)(words: list EVMWord){struct words} : ExecutionState :=\n  match words with \n  | nil        => es\n  | w :: words' =>\n    let mem := getMemory_ES es in \n    let updatedMemory := update (natToWord WLen (acc + offset), w) mem in \n    let new_es := setMemory_ES es updatedMemory in \n    insertItemsIntoMemoryAux new_es (S acc) offset words'\n  end.\n\nDefinition insertItemsIntoMemory(es: ExecutionState)(offset: nat)(words: list EVMWord): ExecutionState :=\n  insertItemsIntoMemoryAux es 0 offset words.\n\nDefinition zipBytesToWord(l: list (word 8)):= \n  fold_left (fun acc => fun b => wor (wlshift' acc 8) (bytetoEWMword b)) l WZero.\n(* \nLemma \nCompute let w0 := natToWord 8 1 in let w1 := natToWord 8 1 in let w2 := natToWord 8 1 in let res := zipBytesToWord (w1 :: w1 :: w1 :: w1 :: nil) in wordToN res.\n *)\n\nFixpoint zipListOfBytesIntoListOfWordsAux(l: list (word 8))(crutch: nat): list EVMWord :=\n  match crutch with \n  | O => match l with | nil => nil | _ :: __ => (zipBytesToWord l) :: nil end\n  | S p => zipListOfBytesIntoListOfWordsAux (skipn 32 l) (p) ++ (zipBytesToWord (firstn 32 l) :: nil) \n  end.\n\nDefinition zipListOfBytesIntoListOfWords(l: list (word 8)): list EVMWord := \n  zipListOfBytesIntoListOfWordsAux l ( ((length l) / 32) + 1).\n\n(* WordUtil *)\nDefinition extractByteAsNat(w: EVMWord): ErrorCode + nat := \n  match weqb (wlshift' w 8%nat) WZero with \n  | true  => inr (wordToNat w)\n  | false => inl BadWordAsByte\n  end.\n\n(* WordUtil *)\nInductive SimplePriceOpcode: Set :=\n| ADD\t          : SimplePriceOpcode\n| MUL\t          : SimplePriceOpcode\n| SUB\t          : SimplePriceOpcode\n| DIV\t          : SimplePriceOpcode\n| SDIV\t        : SimplePriceOpcode\n| MOD\t          : SimplePriceOpcode\n| SMOD\t        : SimplePriceOpcode\n| ADDMOD\t      : SimplePriceOpcode\n| MULMOD\t      : SimplePriceOpcode\n| SIGNEXTEND\t  : SimplePriceOpcode\n| LT\t          : SimplePriceOpcode\n| GT\t          : SimplePriceOpcode\n| SLT\t          : SimplePriceOpcode\n| SGT\t          : SimplePriceOpcode\n| EQ\t          : SimplePriceOpcode\n| ISZERO\t      : SimplePriceOpcode\n| AND\t          : SimplePriceOpcode\n| OR\t          : SimplePriceOpcode\n| XOR\t          : SimplePriceOpcode\n| NOT\t          : SimplePriceOpcode\n| BYTE          : SimplePriceOpcode\n| ADDRESS\t      : SimplePriceOpcode\n| BALANCE\t      : SimplePriceOpcode\n| ORIGIN\t      : SimplePriceOpcode\n| CALLER\t      : SimplePriceOpcode\n| CALLVALUE\t    : SimplePriceOpcode\n| CALLDATALOAD\t: SimplePriceOpcode\n| CALLDATASIZE\t: SimplePriceOpcode\n| CODESIZE\t    : SimplePriceOpcode\n| GASPRICE\t    : SimplePriceOpcode\n| EXTCODESIZE\t  : SimplePriceOpcode\n| BLOCKHASH\t    : SimplePriceOpcode\n| COINBASE\t    : SimplePriceOpcode\n| TIMESTAMP\t    : SimplePriceOpcode\n| NUMBER\t      : SimplePriceOpcode\n| DIFFICULTY  \t: SimplePriceOpcode\n| GASLIMIT\t    : SimplePriceOpcode\n| POP\t          : SimplePriceOpcode\n| MLOAD\t        : SimplePriceOpcode\n| MSTORE\t      : SimplePriceOpcode\n| MSTORE8\t      : SimplePriceOpcode\n| SLOAD\t        : SimplePriceOpcode\n| PC\t          : SimplePriceOpcode\n| MSIZE\t        : SimplePriceOpcode\n| GAS\t          : SimplePriceOpcode\n| JUMPDEST\t    : SimplePriceOpcode\n| PUSH\t        : word 5 -> EVMWord -> SimplePriceOpcode\n| DUP\t          : word 4 -> SimplePriceOpcode\n| SWAP\t        : word 4 -> SimplePriceOpcode\n| CREATE\t      : SimplePriceOpcode\n| JUMP          : SimplePriceOpcode\n| JUMPI         : SimplePriceOpcode\n.\n\nDefinition simplePriceOpcodePrice(o: SimplePriceOpcode): nat :=\n  match o with\n  | ADD\t          => 3\n  | MUL\t          => 5\n  | SUB\t          => 3\n  | DIV\t          => 5\n  | SDIV\t        => 5\n  | MOD\t          => 5\n  | SMOD\t        => 5\n  | ADDMOD\t      => 8\n  | MULMOD\t      => 8\n  | SIGNEXTEND\t  => 5\n  | LT\t          => 3\n  | GT\t          => 3\n  | SLT\t          => 3\n  | SGT\t          => 3\n  | EQ\t          => 3\n  | ISZERO\t      => 3\n  | AND\t          => 3\n  | OR\t          => 3\n  | XOR\t          => 3\n  | NOT\t          => 3\n  | BYTE          => 3\n  | ADDRESS\t      => 2\n  | BALANCE\t      => 400\n  | ORIGIN\t      => 2\n  | CALLER\t      => 2\n  | CALLVALUE\t    => 2\n  | CALLDATALOAD\t=> 3\n  | CALLDATASIZE\t=> 2\n  | CODESIZE\t    => 2\n  | GASPRICE\t    => 2\n  | EXTCODESIZE\t  => 700\n  | BLOCKHASH\t    => 20\n  | COINBASE\t    => 2\n  | TIMESTAMP\t    => 2\n  | NUMBER\t      => 2\n  | DIFFICULTY  \t=> 2\n  | GASLIMIT\t    => 2\n  | POP\t          => 2\n  | MLOAD\t        => 3\n  | MSTORE\t      => 3\n  | MSTORE8\t      => 3\n  | SLOAD\t        => 200\n  | PC\t          => 2\n  | MSIZE\t        => 2\n  | GAS\t          => 2\n  | JUMPDEST\t    => 1\n  | PUSH _ _\t    => 3\n  | DUP _\t        => 3\n  | SWAP\t_       => 3\n  | CREATE\t      => 32000\n  | JUMP          => 8\n  | JUMPI         => 10\n  end.\n\nInductive ComplexPriceOpcode: Set :=\n|\tEXP                : ComplexPriceOpcode\n|\tSHA3\t             : ComplexPriceOpcode\n|\tCALLDATACOPY\t     : ComplexPriceOpcode\n|\tCODECOPY\t         : ComplexPriceOpcode\n|\tEXTCODECOPY\t       : ComplexPriceOpcode\n|\tSSTORE\t           : ComplexPriceOpcode\n|\tLOG0\t             : ComplexPriceOpcode\n|\tLOG1\t             : ComplexPriceOpcode\n|\tLOG2\t             : ComplexPriceOpcode\n|\tLOG3\t             : ComplexPriceOpcode\n|\tLOG4\t             : ComplexPriceOpcode\n|\tCALL\t             : ComplexPriceOpcode\n|\tCALLCODE\t         : ComplexPriceOpcode\n|\tDELEGATECALL\t     : ComplexPriceOpcode\n|\tSELFDESTRUCT\t     : ComplexPriceOpcode\n.\n\n\nInductive OpCode: Set :=\n|\tSTOP\t              : OpCode\n|\tRETURN\t            : OpCode\n| ComplexPriceOpcodeMk: ComplexPriceOpcode -> OpCode\n| SimplePriceOpcodeMk : SimplePriceOpcode  -> OpCode\n.\n\nInductive CallInfo: Type := \n| CallInfoMk: \n  list (EVMWord)(*calldata*) ->\n  EVMWord(*this contract address*) ->\n  EVMWord(*caller balance*) ->\n  EVMWord(*transaction hash*) ->\n  EVMWord(*caller address*) ->\n  EVMWord(*call eth value*) ->\n  list Byte(*this contract code*) ->\n  EVMWord(*tx gas price*) ->\n  EVMWord(*block hash*) ->\n  EVMWord(*block number*) ->\n  EVMWord(*block dificulty*) ->\n  EVMWord(*block timestamp*) ->\n  EVMWord(*gas block limit*) ->\n  EVMWord(*miner's address*) ->\n  map_n_evmword(*account balances *) -> \n  CallInfo.\n\n(* \n  match _ with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n  end\n *)\nDefinition get_calldata(ci: CallInfo): list EVMWord := \n  match ci with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n    calldata\n  end.\n\nDefinition get_thisContractAddress(ci: CallInfo): EVMWord := \n  match ci with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n    thisContractAddress\n  end.\n\nDefinition get_callerBalance(ci: CallInfo): EVMWord := \n  match ci with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n    callerBalance\n  end.\n\nDefinition get_transactionHash(ci: CallInfo): EVMWord := \n  match ci with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n    transactionHash\n  end.\n\nDefinition get_callerAddress(ci: CallInfo): EVMWord := \n  match ci with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n    callerAddress\n  end.\n\nDefinition get_callEthValue(ci: CallInfo): EVMWord := \n  match ci with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n    callEthValue\n  end.\n\nDefinition get_thisContractCode(ci: CallInfo): list (word ByteLen) := \n  match ci with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n    thisContractCode\n  end.\n\nDefinition get_txGasPrice(ci: CallInfo): EVMWord := \n  match ci with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n    txGasPrice\n  end.\n\nDefinition get_blockHash(ci: CallInfo):EVMWord := \n  match ci with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n    blockHash\n  end.\n\nDefinition get_blockNumber(ci: CallInfo): EVMWord := \n  match ci with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n    blockNumber\n  end.\n\nDefinition get_blockDificulty(ci: CallInfo): EVMWord := \n  match ci with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n    blockDificulty\n  end.\n\nDefinition get_gasLimit(ci: CallInfo): EVMWord := \n  match ci with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n    blockDificulty\n  end.\n\nDefinition get_miner(ci: CallInfo): EVMWord := \n  match ci with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n    miner\n  end.\n\nDefinition get_blockTimestamp(ci: CallInfo): EVMWord := \n  match ci with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n    blockTimestamp\n  end.\n\nDefinition get_accountBalances(ci: CallInfo): map_n_evmword := \n  match ci with \n  | CallInfoMk calldata thisContractAddress callerBalance transactionHash callerAddress callEthValue thisContractCode txGasPrice blockHash blockNumber blockDificulty blockTimestamp gasLimit miner accountBalances=> \n    accountBalances\n  end.\n\nFixpoint getSliceFromMapAux{V: Type}(m: M.t V)(offset: EVMWord)(length : nat)(acc: list V){struct length}: ErrorCode + (list V) := \n  match length with \n  | O      => \n    match find offset m with\n    | Some v => inr (acc ++ (v :: nil))\n    | None   => inl NonexistentMemoryCell\n    end\n  | S pred => \n    match find offset m  with\n    | Some v => getSliceFromMapAux m (wplus offset WTrue) pred (acc ++ (v :: nil))\n    | None   => inl NonexistentMemoryCell\n    end\n  end.\n\nDefinition getSliceFromMap{V: Type}(m: M.t V)(offset: EVMWord)(length : nat): ErrorCode + (list V) := \n  getSliceFromMapAux m offset length nil.\n\nDefinition stopAction(state: ExecutionState): OpcodeApplicationResult := \n  stopExecutionWithSuccess (state).\n\nDefinition addActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    ( fun tup3 => \n      match tup3 with \n      | (es, a, b) => (pushItemToExecutionStateStack es (wplus a b))  \n      end\n    ).\n\nDefinition mulActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b) => \n        pushItemToExecutionStateStack es (wmult a b)\n      end\n    ).\n\nDefinition subActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b) => pushItemToExecutionStateStack es (wordSubModulus a b)\n      end\n    ).\n\nDefinition divActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b) => (pushItemToExecutionStateStack es (wdiv a b))  \n      end\n    ).\n\nDefinition sdivActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b) => (pushItemToExecutionStateStack es (wdivZ a b))  \n      end\n    ).\n\nDefinition modActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b) => (pushItemToExecutionStateStack es (wmod a b))  \n      end\n    ).\n\nDefinition smodActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap \n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b) => (pushItemToExecutionStateStack es (ZToWord WLen (Z.rem (wordToZ a) (wordToZ b))))  \n      end\n    ).\n\nDefinition addmodActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap \n    (removeAndReturnFromStackThreeItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b, N) => \n      let za := wordToZ a in let zb := wordToZ b in let zN := Z.of_N (wordToN N) in \n      let zres := Z.rem (za + zb) zN in\n      (pushItemToExecutionStateStack es (ZToWord WLen zres))  \n      end\n    ).\n\nDefinition mulmodActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap \n    (removeAndReturnFromStackThreeItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b, N) => \n      let za := wordToZ a in let zb := wordToZ b in let zN := Z.of_N (wordToN N) in \n      let zres := Z.rem (za * zb) zN in\n      (pushItemToExecutionStateStack es (ZToWord WLen zres))  \n      end\n    ).\n\nDefinition signextendActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap \n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b) => \n        match extractByteAsNat b with \n        | inl err => failWithErrorCode es err\n        | inr n   => (pushItemToExecutionStateStack es (sextWordBytes a n))\n        end\n      end\n    ).\n\nDefinition ltActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b) => (pushItemToExecutionStateStack es (boolToWord (wultb a b)))  \n      end\n    ).\n\nDefinition gtActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b) => (pushItemToExecutionStateStack es (boolToWord (wugtb a b)))  \n      end\n    ).\n\n\nDefinition sltActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b) => (pushItemToExecutionStateStack es (boolToWord (wsltb a b)))  \n      end\n    ).\n\nDefinition sgtActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b) => (pushItemToExecutionStateStack es (boolToWord (wsgtb a b)))  \n      end\n    ).\n\n\nDefinition eqActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b) => (pushItemToExecutionStateStack es (boolToWord (weqb a b)))  \n      end\n    ).\n\nDefinition iszeroActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackOneItem state)\n    (fun tup2 => \n      match tup2 with \n      | (es, a) => (pushItemToExecutionStateStack es (boolToWord (weqb a WZero)))  \n      end\n    ).\n\nDefinition andActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b) => (pushItemToExecutionStateStack es (wand a b))  \n      end\n    ).\n\nDefinition orActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b) => (pushItemToExecutionStateStack es (wor a b))  \n      end\n    ).\n\nDefinition xorActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, a, b) => (pushItemToExecutionStateStack es (wxor a b))  \n      end\n    ).\n\nDefinition notActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackOneItem state)\n    (fun tup2 => \n      match tup2 with \n      | (es, a) => (pushItemToExecutionStateStack es (wnot a))  \n      end\n    ).\n\nDefinition byteActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, i, x) => \n        match extractByteAsNat i with \n        | inr inat    => \n            match Nat.ltb inat 32 with \n            | true  => (pushItemToExecutionStateStack es (withbyte x inat)) \n            | false => failWithErrorCode es BadShlArgI\n            end\n        | inl errCode => failWithErrorCode es errCode\n        end\n      end\n    ).\n\nDefinition shlActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, i, x) => \n        match extractByteAsNat i with \n        | inr inat    => \n            match Nat.ltb inat 257 with \n            | true  => (pushItemToExecutionStateStack es (wlshift' x inat)) \n            | false => failWithErrorCode es BadShrArgI\n            end\n        | inl errCode => failWithErrorCode es errCode\n        end\n      end\n    ).\n\nDefinition shrActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, i, x) => \n        match extractByteAsNat i with \n        | inr inat    => \n            match Nat.ltb inat 257 with \n            | true  => (pushItemToExecutionStateStack es (wrshift' x inat)) \n            | false => failWithErrorCode es BadByteArgI\n            end\n        | inl errCode => failWithErrorCode es errCode\n        end\n      end\n    ).\n\n(*SHA3*)\nDefinition addressActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult := \n  (pushItemToExecutionStateStack state (get_thisContractAddress ci)).\n\nDefinition balanceActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult :=\n  flatMap \n  (removeAndReturnFromStackOneItem state)\n  (fun tup2 => \n      match tup2 with \n      | (es, a) => \n        match find a (get_accountBalances ci) with\n        | Some balance => (pushItemToExecutionStateStack es balance)  \n        | None => failWithErrorCode es NonexistentAddress\n        end\n      end\n    ).\n  \nDefinition originActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult := \n  (pushItemToExecutionStateStack state (get_callerAddress ci)).\n\n(*  becasue currently implemnted state of EVM does not support nested contract calls, callser = origin *)\nDefinition callerActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult := \n  (pushItemToExecutionStateStack state (get_callerAddress ci)).\n\nDefinition callvalueActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult := \n  (pushItemToExecutionStateStack state (get_callEthValue ci)).\n\nDefinition calldataloadActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackOneItem state)\n    (fun tup2 => \n      match tup2 with (* todo complete*)\n      | (es, idxWord) => \n        let i := wordToNat idxWord in \n          match nth_error (get_calldata ci) i with \n          | Some dataCell => (pushItemToExecutionStateStack es dataCell)  \n          | None          => failWithErrorCode es BadCallDataLoadArgI\n          end\n      end\n    ).\n\nDefinition calldatasizeActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult := \n    (pushItemToExecutionStateStack state (natToWord WLen (length (get_calldata ci)))).\n\n(*Calldatacopy*)\n\nDefinition codesizeActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult := \n    (pushItemToExecutionStateStack state (natToWord WLen (length (get_thisContractCode ci)))).\n(* codecopy *)\n\nDefinition gaspriceActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult := \n    (pushItemToExecutionStateStack state (get_txGasPrice ci)).\n\nDefinition exctcodesizeActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult := \n  flatMap \n  (removeAndReturnFromStackOneItem state)\n    (fun tup2 => \n      match tup2 with \n      | (es, address) => \n        match find address (getContractMap_ES es) with\n        | Some contract => (pushItemToExecutionStateStack state (natToWord WLen (length contract)))\n        | None          => failWithErrorCode es NonexistentMemoryCell\n        end\n      end\n    ).\n(* extcodecopy *)\n\nDefinition blockhashActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult := \n    (pushItemToExecutionStateStack state (get_blockHash ci)).\n\nDefinition coinbaseActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult := \n    (pushItemToExecutionStateStack state (get_miner ci)).\n\nDefinition timestampActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult := \n    (pushItemToExecutionStateStack state (get_blockTimestamp ci)).\n\nDefinition numberActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult := \n    (pushItemToExecutionStateStack state (get_blockNumber ci)).\n\nDefinition dificultyActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult := \n    (pushItemToExecutionStateStack state (get_blockDificulty ci)).\n\nDefinition gaslimitActionPure(state: ExecutionState)(ci: CallInfo): OpcodeApplicationResult := \n    (pushItemToExecutionStateStack state (get_gasLimit ci)).\n\nDefinition popActionPure(state: ExecutionState): OpcodeApplicationResult := \n    flatMap\n    (removeAndReturnFromStackOneItem state)\n    (fun tup2 => \n      runningExecutionWithState (fst tup2)\n    ).\n\nDefinition mloadActionPure(state: ExecutionState): OpcodeApplicationResult := \n  flatMap \n  (removeAndReturnFromStackOneItem state)\n    (fun tup2 => \n      match tup2 with \n      | (es, key) => \n        match find key (getMemory_ES es) with\n        | Some wrd => (pushItemToExecutionStateStack state wrd)\n        | None     => failWithErrorCode es NonexistentMemoryCell\n        end\n      end\n    ).\n\nDefinition mstoreActionPure(state: ExecutionState): OpcodeApplicationResult := \n  flatMap \n  (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, key, value) => runningExecutionWithState (setMemory_ES es (update (key, value) (getMemory_ES es)) )\n      end\n    ).\n\nDefinition mstore8ActionPure(state: ExecutionState): OpcodeApplicationResult := \n  flatMap \n  (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, key, value) => runningExecutionWithState (setMemory_ES es (update (key, wand value W0xFF) (getMemory_ES es)) )\n      end\n    ).\n\n\nDefinition sloadActionPure(state: ExecutionState): OpcodeApplicationResult := \n  flatMap \n  (removeAndReturnFromStackOneItem state)\n    (fun tup2 => \n      match tup2 with \n      | (es, key) => \n        match find key (getStorage_ES es) with\n        | Some wrd => (pushItemToExecutionStateStack state wrd)\n        | None     => failWithErrorCode es NonexistentMemoryCell\n        end\n      end\n    ).\n\nDefinition sstoreActionPure(state: ExecutionState): ExecutionResultOr (ExecutionState * nat) := \n  flatMap\n  (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with \n      | (es, key, value) => \n        let storage := getStorage_ES es in\n        let updatedStorageES := setStorage_ES es (update (key, value) storage) in\n        match find key storage with \n         | Some w => \n          match (weqb w WZero, weqb value WZero)  with \n          | (true, true)  => runningExecutionWithState (es, 5000)\n          | (true, false) => runningExecutionWithState (updatedStorageES, 20000)\n          | (false, _) => runningExecutionWithState (setStorage_ES es (update (key, value) (getStorage_ES es)), 5000)\n          end\n         | None => runningExecutionWithState (updatedStorageES, 20000)\n        end\n      end\n    ).\n\nDefinition pcActionPure(state: ExecutionState)(programCounter: nat): OpcodeApplicationResult := \n  (pushItemToExecutionStateStack state (natToWord  WLen programCounter)).\n\nDefinition msizeActionPure(state: ExecutionState): OpcodeApplicationResult := \n  (pushItemToExecutionStateStack state (natToWord WLen (mapLength (getMemory_ES state)))).\n\nDefinition gasActionPure(state: ExecutionState)(gas: nat): OpcodeApplicationResult := \n  (pushItemToExecutionStateStack state (natToWord WLen gas)).\n\nDefinition pushActionPure(bytes: word 5)(w: EVMWord)(state: ExecutionState): OpcodeApplicationResult :=\n  let checkedWord := pushWordPass w (wordToNat bytes + 1) in \n  (pushItemToExecutionStateStack state checkedWord).\n\nDefinition dupActionPure(bytes: word 4)(state: ExecutionState):OpcodeApplicationResult := \n  flatMap\n  (peekNthItemFromStack state (wordToNat bytes)) \n  (fun item => \n    (pushItemToExecutionStateStack state item)\n  ).\n\nDefinition swapActionPure(bytes: word 4)(state: ExecutionState): OpcodeApplicationResult := \n   let stack := getStack_ES state in \n   match listSwapWithHead(stack)((wordToNat bytes) + 1)  with \n   | Some swappedStack => runningExecutionWithState (setStack_ES state swappedStack)\n   | None              => failWithErrorCode state BadPeekArg\n   end.\n\n\n(* LOG*) \n(* CREATE *)\n(* CALL *)\n(* CALLCODE*)\nDefinition returnActionPure(state: ExecutionState): ExecutionResult := \n    flatMap\n    (removeAndReturnFromStackTwoItemsEnder state)\n    (fun tup3 => \n      match tup3 with (* todo complete*)\n      | (es, offset, length) => \n        match getSliceFromMap (getMemory_ES es) offset (wordToNat length) with \n        | inl error => inl (ErrorneousExecutionResultMk error es)\n        | inr returndata  => inr (SuccessfulExecutionResultMkWithData es returndata)\n        end\n      end\n    ).\n\nDefinition jumpActionPure(state: ExecutionState)(program: list OpCode): OpcodeApplicationResult:= \n  flatMap\n  (removeAndReturnFromStackOneItem state)\n  (fun tup2 => \n    match tup2 with  \n    | (es, pos) => \n      if N.ltb (wordToN pos) (N.of_nat (length program)) \n      then \n        let posNat := wordToNat pos in\n        match nth_error program posNat with\n        | Some(SimplePriceOpcodeMk JUMPDEST) => runningExecutionWithState (setPc_ES es posNat)\n        | _ => failWithErrorCode es InvalidJumpDest\n        end\n      else failWithErrorCode es InvalidJumpDest\n    end\n  ).\n\nDefinition jumpiActionPure(state: ExecutionState)(program: list OpCode): OpcodeApplicationResult:= \n  flatMap\n  (removeAndReturnFromStackTwoItems state)\n  (fun tup3 => \n    match tup3 with  \n    | (es, pos, cond) => \n      if weqb cond WZero \n      then runningExecutionWithState es  \n      else if N.ltb (wordToN pos) (N.of_nat (length program)) \n           then\n             let posNat := wordToNat pos in\n             match nth_error program posNat with\n             | Some(SimplePriceOpcodeMk JUMPDEST) => runningExecutionWithState (setPc_ES es posNat)\n             | _ => failWithErrorCode es InvalidJumpDest\n             end\n           else failWithErrorCode es InvalidJumpDest\n    end\n  ).\n\nDefinition calldatacopyActionPure(state: ExecutionState)(ci: CallInfo): ExecutionResultOr (ExecutionState * nat) := \n  flatMap\n  (removeAndReturnFromStackThreeItems state) \n  (fun tup4 => \n    match tup4 with \n    | (es, destOffset, offset, length) => \n      match getSliceFromList (get_calldata ci) (wordToNat offset) (wordToNat length) with \n      | Some words => runningExecutionWithState ((insertItemsIntoMemory es (wordToNat destOffset) words), 2 + (List.length words) * 3)\n      | None       => failWithErrorCode es NonexistentCallDataCell\n      end\n    end)\n.\n\nDefinition codecopyActionPure(state: ExecutionState)(ci: CallInfo): ExecutionResultOr (ExecutionState * nat):= \n  flatMap\n  (removeAndReturnFromStackThreeItems state) \n  (fun tup4 => \n    match tup4 with \n    | (es, destOffset, offset, length) => \n      match getSliceFromList (get_thisContractCode ci) (wordToNat offset) (wordToNat length) with \n      | Some words => runningExecutionWithState ((insertItemsIntoMemory es (wordToNat destOffset) (zipListOfBytesIntoListOfWords words)), 2 + (List.length words) * 3)\n      | None       => failWithErrorCode es NonexistentCallDataCell\n      end\n    end)\n.\n\nDefinition extcodecopyActionPure(state: ExecutionState)(ci: CallInfo): ExecutionResultOr (ExecutionState * nat) := \n  flatMap\n  (removeAndReturnFromStackFourItems state) \n  (fun tup5 => \n    match tup5 with \n    | (es, addr, destOffset, offset, length) => \n      match find addr (getContractMap_ES es) with \n      | Some contract => \n        match getSliceFromList (contract) (wordToNat offset) (wordToNat length) with \n        | Some words => runningExecutionWithState ((insertItemsIntoMemory es (wordToNat destOffset) (zipListOfBytesIntoListOfWords words)), 700 + (List.length words) * 3)\n        | None       => failWithErrorCode es NonexistentCallDataCell\n        end\n      | None => failWithErrorCode es NonexistentContract\n      end\n    end)\n.\n\nDefinition log0ActionPure(state: ExecutionState): ExecutionResultOr (ExecutionState * nat) := \n  flatMap \n  (removeAndReturnFromStackTwoItems state) \n  (fun tup3 => \n    match tup3 with\n    | (es, offset, length) => \n      match getSliceFromMap (getMemory_ES es) offset (wordToNat length) with \n        | inl error => failWithErrorCode es error \n        | inr logData  => \n          let log := Log0 logData in \n          let logs := getLog_ES es in \n          let es2 := setLog_ES es logs in\n            runningExecutionWithState (es2, 375 + (List.length logData * 8 * 32))\n        end\n      end\n    ).\n\nDefinition log1ActionPure(state: ExecutionState): ExecutionResultOr (ExecutionState * nat) := \n  flatMap \n  (removeAndReturnFromStackThreeItems state) \n  (fun tup4 => \n    match tup4 with\n    | (es, offset, length, topic0) => \n      match getSliceFromMap (getMemory_ES es) offset (wordToNat length) with \n        | inl error => failWithErrorCode es error \n        | inr logData  => \n          let log := Log1 topic0 logData  in \n          let logs := getLog_ES es in \n          let es2 := setLog_ES es logs in\n            runningExecutionWithState (es2, 2 * 375 + (List.length logData * 8 * 32))\n        end\n      end\n    ).\n\nDefinition log2ActionPure(state: ExecutionState): ExecutionResultOr (ExecutionState * nat) := \n  flatMap \n  (removeAndReturnFromStackFourItems state) \n  (fun tup5 => \n    match tup5 with\n    | (es, offset, length, topic0, topic1) => \n      match getSliceFromMap (getMemory_ES es) offset (wordToNat length) with \n        | inl error => failWithErrorCode es error \n        | inr logData  => \n          let log := Log2 topic0 topic1 logData  in \n          let logs := getLog_ES es in \n          let es2 := setLog_ES es logs in\n            runningExecutionWithState (es2, 3 * 375  + (List.length logData * 8 * 32))\n        end\n      end\n    ).\n\nDefinition log3ActionPure(state: ExecutionState): ExecutionResultOr (ExecutionState * nat) := \n  flatMap \n  (removeAndReturnFromStackFiveItems state) \n  (fun tup6 => \n    match tup6 with\n    | (es, offset, length, topic0, topic1, topic2) => \n      match getSliceFromMap (getMemory_ES es) offset (wordToNat length) with \n        | inl error => failWithErrorCode es error \n        | inr logData  => \n          let log := Log3 topic0 topic1 topic2 logData  in \n          let logs := getLog_ES es in \n          let es2 := setLog_ES es logs in\n            runningExecutionWithState  (es2, 4 * 375  + (List.length logData * 8 * 32))\n        end\n      end\n    ).\n\nDefinition log4ActionPure(state: ExecutionState): ExecutionResultOr (ExecutionState * nat)  := \n  flatMap \n  (removeAndReturnFromStackSixItems state) \n  (fun tup6 => \n    match tup6 with\n    | (es, offset, length, topic0, topic1, topic2, topic3) => \n      match getSliceFromMap (getMemory_ES es) offset (wordToNat length) with \n        | inl error => failWithErrorCode es error \n        | inr logData  => \n          let log := Log4 topic0 topic1 topic2 topic3 logData  in \n          let logs := getLog_ES es in \n          let es2 := setLog_ES es logs in\n            runningExecutionWithState  (es2, 5 * 375  + (List.length logData * 8 * 32))\n        end\n      end\n    ).\n\n(*DELEGATECALL*)\n(*SELFDESTRUCT*)\nDefinition expCost(pow: word WLen): nat := \n  if weqb pow WZero \n  then 10%nat\n  else 10%nat + 10%nat * (1%nat + ((log2Orzero pow)/ 8%nat)).\n\nDefinition expActionPure(state: ExecutionState): ExecutionResultOr (ExecutionState * nat)  :=\n  flatMap \n  (removeAndReturnFromStackTwoItems state)\n    (fun tup3 => \n      match tup3 with  \n      | (es, a, pow) => \n        let resN := expmod (wordToN a) (wordToN pow) (wordModulus) in \n        let res := NToWord WLen resN in\n        attach (pushItemToExecutionStateStack es res) (expCost pow)\n      end\n    ).\n\nDefinition opcodeProgramStateChange(opc: SimplePriceOpcode)(state: ExecutionState)(ci: CallInfo)(gas pc: nat)(program: list OpCode): OpcodeApplicationResult := \n  match opc with \n  | ADD\t          => addActionPure state\n  | MUL\t          => mulActionPure state\n  | SUB\t          => subActionPure state\n  | DIV\t          => divActionPure state\n  | SDIV\t        => sdivActionPure state\n  | MOD\t          => modActionPure state\n  | SMOD\t        => smodActionPure state \n  | ADDMOD\t      => addmodActionPure state \n  | MULMOD\t      => mulmodActionPure state\n  | SIGNEXTEND\t  => signextendActionPure state\n  | LT\t          => ltActionPure state\n  | GT\t          => gtActionPure state\n  | SLT\t          => sltActionPure state\n  | SGT\t          => sgtActionPure state\n  | EQ\t          => eqActionPure state\n  | ISZERO\t      => iszeroActionPure state\n  | AND\t          => andActionPure state\n  | OR\t          => orActionPure state\n  | XOR\t          => xorActionPure state\n  | NOT\t          => notActionPure state\n  | BYTE          => byteActionPure state\n  | ADDRESS\t      => addressActionPure state ci\n  | BALANCE\t      => balanceActionPure state ci\n  | ORIGIN\t      => originActionPure state ci\n  | CALLER\t      => callerActionPure state ci\n  | CALLVALUE\t    => callvalueActionPure state ci\n  | CALLDATALOAD\t=> calldataloadActionPure state ci\n  | CALLDATASIZE\t=> calldatasizeActionPure state ci\n  | CODESIZE\t    => codesizeActionPure state ci\n  | GASPRICE\t    => gaspriceActionPure state ci\n  | EXTCODESIZE\t  => exctcodesizeActionPure state ci\n  | BLOCKHASH\t    => blockhashActionPure state ci\n  | COINBASE\t    => coinbaseActionPure state ci\n  | TIMESTAMP\t    => timestampActionPure state ci\n  | NUMBER\t      => numberActionPure state ci\n  | DIFFICULTY  \t=> dificultyActionPure state ci\n  | GASLIMIT\t    => gaslimitActionPure state ci\n  | POP\t          => popActionPure state\n  | MLOAD\t        => mloadActionPure state\n  | MSTORE\t      => mstoreActionPure state\n  | MSTORE8\t      => mstore8ActionPure state\n  | SLOAD\t        => sloadActionPure state\n  | PC\t          => pcActionPure state pc \n  | MSIZE\t        => msizeActionPure state\n  | GAS\t          => gasActionPure state gas \n  | JUMPDEST\t    => runningExecutionWithState state\n  | PUSH arg word\t=> pushActionPure arg word state\n  | DUP arg\t      => dupActionPure arg state\n  | SWAP\targ     => swapActionPure arg state\n  | CREATE\t      => failWithErrorCode state NotImplemented\n  | JUMP          => jumpActionPure state program\n  | JUMPI         => jumpiActionPure state program\n(*   | _   => stopExecutionWithSuccess (state) *)\n  end.\n\n\nDefinition opcodeProgramStateChangeComplex(opc: ComplexPriceOpcode)(state: ExecutionState)(ci: CallInfo)(gas pc: nat)(program: list OpCode): ExecutionResultOr (ExecutionState* nat) := \n  match opc with \n  |\tEXP           => expActionPure state\n  |\tSHA3          => failWithErrorCode state NotImplemented\n  |\tCALLDATACOPY  => calldatacopyActionPure state ci\n  |\tCODECOPY      => codecopyActionPure state ci\n  |\tEXTCODECOPY   => extcodecopyActionPure state ci\n  |\tSSTORE        => sstoreActionPure state \n  |\tLOG0          => log0ActionPure state \n  |\tLOG1          => log1ActionPure state \n  |\tLOG2          => log2ActionPure state \n  |\tLOG3          => log3ActionPure state \n  |\tLOG4          => log4ActionPure state \n  |\tCALL          => failWithErrorCode state NotImplemented\n  |\tCALLCODE      => failWithErrorCode state NotImplemented\n  |\tDELEGATECALL  => failWithErrorCode state NotImplemented\n  |\tSELFDESTRUCT  => failWithErrorCode state NotImplemented\n  end.\n\n\n\n\n(* Super ugly but i don't wan to bother with well-founded stuff.*)\n(* Check Nat.eqb.\nCheck bool. *)\n\nFixpoint actOpcode(gas programCounter: nat)(ec: ExecutionState)(program: list OpCode)(callInfo: CallInfo){struct gas}: ExecutionResult :=\n    match gas with \n    | S predGas => \n      match (nth_error program programCounter) with \n      | Some opc => \n        match opc with \n        | STOP                        => inr (SuccessfulExecutionResultMk ec)\n        |\tRETURN\t                    => returnActionPure ec\n        | ComplexPriceOpcodeMk opcode => \n          match opcodeProgramStateChangeComplex opcode ec callInfo gas programCounter program with\n          | inl result => inr (SuccessfulExecutionResultMk ec)\n          | inr (updatedState, reducedGas) => \n            actOpcode (predGas - (reducedGas) - 1) (S programCounter) updatedState program callInfo\n          end\n        | SimplePriceOpcodeMk opcode  => \n          match opcodeProgramStateChange opcode ec callInfo gas programCounter program with \n          | inl result       => result\n          | inr updatedState => (* reduce gas and go on*)(* gas - gasCost = (gas - 1) - (gasCost - 1)*)\n            actOpcode (predGas - ((simplePriceOpcodePrice opcode) -1)) (S programCounter) updatedState program callInfo\n          end\n        end\n      | None     => inl (ErrorneousExecutionResultMk InvalidJumpDest ec)\n      end\n    | O         => \n      match (Nat.eqb programCounter (S(length program))) with \n      | true  => inr (SuccessfulExecutionResultMk ec)\n      | false => inl (ErrorneousExecutionResultMk  OutOfGas ec)\n      end\n    end.\n\nFixpoint actOpcodeWithInstructionsLimitation(maxinstructions gas programCounter: nat)(ec: ExecutionState)(program: list OpCode)(callInfo: CallInfo){struct maxinstructions}: ExecutionResult :=\n    match maxinstructions with \n    | S instructionsLeft => \n      match (nth_error program programCounter) with \n      | Some opc => \n        match opc with \n        | STOP                        => inr (SuccessfulExecutionResultMk ec)\n        |\tRETURN\t                    => returnActionPure ec\n        | ComplexPriceOpcodeMk opcode => inr (SuccessfulExecutionResultMk ec) (* TODO change to the opcodes implementation*)\n        | SimplePriceOpcodeMk opcode  => \n          match opcodeProgramStateChange opcode ec callInfo gas programCounter program with \n          | inl result       => result\n          | inr updatedState => (* reduce gas and go on*)(* gas - gasCost = (gas - 1) - (gasCost - 1)*)\n            let gasLeft := gas - (simplePriceOpcodePrice opcode) in\n            let gasPositive := Nat.ltb (simplePriceOpcodePrice opcode) gas in \n            let gasZero := Nat.eqb gas (simplePriceOpcodePrice opcode) in \n            let over := Nat.eqb programCounter (S(length program)) in \n              match (gasPositive, gasZero, over) with \n              | (true, _, _)     => actOpcodeWithInstructionsLimitation (instructionsLeft)(gasLeft)(S programCounter) updatedState program callInfo\n              | (_, true, true)  => inr (SuccessfulExecutionResultMk ec)\n              | (false, _, _)    => inl (ErrorneousExecutionResultMk  OutOfGas ec)\n              end\n            \n          end\n        end\n      | None     => inl (ErrorneousExecutionResultMk InvalidJumpDest ec)\n      end\n    | O         => \n      match (Nat.eqb programCounter (S(length program))) with \n      | true  => inr (SuccessfulExecutionResultMk ec)\n      | false => inl (ErrorneousExecutionResultMk  OutOfGas ec)\n      end\n    end. \n(* Facts about opcodes *)\n\nDefinition rightProj{A B: Type}(s: A+B): option B := \nmatch s with\n| inr b => Some b\n| inl _ => None\nend.\n\nLemma liftedSome{T: Type}: forall t1 t2: T, t1 = t2 <-> Some t1 = Some t2. Proof.\nintros.\nsplit.\nintros.\nrewrite H.\ntrivial.\nintros.\ninjection H as H.\napply H. \nDefined.\n\nLemma liftSome{T: Type}: forall t1 t2: T, t1 = t2 -> Some t1 = Some t2. Proof.\napply liftedSome.\nDefined.\n\nLemma unliftSome{T: Type}: forall t1 t2: T, Some t1 = Some t2 -> t1 =t2. Proof.\napply liftedSome.\nDefined.\n\nLemma listsEqualHeads{T: Type}: forall t1 t2: T, forall tail: list T, t1 :: tail = t2 :: tail <-> t1 = t2. Proof.\nintros.\nsplit. \nintros.\ninjection H as H.\nrewrite H.\ntrivial.\nintros.\nrewrite H.\ntrivial.\nDefined.\n\nLemma listLengthApp{T: Type}: forall h: T, forall l t: list T, h :: t = l -> length l = S (length t). Proof.\nintros. \nintros.\nrewrite <- H.\n(* cut (forall T: Type, forall t: T, forall tail: list T, (t :: nil) ++ tail = t :: tail). *)\ncut (h :: t = (h :: nil) ++ t). intros. rewrite H0. rewrite app_length.\ncut (length (h :: nil) = 1). intros. rewrite H1.\ntrivial. \nunfold length.\ntrivial.\nunfold app.\ntrivial.\nDefined.\n\nLemma natLtbPlusOne: forall n m: nat, n <? m = true -> S n <? S m = true.\nProof.\nintros.\ntauto.\nQed.\n\nLemma listAppLength{T: Type}: forall n: nat, forall h t l: list T, length l < n -> l = h ++ t -> length (t) < n. Proof.\nintros.\nrewrite H0 in H.\nrewrite app_length in H.\nlia.\nQed.\n\nLemma rightCrossover: forall n m: nat, n < m -> n <? m = true. Proof.\nAdmitted. \n\nLemma leftCrossover: forall n m: nat, n <? m = true -> n < m. Proof.\nAdmitted.\nLtac unfoldUtilDefinitions := \nunfold \nmapO, rightProj,attach, \"*\",\ngetStack_ES, removeAndReturnFromStackOneItem, removeAndReturnFromStackTwoItems, removeAndReturnFromStackThreeItems, pushItemToExecutionStateStack, \ngetStack_ES, failWithErrorCode, runningExecutionWithState, setStack_ES, flatMap.\n\nLtac unfoldUtilDefinitionsIn H := \nunfold \nmapO, rightProj, attach, \"*\",\ngetStack_ES, removeAndReturnFromStackOneItem, removeAndReturnFromStackTwoItems, removeAndReturnFromStackThreeItems, pushItemToExecutionStateStack, failWithErrorCode, runningExecutionWithState, setStack_ES, flatMap in H.\n\nLtac cutRewrite bla hname:=  \ncut(bla); only 1 : intro hname; only 1 :rewrite hname.\n\nLtac cutRewriteInL bla hname hnameTarg:=  \ncut(bla); only 1 : intro hname; only 1 : rewrite <- hname in hnameTarg.\n\nLtac cutRewriteInR bla hname hnameTarg:=  \ncut(bla); only 1 : intro hname; only 1 : rewrite -> hname in hnameTarg.\n\n\nTheorem addActionPureSuccess:\nforall es: ExecutionState, \nforall w1 w2: EVMWord,\nforall tail: list EVMWord,\nlet preStack := getStack_ES es in\nlet post := addActionPure es in\nlet postStack := mapO (rightProj post) (getStack_ES) in\nlength preStack < 1024 -> preStack = w1 :: w2 :: tail ->\npostStack = Some(wplus w1 w2 :: tail).\nProof.\nintros es w1 w2 tail preStack post postStack H H0.\ndestruct es.\nsubst preStack. subst postStack. subst post.\nunfold addActionPure.\nunfoldUtilDefinitions.\nunfoldUtilDefinitionsIn H.\nunfoldUtilDefinitionsIn H0.\nrewrite H0. \ncutRewrite (length tail <? 1024 = true) H1.\nrewrite <- liftedSome.\nrewrite listsEqualHeads.\ntrivial.\ncutRewriteInL ((w1 :: w2 :: nil) ++ tail = w1 :: w2 :: tail) H1 H0. rewrite H0 in H.\nrewrite rightCrossover. trivial.\napply (listAppLength 1024 (w1 :: w2 :: nil) tail l).\nrewrite <- H0 in H.\napply H.\nassumption.\nunfold \"++\".\ntrivial.\nQed.\n\n\nTheorem mulActionPureSuccess: \nforall es: ExecutionState, \nforall w1 w2: EVMWord,\nforall tail: list EVMWord,\nlet preStack := getStack_ES es in\nlet post := mulActionPure es in\nlet postStack := mapO (rightProj post) (getStack_ES) in\nlength preStack < 1024 -> preStack = w1 :: w2 :: tail ->\npostStack = Some(wmult w1 w2 :: tail). Proof.\nintros es w1 w2 tail preStack post postStack H H0.\ndestruct es.\nsubst preStack. subst postStack. subst post.\nunfold mulActionPure.\nunfoldUtilDefinitions.\nunfoldUtilDefinitionsIn H.\nunfoldUtilDefinitionsIn H0.\nrewrite H0. \ncutRewrite (length tail <? 1024 = true) H1.\nrewrite <- liftedSome.\nrewrite listsEqualHeads.\ntrivial.\ncutRewriteInL ((w1 :: w2 :: nil) ++ tail = w1 :: w2 :: tail) H1 H0. rewrite H0 in H.\nrewrite rightCrossover. trivial.\napply (listAppLength 1024 (w1 :: w2 :: nil) tail l).\nrewrite <- H0 in H.\napply H.\nassumption.\nunfold \"++\".\ntrivial.\nQed.\n\nTheorem subActionPureSuccess: \nforall es: ExecutionState, \nforall w1 w2: EVMWord,\nforall tail: list EVMWord,\nlet preStack := getStack_ES es in\nlet post := subActionPure es in\nlet postStack := mapO (rightProj post) (getStack_ES) in\nlength preStack < 1024 -> preStack = w1 :: w2 :: tail ->\npostStack = Some(wordSubModulus w1 w2 :: tail). Proof.\nintros es w1 w2 tail preStack post postStack H H0.\ndestruct es.\nsubst preStack. subst postStack. subst post.\nunfold subActionPure.\nunfoldUtilDefinitions.\nunfoldUtilDefinitionsIn H.\nunfoldUtilDefinitionsIn H0.\nrewrite H0. \ncutRewrite (length tail <? 1024 = true) H1.\nrewrite <- liftedSome.\nrewrite listsEqualHeads.\ntrivial.\ncutRewriteInL ((w1 :: w2 :: nil) ++ tail = w1 :: w2 :: tail) H1 H0. rewrite H0 in H.\nrewrite rightCrossover. trivial.\napply (listAppLength 1024 (w1 :: w2 :: nil) tail l).\nrewrite <- H0 in H.\napply H.\nassumption.\nunfold \"++\".\ntrivial.\nQed.\n\nTheorem divActionPureSuccess: \nforall es: ExecutionState, \nforall w1 w2: EVMWord,\nforall tail: list EVMWord,\nlet preStack := getStack_ES es in\nlet post := divActionPure es in\nlet postStack := mapO (rightProj post) (getStack_ES) in\nlength preStack < 1024 -> preStack = w1 :: w2 :: tail ->\npostStack = Some(wdiv w1 w2 :: tail). Proof.\nintros es w1 w2 tail preStack post postStack H H0.\ndestruct es.\nsubst preStack. subst postStack. subst post.\nunfold divActionPure.\nunfoldUtilDefinitions.\nunfoldUtilDefinitionsIn H.\nunfoldUtilDefinitionsIn H0.\nrewrite H0. \ncutRewrite (length tail <? 1024 = true) H1.\nrewrite <- liftedSome.\nrewrite listsEqualHeads.\ntrivial.\ncutRewriteInL ((w1 :: w2 :: nil) ++ tail = w1 :: w2 :: tail) H1 H0. rewrite H0 in H.\nrewrite rightCrossover. trivial.\napply (listAppLength 1024 (w1 :: w2 :: nil) tail l).\nrewrite <- H0 in H.\napply H.\nassumption.\nunfold \"++\".\ntrivial.\nQed.\n\nTheorem sdivActionPureSuccess: \nforall es: ExecutionState, \nforall w1 w2: EVMWord,\nforall tail: list EVMWord,\nlet preStack := getStack_ES es in\nlet post := sdivActionPure es in\nlet postStack := mapO (rightProj post) (getStack_ES) in\nlength preStack < 1024 -> preStack = w1 :: w2 :: tail ->\npostStack = Some(wdivZ w1 w2 :: tail). Proof.\nintros es w1 w2 tail preStack post postStack H H0.\ndestruct es.\nsubst preStack. subst postStack. subst post.\nunfold sdivActionPure.\nunfoldUtilDefinitions.\nunfoldUtilDefinitionsIn H.\nunfoldUtilDefinitionsIn H0.\nrewrite H0. \ncutRewrite (length tail <? 1024 = true) H1.\nrewrite <- liftedSome.\nrewrite listsEqualHeads.\ntrivial.\ncutRewriteInL ((w1 :: w2 :: nil) ++ tail = w1 :: w2 :: tail) H1 H0. rewrite H0 in H.\nrewrite rightCrossover. trivial.\napply (listAppLength 1024 (w1 :: w2 :: nil) tail l).\nrewrite <- H0 in H.\napply H.\nassumption.\nunfold \"++\".\ntrivial.\nQed.\n\nTheorem modActionPureSuccess: \nforall es: ExecutionState, \nforall w1 w2: EVMWord,\nforall tail: list EVMWord,\nlet preStack := getStack_ES es in\nlet post := modActionPure es in\nlet postStack := mapO (rightProj post) (getStack_ES) in\nlength preStack < 1024 -> preStack = w1 :: w2 :: tail ->\npostStack = Some(wmod w1 w2 :: tail). Proof.\nintros es w1 w2 tail preStack post postStack H H0.\ndestruct es.\nsubst preStack. subst postStack. subst post.\nunfold modActionPure.\nunfoldUtilDefinitions.\nunfoldUtilDefinitionsIn H.\nunfoldUtilDefinitionsIn H0.\nrewrite H0. \ncutRewrite (length tail <? 1024 = true) H1.\nrewrite <- liftedSome.\nrewrite listsEqualHeads.\ntrivial.\ncutRewriteInL ((w1 :: w2 :: nil) ++ tail = w1 :: w2 :: tail) H1 H0. rewrite H0 in H.\nrewrite rightCrossover. trivial.\napply (listAppLength 1024 (w1 :: w2 :: nil) tail l).\nrewrite <- H0 in H.\napply H.\nassumption.\nunfold \"++\".\ntrivial.\nQed.\n\nTheorem smodActionPureSuccess: \nforall es: ExecutionState, \nforall w1 w2: EVMWord,\nforall tail: list EVMWord,\nlet preStack := getStack_ES es in\nlet post := smodActionPure es in\nlet postStack := mapO (rightProj post) (getStack_ES) in\nlet res := ZToWord WLen (Z.rem (wordToZ w1) (wordToZ w2)) in\nlength preStack < 1024 -> preStack = w1 :: w2 :: tail ->\npostStack = Some(res :: tail). Proof.\nintros es w1 w2 tail preStack post postStack res H H0.\ndestruct es.\nsubst preStack. subst postStack. subst post. subst res.\nunfold smodActionPure.\nunfoldUtilDefinitions.\nunfoldUtilDefinitionsIn H.\nunfoldUtilDefinitionsIn H0.\nrewrite H0. \ncutRewrite (length tail <? 1024 = true) H1.\nrewrite <- liftedSome.\nrewrite listsEqualHeads.\ntrivial.\ncutRewriteInL ((w1 :: w2 :: nil) ++ tail = w1 :: w2 :: tail) H1 H0. rewrite H0 in H.\nrewrite rightCrossover. trivial.\napply (listAppLength 1024 (w1 :: w2 :: nil) tail l).\nrewrite <- H0 in H.\napply H.\nassumption.\nunfold \"++\".\ntrivial.\nQed.\n\nTheorem addmodActionPureSuccess: \nforall es: ExecutionState, \nforall w1 w2 w3: EVMWord,\nforall tail: list EVMWord,\nlet preStack := getStack_ES es in\nlet post := addmodActionPure es in\nlet postStack := mapO (rightProj post) (getStack_ES) in\nlet res := ZToWord WLen (Z.rem ((wordToZ w1) + (wordToZ w2)) (Z.of_N (wordToN w3))) in\nlength preStack < 1024 -> preStack = w1 :: w2 :: w3 :: tail ->\npostStack = Some(res  :: tail). Proof.\nintros es w1 w2 w3 tail preStack post postStack res H H0.\ndestruct es.\nsubst preStack. subst postStack. subst post. subst res.\nunfold addmodActionPure.\nunfoldUtilDefinitions.\nunfoldUtilDefinitionsIn H.\nunfoldUtilDefinitionsIn H0.\nrewrite H0. \ncutRewrite (length tail <? 1024 = true) H1.\nrewrite <- liftedSome.\nrewrite listsEqualHeads.\ntrivial.\ncutRewriteInL ((w1 :: w2 :: w3 :: nil) ++ tail = w1 :: w2 :: w3 :: tail) H1 H0. rewrite H0 in H.\nrewrite rightCrossover. trivial.\napply (listAppLength 1024 (w1 :: w2 :: w3 :: nil) tail l).\nrewrite <- H0 in H.\napply H.\nassumption.\nunfold \"++\".\ntrivial.\nQed.\n\nTheorem mulmodActionPureSuccess: \nforall es: ExecutionState, \nforall w1 w2 w3: EVMWord,\nforall tail: list EVMWord,\nlet preStack := getStack_ES es in\nlet post := mulmodActionPure es in\nlet postStack := mapO (rightProj post) (getStack_ES) in\nlet res := ZToWord WLen (Z.rem ((wordToZ w1) * (wordToZ w2)) (Z.of_N (wordToN w3))) in\nlength preStack < 1024 -> preStack = w1 :: w2 :: w3 :: tail ->\npostStack = Some(res  :: tail). Proof.\nintros es w1 w2 w3 tail preStack post postStack res H H0.\ndestruct es.\nsubst preStack. subst postStack. subst post. subst res.\nunfold mulmodActionPure.\nunfoldUtilDefinitions.\nunfoldUtilDefinitionsIn H.\nunfoldUtilDefinitionsIn H0.\nrewrite H0. \ncutRewrite (length tail <? 1024 = true) H1.\nrewrite <- liftedSome.\nrewrite listsEqualHeads.\ntrivial.\ncutRewriteInL ((w1 :: w2 :: w3 :: nil) ++ tail = w1 :: w2 :: w3 :: tail) H1 H0. rewrite H0 in H.\nrewrite rightCrossover. trivial.\napply (listAppLength 1024 (w1 :: w2 :: w3 :: nil) tail l).\nrewrite <- H0 in H.\napply H.\nassumption.\nunfold \"++\".\ntrivial.\nQed.\n\n\nTheorem expActionPureSuccess: \nforall es: ExecutionState, \nforall w1 w2: EVMWord,\nforall tail: list EVMWord,\nlet preStack := getStack_ES es in\nlet post := expActionPure es in\nlet postStack := mapO (rightProj post) (fst * getStack_ES) in\nlet res := NToWord WLen (expmod (wordToN w1) (wordToN w2) (wordModulus)) in\nlength preStack < 1024 -> preStack = w1 :: w2 :: tail ->\npostStack = Some(res :: tail). Proof.\nintros es w1 w2 tail preStack post postStack res H H0.\ndestruct es.\nsubst preStack. subst postStack. subst post. subst res.\nunfold expActionPure.\nunfoldUtilDefinitions.\nunfoldUtilDefinitionsIn H.\nunfoldUtilDefinitionsIn H0.\nrewrite H0.\nunfold \"*\" .\nunfold fst.\ncutRewrite (length tail <? 1024 = true) H1.\nunfold map.\nrewrite <- liftedSome.\nrewrite listsEqualHeads.\ntrivial.\ncutRewriteInL ((w1 :: w2 :: nil) ++ tail = w1 :: w2 :: tail) H1 H0. rewrite H0 in H.\nrewrite rightCrossover. trivial.\napply (listAppLength 1024 (w1 :: w2 :: nil) tail l).\nrewrite <- H0 in H.\napply H.\nassumption.\nunfold \"++\".\ntrivial.\nQed.\n\n\nTheorem signextendActionPureSuccess: \nforall es: ExecutionState, \nforall w1 w2: EVMWord,\nforall tail: list EVMWord,\nlet preStack := getStack_ES es in\nlet b := rightProj (extractByteAsNat w2) in\nlet res := mapO b (fun bb => sextWordBytes w1 bb) in\nlet post := signextendActionPure es in\nlet postStack := mapO (rightProj post) (getStack_ES) in\nlength preStack < 1024 -> weqb (wlshift' w2 8%nat) WZero = true -> preStack = w1 :: w2 :: tail ->\npostStack = mapO res (fun h => h :: tail). Proof.\nintros es w1 w2 tail preStack b res post postStack H H1 H0.\ndestruct es.\nsubst preStack. subst postStack. subst post. subst res. subst b. \nunfold signextendActionPure. \nunfoldUtilDefinitions.\nunfoldUtilDefinitionsIn H.\nunfoldUtilDefinitionsIn H0.\nrewrite H0.\nunfold extractByteAsNat.\nrewrite H1.\ncutRewrite (length tail <? 1024 = true) H2.\nrewrite <- liftedSome.\nrewrite listsEqualHeads.\ntrivial.\ncutRewriteInL ((w1 :: w2 :: nil) ++ tail = w1 :: w2 :: tail) H2 H0. rewrite H0 in H.\nrewrite rightCrossover. trivial.\napply (listAppLength 1024 (w1 :: w2 :: nil) tail l).\nrewrite <- H0 in H.\napply H.\nassumption.\nunfold \"++\".\ntrivial.\nQed.\n", "meta": {"author": "ivan71kmayshan27", "repo": "coq-evm", "sha": "ea40f62b5536c2a9229983b65c9ae85711d24a7e", "save_path": "github-repos/coq/ivan71kmayshan27-coq-evm", "path": "github-repos/coq/ivan71kmayshan27-coq-evm/coq-evm-ea40f62b5536c2a9229983b65c9ae85711d24a7e/evmModel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6699392803084773}}
{"text": "Require Export Andasl.\nRequire Export Andasr.\nSection ml.\nVariables A B C:Prop.\nTheorem Andas: and (and A B) C <-> and A (and B C).\nProof.\n    split.\n    (* intro H0. *)\n    apply Andasl.\n    (* assumption. *)\n    (* intro H1. *)\n    apply Andasr.\n    (* assumption. *)\nQed.\nEnd ml.\n\nCheck Andas.", "meta": {"author": "ya0201", "repo": "mycoq-learning", "sha": "cc25eeeb8ef82917af329d69c4ea079935155005", "save_path": "github-repos/coq/ya0201-mycoq-learning", "path": "github-repos/coq/ya0201-mycoq-learning/mycoq-learning-cc25eeeb8ef82917af329d69c4ea079935155005/acintui/Andas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6699392754159427}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nDefinition synth (x : natural) (y : natural) : natural := plus (Succ x) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_plus_commut_64_plus_succ/goal33conj63_coqofml_K7oZKL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6699392705234077}}
{"text": "Require Import Omega.\nRequire Import ineqchain.\nRequire Import Coq.Classes.Morphisms.\n\nFixpoint ack (x y : nat) : nat :=\n  match x with\n  | 0 => S y\n  | S x' => let fix ackn (y : nat) :=\n               match y with\n               | 0 => ack x' 1\n               | S y' => ack x' (ackn y')\n               end\n           in ackn y\n  end.\n\nProposition ack_1_y_eq_SSy :\n  forall (y : nat), ack 1 y = S (S y).\nProof.\n  induction y.\n  - @ goal : (ack 1 0 = 2).\n    Left\n    = 2.\n    = Right.\n  - @ goal : (ack 1 (S y) = S (S (S y))).\n    @ IHy  : (ack 1 y = S (S y)).\n    Left\n    = (ack 1 (S y)).\n    = (ack 0 (ack 1 y)).\n    = (ack 0 (S (S y)))      { by IHy }.\n    = (S (S (S y))).\n    = Right.\nQed.\n\nProposition ack_SSy_le_ack_Sx_y :\n  forall (x y : nat), S (S y) <= ack (S x) y.\nProof.\n  induction x.\n  - intros y.\n    @ goal : (S (S y) <= ack 1 y).\n    Left\n    = (S (S y)).\n    = (ack 1 y)   { by ack_1_y_eq_SSy }.\n    = Right.\n  - induction y.\n    + @ goal : (2 <= ack (S (S x)) 0).\n      @ IHx :\n        (forall y : nat, S (S y) <= ack (S x) y).\n      Right\n      =  (ack (S (S x)) 0).\n      =  (ack (S x) 1).\n      >= (S (S 1))         { by IHx }.\n      >= 2                 { omega }.\n      = Left.\n    + @ goal :\n        (S (S (S y)) <= ack (S (S x)) (S y)).\n      @ IHx  :\n        (forall y : nat, S (S y) <= ack (S x) y).\n      @ IHy  :\n        (S (S y) <= ack (S (S x)) y).\n      Right\n      =  (ack (S (S x)) (S y)).\n      =  (ack (S x) (ack (S (S x)) y)).\n      >= (S (S (ack (S (S x)) y))) { by IHx }.\n      >= (S (S (S (S y))))         { by IHy }.\n      >= (S (S (S y)))             { omega }.\n      = Left.\nQed.\n\nProposition Sy_le_ack_x_y :\n  forall (x y : nat), y < ack x y.\nProof.\n  induction x.\n  - intros y.\n    @ goal : (y < ack 0 y).\n    Left\n    = y.\n    < (S y)            { omega }.\n    = Right.\n  - intros y.\n    @ goal : (y < ack (S x) y).\n    Right\n    =  (ack (S x) y).\n    >= (S (S y))       { by ack_SSy_le_ack_Sx_y }.\n    >  y               { omega }.\n    = Left.\nQed.\n\nProposition ack_x_y_lt_ack_x_Sy :\n  forall (x y : nat), ack x y < ack x (S y).\nProof.\n  induction x.\n  - intros y.\n    @ goal : (ack 0 y < ack 0 (S y)).\n    Right\n    = (ack 0 (S y)).\n    = (S (S y)).\n    > (S y)  { omega }.\n    = (ack 0 y).\n    = Left.\n  - intros y.\n    @ goal : (ack (S x) y < ack (S x) (S y)).\n    Right\n    =  (ack (S x) (S y)).\n    =  (ack x (ack (S x) y)).\n    >  (ack (S x) y)     { by Sy_le_ack_x_y }.\n    =  Left.\nQed.\n\nProgram Instance ack_monotone_y : Proper (eq ++> le ++> le) (ack).\nNext Obligation.\nProof.\n  unfold respectful.\n  intros x y H x0 y0 H0.\n  rewrite H.\n  induction H0.\n  - reflexivity.\n  - Left\n    =  (ack y x0).\n    <= (ack y m)     { by IHle }.\n    <= (ack y (S m)) { by ack_x_y_lt_ack_x_Sy }.\n    =  Right.\nQed.\n\nProposition ack_x_Sy_le_ack_Sx_y :\n  forall (x y : nat), ack x (S y) <= ack (S x) y.\nProof.\n  intros x y; revert x.\n  induction y.\n  - intros x.\n    @ goal : (ack x 1 <= ack (S x) 0).\n    Left\n    = (ack (S x) 0).\n    = (ack x 1).\n    = Right.\n  - intros x.\n    @ goal : (ack x (S (S y)) <= ack (S x) (S y)).\n    @ IHy  : (forall x : nat, ack x (S y) <= ack (S x) y).\n    Left\n    =  (ack x (S (S y))).\n    <= (ack x (ack (S x) y))  { by ack_SSy_le_ack_Sx_y }.\n    =  (ack (S x) (S y)).\n    =  Right.\nQed.\n\nProposition ack_x_y_le_ack_Sx_y :\n  forall (x y : nat), ack x y < ack (S x) y.\nProof.\n  intros x y.\n  Left\n  =  (ack x y).\n  <  (ack x (S y)) { by ack_x_y_lt_ack_x_Sy }.\n  <= (ack (S x) y) { by ack_x_Sy_le_ack_Sx_y }.\n  =  Right.\nQed.\n\nProgram Instance ack_monotone_x : Proper (le ++> eq ++> le) (ack).\nNext Obligation.\nProof.\n  unfold respectful.\n  intros x y H x0 y0 H0.\n  rewrite H0.\n  induction H.\n  - reflexivity.\n  - Left\n    =  (ack x y0).\n    <= (ack m y0)     { by IHle }.\n    <= (ack (S m) y0) { by ack_x_y_le_ack_Sx_y }.\n    =  Right.\nQed.\n\nProposition ack_c1_ack_c2_x_le_ack_c3_x :\n  forall (x c1 c2 : nat), exists (c3 : nat),\n      ack c1 (ack c2 x) <= ack c3 x.\nProof.\n  intros x c1 c2.\n  exists (S (S (max c1 c2))).\n  Left\n  =  (ack c1 (ack c2 x)).\n  <= (ack (max c1 c2) (ack c2 x))\n       { because (c1 <= max c1 c2) by (apply Nat.le_max_l) }.\n  <= (ack (max c1 c2) (ack (S (max c1 c2)) x))\n       { because (c2 <= S (max c1 c2)) by (rewrite <- Nat.le_max_r; omega) }.\n  =  (ack (S (max c1 c2)) (S x)).\n  <= (ack (S (S (max c1 c2))) x)  { by ack_x_Sy_le_ack_Sx_y }.\n  =  Right.\nQed.", "meta": {"author": "MurataKosuke", "repo": "Inequality", "sha": "190085c656a68fa55e9bf9388728b392806eaa2b", "save_path": "github-repos/coq/MurataKosuke-Inequality", "path": "github-repos/coq/MurataKosuke-Inequality/Inequality-190085c656a68fa55e9bf9388728b392806eaa2b/ack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6699200011588482}}
{"text": "\nCoInductive CoNat : Set := \n| Zero : CoNat\n| Succ : CoNat -> CoNat.\n\nCoInductive CoEq : CoNat -> CoNat -> Prop := \n| coeq_base : CoEq Zero Zero\n| coeq_next : forall x y, CoEq x y -> CoEq (Succ x) (Succ y).\n\n(* assists with deconstruction in proofs *)\nDefinition decomp (x : CoNat) : CoNat := \n  match x with \n    | Zero => Zero\n    | Succ x' => Succ x'\n  end.\n\nLemma decomp_eql : forall x, x = decomp x.\n  intro x. case x. simpl. auto.\n  intros. simpl. auto.\nDefined.    \n\nCoFixpoint plus (x: CoNat) (y: CoNat) : CoNat := \n  match x with \n    | Zero => y \n    | Succ x' => Succ (plus x' y)\n  end.\n\nRequire Import List. \nFixpoint sum (xs:list CoNat) : CoNat := \n  match xs with \n    | nil => Zero\n    | cons x xs' => plus x (sum xs')\n  end.\n\nCoInductive CoList : Set := \n| CoNil : CoList \n| CoCons : CoNat -> CoList -> CoList.\n\nDefinition decompl (xs : CoList) : CoList := \n  match xs with \n    | CoNil => CoNil\n    | CoCons x' xs' => CoCons x' xs'\n  end.\n\nLemma decompl_eql : forall x, x = decompl x.\n  intro x. case x. simpl. auto.\n  intros. simpl. auto.\nDefined.    \n\n(* \nCoFixpoint sumlen (xs: CoList) : CoNat := \n  match xs with \n    | CoNil => Zero \n    | CoCons x' xs' => Succ (plus x' (sumlen xs'))\n  end.\n*)\n\nCoFixpoint f (x : CoNat) (xs : CoList) := \n  match x with \n    | Zero => match xs with \n                | CoNil => Zero\n                | CoCons x' xs' => Succ (f x' xs')\n              end\n    | Succ x' => Succ (f x' xs)\n  end.\n\nDefinition sumlen (xs : CoList) := \n  match xs with\n    | CoNil => Zero \n    | CoCons x' xs' => Succ (f x' xs')\n  end.\n\nCoFixpoint f (x : CoNat) (xs : CoList) := \n  match x with \n    | Zero => match xs with \n                | CoNil => Zero\n                | CoCons x' xs' => Succ (f x' xs')\n              end\n    | Succ x' => Succ (f x' xs)\n  end.\n\nDefinition sum (xs : List) := \n  match xs with\n    | CoNil => Zero \n    | CoCons x' xs' => Succ (f x' xs')\n  end.\n\n\n\n\n\n\nInfix \"::\" := CoCons (at level 60, right associativity).\n\nLemma test : sumlen (Zero::Zero::(Succ((Succ(Zero))))::CoNil) = Succ(Succ(Succ(Zero))).\nProof.\n  intros. rewrite (decomp_eql (sumlen (Zero :: Zero :: Succ (Succ Zero) ::CoNil))). simpl.\n  rewrite (decomp_eql (f Zero (Zero :: Succ (Succ Zero) :: CoNil))). simpl.\n  rewrite (decomp_eql (f Zero (Succ (Succ Zero) :: CoNil))). simpl.\n  rewrite (decomp_eql (f (Succ (Succ Zero)) CoNil)). simpl.\n  rewrite (decomp_eql (f (Succ Zero) CoNil)). simpl.\n  rewrite (decomp_eql (f Zero CoNil)). simpl.\n\ng = (% x'. (% xs'. (case x' of \n                      | Succ(x') => Succ(((g x') xs'))\n                      | Zero => (f xs'))));\nf = (% xs. (case xs of \n              | Cons(x',xs') => case x' of \n                                  | Zero => Succ(f xs')\n                                  | Succ(x') => Succ(Succ(g x' xs'))\n              | Nil => Zero));\n\n", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/cosum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6699199914874944}}
{"text": "Require Import GeoCoq.Axioms.parallel_postulates.\nRequire Import GeoCoq.Tarski_dev.Annexes.suma.\nRequire Import GeoCoq.Tarski_dev.Ch12_parallel.\n\nSection weak_inverse_projection_postulate_bachmann_s_lotschnittaxiom.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\n(** Formalization of a proof from Bachmann's article \"Zur Parallelenfrage\" *)\n\nLemma weak_inverse_projection_postulate__bachmann_s_lotschnittaxiom :\n  weak_inverse_projection_postulate -> bachmann_s_lotschnittaxiom.\nProof.\nintro hrap.\ncut (forall A1 A2 B1 B2 C1 C2 D1 D2 IAB IAC IBD,\n        Perp A1 A2 B1 B2 -> Perp A1 A2 C1 C2 -> Perp B1 B2 D1 D2 ->\n        Col A1 A2 IAB -> Col B1 B2 IAB ->\n        Col A1 A2 IAC -> Col C1 C2 IAC ->\n        Col B1 B2 IBD -> Col D1 D2 IBD ->\n        Coplanar IAB IAC IBD C1 -> Coplanar IAB IAC IBD C2 ->\n        Coplanar IAB IAC IBD D1 -> Coplanar IAB IAC IBD D2 ->\n       ~ Col IAB IAC IBD ->\n        exists I, Col C1 C2 I /\\ Col D1 D2 I).\n\n  {\n  clear hrap; intro lotschnitt.\n  intros P Q R P1 R1 HPQ HQR HPerQ HPerP HPerR HCop1 HCop2.\n  destruct (eq_dec_points P P1).\n    subst; exists R; Col.\n  destruct (eq_dec_points R R1).\n    subst; exists P; Col.\n  assert (HNCol : ~ Col P Q R) by (apply per_not_col; auto).\n  destruct (lotschnitt P Q Q R P P1 R R1 Q P R) as [S [HS1 HS2]]; Col; Perp; Cop.\n  exists S; auto.\n  }\n\n  {\n  intros A1 A2 B1 B2 C1 C2 D1 D2 IAB IAC IBD HPerpAB HPerpAC HPerpBD.\n  intros HCol1 HCol2 HCol3 HCol4 HCol5 HCol6 HCop1 HCop2 HCop3 HCop4 HNC1.\n  assert (Col IAB IAC A1) by (assert_diffs; ColR).\n  assert (Col IAB IAC A2) by (assert_diffs; ColR).\n  assert (Col IAB IBD B1) by (assert_diffs; ColR).\n  assert (Col IAB IBD B2) by (assert_diffs; ColR).\n  assert (Coplanar IAB IAC IBD A1) by Cop.\n  assert (Coplanar IAB IAC IBD A2) by Cop.\n  assert (Coplanar IAB IAC IBD B1) by Cop.\n  assert (Coplanar IAB IAC IBD B2) by Cop.\n  assert (HNC2 : ~ Col A1 A2 D1).\n    {\n    apply par_strict_not_col_1 with D2; apply par_not_col_strict with IBD;\n    Col; try (intro; apply HNC1; assert_diffs; ColR).\n    apply l12_9 with B1 B2; Perp; CopR.\n    }\n  assert (HNC3 : ~ Col B1 B2 C1).\n    {\n    apply par_strict_not_col_1 with C2; apply par_not_col_strict with IAC;\n    Col; try (intro; apply HNC1; assert_diffs; ColR).\n    apply l12_9 with A1 A2; Perp; CopR.\n    }\n  assert (HParA : Par_strict A1 A2 D1 D2).\n    apply par_not_col_strict with D1; Col; apply l12_9 with B1 B2; Perp; CopR.\n  assert (HParB : Par_strict B1 B2 C1 C2).\n    apply par_not_col_strict with C1; Col; apply l12_9 with A1 A2; Perp; CopR.\n  assert (HNCol3 : ~ Col IAC B1 B2) by (apply par_not_col with C1 C2; Par; ColR).\n  assert (HNCol4 : ~ Col IBD A1 A2) by (apply par_not_col with D1 D2; Par; ColR).\n  assert (HNCol5 : ~ Col IAB C1 C2) by (apply par_not_col with B1 B2; Par; ColR).\n  assert (HNCol6 : ~ Col IAB D1 D2) by (apply par_not_col with A1 A2; Par; ColR).\n  assert (HPQ : IAC <> IAB) by (assert_diffs; auto).\n  assert (HQR : IAB <> IBD) by (assert_diffs; auto).\n  rename IAB into Q; rename IAC into P; rename IBD into R.\n  assert (Per P Q R).\n    {\n    apply perp_per_2; apply perp_col2 with A1 A2; Col;\n    apply perp_sym; apply perp_col2 with B1 B2; Col; Perp.\n    }\n  assert (HNCol7 : ~ Col P Q R) by (apply per_not_col; trivial).\n  destruct (angle_bisector P Q R) as [M [HM1 HM2]]; auto.\n  assert (HSuma : SumA P Q M P Q M P Q R).\n    assert_diffs; apply conga3_suma__suma with P Q M M Q R P Q R; CongA; SumA.\n  assert (HAcute : Acute P Q M).\n  { apply nbet_sams_suma__acute with P Q R; auto.\n      intro HBet; apply HNCol7; Col.\n    destruct (sams_dec P Q M P Q M); trivial.\n    assert_diffs.\n    exfalso; apply (lea__nlta P Q M P Q R).\n      exists M; split; CongA.\n    apply obtuse_per__lta; trivial.\n    apply nsams__obtuse; auto.\n  }\n\n  assert (HC3 : exists C3, Col C1 C2 C3 /\\ OS P Q R C3).\n  { destruct (diff_col_ex3 C1 C2 P) as [C0]; Col; spliter.\n    destruct (cop_not_par_same_side P Q C0 P P R) as [C3 []]; Col.\n      intro; apply HNCol5; ColR.\n      assert (Coplanar P Q R C0); [|Cop].\n      assert_diffs; apply col_cop2__cop with C1 C2; Col; Cop.\n    exists C3; split; trivial; ColR.\n  }\n  destruct HC3 as [C3 [HCol7 HOS1]].\n  destruct (hrap P Q M P Q R P C3) as [S [HS1 HS2]]; trivial.\n    apply out_trivial; auto.\n    assert_diffs; auto.\n    assert (HP := HPerpAC); destruct HP as [P' [_ [_ [HP1 [HP2 HP3]]]]].\n    assert (P = P'); [|treat_equalities; apply HP3; Col].\n    elim (perp_not_col2 _ _ _ _ HPerpAC); intro; assert_diffs;\n    [apply l6_21 with A1 A2 C1 C2|apply l6_21 with A1 A2 C2 C1]; Col.\n    assert (Coplanar P Q R M) by Cop.\n    assert (Coplanar P Q R C3); [|CopR].\n    assert_diffs; apply col_cop2__cop with C1 C2; Col; Cop.\n\n  assert (HD3 : exists D3, Col D1 D2 D3 /\\ OS R Q P D3).\n  { destruct (diff_col_ex3 D1 D2 R) as [D0]; Col; spliter.\n    destruct (cop_not_par_same_side R Q D0 R R P) as [D3 []]; Col.\n      intro; apply HNCol6; ColR.\n      assert (Coplanar P Q R D0); [|CopR].\n      assert_diffs; apply col_cop2__cop with D1 D2; Col; Cop.\n    exists D3; split; trivial; ColR.\n  }\n  destruct HD3 as [D3 [HCol8 HOS2]].\n  destruct (hrap R Q M R Q P R D3) as [T [HT1 HT2]]; Perp.\n    apply (acute_conga__acute P Q M); CongA.\n    assert_diffs; apply conga3_suma__suma with P Q M P Q M P Q R; CongA.\n    apply out_trivial; auto.\n    assert_diffs; auto.\n    assert (HP := HPerpBD); destruct HP as [R' [_ [_ [HR1 [HR2 HR3]]]]].\n    assert (R = R'); [|treat_equalities; apply HR3; Col].\n    elim (perp_not_col2 _ _ _ _ HPerpBD); intro; assert_diffs;\n    [apply l6_21 with B1 B2 D1 D2|apply l6_21 with B1 B2 D2 D1]; Col.\n    assert (Coplanar P Q R M) by Cop.\n    assert (Coplanar P Q R D3); [|CopR].\n    assert_diffs; apply col_cop2__cop with D1 D2; Col; Cop.\n\n  assert (HOut : Out Q S T) by (apply l6_7 with M; trivial; apply l6_6; assumption).\n  assert (HCol9 : Col C1 C2 S) by (assert_diffs; ColR).\n  assert (HCol10 : Col D1 D2 T) by (assert_diffs; ColR).\n  destruct (col_dec C1 C2 T).\n    exists T; Col.\n  destruct (col_dec D1 D2 S).\n    exists S; Col.\n  destruct HOut as [HSQ [HTQ [HBet|HBet]]].\n  - assert (HTS : TS C1 C2 R T).\n      apply l9_8_2 with Q.\n      repeat split; Col; exists S; Col.\n      apply l12_6, par_strict_col2_par_strict with B1 B2; Par; Col.\n    assert_diffs.\n    destruct HTS as [_ [_ [I [HI1 HI2]]]].\n    exists I; split; ColR.\n  - assert (HTS : TS D1 D2 P S).\n      apply l9_8_2 with Q.\n      repeat split; Col; exists T; Col.\n      apply l12_6, par_strict_col2_par_strict with A1 A2; Par; Col.\n    assert_diffs.\n    destruct HTS as [_ [_ [I [HI1 HI2]]]].\n    exists I; split; ColR.\n  }\nQed.\n\nEnd weak_inverse_projection_postulate_bachmann_s_lotschnittaxiom.", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/GeoCoq/Meta_theory/Parallel_postulates/weak_inverse_projection_postulate_bachmann_s_lotschnittaxiom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6698425745448618}}
{"text": "Require Import Tapl.Stlc.Base.\n\n(* Our presentation of simply typed lambda calculus has a single base type, Unit. *)\nInductive type : Type :=\n  | ty_unit  : type \n  | ty_arrow : type → type → type.\n\nInductive term : Type :=\n  | tm_var  : nat → term\n  | tm_abs  : type → term → term\n  | tm_app  : term → term → term\n  | tm_unit : term.\n\nCoercion tm_var : nat >-> term.\n\n(* Values *)\n\nDefinition context := list type.\nInductive wf : context -> term -> Prop :=\n  | wf_var  : forall G i, \n         (exists T, get i G = Some T)\n      -> wf G (tm_var i)\n  | wf_abs  : forall G T t,\n         wf (T :: G) t \n      -> wf G (tm_abs T t)\n  | wf_app  : forall G t1 t2,\n         wf G t1\n      -> wf G t2\n      -> wf G (tm_app t1 t2)\n  | wf_unit : forall G, \n      wf G tm_unit.\nGlobal Hint Constructors wf : core.\n\nDefinition closed (t: term) := wf nil t.\n\nInductive wnfX : term → Prop :=\n  | wnf_val : ∀ T t, wnfX (tm_abs T t)\n  | wnf_unit : wnfX tm_unit.\nGlobal Hint Constructors wnfX : core.\n\nDefinition value (t : term) := wnfX t ∧ closed t.\n\n(* Substitution *)\n\n(* lift shifts all the free variables over by 1 *)\n\nFixpoint lift (k : nat) (t : term) :=\n  match t with\n  | tm_var i => match compare i k with \n                | Lt => tm_var i\n                | _  => tm_var (S i)\n                end\n  | tm_abs T t' => tm_abs T (lift (S k) t')\n  | tm_app t1 t2 => tm_app (lift k t1) (lift k t2)\n  | tm_unit => tm_unit\n  end.\n\n(*\nFixpoint lift (k : nat) (t : term) :=\n  match t with\n  | tm_var i => if leb k i\n                then tm_var (S i)\n                else tm_var i\n  | tm_abs T t' => tm_abs T (lift (S k) t')\n  | tm_app t1 t2 => tm_app (lift k t1) (lift k t2)\n  | tm_unit => tm_unit\n  end.\n*)\n(* [k -> s]t *)\n(* substX replaces the k'th free variable with s in t.\n   if s has free variables, s is lifted when substituting over binders to make sure the free variables in s are correct.\n   All free variables j > k are shifted down one, to account for the fact that the k'th free variable has been substituted.\n*)\nFixpoint substX (k : nat) (s : term) (t : term) :=\n  match t with\n  | tm_var i => match compare i k with\n                | Eq => s\n                | Lt => tm_var i\n                | Gt => tm_var (pred i)\n                end\n  | tm_abs T t' => tm_abs T (substX (S k) (lift 0 s) t')\n  | tm_app t1 t2 => tm_app (substX k s t1) (substX k s t2)\n  | tm_unit => tm_unit\n  end.\n\n(* Examples *)\n(* [0 -> (λ.T 0)] (1 0 2) = 0 (λ.T 0) 1*)\nExample ex1 : substX 0 (tm_abs ty_unit 0) (tm_app (tm_app 1 0) 2)\n            = tm_app (tm_app 0 (tm_abs ty_unit 0)) 1.\nProof.\n  simpl. reflexivity.\nQed.\n\n\n\n\n(* Evaluation *)\n\nReserved Notation \"t '-->' t'\" (at level 40).\nInductive step : term -> term -> Prop :=\n  | st_app1 : forall t1 t1' t2,\n      t1 --> t1' ->\n      tm_app t1 t2 --> tm_app t1' t2\n  | st_app2 : forall v1 t2 t2',\n      value v1 ->\n      t2 --> t2' ->\n      tm_app v1 t2 --> tm_app v1 t2'\n  | st_appAbs : forall T t1 v2,\n      value v2 ->\n      tm_app (tm_abs T t1) v2 --> substX 0 v2 t1\n      \nwhere \"t '-->' t'\" := (step t t').\nGlobal Hint Constructors step : core.\n\n(* multi_step is the reflexive/transitive closure of the step relation *)\n\nDefinition multi_step := multi_rel step.\nNotation \"t '-->*' t'\" := (multi_step t t') (at level 40).\n(*\nInductive multi_step : term -> term -> Prop := \n  | ms_refl : forall t, \n      t -->* t\n  | ms_trans : forall t1 t2 t3,\n      t1 --> t2 ->\n      t2 -->* t3 ->\n      t1 -->* t3\nwhere \"t '-->*' t'\" := (multi_step t t').\n*)\n\n\n\n\n\n", "meta": {"author": "tmoux", "repo": "coq-pl", "sha": "fe79928ab82daebe5012cd3204a0eeff83ee8ade", "save_path": "github-repos/coq/tmoux-coq-pl", "path": "github-repos/coq/tmoux-coq-pl/coq-pl-fe79928ab82daebe5012cd3204a0eeff83ee8ade/tapl/Stlc/Exp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439708, "lm_q2_score": 0.7826624688140728, "lm_q1q2_score": 0.6698425745003751}}
{"text": "(**************************************************************************)\n(*  This is part of ATBR, it is distributed under the terms of the        *)\n(*         GNU Lesser General Public License version 3                    *)\n(*              (see file LICENSE for more details)                       *)\n(*                                                                        *)\n(*       Copyright 2009-2011: Thomas Braibant, Damien Pous.               *)\n(**************************************************************************)\n\n(** Simple properties about Kleene algebras *)\n\nRequire Import Common.\nRequire Import Classes.\nRequire Import Graph.\nRequire Import Monoid.\nRequire Import SemiLattice.\nRequire Import SemiRing.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nSection Props0.\n\n  Context `{KA: KleeneAlgebra}.\n\n  (** other induction schemes  *)\n  Lemma star_destruct_right_old A B: forall (a: X A A) (b c: X B A), b+c*a <== c  ->  b*a# <== c.\n  Proof.\n    intros; transitivity (c*a#).\n     rewrite <- H; semiring_reflexivity.\n     apply star_destruct_right.\n     rewrite <- H at -1; auto with algebra. \n  Qed.\n\n  Lemma star_destruct_left_old A B: forall (a: X A A) (b c: X A B), b+a*c <== c  ->  a#*b <== c.\n  Proof.\n    intros; transitivity (a#*c).\n     rewrite <- H; semiring_reflexivity.\n     apply star_destruct_left.\n     rewrite <- H at -1; auto with algebra. \n  Qed.\n\n  Lemma star_destruct_right_one A: forall (a c: X A A), 1+c*a <== c  ->  a# <== c.\n  Proof.\n    intros. rewrite <- (dot_neutral_left (a#)).\n    apply star_destruct_right_old. assumption.\n  Qed.\n\n  Lemma star_destruct_left_one A: forall (a c: X A A), 1+a*c <== c  ->  a# <== c.\n  Proof.\n    intros. rewrite <- (dot_neutral_right (a#)).\n    apply star_destruct_left_old. assumption.\n  Qed.\n\nEnd Props0.\n\n(** simple tactics to run an induction without having to remember which scheme to use  *)\nLtac star_left_induction :=\n  first [ apply star_destruct_left |\n          apply star_destruct_left_old |\n          apply star_destruct_left_one ].\n\nLtac star_right_induction :=\n  first [ apply star_destruct_right |\n          apply star_destruct_right_old |\n          apply star_destruct_right_one ].\n\n\n(** simple properties  *)\nSection Props1.\n\n  Context `{KA: KleeneAlgebra}.\n  Variable A: T. \n\n  Global Instance star_incr: \n  Proper ((leq A A) ==> (leq A A)) (star A).\n  Proof.\n    intros a b H.\n    star_right_induction.\n    rewrite H. rewrite star_make_left. reflexivity.\n  Qed.\n\n  Global Instance star_compat: Proper ((equal A A) ==> (equal A A)) (star A).\n  Proof.\n    intros a b H. apply leq_antisym; apply star_incr; apply equal_leq; auto. \n  Qed.\n  \n  Lemma one_leq_star_a (a: X A A): 1 <== a#.\n  Proof.\n    rewrite <- star_make_left; auto with algebra. \n  Qed.\n\n  Lemma a_leq_star_a (a: X A A): a <== a#.\n  Proof.\n    rewrite <- star_make_left.\n    rewrite <- one_leq_star_a. \n    semiring_reflexivity.\n  Qed.\n\n  Lemma star_mon_is_one (a: X A A): a <== 1 -> a# == 1.\n  Proof.\n    intro H.\n    apply leq_antisym. \n    star_left_induction.\n    rewrite H; semiring_reflexivity.\n    apply one_leq_star_a.\n  Qed.\n\n  Lemma star_one: (1#: X A A) == 1.\n  Proof.\n    apply star_mon_is_one; reflexivity.\n  Qed.\n  \n  Lemma star_zero: (0#: X A A) == 1.\n  Proof.\n    apply star_mon_is_one; apply zero_inf.\n  Qed.\n\n  Lemma star_a_a_leq_star_a (a: X A A): a#*a <== a#.\n  Proof.\n    rewrite <- star_make_left at 2.\n    semiring_reflexivity.\n  Qed.\n\n  Lemma a_star_a_leq_star_a_a (a: X A A): a*a# <== a#*a.\n  Proof.\n    star_right_induction.\n    rewrite star_a_a_leq_star_a at 1.\n    apply plus_destruct_leq; auto.\n    rewrite <- one_leq_star_a. semiring_reflexivity.\n  Qed.\n\n  Lemma star_make_right (a:X A A): 1+a*a# == a#.\n  Proof. \n    apply leq_antisym.\n    rewrite a_star_a_leq_star_a_a.\n    apply plus_destruct_leq.\n    apply one_leq_star_a.\n    apply star_a_a_leq_star_a.\n\n    star_right_induction.\n    rewrite <- star_make_left at 2.\n    semiring_reflexivity.\n  Qed.\n\nEnd Props1.\n\n(** hints *)\nGlobal Hint Extern 1 (equal _ _ _ _) => apply star_compat; instantiate: compat algebra.\nGlobal Hint Extern 0 (equal _ _ _ _) => apply star_make_left: algebra.\nGlobal Hint Extern 0 (equal _ _ _ _) => apply star_make_right: algebra.\nGlobal Hint Extern 0 (equal _ _ _ _) => apply star_one: algebra.\nGlobal Hint Extern 0 (equal _ _ _ _) => apply star_zero: algebra.\nGlobal Hint Extern 0 (leq _ _ _ _) => apply a_leq_star_a: algebra.\nGlobal Hint Extern 0 (leq _ _ _ _) => apply one_leq_star_a: algebra.\n\nHint Rewrite @star_zero @star_one using ti_auto : simpl.\nHint Rewrite @star_mon_is_one using ti_auto : simpl.\n\n\n(** dual Kleene algebra *)\nModule Dual. Section Protect.\n  Existing Instance Classes.Dual.Monoid_Ops.\n  Existing Instance Classes.Dual.SemiLattice_Ops.\n  Existing Instance Classes.Dual.Star_Op.\n  Instance KleeneAlgebra `{KA: KleeneAlgebra}: KleeneAlgebra (Dual.Graph G).\n  Proof.\n    constructor.\n    apply (@Dual.IdemSemiRing G). eauto with typeclass_instances.\n    exact (@star_make_right _ _ _ _ KA).\n    exact (@star_destruct_right _ _ _ _ KA).\n    exact (@star_destruct_left _ _ _ _ KA).\n  Defined.\n\nEnd Protect. End Dual.\n\n\n(** more properties  *)\nSection Props2.\n  Context `{KA: KleeneAlgebra}.\n  Variable A: T.\n\n  Lemma star_trans (a: X A A): a#*a# == a#.\n  Proof.\n    apply leq_antisym.\n    star_right_induction.\n    rewrite star_a_a_leq_star_a. reflexivity.\n    rewrite <- one_leq_star_a at 3. semiring_reflexivity.\n  Qed.\n\n  Lemma star_idem (a: X A A): a## == a#.\n  Proof.\n    apply leq_antisym.\n    star_right_induction.\n    rewrite star_trans.\n    rewrite (one_leq_star_a a). auto with algebra. \n    apply a_leq_star_a.\n  Qed.\n\n  Lemma a_star_a_leq_star_a: forall (a: X A A), a*a# <== a#.\n  Proof.\n    exact (star_a_a_leq_star_a (KA:=Dual.KleeneAlgebra) (A:=A)).\n  Qed.\n\n  Lemma star_distr (a b: X A A): (a + b)# == a# * (b*a#)#.\n  Proof.\n    apply leq_antisym.\n\n    star_left_induction.\n\n    semiring_normalize.\n    ac_rewrite (star_make_right (b*a#)).\n    rewrite <- (star_make_right a) at 4.\n    semiring_reflexivity.\n\n    rewrite <- (star_trans (a+b)).\n    apply dot_incr.\n     apply star_incr. auto with algebra.\n     rewrite <- (star_idem (a+b)). apply star_incr.\n    rewrite <- (a_star_a_leq_star_a (a+b)).\n    apply dot_incr. auto with algebra. \n    apply star_incr. auto with algebra.\n  Qed.\n\n  Lemma semicomm_iter_right B (a: X A A) (b: X B B) (c: X B A): c*a <== b*c -> c*a# <== b#*c.\n  Proof.\n    intro H.\n    star_right_induction.\n    monoid_rewrite H.\n    rewrite <- star_make_left at 2.\n    semiring_reflexivity.\n  Qed.\n\n  Lemma wsemicomm_iter_right (a b : X A A): a*b <== b#*a  ->  a*b# <== b#*a.\n  Proof.\n    intros H.\n    rewrite <- star_idem at 2.\n    apply semicomm_iter_right; assumption. \n  Qed.\n   \nEnd Props2.\n\nGlobal Hint Extern 1 (leq _ _ _ _) => apply star_incr: compat algebra.\nGlobal Hint Extern 0 (equal _ _ _ _) => apply star_idem: algebra.\nGlobal Hint Extern 0 (equal _ _ _ _) => apply star_trans: algebra.\n\n\n(** more properties, by duality  *)\nSection Props3.\n  Context `{KA: KleeneAlgebra}.\n  \n  Lemma semicomm_iter_left: forall A B (a: X A A) (b: X B B) (c: X A B), a*c <== c*b -> a#*c <== c*b#.\n  Proof.\n    exact (semicomm_iter_right (KA:=Dual.KleeneAlgebra)).\n  Qed.\n\n  Lemma wsemicomm_iter_left: forall A (b a : X A A), a*b <== b*a#  ->  a#*b <== b*a#.\n  Proof.\n    exact (wsemicomm_iter_right (KA:=Dual.KleeneAlgebra)).\n  Qed.\n\n  Lemma comm_iter_left A B (x : X A B) a b:  a * x == x * b -> a# * x == x * b# .\n  Proof.\n    intro H.\n    apply leq_antisym.\n    apply semicomm_iter_left, equal_leq. trivial.\n    apply semicomm_iter_right, equal_leq. auto. \n  Qed.\n\n  Lemma move_star A (a: X A A): a#*a == a*a#.\n  Proof. apply comm_iter_left; reflexivity. Qed.\n\n  Lemma move_star2 A B (a: X A B) (b: X B A): (a*b)#*a == a*(b*a)#.\n  Proof. apply comm_iter_left. semiring_reflexivity. Qed.\n\nEnd Props3.\n\nSection Props4.\n  Context `{KA: KleeneAlgebra}.\n  \n  Lemma comm_iter_right: forall B A (x : X A B) a b,  x * a == b * x -> x * a# == b# * x .\n  Proof.\n    exact (comm_iter_left (KA:=Dual.KleeneAlgebra)).\n  Qed.\n\nEnd Props4.\n", "meta": {"author": "coq-community", "repo": "atbr", "sha": "6f752796dd5bf2d7af1ee085ece65138c0561ab9", "save_path": "github-repos/coq/coq-community-atbr", "path": "github-repos/coq/coq-community-atbr/atbr-6f752796dd5bf2d7af1ee085ece65138c0561ab9/theories/KleeneAlgebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388125473628, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.6698382707136283}}
{"text": "Require Import String.\nDefinition goal := \"tesst assures of boolean xor function\"%string.\n\nDefinition xor (b1 b2 : bool) : bool :=\n  match (b1,b2) with\n  | (true,  true) => false\n  | (false, false) => false\n  | _ => true\n  end.\n\n(*fasle, false should be false*)\nFact xor1: xor false false = false.\nProof. simpl. reflexivity. Qed.\n\n(*false, true should be true*)\nFact xor2: xor false true = true.\nProof. simpl. reflexivity. Qed.\n\n(*false, false should be false*)\nFact xor3: xor true false = true.\nProof. simpl. reflexivity. Qed.\n\n(*true, true should be false*)\nFact xor4: xor true true = false.\nProof. simpl. reflexivity. Qed.\n\nRequire Import String.\nPrint goal. ", "meta": {"author": "lexieAA", "repo": "coq-proofs", "sha": "39b9ec185a3012db63f135ee5e0cb69e6a639214", "save_path": "github-repos/coq/lexieAA-coq-proofs", "path": "github-repos/coq/lexieAA-coq-proofs/coq-proofs-39b9ec185a3012db63f135ee5e0cb69e6a639214/boolean_function.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.6698382604690799}}
{"text": "Require Import refocusing_substitutions.\nRequire Import Setoid.\n\nModule Arith_Lang <: RED_LANG.\n\n  Parameter var_name : Set.\n\n  Inductive term' : Set :=\n  | num  : nat -> term'\n  | plus : term' -> term' -> term'\n  | times: term' -> term' -> term'\n  | var  : var_name -> term'.\n  Definition term := term'.\n\n  Inductive value' : Set :=\n  | v_num : nat -> value'.\n  Definition value := value'.\n\n  Inductive redex' : Set :=\n  | r_plus  : value -> value -> redex'\n  | r_times : value -> value -> redex'\n  | r_var   : var_name -> redex'.\n  Definition redex := redex'.\n\n  Definition value_to_term (v : value) : term :=\n  match v with\n  | v_num v' => num v'\n  end.\n  Coercion value_to_term : value >-> term.\n\n  Lemma value_to_term_injective : forall v v', value_to_term v = value_to_term v' -> v = v'.\n  Proof.\n  intros v v0; case v; case v0; simpl; intros; try discriminate; injection H;\n  intros; subst; auto.\n  Qed.\n\n  Definition redex_to_term (r : redex) : term :=\n  match r with\n  | r_plus m n => plus (m:term) (n:term)\n  | r_times m n => times (m:term) (n:term)\n  | r_var x => var x\n  end.\n  Coercion redex_to_term : redex >-> term.\n\n  Lemma redex_to_term_injective : forall r r', redex_to_term r = redex_to_term r' -> r = r'.\n  Proof with auto.\n  intros r r0; case r; case r0; intros; try discriminate; injection H; intros;\n  try (rewrite (value_to_term_injective _ _ H1); rewrite (value_to_term_injective _ _ H0))...\n  rewrite H0...\n  Qed.\n\n  Parameter env : var_name -> nat.\n\n  Inductive elem_context' : Set :=\n  | plus_r : term -> elem_context'\n  | plus_l : value -> elem_context'\n  | times_r : term -> elem_context'\n  | times_l : value -> elem_context'.\n  Definition elem_context := elem_context'.\n  Definition context := list elem_context.\n  Definition empty : context := nil.\n\n  Definition atom_plug (t : term) (ec : elem_context) :=\n  match ec with\n  | plus_r t' => plus t t'\n  | plus_l v => plus (v:term) t\n  | times_r t' =>times t t'\n  | times_l v => times (v:term) t\n  end.\n  Definition compose (c0 c1 : context) : context := app c0 c1.\n  Definition plug (t : term) (c : context) : term := fold_left atom_plug c t.\n\n  Lemma plug_compose : forall c1 c2 r, plug r (compose c1 c2) = plug (plug r c1) c2.\n  Proof.\n  induction c1; simpl; auto.\n  Qed.\n\n  Definition contract (r : redex) : option term :=\n  match r with\n  | r_plus (v_num n) (v_num m) => Some (num (n+m))\n  | r_times (v_num n) (v_num m) => Some (num (n*m))\n  | r_var x => Some (num (env x))\n  end.\n\n  Lemma decompose : forall t : term, (exists v : value, t = v) \\/\n                      (exists r : redex, exists c : context, plug r c = t).\n  Proof with auto.\n    induction t; simpl.\n    left; exists (v_num n); auto.\n    right; elim IHt1; intros.\n    destruct H as [v1 H]; subst.\n    elim IHt2; intros.\n    destruct H as [v2 H]; subst.\n    exists (r_plus v1 v2); exists empty; simpl...\n    destruct H as [r [c H]]; exists r; exists (compose c (plus_l v1 :: empty)); rewrite plug_compose; simpl; subst; auto.\n    destruct H as [r [c H]]; exists r; exists (compose c (plus_r t2 :: empty)); rewrite plug_compose; simpl; subst; auto.\n    right; elim IHt1; intros.\n    destruct H as [v1 H]; subst.\n    elim IHt2; intros.\n    destruct H as [v2 H]; subst.\n    exists (r_times v1 v2); exists empty; simpl...\n    destruct H as [r [c H]]; exists r; exists (compose c (times_l v1 :: empty)); rewrite plug_compose; simpl; subst; auto.\n    destruct H as [r [c H]]; exists r; exists (compose c (times_r t2 :: empty)); rewrite plug_compose; simpl; subst; auto.\n    right; exists (r_var v); exists empty; simpl...\n  Qed.\n\n  Inductive decomp : Set :=\n  | d_val : value -> decomp\n  | d_red : redex -> context -> decomp.\n\n  Inductive interm_dec : Set :=\n  | in_red : redex -> interm_dec\n  | in_val : value -> interm_dec\n  | in_term: term -> elem_context -> interm_dec.\n\n  Definition decomp_to_term (d : decomp) : term :=\n  match d with\n    | d_val v => value_to_term v\n    | d_red r c0 => plug (redex_to_term r) c0\n  end.\n  Definition only_empty (t : term) : Prop := forall t' c, plug t' c = t -> c = empty.\n  Definition only_trivial (t : term) : Prop := forall t' c, plug t' c = t -> c = empty \\/ exists v, t' = value_to_term v.\n\n  Lemma value_trivial : forall v : value, only_trivial (value_to_term v).\n  Proof.\n    intros v t c; left; generalize dependent t; induction c; simpl in *; auto;\n    destruct v; destruct a; destruct c; intros; simpl in *; try discriminate H; discriminate (IHc _ H).\n  Qed.\n  Lemma redex_trivial : forall r : redex, only_trivial (redex_to_term r).\n  Proof.\n    intros r t c; generalize dependent t; induction c; intros; [left; auto | right]; destruct a;( simpl in *;\n    destruct (IHc _ H) as [H0 | [v0 H0]]; subst;[ destruct r; inversion H; subst;\n    match goal with [ |- exists u, _ ?v = _ u ] => exists v; reflexivity end | destruct v0; discriminate]).\n  Qed.\n  Lemma value_redex : forall (v : value) (r : redex), value_to_term v <> redex_to_term r.\n  Proof.\n    destruct v; destruct r; intro; discriminate.\n  Qed.\n\n  Lemma ot_subt : forall t t0 ec, only_trivial t -> atom_plug t0 ec = t -> exists v, t0 = value_to_term v.\n  Proof with auto.\n    intros; destruct (H t0 (ec :: nil)) as [H1 | [v H1]]...\n    discriminate.\n    exists v...\n  Qed.\n\n  Ltac ot_v t ec :=\n  match goal with\n  | [Hot : (only_trivial ?H1) |- _] => destruct (ot_subt _ t ec Hot) as [?v HV]; [auto | subst t]\n  end.\n\n  Ltac mlr rv :=\n  match goal with [ |- (exists v, ?H1 = value_to_term v) \\/ (exists r, ?H1 = redex_to_term r)] =>\n    match rv with\n    | (?v : value) => left; exists v\n    | (?r : redex) => right; exists r\n    end; simpl; auto\n  end.\n\n  Lemma trivial_val_red : forall t : term, only_trivial t ->\n    (exists v : value, t = value_to_term v) \\/ (exists r : redex, t = redex_to_term r).\n  Proof with auto.\n    destruct t; intros.\n    mlr (v_num n).\n    ot_v t1 (plus_r t2); ot_v t2 (plus_l v); mlr (r_plus v v0).\n    ot_v t1 (times_r t2); ot_v t2 (times_l v); mlr (r_times v v0).\n    mlr (r_var v).\n  Qed.\n\nEnd Arith_Lang.\n\nModule Arith_Sem <: RED_SEM Arith_Lang.\n\n  Definition term := Arith_Lang.term.\n  Definition value := Arith_Lang.value.\n  Definition redex := Arith_Lang.redex.\n  Definition context := Arith_Lang.context.\n  Definition empty := Arith_Lang.empty.\n  Definition decomp := Arith_Lang.decomp.\n  Definition d_val := Arith_Lang.d_val.\n  Definition d_red := Arith_Lang.d_red.\n  Definition value_to_term : value -> term := Arith_Lang.value_to_term.\n  Definition redex_to_term : redex -> term := Arith_Lang.redex_to_term.\n  Definition decomp_to_term : (decomp -> term) := Arith_Lang.decomp_to_term.\n  Definition plug : term -> context -> term := Arith_Lang.plug.\n  Definition compose : context -> context -> context := Arith_Lang.compose.\n  Definition contract : redex -> option term := Arith_Lang.contract.\n  Definition interm_dec := Arith_Lang.interm_dec.\n  Definition in_red := Arith_Lang.in_red.\n  Definition in_val := Arith_Lang.in_val.\n  Definition in_term := Arith_Lang.in_term.\n  Definition r_var := Arith_Lang.r_var.\n  Definition num := Arith_Lang.num.\n  Definition var := Arith_Lang.var.\n  Definition var_name := Arith_Lang.var_name.\n  Definition plus_r := Arith_Lang.plus_r.\n  Definition plus_l := Arith_Lang.plus_l.\n  Definition plus := Arith_Lang.plus.\n  Definition v_num := Arith_Lang.v_num.\n  Definition times := Arith_Lang.times.\n  Definition times_r := Arith_Lang.times_r.\n  Definition times_l := Arith_Lang.times_l.\n  Definition r_plus := Arith_Lang.r_plus.\n  Definition r_times := Arith_Lang.r_times.\n\n  Coercion value_to_term : value >-> term.\n  Coercion redex_to_term : redex >-> term.\n\n  Inductive dec' : term -> context -> decomp -> Prop :=\n  | t_var : forall (x : var_name) (c : context), dec' (var x) c (d_red (r_var x) c)\n  | t_num : forall (n : nat) (c : context) (d : decomp),\n              decctx' (v_num n) c d -> dec' (num n) c d\n  | t_plus: forall (t0 t1 : term) (c : context) (d : decomp),\n              dec' t0 (plus_r t1 :: c) d -> dec' (plus t0 t1) c d\n  | t_mul : forall (t0 t1 : term) (c : context) (d : decomp),\n              dec' t0 (times_r t1 :: c) d -> dec' (times t0 t1) c d\n  with decctx' : value -> context -> decomp -> Prop :=\n  | c_empty : forall (v : value), decctx' v empty (d_val v)\n  | c_plus_r: forall (v : value) (t : term) (c : context) (d : decomp),\n                dec' t (plus_l v :: c) d -> decctx' v (plus_r t :: c) d\n  | c_plus_l: forall (v v0 : value) (c : context), decctx' v (plus_l v0 :: c) (d_red (r_plus v0 v) c)\n  | c_mul_r : forall (v : value) (t : term) (c : context) (d : decomp),\n                dec' t (times_l v :: c) d -> decctx' v (times_r t :: c) d\n  | c_mul_l : forall (v v0 : value) (c : context), decctx' v (times_l v0 :: c) (d_red (r_times v0 v) c).\n\n  Definition dec := dec'.\n  Definition decctx := decctx'.\n\n  Scheme dec_Ind := Induction for dec' Sort Prop\n  with decctx_Ind := Induction for decctx' Sort Prop.\n\n  (** dec is left inverse of plug *)\n  Lemma dec_correct : forall t c d, dec t c d -> decomp_to_term d = plug t c.\n  Proof.\n    induction 1 using dec_Ind with\n    (P := fun t c d (H : dec t c d) => decomp_to_term d = plug t c)\n    (P0:= fun v c d (H : decctx v c d) => decomp_to_term d = plug v c); simpl; auto.\n  Qed.\n\n  (** A redex in context will only ever be reduced to itself *)\n  Lemma dec_redex_self : forall (r : redex) (c : context), dec (redex_to_term r) c (d_red r c).\n  Proof.\n    intro; case r; intros; constructor; destruct v; destruct v0; repeat constructor.\n  Qed.\n\n  Lemma dec_plug : forall c c0 t d, dec (plug t c) c0 d -> dec t (compose c c0) d.\n  Proof with auto.\n    induction c; intros; simpl in *; auto; destruct a;\n    assert (hh := IHc _ _ _ H); inversion hh; subst; auto;\n    destruct v; inversion H4; subst; inversion H1; subst...\n  Qed.\n\n  Lemma dec_plug_rev : forall c c0 t d, dec t (compose c c0) d -> dec (plug t c) c0 d.\n  Proof with auto.\n    induction c; intros; simpl in *; auto; destruct a;\n    try (destruct v); apply IHc; repeat constructor...\n  Qed.\n\n  Inductive decempty : term -> decomp -> Prop :=\n  | d_intro : forall (t : term) (d : decomp), dec t empty d -> decempty t d.\n\n  Inductive iter : decomp -> value -> Prop :=\n  | i_val : forall (v : value), iter (d_val v) v\n  | i_red : forall (r : redex) (t : term) (c : context) (d : decomp) (v : value),\n              contract r = Some t -> decempty (plug t c) d -> iter d v -> iter (d_red r c) v.\n\n  Inductive eval : term -> value -> Prop :=\n  | e_intro : forall (t : term) (d : decomp) (v : value), decempty t d -> iter d v -> eval t v.\n\n  Definition decompose := Arith_Lang.decompose.\n\nEnd Arith_Sem.\n\nModule Arith_Ref_Lang <: RED_REF_LANG.\n\n  Module R := Arith_Lang.\n\n  Definition dec_term (t : R.term) : R.interm_dec :=\n  match t with\n  | Arith_Lang.var vname => R.in_red (Arith_Lang.r_var vname)\n  | Arith_Lang.num n => R.in_val (Arith_Lang.v_num n)\n  | Arith_Lang.plus n m => R.in_term n (Arith_Lang.plus_r m)\n  | Arith_Lang.times n m => R.in_term n (Arith_Lang.times_r m)\n  end.\n  Definition dec_context : R.elem_context -> R.value -> R.interm_dec :=\n  fun (ec : R.elem_context) (v : R.value) => match ec with\n  | Arith_Lang.plus_r n => R.in_term n (Arith_Lang.plus_l v)\n  | Arith_Lang.plus_l v' => R.in_red (Arith_Lang.r_plus v' v)\n  | Arith_Lang.times_r n => R.in_term n (Arith_Lang.times_l v)\n  | Arith_Lang.times_l v' => R.in_red (Arith_Lang.r_times v' v)\n  end.\n\n  Inductive subterm_one_step : R.term -> R.term -> Prop :=\n  | st_1 : forall t t0 ec (DECT : t = R.atom_plug t0 ec), subterm_one_step t0 t.\n  Lemma wf_st1 : well_founded subterm_one_step.\n  Proof.\n    prove_st_wf.\n  Qed.\n\n  Definition subterm_order := clos_trans_n1 R.term subterm_one_step.\n  Notation \" a <| b \" := (subterm_order a b) (at level 40).\n  Definition wf_sto : well_founded subterm_order := wf_clos_trans_r _ _ wf_st1.\n\n(*  Inductive elem_context_one_step : R.elem_context -> R.elem_context -> Prop :=\n  | ec_1 : forall ec ec0 v t (DECEC : dec_context ec v = R.in_term t ec0), \n             elem_context_one_step ec0 ec.\n\n  Ltac wf_ec_step :=\n  constructor; match goal with\n    | [ |- forall u (T:?eco u _), Acc ?eco u ] => intros y T; inversion T as [ec ec0 ?t ?v ?Hcc]; subst ec ec0; clear T\n  end; match goal with \n    | [ Hcc : dec_context _ _ = R.in_term _ ?cc |- Acc ?eco ?cc] => inversion Hcc; subst; clear Hcc\n  end.\n\n  Ltac prove_ec_wf := intro a; destruct a; repeat wf_ec_step.\n\n  Lemma wf_ec1 : well_founded elem_context_one_step.\n  Proof.\n    prove_ec_wf.\n  Qed.\n\n  Definition ec_order := clos_trans_1n _ elem_context_one_step.\n  Notation \" a <: b \" := (ec_order a b) (at level 40).\n  Definition wf_eco : well_founded ec_order := wf_clos_trans_l _ _ wf_ec1.*)\n\n  Definition ec_order (ec0 ec1 : R.elem_context) : Prop :=\n  match ec0, ec1 with\n  | R.plus_l _, R.plus_r _ => True\n  | R.times_l _, R.times_r _ => True\n  | _, _ => False\n  end.\n  Notation \" a <: b \" := (ec_order a b) (at level 40).\n  Lemma wf_eco : well_founded ec_order.\n  Proof.\n    prove_ec_wf.\n  Qed.\n\n  Lemma dec_term_red_empty  : forall t r, dec_term t = R.in_red r -> R.only_empty t.\n  Proof.\n    intros t r H; destruct t; inversion H; subst; intros t c; generalize t; induction c; intros;\n    simpl in *; auto; clear H; assert (ht := IHc _ H0); subst c; destruct a; inversion H0.\n  Qed.\n  Lemma dec_term_val_empty : forall t v, dec_term t = R.in_val v -> R.only_empty t.\n  Proof.\n    intros t v H; destruct t; inversion H; subst; intros t c; generalize t; induction c; intros;\n    simpl in *; auto; clear H; assert (ht := IHc _ H0); subst c; destruct a; inversion H0.\n  Qed.\n\n  Lemma dec_term_term_top   : forall t t' ec, dec_term t = R.in_term t' ec -> forall ec', ~ ec <: ec'.\n  Proof.\n    intros t t' ec H ec' H0; destruct t; inversion H; subst; destruct ec'; inversion H0.\n  Qed.\n  Lemma dec_context_red_bot : forall ec v r, dec_context ec v = R.in_red r -> forall ec', ~ec' <: ec.\n  Proof.\n    intros ec v r H ec' H0; destruct ec; inversion H; subst; destruct ec'; inversion H0.\n  Qed.\n  Lemma dec_context_val_bot : forall ec v v0, dec_context ec v = R.in_val v0 -> forall ec', ~ec' <: ec.\n  Proof.\n    intros ec v r H ec' H0; destruct ec; inversion H; subst; destruct ec'; inversion H0.\n  Qed.\n  Lemma dec_context_term_next : forall ec v t ec', dec_context ec v = R.in_term t ec' -> ec' <: ec /\\ forall ec'', ec'' <: ec -> ~ec' <: ec''.\n  Proof.\n    intros; destruct ec; inversion H; subst; repeat constructor; intros; destruct ec''; inversion H0; intro; inversion H1.\n  Qed.\n\n  Lemma dec_term_correct : forall t, match dec_term t with\n    | R.in_red r => R.redex_to_term r = t\n    | R.in_val v => R.value_to_term v = t\n    | R.in_term t' ec => R.atom_plug t' ec = t\n    end.\n  Proof.\n    destruct t; simpl; auto.\n  Qed.\n  Lemma dec_context_correct : forall ec v, match dec_context ec v with\n    | R.in_red r => R.redex_to_term r = R.atom_plug (R.value_to_term v) ec\n    | R.in_val v0 => R.value_to_term v0 = R.atom_plug (R.value_to_term v) ec\n    | R.in_term t ec' => R.atom_plug t ec' = R.atom_plug (R.value_to_term v) ec\n    end.\n  Proof.\n    destruct ec; simpl; auto.\n  Qed.\n\n  Ltac inj_vr := match goal with\n  | [Hv : R.value_to_term _ = R.value_to_term _ |- _] => apply R.value_to_term_injective in Hv\n  | [Hr : R.redex_to_term _ = R.redex_to_term _ |- _] => apply R.redex_to_term_injective in Hr\n  | [ |- _] => idtac\n  end.\n\n  Lemma ec_order_antisym : forall ec ec0, ec <: ec0 -> ~ec0 <: ec.\n  Proof.\n    destruct ec; destruct ec0; intros H H0; inversion H; inversion H0.\n  Qed.\n  Lemma dec_ec_ord : forall t0 t1 ec0 ec1, R.atom_plug t0 ec0 = R.atom_plug t1 ec1 -> ec0 <: ec1 \\/ ec1 <: ec0 \\/ (t0 = t1 /\\ ec0 = ec1).\n  Proof.\n    destruct ec0; destruct ec1; intros; inversion H; inj_vr; subst; simpl in *; auto.\n  Qed.\n  Lemma elem_context_det : forall t0 t1 ec0 ec1, ec0 <: ec1 -> R.atom_plug t0 ec0 = R.atom_plug t1 ec1 ->\n    exists v, t1 = R.value_to_term v.\n  Proof.\n    destruct ec0; destruct ec1; intros; inversion H; inversion H0; subst; exists v; auto.\n  Qed.\n\nEnd Arith_Ref_Lang.\n\nModule Arith_Ref_Sem_Auto <: RED_REF_SEM Arith_Lang := RedRefSem Arith_Ref_Lang.\n\nModule Arith_Ref_Sem <: RED_REF_SEM Arith_Lang.\n\n  Definition term := Arith_Lang.term.\n  Definition value := Arith_Lang.value.\n  Definition redex := Arith_Lang.redex.\n  Definition context := Arith_Lang.context.\n  Definition empty := Arith_Lang.empty.\n  Definition decomp := Arith_Lang.decomp.\n  Definition elem_context := Arith_Lang.elem_context.\n  Definition d_val := Arith_Lang.d_val.\n  Definition d_red := Arith_Lang.d_red.\n  Definition value_to_term : value -> term := Arith_Lang.value_to_term.\n  Definition redex_to_term : redex -> term := Arith_Lang.redex_to_term.\n  Definition decomp_to_term : (decomp -> term) := Arith_Lang.decomp_to_term.\n  Definition atom_plug := Arith_Lang.atom_plug.\n  Definition plug : term -> context -> term := Arith_Lang.plug.\n  Definition compose : context -> context -> context := Arith_Lang.compose.\n  Definition contract : redex -> option term := Arith_Lang.contract.\n  Definition interm_dec := Arith_Lang.interm_dec.\n  Definition in_red := Arith_Lang.in_red.\n  Definition in_val := Arith_Lang.in_val.\n  Definition in_term := Arith_Lang.in_term.\n\n  Coercion value_to_term : value >-> term.\n  Coercion redex_to_term : redex >-> term.\n\n  (** Functions specifying atomic steps of induction on terms and contexts -- needed to avoid explicit induction on terms and contexts in construction of the AM *)\n  Definition dec_term : term -> interm_dec :=\n  fun (t : term) => match t with\n  | Arith_Lang.var vname => in_red (Arith_Lang.r_var vname)\n  | Arith_Lang.num n => in_val (Arith_Lang.v_num n)\n  | Arith_Lang.plus n m => in_term n (Arith_Lang.plus_r m)\n  | Arith_Lang.times n m => in_term n (Arith_Lang.times_r m)\n  end.\n  Definition dec_context : elem_context -> value -> interm_dec :=\n  fun (ec : elem_context) (v : value) => match ec with\n  | Arith_Lang.plus_r n => in_term n (Arith_Lang.plus_l v)\n  | Arith_Lang.plus_l v' => in_red (Arith_Lang.r_plus v' v)\n  | Arith_Lang.times_r n => in_term n (Arith_Lang.times_l v)\n  | Arith_Lang.times_l v' => in_red (Arith_Lang.r_times v' v)\n  end.\n\n  Lemma dec_term_value : forall (v:value), dec_term (v:term) = in_val v.\n  Proof.\n    destruct v; simpl; auto.\n  Qed.\n  Hint Resolve dec_term_value.\n\n  Lemma dec_term_correct : forall t, match dec_term t with\n    | in_red r => redex_to_term r = t\n    | in_val v => value_to_term v = t\n    | in_term t0 c0 => atom_plug t0 c0 = t\n  end.\n  Proof.\n    intro t; case t; intros; simpl; auto.\n  Qed.\n  Lemma dec_context_correct : forall c v, match dec_context c v with\n    | in_red r => redex_to_term r = atom_plug (value_to_term v) c\n    | in_val v0 => value_to_term v0 = atom_plug (value_to_term v) c\n    | in_term t c0 => atom_plug t c0 = atom_plug (value_to_term v) c\n  end.\n  Proof.\n    destruct c; intros; simpl; auto.\n  Qed.\n  \n  (** A decomposition function specified in terms of the atomic functions above *)\n  Inductive dec : term -> context -> decomp -> Prop :=\n  | d_dec  : forall (t : term) (c : context) (r : redex),\n                 dec_term t = in_red r -> dec t c (d_red r c)\n  | d_v    : forall (t : term) (c : context) (v : value) (d : decomp),\n                 dec_term t = in_val v -> decctx v c d -> dec t c d\n  | d_term : forall (t t0 : term) (c : context) (ec : elem_context) (d : decomp),\n                 dec_term t = in_term t0 ec -> dec t0 (ec :: c) d -> dec t c d\n  with decctx : value -> context -> decomp -> Prop :=\n  | dc_end  : forall (v : value), decctx v empty (d_val v)\n  | dc_dec  : forall (v : value) (ec : elem_context) (c : context) (r : redex),\n                dec_context ec v = in_red r -> decctx v (ec :: c) (d_red r c)\n  | dc_val  : forall (v v0 : value) (ec : elem_context) (c : context) (d : decomp),\n                dec_context ec v = in_val v0 -> decctx v0 c d -> decctx v (ec :: c) d\n  | dc_term : forall (v : value) (ec ec0 : elem_context) (c : context) (t : term) (d : decomp),\n                dec_context ec v = in_term t ec0 -> dec t (ec0 :: c) d -> decctx v (ec :: c) d.\n\n  Scheme dec_Ind := Induction for dec Sort Prop\n  with decctx_Ind := Induction for decctx Sort Prop.\n\n  Lemma dec_red_ref : forall t c d, Arith_Sem.dec t c d <-> dec t c d.\n  Proof with eauto.\n    intros; split; intro.\n    induction H using Arith_Sem.dec_Ind with\n    (P := fun t c d (H : Arith_Sem.dec t c d) => dec t c d)\n    (P0:= fun v c d (H : Arith_Sem.decctx v c d) => decctx v c d);\n    [ constructor | econstructor 2 | econstructor 3 | econstructor 3 | constructor\n    | econstructor 4 | constructor | econstructor 4 | constructor]; simpl...\n    induction H using dec_Ind with\n    (P := fun t c d (H : dec t c d) => Arith_Sem.dec t c d)\n    (P0:= fun v c d (H : decctx v c d) => Arith_Sem.decctx v c d);\n    try (destruct t; inversion e; subst; constructor); auto; try constructor;\n    destruct ec; inversion e; subst; constructor...\n  Qed.\n\n  Module RS : RED_SEM Arith_Lang with Definition dec := dec.\n\n    Definition dec := dec.\n\n    Inductive decempty : term -> decomp -> Prop :=\n    | d_intro : forall (t : term) (d : decomp), dec t empty d -> decempty t d.\n\n    Inductive iter : decomp -> value -> Prop :=\n    | i_val : forall (v : value), iter (d_val v) v\n    | i_red : forall (r : redex) (t : term) (c : context) (d : decomp) (v : value),\n                contract r = Some t -> decempty (plug t c) d -> iter d v -> iter (d_red r c) v.\n\n    Inductive eval : term -> value -> Prop :=\n    | e_intro : forall (t : term) (d : decomp) (v : value), decempty t d -> iter d v -> eval t v.\n\n    Lemma dec_redex_self : forall (r : redex) (c : context), dec (redex_to_term r) c (d_red r c).\n    Proof.\n      intros; rewrite <- dec_red_ref; apply Arith_Sem.dec_redex_self.\n    Qed.\n\n    (** dec is left inverse of plug *)\n    Lemma dec_correct : forall t c d, dec t c d -> decomp_to_term d = plug t c.\n    Proof.\n      intros; apply Arith_Sem.dec_correct; rewrite dec_red_ref; auto.\n    Qed.\n\n    Lemma dec_plug : forall c c0 t d, dec (plug t c) c0 d -> dec t (compose c c0) d.\n    Proof.\n      intros; rewrite <- dec_red_ref; apply Arith_Sem.dec_plug; rewrite dec_red_ref; auto.\n    Qed.\n\n    Lemma dec_plug_rev : forall c c0 t d, dec t (compose c c0) d -> dec (plug t c) c0 d.\n    Proof.\n      intros; rewrite <- dec_red_ref; apply Arith_Sem.dec_plug_rev; rewrite dec_red_ref; auto.\n    Qed.\n    Definition decompose := Arith_Sem.decompose.\n\n  End RS.\n\n  Lemma iter_red_ref : forall d v, Arith_Sem.iter d v <-> RS.iter d v.\n  Proof.\n    intros; split; intro; induction H; try constructor;\n    constructor 2 with t d; auto; constructor; \n    [ inversion_clear H0; rewrite <- dec_red_ref | inversion_clear D_EM; rewrite dec_red_ref]; auto.\n  Qed.\n\n  Lemma eval_red_ref : forall t v, Arith_Sem.eval t v <-> RS.eval t v.\n  Proof.\n    intros; split; intro; inversion_clear H; constructor 1 with d.\n    constructor; inversion_clear H0; rewrite <- dec_red_ref; auto.\n    rewrite <- iter_red_ref; auto.\n    constructor; inversion_clear D_EM; rewrite dec_red_ref; auto.\n    rewrite iter_red_ref; auto.\n  Qed.\n\n  Lemma dec_val_self : forall v c d, dec (Arith_Lang.value_to_term v) c d <-> decctx v c d.\n  Proof.\n    split; intro.\n    destruct v; inversion H; inversion H0; subst; auto.\n    assert (hh := dec_term_value v); econstructor; eauto.\n  Qed.\n\nEnd Arith_Ref_Sem.\n\nModule Arith_PE_Sem <: PE_REF_SEM Arith_Lang.\n\n  Module Red_Sem := Arith_Ref_Sem.\n\n  Lemma dec_context_not_val : forall (v v0 : Arith_Lang.value) (ec : Arith_Lang.elem_context), ~Red_Sem.dec_context ec v = Arith_Lang.in_val v0.\n  Proof.\n    destruct ec; intros; simpl; intro; discriminate.\n  Qed.\n  Hint Resolve dec_context_not_val.\n  Definition dec_term_value := Red_Sem.dec_term_value.\n\nEnd Arith_PE_Sem.\n\nModule EAM := ProperEAMachine Arith_Lang Arith_Ref_Sem.\nModule PEM := ProperPEMachine Arith_Lang Arith_PE_Sem.\n\nModule EAArithMachine <: ABSTRACT_MACHINE.\n\n  Definition term := Arith_Lang.term.\n  Definition value := Arith_Lang.value.\n  Definition redex := Arith_Lang.redex.\n  Definition context := Arith_Lang.context.\n  Definition num := Arith_Lang.num.\n  Definition plus := Arith_Lang.plus.\n  Definition times := Arith_Lang.times.\n  Definition var  := Arith_Lang.var.\n  Definition v_num := Arith_Lang.v_num.\n  Definition r_plus := Arith_Lang.r_plus.\n  Definition r_times:= Arith_Lang.r_times.\n  Definition r_var  := Arith_Lang.r_var.\n  Definition empty := Arith_Lang.empty.\n  Definition plus_r := Arith_Lang.plus_r.\n  Definition plus_l := Arith_Lang.plus_l.\n  Definition times_r := Arith_Lang.times_r.\n  Definition times_l := Arith_Lang.times_l.\n  Definition value_to_term : value -> term := Arith_Lang.value_to_term.\n  Definition redex_to_term : redex -> term := Arith_Lang.redex_to_term.\n  Coercion value_to_term : value >-> term.\n  Coercion redex_to_term : redex >-> term.\n\n  Definition contract := Arith_Lang.contract.\n  Definition plug := Arith_Lang.plug.\n  Definition compose := Arith_Lang.compose.\n\n  Definition decomp := Arith_Lang.decomp.\n  Definition d_val := Arith_Lang.d_val.\n  Definition d_red := Arith_Lang.d_red.\n\n  Definition configuration := EAM.configuration.\n  Definition c_init := EAM.c_init.\n  Definition c_eval := EAM.c_eval.\n  Definition c_apply := EAM.c_apply.\n  Definition c_final := EAM.c_final.\n\n  Definition var_name := Arith_Lang.var_name.\n  Definition env := Arith_Lang.env.\n\n  Inductive transition' : configuration -> configuration -> Prop :=\n  | t_init : forall t : term, transition' (c_init t) (c_eval t empty)\n  | t_val  : forall (v : value) (c : context), transition' (c_eval (v:term) c) (c_apply c v)\n  | t_plus : forall (t s : term) (c : context), transition' (c_eval (plus t s) c) (c_eval t (plus_r s :: c))\n  | t_times: forall (t s : term) (c : context), transition' (c_eval (times t s) c) (c_eval t (times_r s :: c))\n  | t_var  : forall (x : var_name) (c : context), transition' (c_eval (var x) c) (c_eval (num (env x)) c)\n  | t_empty  : forall v : value, transition' (c_apply empty v) (c_final v)\n  | t_plus_r : forall (t : term) (v : value) (c : context), transition' (c_apply (plus_r t :: c) v) (c_eval t (plus_l v :: c))\n  | t_plus_l : forall (v v0 : value) (c : context) (t : term),\n                 contract (r_plus v0 v) = Some t -> transition' (c_apply (plus_l v0 :: c) v) (c_eval t c)\n  | t_times_r: forall (t : term) (v : value) (c : context), transition' (c_apply (times_r t :: c) v) (c_eval t (times_l v :: c))\n  | t_times_l: forall (v v0 : value) (c : context) (t : term),\n                 contract (r_times v0 v) = Some t -> transition' (c_apply (times_l v0 :: c) v) (c_eval t c).\n\n  Definition transition := transition'.\n\n  Inductive trans_close : configuration -> configuration -> Prop :=\n  | one_step   : forall (c0 c1 : configuration), transition c0 c1 -> trans_close c0 c1\n  | multi_step : forall (c0 c1 c2 : configuration), transition c0 c1 -> trans_close c1 c2 -> trans_close c0 c2.\n\n  Inductive eval : term -> value -> Prop :=\n  | e_intro : forall (t : term) (v : value), trans_close (c_init t) (c_final v) -> eval t v.\n\n  Lemma trEA_M : forall w w' : configuration, EAM.transition w w' -> transition w w'.\n  Proof with eauto.\n    intros w w' H; inversion H; subst;\n    try (destruct ec; inversion DC; subst; constructor; auto);\n    try constructor; destruct t; inversion DT; subst; try constructor.\n    inversion CONTR; subst; constructor.\n    cutrewrite (Arith_Lang.num n = value_to_term (Arith_Lang.v_num n)); [constructor | auto].\n  Qed.\n  Hint Resolve trEA_M.\n\n  Lemma tcEA_M : forall w w' : configuration, EAM.AM.trans_close w w' -> trans_close w w'.\n  Proof with eauto.\n    intros w w' H; induction H; subst; [ constructor 1 | econstructor 2]...\n  Qed.\n\n  Lemma evalEA_M : forall t v, EAM.AM.eval t v -> eval t v.\n  Proof.\n    intros t v H; inversion H; constructor; apply tcEA_M; auto.\n  Qed.\n  Hint Resolve evalEA_M.\n\n  Lemma trM_EA : forall w w' : configuration, transition w w' -> EAM.AM.transition w w'.\n  Proof with eauto.\n    intros w w' H; inversion H; subst; econstructor; simpl...\n  Qed.\n  Hint Resolve trM_EA.\n\n  Lemma tcM_EA : forall w w' : configuration, trans_close w w' -> EAM.AM.trans_close w w'.\n  Proof with eauto.\n    induction 1; [ constructor 1 | econstructor 2]...\n  Qed.\n\n  Lemma evalM_EA : forall t v, eval t v -> EAM.AM.eval t v.\n  Proof.\n    intros t v H; inversion H; constructor; apply tcM_EA; auto.\n  Qed.\n  Hint Resolve evalM_EA.\n\n  Theorem ArithMachineCorrect : forall (t : term) (v : value), Arith_Sem.eval t v <-> eval t v.\n  Proof with auto.\n    intros; rewrite Arith_Ref_Sem.eval_red_ref; rewrite EAM.eval_apply_correct; split...\n  Qed.\n\nEnd EAArithMachine.\n\nModule PEArithMachine <: ABSTRACT_MACHINE.\n\n  Definition term := Arith_Lang.term.\n  Definition value := Arith_Lang.value.\n  Definition redex := Arith_Lang.redex.\n  Definition context := Arith_Lang.context.\n  Definition num := Arith_Lang.num.\n  Definition plus := Arith_Lang.plus.\n  Definition times := Arith_Lang.times.\n  Definition var  := Arith_Lang.var.\n  Definition v_num := Arith_Lang.v_num.\n  Definition r_plus := Arith_Lang.r_plus.\n  Definition r_times:= Arith_Lang.r_times.\n  Definition r_var  := Arith_Lang.r_var.\n  Definition empty := Arith_Lang.empty.\n  Definition plus_r := Arith_Lang.plus_r.\n  Definition plus_l := Arith_Lang.plus_l.\n  Definition times_r := Arith_Lang.times_r.\n  Definition times_l := Arith_Lang.times_l.\n  Definition value_to_term : value -> term := Arith_Lang.value_to_term.\n  Definition redex_to_term : redex -> term := Arith_Lang.redex_to_term.\n  Coercion value_to_term : value >-> term.\n  Coercion redex_to_term : redex >-> term.\n\n  Definition contract := Arith_Lang.contract.\n  Definition plug := Arith_Lang.plug.\n  Definition compose := Arith_Lang.compose.\n\n  Definition decomp := Arith_Lang.decomp.\n  Definition d_val := Arith_Lang.d_val.\n  Definition d_red := Arith_Lang.d_red.\n\n  Definition configuration := PEM.configuration.\n  Definition c_init := PEM.c_init.\n  Definition c_eval := PEM.c_eval.\n  Definition c_final := PEM.c_final.\n\n  Definition var_name := Arith_Lang.var_name.\n  Definition env := Arith_Lang.env.\n\n  Inductive transition' : configuration -> configuration -> Prop :=\n  | t_init : forall t : term, transition' (c_init t) (c_eval t empty)\n  | t_plus : forall (t s : term) (c : context), transition' (c_eval (plus t s) c) (c_eval t (plus_r s :: c))\n  | t_times: forall (t s : term) (c : context), transition' (c_eval (times t s) c) (c_eval t (times_r s :: c))\n  | t_var  : forall (x : var_name) (c : context), transition' (c_eval (var x) c) (c_eval (num (env x)) c)\n  | t_empty  : forall v : value, transition' (c_eval (v:term) empty) (c_final v)\n  | t_plus_r : forall (t : term) (v : value) (c : context), transition' (c_eval (v:term) (plus_r t :: c)) (c_eval t (plus_l v :: c))\n  | t_plus_l : forall (v v0 : value) (c : context) (t : term),\n                 contract (r_plus v0 v) = Some t -> transition' (c_eval (v:term) (plus_l v0 :: c)) (c_eval t c)\n  | t_times_r: forall (t : term) (v : value) (c : context), transition' (c_eval (v:term) (times_r t :: c)) (c_eval t (times_l v :: c))\n  | t_times_l: forall (v v0 : value) (c : context) (t : term),\n                 contract (r_times v0 v) = Some t -> transition' (c_eval (v:term) (times_l v0 :: c)) (c_eval t c).\n\n  Definition transition := transition'.\n  Inductive trans_close : configuration -> configuration -> Prop :=\n  | one_step   : forall (c0 c1 : configuration), transition c0 c1 -> trans_close c0 c1\n  | multi_step : forall (c0 c1 c2 : configuration), transition c0 c1 -> trans_close c1 c2 -> trans_close c0 c2.\n\n  Inductive eval : term -> value -> Prop :=\n  | e_intro : forall (t : term) (v : value), trans_close (c_init t) (c_final v) -> eval t v.\n\n  Lemma trPE_M : forall w w' : configuration, PEM.transition w w' -> transition w w'.\n  Proof with eauto.\n    assert (numeq : forall (n : nat), Arith_Lang.num n = value_to_term (Arith_Lang.v_num n))...\n    intros w w' H; inversion H; subst;\n    try constructor; destruct t; inversion DT; subst; try constructor.\n    inversion CONTR; subst; constructor.\n    rewrite numeq; constructor.\n    destruct ec; inversion DC; subst; destruct v; inversion CONTR; subst; rewrite numeq; constructor...\n    destruct ec; inversion DC; subst; rewrite numeq; constructor...\n  Qed.\n  Hint Resolve trPE_M.\n\n  Lemma tcPE_M : forall w w' : configuration, PEM.AM.trans_close w w' -> trans_close w w'.\n  Proof with eauto.\n    intros w w' H; induction H; subst; [ constructor 1 | econstructor 2]...\n  Qed.\n\n  Lemma evalPE_M : forall t v, PEM.AM.eval t v -> eval t v.\n  Proof.\n    intros t v H; inversion H; constructor; apply tcPE_M; auto.\n  Qed.\n  Hint Resolve evalPE_M.\n\n  Lemma trM_PE : forall w w' : configuration, transition w w' -> PEM.AM.transition w w'.\n  Proof with eauto.\n    intros w w' H; inversion H; subst; econstructor; simpl...\n  Qed.\n  Hint Resolve trM_PE.\n\n  Lemma tcM_PE : forall w w' : configuration, trans_close w w' -> PEM.AM.trans_close w w'.\n  Proof with eauto.\n    induction 1; [ constructor 1 | econstructor 2]...\n  Qed.\n\n  Lemma evalM_PE : forall t v, eval t v -> PEM.AM.eval t v.\n  Proof.\n    intros t v H; inversion H; constructor; apply tcM_PE; auto.\n  Qed.\n  Hint Resolve evalM_PE.\n\n  Theorem ArithMachineCorrect : forall (t : term) (v : value), Arith_Sem.eval t v <-> eval t v.\n  Proof with auto.\n    intros t v; rewrite Arith_Ref_Sem.eval_red_ref; rewrite PEM.push_enter_correct; split...\n  Qed.\n\nEnd PEArithMachine.\n", "meta": {"author": "fsieczkowski", "repo": "Refocusing", "sha": "52bd620d5179cf660aa2c84ae7a8593927ab85ee", "save_path": "github-repos/coq/fsieczkowski-Refocusing", "path": "github-repos/coq/fsieczkowski-Refocusing/Refocusing-52bd620d5179cf660aa2c84ae7a8593927ab85ee/substitutions/simple_arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.669805455174876}}
{"text": "Require Import BinInt ZArith_dec Zorder.\nRequire Export Id.\nRequire Export State.\nRequire Export Expr.\n\nFrom hahn Require Import HahnBase.\n\nDefinition eval_op (op : bop) (z1 z2 : Z) : option Z :=\n  match op with\n  | Add => Some (z1 + z2)%Z\n  | Sub => Some (z1 - z2)%Z\n  | Mul => Some (z1 * z2)%Z\n  | Div =>\n    match z2 with\n    | 0%Z => None\n    | _   => Some (Z.div z1 z2)\n    end\n  | Mod =>\n    match z2 with\n    | 0%Z => None\n    | _   => Some (Z.modulo z1 z2)\n    end\n  | Le =>\n    match Ztrichotomy_inf z1 z2 with\n    | inleft  _ => Some 1%Z\n    | _ => Some 0%Z\n    end\n  | Lt =>\n    match Ztrichotomy_inf z1 z2 with\n    | inleft (left _) => Some 1%Z\n    | _ => Some 0%Z\n    end\n  | Ge =>\n    match Ztrichotomy_inf z1 z2 with\n    | inleft (right _)\n    | inright _ => Some 1%Z\n    | _ => Some 0%Z\n    end\n  | Gt =>\n    match Ztrichotomy_inf z1 z2 with\n    | inright _ => Some 1%Z\n    | _ => Some 0%Z\n    end\n  | Eq =>\n    match Ztrichotomy_inf z1 z2 with\n    | inleft (right _) => Some 1%Z\n    | _ => Some 0%Z\n    end\n  | Ne =>\n    match Ztrichotomy_inf z1 z2 with\n    | inleft (right _) => Some 0%Z\n    | _ => Some 1%Z\n    end\n  | And =>\n    match z1, z2 with\n    | 1%Z, 1%Z => Some 1%Z\n    | 0%Z, 0%Z \n    | 0%Z, 1%Z\n    | 1%Z, 0%Z => Some 0%Z\n    | _, _ => None\n    end\n  | Or =>\n    match z1, z2 with\n    | 0%Z, 0%Z => Some 0%Z\n    | 0%Z, 1%Z\n    | 1%Z, 0%Z\n    | 1%Z, 1%Z => Some 1%Z\n    | _, _ => None\n    end\n  end.\n\nFixpoint cfold (e : expr) : expr :=\n  match e with\n  | Bop op e1 e2 =>\n    let (c1, c2) := (cfold e1, cfold e2) in\n    match c1, c2 with\n    | Nat z1, Nat z2 =>\n      match eval_op op z1 z2 with\n      | Some v1 => Nat v1\n      | _       => Bop op c1 c2\n      end\n    | _, _ => Bop op c1 c2\n    end\n  | _ => e\n  end.\n\nLemma cfold_correct (e : expr) : cfold e ~e~ e.\nProof. admit. Admitted.\n", "meta": {"author": "semantics-classroom", "repo": "semantics-problems-dj-kostya", "sha": "d82830853a84c68320c851e9e67d9d9aecdc6f2f", "save_path": "github-repos/coq/semantics-classroom-semantics-problems-dj-kostya", "path": "github-repos/coq/semantics-classroom-semantics-problems-dj-kostya/semantics-problems-dj-kostya-d82830853a84c68320c851e9e67d9d9aecdc6f2f/src/ConstantFolding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6698054521495459}}
{"text": "Require Import XR_Rmin.\nRequire Import XR_Rle_dec.\nRequire Import XR_Rle_trans.\nRequire Import XR_Rnot_le_lt.\n\nLocal Open Scope R_scope.\n\nLemma Rle_min_compat_l : forall x y z, x <= y -> Rmin z x <= Rmin z y.\nProof.\n  intros x y z.\n  intro h.\n  unfold Rmin.\n  destruct (Rle_dec z x) as [ hminxl | hminxr ] ;\n  destruct (Rle_dec z y) as [ hminyl | hminyr ].\n  {\n    right.\n    reflexivity.\n  }\n  {\n    apply Rle_trans with x.\n    { exact hminxl. }\n    { exact h. }\n  }\n  {\n    left.\n    apply Rnot_le_lt.\n    exact hminxr.\n  }\n  { exact h. }\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_Rle_min_compat_l.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6697998435926145}}
{"text": "Definition compose {A B C: Prop} (f: A -> B) (g: B -> C) (x: A) := g (f (x)).\n\nLemma transitive : forall A B C D: Prop, forall f: A -> B, forall g: B -> C, forall h: C -> D, forall x: A, h ((compose f g) x) = (compose g h) (f x).\nProof.\n  intros.\n  unfold compose.\n  reflexivity.\nQed.\n", "meta": {"author": "ml4tp", "repo": "gamepad", "sha": "7092f50a96eae9a862e72ecb8a55a217fa97723c", "save_path": "github-repos/coq/ml4tp-gamepad", "path": "github-repos/coq/ml4tp-gamepad/gamepad-7092f50a96eae9a862e72ecb8a55a217fa97723c/examples/implicit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6697998385653774}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom Equations Require Import Equations.\nSet Equations With UIP.\n\nSection list.\n\nVariable (A : Set) (A_eqdec : EqDec A).\n\nInductive list := nil | cons : A -> list -> list.\n\nDerive NoConfusion EqDec for list.\n\nFixpoint length (l : list) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => (length l').+1\n  end.\n\nEnd list.\n\nSection tuple.\n\nVariable (A : Set) (A_eqdec : EqDec A).\n\nInductive tuple i := { l : list A; p : (length _ l == i) = true }.\n\n(* Derive NoConfusionHom seems much slower, so we use Derive NoConfusion *)\n(* Time Equations Derive NoConfusionHom for t. *)\n\n(* Equations Derive NoConfusion EqDec for bool.\nEquations Derive NoConfusion EqDec for nat. *)\nTime Equations Derive NoConfusion EqDec for tuple.\n\nEnd tuple.\n\nSucceed Check tuple_eqdec.\n", "meta": {"author": "eponier", "repo": "compare-eq", "sha": "cc2da184e747d0ad6ada8597e1ebf03377e413e2", "save_path": "github-repos/coq/eponier-compare-eq", "path": "github-repos/coq/eponier-compare-eq/compare-eq-cc2da184e747d0ad6ada8597e1ebf03377e413e2/features/tuple/equations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6697998288729897}}
{"text": "(* (c) Copyright Christian Doczkal, Saarland University                   *)\n(* Distributed under the terms of the CeCILL-B license                    *)\nRequire Import Relations Recdef.\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import all_ssreflect.\nFrom libs Require Import edone bcase fset base.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(** * Directed Acyclic Graphs *)\n\n(** ** Termination and Transitive Closure *)\n\nInductive sn (X : Type) (R : X -> X -> Prop) (x : X) : Prop :=\n  SN : (forall y, R x y -> sn R y) -> sn R x.\n\nInductive star (X : Type) (R : X -> X -> Prop) (x : X) : X -> Prop :=\n| Star0 : star R x x\n| StarL y z : R x z -> star R z y -> star R x y.\n\nDefinition terminates X (e : X -> X -> Prop) := forall x, sn e x.\n\nLemma sn_preimage T1 T2 (e1 : T1 -> T1 -> Prop) (e2 : T2 -> T2 -> Prop) (h : T1 -> T2) x :\n  (forall x y, e1 x y -> e2 (h x) (h y)) -> sn e2 (h x) -> sn e1 x.\nProof.\n  move eqn:(h x) => v A B. elim: B h x A eqn => {v} - v _ ih h x A eqn.\n  apply: SN => y /A. rewrite eqn => /ih; eauto.\nQed.\n\nLemma terminates_gtn : terminates (fun n m => m < n). \nProof. \n  move => n. elim: n {-2}n (leqnn n) => [|n IHn] m Hm ;constructor. \n  - move => k Hk. by move: (leq_trans Hk Hm).\n  - move => k Hk. apply: IHn. rewrite -ltnS. exact: leq_trans Hm.\nQed.\n\nLemma terminates_measure T (f : T -> nat) (e : T -> T -> Prop)  :\n      (forall x y, e x y -> f y < f x) -> terminates e.\nProof. move => H x. exact: sn_preimage (terminates_gtn (f x)). Qed.\n\n(** ** Finite Rooted Labeled Graphs *)\n\nRecord graph (L : Type) :=\n  Graph { vertex :> finType ; edge : rel vertex ; label : vertex -> L  }.\n\nRecord rGraph (L : Type) := RGraph {\n    graph_of :> graph L ;\n    root : graph_of ;\n    rootP x : connect (@edge _ graph_of) root x }.\n\nSection GraphTheory.\n  Variables (L : choiceType) (p : L -> {fset L} -> bool).\n  Implicit Types (G : graph L) (rG : rGraph L).\n\n  Definition erel G := (@edge _ G).\n\n  Definition glocal G := [forall x : G, p (label x) [fset (label y) | y <- fset (edge x)]].\n  Definition respects e G := [forall x : G, forall y : G, edge x y ==> e (label x) (label y)].\n\n  Definition leaf G (x:G) := ~~ [exists y, edge x y].\nEnd GraphTheory.\n\nArguments erel [L] G _ _.\nArguments existT [A] [P] x _.\n\n(** The reachable subgraph of every element is rooted at that element *)\n\nDefinition restrict (T : finType) (P : pred T) (Tp : subType P) (e : rel T) :=\n  fun x y : Tp => e (val x) (val y).\nArguments restrict [T P] Tp e x y.\n\nLemma connect_subtype (T : finType) (x0 : T) (e : rel T) (Tp : subFinType (connect e x0)) :\n  forall x p, connect (restrict Tp e) (Sub x0 p) x.\nProof.\n  move => x. case: (SubP x) => {x} - x Px. \n  case/connectP : Px (Px) => pth. elim/last_ind: pth x => [x _ -> Px /= p|pth y IH x /=].\n  - by rewrite (bool_irrelevance p Px) connect0.\n  - rewrite rcons_path last_rcons.\n    case/andP => Pth xy E Px p. subst.\n    have conn : connect e x0 (last x0 pth) by apply/connectP; exists pth.\n    apply: connect_trans.\n    + exact: IH.\n    + apply: connect1. by rewrite /restrict !SubK.\nQed.\n\n(** Disjoint Union of finite graphs *)\n\nSection Disjoint.\n  Variables (L : Type) (I:finType) (G : I -> graph L).\n\n  Definition lift_edge (x y : {i : I & G i}) :=\n    (tag x == tag y) && edge (tagged x) (tagged_as x y).\n\n  Lemma lift_eq (i : I) (x y : G i)  :\n    lift_edge (existT i x) (existT i y) = edge x y.\n  Proof. by rewrite /lift_edge /= eqxx tagged_asE. Qed.\n\n  Lemma lift_eqn (ix iy : I) (x : G ix) (y : G iy)  :\n    ix != iy -> lift_edge (existT ix x) (existT iy y) = false.\n  Proof. by rewrite /lift_edge /= => /negbTE ->. Qed.\n\n  Lemma liftE (i j : I) (x : G i) (y : G j) :\n    lift_edge (existT i x) (existT j y) -> j = i.\n  Proof. by case/andP => /= /eqP. Qed.\n\n  Lemma lift_connect (i : I) (x y : G i) :\n    connect (@edge _ (G i)) x y -> connect lift_edge (existT i x) (existT i y).\n  Proof. case/connectP => p.\n    elim: p x y => /= [x y _  ->|z p IHp x y /andP [? ?] ?]; first exact: connect0.\n    apply: (@connect_trans _ _ (existT i z)); last exact: IHp.\n    by rewrite connect1 // lift_eq.\n  Qed.\nEnd Disjoint.\n", "meta": {"author": "chdoc", "repo": "comp-dec-modal", "sha": "8b29cf6aae2d8fa941efd66f90c4f00b95eab084", "save_path": "github-repos/coq/chdoc-comp-dec-modal", "path": "github-repos/coq/chdoc-comp-dec-modal/comp-dec-modal-8b29cf6aae2d8fa941efd66f90c4f00b95eab084/CTL/dags.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6697998195426883}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*                                                            *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\n(* A inductive characterization of list bi-inclusion\n    as closure under contraction and permutation\n\n    The proof does not require decidable equality\n    and uses the somehow generalized PHP that\n    states m ⊆ l and |l| <= |m| -> m has dup \\/ l ~p m\n\n *)\n\nRequire Import Arith Lia List Permutation.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac php.\n\nFrom Undecidability.Shared.Libs.DLW.Wf \n  Require Import measure_ind.\n\nSet Implicit Arguments.\n\nLocal Reserved Notation \"x ≡ y\" (at level 70, no associativity).\nLocal Reserved Notation \"x ⪼ y\" (at level 70, no associativity).\n\nLocal Notation lhd := list_has_dup.\nLocal Infix \"~p\" := Permutation (at level 70, no associativity).\nLocal Notation \"⌊ l ⌋\" := (length l) (at level 1, format \"⌊ l ⌋\").\n\nLocal Infix \"∈\" := In (at level 70, no associativity).\nLocal Infix \"⊆\" := incl (at level 70, no associativity).\nLocal Infix \"≃ₛ\" := (fun l p => l ⊆ p /\\ p ⊆ l) (at level 70, no associativity).\n\nSection incl_extra.\n\n  Variable (X : Type).\n\n  Implicit Type (l : list X).\n\n  Hint Resolve incl_refl incl_tl incl_cons incl_nil_l : core.\n\n  Fact lequiv_refl l : l ≃ₛ l.\n  Proof. split; auto. Qed.\n\n  Fact lequiv_sym l m : l ≃ₛ m -> m ≃ₛ l.\n  Proof. simpl; tauto. Qed.\n\n  Fact lequiv_trans l m k : l ≃ₛ m -> m ≃ₛ k -> l ≃ₛ k.\n  Proof. intros [] []; split; apply incl_tran with m; auto. Qed.\n\n  Fact incl_cons_simpl x l m : l ⊆ m -> x::l ⊆ x::m.\n  Proof. intros; apply incl_cons; simpl; auto. Qed.\n\n  Fact incl_tail_simpl x l : l ⊆ x::l.\n  Proof. auto. Qed.\n\n  Hint Resolve incl_cons_simpl incl_tail_simpl : core.\n\n  Fact incl_swap (x y : X) l : x::y::l ⊆ y::x::l.\n  Proof. intros ? [ -> | [ -> | ] ]; simpl; auto. Qed.\n\n  Fact incl_cntr (x : X) l : x::x::l ⊆ x::l.\n  Proof. intros ? [ -> | [ -> | ] ]; simpl; auto. Qed.\n\n  Fact lequiv_swap x y l : x::y::l ≃ₛ y::x::l.\n  Proof. split; apply incl_cons; simpl; auto. Qed.\n\n  Fact lequiv_app_comm l m : l++m ≃ₛ m++l.\n  Proof. split; intros ?; rewrite !in_app_iff; tauto. Qed.\n\n  Fact incl_cons_l_inv l m x : x::m ⊆ l -> x ∈ l /\\ m ⊆ l.\n  Proof.\n    intros H; split.\n    + apply H; simpl; auto.\n    + apply incl_tran with (2 := H); simpl; auto.\n  Qed.\n\n  Hint Resolve perm_skip Permutation_cons_app : core.\n\n  Fact incl_app_r_inv l m p : m ⊆ l++p -> exists m1 m2, m ~p m1++m2 /\\ m1 ⊆ l /\\ m2 ⊆ p.\n  Proof.\n    induction m as [ | x m IHm ].\n    + exists nil, nil; auto.\n    + intros H; apply incl_cons_l_inv in H as (H1 & H2).\n      destruct (IHm H2) as (m1 & m2 & H3 & H4 & H5).\n      apply in_app_or in H1 as [].\n      * exists (x::m1), m2; simpl; auto.\n      * exists m1, (x::m2); simpl; auto.\n  Qed.\n  \n  Fact incl_cons_r_inv x l m : \n         m ⊆ x::l -> exists m1 m2, m ~p m1 ++ m2 /\\ Forall (eq x) m1 /\\ m2 ⊆ l.\n  Proof.\n    intros H.\n    apply (@incl_app_r_inv (x::nil) _ l) in H as (m1 & m2 & H1 & H2 & H3).\n    exists m1, m2; msplit 2; auto.\n    rewrite Forall_forall.\n    intros a Ha; apply H2 in Ha; destruct Ha as [ | [] ]; auto.\n  Qed.\n\n  Fact incl_right_cons_choose x l m : m ⊆ x::l -> x ∈ m \\/ m ⊆ l.\n  Proof.\n    intros H; apply incl_cons_r_inv in H\n      as ([ | y m1] & m2 & H1 & H2 & H3).\n    + right.\n      intros u H; apply H3; revert H.\n      apply Permutation_in; auto.\n    + left.\n      apply Permutation_in with (1 := Permutation_sym H1).\n      rewrite Forall_forall in H2.\n      rewrite (H2 y); left; auto.\n  Qed.\n\n  Fact incl_left_right_cons x l y m : \n          x::l ⊆ y::m  -> y = x /\\ y ∈ l \n                       \\/ y = x /\\ l ⊆ m\n                       \\/ x ∈ m /\\ l ⊆ y::m.\n  Proof.\n    intros H; apply incl_cons_l_inv in H\n      as [ [|] H2 ]; auto.\n    apply incl_right_cons_choose in H2; tauto.\n  Qed.\n\n  Fact perm_incl_left m1 m2 l: m1 ~p m2 -> m2 ⊆ l -> m1 ⊆ l.\n  Proof. intros H1 H2 ? H; apply H2; revert H; apply Permutation_in; auto. Qed.\n\n  Fact perm_incl_right m l1 l2: l1 ~p l2 -> m ⊆ l1 -> m ⊆ l2.\n  Proof. intros H1 H2 ? ?; apply Permutation_in with (1 := H1), H2; auto. Qed.\n  \nEnd incl_extra.\n\nSection seteq.\n\n  Variable X : Type.\n\n  Implicit Types l : list X.\n\n  Inductive list_contract : list X -> list X -> Prop :=\n    | lc_nil      : nil ⪼  nil\n    | lc_skip     : forall x l m, l ⪼ m -> x::l ⪼ x::m\n    | lc_swap     : forall x y l, x::y::l ⪼ y::x::l\n    | lc_cntr     : forall x l, x::x::l ⪼ x::l\n    | lc_trans    : forall l m k, l ⪼ m -> m ⪼ k -> l ⪼ k\n  where \"l ⪼ m\" := (list_contract l m).\n\n  Hint Constructors list_contract : core.\n\n  Fact perm_lc l m : l ~p m -> l ⪼ m.\n  Proof. induction 1; eauto. Qed.\n\n  Fact lc_length l m : l ⪼ m -> ⌊m⌋ <= ⌊l⌋.\n  Proof. induction 1; simpl; lia. Qed.\n\n  Fact lc_nil_inv_l l : nil ⪼ l -> l = nil.\n  Proof.\n    intros H; apply lc_length in H.\n    destruct l; simpl in *; auto; lia.\n  Qed.\n\n  Hint Resolve perm_swap perm_trans : core.\n\n  Fact lc_length_perm l m : l ⪼ m -> ⌊m⌋ < ⌊l⌋ \\/ l ~p m.\n  Proof.\n    induction 1 as [ | ? ? ? ? [] | | \n      | ? ? ? ? [] ? [] ]; simpl; eauto;\n      repeat match goal with\n        | H: _ ⪼ _ |- _ => apply lc_length in H\n      end; lia.\n  Qed.\n\n  Fact lc_refl l : l ⪼ l.\n  Proof. apply perm_lc; auto. Qed.\n\n  (* When viewed as sets, the lists are equivalent,\n      ie closed under perm + contraction + RST *)\n\n  Inductive list_seteq : list X -> list X -> Prop :=\n    | lseq_nil   : nil ≡ nil\n    | lseq_skip  : forall x l m, l ≡ m -> x::l ≡ x::m\n    | lseq_swap  : forall x y l, x::y::l ≡ y::x::l\n    | lseq_dup   : forall x l, x::x::l ≡ x::l\n    | lseq_sym   : forall l m, l ≡ m -> m ≡ l \n    | lseq_trans : forall l m k, l ≡ m -> m ≡ k -> l ≡ k\n  where \"l ≡ m\" := (list_seteq l m).\n\n  Hint Constructors list_seteq : core.\n\n  Fact lc_lseq l m : l ⪼ m -> l ≡ m.\n  Proof. induction 1; eauto. Qed.\n\n  Hint Resolve perm_lc lc_lseq : core.\n\n  Fact perm_lseq l m : l ~p m -> l ≡ m.\n  Proof. auto. Qed.\n\n  Hint Resolve incl_refl incl_cons_simpl incl_swap incl_cntr incl_tl incl_tran : core.\n\n  Fact lseq_lequiv l m : l ≡ m -> l ≃ₛ m.\n  Proof.\n    induction 1 as [ | ? ? ? ? [] | | \n                   | ? ? ? []\n                   | ? ? ? ? [] ? [] ]; eauto.\n  Qed.\n \n  Hint Resolve lseq_lequiv : core.\n\n  Fact lc_lequiv l m : l ⪼ m -> l ≃ₛ m.\n  Proof. intro; apply lseq_lequiv; auto. Qed.\n\n  Hint Resolve incl_l_nil : core.\n\n  Fact lc_nil_inv_r l : l ⪼ nil -> l = nil.\n  Proof. intros H; apply lc_lequiv in H as []; auto. Qed.\n \n  Hint Resolve list_has_dup_swap in_eq in_cons in_list_hd0 in_list_hd1 : core.\n\n  Notation lhd_cons_iff := list_has_dup_cons_iff.\n\n  Fact lc_lhd l m : l ⪼ m -> lhd m -> lhd l.\n  Proof.\n    induction 1 as [ | x l m H IH | | | ]; eauto.\n    rewrite !lhd_cons_iff; intros []; auto.\n    apply lc_lequiv in H as []; auto.\n  Qed.\n\n  Fact lseq_incl l m : l ≡ m -> l ⊆ m.\n  Proof. intro; apply lseq_lequiv; auto. Qed.\n\n  (* A list with a dup is contractible in a smaller one *) \n\n  Lemma lhd_lc l : lhd l -> exists m, l ⪼ m /\\ ⌊m⌋ < ⌊l⌋.\n  Proof.\n    induction 1 as [ l x H | l x H (m & H1 & H2) ].\n    + apply in_split in H as (l1 & l2 & ->).\n      exists (l1++x::l2); split; simpl; try lia.\n      apply lc_trans with (x::x::l1++l2).\n      * apply perm_lc, perm_skip, Permutation_sym,\n              Permutation_cons_app; auto.\n      * apply lc_trans with (1 := lc_cntr _ _), perm_lc,\n              Permutation_cons_app; auto.\n    + exists (x::m); split; simpl; auto; lia.\n  Qed.\n\n  Hint Resolve lc_lseq : core.\n\n  Lemma lhd_lseq l : lhd l -> exists m, l ≡ m /\\ ⌊m⌋ < ⌊l⌋.\n  Proof. intro H; apply lhd_lc in H as (? & ? & ?); eauto. Qed.\n\n  Hint Constructors list_contract : core.\n\n  Hint Resolve lc_refl lc_lhd : core.\n\n  Lemma lequiv_php_choose l m : l ≃ₛ m -> l ~p m \\/ lhd l \\/ lhd m.\n  Proof.\n    intros [ I1 I2 ].\n    destruct (le_lt_dec ⌊m⌋ ⌊l⌋) as [ H1 | H1 ].\n    + apply length_le_and_incl_implies_dup_or_perm in H1; tauto.\n    + apply finite_php_dup in H1; tauto.\n  Qed.\n\n  (* if l and m are equivalent, either\n     1) l ~p m in which case l is contractible into m\n     2) lhd l hence l is contracted into a smaller one and recursion\n     3) lhd m hence m is contracted into a smaller one and recursion\n   *)\n\n  Hint Resolve lequiv_trans : core.\n\n  Lemma lequiv_lc l m : l ≃ₛ m -> exists c, l ⪼ c /\\ m ⪼ c.\n  Proof.\n    induction on l m as IH with measure (⌊l⌋+⌊m⌋); intros H1.\n    destruct (lequiv_php_choose H1) as [ H2 | [ H2 | H2 ] ]; eauto.\n    + apply lhd_lc in H2 as (c & ? & ?).\n      destruct (IH c m) as (d & ? & ?); eauto; lia.\n    + apply lhd_lc in H2 as (c & ? & ?).\n      destruct (IH l c) as (d & ? & ?); eauto; lia.\n  Qed.\n\n  Lemma lequiv_lseq l m : l ≃ₛ m -> l ≡ m.\n  Proof. intros H; apply lequiv_lc in H as (c & []); eauto. Qed.\n\n  Hint Resolve lequiv_lseq : core.\n\n  (* seteq is equivalent to bi-inclusion *)\n\n  Theorem lseq_lequiv_iff l m : l ≡ m <-> l ≃ₛ m.\n  Proof. split; auto. Qed.\n\n  (* A nice induction principle for list bi-inclusion *)\n\n  Section lequiv_ind.\n\n    Variables (P : list X -> list X -> Prop)\n              (HP0 : P nil nil)\n              (HP1 : forall x l m, l ≃ₛ 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 x l, P (x::x::l) (x::l))\n              (HP4 : forall l m, l ≃ₛ m -> P l m -> P m l)\n              (HP5 : forall l m k, l ≃ₛ m -> P l m -> m ≃ₛ k -> P m k -> P l k).\n\n    Theorem lequiv_ind l m : l ≃ₛ m -> P l m.\n    Proof. rewrite <- lseq_lequiv_iff; induction 1; eauto. Qed.\n\n  End lequiv_ind.\n\n  Lemma lequiv_lhd_or_contract l m : l ≃ₛ m -> lhd m \\/ l ⪼  m.\n  Proof.\n    simpl; intros H.\n    destruct lequiv_lc with (1 := H) as (d & H1 & H2).\n    apply lc_length_perm in H2 as [ H2 | H2 ].\n    + apply finite_php_dup in H2; auto.\n      apply lc_lseq, lseq_lequiv in H1.\n      apply incl_tran with l; tauto.\n    + right; apply lc_trans with (1 := H1).\n      apply perm_lc, Permutation_sym; auto.\n  Qed.\n\nEnd seteq.\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/seteq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6697998141533641}}
{"text": "\n\n(*Technically we haven't learned how to do Definitions yet but I didn't want to type this twice so looked ahead*)\nDefinition sum5 (a1:nat) (a2:nat) (a3:nat) (a4:nat) (a5:nat) : nat :=\n    a1 + a2 + a3 + a4 + a5.\n\nCheck sum5.\n\nCompute sum5 1 1 1 1 1. (*5*)\nCompute sum5 1 2 3 4 5. (*15*)", "meta": {"author": "James-Oswald", "repo": "Coq-In-A-Hurry", "sha": "d9ba73090affe7d7c8a324bf726f709a7b949a15", "save_path": "github-repos/coq/James-Oswald-Coq-In-A-Hurry", "path": "github-repos/coq/James-Oswald-Coq-In-A-Hurry/Coq-In-A-Hurry-d9ba73090affe7d7c8a324bf726f709a7b949a15/Chapter1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.669799814153364}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLemma ltn_perm_iota n l (p : perm_eq l (iota 0 n.+1)) m : nth 0 l m < n.+1. \nProof.\nhave [ltms|] := boolP (m < size l); last by rewrite -leqNgt => lesm; rewrite nth_default.  \nmove: (perm_mem p) (@mem_nth _ 0 _ _ ltms) => ->.\nby rewrite mem_iota add0n => /andP [].\nQed.\n\nSection RankImpl.\n\nVariables (n : nat) (T : eqType) (r : rel T) (s : n.+1.-tuple T).\n\nVariable (tr : transitive r) (rr : reflexive r) (totr : total r) (ar : antisymmetric r).\n\nLet A := 'I_n.+1.\n\nLet ranking := n.+1.-tuple 'I_n.+1.\n\nNotation i0 := ord0.\nNotation t0 := (tnth s ord0).\n\nLet si := zip_tuple s (ord_tuple n.+1).\n\nLet ri := \n      [rel si1 si2 : T * 'I_n.+1 | r si1.1 si2.1 && ((si1.1 == si2.1) ==> (si1.2 <= si2.2))].\n\nLemma transitive_ri: transitive ri.\nProof. \nmove=> x y z /=; rewrite /ri /= => /andP [ryx /implyP leyx] /andP [rxy /implyP lexz].\napply/andP; split; first by rewrite (@tr x.1).\napply/implyP => /eqP eqyz.\nrewrite -eqyz in lexz.\nhave [eqxy1|] := boolP (y.1 == x.1). \n- by rewrite (@leq_trans x.2) // ?leyx // ?leyz lexz // eq_sym.\n- rewrite -eqyz in rxy.\n  have -> // : y.1 = x.1.\n    apply: ar; rewrite ryx rxy => //.\n    by rewrite eq_refl. \nQed.  \n\nLemma reflexive_ri: reflexive ri. \nProof. move=> j. rewrite /ri /=. by rewrite rr leqnn //= implybT. Qed.\n\nLemma total_ri: total ri. \nProof. \nmove=> x y; rewrite /ri /=. \nhave [|//] := boolP (x.1 == y.1).\n- rewrite eq_sym => /eqP ->.\n  rewrite eq_refl !implyTb.\n  move: (leq_total x.2 y.2) => /orP [le2|le2']; first by rewrite le2 rr.\n  by rewrite le2' rr orbT.\n- rewrite -(negbK (y.1 == x.1)) eq_sym => -> /=.\n  by rewrite !andbT totr.\nQed.\n\nLemma anti_ri : antisymmetric ri.\nProof. \nmove=> x y; rewrite /ri /= => /andP [/andP [rxy lexy2]] /andP [ryx leyx2].\nhave eq11: x.1 = y.1 by apply: ar; rewrite rxy ryx.\nrewrite eq11 eq_refl ?implyTb in lexy2 leyx2.\nhave/eqP eq22: x.2 == y.2.\n  by rewrite -(inj_eq val_inj) /= eqn_leq lexy2 leyx2.\nby rewrite (surjective_pairing x) (surjective_pairing y) eq22 eq11.\nQed.\n\nLet si' := sort ri si.\n\nLet is_rank (rank : A -> 'I_n.+1) (rval : 'I_n.+1 -> T) :=\n  (forall (i j : A), i <= j -> r (rval i) (rval j))\n  /\\ (forall i : 'I_n.+1, rval (rank i) = tnth s i).\n\nLocal Lemma ltn_pred2k k l (p : perm_eq l (iota 0 n.+1)) :\n  find [pred t | t.2 == k] [seq nth (t0, i0) si i | i <- l] < size l.\nProof.\nhave kinl: val k \\in l by rewrite (perm_mem p) mem_iota add0n ltn_ord. \nhave nth_si : nth (t0, i0) si k = (tnth s k, k).\n  by rewrite [in RHS](tnth_nth t0) nth_zip ?nth_ord_enum \n           1?(tnth_nth t0) ?size_enum_ord ?size_tuple.\nset l' := (X in find _ X); set t2k := [pred t | t.2 == k].   \nhave // : find t2k l' < size l.\n  have -> : size l = size l' by rewrite size_map. \n  rewrite -has_find /=.  \n  apply/(has_nthP (t0, i0)). \n  exists (index (tnth s k, k) l') => /=; first by rewrite index_mem -nth_si map_f.\n  by rewrite nth_index //= -nth_si map_f.  \nQed.\n\nDefinition zip_rank : A -> 'I_n.+1.\nhave zip_rank_bnd (i : A) : find [pred t | t.2 == i] si' < n.+1. \n  rewrite /si' /=; have [l p ->] := perm_iota_sort ri (t0, i0) si. \n  rewrite size_tuple in p.   \n  by rewrite (@leq_trans (size l)) ?ltn_pred2k // (perm_size p) size_iota.\nexact: (fun (i : A) => Ordinal (zip_rank_bnd i)).\nDefined.\n\nDefinition zip_rval := (fun (r : 'I_n.+1) => (nth (t0, i0) si' r).1).\n\nLemma is_rank_zip : is_rank zip_rank zip_rval.\nProof. \nrewrite /zip_rank /zip_rval /=.\nhave szsn1 : size s = size (enum 'I_n.+1) by rewrite size_tuple ?cardE size_enum_ord.\nhave find_zip t (alln1 : forall j, j \\in t -> j < n.+1) k : \n  find [pred x | x.2 == k] [seq nth (t0, i0) si i | i <- t] = \n    find [pred x | x == val k] t. \n  elim: t alln1 => [//=|x t IH alln1 /=].\n  rewrite nth_zip /= -?(inj_eq val_inj) /= ?nth_enum_ord ?alln1 ?mem_head // ?IH //\n          ?size_tuple ?cardE ?size_enum_ord // => q qint.\n  by rewrite alln1 // inE qint orbT.\nsplit=> [i j leij|k].   \n- have ssi' : sorted ri si' by rewrite sort_sorted //; exact: total_ri.\n  move: (sorted_leq_nth transitive_ri reflexive_ri (t0, i0) ssi' i j).\n  by rewrite ?inE ?size_tuple ?ltn_ord // => /(_ erefl erefl leij) /= /andP [].    \n- rewrite /si' /=; have [l p ->] := perm_iota_sort ri (t0, i0) si.   \n  have kinl: val k \\in l. \n    by rewrite (perm_mem p) mem_iota add0n size_zip size_tuple /= size_enum_ord minnn.\n  rewrite size_tuple in p.   \n  set l' := (X in find _ X); set t2k := [pred t | t.2 == k].  \n  have ltfinds : find t2k l' < size l by rewrite ltn_pred2k.\n  rewrite (nth_map 0) /=; last by exact: ltfinds.\n  rewrite nth_zip ?[RHS](tnth_nth t0) //=. \n  have nthfindl' : nth 0 l (find t2k l') = (nth (t0, i0) l' (find t2k l')).2.\n    by rewrite (nth_map 0) ?nth_zip /= ?nth_enum_ord //  ltn_perm_iota.\n  rewrite nthfindl'.  \n  set ikl' := (find t2k l'); pose ikl := index (val k) l.   \n  have eqnths : nth 0 l ikl' = nth 0 l ikl.\n    rewrite nth_index //=. \n    move: (ltfinds); have -> : size l = size l' by rewrite size_map. \n    rewrite -has_find => /(has_nthP (t0, i0)) [j ltjs]. \n    rewrite size_map in ltjs.\n    rewrite nthfindl' (nth_map 0) // nth_zip /= -?(inj_eq val_inj) //=.\n    rewrite (nth_map 0) // nth_zip /= ?nth_enum_ord ?ltn_perm_iota //.  \n    rewrite find_zip // => [nthljk|q /(nthP 0) [? _ <-]]; last by rewrite ltn_perm_iota.\n    have -> : (find [pred x | x == val k] l) = j; last by exact/eqP.\n       case: findP => [/hasPn /(_ (nth 0 l j)) /=|q ltql pre post]; \n         first by rewrite nthljk mem_nth // => /(_ erefl).\n       have/(uniqP 0)/(_ q j): uniq l by rewrite (perm_uniq p) iota_uniq.\n       apply; rewrite ?inE //.\n       move: (pre 0) => /= /eqP ->.\n       by rewrite (eqP nthljk).\n   by rewrite -nthfindl' eqnths nth_index.\nQed.\n\nEnd RankImpl.\n\nVariable (n' : nat).\nLet n := n'.+2.\n\nDefinition A := 'I_n.\n\nDefinition bids := A -> nat.\nDefinition vals := A -> nat.\n\nSection RankDef.\n\nDefinition is_rank (b : bids) (rank : A -> 'I_n) (rval : 'I_n -> nat) :=\n  (forall (i j : 'I_n), i <= j -> rval j <= rval i)\n  /\\ (forall i : 'I_n, rval (rank i) = b i).\n\nRecord ranking (b : bids):= Ranking {  \n    rank : A -> 'I_n;\n    rval : 'I_n -> nat;\n    _ : is_rank b rank rval }.\n\nLemma rval_def (b : bids) (r : ranking b) i : rval r (rank r i) = b i.\nProof. by case: r => ? ? [h1 h2] /=. Qed.\n\nLemma rval_geq (b : bids) (r : ranking b) (i j : 'I_n) : i <= j -> rval r j <= rval r i. \n\nProof. by case: r => ? ? [h1 h2] /h1. Qed.\n\nDefinition differ_on (b b' : bids) (i : A):= forall j, i != j -> b j = b' j.\n\nLemma differ_on_sym (b b' : bids) i : differ_on b b' i -> differ_on b' b i.\nProof. by move=> d j neij; move: d => /(_ j neij) ->. Qed.\n\nDefinition buildr (b : bids) : ranking b.\nhave tr: transitive geq by move=> i j k /= ? ?; exact: (@leq_trans i).\nhave rr: reflexive geq. by move=> /= ?. \nhave totr : total geq by move=> i j /=; exact: leq_total.\nhave ar : antisymmetric geq by move=> i j /=;rewrite -eqn_leq => /eqP ->. \npose tb := mktuple b.\nhave/Ranking //: is_rank b (zip_rank geq tb) (zip_rval geq tb).\n  move: (is_rank_zip tb tr rr totr ar) => /= [rk rv].\n  by split=> // => i; rewrite -(tnth_mktuple b).\nDefined.\n\nLemma rank_stable (b b' : bids) i (h_diff : differ_on b b' i) :\n  let r := buildr b in\n  let r' := buildr b' in\n  forall (h_notmoved : rank r i = rank r' i) j (h_idx : rank r i != j),\n     rval r j = rval r' j.\nProof.\nset r := buildr b; set r' := buildr b'.\nmove=> /= eqrr'i rj.\nAdmitted.\n\nLemma rank_shift (b b' : bids)\n  (r : ranking b)\n  (r' : ranking b')\n  i\n  (h_diff : differ_on b b' i) \n  (h_rank : rank r i <= rank r' i)\n  :\n  forall j, rval r' j = if rank r i <= j < rank r' i then rval r (inord j.+1) else rval r j.\n(*¨  (forall (j : 'I_n), (j < rank r i) || (rank r' i <= j) -> rval r j = rval r' j)\n  /\\ (forall (j : 'I_n), \n      (rank r i <= j < rank r i) -> rval r (inord j.+1) = rval r' j). *)\nProof.\nAdmitted.\n \nDefinition U_SP (v : vals) (b : bids) (i : A) :=\n  let r := buildr b in \n  if rank r i == inord 0 then\n    v i - rval r (inord 1)\n  else\n    0\n.\n\nLemma SP_truthful\n   (v : vals) (b b': bids) (i : A)\n   (h_diff : differ_on b b' i) (h_truth : b i = v i) :\n   U_SP v b i >= U_SP v b' i.\nProof.\nrewrite /U_SP.\nset r := buildr b.\nset r' := buildr b'.\ncase: ifP => h_r2 => //; case: ifP => h_r1.\n- have h_idx: rank r i != inord 1.\n    by rewrite (eqP h_r1) -(inj_eq val_inj) /= !inordK.\n  have snd_eq : rval r (inord 1) = rval r' (inord 1).\n    apply: (rank_stable h_diff _ h_idx) => //.\n    by rewrite (eqP h_r1) (eqP h_r2).\n  by rewrite snd_eq. \n- (* overbidding case *)\n  have -> : rval r' (inord 1) = rval r (inord 0).\n    have ltr'r: rank r' i <= rank r i by rewrite (eqP h_r2) inordK. \n    rewrite (rank_shift (differ_on_sym h_diff) ltr'r) ifT ?inordK // (eqP h_r2) inordK //=.\n    rewrite (contraFltn _ h_r1) // leq_eqVlt ltn0 h_r1. \n    rewrite -(inj_eq val_inj) /= inordK // in h_r1.\n    by rewrite h_r1.\n  by rewrite -h_truth -(rval_def r) leq_subCl subn0 (@rval_geq _ _ (inord 0)) // inordK.\nQed.\n\nEnd RankDef.\n\n\n", "meta": {"author": "jouvelot", "repo": "mech.v", "sha": "d1d8a140f9c4d4a361acc91318d97bce8bcac0c6", "save_path": "github-repos/coq/jouvelot-mech.v", "path": "github-repos/coq/jouvelot-mech.v/mech.v-d1d8a140f9c4d4a361acc91318d97bce8bcac0c6/rank.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.7371581684030624, "lm_q1q2_score": 0.6697951028571272}}
{"text": "Require Import Relations.\nSection Sequences.\n Variable A : Set.\n\n Variable R : A -> A -> Prop. \n\n Lemma not_acc : forall a b:A, R a b -> ~ Acc R a -> ~ Acc R b.\n Proof.\n  intros a b H H0 H1.\n  absurd (Acc R a); auto.\n  generalize a H.\n  elim H1; auto.\n Qed.\n\n Lemma acc_imp : forall a b:A, R a b -> Acc R b -> Acc R a.\n Proof.\n  intros a b H H0.\n  generalize a H. \n  elim H0; auto.\n Qed.\n\n\n Hypothesis W : well_founded R.\n Hint Resolve W.\n\t\n Section seq_intro.\n  Variable seq : nat -> A. \n\n  Let is_in_seq (x:A) :=  exists i : nat, x = seq i.\n\n  Lemma not_decreasing_aux : ~ (forall n:nat, R (seq (S n)) (seq n)). \n  Proof.\n   unfold not in |- *; intro dec.\n   cut (forall a:A, is_in_seq a -> ~ Acc R a).\n   intro H.\n   absurd (Acc R (seq 0)).\n   apply H.\n   exists 0; trivial. \n   apply W.\n   intro a; pattern a in |- *.\n   apply well_founded_ind with A R.\n   assumption.\n   intros x Hx H.\n   elim H.\n   intros i egi.  \n   cut (R (seq (S i)) (seq i)).\n   intro H1.\n   rewrite egi.\n   apply not_acc with (seq (S i)); auto.\n   apply Hx.\n   rewrite egi; auto.\n   exists (S i); auto.\n   auto.\n Qed.\n End seq_intro.\n\n Theorem not_decreasing :\n  ~ (exists seq : nat -> A, (forall i:nat, R (seq (S i)) (seq i))).\n Proof.\n  unfold not in |- *; intro H.\n  case H; intros s Hs.\n  absurd (forall i:nat, R (s (S i)) (s i)); auto.\n  apply not_decreasing_aux.\n Qed.\n\nEnd Sequences.\n\nRequire Import Relation_Operators.\n\nInductive R0  : nat->nat-> Prop :=\nr0_intro : R0 2 1.\n\nLemma R0_wf : well_founded  R0.\nsplit.\nintros.\ninversion H.\nsplit.\ninversion 1.\nQed.\n\nRequire Import Wf_nat.\n\nSearch well_founded.\nCheck (lt_wf: well_founded lt).\n\n\n\nHypothesis Uwf : well_founded (union _ lt R0).\n\n\nFixpoint s (n:nat) : nat :=\n match n with 0 => 1\n            | 1 => 2\n            | S (S p) => s p\n end.\n\nGoal False.\ndestruct (not_decreasing _ (union _ lt R0)).\napply Uwf.\nexists s.\nassert (forall i, union nat lt R0 (s (S i)) (s i) /\\\n                  union nat lt R0 (s (S (S i))) (s (S i))).\ninduction i;simpl.\nsplit.\nright;constructor.\nleft;auto with arith.\ndestruct IHi;split;auto.\nfirstorder.\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/newstuff/SRC/union_not_wf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6697950957863038}}
{"text": "Require Import ZArith.\nOpen Scope Z_scope.\n(* Types *)\nNotation Int P := {v:Z|P v}.\n(* Notation RefZ P  := (sig P Z). *)\n\nNotation Nat := ({v:Z| v >= 0}).\nDefinition Bool {b:bool} := {v:bool | v = b}.\n\nNotation \"` x\" := (proj1_sig x) (at level 10).", "meta": {"author": "lykmast", "repo": "coq-refinements", "sha": "0ec3cbfdcf9d26c14b2781d632d33d256938c765", "save_path": "github-repos/coq/lykmast-coq-refinements", "path": "github-repos/coq/lykmast-coq-refinements/coq-refinements-0ec3cbfdcf9d26c14b2781d632d33d256938c765/theories/Types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6697950889411342}}
{"text": "Require Import Relations.\nSection leibniz.\n Variable A : Type.\n \n\n Definition leibniz (a b:A) : Prop := forall P:A -> Prop, P a -> P b.\n\n Theorem leibniz_sym : symmetric A leibniz.\n Proof.\n  intros a b H Q; apply H; trivial.\n Qed.\n\n Theorem leibniz_refl : reflexive A leibniz. \n Proof.\n  intros a P; trivial.\n Qed.\n\n\n\n Theorem leibniz_trans : transitive A leibniz.\n Proof.\n  intros x y z Hxy Hyz; unfold leibniz; intros P H.\n  apply Hyz;  apply Hxy; assumption.\n Qed.\n\n\n #[local] Hint Resolve leibniz_trans leibniz_sym leibniz_refl : core.\n\n Theorem leibniz_equiv : equiv A leibniz.\n Proof.\n  now repeat split. \n Qed.\n\n\n Theorem leibniz_least :\n  forall R:relation A, reflexive A R -> inclusion A leibniz R.\n Proof.\n  intros R H x y H0; apply H0; apply H.\n Qed.\n\n\n Theorem leibniz_eq : forall a b:A, leibniz a b -> a = b.\n Proof.\n  intros a b H;   now apply H.\n Qed.\n\n Theorem eq_leibniz : forall a b:A, a = b -> leibniz a b.\n Proof.\n  intros a b e; rewrite e; unfold leibniz; auto.\n Qed.\n\n Theorem leibniz_ind :\n  forall (x:A) (P:A -> Prop), P x -> forall y:A, leibniz x y -> P y.\n Proof.\n  intros x P H y Hy; now apply Hy.\n Qed.\n\n\nEnd leibniz.\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/ch5_everydays_logic/SRC/leibniz.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6697640487177599}}
{"text": "Require Import Coq.Logic.ChoiceFacts.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.ClassicalChoice.\nRequire Import Coq.micromega.Psatz.\nRequire Import Coq.Arith.Arith.\nRequire Import Logic.lib.Coqlib.\nRequire Import Logic.lib.RelationPairs_ext.\nRequire Import Logic.GeneralLogic.KripkeModel.\nRequire Import Logic.SeparationLogic.Model.SeparationAlgebra.\nRequire Import Logic.SeparationLogic.Model.UpwardsClosure.\nRequire Import Logic.SeparationLogic.Model.DownwardsClosure.\nRequire Import Logic.SeparationLogic.Model.OrderedSA.\nRequire Import Logic.SeparationLogic.Model.OSAGenerators.\n\n\n\n(***********************************)\n(* ALGEBRAS ON NATURALS            *)\n(***********************************)\n \nSection nat_algs.\n\n  Definition nat_leR: Relation nat := le.\n  Definition nat_geR: Relation nat := ge.\n\n  Instance po_nat_leR: PreOrder (@Krelation _ nat_leR) := Nat.le_preorder.\n\n  Instance po_nat_geR: PreOrder (@Krelation _ nat_geR).\n  Proof.\n    constructor.\n    + hnf; intros; hnf; lia.\n    + hnf; intros; hnf in *; lia.\n  Qed.\n\n  Definition indexAlg: @SeparationAlgebra nat equiv_Join.\n  Proof. constructor; intros.\n         - inversion H; congruence.\n         - inversion H; inversion H0; subst.\n           exists mxyz; split; constructor; auto.\n  Defined.\n\n  (* upwards-closed*)\n  Instance IndexAlg_uSA:\n    @UpwardsClosedSeparationAlgebra _  nat_geR equiv_Join.\n  Proof.\n    hnf; intros.\n    inversion H; subst.\n    exists n, n. repeat split; auto.\n  Qed.\n\n  (* Increasing*)\n  Instance IndexAlg_increasing:\n    @IncreasingSeparationAlgebra _ nat_geR equiv_Join.\n  Proof.\n    constructor; intro.\n    hnf; intros. inversion H; subst.\n    hnf; reflexivity.\n  Qed.\n\n  (* Residual*)\n  Instance IndexAlg_residual:\n    @ResidualSeparationAlgebra _ nat_geR equiv_Join.\n  Proof.\n    constructor; intro.\n    exists n, n; split;\n    constructor;\n    reflexivity.\n  Qed.\n\n  (* Unital *)\n  Instance IndexAlg_unital:\n    @UnitalSeparationAlgebra _ nat_geR equiv_Join.\n  Proof.\n    apply <- (@incr_unital_iff_residual _ nat_geR _ equiv_Join).\n    + apply IndexAlg_residual.\n    + apply IndexAlg_increasing.\n  Qed.\n\n  (* Minimum Algebra *)\n  Inductive min_Join: nat -> nat -> nat -> Prop:=\n  | min_j x y z: z <= x -> z <= y -> min_Join x y z.\n\n  Definition minAlg: @SeparationAlgebra nat min_Join.\n  Proof.\n     constructor; intros.\n     - inversion H; subst; constructor; auto.\n     - inversion H; inversion H0; subst.\n       exists (Min.min my mz); split; constructor.\n       + apply Min.le_min_l.\n       + apply Min.le_min_r.\n       + transitivity mxy; auto.\n       + apply Min.min_glb.\n         * transitivity mxy; auto.\n         * auto.\n  Qed.\n\n  (* downwards closure of Index algebra *)\n  Lemma min_Join_is_downwards_closure: min_Join = @DownwardsClosure_J _ nat_geR equiv_Join.\n  Proof.\n    extensionality a.\n    extensionality b.\n    extensionality c.\n    unfold DownwardsClosure_J.\n    apply prop_ext.\n    split; intros.\n    + simpl.\n      inversion H; subst.\n      exists c, c.\n      split; [| split]; hnf; auto.\n    + destruct H as [a' [b' [? [? ?]]]].\n      inversion H1; subst.\n      constructor; auto.\n  Qed.\n\n  (* upwards-closed *)\n  Instance minAlg_uSA:\n    @UpwardsClosedSeparationAlgebra _ nat_geR min_Join.\n  Proof.\n    hnf; intros.\n    inversion H;  subst.\n    exists m1, m2; split; constructor;\n    first[ solve[transitivity m; auto] | reflexivity].\n  Qed.\n\n\n  (* downwards-closed *)\n  Instance minAlg_dSA:\n    @DownwardsClosedSeparationAlgebra _ nat_geR min_Join.\n  Proof.\n    hnf; intros.\n    inversion H; subst.\n    exists m; split ; constructor.\n    - transitivity m1; auto.\n    - transitivity m2; auto.\n  Qed.\n\n  (* Increasing *)\n  Instance minAlg_increasing:\n    @IncreasingSeparationAlgebra _ nat_geR min_Join.\n  Proof.\n    constructor; intro.\n    hnf; intros. inversion H; subst; auto.\n  Qed.\n\n  (*Residual*)\n  Instance minAlg_residual:\n    @ResidualSeparationAlgebra _ nat_geR min_Join.\n  Proof.\n    constructor; intro.\n    exists n, n; split.\n    constructor; reflexivity.\n    reflexivity.\n  Qed.\n\n  (* Unital *)\n  Instance minAlg_unital:\n    @UnitalSeparationAlgebra _ nat_geR min_Join.\n  Proof.\n    apply incr_unital_iff_residual.\n    apply minAlg_increasing.\n    apply minAlg_residual.\n  Qed.\n \n  \n(** *Sum Algebra on NAT*)\n\n  Inductive sum_Join: nat -> nat -> nat -> Prop:=\n  |sum_j x y z: x + y = z -> sum_Join x y z.\n\n  Definition sumAlg: @SeparationAlgebra _ sum_Join.\n  Proof.\n    constructor; intros.\n    - inversion H; subst.\n      rewrite Nat.add_comm;\n      constructor; auto.\n    - inversion H; inversion H0; subst.\n      exists (my+mz); split; try constructor; simpl;\n      lia.\n  Qed.\n\n  (* upwards-closed*)\n  Instance sumAlg_uSA:\n    @UpwardsClosedSeparationAlgebra _ nat_geR sum_Join.\n  Proof.\n    hnf; intros.\n    simpl in H0.\n    inversion H;  subst.\n    destruct (le_lt_dec n m1).\n    - exists n, 0; split; constructor; simpl; hnf; try lia.\n    - exists m1, (n - m1); split; constructor; simpl; hnf in *; try lia.\n  Qed.\n\n  (* downwards-closed*)\n  Instance sumAlg_dSA:\n    @DownwardsClosedSeparationAlgebra _ nat_geR sum_Join.\n  Proof.\n    hnf; intros.\n    simpl in H0, H1.\n    inversion H; subst.\n    exists (n1 + n2); split; simpl; try constructor; hnf in *; try lia.\n  Qed.\n\n  (* The only increasing is 0*)\n  Lemma sumAlg_zero_decreasing:\n  @increasing nat nat_geR sum_Join 0.\n  Proof. hnf; intros.\n       hnf.\n       inversion H; subst; lia.\n  Qed.\n\n  Lemma sumAlg_zero_decreasing_only:\n    forall x,\n      @increasing nat nat_geR sum_Join x -> x = 0.\n  Proof.\n    intros.\n    specialize (H 1 (x+1) ltac:(constructor; lia)).\n    simpl in H. hnf in H; lia.\n  Qed.\n  \n  (* Unital *)\n  Instance sumAlg_unital:\n    @UnitalSeparationAlgebra _ nat_geR sum_Join.\n  Proof.\n    constructor; intros.\n    - exists 0; split.\n      + exists n; split; simpl; try constructor; lia.\n      + hnf; intros.\n        inversion H; subst; simpl;\n        hnf; lia.\n  Qed.\n  \n  (*Residual*)\n  Instance sumAlg_residual:\n    @ResidualSeparationAlgebra _ nat_geR sum_Join.\n  Proof.\n    constructor; intro.\n    exists 0, n; split.\n    constructor; lia.\n    hnf; lia.\n  Qed.\n\n(** *Minimum Algebra on Positive integers*)\n  \n  Record natPlus: Type:=\n   natp { nat_p:> nat;\n      is_pos: 0 < nat_p}.\n\n\n  Inductive sump_Join: natPlus -> natPlus -> natPlus -> Prop:=\n  |sump_j (x y z:natPlus): x + y = z -> sump_Join x y z.\n\n  Definition lep (n m:natPlus):= n <= m.\n\n  Lemma lep_preorder: RelationClasses.PreOrder lep.\n  Proof.\n    constructor;\n    hnf; intros;\n    try apply Nat.le_preorder.\n    destruct x, y, z;\n    unfold lep in *; simpl in *;\n    lia.\n  Qed.\n\n  Definition natPlus_R: Relation natPlus:= lep.\n\n  Definition po_natPlus_R: PreOrder (@Krelation _ natPlus_R) :=\n    lep_preorder.\n\nDefinition sumpAlg: @SeparationAlgebra _ sump_Join.\nProof. constructor; intros.\n       - inversion H; subst.\n         rewrite Nat.add_comm in H0;\n           constructor; auto.\n       - inversion H; inversion H0; subst.\n         exists (natp (my+mz)\n                          ltac:(destruct my, mz; simpl in *; lia))\n         ; split; try constructor; simpl;\n         lia.\nQed.\n\n(* it is NOT upwards-closed*)\nInstance sumpAlg_uSA:\n  @UpwardsClosedSeparationAlgebra _ natPlus_R sump_Join.\nProof.\n  hnf; intros.\n  simpl in H0.\n  inversion H;  subst.\nAbort.\n \n(* downwards-closed*)\nInstance sumpAlg_dSA:\n  @DownwardsClosedSeparationAlgebra _ natPlus_R sump_Join.\nProof.\n  hnf; intros.\n  simpl in H0, H1.\n  inversion H; subst.\n  unfold lep in *.\n  destruct m1, m2, m, n1, n2; simpl in *.\n  exists (natp (nat_p3 + nat_p4) ltac:(simpl in *; lia));\n    split; simpl; try constructor; try lia.\n  reflexivity.\n  unfold natPlus_R, lep in *; simpl.\n  revert is_pos2 H.\n  rewrite <- H2. unfold Krelation in *. simpl in *. lia.\nQed.\n  \n  (*it is NOT Residual*)\n  Instance sumpAlg_residual:\n    @ResidualSeparationAlgebra _ natPlus_R sump_Join.\n  Proof.\n    constructor; intro.\n    unfold residue.\n  Abort.\n\n\n\n(** *sum Algebra inverted*)\n\nDefinition suminvAlg: @SeparationAlgebra _ sum_Join.\nProof. constructor; intros.\n       - inversion H; subst.\n         rewrite Nat.add_comm;\n         constructor; auto.\n       - inversion H; inversion H0; subst.\n         exists (my+mz)\n         ; split; try constructor; simpl;\n         lia.\nQed.\n\n(* upwards-closed*)\nInstance suminvAlg_uSA:\n  @UpwardsClosedSeparationAlgebra _ nat_leR sum_Join.\nProof.\n  hnf; intros.\n  simpl in H0.\n  inversion H;  subst.\n  destruct (le_ge_dec m1 m2).\n  - exists m1, (n- m1). split; constructor; simpl; hnf in *; try lia.\n  - exists (n-m2), m2. split; constructor; simpl; hnf in *; try lia.\nQed.\n\n(* downwards-closed*)\nInstance suminvAlg_dSA:\n  @DownwardsClosedSeparationAlgebra _ nat_leR sum_Join.\nProof.\n  hnf; intros.\n  simpl in H0, H1.\n  inversion H; subst.\n  exists (n1 + n2); split; simpl; try constructor; hnf in *; try lia.\nQed.\n\n\n  (*Residual*)\n  Instance suminvAlg_increasing:\n    @IncreasingSeparationAlgebra _ nat_leR sum_Join.\n  Proof.\n    constructor; intro.\n    hnf; intros.\n    inversion H; subst.\n    hnf. lia.\n  Qed.\n\n  \n  (*Residual*)\n  Instance suminvAlg_residual:\n    @ResidualSeparationAlgebra _ nat_leR sum_Join.\n  Proof.\n    constructor; intro.\n    exists 0, n; split.\n    constructor; lia.\n    reflexivity.\n  Qed.\n  \n  (* Unital *)\n  Instance suminvAlg_unital:\n    @UnitalSeparationAlgebra _ nat_leR sum_Join.\n  Proof.\n    apply incr_unital_iff_residual.\n    apply suminvAlg_increasing.\n    apply suminvAlg_residual.\n  Qed.\nEnd nat_algs.\n\n\n(***********************************)\n(* ALGEBRAS ON RATIONALS           *)\n(***********************************)\n\nRequire Import Coq.QArith.QArith.\n(*Require Import Coq.Reals.Rdefinitions.*)\n(*Q overloads <= !*)\nRequire Import Ring.\n\n\n(** *Minimum Algebra on Positive rationals*)\n  (*\n  Record QPlus: Type:=\n   qp { q_p:> Q;\n      qis_pos: (0 < q_p)}.\n\n\n  Inductive sumqp_Join: QPlus -> QPlus -> QPlus -> Prop:=\n  |sumqp_j (x y z:QPlus): (x + y) = z -> sumqp_Join x y z.\n\nDefinition leqp (n m:QPlus):= (n <= m).\nLemma leqp_preorder: RelationClasses.PreOrder leqp.\nProof.\n  constructor;\n  hnf; intros.\n  unfold leqp.\n  - apply Qle_refl.\n  - eapply Qle_trans; eauto.\nQed.\n\nDefinition QPlus_kiM: KripkeIntuitionisticModel QPlus:=\n    Build_KripkeIntuitionisticModel _ _ leqp_preorder.\n\nDefinition qpAlg: @SeparationAlgebra _ sumqp_Join.\nProof. constructor; intros.\n       - inversion H; subst.\n         destruct m1, m2, m.\n         simpl in *.\n         rewrite Qplus_comm in H0. ;\n           constructor; auto.\n       - inversion H; inversion H0; subst.\n         assert (HH: 0 < (my+mz)).\n         { destruct my, mz; simpl.\n           replace 0 with (0+0) by reflexivity.\n           apply Qplus_lt_le_compat; auto.\n           apply Qlt_le_weak; auto. }\n           \n         exists (qp (my+mz) HH); split; simpl;\n         constructor; simpl.\n         reflexivity.\n         rewrite <- H5, <-H1.\n         apply Qplus_assoc.\nQed.\n\n(* it is NOT upwards-closed*)\nInstance sumqpAlg_dSA:\n  @UpwardsClosedSeparationAlgebra _ sumqp_Join QPlus_kiM.\nProof.\n  hnf; intros.\n  simpl in H0.\n  unfold leqp in H0.\n  inversion H;  subst.\n  rewrite <- H1 in H0.\n  destruct (Qlt_le_dec (n/(1+1)) m1).\n  assert (HH: 0 < n / (1 + 1)).\n  { apply Qlt_shift_div_l.\n    - rewrite <- (Qplus_0_l 0).\n      apply Qplus_lt_le_compat.\n      unfold Qlt; simpl; lia.\n      unfold Qle; simpl; lia.\n    - rewrite Qmult_0_l.\n      destruct n; auto. }\n  exists (qp (n / (1 + 1)) HH), (qp (n / (1 + 1)) HH); split.\n  - constructor; simpl.\n    \n  simpl.\n  - exists bindings_list\nAbort.\n \n(* downwards-closed*)\nInstance sumpAlg_uSA:\n  @DownwardsClosedSeparationAlgebra _ sump_Join natPlus_kiM.\nProof.\n  hnf; intros.\n  simpl in H0, H1.\n  inversion H; subst.\n  unfold lep in *.\n  destruct m1, m2, m, n1, n2; simpl in *.\n  exists (natp (nat_p3 + nat_p4) ltac:(simpl in *; lia));\n    split; simpl; try constructor; try lia.\n  reflexivity.\n  unfold lep; simpl.\n  rewrite <- H2; lia.\nQed.\n  \n  (*it is NOT Residual*)\n  Instance sumpAlg_residual:\n    @ResidualSeparationAlgebra _ natPlus_kiM sump_Join.\n  Proof.\n    constructor; intro.\n    unfold residue.\n  Abort.\n*)\n\n    \n(***********************************)\n(* Regular HEAPS                   *)\n(***********************************)\n\nSection heaps.\n  Context (addr val: Type).\n\nDefinition Heap: Type := addr -> option val.\n\nInstance Heap_Join: Join Heap :=\n  @fun_Join _ _ (@option_Join _ (trivial_Join)).\n\nInstance Heap_SA: SeparationAlgebra Heap :=\n  @fun_SA _ _ _ (@option_SA _ _ (trivial_SA)).\n\n(** * Discrete heap *)\nInstance discHeap_R: Relation Heap := eq.\nInstance po_discHeap_R: PreOrder Krelation := eq_preorder _.\n\nProgram Instance discHeap_ikiM: IdentityKripkeIntuitionisticModel Heap.\n\n(*Upwards-closed*)\nInstance discHeap_uSA:\n  @UpwardsClosedSeparationAlgebra Heap discHeap_R Heap_Join.\nProof.\n  eapply ikiM_uSA.\nQed.\n\n(*Downwards-closed*)\nInstance discHeap_dSA:\n  @DownwardsClosedSeparationAlgebra Heap discHeap_R Heap_Join.\nProof.\n  eapply ikiM_dSA.\nQed.\n\n(*Empty heap is increasing element*)\nLemma discHeap_empty_increasing:\n  @increasing Heap discHeap_R Heap_Join (fun _ => None).\nProof. hnf; intros.\n       hnf.\n       extensionality x; specialize (H  x).\n       inversion H; reflexivity.\nQed.\n\n(*Unital*)\nInstance discHeap_unital:\n  @UnitalSeparationAlgebra Heap discHeap_R Heap_Join.\nProof.\n  constructor; intros.\n  - exists (fun _ => None); split.\n    + exists n; split.\n      * hnf; intros.\n        unfold join.\n        destruct (n x); constructor.\n      * hnf; intros.\n        reflexivity.\n    + hnf; intros.\n      hnf; extensionality x.\n      specialize (H x).\n      inversion H; reflexivity.\nQed.\n\n(*Residual*)\nInstance discHeap_residual:\n  @ResidualSeparationAlgebra Heap discHeap_R Heap_Join.\nProof. apply unital_is_residual; apply discHeap_unital. Qed.\n  \n\n(** * Monotonic heap*)\n\nInstance monHeap_R: Relation Heap :=\n  @pointwise_relation _ _ (@option01_relation _ eq).\n\nInstance po_monHeap_R: PreOrder Krelation :=\n  @pointwise_preorder _ _ _ (@option01_preorder _ _ (eq_preorder _)).\n\n(* Upwards-closed*)\nInstance monHeap_uSA:\n  @UpwardsClosedSeparationAlgebra Heap monHeap_R Heap_Join.\nProof.\n  apply fun_uSA.\n  apply option_ord_uSA.\n  apply (@ikiM_uSA val eq (eq_preorder _) (eq_ikiM)).\nQed.\n\n(*Downwards-closed*)\nDefinition monHeap_dSA:\n  @DownwardsClosedSeparationAlgebra Heap monHeap_R Heap_Join.\nProof.\n  eapply fun_dSA.\n  eapply option_ord_dSA.\n  - apply eq_preorder.\n  - apply trivial_SA.\n  - apply (@ikiM_dSA val eq (eq_preorder _) (eq_ikiM)).\n  - apply trivial_incrSA.\nQed.\n\n(* Increasing *)\nInstance monHeap_increasing:\n  @IncreasingSeparationAlgebra Heap monHeap_R Heap_Join.\nProof.\n  constructor; intros.\n  hnf; intros.\n  hnf; intros.\n  specialize (H a).\n  inversion H; constructor.\n  - reflexivity.\n  - inversion H3. (*subst; reflexivity.*)\nQed.\n\n(* Residual *)\nInstance monHeap_residual:\n  @ResidualSeparationAlgebra Heap monHeap_R Heap_Join.\nProof.\n  constructor; intros.\n  exists (fun _ => None).\n  hnf; intros.\n  exists n; split.\n  - hnf; intros x; destruct (n x); constructor.\n  - reflexivity.\nQed.\n\n(* Unital *)\nInstance monHeap_unital:\n  @UnitalSeparationAlgebra Heap monHeap_R Heap_Join.\nProof.\n  apply incr_unital_iff_residual.\n  apply monHeap_increasing.\n  apply monHeap_residual.\nQed.\n\nEnd heaps.\n\n(***********************************)\n(* The other nondisjoint HEAPS     *)\n(***********************************)\n\nSection heaps'.\n  Context (addr val: Type).\n\nDefinition Heap': Type := addr -> option val.\n\nInstance Heap_Join': Join Heap' :=\n  @fun_Join _ _ (@option_Join _ (equiv_Join)).\n\nInstance Heap_SA': SeparationAlgebra Heap' :=\n  @fun_SA _ _ _ (@option_SA _ _ (equiv_SA)).\n\n(** * Discrete heap *)\nInstance discHeap_R': Relation Heap' :=\n  eq.\n\nInstance po_discHeap_R': PreOrder Krelation :=\n  eq_preorder _.\n\nProgram Instance discHeap_ikiM': IdentityKripkeIntuitionisticModel Heap'.\n\n(*Upwards-closed*)\nInstance discHeap_uSA':\n  @UpwardsClosedSeparationAlgebra Heap' discHeap_R' Heap_Join'.\nProof.\n  eapply ikiM_uSA.\nQed.\n\n(*Downwards-closed*)\nInstance discHeap_dSA':\n  @DownwardsClosedSeparationAlgebra Heap' discHeap_R' Heap_Join'.\nProof.\n  eapply ikiM_dSA.\nQed.\n\n(*Empty heap is increasing element*)\nLemma discHeap_empty_increasing':\n  @increasing Heap' discHeap_R' Heap_Join' (fun _ => None).\nProof. hnf; intros.\n       hnf.\n       extensionality x; specialize (H  x).\n       inversion H; reflexivity.\nQed.\n\n(*Unital*)\nInstance discHeap_unital':\n  @UnitalSeparationAlgebra Heap' discHeap_R' Heap_Join'.\nProof.\n  constructor; intros.\n  - exists (fun _ => None); split.\n    + exists n; split.\n      * hnf; intros.\n        unfold join.\n        destruct (n x); constructor.\n      * hnf; intros.\n        reflexivity.\n    + hnf; intros.\n      hnf; extensionality x.\n      specialize (H x).\n      inversion H; reflexivity.\nQed.\n\n(*Residual*)\nInstance discHeap_residual':\n  @ResidualSeparationAlgebra Heap' discHeap_R' Heap_Join'.\nProof. apply unital_is_residual; apply discHeap_unital'. Qed.\n\n(** * Monotonic heap*)\nInstance monHeap_R': Relation Heap' :=\n  @pointwise_relation _ _ (@option01_relation _ eq).\n\nInstance po_monHeap_R': PreOrder Krelation :=\n  @pointwise_preorder _ _ _ (@option01_preorder _ _ (eq_preorder _)).\n\n(* Upwards-closed*)\nInstance monHeap_uSA':\n  @UpwardsClosedSeparationAlgebra Heap' monHeap_R' Heap_Join'.\nProof.\n  eapply fun_uSA.\n  eapply option_ord_uSA.\n  apply (@ikiM_uSA val eq (eq_preorder _) (eq_ikiM)).\nQed.\n\n(*Downwards-closed*)\nDefinition monHeap_dSA':\n  @DownwardsClosedSeparationAlgebra Heap' monHeap_R' Heap_Join'.\nProof.\n  eapply fun_dSA.\n  eapply option_ord_dSA.\n  - apply eq_preorder.\n  - apply equiv_SA.\n  - apply (@ikiM_dSA val eq (eq_preorder _) (eq_ikiM)).\n  - apply equiv_incrSA.\nQed.\n\n(* Increasing *)\nInstance monHeap_increasing':\n  @IncreasingSeparationAlgebra Heap' monHeap_R' Heap_Join'.\nProof.\n  constructor; intros.\n  hnf; intros.\n  hnf; intros.\n  specialize (H a).\n  inversion H; constructor.\n  - reflexivity.\n  - inversion H3. subst; reflexivity.\nQed.\n\n(* Residual *)\nInstance monHeap_residual':\n  @ResidualSeparationAlgebra Heap' monHeap_R' Heap_Join'.\nProof.\n  constructor; intros.\n  exists (fun _ => None).\n  hnf; intros.\n  exists n; split.\n  - hnf; intros x; destruct (n x); constructor.\n  - reflexivity.\nQed.\n\n(* Unital *)\nInstance monHeap_unital':\n  @UnitalSeparationAlgebra Heap' monHeap_R' Heap_Join'.\nProof.\n  apply incr_unital_iff_residual.\n  apply monHeap_increasing'.\n  apply monHeap_residual'.\nQed.\n  \nEnd heaps'.\n\n\n\n(***********************************)\n(* TYPED HEAPS                     *)\n(***********************************)\n\nSection typed_heaps.\n\n  Inductive htype:=\n  |char\n  |short1\n  |short2.\n\n  Inductive ht_ord: htype -> htype -> Prop :=\n    |htype_refl x: ht_ord x x\n    |htype_sht1 : ht_ord char short1\n    |htype_sht2 : ht_ord char short2.\n\n  Instance ht_preorder: PreOrder ht_ord.\n  Proof.\n    constructor;\n    hnf; intros.\n    - constructor.\n    - inversion H; inversion H0; subst; subst; try solve [constructor].\n  Qed.\n\n  Notation THeap':= (nat -> option htype).\n  Definition THvalid (TH:THeap'):=\n     forall n, TH n = Some short1 <->\n                   TH (S n) = Some short2.\n  Record THeap: Type :=\n    { theap:> nat -> option htype;\n      th_wf1: THvalid theap}.\n  \n  Instance THeap_Join': Join THeap' :=\n    @fun_Join _ _ (@option_Join _ (trivial_Join)).\n  \n  Inductive THeap_Join: Join THeap :=\n  | th_join (h1 h2 h3: THeap): THeap_Join' h1 h2 h3 ->\n                               THeap_Join h1 h2 h3.\n\nInstance THeap_SA': @SeparationAlgebra _ THeap_Join':=\n  @fun_SA _ _ _ (@option_SA _ _ (trivial_SA)).\n\nLemma THeap_Join_valid:\n  forall {h1 h2 h3}, THeap_Join' h1 h2 h3 ->\n              THvalid h1 ->\n              THvalid h2 ->\n              THvalid h3.\nProof.\n  intros; intros n; assert (H' :=  H).\n  specialize (H n); specialize (H' (S n));\n  specialize (H0 n); specialize (H1 n);\n  destruct H0 as [H0 H0']; destruct H1 as [H1 H1'].\n  split; intros HH.\n  - rewrite HH in H.\n    inversion H; subst.\n    + symmetry in H4;\n      rewrite (H1 H4) in H'.\n      inversion H'; try reflexivity; subst.\n      inversion H7; subst; reflexivity.\n    + symmetry in H3;\n      rewrite (H0 H3) in H'.\n      inversion H'; try reflexivity; subst.\n      inversion H7; subst; reflexivity.\n    + inversion H5; subst.\n  - rewrite HH in H'.\n    inversion H'; subst.\n    + symmetry in H4;\n      rewrite (H1' H4) in H.\n      inversion H; try reflexivity; subst.\n      inversion H7; subst; reflexivity.\n    + symmetry in H3;\n      rewrite (H0' H3) in H.\n      inversion H; try reflexivity; subst.\n      inversion H7; subst; reflexivity.\n    + inversion H5; subst.\nQed.\n    \nInstance THeap_SA: @SeparationAlgebra THeap THeap_Join.\nProof.\n  constructor; intros.\n  - inversion H; subst.\n    constructor. apply join_comm; auto.\n  - inversion H; inversion H0; subst.\n    pose ( join_assoc _ _  _ _ _ H1 H5) as HH.\n    destruct HH as [myz' [HH1 HH2]].\n    assert (forall n, myz' n = Some short1 <->\n                 myz' (S n) = Some short2).\n    { eapply (THeap_Join_valid HH1).\n      apply my.\n      apply mz. }\n    exists (Build_THeap myz' H2); split; constructor; auto.\nQed.\n\nInductive THeap_order': THeap' -> THeap' -> Prop:=\n| THeap_ord (h1 h2:THeap'):\n    (forall (n:nat) (c:htype), h2 n = Some c ->\n           exists (c':htype), h1 n = Some c' /\\\n                         ht_ord c' c) ->\nTHeap_order' h2 h1.\n\nDefinition THeap_order (h1 h2: THeap): Prop:=\n  THeap_order' h1 h2.\n\nInstance THeap_preorder': PreOrder THeap_order'.\nconstructor.\n- hnf; intros.\n  constructor; intros.\n  exists c; split; auto; constructor.\n- hnf; intros.\n  inversion H;\n    inversion H0; subst.\n  constructor; intros.\n  apply H1 in H2; destruct H2 as [c0 [HH1 HH2]].\n  apply H4 in HH1; destruct HH1 as [c' [HH3 HH4]].\n  exists c'; split; auto.\n  transitivity c0; auto.\nQed.\n\nLemma THeap_preorder: PreOrder THeap_order.\nconstructor.\n- hnf; intros.\n  hnf; reflexivity.\n- hnf; intros.\n  hnf in H, H0.\n  hnf; transitivity y; auto.\nQed.\n\nInstance THeap_R': Relation THeap' := THeap_order'.\n\nInstance po_THeap_R': PreOrder (@Krelation _ THeap_R').\nProof.\n  eapply THeap_preorder'.\nDefined.\n\nInstance THeap_R: Relation THeap := THeap_order.\n\nInstance po_THeap_R: PreOrder (@Krelation _ THeap_R).\nProof.\n  eapply THeap_preorder.\nDefined.\n\n(*It is NOT up-closed*)\nInstance THeap_uSA:\n  @UpwardsClosedSeparationAlgebra THeap THeap_R THeap_Join.\nProof.\n  hnf; intros.\n  hnf in H0.\n  exists m1.\n  pose (m2':= (fun n => match m1 n with\n                       Some _ => None\n                     | _ => m n\n                     end)).\n  assert (THvalid m2').\nAbort.\n\n(* downwards-closed*)\nInstance THeap_dSA':\n  @DownwardsClosedSeparationAlgebra _ THeap_R' THeap_Join'.\nProof.\n  hnf; intros.\n  inversion H0; inversion H1; subst.\n  exists (fun n => match n1 n with\n           |Some x => Some x\n           |_ => n2 n\n           end); split.\n  - hnf; intros.\n    destruct (n1 x) eqn:AA.\n    + destruct (n2 x) eqn:BB.\n      * specialize (H2 x); specialize (H5 x).\n        apply H2 in AA; destruct AA as [x' [AA1 AA2]].\n        apply H5 in BB; destruct BB as [x'' [BB1 BB2]].\n        specialize (H x).\n        rewrite AA1, BB1 in H.\n        inversion H; subst. inversion H7.\n      * constructor.\n    + destruct (n2 x); constructor.\n  - constructor; intros.\n    destruct (n1 n) eqn:n1n.\n    + apply H2 in n1n; destruct n1n as [c' [HH1 HH2]].\n      exists c';split.\n      * specialize (H n).\n        rewrite HH1 in H.\n        inversion H; subst; try reflexivity.\n        inversion H8.\n      * inversion H3; subst; auto.\n    + apply H5 in H3; destruct H3 as [c' [HH1 HH2]].\n      exists c';split.\n      * specialize (H n).\n        rewrite HH1 in H.\n        inversion H; subst; try reflexivity.\n        inversion H7.\n      * auto.\nQed.\n  \nInstance THeap_dSA:\n  @DownwardsClosedSeparationAlgebra THeap THeap_R THeap_Join.\nProof.\n  hnf; intros.\n  hnf in H0, H1.\n  inversion H; subst.\n  destruct (THeap_dSA' _ _ _ _ _ H2 H0 H1) as [n [HH1 HH2]].\n  assert (HH: THvalid n).\n  { apply (THeap_Join_valid HH1);\n    first [apply n1 | apply n2]. }\n  exists (Build_THeap n HH); split; auto;\n  constructor; auto.\nQed.\n\n(* Increasing *)\nInstance THeap_increasingSA':\n  @IncreasingSeparationAlgebra _ THeap_R' THeap_Join'.\nProof.\n  constructor; intros.\n  hnf; intros.\n  constructor; intros.\n  specialize (H n0).\n  rewrite H0 in H; inversion H; subst.\n  - exists c; split; auto; reflexivity.\n  - inversion H4.\nQed.\n\nInstance THeap_increasingSA:\n  @IncreasingSeparationAlgebra _ THeap_R THeap_Join.\nProof.\n  constructor; intros.\n  hnf; intros.\n  simpl in *.\n  eapply THeap_increasingSA'; auto.\n  hnf in H; hnf ; intros.\n  inversion H; subst; auto.\nQed.\n\n(*Residual*)\nInstance THeap_residualSA':\n  @ResidualSeparationAlgebra _ THeap_R' THeap_Join'.\nProof.\n  constructor; intros.\n  exists (fun _ => None).\n  hnf; intros.\n  exists n; split; try reflexivity.\n  hnf; intros.\n  destruct (n x); constructor.\nQed.\n\nInstance THeap_residualSA:\n  @ResidualSeparationAlgebra _ THeap_R THeap_Join.\nProof.\n  constructor; intros.\n  assert (THvalid (fun _ => None)).\n  { constructor; intros HH; inversion HH. }\n  exists (Build_THeap _ H).\n  exists n; split; try reflexivity.\n  constructor.\n  hnf; intros. destruct (n x); constructor.\nQed.\n\n(*Unital*)\nInstance THeap_UnitalSA':\n  @UnitalSeparationAlgebra _ THeap_R' THeap_Join'.\nProof.\n  apply incr_unital_iff_residual.\n  apply THeap_increasingSA'.\n  apply THeap_residualSA'.\nQed.\n\nInstance THeap_UnitalSA:\n  @UnitalSeparationAlgebra _ THeap_R THeap_Join.\nProof.\n  apply incr_unital_iff_residual.\n  apply THeap_increasingSA.\n  apply THeap_residualSA.\nQed.\n\nEnd typed_heaps.\n\n(***********************************)\n(* Step-Index                      *)\n(***********************************)\n\nSection step_index.\n\n  Definition StepIndex_R (worlds: Type) {R: Relation worlds}:\n    Relation (nat * worlds) :=\n    @RelProd _ _ nat_geR R.\n\n  Definition po_StepIndex_R (worlds: Type) {R: Relation worlds} {po_R: PreOrder (@Krelation _ R)}:\n    PreOrder (@Krelation _ (StepIndex_R worlds)):=\n    @RelProd_Preorder _ _ _ _ po_nat_geR po_R.\n\n  Definition StepIndex_Join (worlds: Type) {J: Join worlds}: Join (nat * worlds) :=\n    @prod_Join _ _ equiv_Join J.\n\n  Definition StepIndex_SA\n             (worlds: Type)\n             {J: Join worlds}\n             {SA: SeparationAlgebra worlds}:\n    @SeparationAlgebra (nat * worlds)\n                       (StepIndex_Join worlds) := @prod_SA _ _ _ _ equiv_SA SA.\n\n  Definition StepIndex_uSA (worlds: Type) {R: Relation worlds}\n             {J: Join worlds} {uSA: UpwardsClosedSeparationAlgebra worlds}:\n    @UpwardsClosedSeparationAlgebra (nat * worlds) (StepIndex_R worlds) (StepIndex_Join worlds) :=\n    @prod_uSA _ _ _ _  _ _ (@identity_uSA _ nat_geR) uSA.\n\n  Definition StepIndex_Increasing\n             (worlds: Type) {R: Relation worlds}\n             {J: Join worlds} {incrSA: IncreasingSeparationAlgebra worlds}:\n    @IncreasingSeparationAlgebra (nat * worlds)\n                                  (StepIndex_R worlds)\n                                  (StepIndex_Join worlds) :=\n    @prod_incrSA _ _ _ _ _ _ IndexAlg_increasing incrSA.\n\n  Definition StepIndex_Unital\n             (worlds: Type) {R: Relation worlds}\n             {J: Join worlds} {USA: UnitalSeparationAlgebra worlds}:\n    @UnitalSeparationAlgebra (nat * worlds)\n                                  (StepIndex_R worlds)\n                                  (StepIndex_Join worlds) :=\n    @prod_unitalSA _ _ _  _ _ _ IndexAlg_unital USA.\n\n  Definition StepIndex_Residual\n             (worlds: Type) {R: Relation worlds}\n             {J: Join worlds} {rSA: ResidualSeparationAlgebra worlds}:\n    @ResidualSeparationAlgebra (nat * worlds)\n                                  (StepIndex_R worlds)\n                                  (StepIndex_Join worlds) :=\n    @prod_residualSA _ _ _  _ _ _ IndexAlg_residual rSA.\n\n  (** *step-indexed HEAPS*)\n  Context (addr val: Type).\n  Notation heap:= (Heap addr val).\n\n  Instance heap_jn: Join heap:= (Heap_Join addr val).\n\n  Instance SIheap_Join: Join (nat * heap) := StepIndex_Join heap.\n\n  (** *Monotonic, step-indexed heap *)\n  Definition monSIheap_R := @StepIndex_R heap (monHeap_R addr val).\n\n  Definition po_monSIheap_R := @po_StepIndex_R heap _ (po_monHeap_R addr val).\n\n  (*Upwards-closed *)\n  Instance monSIheap_uSA:\n    @UpwardsClosedSeparationAlgebra _ monSIheap_R SIheap_Join.\n  Proof.\n    eapply StepIndex_uSA.\n    apply monHeap_uSA.\n  Qed.\n\n  (* NOT Downwards-closed *)\n\n  (* Increasing *)\n  Instance monSIheap_increasing:\n    @IncreasingSeparationAlgebra _ monSIheap_R SIheap_Join.\n  Proof.\n    eapply StepIndex_Increasing.\n    apply monHeap_increasing.\n  Qed.\n\n  (*Unital *)\n  Instance monSIheap_unital:\n    @UnitalSeparationAlgebra _ monSIheap_R SIheap_Join.\n  Proof.\n    eapply StepIndex_Unital.\n    apply monHeap_unital.\n  Qed.\n\n  (*Residual *)\n  Instance monSIheap_residual:\n    @ResidualSeparationAlgebra _ monSIheap_R SIheap_Join.\n  Proof.\n    eapply StepIndex_Residual.\n    apply monHeap_residual.\n  Qed.\n\n  (** *Discrete, step-indexed heap *)\n  Definition discSIheap_R:= @StepIndex_R heap (discHeap_R addr val).\n  Definition po_discSIheap_R:= @po_StepIndex_R heap _ (po_discHeap_R addr val).\n\n  (*Upwards-closed *)\n  Instance discSIheap_uSA:\n    @UpwardsClosedSeparationAlgebra _ discSIheap_R SIheap_Join.\n  Proof.\n    eapply StepIndex_uSA.\n    apply discHeap_uSA.\n  Qed.\n\n  (* NOT Downwards-closed *)\n\n  (* NOT Decreasing *)\n\n  (*Unital *)\n  Instance discSIheap_unital:\n    @UnitalSeparationAlgebra _ discSIheap_R SIheap_Join.\n  Proof.\n    eapply StepIndex_Unital.\n    apply discHeap_unital.\n  Qed.\n\n  (*Residual *)\n  Instance discSIheap_residual:\n    @ResidualSeparationAlgebra _ discSIheap_R SIheap_Join.\n  Proof.\n    eapply StepIndex_Residual.\n    apply discHeap_residual.\n  Qed.\n\nEnd step_index.\n\n(***********************************)\n(* ALGEBRAS ON NATURALS            *)\n(***********************************)\n\nSection Prop_alg.\n\nInstance Prop_Join: Join Prop := fun P Q R => (P \\/ Q <-> R) /\\ (P -> Q -> False).\n  \nInstance discProp_R: Relation Prop := fun P Q => P <-> Q.\n\nInstance Prop_SA: SeparationAlgebra Prop.\nProof.\n  constructor.\n  + intros.\n    hnf in *; tauto.\n  + intros.\n    exists (my \\/ mz).\n    split; hnf in *; tauto.\nQed.\n\nInstance po_discProp_R: PreOrder Krelation.\nProof.\n  constructor; constructor;\n  hnf in *; tauto.\nQed.\n\nInstance discProp_ikiM: IdentityKripkeIntuitionisticModel Prop.\nProof.\n  constructor.\n  intros.\n  apply prop_ext; auto.\nQed.\n\nInstance discProp_uSA:\n  @UpwardsClosedSeparationAlgebra Prop discProp_R Prop_Join.\nProof.\n  eapply ikiM_uSA.\nQed.\n  \nInstance discProp_dSA:\n  @DownwardsClosedSeparationAlgebra Prop discProp_R Prop_Join.\nProof.\n  eapply ikiM_dSA.\nQed.\n\nInstance discProp_unitSA:\n  @UnitalSeparationAlgebra Prop discProp_R Prop_Join.\nProof.\n  constructor.\n  intros.\n  exists False.\n  split.\n  + hnf.\n    exists n; split; hnf; tauto.\n  + hnf.\n    intros.\n    hnf in *; tauto.\nQed.\n\nEnd Prop_alg.\n\nSection pred_alg.\n\nContext (A : Type).\n\nDefinition Pred: Type := A -> Prop.\n\nInstance Pred_Join: Join Pred :=\n  @fun_Join _ _ Prop_Join.\n\nInstance Pred_SA: SeparationAlgebra Pred :=\n  @fun_SA _ _ _ Prop_SA.\n\nInstance discPred_R: Relation Pred := pointwise_relation _ discProp_R.\nInstance po_discPred_R: PreOrder Krelation := pointwise_preorder _ _ po_discProp_R.\n\nInstance discPred_uSA: @UpwardsClosedSeparationAlgebra Pred discPred_R Pred_Join :=\n  fun_uSA _ _ discProp_uSA.\n\nInstance discPred_dSA: @DownwardsClosedSeparationAlgebra Pred discPred_R Pred_Join :=\n  fun_dSA _ _ discProp_dSA.\n\nInstance discPred_unital: @UnitalSeparationAlgebra Pred discPred_R Pred_Join :=\n  fun_unitSA _ _ discProp_unitSA.\n\nEnd pred_alg.\n\n(***********************************)\n(* Resource Bounds                 *)\n(***********************************)\n\n\n\n(*\n(** * Discrete heap *)\nInstance discHeap_kiM: KripkeIntuitionisticModel Heap :=\n  identity_kiM.\n\nProgram Instance discHeap_ikiM: IdentityKripkeIntuitionisticModel Heap.\n\n(*Upwards-closed*)\nInstance discHeap_dSA:\n  @UpwardsClosedSeparationAlgebra Heap Heap_Join discHeap_kiM.\nProof.\n  eapply ikiM_dSA.\nQed.\n\n(*Downwards-closed*)\nInstance discHeap_uSA:\n  @DownwardsClosedSeparationAlgebra Heap Heap_Join discHeap_kiM.\nProof.\n  eapply ikiM_uSA.\nQed.\n\n(*Empty heap is decreasing element*)\nLemma discHeap_empty_decreasing:\n  @nonpositive Heap discHeap_kiM Heap_Join (fun _ => None).\nProof. hnf; intros.\n       hnf.\n       extensionality x; specialize (H  x).\n       inversion H; reflexivity.\nQed.\n\n(*Unital*)\nInstance discHeap_unital:\n  @UnitalSeparationAlgebra Heap discHeap_kiM Heap_Join.\nProof.\n  constructor; intros.\n  - exists (fun _ => None); split.\n    + exists n; split.\n      * hnf; intros.\n        unfold join.\n        destruct (n x); constructor.\n      * hnf; intros.\n        reflexivity.\n    + hnf; intros.\n      hnf; extensionality x.\n      specialize (H x).\n      inversion H; reflexivity.\n  - hnf; intros.\n    inversion H; subst.\n    apply H0 in H1.\n    inversion H1.\n    reflexivity.\nQed.\n\n\n\n\n\n\n\n\n\nClass SeparationAlgebra_unit (worlds: Type) {J: Join worlds} := {\n  unit: worlds;\n  unit_join: forall n, join n unit n;\n  unit_spec: forall n m, join n unit m -> n = m\n}.\n\n(***********************************)\n(* More examples                   *)\n(***********************************)\n(*\nProgram Definition nat_le_kiM: KripkeIntuitionisticModel nat := \n  Build_KripkeIntuitionisticModel nat (fun a b => a <= b) _.\nNext Obligation.\n  constructor; hnf; intros.\n  + apply le_n.\n  + eapply NPeano.Nat.le_trans; eauto.\nQed.\n\n(* TODO: Probably don't need this one. *)\nProgram Definition SAu_kiM (worlds: Type) {J: Join worlds} {SA: SeparationAlgebra worlds} {SAu: SeparationAlgebra_unit worlds} : KripkeIntuitionisticModel worlds :=\n  Build_KripkeIntuitionisticModel worlds (fun a b => exists b', join b b' a) _.\nNext Obligation.\n  constructor; hnf; intros.\n  + exists unit; apply unit_join.\n  + destruct H as [? ?], H0 as [? ?].\n    destruct (join_assoc _ _ _ _ _ H0 H) as [? [? ?]].\n    exists x2; auto.\nQed.\n\nDefinition Stack (LV val: Type): Type := LV -> val.\n\nDefinition StepIndex_kiM (worlds: Type) {kiM: KripkeIntuitionisticModel worlds}: KripkeIntuitionisticModel (nat * worlds) := @prod_kiM _ _ nat_le_kiM kiM.\n\nDefinition StepIndex_Join (worlds: Type) {J: Join worlds}: Join (nat * worlds) :=\n  @prod_Join _ _ (equiv_Join _) J.\n\nDefinition StepIndex_SA (worlds: Type) {J: Join worlds} {SA: SeparationAlgebra worlds}:\n  @SeparationAlgebra (nat * worlds) (StepIndex_Join worlds) := @prod_SA _ _ _ _ (equiv_SA _) SA.\n\nDefinition StepIndex_dSA (worlds: Type) {kiM: KripkeIntuitionisticModel worlds}\n           {J: Join worlds} {dSA: UpwardsClosedSeparationAlgebra worlds}:\n  @UpwardsClosedSeparationAlgebra (nat * worlds) (StepIndex_Join worlds) (StepIndex_kiM worlds):= @prod_dSA _ _ _ _ _ _ (@identity_dSA _ nat_le_kiM) dSA.\n\n*)*)\n", "meta": {"author": "QinxiangCao", "repo": "LOGIC", "sha": "d1476d57345c87447ea500b3d5ea99ee6d0f6863", "save_path": "github-repos/coq/QinxiangCao-LOGIC", "path": "github-repos/coq/QinxiangCao-LOGIC/LOGIC-d1476d57345c87447ea500b3d5ea99ee6d0f6863/SeparationLogic/Model/OSAExamples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995028, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6697640464663046}}
{"text": "Require Import Classical.\n\nParameter S: Set.\nParameter c d: S.\n\n(*Praedikate*)\nParameter D P Q: S -> Prop.\nParameter L: S -> S -> Prop.\n\nAxiom A1: forall x, D x -> exists y, P y /\\ L y x.\nAxiom A2: forall x, P x -> forall y, Q y -> ~L x y.\n\nTheorem T: forall x, D x -> ~Q x.\nProof.\n  intro c.\n  intro.\n  intro.\n\n  pose proof A1 as A1.\n  pose proof A2 as A2.\n\n  assert (exists y, P y /\\ L y c).\n  apply A1.\n  assumption.\n\n  destruct H1 as [d H1].\n  destruct H1 as [H1 H2].\n\n  assert (~L d c).\n  apply A2.\n  assumption.\n  assumption.\n  \n  contradiction.\nQed.", "meta": {"author": "Erdragh", "repo": "coq", "sha": "538cabcaf98e877226a2264524ef3e11568e6871", "save_path": "github-repos/coq/Erdragh-coq", "path": "github-repos/coq/Erdragh-coq/coq-538cabcaf98e877226a2264524ef3e11568e6871/uebung10/exercise1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6697640401010523}}
{"text": "Require Import XR_Rsqr.\nRequire Import XR_Rsqr_neg.\nRequire Import XR_Rsqr_plus.\nRequire Import XR_R2.\nRequire Import XR_Rminus.\nRequire Import XR_Ropp_mult_distr_r.\n\nLocal Open Scope R_scope.\n\nLemma Rsqr_minus : forall x y:R, Rsqr (x - y) = Rsqr x + Rsqr y - R2 * x * y.\nProof.\n  intros x y.\n  unfold Rminus.\n  rewrite Rsqr_plus.\n  rewrite <- Rsqr_neg.\n  rewrite <- Ropp_mult_distr_r.\n  reflexivity.\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_minus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6697640393228239}}
{"text": "Require Export SpecSyntax.\nRequire Export BoilerplateFunctions.\nSet Implicit Arguments.\n\n(*************************************************************************)\n(* Reduction relation                                                    *)\n(*************************************************************************)\n\nFixpoint Value (t : Tm) : Prop :=\n  match t with\n    | tt       => True\n    | abs _ _  => True\n    | prod x y => Value x ∧ Value y\n    | _        => False\n  end.\n\nInductive Match : Pat → Tm → Tm → Tm → Prop :=\n  | M_Var {T v t} :\n      Match (pvar T) v t (substTm 0 v t)\n  | M_Prod {p1 p2 v1 v2 t t' t''} :\n      Match p2 (weakenTm v2 (bindPat p1)) t t' →\n      Match p1 v1 t' t'' →\n      Match (pprod p1 p2) (prod v1 v2) t t''.\n\nInductive red : Tm → Tm → Prop :=\n  | appabs {T11 t12 t2} :\n      Value t2 → red (app (abs T11 t12) t2) (substTm 0 t2 t12)\n  | appfun {t1 t1' t2} :\n      red t1 t1' → red (app t1 t2) (app t1' t2)\n  | apparg {t1 t2 t2'} :\n      Value t1 → red t2 t2' → red (app t1 t2) (app t1 t2')\n  | prodl {t1 t1' t2} :\n      red t1 t1' → red (prod t1 t2) (prod t1' t2)\n  | prodr {t1 t2 t2'} :\n      Value t1 → red t2 t2' → red (prod t1 t2) (prod t1 t2')\n  | lettp {p t1 t1' t2} :\n      red t1 t1' → red (lett p t1 t2) (lett p t1' t2)\n  | lettv {p t1 t3 t2} :\n      Value t1 → Match p t1 t2 t3 → red (lett p t1 t2) t3.\n\n(******************************************************************************)\n(* Typing relation.                                                           *)\n(******************************************************************************)\n\nInductive PTyping (Γ: Env) : Pat → Ty → Ext → Prop :=\n  | P_Var {T} :\n      PTyping Γ (pvar T) T (exvar exempty T)\n  | P_Prod {p1 p2 T1 T2 Δ1 Δ2} :\n      PTyping Γ p1 T1 Δ1 → PTyping (extend Γ Δ1) p2 T2 Δ2 →\n      PTyping Γ (pprod p1 p2) (tprod T1 T2) (append Δ1 Δ2).\n\nInductive Typing (Γ: Env) : Tm → Ty → Prop :=\n  | T_Var {y T} :\n      lookup_evar Γ y T → Typing Γ (var y) T\n  | T_Unit :\n      Typing Γ tt tunit\n  | T_Abs {t T1 T2} :\n      Typing (evar Γ T1) t T2 →\n      Typing Γ (abs T1 t) (tarr T1 T2)\n  | T_App {t1 t2 T11 T12} :\n      Typing Γ t1 (tarr T11 T12) → Typing Γ t2 T11 →\n      Typing Γ (app t1 t2) T12\n  | T_Prod {t1 T1 t2 T2} :\n      Typing Γ t1 T1 → Typing Γ t2 T2 →\n      Typing Γ (prod t1 t2) (tprod T1 T2)\n  | T_Let {p t1 t2 T1 T2 Δ} :\n      Typing Γ t1 T1 → PTyping Γ p T1 Δ →\n      Typing (extend Γ Δ) t2 T2 →\n      Typing Γ (lett p t1 t2) T2.\nArguments T_Unit {Γ}.\n", "meta": {"author": "Blaisorblade", "repo": "knot-esop-2017-case-study", "sha": "cf541cb38a483a514474f4c948bf005bc49b1e6f", "save_path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study", "path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study/knot-esop-2017-case-study-cf541cb38a483a514474f4c948bf005bc49b1e6f/casestudy/manual/stlcprod/SpecSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.754914975839675, "lm_q1q2_score": 0.6697640389337091}}
{"text": "Require Import Rbase MyRIneq.\nRequire Import Rsequence_def Rsequence_facts Rsequence_cv_facts.\n\nRequire Import List.\nRequire Import Option.\nRequire Import Tactics.\n\n(* Reifications of sequences, limits and being the limit of a\n   particular sequence. *)\n\nInductive rseq :=\n  | rseq_cst   : forall (r : R), rseq\n  | rseq_var   : forall (n : nat), rseq\n  | rseq_opp   : forall (r : rseq), rseq\n  | rseq_plus  : forall (rl rr : rseq), rseq\n  | rseq_minus : forall (rl rr : rseq), rseq.\n\nInductive rseq_limit :=\n  | minus_inf : rseq_limit\n  | finite : forall (l : R), rseq_limit\n  | plus_inf : rseq_limit.\n\nDefinition is_limit r l := match l with\n  | minus_inf => Rseq_cv_neg_infty r\n  | finite l => Rseq_cv r l\n  | plus_inf => Rseq_cv_pos_infty r\nend.\n\n(* Two extensionally equal sequences have the same limit. *)\n\nLemma is_limit_ext : forall r s k l,\n  is_limit r k ->\n  r == s -> k = l ->\n  is_limit s l.\nProof.\nintros r s k [] Hrk Hrs Hkl ;\n [ eapply Rseq_cv_neg_infty_eq_compat\n | eapply Rseq_cv_eq_compat ; [symmetry |]\n | eapply Rseq_cv_pos_infty_eq_compat ]\n ; subst ; eassumption.\nQed.\n\nDefinition Rseq_with_limit := {r : Rseq & {l : rseq_limit | is_limit r l}}.\n\nDefinition rseq_limit_opp l := match l with\n  | minus_inf => plus_inf\n  | finite u  => finite (- u)\n  | plus_inf  => minus_inf\nend.\n\nLemma rseq_limit_opp_is_limit : forall r l,\n  is_limit r l ->\n  is_limit (- r) (rseq_limit_opp l).\nProof.\nintros r [] Hl ; simpl ;\n [ apply Rseq_cv_neg_infty_opp_compat\n | apply Rseq_cv_opp_compat\n | apply Rseq_cv_pos_infty_opp_compat] ;\n assumption.\nQed.\n\nDefinition rseq_limit_add ll lr := match ll, lr with\n  | minus_inf, plus_inf  => None\n  | plus_inf , minus_inf => None\n  | minus_inf, _         => Some minus_inf\n  | _        , minus_inf => Some minus_inf\n  | plus_inf , _         => Some plus_inf\n  | _        , plus_inf  => Some plus_inf\n  | finite u , finite v  => Some (finite (u + v))\nend.\n\nFixpoint comp_limit (r : rseq) (env : list Rseq_with_limit) : option rseq_limit :=\nmatch r with\n  | rseq_cst r => Return (finite r)\n  | rseq_var n => Bind (nth_error env n) (fun x => Return (proj1_sig (projT2 x)))\n  | rseq_opp r => Bind (comp_limit r env) (fun l => Some (rseq_limit_opp l))\n  | rseq_plus rl rr => Bind (comp_limit rl env) (fun ll =>\n                       Bind (comp_limit rr env) (fun lr => rseq_limit_add ll lr))\n  | rseq_minus rl rr => Bind (comp_limit rl env) (fun ll =>\n                        Bind (comp_limit rr env) (fun lr => rseq_limit_add ll (rseq_limit_opp lr)))\nend.\n\nFixpoint comp_rseq (r : rseq) (env : list Rseq_with_limit) := match r with\n  | rseq_cst r => Return (Rseq_constant r)\n  | rseq_var n => Bind (nth_error env n) (fun un => Some (projT1 un))\n  | rseq_opp r => Bind (comp_rseq r env) (fun un => Some (Rseq_opp un))\n  | rseq_plus rl rr => Bind (comp_rseq rl env) (fun un =>\n                       Bind (comp_rseq rr env) (fun vn => Some (Rseq_plus un vn)))\n  | rseq_minus rl rr => Bind (comp_rseq rl env) (fun un =>\n                       Bind (comp_rseq rr env) (fun vn => Some (Rseq_minus un vn)))\nend.\n\nLtac fold_is_limit := match goal with\n  | |- Rseq_cv ?r ?l => fold (is_limit r (finite l))\n  | |- Rseq_cv_neg_infty ?r => fold (is_limit r minus_inf)\n  | |- Rseq_cv_pos_infty ?r => fold (is_limit r plus_inf)\nend.\n\nLemma comp_rseq_limit_compat : forall r env un l,\n  comp_rseq r env = Some un ->\n  comp_limit r env = Some l ->\n  is_limit un l.\nProof.\nintros r env ; induction r ; intros un l Hun Hl ; simpl in *.\n inversion Hun ; inversion Hl ; apply Rseq_constant_cv.\n destruct (nth_error env n) as [Hget |].\n  inversion Hun ; inversion Hl ; apply (proj2_sig (projT2 Hget)).\n  inversion Hl.\n destruct (comp_rseq r env) as [vn |] ; [| inversion Hun] ;\n  destruct (comp_limit r env) as [lo |] ; [| inversion Hl] ;\n  inversion Hun ; inversion Hl.\n  apply rseq_limit_opp_is_limit, IHr ; reflexivity.\n destruct (comp_rseq r1 env) as [vn |] ; [| inversion Hun] ;\n  destruct (comp_limit r1 env) as [ll |] ; [| inversion Hl] ;\n  destruct (comp_rseq r2 env) as [wn |] ; [| inversion Hun] ;\n  destruct (comp_limit r2 env) as [lr |] ; [| inversion Hl].\n   destruct ll ; destruct lr ; inversion Hun ; inversion Hl ;\n   subst.\n    apply Rseq_cv_neg_infty_plus_compat ; fold_is_limit ;\n     [apply IHr1 | apply IHr2] ; reflexivity.\n    eapply Rseq_cv_finite_plus_neg_infty_l ; fold_is_limit ;\n     [apply IHr1 | apply IHr2] ; reflexivity.\n    eapply Rseq_cv_finite_plus_neg_infty_r ; fold_is_limit ;\n     [apply IHr1 | apply IHr2] ; reflexivity.\n    eapply Rseq_cv_plus_compat ; fold_is_limit ;\n     [apply IHr1 | apply IHr2] ; reflexivity.\n    eapply Rseq_cv_finite_plus_pos_infty_r ; fold_is_limit ;\n     [apply IHr1 | apply IHr2] ; reflexivity.\n    eapply Rseq_cv_finite_plus_pos_infty_l ; fold_is_limit ;\n     [apply IHr1 | apply IHr2] ; reflexivity.\n    apply Rseq_cv_pos_infty_plus_compat ; fold_is_limit ;\n     [apply IHr1 | apply IHr2] ; reflexivity.\n destruct (comp_rseq r1 env) as [vn |] ; [| inversion Hun] ;\n  destruct (comp_limit r1 env) as [ll |] ; [| inversion Hl] ;\n  destruct (comp_rseq r2 env) as [wn |] ; [| inversion Hun] ;\n  destruct (comp_limit r2 env) as [lr |] ; [| inversion Hl].\n   inversion Hun ; eapply (is_limit_ext (Rseq_plus vn (Rseq_opp wn))) ;\n    [| intro n ; unfold Rseq_plus, Rseq_minus, Rseq_opp ; ring | reflexivity].\n   destruct ll ; destruct lr ; inversion Hl ; subst.\n    apply Rseq_cv_finite_plus_neg_infty_l with (- l0)%R ; fold_is_limit ;\n     [apply IHr1 | fold (rseq_limit_opp (finite l0)) ;\n     apply rseq_limit_opp_is_limit, IHr2] ; reflexivity.\n    apply Rseq_cv_neg_infty_plus_compat ; fold_is_limit ;\n     [apply IHr1 | fold (rseq_limit_opp plus_inf) ;\n     apply rseq_limit_opp_is_limit, IHr2] ; reflexivity.\n    apply Rseq_cv_finite_plus_pos_infty_r with l0 ; fold_is_limit ;\n     [apply IHr1 | fold (rseq_limit_opp minus_inf) ;\n     apply rseq_limit_opp_is_limit, IHr2] ; reflexivity.\n    apply Rseq_cv_plus_compat ; fold_is_limit ;\n     [apply IHr1 | fold (rseq_limit_opp (finite l1)) ;\n     apply rseq_limit_opp_is_limit, IHr2] ; reflexivity.\n    eapply Rseq_cv_finite_plus_neg_infty_r ; fold_is_limit ;\n     [apply IHr1 | fold (rseq_limit_opp plus_inf) ;\n     apply rseq_limit_opp_is_limit, IHr2] ; reflexivity.\n    apply Rseq_cv_pos_infty_plus_compat ; fold_is_limit ;\n     [apply IHr1 | fold (rseq_limit_opp minus_inf) ;\n     apply rseq_limit_opp_is_limit, IHr2] ; reflexivity.\n    apply Rseq_cv_finite_plus_pos_infty_l with (- l0)%R ; fold_is_limit ;\n     [apply IHr1 | fold (rseq_limit_opp (finite l0)) ;\n     apply rseq_limit_opp_is_limit, IHr2] ; reflexivity.\nQed.\n\nDefinition rseq_precondition r env un l :=\nmatch comp_rseq r env with\n  | None    => False\n  | Some vn =>\n  match comp_limit r env with\n    | None => False\n    | Some v => (un == vn) /\\ (l = v)\n  end\nend.\n\nLemma tactic_correctness : forall r env un l,\n   rseq_precondition r env un l ->\n   is_limit un l.\nProof.\nunfold rseq_precondition ; intros r env un l ;\n destruct (comp_rseq r env) eqn:E; symmetry in E;\n destruct (comp_limit r env) eqn:E'; symmetry in E';\n intros [].\n intros ; eapply is_limit_ext ;\n  [ eapply comp_rseq_limit_compat | |] ;\n  symmetry ; eassumption.\nQed.\n\n\n\n(*\n\nSection Test.\n\nLtac add_var v l :=\n  let rec aux v l n := match l with\n    | nil       => constr: (n , v :: nil)\n    | v  :: _   => constr: (n , l)\n    | ?a :: ?tl => match aux v tl (S n) with | (?m , ?tl') => constr: (m , cons a tl') end\n    end in\n  aux v l O.\n\nLtac known_limit An := match goal with\n  | [ H: is_limit An ?a |- _ ] => constr: (Some (An , a , H))\n  | _                          => constr: (None  )\nend.\n\nLtac reify_rseq_aux f l := match f with\n  | Rseq_constant ?v  => constr: (rseq_cst v , l)\n  | Rseq_opp  ?un     =>\n        match reify_rseq_aux un l  with | (?UN , ?l1) => constr: (rseq_opp UN , l1) end\n  | Rseq_plus ?un ?vn =>\n        match reify_rseq_aux un l  with | (?UN , ?l1) =>\n        match reify_rseq_aux vn l1 with | (?VN , ?l2) => constr: (rseq_plus UN VN , l2) end end\n  | Rseq_minus ?un ?vn =>\n        match reify_rseq_aux un l  with | (?UN , ?l1) =>\n        match reify_rseq_aux vn l1 with | (?VN , ?l2) => constr: (rseq_minus UN VN , l2) end end\n  | ?An =>\n        match known_limit An with | None => fail | Some ?a =>\n        match add_var a l with | (?A , ?l1) => constr: (rseq_var A , l1) end end\nend.\n\nCheck tactic_correctness.\n\nLtac reify_rseq := match goal with\n  | |- Rseq_cv ?f ?l =>\n        match reify_rseq_aux f (@nil Rseq_with_limit) with | (?r , ?env) =>\n        change (is_limit f (finite l)) end end.\n\n\nVariable Un Vn : Rseq.\nVariable u  v  : R.\n\nHypothesis Un_cv : Rseq_cv Un u.\nHypothesis Vn_cv : Rseq_cv Vn v.\n\n\nGoal Rseq_cv Un u.\nProof.\nfold (is_limit Un (finite u)) in *.\nfold (is_limit Vn (finite v)) in *.\nreify_rseq.\n  apply (tactic_correctness (rseq_var 0) (Un :: nil) Un (finite u)).\n\n  with (r := r) (env := env) \n eapply tactic_correctness.\n*)\n", "meta": {"author": "coq-community", "repo": "coqtail-math", "sha": "be26e1a6a52f2e13e0779c68aba685ddfb4f0535", "save_path": "github-repos/coq/coq-community-coqtail-math", "path": "github-repos/coq/coq-community-coqtail-math/coqtail-math-be26e1a6a52f2e13e0779c68aba685ddfb4f0535/Reals/Rsequence/Rsequence_tactics_reflection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6697640370713683}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq             *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later            *)\nFrom mathcomp Require Import all_ssreflect ssralg finalg poly polydiv.\nFrom mathcomp Require Import cyclic perm matrix mxpoly vector mxalgebra zmodp.\nFrom mathcomp Require Import finfield falgebra fieldext.\nRequire Import ssr_ext ssralg_ext vandermonde linearcode.\nRequire Import dft poly_decoding grs bch.\n\n(******************************************************************************)\n(*            Work in progress about alternant and Goppa codes                *)\n(******************************************************************************)\n\n(* OUTLINE:\n- Section location_polynomial.\n- Section grs_polynomial.\n- Section injection_into_extension_field.\n- Section alternant_code.\n- Section narrow_sense_BCH_are_Goppa. (wip)\n*)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory.\nLocal Open Scope ring_scope.\n\nLocal Open Scope vec_ext_scope.\n\nSection location_polynomial.\n\nVariables (n : nat) (F : finFieldType) (a : 'rV[F]_n).\n\n(** the values of the location polynomial at points a``_i,\n   they determine uniquely the location polynomial of size n (i.e., deg <= n.-1) *)\nDefinition location_polynomial_points :=\n  \\row_i \\prod_(j < n | j != i) (a ``_ i - a ``_ j).\n\nEnd location_polynomial.\n\n(* NB: the notation GRS_k(kappa, g) in the classification book *)\nSection grs_polynomial.\n\nVariables (n : nat) (F : finFieldType) (a : 'rV[F]_n).\nVariable g : {poly F}.\nLet b := \\row_(i < n) (((location_polynomial_points a) ``_ i)^-1 * g.[a ``_ i]).\nVariable (r : nat).\n\nDefinition GRS_PCM_polynomial := @GRS.PCM _ F a b r.\n\nEnd grs_polynomial.\n\nSection injection_into_extension_field.\n\nVariables (F0 : finFieldType) (F1 : fieldExtType F0).\n\nDefinition ext_inj : {rmorphism F0 -> F1} := @GRing.in_alg_rmorphism F0 F1.\n\nDefinition ext_inj_tmp : {rmorphism F0 -> (FinFieldExtType F1)} := ext_inj.\n\nVariable n : nat.\n\nDefinition ext_inj_rV : 'rV[F0]_n -> 'rV[F1]_n := @map_mx _ _ ext_inj 1 n.\n\nEnd injection_into_extension_field.\n\nSection alternant_code.\n\n(** declare F_q *)\nVariable p u' : nat.\nLet u := u'.+1.\nHypothesis primep : prime p.\n\nLet Fq : finFieldType := GF u primep.\nLet q := p ^ u.\nLet p_char : p \\in [char Fq].\nProof. apply char_GFqm. Qed.\n\n(** declare F_{q^m} *)\nVariable m' : nat.\nLet m := m'.+1.\nVariable Fqm : fieldExtType Fq.\nHypothesis card_Fqm : #| FinFieldExtType Fqm | = q ^ m.\n\n(** build GRS_k(kappa, g) *)\nVariable n : nat.\nVariable a : 'rV[Fqm]_n.\nVariable g : {poly Fqm}.\nVariable k : nat.\n\nDefinition alternant_PCM : 'M_(k, n) := @GRS_PCM_polynomial n (FinFieldExtType Fqm) a g k.\n\nDefinition alternant_code := Rcode.t (@ext_inj_tmp Fq Fqm) (kernel alternant_PCM).\n\n(** Goppa codes are a special case of alternant codes *)\nDefinition goppa_code_condition := size g = (n - k).+1.\n\nEnd alternant_code.\n\nSection narrow_sense_BCH_are_Goppa.\n\n(** declare F_q *)\nVariable p u' : nat.\nLet u := u'.+1.\nHypothesis primep : prime p.\n\nLet Fq : finFieldType := GF u primep.\nLet q := p ^ u.\nLet p_char : p \\in [char Fq].\nProof. apply char_GFqm. Qed.\n\n(** declare F_{q^m} *)\nVariable m' : nat.\nLet m := m'.+1.\nVariable Fqm : fieldExtType Fq.\nHypothesis card_Fqm : #| FinFieldExtType Fqm | = q ^ m.\n\n(** we are talking about narrow-sense Goppa codes *)\nLet n : nat := (q^m).-1.\nVariable e : Fqm.\nHypothesis e_prim : n.-primitive_root e.\nLet a : 'rV[Fqm]_n := rVexp e n.\nVariable t : nat.\n\n(** we have to instantiate Goppa codes with a monomial to recover BCH codes *)\nLet g : {poly (FinFieldExtType Fqm)} := 'X^(n - t).\n\n(** from the Goppa code condition, we have only one choice for its degree *)\nLet goppa_code_condition_check : goppa_code_condition n g t.\nProof. by rewrite /goppa_code_condition size_polyXn. Qed.\n\n(* NB: we only have binary BCH codes, so we should maybe restrict q at\nthis point *)\n\n(** wip *)\nLemma narrow_sense_BCH_are_Goppa :\n  @BCH.PCM (FinFieldExtType _) _ a t =\n  @alternant_PCM _ u' primep Fqm _ a g t(*?*).\nProof.\nrewrite /BCH.code /alternant_code.\nAbort.\n\nEnd narrow_sense_BCH_are_Goppa.\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/ecc_classic/alternant.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.669718817913943}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.euclidean_tactics.\nRequire Import ProofCheckingEuclid.lemma_ABCequalsCBA.\nRequire Import ProofCheckingEuclid.lemma_NCdistinct.\nRequire Import ProofCheckingEuclid.lemma_NCorder.\nRequire Import ProofCheckingEuclid.lemma_betweennotequal.\nRequire Import ProofCheckingEuclid.lemma_collinearorder.\nRequire Import ProofCheckingEuclid.lemma_congruencesymmetric.\nRequire Import ProofCheckingEuclid.lemma_doublereverse.\nRequire Import ProofCheckingEuclid.lemma_equalanglessymmetric.\nRequire Import ProofCheckingEuclid.lemma_equalanglestransitive.\nRequire Import ProofCheckingEuclid.lemma_inequalitysymmetric.\nRequire Import ProofCheckingEuclid.lemma_layoff.\nRequire Import ProofCheckingEuclid.lemma_onray_impliescollinear.\nRequire Import ProofCheckingEuclid.lemma_onray_strict.\nRequire Import ProofCheckingEuclid.lemma_s_conga.\nRequire Import ProofCheckingEuclid.lemma_s_inangle.\nRequire Import ProofCheckingEuclid.lemma_s_ncol_ABD_col_ABC_ncol_ACD.\nRequire Import ProofCheckingEuclid.lemma_s_ncol_n_col.\nRequire Import ProofCheckingEuclid.lemma_s_onray_assert_ABB.\nRequire Import ProofCheckingEuclid.proposition_10.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma proposition_09 :\n\tforall A B C,\n\tnCol B A C ->\n\texists X, CongA B A X X A C /\\ InAngle B A C X.\nProof.\n\tintros A B C.\n\tintros nCol_B_A_C.\n\n\tpose proof (lemma_NCorder _ _ _ nCol_B_A_C) as (nCol_A_B_C & nCol_A_C_B & _ & _ & _).\n\tpose proof (lemma_s_ncol_n_col _ _ _ nCol_A_B_C) as n_Col_A_B_C.\n\tpose proof (lemma_NCdistinct _ _ _ nCol_A_B_C) as (neq_A_B & _ & neq_A_C & _ & _ & _).\n\n\tpose proof (lemma_s_onray_assert_ABB _ _ neq_A_B) as OnRay_AB_B.\n\n\tpose proof (lemma_layoff _ _ _ _ neq_A_C neq_A_B) as (E & OnRay_AC_E & Cong_AE_AB).\n\n\tpose proof (lemma_onray_impliescollinear _ _ _ OnRay_AC_E) as Col_A_C_E.\n\tpose proof (lemma_onray_strict _ _ _ OnRay_AC_E) as neq_A_E.\n\n\tpose proof (lemma_s_ncol_ABD_col_ABC_ncol_ACD _ _ _ _ nCol_A_C_B Col_A_C_E neq_A_E) as nCol_A_E_B.\n\tpose proof (lemma_NCorder _ _ _ nCol_A_E_B) as (_ & _ & _ & _ & nCol_B_E_A).\n\tpose proof (lemma_NCdistinct _ _ _ nCol_A_E_B) as (_ & _ & _ & _ & neq_B_E & _).\n\n\tpose proof (lemma_congruencesymmetric _ _ _ _ Cong_AE_AB) as Cong_AB_AE.\n\n\tpose proof (proposition_10 _ _ neq_B_E) as (F & BetS_B_F_E & Cong_FB_FE).\n\n\tpose proof (cn_congruencereflexive A F) as Cong_AF_AF.\n\n\tpose proof (lemma_betweennotequal _ _ _ BetS_B_F_E) as (_ & neq_B_F & _).\n\n\tassert (Col B F E) as Col_B_F_E by (unfold Col; one_of_disjunct BetS_B_F_E).\n\tpose proof (lemma_collinearorder _ _ _ Col_B_F_E) as (_ & _ & _ & Col_B_E_F & _).\n\n\tpose proof (lemma_s_inangle _ _ _ _ _ _ OnRay_AB_B OnRay_AC_E BetS_B_F_E) as InAngle_BAC_F.\n\n\tpose proof (lemma_s_ncol_ABD_col_ABC_ncol_ACD _ _ _ _ nCol_B_E_A Col_B_E_F neq_B_F) as nCol_B_F_A.\n\tpose proof (lemma_NCorder _ _ _ nCol_B_F_A) as (_ & _ & _ & nCol_B_A_F & _).\n\n\tpose proof (lemma_NCdistinct _ _ _ nCol_B_A_F) as (_ & neq_A_F & _ & _ & _ & _).\n\tpose proof (lemma_s_onray_assert_ABB _ _ neq_A_F) as OnRay_AF_F.\n\n\tpose proof (lemma_doublereverse _ _ _ _ Cong_FB_FE) as (Cong_EF_BF & _).\n\tpose proof (lemma_congruencesymmetric _ _ _ _ Cong_EF_BF) as Cong_BF_EF.\n\n\tpose proof (\n\t\tlemma_s_conga\n\t\tB A F C A F\n\t\t_ _ _ _\n\t\tOnRay_AB_B\n\t\tOnRay_AF_F\n\t\tOnRay_AC_E\n\t\tOnRay_AF_F\n\t\tCong_AB_AE\n\t\tCong_AF_AF\n\t\tCong_BF_EF\n\t\tnCol_B_A_F\n\t) as CongA_BAF_CAF.\n\n\tpose proof (lemma_equalanglessymmetric _ _ _ _ _ _ CongA_BAF_CAF) as CongA_CAF_BAF.\n\tassert (CongA_CAF_BAF2 := CongA_CAF_BAF).\n\tdestruct CongA_CAF_BAF2 as (_ & _ & _ & _ & _ & _ & _ & _ & _ & _ & _ & nCol_C_A_F).\n\tpose proof (lemma_ABCequalsCBA _ _ _ nCol_C_A_F) as CongA_CAF_FAC.\n\tpose proof (lemma_equalanglestransitive _ _ _ _ _ _ _ _ _ CongA_BAF_CAF CongA_CAF_FAC) as CongA_BAF_FAC.\n\n\texists F.\n\tsplit.\n\texact CongA_BAF_FAC.\n\texact InAngle_BAC_F.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/proposition_09.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6696735261428253}}
{"text": "Require Export BinInt.\nRequire Import BinNat.\nRequire Import Karatsuba.\n\nDefinition Zmult x y := \nmatch x, y with\n|Z0, _ => Z0\n|_, Z0 => Z0\n|(Zpos x'), (Zpos y') => Z_of_N (KaratsubaMult (Npos x') (Npos y'))\n|(Zpos x'), (Zneg y') => Zopp (Z_of_N (KaratsubaMult (Npos x') (Npos y')))\n|(Zneg x'), (Zpos y') => Zopp (Z_of_N (KaratsubaMult (Npos x') (Npos y')))\n|(Zneg x'), (Zneg y') => Z_of_N (KaratsubaMult (Npos x') (Npos y'))\nend.\n\nTheorem ZmultCorrect : forall x y, (Zmult x y)=(BinInt.Zmult x y).\nProof.\nintros.\ndestruct x; destruct y; try reflexivity;\nsimpl;\nrewrite KaratsubaMultCorrect;\nreflexivity.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "karatsuba", "sha": "6c20ebe144d5c9a86ba47e11affecf11fa2c8881", "save_path": "github-repos/coq/coq-contribs-karatsuba", "path": "github-repos/coq/coq-contribs-karatsuba/karatsuba-6c20ebe144d5c9a86ba47e11affecf11fa2c8881/Karatsuba/Zmult.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6695991416770485}}
{"text": "Require Import ssreflect ssrbool ssrnat fintype.\nSet Implicit Arguments.\n\nRecord pos := mkPos { n :> nat ; N_pos : (0 < n)%coq_nat }.\n\nLemma is_pos (p : pos) : 0 < p.\nProof. by case: p=> m pf; apply/ltP. Qed.\n\nDefinition i0 (p : pos) : 'I_p := Ordinal (is_pos p).\n", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/linking/pos.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6695991383948261}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import ssrbool eqtype ssrnat seq fintype ssrfun tuple finset.\nFrom Bits\n     Require Import bits.\nRequire Import spec.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nDefinition inter n (bs bs': BITS n) : BITS n := andB bs bs'.\n\nLemma inter_repr n (bs bs' : BITS n) E E' : repr bs E -> repr bs' E' ->\n    repr (inter bs bs') (E :&: E').\nProof. by move=> -> ->; apply/setP => i; rewrite !inE getBit_liftBinOp. Qed.\n", "meta": {"author": "artart78", "repo": "coq-bitset", "sha": "806821b4ccf259885dfb5645e0e6957fb1149c52", "save_path": "github-repos/coq/artart78-coq-bitset", "path": "github-repos/coq/artart78-coq-bitset/coq-bitset-806821b4ccf259885dfb5645e0e6957fb1149c52/src/ops/inter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6695991364920695}}
{"text": "(*|\n####################################\nSplit conjunction goal into subgoals\n####################################\n\n:Link: https://stackoverflow.com/q/43945888\n|*)\n\n(*|\nQuestion\n********\n\nConsider the following toy exercise:\n|*)\n\nTheorem swap_id : forall (m n : nat), m = n -> (m, n) = (n, m).\nProof.\n  intros m n H.\n\n(*| At this point I have the following: |*)\n\n  Show. (* .unfold .messages *)\nAbort. (* .none *)\n\n(*|\nI would like to split the goal into two subgoals, ``m = n`` and ``n =\nm``. Is there a tactic which does that?\n|*)\n\n(*|\nAnswer\n******\n\nSolve using the `f_equal\n<https://coq.inria.fr/refman/Reference-Manual010.html#hevea_tactic169>`__\ntactic:\n|*)\n\nTheorem test : forall (m n : nat), m = n -> (m, n) = (n, m).\nProof.\n  intros m n H. f_equal.\n\n(*| With state: |*)\n\n  Show. (* .unfold .messages *)\n\n(*|\n----\n\n**A:** A comment about the reason ``f_equal`` works: if we unfold some\nnotations, we'll get from the goal ``(m, n) = (n, m)`` to ``pair m n =\npair n m``, where ``pair`` is the only constructor of the ``prod``\ndatatype. At this point it should be obvious why ``f_equal`` splits\nthe goal into two subgoals.\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/split-conjunction-goal-into-subgoals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.6695956058145014}}
{"text": "(* Author: Yubo CAI, Junyuan WANG *)\n(* CSE203 Logic and Proof Final Project *)\n\n(* -------------------------------------------------------------------- *)\nFrom mathcomp Require Import all_ssreflect.\n(* --------------- *) Import Monoid.\n\n(* -------------------------------------------------------------------- *)\nSet   Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet   Printing Projections.\nSet   Printing Projections.\nUnset SsrOldRewriteGoalsOrder.\n\n(* -------------------------------------------------------------------- *)\nNotation \"[ 'seq' E | i < n ]\" := (mkseq (fun i => E) n)\n  (at level 0, E at level 99, i name,\n   format \"[ 'seq'  E  |  i  <  n ]\") : seq_scope.\n\n(* ==================================================================== *)\nLemma mkseqS {T : Type} (f : nat -> T) (n : nat) :\n  [seq f i | i < n.+1] = rcons [seq f i | i < n] (f n).\nProof.\nby rewrite /mkseq -addn1 iotaD map_cat /= add0n cats1.\nQed.\n\n(* ==================================================================== *)\n(* Some extras arithmetic lemmas that are needed later                  *)\nLemma sum_pow2 (n : nat) :\n  \\sum_(i < n) 2^i = (2^n).-1.\nProof.\nelim: n => [|n ih]; first by rewrite big_ord0.\nrewrite big_ord_recr //= ih [LHS]addnC -subn1.\nrewrite addnBA ?expn_gt0 // subn1; congr _.-1.\nby rewrite addnn -mul2n -expnS.\nQed.\n\n(* -------------------------------------------------------------------- *)\nLemma modn2_neq0 (n : nat) : (n %% 2 != 0) = n %% 2 :> nat.\nProof. by rewrite modn2 eqb0 negbK. Qed.\n\n(* -------------------------------------------------------------------- *)\nLemma divnE (n : nat) (p : nat) (k : nat) :\n  p != 0 -> k * p <= n < k.+1 * p -> n %/ p = k.\nProof.\nmove=> nz_p; elim: k n => [|k ih] n.\n- by rewrite !simpm => lt; rewrite divn_small.\nrewrite [X in X <= _]mulSn [X in _ < X]mulSn => rg; have le_pn: p <= n.\n- by case/andP: rg => [+ _] => /(leq_trans _); apply; apply/leq_addr.\nmove: rg; rewrite -leq_subRL // -ltn_subLR //.\nmove/ih => <-; rewrite -{1}[n](subnK le_pn) divnDr //.\nby rewrite divnn lt0n nz_p addn1.\nQed.\n\n(* -------------------------------------------------------------------- *)\nLemma divn_sumr {I : Type} (P : pred I) (F : I -> nat) (r : seq I) (d : nat) :\n  (forall i, P i -> d %| F i) ->\n    (\\sum_(i <- r | P i) F i) %/ d = \\sum_(i <- r | P i) (F i) %/ d.\nProof.\nmove=> hdvd; elim/big_rec2: _ => //=; first by rewrite div0n.\nby move=> i _ n Pi <-; rewrite divnDl ?hdvd.\nQed.\n\n(* ==================================================================== *)\n(* We define the discrete logarithm in base 2.                          *)\n(*                                                                      *)\n(*   - log2(n) = the number of bits needed to represent all `n`         *)\n(*               differents values or the range [0..n[                  *)\n\nDefinition log2 (n : nat) := trunc_log 2 n.\n\nLemma log2_0 : log2 0 = 0.\nProof. exact: trunc_log0. Qed.\n\nLemma log2_1 : log2 1 = 0.\nProof. exact: trunc_log1. Qed.\n\nLemma log2_expnK n : log2 (2 ^ n) = n.\nProof. exact: trunc_expnK. Qed.\n\nLemma log2_eq n k : 2 ^ n <= k < 2 ^ n.+1 -> log2 k = n.\nProof. exact: trunc_log_eq. Qed.\n\nLemma log2_homo : {homo log2 : m n / m <= n}.\nProof. exact: leq_trunc_log. Qed.\n\nLemma log2_double (n : nat) : 0 < n -> log2 n.*2 = (log2 n).+1.\nProof. exact: trunc_log2_double. Qed.\n\nLemma log2S (n : nat) : 1 < n -> log2 n = (log2 n./2).+1.\nProof. exact: trunc_log2S. Qed.\n\nLemma log2_eq0 (n : nat) : (log2 n == 0) = (n < 2).\nProof. by rewrite trunc_log_eq0 /= ltnS. Qed.\n\nLemma log2_lt2 (n : nat) : n < 2 -> log2 n = 0.\nProof. by rewrite -log2_eq0 => /eqP. Qed.\n\nLemma log2_ltn (n : nat) : n < 2 ^ (log2 n).+1.\nProof. exact: trunc_log_ltn. Qed.\n\nLemma log2_bounds (n : nat) : n != 0 -> 2 ^ (log2 n) <= n < 2 ^ (log2 n).+1.\nProof.\nby move=> nz_n; apply: (@trunc_log_bounds 2 n) => //; rewrite lt0n.\nQed.\n\n(* ==================================================================== *)\n(* We provide a library for bit-vectors. A bit-vector is any sequence   *)\n(* of booleans whose last element is not `false`.                       *)\n\nRecord bits := Bitseq { bitseq :> seq bool; _ : last true bitseq; }.\n\nCanonical  bits_subType := Eval hnf in [subType for bitseq].\nDefinition bits_eqMixin := Eval hnf in [eqMixin of bits by <:].\nCanonical  bits_eqType  := Eval hnf in EqType bits bits_eqMixin.\n\nLemma bits_inj : injective bitseq.\nProof. exact: val_inj. Qed.\n\n(* -------------------------------------------------------------------- *)\n(* The notation `b.[i]` allows to access the `i`-th bit of a bit-       *)\n(* vector `b`. The bit-vector is implicitly padded with a infinite      *)\n(* sequence of `false`.                                                 *)\n\nDefinition bit i (b : seq bool) := nosimpl (nth false b i).\n\nNotation \"b .[ i ]\" := (bit i b).\n\nLemma bit_oversize (b : bits) (i : nat) :\n  size b <= i -> b.[i] = false.\nProof. by case: b => /= b _ lti; rewrite /bit nth_default. Qed.\n\n(* -------------------------------------------------------------------- *)\n(* We now prove that for any sequence `s` of booleans, there exists a   *)\n(* bit-vector `t` with the same bits (once padded with an infinite      *)\n(* sequence of `false`), i.e. `t` is `s` with the final `false`         *)\n(* elements trimed.                                                     *)\n\nLemma bits_canon_spec (s : seq bool) :\n  { t : seq bool |\n        forall i, nth false s i = nth false t i\n      & last true t }.\nProof.\nelim/last_ind: s => [|s [] ih]; first by exists [::].\n- by exists (rcons s true) => //; rewrite last_rcons.\ncase: ih => bs h1 h2; exists bs => //.\nmove=> i; rewrite nth_rcons; case: ltnP => // le.\nrewrite if_same; apply/esym; case: (ltnP i (size bs)); last first.\n- by move=> ?; rewrite nth_default.\nmove/(leq_ltn_trans le) => {le} lt; absurd false => //.\nmove: h2; rewrite (last_nth false) -[size bs]prednK //=.\n- by apply: (leq_ltn_trans _ lt).\nrewrite -h1 nth_default // -ltnS prednK //.\nby apply: (leq_ltn_trans _ lt).\nQed.\n\n(* -------------------------------------------------------------------- *)\n(* The function `mkbits` allows the creation of a bit-vector from a     *)\n(* given sequence of booleans.                                          *)\n\nDefinition mkbits_def (s : seq bool) :=\n  Bitseq (s2valP' (bits_canon_spec s)).\n\nFact mkbits_key : unit.\nProof. by []. Qed.\n\nDefinition mkbits := locked_with mkbits_key mkbits_def.\nCanonical mkbits_unlockable := [unlockable fun mkbits].\n\n(* -------------------------------------------------------------------- *)\nLemma mkbitsE (s : seq bool) (i : nat) : (mkbits s).[i] = s.[i].\nProof. by rewrite unlock; move: (s2valP (bits_canon_spec s) i). Qed.\n\n(* -------------------------------------------------------------------- *)\nLemma size_mkbits_le (s : seq bool) :\n  size (mkbits s) <= size s.\nProof.\nrewrite leqNgt; apply/negP => lt.\nhave := mkbitsE s (size (mkbits s)).-1; rewrite [X in _ = X]nth_default.\n- by rewrite -ltnS prednK // (leq_ltn_trans _ lt).\nrewrite /bit (@set_nth_default _ _ true) ?prednK //.\n- by apply: (leq_ltn_trans _ lt).\nby rewrite nth_last unlock (s2valP' (bits_canon_spec s)).\nQed.\n\n(* -------------------------------------------------------------------- *)\nLemma mkbitsK (s : seq bool) : last true s -> mkbits s = s :> seq _.\nProof.\nmove=> h; apply: (@eq_from_nth _ false); last first.\n- by move=> i lti; apply: mkbitsE.\nhave := size_mkbits_le s; rewrite leq_eqVlt => /orP[/eqP //|lt].\nabsurd (last true s) => //; rewrite -nth_last.\nrewrite (@set_nth_default _ _ false).\n- by rewrite prednK // (leq_ltn_trans _ lt).\nrewrite -/(bit _ _) -mkbitsE /bit nth_default //.\nby rewrite -ltnS prednK // (leq_ltn_trans _ lt).\nQed.\n\n(* -------------------------------------------------------------------- *)\n(* Two bit-vectors are equal (i.e. represented by the same sequence)    *)\n(* iff they have the same bits (once padded with an infinite sequence   *)\n(* of `false`.                                                          *)\n\nLemma bits_eqP (b1 b2 : bits) :\n  reflect (forall i, b1.[i] = b2.[i]) (b1 == b2).\nProof.\napply: (iffP eqP) => [->//|].\ncase: b1 b2 => [b1 h1] [b2 h2] /= eq_bits.\napply/val_eqP/eqP => /=; apply: (@eq_from_nth _ false); last first.\n- by move=> i _; apply: eq_bits.\nwlog: b1 h1 b2 h2 eq_bits / (size b1 <= size b2) => [wlog|].\n- case: (leqP (size b1) (size b2)); first by apply: wlog.\n  by move/ltnW => le; apply/esym/wlog.\nrewrite leq_eqVlt => /orP[/eqP //|lt_sz].\nabsurd false => //; move/(_ (size b2).-1): eq_bits.\nrewrite [X in _ = X]/bit (set_nth_default true).\n- by rewrite ltn_predL (leq_ltn_trans _ lt_sz).\nrewrite nth_last h2 -/(is_true _) /bit nth_default //.\nby rewrite -ltnS prednK // (leq_ltn_trans _ lt_sz).\nQed.\n\nLemma bits_eqW (b1 b2 : bits) :\n  (forall i, b1.[i] = b2.[i]) <-> (b1 = b2).\nProof. by rewrite (rwP eqP); split=> /bits_eqP. Qed.\n\n(* -------------------------------------------------------------------- *)\n(* The empty bit-vector and some related lemmas.                        *)\n\nDefinition bits0 := mkbits [::].\n\nNotation \"0%:B\" := bits0 (at level 0).\n\nLemma b0E (i : nat) : 0%:B.[i] = false.\nProof. by rewrite mkbitsE /bit nth_nil. Qed.\n\nLemma val_b0E : val 0%:B = [::].\nProof. by rewrite /mkbits /= mkbitsK. Qed.\n\nLemma size_b0 : size 0%:B = 0.\nProof. by rewrite val_b0E. Qed.\n\n(* -------------------------------------------------------------------- *)\nLemma size_bits_eq0P (b : bits) :\n  (size b == 0) = (b == 0%:B).\nProof. by rewrite -val_eqE /= val_b0E size_eq0. Qed.\n\n(* -------------------------------------------------------------------- *)\nLemma bits_neq0P (b : bits) :\n  reflect (exists i, b.[i]) (b != 0%:B).\nProof.\napply: (iffP idP); last first.\n- by case=> i nz_bi; apply/contraL: nz_bi => /eqP->; rewrite b0E.\ncase: b => b hb /=; rewrite -size_bits_eq0P /= => nz_szb.\nmove: hb; rewrite (last_nth false) -[size b]prednK ?lt0n //=.\nby move: _.-1 => i h; exists i.\nQed.\n\n(* -------------------------------------------------------------------- *)\nLemma bits_neq0W (b : bits) : (exists i, b.[i]) <-> (b <> 0%:B).\nProof. by split=> [|/eqP] /bits_neq0P => // /eqP. Qed.\n\n(* -------------------------------------------------------------------- *)\nLemma hibit_neq0P (b : bits) : (b != 0%:B) = b.[(size b).-1].\nProof.\nrewrite -size_bits_eq0P; case: b => /= b hb.\nby rewrite /bit nth_last; case: b hb.\nQed.\n\n(* -------------------------------------------------------------------- *)\nLemma hibit_neq0W (b : bits) : (b <> 0%:B) <-> b.[(size b).-1].\nProof. by rewrite -hibit_neq0P; split=> /eqP. Qed.\n\n(* -------------------------------------------------------------------- *)\n(* The bitwise xor (eXclusive OR) of two bit-vectors                    *)\n\nDefinition bxor (b1 b2 : bits) : bits :=\n  mkbits [seq b1.[i] (+) b2.[i] | i < maxn (size b1) (size b2)].\n\nLemma bxorE (b1 b2 : bits) (i : nat) :\n  (bxor b1 b2).[i] = b1.[i] (+) b2.[i].\nProof.\nrewrite mkbitsE /=; case: (ltnP i (maxn (size b1) (size b2))) => [lt|ge].\n- by rewrite /bit nth_mkseq.\nrewrite /bit !nth_default ?size_mkseq //;\n  by move: ge; rewrite geq_max => /andP[].\nQed.\n\n(* -------------------------------------------------------------------- *)\n(* We prove that the set of bitvectors, with 0%:B and (.+), forms a     *)\n(* commutative monoid.                                                  *)\n\nLemma bxor0b : left_id 0%:B bxor.\nProof.\nby move=> b; apply/eqP/bits_eqP => i; rewrite !(bxorE, b0E) addFb.\nQed.\n\nLemma bxorC : commutative bxor.\nProof.\nby move=> b1 b2; apply/eqP/bits_eqP => i; rewrite !bxorE addbC.\nQed.\n\nLemma bxorA : associative bxor.\nProof.\nby move=> b1 b2 b3; apply/eqP/bits_eqP => i; rewrite !bxorE addbA.\nQed.\n\nLemma bxorb0 : right_id 0%:B bxor.\nProof. by move=> b; rewrite bxorC bxor0b. Qed.\n\nLemma bxorbb : self_inverse 0%:B bxor.\nProof.\nby  move=> b; apply/eqP/bits_eqP => i; rewrite bxorE b0E addbb.\nQed.\n\nNotation \"b1 .+ b2\" := (bxor b1 b2) (at level 50, left associativity).\n\nCanonical bxor_monoid := Monoid.Law bxorA bxor0b bxorb0.\nCanonical bxor_comoid := Monoid.ComLaw bxorC.\n\n(* -------------------------------------------------------------------- *)\nLemma bigxorE {I : Type} (P : pred I) (F : I -> bits) (r : seq I) (i : nat) :\n    (\\big[bxor/0%:B]_(x <- r | P x) F x).[i]\n  = \\big[addb/false]_(x <- r | P x) (F x).[i].\nProof.\nelim/big_ind2: _ => //; first by rewrite b0E.\nby move=> _ bs _ cs <- <-; rewrite bxorE.\nQed.\n\n(* ==================================================================== *)\n(* We now define functions from converting from bit-vectors to natural  *)\n(* numbers, following the 1-complement convention.                      *)\n(*                                                                      *)\n(* We prove that b2n / n2b are the inverse of each other, along with    *)\n(* some more basic properties.                                          *)\n\nDefinition b2n (b : bits) : nat :=\n  \\sum_(i < size b) 2^i * b.[i].\n\nDefinition n2b (n : nat) : bits :=\n  mkbits [seq (n %/ (2 ^ i)) %% 2 != 0 | i < (log2 n).+1].\n\n(* -------------------------------------------------------------------- *)\nLemma b2nWE (n : nat) (b : bits) :\n  size b <= n -> b2n b = \\sum_(i < n) 2^i * b.[i].\nProof.\npose F i := 2^i * b.[i]; move=> le; rewrite /b2n.\nrewrite (big_ord_widen n F) // big_mkcond /=.\napply: eq_bigr; case=> /= i lti _; rewrite {}/F.\nby case: ltnP => // gei; rewrite /bit nth_default ?simpm.\nQed.\n\n(* -------------------------------------------------------------------- *)\nLemma n2b0 : n2b 0 = 0%:B.\nProof. \napply/eqP/bits_eqP => i; rewrite b0E /n2b mkbitsE.\nrewrite log2_0 -(@eq_mkseq _ (fun=> false)) //.\n- by move=> j /=; rewrite div0n mod0n eqxx.\ncase: (ltnP i 1) => ?; first by rewrite /bit nth_mkseq.\nby rewrite /bit nth_default.\nQed.\n\n(* -------------------------------------------------------------------- *)\nLemma n2bE (n : nat) (i : nat) :\n  (n2b n).[i] = ((n %/ 2 ^ i) %% 2 != 0).\nProof.\ncase: (n =P 0) => [->|/eqP nz_n].\n- by rewrite n2b0 b0E div0n mod0n eqxx.\nrewrite mkbitsE; case: (ltnP i (log2 n).+1) => [lt|ge].\n- by rewrite /bit nth_mkseq.\nrewrite /bit nth_default ?size_mkseq //.\napply/esym/negbTE; rewrite negbK divn_small //.\nhave /andP [_ +] := log2_bounds nz_n.\nby move/leq_trans; apply; apply: leq_pexp2l.\nQed.\n\n(* -------------------------------------------------------------------- *)\nLemma size_n2b (i : nat) : i != 0 -> size (n2b i) = (log2 i).+1.\nProof.\nmove=> nz_i; set d := (log2 i).+1.\nsuff nz: (n2b i).[d.-1].\n- apply/eqP; rewrite /n2b; set s := (X in mkbits X).\n  have := size_mkbits_le s; rewrite size_mkseq -/d.  \n  rewrite leq_eqVlt => /orP[//|lt]. absurd (n2b i).[d.-1] => //.\n  by rewrite bit_oversize.\nhave := log2_bounds nz_i; rewrite n2bE /d /=.\nrewrite -[X in X <= _]mul1n expnS => /divnE -> //.\nby rewrite -lt0n expn_gt0.\nQed.\n\n(* -------------------------------------------------------------------- *)\nLemma size_n2b_half (i : nat) :\n  size (n2b i./2) = (size (n2b i)).-1.\nProof.\ncase: i => /= [|i]; first by rewrite n2b0 /= size_b0.\ncase: i => /= [|i].\n- by rewrite n2b0 size_b0 /n2b log2_1 mkbitsK.\nby rewrite !size_n2b //= [in RHS]log2S.\nQed.\n\n(* -------------------------------------------------------------------- *)\nLemma b2nE (b : bits) (i : nat) :\n  ((b2n b) %/ 2 ^ i) %% 2 = b.[i].\nProof.\npose F (i : nat) := 2 ^ i * b.[i]; rewrite /b2n.\nhave dvdF (j : nat) : i <= j -> 2 ^ i %| F j.\n- by move=> le_ij; rewrite dvdn_mulr // dvdn_exp2l.\ncase: (ltnP i (size b)) => [lti|gei]; last first.\n- rewrite bit_oversize //= divn_small ?mod0n //.\n  apply: (@leq_ltn_trans (\\sum_(j < size b) 2 ^ j)).\n  - apply: leq_sum; case=> /= j ltj _.\n    by case: b.[_]; rewrite simpm.\n  by rewrite sum_pow2 prednK ?expn_gt0 // leq_pexp2l.\nrewrite -(big_mkord xpredT F) (big_cat_nat _ (n := i.+1)) //=.\nrewrite divnDr; first rewrite big_nat dvdn_sum //.\n- by move=> j /andP[/ltnW + _]; apply: dvdF.\nrewrite -[X in (_ + X)](@divnK 2); last rewrite addnC modnMDl.\n- rewrite big_nat divn_sumr.\n  - by move=> j /andP[/ltnW + _]; apply: dvdF.\n  rewrite dvdn_sum // => j /andP[/[dup] lt_ik / ltnW le_ij _].\n  rewrite /F mulnC -muln_divA ?dvdn_exp2l //.\n  by rewrite dvdn_mull // -expnB // dvdn_exp // subn_gt0.\nrewrite big_nat_recr //= divnDr ?dvdn_mulr //.\nrewrite mulKn ?expn_gt0 // [X in X+_](_ : _ = 0); last first.\n- by rewrite add0n modn_small // ltnS leq_b1.\nrewrite divn_small // (@leq_ltn_trans (\\sum_(j < i) 2 ^ j)) //.\n- rewrite big_mkord; apply: leq_sum => /= -[/= k ltk] _.\n  apply/(@leq_trans (2 ^ k))/leq_pexp2l => //.\n  by rewrite /F; case: b.[k]; rewrite simpm.\n- by rewrite sum_pow2 ltn_predL expn_gt0.\nQed.\n\n(* -------------------------------------------------------------------- *)\nLemma b2nK : cancel b2n n2b.\nProof.\nby move=> b; apply/eqP/bits_eqP => i; rewrite n2bE b2nE eqb0 negbK.\nQed.\n\n(* -------------------------------------------------------------------- *)\nLemma n2bK : cancel n2b b2n.\nProof.\nsuff: forall l, forall i, log2 i = l -> b2n (n2b i) = i.\n- by move=> ih i; apply: (ih (log2 i)).\nelim=> [|l ih] i logiE.\n- rewrite /n2b logiE mkseqS /= expn0 divn1.\n  rewrite (b2nWE (size_mkbits_le _)) /=.\n  rewrite big_ord_recl /= big_ord0 addn0.\n  rewrite expn0 mul1n mkbitsE /bit /= modn2_neq0.\n  by rewrite modn_small // -log2_eq0; apply/eqP.\nhave gt1_n: 1 < i by rewrite ltnNge -ltnS -log2_eq0 logiE.\npose F i k := 2 ^ k * (n2b i).[k].\nhave gt0_size: 0 < size (n2b i).\n- by rewrite lt0n size_n2b //; case: {+}i gt1_n.\nrewrite /b2n -(big_mkord predT (F i)) /= -[size _]prednK //.\nrewrite big_nat_recl //= {1}/F expn0 mul1n.\nrewrite -(eq_big_nat _ _ (F1 := fun j => (F i./2 j) * 2)).\n- move=> k rg_k; rewrite /F n2bE modn2_neq0.\n  rewrite mulnAC -expnSr; congr (_ * _).\n  by rewrite n2bE modn2_neq0 -divn2 -divnMA -expnS.\nrewrite -big_distrl /= -size_n2b_half big_mkord -/(b2n _) ih.\n- by rewrite log2S // in logiE; case: logiE.\nrewrite n2bE expn0 divn1 modn2_neq0.\nby rewrite addnC -divn2; apply/esym/divn_eq.\nQed.\n\n(* -------------------------------------------------------------------- *)\nLemma lt_n2b (b1 b2 : bits) :\n  (exists2 k,\n      (forall i, k < i -> b1.[i] = b2.[i])\n    & b1.[k] < b2.[k])\n  -> b2n b1 < b2n b2.\nProof.\ncase=> k eq lt; pose s := maxn (size b1) (size b2).\nrewrite !(@b2nWE s) /=; try by rewrite leq_max leqnn simpm.\npose g (b : bits) (i : nat) := 2^i * b.[i].\nhave [z_b1k nz_b2k] : (~~ b1.[k]) /\\ b2.[k].\n- by case: b1.[k] b2.[k] lt => [] [].\nrewrite -(big_mkord predT (g b1)) -(big_mkord predT (g b2)) /=.\nhave lek: k < s.\n- apply/(@leq_trans (size b2))/leq_maxr.\n  apply/contraLR: lt; rewrite -!(leqNgt, ltnNge).\n  by move/bit_oversize => ->.\nrewrite [X in X<_](big_cat_nat _ (n := k.+1)) //=.\nrewrite [X in _<X](big_cat_nat _ (n := k.+1)) //=.\nrewrite -!addSn; apply: leq_add; last first.\n- rewrite leq_eqVlt -(rwP orP) /g; left; apply/eqP.\n  by apply/eq_big_nat => i /andP[+ _] => /eq ->.\nrewrite !big_nat_recr //= {2 4}/g.\nrewrite (negbTE z_b1k) nz_b2k ?simpm.\napply: (@leq_trans (2 ^ k)); last by apply: leq_addl.\napply: (@leq_ltn_trans (\\sum_(0 <= i < k) 2 ^ i)).\n- apply: leq_sum => i _; rewrite {}/g.\n  by case: b1.[i]; rewrite ?simpm.\nsuff ->: \\sum_(0 <= i < k) 2 ^ i = (2 ^ k).-1.\n- by rewrite prednK // expn_gt0.\n- by rewrite big_mkord; apply/sum_pow2.\nQed.\n\n(* ==================================================================== *)\nModule Nim.\nContext (p : nat).\n\n(* A Nim game is composed of `p` rows of matches. We represents this    *)\n(* as a function from [s : 'I_p -> nat] where [s i] denotes the number  *)\n(* of matches in the row [i].                                           *)\n(*                                                                      *)\n(* The type ['I_p] stands for the range [0..p[, i.e. for the set of the *)\n(* natural numbers lower then [p].                                      *)\n(*                                                                      *)\n(* It is defined as the following induction predicate/type:             *)\n(*                                                                      *)\n(* Inductive ordinal (p : nat) :=                                       *)\n(* | Ordinal : forall (i : nat), (i < p) -> ordinal p.                  *)\n\nDefinition state := 'I_p -> nat.\n\n(* We now define a function that, given a state [s], returns a list     *)\n(* of natural numbers [r] s.t. for any natural number [i] lower than    *)\n(* [p], the [i]-th element of [r] is equal to the number of matches     *)\n(* in the [i]-th row of [s] (i.e. is equal to [s i])                    *)\n(*                                                                      *)\n(* The function [map] is defined as follows:                            *)\n(*                                                                      *)\n(* Fixpoint map (f : T -> U) (s : list T) : list U :=                   *)\n(*   match s with                                                       *)\n(*   | nil => nil                                                       *)\n(*   | cons x s' => cons (f x) (map f s')                               *)\n(*   end.                                                               *)\n(*                                                                      *)\n(* Note that [map (fun i => f i) s] is printed as:                      *)\n(*                                                                      *)\n(*   [seq s i | i <- s]                                                 *)\n(*                                                                      *)\n(* Also, note that [enum 'I_p] is the list that contains all the        *)\n(* natural numbers from [0] to [p] (excluded).                          *)\n\nDefinition rows (s : state) : list nat :=\n  map (fun i => s i) (enum 'I_p).\n\n(* We prove that the size of [rows s] if equal to [p] where [size] is   *)\n(* defined as follow:                                                   *)\n(*                                                                      *)\n(* Fixpoint size (s : seq T) :=                                         *)\n(*   match s with                                                       *)\n(*   | nil => 0                                                         *)\n(*   | cons _ s' => S (size s)                                          *)\n(*   end.                                                               *)\n\nLemma size_rows (s : state) : size (rows s) = p.\nProof. by rewrite /rows size_map size_enum_ord. Qed.\n\n(* We also prove that the [i]-th element of [rows s] is equal to [s i]. *)\n(* We use the function [nth] for that purpose, whose definition is:     *)\n(*                                                                      *)\n(* Fixpoint nth (x0 : T) (s : list T) (i : nat) {struct i} :=           *)\n(*   match s with                                                       *)\n(*   | nil =>                                                           *)\n(*       x0                                                             *)\n(*   | cons y s' =>                                                     *)\n(*       match i with                                                   *)\n(*       | O => y                                                       *)\n(*       | S j => nth x0 s j                                            *)\n(*       end                                                            *)\n(*   end.                                                               *)\n\nLemma nth_rows (s : state) (i : 'I_p) : nth 0 (rows s) i = s i.\nProof. by rewrite (nth_map i) ?size_enum_ord // nth_ord_enum. Qed.\n\n(* At each turn, the running player must select a row and remove at     *)\n(* least 1 match from this row. We here denote a binary relation [R]    *)\n(* over states s.t. [s1 R_i s2] iff it is possible to move from [s1] to *)\n(* [s2] in one turn on row [i].                                         *)\n\nInductive R (i : 'I_p) (s1 s2 : state) : Prop :=\n| Turn :\n      (s2 i < s1 i)\n   -> (forall j : 'I_p, j != i -> s2 j = s1 j)\n   -> R i s1 s2.\n  \n(* -------------------------------------------------------------------- *)\n(* The weight a of Nim state is obtained by xor'ing the number of       *)\n(* matches (in 1-complement) for all the game rows.                     *)\n\n(* First, write a function [weight_r] that takes a list [s] of natural  *)\n(* numbers, and that returns bit-vector obtained by xor'ing all the     *)\n(* elements [s] (in 1-complement).                                      *)\n(*                                                                      *)\n(* Hint: define a Fixpoint over [s] & use [bits0], [bxor] & [n2b].      *)\n\nFixpoint weight_r (s : seq nat) {struct s} : bits :=\n  match s with\n  | nil => bits0\n  | cons n s' => bxor (n2b n) (weight_r s')\n  end.\n\n(* We define the function [weight] s.t. [weight s] returns the weight   *)\n(* of the game state [s].                                               *)\n\nDefinition weight (s : state) : bits :=\n  weight_r (rows s).\n\n(* -------------------------------------------------------------------- *)\n(* Prove that the empty game board has a weight of 0                    *)\n(*                                                                      *)\n(* Here, [fun=> 0] denotes the constant function equal to 0.            *)\n\nLemma weight_empty : weight (fun=> 0) = 0%:B.\nProof.\n(* We start by unfolding the definition of [weight] & [rows]            *)\nrewrite /weight /rows.\n(* The proof can now be done by induction over [enum 'I_p]              *)\n(* FIXME *)\nelim: (enum 'I_p) => [|i s IHs] /=.\n- auto.\n- rewrite IHs.\n  rewrite n2b0.\n  rewrite bxor0b.\n  auto. \nQed.\n\n\n(* -------------------------------------------------------------------- *)\n(* We now prove some extra lemmas about [weight_r].                     *)\n(*                                                                      *)\n(* Hint: you can use the lemmas [bxor??] here.                          *)\n\nLemma weight_r0: weight_r nil = bits0.\nProof.\nrewrite /weight_r.\nauto.\nQed.\n\n\nLemma weight_r1 (n : nat): weight_r [:: n] = n2b n.\nProof.\nrewrite /weight_r.\nrewrite bxorb0.\nauto.\nQed.\n\n\nLemma weight_rS (n : nat) (ns : list nat) :\n  weight_r (n :: ns) = n2b n .+ weight_r ns.\nProof.\nrewrite /weight_r //=.\nQed.\n\n(* Here, [++] denotes [cat], the list-concatenation function.           *)\n(*                                                                      *)\n(* The function [cat] is defined as follows:                            *)\n(*                                                                      *)\n(* Fixpoint cat (r s : seq T) {struct r} :=                             *)\n(*   match r with                                                       *)\n(*   | nil => s                                                         *)\n(*   | cons y r' => cons y (cat r' s)                                   *)\n(*   end.                                                               *)\n\nLemma weight_rD (r s : list nat) :\n  weight_r (r ++ s) = bxor (weight_r r) (weight_r s).\nProof.\n(* FIXME *)\ninduction r.\n- simpl. rewrite bxor0b. auto.\n- simpl. rewrite IHr. rewrite bxorA. auto.\nQed.     \n\n(* -------------------------------------------------------------------- *)\n(* We can describe how the weight evolves after one turn                *)\n(*                                                                      *)\n(* We first  prove a characterization of [R]                            *)\n\nLemma RP (i : 'I_p) (s1 s2 : state) : R i s1 s2 ->\n  exists (p : seq nat) (q : seq nat),\n    [/\\ size p = i\n      , rows s1 = p ++ (s1 i) :: q\n      & rows s2 = p ++ (s2 i) :: q].\nProof.\ncase=> lt_s eq_s; exists (take i (rows s1)), (drop i.+1 (rows s1)); split.\n- by rewrite size_take size_rows ltn_ord.\n- rewrite -cat1s catA cats1 -[s1 i]nth_rows /=.\n  by rewrite -take_nth ?size_rows // cat_take_drop.\nrewrite -cat1s catA cats1 -[s2 i]nth_rows /=.\nhave ->: take i (rows s1) = take i (rows s2).\n- rewrite -!(map_nth_iota0 0) ?size_rows 1?ltnW //.\n  apply/eq_in_map=> j; rewrite mem_iota /= add0n => lt_ji.\n  have lt_jp: j < p by apply: (ltn_trans lt_ji).\n  rewrite !(nth_rows _ (Ordinal lt_jp)) /=.\n  by apply/esym/eq_s; rewrite -val_eqE /= ltn_eqF.\nhave ->: drop i.+1 (rows s1) = drop i.+1 (rows s2).\n- rewrite -[LHS](take_oversize (n := p - i.+1)).\n  - by rewrite size_drop size_rows.\n  rewrite -[RHS](take_oversize (n := p - i.+1)).\n  - by rewrite size_drop size_rows.\n  rewrite -!(map_nth_iota 0) ?size_rows //.\n  apply/eq_in_map=> j; rewrite mem_iota => /andP[lt_ij].\n  rewrite subnKC // => lt_jp.\n  rewrite !(nth_rows _ (Ordinal lt_jp)) /=.\n  by apply/esym/eq_s; rewrite -val_eqE /= gtn_eqF.\nby rewrite -take_nth ?size_rows // cat_take_drop.\nQed.    \n\n(* We can now state and prove how the weight of the state evolves       *)\n(* between two states related by [R].                                   *)\n(*                                                                      *)\n(* Hint: use [RP] and the [weight_rX] lemmas.                           *)\n(* Hint: you will also need the [bxorX] lemmas family.                  *)\n\n(* We write an auxiliary bxor operation here *)\nLemma bxorACA b1 b2 b3: (b1 .+ b2) .+ b3 = (b1 .+ b3) .+ b2.\nProof.\nby rewrite -bxorA [b2 .+ b3] bxorC bxorA.\nQed.\n\nLemma turn_weight (i : 'I_p) (s1 s2 : state) :\n  R i s1 s2 -> weight s2 = weight s1 .+ n2b (s1 i) .+ n2b (s2 i).\nProof.\n(* FIXME *)\nmove=> H. apply RP in H.\ncase: H => p H. case: H => q H. case: H => H1 H2 H3.\nrewrite /weight. \nrewrite H2 H3.\nrewrite weight_rD.\nrewrite weight_rD.\nrewrite weight_rS.\nrewrite weight_rS.\nrewrite bxorA.\nrewrite bxorA.\nrewrite ![(_ .+ n2b (s1 i)) .+ _]bxorACA.\nrewrite -!bxorA.\nrewrite bxorbb.\nrewrite bxorb0.\nrewrite bxorA.\nrewrite bxorC.\nrewrite bxorA.\nrewrite bxorA.\nrewrite ![( _ .+ weight_r q)]bxorC.\nauto.\nQed.\n\n\n(* -------------------------------------------------------------------- *)\n(* Any move from a 0-weighted game leads to a non 0-weighted game       *)\n(*                                                                      *)\n(* Hint: you should use [turn_weight] here.                             *)\n(* Hint: you can use the injectivity of n2b.                            *)\n(* Hint: b1 (+) b2 = true iff b1 = b2.                                  *)\n(* Hint: you can use contraposition, e.g. [contra_neq_not].             *)\n\nLemma ltf (n : nat):\n  n < n -> false.\nProof.\nintros.\ninduction n.\n- done.\n- by apply IHn in H.\nQed.\n\nLemma b02bnbb (x : 'I_p) (s : state):\n  0%:B = n2b (s x) .+ n2b (s x).\nProof.\nby rewrite bxorbb.\nQed.\n\nLemma z2nz (i : 'I_p) (s1 s2 : state) :\n  R i s1 s2 -> weight s1 = 0%:B -> weight s2 <> 0%:B.\nProof.\nhave n2b_inj: forall m n, n2b m = n2b n -> m = n.\n- by move=> m n /(can_inj n2bK).\n(* FIXME *)\n\nmove => H1 H2.\nhave HR: R i s1 s2.\napply H1.\ndestruct HR. \napply turn_weight in H1.\nrewrite H2 in H1.\nrewrite bxor0b in H1.\nmove => H3.\nrewrite H1 in H3.\nrewrite (b02bnbb i s2) in H3.\nhave contra: n2b (s1 i) .+ n2b (s2 i) .+ n2b (s2 i) = n2b (s2 i) .+ n2b (s2 i) .+ n2b (s2 i).\nby rewrite H3.\nmove: contra.\nrewrite -bxorA.\nrewrite -bxorA.\nrewrite bxorbb.\nrewrite bxorb0.\nrewrite bxorb0.\nmove => contra.\napply n2b_inj in contra.\nrewrite contra in H.\napply ltf  in H.\nauto.\nQed.\n\n\n(* -------------------------------------------------------------------- *)\n(* From any non 0-weight game, it is possible to move to a              *)\n(* 0-weighted game.                                                     *)\n(*                                                                      *)\n(* Hint: for this one, you are on your own.                             *)\n(* Hint: https://en.wikipedia.org/wiki/Nim#Proof_of_the_winning_formula *)\n\nLemma nz2z (s : state) : weight s <> 0%:B ->\n  exists (i : 'I_p), exists (s' : state), weight s' = 0%:B /\\ R i s s'.\nProof.\n\n(* FIXME *)\nintros.\npose w := weight s.\nremember (size w).-1 as d.\n\n(* Prove that w.[d] not equal to 0 *)\nhave hi: w.[d].\nrewrite Heqd.\napply hibit_neq0W.\napply H.\nhave hd := ((hibit_neq0W (weight s)).1 H).\nrewrite -Heqd in hd.\n\n(* Prove exist k such that x_k[d] not zero, prove by contradiction *)\nhave somek : exists (k : 'I_p), (n2b (s k)).[d].\n- apply/existsP/existsPn => //=.\nintro h2.\nunfold weight in hd.\nunfold rows in hd.\ninduction (enum 'I_p).\n- rewrite //b0E// in hd.\n- rewrite //bxorE in hd.\napply IHl.\nrewrite (negbTE (h2 a))// in hd.\nmove: somek => [k HX].\n(* pose x := n2b (s k) .\npose y := w .+ x. *)\nremember (weight s) as hw.\nremember (n2b (s k)) as x.\nremember  ( hw .+ x ) as y.\nremember (fun i => if i == k then b2n y else s i) as s'.\n\nhave sk' : s' k = b2n y.\n    rewrite Heqs'.\n    rewrite ifT.\n    auto.\n    auto.\n\nhave sk : s k = b2n x.\n    rewrite Heqx.\n    rewrite n2bK.\n    auto.\n\nhave HY: negb y.[d].\n    rewrite Heqy.\n    rewrite bxorE.\n    rewrite hi.\n    rewrite HX.\n    simpl.\n    apply is_true_true.\n\n(* Claim that y_k < x_k *)\nhave yltx: b2n y < b2n x.       \n    apply lt_n2b. \n    exists d.\n\n(* prove for all d<i x_k = y_k *)\nhave yxw: forall i, d < i -> y.[i] = x.[i].            \n    intros i h_i.\n    rewrite Heqx.\n    rewrite Heqy.\n    rewrite Heqhw.\n    rewrite bxorE - Heqx.\n    rewrite Heqd in h_i.\n    have hs: (size (weight s)) <= i.\n    unfold w in h_i. rewrite Heqhw in h_i.\n    - by (induction (size (weight s)) => //=; rewrite ltnS; apply IHn).\n    - rewrite (bit_oversize hs) //. apply yxw. \n\nhave yx: y.[d] < x.[d].\n    rewrite HX.\n    have yf: y.[d] = false.\n    apply negbTE.\n    apply HY.\n    rewrite yf.\n    simpl.\n    auto.\n    apply yx.\n\nexists k.\nexists s'.\n\n(* Finish the prove with weight s' = 0%:B /\\ R k s s' *)\nhave rr: R k s s'.\n    split.\n    rewrite sk.\n    rewrite sk'.\n    apply yltx.\n    intros.\n    rewrite Heqs'.\n    rewrite ifF.\n    revert H0.\n    rewrite neq_ltn => /orP [].\n    apply ltn_eqF.\n    apply gtn_eqF.\n    auto.\n\nsplit.\nrevert rr.\nhave w0: (weight s .+ n2b (s k) .+ n2b (s' k) = 0%:B).\nrewrite <- Heqhw.\nrewrite <- Heqx.\nrewrite <- Heqy.\nhave skrev': (n2b (s' k) = y).\nrewrite sk'.\nrewrite b2nK.\nauto.\nrewrite skrev'.\nrewrite bxorbb.\nauto.\nrewrite <- w0.      \napply turn_weight.\napply rr.\nQed.\n\n\nEnd Nim.\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/Project/nim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.6695956036206065}}
{"text": "(** * Tutoriel 6 - Ltac *)\n\n(** Dans ce tutoriel plus avancé, nous allons voir comment\n    écrire nos propres tactiques, à l'aide de Ltac. *)\n\n\n(** ** I. Un premier exemple *)\n\n(** Un premier cas d'utilisation de Ltac  *)\n\nModule Ltac_example.\n  Require Import ZArith Lia.\n  Open Scope Z_scope.\n\n (* Définition du type des listes de couples. *)\n Inductive elt_list :=\n  | Nil : elt_list\n  | Cons : Z -> Z -> elt_list -> elt_list.\n\n (* Un invariant exprimant que les couples sont rangés \n    par ordre croissant, ne se chevauchent pas, et sont\n    séparés d'au moins deux entiers. *)\n Inductive Inv_elt_list : Z -> elt_list -> Prop :=\n  | invNil  : forall b, Inv_elt_list b Nil\n  | invCons : forall (a b j : Z) (q : elt_list),\n     j <= a -> a <= b ->  Inv_elt_list (b+2) q ->\n     Inv_elt_list j (Cons a b q).\n\n (* Un théorème exprimant que si y est plus petit que\n    tous les éléments de l, et que z est plus petit que y,\n    alors z est plus petit que tous les éléments de l. *)\n Theorem inv_elt_list_monoton : forall l y z, \n Inv_elt_list y l -> z <= y -> Inv_elt_list z l.\n Proof.\n intros l y z Hinv Hle.\n induction Hinv.\n  - constructor.\n  - constructor;(lia||assumption).\n Qed.\n\n (* La tactique [Inv_monotony z] prend en argument une valeur [z] pour\n    la variable nommée [y] dans le théorème précédent, valeur difficile \n    à inférer pour Coq.\n    Deux buts seront alors générés :\n       - un de la forme [Inv_elt_list y l], noté B1\n       - et l'autre de la forme [z <= y],   noté B2.\n    La tactique [Inv_monotony] permet de finir la preuve si B1 est dans\n    les hypothèses et si B2 peut être déduit grâce à la tactique [lia]. *)\n Ltac Inv_monotony z := \n   apply inv_elt_list_monoton with (y:=z);\n    [assumption|lia].\n\nEnd Ltac_example.\n\n(** ** II. Quelques cas d'usage de Ltac *)\n\n  (** Avec Ltac, il est possible de faire bien plus que d'enchainer des \n      tactiques les unes à la suite des autres, comme nous l'avons vu dans \n      l'exemple précédent.\n      Une fonctionnalité très puissante de Ltac est de pouvoir faire du \n      pattern-matching sur le but courant. *)\n\n(** *** A. Un premier pattern-matching très simple *)\n\n  (** Voici un premier exemple pour vous montrer la syntaxe d'un\n      pattern-matching dans le langage de Ltac :  *)\n  Ltac my_trivial_tactic :=\n   match goal with\n      | [ |- _ ] => intro\n      | [ |- True ] => constructor\n    end.\n\n  (** Avec la tactique précédente, nous pouvons prouver : *)\n  Theorem m1 : True.\n  Proof. my_trivial_tactic. Qed.\n\n  (** Notez que [True] matche le 1er cas du pattern-matching de\n      [my_trival_tactic] et pourtant ce n'est pas ce cas de figure qui est\n      utilisé pour construire le terme de preuve, mais bien le 2ème.\n      En effet, le 1er cas du pattern-matching renvoie une erreur car la\n      tactique [intro] ne peut pas être utilisée sur le but [True]. *)\n\n(** *** B. Ecrire un pattern-matching plus compliqué *)\n\n  (** La tactique [find_if] vérifie si la conclusion est un if, puis,\n      si c'est le cas, détruit l'expression de test. *)\n  Ltac find_if :=\n    match goal with\n      | [ |- if ?X then _ else _ ] => destruct X\n    end.\n\n  (** Certaines classes de théorèmes sont triviales à prouver\n      automatiquement avec une telle tactique, comme par exemple : *)\n  Goal forall (a b c : bool),\n    if a\n      then if b\n        then True\n        else True\n      else if c\n        then True\n        else True.\n  Proof.\n    intros.\n    repeat find_if.\n      + constructor.\n      + constructor.\n      + constructor.\n      + constructor.\n    (* ou encore : [intros; repeat find_if; constructor.] *)\n  Qed.\n\n  (** Malheureusement, la tactique [find_if] n'est pas capable de détecter\n      qu'un if apparait dans un sous-terme du but, comme le montre l'exemple \n      suivant : *)\n  Goal forall (a b : bool),\n    (if a then 42 else 42) = (if b then 42 else 42).\n  Proof.\n    intros. \n    repeat find_if. (* Rien ne se passe. *)\n  Abort.\n\n  (** Le pattern [context] permet de résoudre ce problème. *)\n\n  (** Le comportement de la tactique [find_if_inside] est de trouver tout\n      sous-terme de la conclusion qui est un if, et ensuite de détruire\n      l'expression de test. *)\n  Ltac find_if_inside :=\n    match goal with\n      | [ |- context[if ?X then _ else _] ] => destruct X\n    end.\n\n  (** Cette version étend ce que pouvait résoudre la tactique [find_if],\n      car nous pouvons toujours démontrer : *)\n  Goal forall (a b c : bool),\n    if a\n      then if b\n        then True\n        else True\n      else if c\n        then True\n        else True.\n  Proof.\n    intros; repeat find_if_inside; constructor.\n  Qed.\n\n  (** Mais nous pouvons également utiliser [find_if_inside] pour prouver\n      les objectifs que [find_if] ne simplifie pas suffisamment : *)\n  Goal forall (a b : bool),\n    (if a then 42 else 42) = (if b then 42 else 42).\n  Proof.\n    intros; repeat find_if_inside; reflexivity.\n  Qed.\n\n(** *** C. Faire référence à une hypothèse dans un pattern-matching *)\n\n  (** Lorsque nous avons écrit les tactiques [find_if] et [find_if_inside],\n      nous avons vu la syntaxe [?X], permettant de faire référence à un \n      sous-terme. *)\n\n  (** Notez ici comment faire référence à une hypothèse dans le\n      pattern-matching : *)\n  Ltac intro_exact := intros; match goal with\n      | [ H : _ |- _ ] => exact H\n    end.\n\n  (** Avec la tactique [intro_exact], il est possible de prouver le but\n      suivant : *)\n  Goal forall P Q R : Prop, P -> Q -> R -> Q.\n  Proof. intro_exact. Qed.\n\n(** *** D. Pour le débuggage : [idtac] *)\n\n(** Ltac n'est pas très simple à prendre en main.\n    Pour vous aider à mieux comprendre pourquoi la tactique que vous\n    avez écrit ne fait pas ce que vous voulez, vous pouvez utiliser la\n    tactique [idtac]. *)\n\nLtac ex_idtac :=\n  intros; match goal with\n              | [ H : ?P |- _ ] => idtac H ; idtac P\n          end.\n\nGoal forall P, P -> P.\nProof. ex_idtac. apply X. Qed.\n\n\n(** ** III. Quelques exercices *)\n\n  (** *** Exercice 1 - Votre version de la tactique [tauto] *)\n\n  (** Cet exercice vous propose d'utiliser le langage de Ltac pour écrire\n      une version la plus proche possible de la tactique [tauto].\n      Vous nommerez votre tactique [my_tauto]. *)\n\nLtac my_tauto := \n  intros; repeat match goal with\n      | [ |- True ] => constructor ; idtac \"1\"\n      | [ _ : ?X |- ?X ] => assumption ; idtac \"2\"\n      | [ H : False |- _ ] => contradiction ; idtac \"3\"\n      | [ H : _/\\_ |- _ ] => destruct H ; idtac \"4\"\n      | [ |- _/\\_ ] => split ; idtac \"5\"\n      | [ H : _\\/_ |- _ ] => destruct H ; idtac \"6\"\n      | [ H : ?P->?Q |- ?Q ] => apply H ; idtac \"7\"\n      | [ H2 : _->_ |- _ ] => destruct H2 ; idtac H2 ; idtac \"8\"\n      | [ x : _ |- ex _ ] => exists x ; idtac \"9\"\n      | [ H : exists _,_  |- _] => destruct H ; idtac H ; idtac \"10\"\n      end.\n\n\n  (** Voici quelques cas de tests pour vous aider à tester votre tactique : *)\n\n  (* Niveau 1 : Une première version *)\n  Goal forall P, P -> True.\n  Proof. my_tauto. Qed.\n\n  Goal forall P Q R : Prop, P -> Q -> R -> Q.\n  Proof. my_tauto. Qed.\n\n  Goal forall P Q R : Prop,\n    P /\\ R /\\ Q -> Q /\\ R /\\ P.\n  Proof. my_tauto. Qed.\n\n  Goal forall P Q : Prop,\n    Q /\\ (P /\\ False) /\\ P -> P /\\ Q.\n  Proof. my_tauto. Qed.\n\n  Goal forall P Q,\n    False /\\ P -> Q.\n  Proof. my_tauto. Qed.\n\n\n  (* Niveau 2 : Avec le modus ponens *)\n  Goal forall P Q : Prop,\n    (P -> Q) -> (P -> True /\\ Q).\n  Proof. my_tauto. Qed.\n\n  Goal forall P Q R : Prop,\n    (Q -> R) -> (P /\\ Q -> P /\\ R).\n  Proof. my_tauto. Qed.\n\n  Goal forall P Q R S,\n    (S -> P /\\ (Q /\\ R)) -> (S -> (P /\\ Q) /\\ R).\n  Proof. my_tauto. Qed.\n\n  Goal forall P Q R S,\n    (S -> Q /\\ (P /\\ R)) -> (S -> (P /\\ Q) /\\ R).\n  Proof. my_tauto. Qed.\n\n  Goal forall P Q R,\n    (R -> P /\\ Q) -> (R -> Q /\\ P).\n  Proof. my_tauto. Qed.\n\n  Goal forall P Q,\n    (P -> Q /\\ True) -> (P -> Q).\n  Proof. my_tauto. Qed.\n\n\n  (* Niveau 3 : Quelques cas plus avancés *)\n  Goal forall P Q R : Prop, \n    (P \\/ Q \\/ False) /\\ (P -> Q) -> True /\\ Q.\n  Proof. my_tauto. Qed.\n\n  Goal forall P Q,\n    (P /\\ True -> Q) -> (P -> Q).\n  Proof. my_tauto. Qed.\n\n  Goal forall P Q R S,\n    (P /\\ (Q /\\ R) -> S) -> ((P /\\ Q) /\\ R -> S).\n  Proof. my_tauto. Qed.\n\n  Goal forall P Q R S,\n    (Q /\\ (P /\\ R) -> S) -> ((P /\\ Q) /\\ R -> S).\n  Proof. my_tauto. Qed.\n\n  Goal forall P Q R,\n    (P /\\ Q -> R) -> (Q /\\ P -> R).\n  Proof. my_tauto. Qed.\n\n  (* Niveau 4 : Pour aller plus loin que la tactique [tauto] *)\n  Goal forall (T : Type) (P : T -> Prop) (Q R : Prop),\n    (forall x, P x /\\ Q -> R) -> (exists y, P y /\\ Q -> R).\n  Proof. my_tauto. Abort. (* L'énoncé est faux en l'état, nous ne savons pas si il existe un élément de type  T*)\n\n  Goal forall (T : Type) (P : T -> Prop) (Q R : Prop) x,\n    (Q -> P x /\\ R) -> (Q -> ex P /\\ R).\n  Proof. my_tauto. Qed.\n\n  Goal forall (P : nat -> Prop) Q, (exists x, P x /\\ Q) -> Q /\\ (exists x, P x).\n  Proof. my_tauto. Qed.\n\n\n  (** *** Exercice 2 - Passer de [bool] à [Prop] *)\n\n  Require Import Arith Lia.\n\n  (** Vous avez peut-être déjà remarqué que, parfois, Coq fait apparaitre des\n      \"notations\" un peu étranges, comme [<=?]. *)\n\n  (** En réalité, [<=] est une notation pour [le], qui lui-même est un \n      prédicat inductif. Son type de retour est donc [Prop]. *)\n\n  Check le.\n  Check 1 <= 2.\n\n  (** Par contre, [<=?] a pour type de retour [bool], comme vous le montre \n  les commandes suivantes : *)\n  Check  1 <=? 2.\n  Check (1 <=? 2) = true.\n\n  (** Il est tout à fait possible de passer d'une notation à l'autre : *)\n  Lemma le_bool_imp_le : forall n m, (n <=? m) = true -> (n <= m).\n  Proof. \n    induction n.\n    + destruct m.\n      { intros. constructor.                     }\n      { intros. constructor. apply Peano.le_0_n. }\n    + destruct m.\n      { simpl. intro H. discriminate H.                                 }\n      { simpl. intro H. apply IHn in H. apply Peano.le_n_S. assumption. }\n  Qed.\n\nLemma le_imp_le_bool : forall n m, (n <= m) -> (n <=? m)=true.\nProof.\n  induction n.\n  + intros. simpl. reflexivity.\n  + intros. simpl. destruct m. inversion H. inversion H. \n    ++ pose proof (IHn m). rewrite H1 in H0. apply H0. constructor.\n    ++ apply Peano.le_S_n in H. apply (IHn m). exact H.\nQed.\n\n  (** Mais comme [lia] ne raisonne que sur [Prop], cette tactique est capable\n      de prouver le but [lt_impl_le_prop], mais pas le but [lt_impl_le_bool]. *)\n  Lemma lt_impl_le_prop : forall n m, n < m -> n <= m.\n  Proof. intros. lia. Qed.\n\nLtac conv_bool_to_prop := repeat match goal with\n  | [ H : _ <? _ = true|- _ ] => apply le_bool_imp_le in H ; idtac \"1\"\n  | [ H : _ <=? _ = true|- _ ] => apply le_bool_imp_le in H ; idtac \"1.2\"\n  | [ |-  _ <? _ = true ] => apply le_imp_le_bool ; idtac \"2\"\n  | [ |-  _ <=? _ = true ] => apply le_imp_le_bool ; idtac \"2.2\"\n\nend.\n\n  Lemma lt_impl_le_bool : forall n m, (n <? m) = true -> (n <=? m) = true.\n  Proof. intros. conv_bool_to_prop. lia. Qed.\n\n\n  (** Votre objectif est donc d'écrire une tactique qui réécrit des notations\n      [bool] en des notations sur [Prop].\n      L'utilisation de la bibliothèque standard de Coq est fortement \n      recommandée. *)\n\n  (** Vous commencerez par écrire une tactique qui transforme uniquement les\n      hypothèses.\n      Ensuite, il sera plus simple d'écrire une tactique qui transforme le but\n      courant, en adaptant la tactique écrite précédemment. *)\n\n\n\n(** ** IV. Des références pour aller plus loin *)\n\n(** Ltac :\n      - http://adam.chlipala.net/cpdt/html/Match.html\n      - http://www.lirmm.fr/~delahaye/papers/ltac%20(LPAR%2700).pdf\n\n    Ltac2, une version typée de Ltac :\n      - https://coq.inria.fr/refman/proof-engine/ltac2.html *)\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/TD6_B_Ltac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757312, "lm_q2_score": 0.8056321913146128, "lm_q1q2_score": 0.6695955915723764}}
{"text": "Lemma structured_intro_example1: forall A B C:Prop, A/\\B/\\C -> A.\nProof.\n  intros A B C [Ha [Hb Hc]].\n\n(*\n\n A : Prop\n B : Prop\n C : Prop\n Ha : A\n Hb : B\n Hc : C\n ============================\n  A\n*)\n\nAbort.\n\nLemma structured_intro_example2: forall A B:Prop, A\\/B/\\(B->A)->A.\nProof.\n intros A B [Ha | [Hb Hi]]. \n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/intro.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807406, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6695591613270987}}
{"text": "Require Import ZArith.\nRequire Import NArith.\nRequire Import NAux.\nRequire Export Replace2.\nRequire Import P.\n\nRequire Import Reals.\n\n(* Definition of the opposite for nat *)\nDefinition Natopp := (fun x:nat => 0%nat).\n\n(* Definition of the opposite for N *)\nDefinition Nopp := (fun x:N => 0%N).\n\n(* Auxillary functions for Z *)\n\nDefinition is_Z0 := (Zeq_bool 0).\nDefinition is_Z1 := (Zeq_bool 1).\nDefinition is_Zpos := (Zle_bool 0).\nDefinition is_Zdiv :=\n  fun x y => if Zeq_bool x Z0 then false else Zeq_bool Z0 (Zmod y x).\nDefinition Zgcd :=\n fun x y => (if (is_Zdiv x y) then x else if (is_Zdiv y x) then y else 1%Z).\n\n(* Check if a nat is a number *)\nLtac is_NatCst p :=\n  match p with\n  | O => constr:(true)\n  | S ?p' => is_NatCst p'\n  | _ => constr:(false)\nend.\n\n(* Convert a Z into a nat if it is a number *)\nLtac NatCst t :=\n  match is_NatCst t with\n  | false => constr:(false)\n  | _ => let res := eval compute in (Z_of_nat t) in constr:(res)\nend.\n\n\n(* Check if a number is a positive *)\nLtac is_PCst p :=\n  match p with\n  | xH => constr:(true)\n  | xO ?p' => is_PCst p'\n  | xI ?p' => is_PCst p'\n  | _ => constr:(false)\nend.\n\n(* Check if a N is a number *)\nLtac is_NCst p :=\n  match p with\n  | N0 => constr:(true)\n  | Npos ?p' => is_PCst p'\n  | _ => constr:(false)\nend.\n\n(* Convert a Z into a nat if it is a number *)\nLtac NCst t :=\n  match is_NCst t with\n  | false => constr:(false)\n  | _ => let res := eval compute in (Z_of_N t) in constr:(res)\nend.\n\n(* If a number is an integer return itself otherwise false *)\nLtac ZCst t :=\n  match t with\n  | Z0 => constr:(t)\n  | Zpos ?p => match is_PCst p with\n               | false => constr:(false)\n               | _ => constr:(t)\n               end\n  | Zneg ?p => match is_PCst p with\n               | false => constr:(false)\n               | _ => constr:(t)\n               end\n  | _ => constr:(false)\n  end.\n\n(* Check if a number is an integer *)\nLtac is_ZCst t := match t with\n                | Z0 => constr:(true)\n                | Zpos ?p => is_PCst p\n                | Zneg ?p => is_PCst p\n                | _ => constr:(false) end.\n\n\n(* Turn a positive into a real *)\nFixpoint P2R (z: positive) {struct z}: R :=\n  match z with\n     xH => 1%R\n  | (xO xH) => 2%R\n  | (xI xH) => 3%R\n  | (xO z1) => (2*(P2R z1))%R\n  | (xI z1) => (1+2*(P2R z1))%R\n end.\n\n(* Turn an integer into a real *)\nDefinition Z2R (z: Z): R :=\n  match z with\n     Z0 => 0%R\n  | (Zpos z1) => (P2R z1)%R\n  | (Zneg z1) => (-(P2R z1))%R\n end.\n\n(* Turn a R when possible into a Z *)\nLtac RCst t :=\n  match t with\n   | R0 => constr:(Z0)\n   | R1 => constr:(Zpos xH)\n   | Rplus ?e1 ?e2 =>\n       match (RCst e1) with\n        false => constr:(false)\n      | ?e3 => match (RCst e2) with\n                 false => constr:(false)\n              |  ?e4 =>  eval vm_compute in (Zplus e3  e4)\n              end\n      end\n   | Rminus ?e1 ?e2 =>\n       match (RCst e1) with\n        false => constr:(false)\n      | ?e3 => match (RCst e2) with\n                 false => constr:(false)\n              |  ?e4 => eval vm_compute in (Zminus e3  e4)\n              end\n      end\n   | Rmult ?e1 ?e2 =>\n       match (RCst e1) with\n        false => constr:(false)\n      | ?e3 => match (RCst e2) with\n                 false => constr:(false)\n              |  ?e4 => eval vm_compute in (Zmult e3  e4)\n              end\n      end\n   | Ropp ?e1 =>\n       match (RCst e1) with\n        false => constr:(false)\n      | ?e3 => eval vm_compute in (Z.opp e3)\n      end\n   | IZR ?e1 =>\n       match (ZCst e1) with\n        false => constr:(false)\n      | ?e3 => e3\n      end\n\n   | _ => constr:(false)\n end.\n\n\n(* Remove the Z.abs_nat of a number, unfortunately stops at\n   the first Z.abs_nat x where x is not a number *)\n\nLtac clean_zabs term :=\n  match term with\n   context id [(Z.abs_nat ?X)] =>\n     match is_ZCst X with\n       true =>\n         let x := eval vm_compute in (Z.abs_nat X) in\n         let y := context id [x] in\n           clean_zabs y\n     | false => term\n     end\n    | _ => term\n  end.\n\n(* Remove the Z.abs_N of a number, unfortunately stops at\n   the first Z.abs_nat x where x is not a number *)\n\nLtac clean_zabs_N term :=\n  match term with\n   context id [(Z.abs_N ?X)] =>\n     match is_ZCst X with\n       true =>\n         let x := eval vm_compute in (Z.abs_N X) in\n         let y := context id [x] in\n           clean_zabs_N y\n     | false => term\n     end\n    | _ => term\n  end.\n\n(* Equality test for Ltac *)\n\nLtac eqterm t1 t2 :=\n  match constr:((t1,t2)) with (?X, ?X) => true | _ => false end.\n\n(* For replace *)\n\nTheorem trans_equal_r : forall (A: Set) (x y z:A), y = z -> x = y -> x = z.\nintros; apply trans_equal with y; auto.\nQed.\n\n(* Theorems for nat *)\n\nOpen Scope nat_scope.\n\nTheorem plus_eq_compat_l: forall a b c, b = c -> a + b = a + c.\nintros; apply f_equal2 with (f := plus); auto.\nQed.\n\nTheorem plus_neg_compat_l: forall a b c, b <> c -> a + b <> a + c.\nintros a b c H H1; case H.\napply plus_reg_l with a; auto.\nQed.\n\nTheorem plus_ge_compat_l: forall n m p : nat, n >= m -> p + n >= p + m.\nintros n m p H; unfold ge; apply plus_le_compat_l; auto.\nQed.\n\nTheorem plus_neg_reg_l: forall a b c,  a + b <> a + c -> b <> c.\nintros a b c H H1; case H; subst; auto.\nQed.\n\nTheorem plus_ge_reg_l: forall n m p : nat, p + n >= p + m -> n >= m.\nintros n m p H; unfold ge; apply plus_le_reg_l with p; auto.\nQed.\n\n(* For replace *)\nTheorem eq_lt_trans_l : forall x y z, (x = z) -> (x < y) -> (z < y).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_lt_trans_r : forall x y z, (y = z) -> (x < y) -> (x < z).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_gt_trans_l : forall x y z, (x = z) -> (x > y) -> (z > y).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_gt_trans_r : forall x y z, (y = z) -> (x > y) -> (x > z).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_le_trans_l : forall x y z, (x = z) -> (x <= y) -> (z <= y).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_le_trans_r : forall x y z, (y = z) -> (x <= y) -> (x <= z).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_ge_trans_l : forall x y z, (x = z) -> (x >= y) -> (z >= y).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_ge_trans_r : forall x y z, (y = z) -> (x >= y) -> (x >= z).\nintros x y z H; rewrite H; auto.\nQed.\n\nTheorem ge_trans: forall x y z, (x >= z) -> (z >= y) -> (x >= y).\nintros x y z H1 H2; red; apply le_trans with z; auto.\nQed.\n\nClose Scope nat_scope.\n\n(* Theorems for N *)\n\nOpen Scope N_scope.\n\nTheorem Nplus_eq_compat_l: forall a b c, b = c -> a + b = a + c.\nintros; apply f_equal2 with (f:= Nplus); auto.\nQed.\n\nTheorem Nplus_neg_compat_l: forall a b c, b <> c -> a + b <> a + c.\nintros a b c H1 H2; case H1.\napply Nplus_reg_l with a; auto.\nQed.\n\nTheorem Nplus_lt_compat_l: forall n m p, n < m -> p + n < p + m.\nintros; to_nat; auto with arith.\nQed.\n\nTheorem Nplus_gt_compat_l: forall n m p, n > m -> p + n > p + m.\nintros; to_nat; auto with arith.\nQed.\n\nTheorem Nplus_le_compat_l: forall n m p, n <= m -> p + n <= p + m.\nintros; to_nat; auto with arith.\nQed.\n\nTheorem Nplus_ge_compat_l: forall n m p, n >= m -> p + n >= p + m.\nintros; to_nat; auto with arith.\nQed.\n\nTheorem Nplus_neg_reg_l: forall a b c,  a + b <> a + c -> b <> c.\nintros a b c H H1; case H; apply f_equal2 with (f:= Nplus); auto.\nQed.\n\nTheorem Nplus_lt_reg_l: forall n m p, p + n < p + m -> n < m.\nintros; to_nat; apply plus_lt_reg_l with nn1; auto with arith.\nQed.\n\nTheorem Nplus_gt_reg_l: forall n m p, p + n > p + m -> n > m.\nintros; to_nat; apply plus_gt_reg_l with nn1; auto with arith.\nQed.\n\nTheorem Nplus_le_reg_l: forall n m p, p + n <= p + m -> n <= m.\nintros; to_nat; apply plus_le_reg_l with nn1; auto with arith.\nQed.\n\nTheorem Nplus_ge_reg_l: forall n m p, p + n >= p + m -> n >= m.\nintros; to_nat; apply plus_ge_reg_l with nn1; auto with arith.\nQed.\n\n(* For replace *)\nTheorem Neq_lt_trans_l : forall x y z, (x = z) -> (x < y) -> (z < y).\nintros; subst; auto.\nQed.\n\nTheorem Neq_lt_trans_r : forall x y z, (y = z) -> (x < y) -> (x < z).\nintros; subst; auto.\nQed.\n\nTheorem Neq_gt_trans_l : forall x y z, (x = z) -> (x > y) -> (z > y).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem Neq_gt_trans_r : forall x y z, (y = z) -> (x > y) -> (x > z).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem Neq_le_trans_l : forall x y z, (x = z) -> (x <= y) -> (z <= y).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem Neq_le_trans_r : forall x y z, (y = z) -> (x <= y) -> (x <= z).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem Neq_ge_trans_l : forall x y z, (x = z) -> (x >= y) -> (z >= y).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem Neq_ge_trans_r : forall x y z, (y = z) -> (x >= y) -> (x >= z).\nintros x y z H; rewrite H; auto.\nQed.\n\nTheorem Nge_trans: forall x y z, (x >= z) -> (z >= y) -> (x >= y).\nintros; to_nat; red; apply le_trans with nn1; auto with arith.\nQed.\n\nClose Scope N_scope.\n\n(* Theorems for Z *)\n\nOpen Scope Z_scope.\n\nTheorem Zplus_eq_compat_l: forall a b c:Z, (b = c -> a + b = a + c)%Z.\nintros; apply f_equal2 with (f := Zplus); auto.\nQed.\n\nTheorem Zplus_neg_compat_l: forall a b c: Z, (b <> c -> a + b <> a + c)%Z.\nintros a b c H H1; case H.\napply Zplus_reg_l with a; auto.\nQed.\n\nTheorem Zplus_ge_compat_l: forall n m p : Z, (n >= m -> p + n >= p + m)%Z.\nintros n m p H; apply Z.le_ge; apply Zplus_le_compat_l; auto; apply Z.ge_le; auto.\nQed.\n\nTheorem Zplus_neg_reg_l: forall a b c: Z,  (a + b <> a + c -> b <> c)%Z.\nintros a b c H H1; case H; subst; auto.\nQed.\n\nTheorem Zplus_ge_reg_l: forall n m p : Z, (p + n >= p + m -> n >= m)%Z.\nintros n m p H; apply Z.le_ge; apply Zplus_le_reg_l with p; auto; apply Z.ge_le; auto.\nQed.\n\n(* Theorems to simplify the goal 0 ? x * y and x * y ? 0 where ? is < > <= >= *)\n\nTheorem Zle_sign_pos_pos: forall x y: Z, (0 <= x -> 0 <= y  -> 0 <= x * y)%Z.\nauto with zarith.\nQed.\n\nTheorem Zle_sign_neg_neg: forall x y: Z, (x <= 0 -> y <= 0  -> 0 <= x * y)%Z.\nintros x y H1 H2; replace (x * y)%Z with (-x * -y)%Z; auto with zarith; ring.\nQed.\n\nTheorem Zopp_le: forall n m, (m <= n -> -n <= -m)%Z.\nauto with zarith.\nQed.\n\nTheorem Zle_pos_neg: forall x, (0 <= -x -> x <= 0)%Z.\nauto with zarith.\nQed.\n\nTheorem Zle_sign_pos_neg: forall x y: Z, (0 <= x -> y <= 0  -> x * y <= 0)%Z.\nintros x y H1 H2; apply Zle_pos_neg; replace (- (x * y))%Z with (x * (- y))%Z; auto with zarith; ring.\nQed.\n\nTheorem Zle_sign_neg_pos: forall x y: Z, (x <= 0 -> 0 <= y  -> x * y <= 0)%Z.\nintros x y H1 H2; apply Zle_pos_neg; replace (- (x * y))%Z with (-x * y)%Z; auto with zarith; ring.\nQed.\n\n\nTheorem Zlt_sign_pos_pos: forall x y: Z, (0 < x -> 0 < y  -> 0 < x * y)%Z.\nintros; apply Zmult_lt_O_compat; auto with zarith.\nQed.\n\nTheorem Zlt_sign_neg_neg: forall x y: Z, (x < 0 -> y < 0  -> 0 < x * y)%Z.\nintros x y H1 H2; replace (x * y)%Z with (-x * -y)%Z; auto with zarith; try ring.\napply Zmult_lt_O_compat; auto with zarith.\nQed.\n\nTheorem Zlt_pos_neg: forall x, (0 < -x -> x < 0)%Z.\nauto with zarith.\nQed.\n\nTheorem Zlt_sign_pos_neg: forall x y: Z, (0 < x -> y < 0  -> x * y < 0)%Z.\nintros x y H1 H2; apply Zlt_pos_neg; replace (- (x * y))%Z with (x * (- y))%Z; auto with zarith; try ring.\napply Zmult_lt_O_compat; auto with zarith.\nQed.\n\nTheorem Zlt_sign_neg_pos: forall x y: Z, (x < 0 -> 0 < y  -> x * y < 0)%Z.\nintros x y H1 H2; apply Zlt_pos_neg; replace (- (x * y))%Z with (-x * y)%Z; auto with zarith; try ring.\napply Zmult_lt_O_compat; auto with zarith.\nQed.\n\nTheorem Zge_sign_neg_neg: forall x y: Z, (0 >= x -> 0 >= y  -> x * y >= 0)%Z.\nintros; apply Z.le_ge; apply Zle_sign_neg_neg; auto with zarith.\nQed.\n\nTheorem Zge_sign_pos_pos: forall x y: Z, (x >= 0 -> y >= 0  -> x * y >= 0)%Z.\nintros; apply Z.le_ge; apply Zle_sign_pos_pos; auto with zarith.\nQed.\n\nTheorem Zge_neg_pos: forall x, (0 >= -x -> x >= 0)%Z.\nauto with zarith.\nQed.\n\nTheorem Zge_sign_neg_pos: forall x y: Z, (0 >= x -> y >= 0  -> 0>= x * y)%Z.\nintros; apply Z.le_ge; apply Zle_sign_neg_pos; auto with zarith.\nQed.\n\nTheorem Zge_sign_pos_neg: forall x y: Z, (x >= 0 -> 0 >= y  -> 0 >= x * y)%Z.\nintros; apply Z.le_ge; apply Zle_sign_pos_neg; auto with zarith.\nQed.\n\n\nTheorem Zgt_sign_neg_neg: forall x y: Z, (0 > x -> 0 > y  -> x * y > 0)%Z.\nintros; apply Z.lt_gt; apply Zlt_sign_neg_neg; auto with zarith.\nQed.\n\nTheorem Zgt_sign_pos_pos: forall x y: Z, (x > 0 -> y > 0  -> x * y > 0)%Z.\nintros; apply Z.lt_gt; apply Zlt_sign_pos_pos; auto with zarith.\nQed.\n\nTheorem Zgt_neg_pos: forall x, (0 > -x -> x > 0)%Z.\nauto with zarith.\nQed.\n\nTheorem Zgt_sign_neg_pos: forall x y: Z, (0 > x -> y > 0  -> 0> x * y)%Z.\nintros; apply Z.lt_gt; apply Zlt_sign_neg_pos; auto with zarith.\nQed.\n\nTheorem Zgt_sign_pos_neg: forall x y: Z, (x > 0 -> 0 > y  -> 0 > x * y)%Z.\nintros; apply Z.lt_gt; apply Zlt_sign_pos_neg; auto with zarith.\nQed.\n\n(* Theorems to simplify the hyp 0 ? x * y and x * y ? 0 where ? is < > <= >= *)\n\nTheorem Zle_sign_pos_pos_rev: forall x y: Z, (0 < x -> 0 <= x * y -> 0 <= y)%Z.\nintros x y H1 H2; case (Zle_or_lt 0 y); auto with zarith.\nintros H3; absurd (0 <= x * y)%Z; auto with zarith.\napply Zlt_not_le;apply Zlt_sign_pos_neg; auto.\nQed.\n\nTheorem Zle_sign_neg_neg_rev: forall x y: Z, (x < 0 -> 0 <= x * y ->  y <= 0)%Z.\nintros x y H1 H2; case (Zle_or_lt y  0); auto with zarith.\nintros H3; absurd (0 <= x * y)%Z; auto with zarith.\napply Zlt_not_le;apply Zlt_sign_neg_pos; auto.\nQed.\n\nTheorem Zle_sign_pos_neg_rev: forall x y: Z, (0 < x -> x * y <= 0 -> y <= 0)%Z.\nintros x y H1 H2; case (Zle_or_lt y 0); auto with zarith.\nintros H3; absurd (x * y <= 0)%Z; auto with zarith.\napply Zlt_not_le;apply Zlt_sign_pos_pos; auto.\nQed.\n\nTheorem Zle_sign_neg_pos_rev: forall x y: Z, (x < 0 -> x * y <= 0 ->  0 <= y)%Z.\nintros x y H1 H2; case (Zle_or_lt 0 y); auto with zarith.\nintros H3; absurd (x * y <= 0)%Z; auto with zarith.\napply Zlt_not_le;apply Zlt_sign_neg_neg; auto.\nQed.\n\nTheorem Zge_sign_pos_pos_rev: forall x y: Z, (x > 0 -> x * y >= 0 -> y >= 0)%Z.\nintros x y H1 H2; apply Z.le_ge; apply Zle_sign_pos_pos_rev with x; auto with zarith.\nQed.\n\nTheorem Zge_sign_neg_neg_rev: forall x y: Z, (0 > x -> x * y  >= 0->  0 >= y)%Z.\nintros x y H1 H2; apply Z.le_ge; apply Zle_sign_neg_neg_rev with x; auto with zarith.\nQed.\n\nTheorem Zge_sign_pos_neg_rev: forall x y: Z, (x > 0 -> 0 >= x * y -> 0 >= y)%Z.\nintros x y H1 H2; apply Z.le_ge; apply Zle_sign_pos_neg_rev with x; auto with zarith.\nQed.\n\nTheorem Zge_sign_neg_pos_rev: forall x y: Z, (0 > x -> 0 >= x * y ->  y >= 0)%Z.\nintros x y H1 H2; apply Z.le_ge; apply Zle_sign_neg_pos_rev with x; auto with zarith.\nQed.\n\nTheorem Zlt_sign_pos_pos_rev: forall x y: Z, (0 < x -> 0 < x * y -> 0 < y)%Z.\nintros x y H1 H2; case (Zle_or_lt y 0); auto with zarith.\nintros H3; absurd (0 < x * y)%Z; auto with zarith.\napply Zle_not_lt;apply Zle_sign_pos_neg; auto with zarith.\nQed.\n\nTheorem Zlt_sign_neg_neg_rev: forall x y: Z, (x < 0 -> 0 < x * y ->  y < 0)%Z.\nintros x y H1 H2; case (Zle_or_lt 0 y); auto with zarith.\nintros H3; absurd (0 < x * y)%Z; auto with zarith.\napply Zle_not_lt;apply Zle_sign_neg_pos; auto with zarith.\nQed.\n\nTheorem Zlt_sign_pos_neg_rev: forall x y: Z, (0 < x -> x * y < 0 -> y < 0)%Z.\nintros x y H1 H2; case (Zle_or_lt 0 y); auto with zarith.\nintros H3; absurd (x * y < 0)%Z; auto with zarith.\napply Zle_not_lt;apply Zle_sign_pos_pos; auto with zarith.\nQed.\n\nTheorem Zlt_sign_neg_pos_rev: forall x y: Z, (x < 0 -> x * y < 0 ->  0 < y)%Z.\nintros x y H1 H2; case (Zle_or_lt y 0); auto with zarith.\nintros H3; absurd (x * y < 0)%Z; auto with zarith.\napply Zle_not_lt;apply Zle_sign_neg_neg; auto with zarith.\nQed.\n\nTheorem Zgt_sign_pos_pos_rev: forall x y: Z, (x > 0 -> x * y > 0 -> y > 0)%Z.\nintros x y H1 H2; apply Z.lt_gt; apply Zlt_sign_pos_pos_rev with x; auto with zarith.\nQed.\n\nTheorem Zgt_sign_neg_neg_rev: forall x y: Z, (0 > x -> x * y  > 0->  0 > y)%Z.\nintros x y H1 H2; apply Z.lt_gt; apply Zlt_sign_neg_neg_rev with x; auto with zarith.\nQed.\n\nTheorem Zgt_sign_pos_neg_rev: forall x y: Z, (x > 0 -> 0 > x * y -> 0 > y)%Z.\nintros x y H1 H2; apply Z.lt_gt; apply Zlt_sign_pos_neg_rev with x; auto with zarith.\nQed.\n\nTheorem Zgt_sign_neg_pos_rev: forall x y: Z, (0 > x -> 0 > x * y ->  y > 0)%Z.\nintros x y H1 H2; apply Z.lt_gt; apply Zlt_sign_neg_pos_rev with x; auto with zarith.\nQed.\n\n(* Theorem to simplify x * y ? x * z where ? is < > <= >= *)\n\nTheorem Zmult_le_neg_compat_l:\n  forall n m p : Z, (m <= n)%Z -> (p <= 0)%Z -> (p * n <= p * m)%Z.\nintros n m p H1 H2; replace (p * n)%Z with (-(-p * n))%Z; auto with zarith; try ring.\nreplace (p * m)%Z with (-(-p * m))%Z; auto with zarith; try ring.\napply Zopp_le; apply Zmult_le_compat_l; auto with zarith.\nQed.\n\nTheorem Zopp_lt: forall n m, (m < n -> -n < -m)%Z.\nauto with zarith.\nQed.\n\nTheorem Zmult_lt_neg_compat_l:\n  forall n m p : Z, (m < n)%Z -> (p < 0)%Z -> (p * n < p * m)%Z.\nintros n m p H1 H2; replace (p * n)%Z with (-(-p * n))%Z; auto with zarith; try ring.\nreplace (p * m)%Z with (-(-p * m))%Z; auto with zarith; try ring.\napply Zopp_lt; apply Zmult_lt_compat_l; auto with zarith.\nQed.\n\nTheorem Zopp_ge: forall n m, (m >= n -> -n >= -m)%Z.\nauto with zarith.\nQed.\n\nTheorem Zmult_ge_neg_compat_l:\n  forall n m p : Z, (m >= n)%Z -> (0 >= p)%Z -> (p * n >= p * m)%Z.\nintros n m p H1 H2; replace (p * n)%Z with (-(-p * n))%Z; auto with zarith; try ring.\nreplace (p * m)%Z with (-(-p * m))%Z; auto with zarith; try ring.\napply Zopp_ge; apply Zmult_ge_compat_l; auto with zarith.\nQed.\n\nTheorem Zopp_gt: forall n m, (m > n -> -n > -m)%Z.\nauto with zarith.\nQed.\n\nTheorem Zmult_gt_neg_compat_l:\n  forall n m p : Z, (m > n)%Z -> (0 > p)%Z -> (p * n > p * m)%Z.\nintros n m p H1 H2; replace (p * n)%Z with (-(-p * n))%Z; auto with zarith; try ring.\nreplace (p * m)%Z with (-(-p * m))%Z; auto with zarith; try ring.\napply Zopp_gt; apply Zmult_gt_compat_l; auto with zarith.\nQed.\n\n\n(* Theorem to simplify a hyp x * y ? x * z where ? is < > <= >= *)\n\n\nTheorem Zmult_le_compat_l_rev:\n  forall n m p : Z, (0 < p)%Z -> (p * n <= p * m)%Z -> (n <= m)%Z.\nintros n m p H H1; case (Zle_or_lt n m); auto; intros H2.\nabsurd (p * n <= p * m)%Z; auto with zarith.\napply Zlt_not_le; apply Zmult_lt_compat_l; auto.\nQed.\n\nTheorem Zmult_le_neg_compat_l_rev:\n  forall n m p : Z, (p < 0)%Z -> (p * n <= p * m)%Z -> (m <= n)%Z.\nintros n m p H H1; case (Zle_or_lt m n); auto; intros H2.\nabsurd (p * n <= p * m)%Z; auto with zarith.\napply Zlt_not_le; apply Zmult_lt_neg_compat_l; auto.\nQed.\n\nTheorem Zmult_lt_compat_l_rev:\n  forall n m p : Z, (0 < p)%Z -> (p * n < p * m)%Z -> (n < m)%Z.\nintros n m p H H1; case (Zle_or_lt m n); auto; intros H2.\nabsurd (p * n < p * m)%Z; auto with zarith.\napply Zle_not_lt; apply Zmult_le_compat_l; auto with zarith.\nQed.\n\nTheorem Zmult_lt_neg_compat_l_rev:\n  forall n m p : Z, (p < 0)%Z -> (p * n < p * m)%Z -> (m < n)%Z.\nintros n m p H H1; case (Zle_or_lt n m); auto; intros H2.\nabsurd (p * n < p * m)%Z; auto with zarith.\napply Zle_not_lt; apply Zmult_le_neg_compat_l; auto with zarith.\nQed.\n\nTheorem Zmult_ge_compat_l_rev:\n  forall n m p : Z, (p > 0)%Z -> (p * n >= p * m)%Z -> (n >= m)%Z.\nintros n m p H H1;\n apply Z.le_ge; apply Zmult_le_compat_l_rev with p; auto with zarith.\nQed.\n\nTheorem Zmult_ge_neg_compat_l_rev:\n  forall n m p : Z, (0 > p)%Z -> (p * n >= p * m)%Z -> (m >= n)%Z.\nintros n m p H H1;\n apply Z.le_ge; apply Zmult_le_neg_compat_l_rev with p; auto with zarith.\nQed.\n\nTheorem Zmult_gt_compat_l_rev:\n  forall n m p : Z, (p > 0)%Z -> (p * n > p * m)%Z -> (n > m)%Z.\nintros n m p H H1;\n apply Z.lt_gt; apply Zmult_lt_compat_l_rev with p; auto with zarith.\nQed.\n\nTheorem Zmult_gt_neg_compat_l_rev:\n  forall n m p : Z, (0 > p)%Z -> (p * n > p * m)%Z -> (m > n)%Z.\nintros n m p H H1;\n apply Z.lt_gt; apply Zmult_lt_neg_compat_l_rev with p; auto with zarith.\nQed.\n\n(* For replace *)\n\nTheorem eq_Zlt_trans_l : forall x y z, (x = z) -> (x < y) -> (z < y).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_Zlt_trans_r : forall x y z, (y = z) -> (x < y) -> (x < z).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_Zgt_trans_l : forall x y z, (x = z) -> (x > y) -> (z > y).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_Zgt_trans_r : forall x y z, (y = z) -> (x > y) -> (x > z).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_Zle_trans_l : forall x y z, (x = z) -> (x <= y) -> (z <= y).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_Zle_trans_r : forall x y z, (y = z) -> (x <= y) -> (x <= z).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_Zge_trans_l : forall x y z, (x = z) -> (x >= y) -> (z >= y).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_Zge_trans_r : forall x y z, (y = z) -> (x >= y) -> (x >= z).\nintros x y z H; rewrite H; auto.\nQed.\n\nTheorem Zge_trans: forall x y z, (x >= z) -> (z >= y) -> (x >= y).\nintros x y z H1 H2; red; apply Zge_trans with z; auto.\nQed.\n\nClose Scope Z_scope.\n\n(* Theorems for R *)\n\nOpen Scope R_scope.\n\nTheorem Rplus_eq_compat_l: forall a b c:R, (b = c -> a + b = a + c)%R.\nintros; apply f_equal2 with (f := Rplus); auto.\nQed.\n\nTheorem Rplus_neg_compat_l: forall a b c: R, (b <> c -> a + b <> a + c)%R.\nintros a b c H H1; case H.\napply Rplus_eq_reg_l with a; auto.\nQed.\n\nTheorem Rplus_ge_compat_l: forall n m p : R, (n >= m -> p + n >= p + m)%R.\nintros n m p H; apply Rle_ge; apply Rplus_le_compat_l; auto; apply Rge_le; auto.\nQed.\n\nTheorem Rplus_neg_reg_l: forall a b c: R,  (a + b <> a + c -> b <> c)%R.\nintros a b c H H1; case H; subst; auto.\nQed.\n\nTheorem Rplus_ge_reg_l: forall n m p : R, (p + n >= p + m -> n >= m)%R.\nintros n m p H; apply Rle_ge; apply Rplus_le_reg_l with p; auto; apply Rge_le; auto.\nQed.\n\n(* Theorems to simplify the goal 0 ? x * y and x * y ? 0 where ? is < > <= >= *)\n\nTheorem Rle_sign_pos_pos: forall x y, (0 <= x -> 0 <= y  -> 0 <= x * y)%R.\nintros x y H; apply Rmult_le_pos; auto with real.\nQed.\n\nTheorem Rle_sign_neg_neg: forall x y, (x <= 0 -> y <= 0  -> 0 <= x * y)%R.\nintros x y H1 H2; replace (x * y)%R with (-x * -y)%R; auto with real; try ring.\napply Rmult_le_pos; auto with real.\nQed.\n\nTheorem Rle_pos_neg: forall x, (0 <= -x -> x <= 0)%R.\nintros x H; rewrite <- (Ropp_involutive 0);  rewrite <- (Ropp_involutive x); auto with real.\napply Ropp_le_contravar; auto with real.\nrewrite Ropp_0; auto with real.\nQed.\n\nTheorem Rle_sign_pos_neg: forall x y: R, (0 <= x -> y <= 0  -> x * y <= 0)%R.\nintros x y H1 H2; apply Rle_pos_neg; replace (- (x * y))%R with (x * (- y))%R; auto with real; try ring.\napply Rmult_le_pos; auto with real.\nQed.\n\nTheorem Rle_sign_neg_pos: forall x y, (x <= 0 -> 0 <= y  -> x * y <= 0)%R.\nintros x y H1 H2; apply Rle_pos_neg; replace (- (x * y))%R with (-x * y)%R; auto with real; try ring.\napply Rmult_le_pos; auto with real.\nQed.\n\nTheorem Rlt_sign_pos_pos: forall x y, (0 < x -> 0 < y  -> 0 < x * y)%R.\nintros; apply Rmult_lt_0_compat; auto with real.\nQed.\n\nTheorem Rlt_sign_neg_neg: forall x y, (x < 0 -> y < 0  -> 0 < x * y)%R.\nintros x y H1 H2; replace (x * y)%R with (-x * -y)%R; auto with real; try ring.\napply Rmult_lt_0_compat; auto with real.\nQed.\n\nTheorem Rlt_pos_neg: forall x, (0 < -x -> x < 0)%R.\nintros x H; rewrite <- (Ropp_involutive 0);  rewrite <- (Ropp_involutive x); auto with real.\napply Ropp_lt_contravar; auto with real.\nrewrite Ropp_0; auto with real.\nQed.\n\nTheorem Rlt_sign_pos_neg: forall x y, (0 < x -> y < 0  -> x * y < 0)%R.\nintros x y H1 H2; apply Rlt_pos_neg; replace (- (x * y))%R with (x * (- y))%R; auto with real; try ring.\napply Rmult_lt_0_compat; auto.\nreplace 0%R with (-0)%R; auto with real.\nQed.\n\nTheorem Rlt_sign_neg_pos: forall x y, (x < 0 -> 0 < y  -> x * y < 0)%R.\nintros x y H1 H2; apply Rlt_pos_neg; replace (- (x * y))%R with (-x * y)%R; auto with real; try ring.\napply Rmult_lt_0_compat; auto with real.\nQed.\n\n\n\nTheorem Rge_sign_neg_neg: forall x y, (0 >= x -> 0 >= y  -> x * y >= 0)%R.\nintros; apply Rle_ge; apply Rle_sign_neg_neg; auto with real.\nQed.\n\nTheorem Rge_sign_pos_pos: forall x y, (x >= 0 -> y >= 0  -> x * y >= 0)%R.\nintros; apply Rle_ge; apply Rle_sign_pos_pos; auto with real.\nQed.\n\nTheorem Rge_neg_pos: forall x, (0 >= -x -> x >= 0)%R.\nintros x H; rewrite <- (Ropp_involutive 0);  rewrite <- (Ropp_involutive x); auto with real.\napply Rle_ge;apply Ropp_le_contravar; auto with real.\nrewrite Ropp_0; auto with real.\nQed.\n\nTheorem Rge_sign_neg_pos: forall x y: R, (0 >= x -> y >= 0  -> 0>= x * y)%R.\nintros; apply Rle_ge; apply Rle_sign_neg_pos; auto with real.\nQed.\n\nTheorem Rge_sign_pos_neg: forall x y, (x >= 0 -> 0 >= y  -> 0 >= x * y)%R.\nintros; apply Rle_ge; apply Rle_sign_pos_neg; auto with real.\nQed.\n\n\nTheorem Rgt_sign_neg_neg: forall x y, (0 > x -> 0 > y  -> x * y > 0)%R.\nintros; red;  apply Rlt_sign_neg_neg; auto with real.\nQed.\n\nTheorem Rgt_sign_pos_pos: forall x y, (x > 0 -> y > 0  -> x * y > 0)%R.\nintros; red; apply Rlt_sign_pos_pos; auto with real.\nQed.\n\nTheorem Rgt_neg_pos: forall x, (0 > -x -> x > 0)%R.\nintros x H; rewrite <- (Ropp_involutive 0);  rewrite <- (Ropp_involutive x); auto with real.\nred;apply Ropp_lt_contravar; auto with real.\nrewrite Ropp_0; auto with real.\nQed.\n\nTheorem Rgt_sign_neg_pos: forall x y, (0 > x -> y > 0  -> 0> x * y)%R.\nintros; red; apply Rlt_sign_neg_pos; auto with real.\nQed.\n\nTheorem Rgt_sign_pos_neg: forall x y, (x > 0 -> 0 > y  -> 0 > x * y)%R.\nintros; red; apply Rlt_sign_pos_neg; auto with real.\nQed.\n\n(* Theorems to simplify the hyp 0 ? x * y and x * y ? 0 where ? is < > <= >= *)\n\nTheorem Rle_sign_pos_pos_rev: forall x y: R, (0 < x -> 0 <= x * y -> 0 <= y)%R.\nintros x y H1 H2; case (Rle_or_lt 0 y); auto with real.\nintros H3; absurd (0 <= x * y)%R; auto with real.\napply Rlt_not_le;apply Rlt_sign_pos_neg; auto.\nQed.\n\nTheorem Rle_sign_neg_neg_rev: forall x y: R, (x < 0 -> 0 <= x * y ->  y <= 0)%R.\nintros x y H1 H2; case (Rle_or_lt y  0); auto with real.\nintros H3; absurd (0 <= x * y)%R; auto with real.\napply Rlt_not_le;apply Rlt_sign_neg_pos; auto.\nQed.\n\nTheorem Rle_sign_pos_neg_rev: forall x y: R, (0 < x -> x * y <= 0 -> y <= 0)%R.\nintros x y H1 H2; case (Rle_or_lt y 0); auto with real.\nintros H3; absurd (x * y <= 0)%R; auto with real.\napply Rlt_not_le;apply Rlt_sign_pos_pos; auto.\nQed.\n\nTheorem Rle_sign_neg_pos_rev: forall x y: R, (x < 0 -> x * y <= 0 ->  0 <= y)%R.\nintros x y H1 H2; case (Rle_or_lt 0 y); auto with real.\nintros H3; absurd (x * y <= 0)%R; auto with real.\napply Rlt_not_le;apply Rlt_sign_neg_neg; auto.\nQed.\n\nTheorem Rge_sign_pos_pos_rev: forall x y: R, (x > 0 -> x * y >= 0 -> y >= 0)%R.\nintros x y H1 H2; apply Rle_ge; apply Rle_sign_pos_pos_rev with x; auto with real.\nQed.\n\nTheorem Rge_sign_neg_neg_rev: forall x y: R, (0 > x -> x * y  >= 0->  0 >= y)%R.\nintros x y H1 H2; apply Rle_ge; apply Rle_sign_neg_neg_rev with x; auto with real.\nQed.\n\nTheorem Rge_sign_pos_neg_rev: forall x y: R, (x > 0 -> 0 >= x * y -> 0 >= y)%R.\nintros x y H1 H2; apply Rle_ge; apply Rle_sign_pos_neg_rev with x; auto with real.\nQed.\n\nTheorem Rge_sign_neg_pos_rev: forall x y: R, (0 > x -> 0 >= x * y ->  y >= 0)%R.\nintros x y H1 H2; apply Rle_ge; apply Rle_sign_neg_pos_rev with x; auto with real.\nQed.\n\nTheorem Rlt_sign_pos_pos_rev: forall x y: R, (0 < x -> 0 < x * y -> 0 < y)%R.\nintros x y H1 H2; case (Rle_or_lt y 0); auto with real.\nintros H3; absurd (0 < x * y)%R; auto with real.\napply Rle_not_lt;apply Rle_sign_pos_neg; auto with real.\nQed.\n\nTheorem Rlt_sign_neg_neg_rev: forall x y: R, (x < 0 -> 0 < x * y ->  y < 0)%R.\nintros x y H1 H2; case (Rle_or_lt 0 y); auto with real.\nintros H3; absurd (0 < x * y)%R; auto with real.\napply Rle_not_lt;apply Rle_sign_neg_pos; auto with real.\nQed.\n\nTheorem Rlt_sign_pos_neg_rev: forall x y: R, (0 < x -> x * y < 0 -> y < 0)%R.\nintros x y H1 H2; case (Rle_or_lt 0 y); auto with real.\nintros H3; absurd (x * y < 0)%R; auto with real.\napply Rle_not_lt;apply Rle_sign_pos_pos; auto with real.\nQed.\n\nTheorem Rlt_sign_neg_pos_rev: forall x y: R, (x < 0 -> x * y < 0 ->  0 < y)%R.\nintros x y H1 H2; case (Rle_or_lt y 0); auto with real.\nintros H3; absurd (x * y < 0)%R; auto with real.\napply Rle_not_lt;apply Rle_sign_neg_neg; auto with real.\nQed.\n\nTheorem Rgt_sign_pos_pos_rev: forall x y: R, (x > 0 -> x * y > 0 -> y > 0)%R.\nintros x y H1 H2; red; apply Rlt_sign_pos_pos_rev with x; auto with real.\nQed.\n\nTheorem Rgt_sign_neg_neg_rev: forall x y: R, (0 > x -> x * y  > 0->  0 > y)%R.\nintros x y H1 H2; red; apply Rlt_sign_neg_neg_rev with x; auto with real.\nQed.\n\nTheorem Rgt_sign_pos_neg_rev: forall x y: R, (x > 0 -> 0 > x * y -> 0 > y)%R.\nintros x y H1 H2; red; apply Rlt_sign_pos_neg_rev with x; auto with real.\nQed.\n\nTheorem Rgt_sign_neg_pos_rev: forall x y: R, (0 > x -> 0 > x * y ->  y > 0)%R.\nintros x y H1 H2; red; apply Rlt_sign_neg_pos_rev with x; auto with real.\nQed.\n\n(* Theorem to simplify x * y ? x * z where ? is < > <= >= *)\n\nTheorem Rmult_le_compat_l:\n  forall n m p : R, (m <= n)%R -> (0 <= p)%R -> (p * m <= p * n)%R.\nauto with real.\nQed.\n\nTheorem Rmult_le_neg_compat_l:\n  forall n m p : R, (m <= n)%R -> (p <= 0)%R -> (p * n <= p * m)%R.\nintros n m p H1 H2; replace (p * n)%R with (-(-p * n))%R; auto with real; try ring.\nreplace (p * m)%R with (-(-p * m))%R; auto with real; try ring.\nQed.\n\nTheorem Ropp_lt: forall n m, (m < n -> -n < -m)%R.\nauto with real.\nQed.\n\nTheorem Rmult_lt_neg_compat_l:\n  forall n m p : R, (m < n)%R -> (p < 0)%R -> (p * n < p * m)%R.\nintros n m p H1 H2; replace (p * n)%R with (-(-p * n))%R; auto with real; try ring.\nreplace (p * m)%R with (-(-p * m))%R; auto with real; try ring.\nQed.\n\nTheorem Ropp_ge: forall n m, (m >= n -> -n >= -m)%R.\nauto with real.\nQed.\n\nTheorem Rmult_ge_compat_l:\n  forall n m p : R, (m >= n)%R -> (p >= 0)%R -> (p * m >= p * n)%R.\nintros n m p H H1; apply Rle_ge; auto with real.\nQed.\n\nTheorem Rmult_ge_neg_compat_l:\n  forall n m p : R, (m >= n)%R -> (0 >= p)%R -> (p * n >= p * m)%R.\nintros n m p H1 H2; replace (p * n)%R with (-(-p * n))%R; auto with real; try ring.\nreplace (p * m)%R with (-(-p * m))%R; auto with real;try ring.\nQed.\n\nTheorem Ropp_gt: forall n m, (m > n -> -n > -m)%R.\nauto with real.\nQed.\n\nTheorem Rmult_gt_compat_l:\n  forall n m p : R, (n > m)%R -> (p > 0)%R -> (p * n > p * m)%R.\nunfold Rgt; auto with real.\nQed.\n\n\nTheorem Rmult_gt_neg_compat_l:\n  forall n m p : R, (m > n)%R -> (0 > p)%R -> (p * n > p * m)%R.\nintros n m p H1 H2; replace (p * n)%R with (-(-p * n))%R; auto with real; try ring.\nreplace (p * m)%R with (-(-p * m))%R; auto with real; try ring.\nQed.\n\n(* Theorem to simplify a hyp x * y ? x * z where ? is < > <= >= *)\n\n\nTheorem Rmult_le_compat_l_rev:\n  forall n m p : R, (0 < p)%R -> (p * n <= p * m)%R -> (n <= m)%R.\nintros n m p H H1; case (Rle_or_lt n m); auto; intros H2.\nabsurd (p * n <= p * m)%R; auto with real.\napply Rlt_not_le; apply Rmult_lt_compat_l; auto.\nQed.\n\nTheorem Rmult_le_neg_compat_l_rev:\n  forall n m p : R, (p < 0)%R -> (p * n <= p * m)%R -> (m <= n)%R.\nintros n m p H H1; case (Rle_or_lt m n); auto; intros H2.\nabsurd (p * n <= p * m)%R; auto with real.\napply Rlt_not_le; apply Rmult_lt_neg_compat_l; auto.\nQed.\n\nTheorem Rmult_lt_compat_l_rev:\n  forall n m p : R, (0 < p)%R -> (p * n < p * m)%R -> (n < m)%R.\nintros n m p H H1; case (Rle_or_lt m n); auto; intros H2.\nabsurd (p * n < p * m)%R; auto with real.\napply Rle_not_lt; apply Rmult_le_compat_l; auto with real.\nQed.\n\nTheorem Rmult_lt_neg_compat_l_rev:\n  forall n m p : R, (p < 0)%R -> (p * n < p * m)%R -> (m < n)%R.\nintros n m p H H1; case (Rle_or_lt n m); auto; intros H2.\nabsurd (p * n < p * m)%R; auto with real.\napply Rle_not_lt; apply Rmult_le_neg_compat_l; auto with real.\nQed.\n\nTheorem Rmult_ge_compat_l_rev:\n  forall n m p : R, (p > 0)%R -> (p * n >= p * m)%R -> (n >= m)%R.\nintros n m p H H1;\n apply Rle_ge; apply Rmult_le_compat_l_rev with p; auto with real.\nQed.\n\nTheorem Rmult_ge_neg_compat_l_rev:\n  forall n m p : R, (0 > p)%R -> (p * n >= p * m)%R -> (m >= n)%R.\nintros n m p H H1;\n apply Rle_ge; apply Rmult_le_neg_compat_l_rev with p; auto with real.\nQed.\n\nTheorem Rmult_gt_compat_l_rev:\n  forall n m p : R, (p > 0)%R -> (p * n > p * m)%R -> (n > m)%R.\nintros n m p H H1;\n red; apply Rmult_lt_compat_l_rev with p; auto with real.\nQed.\n\nTheorem Rmult_gt_neg_compat_l_rev:\n  forall n m p : R, (0 > p)%R -> (p * n > p * m)%R -> (m > n)%R.\nintros n m p H H1;\n red; apply Rmult_lt_neg_compat_l_rev with p; auto with real.\nQed.\n\n(* For replace *)\n\nTheorem eq_Rlt_trans_l : forall x y z, (x = z) -> (x < y) -> (z < y).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_Rlt_trans_r : forall x y z, (y = z) -> (x < y) -> (x < z).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_Rgt_trans_l : forall x y z, (x = z) -> (x > y) -> (z > y).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_Rgt_trans_r : forall x y z, (y = z) -> (x > y) -> (x > z).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_Rle_trans_l : forall x y z, (x = z) -> (x <= y) -> (z <= y).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_Rle_trans_r : forall x y z, (y = z) -> (x <= y) -> (x <= z).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_Rge_trans_l : forall x y z, (x = z) -> (x >= y) -> (z >= y).\nintros x y z H; rewrite H; auto.\nQed.\nTheorem eq_Rge_trans_r : forall x y z, (y = z) -> (x >= y) -> (x >= z).\nintros x y z H; rewrite H; auto.\nQed.\n\nTheorem Rge_trans: forall x y z, (x >= z) -> (z >= y) -> (x >= y).\nintros x y z H1 H2; red; apply Rge_trans with z; auto.\nQed.\n\n(* For RGroundTac *)\n\n\nTheorem Z2R_correct: forall p, (Z2R p) = (IZR p).\nintros p; case p; auto.\nintros p1; elim p1; auto.\nintros p2 Rec; pattern (Zpos (xI p2)) at 2; replace (Zpos (xI p2)) with (2 * (Zpos p2) +1)%Z; auto with zarith.\nrewrite plus_IZR; rewrite mult_IZR; rewrite <- Rec.\nsimpl Z2R; simpl IZR; case p2; intros; simpl (P2R 1);ring.\nintros p2 Rec; pattern (Zpos (xO p2)) at 2; replace (Zpos (xO p2)) with (2 * (Zpos p2))%Z; auto with zarith.\nrewrite mult_IZR; rewrite <- Rec.\nsimpl Z2R; simpl IZR; case p2; intros; simpl (P2R 1); ring.\nintros p1; elim p1; auto.\nintros p2 Rec; pattern (Zneg (xI p2)) at 2; replace (Zneg (xI p2)) with ((2 * (Zneg p2) +  -1))%Z; auto with zarith.\nrewrite plus_IZR; rewrite mult_IZR; rewrite <- Rec.\nsimpl Z2R; simpl IZR; case p2; intros; simpl (P2R 1); ring.\nintros p2 Rec; pattern (Zneg (xO p2)) at 2; replace (Zneg (xO p2)) with (2 * (Zneg p2))%Z; auto with zarith.\nrewrite mult_IZR; rewrite <- Rec.\nsimpl Z2R; simpl IZR; case p2; intros; simpl (P2R 1); ring.\nQed.\n\nTheorem Z2R_le: forall p q, (p <= q)%Z -> (Z2R p <= Z2R q)%R.\nintros p q; repeat rewrite Z2R_correct; intros; apply IZR_le; auto.\nQed.\n\nTheorem Z2R_lt: forall p q, (p < q)%Z -> (Z2R p < Z2R q)%R.\nintros p q; repeat rewrite Z2R_correct; intros; apply IZR_lt; auto.\nQed.\n\nTheorem Z2R_ge: forall p q, (p >= q)%Z -> (Z2R p >= Z2R q)%R.\nintros p q; repeat rewrite Z2R_correct; intros; apply IZR_ge; auto.\nQed.\n\nTheorem Z2R_gt: forall p q, (p > q)%Z -> (Z2R p > Z2R q)%R.\nintros p q; repeat rewrite Z2R_correct; intros; red; apply IZR_lt;\napply Z.gt_lt; auto.\nQed.\n\nClose Scope R_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/PolTac/PolAux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6695591541370733}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(**********************************************************************\n    Igroup\n\n    Build the group of the inversible elements for the operation\n\n    Definition: ZpGroup\n  **********************************************************************)\nRequire Import ZArith.\nRequire Import Tactic.\nRequire Import Wf_nat.\nRequire Import UList.\nRequire Import ListAux.\nRequire Import FGroup.\n\nOpen Scope Z_scope.\n\nSection IG.\n\nVariable A: Set.\nVariable op: A -> A -> A.\nVariable support: list A.\nVariable e: A.\n\nHypothesis A_dec: forall a b: A, {a = b} + {a <> b}.\nHypothesis support_ulist: ulist support.\nHypothesis e_in_support: In e support.\nHypothesis op_internal: forall a b, In a support -> In b support -> In (op a b) support.\nHypothesis op_assoc: forall a b c, In a support -> In b support -> In c support -> op a (op b c) = op (op a b) c.\nHypothesis e_is_zero_l:  forall a, In a support ->  op e a = a.\nHypothesis e_is_zero_r:  forall a, In a support ->  op a e = a.\n\n(**************************************\n  is_inv_aux tests if there is an inverse of a for op in l\n **************************************)\n\nFixpoint is_inv_aux (l: list A) (a: A) {struct l}: bool :=\n  match l with nil => false | cons b l1 =>\n   if (A_dec (op a b) e) then if (A_dec (op b a) e) then true else is_inv_aux l1 a else is_inv_aux l1 a\n  end.\n\nTheorem is_inv_aux_false: forall b l, (forall a, (In a l) -> op b a <> e \\/  op a b <> e) -> is_inv_aux l b = false.\nintros b l; elim l; simpl; auto.\nintros a l1 Rec H; case (A_dec (op a b) e); case (A_dec (op b a) e); auto.\nintros H1 H2; case (H a); auto; intros H3; case H3; auto.\nQed.\n\n(**************************************\n  is_inv tests if there is an inverse in support\n **************************************)\nDefinition is_inv := is_inv_aux support.\n\n(**************************************\n  isupport_aux returns the sublist of inversible element of support\n **************************************)\n\nFixpoint isupport_aux (l: list A) : list  A :=\n  match l with nil => nil | cons a  l1 => if is_inv a then a::isupport_aux l1 else isupport_aux l1 end.\n\n(**************************************\n  Some properties of isupport_aux\n **************************************)\n\nTheorem isupport_aux_is_inv_true: forall l a, In a (isupport_aux l) -> is_inv a = true.\nintros l a; elim l; simpl; auto.\nintros b l1 H; case_eq (is_inv b); intros H1; simpl; auto.\nintros [H2 | H2]; subst; auto.\nQed.\n\nTheorem isupport_aux_is_in: forall l a,  is_inv a = true -> In a l -> In a (isupport_aux l).\nintros l a; elim l; simpl; auto.\nintros b l1 Rec H [H1 | H1]; subst.\nrewrite H; auto with datatypes.\ncase (is_inv b); auto with datatypes.\nQed.\n\n\nTheorem isupport_aux_not_in:\n  forall b l, (forall a, (In a support) -> op b a <> e \\/  op a b <> e) -> ~ In b (isupport_aux l).\nintros b l; elim l; simpl; simpl; auto.\nintros a l1 H; case_eq (is_inv a); intros H1; simpl; auto.\nintros H2 [H3 | H3]; subst.\ncontradict H1.\nunfold is_inv; rewrite is_inv_aux_false; auto.\ncase H; auto; apply isupport_aux_is_in; auto.\nQed.\n\nTheorem isupport_aux_incl: forall l, incl (isupport_aux l) l.\nintros l; elim l; simpl; auto with datatypes.\nintros a l1 H1; case (is_inv a); auto with datatypes.\nQed.\n\nTheorem isupport_aux_ulist: forall l, ulist l -> ulist (isupport_aux l).\nintros l; elim l; simpl; auto with datatypes.\nintros a l1 H1 H2; case_eq (is_inv a); intros H3; auto with datatypes.\napply ulist_cons; auto with datatypes.\nintros H4; apply (ulist_app_inv _ (a::nil) l1 a); auto with datatypes.\napply (isupport_aux_incl l1 a); auto.\napply H1; apply ulist_app_inv_r with (a:: nil); auto.\napply H1; apply ulist_app_inv_r with (a:: nil); auto.\nQed.\n\n(**************************************\n  isupport is the sublist of inversible element of support\n **************************************)\n\nDefinition isupport := isupport_aux support.\n\n(**************************************\n  Some properties of isupport\n **************************************)\n\nTheorem isupport_is_inv_true: forall a, In a isupport -> is_inv a = true.\nunfold isupport; intros a H; apply isupport_aux_is_inv_true with (1 := H).\nQed.\n\nTheorem isupport_is_in: forall a,  is_inv a = true -> In a support -> In a isupport.\nintros a H H1; unfold isupport; apply isupport_aux_is_in; auto.\nQed.\n\nTheorem isupport_incl: incl isupport support.\nunfold isupport; apply isupport_aux_incl.\nQed.\n\nTheorem isupport_ulist: ulist isupport.\nunfold isupport; apply isupport_aux_ulist.\napply support_ulist.\nQed.\n\nTheorem isupport_length: (length isupport <= length support)%nat.\napply ulist_incl_length.\napply isupport_ulist.\napply isupport_incl.\nQed.\n\nTheorem isupport_length_strict:\n  forall b, (In b support) -> (forall a, (In a support) -> op b a <> e \\/  op a b <> e) ->\n           (length isupport < length support)%nat.\nintros b H H1; apply ulist_incl_length_strict.\napply isupport_ulist.\napply isupport_incl.\nintros H2; case (isupport_aux_not_in b support); auto.\nQed.\n\nFixpoint inv_aux (l: list A) (a: A) {struct l}: A :=\n  match l with nil => e | cons b l1 =>\n   if  A_dec (op a b) e then  if (A_dec (op b a) e) then b else inv_aux l1 a else inv_aux l1 a\n  end.\n\nTheorem inv_aux_prop_r: forall l a, is_inv_aux l a = true -> op a (inv_aux l a) = e.\nintros l a; elim l; simpl.\nintros; discriminate.\nintros b l1 H1; case (A_dec (op a b) e); case (A_dec (op b a) e); intros H3 H4; subst; auto.\nQed.\n\nTheorem inv_aux_prop_l: forall l a, is_inv_aux l a = true -> op (inv_aux l a) a = e.\nintros l a; elim l; simpl.\nintros; discriminate.\nintros b l1 H1; case (A_dec (op a b) e); case (A_dec (op b a) e); intros H3 H4; subst; auto.\nQed.\n\nTheorem inv_aux_inv: forall l a b, op a b = e -> op b a = e ->  (In a l) -> is_inv_aux l b = true.\nintros l a b; elim l; simpl.\nintros  _ _ H; case H.\nintros c l1 Rec H H0 H1; case H1; clear H1; intros H1. subst c.\ncase (A_dec (op b a) e); case (A_dec (op a b) e); auto.\ncase (A_dec (op b c) e); case (A_dec (op c b) e); auto.\nQed.\n\nTheorem inv_aux_in: forall l a,  In (inv_aux l a) l \\/ inv_aux l a = e.\nintros l a; elim l; simpl; auto.\nintros b l1; case (A_dec (op a b) e); case (A_dec (op b a) e); intros _ _ [H1 | H1]; auto.\nQed.\n\n(**************************************\n  The inverse function\n **************************************)\n\nDefinition inv := inv_aux support.\n\n(**************************************\n  Some properties of inv\n **************************************)\n\nTheorem inv_prop_r: forall a, In a isupport -> op a (inv a) = e.\nintros a H; unfold inv; apply inv_aux_prop_r with (l := support).\nchange (is_inv a = true).\napply isupport_is_inv_true; auto.\nQed.\n\nTheorem inv_prop_l: forall a, In a isupport -> op (inv a) a = e.\nintros a H; unfold inv; apply inv_aux_prop_l with (l := support).\nchange (is_inv a = true).\napply isupport_is_inv_true; auto.\nQed.\n\nTheorem is_inv_true: forall a b, op b a = e ->  op a b = e -> (In a support) -> is_inv b = true.\nintros a b H H1 H2; unfold is_inv; apply inv_aux_inv with a; auto.\nQed.\n\nTheorem is_inv_false: forall b, (forall a, (In a support) -> op b a <> e \\/  op a b <> e) -> is_inv b = false.\nintros b H; unfold is_inv; apply is_inv_aux_false; auto.\nQed.\n\nTheorem inv_internal: forall a, In a isupport -> In (inv a) isupport.\nintros a H; apply isupport_is_in.\napply is_inv_true with a; auto.\napply inv_prop_l; auto.\napply inv_prop_r; auto.\napply (isupport_incl a); auto.\ncase (inv_aux_in support a); unfold inv; auto.\nintros H1; rewrite H1; apply e_in_support; auto with zarith.\nQed.\n\n(**************************************\n   We are now ready to build our group\n **************************************)\n\nDefinition IGroup : (FGroup op).\ngeneralize (fun x=> (isupport_incl x)); intros Hx.\napply mkGroup with (s := isupport) (e := e) (i := inv); auto.\napply isupport_ulist.\nintros a b H H1.\nassert (Haii: In (inv a) isupport); try apply  inv_internal; auto.\nassert (Hbii: In (inv b) isupport); try apply  inv_internal; auto.\napply isupport_is_in; auto.\napply is_inv_true with (op (inv b) (inv a)); auto.\nrewrite op_assoc; auto.\nrewrite <- (op_assoc a); auto.\nrewrite inv_prop_r; auto.\nrewrite e_is_zero_r; auto.\napply inv_prop_r; auto.\nrewrite <- (op_assoc (inv b)); auto.\nrewrite  (op_assoc (inv a)); auto.\nrewrite inv_prop_l; auto.\nrewrite e_is_zero_l; auto.\napply inv_prop_l; auto.\napply isupport_is_in; auto.\napply is_inv_true with e; auto.\nintros a H; apply inv_internal; auto.\nintros; apply inv_prop_l; auto.\nintros; apply inv_prop_r; auto.\nDefined.\n\nEnd IG.\n", "meta": {"author": "thery", "repo": "coqprime", "sha": "431d7a66877cbe8688fc8864ef892369401440e1", "save_path": "github-repos/coq/thery-coqprime", "path": "github-repos/coq/thery-coqprime/coqprime-431d7a66877cbe8688fc8864ef892369401440e1/src/Coqprime/PrimalityTest/IGroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6695591515549172}}
{"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(** Power Function *)\n\nRequire Import NZAxioms NZMulOrder.\n\n(** Interface of a power function, then its specification on naturals *)\n\nModule Type Pow (Import A : Typ).\n Parameters Inline pow : t -> t -> t.\nEnd Pow.\n\nModule Type PowNotation (A : Typ)(Import B : Pow A).\n Infix \"^\" := pow.\nEnd PowNotation.\n\nModule Type Pow' (A : Typ) := Pow A <+ PowNotation A.\n\nModule Type NZPowSpec (Import A : NZOrdAxiomsSig')(Import B : Pow' A).\n Declare Instance pow_wd : Proper (eq==>eq==>eq) pow.\n Axiom pow_0_r : forall a, a^0 == 1.\n Axiom pow_succ_r : forall a b, 0<=b -> a^(succ b) == a * a^b.\n Axiom pow_neg_r : forall a b, b<0 -> a^b == 0.\nEnd NZPowSpec.\n\n(** The above [pow_neg_r] specification is useless (and trivially\n   provable) for N. Having it here allows to already derive\n   some slightly more general statements. *)\n\nModule Type NZPow (A : NZOrdAxiomsSig) := Pow A <+ NZPowSpec A.\nModule Type NZPow' (A : NZOrdAxiomsSig) := Pow' A <+ NZPowSpec A.\n\n(** Derived properties of power *)\n\nModule Type NZPowProp\n (Import A : NZOrdAxiomsSig')\n (Import B : NZPow' A)\n (Import C : NZMulOrderProp A).\n\nHint Rewrite pow_0_r pow_succ_r : nz.\n\n(** Power and basic constants *)\n\nLemma pow_0_l : forall a, 0<a -> 0^a == 0.\nProof.\n intros a Ha.\n destruct (lt_exists_pred _ _ Ha) as (a' & EQ & Ha').\n rewrite EQ. now nzsimpl.\nQed.\n\nLemma pow_0_l' : forall a, a~=0 -> 0^a == 0.\nProof.\n intros a Ha.\n destruct (lt_trichotomy a 0) as [LT|[EQ|GT]]; try order.\n now rewrite pow_neg_r.\n now apply pow_0_l.\nQed.\n\nLemma pow_1_r : forall a, a^1 == a.\nProof.\n intros. now nzsimpl'.\nQed.\n\nLemma pow_1_l : forall a, 0<=a -> 1^a == 1.\nProof.\n apply le_ind; intros. solve_proper.\n now nzsimpl.\n now nzsimpl.\nQed.\n\nHint Rewrite pow_1_r pow_1_l : nz.\n\nLemma pow_2_r : forall a, a^2 == a*a.\nProof.\n intros. rewrite two_succ. nzsimpl; order'.\nQed.\n\nHint Rewrite pow_2_r : nz.\n\n(** Power and nullity *)\n\nLemma pow_eq_0 : forall a b, 0<=b -> a^b == 0 -> a == 0.\nProof.\n intros a b Hb. apply le_ind with (4:=Hb).\n solve_proper.\n rewrite pow_0_r. order'.\n clear b Hb. intros b Hb IH.\n rewrite pow_succ_r by trivial.\n intros H. apply eq_mul_0 in H. destruct H; trivial.\n now apply IH.\nQed.\n\nLemma pow_nonzero : forall a b, a~=0 -> 0<=b -> a^b ~= 0.\nProof.\n intros a b Ha Hb. contradict Ha. now apply pow_eq_0 with b.\nQed.\n\nLemma pow_eq_0_iff : forall a b, a^b == 0 <-> b<0 \\/ (0<b /\\ a==0).\nProof.\n intros a b. split.\n intros H.\n destruct (lt_trichotomy b 0) as [Hb|[Hb|Hb]].\n now left.\n rewrite Hb, pow_0_r in H; order'.\n right. split; trivial. apply pow_eq_0 with b; order.\n intros [Hb|[Hb Ha]]. now rewrite pow_neg_r.\n rewrite Ha. apply pow_0_l'. order.\nQed.\n\n(** Power and addition, multiplication *)\n\nLemma pow_add_r : forall a b c, 0<=b -> 0<=c ->\n  a^(b+c) == a^b * a^c.\nProof.\n intros a b c Hb. apply le_ind with (4:=Hb). solve_proper.\n now nzsimpl.\n clear b Hb. intros b Hb IH Hc.\n nzsimpl; trivial.\n rewrite IH; trivial. apply mul_assoc.\n now apply add_nonneg_nonneg.\nQed.\n\nLemma pow_mul_l : forall a b c,\n  (a*b)^c == a^c * b^c.\nProof.\n intros a b c.\n destruct (lt_ge_cases c 0) as [Hc|Hc].\n rewrite !(pow_neg_r _ _ Hc). now nzsimpl.\n apply le_ind with (4:=Hc). solve_proper.\n now nzsimpl.\n clear c Hc. intros c Hc IH.\n nzsimpl; trivial.\n rewrite IH; trivial. apply mul_shuffle1.\nQed.\n\nLemma pow_mul_r : forall a b c, 0<=b -> 0<=c ->\n  a^(b*c) == (a^b)^c.\nProof.\n intros a b c Hb. apply le_ind with (4:=Hb). solve_proper.\n intros. now nzsimpl.\n clear b Hb. intros b Hb IH Hc.\n nzsimpl; trivial.\n rewrite pow_add_r, IH, pow_mul_l; trivial. apply mul_comm.\n now apply mul_nonneg_nonneg.\nQed.\n\n(** Positivity *)\n\nLemma pow_nonneg : forall a b, 0<=a -> 0<=a^b.\nProof.\n intros a b Ha.\n destruct (lt_ge_cases b 0) as [Hb|Hb].\n now rewrite !(pow_neg_r _ _ Hb).\n apply le_ind with (4:=Hb). solve_proper.\n nzsimpl; order'.\n clear b Hb. intros b Hb IH.\n nzsimpl; trivial. now apply mul_nonneg_nonneg.\nQed.\n\nLemma pow_pos_nonneg : forall a b, 0<a -> 0<=b -> 0<a^b.\nProof.\n intros a b Ha Hb. apply le_ind with (4:=Hb). solve_proper.\n nzsimpl; order'.\n clear b Hb. intros b Hb IH.\n nzsimpl; trivial. now apply mul_pos_pos.\nQed.\n\n(** Monotonicity *)\n\nLemma pow_lt_mono_l : forall a b c, 0<c -> 0<=a<b -> a^c < b^c.\nProof.\n intros a b c Hc. apply lt_ind with (4:=Hc). solve_proper.\n intros (Ha,H). nzsimpl; trivial; order.\n clear c Hc. intros c Hc IH (Ha,H).\n nzsimpl; try order.\n apply mul_lt_mono_nonneg; trivial.\n apply pow_nonneg; try order.\n apply IH. now split.\nQed.\n\nLemma pow_le_mono_l : forall a b c, 0<=a<=b -> a^c <= b^c.\nProof.\n intros a b c (Ha,H).\n destruct (lt_trichotomy c 0) as [Hc|[Hc|Hc]].\n rewrite !(pow_neg_r _ _ Hc); now nzsimpl.\n rewrite Hc; now nzsimpl.\n apply lt_eq_cases in H. destruct H as [H|H]; [|now rewrite <- H].\n apply lt_le_incl, pow_lt_mono_l; now try split.\nQed.\n\nLemma pow_gt_1 : forall a b, 1<a -> (0<b <-> 1<a^b).\nProof.\n intros a b Ha. split; intros Hb.\n rewrite <- (pow_1_l b) by order.\n apply pow_lt_mono_l; try split; order'.\n destruct (lt_trichotomy b 0) as [H|[H|H]]; trivial.\n rewrite pow_neg_r in Hb; order'.\n rewrite H, pow_0_r in Hb. order.\nQed.\n\nLemma pow_lt_mono_r : forall a b c, 1<a -> 0<=c -> b<c -> a^b < a^c.\nProof.\n intros a b c Ha Hc H.\n destruct (lt_ge_cases b 0) as [Hb|Hb].\n rewrite pow_neg_r by trivial. apply pow_pos_nonneg; order'.\n assert (H' : b<=c) by order.\n destruct (le_exists_sub _ _ H') as (d & EQ & Hd).\n rewrite EQ, pow_add_r; trivial. rewrite <- (mul_1_l (a^b)) at 1.\n apply mul_lt_mono_pos_r.\n apply pow_pos_nonneg; order'.\n apply pow_gt_1; trivial.\n apply lt_eq_cases in Hd; destruct Hd as [LT|EQ']; trivial.\n  rewrite <- EQ' in *. rewrite add_0_l in EQ. order.\nQed.\n\n(** NB: since 0^0 > 0^1, the following result isn't valid with a=0 *)\n\nLemma pow_le_mono_r : forall a b c, 0<a -> b<=c -> a^b <= a^c.\nProof.\n intros a b c Ha H.\n destruct (lt_ge_cases b 0) as [Hb|Hb].\n rewrite (pow_neg_r _ _ Hb). apply pow_nonneg; order.\n apply le_succ_l in Ha; rewrite <- one_succ in Ha.\n apply lt_eq_cases in Ha; destruct Ha as [Ha|Ha]; [|rewrite <- Ha].\n apply lt_eq_cases in H; destruct H as [H|H]; [|now rewrite <- H].\n apply lt_le_incl, pow_lt_mono_r; order.\n nzsimpl; order.\nQed.\n\nLemma pow_le_mono : forall a b c d, 0<a<=c -> b<=d ->\n a^b <= c^d.\nProof.\n intros. transitivity (a^d).\n apply pow_le_mono_r; intuition order.\n apply pow_le_mono_l; intuition order.\nQed.\n\nLemma pow_lt_mono : forall a b c d, 0<a<c -> 0<b<d ->\n a^b < c^d.\nProof.\n intros a b c d (Ha,Hac) (Hb,Hbd).\n apply le_succ_l in Ha; rewrite <- one_succ in Ha.\n apply lt_eq_cases in Ha; destruct Ha as [Ha|Ha]; [|rewrite <- Ha].\n transitivity (a^d).\n apply pow_lt_mono_r; intuition order.\n apply pow_lt_mono_l; try split; order'.\n nzsimpl; try order. apply pow_gt_1; order.\nQed.\n\n(** Injectivity *)\n\nLemma pow_inj_l : forall a b c, 0<=a -> 0<=b -> 0<c ->\n a^c == b^c -> a == b.\nProof.\n intros a b c Ha Hb Hc EQ.\n destruct (lt_trichotomy a b) as [LT|[EQ'|GT]]; trivial.\n assert (a^c < b^c) by (apply pow_lt_mono_l; try split; trivial).\n order.\n assert (b^c < a^c) by (apply pow_lt_mono_l; try split; trivial).\n order.\nQed.\n\nLemma pow_inj_r : forall a b c, 1<a -> 0<=b -> 0<=c ->\n a^b == a^c -> b == c.\nProof.\n intros a b c Ha Hb Hc EQ.\n destruct (lt_trichotomy b c) as [LT|[EQ'|GT]]; trivial.\n assert (a^b < a^c) by (apply pow_lt_mono_r; try split; trivial).\n order.\n assert (a^c < a^b) by (apply pow_lt_mono_r; try split; trivial).\n order.\nQed.\n\n(** Monotonicity results, both ways *)\n\nLemma pow_lt_mono_l_iff : forall a b c, 0<=a -> 0<=b -> 0<c ->\n  (a<b <-> a^c < b^c).\nProof.\n intros a b c Ha Hb Hc.\n split; intro LT.\n apply pow_lt_mono_l; try split; trivial.\n destruct (le_gt_cases b a) as [LE|GT]; trivial.\n assert (b^c <= a^c) by (apply pow_le_mono_l; try split; order).\n order.\nQed.\n\nLemma pow_le_mono_l_iff : forall a b c, 0<=a -> 0<=b -> 0<c ->\n  (a<=b <-> a^c <= b^c).\nProof.\n intros a b c Ha Hb Hc.\n split; intro LE.\n apply pow_le_mono_l; try split; trivial.\n destruct (le_gt_cases a b) as [LE'|GT]; trivial.\n assert (b^c < a^c) by (apply pow_lt_mono_l; try split; trivial).\n order.\nQed.\n\nLemma pow_lt_mono_r_iff : forall a b c, 1<a -> 0<=c ->\n  (b<c <-> a^b < a^c).\nProof.\n intros a b c Ha Hc.\n split; intro LT.\n now apply pow_lt_mono_r.\n destruct (le_gt_cases c b) as [LE|GT]; trivial.\n assert (a^c <= a^b) by (apply pow_le_mono_r; order').\n order.\nQed.\n\nLemma pow_le_mono_r_iff : forall a b c, 1<a -> 0<=c ->\n  (b<=c <-> a^b <= a^c).\nProof.\n intros a b c Ha Hc.\n split; intro LE.\n apply pow_le_mono_r; order'.\n destruct (le_gt_cases b c) as [LE'|GT]; trivial.\n assert (a^c < a^b) by (apply pow_lt_mono_r; order').\n order.\nQed.\n\n(** For any a>1, the a^x function is above the identity function *)\n\nLemma pow_gt_lin_r : forall a b, 1<a -> 0<=b -> b < a^b.\nProof.\n intros a b Ha Hb. apply le_ind with (4:=Hb). solve_proper.\n nzsimpl. order'.\n clear b Hb. intros b Hb IH. nzsimpl; trivial.\n rewrite <- !le_succ_l in *. rewrite <- two_succ in Ha.\n transitivity (2*(S b)).\n  nzsimpl'. rewrite <- 2 succ_le_mono.\n  rewrite <- (add_0_l b) at 1. apply add_le_mono; order.\n apply mul_le_mono_nonneg; trivial.\n order'.\n now apply lt_le_incl, lt_succ_r.\nQed.\n\n(** Someday, we should say something about the full Newton formula.\n    In the meantime, we can at least provide some inequalities about\n    (a+b)^c.\n*)\n\nLemma pow_add_lower : forall a b c, 0<=a -> 0<=b -> 0<c ->\n  a^c + b^c <= (a+b)^c.\nProof.\n intros a b c Ha Hb Hc. apply lt_ind with (4:=Hc). solve_proper.\n nzsimpl; order.\n clear c Hc. intros c Hc IH.\n assert (0<=c) by order'.\n nzsimpl; trivial.\n transitivity ((a+b)*(a^c + b^c)).\n rewrite mul_add_distr_r, !mul_add_distr_l.\n apply add_le_mono.\n rewrite <- add_0_r at 1. apply add_le_mono_l.\n  apply mul_nonneg_nonneg; trivial.\n  apply pow_nonneg; trivial.\n rewrite <- add_0_l at 1. apply add_le_mono_r.\n  apply mul_nonneg_nonneg; trivial.\n  apply pow_nonneg; trivial.\n apply mul_le_mono_nonneg_l; trivial.\n now apply add_nonneg_nonneg.\nQed.\n\n(** This upper bound can also be seen as a convexity proof for x^c :\n    image of (a+b)/2 is below the middle of the images of a and b\n*)\n\nLemma pow_add_upper : forall a b c, 0<=a -> 0<=b -> 0<c ->\n  (a+b)^c <= 2^(pred c) * (a^c + b^c).\nProof.\n assert (aux : forall a b c, 0<=a<=b -> 0<c ->\n         (a + b) * (a ^ c + b ^ c) <= 2 * (a * a ^ c + b * b ^ c)).\n (* begin *)\n  intros a b c (Ha,H) Hc.\n  rewrite !mul_add_distr_l, !mul_add_distr_r. nzsimpl'.\n  rewrite <- !add_assoc. apply add_le_mono_l.\n  rewrite !add_assoc. apply add_le_mono_r.\n  destruct (le_exists_sub _ _ H) as (d & EQ & Hd).\n  rewrite EQ.\n  rewrite 2 mul_add_distr_r.\n  rewrite !add_assoc. apply add_le_mono_r.\n  rewrite add_comm. apply add_le_mono_l.\n  apply mul_le_mono_nonneg_l; trivial.\n  apply pow_le_mono_l; try split; order.\n (* end *)\n intros a b c Ha Hb Hc. apply lt_ind with (4:=Hc). solve_proper.\n nzsimpl; order.\n clear c Hc. intros c Hc IH.\n assert (0<=c) by order.\n nzsimpl; trivial.\n transitivity ((a+b)*(2^(pred c) * (a^c + b^c))).\n apply mul_le_mono_nonneg_l; trivial.\n now apply add_nonneg_nonneg.\n rewrite mul_assoc. rewrite (mul_comm (a+b)).\n assert (EQ : S (P c) == c) by (apply lt_succ_pred with 0; order').\n assert (LE : 0 <= P c) by (now rewrite succ_le_mono, EQ, le_succ_l).\n assert (EQ' : 2^c == 2^(P c) * 2) by (rewrite <- EQ at 1; nzsimpl'; order).\n rewrite EQ', <- !mul_assoc.\n apply mul_le_mono_nonneg_l.\n apply pow_nonneg; order'.\n destruct (le_gt_cases a b).\n apply aux; try split; order'.\n rewrite (add_comm a), (add_comm (a^c)), (add_comm (a*a^c)).\n apply aux; try split; order'.\nQed.\n\nEnd NZPowProp.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/Numbers/NatInt/NZPow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6695591392005792}}
{"text": "(** * Introduction *)\n\nSet Warnings \"-extraction-opaque-accessed,-extraction\".\nSet Warnings \"-notation-overridden,-parsing\".\n\nFrom QuickChick Require Import QuickChick.\nRequire Import List ZArith. Import ListNotations.\n\n(* ################################################################# *)\n(** * A First Taste of Testing *)\n\n(** Consider the following definition of a function [remove], which\n    takes a natural number [x] and a list of nats [l] and removes [x]\n    from the list. *)\n\nFixpoint remove (x : nat) (l : list nat) : list nat :=\n  match l with\n    | []   => []\n    | h::t => if h =? x then t else h :: remove x t\n  end.\n\n(** One possible specification for [remove] might be this property... *)\n\nConjecture removeP : forall x l,  ~ (In x (remove x l)).\n\n(** ...which says that [x] never occurs in the result of [remove x l]\n    for any [x] and [l].  ([Conjecture foo...] means the same as\n    [Theorem foo... Admitted.]  Formally, [foo] is treated as an\n    axiom.) *)\n\n(** Sadly, this property is false, as we would (eventually) discover\n    if we were to try to prove it. *)\n\n(** A different -- perhaps much more efficient -- way to discover\n    the discrepancy between the definition and specification is\n    to _test_ it: *)\n\n(* QuickChick removeP. *)\n\n(** (Try uncommenting and evaluating the previous line.) *)\n\n(** The [QuickChick] command takes an \"executable\" property (we'll see\n    later exactly what this means) and attempts to falsify it by\n    running it on many randomly generated inputs, resulting in output\n    like this:\n\n       0 \n       [0, 0] \n       Failed! After 17 tests and 12 shrinks\n\n    This means that, if we run [remove] with [x] being [0] and [l] \n    being the two-element list containing two zeros, then the property \n    [removeP] fails. *)\n\n(** With this example in hand, we can see that the [then] branch\n    of [remove] fails to make a recursive call, which means that only\n    one occurence of [x] will be deleted. The last line of the output\n    records that it took 17 tests to identify some fault-inducing\n    input and 12 \"shrinks\" to reduce it to a minimal\n    counterexample. *)\n\n(** **** Exercise: 1 star (insertP)  *)\n(** Here is a somewhat mangled definition of a function for inserting a\n   new element into a sorted list of numbers: *)\n\nFixpoint insert x l :=\n  match l with\n  | [] => [x]\n  | y::t => if y <? x then insert x t else y::t\n  end.\n\n(** Write a property that says \"inserting a number [x] into a list [l]\n    always yields a list containing [x].\"  Make sure QuickChick finds\n    a counterexample. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars (insertP2)  *)\n(** Translate the following claim into a [Conjecture] (using [In] for\n    list membership): \"For all numbers [x] and [y] and lists [l], if\n    [y] is in [l] then it is also in the list that results from\n    inserting [x] into [l]\" (i.e., [insert] preserves all the elements\n    already in [l]). Make sure QuickChick finds a counterexample. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ################################################################# *)\n(** * Overview *)\n\n(** Property-based random testing involves four basic ingredients:\n\n    - an _executable property_ like [removeP],\n    - _generators_ for random elements of the types of the inputs to\n      the property (here, numbers and lists of numbers),\n    - _printers_ for converting data structures like numbers and lists\n      to strings when reporting counterexamples, and\n    - _shrinkers_, which are used to minimize counterexamples. *)\n\n(** We will delve into each of these in detail later on, but first we\n    need to make a digression to explain Coq's support for\n    _typeclasses_, which QuickChick uses extensively both internally\n    and in its programmatic interface to users.  This is the\n    [Typeclasses] chapter.\n    \n    In the [QC] chapter we'll cover the core concepts and\n    features of QuickChick itself.\n\n    The [TImp] chapter develops a small case study around a typed\n    variant of the Imp language.\n\n    The [QuickChickTool] chapter presents a command line tool,\n    _quickChick_, that supports larger-scale projects and mutation\n    testing.\n\n    The [QuickChickInterface] chapter is a complete reference\n    manual for QuickChick.\n\n    Finally, the [Postscript] chapter gives some suggestions for\n    further reading. *)\n\n(* Tue Oct 9 11:47:30 EDT 2018 *)\n", "meta": {"author": "sbihel", "repo": "softwarefoundations", "sha": "bf071a7b57382d3db2c52d1e2c4b483993e55ef9", "save_path": "github-repos/coq/sbihel-softwarefoundations", "path": "github-repos/coq/sbihel-softwarefoundations/softwarefoundations-bf071a7b57382d3db2c52d1e2c4b483993e55ef9/qc/Introduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.8902942268497306, "lm_q1q2_score": 0.6695124628329536}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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) : natural := mult Zero (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_90_mult_zero/goal33conj52_coqofml_yZ49kv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942232112239, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6695124502005518}}
{"text": "Require Import Arith Lia Nat.\nFrom Undecidability.Synthetic Require Import DecidabilityFacts.\nFrom FOL.Tennenbaum Require Import SyntheticInType CantorPairing.\n(** * Decidability of bounded quantifiers. *)\n\n\n\nLemma Dec_sigT_transport {X} p q :\n  Dec_sigT p -> (forall x : X, p x <-> q x) -> Dec_sigT q.\nProof.\n  intros Dec_p Equiv. intros x.\n  destruct (Dec_p x) as [H|H];\n  [left | right]; firstorder.\nQed.\n\n\nLemma dec_lt_bounded_sig N (p : nat -> Type) :\n  (forall x, p x + (p x -> False)) -> { x & ((x < N) * p x)%type } + (forall x, x < N -> p x -> False).\nProof.\n  intros Dec_p. induction N.\n  right. intros []; lia.\n  destruct (IHN) as [IH | IH].\n  - left. destruct IH as [x Hx].\n    exists x. split. destruct Hx. lia. apply Hx.\n  - destruct (Dec_p N) as [HN | HN]. \n    + left. exists N. split. lia. apply HN.\n    + right. intros x Hx.\n      assert (x = N \\/ x < N) as [->|] by lia; auto.\n      now apply IH.\nDefined.\n\n\nLemma dec_lt_bounded_exist' N p :\n  Dec_sigT p -> (exists x, x < N /\\ p x) + (forall x, x < N -> ~ p x).\nProof.\n  intros Dec_p. induction N.\n  right. intros []; lia.\n  destruct (IHN) as [IH | IH].\n  - left. destruct IH as [x Hx].\n    exists x. split. lia. apply Hx.\n  - destruct (Dec_p N) as [HN | HN]. \n    + left. exists N. split. lia. apply HN.\n    + right. intros x Hx.\n      assert (x = N \\/ x < N) as [->|] by lia; auto.\nDefined.\n\n\nLemma dec_lt_bounded_exist N p :\n  Dec_sigT p -> dec (exists x, x < N /\\ p x).\nProof.\n  intros Dec_p.\n  destruct (dec_lt_bounded_exist' N p Dec_p).\n  now left. right. firstorder.\nDefined.\n\n\nLemma dec_lt_bounded_forall N p :\n  Dec_sigT p -> dec (forall x, x < N -> p x).\nProof.\n  intros Dec_p. induction N.\n  left. lia.\n  destruct (Dec_p N) as [HN | HN].\n  - destruct (IHN) as [IH | IH].\n    +  left. intros x Hx.\n    assert (x = N \\/ x < N) as [->|] by lia; auto.\n    + right. intros H. apply IH.\n      intros x Hx. apply H. lia.\n  - right. intros H. apply HN.\n    apply H. lia. \nDefined.\n\n\nLemma neg_lt_bounded_forall N p : \n  Dec_sigT p -> (~ forall x, x < N -> p x) -> exists x, x < N /\\ ~ p x. \nProof.\n  intros Hp H.\n  induction N. exfalso. apply H; lia.\n  destruct (Hp N).\n  - destruct IHN as [n ]. \n    + intros H1. apply H. intros.\n      assert (x = N \\/ x < N) as [->|] by lia. \n      auto. now apply H1.\n    + exists n. intuition lia. \n  - exists N. auto.\nQed.\n\n(** * The product type for Nat is witnessing. *)\n\nTheorem ProductWO (p : nat -> nat -> Prop) : \n  ( forall x y, dec (p x y) ) -> (exists x y, p x y) -> { x & { y & p x y }}.\nProof.\n  intros Dec_p H.\n  pose (P n := let (x, y) := decode n in p x y).\n  assert ({n & P n}) as [n Hn].\n  apply Witnessing_nat.\n  - intros n.\n    destruct (decode n) as [x y] eqn:E.\n    destruct (Dec_p x y); (left + right); unfold P; now rewrite E.\n  - destruct H as (x & y & H).\n    exists (code (x, y)). unfold P.\n    now rewrite inv_dc.\n  - destruct (decode n) as [x y] eqn:E.\n    exists x, y. unfold P in Hn; now rewrite E in Hn.\nQed.", "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/MoreDecidabilityFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942232112239, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6695124502005518}}
{"text": "\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq.\nFrom Coq Require Import ssrfun.\nRequire Import AutosubstSsr ARS Context.\nRequire Import Program.Equality.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* presyntax *)\n\nInductive term : Type :=\n| Var (x : var)\n| TT\n| App (s t : term)\n| Fun (s : {bind 2 of term})\n| Pi (s : term) (t : {bind term})\n| Cast (s t : term).\n\n\n\nInstance Ids_term : Ids term. derive. Defined.\nInstance Rename_term : Rename term. derive. Defined.\nInstance Subst_term : Subst term. derive. Defined.\nInstance substLemmas_term : SubstLemmas term. derive. Qed.\n\n", "meta": {"author": "qcfu-bu", "repo": "dtest-coq", "sha": "213952f2185d95c7b4ad1e9793ee471b9d384550", "save_path": "github-repos/coq/qcfu-bu-dtest-coq", "path": "github-repos/coq/qcfu-bu-dtest-coq/dtest-coq-213952f2185d95c7b4ad1e9793ee471b9d384550/theories/ast.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6695124430634901}}
{"text": "(** This file continues the development of algebra [Operation]. It\n    gives a way to construct operations using (conventional) curried\n    functions, and shows that such curried operations are equivalent\n    to the uncurried operations [Operation]. *)\n\nRequire Export HoTT.Algebra.Universal.Algebra.\n\nRequire Import\n  HoTT.Types\n  HoTT.Spaces.Finite\n  HoTT.Spaces.Nat.\n\nLocal Open Scope Algebra_scope.\nLocal Open Scope nat_scope.\n\n(** Functions [head_dom'] and [head_dom] are used to get the first\n    element of a nonempty operation domain [a : forall i, A (ss i)]. *)\n\nMonomorphic Definition head_dom' {σ} (A : Carriers σ) (n : nat)\n  : forall (N : n > 0) (ss : FinSeq n (Sort σ)) (a : forall i, A (ss i)),\n    A (fshead' n N ss)\n  := match n with\n     | 0 => fun N ss _ => Empty_rec (not_lt_n_n _ N)\n     | n'.+1 => fun N ss a => a fin_zero\n     end.\n\nMonomorphic Definition head_dom {σ} (A : Carriers σ) {n : nat}\n  (ss : FinSeq n.+1 (Sort σ)) (a : forall i, A (ss i))\n  : A (fshead ss)\n  := head_dom' A n.+1 _ ss a.\n\n(** Functions [tail_dom'] and [tail_dom] are used to obtain the tail\n    of an operation domain [a : forall i, A (ss i)]. *)\n\nMonomorphic Definition tail_dom' {σ} (A : Carriers σ) (n : nat)\n  : forall (ss : FinSeq n (Sort σ)) (a : forall i, A (ss i)) (i : Fin (pred n)),\n    A (fstail' n ss i)\n  := match n with\n     | 0 => fun ss _ i => Empty_rec i\n     | n'.+1 => fun ss a i => a (fsucc i)\n     end.\n\nMonomorphic Definition tail_dom {σ} (A : Carriers σ) {n : nat}\n  (ss : FinSeq n.+1 (Sort σ)) (a : forall i, A (ss i))\n  : forall i, A (fstail ss i)\n  := tail_dom' A n.+1 ss a.\n\n(** Functions [cons_dom'] and [cons_dom] to add an element to\n    the front of a given domain [a : forall i, A (ss i)]. *)\n\nMonomorphic Definition cons_dom' {σ} (A : Carriers σ) {n : nat}\n  : forall (i : Fin n) (ss : FinSeq n (Sort σ)) (N : n > 0),\n    A (fshead' n N ss) -> (forall i, A (fstail' n ss i)) -> A (ss i)\n  := fin_ind\n      (fun n i =>\n        forall (ss : Fin n -> Sort σ) (N : n > 0),\n        A (fshead' n N ss) -> (forall i, A (fstail' n ss i)) -> A (ss i))\n      (fun n' _ z x _ => x)\n      (fun n' i' _ => fun _ _ _ xs => xs i').\n\nDefinition cons_dom {σ} (A : Carriers σ)\n  {n : nat} (ss : FinSeq n.+1 (Sort σ))\n  (x : A (fshead ss)) (xs : forall i, A (fstail ss i))\n  : forall i : Fin n.+1, A (ss i)\n  := fun i => cons_dom' A i ss _ x xs.\n\n(** The empty domain: *)\n\nDefinition nil_dom {σ} (A : Carriers σ) (ss : FinSeq 0 (Sort σ))\n  : forall i : Fin 0, A (ss i)\n  := Empty_ind (A o ss).\n\n(** A specialization of [Operation] to finite [Fin n] arity. *)\n\nDefinition FiniteOperation {σ : Signature} (A : Carriers σ)\n  {n : nat} (ss : FinSeq n (Sort σ)) (t : Sort σ) : Type\n  := Operation A {| Arity := Fin n; sorts_dom := ss; sort_cod := t |}.\n\n(** A type of curried operations\n<<\nCurriedOperation A [s1, ..., sn] t := A s1 -> ... -> A sn -> A t.\n>> *)\n\nFixpoint CurriedOperation {σ} (A : Carriers σ) {n : nat}\n  : (FinSeq n (Sort σ)) -> Sort σ -> Type\n  := match n with\n     | 0 => fun ss t => A t\n     | n'.+1 =>\n        fun ss t => A (fshead ss) -> CurriedOperation A (fstail ss) t\n     end.\n\n(** Function [operation_uncurry] is used to uncurry an operation\n<<\noperation_uncurry A [s1, ..., sn] t (op : CurriedOperation A [s1, ..., sn] t)\n  : FiniteOperation A [s1, ..., sn] t\n  := fun (x1 : A s1, ..., xn : A xn) => op x1 ... xn\n>>\nSee [equiv_operation_curry] below. *)\n\nFixpoint operation_uncurry {σ} (A : Carriers σ) {n : nat}\n  : forall (ss : FinSeq n (Sort σ)) (t : Sort σ),\n    CurriedOperation A ss t -> FiniteOperation A ss t\n  := match n with\n     | 0 => fun ss t op _ => op\n     | n'.+1 =>\n        fun ss t op a =>\n          operation_uncurry A (fstail ss) t (op (a fin_zero)) (a o fsucc)\n     end.\n\nLocal Example computation_example_operation_uncurry\n  : forall\n      (σ : Signature) (A : Carriers σ) (n : nat) (s1 s2 t : Sort σ)\n      (ss := (fscons s1 (fscons s2 fsnil)))\n      (op : CurriedOperation A ss t) (a : forall i, A (ss i)),\n    operation_uncurry A ss t op\n    = fun a => op (a fin_zero) (a (fsucc fin_zero)).\nProof.\n  reflexivity.\nQed.\n\n(** Function [operation_curry] is used to curry an operation\n<<\noperation_curry A [s1, ..., sn] t (op : FiniteOperation A [s1, ..., sn] t)\n  : CurriedOperation A [s1, ..., sn] t\n  := fun (x1 : A s1) ... (xn : A xn) => op (x1, ..., xn)\n>>\nSee [equiv_operation_curry] below. *)\n\nFixpoint operation_curry {σ} (A : Carriers σ) {n : nat} \n  : forall (ss : FinSeq n (Sort σ)) (t : Sort σ),\n    FiniteOperation A ss t -> CurriedOperation A ss t\n  := match n with\n     | 0 => fun ss t op => op (Empty_ind _)\n     | n'.+1 =>\n        fun ss t op x =>\n          operation_curry A (fstail ss) t (op o cons_dom A ss x)\n     end.\n\nLocal Example computation_example_operation_curry\n  : forall\n      (σ : Signature) (A : Carriers σ) (n : nat) (s1 s2 t : Sort σ)\n      (ss := (fscons s1 (fscons s2 fsnil)))\n      (op : FiniteOperation A ss t)\n      (x1 : A s1) (x2 : A s2),\n    operation_curry A ss t op\n    = fun x1 x2 => op (cons_dom A ss x1 (cons_dom A _ x2 (nil_dom A _))).\nProof.\n  reflexivity.\nQed.\n\nLemma expand_cons_dom' {σ} (A : Carriers σ) (n : nat)\n  : forall (i : Fin n) (ss : FinSeq n (Sort σ)) (N : n > 0)\n           (a : forall i, A (ss i)),\n    cons_dom' A i ss N (head_dom' A n N ss a) (tail_dom' A n ss a) = a i.\nProof.\n  intro i.\n  induction i using fin_ind; intros ss N a.\n  - unfold cons_dom'.\n    rewrite compute_fin_ind_fin_zero.\n    reflexivity.\n  - unfold cons_dom'.\n    by rewrite compute_fin_ind_fsucc.\nQed.\n\nLemma expand_cons_dom `{Funext} {σ} (A : Carriers σ)\n  {n : nat} (ss : FinSeq n.+1 (Sort σ)) (a : forall i, A (ss i))\n  : cons_dom A ss (head_dom A ss a) (tail_dom A ss a) = a.\nProof.\n  funext i.\n  apply expand_cons_dom'.\nDefined.\n\nLemma path_operation_curry_to_cunurry `{Funext} {σ} (A : Carriers σ)\n  {n : nat} (ss : FinSeq n (Sort σ)) (t : Sort σ)\n  : operation_uncurry A ss t o operation_curry A ss t == idmap.\nProof.\n  intro a.\n  induction n as [| n IHn].\n  - funext d. refine (ap a _). apply path_contr.\n  - funext a'.\n    refine (ap (fun x => x _) (IHn _ _) @ _).\n    refine (ap a _).\n    apply expand_cons_dom.\nQed.\n\nLemma path_operation_uncurry_to_curry `{Funext} {σ} (A : Carriers σ)\n  {n : nat} (ss : FinSeq n (Sort σ)) (t : Sort σ)\n  : operation_curry A ss t o operation_uncurry A ss t == idmap.\nProof.\n  intro a.\n  induction n; [reflexivity|].\n  funext x.\n  refine (_ @ IHn (fstail ss) (a x)).\n  refine (ap (operation_curry A (fstail ss) t) _).\n  funext a'.\n  simpl.\n  unfold cons_dom, cons_dom'.\n  rewrite compute_fin_ind_fin_zero.\n  refine (ap (operation_uncurry A (fstail ss) t (a x)) _).\n  funext i'.\n  now rewrite compute_fin_ind_fsucc.\nQed.\n\nGlobal Instance isequiv_operation_curry `{Funext} {σ} (A : Carriers σ)\n  {n : nat} (ss : FinSeq n (Sort σ)) (t : Sort σ)\n  : IsEquiv (operation_curry A ss t).\nProof.\n  srapply isequiv_adjointify.\n  - apply operation_uncurry.\n  - apply path_operation_uncurry_to_curry.\n  - apply path_operation_curry_to_cunurry.\nDefined.\n\nDefinition equiv_operation_curry `{Funext} {σ} (A : Carriers σ)\n  {n : nat} (ss : FinSeq n (Sort σ)) (t : Sort σ)\n  : FiniteOperation A ss t <~> CurriedOperation A ss t\n  := Build_Equiv _ _ (operation_curry A ss t) _.\n\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Algebra/Universal/Operation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6693044940759475}}
{"text": "(* Ejercicio 3 - dependencia del 4 *)\nSection Ejercicio3.\n\nVariable A B C: Set.\n\nDefinition apply := fun (x : A -> B) (y : A) => (x y).\nDefinition o_ := fun (x : A -> B) (y : B -> C) => fun (z : A) => (y (x z)).\nDefinition twice := fun (x : A -> A) (y : A) => (x (x y)).\n\n(* Al cerrar la sección, los operadores anteriores se generalizan *)\nEnd Ejercicio3.\n\n\n(* Ejercicio 4 *)\nSection Ejercicio4.\n\nVariable A: Set.\n\nInfix \"o\" := (o_ A A A) (at level 80, right associativity).\nDefinition id := fun (x : A) => x.\n\nTheorem e4_1 : forall x:A, (id o id) x = id x.\nProof.\n  reflexivity.\nQed.\n\nTheorem e4_2 : forall x:A, (id o id) x = id x.\nProof.\n  cbv delta.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem e4_3 : forall x:A, (id o id) x = id x.\nProof.\n  intros.\n  unfold o_, id.\n  reflexivity.\nQed.\n\nEnd Ejercicio4.\n\n\n(* Ejercicio 5 *)\nSection Ejercicio5.\n\n(* 5.1 *)\nDefinition opI (A : Set) (x : A) := x.\nDefinition opK (A : Set) (B : Set) (x : A) (y : B) := x.\nDefinition opS (A : Set) (B : Set) (C : Set) (f : A -> B -> C) (g : A -> B) (x : A) := ((f x) (g x)).\n\n(* 5.2 *)\n(* Para formalizar el siguiente lema, determine los tipos ?1 ... ?8 adecuados *)\nLemma e52 : forall A B : Set, opS A (B -> A) A (opK A (B -> A)) (opK A B) = opI A.\nProof.\n  reflexivity.\nQed.\n\nEnd Ejercicio5.\n\n\n(* Ejercicio 10 *)\nSection Ejercicio10.\n\nParameter Array : Set -> nat -> Set.\nParameter emptyA : forall X : Set, Array X 0.\nParameter addA : forall (X : Set) (n : nat), X -> Array X n -> Array X (S n).\n\nParameter Matrix : Set -> nat -> Set.\nParameter emptyM : forall {X : Set}, Matrix X 0.\nParameter addM : forall {X : Set}, forall {n : nat}, Matrix X n -> Array X (n + 1) -> Matrix X (n + 1).\n\nDefinition M1 := addM emptyM (addA nat 0 1 (emptyA nat)). (* matriz de una columna *)\nDefinition M2 := addM M1 (addA nat 1 2 (addA nat 0 2 (emptyA nat))). (* matriz de dos columnas *) \nDefinition M3 := addM M2 (addA nat 2 3 (addA nat 1 3 (addA nat 0 3 (emptyA nat)))). (* matriz de tres columnas *)\n\nEnd Ejercicio10.\n\n\n(* Ejercicio 11 *)\nSection Ejercicio11.\n\nParameter ABNat : forall n: nat, Set.\nParameter emptyAB : ABNat 0.\nParameter addAB : forall {n: nat}, nat -> ABNat n -> ABNat n -> ABNat (n + 1).\n\nDefinition AB1 := addAB 7 emptyAB emptyAB.\nDefinition AB2 := addAB 3 AB1 AB1.\n\nCheck AB2.\n\nParameter BTree : forall T: Set, forall n: nat, Set.\nParameter emptyBT : forall {T: Set}, BTree T 0.\nParameter addBT : forall {T: Set}, forall {n: nat}, T -> BTree T n -> BTree T n -> BTree T (n + 1).\n\nDefinition BT1 := addBT 7 emptyBT emptyBT.\nDefinition BT2 := addBT 3 BT1 BT1.\n\nCheck BT2.\n\nDefinition BBT1 := addBT false emptyBT emptyBT.\nDefinition BBT2 := addBT true BBT1 BBT1.\n\nCheck BBT2.\n\nEnd Ejercicio11.\n\n\n(* Ejercicio 15 *)\nSection Ejercicio15.\n\nVariable U : Set.\nVariable e : U.\nVariable A B : U -> Prop.\nVariable P : Prop.\nVariable R : U -> U -> Prop.\n\nLemma Ej315_1 : (forall x : U, A x -> B x) -> (forall x : U, A x) -> forall x : U, B x.\nProof.\n  intros.\n  exact (H x (H0 x)).\nQed.\n\nLemma Ej315_2 : forall x : U, A x -> ~ (forall x : U, ~ A x).\nProof.\n  unfold not.\n  intros.\n  exact (H0 x H).\nQed.\n\nLemma Ej315_3 : (forall x : U, P -> A x) -> P -> forall x : U, A x.\nProof.\n  exact (fun D => fun P => fun x => D x P).\nQed.\n\nLemma Ej315_4 : (forall x y : U, R x y) -> forall x : U, R x x.\nProof.\n  exact (fun G => fun x => G x x).\nQed.\n\nLemma Ej315_5 : (forall x y: U, R x y -> R y x) ->\n                 forall z : U, R e z -> R z e.\nProof.\n  exact (fun C => fun z => C e z).\nQed.\n\nEnd Ejercicio15.\n\n", "meta": {"author": "elopez", "repo": "CFPTT", "sha": "5df066218d0acba5a009db498e6125d69865096a", "save_path": "github-repos/coq/elopez-CFPTT", "path": "github-repos/coq/elopez-CFPTT/CFPTT-5df066218d0acba5a009db498e6125d69865096a/práctica 3/p3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.6693044754896907}}
{"text": "Require Import Reals Psatz.\nRequire Import Coquelicot.Hierarchy.\nRequire Import Coquelicot.Rbar.\nRequire Import Top.linear_map.\nRequire Import Top.continuous_linear_map.\nRequire Import Omega Init.Nat Arith.EqNat.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Ah_properties.\nRequire Import Eigen_system.\n\nVariable h:R. (* h is the discretization step *)\nHypothesis h_gt_0: 0<h. (* assumption that the discretization step > 0 *)\n\nLemma inv_sqr_h_ge_0: 0 <= 1 * / (h * h).\nProof.\nassert( 0< h -> 0 <= 1 * / (h * h)). { intros. apply Rlt_le. assert( 0<h -> 0<(h*h)). { nra. }\nassert(0 < h * h->0 < 1 * / (h * h)). \nassert(1 * / (h * h)= /(h*h)). { nra. } rewrite H1.  apply (Rinv_0_lt_compat (h*h)).\napply H1. nra. } apply H. apply h_gt_0.\nQed.\n\n\nLemma N_not_zero: forall N:nat, (2<N)%nat -> INR (N+1) <> 0.\nProof.\nintros.\nassert ( 0 < INR (N+1) -> INR (N+1) <> 0). { nra. } apply H0.\napply lt_0_INR. omega.\nQed.\n\nRequire Import R_sqrt Rpower.\n\n(** This is where we instatiate the eigen value for Ah(a, b, a) with a= (1/h^2), b= -2 / (h^2) **)\nLemma lambda : forall (m N:nat) , (2<N)%nat -> (0<=m<N)%nat ->\n  coeff_mat 0 (Lambda m N (1/(h^2)) (-2/ (h^2)) (1/(h^2))) 0%nat 0%nat= - (4/ (h^2))* (sin ( (INR (m+1) * PI)*/(2* INR (N+1))))^2.\nProof.\nintros. unfold Lambda.\nassert (coeff_mat 0\n        (mk_matrix 1 1\n           (fun _ _ : nat =>\n            -2 / h ^ 2 + 2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) * cos (INR (m + 1) * PI * / INR (N + 1)))) 0 0=(fun _ _ : nat =>\n            -2 / h ^ 2 + 2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) * cos (INR (m + 1) * PI * / INR (N + 1))) 0%nat 0%nat).\n{ apply (coeff_mat_bij 0 (fun _ _ : nat =>\n            -2 / h ^ 2 + 2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) * cos (INR (m + 1) * PI * / INR (N + 1))) 0%nat 0%nat).\n  omega. omega.\n} rewrite H1.\nassert (sqrt (1 / h ^ 2 * (1 / h ^ 2))= (1 / h ^ 2)). { apply sqrt_square. assert (h^2 = h* h). { nra. } rewrite H2. apply inv_sqr_h_ge_0. }\nrewrite H2.\nassert (-2 / h ^ 2 + 2 * (1 / h ^ 2) * cos (INR (m + 1) * PI * / INR (N + 1))=\n          (2 / h ^ 2) * (-1+  cos (INR (m + 1) * PI * / INR (N + 1)))). { nra. } rewrite H3.\ncut((-1 + cos (INR (m+1) * PI * / INR (N + 1)))= -2* sin (INR (m+1) * PI * / (2 * INR (N + 1))) ^ 2).\n+ intros. rewrite H4. nra.\n+ assert(cos (INR (m+1) * PI * / INR (N + 1))= cos (2* ((INR (m+1) * PI)*/(2* INR (N+1))))).\n  { assert((INR (m+1) * PI * / INR (N + 1))= (2 * (INR (m+1) * PI * / (2 * INR (N + 1))))).\n    { assert(/ (2 * INR (N + 1))= (/2)* (/ INR (N+1))). { apply Rinv_mult_distr. nra. apply N_not_zero. omega. } rewrite H4. nra. }\n      rewrite H4. reflexivity.\n    } rewrite H4.\n  assert (-2 * sin (INR (m+1) * PI * / (2 * INR (N + 1))) ^ 2= -1 + (1-2 * sin (INR (m+1) * PI * / (2 * INR (N + 1))) ^ 2)).\n  { nra. } rewrite H5.\n  apply Rplus_eq_compat_l. \n  assert (sin (INR (m+1) * PI * / (2 * INR (N + 1))) ^ 2= sin (INR (m+1) * PI * / (2 * INR (N + 1)))* sin (INR (m+1) * PI * / (2 * INR (N + 1)))). { nra. } rewrite H6.\n  assert (2 * (sin (INR (m+1) * PI * / (2 * INR (N + 1))) * sin (INR (m+1) * PI * / (2 * INR (N + 1))))=\n                2 * sin (INR (m+1) * PI * / (2 * INR (N + 1))) * sin (INR (m+1) * PI * / (2 * INR (N + 1)))). { nra. } rewrite H7.\n  apply cos_2a_sin.\nQed.\n\n(*** Proving the uniform boundedness of 1/ | lambda_min| for Ah (1/h^2, -2/h^2, 1/h^2) **)\n\n(* Define a real valued concae function *)\nDefinition concave (f:R->R) (x y c:R):= 0<=c<=1 ->f(c*x + (1-c) * y) >= c* f x + (1-c) * f y.\n\nLemma inverse_a_b: forall (a b:R), (a <> 0) /\\ (b<>0)-> a/b= 1/(b/a).\nProof.\nintros.\nassert ( 1 / (b / a)= /(b * /a)). { nra. } rewrite H0.\nassert (/ (b * / a)= /b * //a). { apply Rinv_mult_distr. nra. apply Rinv_neq_0_compat. nra. }\nrewrite H1. assert ( / / a= a). { apply Rinv_involutive. nra. } rewrite H2. nra.\nQed.\n\n\nDefinition g (f:R-> R)(pr:derivable f) (x:R):= derive_pt f x (pr x).\n\n(** Stating the property of a concave function that in the interval [a,b], the 2nd derivative of a differentiable function g is <=0 ***)\nHypothesis concave_def: forall (f:R->R) (g:R->R) (a b c x:R) (pr: derivable f) (pr1:derivable g), a<=x<=b -> concave f a b c<-> \n      derive_pt g x (pr1 x) <=0.\n\n\nLemma sin_concave_1 (x:R) : 0<=x<=PI/2 -> concave sin 0 (PI / 2) (1-(2/PI)*x).\nProof.\nintros.\nassert (concave sin 0 (PI/2) (1-(2/PI)*x)<-> derive_pt cos x (derivable_pt_cos x) <=0). { apply (concave_def sin  cos 0 (PI/2) (1-(2/PI)*x) x  ( derivable_pt_sin) (derivable_pt_cos )).  nra. } \ndestruct H0.\napply H1. \nassert (derive_pt cos x (derivable_pt_cos x)= -sin x). { apply derive_pt_cos. } rewrite H2.\nassert ( 0 = -0). { nra. } rewrite H3.\napply Ropp_le_contravar.\napply sin_ge_0. nra. nra.\nQed.\n\nLemma sin_concave (x:R):0<=x<=PI/2 ->  sin x >= 2 / PI * x <-> concave sin 0 (PI/2) (1-(2/PI)*x).\nProof.\nsplit.\n+ intros. unfold concave.\n  intros.\n  assert(sin 0 = 0). { apply sin_0. } rewrite H2.\n  assert (sin (PI/2) =1). { apply sin_PI2. } rewrite H3.\n  assert ((1 - 2 / PI * x) * 0=0). { nra. } rewrite H4. \n  assert ((1 - (1 - 2 / PI * x)) * 1= (2/PI)*x). { nra. } rewrite H5. \n  assert ((1 - (1 - 2 / PI * x)) * (PI / 2)=x). \n  { assert ((1 - (1 - 2 / PI * x))= (2/PI)*x). { nra. } rewrite H6.\n    assert (2 / PI * x * (PI / 2)= ((2/PI)* (PI/2))*x). { nra. } rewrite H7.\n    assert (2 / PI * (PI / 2)=1).\n    { assert (2 / PI= 1/ (PI/2)).  apply (inverse_a_b 2 PI). \n      split.\n      - nra.\n      - apply PI_neq0.\n      rewrite H8. \n      assert (1 / (PI / 2)= / (PI / 2)). { nra. } rewrite H9.\n      symmetry. apply Rinv_l_sym .  \n      assert (0 < (PI/2) -> PI / 2 <> 0). { nra. } apply H10. apply PI2_RGT_0.\n    } rewrite H8. nra.\n  } \n  assert (0 + (1 - (1 - 2 / PI * x)) * (PI / 2)= x). { nra. } rewrite H7.\n  assert (0 + 2 / PI * x= 2 / PI * x). { nra. } rewrite H8. apply H0.\n+ intros.\n  unfold concave in H0. \n    assert ( 0 <= 1 - 2 / PI * x <= 1). \n    { split.\n      - assert ( 0 = 1-1). { nra. } rewrite H1.\n        apply Rplus_le_compat_l. apply Ropp_ge_le_contravar. \n        assert ( 1= (/ (PI /2)) * (PI/2)). { apply Rinv_l_sym.  \n        assert (0 < (PI/2) -> PI / 2 <> 0). { nra. } apply H2. apply PI2_RGT_0. }\n       rewrite H2.\n        assert ( 2/ PI = /(PI/2)). \n        { assert (/ (PI / 2)= 1/ (PI/2)).  { nra. } rewrite H3. apply inverse_a_b. \n          split. nra. apply PI_neq0. } rewrite H3.\n        apply Rmult_ge_compat_l. nra.  nra.\n      - assert (1= 1-0). { nra. } rewrite H1.\n        assert ( 1 - 0 - 2 / PI * x= 1 - 2 / PI * x). { nra. } rewrite H2.\n        apply Rplus_le_compat. nra.\n        apply Ropp_ge_le_contravar. \n        assert (0 =(2/PI)*0). { nra. } rewrite H3. apply Rmult_ge_compat_l. \n        apply Rle_ge. apply Rlt_le. \n        assert (2 / PI= 1/ (PI/2)). { apply inverse_a_b. split. nra. apply PI_neq0. } rewrite H4.\n        assert (1 / (PI / 2)= / (PI/2)). { nra. } rewrite H5. apply Rinv_0_lt_compat. apply PI2_RGT_0. nra.\n    }\n    specialize (H0 H1). \n    assert(sin 0 = 0). { apply sin_0. } rewrite H2 in H0.\n    assert (sin (PI/2) =1). { apply sin_PI2. } rewrite H3 in H0.\n    assert ((1 - 2 / PI * x) * 0=0). { nra. } rewrite H4 in H0. \n    assert ((1 - (1 - 2 / PI * x)) * 1= (2/PI)*x). { nra. } rewrite H5 in H0.\n    assert ((1 - (1 - 2 / PI * x)) * (PI / 2)=x). \n    { assert ((1 - (1 - 2 / PI * x))= (2/PI)*x). { nra. } rewrite H6.\n      assert (2 / PI * x * (PI / 2)= ((2/PI)* (PI/2))*x). { nra. } rewrite H7.\n      assert (2 / PI * (PI / 2)=1).\n      { assert (2 / PI= 1/ (PI/2)).  apply (inverse_a_b 2 PI). \n        split.\n        - nra.\n        - apply PI_neq0.\n        rewrite H8. \n        assert (1 / (PI / 2)= / (PI / 2)). { nra. } rewrite H9.\n        symmetry. apply Rinv_l_sym .  \n        assert (0 < (PI/2) -> PI / 2 <> 0). { nra. } apply H10. apply PI2_RGT_0.\n      } rewrite H8. nra.\n    } \n    assert (0 + (1 - (1 - 2 / PI * x)) * (PI / 2)= x). { nra. } rewrite H7 in H0.\n    assert (0 + 2 / PI * x= 2 / PI * x). { nra. } rewrite H8 in H0. apply H0.\nQed.\n\n\nLemma limit_trigo : forall x:R, 0<=x<=(PI/2) -> (2* x)/PI <= sin x.\nProof.\nintros.\napply Rge_le. \nassert (sin x >= 2 / PI * x <-> concave sin 0 (PI/2) (1-(2/PI)*x)). { apply sin_concave. nra. } \ndestruct H0. \nassert (2 * x / PI= 2 / PI * x). { nra. } rewrite H2. apply H1. apply sin_concave_1. nra.\nQed.\n\n\nLemma spectral_intermed: forall x:R, 0<x<=PI/2 -> (x^2)/ (sin x)^2 <= (PI^2)/4.\nProof.\nintros.\nassert (x ^ 2 / sin x ^ 2= Rsqr ( x / sin x)). \n{ assert ( x^2 = Rsqr x). { simpl. unfold Rsqr. nra. } rewrite H0.\n  assert (sin x ^ 2= Rsqr (sin x)). { simpl. unfold Rsqr. nra. } rewrite H1.\n  symmetry. apply Rsqr_div. \n  assert (0< sin x -> sin x <> 0). { nra. } apply H2. apply sin_gt_0. nra. nra. \n} rewrite H0.\nassert (PI ^ 2 / 4= Rsqr (PI/2)).\n{ assert (PI^2 = Rsqr PI). { simpl. unfold Rsqr. nra. } rewrite H1.\n  assert (4 = Rsqr 2). { auto. } rewrite H2. symmetry. apply Rsqr_div. auto. }\n  rewrite H1.\n  apply Rsqr_incr_1.\n  apply Rmult_le_reg_r with (2/PI). \n  assert ( 2/ PI = 1/ (PI/2)). { apply inverse_a_b. nra. } rewrite H2.\n  assert (1 / (PI / 2)= / (PI/2)). { nra. } rewrite H3. apply Rinv_0_lt_compat. nra.\n  assert (PI / 2 * (2 / PI)=1). \n  { assert ((2 / PI)= 1/ (PI/2)). { apply inverse_a_b. nra. } rewrite H2.\n    assert ((1 / (PI / 2))= / (PI/2)). { nra. } rewrite H3. apply Rinv_r. nra.\n  }   rewrite H2.\n  apply Rmult_le_reg_r with (sin x).\n  apply sin_gt_0. nra. nra.\n  assert (x / sin x * (2 / PI) * sin x= (x * 2/PI) * (/sin x * sin x)). { nra. } rewrite H3.\n  assert ((/ sin x * sin x)= 1). { symmetry. apply Rinv_l_sym. assert ( 0< sin x -> sin x <> 0). { nra. } apply H4.\n  apply sin_gt_0. nra. nra. }\n  rewrite H4.\n  assert ( (2* x)/PI= x * 2 / PI * 1). { nra. } rewrite <- H5.\n  assert (1 * sin x= sin x). { nra. } rewrite H6. apply limit_trigo. nra.\n  apply Rlt_le. assert (x / sin x= x* (/sin x)). { nra. } rewrite H2. \n  apply Rmult_lt_0_compat. nra. apply Rinv_0_lt_compat. apply sin_gt_0. nra. nra. nra.\nQed.\n\n(*** Define the minimum eigen value for Ah (1/h^2, -2/(h^2), 1/h^2). m=1 ***)\nDefinition Lambda_min (N:nat):= (-2/(h^2)) + 2 * (1/(h^2)) * cos (INR 1 * PI * / INR (N + 1)).\n\nVariable L:R. (* L is the length of the domain *)\nHypothesis L_ge_0: 0< L.\n\nLemma L_PI_gt_0 (L:R): 0 < L /\\ 0 < PI -> 0 < L / PI.\nProof.\nintros. \nassert ( L / PI= L * (/PI)). { nra. } rewrite H0.\napply Rmult_lt_0_compat. nra. apply Rinv_0_lt_compat. nra.\nQed.\n\n\nHypothesis h_L: forall (N:nat), h = L/ INR (N+1). \n\nLemma inv_gt_0: forall a b:R, 0<a /\\ 0< b -> 0< a/b.\nProof.\nintros.\nassert (a / b= a * (/b)). { nra. } rewrite H0. apply Rmult_lt_0_compat.\n+ nra.\n+ apply Rinv_0_lt_compat. nra.\nQed.\n\n(*** Proof that 1/|lambda_min| for Ah (1/h^2, -2/h^2, 1/h^2) is uniformly bounded by L^2/4 **)\nLemma spectral : forall N:nat , (2<N)%nat -> 1/ Rabs( Lambda_min N) <= L^2 / 4.\nProof.\nintros.\ncut ( 1 / Rabs (Lambda_min  N)= (L^2/ (PI^2)) * ( (PI/ (2* INR (N+1)))^2 / (sin (PI/ (2* INR (N+1))))^2)).\n+ intros. rewrite H0.\n  assert (( (PI/ (2* INR (N+1)))^2 / (sin (PI/ (2* INR (N+1))))^2)<= (PI^2)/4).\n  { apply spectral_intermed.\n    split.\n    + assert ( 0< PI /\\ 0<(2 * INR (N + 1)) -> 0 < PI / (2 * INR (N + 1))). { apply inv_gt_0. }\n      apply H1.\n      split.\n      - apply PI_RGT_0.\n      - apply Rmult_lt_0_compat. nra. apply lt_0_INR. omega.\n    + assert (PI / (2 * INR (N + 1))= PI * /(2 * INR (N + 1))). { nra. } rewrite H1.\n      assert (PI / 2= PI * (/2)). { nra. } rewrite H2.\n      apply Rmult_le_compat_l. apply Rlt_le. apply PI_RGT_0.\n      apply Rlt_le. apply Rinv_1_lt_contravar. nra. \n      assert (2= 2* 1). { nra. } rewrite H3.\n      assert (2 * 1 * INR (N + 1)= 2* (INR (N+1))). { nra. } rewrite H4.\n      apply Rmult_lt_compat_l. nra.\n      apply lt_1_INR. omega.\n  }\n  assert (L ^ 2 / 4= (L^2 /(PI^2)) * (PI^2/4)).  \n  {  assert ( L ^ 2 / PI ^ 2 * (PI ^ 2 / 4)= (L^2/4) * ( / (PI^2) * (PI^2))). { nra. } rewrite H2.\n     assert ( 1= ( / (PI^2) * (PI^2))). { apply Rinv_l_sym. assert ( PI <> 0 -> PI ^ 2 <> 0). { nra. } apply H3. apply PI_neq0. }\n  rewrite <-H3. nra.\n  } rewrite H2.\n  apply Rmult_le_compat_l.  apply Rlt_le.\n  assert (0< L/PI ->  0 <L ^ 2 / PI ^ 2). \n  { intros. \n    assert (L ^ 2 = Rsqr L). { simpl. unfold Rsqr. nra. } rewrite H4.\n    assert (PI ^ 2= Rsqr PI). { simpl. unfold Rsqr. nra. } rewrite H5.\n    assert (Rsqr (L/PI) = L² / PI²). { apply Rsqr_div. apply PI_neq0. } rewrite <- H6.\n    apply Rsqr_pos_lt.\n    assert (0 < L/PI -> L / PI <> 0). { nra. } apply H7. apply L_PI_gt_0. split. apply L_ge_0. apply PI_RGT_0.\n  }\n  apply H3.\n  apply L_PI_gt_0. split. apply L_ge_0. apply PI_RGT_0. apply H1.\n+ assert ( (Lambda_min  N)<0 -> Rabs (Lambda_min  N)= - (Lambda_min  N)). \n  { apply Rabs_left. } rewrite H0.\n  unfold Lambda_min. \n  cut ((-2/(h^2))  + 2 * (1/(h^2))* cos (INR 1 * PI * / INR (N + 1))= (2*/ (h^2))* (-1+ cos (INR 1 * PI * / INR (N + 1)))).\n  - intros. rewrite H1.\n    assert ((-1 + cos (INR 1 * PI * / INR (N + 1)))= -2 *sin (PI / (2 * INR (N + 1))) ^ 2).\n    { assert (INR 1 * PI * / INR (N + 1)= 2* (PI/ (2* INR (N+1)))).\n      { assert (INR 1= 1). { reflexivity. } rewrite H2. \n      assert (1=2* (/2)). { nra. } rewrite H3.\n      assert (2 * / 2 * PI * / INR (N + 1)= (2* PI) * (/2 * / INR (N+1))). { nra. } rewrite H4.\n      assert (2 * (PI / (2 * INR (N + 1)))= (2* PI) * (/ (2* INR (N+1)))). { nra. } rewrite H5.\n      apply Rmult_eq_compat_l. symmetry. apply Rinv_mult_distr. nra. \n      assert (0 < INR (N+1) -> INR (N + 1) <> 0). { nra. } apply H6.\n      apply lt_0_INR. omega.\n    } rewrite H2.\n    assert ( -2 * sin (PI / (2 * INR (N + 1))) ^ 2= -1 + (1 -2 * sin (PI / (2 * INR (N + 1))) ^ 2)). { nra. } rewrite H3.\n    apply Rplus_eq_compat_l. \n    assert (1 - 2 * sin (PI / (2 * INR (N + 1))) ^ 2= 1 - 2 * sin (PI / (2 * INR (N + 1)))* sin (PI / (2 * INR (N + 1)))). { nra. } rewrite H4.\n    apply cos_2a_sin.\n    }\n    rewrite H2.\n    assert (-(2 * / h ^ 2 * (-2 * sin (PI / (2 * INR (N + 1))) ^ 2))= (4* / (h^2)) * sin (PI / (2 * INR (N + 1)))^2). { nra. } \n    rewrite H3.\n    assert (1 /(4 * / h ^ 2 * sin (PI / (2 * INR (N + 1))) ^ 2)= / ((4* / (h^2)) * (sin (PI / (2 * INR (N + 1))) ^ 2))).\n    { nra. } rewrite H4.\n    assert (/ ((4* / (h^2)) * (sin (PI / (2 * INR (N + 1))) ^ 2))= / (4/ (h^2)) * /(sin (PI / (2 * INR (N + 1))) ^ 2)).\n    { apply Rinv_mult_distr. \n      assert (0 < 4/ (h^2) -> 4 / h ^ 2 <> 0). { nra. } apply H5. \n      assert ( 4 / h ^ 2= 4 * (/ h^2)). { nra. } rewrite H6.\n      apply Rmult_lt_0_compat. nra. apply Rinv_0_lt_compat. \n      assert (0< h -> 0 < h ^ 2). { nra. } apply H7. apply h_gt_0.\n      assert (sin (PI / (2 * INR (N + 1))) <> 0 -> sin (PI / (2 * INR (N + 1))) ^ 2 <> 0). { nra. } apply H5.\n      assert (0 < sin (PI / (2 * INR (N + 1))) -> sin (PI / (2 * INR (N + 1))) <> 0). { nra. } apply H6.\n      assert ( sin 0 = 0). { apply sin_0. } rewrite <- H7.\n      apply sin_increasing_1. assert (0=-0). { nra. } rewrite H8. \n      apply Ropp_ge_le_contravar. apply Rgt_ge. apply PI2_RGT_0. apply Rlt_le. apply PI2_RGT_0.\n      apply Rle_trans with 0. assert (0=-0). { nra. } rewrite H8. \n      apply Ropp_ge_le_contravar. apply Rgt_ge. apply PI2_RGT_0. apply Rlt_le. assert (0 = PI * 0). { nra. } rewrite H8.\n      assert (PI / (2 * INR (N + 1))= PI * (/ (2 * INR (N + 1)))). { nra. } rewrite H9. apply Rmult_lt_compat_l.\n      apply PI_RGT_0. apply Rinv_0_lt_compat. assert (0=2* 0). { nra. } rewrite H10. apply Rmult_lt_compat_l. nra. apply lt_0_INR. omega.\n      apply Rlt_le. assert (PI / (2 * INR (N + 1))= PI * (/ (2* INR (N+1)))). { nra. } rewrite H8.\n      assert (PI / 2= PI * (/2)). { nra. } rewrite H9. apply Rmult_lt_compat_l. apply PI_RGT_0. apply Rinv_1_lt_contravar. nra. \n      assert (2= 2 * 1). { nra. } rewrite H10. \n      assert (2 * 1 * INR (N + 1)= 2* INR (N+1)). { nra. } rewrite H11. apply Rmult_lt_compat_l.\n      nra. apply lt_1_INR. omega.\n      assert ( 0 = PI * 0). { nra. } rewrite H8.\n      assert ( PI / (2 * INR (N + 1))= PI * (/ (2* INR (N+1)))). { nra. } rewrite H9.\n      apply Rmult_lt_compat_l. apply PI_RGT_0. apply Rinv_0_lt_compat. assert (0=2* 0). { nra. } rewrite H10.\n      apply Rmult_lt_compat_l. nra. apply lt_0_INR. omega.\n    }\n    rewrite H5. \n    assert (/ (4 / h ^ 2) = 1/ (4 / h ^ 2)). { nra. } rewrite H6.\n    assert ( (h^2)/4 = 1 / (4 / h ^ 2)). { apply inverse_a_b. split.\n     assert (0<h -> h ^ 2 <> 0). { nra. } apply H7. apply h_gt_0. nra. }\n    rewrite <-H7.\n    assert (h ^ 2 / 4= L ^ 2 / PI ^ 2 * (PI / (2 * INR (N + 1))) ^ 2). \n    { assert (h= L/ INR (N+1)). { apply h_L. } rewrite H8.\n      assert ((L / INR (N + 1)) ^ 2= (L^2) / (INR (N+1))^2). \n      { assert ((L / INR (N + 1)) ^ 2= Rsqr (L/ INR (N+1))). { simpl. unfold Rsqr. nra. } rewrite H9.\n        assert (L ^ 2 = Rsqr L). { simpl. unfold Rsqr. nra. } rewrite H10.\n        assert (INR (N + 1) ^ 2= Rsqr (INR (N+1))). { simpl. unfold Rsqr. nra. } rewrite H11.\n        apply Rsqr_div. assert ( 0< INR (N+1) -> INR (N + 1) <> 0). { nra. } apply H12. apply lt_0_INR. omega. \n      }\n      assert ( 4= Rsqr 2). { auto. } rewrite H10.\n      assert ((L / INR (N + 1)) ^ 2= Rsqr ( L/ INR (N+1))). \n      { simpl. unfold Rsqr. nra. } rewrite H11.\n      assert (Rsqr ((L / INR (N + 1))/ 2)= (L / INR (N + 1))² / 2²). { apply Rsqr_div. nra. } rewrite <-H12.\n      assert (L / INR (N + 1) / 2= L * (/INR (N+1)) * /2). { nra. } rewrite H13.\n      assert (L * (/INR (N+1)) * /2= L * (/ INR (N+1) * /2)). { nra. } rewrite H14.\n      assert ( / (INR (N+1) * 2) =(/ INR (N+1) * /2)). { apply Rinv_mult_distr. \n        assert (0< INR (N+1) -> INR (N + 1) <> 0). { nra. } apply H15. apply lt_0_INR. omega. nra. }\n      rewrite<- H15.\n      assert ((INR (N + 1) * 2) = 2* INR (N+1)). { apply Rmult_comm. } rewrite H16. \n      assert (PI * / (2* INR (N+1)) * (L */ PI) = L * / (2 * INR (N + 1))). { apply Rinv_mult_simpl. apply PI_neq0. } rewrite <-H17.\n      assert ((L * / PI)= L/ PI). { nra. } rewrite H18.\n      assert (PI * / (2 * INR (N + 1))= PI/ (2* INR (N+1))). { nra. } rewrite H19.\n      assert ((PI / (2 * INR (N + 1)) * (L / PI))² = Rsqr (PI/ (2* INR (N+1))) * Rsqr (L/PI)). { apply Rsqr_mult. } rewrite H20.\n      assert (L ^ 2 / PI ^ 2= Rsqr (L/PI)). \n      { assert (L ^ 2= Rsqr L). { simpl. unfold Rsqr. nra. } rewrite H21.\n        assert (PI ^ 2= Rsqr PI). { simpl. unfold Rsqr. nra. } rewrite H22.\n        symmetry.  apply Rsqr_div. apply PI_neq0. \n      } rewrite H21.\n      assert ((PI / (2 * INR (N + 1))) ^ 2= Rsqr (PI/ (2* INR (N+1)))). \n      { simpl. unfold Rsqr. nra. } rewrite H22. nra.\n     } rewrite H8. nra.\n  - nra.\nunfold Lambda_min. \nassert (-2 / h ^ 2 +2 * (1 / h ^ 2) *cos (INR 1 * PI * / INR (N + 1))= (2/ h^2) * (-1 + cos (INR 1 * PI * / INR (N + 1)))).\n{ nra. } rewrite H1.\nassert (0= (2/ h^2) * 0). { nra. } rewrite H2.\napply Rmult_lt_compat_l. assert ( 0 = 2* 0). { nra. } rewrite H3.\nassert ( 2 / h ^ 2= 2* (/ h^2)). { apply Rmult_eq_compat_l. reflexivity. } rewrite H4. apply Rmult_lt_compat_l. nra.\napply Rinv_0_lt_compat. assert ( 0 < h -> 0< h ^ 2). { nra. } apply H5. apply h_gt_0.\nassert (0=-1+1). { nra. } rewrite H3.\napply Rplus_lt_compat_l.\nassert ((INR 1 * PI * / INR (N + 1))= PI / INR (N + 1)).\n{ assert (INR 1 = 1). { reflexivity. } rewrite H4. nra. } rewrite H4.\nassert (cos 0 =1). { apply cos_0. } rewrite <- H5.\napply cos_decreasing_1. nra. apply Rlt_le. apply PI_RGT_0. apply Rlt_le.\nassert (0 = PI * 0). { nra. } rewrite H6.\nassert (PI / INR (N + 1)= PI * (/ INR (N+1))). { nra. } rewrite H7.\napply Rmult_lt_compat_l. apply PI_RGT_0. apply Rinv_0_lt_compat. apply lt_0_INR. omega.\napply Rlt_le. assert (PI= PI * 1). { nra. } rewrite H6.\nassert (PI * 1 / INR (N + 1)= PI * (/INR (N+1))). { nra. } rewrite H7.\napply Rmult_lt_compat_l. apply PI_RGT_0. assert (1 = /1). { nra. } rewrite H8. apply Rinv_1_lt_contravar. nra.\napply lt_1_INR. omega.\nassert (0= PI * 0). { nra. } rewrite H6.\nassert ( PI / INR (N + 1)= PI * (/ INR (N+1))). { nra. } rewrite H7.\napply Rmult_lt_compat_l. apply PI_RGT_0. apply Rinv_0_lt_compat. apply lt_0_INR. omega.\nQed.\n\n\n(* Proof that for any vector v , y^{T} * \\Lambda ^{-2} y = \\sum y_{i}^2/ \\lambda_{i} *)\n\nDefinition lam (j N:nat) (a b c:R):= 1/(coeff_mat 0 (Lambda j N a b c) 0%nat 0%nat).\n\n(* Proof on boundedness of eigen values *)\nLemma inverse_rel: forall (a b:R), (0<a /\\ 0< b) -> (b<=a) -> 1/a <= 1/b.\nProof.\nintros.\napply Rmult_le_reg_r with a.\n+ nra.\n+ assert (1 / a * a= 1). { assert (1 / a= / a). { nra. } rewrite H1. symmetry. apply Rinv_l_sym. nra. } rewrite H1.\napply Rmult_le_reg_r with b.\n+ nra.\n+  assert (1 / b * a * b= ( / b *b) * a). { nra. } rewrite H2.\n   assert (/ b * b =1). { symmetry. apply Rinv_l_sym. nra. } rewrite H3.\n   apply Rmult_le_compat_l. \n   - nra.\n   - apply H0.\nQed.\n\n(** Proof that all eigen values of Ah (1/h^2, -2/h^2, 1/h^2) are negative ***)\n\nLemma eig_0: forall (i N:nat), (2<N)%nat -> (0<= i < N)%nat -> (-2/(h^2)) + 2 * sqrt ((1/(h^2))* (1/(h^2))) * cos (INR (i+1) * PI * / INR (N + 1)) < 0.\nProof.\nintros.\nassert (sqrt (1 / h ^ 2 * (1 / h ^ 2))=1 / h ^ 2 ). { apply sqrt_square. assert (h ^ 2= h* h). { nra. } rewrite H1. apply inv_sqr_h_ge_0. } rewrite H1.\nassert (-2 / h ^ 2 + 2 * (1 / h ^ 2) * cos (INR (i + 1) * PI * / INR (N + 1))= \n          (2/ (h^2)) * (- 1 +  cos (INR (i + 1) * PI * / INR (N + 1)))). { nra. } rewrite H2.\nassert ( 0 = (2/ (h^2))*0). { nra. } rewrite H3.\napply Rmult_lt_compat_l. \n+ assert ( 0 < 1/ (h^2) ->0 < 2 / h ^ 2). { nra. } apply H4. assert (1 / h ^ 2= / (h^2)). { nra. } rewrite H5.\n  apply Rinv_0_lt_compat. assert ( 0< h -> 0 < h ^ 2). { nra. } apply H6. apply h_gt_0.\n+ assert (0 = -1 +1). { nra. } rewrite H4.\n  apply Rplus_lt_compat_l.\n  assert ( cos 0 = 1). { apply cos_0. } rewrite <- H5.\n  apply cos_decreasing_1.\n  - nra.\n  - apply Rlt_le. apply PI_RGT_0.\n  - assert (INR (i + 1) * PI * / INR (N + 1)= (INR (i+1)) * (PI * / INR (N + 1))). { nra. } rewrite H6.\n    apply Rlt_le. apply Rmult_lt_0_compat. apply lt_0_INR. omega. apply Rmult_lt_0_compat. apply PI_RGT_0. apply Rinv_0_lt_compat. apply lt_0_INR. omega.\n  - apply Rmult_le_reg_r with (INR (N+1)). apply lt_0_INR. omega.\n    assert (INR (i + 1) * PI * / INR (N + 1) * INR (N + 1)= PI * INR (i+1) * ( / INR (N+1) * INR (N+1))). { nra. } rewrite H6.\n    assert (( / INR (N+1) * INR (N+1))=1). { symmetry. apply Rinv_l_sym. assert ( 0< INR (N+1) -> INR (N+1) <> 0). { nra. } apply H7. apply lt_0_INR. omega. }\n    rewrite H7.\n    assert (PI * INR (i + 1) * 1= PI * INR (i+1)). { nra. } rewrite H8.\n    apply Rmult_le_compat_l. apply Rlt_le. apply PI_RGT_0. apply le_INR. omega.\n  - assert (INR (i + 1) * PI * / INR (N + 1)= (INR (i+1)) * (PI * / INR (N + 1))). { nra. } rewrite H6.\n    apply Rmult_lt_0_compat. apply lt_0_INR. omega. apply Rmult_lt_0_compat. apply PI_RGT_0. apply Rinv_0_lt_compat. apply lt_0_INR. omega.\nQed.\n\n(** Proof that all eigen values of Ah(1/h^2, -2/h^2, 1/h^2) are non-zero ***)\nLemma eig_1: forall (i N:nat) , (2< N)%nat /\\ (0<=i<N)%nat-> coeff_mat 0 (Lambda i N (1/(h^2)) (-2/(h^2)) (1/(h^2))) 0 0 <> 0.\nProof.\nintros.\nunfold Lambda.\nassert (coeff_mat 0\n          (mk_matrix 1 1\n             (fun _ _ : nat =>\n              (-2/(h^2))  +\n              2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) * cos (INR (i+1) * PI * / INR (N + 1))))\n          0 0= (fun _ _ : nat =>\n              (-2/(h^2)) +\n              2 *  sqrt (1 / h ^ 2 * (1 / h ^ 2)) * cos (INR (i+1) * PI * / INR (N + 1))) 0%nat 0%nat).\n{ apply (coeff_mat_bij 0 (fun _ _ : nat =>\n              (-2/(h^2)) +\n              2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) * cos (INR (i+1) * PI * / INR (N + 1))) 0%nat 0%nat). omega. omega. } rewrite H0.\nassert (-2 / h ^ 2  + 2 *sqrt (1 / h ^ 2 * (1 / h ^ 2)) * cos (INR (i+1) * PI * / INR (N + 1)) < 0  -> \n              -2 / h ^ 2  + 2 * sqrt (1 / h ^ 2 * (1 / h ^ 2))* cos (INR (i+1) * PI * / INR (N + 1)) <>0).\n{ nra. } apply H1. apply eig_0. destruct H. apply H. destruct H. apply H2.\nQed.\n\n(** proof that the minimum eigen value of Ah(1/h^2, -2/h^2, 1/h^2) is non-zero. ***)\nLemma eig_2: forall (N:nat), (2<N)%nat -> Lambda_min  N <> 0.\nProof.\nintros.\nunfold Lambda_min. \nassert (sqrt (1 / h ^ 2 * (1 / h ^ 2))=1 / h ^ 2 ). { apply sqrt_square. assert (h ^ 2= h* h). { nra. } rewrite H0. apply inv_sqr_h_ge_0. } rewrite <-H0.\nassert (-2 / h ^ 2 + 2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) * cos (INR 1 * PI * / INR (N + 1)) <0 ->\n           -2 / h ^ 2 + 2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) * cos (INR 1 * PI * / INR (N + 1)) <> 0). { nra. } apply H1. \n assert (1%nat = (0+1)%nat).  { omega. } rewrite H2. apply eig_0. omega. omega.\nQed.\n\n\n(** Proof that 1/|lambda_min| is the maximum absolute eigen value of the inverse A^{-1} (1/h^2, -2/h^2, 1/h^2) **)\nLemma eigen_relation: forall (i N:nat), (2<N)%nat -> (0<=i<N)%nat -> Rabs (lam i N (1/(h^2)) (-2/(h^2)) (1/(h^2)) ) <= 1/ Rabs( Lambda_min  N).\nProof.\nintros.\nunfold lam.\nassert ((1 / coeff_mat 0 (Lambda i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2)) 0 0)= (/ (coeff_mat 0 (Lambda i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2)) 0 0))). \n{ nra. } rewrite H1.\nassert (Rabs (/ coeff_mat 0 (Lambda i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2)) 0 0)= / Rabs ( coeff_mat 0 (Lambda i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2)) 0 0)).\n{  apply Rabs_Rinv. apply eig_1. omega. }\nrewrite H2.\nassert (/ Rabs (coeff_mat 0 (Lambda i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2)) 0 0)= 1/ Rabs (coeff_mat 0 (Lambda i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2)) 0 0)). { nra. } rewrite H3.\napply inverse_rel.\n+ split.\n  - apply Rabs_pos_lt. apply eig_1. omega.\n  - apply Rabs_pos_lt. apply eig_2. omega.\n+ unfold Lambda_min. unfold Lambda.\n  assert (coeff_mat 0\n             (mk_matrix 1 1\n                (fun _ _ : nat =>\n                 -2 / h ^ 2  +\n                 2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) *\n                 cos (INR (i+1) * PI * / INR (N + 1)))) 0 0=  (fun _ _ : nat =>\n                 -2 / h ^ 2 +\n                 2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) *\n                 cos (INR (i+1) * PI * / INR (N + 1))) 0%nat 0%nat).\n  { apply (coeff_mat_bij 0 (fun _ _ : nat =>\n                 -2 / h ^ 2  +\n                 2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) *\n                 cos (INR (i+1) * PI * / INR (N + 1))) 0%nat 0%nat). omega. omega. } rewrite H4.\n  assert (i=0%nat \\/ (0< i < N)%nat). { omega. }\n  destruct H5.\n  + rewrite H5. assert ( 1%nat = (0+1)%nat). { omega. } rewrite <-H6.\n    assert (sqrt (1 / h ^ 2 * (1 / h ^ 2)) =(1 / h ^ 2)). { apply sqrt_square. assert (h^2 = h*h). { nra. } rewrite H7. apply inv_sqr_h_ge_0. } rewrite H7. nra.\n  + assert (sqrt (1 / h ^ 2 * (1 / h ^ 2)) =(1 / h ^ 2)). { apply sqrt_square. assert (h^2 = h*h). { nra. } rewrite H6. apply inv_sqr_h_ge_0. } \n    assert (Rabs (-2 / h ^ 2 + 2 * (1 / h ^ 2) * cos (INR 1 * PI * / INR (N + 1)))=Rabs  (-2 / h ^ 2+  2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) * cos (INR 1 * PI * / INR (N + 1)))).\n    { rewrite H6. nra. } rewrite H7.\n    assert (Rabs  (-2 / h ^ 2+  2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) * cos (INR 1 * PI * / INR (N + 1)))= \n              -(-2 / h ^ 2  +  2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) * cos (INR 1 * PI * / INR (N + 1)))). { apply Rabs_left. assert (1%nat = (0+1)%nat). { omega. } rewrite H8. apply eig_0. omega. omega. }\n    assert ( Rabs (-2 / h ^ 2  +  2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) * cos (INR (i+1) * PI * / INR (N + 1)))=\n              - (-2 / h ^ 2  +  2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) * cos (INR (i+1) * PI * / INR (N + 1)))). { apply Rabs_left. apply eig_0. omega. omega. }\n    rewrite H8. rewrite H9.\n    apply Ropp_ge_le_contravar.\n    apply (Rplus_ge_compat_l (-2 / h ^ 2 ) (2 * sqrt (1 / h ^ 2 * (1 / h ^ 2))* cos (INR 1 * PI * / INR (N + 1))) \n                (2 *  sqrt (1 / h ^ 2 * (1 / h ^ 2)) * cos (INR (i+1) * PI * / INR (N + 1)))). \n    apply Rmult_ge_compat_l.\n    - assert ( 0 = 2 * 0). { nra. } rewrite H10. apply Rmult_ge_compat_l. nra. \n      assert (0 <= sqrt (1 / h ^ 2 * (1 / h ^ 2)) -> sqrt (1 / h ^ 2 * (1 / h ^ 2)) >= 0). { nra. } apply H11. apply sqrt_pos.\n    - assert (cos (INR (i+1) * PI * / INR (N + 1)) <= cos (INR 1 * PI * / INR (N + 1)) -> cos (INR 1 * PI * / INR (N + 1)) >=cos (INR (i+1) * PI * / INR (N + 1))).\n      { nra. } apply H10. apply Rlt_le.\n      apply cos_decreasing_1. \n      * assert (INR 1 =1). { reflexivity. } rewrite H11. assert (1 * PI * / INR (N + 1) = PI * (/ INR (N+1))). { nra. } rewrite H12.\n        apply Rlt_le. apply Rmult_lt_0_compat. apply PI_RGT_0. apply Rinv_0_lt_compat. apply lt_0_INR. omega.\n      * assert (INR 1= 1). { reflexivity. } rewrite H11. assert (PI = PI * (/1)). { nra. } rewrite H12. \n        assert (1 * (PI * / 1) * / INR (N + 1)= PI * (/ INR (N+1))). { nra. } rewrite H13.\n        apply Rmult_le_compat_l. apply Rlt_le. apply PI_RGT_0. apply Rlt_le. apply Rinv_lt_contravar.\n        assert (1 * INR (N + 1)= INR (N+1)). { nra. } rewrite H14. apply lt_0_INR. omega.\n      * apply lt_1_INR. omega.\n      * apply Rlt_le. assert (INR (i+1) * PI * / INR (N + 1) = (INR (i+1)) * ( PI * (/ INR (N+1)))). { nra. } rewrite H11.\n        apply Rmult_lt_0_compat. apply lt_0_INR. omega. apply Rmult_lt_0_compat. apply PI_RGT_0.\n        apply Rinv_0_lt_compat. apply lt_0_INR. omega.\n      * assert (PI =1 * PI). { nra. } rewrite H11.\n        assert (INR (i+1) * (1 * PI) * / INR (N + 1)= ((INR (i+1)) *(/ INR (N+1))) * PI). { nra. } rewrite H12.\n        apply Rmult_le_compat.\n        - apply Rlt_le. apply Rmult_lt_0_compat. apply lt_0_INR. omega. apply Rinv_0_lt_compat. apply lt_0_INR. omega.\n        - apply Rlt_le. apply PI_RGT_0.\n        - assert ( 1 = INR (N+1) */ (INR (N+1))). { apply Rinv_r_sym. assert ( 0 < INR (N+1) -> INR (N+1) <> 0). { nra. } apply H13. apply lt_0_INR. omega. } rewrite H13.\n          apply Rmult_le_compat_r. apply Rlt_le. apply Rinv_0_lt_compat. apply lt_0_INR. omega.\n          apply le_INR. omega.\n        - nra.\n      * assert (INR 1 * PI * / INR (N + 1) = (INR 1) * (PI * / INR (N + 1))). { nra. } rewrite H11.\n        assert (INR (i+1) * PI * / INR (N + 1) = (INR (i+1)) * (PI * / INR (N + 1))). { nra. } rewrite H12.\n        apply Rmult_lt_compat_r. \n        { apply Rmult_lt_0_compat. apply PI_RGT_0. apply Rinv_0_lt_compat. apply lt_0_INR. omega. }\n        { apply lt_INR. omega. }\nQed.\n\nLemma sum_n_m_le : forall (n m N:nat) (a: nat -> R) (b : nat -> R), (2<N)%nat -> (0<n<=m)%nat -> (n<N)%nat /\\ (m<N)%nat ->  (forall i:nat , (0<=i<N)%nat -> a i <= b i) -> \n    sum_n_m (fun l:nat => a l) n m <=sum_n_m (fun l:nat => b l) n m.\nProof.\nintros.\ninduction m. contradict H. omega.\nassert ( n= S m \\/ (0<n<S m)%nat). { omega. } destruct H3.\n+ rewrite H3.\n  assert (sum_n_m (fun l : nat => a l) (S m) (S m)= (fun l : nat => a l) (S m)).\n  { apply (sum_n_n (fun l : nat => a l) (S m)). } rewrite H4.\n  assert (sum_n_m (fun l : nat => b l) (S m) (S m) = (fun l : nat => b l) (S m)).\n  { apply (sum_n_n (fun l : nat => b l) (S m)). } rewrite H5.\n  specialize (H2 (S m)). apply H2. omega.\n+ clear H0. \n   assert ((0 < n < S m)%nat -> (0 < n <= m)%nat). { omega. }  specialize (H0 H3). specialize (IHm H0).\n    assert ( sum_n_m (fun l : nat => a l) n (S m) = sum_n_m (fun l : nat => a l) n m + (fun l : nat => a l) (S m)).\n    { apply (sum_n_Sm (fun l : nat => a l)). omega. } rewrite H4.\n    assert (sum_n_m (fun l : nat => b l) n (S m) =sum_n_m (fun l : nat => b l) n m + (fun l : nat => b l) (S m)).\n    { apply (sum_n_Sm  (fun l : nat => b l)). omega. } rewrite H5.\n    apply Rplus_le_compat. apply IHm. specialize (H2 (S m)). omega. apply H2. omega.\nQed.  \n\nRequire Import linear_algebra.\n\nLemma max_spectral: forall (N:nat) (v: matrix N 1%nat),(2<N)%nat ->  vec_norm_2 N v =1 -> \n    sqrt (sum_n_m (fun i:nat => (coeff_mat 0 v i 0%nat)^2 * (lam i N (1/(h^2)) (-2/(h^2)) (1/(h^2)))^2) 0%nat (pred N)) <= 1/ Rabs(Lambda_min  N).\nProof.\nintros.\nassert (1 / Rabs (Lambda_min  N) =sqrt (Rsqr ( 1 / Rabs (Lambda_min  N)))). \n{ symmetry. apply sqrt_Rsqr. assert (1 / Rabs (Lambda_min  N)= / Rabs (Lambda_min  N)). { nra. } rewrite H1.\nassert (Rabs (/(Lambda_min  N)) = / Rabs (Lambda_min  N)). { apply Rabs_Rinv. apply eig_2. omega. } rewrite <-H2. apply Rabs_pos. }\nrewrite H1.  apply sqrt_le_1_alt. \nassert ((1 / Rabs (Lambda_min  N))²= Rsqr (1) / Rsqr(Rabs (Lambda_min  N))). \n{ apply Rsqr_div. apply Rabs_no_R0. apply eig_2. omega. } rewrite H2.\nassert ( 1² / (Rabs (Lambda_min  N))²= Rsqr(vec_norm_2 N v)/ (Rabs (Lambda_min  N))²). \n{ rewrite <- H0. reflexivity. } rewrite H3. unfold vec_norm_2.\nassert ( (sqrt (sum_n_m (fun l : nat => coeff_mat 0 v l 0 ^ 2) 0  (pred N)))²= (sum_n_m (fun l : nat => coeff_mat 0 v l 0 ^ 2) 0  (pred N))).\n{ apply Rsqr_sqrt. \n  assert (sum_n_m (fun l : nat => coeff_mat 0 v l 0 ^ 2) 0 (pred N)= sum_n_m (fun l : nat => coeff_mat 0 v l 0 ^ 2) 0%nat 0%nat +\n            sum_n_m (fun l : nat => coeff_mat 0 v l 0 ^ 2) 1%nat (pred N)).\n  { apply (sum_n_m_Chasles (fun l : nat => coeff_mat 0 v l 0 ^ 2) 0%nat 0%nat (pred N)). omega. omega. } rewrite H4.\n  apply Rplus_le_le_0_compat. \n  + assert (sum_n_m (fun l : nat => coeff_mat 0 v l 0 ^ 2) 0 0= (fun l : nat => coeff_mat 0 v l 0 ^ 2) 0%nat). \n    { apply (sum_n_n (fun l : nat => coeff_mat 0 v l 0 ^ 2) 0%nat). } rewrite H5. nra.\n  + apply sum_elem_pos. omega.\n    intros. nra.\n} rewrite H4.\nassert (sum_n_m (fun l : nat => coeff_mat 0 v l 0 ^ 2) 0 (pred N) /(Rabs (Lambda_min  N))²= \n          sum_n_m (fun l:nat => (coeff_mat 0 v l 0)^2 * (1/ Rsqr (Rabs( Lambda_min  N)))) 0%nat (pred N)).\n{ symmetry. \n  assert (sum_n_m (fun l : nat => coeff_mat 0 v l 0 ^ 2) 0 (pred N) /(Rabs (Lambda_min  N))²= \n            sum_n_m (fun l : nat => coeff_mat 0 v l 0 ^ 2) 0 (pred N) * (1/ Rsqr(Rabs (Lambda_min  N)))). { nra. } rewrite H5.\n  apply (sum_n_m_mult_r (1 / (Rabs (Lambda_min  N))²)(fun l : nat => coeff_mat 0 v l 0 ^ 2) 0%nat (pred N)).\n} rewrite H5.\nassert (sum_n_m (fun i : nat => coeff_mat 0 v i 0 ^ 2 * lam i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ^ 2  )  0 (pred N)= sum_n_m (fun i : nat => coeff_mat 0 v i 0 ^ 2 * lam i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ^ 2 ) 0%nat 0%nat +\n          sum_n_m (fun i : nat => coeff_mat 0 v i 0 ^ 2 * lam i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ^ 2  ) 1%nat (pred N)).\n{ apply (sum_n_m_Chasles (fun i : nat => coeff_mat 0 v i 0 ^ 2 * lam i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ^ 2 ) 0%nat 0%nat (pred N)). omega. omega. } rewrite H6.\nassert (sum_n_m  (fun l : nat =>   coeff_mat 0 v l 0 ^ 2 *   (1 / (Rabs (Lambda_min  N))²)) 0   (pred N)= \n          sum_n_m  (fun l : nat =>   coeff_mat 0 v l 0 ^ 2 *   (1 / (Rabs (Lambda_min  N))²)) 0%nat 0%nat + \n            sum_n_m  (fun l : nat =>   coeff_mat 0 v l 0 ^ 2 *   (1 / (Rabs (Lambda_min  N))²)) 1%nat (pred N)).\n{ apply (sum_n_m_Chasles (fun l : nat =>   coeff_mat 0 v l 0 ^ 2 *   (1 / (Rabs (Lambda_min  N))²)) 0%nat 0%nat (pred N)). omega. omega. } rewrite H7.\napply Rplus_le_compat.\n+ assert (sum_n_m (fun i : nat => coeff_mat 0 v i 0 ^ 2 * lam i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ^ 2)  0 0= (fun i : nat => coeff_mat 0 v i 0 ^ 2 * lam i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ^ 2) 0%nat).\n  { apply (sum_n_n (fun i : nat => coeff_mat 0 v i 0 ^ 2 *lam i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ^ 2) 0%nat). } rewrite H8.\n  assert (sum_n_m  (fun l : nat =>   coeff_mat 0 v l 0 ^ 2 *   (1 / (Rabs (Lambda_min  N))²)) 0 0= \n            (fun l : nat =>   coeff_mat 0 v l 0 ^ 2 *   (1 / (Rabs (Lambda_min  N))²)) 0%nat).\n  { apply (sum_n_n  (fun l : nat =>   coeff_mat 0 v l 0 ^ 2 *   (1 / (Rabs (Lambda_min  N))²)) 0%nat). } rewrite H9.\n  apply Rmult_le_compat_l. nra. \n  assert (lam 0 N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ^ 2 = Rsqr (Rabs (lam 0 N (1/(h^2)) (-2/(h^2)) (1/(h^2)) ))).\n  { assert (lam 0 N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ^ 2= Rsqr (lam 0 N (1/(h^2)) (-2/(h^2)) (1/(h^2)) )). { simpl. unfold Rsqr. nra. } rewrite H10. apply Rsqr_abs. }\n  rewrite H10. assert ( Rsqr 1 = 1). { apply Rsqr_1. } rewrite <- H11.\n  assert (Rsqr (1 / Rabs( Lambda_min  N)) = 1² / (Rabs (Lambda_min  N))²). { apply Rsqr_div. apply Rabs_no_R0. apply eig_2. omega. } rewrite <-H12.\n  apply Rsqr_incr_1.  unfold lam. \n  assert ( (1 / coeff_mat 0 (Lambda 0 N (1² / h ^ 2) (-2 / h ^ 2) (1² / h ^ 2)) 0 0)= / (coeff_mat 0 (Lambda 0 N (1² / h ^ 2) (-2 / h ^ 2) (1² / h ^ 2)) 0 0)). { nra. } rewrite H13.\n  assert (Rabs (/ coeff_mat 0 (Lambda 0 N (1² / h ^ 2) (-2 / h ^ 2) (1² / h ^ 2) ) 0 0) = / Rabs (coeff_mat 0 (Lambda 0 N (1² / h ^ 2) (-2 / h ^ 2) (1² / h ^ 2) ) 0 0)). { apply Rabs_Rinv.  rewrite H11. apply eig_1. omega. } rewrite H14.\n  assert (1 / Rabs (Lambda_min  N) = / Rabs (Lambda_min  N)). { nra. } rewrite H15. rewrite H11.\n  apply Rmult_le_reg_r with (Rabs (coeff_mat 0 (Lambda 0 N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ) 0 0) *  Rabs (Lambda_min  N)).\n  assert (Rabs ( (coeff_mat 0 (Lambda 0 N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ) 0 0) * (Lambda_min  N)) = Rabs (coeff_mat 0 (Lambda 0 N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ) 0 0) * Rabs (Lambda_min  N)). { apply Rabs_mult. } rewrite <- H16. apply Rabs_pos_lt.\n  apply Rmult_integral_contrapositive_currified. apply eig_1. omega. apply eig_2. omega.\n  assert (/ Rabs (coeff_mat 0 (Lambda 0 N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2)) 0 0) *(Rabs (coeff_mat 0 (Lambda 0 N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ) 0 0) * Rabs (Lambda_min  N))=\n          (/ Rabs (coeff_mat 0 (Lambda 0 N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2)) 0 0) * (Rabs (coeff_mat 0 (Lambda 0 N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ) 0 0))) * Rabs (Lambda_min  N)). { nra. } rewrite H16.\n  assert ( (/ Rabs (coeff_mat 0 (Lambda 0 N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ) 0 0) * (Rabs (coeff_mat 0 (Lambda 0 N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ) 0 0)))=1).\n  { symmetry. apply Rinv_l_sym. apply Rabs_no_R0. apply eig_1. omega. } rewrite H17.\n  assert (/ Rabs (Lambda_min  N) *(Rabs (coeff_mat 0 (Lambda 0 N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2)) 0 0) * Rabs (Lambda_min  N))=\n          (/ Rabs (Lambda_min  N) *  Rabs (Lambda_min  N)) * Rabs (coeff_mat 0 (Lambda 0 N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ) 0 0)). { nra. } rewrite H18.\n  assert ( (/ Rabs (Lambda_min  N) *  Rabs (Lambda_min  N))=1).\n  { symmetry. apply Rinv_l_sym. apply Rabs_no_R0. apply eig_2. omega. } rewrite H19.\n  apply Rmult_le_compat_l. nra. unfold Lambda_min. unfold Lambda.\n  assert (coeff_mat 0\n     (mk_matrix 1 1\n        (fun _ _ : nat =>\n        -2 / h ^ 2  +\n         2 * sqrt (1 / h ^ 2 * (1 / h ^ 2))*\n         cos (INR (0 + 1) * PI * / INR (N + 1)))) 0 0= (fun _ _ : nat =>\n         -2 / h ^ 2  +\n         2 * sqrt (1 / h ^ 2 * (1 / h ^ 2))*\n         cos (INR (0 + 1) * PI * / INR (N + 1))) 0%nat 0%nat).\n  { apply (coeff_mat_bij 0  (fun _ _ : nat =>\n                  -2 / h ^ 2  +\n                  2 * sqrt (1 / h ^ 2 * (1 / h ^ 2)) *\n                  cos (INR (0 + 1) * PI * / INR (N + 1))) 0%nat 0%nat). omega. omega. } \n  rewrite H20.\n  assert ((0 + 1)%nat = 1%nat). { omega. } rewrite H21.\n  assert (sqrt (1 / h ^ 2 * (1 / h ^ 2))= (1/(h^2))). { apply sqrt_square. assert (h^2= h*h). nra. rewrite H22. apply inv_sqr_h_ge_0. } rewrite H22. \n  apply Rle_refl.\n  apply Rabs_pos. apply Rlt_le. \n  assert (1 / Rabs (Lambda_min  N)= /Rabs (Lambda_min  N)). { nra. } rewrite H13. apply Rinv_0_lt_compat. apply Rabs_pos_lt. apply eig_2. omega.\n+ apply (sum_n_m_le 1%nat (pred N) N (fun i : nat => coeff_mat 0 v i 0 ^ 2 * lam i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ^ 2) (fun l : nat =>\n                          coeff_mat 0 v l 0 ^ 2 *   (1 / (Rabs (Lambda_min  N))²))). omega. omega. omega.\n  intros. apply Rmult_le_compat_l. nra. \n  assert (lam i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ^ 2 = Rsqr (Rabs (lam i N (1/(h^2)) (-2/(h^2)) (1/(h^2))))).\n  { assert (lam i N (1 / h ^ 2) (-2 / h ^ 2) (1 / h ^ 2) ^ 2= Rsqr (lam i N (1/(h^2)) (-2/(h^2)) (1/(h^2)) )). { simpl. unfold Rsqr. nra. } rewrite H9. apply Rsqr_abs. }\n  rewrite H9. assert ( Rsqr 1 = 1). { apply Rsqr_1. } rewrite <- H10.\n  assert (Rsqr (1 / Rabs( Lambda_min  N)) = 1² / (Rabs (Lambda_min  N))²). { apply Rsqr_div. apply Rabs_no_R0. apply eig_2. omega. } rewrite <-H11.\n  apply Rsqr_incr_1. rewrite H10. apply eigen_relation. omega. omega. apply Rabs_pos. apply Rlt_le.\n  assert ( 1 / Rabs (Lambda_min  N)= /  Rabs (Lambda_min  N)). { nra. } rewrite H12. apply Rinv_0_lt_compat. apply Rabs_pos_lt. apply eig_2. omega.\nQed.\n\n(* Define matrix norm *)\nDefinition matrix_norm (N:nat):= 1/ Rabs(Lambda_min N ).\n\n(* Applying the stability definition from the formalization of the Lax equivalence theorem to the numerical scheme *)\n\nRequire Import lax_equivalence.\n\nVariable m:nat.\nHypothesis size: forall m:nat , (2<m)%nat. (* condition on the size of the matrix *)\n\n\nNotation Xh:= lax_equivalence.Xh.\nNotation X:= lax_equivalence.X.\nNotation Y:= lax_equivalence.Y.\nNotation Yh:= lax_equivalence.Yh.\nNotation E:= lax_equivalence.E.\nNotation F:= lax_equivalence.F.\nNotation Aop:= lax_equivalence.Aop.\nNotation Ah_op:= lax_equivalence.Ah_op.\n\nHypothesis mat_op_norm: \n  forall (u:X) (f:Y) (h:R) (uh: Xh h) (rh: forall (h:R), X -> (Xh h)) (sh: forall (h:R), Y->(Yh h))\n (E: Y->X) (Eh:forall (h:R), (Yh h)->(Xh h)), operator_norm (Eh h) = matrix_norm m .\n\n\nTheorem stability: \n  forall (u:X) (f:Y) (h:R) (uh: Xh h) (rh: forall (h:R), X -> (Xh h)) (sh: forall (h:R), Y->(Yh h))\n  (E: Y->X) (Eh:forall (h:R), (Yh h)->(Xh h)), exists K:R , forall (h:R), operator_norm(Eh h)<=K.\nProof.\nintros.\nexists (L^2 / 4).\nintros.\nassert  (operator_norm (Eh h1)= matrix_norm m ).\n{ apply mat_op_norm. auto. auto. auto. auto. auto. auto. } rewrite H.\nunfold matrix_norm. apply spectral.  apply size.\nQed.", "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/stability.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.6692982362648169}}
{"text": "From mathcomp\n  Require Import ssreflect ssrbool ssrnat.\n\nPrint bool.\n\nPrint nat.\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\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: P n') => \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\nAbout nat_rec.\n\nCheck sum_no_zero 0.\nCheck sum_no_zero 1.\n\nSearch \"filt\" (_ -> list _).\n\nSearch _ ((?X -> ?Y ) -> _ ?X -> _ ?Y ).\nSearch _ (?a * ?b : nat).\nSearch _ (?a * ?b : Type).\n\nLocate \"_ + _\".\n\nInductive my_prod (A B : Type) : Type := my_pair of A & B.\n\nFail Check my_pair tt 1.\n\nArguments my_pair [A B].\nNotation \"X ** Y\" := (my_prod X Y ) (at level 2).\nNotation \"( X ,, Y )\" := (my_pair X Y ).\n\nCheck my_pair tt 1.\n\n\nTheorem false_absutd: False -> (1 = 2).\nProof.\ncase.\nRestart.\napply: False_ind.\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/pnp/FunProg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6692449096646474}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** Properties of Square Root Function *)\n\nRequire Import NAxioms NSub NZSqrt.\n\nModule NSqrtProp (Import A : NAxiomsSig')(Import B : NSubProp A).\n\n Module Import Private_NZSqrt := Nop <+ NZSqrtProp A A B.\n\n Ltac auto' := trivial; try rewrite <- neq_0_lt_0; auto using le_0_l.\n Ltac wrap l := intros; apply l; auto'.\n\n (** We redefine NZSqrt's results, without the non-negative hyps *)\n\nLemma sqrt_spec' : forall a, √a*√a <= a < S (√a) * S (√a).\nProof. wrap sqrt_spec. Qed.\n\nDefinition sqrt_unique : forall a b, b*b<=a<(S b)*(S b) -> √a == b\n := sqrt_unique.\n\nLemma sqrt_square : forall a, √(a*a) == a.\nProof. wrap sqrt_square. Qed.\n\nDefinition sqrt_le_mono : forall a b, a<=b -> √a <= √b\n := sqrt_le_mono.\n\nDefinition sqrt_lt_cancel : forall a b, √a < √b -> a < b\n := sqrt_lt_cancel.\n\nLemma sqrt_le_square : forall a b, b*b<=a <-> b <= √a.\nProof. wrap sqrt_le_square. Qed.\n\nLemma sqrt_lt_square : forall a b, a<b*b <-> √a < b.\nProof. wrap sqrt_lt_square. Qed.\n\nDefinition sqrt_0 := sqrt_0.\nDefinition sqrt_1 := sqrt_1.\nDefinition sqrt_2 := sqrt_2.\n\nDefinition sqrt_lt_lin : forall a, 1<a -> √a<a\n := sqrt_lt_lin.\n\nLemma sqrt_le_lin : forall a, √a<=a.\nProof. wrap sqrt_le_lin. Qed.\n\nDefinition sqrt_mul_below : forall a b, √a * √b <= √(a*b)\n := sqrt_mul_below.\n\nLemma sqrt_mul_above : forall a b, √(a*b) < S (√a) * S (√b).\nProof. wrap sqrt_mul_above. Qed.\n\nLemma sqrt_succ_le : forall a, √(S a) <= S (√a).\nProof. wrap sqrt_succ_le. Qed.\n\nLemma sqrt_succ_or : forall a, √(S a) == S (√a) \\/ √(S a) == √a.\nProof. wrap sqrt_succ_or. Qed.\n\nDefinition sqrt_add_le : forall a b, √(a+b) <= √a + √b\n := sqrt_add_le.\n\nLemma add_sqrt_le : forall a b, √a + √b <= √(2*(a+b)).\nProof. wrap add_sqrt_le. Qed.\n\n(** For the moment, we include stuff about [sqrt_up] with patching them. *)\n\nInclude NZSqrtUpProp A A B Private_NZSqrt.\n\nEnd NSqrtProp.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Numbers/Natural/Abstract/NSqrt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6692159135972673}}
{"text": "Require Import Coq.micromega.Psatz.\nRequire Import PL.Imp.\nRequire Import PL.RTClosure.\n\nInductive aexp_halt: aexp -> Prop :=\n  | AH_num : forall n, aexp_halt (ANum n).\n\nInductive astep : state -> aexp -> aexp -> Prop :=\n  | AS_Id : forall st X,\n      astep st\n        (AId X) (ANum (st X))\n\n  | AS_Plus1 : forall st a1 a1' a2,\n      astep st\n        a1 a1' ->\n      astep st\n        (APlus a1 a2) (APlus a1' a2)\n  | AS_Plus2 : forall st a1 a2 a2',\n      aexp_halt a1 ->\n      astep st\n        a2 a2' ->\n      astep st\n        (APlus a1 a2) (APlus a1 a2')\n  | AS_Plus : forall st n1 n2,\n      astep st\n        (APlus (ANum n1) (ANum n2)) (ANum (n1 + n2))\n\n  | AS_Minus1 : forall st a1 a1' a2,\n      astep st\n        a1 a1' ->\n      astep st\n        (AMinus a1 a2) (AMinus a1' a2)\n  | AS_Minus2 : forall st a1 a2 a2',\n      aexp_halt a1 ->\n      astep st\n        a2 a2' ->\n      astep st\n        (AMinus a1 a2) (AMinus a1 a2')\n  | AS_Minus : forall st n1 n2,\n      astep st\n        (AMinus (ANum n1) (ANum n2)) (ANum (n1 - n2))\n\n  | AS_Mult1 : forall st a1 a1' a2,\n      astep st\n        a1 a1' ->\n      astep st\n        (AMult a1 a2) (AMult a1' a2)\n  | AS_Mult2 : forall st a1 a2 a2',\n      aexp_halt a1 ->\n      astep st\n        a2 a2' ->\n      astep st\n        (AMult a1 a2) (AMult a1 a2')\n  | AS_Mult : forall st n1 n2,\n      astep st\n        (AMult (ANum n1) (ANum n2)) (ANum (n1 * n2)).\n\nInductive bexp_halt: bexp -> Prop :=\n  | BH_True : bexp_halt BTrue\n  | BH_False : bexp_halt BFalse.\n\nInductive bstep : state -> bexp -> bexp -> Prop :=\n\n  | BS_Eq1 : forall st a1 a1' a2,\n      astep st\n        a1 a1' ->\n      bstep st\n        (BEq a1 a2) (BEq a1' a2)\n  | BS_Eq2 : forall st a1 a2 a2',\n      aexp_halt a1 ->\n      astep st\n        a2 a2' ->\n      bstep st\n        (BEq a1 a2) (BEq a1 a2')\n  | BS_Eq_True : forall st n1 n2,\n      n1 = n2 ->\n      bstep st\n        (BEq (ANum n1) (ANum n2)) BTrue\n  | BS_Eq_False : forall st n1 n2,\n      n1 <> n2 ->\n      bstep st\n        (BEq (ANum n1) (ANum n2)) BFalse\n\n  | BS_Le1 : forall st a1 a1' a2,\n      astep st\n        a1 a1' ->\n      bstep st\n        (BLe a1 a2) (BLe a1' a2)\n  | BS_Le2 : forall st a1 a2 a2',\n      aexp_halt a1 ->\n      astep st\n        a2 a2' ->\n      bstep st\n        (BLe a1 a2) (BLe a1 a2')\n  | BS_Le_True : forall st n1 n2,\n      n1 <= n2 ->\n      bstep st\n        (BLe (ANum n1) (ANum n2)) BTrue\n  | BS_Le_False : forall st n1 n2,\n      n1 > n2 ->\n      bstep st\n        (BLe (ANum n1) (ANum n2)) BFalse\n\n  | BS_NotStep : forall st b1 b1',\n      bstep st\n        b1 b1' ->\n      bstep st\n        (BNot b1) (BNot b1')\n  | BS_NotTrue : forall st,\n      bstep st\n        (BNot BTrue) BFalse\n  | BS_NotFalse : forall st,\n      bstep st\n        (BNot BFalse) BTrue\n\n  | BS_AndStep : forall st b1 b1' b2,\n      bstep st\n        b1 b1' ->\n      bstep st\n       (BAnd b1 b2) (BAnd b1' b2)\n  | BS_AndTrue : forall st b,\n      bstep st\n       (BAnd BTrue b) b\n  | BS_AndFalse : forall st b,\n      bstep st\n       (BAnd BFalse b) BFalse.\n       \n   \nDefinition multi_astep (st: state): aexp -> aexp -> Prop := clos_refl_trans (astep st).\n\nDefinition multi_bstep (st: state): bexp -> bexp -> Prop := clos_refl_trans (bstep st).\n\n\nTheorem multi_congr_APlus1: forall st a1 a1' a2,\n  multi_astep st a1 a1' ->\n  multi_astep st (a1 + a2) (a1' + a2).\nProof.\n  intros.\n  induction_n1 H.\n  + reflexivity.\n  + etransitivity_n1.\n    - apply IHrt.\n    - apply AS_Plus1.\n      exact H.\nQed.\n\n\nTheorem multi_congr_APlus2: forall st a1 a2 a2',\n  aexp_halt a1 ->\n  multi_astep st a2 a2' ->\n  multi_astep st (a1 + a2) (a1 + a2').\nProof.\n  intros.\n  induction_n1 H0.\n  + reflexivity.\n  + etransitivity_n1.\n    - apply IHrt.\n    - apply AS_Plus2.\n      * exact H.\n      * exact H0.\nQed.\n\n\nTheorem multi_congr_AMinus1: forall st a1 a1' a2,\n  multi_astep st a1 a1' ->\n  multi_astep st (a1 - a2) (a1' - a2).\nProof.\n  intros.\n  induction_n1 H.\n  + reflexivity.\n  + etransitivity_n1.\n    - apply IHrt.\n    - apply AS_Minus1.\n      exact H.\nQed.\n\nTheorem multi_congr_AMinus2: forall st a1 a2 a2',\n  aexp_halt a1 ->\n  multi_astep st a2 a2' ->\n  multi_astep st (a1 - a2) (a1 - a2').\nProof.\n  intros.\n  induction_n1 H0.\n  + reflexivity.\n  + etransitivity_n1.\n    - apply IHrt.\n    - apply AS_Minus2.\n      * exact H.\n      * exact H0.\nQed.\n\nTheorem multi_congr_AMult1: forall st a1 a1' a2,\n  multi_astep st a1 a1' ->\n  multi_astep st (a1 * a2) (a1' * a2).\nProof.\n  intros.\n  induction_n1 H.\n  + reflexivity.\n  + etransitivity_n1.\n    - apply IHrt.\n    - apply AS_Mult1.\n      exact H.\nQed.\n\nTheorem multi_congr_AMult2: forall st a1 a2 a2',\n  aexp_halt a1 ->\n  multi_astep st a2 a2' ->\n  multi_astep st (a1 * a2) (a1 * a2').\nProof.\n  intros.\n  induction_n1 H0.\n  + reflexivity.\n  + etransitivity_n1.\n    - apply IHrt.\n    - apply AS_Mult2.\n      * exact H.\n      * exact H0.\nQed.\n\n\nLocal Open Scope imp.\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,\n      cstep (Skip ;; c2, st) (c2, st)\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        \n(* ================================================================= *)\n(** ** Multi-step Relation *)\nDefinition multi_cstep: com * state -> com * state -> Prop :=\n  clos_refl_trans cstep.\n\nTheorem multi_congr_CSeq: forall st1 c1 st1' c1' c2,\n  multi_cstep (c1, st1) (c1', st1') ->\n  multi_cstep (c1 ;; c2, st1) (c1';; c2, st1').\nProof.\n  intros.\n  induction_n1 H.\n  + reflexivity.\n  + etransitivity_n1.\n    - apply IHrt.\n    - apply CS_SeqStep.\n      exact H.\nQed.\n\nTheorem multi_congr_CIf: forall st b b' c1 c2,\n  multi_bstep st b b' ->\n  multi_cstep\n    (If b Then c1 Else c2 EndIf, st)\n    (If b' Then c1 Else c2 EndIf, st).\nProof.\n  intros.\n  induction_n1 H.\n  + reflexivity.\n  + etransitivity_n1.\n    - exact IHrt.\n    - apply CS_IfStep.\n      exact H.\nQed.\n", "meta": {"author": "wangshanyw", "repo": "CS263-Programming-Language-Project", "sha": "6a4ac5895d018349645805b77ab129ee199d7b99", "save_path": "github-repos/coq/wangshanyw-CS263-Programming-Language-Project", "path": "github-repos/coq/wangshanyw-CS263-Programming-Language-Project/CS263-Programming-Language-Project-6a4ac5895d018349645805b77ab129ee199d7b99/Small_Step_Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139576, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6691666563066073}}
{"text": "Require Import Coq.Arith.EqNat.\nRequire Import Coq.Relations.Relations.\nRequire Import Coq.Sorting.Permutation.\n\nRequire Import Bitoychain.Coqlib.\nRequire Import Bitoychain.Integers.\n\nRequire Import Bitoychain.Coqlib2.\nRequire Export Bitoychain.eq_dec.\n\nLemma max_two_power_nat: forall n1 n2, Z.max (two_power_nat n1) (two_power_nat n2) = two_power_nat (Nat.max n1 n2).\nProof.\n  intros.\n  rewrite !two_power_nat_two_p.\n  pose proof Zle_0_nat n1; pose proof Zle_0_nat n2.\n  rewrite Nat2Z.inj_max.\n  forget (Z.of_nat n1) as m1; forget (Z.of_nat n2) as m2.\n  destruct (Z_le_dec m1 m2).\n  + rewrite (Z.max_r m1 m2) by omega.\n    apply Z.max_r.\n    apply two_p_monotone; omega.\n  + rewrite (Z.max_l m1 m2) by omega.\n    apply Z.max_l.\n    apply two_p_monotone; omega.\nQed.\n\nLemma Z_max_two_p: forall m1 m2, (exists n, m1 = two_power_nat n) -> (exists n, m2 = two_power_nat n) -> (exists n, Z.max m1 m2 = two_power_nat n).\nProof.\n  intros ? ? [? ?] [? ?].\n  subst.\n  rewrite max_two_power_nat.\n  eexists; reflexivity.\nQed.\n\nLemma power_nat_divide: forall n m, two_power_nat n <= two_power_nat m -> Z.divide (two_power_nat n) (two_power_nat m).\nProof.\n  intros.\n  repeat rewrite two_power_nat_two_p in *.\n  unfold Zdivide.\n  exists (two_p (Z.of_nat m - Z.of_nat n)).\n  assert ((Z.of_nat m) = (Z.of_nat m - Z.of_nat n) + Z.of_nat n) by omega.\n  rewrite H0 at 1.\n  assert (Z.of_nat m >= 0) by omega.\n  assert (Z.of_nat n >= 0) by omega.\n  assert (Z.of_nat n <= Z.of_nat m).\n    destruct (Z_le_gt_dec (Z.of_nat n) (Z.of_nat m)).\n    exact l.\n    assert (Z.of_nat m < Z.of_nat n) by omega.\n    assert (two_p (Z.of_nat m) < two_p (Z.of_nat n)) by (apply two_p_monotone_strict; omega).\n    omega.\n  apply (two_p_is_exp (Z.of_nat m - Z.of_nat n) (Z.of_nat n)); omega.\nQed.\n\nLemma power_nat_divide_ge: forall n m: Z,\n  (exists N, n = two_power_nat N) ->\n  (exists M, m = two_power_nat M) ->\n  (n >= m <-> (m | n)).\nProof.\n  intros.\n  destruct H, H0.\n  split; intros.\n  + subst.\n    apply power_nat_divide.\n    omega.\n  + destruct H1 as [k ?].\n    rewrite H1.\n    pose proof two_power_nat_pos x0.\n    pose proof two_power_nat_pos x.\n    assert (k > 0).\n    Focus 1. {\n      eapply Zmult_gt_0_reg_l.\n      + exact H2.\n      + rewrite <- H0, Z.mul_comm; omega.\n    } Unfocus.\n    rewrite <- (Z.mul_1_l m) at 2.\n    apply Zmult_ge_compat_r; omega.\nQed.\n\nLemma power_nat_divide_le: forall n m: Z,\n  (exists N, n = two_power_nat N) ->\n  (exists M, m = two_power_nat M) ->\n  (m <= n <-> (m | n)).\nProof.\n  intros.\n  rewrite <- power_nat_divide_ge; auto.\n  omega.\nQed.\n\nLemma two_p_max_divide: forall m1 m2 m, (exists n, m1 = two_power_nat n) -> (exists n, m2 = two_power_nat n) -> ((Z.max m1 m2 | m) <-> (m1 | m) /\\ (m2 | m)).\nProof.\n  intros.\n  destruct (Z_le_dec m1 m2).\n  + rewrite Z.max_r by omega.\n    rewrite power_nat_divide_le in l by auto.\n    pose proof Zdivides_trans m1 m2 m.\n    tauto.\n  + rewrite Z.max_l by omega.\n    assert (m2 <= m1) by omega.\n    rewrite power_nat_divide_le in H1 by auto.\n    pose proof Zdivides_trans m2 m1 m.\n    tauto.\nQed.\n\nLemma two_p_max_1: forall m1 m2, (exists n, m1 = two_power_nat n) -> (exists n, m2 = two_power_nat n) -> (Z.max m1 m2 = 1 <-> m1 = 1 /\\ m2 = 1).\nProof.\n  assert (forall x, (exists n : nat, x = two_power_nat n) -> (x = 1 <-> (x | 1))).\n  + intros.\n    split; intros.\n    - subst.\n      exists 1; auto.\n    - rewrite <- power_nat_divide_le in H0 by (auto; exists 0%nat; auto).\n      destruct H as [n ?]; subst x.\n      pose proof two_power_nat_pos n.\n      omega.\n  + intros m1 m2 Hm1 Hm2.\n    pose proof Z_max_two_p _ _ Hm1 Hm2 as Hmax.\n    rewrite (H _ Hm1), (H _ Hm2), (H _ Hmax).\n    apply two_p_max_divide; auto.\nQed.\n\nLemma two_power_nat_0: forall x, (exists n, x = two_power_nat n) -> x <> 0.\nProof.\n  intros.\n  destruct H.\n  pose proof two_power_nat_pos x0.\n  omega.\nQed.\n\nHint Rewrite andb_true_iff: align.\nHint Rewrite <- Zle_is_le_bool: align.\nHint Rewrite Z.eqb_eq: align.\nHint Rewrite power_nat_divide_le using (auto with align): align.\nHint Rewrite Z.mod_divide using (apply two_power_nat_0; auto with align): align.\nHint Rewrite two_p_max_divide using (auto with align): align.\nHint Rewrite two_p_max_1 using (auto with align): align.\nHint Resolve Z_max_two_p: align.\n\nLemma Z_of_nat_ge_O: forall n, Z.of_nat n >= 0.\nProof. intros.\nchange 0 with (Z.of_nat O).\napply inj_ge. clear; omega.\nQed.\n\nLemma nth_error_nth:\n  forall A (al: list A) (z: A) i, (i < length al)%nat -> nth_error al i = Some (nth i al z).\nProof.\nintros. revert al H; induction i; destruct al; simpl; intros; auto; try omega.\napply IHi. omega.\nQed.\n\nLemma nat_of_Z_eq: forall i, nat_of_Z (Z_of_nat i) = i.\nProof.\nintros.\napply inj_eq_rev.\nrewrite nat_of_Z_eq; auto.\nomega.\nQed.\n\nLemma nth_error_length:\n  forall {A} i (l: list A), nth_error l i = None <-> (i >= length l)%nat.\nProof.\ninduction i; destruct l; simpl; intuition.\ninv H.\ninv H.\nrewrite IHi in H. omega.\nrewrite IHi. omega.\nQed.\n\nLemma prop_unext: forall P Q: Prop, P=Q -> (P<->Q).\nProof. intros. subst; split; auto. Qed.\n\nLemma list_norepet_In_In: forall {K X} a x y (l:list (K*X)),\n  list_norepet (map (@fst K X) l) -> In (a, x) l -> In (a, y) l -> x = y.\nProof.\n  induction l; intros N Ix Iy.\n   - inv Ix.\n   - simpl in N; inv N.\n     destruct Ix.\n     + subst.\n       simpl in Iy; destruct Iy as [|Iy]; [congruence|].\n       exfalso; apply (in_map (@fst K X)) in Iy; tauto.\n     + simpl in Iy; destruct Iy as [|Iy].\n       subst. exfalso; apply (in_map (@fst K X)) in H; tauto.\n       apply IHl; auto.\nQed.\n\nInductive sublist {A} : list A -> list A -> Prop :=\n| sublist_nil : sublist nil nil\n| sublist_cons a l1 l2 : sublist l1 l2 -> sublist (a :: l1) (a :: l2)\n| sublist_drop a l1 l2 : sublist l1 l2 -> sublist l1 (a :: l2).\n\nLemma sublist_In {A} (a : A) l1 l2 : sublist l1 l2 -> In a l1 -> In a l2.\nProof.\n  intros S; induction S; intros I.\n  - inversion I.\n  - simpl in I; destruct I.\n    subst; left; auto.\n    right; auto.\n  - right; auto.\nQed.\n\nLemma sublist_norepet {A} (l1 l2 : list A) : sublist l1 l2 -> list_norepet l2 -> list_norepet l1.\nProof.\n  intros S; induction S; intros N; auto.\n  - inversion N; subst; constructor; auto.\n    pose proof sublist_In a l1 l2; auto.\n  - inversion N; auto.\nQed.\n\nRequire Import Coq.Sets.Ensembles.\n\nDefinition Ensemble_join {A} (X Y Z: Ensemble A): Prop :=\n  (forall a, Z a <-> X a \\/ Y a) /\\ (forall a, X a -> Y a -> False).\n\nRequire Coq.Logic.ConstructiveEpsilon.\n\nLemma decidable_countable_ex_sig {A} (f : nat -> A)\n      (Hf : forall a, exists n, a = f n)\n      (P : A -> Prop)\n      (Pdec : forall x, {P x} + {~ P x}) :\n  (exists x : A, P x) -> {x : A | P x}.\nProof.\n  intros E.\n  cut ({n | P (f n)}). intros [n Hn]; eauto.\n  apply ConstructiveEpsilon.constructive_indefinite_ground_description_nat.\n  intro; apply Pdec.\n  destruct E as [x Hx].\n  destruct (Hf x) as [n ->].\n  eauto.\nQed.\n\n(** Additions to [if_tac]: when mature, move these upstream *)\n\nTactic Notation \"if_tac\" \"eq:\" simple_intropattern(E) :=\n  match goal with\n    |- context [if ?a then _ else _] =>\n    destruct a as [?H | ?H] eqn:E\n  end.\n\nTactic Notation \"if_tac\" simple_intropattern(H) \"eq:\" simple_intropattern(E):=\n  match goal with\n    |- context [if ?a then _ else _] =>\n    destruct a as H eqn:E\n  end.\n\nTactic Notation \"if_tac\" \"in\" hyp(H0) \"eq:\" simple_intropattern(E) :=\n  match type of H0 with\n    context [if ?a then _ else _] =>\n    destruct a as [?H  | ?H] eqn:E\n  end.\n\nTactic Notation \"if_tac\" simple_intropattern(H) \"in\" hyp(H1) \"eq:\" simple_intropattern(E) :=\n  match type of H1 with\n    context [if ?a then _ else _] =>\n    destruct a as H eqn:E\n  end.\n\n(** Specializing a hypothesis with a newly created goal *)\n\nTactic Notation \"assert_specialize\" hyp(H) :=\n  match type of H with\n    forall x : ?P, _ =>\n    let Htemp := fresh \"Htemp\" in\n    assert P as Htemp; [ | specialize (H Htemp); try clear Htemp ]\n  end.\n\nTactic Notation \"assert_specialize\" hyp(H) \"by\" tactic(tac) :=\n  match type of H with\n    forall x : ?P, _ =>\n    let Htemp := fresh \"Htemp\" in\n    assert P as Htemp by tac; specialize (H Htemp); try clear Htemp\n  end.\n\nTactic Notation \"assert_specialize\" hyp(H) \"as\" simple_intropattern(Hnew) :=\n  match type of H with\n    forall x : ?P, _ =>\n    assert P as Hnew; [ | specialize (H Hnew) ]\n  end.\n\nTactic Notation \"assert_specialize\" hyp(H) \"as\" simple_intropattern(Hnew) \"by\" tactic(tac) :=\n  match type of H with\n    forall x : ?P, _ =>\n    assert P as Hnew by tac;\n    specialize (H Hnew)\n  end.\n\n(** Auto-specializing a hypothesis *)\n\nLtac autospec H := specialize (H ltac:(solve [eauto])).\n\n(** When a hypothesis/term is provably equal, but not convertible, to\n    your goal *)\n\nLtac exact_eq H :=\n  revert H;\n  match goal with\n    |- ?p -> ?q => cut (p = q); [intros ->; auto | ]\n  end.\n\n(** Auto rewriting of a term *)\n\nTactic Notation \"rewr\" :=\n  match goal with\n  | H : ?f = _ |- context [?f] => rewrite H\n  | H : ?f _ = ?f _ |- _ => try (injection H; repeat intros ->)\n  end.\n\nTactic Notation \"rewr\" constr(e) :=\n  match goal with\n    E : e = _ |- _ => rewrite E\n  | E : _ = e |- _ => rewrite <-E\n  end.\n\nTactic Notation \"rewr\" constr(e) \"in\" \"*\" :=\n  match goal with\n    E : e = _ |- _ => rewrite E in *\n  | E : _ = e |- _ => rewrite <-E in *\n  end.\n\nTactic Notation \"rewr\" constr(e) \"in\" hyp(H) :=\n  match goal with\n    E : e = _ |- _ => rewrite E in H\n  | E : _ = e |- _ => rewrite <-E in H\n  end.\n\nLemma perm_search:\n  forall {A} (a b: A) r s t,\n     Permutation (a::t) s ->\n     Permutation (b::t) r ->\n     Permutation (a::r) (b::s).\nProof.\nintros.\neapply perm_trans.\napply perm_skip.\napply Permutation_sym.\napply H0.\neapply perm_trans.\napply perm_swap.\napply perm_skip.\napply H.\nQed.\n\nLemma Permutation_concat: forall {A} (P Q: list (list A)),\n  Permutation P Q ->\n  Permutation (concat P) (concat Q).\nProof.\n  intros.\n  induction H.\n  + apply Permutation_refl.\n  + simpl.\n    apply Permutation_app_head; auto.\n  + simpl.\n    rewrite !app_assoc.\n    apply Permutation_app_tail.\n    apply Permutation_app_comm.\n  + eapply Permutation_trans; eauto.\nQed.    \n\nLemma Permutation_app_comm_trans:\n forall (A: Type) (a b c : list A),\n   Permutation (b++a) c ->\n   Permutation (a++b) c.\nProof.\nintros.\neapply Permutation_trans.\napply Permutation_app_comm.\nauto.\nQed.\n\nLtac solve_perm :=\n    (* solves goals of the form (R ++ ?i = S)\n          where R and S are lists, and ?i is a unification variable *)\n  try match goal with\n       | |-  Permutation (?A ++ ?B) _ =>\n            is_evar A; first [is_evar B; fail 1| idtac];\n            apply Permutation_app_comm_trans\n       end;\n  repeat first [ apply Permutation_refl\n       | apply perm_skip\n       | eapply perm_search\n       ].\n\nGoal exists e, Permutation ((1::2::nil)++e) (3::2::1::5::nil).\neexists.\nsolve_perm.\nQed.\n\nLemma range_pred_dec: forall (P: nat -> Prop),\n  (forall n, {P n} + {~ P n}) ->\n  forall m,\n    {forall n, (n < m)%nat -> P n} + {~ forall n, (n < m)%nat -> P n}.\nProof.\n  intros.\n  induction m.\n  + left.\n    intros; omega.\n  + destruct (H m); [destruct IHm |].\n    - left.\n      intros.\n      destruct (eq_dec n m).\n      * subst; auto.\n      * apply p0; omega.\n    - right.\n      intro.\n      apply n; clear n.\n      intros; apply H0; omega.\n    - right.\n      intro.\n      apply n; clear n.\n      apply H0.\n      omega.\nQed.\n\nLemma Z2Nat_neg: forall i, i < 0 -> Z.to_nat i = 0%nat.\nProof.\n  intros.\n  destruct i; try reflexivity.\n  pose proof Zgt_pos_0 p; omega.\nQed.\n\nLemma Zrange_pred_dec: forall (P: Z -> Prop),\n  (forall z, {P z} + {~ P z}) ->\n  forall l r,  \n    {forall z, l <= z < r -> P z} + {~ forall z, l <= z < r -> P z}.\nProof.\n  intros.\n  assert ((forall n: nat, (n < Z.to_nat (r - l))%nat -> P (l + Z.of_nat n)) <-> (forall z : Z, l <= z < r -> P z)).\n  Focus 1. {\n    split; intros.\n    + specialize (H0 (Z.to_nat (z - l))).\n      rewrite <- Z2Nat.inj_lt in H0 by omega.\n      spec H0; [omega |].\n      rewrite Z2Nat.id in H0 by omega.\n      replace (l + (z - l)) with z in H0 by omega.\n      auto.\n    + apply H0.\n      rewrite Nat2Z.inj_lt in H1.\n      destruct (zlt (r - l) 0).\n      - rewrite Z2Nat_neg in H1 by omega.\n        simpl in H1.\n        omega.\n      - rewrite Z2Nat.id in H1 by omega.\n        omega.\n  } Unfocus.\n  eapply sumbool_dec_iff; [clear H0 | eassumption].\n  apply range_pred_dec.\n  intros.\n  apply H.\nQed.\n\nDefinition eqb_list {A: Type} (eqb_A: A -> A -> bool): list A -> list A -> bool :=\n  fix eqb_list (l1 l2: list A): bool :=\n    match l1, l2 with\n    | nil, nil => true\n    | a1 :: l1, a2 :: l2 => eqb_A a1 a2 && eqb_list l1 l2\n    | _, _ => false\n    end.\n\nLemma eqb_list_spec: forall {A: Type} (eqb_A: A -> A -> bool),\n  (forall a1 a2, eqb_A a1 a2 = true <-> a1 = a2) ->\n  (forall l1 l2, eqb_list eqb_A l1 l2 = true <-> l1 = l2).\nProof.\n  intros.\n  revert l2; induction l1 as [| a1 l1]; intros; destruct l2 as [| a2 l2].\n  + simpl.\n    tauto.\n  + simpl.\n    split; intros; congruence.\n  + simpl.\n    split; intros; congruence.\n  + simpl.\n    rewrite andb_true_iff.\n    rewrite  H.\n    rewrite IHl1.\n    split; intros.\n    - destruct H0; subst; auto.\n    - inv H0; auto.\nQed.\n", "meta": {"author": "palmskog", "repo": "bitoychain", "sha": "342e7829a98d7e1cd2fd0c42c9d1daafdf8e399e", "save_path": "github-repos/coq/palmskog-bitoychain", "path": "github-repos/coq/palmskog-bitoychain/bitoychain-342e7829a98d7e1cd2fd0c42c9d1daafdf8e399e/SHA256/coqlib4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6691666541789068}}
{"text": "(* Exercise 13 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_013 : (exists x : D, P x \\/ Q x) -> (forall x : D, ~(Q x)) -> (exists x : D, P x).\nProof.\nimp_i a1.\nimp_i a2.\nexi_e (exists x:D, P x \\/ Q x) a a3.\nhyp a1.\nexi_i a.\ndis_e (P a \\/ Q a) a4 a4.\nhyp a3.\nhyp a4.\nneg_e (Q a).\nall_e (forall x:D, ~Q x) a.\nhyp a2.\nhyp a4.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred013.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6690836368402654}}
{"text": "Require Export Coq.Strings.String.\nRequire Export Coq.Bool.Bool.\nRequire Export Compare_dec.\nRequire Export Coq.Lists.List.\nRequire Export DPLL.ExplicitName.\nExport ListNotations.\n\n\n(* ***************************************************************** *)\n(*                                                                   *)\n(*                                                                   *)\n(*  Definition of DPLL                                               *)\n(*                                                                   *)\n(*                                                                   *)\n(* ***************************************************************** *)\n\n(* ***************************************************************** *)\n(*                                                                   *)\n(*  Definition of CNF propositions                                   *)\n(*                                                                   *)\n(* ***************************************************************** *)\n\n(** PV is imported from ExplicitName. You do not need to read those\n    details. It is about string and string comparisons. *)\nModule PV := StringName.\n\n(** ident:Type of variables. Here, _[PV.t]_ is just string. *)\nDefinition ident := PV.t.\n\n(** clause: list of literals.\n      - true: positive literal\n      - false: negative literal *)\nDefinition clause := list (bool * ident).\n\nDefinition CNF := list clause.\n\n(* ***************************************************************** *)\n(*                                                                   *)\n(*  Definition of Assignments                                        *)\n(*                                                                   *)\n(* ***************************************************************** *)\n\n(** partial_asgn: list of variables and their values *)\nDefinition partial_asgn := list (ident * bool).\n\n(** asgn: value of all variables, total function *)\nDefinition asgn:= ident-> bool.\n\n(** PV.look_up: find the value of x in partial_asgn J *)\nPrint PV.look_up.\n\n(* ***************************************************************** *)\n(*                                                                   *)\n(*  Unit Propagation                                                 *)\n(*                                                                   *)\n(* ***************************************************************** *)\n\n(** We define _[unit_pro]_ to improve a partial assignment. The return\n    value is _[None]_ is a conflict can be derived. *)\n\nInductive UP_result :=\n| Conflict\n| UP (x: ident) (b: bool)\n| Nothing.\n\n(** Construct UP_result from a clause c.\nIf all literals in c contradicts with J, return Conflict.\nIf there is only one literal (op, x) that is not assgined in J, return UP x op.\nO.w., return Nothing. *)\nFixpoint find_unit_pro_in_clause (c: clause) (J: partial_asgn) (cont: UP_result): UP_result :=\n  match c with\n  | nil => cont\n  | (op, x) :: c' =>\n      match PV.look_up x J with\n      | None => match cont with\n                | Conflict => find_unit_pro_in_clause c' J (UP x op)\n                | UP _ _ => Nothing\n                | _ => Nothing\n                end\n      | Some b => if eqb op b then Nothing else find_unit_pro_in_clause c' J cont\n      end\n  end.\n\nDefinition unit_pro' (P: CNF) (J: partial_asgn): list UP_result :=\n  map (fun c => find_unit_pro_in_clause c J Conflict) P.\n\n (* Type of fold_left: (A -> B -> A) -> list B -> A -> A. \nBelow, A is option partial_asgn and B is UP_res. *)\nCheck fold_left.\nPrint fold_left.\n(** Construct partial asgn from a list of UP_result. *)\nDefinition fold_UP_result (rs: list UP_result): option partial_asgn :=\n  fold_left (fun (o: option partial_asgn) (r: UP_result) =>\n               match r, o with\n               | _, None => None\n               | Nothing, _ => o\n               | Conflict, _ => None\n               | UP x b, Some J => Some ((x, b) :: J)\n               end) rs (Some nil).\n\n(** Improve partial_asgn by unit propagation. *)\nDefinition unit_pro (P: CNF) (J: partial_asgn): option partial_asgn :=\n  fold_UP_result (unit_pro' P J).\n  \n(* ***************************************************************** *)\n(*                                                                   *)\n(*  Filter                                                           *)\n(*                                                                   *)\n(* ***************************************************************** *)\n\n(** Literal of value false will be eliminated by _[clause_filter]_ from\n    a clause. Literals of value true and literals of an unknown value\n    will be left. *)\nDefinition clause_filter (J: partial_asgn) (c: clause): clause :=\n  filter (fun opx: bool * ident =>\n            match opx with\n            | (op, x) => match PV.look_up x J with\n                         | None => true\n                         | Some b => eqb b op\n                         end\n            end) c.\n\n(** This function _[clause_not_ex_true]_ tests whether no literal in the\n    clause is known to be true. *)\nDefinition clause_not_ex_true (J: partial_asgn) (c: clause): bool :=\n  negb \n  (existsb\n      (fun opx: bool * ident =>\n            match opx with\n            | (op, x) => match PV.look_up x J with\n                         | None => false\n                         | Some b => eqb b op\n                         end\n            end) c).\n\n(** After all, literals that are known to be false are eliminated;\n    clauses with at least one literal known to be true are alsi\n    eliminated. *)\nDefinition CNF_filter (P: CNF) (J: partial_asgn): CNF :=\n  map (clause_filter J) (filter (clause_not_ex_true J) P).\n  \n(* ***************************************************************** *)\n(*                                                                   *)\n(*  DPLL                                                             *)\n(*                                                                   *)\n(* ***************************************************************** *)\n\n(* Pick P is the first identifier of P. *)\nDefinition pick (P: CNF): ident :=\n  match P with\n  | ((_, x) :: _) :: _ => x\n  | _ => \"impossible\"%string\n  end.\n\nFixpoint DPLL_UP (P: CNF) (J: partial_asgn) (n: nat): bool :=\n  match n with \n  | O => true \n  | S n' =>\n    match unit_pro P J with  (* apply unit propagation to improve assignment *)\n    | None => false\n    | Some kJ => \n      match kJ with\n        | nil => DPLL_filter P J n'  (* no unit, filter by assignment *)\n        | _ => DPLL_UP P (kJ ++ J) n' (* improve assignment *)\n      end\n    end\n  end\nwith DPLL_filter (P: CNF) (J: partial_asgn) (n: nat): bool :=\n  match n with \n    | O => true\n    | S n' => DPLL_pick (CNF_filter P J) nil n' (* eliminate literals that are already known *)\n  end\nwith DPLL_pick (P: CNF) (J: partial_asgn) (n: nat): bool :=\n  match n with \n    | O => true\n    | S n' =>\n      let x := pick P in\n      DPLL_UP P ((x, true) :: J) n' || DPLL_UP P ((x, false) :: J) n'  (* DFS *)\n  end.\n\n(* ***************************************************************** *)\n(*                                                                   *)\n(*  Examples                                                         *)\n(*                                                                   *)\n(* ***************************************************************** *)\n\nLocal Open Scope string.\n\nDefinition cnf1 :=\n  ((true, \"x\") :: (true, \"y\") :: nil) :: ((true, \"x\") :: (false, \"y\") :: nil) :: nil.\n\nEval compute in (DPLL_UP cnf1 nil 6).\n\nDefinition cnf2 :=\n  ((true, \"x\") :: (true, \"y\") :: nil) :: ((true, \"x\") :: (false, \"y\") :: nil) :: ((false, \"x\") :: nil) :: nil.\n\nEval compute in (DPLL_UP cnf2 nil 6).\n\nDefinition cnf3 :=\n  ((false, \"x\") :: (true, \"y\") :: nil) ::\n  ((false, \"y\") :: (true, \"z\") :: nil) ::\n  ((false, \"z\") :: (true, \"w\") :: nil) ::\n  ((true, \"x\") :: nil) ::\n  ((false, \"w\") :: nil) :: nil.\n\nEval compute in (DPLL_UP cnf3 nil 12).\nClose Scope string.\n\n(* ***************************************************************** *)\n(*                                                                   *)\n(*                                                                   *)\n(*  Definition of Satisfiability                                     *)\n(*                                                                   *)\n(*                                                                   *)\n(* ***************************************************************** *)\n\nLemma ident_eqdec: forall x y: ident, {x=y}+{x<>y}. \nProof. apply string_dec. Qed.\n\nCheck PV.eqb_eq.\n\nCheck PV.eqb_neq.\n\nCheck Bool.eqb_true_iff.\n\nCheck Bool.eqb_false_iff.\n\nDefinition asgn_match(J:partial_asgn)(B:asgn):=\n  forall x b, PV.look_up x J = Some b -> B x = b. \n\nDefinition expand(J:partial_asgn): asgn:=\n  fun x =>\n    match PV.look_up x J with\n    | Some b => b\n    | None => true\n    end.\n\n\nDefinition set_ident(B:asgn)(s:ident)(b:bool):asgn:=\n  fun x => if ident_eqdec x s then b else B x.\n  \n(** CNF_sat: CNF -> asgn -> bool *)\nDefinition literal_sat(l: bool * ident)(B:asgn):bool:=\n  match l with\n  | (b,x) => eqb b (B x)\n  end. \n\nPrint fold_right.  \n\n (* Type of fold_right: (B -> A -> A) -> A -> list B -> A. \nBelow, A is bool and B is (bool * ident). *)\nDefinition clause_sat(C:clause)(B:asgn):bool:=\n  fold_right (fun l => orb (literal_sat l B)) false C.\n\n(* Below, A is bool and B is clause. *)\nDefinition CNF_sat (P:CNF)(B:asgn):bool:=\n  fold_right (fun c => andb (clause_sat c B)) true P.\n\n(* ***************************************************************** *)\n(*                                                                   *)\n(*                                                                   *)\n(*  Your goal: prove CNF is not satisfiable if DPLL returns false    *)\n(*                                                                   *)\n(*                                                                   *)\n(* ***************************************************************** *)\n\n(**  Proving following lemmas may be helpful.\n\n     But you can ignore them if you can prove the final theorem\n     _[DPLL_sound]_ without these lemmas. *)\n\nLemma UP_cannot_to_Conflict: forall c J x op,\n  find_unit_pro_in_clause c J (UP x op) = Conflict -> False.\nProof.\n  intros.\n  induction c.\n  + simpl in H. discriminate H.\n  + simpl in H.\n      destruct a as (op0, x0).\n      destruct (PV.look_up x0 J) eqn:?.\n      - destruct (eqb op0 b) eqn:?.\n        * discriminate H.\n        * tauto.\n      - discriminate H.\nQed.\n\nLemma find_unit_pro_in_clause_Conflict:\n  forall c J B,\n    find_unit_pro_in_clause c J Conflict = Conflict ->\n    asgn_match J B ->\n    clause_sat c B = false.\nProof.\n  intros.\n  induction c.\n  + simpl. tauto.\n  + simpl.\n      unfold orb.\n      destruct (literal_sat a B) eqn:?.\n      - simpl in H.\n        destruct a as (op,x).\n        destruct (PV.look_up x J) eqn:?.\n        * unfold asgn_match in H0.\n           specialize (H0 x b).\n           specialize (H0 Heqo).\n           unfold literal_sat in Heqb.\n           rewrite H0 in Heqb.\n           rewrite Heqb in H.\n           discriminate H.\n        * specialize (UP_cannot_to_Conflict c J x op). tauto.\n      - apply IHc.\n        simpl in H.\n        destruct a as (op,x).\n        destruct (PV.look_up x J) eqn:?.\n        * unfold asgn_match in H0.\n           specialize (H0 x b).\n           specialize (H0 Heqo).\n           unfold literal_sat in Heqb.\n           rewrite H0 in Heqb.\n           rewrite Heqb in H.\n           tauto.\n        * specialize (UP_cannot_to_Conflict c J x op). tauto.\nQed.\n\nLemma UP_remain:\n  forall c J x b x0 b0,\n    find_unit_pro_in_clause c J (UP x0 b0) = UP x b ->\n    (x = x0 /\\ b = b0).\nProof.\n  intros.\n  induction c.\n  + simpl in H. injection H. auto.\n  + simpl in H. destruct a as (op,x1).\n      destruct (PV.look_up x1 J) eqn:H1.\n      - destruct (eqb op b1) eqn:Hop.\n        * discriminate H.\n        * auto.\n      - discriminate H.\nQed.\n\nLemma UP_unchange_implies_unmatch:\n  forall c J B x b,\n    find_unit_pro_in_clause c J (UP x b) = UP x b ->\n    clause_sat c B = true ->\n    asgn_match J B ->\n    False.\nProof.\n  intros.\n  induction c.\n  + simpl in H0. discriminate H0.\n  + destruct a as (b0, x0).\n      simpl in H0.\n      unfold orb in H0.\n      destruct (eqb b0 (B x0)) eqn:Hb0.\n      - simpl in H.\n        destruct (PV.look_up x0 J) eqn:?.\n        * destruct (eqb b0 b1) eqn:Hb1.\n          ++ discriminate H.\n          ++ unfold asgn_match in H1.\n                specialize (H1 x0 b1 Heqo).\n                rewrite eqb_true_iff in Hb0.\n                rewrite <- Hb0 in H1.\n                rewrite eqb_false_iff in Hb1. auto.\n        * discriminate H. \n      - apply IHc; try tauto. clear IHc.\n        simpl in H.\n        destruct (PV.look_up x0 J) eqn:?.\n        * destruct (eqb b0 b1) eqn:Hb1.\n           ++ discriminate H.\n           ++ tauto.\n        * discriminate H.\nQed.\n\nLemma find_unit_pro_in_clause_Conflict_UP:\n  forall c J B x b,\n    find_unit_pro_in_clause c J Conflict = UP x b ->\n    asgn_match J B ->\n    clause_sat c B = true ->\n    asgn_match ((x, b) :: J) B.\nProof.\n  intros.\n  induction c; simpl.\n  + unfold clause_sat in *; unfold fold_right in *; discriminate.\n  + destruct a as [op id].\n    unfold find_unit_pro_in_clause in *.\n    destruct (PV.look_up id J) eqn:?.\n    - destruct (eqb op b0) eqn:?.\n      -- discriminate.\n      -- pose proof IHc H.\n        simpl in H1.\n        pose proof H0 id b0.\n        specialize (H3 Heqo).\n        rewrite H3 in H1.\n        rewrite Heqb1 in H1.\n        simpl in H1.\n        specialize (H2 H1).\n        apply H2.\n    - simpl in *.\n      unfold asgn_match in *. \n      simpl in *.\n      intros.\n      destruct (PV.eqb x x0) eqn:?.\n      -- pose proof PV.eqb_eq x x0.\n         rewrite H3 in Heqb1.\n         injection H2. intros. subst x0 b0. simpl in *.\n         assert (find_unit_pro_in_clause c J (UP id op) = UP x b) by auto. clear H.\n         specialize (UP_remain c J x b id op). intros.\n         specialize (H H4). destruct H. subst id op. clear H2 H3.\n         unfold orb in H1.\n         destruct (eqb b (B x)) eqn:HB.\n         * rewrite eqb_true_iff in HB. auto.\n         * specialize (UP_unchange_implies_unmatch c J B x b). intros.\n            specialize (H H4 H1 H0). contradiction H.\n      -- pose proof H0 x0 b0.\n         specialize (H3 H2).\n         apply H3.\nQed.\n\nLemma clause_filter_sat: forall c J B,\n    asgn_match J B ->\n    clause_sat c B = true ->\n    clause_sat (clause_filter J c) B = true.\nProof. \n  intros.\n  unfold asgn_match in H.\n  induction c.\n  + unfold clause_sat in H0; unfold fold_right in H0. discriminate.\n  + simpl.\n    destruct a as [op x].\n    destruct (PV.look_up x J) eqn:?; simpl.\n    - destruct (eqb b op) eqn:?; simpl; apply H in Heqo.\n      --rewrite Heqo. \n        rewrite eqb_true_iff in Heqb0.\n        assert (op = b). { auto. }\n        rewrite <-eqb_true_iff in H1.\n        rewrite H1. simpl; reflexivity. \n      --unfold clause_sat in H0; unfold fold_right in H0; unfold literal_sat in H0.\n        rewrite Heqo in H0.\n        rewrite eqb_false_iff in Heqb0.\n        assert (op <> b). { auto. }\n        rewrite <-eqb_false_iff in H1.\n        rewrite H1 in H0. \n        simpl in H0.\n        specialize (IHc H0); apply IHc.\n    - unfold fold_right in H0; unfold literal_sat in H0.\n      destruct (eqb op (B x)) eqn:?; simpl.\n      --reflexivity.\n      --simpl in H0.\n        rewrite Heqb in H0. \n        simpl in H0.\n        specialize (IHc H0); apply IHc.\nQed.\n\nLemma CNF_filter_sat: forall P J B,\n    asgn_match J B ->\n    CNF_sat P B = true ->\n    CNF_sat (CNF_filter P J ) B = true.\nProof.\n  intros.\n  induction P.\n  + unfold CNF_sat; unfold fold_right; unfold CNF_filter. \n    simpl; reflexivity.\n  + unfold CNF_sat in *; unfold fold_right in *; unfold CNF_filter in *; simpl. \n    destruct (clause_not_ex_true J a) eqn:?; simpl.\n    - destruct (clause_sat a B) eqn:?; simpl.\n      --pose proof clause_filter_sat a J B.\n        pose proof H1 H Heqb0.\n        simpl in H0.\n        specialize (IHP H0).\n        rewrite H2; simpl.\n        apply IHP.\n      --simpl in H0. discriminate.\n    - destruct (clause_sat a B) eqn:?; simpl.\n      --pose proof clause_filter_sat a J B.\n        pose proof H1 H Heqb0.\n        simpl in H0.\n        specialize (IHP H0).\n        apply IHP.\n      --simpl in H0. discriminate.\nQed.\n\nLemma CNF_sat_pick_fail: forall x J B,\n    asgn_match J B ->\n    asgn_match ((x,true)::J) B \\/ asgn_match ((x,false)::J) B.\nProof.\n  intros.\n(*   discuss B x = true or false *)\n  destruct (B x) eqn:?.\n  + left.\n      unfold asgn_match.\n      intros.\n      destruct (ident_eqdec x x0).\n      - subst x0.\n        simpl in H0.\n        destruct (PV.eqb x x) eqn:?.\n        * injection H0.\n           intros. subst b. tauto.\n        * unfold PV.eqb in Heqb0.\n           destruct (PV.eq_dec x x). \n           ++ discriminate Heqb0.\n           ++ contradiction n. tauto.\n      - simpl in H0.\n        destruct (PV.eqb x x0) eqn:?.\n        * unfold PV.eqb in Heqb0.\n          destruct (PV.eq_dec x x0).\n          ++ subst x. contradiction.\n          ++ discriminate Heqb0.\n        * apply H. tauto.\n  + right.\n      unfold asgn_match.\n      intros.\n      destruct (ident_eqdec x x0).\n      - subst x0.\n        simpl in H0.\n        destruct (PV.eqb x x) eqn:?.\n        * injection H0.\n           intros. subst b. tauto.\n        * unfold PV.eqb in Heqb0.\n           destruct (PV.eq_dec x x). discriminate Heqb0. contradiction n. tauto.\n      - simpl in H0.\n        destruct (PV.eqb x x0) eqn:?.\n        * unfold PV.eqb in Heqb0.\n          destruct (PV.eq_dec x x0).\n          ++ subst x. contradiction.\n          ++ discriminate Heqb0.\n        * apply H. tauto.\nQed.\n\nLemma none_implies_none: forall rs,\n  fold_left (fun (o: option partial_asgn) (r: UP_result) =>\n           match r, o with\n           | _, None => None\n           | Nothing, _ => o\n           | Conflict, _ => None\n           | UP x b, Some J => Some ((x, b) :: J)\n           end) rs None = None.\nProof.\n  induction rs; simpl.\n  + tauto.\n  + destruct a; tauto.\nQed.\n\nLemma none_hold: forall rs J1 J2,\n  fold_left (fun (o: option partial_asgn) (r: UP_result) =>\n           match r, o with\n           | _, None => None\n           | Nothing, _ => o\n           | Conflict, _ => None\n           | UP x b, Some J => Some ((x, b) :: J)\n           end) rs (Some J1) = None ->\n  fold_left (fun (o: option partial_asgn) (r: UP_result) =>\n           match r, o with\n           | _, None => None\n           | Nothing, _ => o\n           | Conflict, _ => None\n           | UP x b, Some J => Some ((x, b) :: J)\n           end) rs (Some J2) = None.\nProof.\n  induction rs.\n  + simpl. intros. discriminate H.\n  + intros. simpl in *.\n      destruct a eqn:Ha.\n      - specialize (none_implies_none rs). intros. tauto.\n      - specialize (IHrs ((x, b) :: J1) ((x, b) :: J2)). tauto.\n      - specialize (IHrs J1 J2). tauto.\nQed.\n\nLemma split_keep_none: forall rs x b,\n  fold_UP_result (UP x b :: rs) = None ->\n  fold_UP_result rs = None.\nProof.\n  intros. unfold fold_UP_result in *. simpl in H.\n  specialize (none_hold rs [(x, b)] []). intros. tauto.\nQed.\n\nLemma none_remain: forall rs x b,\n  fold_UP_result rs = None ->\n  fold_UP_result (UP x b :: rs) = None.\nProof.\n  intros. unfold fold_UP_result in *. simpl.\n  specialize (none_hold rs [] [(x,b)]). intros. tauto.\nQed.\n\nLemma unit_pro_keep_match: forall P J J1 B,\n  unit_pro P J = Some J1 ->\n  CNF_sat P B = true ->\n  asgn_match J B ->\n  asgn_match (J1 ++ J) B.\nProof.\n  induction P.\n  + intros.\n      unfold unit_pro in H.\n      simpl in H.\n      unfold fold_UP_result in H.\n      simpl in H.\n      injection H. intros. rewrite <- H2. simpl. tauto.\n  + intros.\n      remember (unit_pro P J) as oJ2.\n      assert (unit_pro P J = oJ2) by auto.\n      destruct oJ2 eqn:?.\n      - remember p as J2. clear HeqoJ2 Heqo oJ2 HeqJ2 p.\n        simpl in H0. unfold andb in H0.\n        destruct (clause_sat a B) eqn:?.\n        * specialize (IHP J J2 B H2 H0 H1).\n           destruct (find_unit_pro_in_clause a J Conflict) eqn:Ha.\n           ++ (* H is impossible *)\n                 unfold unit_pro in H. simpl in H.\n                 rewrite Ha in H.\n                 unfold fold_UP_result in H. simpl in H.\n                 specialize (none_implies_none (unit_pro' P J)). intros.\n                 rewrite H3 in H. discriminate H.\n           ++ pose proof find_unit_pro_in_clause_Conflict_UP a J B x b.\n                 specialize (H3 Ha H1 Heqb).\n                 assert (B x = b). {\n                     unfold asgn_match in H3.\n                     specialize (H3 x b). simpl in H3.\n                     assert (PV.eqb x x = true). {\n                        rewrite PV.eqb_eq. tauto.\n                     }\n                     rewrite H4 in H3. auto.\n                 }\n                 unfold unit_pro in H. simpl in H.\n                 rewrite Ha in H.\n                 unfold unit_pro in H2.\n                 admit.\n                 (* unfold asgn_match. intros.\n                 destruct (PV.look_up x0 (J2 ++ J)) eqn:HJ.\n                 -- unfold asgn_match in IHP.\n                     specialize (IHP x0 b0).\n                     destruct (eqb b0 b1) eqn:Hb0.\n                     ** rewrite eqb_true_iff in Hb0. subst b1. auto.\n                     ** (* This is impossible because J1++J cannot contradicts with J2++J. *)\n                         admit.\n                 -- (* x0 must be x *)\n                    admit. *)\n           ++ assert (J1 = J2). {\n                   unfold unit_pro in H. simpl in H.\n                   rewrite Ha in H.\n                   unfold fold_UP_result in H. simpl in H.\n                   assert (fold_UP_result (unit_pro' P J) = Some J1) by auto.\n                   assert (unit_pro P J = Some J1) by auto.\n                   rewrite H4 in H2. injection H2. tauto. \n                 }\n                 rewrite H3. tauto.\n        * discriminate H0.\n      - unfold unit_pro in H, H2. simpl in H.\n        destruct (find_unit_pro_in_clause a J Conflict) eqn:?.\n        * unfold fold_UP_result in H. simpl in H.\n           specialize (none_implies_none (unit_pro' P J)). intros.\n           rewrite H3 in H. discriminate H.\n        * specialize (none_remain (unit_pro' P J) x b).\n           intros. specialize (H3 H2). rewrite H3 in H. discriminate H.\n        * unfold fold_UP_result in H, H2. simpl in H.\n           rewrite H in H2. discriminate H2.\nAdmitted.\n\n\n\n(* ***************************************************************** *)\n(*                                                                   *)\n(*                                                                   *)\n(*  Final Theorems: Soundness of DPLL                                *)\n(*                                                                   *)\n(*                                                                   *)\n(* ***************************************************************** *)\n\nLemma DPLL_UP_false_Jsat: forall n P J B,\n    DPLL_UP P J n = false ->\n    CNF_sat P B = true ->\n    asgn_match J B ->\n    False\nwith\n  DPLL_filter_false_Jsat: forall n P J B,\n    DPLL_filter P J n = false ->\n    CNF_sat P B = true ->\n    asgn_match J B ->\n    False\nwith \n  DPLL_pick_false_Jsat: forall n P J B,\n    DPLL_pick P J n = false ->\n    CNF_sat P B = true ->\n    asgn_match J B ->\n    False.\nProof.\n  + clear DPLL_UP_false_Jsat.\n      intros n.\n      induction n.\n      - intros.\n        unfold DPLL_UP in H. discriminate H.\n      - intros.\n        simpl in H.\n        destruct (unit_pro P J) eqn:Hup.\n        * destruct p eqn:Hp.\n           ++ specialize (DPLL_filter_false_Jsat n P J B).\n                 apply DPLL_filter_false_Jsat; tauto.\n           ++ rewrite <- Hp in *.\n                 specialize (IHn P (p ++ J) B).\n                 apply IHn; try tauto.\n                 specialize (unit_pro_keep_match P J p B).\n                 intros. tauto.\n        * (* conflict is derived *)\n           (* One clause contradicts with J, so B cannot satisfy P. *)\n          induction P.\n          ++ unfold unit_pro in Hup.\n                simpl in Hup.\n                unfold fold_UP_result in Hup.\n                simpl in Hup. discriminate Hup.\n          ++ (* If _[a]_ contradicts with _[J]_, then _[B]_ cannot satisfy _[a]_.\n                O.w., use _[IHP]_. *)\n                destruct (find_unit_pro_in_clause a J Conflict) eqn:Ha.\n                -- specialize (find_unit_pro_in_clause_Conflict a J B).\n                    intros.\n                    specialize (H2 Ha H1).\n                    simpl in H0.\n                    unfold andb in H0.\n                    rewrite H2 in H0. discriminate H0.\n                -- apply IHP.\n                   ** unfold unit_pro in Hup.\n                        simpl in Hup.\n                        rewrite Ha in Hup.\n                        specialize (split_keep_none (unit_pro' P J) x b).\n                        tauto.\n                   ** simpl in H0.\n                        unfold andb in H0.\n                        destruct (clause_sat a B).\n                        +++ tauto.\n                        +++ discriminate H0.\n                -- apply IHP.\n                   ** unfold unit_pro in Hup.\n                        simpl in Hup.\n                        rewrite Ha in Hup.\n                        assert (fold_UP_result (unit_pro' P J) = None). {\n                          unfold fold_UP_result in Hup.\n                          simpl in Hup.\n                          tauto.\n                        }\n                        tauto.\n                   ** simpl in H0.\n                        unfold andb in H0.\n                        destruct (clause_sat a B).\n                        +++ tauto.\n                        +++ discriminate H0.\n  + clear DPLL_filter_false_Jsat.\n      intros n.\n      induction n.\n      - intros.\n        unfold DPLL_filter in H. discriminate H.\n      - intros.\n        simpl in H.\n        specialize (DPLL_pick_false_Jsat n (CNF_filter P J) [] B).\n        apply DPLL_pick_false_Jsat; try tauto.\n        * specialize (CNF_filter_sat P J B).\n           tauto.\n        * unfold asgn_match.\n           intros.\n           unfold PV.look_up in H2. discriminate H2.\n  + clear DPLL_pick_false_Jsat.\n      intros n.\n      induction n.\n      - intros.\n        unfold DPLL_pick in H. discriminate H.\n      - intros.\n        simpl in H.\n        remember (pick P) as x.\n        unfold orb in H.\n        destruct (DPLL_UP P ((x, true) :: J) n) eqn:?.\n        * discriminate H.\n        * specialize (CNF_sat_pick_fail x J B).\n           intros.\n           apply H2 in H1. clear H2.\n           destruct H1.\n           ++ specialize (DPLL_UP_false_Jsat n P ((x, true) :: J) B).\n                 apply DPLL_UP_false_Jsat; try tauto.\n           ++ specialize (DPLL_UP_false_Jsat n P ((x, false) :: J) B).\n                 apply DPLL_UP_false_Jsat; try tauto.\nQed.\n\nTheorem DPLL_sound: forall n P M,\n  DPLL_UP P nil n = false ->\n  CNF_sat P M = false.\nProof.\n  intros.\n  specialize (DPLL_UP_false_Jsat n P nil M).\n  intros.\n  destruct (CNF_sat P M) eqn:?.\n  + apply H0 in H.\n      - contradiction H.\n      - tauto.\n      - unfold asgn_match.\n        intros.\n        simpl in H1.\n        discriminate H1.\n  + tauto.\nQed.\n", "meta": {"author": "Kaiwen-Zhu", "repo": "CS2612-Project", "sha": "4741afe4640b6afd64aabbaed9af203eeb8d0fbc", "save_path": "github-repos/coq/Kaiwen-Zhu-CS2612-Project", "path": "github-repos/coq/Kaiwen-Zhu-CS2612-Project/CS2612-Project-4741afe4640b6afd64aabbaed9af203eeb8d0fbc/DPLL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6690458560817026}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq div fintype.\nRequire Import finfun path.\n\n(******************************************************************************)\n(* This file provides a generic definition for iterating an operator over a   *)\n(* set of indices (reducebig); this big operator is parametrized by the       *)\n(* return type (R), the type of indices (I), the operator (op), the default   *)\n(* value on empty lists (idx), the range of indices (r), the filter applied   *)\n(* on this range (P) and the expression we are iterating (F). The definition  *)\n(* is not to be used directly, but via the wide range of notations provided   *)\n(* and which allows a natural use of big operators.                           *)\n(*   The lemmas can be classified according to the operator being iterated:   *)\n(*  1. results independent of the operator: extensionality with respect to    *)\n(*     the range of indices, to the filtering predicate or to the expression  *)\n(*     being iterated; reindexing, widening or narrowing of the range of      *)\n(*     indices; we provide lemmas for the special cases where indices are     *)\n(*     natural numbers or bounded natural numbers (\"ordinals\"). We supply     *)\n(*     several \"functional\" induction principles that can be used with the    *)\n(*     ssreflect 1.3 \"elim\" tactic to do induction over the index range for   *)\n(*     up to 3 bigops simultaneously.                                         *)\n(*  2. results depending on the properties of the operator:                   *)\n(*     We distinguish: monoid laws (op is associative, idx is an identity     *)\n(*     element), abelian monoid laws (op is also commutative), and laws with  *)\n(*     a distributive operation (semi-rings). Examples of such results are    *)\n(*     splitting, permuting, and exchanging bigops.                           *)\n(* A special section is dedicated to big operators on natural numbers.        *)\n(******************************************************************************)\n(* Notations:                                                                 *)\n(* The general form for iterated operators is                                 *)\n(*         <bigop>_<range> <general_term>                                     *)\n(* - <bigop> is one of \\big[op/idx], \\sum, \\prod, or \\max (see below)         *)\n(* - <general_term> can be any expression                                     *)\n(* - <range> binds an index variable in <general_term>; <range> is one of     *)\n(*    (i <- s)     i ranges over the sequence s                               *)\n(*    (m <= i < n) i ranges over the nat interval m, m.+1, ..., n.-1          *)\n(*    (i < n)      i ranges over the (finite) type 'I_n (i.e., ordinal n)     *)\n(*    (i : T)      i ranges over the finite type T                            *)\n(*    i or (i)     i ranges over its (inferred) finite type                   *)\n(*    (i in A)     i ranges over the elements that satisfy the collective     *)\n(*                 predicate A (the domain of A must be a finite type)        *)\n(*    (i <- s | C) limits the range to those i for which C holds (i is thus   *)\n(*                 bound in C); works with all six kinds of ranges above.     *)\n(* - the fall-back notation <bigop>_(<- s | predicate) function is used if    *)\n(*   the Coq display algorithm fails to recognize any of the above (such as   *)\n(*   when <general_term> does not depend on i);                               *)\n(* - one can use the \"\\big[op/idx]\" notations for any operator;               *)\n(* - the \"\\sum\", \"\\prod\" and \"\\max\" notations in the %N scope are used for    *)\n(*   natural numbers with addition, multiplication and maximum (and their     *)\n(*   corresponding neutral elements), respectively;                           *)\n(* - the \"\\sum\" and \"\\prod\" reserved notations are overloaded in ssralg in    *)\n(*   the %R scope, in mxalgebra and vector in the %MS and %VS scopes; \"\\prod\" *)\n(*   is also overloaded in fingroup, the %g and %G scopes.                    *)\n(* - we reserve \"\\bigcup\" and \"\\bigcap\" notations for iterated union and      *)\n(*   intersection (of sets, groups, vector spaces, etc).                      *)\n(******************************************************************************)\n(* Tips for using lemmas in this file:                                        *)\n(* to apply a lemma for a specific operator: if no special property is        *)\n(* required for the operator, simply apply the lemma; if the lemma needs      *)\n(* certain properties for the operator, make sure the appropriate Canonical   *)\n(* instances are declared.                                                    *)\n(******************************************************************************)\n(* Interfaces for operator properties are packaged in the Monoid submodule:   *)\n(*     Monoid.law idx == interface (keyed on the operator) for associative    *)\n(*                       operators with identity element idx.                 *)\n(* Monoid.com_law idx == extension (telescope) of Monoid.law for operators    *)\n(*                       that are also commutative.                           *)\n(* Monoid.mul_law abz == interface for operators with absorbing (zero)        *)\n(*                       element abz.                                         *)\n(* Monoid.add_law idx mop == extension of Monoid.com_law for operators over   *)\n(*                       which operation mop distributes (mop will often also *)\n(*                       have a Monoid.mul_law idx structure).                *)\n(* [law of op], [com_law of op], [mul_law of op], [add_law mop of op] ==      *)\n(*                       syntax for cloning Monoid structures.                *)\n(*      Monoid.Theory == submodule containing basic generic algebra lemmas    *)\n(*                       for operators satisfying the Monoid interfaces.      *)\n(*       Monoid.simpm == generic monoid simplification rewrite multirule.     *)\n(* Monoid structures are predeclared for many basic operators: (_ && _)%B,    *)\n(* (_ || _)%B, (_ (+) _)%B (exclusive or) , (_ + _)%N, (_ * _)%N, maxn,       *)\n(* gcdn, lcmn and (_ ++ _)%SEQ (list concatenation).                          *)\n(******************************************************************************)\n(* Additional documentation for this file:                                    *)\n(* Y. Bertot, G. Gonthier, S. Ould Biha and I. Pasca.                         *)\n(* Canonical Big Operators. In TPHOLs 2008, LNCS vol. 5170, Springer.         *)\n(* Article available at:                                                      *)\n(*     http://hal.inria.fr/docs/00/33/11/93/PDF/main.pdf                      *)\n(******************************************************************************)\n(* Examples of use in: poly.v, matrix.v                                       *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nReserved Notation \"\\big [ op / idx ]_ i F\"\n  (at level 36, F at level 36, op, idx at level 10, i at level 0,\n     right associativity,\n           format \"'[' \\big [ op / idx ]_ i '/  '  F ']'\").\nReserved Notation \"\\big [ op / idx ]_ ( <- r | P ) F\"\n  (at level 36, F at level 36, op, idx at level 10, r at level 50,\n           format \"'[' \\big [ op / idx ]_ ( <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / idx ]_ ( i <- r | P ) F\"\n  (at level 36, F at level 36, op, idx at level 10, i, r at level 50,\n           format \"'[' \\big [ op / idx ]_ ( i  <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / idx ]_ ( i <- r ) F\"\n  (at level 36, F at level 36, op, idx at level 10, i, r at level 50,\n           format \"'[' \\big [ op / idx ]_ ( i  <-  r ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / idx ]_ ( m <= i < n | P ) F\"\n  (at level 36, F at level 36, op, idx at level 10, m, i, n at level 50,\n           format \"'[' \\big [ op / idx ]_ ( m  <=  i  <  n  |  P )  F ']'\").\nReserved Notation \"\\big [ op / idx ]_ ( m <= i < n ) F\"\n  (at level 36, F at level 36, op, idx at level 10, i, m, n at level 50,\n           format \"'[' \\big [ op / idx ]_ ( m  <=  i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / idx ]_ ( i | P ) F\"\n  (at level 36, F at level 36, op, idx at level 10, i at level 50,\n           format \"'[' \\big [ op / idx ]_ ( i  |  P ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / idx ]_ ( i : t | P ) F\"\n  (at level 36, F at level 36, op, idx at level 10, i at level 50,\n           format \"'[' \\big [ op / idx ]_ ( i   :  t   |  P ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / idx ]_ ( i : t ) F\"\n  (at level 36, F at level 36, op, idx at level 10, i at level 50,\n           format \"'[' \\big [ op / idx ]_ ( i   :  t ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / idx ]_ ( i < n | P ) F\"\n  (at level 36, F at level 36, op, idx at level 10, i, n at level 50,\n           format \"'[' \\big [ op / idx ]_ ( i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / idx ]_ ( i < n ) F\"\n  (at level 36, F at level 36, op, idx at level 10, i, n at level 50,\n           format \"'[' \\big [ op / idx ]_ ( i  <  n )  F ']'\").\nReserved Notation \"\\big [ op / idx ]_ ( i 'in' A | P ) F\"\n  (at level 36, F at level 36, op, idx at level 10, i, A at level 50,\n           format \"'[' \\big [ op / idx ]_ ( i  'in'  A  |  P ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / idx ]_ ( i 'in' A ) F\"\n  (at level 36, F at level 36, op, idx at level 10, i, A at level 50,\n           format \"'[' \\big [ op / idx ]_ ( i  'in'  A ) '/  '  F ']'\").\n\nReserved Notation \"\\sum_ i F\"\n  (at level 41, F at level 41, i at level 0,\n           right associativity,\n           format \"'[' \\sum_ i '/  '  F ']'\").\nReserved Notation \"\\sum_ ( <- r | P ) F\"\n  (at level 41, F at level 41, r at level 50,\n           format \"'[' \\sum_ ( <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( i <- r | P ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\sum_ ( i  <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( i <- r ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\sum_ ( i  <-  r ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( m <= i < n | P ) F\"\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\sum_ ( m  <=  i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( m <= i < n ) F\"\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\sum_ ( m  <=  i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( i | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\sum_ ( i  |  P ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( i : t | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           only parsing).\nReserved Notation \"\\sum_ ( i : t ) F\"\n  (at level 41, F at level 41, i at level 50,\n           only parsing).\nReserved Notation \"\\sum_ ( i < n | P ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\sum_ ( i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( i < n ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\sum_ ( i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( i 'in' A | P ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\sum_ ( i  'in'  A  |  P ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( i 'in' A ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\sum_ ( i  'in'  A ) '/  '  F ']'\").\n\nReserved Notation \"\\max_ i F\"\n  (at level 41, F at level 41, i at level 0,\n           format \"'[' \\max_ i '/  '  F ']'\").\nReserved Notation \"\\max_ ( <- r | P ) F\"\n  (at level 41, F at level 41, r at level 50,\n           format \"'[' \\max_ ( <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( i <- r | P ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\max_ ( i  <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( i <- r ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\max_ ( i  <-  r ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( m <= i < n | P ) F\"\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\max_ ( m  <=  i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( m <= i < n ) F\"\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\max_ ( m  <=  i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( i | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\max_ ( i  |  P ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( i : t | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           only parsing).\nReserved Notation \"\\max_ ( i : t ) F\"\n  (at level 41, F at level 41, i at level 50,\n           only parsing).\nReserved Notation \"\\max_ ( i < n | P ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\max_ ( i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( i < n ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\max_ ( i  <  n )  F ']'\").\nReserved Notation \"\\max_ ( i 'in' A | P ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\max_ ( i  'in'  A  |  P ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( i 'in' A ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\max_ ( i  'in'  A ) '/  '  F ']'\").\n\nReserved Notation \"\\prod_ i F\"\n  (at level 36, F at level 36, i at level 0,\n           format \"'[' \\prod_ i '/  '  F ']'\").\nReserved Notation \"\\prod_ ( <- r | P ) F\"\n  (at level 36, F at level 36, r at level 50,\n           format \"'[' \\prod_ ( <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( i <- r | P ) F\"\n  (at level 36, F at level 36, i, r at level 50,\n           format \"'[' \\prod_ ( i  <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( i <- r ) F\"\n  (at level 36, F at level 36, i, r at level 50,\n           format \"'[' \\prod_ ( i  <-  r ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( m <= i < n | P ) F\"\n  (at level 36, F at level 36, i, m, n at level 50,\n           format \"'[' \\prod_ ( m  <=  i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( m <= i < n ) F\"\n  (at level 36, F at level 36, i, m, n at level 50,\n           format \"'[' \\prod_ ( m  <=  i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( i | P ) F\"\n  (at level 36, F at level 36, i at level 50,\n           format \"'[' \\prod_ ( i  |  P ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( i : t | P ) F\"\n  (at level 36, F at level 36, i at level 50,\n           only parsing).\nReserved Notation \"\\prod_ ( i : t ) F\"\n  (at level 36, F at level 36, i at level 50,\n           only parsing).\nReserved Notation \"\\prod_ ( i < n | P ) F\"\n  (at level 36, F at level 36, i, n at level 50,\n           format \"'[' \\prod_ ( i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( i < n ) F\"\n  (at level 36, F at level 36, i, n at level 50,\n           format \"'[' \\prod_ ( i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( i 'in' A | P ) F\"\n  (at level 36, F at level 36, i, A at level 50,\n           format \"'[' \\prod_ ( i  'in'  A  |  P )  F ']'\").\nReserved Notation \"\\prod_ ( i 'in' A ) F\"\n  (at level 36, F at level 36, i, A at level 50,\n           format \"'[' \\prod_ ( i  'in'  A ) '/  '  F ']'\").\n\nReserved Notation \"\\bigcup_ i F\"\n  (at level 41, F at level 41, i at level 0,\n           format \"'[' \\bigcup_ i '/  '  F ']'\").\nReserved Notation \"\\bigcup_ ( <- r | P ) F\"\n  (at level 41, F at level 41, r at level 50,\n           format \"'[' \\bigcup_ ( <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\bigcup_ ( i <- r | P ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\bigcup_ ( i  <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\bigcup_ ( i <- r ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\bigcup_ ( i  <-  r ) '/  '  F ']'\").\nReserved Notation \"\\bigcup_ ( m <= i < n | P ) F\"\n  (at level 41, F at level 41, m, i, n at level 50,\n           format \"'[' \\bigcup_ ( m  <=  i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\bigcup_ ( m <= i < n ) F\"\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\bigcup_ ( m  <=  i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\bigcup_ ( i | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\bigcup_ ( i  |  P ) '/  '  F ']'\").\nReserved Notation \"\\bigcup_ ( i : t | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\bigcup_ ( i   :  t   |  P ) '/  '  F ']'\").\nReserved Notation \"\\bigcup_ ( i : t ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\bigcup_ ( i   :  t ) '/  '  F ']'\").\nReserved Notation \"\\bigcup_ ( i < n | P ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\bigcup_ ( i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\bigcup_ ( i < n ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\bigcup_ ( i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\bigcup_ ( i 'in' A | P ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\bigcup_ ( i  'in'  A  |  P ) '/  '  F ']'\").\nReserved Notation \"\\bigcup_ ( i 'in' A ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\bigcup_ ( i  'in'  A ) '/  '  F ']'\").\n\nReserved Notation \"\\bigcap_ i F\"\n  (at level 41, F at level 41, i at level 0,\n           format \"'[' \\bigcap_ i '/  '  F ']'\").\nReserved Notation \"\\bigcap_ ( <- r | P ) F\"\n  (at level 41, F at level 41, r at level 50,\n           format \"'[' \\bigcap_ ( <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\bigcap_ ( i <- r | P ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\bigcap_ ( i  <-  r  |  P )  F ']'\").\nReserved Notation \"\\bigcap_ ( i <- r ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\bigcap_ ( i  <-  r ) '/  '  F ']'\").\nReserved Notation \"\\bigcap_ ( m <= i < n | P ) F\"\n  (at level 41, F at level 41, m, i, n at level 50,\n           format \"'[' \\bigcap_ ( m  <=  i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\bigcap_ ( m <= i < n ) F\"\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\bigcap_ ( m  <=  i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\bigcap_ ( i | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\bigcap_ ( i  |  P ) '/  '  F ']'\").\nReserved Notation \"\\bigcap_ ( i : t | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\bigcap_ ( i   :  t   |  P ) '/  '  F ']'\").\nReserved Notation \"\\bigcap_ ( i : t ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\bigcap_ ( i   :  t ) '/  '  F ']'\").\nReserved Notation \"\\bigcap_ ( i < n | P ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\bigcap_ ( i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\bigcap_ ( i < n ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\bigcap_ ( i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\bigcap_ ( i 'in' A | P ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\bigcap_ ( i  'in'  A  |  P ) '/  '  F ']'\").\nReserved Notation \"\\bigcap_ ( i 'in' A ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\bigcap_ ( i  'in'  A ) '/  '  F ']'\").\n\nModule Monoid.\n\nSection Definitions.\nVariables (T : Type) (idm : T).\n\nStructure law := Law {\n  operator : T -> T -> T;\n  _ : associative operator;\n  _ : left_id idm operator;\n  _ : right_id idm operator\n}.\nLocal Coercion operator : law >-> Funclass.\n\nStructure com_law := ComLaw {\n   com_operator : law;\n   _ : commutative com_operator\n}.\nLocal Coercion com_operator : com_law >-> law.\n\nStructure mul_law := MulLaw {\n  mul_operator : T -> T -> T;\n  _ : left_zero idm mul_operator;\n  _ : right_zero idm mul_operator\n}.\nLocal Coercion mul_operator : mul_law >-> Funclass.\n\nStructure add_law (mul : T -> T -> T) := AddLaw {\n  add_operator : com_law;\n  _ : left_distributive mul add_operator;\n  _ : right_distributive mul add_operator\n}.\nLocal Coercion add_operator : add_law >-> com_law.\n\nLet op_id (op1 op2 : T -> T -> T) := phant_id op1 op2.\n\nDefinition clone_law op :=\n  fun (opL : law) & op_id opL op =>\n  fun opmA op1m opm1 (opL' := @Law op opmA op1m opm1)\n    & phant_id opL' opL => opL'.\n\nDefinition clone_com_law op :=\n  fun (opL : law) (opC : com_law) & op_id opL op & op_id opC op =>\n  fun opmC (opC' := @ComLaw opL opmC) & phant_id opC' opC => opC'.\n\nDefinition clone_mul_law op :=\n  fun (opM : mul_law) & op_id opM op =>\n  fun op0m opm0 (opM' := @MulLaw op op0m opm0) & phant_id opM' opM => opM'.\n\nDefinition clone_add_law mop aop :=\n  fun (opC : com_law) (opA : add_law mop) & op_id opC aop & op_id opA aop =>\n  fun mopDm mopmD (opA' := @AddLaw mop opC mopDm mopmD)\n    & phant_id opA' opA => opA'.\n\nEnd Definitions.\n\nModule Import Exports.\nCoercion operator : law >-> Funclass.\nCoercion com_operator : com_law >-> law.\nCoercion mul_operator : mul_law >-> Funclass.\nCoercion add_operator : add_law >-> com_law.\nNotation \"[ 'law' 'of' f ]\" := (@clone_law _ _ f _ id _ _ _ id)\n  (at level 0, format\"[ 'law'  'of'  f ]\") : form_scope.\nNotation \"[ 'com_law' 'of' f ]\" := (@clone_com_law _ _ f _ _ id id _ id)\n  (at level 0, format \"[ 'com_law'  'of'  f ]\") : form_scope.\nNotation \"[ 'mul_law' 'of' f ]\" := (@clone_mul_law _ _ f _ id _ _ id)\n  (at level 0, format\"[ 'mul_law'  'of'  f ]\") : form_scope.\nNotation \"[ 'add_law' m 'of' a ]\" := (@clone_add_law _ _ m a _ _ id id _ _ id)\n  (at level 0, format \"[ 'add_law'  m  'of'  a ]\") : form_scope.\nEnd Exports.\n\nSection CommutativeAxioms.\n\nVariable (T : Type) (zero one : T) (mul add : T -> T -> T) (inv : T -> T).\nHypothesis mulC : commutative mul.\n\nLemma mulC_id : left_id one mul -> right_id one mul.\nProof. by move=>  mul1x x; rewrite mulC. Qed.\n\nLemma mulC_zero : left_zero zero mul -> right_zero zero mul.\nProof. by move=> mul0x x; rewrite mulC. Qed.\n\nLemma mulC_dist : left_distributive mul add -> right_distributive mul add.\nProof. by move=> mul_addl x y z; rewrite !(mulC x). Qed.\n\nEnd CommutativeAxioms.\n\nModule Theory.\n\nSection Theory.\nVariables (T : Type) (idm : T).\n\nSection Plain.\nVariable mul : law idm.\nLemma mul1m : left_id idm mul. Proof. by case mul. Qed.\nLemma mulm1 : right_id idm mul. Proof. by case mul. Qed.\nLemma mulmA : associative mul. Proof. by case mul. Qed.\nLemma iteropE n x : iterop n mul x idm = iter n (mul x) idm.\nProof. by case: n => // n; rewrite iterSr mulm1 iteropS. Qed.\nEnd Plain.\n\nSection Commutative.\nVariable mul : com_law idm.\nLemma mulmC : commutative mul. Proof. by case mul. Qed.\nLemma mulmCA : left_commutative mul.\nProof. by move=> x y z; rewrite !mulmA (mulmC x). Qed.\nLemma mulmAC : right_commutative mul.\nProof. by move=> x y z; rewrite -!mulmA (mulmC y). Qed.\nLemma mulmACA : interchange mul mul.\nProof. by move=> x y z t; rewrite -!mulmA (mulmCA y). Qed.\nEnd Commutative.\n\nSection Mul.\nVariable mul : mul_law idm.\nLemma mul0m : left_zero idm mul. Proof. by case mul. Qed.\nLemma mulm0 : right_zero idm mul. Proof. by case mul. Qed.\nEnd Mul.\n\nSection Add.\nVariables (mul : T -> T -> T) (add : add_law idm mul).\nLemma addmA : associative add. Proof. exact: mulmA. Qed.\nLemma addmC : commutative add. Proof. exact: mulmC. Qed.\nLemma addmCA : left_commutative add. Proof. exact: mulmCA. Qed.\nLemma addmAC : right_commutative add. Proof. exact: mulmAC. Qed.\nLemma add0m : left_id idm add. Proof. exact: mul1m. Qed.\nLemma addm0 : right_id idm add. Proof. exact: mulm1. Qed.\nLemma mulm_addl : left_distributive mul add. Proof. by case add. Qed.\nLemma mulm_addr : right_distributive mul add. Proof. by case add. Qed.\nEnd Add.\n\nDefinition simpm := (mulm1, mulm0, mul1m, mul0m, mulmA).\n\nEnd Theory.\n\nEnd Theory.\nInclude Theory.\n\nEnd Monoid.\nExport Monoid.Exports.\n\nSection PervasiveMonoids.\n\nImport Monoid.\n\nCanonical andb_monoid := Law andbA andTb andbT.\nCanonical andb_comoid := ComLaw andbC.\n\nCanonical andb_muloid := MulLaw andFb andbF.\nCanonical orb_monoid := Law orbA orFb orbF.\nCanonical orb_comoid := ComLaw orbC.\nCanonical orb_muloid := MulLaw orTb orbT.\nCanonical addb_monoid := Law addbA addFb addbF.\nCanonical addb_comoid := ComLaw addbC.\nCanonical orb_addoid := AddLaw andb_orl andb_orr.\nCanonical andb_addoid := AddLaw orb_andl orb_andr.\nCanonical addb_addoid := AddLaw andb_addl andb_addr.\n\nCanonical addn_monoid := Law addnA add0n addn0.\nCanonical addn_comoid := ComLaw addnC.\nCanonical muln_monoid := Law mulnA mul1n muln1.\nCanonical muln_comoid := ComLaw mulnC.\nCanonical muln_muloid := MulLaw mul0n muln0.\nCanonical addn_addoid := AddLaw mulnDl mulnDr.\n\nCanonical maxn_monoid := Law maxnA max0n maxn0.\nCanonical maxn_comoid := ComLaw maxnC.\nCanonical maxn_addoid := AddLaw maxn_mull maxn_mulr.\n\nCanonical gcdn_monoid := Law gcdnA gcd0n gcdn0.\nCanonical gcdn_comoid := ComLaw gcdnC.\nCanonical gcdnDoid := AddLaw muln_gcdl muln_gcdr.\n\nCanonical lcmn_monoid := Law lcmnA lcm1n lcmn1.\nCanonical lcmn_comoid := ComLaw lcmnC.\nCanonical lcmn_addoid := AddLaw muln_lcml muln_lcmr.\n\nCanonical cat_monoid T := Law (@catA T) (@cat0s T) (@cats0 T).\n\nEnd PervasiveMonoids.\n\n(* Unit test for the [...law of ...] Notations\nDefinition myp := addn. Definition mym := muln.\nCanonical myp_mon := [law of myp].\nCanonical myp_cmon := [com_law of myp].\nCanonical mym_mul := [mul_law of mym].\nCanonical myp_add := [add_law _ of myp].\nPrint myp_add.\nPrint Canonical Projections.\n*)\n\nDelimit Scope big_scope with BIG.\nOpen Scope big_scope.\n\nDefinition reducebig R I idx op r (P : pred I) (F : I -> R) : R :=\n  foldr (fun i x => if P i then op (F i) x else x) idx r.\n\nModule Type BigOpSig.\nParameter bigop : forall R I,\n   R -> (R -> R -> R) -> seq I -> pred I -> (I -> R) -> R.\nAxiom bigopE : bigop = reducebig.\nEnd BigOpSig.\n\nModule BigOp : BigOpSig.\nDefinition bigop := reducebig.\nLemma bigopE : bigop = reducebig. Proof. by []. Qed.\nEnd BigOp.\n\nNotation bigop := BigOp.bigop (only parsing).\nCanonical bigop_unlock := Unlockable BigOp.bigopE.\n\nDefinition index_iota m n := iota m (n - m).\n\nDefinition index_enum (T : finType) := Finite.enum T.\n\nLemma mem_index_iota m n i : i \\in index_iota m n = (m <= i < n).\nProof.\nrewrite mem_iota; case le_m_i: (m <= i) => //=.\nby rewrite -leq_subLR subSn // -subn_gt0 -subnDA subnKC // subn_gt0.\nQed.\n\nLemma mem_index_enum T i : i \\in index_enum T.\nProof. by rewrite -[index_enum T]enumT mem_enum. Qed.\nHint Resolve mem_index_enum.\n\nLemma filter_index_enum T P : filter P (index_enum T) = enum P.\nProof. by []. Qed.\n\nNotation \"\\big [ op / idx ]_ ( <- r | P ) F\" :=\n  (bigop idx op r P F) : big_scope.\nNotation \"\\big [ op / idx ]_ ( i <- r | P ) F\" :=\n  (bigop idx op r (fun i => P%B) (fun i => F)) : big_scope.\nNotation \"\\big [ op / idx ]_ ( i <- r ) F\" :=\n  (bigop idx op r (fun _ => true) (fun  i => F)) : big_scope.\nNotation \"\\big [ op / idx ]_ ( m <= i < n | P ) F\" :=\n  (bigop idx op (index_iota m n) (fun i : nat => P%B) (fun i : nat => F))\n     : big_scope.\nNotation \"\\big [ op / idx ]_ ( m <= i < n ) F\" :=\n  (bigop idx op (index_iota m n) (fun _ => true) (fun i : nat => F))\n     : big_scope.\nNotation \"\\big [ op / idx ]_ ( i | P ) F\" :=\n  (bigop idx op (index_enum _) (fun i => P%B) (fun i => F)) : big_scope.\nNotation \"\\big [ op / idx ]_ i F\" :=\n  (bigop idx op (index_enum _) (fun _ => true) (fun i => F)) : big_scope.\nNotation \"\\big [ op / idx ]_ ( i : t | P ) F\" :=\n  (bigop idx op (index_enum _) (fun i : t => P%B) (fun i : t => F))\n     (only parsing) : big_scope.\nNotation \"\\big [ op / idx ]_ ( i : t ) F\" :=\n  (bigop idx op (index_enum _) (fun _ => true) (fun i : t => F))\n     (only parsing) : big_scope.\nNotation \"\\big [ op / idx ]_ ( i < n | P ) F\" :=\n  (\\big[op/idx]_(i : ordinal n | P%B) F) : big_scope.\nNotation \"\\big [ op / idx ]_ ( i < n ) F\" :=\n  (\\big[op/idx]_(i : ordinal n) F) : big_scope.\nNotation \"\\big [ op / idx ]_ ( i 'in' A | P ) F\" :=\n  (\\big[op/idx]_(i | (i \\in A) && P) F) : big_scope.\nNotation \"\\big [ op / idx ]_ ( i 'in' A ) F\" :=\n  (\\big[op/idx]_(i | i \\in A) F) : big_scope.\n\nNotation Local \"+%N\" := addn (at level 0, only parsing).\nNotation \"\\sum_ ( <- r | P ) F\" :=\n  (\\big[+%N/0%N]_(<- r | P%B) F%N) : nat_scope.\nNotation \"\\sum_ ( i <- r | P ) F\" :=\n  (\\big[+%N/0%N]_(i <- r | P%B) F%N) : nat_scope.\nNotation \"\\sum_ ( i <- r ) F\" :=\n  (\\big[+%N/0%N]_(i <- r) F%N) : nat_scope.\nNotation \"\\sum_ ( m <= i < n | P ) F\" :=\n  (\\big[+%N/0%N]_(m <= i < n | P%B) F%N) : nat_scope.\nNotation \"\\sum_ ( m <= i < n ) F\" :=\n  (\\big[+%N/0%N]_(m <= i < n) F%N) : nat_scope.\nNotation \"\\sum_ ( i | P ) F\" :=\n  (\\big[+%N/0%N]_(i | P%B) F%N) : nat_scope.\nNotation \"\\sum_ i F\" :=\n  (\\big[+%N/0%N]_i F%N) : nat_scope.\nNotation \"\\sum_ ( i : t | P ) F\" :=\n  (\\big[+%N/0%N]_(i : t | P%B) F%N) (only parsing) : nat_scope.\nNotation \"\\sum_ ( i : t ) F\" :=\n  (\\big[+%N/0%N]_(i : t) F%N) (only parsing) : nat_scope.\nNotation \"\\sum_ ( i < n | P ) F\" :=\n  (\\big[+%N/0%N]_(i < n | P%B) F%N) : nat_scope.\nNotation \"\\sum_ ( i < n ) F\" :=\n  (\\big[+%N/0%N]_(i < n) F%N) : nat_scope.\nNotation \"\\sum_ ( i 'in' A | P ) F\" :=\n  (\\big[+%N/0%N]_(i in A | P%B) F%N) : nat_scope.\nNotation \"\\sum_ ( i 'in' A ) F\" :=\n  (\\big[+%N/0%N]_(i in A) F%N) : nat_scope.\n\nNotation Local \"*%N\" := muln (at level 0, only parsing).\nNotation \"\\prod_ ( <- r | P ) F\" :=\n  (\\big[*%N/1%N]_(<- r | P%B) F%N) : nat_scope.\nNotation \"\\prod_ ( i <- r | P ) F\" :=\n  (\\big[*%N/1%N]_(i <- r | P%B) F%N) : nat_scope.\nNotation \"\\prod_ ( i <- r ) F\" :=\n  (\\big[*%N/1%N]_(i <- r) F%N) : nat_scope.\nNotation \"\\prod_ ( m <= i < n | P ) F\" :=\n  (\\big[*%N/1%N]_(m <= i < n | P%B) F%N) : nat_scope.\nNotation \"\\prod_ ( m <= i < n ) F\" :=\n  (\\big[*%N/1%N]_(m <= i < n) F%N) : nat_scope.\nNotation \"\\prod_ ( i | P ) F\" :=\n  (\\big[*%N/1%N]_(i | P%B) F%N) : nat_scope.\nNotation \"\\prod_ i F\" :=\n  (\\big[*%N/1%N]_i F%N) : nat_scope.\nNotation \"\\prod_ ( i : t | P ) F\" :=\n  (\\big[*%N/1%N]_(i : t | P%B) F%N) (only parsing) : nat_scope.\nNotation \"\\prod_ ( i : t ) F\" :=\n  (\\big[*%N/1%N]_(i : t) F%N) (only parsing) : nat_scope.\nNotation \"\\prod_ ( i < n | P ) F\" :=\n  (\\big[*%N/1%N]_(i < n | P%B) F%N) : nat_scope.\nNotation \"\\prod_ ( i < n ) F\" :=\n  (\\big[*%N/1%N]_(i < n) F%N) : nat_scope.\nNotation \"\\prod_ ( i 'in' A | P ) F\" :=\n  (\\big[*%N/1%N]_(i in A | P%B) F%N) : nat_scope.\nNotation \"\\prod_ ( i 'in' A ) F\" :=\n  (\\big[*%N/1%N]_(i in A) F%N) : nat_scope.\n\nNotation \"\\max_ ( <- r | P ) F\" :=\n  (\\big[maxn/0%N]_(<- r | P%B) F%N) : nat_scope.\nNotation \"\\max_ ( i <- r | P ) F\" :=\n  (\\big[maxn/0%N]_(i <- r | P%B) F%N) : nat_scope.\nNotation \"\\max_ ( i <- r ) F\" :=\n  (\\big[maxn/0%N]_(i <- r) F%N) : nat_scope.\nNotation \"\\max_ ( i | P ) F\" :=\n  (\\big[maxn/0%N]_(i | P%B) F%N) : nat_scope.\nNotation \"\\max_ i F\" :=\n  (\\big[maxn/0%N]_i F%N) : nat_scope.\nNotation \"\\max_ ( i : I | P ) F\" :=\n  (\\big[maxn/0%N]_(i : I | P%B) F%N) (only parsing) : nat_scope.\nNotation \"\\max_ ( i : I ) F\" :=\n  (\\big[maxn/0%N]_(i : I) F%N) (only parsing) : nat_scope.\nNotation \"\\max_ ( m <= i < n | P ) F\" :=\n (\\big[maxn/0%N]_(m <= i < n | P%B) F%N) : nat_scope.\nNotation \"\\max_ ( m <= i < n ) F\" :=\n (\\big[maxn/0%N]_(m <= i < n) F%N) : nat_scope.\nNotation \"\\max_ ( i < n | P ) F\" :=\n (\\big[maxn/0%N]_(i < n | P%B) F%N) : nat_scope.\nNotation \"\\max_ ( i < n ) F\" :=\n (\\big[maxn/0%N]_(i < n) F%N) : nat_scope.\nNotation \"\\max_ ( i 'in' A | P ) F\" :=\n (\\big[maxn/0%N]_(i in A | P%B) F%N) : nat_scope.\nNotation \"\\max_ ( i 'in' A ) F\" :=\n (\\big[maxn/0%N]_(i in A) F%N) : nat_scope.\n\n(* Redundant, unparseable notation to print some constant sums and products. *)\nNotation \"\\su 'm_' ( i | P ) e\" :=\n  (\\sum_(<- index_enum _ | (fun i => P)) (fun _ => e%N))\n  (at level 41, e at level 41, format \"\\su 'm_' ( i  |  P )  e\") : nat_scope.\n\nNotation \"\\su 'm_' ( i 'in' A ) e\" :=\n  (\\sum_(<- index_enum _ | (fun i => i \\in A)) (fun _ => e%N))\n  (at level 41, e at level 41, format \"\\su 'm_' ( i  'in'  A )  e\") : nat_scope.\n\nNotation \"\\su 'm_' ( i 'in' A | P ) e\" :=\n  (\\sum_(<- index_enum _ | (fun i => (i \\in A) && P)) (fun _ => e%N))\n  (at level 41, e at level 41, format \"\\su 'm_' ( i  'in'  A  |  P )  e\")\n    : nat_scope.\n\nNotation \"\\pro 'd_' ( i | P ) e\" :=\n  (\\prod_(<- index_enum _ | (fun i => P)) (fun _ => e%N))\n  (at level 36, e at level 36, format \"\\pro 'd_' ( i  |  P )  e\") : nat_scope.\n\n(* Induction loading *)\nLemma big_load R (K K' : R -> Type) idx op I r (P : pred I) F :\n  K (\\big[op/idx]_(i <- r | P i) F i) * K' (\\big[op/idx]_(i <- r | P i) F i)\n  -> K' (\\big[op/idx]_(i <- r | P i) F i).\nProof. by case. Qed.\n\nImplicit Arguments big_load [R K' I].\n\nSection Elim3.\n\nVariables (R1 R2 R3 : Type) (K : R1 -> R2 -> R3 -> Type).\nVariables (id1 : R1) (op1 : R1 -> R1 -> R1).\nVariables (id2 : R2) (op2 : R2 -> R2 -> R2).\nVariables (id3 : R3) (op3 : R3 -> R3 -> R3).\n\nHypothesis Kid : K id1 id2 id3.\n\nLemma big_rec3 I r (P : pred I) F1 F2 F3\n    (K_F : forall i y1 y2 y3, P i -> K y1 y2 y3 ->\n       K (op1 (F1 i) y1) (op2 (F2 i) y2) (op3 (F3 i) y3)) :\n  K (\\big[op1/id1]_(i <- r | P i) F1 i)\n    (\\big[op2/id2]_(i <- r | P i) F2 i)\n    (\\big[op3/id3]_(i <- r | P i) F3 i).\nProof. by rewrite unlock; elim: r => //= i r; case: ifP => //; exact: K_F. Qed.\n\nHypothesis Kop : forall x1 x2 x3 y1 y2 y3,\n  K x1 x2 x3 -> K y1 y2 y3-> K (op1 x1 y1) (op2 x2 y2) (op3 x3 y3).\nLemma big_ind3 I r (P : pred I) F1 F2 F3\n   (K_F : forall i, P i -> K (F1 i) (F2 i) (F3 i)) :\n  K (\\big[op1/id1]_(i <- r | P i) F1 i)\n    (\\big[op2/id2]_(i <- r | P i) F2 i)\n    (\\big[op3/id3]_(i <- r | P i) F3 i).\nProof. by apply: big_rec3 => i x1 x2 x3 /K_F; exact: Kop. Qed.\n\nEnd Elim3.\n\nImplicit Arguments big_rec3 [R1 R2 R3 id1 op1 id2 op2 id3 op3 I r P F1 F2 F3].\nImplicit Arguments big_ind3 [R1 R2 R3 id1 op1 id2 op2 id3 op3 I r P F1 F2 F3].\n\nSection Elim2.\n\nVariables (R1 R2 : Type) (K : R1 -> R2 -> Type) (f : R2 -> R1).\nVariables (id1 : R1) (op1 : R1 -> R1 -> R1).\nVariables (id2 : R2) (op2 : R2 -> R2 -> R2).\n\nHypothesis Kid : K id1 id2.\n\nLemma big_rec2 I r (P : pred I) F1 F2\n    (K_F : forall i y1 y2, P i -> K y1 y2 ->\n       K (op1 (F1 i) y1) (op2 (F2 i) y2)) :\n  K (\\big[op1/id1]_(i <- r | P i) F1 i) (\\big[op2/id2]_(i <- r | P i) F2 i).\nProof. by rewrite unlock; elim: r => //= i r; case: ifP => //; exact: K_F. Qed.\n\nHypothesis Kop : forall x1 x2 y1 y2,\n  K x1 x2 -> K y1 y2 -> K (op1 x1 y1) (op2 x2 y2).\nLemma big_ind2 I r (P : pred I) F1 F2 (K_F : forall i, P i -> K (F1 i) (F2 i)) :\n  K (\\big[op1/id1]_(i <- r | P i) F1 i) (\\big[op2/id2]_(i <- r | P i) F2 i).\nProof. by apply: big_rec2 => i x1 x2 /K_F; exact: Kop. Qed.\n\nHypotheses (f_op : {morph f : x y / op2 x y >-> op1 x y}) (f_id : f id2 = id1).\nLemma big_morph I r (P : pred I) F :\n  f (\\big[op2/id2]_(i <- r | P i) F i) = \\big[op1/id1]_(i <- r | P i) f (F i).\nProof. by rewrite unlock; elim: r => //= i r <-; rewrite -f_op -fun_if. Qed.\n\nEnd Elim2.\n\nImplicit Arguments big_rec2 [R1 R2 id1 op1 id2 op2 I r P F1 F2].\nImplicit Arguments big_ind2 [R1 R2 id1 op1 id2 op2 I r P F1 F2].\nImplicit Arguments big_morph [R1 R2 id1 op1 id2 op2 I].\n\nSection Elim1.\n\nVariables (R : Type) (K : R -> Type) (f : R -> R).\nVariables (idx : R) (op op' : R -> R -> R).\n\nHypothesis Kid : K idx.\n\nLemma big_rec I r (P : pred I) F\n    (Kop : forall i x, P i -> K x -> K (op (F i) x)) :\n  K (\\big[op/idx]_(i <- r | P i) F i).\nProof. by rewrite unlock; elim: r => //= i r; case: ifP => //; exact: Kop. Qed.\n\nHypothesis Kop : forall x y, K x -> K y -> K (op x y).\nLemma big_ind I r (P : pred I) F (K_F : forall i, P i -> K (F i)) :\n  K (\\big[op/idx]_(i <- r | P i) F i).\nProof. by apply: big_rec => // i x /K_F /Kop; exact. Qed.\n\nHypothesis Kop' : forall x y, K x -> K y -> op x y = op' x y.\nLemma eq_big_op I r (P : pred I) F (K_F : forall i, P i -> K (F i)) :\n  \\big[op/idx]_(i <- r | P i) F i = \\big[op'/idx]_(i <- r | P i) F i.\nProof.\nby elim/(big_load K): _; elim/big_rec2: _ => // i _ y Pi [Ky <-]; auto.\nQed.\n\nHypotheses (fM : {morph f : x y / op x y}) (f_id : f idx = idx).\nLemma big_endo I r (P : pred I) F :\n  f (\\big[op/idx]_(i <- r | P i) F i) = \\big[op/idx]_(i <- r | P i) f (F i).\nProof. exact: big_morph. Qed.\n\nEnd Elim1.\n\nImplicit Arguments big_rec [R idx op I r P F].\nImplicit Arguments big_ind [R idx op I r P F].\nImplicit Arguments eq_big_op [R idx op I].\nImplicit Arguments big_endo [R idx op I].\n\nSection Extensionality.\n\nVariables (R : Type) (idx : R) (op : R -> R -> R).\n\nSection SeqExtension.\n\nVariable I : Type.\n\nLemma big_filter r (P : pred I) F :\n  \\big[op/idx]_(i <- filter P r) F i = \\big[op/idx]_(i <- r | P i) F i.\nProof. by rewrite unlock; elim: r => //= i r <-; case (P i). Qed.\n\nLemma big_filter_cond r (P1 P2 : pred I) F :\n  \\big[op/idx]_(i <- filter P1 r | P2 i) F i\n     = \\big[op/idx]_(i <- r | P1 i && P2 i) F i.\nProof.\nrewrite -big_filter -(big_filter r); congr bigop.\nrewrite -filter_predI; apply: eq_filter => i; exact: andbC.\nQed.\n\nLemma eq_bigl r (P1 P2 : pred I) F :\n    P1 =1 P2 ->\n  \\big[op/idx]_(i <- r | P1 i) F i = \\big[op/idx]_(i <- r | P2 i) F i.\nProof. by move=> eqP12; rewrite -!(big_filter r) (eq_filter eqP12). Qed.\n\n(* A lemma to permute aggregate conditions. *)\nLemma big_andbC r (P Q : pred I) F :\n  \\big[op/idx]_(i <- r | P i && Q i) F i\n    = \\big[op/idx]_(i <- r | Q i && P i) F i.\nProof. by apply: eq_bigl => i; exact: andbC. Qed.\n\nLemma eq_bigr r (P : pred I) F1 F2 : (forall i, P i -> F1 i = F2 i) ->\n  \\big[op/idx]_(i <- r | P i) F1 i = \\big[op/idx]_(i <- r | P i) F2 i.\nProof. by move=> eqF12; elim/big_rec2: _ => // i x _ /eqF12-> ->. Qed.\n\nLemma eq_big r (P1 P2 : pred I) F1 F2 :\n    P1 =1 P2 -> (forall i, P1 i -> F1 i = F2 i) ->\n  \\big[op/idx]_(i <- r | P1 i) F1 i = \\big[op/idx]_(i <- r | P2 i) F2 i.\nProof. by move/eq_bigl <-; move/eq_bigr->. Qed.\n\nLemma congr_big r1 r2 (P1 P2 : pred I) F1 F2 :\n    r1 = r2 -> P1 =1 P2 -> (forall i, P1 i -> F1 i = F2 i) ->\n  \\big[op/idx]_(i <- r1 | P1 i) F1 i = \\big[op/idx]_(i <- r2 | P2 i) F2 i.\nProof. by move=> <-{r2}; exact: eq_big. Qed.\n\nLemma big_nil (P : pred I) F : \\big[op/idx]_(i <- [::] | P i) F i = idx.\nProof. by rewrite unlock. Qed.\n\nLemma big_cons i r (P : pred I) F :\n    let x := \\big[op/idx]_(j <- r | P j) F j in\n  \\big[op/idx]_(j <- i :: r | P j) F j = if P i then op (F i) x else x.\nProof. by rewrite unlock. Qed.\n\nLemma big_map J (h : J -> I) r (P : pred I) F :\n  \\big[op/idx]_(i <- map h r | P i) F i\n     = \\big[op/idx]_(j <- r | P (h j)) F (h j).\nProof. by rewrite unlock; elim: r => //= j r ->. Qed.\n\nLemma big_nth x0 r (P : pred I) F :\n  \\big[op/idx]_(i <- r | P i) F i\n     = \\big[op/idx]_(0 <= i < size r | P (nth x0 r i)) (F (nth x0 r i)).\nProof. by rewrite -{1}(mkseq_nth x0 r) big_map /index_iota subn0. Qed.\n\nLemma big_hasC r (P : pred I) F :\n  ~~ has P r -> \\big[op/idx]_(i <- r | P i) F i = idx.\nProof.\nby rewrite -big_filter has_count count_filter -eqn0Ngt unlock => /nilP->.\nQed.\n\nLemma big_pred0_eq (r : seq I) F : \\big[op/idx]_(i <- r | false) F i = idx.\nProof. by rewrite big_hasC // has_pred0. Qed.\n\nLemma big_pred0 r (P : pred I) F :\n  P =1 xpred0 -> \\big[op/idx]_(i <- r | P i) F i = idx.\nProof. by move/eq_bigl->; exact: big_pred0_eq. Qed.\n\nLemma big_cat_nested r1 r2 (P : pred I) F :\n    let x := \\big[op/idx]_(i <- r2 | P i) F i in\n  \\big[op/idx]_(i <- r1 ++ r2 | P i) F i = \\big[op/x]_(i <- r1 | P i) F i.\nProof. by rewrite unlock /reducebig foldr_cat. Qed.\n\nLemma big_catl r1 r2 (P : pred I) F :\n    ~~ has P r2 ->\n  \\big[op/idx]_(i <- r1 ++ r2 | P i) F i = \\big[op/idx]_(i <- r1 | P i) F i.\nProof. by rewrite big_cat_nested => /big_hasC->. Qed.\n\nLemma big_catr r1 r2 (P : pred I) F :\n     ~~ has P r1 ->\n  \\big[op/idx]_(i <- r1 ++ r2 | P i) F i = \\big[op/idx]_(i <- r2 | P i) F i.\nProof.\nrewrite -big_filter -(big_filter r2) filter_cat.\nby rewrite has_count count_filter; case: filter.\nQed.\n\nLemma big_const_seq r (P : pred I) x :\n  \\big[op/idx]_(i <- r | P i) x = iter (count P r) (op x) idx.\nProof. by rewrite unlock; elim: r => //= i r ->; case: (P i). Qed.\n\nEnd SeqExtension.\n\n(* The following lemmas can be used to localise extensionality to a specific  *)\n(* index sequence. This is done by ssreflect rewriting, before applying       *)\n(* congruence or induction lemmas.                                            *)\nLemma big_seq_cond (I : eqType) r (P : pred I) F :\n  \\big[op/idx]_(i <- r | P i) F i\n    = \\big[op/idx]_(i <- r | (i \\in r) && P i) F i.\nProof.\nby rewrite -!(big_filter r); congr bigop; apply: eq_in_filter => i ->.\nQed.\n\nLemma big_seq (I : eqType) (r : seq I) F :\n  \\big[op/idx]_(i <- r) F i = \\big[op/idx]_(i <- r | i \\in r) F i.\nProof. by rewrite big_seq_cond big_andbC. Qed.\n\nLemma eq_big_seq (I : eqType) (r : seq I) F1 F2 :\n  {in r, F1 =1 F2} -> \\big[op/idx]_(i <- r) F1 i = \\big[op/idx]_(i <- r) F2 i.\nProof. by move=> eqF; rewrite !big_seq (eq_bigr _ eqF). Qed.\n\n(* Similar lemmas for exposing integer indexing in the predicate. *)\nLemma big_nat_cond m n (P : pred nat) F :\n  \\big[op/idx]_(m <= i < n | P i) F i\n    = \\big[op/idx]_(m <= i < n | (m <= i < n) && P i) F i.\nProof.\nby rewrite big_seq_cond; apply: eq_bigl => i; rewrite mem_index_iota.\nQed.\n\nLemma big_nat m n F :\n  \\big[op/idx]_(m <= i < n) F i = \\big[op/idx]_(m <= i < n | m <= i < n) F i.\nProof. by rewrite big_nat_cond big_andbC. Qed.\n\nLemma congr_big_nat m1 n1 m2 n2 P1 P2 F1 F2 :\n    m1 = m2 -> n1 = n2 ->\n    (forall i, m1 <= i < n2 -> P1 i = P2 i) ->\n    (forall i, P1 i && (m1 <= i < n2) -> F1 i = F2 i) ->\n  \\big[op/idx]_(m1 <= i < n1 | P1 i) F1 i\n    = \\big[op/idx]_(m2 <= i < n2 | P2 i) F2 i.\nProof.\nmove=> <- <- eqP12 eqF12; rewrite big_seq_cond (big_seq_cond _ P2).\napply: eq_big => i; rewrite ?inE /= !mem_index_iota.\n  by apply: andb_id2l; exact: eqP12.\nby rewrite andbC; exact: eqF12.\nQed.\n\nLemma eq_big_nat m n F1 F2 :\n    (forall i, m <= i < n -> F1 i = F2 i) ->\n  \\big[op/idx]_(m <= i < n) F1 i = \\big[op/idx]_(m <= i < n) F2 i.\nProof. by move=> eqF; apply: congr_big_nat. Qed.\n\nLemma big_geq m n (P : pred nat) F :\n  m >= n -> \\big[op/idx]_(m <= i < n | P i) F i = idx.\nProof. by move=> ge_m_n; rewrite /index_iota (eqnP ge_m_n) big_nil. Qed.\n\nLemma big_ltn_cond m n (P : pred nat) F :\n    m < n -> let x := \\big[op/idx]_(m.+1 <= i < n | P i) F i in\n  \\big[op/idx]_(m <= i < n | P i) F i = if P m then op (F m) x else x.\nProof.\nby case: n => [//|n] le_m_n; rewrite /index_iota subSn // big_cons.\nQed.\n\nLemma big_ltn m n F :\n     m < n ->\n  \\big[op/idx]_(m <= i < n) F i = op (F m) (\\big[op/idx]_(m.+1 <= i < n) F i).\nProof. move=> lt_mn; exact: big_ltn_cond. Qed.\n\nLemma big_addn m n a (P : pred nat) F :\n  \\big[op/idx]_(m + a <= i < n | P i) F i =\n     \\big[op/idx]_(m <= i < n - a | P (i + a)) F (i + a).\nProof.\nrewrite /index_iota -subnDA addnC iota_addl big_map.\nby apply: eq_big => ? *; rewrite addnC.\nQed.\n\nLemma big_add1 m n (P : pred nat) F :\n  \\big[op/idx]_(m.+1 <= i < n | P i) F i =\n     \\big[op/idx]_(m <= i < n.-1 | P (i.+1)) F (i.+1).\nProof.\nby rewrite -addn1 big_addn subn1; apply: eq_big => ? *; rewrite addn1.\nQed.\n\nLemma big_nat_recl n F :\n  \\big[op/idx]_(0 <= i < n.+1) F i =\n     op (F 0) (\\big[op/idx]_(0 <= i < n) F i.+1).\nProof. by rewrite big_ltn // big_add1. Qed.\n\nLemma big_mkord n (P : pred nat) F :\n  \\big[op/idx]_(0 <= i < n | P i) F i = \\big[op/idx]_(i < n | P i) F i.\nProof.\nrewrite /index_iota subn0 -(big_map (@nat_of_ord n)).\nby congr bigop; rewrite /index_enum unlock val_ord_enum.\nQed.\n\nLemma big_nat_widen m n1 n2 (P : pred nat) F :\n     n1 <= n2 ->\n  \\big[op/idx]_(m <= i < n1 | P i) F i\n      = \\big[op/idx]_(m <= i < n2 | P i && (i < n1)) F i.\nProof.\nmove=> len12; symmetry; rewrite -big_filter filter_predI big_filter.\nhave [ltn_trans eq_by_mem] := (ltn_trans, eq_sorted_irr ltn_trans ltnn).\ncongr bigop; apply: eq_by_mem; rewrite ?sorted_filter ?iota_ltn_sorted // => i.\nrewrite mem_filter !mem_index_iota andbCA andbA andb_idr => // /andP[_].\nby move/leq_trans->.\nQed.\n\nLemma big_ord_widen_cond n1 n2 (P : pred nat) (F : nat -> R) :\n     n1 <= n2 ->\n  \\big[op/idx]_(i < n1 | P i) F i\n      = \\big[op/idx]_(i < n2 | P i && (i < n1)) F i.\nProof. by move/big_nat_widen=> len12; rewrite -big_mkord len12 big_mkord. Qed.\n\nLemma big_ord_widen n1 n2 (F : nat -> R) :\n    n1 <= n2 ->\n  \\big[op/idx]_(i < n1) F i = \\big[op/idx]_(i < n2 | i < n1) F i.\nProof. by move=> le_n12; exact: (big_ord_widen_cond (predT)). Qed.\n\nLemma big_ord_widen_leq n1 n2 (P : pred 'I_(n1.+1)) F :\n    n1 < n2 ->\n  \\big[op/idx]_(i < n1.+1 | P i) F i\n      = \\big[op/idx]_(i < n2 | P (inord i) && (i <= n1)) F (inord i).\nProof.\nmove=> len12; pose g G i := G (inord i : 'I_(n1.+1)).\nrewrite -(big_ord_widen_cond (g _ P) (g _ F) len12) {}/g.\nby apply: eq_big => i *; rewrite inord_val.\nQed.\n\nLemma big_ord0 P F : \\big[op/idx]_(i < 0 | P i) F i = idx.\nProof. by rewrite big_pred0 => [|[]]. Qed.\n\nImport tuple.\nLemma big_tnth I r (P : pred I) F :\n  let r_ := tnth (in_tuple r) in\n  \\big[op/idx]_(i <- r | P i) F i\n     = \\big[op/idx]_(i < size r | P (r_ i)) (F (r_ i)).\nProof.\ncase: r => /= [|x0 r]; first by rewrite big_nil big_ord0.\nby rewrite (big_nth x0) big_mkord; apply: eq_big => i; rewrite (tnth_nth x0).\nQed.\n\nLemma big_ord_narrow_cond n1 n2 (P : pred 'I_n2) F (le_n12 : n1 <= n2) :\n    let w := widen_ord le_n12 in\n  \\big[op/idx]_(i < n2 | P i && (i < n1)) F i\n    = \\big[op/idx]_(i < n1 | P (w i)) F (w i).\nProof.\ncase: n1 => [|n1] /= in le_n12 *.\n  by rewrite big_ord0 big_pred0 // => i; rewrite andbF.\nrewrite (big_ord_widen_leq _ _ le_n12); apply: eq_big => i.\n  by apply: andb_id2r => le_i_n1; congr P; apply: val_inj; rewrite /= inordK.\nby case/andP=> _ le_i_n1; congr F; apply: val_inj; rewrite /= inordK.\nQed.\n\nLemma big_ord_narrow_cond_leq n1 n2 (P : pred _) F (le_n12 : n1 <= n2) :\n    let w := @widen_ord n1.+1 n2.+1 le_n12 in\n  \\big[op/idx]_(i < n2.+1 | P i && (i <= n1)) F i\n  = \\big[op/idx]_(i < n1.+1 | P (w i)) F (w i).\nProof. exact: (@big_ord_narrow_cond n1.+1 n2.+1). Qed.\n\nLemma big_ord_narrow n1 n2 F (le_n12 : n1 <= n2) :\n    let w := widen_ord le_n12 in\n  \\big[op/idx]_(i < n2 | i < n1) F i = \\big[op/idx]_(i < n1) F (w i).\nProof. exact: (big_ord_narrow_cond (predT)). Qed.\n\nLemma big_ord_narrow_leq n1 n2 F (le_n12 : n1 <= n2) :\n    let w := @widen_ord n1.+1 n2.+1 le_n12 in\n  \\big[op/idx]_(i < n2.+1 | i <= n1) F i = \\big[op/idx]_(i < n1.+1) F (w i).\nProof.  exact: (big_ord_narrow_cond_leq (predT)). Qed.\n\nLemma big_ord_recl n F :\n  \\big[op/idx]_(i < n.+1) F i =\n     op (F ord0) (\\big[op/idx]_(i < n) F (@lift n.+1 ord0 i)).\nProof.\npose G i := F (inord i); have eqFG i: F i = G i by rewrite /G inord_val.\nrewrite (eq_bigr _ (fun i _ => eqFG i)) -(big_mkord _ (fun _ => _) G) eqFG.\nrewrite big_ltn // big_add1 /= big_mkord; congr op.\nby apply: eq_bigr => i _; rewrite eqFG.\nQed.\n\nLemma big_const (I : finType) (A : pred I) x :\n  \\big[op/idx]_(i in A) x = iter #|A| (op x) idx.\nProof. by rewrite big_const_seq count_filter cardE. Qed.\n\nLemma big_const_nat m n x :\n  \\big[op/idx]_(m <= i < n) x = iter (n - m) (op x) idx.\nProof. by rewrite big_const_seq count_predT size_iota. Qed.\n\nLemma big_const_ord n x :\n  \\big[op/idx]_(i < n) x = iter n (op x) idx.\nProof. by rewrite big_const card_ord. Qed.\n\nEnd Extensionality.\n\nSection MonoidProperties.\n\nImport Monoid.Theory.\n\nVariable R : Type.\n\nVariable idx : R.\nNotation Local \"1\" := idx.\n\nSection Plain.\n\nVariable op : Monoid.law 1.\n\nNotation Local \"*%M\" := op (at level 0).\nNotation Local \"x * y\" := (op x y).\n\nLemma eq_big_idx_seq idx' I r (P : pred I) F :\n     right_id idx' *%M -> has P r ->\n   \\big[*%M/idx']_(i <- r | P i) F i =\\big[*%M/1]_(i <- r | P i) F i.\nProof.\nmove=> op_idx'; rewrite -!(big_filter _ _ r) has_count count_filter.\ncase/lastP: (filter P r) => {r}// r i _.\nby rewrite -cats1 !(big_cat_nested, big_cons, big_nil) op_idx' mulm1.\nQed.\n\nLemma eq_big_idx idx' (I : finType) i0 (P : pred I) F :\n     P i0 -> right_id idx' *%M ->\n  \\big[*%M/idx']_(i | P i) F i =\\big[*%M/1]_(i | P i) F i.\nProof.\nby move=> Pi0 op_idx'; apply: eq_big_idx_seq => //; apply/hasP; exists i0.\nQed.\n\nLemma big1_eq I r (P : pred I) : \\big[*%M/1]_(i <- r | P i) 1 = 1.\nProof.\nby rewrite big_const_seq; elim: (count _ _) => //= n ->; exact: mul1m.\nQed.\n\nLemma big1 I r (P : pred I) F :\n  (forall i, P i -> F i = 1) -> \\big[*%M/1]_(i <- r | P i) F i = 1.\nProof. by move/(eq_bigr _)->; exact: big1_eq. Qed.\n\nLemma big1_seq (I : eqType) r (P : pred I) F :\n    (forall i, P i && (i \\in r) -> F i = 1) ->\n  \\big[*%M/1]_(i <- r | P i) F i = 1.\nProof. by move=> eqF1; rewrite big_seq_cond big_andbC big1. Qed.\n\nLemma big_seq1 I (i : I) F : \\big[*%M/1]_(j <- [:: i]) F j = F i.\nProof. by rewrite unlock /= mulm1. Qed.\n\nLemma big_mkcond I r (P : pred I) F :\n  \\big[*%M/1]_(i <- r | P i) F i =\n     \\big[*%M/1]_(i <- r) (if P i then F i else 1).\nProof. by rewrite unlock; elim: r => //= i r ->; case P; rewrite ?mul1m. Qed.\n\nLemma big_mkcondr I r (P Q : pred I) F :\n  \\big[*%M/1]_(i <- r | P i && Q i) F i =\n     \\big[*%M/1]_(i <- r | P i) (if Q i then F i else 1).\nProof. by rewrite -big_filter_cond big_mkcond big_filter. Qed.\n\nLemma big_mkcondl I r (P Q : pred I) F :\n  \\big[*%M/1]_(i <- r | P i && Q i) F i =\n     \\big[*%M/1]_(i <- r | Q i) (if P i then F i else 1).\nProof. by rewrite big_andbC big_mkcondr. Qed.\n\nLemma big_cat I r1 r2 (P : pred I) F :\n  \\big[*%M/1]_(i <- r1 ++ r2 | P i) F i =\n     \\big[*%M/1]_(i <- r1 | P i) F i * \\big[*%M/1]_(i <- r2 | P i) F i.\nProof.\nrewrite !(big_mkcond _ P) unlock.\nby elim: r1 => /= [|i r1 ->]; rewrite (mul1m, mulmA).\nQed.\n\nLemma big_pred1_eq (I : finType) (i : I) F :\n  \\big[*%M/1]_(j | j == i) F j = F i.\nProof. by rewrite -big_filter filter_index_enum enum1 big_seq1. Qed.\n\nLemma big_pred1 (I : finType) i (P : pred I) F :\n  P =1 pred1 i -> \\big[*%M/1]_(j | P j) F j = F i.\nProof. by move/(eq_bigl _ _)->; exact: big_pred1_eq. Qed.\n\nLemma big_cat_nat n m p (P : pred nat) F : m <= n -> n <= p ->\n  \\big[*%M/1]_(m <= i < p | P i) F i =\n   (\\big[*%M/1]_(m <= i < n | P i) F i) * (\\big[*%M/1]_(n <= i < p | P i) F i).\nProof.\nmove=> le_mn le_np; rewrite -big_cat -{2}(subnKC le_mn) -iota_add subnDA.\nby rewrite subnKC // leq_sub.\nQed.\n\nLemma big_nat1 n F : \\big[*%M/1]_(n <= i < n.+1) F i = F n.\nProof. by rewrite big_ltn // big_geq // mulm1. Qed.\n\nLemma big_nat_recr n F :\n  \\big[*%M/1]_(0 <= i < n.+1) F i = (\\big[*%M/1]_(0 <= i < n) F i) * F n.\nProof. by rewrite (@big_cat_nat n) ?leqnSn // big_nat1. Qed.\n\nLemma big_ord_recr n F :\n  \\big[*%M/1]_(i < n.+1) F i =\n     (\\big[*%M/1]_(i < n) F (widen_ord (leqnSn n) i)) * F ord_max.\nProof.\ntransitivity (\\big[*%M/1]_(0 <= i < n.+1) F (inord i)).\n  by rewrite big_mkord; apply: eq_bigr=> i _; rewrite inord_val.\nrewrite big_nat_recr big_mkord; congr (_ * F _); last first.\n  by apply: val_inj; rewrite /= inordK.\nby apply: eq_bigr => [] i _; congr F; apply: ord_inj; rewrite inordK //= leqW.\nQed.\n\nLemma big_sumType (I1 I2 : finType) (P : pred (I1 + I2)) F :\n  \\big[*%M/1]_(i | P i) F i =\n        (\\big[*%M/1]_(i | P (inl _ i)) F (inl _ i))\n      * (\\big[*%M/1]_(i | P (inr _ i)) F (inr _ i)).\nProof.\nby rewrite /index_enum {1}[@Finite.enum]unlock /= big_cat !big_map.\nQed.\n\nLemma big_split_ord m n (P : pred 'I_(m + n)) F :\n  \\big[*%M/1]_(i | P i) F i =\n        (\\big[*%M/1]_(i | P (lshift n i)) F (lshift n i))\n      * (\\big[*%M/1]_(i | P (rshift m i)) F (rshift m i)).\nProof.\nrewrite -(big_map _ _ (lshift n) _ P F) -(big_map _ _ (@rshift m _) _ P F).\nrewrite -big_cat; congr bigop; apply: (inj_map val_inj).\nrewrite /index_enum -!enumT val_enum_ord map_cat -map_comp val_enum_ord.\nrewrite -map_comp (map_comp (addn m)) val_enum_ord.\nby rewrite -iota_addl addn0 iota_add.\nQed.\n\nEnd Plain.\n\nSection Abelian.\n\nVariable op : Monoid.com_law 1.\n\nNotation Local \"'*%M'\" := op (at level 0).\nNotation Local \"x * y\" := (op x y).\n\nLemma eq_big_perm (I : eqType) r1 r2 (P : pred I) F :\n    perm_eq r1 r2 ->\n  \\big[*%M/1]_(i <- r1 | P i) F i = \\big[*%M/1]_(i <- r2 | P i) F i.\nProof.\nmove/perm_eqP; rewrite !(big_mkcond _ _ P).\nelim: r1 r2 => [|i r1 IHr1] r2 eq_r12.\n  by case: r2 eq_r12 => // i r2; move/(_ (pred1 i)); rewrite /= eqxx.\nhave r2i: i \\in r2 by rewrite -has_pred1 has_count -eq_r12 /= eqxx.\ncase/splitPr: r2 / r2i => [r3 r4] in eq_r12 *; rewrite big_cat /= !big_cons.\nrewrite mulmCA; congr (_ * _); rewrite -big_cat; apply: IHr1 => a.\nmove/(_ a): eq_r12; rewrite !count_cat /= addnCA; exact: addnI.\nQed.\n\nLemma big_uniq (I : finType) (r : seq I) F :\n  uniq r -> \\big[*%M/1]_(i <- r) F i = \\big[*%M/1]_(i in r) F i.\nProof.\nmove=> uniq_r; rewrite -(big_filter _ _ _ (mem r)); apply: eq_big_perm.\nby rewrite filter_index_enum uniq_perm_eq ?enum_uniq // => i; rewrite mem_enum.\nQed.\n\nLemma big_index_uniq (I : eqType) (r : seq I) (E : 'I_(size r) -> R) :\n    uniq r ->\n  \\big[*%M/1]_i E i = \\big[*%M/1]_(x <- r) oapp E idx (insub (index x r)).\nProof.\nmove=> Ur; apply/esym; rewrite big_tnth; apply: eq_bigr => i _.\nby rewrite index_uniq // valK.\nQed.\n\nLemma big_rem (I : eqType) r x (P : pred I) F :\n    x \\in r ->\n  \\big[*%M/1]_(y <- r | P y) F y\n    = (if P x then F x else 1) * \\big[*%M/1]_(y <- rem x r | P y) F y.\nProof.\nby move/perm_to_rem/(eq_big_perm _)->; rewrite !(big_mkcond _ _ P) big_cons.\nQed.\n\nLemma big_undup (I : eqType) (r : seq I) (P : pred I) F :\n    idempotent *%M ->\n  \\big[*%M/1]_(i <- undup r | P i) F i = \\big[*%M/1]_(i <- r | P i) F i.\nProof.\nmove=> idM; rewrite -!(big_filter _ _ _ P) filter_undup.\nelim: {P r}(filter P r) => //= i r IHr.\ncase: ifP => [r_i | _]; rewrite !big_cons {}IHr //.\nby rewrite (big_rem _ _ r_i) mulmA idM.\nQed.\n\nLemma eq_big_idem (I : eqType) (r1 r2 : seq I) (P : pred I) F :\n    idempotent *%M -> r1 =i r2 ->\n  \\big[*%M/1]_(i <- r1 | P i) F i = \\big[*%M/1]_(i <- r2 | P i) F i.\nProof.\nmove=> idM eq_r; rewrite -big_undup // -(big_undup r2) //; apply/eq_big_perm.\nby rewrite uniq_perm_eq ?undup_uniq // => i; rewrite !mem_undup eq_r.\nQed.\n\nLemma big_split I r (P : pred I) F1 F2 :\n  \\big[*%M/1]_(i <- r | P i) (F1 i * F2 i) =\n    \\big[*%M/1]_(i <- r | P i) F1 i * \\big[*%M/1]_(i <- r | P i) F2 i.\nProof.\nby elim/big_rec3: _ => [|i x y _ _ ->]; rewrite ?mulm1 // mulmCA -!mulmA mulmCA.\nQed.\n\nLemma bigID I r (a P : pred I) F :\n  \\big[*%M/1]_(i <- r | P i) F i =\n    \\big[*%M/1]_(i <- r | P i && a i) F i *\n    \\big[*%M/1]_(i <- r | P i && ~~ a i) F i.\nProof.\nrewrite !(big_mkcond _ _ _ F) -big_split.\nby apply: eq_bigr => i; case: (a i); rewrite !simpm.\nQed.\nImplicit Arguments bigID [I r].\n\nLemma bigU (I : finType) (A B : pred I) F :\n    [disjoint A & B] ->\n  \\big[*%M/1]_(i in [predU A & B]) F i =\n    (\\big[*%M/1]_(i in A) F i) * (\\big[*%M/1]_(i in B) F i).\nProof.\nmove=> dAB; rewrite (bigID (mem A)).\ncongr (_ * _); apply: eq_bigl => i; first by rewrite orbK.\nby have:= pred0P dAB i; rewrite andbC /= !inE; case: (i \\in A).\nQed.\n\nLemma bigD1 (I : finType) j (P : pred I) F :\n  P j -> \\big[*%M/1]_(i | P i) F i\n    = F j * \\big[*%M/1]_(i | P i && (i != j)) F i.\nProof.\nmove=> Pj; rewrite (bigID (pred1 j)); congr (_ * _).\nby apply: big_pred1 => i; rewrite /= andbC; case: eqP => // ->.\nQed.\nImplicit Arguments bigD1 [I P F].\n\nLemma bigD1_seq (I : eqType) (r : seq I) j F : \n    j \\in r -> uniq r ->\n  \\big[*%M/1]_(i <- r) F i = F j * \\big[*%M/1]_(i <- r | i != j) F i.\nProof. by move=> /big_rem-> /rem_filter->; rewrite big_filter. Qed.\n\nLemma cardD1x (I : finType) (A : pred I) j :\n  A j -> #|SimplPred A| = 1 + #|[pred i | A i & i != j]|.\nProof.\nmove=> Aj; rewrite (cardD1 j) [j \\in A]Aj; congr (_ + _).\nby apply: eq_card => i; rewrite inE /= andbC.\nQed.\nImplicit Arguments cardD1x [I A].\n\nLemma partition_big (I J : finType) (P : pred I) p (Q : pred J) F :\n    (forall i, P i -> Q (p i)) ->\n      \\big[*%M/1]_(i | P i) F i =\n         \\big[*%M/1]_(j | Q j) \\big[*%M/1]_(i | P i && (p i == j)) F i.\nProof.\nmove=> Qp; transitivity (\\big[*%M/1]_(i | P i && Q (p i)) F i).\n  by apply: eq_bigl => i; case Pi: (P i); rewrite // Qp.\nelim: {Q Qp}_.+1 {-2}Q (ltnSn #|Q|) => // n IHn Q.\ncase: (pickP Q) => [j Qj | Q0 _]; last first.\n  by rewrite !big_pred0 // => i; rewrite Q0 andbF.\nrewrite ltnS (cardD1x j Qj) (bigD1 j) //; move/IHn=> {n IHn} <-.\nrewrite (bigID (fun i => p i == j)); congr (_ * _); apply: eq_bigl => i.\n  by case: eqP => [-> | _]; rewrite !(Qj, simpm).\nby rewrite andbA.\nQed.\n\nImplicit Arguments partition_big [I J P F].\n\nLemma reindex_onto (I J : finType) (h : J -> I) h' (P : pred I) F :\n   (forall i, P i -> h (h' i) = i) ->\n  \\big[*%M/1]_(i | P i) F i =\n    \\big[*%M/1]_(j | P (h j) && (h' (h j) == j)) F (h j).\nProof.\nmove=> h'K; elim: {P}_.+1 {-3}P h'K (ltnSn #|P|) => //= n IHn P h'K.\ncase: (pickP P) => [i Pi | P0 _]; last first.\n  by rewrite !big_pred0 // => j; rewrite P0.\nrewrite ltnS (cardD1x i Pi); move/IHn {n IHn} => IH.\nrewrite (bigD1 i Pi) (bigD1 (h' i)) h'K ?Pi ?eq_refl //=; congr (_ * _).\nrewrite {}IH => [|j]; [apply: eq_bigl => j | by case/andP; auto].\nrewrite andbC -andbA (andbCA (P _)); case: eqP => //= hK; congr (_ && ~~ _).\nby apply/eqP/eqP=> [<-|->] //; rewrite h'K.\nQed.\nImplicit Arguments reindex_onto [I J P F].\n\nLemma reindex (I J : finType) (h : J -> I) (P : pred I) F :\n    {on [pred i | P i], bijective h} ->\n  \\big[*%M/1]_(i | P i) F i = \\big[*%M/1]_(j | P (h j)) F (h j).\nProof.\ncase=> h' hK h'K; rewrite (reindex_onto h h' h'K).\nby apply: eq_bigl => j; rewrite !inE; case Pi: (P _); rewrite //= hK ?eqxx.\nQed.\nImplicit Arguments reindex [I J P F].\n\nLemma reindex_inj (I : finType) (h : I -> I) (P : pred I) F :\n  injective h -> \\big[*%M/1]_(i | P i) F i = \\big[*%M/1]_(j | P (h j)) F (h j).\nProof. move=> injh; exact: reindex (onW_bij _ (injF_bij injh)). Qed.\nImplicit Arguments reindex_inj [I h P F].\n\nLemma big_nat_rev m n P F :\n  \\big[*%M/1]_(m <= i < n | P i) F i\n     = \\big[*%M/1]_(m <= i < n | P (m + n - i.+1)) F (m + n - i.+1).\nProof.\ncase: (ltnP m n) => ltmn; last by rewrite !big_geq.\nrewrite -{3 4}(subnK (ltnW ltmn)) addnA.\ndo 2!rewrite (big_addn _ _ 0) big_mkord; rewrite (reindex_inj rev_ord_inj) /=.\nby apply: eq_big => [i | i _]; rewrite /= -addSn subnDr addnC addnBA.\nQed.\n\nLemma pair_big_dep (I J : finType) (P : pred I) (Q : I -> pred J) F :\n  \\big[*%M/1]_(i | P i) \\big[*%M/1]_(j | Q i j) F i j =\n    \\big[*%M/1]_(p | P p.1 && Q p.1 p.2) F p.1 p.2.\nProof.\nrewrite (partition_big (fun p => p.1) P) => [|j]; last by case/andP.\napply: eq_bigr => i /= Pi; rewrite (reindex_onto (pair i) (fun p => p.2)).\n   by apply: eq_bigl => j; rewrite !eqxx [P i]Pi !andbT.\nby case=> i' j /=; case/andP=> _ /=; move/eqP->.\nQed.\n\nLemma pair_big (I J : finType) (P : pred I) (Q : pred J) F :\n  \\big[*%M/1]_(i | P i) \\big[*%M/1]_(j | Q j) F i j =\n    \\big[*%M/1]_(p | P p.1 && Q p.2) F p.1 p.2.\nProof. exact: pair_big_dep. Qed.\n\nLemma pair_bigA (I J : finType) (F : I -> J -> R) :\n  \\big[*%M/1]_i \\big[*%M/1]_j F i j = \\big[*%M/1]_p F p.1 p.2.\nProof. exact: pair_big_dep. Qed.\n\nLemma exchange_big_dep I J rI rJ (P : pred I) (Q : I -> pred J)\n                       (xQ : pred J) F :\n    (forall i j, P i -> Q i j -> xQ j) ->\n  \\big[*%M/1]_(i <- rI | P i) \\big[*%M/1]_(j <- rJ | Q i j) F i j =\n    \\big[*%M/1]_(j <- rJ | xQ j) \\big[*%M/1]_(i <- rI | P i && Q i j) F i j.\nProof.\nmove=> PQxQ; pose p u := (u.2, u.1).\nrewrite (eq_bigr _ _ _ (fun _ _ => big_tnth _ _ rI _ _)) (big_tnth _ _ rJ).\nrewrite (eq_bigr _ _ _ (fun _ _ => (big_tnth _ _ rJ _ _))) big_tnth.\nrewrite !pair_big_dep (reindex_onto (p _ _) (p _ _)) => [|[]] //=.\napply: eq_big => [] [j i] //=; symmetry; rewrite eqxx andbT andb_idl //.\nby case/andP; exact: PQxQ.\nQed.\nImplicit Arguments exchange_big_dep [I J rI rJ P Q F].\n\nLemma exchange_big I J rI rJ (P : pred I) (Q : pred J) F :\n  \\big[*%M/1]_(i <- rI | P i) \\big[*%M/1]_(j <- rJ | Q j) F i j =\n    \\big[*%M/1]_(j <- rJ | Q j) \\big[*%M/1]_(i <- rI | P i) F i j.\nProof.\nrewrite (exchange_big_dep Q) //; apply: eq_bigr => i /= Qi.\nby apply: eq_bigl => j; rewrite Qi andbT.\nQed.\n\nLemma exchange_big_dep_nat m1 n1 m2 n2 (P : pred nat) (Q : rel nat)\n                           (xQ : pred nat) F :\n    (forall i j, m1 <= i < n1 -> m2 <= j < n2 -> P i -> Q i j -> xQ j) ->\n  \\big[*%M/1]_(m1 <= i < n1 | P i) \\big[*%M/1]_(m2 <= j < n2 | Q i j) F i j =\n    \\big[*%M/1]_(m2 <= j < n2 | xQ j)\n       \\big[*%M/1]_(m1 <= i < n1 | P i && Q i j) F i j.\nProof.\nmove=> PQxQ; rewrite (eq_bigr _ _ _ (fun _ _ => big_seq_cond _ _ _ _ _)).\nrewrite big_seq_cond /= (exchange_big_dep xQ) => [|i j]; last first.\n  by rewrite !mem_index_iota => /andP[mn_i Pi] /andP[mn_j /PQxQ->].\nrewrite 2!(big_seq_cond _ _ _ xQ); apply: eq_bigr => j /andP[-> _] /=.\nby rewrite [rhs in _ = rhs]big_seq_cond; apply: eq_bigl => i; rewrite -andbA.\nQed.\nImplicit Arguments exchange_big_dep_nat [m1 n1 m2 n2 P Q F].\n\nLemma exchange_big_nat m1 n1 m2 n2 (P Q : pred nat) F :\n  \\big[*%M/1]_(m1 <= i < n1 | P i) \\big[*%M/1]_(m2 <= j < n2 | Q j) F i j =\n    \\big[*%M/1]_(m2 <= j < n2 | Q j) \\big[*%M/1]_(m1 <= i < n1 | P i) F i j.\nProof.\nrewrite (exchange_big_dep_nat Q) //.\nby apply: eq_bigr => i /= Qi; apply: eq_bigl => j; rewrite Qi andbT.\nQed.\n\nEnd Abelian.\n\nEnd MonoidProperties.\n\nImplicit Arguments big_filter [R op idx I].\nImplicit Arguments big_filter_cond [R op idx I].\nImplicit Arguments congr_big [R op idx I r1 P1 F1].\nImplicit Arguments eq_big [R op idx I r P1 F1].\nImplicit Arguments eq_bigl [R op idx  I r P1].\nImplicit Arguments eq_bigr [R op idx I r  P F1].\nImplicit Arguments eq_big_idx [R op idx idx' I P F].\nImplicit Arguments big_seq_cond [R op idx I r].\nImplicit Arguments eq_big_seq [R op idx I r F1].\nImplicit Arguments congr_big_nat [R op idx m1 n1 P1 F1].\nImplicit Arguments big_map [R op idx I J r].\nImplicit Arguments big_nth [R op idx I r].\nImplicit Arguments big_catl [R op idx I r1 r2 P F].\nImplicit Arguments big_catr [R op idx I r1 r2  P F].\nImplicit Arguments big_geq [R op idx m n P F].\nImplicit Arguments big_ltn_cond [R op idx m n P F].\nImplicit Arguments big_ltn [R op idx m n F].\nImplicit Arguments big_addn [R op idx].\nImplicit Arguments big_mkord [R op idx n].\nImplicit Arguments big_nat_widen [R op idx] .\nImplicit Arguments big_ord_widen_cond [R op idx n1].\nImplicit Arguments big_ord_widen [R op idx n1].\nImplicit Arguments big_ord_widen_leq [R op idx n1].\nImplicit Arguments big_ord_narrow_cond [R op idx n1 n2 P F].\nImplicit Arguments big_ord_narrow_cond_leq [R op idx n1 n2 P F].\nImplicit Arguments big_ord_narrow [R op idx n1 n2 F].\nImplicit Arguments big_ord_narrow_leq [R op idx n1 n2 F].\nImplicit Arguments big_mkcond [R op idx I r].\nImplicit Arguments big1_eq [R op idx I].\nImplicit Arguments big1_seq [R op idx I].\nImplicit Arguments big1 [R op idx I].\nImplicit Arguments big_pred1 [R op idx I P F].\nImplicit Arguments eq_big_perm [R op idx I r1 P F].\nImplicit Arguments big_uniq [R op idx I F].\nImplicit Arguments big_rem [R op idx I r P F].\nImplicit Arguments bigID [R op idx I r].\nImplicit Arguments bigU [R op idx I].\nImplicit Arguments bigD1 [R op idx I P F].\nImplicit Arguments bigD1_seq [R op idx I r F].\nImplicit Arguments partition_big [R op idx I J P F].\nImplicit Arguments reindex_onto [R op idx I J P F].\nImplicit Arguments reindex [R op idx I J P F].\nImplicit Arguments reindex_inj [R op idx I h P F].\nImplicit Arguments pair_big_dep [R op idx I J].\nImplicit Arguments pair_big [R op idx I J].\nImplicit Arguments exchange_big_dep [R op idx I J rI rJ P Q F].\nImplicit Arguments exchange_big_dep_nat [R op idx m1 n1 m2 n2 P Q F].\nImplicit Arguments big_ord_recl [R op idx].\nImplicit Arguments big_ord_recr [R op idx].\nImplicit Arguments big_nat_recl [R op idx].\nImplicit Arguments big_nat_recr [R op idx].\n\nSection Distributivity.\n\nImport Monoid.Theory.\n\nVariable R : Type.\nVariables zero one : R.\nNotation Local \"0\" := zero.\nNotation Local \"1\" := one.\nVariable times : Monoid.mul_law 0.\nNotation Local \"*%M\" := times (at level 0).\nNotation Local \"x * y\" := (times x y).\nVariable plus : Monoid.add_law 0 *%M.\nNotation Local \"+%M\" := plus (at level 0).\nNotation Local \"x + y\" := (plus x y).\n\nLemma big_distrl I r a (P : pred I) F :\n  \\big[+%M/0]_(i <- r | P i) F i * a = \\big[+%M/0]_(i <- r | P i) (F i * a).\nProof. by rewrite (big_endo ( *%M^~ a)) ?mul0m // => x y; exact: mulm_addl. Qed.\n\nLemma big_distrr I r a (P : pred I) F :\n  a * \\big[+%M/0]_(i <- r | P i) F i = \\big[+%M/0]_(i <- r | P i) (a * F i).\nProof. by rewrite big_endo ?mulm0 // => x y; exact: mulm_addr. Qed.\n\nLemma big_distrlr I J rI rJ (pI : pred I) (pJ : pred J) F G :\n  (\\big[+%M/0]_(i <- rI | pI i) F i) * (\\big[+%M/0]_(j <- rJ | pJ j) G j)\n   = \\big[+%M/0]_(i <- rI | pI i) \\big[+%M/0]_(j <- rJ | pJ j) (F i * G j).\nProof. by rewrite big_distrl; apply: eq_bigr => i _; rewrite big_distrr. Qed.\n\nLemma big_distr_big_dep (I J : finType) j0 (P : pred I) (Q : I -> pred J) F :\n  \\big[*%M/1]_(i | P i) \\big[+%M/0]_(j | Q i j) F i j =\n     \\big[+%M/0]_(f in pfamily j0 P Q) \\big[*%M/1]_(i | P i) F i (f i).\nProof.\npose fIJ := {ffun I -> J}; pose Pf := pfamily j0 (_ : seq I) Q.\nrewrite -big_filter filter_index_enum; set r := enum P; symmetry.\ntransitivity (\\big[+%M/0]_(f in Pf r) \\big[*%M/1]_(i <- r) F i (f i)).\n  apply: eq_big => f; last by rewrite -big_filter filter_index_enum.\n  by apply: eq_forallb => i; rewrite /= mem_enum.\nhave: uniq r by exact: enum_uniq.\nelim: {P}r => /= [_ | i r IHr].\n  rewrite (big_pred1 [ffun => j0]) ?big_nil //= => f.\n  apply/familyP/eqP=> /= [Df |->{f} i]; last by rewrite ffunE !inE.\n  by apply/ffunP=> i; rewrite ffunE; exact/eqP/Df.\ncase/andP=> /negbTE nri; rewrite big_cons big_distrl => {IHr}/IHr <-.\nrewrite (partition_big (fun f : fIJ => f i) (Q i)) => [|f]; last first.\n  by move/familyP/(_ i); rewrite /= inE /= eqxx.\npose seti j (f : fIJ) := [ffun k => if k == i then j else f k].\napply: eq_bigr => j Qij.\nrewrite (reindex_onto (seti j) (seti j0)) => [|f /andP[_ /eqP fi]]; last first.\n  by apply/ffunP=> k; rewrite !ffunE; case: eqP => // ->.\nrewrite big_distrr; apply: eq_big => [f | f eq_f]; last first.\n  rewrite big_cons ffunE eqxx !big_seq; congr (_ * _).\n  by apply: eq_bigr => k; rewrite ffunE; case: eqP nri => // -> ->.\nrewrite !ffunE !eqxx andbT; apply/andP/familyP=> /= [[Pjf fij0] k | Pff].\n  have:= familyP Pjf k; rewrite /= ffunE inE; case: eqP => // -> _.\n  by rewrite nri -(eqP fij0) !ffunE !inE !eqxx.\nsplit; [apply/familyP | apply/eqP/ffunP] => k; have:= Pff k; rewrite !ffunE.\n  by rewrite inE; case: eqP => // ->.\nby case: eqP => // ->; rewrite nri /= => /eqP.\nQed.\n\nLemma big_distr_big (I J : finType) j0 (P : pred I) (Q : pred J) F :\n  \\big[*%M/1]_(i | P i) \\big[+%M/0]_(j | Q j) F i j =\n     \\big[+%M/0]_(f in pffun_on j0 P Q) \\big[*%M/1]_(i | P i) F i (f i).\nProof.\nrewrite (big_distr_big_dep j0); apply: eq_bigl => f.\nby apply/familyP/familyP=> Pf i; case: ifP (Pf i).\nQed.\n\nLemma bigA_distr_big_dep (I J : finType) (Q : I -> pred J) F :\n  \\big[*%M/1]_i \\big[+%M/0]_(j | Q i j) F i j\n    = \\big[+%M/0]_(f in family Q) \\big[*%M/1]_i F i (f i).\nProof.\ncase: (pickP J) => [j0 _ | J0]; first exact: (big_distr_big_dep j0).\nrewrite {1 4}/index_enum -enumT; case: (enum I) (mem_enum I) => [I0 | i r _].\n  have f0: I -> J by move=> i; have:= I0 i.\n  rewrite (big_pred1 (finfun f0)) ?big_nil // => g.\n  by apply/familyP/eqP=> _; first apply/ffunP; move=> i; have:= I0 i.\nhave Q0 i': Q i' =1 pred0 by move=> j; have:= J0 j.\nrewrite big_cons /= big_pred0 // mul0m big_pred0 // => f.\nby apply/familyP=> /(_ i); rewrite [_ \\in _]Q0.\nQed.\n\nLemma bigA_distr_big (I J : finType) (Q : pred J) (F : I -> J -> R) :\n  \\big[*%M/1]_i \\big[+%M/0]_(j | Q j) F i j\n    = \\big[+%M/0]_(f in ffun_on Q) \\big[*%M/1]_i F i (f i).\nProof. exact: bigA_distr_big_dep. Qed.\n\nLemma bigA_distr_bigA (I J : finType) F :\n  \\big[*%M/1]_(i : I) \\big[+%M/0]_(j : J) F i j\n    = \\big[+%M/0]_(f : {ffun I -> J}) \\big[*%M/1]_i F i (f i).\nProof. by rewrite bigA_distr_big; apply: eq_bigl => ?; exact/familyP. Qed.\n\nEnd Distributivity.\n\nImplicit Arguments big_distrl [R zero times plus I r].\nImplicit Arguments big_distrr [R zero times plus I r].\nImplicit Arguments big_distr_big_dep [R zero one times plus I J].\nImplicit Arguments big_distr_big [R zero one times plus I J].\nImplicit Arguments bigA_distr_big_dep [R zero one times plus I J].\nImplicit Arguments bigA_distr_big [R zero one times plus I J].\nImplicit Arguments bigA_distr_bigA [R zero one times plus I J].\n\nSection BigBool.\n\nSection Seq.\n\nVariables (I : Type) (r : seq I) (P B : pred I).\n\nLemma big_has : \\big[orb/false]_(i <- r) B i = has B r.\nProof. by rewrite unlock. Qed.\n\nLemma big_all : \\big[andb/true]_(i <- r) B i = all B r.\nProof. by rewrite unlock. Qed.\n\nLemma big_has_cond : \\big[orb/false]_(i <- r | P i) B i = has (predI P B) r.\nProof. by rewrite big_mkcond unlock. Qed.\n\nLemma big_all_cond :\n  \\big[andb/true]_(i <- r | P i) B i = all [pred i | P i ==> B i] r.\nProof. by rewrite big_mkcond unlock. Qed.\n\nEnd Seq.\n\nSection FinType.\n\nVariables (I : finType) (P B : pred I).\n\nLemma big_orE : \\big[orb/false]_(i | P i) B i = [exists (i | P i), B i].\nProof. by rewrite big_has_cond; apply/hasP/existsP=> [] [i]; exists i. Qed.\n\nLemma big_andE : \\big[andb/true]_(i | P i) B i = [forall (i | P i), B i].\nProof.\nrewrite big_all_cond; apply/allP/forallP=> /= allB i; rewrite allB //.\nexact: mem_index_enum.\nQed.\n\nEnd FinType.\n\nEnd BigBool.\n\nSection NatConst.\n\nVariables (I : finType) (A : pred I).\n\nLemma sum_nat_const n : \\sum_(i in A) n = #|A| * n.\nProof. by rewrite big_const iter_addn_0 mulnC. Qed.\n\nLemma sum1_card : \\sum_(i in A) 1 = #|A|.\nProof. by rewrite sum_nat_const muln1. Qed.\n\nLemma sum1_count J (r : seq J) (a : pred J) : \\sum_(j <- r | a j) 1 = count a r.\nProof. by rewrite big_const_seq iter_addn_0 mul1n. Qed.\n\nLemma sum1_size J (r : seq J) : \\sum_(j <- r) 1 = size r.\nProof. by rewrite sum1_count count_predT. Qed.\n\nLemma prod_nat_const n : \\prod_(i in A) n = n ^ #|A|.\nProof. by rewrite big_const -Monoid.iteropE. Qed.\n\nLemma sum_nat_const_nat n1 n2 n : \\sum_(n1 <= i < n2) n = (n2 - n1) * n.\nProof. by rewrite big_const_nat; elim: (_ - _) => //= ? ->. Qed.\n\nLemma prod_nat_const_nat n1 n2 n : \\prod_(n1 <= i < n2) n = n ^ (n2 - n1).\nProof. by rewrite big_const_nat -Monoid.iteropE. Qed.\n\nEnd NatConst.\n\nLemma leqif_sum (I : finType) (P C : pred I) (E1 E2 : I -> nat) :\n    (forall i, P i -> E1 i <= E2 i ?= iff C i) ->\n  \\sum_(i | P i) E1 i <= \\sum_(i | P i) E2 i ?= iff [forall (i | P i), C i].\nProof.\nmove=> leE12; rewrite -big_andE.\nby elim/big_rec3: _ => // i Ci m1 m2 /leE12; exact: leqif_add.\nQed.\n\nLemma leq_sum I r (P : pred I) (E1 E2 : I -> nat) :\n    (forall i, P i -> E1 i <= E2 i) ->\n  \\sum_(i <- r | P i) E1 i <= \\sum_(i <- r | P i) E2 i.\nProof. by move=> leE12; elim/big_ind2: _ => // m1 m2 n1 n2; exact: leq_add. Qed.\n\nLemma sum_nat_eq0 (I : finType) (P : pred I) (E : I -> nat) :\n  (\\sum_(i | P i) E i == 0)%N = [forall (i | P i), E i == 0%N].\nProof. by rewrite eq_sym -(@leqif_sum I P _ (fun _ => 0%N) E) ?big1_eq. Qed.\n\nLemma prodn_cond_gt0 I r (P : pred I) F :\n  (forall i, P i -> 0 < F i) -> 0 < \\prod_(i <- r | P i) F i.\nProof. by move=> Fpos; elim/big_ind: _ => // n1 n2; rewrite muln_gt0 => ->. Qed.\n\nLemma prodn_gt0 I r (P : pred I) F :\n  (forall i, 0 < F i) -> 0 < \\prod_(i <- r | P i) F i.\nProof. move=> Fpos; exact: prodn_cond_gt0. Qed.\n\nLemma leq_bigmax_cond (I : finType) (P : pred I) F i0 :\n  P i0 -> F i0 <= \\max_(i | P i) F i.\nProof. by move=> Pi0; rewrite (bigD1 i0) ?leq_maxl. Qed.\nImplicit Arguments leq_bigmax_cond [I P F].\n\nLemma leq_bigmax (I : finType) F (i0 : I) : F i0 <= \\max_i F i.\nProof. exact: leq_bigmax_cond. Qed.\nImplicit Arguments leq_bigmax [I F].\n\nLemma bigmax_leqP (I : finType) (P : pred I) m F :\n  reflect (forall i, P i -> F i <= m) (\\max_(i | P i) F i <= m).\nProof.\napply: (iffP idP) => leFm => [i Pi|].\n  by apply: leq_trans leFm; exact: leq_bigmax_cond.\nby elim/big_ind: _ => // m1 m2; rewrite geq_max => ->.\nQed.\n\nLemma bigmax_sup (I : finType) i0 (P : pred I) m F :\n  P i0 -> m <= F i0 -> m <= \\max_(i | P i) F i.\nProof. by move=> Pi0 le_m_Fi0; exact: leq_trans (leq_bigmax_cond i0 Pi0). Qed.\nImplicit Arguments bigmax_sup [I P m F].\n\nLemma bigmax_eq_arg (I : finType) i0 (P : pred I) F :\n  P i0 -> \\max_(i | P i) F i = F [arg max_(i > i0 | P i) F i].\nProof.\nmove=> Pi0; case: arg_maxP => //= i Pi maxFi.\nby apply/eqP; rewrite eqn_leq leq_bigmax_cond // andbT; exact/bigmax_leqP.\nQed.\nImplicit Arguments bigmax_eq_arg [I P F].\n\nLemma eq_bigmax_cond (I : finType) (A : pred I) F :\n  #|A| > 0 -> {i0 | i0 \\in A & \\max_(i in A) F i = F i0}.\nProof.\ncase: (pickP A) => [i0 Ai0 _ | ]; last by move/eq_card0->.\nby exists [arg max_(i > i0 in A) F i]; [case: arg_maxP | exact: bigmax_eq_arg].\nQed.\n\nLemma eq_bigmax (I : finType) F : #|I| > 0 -> {i0 : I | \\max_i F i = F i0}.\nProof. by case/(eq_bigmax_cond F) => x _ ->; exists x. Qed.\n\nLemma expn_sum m I r (P : pred I) F :\n  (m ^ (\\sum_(i <- r | P i) F i) = \\prod_(i <- r | P i) m ^ F i)%N.\nProof. exact: (big_morph _ (expnD m)). Qed.\n\nLemma dvdn_biglcmP (I : finType) (P : pred I) F m :\n  reflect (forall i, P i -> F i %| m) (\\big[lcmn/1%N]_(i | P i) F i %| m).\nProof.\napply: (iffP idP) => [dvFm i Pi | dvFm].\n  by rewrite (bigD1 i) // dvdn_lcm in dvFm; case/andP: dvFm.\nby elim/big_ind: _ => // p q p_m; rewrite dvdn_lcm p_m.\nQed. \n\nLemma biglcmn_sup (I : finType) i0 (P : pred I) F m :\n  P i0 -> m %| F i0 -> m %| \\big[lcmn/1%N]_(i | P i) F i.\nProof.\nby move=> Pi0 m_Fi0; rewrite (dvdn_trans m_Fi0) // (bigD1 i0) ?dvdn_lcml.\nQed.\nImplicit Arguments biglcmn_sup [I P F m].\n\nLemma dvdn_biggcdP (I : finType) (P : pred I) F m :\n  reflect (forall i, P i -> m %| F i) (m %| \\big[gcdn/0]_(i | P i) F i).\nProof.\napply: (iffP idP) => [dvmF i Pi | dvmF].\n  by rewrite (bigD1 i) // dvdn_gcd in dvmF; case/andP: dvmF.\nby elim/big_ind: _ => // p q m_p; rewrite dvdn_gcd m_p.\nQed. \n\nLemma biggcdn_inf (I : finType) i0 (P : pred I) F m :\n  P i0 -> F i0 %| m -> \\big[gcdn/0]_(i | P i) F i %| m.\nProof. by move=> Pi0; apply: dvdn_trans; rewrite (bigD1 i0) ?dvdn_gcdl. Qed.\nImplicit Arguments biggcdn_inf [I P F m].\n\nUnset Implicit Arguments.\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/bigop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6690458534240479}}
{"text": "Require Import Coq.Lists.List.\n\nSection REL.\nVariable A : Type.\nVariable IsA : A -> Prop.\nVariable LE : A -> A -> Prop.\nVariable LE_inv: forall t t', LE t t' -> IsA t /\\ IsA t'.\nVariable LE_dec: forall t t', {LE t t'} + {~ LE t t'}.\nVariable LE_refl: forall t, IsA t -> LE t t.\nVariable LE_trans:\n  forall t1 t2 t3,\n  LE t1 t2 ->\n  LE t2 t3 ->\n  LE t1 t3.\n\nDefinition Unrelated t t' := (~ LE t t' /\\ ~ LE t' t).\n\nLet le_inv_left: forall t t', LE t t' -> IsA t.\nProof.\n  intros.\n  apply LE_inv in H.\n  intuition.\nQed.\n\nLet le_inv_right: forall t t', LE t t' -> IsA t'.\nProof.\n  intros.\n  apply LE_inv in H.\n  intuition.\nQed.\n\nLemma unrelated_symm:\n  forall t t',\n  Unrelated t t' ->\n  Unrelated t' t.\nProof.\n  intros.\n  unfold Unrelated in *.\n  intuition.\nQed.\n\nDefinition Smallest (t:A) (ts:list A) :=\n  In t ts /\\ forall t', In t' ts -> Unrelated t t' \\/ LE t t'.\n\nLemma smallest_inv:\n  forall x l,\n  Smallest x l ->\n  In x l.\nProof.\n  intros.\n  unfold Smallest in *.\n  intuition.\nQed.\n\nLemma has_smallest_step_eq:\n  forall x y ts,\n  LE y x ->\n  In y ts ->\n  Smallest y ts ->\n  Smallest y (x :: ts).\nProof.\n  intros.\n  unfold Smallest in *.\n  destruct H1 as (_, H1).\n  intuition.\n  inversion H2.\n  - subst. intuition.\n  - apply H1. intuition.\nQed.\n\nLemma has_smallest_step_le:\n  forall t t' ts,\n  Smallest t' ts ->\n  LE t t' ->\n  Forall IsA ts ->\n  Smallest t (t::ts).\nProof.\n  intros.\n  unfold Smallest.\n  split.\n  { intuition. }\n  intros.\n  rename t'0 into x.\n  unfold Smallest in *.\n  destruct H as (_, H).\n  assert (Hx := H x).\n  inversion H2.\n  - subst.\n    right.\n    apply LE_refl.\n    apply le_inv_left with (t':=t').\n    assumption.\n  - apply Hx in H3. clear Hx H.\n    destruct (LE_dec t x).\n    { intuition. }\n    left.\n    destruct H3.\n    + unfold Unrelated in *.\n      split. { intuition. }\n      destruct H.\n      intuition.\n      assert (LE x t'). {\n        apply LE_trans with (t2:=t); repeat auto.\n      }\n      contradiction H5.\n    + assert (LE t x). {\n        apply LE_trans with (t2:=t'); repeat auto.\n      }\n      contradiction H3.\nQed.\n\nLemma has_smallest_step_unrelated:\n  forall x y ts,\n  In y ts ->\n  Smallest y ts ->\n  Unrelated x y ->\n  Smallest y (x :: ts).\nProof.\n  intros.\n  unfold Smallest.\n  intuition.\n  inversion H2.\n  - subst.\n    left.\n    apply unrelated_symm.\n    assumption.\n  - unfold Smallest in H0.\n    destruct H0 as (_, H0).\n    apply H0.\n    assumption.\nQed.\n\nLemma has_smallest_cons:\n  forall x y ts,\n  Forall IsA ts -> \n  Smallest y ts ->\n  exists z, Smallest z (x :: ts).\nProof.\n  intros x y ts Hisa Hsmall.\n  destruct (LE_dec y x).\n  - exists y.\n    apply has_smallest_step_eq; repeat auto.\n    apply smallest_inv in Hsmall; assumption.\n  - destruct (LE_dec x y).\n    + exists x.\n      split. { intuition. }\n      apply has_smallest_step_le with (t':=y); repeat auto.\n    + exists y.\n      assert (Unrelated x y). {\n        unfold Unrelated; intuition.\n      }\n      intuition.\n      apply has_smallest_step_unrelated; repeat auto.\n      apply smallest_inv in Hsmall; assumption.\nQed.\n\n\nLet in_inv_eq:\n  forall {A} (x y:A),\n  In x (y :: nil) ->\n  x = y.\nProof.\n  intros.\n  inversion H.\n  auto.\n  inversion H0.\nQed.\n\nTheorem has_smallest:\n  forall ts,\n  ts <> nil ->\n  Forall IsA ts ->\n  exists t, Smallest t ts.\nProof.\n  intros ts Hnil Hfor.\n  induction ts.\n  (* absurd *) {\n    contradiction Hnil.\n    auto.\n  }\n  destruct ts.\n  - exists a.\n    unfold Smallest.\n    split. { intuition. }\n    intros t' Hin.\n    apply in_inv_eq in Hin.\n    subst.\n    right; apply LE_refl.\n    apply Forall_inv with (l:=nil); assumption.\n  - assert (IHnil : a0 :: ts <> nil). {\n      intuition. inversion H.\n    }\n    assert (IHfor : Forall IsA (a0 :: ts)). {\n      inversion Hfor.\n      auto.\n    }\n    assert (Hoo := IHts IHnil IHfor).\n    destruct Hoo as (t, H).\n    apply has_smallest_cons with (y:=t); repeat auto.\nQed.\nEnd REL.\n", "meta": {"author": "cogumbreiro", "repo": "habanero-coq", "sha": "2e7b1be0e25e53b4c6aba20a45700d6c743d7ce2", "save_path": "github-repos/coq/cogumbreiro-habanero-coq", "path": "github-repos/coq/cogumbreiro-habanero-coq/habanero-coq-2e7b1be0e25e53b4c6aba20a45700d6c743d7ce2/src/Phasers/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.6690458518009447}}
{"text": "Module functionplayground.\n\nFixpoint factorial (n:nat) : nat :=\n  match n with\n  | O => 1\n  | S O => 1\n  | S n' => (S n') * (factorial n')\n  end.\n\nExample test_factorial1 : factorial 3 = 6.\nProof. simpl. exact eq_refl. Qed.\n\nExample test_factorial2 : factorial 5 = 10 * 12.\nProof. simpl. exact eq_refl. Qed.\n\nNotation \"x !\" := (factorial x) (at level 50) : nat_scope.\n\nTheorem andb_true_elim2 : forall b c : bool, andb b c = true -> c = true.\nProof.\n  intros b c.\n  destruct b, c.\n    simpl. reflexivity.\n    simpl. discriminate.\n    simpl. discriminate.\n    simpl. discriminate.\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/functiontypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.6690458340893594}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\n\n(** For backwards compatibility with hint locality attributes. *)\nSet Warnings \"-unsupported-attributes\".\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; lia.\n  f_equal. eapply IHn; eauto. lia.\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; lia.\n  f_equal. eapply IHn; eauto. lia.\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; lia.\n  simpl. f_equal. eapply IHn; lia.\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  lia.\n  simpl. replace (n - 0) with n; [ | lia ]. reflexivity.\nQed.\n\n#[global]\nHint Rewrite firstn_app_L firstn_app_R firstn_all firstn_0 firstn_cons using lia : 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; lia.\n  eapply IHn. lia.\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; lia.\n  eapply IHn. lia.\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; lia.\n  apply IHn; lia.\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  lia.\n  simpl. replace (n - 0) with n; [ | lia ]. reflexivity.\nQed.\n\n#[global]\nHint Rewrite skipn_app_L skipn_app_R skipn_0 skipn_all skipn_cons using lia : list_rw.\n", "meta": {"author": "coq-community", "repo": "coq-ext-lib", "sha": "4811a83db9ccd81f4dcbf77eeff0484dfb21a48b", "save_path": "github-repos/coq/coq-community-coq-ext-lib", "path": "github-repos/coq/coq-community-coq-ext-lib/coq-ext-lib-4811a83db9ccd81f4dcbf77eeff0484dfb21a48b/theories/Data/ListFirstnSkipn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.6689649956286103}}
{"text": "From Complexity.NP.SAT Require Export SharedSAT.\nRequire Import Lia. \n\nFrom Undecidability.L.Tactics Require Import LTactics GenEncode.\nFrom Undecidability.L.Datatypes Require Import  LProd LOptions LBool LNat Lists LUnit.\nFrom Undecidability.L.Functions Require Import EqBool. \nFrom Complexity.Complexity Require Import UpToCPoly.\nFrom Complexity.Libs.CookPrelim Require Import MorePrelim.\n\n(** * SAT: Satisfiability of CNFs *)\n\n(** ** Definition of SAT *)\n(** Conjunctive normal forms (need not be canonical)*)\n(* We use notations instead of definitions because the extraction mechanism does not cope well with aliases *)\nNotation var := (nat) (only parsing). \nNotation literal := ((bool * var)%type) (only parsing).\nNotation clause := (list literal) (only parsing). \nNotation cnf := (list clause) (only parsing).\n\n(** Assignments as lists of natural numbers: contain the indices of variables that are mapped to true *)\nImplicit Types (a : assgn) (N : cnf) (C : clause) (l :literal).\n\n(** just a notation here; the definition is shared with FSAT *)\nNotation evalVar := evalVar. \n\nDefinition evalLiteral a l : bool := match l with\n  | (s, v) => Bool.eqb (evalVar a v) s \nend. \n\n(**Empty disjunction evaluates to false*)\nDefinition evalClause a C := existsb (evalLiteral a) C. \n\n(**Empty conjunction evaluates to true *)\nDefinition evalCnf a N := forallb (evalClause a) N. \n\n(** Some helpful properties *)\n(** A characterisation of one processing step of evaluation *)\nLemma evalClause_step_inv a C l b : \n  evalClause a (l::C) = b <-> exists b1 b2, evalClause a C = b2 /\\ evalLiteral a l = b1 /\\ b = b1 || b2.\nProof.\n  cbn. split; intros. \n  - rewrite <- H. eauto.\n  - destruct H as (b1 & b2 & <- & <- & ->). eauto.\nQed. \n\nLemma evalCnf_step_inv a N C b : \n  evalCnf a (C :: N) = b <-> exists b1 b2, evalCnf a N = b2 /\\ evalClause a C = b1 /\\ b = b1 && b2. \nProof. \n  cbn. split; intros. \n  - rewrite <- H. eauto. \n  - destruct H as (b1 & b2 & <- & <- & ->). eauto.\nQed. \n\nLemma evalLiteral_var_iff a b v : \n  evalLiteral a (b, v) = true <-> evalVar a v = b. \nProof. \n  unfold evalLiteral. destruct b, evalVar; cbn; firstorder.\nQed. \n\nLemma evalClause_literal_iff a C : \n  evalClause a C = true <-> (exists l, l el C /\\ evalLiteral a l = true). \nProof. apply existsb_exists. Qed.\n\nCorollary evalClause_app a C1 C2 : \n  evalClause a (C1 ++ C2) = true <-> (evalClause a C1 = true \\/ evalClause a C2 = true). \nProof. \n  rewrite !evalClause_literal_iff. setoid_rewrite in_app_iff. firstorder.\nQed.\n\nLemma evalCnf_clause_iff a N : \n  evalCnf a N = true <-> (forall C, C el N -> evalClause a C = true). \nProof. apply forallb_forall. Qed.\n\nCorollary evalCnf_app_iff a N1 N2 : \n  evalCnf a (N1 ++ N2) = true <-> (evalCnf a N1 = true /\\ evalCnf a N2 = true). \nProof. \n  rewrite !evalCnf_clause_iff. setoid_rewrite in_app_iff. firstorder.\nQed.\n\nDefinition satisfies a N := evalCnf a N = true.\nDefinition SAT N : Prop := exists (a : assgn), satisfies a N. \n\nLemma evalLiteral_assgn_equiv a1 a2 l : a1 === a2 -> evalLiteral a1 l = evalLiteral a2 l. \nProof. \n  intros [H1 H2]. destruct l as (b & v). unfold evalLiteral. destruct (evalVar a1 v) eqn:Hev1. \n  - apply (evalVar_monotonic H1) in Hev1. easy.\n  - destruct (evalVar a2 v) eqn:Hev2; [ | easy]. \n    apply (evalVar_monotonic H2) in Hev2. congruence. \nQed.\n\nLemma evalClause_assgn_equiv a1 a2 C : a1 === a2 -> evalClause a1 C = evalClause a2 C. \nProof. \n  intros H. enough (evalClause a1 C = true <-> evalClause a2 C = true).\n  - destruct evalClause; destruct evalClause; firstorder; easy. \n  - rewrite !evalClause_literal_iff. now setoid_rewrite (evalLiteral_assgn_equiv _ H). \nQed.\n\nLemma evalCnf_assgn_equiv a1 a2 N : a1 === a2 -> evalCnf a1 N = evalCnf a2 N. \nProof. \n  intros H. enough (evalCnf a1 N = true <-> evalCnf a2 N = true). \n  - destruct evalCnf; destruct evalCnf; firstorder; easy.\n  - rewrite !evalCnf_clause_iff. now setoid_rewrite (evalClause_assgn_equiv _ H).\nQed. \n\n(** Bounds on the number of used variables*)\nDefinition varInLiteral v (l : literal) := exists b, l = (b, v).\nDefinition varInClause v c := exists l, l el c /\\ varInLiteral v l. \nDefinition varInCnf v cn := exists cl, cl el cn /\\ varInClause v cl. \n\nDefinition clause_varsIn (p : nat -> Prop) c := forall v, varInClause v c -> p v. \nDefinition cnf_varsIn (p : nat -> Prop) c := forall v, varInCnf v c -> p v. \n\nLemma cnf_varsIn_app c1 c2 p : cnf_varsIn p (c1 ++ c2) <-> cnf_varsIn p c1 /\\ cnf_varsIn p c2. \nProof. \n  unfold cnf_varsIn. unfold varInCnf. setoid_rewrite in_app_iff. split; [intros H  |intros [H1 H2]].\n  - split; intros v [cl [H3 H4]]; apply H; eauto.\n  - intros v [cl [[H3 | H3] H4]]; [apply H1 | apply H2]; eauto.\nQed.\n\nLemma cnf_varsIn_monotonic (p1 p2 : nat -> Prop) c : (forall n, p1 n -> p2 n) -> cnf_varsIn p1 c -> cnf_varsIn p2 c. \nProof. \n  intros H H1 v H2. apply H, H1, H2. \nQed. \n\n(** size of CNF in terms of number of operators *)\nDefinition size_clause C := length C. (*we should subtract 1 here, but this would only complicate things *)\nDefinition size_cnf N := sumn (map size_clause N) + length N. \n\nLemma size_clause_app C1 C2 : size_clause (C1 ++ C2) = size_clause C1 + size_clause C2. \nProof. \n  unfold size_clause. now rewrite app_length. \nQed.\n\nLemma size_cnf_app N1 N2 : size_cnf (N1 ++ N2) = size_cnf N1 + size_cnf N2. \nProof. \n  unfold size_cnf. rewrite map_app, sumn_app, app_length. lia.\nQed. \n", "meta": {"author": "uds-psl", "repo": "coq-library-complexity", "sha": "5a996877f16fd6fe16dc5f0c3b933486957869df", "save_path": "github-repos/coq/uds-psl-coq-library-complexity", "path": "github-repos/coq/uds-psl-coq-library-complexity/coq-library-complexity-5a996877f16fd6fe16dc5f0c3b933486957869df/theories/NP/SAT/SAT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924954, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.6689649919077654}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule Lect3.\n  (*** Universal quantifier *)\n\n  Section Motivation.\n    Variables A B : Type.\n\n    (** Suppose we wrote two functions:\n        a simple (a.k.a. gold) implementation and\n        its optimized version.\n        How do we go about specifying their equivalence? *)\n    Variables fgold fopt : A -> B.\n\n    Lemma fopt_equiv_fgold :\n      forall x : A, fgold x = fopt x.\n    Abort.\n\n    (* Dependently typed functions *)\n\n    (* Рекомендую предварительно получить какое-то представление или освежить знания о зависимых типах.\n       Достаточно потратить 5 минут на чтение русской вики:\n       https://ru.wikipedia.org/wiki/%D0%97%D0%B0%D0%B2%D0%B8%D1%81%D0%B8%D0%BC%D1%8B%D0%B9_%D1%82%D0%B8%D0%BF  *)\n\n    (** ** Dependently typed predecessor function *)\n\n    Definition Pred n :=\n      if n is S n' then nat else unit.\n\n    (** the value of [unit] type plays the role of a placeholder *)\n    Print unit.\n\n    Definition predn_dep : forall n, Pred n :=\n      fun n => if n is S n' then n' else tt.\n\n    Print erefl.\n    Print Logic.eq_refl.\n\n    Check erefl : predn_dep 7 = 6.\n    Compute predn_dep 7.\n    Fail Check erefl : predn_dep 0 = 0.\n    Check predn_dep 0 : unit.\n    Check predn_dep 0 : Pred 0.\n    Check predn_dep 7 : nat.\n\n    Check erefl : predn_dep 0 = tt.\n    Check erefl : Pred 0 = unit.\n\n    (** ** Annotations for dependent pattern matching *)\n\n    (** Type inference is undecidable *)\n\n    (* Тут мы просим вывести ф-цию над типами.\n       Другими словами мы \"просим\" провести унификацию\n       высшего порядка, т.е. вывести \"теорему\",\n       которую мы \"доказали\", построив данный proof-term,\n       а это алгоритмически не разрешимая задача. *)\n    Fail Check (fun n => if n is S n' then n' else tt).\n\n    Check (\n        fun n =>\n          if n is S n' as n0 return Pred n0\n          then n'\n          else tt).\n\n    (**\n    General form of pattern matching construction:\n    [match expr as T in (deptype A B) return exprR].\n\n    - [return exprR] denotes the dependent type of the expression\n    - [as T] is needed when we are matching on complex expressions,\n    not just variables\n    *)\n\n    (* Functional type is just a notation *)\n    (* for a special case of [forall] *)\n\n    (*\n       \"A -> B\" := forall _ : A, B\n       Это зависимая ф-ция, в том случае, когда возвращаемый тип\n       никак не зависит от входного значения.\n\n       Это нотация из стандартной библиотеки, которая означает:\n       для неважно какого значения из типа [A] мы всегда возвращаем один и тот же тип [B]\n\n       Вообще говоря, обычное функциональное пространство является\n       тем частным случаем, когда область значений не зависит от входного параметра\n    *)\n    Locate \"->\".\n\n    (* Следующие записи эквивалентны *)\n    Check predn : nat -> nat.\n    (* Мы можем назвать как-то входное значение в типе ф-ции, но\n       [Check] распечатает без него, тк в выходном типе оно никак не используется *)\n    Check predn : forall _ : nat, nat.\n    (* Аналогично *)\n    Check predn : forall x : nat, (fun _ => nat) x.\n\n  End Motivation.\n\n  (** * Usage of [forall] in standalone expressions *)\n\n  Section StandardPredicates.\n    Variable T : Type.\n    Implicit Types (op add : T -> T -> T).\n\n    Definition associative op :=\n      forall x y z, op x (op y z) = op (op x y) z.\n\n    Definition left_distributive op add :=\n      forall x y z, op (add x y) z = add (op x z) (op y z).\n\n    Definition left_id e op :=\n      forall x, op e x = x.\n  End StandardPredicates.\n\n  (* Закон исключённого третьего влечёт\n     за собой дуальноe правило Фробениуса *)\n\n  Definition LEM :=\n    forall P : Prop, P \\/ ~ P.\n\n  Definition Frobenius2 :=\n    forall (A : Type) (P : A -> Prop) (Q : Prop),\n      (forall x, Q \\/ P x) <-> (Q \\/ forall x, P x).\n\n  Lemma lem_implies_Frobenius2 :\n    LEM -> Frobenius2.\n  Proof.\n    rewrite /LEM /Frobenius2.\n    move=> lem.\n    move=> A P Q.\n    split.\n    - move=> all_qpx.\n      move: (lem Q).\n      case.\n      + move=> q.\n        left.\n        exact q.\n      + move=> nq.\n        right.\n        move=> x.\n        Check all_qpx x.\n        case: (all_qpx x).\n        Undo.\n        move: (all_qpx x).\n        case.\n        (* Check nq : Q -> False. *)\n        (* Конструкция \"вид\" [move/H] это приблизительный аналог\n           [move=> top. move: (H top)]\n\n           Соотвественно это работает и с [case/H],\n           что будет эквивалентно [move=> top. case: (H top)] *)\n        * move/nq.\n          Undo.\n          move=> q. move: (nq q).\n          done.\n        * by [].\n    case.\n    - move => q x.\n      left.\n      exact: q.\n    - move => all_px x.\n      right.\n      exact: all_px x.\n    Undo 9.\n\n    case; first by move=> q x; left.\n    move=> all_px x.\n    right. exact: all_px.\n    Undo 2.\n    by right.\n  Qed.\n\n  (* Давайте докажем, что это работает и в обратную сторону *)\n\n  Lemma Frobenius2_lem : Frobenius2 -> LEM.\n  Proof.\n    rewrite /Frobenius2=> frob.\n    rewrite /LEM. Undo.\n    (* Поскольку мы знаем определение [LEM], то\n       мы можем сразу ввести [P] в контекст и\n       Coq развернёт определение автоматически *)\n    move=> P.\n    (* rewrite /not. *)\n    Check (frob P (fun _ => False) P).\n    (* frob : forall (A : Type) (P : A -> Prop) (Q : Prop), *)\n    (*        (forall x : A, Q \\/ P x) <-> Q \\/ (forall x : A, P x) *)\n    (* frob P (fun _ : P => False) P *)\n    (*      : (P -> P \\/ False) <-> P \\/ (P -> False) *)\n    case: (frob P (fun _ => False) P).\n    (* Переносим в контекст первые два, но\n       второе пропускаем и сразу возвращаем первое в цель *)\n    move=> H _; move: H.\n    (* [apply.] это \"дефективная форма\" тактики [apply],\n       что значит по сути \"использование тактики без модификаторов\" *)\n    apply. move=> x. left. exact: x.\n    Undo 4.\n    (* Т.е. получается, что [left]/[right] переносит\n       всё до первой дизъюнкии в контекст? Да.\n       Это плохо. Способ выше -- правильный *)\n    apply. left. exact: x.\n    Undo 3.\n    by apply; left.\n  Qed.\n\n  Module MyExistential.\n\nInductive ex_my (A : Type) (P : A -> Prop) : Prop :=\n| ex_intro (x : A) (proof : P x).\n\n    (* ex_intro [предикат] [значение] [доказательство, что предикат выполняется на этом значении] *)\n\n    (* Если у нас написано, что существует [x] для\n       которого выполняется [P x], то мы имеем дело с некой парой.\n       Для того, чтобы воспользоваться этой парой мы должны сделать\n       по ней pattern-matching типа [case x px] и получим в контексте 2 значения.\n       Зависимая типизация тут это ключевая особенность. *)\n\n    (* В Coq уже есть [ex], определение выше нужно было просто,\n       чтобы посмотреть как оно устроено под капотом. *)\n\n    (** Simplified notation *)\n    Notation \"’exists’ x : A , p\" :=\n      (ex_my (fun x : A => p))\n        (at level 200, right associativity).\n\n    (** Full-blown notation: multiple binders *)\n    Notation \"'exists' x .. y , p\" :=\n      (ex_my (fun x => .. (ex_my (fun y => p)) ..))\n        (at level 200, x binder, right associativity,\n         format \"'[' 'exists'  '/  ' x  ..  y ,  '/  ' p ']'\")\n      : type_scope.\n\n    Print ex_my.\n    Print ex.\n\n  End MyExistential.\n\n  (* Т.е. если существует [x] для которого утверждение истинно,\n     то не для всех [x] оно не истинно. *)\n  Lemma exists_not_forall A (P : A -> Prop) :\n    (exists x, P x) -> ~ (forall x, ~ P x).\n  Proof.\n    case=> x px.\n    move=> all.\n    Check (all x).\n    exact: (all x px).\n  Qed.\n\n  (* Можно имитировать обычную пару при помощи exists:\n     A /\\ B\n     exists _ : A, B\n\n     Т.е. существует некоторое\n     утверждение _ (которое мы никак не именуем) типа [A]\n     и утверждение типа [B].\n\n     Можно посмотреть на подстановку:\n\n     Notation \"’exists’ _ : A, B\" :=\n      (ex (fun x : A => B))\n        (at level 200, right associativity).\n  *)\n\n  (* Definition curry' {A B C} : *)\n  (*   (A * B -> C) -> (A -> B -> C) := *)\n  (*   fun f => (fun a b => f (a; b)). *)\n\n  Definition curry {A B C} :\n    (A * B -> C) -> (A -> B -> C).\n  (* Не будем тут писать слово [Proof], тк тут мы\n     имеем ввиду некую вычислительную сущность, а не док-во *)\n  move=> f a b.\n  (* exact: (f (pair a b)). *)\n  exact: (f (a, b)).\n  (* Используем Defined, тк мы хотим уметь считать при помощи этой ф-ции. *)\n Defined.\n\n  Lemma curry_dep A (P : A -> Prop) Q :\n    ((exists x, P x) -> Q) -> (forall x, P x -> Q).\n  Proof.\n    move=> f x px.\n    (* Print ex_intro. *)\n    (* ex_intro : forall x : A, P x -> exists y, P y *)\n    exact: (f (ex_intro P x px)).\n  Qed.\n\n  Section Symmetric_Transitive_Relation.\n    (* У нас есть некоторое отношение [R] над типом [D] *)\n    Variables (D : Type) (R : D -> D -> Prop).\n\n    (* [Hypothesis] is a different syntax for [Variable] *)\n\n    (* Отношение симметрично *)\n    Hypothesis Rsym :\n      forall x y, R x y -> R y x.\n\n    (* Отношение транзитивно *)\n    Hypothesis Rtrans :\n      forall x y z, R x y -> R y z -> R x z.\n\n    (* Если нам известно про некое соотношение,\n       в котором есть хотя бы одна пара (оно не пустое),\n       то такое отношение ещё и рефлексивно, т.е. любой [x]\n       находится в отношении [R] с самим собой. *)\n    Lemma relf_if :\n      forall x : D, (exists y, R x y) -> R x x.\n    Proof.\n      move=> x.\n      case=> y rxy.\n      move: (Rsym rxy).\n      move: rxy.\n      apply: Rtrans.\n    Qed.\n\n  End Symmetric_Transitive_Relation.\n\n  Lemma exfalso_quodlibet :\n    False -> forall P : Prop, P.\n  Proof. by []. Qed.\n\n  (* Импликация это ф-ция, которая принимает [f : False] и\n     производит некоторую ф-цию, которая принимает\n     произвольное утверждение [P] и производит его доказательство. *)\n  Definition exfalso_quodlibet_term :\n    False -> forall P : Prop, P :=\n    fun f =>\n      (* Поскольку [False] это индуктивный тип, то\n         по его значениям можно паттерн-матчить.\n         А конструкторов у нас 0, столько и запишем :) *)\n      match f with end.\n\n  (* Частный случай *)\n  Lemma False_implies_false :\n    False -> false.\n  Check false : Type.\n  Print false.\n  Set Printing Coercions.\n  (* Set Printing All. *)\n  rewrite /is_true.\n  (* Теперь мы видим, что на самом деле от нас требуется доказать, что:\n     False -> false = true\n\n     Мы тут видим [false = true], потому что\n     is_true = fun b : bool => eq b true : forall _ : bool, Prop\n\n     Вообще говоря, у нас это не тайпчекается,\n     потому что здесь должен быть тип.\n\n     Коэрции это такой способ реализовать в Coq подтипирование.\n     Поскольку в теории типов, на которой основан Coq подтипирования нет,\n     то это реализовано при помощи такого мета-механизма.\n     Как только Coq видит, что есть некий терм, который\n     не проходит проверку типов (у нас это [false = true]),\n     то он ищет в своей базе коэрций способ преобразовать его так,\n     чтобы он тайпчекался. В нашем случае наиболее простой выход,\n     который он находит это использовать [is_true].\n\n     False -> is_true false\n\n     forall _ : False, @eq bool false true\n  *)\n  Proof. case. Qed.\n\n  (* Вот так, например, определена коэрция [is_true]: *)\n  Unset Printing Notations.\n  Print is_true.\n  Set Printing Notations.\n\n  (* Coercion is_true : bool >-> Sortclass. *)\n  (* Print Coercions. *)\n\n  (* Going in the other direction *)\n  Lemma false_implies_False :\n    false -> False.\n  Proof. by []. Qed.\n\n  Check I : True.\n\n  (* Чтобы разобраться что происходит под капотом,\n     можно построить следующий пруф-терм: *)\n  Definition false_implies_False_term :\n    false -> False :=\n (* Раскроем коэрцию: *)\n (* fun eq : false         => *)\n (* fun eq : is_true false => *)\n    fun eq : false = true  =>\n      (* тут false не меняется, а true меняется (тк это индекс) *)\n      (* [in] это по сути [:],\n         т.е. это нужно читать как [eq : eq _ b] *)\n      match eq in (_ = b)\n            return (if b then False else True)\n\n      (* до паттерн-матчинга мы знаем,\n         что [true] унифицируется с [b] /\n         что [b] и [true] это одно и то же:\n\n         return (if true False else True)\n         return False *)\n\n      (* внутри паттерн-матчинга [b]\n         \"унифицируется c\" / \"заменяется на\" [false]):\n\n         return (if false False else True)\n         return True *)\n\n      with\n      | erefl => I : True\n      end.\n\n  (* See:\n     https://coq.inria.fr/refman/addendum/extended-pattern-matching.html#dependent-pattern-matching\n     https://github.com/coq/coq/wiki/MatchAsInReturn.\n\n     [match] allows the result type to depend on both\n     the input value, and the parameters of the input type. *)\n\n  (* Все параметры индуктивного типа заменяются на _,\n     а всем индексам можно дать имена *)\n\n  (* fun     eq : false = true => *)\n  (*   match eq : (_    = b) *)\n\n  (* Ещё один хороший\\понятный пример из документации.\n     Здесь тип возвращаемого списка зависит от типов переданных списков.\n\n     Fixpoint concat (n:nat) (l:listn n) (m:nat) (l':listn m) {struct l} : listn (n + m) :=\n     match l in listn n return listn (n + m) with\n     | niln => l'\n     | consn n' a y => consn (n' + m) a (concat n' y m l')\n     end.\n\n     И ещё один:\n\n     Definition tail n (v: listn (S n)) :=\n     match v in listn (S m) return listn m with\n     | niln => False_rect unit\n     | consn n' a y => y\n     end.\n  *)\n\n\n  (* Injectivity of constructors *)\n\nLemma succ_inj n m :\n  S n = S m -> n = m.\nProof.\n  case. (* special case for [case] *)\n    (* Тактика [case] работает особым образом в таком случае.\n       Если мы на таком равенстве с конструкторами используем её, то\n       она нам преобразует в соотв. форму -- \"распаковывает\" конструкторы.\n     *)\n    Show Proof.\n    (* f_equal : forall (A B : Type) (f : A -> B) (x y : A), x = y -> f x = f y *)\n    done.\n  Qed.\n\n  Lemma pair_inj A B (a1 a2 : A) (b1 b2 : B) :\n    (a1, b1) = (a2, b2) -> (a1 = a2) /\\ (b1 = b2).\n  Proof.\n    case.\n    move=> H1 H2.\n    rewrite H1.\n    rewrite H2.\n    by [].\n\n    Restart.\n\n    case.\n    move=> ->->.\n    by [].\n\n    Restart.\n\n    by case=> ->->.\n  Qed.\n\n  (*** Induction *)\n\n    Lemma addnA :\n      associative addn.\n    Proof.\n      (* Мы знаем определение ассоциативности,\n         поэтому можем сразу переместить x, y и z в контекст и\n         Coq поймёт, что нужно развенуть определение *)\n\n      (* Либо можно вот так развернуть его в цели: *)\n      Eval hnf in associative addn.\n\n      move=> x y z.\n      (* Есть такая эвристика, что если ф-ция определена рекурсивно по\n         1-му аргументу, то индукцию следует тоже делать по 1-му аргументу.\n\n         Индукция есть в некотором смысле символическое вычисление. *)\n\n      elim: x.\n      - by [].\n\n      (* Мы хотим избавляться от таких тривиальных целей,\n         как в первом случае. Это можно сделать при помощи\n         флага [//], который делает тоже самое, что и [by []]. *)\n      Undo 3.\n\n      elim: x=> //.\n      Undo 1.\n\n      elim: x.\n      have : 0 + 1 = 1.\n\n      Print addn.\n      (* Модификатор [/=] запускает классическую тактику [simpl],\n         которая двойные определения не разворачивает:\n         [addn = nosimpl addn_rec] *)\n\n      (* Set Printing All. *)\n      (* rewrite /addn. *)\n      (* Print addn. *)\n      (* [/=] запускает классическую тактику [simpl] *)\n      (* addn тут не развернётся, тк внутри него [addn_rec] помечена как [nosimpl]:\n         addn = nosimpl addn_rec : nat -> nat -> nat\n         см. https://coq.inria.fr/refman/proof-engine/ssreflect-proof-language.html?highlight=nosimpl *)\n      move=> /=.\n\n      (* Unset Printing All. *)\n      done.\n\n      Restart.\n\n      move=> x y z.\n      elim: x=> // x IH.\n      Search _ (_.+1 + _).\n      rewrite addSn.\n      rewrite IH.\n      done.\n\n      Restart.\n\n      by move=> x y z; elim: x=> // x IH; rewrite addSn IH.\n    Qed.\n\n    Lemma add0n :\n      left_id 0 addn.\n    Proof.\n      (* Это просто вычисляется (по определению суммы [add_n]) *)\n      rewrite /left_id.\n      by [].\n    Qed.\n\n    Lemma addn0 :\n      right_id 0 addn.\n    Proof.\n      rewrite /right_id.\n      (* А вот тут уже только по индукции *)\n\n      elim.\n      - by [].\n      - move=> n IHn.\n        About addSn.\n        rewrite addSn.\n        rewrite IHn.\n        done.\n\n      Restart.\n\n      move=> x.\n      elim: x=> // x IHn.\n\n      Restart.\n\n      by elim=> // x IH; rewrite addSn IH.\n    Qed.\n\n    Lemma addSnnS m n :\n      m.+1 + n = m + n.+1.\n    Proof.\n      elim: m=> //.\n      move=> m IH.\n      rewrite addSn IH.\n      done.\n\n      Restart.\n\n      by elim: m=> // m IH; rewrite addSn IH.\n    Qed.\n\n    Lemma addnC :\n      commutative addn.\n    Proof.\n      move=> x y.\n      elim: x.\n      - rewrite addn0. done.\n      - move=> n IHn.\n        rewrite addSn.\n        rewrite -addSnnS.\n        rewrite IHn.\n        rewrite addSn.\n        done.\n\n      Restart.\n\n      move=> x y.\n      elim: x; first by rewrite addn0.\n      by move=> x IHn; rewrite addSn IHn -addSnnS.\n    Qed.\n\n    Check nat_ind.\n\n    (* Определим элиминатор индукции.\n       В теории типов индукция кодируется через рекурсию,\n       т.е. у нас нет отдельно рекурсии и отдельно индукции. *)\n\n    Definition nat_ind_my :\n      forall P : nat -> Prop,\n        P 0 -> (forall n : nat, P n -> P n.+1) ->\n        forall n : nat, P n :=\n      fun P p0 step =>\n        fix rec n :=\n          if n is n'.+1\n            then step n' (rec n')\n            else p0.\nEnd Lect3.\n", "meta": {"author": "vyorkin", "repo": "coq-fv", "sha": "d65348888fc51722585d81f189fd1b71da7b8c3b", "save_path": "github-repos/coq/vyorkin-coq-fv", "path": "github-repos/coq/vyorkin-coq-fv/coq-fv-d65348888fc51722585d81f189fd1b71da7b8c3b/lectures/lecture03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6689649860415604}}
{"text": "From mathcomp Require Import all_ssreflect.\nRequire Import ssromega.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* ゴールと前提にある if式の条件で場合分けする。 *)\nLtac if_condition' :=\n  intros;\n  repeat match goal with\n         | [ |- context[if ?b then _ else _] ] =>\n           let H' := fresh in destruct b eqn: H'\n         | [ H : context[if ?b then _ else _] |- _ ] =>\n           let H' := fresh in destruct b eqn: H'\n         | _ => idtac\n         end.\n\nLtac if_condition :=\n  if_condition'; try done; ssromega.\n\n(* Sample *)\nGoal forall m n, (if m < n then m else n) = (if n <= m then n else m).\nProof.\n  if_condition.\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/common/ssrifcond.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.6689649854420446}}
{"text": "(* infotheo (c) AIST. R. Affeldt, M. Hagiwara, J. Senizergues. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq div choice fintype.\nFrom mathcomp Require Import finfun bigop prime binomial ssralg finset fingroup finalg matrix.\nRequire Import Reals Fourier.\nRequire Import Reals_ext ssr_ext ssralg_ext log2 Rssr tuple_prod Rbigop proba entropy.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(** * Definition of channels and of the capacity *)\n\n(*Local Open Scope tuple_ext_scope.*)\n\nModule Channel1.\n\nSection Channel1_sect.\n\nVariables A B : finType.\n\n(** Probability transition matrix: *)\n\n(** Definition of a discrete channel of input alphabet A and output alphabet B.\n    It is a collection of probability mass functions, one for each a in A: *)\n\nLocal Notation \"'`Ch_1'\" := (A -> dist B).\n\n(** Channels with non-empty alphabet: *)\n\nRecord chan_star := mkChan {\n  c :> `Ch_1 ;\n  input_not_0 : (0 < #|A|)%nat }.\n\nLocal Notation \"'`Ch_1*'\" := (chan_star).\n\nLemma chan_star_eq (c1 c2 : `Ch_1*) : c c1 = c c2 -> c1 = c2.\nProof.\ndestruct c1 as [c1 Hc1].\ndestruct c2 as [c2 Hc2].\nmove=> /= ?; subst c2.\nf_equal.\napply eq_irrelevance.\nQed.\n\nEnd Channel1_sect.\n\nEnd Channel1.\n\nDefinition chan_star_coercion := Channel1.c.\nCoercion chan_star_coercion : Channel1.chan_star >-> Funclass.\n\nNotation \"'`Ch_1(' A ',' B ')'\" := (A -> dist B) (at level 10, A, B at next level) : channel_scope.\n\nNotation \"'`Ch_1*(' A ',' B ')'\" := (@Channel1.chan_star A B) (at level 10, A, B at next level) : channel_scope.\n\nLocal Open Scope channel_scope.\n\nModule DMC.\n\nSection DMC_sect.\n\nVariables A B : finType.\nVariable W : `Ch_1(A, B).\nVariable n : nat.\n\n(** nth extension of the discrete memoryless channel (DMC): *)\n\nLocal Open Scope proba_scope.\nLocal Open Scope ring_scope.\n\nDefinition channel_ext n := 'rV[A]_n -> {dist 'rV[B]_n}.\n\nLocal Notation \"'`Ch_' n\" := (channel_ext n) (at level 9, n at next level, format \"'`Ch_'  n\").\n\n(** Definition of a discrete memoryless channel (DMC).\n    W(y|x) = \\Pi_i W_0(y_i|x_i) where W_0 is a probability\n    transition matrix. *)\n\nLocal Open Scope vec_ext_scope.\n\nDefinition f (va vb : 'rV_n) := \\rmul_(i < n) W (va ``_ i) (vb ``_ i).\n\nLemma f0 va vb : 0 <= f va vb.\nProof. apply Rle_0_big_mult => /= i; by apply Rle0f. Qed.\n\nLemma f1 va : \\rsum_(vb in 'rV_n) f va vb = 1%R.\nProof.\nset f' := fun i b => W va ``_ i b.\nsuff H : \\rsum_(g : {ffun 'I_n -> B}) \\rmul_(i < n) f' i (g i) = 1%R.\n  rewrite -{}[RHS]H /f'.\n  rewrite (reindex_onto (fun vb : 'rV_n => [ffun x => vb ``_ x])\n    (fun g  => \\row_(k < n) g k)) /=; last first.\n    move=> g _; apply/ffunP => /= i; by rewrite ffunE mxE.\n  apply eq_big => vb.\n  - rewrite inE.\n    apply/esym/eqP/matrixP => a b; by rewrite {a}(ord1 a) mxE ffunE.\n  - move=> _; apply eq_bigr => i _; by rewrite ffunE.\nrewrite -bigA_distr_bigA /= /f'.\ntransitivity (\\rmul_(i < n) 1%R); first by apply eq_bigr => i _; rewrite pmf1.\nby rewrite big_const_ord iter_Rmult pow1.\nQed.\n\nDefinition c : `Ch_n := locked (fun ta => makeDist (f0 ta) (f1 ta)).\n\nEnd DMC_sect.\n\nEnd DMC.\n\nNotation \"'`Ch_' n '(' A ',' B ')'\" := (@DMC.channel_ext A B n) (at level 10, n, A, B at next level) : channel_scope.\n\nNotation \"'`Ch_' n '(' A ',' B ')'\" := (@DMC.channel_ext A B n) (at level 10, A, B, n at next level, format \"'`Ch_'  n  '(' A ','  B ')'\") : channel_scope.\n\nNotation \"W '``^' n\" := (@DMC.c _ _ W n) (at level 10) : channel_scope.\n\nNotation \"W '``^' n '(|' c ')'\" := (@DMC.c _ _ W n c) (at level 10, n, c at next level) : channel_scope.\n\nNotation \"W '``^' n '(' b '|' a ')'\" := (@DMC.c _ _ W n a b) (at level 10, n, b, a at next level) : channel_scope.\n\nLocal Open Scope proba_scope.\n\nLemma DMC_nonneg {A B : finType} n (W : `Ch_1(A, B)) b a : 0 <= W ``^ n (b | a).\nProof. rewrite /DMC.c. unlock. by apply DMC.f0. Qed.\n\nModule OutDist.\n\nSection OutDist_sect.\n\nVariables A B : finType.\nVariable P : dist A.\nVariable W  : `Ch_1(A, B).\n\n(** Output distribution for the discrete channel: *)\n\nDefinition f (b : B) := \\rsum_(a in A) W a b * P a.\n\nLemma f0 (b : B) : 0 <= f b.\nProof. apply: Rle_big_0_P_g => a _; apply: Rmult_le_pos; by apply Rle0f. Qed.\n\nLemma f1 : \\rsum_(b in B) f b = 1.\nProof.\nrewrite exchange_big /= -(pmf1 P).\napply eq_bigr => a _; by rewrite -big_distrl /= (pmf1 (W a)) Rmult_1_l.\nQed.\n\nDefinition d : dist B := makeDist f0 f1.\n\nEnd OutDist_sect.\n\nEnd OutDist.\n\nNotation \"'`O(' P , W )\" := (OutDist.d P W) (at level 10, P, W at next level) : channel_scope.\n\nSection OutDist_prop.\n\nVariables A B : finType.\n\n(** Equivalence between both definition when n = 1: *)\n\nLocal Open Scope reals_ext_scope.\nLocal Open Scope vec_ext_scope.\nLocal Open Scope ring_scope.\n\nLemma tuple_pmf_out_dist (W : `Ch_1(A, B)) (P : dist A) n (b : 'rV_ _):\n   \\rsum_(j0 : 'rV[A]_n)\n      ((\\rmul_(i < n) W j0 ``_ i b ``_ i) * P `^ _ j0)%R =\n   TupleDist.f (`O(P , W)) b.\nProof.\nrewrite /TupleDist.f /=.\napply/esym.\nrewrite bigA_distr_big_dep /=.\nrewrite (reindex_onto (fun p : 'rV_ _ => [ffun x => p ``_ x]) (fun y => \\row_(k < n) y k)) //=; last first.\n  move=> i _.\n  apply/ffunP => /= n0.\n  by rewrite ffunE mxE.\n(*rewrite (@big_tcast _ _ _ _ _ (card_ord n)) //.*)\napply eq_big.\n- move=> a /=.\n  apply/andP; split.\n    by apply/forallP.\n  by apply/eqP/matrixP => a' b'; rewrite {a'}(ord1 a') mxE ffunE.\n- move=> a Ha.\n  rewrite big_split /=.\n  congr (_ * _)%R.\n  + apply eq_bigr => i /= _; by rewrite ffunE.\n  + apply eq_bigr => i /= _; by rewrite ffunE.\nQed.\n\nEnd OutDist_prop.\n\n(** Output entropy: *)\n\nLocal Open Scope entropy_scope.\n\nNotation \"'`H(' P '`o' W )\" := (`H ( `O( P , W ))) (at level 10, P, W at next level) : channel_scope.\n\nModule JointDist.\n\nSection JointDist_sect.\n\nVariables A B : finType.\nVariable P : dist A.\nVariable W : `Ch_1(A, B).\n\n(** Joint distribution: *)\n\nDefinition f (ab : A * B) := W ab.1 ab.2 * P ab.1.\n\nLemma f0 (ab : A * B) : 0 <= f ab.\nProof. apply: Rmult_le_pos; by [apply ptm0 | apply Rle0f]. Qed.\n\nLemma f1 : \\rsum_(ab | ab \\in {: A * B}) (W ab.1) ab.2 * P ab.1 = 1.\nProof.\nrewrite -(pair_big xpredT xpredT (fun a b => (W a) b * P a)) /= -(pmf1 P).\napply eq_bigr => /= t Ht; by rewrite -big_distrl /= pmf1 Rmult_1_l.\nQed.\n\nDefinition d : dist [finType of A * B] := makeDist f0 f1.\n\nEnd JointDist_sect.\n\nEnd JointDist.\n\nDefinition JointDistd {A B : finType} (P : dist A) (W : `Ch_1(A, B)) :=\n  nosimpl JointDist.d _ _ P W.\n\nNotation \"'`J(' P , W )\" := (JointDistd P W) (at level 10, P, W at next level) : channel_scope.\n\nSection Pr_tuple_prod_sect.\n\nVariable A B : finType.\nVariable P : dist A.\nVariable W : `Ch_1(A, B).\nVariable n : nat.\n\nLemma Pr_tuple_prod Q : Pr (`J(P `^ n, (W ``^ n))) [set x | Q x] =\n  Pr (`J(P, W)) `^ n [set x | Q (tuple_prod x)].\nProof.\nrewrite /Pr.\nrewrite rsum_rV_prod /=.\napply eq_big.\n  move=> tab /=.\n  by rewrite !inE prod_tupleK.\nmove=> tab.\nrewrite inE => Htab.\nrewrite /JointDist.f /TupleDist.f.\nrewrite /DMC.c; unlock => /=.\nrewrite -big_split /=.\napply eq_bigr => i /= _.\nby rewrite /JointDist.f /= -snd_tnth_prod_tuple -fst_tnth_prod_tuple.\nQed.\n\nEnd Pr_tuple_prod_sect.\n\n(** Mutual entropy: *)\n\nNotation \"`H( P , W )\" := (`H ( `J(P , W))) (at level 10, P, W at next level) : channel_scope.\n\nSection conditional_entropy.\n\nVariable A B : finType.\nVariable W : `Ch_1(A, B).\nVariable P : dist A.\n\n(** Definition of conditional entropy *)\n\nDefinition cond_entropy := `H(P , W) - `H P.\n\nEnd conditional_entropy.\n\nNotation \"`H( W | P )\" := (cond_entropy W P) (at level 10, W, P at next level) : channel_scope.\n\nLocal Open Scope channel_scope.\n\nSection conditional_entropy_prop.\n\nVariables A B : finType.\nVariable W : `Ch_1(A, B).\nVariable P : dist A.\nLocal Open Scope channel_scope.\nLocal Open Scope Rb_scope.\n\n(** Equivalent expression of the conditional entropy (cf. Lemma 6.23) *)\n\nLemma cond_entropy_single_sum : `H( W | P ) = \\rsum_(a in A) P a * `H (W a).\nProof.\nrewrite /cond_entropy /`H /OutDist.d /JointDist.d /=.\nrewrite -(pair_big xpredT xpredT (fun a b => (W a) b * P a * log (W a b * P a))) /=.\nrewrite /Rminus -Ropp_plus_distr /=; f_equal.\nrewrite (big_morph _ morph_Ropp Ropp_0) -big_split /= (big_morph _ morph_Ropp Ropp_0).\napply eq_bigr => // a _.\ncase/boolP : (P a == 0); move=> Hcase.\n- move/eqP in Hcase.\n  rewrite Hcase !(mul0R, addR0, Ropp_0).\n  transitivity (- \\rsum_(b : B) 0).\n    f_equal.\n    apply eq_bigr => // b _.\n    by rewrite !(mul0R, mulR0).\n  by rewrite big_const iter_Rplus mulR0 Ropp_0.\n- rewrite Rmult_comm -(Rmult_1_r (-(log (P a) * P a))) -(pmf1 (W a)).\n  rewrite (big_morph _ (morph_mulRDr _) (mulR0 _)) Ropp_mult_distr_r_reverse; f_equal.\n  rewrite (big_morph _ (morph_mulRDr _) (mulR0 _)) -big_split /=.\n  apply eq_bigr => // b _.\n  case/boolP : (W a b == 0); move=> Hcase2.\n  - move/eqP in Hcase2.\n    by rewrite Hcase2 !mul0R !mulR0 addR0.\n  - rewrite log_mult; last 2 first.\n    + apply Rlt_le_neq; first by apply Rle0f.\n      move=> abs; by rewrite -abs eqxx in Hcase2.\n    + apply Rlt_le_neq; first by apply Rle0f.\n      move=> abs; by rewrite -abs eqxx in Hcase.\n   by field.\nQed.\n\nEnd conditional_entropy_prop.\n\nSection mutual_information_section.\n\nVariables A B : finType.\n\n(** Mutual information of distributions *)\n\nDefinition mut_info_dist (P : dist [finType of A * B]) :=\n  `H (ProdDist.proj1 P) + `H (ProdDist.proj2 P) - `H P.\n\n(** Mutual information of input/output *)\n\nDefinition mut_info P (W : `Ch_1(A, B)) := `H P + `H(P `o W) - `H(P , W).\n\nEnd mutual_information_section.\n\nNotation \"`I( P ; W )\" := (mut_info P W) (at level 50) : channel_scope.\n\nSection capacity_definition.\n\nVariables A B : finType.\n\n(** Relation defining the capacity of a channel: *)\n\nDefinition ubound {S : Type} (f : S -> R) (ub : R) := forall a, f a <= ub.\n\nDefinition lubound {S : Type} (f : S -> R) (lub : R) :=\n  ubound f lub /\\ forall ub, ubound f ub -> lub <= ub.\n\nDefinition capacity (W : `Ch_1(A, B)) cap := lubound (fun P => `I(P ; W)) cap.\n\nLemma capacity_uniq (W : `Ch_1(A, B)) r1 r2 :\n  capacity W r1 -> capacity W r2 -> r1 = r2.\nProof. case=> H1 H2 [H3 H4]; apply Rle_antisym; by [apply H2 | apply H4]. Qed.\n\nEnd capacity_definition.\n", "meta": {"author": "johnbender", "repo": "shannon", "sha": "552c66f7c76ad687430f4fb8122a2a2b94b741ee", "save_path": "github-repos/coq/johnbender-shannon", "path": "github-repos/coq/johnbender-shannon/shannon-552c66f7c76ad687430f4fb8122a2a2b94b741ee/channel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835330070838, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6689649807748704}}
{"text": "(** * Hashfun: Functional model of hash tables *)\n\n(** ** This C program, [hash.c], implements a hash table with\n   external chaining.  See http://www.cs.princeton.edu/~appel/HashTables.pdf\n   for an introduction to hash tables.  *)\n\n(** \n\n#include <stddef.h>\n\nextern void * malloc (size_t n);\nextern void exit(int n);\nextern size_t strlen(const char *str);\nextern char *strcpy(char *dest, const char *src);\nextern int strcmp(const char *str1, const char *str2);\n\nunsigned int hash (char *s) {\n  unsigned int n=0;\n  unsigned int i=0;\n  int c=s[i];\n  while (c) {\n    n = n*65599u+(unsigned)c;\n    i++;\n    c=s[i];\n  }\n  return n;\n}\n\nstruct cell {\n  char *key;\n  unsigned int count;\n  struct cell *next;\n};\n\nenum {N = 109};\n\nstruct hashtable {\n  struct cell *buckets[N];\n};\n\nchar *copy_string (char *s) {\n  int i,n = strlen(s)+1;\n  char *p = malloc(n);\n  if (!p) exit(1);\n  strcpy(p,s);\n  return p;\n}\n\nstruct hashtable *new_table (void) {\n  int i;\n  struct hashtable *p = (struct hashtable * )malloc(sizeof(struct hashtable));\n  if (!p) exit(1);\n  for (i=0; i<N; i++) p->buckets[i]=NULL;\n  return p;\n}  \n\nstruct cell *new_cell (char *key, int count, struct cell *next) {\n  struct cell *p = (struct cell * )malloc(sizeof(struct cell));\n  if (!p) exit(1);\n  p->key = copy_string(key);\n  p->count = count;\n  p->next = next;\n  return p;\n}\n\nunsigned int get (struct hashtable *table, char *s) {\n  unsigned int h = hash(s);\n  unsigned int b = h % N;\n  struct cell *p = table->buckets[b];\n  while (p) {\n    if (strcmp(p->key, s)==0)\n      return p->count;\n    p=p->next;\n  }\n  return 0;\n}\n\nvoid incr_list (struct cell **r0, char *s) {\n  struct cell *p, **r;\n  for(r=r0; ; r=&p->next) {\n    p = *r;\n    if (!p) {\n      *r = new_cell(s,1,NULL);\n      return;\n    }\n    if (strcmp(p->key, s)==0) {\n      p->count++;\n      return;\n    }\n  }\n}  \n\nvoid incr (struct hashtable *table, char *s) {\n  unsigned int h = hash(s);\n  unsigned int b = h % N;\n  incr_list (& table->buckets[b], s);\n}\n*)\n\n(* ================================================================= *)\n(** ** A functional model *)\n\n(** Before we prove the C program correct, we write a functional\n program that models its behavior as closely as possible.  \n The functional program won't be (average) constant time per access,\n like the C program, because it takes linear time to get the nth\n element of a list, while the C program can subscript an array in\n constant time.  But we are not worried about the execution time\n of the functional program; only that it serve as a model\n for specifying the C program. *)\n\n\nRequire Import VST.floyd.functional_base.\nRequire ReflOmegaCore.\n\nDefinition string := list byte.\nInstance EqDec_string: EqDec string := list_eq_dec Byte.eq_dec. \n\nFixpoint hashfun_aux (h: Z) (s: string) : Z :=\n match s with\n | nil => h\n | c :: s' =>\n      hashfun_aux ((h * 65599 + Byte.signed c) mod Int.modulus) s'\nend.\n\nDefinition hashfun (s: string) := hashfun_aux 0 s.\n\nDefinition hashtable_contents := list (list (string * Z)).\n\nDefinition N := 109.\nLemma N_eq : N = 109. \nProof. reflexivity. Qed.\nHint Rewrite N_eq : rep_omega.\nGlobal Opaque N.\n\nDefinition empty_table : hashtable_contents :=\n  list_repeat (Z.to_nat N) nil.\n\nFixpoint list_get (s: string) (al: list (string * Z)) : Z :=\n  match al with\n | (k,i) :: al' => if eq_dec s k then i else list_get s al'\n | nil => 0\n end.\n\nFixpoint list_incr (s: string) (al: list (string * Z))\n              :  list (string * Z) :=\n  match al with\n | (k,i) :: al' => if eq_dec s k \n                      then (k, i +1)::al'\n                      else (k,i)::list_incr s al'\n | nil => (s, 1)::nil\n end.\n\nDefinition hashtable_get  (s: string) (contents: hashtable_contents) : Z :=\n  list_get s (Znth (hashfun s mod (Zlength contents)) contents).\n\nDefinition hashtable_incr (s: string) (contents: hashtable_contents)\n                      : hashtable_contents :=\n  let h := hashfun s mod (Zlength contents)\n  in let al := Znth h contents\n  in upd_Znth h contents (list_incr s al).\n\n(** **** Exercise: 2 stars (hashfun_inrange)  *)\n\nLemma mod_range: forall z m: Z, 0 < m -> 0 <= z mod m <= m - 1.\nProof.\n  intros.\n  assert(0 <= z mod m < m). {\n    apply Z.mod_pos_bound; auto.\n  }\n  omega.\nQed.\n\nLemma mod_in_range: forall z : Z, 0 <= (z mod Int.modulus) <= Int.max_unsigned.\nProof.\n  intros.\n  unfold Int.max_unsigned.\n  assert(4294967296 = Int.modulus). {\n    compute; reflexivity.\n  }\n  rewrite <- H; clear H.\n  apply mod_range; omega.\nQed.\n\nLemma hashfun_aux_inrange: forall s h, 0 <= h <= Int.max_unsigned ->\n                                  0 <= hashfun_aux h s <= Int.max_unsigned.\nProof.\n  induction s as [|h t].\n  - (* s is nil *)\n    intros.\n    auto.\n  - (* s is h :: t *)\n    intros.\n    simpl.\n    apply IHt.\n    apply mod_in_range.\nQed.\n\nLemma hashfun_inrange: forall s, 0 <= hashfun s <= Int.max_unsigned.\nProof.\n  unfold hashfun.\n  intros.\n  apply hashfun_aux_inrange.\n  rep_omega.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star (hashfun_get_unfold)  *)\nLemma hashtable_get_unfold:\n forall sigma (cts: list (list (string * Z) * val)),\n hashtable_get sigma (map fst cts) =\n  list_get sigma (Znth (hashfun sigma mod (Zlength cts)) (map fst cts)).\nProof.\n  intros.\n  unfold hashtable_get.\n  rewrite Zlength_map.\n  auto.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars (Zlength_hashtable_incr)  *)\nLemma Zlength_hashtable_incr:\n forall sigma cts, \n      0 < Zlength cts -> \n      Zlength (hashtable_incr sigma cts) = Zlength cts.\nProof.\n  intros.\n  unfold hashtable_incr.\n  rewrite upd_Znth_Zlength; auto.\n  apply Z.mod_pos_bound; auto.\nQed.\nHint Rewrite Zlength_hashtable_incr using list_solve : sublist.\n(** [] *)\n\nLemma int_rep_helper: forall x y,\n    x mod Int.modulus = y  mod Int.modulus ->\n    Int.repr x = Int.repr y.\nProof.\n  intros.\n  apply Int.eqm_samerepr.\n  unfold Int.eqm.\n  assert(0 < Int.modulus). {\n    rep_omega.\n  }\n  remember Int.modulus as b.\n  clear Heqb.\n  unfold Int.eqmod.\n  assert(x = b * (x / b) + (x mod b)). {\n    apply Z.div_mod.\n    rep_omega.\n  }\n  assert(y = b * (y / b) + (y mod b)). {\n    apply Z.div_mod.\n    rep_omega.\n  }\n  assert(y mod b = y - b * (y / b)). {\n    omega.\n  }\n  rewrite H in H1.\n  rewrite H3 in H1.\n  clear H H2 H3.\n  remember (x / b) as xb.\n  remember (y / b) as yb.\n  clear H0 Heqxb Heqyb.\n  exists (xb - yb).\n  rewrite Z.mul_comm.\n  rewrite H1; clear H1.\n  rewrite Z.mul_sub_distr_l.\n  rewrite Z.add_sub_assoc.\n  omega.\nQed.\n\nDefinition hash_step (hin: Z) (c: byte) :=\n  ((hin * 65599 + Byte.signed c) mod Int.modulus).\n\nDefinition hashfun_aux' (h: Z) (s: string) :=\n  fold_left hash_step s h.\n\nLemma hashfun_aux_equiv:\n  forall h s, hashfun_aux h s = hashfun_aux' h s.\nProof.\n  intros.\n  revert h.\n  induction s as [| sh st].\n  - (* s is nil *)\n    intros.\n    unfold hashfun_aux.\n    unfold hashfun_aux'.\n    simpl.\n    auto.\n  - (* s is sh :: st *)\n    intros.\n    unfold hashfun_aux.\n    fold hashfun_aux.\n    rewrite IHst.\n    unfold hashfun_aux'.\n    unfold fold_left.\n    auto.\nQed.\n\nDefinition hash_step' (c: byte) (hin: Z) :=\n  hash_step hin c.\n\nDefinition hashfun_aux'' (h: Z) (s: string) :=\n  fold_right hash_step' h (rev s).\n\nLemma hashfun_aux_equiv':\n  forall h s, hashfun_aux' h s = hashfun_aux'' h s.\nProof.\n  intros.\n  unfold hashfun_aux'.\n  unfold hashfun_aux''.\n  assert(hash_step = (fun x y => hash_step' y x)). {\n    unfold hash_step'.\n    unfold hash_step.\n    auto.\n  }\n  rewrite H.\n  rewrite fold_left_rev_right.\n  auto.\nQed.\n\nLemma hashfun_aux_equiv'':\n  forall h s, hashfun_aux h s = hashfun_aux'' h s.\nProof.\n  intros.\n  rewrite hashfun_aux_equiv.\n  rewrite hashfun_aux_equiv'.\n  auto.\nQed.\n\nSearch (rev _ ++ rev _).\nLemma hashfun_snoc0:\n  forall (s1 s2: string) (h: Z),\n    Int.repr (hashfun_aux h (s1 ++ s2)) =\n    Int.repr (hashfun_aux (hashfun_aux h s1) s2).\nProof.\n  intros.\n  apply int_rep_helper.\n  rewrite hashfun_aux_equiv''.\n  rewrite hashfun_aux_equiv''.\n  rewrite hashfun_aux_equiv''.\n  unfold hashfun_aux''.\n  rewrite rev_app_distr.\n  rewrite fold_right_app.\n  auto.\nQed.\n\nLemma hashfun_snoc:\n  forall sigma h lo i,\n    0 <= lo ->\n    lo <= i < Zlength sigma ->\n  Int.repr (hashfun_aux h (sublist lo (i + 1) sigma)) =\n  Int.repr (hashfun_aux h (sublist lo i sigma) * 65599 + Byte.signed (Znth i sigma)).\nProof.\n  intros.\n  assert(sublist lo (i + 1) sigma =\n         sublist lo i sigma ++ sublist i (i + 1) sigma). {\n    rewrite (sublist_split lo i (i+1)); try omega; auto.\n  }\n  rewrite H1. clear H1.\n  rewrite hashfun_snoc0.\n  rewrite sublist_len_1; try omega; auto.\n  apply int_rep_helper.\n  unfold hashfun_aux at 1.\n  rewrite Zmod_mod.\n  auto.\nQed.\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** Functional model satisfies the high-level specification *)\n\n(** The purpose of a hash table is to implement a finite mapping,\n  (a finite function) from keys to values.  We claim that the\n  functional model ([empty_table, hashtable_get, hashtable_incr])\n  correctly implements the appropriate operations on the abstract\n  data type of finite functions.\n\n  We formalize that statement by defining a Module Type: *)\n\nModule Type COUNT_TABLE.\n Parameter table: Type.\n Parameter key : Type.\n Parameter empty: table.\n Parameter get: key -> table -> Z.\n Parameter incr: key -> table -> table.\n Axiom gempty: forall k,   (* get-empty *)\n       get k empty = 0.\n Axiom gss: forall k t,      (* get-set-same *)\n      get k (incr k t) = 1+(get k t).\n Axiom gso: forall j k t,    (* get-set-other *)\n      j <> k -> get j (incr k t) = get j t.\nEnd COUNT_TABLE.\n\n(** This means:  in any [Module] that satisfies this [Module Type],\n   there's a type [table] of count-tables,\n   and operators [empty], [get], [set] that satisfy the axioms\n   [gempty], [gss], and [gso]. *)\n  \n(* ----------------------------------------------------------------- *)\n(** *** A \"reference\" implementation of COUNT_TABLE *)\n\n(** **** Exercise: 2 stars (FunTable)  *)\n(**  It's easy to make a slow implementation of [COUNT_TABLE], using functions. *)\n\nModule FunTable <: COUNT_TABLE.\n Definition table: Type := nat -> Z.\n Definition key : Type := nat.\n Definition empty: table := fun k => 0.\n Definition get (k: key) (t: table) : Z := t k.\n Definition incr (k: key) (t: table) : table :=\n    fun k' => if Nat.eqb k' k then 1 + t k' else t k'.\n Lemma gempty: forall k,  get k empty = 0.\n Proof.\n   intros.\n   unfold get.\n   unfold empty.\n   auto.\n Qed.\n \n Lemma gss: forall k t,  get k (incr k t) = 1+(get k t).\n Proof.\n   intros.\n   unfold get.\n   unfold incr.\n   rewrite Nat.eqb_refl.\n   auto.\n Qed.\n \n Lemma gso: forall j k t,  j <> k -> get j (incr k t) = get j t.\n Proof.\n   intros.\n   unfold get.\n   unfold incr.\n   rewrite <- Nat.eqb_neq in H.\n   rewrite H.\n   auto.\n Qed.\n \nEnd FunTable.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Demonstration that hash tables implement COUNT_TABLE *)\n\n(** **** Exercise: 3 stars (IntHashTable)  *)\n(**  Now we make a \"fast\" implementation using hash tables.  We\n  put \"fast\" in quotes because, unlike the imperative implementation,\n the purely functional implementation takes linear time, not constant time,\n to select the the i'th bucket.  That is, [Znth i al] takes time proportional to [i].\n But that is no problem, because we are not using [hashtable_get] and\n [hashtable_incr] as our real implementation; they are serving as the \n _functional model_ of the fast implementation in C.  *)\n\nModule IntHashTable <: COUNT_TABLE.\n Definition hashtable_invariant (cts: hashtable_contents) : Prop :=\n  Zlength cts = N /\\\n  forall i, 0 <= i < N ->\n             list_norepet (map fst (Znth i cts))\n             /\\ Forall (fun s => hashfun s mod N = i) (map fst (Znth i cts)).\n Definition table := sig hashtable_invariant.\n Definition key := string.\n\n Lemma empty_invariant: hashtable_invariant empty_table.\n Proof.\n   \n   unfold empty_table.\n   unfold hashtable_invariant;split.\n   { (* Length *)\n     rewrite  Zlength_correct.\n     rewrite length_list_repeat.\n     rewrite Z2Nat.id; auto.\n     rewrite N_eq.\n     omega.\n   }\n   \n   { intros;split.\n     { (* list_norepet (map fst (Znth i (list_repeat (Z.to_nat N) nil))) *)\n       rewrite Znth_list_repeat_inrange;auto.\n       simpl.\n       apply list_norepet_nil.\n     }\n     { (* Forall (fun s : string => hashfun s mod N = i)\n          (map fst (Znth i (list_repeat (Z.to_nat N) nil))) *)  \n       rewrite Znth_list_repeat_inrange;auto.\n       simpl.\n       constructor.\n     }\n   }\n Qed.\n\n Lemma list_incr_in_existing:\n   forall (s: string) (al: list (string * Z)),\n     (In s (map fst al)) ->\n     (map fst (list_incr s al)) = (map fst al).\n Proof.\n   intros.\n   induction al as [|hd tl].\n   - (* al is nil *)\n     inversion H.\n   - (* al is hd :: tl *)\n     destruct hd as [hs hz].\n     simpl in *.\n     destruct (eq_dec s hs) eqn: dshs.\n     * simpl;auto.\n     * simpl.\n       f_equal.\n       apply IHtl.\n       destruct H; auto.\n       subst hs. contradiction.\n Qed.\n \n Lemma list_incr_not_in_existing:\n   forall (s: string) (al: list (string * Z)),\n     ~ (In s (map fst al)) ->\n     (map fst (list_incr s al)) = (map fst al) ++ s :: nil.\n Proof.\n   intros.\n   revert H.\n   induction al as [|hd tl].\n   - (* al is nil *)\n     intros.\n     simpl; auto.\n   - (* al is hd :: tl *)\n     intros.\n     destruct hd as [hs hz].\n     simpl in *.\n     assert(hs <> s /\\ ~ In s (map fst tl)). {\n        split.\n        - unfold not.\n          intro.\n          subst hs.\n          apply H.\n          left;auto.\n        - intro.\n          apply H.\n          right;auto.\n     }\n     destruct H0.\n     destruct (eq_dec s hs) eqn: dshs.\n     * subst hs.\n       contradiction.\n     * simpl in *.\n       f_equal.\n       apply IHtl;auto.\n Qed.\n\n Lemma list_incr_not_in:\n   forall (s hstring : string) (t : list (string * Z)),\n     ~ In hstring (map fst t) ->\n     s <> hstring -> ~ In hstring (map fst (list_incr s t)).\n Proof.\n   intros s hstring t H2 n.\n   assert(forall l l' : list byte, {l = l'} + {l <> l'}). {\n     apply list_eq_dec.\n     apply Byte.eq_dec.\n   }\n   destruct (ListDec.In_dec H s (map fst t)) eqn: si.\n   - rewrite list_incr_in_existing; auto.\n   - rewrite list_incr_not_in_existing; auto.\n     intro.\n     remember (map fst t) as ts.\n     remember (s :: nil) as ssingle.\n     Search app.\n     apply in_app_or in H0.\n     destruct H0; try contradiction.\n     subst ssingle.\n     simpl in *.\n     destruct H0; try contradiction.\n Qed.\n \n Lemma list_incr_nodup:\n   forall (s: string) (al: list (string * Z)),\n     list_norepet (map fst al) -> list_norepet (map fst (list_incr s al)).\n Proof.\n   intros.\n   induction al as [|h t].\n   - (* al is nil *)\n     vm_compute.\n     assert(~In s nil). {\n       auto.\n     }\n     apply (list_norepet_cons s H0).\n     constructor.\n   - inversion H.\n     simpl.\n     destruct h as [hstring hcount].\n     simpl in *.\n     destruct (eq_dec s hstring) eqn: sh.\n     * simpl.\n       apply list_norepet_cons; auto.\n     * simpl in *.\n       apply list_norepet_cons; auto.\n       apply list_incr_not_in; auto.\n Qed.\n\nCheck ReflOmegaCore.ZOmega.IP.beq_reflect.\n Lemma incr_invariant:\n   forall k cts, hashtable_invariant cts -> hashtable_invariant (hashtable_incr k cts).\n Proof.\n   intros.\n   destruct H.\n   unfold hashtable_incr.\n   split.\n   { (* Length unchanged *)\n     rewrite upd_Znth_Zlength; auto.\n     assert(forall (A: Type) (l: list A), 0 <= Zlength l). {\n       intros.\n       apply (Zlength_nonneg l).\n     }\n     specialize (H1 (list (string * Z)) cts).\n     rewrite H in *.\n     rewrite N_eq in *.\n     generalize (hashfun k).\n     intros.\n     apply Z.mod_pos_bound; omega.\n   }\n   intros.\n   split.\n   {\n     (* list_norepet *)\n     remember (hashfun k mod Zlength cts) as bucket.\n     destruct (ReflOmegaCore.ZOmega.IP.beq_reflect bucket i).\n     { (* bucket = i *)\n       subst i.\n       rewrite <- H in *.\n       rewrite upd_Znth_same; auto.\n       apply list_incr_nodup.\n       specialize (H0 bucket).\n       apply H0 in H1.\n       destruct H1; auto.\n     }\n     { (* bucket != i *)\n       rewrite <- H in *.\n       rewrite upd_Znth_diff; auto.\n       specialize (H0 i).\n       apply H0 in H1.\n       destruct H1;auto.\n       subst bucket.\n       rewrite H in *.\n       rewrite N_eq in *.\n       apply Z.mod_pos_bound.\n       omega.\n     }\n   }\n   { (* All the strings in the ith bucket hash to i. *)\n     remember (hashfun k mod Zlength cts) as bucket.\n     destruct (ReflOmegaCore.ZOmega.IP.beq_reflect bucket i).\n     { (* bucket = i *)\n       subst i.\n       rewrite <- H in *.\n       rewrite upd_Znth_same; auto.\n       assert(forall l l' : list byte, {l = l'} + {l <> l'}). {\n         apply list_eq_dec.\n         apply Byte.eq_dec.\n       }\n       destruct (ListDec.In_dec H2 k (map fst (Znth bucket cts))) eqn: si.\n       { (* k is in the bucket already. *)\n         rewrite list_incr_in_existing; auto.\n         specialize (H0 bucket).\n         apply H0 in H1.\n         destruct H1; auto.\n       }\n       { (* k is not in the bucket. *)\n         rewrite list_incr_not_in_existing; auto.\n         specialize (H0 bucket).\n         apply H0 in H1.\n         destruct H1; auto.\n         apply Forall_app.\n         split; auto.\n       }\n     }\n     { (* bucket != i *)\n       rewrite <- H in *.\n       rewrite upd_Znth_diff; auto.\n       specialize (H0 i).\n       apply H0 in H1.\n       destruct H1;auto.\n       subst bucket.\n       rewrite H in *.\n       rewrite N_eq in *.\n       apply Z.mod_pos_bound.\n       omega.\n     }\n   }\n Qed.\n \n\n Definition empty : table := exist _ _ empty_invariant.\n Definition get : key -> table -> Z := fun k tbl => hashtable_get k (proj1_sig tbl).\n Definition incr : key -> table -> table := \n       fun k tbl => exist _ _ (incr_invariant k _ (proj2_sig tbl)).\n\n\n Theorem gempty: forall k, get k empty = 0.\n Proof.\n   intros.\n   unfold empty.\n   unfold empty_table.\n   unfold get.\n   simpl.\n   unfold hashtable_get.\n   rewrite  Zlength_correct.\n   rewrite length_list_repeat.\n   assert(0 < N). {\n     rewrite N_eq;omega.\n   }\n   rewrite Z2Nat.id by omega.\n   remember (hashfun k mod N) as bucket.\n   assert(0 <= bucket < N). {\n     subst bucket.\n     apply Z.mod_pos_bound. auto.\n   }\n   rewrite Znth_list_repeat_inrange by auto.\n   simpl; auto.\n Qed.\n \n Lemma get_incr_result:\n   forall (k : key) (bklist : list (string * Z)),\n     list_get k (list_incr k bklist) = 1 + list_get k bklist.\n Proof.\n   intros k bklist.\n   induction bklist as [|hd tl].\n   - (* bklist is  nil *)\n     simpl.\n     rewrite pred_dec_true;auto.\n   - (* inductive case *)\n     simpl.\n     destruct hd as [hk hz].\n     destruct (eq_dec k hk).\n     * rewrite pred_dec_true; auto.\n       unfold list_get.\n       rewrite pred_dec_true; auto.\n       rewrite pred_dec_true; auto.\n       rewrite Z.add_comm.\n       reflexivity.\n     * rewrite pred_dec_false; auto.\n       unfold list_get.\n       rewrite pred_dec_false; auto.\n       rewrite pred_dec_false; auto.\n Qed.\n\n Lemma get_incr_diff_result:\n   forall (j k : key) (bklist : list (string * Z)),\n     j <> k -> \n     list_get j (list_incr k bklist) = list_get j bklist.\n Proof.\n   intros j k bklist H.\n   induction bklist as [|hd tl].\n   - (* bklist is  nil *)\n     simpl.\n     rewrite pred_dec_false;auto.\n   - (* inductive case *)\n     simpl.\n     destruct hd as [hk hz].\n     destruct (eq_dec j hk).\n     * (* j = hk *)\n       rewrite (pred_dec_true (eq_dec j hk)); auto.\n       rewrite pred_dec_false.\n       simpl.\n       rewrite pred_dec_true; auto.\n       intro.\n       subst j k.\n       contradiction.\n     * (* j <> hk *)\n       rewrite (pred_dec_false (eq_dec j hk)); auto.\n       destruct (eq_dec k hk).\n     { (* k = hk *)\n       rewrite pred_dec_true.\n       simpl.\n       rewrite pred_dec_false; auto.\n       assumption.\n     }\n     { (* k <> hk *)\n       rewrite pred_dec_false; auto.\n       simpl.\n       rewrite pred_dec_false; auto.\n     }\n Qed.\n\n Theorem gss: forall k t,  get k (incr k t) =  1 + (get k t).\n Proof.\n   intros.\n   unfold incr.\n   unfold get.\n   unfold hashtable_get.\n   unfold hashtable_incr.\n   destruct t.\n   simpl.\n   destruct h.\n   rewrite H in *.\n   rewrite N_eq in *.\n   remember (hashfun k mod 109) as bk.\n   assert(forall z : Z,\n             1 + z =\n             (match z with\n             | 0%Z => 1%Z\n             | Z.pos y' => Z.pos match y' with\n                                | q~1 => (Pos.succ q)~0\n                                | q~0 => q~1\n                                | 1 => 2\n                                end\n             | Z.neg y' => Z.pos_sub 1 y'\n              end)%positive). {\n     reflexivity.\n   }\n   rewrite <- H1.\n   assert(0 <= bk < Zlength x). {\n     rewrite Heqbk.\n     rewrite H.\n     apply Z.mod_pos_bound; omega.\n   }\n   rewrite upd_Znth_Zlength;auto.\n   rewrite H.\n   rewrite <- Heqbk.\n   rewrite upd_Znth_same;auto.\n   Search list_incr.\n   remember (Znth bk x) as bklist.\n   rewrite H in *.\n   apply get_incr_result.\n Qed.\n \n Theorem gso: forall j k t,    (* get-set-other *)\n      j <> k -> get j (incr k t) = get j t.\n Proof.\n   intros j k t Hne.\n   unfold incr.\n   unfold get.\n   unfold hashtable_get.\n   unfold hashtable_incr.\n   destruct t.\n   simpl.\n   destruct h.\n   rewrite H in *.\n   rewrite N_eq in *.\n   remember (hashfun k mod 109) as bk.\n   assert(0 <= bk < Zlength x). {\n     rewrite Heqbk.\n     rewrite H.\n     apply Z.mod_pos_bound; omega.\n   }\n   rewrite upd_Znth_Zlength;auto.\n   remember (hashfun j mod 109) as bj.\n   assert(0 <= bj < Zlength x). {\n     rewrite Heqbj.\n     rewrite H.\n     apply Z.mod_pos_bound; omega.\n   }\n   rewrite H.\n   rewrite <- Heqbj.\n   destruct (Z.eq_dec bj bk) eqn:eqbjbk.\n   { (* bj = bk *)\n     rewrite e.\n     rewrite upd_Znth_same.\n     apply get_incr_diff_result; auto.\n     assumption.\n   }\n   { (* bj <> bk *)\n     rewrite upd_Znth_diff; auto.\n   }\n Qed.\n\n(** [] *)\n\nEnd IntHashTable.\n", "meta": {"author": "richardlford", "repo": "digsim", "sha": "4da30b04be3c66762050e56f1eb5a533d6d806d7", "save_path": "github-repos/coq/richardlford-digsim", "path": "github-repos/coq/richardlford-digsim/digsim-4da30b04be3c66762050e56f1eb5a533d6d806d7/formal/hash/Hashfun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.6689649748145516}}
{"text": "Require Import Naturelle.\nSection Session1_2021_Logique_Exercice_1.\n\nVariable A B C : Prop.\n\nTheorem Exercice_1_Naturelle :  ((A -> C) \\/ (B -> C)) -> ((A /\\ B) -> C).\nProof.\nI_imp H1.\nI_imp H2.\nE_ou (A -> C) (B -> C).\nHyp H1.\nI_imp H3.\nE_imp A.\nHyp H3.\nE_et_g B.\nHyp H2.\nI_imp H4.\nE_imp B.\nHyp H4.\nE_et_d A.\nHyp H2.\nQed.\n\nTheorem Exercice_1_Coq : ((A -> C) \\/ (B -> C)) -> ((A /\\ B) -> C).\nProof.\nintro H1.\nintro H2.\nelim H1.\nintro H3.\ncut A.\nexact H3.\ncut (A /\\ B).\nintro H.\nelim H.\nintros HA HB.\nexact HA.\nexact H2.\nintro H4.\ncut B.\nexact H4.\ncut (A /\\ B).\nintro H.\nelim H.\nintros HA HB.\nexact HB.\nexact H2.\nQed.\n\nEnd Session1_2021_Logique_Exercice_1.\n\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_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6689148123461097}}
{"text": "Require Import Basics.\nRequire Import Types.\nRequire Import Diagrams.Graph.\nRequire Import Diagrams.Diagram.\nRequire Import Diagrams.Cocone.\n\n(** Parallel pairs *)\n\nDefinition parallel_pair_graph : Graph.\nProof.\n  serapply (Build_Graph Bool).\n  intros i j.\n  exact (if i then if j then Empty else Bool else Empty).\nDefined.\n\n(** Parallel pair diagram *)\n\nDefinition parallel_pair {A B : Type} (f g : A -> B)\n  : Diagram parallel_pair_graph.\nProof.\n  serapply Build_Diagram.\n  1: intros []; [exact A | exact B].\n  intros [] [] []; [exact f | exact g].\nDefined.\n\n(** Cones on [parallel_pair]s *)\n\nDefinition Build_parallel_pair_cocone {A B Q} {f g : B -> A}\n  `(q: A -> Q) (Hq: q o g == q o f)\n  : Cocone (parallel_pair f g) Q.\nProof.\n  serapply Build_Cocone.\n  1: intros []; [exact (q o f) | exact q].\n  intros [] [] []; [reflexivity | exact Hq].\nDefined.", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/theories/Diagrams/ParallelPair.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.668846197105257}}
{"text": "Require Import Basics.\nRequire Import Pointed.Core.\nRequire Import Colimits.Pushout.\n\n(* Here we define the Wedge sum of two pointed types *)\n\nLocal Open Scope pointed_scope.\n\nDefinition Wedge (X Y : pType) : pType\n  := [Pushout (fun _ : Unit => point X) (fun _ => point Y), pushl (point X)].\n\nNotation \"X \\/ Y\" := (Wedge X Y) : pointed_scope.\n\nDefinition wglue {X Y : pType}\n  : pushl (point X) = (pushr (point Y) : X \\/ Y) := pglue tt.\n\nDefinition wedge_incl {X Y : pType} : X \\/ Y -> X * Y :=\n Pushout_rec _ (fun x => (x, point Y)) (fun y => (point X, y)) \n  (fun _ : Unit => idpath).\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Homotopy/Wedge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6688461937126693}}
{"text": "Definition rewriting (A : Type) := A -> A -> Prop.\nAxiom A : Type.\nAxiom r : rewriting A.\n\nInductive path : A -> A -> Type :=\n| refl (a : A) : path a a\n| trs  {a b c : A} : path a b -> r b c -> path a c.\n\nFixpoint size {a b : A} (p : path a b) : nat :=\n  match p with\n  | refl _ => 0\n  | trs p' _ => 1 + (size p')\n  end.\n\n    \nTheorem diamond_implies_CR :\n  forall (diam : forall (x y z : A), r x y -> r x z -> exists w, (r y w) /\\ (r z w))\n    (a b c : A) (p1 : path a b) (p2 : path a c),\n  exists (d : A) (p1' : path b d) (p2' : path c d),\n    size p1 = size p2' /\\ size p2 = size p1'.\nProof.\n  intros. induction p1. (* induction on a --> b *)\n  -exists c. exists p2. exists (refl c). split; reflexivity.\n  -rename c0 into b'. pose (H := IHp1 p2). destruct H. destruct H. destruct H. destruct H. clear IHp1.\n   generalize dependent c.\n   assert (exists d (p1' : path b' d) (p2' : r x d), size p1' = size x0). \n   +induction x0.\n    ++intros. rename a0 into b. exists b'. exists (refl _). exists r0. reflexivity.\n    ++rename b into x'. rename a0 into b. pose (H := IHx0 p1 r0).\n      destruct H. destruct H. destruct H. pose (H0:= diam _ _ _ x2 r1).\n      destruct H0. destruct H0.\n      exists x3. exists (trs x1 H0). exists H1. simpl. rewrite H. reflexivity.\n   +intros. destruct H. destruct H. destruct H.\n    exists x2. exists x3. exists (trs x1 x4). split.\n    ++simpl. rewrite H0. reflexivity.\n    ++rewrite H. apply H1.\nQed.\n\n", "meta": {"author": "thiagofelicissimo", "repo": "diamond-implies-cr", "sha": "a0f90eabc4bb8f73cc96aa8fc7a19d98be3e20cb", "save_path": "github-repos/coq/thiagofelicissimo-diamond-implies-cr", "path": "github-repos/coq/thiagofelicissimo-diamond-implies-cr/diamond-implies-cr-a0f90eabc4bb8f73cc96aa8fc7a19d98be3e20cb/diamond-implies-cr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6687687896676462}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Export Structured.\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 (cons nat 3 (nil nat)).\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n  \nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity. Qed.\n\nExample test_repeat2 :\n  repeat bool true 2 = cons bool true (cons bool true (nil bool)).\nProof. reflexivity. Qed.\n\nModule MumbleGrumble.\n\n  Inductive mumble : Type :=\n    | a : mumble\n    | b : mumble -> nat -> mumble\n    | c : mumble.\n\n  Inductive grumble (X : Type) : Type :=\n    | d : mumble -> grumble X\n    | e : X -> grumble X.\n\n  (* Check (d (b a 5)) *)\n  Check (d mumble (b a 5)).\n  Check (d bool (b a 5)).\n  Check (e bool true).\n  Check (e mumble (b c 0)).\n  (* Check (e bool (b c 0)). *)\n  Check c.\n\nEnd MumbleGrumble.\n\n\n    \n", "meta": {"author": "jonludlam", "repo": "softwarefoundations", "sha": "26b49791958ffec7cdf47541c7ebaa5667d6da0a", "save_path": "github-repos/coq/jonludlam-softwarefoundations", "path": "github-repos/coq/jonludlam-softwarefoundations/softwarefoundations-26b49791958ffec7cdf47541c7ebaa5667d6da0a/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.6687687878976217}}
{"text": "\n(* Exercise 66 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\n\n(* This theorem shows that on a domain of at most two elements,\n   any instantation of three variables will have a duplicate.\n   Try the same for a domain of three elements, if you have\n   a spare afternoon, the length of the proof explodes with\n   the number of elements of D.\n*)\n\nHypothesis Domain : exists x1 : D, exists x2 : D, forall x : D,\n  (x = x1 \\/ x = x2).\n\nTheorem exercise_066 : forall x1 : D, forall x2 : D, forall x3 : D, (x1=x2 \\/ x1=x3 \\/ x2=x3).\nProof.\nexi_e (exists x1 : D, exists x2 : D, forall x : D,\n  (x = x1 \\/ x = x2)) a a1.\n  hyp Domain.\nexi_e (exists x2 : D, forall x : D,\n  (x = a \\/ x = x2)) b a2.\nhyp a1.\nall_i c.\nall_i d.\nall_i e.\ndis_e (c = a \\/ c = b) a3 a3.\nall_e (forall x:D, x = a \\/ x = b) c.\nhyp a2.\nreplace c with a.\ndis_e (d = a \\/ d = b) a4 a4.\nall_e (forall x:D, x = a \\/ x = b) d.\nhyp a2.\nreplace d with a.\ndis_i1.\nlin_solve.\nreplace d with b.\ndis_e (e = a \\/ e = b) a5 a5.\nall_e (forall x:D, x = a \\/ x = b) e.\nhyp a2.\nreplace e with a.\ndis_i2.\ndis_i1.\nlin_solve.\nreplace e with b.\ndis_i2.\ndis_i2.\nlin_solve.\ndis_e (d = a \\/ d = b) a4 a4.\nall_e (forall x:D, x = a \\/ x = b) d.\nhyp a2.\nreplace d with a.\ndis_e (e = a \\/ e = b) a5 a5.\nall_e (forall x:D, x = a \\/ x = b) e.\nhyp a2.\nreplace e with a.\ndis_i2.\ndis_i2.\nlin_solve.\nreplace e with b.\nreplace c with b.\ndis_i2.\ndis_i1.\nlin_solve.\nreplace c with b.\nreplace d with b.\ndis_i1.\nlin_solve.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred066.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6687687878976216}}
{"text": "Section SetTheory.\n  \n  (* 「Coqによる定理証明入門」 神戸大学 高橋先生 *)\n  (* http://herb.h.kobe-u.ac.jp/coq/coq.pdf *)\n  (* bullet を使ってリライトしています。演習問題の答えはありません。 *)\n  \n  Require Import Ensembles.\n  Require Import Classical.\n  \n  Variable U : Type.\n  Definition Shugo := Ensemble U.\n  \n  Notation \"x ∈ A\" := (In U A x) (at level 55,no associativity).\n  Notation \"A ⊆ B\" := (Included U A B) (at level 54, no associativity).\n  Notation \"A ∩ B\" := (Intersection U A B) (at level 53, right associativity).\n  Notation \"A ∪ B\" := (Union U A B) (at level 53, right associativity).\n  Notation \"A \\ B\" := (Setminus U A B) (at level 52, no associativity).\n  Notation ø := (Empty_set U).\n  Notation Ω := (Full_set U).\n\n  (* Variables A B C : Shugo. *)\n  \n  Lemma in_or_not (A : Shugo) : forall x, (x ∈ A) \\/ ~ x ∈ A.\n  Proof.\n    intros x.\n    now apply classic.\n  Qed.\n  \n  Lemma bubun_traisitive A B C : A ⊆ B /\\ B ⊆ C -> A ⊆ C.\n  Proof.\n    (* unfold Included. *)\n    intros H x HxA.\n    destruct H as [HAB HBC].\n    apply HBC.\n    now apply HAB.\n  Qed.\n\n  Lemma empty_bubun A : ø ⊆ A.\n  Proof.\n    (* unfold Included. *)\n    intros x He.\n    now destruct He.\n  Qed.\n\n  Lemma full_bubun A : A ⊆ Ω.\n  Proof.\n    (* unfold Included. *)\n    intros x HxA.\n    Check Full_intro : forall (U : Type) (x : U), In U (Full_set U) x.\n    now apply Full_intro.\n  Qed.\n  \n  Ltac seteq := apply Extensionality_Ensembles; unfold Same_set; split.\n  \n  Lemma union_id A : A ∪ A = A.\n  Proof.\n    seteq.\n    - intros x HAA.\n      now destruct HAA.\n    - intros x HA.\n      Check Union_introl.\n      now apply Union_introl.\n  Qed.\n\n  Lemma union_comm A B : A ∪ B = B ∪ A.\n  Proof.\n    seteq.\n    - intros x HxAB.\n      destruct HxAB.\n      + now apply Union_intror.\n      + now apply Union_introl.\n    - intros x HxBA.\n      destruct HxBA.\n      + now apply Union_intror.\n      + now apply Union_introl.\n  Qed.\n\n  (*\n  3. A∪(B∪C) = (A∪B)∪C\n  4. A ⊆ A∪B, B ⊆ A∪B\n  5. A, B ⊆ C → A∪B ⊆ C\n   *)\n  \n  Lemma probA4b A B : A ∪ B = B -> A ⊆ B.\n  Proof.\n    intros HAB_B x HxA.\n    rewrite <- HAB_B.\n    now apply Union_introl.\n  Qed.\n\n  (*\n  1. A∩A = A\n  2. A∩B = B∩A\n  3. A∩(B∩C) = (A∩B)∩C\n  4. A∩B ⊆ A, A∩B ⊆ B\n  5. C ⊆ A, B → C ⊆ A∩B\n  6. A ⊆ B ⇔ A∩B = A\n   *)\n  \n  (* 素集合 *)\n  Lemma Kuu A B : Disjoint U A B <-> A ∩ B = ø.\n  Proof.\n    split.\n    - intros Hd.\n      seteq.\n      + intros x HxAB.\n        destruct Hd as [Hd].\n        specialize (Hd x).\n        easy.                               (* 前提が矛盾 *)\n      + now apply empty_bubun.\n    - intros HAB_E.\n      apply Disjoint_intro.\n      intros x.\n      rewrite HAB_E.\n      intros HxE.\n      now destruct HxE.                     (* 前提にx∈ø で矛盾 *)\n  Qed.\n\n  Lemma probA7b A B C : A ∪ B = B ∩ C -> A ⊆ B /\\ B ⊆ C.\n  Proof.\n    intros HAB_BC.\n    split.\n    - intros x HxA.\n      assert (x ∈ A ∪ B).\n      + now apply Union_introl; apply HxA.\n      + rewrite HAB_BC in H.\n        now destruct H.\n    - intros x HxB.\n      assert (x ∈ A ∪ B).\n      + now apply Union_intror; apply HxB.\n      + rewrite HAB_BC in H.\n        now destruct H.\n  Qed.\n  \n  (* \\ の優先順位を変えている。 *)\n  Lemma setminus A B : forall x, x ∈ A -> ~ x ∈ B -> x ∈ A \\ B.\n  Proof.\n    intros x HxA HnxB.\n    split.\n    - easy.                                 (* x ∈ A *)\n    - easy.                                 (* ~ x ∈ B *)\n  Qed.\n  \n  Lemma probA8 A B : (A \\ B) ∪ (A ∩ B) = A.\n  Proof.\n    seteq.\n    - intros x H.\n      destruct H as [x [HA HB] | x [HA HB]].\n      + easy.\n      + easy.\n    - intros x.\n      destruct (in_or_not B x).\n      + intros HxA.\n        apply Union_intror.\n        now apply Intersection_intro.\n      + intros HxA.\n        apply Union_introl.\n        now apply setminus.\n  Qed.\n  \n  (* 集合族 *)\n\n  Variable K : Type.\n  Definition Fam := K -> Shugo.\n\n  Inductive UnionF (X : Fam) : Shugo :=\n    unionf_intro : forall x : U, (exists n : K, x ∈ X n) -> x ∈ UnionF X.\n  \n  Inductive InterF (X : Fam) : Shugo :=\n    interf_intro : forall x : U, (forall n : K, x ∈ X n) -> x ∈ InterF X.\n  \n  Lemma mem_unionf F : forall n, F n ⊆ UnionF F.\n  Proof.\n    intros n x HxFn.\n    apply unionf_intro.\n    now exists n.\n  Qed.\n  \n  Lemma mem_interf F : forall n, InterF F ⊆ F n.\n  Proof.\n    intros n x HIF.\n    destruct HIF as [x HIF].\n    specialize (HIF n).\n    easy.\n  Qed.\n  \n  Lemma unionf_inc F G : (forall n, F n ⊆ G n) -> UnionF F ⊆ UnionF G.\n  Proof.\n    intros HFG x H.\n    destruct H as [x [n H]].\n    apply unionf_intro.\n    exists n.\n    now apply (HFG n).\n  Qed.\n  \n  Lemma interf_inc F G : (forall n, F n ⊆ G n) -> InterF F ⊆ InterF G.\n  Proof.\n    intros HFG x H.\n    unfold Included in HFG.\n    destruct H as [x H].\n    apply interf_intro.\n    intros n.\n    specialize (HFG n x).\n    specialize (H n).    \n    now apply HFG.\n  Qed.\n\nEnd SetTheory.\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/htpl/coq_sets_ku.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303236047049, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.6687431533220264}}
{"text": "Require Import Bool Arith List.\nImport ListNotations.\n\nModule dep_typ.\n\nInductive fulltree (A:Type) : nat -> Type := \n|leaf : A -> fulltree A 0\n|node n : fulltree A n -> fulltree A n -> fulltree A (S(n)) \n.\n\nArguments leaf {A}.\nArguments node {A}.\n\nDefinition blist (A:Type) : Type := \nlist {n & fulltree A n}\n.\n\nDefinition tcast {A} {n} {m} (v: fulltree A n)(h : n = m) : fulltree A m :=\n  match h with\n  | eq_refl => v\n  end.\n\nFixpoint tcons {A} {n:nat} (t:fulltree A n) (l:blist A) := \n\tmatch l with \n\t|[] => [existT _ n t]\n\t|(existT _ n' t')::ll =>\n\t\tmatch Nat.eq_dec n n' with\n\t\t|left p =>  tcons   (node _ (tcast t p) t')   ll \n\t\t|right _=> (existT _ n t) ::l\n\t\tend\nend.\n\n\nDefinition bcons {A} (a:A) l := tcons (leaf a) l.\nCompute bcons 1 (bcons 2 (bcons 3 (bcons 4 []))).\nCompute bcons 1 (bcons 2 (bcons 3  [])).\n\nFixpoint tdecons {A} {n} (t:fulltree A n) (l:blist A) := \n\tmatch t with\n\t|leaf a => (a,l)\n\t|node n fg fd => \n\t\ttdecons fg ((existT _ _ fd)::l) \n\tend.\n\nDefinition bdecons [A:Type] (l: blist A) := \n\tmatch l with \n\t| [] => None\n\t| (existT _ _ t)::ll => Some (tdecons t ll)\n\tend.\n\nDefinition l := bcons 1 (bcons 2 (bcons 3  [])).\nCompute l .\nCompute bdecons l .\n\nFixpoint tnth [A:Type] {st} (t: fulltree A st) n := \n\tmatch t,n with \n\t|leaf a,0 => Some a \n\t|leaf _,_ => None \n\t|node st fg fd, _ => \n\t\tlet st' := 2^(pred st) in\n\t\tif n <? st'  \n\t\tthen tnth fg n\n\t\telse tnth fd (n-st')\n\tend.\t\n\t\n\nFixpoint bnth [A:Type] (l: blist A) n := \nmatch l with \n\t| [] => None\n\t| (existT _ st t)::ll => \n\t\tlet st' := 2^st in\n\t\tif n <? st' \n\t\tthen tnth t n\n\t\telse bnth ll (n-st') \nend.\n\nCompute l.\nCompute bnth l 1.\n\nEnd dep_typ.\n\nInductive tree (A:Type) : Type := \n|leaf : A -> tree A \n|node : tree A -> tree A -> tree A\n.\n\nArguments leaf {A}.\nArguments node {A}.\n\n\nDefinition option_bind {A B} (o : option A) (f:A -> option B) : option B :=\n match o with\n | Some x => f x\n | None => None\n end.\n\nInfix \">>=\" := option_bind (at level 20, left associativity).\n\nFixpoint perfect_depth {A} (t: tree A) : option nat := \nmatch t with \n|leaf _ => Some 0\n|node fg fd => \n\tperfect_depth fg >>= fun size_fg => \n\tperfect_depth fd >>= fun size_fd =>\n\tif size_fg =? size_fd then Some (S(size_fd+size_fd))\n\telse None\nend.\n\nDefinition t1 := (node (leaf 0) (leaf 0)).\nDefinition t2 := (node t1 (leaf 0)).\nCompute perfect_depth t1.\nCompute perfect_depth t2.\n\nModule Type MONAD.\n  Parameter t : Type -> Type.\n  Parameter bind : forall {A B}, t A -> (A -> t B) -> t B.\n  Parameter ret : forall {A}, A -> t A. (* ret, since return is a Coq keyword *)\nEnd MONAD.\n\nCheck List.filter_map.\n\nRequire Import Bool Arith List.\nModule MList <: MONAD.\n  Definition t := list.\n  Definition ret  (a:nat) := [a].\n  Definition bind  (l:list nat) (f:nat->list nat) := List.filter_map Nat.eqb f l.\nEnd MList.\n\nInfix \">>=\" := MList.bind (at level 20, left associativity).\n\nDefinition scoring (n:nat) := [n+3;n+5;n+7].\n\nFixpoint next_scores l n := \n\tmatch n with \n\t|0 => l\n\t|S n' => \n\t\tnext_scores l n' >>= scoring\n\tend.\n\nCompute next_scores [0] 2.\n\nCheck List.flat_map.", "meta": {"author": "sebastienPatte", "repo": "Coq", "sha": "1c031f13db8d7101ca356c23b36d560c0a194de1", "save_path": "github-repos/coq/sebastienPatte-Coq", "path": "github-repos/coq/sebastienPatte-Coq/Coq-1c031f13db8d7101ca356c23b36d560c0a194de1/LMFI/td5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.6687431353305539}}
{"text": "(** 2-2-matrices over a ring A *)\n\nRequire Import Ring.\n\nSection matrices.\n Variables (A:Type)\n           (zero one : A) \n           (plus mult minus : A -> A -> A)\n           (sym : A -> A).\n Notation \"0\" := zero.  Notation \"1\" := one.\n Notation \"x + y\" := (plus x y).  \n Notation \"x * y\" := (mult x y).\n\n Variable rt : ring_theory  zero one plus mult minus sym (@eq A).\n\n Add Ring Aring : rt.  \n\nStructure M2 : Type := {c00 : A;  c01 : A;\n                        c10 : A;  c11 : A}.\n\nDefinition Id2 : M2 := Build_M2 1 0 0 1.\n\nDefinition M2_mult (m m':M2) : M2 :=\n Build_M2 (c00 m * c00 m' + c01 m * c10 m')\n          (c00 m * c01 m' + c01 m * c11 m')\n          (c10 m * c00 m' + c11 m * c10 m')\n          (c10 m * c01 m' + c11 m * c11 m').\n\n\n\nLemma M2_eq_intros : forall a b c d a' b' c' d',\n  a=a' -> b=b' -> c=c' -> d=d' ->\n   Build_M2 a b c d = Build_M2 a' b' c' d'.\nProof. \n intros; now f_equal.\nQed.\n\nEnd matrices.\n\nArguments Build_M2 {A} _ _ _ _.\nArguments M2_mult {A} _ _ _  _.\nArguments c00 {A} _.\nArguments Id2 {A} zero one.\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/Mat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624557, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6687281051033955}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Lia.\n\nFrom Undecidability.Shared.Libs.DLW \n  Require Import utils list_bool gcd pos vec subcode sss.\n\nFrom Undecidability.MinskyMachines.MMA\n  Require Import mma_defs.\n\nSet Implicit Arguments.\n\nTactic Notation \"rew\" \"length\" := autorewrite with length_db.\n\nLocal Notation \"e #> x\" := (vec_pos e x).\nLocal Notation \"e [ v / x ]\" := (vec_change e x v).\n\nLocal Notation \"P // s -[ k ]-> t\" := (sss_steps (@mma_sss _) P k s t).\nLocal Notation \"P // s -+> t\" := (sss_progress (@mma_sss _) P s t).\nLocal Notation \"P // s ->> t\" := (sss_compute (@mma_sss _) P s t).\nLocal Notation \"P // s ↓\" := (sss_terminates (@mma_sss _) P s). \n\n(* Utils for FRACTRAN with two counter *)\n\nSection Minsky_Machine_alt_utils.\n\n  Variable (n : nat).\n  \n  Ltac dest x y := destruct (pos_eq_dec x y) as [ | ]; [ subst x | ]; rew vec.\n\n  Hint Resolve subcode_refl : core.\n\n  Section mma_jump.\n\n    Variable (j : nat) (x : pos n).\n\n    Definition mma_jump := INCₐ x :: DECₐ x j :: nil.\n\n    Notation JUMPₐ := mma_jump.\n\n    Fact mma_jump_length : length JUMPₐ = 2.\n    Proof. auto. Qed.\n    \n    Fact mma_jump_progress i v w : w = v -> (i,JUMPₐ) // (i,v) -+> (j,w).\n    Proof.\n      intros ->.\n      unfold mma_jump.\n      mma sss INC with x.\n      mma sss DEC S with x j (v#>x); rew vec.\n      mma sss stop.\n    Qed.\n\n    Fact mma_jump_spec i v : (i,JUMPₐ) // (i,v) ->> (j,v).\n    Proof. now apply sss_progress_compute, mma_jump_progress. Qed.\n\n  End mma_jump.\n\n  Notation JUMPₐ := mma_jump.\n\n  Hint Rewrite mma_jump_length : length_db.\n\n  Section mma_null.\n\n    (* Empty one register/counter *)\n\n    Variable (x : pos n) (i : nat).\n\n    Definition mma_null := DECₐ x i :: nil.\n\n    Fact mma_null_length : length mma_null = 1.\n    Proof. auto. Qed.\n    \n    Let mma_null_spec k v w :   v#>x = k \n                             -> w = v[0/x]\n                             -> (i,mma_null) // (i,v) -+> (1+i,w).\n    Proof.\n      unfold mma_null.\n      revert v w.\n      induction k as [ | k IHk ]; intros v w H1 H2; subst w.\n      + mma sss DEC zero with x i.\n        mma sss stop; f_equal.\n        apply vec_pos_ext; intros z; dest z x.\n      + mma sss DEC S with x i k.\n        apply sss_progress_compute.\n        apply IHk; rew vec.\n    Qed.\n\n    Fact mma_null_progress v st : \n             st = (1+i,v[0/x])\n          -> (i,mma_null) // (i,v) -+> st.\n    Proof.\n      intros; subst.\n      apply mma_null_spec with (1 := eq_refl); auto.\n    Qed.\n\n  End mma_null.\n\n  Notation NULLₐ := mma_null.\n\n  Hint Rewrite mma_null_length : length_db.\n\n  Section mma_null_list.\n\n    Fixpoint mma_null_list (l : list (pos n)) i :=\n      match l with \n        | nil  => nil\n        | x::l => DECₐ x i :: mma_null_list l (S i)\n      end.\n\n    Fact mma_null_list_length l i : length (mma_null_list l i) = length l.\n    Proof. revert i; induction l; simpl; intro; f_equal; auto. Qed.\n  \n    Fact mma_null_list_spec l i v w :\n           (forall p, In p l -> w#>p = 0)\n        -> (forall p, ~ In p l -> w#>p = v#> p)\n        -> (i,mma_null_list l i) // (i,v) ->> (length l+i,w).\n    Proof.\n      revert i v w; induction l as [ | x l IHl ]; simpl; intros i v w H1 H2.\n      + replace w with v.\n        1: mma sss stop.\n        apply vec_pos_ext; intro p; rewrite H2; auto.\n      + apply subcode_sss_compute_trans \n          with (P := (i,DECₐ x i::nil)) (st2 := (S i,v[0/x])); auto.\n        * apply sss_progress_compute, mma_null_progress; auto.\n        * apply subcode_sss_compute with (P := (S i, mma_null_list l (S i))); auto.\n          replace (S (length l+i)) with (length l+S i) by lia.\n          apply IHl.\n          - intros; apply H1; auto.\n          - intros p Hp.\n            dest p x.\n            apply H2; firstorder.\n    Qed.\n\n  End mma_null_list.\n\n  Section mma_null_all.\n  \n    Variable (i : nat).\n\n    Definition mma_null_all := mma_null_list (pos_list n) i.\n  \n    Fact mma_null_all_length : length mma_null_all = n.\n    Proof. \n      unfold mma_null_all.\n      rewrite mma_null_list_length.\n      apply pos_list_length.\n    Qed.\n\n    Fact mma_null_all_spec v :\n          (i,mma_null_all) // (i,v) ->> (n+i,vec_zero).\n    Proof.\n      replace (n+i) with (length (pos_list n)+i).\n      + apply mma_null_list_spec.\n        * intros; apply vec_zero_spec.\n        * intros ? []; apply pos_list_prop.\n      + now rewrite pos_list_length.\n    Qed.\n\n  End mma_null_all.\n\n  Section mma_incs.\n\n    (* Add a constant value k to register x *)\n\n    Variable (x : pos n).\n\n    Fixpoint mma_incs k := \n      match k with \n        | 0   => nil\n        | S k => INCₐ x :: mma_incs k\n      end.\n\n    Fact mma_incs_length k : length (mma_incs k) = k.\n    Proof. induction k; simpl; f_equal; auto. Qed.\n\n    Fact mma_incs_compute k i v st :\n             st = (k+i,v[(k+(v#>x))/x])\n          -> (i,mma_incs k) // (i,v) ->> st.\n    Proof.\n      revert i v st; induction k as [ | k IHk ]; intros i v st ?; subst.\n      + mma sss stop; f_equal; auto.\n        apply vec_pos_ext; intros p; dest p x.\n      + simpl; mma sss INC with x.\n        apply subcode_sss_compute with (P := (1+i,mma_incs k)); auto.\n        apply IHk; f_equal; try lia.\n        apply vec_pos_ext; intros p; dest p x.\n    Qed.\n\n  End mma_incs.\n\n  Notation INCSₐ := mma_incs.\n\n  Hint Rewrite mma_incs_length : length_db.\n\n  Section mma_isempty.\n\n    Variable (x : pos n) (p i : nat).\n\n    Definition mma_isempty := DECₐ x (3+i) :: JUMPₐ p x ++ INCₐ x :: nil.\n\n    Notation EMPTYₐ := mma_isempty.\n\n    Fact mma_isempty_length : length EMPTYₐ = 4.\n    Proof. auto. Qed.\n    \n    Fact mma_empty_progress v st : st = (p,v) -> v#>x = 0 -> (i,EMPTYₐ) // (i,v) -+> st.\n    Proof.\n      intros -> H.\n      unfold mma_isempty, mma_jump; simpl app.\n      mma sss DEC zero with x (3+i); rew vec.\n      mma sss INC with x.\n      mma sss DEC S with x p (0); rew vec.\n      mma sss stop; f_equal.\n      apply vec_pos_ext; intros y; dest y x; lia.\n    Qed.\n\n    Fact mma_non_empty_progress v st : st = (4+i,v) -> v#>x <> 0 -> (i,EMPTYₐ) // (i,v) -+> st.\n    Proof.\n      intros -> H.\n      unfold mma_isempty.\n      case_eq (v#>x).\n      + now intros; subst.\n      + clear H; intros u H.\n        mma sss DEC S with x (3+i) u; rew vec.\n        mma sss INC with x; auto.\n        mma sss stop; f_equal.\n        apply vec_pos_ext; intros y; dest y x; lia.\n    Qed.\n\n  End mma_isempty.\n\n  Notation EMPTYₐ := mma_isempty.\n\n  Hint Rewrite mma_isempty_length : length_db.\n\n  Section mma_transfert.\n\n    (* Added the content of src to dst while emptying src *)\n\n    Variables (src dst : pos n) (Hsd : src <> dst) (i : nat).\n\n    Definition mma_transfert := INCₐ dst :: DECₐ src i :: DECₐ dst (3+i) :: nil.\n\n    Fact mma_transfert_length : length mma_transfert = 3.\n    Proof. reflexivity. Qed.\n\n    Let mma_transfert_spec v w k x :    v#>src = k\n                                     -> v#>dst = x\n                                     -> w = v[0/src][(1+k+x)/dst]\n                                     -> (i,mma_transfert) // (i,v) -+> (2+i,w).\n    Proof.\n      unfold mma_transfert.\n      revert v w x.\n      induction k as [ | k IHk ]; intros v w x H1 H2 H3; subst w.\n      + mma sss INC with dst.\n        mma sss DEC zero with src i; rew vec.\n        mma sss stop; f_equal; auto.\n        apply vec_pos_ext; intros z; dest z dst; dest z src.\n      + mma sss INC with dst.\n        mma sss DEC S with src i k; rew vec.\n        apply sss_progress_compute, IHk with (x := 1+x); rew vec.\n        apply vec_pos_ext; intros p.\n        dest p dst; try lia; dest p src.\n    Qed.\n\n    Fact mma_transfert_progress v st : \n           st = (3+i,v[0/src][((v#>src)+(v#>dst))/dst])\n        -> (i,mma_transfert) // (i,v) -+> st.\n    Proof using Hsd.\n      intros ?; subst.\n      apply sss_progress_trans with (2+i, v[0/src][(1+(v#>src)+(v#>dst))/dst]).\n      + apply mma_transfert_spec with (1 := eq_refl) (2 := eq_refl); auto.\n      + unfold mma_transfert.\n        mma sss DEC S with dst (3+i) ((v#>src)+(v#>dst)); rew vec.\n        mma sss stop.\n    Qed.\n\n  End mma_transfert.\n\n  Notation TRANSFERTₐ := mma_transfert.\n\n  Hint Rewrite mma_transfert_length : length_db.\n \n  Section mma_mult_cst.\n\n    (* dst <- k*src+dst *)\n\n    Variable (src dst : pos n) (Hsd : src <> dst) (k i : nat).\n\n    Definition mma_mult_cst :=\n           DECₐ src (3+i) :: JUMPₐ (5+k+i) src \n        ++ INCSₐ dst k ++ JUMPₐ i src. \n\n    Fact mma_mult_cst_length : length mma_mult_cst = 5+k.\n    Proof. unfold mma_mult_cst; rew length; lia. Qed.\n\n    Let mma_mult_cst_spec x v st :\n             v#>src = x\n          -> st = (5+k+i,v[0/src][(x*k+(v#>dst))/dst])\n          -> (i,mma_mult_cst) // (i,v) -+> st.\n    Proof.\n      unfold mma_mult_cst.\n      revert v st; induction x as [ | x IHx ]; intros v st Hv ?; subst.\n      + mma sss DEC zero with src (3+i).\n        apply sss_progress_compute.\n        apply subcode_sss_progress with (P := (1+i,JUMPₐ (5+k+i) src)); auto. \n        apply mma_jump_progress.\n        apply vec_pos_ext; intros y; dest y dst; dest y src; lia.\n      + mma sss DEC S with src (3+i) x.\n        apply sss_compute_trans with (3+k+i,v[x/src][(k+(v#>dst))/dst]).\n        * apply subcode_sss_compute with (P := (3+i,mma_incs dst k)); auto.\n          apply mma_incs_compute; f_equal; try lia.\n          apply vec_pos_ext; intros y; dest y dst; lia.\n        * apply sss_compute_trans with (i,v[x/src][(k+(v#>dst))/dst]).\n          - apply sss_progress_compute.\n            apply subcode_sss_progress with (P := (3+k+i,JUMPₐ i src)); auto.\n            apply mma_jump_progress.\n            apply vec_pos_ext; intros y; dest y dst; dest y src; lia.\n          - apply sss_progress_compute, IHx; rew vec; f_equal.\n            apply vec_pos_ext; intros y; dest y dst; try ring.\n            dest y src.\n    Qed.\n\n    Fact mma_mult_cst_progress v st :\n             st = (5+k+i,v[0/src][(k*(v#>src)+(v#>dst))/dst])\n          -> (i,mma_mult_cst) // (i,v) -+> st.\n    Proof using Hsd.\n      intros ?; subst.\n      apply mma_mult_cst_spec with (1 := eq_refl); do 2 f_equal.\n      ring.\n    Qed.\n\n  End mma_mult_cst.\n\n  Notation MULT_CSTₐ := mma_mult_cst.\n\n  Hint Rewrite mma_mult_cst_length : length_db.\n\n  Section mma_mult_cst_with_zero.\n\n    Variable (x z : pos n) (Hxz : x <> z) (k i : nat).\n\n    Definition mma_mult_cst_with_zero :=\n           MULT_CSTₐ x z k i ++ TRANSFERTₐ z x (5+k+i).\n\n    Fact mma_mult_cst_with_zero_length :length mma_mult_cst_with_zero = 8+k.\n    Proof. unfold mma_mult_cst_with_zero; rew length; lia. Qed.\n\n    (* v#>x is multiplied by k and the PC jumps to the\n       end of this (sub-)program *)\n\n    Fact mma_mult_cst_with_zero_progress v st :\n             v#>z = 0\n          -> st = (8+k+i,v[(k*(v#>x))/x])\n          -> (i,mma_mult_cst_with_zero) // (i,v) -+> st.\n    Proof using Hxz.\n      unfold mma_mult_cst_with_zero.\n      intros H1 H2.\n      apply sss_progress_trans with (st2 := (5+k+i, v[0/x][(k*(v#>x))/z])).\n      + apply subcode_sss_progress with (P := (i,MULT_CSTₐ x z k i)); auto.\n        apply mma_mult_cst_progress; auto.\n        do 2 f_equal; lia.\n      + apply subcode_sss_progress with (P := (5+k+i,TRANSFERTₐ z x (5+k+i))); auto.\n        apply mma_transfert_progress; auto.\n        rewrite H2; f_equal; rew vec.\n        apply vec_pos_ext; intros p.\n        dest p x; dest p z.\n    Qed.\n\n  End mma_mult_cst_with_zero.\n\n  Notation MULT_CST_WZₐ := mma_mult_cst_with_zero.\n\n  Hint Rewrite mma_mult_cst_with_zero_length : length_db.\n\n  Section mma_decs.\n\n    (* \"mma_dec dst p q k\" at i \n\n        removes constant k to dst:\n\n        if dst < k, dst ends up empty and jump to q\n        if k <= dst, dst is decremented by k and jump to p \n\n      *)\n\n    Variable (dst : pos n) (p q : nat).\n\n    Fixpoint mma_decs k i := \n      match k with \n        | 0   => INCₐ dst :: DECₐ dst p :: nil\n        | S k => DECₐ dst (3+i) :: INCₐ dst :: DECₐ dst q :: mma_decs k (3+i)\n      end.\n\n    Fact mma_decs_length k i : length (mma_decs k i) = 2+3*k.\n    Proof.\n      revert i; induction k as [ | ? IHk ]; intros i; simpl; auto.\n      rewrite IHk; lia.\n    Qed.\n\n    Let mma_decs_spec_lt k i v w : \n            v#>dst < k \n         -> w = v[0/dst]\n         -> (i,mma_decs k i) // (i,v) -+> (q,w).\n    Proof.\n      revert i v w; induction k as [ | k IHk ]; intros i v w H1 ?; subst w.\n      + lia.\n      + unfold mma_decs; fold mma_decs.\n        case_eq (v#>dst).\n        * intros H2.\n          mma sss DEC zero with dst (3+i).\n          mma sss INC with dst.\n          mma sss DEC S with dst q (v#>dst); rew vec.\n          mma sss stop; f_equal.\n          apply vec_pos_ext; intros x; dest x dst.\n        * intros d Hd.\n          mma sss DEC S with dst (3+i) d.\n          apply subcode_sss_compute with (P := (3+i,mma_decs k (3+i))); auto.\n          apply sss_progress_compute, IHk; rew vec; try lia.\n    Qed.\n\n    Let mma_decs_spec_le k i v w : \n            k <= v#>dst \n         -> w = v[((v#>dst)-k)/dst]\n         -> (i,mma_decs k i) // (i,v) -+> (p,w).\n    Proof.\n      revert i v w; induction k as [ | k IHk ]; intros i v w H1 ?; subst w.\n      + simpl.\n        mma sss INC with dst.\n        mma sss DEC S with dst p (v#>dst); rew vec.\n        mma sss stop; f_equal.\n        apply vec_pos_ext; intros x; dest x dst; try lia.\n      + unfold mma_decs; fold mma_decs.\n        mma sss DEC S with dst (3+i) ((v#>dst) - 1); try lia.\n        apply subcode_sss_compute with (P := (3+i,mma_decs k (3+i))); auto.\n        apply sss_progress_compute, IHk; rew vec; try lia.\n        apply vec_pos_ext; intros x; dest x dst; lia.\n    Qed.\n\n    Fact mma_decs_lt_progress k i v st :\n             v#>dst < k \n          -> st = (q,v[0/dst])\n          -> (i,mma_decs k i) // (i,v) -+> st.\n    Proof.\n      intros H1 ?; subst st.\n      apply mma_decs_spec_lt; auto.\n    Qed.\n\n    Fact mma_decs_le_progress k i v st :\n             k <= v#>dst \n          -> st = (p,v[((v#>dst)-k)/dst])\n          -> (i,mma_decs k i) // (i,v) -+> st.\n    Proof.\n      intros H1 ?; subst st.\n      apply mma_decs_spec_le; auto.\n    Qed.\n\n  End mma_decs.\n\n  Notation DECSₐ := mma_decs.\n\n  Section mma_decs_copy.\n\n    (* Same as mma_decs except that the quantity\n       removed from dst is transfered into tmp *)\n\n    Variable (dst tmp : pos n) (Hdt : dst <> tmp) (p q : nat).\n\n    Fixpoint mma_decs_copy k i := \n      match k with \n        | 0   => INCₐ dst :: DECₐ dst p :: nil\n        | S k => DECₐ dst (3+i) :: INCₐ dst :: DECₐ dst q :: INCₐ tmp :: mma_decs_copy k (4+i)\n      end.\n\n    Fact mma_decs_copy_length k i : length (mma_decs_copy k i) = 2+4*k.\n    Proof.\n      revert i; induction k as [ | ? IHk ]; intros i; simpl; auto.\n      rewrite IHk; lia.\n    Qed.\n\n    Let mma_decs_copy_spec_lt k i v w : \n            v#>dst < k \n         -> w = v[0/dst][((v#>dst)+(v#>tmp))/tmp]\n         -> (i,mma_decs_copy k i) // (i,v) -+> (q,w).\n    Proof.\n      revert i v w; induction k as [ | k IHk ]; intros i v w H1 ?; subst w.\n      + lia.\n      + unfold mma_decs_copy; fold mma_decs_copy.\n        case_eq (v#>dst).\n        * intros H2.\n          mma sss DEC zero with dst (3+i).\n          mma sss INC with dst.\n          mma sss DEC S with dst q (v#>dst); rew vec.\n          mma sss stop; f_equal.\n          apply vec_pos_ext; intros x; dest x tmp; dest x dst.\n        * intros d Hd.\n          mma sss DEC S with dst (3+i) d.\n          mma sss INC with tmp.\n          apply subcode_sss_compute with (P := (4+i,mma_decs_copy k (4+i))); auto.\n          apply sss_progress_compute; rewrite Nat.add_assoc.\n          apply IHk; rew vec; try lia.\n          apply vec_pos_ext; intros x; dest x tmp; try lia; dest x dst.\n    Qed.\n\n    Let mma_decs_copy_spec_le k i v w : \n            k <= v#>dst \n         -> w = v[((v#>dst)-k)/dst][(k+(v#>tmp))/tmp]\n         -> (i,mma_decs_copy k i) // (i,v) -+> (p,w).\n    Proof.\n      revert i v w; induction k as [ | k IHk ]; intros i v w H1 ?; subst w.\n      + simpl.\n        mma sss INC with dst.\n        mma sss DEC S with dst p (v#>dst); rew vec.\n        mma sss stop; f_equal.\n        apply vec_pos_ext; intros x; dest x dst; try lia; dest x tmp.\n      + unfold mma_decs_copy; fold mma_decs_copy.\n        mma sss DEC S with dst (3+i) ((v#>dst) - 1); try lia.\n        mma sss INC with tmp.\n        apply subcode_sss_compute with (P := (4+i,mma_decs_copy k (4+i))); auto.\n        apply sss_progress_compute, IHk; rew vec; try lia.\n        apply vec_pos_ext; intros x; dest x tmp; try lia; dest x dst; lia.\n    Qed.\n\n    Fact mma_decs_copy_lt_progress k i v st :\n             v#>dst < k \n          -> st = (q,v[0/dst][((v#>dst)+(v#>tmp))/tmp])\n          -> (i,mma_decs_copy k i) // (i,v) -+> st.\n    Proof using Hdt.\n      intros H1 ?; subst st.\n      apply mma_decs_copy_spec_lt; auto.\n    Qed.\n\n    Fact mma_decs_copy_le_progress k i v st :\n             k <= v#>dst \n          -> st = (p,v[((v#>dst)-k)/dst][(k+(v#>tmp))/tmp])\n          -> (i,mma_decs_copy k i) // (i,v) -+> st.\n    Proof using Hdt.\n      intros H1 ?; subst st.\n      apply mma_decs_copy_spec_le; auto.\n    Qed.\n\n  End mma_decs_copy.\n\n  Notation DECS_COPYₐ := mma_decs_copy.\n\n  Hint Rewrite mma_decs_length mma_decs_copy_length : length_db.\n\n  Section mma_mod_cst.\n\n    (* test whether k divides src and transfer of src into dst *)\n\n    Variable (x t : pos n) (Hxt : x <> t) (p q k i : nat).\n\n    Definition mma_mod_cst :=\n            EMPTYₐ x p i ++ DECS_COPYₐ x t i q k (4+i).\n\n    Fact mma_mod_cst_length : length mma_mod_cst = 6+4*k.\n    Proof. unfold mma_mod_cst; rew length; lia. Qed.\n\n    (* This is of no use when k = 0 *)\n\n    Hypothesis (Hk : 0 < k).\n\n    Let mma_mod_cst_spec_0 v :\n           v#>x = 0\n        -> (i,mma_mod_cst) // (i,v) -+> (p,v).\n    Proof.\n      intros H; unfold mma_mod_cst.\n      apply subcode_sss_progress with (P := (i, EMPTYₐ x p i)); auto.\n      apply mma_empty_progress; auto.\n    Qed.\n\n    Let mma_mod_cst_spec_1 a b v w :\n           v#>x = a*k+b\n        -> w = v[b/x][(a*k+(v#>t))/t]\n        -> (i,mma_mod_cst) // (i,v) ->> (i,w).\n    Proof.\n      revert v w; induction a as [ | a IHa ]; intros v w H1 H2; subst w.\n      + mma sss stop; f_equal.\n        simpl in H1; rewrite <- H1; simpl; rew vec.\n      + unfold mma_mod_cst.\n        apply sss_compute_trans with (4+i,v).\n        * apply sss_progress_compute,\n                subcode_sss_progress with (P := (i, EMPTYₐ x p i)); auto.\n          apply mma_non_empty_progress; auto; lia.\n        * apply sss_compute_trans with (i, v[(a*k+b)/x][(k+(v#>t))/t]).\n          - apply subcode_sss_compute with (P := (4+i,mma_decs_copy x t i q k (4+i))); auto.\n            apply sss_progress_compute, mma_decs_copy_le_progress; auto; rew vec.\n            { simpl; generalize (a*k); intro; lia. }\n            do 3 f_equal; rewrite H1; simpl mult; generalize (a*k); intro; lia.\n          - apply IHa; rew vec.\n            apply vec_pos_ext; intros y; dest y t; try ring; dest y x.\n    Qed.\n\n    Let mma_mod_cst_spec_2 v w :\n           0 < v#>x < k\n        -> w = v[0/x][((v#>x)+(v#>t))/t]\n        -> (i,mma_mod_cst) // (i,v) -+> (q,w).\n    Proof.\n      intros H ?; subst; unfold mma_mod_cst.\n      apply sss_progress_trans with (4+i,v).\n      + apply subcode_sss_progress with (P := (i, EMPTYₐ x p i)); auto.\n        apply mma_non_empty_progress; auto; lia.\n      + apply subcode_sss_progress with (P := (4+i, DECS_COPYₐ x t i q k (4+i))); auto.\n        apply mma_decs_copy_lt_progress; auto; lia.\n    Qed.\n \n    Fact mma_mod_cst_divides_progress v a st :\n            v#>x = a*k\n         -> st = (p,v[0/x][((v#>x)+(v#>t))/t])\n         -> (i,mma_mod_cst) // (i,v) -+> st.\n    Proof using Hxt Hk.\n      intros H1 ?; subst st.\n      apply sss_compute_progress_trans with (i,v[0/x][((v#>x)+(v#>t))/t]).\n      + apply mma_mod_cst_spec_1 with (a := a) (b := 0); try lia.\n        rewrite <- H1; auto.\n      + apply mma_mod_cst_spec_0; rew vec.\n    Qed.\n\n    Fact mma_mod_cst_not_divides_progress v a b st :\n            v#>x = a*k+b\n         -> 0 < b < k\n         -> st = (q,v[0/x][((v#>x)+(v#>t))/t])\n         -> (i,mma_mod_cst) // (i,v) -+> st.\n    Proof using Hxt Hk.\n      intros H1 H2 ?; subst st.\n      apply sss_compute_progress_trans with (i,v[b/x][(a*k+(v#>t))/t]).\n      + apply mma_mod_cst_spec_1 with (a := a) (b := b); try lia; auto.\n      + apply mma_mod_cst_spec_2; rew vec.\n        apply vec_pos_ext; intros y; dest y t; try lia; dest y x.\n    Qed.\n  \n  End mma_mod_cst.\n\n  Notation MOD_CSTₐ := mma_mod_cst.\n\n  Hint Rewrite mma_decs_length mma_mod_cst_length : length_db.\n\n  Section mma_div_cst.\n\n    (* Division by a constant *)\n\n    Variable (s d : pos n) (Hsd : s <> d) (k i : nat).\n\n    Let p := (2+3*k+i).\n    Let q := (5+3*k+i).\n\n    Definition mma_div_cst := \n         DECSₐ s p q k i ++ INCₐ d :: JUMPₐ i s.\n\n    Fact mma_div_cst_length : length mma_div_cst = 5+3*k.\n    Proof. unfold mma_div_cst; rew length; lia. Qed.\n\n    Hypothesis (Hk : 0 < k).\n\n    Let mma_div_cst_spec a v w :\n           v#>s = a*k\n        -> w = v[0/s][(a+(v#>d))/d]\n        -> (i, mma_div_cst) // (i,v) -+> (q,w).\n    Proof.\n      unfold mma_div_cst; revert v w; induction a as [ | a IHa ]; intros v w H1 ?; subst w.\n      + apply subcode_sss_progress with (P := (i,mma_decs s p q k i)); auto.\n        apply mma_decs_lt_progress; try lia.\n        f_equal; simpl.\n        apply vec_pos_ext; intros y; dest y d.\n      + apply sss_progress_trans with (p,v[(a*k)/s]).\n        * apply subcode_sss_progress with (P := (i,mma_decs s p q k i)); auto.\n          apply mma_decs_le_progress.\n          - rewrite H1; simpl; generalize (a*k); intro; lia.\n          - f_equal.\n            apply vec_pos_ext; intros y; dest y d; dest y s.\n            rewrite H1; simpl; generalize (a*k); intro; lia.\n        * unfold p.\n          mma sss INC with d.\n          apply sss_compute_trans with (i,v[(a*k)/s][(S (v[(a*k)/s]#>d))/d]).\n          - apply sss_progress_compute,\n                  subcode_sss_progress with (P := (3+3*k+i, JUMPₐ i s)); auto.\n            apply mma_jump_progress; auto.\n          - apply sss_progress_compute, IHa; rew vec.\n            apply vec_pos_ext; intros y; dest y d; try lia; dest y s.\n    Qed.\n\n    Fact mma_div_cst_progress a v st :\n            v#>s = a*k\n         -> st = (q,v[0/s][(a+(v#>d))/d])\n         -> (i, mma_div_cst) // (i,v) -+> st.\n    Proof using Hsd Hk.\n      intros H1 H2; subst st; apply mma_div_cst_spec with (1 := H1); auto.\n    Qed.\n\n  End mma_div_cst.\n\n  Notation DIV_CSTₐ := mma_div_cst.\n\n  Hint Rewrite mma_div_cst_length : length_db.\n\n  Section mma_div_branch.\n\n    Variable (x z : pos n) (Hxz : x <> z) (k i j : nat).\n\n    Let p :=  6+4*k+i.\n    Let q := 13+7*k+i.\n\n    (* The algorithm: \n         - test the divisibility of x by k while\n           x is transfered to z\n         - if divisible jump to p\n           if not jump to q\n         - at p: divides z by k, result into x\n                 jump to j\n         - at q: transfer z to x *)\n\n    Definition mma_div_branch :=\n                   MOD_CSTₐ x z p q k i\n      (* p: *)  ++ DIV_CSTₐ z x k p ++ JUMPₐ j z\n      (* q: *)  ++ TRANSFERTₐ z x q.\n\n    Fact mma_div_branch_length : length mma_div_branch = 16+7*k.\n    Proof. unfold mma_div_branch; rew length; lia. Qed.\n\n    (* When k divides v#>x then it gets divided (by k)\n       and the PC jumps to j *)\n\n    Fact mma_div_branch_0_progress a v st :\n            v#>z = 0\n         -> 0 < k\n         -> v#>x = a*k\n         -> st = (j,v[a/x])\n         -> (i, mma_div_branch) // (i,v) -+> st.\n    Proof using Hxz.\n      intros H1 H2 H3 ->; unfold mma_div_branch.\n      apply sss_progress_trans with (st2 := (p,v[0/x][(a*k)/z])).\n      1:{ apply subcode_sss_progress with (P := (i,MOD_CSTₐ x z p q k i)); auto.\n          apply mma_mod_cst_divides_progress with a; auto.\n          do 2 f_equal; lia. }\n      apply sss_progress_trans with (st2 := (11+7*k+i,v[a/x])).\n      1:{ apply subcode_sss_progress with (P := (p,DIV_CSTₐ z x k p)); auto.\n          apply mma_div_cst_progress with a; auto; rew vec.\n          unfold p.\n          f_equal; try lia.\n          apply vec_pos_ext; intros y.\n          dest y x; dest y z. }\n      1:{ apply subcode_sss_progress with (P := (11+7*k+i,JUMPₐ j z)); auto.\n          apply mma_jump_progress; auto. }\n    Qed.\n\n    (* When k does not divide v#>x then registers are globally \n       unmodified and the PC jumps to the end of this (sub-)program *)\n\n    Fact mma_div_branch_1_progress v st :\n            v#>z = 0\n         -> 0 < k\n         -> ~ divides k (v#>x)\n         -> st = (16+7*k+i,v)\n         -> (i, mma_div_branch) // (i,v) -+> st.\n    Proof using Hxz.\n      intros H1 H2 H3 ->; unfold mma_div_branch.\n      destruct (div_full (v#>x) k) as (a & r & H5 & H6).\n      assert (0 < r < k) as H7.\n      1:{ split; destruct r; try lia.\n          destruct H3; exists a; lia. }\n      apply sss_progress_trans with (st2 := (q,v[0/x][(v#>x)/z])).\n      1:{ apply subcode_sss_progress with (P := (i,MOD_CSTₐ x z p q k i)); auto.\n          apply mma_mod_cst_not_divides_progress with (3 := H5); auto.\n          do 2 f_equal; lia. }\n      1:{ apply subcode_sss_progress with (P := (q,TRANSFERTₐ z x q)); auto.\n          apply mma_transfert_progress; auto.\n          f_equal; rew vec.\n          apply vec_pos_ext; intros y.\n          dest y x; dest y z. }\n    Qed.\n\n  End mma_div_branch.\n\n  Section mma_loop.\n\n    Variables (x : pos n) (i : nat).\n\n    Definition mma_loop := JUMPₐ i x.\n\n    Fact mma_loop_loop v : (i,mma_loop) // (i,v) -+> (i,v).\n    Proof. apply mma_jump_progress; auto. Qed.\n\n    Theorem mma_loop_spec v : ~ (i,mma_loop) // (i,v) ↓.\n    Proof.\n      apply sss_progress_non_termination.\n      + apply mma_sss_fun.\n      + apply mma_loop_loop.\n    Qed.\n\n  End mma_loop.\n\n  Notation LOOPₐ := mma_loop.\n\nEnd Minsky_Machine_alt_utils.\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/MMA/mma_utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624557, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6687280899253123}}
{"text": "(**\nThis file is part of the Coq.Interval library for proving bounds of\nreal-valued expressions in Coq: http://coq-interval.gforge.inria.fr/\n\nCopyright (C) 2007-2016, Inria\n\nThis library is governed by the CeCILL-C license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the library under the terms of the CeCILL-C\nlicense as circulated by CEA, CNRS and Inria at the following URL:\nhttp://www.cecill.info/\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided\nonly with a limited warranty and the library's author, the holder of\nthe economic rights, and the successive licensors have only limited\nliability. See the COPYING file for more details.\n*)\n\nFrom Coq Require Import Reals Psatz.\n\nRequire Import Xreal.\nRequire Import Basic.\nRequire Import Sig.\nRequire Import Interval.\nRequire Import Float.\nRequire Import Transcend.\n\nModule FloatIntervalFull (F : FloatOps with Definition sensible_format := true) <: IntervalOps.\n\nModule T := TranscendentalFloatFast F.\nInclude FloatInterval F.\n\nDefinition c3 := F.fromZ 3.\nDefinition c4 := F.fromZ 4.\nDefinition c8 := F.fromZ 8.\n\nDefinition pi prec :=\n  mul2 prec (mul2 prec (T.pi4 prec)).\n\nLemma pi_correct :\n  forall prec, contains (convert (pi prec)) (Xreal PI).\nProof.\nintros prec.\nunfold pi.\nreplace (Xreal PI) with (Xmul (Xreal (PI/4)) (Xreal (Raux.bpow radix2 2))).\nchange (Xreal (Raux.bpow _ _)) with (Xreal 2 * Xreal 2)%XR.\nrewrite <-Xmul_assoc.\ndo 2 apply mul2_correct.\napply T.pi4_correct.\nchange (Raux.bpow _ _) with 4%R.\nsimpl.\napply f_equal.\nfield.\nQed.\n\n(* accurate only for |xi| <= 2 * pi *)\nDefinition cos prec xi :=\n  match abs xi with\n  | Ibnd xl xu =>\n    if F'.le' xu xl then T.cos_fast prec xl else\n    let pi4 := T.pi4 prec in\n    if F'.le' xu (F.mul_DN prec (lower pi4) c4) then\n      bnd (lower (T.cos_fast prec xu)) (upper (T.cos_fast prec xl))\n    else\n      if F'.le' xu (F.mul_DN prec (lower pi4) c8) then\n        if F'.le' (F.mul_UP prec (upper pi4) c4) xl then\n          bnd (lower (T.cos_fast prec xl)) (upper (T.cos_fast prec xu))\n        else\n          bnd cm1 (F.max (upper (T.cos_fast prec xl)) (upper (T.cos_fast prec xu)))\n      else\n        let d := F.sub_UP prec xu xl in\n        if F'.le' d c3 then\n          let m := F.midpoint xl xu in\n          let d := F.max (F.sub_UP prec xu m) (F.sub_UP prec m xl) in\n          let c := T.cos_fast prec m in\n          meet (bnd cm1 c1) (add prec c (bnd (F.neg d) d))\n        else bnd cm1 c1\n  | Inan => Inan\n  end.\n\nLemma cos_correct :\n  forall prec, extension Xcos (cos prec).\nProof.\nintros prec xi x Hx.\nunfold cos.\ngeneralize (abs_correct xi x Hx) (abs_ge_0' xi).\ndestruct (abs xi) as [|xl xu]; [easy|].\ndestruct x as [|x].\n{ now simpl; case (_ && _)%bool. }\nunfold convert at 1.\ncase_eq (F.valid_lb xl); [|intros _ [H0 H1]; lra].\ncase_eq (F.valid_ub xu); [|intros _ _ [H0 H1]; lra].\nintros Vxu Vxl [Hxl Hxu].\nintros Hal.\nsimpl in Hal.\nassert (H : not_empty (convert xi)).\n{ now exists x. }\nspecialize (Hal H); clear H.\nunfold Xbind.\nreplace (Rtrigo_def.cos x) with (Rtrigo_def.cos (Rabs x)).\n2: now unfold Rabs ; case Rcase_abs ; intros _ ; try easy ; apply cos_neg.\nclear Hx.\nassert (Hcxl := T.cos_fast_correct prec xl).\nassert (Hcxu := T.cos_fast_correct prec xu).\ncase_eq (F'.le' xu xl).\n{ intros Hl.\n  apply F'.le'_correct in Hl.\n  destruct (F.toX xu) as [|xur] ; [easy|].\n  destruct (F.toX xl) as [|xlr] ; [easy|].\n  replace (Rabs x) with xlr.\n  { exact Hcxl. }\n  apply Rle_antisym.\n  { easy. }\n  now apply Rle_trans with (2 := Hl). }\nintros _.\nunfold cm1, c1, c3.\nassert (Hlb'_cos : F.valid_lb (lower (T.cos_fast prec xl)) = true).\n{ generalize Hcxl.\n  unfold T.I.convert.\n  case (T.cos_fast prec xl).\n  { now simpl; rewrite F'.valid_lb_nan. }\n  simpl.\n  intros l u.\n  case (F.valid_lb l); [easy|].\n  now simpl; case F.toX; [|intros r [H0 H1]; lra]. }\nassert (Hub'_cos : F.valid_ub (upper (T.cos_fast prec xu)) = true).\n{ generalize Hcxu.\n  unfold T.I.convert.\n  case (T.cos_fast prec xu).\n  { now simpl; rewrite F'.valid_ub_nan. }\n  simpl.\n  intros l u.\n  rewrite Bool.andb_comm.\n  case (F.valid_ub u); [easy|].\n  now simpl; case F.toX; [|intros r [H0 H1]; lra]. }\nassert (Hub_cos : F.valid_ub (upper (T.cos_fast prec xl)) = true).\n{ generalize Hcxl.\n  unfold T.I.convert.\n  case (T.cos_fast prec xl).\n  { now simpl; rewrite F'.valid_ub_nan. }\n  simpl.\n  intros l u; rewrite Bool.andb_comm.\n  case (F.valid_ub u); [easy|].\n  now simpl; case F.toX; [|intros r [H0 H1]; lra]. }\nassert (Hlb_cos : F.valid_lb (lower (T.cos_fast prec xu)) = true).\n{ generalize Hcxu.\n  unfold T.I.convert.\n  case (T.cos_fast prec xu).\n  { now simpl; rewrite F'.valid_lb_nan. }\n  simpl.\n  intros l u.\n  now case (F.valid_lb l); [|simpl; case Xcos; [|intros r [H0 H1]; lra]]. }\ncase_eq (F'.le' xu (F.mul_DN prec (lower (T.pi4 prec)) c4)).\n{ intros Hu.\n  apply F'.le'_correct in Hu.\n  destruct (F.toX xu) as [|xur] ; try easy.\n  assert (Hxur: (xur <= PI)%R).\n  { revert Hu.\n    elim (F.mul_DN_correct prec (lower (T.pi4 prec)) (F.fromZ 4)).\n    2:{ unfold F.is_non_neg_real, F.is_non_pos_real, F.is_non_neg, F.is_non_pos.\n      rewrite (F'.valid_ub_real (F.fromZ 4));\n      [|rewrite F.real_correct..];\n      (rewrite F.fromZ_correct; [|lia]); [|easy].\n      generalize (T.pi4_correct prec).\n      unfold T.I.convert.\n      case T.pi4.\n      { simpl; intros _; do 3 right; rewrite F'.valid_lb_nan, F'.nan_correct.\n        repeat split; lra. }\n      intros l u; simpl.\n      rewrite F.valid_lb_correct.\n      case F.classify; [..|intros [H0 H1]; lra]; intros _;\n      (case F.toX; [now do 3 right; repeat split; lra|]; intro rl);\n      (case (Rle_or_lt 0 rl); intro Hrl;\n        [now left; repeat split; lra|do 3 right; repeat split; lra]). }\n    intros Vmdn.\n    unfold le_lower, le_upper.\n    unfold c4.\n    case F.toX; [easy|]; intro Rmdn; simpl.\n    rewrite F.fromZ_correct; [|lia].\n    generalize (T.pi4_correct prec).\n    destruct (T.pi4 prec) as [|pi4l pi4u] ; simpl.\n    { now rewrite F'.nan_correct. }\n    case (_ && _)%bool; [|intros [H0 H1]; lra].\n    case F.toX; [easy|]; intro pi4r.\n    simpl.\n    intros [H _] Hu.\n    apply Ropp_le_cancel in Hu.\n    intro H'; apply (Rle_trans _ _ _ H'); clear H'.\n    apply Rle_trans with (1 := Hu).\n    lra. }\n  clear Hu.\n  unfold convert; simpl.\n  rewrite Hlb_cos; simpl.\n  rewrite Hub_cos; simpl.\n  split.\n  { destruct (T.cos_fast prec xu) as [|cu cu'] ; simpl.\n    { now rewrite F'.nan_correct. }\n    generalize Hcxu; unfold T.I.convert;\n      case (_ && _)%bool; [|intros [H0 H1]; lra].\n    intros [Hcu _].\n    destruct (F.toX cu) as [|cur] ; [easy|].\n    apply Rle_trans with (1 := Hcu).\n    apply cos_decr_1 with (4 := Hxur).\n    { apply Rabs_pos. }\n    { now apply Rle_trans with xur. }\n    { revert Hxu; apply Rle_trans, Rabs_pos. }\n    exact Hxu. }\n  generalize (T.cos_fast_correct prec xl).\n  unfold T.I.convert.\n  case_eq (T.cos_fast prec xl); [now simpl; rewrite F'.nan_correct|].\n  intros cl' cl Hcl.\n  generalize Hub_cos; rewrite Hcl; simpl=> ->.\n  generalize Hlb'_cos; rewrite Hcl; simpl=> ->; simpl.\n  destruct (F.toX xl) as [|xlr] ; [easy|].\n  intros [_ Hl].\n  destruct (F.toX cl) as [|clr] ; [easy|].\n  apply Rle_trans with (2 := Hl).\n  apply cos_decr_1 with (1 := Hal).\n  { apply Rle_trans with (2 := Hxur).\n    now apply Rle_trans with (Rabs x). }\n  { apply Rabs_pos. }\n  { now apply Rle_trans with xur. }\n  apply Hxl. }\nintros _.\ncase_eq (F'.le' xu (F.mul_DN prec (lower (T.pi4 prec)) c8)).\n{ intros Hu.\n  apply F'.le'_correct in Hu.\n  destruct (F.toX xu) as [|xur] ; [easy|].\n  assert (Hxur: (xur <= 2 * PI)%R).\n  { revert Hu.\n    elim (F.mul_DN_correct prec (lower (T.pi4 prec)) (F.fromZ 8)).\n    2:{ unfold F.is_non_neg_real, F.is_non_pos_real, F.is_non_neg, F.is_non_pos.\n      rewrite (F'.valid_ub_real (F.fromZ 8));\n      [|rewrite F.real_correct..];\n      (rewrite F.fromZ_correct; [|lia]); [|easy..].\n      generalize (T.pi4_correct prec).\n      unfold T.I.convert.\n      case T.pi4.\n      { simpl; intros _; do 3 right; rewrite F'.valid_lb_nan, F'.nan_correct.\n        repeat split; lra. }\n      intros l u; simpl.\n      rewrite F.valid_lb_correct.\n      case F.classify; [..|intros [H0 H1]; lra]; intros _;\n      (case F.toX; [now do 3 right; repeat split; lra|]; intro rl);\n      (case (Rle_or_lt 0 rl); intro Hrl;\n        [now left; repeat split; lra|do 3 right; repeat split; lra]). }\n    intros Vmdn.\n    unfold le_lower, le_upper.\n    unfold c8.\n    case F.toX; [easy|]; intro rmdn; simpl.\n    rewrite F.fromZ_correct; [|lia].\n    generalize (T.pi4_correct prec).\n    unfold T.I.convert.\n    case T.pi4; [now simpl; rewrite F'.nan_correct|]; intros l u.\n    case (_ && _)%bool; [|intros [H0 H1]; lra].\n    simpl.\n    case F.toX; simpl; [easy|].\n    intros rlpi4 [Hrlpi4 _].\n    lra. }\n  clear Hu.\n  case_eq (F'.le' (F.mul_UP prec (upper (T.pi4 prec)) c4) xl).\n  { intros Hl.\n    apply F'.le'_correct in Hl.\n    destruct (F.toX xl) as [|xlr].\n    { now destruct (F.toX (F.mul_UP prec (upper (T.pi4 prec)) c4)). }\n    assert (Hxlr: (PI <= xlr)%R).\n    { revert Hl.\n      elim (F.mul_UP_correct prec (upper (T.pi4 prec)) (F.fromZ 4)).\n      2:{ unfold F.is_non_neg, F.is_non_pos, F.is_non_pos_real, F.is_non_neg_real.\n        rewrite (F'.valid_ub_real (F.fromZ 4));\n        [|rewrite F.real_correct..];\n        (rewrite F.fromZ_correct; [|lia]); [|easy..].\n        generalize (T.pi4_correct prec).\n        unfold T.I.convert.\n        case T.pi4.\n        { simpl; intros _; left; rewrite F'.valid_ub_nan, F'.nan_correct.\n          repeat split; lra. }\n        intros l u; simpl.\n        rewrite F.valid_ub_correct, Bool.andb_comm.\n        case F.classify; [..|intros [H0 H1]; lra|]; intros _;\n          (case F.toX; [now left; repeat split; lra|]; intro ru);\n          (case (Rle_or_lt 0 ru); intro Hru;\n           [now left; repeat split; lra|do 2 right; left; lra]). }\n      intros Vmup.\n      rewrite F.fromZ_correct; [|lia].\n      unfold le_upper.\n      unfold c4.\n      case F.toX; [easy|]; intro rmup.\n      generalize (T.pi4_correct prec).\n      unfold T.I.convert.\n      case T.pi4; [now simpl; rewrite F'.nan_correct|]; intros l u.\n      case (_ && _)%bool; [|intros [H0 H1]; lra].\n      simpl.\n      case (F.toX u); simpl; [easy|].\n      intros rupi4 [_ Hrupi4].\n      lra. }\n    clear Hl.\n    simpl.\n    rewrite Hlb'_cos, Hub'_cos.\n    split.\n    { destruct (T.cos_fast prec xl) as [|cl cl'] ; simpl.\n      { now rewrite F'.nan_correct. }\n      revert Hcxl.\n      unfold T.I.convert.\n      case (_ && _)%bool; [|intros [H0 H1]; lra].\n      intros [Hcl _].\n      destruct (F.toX cl) as [|clr] ; [easy|].\n      apply Rle_trans with (1 := Hcl).\n      apply cos_incr_1 with (1 := Hxlr) (5 := Hxl).\n      { apply Rle_trans with (2 := Hxur).\n        apply Rle_trans with (1 := Hxl) (2 := Hxu). }\n      { apply Rle_trans with (1 := Hxlr) (2 := Hxl). }\n      apply Rle_trans with (1 := Hxu) (2 := Hxur). }\n    destruct (T.cos_fast prec xu) as [|cu' cu] ; simpl.\n    { now rewrite F'.nan_correct. }\n    revert Hcxu.\n    unfold T.I.convert.\n    case (_ && _)%bool; [|intros [H0 H1]; lra].\n    intros [_ Hcu].\n    destruct (F.toX cu) as [|cur] ; [easy|].\n    apply Rle_trans with (2 := Hcu).\n    apply cos_incr_1 with (4 := Hxur) (5 := Hxu).\n    { apply Rle_trans with (1 := Hxlr) (2 := Hxl). }\n    { apply Rle_trans with (1 := Hxu) (2 := Hxur). }\n    apply Rle_trans with (1 := Hxlr).\n    apply Rle_trans with (1 := Hxl) (2 := Hxu). }\n  intros _.\n  unfold convert.\n  simpl; rewrite F'.valid_lb_real.\n  2: now rewrite F.real_correct, F.fromZ_correct; [..|lia].\n  generalize (F'.max_valid_ub _ _ Hub_cos Hub'_cos).\n  intros [Vmax Hmax].\n  rewrite Vmax, Hmax.\n  split.\n  { rewrite F.fromZ_correct; [|lia].\n    apply COS_bound. }\n  destruct (T.cos_fast prec xl) as [|cl' cl] ; simpl.\n  { now rewrite F'.nan_correct. }\n  revert Hcxl.\n  unfold T.I.convert; simpl.\n  simpl in Hlb'_cos.\n  rewrite Hlb'_cos.\n  simpl in Hub_cos.\n  rewrite Hub_cos.\n  simpl.\n  destruct (F.toX xl) as [|xlr] ; [easy|].\n  intros [_ Hcl].\n  destruct (F.toX cl) as [|clr] ; [easy|].\n  destruct (T.cos_fast prec xu) as [|cu' cu] ; simpl.\n  { now rewrite F'.nan_correct. }\n  revert Hcxu.\n  unfold T.I.convert.\n  simpl in Hub'_cos.\n  rewrite Hub'_cos.\n  simpl in Hlb_cos.\n  rewrite Hlb_cos.\n  simpl.\n  intros [_ Hcu].\n  destruct (F.toX cu) as [|cur] ; [easy|].\n  destruct (Rle_dec (Rabs x) PI) as [Hx|Hx].\n  { apply Rle_trans with (2 := Rmax_l _ _).\n    apply Rle_trans with (2 := Hcl).\n    apply cos_decr_1 with (1 := Hal) (3 := Rabs_pos _) (4 := Hx) (5 := Hxl).\n    apply Rle_trans with (1 := Hxl) (2 := Hx). }\n  apply Rle_trans with (2 := Rmax_r _ _).\n  apply Rle_trans with (2 := Hcu).\n  apply Rnot_le_lt, Rlt_le in Hx.\n  apply cos_incr_1 with (1 := Hx) (4 := Hxur) (5 := Hxu).\n  { apply Rle_trans with (1 := Hxu) (2 := Hxur). }\n  apply Rle_trans with (1 := Hx) (2 := Hxu). }\nintros _.\ncase_eq (F'.le' (F.sub_UP prec xu xl) (F.fromZ 3)).\n{ intros Hd.\n  apply F'.le'_correct in Hd.\n  revert Hd.\n  elim (F.sub_UP_correct prec xu xl); [|easy..].\n  intros Vsup.\n  unfold le_upper.\n  case F.toX; [easy|]; intro rsup.\n  rewrite F.fromZ_correct; [|lia].\n  case_eq (F.toX xu) ; [easy|] ; intros xur Hur.\n  case_eq (F.toX xl) ; [easy|] ; intros xlr Hlr.\n  rewrite Hur in Hxu.\n  rewrite Hlr in Hxl.\n  intros Hsup Hrsup3.\n  simpl in Hsup.\n  apply meet_correct.\n  { unfold convert, bnd.\n    rewrite F'.valid_lb_real;\n      [|now rewrite F.real_correct, F.fromZ_correct; [..|lia]].\n    rewrite F'.valid_ub_real;\n      [|now rewrite F.real_correct, F.fromZ_correct; [..|lia]].\n    rewrite F.fromZ_correct; [|lia].\n    rewrite F.fromZ_correct; [|lia].\n    apply COS_bound. }\n  elim (F.midpoint_correct xl xu);\n    [|easy|now rewrite F.real_correct, ?Hlr, ?Hur..\n     |now unfold F.toR; rewrite Hlr, Hur; apply (Rle_trans _ _ _ Hxl)].\n  set (m := F.midpoint xl xu).\n  intros Rm [Hlm Hum].\n  replace (Xreal (Rtrigo_def.cos (Rabs x)))\n      with (Xadd (Xcos (Xreal (F.toR m))) (Xreal (Rtrigo_def.cos (Rabs x) - Rtrigo_def.cos (F.toR m))))\n      by (apply (f_equal Xreal) ; ring).\n  apply add_correct.\n  { generalize (T.cos_fast_correct prec m).\n    now rewrite (F'.real_correct _ Rm). }\n  simpl.\n  rewrite F'.valid_lb_neg.\n  rewrite F'.neg_correct.\n  elim (F.sub_UP_correct prec xu m);\n    [|easy|now generalize (F.classify_correct m); rewrite Rm, F.valid_lb_correct;\n           case F.classify].\n  intros Vsxum Hsxum.\n  elim (F.sub_UP_correct prec m xl);\n    [|now generalize (F.classify_correct m); rewrite Rm, F.valid_ub_correct;\n      case F.classify|easy].\n  intros Vsmxl Hsmxl.\n  elim (F'.max_valid_ub _ _ Vsxum Vsmxl).\n  intros Vm Hm.\n  rewrite Vm, Hm.\n  revert Hsxum Hsmxl.\n  rewrite Hlr, Hur, (F'.real_correct _ Rm).\n  unfold le_upper.\n  case F.toX; [easy|]; simpl.\n  intros rsxum Hrsxum.\n  case F.toX; [easy|]; simpl.\n  intros rsmxl Hrsmxl.\n  apply Raux.Rabs_le_inv.\n  destruct (MVT_abs Rtrigo_def.cos (fun t => Ropp (sin t)) (F.toR m) (Rabs x)) as [v [-> _]].\n  { intros c _.\n    apply derivable_pt_lim_cos. }\n  apply Rle_trans with (1 * Rabs (Rabs x - (F.toR m)))%R.\n  { apply Rmult_le_compat_r.\n    apply Rabs_pos.\n    rewrite Rabs_Ropp.\n    apply Rabs_le, SIN_bound. }\n  rewrite Rmult_1_l.\n  case (Rle_lt_dec (Rabs x) (F.toR m)); intro Hxm.\n  { refine (Rle_trans _ _ _ _ (Rmax_r _ _)).\n    rewrite Rabs_minus_sym, Rabs_pos_eq; [|lra].\n    apply (Rle_trans _ ((F.toR m) - xlr)); lra. }\n  refine (Rle_trans _ _ _ _ (Rmax_l _ _)).\n  rewrite Rabs_pos_eq; [|lra].\n  apply (Rle_trans _ (xur - (F.toR m))); lra. }\nintros _.\nunfold convert, bnd.\nrewrite F'.valid_lb_real;\n  [|now rewrite F.real_correct, F.fromZ_correct; [..|lia]].\nrewrite F'.valid_ub_real;\n  [|now rewrite F.real_correct, F.fromZ_correct; [..|lia]].\nrewrite F.fromZ_correct; [|lia].\nrewrite F.fromZ_correct; [|lia].\napply COS_bound.\nQed.\n\n(* accurate only for |xi| <= 5/2*pi *)\nDefinition sin prec xi :=\n  match xi with\n  | Ibnd xl xu =>\n    if F'.le' xu xl then T.sin_fast prec xl else\n    let pi4 := T.pi4 prec in\n    let pi2 := F.mul_DN prec (lower pi4) c2 in\n    match F'.le' (F.neg pi2) xl, F'.le' xu pi2 with\n    | true, true =>\n      bnd (lower (T.sin_fast prec xl)) (upper (T.sin_fast prec xu))\n    | true, false =>\n      cos prec (sub prec (mul2 prec pi4) xi)\n    | _, _ =>\n      neg (cos prec (add prec xi (mul2 prec pi4)))\n    end\n  | Inan => Inan\n  end.\n\nTheorem sin_correct :\n  forall prec, extension Xsin (sin prec).\nProof.\nintros prec [|xl xu]; [easy|].\nintros [|x].\n{ now simpl; case (_ && _)%bool. }\nintro Hx; generalize Hx.\nunfold convert at 1.\ncase_eq (F.valid_lb xl); [|intros _ [H0 H1]; lra].\ncase_eq (F.valid_ub xu); [|intros _ _ [H0 H1]; lra].\nintros Vxu Vxl [Hxl Hxu].\nunfold sin.\ncase_eq (F'.le' xu xl).\n{ intros Hl.\n  apply F'.le'_correct in Hl.\n  assert (Hsxl := T.sin_fast_correct prec xl).\n  destruct (F.toX xu) as [|xur] ; try easy.\n  destruct (F.toX xl) as [|xlr] ; try easy.\n  replace x with xlr.\n  { exact Hsxl. }\n  apply Rle_antisym with (1 := Hxl).\n  now apply Rle_trans with (2 := Hl). }\nintros _.\nset (pi2 := F.mul_DN prec (lower (T.pi4 prec)) c2).\ncase_eq (F'.le' (F.neg pi2) xl).\n{ intros Hpl.\n  generalize (F'.le'_correct _ _ Hpl).\n  xreal_tac xl.\n  { now case (F.toX (F.neg pi2)). }\n  clear Hpl. intros Hpl.\n  case_eq (F'.le' xu pi2).\n  { intros Hpu.\n    generalize (F'.le'_correct _ _ Hpu).\n    xreal_tac xu. easy.\n    xreal_tac pi2. easy.\n    clear Hpu. intros Hpu.\n    revert Hpl.\n    rewrite F'.neg_correct, X1.\n    simpl.\n    intros Hpl.\n    elim (F.mul_DN_correct prec (lower (T.pi4 prec)) c2).\n    2: { unfold F.is_non_neg_real, F.is_non_pos_real, F.is_non_neg, F.is_non_pos.\n         unfold c2.\n         rewrite (F'.valid_ub_real (F.fromZ 2)); [|rewrite F.real_correct];\n         (rewrite F.fromZ_correct; [|lia]); [|easy].\n      generalize (T.pi4_correct prec).\n      unfold T.I.convert.\n      case T.pi4.\n      { intros _; do 3 right; simpl.\n        rewrite F'.valid_lb_nan, F'.nan_correct; repeat split; lra. }\n      intros pl pu; simpl.\n      case (F.valid_lb pl); [|intros [H0 H1]; lra]; intros _.\n      case F.toX; [do 3 right; repeat split; lra|].\n      intro r'.\n      case (Rle_or_lt 0 r'); intro Hr'; [left; split; lra|].\n      do 3 right; repeat split; lra. }\n    fold pi2.\n    intros Vpi2.\n    unfold le_lower, le_upper.\n    unfold c2.\n    rewrite X1, F.fromZ_correct; [|lia].\n    simpl.\n    generalize (T.pi4_correct prec).\n    unfold T.I.convert.\n    case T.pi4; [now simpl; rewrite F'.nan_correct|].\n    intros pl pu.\n    case (_ && _)%bool; [|intros [H0 H1]; lra].\n    simpl.\n    case F.toX; [easy|].\n    intros rpl [Hrpl _].\n    simpl.\n    intro Hrpl'.\n    assert (Hpl' : (-(PI/2) <= r)%R) by lra.\n    assert (Hpu' : (r0 <= PI/2)%R) by lra.\n    cut (match F.toX (upper (T.sin_fast prec xu)) with\n         | Xnan => True\n         | Xreal r3 => (Rtrigo_def.sin x <= r3)%R\n         end).\n    { cut (match F.toX (lower (T.sin_fast prec xl)) with\n           | Xnan => True\n           | Xreal r3 => (r3 <= Rtrigo_def.sin x)%R\n           end).\n      { generalize (T.sin_fast_correct prec xu).\n        generalize (T.sin_fast_correct prec xl).\n        destruct (T.sin_fast prec xl) as [|yl yu]; simpl;\n          [rewrite F'.valid_lb_nan|];\n          (destruct (T.sin_fast prec xu) as [|zl zu]; simpl;\n           [rewrite F'.valid_ub_nan|]); rewrite ?F'.nan_correct; [easy|..];\n            try (case (F.valid_lb yl);\n                 [|now simpl; case Xsin; [|intros rs [H0 H1]; lra]]);\n            try (case (F.valid_ub zu);\n                 [|now intros _;\n                   rewrite Bool.andb_comm; case Xsin; [|intros rs [H0 H1]; lra]]);\n            try (case (F.valid_ub yu);\n                 [|now simpl; case Xsin; [|intros rs [H0 H1]; lra]]);\n            try (case (F.valid_lb zl);\n                 [|now intros _;\n                   rewrite Bool.andb_comm; case Xsin; [|intros rs [H0 H1]; lra]]);\n            now case Xsin. }\n      generalize (T.sin_fast_correct prec xl).\n      destruct (T.sin_fast prec xl) as [|yl yu].\n      { simpl.\n        now rewrite F'.nan_correct. }\n      rewrite X.\n      simpl.\n      xreal_tac yl; [easy|].\n      case (_ && _)%bool; [|intros [H0 H1]; lra].\n      intros [Hy _].\n      apply Rle_trans with (1 := Hy).\n      assert (H' := Rle_trans _ _ _ Hxu Hpu').\n      apply sin_incr_1; try easy.\n      { now apply Rle_trans with x. }\n      now apply Rle_trans with r. }\n    generalize (T.sin_fast_correct prec xu).\n    destruct (T.sin_fast prec xu) as [|yl yu].\n    { simpl.\n      now rewrite F'.nan_correct. }\n    rewrite X0.\n    simpl.\n    xreal_tac yu; [easy|].\n    case (_ && _)%bool; [|intros [H0 H1]; lra].\n    intros [_ Hy].\n    apply Rle_trans with (2 := Hy).\n    assert (H' := Rle_trans _ _ _ Hpl' Hxl).\n    apply sin_incr_1; try easy.\n    { now apply Rle_trans with r0. }\n    now apply Rle_trans with x. }\n  intros _.\n  unfold Xsin.\n  rewrite <- cos_shift.\n   change (Xreal (Rtrigo_def.cos (PI / 2 - x))) with (Xcos (Xsub (Xreal (PI / 2)) (Xreal x))).\n   apply cos_correct.\n   apply sub_correct with (2 := Hx).\n   replace (PI / 2)%R with (PI / 4 * 2)%R by field.\n   change (Xreal (PI / 4 * 2)) with (Xreal (PI / 4) * Xreal 2)%XR.\n   apply mul2_correct.\n   apply T.pi4_correct. }\nintros _.\nrewrite <- (Ropp_involutive x).\nunfold Xsin.\nrewrite sin_neg.\napply (neg_correct _ (Xreal _)).\nrewrite <- cos_shift.\nreplace (PI / 2 - - x)%R with (x + PI / 2)%R by ring.\nchange (Xreal (Rtrigo_def.cos (x + PI / 2))) with (Xcos (Xadd (Xreal x) (Xreal (PI / 2)))).\napply cos_correct.\napply (add_correct _ _ _ _ _ Hx).\nreplace (PI / 2)%R with (PI / 4 * 2)%R by field.\nchange (Xreal (PI / 4 * 2)) with (Xreal (PI / 4) * Xreal 2)%XR.\napply mul2_correct.\napply T.pi4_correct.\nQed.\n\n(* meaningful only for |xi| <= pi/2 *)\nDefinition tan prec xi :=\n  match xi with\n  | Ibnd xl xu =>\n    if F'.le' xu xl then T.tan_fast prec xl else\n    let pi2 := F.mul_DN prec (lower (T.pi4 prec)) c2 in\n    match F'.lt' (F.neg pi2) xl, F'.lt' xu pi2 with\n    | true, true =>\n      bnd (lower (T.tan_fast prec xl)) (upper (T.tan_fast prec xu))\n    | _, _ => Inan\n    end\n  | Inan => Inan\n  end.\n\nLemma tan_correct :\n  forall prec, extension Xtan (tan prec).\nProof.\nintros prec [|xl xu]; [easy|].\nintros [|x].\n{ now simpl; case (_ && _)%bool. }\nintro Hx; generalize Hx.\nunfold convert at 1.\ncase_eq (F.valid_lb xl); [|intros _ [H0 H1]; lra].\ncase_eq (F.valid_ub xu); [|intros _ _ [H0 H1]; lra].\nintros Vxu Vxl [Hxl Hxu].\nunfold tan.\ncase_eq (F'.le' xu xl).\n{ intros Hl.\n  apply F'.le'_correct in Hl.\n  assert (Htxl := T.tan_fast_correct prec xl).\n  unfold convert in Hx; rewrite Vxl, Vxu in Hx; simpl in Hx.\n  destruct (F.toX xu) as [|xur] ; try easy.\n  destruct (F.toX xl) as [|xlr] ; try easy.\n  replace x with xlr.\n  { exact Htxl. }\n  apply Rle_antisym with (1 := proj1 Hx).\n  apply Rle_trans with (2 := Hl).\n  apply Hx. }\nintros _.\ncase_eq (F'.lt' (F.neg (F.mul_DN prec (lower (T.pi4 prec)) c2)) xl) ; try easy.\nintros Hlt1.\napply F'.lt'_correct in Hlt1.\ncase_eq (F'.lt' xu (F.mul_DN prec (lower (T.pi4 prec)) c2)) ; try easy.\nintros Hlt2.\napply F'.lt'_correct in Hlt2.\ngeneralize (T.tan_correct prec xl) (T.tan_correct prec xu).\nunfold convert in Hx; rewrite Vxl, Vxu in Hx; simpl in Hx.\ndestruct (F.toX xl) as [|rl].\n{ now destruct (F.toX (F.neg (F.mul_DN prec (lower (T.pi4 prec)) c2))). }\ndestruct (F.toX xu) as [|ru] ; try easy.\nintros Hl Hu.\nrewrite bnd_correct.\n2: { generalize (T.tan_fast_correct prec xl).\n  unfold T.I.convert.\n  case T.tan_fast; [now simpl; unfold valid_lb; rewrite F'.valid_lb_nan|].\n  intros l u; simpl; unfold valid_lb; case F.valid_lb; [easy|].\n  now case Xtan; [|intros r [H0 H1]; lra]. }\n2: { generalize (T.tan_fast_correct prec xu).\n  unfold T.I.convert.\n  case T.tan_fast; [now simpl; unfold valid_ub; rewrite F'.valid_ub_nan|].\n  intros l u; rewrite Bool.andb_comm.\n  simpl; unfold valid_ub; case F.valid_ub; [easy|].\n  now case Xtan; [|intros r [H0 H1]; lra]. }\nrewrite F'.neg_correct in Hlt1.\nelim (F.mul_DN_correct prec (lower (T.pi4 prec)) c2).\n2: { unfold F.is_non_neg_real, F.is_non_pos_real, F.is_non_neg, F.is_non_pos.\n  unfold c2.\n  rewrite (F'.valid_ub_real (F.fromZ 2)); [|rewrite F.real_correct];\n  (rewrite F.fromZ_correct; [|lia]); [|easy].\n  generalize (T.pi4_correct prec).\n  unfold T.I.convert.\n  case T.pi4.\n  { intros _; do 3 right; simpl.\n    rewrite F'.valid_lb_nan, F'.nan_correct; repeat split; lra. }\n  intros pl pu; simpl.\n  case (F.valid_lb pl); [|intros [H0 H1]; lra]; intros _.\n  case F.toX; [do 3 right; repeat split; lra|].\n  intro r'.\n  case (Rle_or_lt 0 r'); intro Hr'; [left; split; lra|].\n  do 3 right; repeat split; lra. }\nintro Vmpi2.\nunfold le_lower, le_upper.\nunfold c2.\nrewrite F.fromZ_correct; [|lia].\nrevert Hlt1 Hlt2.\nunfold c2.\ncase F.toX; [easy|]; intro rpi2.\nsimpl.\nintros Hlt1 Hlt2.\ngeneralize (T.pi4_correct prec).\ndestruct (T.pi4 prec) as [|pi4l pi4u].\n{ now simpl; rewrite F'.nan_correct. }\nunfold T.I.convert.\ncase (_ && _)%bool; [|intros [H0 H1]; lra].\nintros [Hpil _].\nsimpl.\ndestruct (F.toX pi4l) as [|pi4r] ; [easy|].\nsimpl.\nintro Hmpi2.\napply (Rmult_le_compat_r 2) in Hpil; [|now apply IZR_le].\nunfold Rdiv in Hpil.\nreplace (PI * /4 * 2)%R with (PI / 2)%R in Hpil by field.\nassert (H1: (- PI / 2 < rl)%R) by lra.\nassert (H2: (ru < PI / 2)%R) by lra.\nunfold Xtan'.\nsimpl.\ncase is_zero_spec.\n{ simpl in Hx.\n  apply Rgt_not_eq, cos_gt_0.\n  { apply Rlt_le_trans with (2 := proj1 Hx).\n    unfold Rdiv.\n    now rewrite <- Ropp_mult_distr_l_reverse. }\n  now apply Rle_lt_trans with ru. }\nunfold Xtan' in Hl, Hu.\nintros _.\nsplit.\n- destruct (T.tan_fast prec xl) as [|tl tu].\n  { simpl.\n    now rewrite F'.nan_correct. }\n  revert Hl.\n  simpl.\n  case (_ && _)%bool; [|now case is_zero; [|intros [H0' H1']; lra]].\n  simpl.\n  case is_zero_spec ; [easy|].\n  intros _ [H _].\n  destruct (F.toX tl) as [|rtl] ; try easy.\n  apply Rle_trans with (1 := H).\n  destruct (proj1 Hx) as [Hx'|Hx'].\n  { apply Rlt_le.\n    apply tan_increasing ; try easy.\n    now apply Rle_lt_trans with ru. }\n  rewrite Hx'.\n  apply Rle_refl.\n- destruct (T.tan_fast prec xu) as [|tl tu].\n  { now simpl; rewrite F'.nan_correct. }\n  revert Hu.\n  simpl.\n  case (_ && _)%bool; [|now case is_zero; [|intros [H0' H1']; lra]].\n  simpl.\n  case is_zero_spec ; [easy|].\n  intros _ [_ H].\n  destruct (F.toX tu) as [|rtu] ; try easy.\n  apply Rle_trans with (2 := H).\n  destruct (proj2 Hx) as [Hx'|Hx'].\n  { apply Rlt_le.\n    apply tan_increasing ; try easy.\n    now apply Rlt_le_trans with rl. }\n  rewrite Hx'.\n  apply Rle_refl.\nQed.\n\nDefinition atan prec xi :=\n  match xi with\n  | Ibnd xl xu =>\n    Ibnd\n     (if F.real xl then lower (T.atan_fast prec xl)\n      else F.neg (F.mul_UP prec (upper (T.pi4 prec)) c2))\n     (if F.real xu then upper (T.atan_fast prec xu)\n      else F.mul_UP prec (upper (T.pi4 prec)) c2)\n  | Inan => Inan\n  end.\n\nLemma atan_correct :\n  forall prec, extension Xatan (atan prec).\nProof.\nintros prec [|xl xu]; [easy|].\nintros [|x].\n{ now simpl; case (_ && _)%bool. }\nintro Hx; generalize Hx.\nunfold convert at 1.\ncase_eq (F.valid_lb xl); [|intros _ [H0 H1]; lra].\ncase_eq (F.valid_ub xu); [|intros _ _ [H0 H1]; lra].\nintros Vxu Vxl [Hxl Hxu].\nassert (Hpi := T.pi4_correct prec).\nsimpl.\nunfold convert in Hx; rewrite Vxl, Vxu in Hx; simpl in Hx.\nelim (F.mul_UP_correct prec (upper (T.pi4 prec)) c2).\n2: { unfold F.is_non_neg, F.is_non_pos, F.is_non_pos_real, F.is_non_neg_real.\n  unfold c2.\n  rewrite (F'.valid_ub_real (F.fromZ 2)); [|rewrite F.real_correct];\n  (rewrite F.fromZ_correct; [|lia]); [|easy].\n  generalize (T.pi4_correct prec).\n  unfold T.I.convert.\n  case T.pi4.\n  { intros _; left; simpl.\n    rewrite F'.valid_ub_nan, F'.nan_correct; repeat split; lra. }\n  intros pl pu; simpl.\n  rewrite Bool.andb_comm.\n  case (F.valid_ub pu); [|intros [H0 H1]; lra]; intros _.\n  case F.toX; [left; repeat split; lra|].\n  intro r'.\n  case (Rle_or_lt 0 r'); intro Hr'; [left; repeat split; lra|].\n  do 2 right; left; repeat split; lra. }\nintros Vmpi2 Hmpi2.\nset (l := if F.real xl then _ else _).\nset (u := if F.real xu then _ else _).\nassert (Vl : F.valid_lb l = true).\n{ unfold l; rewrite F.real_correct.\n  generalize (T.atan_fast_correct prec xl).\n  case F.toX.\n  { now intros _; rewrite F'.valid_lb_neg. }\n  intro r.\n  unfold T.I.convert.\n  case T.atan_fast; [now simpl; rewrite F'.valid_lb_nan|].\n  intros l' u'.\n  simpl.\n  now case F.valid_lb; [|intros [H0 H1]; lra]. }\nassert (Vu : F.valid_ub u = true).\n{ unfold u; rewrite F.real_correct.\n  generalize (T.atan_fast_correct prec xu).\n  case F.toX; [easy|].\n  intro r.\n  unfold T.I.convert.\n  case T.atan_fast; [now simpl; rewrite F'.valid_ub_nan|].\n  intros l' u'.\n  simpl.\n  now rewrite Bool.andb_comm; case F.valid_ub; [|intros [H0 H1]; lra]. }\nrewrite Vl, Vu; simpl.\nunfold l, u.\nrewrite 2!F.real_correct.\nsplit.\n- generalize (proj1 Hx). clear Hx.\n  case_eq (F.toX xl).\n  { intros _ _.\n    rewrite F'.neg_correct.\n    revert Hmpi2; unfold le_upper.\n    case F.toX; [easy|]; intro rmpi2.\n    unfold c2.\n    rewrite F.fromZ_correct; [|lia].\n    destruct (T.pi4 prec) as [|pi4l pi4u] ; simpl.\n    { now rewrite F'.nan_correct. }\n    revert Hpi; simpl.\n    case (_ && _)%bool; [|intros [H0 H1]; lra]; simpl; intro Hpi.\n    destruct (F.toX pi4u) as [|rpi4] ; [easy|].\n    simpl.\n    intro H.\n    apply (Rle_trans _ _ _ (Ropp_le_contravar _ _ H)).\n    apply Rlt_le.\n    apply Rle_lt_trans with (2 := proj1 (atan_bound x)).\n    lra. }\n  intros rl Hl Hx.\n  generalize (T.atan_correct prec xl).\n  destruct (T.atan_fast prec xl) as [|al au].\n  { intros _.\n    simpl.\n    now rewrite F'.nan_correct. }\n  simpl.\n  rewrite Hl.\n  case (_ && _)%bool; [|intros [H0 H1]; lra].\n  destruct (F.toX al) as [|ral] ; [easy|].\n  intros [H _].\n  apply Rle_trans with (1 := H).\n  destruct Hx as [Hx|Hx].\n  { now apply Rlt_le, atan_increasing. }\n  rewrite Hx.\n  apply Rle_refl.\n- generalize (proj2 Hx). clear Hx.\n  case_eq (F.toX xu).\n  { intros _ _.\n    revert Hmpi2.\n    unfold le_upper.\n    case F.toX; [easy|]; intro rmpi2.\n    unfold c2.\n    rewrite F.fromZ_correct; [|lia].\n    destruct (T.pi4 prec) as [|pi4l pi4u] ; simpl.\n    { now rewrite F'.nan_correct. }\n    revert Hpi; simpl.\n    case (_ && _)%bool; [|intros [H0 H1]; lra]; simpl; intro Hpi.\n    destruct (F.toX pi4u) as [|rpi4] ; [easy|].\n    simpl.\n    apply Rle_trans.\n    apply Rlt_le.\n    apply Rlt_le_trans with (1 := proj2 (atan_bound x)).\n    lra. }\n  intros rl Hl Hx.\n  generalize (T.atan_correct prec xu).\n  destruct (T.atan_fast prec xu) as [|al au].\n  { intros _.\n    simpl.\n    now rewrite F'.nan_correct. }\n  simpl.\n  rewrite Hl.\n  case (_ && _)%bool; [|intros [H0 H1]; lra].\n  destruct (F.toX au) as [|rau] ; [easy|].\n  intros [_ H].\n  apply Rle_trans with (2 := H).\n  destruct Hx as [Hx|Hx].\n  { now apply Rlt_le, atan_increasing. }\n  rewrite Hx.\n  apply Rle_refl.\nQed.\n\nDefinition exp prec xi :=\n  match xi with\n  | Ibnd xl xu =>\n    Ibnd\n     (if F.real xl then lower (T.exp_fast prec xl) else F.zero)\n     (if F.real xu then upper (T.exp_fast prec xu) else F.nan)\n  | Inan => Inan\n  end.\n\nTheorem exp_correct :\n  forall prec, extension Xexp (exp prec).\nProof.\nintros prec [|xl xu]; [now trivial|].\nintros [|x]; [now simpl; case (_ && _)%bool|].\nunfold convert at 1.\ncase_eq (F.valid_lb xl); [|intros _ [H0 H1]; lra].\ncase_eq (F.valid_ub xu); [|intros _ _ [H0 H1]; lra].\nintros Vxu Vxl [Hxl Hxu].\nsimpl.\nset (l := if F.real xl then _ else _).\nset (u := if F.real xu then _ else _).\nassert (Vl : F.valid_lb l = true).\n{ unfold l.\n  rewrite F.real_correct.\n  generalize (T.exp_fast_correct prec xl).\n  case F.toX.\n  { now simpl; rewrite F'.valid_lb_zero. }\n  intro rxl.\n  unfold T.I.convert.\n  simpl.\n  case T.exp_fast.\n  { now simpl; rewrite F'.valid_lb_nan. }\n  intros rl ru.\n  simpl.\n  now case F.valid_lb; [|intros [H0 H1]; lra]. }\nassert (Vu : F.valid_ub u = true).\n{ unfold u.\n  rewrite F.real_correct.\n  generalize (T.exp_fast_correct prec xu).\n  case F.toX.\n  { now rewrite F'.valid_ub_nan. }\n  intro rxu.\n  unfold T.I.convert.\n  simpl.\n  case T.exp_fast.\n  { now simpl; rewrite F'.valid_ub_nan. }\n  intros rl ru.\n  simpl; rewrite Bool.andb_comm.\n  now case F.valid_ub; [|intros [H0 H1]; lra]. }\nrewrite Vl, Vu; unfold l, u.\nsplit.\n{ (* lower *)\n  clear Hxu.\n  rewrite F.real_correct.\n  xreal_tac xl.\n  { rewrite F.zero_correct.\n    simpl.\n    apply Rlt_le.\n    apply exp_pos. }\n  generalize (T.exp_fast_correct prec xl).\n  destruct (T.exp_fast prec xl) as [|yl yu].\n  { unfold lower.\n    now rewrite F'.nan_correct. }\n  rewrite X.\n  unfold T.I.convert.\n  case (_ && _)%bool; [|intros [H0 H1]; lra].\n  intros (H, _).\n  simpl.\n  xreal_tac2.\n  apply Rle_trans with (1 := H).\n  now apply Raux.exp_le. }\n(* upper *)\nclear Hxl.\nrewrite F.real_correct.\nxreal_tac xu.\n{ now rewrite F'.nan_correct. }\ngeneralize (T.exp_fast_correct prec xu).\ndestruct (T.exp_fast prec xu) as [|yl yu].\n{ unfold upper.\n  now rewrite F'.nan_correct. }\nrewrite X.\nunfold T.I.convert.\ncase (_ && _)%bool; [|intros [H0 H1]; lra].\nintros (_, H).\nsimpl.\nxreal_tac2.\napply Rle_trans with (2 := H).\nnow apply Raux.exp_le.\nQed.\n\nDefinition ln prec xi :=\n  match xi with\n  | Ibnd xl xu =>\n    if F'.lt' F.zero xl then\n      Ibnd\n        (lower (T.ln_fast prec xl))\n        (if F.real xu then upper (T.ln_fast prec xu) else F.nan)\n    else Inan\n  | Inan => Inan\n  end.\n\nTheorem ln_correct :\n  forall prec, extension Xln (ln prec).\nProof.\nintros prec [|xl xu]; [easy|].\nunfold Xln'.\nintros [|x]; [now unfold convert; case (_ && _)%bool|].\nsimpl.\ncase_eq (F.valid_lb xl); [|intros _ [H0 H1]; lra].\ncase_eq (F.valid_ub xu); [|intros _ _ [H0 H1]; lra].\nintros Vxu Vxl [Hl Hu].\ncase_eq (F'.lt' F.zero xl) ; intros Hlt ; [|easy].\napply F'.lt'_correct in Hlt.\nrewrite F.zero_correct in Hlt.\nsimpl.\nset (l := lower _).\nset (u := if F.real xu then _ else _).\nassert (Vl : F.valid_lb l = true).\n{ generalize (T.ln_fast_correct prec xl).\n  unfold l, T.I.convert.\n  case T.ln_fast; [now simpl; rewrite F'.valid_lb_nan|].\n  intros rl ru.\n  simpl.\n  now case F.valid_lb; [|case Xln; [|intros r [H0 H1]; lra]]. }\nassert (Vu : F.valid_ub u = true).\n{ generalize (T.ln_fast_correct prec xu).\n  unfold u, T.I.convert; simpl.\n  rewrite F.real_correct.\n  case F.toX; [now rewrite F'.valid_ub_nan|].\n  intro r.\n  case T.ln_fast; [now simpl; rewrite F'.valid_ub_nan|].\n  intros rl ru.\n  rewrite Bool.andb_comm; simpl.\n  now case F.valid_ub; [|case Xln'; [|intros r' [H0 H1]; lra]]. }\nrewrite Vl, Vu; unfold l, u; clear Vl l Vu u; simpl.\ncase is_positive_spec.\n{ intros Hx.\n  simpl.\n  split.\n  { generalize (T.ln_fast_correct prec xl).\n    case T.ln_fast.\n    { intros _.\n      simpl.\n      now rewrite F'.nan_correct. }\n    intros l u.\n    simpl.\n    case_eq (Xln (F.toX xl)); [now intros _; case (_ && _)%bool|].\n    intros lnx Hlnx.\n    case (_ && _)%bool; [|intros [H0 H1]; lra].\n    intros [H _].\n    destruct (F.toX l) as [|lr]; [easy|].\n    apply Rle_trans with (1 := H).\n    destruct (F.toX xl) as [|xlr]; [easy|].\n    revert Hlnx.\n    unfold Xln'.\n    simpl.\n    case is_positive_spec.\n    { intros _ H'.\n      injection H'.\n      intros <-.\n      destruct Hl as [Hl|Hl].\n      { now apply Rlt_le, ln_increasing. }\n      rewrite Hl.\n      apply Rle_refl. }\n    easy. }\n  rewrite F.real_correct.\n  case_eq (F.toX xu).\n  { now rewrite F'.nan_correct. }\n  intros xur Hxu.\n  rewrite Hxu in Hu.\n  generalize (T.ln_fast_correct prec xu).\n  case T.ln_fast.\n  { intros _.\n    simpl.\n    now rewrite F'.nan_correct. }\n  intros l u.\n  simpl.\n  rewrite Hxu.\n  unfold Xln'.\n  simpl.\n  case (_ && _)%bool; [|now case is_positive; [intros [H0 H1]; lra|]].\n  case is_positive_spec.\n  { intros _.\n    intros [_ H].\n    destruct (F.toX u) as [|ur]; [easy|].\n    apply Rle_trans with (2 := H).\n    destruct Hu as [Hu|Hu].\n    { now apply Rlt_le, ln_increasing. }\n    rewrite Hu.\n    apply Rle_refl. }\n  easy. }\nintros Hx.\ndestruct (F.toX xl) as [|xlr]; [easy|].\nelim Rle_not_lt with (1 := Hx).\nnow apply Rlt_le_trans with xlr.\nQed.\n\nEnd FloatIntervalFull.\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/src/Interval/Float_full.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6687235769095531}}
{"text": "Set Universe Polymorphism.\nRequire Import HoTT. \n\n(** * Pointed partial order *)\n\n(**\n\n  A pointed partial order is a type [A] equipped with a partial order [≼]\n  (reflexive, transitive relation) and a least element [bot] for that\n  relation.\n\n*)\n\nReserved Notation \"x ≼ y\" (at level 50).\n\n(* =PartialOrder_pp= *)\nClass IsPartialOrder_pp (A: Type) := { \n    rel: A -> A -> HProp where \"x ≼ y\" := (rel x y);\n    bot: A;\n    rel_refl: forall x, x ≼ x;\n    rel_trans: forall x y z, x ≼ y -> y ≼ z -> x ≼ z;\n    rel_antisym: forall x y, x ≼ y -> y ≼ x -> x = y;\n    bot_is_least: forall x, bot ≼ x;\n}.\n(* =end= *)\n\nArguments rel_trans {_ _ _ _ _} _ _.\n\nNotation \"x ≼ y\" := (rel x y).\n\n(* =partial_order_forall= *)\nInstance IsPartialOrder_pp_fun (A: Type)(B: A -> Type) \n    `{forall a, IsPartialOrder_pp (B a)}: IsPartialOrder_pp (forall a, B a) :=\n  {| rel := fun f g => hprop (forall a, f a ≼ g a);\n     bot := fun a => bot |}.\n(* =end= *)\nProof.\n  - simpl; intros. apply rel_refl.\n  - simpl; intros f g h H1 H2 a. eapply rel_trans; auto.\n  - simpl; intros f g H1 H2. apply funext. intro x. apply rel_antisym; auto. \n  - simpl; intros f a. apply bot_is_least.\nDefined.\n\n(** A monotone function between two partial orders respects the partial order\nand transports bottom to bottom. *)\n\n(* =monotone_fun= *)\nRecord monotone_function A B `{IsPartialOrder_pp A} `{IsPartialOrder_pp B} :=\n Build_Mon { \n     f_ord:> A -> B ;\n    mon: forall x y, x ≼ y -> f_ord x ≼ f_ord y;\n    p_mon: f_ord bot ≼ bot\n  }.\nNotation \"A --> B\" := (monotone_function A B)\n(* =end= *)\n                        (at level 10).\n\nArguments f_ord {_ _ _ _} _ _. \nArguments mon {_ _ _ _} _ {_ _} _. \nArguments Build_Mon {_ _ _ _} _ _ _.\n", "meta": {"author": "CoqHott", "repo": "DICoq", "sha": "6abf83fbf3a78f45885760afa700c26a804f7ccc", "save_path": "github-repos/coq/CoqHott-DICoq", "path": "github-repos/coq/CoqHott-DICoq/DICoq-6abf83fbf3a78f45885760afa700c26a804f7ccc/PartialOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6687235600967053}}
{"text": "(* Software Foundations *)\n(* Exercise: 2 star, and_assoc *)\n\nInductive and(P Q: Prop): Prop:=\n  conj: P -> Q -> (and P Q).\n\nNotation \"P /\\ Q\" := (and P Q): type_scope.\nTheorem and_assoc : forall P Q R : Prop, P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n    intros P Q R H. inversion H as [HP [HQ HR]].\n    split.\n    split.\n    apply HP.\n    apply HQ.\n    apply HR.\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/and_assoc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6686988752226901}}
{"text": "C02W82DBHV2R:~ i847419$ coqtop\nWelcome to Coq 8.8.0 (April 2018)\n\nCoq < Require Import Classical.\n\nCoq < Theorem exp018 : (forall P Q R S : Prop, ((P \\/ Q) /\\ (P -> R) /\\ (Q -> S) -> (R \\/ S))).\n1 subgoal\n  \n  ============================\n  forall P Q R S : Prop, (P \\/ Q) /\\ (P -> R) /\\ (Q -> S) -> R \\/ S\n\nexp018 < intros.\n1 subgoal\n  \n  P, Q, R, S : Prop\n  H : (P \\/ Q) /\\ (P -> R) /\\ (Q -> S)\n  ============================\n  R \\/ S\n\nexp018 < destruct H.\n1 subgoal\n  \n  P, Q, R, S : Prop\n  H : P \\/ Q\n  H0 : (P -> R) /\\ (Q -> S)\n  ============================\n  R \\/ S\n\nexp018 < destruct H0.\n1 subgoal\n  \n  P, Q, R, S : Prop\n  H : P \\/ Q\n  H0 : P -> R\n  H1 : Q -> S\n  ============================\n  R \\/ S\n\nexp018 < tauto.\nNo more subgoals.\n\nexp018 < Qed.\nexp018 is defined\n", "meta": {"author": "billwestfall", "repo": "coq_ide", "sha": "a2985a04f37f9c1c6f23799d543fdb862792d54b", "save_path": "github-repos/coq/billwestfall-coq_ide", "path": "github-repos/coq/billwestfall-coq_ide/coq_ide-a2985a04f37f9c1c6f23799d543fdb862792d54b/logic/misc/018.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6686988750819661}}
{"text": "Require Export B8_Point_Def.\n\nSection TRIANGLE_SPECIFICATION.\n\nLemma TriangleSpecPerm : forall A B C : Point,\n\tTriangleSpec (Distance A B) (Distance B C) (Distance C A) ->\n\tTriangleSpec (Distance B C) (Distance C A) (Distance A B) .\nProof.\n\tunfold TriangleSpec in |- *; intuition.\nQed.\n\nLemma ClockwiseTriangleSpec : forall A B C : Point,\n\tClockwise A B C ->\n\tTriangleSpec (Distance A B) (Distance B C) (Distance C A).\nProof.\n\tunfold TriangleSpec in |- *; intuition.\n\t rewrite (DistSym A B); apply TriangularIneq.\n\t   apply ClockwiseBCA; auto.\n\t rewrite (DistSym B C); apply TriangularIneq.\n\t   apply ClockwiseCAB; auto.\n\t rewrite (DistSym C A); apply TriangularIneq; auto.\nQed.\n\nEnd TRIANGLE_SPECIFICATION.\n", "meta": {"author": "coq-contribs", "repo": "ruler-compass-geometry", "sha": "ee36f5cd523abaa2e0b676c4100c02ec496c0bfd", "save_path": "github-repos/coq/coq-contribs-ruler-compass-geometry", "path": "github-repos/coq/coq-contribs-ruler-compass-geometry/ruler-compass-geometry-ee36f5cd523abaa2e0b676c4100c02ec496c0bfd/B9_Inegalite_Triang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6686491630693132}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nFrom GraphTheory Require Import edone preliminaries digraph sgraph.\nFrom fourcolor Require Import hypermap geometry jordan color coloring combinatorial4ct.\nFrom GraphTheory Require Import hmap_ops.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nDefinition kconnected_map (k : nat) (G : hypermap) := \n  k < fcard node G /\\ \n  forall A : pred G, #|A| < k -> \n    {in [predC fclosure node A]&, forall x y, connect (restrict [predC fclosure node A] glink) x y}.\n\nLemma closed_connect (T : finType) (e : rel T) (A : pred T) : \n  closed e A -> {in A, subrel (connect e) (connect (restrict A e))}.\nProof.\nmove => clA x xA y.\ncase/connectP => p; elim: p x xA => [x _ _ -> //|z p IHp /= x xA /andP [xz pth_p] lst_p].\nhave zA: z \\in A by rewrite -(clA _ _ xz).\nby apply: connect_trans (IHp _ zA pth_p lst_p); apply:connect1; rewrite /= xA zA.\nQed.\n\nLemma in_connect_sym (T : finType) (e : rel T) (A : pred T) : \n  closed e A -> connect_sym e -> {in A&, connect_sym (restrict A e)}.\nProof. \nmove => clA sym_e x y xA yA.\nwlog suff : x y xA yA / connect (restrict A e) x y -> connect (restrict A e) y x.\n{ by move => W; apply/idP/idP; apply: W. }\ncase/connectP => p; elim: p x xA => /= [x _ _ -> //| z p IHp x xA].\nrewrite -!andbA => /and4P [_ zA x_z pth_p lst_p].\nhave {pth_p lst_p} IH := IHp _ zA pth_p lst_p. apply: connect_trans IH _.\nhave := (connect1 x_z); rewrite sym_e; exact: closed_connect.\nQed.\n\nLemma sub_restrict T (e1 e2 : rel T) (A : pred T) : \n  {in A&, subrel e1 e2} -> subrel (restrict A e1) (restrict A e2).\nProof. move => sub x y /=/andP[/andP [xA yA] xy]. by rewrite xA yA sub. Qed.\n\nLemma glinkN (G : hypermap) : subrel (frel node) (@glink G).\nProof. move => x y. by rewrite /glink /= => ->. Qed.\n\nLemma sub_node_clink {G : hypermap} : subrel (frel (finv node)) (@clink G).\nProof. move => x y /eqP <-. by rewrite /clink/= eqxx. Qed.\n\nLemma in_clink_glink (G : hypermap) (A : pred G) (plainG : plain G) : \n  fclosed node A -> {in A&, connect (restrict A clink) =2 connect (restrict A glink)}.\nProof.\nmove => clA x y xA yA. apply/idP/idP.\n- case/connectP => [p]. elim: p x xA => [x xA _ -> //|z p IHp x xA /=].\n  rewrite -!andbA => /and4P [_ zA xz pth_p lst_p]. \n  apply: connect_trans (IHp _ zA pth_p lst_p) => {pth_p lst_p}.\n  case/clinkP : xz xA zA => [->|<-] => xA zA.\n  + apply: connect_mono. apply: sub_restrict. apply: in2W. exact: glinkN.\n    rewrite in_connect_sym // ?connect1 //=. exact: cnodeC.\n  + by apply connect1; rewrite /= xA zA /glink/= eqxx.\n- case/connectP => [p]. elim: p x xA => [x xA _ -> //|z p IHp x xA /=].\n  rewrite -!andbA => /and4P [_ zA xz pth_p lst_p]. \n  apply: connect_trans (IHp _ zA pth_p lst_p) => {pth_p lst_p IHp}.\n  gen have N,N': x z xA zA {xz} / node x == z -> connect (restrict A clink) x z.\n  { move/eqP => E. rewrite -{}E in zA *. \n    apply: connect_mono. apply: sub_restrict. apply: in2W. exact: sub_node_clink.\n    rewrite in_connect_sym // ?connect1 //= ?xA ?zA ?finv_f ?eqxx //.\n    * move => u v /eqP <-. by rewrite (clA (finv node u) u) //= f_finv.\n    * by apply/fconnect_sym/finv_inj. }\n  gen have F,F': x z xA zA {xz N N'} / face x == z -> connect (restrict A clink) x z.\n  { move/eqP => E; rewrite -{}E in zA *. by apply: connect1; rewrite /= xA zA clinkF. }\n  case/or3P : xz => //= {N' F'}.\n  rewrite -plain_eq' => // /eqP => E; rewrite -{}E in zA *. \n  have ? : face x \\in A by rewrite (clA (face x) (node (face x))) //=.\n  apply: connect_trans (N (face x) _ _ _ _) => //. exact: F.\nQed.\n\nDefinition avoid_one (G : hypermap) := \n  forall z x y : G , ~~ cnode z x -> ~~ cnode z y -> connect (restrict [predC cnode z] clink) x y.\n\nLemma two_connected_avoid (G : hypermap) (plainG : plain G) : \n  kconnected_map 2 G -> avoid_one G.\nProof.\ncase => _ tcG z x y Hx Hy.\nhave:= tcG (pred1 z) _; rewrite card1 => /(_ isT) {tcG} tcG.\nhave Nz : cnode z =i fclosure node (pred1 z) by apply/closure1/cnodeC.\nhave PNz : [predC cnode z] =i [predC fclosure node (pred1 z)]. \n{ by move => u; rewrite inE /= Nz. }\nrewrite in_clink_glink //; last exact/predC_closed/connect_closed/cnodeC.\napply: connect_restrict_mono (tcG x y _ _); rewrite -?PNz //.\napply/subsetP => u. by rewrite -PNz.\nQed.\n\nDefinition drestrict (G : diGraph) (A : pred G) := DiGraph (restrict A (--)).\n\nLemma upathPR (G : diGraph) (x y : G) A :\n  reflect (exists p : seq G, @upath (drestrict A) x y p)\n          (connect (restrict A (--)) x y).\nProof. exact: (@upathP (drestrict A)). Qed.\n\nLemma upath_rconsE (G: diGraph) (x y : G) p : x != y ->\n    upath x y p -> path (--) x (rcons (behead (belast x p)) y) /\\ uniq (rcons (belast x p) y).\nProof.\nrewrite /upath/pathp; elim/last_ind : p x y => [x y /negbTE-> //|p z ? x y ?]. \nrewrite !belast_rcons last_rcons /= -andbA => /and4P [H1 H2 H3 /eqP<-].\nby rewrite H1 H2 H3.\nQed.\n\nLemma drestrict_upath (G : diGraph) (x y : G) (A : pred G) (p : seq G) :\n  @upath (@drestrict G A) x y p -> @upath G x y p.\nProof.\nelim: p x => // z p IH x /upath_consE [/= /andP [_ u1] u2 u3]. \nrewrite upath_cons u1 u2 /=. exact: IH.\nQed.\n\n(* TODO: \n   - clean up digraph/sgraph connect/path lemmas\n   - provide link between [p : Path x y] and [path e x (rcons q y)] *)\nLemma connect_inE (T : finType) (e : rel T) (A : pred T) (x y : T) : \n  x != y -> connect (restrict A e) x y -> \n  (exists p, [/\\ path e x (rcons p y), uniq (x::rcons p y) & {subset x::rcons p y <= A}]).\nProof.\nmove => xDy. case/(@upathPR (DiGraph e)) => p U. \nmove/upath_rconsE : (drestrict_upath U) => -/(_ xDy) [P1 P2].\nhave E : last x p = y by case/andP : U => _; apply: pathp_last.\nrewrite -E -lastI in P2. \nexists (behead (belast x p)); split => //. \n- suff -> : rcons (behead (belast x p)) y = p by [].\n  destruct p; rewrite -?E -?lastI //=. by rewrite -E /= eqxx in xDy. \n- move/upath_rconsE : (U) => /(_ xDy) => -[P _]. \n  apply/cons_subset; split; last exact: rpath_sub P. \n  destruct p; simpl in *. by rewrite E eqxx in xDy. \n  case/upath_consE : U => /=. by rewrite /edge_rel/=; case: (x \\in A).\nQed.\n\nLemma sub_face_clink { G : hypermap } : @subrel G (frel face) clink.\nProof. by move => u v /eqP ?; apply/clinkP; right. Qed.\n\nLemma path_take_nth (T : eqType) (e : rel T) x s n : \n  n < size s -> path e x s -> e (last x (take n s)) (nth x s n).\nProof.\nelim: s x n => // a s IH x [|n] /=; first by case (e x a).\nrewrite ltnS => ? /andP [_ ?]; by rewrite (set_nth_default a x) ?IH.\nQed.\n\nLemma path_take (T : eqType) (e : rel T) x s n : \n  path e x s -> path e x (take n s).\nProof. by rewrite -{1}[s](cat_take_drop n) cat_path; case/andP. Qed.\n\nLemma disjoint_subpath (T : finType) (A B : pred T) (e : rel T) x y (p : seq T) :\n  x \\in A -> y \\in B -> path e x (rcons p y) -> [disjoint A & B] ->\n  exists u v q, [/\\ u \\in A, v \\in B, path e u (rcons q v), \n              subseq (u:: rcons q v) (x:: rcons p y) & [disjoint q & [predU A & B]]].\nProof.\nhave [m Hm] := ubnP (size p); elim: m x y p Hm => // n IH x y p p_n xA xB pth_p disAB.\ncase: (boolP [disjoint p & [predU A & B]]) => [?|]; first by exists x; exists y; exists p.\ncase/pred0Pn => z /andP[z_in_p z_in_AB].\ncase/splitP def_p : p _ _ / z_in_p pth_p p_n => [p1 p2].\nrewrite rcons_cat cat_path last_rcons => /andP [pth_p1 pth_p2].\nrewrite size_cat size_rcons addSn ltnS => size_p. \nhave {z_in_AB} [z_in_A|z_in_B] := orP z_in_AB.\n- case:(IH z y p2) => //. apply: leq_ltn_trans size_p. exact: leq_addl. \n  move => u [v] [q] [uA vB Q1 Q2 Q3]; exists u; exists v; exists q. split => //. \n  apply: subseq_trans Q2 _. rewrite -(cats1 _ z) -catA cat1s -cat_cons.   \n  exact: suffix_subseq.\n- case:(IH x z p1) => //. apply: leq_ltn_trans size_p. exact: leq_addr. \n  move => u [v] [q] [uA vB Q1 Q2 Q3]; exists u; exists v; exists q. split => //. \n  apply: subseq_trans Q2 _. exact: prefix_subseq.\nQed.\n\nLemma last_belast (T : eqType) (x : T) (s : seq T) : \n  uniq (x :: s) -> last x s \\in belast x s = false.\nProof. \nelim: s x => //= y s IH x /andP [Hx ?]. rewrite inE IH // orbF.\napply: contraNF Hx => /eqP <-. exact: mem_last.\nQed.\n\nLemma last_head_behead (T : eqType) (x : T) (p : seq T) : last (head x p) (behead (rcons p x)) = x.\nProof. case: p => //= ? ?. exact: last_rcons. Qed.\n\nLemma last_memE (T : eqType) (x : T) (s : seq T) (a : pred T) : \n  last x s \\in a -> (x \\in a) + { y | y \\in s & y \\in a}.\nProof. \nelim/last_ind : s => [|s y _]; first by left.\nby rewrite last_rcons; right;exists y => //; rewrite mem_rcons mem_head.\nQed.\n\n\nLemma index_finv (T : finType) (f : T -> T) x : \n  findex f x (finv f x) = (order f x).-1.\nProof. by rewrite findex_iter // orderSpred. Qed.\n\nLemma bar (T : finType) (f : T -> T) x : \n  injective f -> findex f (f x) x = (order f (f x)).-1.\nProof. move => inj_f. have := index_finv f (f x). by rewrite finv_f. Qed.\n\n(** Every face of a two connected loopless plain graph is bounded by a\ncycle. In the hypermap representation, this amounts to showing that\ndistinct nodes on an f-cycle belong to different n-cycles *)\n(* TODO: simplify further (use [rot_to_arc] for f-cycle) *)\nLemma two_connected_cyle (G : hypermap) :\n  avoid_one G -> plain G -> loopless G -> planar G ->\n  forall x y : G, x != y -> cface x y -> ~~ cnode x y.\nProof.\nmove => tcG plainG llG planarG x y xDy cf_xy; apply/negP => cn_xy.\nwlog [p [path_p uniq_p disj_p]] : x xDy cf_xy cn_xy / \n  exists p, [/\\ fpath (finv node) y (rcons p x), uniq p & [disjoint p & cface x]].\n{ move => W. \n  pose o := orbit (finv node) y; pose a := cface x.\n  have [o' def_o] : exists o', o = y :: o' by rewrite /o/orbit -orderSpred /=; eexists.\n  have has_x : has a o'; first (apply/hasP; exists x; last exact: connect0). \n    suff: x \\in o by rewrite def_o inE (negPf xDy).\n    by rewrite -fconnect_orbit same_fconnect_finv // cnodeC.\n  case/split_find def_o' : _ _ _ / has_x => [x' p q a_x' hasNp]; subst o'.\n  have: uniq o by apply: orbit_uniq.\n  have: fcycle (finv node) o by apply/cycle_orbit/finv_inj. \n  have cf_x'y: cface x' y by apply: connect_trans cf_xy; rewrite cfaceC.\n  rewrite def_o /= rcons_path cat_path -!andbA => /andP [path_p _].\n  rewrite cat_uniq rcons_uniq -!andbA mem_cat mem_rcons inE !negb_or -!andbA eq_sym.\n  move => /andP[? /and5P[_ _ _ uniq_p _]]; apply: (W x') => //. \n  - rewrite cnodeC -same_fconnect_finv //; apply/connectP; exists (rcons p x') => //.\n    by rewrite last_rcons.\n  - exists p; split => //; rewrite disjoint_has // (eq_has (_ : cface x' =i cface x)) //.\n    move=> z; rewrite !inE; apply: (same_connect cfaceC). \n    by apply: connect_trans cf_x'y _; rewrite cfaceC. }\n(* Exibiting the f-cycle *)\nhave := cycle_orbit faceI x; have := orbit_uniq face x.\nhave : y \\in orbit face x by rewrite -fconnect_orbit.\ncase def_c : (orbit face x) => [//|x0 c].\nmove: (def_c).\nhave {def_c} -> : x0 = x by move: def_c; rewrite /orbit -orderSpred; case. \nmove => def_c y_in_c uniq_c cycle_c. \nrewrite inE eq_sym (negbTE xDy) /= in y_in_c.\n(* Splitting the f-cycle *)\ncase/splitP def_c' : {1}c _ _ / y_in_c => [c1 c2].\nmove: uniq_c. rewrite def_c' /= cat_uniq has_sym has_rcons mem_cat mem_rcons rcons_uniq.\nrewrite !inE (negbTE xDy) !negb_or /= -disjoint_has -!andbA disjoint_sym.\ncase/and5P => x_c1 x_c2 y_c1 uniq_c1 /and3P [y_c2 dis_c1_c2 uniq_c2].\nmove: path_p; rewrite rcons_path /= => /andP [path_p /eqP lst_p].\n(* Obtain contour connecting [c1] and [c2] *)\nhave [u [v] [q] [path_q u_c v_c uniq_q disj_q]]: \n  exists u v q, [/\\ path clink u (rcons q v), u \\in c2, v \\in c1, uniq q & [disjoint q & [predU cface x & p]]].\n{  have [u [u_c1 Hu]] : exists u, u \\in c1 /\\ ~~ cnode x u. {\n     destruct c1 as [|a ?]; move: cycle_c cn_xy; rewrite def_c'.\n     - case/andP => /eqP <- _. by rewrite (negbTE (loopless_face _ _ _)). \n     - rewrite rcons_cons /= rcons_path => /and3P [/eqP<- _ _]. \n       exists (face x). by rewrite mem_head loopless_face. }\n   have [v [v_c2 Hv]] : exists v, v \\in c2 /\\ ~~ cnode x v. { \n     elim/last_ind : c2 def_c' cycle_c cn_xy {x_c2 y_c2 dis_c1_c2 uniq_c2} => [|? a _] /= ->. \n     - rewrite cats0 /= rcons_path last_rcons => /andP [_ /eqP <-]. \n       by rewrite cnodeC (negbTE (loopless_face _ _ _)). \n     - rewrite !(rcons_path,cat_path) /= -!andbA last_cat !last_rcons => /and5P [_ _ _ _ /eqP E ?].\n       exists (finv face x). by rewrite -E finv_f // mem_rcons mem_head cnodeC loopless_face. }\n   have uDv : v != u. \n   { apply: contraTneq dis_c1_c2 => ?; subst. by apply/pred0Pn; exists u. }\n   have [q [pth_q uniq_q sub_q]] := @connect_inE _ _ _ _ _ uDv (tcG x v u Hv Hu).\n   have [u0 [v0] [q0] [A B C D E]] := disjoint_subpath  v_c2 u_c1 pth_q dis_c1_c2.\n   exists u0; exists v0; exists q0; split => //. \n   - apply: subseq_uniq uniq_q. apply: subseq_trans D. \n     exact: subseq_trans (subseq_rcons _ _) (subseq_cons _ _).\n   - move/mem_subseq in D. \n     apply/disjointP => z in_q0; apply/negP; rewrite !inE negb_or fconnect_orbit def_c.\n     have Nz k : cnode y k -> z != k. \n     { move => Nyk. have:= connect_trans cn_xy Nyk.\n       apply contraTneq => <-. by apply/sub_q/D; rewrite !(inE,mem_rcons) in_q0. }\n     rewrite def_c' !(inE,mem_rcons,mem_cat) !negb_or !Nz 1?cnodeC //= -negb_or orbC. \n     move: (disjointFr E in_q0); rewrite inE => -> /=. \n     apply: contraTN (eqxx z) => z_p; apply/Nz. \n     rewrite -same_fconnect_finv //. \n     move/path_connect in path_p. by apply/path_p; rewrite !inE z_p. }\ncase/splitP def_c2 : {1}c2 _ _ / (u_c) => [c21 c22]. \npose mp := rcons p x ++ rcons c1 y ++ rcons c21 u ++ q.\nsuff: Moebius_path mp by apply/negP; exact: planarP.\nmove: path_q; rewrite rcons_path => /andP [path_q lst_q].\nhave/andP [dis_q_f dis_q_p] : [disjoint q & (x::c)] && [disjoint p & q].\n{ move: disj_q. rewrite disjoint_sym disjointU => /andP [A ->]; rewrite andbT disjoint_sym.\n  by apply: disjointWl A; apply/subsetP => ?; rewrite -def_c -fconnect_orbit. }\nrewrite /mp headI /Moebius_path -{2}headI /=.\napply/and3P; split.\n- suff: uniq (rcons p x ++ c ++ q). \n  { apply: subseq_uniq. apply: cat_subseq => //. rewrite catA. apply: cat_subseq => //.\n    rewrite def_c' def_c2. apply: cat_subseq => //. exact: prefix_subseq. }\n  rewrite -cats1 -catA [[:: x] ++ _ ++ _]catA cat1s -def_c.\n  rewrite cat_uniq has_cat negb_or -!disjoint_has uniq_p /=.\n  rewrite ![[disjoint _ & p]]disjoint_sym dis_q_p (disjointWr _ disj_p). \n  2: by apply/subsetP => z; rewrite -fconnect_orbit.\n  rewrite cat_uniq orbit_uniq -disjoint_has disjoint_sym uniq_q /= andbT.\n  by rewrite disjoint_sym def_c.\n- rewrite !catA cat_path !last_cat last_rcons path_q andbT -catA.\n  rewrite cat_path last_head_behead (_ : path _ _ _) /=.\n  + move/(sub_path sub_face_clink) : cycle_c. \n    by rewrite def_c' def_c2 !rcons_cat catA [in X in X -> _]cat_path => /andP [-> _].\n  + move/(sub_path sub_node_clink): path_p lst_p. destruct p as [|z p] => //= /andP [A B] <-.\n    by rewrite rcons_path B -{1}[last z p](f_finv nodeI) clinkN.\n- rewrite 3!last_cat last_rcons. \n  have -> : node (head x p) = y. \n  { move: path_p lst_p. destruct p as [|z p]=> /= [_ <-|/andP[/eqP <- _] _]; exact: f_finv. }\n  suff -> : finv node (last u q) = v. \n  { by rewrite !mem2_cat (_ : mem2 (rcons c1 y) v y) // -cats1 mem2_cat v_c !inE eqxx. }\n  case/clinkP: lst_q => [->|def_v]; first by rewrite ?finv_f. \n  case: notF. (* the last step of [u::rcons q v] cannot be an f-step *)\n  have: finv face v \\in x::c1. \n  { have : fpath face x c1. \n    { move: cycle_c. rewrite def_c' -cat1s catA /= rcons_cat cat_path rcons_path. by case: (fpath _ _ c1). }\n    case/splitP : v_c => [p1 p2 _]. rewrite cat_path !rcons_path last_rcons -andbA /=.\n    case/and3P => _ /eqP <- _. by rewrite finv_f // -cats1 -catA /= -cat_cons mem_cat  mem_last. }\n  rewrite -{}def_v finv_f //. case/last_memE => [|[z Z1]].\n  + rewrite inE (disjointFr dis_c1_c2) // orbF => E. by rewrite -(eqP E) u_c in x_c2.\n  + rewrite inE; case/predU1P => [?|H].\n    * subst z. by rewrite (disjointFl dis_q_f) // mem_head in Z1.\n    * by rewrite (disjointFl dis_q_f) // def_c' !(inE,mem_rcons,mem_cat) H in Z1. \nQed.\n\n", "meta": {"author": "coq-community", "repo": "graph-theory", "sha": "18bdabc919f6b20946f40cd5d4fbb5143c46a2bf", "save_path": "github-repos/coq/coq-community-graph-theory", "path": "github-repos/coq/coq-community-graph-theory/graph-theory-18bdabc919f6b20946f40cd5d4fbb5143c46a2bf/theories/planar/hcycle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6686491554062949}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(***********************************************************************\n    Summation.v from Z to Z\n *********************************************************************)\nRequire Import Arith.\nRequire Import ArithRing.\nRequire Import ListAux.\nRequire Import ZArith.\nRequire Import Lia.\nRequire Import Iterator.\nRequire Import ZProgression.\n\n\nOpen Scope Z_scope.\n(* Iterated Sum *)\n\nDefinition Zsum :=\n   fun n m f =>\n   if Zle_bool n m\n     then iter 0 f Zplus (progression Z.succ n (Z.abs_nat  ((1 + m) - n)))\n     else iter 0 f Zplus (progression Z.pred n (Z.abs_nat  ((1 + n) - m))).\nGlobal Hint Unfold Zsum : core.\n\nLemma Zsum_nn: forall n f,  Zsum n n f = f n.\nintros n f; unfold Zsum; rewrite Zle_bool_refl.\nreplace ((1 + n) - n) with 1; auto with zarith.\nsimpl; ring.\nQed.\n\nTheorem permutation_rev: forall (A:Set) (l : list A),  permutation (rev l) l.\nintros a l; elim l; simpl; auto.\nintros a1 l1 Hl1.\napply permutation_trans with (cons a1 (rev l1)); [|auto].\nchange (permutation (rev l1 ++ (a1 :: nil)) (app (cons a1 nil) (rev l1))); auto.\nQed.\n\nLemma Zsum_swap: forall (n m : Z) (f : Z ->  Z),  Zsum n m f = Zsum m n f.\nProof.\n  intros n m f; revert n m.\n  cut (forall n m, n < m -> Zsum n m f = Zsum m n f).\n  { intros L n m.\n    destruct (Ztrichotomy n m) as [ LT | [ -> | GT ] ].\n    - apply L, LT.\n    - reflexivity.\n    - symmetry; apply L, Z.gt_lt, GT. }\nintros n m n_lt_m; unfold Zsum.\nreplace (m <=? n) with false by (symmetry; apply Z.leb_gt, n_lt_m).\nreplace (n <=? m) with true by (symmetry; apply Z.leb_le, Z.lt_le_incl, n_lt_m).\napply iter_permutation; auto with zarith.\napply permutation_trans\n     with (rev (progression Z.succ n (Z.abs_nat  ((1 + m) - n)))).\napply permutation_sym; apply permutation_rev.\nrewrite Zprogression_opp; auto with zarith.\nreplace (n + Z_of_nat (pred (Z.abs_nat  ((1 + m) - n)))) with m; auto.\nreplace (Z.abs_nat  ((1 + m) - n)) with (S (Z.abs_nat  (m - n))).\nsimpl.\nrewrite inj_Zabs_nat.\nrewrite Z.abs_eq; auto with zarith.\nlia.\nQed.\n\nLemma Zsum_split_up:\n forall (n m p : Z) (f : Z ->  Z),\n ( n <= m < p ) ->  Zsum n p f = Zsum n m f + Zsum (m + 1) p f.\nintros n m p f [H H0].\ncase (Zle_lt_or_eq _ _ H); clear H; intros H.\nunfold Zsum; (repeat rewrite Zle_imp_le_bool); auto with zarith.\nassert (H1: n < p).\napply Z.lt_trans with ( 1 := H ); auto with zarith.\nassert (H2: m < 1 + p).\napply Z.lt_trans with ( 1 := H0 ); auto with zarith.\nassert (H3: n < 1 + m).\napply Z.lt_trans with ( 1 := H ); auto with zarith.\nassert (H4: n < 1 + p).\napply Z.lt_trans with ( 1 := H1 ); auto with zarith.\nreplace (Z.abs_nat  ((1 + p) - (m + 1)))\n     with (minus (Z.abs_nat  ((1 + p) - n)) (Z.abs_nat  ((1 + m) - n))).\napply iter_progression_app. 1-3: auto with zarith.\napply inj_le_rev.\n(repeat rewrite inj_Zabs_nat); auto with zarith.\n(repeat rewrite Z.abs_eq); auto with zarith.\nrewrite next_n_Z.\nrewrite inj_Zabs_nat.\nrewrite Z.abs_eq; auto with zarith.\napply inj_eq_rev.\nrewrite inj_minus1.\n(repeat rewrite inj_Zabs_nat).\n(repeat rewrite Z.abs_eq); auto with zarith.\napply inj_le_rev.\n(repeat rewrite inj_Zabs_nat).\n(repeat rewrite Z.abs_eq); auto with zarith.\nsubst m.\nrewrite Zsum_nn; auto with zarith.\nunfold Zsum; generalize (Zle_cases n p); generalize (Zle_cases (n + 1) p);\n case (Zle_bool n p); case (Zle_bool (n + 1) p); auto with zarith.\nintros H1 H2.\nreplace (Z.abs_nat  ((1 + p) - n)) with (S (Z.abs_nat  (p - n))).\nreplace (n + 1) with (Z.succ n) by auto with zarith.\nreplace ((1 + p) - Z.succ n) with (p - n); auto with zarith.\napply inj_eq_rev.\nrewrite inj_S; (repeat rewrite inj_Zabs_nat).\n(repeat rewrite Z.abs_eq); auto with zarith.\nQed.\n\nLemma Zsum_S_left:\n forall (n m : Z) (f : Z ->  Z), n < m ->  Zsum n m f = f n + Zsum (n + 1) m f.\nintros n m f H; rewrite (Zsum_split_up n n m f); auto with zarith.\nrewrite Zsum_nn; auto with zarith.\nQed.\n\nLemma Zsum_S_right:\n forall (n m : Z) (f : Z ->  Z),\n n <= m ->  Zsum n (m + 1) f = Zsum n m f  + f (m + 1).\nintros n m f H; rewrite (Zsum_split_up n m (m + 1) f); auto with zarith.\nrewrite Zsum_nn; auto with zarith.\nQed.\n\nLemma Zsum_split_down:\n forall (n m p : Z) (f : Z ->  Z),\n ( p < m <= n ) ->  Zsum n p f = Zsum n m f  + Zsum (m - 1) p f.\nintros n m p f [H H0].\ncase (Zle_lt_or_eq p (m - 1)); auto with zarith; intros H1.\npattern m at 1; replace m with ((m - 1) + 1) by auto with zarith.\nrepeat rewrite (Zsum_swap n).\nrewrite (Zsum_swap (m - 1)).\nrewrite Zplus_comm.\napply Zsum_split_up; auto with zarith.\nsubst p.\nrepeat rewrite (Zsum_swap n).\nrewrite Zsum_nn.\nunfold Zsum; (repeat rewrite Zle_imp_le_bool); auto with zarith.\nreplace (Z.abs_nat   ((1 + n) - (m - 1))) with (S (Z.abs_nat   (n - (m - 1)))).\nrewrite Zplus_comm.\nreplace (Z.abs_nat   ((1 + n) - m)) with (Z.abs_nat  (n - (m - 1))).\npattern m at 4; replace m with (Z.succ (m - 1)); auto with zarith.\napply f_equal with ( f := Z.abs_nat  ); auto with zarith.\napply inj_eq_rev.\nrewrite inj_S.\n(repeat rewrite inj_Zabs_nat).\n(repeat rewrite Z.abs_eq); auto with zarith.\nQed.\n\n\nLemma Zsum_ext:\n forall (n m : Z) (f g : Z ->  Z),\n n <= m ->\n (forall (x : Z), ( n <= x <= m ) ->  f x = g x) ->  Zsum n m f = Zsum n m g.\nintros n m f g HH H.\nunfold Zsum; auto.\nunfold Zsum; (repeat rewrite Zle_imp_le_bool); auto with zarith.\napply iter_ext; auto with zarith.\nintros a H1; apply H; auto; split.\napply Zprogression_le_init with ( 1 := H1 ).\ncut (a < Z.succ m); auto with zarith.\nreplace (Z.succ m) with (n + Z_of_nat (Z.abs_nat  ((1 + m) - n))).\napply Zprogression_le_end; auto with zarith.\nrewrite inj_Zabs_nat.\n(repeat rewrite Z.abs_eq); auto with zarith.\nQed.\n\nLemma Zsum_add:\n forall (n m : Z) (f g : Z ->  Z),\n  Zsum n m f  + Zsum n m g = Zsum n m (fun (i : Z) => f i + g i).\nintros n m f g; unfold Zsum; case (Zle_bool n m); apply iter_comp;\n auto with zarith.\nQed.\n\nLemma Zsum_times:\n forall n m x f,  x * Zsum n m f = Zsum n m (fun i=> x * f i).\nintros n m x f.\nunfold Zsum. case (Zle_bool n m); intros; apply iter_comp_const with (k := (fun y : Z => x * y)); auto with zarith.\nQed.\n\nLemma inv_Zsum:\n forall (P : Z ->  Prop) (n m : Z) (f : Z ->  Z),\n n <= m ->\n P 0 ->\n (forall (a b : Z), P a -> P b ->  P (a + b)) ->\n (forall (x : Z), ( n <= x <= m ) ->  P (f x)) ->  P (Zsum n m f).\nintros P n m f HH H H0 H1.\nunfold Zsum; rewrite Zle_imp_le_bool; auto with zarith; apply iter_inv; auto.\nintros x H3; apply H1; auto; split.\napply Zprogression_le_init with ( 1 := H3 ).\ncut (x < Z.succ m); auto with zarith.\nreplace (Z.succ m) with (n + Z_of_nat (Z.abs_nat  ((1 + m) - n))).\napply Zprogression_le_end; auto with zarith.\nrewrite inj_Zabs_nat.\n(repeat rewrite Z.abs_eq); auto with zarith.\nQed.\n\n\nLemma Zsum_pred:\n forall (n m : Z) (f : Z ->  Z),\n  Zsum n m f = Zsum (n + 1) (m + 1) (fun (i : Z) => f (Z.pred i)).\nintros n m f.\nunfold Zsum.\ngeneralize (Zle_cases n m); generalize (Zle_cases (n + 1) (m + 1));\n case (Zle_bool n m); case (Zle_bool (n + 1) (m + 1)); auto with zarith.\nreplace ((1 + (m + 1)) - (n + 1)) with ((1 + m) - n); auto with zarith.\nintros H1 H2; cut (exists c , c = Z.abs_nat  ((1 + m) - n) ).\nintros [c H3]; rewrite <- H3.\ngeneralize n; elim c; auto with zarith; clear H1 H2 H3 c n.\nintros c H n; simpl; eq_tac; auto with zarith.\neq_tac; unfold Z.pred; auto with zarith.\nreplace (Z.succ (n + 1)) with (Z.succ n + 1); auto with zarith.\nexists (Z.abs_nat  ((1 + m) - n)); auto.\nreplace ((1 + (n + 1)) - (m + 1)) with ((1 + n) - m); auto with zarith.\nintros H1 H2; cut (exists c , c = Z.abs_nat  ((1 + n) - m) ).\nintros [c H3]; rewrite <- H3.\ngeneralize n; elim c; auto with zarith; clear H1 H2 H3 c n.\nintros c H n; simpl; (eq_tac; auto with zarith).\neq_tac; unfold Z.pred; auto with zarith.\nreplace (Z.pred (n + 1)) with (Z.pred n + 1); auto with zarith.\nunfold Z.pred; auto with zarith.\nexists (Z.abs_nat  ((1 + n) - m)); auto.\nQed.\n\nTheorem Zsum_c:\n forall (c p q : Z), p <= q ->  Zsum p q (fun x => c) = ((1 + q) - p) * c.\nintros c p q Hq; unfold Zsum.\nrewrite Zle_imp_le_bool; auto with zarith.\npattern ((1 + q) - p) at 2.\n rewrite <- Z.abs_eq; auto with zarith.\n rewrite <- inj_Zabs_nat; auto with zarith.\ncut (exists r , r = Z.abs_nat  ((1 + q) - p) );\n [intros [r H1]; rewrite <- H1 | exists (Z.abs_nat  ((1 + q) - p))]; auto.\ngeneralize p; elim r; auto with zarith.\nintros n H p0; replace (Z_of_nat (S n)) with (Z_of_nat n + 1).\nsimpl; rewrite H; ring.\nrewrite inj_S; auto with zarith.\nQed.\n\nTheorem Zsum_Zsum_f:\n forall (i j k l : Z) (f : Z -> Z ->  Z),\n i <= j ->\n k < l ->\n  Zsum i j (fun x => Zsum k (l + 1) (fun y => f x y)) =\n  Zsum i j (fun x => Zsum k l (fun y => f x y) + f x (l + 1)).\nintros; apply Zsum_ext; intros; auto with zarith.\nrewrite Zsum_S_right; auto with zarith.\nQed.\n\nTheorem Zsum_com:\n forall (i j k l : Z) (f : Z -> Z ->  Z),\n  Zsum i j (fun x => Zsum k l (fun y => f x y)) =\n  Zsum k l (fun y => Zsum i j (fun x => f x y)).\nintros; unfold Zsum; case (Zle_bool i j); case (Zle_bool k l); apply iter_com;\n auto with zarith.\nQed.\n\nTheorem Zsum_le:\n forall (n m : Z) (f g : Z ->  Z),\n n <= m ->\n (forall (x : Z), ( n <= x <= m ) ->  (f x <= g x )) ->\n  (Zsum n m f <= Zsum n m g ).\nintros n m f g Hl H.\nunfold Zsum; rewrite Zle_imp_le_bool; auto with zarith.\nunfold Zsum;\n cut\n  (forall x,\n   In x (progression Z.succ n (Z.abs_nat  ((1 + m) - n))) ->  ( f x <= g x )).\nelim (progression Z.succ n (Z.abs_nat  ((1 + m) - n))); simpl; auto with zarith.\nintros x H1; apply H; split.\napply Zprogression_le_init with ( 1 := H1 ); auto.\ncut (x < m + 1); auto with zarith.\nreplace (m + 1) with (n + Z_of_nat (Z.abs_nat  ((1 + m) - n))).\napply Zprogression_le_end; auto with zarith.\nrewrite inj_Zabs_nat.\nrewrite Z.abs_eq; auto with zarith.\nQed.\n\nTheorem iter_le:\nforall (f g: Z -> Z)  l, (forall a, In a l -> f a <= g a) ->\n  iter 0 f Zplus l <= iter 0 g Zplus l.\nintros f g l; elim l; simpl; auto with zarith.\nQed.\n\nTheorem Zsum_lt:\n forall n m f g,\n (forall x, n <= x -> x <= m ->  f x <= g x) ->\n (exists x, n <= x /\\ x <= m /\\  f x < g x) ->\n  Zsum n m f < Zsum n m g.\nintros n m f g H (d, (Hd1, (Hd2, Hd3))); unfold Zsum; rewrite Zle_imp_le_bool; auto with zarith.\ncut (In d (progression  Z.succ n (Z.abs_nat  (1 + m - n)))).\ncut (forall x, In x (progression Z.succ n (Z.abs_nat  (1 + m - n)))->  f x <= g x).\nelim (progression  Z.succ n (Z.abs_nat  (1 + m - n))); simpl; auto with zarith.\nintros a l Rec  H0 [H1 | H1]; subst; auto.\napply Z.le_lt_trans with (f d + iter 0 g Zplus l); auto with zarith.\napply Zplus_le_compat_l.\napply iter_le; auto.\napply Z.lt_le_trans with (f a + iter 0 g Zplus l); auto with zarith.\nintros x H1; apply H.\napply Zprogression_le_init with ( 1 := H1 ); auto.\ncut (x < m + 1); auto with zarith.\nreplace (m + 1) with (n + Z_of_nat (Z.abs_nat  ((1 + m) - n))).\napply Zprogression_le_end with ( 1 := H1 ); auto with arith.\nrewrite inj_Zabs_nat.\nrewrite Z.abs_eq; auto with zarith.\napply in_Zprogression.\nrewrite inj_Zabs_nat.\nrewrite Z.abs_eq; auto with zarith.\nQed.\n\nTheorem Zsum_minus:\n forall n m f g,  Zsum n m f - Zsum n m g = Zsum n m (fun x => f x - g x).\nintros n m f g; apply trans_equal with (Zsum n m f + (-1) * Zsum n m g); auto with zarith.\nrewrite Zsum_times; rewrite Zsum_add; auto with zarith.\nQed.\n", "meta": {"author": "thery", "repo": "coqprime", "sha": "431d7a66877cbe8688fc8864ef892369401440e1", "save_path": "github-repos/coq/thery-coqprime", "path": "github-repos/coq/thery-coqprime/coqprime-431d7a66877cbe8688fc8864ef892369401440e1/src/Coqprime/Z/ZSum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6686491504558355}}
{"text": "Theorem ex1_4: forall a b c : Prop,\n              forall B : (b -> c) -> (a -> b) -> a -> c,\n              forall C : (a -> b -> c) -> b -> a -> c,\n              forall W : (a -> a -> b) -> a -> b,\n              ((a -> b -> c) -> (a -> b) -> a -> c).\nProof.\n  intros. apply B. intro. apply C.\n  assumption. assumption. assumption. apply W.\n  intro. assumption. assumption.\nQed.\n\nPrint ex1_4.\n\nTheorem ex2_2: forall A B C D : Prop,\n               (A -> B) /\\ (C -> D) /\\\n               (A \\/ C) /\\ ~(B /\\ D) -> \n               (B -> A) /\\ (D -> C).\nProof.\n  Require Import Coq.Program.Basics.\n  intros. split. decompose [and] H.\n  elim H1. apply const. intros.\n  elim H4. split.\n  assumption. apply (H2 H3).\n  decompose [and] H. elim H1.\n  intros. elim H4.\n  split. apply (H0 H3). assumption.\n  apply const.\nQed.\n\nTheorem ex3_11: forall P Q R : Prop,\n                (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n  intros. repeat apply H || apply H0 || apply H1.\nQed.\n\nTheorem ex3_12: forall P Q R : Prop,\n                (P -> Q -> R) -> (Q -> P -> R).\nProof.\n  intros. repeat apply H || apply H0 || apply H1.\nQed.\n\nTheorem ex3_13: forall P Q R : Prop,\n                (P -> R) -> P -> Q -> R.\nProof.\n  intros. repeat apply H || apply H0 || apply H1.\nQed.\n\nTheorem ex3_14: forall P Q : Prop,\n                (P -> P -> Q) -> P -> Q.\nProof.\n  intros. repeat apply H || apply H0 || apply H1.\nQed.\n\nTheorem ex3_15: forall P Q : Prop,\n                (P -> Q) -> (P -> P -> Q).\nProof.\n  intros. repeat apply H || apply H0 || apply H1.\nQed.\n\nTheorem ex3_16: forall P Q R S : Prop,\n                (P -> Q) -> (P -> R) -> (Q -> R -> S) -> P -> S.\nProof.\n  intros. repeat apply H || apply H0 || apply H1 || apply H2.\nQed.\n\nTheorem ex3_17: forall P Q : Prop,\n                ((((P -> Q) -> P) -> P) -> Q) -> Q.\nProof.\n  intros. repeat first [apply H1;intros | apply H0;intros | apply H;intros].\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-00/Ed2409.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6686491457427063}}
{"text": "(* \n\n  Material para o encontro do\n  dia 17/03/2023. \n  \n  Unicamp. GLM/Grupo_Coq. \n\n  Autor: Renato Reis Leme\n  Web: https://renatoleme.github.io/\n  \n  São Paulo, 16 de março de 2023.\n*)\n\nRequire Import String.\n\nInductive string_or_nat := \n| String : string -> string_or_nat\n| Nat : nat -> string_or_nat.\n\nCheck String \"Hello World!\".\nCheck Nat 23.\n\n(* Record type (each of) *)\n\nInductive nat_string_pair :=\n| Pair : (nat * string) -> nat_string_pair.\n\nOpen Scope string_scope.\n\nCheck Pair (23 , \"Hello World!\").\n\nClose Scope string_scope.\n\n(**)\n\nInductive dia : Type := \n| Segunda\n| Terca\n| Quarta\n| Quinta\n| Sexta\n| Sabado\n| Domingo.\n\nCheck Segunda.\nCheck Domingo.\nCheck Sexta.\n\nDefinition proximo_dia_util \n  (d : dia) : dia :=\n  match d with\n  | Segunda => Terca\n  | Terca => Quarta\n  | Quarta => Quinta\n  | Quinta => Sexta\n  | Sexta => Segunda\n  | Sabado => Segunda\n  | Domingo => Segunda\n  end.\n  \nCompute proximo_dia_util \n(proximo_dia_util Quarta).\n\nExample teste_proximo_dia_util :\n  (proximo_dia_util \n  (proximo_dia_util Terca)) = Quinta.\nProof.\n  simpl. reflexivity.\nQed.\n\n(**)\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 (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  \nExample test_orb1: \n(orb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb2: \n(orb false false) = false.\nProof. simpl. reflexivity. Qed.\nExample test_orb3: \n(orb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb4: \n(orb true true) = true.\nProof. simpl. reflexivity. Qed.\n\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_orb_notation : \nfalse || true || false || \nfalse || false = true.\nProof. simpl. reflexivity. Qed.\n\nDefinition negb' (b : bool) : bool :=\n  if b then false\n  else true.\n\nDefinition andb' (a b : bool) : bool :=\n  if a then b\n  else false.\n\nDefinition orb' (a b : bool) : bool :=\n  if a then true\n  else b.\n  \nCheck true.\nCheck (negb true) : bool.\n\n(**)\n\nInductive rgb : Type :=\n| red\n| green\n| blue.\n\nInductive color : Type :=\n| black\n| white\n| primary (p : rgb).\n\nDefinition monochrome (c : color) : bool :=\n  match c with\n  | black => true\n  | white => true\n  | primary p => false\n  end.\n  \nDefinition isred (c : color) : bool :=\n  match c with\n  | black => false\n  | white => false\n  | primary red => true\n  | primary _ => false\n  end.", "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/sf/1-basics/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.8757869835428965, "lm_q1q2_score": 0.6686491422671917}}
{"text": "(**\n Written by Sosuke Moriguchi (@chiguri on Twitter)\n             Kwansei Gakuin University\n**)\n\n\n(* 全体において、well-founded inductionを使わないことを目標とした *)\nSection tpp2014.\n\nRequire Import Arith.\n\n(********************************** (1)の準備 **************************************)\nFixpoint mod3 n :=\nmatch n with\n| S (S (S m)) => mod3 m\n| S (S O) => 2\n| S O => 1\n| O => 0\nend.\n\n\n\n(* mod3の動きに基づく帰納法 *)\nLemma mod3_ind : forall P : nat -> Prop,\n P 0 ->\n P 1 ->\n P 2 ->\n (forall n, P n -> P (S (S (S n)))) ->\n  forall n, P n.\nintros P H0 H1 H2 H.\n fix f 1.\n  intro.\n   destruct n as [ | [ | [ | n]]].\n    apply H0.\n    apply H1.\n    apply H2.\n    apply H; apply f.\nQed.\n\n\n\nLemma tripleadd_mult3 : forall n, n + n + n = n * 3.\nintro; rewrite mult_comm; simpl.\n rewrite plus_comm; f_equal.\n  f_equal.\n   rewrite plus_comm; auto.\nQed.\n\n\n\nLemma mod3_case : forall n, mod3 n = 0 \\/ mod3 n = 1 \\/ mod3 n = 2.\napply mod3_ind; auto.\nQed.\n\n\n\nLemma mult3_mod3 : forall n, mod3 (n * 3) = 0.\nintro n; induction n; auto.\nQed.\n\nLemma mult3_add_mod3 : forall m n, mod3 (n * 3 + m) = mod3 m.\ninduction n; auto.\nQed.\n\n\nLemma mod3_add_mod3 : forall m n, mod3 (m + n) = mod3 (mod3 m + mod3 n).\nintro n; apply mod3_ind with (n:=n); clear n; intros.\n simpl.\n  case mod3_case with n; intro.\n   rewrite H; auto.\n   destruct H as [H | H]; rewrite H; auto.\n simpl (mod3 1).\n  revert n; apply mod3_ind; auto.\n revert n; apply mod3_ind; auto.\n simpl; rewrite H; auto.\nQed.\n\n\n\n\n\n(*  (1): a^2 mod 3 = 0 or 1 *)\nTheorem Prob1 : forall a, mod3 (a * a) = 0 \\/ mod3 (a * a) = 1.\napply mod3_ind; intros; auto; destruct H.\n left; simpl.\n  rewrite plus_comm; simpl.\n   rewrite plus_comm; simpl.\n    rewrite plus_assoc; rewrite plus_comm; simpl.\n     rewrite plus_comm; rewrite plus_assoc.\n      rewrite tripleadd_mult3.\n       rewrite mult3_add_mod3.\n        rewrite mult_comm; simpl.\n         repeat (rewrite plus_assoc).\n          rewrite tripleadd_mult3.\n           rewrite mult3_add_mod3.\n            auto.\n right; simpl.\n  rewrite plus_comm; simpl.\n   rewrite plus_comm; simpl.\n    rewrite plus_assoc; rewrite plus_comm; simpl.\n     rewrite plus_comm; rewrite plus_assoc.\n      rewrite tripleadd_mult3.\n       rewrite mult3_add_mod3.\n        rewrite mult_comm; simpl.\n         repeat (rewrite plus_assoc).\n          rewrite tripleadd_mult3.\n           rewrite mult3_add_mod3.\n            auto.\nQed.\n\n(* 全く同じやり方なのでLtacにすればもっと簡単に終わる *)\n\n\n\n\n\n(********************************** (2)の準備 **************************************)\n\nLemma square_mod3_0 : forall x, mod3 (x * x) = 0 -> mod3 x = 0.\nintro x; apply mod3_ind with (n := x); intros; auto.\n simpl in H; discriminate.\n simpl in H0.\n  rewrite plus_comm in H0; simpl in H0.\n   rewrite plus_comm in H0; simpl in H0.\n    rewrite plus_assoc in H0; rewrite plus_comm in H0; simpl in H0.\n     rewrite plus_comm in H0; rewrite plus_assoc in H0.\n      rewrite tripleadd_mult3 in H0.\n       rewrite mult3_add_mod3 in H0.\n        rewrite mult_comm in H0; simpl in *.\n         repeat (rewrite plus_assoc in H0).\n          rewrite tripleadd_mult3 in H0.\n           rewrite mult3_add_mod3 in H0.\n            auto.\nQed.\n\n\n\nLemma mod3_0_mult3 : forall n, mod3 n = 0 -> exists m, n = 3 * m.\nintro n; apply mod3_ind with (n := n); intuition.\n exists 0; auto.\n simpl in H; discriminate.\n simpl in H; discriminate.\n destruct H1.\n  exists (S x).\n   rewrite H; simpl.\n    f_equal.\n     rewrite (plus_comm _ (S _)); simpl; f_equal.\n      rewrite (plus_comm _ (S _)); simpl; f_equal.\n       rewrite (plus_comm _ 0); simpl; apply plus_assoc.\nQed.\n\n\nLemma mult3_eq : forall m n, 3 * m = 3 * n -> m = n.\n (* もちろん3でなくても0でなければ成り立つ。使わないからこれだけ *)\nintros m n; repeat (rewrite (mult_comm 3)); revert n; induction m; intros.\n destruct n.\n  auto.\n   simpl in H; inversion H.\n destruct n; simpl in H; inversion H.\n  f_equal; auto.\nQed.\n\n\n\n\n\n\n(*  (2)の一部： a^2 + b^2 = 3c^2ならば 3|a^2 かつ 3|b^2   めんどくさいのでNotationはなし *)\nLemma Prob2_ab : forall a b c, a * a + b * b = 3 * c * c -> mod3 (a * a) = 0 /\\ mod3 (b * b) = 0.\nintros.\n rewrite <- mult_assoc in H; rewrite (mult_comm 3) in H.\n  assert (mod3 (a * a + b * b) = 0).\n   rewrite H; apply mult3_mod3.\n   rewrite mod3_add_mod3 in H0.\n    case Prob1 with a; case Prob1 with b; intros; auto;\n     rewrite H1 in H0; rewrite H2 in H0; simpl in H0; discriminate.\nQed.\n\n\n(*  (2)の一部： a^2 + b^2 = 3c^2ならば 3|c^2 *)\nLemma Prob2_c : forall a b c, a * a + b * b = 3 * c * c -> mod3 (c * c) = 0.\nintros.\n destruct (Prob2_ab a b c H).\n  apply square_mod3_0 in H0.\n   apply square_mod3_0 in H1.\n    apply mod3_0_mult3 in H0.\n      apply mod3_0_mult3 in H1.\n       destruct H0; destruct H1; subst.\n        repeat (rewrite <- mult_assoc in H).\n         rewrite <- mult_plus_distr_l in H.\n          apply mult3_eq in H.\n           rewrite <- H.\n            repeat (rewrite (mult_comm 3)).\n             repeat (rewrite mult_assoc).\n              repeat (rewrite <- (mult_comm 3)).\n               rewrite <- mult_plus_distr_l.\n                rewrite mult_comm.\n                 apply mult3_mod3.\nQed.\n\n\n(*  (2)  *)\nTheorem Prob2 : forall a b c, a * a + b * b = 3 * c * c -> mod3 (a * a) = 0 /\\ mod3 (b * b) = 0 /\\ mod3 (c * c) = 0.\nintros.\n destruct Prob2_ab with a b c as [H0 H1]; assert (H2 := Prob2_c _ _ _ H); auto.\nQed.\n\n\n\n\n\n\n\n(********************************** (3)の準備 **************************************)\n\n\nFixpoint div3 n :=\nmatch n with\n| S (S (S m)) => S (div3 m)\n| _ => 0\nend.\n\n\n\nLemma div3_mod3 : forall n, n = (div3 n) * 3 + mod3 n.\napply mod3_ind; intros; auto.\n simpl.\n  repeat f_equal; auto.\nQed.\n\n\n\n\n(* div3に基づく帰納法の準備：なお、well-founded inductionを使うならば0<nでdiv3 n < nを示せば十分 *)\nFixpoint exp3 n :=\nmatch n with\n| O => 1\n| S n' => 3 * exp3 n'\nend.\n\n\n(* 3で割って0になるまでの回数：この第二引数で帰納法を行う *)\nInductive div3num : nat -> nat -> Prop :=\n| div3_O : div3num 0 0\n| div3_n : forall m n, exp3 n <= m -> m < exp3 (S n) -> div3num m (S n).\n\n\n\nLemma exp3_not0 : forall n, exp3 n <> 0.\ninduction n.\n simpl; intro; inversion H.\n simpl.\n  intro H; apply IHn.\n   destruct (plus_is_O _ _ H); auto.\nQed.\n\n\nLemma exp3_lt : forall n, exp3 n < exp3 (S n).\nintro; simpl.\n case_eq (exp3 n); intros.\n  elim (exp3_not0 _ H).\n  unfold lt.\n   simpl.\n    rewrite plus_comm; simpl.\n     repeat (apply le_n_S).\n      rewrite <- plus_assoc; apply le_plus_l.\nQed.\n\n\n\nLemma div3num_ex : forall n, exists m, div3num n m.\ninduction n.\n exists 0.\n  constructor.\n destruct IHn.\n  inversion H.\n   exists 1.\n    constructor; simpl; auto.\n   unfold lt in H1.\n    apply le_lt_or_eq in H1.\n     subst; destruct H1.\n      exists (S n0); constructor.\n       apply le_trans with n; auto.\n       auto.\n      exists (S (S n0)).\n       constructor.\n        rewrite H1; auto.\n        rewrite H1; apply exp3_lt.\nQed.\n\n\n\n\n\nLemma mult3_div3 : forall n, div3 (3 * n) = n.\napply mod3_ind; intros; auto.\n simpl.\n  f_equal.\n   rewrite plus_comm; simpl; f_equal.\n    rewrite (plus_comm n); simpl; f_equal.\n     rewrite (plus_comm n); simpl; rewrite tripleadd_mult3.\n      rewrite mult_comm; auto.\nQed.\n\n\n\nLemma exp3_div3_pred : forall n, div3 (exp3 (S n)) = exp3 n.\nintro; unfold exp3.\n apply mult3_div3.\nQed.\n\n\n\n\nLemma div3_le : forall m n, m <= n -> div3 m <= div3 n.\nfix f 1; intros.\n destruct m as [ | [ | [ | m ]]]; try (apply le_O_n).\n  destruct n.\n   elim (le_Sn_O _ H).\n   apply le_S_n in H; destruct n.\n    elim (le_Sn_O _ H).\n    apply le_S_n in H; destruct n.\n     elim (le_Sn_O _ H).\n     simpl; apply le_n_S.\n      apply f.\n       apply le_S_n; apply H.\nQed.\n\n\nLemma div3_mult3_S : forall m, div3 (m * 3) = div3 (S (m * 3)).\nfix f 1.\n intro.\n  destruct m.\n   reflexivity.\n    simpl.\n     f_equal.\n      apply f.\nQed.\n\n\nLemma div3_mult3_SS : forall m, div3 (m * 3) = div3 (S (S (m * 3))).\nfix f 1.\n intro.\n  destruct m.\n   reflexivity.\n    simpl.\n     f_equal.\n      apply f.\nQed.\n\n\n\nLemma div3_exp3_lt : forall m n, m < exp3 (S n) -> div3 m < exp3 n.\ninduction m; intros.\n case_eq (exp3 n); intros.\n  elim (exp3_not0 _ H0).\n  unfold lt; apply le_n_S; apply le_O_n.\n rewrite (div3_mod3 m).\n  case (mod3_case m); intro.\n   rewrite H0.\n    rewrite plus_comm; simpl plus; rewrite <- div3_mult3_S.\n     rewrite mult_comm; rewrite mult3_div3.\n      apply IHm.\n       apply lt_trans with (S m); auto.\n   destruct H0.\n    rewrite H0; rewrite plus_comm; simpl plus; rewrite <- div3_mult3_SS.\n     rewrite mult_comm; rewrite mult3_div3.\n      apply IHm.\n       apply lt_trans with (S m); auto.\n    rewrite H0; rewrite plus_comm; simpl.\n     rewrite mult_comm; rewrite mult3_div3.\n      assert (m < S m).\n       auto.\n       apply (lt_trans _ _ (exp3 (S n))) in H1; auto.\n        apply IHm in H1.\n         unfold lt in H1; apply le_lt_or_eq in H1.\n          destruct H1; auto.\n           unfold lt in H.\n            rewrite (div3_mod3 m) in H.\n             rewrite plus_comm in H; rewrite H0 in H; simpl plus in H.\n              simpl exp3 in H; rewrite <- H1 in H.\n               rewrite mult_comm in H; simpl in H.\n                rewrite (plus_comm _ 0) in H; apply le_S_n in H.\n                 rewrite (plus_comm _ (S _)) in H; simpl in H; apply le_S_n in H.\n                  rewrite (plus_comm _ (S _)) in H.\n                   rewrite <- plus_assoc in H.\n                    simpl in H; apply le_S_n in H.\n                     elim (le_Sn_n _ H).\nQed.\n\n\n\n\nLemma div3num_div3_decrease : forall m n, div3num n (S m) -> div3num (div3 n) m.\nintros.\n inversion H.\n  destruct m.\n   unfold lt in *; simpl in *.\n    destruct n as [ | [ | [ | n ]]]; try constructor.\n     repeat (apply le_S_n in H3).\n      elim (le_Sn_O n H3).\n   constructor.\n    rewrite <- exp3_div3_pred; apply div3_le; auto.\n    apply div3_exp3_lt; auto.\nQed.\n\n\n\n(* div3に基づく帰納法：割ったもので証明が作れる *)\nLemma div3_ind : forall P : nat -> Prop,\n P 0 ->\n (forall n, P (div3 n) -> P n) -> forall n, P n.\nintros P H0 IH n.\n destruct (div3num_ex n).\n  revert n H; induction x; intros.\n   inversion H.\n    auto.\n   apply IH.\n    apply div3num_div3_decrease in H.\n     auto.\nQed.\n\n\n\n\n(*  (3)の一部：a = 0のみ  *)\nLemma Prob3_a : forall a b c, a * a + b * b = 3 * c * c -> a = 0.\nintro a; apply div3_ind with (n:=a); intros.\n auto.\n destruct (Prob2 n b c H0) as [H1 [H2 H3]].\n  apply square_mod3_0 in H1;\n     apply square_mod3_0 in H2;\n     apply square_mod3_0 in H3.\n   apply mod3_0_mult3 in H1;\n       apply mod3_0_mult3 in H2;\n       apply mod3_0_mult3 in H3.\n    destruct H1;\n        destruct H2;\n        destruct H3.\n     subst.\n      rewrite mult3_div3 in H.\n       assert (3 * x = 3 * 0 -> 3 * x = 0).\n        auto.\n        apply H1.\n         f_equal.\n          apply H with x0 x1.\n           repeat (rewrite <- mult_assoc in H0).\n            rewrite <- mult_plus_distr_l in H0.\n             apply mult3_eq in H0.\n              repeat (rewrite (mult_comm 3) in H0).\n               repeat (rewrite mult_assoc in H0).\n                repeat (rewrite (mult_comm _ 3) in H0).\n                 rewrite <- mult_plus_distr_l in H0.\n                  apply mult3_eq in H0.\n                   rewrite H0; apply mult_assoc.\nQed.\n\n\n\n\n(*  (3)の一部：b = 0のみ  *)\nLemma Prob3_b : forall a b c, a * a + b * b = 3 * c * c -> b = 0.\nintros.\n rewrite (Prob3_a _ _ _ H) in H.\n  clear a; revert c H; apply div3_ind with (n:=b); intros.\n   auto.\n   destruct (Prob2 _ _ _ H0) as [_ [H2 H3]].\n    simpl plus in *.\n     apply square_mod3_0 in H2;\n         apply square_mod3_0 in H3.\n      apply mod3_0_mult3 in H2;\n          apply mod3_0_mult3 in H3.\n       destruct H2; destruct H3.\n        subst.\n         rewrite mult3_div3 in H.\n          repeat (rewrite <- mult_assoc in H0).\n           apply mult3_eq in H0.\n            repeat (rewrite mult_assoc in H0).\n             repeat (rewrite (mult_comm _ 3) in H0).\n              repeat (rewrite <- mult_assoc in H0).\n               apply mult3_eq in H0.\n                rewrite mult_assoc in H0.\n                 apply H in H0.\n                  rewrite H0; auto.\nQed.\n\n\n(*  (3) a^2 + b^2 = 3c^2 ならば a = b = c = 0  *)\nTheorem Prob3 : forall a b c, a * a + b * b = 3 * c * c -> a = 0 /\\ b = 0 /\\ c = 0.\nintros.\n assert (H0 := Prob3_a _ _ _ H).\n  assert (H1 := Prob3_b _ _ _ H).\n   subst; split; auto.\n    split; auto.\n     simpl plus in H.\n      destruct c; auto.\n       simpl in H; inversion H.\nQed.\n\n\n\n\nEnd tpp2014.\n\n", "meta": {"author": "KyushuUniversityMathematics", "repo": "TPP2014", "sha": "8439769862a9619cdb4e0af1597d447c7cca2325", "save_path": "github-repos/coq/KyushuUniversityMathematics-TPP2014", "path": "github-repos/coq/KyushuUniversityMathematics-TPP2014/TPP2014-8439769862a9619cdb4e0af1597d447c7cca2325/SosukeMoriguchi/tpp2014.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6686491340785479}}
{"text": "Inductive listn : nat -> Set :=\n  | niln : listn 0\n  | consn : forall n : nat, nat -> listn n -> listn (S n).\n\nDefinition length1 (n : nat) (l : listn n) :=\n  match l with\n  | consn n _ (consn m _ _) => S (S m)\n  | consn n _ _ => 1\n  | _ => 0\n  end.\n\nType\n  (fun (n : nat) (l : listn n) =>\n   match n return nat with\n   | O => 0\n   | S n => match l return nat with\n            | niln => 1\n            | l' => length1 (S n) l'\n            end\n   end).\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/failure/Case7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6686220820833925}}
{"text": "Set Implicit Arguments.\nRequire Import ZArith Psatz.\nRequire Import Znumtheory.\nRequire Import Classical.\nRequire Import FunInd Recdef.\nRequire Import List.\nImport ListNotations.\nRequire Import MiniCooper.MyTactics.\nRequire Import MiniCooper.Constant.\nOpen Scope list_scope.\nOpen Scope Z_scope.\n\n\n(* ------------------------------------------------------------------------- *)\n\n(* Arithmetic lemmas. *)\n\nLtac Zabs_either :=\n  match goal with |- context[Z.abs ?k] =>\n    pattern (Z.abs k); eapply Zabs_intro; intros\n  end.\n\nLtac quotient q :=\n  match goal with\n  h: (?z | ?l), nz: ?z <> 0 |- _ =>\n    let eq := fresh in\n    destruct h as [ q eq ];\n    rewrite eq in *; (* replace [l] with [q * z] *)\n    try rewrite (@Z_div_mult_full q z nz) in * (* replace [l / z] with [q] *)\n end.\n\nLemma nonzero_quotient:\n  forall z l,\n  l <> 0 ->\n  z <> 0 ->\n  (z | l) ->\n  l / z <> 0.\nProof.\n  intros. quotient q. intro. subst. omega.\nQed.\n\nLemma sign_multiply_is_Zabs:\n  forall q,\n  q / Z.abs q * q = Z.abs q.\nProof.\n  intros.\n  destruct (@Ztrichotomy q 0) as [ | [ | ]].\n  (* Sub-case: [q < 0]. *)\n  rewrite Zabs_non_eq; try omega.\n  rewrite Z_div_zero_opp_r; eauto using Z_mod_same_full.\n  rewrite Z_div_same_full; try omega.\n  (* Sub-case: [q = 0]. *)\n  subst. auto.\n  (* Sub-case: [q > 0]. *)\n  rewrite Z.abs_eq; try omega.\n  rewrite Z_div_same_full; omega.\nQed.\n\nLemma Zlcm_pos:\n  forall a b,\n  0 < a ->\n  0 < b ->\n  0 < Z.lcm a b.\nProof.\n  intros. rewrite Z.le_neq. split. apply Z.lcm_nonneg.\n  intro HH. symmetry in HH. rewrite Z.lcm_eq_0 in HH. lia.\nQed.\n\nHint Constructors Forall.\n\nLemma Forall_app : forall A P (l1 l2: list A),\n  Forall P l1 ->\n  Forall P l2 ->\n  Forall P (l1 ++ l2).\nProof.\n  induction l1; intros; simpl in *; eauto.\n  match goal with h: Forall _ (_ :: _) |- _ => depelim h end.\n  auto.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Our model is Z. *)\n\nNotation num := Z.\n\n(* We represent variables using de Bruijn indices. *)\n\nNotation var := nat.\n\n(* An environment is a total function of variables into the model. *)\n\nNotation environment := (var -> num).\n\n(* Extensional equality of environments. *)\n\nDefinition enveq (env1 env2 : environment) : Prop :=\n  forall x, env1 x = env2 x.\n\n(* ------------------------------------------------------------------------- *)\n\n(* A term is a sum of summands of the form [k.x], where [k] is a constant and\n   [x] is a variable, and of a final constant. *)\n\nInductive term :=\n| TSummand: num -> var -> term -> term\n| TConstant: constant -> term.\n\n(* The logical interpretation of a term. *)\n\nFixpoint interpret_term (cenv env : environment) (t : term) : num :=\n  match t with\n  | TSummand k y u =>\n      k * env y + interpret_term cenv env u\n  | TConstant c =>\n      interpret_constant cenv c\n  end.\n\n(* A term is well-formed if its coefficients are non-zero and its variables\n   are sorted in increasing order. *)\n\nInductive wft : var -> term -> Prop :=\n| WftSummand:\n    forall x k y u,\n    k <> 0 ->\n    (x <= y)%nat ->\n    wft (S y) u ->\n    wft x (TSummand k y u)\n| WftConstant:\n    forall x k,\n    wft x (TConstant k).\n\nHint Constructors wft.\n\nLemma wft_monotone:\n  forall x1 x2 t,\n  wft x2 t ->\n  (x1 <= x2)%nat ->\n  wft x1 t.\nProof.\n  induction 1; intros; eauto.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Multiplication of a term by a constant. *)\n\nFixpoint mul_nonzero (n : num) (t : term) : term :=\n  match t with\n  | TSummand k x u =>\n      TSummand (n * k) x (mul_nonzero n u)\n  | TConstant k =>\n      TConstant (cmul n k)\n  end.\n\nDefinition mul (n : num) (t : term) : term :=\n  if Z.eq_dec n 0 then TConstant (CGround 0) else mul_nonzero n t.\n\nLemma wf_mul_nonzero:\n  forall n,\n  n <> 0 ->\n  forall x t,\n  wft x t ->\n  wft x (mul_nonzero n t).\nProof.\n  induction 2; simpl; econstructor; eauto. nia.\nQed.\n\nLemma wf_mul:\n  forall n x t,\n  wft x t ->\n  wft x (mul n t).\nProof.\n  intros. unfold mul. destruct (Z.eq_dec n 0); eauto using wf_mul_nonzero.\nQed.\n\nLemma interpret_mul_nonzero:\n  forall cenv env n t,\n  interpret_term cenv env (mul_nonzero n t) = n * interpret_term cenv env t.\nProof.\n  induction t; simpl; auto. rewrite IHt. ring. now rewrite interpret_cmul.\nQed.\n\nLemma interpret_mul:\n  forall cenv env n t,\n  interpret_term cenv env (mul n t) = n * interpret_term cenv env t.\nProof.\n  intros. unfold mul. destruct (Z.eq_dec n 0).\n  subst. simpl. auto.\n  eauto using interpret_mul_nonzero.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Negation of a term. *)\n\nDefinition neg t :=\n  mul (-1) t.\n\nLemma wf_neg:\n  forall x t,\n  wft x t ->\n  wft x (neg t).\nProof.\n  unfold neg. eauto using wf_mul.\nQed.\n\nLemma interpret_neg:\n  forall cenv env t,\n  interpret_term cenv env (neg t) = -(interpret_term cenv env t).\nProof.\n  unfold neg. intros. rewrite interpret_mul. ring.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Addition of two terms. *)\n\n(* This is analogous to merging two sorted lists. *)\n\n(* TEMPORARY comparison over nat is very inefficient; use positive or some\n   other representation of terms? *)\n\nFixpoint add (t1 t2 : term) : term :=\n  let fix add_t1 t2 :=\n    match t1, t2 with\n    | TSummand k1 x1 u1, TSummand k2 x2 u2 =>\n        match Nat.compare x1 x2 with\n        | Eq =>\n            (* [x1 = x2] *)\n            let k := k1 + k2 in\n            if Z.eq_dec k 0 then\n              add u1 u2\n            else\n              TSummand k x1 (add u1 u2)\n        | Lt =>\n            (* [x1 < x2] *)\n            TSummand k1 x1 (add u1 t2)\n        | Gt =>\n            (* [x1 > x2] *)\n            TSummand k2 x2 (add_t1 u2)\n        end\n    | TSummand k1 x1 u1, TConstant _ =>\n        TSummand k1 x1 (add u1 t2)\n    | TConstant _, TSummand k2 x2 u2 =>\n        TSummand k2 x2 (add_t1 u2)\n    | TConstant k1, TConstant k2 =>\n        TConstant (cadd k1 k2)\n    end\n  in\n  add_t1 t2.\n\nLemma wf_add:\n  forall t1 t2 x,\n  wft x t1 ->\n  wft x t2 ->\n  wft x (add t1 t2).\nProof.\n  induction t1 as [ k1 x1 u1 | k1 ];\n  induction t2 as [ k2 x2 u2 | k2 ];\n  inversion 1; inversion 1; subst; simpl.\n  (* Case TSummand/TSummand. *)\n  case_eq (Nat.compare x1 x2); intro.\n    (* Sub-case x1 = x2. *)\n    applyin nat_compare_eq.\n    (* forwards: nat_compare_eq.  eassumption.*)\n    destruct (Z.eq_dec (k1 + k2) 0); eauto using wft_monotone.\n    (* Sub-case x1 < x2. *)\n    applyin nat_compare_Lt_lt.\n    (* forwards: nat_compare_Lt_lt. eassumption. *)\n    eauto using wft_monotone.\n    (* Sub-case x1 > x2. *)\n    applyin nat_compare_Gt_gt.\n    (* forwards: nat_compare_Gt_gt. eassumption. *)\n    eauto using wft_monotone.\n  (* Case TSummand/TConstant. *)\n  eauto.\n  (* Case TConstant/TSummand. *)\n  eauto.\n  (* Case TConstant/TConstant. *)\n  eauto.\nQed.\n\nLemma interpret_add:\n  forall cenv env t1 t2,\n  interpret_term cenv env (add t1 t2) =\n  interpret_term cenv env t1 + interpret_term cenv env t2.\nProof.\n  induction t1 as [ k1 x1 u1 | k1 ];\n  induction t2 as [ k2 x2 u2 | k2 ];\n  simpl.\n  (* Case TSummand/TSummand. *)\n  case_eq (Nat.compare x1 x2); intro.\n    (* Sub-case x1 = x2. *)\n    applyin nat_compare_eq.\n    (* forwards: nat_compare_eq. eassumption.  *)subst x1.\n    destruct (Z.eq_dec (k1 + k2) 0) as [ k1k2 | ].\n      (* Sub-sub-case k1 + k2 = 0. *)\n      match goal with |- ?lhs = _ =>\n        assert (lhs = lhs + (k1 + k2) * env x2) as -> end.\n      now rewrite k1k2; ring. rewrite IHu1. ring.\n      (* Sub-sub-sub k1 + k2 <> 0. *)\n      simpl. rewrite IHu1. ring.\n    (* Sub-case x1 < x2. *)\n    simpl. rewrite IHu1. simpl. ring.\n    (* Sub-case x1 > x2. *)\n    simpl in *. rewrite IHu2. ring.\n  (* Case TSummand/TConstant. *)\n  rewrite IHu1. simpl. ring.\n  (* Case TConstant/TSummand. *)\n  simpl in *. rewrite IHu2. ring.\n  (* Case TConstant/TConstant. *)\n  rewrite interpret_cadd. ring.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Subtraction of two terms. *)\n\nDefinition sub t1 t2 :=\n  add t1 (neg t2).\n\nLemma wf_sub:\n  forall t1 t2 x,\n  wft x t1 ->\n  wft x t2 ->\n  wft x (sub t1 t2).\nProof.\n  unfold sub. eauto using wf_add, wf_neg.\nQed.\n\nLemma interpret_sub:\n  forall cenv env t1 t2,\n  interpret_term cenv env (sub t1 t2) =\n  interpret_term cenv env t1 - interpret_term cenv env t2.\nProof.\n  intros. unfold sub. rewrite interpret_add. rewrite interpret_neg. ring.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Environment extension, in de Bruijn style. *)\n\n(* A new variable 0 is introduced; pre-existing variables are shifted. *)\n\nDefinition extend (env : environment) (z : num) : environment :=\n  fun (y : nat) =>\n    match y with\n    | O => z\n    | S y => env y\n    end.\n\nLemma extend_extensional:\n  forall env1 env2,\n  enveq env1 env2 ->\n  forall z,\n  enveq (extend env1 z) (extend env2 z).\nProof.\n  unfold enveq. intros ? ? ? ? [ | ]; simpl; eauto.\nQed.\n\nLemma extend_env_other:\n  forall env n1 n2 y,\n  (y > 0)%nat ->\n  extend env n1 y = extend env n2 y.\nProof.\n  intros. destruct y. exfalso; omega. auto.\nQed.\n\n(* If the variable 0 does not occur in the term [t], then the interpretation of\n   [t] does not depend upon the interpretation of this variable. *)\n\nLemma extend_insensitive:\n  forall cenv env n1 n2 x t,\n  wft x t ->\n  (x > 0)%nat ->\n  interpret_term cenv (extend env n1) t = interpret_term cenv (extend env n2) t.\nProof.\n  induction 1; intros; simpl; auto.\n  rewrite IHwft; eauto. erewrite extend_env_other; eauto.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Change of variables, in de Bruijn style. *)\n\n(* The variable 0 is scaled down by a factor of [l], that is, the value of the\n   new variable represents [l] times the value of the old variable. Other\n   variables are unaffected. *)\n\nDefinition adjust_env l env : environment :=\n  fun (y : nat) =>\n    match y with\n    | O => l * env O\n    | S _ => env y\n    end.\n\nLemma adjust_env_other:\n  forall l env y,\n  (y > 0)%nat ->\n  adjust_env l env y = env y.\nProof.\n  intros. destruct y. exfalso; omega. auto.\nQed.\n\n(* If the variable 0 does not occur in the term [t], then the interpretation of\n   [t] is not affected by this change of variables. *)\n\nLemma adjust_insensitive:\n  forall cenv l env x t,\n  wft x t ->\n  (x > 0)%nat ->\n  interpret_term cenv (adjust_env l env) t = interpret_term cenv env t.\nProof.\n  induction 1; intros; simpl; auto.\n  rewrite IHwft; eauto. rewrite adjust_env_other; eauto.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* An atomic formula is of the form [0 = t], [0 < t], or [c divides t]. On top\n   of this, we build a first-order logic. *)\n\nInductive predicate :=\n| Eq: predicate (* 0 = *)\n| Lt: predicate (* 0 < *)\n| Dv: num -> predicate (* c divides *).\n\nInductive formula :=\n| FAtom: predicate -> term -> formula\n| FFalse: formula\n| FTrue: formula\n| FAnd: formula -> formula -> formula\n| FOr: formula -> formula -> formula\n| FNot: formula -> formula\n| FExists: formula -> formula.\n\n(* The logical interpretation of a formula. *)\n\nDefinition interpret_predicate (p : predicate) (t : num) : Prop :=\n  match p with\n  | Eq =>\n      0 = t\n  | Lt =>\n      0 < t\n  | Dv d =>\n      (d | t)\n  end.\n\nFixpoint interpret_formula cenv env (f : formula) : Prop :=\n  match f with\n  | FAtom p t =>\n      interpret_predicate p (interpret_term cenv env t)\n  | FFalse =>\n      False\n  | FTrue =>\n      True\n  | FAnd f1 f2 =>\n      interpret_formula cenv env f1 /\\ interpret_formula cenv env f2\n  | FOr f1 f2 =>\n      interpret_formula cenv env f1 \\/ interpret_formula cenv env f2\n  | FNot f =>\n      ~ interpret_formula cenv env f\n  | FExists f =>\n      exists z, interpret_formula cenv (extend env z) f\n  end.\n\n(* A definition of the predicate ``all atoms in the (quantifier-free) formula\n   F satisfy the predicate P''. *)\n\nInductive all (P : predicate -> term -> Prop) : formula -> Prop :=\n| all_FAtom:\n    forall p t,\n    P p t ->\n    all P (FAtom p t)\n| all_FFalse:\n    all P FFalse\n| all_FTrue:\n    all P FTrue\n| all_FAnd:\n    forall f1 f2,\n    all P f1 ->\n    all P f2 ->\n    all P (FAnd f1 f2)\n| all_FOr:\n    forall f1 f2,\n    all P f1 ->\n    all P f2 ->\n    all P (FOr f1 f2)\n| all_FNot:\n    forall f,\n    all P f ->\n    all P (FNot f).\n\n(* A characterization of quantifier-free formulae. *)\n\nNotation qf f :=\n  (all (fun p t => True) f).\n\n(* A characterization of NNF form: negations are applied only to atoms,\n   and negated inequalities are not permitted.\n   Our NNF forms are quantifier-free. *)\n\nInductive nnf : formula -> Prop :=\n| nnf_FAtom:\n    forall p t,\n    nnf (FAtom p t)\n| nnf_FNot_FAtom:\n    forall p t,\n    p <> Lt ->\n    nnf (FNot (FAtom p t))\n| nnf_FAnd:\n    forall f1 f2,\n    nnf f1 ->\n    nnf f2 ->\n    nnf (FAnd f1 f2)\n| nnf_FOr:\n    forall f1 f2,\n    nnf f1 ->\n    nnf f2 ->\n    nnf (FOr f1 f2)\n| nnf_FTrue:\n    nnf FTrue\n| nnf_FFalse:\n    nnf FFalse.\n\nHint Constructors all nnf.\nHint Extern 1 (_ <> Lt) => congruence.\n\n(* The predicate [all P] is covariant in [P]. *)\n\nLemma all_covariant:\n  forall (P Q : predicate -> term -> Prop),\n  (forall p t, P p t -> Q p t) ->\n  forall f,\n  all P f ->\n  all Q f.\nProof.\n  induction 2; eauto.\nQed.\n\n(* Well-formed predicates rule out \"divisible by 0\" atoms *)\n\nInductive wfp : predicate -> Prop :=\n| WfpDv : forall c,\n  0 < c -> wfp (Dv c)\n| WfpEq :\n  wfp Eq\n| WfpLt :\n  wfp Lt.\n\nHint Constructors wfp.\n\n(* A characterization of formulae where all terms and predicates are\n   well-formed. *)\n\nNotation wff :=\n  (all (fun p t => wft 0 t /\\ wfp p)).\n\n(* ------------------------------------------------------------------------- *)\n\n(* The interpretation of terms and formulas is compatible with extensional\n   equality of environments. *)\n\nLemma interpret_term_extensional:\n  forall cenv env1 env2,\n  enveq env1 env2 ->\n  forall t,\n  interpret_term cenv env1 t = interpret_term cenv env2 t.\nProof.\n  induction t; simpl; congruence.\nQed.\n\nLemma interpret_formula_extensional:\n  forall cenv f env1 env2,\n  enveq env1 env2 ->\n  ( interpret_formula cenv env1 f <-> interpret_formula cenv env2 f ).\nProof.\n  induction f; intros; simpl; try tauto.\n  (* Case: [FAtom]. *)\n  erewrite interpret_term_extensional; [ idtac | eauto ]. tauto.\n  (* Case: [FAnd]. *)\n  specialize (IHf1 env1 env2).\n  specialize (IHf2 env1 env2). tauto.\n  (* Case: [FOr]. *)\n  specialize (IHf1 env1 env2).\n  specialize (IHf2 env1 env2). tauto.\n  (* Case: [FNot]. *)\n  specialize (IHf env1 env2). tauto.\n  (* Case: [FExists]. *)\n  split; intros [ z ? ]; exists z; [ rewrite <-IHf | rewrite IHf ];\n  eauto using extend_extensional.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* A tactic that destructs a predicate, if there is one in the assumptions. *)\n\nLtac predicate :=\n  match goal with p: predicate |- _ => destruct p end.\n\n(* A tactic that destructs an all-atoms-satisfy-P assumption. *)\n\nLtac all :=\n  match goal with h: all _ _ |- _ => first [ now depelim h | depelim h;[] ] end.\n\n(* A tactic that destructs a term, distinguishing the TSummand and TConstant\n   cases, and in the former case, distinguishing the variable 0 from other\n   variables. *)\n\nLtac term :=\n  match goal with t: term |- _ => destruct t as [ ? [ | ? ] ? | ? ] end.\n\n(* A tactic that destructs a [wft] assumption. *)\n\nLtac wft :=\n  match goal with h: wft _ _ |- _ => depelim h end.\n\nLtac wfp :=\n  match goal with h: wfp ?p |- _ => depelim h end.\n\nLtac wff :=\n  match goal with\n  | h: wff _ |- _ => depelim h\n  | h: wft _ _ /\\ wfp _ |- _ => simpl in h; destruct h\n  end.\n\nLtac nnf :=\n  match goal with h: nnf _ |- _ => depelim h end.\n\nLtac classical :=\n  match goal with\n  | h: ~ ~ _ |- _ => apply NNPP in h\n  | h: ~ (_ /\\ _) |- _ => apply not_and_or in h\n  | h: ~ (_ \\/ _) |- _ => apply not_or_and in h\n  end.\n\n(* ------------------------------------------------------------------------- *)\n\n(* [wff] and [nnf] both entail that the formula is quantifier-free. *)\n\nLemma qf_nnf:\n  forall f,\n  nnf f ->\n  qf f.\nProof.\n  induction f; intros; simpl in *; nnf; eauto.\nQed.\n\nLemma qf_wff:\n  forall f,\n  wff f ->\n  qf f.\nProof.\n  intros. eapply all_covariant; [|eassumption]. eauto.\nQed.\n\n(* Smart constructors for conjunction, disjunction, and negation. *)\n\n(* Conjunction *)\n\nDefinition conjunction f1 f2 :=\n  match f1, f2 with\n  | FFalse, _\n  | _, FFalse =>\n      FFalse\n  | FTrue, f\n  | f, FTrue =>\n      f\n  | _, _ =>\n      FAnd f1 f2\n  end.\n\nLemma interpret_conjunction:\n  forall cenv env f1 f2,\n  interpret_formula cenv env (conjunction f1 f2) <->\n  interpret_formula cenv env f1 /\\ interpret_formula cenv env f2.\nProof.\n  intros. unfold conjunction. destruct f1; destruct f2; simpl; tauto.\nQed.\n\nLemma all_conjunction:\n  forall f1 f2 P,\n  all P f1 ->\n  all P f2 ->\n  all P (conjunction f1 f2).\nProof.\n  intros; destruct f1; destruct f2; simpl in *; eauto.\nQed.\n\nDefinition wf_conjunction := all_conjunction.\n\nLemma nnf_conjunction:\n  forall f1 f2,\n  nnf f1 ->\n  nnf f2 ->\n  nnf (conjunction f1 f2).\nProof.\n  intros; destruct f1; destruct f2; simpl in *; eauto.\nQed.\n\n(* Disjunction *)\n\nDefinition disjunction f1 f2 :=\n  match f1, f2 with\n  | FTrue, _\n  | _, FTrue =>\n      FTrue\n  | FFalse, f\n  | f, FFalse =>\n      f\n  | _, _ =>\n      FOr f1 f2\n  end.\n\nLemma interpret_disjunction:\n  forall cenv env f1 f2,\n  interpret_formula cenv env (disjunction f1 f2) <->\n  interpret_formula cenv env f1 \\/ interpret_formula cenv env f2.\nProof.\n  intros. unfold disjunction. destruct f1; destruct f2; simpl; tauto.\nQed.\n\nLemma all_disjunction:\n  forall f1 f2 P,\n  all P f1 ->\n  all P f2 ->\n  all P (disjunction f1 f2).\nProof.\n  intros; destruct f1; destruct f2; simpl in *; eauto.\nQed.\n\nDefinition wf_disjunction := all_disjunction.\n\nLemma nnf_disjunction:\n  forall f1 f2,\n  nnf f1 ->\n  nnf f2 ->\n  nnf (disjunction f1 f2).\nProof.\n  intros; destruct f1; destruct f2; simpl in *; eauto.\nQed.\n\n(* Negation *)\n\nDefinition negation f :=\n  match f with\n  | FTrue =>\n      FFalse\n  | FFalse =>\n      FTrue\n  | FNot f =>\n      f\n  | f =>\n      FNot f\n  end.\n\nLemma interpret_negation:\n  forall cenv env f,\n  interpret_formula cenv env (negation f) <-> ~ interpret_formula cenv env f.\nProof.\n  (* Note: The elimination of double negation requires classical reasoning. *)\n  intros. unfold negation. destruct f; simpl; tauto.\nQed.\n\nLemma all_negation:\n  forall f P,\n  all P f ->\n  all P (negation f).\nProof.\n  intros; destruct f; simpl in *; all; eauto.\nQed.\n\nDefinition wf_negation := all_negation.\n\n(* Iterated disjunction, and iterated \\/ *)\n\nDefinition big_disjunction A (F : A -> formula) (l : list A) : formula :=\n  fold_right (fun x Q => disjunction (F x) Q) FFalse l.\n\nDefinition big_or A (P : A -> Prop) (l : list A) : Prop :=\n  fold_right (fun x Q => P x \\/ Q) False l.\n\nLemma interpret_big_disjunction:\n  forall A cenv env (F : A -> formula) l,\n  interpret_formula cenv env (big_disjunction F l) <->\n  big_or (fun x => interpret_formula cenv env (F x)) l.\nProof.\n  induction l; simpl; try tauto.\n  rewrite interpret_disjunction. tauto.\nQed.\n\nLemma all_big_disjunction:\n  forall A (F : A -> formula) (l : list A) P,\n  (forall x,\n   In x l ->\n   all P (F x)) ->\n  all P (big_disjunction F l).\nProof.\n  intros * HH.\n  induction l; simpl in *; eauto.\n  apply all_disjunction; eauto.\nQed.\n\nLemma nnf_big_disjunction:\n  forall A (F : A -> formula) (l : list A),\n  (forall x,\n   In x l ->\n   nnf (F x)) ->\n  nnf (big_disjunction F l).\nProof.\n  intros. induction l; simpl in *; eauto.\n  apply nnf_disjunction; eauto.\nQed.\n\nLemma big_or_prove : forall A (P : A -> Prop) l x,\n  In x l ->\n  P x ->\n  big_or P l.\nProof.\n  induction l; intros * HIn; inversion HIn.\n  - subst. cbn. tauto.\n  - intros. simpl. eauto.\nQed.\n\nLemma big_or_inv : forall A (P : A -> Prop) l,\n  big_or P l ->\n  exists x, In x l /\\ P x.\nProof.\n  induction l; intros * H; simpl in H; try tauto.\n  firstorder.\nQed.\n\nLemma big_or_extens : forall A (P1 P2 : A -> Prop) l,\n  (forall x, P1 x <-> P2 x) ->\n  big_or P1 l <-> big_or P2 l.\nProof.\n  intros * E. induction l; intros; simpl in *; try tauto.\n  rewrite IHl, E; tauto.\nQed.\n\nLemma big_or_distr : forall A (P1 P2 : A -> Prop) l,\n  big_or (fun x => P1 x \\/ P2 x) l <->\n  big_or P1 l \\/ big_or P2 l.\nProof.\n  induction l; intros; simpl in *; tauto.\nQed.\n\n(* Or we could setup rewriting under [big_or]... *)\nLemma interpret_big_disjunction2:\n  forall A B cenv env (F : A -> B -> formula) l1 l2,\n  interpret_formula cenv env\n    (big_disjunction (fun x => big_disjunction (F x) l1) l2) <->\n  big_or (fun x => big_or (fun y => interpret_formula cenv env (F x y)) l1) l2.\nProof.\n  intros. rewrite interpret_big_disjunction. apply big_or_extens.\n  intros. rewrite interpret_big_disjunction. reflexivity.\nQed.\n\n(* Intervals, to use as support for [big_disjunction] and [big_or]. *)\n(* TODO: use [seq] instead *)\n\n(* The interval of 0 (included) to n (excluded): [0, n). *)\n\nFixpoint interval' (n : nat) : list Z :=\n  match n with\n  | O => []\n  | S n' => Z.of_nat n' :: interval' n'\n  end.\n\nDefinition interval (x : Z) : list Z :=\n  interval' (Z.to_nat x).\n\nLemma In_interval' : forall x n,\n  In x (interval' n) <-> 0 <= x < Z.of_nat n.\nProof.\n  induction n; intros.\n  - simpl. lia.\n  - cbn [interval' In]. destruct (Z.eq_dec x (Z.of_nat n)); [ lia |].\n    split; intro.\n    + intuition lia.\n    + rewrite IHn. lia.\nQed.\n\nLemma In_interval : forall x n,\n  In x (interval n) <-> 0 <= x < n.\nProof.\n  intros. unfold interval. rewrite In_interval'.\n  split; intro; rewrite Z2Nat.id in *; try lia.\n  destruct n; simpl in *; lia.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Bringing a formula into NNF form. *)\n\n(* This transformation will be applied only to quantifier-free formulae, so\n   we are happy to do nothing in the [FExists] case. *)\n\nFixpoint posnnf (f : formula) : formula :=\n  match f with\n  | FNot f =>\n      negnnf f\n  | FAnd f1 f2 =>\n      FAnd (posnnf f1) (posnnf f2)\n  | FOr f1 f2 =>\n      FOr (posnnf f1) (posnnf f2)\n  | FTrue\n  | FFalse\n  | FAtom _ _\n  | FExists _\n    => f\n  end\n\nwith negnnf (f : formula) : formula :=\n  match f with\n  | FNot f =>\n      posnnf f\n  | FAnd f1 f2 =>\n      FOr (negnnf f1) (negnnf f2)\n  | FOr f1 f2 =>\n      FAnd (negnnf f1) (negnnf f2)\n  | FTrue =>\n      FFalse\n  | FFalse =>\n      FTrue\n  | FAtom Lt t =>\n      (* Negated inequalities are not permitted by our assumptions.\n         Reverse them. The atom [~(0 < t)] can be transformed into\n         [0 < 1 - t]. *)\n      FAtom Lt (sub (TConstant (CGround 1)) t)\n  | FAtom _ _\n  | FExists _ =>\n      FNot f\n  end.\n\nLemma interpret_posnnf:\n  forall cenv env f,\n  interpret_formula cenv env (posnnf f) <-> interpret_formula cenv env f\nwith interpret_negnnf:\n  forall cenv env f,\n  interpret_formula cenv env (negnnf f) <-> ~ interpret_formula cenv env f.\nProof.\n  (* Proof of the first lemma. *)\n  induction f; simpl; try tauto. auto.\n  (* Proof of the second lemma. *)\n  induction f; try predicate; simpl; try tauto.\n    (* Case: [Lt] atoms. *)\n    rewrite interpret_sub.\n    simpl (interpret_term cenv env (TConstant (CGround 1))).\n    omega. (* cool *)\n    (* Case: [FNot]. Again, classical reasoning is required. *)\n    split.\n    specialize (interpret_posnnf cenv env f). tauto.\n    intro. apply <- interpret_posnnf. tauto.\nQed.\n\nLemma nnf_posnnf:\n  forall f,\n  qf f ->\n  nnf (posnnf f)\nwith nnf_negnnf:\n  forall f,\n  qf f ->\n  nnf (negnnf f).\nProof.\n  (* Proof of the first lemma. *)\n  induction f; intros; simpl; try all; eauto.\n  (* Proof of the second lemma. *)\n  induction f; intros; try predicate; simpl; try all; eauto.\nQed.\n\nLemma wf_posnnf:\n  forall f,\n  wff f ->\n  wff (posnnf f)\nwith wf_negnnf:\n  forall f,\n  wff f ->\n  wff (negnnf f).\nProof.\n  induction f; intros; simpl; try all; eauto.\n  induction f; intros; try predicate; simpl; try all;\n    unpack; eauto using wf_sub.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Throughout the quantifier elimination procedure, the variable [x] which we\n   wish to eliminate is the de Bruijn index [0]. This means that [x] always\n   appear in front of a term, if it appears at all. *)\n\n(* ------------------------------------------------------------------------- *)\n\n(* Computing the least common multiple of the coefficients of [x] in a\n   quantifier-free formula. *)\n\n(* Collect all coefficients and compute their LCM. *)\n\nFixpoint formula_lcm (f : formula) : num :=\n  match f with\n  | FAtom _ (TSummand c 0 _) =>\n      Z.abs c\n  | FAtom _ (TSummand _ _ _)\n  | FAtom _ (TConstant _)\n  | FFalse\n  | FTrue\n  | FExists _ =>\n      1\n  | FAnd f1 f2\n  | FOr f1 f2 =>\n      Z.lcm (formula_lcm f1) (formula_lcm f2)\n  | FNot f =>\n      formula_lcm f\n  end.\n\n(* Characterize what is computed: a common multiple of all coefficients\n   of [x]. The fact that this is the least common multiple does not seem\n   to be required for soundness. *)\n\n(* We write [all (dvx l) f] when all coefficients of [x] in the formula [f]\n   divide [l]. *)\n\nDefinition dvx (l : num) (p : predicate) (t : term) : Prop :=\n  match t with\n  | TSummand c 0 _ =>\n      (c | l)\n  | TSummand _ _ _\n  | TConstant _ =>\n      True\n  end.\n\nLemma dvx_transitive:\n  forall l1 l2 p t,\n  dvx l1 p t ->\n  (l1 | l2) ->\n  dvx l2 p t.\nProof.\n  intros; term; simpl in *; eauto using Z.divide_trans.\nQed.\n\nLemma all_dvx_transitive:\n  forall l1 l2 f,\n  all (dvx l1) f ->\n  (l1 | l2) ->\n  all (dvx l2) f.\nProof.\n  induction 1; intros; econstructor; eauto using dvx_transitive.\nQed.\n\nLemma all_dvx_formula_lcm:\n  forall f,\n  qf f ->\n  all (dvx (formula_lcm f)) f.\nProof.\n  induction f; intros; try all; simpl; try solve [ econstructor ].\n  (* Case: [FAtom]. *)\n  econstructor. unfold dvx.\n  term; eauto. rewrite Z.divide_abs_r. reflexivity.\n  (* Case: [FAnd]. *)\n  econstructor; eapply all_dvx_transitive;\n    eauto using Z.divide_lcm_l, Z.divide_lcm_r.\n  (* Case: [FOr]. *)\n  econstructor; eapply all_dvx_transitive;\n    eauto using Z.divide_lcm_l, Z.divide_lcm_r.\n  (* Case: [FNot]. *)\n  econstructor; eauto.\nQed.\n\nLemma formula_lcm_nonneg:\n  forall f,\n  wff f ->\n  0 < formula_lcm f.\nProof.\n  induction 1; simpl; eauto using Zlcm_pos with zarith.\n  (* Case: [FAtom]. *)\n  term; wff; wft; wfp; lia.\nQed.\n\nLemma formula_lcm_nonzero:\n  forall f,\n  wff f ->\n  formula_lcm f <> 0.\nProof.\n  intros. applyin formula_lcm_nonneg. lia.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Adjusting the coefficients of [x] in a quantifier-free formula. *)\n\n(* We assume that the integer [l] has been computed by [formula_lcm] above.\n   We multiply each atom by a constant factor, so that the coefficient of [x]\n   reaches [l] -- or its opposite. Then, we immediately normalize the\n   coefficient of [x] down to [1] or [-1], as we perform a change of variables\n   and write [x] for [l.x]. *)\n\nFixpoint adjust (l : num) (f : formula) : formula :=\n  match f with\n\n  | FAtom Eq (TSummand c 0 u) =>\n\n      (* Compute by how much we must multiply. *)\n      let m := l / c in\n      (* The coefficient of [x] becomes [l], but is renormalized to [1];\n         the rest of the term is multiplied by [m]. *)\n      FAtom Eq (TSummand 1 0 (mul m u))\n\n  | FAtom Lt (TSummand c 0 u) =>\n\n      (* Compute by how much we must multiply. *)\n      let m := l / c in\n      (* Make sure that this is a positive factor, as we can't reverse\n         the predicate [Lt]. *)\n      let am := Z.abs m in\n      (* Thus, the coefficient of [x] will be renormalized to either\n         [1] or [-1]. *)\n      let coeffx := m / am in\n      (* The coefficient of [x] is renormalized to [coeffx];\n         the rest of the term is multiplied by [am]. *)\n      FAtom Lt (TSummand coeffx 0 (mul am u))\n\n  | FAtom (Dv d) (TSummand c 0 u) =>\n\n      (* Compute by how much we must multiply. *)\n      let m := l / c in\n      (* The coefficient of [x] becomes [l], but is renormalized to [1];\n         the rest of the term is multiplied by [m]. The divisor [d] is\n         multiplied by [m], but we are careful to keep it positive. *)\n      FAtom (Dv (Z.abs m * d)) (TSummand 1 0 (mul m u))\n\n  | FAtom _ (TSummand _ _ _)\n  | FAtom _ (TConstant _)\n  | FExists _ =>\n      f\n  | FFalse =>\n      FFalse\n  | FTrue =>\n      FTrue\n  | FAnd f1 f2 =>\n      FAnd (adjust l f1) (adjust l f2)\n  | FOr f1 f2 =>\n      FOr (adjust l f1) (adjust l f2)\n  | FNot f =>\n      FNot (adjust l f)\n  end.\n\n(* The following lemmas state that multiplying an atom by a (non-zero)\n   constant factor does not affect its meaning. *)\n\nLemma scale_Eq_atom:\n  forall k t u,\n  k <> 0 ->\n  t = k * u ->\n  ( 0 = t <-> 0 = u ).\nProof. intros. nia. Qed.\n\nLemma scale_Lt_atom:\n  forall k t u,\n  0 < k ->\n  t = k * u ->\n  ( 0 < t <-> 0 < u ).\nProof. intros; nia. Qed.\n\nLemma scale_Dv_atom:\n  forall k d1 d2 t1 t2,\n  d1 = k * d2 ->\n  k <> 0 ->\n  t1 = k * t2 ->\n  ( (d1 | t1) <-> (d2 | t2) ).\nProof.\n  intros. split; intros * h; subst.\n  (* Left to right. *)\n  destruct h as [ q h ]. exists q.\n  assert (i: t2 * k = (q * d2) * k).\n  { rewrite Zmult_comm. rewrite h. ring. }\n  clear h. rewrite <- (@Z_div_mult_full t2 k); eauto.\n  rewrite i.\n  rewrite Z_div_mult_full; eauto.\n  (* Right to left. *)\n  eauto using Zmult_divide_compat_l.\nQed.\n\nLemma scale_Dv_atom_Zabs:\n  forall k d1 d2 t1 t2,\n  d1 = Z.abs k * d2 ->\n  k <> 0 ->\n  t1 = k * t2 ->\n  ( (d1 | t1) <-> (d2 | t2) ).\nProof.\n  (* Either [Z.abs k] is [-k], or it is [k]. *)\n  intro k. Zabs_either.\n  (* Sub-case: [-k]. *)\n  rewrite <-(Z.divide_opp_l d1). subst.\n  eapply scale_Dv_atom; [ idtac | eauto | eauto ].\n  ring.\n  (* Sub-case: [k]. *)\n  eauto using scale_Dv_atom.\nQed.\n\n(* If [l] is indeed a common multiple of all the coefficients of [x], then\n   the interpretation of the new formula [adjust l f], in an environment\n   where the new [x] stands for [l] times the old [x], coincides with the\n   interpretation of the old formula [f]. *)\n\nOpaque Zmult.\n\nLemma interpret_adjust:\n  forall l,\n  l <> 0 ->\n  forall cenv env f,\n  all (dvx l) f ->\n  wff f ->\n  interpret_formula cenv (adjust_env l env) (adjust l f) <->\n  interpret_formula cenv env f.\nProof.\n  (* All cases but [FAtom] are trivial. *)\n  induction 2; intros; all; simpl; try tauto.\n  (* Distinguish several sub-cases, depending upon the predicate and the form of\n     the term. *)\n  predicate; term; unfold dvx in *; wff; wft; simpl;\n  (* Solve the easy sub-cases where [x] does not appear. *)\n  try solve [ tauto | erewrite adjust_insensitive; eauto; tauto ];\n  (* In each remaining sub-case, [x] does not appear in the tail of the term. *)\n  rewrite interpret_mul;\n  erewrite adjust_insensitive; eauto;\n  (* In each remaining sub-case, the goal can be simplified by replacing the\n     quotient [l / z] with an integer meta-variable [q]. *)\n  quotient q.\n\n  (* Three interesting sub-cases remain. *)\n\n  (* Sub-case: an equality atom where [x] occurs. *)\n  eapply (@scale_Eq_atom q); nia.\n\n  (* Sub-case: an inequality atom where [x] occurs. *)\n  eapply (@scale_Lt_atom (Z.abs q)). nia.\n  ring_simplify. rewrite sign_multiply_is_Zabs; eauto. ring.\n\n  (* Sub-case: a divisibility atom where [x] occurs. *)\n  eapply scale_Dv_atom_Zabs. eauto. nia. ring.\nQed.\n\nLemma interpret_adjust_formula_lcm:\n  forall f,\n  wff f ->\n  forall cenv env,\n  interpret_formula cenv (adjust_env (formula_lcm f) env)\n    (adjust (formula_lcm f) f) <->\n  interpret_formula cenv env f.\nProof.\n  intros.\n  eapply interpret_adjust.\n  eauto using formula_lcm_nonzero.\n  eapply all_dvx_formula_lcm. eauto using all_covariant.\n  eassumption.\nQed.\n\nLemma nnf_adjust:\n  forall f l,\n  nnf f ->\n  nnf (adjust l f).\nProof.\n  induction f; intros; simpl in *; nnf; eauto.\n  { predicate; term; eauto. }\n  { unfold adjust. predicate; term; eauto. }\nQed.\n\n(* After the formula has been transformed using [adjust], all coefficients of\n   [x] are 1, except in inequality atoms, where they might be 1 or -1. *)\n\n(* Furthermore, the formula is still well-formed. We combine the two\n   properties, as it is easier to establish them together. (For an inequality\n   atom, well-formedness requires the coefficient of [x] to be nonzero,\n   whereas, for the atom to be normal, the coefficient must be 1 or -1.) *)\n\nDefinition normal (p : predicate) (t : term) : Prop :=\n  match p with Dv d => 0 < d | _ => True end /\\\n  match p, t with\n  | (Eq | Dv _), TSummand c 0 u =>\n      c = 1 /\\ wft 1%nat u\n  | Lt, TSummand c 0 u =>\n      (c = -1 \\/ c = 1) /\\ wft 1%nat u\n  | _, TSummand _ _ _\n  | _, TConstant _ =>\n      wft 0%nat t\n  end.\n\nLemma wf_normal:\n  forall f,\n  all normal f ->\n  wff f.\nProof.\n  induction f; intros; simpl in *; all; eauto.\n  unfold normal in *. predicate; term; unpack; eauto.\nQed.\n\nHint Resolve wf_normal.\n\nLemma normal_adjust:\n  forall l,\n  l <> 0 ->\n  forall f,\n  all (dvx l) f ->\n  wff f ->\n  all normal (adjust l f).\nProof.\n  induction 2; intros; all; simpl; eauto.\n  (* Case [FAtom]. *)\n  predicate; term; unfold dvx in *; wff; wft; wfp; econstructor; simpl;\n    unfold normal; intuition eauto using wf_mul.\n  (* Only the sub-case of [Lt] atoms is slightly non-trivial. *)\n  { Zabs_either.\n    left.\n    rewrite Z_div_zero_opp_r; eauto using Z_mod_same_full.\n    rewrite Z_div_same_full; eauto using nonzero_quotient.\n    right.\n    rewrite Z_div_same_full; eauto using nonzero_quotient. }\n  { apply Z.mul_pos_pos; [|lia]. apply Z.abs_pos. apply nonzero_quotient; auto. }\nQed.\n\nLemma normal_adjust_formula_lcm:\n  forall f,\n  wff f ->\n  all normal (adjust (formula_lcm f) f).\nProof.\n  intros.\n  eapply normal_adjust.\n    eauto using formula_lcm_nonzero.\n    eapply all_dvx_formula_lcm. eauto using all_covariant.\n    eassumption.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Making sure that all coefficients of [x] in a quantifier-free formula\n   are [1] or [-1]. *)\n\nDefinition unity (f : formula) : formula :=\n\n  (* Compute the least common multiple of all coefficients of [x]. *)\n\n  let l := formula_lcm f in\n\n  (* Adjust all coefficients of [x] in the formula to be [1] or [-1].\n     This represents a change of variable: the new [x] stands for the\n     old [l.x]. *)\n\n  let f := adjust l f in\n\n  (* For the change of variable to make sense, we must add a constraint\n     that [l] divides the new [x]. Of course, this is required only if\n     [l] is not [1]. *)\n\n  if Z.eq_dec l 1 then\n    f\n  else\n    FAnd\n      f\n      (FAtom (Dv l) (TSummand 1 0 (TConstant (CGround 0)))).\n\n(* This transformation is meaning-preserving. *)\n\nLemma interpret_formula_adjust_env_1:\n  forall cenv env f,\n  interpret_formula cenv env f <-> interpret_formula cenv (adjust_env 1 env) f.\nProof.\n  intros. eapply interpret_formula_extensional.\n  intros [ | ]; simpl; intros; ring.\nQed.\n\nLemma exists_equivalence:\n  forall (A : Type) (P Q : A -> Prop),\n  (forall z, P z <-> Q z) ->\n  ( (exists z, P z) <-> (exists z, Q z) ).\nProof. firstorder. Qed.\n\nLemma interpret_unity:\n  forall cenv env f,\n  wff f ->\n  interpret_formula cenv env (FExists f) <->\n  interpret_formula cenv env (FExists (unity f)).\nProof.\n  intros. unfold unity. simpl.\n  destruct (Z.eq_dec (formula_lcm f) 1) as [ eq | _ ].\n  (* Case: [formula_lcm f] is 1. No change of variables is required. *)\n  eapply exists_equivalence; intro.\n  rewrite (@interpret_formula_adjust_env_1 _ _ (adjust _ _)).\n  rewrite <- eq.\n  rewrite interpret_adjust_formula_lcm; eauto.\n  tauto.\n  (* General case. A change of variables is required. We consider the\n     two directions of the equivalence separately. *)\n  split; intros [ z ? ].\n  (* Left to right. *)\n  (* The new [x] represents [l] times the old [x]. *)\n  exists ((formula_lcm f) * z). simpl. split.\n  rewrite interpret_formula_extensional.\n  eapply interpret_adjust_formula_lcm; eassumption.\n  intros [ | ]; auto.\n  exists z. ring.\n  (* Right to left. *)\n  (* The new [x] is divisible by [l]; the old [x] is the quotient [q]. *)\n  simpl in *. unpack.\n  replace (1 * z + 0) with z in *; [ idtac | ring ].\n  assert (formula_lcm f <> 0). eauto using formula_lcm_nonzero.\n  quotient q.\n  exists q.\n  rewrite <- interpret_adjust_formula_lcm; eauto.\n  rewrite interpret_formula_extensional; eauto.\n  intros [ | ]; simpl; eauto using Zmult_comm.\nQed.\n\nLemma normal_unity:\n  forall f,\n  wff f ->\n  all normal (unity f).\nProof.\n  intros. unfold unity.\n  destruct (Z.eq_dec (formula_lcm f) 1).\n  eauto using normal_adjust_formula_lcm.\n  econstructor.\n    eauto using normal_adjust_formula_lcm.\n    econstructor. split; eauto using formula_lcm_nonneg.\nQed.\n\nLemma wf_unity:\n  forall f,\n  wff f ->\n  wff (unity f).\nProof. eauto using normal_unity. Qed.\n\nLemma nnf_unity:\n  forall f,\n  nnf f ->\n  nnf (unity f).\nProof.\n  induction f; intros; simpl in *; nnf; eauto;\n    unfold unity; case_if; eauto using nnf_adjust.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* A subset of Z either admits arbitrarily large negative elements or admits a\n   lower bound. *)\n\nNotation sink P := (forall x, exists y, y < x /\\ P y).\nNotation lower_bound P := (exists x, forall y, y < x -> ~ P y).\nNotation least_element P := (exists x, P x /\\ forall y, y < x -> ~ P y).\n\nLemma sink_or_lower_bound:\n  forall P : Z -> Prop,\n  sink P \\/ lower_bound P.\nProof.\n  intro.\n  (* Apply the excluded middle. *)\n  match goal with |- ?P \\/ _ => destruct (classic P) as [ h | h ] end.\n  left. assumption.\n  right.\n  (* Push the negations inwards using de Morgan's laws. *)\n  generalize (not_all_ex_not _ _ h); clear h; intros [ x h ].\n  exists x; intros.\n  generalize (not_ex_all_not _ _ h); clear h; intro h.\n  specialize (h y).\n  tauto.\nQed.\n\n(* A non-empty subset of Z either that admits a lower bound admits a least\n   element. *)\n\nLemma lower_bound_least_element_preliminary:\n  (* For every subset P of Z, *)\n  forall P : Z -> Prop,\n  (* If P admits a lower bound, *)\n  forall floor,\n  (forall y, y < floor -> ~ P y) ->\n  (* Then, for all y at or above this lower bound, *)\n  forall y,\n  floor <= y ->\n  (* If there is an element of P below y, *)\n  (exists x, P x /\\ x < y) ->\n  (* Then P admits a least element. *)\n  (exists x, P x /\\ forall y, y < x -> ~ P y).\nProof.\n  (* The idea is that [y] sweeps from left to right. In the base case, [y] is\n     [floor], and the statement is trivial, because there is no element of [P]\n     below floor. If we can prove the inductive case, then we can sweep [y]\n     arbitrarily far towards the right, so that the condition ``if there is an\n     element of [P] below [y]'' in the limit becomes equivalent to ``if there\n     is an element of [P]''. *)\n  intros * hfloor.\n  (* We prove this by well-founded induction, bounded below by [floor]. *)\n  eapply (@Zlt_lower_bound_ind (fun y =>\n    (exists x, P x /\\ x < y) -> (exists x, P x /\\ forall y, y < x -> ~ P y)\n  )).\n  intros y ih ? [ x [ ? ? ]].\n  (* [x] satisfies [P], so it cannot be below [floor]. *)\n  assert (~ x < floor). specialize (hfloor x). tauto.\n  (* Either [x] is the least element of [P], or there is another solution of [P]\n     between [floor] and [x]. Let us refer to it as [sx], for ``a smaller [x]''.\n  *)\n  destruct (classic (forall y, y < x -> ~ P y)) as [ | hsx ].\n  solve [ eauto ].\n  generalize (not_all_ex_not _ _ hsx); clear hsx; intros [ sx hsx ].\n  generalize (imply_to_and _ _ hsx); clear hsx; intros [ ? hsx ].\n  generalize (NNPP _ hsx); clear hsx; intros hsx.\n  (* We may now use the induction hypothesis, where [sx] plays the role of [x],\n     and [x] plays the role of [y]. *)\n  eapply (ih x). omega. eauto.\nQed.\n\nLemma lower_bound_least_element:\n  (* For every subset P of Z, *)\n  forall P : Z -> Prop,\n  (* If P admits a lower bound, *)\n  forall floor,\n  (forall y, y < floor -> ~ P y) ->\n  (* And P is non-empty, *)\n  (exists x, P x) ->\n  (* Then P admits a least element. *)\n  (exists x, P x /\\ forall y, y < x -> ~ P y).\nProof.\n  intros * hfloor [ x ? ].\n  eapply lower_bound_least_element_preliminary with (y := x + 1).\n  eassumption.\n  assert (~ x < floor). specialize (hfloor x). tauto. omega.\n  exists x. split. assumption. omega.\nQed.\n\n(* A non-empty subset of Z either admits arbitrarily large negative elements or\n   admits a least element. *)\n\nLemma sink_or_least_element:\n  forall P : Z -> Prop,\n  (exists x, P x) ->\n  sink P \\/ least_element P.\nProof.\n  intros.\n  destruct (@sink_or_lower_bound P) as [ | [ floor hfloor ] ].\n  left. assumption.\n  right. eauto using lower_bound_least_element.\nQed.\n\n(* The reciprocal statement is of course true. *)\n\nLemma sink_or_least_element_reciprocal:\n  forall P : Z -> Prop,\n  sink P \\/ least_element P ->\n  exists x, P x.\nProof.\n  intros * [ h | [ x [ ? ? ]]].\n  specialize (h 0). unpack. eauto.\n  eauto.\nQed.\n\nLemma exists_equiv_sink_or_least_element:\n  forall P : Z -> Prop,\n  (exists x, P x) <-> sink P \\/ least_element P.\nProof.\n  intros; split;\n    eauto using sink_or_least_element, sink_or_least_element_reciprocal.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Computing the ``minus infinity'' version of a formula P. This new formula\n   holds if and only if the original formula admits arbitrarily large negative\n   solutions for [x]. As before, we take [x] to be the variable with de Bruijn\n   index 0. *)\n\n(* Note that the formula [minusinf f] still depends on [x], because divisibility\n   atoms are unchanged and may still refer to [x]. *)\n\nFunction minusinf (f : formula) : formula :=\n  match f with\n\n  | FAtom Eq (TSummand c 0 _) =>\n\n      (* [c] is 1. We have an equality on [x]. This can't be satisfied by\n         arbitrarily small values of [x].  *)\n\n      FFalse\n\n  | FAtom Lt (TSummand c 0 _) =>\n\n      (* [c] is 1 or -1. We have an inequality on [x]. This is satisfied by\n         arbitrarily small values of [x] if and only if the coefficient [c] is\n         negative. *)\n\n      if Z.eq_dec c 1 then FFalse else FTrue\n\n  | FAtom _ _\n  | FExists _ =>\n\n      (* Division atoms are insensitive to translation, so they are\n         retained. Atoms that do not mention [x] at all are retained as\n         well. *)\n\n      f\n\n  | FFalse =>\n      FFalse\n  | FTrue =>\n      FTrue\n  | FAnd f1 f2 =>\n      conjunction (minusinf f1) (minusinf f2)\n  | FOr f1 f2 =>\n      disjunction (minusinf f1) (minusinf f2)\n  | FNot f =>\n      negation (minusinf f)\n\n  end.\n\n(* For sufficiently large negative [x], [f] and [minusinf f] are equivalent. *)\n\nLemma interpret_minusinf:\n  forall cenv env f,\n  all normal f ->\n  exists y,\n  forall x, x < y ->\n  interpret_formula cenv (extend env x) f <->\n  interpret_formula cenv (extend env x) (minusinf f).\nProof.\n  induction 1; simpl; try solve [ exists 0; tauto ].\n  (* Case [FAtom]. *)\n  predicate; term; unfold normal in *; unpack;\n  try solve [ exists 0; tauto ];\n  try match goal with h: ?c = -1 \\/ ?c = 1 |- _ => destruct h end;\n  subst; simpl.\n  (* Sub-case: an atom [0 = x + t]. This equality cannot be satisfied\n     as [x] tends towards minus infinity. *)\n  exists (- interpret_term cenv (extend env 0) t). intros.\n  erewrite extend_insensitive with (n2 := 0). lia. eassumption. lia.\n  (* Sub-case: an atom [0 < -x + t]. This equality is satisfied\n     as [x] tends towards minus infinity. *)\n  exists (interpret_term cenv (extend env 0) t). intros.\n  erewrite extend_insensitive with (n2 := 0). lia. eassumption. lia.\n  (* Sub-case: an atom [0 < x + t]. This equality cannot be satisfied\n     as [x] tends towards minus infinity. *)\n  exists (- interpret_term cenv (extend env 0) t). intros.\n  erewrite extend_insensitive with (n2 := 0). lia. eassumption. lia.\n  (* Case [FAnd]. *)\n  destruct IHall1 as [ y1 ih1 ].\n  destruct IHall2 as [ y2 ih2 ].\n  exists (Z.min y1 y2). intros.\n  unpack (Z.le_min_l y1 y2).\n  unpack (Z.le_min_r y1 y2).\n  rewrite interpret_conjunction.\n  rewrite ih1; try omega.\n  rewrite ih2; try omega.\n  tauto.\n  (* Case [FOr]. *)\n  destruct IHall1 as [ y1 ih1 ].\n  destruct IHall2 as [ y2 ih2 ].\n  exists (Z.min y1 y2). intros.\n  unpack (Z.le_min_l y1 y2).\n  unpack (Z.le_min_r y1 y2).\n  rewrite interpret_disjunction.\n  rewrite ih1; try omega.\n  rewrite ih2; try omega.\n  tauto.\n  (* Case [FNot]. *)\n  destruct IHall as [ y ih ].\n  exists y. intros.\n  rewrite interpret_negation.\n  rewrite ih; try omega.\n  tauto.\nQed.\n\nLemma wf_minusinf:\n  forall f,\n  wff f ->\n  wff (minusinf f).\nProof.\n  induction f; intros; simpl in *; wff;\n  eauto using wf_conjunction, wf_disjunction, wf_negation.\n  wff; wfp; wft; eauto;\n  match goal with |- wff (match ?y with _ => _ end) =>\n    destruct y\n  end; try case_if; eauto.\nQed.\n\nLemma nnf_minusinf:\n  forall f,\n  nnf f ->\n  nnf (minusinf f).\nProof.\n  induction f; intros; nnf; simpl in *;\n    eauto using nnf_conjunction, nnf_disjunction.\n  { predicate; term; eauto; case_if; eauto. }\n  { predicate; term; eauto; simpl in *; eauto; congruence. }\nQed.\n\nLemma sink_minusinf_equiv:\n  forall cenv env f,\n  all normal f ->\n  sink (fun x => interpret_formula cenv (extend env x) f) <->\n  sink (fun x => interpret_formula cenv (extend env x) (minusinf f)).\nProof.\n  intros * Hn.\n  pose proof (interpret_minusinf cenv env Hn) as [y0 Hy0].\n  split.\n  { intros H x. destruct (H (Z.min x y0)) as [y' [? ?]].\n    exists y'. rewrite <-Hy0 by lia. split; auto. lia. }\n  { intros H x. destruct (H (Z.min x y0)) as [y' [? ?]].\n    exists  y'. rewrite Hy0 by lia. split; auto. lia. }\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Compute the least common multiple of the division atoms that involve [x]. *)\n\nFixpoint divlcm (f : formula) : num :=\n  match f with\n  | FAtom (Dv d) (TSummand c 0 _) =>\n    (* [d] is positive *)\n    d\n  | FAnd f1 f2\n  | FOr f1 f2 =>\n    Z.lcm (divlcm f1) (divlcm f2)\n  | FNot f =>\n    divlcm f\n  | _ =>\n    1\n  end.\n\n(* Characterize what is computed: a common multiple of all division atoms\n   involving [x]. The fact that this is the least common multiple does not seem\n   to be required for soundness. *)\n\n(* We write [all (dvdvx l) f] when all division atoms involving [x] in the\n   formula [f] divide [l]. *)\n\nDefinition dvdvx (l : num) (p : predicate) (t : term) : Prop :=\n  match p with\n  | Dv c =>\n    match t with\n    | TSummand _ 0 _ => (c | l)\n    | _ => True\n    end\n  | Eq | Lt =>\n    True\n  end.\n\nLemma dvdvx_transitive:\n  forall l1 l2 p t,\n  dvdvx l1 p t ->\n  (l1 | l2) ->\n  dvdvx l2 p t.\nProof.\n  intros. predicate; term; simpl in *; eauto using Z.divide_trans.\nQed.\n\nLemma all_dvdvx_transitive:\n  forall l1 l2 f,\n  all (dvdvx l1) f ->\n  (l1 | l2) ->\n  all (dvdvx l2) f.\nProof.\n  induction 1; intros; econstructor; eauto using dvdvx_transitive.\nQed.\n\nLemma all_dvdvx_divlcm:\n  forall f,\n  wff f ->\n  all (dvdvx (divlcm f)) f.\nProof.\n  induction f; intros; try all; simpl; try solve [ econstructor ].\n  (* Case: [FAtom]. *)\n  { econstructor. unfold dvdvx. predicate; term; eauto using Z.divide_refl. }\n  (* Case: [FAnd]. *)\n  { econstructor; eapply all_dvdvx_transitive;\n    eauto using Z.divide_lcm_l, Z.divide_lcm_r. }\n  (* Case: [FOr]. *)\n  { econstructor; eapply all_dvdvx_transitive;\n    eauto using Z.divide_lcm_l, Z.divide_lcm_r. }\n  (* Case: [FNot]. *)\n  { econstructor; eauto. }\nQed.\n\nLemma divlcm_nonneg:\n  forall f,\n  wff f ->\n  0 < divlcm f.\nProof.\n  induction 1; simpl; eauto using Zlcm_pos with zarith.\n  (* Case: [FAtom]. *)\n  term; wff; wft; wfp; try omega.\nQed.\n\n(* [minusinf f] is invariant by changing [x] to [x + k * (divlcm f)] for any\n   [k]. *)\n\nLemma interpret_minusinf_modulo_dvdvx:\n  forall cenv env f x k D,\n  wff f ->\n  all (dvdvx D) f ->\n  interpret_formula cenv (extend env x) (minusinf f) <->\n  interpret_formula cenv (extend env (x + k * D)) (minusinf f).\nProof.\n  intros cenv env f.\n  functional induction (minusinf f); intros; simpl; try tauto.\n  { predicate; term; wff; wff; wft; simpl in *; try tauto;\n    try solve [ erewrite extend_insensitive by eauto; reflexivity ].\n    all; simpl in *.\n    erewrite extend_insensitive with (n2 := x + k * D) by eauto.\n    rewrite Z.mul_add_distr_l.\n    rewrite <-Z.add_assoc, (Z.add_comm (z0 * (k * D))), Z.add_assoc.\n    split; intro HD.\n    - eauto with zarith.\n    - rewrite Z.add_comm in HD.\n      eapply Z.divide_add_cancel_r; [| apply HD].\n      eauto with zarith. }\n  { wff. }\n  { wff. all. rewrite !interpret_conjunction.\n    rewrite (IHf0 x k D), (IHf1 x k D) by auto. tauto. }\n  { wff. all. rewrite !interpret_disjunction.\n    rewrite (IHf0 x k D), (IHf1 x k D) by auto. tauto. }\n  { wff. all. rewrite !interpret_negation.\n    rewrite (IHf0 x k D) by auto. tauto. }\nQed.\n\nLemma interpret_minusinf_modulo_divlcm:\n  forall cenv env f x k,\n  wff f ->\n  interpret_formula cenv (extend env x) (minusinf f) <->\n  interpret_formula cenv (extend env (x + k * (divlcm f))) (minusinf f).\nProof.\n  intros. eauto using interpret_minusinf_modulo_dvdvx, all_dvdvx_divlcm.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* If [P] is invariant by translation modulo [D], then [sink P] is equivalent to\n   a big disjunction (thus eliminating an existential quantifier). *)\n\nLemma sink_invariant_modulo_equiv_exists:\n  forall P : Z -> Prop,\n  forall D : Z,\n  0 < D ->\n  (forall x k, P x <-> P (x + k * D)) ->\n  sink P <-> (exists y, P y).\nProof.\n  intros * HD HPinv.\n  split.\n  { (* the trivial case *)\n    intros H. destruct (H 0) as [y [? ?]]. eauto. }\n  { intros [y Hy] x. destruct (Z_lt_le_dec y x). now eauto.\n    exists (y + ((x - y) / D - 1) * D); split; cycle 1.\n    now rewrite <-HPinv. pose proof (Z.mul_div_le (x - y) D); lia. }\nQed.\n\nLemma invariant_modulo_exists_equiv_big_or:\n  forall P : Z -> Prop,\n  forall D : Z,\n  0 < D ->\n  (forall x k, P x <-> P (x + k * D)) ->\n  (exists y, P y) <-> big_or P (interval D).\nProof.\n  intros * HD HPinv.\n  split.\n  { intros [y Hy]. apply big_or_prove with (y mod D).\n    - pose proof (Z.mod_pos_bound y D). rewrite In_interval. lia.\n    - rewrite HPinv with (k := y / D).\n      rewrite Z.add_comm, Z.mul_comm, <-Z.div_mod; auto. }\n  { intro H. destruct (big_or_inv _ _ H) as [i [H1 H2]]. eauto. }\nQed.\n\nLemma sink_equiv_big_or:\n  forall P : Z -> Prop,\n  forall D : Z,\n  0 < D ->\n  (forall x k, P x <-> P (x + k * D)) ->\n  sink P <-> big_or P (interval D).\nProof.\n  intros.\n  rewrite sink_invariant_modulo_equiv_exists with D by auto.\n  apply invariant_modulo_exists_equiv_big_or; auto.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Substitution of a term [t] for a variable [x] within a formula. *)\n\nFixpoint subst (t : term) (f : formula) : formula :=\n  match f with\n  | FAtom p (TSummand c 0 u) =>\n    FAtom p (add (mul c t) u)\n  | FNot f =>\n    FNot (subst t f)\n  | FAnd f1 f2 =>\n    FAnd (subst t f1) (subst t f2)\n  | FOr f1 f2 =>\n    FOr (subst t f1) (subst t f2)\n  | _ =>\n    f\n  end.\n\nLemma interpret_subst:\n  forall cenv env f t u,\n  wff f ->\n  interpret_formula cenv (extend env u) (subst t f) <->\n  interpret_formula cenv (extend env (interpret_term cenv (extend env u) t)) f.\nProof.\n  induction 1; simpl; try tauto.\n  term; wff; wft; simpl in *.\n  rewrite interpret_add, interpret_mul.\n  erewrite extend_insensitive with\n    (n1:=interpret_term cenv (extend env u) t) (n2:=u) by eauto.\n  tauto.\n  erewrite extend_insensitive. reflexivity. eauto. eauto.\n  tauto.\nQed.\n\nLemma wf_subst:\n  forall f t,\n  wft 0 t ->\n  wff f ->\n  wff (subst t f).\nProof.\n  induction f; intros; simpl in *; wff; eauto.\n  wff. destruct t; [destruct n|]; wft; eauto .\n  constructor. split; auto. apply wf_add. apply wf_mul; auto.\n  eapply wft_monotone. eauto. omega.\nQed.\n\nNotation wff1 f := (all (fun p t => wft 1 t /\\ wfp p) f).\n\nLemma wf1_subst:\n  forall f t,\n  wft 1 t ->\n  wff f ->\n  wff1 (subst t f).\nProof.\n  induction f; intros; simpl in *; wff; eauto.\n  wff. destruct t; [destruct n|]; wft; eauto using wf_add, wf_mul.\nQed.\n\nLemma nnf_subst:\n  forall f t,\n  nnf f ->\n  nnf (subst t f).\nProof.\n  induction f; intros; simpl in *; nnf; eauto; simpl;\n  repeat\n    match goal with |- context [ match ?x with _ => _ end ] => destruct x end;\n  eauto.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Shifting (down) all the de Bruijn variables of a term. This only makes sense\n   if the first variable does not appear in the term. *)\n\nFixpoint shift_term (t : term) : term :=\n  match t with\n  | TSummand c (S n) u =>\n    TSummand c n (shift_term u)\n  | _ =>\n    t\n  end.\n\nLemma wf_shift_term:\n  forall t n,\n  wft (S n) t ->\n  wft n (shift_term t).\nProof.\n  induction t; intros; wft; simpl; try now constructor.\n  destruct n; auto with zarith.\nQed.\n\nLemma interpret_shift_term:\n  forall cenv env t x,\n  wft 1 t ->\n  interpret_term cenv (extend env x) t = interpret_term cenv env (shift_term t).\nProof.\n  induction t; intros; simpl in *; auto.\n  wft. rewrite IHt. now destruct n.\n  eapply wft_monotone; eauto with zarith.\nQed.\n\n(* Same with a formula. *)\n\nFixpoint shift (f : formula) : formula :=\n  match f with\n  | FAtom p t =>\n    FAtom p (shift_term t)\n  | FNot f =>\n    FNot (shift f)\n  | FAnd f1 f2 =>\n    FAnd (shift f1) (shift f2)\n  | FOr f1 f2 =>\n    FOr (shift f1) (shift f2)\n  | f =>\n    f\n  end.\n\nLemma interpret_shift:\n  forall cenv env f x,\n  wff1 f ->\n  interpret_formula cenv env (shift f) <->\n  interpret_formula cenv (extend env x) f.\nProof.\n  induction 1; simpl in *; try tauto.\n  wff. rewrite interpret_shift_term; tauto.\nQed.\n\nLemma wf_shift:\n  forall f,\n  wff1 f ->\n  wff (shift f).\nProof.\n  induction f; intros; simpl in *; all; unpack; eauto using wf_shift_term.\nQed.\n\nLemma nnf_shift:\n  forall f,\n  nnf f ->\n  nnf (shift f).\nProof.\n  induction f; intros; simpl in *; nnf; eauto. constructor. auto.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Quantifier elimination for formulas, in the \"sink\" case. *)\n\nNotation sink_interpret cenv env f :=\n  (sink (fun x => interpret_formula cenv (extend env x) f)).\n\nNotation sink_interpret_qe cenv env f := (\n  interpret_formula cenv env (\n    big_disjunction (fun i => subst (TConstant (CGround i)) (minusinf f))\n      (interval (divlcm f))\n  )\n).\n\nLemma sink_qe:\n  forall cenv env f u,\n  all normal f ->\n  sink_interpret cenv env f <-> sink_interpret_qe cenv (extend env u) f.\nProof.\n  intros. rewrite sink_minusinf_equiv by auto.\n  rewrite sink_equiv_big_or with (D := divlcm f); cycle 1.\n  now apply divlcm_nonneg; auto.\n  now eauto using interpret_minusinf_modulo_divlcm.\n  rewrite interpret_big_disjunction. apply big_or_extens.\n  intro. rewrite interpret_subst. reflexivity.\n  now apply wf_minusinf; auto.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n(* We now turn to the other case, where the set of solutions is bounded. *)\n\n(* Constructing the B-set. *)\n\n(* We slightly modify the boundary points returned by [bset] compared to the\n   description given e.g. in Harrison's book: in order to have [0 <= j < D]\n   instead of [1 <= j <= D] in [bset_correct] below, we have to add 1 to the\n   boundary points we return here.\n\n   Having intervals [0, n) instead of [1, n] makes the proofs easier...\n *)\n\nFunction bset (f : formula) : list term :=\n  match f with\n  | FNot (FAtom Eq (TSummand c 0 u)) =>\n    (* [c] = 1 *)\n    (* The atom is [0 <> x + u]. This changes from true to false when [x] is\n       [-u+1]. *)\n    [ add (neg u) (TConstant (CGround 1)) ]\n  | FAtom Eq (TSummand c 0 u) =>\n    (* [c] = 1 *)\n    (* The atom is [0 = x + u]. This changes from true to false when [x] is\n       [-u]. *)\n    [ neg u ]\n  | FAtom Lt (TSummand c 0 u) =>\n    if Z.eqb c 1 then\n      (* The atom is [0 < x + u]. This changes from true to false when [x] is\n         [-u+1]. *)\n      [ add (neg u) (TConstant (CGround 1)) ]\n    else\n      (* [c] = -1 *)\n      []\n  | FNot (FAtom _ _) =>\n    []\n  | FNot _ =>\n    (* Impossible case since [f] is assumed to be in NNF *)\n    []\n  | FAnd f1 f2\n  | FOr f1 f2 =>\n    (* TEMPORARY eliminate duplicates, implement sets of terms *)\n    bset f1 ++ bset f2\n  | _ =>\n    []\n  end.\n\n(* Terms in [bset f] do not contain the variable [x]. *)\n\nLemma wf1_bset:\n  forall f,\n  wff f ->\n  Forall (wft 1) (bset f).\nProof.\n  induction f; intros; wff; simpl in *; eauto using Forall_app.\n  { predicate; term; wff; wft; simpl in *; try case_if;\n      eauto using wf_neg, wf_add, wf_neg. }\n  { destruct f; eauto. do 2 wff. predicate; term; eauto.\n    wft. eauto using wf_add, wf_neg. }\nQed.\n\nLemma wf1_In_bset:\n  forall f t,\n  wff f ->\n  In t (bset f) ->\n  wft 1 t.\nProof.\n  intros. applyin wf1_bset. rewrite Forall_forall in *. eauto.\nQed.\n\nLemma bset_correct:\n  forall cenv env f D x u,\n  all normal f ->\n  nnf f ->\n  0 < D ->\n  all (dvdvx D) f ->\n  interpret_formula cenv (extend env x) f ->\n  ~ interpret_formula cenv (extend env (x - D)) f ->\n  exists b j,\n    x = interpret_term cenv (extend env u) b + j /\\\n    In b (bset f) /\\\n    0 <= j < D.\nProof.\n  intros cenv env f.\n  functional induction (bset f); intros; simpl in *;\n    repeat all; unfold normal in *; unpack.\n  { (* Atom [0 <> x + u] *)\n    subst c. rewrite Z.mul_1_l in *. classical.\n    exists (add (neg u) (TConstant (CGround 1))). (* b = -u+1 *)\n    exists (D - 1). (* j = D-1 *)\n    rewrite interpret_add, interpret_neg. simpl.\n    erewrite extend_insensitive with (n2:=x); eauto.\n    erewrite extend_insensitive with (n1:=x-D) (n2:=x) in *; eauto.\n    eauto with zarith. }\n  { (* Atom [0 = x + u] *)\n    subst c. rewrite Z.mul_1_l in *.\n    exists (neg u). (* b = -u *)\n    exists 0. (* j = 0 *)\n    erewrite extend_insensitive with (n2:=x); eauto using wf_neg, wf_add.\n    rewrite interpret_neg. eauto with zarith. }\n  { (* Atom [0 < x + u] *)\n    rewrite Z.eqb_eq in *. subst c. rewrite Z.mul_1_l in *.\n    exists (add (neg u) (TConstant (CGround 1))). (* b = -u+1 *)\n    rewrite <-Z.le_ngt in *.\n    erewrite extend_insensitive with (n1:=x-D) (n2:=x) in *; eauto.\n    erewrite extend_insensitive with (n2:=x); eauto using wf_add, wf_neg.\n    rewrite interpret_add, interpret_neg. simpl.\n    set (u' := interpret_term cenv (extend env x) u) in *.\n    assert (-u' + 1 <= x <= -u' + D) by lia.\n    exists (x + u' - 1). (* j *) eauto with zarith. }\n  { (* Atom [0 < - x + u] *)\n    rewrite Z.eqb_neq in *. exfalso.\n    erewrite extend_insensitive with (n1:=x-D) (n2:=x) in *; eauto.\n    nia. }\n  { exfalso. predicate; term; nnf; simpl in *; eauto; classical.\n    - wft. erewrite extend_insensitive with (n1:=x-D) in *; eauto.\n    - unpack. subst. rewrite Z.mul_1_l in *.\n      erewrite extend_insensitive with (n1:=x-D) (n2:=x) in *; eauto.\n      match goal with h: ~ (_ | _) |- _ => apply h end.\n      apply Z.divide_add_cancel_r with (-D).\n      auto with zarith.\n      rewrite Z.add_assoc, Z.add_opp_l. auto.\n    - wft. erewrite extend_insensitive with (n1:=x-D) (n2:=x) in *; eauto. }\n  { nnf. exfalso. predicate; term; eauto. }\n  { nnf. classical.\n    match goal with h: _ \\/ _ |- _ => destruct h end; [ spec IHl | spec IHl0 ];\n      unpack; do 2 eexists; repeat split; eauto using in_or_app. }\n  { nnf. classical. unpack.\n    match goal with h: _ \\/ _ |- _ => destruct h end; [ spec IHl | spec IHl0 ];\n      unpack; do 2 eexists; repeat split; eauto using in_or_app. }\n  { exfalso.\n    destruct f; simpl in *; eauto; repeat all.\n    - predicate; term; eauto; unfold normal in *; unpack; simpl in *.\n      + wft. erewrite extend_insensitive with (n1:=x-D) (n2:=x) in *; eauto.\n      + wft. erewrite extend_insensitive with (n1:=x-D) (n2:=x) in *; eauto.\n      + match goal with h: ~ (_ | _) |- _ => apply h end.\n        rewrite Z.mul_sub_distr_l, <-Z.add_sub_swap.\n        apply Z.divide_sub_r; eauto with zarith.\n        erewrite extend_insensitive with (n1:=x-D) (n2:=x); eauto.\n      + wft. erewrite extend_insensitive with (n1:=x-D) (n2:=x) in *; eauto.\n    - destruct f; eauto; predicate; term; eauto. }\nQed.\n\nLemma bset_correct_divlcm:\n  forall cenv env f x u,\n  all normal f ->\n  nnf f ->\n  interpret_formula cenv (extend env x) f ->\n  ~ interpret_formula cenv (extend env (x - divlcm f)) f ->\n  exists b j,\n    x = interpret_term cenv (extend env u) b + j /\\\n    In b (bset f) /\\\n    0 <= j < divlcm f.\nProof.\n  intros.\n  apply bset_correct; auto.\n  now apply divlcm_nonneg; auto.\n  now apply all_dvdvx_divlcm; auto.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Quantifier elimination for formulas, in the \"least element\" case. *)\n\nNotation least_element_interpret cenv env f :=\n  (least_element (fun x => interpret_formula cenv (extend env x) f)).\n\nNotation least_element_interpret_qe cenv env f := (\n  interpret_formula cenv env (\n    big_disjunction (fun i =>\n      big_disjunction (fun b =>\n        subst (add b (TConstant (CGround i))) f\n      ) (bset f)\n    ) (interval (divlcm f))\n  )\n).\n\nLemma least_element_qe_impl:\n  forall cenv env f u,\n  all normal f ->\n  nnf f ->\n  least_element_interpret cenv env f ->\n  least_element_interpret_qe cenv (extend env u) f.\nProof.\n  intros * ? ? [x [Hf Hnf]]. pose (D := divlcm f).\n  specialize (Hnf (x - D)). spec1 Hnf.\n  { enough (0 < D) by lia. eauto using divlcm_nonneg. }\n  rewrite interpret_big_disjunction2.\n  destruct (@bset_correct_divlcm cenv env f x u) as [b [j (Hx&?&?)]]; auto.\n  apply big_or_prove with j; auto. rewrite In_interval; auto.\n  apply big_or_prove with b; auto.\n  rewrite interpret_subst by auto. rewrite interpret_add. simpl.\n  rewrite Hx in Hf. apply Hf.\nQed.\n\n(* We do not actually need to prove the equivalence for the final theorem to\n   hold. For the reverse direction, we only need to prove this: *)\n\nLemma least_element_qe_rev:\n  forall cenv env f u,\n  all normal f ->\n  nnf f ->\n  least_element_interpret_qe cenv (extend env u) f ->\n  exists x, interpret_formula cenv (extend env x) f.\nProof.\n  intros ? ? ? ? ? ? Hqe.\n  rewrite interpret_big_disjunction in Hqe.\n  apply big_or_inv in Hqe. destruct Hqe as [j [? Hqe]].\n  rewrite interpret_big_disjunction in Hqe.\n  apply big_or_inv in Hqe. destruct Hqe as [b [? Hqe]].\n  rewrite interpret_subst, interpret_add in Hqe; eauto using wf_unity.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* The main function of the implementation. [cooper] eliminates one existential\n   quantifier. *)\n\nDefinition cooper (f : formula) : formula :=\n  let f := unity f in\n  let f_inf := minusinf f in\n  let bs := bset f in\n  let js := interval (divlcm f) in\n  let f_element := (fun j b => subst (add b (TConstant (CGround j))) f) in\n  let stage := (fun j =>\n    disjunction (subst (TConstant (CGround j)) f_inf)\n                (big_disjunction (f_element j) bs)\n  ) in\n  shift (big_disjunction stage js).\n\n(* [cooper f] is equivalent to [FExists f], and is quantifier-free. *)\n\nLemma interpret_cooper:\n  forall cenv env f,\n  wff f ->\n  nnf f ->\n  interpret_formula cenv env (cooper f) <->\n  interpret_formula cenv env (FExists f).\nProof.\n  intros.\n  rewrite interpret_unity by auto. simpl.\n  unfold cooper.\n  (* 0 is a dummy value, associated in the environment to variable [x],\n     which does not happen in the term. *)\n  rewrite interpret_shift with (x:=0); cycle 1.\n  { apply all_big_disjunction. intros. apply all_disjunction.\n    - now apply wf1_subst, wf_minusinf, wf_unity.\n    - apply all_big_disjunction. intros. apply wf1_subst.\n      + apply wf_add; auto. eapply wf1_In_bset;[|eassumption]. now apply wf_unity.\n      + now apply wf_unity. }\n\n  rewrite interpret_big_disjunction.\n  erewrite big_or_extens; cycle 1.\n  { intro. match goal with |- _ <-> ?x => set (toto := x) end.\n    rewrite interpret_disjunction.\n    subst toto. apply iff_refl. }\n  rewrite big_or_distr.\n\n  rewrite exists_equiv_sink_or_least_element.\n  assert (HH: forall (A B C D: Prop),\n             A <-> C ->\n             (D -> B) ->\n             (B -> C \\/ D) ->\n             A \\/ B <-> C \\/ D) by tauto.\n  apply HH; clear HH.\n\n  { (* QE for the \"sink\" case. *)\n    rewrite sink_qe. rewrite interpret_big_disjunction. reflexivity.\n    apply normal_unity; auto. }\n\n  { (* QE for the \"least element\" case (-> direction). *)\n    rewrite <-interpret_big_disjunction.\n    apply least_element_qe_impl. now apply normal_unity. now apply nnf_unity. }\n\n  { (* QE for the \"least element\" case (<- direction). *)\n    rewrite <-interpret_big_disjunction.\n    rewrite <-exists_equiv_sink_or_least_element.\n    apply least_element_qe_rev. now apply normal_unity. now apply nnf_unity. }\nQed.\n\n(* [cooper] preserves well-formedness and the negative normal form *)\n\nLemma wf_cooper:\n  forall f,\n  wff f ->\n  wff (cooper f).\nProof.\n  (* In theory this proof could be a single [eauto using] invocation, but it\n     doesn't work for some reason. *)\n  intros. unfold cooper.\n  apply wf_shift.\n  apply all_big_disjunction. intros.\n  apply all_disjunction. now eauto using wf1_subst, wf_minusinf, wf_unity.\n  apply all_big_disjunction. intros.\n  apply wf1_subst. now eauto using wf1_subst, wf_unity, wf_add, wf1_In_bset.\n  now apply wf_unity.\nQed.\n\nLemma nnf_cooper:\n  forall f,\n  nnf f ->\n  nnf (cooper f).\nProof.\n  intros. unfold cooper.\n  apply nnf_shift, nnf_big_disjunction. intros.\n  apply nnf_disjunction.\n  now apply nnf_subst, nnf_minusinf, nnf_unity.\n  apply nnf_big_disjunction. intros.\n  now apply nnf_subst, nnf_unity.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n(* A simplification procedure for terms & formulas *)\n\nFixpoint simpl_term (t : term) : term :=\n  match t with\n  | TSummand k y u =>\n    TSummand k y (simpl_term u)\n  | TConstant c =>\n    TConstant (simpl_constant c)\n  end.\n\nDefinition boolf (b : bool) : formula :=\n  match b with\n  | true => FTrue\n  | false => FFalse\n  end.\n\nDefinition Zdivideb (x y : Z) : bool :=\n  if Zdivide_dec x y then true else false.\n\nFunction simpl_atom (p : predicate) (t : term) : formula :=\n  match t with\n  | TConstant (CGround k) =>\n    match p with\n    | Eq => boolf (Z.eqb 0 k)\n    | Lt => boolf (Z.ltb 0 k)\n    | Dv z => boolf (Zdivideb z k)\n    end\n  | _ => FAtom p t\n  end.\n\nFixpoint simpl_formula (f : formula) : formula :=\n  match f with\n  | FAtom p t =>\n    simpl_atom p (simpl_term t)\n  | FFalse =>\n    FFalse\n  | FTrue =>\n    FTrue\n  | FAnd f1 f2 =>\n    conjunction (simpl_formula f1) (simpl_formula f2)\n  | FOr f1 f2 =>\n    disjunction (simpl_formula f1) (simpl_formula f2)\n  | FNot f =>\n    negation (simpl_formula f)\n  | FExists f =>\n    FExists (simpl_formula f)\n  end.\n\nLemma interpret_simpl_term:\n  forall cenv env t,\n  interpret_term cenv env (simpl_term t) =\n  interpret_term cenv env t.\nProof.\n  induction t; intros; simpl in *; eauto using interpret_simpl_constant.\nQed.\n\nLemma wft_simpl_term:\n  forall t n,\n  wft n t ->\n  wft n (simpl_term t).\nProof. induction t; intros; simpl in *; wft; eauto. Qed.\n\nLemma interpret_simpl_atom:\n  forall cenv env p t,\n  interpret_formula cenv env (simpl_atom p t) <->\n  interpret_formula cenv env (FAtom p t).\nProof.\n  intros.\n  functional induction (simpl_atom p t); unfold boolf, Zdivideb in *;\n    repeat case_if; simpl;\n    rewrite ?Z.eqb_eq, ?Z.eqb_neq, ?Z.ltb_lt, ?Z.ltb_ge in *;\n    try lia; try tauto; discriminate.\nQed.\n\nLemma wf_simpl_atom:\n  forall p t,\n  wft 0 t ->\n  wfp p ->\n  wff (simpl_atom p t).\nProof.\n  intros.\n  functional induction (simpl_atom p t); unfold boolf; cbn -[Z.eqb]; eauto;\n    case_if; eauto.\nQed.\n\nLemma interpret_simpl_formula:\n  forall cenv f env,\n  interpret_formula cenv env (simpl_formula f) <->\n  interpret_formula cenv env f.\nProof.\n  induction f; intros; simpl in *; eauto; try tauto.\n  - now rewrite interpret_simpl_atom; simpl; rewrite interpret_simpl_term.\n  - rewrite interpret_conjunction, IHf1, IHf2. tauto.\n  - rewrite interpret_disjunction, IHf1, IHf2. tauto.\n  - rewrite interpret_negation, IHf. tauto.\n  - apply exists_equivalence. eauto.\nQed.\n\nLemma wf_simpl_formula:\n  forall f,\n  wff f ->\n  wff (simpl_formula f).\nProof.\n  induction f; intros; simpl in *; wff; unpack;\n    eauto using wft_simpl_term, wf_simpl_atom,\n    wf_conjunction, wf_disjunction, wf_negation.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* The main quantifier elimination algorithm: [qe] turns a formula into an\n   equivalent quantifier-free formula. *)\n\nFunction map_disjuncts (transform : formula -> formula) (f : formula) :=\n  match f with\n  | FOr f1 f2 =>\n    disjunction (transform f1) (transform f2)\n  | FFalse =>\n    FFalse\n  | _ =>\n    transform f\n  end.\n\nFixpoint qe (f : formula) : formula :=\n  match f with\n  | FAtom _ _ | FFalse | FTrue =>\n    f\n  | FAnd f1 f2 =>\n    conjunction (qe f1) (qe f2)\n  | FOr f1 f2 =>\n    disjunction (qe f1) (qe f2)\n  | FNot f =>\n    negation (qe f)\n  | FExists f =>\n    (* Innermost quantifiers are eliminated first. *)\n    let f := qe f in\n    (* Bring the body into NNF. *)\n    let f := posnnf f in\n    (* An existential quantifier can be pushed into a disjunction, so each\n       toplevel disjunct can be treated independently. Over each disjunct, apply\n       [cooper] to eliminate the existential quantifier. *)\n    let f := map_disjuncts cooper f in\n    simpl_formula f\n  end.\n\n(* ------------------------------------------------------------------------- *)\n\n(* Like [all], but also under exists. *)\nInductive all_under_ex (P : predicate -> term -> Prop) : formula -> Prop :=\n| all_under_ex_FAtom:\n    forall p t,\n    P p t ->\n    all_under_ex P (FAtom p t)\n| all_under_ex_FFalse:\n    all_under_ex P FFalse\n| all_under_ex_FTrue:\n    all_under_ex P FTrue\n| all_under_ex_FAnd:\n    forall f1 f2,\n    all_under_ex P f1 ->\n    all_under_ex P f2 ->\n    all_under_ex P (FAnd f1 f2)\n| all_under_ex_FOr:\n    forall f1 f2,\n    all_under_ex P f1 ->\n    all_under_ex P f2 ->\n    all_under_ex P (FOr f1 f2)\n| all_under_ex_FNot:\n    forall f,\n    all_under_ex P f ->\n    all_under_ex P (FNot f)\n| all_under_ex_FExists:\n    forall f,\n    all_under_ex P f ->\n    all_under_ex P (FExists f).\n\nHint Constructors all_under_ex.\n\nNotation wff_ue f := (all_under_ex (fun p t => wft 0 t /\\ wfp p) f).\n\nLtac wff_ue :=\n  match goal with h: wff_ue _ |- _ => depelim h end.\n\n(* ------------------------------------------------------------------------- *)\n(* [qe f] is equivalent to [f], and does not contain quantifiers. *)\n\nLemma all_map_disjuncts:\n  forall transform f P,\n  all P f ->\n  (forall x, all P x -> all P (transform x)) ->\n  all P (map_disjuncts transform f).\nProof.\n  intros. destruct f; simpl; eauto.\n  all. apply all_disjunction; eauto.\nQed.\n\n(* This entails that [qe f] is quantifier-free. *)\nLemma wf_qe:\n  forall f,\n  wff_ue f ->\n  wff (qe f).\nProof.\n  induction f; intros; simpl in *; wff_ue;\n    eauto using wf_conjunction, wf_disjunction, wf_negation.\n  apply wf_simpl_formula, all_map_disjuncts; eauto using wf_posnnf, wf_cooper.\nQed.\n\n(* [qe f] is equivalent to [f]. *)\n\nLemma interpret_qe:\n  forall cenv f env,\n  wff_ue f ->\n  interpret_formula cenv env (qe f) <-> interpret_formula cenv env f.\nProof.\n  induction f; intros; wff_ue; simpl in * |-; try tauto;\n  [ repeat match goal with\n      h: forall e:environment, _ |- _ => specialize (h env)\n    end; simpl\n  .. | ].\n  rewrite interpret_conjunction; tauto.\n  rewrite interpret_disjunction; tauto.\n  rewrite interpret_negation; tauto.\n\n  (* FExists case *)\n  cbn [qe].\n  assert (wff (posnnf (qe f))). now apply wf_posnnf, wf_qe.\n  assert (nnf (posnnf (qe f))). now apply nnf_posnnf, qf_wff, wf_qe.\n  transitivity (interpret_formula cenv env (cooper (posnnf (qe f)))); cycle 1.\n  { rewrite interpret_cooper by auto. simpl. apply exists_equivalence.\n    intro. rewrite interpret_posnnf. auto. }\n\n  rewrite interpret_simpl_formula.\n  functional induction (map_disjuncts cooper (posnnf (qe f))); try tauto;[].\n  rewrite interpret_disjunction. wff. nnf.\n  rewrite !interpret_cooper by auto.\n  simpl. split.\n  { intros HH. destruct HH as [[x ?]|[x ?]]; exists x; tauto. }\n  { intros HH. destruct HH as [x [?|?]]; [left|right]; exists x; tauto. }\nQed.\n", "meta": {"author": "Armael", "repo": "minicooper", "sha": "3f051307039456a88cf093921278b0dcf224f7cf", "save_path": "github-repos/coq/Armael-minicooper", "path": "github-repos/coq/Armael-minicooper/minicooper-3f051307039456a88cf093921278b0dcf224f7cf/src/Theory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6685952177542034}}
{"text": "(* This file is a modification of an eponymous file from the CoqApprox        *)\n(* library. The header of the original file is reproduced below. Changes are  *)\n(* part of the analysis library and enjoy the same licence as this library.   *)\n(**\nThis file is part of the CoqApprox formalization of rigorous\npolynomial approximation in Coq:\nhttp://tamadi.gforge.inria.fr/CoqApprox/\n\nCopyright (c) 2010-2013, ENS de Lyon and Inria.\n\nThis library is governed by the CeCILL-C license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the library under the terms of the CeCILL-C\nlicense as circulated by CEA, CNRS and Inria at the following URL:\nhttp://www.cecill.info/\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided\nonly with a limited warranty and the library's author, the holder of\nthe economic rights, and the successive licensors have only limited\nliability. See the COPYING file for more details.\n*)\n\nRequire Import Rdefinitions Raxioms RIneq Rbasic_fun Zwf.\nRequire Import Epsilon FunctionalExtensionality Ranalysis1 Rsqrt_def.\nRequire Import Rtrigo1 Reals.\nFrom mathcomp Require Import all_ssreflect ssralg poly mxpoly ssrnum.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nImport Order.TTheory GRing.Theory Num.Theory.\n\nLocal Open Scope R_scope.\n\nLemma Req_EM_T (r1 r2 : R) : {r1 = r2} + {r1 <> r2}.\nProof.\ncase: (total_order_T r1 r2) => [[r1Lr2 | <-] | r1Gr2].\n- by right=> r1Er2; case: (Rlt_irrefl r1); rewrite {2}r1Er2.\n- by left.\nby right=> r1Er2; case: (Rlt_irrefl r1); rewrite {1}r1Er2.\nQed.\n\nDefinition eqr (r1 r2 : R) : bool :=\n  if Req_EM_T r1 r2 is left _ then true else false.\n\nLemma eqrP : Equality.axiom eqr.\nProof.\nby move=> r1 r2; rewrite /eqr; case: Req_EM_T=> H; apply: (iffP idP).\nQed.\n\nCanonical R_eqMixin := EqMixin eqrP.\nCanonical R_eqType := Eval hnf in EqType R R_eqMixin.\n\nFact inhR : inhabited R.\nProof. exact: (inhabits 0). Qed.\n\nDefinition pickR (P : pred R) (n : nat) :=\n  let x := epsilon inhR P in if P x then Some x else None.\n\nFact pickR_some P n x : pickR P n = Some x -> P x.\nProof. by rewrite /pickR; case: (boolP (P _)) => // Px [<-]. Qed.\n\nFact pickR_ex (P : pred R) :\n  (exists x : R, P x) -> exists n, pickR P n.\nProof. by rewrite /pickR; move=> /(epsilon_spec inhR)->; exists 0%N. Qed.\n\nFact pickR_ext (P Q : pred R) : P =1 Q -> pickR P =1 pickR Q.\nProof.\nmove=> PEQ n; rewrite /pickR; set u := epsilon _ _; set v := epsilon _ _.\nsuff->: u = v by rewrite PEQ.\nby congr epsilon; apply: functional_extensionality=> x; rewrite PEQ.\nQed.\n\nDefinition R_choiceMixin : choiceMixin R :=\n  Choice.Mixin pickR_some pickR_ex pickR_ext.\n\nCanonical R_choiceType := Eval hnf in ChoiceType R R_choiceMixin.\n\nFact RplusA : associative (Rplus).\nProof. by move=> *; rewrite Rplus_assoc. Qed.\n\nDefinition R_zmodMixin := ZmodMixin RplusA Rplus_comm Rplus_0_l Rplus_opp_l.\n\nCanonical R_zmodType := Eval hnf in ZmodType R R_zmodMixin.\n\nFact RmultA : associative (Rmult).\nProof. by move=> *; rewrite Rmult_assoc. Qed.\n\nFact R1_neq_0 : R1 != R0.\nProof. by apply/eqP/R1_neq_R0. Qed.\n\nDefinition R_ringMixin := RingMixin RmultA Rmult_1_l Rmult_1_r\n  Rmult_plus_distr_r Rmult_plus_distr_l R1_neq_0.\n\nCanonical R_ringType := Eval hnf in RingType R R_ringMixin.\nCanonical R_comRingType := Eval hnf in ComRingType R Rmult_comm.\n\nImport Monoid.\n\nCanonical Radd_monoid := Law RplusA Rplus_0_l Rplus_0_r.\nCanonical Radd_comoid := ComLaw Rplus_comm.\n\nCanonical Rmul_monoid := Law RmultA Rmult_1_l Rmult_1_r.\nCanonical Rmul_comoid := ComLaw Rmult_comm.\n\nCanonical Rmul_mul_law := MulLaw Rmult_0_l Rmult_0_r.\nCanonical Radd_add_law := AddLaw Rmult_plus_distr_r Rmult_plus_distr_l.\n\nDefinition Rinvx r := if (r != 0) then / r else r.\n\nDefinition unit_R r := r != 0.\n\nLemma RmultRinvx : {in unit_R, left_inverse 1 Rinvx Rmult}.\nProof.\nmove=> r; rewrite -topredE /unit_R /Rinvx => /= rNZ /=.\nby rewrite rNZ Rinv_l //; apply/eqP.\nQed.\n\nLemma RinvxRmult : {in unit_R, right_inverse 1 Rinvx Rmult}.\nProof.\nmove=> r; rewrite -topredE /unit_R /Rinvx => /= rNZ /=.\nby rewrite rNZ Rinv_r //; apply/eqP.\nQed.\n\nLemma intro_unit_R x y : y * x = 1 /\\ x * y = 1 -> unit_R x.\nProof.\nmove=> [yx_eq1 _]; apply: contra_eqN yx_eq1 => /eqP->.\nby rewrite Rmult_0_r eq_sym R1_neq_0.\nQed.\n\nLemma Rinvx_out : {in predC unit_R, Rinvx =1 id}.\nProof. by move=> x; rewrite inE/= /Rinvx -if_neg => ->. Qed.\n\nDefinition R_unitRingMixin :=\n  UnitRingMixin RmultRinvx RinvxRmult intro_unit_R Rinvx_out.\n\nCanonical R_unitRing :=\n  Eval hnf in UnitRingType R R_unitRingMixin.\n\nCanonical R_comUnitRingType :=\n  Eval hnf in [comUnitRingType of R].\n\nLemma R_idomainMixin x y : x * y = 0 -> (x == 0) || (y == 0).\nProof. by move=> /Rmult_integral []->; rewrite eqxx ?orbT. Qed.\n\nCanonical R_idomainType := Eval hnf in IdomainType R R_idomainMixin.\n\nLemma R_fieldMixin : GRing.Field.mixin_of [unitRingType of R].\nProof. by done. Qed.\n\nDefinition R_fieldIdomainMixin := FieldIdomainMixin R_fieldMixin.\n\nCanonical R_fieldType := FieldType R R_fieldMixin.\n\n(** Reflect the order on the reals to bool *)\n\nDefinition Rleb r1 r2 := if Rle_dec r1 r2 is left _ then true else false.\nDefinition Rltb r1 r2 := Rleb r1 r2 && (r1 != r2).\nDefinition Rgeb r1 r2 := Rleb r2 r1.\nDefinition Rgtb r1 r2 := Rltb r2 r1.\n\nLemma RlebP r1 r2 : reflect (r1 <= r2) (Rleb r1 r2).\nProof. by rewrite /Rleb; apply: (iffP idP); case: Rle_dec. Qed.\n\nLemma RltbP r1 r2 : reflect (r1 < r2) (Rltb r1 r2).\nProof.\nrewrite /Rltb /Rleb; apply: (iffP idP); case: Rle_dec=> //=.\n- by case=> // r1Er2 /eqP[].\n- by move=> _ r1Lr2; apply/eqP/Rlt_not_eq.\nby move=> Nr1Lr2 r1Lr2; case: Nr1Lr2; left.\nQed.\n\n(*\nLtac toR := rewrite /GRing.add /GRing.opp /GRing.zero /GRing.mul /GRing.inv\n  /GRing.one //=.\n*)\n\nSection ssreal_struct.\n\nImport GRing.Theory.\nImport Num.Theory.\nImport Num.Def.\n\nLocal Open Scope R_scope.\n\nLemma Rleb_norm_add x y : Rleb (Rabs (x + y)) (Rabs x + Rabs y).\nProof. by apply/RlebP/Rabs_triang. Qed.\n\nLemma addr_Rgtb0 x y : Rltb 0 x -> Rltb 0 y -> Rltb 0 (x + y).\nProof. by move/RltbP=> Hx /RltbP Hy; apply/RltbP/Rplus_lt_0_compat. Qed.\n\nLemma Rnorm0_eq0 x : Rabs x = 0 -> x = 0.\nProof. by move=> H; case: (x == 0) /eqP=> // /Rabs_no_R0. Qed.\n\nLemma Rleb_leVge x y : Rleb 0 x -> Rleb 0 y -> (Rleb x y) || (Rleb y x).\nProof.\nmove/RlebP=> Hx /RlebP Hy; case: (Rlt_le_dec x y).\nby move/Rlt_le/RlebP=> ->.\nby move/RlebP=> ->; rewrite orbT.\nQed.\n\nLemma RnormM : {morph Rabs : x y / x * y}.\nexact: Rabs_mult. Qed.\n\nLemma Rleb_def x y : (Rleb x y) = (Rabs (y - x) == y - x).\napply/(sameP (RlebP x y))/(iffP idP)=> [/eqP H| /Rle_minus H].\n  apply: Rminus_le; rewrite -Ropp_minus_distr.\n  apply/Rge_le/Ropp_0_le_ge_contravar.\n  by rewrite -H; apply: Rabs_pos.\napply/eqP/Rabs_pos_eq.\nrewrite -Ropp_minus_distr.\nby apply/Ropp_0_ge_le_contravar/Rle_ge.\nQed.\n\nLemma Rltb_def x y : (Rltb x y) = (y != x) && (Rleb x y).\napply/(sameP (RltbP x y))/(iffP idP).\n  case/andP=> /eqP H /RlebP/Rle_not_gt H2.\n  by case: (Rtotal_order x y)=> // [][] // /esym.\nmove=> H; apply/andP; split; [apply/eqP|apply/RlebP].\n  exact: Rgt_not_eq.\nexact: Rlt_le.\nQed.\n\nDefinition R_numMixin := NumMixin Rleb_norm_add addr_Rgtb0 Rnorm0_eq0\n                                  Rleb_leVge RnormM Rleb_def Rltb_def.\nCanonical R_porderType := POrderType ring_display R R_numMixin.\nCanonical R_numDomainType := NumDomainType R R_numMixin.\nCanonical R_normedZmodType := NormedZmodType R R R_numMixin.\n\nLemma RleP : forall x y, reflect (Rle x y) (x <= y)%R.\nProof. exact: RlebP. Qed.\nLemma RltP : forall x y, reflect (Rlt x y) (x < y)%R.\nProof. exact: RltbP. Qed.\n(* :TODO: *)\n(* Lemma RgeP : forall x y, reflect (Rge x y) (x >= y)%R. *)\n(* Proof. exact: RlebP. Qed. *)\n(* Lemma RgtP : forall x y, reflect (Rgt x y) (x > y)%R. *)\n(* Proof. exact: RltbP. Qed. *)\n\nCanonical R_numFieldType := [numFieldType of R].\n\nLemma Rreal_axiom (x : R) : (0 <= x)%R || (x <= 0)%R.\nProof.\ncase: (Rle_dec 0 x)=> [/RleP ->|] //.\nby move/Rnot_le_lt/Rlt_le/RleP=> ->; rewrite orbT.\nQed.\n\nLemma R_total : totalPOrderMixin R_porderType.\nProof.\nmove=> x y; case: (Rle_lt_dec x y) => [/RleP -> //|/Rlt_le/RleP ->];\n  by rewrite orbT.\nQed.\n\nCanonical R_latticeType := LatticeType R R_total.\nCanonical R_distrLatticeType := DistrLatticeType R R_total.\nCanonical R_orderType := OrderType R R_total.\nCanonical R_realDomainType := [realDomainType of R].\nCanonical R_realFieldType := [realFieldType of R].\n\nLemma Rarchimedean_axiom : Num.archimedean_axiom R_numDomainType.\nProof.\nmove=> x; exists (Z.abs_nat (up x) + 2)%N.\nhave [Hx1 Hx2]:= (archimed x).\nhave Hz (z : Z): z = (z - 1 + 1)%Z by rewrite Zplus_comm Zplus_minus.\nhave Zabs_nat_Zopp z : Z.abs_nat (- z)%Z = Z.abs_nat z by case: z.\napply/RltbP/Rabs_def1.\n  apply: (Rlt_trans _ ((Z.abs_nat (up x))%:R)%R); last first.\n    rewrite -[((Z.abs_nat _)%:R)%R]Rplus_0_r mulrnDr.\n    by apply/Rplus_lt_compat_l/Rlt_0_2.\n  apply: (Rlt_le_trans _ (IZR (up x)))=> //.\n  elim/(well_founded_ind (Zwf_well_founded 0)): (up x) => z IHz.\n  case: (Z_lt_le_dec 0 z) => [zp | zn].\n    rewrite [z]Hz plus_IZR Zabs_nat_Zplus //; last exact: Zlt_0_le_0_pred.\n    rewrite plusE mulrnDr.\n    apply/Rplus_le_compat_r/IHz; split; first exact: Zlt_le_weak.\n    exact: Zlt_pred.\n  apply: (Rle_trans _ (IZR 0)); first exact: IZR_le.\n  by apply/RlebP/(ler0n R_numDomainType (Z.abs_nat z)).\napply: (Rlt_le_trans _ (IZR (up x) - 1)).\n  apply: Ropp_lt_cancel; rewrite Ropp_involutive.\n  rewrite Ropp_minus_distr /Rminus -opp_IZR -{2}(Z.opp_involutive (up x)).\n  elim/(well_founded_ind (Zwf_well_founded 0)): (- up x)%Z => z IHz .\n  case: (Z_lt_le_dec 0 z) => [zp | zn].\n  rewrite [z]Hz Zabs_nat_Zopp plus_IZR.\n  rewrite Zabs_nat_Zplus //; last exact: Zlt_0_le_0_pred.\n    rewrite plusE -Rplus_assoc -addnA [(_ + 2)%N]addnC addnA mulrnDr.\n    apply: Rplus_lt_compat_r; rewrite -Zabs_nat_Zopp.\n    apply: IHz; split; first exact: Zlt_le_weak.\n    exact: Zlt_pred.\n  apply: (Rle_lt_trans _ 1).\n    rewrite -{2}[1]Rplus_0_r; apply: Rplus_le_compat_l.\n    by rewrite -/(IZR 0); apply: IZR_le.\n  rewrite mulrnDr; apply: (Rlt_le_trans _ 2).\n    by rewrite -{1}[1]Rplus_0_r; apply/Rplus_lt_compat_l/Rlt_0_1.\n  rewrite -[2]Rplus_0_l; apply: Rplus_le_compat_r.\n  by apply/RlebP/(ler0n R_numDomainType (Z.abs_nat _)).\napply: Rminus_le.\nrewrite /Rminus Rplus_assoc [- _ + _]Rplus_comm -Rplus_assoc -!/(Rminus _ _).\nexact: Rle_minus.\nQed.\n\n(* Canonical R_numArchiDomainType := ArchiDomainType R Rarchimedean_axiom. *)\n(* (* Canonical R_numArchiFieldType := [numArchiFieldType of R]. *) *)\n(* Canonical R_realArchiDomainType := [realArchiDomainType of R]. *)\nCanonical R_realArchiFieldType := ArchiFieldType R Rarchimedean_axiom.\n\n(** Here are the lemmas that we will use to prove that R has\nthe rcfType structure. *)\n\nLemma continuity_eq f g : f =1 g -> continuity f -> continuity g.\nProof.\nmove=> Hfg Hf x eps Heps.\nhave [y [Hy1 Hy2]]:= Hf x eps Heps.\nby exists y; split=> // z; rewrite -!Hfg; exact: Hy2.\nQed.\n\nLemma continuity_sum (I : finType) F (P : pred I):\n(forall i, P i -> continuity (F i)) ->\ncontinuity (fun x => (\\sum_(i | P i) ((F i) x)))%R.\nProof.\nmove=> H; elim: (index_enum I)=> [|a l IHl].\n  set f:= fun _ => _.\n  have Hf: (fun x=> 0) =1 f by move=> x; rewrite /f big_nil.\n  by apply: (continuity_eq Hf); exact: continuity_const.\nset f := fun _ => _.\ncase Hpa: (P a).\n  have Hf: (fun x => F a x + \\sum_(i <- l | P i) F i x)%R =1 f.\n    by move=> x; rewrite /f big_cons Hpa.\n  apply: (continuity_eq Hf); apply: continuity_plus=> //.\n  exact: H.\nhave Hf: (fun x => \\sum_(i <- l | P i) F i x)%R =1 f.\n  by move=> x; rewrite /f big_cons Hpa.\nexact: (continuity_eq Hf).\nQed.\n\nLemma continuity_exp f n: continuity f -> continuity (fun x => (f x)^+ n)%R.\nProof.\nmove=> Hf; elim: n=> [|n IHn]; first exact: continuity_const.\nset g:= fun _ => _.\nhave Hg: (fun x=> f x * f x ^+ n)%R =1 g.\n  by move=> x; rewrite /g exprS.\nby apply: (continuity_eq Hg); exact: continuity_mult.\nQed.\n\nLemma Rreal_closed_axiom : Num.real_closed_axiom R_numDomainType.\nProof.\nmove=> p a b; rewrite !le_eqVlt.\ncase Hpa: ((p.[a])%R == 0%R).\n  by move=> ? _ ; exists a=> //; rewrite lexx le_eqVlt.\ncase Hpb: ((p.[b])%R == 0%R).\n  by move=> ? _; exists b=> //; rewrite lexx le_eqVlt andbT.\ncase Hab: (a == b).\n  by move=> _; rewrite (eqP Hab) eq_sym Hpb (ltNge 0) /=; case/andP=> /ltW ->.\nrewrite eq_sym Hpb /=; clear=> /RltbP Hab /andP [] /RltbP Hpa /RltbP Hpb.\nsuff Hcp: continuity (fun x => (p.[x])%R).\n  have [z [[Hza Hzb] /eqP Hz2]]:= IVT _ a b Hcp Hab Hpa Hpb.\n  by exists z=> //; apply/andP; split; apply/RlebP.\nrewrite -[p]coefK poly_def.\nset f := fun _ => _.\nhave Hf: (fun (x : R) => \\sum_(i < size p) (p`_i * x^+i))%R =1 f.\n  move=> x; rewrite /f horner_sum.\n  by apply: eq_bigr=> i _; rewrite hornerZ hornerXn.\napply: (continuity_eq Hf); apply: continuity_sum=> i _.\napply:continuity_scal; apply: continuity_exp=> x esp Hesp.\nby exists esp; split=> // y [].\nQed.\n\nCanonical R_rcfType := RcfType R Rreal_closed_axiom.\n(* Canonical R_realClosedArchiFieldType := [realClosedArchiFieldType of R]. *)\n\nEnd ssreal_struct.\n\nLocal Open Scope ring_scope.\nFrom mathcomp.classical Require Import boolp classical_sets.\nRequire Import reals.\n\nSection ssreal_struct_contd.\nImplicit Type E : set R.\n\nLemma is_upper_boundE E x : is_upper_bound E x = (ubound E) x.\nProof.\nrewrite propeqE; split; [move=> h|move=> /ubP h y Ey; exact/RleP/h].\nby apply/ubP => y Ey; apply/RleP/h.\nQed.\n\nLemma boundE E : bound E = has_ubound E.\nProof. by apply/eq_exists=> x; rewrite is_upper_boundE. Qed.\n\nLemma Rcondcomplete E : has_sup E -> {m | isLub E m}.\nProof.\nmove=> [E0 uE]; have := completeness E; rewrite boundE => /(_ uE E0)[x [E1 E2]].\nexists x; split; first by rewrite -is_upper_boundE; apply: E1.\nby move=> y; rewrite -is_upper_boundE => /E2/RleP.\nQed.\n\nLemma Rsupremums_neq0 E : has_sup E -> (supremums E !=set0)%classic.\nProof. by move=> /Rcondcomplete[x [? ?]]; exists x. Qed.\n\nLemma Rsup_isLub x0 E : has_sup E -> isLub E (supremum x0 E).\nProof.\nhave [-> [/set0P]|E0 hsE] := eqVneq E set0; first by rewrite eqxx.\nhave [s [Es sE]] := Rcondcomplete hsE.\nsplit => x Ex; first by apply/ge_supremum_Nmem=> //; exact: Rsupremums_neq0.\nrewrite /supremum (negbTE E0); case: xgetP => /=.\n  by move=> _ -> [_ EsE]; apply/EsE.\nby have [y Ey /(_ y)] := Rsupremums_neq0 hsE.\nQed.\n\n(* :TODO: rewrite like this using (a fork of?) Coquelicot *)\n(* Lemma real_sup_adherent (E : pred R) : real_sup E \\in closure E. *)\nLemma real_sup_adherent x0 E (eps : R) : (0 < eps) ->\n  has_sup E -> exists2 e, E e & (supremum x0 E - eps) < e.\nProof.\nmove=> eps_gt0 supE; set m := _ - eps; apply: contrapT=> mNsmall.\nhave : (ubound E) m.\n  apply/ubP => y Ey.\n  by have /negP := mNsmall (ex_intro2 _ _ y Ey _); rewrite -leNgt.\nhave [_ /(_ m)] := Rsup_isLub x0 supE.\nmove => m_big /m_big.\nby rewrite -subr_ge0 addrC addKr oppr_ge0 leNgt eps_gt0.\nQed.\n\nLemma Rsup_ub x0 E : has_sup E -> (ubound E) (supremum x0 E).\nProof.\nby move=> supE x Ex; apply/ge_supremum_Nmem => //; exact: Rsupremums_neq0.\nQed.\n\nDefinition real_realMixin : Real.mixin_of _ :=\n  RealMixin (@Rsup_ub (0 : R)) (real_sup_adherent 0).\nCanonical real_realType := RealType R real_realMixin.\n\nImplicit Types (x y : R) (m n : nat).\n\n(* equational lemmas about exp, sin and cos for mathcomp compat *)\n\n(* Require Import realsum. *)\n\n(* :TODO: One day, do this *)\n(* Notation \"\\Sum_ i E\" := (psum (fun i => E)) *)\n(*  (at level 100, i ident, format \"\\Sum_ i  E\") : ring_scope. *)\n\n(* Definition exp x := \\Sum_n (n`!)%:R^-1 * x ^ n. *)\n\nLemma expR0 : exp (0 : R) = 1.\nProof. by rewrite exp_0. Qed.\n\nLemma expRD x y : exp x * exp y = exp (x + y).\nProof. by rewrite exp_plus. Qed.\n\nLemma expRX x n : exp x ^+ n = exp (x *+ n).\nProof.\nelim: n => [|n Ihn]; first by rewrite expr0 mulr0n exp_0.\nby rewrite exprS Ihn mulrS expRD.\nQed.\n\nLemma sinD x y : sin (x + y) = sin x * cos y + cos x * sin y.\nProof. by rewrite sin_plus. Qed.\n\nLemma cosD x y : cos (x + y) = (cos x * cos y - sin x * sin y).\nProof. by rewrite cos_plus. Qed.\n\nLemma RplusE x y : Rplus x y = x + y. Proof. by []. Qed.\n\nLemma RminusE x y : Rminus x y = x - y. Proof. by []. Qed.\n\nLemma RmultE x y : Rmult x y = x * y. Proof. by []. Qed.\n\nLemma RoppE x : Ropp x = - x. Proof. by []. Qed.\n\nLemma RinvE x : x != 0 -> Rinv x = x^-1.\nProof. by move=> x_neq0; rewrite -[RHS]/(if _ then _ else _) x_neq0. Qed.\n\nLemma RdivE x y : y != 0 -> Rdiv x y = x / y.\nProof. by move=> y_neq0; rewrite /Rdiv RinvE. Qed.\n\nLemma INRE n : INR n = n%:R.\nProof. elim: n => // n IH; by rewrite S_INR IH RplusE -addn1 natrD. Qed.\n\nLemma RsqrtE x : 0 <= x -> sqrt x = Num.sqrt x.\nProof.\nmove => x0; apply/eqP; have [t1 t2] := conj (sqrtr_ge0 x) (sqrt_pos x).\nrewrite eq_sym -(eqr_expn2 (_: 0 < 2)%N t1) //; last by apply /RleP.\nrewrite sqr_sqrtr // !exprS expr0 mulr1 -RmultE ?sqrt_sqrt //; by apply/RleP.\nQed.\n\nLemma RpowE x n : pow x n = x ^+ n.\nProof. by elim: n => [ | n In] //=; rewrite exprS In RmultE. Qed.\n\nLemma RmaxE x y : Rmax x y = Num.max x y.\nProof.\ncase: (lerP x y) => H; first by rewrite Rmax_right //; apply: RlebP.\nby rewrite ?ltW // Rmax_left //;  apply/RlebP; move/ltW : H.\nQed.\n\n(* useful? *)\nLemma RminE x y : Rmin x y = Num.min x y.\nProof.\ncase: (lerP x y) => H; first by rewrite Rmin_left //; apply: RlebP.\nby rewrite ?ltW // Rmin_right //;  apply/RlebP; move/ltW : H.\nQed.\n\nSection bigmaxr.\nContext {R : realDomainType}.\n\n(* bigop pour le max pour des listes non vides ? *)\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nDefinition bigmaxr (r : R) s := \\big[Num.max/head r s]_(i <- s) i.\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bigmaxr_nil (x0 : R) : bigmaxr x0 [::] = x0.\nProof. by rewrite /bigmaxr /= big_nil. Qed.\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bigmaxr_un (x0 x : R) : bigmaxr x0 [:: x] = x.\nProof. by rewrite /bigmaxr /= big_cons big_nil maxxx. Qed.\n\n(* previous definition *)\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bigmaxrE (r : R) s : bigmaxr r s = foldr Num.max (head r s) (behead s).\nProof.\nrewrite (_ : bigmaxr _ _ = if s isn't h :: t then r else \\big[Num.max/h]_(i <- s) i).\n  case: s => // ? t; rewrite big_cons /bigmaxr.\n  by elim: t => //= [|? ? <-]; [rewrite big_nil maxxx | rewrite big_cons maxCA].\nby case: s => //=; rewrite /bigmaxr big_nil.\nQed.\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bigrmax_dflt (x y : R) s : Num.max x (\\big[Num.max/x]_(j <- y :: s) j) =\n  Num.max x (\\big[Num.max/y]_(i <- y :: s) i).\nProof.\nelim: s => /= [|h t IH] in x y *.\nby rewrite !big_cons !big_nil maxxx maxCA maxxx maxC.\nby rewrite big_cons maxCA IH maxCA [in RHS]big_cons IH.\nQed.\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bigmaxr_cons (x0 x y : R) lr :\n  bigmaxr x0 (x :: y :: lr) = Num.max x (bigmaxr x0 (y :: lr)).\nProof. by rewrite [y :: lr]lock /bigmaxr /= -lock big_cons bigrmax_dflt. Qed.\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bigmaxr_ler (x0 : R) s i :\n  (i < size s)%N -> (nth x0 s i) <= (bigmaxr x0 s).\nProof.\nrewrite /bigmaxr; elim: s i => // h t IH [_|i] /=.\n  by rewrite big_cons /= le_maxr lexx.\nrewrite ltnS => ti; case: t => [|h' t] // in IH ti *.\nby rewrite big_cons bigrmax_dflt le_maxr orbC IH.\nQed.\n\n(* Compatibilité avec l'addition *)\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bigmaxr_addr (x0 : R) lr (x : R) :\n  bigmaxr (x0 + x) (map (fun y : R => y + x) lr) = (bigmaxr x0 lr) + x.\nProof.\nrewrite /bigmaxr; case: lr => [|h t]; first by rewrite !big_nil.\nelim: t h => /= [|h' t IH] h; first by rewrite ?(big_cons,big_nil) -addr_maxl.\nby rewrite [in RHS]big_cons bigrmax_dflt addr_maxl -IH big_cons bigrmax_dflt.\nQed.\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bigmaxr_mem (x0 : R) lr : (0 < size lr)%N -> bigmaxr x0 lr \\in lr.\nProof.\nrewrite /bigmaxr; case: lr => // h t _.\nelim: t => //= [|h' t IH] in h *; first by rewrite big_cons big_nil inE maxxx.\nrewrite big_cons bigrmax_dflt inE eq_le; case: lerP => /=.\n- by rewrite le_maxr lexx.\n- by rewrite lt_maxr ltxx => ?; rewrite max_r ?IH // ltW.\nQed.\n\n(* TODO: bigmaxr_morph? *)\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bigmaxr_mulr (A : finType) (s : seq A) (k : R) (x : A -> R) :\n  0 <= k -> bigmaxr 0 (map (fun i => k * x i) s) = k * bigmaxr 0 (map x s).\nProof.\nmove=> k0; elim: s => /= [|h [/=|h' t ih]].\nby rewrite bigmaxr_nil mulr0.\nby rewrite !bigmaxr_un.\nby rewrite bigmaxr_cons {}ih bigmaxr_cons maxr_pmulr.\nQed.\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bigmaxr_index (x0 : R) lr :\n  (0 < size lr)%N -> (index (bigmaxr x0 lr) lr < size lr)%N.\nProof.\nrewrite /bigmaxr; case: lr => //= h t _; case: ifPn => // /negbTE H.\nmove: (@bigmaxr_mem x0 (h :: t) isT).\nby rewrite ltnS index_mem inE /= eq_sym H.\nQed.\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bigmaxr_lerP (x0 : R) lr (x : R) :\n  (0 < size lr)%N ->\n  reflect (forall i, (i < size lr)%N -> (nth x0 lr i) <= x) ((bigmaxr x0 lr) <= x).\nProof.\nmove=> lr_size; apply: (iffP idP) => [le_x i i_size | H].\n  by apply: (le_trans _ le_x); apply: bigmaxr_ler.\nby move/(nthP x0): (bigmaxr_mem x0 lr_size) => [i i_size <-]; apply: H.\nQed.\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bigmaxr_ltrP (x0 : R) lr (x : R) :\n  (0 < size lr)%N ->\n  reflect (forall i, (i < size lr)%N -> (nth x0 lr i) < x) ((bigmaxr x0 lr) < x).\nProof.\nmove=> lr_size; apply: (iffP idP) => [lt_x i i_size | H].\n  by apply: le_lt_trans lt_x; apply: bigmaxr_ler.\nby move/(nthP x0): (bigmaxr_mem x0 lr_size) => [i i_size <-]; apply: H.\nQed.\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bigmaxrP (x0 : R) lr (x : R) :\n  (x \\in lr /\\ forall i, (i < size lr) %N -> (nth x0 lr i) <= x) -> (bigmaxr x0 lr = x).\nProof.\nmove=> [] /(nthP x0) [] j j_size j_nth x_ler; apply: le_anti; apply/andP; split.\n  by apply/bigmaxr_lerP => //; apply: (leq_trans _ j_size).\nby rewrite -j_nth (bigmaxr_ler _ j_size).\nQed.\n\n(* surement à supprimer à la fin\nLemma bigmaxc_lttc x0 lc :\n  uniq lc -> forall i, (i < size lc)%N -> (i != index (bigmaxc x0 lc) lc)\n    -> lttc (nth x0 lc i) (bigmaxc x0 lc).\nProof.\nmove=> lc_uniq Hi size_i /negP neq_i.\nrewrite lttc_neqAle (bigmaxc_letc _ size_i) andbT.\napply/negP => /eqP H; apply: neq_i; rewrite -H eq_sym; apply/eqP.\nby apply: index_uniq.\nQed. *)\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bigmaxr_lerif (x0 : R) lr :\n  uniq lr -> forall i, (i < size lr)%N ->\n     (nth x0 lr i) <= (bigmaxr x0 lr) ?= iff (i == index (bigmaxr x0 lr) lr).\nProof.\nmove=> lr_uniq i i_size; rewrite /Num.leif (bigmaxr_ler _ i_size).\nrewrite -(nth_uniq x0 i_size (bigmaxr_index _ (leq_trans _ i_size)) lr_uniq) //.\nrewrite nth_index //.\nby apply: bigmaxr_mem; apply: (leq_trans _ i_size).\nQed.\n\n(* bigop pour le max pour des listes non vides ? *)\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nDefinition bmaxrf n (f : {ffun 'I_n.+1 -> R}) :=\n  bigmaxr (f ord0) (codom f).\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bmaxrf_ler n (f : {ffun 'I_n.+1 -> R}) i :\n  (f i) <= (bmaxrf f).\nProof.\nmove: (@bigmaxr_ler (f ord0) (codom f) (nat_of_ord i)).\nrewrite /bmaxrf size_codom card_ord => H; move: (ltn_ord i); move/H.\nsuff -> : nth (f ord0) (codom f) i = f i; first by [].\nby rewrite /codom (nth_map ord0) ?size_enum_ord // nth_ord_enum.\nQed.\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bmaxrf_index n (f : {ffun 'I_n.+1 -> R}) :\n  (index (bmaxrf f) (codom f) < n.+1)%N.\nProof.\nrewrite /bmaxrf.\nrewrite [in X in (_ < X)%N](_ : n.+1 = size (codom f)); last first.\n  by rewrite size_codom card_ord.\nby apply: bigmaxr_index; rewrite size_codom card_ord.\nQed.\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nDefinition index_bmaxrf n f := Ordinal (@bmaxrf_index n f).\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma ordnat i n (ord_i : (i < n)%N) : i = Ordinal ord_i :> nat.\nProof. by []. Qed.\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma eq_index_bmaxrf n (f : {ffun 'I_n.+1 -> R}) :\n  f (index_bmaxrf f) = bmaxrf f.\nProof.\nmove: (bmaxrf_index f).\nrewrite -[X in _ (_ < X)%N]card_ord -(size_codom f) index_mem.\nmove/(nth_index (f ord0)) => <-; rewrite (nth_map ord0).\n  by rewrite (ordnat (bmaxrf_index _)) /index_bmaxrf nth_ord_enum.\nby rewrite size_enum_ord; apply: bmaxrf_index.\nQed.\n\n#[deprecated(note=\"To be removed. Use topology.v's bigmax/min lemmas instead.\")]\nLemma bmaxrf_lerif n (f : {ffun 'I_n.+1 -> R}) :\n  injective f -> forall i,\n     (f i) <= (bmaxrf f) ?= iff (i == index_bmaxrf f).\nProof.\nby move=> inj_f i; rewrite /Num.leif bmaxrf_ler -(inj_eq inj_f) eq_index_bmaxrf.\nQed.\n\nEnd bigmaxr.\n\nEnd ssreal_struct_contd.\n\nRequire Import signed topology normedtype.\n\nSection analysis_struct.\n\nCanonical R_pointedType := [pointedType of R for pointed_of_zmodule R_ringType].\nCanonical R_filteredType :=\n  [filteredType R of R for filtered_of_normedZmod R_normedZmodType].\nCanonical R_topologicalType : topologicalType := TopologicalType R\n  (topologyOfEntourageMixin\n    (uniformityOfBallMixin\n      (@nbhs_ball_normE _ R_normedZmodType)\n      (pseudoMetric_of_normedDomain R_normedZmodType))).\nCanonical R_uniformType : uniformType :=\n  UniformType R\n  (uniformityOfBallMixin (@nbhs_ball_normE _ R_normedZmodType)\n    (pseudoMetric_of_normedDomain R_normedZmodType)).\nCanonical R_pseudoMetricType : pseudoMetricType R_numDomainType :=\n  PseudoMetricType R (pseudoMetric_of_normedDomain R_normedZmodType).\n\n(* TODO: express using ball?*)\nLemma continuity_pt_nbhs (f : R -> R) x :\n  continuity_pt f x <->\n  forall eps : {posnum R}, nbhs x (fun u => `|f u - f x| < eps%:num).\nProof.\nsplit=> [fcont e|fcont _/RltP/posnumP[e]]; last first.\n  have [_/posnumP[d] xd_fxe] := fcont e.\n  exists d%:num; split; first by apply/RltP; have := [gt0 of d%:num].\n  by move=> y [_ /RltP yxd]; apply/RltP/xd_fxe; rewrite /= distrC.\nhave /RltP egt0 := [gt0 of e%:num].\nhave [_ [/RltP/posnumP[d] dx_fxe]] := fcont e%:num egt0.\nexists d%:num => //= y xyd; case: (eqVneq x y) => [->|xney].\n  by rewrite subrr normr0.\napply/RltP/dx_fxe; split; first by split=> //; apply/eqP.\nby have /RltP := xyd; rewrite distrC.\nQed.\n\nLemma continuity_pt_cvg (f : R -> R) (x : R) :\n  continuity_pt f x <-> {for x, continuous f}.\nProof.\neapply iff_trans; first exact: continuity_pt_nbhs.\napply iff_sym.\nhave FF : Filter (f @ x).\n  by typeclasses eauto.\n  (*by apply fmap_filter; apply: @filter_filter' (locally_filter _).*)\ncase: (@fcvg_ballP _ _ (f @ x) FF (f x)) => {FF}H1 H2.\n(* TODO: in need for lemmas and/or refactoring of already existing lemmas (ball vs. Rabs) *)\nsplit => [{H2} - /H1 {}H1 eps|{H1} H].\n- have {H1} [//|_/posnumP[x0] Hx0] := H1 eps%:num.\n  exists x0%:num => //= Hx0' /Hx0 /=.\n  by rewrite /= distrC; apply.\n- apply H2 => _ /posnumP[eps]; move: (H eps) => {H} [_ /posnumP[x0] Hx0].\n  exists x0%:num => //= y /Hx0 /= {}Hx0.\n  by rewrite /ball /= distrC.\nQed.\n\nLemma continuity_ptE (f : R -> R) (x : R) :\n  continuity_pt f x <-> {for x, continuous f}.\nProof. exact: continuity_pt_cvg. Qed.\n\nLocal Open Scope classical_set_scope.\n\nLemma continuity_pt_cvg' f x :\n  continuity_pt f x <-> f @ x^' --> f x.\nProof. by rewrite continuity_ptE continuous_withinNx. Qed.\n\nLemma continuity_pt_dnbhs f x :\n  continuity_pt f x <->\n  forall eps, 0 < eps -> x^' (fun u => `|f x - f u| < eps).\nProof.\nrewrite continuity_pt_cvg' (@cvgrPdist_lt _ [normedModType _ of R^o]).\nexact.\nQed.\n\nLemma nbhs_pt_comp (P : R -> Prop) (f : R -> R) (x : R) :\n  nbhs (f x) P -> continuity_pt f x -> \\near x, P (f x).\nProof. by move=> Lf /continuity_pt_cvg; apply. Qed.\n\nEnd analysis_struct.\n", "meta": {"author": "math-comp", "repo": "analysis", "sha": "ee12aba894e8949a32daa9d2ee72b3a440c0609f", "save_path": "github-repos/coq/math-comp-analysis", "path": "github-repos/coq/math-comp-analysis/analysis-ee12aba894e8949a32daa9d2ee72b3a440c0609f/theories/Rstruct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6685771754822184}}
{"text": "Require Import GraphBasics.Graphs.\nRequire Import GraphBasics.Trees.\nRequire Import Coq.Logic.Classical_Prop.\nRequire Export Coq.Bool.BoolEq.\n\n\n(* part of the network model that represents the underlying network graph *)\n(* we model the topology of a network as a connected undirected graph *)\nSection Topology.\n\nNotation \"a =/= b\" := (beq_nat (Some a) (Some b)) (at level 70).\nNotation \"a == b\" := (beq_nat a b) (at level 70).\n\n\n(* a component is modelled as a vertex (of a graph) *)\nDefinition Component := Vertex.\n\n(* each component has a unique identifier *)\nDefinition component_index (c : Component):nat := match c with\n                          | index x => x\n                          end.\n\n(* from vertices to components *)\n(* our universe is a set of components *)\nDefinition C_set := U_set Component.\nDefinition C_list := U_list Component.\nDefinition C_nil:= V_nil.\n\n(* it is decidable whether two components x,y are the same or different *)\nLemma C_eq_dec : forall x y : Component, {x = y} + {x <> y}.\nProof.\n        simple destruct x; simple destruct y; intros.\n        case (eq_nat_dec n n0); intros.\n        left; rewrite e; trivial.\n        right; injection; trivial.\nQed.\n\n(* CA_list is a list of the set of arcs a *)\n(* we match over the constructors of the connected graph c *)\nFixpoint CA_list (v : V_set) (a : A_set) (c : Connected v a) {struct c} :\n A_list :=\n  match c with\n  | C_isolated x => A_nil\n  | C_leaf v' a' c' x y _ _ => A_ends x y :: A_ends y x :: CA_list v' a' c'\n  | C_edge v' a' c' x y _ _ _ _ _ =>\n      A_ends x y :: A_ends y x :: CA_list v' a' c'\n  | C_eq v' _ a' _ _ _ c' => CA_list v' a' c'\n  end.\n\n(* CV_list is a list of the set vertices v *)\nFixpoint CV_list (v : V_set) (a : A_set) (c: Connected v a) {struct c} :\n V_list :=\n  match c with\n  | C_isolated x => x::V_nil\n  | C_leaf v' a' c' x y _ _ => y :: CV_list v' a' c'\n  | C_edge v' a' c' x y _ _ _ _ _  => CV_list v' a' c'\n  | C_eq v' _ a' _ _ _ c' => CV_list v' a' c'\n  end.\n\n(* necessary as an Axiom?\nVariable Component_prop: forall (c:Component)(v : V_set) (a : A_set)(g : Connected v a),\nIn c (CV_list v a g). *)\n\n(* connected graph is symmetric and thereby represents an undirected graph *)\nLemma C_non_directed: forall (v : V_set) (a : A_set) (c : Connected v a) (x y : Vertex),\n a (A_ends x y) -> a (A_ends y x).\nProof.\nintros.\napply Connected_Isa_Graph in c.\napply G_non_directed with (v:=v).\napply c.\napply H.\nQed.\n\n(**)\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\n(* true iff components n and m are equal *)\nDefinition beq_comp (n m : Component) : bool :=\nbeq_nat (component_index n) (component_index m). \n\n\n(* Basic properties for beq: maybe these arent used*)\n(*\n(* alternatively to the definition of beq *)\nVariable beq : Component -> Component -> bool.\nVariable beq_refl : forall x:Component, true = beq x x.\n\nVariable beq_eq : forall x y:Component, true = beq x y -> x = y.\n\nVariable beq_eq_true : forall x y:Component, x = y -> true = beq x y.\n\nVariable beq_eq_not_false : forall x y:Component, x = y -> false <> beq x y.\n\nVariable beq_false_not_eq : forall x y:Component, false = beq x y -> x <> y.\n\nVariable exists_beq_eq : forall x y:Component, {b : bool | b = beq x y}.\n\nVariable not_eq_false_beq : forall x y:Component, x <> y -> false = beq x y.\n\nVariable eq_dec : forall x y:Component, {x = y} + {x <> y}. \n*)\n\n(* true iff component a is in list l *)\nFixpoint In_bool (a: Component) (l:C_list) : bool:=\n  match l with\n  | nil => false\n  | b :: m => beq_comp b a || In_bool a m\n  end.\n\n(* list of neighbors of component c *)\nDefinition neighbors (v : V_set) (a : A_set) (g : Connected v a) (c: Component) : C_list :=\n(A_in_neighborhood c (CA_list v a g)).\n\n(* since the graph is symmetric, the in- and out-neighborhood is the same*)\nLemma neighbors_connected_prop :\nforall k (v : V_set) (a : A_set)(g : Connected v a) (c: Component),\n In k (A_out_neighborhood c (CA_list v a g)) <-> In k (A_in_neighborhood c (CA_list v a g)).\nProof.\n  split.\n{ intros.\n  induction g.\n  - auto.\n  - simpl in *.\n    destruct (V_eq_dec c y).\n    destruct (V_eq_dec c x).\n    simpl in *.\n    repeat destruct H; auto.\n    simpl in *; auto.\n    repeat destruct H; auto.\n    destruct (V_eq_dec c x).\n    simpl in *; auto.\n    repeat destruct H; auto.\n    apply (IHg H).\n  - simpl in *.\n    destruct (V_eq_dec c y).\n    destruct (V_eq_dec c x).\n    simpl.\n    simpl in H.\n    destruct H.\n    right.\n    left.\n    apply H.\n    destruct H.\n    left.\n    apply H.\n    apply IHg in H.\n    right.\n    right.\n    apply H.\n\n    simpl in *.\n    destruct H.\n    left. apply H.\n    right. apply (IHg H).\n\n    destruct (V_eq_dec c x).\n    simpl in *.\n    destruct H.\n    left. apply H.\n    right. apply (IHg H).\n    apply (IHg H).\n  - rewrite <- e.\n    rewrite <- e0.\n    apply (IHg H). }\n\n{ intros.\n  induction g.\n  - auto.\n  - simpl in *.\n    destruct (V_eq_dec c x).\n    destruct (V_eq_dec c y).\n    simpl in *.\n    repeat destruct H; auto.\n    simpl in *.\n    repeat destruct H; auto.\n    destruct (V_eq_dec c y).\n    simpl in *.\n    repeat destruct H; auto.\n    apply (IHg H).\n  - simpl in *.\n    destruct (V_eq_dec c x).\n    destruct (V_eq_dec c y).\n    simpl in *.\n    repeat destruct H; auto.\n    simpl in *.\n    repeat destruct H; auto.\n    destruct (V_eq_dec c y).\n    simpl in *.\n    repeat destruct H; auto.\n    apply (IHg H).\n  - rewrite <- e.\n    rewrite <- e0.\n    apply (IHg H). }\nQed.\n\n(* for a parent k of c holds that k is also a neighbor of c *)\nLemma parent_neighbors_: forall (v: V_set) (a: A_set)(g: Connected v a) (c k:Component),\na (A_ends c k) <-> In k (A_in_neighborhood c (CA_list v a g)).\nProof.\n  split; intros.\n{ induction g.\n  - auto.\n    inversion H.\n  - simpl in *.\n    destruct (V_eq_dec c y).\n    destruct (V_eq_dec c x).\n    simpl in *.\n    inversion H.\n    inversion H0.\n    right. left. reflexivity.\n    left. reflexivity.\n    right. right. apply (IHg H0).\n    simpl in *.\n    inversion H.\n    inversion H0.\n    symmetry in H3. intuition.\n    left. auto.\n    right. apply (IHg H0).\n    destruct (V_eq_dec c x).\n    simpl in *.\n    inversion H.\n    inversion H0.\n    left. reflexivity.\n    symmetry in H3. intuition.\n    right. apply (IHg H0).\n    inversion H.\n    inversion H0; symmetry in H3; intuition.\n    apply (IHg H0).\n  - simpl in *.\n    destruct (V_eq_dec c y).\n    destruct (V_eq_dec c x).\n    simpl in *.\n    inversion H.\n    inversion H0.\n    right. left. reflexivity.\n    left. reflexivity.\n    right. right. apply (IHg H0).\n    simpl in *.\n    inversion H.\n    inversion H0.\n    symmetry in H3. intuition.\n    left. auto.\n    right. apply (IHg H0).\n    destruct (V_eq_dec c x).\n    simpl in *.\n    inversion H.\n    inversion H0.\n    left. reflexivity.\n    symmetry in H3. intuition.\n    right. apply (IHg H0).\n    inversion H.\n    inversion H0; symmetry in H3; intuition.\n    apply (IHg H0).\n  - rewrite <- e.\n    rewrite <- e0.\n    rewrite <- e0 in H.\n    simpl.\n    apply (IHg H). }\n{ induction g.\n  - auto.\n    inversion H.\n  - simpl in *.\n    destruct (V_eq_dec c y).\n    destruct (V_eq_dec c x).\n    rewrite e in *. rewrite e0 in *.\n    apply n in v0. intuition.\n    rewrite e in *. simpl in *.\n    destruct H. apply In_left. rewrite H in *. apply E_left.\n    apply In_right. apply (IHg H).\n    destruct (V_eq_dec c x).\n    simpl in *; destruct H; auto.\n    rewrite e in *; rewrite H in *.\n    apply In_left. apply E_right.\n    apply In_right. apply (IHg H).\n    apply In_right. apply (IHg H).\n  - simpl in *.\n    destruct (V_eq_dec c y).\n    destruct (V_eq_dec c x).\n    rewrite e in *. rewrite e0 in *.\n    intuition.\n    rewrite e in *. simpl in *.\n    destruct H. apply In_left. rewrite H in *. apply E_left.\n    apply In_right. apply (IHg H).\n    destruct (V_eq_dec c x).\n    simpl in *; destruct H; auto.\n    rewrite e in *; rewrite H in *.\n    apply In_left. apply E_right.\n    apply In_right. apply (IHg H).\n    apply In_right. apply (IHg H).\n  - rewrite <- e in *.\n    rewrite <- e0 in *.\n    simpl in *.\n    apply (IHg H). }\nQed.\n\n\n(* true iff list l contains (multiple times) only component c *)\nFixpoint forallb_neighbors (l:C_list) (c:Component) : bool :=\n      match l with\n        | nil => true\n        | a::k => beq_comp a c && forallb_neighbors k c\n      end.\n\n(*  *)\nLemma forallb_forall_ : forall (l:C_list) (c:Component), \n(forallb_neighbors l c = true) <-> (forall x, In x l ->  x = c).\nProof.\n  split; intros.\n{ induction l.\n  - inversion H0.\n  - simpl in H.\n    apply andb_prop in H.\n    destruct H.\n    unfold beq_comp in H.\n    apply Nat.eqb_eq in H.\n    destruct (a).\n    destruct (c).\n    unfold component_index in H.\n    simpl in H0.\n    destruct H0.\n    rewrite <- H. rewrite <- H0. reflexivity.\n    apply (IHl H1 H0). }\n{ induction l.\n  - reflexivity.\n  - intuition.\n    simpl. apply andb_true_intro.\n    split.\n    symmetry. apply beq_eq_true.\n    simpl in H. intuition.\n    destruct x.\n    unfold beq_comp.\n    simpl.\n    symmetry.\n    apply <- Nat.eqb_eq.\n    reflexivity.\n    specialize (H a).\n    apply H.\n    simpl.\n    left.\n    reflexivity.\n    apply IHl.\n    intros.\n    apply H.\n    simpl. right. apply H0. }\nQed.\n\n(* if an arc is in the arc set a, then it is also in the arc list CA_list *)\nLemma arc_list_set: forall (v: V_set)(a: A_set)(g: Connected v a) (x y : Component),\na (A_ends x y) -> In (A_ends x y) (CA_list v a g).\nProof.\n  intros.\n  induction g.\n  - inversion H.\n  - simpl in *.\n    inversion H.\n    inversion H0.\n    auto.\n    auto.\n    right. right. apply (IHg H0).\n  - simpl in *.\n    inversion H.\n    inversion H0 ; auto.\n    right. right. apply (IHg H0).\n  - rewrite <- e in *. rewrite <- e0 in *.\n    apply (IHg H).\nQed.\n\n(* if there is an arc from y to x in the list CA_list, then x is a neighbor of y *)\nLemma arc_list_neighbors:\nforall (v: V_set)(a: A_set)(g: Connected v a) x y,\nIn (A_ends x y) (CA_list v a g) -> In x (neighbors v a g y).\nProof.\nintros.\nunfold neighbors.\nunfold A_in_neighborhood.\ninduction ( (CA_list v a g)).\ncontradiction.\ndestruct a0.\ndestruct (V_eq_dec y v1).\ndestruct H.\nunfold In.\nleft.\ninversion H.\ndestruct H.\ntrivial.\nunfold In.\nright.\nunfold In in IHa0.\napply IHa0.\nunfold In in H.\ntrivial.\ndestruct H.\ninversion H.\nrewrite H2 in n.\ncontradiction.\napply IHa0.\ntrivial.\nQed. \n\n(* if there is an arc from y to x in a, then comp1 is a neighbor of comp2 *)\nLemma neighbourslist_prep:\nforall (v: V_set)(a: A_set)(g: Connected v a)(comp1 comp2: Component),\na (A_ends comp1 comp2) -> In comp1 (neighbors v a g comp2).\nProof.\nunfold neighbors.\nintros.\napply (arc_list_set v a g) in H.\napply arc_list_neighbors in H. \nunfold neighbors in H.\ntrivial.\nQed.\n\n(* if there is a path from comp1 to comp2 with x being the first component on the path,\n * then comp1 is a neighbor of x *)\nLemma neighbourslist2:\nforall (v: V_set)(a: A_set)(g: Connected v a)(x comp1 comp2: Component)  (el : E_list) (clist: list Component),\n Path v a comp1 comp2 (x::clist) el -> In comp1  (neighbors v a g x).\nProof.\nintros.\napply neighbourslist_prep.\ninversion H.\ntrivial.\nQed.\n\n(* removes a component from a list of components *)\nFixpoint remove (x : Component) (l : list Component) : list Component :=\n    match l with\n    | nil => nil\n    | y::tl => if ((component_index x) == (component_index y)) then tl else y::(remove x tl)\n    end.\n\n(* true iff a list of component is empty *)\nDefinition empty (l : list Component) : bool :=\n  match l with\n  | nil => true\n  | a :: m => false\n  end.\n\nEnd Topology.", "meta": {"author": "voellinger", "repo": "verified-certifying-distributed-algorithms", "sha": "35b2a4dc5c0aec6228ded6b10bbe4d086692dadb", "save_path": "github-repos/coq/voellinger-verified-certifying-distributed-algorithms", "path": "github-repos/coq/voellinger-verified-certifying-distributed-algorithms/verified-certifying-distributed-algorithms-35b2a4dc5c0aec6228ded6b10bbe4d086692dadb/framework/networkmodel/NetworkModelTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6685764681951343}}
{"text": "Require Import rt.util.all.\nRequire Import rt.analysis.global.parallel.bertogna_edf_theory.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop div path.\n\nModule ResponseTimeIterationEDF.\n\n  Import ResponseTimeAnalysisEDF.\n\n  (* In this section, we define the algorithm for Bertogna and Cirinei's\n     response-time analysis for EDF scheduling with parallel jobs. *)\n  Section Analysis.\n    \n    Context {sporadic_task: eqType}.\n    Variable task_cost: sporadic_task -> time.\n    Variable task_period: sporadic_task -> time.\n    Variable task_deadline: sporadic_task -> time.\n\n    (* As input for each iteration of the algorithm, we consider pairs\n       of tasks and computed response-time bounds. *)\n    Let task_with_response_time := (sporadic_task * time)%type.\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 -> sporadic_task.\n\n    (* Consider a platform with num_cpus processors. *)  \n    Variable num_cpus: nat.\n\n    (* First, recall the jitter-aware interference bound for EDF, ... *)\n    Let I (rt_bounds: seq task_with_response_time)\n          (tsk: sporadic_task) (delta: time) :=\n      total_interference_bound_edf task_cost task_period task_deadline tsk rt_bounds delta.\n\n    (* ..., which yields the following response-time bound. *)\n    Definition edf_response_time_bound (rt_bounds: seq task_with_response_time)\n                                           (tsk: sporadic_task) (delta: time) :=\n      task_cost tsk + div_floor (I rt_bounds tsk delta) num_cpus.\n\n    (* Also note that a response-time is only valid if it is no larger\n       than the deadline. *)\n    Definition R_le_deadline (pair: task_with_response_time) :=\n      let (tsk, R) := pair in\n        R <= task_deadline tsk.\n\n    (* Next we define the fixed-point iteration for computing\n       Bertogna's response-time bound of a task set. *)\n    \n    (* Given a sequence 'rt_bounds' of task and response-time bounds\n       from the previous iteration, we compute the response-time\n       bound of a single task using the RTA for EDF. *)\n    Definition update_bound (rt_bounds: seq task_with_response_time)\n                        (pair : task_with_response_time) :=\n      let (tsk, R) := pair in\n        (tsk, edf_response_time_bound rt_bounds tsk R).\n\n    (* To compute the response-time bounds of the entire task set,\n       We start the iteration with a sequence of tasks and costs:\n       <(task1, cost1), (task2, cost2), ...>. *)\n    Let initial_state (ts: seq sporadic_task) :=\n      map (fun t => (t, task_cost t)) ts.\n\n    (* Then, we successively update the the response-time bounds based\n       on the slack computed in the previous iteration. *)\n    Definition edf_rta_iteration (rt_bounds: seq task_with_response_time) :=\n      map (update_bound rt_bounds) rt_bounds.\n\n    (* To ensure that the procedure converges, we run the iteration a\n       \"sufficient\" number of times: task_deadline tsk - task_cost tsk + 1.\n       This corresponds to the time complexity of the procedure. *)\n    Let max_steps (ts: seq sporadic_task) :=\n      \\sum_(tsk <- ts) (task_deadline tsk - task_cost tsk) + 1.\n\n    (* This yields the following definition for the RTA. At the end of\n       the iteration, we check if all computed response-time bounds\n       are less than or equal to the deadline, in which case they are\n       valid. *)\n    Definition edf_claimed_bounds (ts: seq sporadic_task) :=\n      let R_values := iter (max_steps ts) edf_rta_iteration (initial_state ts) in\n        if (all R_le_deadline R_values) then\n          Some R_values\n        else None.\n\n    (* The schedulability test simply checks if we got a list of\n       response-time bounds (i.e., if the computation did not fail). *)\n    Definition edf_schedulable (ts: seq sporadic_task) :=\n      edf_claimed_bounds ts != None.\n\n    (* In the following section, we prove several helper lemmas about the\n       list of tasks/response-time bounds. *)\n    Section SimpleLemmas.\n\n      (* Updating a single response-time bound does not modify the task. *)\n      Lemma edf_claimed_bounds_unzip1_update_bound :\n        forall l rt_bounds,\n          unzip1 (map (update_bound rt_bounds) l) = unzip1 l.\n      Proof.\n        induction l; first by done.\n        intros rt_bounds.\n        simpl; f_equal; last by done.\n        by unfold update_bound; desf.\n      Qed.\n\n      (* At any point of the iteration, the tasks are the same. *)\n      Lemma edf_claimed_bounds_unzip1_iteration :\n        forall l k,\n          unzip1 (iter k edf_rta_iteration (initial_state l)) = l.\n      Proof.\n        intros l k; clear -k.\n        induction k; simpl.\n        {\n          unfold initial_state.\n          induction l; first by done.\n          by simpl; rewrite IHl.\n        }\n        {\n          unfold edf_rta_iteration. \n          by rewrite edf_claimed_bounds_unzip1_update_bound.\n        }\n      Qed.\n\n      (* The iteration preserves the size of the list. *)\n      Lemma edf_claimed_bounds_size :\n        forall l k,\n          size (iter k edf_rta_iteration (initial_state l)) = size l.\n      Proof.\n        intros l k; clear -k.\n        induction k; simpl; first by rewrite size_map.\n        by rewrite size_map.\n      Qed.\n\n      (* If the analysis succeeds, the computed response-time bounds are no smaller\n         than the task cost. *)\n      Lemma edf_claimed_bounds_ge_cost :\n        forall l k tsk R,\n          (tsk, R) \\in (iter k edf_rta_iteration (initial_state l)) ->\n          R >= task_cost tsk.\n      Proof.\n        intros l k tsk R IN.\n        destruct k.\n        {\n          move: IN => /mapP IN; destruct IN as [x IN EQ]; inversion EQ.\n          by apply leqnn.\n        }\n        {\n          rewrite iterS in IN.\n          move: IN => /mapP IN; destruct IN as [x IN EQ].\n          unfold update_bound in EQ; destruct x; inversion EQ.\n          by unfold edf_response_time_bound; apply leq_addr.\n        }\n      Qed.\n\n      (* If the analysis suceeds, the computed response-time bounds are no larger\n         than the deadline. *)\n      Lemma edf_claimed_bounds_le_deadline :\n        forall ts rt_bounds tsk R,\n          edf_claimed_bounds ts = Some rt_bounds ->\n          (tsk, R) \\in rt_bounds ->\n          R <= task_deadline tsk.\n      Proof.\n        intros ts rt_bounds tsk R SOME PAIR; unfold edf_claimed_bounds in SOME.\n        destruct (all R_le_deadline (iter (max_steps ts)\n                                          edf_rta_iteration (initial_state ts))) eqn:DEADLINE;\n          last by done.\n        move: DEADLINE => /allP DEADLINE.\n        inversion SOME as [EQ]; rewrite -EQ in PAIR.\n        by specialize (DEADLINE (tsk, R) PAIR).\n      Qed.\n\n      (* The list contains a response-time bound for every task in the task set. *)\n      Lemma edf_claimed_bounds_has_R_for_every_task :\n        forall ts rt_bounds tsk,\n          edf_claimed_bounds ts = Some rt_bounds ->\n          tsk \\in ts ->\n          exists R,\n            (tsk, R) \\in rt_bounds.\n      Proof.\n        intros ts rt_bounds tsk SOME IN.\n        unfold edf_claimed_bounds in SOME.\n        destruct (all R_le_deadline (iter (max_steps ts) edf_rta_iteration (initial_state ts)));\n          last by done.\n        inversion SOME as [EQ]; clear SOME EQ.\n        generalize dependent tsk.\n        induction (max_steps ts) as [| step]; simpl in *.\n        {\n          intros tsk IN; unfold initial_state.\n          exists (task_cost tsk).\n          by apply/mapP; exists tsk.\n        }\n        {\n          intros tsk IN.\n          set prev_state := iter step edf_rta_iteration (initial_state ts).\n          fold prev_state in IN, IHstep.\n          specialize (IHstep tsk IN); des.\n          exists (edf_response_time_bound prev_state tsk R).\n          by apply/mapP; exists (tsk, R); [by done | by f_equal].\n        }\n      Qed.\n     \n    End SimpleLemmas.\n\n    (* In this section, we prove the convergence of the RTA procedure.\n       Since we define the RTA procedure as the application of a function\n       a fixed number of times, this translates into proving that the value\n       of the iteration at (max_steps ts) is equal to the value at (max_steps ts) + 1. *)\n    Section Convergence.\n\n      (* Consider any sequence of tasks with valid parameters. *)\n      Variable ts: seq sporadic_task.\n      Hypothesis H_valid_task_parameters:\n        valid_sporadic_taskset task_cost task_period task_deadline ts.\n      \n      (* To simplify, let f denote the RTA procedure. *)\n      Let f (k: nat) := iter k edf_rta_iteration (initial_state ts).\n\n      (* Since the iteration is applied directly to a list of tasks and response-times,\n         we define a corresponding relation \"<=\" over those lists. *)\n\n      (* Let 'all_le' be a binary relation over lists of tasks/response-time bounds.\n         It states that every element of list l1 has a response-time bound R that is less\n         than or equal to the corresponding response-time bound R' in list l2 (point-wise).\n         In addition, the relation states that the tasks of both lists are unchanged. *)\n      Let all_le := fun (l1 l2: list task_with_response_time) =>\n        (unzip1 l1 == unzip1 l2) &&\n        all (fun p => (snd (fst p)) <= (snd (snd p))) (zip l1 l2).\n\n      (* Similarly, we define a strict version of 'all_le' called 'one_lt', which states that\n         there exists at least one element whose response-time bound increases. *)\n      Let one_lt := fun (l1 l2: list task_with_response_time) =>\n        (unzip1 l1 == unzip1 l2) &&\n        has (fun p => (snd (fst p)) < (snd (snd p))) (zip l1 l2).\n\n      (* Next, we prove some basic properties about the relation all_le. *)\n      Section RelationProperties.\n\n        (* The relation is reflexive, ... *)\n        Lemma all_le_reflexive : reflexive all_le.\n        Proof.\n          intros l; unfold all_le; rewrite eq_refl andTb.\n          destruct l; first by done.\n          by apply/(zipP t (fun x y => snd x <= snd y)).\n        Qed.\n\n        (* ... and transitive. *)\n        Lemma all_le_transitive: transitive all_le.\n        Proof.\n          unfold transitive, all_le.\n          move => y x z /andP [/eqP ZIPxy LExy] /andP [/eqP ZIPyz LEyz].\n          apply/andP; split; first by rewrite ZIPxy -ZIPyz.\n          move: LExy => /(zipP _ (fun x y => snd x <= snd y)) LExy.\n          move: LEyz => /(zipP _ (fun x y => snd x <= snd y)) LEyz.\n          assert (SIZExy: size (unzip1 x) = size (unzip1 y)).\n            by rewrite ZIPxy.\n          assert (SIZEyz: size (unzip1 y) = size (unzip1 z)).\n            by rewrite ZIPyz.\n          rewrite 2!size_map in SIZExy; rewrite 2!size_map in SIZEyz.\n          destruct y.\n          {\n            apply size0nil in SIZExy; symmetry in SIZEyz.\n            by apply size0nil in SIZEyz; subst.\n          }\n          apply/(zipP t (fun x y => snd x <= snd y));\n            first by rewrite SIZExy -SIZEyz. \n          intros i LTi.\n          exploit LExy; first by rewrite SIZExy.\n          {\n            rewrite size_zip -SIZEyz -SIZExy minnn in LTi.\n            by rewrite size_zip -SIZExy minnn; apply LTi.\n          }\n          instantiate (1 := t); intro LE.\n          exploit LEyz; first by apply SIZEyz.\n          {\n            rewrite size_zip SIZExy SIZEyz minnn in LTi.\n            by rewrite size_zip SIZEyz minnn; apply LTi.\n          }\n          by instantiate (1 := t); intro LE'; apply (leq_trans LE).\n        Qed.\n\n        (* At any step of the iteration, the corresponding list\n           is larger than or equal to the initial state. *)\n        Lemma bertogna_edf_comp_iteration_preserves_minimum :\n          forall step, all_le (initial_state ts) (f step). \n        Proof.\n          unfold f.\n          intros step; destruct step; first by apply all_le_reflexive.\n          apply/andP; split.\n          {\n            assert (UNZIP0 := edf_claimed_bounds_unzip1_iteration ts 0).\n            by simpl in UNZIP0; rewrite UNZIP0 edf_claimed_bounds_unzip1_iteration.\n          }  \n          destruct ts as [| tsk0 ts'].\n          {\n            clear -step; induction step; first by done.\n            by rewrite iterSr IHstep.\n          }\n\n          apply/(zipP (tsk0,0) (fun x y => snd x <= snd y));\n            first by rewrite edf_claimed_bounds_size size_map.\n\n          intros i LTi; rewrite iterS; unfold edf_rta_iteration at 1.\n          have MAP := @nth_map _ (tsk0,0) _ (tsk0,0).\n          rewrite size_zip edf_claimed_bounds_size size_map minnn in LTi.\n          rewrite MAP; clear MAP; last by rewrite edf_claimed_bounds_size.\n          destruct (nth (tsk0, 0) (initial_state (tsk0 :: ts')) i) as [tsk_i R_i] eqn:SUBST.\n          rewrite SUBST; unfold update_bound.\n          unfold initial_state in SUBST.\n          have MAP := @nth_map _ tsk0 _ (tsk0, 0).\n          rewrite ?MAP // in SUBST; inversion SUBST; clear MAP. \n          assert (EQtsk: tsk_i = fst (nth (tsk0, 0) (iter step edf_rta_iteration\n                                                         (initial_state (tsk0 :: ts'))) i)).\n          {\n            have MAP := @nth_map _ (tsk0,0) _ tsk0 (fun x => fst x).\n            rewrite -MAP; clear MAP; last by rewrite edf_claimed_bounds_size.\n            have UNZIP := edf_claimed_bounds_unzip1_iteration; unfold unzip1 in UNZIP.\n            by rewrite UNZIP; symmetry. \n          }\n          destruct (nth (tsk0, 0) (iter step edf_rta_iteration (initial_state (tsk0 :: ts')))) as [tsk_i' R_i'].\n          by simpl in EQtsk; rewrite -EQtsk; subst; apply leq_addr.\n        Qed.\n\n        (* The application of the function is inductive. *)\n        Lemma bertogna_edf_comp_iteration_inductive (P : seq task_with_response_time -> Type) :\n          P (initial_state ts) ->\n          (forall k, P (f k) -> P (f (k.+1))) ->\n          P (f (max_steps ts)).\n        Proof.\n          by intros P0 Pn; induction (max_steps ts); last by apply Pn.\n        Qed.\n\n        (* As a last step, we show that edf_rta_iteration preserves order, i.e., for any\n           list l1 no smaller than the initial state, and list l2 such that\n           l1 <= l2, we have (edf_rta_iteration l1) <= (edf_rta_iteration l2). *)\n        Lemma bertogna_edf_comp_iteration_preserves_order :\n          forall l1 l2,\n            all_le (initial_state ts) l1 ->\n            all_le l1 l2 ->\n            all_le (edf_rta_iteration l1) (edf_rta_iteration l2).\n        Proof.\n          rename H_valid_task_parameters into VALID.\n          intros x1 x2 LEinit LE.\n          move: LE => /andP [/eqP ZIP LE]; unfold all_le.\n\n          assert (UNZIP': unzip1 (edf_rta_iteration x1) = unzip1 (edf_rta_iteration x2)).\n          {\n            by rewrite 2!edf_claimed_bounds_unzip1_update_bound.\n          }\n\n          apply/andP; split; first by rewrite UNZIP'.\n          apply f_equal with (B := nat) (f := fun x => size x) in UNZIP'.\n          rename UNZIP' into SIZE.\n          rewrite size_map [size (unzip1 _)]size_map in SIZE.\n          move: LE => /(zipP _ (fun x y => snd x <= snd y)) LE.\n          destruct x1 as [| p0 x1'], x2 as [| p0' x2']; try (by ins).\n          apply/(zipP p0 (fun x y => snd x <= snd y)); first by done.\n\n          intros i LTi.\n          exploit LE; first by rewrite 2!size_map in SIZE.\n          {\n            by rewrite size_zip 2!size_map -size_zip in LTi; apply LTi.\n          }\n          rewrite 2!size_map in SIZE.\n          instantiate (1 := p0); intro LEi.\n          rewrite (nth_map p0);\n            last by rewrite size_zip 2!size_map -SIZE minnn in LTi.\n          rewrite (nth_map p0);\n            last by rewrite size_zip 2!size_map SIZE minnn in LTi.\n          unfold update_bound, edf_response_time_bound; desf; simpl.\n          rename s into tsk_i, s0 into tsk_i', t into R_i, t0 into R_i', Heq into EQ, Heq0 into EQ'.\n          assert (EQtsk: tsk_i = tsk_i').\n          {\n            destruct p0 as [tsk0 R0], p0' as [tsk0' R0']; simpl in H2; subst.\n            have MAP := @nth_map _ (tsk0',R0) _ tsk0' (fun x => fst x) i ((tsk0', R0) :: x1').\n            have MAP' := @nth_map _ (tsk0',R0) _ tsk0' (fun x => fst x) i ((tsk0', R0') :: x2').\n            assert (FSTeq: fst (nth (tsk0', R0)((tsk0', R0) :: x1') i) =\n                           fst (nth (tsk0',R0) ((tsk0', R0') :: x2') i)).\n            {\n              rewrite -MAP;\n                last by simpl; rewrite size_zip 2!size_map /= -H0 minnn in LTi.\n              rewrite -MAP';\n                last by simpl; rewrite size_zip 2!size_map /= H0 minnn in LTi.\n              by f_equal; simpl; f_equal.\n            }\n            apply f_equal with (B := sporadic_task) (f := fun x => fst x) in EQ.\n            apply f_equal with (B := sporadic_task) (f := fun x => fst x) in EQ'.\n            by rewrite FSTeq EQ' /= in EQ; rewrite EQ.\n          }\n          subst tsk_i'; rewrite leq_add2l.\n          unfold I, total_interference_bound_edf; apply leq_div2r.\n          rewrite 2!big_cons.\n          destruct p0 as [tsk0 R0], p0' as [tsk0' R0'].\n          simpl in H2; subst tsk0'.\n          rename R_i into delta, R_i' into delta'.\n          rewrite EQ EQ' in LEi; simpl in LEi.\n          rename H0 into SIZE, H1 into UNZIP; clear EQ EQ'.\n\n          assert (SUBST: forall l delta,\n                    \\sum_(j <- l | let '(tsk_other, _) := j in\n                      different_task tsk_i tsk_other)\n                        (let '(tsk_other, R_other) := j in\n                          interference_bound_edf task_cost task_period task_deadline tsk_i delta\n                            (tsk_other, R_other)) =\n                    \\sum_(j <- l | different_task tsk_i (fst j))\n                      interference_bound_edf task_cost task_period task_deadline tsk_i delta j).\n          {\n            intros l x; clear -l.\n            induction l; first by rewrite 2!big_nil.\n            by rewrite 2!big_cons; rewrite IHl; desf; rewrite /= Heq in Heq0.\n          } rewrite 2!SUBST; clear SUBST.\n\n          assert (VALID': valid_sporadic_taskset task_cost task_period task_deadline\n                                                       (unzip1 ((tsk0, R0) :: x1'))).\n          {\n            move: LEinit => /andP [/eqP EQinit _].\n            rewrite -EQinit; unfold valid_sporadic_taskset.\n            move => tsk /mapP IN. destruct IN as [p INinit EQ]; subst.\n            by move: INinit => /mapP INinit; destruct INinit as [tsk INtsk]; subst; apply VALID.\n          }\n\n          assert (GE_COST: all (fun p => task_cost (fst p) <= snd p) ((tsk0, R0) :: x1')). \n          {\n            clear LE; move: LEinit => /andP [/eqP UNZIP' LE].\n            move: LE => /(zipP _ (fun x y => snd x <= snd y)) LE.\n            specialize (LE (tsk0, R0)).\n            apply/(all_nthP (tsk0,R0)).\n            intros j LTj; generalize UNZIP'; simpl; intro SIZE'.\n            have F := @f_equal _ _ size (unzip1 (initial_state ts)).\n            apply F in SIZE'; clear F; rewrite /= 3!size_map in SIZE'.\n            exploit LE; [by rewrite size_map /= | |].\n            {\n              rewrite size_zip size_map /= SIZE' minnn.\n              by simpl in LTj; apply LTj.\n            }\n            clear LE; intro LE.\n            unfold initial_state in LE.\n            have MAP := @nth_map _ tsk0 _ (tsk0,R0).\n            rewrite MAP /= in LE;\n              [clear MAP | by rewrite SIZE'; simpl in LTj].\n            apply leq_trans with (n := task_cost (nth tsk0 ts j));\n              [apply eq_leq; f_equal | by done].\n            have MAP := @nth_map _ (tsk0, R0) _ tsk0 (fun x => fst x).\n            rewrite -MAP; [clear MAP | by done].\n            unfold unzip1 in UNZIP'; rewrite -UNZIP'; f_equal.\n            clear -ts; induction ts; [by done | by simpl; f_equal].\n          }\n          move: GE_COST => /allP GE_COST.\n\n          assert (LESUM: \\sum_(j <- x1' | different_task tsk_i (fst j))\n                        interference_bound_edf task_cost task_period task_deadline tsk_i delta j <=                                  \\sum_(j <- x2' | different_task tsk_i (fst j))\n                        interference_bound_edf task_cost task_period task_deadline tsk_i delta' j).\n          {\n            set elem := (tsk0, R0); rewrite 2!(big_nth elem).\n            rewrite -SIZE.\n            rewrite big_mkcond [\\sum_(_ <- _ | different_task _ _)_]big_mkcond.\n            rewrite big_seq_cond [\\sum_(_ <- _ | true) _]big_seq_cond.\n            apply leq_sum; intros j; rewrite andbT; intros INj.\n            rewrite mem_iota add0n subn0 in INj; move: INj => /andP [_ INj].\n            assert (FSTeq: fst (nth elem x1' j) = fst (nth elem x2' j)).\n            {\n              have MAP := @nth_map _ elem _ tsk0 (fun x => fst x).\n              by rewrite -2?MAP -?SIZE //; f_equal.\n            } rewrite -FSTeq.\n            destruct (different_task tsk_i (fst (nth elem x1' j))) eqn:INTERF;\n              last by done.\n            {\n              exploit (LE elem); [by rewrite /= SIZE | | intro LEj].\n              {\n                rewrite size_zip 2!size_map /= -SIZE minnn in LTi.\n                by rewrite size_zip /= -SIZE minnn; apply (leq_ltn_trans INj).\n              }\n              simpl in LEj.\n              exploit (VALID' (fst (nth elem x1' j))); last intro VALIDj.\n              {\n                apply/mapP; exists (nth elem x1' j); last by done.\n                by rewrite in_cons; apply/orP; right; rewrite mem_nth.\n              }\n              exploit (GE_COST (nth elem x1' j)); last intro GE_COSTj.\n              {\n                by rewrite in_cons; apply/orP; right; rewrite mem_nth.\n              }\n              unfold is_valid_sporadic_task in *.\n              destruct (nth elem x1' j) as [tsk_j R_j] eqn:SUBST1,\n                       (nth elem x2' j) as [tsk_j' R_j'] eqn:SUBST2.\n              rewrite SUBST1 SUBST2 in LEj.\n              simpl in FSTeq; rewrite -FSTeq; simpl in LEj; simpl in VALIDj; des.\n              by apply interference_bound_edf_monotonic.\n            }\n          }\n          destruct (different_task tsk_i tsk0) eqn:INTERFtsk0; last by done.\n          apply leq_add; last by done.\n          {             \n            exploit (LE (tsk0, R0)); [by rewrite /= SIZE | | intro LEj];\n              first by instantiate (1 := 0); rewrite size_zip /= -SIZE minnn.\n            exploit (VALID' tsk0); first by rewrite in_cons; apply/orP; left.\n            exploit (GE_COST (tsk0, R0)); first by rewrite in_cons eq_refl orTb.\n            unfold is_valid_sporadic_task; intros GE_COST0 VALID0; des; simpl in LEj.\n            by apply interference_bound_edf_monotonic.\n          }\n        Qed.\n\n        (* It follows from the properties above that the iteration is monotonically increasing. *)\n        Lemma bertogna_edf_comp_iteration_monotonic: forall k, all_le (f k) (f k.+1).\n        Proof.\n          unfold f; intros k.\n          apply fun_mon_iter_mon_generic with (x1 := k) (x2 := k.+1);\n            try (by done);\n            [ by apply all_le_reflexive\n            | by apply all_le_transitive\n            | by apply bertogna_edf_comp_iteration_preserves_order\n            | by apply bertogna_edf_comp_iteration_preserves_minimum].\n        Qed.\n\n      End RelationProperties.\n\n      (* Knowing that the iteration is monotonically increasing (with respect to all_le),\n         we show that the RTA procedure converges to a fixed point. *)\n\n      (* First, note that when there are no tasks, the iteration trivially converges. *)\n      Lemma bertogna_edf_comp_f_converges_with_no_tasks :\n        size ts = 0 ->\n        f (max_steps ts) = f (max_steps ts).+1.\n      Proof.\n        intro SIZE; destruct ts; last by inversion SIZE.\n        unfold max_steps; rewrite big_nil /=.\n        by unfold edf_rta_iteration.\n      Qed.\n\n      (* Otherwise, if the iteration reached a fixed point before (max_steps ts), then\n         the value at (max_steps ts) is still at a fixed point. *)\n      Lemma bertogna_edf_comp_f_converges_early :\n        (exists k, k <= max_steps ts /\\ f k = f k.+1) ->\n        f (max_steps ts) = f (max_steps ts).+1.\n      Proof.\n        by intros EX; des; apply iter_fix with (k := k).\n      Qed.\n\n      (* Else, we derive a contradiction. *)\n      Section DerivingContradiction.\n\n        (* Assume that there are tasks. *)\n        Hypothesis H_at_least_one_task: size ts > 0.\n\n        (* Assume that the iteration continued to diverge. *)\n        Hypothesis H_keeps_diverging:\n          forall k,\n            k <= max_steps ts -> f k != f k.+1.\n\n        (* Since the iteration is monotonically increasing, it must be\n           strictly increasing. *)\n        Lemma bertogna_edf_comp_f_increases :\n          forall k,\n            k <= max_steps ts -> one_lt (f k) (f k.+1).\n        Proof.\n          rename H_at_least_one_task into NONEMPTY.\n          intros step LEstep; unfold one_lt; apply/andP; split;\n            first by rewrite 2!edf_claimed_bounds_unzip1_iteration.\n          rewrite -[has _ _]negbK; apply/negP; unfold not; intro ALL.\n          rewrite -all_predC in ALL.\n          move: ALL => /allP ALL.\n          exploit (H_keeps_diverging step); [by done | intro DIFF].\n          assert (DUMMY: exists tsk: sporadic_task, True).\n          {\n            destruct ts as [|tsk0]; first by rewrite ltnn in NONEMPTY.\n            by exists tsk0.\n          }\n          des; clear DUMMY.\n          move: DIFF => /eqP DIFF; apply DIFF.\n          apply eq_from_nth with (x0 := (tsk, 0));\n            first by simpl; rewrite size_map.\n          {\n            intros i LTi.\n            remember (nth (tsk, 0)(f step) i) as p_i;rewrite -Heqp_i.\n            remember (nth (tsk, 0)(f step.+1) i) as p_i';rewrite -Heqp_i'.\n            rename Heqp_i into EQ, Heqp_i' into EQ'.\n            exploit (ALL (p_i, p_i')).\n            {\n              rewrite EQ EQ'.\n              rewrite -nth_zip; last by unfold f; rewrite iterS size_map.\n              apply mem_nth; rewrite size_zip.\n              unfold f; rewrite iterS size_map.\n              by rewrite minnn.\n            }\n            unfold predC; simpl; rewrite -ltnNge; intro LTp.\n\n            have GROWS := bertogna_edf_comp_iteration_monotonic step.\n            move: GROWS => /andP [_ /allP GROWS].\n            exploit (GROWS (p_i, p_i')).\n            {\n              rewrite EQ EQ'.\n              rewrite -nth_zip; last by unfold f; rewrite iterS size_map.\n              apply mem_nth; rewrite size_zip.\n              unfold f; rewrite iterS size_map.\n              by rewrite minnn.\n            }\n            simpl; intros LE.\n            destruct p_i as [tsk_i R_i], p_i' as [tsk_i' R_i'].\n            simpl in *.\n            assert (EQtsk: tsk_i = tsk_i').\n            {\n              unfold edf_rta_iteration in EQ'.\n              rewrite (nth_map (tsk, 0)) in EQ'; last by done.\n              by unfold update_bound in EQ'; desf.\n            }\n            rewrite EQtsk; f_equal.\n            by apply/eqP; rewrite eqn_leq; apply/andP; split.\n          }\n        Qed.\n\n        (* In the end, each response-time bound is so high that the sum\n           of all response-time bounds exceeds the sum of all deadlines.\n           Contradiction! *)\n        Lemma bertogna_edf_comp_rt_grows_too_much :\n          forall k,\n            k <= max_steps ts ->\n            \\sum_((tsk, R) <- f k) (R - task_cost tsk) + 1 > k.\n        Proof.\n          have LT := bertogna_edf_comp_f_increases.\n          have MONO := bertogna_edf_comp_iteration_monotonic.\n          rename H_at_least_one_task into NONEMPTY.\n          unfold valid_sporadic_taskset, is_valid_sporadic_task in *.\n          rename H_valid_task_parameters into VALID.\n          intros step LE.\n          assert (DUMMY: exists tsk: sporadic_task, True).\n          {\n            destruct ts as [|tsk0]; first by rewrite ltnn in NONEMPTY.\n            by exists tsk0.\n          } destruct DUMMY as [elem _].\n\n          induction step; first by rewrite addn1.\n          {\n            rewrite -addn1 ltn_add2r.\n            apply leq_ltn_trans with (n := \\sum_(i <- f step) (let '(tsk, R) := i in R - task_cost tsk)).\n            {\n              rewrite -ltnS; rewrite addn1 in IHstep.\n              by apply IHstep, ltnW.\n            }\n            rewrite (eq_bigr (fun x => snd x - task_cost (fst x)));\n              last by ins; destruct i.\n            rewrite [\\sum_(_ <- f step.+1)_](eq_bigr (fun x => snd x - task_cost (fst x)));\n              last by ins; destruct i.\n            unfold f at 2; rewrite iterS.\n            rewrite big_map; fold (f step).\n            rewrite -(ltn_add2r (\\sum_(i <- f step) task_cost (fst i))).\n            rewrite -2!big_split /=.\n            rewrite big_seq_cond [\\sum_(_ <- _ | true)_]big_seq_cond.\n            rewrite (eq_bigr (fun i => snd i)); last first.\n            {\n              intro i; rewrite andbT; intro IN;\n              rewrite subh1; first by rewrite -addnBA // subnn addn0.\n              have GE_COST := edf_claimed_bounds_ge_cost ts step.\n              by destruct i; apply GE_COST.\n            }\n            rewrite [\\sum_(_ <- _ | _)(_ - _ + _)](eq_bigr (fun i => snd (update_bound (f step) i))); last first.\n            {\n              intro i; rewrite andbT; intro IN.\n              unfold update_bound; destruct i; simpl.\n              rewrite subh1; first by rewrite -addnBA // subnn addn0.\n              apply (edf_claimed_bounds_ge_cost ts step.+1).\n              by rewrite iterS; apply/mapP; exists (s, t).\n            }\n            rewrite -2!big_seq_cond.\n           \n            specialize (LT step (ltnW LE)).\n            specialize (MONO step).\n            move: LT => /andP [_ LT]; move: LT => /hasP LT.\n            destruct LT as [[x1 x2] INzip LT]; simpl in *.\n            move: MONO => /andP [_ /(zipP _ (fun x y => snd x <= snd y)) MONO].\n            rewrite 2!(big_nth (elem, 0)).\n            apply mem_zip_exists with (elem := (elem, 0)) (elem' := (elem, 0)) in INzip; des;\n              last by rewrite size_map.\n            rewrite -> big_cat_nat with (m := 0) (n := idx) (p := size (f step));\n              [simpl | by done | by apply ltnW].\n            rewrite -> big_cat_nat with (m := idx) (n := idx.+1) (p := size (f step));\n              [simpl | by done | by done].\n            rewrite big_nat_recr /=; last by done.\n            rewrite -> big_cat_nat with (m := 0) (n := idx) (p := size (f step));\n              [simpl | by done | by apply ltnW].\n            rewrite -> big_cat_nat with (m := idx) (n := idx.+1) (p := size (f step));\n              [simpl | by done | by done].\n            rewrite big_nat_recr /=; last by done.\n            rewrite [\\sum_(idx <= i < idx) _]big_geq // add0n.\n            rewrite [\\sum_(idx <= i < idx) _]big_geq // add0n.\n            rewrite -addn1 -addnA; apply leq_add.\n            {\n              rewrite big_nat_cond [\\sum_(_ <= _ < _ | true) _]big_nat_cond.\n              apply leq_sum; move => i /andP [/andP [LT1 LT2] _].\n              exploit (MONO (elem,0)); [by rewrite size_map | | intro LEi].\n              {\n                rewrite size_zip; apply (ltn_trans LT2).\n                by apply leq_trans with (n := size (f step));\n                  [by done | by rewrite size_map minnn].\n              }\n              unfold edf_rta_iteration in LEi.\n              by rewrite -> nth_map with (x1 := (elem, 0)) in LEi;\n                last by apply (ltn_trans LT2).\n            }\n            rewrite -addnA [_ + 1]addnC addnA; apply leq_add.\n            {\n              unfold edf_rta_iteration in INzip2; rewrite addn1.\n              rewrite -> nth_map with (x1 := (elem, 0)) in INzip2; last by done.\n              by rewrite -INzip2 -INzip1.\n            }\n            {\n              rewrite big_nat_cond [\\sum_(_ <= _ < _ | true) _]big_nat_cond.\n              apply leq_sum; move => i /andP [/andP [LT1 LT2] _].\n              exploit (MONO (elem,0));\n                [ by rewrite size_map\n                | by rewrite size_zip; apply (leq_trans LT2); rewrite size_map minnn | intro LEi ].\n              unfold edf_rta_iteration in LEi.\n              by rewrite -> nth_map with (x1 := (elem, 0)) in LEi; last by done.\n            }\n          }\n        Qed.\n\n      End DerivingContradiction. \n\n      (* Using the lemmas above, we prove that edf_rta_iteration reaches\n         a fixed point after (max_steps ts) step, ... *)\n      Lemma edf_claimed_bounds_finds_fixed_point_of_list :\n        forall rt_bounds,\n          edf_claimed_bounds ts = Some rt_bounds ->\n          valid_sporadic_taskset task_cost task_period task_deadline ts ->\n          f (max_steps ts) = edf_rta_iteration (f (max_steps ts)). \n      Proof.\n        intros rt_bounds SOME VALID.\n        unfold valid_sporadic_taskset, is_valid_sporadic_task in *.\n        unfold edf_claimed_bounds in SOME; desf.\n        rename Heq into LE.\n        fold (f (max_steps ts)) in *; fold (f (max_steps ts).+1).\n\n        (* Either the task set is empty or not. *)\n        destruct (size ts == 0) eqn:EMPTY;\n          first by apply bertogna_edf_comp_f_converges_with_no_tasks; apply/eqP.\n        apply negbT in EMPTY; rewrite -lt0n in EMPTY.\n\n        (* Either f converges by the deadline or not. *)\n        destruct ([exists k in 'I_((max_steps ts).+1), f k == f k.+1]) eqn:EX.\n        {\n          move: EX => /exists_inP EX; destruct EX as [k _ ITERk].\n          destruct k as [k LTk]; simpl in ITERk.\n          apply bertogna_edf_comp_f_converges_early.\n          exists k; split; [by apply LTk | by apply/eqP].\n        }\n\n        (* If not, then we reach a contradiction *)\n        apply negbT in EX; rewrite negb_exists_in in EX.\n        move: EX => /forall_inP EX.\n\n        assert (SAMESUM: \\sum_(tsk <- ts) task_cost tsk = \\sum_(p <- f (max_steps ts)) task_cost (fst p)).\n        {\n          have MAP := @big_map _ 0 addn _ _ (fun x => fst x) (f (max_steps ts))\n                               (fun x => true) (fun x => task_cost x).\n          have UNZIP := edf_claimed_bounds_unzip1_iteration ts (max_steps ts).\n          fold (f (max_steps ts)) in UNZIP; unfold unzip1 in UNZIP.\n          by rewrite UNZIP in MAP; rewrite MAP.\n        }\n        \n        (* Show that the sum is less than the sum of all deadlines. *)\n        assert (SUM: \\sum_(p <- f (max_steps ts)) (snd p - task_cost (fst p)) + 1 <= max_steps ts). \n        {\n          unfold max_steps at 2; rewrite leq_add2r.\n          rewrite -(leq_add2r (\\sum_(tsk <- ts) task_cost tsk)).\n          rewrite {1}SAMESUM -2!big_split /=.\n          rewrite big_seq_cond [\\sum_(_ <- _ | true)_]big_seq_cond.\n          rewrite (eq_bigr (fun x => snd x)); last first.\n          {\n            intro i; rewrite andbT; intro IN.\n            rewrite subh1; first by rewrite -addnBA // subnn addn0.\n            have GE_COST := edf_claimed_bounds_ge_cost ts (max_steps ts).\n            fold (f (max_steps ts)) in GE_COST.\n            by destruct i; apply GE_COST.\n          }\n          rewrite (eq_bigr (fun x => task_deadline x)); last first.\n          {\n            intro i; rewrite andbT; intro IN.\n            rewrite subh1; first by rewrite -addnBA // subnn addn0.\n            by specialize (VALID i IN); des.\n          }\n          rewrite -2!big_seq_cond.\n          have MAP := @big_map _ 0 addn _ _ (fun x => fst x) (f (max_steps ts))\n                               (fun x => true) (fun x => task_deadline x).\n          have UNZIP := edf_claimed_bounds_unzip1_iteration ts (max_steps ts).\n          fold (f (max_steps ts)) in UNZIP; unfold unzip1 in UNZIP.\n          rewrite UNZIP in MAP; rewrite MAP.\n          rewrite big_seq_cond [\\sum_(_ <- _|true)_]big_seq_cond.\n          apply leq_sum; intro i; rewrite andbT; intro IN.\n          move: LE => /allP LE; unfold R_le_deadline in LE.\n          by specialize (LE i IN); destruct i.\n        }\n\n        have TOOMUCH :=\n          bertogna_edf_comp_rt_grows_too_much EMPTY _ (max_steps ts) (leqnn (max_steps ts)).\n        exploit TOOMUCH; [| intro BUG].\n        {\n          intros k LEk; rewrite -ltnS in LEk.\n          by exploit (EX (Ordinal LEk)); [by done | by ins].\n        }\n        rewrite (eq_bigr (fun i => snd i - task_cost (fst i))) in BUG;\n          last by ins; destruct i.\n        by apply (leq_ltn_trans SUM) in BUG; rewrite ltnn in BUG. \n      Qed.\n\n      (* ...and since there cannot be a vector of response-time bounds with values less than\n         the task costs, this solution is also the least fixed point. *)\n      Lemma edf_claimed_bounds_finds_least_fixed_point :\n        forall v,\n          all_le (initial_state ts) v ->\n          v = edf_rta_iteration v ->\n          all_le (f (max_steps ts)) v.\n      Proof.\n        intros v GE0 EQ.\n        apply bertogna_edf_comp_iteration_inductive; first by done.\n        intros k GEk.\n        rewrite EQ.\n        apply bertogna_edf_comp_iteration_preserves_order; last by done.\n        by apply bertogna_edf_comp_iteration_preserves_minimum.\n      Qed.\n\n      (* Therefore, with regard to the response-time bound recurrence, ...*)\n      \n      (* ..., the individual response-time bounds (elements of the list) are also fixed points. *)\n      Theorem edf_claimed_bounds_finds_fixed_point_for_each_bound :\n        forall tsk R rt_bounds,\n          edf_claimed_bounds ts = Some rt_bounds ->\n          (tsk, R) \\in rt_bounds ->\n          R = edf_response_time_bound rt_bounds tsk R.\n      Proof.\n        intros tsk R rt_bounds SOME IN.\n        have CONV := edf_claimed_bounds_finds_fixed_point_of_list rt_bounds.\n        rewrite -iterS in CONV; fold (f (max_steps ts).+1) in CONV.\n        unfold edf_claimed_bounds in *; desf.\n        exploit (CONV); [by done | by done | intro ITER; clear CONV].\n        unfold f in ITER.\n\n        cut (update_bound (iter (max_steps ts)\n               edf_rta_iteration (initial_state ts)) (tsk,R) = (tsk, R)).\n        {\n          intros EQ.\n          have F := @f_equal _ _ (fun x => snd x) _ (tsk, R).\n          by apply F in EQ; simpl in EQ.\n        }\n        set s := iter (max_steps ts) edf_rta_iteration (initial_state ts).\n        fold s in ITER, IN.\n        move: IN => /(nthP (tsk,0)) IN; destruct IN as [i LT EQ].\n        generalize EQ; rewrite ITER iterS in EQ; intro EQ'.\n        fold s in EQ.\n        unfold edf_rta_iteration in EQ.\n        have MAP := @nth_map _ (tsk,0) _ _ (update_bound s). \n        by rewrite MAP // EQ' in EQ; rewrite EQ.\n      Qed.\n      \n    End Convergence.\n\n    Section MainProof.\n\n      (* Consider a task set ts where... *)\n      Variable ts: taskset_of sporadic_task.\n      \n      (* ...all tasks have valid parameters ... *)\n      Hypothesis H_valid_task_parameters:\n        valid_sporadic_taskset task_cost task_period task_deadline ts.\n\n      (* ...and constrained deadlines.*)\n      Hypothesis H_constrained_deadlines:\n        forall tsk, tsk \\in ts -> task_deadline tsk <= task_period tsk.\n\n      (* Next, consider any arrival sequence such that...*)\n      Context {arr_seq: arrival_sequence Job}.\n\n     (* ...all jobs come from task set ts, ...*)\n      Hypothesis H_all_jobs_from_taskset:\n        forall j, arrives_in arr_seq j -> job_task j \\in ts.\n      \n      (* ...they 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      (* ... and satisfy the sporadic task model.*)\n      Hypothesis H_sporadic_tasks:\n        sporadic_task_model task_period job_arrival job_task arr_seq.\n      \n      (* Then, consider any platform with at least one CPU such that...*)\n      Variable sched: schedule Job num_cpus.\n      Hypothesis H_at_least_one_cpu: num_cpus > 0.\n      Hypothesis H_jobs_come_from_arrival_sequence:\n        jobs_come_from_arrival_sequence sched arr_seq.\n\n      (* ...jobs only execute after they arrived and no longer\n         than their execution costs,... *)\n      Hypothesis H_jobs_must_arrive_to_execute:\n        jobs_must_arrive_to_execute job_arrival sched.\n      Hypothesis H_completed_jobs_dont_execute:\n        completed_jobs_dont_execute job_cost sched.\n\n      (* Assume a work-conserving scheduler with EDF policy. *)\n      Hypothesis H_work_conserving: work_conserving job_arrival job_cost arr_seq sched.\n      Hypothesis H_edf_policy: respects_JLFP_policy job_arrival job_cost arr_seq sched\n                                                    (EDF job_arrival job_deadline).\n\n      Definition no_deadline_missed_by_task (tsk: sporadic_task) :=\n        task_misses_no_deadline job_arrival job_cost job_deadline job_task arr_seq sched tsk.\n      Definition no_deadline_missed_by_job :=\n        job_misses_no_deadline job_arrival job_cost job_deadline sched.\n      Let response_time_bounded_by (tsk: sporadic_task) :=\n        is_response_time_bound_of_task job_arrival job_cost job_task arr_seq sched tsk.\n\n      (* In the following theorem, we prove that any response-time bound contained\n         in edf_claimed_bounds is safe. The proof follows by direct application of\n         the main Theorem from bertogna_edf_theory.v. *)\n      Theorem edf_analysis_yields_response_time_bounds :\n        forall tsk R,\n          (tsk, R) \\In edf_claimed_bounds ts ->\n          response_time_bounded_by tsk R.\n      Proof.\n        intros tsk R IN j JOBj.\n        destruct (edf_claimed_bounds ts) as [rt_bounds |] eqn:SOME; last by done.\n        unfold edf_rta_iteration in *.\n        have BOUND := bertogna_cirinei_response_time_bound_edf.\n        unfold is_response_time_bound_of_task in *.\n        apply BOUND with (task_cost := task_cost) (task_period := task_period)\n           (arr_seq := arr_seq) (task_deadline := task_deadline) (job_deadline := job_deadline)\n           (job_task := job_task) (ts := ts) (tsk := tsk) (rt_bounds := rt_bounds); try (by ins).\n          by unfold edf_claimed_bounds in SOME; desf; rewrite edf_claimed_bounds_unzip1_iteration.\n          by ins; apply edf_claimed_bounds_finds_fixed_point_for_each_bound with (ts := ts).\n          by ins; rewrite (edf_claimed_bounds_le_deadline ts rt_bounds).\n      Qed.\n      \n      (* Therefore, if the schedulability test suceeds, ...*)\n      Hypothesis H_test_succeeds: edf_schedulable ts.\n      \n      (*... no task misses its deadline. *)\n      Theorem taskset_schedulable_by_edf_rta :\n        forall tsk, tsk \\in ts -> no_deadline_missed_by_task tsk.\n      Proof.\n        have RLIST := (edf_analysis_yields_response_time_bounds).\n        have DL := (edf_claimed_bounds_le_deadline ts).\n        have HAS := (edf_claimed_bounds_has_R_for_every_task ts).\n        unfold no_deadline_missed_by_task, task_misses_no_deadline,\n               job_misses_no_deadline, completed,\n               edf_schedulable,\n               valid_sporadic_job in *.\n        rename H_valid_job_parameters into JOBPARAMS,\n               H_valid_task_parameters into TASKPARAMS,\n               H_constrained_deadlines into RESTR,\n               H_completed_jobs_dont_execute into COMP,\n               H_jobs_must_arrive_to_execute into MUSTARRIVE,\n               H_all_jobs_from_taskset into ALLJOBS,\n               H_test_succeeds into TEST.\n        \n        move => tsk INtsk j ARRj JOBtsk.\n        destruct (edf_claimed_bounds ts) as [rt_bounds |] eqn:SOME; last by ins.\n        exploit (HAS rt_bounds tsk); [by ins | by ins | clear HAS; intro HAS; des].\n        have COMPLETED := RLIST tsk R HAS j ARRj JOBtsk.\n        exploit (DL rt_bounds tsk R);\n          [by ins | by ins | clear DL; intro DL].\n   \n        rewrite eqn_leq; apply/andP; split; first by apply cumulative_service_le_job_cost.\n        apply leq_trans with (n := service sched j (job_arrival j + R)); last first.\n        {\n          unfold valid_sporadic_taskset, is_valid_sporadic_task in *.\n          apply extend_sum; rewrite // leq_add2l.\n          specialize (JOBPARAMS j ARRj); des; rewrite JOBPARAMS1.\n          by rewrite JOBtsk.\n        }\n        rewrite leq_eqVlt; apply/orP; left; rewrite eq_sym.\n        by apply COMPLETED.\n      Qed.\n\n      (* For completeness, since all jobs of the arrival sequence\n         are spawned by the task set, we conclude that no job misses\n         its deadline. *)\n      Theorem jobs_schedulable_by_edf_rta :\n        forall j, arrives_in arr_seq j -> no_deadline_missed_by_job j.\n      Proof.\n        intros j ARRj.\n        have SCHED := taskset_schedulable_by_edf_rta.\n        unfold no_deadline_missed_by_task, task_misses_no_deadline in *.\n        apply SCHED with (tsk := job_task j); try (by done).\n        by apply H_all_jobs_from_taskset.\n      Qed.\n      \n    End MainProof.\n\n  End Analysis.\n\nEnd ResponseTimeIterationEDF.", "meta": {"author": "cd-public", "repo": "rt-proofs", "sha": "ebef0b65460fe009c51f638fe2b459f16a6d1dd5", "save_path": "github-repos/coq/cd-public-rt-proofs", "path": "github-repos/coq/cd-public-rt-proofs/rt-proofs-ebef0b65460fe009c51f638fe2b459f16a6d1dd5/analysis/global/parallel/bertogna_edf_comp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6685764655905913}}
{"text": "Load \"include/ops_header.v\".\n\nModule precond.\n\nDefinition Sn (n k : int) := (k != n + 1) /\\ (n != -1).\n\nDefinition Sk (n k : int) := (k + 1 != 0) /\\ (n != 0).\n\nEnd precond.\n\nDefinition not_D (n k : int) := (n >= 0) && (k >= 0) && (k < n).\n\nLoad \"include/ann_c.v\".\n\nDefinition CT (c : int -> int -> rat) := forall (n_ k_ : int), not_D n_ k_ -> \nP_horner (c ^~ k_) n_ = Q_flat c n_ (int.shift 1 k_) - Q_flat c n_ k_.\n\nRecord Ann c : Type := ann {\n  Sn_ : Sn c;\n  Sk_ : Sk c\n}.\n", "meta": {"author": "coq-community", "repo": "apery", "sha": "305046d98025d75ca426cc44283302963389f1dc", "save_path": "github-repos/coq/coq-community-apery", "path": "github-repos/coq/coq-community-apery/apery-305046d98025d75ca426cc44283302963389f1dc/theories/annotated_recs_c.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6685534132195576}}
{"text": "Require Import Cast.\nRequire Import Eq.\nRequire Import Setoids.\n\nDefinition fw (a b:Setoid) (p:elems a = elems b) (x:elems a) : elems b := cast p x.\nDefinition bw (a b:Setoid) (p:elems a = elems b) (y:elems b) : elems a := cast' p y.\n\nArguments fw {a} {b} _ _.\nArguments bw {a} {b} _ _.\n\n\nLemma bwfw : forall (a b:Setoid) (p q:elems a = elems b) (x:elems a),\n    bw p (fw q x) = x.\nProof. intros a b p q x. apply cast_inv_left. Qed.\n\nLemma fwbw : forall (a b:Setoid) (p q:elems a = elems b) (y:elems b),\n    fw p (bw q y) = y.\nProof. intros a b p q y. apply cast_inv_right. Qed.\n\n\nLemma sameSetoid : forall (a b:Setoid) (p:elems a = elems b),\n    (forall (x y:elems a), x == y -> fw p x == fw p y) ->\n    (forall (x y:elems b), x == y -> bw p x == bw p y) -> \n    a = b.\nProof.\n    intros [a eqA] [b eqB]. simpl. intro p. revert eqA eqB. \n    rewrite <- p. clear p. unfold fw, bw, cast'. simpl.\n    intros eqA eqB Hf Hb. \n    assert (eqA = eqB) as E.\n        { apply sameEq. split.\n            - apply Hf.\n            - apply Hb.\n        } \n    rewrite E. reflexivity.\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/cat/EqSetoids.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6684742626069811}}
{"text": "(* Prefer to not include this file \nRequire Export ECAlg. \nRequire Export SM3. \n \nOpen Scope N_scope. \n\n(* TODO RANDOMLY sample a number in [low, high] *)\nDefinition SampleN (low : N)(high : N)(seed : N) : N :=\n  low + (seed mod (high + 1 - low)). \n\n(*Compute map (SampleN 10 20) (Nlist 15). *)\n\n(* Generally try each element in l until func returns false. Should all true returns true *)\nFixpoint Scrutinize (DomType : Type)(test : DomType -> bool)(l : list DomType) : bool :=\n  match l with\n  | [] => true\n  | h :: tl =>\n      match test h with\n      | false => false\n      | true => Scrutinize DomType test tl\n      end\n  end. \n\nDefinition ScrutN (test : N -> bool)(l : list N): bool :=\n  Scrutinize N test l. \n\n(* For B.1.10, false if composite *)\nDefinition TryFunb (func : N -> bool)(l : list N) : bool :=\n  ScrutN func l.  \n(*\n  match l with\n  | [] => true\n  | j :: tl =>\n      match func j with\n      | false => false (* b.5 *)\n      | true => TryFunb tl func (* b.6 *)\n      end\n  end. \n*)\n(*\nFixpoint TryFunb (l : list N)(func : N -> (bool * N)) : (bool * N * N) :=\n  match l with\n  | [] => (true, 0, 0)\n  | j :: tl =>\n      match func j with\n      | (false, i) => (false, j, i) (* b.5 *)\n      | (true, i) => TryFunb tl func (* b.6 *)\n      end\n  end. \n*)\nFixpoint TryFunb4 (b u : N)(func : N -> N -> option bool)(l : list N) : bool :=\n  match l with\n  | [] => false (* b.5 *)\n  | i :: tl =>\n      let b2 := (N.square b) mod u in\n        match func i b2 with\n        | Some result => result\n        | None => TryFunb4 b2 u func tl\n        end\n  end.\n\nDefinition NInterval (low : N)(high : N) : list N :=\n  map (N.add low) (Nlist (high + 1 - low)).\n\n(* Returns (v, w) so that m = 2 ^ v * w and w is odd *)\nFixpoint Decom_tail (v : N)(n : positive) : N * positive :=\n  match n with\n  | xH => (v, xH)\n  | xI _ => (v, n)\n  | xO n' => Decom_tail (v + 1) n'\n  end. \n\nDefinition Decom (m : N) : N * N :=\n  match m with\n  | N0 => (0, 0)\n  | Npos n => \n      match Decom_tail N0 n with\n      | (v, w) => (v, Npos w)\n      end\n  end. \n\n\n(*B.1.10 u is odd and T is positive. If returns true then u is a ProbPrime.\nIf Returns false then u is a composite.  *)\n(* TODO NInterval is too long in memory *)\nDefinition ProPrimTest (T : N)(u : N) : bool :=\n  let m := u - 1 in\n  let (v, w) := Decom m in (\n  TryFunb  \n  (fun j =>\n    let a := SampleN 2 m j in\n    let b := (a ^ w) mod u in\n    if orb (N.eqb b 1) (N.eqb b m) then true (* b.3 *) else\n      TryFunb4 b u  (* b.4 *)\n      (fun i b2 =>\n          if N.eqb b2 m then Some true else (* b.4.2 *)\n          if N.eqb b2 1 then Some false else (* b.4.3 *)\n          None (* b.4.4 *)\n      ) (NInterval 1 (v - 1)))\n  )\n  (NInterval 1 T). \n\n\n(*\nDefinition ProPrimTest_debug (T : N)(u : N) : (bool * N * N * N * N * N * N) :=\n  let m := u - 1 in\n  let (v, w) := Decom m in (\n  TryFunb (NInterval 1 T) \n  (fun j =>\n    let a := SampleN 2 m j in\n    let b := (a ^ w) mod u in\n    if orb (N.eqb b 1) (N.eqb b m) then (true, j) (* b.3 *) else\n      TryFunb4 (NInterval 1 (v - 1)) b u (* b.4 *)\n      (fun i b2 =>\n          if N.eqb b2 m then Some true else (* b.4.2 *)\n          if N.eqb b2 1 then Some false else (* b.4.3 *)\n          None (* b.4.4 *)\n      )\n  ), u, m, v, w). \n\nDefinition ProPrimTest (T : N)(u : N) : bool :=\n  match ProPrimTest_debug T u with\n  | (result, _, _, _, _, _, _) => result\n  end.\n*)\n(*\nCompute map (ProPrimTest_debug 999) (NInterval 3 99). (* 100% Correct *)\n*)\n\n(* From C.2 Example 1 *)\nDefinition constant_a := HexString.to_N \"0xBB8E5E8FBC115E139FE6A814FE48AAA6F0ADA1AA5DF91985\". \nDefinition constant_p := HexString.to_N \"0xBDB6F4FE3E8B1D9E0DA8C0D46F4C318CEFE4AFE3B6B8551F\". \n \n(* true if passed the test, i.e. not singular *)\nDefinition SingTest (a b p : N) : bool :=\n negb (4 * (P_power a 3 p) + 27 * (square b) =? 0). \n(* D.1.1 method 2, true if this tuple is valid*)\nDefinition CheckSEED (SEED : bL)(a p : N) : option (bL * N * N) :=\n  (*if Nat.leb (List.length SEED) 191%nat then None else*)\n  let b := (SM3_HashN SEED) mod p in \n    if negb (SingTest a b p) then None\n    else Some (SEED, a, b). \n\nFixpoint GenSab_tail (p a : N)(seedl : list bL) : option (bL * N * N) :=\n  match seedl with\n  | [] => None\n  | h :: tl =>\n      match CheckSEED h a p with\n      | Some tuple => Some tuple\n      | None => GenSab_tail p a tl\n      end\n  end. \n\nDefinition constant_seedlist := map \n  (fun x => NtobL_len 192 x) [0; 1; 2 ^ 90; 2 ^ 191]. \n\nDefinition GenSab (a p : N) : option (bL * N * N) :=\n  GenSab_tail p a constant_seedlist. \n\nDefinition DisplaySab (para : option (bL * N * N)) :=\n  match para with\n  | None => (\"\", \"\", \"\")\n  | Some (SEED, a, b) => (bStohS (bLtobS SEED), HexString.of_N a, HexString.of_N b)\n  end. \n\n\n(* D.2.1 method 2 *)\nDefinition VeriSab (p b : N)(SEED : bL) : bool :=\n  b =? (SM3_HashN SEED) mod p. \n\nDefinition constant_T := 999. \n\n\n(* A.4.2.1, true means pass *)\n(* j = B - i + 1 *)\nFixpoint MOV_Test_tail (q n : N)(j : nat)(acc : list (bool * N)) : list (bool * N)  :=\n  match j with\n  | O => acc (* i = B + 1, break *) \n  | S j' =>\n      match acc with\n      | [] => [] (*which will not happen*)\n      | (b_old, t_old) :: tl =>\n        let t := (t_old * q) mod n in\n        let b := andb b_old (negb (t =? 1)) in\n          MOV_Test_tail q n j' ((b, t) :: acc)\n      end\n  end. \n\n(* n is a prime and q is a prime exponent *)\nDefinition MOV_Test (B: nat)(q n : N) : bool :=\n  fst (List.hd (false, 0) (MOV_Test_tail q n B [(true, 1)])). \n\nDefinition constant_B := 27%nat. \n\n(* A.4.2.2, true means pass *)\nDefinition Anomalous_Curve_Test (p order: N) : bool :=\n  negb (p =? order). \n\n(* floor(2*sqrt(p)) *)\nDefinition floor2sqrt(p : N) : N :=\n  let r2 := N.double (N.sqrt p) in\n  if r2 =? N.sqrt (p * 4) then r2 else r2 + 1. \n\nDefinition Computeh' (p n : N) : N :=\n  N.div (p + 1 + (floor2sqrt p)) n. \n(* 5.2.2 returns None if valid, otherwise Some error message*)\n(* Quick tests for large inputs *)\nDefinition VeriSysPara_Quick (p a b n h xG yG order : N)(SEED : bL) : option string :=\n  if even p then Some \"p is even.\" else\n  if p <=? a then Some \"a >= p\" else\n  if p <=? b then Some \"b >= p\" else\n  if p <=? xG then Some \"xG >= p\" else\n  if p <=? yG then Some \"yG >= p\" else\n  let SEED_len := (N.of_nat (List.length SEED)) in\n  if andb (0 <? SEED_len) (SEED_len <? 192) then Some \"SEED is shorter than 192.\" else\n  if andb (0 <? SEED_len ) (negb (VeriSab p b SEED)) then Some \"Failed in VeriSab.\" else\n  if negb (SingTest p a b) then Some \"Failed in SingTest.\" else\n  if negb (OnCurve_pf p a b xG yG) then Some \"Failed in OnCurveTest.\" else\n  if n <=? N.shiftl 1 191 then Some \"n <= 2 ^ 192.\" else\n  if square n <=? 16 * p then Some \"n <= 4 p ^ 1/2.\" else\n  if negb (h =? Computeh' p n) then Some \"h != h'.\" else\n  None. \n\n(* These tests are quite time consuming *)\nDefinition VeriSysPara (p a b n h xG yG order: N)(SEED : bL) : option string :=\n  match VeriSysPara_Quick p a b n h xG yG order SEED with\n  | Some msg => Some msg\n  | None =>\n    if negb (GE_eqb (pf_mul p a (Cop (xG, yG)) n) InfO) then Some \"[n]G != O.\" else\n    if negb (ProPrimTest constant_T p) then Some \"p is a composite.\" else\n    if negb (ProPrimTest constant_T n)  then Some \"n is a composite.\" else\n    if negb (MOV_Test constant_B p n ) then Some \"Failed in MOV test\" else \n    if negb (Anomalous_Curve_Test p order) then Some \"Failed in Anomalous Curve Test\" else\n    None\n  end.\nModule tests. \n\n(*\n(* C.2 *)\n(* Example 1 *)\nTime Compute \nlet p := hStoN \"BDB6F4FE3E8B1D9E0DA8C0D46F4C318CEFE4AFE3B6B8551F\" in\nlet a := hStoN \"BB8E5E8FBC115E139FE6A814FE48AAA6F0ADA1AA5DF91985\" in\nlet b := hStoN \"1854BEBDC31B21B7AEFC80AB0ECD10D5B1B3308E6DBF11C1\" in\nlet xG := hStoN \"4AD5F7048DE709AD51236DE65E4D4B482C836DC6E4106640\" in\nlet yG := hStoN \"02BB3A02D4AAADACAE24817A4CA3A1B014B5270432DB27D2\" in\nlet n := hStoN \"BDB6F4FE3E8B1D9E0DA8C0D40FC962195DFAE76F56564677\" in\nlet h := 1 in (*By Hasse Thm*)\nlet order := 1 in (*There is no way for me to know it, just assign it to test*)\n  VeriSysPara_Quick p a b n h xG yG order []\n\n. (* None *)\n\n(* Example 2 *)\nTime Compute \nlet p := hStoN \"8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3\" in\nlet a := hStoN \"787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498\" in\nlet b := hStoN \"63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A\" in\nlet xG := hStoN \"421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D\" in\nlet yG := hStoN \"0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2\" in\nlet n := hStoN \"8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7\" in\nlet h := 1 in (*By Hasse Thm*)\nlet order := 1 in (*There is no way for me to know it, just assign it to test*)\n  VeriSysPara_Quick p a b n h xG yG order []\n. (* None *)\n\nEnd tests. \n*)\n\n(* B.2.4, Irredicible Polynomial Test*)\n(* j = d/2 - i *)\nFixpoint IrdBody (sq : N -> N)(gcd : N -> N -> N)(f u' : N)(j : nat) : bool :=\n  match j with\n  | O => true\n  | S j' =>\n    let u := B_mod (sq u') f in\n    let g := gcd (B_add u 2) f in\n      if N.eqb g 1 then IrdBody sq gcd f u j'\n        else false\n  end. \n\nDefinition IrdTest (f : N) : bool :=\n  let d := size_nat f in\n  let u := 2%N in\n    IrdBody (Bp_sq_raw) B_gcd f u (Nat.div d 2). \n\n(*\n(* TODO need test casess *)\n\nCompute IrdTest  37. (* Correct  *)\n\nCompute List.length []. \n\nPrint map. \n\nCompute map N.double [2; 3]. \n\nDefinition TPB_list := map decode_TPB TPB_IRP. \n \n(*Compute map IrdTest (TPB_list). All true, correct *)\nDefinition PPB_list := map decode_PPB PPB_IRP. \n(*Time Compute map IrdTest (PPB_list).*) (*Finished transaction in 393.439 secs (393.19u,0.153s) (successful)All true, correct *)\n*)\nEnd tests. \n*)", "meta": {"author": "sleepycoke", "repo": "ShangMi_Coq", "sha": "0bbfe578c332f87535f2fa2dc595259ba944f206", "save_path": "github-repos/coq/sleepycoke-ShangMi_Coq", "path": "github-repos/coq/sleepycoke-ShangMi_Coq/ShangMi_Coq-0bbfe578c332f87535f2fa2dc595259ba944f206/SysPara.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6684742532951451}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.PArith.BinPosDef.\nRequire Import Coq.ZArith.Znumtheory.\n\nRequire Import Crypto.Spec.ModularArithmetic.\nRequire Import Crypto.Arithmetic.PrimeFieldTheorems.\nRequire Import Coq.Bool.Bool.\n\n\nRequire Import Circom.Tuple.\nRequire Import Crypto.Util.Decidable. (* Crypto.Util.Notations. *)\nRequire Import BabyJubjub.\nRequire Import Coq.setoid_ring.Ring_theory Coq.setoid_ring.Field_theory Coq.setoid_ring.Field_tac.\nRequire Import Crypto.Algebra.Ring Crypto.Algebra.Field.\n\nFrom Circom Require Import Circom Default LibTactics Util.\nRequire Import Circom.Circom Circom.Default.\n\n(* Circuit:\n* https://github.com/iden3/circomlib/blob/master/circuits/gates.circom\n*)\n\nLocal Open Scope list_scope.\nLocal Open Scope F_scope.\n\nModule Gates.\n\n#[local] Hint Extern 10 (_ = _) => fqsatz : core.\n#[local] Hint Extern 10 (binary _) => (left; fqsatz) || (right; fqsatz): core.\n\n\nModule XOR.\n(* template XOR() {\n    signal input a;\n    signal input b;\n    signal output out;\n    out <== a + b - 2*a*b;\n} *)\n\nDefinition cons (a b out: F) :=\n  out = a + b - (1 + 1) * a * b.\n\nRecord t := { a:F; b:F; out:F; _cons: cons a b out; }.\n\nTheorem soundness: forall (c: t), \n  (* pre-conditions *)\n  binary c.(a) ->\n  binary c.(b) ->\n  (* post-conditions *)\n  if (c.(a) = c.(b))? then c.(out) = 0 else c.(out) = 1 /\\\n  binary c.(out).\nProof.\n  unwrap_C.\n  intros c Ha Hb. destruct c as [a b c _cons].\n  unfold cons in *. simpl in *.\n  destruct Ha; destruct Hb; subst; split_dec; intuit;\n  auto.\nQed.\nEnd XOR.\n\n\nModule AND.\n(* template AND() {\n    signal input a;\n    signal input b;\n    signal output out;\n    out <== a*b;\n} *)\n\nDefinition cons (a b out: F) :=\n  out = a * b.\n\nRecord t := { a:F; b:F; out:F; _cons: cons a b out; }.\n\nTheorem soundness: forall (c: t), \n  (* pre-conditions *)\n  binary c.(a) ->\n  binary c.(b) ->\n  (* post-conditions *)\n  binary c.(out) /\\\n  ((c.(a) = 1)?) && ((c.(b) = 1)?) = ((c.(out) = 1)?).\nProof.\n  unwrap_C.\n  intros c Ha Hb. destruct c as [a b c _cons].\n  unfold cons in *. simpl in *.\n  destruct Ha; destruct Hb; subst; split_dec; intuit;\n  auto || (exfalso; auto).\nQed.\n\nLemma is_sound (c: t):\n  binary c.(a) ->\n  binary c.(b) ->\n  (c.(out) = 1 <-> (c.(a) = 1 /\\ c.(b) = 1)).\nProof.\n  intros Hbin_a Hbin_b.\n  specialize (soundness c Hbin_a Hbin_b). intro.\n  split_dec; simpl in *; intuit; auto || discriminate.\nQed.\n\n\nLemma is_binary (c: t):\n  binary c.(a) ->\n  binary c.(b) ->\n  binary c.(out).\nProof. specialize (soundness c). intuit. Qed.\n\nDefinition wgen: t. skip. Defined.\n\n#[global] Instance Default: Default t. constructor. exact wgen. Defined.\n\nEnd AND.\n\n\n\nModule OR.\n(* template OR() {\n    signal input a;\n    signal input b;\n    signal output out;\n\n    out <== a + b - a*b;\n} *)\nDefinition cons (a b out: F) :=\n  out = a + b - a*b.\n\nRecord t := { a:F; b:F; out:F; _cons: cons a b out; }.\n\nTheorem soundness: forall (c: t), \n  (* pre-conditions *)\n  binary c.(a) ->\n  binary c.(b) ->\n  (* post-conditions *)\n  binary c.(out) /\\\n  ((c.(a) = 1)?) || ((c.(b) = 1)?) = ((c.(out) = 1)?).\nProof.\n  unwrap_C.\n  intros c Ha Hb. destruct c as [a b c _cons].\n  unfold cons in *. simpl in *.\n  destruct Ha; destruct Hb; subst; split_dec; intuit;\n  auto || (exfalso; auto).\nQed.\n\nLemma is_sound (c: t):\n  binary c.(a) ->\n  binary c.(b) ->\n  (c.(out) = 1 <-> (c.(a) = 1 \\/ c.(b) = 1)).\nProof.\n  intros Hbin_a Hbin_b.\n  specialize (soundness c Hbin_a Hbin_b). intro.\n  split_dec; simpl in *; intuit; auto || discriminate.\nQed.\n\n\nLemma is_binary (c: t):\n  binary c.(a) ->\n  binary c.(b) ->\n  binary c.(out).\nProof. specialize (soundness c). intuition idtac. Qed.\n\nDefinition wgen: t. skip. Defined.\n\n#[global] Instance Default: Default t. constructor. exact wgen. Defined.\nEnd OR.\n\n\n\nModule NOT.\n(* template NOT() {\n    signal input in;\n    signal output out;\n\n    out <== 1 + in - 2*in;\n} *)\nDefinition cons (_in out: F) :=\n  out = 1 + _in - (1 + 1) * _in.\n\nRecord t := { _in:F; out:F; _cons: cons _in out; }.\n\nLemma not_0_eq_1: (0:F) <> (1:F).\nProof. unwrap_C. fqsatz.\nQed.\n\nTheorem soundness: forall (c: t), \n  (* pre-conditions *)\n  binary c.(_in) ->\n  (* post-conditions *)\n  binary c.(out) /\\\n  ((c.(_in) = 1)?) = ((c.(out) = 0)?).\nProof.\n  unwrap_C.\n  intros c Ha. destruct c as [_in out _cons].\n  unfold cons in *. simpl in *.\n  destruct Ha; subst; split_dec; intuit; auto || (exfalso; auto).\nQed.\n\nDefinition wgen: t. skip. Defined.\n\n#[global] Instance Default: Default t. constructor. exact wgen. Defined.\nEnd NOT.\n\n\n\nModule NAND.\n(* template NAND() {\n    signal input a;\n    signal input b;\n    signal output out;\n\n    out <== 1 - a*b;\n} *)\n\nDefinition cons (a b out: F) :=\n  out = 1 - a * b.\n\nRecord t := { a:F; b:F; out:F; _cons: cons a b out; }.\n\nTheorem soundness: forall (c: t), \n  (* pre-conditions *)\n  binary c.(a) ->\n  binary c.(b) ->\n  (* post-conditions *)\n  binary c.(out) /\\\n  ((c.(a) = 1)?) && ((c.(b) = 1)?) = ((c.(out) = 0)?).\nProof.\n  unwrap_C.\n  intros c Ha Hb. destruct c as [a b c _cons].\n  unfold cons in *. simpl in *.\n  destruct Ha; destruct Hb; subst; split_dec; intuit;\n  auto || (exfalso; auto).\nQed.\n\nDefinition wgen: t. skip. Defined.\n\n#[global] Instance Default: Default t. constructor. exact wgen. Defined.\n\nEnd NAND.\n\n\n\nModule NOR.\n(* template NOR() {\n    signal input a;\n    signal input b;\n    signal output out;\n\n    out <== a*b + 1 - a - b;\n} *)\nDefinition cons (a b out: F) :=\n  out = a*b + 1 - a - b.\n\nRecord t := { a:F; b:F; out:F; _cons: cons a b out; }.\n\nTheorem soundness: forall (c: t), \n  (* pre-conditions *)\n  binary c.(a) ->\n  binary c.(b) ->\n  (* post-conditions *)\n  binary c.(out) /\\\n  ((c.(a) = 1)?) || ((c.(b) = 1)?) = ((c.(out) = 0)?).\nProof.\n  unwrap_C.\n  intros c Ha Hb. destruct c as [a b c _cons].\n  unfold cons in *. simpl in *.\n  destruct Ha; destruct Hb; subst; split_dec; intuit;\n  auto || (exfalso; auto).\nQed.\n\nDefinition wgen: t. skip. Defined.\n\n#[global] Instance Default: Default t. constructor. exact wgen. Defined.\nEnd NOR.\n\n\nModule MultiAND.\n\n(* template MultiAND(n) {\n    signal input in[n];\n    signal output out;\n    component and1;\n    component and2;\n    component ands[2];\n    if (n==1) {\n        out <== in[0];\n    } else if (n==2) {\n        and1 = AND();\n        and1.a <== in[0];\n        and1.b <== in[1];\n        out <== and1.out;\n    } else {\n        and2 = AND();\n        var n1 = n\\2;\n        var n2 = n-n\\2;\n        ands[0] = MultiAND(n1);\n        ands[1] = MultiAND(n2);\n        var i;\n        for (i=0; i<n1; i++) ands[0].in[i] <== in[i];\n        for (i=0; i<n2; i++) ands[1].in[i] <== in[n1+i];\n        and2.a <== ands[0].out;\n        and2.b <== ands[1].out;\n        out <== and2.out;\n    }\n} *)\n\nEnd MultiAND.\n\nEnd Gates.", "meta": {"author": "Veridise", "repo": "Coda", "sha": "d22d56c09ac541f012adae34820850ce6cd10270", "save_path": "github-repos/coq/Veridise-Coda", "path": "github-repos/coq/Veridise-Coda/Coda-d22d56c09ac541f012adae34820850ce6cd10270/BigInt/src/CircomLib/Gates.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6684742507520389}}
{"text": "Require Import ILL.Definitions.\n\n(** ** PCP reduces to BPCP *)\n\n(* natural numbers n to bitstrings of the form 1^n *)\n\nDefinition to_bitstring (n : nat) : string bool := Nat.iter n (cons true) [].\n\nLemma bitstring_false a : ~ false el to_bitstring a.\nProof.\n  induction a; cbn; firstorder.\nQed.\n\n(* strings of natural numbers to bitstrings, [ n1, ... n2 ] |-> 1^n1 0 ... 1^n2 0 *)\nFixpoint f_s (x : string nat) : string bool :=\n  match x with\n  | nil => nil\n  | a :: x => to_bitstring a ++ [false] ++ f_s x\n  end.\n\nLemma f_s_app x y : f_s (x ++ y) = f_s x ++ f_s y.\nProof.\n  induction x; cbn. \n  - reflexivity.\n  - rewrite IHx. now simpl_list.\nQed.\n\n(* extension to cards and stacks *)\nDefinition f_c '(x,y) := (f_s x, f_s y).\nDefinition f (P : SRS) : BSRS :=\n  map f_c P.\n\nLemma tau1_f A : tau1 (f A) = f_s (tau1 A).\nProof.\n  induction A as [ | (x,y) ]; cbn.\n  - reflexivity.\n  - unfold f in IHA. now rewrite IHA, f_s_app.\nQed.\n\nLemma tau2_f A : tau2 (f A) = f_s (tau2 A).\nProof.\n  induction A as [ | (x,y) ]; cbn.\n  - reflexivity.\n  - unfold f in IHA. now rewrite IHA, f_s_app.\nQed.\n\n(* interpretation of a bitstring as list of natural numbers *)\nFixpoint g_s' (x : string bool) (n : nat) : string nat :=\n  match x with\n  | nil => nil\n  | true :: x' => g_s' x' (S n)\n  | false :: x' => n :: g_s' x' 0\n  end.\n\nLemma g_s'_app n x y :\n  g_s' (f_s x ++ y) n = match x with nil => g_s' y n | m :: x => n + m :: x ++ g_s' y 0 end.\nProof.\n  revert n y. induction x as [ | m]; intros; cbn in *.\n  - reflexivity.\n  - revert n; induction m; intros; cbn in *.\n    + destruct x.\n      * do 2 f_equal. omega.\n      * rewrite IHx. f_equal. omega.\n    + rewrite IHm. f_equal. omega.\nQed.\n\nDefinition g_s x := g_s' x 0.\n\nLemma f_g_s'_inv x : g_s (f_s x) = x.\nProof.\n  unfold g_s. setoid_rewrite <- app_nil_r at 2. rewrite g_s'_app.\n  destruct x; now simpl_list. \nQed.\n\n(* extension to cards and stacks *)\nDefinition g_c '(x,y) := (g_s x, g_s y).\nDefinition g (P : BSRS) : SRS :=\n  map g_c P.\n\n(* Invariants *)\n\nLemma tau1_g A B : A <<= f B -> tau1 (g A) = g_s (tau1 A).\nProof.\n  induction A as [ | (x,y)]; cbn.\n  - reflexivity.\n  - unfold g in IHA. intros. rewrite !IHA. \n    assert ( x /y el map f_c B) as ((x',y') & ? & ?) % in_map_iff by firstorder; inv H0.\n    rewrite g_s'_app. destruct x'.\n    + cbn. reflexivity.\n    + rewrite f_g_s'_inv. cbn. reflexivity.\n    + firstorder.\nQed.\n\nLemma tau2_g A B : A <<= f B -> tau2 (g A) = g_s (tau2 A).\nProof.\n  induction A as [ | (x,y)]; cbn.\n  - reflexivity.\n  - unfold g in IHA. intros. rewrite !IHA. \n    assert ( x /y el map f_c B) as ((x',y') & ? & ?) % in_map_iff by firstorder; inv H0.\n    rewrite g_s'_app. destruct y'.\n    + cbn. reflexivity.\n    + rewrite f_g_s'_inv. cbn. reflexivity.\n    + firstorder.\nQed.\n\nLemma f_subset B A : A <<= B -> f A <<= f B.\nProof.\n  induction A in B |- *; intros H; cbn.\n  * firstorder.\n  * intros ? [| H0]; subst.\n    -- unfold f. eapply in_map_iff. eauto.\n    -- eapply IHA in H0; eauto.\nQed.\n\nLemma f_g_subset B A : A <<= f B -> g A <<= B.\nProof.\n  revert B; induction A; intros B H; cbn.\n  * firstorder.\n  * assert (a el f B) by firstorder.\n    unfold f in H0. eapply in_map_iff in H0 as ((x,y) & ? & ?). inv H0.\n    intros ? [|]; subst. cbn. now rewrite !f_g_s'_inv. firstorder.\nQed.\n\nLemma PCP_BPCP : PCP ⪯  BPCP.\nProof.\n  exists f. intros B. split.\n  - intros (A & HP & He & H). exists (f A). repeat split.\n    + now eapply f_subset.\n    + destruct A; cbn; congruence.\n    + unfold f, f_c, f_s. setoid_rewrite tau1_f. setoid_rewrite tau2_f. now rewrite H.\n  - intros (A & HP & He & H). exists (g A). repeat split.\n    + eapply f_g_subset; eauto.\n    + destruct A; cbn; congruence.\n    + erewrite tau1_g, tau2_g, H; eauto.\nQed.\n\n     \n\n          \n          \n\n          \n        \n    \n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/coq-library-undecidability/ILL/PCP_BPCP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6684742422621293}}
{"text": "(************************************************************************)\n(* Copyright (c) 2017, Ajay Kumar Eeralla <ae266@mail.missouri.edu>     *)\n(*                     Rohit Chadha <chadhar@missouri.edu>              *)\n(*                                                                      *)\n(* Licensed under the MIT license, see the LICENSE file or              *)\n(* http://en.wikipedia.org/wiki/Mit_license                             *)\n(************************************************************************)\n\n\n(** * Definitions *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Arith.Plus.\nRequire Import Coq.Lists.List .\nRequire Import Le Gt Minus Bool Setoid.\nRequire Import List.\nRequire Import Coq.Lists.ListSet .\nRequire Import Coq.Init.Peano.\nRequire Import Coq.Structures.OrderedTypeEx.\nRequire Import Coq.Arith.Peano_dec.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Coq.Init.Logic.\nRequire Import Coq.NArith.BinNat.\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Classes.SetoidTactics.\nRequire Import Relation_Definitions.\nRequire Import Morphisms.\nRequire Import Setoid.\nRequire Import Program.\nRequire Import Coq.Logic.JMeq.\n\n\n(** Mutually dependent inductive types: [Bool] and [message] \nNote that type [Bool] is different from the built-in type [bool]\n*)\nUnset Elimination Schemes.\nSet Boolean Equality Schemes.\nSet Decidable Equality Schemes.\n\nInductive message : Type :=\n| Mvar : nat -> message\n| O: message\n| acc : message\n| lsk : message\n| lnc : message\n| N: nat -> message\n| if_then_else_M: Bool -> message -> message -> message\n| exp : message -> message -> message -> message\n| pair: message -> message -> message\n| pi1 : message -> message\n| pi2 : message -> message\n| ggen : message -> message \n| rr : message -> message\n| new : message\n| act : message -> message\n| m : message -> message\n| nc : message -> message\n| enc: message -> message -> message->message\n| dec : message-> message -> message\n| to : message -> message\n| k: message -> message\n| sign : message -> message -> message\n| reveal: message -> message\n| i : nat -> message\n| L : message -> message   \n| rs : message -> message\n(** *Foo function symbols *) \n| commit: message -> message -> message -> message\n| open: message -> message -> message -> message\n(** ** Blind signatures *)                                           \n| blind: message -> message -> message\n| unblind: message -> message -> message\n| bsign : message -> message -> message                                   \n| v : message -> message\n| V :nat -> message\n| ok :message\n| f: list message  -> message                                   \nwith Bool : Type :=\n| Bvar: nat -> Bool \n| TRue: Bool\n| FAlse: Bool\n| EQ_B : Bool -> Bool -> Bool\n| EQ_M : message -> message -> Bool\n| if_then_else_B :  Bool -> Bool -> Bool -> Bool\n| EQL : message -> message -> Bool\n| ver : message -> message -> message -> Bool\n| bver : message -> message -> message -> Bool\n| bacc : message -> message -> message -> Bool.\n\nSet Elimination Schemes.\n\nEval compute in message_beq O O.\nEval compute in message_beq (f [N 1;O]) (f [N 1; N 2]).\n\n(** [oursum] *)\n\nInductive oursum : Type:= \n| msg :  message -> oursum\n| bol :  Bool  -> oursum.\n\n(** [ilist]: Polymorphic length-indexed list *)\n\nInductive ilist A : nat -> Type :=\n| Nil : ilist A 0\n| Cons: forall n, A-> ilist A n  -> ilist A (S n).\n\n(** Notations *)\n\nNotation \"x :: l\" := (Cons _ _ x l )(at level 60, right associativity).\nNotation \"[]\" := (Nil _) (at level 1).\nNotation \"[ x ; .. ; y ]\" := (Cons _ _ x ..(Cons _ _ y (Nil _)) ..) .\n  \n(** Decidable [ilist] equality *)\n\nFixpoint ilist_beq {m1 m2} (l1 : ilist oursum m1)( l2: ilist oursum m2) :bool:=\nmatch l1, l2 with\n    | [] , [] => true\n    | Cons n' h1 t1 , Cons m' h2 t2 => if (beq_nat n' m') then  (andb (oursum_beq h1 h2) (ilist_beq t1 t2))\n                                                                  else false\n    | _ , _ => false                          \n  end.\n\nEval compute in ilist_beq [msg O ; msg O] [msg O; msg (N 1)].\n\n(** [mylist]: an [ilist] with type [oursum] *)\n\nDefinition mylist : nat-> Type := ilist oursum.\n\n(** Decidable [mylist] equality *)\n\nFixpoint mylist_beq {m1 m2} (l1: mylist m1) ( l2:mylist m2) :bool:=\n  match l1, l2 with\n    | [] , [] => true\n    | Cons n' h1 t1 , Cons m' h2 t2 => if (beq_nat n' m') then (andb (oursum_beq h1 h2) (mylist_beq t1 t2))\n                                                                 else false\n    | _ , _ => false                          \n  end.\n      \n\n(** [notb] *)\n\nDefinition  notb (b: Bool) := (if_then_else_B b (FAlse) (TRue)).\n\n(* if_then is defined\nDefinition if_then (b:Bool) (t:message) := if_then_else_M b t O.*)\n\n(** [andB] *)\nDefinition andB (b1 b2 :Bool) := if_then_else_B b1 b2 FAlse.\nNotation \" b1 & b2\" := (andB b1 b2 ) (at level 0).\n\n(** Notaions for [pair] *)\n Notation \"( x , y , .. , z )\" := (pair .. (pair x y) .. z) .\nEval compute in (O,O).\n(** [ggen] is randomized algorithm takes name and outputs a pair, group descriptor and generator *)\n(** Group descriptor [G]: proj1 of the pair *)\nDefinition G (n: nat) := (pi1 (ggen (N n))).\n\n(** Group generator [g]: proj2 of the pair *)\nDefinition g( n:nat) := (pi2 (ggen (N n))).\n\n(** [k] acts as key generation algorithm that take agent name and output a [pair] of public and private keys *)\nDefinition pk (a:message) := (pi1 (k a)).\nDefinition sk (a:message) := (pi2 (k a)).\n\n(** [rr] represents randomness *)\nDefinition r (n:nat) := (rr (N n)).\n\n(** Check if a term of oursum starts with [bol] constructor *)\n\nDefinition chkbol_os (a : oursum) : bool  :=\nmatch a with\n| bol a' => true\n| msg a' => false\nend.\n\n(** Check if a term of [oursum] starts with [msg] constructor *)\n\nDefinition chkmsg_os (a : oursum) : bool  :=\nmatch a with\n| bol a' => false\n| msg a' => true\nend.\n\n(** Get [Bool] term out of an [oursum] term *)\n\nDefinition ostobol (a :oursum) : Bool :=\n match a with\n| bol a' => a'\n| msg a' => TRue\nend. \n\n(** Get [msg] term out of an [oursum] term *)\n          \nDefinition ostomsg (a : oursum) : message :=\nmatch a with\n| bol a' => O\n| msg a' => a'\nend.\n\n\n(** [ilist message n] --> [mylist n] *)\n\nFixpoint conv_mlist_mylist {n:nat} (ml : ilist message n) : mylist n :=\n\nmatch ml with\n| Nil => []\n| a :: h => msg a :: (conv_mlist_mylist h)\nend.\n\n(** [ilist Bool n] --> [mylist n] *)\n\n\nFixpoint conv_blist_mylist {n:nat} (ml : ilist Bool n) : mylist n :=\nmatch ml with\n| Nil => []\n| a :: h => bol a :: (conv_blist_mylist h)\nend.\n\n(** [list message] --> [mylist (length l)] *)\n\nFixpoint conv_listm_mylist ( l :  list message) : mylist (length l) :=\nmatch l with\n| nil => []\n| cons a h => msg a :: (conv_listm_mylist h)\nend.\n\n(** [mylist n] --> [list messge] *)\n\nFixpoint conv_mylist_listm {n:nat} (osl: mylist n) : list message :=\nmatch osl with\n| [] => nil\n| a :: h => cons  (if (chkmsg_os a) then (ostomsg a) else O) (conv_mylist_listm h)\n \nend.\n\n(** [mylist n] --> [list oursum] *)\n\nFixpoint conv_mylist_listos {n:nat} (osl:mylist n) :list oursum :=\nmatch osl with \n| [] => nil\n| a :: h => (cons a (conv_mylist_listos h ) )\nend.\n\n(** [mylist n] --> [ilist Bool n] *)\n\nFixpoint conv_mylist_listb {n:nat} (osl: mylist n) : ilist Bool n :=\nmatch osl with\n| [] => @Nil Bool\n| a :: h => Cons _ _ (if (chkbol_os a) then (ostobol a) else TRue) (conv_mylist_listb h)\nend.\n\n(** [list oursum] --> [mylist (length l)] *)\n\nFixpoint conv_listos_mylist (l : list oursum) : (mylist (length l)) :=\nmatch l with\n| nil => []\n| cons h t => h:: (conv_listos_mylist t)\nend.\n\n(** [Sublist] *)\n\nDefinition sublist {A:Type} (n m:nat) (l:list A) :=\n  skipn n (firstn m l).\n \n(** Substitution: x <- s in t, where x, s, and t are [Bool] or [message] *)\n\nReserved Notation \"'[[' x ':=' s ']]' t\" (at level 0).\nReserved Notation \"'{{' x ':=' s '}}' t\" (at level 0).\n\nFixpoint submsg_bol (n : nat )(s:message) (b:Bool) : Bool :=\n  match b with\n    | EQ_B  b1 b2 =>  EQ_B  ([[n:= s]]b1) ([[n:= s]] b2)\n    | EQ_M t1 t2 => EQ_M ( {{n:= s }} t1) ( {{ n:=s }} t2)\n    | if_then_else_B t1 t2 t3 => if_then_else_B  ([[n:=s]]t1) ( [[n:=s]] t2) ( [[n:=s]]t3) \n    | EQL t1 t2 => EQL ( {{ n := s }} t1) ( {{ n:=s }} t2)\n    | ver t1 t2 t3 => ver ({{n:=s}}t1) ({{n:=s}}t2) ({{n:=s}}t3)\n    | bver t1 t2 t3 => bver ({{n:=s}}t1) ({{n:=s}}t2) ({{n:=s}}t3)\n    | bacc t1 t2 t3 =>  bacc ({{n:=s}}t1) ({{n:=s}}t2) ({{n:=s}}t3)\n    | _ => b\n  end\n    where \"'[[' x ':=' s ']]' t\" := (submsg_bol x s t)\nwith submsg_msg (n : nat )(s:message) (t:message) : message :=\n       match t with \n         | if_then_else_M b3 t1 t2 => if_then_else_M ([[n:=s]] b3) ({{n:=s}} t1) ({{n:=s}} t2)\n         | (Mvar n') =>  if (beq_nat n' n) then s else t\n         | exp t1 t2 t3 => exp ( {{ n :=s }} t1) ( {{ n:=s }} t2) ( {{ n:=s }} t3)\n         | pair t1 t2 => pair ( {{ n:=s }} t1) ( {{ n:=s }} t2)\n         | pi1 t1 => pi1 ( {{ n:=s }} t1) \n         | pi2 t1 => pi2 ( {{ n:=s }} t1) \n         | ggen t1 => ggen ( {{ n:=s }} t1)\n         | act t1 => act( {{ n:=s }} t1)\n         | rr t1 => rr ({{ n:=s}}t1)\n         | rs t1 => rs ({{n:=s}} t1)\n         | L t1 => L ({{ n:=s}}t1)\n         | m t1 => m ( {{ n:=s }} t1)\n         | enc t1 t2 t3 =>  enc ( {{ n :=s }} t1) ( {{ n:=s }} t2) ( {{ n:=s }} t3)\n         | dec t1 t2 => dec ( {{ n:=s }} t1) ( {{ n:=s }} t2)\n         | k t1 => k ( {{ n:=s }} t1) \n         | nc t => nc  ( {{ n:=s }} t) \n         | to t1 => to  ( {{ n:=s }} t1) \n         | reveal t1 => reveal ( {{ n:=s }} t1)\n         | sign t1 t2 => sign ({{n:=s}}t1) ({{n:=s}}t2)\n         | f l =>  (f (@map message message  (submsg_msg n s) l))\n         (** foo function symbol *)\n         | commit t1 t2 t3 => commit ({{n:=s}}t1) ({{n:=s}}t2) ({{n:=s}}t3)\n         | open t1 t2 t3 => open ({{n:=s}}t1) ({{n:=s}}t2) ({{n:=s}}t3)\n         | blind t1 t2 => blind ({{n:=s}}t1) ({{n:=s}}t2)\n         | unblind t1 t2 => unblind ({{n:=s}}t1) ({{n:=s}}t2)\n         | bsign t1 t2 => bsign ({{n:=s}}t1) ({{n:=s}}t2)                    \n         | _ => t\n       end\n         where \"'{{' x ':=' s '}}' t\" := (submsg_msg x s t).\n\n(** Substitution: x <- s in t, x is of type variable, t is of [oursum] *)\n\nDefinition submsg_os (n:nat)(s:message) (t:oursum):oursum :=\nmatch t with \n| msg t1 =>  msg ({{n := s}} t1)\n| bol b1 =>  bol ( [[n := s]] b1)\nend.\n\n(** Substitution in [ilist message n'] *)\n\nFixpoint submsg_mlist  {n' :nat} (n:nat)(s:message)(l : ilist message n') : ilist message n' :=\nmatch l with \n| [] => []\n| h::t  =>  ({{n := s}} h) :: (submsg_mlist n s t )\nend.\nEval compute in (submsg_msg 1 O  (f [ (Mvar 1) ; (N 2) ; (N 1)])).\nEval compute in  ( {{ 1 := O }} (N 1) ).\n\n\n(** Substitutions for [Bool] variable in [Bool] and [message] *)\n\nReserved Notation \"'[' x ':=' s ']' t\" (at level 0).\nReserved Notation \"'(' x ':=' s ')' t\" (at level 0).\n\nFixpoint subbol_bol (n : nat )(s:Bool) (b:Bool) : Bool :=\n  match b with \n    | Bvar n' =>  if (beq_nat n' n) then s else b\n    | EQ_B  b1 b2 =>  EQ_B  ([n:=s] b1) ([n:=s] b2)\n    | EQ_M t1 t2 => EQ_M ((n:= s)t1) ((n:=s) t2)\n    | if_then_else_B t1 t2 t3 => if_then_else_B  ([n:=s] t1) ([n:=s] t2) ([n:=s] t3)\n    | EQL t1 t2 => EQL ((n:=s) t1) ((n:=s) t2)\n    | ver t1 t2 t3 => ver ((n:=s)t1) ((n:=s)t2) ((n:=s)t3)\n    | bver t1 t2 t3 => bver ((n:=s)t1) ((n:=s)t2) ((n:=s)t3)\n    | bacc t1 t2 t3 => bacc ((n:=s)t1) ((n:=s)t2) ((n:=s)t3)\n    | _ => b\n  end\n    where \"'[' x ':=' s ']' t\" := (subbol_bol x s t)\nwith subbol_msg (n : nat )(s:Bool) (t:message) : message :=\n       match t with \n         | if_then_else_M b3 t1 t2 => if_then_else_M ([n:=s] b3) ((n:=s)t1) ( (n:=s)t2)\n         | exp t1 t2 t3 => exp (( n:=s ) t1) (( n:=s) t2) (( n:=s ) t3)\n         | pair t1 t2 => pair (( n:=s ) t1) (( n:=s) t2)\n         | pi1 t1 => pi1 (( n:=s ) t1) \n         | pi2 t1 => pi2 (( n:=s ) t1) \n         | ggen t1 => ggen (( n:=s ) t1)\n         | act t1 => act(( n:=s ) t1)\n         | rr t1 => rr ((n:=s) t1)\n         | rs t1 => rs ((n:=s) t1)\n         | L t1 => L ((n:=s) t1)\n         | m t1 => m (( n:=s ) t1)\n         | enc t1 t2 t3 => enc (( n:=s ) t1) (( n:=s) t2) (( n:=s ) t3)\n         | dec t1 t2 => dec  (( n:=s ) t1) (( n:=s) t2) \n         | k t1 => k (( n:=s ) t1)\n         | nc t1 =>  nc (( n:=s ) t1)\n         | to t1 => to (( n:=s ) t1)\n         | reveal t1 => reveal (( n:=s ) t1)\n         | sign t1 t2 => sign ((n:=s)t1) ((n:=s)t2)\n         | f l => (f (@map message message (subbol_msg n s) l))\n         (** foo function symbol *)\n         | commit t1 t2 t3 => commit ((n:=s)t1) ((n:=s)t2) ((n:=s)t3)\n         | open t1 t2 t3 => open ((n:=s)t1) ((n:=s)t2) ((n:=s)t3)\n         | blind t1 t2 => blind ((n:=s)t1) ((n:=s)t2)\n         | unblind t1 t2 => unblind ((n:=s)t1) ((n:=s)t2)\n         | bsign t1 t2 => bsign ((n:=s)t1) ((n:=s)t2)                            \n         | v t1 => v ((n:=s) t1)\n         | _ => t\n       end\n         where \"'(' x ':=' s ')' t\" := (subbol_msg x s t).\n\n(** Substitution for [Bool] variable in a term of type [oursum] *)\n\nDefinition  subbol_os (n:nat)(s:Bool) (t:oursum):oursum :=\n  match t with \n    |msg t1 =>  msg ((n := s) t1)\n    |bol b1 =>  bol ( [n := s] b1)\n  end.\n\n(** Testing properties on list elements*)\n\nFixpoint test_list {X:Type} (test: X -> bool) (l:list X): bool := \n  match l with\n    | nil => true\n    | cons h t => if (test h) then (test_list test t) else false\n  end.\n  \n(** Check if a term is ground *)\n\nFixpoint clos_bol (b :Bool):bool:=\n  match b with \n    | Bvar n' =>  false\n    | EQ_B  b1 b2 =>  (andb (clos_bol b1) (clos_bol b2))\n    | EQ_M t1 t2 => (andb (clos_msg t1) (clos_msg t2))\n    | if_then_else_B b t1 t2 =>  andb (clos_bol b) (andb (clos_bol t1) (clos_bol t2))\n    | EQL t1 t2 => (andb (clos_msg t1) (clos_msg t2))\n    | ver t1 t2 t3 => (andb (andb (clos_msg t1) (clos_msg t2)) (clos_msg t3))\n    | bver t1 t2 t3 => (andb (andb (clos_msg t1) (clos_msg t2)) (clos_msg t3))\n    | bacc t1 t2 t3 => (andb (andb (clos_msg t1) (clos_msg t2)) (clos_msg t3))\n    | _ => true                     \n  end\nwith clos_msg (t:message) : bool:=\n       match t with \n         | if_then_else_M b t1 t2 => andb (clos_bol b) (andb (clos_msg t1) (clos_msg t2))\n         | (Mvar n') => false\n         | exp t1 t2 t3 => andb (clos_msg t1) (andb (clos_msg t2) (clos_msg t3))\n         | pair t1 t2 => (andb (clos_msg t1) (clos_msg t2))\n         | pi1 t1 => (clos_msg t1) \n         | pi2 t1 => (clos_msg t1) \n         | ggen t1 => (clos_msg t1) \n         | act t1 => (clos_msg t1) \n         | rr t1 => (clos_msg t1)\n         | rs t1 => (clos_msg t1)\n         | L t1 => (clos_msg t1)           \n         | m t1 =>  (clos_msg t1) \n         | enc t1 t2 t3 => andb (clos_msg t1) (andb (clos_msg t2) (clos_msg t3))\n         | dec t1 t2 =>(andb (clos_msg t1) (clos_msg t2))\n         | k t1 => (clos_msg t1) \n         | nc t1 => (clos_msg t1) \n         | to t1 => (clos_msg t1)\n         | reveal t1 => (clos_msg t1)\n         | sign t1 t2 => (andb (clos_msg t1) (clos_msg t2))\n         | f l => (@forallb message clos_msg l) \n         (** foo function symbol *)\n         | commit t1 t2 t3 =>  andb (clos_msg t1) (andb (clos_msg t2) (clos_msg t3))\n         | open t1 t2 t3 =>  andb (clos_msg t1) (andb (clos_msg t2) (clos_msg t3))\n         | blind t1 t2 =>  (andb (clos_msg t1) (clos_msg t2))\n         | unblind t1 t2 =>  (andb (clos_msg t1) (clos_msg t2))\n         | bsign t1 t2 => (andb (clos_msg t1) (clos_msg t2))\n         | v t1 => (clos_msg t1)\n         | _ => true\n       end.\n\n\n(** Check if a term of type of [oursum] is closed *)\n\nDefinition clos_os (t:oursum): bool :=\n  match t with \n    | msg t1 =>  clos_msg (t1)\n    | bol b1 =>  clos_bol (b1)\n  end. \n\n(** Check if every element of [message] list is closed *)\n\nFixpoint clos_listm (l: list message):bool:=\n  match l with \n    | nil=> true\n    | cons  h t => (andb (clos_msg h) (clos_listm t))\n  end.\n\n(** Check if every element of [Bool] list is closed *)\n\nFixpoint clos_listb (l: list Bool ):bool:=\n  match l with \n    | nil=> true\n    | cons h t => (andb (clos_bol h) (clos_listb t))\n  end.\n\n(** Check if [mylist] is closed *)\n\nFixpoint clos_mylist {n:nat} (l: mylist n):bool :=\n  match l with \n    | Nil => true\n    | h :: t => (andb (clos_os h) (clos_mylist t))\n  end.\n\n(** Check if a variable occure in a term of type [message] or [Bool] *)\n\nFixpoint var_free_bol (n : nat )(t:Bool) : bool :=\n  match t with \n    | Bvar n' => if (beq_nat n' n) then true else false\n    | EQ_B  b1 b2 =>  orb (var_free_bol n b1)  ( var_free_bol n b2)\n    | EQ_M t1 t2 => orb (var_free_msg n t1) ( var_free_msg n t2)\n    | if_then_else_B t1 t2 t3 => orb ( var_free_bol n t1)  (orb (var_free_bol n t2)(var_free_bol n t3) )\n    | EQL t1 t2 => orb ( var_free_msg n t1) ( var_free_msg n t2)\n    | ver t1 t2 t3 => (orb  (orb (var_free_msg n t1) (var_free_msg n t2)) (var_free_msg n t3))\n    | bver t1 t2 t3 => (orb  (orb (var_free_msg n t1) (var_free_msg n t2)) (var_free_msg n t3))\n    | bacc t1 t2 t3 => (orb  (orb (var_free_msg n t1) (var_free_msg n t2)) (var_free_msg n t3))\n    | _ => true\n  end\nwith var_free_msg (n : nat )(t:message) : bool :=\n       match t with \n         | if_then_else_M b3 t1 t2 => orb (var_free_bol n b3) (orb ( var_free_msg n  t1)( var_free_msg n t2))\n         | (Mvar n') => if (beq_nat n' n) then true else false\n         | exp t1 t2 t3 => orb ( var_free_msg n t1) (orb ( var_free_msg n t2) ( var_free_msg n t3))\n         | pair t1 t2 => orb(var_free_msg n t1) ( var_free_msg n t2)\n         | pi1 t1 => ( var_free_msg n t1)\n         | pi2 t1 => (var_free_msg n t1)\n         | ggen t1 => (var_free_msg n t1)\n         | act t1 => ( var_free_msg n t1)\n         | rr t1 => (var_free_msg n t1)\n         | rs t1 => (var_free_msg n t1)\n         | L t1 => (var_free_msg n t1)\n         | m t1 => ( var_free_msg n t1)\n         | enc t1 t2 t3 =>  orb (var_free_msg n t1) (orb ( var_free_msg n t2) ( var_free_msg n t3))\n         | dec t1 t2 => orb( var_free_msg n t1) (var_free_msg n t2)\n         | k t1 => (var_free_msg n t1)\n         | nc t1  => (var_free_msg n t1)\n         | to t1 => (var_free_msg n t1) \n         | reveal t1 => (var_free_msg n t1)\n         | sign t1 t2 => (orb (var_free_msg n t1) (var_free_msg n t2))\n         | f l => (@forallb message (var_free_msg n) l)\n         (** foo function symbol *)  \n         | commit t1 t2 t3 =>  orb (var_free_msg n t1) (orb (var_free_msg n t2) (var_free_msg n t3))\n         | open t1 t2 t3 =>   orb (var_free_msg n t1) (orb (var_free_msg n t2) (var_free_msg n t3))\n         | blind t1 t2 =>  orb (var_free_msg n t1) (var_free_msg n t2)\n         | unblind t1 t2 =>  orb (var_free_msg n t1) (var_free_msg n t2)\n         | bsign t1 t2 => (orb (var_free_msg n t1) (var_free_msg n t2))                        \n         | v t1 => (var_free_msg n t1)\n         | _ => true\n       end.            \n\n\n(** Check if a variable occur in a term of type [oursum] *)\n\nDefinition var_free_os (n:nat) (t:oursum) : bool :=\n  match t with\n    | msg t1 => (var_free_msg n t1)\n    | bol b1 => (var_free_bol n b1)\n  end.\n\n(** Check if [mylist] contain a variable in one of the element *)\n\nFixpoint var_free_mylist (n:nat) {m} (l:mylist m) : bool :=\n  match l with\n    | [] => false\n    | h :: t => (orb (var_free_os n h) (var_free_mylist n t))\n  end.\n\n(** Concatenation of two mylists *)\n\nFixpoint app_mylist {n1} {n2}  (ml1 : mylist n1) (ml2 : mylist n2) : mylist (plus n1 n2) :=\n  match ml1 in (ilist _ n1) return (ilist _ (n1 + n2)) with\n    | [] => ml2\n    | Cons n1 x ml3 => Cons _ _ x (app_mylist ml3  ml2 )\n  end.\nNotation \"ml1 ++ ml2 \" := (app_mylist  ml1 ml2) (at level 60, right associativity).\n\nEval compute in message_beq (Mvar 2) (Mvar 3).\n \n(** Check for absence of a variable *)\n\nFixpoint notoccur_bol (n : nat )(t:Bool) : bool :=\n  match t with \n    | EQ_B  b1 b2 =>  andb (notoccur_bol n b1)  (notoccur_bol n b2)\n    | EQ_M t1 t2 => andb (notoccur_msg n t1) ( notoccur_msg n t2)\n    | if_then_else_B t1 t2 t3 => andb ( notoccur_bol n t1)  (andb (notoccur_bol n t2)(notoccur_bol n t3) )\n    | EQL t1 t2 => andb ( notoccur_msg n t1) ( notoccur_msg n t2)\n    | ver t1 t2 t3 => (andb  (andb (notoccur_msg n t1) (notoccur_msg n t2)) (notoccur_msg n t3))\n    | bver t1 t2 t3 => (andb  (andb (notoccur_msg n t1) (notoccur_msg n t2)) (notoccur_msg n t3))\n    | bacc t1 t2 t3 => (andb  (andb (notoccur_msg n t1) (notoccur_msg n t2)) (notoccur_msg n t3))\n    | _ => true                     \n  end\nwith notoccur_msg (n : nat )(t:message) : bool :=\n       match t with \n         | if_then_else_M b3 t1 t2 => andb (notoccur_bol n b3) (andb ( notoccur_msg n  t1)( notoccur_msg n t2))\n         | N n'=> if (beq_nat n' n) then false else true\n         | exp t1 t2 t3 =>  (andb ( notoccur_msg n t1) (andb ( notoccur_msg n t2) ( notoccur_msg n t3)))\n         | pair t1 t2 => andb( notoccur_msg n t1) ( notoccur_msg n t2)\n         | pi1 t1 => ( notoccur_msg n t1)\n         | pi2 t1 => ( notoccur_msg n t1)\n         | ggen t1 => ( notoccur_msg n t1)\n         | act t1 => ( notoccur_msg n t1)\n         | rr t1 => ( notoccur_msg n t1)\n         | rs t1 => (notoccur_msg n t1)\n         | L t1 => (notoccur_msg n t1)\n         | m t1 => ( notoccur_msg n t1)\n         | enc t1 t2 t3 =>  andb ( notoccur_msg n t1) (andb ( notoccur_msg n t2) ( notoccur_msg n t3))\n         | dec t1 t2 => andb( notoccur_msg n t1) ( notoccur_msg n t2)\n         | k t1 => ( notoccur_msg n t1)\n         | nc t1 =>  ( notoccur_msg n t1)\n         | to t1 => (notoccur_msg n t1) \n         | reveal t1 => (notoccur_msg n t1)\n         | sign t1 t2 => (andb (notoccur_msg n t1) (notoccur_msg n t2))\n         | f l => (@forallb message (notoccur_msg n) l) \n         (** foo function symbol *)  \n         | commit t1 t2 t3 =>  orb (notoccur_msg n t1) (orb (notoccur_msg n t2) (notoccur_msg n t3))\n         | open t1 t2 t3 =>  orb (notoccur_msg n t1) (orb (notoccur_msg n t2) (notoccur_msg n t3))\n         | blind t1 t2 =>  orb (notoccur_msg n t1) (notoccur_msg n t2)\n         | unblind t1 t2 =>  orb (notoccur_msg n t1) (notoccur_msg n t2)\n         | bsign t1 t2 => (andb (notoccur_msg n t1) (notoccur_msg n t2))                        \n         | v t1 => (notoccur_msg n t1)\n         | _ => true               \n       end.            \nEval compute in (notoccur_msg 1 (pi2 (N 2))).\n\n(** Check if absence of a variable in a term of [oursum] *)\n\nDefinition  notoccur_os (n:nat)(t:oursum): bool :=\n  match t with \n  | bol b => notoccur_bol n b \n  | msg t => notoccur_msg n t\n  end.\n\n(** Check if absence of a variable in [ilist] *)\n\nFixpoint notoccur_mlist (x:nat) {n} (ml : ilist message n):bool :=\n  match ml with\n    | [] => true\n    | h:: ml1 => (andb (notoccur_msg x h) (notoccur_mlist x ml1))\n  end.\n\n(** Check if absence of a variable in [ilist] *)\n\nFixpoint notoccur_blist {m:nat}(x:nat) (ml : ilist Bool m):bool :=\n  match ml with\n    | [] => true\n    | h :: ml1 => (andb (notoccur_bol x h) (notoccur_blist x ml1))\n  end.\n\n(** Check if absence of a variable in [mylist] *)\n\nFixpoint notoccur_mylist {m:nat}(x:nat) (ml :  mylist m):bool :=\n  match ml with\n    | [] => true\n    | h :: ml1 => (andb (notoccur_os x h) (notoccur_mylist x ml1))\n  end.\n\n(** Number of occurences of an element in [ilist] *)\n\nFixpoint count_occur {n:nat} (x : nat)(l : ilist nat n) : nat :=\n  match l with\n    | [] => 0\n    | y::t =>  if (beq_nat y x) then S (count_occur x t) else (count_occur x t)\n  end.\nEval compute in (count_occur 1 [1;1;1]).\n\n(** Check if no redundancies in [ilist] *)\n\nFixpoint nodup_ilist {n:nat}(l:ilist nat n): bool :=\n  match l with\n    |Nil => true\n    | h::t => let x := (count_occur h (h::t) ) in\n              match (beq_nat x 1) with\n                | true => (andb true (nodup_ilist t)) \n                | false => false\n              end\n  end.\n\nEval compute in (nodup_ilist [1;1]).\nEval compute in (nodup_ilist [1;2;3]).\n\n(** Check if each element in [ilist nat n] occurs in [ilist message m] *)\n\nFixpoint notocclist_mlist {n:nat} (nl:ilist nat n){m}(ml:ilist message m): bool :=\n  match nl with\n    | [] => true\n    | h::t=> (andb (notoccur_mlist h ml) (notocclist_mlist t ml))\n  end.\n\nEval compute in (notoccur_mlist 1 [(N 2);(N 4)]).\nEval compute in True \\/ False.\n\n(** Check if each element in (ilist nat n) occurs in (mylist m) *)\n\nFixpoint notocclist_mylist {n:nat} {m:nat}(nl:ilist nat n)(ml: mylist m): bool :=\nmatch nl with\n|[] => true\n| h::t=> (andb (notoccur_mylist h ml) (notocclist_mylist t ml))\nend.\nEval compute in (notoccur_mylist 1 [msg (N 2); msg (N 4)]).\n\n(** Check if an element occurs in [ilist] *)\n\n Fixpoint notoccur_nlist {n:nat}(a:nat) (l:ilist nat n) : bool :=\n    match l with\n      | Nil => true\n      | h::t =>   if (beq_nat h a) then false else (andb true (notoccur_nlist a t) )\n    end.\nEval compute in (notoccur_nlist 1 [2;3;1]).\nEval compute in (S (pred 1)).\n\n(** Function [Fresh] to check if the list of numbers are freshly generated numbers *)\n\nDefinition Fresh {n:nat}{m:nat} (nl : ilist nat n)(ml : mylist m): bool :=\n  match nl with \n    | [] => true\n    | [a] => (notoccur_mylist a ml) \n    | l => (andb (nodup_ilist l) (notocclist_mylist l ml) )\n  end. \n\n(** Check if an [exp term (exp (G n) (g n) (r n1))] occurs in a term *)\n(** Check if a term t of type message occurs in a term of either [message] or [Bool] type *)\n\nFixpoint checkmtbol (t:message) (b:Bool) : bool :=\n  match b with \n    | EQ_B  b1 b2 =>  orb (checkmtbol t b1)  (checkmtbol t b2)\n    | EQ_M t1 t2 => orb (checkmtmsg t t1) ( checkmtmsg t t2)\n    | if_then_else_B t1 t2 t3 => orb ( checkmtbol t t1)  (orb (checkmtbol t t2)(checkmtbol t t3) )\n    | EQL t1 t2 => orb ( checkmtmsg t t1) ( checkmtmsg t t2)\n    | ver t1 t2 t3 => (orb  (orb (checkmtmsg t t1) (checkmtmsg t t2)) (checkmtmsg t t3))\n    | bver t1 t2 t3 => (orb  (orb (checkmtmsg t t1) (checkmtmsg t t2)) (checkmtmsg t t3))\n    | bacc t1 t2 t3 => (orb  (orb (checkmtmsg t t1) (checkmtmsg t t2)) (checkmtmsg t t3))\n    | _ => false\n  end\nwith checkmtmsg (t:message) (t':message) : bool :=\n       if (message_beq t t') then true else\n         match t' with\n           | if_then_else_M b3 t1 t2 => orb (checkmtbol t b3) (orb ( checkmtmsg t  t1)( checkmtmsg t t2))\n           | exp t1 t2 t3 =>  (orb (checkmtmsg t t1) (orb (checkmtmsg t t2) (checkmtmsg t t3)))\n           | pair t1 t2 => orb( checkmtmsg t t1) ( checkmtmsg t t2)\n           | pi1 t1 => ( checkmtmsg t t1)\n           | pi2 t1 => ( checkmtmsg t t1)\n           | ggen t1 => ( checkmtmsg t t1)\n           | act t1 => ( checkmtmsg t t1)\n           | rr t1 => ( checkmtmsg t t1)\n           | rs t1 => (checkmtmsg t t1)\n           | L t1 => (checkmtmsg t t1)\n           | m t1 => ( checkmtmsg t t1)\n           | enc t1 t2 t3 =>  orb ( checkmtmsg t t1) (orb ( checkmtmsg t t2) ( checkmtmsg t t3))\n           | dec t1 t2 => orb( checkmtmsg t t1) ( checkmtmsg t t2)\n           | k t1 => ( checkmtmsg t t1)\n           | nc t1 =>( checkmtmsg t t1)\n           | to t1 => (checkmtmsg t t1) \n           | reveal t1 => (checkmtmsg t t1)\n           | sign t1 t2 => (orb (checkmtmsg t t1) (checkmtmsg t t2))\n           | f l => (@existsb message (checkmtmsg t) l)\n           (** foo function symbol *)  \n           | commit t1 t2 t3 =>  orb (checkmtmsg t t1) (orb (checkmtmsg t t2) (checkmtmsg t t3))\n           | open t1 t2 t3 =>  orb (checkmtmsg t t1) (orb (checkmtmsg t t2) (checkmtmsg t t3))\n           | blind t1 t2 =>  orb (checkmtmsg t t1) (checkmtmsg t t2)\n           | unblind t1 t2 =>  orb (checkmtmsg t t1) (checkmtmsg t t2)\n           | bsign t1 t2 => (orb (checkmtmsg t t1) (checkmtmsg t t2))                        \n           | v t1 => (checkmtmsg t t1)\n           | _ => false\n         end.            \n          \n \n\n(** Check for given term [(exp (G n) (g n) (r n1))] occurs in [oursum] *)\n(** Check if a message term occurs in a term of [oursum] *)\n\nDefinition checkmtos (t:message) (t':oursum): bool :=\n  match t' with \n    |bol b => checkmtbol t b \n    |msg t'' => checkmtmsg t t''\n  end.\n\n\n(** Check for [exp] term in a term of type [list message] *)\n\nFixpoint checkmtlism (t:message) (l: list message):bool :=\n  match l with\n    | nil => true\n    |  cons h t' => (orb (checkmtmsg t h) (checkmtlism t t'))\n  end.\n\n(** Check for [exp] term in a term of type [mylist] *)\n\nFixpoint checkmtmylis (t:message) {m} (l: mylist m):bool :=\n  match l with\n    | [] => true\n    |  h::t' => (orb (checkmtos t h) (checkmtmylis t t'))\n  end.\n\n(** Get an element at a [pos] in [mylist] *)\n\nFixpoint getelt_at_pos (p :nat) {m}   (ml : mylist m ) : oursum :=\n  match (leb p m), p with \n    | false, _  => msg O\n    | true, 0 => msg O\n    | true, 1  => match ml with \n                    | [] => msg O\n                    | h :: t => h\n                  end\n    | true,  (S n') => match ml with\n                         | [] => (msg O)\n                         | h :: t => (getelt_at_pos n' t)\n                       end\n  end.\n\n        \n(** Get an element at a [pos] in [ilist] *)\n\nFixpoint getelt_ml {m}  (p :nat) (ml : ilist message m) : message :=\n  match p with \n    | 0 => O\n    | 1 => match ml with  \n             | [] => O\n             | h :: t => h\n           end\n    | (S n') => match ml with\n                  | Nil => O\n                  | h :: t => (getelt_ml   n' t)\n                end\n  end.\n\n(** Appending an element to [mylist] at front *)\n\nFixpoint app_elt_front (x:oursum) {n} (ml: mylist n) : mylist ( S n):=\n  match ml with\n    | [] => [x]\n    | ml3 => (app_mylist [x] ml3)\n  end.\nNotation \" x +++ m1 \" := (app_elt_front x m1)(at level 0, right associativity).\nEval compute in getelt_at_pos  2 [bol (Bvar 1) ; bol (Bvar 2); msg (N 1); msg (N 2); msg (N 3)].\n\n\n(** Appending an element of [mylist] at rear *)\n\nFixpoint app_elt_last (x:oursum) {n} (ml: mylist n) : mylist ( S n):=\n  match ml with\n    | [] => [x]\n    | h::ml3 => h :: (app_elt_last x ml3)\n  end.\n\n(** Reversing [mylist] *)\n\nFixpoint reverse {n}(ml: mylist n) : mylist n :=\n  match ml with\n    | [] => []\n    | x :: ml' => (app_elt_last x (reverse ml') )\n  end.\n\n(** Insert an element at given position *)\n\nFixpoint insert_at_pos (p:nat) (x:oursum) {n} (l:mylist n) : mylist (S n) :=\n  match (leb p n) , p with\n    | false, _ => (app_elt_last (msg O) l)\n    | true, 0  =>  (app_elt_last (msg O) l)\n    | true, 1 => (app_elt_front x l)\n    | true , (S n') => match l with\n                         | [] => [x]\n                         | h :: t => (app_mylist [h] (insert_at_pos n' x t))\n                       end\n  end.\n\nEval compute in (insert_at_pos 5 (msg O) [msg O; msg new ; msg acc; msg O]).\n\n(** Check if the term at [pos] is [Bool] *)\n\nDefinition chkbol_at_pos  {m} (n :nat) (ml :mylist m) : bool := (chkbol_os (getelt_at_pos  n ml)).\n\n(** Check if the term at [pos] is [message] *) \n\nDefinition chkmsg_at_pos {m} (n :nat) (ml :mylist m) : bool := (chkmsg_os (getelt_at_pos n ml)).\n\n\n(** Negating an element at given [pos] in [mylist] *)\n\nDefinition neg_at_pos {m}   (p:nat ) (ml : mylist m) : mylist 1 :=\nmatch  (chkbol_os (getelt_at_pos p ml)) with\n| true => [bol (notb (ostobol (getelt_at_pos p ml)))]\n| false =>  [(getelt_at_pos p ml)]\nend .\n\nEval compute in neg_at_pos  2  [bol (Bvar 1) ; bol (Bvar 2); msg (N 1); msg (N 2); msg (N 3)].\n\n(** Pairing two elements from [mylist] *)\n\nDefinition pair_at_pos {m}  (p1 p2 : nat) (ml : mylist m) : message :=\n  match (chkmsg_os (getelt_at_pos  p1 ml)) with\n    | true => match (chkmsg_os (getelt_at_pos  p2 ml)) with\n                | true => (pair (ostomsg (getelt_at_pos  p1 ml)) (ostomsg (getelt_at_pos  p2 ml)))\n                | false => (pair (ostomsg  (getelt_at_pos  p1 ml)) O)\n              end\n    | false => match (chkmsg_os (getelt_at_pos  p2 ml)) with\n                 | true => (pair O (ostomsg (getelt_at_pos  p2 ml)))\n                 | false => (pair O O)\n               end\n  end.\n\n\n(** Constructing [exp] term with three terms at positions p1, p2, and p3 in [mylist] *)\n\nDefinition exp_at_pos {m} (p1 p2 p3 :nat) (ml :mylist m) : message :=\n  match (chkmsg_os (getelt_at_pos  p1 ml)) with\n    | true => match (chkmsg_os (getelt_at_pos  p2 ml)) with\n                | true =>  match (chkmsg_os (getelt_at_pos  p3 ml)) with\n                             | true => (exp (ostomsg (getelt_at_pos p1 ml)) (ostomsg (getelt_at_pos  p2 ml))  (ostomsg (getelt_at_pos  p3 ml)) )        \n                             | flase => (exp (ostomsg (getelt_at_pos  p1 ml)) (ostomsg (getelt_at_pos  p2 ml))   O )        \n                           end\n                | false =>   match (chkmsg_os (getelt_at_pos  p3 ml)) with\n                               | true => (exp (ostomsg (getelt_at_pos  p1 ml)) O (ostomsg (getelt_at_pos  p3 ml)) )        \n                               | flase => (exp (ostomsg (getelt_at_pos  p1 ml)) O   O )        \n                             end\n              end \n    | false =>  match (chkmsg_os (getelt_at_pos  p2 ml)) with\n                  | true =>  match (chkmsg_os (getelt_at_pos  p3 ml)) with\n                               | true => (exp O (ostomsg (getelt_at_pos  p2 ml))  (ostomsg (getelt_at_pos  p3 ml)) )        \n                               | flase => (exp O (ostomsg (getelt_at_pos  p2 ml))   O )        \n                             end\n                  | false =>   match (chkmsg_os (getelt_at_pos  p3 ml)) with\n                                 | true => (exp O O (ostomsg (getelt_at_pos  p3 ml)) )        \n                                 | flase => (exp O  O   O )        \n                               end\n                end \n  end.\n\nEval compute in exp_at_pos  3 4 4  [bol (Bvar 1) ; bol (Bvar 2); msg (N 1); msg (N 2); msg (N 3)].\n\n(** Constructing a [EQ_M] term in with the elements in [mylist] *)\n\nDefinition EQ_M_at_pos {m}  (p1 p2 : nat) (ml : mylist m) : Bool :=\n  match (chkmsg_os (getelt_at_pos  p1 ml)) with\n    | true => match (chkmsg_os (getelt_at_pos  p2 ml)) with\n                | true => (EQ_M (ostomsg (getelt_at_pos  p1 ml)) (ostomsg (getelt_at_pos  p2 ml)))\n                | false => (EQ_M (ostomsg (getelt_at_pos  p2 ml)) O)\n              end\n    | false => match (chkmsg_os (getelt_at_pos p2 ml)) with\n                 | true => (EQ_M O (ostomsg (getelt_at_pos  p2 ml)))\n                 | false => (EQ_M O O)\n               end\n  end.\n\n(** Constructing a [EQ_B] term in with the elements in [mylist] *)\n\nDefinition EQ_B_at_pos {m}(p1 p2 : nat) (ml : mylist m) : Bool :=\n  match (chkbol_os (getelt_at_pos  p1 ml)) with\n    | true => match (chkbol_os (getelt_at_pos  p2 ml)) with\n                | true => (EQ_B (ostobol (getelt_at_pos  p1 ml)) (ostobol (getelt_at_pos  p2 ml)))\n                | false => (EQ_B (ostobol (getelt_at_pos  p1 ml)) TRue)\n              end\n    | false => match (chkbol_os (getelt_at_pos  p2 ml)) with\n                 | true => (EQ_B TRue (ostobol (getelt_at_pos  p2 ml)))\n                 | false => (EQ_B TRue TRue)\n               end\n  end.\n\n(** Constructing a [andB] term in with the elements in [mylist] *)\n\nDefinition andB_at_pos {m} (p1 p2 : nat) (ml : mylist m) : Bool :=\n  match (chkbol_os (getelt_at_pos  p1 ml)) with\n    | true => match (chkbol_os (getelt_at_pos  p2 ml)) with\n                | true => (andB (ostobol (getelt_at_pos  p1 ml)) (ostobol (getelt_at_pos  p2 ml)))\n                | false => (andB (ostobol (getelt_at_pos  p1 ml)) TRue)\n              end\n    | false => match (chkbol_os (getelt_at_pos  p2 ml)) with\n                 | true => (andB TRue (ostobol (getelt_at_pos  p2 ml)))\n                 | false => (andB TRue TRue)\n               end\n  end.\n\n(** Negating an element at [pos] in [mylist] *)\n\nDefinition notB_at_pos {m} (p : nat) (ml : mylist m) : Bool :=\n  match (chkbol_os (getelt_at_pos  p ml)) with\n    | true =>  notb (ostobol (getelt_at_pos  p ml))    \n    | false => notb (TRue)\n  end.\n\n\n(** Construction [if_then_else_M] term from [mylist] *)\n\nDefinition IfM_at_pos {m}  (p1 p2 p3 p4 :nat)(ml : mylist m) : message :=\n  match (chkbol_os (getelt_at_pos  p1 ml)) with \n    | true => match (chkmsg_os (getelt_at_pos  p2 ml)) with\n                | true => match (chkmsg_os (getelt_at_pos  p3 ml)) with\n                            | true =>  (if_then_else_M (ostobol (getelt_at_pos  p1 ml)) (ostomsg (getelt_at_pos  p2 ml))  ((ostomsg (getelt_at_pos  p3 ml))))\n                            | false => (if_then_else_M (ostobol (getelt_at_pos  p1 ml)) (ostomsg (getelt_at_pos  p2 ml)) O)\n                          end\n                | false =>  match (chkmsg_os (getelt_at_pos  p3 ml)) with\n                              | true =>  (if_then_else_M (ostobol (getelt_at_pos  p1 ml)) O ((ostomsg (getelt_at_pos  p3 ml))))\n                              | false => (if_then_else_M (ostobol (getelt_at_pos  p1 ml)) O  O)\n                            end\n              end\n    | false =>  match (chkmsg_os (getelt_at_pos  p2 ml)) with\n                  | true => match (chkmsg_os (getelt_at_pos  p3 ml)) with\n                              | true =>  (if_then_else_M TRue (ostomsg (getelt_at_pos  p2 ml))  ((ostomsg (getelt_at_pos  p3 ml))))\n                              | false => (if_then_else_M TRue (ostomsg (getelt_at_pos  p2 ml)) O)\n                            end\n                  | false =>  match (chkmsg_os (getelt_at_pos  p3 ml)) with\n                                | true =>  (if_then_else_M TRue O ((ostomsg (getelt_at_pos  p3 ml))))\n                                | false => (if_then_else_M TRue O  O)\n                              end\n                end\n                  \n  end.\n\n(** Construction [if_then_else_B] with terms in [mylist] *)\n\nDefinition IfB_at_pos {m}  (p1 p2 p3 p4 :nat)(ml : mylist m) : Bool :=\n  match (chkbol_os (getelt_at_pos  p1 ml)) with \n    | true => match (chkbol_os (getelt_at_pos  p2 ml)) with\n                | true => match (chkbol_os (getelt_at_pos  p3 ml)) with\n                            | true =>  (if_then_else_B (ostobol (getelt_at_pos  p1 ml)) (ostobol (getelt_at_pos  p2 ml))  ((ostobol (getelt_at_pos  p3 ml))))\n                            | false => (if_then_else_B (ostobol (getelt_at_pos  p1 ml)) (ostobol (getelt_at_pos  p2 ml)) TRue)\n                          end\n                | false =>  match (chkbol_os (getelt_at_pos  p3 ml)) with\n                              | true =>  (if_then_else_B (ostobol (getelt_at_pos  p1 ml)) TRue ((ostobol (getelt_at_pos  p3 ml))))\n                              | false => (if_then_else_B (ostobol (getelt_at_pos  p1 ml)) TRue  TRue)\n                            end\n              end\n    | false =>  match (chkbol_os (getelt_at_pos  p2 ml)) with\n                  | true => match (chkbol_os (getelt_at_pos  p3 ml)) with\n                              | true =>  (if_then_else_B TRue (ostobol (getelt_at_pos  p2 ml))  ((ostobol (getelt_at_pos  p3 ml))))\n                              | false => (if_then_else_B TRue (ostobol (getelt_at_pos  p2 ml)) TRue)\n                            end\n                  | false =>  match (chkbol_os (getelt_at_pos  p3 ml)) with\n                                | true =>  (if_then_else_B TRue TRue ((ostobol (getelt_at_pos  p3 ml))))\n                                | false => (if_then_else_B TRue TRue TRue)\n                              end\n                end\n                  \n  end.\n\n(** Constructing a [pair] term from [mylist] *)\n\nDefinition pair_term_pos {n}  (m:message) (p:nat)  (ml : mylist n): message :=\n  (pair m (ostomsg (getelt_at_pos  p ml))).\n\n(** [If_then_else_M] b1 m1 ( ( m1, m2), m3) : b1 at n1, m1 at n2, m2 at n3, m3 at n4 *)\n\nDefinition ifm_nespair {m}  (p1 p2 p3 p4 :nat)(ml : mylist m) : message := \n  match (chkbol_os (getelt_at_pos  p1 ml)) with \n    | true => match (chkmsg_os (getelt_at_pos  p2 ml)) with\n                | true => if_then_else_M  (ostobol (getelt_at_pos  p1 ml)) (ostomsg (getelt_at_pos  p2 ml))  (pair_term_pos  (pair_at_pos  p2 p3 ml) p4 ml)\n                | false => (if_then_else_M  (ostobol (getelt_at_pos  p1 ml)) O (pair_term_pos  (pair_term_pos  O p3 ml) p4 ml))\n              end\n    |false => match (chkmsg_os (getelt_at_pos  p2 ml)) with\n                | true => (if_then_else_M  TRue (ostomsg (getelt_at_pos  p2 ml))  (pair_term_pos  (pair_at_pos  p2 p3 ml) p4 ml))\n                | false => (if_then_else_M  TRue  O (pair_term_pos  (pair_term_pos  O p3 ml)  p4 ml))\n              end\n  end.\n\nEval compute in ifm_nespair  1 3 4 5  [bol (Bvar 1) ; bol (Bvar 2); msg (N 1); msg (N 2); msg (N 3)].\n\n\n(** [If_then_else_M] b1 m1 (m2, m3) : b1 at n1, m1 at n2, m2 at n3, m3 at n4 *)\n\nDefinition ifm_pair {m}  (p1 p2 p3 p4 :nat)(ml : mylist m) : message := \n  match (chkbol_os (getelt_at_pos  p1 ml)) with \n    | true => match (chkmsg_os (getelt_at_pos  p2 ml)) with\n                | true => (if_then_else_M  (ostobol (getelt_at_pos  p1 ml)) (ostomsg (getelt_at_pos  p2 ml)) (pair_at_pos  p3 p4 ml))\n                | false => (if_then_else_M  (ostobol (getelt_at_pos  p1 ml)) O  (pair_at_pos  p3 p4 ml))\n              end\n    |false => match (chkmsg_os (getelt_at_pos  p2 ml)) with\n                | true => (if_then_else_M  TRue (ostomsg (getelt_at_pos  p2 ml))  (pair_at_pos  p3 p4 ml))\n                | false => (if_then_else_M  TRue  O  (pair_at_pos  p3 p4 ml))\n              end\n  end.\n            \nEval compute in ifm_pair 1 2 3 4  [bol (Bvar 1) ; bol (Bvar 2); msg (N 1); msg (N 2); msg (N 3)].\n  \n(** Dropping the last element in [mylist] *)\n\nDefinition dropone {n:nat} (m:mylist n):(mylist (pred n)):=\n  match m with \n    | [] => []\n    |  h:: m1 => m1\n  end.\n\n(** Dropping last two elements in a [mylist] *)\n\nDefinition  droptwo {n:nat} (ml: mylist n): mylist (pred (pred n)):= (dropone (dropone ml)).\n\n(** Apply reveal at position in [mylist] *)\n\nDefinition reveal_at_pos{m} (p:nat) (ml: mylist m) : message :=\n  match (chkmsg_os (getelt_at_pos  p ml)) with\n    | true =>  reveal (ostomsg (getelt_at_pos p ml) )\n    | false => reveal O\n  end.\n\n(** Apply [to] at position in [mylist] *)\n\nDefinition to_at_pos {m} (p:nat) (ml: mylist m) : message :=\n  match (chkmsg_os (getelt_at_pos  p ml)) with\n    | true =>  to (ostomsg (getelt_at_pos  p ml) )\n    | false => to O\n  end.\n\n(** Apply [act] at position in [mylist] *)\n\nDefinition act_at_pos {m} (p:nat) (ml: mylist m) : message :=\n  match (chkmsg_os (getelt_at_pos  p ml)) with\n    | true =>  act (ostomsg (getelt_at_pos  p ml) )\n    | false => act O\n  end.\n\n(** Apply [m] at position in [mylist] *)\n\nDefinition m_at_pos {n} (p:nat) (ml:mylist n) : message :=\n  match (chkmsg_os (getelt_at_pos p ml)) with\n    | true =>  m (ostomsg (getelt_at_pos p ml) )\n    | false => m O\n  end.\nEval compute in to_at_pos 4 [bol (Bvar 1) ; bol (Bvar 2); msg (N 1); msg (N 2); msg (N 3)]. \n\n(** Constant function [const] *)\n\nDefinition const {X:Type}{Y:Type}(a : X) := fun _ : Y => a.\nEval compute in (const (N 0) O ).\n\n(** Substitute [Bool] in [mylist] *)\n\nFixpoint subbol_mylist {n1:nat} (n:nat)(s:Bool)(ml: mylist n1):mylist n1 :=\n  match ml with \n    | Nil => []\n    | h::t => (subbol_os n s h) :: (subbol_mylist n s t)\n  end.\n\n(** Substitute [message] in [mylist] *)\n\nFixpoint submsg_mylist {n1:nat} (n:nat)(s:message)(ml: mylist n1):mylist n1 :=\n  match ml with \n    | Nil => []\n    | h::t => (submsg_os n s h) :: (submsg_mylist n s t)\n  end.\nEval compute in (subbol_mylist 1 TRue [msg O; msg (Mvar 1); bol (Bvar 1)]).\nEval compute in (submsg_os 1  ( O) (bol (Bvar 1))).\n\n(** Drop last element *)\n\nDefinition drpone_last {n} (l:mylist (S n)) : mylist n :=  dropone(reverse l).\n\n(** Project last element *)\n\nDefinition proj_one {n} (l: mylist n) : mylist 1:=\n  match (reverse   l)  with\n    | [] => [msg O]\n    | h::t => [h]\n  end.\n\n(** Project last two *)\n\nDefinition proj_two {n} (l:mylist n) : mylist 2:=\n  match (reverse l) with\n    |[] => [msg O; msg O]\n    | h::t::l' => [t;h]\n    | h:: t => [msg O; h]\n  end.\n\n(** Drop last but one *)\n\nDefinition droplastsec {n} (l:mylist n) : mylist (pred (pred n) + pred 2) :=\n  let y := (proj_two l) in\n  let x := (droptwo (reverse l)) in\n  let y1:= (dropone y) in \n  (app_mylist (reverse x) y1).\n\nEval compute in (droplastsec  [msg O; msg (Mvar 1)]).\n\n(** Project last three *)\n\nDefinition proj_three {n} (l: mylist n) : mylist 3:=\n  match (reverse l) with \n    | [] => [msg O ; msg O ; msg O]\n    | h :: h1 :: h2 :: l1 => [h2 ; h1 ; h]\n    | h :: h1 :: t => [ msg O; h1 ; h]\n    | h :: t => [msg O ; msg O ; h]\n  end.\n\n(** Drop last but third *)\n\nDefinition droplast3rd {n} (l:mylist n) : mylist (( pred (pred (pred n) ) ) + pred 3) :=\n  let y := (proj_three l) in \n  let x := (dropone (droptwo (reverse l))) in\n  let y1 := (dropone y) in \n  (app_mylist (reverse x) y1).\n\nEval compute in (droplast3rd  [ msg (Mvar 1)]).\n\n(** Construct [mylist n] where each element is [msg O] *)\n\nFixpoint app_n_elts (n:nat) :mylist n :=\n  match n with\n    | 0 => []\n    | S n' => (app_mylist (app_elt_front (msg O) []) (app_n_elts n'))\n  end.\n\nEval compute in app_n_elts 3.\n\n(** Apply [pred] on [m] for [n] times *)\n\nFixpoint app_pred_n (n m:nat) : nat :=\n  match n with \n    | 0 => m\n    | S n' => (app_pred_n n' (pred m))\n  end.\n\n(** Drop [n] elements from [mylist] *)\n\nFixpoint drop_n_times (n :nat) {m} (l:mylist m) : mylist (app_pred_n n m) :=\n  match (leb n m) with \n    | true => match n with\n                | 0 => l\n                | S n' => let x := (dropone l) in\n                          drop_n_times n' x\n              end\n    | false => app_n_elts (app_pred_n n  m)\n  end.  \n\nEval compute in drop_n_times 5 [msg O; msg O; msg O; msg O].\n\n(** First [n] elements of [mylist] **)\n\nDefinition Firstn (n:nat) {m} (l: mylist m) : mylist (app_pred_n (app_pred_n n  m) m) :=  reverse (drop_n_times (app_pred_n n m ) (reverse l)).\n\n(** Skip or remove first [n] elements in [mylist] **)\n\nDefinition Skipn (n:nat) {m} (l: mylist m) : mylist (app_pred_n n m) :=  drop_n_times n l.\n\n(** Swap two elements in a [mylist] *)\n\nDefinition swap_mylist (p1 p2 :nat) {m} (l:mylist m) : mylist\n    (pred (app_pred_n (app_pred_n p1 m) m) +\n     (1 +\n      (pred\n         (app_pred_n (app_pred_n (app_pred_n p1 p2) (app_pred_n p1 m))\n            (app_pred_n p1 m)) +\n       (1 + app_pred_n (app_pred_n p1 p2) (app_pred_n p1 m))))) :=\n  let x := (Firstn p1 l) in \n  let y := (Skipn p1 l) in \n  let x1 := (proj_one x) in \n  let x2 := reverse (dropone (reverse x)) in\n  let x3 := (Firstn (app_pred_n p1 p2 ) y) in\n  let x4 :=  (Skipn (app_pred_n p1 p2) y) in\n  let x5 := (proj_one x3) in\n  let x6 := reverse (dropone (reverse x3)) in \n  x2 ++ x5 ++ x6 ++ x1 ++ x4.\n\nEval compute in swap_mylist 1 3  [ msg O; msg (Mvar 3); msg (Mvar 2); msg (Mvar 1)].\n\n(** Proj an element at a given [pos] [p] in [mylist] *)\n\nDefinition proj_at_pos (p:nat) {m} (l:mylist m) : mylist (pred (app_pred_n (app_pred_n p m) m) + app_pred_n p m) :=\n  let x := (Firstn p l) in\n  let y := (Skipn p l) in\n  let x1 := reverse (dropone (reverse x)) in\n  x1 ++ y.\n\nEval compute in proj_at_pos 3  [ msg O; msg (Mvar 3); msg (Mvar 2); msg (Mvar 1)].\n\n(** Check [equality] of two lists *)\n\nSection def.\nVariable A B :Type. \nVariable  f: message -> message -> bool.\n(**check if two lists equal*)\nFixpoint check_eq_listm  (l l' :list message)  :bool :=\n  match l  with\n    | nil => match l' with\n               | nil => true\n               | _ => false\n             end  \n    | cons h t =>  match l' with\n                     | cons h' t' => (andb (f h h') (check_eq_listm t t'))\n                     | _ => false\n                   end\n  end.\nEnd def.\n  \n(*  \n \n(** Check if two [Bool] terms equal *)\n\nFixpoint check_eq_bol (b b': Bool) : bool :=\nmatch b with \n         | Bvar n' => match b' with \n                        | (Bvar n'') => if (beq_nat n' n'') then true else false\n                        | _ => false\n                       end\n         | FAlse => match b' with \n                      | FAlse => true \n                      | _ => false\n                    end\n         | TRue => match b' with \n                     | TRue => true\n                     | _ => false \n                    end\n         | EQ_B b1 b2 => match b' with \n                           | EQ_B b3 b4 => (andb (check_eq_bol b1 b3) (check_eq_bol b2 b4))\n                           | _ => false\n                        end\n         | EQ_M t1 t2 => match b' with \n                          | EQ_M t3 t4 => (andb (check_eq_msg t1 t3) (check_eq_msg t2 t4))\n                          | _ => false\n                         end\n         | EQL t1 t2 => match b' with \n                          | EQL t3 t4 => (andb (check_eq_msg t1 t3) (check_eq_msg t2 t4))\n                          | _ => false\n                        end\n         | (if_then_else_B b1 b2  b3) =>  match b' with \n                                            | (if_then_else_B b4 b5 b6) => (andb (check_eq_bol b1 b4) (andb (check_eq_bol b2 b5) (check_eq_bol b3 b6)))\n                                            | _ => false\n                                          end\n         | ver t1 t2 t3 =>  match b' with\n                              | ver t4 t5 t6 => (andb (check_eq_msg t1 t4) (andb (check_eq_msg t2 t5 ) (check_eq_msg t3 t6)))\n                              | _ => false\n                            end\n         | elig b1 => match b' with\n                      | elig b2 => (check_eq_msg b1 b2)\n                      | _ => false\n                      end\n end \nwith check_eq_msg ( t t' : message ) : bool :=\n   match t with    \n     | Mvar n =>  match t' with \n                    | Mvar n' => (beq_nat n n')\n                    | _  => false \n                   end\n  \n    | O => match t' with\n              | O => true\n              | _ => false\n            end\n     | lnc => match t' with\n                | lnc => true\n                | _ => false\n              end\n       | lsk => match t' with\n                  | lsk => true\n                  | _ => false\n                end\n        | acc => match t' with\n                   | acc => true\n                   | _ => false \n                 end\n     | N n'=>  match t' with\n                 | N n'' => if (beq_nat n' n'') then true else false\n                 | _ => false \n               end\n\n     | (if_then_else_M b1 t1 t2) =>  match t' with \n                                       | (if_then_else_M b2 t3 t4) => (andb (check_eq_bol b1 b2) (andb (check_eq_msg t1 t3) (check_eq_msg t2 t4)))\n                                       | _ => false\n                                     end\n   | exp t1 t2 t3 =>  match t' with\n                        | exp t4 t5 t6 => (andb (check_eq_msg t1 t4) (andb (check_eq_msg t2 t5 ) (check_eq_msg t3 t6)))\n                        | _ => false\n                      end\n\n   | pair t1 t2 => match t' with\n                     | pair t3 t4 => (andb (check_eq_msg t1 t3) (check_eq_msg t2 t4))\n                     | _ => false\n                   end \n                                \n   | pi1 t1 =>  match t' with\n                  | pi1 t2 =>  (check_eq_msg t1 t2)\n                  | _ => false\n                end\n                \n   | pi2 t1 => match t' with\n                 | pi2 t2 =>  (check_eq_msg t1 t2)\n                 | _ => false\n              end\n            \n   | ggen t1 =>   match t' with\n                    | ggen t2 =>  (check_eq_msg t1 t2)\n                    | _ => false\n                  end\n   |rr t1 =>   match t' with\n                 | rr t2 =>  (check_eq_msg t1 t2)\n                 | _ => false \n               end   \n   | new => match t' with \n              | new => true\n              | _ => false\n            end\n          \n   | act t1 => match t' with\n                 | act t2 =>  (check_eq_msg t1 t2)\n                 | _ => false\n               end\n             \n   | m t1 =>   match t' with\n                 | m t2 =>  (check_eq_msg t1 t2)\n                 | _ => false\n               end\n  | nc t1  =>  match t' with\n                 | nc t2 =>  (check_eq_msg t1 t2)\n                 | _ => false\n               end\n   |rs t1 =>   match t' with\n                 | rs t2 =>  (check_eq_msg t1 t2)\n                 | _ => false\n               end\n          \n   |L t1 => match t' with\n             | L t2 =>  (check_eq_msg t1 t2)\n             | _ => false\n            end            \n           \n   | enc t1 t2 t3 =>  match t' with\n                        | enc t4 t5 t6 => (andb (check_eq_msg t1 t4) (andb (check_eq_msg t2 t5 ) (check_eq_msg t3 t6)))\n                        | _ => false\n                      end\n  |dec t1 t2 =>  match t' with\n                   | dec t3 t4 => (andb (check_eq_msg t1 t3) (check_eq_msg t2 t4))\n                   | _ => false\n                end \n                   \n   |k t1 => match t' with\n              | k t2 =>  (check_eq_msg t1 t2)\n              | _ => false\n             end\n          \n             \n   | to t1 => match t' with\n                | to t2 =>  (check_eq_msg t1 t2)\n                | _ => false\n              end\n   | reveal t1 =>   match t' with\n                      | reveal t2 =>  (check_eq_msg t1 t2)\n                      | _ => false\n                    end\n  \n              \n   | sign t1 t2 =>   match t' with\n                       | sign t3 t4 => (andb (check_eq_msg t1 t3) (check_eq_msg t2 t4))\n                       | _ => false\n                     end \n               \n   | i n' =>  match t' with\n                | i n'' => if  (beq_nat n' n'') then true else false\n                | _ => false\n             end\n\n                 (** foo function symbol *)  \n| commit t1 t2 t3 => match t' with\n                        | commit t4 t5 t6 => (andb (check_eq_msg t1 t4) (andb (check_eq_msg t2 t5 ) (check_eq_msg t3 t6)))\n                        | _ => false\n                      end\n| open t1 t2 t3 =>  match t' with\n                        | open t4 t5 t6 => (andb (check_eq_msg t1 t4) (andb (check_eq_msg t2 t5 ) (check_eq_msg t3 t6)))\n                        | _ => false\n                      end\n| blind t1 t2 =>  match t' with\n                       | blind t3 t4 => (andb (check_eq_msg t1 t3) (check_eq_msg t2 t4))\n                       | _ => false\n                     end \n| unblind t1 t2 =>  match t' with\n                       | unblind t3 t4 => (andb (check_eq_msg t1 t3) (check_eq_msg t2 t4))\n                       | _ => false\n                    end\n| v t1 => match t' with\n                | v t2 =>  (check_eq_msg t1 t2)\n                | _ => false\n              end    \n | dcsn t1 => match t' with\n                      | dcsn t2 =>  (check_eq_msg t1 t2)\n                      | _ => false\n                    end\n|V n' =>  match t' with\n                | V n'' => if  (beq_nat n' n'') then true else false\n                | _ => false\n             end\n\n| ok => match t' with\n              | ok => true\n              | _ => false\n            end\n| f l =>   match t' with\n                | f l' => ( @check_eq_listm  (check_eq_msg ) l l')\n                | _ => false\n              end\n                   \n   end.\n                 \n\n*)  \n\n(** Check occurence of a term in a term *)\n \nFixpoint checkbtbol ( b':Bool) (b:Bool) : bool :=\n  if (Bool_beq b' b) then true else\n  match b  with \n    | EQ_B  b1 b2 => (orb (checkbtbol b' b1) (checkbtbol b' b2))\n    | EQ_M t1 t2 =>   (orb (checkbtmsg b' t1) (checkbtmsg b' t2))\n    | if_then_else_B t1 t2 t3 =>  (orb (checkbtbol b' t1) (orb (checkbtbol b' t2) (checkbtbol b' t3)))\n    | EQL t1 t2 =>   (orb (checkbtmsg b' t1 ) (checkbtmsg b' t2))\n    | ver t1 t2 t3 =>   (orb (checkbtmsg b' t1)  (orb (checkbtmsg b' t2) (checkbtmsg b' t3)))\n    | bver t1 t2 t3 => (orb (checkbtmsg b' t1)  (orb (checkbtmsg b' t2) (checkbtmsg b' t3)))\n    | bacc t1 t2 t3 => (orb (checkbtmsg b' t1)  (orb (checkbtmsg b' t2) (checkbtmsg b' t3)))\n    | _ => false\n  end\nwith checkbtmsg (b :Bool) (t:message) : bool :=\n       match t with \n         | if_then_else_M b' t1 t2 =>   (orb (checkbtbol b b') (orb (checkbtmsg b t1) (checkbtmsg b t2)))\n         | exp t1 t2 t3 => (orb (checkbtmsg b t1) (orb (checkbtmsg b t2) (checkbtmsg b t3)))\n         | pair t1 t2 => (orb (checkbtmsg b t1) (checkbtmsg b t2))\n         | pi1 t1 =>  (checkbtmsg b t1) \n         | pi2 t1 =>  (checkbtmsg b t1) \n         | ggen t1 =>  (checkbtmsg b t1) \n         | act t1 =>   (checkbtmsg b t1) \n         | rr t1 =>   (checkbtmsg b t1) \n         | rs t1 =>  (checkbtmsg b t1) \n         | L t1 =>   (checkbtmsg b t1) \n         | m t1 =>   (checkbtmsg b t1) \n         | enc t1 t2 t3 =>   (orb (checkbtmsg b t1) (orb (checkbtmsg b t2) (checkbtmsg b t3)))\n         | dec t1 t2 => (orb (checkbtmsg b t1) (checkbtmsg b t2))\n         | k t1 =>  (checkbtmsg b t1) \n         | nc t1 => (checkbtmsg b t1) \n         | to t1 =>  (checkbtmsg b t1) \n         | reveal t1 =>  (checkbtmsg b t1) \n         | sign t1 t2 =>(orb (checkbtmsg b t1) (checkbtmsg b t2))\n         (** foo function symbol *)  \n         | commit t1 t2 t3 => (orb (checkbtmsg b t1) (orb (checkbtmsg b t2) (checkbtmsg b t3)))\n         | open t1 t2 t3 => (orb (checkbtmsg b t1) (orb (checkbtmsg b t2) (checkbtmsg b t3)))\n         | blind t1 t2 => (orb (checkbtmsg b t1) (checkbtmsg b t2))\n         | unblind t1 t2 =>  (orb (checkbtmsg b t1) (checkbtmsg b t2))\n         | bsign t1 t2 =>(orb (checkbtmsg b t1) (checkbtmsg b t2))                      \n         | v t1 => (checkbtmsg b t1)\n         | f l => (@existsb message (checkbtmsg b) l)\n         | _ => false\n       end. \n\n(*\n(** Check for a [message] in [Bool] *)\n\n \nFixpoint occmsg_in_bol ( t':message) (t:Bool) : bool :=\n match t  with \n| Bvar n'  =>  false\n| FAlse =>  false\n| TRue => false\n| EQ_B  b1 b2 => (orb (occmsg_in_bol t' b1) (occmsg_in_bol t' b2))\n| EQ_M t1 t2 =>   (orb (message_beq t' t1) (orb (message_beq t' t2) (orb (occmsg_in_msg t' t1) (occmsg_in_msg t' t2))))\n| if_then_else_B t1 t2 t3 => (orb (occmsg_in_bol t' t1) (orb (occmsg_in_bol t' t2) (occmsg_in_bol t' t3)))\n| EQL t1 t2 =>  (orb (message_beq t' t1) (orb (message_beq t' t2) (orb (occmsg_in_msg t' t1) (occmsg_in_msg t' t2))))\n| ver t1 t2 t3 => (orb (message_beq t' t1) (orb (message_beq t' t2) (orb (message_beq t' t3)  (orb (occmsg_in_msg t' t1) (orb (occmsg_in_msg t' t2) (occmsg_in_msg t' t3))))))\n| bver t1 t2 t3 => (orb (message_beq t' t1) (orb (message_beq t' t2) (orb (message_beq t' t3)  (orb (occmsg_in_msg t' t1) (orb (occmsg_in_msg t' t2) (occmsg_in_msg t' t3))))))\n| bacc t1 t2 t3 => (orb (message_beq t' t1) (orb (message_beq t' t2) (orb (message_beq t' t3)  (orb (occmsg_in_msg t' t1) (orb (occmsg_in_msg t' t2) (occmsg_in_msg t' t3))))))                    \n end\nwith occmsg_in_msg  (t':message) (t:message) : bool :=\n match t with \n| if_then_else_M b t1 t2 => (orb (occmsg_in_bol  t' b) (orb (message_beq t' t) (orb (occmsg_in_msg t' t1) (occmsg_in_msg t' t2))))\n| (Mvar n') => message_beq t' t\n| O => (message_beq t' t)\n| acc => (message_beq t' t)\n| N n'=> (message_beq t' t)\n|new => (message_beq t' t)\n| lsk => (message_beq t' t)\n| lnc => (message_beq t' t)\n| exp t1 t2 t3 => (orb (message_beq t' t) (orb (occmsg_in_msg t' t1) (orb (occmsg_in_msg t' t2) (occmsg_in_msg t' t3))))\n| pair t1 t2 => (orb (message_beq t' t) (orb (occmsg_in_msg t' t1) (occmsg_in_msg t' t2)))\n| pi1 t1 => (orb (message_beq t' t) (occmsg_in_msg t' t1) )\n| pi2 t1 =>   (orb (message_beq t' t) (occmsg_in_msg t' t1) )\n| ggen t1 =>   (orb (message_beq t' t) (occmsg_in_msg t' t1) )\n| act t1 =>    (orb (message_beq t' t) (occmsg_in_msg t' t1) )\n| rr t1 =>    (orb (message_beq t' t) (occmsg_in_msg t' t1) )\n| rs t1 =>   (orb (message_beq t' t) (occmsg_in_msg t' t1) )\n| L t1 =>    (orb (message_beq t' t) (occmsg_in_msg t' t1) )\n| m t1 =>    (orb (message_beq t' t) (occmsg_in_msg t' t1) )\n|enc t1 t2 t3 =>  (orb (message_beq t' t) (orb (occmsg_in_msg t' t1) (orb (occmsg_in_msg t' t2) (occmsg_in_msg t' t3))))\n|dec t1 t2 => (orb (message_beq t' t) (orb (occmsg_in_msg t' t1) (occmsg_in_msg t' t2)))\n| k t1 =>  (orb (message_beq t' t) (occmsg_in_msg t' t1) ) \n| nc t1 =>  (orb (message_beq t' t) (occmsg_in_msg t' t1) )\n| to t1 =>  (orb (message_beq t' t) (occmsg_in_msg t' t1) )\n| dcsn t1 =>  (orb (message_beq t' t) (occmsg_in_msg t' t1) )\n| reveal t1 =>  (orb (message_beq t' t) (occmsg_in_msg t' t1) ) \n| sign t1 t2 =>(orb (occmsg_in_msg t' t1) (occmsg_in_msg t' t2))\n| i n' => (message_beq t' t)\n  (** foo function symbol *)  \n| commit t1 t2 t3 =>  (orb (message_beq t' t) (orb (occmsg_in_msg t' t1) (orb (occmsg_in_msg t' t2) (occmsg_in_msg t' t3))))\n| open t1 t2 t3 =>  (orb (message_beq t' t) (orb (occmsg_in_msg t' t1) (orb (occmsg_in_msg t' t2) (occmsg_in_msg t' t3))))\n| blind t1 t2 => (orb (message_beq t' t) (orb (occmsg_in_msg t' t1) (occmsg_in_msg t' t2)))\n| unblind t1 t2 => (orb (message_beq t' t) (orb (occmsg_in_msg t' t1) (occmsg_in_msg t' t2)))\n| bsign t1 t2 =>(orb (occmsg_in_msg t' t1) (occmsg_in_msg t' t2))                     \n| v t1 =>  (orb (message_beq t' t) (occmsg_in_msg t' t1) )\n| V n' => (message_beq t' t)\n| ok => (message_beq t' t)\n| f l => (@existsb message (occmsg_in_msg t') l)\n        end.   \n\nEval compute in checkbtbol TRue (EQ_M O O).\n         \n\n\nEval compute in checkmtbol O (EQ_M O O)&TRue .\n\n\n(** Check if a [message] term occur in oursum *)\n\nFixpoint checkmtos (t': message) (t'':oursum): bool := \nmatch t'' with \n| msg t => occmsg_in_msg t' t\n| bol b => occmsg_in_bol t' b\nend.\n\n\n\nCheck notb.\nCheck negb.\n\nFixpoint occmsg_in_mylist  {n:nat}(t:message) (l:mylist n): bool :=\nmatch l with\n| [] => false\n| x :: h =>  if (occmsg_in_os t x) then true else (occmsg_in_mylist t h)\nend.\n\n*)\n   \n(** Substitute term ts ([Bool]) for a term t'([Bool]) replace b' with s in b *)\n\nFixpoint subbol_bol'  (b' : Bool) (s: Bool) (b :Bool) : Bool :=\n  if (Bool_beq b' b) then s else\n    match b  with\n      | EQ_B b1 b2 => EQ_B (subbol_bol' b' s b1) (subbol_bol' b' s b2)\n      | EQ_M t1 t2 => EQ_M (subbol_msg' b' s t1) (subbol_msg' b' s t2)\n      | EQL t1 t2 => EQL (subbol_msg' b' s t1) (subbol_msg' b' s t2)\n      | if_then_else_B b1 b2 b3 => if_then_else_B (subbol_bol' b' s b1) (subbol_bol' b' s b2) (subbol_bol' b' s b3)\n      | ver t1 t2 t3 =>  ver (subbol_msg' b' s t1) (subbol_msg' b' s t2) (subbol_msg' b' s t3)\n      | bver t1 t2 t3 => bver (subbol_msg' b' s t1) (subbol_msg' b' s t2) (subbol_msg' b' s t3)                                    \n      | bacc t1 t2 t3 => bacc (subbol_msg' b' s t1) (subbol_msg' b' s t2) (subbol_msg' b' s t3)\n      | _             => b             \n    end\nwith subbol_msg' (b' : Bool )(s: Bool) (t:message) : message :=\n       match t with \n         | if_then_else_M b t1 t2 =>    (if_then_else_M (subbol_bol' b' s b) (subbol_msg' b' s t1) (subbol_msg' b' s t2))                                     \n         | exp t1 t2 t3 =>   exp  (subbol_msg' b' s t1) (subbol_msg' b' s t2) (subbol_msg' b' s t3)\n         | pair t1 t2 => pair (subbol_msg' b' s t1) (subbol_msg' b' s t2)\n         | pi1 t1 =>  pi1 (subbol_msg' b' s t1)\n         | pi2 t1 =>  pi2 (subbol_msg' b' s t1)\n         | ggen t1 =>   ggen (subbol_msg' b' s t1)\n         | act t1 =>  act (subbol_msg' b' s t1)\n         | rr t1 =>    rr (subbol_msg' b' s t1)\n         | rs t1 =>   rs (subbol_msg' b' s t1)\n         | L t1 =>  L (subbol_msg' b' s t1)\n         | m t1 =>    m (subbol_msg' b' s t1)\n         | enc t1 t2 t3 => enc (subbol_msg' b' s t1) (subbol_msg' b' s t2) (subbol_msg' b' s t3)\n         | dec t1 t2 => dec  (subbol_msg' b' s t1) (subbol_msg' b' s t2) \n         | k t1 =>  k (subbol_msg' b' s t1)\n         | nc t1 =>  nc (subbol_msg' b' s t1)\n         | to t1 => to  (subbol_msg' b' s t1) \n         | reveal t1 =>  reveal (subbol_msg' b' s t1) \n         | sign t1 t2 =>   sign (subbol_msg' b' s t1) (subbol_msg' b' s t2) \n         (** foo function symbol *)  \n         | commit t1 t2 t3 => commit (subbol_msg' b' s t1) (subbol_msg' b' s t2) (subbol_msg' b' s t3)\n         | open t1 t2 t3 => open (subbol_msg' b' s t1) (subbol_msg' b' s t2) (subbol_msg' b' s t3)\n         | blind t1 t2 => blind (subbol_msg' b' s t1) (subbol_msg' b' s t2)\n         | unblind t1 t2 => unblind (subbol_msg' b' s t1) (subbol_msg' b' s t2)\n         | f l =>  (f (@map message message  (subbol_msg' b' s) l))\n         | v t1 => v (subbol_msg' b' s t1)\n         | bsign t1 t2  =>   bsign (subbol_msg' b' s t1) (subbol_msg' b' s t2)\n         | _ => t                  \n       end.\n                 \n     \n\n\nFixpoint submsg_bol' (t' : message)(s:message) (b:Bool) : Bool :=\n  match b with\n    | EQ_B  b1 b2 =>  (EQ_B (submsg_bol' t' s b1) (submsg_bol' t' s b2))\n    | EQ_M t1 t2 => (EQ_M (submsg_msg' t' s t1) (submsg_msg' t' s t2))\n    | if_then_else_B t1 t2 t3 => (if_then_else_B (submsg_bol' t' s t1) (submsg_bol' t' s t2) (submsg_bol' t' s t3))\n    | EQL t1 t2 =>  (EQL (submsg_msg' t' s t1) (submsg_msg' t' s t2))\n    | ver t1 t2 t3 => ver  (submsg_msg' t' s t1) (submsg_msg' t' s t2) (submsg_msg' t' s t3)\n    | bver t1 t2 t3 => bver (submsg_msg' t' s t1) (submsg_msg' t' s t2) (submsg_msg' t' s t3)\n    | bacc t1 t2 t3 => bacc (submsg_msg' t' s t1) (submsg_msg' t' s t2) (submsg_msg' t' s t3)\n    | _ => b\n  end\nwith submsg_msg' (t' : message )(s:message) (t:message) : message :=\nif  (message_beq t' t)  then s else\n  match t with \n    | if_then_else_M b1 t1 t2 => (if_then_else_M (submsg_bol' t' s b1) (submsg_msg' t' s t1) (submsg_msg' t' s t2))\n    | exp t1 t2 t3 =>  exp  (submsg_msg' t' s t1) (submsg_msg' t' s t2) (submsg_msg' t' s t3)\n    | pair t1 t2 => pair (submsg_msg' t' s t1) (submsg_msg' t' s t2)\n    | pi1 t1 => pi1 (submsg_msg' t' s t1)\n    | pi2 t1 => pi2 (submsg_msg' t' s t1)\n    | ggen t1 =>  ggen (submsg_msg' t' s t1)\n    | act t1 =>   act (submsg_msg' t' s t1)\n    | rr t1 =>   rr (submsg_msg' t' s t1)\n    | rs t1 =>   rs (submsg_msg' t' s t1)\n    | L t1 =>  L (submsg_msg' t' s t1)\n    | m t1 =>  m (submsg_msg' t' s t1)\n    | enc t1 t2 t3 => enc (submsg_msg' t' s t1) (submsg_msg' t' s t2) (submsg_msg' t' s t3)\n    | dec t1 t2 =>  dec  (submsg_msg' t' s t1) (submsg_msg' t' s t2) \n    | k t1 =>  k (submsg_msg' t' s t1)\n    | nc t1 =>   nc  (submsg_msg' t' s t1) \n    | to t1 =>  to  (submsg_msg' t' s t1) \n    | reveal t1 => reveal (submsg_msg' t' s t1) \n    | sign t1 t2 =>  sign (submsg_msg' t' s t1) (submsg_msg' t' s t2) \n    | commit t1 t2 t3 => commit (submsg_msg' t' s t1) (submsg_msg' t' s t2) (submsg_msg' t' s t3)\n    | open t1 t2 t3 =>  open (submsg_msg' t' s t1) (submsg_msg' t' s t2) (submsg_msg' t' s t3)\n    | blind t1 t2 =>  blind (submsg_msg' t' s t1) (submsg_msg' t' s t2) \n    | unblind t1 t2 => unblind (submsg_msg' t' s t1) (submsg_msg' t' s t2) \n    | v t1 =>   to  (submsg_msg' t' s t1)\n    | f l =>   (f (@map message message  (submsg_msg' t' s) l))\n    | _ => t\n    end.\n      \nEval compute in (submsg_msg' (Mvar 1) O (Mvar 2)).\n\n\n\n(** Check if a term is constant *)\n\nDefinition const_bol (t:Bool) : bool :=\n  match t with \n    | TRue => true\n    | FAlse => true\n    | _ => false\n  end.\n\nDefinition const_msg (t:message) : bool :=\n  match t with\n    | O => true\n    | lnc => true\n    | lsk => true\n    | acc => true\n    | new => true\n    | i n' => true\n    | V n' => true\n    | _ => false\n  end.\n               \n(** Subterms of list of terms. *)\n\nSection subtrm.\nVariable f: message -> list message.\nFixpoint subtrmls (l: list message) : list message :=\n  match l with\n    | nil => nil\n    | cons h t => (app (f h) (subtrmls t))\n  end.\nEnd subtrm.\n\n(** subterms of [message], or [Bool] terms. *)\n\nFixpoint subtrmls_bol  (t: Bool) : list message :=\n  match t with \n    | EQ_B  b1 b2 =>  (app (subtrmls_bol  b1) (subtrmls_bol b2) )\n    | EQ_M t1 t2 => (app (subtrmls_msg t1) (subtrmls_msg t2) )\n    | if_then_else_B t1 t2 t3 => (app (subtrmls_bol t1) (app (subtrmls_bol t2) (subtrmls_bol t3)))\n    | EQL t1 t2 => (app (subtrmls_msg t1) (subtrmls_msg t2) )\n    | ver t1 t2 t3 => (app (subtrmls_msg t1) (app (subtrmls_msg t2) (subtrmls_msg t3)))\n    | bver t1 t2 t3 => (app (subtrmls_msg t1) (app (subtrmls_msg t2) (subtrmls_msg t3)))\n    | bacc t1 t2 t3 => (app (subtrmls_msg t1) (app (subtrmls_msg t2) (subtrmls_msg t3)))\n    | _ => nil\n end\nwith subtrmls_msg (t:message) : list message :=\n       match t with \n         | if_then_else_M b3 t1 t2 => (app (cons (if_then_else_M b3 t1 t2) nil)  (app (subtrmls_bol b3) (app (subtrmls_msg t1) (subtrmls_msg t2))))\n         | (Mvar n') => (cons (Mvar n') nil)\n         | acc => (cons acc nil)\n         | lnc => (cons lnc nil)\n         | lsk => (cons lsk nil)\n         | O => (cons O nil)\n         | N n'=> (cons (N n') nil)\n         | new =>  (cons new nil)\n         | exp t1 t2 t3 => (app   (cons (exp t1 t2 t3) nil) (app (subtrmls_msg t1) (app (subtrmls_msg t2) (subtrmls_msg t3))))\n         | pair t1 t2 => (app (cons (pair t1 t2) nil) (app (subtrmls_msg  t1) (subtrmls_msg t2) ))\n         | pi1 t1 => (app (cons (pi1 t1) nil) (subtrmls_msg t1) )\n         | pi2 t1 => (app (cons (pi2 t1) nil) (subtrmls_msg t1) )\n         | ggen t1 => (app (cons (ggen t1) nil) (subtrmls_msg t1) )\n         | act t1 => (app (cons (act t1) nil) (subtrmls_msg t1) )\n         | rr t1 => (app  (cons (rr t1) nil) (subtrmls_msg t1) )\n         | rs t1 => (app (cons (rs t1) nil) (subtrmls_msg t1) )\n         | L t1 => (app (cons (L t1) nil)  (subtrmls_msg t1) )\n         | m t1 => (app ( cons (m t1) nil) (subtrmls_msg t1) )\n         | enc t1 t2 t3 => (app (cons (enc t1 t2 t3) nil) (app (subtrmls_msg t1) (app (subtrmls_msg t2) (subtrmls_msg t3))))\n         | dec t1 t2 => (app (cons ( dec t1 t2) nil) (app (subtrmls_msg t1) (subtrmls_msg t2)))\n         | k t1 => (app (cons (k t1) nil) (subtrmls_msg t1) )\n         | nc n => (cons (nc n) nil) \n         | to t1 => (app (cons (to t1) nil) (subtrmls_msg t1) )\n         | reveal t1 => (app (cons (reveal t1) nil) (subtrmls_msg t1) )\n         | sign t1 t2 => (app (cons (sign t1 t2) nil)  (app (subtrmls_msg t1) (subtrmls_msg t2)))\n         (** Foo function protocol *)\n         | commit t1 t2 t3 => (app (cons (commit t1 t2 t3) nil) (app (subtrmls_msg t1) (app (subtrmls_msg t2) (subtrmls_msg t3))))\n         | open t1 t2 t3 => (app (cons (open t1 t2 t3) nil) (app (subtrmls_msg t1) (app (subtrmls_msg t2) (subtrmls_msg t3))))\n         | blind t1 t2 => (app (cons ( blind t1 t2) nil) (app (subtrmls_msg t1) (subtrmls_msg t2)))\n         | unblind t1 t2 => (app (cons ( unblind t1 t2) nil) (app (subtrmls_msg t1) (subtrmls_msg t2)))\n         | v t1 => (app ( cons (m t1) nil) (subtrmls_msg t1) )\n         | ok => (cons ok nil)\n         | bsign t1 t2 => (app (cons (bsign t1 t2) nil)  (app (subtrmls_msg t1) (subtrmls_msg t2)))\n         | f l => ((cons (f l) (@subtrmls subtrmls_msg l)))\n         | _ => nil\n       end.\nEval compute in (subtrmls_msg (sign (if_then_else_M TRue (dec O (sk (N 1))) O) new)).\n\n(** Subterms of [oursum] term. *)\n\nDefinition subtrmls_os (t:oursum) : list message :=\n  match t with \n    | msg t1 => subtrmls_msg t1\n    | bol b1 =>  subtrmls_bol b1\n  end.\n\n(** Subterms of terms of type [mylist n] for some [n].*)\n\nFixpoint subtrmls_mylist {n} (l:mylist n) : list message :=\n  match l with \n    | [] => nil\n    | h:: t => (app (subtrmls_os h) (subtrmls_mylist t))\n  end.\n\n(** Check if [(N n)] occurs only under either [sk] or [pk] . *)\n\n(** [message] or [Bool]. *)\nFixpoint onlyin_pkrsk_bol (n : nat )(t:Bool) : bool :=\n  match t with \n    | Bvar n' => if (beq_nat n' n) then false else true\n    | EQ_B  b1 b2 =>  (andb (onlyin_pkrsk_bol n b1)  (onlyin_pkrsk_bol n b2))\n    | EQ_M t1 t2 => andb (onlyin_pkrsk_msg n t1) ( onlyin_pkrsk_msg n t2)\n    | if_then_else_B t1 t2 t3 =>  (andb (onlyin_pkrsk_bol n t1) (andb (onlyin_pkrsk_bol n t2) ( onlyin_pkrsk_bol n t3)))\n    | EQL t1 t2 =>  (andb (onlyin_pkrsk_msg n t1) ( onlyin_pkrsk_msg n t2))\n    | ver t1 t2 t3 => (andb (onlyin_pkrsk_msg n t1) (andb (onlyin_pkrsk_msg n t2) ( onlyin_pkrsk_msg n t3)))\n    | bver t1 t2 t3 => (andb (onlyin_pkrsk_msg n t1) (andb (onlyin_pkrsk_msg n t2) ( onlyin_pkrsk_msg n t3)))\n    | bacc t1 t2 t3 => (andb (onlyin_pkrsk_msg n t1) (andb (onlyin_pkrsk_msg n t2) ( onlyin_pkrsk_msg n t3)))\n    | _ => true\n  end\nwith onlyin_pkrsk_msg (n : nat )(t:message) : bool :=\n       match t with\n         | if_then_else_M b t1 t2 => (andb (onlyin_pkrsk_bol n b) (andb (onlyin_pkrsk_msg n t1) ( onlyin_pkrsk_msg n t2)))\n         | (Mvar n') =>  if (beq_nat n' n) then false else true\n         | N n'=> if (beq_nat n' n) then false else true\n         | exp t1 t2 t3 =>  (andb (onlyin_pkrsk_msg n t1) (andb (onlyin_pkrsk_msg n t2) ( onlyin_pkrsk_msg n t3)))\n         | pair t1 t2 =>  andb (onlyin_pkrsk_msg n t1) ( onlyin_pkrsk_msg n t2)\n         | pi1 t1 => match t1 with\n                       | (k (N n)) => true\n                       | _ => true\n                     end\n         | pi2 t1 => match t1 with\n                       | (k (N n)) => true\n                       | _ => true\n                     end\n         | ggen t1 =>  (onlyin_pkrsk_msg n t1)\n         | act t1 =>  (onlyin_pkrsk_msg n t1)\n         | rr t1 =>  (onlyin_pkrsk_msg n t1)\n         | rs t1 =>  (onlyin_pkrsk_msg n t1)\n         | L t1 =>  (onlyin_pkrsk_msg n t1)\n         | m t1 =>  (onlyin_pkrsk_msg n t1)\n         | enc t1 t2 t3 =>  (andb (onlyin_pkrsk_msg n t1) (andb (onlyin_pkrsk_msg n t2) ( onlyin_pkrsk_msg n t3)))\n         | dec t1 t2 => andb (onlyin_pkrsk_msg n t1) ( onlyin_pkrsk_msg n t2)\n         | k t1 =>  (onlyin_pkrsk_msg n t1) \n         | nc t1 => (onlyin_pkrsk_msg n t1) \n         | to t1 => (onlyin_pkrsk_msg n t1) \n         | reveal t1 => (onlyin_pkrsk_msg n t1) \n         | sign t1 t2 => andb (onlyin_pkrsk_msg n t1) ( onlyin_pkrsk_msg n t2)\n         (** Foo function protocol *)\n         | commit t1 t2 t3 => (andb (onlyin_pkrsk_msg n t1) (andb (onlyin_pkrsk_msg n t2) ( onlyin_pkrsk_msg n t3)))\n         | open t1 t2 t3 => (andb (onlyin_pkrsk_msg n t1) (andb (onlyin_pkrsk_msg n t2) ( onlyin_pkrsk_msg n t3)))\n         | blind t1 t2 => andb (onlyin_pkrsk_msg n t1) ( onlyin_pkrsk_msg n t2)\n         | unblind t1 t2 => andb (onlyin_pkrsk_msg n t1) ( onlyin_pkrsk_msg n t2)\n         | v t1 => (onlyin_pkrsk_msg n t1)\n         | bsign t1 t2 => andb (onlyin_pkrsk_msg n t1) ( onlyin_pkrsk_msg n t2)\n         | f l => (@forallb message (onlyin_pkrsk_msg n) l)\n         | _ => true\n       end.\n\nEval compute in (onlyin_pkrsk_msg 1  (f [ (k (N 1))])).\n\n(** [oursum] *)\n\nDefinition onlyin_pkrsk_os (n : nat )(t:oursum) : bool :=\n  match t with\n    | msg t1 => (onlyin_pkrsk_msg n t1)\n    | bol b => (onlyin_pkrsk_bol n b)\n  end.\n\n(** [mylist m] for some m *)\n\nFixpoint onlyin_pkrsk_mylist (n : nat ){m}(t: mylist m) : bool :=\n  match t with\n    | []  => true\n    | h:: t=> (andb (onlyin_pkrsk_os n h) (onlyin_pkrsk_mylist n t))\n  end.\n\n(** Check if sk(N n) occurs as [(sign (sk (K n)) _)]. *)\n\nFixpoint skn_in_sign_bol (n : nat )(t:Bool) : bool :=\n  match t with \n    | EQ_B  b1 b2 =>  (andb (skn_in_sign_bol n b1)  (skn_in_sign_bol n b2))\n    | EQ_M t1 t2 => andb (skn_in_sign_msg n t1) ( skn_in_sign_msg n t2)\n    | if_then_else_B t1 t2 t3 =>  (andb (skn_in_sign_bol n t1) (andb (skn_in_sign_bol n t2) ( skn_in_sign_bol n t3)))\n    | EQL t1 t2 =>  (andb (skn_in_sign_msg n t1) ( skn_in_sign_msg n t2))\n    | ver t1 t2 t3 => (andb (skn_in_sign_msg n t1) (andb (skn_in_sign_msg n t2) ( skn_in_sign_msg n t3)))\n    | bver t1 t2 t3 => (andb (skn_in_sign_msg n t1) (andb (skn_in_sign_msg n t2) ( skn_in_sign_msg n t3)))\n    | bacc t1 t2 t3 => (andb (skn_in_sign_msg n t1) (andb (skn_in_sign_msg n t2) ( skn_in_sign_msg n t3)))\n    | _  => true\n end\nwith skn_in_sign_msg (n : nat )(t:message) : bool :=\n       match t with \n         | if_then_else_M b t1 t2 => (andb (skn_in_sign_bol n b) (andb (skn_in_sign_msg n t1) ( skn_in_sign_msg n t2)))\n         | exp t1 t2 t3 =>  (andb (skn_in_sign_msg n t1) (andb (skn_in_sign_msg n t2) ( skn_in_sign_msg n t3)))\n         | pair t1 t2 =>  andb (skn_in_sign_msg n t1) ( skn_in_sign_msg n t2)\n         | pi2 t1 => (skn_in_sign_msg n t1)\n         | pi1 t1 => (skn_in_sign_msg n t1)\n         | ggen t1 =>  (skn_in_sign_msg n t1)\n         | act t1 =>  (skn_in_sign_msg n t1)\n         | rr t1 =>  (skn_in_sign_msg n t1)\n         | rs t1 =>  (skn_in_sign_msg n t1)\n         | L t1 =>  (skn_in_sign_msg n t1)\n         | m t1 =>  (skn_in_sign_msg n t1)\n         |enc t1 t2 t3 =>  (andb (skn_in_sign_msg n t1) (andb (skn_in_sign_msg n t2) ( skn_in_sign_msg n t3)))\n         |dec t1 t2 => andb (skn_in_sign_msg n t1) ( skn_in_sign_msg n t2)\n         | k t1 =>  (skn_in_sign_msg n t1) \n         | nc t1 => (skn_in_sign_msg n t1) \n         | to t1 => (skn_in_sign_msg n t1) \n         | reveal t1 => (skn_in_sign_msg n t1) \n         | sign t1 t2 => andb (match t1 with \n                                 | pi2 (k (N n')) => if  (beq_nat n' n) then true else true\n                                 | _ => true\n                               end) (skn_in_sign_msg n t2) \n         (** Foo function protocol *)\n         | commit t1 t2 t3 => (andb (skn_in_sign_msg n t1) (andb (skn_in_sign_msg n t2) ( skn_in_sign_msg n t3)))\n         | open t1 t2 t3 => (andb (skn_in_sign_msg n t1) (andb (skn_in_sign_msg n t2) ( skn_in_sign_msg n t3)))\n         | blind t1 t2 => andb (skn_in_sign_msg n t1) ( skn_in_sign_msg n t2)\n         | unblind t1 t2 => andb (skn_in_sign_msg n t1) ( skn_in_sign_msg n t2)\n         | v t1 => (skn_in_sign_msg n t1) \n         | f  l => (@forallb message (skn_in_sign_msg n) l)\n         | bsign t1 t2 => andb (match t1 with \n                                 | pi2 (k (N n')) => if  (beq_nat n' n) then true else true\n                                 | _ => true\n                                end) (skn_in_sign_msg n t2)\n         | _ => true\n       end.\n\n(** [oursum]  *)\n\nDefinition  skn_in_sign_os (n : nat )(t:oursum) : bool :=\n  match t with\n    | msg t1 => (skn_in_sign_msg n t1)\n    | bol b => (skn_in_sign_bol n b)\n  end.\n\n(** [mylist m] *)\n\nFixpoint  skn_in_sign_mylist (n : nat ){m}(t: mylist m) : bool :=\n  match t with\n    | []  => true\n    | h:: t => (andb (skn_in_sign_os n h)  (skn_in_sign_mylist  n t)) \n  end.\nEval compute in (sk (N 2)).\nEval compute in skn_in_sign_msg 1 (sign (sk (N 2)) O).\n\n(** List of subterms of the form [sign ( sk(N n), t1),.....,sign ( sk(N n), tl)]. *)\n\nFixpoint list_skn_in_sign (n:nat) (l:list message) : list message :=\n  match l with \n    | nil => nil\n    | cons h t => (app (match h with \n                          | sign (pi2 (k (N n'))) _ => if (beq_nat n' n) then (cons h nil) else nil\n                          | _ => nil\n                        end) \n                       (list_skn_in_sign n t))\n  end.\nEval compute in ( list_skn_in_sign 1 (subtrmls_msg (sign (if_then_else_M TRue (dec O (sk (N 1))) O) new))).\n\n\n", "meta": {"author": "ajayeeralla", "repo": "compSoundProofsWOracleMoves", "sha": "8480855887a9092d16dc183ce6ed19315a3ffa96", "save_path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves", "path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves/compSoundProofsWOracleMoves-8480855887a9092d16dc183ce6ed19315a3ffa96/definitions1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220787, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6684742308374823}}
{"text": "(* Code for Software Foundations, Chapter 5: Poly: Polymorphism and Higher-Order Functions *)\n\nRequire Import Arith.\nRequire Import List.\n\n(* mumble_grumble *)\n\nModule MumbleGrumble.\n\nInductive mumble : Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\n\nInductive grumble (T : Type) : Type :=\n  | d : mumble -> grumble T\n  | e : T -> grumble T.\n\n(* Which of the following are well-typed elements of grumble X for some type X ?\n  d (b a 5)        : F\n  d mumble (b a 5) : T\n  d bool (b a 5)   : T\n  e bool true      : T\n  e mumble (b c 0) : T\n  e bool (b c 0)   : F\n  c                : T\n*)\n\nEnd MumbleGrumble.\n\n(* poly_exercises *)\n\nTheorem app_nil_r :\n  forall X : Type, forall l : list X, l ++ nil = l.\nProof.\n  induction l.\n  + simpl; reflexivity.\n  + simpl.\n    pattern l at 2.\n    rewrite IHl.\n    reflexivity.\nQed.\n\nTheorem app_nil_l :\n  forall X : Type, forall l : list X, nil ++ l = l.\nProof.\n  reflexivity.\nQed.\n\nLemma cons_injection :\n  forall (A : Type) (n : A) (l1 l2 : list A), l1 = l2 -> n :: l1 = n :: l2.\nProof.\n  intros A n l1 l2.\n  induction l1, l2.\n  + simpl; reflexivity.\n  + inversion 1.\n  + inversion 1.\n  + intros h1; rewrite h1; reflexivity.\nQed.\n\nTheorem app_assoc :\n  forall (A : Type) (l m n : list A), l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  induction l, m.\n  + simpl; reflexivity.\n  + simpl; reflexivity.\n  + simpl; rewrite app_nil_r; reflexivity.\n  + simpl.\n    intros n.\n    apply (cons_injection A a (l ++ a0 :: m ++ n) ((l ++ a0 :: m) ++ n)).\n    rewrite <- IHl; trivial.\nQed.\n\nTheorem app_length :\n  forall (X : Type) (l1 l2 : list X), length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros X l1 l2.\n  induction l1.\n  + simpl; reflexivity.\n  + simpl; rewrite IHl1; reflexivity.\nQed.\n\n(* more_poly_exercises *)\n\nTheorem rev_app_distr :\n  forall (X : Type) (l1 l2 : list X), rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros X l1 l2.\n  induction l1, l2.\n  + simpl; reflexivity.\n  + simpl; rewrite app_nil_r; reflexivity.\n  + simpl; repeat rewrite app_nil_r; reflexivity.\n  + simpl.\n    rewrite app_assoc.\n    rewrite IHl1.\n    assert(app_xs_r : forall (l1 l2 l3 : list X), l1 = l2 -> l1 ++ l3 = l2 ++ l3).\n    - intros l1' l2' l3' h1.\n      rewrite h1; reflexivity.\n    - apply app_xs_r.\n      apply app_xs_r.\n      simpl; reflexivity.\nQed.\n\nTheorem rev_involutive :\n  forall (X : Type) (l : list X), rev (rev l) = l.\nProof.\n  induction l.\n  + simpl; reflexivity.\n  + simpl.\n    rewrite rev_app_distr.\n    rewrite IHl.\n    simpl; reflexivity.\nQed.\n\n(* combine_checks *)\n\n(*\nCheck @combine.\nEval compute in combine (1::2::nil) (false::false::true::true::nil).\n*)\n\n(* split *)\nFixpoint split {X Y : Type} (l : list (X * Y)) : (list X) * (list Y) :=\n  match l with\n    | nil        => (nil, nil)\n    | (a, b)::xs =>\n      let (u, v) := split xs\n      in (a::u, b::v)\n  end.\n\n(* Eval compute in split ((1, false)::(2, false)::nil). *)\n\n(* hd_error_poly *)\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n    | nil   => None\n    | x::xs => Some x\n  end.\n\n(* filter_even_gt7 *)\n\nFixpoint filter {X : Type} (test : X -> bool) (l : list X) {struct l} : list X :=\n  match l with\n    | nil   => nil\n    | x::xs => let rest := filter test xs\n      in match test x with\n        | true  => x :: rest\n        | false => rest\n      end\n  end.\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun x => andb (Nat.even x) (Nat.ltb 7 x)) l.\n\n(* partition *)\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\n(* map_rev *)\n\nFixpoint map {X Y : Type} (f : X -> Y) (l : list X) {struct l} : list Y :=\n  match l with\n    | nil   => nil\n    | x::xs => f x :: map f xs\n  end.\n\nLemma map_append_eq :\n  forall (X Y : Type) (f : X -> Y) (l1 l2 : list X), map f (l1 ++ l2) = map f l1 ++ map f l2.\nProof.\n  intros X Y f l1 l2.\n  induction l1.\n  + simpl; reflexivity.\n  + simpl; rewrite IHl1; reflexivity.\nQed.\n\nTheorem map_rev :\n  forall (X Y : Type) (f : X -> Y) (l : list X), map f (rev l) = rev (map f l).\nProof.\n  induction l.\n  + simpl; reflexivity.\n  + simpl.\n    rewrite map_append_eq.\n    simpl.\n    rewrite IHl.\n    reflexivity.\nQed.\n\n(* flat_map *)\n\nFixpoint flat_map {X Y : Type} (f : X -> list Y) (l : list X) {struct l} : list Y :=\n  match l with\n    | nil   => nil\n    | x::xs => f x ++ flat_map f xs\n  end.\n\nDefinition option_map {X Y : Type} (f : X -> Y) (x : option X) : option Y :=\n  match x with\n    | None    => None\n    | Some x' => Some (f x')\n  end.\n\n(* fold_types_different *)\n\nFixpoint fold {X Y : Type} (f : X -> Y -> Y) (l : list X) (a : Y) : Y :=\n  match l with\n    | nil   => a\n    | x::xs => f x (fold f xs a)\n  end.\n\n(* The type X and Y are different:\n  X: nat\n  Y: bool. *)\nDefinition all_even (xs : list nat) : bool :=\n  fold (fun x acc => andb acc (Nat.even x)) xs true.\n\n(* fold_length *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ acc => S acc) l O.\n\nTheorem fold_length_correct :\n  forall (X : Type) (l : list X), fold_length l = length l.\nProof.\n  induction l.\n  + reflexivity.\n  + simpl.\n    rewrite <- IHl.\n    reflexivity.\nQed.\n\n(* fold_map *)\n\nDefinition fold_map {X Y : Type} (f : X -> Y) (l : list X) : list Y :=\n  fold (fun x acc => f x :: acc) l nil.\n\nTheorem fold_map_correct :\n  forall (X Y : Type) (f : X -> Y) (l : list X), fold_map f l = map f l.\nProof.\n  induction l.\n  + simpl; reflexivity.\n  + simpl; rewrite <- IHl.\n    reflexivity.\nQed.\n\n(* currying *)\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) (t : X * Y) : Z :=\n  match t with\n    | (x, y) => f x y\n  end.\n\nTheorem uncurry_curry :\n  forall (X Y Z : Type) (f : X -> Y -> Z) x y, prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  reflexivity.\nQed.\n\nTheorem curry_uncurry :\n  forall (X Y Z : Type) (f : (X * Y) -> Z) t, prod_uncurry (prod_curry f) t = f t.\nProof.\n  induction t.\n  simpl; reflexivity.\nQed.\n\n(* church_numerals *)\n\nModule Church.\n\nDefinition church :=\n  forall X : Type, (X -> X) -> (X -> X).\n\n(* zero *)\nDefinition zero : church :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(* one *)\nDefinition one : church :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(* two *)\nDefinition two : church :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(* three *)\nDefinition three : church :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f (f x)).\n\n(* succ n *)\nDefinition succ (n : church) : church :=\n  fun (X : Type) (f : X -> X) (x : X) => f ((n X f) x).\n\n(* n + m *)\nDefinition plus (n m : church) : church :=\n  fun (X : Type) (f : X -> X) (x : X) => (m X f) ((n X f) x).\n\n(* n * m *)\nDefinition mult (n m : church) : church :=\n  fun (X : Type) (f : X -> X) => m X (n X f).\n\n(* n ^ m *)\nDefinition exp (n m : church) : church :=\n  fun (X : Type) => (m (X -> X)) (n X).\n\n(*\nEval compute in exp two three.\nEval compute in exp three two.\n*)\n\nEnd Church.\n\nModule ChurchWithFold.\n\n(* TODO : how to represent church numerals in Coq as the paper:\n  <Church numerals, Twice!>. *)\n\nEnd ChurchWithFold.\n\n\n", "meta": {"author": "sighingnow", "repo": "amazing-coq", "sha": "70acce0bac267f76f696b0f0a35865622b6a0ee8", "save_path": "github-repos/coq/sighingnow-amazing-coq", "path": "github-repos/coq/sighingnow-amazing-coq/amazing-coq-70acce0bac267f76f696b0f0a35865622b6a0ee8/software-foundations/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.6684280313914016}}
{"text": "Require Export P03.\n\n\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. induction l1.\n  - reflexivity.\n  - simpl. rewrite -> IHl1. 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/03/P04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.6684280204892651}}
{"text": "(* ***************************************************************** *)\n(*                                                                   *)\n(* Released: 2021/05/24.                                             *)\n(* Due: 2021/05/28, 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 (Assignment9.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 \"Assignment9.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.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\nRequire Import PL.RTClosure.\nRequire Import PL.Lambda.\nImport LambdaIB.\nLocal Open Scope Z.\nLocal Open Scope string.\nNotation \"[ x ; .. ; y ]\" := (@cons tm x .. (@cons tm y (@nil tm)) ..).\n\n(* ################################################################# *)\n(** * Lambda Expressions *)\n\n(** **** Exercise: 2 stars, standard *)\n\n(** Please describe the evaluation process of\n\n    - [app\n         (app\n            (abs \"f\" (abs \"x\" (app \"f\" \"x\")))\n            (abs \"x\" (app (app Omult \"x\") \"x\")))\n         2].\n\n    If writing this expression in python, it is:\n\n    - [(lambda f: lambda x: f (x)) (lambda x: x * x) (2)].\n\n    Remark: your answer should be a list of lambda expressions, the first of\n    which is the original expression and the last of which is the evaluation\n    result. This list should describe the evaluation step by step.\n*)\n\nDefinition process_1: list tm :=\n[\n  app\n    (app\n      (abs \"f\" (abs \"x\" (app \"f\" \"x\")))\n      (abs \"x\" (app (app Omult \"x\") \"x\")))\n    2;\n  app\n    (abs \"x\"\n      (app (abs \"x\" (app (app Omult \"x\") \"x\")) \"x\"))\n    2;\n  app (abs \"x\" (app (app Omult \"x\") \"x\")) 2;\n  app (app Omult 2) 2;\n  4\n].\n(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n(** [] *)\n\n(** **** Exercise: 1 star, standard *)\n\n(** Now you know the evaluation result is 4. Please prove it in Coq. *)\n\nExample result_1:\n  clos_refl_trans step\n    (app\n       (app (abs \"f\" (abs \"x\" (app \"f\" \"x\")))\n            (abs \"x\" (app (app Omult \"x\") \"x\")))\n       2)\n    4.\nProof.\n  repeat\n    (etransitivity_1n; [apply next_state_sound; reflexivity | try simpl subst]).\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard *)\n\n(** We usually call [ abs \"f\" (abs \"x\" (app \"f\" \"x\")) ] the \"apply\" function. In\n    other words, it APPLIES function \"f\" on \"x\". Please prove that it is\n    well-typed. *)\n\nExample type_1: forall T1 T2: ty,\n  empty_context |-\n    (abs \"f\" (abs \"x\" (app \"f\" \"x\"))) \\in ((T1 ~> T2) ~> T1 ~> T2).\nProof.\n  intros.\n  apply T_abs.\n  apply T_abs.\n  eapply T_app; constructor; reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, standard *)\n\n(** Please describe the evaluation process of\n\n    - [app\n         (abs \"x\"\n            (app (app (app Oifthenelse (app (app Oeq \"x\") 0)) 0) 1))\n         2].\n\n    If writing this expression in Coq, it is like:\n\n    - [ (fun x => if x ?= 0 then 0 else 1) 2 ].\n\n*)\n\nDefinition process_2: list tm :=\n[\n  app\n    (abs \"x\"\n      (app (app (app Oifthenelse (app (app Oeq \"x\") 0)) 0) 1))\n    2;\n  app\n    (app (app Oifthenelse (app (app Oeq 2) 0)) 0)\n    1;\n  app (app (app Oifthenelse false) 0) 1;\n  1\n]\n(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *).\n(** [] *)\n\n(** **** Exercise: 2 stars, standard *)\n\n(** In the example above, the function\n\n    - [ abs \"x\" (app (app (app Oifthenelse (app (app Oeq \"x\") 0)) 0) 1) ]\n\n    is usually called the \"test_zero\" function. If it applies to zero, the\n    result is zero. If it applies to non-zero, the result is one. Of course,\n    it has type [TInt ~> TInt]. But, if you write it in a wrong way, you can\n    easily make it ill-typed. For example, the following expression writes:\n    if \"x\" is non-zero, return false instead of one. This must cause a chaos\n    in types.\n\n    Hint: in order to prove the following property, you need to use [inversion]\n    to trace back through the type derivation. You may use\n\n    - [deduce_types_from_head]\n\n    to speed up. But it will only solve parts, but not all, of the problem. *)\n\nLemma ill_typed_example: forall Gamma T,\n  Gamma |-\n    abs \"x\" (app (app (app Oifthenelse (app (app Oeq \"x\") 0)) 0) false) \\in T ->\n  False.\nProof.\n  intros.\n  inversion H; subst.\n  deduce_types_from_head H4.\n  inversion H3; subst.\n  inversion H1; subst.\n  inversion H5; subst.\n  inversion H7.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard *)\n\n(** It is a nice property that the small step semantics of lambda expressions\n    (as we introduced in lectures) are type safe. In other words, for any\n    [t: tm] and [T: ty], if\n\n    - [empty_context |- t \\in T]\n\n    then evaluating [t] must be safe. But, is the reverse direction also true?\n    In other words, is there such an expression [t] that evaluating [t] is safe\n    but no type [T] makes [empty_context |- t \\in T] true.\n\n    1. There exists such [t].\n\n    2. There does not exist such [t]. *)\n\nDefinition my_choice: Z := 1.\n(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n(** [] *)\n\n(** You should start your proof with either one of the following:\n\n    - [ left; split; [reflexivity |] ]\n\n    - [ right; reflexivity ]\n\n*)\n\nLemma reverse_of_type_safe:\n  (my_choice = 1 /\\\n   exists t t', clos_refl_trans step t t' /\\ tm_halt t' /\\\n                (forall T, empty_context |- t \\in T -> False)) \\/\n  (my_choice = 2).\nProof.\n  left; split; [reflexivity |].\n  exists (app\n           (abs \"x\" (app (app (app Oifthenelse (app (app Oeq \"x\") 0)) 0) false))\n           1),\n         false.\n  repeat split.\n  2: constructor.\n  + repeat\n    (etransitivity_1n; [apply next_state_sound; reflexivity | try simpl subst]).\n    reflexivity.\n  + intros.\n    inversion H; subst.\n    apply ill_typed_example in H3.\n    exact H3.\nQed.\n\n(* 2021-05-24 21:19 *)\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/Assignment9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.6684280186722424}}
{"text": "Require Import FinTypes.\n\nDefinition Cardinality (F: finType) := | elem F |.\n\n(** * Dupfreeness *)\n(* Proofs about dupfreeness *)\n\n\nLemma dupfree_countOne (X: eqType) (A: list X) : (forall x, count A x <= 1) -> dupfree A.\nProof.\n  induction A.\n  - constructor.\n  - intro H. constructor.\n    + cbn in H.  specialize (H a). deq a. assert (count A a = 0) by omega. now apply countZero.\n    + apply IHA. intro x. specialize (H x). cbn in H. dec; omega.\nQed.\n\nLemma dupfree_elements (X: finType) : dupfree (elem X).\nProof.\n  destruct X as [X [A AI]]. assert (forall x, count A x <= 1) as H'.\n  {\n    intro x. specialize (AI x). omega.\n  }\n  now apply dupfree_countOne.  \nQed.\n\nLemma dupfree_length (X: finType) (A: list X) : dupfree A -> |A| <= Cardinality X.\nProof.\n  unfold Cardinality.  intros D.\n  rewrite <- (dupfree_card D). rewrite <- (dupfree_card (dupfree_elements X)).\n  apply card_le. apply allSub.\nQed.\n\nLemma disjoint_concat X (A: list (list X)) (B: list X) : (forall C, C el A -> disjoint B C) -> disjoint B (concat A).\nProof.\n  intros H. induction A.\n  - cbn. auto.\n  - cbn. apply disjoint_symm. apply disjoint_app. split; auto using disjoint_symm.\nQed.\n\nLemma dupfree_concat (X: Type) (A: list (list X)) : (forall B, B el A -> dupfree B) /\\ (forall B C, B <> C -> B el A -> C el A -> disjoint B C) -> dupfree A -> dupfree (concat A).\nProof.\n  induction A.\n  - constructor.\n  - intros [H H'] D. cbn. apply dupfree_app.\n    + apply disjoint_concat. intros C E. apply H'; auto. inv D. intro G; apply H2. now subst a.\n    + now apply H.\n    + inv D; apply IHA; auto.\nQed.     \n\n(* (** * Proofs about Cardinality *) *)\n\n(* Lemma Card_positiv (X: finType) (x:X) : Cardinality X > 0. *)\n(* Proof. *)\n(*   pose proof (elem_spec x).  unfold Cardinality.  destruct (elem X). *)\n(*   - contradiction H. *)\n(*   - cbn. omega. *)\n(* Qed.  *)\n\n(* Lemma Cardinality_card_eq (X: finType): card (elem X) = Cardinality X. *)\n(* Proof. *)\n(*   apply dupfree_card. apply dupfree_elements. *)\n(* Qed. *)\n\n(* Lemma card_upper_bound (X: finType) (A: list X): card A <= Cardinality X. *)\n(* Proof. *)\n(*  rewrite <-  Cardinality_card_eq. apply card_le. apply allSub. *)\n(* Qed.   *)\n\n\n(* Lemma injective_dupfree (X: finType) (Y: Type) (A: list X) (f: X -> Y) : injective f -> dupfree (getImage f). *)\n(* Proof. *)\n(*   intro inj. unfold injective in inj. *)\n(*   unfold getImage. apply dupfree_map. *)\n(*   - firstorder. *)\n(*   - apply dupfree_elements. *)\n(* Qed. *)\n\n(* Theorem pidgeonHole_inj (X Y: finType) (f: X -> Y) (inj: injective f): Cardinality X <= Cardinality Y. *)\n(* Proof. *)\n(*   rewrite <- (getImage_length f). apply dupfree_length. apply (injective_dupfree (elem X) inj). *)\n(* Qed. *)\n\n(* Lemma surj_sub (X Y: finType) (f: X -> Y) (surj: surjective f): elem Y <<= getImage f. *)\n(* Proof. *)\n(* intros y E. specialize (surj y). destruct surj as [x H]. subst y. apply getImage_in. *)\n(* Qed. *)\n\n(* Theorem pidgeonHole_surj (X Y: finType) (f: X -> Y) (surj: surjective f): Cardinality X >= Cardinality Y. *)\n(* Proof. *)\n(*   rewrite <- (getImage_length f). rewrite <- Cardinality_card_eq. *)\n(*     pose proof (card_le (surj_sub surj)) as H. pose proof (card_length_leq (getImage f)) as H'. omega. *)\n(* Qed. *)\n\n(* Lemma eq_iff (x y: nat) : x >= y /\\ x <= y -> x = y. *)\n(* Proof. *)\n(*   omega. *)\n(* Qed. *)\n\n(* Corollary pidgeonHole_bij (X Y: finType) (f: X -> Y) (bij: bijective f): *)\n(*   Cardinality X = Cardinality Y. *)\n(* Proof. *)\n(*   destruct bij as [inj surj]. apply eq_iff. split. *)\n(*   - now eapply pidgeonHole_surj. *)\n(*   - eapply pidgeonHole_inj; eauto. *)\n(* Qed.     *)\n\n(* Lemma Prod_Card (X Y: finType) : Cardinality (X (x) Y) = Cardinality X * Cardinality Y. *)\n(* Proof. *)\n(*   cbn.  unfold prodLists. unfold Cardinality. induction (elem X).  *)\n(*   - reflexivity. *)\n(*   - cbn. rewrite app_length. rewrite IHl. f_equal. apply map_length. *)\n(* Qed.     *)\n\n(* Lemma Option_Card (X: finType) : Cardinality (? X) = S(Cardinality X). *)\n(* Proof. *)\n(*   cbn. now rewrite map_length. *)\n(* Qed. *)\n\n(* Lemma SumCard (X Y: finType) : Cardinality (finType_sum X Y) = Cardinality X + Cardinality Y. *)\n(* Proof. *)\n(*   unfold Cardinality. cbn. rewrite app_length. unfold toSumList1, toSumList2. now  repeat rewrite map_length. *)\n(* Qed. *)\n\n(* Lemma extPow_length X Y L P: |@extensionalPower X Y L P| = | L |. *)\n(* Proof. *)\n(*   induction L. *)\n(*   -  reflexivity. *)\n(*   - simpl. f_equal. apply IHL. *)\n(* Qed. *)\n\n\n(* Lemma concat_map_length (X: Type) (A: list X) (B: list (list X)) : *)\n(* | concat (map (fun x => map (cons x) B) A) |= |A| * |B|. *)\n(* Proof. *)\n(*   induction A. *)\n(*   - reflexivity. *)\n(*   - cbn. rewrite app_length. rewrite map_length. congruence. *)\n(* Qed.     *)\n  \n(* Lemma images_length Y (A: list Y) n : |images A n| = (|A| ^ n)%nat. *)\n(* Proof. *)\n(*   induction n. *)\n(*   - reflexivity. *)\n(*   - cbn. rewrite concat_map_length.  now rewrite IHn. *)\n(* Qed. *)\n\n(* Lemma Vector_Card (X Y: finType): Cardinality (Y ^ X) = (Cardinality Y ^ (Cardinality X ))%nat. *)\n(* Proof. *)\n(*   cbn. rewrite extPow_length. now rewrite images_length. *)\n(* Qed. *)\n\n", "meta": {"author": "uds-psl", "repo": "base-library", "sha": "d9f3b8abf379d4c12049dd25c8d1fdf1973dab48", "save_path": "github-repos/coq/uds-psl-base-library", "path": "github-repos/coq/uds-psl-base-library/base-library-d9f3b8abf379d4c12049dd25c8d1fdf1973dab48/FiniteTypes/Cardinality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.6684036924153505}}
{"text": "Inductive roseTree := node (h:list roseTree).\n\nRequire Import List.\nImport ListNotations.\n\n\n\nScheme nat_induct := Induction for nat Sort Type.\nPrint nat_induct.\n\nFixpoint maxList (xs:list nat) : nat :=\nmatch xs with\n| [] => 0\n| y::ys => max y (maxList ys)\nend.\n\nFixpoint depth (t:roseTree) : nat :=\nmatch t with \n| node [] => 0\n| node xs => 1+maxList(map depth xs)\nend.\n\nFixpoint size (t:roseTree) : nat.\ndestruct t.\nrefine (S _).\ninduction h.\n- exact 0.\n- exact (size a + IHh).\nDefined.\n\nDefinition ex :=\nnode [node []; node [node[];node[];node[]]].\n\nCompute (depth ex).\nCompute (size ex).\n\nDefinition roseTree_induct : \nforall (P:roseTree -> Prop),\n(forall xs, (forall t, In t xs -> P t) -> P (node xs)) ->\nforall r, P r.\nProof.\n    intros P H.\n    refine (fix f r := _).\n    destruct r.\n    apply H.\n    induction h.\n    - intros _ [].\n    - intros t [<-|?].\n        + apply f.\n        + now apply IHh.\nDefined.\n\nRequire Import Lia.\nFrom Hammer Require Import Hammer.\n\nLemma depth_eq x xs: depth (node(x::xs)) = max (1+depth x) (depth (node xs)).\nProof.\n    cbn [depth map maxList].\n    destruct xs;cbn [map depth maxList];lia.\nQed.\n\nLemma size_eq x xs: size(node(x::xs)) = size(x) + size(node xs).\nProof.\n    cbn;lia.\nQed.\n\n\nGoal forall t, depth t < size t.\nProof.\n    apply roseTree_induct.\n    induction xs;intros.\n    - cbn;lia.\n    - \n    (* hammer. *)\n    rewrite depth_eq, size_eq.\n    assert(depth a < size a).\n    {\n        apply H;now left.\n    }\n    assert(depth (node xs) < size (node xs)).\n    {\n        apply IHxs;intros;apply H;now right.\n    }\n    lia.\nQed.\n\n\n\nGoal forall t, 1+depth t <= size t.\nProof.\n    induction t.\n    induction h;trivial.\n    - \n    destruct h;trivial.\n    simpl.\nRestart.\n    apply roseTree_induct.\n    intros [] H;trivial.\n    simpl.", "meta": {"author": "uds-psl", "repo": "metacoq-nested-induction", "sha": "0c523566290fe99da46a3e74da8652f02d7a3dd6", "save_path": "github-repos/coq/uds-psl-metacoq-nested-induction", "path": "github-repos/coq/uds-psl-metacoq-nested-induction/metacoq-nested-induction-0c523566290fe99da46a3e74da8652f02d7a3dd6/source/other_code/rose_test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.6684036887347848}}
{"text": "(** * Contraction\n\n    可縮性に関する定理や定義。 *)\n\nRequire Import Basis .\nRequire Import Path .\nRequire Import Homotopy .\n\n(** 戦術を使う。 *)\nDeclare ML Module \"ltac_plugin\" .\nSet Default Proof Mode \"Classic\" .\n\n(** 記法を使う。 *)\nImport Basis.Notation .\nImport Basis.Notation.Path .\n\n\n(** [center] と [x : A] の間に道がある。 *)\nDefinition center_path\n  {A : Type} (cA : contr A) (x : A) : center cA = x .\nProof.\n exact (dsnd cA x) .\nDefined.\n\n(** [A] が [contr] であれば [x y : A] の間に道がある。 *)\nDefinition path_contr\n  {A : Type} (cA : contr A) (x y : A) : x = y .\nProof.\n refine (coninv (y := center cA) _ _) .\n -\n  exact (center_path cA x) .\n -\n  exact (center_path cA y) .\nDefined.\n\n(** [A] が [IC : contr A] であれば、その二点の間の道 [p : paths x y] は\n    [path_contr IC x y] からの道を持つ。 *)\nDefinition K_path_contr\n  {A : Type} (cA : contr A) {x y : A} (p : x = y)\n  : path_contr cA x y = p .\nProof.\n revert y p .\n refine (@paths_elim A x ?[ex_P] _) .\n exact (coninv_pp (center_path cA x)) .\nDefined.\n\n(** [A] が [contr] であれば [p q : paths x y] の間に道がある。 *)\nDefinition path_path_contr\n  {A : Type} (cA : contr A) {x y : A} (p q : x = y) : p = q .\nProof.\n refine (coninv (y := path_contr cA x y) _ _) .\n -\n  exact (K_path_contr cA p) .\n -\n  exact (K_path_contr cA q) .\nDefined.\n\n(** [A] が [contr] であれば、その二点の間の [paths] も [contr] である。 *)\nDefinition contr_paths_contr\n  {A : Type} (cA : contr A) (x y : A) : contr (x = y) .\nProof.\n refine (dpair (path_contr cA x y) _) .\n exact (K_path_contr cA) .\nDefined.\n\n\n(** [x] を始点とする道の集まり。 *)\nDefinition based_paths {X : Type} (x : X) : Type := sigma y, x = y .\n\n(** [p : based_paths x] は [dpair x idpath] からの道を持つ。 *)\nDefinition path_based_paths\n  {X : Type} {x : X} (p : based_paths x)\n  : dpair x 1 = p .\nProof.\n refine (dsum_elim _ p) .\n refine (@paths_elim X x _ _) .\n exact 1 .\nDefined.\n\n(** [based_paths] は [contr] である。 *)\nDefinition contr_based_paths\n  {X : Type} (x : X) : contr (based_paths x) .\nProof.\n refine (dpair (dpair x 1) _) .\n exact path_based_paths .\nDefined.\n\n(** [based_paths] の除去子。 *)\nDefinition based_paths_elim\n  {A : Type} (a : A) (P : based_paths a -> Type)\n  (c : forall a' p, P (dpair a' p))\n  (x : based_paths a) : P x .\nProof.\n revert x .\n refine (dsum_elim _) .\n exact c .\nDefined.\n\n(** [paths_elim] を [based_paths] を使って書き直したもの。 *)\nDefinition paths_elim_by_based_paths\n  {A : Type} (a : A) (P : based_paths a -> Type)\n  (c : P (dpair a 1))\n  (x : based_paths a) : P x .\nProof.\n revert x .\n refine (dsum_elim _) .\n refine (@paths_elim A a _ _) .\n exact c .\nDefined.\n\n\n(** 定義域 (domain) が [contr] である関数は、\n    命題的定値 (propositionally constant) である。 *)\nDefinition contr_dom_constant\n  {A B : Type} (cA : contr A) (f : A -> B) {x y : A}\n  : f x = f y .\nProof.\n refine (ap f _) .\n exact (path_contr cA x y) .\nDefined.\n\n(** [X] が [contr] で [r : Y -> X] が引き込み (retraction) であれば、\n    [Y] もまた [contr] である。\n\n    [s : Y -> X] は [Y -> unit] と同じように [const] によって自明に\n    与えられることに注意せよ。 *)\nDefinition contr_retract\n  {X Y} (cX : contr X) (r : X -> Y) (s : Y -> X)\n  (retr : forall x, r (s x) = x) : contr Y .\nProof.\n refine (dpair (r (center cX)) _) .\n refine (fun y => _) .\n refine (concat (y := r (s y)) _ _).\n -\n  exact (contr_dom_constant cX r) .\n -\n  exact (retr y) .\nDefined.\n\n(** 参考文献:\n\n    * https://github.com/HoTT/HoTT/blob/1940297dd121d54d033274d84c5d023fdc56bfb4/theories/Basics/Contractible.v\n\n    *)\n", "meta": {"author": "Hexirp", "repo": "seityou", "sha": "ba816a97a2299dec3be1a4823e71166dfaaf5637", "save_path": "github-repos/coq/Hexirp-seityou", "path": "github-repos/coq/Hexirp-seityou/seityou-ba816a97a2299dec3be1a4823e71166dfaaf5637/theories/Contraction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.6684036870801903}}
{"text": "(** **** SNU 4190.310, 2016 Spring *)\n\n(** Assignment 07 *)\n(** Due: 2016/05/01 23:59 *)\n\n(* Important: \n   - You are NOT allowed to use the [admit] tactic.\n\n   - Just leave [exact GIVEUP] for those problems that you fail to prove.\n\n   - You are ALLOWED to use any tactics including.\n\n     [tauto], [intuition], [firstorder], [omega].\n*)\n\nDefinition GIVEUP {T: Type} : T.  Admitted.\n\nRequire Export SfLib.\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\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 =>\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\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)\n\n  where \"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  (* WORKED IN CLASS *)\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\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\nFixpoint optimize_1mult (a:aexp) : aexp :=\n  match a with\n  | ANum n =>\n      ANum n\n  | APlus e1 e2 =>\n      APlus (optimize_1mult e1) (optimize_1mult e2)\n  | AMinus e1 e2 =>\n      AMinus (optimize_1mult e1) (optimize_1mult e2)\n  | AMult (ANum 1) e2 =>\n      optimize_1mult e2\n  | AMult e1 (ANum 1) =>\n      optimize_1mult e1\n  | AMult e1 e2 =>\n      AMult (optimize_1mult e1) (optimize_1mult e2)\n  end.\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/07/D.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.6684036816521859}}
{"text": "(* Exercise 5 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\nTheorem exercise_005 : (A /\\ B) -> (A \\/ B).\nProof.\nimp_i Sigma.\ndis_i1.\ncon_e1 B.\nhyp Sigma.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak10/Taak10_prop005.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6683577926854806}}
{"text": "\n(*\n  Context (obj : Type).\n  Context (C : obj -> obj -> Type). \n  Context (compose : forall (X Y Z : obj), C X Y -> C Y Z -> C X Z). \n*)\nFrom ITree Require Import \n     ITree\n     ITreeFacts\n     Basics.Monad.\n\nClass category :=\n  {\n  obj : Type;\n  C : obj -> obj -> Type;\n  compose : forall {X Y Z : obj}, C X Y -> C Y Z -> C X Z;\n  id : forall {X : obj}, C X X;\n  arrow_eq : forall {X Y : obj}, C X Y -> C X Y -> Prop;\n  l_id : forall (X Y : obj) (f : C X Y), arrow_eq f (compose id f);\n  r_id : forall (X Y : obj) (f : C X Y), arrow_eq f (compose f id);\n  assoc : forall (W X Y Z : obj) (f : C W X) (g : C X Y) (h : C Y Z),\n      arrow_eq (compose f (compose g h) ) (compose (compose f g) h)\n  }.\n\n  Notation \"f ∘ g\" := (compose f g) (at level 50).\n  \n\nSection RelativeMonad.\n  Context (C1 C2 : category).\n  Context (T J : @obj C1 -> @obj C2).\n  Context (Meq : forall (X: @obj C2) (Y : @obj C1), C X (T Y) -> C X (T Y) -> Prop ).\n  Notation \"f ~ g\" := (Meq _ _ f g) (at level 60).\n\n  Class RelMonad :=\n    {\n    rret : forall {X : obj}, C (J X) (T X);\n    rbind : forall {X Y : obj}, C (J X) (T Y) -> C (T X) (T Y);\n    rbind_ret : forall (X : obj), rbind (@rret X) ~ id;\n    rret_bind : forall (X Y : obj) (f : C (J X) (T Y) ), rret ∘ (rbind f) ~ f;\n    rbind_bind : forall (X Y Z : obj) (f : C (J X) (T Y)) (g : C (J Y) (T Z)), \n        (rbind f) ∘ (rbind g) ~ rbind (f ∘ (rbind g));\n    }.\n\n\n\nEnd RelativeMonad.\n\nSection TypeCat.\n  Program Instance TypeCat : category :=\n    {|\n    obj := Type;\n    C := fun A B => A -> B;\n    compose := fun _ _ _ f g x => g (f x);\n    id := fun _ x => x;\n    arrow_eq := fun _ _ f g => forall x, f x = g x\n    |}.\n\n\nEnd TypeCat.\n\nSection MonadRelMonad.\n  Context (M : Type -> Type).\n  Context (EqM : Eq1 M).\n  Context (MonadM : Monad M).\n  Context (MonadLawsM : MonadLawsE M).\n\n  Program Instance RMM : RelMonad TypeCat TypeCat M (fun x => x) (fun _ _ f g => forall x, EqM _ (f x) (g x))\n    :=\n    {|\n    rret := fun _ x => ret x;\n    rbind := fun _ _ k m => bind m k;\n    |}.\n  Next Obligation .\n    cbv. destruct MonadM. destruct MonadLawsM. unfold eq1 in *. auto.\n  Qed.\n  Next Obligation.\n    cbv. destruct MonadLawsM. destruct MonadM. unfold eq1 in *. auto.\n  Qed.\n  Next Obligation.\n    cbv. destruct MonadLawsM. destruct MonadM. unfold eq1 in *. auto.\n  Qed.\n\nEnd MonadRelMonad.\n\nSection VectorRelMonad.\n  \n", "meta": {"author": "lag47", "repo": "relative_monads", "sha": "2503bf5fff9bcc1a9d7bcdec229dca6b07ac59fd", "save_path": "github-repos/coq/lag47-relative_monads", "path": "github-repos/coq/lag47-relative_monads/relative_monads-2503bf5fff9bcc1a9d7bcdec229dca6b07ac59fd/RelMonad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.7520125793176223, "lm_q1q2_score": 0.6683577838223974}}
{"text": "\nRequire Export SfLib.\n\nModule Sat.\n\nInductive boolean : Type :=\n  | btrue : boolean \n  | bfalse : boolean\n  .\n\nTactic Notation \"boolean_cases\" tactic(first) ident(c) :=\n  first; [ Case_aux c \"btrue\" | Case_aux c \"bfalse\" ].\n\nInductive formula : Type :=\n  | fval : boolean -> formula\n  | fvar : id -> formula\n  | fite : formula -> formula -> formula -> formula\n  .\n\nTactic Notation \"formula_cases\" tactic(first) ident(c) :=\n  first; [ Case_aux c \"fval\" | Case_aux c \"fvar\" | Case_aux c \"fite\" ].  \n\nNotation ftrue := (fval btrue).\nNotation ffalse := (fval bfalse).\n\nDefinition x := (Id 0).\nDefinition y := (Id 1).\nDefinition z := (Id 2).\nHint Unfold x.\nHint Unfold y.\nHint Unfold z.\n\nDefinition model : Type := (id -> boolean).\n\nFixpoint evaluate (f : formula) (m : model) : boolean :=\n  match f with\n  | fval b => b\n  | fvar x => m x\n  | fite p a b => match evaluate p m with\n                  | btrue => evaluate a m\n                  | bfalse => evaluate b m\n                  end\n  end.\n\nDefinition satisfies (f : formula) (m : model) : Prop :=\n  evaluate f m = btrue \n  .\n\nDefinition satisfiable (f : formula) : Prop :=\n  exists (m : model), satisfies f m\n  .\n\nDefinition unsatisfiable (f : formula) : Prop := not (satisfiable f)\n  .\n  \nInductive appears_free_in : id -> formula -> Prop :=\n  | afi_var : forall x, appears_free_in x (fvar x)\n  | afi_ite1 : forall x t1 t2 t3,\n      appears_free_in x t1 -> appears_free_in x (fite t1 t2 t3)\n  | afi_ite2 : forall x t1 t2 t3,\n      appears_free_in x t2 -> appears_free_in x (fite t1 t2 t3)\n  | afi_ite3 : forall x t1 t2 t3,\n      appears_free_in x t3 -> appears_free_in x (fite t1 t2 t3)\n  .\n\nTactic Notation \"afi_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"afi_var\"\n  | Case_aux c \"afi_ite1\" | Case_aux c \"afi_ite2\" | Case_aux c \"afi_ite3\"\n  ].\n\nHint Constructors appears_free_in.\n\n(* return the number of the largest id that occurs in the given formula *)\nFixpoint max_id (f : formula) : nat :=\n  match f with\n  | fval b => 0\n  | fvar x => match x with\n                | Id n => n\n              end\n  | fite p a b => max (max_id p) (max (max_id a) (max_id b))\n  end.\n\nDefinition fresh_id (f1 : formula) (f2 : formula) : id :=\n   Id (S (max (max_id f1) (max_id f2))).\n\nEnd Sat.\n\n", "meta": {"author": "ruhler", "repo": "smten-theory", "sha": "ebab0e07756a392192bd53f10b9d6b9bb02535f9", "save_path": "github-repos/coq/ruhler-smten-theory", "path": "github-repos/coq/ruhler-smten-theory/smten-theory-ebab0e07756a392192bd53f10b9d6b9bb02535f9/src/Sat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.6683306715117832}}
{"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.\n\n(* Why3 comment *)\n(* infix_ls is replaced with (x < x1)%Z by the coq driver *)\n\n(* Why3 goal *)\nLemma infix_lseq_def : forall (x:Z) (y:Z), (x <= y)%Z <-> ((x < y)%Z \\/\n  (x = y)).\nexact Zle_lt_or_eq_iff.\nQed.\n\n(* Why3 comment *)\n(* infix_pl is replaced with (x + x1)%Z by the coq driver *)\n\n(* Why3 comment *)\n(* prefix_mn is replaced with (-x)%Z by the coq driver *)\n\n(* Why3 comment *)\n(* infix_as is replaced with (x * x1)%Z by the coq driver *)\n\n(* Why3 goal *)\nLemma Assoc : forall (x:Z) (y:Z) (z:Z),\n  (((x + y)%Z + z)%Z = (x + (y + z)%Z)%Z).\nProof.\nintros x y z.\napply sym_eq.\napply Zplus_assoc.\nQed.\n\n(* Why3 goal *)\nLemma Unit_def_l : forall (x:Z), ((0%Z + x)%Z = x).\nProof.\nexact Zplus_0_l.\nQed.\n\n(* Why3 goal *)\nLemma Unit_def_r : forall (x:Z), ((x + 0%Z)%Z = x).\nProof.\nexact Zplus_0_r.\nQed.\n\n(* Why3 goal *)\nLemma Inv_def_l : forall (x:Z), (((-x)%Z + x)%Z = 0%Z).\nProof.\nexact Zplus_opp_l.\nQed.\n\n(* Why3 goal *)\nLemma Inv_def_r : forall (x:Z), ((x + (-x)%Z)%Z = 0%Z).\nProof.\nexact Zplus_opp_r.\nQed.\n\n(* Why3 goal *)\nLemma Comm : forall (x:Z) (y:Z), ((x + y)%Z = (y + x)%Z).\nProof.\nexact Zplus_comm.\nQed.\n\n(* Why3 goal *)\nLemma Assoc1 : forall (x:Z) (y:Z) (z:Z),\n  (((x * y)%Z * z)%Z = (x * (y * z)%Z)%Z).\nProof.\nintros x y z.\napply sym_eq.\napply Zmult_assoc.\nQed.\n\n(* Why3 goal *)\nLemma Mul_distr_l : forall (x:Z) (y:Z) (z:Z),\n  ((x * (y + z)%Z)%Z = ((x * y)%Z + (x * z)%Z)%Z).\nProof.\nintros x y z.\napply Zmult_plus_distr_r.\nQed.\n\n(* Why3 goal *)\nLemma Mul_distr_r : forall (x:Z) (y:Z) (z:Z),\n  (((y + z)%Z * x)%Z = ((y * x)%Z + (z * x)%Z)%Z).\nProof.\nintros x y z.\napply Zmult_plus_distr_l.\nQed.\n\n(* Why3 goal *)\nLemma infix_mn_def : forall (x:Z) (y:Z), ((x - y)%Z = (x + (-y)%Z)%Z).\nreflexivity.\nQed.\n\n(* Why3 goal *)\nLemma Comm1 : forall (x:Z) (y:Z), ((x * y)%Z = (y * x)%Z).\nProof.\nexact Zmult_comm.\nQed.\n\n(* Why3 goal *)\nLemma Unitary : forall (x:Z), ((1%Z * x)%Z = x).\nProof.\nexact Zmult_1_l.\nQed.\n\n(* Why3 goal *)\nLemma NonTrivialRing : ~ (0%Z = 1%Z).\nProof.\ndiscriminate.\nQed.\n\n(* Why3 goal *)\nLemma Refl : forall (x:Z), (x <= x)%Z.\nProof.\nintros x.\napply Zle_refl.\nQed.\n\n(* Why3 goal *)\nLemma Trans : forall (x:Z) (y:Z) (z:Z), (x <= y)%Z -> ((y <= z)%Z ->\n  (x <= z)%Z).\nProof.\nexact Zle_trans.\nQed.\n\n(* Why3 goal *)\nLemma Antisymm : forall (x:Z) (y:Z), (x <= y)%Z -> ((y <= x)%Z -> (x = y)).\nProof.\nexact Zle_antisym.\nQed.\n\n(* Why3 goal *)\nLemma Total : forall (x:Z) (y:Z), (x <= y)%Z \\/ (y <= x)%Z.\nProof.\nintros x y.\ndestruct (Zle_or_lt x y) as [H|H].\nleft.\nassumption.\nright.\nnow apply Zlt_le_weak.\nQed.\n\n(* Why3 goal *)\nLemma ZeroLessOne : (0%Z <= 1%Z)%Z.\nProof.\napply Zle_lt_or_eq_iff.\nnow left.\nQed.\n\n(* Why3 goal *)\nLemma CompatOrderAdd : forall (x:Z) (y:Z) (z:Z), (x <= y)%Z ->\n  ((x + z)%Z <= (y + z)%Z)%Z.\nProof.\nexact Zplus_le_compat_r.\nQed.\n\n(* Why3 goal *)\nLemma CompatOrderMult : forall (x:Z) (y:Z) (z:Z), (x <= y)%Z ->\n  ((0%Z <= z)%Z -> ((x * z)%Z <= (y * z)%Z)%Z).\nProof.\nexact Zmult_le_compat_r.\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/int/Int.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.6683306715117832}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nTheorem append_nil: forall (l: lst), append l Nil = l.\nProof.\n   induction l.\n   { simpl. f_equal. assumption. }\n   { simpl. reflexivity. }\nQed.\n\nTheorem append_assoc:\n   forall (l1 l2 l3: lst), append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\n   induction l1; induction l2; induction l3; try (simpl; reflexivity).\n   { simpl. rewrite <- IHl1. f_equal. }\n   { simpl. lfind.  reflexivity.  }\nAdmitted.\n\nTheorem append_rev_cons:\n   forall (l1 l2: lst) (x: natural),\n   rev (append l1 (Cons x l2)) = append (rev l2) (Cons x (rev l1)).\nProof.\n   induction l1; induction l2; try (simpl; reflexivity).\n   { intro. simpl. rewrite IHl1. simpl. rewrite <- append_assoc.\n   f_equal. }\n   { intro. simpl. rewrite IHl1. simpl. reflexivity. }\nQed.\n\nTheorem rev_append: forall (l1 l2: lst), rev (append l1 l2) = append (rev l2) (rev l1).\nProof.\n   induction l1.\n   { induction l2.\n   { simpl. rewrite append_rev_cons.\n      rewrite <- 2 append_assoc.\n      f_equal. }\n   { simpl. rewrite append_nil. reflexivity. }\n   }\n   { intro. simpl. rewrite append_nil. reflexivity. }\nQed.\n\nTheorem rev_involutive : forall (x : lst), eq (rev (rev x)) x.\nProof.\n   induction x.\n   { simpl. rewrite rev_append. simpl. f_equal.\n   assumption. }\n   { simpl. reflexivity. }\nQed.\n\nTheorem theorem0 : forall (x : lst), eq (rev (append (rev x) Nil)) x.\nProof.\n   intro.\n   rewrite append_nil.\n   apply rev_involutive.\nQed.\n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/clam_lf_goal30_append_assoc_35_append_nil/goal30.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.6683306679701806}}
{"text": "Coq < Section Simplification.\n\nCoq < Variables P Q : Prop.\nP is assumed\nQ is assumed\n\nCoq < Goal (P /\\ Q) -> P.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  ============================\n   P /\\ Q -> P\n\nUnnamed_thm < intro.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  H : P /\\ Q\n  ============================\n   P\n\nUnnamed_thm < elim H.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  H : P /\\ Q\n  ============================\n   P -> Q -> P\n\nUnnamed_thm < intro.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  H : P /\\ Q\n  H0 : P\n  ============================\n   Q -> P\n\nUnnamed_thm < intro.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  H : P /\\ Q\n  H0 : P\n  H1 : Q\n  ============================\n   P\n\nUnnamed_thm < exact H0.\nProof completed.\n\nUnnamed_thm < Qed.\nintro.\nelim H.\nintro.\nintro.\nexact H0.\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/practice13.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.66832548800242}}
{"text": "Load \"Dep/Array\".\n\nFixpoint complete_leaf_tree A r d :=\n  match d with\n  | 0 => A\n  | S d' => array (complete_leaf_tree A r d') r\n  end.\n\nSection Example.\n\nCompute complete_leaf_tree nat 2 3.\n\nCheck Array [|Array [|Array [|0; 1|]; Array [|2; 3|]|]; Array [|Array [|4; 5|]; Array [|6; 7|]|]|] :\n  complete_leaf_tree nat 2 3.\n\nEnd Example.\n\nFixpoint complete_leaf_tree_to_list {A r d} (clt : complete_leaf_tree A r d) :=\n  match d with\n  | 0 => fun (clt : complete_leaf_tree A r 0) =>\n    [clt : A]\n  | S d' => fun (clt : complete_leaf_tree A r (S d')) =>\n    List.flat_map complete_leaf_tree_to_list (array_to_list clt)\n  end clt.\n\nTheorem complete_leaf_tree_to_list_length :\n  forall {A r d} (clt : complete_leaf_tree A r d),\n  length (complete_leaf_tree_to_list clt) = Nat.pow r d.\nProof.\n  intros ? ? ?. induction d; intros clt.\n  - auto.\n  - simpl. rewrite flat_map_length_constant_length_for_type with (k := Nat.pow r d).\n    + rewrite array_to_list_length. auto.\n    + auto.\nQed.\n\nInductive digital_list {A r} : nat -> Type :=\n  | DigitalListNil : digital_list 0\n  | DigitalListCons :\n      forall {d} k,\n      k < r ->\n      array (complete_leaf_tree A r d) k ->\n      digital_list d ->\n      digital_list (S d).\n\nArguments digital_list : clear implicits.\n\nInductive concrete_digital_list {A r} :=\n  | ConcreteDigitalList : forall d, digital_list A r d -> concrete_digital_list.\n\nArguments concrete_digital_list : clear implicits.\n\nFixpoint digital_list_to_list {A r d} (dl : digital_list A r d) :=\n  match dl with\n  | DigitalListNil => []\n  | DigitalListCons k _ a dl' =>\n    List.flat_map complete_leaf_tree_to_list (array_to_list a) ++ digital_list_to_list dl'\n  end.\n\nDefinition concrete_digital_list_to_list {A r} (cdl : concrete_digital_list A r) :=\n  let '(ConcreteDigitalList _ dl) := cdl in digital_list_to_list dl.\n\nSection Example.\n\nCompute array (complete_leaf_tree nat 2 3) 2.\n\nCheck\n  DigitalListCons _ (le_n _)\n  (Array [|Array [|Array [|Array [|0; 1|]; Array [|2; 3|]|]; Array [|Array [|4; 5|]; Array [|6; 7|]|]|]|] :\n    array (complete_leaf_tree _ _ 3) _)\n  (\n    DigitalListCons _ (le_S _ _ (le_n _))\n    (Array [||])\n    (\n      DigitalListCons _ (le_n _)\n      (Array [| Array [|8; 9|]|] : array (complete_leaf_tree _ _ 1) _)\n      (\n        DigitalListCons _ (le_S _ _ (le_n _))\n        (Array [||])\n        DigitalListNil\n      )\n    )\n  ).\n\nEnd Example.\n\nFixpoint digital_list_length {A r d} (dl : digital_list A r d) :=\n  match dl with\n  | DigitalListNil => 0\n  | DigitalListCons k _ _ dl' => (Nat.pow r (pred d)) * k + digital_list_length dl'\n  end.\n\nDefinition concrete_digital_list_length {A r} (cdl : concrete_digital_list A r) :=\n  let '(ConcreteDigitalList _ dl) := cdl in digital_list_length dl.\n\nTheorem digital_list_length_correct :\n  forall {A r d} (dl : digital_list A r d),\n  digital_list_length dl = length (digital_list_to_list dl).\nProof.\n  intros ? ? ? ?. induction dl.\n  - auto.\n  - simpl. rewrite IHdl; clear IHdl. rewrite List.app_length. apply PeanoNat.Nat.add_cancel_r.\n    clear - a. destruct a as [sl]. unfold array_to_list. induction sl.\n    + auto.\n    + rewrite <- mult_n_Sm. rewrite IHsl; clear IHsl. simpl. rewrite List.app_length.\n      rewrite complete_leaf_tree_to_list_length. lia.\nQed.\n\nTheorem concrete_digital_list_length_correct :\n  forall {A r} (cdl : concrete_digital_list A r),\n  concrete_digital_list_length cdl = length (concrete_digital_list_to_list cdl).\nProof.\n  intros ? ? ?. destruct cdl as (d & dl). apply digital_list_length_correct.\nQed.\n\nTheorem digital_list_length_upper_bound :\n  forall {A r d} (dl : digital_list A r d),\n  digital_list_length dl < Nat.pow r d.\nProof.\n  intros ? ? ? ?. induction dl.\n  - auto.\n  - simpl. nia.\nQed.\n\nFixpoint complete_leaf_tree_nth {A r d} (isl : sized_list nat d) (clt : complete_leaf_tree A r d) : option A :=\n  match d with\n  | 0 => fun (isl : sized_list nat 0) (clt : complete_leaf_tree A r 0) =>\n    Some (clt : A)\n  | S d' => fun (isl : sized_list nat (S d')) (clt : complete_leaf_tree A r (S d')) =>\n    match isl with\n    | @SizedListCons _ d'0 i isl'0 => fun (Heqd : S d'0 = S d') =>\n      let isl' := rew (eq_add_S _ _ Heqd) in isl'0 in\n      option_flat_map (complete_leaf_tree_nth isl') (array_nth i clt)\n    end eq_refl\n  end isl clt.\n\nSection Example.\n\nCompute\n  complete_leaf_tree_nth\n    [|1; 1; 0|]\n    (Array [|Array [|Array [|0; 1|]; Array [|2; 3|]|]; Array [|Array [|4; 5|]; Array [|6; 7|]|]|]).\n\nEnd Example.\n\nTheorem complete_leaf_tree_nth_correct :\n  forall {A r d} (isl : sized_list nat d) (clt : complete_leaf_tree A r d),\n  sized_list_forall (fun i => i < r) isl ->\n  complete_leaf_tree_nth isl clt =\n    List.nth_error (complete_leaf_tree_to_list clt) (indexes_sized_list_to_index r isl).\nProof.\n  intros ? ? ?. induction d; intros ? ? ?.\n  - remember 0. destruct isl.\n    + auto.\n    + discriminate.\n  - remember (S d) as d0. destruct isl.\n    + discriminate.\n    + injection Heqd0 as ->. destruct H as (? & ?). simpl.\n      rewrite PeanoNat.Nat.mul_comm. rewrite flat_map_list_nth_error_constant_length_for_type.\n      * rewrite array_nth_correct. apply option_flat_map_ext. intros clt'. apply IHd. auto.\n      * apply complete_leaf_tree_to_list_length.\n      * apply indexes_sized_list_to_index_upper_bound. auto.\nQed.\n\nFixpoint complete_leaf_tree_update {A r d} (isl : sized_list nat d)\n  (x : A) (clt : complete_leaf_tree A r d) : option (complete_leaf_tree A r d) :=\n  match d with\n  | 0 => fun (isl : sized_list nat 0) (clt : complete_leaf_tree A r 0) =>\n    Some (x : complete_leaf_tree A r 0)\n  | S d' => fun (isl : sized_list nat (S d')) (clt : complete_leaf_tree A r (S d')) =>\n    match isl with\n    | @SizedListCons _ d'0 i isl'0 => fun (Heqd : S d'0 = S d') =>\n      let isl' := rew (eq_add_S _ _ Heqd) in isl'0 in\n      option_flat_map\n        (fun clt' => array_update i clt' clt)\n        (option_flat_map (complete_leaf_tree_update isl' x) (array_nth i clt))\n    end eq_refl : option (complete_leaf_tree A r (S d'))\n  end isl clt.\n\nTheorem complete_leaf_tree_update_correct :\n  forall {A r d} x (isl : sized_list nat d) (clt : complete_leaf_tree A r d),\n  sized_list_forall (fun i => i < r) isl ->\n  option_map complete_leaf_tree_to_list (complete_leaf_tree_update isl x clt) =\n    list_update (indexes_sized_list_to_index r isl) x (complete_leaf_tree_to_list clt).\nProof.\n  intros ? ? ? ?. induction d; intros ? ? ?.\n  - simpl. remember (indexes_sized_list_to_index r (d := 0) isl) as i. destruct i.\n    + auto.\n    + exfalso. remember 0. destruct isl; discriminate.\n  - remember (S d) as d0. destruct isl.\n    + discriminate.\n    + rename n0 into i. injection Heqd0 as ->. destruct H as (? & ?). simpl. fold complete_leaf_tree.\n      rewrite PeanoNat.Nat.mul_comm. rewrite flat_map_list_update_constant_length_for_type.\n      * rewrite array_nth_correct. remember (List.nth_error (array_to_list clt) i) as o0.\n        fold complete_leaf_tree in o0. setoid_rewrite <- Heqo0. destruct o0 as [clt0 | ]; auto.\n        simpl. rewrite <- IHd; auto; clear IHd. remember (complete_leaf_tree_update isl x clt0) as o1.\n        destruct o1; auto. simpl.\n        replace (\n          fun clt0 =>\n            @List.flat_map (complete_leaf_tree A r d) A (@complete_leaf_tree_to_list A r d)\n              (@array_to_list (complete_leaf_tree A r d) r clt0)\n        ) with (\n          Basics.compose\n          (@List.flat_map (complete_leaf_tree A r d) A (@complete_leaf_tree_to_list A r d))\n          (fun clt0 => @array_to_list (complete_leaf_tree A r d) r clt0)\n        ) by auto.\n        rewrite <- option_map_option_map. rewrite array_update_correct.\n        rewrite (option_map_ext _ _ _ (List.flat_map_concat_map _)).\n        replace (\n          fun (l : list (complete_leaf_tree A r d)) => List.concat (List.map complete_leaf_tree_to_list l)\n        ) with (\n          Basics.compose\n          (@List.concat _)\n          (List.map (@complete_leaf_tree_to_list A r d))\n        ) by auto.\n        rewrite <- option_map_option_map. f_equal.\n        symmetry. apply list_update_list_map.\n      * apply complete_leaf_tree_to_list_length.\n      * apply indexes_sized_list_to_index_upper_bound. auto.\nQed.\n\nFixpoint complete_leaf_tree_pop {A r d} (clt : complete_leaf_tree A r d) : option (digital_list A r d * A) :=\n  match d with\n  | 0 => fun (Heqd : d = 0) (clt : complete_leaf_tree A r 0) =>\n    Some (DigitalListNil, clt : A)\n  | S d' => fun (Heqd : d = S d') =>\n    match r with\n    | 0 => fun _ _ => None\n    | S r' => fun (Heqn : r = S r') (clt : complete_leaf_tree A (S r') (S d')) =>\n      let (sl0, x) := array_pop clt in\n      option_map\n        (fun '(dl', y) => (DigitalListCons r' (le_n _) sl0 dl', y))\n        (complete_leaf_tree_pop x)\n    end eq_refl\n  end eq_refl clt.\n\nTheorem complete_leaf_tree_pop_correct :\n  forall {A r d} (clt : complete_leaf_tree A r d),\n  r > 1 ->\n  option_map\n    (fun '(dl, x) => digital_list_to_list dl ++ [x])\n    (complete_leaf_tree_pop clt) = Some (complete_leaf_tree_to_list clt).\nProof.\n  intros ? ? ? ? ?. induction d.\n  - auto.\n  - simpl. destruct r; try lia. remember (array_pop clt) as a0_clt0. fold complete_leaf_tree in a0_clt0.\n    destruct a0_clt0 as (a0, clt0). rewrite option_map_option_map. unfold Basics.compose.\n    specialize (IHd clt0). remember (complete_leaf_tree_pop clt0) as o0.\n    destruct o0  as [(dl0, x) | ]; try discriminate. simpl. f_equal. simpl in IHd. injection IHd as ?.\n    rewrite <- List.app_assoc. rewrite H0. specialize (array_pop_correct clt) as ?. rewrite <- Heqa0_clt0 in H1.\n    rewrite <- H1. rewrite List.flat_map_app. simpl. rewrite List.app_nil_r. auto.\nQed.\n\nDefinition digital_list_empty {A r} : digital_list A r 0 := DigitalListNil.\n\nDefinition concrete_digital_list_empty {A r} : concrete_digital_list A r :=\n  ConcreteDigitalList 0 digital_list_empty.\n\nTheorem digital_list_empty_correct :\n  forall {A r},\n  digital_list_to_list (digital_list_empty : digital_list A r 0) = [].\nProof.\n  auto.\nQed.\n\nTheorem concrete_digital_list_empty_correct :\n  forall {A r},\n  concrete_digital_list_to_list (concrete_digital_list_empty : concrete_digital_list A r) = [].\nProof.\n  auto.\nQed.\n\nFixpoint digital_list_nth_inner {A r d} (isl : sized_list nat d) (dl : digital_list A r d)\n  {struct dl} : option A :=\n  match dl with\n  | DigitalListNil => fun (isl : sized_list nat 0) =>\n    None\n  | @DigitalListCons _ _ d' k _ a dl' => fun (isl : sized_list nat (S d')) =>\n    match isl with\n    | @SizedListCons _ d'0 i isl'0 => fun (Heqd : S d'0 = S d') =>\n      let isl' := rew (eq_add_S _ _ Heqd) in isl'0 in\n      if Nat.eqb i k\n      then digital_list_nth_inner isl' dl'\n      else option_flat_map (complete_leaf_tree_nth isl') (array_nth i a)\n    end eq_refl\n  end isl.\n\nDefinition digital_list_nth {A r d} i (dl : digital_list A r d) : option A :=\n  if Nat.ltb i (digital_list_length dl)\n  then digital_list_nth_inner (indexes_sized_list_of_index r i) dl\n  else None.\n\nDefinition concrete_digital_list_nth {A r} i (cdl : concrete_digital_list A r) : option A :=\n  let '(ConcreteDigitalList _ dl) := cdl in digital_list_nth i dl.\n\nTheorem digital_list_nth_inner_correct :\n  forall {A r d} (isl : sized_list nat d) (dl : digital_list A r d),\n  sized_list_forall (fun i => i < r) isl ->\n  indexes_sized_list_to_index r isl < digital_list_length dl ->\n  digital_list_nth_inner isl dl =\n    List.nth_error (digital_list_to_list dl) (indexes_sized_list_to_index r isl).\nProof.\n  intros ? ? ? ? ? ? ?. induction dl.\n  - simpl. symmetry. apply list_nth_error_nil.\n  - simpl. dependent destruction isl. rename n0 into i.\n    unrew. destruct H as (? & ?). simpl in H0.\n    assert (length (List.flat_map complete_leaf_tree_to_list (array_to_list a)) = Nat.pow r d * k). {\n      rewrite (flat_map_length_constant_length_for_type _ _ (Nat.pow r d)).\n      - rewrite array_to_list_length. lia.\n      - apply complete_leaf_tree_to_list_length.\n    }\n    destruct (PeanoNat.Nat.eqb_spec i k).\n    + subst i. rewrite IHdl; auto; try nia; clear IHdl. simpl. rewrite List.nth_error_app2.\n      * f_equal. rewrite H2. lia.\n      * rewrite H2. lia.\n    + clear IHdl. simpl. rewrite List.nth_error_app1.\n      * rewrite PeanoNat.Nat.mul_comm. rewrite flat_map_list_nth_error_constant_length_for_type.\n        -- rewrite <- array_nth_correct. apply option_flat_map_ext. intros clt.\n           apply complete_leaf_tree_nth_correct. auto.\n        -- apply complete_leaf_tree_to_list_length.\n        -- apply indexes_sized_list_to_index_upper_bound. auto.\n      * specialize (indexes_sized_list_to_index_upper_bound isl H1) as ?.\n        specialize (digital_list_length_upper_bound dl) as ?.\n        rewrite H2. nia.\nQed.\n\nTheorem digital_list_nth_correct :\n  forall {A r d} i (dl : digital_list A r d),\n  r > 1 ->\n  digital_list_nth i dl = List.nth_error (digital_list_to_list dl) i.\nProof.\n  intros ? ? ? ? ? ?. unfold digital_list_nth.\n  destruct (PeanoNat.Nat.ltb_spec0 i (digital_list_length dl)).\n  - assert (indexes_sized_list_to_index r (d := d) (indexes_sized_list_of_index r i) = i). {\n      apply indexes_sized_list_to_of_correct.\n      - auto.\n      - apply (PeanoNat.Nat.le_trans _ _ _ l). apply PeanoNat.Nat.lt_le_incl.\n        apply digital_list_length_upper_bound.\n    }\n    rewrite digital_list_nth_inner_correct.\n    + rewrite H0. auto.\n    + apply indexes_sized_list_of_index_upper_bound. auto.\n    + rewrite H0. auto.\n  - rewrite digital_list_length_correct in n. symmetry. apply List.nth_error_None. lia.\nQed.\n\nTheorem concrete_digital_list_nth_correct :\n  forall {A r} i (cdl : concrete_digital_list A r),\n  r > 1 ->\n  concrete_digital_list_nth i cdl = List.nth_error (concrete_digital_list_to_list cdl) i.\nProof.\n  intros ? ? ? ? ?. destruct cdl as (d & dl). apply digital_list_nth_correct. auto.\nQed.\n\nSection Example.\n\nCompute\n  let cdl :=\n    ConcreteDigitalList\n    _\n    (\n      DigitalListCons _ (le_n _)\n      (Array [|Array [|Array [|Array [|0; 1|]; Array [|2; 3|]|]; Array [|Array [|4; 5|]; Array [|6; 7|]|]|]|] :\n        array (complete_leaf_tree _ _ 3) _)\n      (\n        DigitalListCons _ (le_S _ _ (le_n _))\n        (Array [||])\n        (\n          DigitalListCons _ (le_n _)\n          (Array [| Array [|8; 9|]|] : array (complete_leaf_tree _ _ 1) _)\n          (\n            DigitalListCons _ (le_S _ _ (le_n _))\n            (Array [||])\n            DigitalListNil\n          )\n        )\n      )\n    ) in\n  let f :=\n    fix f i :=\n      match i with\n      | 0 => []\n      | S i' => f i' ++ [concrete_digital_list_nth i' cdl]\n      end in\n  (\n    concrete_digital_list_to_list cdl,\n    f (concrete_digital_list_length cdl),\n    concrete_digital_list_nth 100 cdl\n  ).\n\nEnd Example.\n\nFixpoint digital_list_update_inner {A r d} (isl : sized_list nat d) (x : A) (dl : digital_list A r d)\n  {struct dl} : option (digital_list A r d) :=\n  match dl with\n  | DigitalListNil => fun (isl : sized_list nat 0) =>\n    None\n  | @DigitalListCons _ _ d' k Hlt a dl' => fun (isl : sized_list nat (S d')) =>\n    match isl with\n    | @SizedListCons _ d'0 i isl'0 => fun (Heqd : S d'0 = S d') =>\n      let isl' := rew (eq_add_S _ _ Heqd) in isl'0 in\n      if Nat.eqb i k\n      then\n        option_map\n          (DigitalListCons k Hlt a)\n          (digital_list_update_inner isl' x dl')\n      else\n        option_map\n          (fun a0 => DigitalListCons k Hlt a0 dl')\n          (\n            option_flat_map\n              (fun clt' => array_update i clt' a)\n              (option_flat_map (complete_leaf_tree_update isl' x) (array_nth i a))\n          )\n    end eq_refl : option (digital_list A r (S d'))\n  end isl.\n\nDefinition digital_list_update {A r d} i x (dl : digital_list A r d) : option (digital_list A r d) :=\n  if Nat.ltb i (digital_list_length dl)\n  then digital_list_update_inner (indexes_sized_list_of_index r i) x dl\n  else None.\n\nDefinition concrete_digital_list_update {A r} i x (cdl : concrete_digital_list A r) :\n  option (concrete_digital_list A r) :=\n  let '(ConcreteDigitalList _ dl) := cdl in\n    option_map (ConcreteDigitalList _) (digital_list_update i x dl).\n\nTheorem digital_list_update_inner_correct :\n  forall {A r d} (isl : sized_list nat d) x (dl : digital_list A r d),\n  sized_list_forall (fun i => i < r) isl ->\n  indexes_sized_list_to_index r isl < digital_list_length dl ->\n  option_map digital_list_to_list (digital_list_update_inner isl x dl) =\n    list_update (indexes_sized_list_to_index r isl) x (digital_list_to_list dl).\nProof.\n  intros ? ? ? ? ? ? ? ?. induction dl.\n  - simpl. symmetry. apply list_update_nil.\n  - simpl. dependent destruction isl. rename n0 into i.\n    unrew. destruct H as (? & ?). simpl in H0.\n    assert (length (List.flat_map complete_leaf_tree_to_list (array_to_list a)) = Nat.pow r d * k). {\n      rewrite (flat_map_length_constant_length_for_type _ _ (Nat.pow r d)).\n      - rewrite array_to_list_length. lia.\n      - apply complete_leaf_tree_to_list_length.\n    }\n    destruct (PeanoNat.Nat.eqb_spec i k).\n    + subst i. simpl. rewrite list_update_app_2.\n      * rewrite H2.\n        replace (Nat.pow r d * k + indexes_sized_list_to_index r isl - Nat.pow r d * k)\n          with (indexes_sized_list_to_index r isl) by lia.\n        rewrite <- IHdl; auto; try nia; clear IHdl.\n        remember (digital_list_update_inner isl x dl) as o0. destruct o0; auto.\n      * rewrite H2. lia.\n    + clear IHdl. simpl. rewrite list_update_app_1.\n      * rewrite PeanoNat.Nat.mul_comm. rewrite flat_map_list_update_constant_length_for_type.\n        -- rewrite <- array_nth_correct. remember (array_nth i a) as o0. destruct o0; auto. simpl.\n           rewrite option_map_option_map. unfold Basics.compose. simpl.\n           replace (\n             fun (a0 : array (complete_leaf_tree A r d) k) =>\n               List.flat_map complete_leaf_tree_to_list (array_to_list a0) ++ digital_list_to_list dl\n           ) with (\n             Basics.compose\n             (fun l0 => l0 ++ digital_list_to_list dl)\n             (\n               Basics.compose\n               (List.flat_map complete_leaf_tree_to_list)\n               (@array_to_list (complete_leaf_tree A r d) k)\n             )\n           ) by auto.\n           rewrite <- option_map_option_map. f_equal.\n           rewrite <- option_map_option_map. rewrite option_map_option_flat_map.\n           rewrite (option_flat_map_ext _ _ _ (fun _ => array_update_correct _ _ _)).\n           rewrite ? option_map_option_flat_map. rewrite <- complete_leaf_tree_update_correct.\n           rewrite option_map_flat_option_map. unfold Basics.compose.\n           apply option_flat_map_ext. intros clt0. rewrite list_update_list_map.\n           ++ remember (list_update i clt0 (array_to_list a)) as o1. destruct o1; auto. simpl.\n              f_equal. apply List.flat_map_concat_map.\n           ++ auto.\n        -- apply complete_leaf_tree_to_list_length.\n        -- apply indexes_sized_list_to_index_upper_bound. auto.\n      * specialize (indexes_sized_list_to_index_upper_bound isl H1) as ?.\n        specialize (digital_list_length_upper_bound dl) as ?.\n        rewrite H2. nia.\nQed.\n\nTheorem digital_list_update_correct :\n  forall {A r d} i x (dl : digital_list A r d),\n  r > 1 ->\n  option_map digital_list_to_list (digital_list_update i x dl) = list_update i x (digital_list_to_list dl).\nProof.\n  intros ? ? ? ? ? ? ?. unfold digital_list_update.\n  destruct (PeanoNat.Nat.ltb_spec0 i (digital_list_length dl)).\n  - assert (indexes_sized_list_to_index r (d := d) (indexes_sized_list_of_index r i) = i). {\n      apply indexes_sized_list_to_of_correct.\n      - auto.\n      - apply (PeanoNat.Nat.le_trans _ _ _ l). apply PeanoNat.Nat.lt_le_incl.\n        apply digital_list_length_upper_bound.\n    }\n    rewrite digital_list_update_inner_correct.\n    + rewrite H0. auto.\n    + apply indexes_sized_list_of_index_upper_bound. auto.\n    + rewrite H0. auto.\n  - rewrite digital_list_length_correct in n. symmetry. apply list_update_None. lia.\nQed.\n\nTheorem concrete_digital_list_update_correct :\n  forall {A r} i x (cdl : concrete_digital_list A r),\n  r > 1 ->\n  option_map concrete_digital_list_to_list (concrete_digital_list_update i x cdl) =\n    list_update i x (concrete_digital_list_to_list cdl).\nProof.\n  intros ? ? ? ? ? ?. destruct cdl as (d & dl). unfold concrete_digital_list_to_list. simpl.\n  rewrite option_map_option_map. apply digital_list_update_correct. auto.\nQed.\n\nFixpoint digital_list_push {A r d} (x : A) (dl : digital_list A r d) :\n  option (complete_leaf_tree A r d) * (digital_list A r d) :=\n  match dl with\n  | DigitalListNil => fun _ =>\n    (Some (x : complete_leaf_tree A r 0), DigitalListNil)\n  | @DigitalListCons _ _ d' k Hlt a dl' => fun (Heqd : d = S d') =>\n    match digital_list_push x dl' with\n    | (None, dl'0) => (None, @DigitalListCons _ _ d' k Hlt a dl'0)\n    | (Some clt0, dl'0) =>\n      match Compare_dec.le_lt_eq_dec (S k) r Hlt with\n      | left Hlt0 => (None, @DigitalListCons _ _ d' (S k) Hlt0 (array_push clt0 a) dl'0)\n      | right Heq =>\n        match Compare_dec.zerop r with\n        | left _ => (None, @DigitalListCons _ _ d' k Hlt a dl'0)\n        | right Hlt0 => (Some (rew Heq in (array_push clt0 a)), @DigitalListCons _ _ d' 0 Hlt0 array_empty dl'0)\n        end\n      end\n    end\n  end eq_refl.\n\nDefinition concrete_digital_list_push {A r} (x : A) (cdl : concrete_digital_list A r) :\n  concrete_digital_list A r :=\n  let '(ConcreteDigitalList d dl) := cdl in\n    match digital_list_push x dl with\n    | (None, dl0) => ConcreteDigitalList d dl0\n    | (Some clt0, dl0) =>\n      match Compare_dec.lt_dec 1 r with\n      | left Hlt => ConcreteDigitalList (S d) (@DigitalListCons _ _ d 1 Hlt (array_single clt0) dl0)\n      | right _ => ConcreteDigitalList d dl\n      end\n    end.\n\nTheorem digital_list_push_correct :\n  forall {A r d} x (dl : digital_list A r d),\n  r > 1 ->\n  (let (clt0_o, dl0) := digital_list_push x dl in\n    match clt0_o with\n    | None => []\n    | Some clt0 => complete_leaf_tree_to_list clt0\n    end ++ digital_list_to_list dl0) = digital_list_to_list dl ++ [x].\nProof.\n  intros ? ? ? ? ? ?. induction dl.\n  - auto.\n  - simpl. fold complete_leaf_tree.\n    remember (digital_list_push x dl) as clt0_o_dl0. destruct clt0_o_dl0 as (clt0_o, dl0).\n    destruct clt0_o as [clt0 | ].\n    + destruct (Compare_dec.le_lt_eq_dec (S k) r l).\n      * simpl. rewrite <- List.app_assoc. rewrite <- IHdl.\n        rewrite array_push_correct. rewrite List.flat_map_app. simpl.\n        do 2 rewrite <- List.app_assoc. auto.\n      * destruct (Compare_dec.zerop r); try lia. simpl. rewrite <- List.app_assoc. rewrite <- IHdl.\n        unrew. rewrite array_push_correct. rewrite List.flat_map_app. simpl.\n        do 2 rewrite <- List.app_assoc. auto.\n    + simpl. simpl in IHdl. rewrite IHdl. apply List.app_assoc.\nQed.\n\nTheorem concrete_digital_list_push_correct :\n  forall {A r} x (cdl : concrete_digital_list A r),\n  r > 1 ->\n  concrete_digital_list_to_list (concrete_digital_list_push x cdl) =\n    concrete_digital_list_to_list cdl ++ [x].\nProof.\n  intros ? ? ? ? ?. destruct cdl as (d & dl). unfold concrete_digital_list_to_list. simpl.\n  rewrite <- digital_list_push_correct; auto.\n  remember (digital_list_push x dl) as clt0_o_dl0. destruct clt0_o_dl0 as (clt0_o, dl0).\n  destruct clt0_o as [clt0 | ].\n  - destruct (Compare_dec.lt_dec 1 r); try lia. simpl. rewrite <- List.app_assoc. auto.\n  - auto.\nQed.\n\nFixpoint digital_list_pop {A r d} (dl : digital_list A r d) : option (digital_list A r d * A) :=\n  match dl with\n  | DigitalListNil => None\n  | @DigitalListCons _ _ d' k Hlt a dl' =>\n    match digital_list_pop dl' with\n    | None =>\n      match k with\n      | 0 => fun _ _ =>\n        None\n      | S k' => fun (a : array (complete_leaf_tree A r d') (S k')) (Hlt : S k' < r) =>\n        let (a0, blt) := array_pop a in\n        option_map\n          (fun '(dl'0, x) => (@DigitalListCons _ _ d' k' (PeanoNat.Nat.lt_succ_l _ _ Hlt) a0 dl'0, x))\n          (complete_leaf_tree_pop blt)\n      end a Hlt\n    | Some (dl'0, x) => Some (@DigitalListCons _ _ d' k Hlt a dl'0, x)\n    end\n  end.\n\nDefinition concrete_digital_list_pop {A r} (cdl : concrete_digital_list A r) :\n  option (concrete_digital_list A r * A) :=\n  let '(ConcreteDigitalList d dl) := cdl in\n    option_map\n      (fun '(dl0, x) => (ConcreteDigitalList d dl0, x))\n      (digital_list_pop dl).\n\nLemma digital_list_pop_None :\n  forall {A r d} (dl : digital_list A r d),\n  r > 1 ->\n  digital_list_pop dl = None ->\n  digital_list_to_list dl = [].\nProof.\n  intros ? ? ? ? ? ?. induction dl.\n  - auto.\n  - simpl. simpl in H0. remember (digital_list_pop dl) as o0. destruct o0 as [(dl'0, x) | ].\n    + discriminate.\n    + destruct k.\n      * remember 0. destruct a as [sl]. destruct sl; try discriminate. rewrite IHdl; auto.\n      * remember (array_pop a) as a0_clt0. destruct a0_clt0 as (a0, clt0).\n        specialize (complete_leaf_tree_pop_correct clt0 H) as ?.\n        remember (complete_leaf_tree_pop clt0) as o1. destruct o1; discriminate.\nQed.\n\nTheorem digital_list_pop_correct :\n  forall {A r d} (dl : digital_list A r d),\n  r > 1 ->\n  option_map\n    (fun '(dl0, x) => (digital_list_to_list dl0, x))\n    (digital_list_pop dl) = list_pop (digital_list_to_list dl).\nProof.\n  intros ? ? ? ? ?. induction dl.\n  - auto.\n  - simpl. remember (digital_list_pop dl) as o0. destruct o0 as [(dl'0, x) | ].\n    + simpl. simpl in IHdl. symmetry in IHdl. eapply list_pop_app_Some in IHdl. rewrite IHdl. auto.\n    + destruct k.\n      * simpl. remember 0. destruct a as [sl]. destruct sl; try discriminate. auto.\n      * remember (array_pop a) as a0_clt0. destruct a0_clt0 as (a0, clt0).\n        rewrite option_map_option_map. unfold Basics.compose.\n        specialize (complete_leaf_tree_pop_correct clt0 H) as ?.\n        remember (complete_leaf_tree_pop clt0) as o1. destruct o1 as [(dl0, x) | ]; try discriminate.\n        simpl. simpl in H0. injection H0 as ?.\n        specialize (array_pop_correct a) as ?. rewrite <- Heqa0_clt0 in H1.\n        rewrite <- H1. rewrite List.flat_map_app. simpl. rewrite List.app_nil_r. rewrite <- List.app_assoc.\n        rewrite <- H0. rewrite <- List.app_assoc. simpl.\n        symmetry in Heqo0. apply digital_list_pop_None in Heqo0; auto. rewrite Heqo0.\n        symmetry. apply list_pop_cons. apply List.app_assoc.\nQed.\n\nTheorem concrete_digital_list_pop_correct :\n  forall {A r} (cdl : concrete_digital_list A r),\n  r > 1 ->\n  option_map\n    (fun '(cdl0, x) => (concrete_digital_list_to_list cdl0, x))\n    (concrete_digital_list_pop cdl) = list_pop (concrete_digital_list_to_list cdl).\nProof.\n  intros ? ? ? ?. destruct cdl as (d & dl). unfold concrete_digital_list_to_list. simpl.\n  rewrite option_map_option_map. unfold Basics.compose. rewrite <- digital_list_pop_correct; auto.\n  apply option_map_ext. intros (dl0, x). auto.\nQed.\n\nSection Example.\n\nAbout concrete_digital_list_to_list.\n\nAbout concrete_digital_list_empty.\nCheck @concrete_digital_list_empty_correct.\n\nAbout concrete_digital_list_length.\nCheck @concrete_digital_list_length_correct.\n\nAbout concrete_digital_list_nth.\nCheck @concrete_digital_list_nth_correct.\n\nAbout concrete_digital_list_update.\nCheck @concrete_digital_list_update_correct.\n\nAbout concrete_digital_list_push.\nCheck @concrete_digital_list_push_correct.\n\nAbout concrete_digital_list_pop.\nCheck @concrete_digital_list_pop_correct.\n\nEnd Example.\n", "meta": {"author": "afdw", "repo": "digital_list", "sha": "ddadc0735f1240d4b62e962a42edf66bd1612adb", "save_path": "github-repos/coq/afdw-digital_list", "path": "github-repos/coq/afdw-digital_list/digital_list-ddadc0735f1240d4b62e962a42edf66bd1612adb/theories/Dep/DigitalList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6683254821829907}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Bedrock.Examples.AutoSep.\n\nSet Implicit Arguments.\n\n\nDefinition copyS : spec := SPEC(\"dst\", \"src\", \"sz\") reserving 3\n  Al src, Al dst,\n  PRE[V] array src (V \"src\") * array dst (V \"dst\")\n    * [| V \"sz\" = length src |] * [| V \"sz\" = length dst |]\n  POST[_] array src (V \"src\") * array src (V \"dst\").\n\nDefinition agreeUpTo (a b : list W) (i : nat) :=\n  exists c, length c = i\n    /\\ exists a', a = c ++ a'\n    /\\ exists b', b = c ++ b'.\n\nDefinition array := bmodule \"array\" {{\n  bfunction \"copy\"(\"dst\", \"src\", \"sz\", \"i\", \"to\", \"from\") [copyS]\n    \"i\" <- 0;;\n\n    [Al src, Al dst,\n      PRE[V] array src (V \"src\") * array dst (V \"dst\")\n        * [| V \"sz\" = length src |] * [| V \"sz\" = length dst |]\n        * [| agreeUpTo dst src (wordToNat (V \"i\")) |]\n      POST[_] array src (V \"src\") * array src (V \"dst\")]\n    While (\"i\" < \"sz\") {\n      \"to\" <- 4 * \"i\";;\n      \"to\" <- \"dst\" + \"to\";;\n\n      \"from\" <- 4 * \"i\";;\n      \"from\" <- \"src\" + \"from\";;\n\n      \"from\" <-* \"from\";;\n      \"to\" *<- \"from\";;\n\n      \"i\" <- \"i\" + 1\n    };;\n\n    Return 0\n  end\n}}.\n\nLemma agreeUpTo_0 : forall a b, agreeUpTo a b 0.\n  unfold agreeUpTo; exists nil; simpl; eauto.\nQed.\n\nLocal Hint Resolve agreeUpTo_0.\n\nLemma agreeUpTo_S : forall a b n, agreeUpTo a b (wordToNat n)\n  -> n < natToW (length a)\n  -> n < natToW (length b)\n  -> goodSize (length a)\n  -> agreeUpTo (Array.upd a n (Array.sel b n)) b (wordToNat (n ^+ $1)).\n  unfold agreeUpTo; intros;\n    repeat match goal with\n             | [ H : Logic.ex _ |- _ ] => destruct H; intuition; subst\n           end; autorewrite with Arr in *.\n\n  exists (x ++ Array.sel (x ++ x1) n :: nil).\n\n  autorewrite with Arr; simpl.\n  rewrite H3; intuition eauto.\n\n  destruct x1; simpl in *.\n  rewrite H3 in H1.\n  unfold natToW in H1; autorewrite with Arr in H1; generalize H1; clear; intros; nomega.\n\n  destruct x0; simpl in *.\n  rewrite H3 in H0.\n  unfold natToW in H0; autorewrite with Arr in H0; generalize H0; clear; intros; nomega.\n\n  exists x0; autorewrite with Arr; intuition.\n  exists x1; autorewrite with Arr; intuition.\nQed.\n\nLocal Hint Resolve agreeUpTo_S.\n\nLemma agreeUpTo_done : forall a b n,\n  agreeUpTo a b n\n  -> (length a <= n)%nat\n  -> (length b <= n)%nat\n  -> a = b.\n  unfold agreeUpTo; firstorder; subst.\n  rewrite app_length in *.\n  assert (length x0 = 0) by omega.\n  destruct x0; simpl in *; try omega.\n  destruct x1; simpl in *; try omega.\n  auto.\nQed.\n\nLocal Hint Extern 1 (_ < _) => congruence.\n\nTheorem arrayOk : moduleOk array.\n  vcgen; abstract (sep_auto;\n    match goal with\n      | [ |- himp _ (Array.array ?A _) (Array.array ?B _) ] =>\n        replace B with A by (eapply agreeUpTo_done; eauto 10); reflexivity\n      | _ => eauto 10\n    end).\nQed.\n", "meta": {"author": "mit-plv", "repo": "bedrock", "sha": "e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd", "save_path": "github-repos/coq/mit-plv-bedrock", "path": "github-repos/coq/mit-plv-bedrock/bedrock-e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd/Bedrock/Examples/Arr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6683254705441313}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.proposition_10.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_ABCequalsCBA.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_equalanglestransitive.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma proposition_09 : \n   forall A B C, \n   nCol B A C ->\n   exists X, CongA B A X X A C /\\ InAngle B A C X.\nProof.\nintros.\nassert (~ eq A B).\n {\n intro.\n assert (eq B A) by (conclude lemma_equalitysymmetric).\n assert (Col B A C) by (conclude_def Col ).\n contradict.\n }\nassert (~ eq A C).\n {\n intro.\n assert (Col B A C) by (conclude_def Col ).\n contradict.\n }\nlet Tf:=fresh in\nassert (Tf:exists E, (Out A C E /\\ Cong A E A B)) by (conclude lemma_layoff);destruct Tf as [E];spliter.\nassert (~ eq B E).\n {\n intro.\n assert (Col A B E) by (conclude_def Col ).\n assert (Col A C E) by (conclude lemma_rayimpliescollinear).\n assert (Col E A B) by (forward_using lemma_collinearorder).\n assert (Col E A C) by (forward_using lemma_collinearorder).\n assert (neq A E) by (conclude lemma_raystrict).\n assert (neq E A) by (conclude lemma_inequalitysymmetric).\n assert (Col A B C) by (conclude lemma_collinear4).\n assert (Col B A C) by (forward_using lemma_collinearorder).\n contradict.\n }\nlet Tf:=fresh in\nassert (Tf:exists F, (BetS B F E /\\ Cong F B F E)) by (conclude proposition_10);destruct Tf as [F];spliter.\nassert (eq B B) by (conclude cn_equalityreflexive).\nassert (eq F F) by (conclude cn_equalityreflexive).\nassert (Cong A F A F) by (conclude cn_congruencereflexive).\nassert (Cong A B A E) by (conclude lemma_congruencesymmetric).\nassert (Cong E F B F) by (forward_using lemma_doublereverse).\nassert (Cong B F E F) by (conclude lemma_congruencesymmetric).\nassert (~ Col B A F).\n {\n intro.\n assert (Col B F E) by (conclude_def Col ).\n assert (Col F B E) by (forward_using lemma_collinearorder).\n assert (Col F B A) by (forward_using lemma_collinearorder).\n assert (neq B F) by (forward_using lemma_betweennotequal).\n assert (neq F B) by (conclude lemma_inequalitysymmetric).\n assert (Col B E A) by (conclude lemma_collinear4).\n assert (Col A C E) by (conclude lemma_rayimpliescollinear).\n assert (Col E A B) by (forward_using lemma_collinearorder).\n assert (Col E A C) by (forward_using lemma_collinearorder).\n assert (neq A E) by (conclude lemma_raystrict).\n assert (neq E A) by (conclude lemma_inequalitysymmetric).\n assert (Col A B C) by (conclude lemma_collinear4).\n assert (Col B A C) by (forward_using lemma_collinearorder).\n contradict.\n }\nassert (Out A B B) by (conclude lemma_ray4).\nassert (~ eq A F).\n {\n intro.\n assert (Col B A F) by (conclude_def Col ).\n contradict.\n }\nassert (Out A F F) by (conclude lemma_ray4).\nassert (CongA B A F C A F) by (conclude_def CongA ).\nassert (CongA C A F B A F) by (conclude lemma_equalanglessymmetric).\nassert (nCol C A F) by (conclude_def CongA ).\nassert (CongA C A F F A C) by (conclude lemma_ABCequalsCBA).\nassert (CongA B A F F A C) by (conclude lemma_equalanglestransitive).\nassert (InAngle B A C F) by (conclude_def InAngle ).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/proposition_09.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6683254603958484}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice div.\nRequire Import fintype bigops finset prime groups ssralg.\n\n(***********************************************************************)\n(*  Definition of the additive group and ring Zp, represented as 'I_p  *)\n(***********************************************************************)\n(* Definitions:                                                        *)\n(* From fintype.v:                                                     *)\n(*   'I_p == the subtype of integers less than p, taken here as the    *)\n(*           type of integers mod p.                                   *)\n(* This file:                                                          *)\n(*   inZp p_gt0 == the natural projection from nat into the integers   *)\n(*                 mod p (represented as 'I_p), when p_gt0 is a proof  *)\n(*                 that p > 0.                                         *)\n(* the operations:                                                     *)\n(*   Zp0 == neutral element for addition                               *)\n(*   Zp1 == neutral element for multiplication                         *)\n(*   Zp_opp == inverse function for addition                           *)\n(*   Zp_add == addition                                                *)\n(*   Zp_mul == multiplication                                          *)\n(*   Zp_inv == inverse function for multiplication                     *)\n(*  Zp_finGroupType pp == the canonical finGroupType on 'I_pp, when pp *)\n(*                        is a pos_nat.                                *)\n(*  Zp_ring lt1p == the (commutative, unitary) ring structure on 'I_p, *)\n(*                  given lt1p : 1 < p                                 *)\n(*  Fp_field pr_p == the field structure on 'I_p, given pr_p : prime p *)\n(*     Zp p    == the set (and additive group) of all integers mod p.  *)\n(*  Zp_unit p  == the subtype of all units in the ring 'I_p            *)\n(*  Zp_units p == the set (and multiplicative group) of all 'I_p units *)\n(* operations in Zp_units:                                             *)\n(* Zp_unit_one == the neutral element for multiplication in Zp_unit    *)\n(* Zp_unit_inv u == the inverse function for multiplication in Zp_unit *)\n(* Zp_unit_mul u v == multiplication in Zp_unit                        *)\n(* We show that Zp and Zp_units are abelian, and compute their orders. *)\n(***********************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nSection ZpDef.\n\n(***********************************************************************)\n(*                                                                     *)\n(*  Mod p arithmetic on the finite set {0, 1, 2, ..., p - 1}           *)\n(*                                                                     *)\n(***********************************************************************)\n\nVariable p : nat.\nHypothesis p_gt0 : 0 < p.\n\nDefinition Zp : {set 'I_p} := setT.\n\nImplicit Types x y z : 'I_p.\n\n(* Standard injection; val (inZp i) = i %% p *)\nDefinition inZp i := Ordinal (ltn_pmod i p_gt0).\nLemma modZp : forall x, x %% p = x.\nProof. by move=> x; rewrite modn_small ?ltn_ord. Qed.\nLemma valZpK : forall x, inZp x = x.\nProof. by move=> x; apply: val_inj; rewrite /= modZp. Qed.\n\n(* Operations *)\nDefinition Zp0 := Ordinal p_gt0.\nDefinition Zp1 := inZp 1.\nDefinition Zp_opp x := inZp (p - x).\nDefinition Zp_add x y := inZp (x + y).\nDefinition Zp_mul x y := inZp (x * y).\nDefinition Zp_inv x := if coprime p x then inZp (egcdn x p).1 else x.\n\n(* Units subtype *)\n\nInductive Zp_unit : predArgType := ZpUnit x of coprime p x.\n\nImplicit Types u v : Zp_unit.\n\nCoercion Zp_unit_val u := let: ZpUnit x _ := u in x.\n\nCanonical Structure Zp_unit_subType :=\n  Eval hnf in [subType for Zp_unit_val by Zp_unit_rect].\nDefinition Zp_unit_eqMixin := Eval hnf in [eqMixin of Zp_unit by <:].\nCanonical Structure Zp_unit_eqType := Eval hnf in EqType Zp_unit_eqMixin.\nDefinition Zp_unit_choiceMixin := [choiceMixin of Zp_unit by <:].\nCanonical Structure Zp_unit_choiceType :=\n  Eval hnf in ChoiceType Zp_unit_choiceMixin.\nDefinition Zp_unit_countMixin := [countMixin of Zp_unit by <:].\nCanonical Structure Zp_unit_countType :=\n  Eval hnf in CountType Zp_unit_countMixin.\nCanonical Structure Zp_unit_subCountType :=\n  Eval hnf in [subCountType of Zp_unit].\nDefinition Zp_unit_finMixin := [finMixin of Zp_unit by <:].\nCanonical Structure Zp_unit_finType := Eval hnf in FinType Zp_unit_finMixin.\nCanonical Structure Zp_unit_subFinType := Eval hnf in [subFinType of Zp_unit].\n\nDefinition Zp_units : {set Zp_unit} := setT.\n\n(* Additive group structure. *)\n\nLemma Zp_add0z : left_id Zp0 Zp_add.\nProof. exact: valZpK. Qed.\n\nLemma Zp_addNz : left_inverse Zp0 Zp_opp Zp_add.\nProof.\nby move=> x; apply: val_inj; rewrite /= modn_addml subnK ?modnn // ltnW.\nQed.\n\nLemma Zp_addA : associative Zp_add.\nProof.\nby move=> x y z; apply: val_inj; rewrite /= modn_addml modn_addmr addnA.\nQed.\n\nLemma Zp_addC : commutative Zp_add.\nProof. by move=> x y; apply: val_inj; rewrite /= addnC. Qed.\n\nDefinition Zp_groupMixin := FinGroup.Mixin Zp_addA Zp_add0z Zp_addNz.\n\nDefinition Zp_zmodMixin := ZmodMixin Zp_addA Zp_addC Zp_add0z Zp_addNz.\n\n(* Ring operations *)\n\nLemma Zp_mul1z : left_id Zp1 Zp_mul.\nProof. by move=> x; apply: val_inj; rewrite /= modn_mulml mul1n modZp. Qed.\n\nLemma Zp_mulC : commutative Zp_mul.\nProof. by move=> x y; apply: val_inj; rewrite /= mulnC. Qed.\n\nLemma Zp_mulz1 : right_id Zp1 Zp_mul.\nProof. by move=> x; rewrite Zp_mulC Zp_mul1z. Qed.\n\nLemma Zp_mulA : associative Zp_mul.\nProof.\nby move=> x y z; apply: val_inj; rewrite /= modn_mulml modn_mulmr mulnA.\nQed.\n\nLemma Zp_mul_addr : right_distributive Zp_mul Zp_add.\nProof.\nby move=> x y z; apply: val_inj; rewrite /= modn_mulmr modn_add2m muln_addr.\nQed.\n\nLemma Zp_mul_addl : left_distributive Zp_mul Zp_add.\nProof. by move=> x y z; rewrite -!(Zp_mulC z) Zp_mul_addr. Qed.\n\nLemma Zp_mulVz : forall x, coprime p x -> Zp_mul (Zp_inv x) x = Zp1.\nProof.\nmove=> x co_p_x; apply: val_inj; rewrite /Zp_inv co_p_x /= modn_mulml.\nby rewrite -(chinese_modl co_p_x 1 0) /chinese addn0 mul1n mulnC.\nQed.\n\nLemma Zp_mulzV : forall x, coprime p x -> Zp_mul x (Zp_inv x) = Zp1.\nProof. by move=> x Ux; rewrite /= Zp_mulC Zp_mulVz. Qed.\n\nLemma Zp_intro_unit : forall x y, Zp_mul y x = Zp1 -> coprime p x.\nProof.\nmove=> x y [yx1]; have:= coprimen1 p.\nby rewrite -coprime_modr -yx1 coprime_modr coprime_mulr; case/andP.\nQed.\n\nLemma Zp_inv_out : forall x, ~~ coprime p x -> Zp_inv x = x.\nProof. by rewrite /Zp_inv => x; move/negPf->. Qed.\n\nLemma Zp_mulrn : forall x n,\n  ((x : ZmodType Zp_zmodMixin) *+ n)%R = inZp (x * n).\nProof.\nmove=> x n; apply: val_inj => /=.\nelim: n => [|n IHn]; first by rewrite muln0 modn_small.\nby rewrite !GRing.mulrS /= IHn modn_addmr mulnS.\nQed.\n\n(* Multiplicative (unit) group. *)\n\nLemma Zp_unit_one_proof : coprime p Zp1.\nProof. by rewrite coprime_modr coprimen1. Qed.\n\nLemma Zp_unit_mul_proof : forall u v, coprime p (Zp_mul u v).\nProof. by move=> u v; rewrite coprime_modr coprime_mulr (valP u) (valP v). Qed.\n\nLemma Zp_unit_inv_proof : forall u, coprime p (Zp_inv u).\nProof.\nmove=> u; have:= Zp_unit_one_proof; rewrite -(Zp_mulVz (valP u)).\nby rewrite coprime_modr coprime_mulr; case/andP.\nQed.\n\nDefinition Zp_unit_one := ZpUnit Zp_unit_one_proof.\n\nDefinition Zp_unit_inv u := ZpUnit (Zp_unit_inv_proof u).\n\nDefinition Zp_unit_mul u v := ZpUnit (Zp_unit_mul_proof u v).\n\nLemma Zp_unit_mul1g : left_id Zp_unit_one Zp_unit_mul.\nProof. move=> u; apply: val_inj; exact: Zp_mul1z. Qed.\n\nLemma Zp_unit_mulVg : left_inverse Zp_unit_one Zp_unit_inv Zp_unit_mul.\nProof. move=> u; apply: val_inj; exact: Zp_mulVz (valP u). Qed.\n\nLemma Zp_unit_mulA : associative Zp_unit_mul.\nProof. move=> u v w; apply: val_inj; exact: Zp_mulA. Qed.\n\nLemma Zp_unit_mulC : commutative Zp_unit_mul.\nProof. move=> u v; apply: val_inj; exact: Zp_mulC. Qed.\n\nDefinition Zp_unit_groupMixin :=\n  FinGroup.Mixin Zp_unit_mulA Zp_unit_mul1g Zp_unit_mulVg.\n\nDefinition Zp_unit_zmodMixin :=\n  ZmodMixin Zp_unit_mulA Zp_unit_mulC Zp_unit_mul1g Zp_unit_mulVg.\n\n(* Group orders *)\n\nLemma card_Zp : #|Zp| = p.\nProof. by rewrite cardsT card_ord. Qed.\n\nLemma card_Zp_units : #|Zp_units| = phi p.\nProof. by rewrite cardsT card_sub phi_count_coprime big_mkord -sum1_card. Qed.\n\nEnd ZpDef.\n\nSection ZpGroup.\n\n(* Canonical group structures for Zp and Zp_units; we use pos_nat to carry *)\n(* the p > 0 assumption, which works fine for group element orders, but    *)\n(* doesn't extend very well to the ring and field cases, where one needs   *)\n(* stronger constraints (resp., p > 1, prime p) which don't have canonical *)\n(* proofs. \"Type\" classes would work better here.                          *)\n\nImport GroupScope.\n\nVariable p : pos_nat.\n\nCanonical Structure Zp_baseFinGroupType :=\n  Eval hnf in BaseFinGroupType (Zp_groupMixin (valP p)).\nCanonical Structure Zp_finGroupType := FinGroupType (Zp_addNz (valP p)).\nCanonical Structure Zp_zmodType :=\n  Eval hnf in ZmodType (Zp_zmodMixin (valP p)).\nCanonical Structure Zp_group := Eval hnf in [group of Zp p].\n\nCanonical Structure Zp_unit_baseFinGroupType :=\n  Eval hnf in BaseFinGroupType (Zp_unit_groupMixin (valP p)).\nCanonical Structure Zp_unit_finGroupType :=\n  FinGroupType (Zp_unit_mulVg (valP p)).\nCanonical Structure Zp_unit_zmodType :=\n  Eval hnf in ZmodType (Zp_unit_zmodMixin (valP p)).\nCanonical Structure Zp_units_group := Eval hnf in [group of Zp_units p].\n\nImplicit Type x : 'I_p.\n\nDefinition Zp_gen := Zp1 (valP p).\n\nLemma Zp_mulgC : @commutative 'I_p mulg.\nProof. exact: Zp_addC. Qed.\n\nLemma Zp_abelian : abelian (Zp p).\nProof. apply/centsP=> x _ y _; exact: Zp_mulgC. Qed.\n\nLemma Zp_expgn : forall x n, x ^+ n = inZp (valP p) (x * n).\nProof. exact: Zp_mulrn. Qed.\n\nLemma Zp_gen_expgz : forall x, Zp_gen ^+ x = x.\nProof. move=> x; rewrite Zp_expgn; exact: Zp_mul1z. Qed.\n\nLemma Zp_cycle : setT = <[Zp_gen]>.\nProof.\nby apply/setP=> x; rewrite -[x]Zp_gen_expgz inE groupX ?mem_gen ?set11.\nQed.\n\nLemma Zp_unit_mulgC : @commutative (Zp_unit p) mulg.\nProof. exact: Zp_unit_mulC. Qed.\n\nLemma Zp_units_abelian : abelian (Zp_units p).\nProof. apply/centsP=> x _ y _; exact: Zp_unit_mulgC. Qed.\n\nLemma Zp_units_expgn : forall (u : Zp_unit p) n,\n  u ^+ n = inZp (valP p) (u ^ n) :> 'I_p.\nProof.\nmove=> u n; apply: val_inj => /=; elim: n => [|n IHn] //.\nby rewrite expgS /= IHn expnS modn_mulmr.\nQed.\n\nEnd ZpGroup.\n\nImplicit Arguments Zp_gen [p].\n\nSection ZpRing.\n\nOpen Scope ring_scope.\n\nVariable p : nat.\nHypothesis lt1p : 1 < p.\nLet lt0p := ltnW lt1p.\n\nLemma Zp_nontriv : Zp1 lt0p != Zp0 lt0p.\nProof. by rewrite /eq_op /= modn_small. Qed.\n\nDefinition Zp_ringMixin :=\n  @ComRingMixin (ZmodType (Zp_zmodMixin lt0p)) _ _\n           (Zp_mulA _) (Zp_mulC _) (Zp_mul1z _) (Zp_mul_addl _) Zp_nontriv.\n\nDefinition Zp_comRingMixin :\n   @commutative (RingType Zp_ringMixin) *%R := Zp_mulC _.\n\nDefinition Zp_unitMixin :=\n  @ComUnitRingMixin (ComRingType Zp_comRingMixin) (fun i => coprime p i)\n   (Zp_inv lt0p) (Zp_mulVz _) (@Zp_intro_unit _ _) (Zp_inv_out _).\n\nDefinition Zp_ring := ComUnitRingType Zp_unitMixin.\n\nLemma Zp_nat : forall n, n%:R = inZp lt0p n :> Zp_ring.\nProof.\nby move=> n; apply: val_inj; rewrite [n%:R]Zp_mulrn /= modn_mulml mul1n.\nQed.\n\nEnd ZpRing.\n\nLemma ord1 : forall i : 'I_1, i = 0%R.\nProof. case=> [[]] // ?; exact/eqP. Qed.\n\nLemma lshift_ord1 : forall n (i : 'I_1), lshift n i = 0%R :> 'I_n.+1.\nProof. by move=> n i; apply/eqP; rewrite [i]ord1. Qed.\n\n(* Field structure for primes. *)\n\nSection PrimeField.\n\nOpen Scope ring_scope.\n\nVariable p : nat.\nHypothesis pr_p : prime p.\nLet lt1p := prime_gt1 pr_p.\n\nLet Fp_ring := ComUnitRingType (Zp_unitMixin lt1p).\n\nLemma Fp_fieldMixin : GRing.Field.mixin_of Fp_ring.\nProof.\nby move=> x nzx; rewrite /GRing.unit /= prime_coprime // gtnNdvd ?lt0n.\nQed.\n\nDefinition Fp_idomainMixin := FieldIdomainMixin Fp_fieldMixin.\n\nDefinition Fp_field := @FieldType (IdomainType Fp_idomainMixin) Fp_fieldMixin.\n\nEnd PrimeField.\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/zmodp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6682164938795401}}
{"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 Type_class_definition.\nRequire Import Type_class_instance.\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import Lia.\nRequire Import Arith.\nRequire Import Nbinomial.\nRequire Import Setoid.\n\nDefinition iter_l (A : Type) (op : operation A) (neutral : A) (x : A) :=\nfix s n := match n with \n  | O => neutral\n  | S n' => op x (s n')\nend.\n\nDefinition iter_r (A : Type) (op : operation A) (neutral : A) (x : A) :=\nfix s n := match n with \n  | O => neutral\n  | S n' => op (s n') x\nend.\n\nDefinition iter1 (A : Type) (op : operation A) (f : nat -> A) :=\nfix s n := match n with \n  | O => f O\n  | S n' => op (f n) (s n')\nend.\n\nSection Commutative_Ring.\n  Variable X : Type.\n  Variable eqr : relation X.\n  Variable add mul : operation X.\n  Variable zero one : X.\n  Variable CR : Ring_Commutative X eqr add mul zero one.\n  \n  Definition CRpow : X -> nat -> X := iter_r X mul one.\n  Definition CRsum : (nat -> X) -> nat -> X  := iter1 X add.\n  Definition CRnatmul : nat -> X -> X := fun n x => iter_l X add zero x n.\n  \n  Notation \" a ^^ b \" := (CRpow a b) (at level 30, right associativity).\n  Notation \" a * b \" := (mul a b).\n  Notation \" a == b \" := (eqr a b) (at level 90, no associativity).\n  Notation \" a + b \" := (add a b).\n  Notation \" a ** b \" := (CRnatmul a b) (at level 60).\n  \n  Definition newton_sum n a b : X :=\n    CRsum (fun k => (Nbinomial n k) ** (a ^^ k) * (b ^^ (n - k))) n.\n  \n  Definition opp : X -> X.\n  Proof.\n    intros x.\n    destruct (group_reverse x) as [y ?].\n    exact y.\n  Defined.\n  \n  Definition sub : X -> X -> X := fun a b => add a (opp b).\n  \n  Add Setoid X eqr monoid_setoid as setoid_X.\n  \n  Add Morphism add with signature eqr ==> eqr ==> eqr as add_wd.\n  intros.\n  transitivity (x + y0).\n   apply monoid_eq_compat_l; assumption.\n   apply monoid_eq_compat_r; assumption.\n  Qed.\n  \n  Add Morphism mul with signature eqr ==> eqr ==> eqr as mul_wd.\n  intros.\n  transitivity (x * y0).\n   apply monoid_eq_compat_l; assumption.\n   apply monoid_eq_compat_r; assumption.\n  Qed.\n  \n  Add Morphism opp with signature eqr ==> eqr as opp_wd.\n  Proof.\n  intros.\n  unfold opp.\n  destruct (group_reverse x) as [x' ?].\n  destruct (group_reverse y) as [y' ?].\n  transitivity (zero + y'); [ | apply monoid_iden_l].\n  transitivity (x' + x + y'); [ | apply monoid_eq_compat_r; rewrite op_comm; assumption].\n  transitivity (x' + y + y'); [ | apply monoid_eq_compat_r; apply monoid_eq_compat_l; symmetry; assumption].\n  transitivity (zero + x').\n   symmetry; apply monoid_iden_l.\n   transitivity (x' + x + x').\n    apply monoid_eq_compat_r; symmetry; transitivity (x + x'); auto; apply op_comm.\n    transitivity (x' + (y + y')).\n     transitivity (x' + (x + x')).\n      symmetry; apply op_assoc.\n      apply monoid_eq_compat_l; transitivity zero; auto with relations.\n     apply op_assoc.\n  Qed.\n  \n  Lemma Xring : @ring_theory X zero one add mul sub opp eqr.\n  Proof.\n    split; intros.\n     apply monoid_iden_l.\n     apply op_comm.\n     apply op_assoc.\n     apply monoid_iden_l.\n     apply op_comm.\n     apply op_assoc.\n     apply ring_distributive_l.\n     reflexivity.\n     \n     unfold opp.\n     destruct (group_reverse x) as [y ?].\n     assumption.\n  Qed.\n  \n  Add Ring X : Xring.\n  \n  Lemma CRsum_simpl f n : CRsum f (S n) = f (S n) + CRsum f n.\n  Proof.\n  reflexivity.\n  Qed.\n  \n  Lemma CRsum_simpl_r f n : CRsum f (S n) == CRsum f n + f (S n).\n  Proof.\n  intros; simpl; ring.\n  Qed.\n  \n  Lemma CRsum_reindex : forall n f, f O + CRsum (fun k => f (S k)) n == CRsum f (S n).\n  Proof.\n  intros n f.\n  induction n.\n   simpl; ring.\n   \n   do 2 rewrite CRsum_simpl.\n   rewrite <- IHn.\n   ring.\n  Qed.\n  \n  Lemma CRsum_eq_compat_weak : forall a b n, (forall n, a n == b n) -> CRsum a n == CRsum b n.\n  Proof.\n  intros a b n H.\n  induction n.\n   simpl; apply H.\n   \n   simpl.\n   rewrite IHn.\n   rewrite H.\n   reflexivity.\n  Qed.\n  \n  Lemma CRsum_eq_compat : forall a b n, (forall i, i <= n -> a i == b i) -> CRsum a n == CRsum b n.\n  Proof.\n  intros a b n H.\n  induction n.\n   simpl; apply H.\n   constructor.\n   \n   simpl.\n   rewrite IHn.\n    rewrite H.\n     reflexivity.\n     constructor.\n    intros; apply H; auto.\n  Qed.\n  \n  Lemma CRsum_add_compat : forall a b n, CRsum (fun i => a i + b i) n == CRsum a n + CRsum b n.\n  Proof.\n  intros a b n.\n  induction n.\n   simpl; reflexivity.\n   \n   simpl.\n   rewrite IHn.\n   ring.\n  Qed.\n  \n  Lemma CRsum_scal_compat : forall x f n, x * CRsum f n == CRsum (fun n => x * f n) n.\n  Proof.\n  intros a b n.\n  induction n.\n   simpl; reflexivity.\n   \n   simpl.\n   ring_simplify.\n   rewrite IHn.\n   reflexivity.\n  Qed.\n  \n  Lemma CRpow_simpl : forall a n, a ^^ (S n) = a ^^ n * a.\n  Proof.\n  reflexivity.\n  Qed.\n  \n  Lemma CRadd_eq_compat : forall a b c d, a == c -> b == d -> a + b == c + d.\n  Proof.\n  intros ? ? ? ? H H'.\n  rewrite H; rewrite H'.\n  ring.\n  Qed.\n  \n  Lemma CRmul_scal_compat : forall a b n, n ** a * b == a * (n ** b).\n  Proof.\n  intros a b n.\n  induction n.\n   simpl; ring.\n   \n   simpl.\n   rewrite IHn.\n   ring.\n  Qed.\n  \n  Lemma CRscal_eq_compat : forall a b n, a == b -> n ** a == n ** b.\n  Proof.\n  intros a b n H.\n  induction n.\n   simpl; ring.\n   \n   simpl.\n   rewrite IHn.\n   rewrite H.\n   ring.\n  Qed.\n  \n  Lemma CRscal_mult_scal_one : forall a n, (n ** one) * a == n ** a.\n  Proof.\n  intros a n.\n  induction n.\n   simpl; ring.\n   \n   simpl.\n   rewrite <- IHn.\n   ring.\n  Qed.\n  \n  Lemma CRscal_add_eq_compat : forall a b n, (n ** a) + (n ** b) == n ** (a + b).\n  Proof.\n  intros a b n.\n  induction n.\n   simpl; ring.\n   \n   simpl.\n   rewrite <- IHn.\n   ring.\n  Qed.\n  \n  Lemma CRadd_scal_eq_compat : forall a n p, (n ** a) + (p ** a) == (n + p) ** a.\n  Proof.\n  intros a n p.\n  induction n.\n   simpl; ring.\n   \n   simpl.\n   rewrite <- IHn.\n   ring.\n  Qed.\n  \n  Theorem Newton : forall n a b, (a + b) ^^ n == newton_sum n a b.\n  Proof.\n  intros n a b.\n  induction n; [compute; ring | ].\n  destruct n; [compute; ring | ].\n  \n  unfold newton_sum.\n  rewrite CRsum_simpl.\n  rewrite <- CRsum_reindex.\n  \n  rewrite <- (CRsum_eq_compat (fun k => \n    (Nbinomial (S n)    k  ** a ^^ S k * b ^^ (S (S n) - S k)) +\n    (Nbinomial (S n) (S k) ** a ^^ S k * b ^^ (S (S n) - S k)))).\n   rewrite CRsum_add_compat.\n   rewrite CRpow_simpl.\n   rewrite IHn.\n   rewrite ring_distributive_r.\n   unfold newton_sum.\n   do 2 (rewrite (op_comm (O:=mul)); rewrite CRsum_scal_compat).\n   assert (AP:forall a b c d e f, a == e + c -> b == d + f -> a + b == c + (d + (e + f)))\n     by (intros ? ? ? ? ? ? Hi Hj; rewrite Hi; rewrite Hj; ring);\n     apply AP; clear AP.\n    rewrite CRsum_simpl_r.\n    repeat rewrite Nbinomial_diag.\n    repeat rewrite minus_diag.\n    apply CRadd_eq_compat.\n     apply CRsum_eq_compat_weak.\n     intro.\n     rewrite <- CRmul_scal_compat.\n     apply CRscal_eq_compat.\n     rewrite CRpow_simpl.\n     simpl; ring.\n     \n     simpl; ring.\n    \n    rewrite <- CRsum_reindex.\n    apply CRadd_eq_compat.\n     simpl; repeat rewrite binomial_zero; ring.\n     apply CRsum_eq_compat; intros j Hj.\n     rewrite <- minus_Sn_m with (S n) _; [|lia].\n     simpl.\n     rewrite <- CRmul_scal_compat.\n     apply CRscal_eq_compat.\n     ring.\n   \n   intros j Hj.\n   rewrite <- CRscal_mult_scal_one.\n   rewrite <- (CRscal_mult_scal_one _ (Nbinomial (S n) (S j))).\n   rewrite <- ring_distributive_l.\n   rewrite CRadd_scal_eq_compat.\n   rewrite Nbinomial_pascal; [ | lia].\n   rewrite CRscal_mult_scal_one.\n   reflexivity.\n  Qed.\n\nEnd Commutative_Ring.\n", "meta": {"author": "coq-community", "repo": "coqtail-math", "sha": "be26e1a6a52f2e13e0779c68aba685ddfb4f0535", "save_path": "github-repos/coq/coq-community-coqtail-math", "path": "github-repos/coq/coq-community-coqtail-math/coqtail-math-be26e1a6a52f2e13e0779c68aba685ddfb4f0535/Hierarchy/Commutative_ring_binomial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.6682089896772851}}
{"text": "\nRequire Import datatypes.\nRequire Import bigstep.\n\n(****************** One-step Reduction **************)\n\nInductive s1: Spec -> Tape -> State -> Tape -> State -> Prop :=\n\n(* RIGHT move *)\n\n | s1R: forall T:Spec, forall p q:State,\n        forall l r:HTape,\n        (tr T p (read (pair l r))) = (Some (q, R)) ->\n        (s1 T (pair l r) p\n              (pair (Cons (hd r) l) (tl r)) q)\n\n(* LEFT move *)\n\n | s1L: forall T:Spec, forall p q:State,\n        forall l r:HTape,\n        (tr T p (read (pair l r))) = (Some (q, L)) ->\n        (s1 T (pair l r) p\n              (pair (tl l) (Cons (hd l) r)) q)\n\n(* WRITE move *)\n\n | s1W: forall T:Spec, forall p q:State,\n        forall l r:HTape, forall a:Sym,\n        (tr T p (read (pair l r))) = (Some (q, (W a))) ->\n        (s1 T (pair l r) p\n              (pair l (Cons a (tl r))) q).\n\n(****************** Finite Reduction *********************)\n\nInductive sf: Spec -> Tape -> State -> Tape -> State -> Prop :=\n\n(* HALT move *)\n\n   sf0: forall T:Spec, forall q:State, forall t:Tape,\n        (sf T t q t q)\n\n(* inductive moves *)\n\n | sfI: forall T:Spec, forall p q i:State, forall s t u:Tape,\n        (s1 T s p u i) -> (sf T u i t q) ->\n        (sf T s p t q).\n\n(****************** Infinite Reduction *********************)\n\nCoInductive si: Spec -> Tape -> State -> Prop :=\n\n(* coinductive moves *)\n\n | siC: forall T:Spec, forall p q:State, forall s t:Tape,\n        (s1 T s p t q) -> (si T t q) ->\n        (si T s p).\n", "meta": {"author": "asr", "repo": "tm-coinduction", "sha": "599083b74ffdf0c1032c5c2495fef9bf23a4058c", "save_path": "github-repos/coq/asr-tm-coinduction", "path": "github-repos/coq/asr-tm-coinduction/tm-coinduction-599083b74ffdf0c1032c5c2495fef9bf23a4058c/animation/adequacy/smallstep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668095, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6681982363232164}}
{"text": "\nRequire Import FunctionalExtensionality.\nRequire Import ProofIrrelevance.\n\nDefinition ex1 {A : Type} (P : A -> Prop) : Type :=\n  { x : A | P x /\\ forall y : A, P y -> x = y }.\n\n(** Abstract categories **)\n\nSection AbstractCategory.\n\n  Structure CategoryDefinition : Type := mkCategoryDefinition {\n    ob   : Type ;\n    hom  : ob -> ob -> Type ;\n    id   : forall X: ob, hom X X ;\n    comp : forall (X Y Z: ob) (f: hom Y Z) (g: hom X Y), hom X Z\n  }.\n\n  Definition comp_id (def : CategoryDefinition) : Prop :=\n    forall (X Y: ob def) (f: hom def X Y),\n     comp def X X Y f (id def X) = f.\n\n  Definition id_comp (def : CategoryDefinition) : Prop :=\n    forall (X Y: ob def) (f: hom def X Y),\n     comp def X Y Y (id def Y) f = f.\n\n  Definition comp_assoc (def : CategoryDefinition) : Prop :=\n    forall (W X Y Z : ob def)\n           (f : hom def Y Z)\n           (g : hom def X Y)\n           (h : hom def W X),\n             comp def W Y Z f (comp def W X Y g h)\n           = comp def W X Z (comp def X Y Z f g) h.\n\n  Structure Category : Type := mkCategory {\n    def        : CategoryDefinition ;\n    Comp_id    : comp_id def ;\n    Id_comp    : id_comp def ;\n    Comp_assoc : comp_assoc def\n  }.\n\nEnd AbstractCategory.\n\nNotation \"f ** g\"  := (comp (def _) _ _ _ f g) (at level 25).\nNotation \"X ~~> Y\" := (hom (def _) X Y) (at level 35).\n\nSection AbstractCategoryDefs.\n\n  Variable c : Category.\n\n  Definition Ob   := ob (def c).\n  Definition Hom  := hom (def c).\n  Definition Id   := id (def c).\n  Definition Comp := comp (def c).\n\n  Definition initial_object (I : Ob) :=\n    forall X: Ob,\n      ex1 (fun f: I ~~> X, True).\n\n  Definition terminal_object (T : Ob) :=\n    forall X: Ob,\n      ex1 (fun f: X ~~> T, True).\n\n  Definition product (A B AxB : Ob)\n                     (pi1 : AxB ~~> A)\n                     (pi2 : AxB ~~> B) :=\n    forall (X: Ob) (f1 : X ~~> A) (f2 : X ~~> B),\n      ex1 (fun phi : X ~~> AxB,\n              pi1 ** phi = f1 /\\\n              pi2 ** phi = f2\n      ).\n\n  Definition coproduct (A B AuB : Ob)\n                       (in1 : A ~~> AuB)\n                       (in2 : B ~~> AuB) :=\n      forall (X : Ob) (g1 : A ~~> X) (g2 : B ~~> X),\n      ex1 (fun phi : AuB ~~> X,\n              phi ** in1 = g1 /\\\n              phi ** in2 = g2\n      ).\n\n  Definition equalizer (A B : Ob) (f g : A ~~> B)\n                       (E : Ob) (ea : E ~~> A)\n                       (ea_equalize: f ** ea = g ** ea)\n                       :=\n      forall (X : Ob) (xa : X ~~> A) (xa_equalize : f ** xa = g ** xa),\n        ex1 (fun phi : X ~~> E, ea ** phi = xa).\n\n  Definition pullback (A B C : Ob) (f : A ~~> C) (g : B ~~> C)\n                      (P : Ob) (pa : P ~~> A) (pb : P ~~> B)\n                      (p_commute : f ** pa = g ** pb) :=\n      forall (X : Ob) (xa : X ~~> A) (xb : X ~~> B)\n             (x_commute : f ** xa = g ** xb),\n        ex1 (fun phi : X ~~> P, pa ** phi = xa /\\ pb ** phi = xb).\n\nEnd AbstractCategoryDefs.\n", "meta": {"author": "foones", "repo": "dharma", "sha": "bea2a54256082c9349e267caae318d20e79cf8b6", "save_path": "github-repos/coq/foones-dharma", "path": "github-repos/coq/foones-dharma/dharma-bea2a54256082c9349e267caae318d20e79cf8b6/coq/cat/Category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668095, "lm_q2_score": 0.7431679972357831, "lm_q1q2_score": 0.6681982312087001}}
{"text": "From Coq Require Import Arith micromega.Lia.\nFrom BY Require Import Hierarchy.Definitions Monoid Hierarchy.List.\n\nSection BigOp.\n\n  (* Local Open Scope mag_scope. *)\n  Local Open Scope mon_scope.\n\n  Context\n    {A : Type}\n    `{Setoid A}\n    (op : A -> A -> A)\n    `{!Proper ((≡) ==> (≡) ==> (≡)) op}\n    (id : A)\n    `{Assoc A (≡) op}\n    `{LeftId A (≡) id op}\n    `{RightId A (≡) id op}.\n\n  (* Local Instance : Op1 A := op. *)\n  (* Local Instance : Id1 A := id. *)\n  (* Local Instance : Monoid A. split; exact _. Qed. *)\n\n  Local Infix \"∘\" := op.\n  Local Notation \"'ε'\" := id.\n  Local Notation \"(∘)\" := op (only parsing).\n\n  (* Local Instance : Magma A. sub_class_tac. Qed. *)\n  (* Local Instance : SemiGroup A. sub_class_tac. Qed. *)\n\n  (* Instance quot_mon (rel : relation A) `{!MagmaCongruence rel} `{subrelation A (≡) rel} : @Monoid _ rel _ _. *)\n  (* repeat split; try apply _; *)\n  (* cbv; intros; apply is_subrelation; (apply assoc; exact _) || (apply right_id; exact _) || (apply left_id; exact _). Qed. *)\n\n  Global Instance fold_left_proper : Proper ((≡) ==> (≡) ==> (≡)) (fold_left (∘)).\n  Proof.\n    do 3 red. induction x; intros.\n    - inversion H4.\n      subst. assumption.\n    - inversion H4; subst.\n      simpl. apply IHx.\n      assumption.\n      rewrite H5, H8.\n      reflexivity.\n  Qed.\n\n  Lemma fold_left_assoc (a b : A) ls :\n    a ∘ (fold_left (∘) ls b) ≡ fold_left (∘) ls (a ∘ b).\n  Proof.\n    revert b; induction ls; intros b; simpl.\n    - reflexivity.\n    - rewrite IHls.\n      rewrite (assoc (∘)).\n      reflexivity.\n  Qed.\n\n  Context\n    (f : nat -> A).\n\n  Definition big_op_list (l : list nat) f := fold_left (∘) (map f l) ε.\n  Definition big_op f n m := big_op_list (seq n (m - n)) f.\n  Definition big_op_rev f n m := big_op_list (rev (seq n (m - n))) f.\n\n  Hint Unfold big_op big_op_rev big_op_list : bigop.\n\n  Lemma big_op_S_r n m (nltm : n <= m) :\n    big_op f n (S m) = big_op f n m ∘ f m.\n  Proof. unfold big_op, big_op_list.\n         rewrite Nat.sub_succ_l, seq_snoc, map_app, fold_left_app, <- le_plus_minus; auto. Qed.\n\n  Lemma big_op_S_l n m (nltm : n <= m) :\n    big_op f n (S m) ≡ f n ∘ big_op f (S n) (S m).\n  Proof. unfold big_op, big_op_list.\n         rewrite Nat.sub_succ_l, fold_left_assoc. auto.\n         simpl. rewrite (right_id ε (∘)), (left_id ε (∘)).\n         auto. assumption. Qed.\n\n  Lemma big_op_rev_S_r n m (nltm : n <= m) :\n    big_op_rev f n (S m) = big_op_rev f (S n) (S m) ∘ f n.\n  Proof. unfold big_op_rev, big_op_list.\n         rewrite Nat.sub_succ_l by auto; simpl; rewrite map_app, fold_left_app. reflexivity. Qed.\n\n  Lemma big_op_rev_S_l n m (nltm : n <= m) :\n    big_op_rev f n (S m) ≡ f m ∘ big_op_rev f n m.\n  Proof. unfold big_op_rev, big_op_list.\n         rewrite Nat.sub_succ_l, seq_snoc, rev_app_distr, fold_left_assoc, <- le_plus_minus, (right_id ε (∘)) by auto; simpl;\n           rewrite (left_id ε (∘)); auto. Qed.\n\n  Lemma big_op_rev_nil n m (mltn : m <= n) :\n    big_op_rev f n m = ε.\n  Proof. unfold big_op_rev; replace (m - n) with 0 by lia; reflexivity. Qed.\n\n  Lemma big_op_nil n m (mltn : m <= n) :\n    big_op f n m = ε.\n  Proof. unfold big_op; replace (m - n) with 0 by lia; reflexivity. Qed.\n\n  Lemma big_op_split n m k (nmk : n <= m <= k) :\n    (big_op f n m) ∘ (big_op f m k) ≡ big_op f n k.\n  Proof.\n    revert nmk; revert n m. induction k; intros.\n    - assert (n = 0); assert (m = 0); subst; try lia. rewrite big_op_nil, (left_id ε (∘)). reflexivity. lia.\n    - destruct (Nat.eq_dec m (S k)).\n      + subst. rewrite (big_op_nil (S k)), (right_id ε (∘)). reflexivity. lia.\n      + rewrite big_op_S_r, (assoc (∘)), IHk, <- big_op_S_r by lia. reflexivity. Qed.\n\n  Lemma big_op_rev_split n m k (nmk : n <= m <= k) :\n    (big_op_rev f m k) ∘ (big_op_rev f n m) ≡ big_op_rev f n k.\n  Proof.\n    revert nmk; revert n m. induction k; intros.\n    - assert (n = 0); assert (m = 0); try lia; subst. rewrite big_op_rev_nil, (left_id ε (∘)). reflexivity. lia.\n    - destruct (Nat.eq_dec m (S k)).\n      + subst. rewrite (big_op_rev_nil (S k)), (left_id ε (∘)). reflexivity. lia.\n      + rewrite big_op_rev_S_l, <- (assoc (∘)), IHk, <- big_op_rev_S_l by lia. reflexivity. Qed.\n\n  Lemma big_op_shift g n m k :\n    (forall i, f i ≡ g (i + k)) ->\n    big_op f n m ≡ big_op g (n + k) (m + k).\n  Proof.\n    intros. unfold big_op, big_op_list. f_equiv.\n    replace (m + k - (n + k)) with (m - n) by lia.\n    apply map_seq_ext_equiv; intros. rewrite H4.\n    replace (i + (n + k - n)) with (i + k) by lia.\n    reflexivity. lia. Qed.\n\n  Lemma big_op_rev_shift g n m k :\n    (forall i, f i = g (i + k)) ->\n    big_op_rev f n m ≡ big_op_rev g (n + k) (m + k).\n  Proof.\n    intros. unfold big_op_rev, big_op_list. f_equiv.\n    rewrite !map_rev. replace (m + k - (n + k)) with (m - n) by lia.\n\n    f_equiv. apply map_seq_ext_equiv. intros.\n    rewrite H4.\n    replace (i + (n + k - n)) with (i + k) by lia.\n    reflexivity. lia.\n  Qed.\n\nEnd BigOp.\n\nNotation big_sum := (big_op op1 0)%RI.\nNotation big_mul := (big_op op2 1)%RI.\nNotation big_sum_rev := (big_op_rev op1 0)%RI.\nNotation big_mul_rev := (big_op_rev op2 1)%RI.\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/Hierarchy/BigOp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6681975174639808}}
{"text": "From mathcomp Require Import ssreflect.\n\nRequire Import collect_operator.\nRequire Import direct_product.\nRequire Import mapping.\n\n(* 配置集合, MappingSpace *)\nInductive MappingSpace {U:Type} (X Y:Collection U) : Collection (TypeOfDirectProduct U) :=\n  definition_of_mapping_space: forall (F:TypeOfDirectProduct U),\n    (exists f:U->U, MappingFunction f X Y /\\ F = GraphOfFunction f X Y) -> F ∈ MappingSpace X Y.\n\nSection MappingSpace.\n\n  Variable U:Type.\n\n  Theorem element_of_mapping_space_is_function:\n    forall (X Y: Collection U) (F:TypeOfDirectProduct U),\n      F ∈ MappingSpace X Y -> exists f:U->U,MappingFunction f X Y /\\ F = GraphOfFunction f X Y.\n  Proof.\n    move => X Y F HFM.\n    inversion HFM.\n    apply H.\n  Qed.\n\n  Theorem powerset_of_product_included_mapping_space:\n    forall (X Y: Collection U), MappingSpace X Y ⊂ 𝔓(X × Y).\n  Proof.\n    move => X Y F H.\n    split => f H'.\n    inversion H.\n    inversion H0 as [f' [Hf HF]].\n    rewrite HF in H'.\n    inversion H'.\n    inversion H2 as [x [y [Heq [Hyf'x HXY]]]].\n    rewrite -Heq in HXY.\n    assumption.\n  Qed.\n\n  Theorem element_of_mapping_space_to_graph:\n    forall (A B:Collection U) (G:TypeOfDirectProduct U),\n      G ∈ MappingSpace A B -> ConditionOfGraphOfMapping G A B.\n  Proof.\n    move => A B G H.\n    inversion H.\n    inversion H0 as [g].\n    inversion H2.\n    split.\n    apply (direct_product_included_graph_of_function U g A B G).\n    trivial.\n    move => a HaA.\n    exists (g a).\n    split.\n    rewrite H4.\n    split.\n    exists a.\n    exists (g a).\n    split;[reflexivity|split;[reflexivity|]].\n    have L1: exists b:U, b = g a /\\ b ∈ B.\n    apply H3.\n    trivial.\n    inversion L1 as [b [Hbga HbB]].\n    rewrite -Hbga.\n    apply in_and_to_ordered_pair_in_direct_product.\n    split;trivial.\n    move => b' HG'.\n    rewrite H4 in HG'.\n    inversion HG'.\n    inversion H5 as [a0 [b0 [Heq [Hb'ga Hab'AB]]]].\n    apply ordered_pair_to_and in Heq.\n    inversion Heq as [Heql Heqr].\n    rewrite Heqr Heql.\n    apply sym_eq.\n    assumption.\n  Qed.\n\n    \nEnd MappingSpace.\n", "meta": {"author": "seisyuu-hantatsushi", "repo": "implement_set_theory_in_coq", "sha": "49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c", "save_path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq", "path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq/implement_set_theory_in_coq-49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c/coq/mapping_space.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6681975044031693}}
{"text": "(** This file generates unsatisfiable formulas for problems\n   in the fragment SAT + EUF or SAT + EUF + ZArith. *)\n\n(** We define families of boolean variables indexed by an integer. *)\nInductive x : nat -> Prop :=\n| mk_x : forall i, x i.\nInductive y : nat -> Prop :=\n| mk_y : forall i, y i.\nInductive z : nat -> Prop  :=\n| mk_z : forall i, z i.\n\n(** [diamond_equations acc n] appends to the formula [acc] all the \n   disjunctions [(x i = y i /\\ y i = x (S i)) \\/ \n   ((x i = z i) /\\ (z i = x (S i))] for [i] ranging [0] to [pred n].\n   It corresponds to \"diamond\" equalities on the chains [x], [y] and [z]:\n        y0       y1\n      /   \\    /    \\\n   x 0 ----> x 1 -----> .................. ----> x n\n      \\    /   \\    /\n        z0       z1\n   such that each diamond constraint ensures that [x i = x (S i)] by \n   transitivity whether at the top or the bottom of the diamond.\n*)\nFixpoint diamond_equations (acc : Prop) (n : nat) : Prop :=\n  match n with\n    | O => acc\n    | S m => \n      let eq1 := x m = y m /\\ y m = x n in\n      let eq2 := x m = z m /\\ z m = x n in\n        diamond_equations ((eq1 \\/ eq2) -> acc) m\n  end.\n\n(** [diamond n] returns the implication [diamond_equations n -> x 0 = x n].\n   It is a valid formula with [1 + 4 * n] equations between [1 + 3 * n]\n   variables. *)\nDefinition diamond (n : nat) : Prop :=\n  diamond_equations (x 0 = x n) n.\n\n(** We now implement a variation of [diamond] where one layer of a\n   function symbol [f] is added to the [x_i] at every step. Whereas\n   [diamond n] is valid in SAT + equivalence, this one requires congruence.\n\n   [fdiamond_equations f acc n] appends to the formula [acc] all the \n   disjunctions [x i = y i /\\ y i = f (x (S i)) \\/ \n   ((x i = z i) /\\ (z i = f (x (S i)))] for [i] ranging [0] to [pred n].\n   It corresponds to \"diamond\" equalities on the chains [x], [y] and [z]:\n        y0       y1\n      /   \\    /    \\\n   x 0 ---> f(x 1)-----> .................. ----> f^n(x n)\n      \\    /   \\    /\n        z0       z1\n   such that each diamond constraint ensures that [x i = f(x (S i))] \n   by transitivity whether at the top or the bottom of the diamond.\n   NB : it is actually going in reverse order with respect to the above schema\n   but you get the idea.\n*)\nFixpoint fdiamond_equations (f : Prop -> Prop) (acc : Prop) (n : nat) : Prop :=\n  match n with\n    | O => acc\n    | S m => \n      let eq1 := x m = y m /\\ y m = f (x n) in\n      let eq2 := x m = z m /\\ z m = f (x n) in\n        fdiamond_equations f ((eq1 \\/ eq2) -> acc) m\n  end.\n\n(** [fdiamond n] returns the implication \n   [fdiamond_equations f n -> x 0 = f^n (x n)].\n   It is a valid formula with [1 + 4 * n] equations between [1 + 3 * n]\n   variables. *)\nFixpoint power (f : Prop -> Prop) n x :=\n  match n with 0 => x | S m => power f m (f x) end.\nDefinition fdiamond (f : Prop -> Prop) (n : nat) : Prop :=\n  fdiamond_equations f (x 0 = power f n (x n)) n.\n\n(** We define families of integer variables indexed by an integer. *)\nRequire Import ZArith.\nParameter zx : nat -> Z.\nParameter zy : nat -> Z.\nParameter zz : nat -> Z.\n\n(** [diamond_Zequations acc n] appends to the formula [acc] all the \n   disjunctions [(x i = y i /\\ y i = 1 + x (S i)) \\/ \n   ((x i = z i) /\\ (z i = 1 + x (S i))] for [i] ranging [0] to [pred n].\n   It corresponds to \"diamond\" equalities on the chains [x], [y] and [z]:\n        y0       y1\n      /   \\    /    \\\n   x 0 ----> x 1 -----> .................. ----> x n\n      \\    /   \\    /\n        z0       z1\n   such that each diamond constraint ensures that [x i = 1 + x (S i)] by \n   transitivity whether at the top or the bottom of the diamond.\n*)\nFixpoint diamond_Zequations (acc : Prop) (n : nat) : Prop :=\n  match n with\n    | O => acc\n    | S m => \n      let eq1 := zx m = zy m /\\ zy m = (1 + zx n)%Z in\n      let eq2 := zx m = zz m /\\ zz m = (1 + zx n)%Z in\n        diamond_Zequations ((eq1 \\/ eq2) -> acc) m\n  end.\n\n(** [Zdiamond n] returns the implication \n   [diamond_Zequations n -> zx 0 - n = zx n].\n   It is a valid formula with [1 + 4 * n] equations between [1 + 3 * n]\n   variables. *)\nDefinition Zdiamond (n : nat) : Prop :=\n  diamond_Zequations (zx 0 - (Z_of_nat n) = zx n)%Z n.\n\n\n(** Another goal which only contains arithmetic, no real congruence, \n   and basically no propositional value. It is a sequence of arithmetic\n   equalities which simulate the definition of a Fibonacci number.\n   *)\nFixpoint fibo_defs (res : Prop) (n : nat)  : Prop :=\n  match n with\n    | 0 => zx 0 = 1%Z -> res\n    | S m =>\n      match m with \n        | 0 => zx 1 = zx 0 -> fibo_defs res m\n        | S p => zx (S (S p)) = Zplus (zx (S p)) (zx p) -> fibo_defs res m\n      end\n  end.\nFixpoint fibo (n : nat) (z : Z) : Z :=\n  match n with\n    | 0 => 1%Z\n    | S m =>\n      match m with\n        | 0 => 1%Z\n        | S p => Zplus (fibo p (z-2)) (fibo m (z-1))\n      end\n  end.\nDefinition fibo_arith (n : nat) :=\n  fibo_defs (zx n = fibo n (Z_of_nat n)) n.", "meta": {"author": "coq-contribs", "repo": "ergo", "sha": "d31962ab6cb56861e5d83691d4d5cea1b769f2c2", "save_path": "github-repos/coq/coq-contribs-ergo", "path": "github-repos/coq/coq-contribs-ergo/ergo-d31962ab6cb56861e5d83691d4d5cea1b769f2c2/tests/GeneratorsEq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522813, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6681975017910068}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Coq.Lists.List Coq.Lists.SetoidList Coq.Bool.Bool\n        Fiat.Common Fiat.Common.List.Operations Fiat.Common.Equality Fiat.Common.List.FlattenList Fiat.Common.LogicFacts.\n\nUnset Implicit Arguments.\n\nLocal Notation iffT A B := ((A -> B) * (B -> A))%type.\n\nSection ListFacts.\n\n  Lemma map_id :\n    forall {A: Type} (seq: list A),\n      (map (fun x => x) seq) = seq.\n  Proof.\n    intros A seq; induction seq; simpl; congruence.\n  Qed.\n\n  Lemma app_singleton :\n    forall {A} (x: A) s,\n      [x] ++ s = x :: s.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma app_eq_nil_iff :\n    forall {A} s1 s2,\n      @nil A = s1 ++ s2 <-> ([] = s1 /\\ [] = s2).\n  Proof.\n    intros; split; intro H.\n    - symmetry in H; apply app_eq_nil in H; intuition.\n    - intuition; subst; intuition.\n  Qed.\n\n  Lemma singleton_neq_nil :\n    forall {A} (a: A),\n      [a] = [] <-> False.\n  Proof.\n    intuition discriminate.\n  Qed.\n\n  Lemma in_nil_iff :\n    forall {A} (item: A),\n      List.In item [] <-> False.\n  Proof.\n    intuition.\n  Qed.\n\n  Lemma in_not_nil :\n    forall {A} x seq,\n      @List.In A x seq -> seq <> nil.\n  Proof.\n    intros A x seq in_seq eq_nil.\n    apply (@in_nil _ x).\n    subst seq; assumption.\n  Qed.\n\n  Lemma in_seq_false_nil_iff :\n    forall {A} (seq: list A),\n      (forall (item: A), (List.In item seq <-> False)) <->\n      (seq = []).\n  Proof.\n    intros.\n    destruct seq; simpl in *; try tauto.\n    split; intro H.\n    pose proof (H a); intuition.\n    discriminate.\n  Qed.\n\n\n  Lemma map_map :\n    forall { A B C } (f: A -> B) (g: B -> C),\n    forall seq,\n      List.map g (List.map f seq) = List.map (fun x => g (f x)) seq.\n  Proof.\n    intros; induction seq; simpl; f_equal; trivial.\n  Qed.\n\n  Lemma filter_all_true :\n    forall {A} pred (seq: list A),\n      (forall x, List.In x seq -> pred x = true) ->\n      List.filter pred seq = seq.\n  Proof.\n    induction seq as [ | head tail IH ]; simpl; trivial.\n    intros all_true.\n    rewrite all_true by eauto.\n    f_equal; intuition.\n  Qed.\n\n  Lemma filter_all_false :\n    forall {A} seq pred,\n      (forall item : A, List.In item seq -> pred item = false) ->\n      List.filter pred seq = [].\n  Proof.\n    intros A seq pred all_false; induction seq as [ | head tail IH ]; simpl; trivial.\n    rewrite (all_false head) by (simpl; eauto).\n    intuition.\n  Qed.\n\n  Lemma map_filter_all_false :\n    forall {A} pred seq,\n      (forall subseq, List.In subseq seq ->\n                      forall (item: A), List.In item subseq ->\n                                        pred item = false) ->\n      (List.map (List.filter pred) seq) = (List.map (fun x => []) seq).\n  Proof.\n    intros A pred seq all_false;\n    induction seq as [ | subseq subseqs IH ] ; simpl; trivial.\n\n    f_equal.\n\n    specialize (all_false subseq (or_introl eq_refl)).\n    apply filter_all_false; assumption.\n\n    apply IH; firstorder.\n  Qed.\n\n  Lemma foldright_compose :\n    forall {TInf TOutf TAcc}\n           (g : TOutf -> TAcc -> TAcc) (f : TInf -> TOutf)\n           (seq : list TInf) (init : TAcc),\n      List.fold_right (compose g f) init seq =\n      List.fold_right g init (List.map f seq).\n  Proof.\n    intros;\n    induction seq;\n    simpl;\n    [  | rewrite IHseq ];\n    reflexivity.\n  Qed.\n\n  Lemma in_map_unproject :\n    forall {A B} projection seq,\n    forall item,\n      @List.In A item seq ->\n      @List.In B (projection item) (List.map projection seq).\n  Proof.\n    intros ? ? ? seq;\n    induction seq; simpl; intros item in_seq.\n\n    trivial.\n    destruct in_seq;\n      [ left; f_equal | right ]; intuition.\n  Qed.\n\n  Lemma refold_map :\n    forall {A B} (f: A -> B) x seq,\n      f x :: map f seq = map f (x :: seq).\n  Proof.\n    simpl; reflexivity.\n  Qed.\n\n  Lemma refold_in :\n    forall {A} a b l,\n      @List.In A a (b :: l) <-> List.In a l \\/ a = b.\n  Proof.\n    intros; simpl; intuition.\n  Qed.\n\n  Lemma app_map_inv :\n    forall {A B} seq l1 l2 (f: A -> B),\n      l1 ++ l2 = map f seq ->\n      exists l1' l2',\n        seq = l1' ++ l2' /\\ l1 = map f l1' /\\ l2 = map f l2'.\n  Proof.\n    induction seq; simpl; intros.\n\n    exists (@nil A); exists (@nil A); simpl.\n    apply app_eq_nil in H; intuition.\n\n    destruct l1.\n    rewrite app_nil_l in H.\n    exists (@nil A); exists (a :: seq); simpl; intuition.\n\n    rewrite <- app_comm_cons in H.\n    inversion H.\n    specialize (IHseq _ _ _ H2).\n    destruct IHseq as [l1' [l2' (seq_eq_app & l1l1' & l2l2') ] ].\n    exists (a :: l1'); exists (l2'); subst; intuition.\n  Qed.\n\n  Lemma cons_map_inv :\n    forall {A B} seq x1 l2 (f: A -> B),\n      x1 :: l2 = map f seq ->\n      exists x1' l2',\n        seq = x1' :: l2' /\\ x1 = f x1' /\\ l2 = map f l2'.\n  Proof.\n    intros * _eq.\n    destruct seq as [ | x1' l2' ]; simpl in *; try discriminate.\n    inversion _eq.\n    exists x1'; exists l2'; subst; intuition.\n  Qed.\n\n  Lemma map_eq_nil_inv :\n    forall {A B} (f: A -> B) seq,\n      map f seq = [] -> seq = [].\n  Proof.\n    intros; destruct seq; simpl in *; try discriminate; trivial.\n  Qed.\n\n\n  Lemma filter_app :\n    forall {A} (f: A -> _) s1 s2,\n      List.filter f (s1 ++ s2) =\n      List.filter f s1 ++ List.filter f s2.\n  Proof.\n    induction s1; simpl; intros.\n\n    - reflexivity.\n    - destruct (f a); simpl; congruence.\n  Qed.\n\n  Lemma filter_map :\n    forall {A B} f g seq,\n      List.filter f (@List.map A B g seq) =\n      List.map g (List.filter (fun x => f (g x)) seq).\n  Proof.\n    induction seq; simpl; intros.\n\n    - reflexivity.\n    - destruct (f (g a)); simpl; [ f_equal | ]; assumption.\n  Qed.\n\n  Lemma filter_true :\n    forall {A} s,\n      @filter A (fun _ => true) s = s.\n  Proof.\n    induction s; simpl; try rewrite IHs; reflexivity.\n  Qed.\n\n  Lemma filter_false :\n    forall {A} s,\n      @filter A (fun _ => false) s = [].\n  Proof.\n    induction s; simpl; try rewrite IHs; reflexivity.\n  Qed.\n\n  Lemma filter_flat_map_join_snd :\n    forall {A B} f s1 s2,\n      flat_map (filter (fun x : A * B => f (snd x)))\n               (map (fun a1 : A => map (fun b : B => (a1, b)) s2) s1) =\n      flat_map (fun a1 : A => map (fun b : B => (a1, b)) (filter f s2)) s1.\n  Proof.\n    induction s1; simpl; intros; trivial.\n    rewrite IHs1; f_equiv.\n    rewrite filter_map; simpl; reflexivity.\n  Qed.\n\n  Lemma flat_map_empty :\n    forall {A B} s,\n      @flat_map A B (fun _ => []) s = [].\n  Proof.\n    induction s; firstorder.\n  Qed.\n\n  Lemma filter_commute :\n    forall {A} f g seq,\n      @filter A f (filter g seq) = filter g (filter f seq).\n  Proof.\n    induction seq; simpl; intros; trivial.\n    destruct (f a) eqn:eqf; destruct (g a) eqn:eqg;\n    simpl; rewrite ?eqf, ?eqg, ?IHseq; trivial.\n  Qed.\n\n  Lemma fold_right_id {A} :\n    forall seq,\n      @List.fold_right (list A) A (fun elem acc => elem :: acc) [] seq = seq.\n  Proof.\n    induction seq; simpl; try rewrite IHseq; congruence.\n  Qed.\n\n  Lemma fold_left_id {A} :\n    forall seq,\n      @List.fold_left (list A) A (fun acc elem => elem :: acc) seq [] = rev seq.\n  Proof.\n    intros.\n    rewrite <- fold_left_rev_right.\n    apply fold_right_id.\n  Qed.\n\n  Lemma In_partition {A}\n  : forall f (l : list A) a,\n      List.In a l <-> (List.In a (fst (List.partition f l))\n                       \\/ List.In a (snd (List.partition f l))).\n  Proof.\n    split; induction l; simpl; intros; intuition; simpl; subst;\n    first [destruct (f a0); destruct (List.partition f l); simpl in *; intuition\n          | destruct (f a); destruct (List.partition f l); simpl; intuition].\n  Qed.\n\n  Lemma In_partition_matched {A}\n  : forall f (l : list A) a,\n      List.In a (fst (List.partition f l)) ->\n      f a = true.\n  Proof.\n    induction l; simpl; intros; intuition; simpl; subst; eauto.\n    case_eq (f a); destruct (List.partition f l); simpl; intuition;\n    rewrite H0 in H; eauto; inversion H; subst; eauto.\n  Qed.\n\n  Lemma In_partition_unmatched {A}\n  : forall f (l : list A) a,\n      List.In a (snd (List.partition f l)) ->\n      f a = false.\n  Proof.\n    induction l; simpl; intros; intuition; simpl; subst; eauto.\n    case_eq (f a); destruct (List.partition f l); simpl; intuition;\n    rewrite H0 in H; eauto; inversion H; subst; eauto.\n  Qed.\n\n  Lemma nil_in_false :\n    forall {A} seq,\n      seq = nil <-> ~ exists (x: A), List.In x seq.\n  Proof.\n    split; intro H.\n    intros [ x in_seq ]; subst; eauto using in_nil.\n    destruct seq as [ | a ]; trivial.\n    exfalso; apply H; exists a; simpl; intuition.\n  Qed.\n\n  Lemma In_InA :\n    forall (A : Type) (l : list A) (eqA : relation A) (x : A),\n      Equivalence eqA -> List.In x l -> InA eqA x l.\n  Proof.\n    induction l; intros; simpl in *.\n    exfalso; eauto using in_nil.\n    destruct H0.\n    apply InA_cons_hd; subst; reflexivity.\n    apply InA_cons_tl, IHl; trivial.\n  Qed.\n\n  Lemma fold_map :\n    forall {A B C} seq f g init,\n      @List.fold_left C A (fun acc x => f acc (g x)) seq init =\n      @List.fold_left C B (fun acc x => f acc (  x)) (@List.map A B g seq) init.\n  Proof.\n    induction seq; simpl; intros; trivial; try rewrite IHseq; intuition.\n  Qed.\n\n  Lemma fold_plus_sym :\n    forall (seq: list nat) (default: nat),\n      List.fold_right plus default seq =\n      List.fold_left plus seq default.\n  Proof.\n    intros; rewrite <- fold_left_rev_right.\n    revert default; induction seq; simpl; eauto; intros.\n    rewrite fold_right_app; simpl; rewrite <- IHseq.\n    clear IHseq; revert a default; induction seq;\n    simpl; intros; auto with arith.\n    rewrite <- IHseq.\n    rewrite Plus.plus_comm, <- Plus.plus_assoc; f_equal.\n    rewrite Plus.plus_comm; reflexivity.\n  Qed.\n\n  Lemma map_snd {A B C} :\n    forall (f : A -> B) (l : list (C * A)),\n      List.map f (List.map snd l) =\n      List.map snd (List.map (fun ca => (fst ca, f (snd ca))) l).\n  Proof.\n    intros; repeat rewrite List.map_map; induction l; simpl; eauto.\n  Qed.\n\n  Lemma partition_app {A} :\n    forall f (l1 l2 : list A),\n      List.partition f (l1 ++ l2) =\n      (fst (List.partition f l1) ++ fst (List.partition f l2),\n       snd (List.partition f l1) ++ snd (List.partition f l2)).\n  Proof.\n    induction l1; simpl.\n    - intros; destruct (List.partition f l2); reflexivity.\n    - intros; rewrite IHl1; destruct (f a); destruct (List.partition f l1);\n      simpl; f_equal.\n  Qed.\n\n\n  Lemma partition_filter_eq {A} :\n    forall (f : A -> bool) l,\n      fst (List.partition f l) = List.filter f l.\n  Proof.\n    induction l; simpl; eauto.\n    destruct (List.partition f l); destruct (f a); simpl in *; congruence.\n  Qed.\n\n  Lemma partition_filter_neq {A} :\n    forall (f : A -> bool) l,\n      snd (List.partition f l) = List.filter (fun a => negb (f a)) l.\n  Proof.\n    induction l; simpl; eauto.\n    destruct (List.partition f l); destruct (f a); simpl in *; congruence.\n  Qed.\n\n\n  Lemma filter_app_inv {A}\n  : forall pred (l l1 l2 : list A),\n      filter pred l = app l1 l2\n      -> exists l1' l2', l = app l1' l2'\n                         /\\ l1 = filter pred l1'\n                         /\\ l2 = filter pred l2'.\n  Proof.\n    induction l; simpl; intros.\n    - destruct l1; simpl in *;\n      [ destruct l2;\n        [ eexists nil; eexists nil; intuition\n        | discriminate]\n      | discriminate ].\n    - revert H; case_eq (pred a); intros.\n      + destruct l1; simpl in *.\n        * destruct l2; [ discriminate | ].\n          injection H0; intros.\n          apply (IHl [] l2) in H1; destruct_ex; intuition; subst.\n          eexists []; eexists (_ :: _); intuition; simpl.\n          rewrite H, H0; reflexivity.\n        * injection H0; intros.\n          apply IHl in H1; destruct_ex; subst.\n          eexists (a0 :: x); eexists x0; intuition.\n          rewrite H2; reflexivity.\n          simpl; rewrite H, H1; reflexivity.\n      + apply IHl in H0; destruct_ex; subst.\n        eexists (a :: x); eexists x0; intuition.\n        rewrite H1; reflexivity.\n        simpl; rewrite H, H0; reflexivity.\n  Qed.\n\n  Lemma fold_left_sum_acc :\n    forall {A B} seq m n (f: A -> list B),\n      m +\n      fold_left (fun (count : nat) (x : A) => count + length (f x)) seq n =\n      fold_left (fun (count : nat) (x : A) => count + length (f x)) seq\n                (n + m).\n  Proof.\n    induction seq; simpl; intros; eauto with arith.\n    rewrite IHseq; f_equal; eauto with arith.\n    repeat rewrite <- Plus.plus_assoc; f_equal; auto with arith.\n  Qed.\n\n  Lemma length_flat_map :\n    forall {A B} seq (f: A -> list B),\n      List.length (flat_map f seq) =\n      fold_left (fun count (x : A) => count + List.length (f x)) seq 0.\n  Proof.\n    simpl; induction seq; simpl; intros; eauto.\n    rewrite app_length, IHseq; clear.\n    apply fold_left_sum_acc.\n  Qed.\n\n  Lemma filter_and {A}\n  : forall (pred1 pred2 : A -> bool) (l : List.list A),\n      List.filter (fun a => pred1 a && pred2 a) l =\n      List.filter pred2 (List.filter pred1 l).\n  Proof.\n    induction l; simpl; eauto.\n    case_eq (pred1 a); simpl; intros H; eauto;\n    case_eq (pred2 a); simpl; intros; rewrite IHl; eauto.\n  Qed.\n\n  Definition ExtensionalEq {A B} f g :=\n    forall (a: A), @eq B (f a) (g a).\n\n  Lemma filter_by_equiv :\n    forall {A} f g,\n      ExtensionalEq f g ->\n      forall seq, @List.filter A f seq = @List.filter A g seq.\n  Proof.\n    intros A f g obs seq; unfold ExtensionalEq in obs; induction seq; simpl; try rewrite obs; try rewrite IHseq; trivial.\n  Qed.\n\n  Lemma filter_by_equiv_meta :\n    forall {A B : Type} (f g : A -> B -> bool),\n      (forall (a: A), ExtensionalEq (f a) (g a)) ->\n      (forall (a: A) (seq : list B), filter (f a) seq = filter (g a) seq).\n  Proof.\n    intros * equiv *;\n    rewrite (filter_by_equiv _ _ (equiv _));\n    reflexivity.\n  Qed.\n\n  Lemma filter_and' :\n    forall {A} pred1 pred2,\n    forall (seq: list A),\n      List.filter (fun x => andb (pred1 x) (pred2 x)) seq =\n      List.filter pred1 (List.filter pred2 seq).\n  Proof.\n    intros;\n    induction seq;\n    simpl;\n    [ | destruct (pred1 a) eqn:eq1;\n        destruct (pred2 a) eqn:eq2];\n    simpl;\n    try rewrite eq1;\n    try rewrite eq2;\n    trivial;\n    f_equal;\n    trivial.\n  Qed.\n\n  Local Ltac drop_take_t' :=\n    idtac;\n    match goal with\n      | _ => reflexivity\n      | _ => intro\n      | _ => progress simpl in *\n      | [ |- context[drop ?n []] ] => atomic n; destruct n\n      | [ |- context[take ?n []] ] => atomic n; destruct n\n      | [ |- context[drop ?n (_::_)] ] => atomic n; destruct n\n      | [ |- context[take ?n (_::_)] ] => atomic n; destruct n\n      | [ H : _ |- _ ] => rewrite H\n      | _ => solve [ eauto with arith ]\n      | _ => exfalso; omega\n    end.\n\n  Local Ltac drop_take_t := repeat drop_take_t'.\n\n  Lemma drop_map {A B n} (f : A -> B) ls\n  : drop n (map f ls) = map f (drop n ls).\n  Proof.\n    revert n; induction ls; drop_take_t.\n  Qed.\n\n  Lemma take_map {A B n} (f : A -> B) ls\n  : take n (map f ls) = map f (take n ls).\n  Proof.\n    revert n; induction ls; drop_take_t.\n  Qed.\n\n  Lemma take_all {A n} {ls : list A} (H : List.length ls <= n) : take n ls = ls.\n  Proof.\n    revert n H; induction ls; drop_take_t.\n  Qed.\n\n  Lemma drop_all {A n} {ls : list A} (H : List.length ls <= n) : drop n ls = nil.\n  Proof.\n    revert n H; induction ls; drop_take_t.\n  Qed.\n\n  Lemma drop_all_iff {A n} {ls : list A}\n  : (List.length ls <= n) <-> drop n ls = nil.\n  Proof.\n    split; [ apply drop_all | ].\n    revert n; induction ls; [ simpl; intros; omega | ].\n    intros [|n]; simpl.\n    { intro; discriminate. }\n    { intro; auto with arith. }\n  Qed.\n\n  Lemma take_append {A n} {ls ls' : list A}\n  : take n (ls ++ ls') = take n ls ++ take (n - List.length ls) ls'.\n  Proof.\n    revert n ls'; induction ls; drop_take_t.\n  Qed.\n\n  Lemma drop_append {A n} {ls ls' : list A}\n  : drop n (ls ++ ls') = drop n ls ++ drop (n - List.length ls) ls'.\n  Proof.\n    revert n ls'; induction ls; drop_take_t.\n  Qed.\n\n  Lemma fold_right_and_map_impl {A} {init1 init2 : Prop} (H : init1 -> init2) (ls : list A) (f g : A -> Prop) (H' : forall x, f x -> g x)\n  : fold_right and init1 (map f ls) -> fold_right and init2 (map g ls).\n  Proof.\n    induction ls; simpl; trivial; intuition.\n  Qed.\n\n  Lemma f_fold_right_bool_rect {A B T} (f : T -> B) init (ls : list A) a b\n  : f (fold_right (fun x acc => bool_rect (fun _ => T) (a x) acc (b x)) init ls)\n    = fold_right (fun x acc => bool_rect (fun _ => B) (f (a x)) acc (b x)) (f init) ls.\n  Proof.\n    revert init; induction ls; simpl; trivial; intros.\n    edestruct b; simpl; trivial.\n  Qed.\n\n  Lemma fold_right_fun {A B C} (f : A -> C -> (B -> C)) (init : B -> C) (x : B) (ls : list A)\n  : fold_right (fun (a : A) (b : B -> C) x => f a (b x) x) init ls x\n    = fold_right (B := A) (A := C) (fun a b => f a b x) (init x) ls.\n  Proof.\n    induction ls; simpl; trivial.\n    rewrite IHls; reflexivity.\n  Qed.\n\n  Lemma nth_tl {A} n (ls : list A) a\n  : nth n (tl ls) a = nth (S n) ls a.\n  Proof.\n    destruct ls, n; simpl; reflexivity.\n  Qed.\n\n  Lemma nth_drop {A} x y (ls : list A) a\n  : nth x (drop y ls) a = nth (x + y) ls a.\n  Proof.\n    revert x y; induction ls; simpl; intros.\n    { destruct x, y; reflexivity. }\n    { destruct y; simpl.\n      { destruct x; simpl; repeat (f_equal; []); try reflexivity; omega. }\n      { rewrite IHls; destruct x; simpl; repeat (f_equal; []); try reflexivity; omega. } }\n  Qed.\n\n  Lemma nth_error_drop {A} x y (ls : list A)\n  : nth_error (drop y ls) x = nth_error ls (x + y).\n  Proof.\n    revert x y; induction ls; simpl; intros.\n    { destruct x, y; reflexivity. }\n    { destruct y; simpl.\n      { destruct x; simpl; repeat (f_equal; []); try reflexivity; omega. }\n      { rewrite IHls; destruct x; simpl; repeat (f_equal; []); try reflexivity.\n        rewrite NPeano.Nat.add_succ_r; reflexivity. } }\n  Qed.\n\n  Lemma in_map_iffT' {A B}\n        (f : A -> B) (ls : list A) (y : B)\n        (eq_dec : forall y', {y = y'} + {y <> y'})\n  : iffT (In y (map f ls)) { x : A | f x = y /\\ In x ls }.\n  Proof.\n    split; [ | intros [x H]; apply in_map_iff; exists x; assumption ].\n    induction ls as [|l ls IHls].\n    { simpl; intros []. }\n    { simpl.\n      intro H.\n      destruct (eq_dec (f l)) as [e|e].\n      { exists l; split.\n        { clear -e; abstract (subst; reflexivity). }\n        { left. reflexivity. } }\n      { destruct IHls as [x H'].\n        { clear -H e.\n          abstract (destruct H; congruence). }\n        { eexists.\n          split; [ apply H' | right; apply H' ]. } } }\n  Defined.\n\n  Lemma in_map_iffT {A B}\n        (eq_dec : forall y y' : B, {y = y'} + {y <> y'})\n        (f : A -> B) (ls : list A) (y : B)\n  : iffT (In y (map f ls)) { x : A | f x = y /\\ In x ls }.\n  Proof.\n    apply in_map_iffT', eq_dec.\n  Defined.\n\n  Lemma in_map_iffT_nat {A}\n        (f : A -> nat) (ls : list A) (y : nat)\n  : iffT (In y (map f ls)) { x : A | f x = y /\\ In x ls }.\n  Proof.\n    apply in_map_iffT, NPeano.Nat.eq_dec.\n  Defined.\n\n  Lemma nth_take_1_drop {A} (ls : list A) n a\n  : nth n ls a = match take 1 (drop n ls) with\n                   | nil => a\n                   | x::_ => x\n                 end.\n  Proof.\n    revert n.\n    induction ls as [|x xs IHxs]; simpl; intros.\n    { destruct n; reflexivity. }\n    { destruct n; simpl; trivial; [].\n      rewrite IHxs; simpl; reflexivity. }\n  Qed.\n\n  Lemma drop_drop {A} x y (ls : list A)\n  : drop x (drop y ls) = drop (y + x) ls.\n  Proof.\n    revert x y.\n    induction ls as [|l ls IHls].\n    { intros [|x] [|y]; reflexivity. }\n    { intros x [|y]; simpl.\n      { reflexivity. }\n      { apply IHls. } }\n  Defined.\n\n  Lemma drop_dropS {A} y (ls : list A)\n  : drop 1 (drop y ls) = drop (S y) ls.\n  Proof.\n    rewrite drop_drop.\n    rewrite NPeano.Nat.add_1_r.\n    reflexivity.\n  Qed.\n\n  Lemma map_S_seq {A} (f : nat -> A) x y\n  : map (fun i => f (S i)) (seq x y) = map f (seq (S x) y).\n  Proof.\n    clear; revert x; induction y; intros.\n    { reflexivity. }\n    { simpl.\n      rewrite IHy; reflexivity. }\n  Qed.\n\n  Lemma length_drop {A} (n : nat) (ls : list A)\n  : List.length (List.drop n ls) = List.length ls - n.\n  Proof.\n    revert ls; induction n; simpl; intros.\n    { auto with arith. }\n    { destruct ls; simpl; [ reflexivity | ].\n      apply IHn. }\n  Qed.\n\n  Lemma drop_non_empty {A} (n : nat) (ls : list A)\n        (H : ls <> nil)\n  : List.drop (List.length ls - S n) ls <> nil.\n  Proof.\n    intro H'.\n    apply (f_equal (@List.length _)) in H'.\n    simpl in H'.\n    rewrite length_drop in H'.\n    destruct ls.\n    { apply H; reflexivity. }\n    { simpl length in H'.\n      omega. }\n  Qed.\n\n  Lemma drop_S_non_empty {A} (n : nat) (ls : list A)\n        (H : n < List.length ls)\n  : List.drop (List.length ls - S n) ls <> nil.\n  Proof.\n    intro H'.\n    apply (f_equal (@List.length _)) in H'.\n    simpl in H'.\n    rewrite length_drop in H'.\n    omega.\n  Qed.\n\n  Lemma seq_S (start len : nat)\n  : seq (S start) len = map S (seq start len).\n  Proof.\n    revert start; induction len; [ reflexivity | ].\n    simpl in *; intros.\n    rewrite IHlen; reflexivity.\n  Qed.\n\n  Lemma seq_0 (start len : nat)\n  : seq start len = map (fun x => start + x) (seq 0 len).\n  Proof.\n    revert start; induction len; simpl; intros.\n    { reflexivity. }\n    { rewrite IHlen; simpl.\n      rewrite seq_S.\n      rewrite map_map.\n      apply f_equal2.\n      { omega. }\n      { apply map_ext; intro; omega. } }\n  Qed.\n\n  Lemma seq_alt (start len : nat)\n  : seq start len = match len with\n                      | 0 => nil\n                      | S len' => start :: map S (seq start len')\n                    end.\n  Proof.\n    destruct len; simpl.\n    { reflexivity. }\n    { apply f_equal2.\n      { reflexivity. }\n      { rewrite seq_S.\n        reflexivity. } }\n  Qed.\n\n  Lemma In_S_seq {start len x} (Hsmall : start <= x) (H : In (S x) (seq start len))\n  : In x (seq start len).\n  Proof.\n    generalize dependent start; generalize x; induction len; intros; simpl in *.\n    { assumption. }\n    { destruct H as [H|H].\n      { exfalso; omega. }\n      { simpl in *.\n        destruct (lt_eq_lt_dec start x0) as [[H' | H'] | H'];\n          [ right; apply IHlen; assumption\n          | left; assumption\n          | exfalso; omega ]. } }\n  Qed.\n\n  Lemma uniquize_idempotent {A} (beq : A -> A -> bool) (ls : list A)\n  : uniquize beq (uniquize beq ls) = uniquize beq ls.\n  Proof.\n    induction ls as [|x xs IHxs]; simpl; trivial.\n    destruct (Equality.list_bin beq x (uniquize beq xs)) eqn:H;\n      simpl;\n      rewrite ?IHxs, ?H; reflexivity.\n  Qed.\n\n  Lemma uniquize_NoDupA {A} (beq : A -> A -> bool) (ls : list A)\n  : NoDupA (fun x y => beq y x) (uniquize beq ls).\n  Proof.\n    induction ls as [|x xs IHxs]; simpl; [ solve [ constructor ] | ].\n    destruct (Equality.list_bin beq x (uniquize beq xs)) eqn:H; trivial.\n    constructor; trivial.\n    intro H'.\n    apply Equality.list_inA_lb in H'.\n    congruence.\n  Qed.\n\n  Lemma uniquize_NoDup {A} (beq : A -> A -> bool) (beq_lb : forall x y, x = y -> beq x y = true) (ls : list A)\n  : NoDup (uniquize beq ls).\n  Proof.\n    eapply NoDupA_NoDup; [ | apply uniquize_NoDupA ].\n    repeat intro; eauto.\n  Qed.\n\n  Lemma NoDupA_uniquize {A} (beq : A -> A -> bool) (ls : list A) (H : NoDupA (fun x y => beq y x) ls)\n  : uniquize beq ls = ls.\n  Proof.\n    induction ls as [|x xs IHxs]; simpl; [ solve [ constructor ] | ].\n    inversion H; subst.\n    rewrite IHxs by assumption; clear IHxs.\n    destruct (Equality.list_bin beq x xs) eqn:H'; trivial.\n    exfalso.\n    apply Equality.list_inA_bl in H'.\n    tauto.\n  Qed.\n\n  Lemma NoDup_NoDupA {A} (R : relation A) (ls : list A) (R_eq : forall x y, R x y -> x = y) (H : NoDup ls)\n  : NoDupA R ls.\n  Proof.\n    induction ls; [ solve [ constructor ] | ].\n    inversion H; subst.\n    constructor; auto.\n    rewrite InA_alt.\n    intros [y [H' H'']].\n    match goal with\n      | [ H : _ |- _ ] => apply R_eq in H; subst\n    end.\n    tauto.\n  Qed.\n\n  Lemma NoDup_uniquize {A} (beq : A -> A -> bool) (beq_bl : forall x y, beq x y = true -> x = y) (ls : list A) (H : NoDup ls)\n  : uniquize beq ls = ls.\n  Proof.\n    apply NoDupA_uniquize, NoDup_NoDupA; trivial; intros.\n    symmetry; eauto.\n  Qed.\n\n  Lemma uniquize_shorter {A} (ls : list A) beq\n  : List.length (uniquize beq ls) <= List.length ls.\n  Proof.\n    induction ls as [|x xs IHxs]; simpl; trivial.\n    edestruct @Equality.list_bin; simpl; omega.\n  Qed.\n\n  Lemma uniquize_length {A} (ls : list A) beq\n  : List.length (uniquize beq ls) = List.length ls\n    <-> uniquize beq ls = ls.\n  Proof.\n    induction ls as [|x xs IHxs]; simpl; try (split; reflexivity).\n    edestruct @Equality.list_bin; simpl.\n    { pose proof (uniquize_shorter xs beq).\n      split; intro H'.\n      { omega. }\n      { apply (f_equal (@List.length _)) in H'.\n        simpl in H'.\n        omega. } }\n    { destruct IHxs.\n      split; intro;\n      first [ congruence\n            | f_equal; auto ]. }\n  Qed.\n\n  Lemma uniquize_In {A} (ls : list A) (beq : A -> A -> bool) x\n  : In x (uniquize beq ls) -> In x ls.\n  Proof.\n    intro H; induction ls as [|y ys IHys]; simpl in *; trivial.\n    destruct (Equality.list_bin beq y (uniquize beq ys)) eqn:H'.\n    { right; eauto with nocore. }\n    { destruct H.\n      { left; assumption. }\n      { right; eauto with nocore. } }\n  Qed.\n\n  Lemma uniquize_In_refl {A} (ls : list A) (beq : A -> A -> bool) x (refl : beq x x = true) (bl : forall x y, beq x y = true -> x = y)\n  : In x ls -> In x (uniquize beq ls).\n  Proof.\n    intro H; induction ls as [|y ys IHys]; simpl in *; trivial.\n    destruct (Equality.list_bin beq y (uniquize beq ys)) eqn:H';\n      destruct H; subst;\n      eauto with nocore.\n    { apply Equality.list_in_bl in H'; assumption. }\n    { left; reflexivity. }\n    { right; eauto with nocore. }\n  Qed.\n\n  Lemma uniquize_In_refl_iff {A} (ls : list A) (beq : A -> A -> bool) x (refl : beq x x = true) (bl : forall x y, beq x y = true -> x = y)\n  : In x ls <-> In x (uniquize beq ls).\n  Proof.\n    split; first [ apply uniquize_In | apply uniquize_In_refl ]; assumption.\n  Qed.\n\n  Lemma fold_right_bool_rect {T} t b init ls' bv\n  : fold_right (fun (x : T) (acc : bool -> bool)\n                => bool_rect\n                     (fun _ => bool -> bool)\n                     (t x)\n                     acc\n                     (b x))\n               init ls' bv\n    = fold_right (fun (x : T) (acc : bool)\n                  => bool_rect\n                       (fun _ => bool)\n                       (t x bv)\n                       acc\n                       (b x)) (init bv) ls'.\n  Proof.\n    induction ls' as [|x xs IHxs]; simpl;\n    [ | destruct (b x); simpl; rewrite ?IHxs ];\n    reflexivity.\n  Qed.\n\n  Lemma in_up_to {n m} (H : n < m) : List.In n (up_to m).\n  Proof.\n    revert n H; induction m; intros n H.\n    { exfalso; omega. }\n    { simpl.\n      hnf in H.\n      apply le_S_n in H.\n      apply Compare_dec.le_lt_eq_dec in H.\n      destruct H; subst; [ right; eauto | left; reflexivity ]. }\n  Qed.\n\n  Lemma in_up_to_iff {n m} : (n < m) <-> List.In n (up_to m).\n  Proof.\n    revert n; induction m; intros n; simpl.\n    { split; intro; exfalso; omega. }\n    { simpl.\n      specialize (IHm n).\n      destruct IHm.\n      destruct (lt_eq_lt_dec n m) as [[?|?]|?]; split; intros; try omega; eauto; intuition. }\n  Qed.\n\n  Lemma first_index_helper_first_index_error\n        {A B} (f : A -> bool)\n        (rect : option (nat * A) -> B) (ls : list A) (rec : nat * A -> nat * A)\n  : first_index_helper f rect ls rec\n    = rect (let idx := first_index_error f ls in\n            let v := option_rect (fun _ => option A) (nth_error ls) None idx in\n            option_map\n              rec\n              (option_rect\n                 (fun _ => option (nat * A))\n                 (fun v' : A => option_map (fun idx' : nat => (idx', v')) idx)\n                 None\n                 v)).\n  Proof.\n    revert B rec rect; induction ls as [|x xs IHxs]; simpl; intros.\n    { reflexivity. }\n    { destruct (f x).\n      { reflexivity. }\n      { rewrite !IHxs.\n        destruct (first_index_error f xs) as [idx|] eqn:Heq;\n          simpl; [ | reflexivity ].\n        destruct (nth_error xs idx) eqn:Heq'; simpl; [ | reflexivity ].\n        rewrite Heq'; simpl.\n        reflexivity. } }\n  Qed.\n\n  Local Ltac first_index_error_t'\n    := idtac;\n      match goal with\n        | _ => discriminate\n        | _ => congruence\n        | _ => omega\n        | _ => progress unfold value in *\n        | [ H : Some _ = Some _ |- _ ] => inversion H; clear H\n        | _ => progress subst\n        | [ H : ?x = true |- context[?x] ] => rewrite H\n        | [ H : and _ _ |- _ ] => destruct H\n        | [ H : ex _ |- _ ] => destruct H\n        | [ H : iff _ _ |- _ ] => destruct H\n        | [ H : ?x = ?x -> ?A |- _ ] => specialize (H eq_refl)\n        | _ => progress intros\n        | _ => split\n        | [ H : context[if ?b then _ else _] |- _ ] => destruct b eqn:?\n        | [ H : context[option_map _ ?x] |- _ ] => destruct x eqn:?; unfold option_map in H\n        | _ => solve [ repeat (esplit || eassumption) ]\n        | [ H : context[nth_error (_::_) ?x] |- _ ] => is_var x; destruct x; simpl nth_error in H\n        | [ H : S _ < S _ |- _ ] => apply lt_S_n in H\n        | _ => solve [ eauto with nocore ]\n        | [ |- context[if ?b then _ else _] ] => destruct b eqn:?\n        | [ H : ?A -> ?B |- _ ] => let H' := fresh in assert (H' : A) by (assumption || omega); specialize (H H'); clear H'\n        | [ H : forall n, n < S _ -> _ |- _ ] => pose proof (H 0); specialize (fun n => H (S n))\n        | _ => progress simpl in *\n        | [ H : forall x, ?f x = ?f ?y -> _ |- _ ] => specialize (H _ eq_refl)\n        | [ H : forall x, ?f ?y = ?f x -> _ |- _ ] => specialize (H _ eq_refl)\n        | [ H : forall n, S n < S _ -> _ |- _ ] => specialize (fun n pf => H n (lt_n_S _ _ pf))\n        | [ H : nth_error nil ?x = Some _ |- _ ] => is_var x; destruct x\n        | [ H : forall m x, nth_error (_::_) m = Some _ -> _ |- _ ] => pose proof (H 0); specialize (fun m => H (S m))\n        | [ H : or _ _ |- _ ] => destruct H\n        | [ H : forall x, _ = x \\/ _ -> _ |- _ ] => pose proof (H _ (or_introl eq_refl)); specialize (fun x pf => H x (or_intror pf))\n        | [ H : ?x = None |- context[?x] ] => rewrite H\n        | [ H : S _ = S _ |- _ ] => inversion H; clear H\n        | [ H : appcontext[first_index_helper] |- _ ] => rewrite first_index_helper_first_index_error in H\n        | [ |- appcontext[first_index_helper] ] => rewrite first_index_helper_first_index_error\n        | [ H : option_rect _ _ _ ?v = Some _ |- _ ] => destruct v eqn:?; simpl in H\n        | [ H : option_rect _ _ _ ?v = None |- _ ] => destruct v eqn:?; simpl in H\n      end.\n\n  Local Ltac first_index_error_t :=\n    repeat match goal with\n             | _ => progress first_index_error_t'\n             | [ H : _ |- _ ] => rewrite H by repeat first_index_error_t'\n           end.\n\n  Lemma first_index_error_Some_correct {A} (P : A -> bool) (n : nat) (ls : list A)\n  : first_index_error P ls = Some n <-> ((exists elem, nth_error ls n = Some elem /\\ P elem = true)\n                                         /\\ forall m, m < n -> forall elem, nth_error ls m = Some elem -> P elem = false).\n  Proof.\n    revert n.\n    induction ls; simpl; intros.\n    { destruct n; first_index_error_t. }\n    { specialize (IHls (pred n)).\n      destruct n; first_index_error_t. }\n  Qed.\n\n  Lemma first_index_error_None_correct {A} (P : A -> bool) (ls : list A)\n  : first_index_error P ls = None <-> (forall elem, List.In elem ls -> P elem = false).\n  Proof.\n    induction ls; simpl; intros.\n    { first_index_error_t. }\n    { first_index_error_t.\n      match goal with\n        | [ H : first_index_error _ _ = Some _ |- _ ] => apply first_index_error_Some_correct in H\n      end.\n      first_index_error_t. }\n  Qed.\n\n  Lemma first_index_default_first_index_error\n        {A} (f : A -> bool)\n        default\n        (ls : list A)\n  : first_index_default f default ls\n    = option_rect (fun _ => nat) (fun x => x) default (first_index_error f ls).\n  Proof.\n    unfold first_index_default.\n    rewrite first_index_helper_first_index_error; simpl.\n    destruct (first_index_error f ls) as [n|] eqn:H; simpl; [ | reflexivity ].\n    destruct (nth_error ls n) eqn:H'; simpl; [ reflexivity | ].\n    exfalso.\n    apply first_index_error_Some_correct in H.\n    repeat (destruct_head and; destruct_head ex).\n    congruence.\n  Qed.\n\n  Lemma nth_error_In {A} (n : nat) (x : A) (ls : list A)\n  : nth_error ls n = Some x -> List.In x ls.\n  Proof.\n    revert n; induction ls; intros [|n]; simpl in *;\n    intros; try discriminate; unfold value in *.\n    { left; congruence. }\n    { right; eauto. }\n  Qed.\n\n  Lemma nth_error_None_long {A} (n : nat) (ls : list A)\n  : nth_error ls n = None <-> List.length ls <= n.\n  Proof.\n    revert n; induction ls;\n    intros [|n]; try (specialize (IHls n); destruct IHls);\n    simpl in *; split; intros;\n    unfold value in *;\n    try (reflexivity || omega || congruence);\n    intuition.\n  Qed.\n\n  Lemma nth_error_Some_short {A} (n : nat) (x : A) (ls : list A)\n  : nth_error ls n = Some x -> n < List.length ls.\n  Proof.\n    destruct (le_lt_dec (List.length ls) n) as [H|H];\n    intro H'; trivial.\n    apply nth_error_None_long in H; congruence.\n  Qed.\n\n  Lemma nth_error_nth {A} (ls : list A) (n : nat) (y : A)\n  : nth n ls y = match nth_error ls n with\n                   | Some x => x\n                   | None => y\n                 end.\n  Proof.\n    revert n; induction ls; intros [|n]; simpl in *; intros;\n    try discriminate;\n    unfold value in *;\n    eauto.\n  Qed.\n\n  Lemma nth_error_Some_nth {A} (ls : list A) (n : nat) (x : A)\n  : nth_error ls n = Some x -> forall y, nth n ls y = x.\n  Proof.\n    intros H ?; rewrite nth_error_nth, H; reflexivity.\n  Qed.\n\n  Lemma length_up_to n\n  : List.length (up_to n) = n.\n  Proof.\n    induction n; simpl; auto.\n  Qed.\n\n  Lemma filter_out_filter {A} f (ls : list A)\n  :  filter_out f ls = filter (fun x => negb (f x)) ls.\n  Proof.\n    induction ls; simpl; trivial; rewrite !IHls; edestruct f; reflexivity.\n  Qed.\n\n  Lemma filter_filter_out {A} f (ls : list A)\n  :  filter f ls = filter_out (fun x => negb (f x)) ls.\n  Proof.\n    induction ls; simpl; trivial; rewrite !IHls; edestruct f; reflexivity.\n  Qed.\n\n  Lemma nth'_helper_nth {A} n ls (default : A) offset (H : offset <= n)\n  : nth'_helper n ls default offset = nth (n - offset) ls default.\n  Proof.\n    revert n default offset H.\n    induction ls as [|x xs IHxs].\n    { simpl; intros; destruct (n - offset); reflexivity. }\n    { simpl; intros.\n      destruct (beq_nat n offset) eqn:H';\n        [ apply beq_nat_true in H'\n        | apply beq_nat_false in H' ];\n        subst;\n        rewrite ?minus_diag; trivial.\n      destruct (n - offset) eqn:H''.\n      { omega. }\n      { rewrite IHxs by omega.\n        f_equal.\n        omega. } }\n  Qed.\n\n  Lemma nth'_nth {A} n ls (default : A)\n  : nth' n ls default = nth n ls default.\n  Proof.\n    change (nth'_helper n ls default 0 = nth n ls default).\n    rewrite nth'_helper_nth by omega.\n    f_equal; omega.\n  Qed.\n\n\n  Lemma NoDup_filter {A} :\n    forall (f : A -> bool)\n           (l : list A),\n      NoDup l\n      -> NoDup (filter f l).\n  Proof.\n    induction l; simpl.\n    - constructor.\n    - case_eq (f a); simpl; intros.\n      + inversion H0; constructor; eauto.\n        subst; unfold not; intros H1;\n        apply filter_In in H1; intuition.\n      + inversion H0; eauto.\n  Qed.\n\n  Lemma eqlistA_app_iff {A} (R : relation A) (x y z : list A)\n  : SetoidList.eqlistA R (x ++ y) z <-> (exists x' y', (x' ++ y' = z)%list /\\ SetoidList.eqlistA R x x' /\\ SetoidList.eqlistA R y y').\n  Proof.\n    revert z.\n    induction x as [|x xs IHxs]; simpl; intros z;\n    split; intro H.\n    { eexists nil; eexists z; split; [ reflexivity | ].\n      split; first [ assumption | constructor ]. }\n    { destruct H as [x' [y' [H0 [H1 H2]]]]; subst.\n      inversion H1; subst; simpl.\n      assumption. }\n    { inversion_clear H.\n      match goal with\n        | [ H : SetoidList.eqlistA _ _ _ |- _ ]\n          => apply IHxs in H; clear IHxs\n      end.\n      repeat match goal with\n               | [ H : ex _ |- _ ] => destruct H\n               | [ H : and _ _ |- _ ] => destruct H\n               | _ => progress subst\n             end.\n      eexists (_::_)%list; simpl; eexists.\n      repeat split; first [ assumption | constructor; assumption ]. }\n    { repeat match goal with\n               | [ H : ex _ |- _ ] => destruct H\n               | [ H : and _ _ |- _ ] => destruct H\n               | _ => progress subst\n               | [ H : SetoidList.eqlistA _ (_::_) _ |- _ ] => inversion H; clear H\n               | _ => progress simpl\n               | [ |- SetoidList.eqlistA _ (_::_) (_::_) ] => constructor\n               | _ => assumption\n             end.\n      apply IHxs.\n      repeat esplit; eassumption. }\n  Qed.\n\n  Lemma eqlistA_eq {A} ls ls'\n  : @SetoidList.eqlistA A eq ls ls' <-> ls = ls'.\n  Proof.\n    split; intro H; subst; try reflexivity.\n    revert ls' H.\n    induction ls as [|x xs IHxs]; intros []; intros;\n    f_equal;\n    inversion H; subst; trivial; eauto with nocore.\n  Qed.\n\n  Lemma fold_left_orb_true (ls : list bool)\n  : fold_left orb ls true = true.\n  Proof.\n    induction ls; simpl; trivial.\n  Qed.\n\n  Lemma Forall_tails_id {A P} (ls : list A)\n        (H : Forall_tails P ls)\n  : P ls.\n  Proof.\n    destruct ls; simpl in *; try assumption.\n    destruct H; assumption.\n  Defined.\n\n  Lemma Forall_tails_app {A P} (ls ls' : list A)\n        (H : Forall_tails P (ls ++ ls'))\n  : Forall_tails P ls'.\n  Proof.\n    induction ls; simpl in *; trivial.\n    destruct H; auto.\n  Defined.\n\n  Lemma first_index_default_S_cons {A f k} {x} {xs : list A}\n  : first_index_default f (S k) (x::xs) = if (f x) then 0 else S (first_index_default f k xs).\n  Proof.\n    simpl.\n    rewrite first_index_default_first_index_error.\n    rewrite first_index_helper_first_index_error; simpl.\n    destruct (first_index_error f xs) eqn:H, (f x); trivial; simpl.\n    apply first_index_error_Some_correct in H.\n    repeat (destruct_head and; destruct_head ex).\n    match goal with\n      | [ H : ?x = Some _ |- context[?x] ] => rewrite H\n    end.\n    reflexivity.\n  Qed.\n\n  Definition Forall_ForallT_step\n             (Forall_ForallT\n              : forall A P ls,\n                forall ls' ls'', ls = ls' -> ls = ls''\n                                 -> (@Forall A P ls' <-> inhabited (@ForallT A P ls'')))\n             A P ls\n  : forall ls' ls'', ls = ls' -> ls = ls'' -> (@Forall A P ls' <-> inhabited (@ForallT A P ls'')).\n  Proof.\n    intros ls' ls'' H' H''; split; [ intro H | intros [H] ];\n    (destruct ls as [|x xs];\n     [\n     | specialize (@Forall_ForallT A P xs (tl ls') (tl ls'') (f_equal (@tl _) H') (f_equal (@tl _) H''));\n       pose proof (proj1' Forall_ForallT);\n       pose proof (proj2' Forall_ForallT) ]);\n    clear Forall_ForallT;\n    simpl in *;\n    repeat match goal with\n             | [ H : nil = ?ls |- inhabited (ForallT _ ?ls) ] => clear -H; solve [ repeat first [ constructor | subst ] ]\n           end;\n    try solve [ repeat constructor ]; simpl in *.\n    { destruct H;\n      try (exfalso; clear -H'; abstract congruence);\n      simpl in *;\n      specialize_by assumption;\n      destruct_head inhabited;\n      constructor.\n      destruct ls'';\n        try (exfalso; clear -H''; abstract congruence).\n      simpl in *.\n      repeat first [ assumption | constructor ].\n      apply (f_equal (hd x)) in H''.\n      apply (f_equal (hd x)) in H'.\n      simpl in *.\n      clear -H H'' H'.\n      pose proof (eq_trans (eq_sym H') H'') as H'''; clear H' H''.\n      subst; assumption. }\n    { clear -H'; subst; constructor. }\n    { destruct ls';\n      try (exfalso; clear -H'; abstract congruence);\n      simpl in *.\n      destruct ls'';\n        try (exfalso; clear -H''; abstract congruence);\n        simpl in *.\n      destruct_head prod.\n      specialize_by ltac:(repeat first [ assumption | constructor ]).\n      repeat first [ assumption | constructor ].\n      apply (f_equal (hd x)) in H''.\n      apply (f_equal (hd x)) in H'.\n      simpl in *.\n      clear -p H'' H'.\n      pose proof (eq_trans (eq_sym H') H'') as H'''; clear H' H''.\n      subst; assumption. }\n  Defined.\n\n  Global Arguments Forall_ForallT_step {_ _ _} _ _ _ _ _ : simpl never.\n\n  Fixpoint Forall_ForallT' A P ls {struct ls}\n  : forall ls' ls'', ls = ls' -> ls = ls'' -> (@Forall A P ls' <-> inhabited (@ForallT A P ls''))\n    := @Forall_ForallT_step (@Forall_ForallT') A P ls.\n  Global Arguments Forall_ForallT' {_ _ _} _ _ _ _.\n  Definition Forall_ForallT A P ls\n  : @Forall A P ls <-> inhabited (@ForallT A P ls)\n    := @Forall_ForallT' A P ls ls ls eq_refl eq_refl.\n  Global Arguments Forall_ForallT {_ _ _}.\n\n  Lemma step_Forall_ForallT' {A P ls ls' ls'' H' H''}\n  : @Forall_ForallT' A P ls ls' ls'' H' H'' = @Forall_ForallT_step (@Forall_ForallT') A P ls ls' ls'' H' H''.\n  Proof.\n    destruct ls; reflexivity.\n  Defined.\n\n  Fixpoint Forall_ForallT_Forall_eq {A P ls} (x : @Forall A P ls) {struct x}\n  : proj2' Forall_ForallT (proj1' Forall_ForallT x) = x.\n  Proof.\n    unfold Forall_ForallT in *.\n    destruct x as [|? xs p ps]; simpl in *;\n    [ | specialize (@Forall_ForallT_Forall_eq A P xs ps) ].\n    { reflexivity. }\n    { edestruct (@Forall_ForallT');\n      unfold eq_ind_r.\n      simpl in *.\n      match goal with\n        | [ |- context[match ?f ?x with _ => _ end] ]\n          => destruct (f x) eqn:H'\n      end.\n      rewrite Forall_ForallT_Forall_eq; reflexivity. }\n  Qed.\n\n  Fixpoint ForallT_Forall_ForallT_eq {A} {P : A -> Prop} ls (x : inhabited (@ForallT A P ls)) {struct ls}\n  : proj1' Forall_ForallT (proj2' (@Forall_ForallT A P ls) x) = x.\n  Proof.\n    unfold Forall_ForallT in *.\n    destruct ls as [|v vs];\n      [ clear ForallT_Forall_ForallT_eq | specialize (@ForallT_Forall_ForallT_eq A P vs) ];\n      simpl in *;\n      destruct_head inhabited;\n      destruct_head prod;\n      destruct_head True.\n    { reflexivity. }\n    { match goal with\n        | [ x : _ |- _ ] => specialize (ForallT_Forall_ForallT_eq (inhabits x))\n      end.\n      unfold eq_ind_r in *; simpl in *.\n      edestruct (@Forall_ForallT'); simpl in *.\n      repeat (rewrite ForallT_Forall_ForallT_eq; simpl).\n      reflexivity. }\n  Qed.\n\n  Fixpoint ForallT_code A P ls {struct ls} : @ForallT A P ls -> @ForallT A P ls -> Prop\n    := match ls return @ForallT A P ls -> @ForallT A P ls -> Prop with\n         | nil => fun _ _ => True\n         | x::xs => fun H H' => fst H = fst H' /\\ @ForallT_code A P xs (snd H) (snd H')\n       end.\n  Global Arguments ForallT_code {A P ls} _ _.\n  Fixpoint ForallT_encode A P ls {struct ls}\n  : forall (x y : @ForallT A P ls), x = y -> ForallT_code x y.\n  Proof.\n    destruct ls as [|v vs]; simpl; intros x y p.\n    { constructor. }\n    { specialize (@ForallT_encode A P vs (snd x) (snd y) (f_equal snd p)).\n      apply (f_equal fst) in p.\n      split; assumption. }\n  Defined.\n  Global Arguments ForallT_encode {A P ls} {_ _} _.\n  Fixpoint ForallT_decode A P ls {struct ls}\n  : forall (x y : @ForallT A P ls), ForallT_code x y -> x = y.\n  Proof.\n    destruct ls as [|v vs]; simpl; intros x y p.\n    { destruct x, y; reflexivity. }\n    { apply injective_projections'.\n      { apply p. }\n      { apply ForallT_decode, p. } }\n  Defined.\n  Global Arguments ForallT_decode {A P ls} {_ _} _.\n  Fixpoint ForallT_endecode A P ls {struct ls}\n  : forall (x y : @ForallT A P ls) p, @ForallT_encode A P ls x y (ForallT_decode p) = p.\n  Proof.\n    destruct ls as [|v vs]; simpl; intros x y p.\n    { destruct p; reflexivity. }\n    { destruct p as [p0 p1], x, y; simpl in *.\n      destruct p0; simpl in *.\n      apply f_equal2;\n        [ rewrite f_equal_fst_injective_projections'\n        | rewrite f_equal_snd_injective_projections' ];\n        eauto. }\n  Qed.\n  Fixpoint ForallT_deencode A P ls {struct ls}\n  : forall (x y : @ForallT A P ls) p, @ForallT_decode A P ls x y (ForallT_encode p) = p.\n  Proof.\n    destruct ls as [|v vs]; simpl; intros x y p.\n    { destruct p, x; reflexivity. }\n    { rewrite ForallT_deencode.\n      destruct p, x; reflexivity. }\n  Qed.\n\n  Lemma Forall_proof_irrelevance {A P ls} (x y : @Forall A P ls)\n        (pi : forall a (x y : P a), x = y)\n  : x = y.\n  Proof.\n    rewrite <- (Forall_ForallT_Forall_eq x), <- (Forall_ForallT_Forall_eq y).\n    apply f_equal.\n    induction ls as [|v vs IHvs].\n    { reflexivity. }\n    { unfold Forall_ForallT in *.\n      revert IHvs.\n      set (ls := v::vs).\n      set (ls' := v::vs).\n      set (ls'' := v::vs).\n      pose (eq_refl : v::vs = ls) as H.\n      pose (eq_refl : ls = ls') as H'.\n      pose (eq_refl : ls = ls'') as H''.\n      change (v::vs) with ls' in x.\n      change (v::vs) with ls'' in y.\n      change\n        ((forall (x0 : Forall P (tl ls')) (y0 : Forall P (tl ls'')),\n            proj1' (Forall_ForallT' (tl ls') (tl ls'') (f_equal (@tl _) H') (f_equal (@tl _) H'')) x0\n            = proj1' (Forall_ForallT' (tl ls'') (tl ls'') (f_equal (@tl _) H'') (f_equal (@tl _) H'')) y0)\n         -> proj1' (Forall_ForallT' ls' ls'' H' H'') x\n            = proj1' (Forall_ForallT' ls'' ls'' H'' H'') y).\n      clearbody H H' H'' ls ls' ls''.\n      intro IHvs.\n      rewrite !step_Forall_ForallT'.\n      simpl.\n      destruct ls, x, y; try congruence.\n      simpl in *.\n      erewrite IHvs; clear IHvs.\n      match goal with\n        | [ |- match ?e with _ => _ end = match ?e' with _ => _ end ]\n          => unify e e'; destruct e\n      end.\n      unfold eq_ind_r; simpl.\n      repeat (f_equal; []).\n      repeat match goal with\n               | _ => intro\n               | _ => progress simpl in *\n               | _ => progress subst\n               | _ => solve [ eauto with nocore ]\n               | [ |- context[f_equal ?f ?H] ]\n                 => generalize (f_equal f H); clear H\n             end. }\n  Qed.\n\n  Lemma In_InT {A} (x : A) (ls : list A) (H : InT x ls)\n  : In x ls.\n  Proof.\n    induction ls as [|y ys IHys]; simpl in *; trivial.\n    destruct H; [ left | right ]; eauto with nocore.\n  Qed.\n\n  Lemma tl_drop {A} (ls : list A) (n : nat)\n  : tl (List.drop n ls) = List.drop n (tl ls).\n  Proof.\n    revert n; induction ls as [|x xs IHxs].\n    { intros [|?]; reflexivity. }\n    { simpl.\n      destruct n; simpl; trivial.\n      rewrite IHxs; destruct xs; trivial; simpl.\n      apply drop_all; simpl; omega. }\n  Qed.\n\n  Lemma map_ext_in {A B} (f f' : A -> B) (ls : list A)\n        (H : forall a, List.In a ls -> f a = f' a)\n  : List.map f ls = List.map f' ls.\n  Proof.\n    induction ls; simpl; trivial.\n    rewrite H, IHls.\n    { reflexivity. }\n    { intros; apply H; right; assumption. }\n    { left; reflexivity. }\n  Qed.\n\n  Lemma list_bin_map {A B} (f : A -> B) (beq : B -> B -> bool) (ls : list A) x\n  : list_bin beq (f x) (map f ls) = list_bin (fun x y => beq (f x) (f y)) x ls.\n  Proof.\n    induction ls; trivial; simpl.\n    rewrite IHls; reflexivity.\n  Qed.\n\n  Lemma uniquize_map {A B} (f : A -> B) (beq : B -> B -> bool) (ls : list A)\n  : uniquize beq (map f ls) = map f (uniquize (fun x y => beq (f x) (f y)) ls).\n  Proof.\n    induction ls; trivial; simpl.\n    rewrite !IHls, list_bin_map.\n    edestruct @list_bin; simpl; reflexivity.\n  Qed.\n\n  Definition list_rect_In {A} (P : list A -> Type)\n             (ls : list A)\n             (Hnil : P nil)\n             (Hcons : forall x xs, In x ls -> P xs -> P (x::xs))\n  : P ls.\n  Proof.\n    induction ls as [|x xs IHxs]; [ assumption | ].\n    apply Hcons.\n    { left; reflexivity. }\n    { apply IHxs; intros x' xs' H'.\n      apply Hcons.\n      right; exact H'. }\n  Defined.\n\n  Lemma fold_right_and_True_app ls ls'\n  : fold_right and True (ls ++ ls') <-> (fold_right and True ls /\\ fold_right and True ls').\n  Proof.\n    revert ls'; induction ls as [|?? IHls]; simpl; intros; try tauto.\n    rewrite IHls; clear IHls.\n    tauto.\n  Qed.\n\n  Lemma fold_right_and_True_flatten ls\n  : fold_right and True (flatten ls) <-> fold_right and True (map (fold_right and True) ls).\n  Proof.\n    induction ls as [|?? IHls]; try tauto; simpl.\n    rewrite <- IHls; clear IHls.\n    rewrite fold_right_and_True_app; reflexivity.\n  Qed.\n\n  Lemma NoDup_app {A} (ls ls' : list A)\n  : NoDup (ls ++ ls') -> NoDup ls /\\ NoDup ls'.\n  Proof.\n    induction ls; simpl; intro H; split; trivial; try constructor;\n    simpl in *.\n    { inversion H; subst.\n      eauto using in_or_app. }\n    { apply IHls.\n      inversion H; subst; assumption. }\n    { apply IHls; inversion H; subst; assumption. }\n  Qed.\n  Lemma NoDup_app_in {A} (ls ls' : list A) (x : A) (H : NoDup (ls ++ ls'))\n  : In x ls' -> In x ls -> False.\n  Proof.\n    intros H0 H1.\n    induction ls as [|?? IHls]; simpl in *; trivial.\n    destruct H1; inversion H; clear H; subst; eauto.\n    rewrite in_app_iff in *.\n    eauto.\n  Qed.\n\n  Lemma NoDup_app_in_iff {A} (ls ls' : list A)\n  : NoDup (ls ++ ls') <-> (NoDup ls /\\ NoDup ls' /\\\n                           forall x, In x ls' -> In x ls -> False).\n  Proof.\n    induction ls as [|?? IHls]; simpl in *; trivial;\n    repeat (split || intro);\n    repeat match goal with\n             | _ => solve [ constructor ]\n             | _ => assumption\n             | _ => progress simpl in *\n             | _ => progress destruct_head and\n             | _ => progress destruct_head iff\n             | _ => progress split_and\n             | _ => progress subst\n             | _ => progress specialize_by assumption\n             | _ => progress specialize_by tauto\n             | [ H : NoDup (_::_) |- _ ] => inversion H; clear H\n             | [ |- NoDup (_::_) ] => constructor\n             | [ H : _ |- _ ] => rewrite in_app_iff in H\n             | _ => rewrite in_app_iff\n             | [ H : ~(_ \\/ _) |- _ ] => apply Decidable.not_or in H\n             | _ => progress destruct_head or\n             | _ => solve [ eauto using eq_refl with nocore ]\n             | [ |- ~(?A \\/ ?B) ] => cut (~A /\\ ~B); [ tauto | ]\n             | [ |- _ /\\ _ ] => split\n             | [ H : ?T, H' : ?T /\\ _ -> ?B |- _ ] => specialize (fun X => H' (conj H X))\n             | _ => progress split_in_context_by or (fun a b : Type => a) (fun a b : Type => b) ltac:(fun H => intuition eauto)\n             | [ H : forall x, _ -> _ = x -> _ |- _ ] => specialize (fun k => H _ k eq_refl)\n           end.\n  Qed.\n  Lemma NoDup_rev {A} (ls : list A)\n  : NoDup (rev ls) <-> NoDup ls.\n  Proof.\n    induction ls as [|?? IHls]; simpl.\n    { split; intro; constructor. }\n    { split; intro H.\n      { constructor.\n        { rewrite in_rev.\n          rapply @NoDup_app_in; [ eassumption | left; reflexivity ]. }\n        { apply NoDup_app in H; apply IHls, H. } }\n      { rewrite NoDup_app_in_iff, IHls.\n        inversion H; clear H; subst.\n        repeat split; simpl; trivial.\n        { repeat constructor; simpl; intro; trivial. }\n        { intros; destruct_head or; destruct_head False; subst.\n          rewrite <- in_rev in *.\n          eauto with nocore. } } }\n  Qed.\n\n  Lemma uniquize_nonnil {A} beq (ls : list A)\n  : ls <> nil <-> Operations.List.uniquize beq ls <> nil.\n  Proof.\n    induction ls as [|a ls IHls]; simpl.\n    { reflexivity. }\n    { split; intros H H'.\n      { destruct (list_bin beq a (Operations.List.uniquize beq ls)) eqn:Heq.\n        { rewrite H' in IHls.\n          destruct ls; simpl in *; try congruence.\n          destruct IHls.\n          specialize_by congruence.\n          congruence. }\n        { congruence. } }\n      { congruence. } }\n  Qed.\n  Lemma rev_nonnil {A} (ls : list A)\n  : ls <> nil <-> rev ls <> nil.\n  Proof.\n    destruct ls; simpl.\n    { reflexivity. }\n    { split; intros H H';\n      apply (f_equal (@List.length _)) in H';\n      rewrite ?app_length in H';\n      simpl in *;\n      omega. }\n  Qed.\n\n  Lemma Forall_tl {A} P (ls : list A)\n  : List.Forall P ls -> List.Forall P (tl ls).\n  Proof.\n    intro H; destruct H; simpl; try constructor; assumption.\n  Qed.\n  Lemma Forall_inv_iff {A} P x (xs : list A)\n  : List.Forall P (x::xs) <-> (P x /\\ List.Forall P xs).\n  Proof.\n    split; intro H.\n    { inversion H; subst; split; assumption. }\n    { constructor; apply H. }\n  Qed.\n\n  Lemma app_take_drop {A} (ls : list A) n\n  : (Operations.List.take n ls ++ Operations.List.drop n ls)%list = ls.\n  Proof.\n    revert ls; induction n as [|n IHn]; intros.\n    { reflexivity. }\n    { destruct ls as [|x xs]; simpl; trivial.\n      apply f_equal.\n      apply IHn. }\n  Qed.\n\n  Lemma map_proj1_sig_sig_In {A} (ls : list A)\n  : List.map (@proj1_sig _ _) (sig_In ls) = ls.\n  Proof.\n    induction ls; simpl; f_equal; rewrite map_map; simpl; assumption.\n  Qed.\n\n  Lemma in_sig_uip {A} {P : A -> Prop} (UIP : forall x (p q : P x), p = q)\n        (ls : list { x : A | P x })\n        x\n  : List.In x ls <-> List.In (proj1_sig x) (List.map (@proj1_sig _ _) ls).\n  Proof.\n    induction ls as [|y ys IHls]; simpl.\n    { reflexivity. }\n    { repeat match goal with\n               | [ |- ?x = ?x \\/ _ ] => left; reflexivity\n               | [ H : ?A |- _ \\/ ?A ] => right; assumption\n               | [ |- exist _ ?x _ = exist _ ?x _ \\/ _ ] => left; apply f_equal\n               | _ => progress subst\n               | _ => progress simpl in *\n               | [ H : ?A -> ?B, H' : ?A |- _ ] => specialize (H H')\n               | [ H : _ <-> _ |- _ ] => destruct H\n               | [ |- _ <-> _ ] => split\n               | _ => intro\n               | [ H : _ \\/ _ |- _ ] => destruct H\n               | [ H : proj1_sig ?x = _ |- _ ] => is_var x; destruct x\n               | [ |- context[exist _ _ _ = ?x] ] => is_var x; destruct x\n               | _ => solve [ eauto with nocore ]\n             end. }\n  Qed.\n\n  Lemma step_rev_up_to {n}\n  : List.rev (up_to n)\n    = match n with\n        | 0 => nil\n        | S n' => 0::map S (List.rev (up_to n'))\n      end.\n  Proof.\n    induction n; simpl; [ reflexivity | ].\n    etransitivity; [ rewrite IHn | reflexivity ].\n    destruct n; simpl; [ reflexivity | ].\n    rewrite map_app; reflexivity.\n  Qed.\n\n  Lemma map_nth_dep_helper {A B} (f' : nat -> nat) (f : nat -> A -> B) (l : list A) (d : A) (n : nat)\n  : nth n (map (fun n'a => f (fst n'a) (snd n'a))\n               (combine (List.map f' (List.rev (up_to (List.length l)))) l))\n        (f (f' n) d)\n    = f (f' n) (nth n l d).\n  Proof.\n    rewrite <- (map_nth (f (f' n))).\n    rewrite step_rev_up_to.\n    revert f' n; induction l as [|x xs IHxs]; intros.\n    { destruct n; simpl; reflexivity. }\n    { destruct n; simpl; [ reflexivity | ].\n      specialize (IHxs (fun x => f' (S x))).\n      rewrite <- IHxs; clear IHxs.\n      rewrite map_map.\n      rewrite <- step_rev_up_to.\n      reflexivity. }\n  Qed.\n\n  Lemma map_nth_dep {A B} (f : nat -> A -> B) (l : list A) (d : A) (n : nat)\n  : nth n (map (fun n'a => f (fst n'a) (snd n'a))\n               (combine (List.rev (up_to (List.length l))) l))\n        (f n d)\n    = f n (nth n l d).\n  Proof.\n    rewrite <- (map_nth_dep_helper (fun x => x)).\n    rewrite List.map_id; reflexivity.\n  Qed.\n\n  Lemma combine_map_l {A A' B} (g : A -> A') ls ls'\n  : List.combine (List.map g ls) ls'\n    = List.map (fun x : A * B => (g (fst x), snd x))\n               (List.combine ls ls').\n  Proof.\n    revert ls'; induction ls as [|l ls IHls];\n    intros [|l' ls']; simpl; f_equal.\n    eauto with nocore.\n  Qed.\n\n  Lemma combine_map_r {A B B'} (g : B -> B') ls ls'\n  : List.combine ls (List.map g ls')\n    = List.map (fun x : A * B => (fst x, g (snd x)))\n               (List.combine ls ls').\n  Proof.\n    revert ls'; induction ls as [|l ls IHls];\n    intros [|l' ls']; simpl; f_equal.\n    eauto with nocore.\n  Qed.\n\n  Section fold_right_beq.\n    Context {A}\n            {eq_A : BoolDecR A}\n            {Abl : BoolDec_bl (@eq A)}\n            {R}\n            (f : A -> R)\n            (x : A)\n            (base : R).\n\n    Lemma fold_right_beq_in_correct ls\n      : List.fold_right\n          (fun y else_case => If beq y x Then f y Else else_case)\n          base\n          ls\n        = (if list_bin beq x ls then f x else base).\n    Proof.\n      induction ls as [|y ys IHys].\n      { simpl; reflexivity. }\n      { simpl; rewrite IHys; clear IHys.\n        destruct (beq y x) eqn:Heq; simpl.\n        { apply bl in Heq; subst.\n          rewrite Bool.orb_true_r; reflexivity. }\n        { rewrite Bool.orb_false_r; reflexivity. } }\n    Qed.\n  End fold_right_beq.\n\n  Section fold_right_beq'.\n    Context {A}\n            {eq_A : BoolDecR A}\n            {Abl : BoolDec_bl (@eq A)}\n            {Alb : BoolDec_lb (@eq A)}\n            {R}\n            (f : A -> R)\n            (x : A)\n            (base : R).\n\n    Lemma fold_right_beq_in_correct' ls\n      : List.fold_right\n          (fun y else_case => If beq x y Then f y Else else_case)\n          base\n          ls\n        = (if list_bin beq x ls then f x else base).\n    Proof.\n      induction ls as [|y ys IHys].\n      { simpl; reflexivity. }\n      { simpl; rewrite IHys; clear IHys.\n        destruct (beq y x) eqn:Heq; simpl.\n        { apply bl in Heq; subst.\n          rewrite lb by reflexivity.\n          rewrite Bool.orb_true_r; reflexivity. }\n        { destruct (beq x y) eqn:Heq'; simpl.\n          { apply bl in Heq'; subst.\n            rewrite lb in Heq by reflexivity.\n            congruence. }\n          { rewrite Bool.orb_false_r; reflexivity. } } }\n    Qed.\n  End fold_right_beq'.\n\n  Lemma fold_right_uniquize {A B}\n        {eq_A : BoolDecR A}\n        {Abl : BoolDec_bl (@eq A)}\n        {Alb : BoolDec_lb (@eq A)}\n        (f : A -> B) ls x base\n  : List.fold_right\n      (fun y else_case => If beq x y Then f y Else else_case)\n      base\n      (uniquize beq ls)\n    = List.fold_right\n        (fun y else_case => If beq x y Then f y Else else_case)\n        base\n        ls.\n  Proof.\n    rewrite !fold_right_beq_in_correct'.\n    destruct (list_bin beq x ls) eqn:Heq;\n      destruct (list_bin beq x (uniquize beq ls)) eqn:Heq';\n      try reflexivity;\n      exfalso;\n      first [ apply (list_in_bl bl) in Heq\n            | apply (list_in_bl bl) in Heq' ];\n      first [ rewrite (list_in_lb lb)\n              in Heq\n              by (eapply uniquize_In; eassumption)\n            | rewrite (list_in_lb lb)\n              in Heq'\n              by (eapply (uniquize_In_refl _ _ _ (lb eq_refl) bl); assumption) ];\n      try congruence.\n  Qed.\n\n  Lemma uniquize_nil {A beq} (ls : list A)\n  : uniquize beq ls = nil <-> ls = nil.\n  Proof.\n    induction ls as [|l ls IHls]; simpl.\n    { reflexivity. }\n    { destruct (Equality.list_bin beq l (uniquize beq ls)) eqn:Heq.\n      { apply Equality.list_inA_bl in Heq.\n        rewrite SetoidList.InA_altdef, Exists_exists in Heq.\n        destruct_head ex.\n        destruct_head and.\n        split; intro H'; try congruence.\n        rewrite H' in *; simpl in *.\n        destruct_head False. }\n      { split; congruence. } }\n  Qed.\n\n  Lemma uniquize_singleton {A beq}\n        (bl : forall x y : A, beq x y = true -> x = y)\n        (lb : forall x y : A, x = y -> beq x y)\n        (ls : list A) (x : A)\n  : uniquize beq ls = [x] <-> (forall y, In y ls <-> x = y).\n  Proof.\n    induction ls; simpl.\n    { intuition (subst; eauto; split_iff; try congruence). }\n    { destruct (uniquize beq ls) eqn:Heq.\n      { rewrite uniquize_nil in Heq; subst; simpl in *.\n        clear IHls.\n        setoid_rewrite or_false.\n        repeat first [ split\n                     | intro\n                     | progress split_iff\n                     | progress subst\n                     | congruence\n                     | progress f_equal; []\n                     | solve [ eauto ] ]. }\n      { repeat match goal with\n                 | [ |- context[Equality.list_bin ?beq ?x ?ls] ]\n                   => destruct (Equality.list_bin beq x ls) eqn:?\n                 | [ H : Equality.list_bin _ _ _ = true |- _ ]\n                   => apply (Equality.list_in_bl bl) in H\n                 | _ => progress split_iff\n                 | _ => progress simpl in *\n                 | [ H : orb _ _ = true |- _ ] => apply Bool.orb_true_iff in H\n                 | [ H : orb _ _ = false |- _ ] => apply Bool.orb_false_iff in H\n                 | _ => progress subst\n                 | _ => progress split_and\n                 | [ H : _::_ = _::_ |- _ ] => inversion H; clear H\n                 | _ => progress specialize_by ltac:(exact eq_refl)\n                 | _ => congruence\n                 | [ H : forall y, ?a = y \\/ _ -> _ = y |- _ ]\n                   => pose proof (H _ (or_introl eq_refl)); subst a\n                 | [ H : forall y, ?x = y \\/ @?P y -> ?x = y |- _ ]\n                   => assert (forall y, P y -> x = y)\n                     by (intros; apply H; right; assumption);\n                     clear H\n                 | [ H : forall y, @?P y -> @?P y \\/ _ |- _ ]\n                   => clear H\n                 | [ H : (forall x, @?A x <-> @?B x) -> _,\n                         H' : forall x, @?A x -> @?B x\n                                        |- _ ]\n                   => specialize (fun H'' => H (fun x => conj (H' x) (H'' x)))\n                 | [ H : (forall x, ?a = x -> @?P x) -> _ |- _ ]\n                   => specialize (fun pf' : P a\n                                  => H (fun x pf => match pf in (_ = y) return P y with\n                                                      | eq_refl => pf'\n                                                    end))\n                 | [ H : forall y, In y ?ls -> _ = y,\n                       H' : In ?y' ?ls |- _ ]\n                   => pose proof (H _ H'); subst y'\n                 | [ |- ?x = ?x \\/ _ ] => left; reflexivity\n                 | [ |- ?x::_ = ?x::_ ] => apply f_equal\n                 | [ H : ?x::_ = ?x::_ -> _ |- _ ] => specialize (fun H' => H (f_equal (cons x) H'))\n                 | [ Heq : uniquize ?beq ?ls = _::_, H' : In ?x ?ls -> _ |- _ ]\n                   => progress specialize_by ltac:(apply (ListFacts.uniquize_In _ beq);\n                                                   rewrite Heq; first [ left; reflexivity\n                                                                      | right; assumption ])\n                 | _ => progress destruct_head False\n                 | [ Heq : uniquize ?beq ?ls = ?x::_, H' : forall y, In y ?ls -> _ = y |- _ ]\n                   => let H := fresh in\n                      assert (H : In x ls)\n                        by (apply (ListFacts.uniquize_In _ beq);\n                            rewrite Heq; left; reflexivity);\n                        pose proof (H' _ H); subst x\n                 | [ H : context[beq ?x ?x] |- _ ] => rewrite lb in H by reflexivity\n                 | _ => progress destruct_head or\n                 | _ => split\n                 | _ => intro\n               end. } }\n  Qed.\n\n  Lemma find_first_index_error {A} {beq : A -> A -> bool} (bl : forall x y, beq x y = true -> x = y)\n        {B C} (f : A * B -> C) x ls default\n  : option_rect\n      (fun _ => C)\n      (fun idx => nth idx (map f ls) default)\n      default\n      (List.first_index_error\n         (beq x)\n         (map fst ls))\n    = option_rect\n        (fun _ => C)\n        f\n        default\n        (find (fun k => beq x (fst k)) ls).\n  Proof.\n    induction ls as [|l ls IHls]; simpl; [ reflexivity | ].\n    repeat match goal with\n             | _ => rewrite <- IHls; clear IHls\n             | _ => reflexivity\n             | [ |- context[if ?e then _ else _] ] => destruct e eqn:?; simpl\n           end; [].\n    rewrite first_index_helper_first_index_error; simpl.\n    match goal with\n      | [ |- _ = option_rect _ _ _ ?x ]\n        => destruct x eqn:Heq'\n    end; simpl.\n    { apply first_index_error_Some_correct in Heq'.\n      destruct Heq' as [[? [Heq' ?]] ?].\n      rewrite Heq'; simpl; reflexivity. }\n    { reflexivity. }\n  Qed.\n\n  Lemma map_combine_id {A B} (f : A * A -> B) (ls : list A)\n    : List.map f (combine ls ls) = List.map (fun x => f (x, x)) ls.\n  Proof.\n    induction ls as [|l ls IHls]; simpl; [ | rewrite IHls ]; reflexivity.\n  Qed.\n\n  Lemma length_filter {A} f (ls : list A) : length (filter f ls) <= length ls.\n  Proof.\n    induction ls as [|l ls IHls]; simpl.\n    { reflexivity. }\n    { edestruct f; simpl;\n      try apply le_n_S;\n      try apply le_S;\n      apply IHls. }\n  Qed.\n\n  Lemma length_filter_eq {A f} {ls : list A} (H : length (filter f ls) = length ls)\n    : filter f ls = ls.\n  Proof.\n    induction ls as [|l ls IHls]; simpl in *.\n    { reflexivity. }\n    { edestruct f; simpl in *;\n      f_equal;\n      try apply IHls;\n      try omega.\n      { pose proof (length_filter f ls).\n        omega. } }\n  Qed.\n\n  Lemma fold_right_andb_true_map_filter {A} (f : A -> bool) (ls : list A)\n    : fold_right andb true (map f (filter f ls)) = true.\n  Proof.\n    induction ls as [|l ls IHls]; simpl.\n    { reflexivity. }\n    { destruct (f l) eqn:H; simpl; rewrite ?H; simpl; assumption. }\n  Qed.\nEnd ListFacts.\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/List/ListFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.6681411446056065}}
{"text": "Require Import A1_Plan A2_Orientation A5_Cercle A7_Tactics .\nRequire Import C1_Distance C2_CircleAndDistance C5_TriangularInequality C7_Tactics.\n\nSection INTERSECTION_CIRCLES_PROPERTIES.\n\nDefinition IntersectionCirclesPoint (c1 c2 : Circle) (H : SecantCircles c1 c2) := \nlet (M, _) := (InterCirclesPointDef c1 c2 H) in M.\n\nLemma OnCircle1IntersectionCirclesPoint : forall (c1 c2 : Circle) (H : SecantCircles c1 c2),\n\tOnCircle c1 (IntersectionCirclesPoint c1 c2 H).\nProof.\n\tintros; unfold IntersectionCirclesPoint in |- *.\n\tsetInterCircles c1 c2 ipattern:(J).\n\texact Hoc.\nQed.\n\nLemma OnCircle2IntersectionCirclesPoint : forall (c1 c2 : Circle) (H : SecantCircles c1 c2),\n\tOnCircle c2 (IntersectionCirclesPoint c1 c2 H).\nProof.\n\tintros; unfold IntersectionCirclesPoint in |- *.\n\tsetInterCircles c1 c2 ipattern:(J).\n\texact Hoc0.\nQed.\n\nLemma NotClockwiseIntersectionCirclesPoint : forall (c1 c2 : Circle) (H : SecantCircles c1 c2),\n\t~Clockwise (Center c2) (IntersectionCirclesPoint c1 c2 H) (Center c1).\nProof.\n\tintros; unfold IntersectionCirclesPoint in |- *.\n\tsetInterCircles c1 c2 ipattern:(J).\n\texact Hck.\nQed.\n\nLemma UniqueIntersectionCirclesPoint : forall (c1 c2 : Circle) (H : SecantCircles c1 c2), forall M : Point,\n\tOnCircle c1 M -> OnCircle c2 M ->   ~Clockwise (Center c2) M (Center c1) ->\n\tM = IntersectionCirclesPoint c1 c2 H.\nProof.\n\tintros; unfold IntersectionCirclesPoint in |- *.\n\tsetInterCircles c1 c2 ipattern:(J).\n\tapply sym_eq; apply Hun; intuition.\nQed.\n\nLemma EqPointsIntersectionCircles : forall (c1 c2 : Circle) (H : SecantCircles c1 c2), forall M N : Point,\n\tOnCircle c1 M -> OnCircle c2 M ->  ~Clockwise (Center c2) M (Center c1) ->\n\tOnCircle c1 N -> OnCircle c2 N -> ~Clockwise (Center c2) N (Center c1) ->\n\tM = N.\nProof.\n\tintros; apply trans_eq with (y := IntersectionCirclesPoint c1 c2 H).\n\t apply UniqueIntersectionCirclesPoint; trivial.\n\t apply sym_eq; apply UniqueIntersectionCirclesPoint; trivial.\nQed.\n\nLemma EqThirdPoint : forall A B M N : Point,\n\tA <> B ->\n\tDistance A M = Distance A N -> \n\tDistance B M = Distance B N ->  \n\t~Clockwise A M B ->\n\t~Clockwise A N B ->\n\tM = N.\nProof.\n\tintros.\n\tsetCircle0 A A M ipattern:(gamma1).\n\tsetCircle0 B B M ipattern:(gamma2).\n\tapply (EqPointsIntersectionCircles gamma2 gamma1); simplCircle2.\n\t immediate2.\n\t immediate2.\n\t immediate2.\n\t immediate2.\n\t immediate2.\n\t immediate2.\n\t immediate2.\n\t immediate2.\nQed.\n\nEnd INTERSECTION_CIRCLES_PROPERTIES.\n", "meta": {"author": "coq-contribs", "repo": "euclidean-geometry", "sha": "06838851a5924918d98e5a9c07ffa84021e13af7", "save_path": "github-repos/coq/coq-contribs-euclidean-geometry", "path": "github-repos/coq/coq-contribs-euclidean-geometry/euclidean-geometry-06838851a5924918d98e5a9c07ffa84021e13af7/D1_IntersectionCirclesProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.6681411416935169}}
{"text": "(* HEADER\n  Jacob Adley \n  Verified implementation of Leftist-Min-Heap\n  http://typeocaml.com/2015/03/12/heap-leftist-heap/\n  *)\n\n(* Arguments ... : simpl never. *)\n\n(* IMPORTS *)\n(*From VFA *)Require Import Perm.\n(*From QuickChick Require Import QuickChick.*)\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(* --- DEFINITIONS --- *)\nVariable default : nat.\n\nAxiom le_default:\n  forall n : nat, n < default.\n\nAxiom min_default:\n  forall n : nat, (min n default) = n.\n\n(* bounds nw ne sw se *)\nInductive heap : Type :=\n  | E : heap\n    (* left value right rank (length of path to rightmost E) *)\n  | T : heap -> nat -> heap -> nat -> heap.\n\nDefinition empty_heap := E.\n\nDefinition rank (t: heap) :=\n  match t with\n  | E => 0\n  | T _ _ _ rnk => rnk\n  end.\n\nFixpoint size (t: heap) :=\n  match t with\n  | E => 0\n  | T l _ r _ => S ((size l) + (size r))\n  end.\n\n(* rank of right child is always <= rank of left child *)\nFixpoint merge (t1: heap) := fix merge_r (t2: heap) :=\n  match t1,t2 with\n  | E, _ => t2\n  | _, E => t1\n  | T l1 v1 r1 _, T l2 v2 r2 _ =>\n      if (v1 >? v2)\n      then\n        if ((rank (merge_r r2)) <=? (rank l2))\n        then T l2 v2 (merge_r r2) (S (rank (merge_r r2)))\n        else T (merge_r r2) v2 l2 (S (rank l2))\n      else\n        if ((rank (merge r1 t2)) <=? (rank l1))\n        then T l1 v1 (merge r1 t2) (S (rank (merge r1 t2)))\n        else T (merge r1 t2) v1 l1 (S (rank l1))\n  end.\n\nDefinition singleton (v: nat) :=\n  T E v E 1.\n\nDefinition insert (v: nat) (t: heap) :=\n  merge (singleton v) t.\n\nDefinition heap_min (t: heap) :=\n  match t with\n  | E => default\n  | T _ v _ _ => v\n  end.\n\nDefinition deletemin (t: heap) :=\n  match t with\n  | E => E\n  | T l _ r _ =>\n      merge l r\n  end.\n\n(* --- PROPERTIES --- *)\nInductive HeapProp: heap -> Prop :=\n  | HP_E : HeapProp E\n  (*\n  | HP_T: forall l v r rk,\n      v <= heap_min l ->\n      v <= heap_min r ->\n      HeapProp (T l v r rk).\n      *)\n  | HP_T_EE : forall v rnk,\n      HeapProp (T E v E rnk)\n  | HP_T_TE : forall v rnk l1 v1 r1 rnk1,\n      HeapProp (T l1 v1 r1 rnk1) ->\n      v <= v1 ->\n      HeapProp (T (T l1 v1 r1 rnk1) v E rnk)\n  | HP_T_ET : forall v rnk l2 v2 r2 rnk2,\n      HeapProp (T l2 v2 r2 rnk2) ->\n      v <= v2 ->\n      HeapProp (T E v (T l2 v2 r2 rnk2) rnk)\n  | HP_T_TT : forall v rnk l1 v1 r1 rnk1 l2 v2 r2 rnk2,\n      HeapProp (T l1 v1 r1 rnk1) ->\n      HeapProp (T l2 v2 r2 rnk2) ->\n      v <= v1 ->\n      v <= v2 ->\n      HeapProp (T (T l1 v1 r1 rnk1) v (T l2 v2 r2 rnk2) rnk).\n\nInductive LeftistProp: heap -> Prop :=\n  | LP_E : LeftistProp E\n  | LP_T : forall l v r rnk,\n      LeftistProp l ->\n      LeftistProp r ->\n      (rank r) <= (rank l) ->\n      LeftistProp (T l v r rnk).\n\nInductive RankProp: heap -> Prop :=\n  | RP_E : RankProp E\n  | RP_T : forall l v r rnk,\n      RankProp r ->\n      (rank (T l v r rnk)) = (S (rank r)) ->\n      RankProp (T l v r rnk).\n\n(* --- TESTS --- *)\n(* HeapProp *)\nExample heap0:\n  HeapProp E.\nProof. repeat constructor; auto. Qed.\nExample heap1:\n  HeapProp (singleton 1).\nProof. repeat constructor; auto. Qed.\nExample heap2:\n  HeapProp (insert 2 (singleton 1)).\nProof. repeat constructor; auto. Qed.\nExample heap3:\n  HeapProp (merge (insert 2 (singleton 1)) (insert 2 (singleton 1))).\nProof. repeat constructor; auto. Qed.\nExample heap4:\n  HeapProp (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1)))).\nProof. repeat constructor; auto. Qed.\nExample heap5:\n  HeapProp (insert 7 (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1))))).\nProof. repeat constructor; auto. Qed.\nExample heap6:\n  HeapProp (insert 3 (insert 7 (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1)))))).\nProof. repeat constructor; auto. Qed.\nExample heap10:\n  HeapProp (singleton 4).\nProof. repeat constructor; auto. Qed.\nExample heap11:\n  HeapProp (insert 3 (singleton 4)).\nProof. repeat constructor; auto. Qed.\nExample heap12:\n  HeapProp (insert 0 (insert 3 (singleton 4))).\nProof. repeat constructor; auto. Qed.\nExample heap13:\n  HeapProp (insert 6 (insert 0 (insert 3 (singleton 4)))).\nProof. repeat constructor; auto. Qed.\nExample heap14:\n  HeapProp (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4))))).\nProof. repeat constructor; auto. Qed.\nExample heap15:\n  HeapProp (insert 8 (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4)))))).\nProof. repeat constructor; auto. Qed.\nExample heap16:\n  HeapProp (insert 3 (insert 8 (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4))))))).\nProof. repeat constructor; auto. Qed.\nExample heap17:\n  HeapProp (merge (insert 3 (insert 7 (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1)))))) (insert 3 (insert 8 (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4)))))))).\nProof. repeat constructor; auto. Qed.\n\n(* LeftistProp *)\nExample heap_0:\n  LeftistProp E.\nProof. repeat constructor; auto. Qed.\nExample heap_1:\n  LeftistProp (singleton 1).\nProof. repeat constructor; auto. Qed.\nExample heap_2:\n  LeftistProp (insert 2 (singleton 1)).\nProof. repeat constructor; auto. Qed.\nExample heap_3:\n  LeftistProp (merge (insert 2 (singleton 1)) (insert 2 (singleton 1))).\nProof. repeat constructor; auto. Qed.\nExample heap_4:\n  LeftistProp (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1)))).\nProof. repeat constructor; auto. Qed.\nExample heap_5:\n  LeftistProp (insert 7 (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1))))).\nProof. repeat constructor; auto. Qed.\nExample heap_6:\n  LeftistProp (insert 3 (insert 7 (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1)))))).\nProof. repeat constructor; auto. Qed.\nExample heap_10:\n  LeftistProp (singleton 4).\nProof. repeat constructor; auto. Qed.\nExample heap_11:\n  LeftistProp (insert 3 (singleton 4)).\nProof. repeat constructor; auto. Qed.\nExample heap_12:\n  LeftistProp (insert 0 (insert 3 (singleton 4))).\nProof. repeat constructor; auto. Qed.\nExample heap_13:\n  LeftistProp (insert 6 (insert 0 (insert 3 (singleton 4)))).\nProof. repeat constructor; auto. Qed.\nExample heap_14:\n  LeftistProp (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4))))).\nProof. repeat constructor; auto. Qed.\nExample heap_15:\n  LeftistProp (insert 8 (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4)))))).\nProof. repeat constructor; auto. Qed.\nExample heap_16:\n  LeftistProp (insert 3 (insert 8 (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4))))))).\nProof. repeat constructor; auto. Qed.\nExample heap_17:\n  LeftistProp (merge (insert 3 (insert 7 (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1)))))) (insert 3 (insert 8 (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4)))))))).\nProof. repeat constructor; auto. Qed.\n\n(* RankProp *)\nExample heap_0':\n  RankProp E.\nProof. repeat constructor; auto. Qed.\nExample heap_1':\n  RankProp (singleton 1).\nProof. repeat constructor; auto. Qed.\nExample heap_2':\n  RankProp (insert 2 (singleton 1)).\nProof. repeat constructor; auto. Qed.\nExample heap_3':\n  RankProp (merge (insert 2 (singleton 1)) (insert 2 (singleton 1))).\nProof. repeat constructor; auto. Qed.\nExample heap_4':\n  RankProp (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1)))).\nProof. repeat constructor; auto. Qed.\nExample heap_5':\n  RankProp (insert 7 (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1))))).\nProof. repeat constructor; auto. Qed.\nExample heap_6':\n  RankProp (insert 3 (insert 7 (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1)))))).\nProof. repeat constructor; auto. Qed.\nExample heap_10':\n  RankProp (singleton 4).\nProof. repeat constructor; auto. Qed.\nExample heap_11':\n  RankProp (insert 3 (singleton 4)).\nProof. repeat constructor; auto. Qed.\nExample heap_12':\n  RankProp (insert 0 (insert 3 (singleton 4))).\nProof. repeat constructor; auto. Qed.\nExample heap_13':\n  RankProp (insert 6 (insert 0 (insert 3 (singleton 4)))).\nProof. repeat constructor; auto. Qed.\nExample heap_14':\n  RankProp (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4))))).\nProof. repeat constructor; auto. Qed.\nExample heap_15':\n  RankProp (insert 8 (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4)))))).\nProof. repeat constructor; auto. Qed.\nExample heap_16':\n  RankProp (insert 3 (insert 8 (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4))))))).\nProof. repeat constructor; auto. Qed.\nExample heap_17':\n  RankProp (merge (insert 3 (insert 7 (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1)))))) (insert 3 (insert 8 (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4)))))))).\nProof. repeat constructor; auto. Qed.\n\n(* Size *)\nExample size_0:\n  size E = 0.\nProof. simpl. auto. Qed.\nExample size_1:\n  size (singleton 1) = 1.\nProof. simpl. auto. Qed.\nExample size_2:\n  size (insert 2 (singleton 1)) = 2.\nProof. simpl. auto. Qed.\nExample size_3:\n  size (merge (insert 2 (singleton 1)) (insert 2 (singleton 1))) = 4.\nProof. simpl. auto. Qed.\nExample size_4:\n  size (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1)))) = 5.\nProof. simpl. auto. Qed.\nExample size_5:\n  size (insert 7 (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1))))) = 6.\nProof. simpl. auto. Qed.\nExample size_6:\n  size (insert 3 (insert 7 (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1)))))) = 7.\nProof. simpl. auto. Qed.\nExample size_10:\n  size (singleton 4) = 1.\nProof. simpl. auto. Qed.\nExample size_11:\n  size (insert 3 (singleton 4)) = 2.\nProof. simpl. auto. Qed.\nExample size_12:\n  size (insert 0 (insert 3 (singleton 4))) = 3.\nProof. simpl. auto. Qed.\nExample size_13:\n  size (insert 6 (insert 0 (insert 3 (singleton 4)))) = 4.\nProof. simpl. auto. Qed.\nExample size_14:\n  size (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4))))) = 5.\nProof. simpl. auto. Qed.\nExample size_15:\n  size (insert 8 (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4)))))) = 6.\nProof. simpl. auto. Qed.\nExample size_16:\n  size (insert 3 (insert 8 (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4))))))) = 7.\nProof. simpl. auto. Qed.\nExample size_17:\n  size (merge (insert 3 (insert 7 (insert 0 (merge (insert 2 (singleton 1)) (insert 2 (singleton 1)))))) (insert 3 (insert 8 (insert 2 (insert 6 (insert 0 (insert 3 (singleton 4)))))))) = 14.\nProof. simpl. auto. Qed.\n\n(* Tactics *)\nLtac crush_heap :=\n  repeat match goal with\n    | |- HeapProp _ => repeat constructor; auto; omega\n    | |- LeftistProp _ => repeat constructor; auto; omega\n    | |- RankProp _ => repeat constructor; auto; omega\n    | |- context [merge _ _] => unfold merge\n    | |- context [if rank _ <=? rank _ then _ else _] => unfold rank\n    | |- context [if ?x then _ else _] => bdestruct x\n    | |- _ => assumption\n  end.\nLtac crush_heap2 :=\n  repeat match goal with\n    | |- HeapProp _ => repeat constructor; auto; omega\n    | |- LeftistProp _ => repeat constructor; auto; omega\n    | |- RankProp _ => repeat constructor; auto; omega\n    | |- context [merge _ _] => unfold merge\n    | |- context [if rank _ <=? rank _ then _ else _] => unfold rank\n    | |- context [if ?x then _ else _] => bdestruct x\n    | H: HeapProp (T _ _ _ _) |- _ => inv H\n    | H: LeftistProp (T _ _ _ _) |- _ => inv H\n    | H: RankProp (T _ _ _ _) |- _ => inv H\n    | |- _ => assumption\n  end.\n\n(* --- THEOREMS --- *)\nLemma le_impl_lt:\n  forall n m,\n    n < m -> n <= m.\nProof.\n  intros. omega.\nQed.\n\nLemma min_assoc:\n  forall n m p,\n    min n (min m p) = min (min n m) p.\nProof.\n  intros. apply Min.min_assoc.\nQed.\n\nLemma T_neq_E:\n  forall l v r rk, T l v r rk <> E.\nProof.\n  intros. intro H. inversion H.\nQed.\n\nLemma E_neq_T:\n  forall l v r rk, E <> T l v r rk.\nProof.\n  intros. intro H. inversion H.\nQed.\n\nLemma merge_neq_E:\n  forall l v r rk t, merge (T l v r rk) t <> E.\nProof.\n  intros. destruct t; simpl.\n  apply T_neq_E.\n\n  repeat match goal with\n    | |- (if ?x then _ else _) <> _ => bdestruct x\n    | |- T _ _ _ _  <> E => apply T_neq_E\n  end.\nQed.\n\nLemma E_neq_merge:\n  forall l v r rk t, E <> merge (T l v r rk) t.\nProof.\n  intros. destruct t; simpl.\n  apply E_neq_T.\n\n  repeat match goal with\n    | |- _ <> (if ?x then _ else _) => bdestruct x\n    | |- E <> T _ _ _ _ => apply E_neq_T\n  end.\nQed.\n\nLemma insert_not_E:\n  forall v t, insert v t <> E.\nProof.\n  intros.\n  unfold insert.\n  unfold singleton.\n  apply merge_neq_E.\nQed.\n\nLemma E_not_insert:\n  forall v t, E <> insert v t.\nProof.\n  intros.\n  unfold insert.\n  unfold singleton.\n  apply E_neq_merge.\nQed.\n\nTheorem merge_right_E:\n  forall t,\n    (merge t E) = t.\nProof.\n  intros. destruct t; simpl; auto.\nQed.\n\nTheorem merge_left_E:\n  forall t,\n    (merge E t) = t.\nProof.\n  intros. destruct t; simpl; auto.\nQed.\n\nLemma rank_zero:\n  rank E = 0.\nProof.\n  simpl. auto.\nQed.\n\nTheorem rank_sub1_right:\n  forall l v r rk,\n    RankProp (T l v r rk) ->\n    (rank (T l v r rk)) = (S (rank r)).\nProof.\n  intros.\n  inv H.\n  inv H5.\n  omega.\nQed.\n\nTheorem empty_Heap:\n  HeapProp E.\nProof.\n  constructor.\nQed.\n\nTheorem empty_Leftist:\n  LeftistProp E.\nProof.\n  constructor.\nQed.\n\nTheorem empty_Rank:\n  RankProp E.\nProof.\n  constructor.\nQed.\n\nTheorem heap_prop_min:\n  forall l v r rnk,\n    v = heap_min (T l v r rnk).\nProof.\n  intros. unfold heap_min. auto.\nQed.\n\nLemma ins_E:\n  forall v,\n    (T E v E 1) = insert v E.\nProof.\n  intros.\n  unfold insert.\n  simpl.\n  auto.\nQed.\n\nTheorem lt_Heap:\n  forall l v r rk w,\n    HeapProp (T l v r rk) ->\n    w <= v ->\n    HeapProp (T l w r rk).\nProof.\n  intros. inv H; crush_heap.\n  (*intros. crush_heap2.*)\nQed.\n\nLemma heap_impl_children:\n  forall l v r rk,\n    HeapProp (T l v r rk) ->\n    HeapProp l /\\ HeapProp r.\nProof.\n  intros. inv H.\n  - constructor.\n    + constructor.\n    + constructor.\n  - constructor.\n    + auto.\n    + constructor.\n  - constructor.\n    + constructor.\n    + auto.\n  - constructor.\n    + auto.\n    + auto.\nQed.\n\nLemma heap_impl_le:\n  forall l v r rk,\n    HeapProp (T l v r rk) ->\n    v <= heap_min l /\\ v <= heap_min r.\nProof.\n  intros. inv H; simpl.\n  - constructor.\n    + apply (le_impl_lt _ _ (le_default _)).\n    + apply (le_impl_lt _ _ (le_default _)).\n  - constructor.\n    + auto.\n    + apply (le_impl_lt _ _ (le_default _)).\n  - constructor.\n    + apply (le_impl_lt _ _ (le_default _)).\n    + auto.\n  - constructor.\n    + auto.\n    + auto.\nQed.\n\nLemma eq_impl_size_eq:\n  forall h1 h2,\n    h1 = h2 -> size h1 = size h2.\nProof.\n  intros. rewrite H. auto.\nQed.\n\nLemma size_T:\n  forall l v r rk,\n    size (T l v r rk) = S (size l) + (size r).\nProof.\n  intros. simpl. auto.\nQed.\n\nLemma lr_neq_impl_neq:\n  forall l1 v1 r1 rk1 l2 v2 r2 rk2,\n    l1 <> l2 \\/ r1 <> r2 ->\n    (T l1 v1 r1 rk1) <> (T l2 v2 r2 rk2).\nProof.\n  intros.\n  intro.\n  inversion H0.\n  inversion H.\n  - apply H1 in H2.\n    inversion H2.\n  - apply H1 in H4.\n    inversion H4.\nQed.\n\nLemma l_neq_impl_neq:\n  forall l1 v1 r1 rk1 l2 v2 r2 rk2,\n    l1 <> l2 ->\n    (T l1 v1 r1 rk1) <> (T l2 v2 r2 rk2).\nProof.\n  intros.\n  intro.\n  inversion H0.\n  apply H in H2.\n  inversion H2.\nQed.\n\nLemma r_neq_impl_neq:\n  forall l1 v1 r1 rk1 l2 v2 r2 rk2,\n    r1 <> r2 ->\n    (T l1 v1 r1 rk1) <> (T l2 v2 r2 rk2).\nProof.\n  intros.\n  intro.\n  inversion H0.\n  apply H in H4.\n  inversion H4.\nQed.\n\nLemma singleton_neq_ins_T':\n  forall v1 rnk1 v2 v3 rnk2,\n    T E v1 E rnk1 <> insert v2 (T E v3 E rnk2).\nProof.\n  intros.\n  unfold insert.\n  unfold singleton.\n  crush_heap.\n  - inv H0.\n  - apply lr_neq_impl_neq.\n    left.\n    apply E_neq_T.\n  - apply lr_neq_impl_neq.\n    right.\n    apply E_neq_T.\n  - apply lr_neq_impl_neq.\n    left.\n    apply E_neq_T.\nQed.\n\nTheorem size_neq_merge_neq:\n  forall h1 h2,\n    size h1 <> size h2 ->\n    h1 <> h2.\nProof.\n  intros h1. induction h1; intros h2; induction h2; simpl; intros.\n  - auto.\n  - apply E_neq_T.\n  - apply T_neq_E.\n  - intro.\n    inversion H0.\n    rewrite H2 in H.\n    rewrite H4 in H.\n    assert (S (size h2_1) + size h2_2 = S (size h2_1) + size h2_2).\n    { auto. }\n    apply H in H1.\n    inversion H1.\nQed.\n\nTheorem merge_E_implies_E:\n  forall h1 h2,\n    (merge h1 h2) = E ->\n    h1 = E /\\ h2 = E.\nProof.\n  intros h1. induction h1; intros h2; induction h2; intros; split; auto.\n  - apply merge_neq_E in H.\n    inversion H.\n  - apply merge_neq_E in H.\n    inversion H.\nQed.\n\nLemma size_singleton:\n  forall v,\n  size (singleton v) = 1.\nProof.\n  intros. simpl. auto.\nQed.\n\nLemma size_lrv:\n  forall l v r rk,\n    size (T l v r rk) = S ((size l) + (size r)).\nProof.\n  intros. simpl. auto.\nQed.\n\nTheorem merge_add_size:\n  forall h1 h2,\n    size (merge h1 h2) = (size h1) + (size h2).\nProof.\n  intros h1. induction h1.\n  - intros. induction h2; simpl; auto.\n  - intros. induction h2.\n    + simpl. auto.\n    + rewrite (size_lrv h2_1 n1 h2_2 n2).\nAdmitted.\n\nTheorem ins_add1_size:\n  forall h v,\n    size (insert v h) = S (size h).\nProof.\n  intros. unfold insert. apply merge_add_size.\nQed.\n\nTheorem delete_sub1_size:\n  forall h,\n    h <> E ->\n    size h = S (size (deletemin h)).\nProof.\n  intros h. induction h.\n  - intros.\n    contradiction H.\n    auto.\n  - intros.\n    unfold deletemin.\n    rewrite merge_add_size.\n    simpl.\n    auto.\nQed.\n\nFixpoint genHeap (n : nat) :=\n  match n with\n    | 0 => singleton 0\n    | S m => merge (singleton m) (genHeap m)\n  end.\n(* Compute (genHeap 10). *)\n\nTheorem heap_l:\n  forall l v r rk,\n    HeapProp (T l v r rk) ->\n    HeapProp l.\nProof.\n  intros. inv H; crush_heap.\n  (*intros. crush_heap2.*)\nQed.\n\nTheorem heap_r:\n  forall l v r rk,\n    HeapProp (T l v r rk) ->\n    HeapProp r.\nProof.\n  intros. inv H; crush_heap.\n  (*intros. crush_heap2.*)\nQed.\n\nTheorem min_ins_is_heap:\n  forall l v r rk,\n    HeapProp l ->\n    HeapProp r ->\n    v <= heap_min l ->\n    v <= heap_min r ->\n    HeapProp (T l v r rk).\nProof.\n  intros. inv H; inv H0; crush_heap.\nQed.\n\nLemma singleton_neq_ins_T:\n  forall v1 rnk1 v2 v3 rnk2,\n    T E v1 E rnk1 <> insert v2 (T E v3 E rnk2).\nProof.\n  intros.\n  assert (size (T E v1 E rnk1) <> size (insert v2 (T E v3 E rnk2))).\n  { rewrite ins_add1_size.\n    simpl.\n    intro.\n    inv H. }\n  apply (size_neq_merge_neq _ _ H).\nQed.\n\nTheorem merge_Heap:\n  forall t1 t2,\n    HeapProp t1 ->\n    HeapProp t2 ->\n    HeapProp (merge t1 t2).\nProof.\nAdmitted.\n\nTheorem merge_Heap': (* BAD *)\n  forall l1 v1 r1 rk1 l2 v2 r2 rk2,\n    HeapProp (T l1 v1 r1 rk1) ->\n    HeapProp (T l2 v2 r2 rk2) ->\n    HeapProp (merge (T l1 v1 r1 rk1) (T l2 v2 r2 rk2)).\nProof.\n  intros. inv H. inv H0.\n  * unfold merge.\n    bdestruct (v2 <? v1).\n    unfold rank.\n    (* bdestruct (0 <=? rank E). *)\n    - bdestruct (rk1 <=? 0).\n      + constructor.\n        -- constructor.\n        -- omega.\n      + constructor.\n        -- constructor.\n        -- omega.\n    - unfold rank.\n      bdestruct (rk2 <=? 0).\n      + constructor.\n        -- constructor.\n        -- omega.\n      + constructor.\n        -- constructor.\n        -- omega.\n  * unfold merge. \n    bdestruct (v2 <? v1).\n    - unfold rank.\n      bdestruct (rk1 <=? rnk1).\n      + constructor.\n        -- auto.\n        -- constructor.\n        -- omega.\n        -- omega.\n      + constructor.\n        -- constructor.\n        -- auto.\n        -- omega.\n        -- omega.\n    - unfold rank.\n      bdestruct (rk2 <=? 0).\n      + constructor.\n        -- constructor.\n           ++ auto.\n           ++ auto.\n        -- auto.\n      + repeat constructor; auto.\n  * \nAbort.\n\nTheorem merge_Heap'':\n  forall t1 t2,\n    HeapProp t1 ->\n    HeapProp t2 ->\n    HeapProp (merge t1 t2).\nProof.\n  intros t1 t2 H1 H2. revert H1. revert t1. induction H2; intros.\n  - induction t1; crush_heap.\n  - (*inv H1;\n    repeat match goal with\n      | |- HeapProp _ => repeat constructor; auto; omega\n      | |- context [if ?x then _ else _] => bdestruct x\n      (*| |- context [merge ?h1 ?h2] => induction h1; induction h2*)\n      | |- context [merge _ _] => unfold merge\n      | |- context [if rank _ <=? rank _ then _ else _] => unfold rank\n      | H: HeapProp (T _ _ _ _) |- _ => inv H \n      | |- _ => assumption\n    end.*)\nAbort.\n\nTheorem merge_Heap''':\n  forall t1 t2,\n    HeapProp t1 ->\n    HeapProp t2 ->\n    HeapProp (merge t1 t2).\nProof.\n  intros t1. induction t1; intros t2; induction t2; intros H1; induction H1; intros H2; induction H2.\n  - crush_heap.\n  - crush_heap.\n  - crush_heap.\nAbort.\n\nTheorem merge_Leftist:\n  forall t1 t2,\n    LeftistProp t1 ->\n    LeftistProp t2 ->\n    LeftistProp (merge t1 t2).\nProof.\n  intros. induction H; induction H0.\n  - simpl. constructor.\n  - simpl. constructor; auto.\n  - simpl. constructor; auto.\n  - admit.\nAdmitted.\n\nTheorem merge_Rank:\n  forall t1 t2,\n    RankProp t1 ->\n    RankProp t2 ->\n    RankProp (merge t1 t2).\nProof.\n  intros. induction H; induction H0.\n  - simpl. constructor.\n  - simpl. constructor; auto.\n  - simpl. constructor; auto.\n  - admit.\nAdmitted.\n\nCorollary insert_Heap:\n  forall h v,\n    HeapProp h ->\n    HeapProp (insert v h).\nProof.\n  intros.\n  unfold insert.\n  apply merge_Heap.\n  constructor.\n  auto.\nQed.\n\nCorollary insert_Leftist:\n  forall h v,\n    LeftistProp h ->\n    LeftistProp (insert v h).\nProof.\n  intros.\n  unfold insert.\n  apply merge_Leftist.\n  repeat constructor.\n  auto.\nQed.\n\nCorollary insert_Rank:\n  forall h v,\n    RankProp h ->\n    RankProp (insert v h).\nProof.\n  intros.\n  unfold insert.\n  apply merge_Rank.\n  repeat constructor.\n  auto.\nQed.\n\nFixpoint list_min ls :=\n  match ls with\n  | [] => default\n  | c :: [] => c\n  | c :: d => \n      if c <? list_min d\n      then c\n      else list_min d\n  end.\n\n(* --- list_min TESTS --- *)\nExample list_min0:\n  default = list_min [ ].\nProof.\n  simpl. auto.\nQed.\n\nExample list_min1:\n  1 = list_min [ 1 ].\nProof.\n  simpl. auto.\nQed.\n\nExample list_min10:\n  1 = list_min [ 5 ; 6 ; 2 ; 9 ; 3 ; 7 ; 1 ; 8 ; 10 ; 4 ].\nProof.\n  simpl. auto.\nQed.\n\nLemma list_min_null:\n  list_min [] = default.\nProof.\n  auto.\nQed.\n\nLemma min_app':\n  forall l1 l2, list_min (l1 ++ l2) = min (list_min l1) (list_min l2).\nProof.\n  intros l1; induction l1; intros l2; induction l2.\n  - simpl. rewrite min_default. auto.\n  - simpl in IHl2.\n    rewrite list_min_null.\nAbort.\n\nLemma min_cons:\n  forall v l, list_min (v :: l) = min v (list_min l).\nProof.\n  intros. induction l.\n  - unfold list_min.\n    rewrite min_default.\n    auto.\n  - \nAdmitted.\n\nLemma min_app:\n  forall l1 l2, list_min (l1 ++ l2) = min (list_min l1) (list_min l2).\nProof.\n  intros. induction l1.\n  - simpl.\n    rewrite Nat.min_comm.\n    rewrite min_default.\n    auto.\n  - rewrite min_cons.\n    rewrite <- app_comm_cons.\n    rewrite min_cons.\n    rewrite IHl1.\n    rewrite Min.min_assoc.\n    rewrite <- min_assoc.\n    auto.\nQed.\n\n(* --- Abstraction Relationships --- *)\nModule AbsRel0.\n  Inductive Abs: heap -> list nat -> Prop :=\n    | Abs_E: Abs E []\n    | Abs_T: forall h1 h2 l1 l2 rk v,\n        Abs h1 l1 ->\n        Abs h2 l2 ->\n        Abs (T h1 v h2 rk) (v :: (l1 ++ l2)).\n\n  Theorem empty_relate:\n    Abs E [].\n  Proof.\n    constructor.\n  Qed.\n\n  Theorem min_relate:\n    forall h l, Abs h l -> HeapProp h -> heap_min h = list_min l.\n  Proof.\n    intros h l H. induction H; intros.\n    - simpl. auto.\n    - assert (HeapProp h1).\n      { apply heap_impl_children in H1.\n        apply H1. }\n      assert (HeapProp h2).\n      { apply heap_impl_children in H1.\n        apply H1. }\n      apply IHAbs1 in H2.\n      apply IHAbs2 in H3.\n      rewrite min_cons.\n      assert (v <= heap_min h1).\n      { apply (heap_impl_le _ _ _ _ H1). }\n      assert (v <= heap_min h2).\n      { apply (heap_impl_le _ _ _ _ H1). }\n      assert (list_min (l1 ++ l2) = min (list_min l1) (list_min l2)).\n      { apply min_app. }\n      rewrite H6.\n      rewrite Nat.min_assoc.\n      rewrite H2 in H4.\n      rewrite H3 in H5.\n      rewrite min_l.\n      rewrite min_l; auto.\n      rewrite min_l; auto.\n  Qed.\n\n  Theorem size_relate:\n    forall h l,\n      Abs h l ->\n      size h = length l.\n  Proof.\n    intros. induction H.\n    - simpl. auto.\n    - simpl. \n      rewrite IHAbs1.\n      rewrite IHAbs2.\n      rewrite app_length.\n      auto.\n  Qed.\n\n  Lemma relate_singleton:\n    forall v,\n      Abs (singleton v) [v].\n  Proof.\n    intros.\n    unfold singleton. \n    Check Abs_T.\n    apply (Abs_T E E [] [] 1 v empty_relate empty_relate).\n  Qed.\n\n  Lemma abs_E_l:\n    forall l,\n      Abs E l ->\n      l = [].\n  Proof.\n    intros l. induction l; intros.\n    - auto.\n    - inversion H.\n  Qed.\n\n  Lemma abs_h_e:\n    forall h,\n      Abs h [] ->\n      h = E.\n  Proof.\n    intros h. induction h; intros.\n    - auto.\n    - inversion H.\n  Qed.\n\n  Theorem insert_relate:\n    forall h l v,\n      Abs h l ->\n      Abs (insert v h) (v :: l).\n  Proof.\n  Abort.\n\n  Theorem merge_relate:\n    forall h1 h2 l1 l2,\n      Abs h1 l1 ->\n      Abs h2 l2 ->\n      Abs (merge h1 h2) (l1 ++ l2).\n  Proof.\n  Abort.\nEnd AbsRel0.\n\nModule AbsRel1.\n  Inductive Abs: heap -> list nat -> Prop :=\n    | Abs_E: Abs E []\n    | Abs_T: forall h1 h2 l1 l2 rk v,\n        Abs h1 l1 ->\n        Abs h2 l2 ->\n        Abs (T h1 v h2 rk) (v :: (l1 ++ l2)).\n\n  Lemma empty_relate:\n    Abs E [].\n  Proof.\n    constructor.\n  Qed.\n\n  Theorem min_relate:\n    forall h l, Abs h l -> HeapProp h -> heap_min h = list_min l.\n  Proof.\n    intros h l H. induction H; intros.\n    - simpl. auto.\n    - assert (HeapProp h1).\n      { apply heap_impl_children in H1.\n        apply H1. }\n      assert (HeapProp h2).\n      { apply heap_impl_children in H1.\n        apply H1. }\n      apply IHAbs1 in H2.\n      apply IHAbs2 in H3.\n      rewrite min_cons.\n      assert (v <= heap_min h1).\n      { apply (heap_impl_le _ _ _ _ H1). }\n      assert (v <= heap_min h2).\n      { apply (heap_impl_le _ _ _ _ H1). }\n      assert (list_min (l1 ++ l2) = min (list_min l1) (list_min l2)).\n      { apply min_app. }\n      rewrite H6.\n      rewrite Nat.min_assoc.\n      rewrite H2 in H4.\n      rewrite H3 in H5.\n      rewrite min_l.\n      rewrite min_l; auto.\n      rewrite min_l; auto.\n  Qed.\n\n  Theorem size_relate:\n    forall h l,\n      Abs h l ->\n      size h = length l.\n  Proof.\n    intros. induction H.\n    - simpl. auto.\n    - simpl. \n      rewrite IHAbs1.\n      rewrite IHAbs2.\n      rewrite app_length.\n      auto.\n  Qed.\n\n  Lemma relate_singleton:\n    forall v,\n      Abs (singleton v) [v].\n  Proof.\n    intros.\n    unfold singleton. \n    Check Abs_T.\n    apply (Abs_T E E [] [] 1 v empty_relate empty_relate).\n  Qed.\n\n  Lemma abs_E_l:\n    forall l,\n      Abs E l ->\n      l = [].\n  Proof.\n    intros l. induction l; intros.\n    - auto.\n    - inversion H.\n  Qed.\n\n  Lemma abs_h_e:\n    forall h,\n      Abs h [] ->\n      h = E.\n  Proof.\n    intros h. induction h; intros.\n    - auto.\n    - inversion H.\n  Qed.\n\n  (*these two theorems might be impossible with current abs relation ...*)\n  Theorem insert_relate:\n    forall h l v,\n      Abs h l ->\n      Abs (insert v h) (v :: l).\n  Proof.\n  Abort.\n\n  Theorem merge_relate:\n    forall h1 h2 l1 l2,\n      Abs h1 l1 ->\n      Abs h2 l2 ->\n      Abs (merge h1 h2) (l1 ++ l2).\n  Proof.\n  Abort.\nEnd AbsRel1.\n\nModule AbsRel2.\n  Fixpoint heap_In (n : nat) (h : heap) :=\n    match h with\n    | E => False\n    | T l v r _ =>\n        if n =? v\n        then True\n        else (heap_In n l \\/ heap_In n r)\n    end.\n\n  Inductive Abs: heap -> list nat -> Prop :=\n    | Abs_E: Abs E []\n    | Abs_T: forall h1 h2 l rk v,\n        (forall (n : nat), ((heap_In n h1 \\/ heap_In n h2) <-> In n l)) ->\n        Abs (T h1 v h2 rk) (v :: l).\n\n  Lemma empty_relate:\n    Abs E [].\n  Proof.\n    constructor.\n  Qed.\n\n  Lemma singleton_relate:\n    forall v rk,\n      Abs (T E v E rk) [v].\n  Proof.\n    intros. constructor. intros.\n    split; simpl; intro; inv H; auto.\n  Qed.\n\n  Lemma abs_h_e:\n    forall h,\n      Abs h [] ->\n      h = E.\n  Proof.\n    intros h. induction h; intros; auto; inversion H.\n  Qed.\n  \n  Theorem min_relate:\n    forall h l, Abs h l -> HeapProp h -> heap_min h = list_min l.\n  Proof.\n    intros. inv H.\n    - simpl. auto.\n    - admit.\n  Admitted.\n\n  Theorem insert_relate:\n    forall h l v,\n      Abs h l ->\n      Abs (insert v h) (v :: l).\n  Proof.\n  Abort.\n\n(* Arguments ... : simpl never. *)\n\n  Lemma neq_impl_false:\n    forall n : nat,\n      n <> n -> False.\n  Proof.\n    intros. induction n; auto.\n  Qed.\n\n  Lemma in_lr_impl_in:\n    forall l v r rk,\n      heap_In v l \\/ heap_In v r ->\n      heap_In v (T l v r rk).\n  Proof.\n    intros.\n    inv H.\n    - simpl.\n      bdestruct (v =? v).\n      + auto.\n      + apply neq_impl_false in H.\n        inversion H.\n    - simpl.\n      bdestruct (v =? v).\n      + auto.\n      + apply neq_impl_false in H.\n        inversion H.\n  Qed.\n\n  Theorem merge_relate:\n    forall h1 h2 l1 l2,\n      Abs h1 l1 ->\n      Abs h2 l2 ->\n      Abs (merge h1 h2) (l1 ++ l2).\n  Proof.\n    intros h1 h2 l1 l2 H. induction H; intros.\n    - rewrite merge_left_E. simpl. auto.\n    - induction H0.\n      + simpl.\n        rewrite app_nil_r.\n        constructor; auto.\n      + \n  Abort.\nEnd AbsRel2.\n", "meta": {"author": "jtadley", "repo": "Coq", "sha": "a3311688118f1bc5e36503886b1517ecc30477a0", "save_path": "github-repos/coq/jtadley-Coq", "path": "github-repos/coq/jtadley-Coq/Coq-a3311688118f1bc5e36503886b1517ecc30477a0/Heap0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.6681411399382251}}
{"text": "Require Import List.\nImport ListNotations.\n\nInductive Tree (A : Type) : Type :=\n| Empty : Tree A\n| Node : A -> list (Tree A) -> Tree A.\n\nArguments Empty {A}.\nArguments Node {A} _ _.\n\nRequire Import Recdef.\n\nFixpoint fmap {A B : Type} (f : A -> B) (t : Tree A) : Tree B :=\nmatch t with\n| Empty => Empty\n| Node x ts => Node (f x) (map (fmap f) ts)\nend.\n\nFail Functional Scheme fmap_ind := Induction for fmap Sort Prop.\n\nInductive R {A B : Type} (f : A -> B) : Tree A -> Tree B -> Prop :=\n| R_Empty : R f Empty Empty\n| R_Node  :\n    forall (x : A) (ts : list (Tree A)) (ts' : list (Tree B)),\n      Rs f ts ts' -> R f (Node x ts) (Node (f x) ts')\n\nwith\n  Rs {A B : Type} (f : A -> B)\n    : list (Tree A) -> list (Tree B) -> Prop :=\n| Rs_nil  : Rs f [] []\n| Rs_cons :\n    forall\n      (ta : Tree A) (tb : Tree B)\n      (tsa : list (Tree A)) (tsb : list (Tree B)),\n        R f ta tb -> Rs f tsa tsb -> Rs f (ta :: tsa) (tb :: tsb).\n\nFixpoint mirror {A : Type} (t : Tree A) : Tree A :=\nmatch t with\n| Empty => Empty\n| Node x ts => Node x (rev (map mirror ts))\nend.\n\nModule v2.\n\nInductive R {A B : Type} (f : A -> B) : Tree A -> Tree B -> Prop :=\n| R_Empty : R f Empty Empty\n| R_Node  :\n    forall (x : A) (ts : list (Tree A)) (ts' : list (Tree B)),\n      Forall2 (R f) ts ts' -> R f (Node x ts) (Node (f x) ts').\n\nLemma correct :\n  forall {A B : Type} (f : A -> B) (ta : Tree A) (tb : Tree B),\n    R f ta tb -> fmap f ta = tb.\nProof.\n  fix IH 6.\n  destruct 1; cbn; [easy |].\n  induction H; cbn; [easy |].\n  do 2 f_equal.\n  - now apply IH.\n  - now congruence.\nDefined.\n\nLemma complete :\n  forall {A B : Type} (f : A -> B) (ta : Tree A) (tb : Tree B),\n    fmap f ta = tb -> R f ta tb.\nProof.\n  fix IH 4.\n  destruct ta as [| a tas]; cbn; intros tb <-.\n  - now constructor.\n  - constructor.\n    induction tas as [| ta tas' IH']; cbn.\n    + now constructor.\n    + constructor.\n      * now apply IH.\n      * easy.\nDefined.\n\nEnd v2.", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/code/Principles/NestedFunInd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.66814113937992}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.PArith.PArith.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.Lists.List.\nOpen Scope Z_scope.\n\n\n(** * MathClasses-style \"Decision\" class. *)\n\nClass Decision (P: Prop) := decide: {P} + {~P}.\nArguments decide P {_}.\n\n(** A common special case is that of decidable equality. *)\nClass EqDec A := eq_dec (a b : A) :> Decision (a = b).\n\nDefinition isTrue P `{Decision P} :=\n  if decide P then true else false.\n\nLemma isTrue_sound P `{Decision P}:\n  isTrue P = true -> P.\nProof.\n  unfold isTrue.\n  destruct (decide P).\n  tauto.\n  discriminate.\nQed.\n\nLemma isTrue_complete P `{Decision P}:\n  P -> isTrue P = true.\nProof.\n  intro HP.\n  unfold isTrue.\n  destruct (decide P); eauto.\nQed.\n\nLemma isTrue_correct P `{Decision P}:\n  isTrue P = true <-> P.\nProof.\n  split.\n  * apply isTrue_sound.\n  * apply isTrue_complete.\nQed.\n\nLtac decision :=\n  eapply isTrue_sound;\n  reflexivity.\n\nLtac obviously H P :=\n  assert (H: P) by decision.\n\nLtac ensure P :=\n  let H := fresh \"H\" in\n  obviously H P; clear H.\n\n\n(** * Instances *)\n\nInstance decide_Zeq: EqDec Z := Z_eq_dec.\nInstance decide_Zle (m n: Z): Decision (m <= n) := {decide := Z_le_dec m n}.\nInstance decide_Zlt (m n: Z): Decision (m < n) := {decide := Z_lt_dec m n}.\nInstance decide_Zge (m n: Z): Decision (m >= n) := {decide := Z_ge_dec m n}.\nInstance decide_Zgt (m n: Z): Decision (m > n) := {decide := Z_gt_dec m n}.\nInstance decide_nateq: EqDec nat := eq_nat_dec.\nInstance decide_natle m n: Decision (m <= n)%nat := { decide := le_dec m n }.\nInstance decide_natlt m n: Decision (m < n)%nat := { decide := lt_dec m n }.\nInstance decide_poseq: EqDec positive := Pos.eq_dec.\nInstance decide_booleq: EqDec bool := Bool.bool_dec.\nInstance decide_Neq: EqDec N := N.eq_dec.\n\nInstance decide_posle (m n: positive): Decision (Pos.le m n).\nProof.\n  destruct (Pos.leb m n) eqn:leb.\n  - left; apply Pos.leb_le, leb.\n  - right; rewrite <- Pos.leb_le, leb; discriminate.\nDefined.\n\nInstance and_dec A B: Decision A -> Decision B -> Decision (A /\\ B) := {\n  decide :=\n    match (decide A) with\n      | left HA =>\n          match (decide B) with\n            | left HB => left (conj HA HB)\n            | right HnB => right (fun H => HnB (proj2 H))\n          end\n      | right HnA => right (fun H => HnA (proj1 H))\n    end\n}.\n\nInstance or_dec A B: Decision A -> Decision B -> Decision (A \\/ B) := {\n  decide :=\n    match (decide A) with\n      | left HA => left (or_introl HA)\n      | right HnA =>\n        match (decide B) with\n          | left HB => left (or_intror HB)\n          | right HnB => right (fun HAB => match HAB with\n                                             | or_introl HA => HnA HA\n                                             | or_intror HB => HnB HB\n                                           end)\n        end\n    end\n}.\n\nInstance impl_dec P Q `(Pdec: Decision P) `(Qdec: Decision Q): Decision (P->Q) :=\n  {\n    decide :=\n      match Qdec with\n        | left HQ => left (fun _ => HQ)\n        | right HnQ =>\n          match Pdec with\n            | left HP => right _\n            | right HnP => left _\n          end\n      end\n  }.\nProof.\n  * abstract tauto.\n  * abstract tauto.\nDefined.\n\nInstance not_dec P `(Pdec: Decision P): Decision (~P) :=\n  {\n    decide :=\n      match Pdec with\n        | left _ => right _\n        | right _ => left _\n      end\n  }.\nProof.\n  * abstract tauto.\n  * abstract tauto.\nDefined.\n\nProgram Instance decide_none {A} (a: option A): Decision (a = None) := {\n  decide :=\n    match a with\n      | Some _ => right _\n      | None => left _\n    end\n}.\n\nInstance decide_option_eq A `{EqDec A}:\n  EqDec (option A) :=\n  fun x y =>\n    match x, y with\n      | Some x, Some y =>\n        match decide (x = y) with\n          | left H => left (f_equal _ H)\n          | right H => right _\n        end\n      | None, None =>\n        left eq_refl\n      | _, _ =>\n        right _\n    end.\nProof.\n  * abstract (injection; eauto).\n  * abstract discriminate.\n  * abstract discriminate.\nDefined.\n\nSection DECIDE_PROD.\n  Context A `{Adec: EqDec A}.\n  Context B `{Bdec: EqDec B}.\n\n  Global Instance decide_eq_pair: EqDec (A * B).\n  Proof.\n    intros [x1 x2] [y1 y2].\n    destruct (decide (x1 = y1)).\n    destruct (decide (x2 = y2)).\n    left; congruence.\n    right; intro H; inversion H; now auto.\n    right; intro H; inversion H; now auto.\n  Defined.\nEnd DECIDE_PROD.\n\n(** * Decision procedures for lists *)\n\nInstance decide_In: forall `{EqDec} a l, Decision (@In A a l) :=\n  @In_dec.\n\nInstance decide_Forall {A} (P: A -> Prop):\n  (forall a, Decision (P a)) ->\n  (forall l, Decision (Forall P l)).\nProof.\n  intros HP l.\n  induction l.\n  * left.\n    constructor.\n  * destruct (decide (Forall P l)) as [Hl | Hl].\n    destruct (decide (P a)) as [Ha | Ha].\n    + left.\n      constructor;\n      assumption.\n    + right.\n      inversion 1.\n      tauto.\n    + right.\n      inversion 1.\n      tauto.\nDefined.\n\nInstance decide_list_eq `{EqDec}: EqDec (list A) :=\n  list_eq_dec H.\n\n(** * Decision procedures from [compare] *)\n\n(** This takes care of many orders, which are defined as, say,\n  [le x y := compare x y <> Gt]. *)\n\nInstance comparison_eq_dec: EqDec comparison.\nProof.\n  intros x y.\n  red.\n  decide equality.\nDefined.\n\n(** Decision and equivalence *)\n\nLocal Instance decide_rewrite P Q (Heq: P <-> Q) `(Decision P): Decision Q :=\n  match decide P with\n    | left _ => left _\n    | right _ => right _\n  end.\nProof.\n  abstract tauto.\n  abstract tauto.\nDefined.\n\n(** Decision and discriminable cases *)\n\nTheorem decide_discr {A}\n        (Q1 Q2 P: A -> Prop)\n        (discr: forall i, {Q1 i} + {Q2 i})\n        (dec_1: Decision (forall i, Q1 i -> P i))\n        (dec_2: Decision (forall i, Q2 i -> P i)):\n  Decision (forall i, P i).\nProof.\n  unfold Decision in *.\n  firstorder.\nDefined.\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/CAL/liblayers/lib/Decision.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6681411361886775}}
{"text": "Require Export prosa.model.priority.classes.\n\n(** * Numeric Fixed Task Priorities *)\n\n(** We define the notion of arbitrary numeric fixed task priorities, i.e.,\n    tasks are prioritized in order of user-provided numeric priority values,\n    where numerically smaller values indicate lower priorities (as for instance\n    it is the case in Linux). *)\n\n(** First, we define a new task parameter [task_priority] that maps each task\n    to a numeric priority value. *)\nClass TaskPriority (Task : TaskType) := task_priority : Task -> nat.\n\n(** Based on this parameter, we define the corresponding FP policy. *)\nInstance NumericFP (Task : TaskType) `{TaskPriority Task} : FP_policy Task :=\n{\n  hep_task (tsk1 tsk2 : Task) := task_priority tsk1 >= task_priority tsk2\n}.\n\n(** In this section, we prove a few basic properties of numeric fixed priorities. *)\nSection Properties.\n\n  (**  Consider any kind of tasks with specified priorities... *)\n  Context {Task : TaskType}.\n  Context `{TaskPriority Task}.\n\n  (** ...and jobs stemming from these tasks. *)\n  Context {Job : JobType}.\n  Context `{JobTask Job Task}.\n\n  (** The resulting priority policy is reflexive. *)\n  Lemma NFP_is_reflexive : reflexive_priorities.\n  Proof. by move=> ?; rewrite /hep_job_at /JLFP_to_JLDP /hep_job /FP_to_JLFP /hep_task /NumericFP. Qed.\n\n  (** The resulting priority policy is transitive. *)\n  Lemma NFP_is_transitive : transitive_priorities.\n  Proof.\n    move=> t y x z.\n    rewrite /hep_job_at /JLFP_to_JLDP /hep_job /FP_to_JLFP /hep_task /NumericFP.\n    by move=> PRIO_yx PRIO_zy; apply leq_trans with (n := task_priority (job_task y)).\n  Qed.\n\n  (** The resulting priority policy is total. *)\n  Lemma NFP_is_total : total_priorities.\n  Proof. by move=> t j1 j2; apply leq_total. Qed.\n\nEnd Properties.\n\n(** We add the above lemmas into a \"Hint Database\" basic_facts, so Coq\n    will be able to apply them automatically. *)\nHint Resolve\n     NFP_is_reflexive\n     NFP_is_transitive\n     NFP_is_total\n  : basic_facts.\n\n", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/model/priority/numeric_fixed_priority.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830605, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.668141128330054}}
{"text": "(**\nCoq/SSReflect/MathComp による定理証明\n\n第4章 MathComp ライブラリの基本ファイル\n\n4.3 ssrnat.v --- SSReflect 向け nat 型のライブラリ\n\n======\n\n2018_12_02 @suharahiromichi\n *)\n\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(**\n# はじめに\n\n本節はテキストを参照しながら、MathComp のソースコードに沿って説明していきます。\nソースコードが手元にあるならば、それも参照してください。\nopamでインストールしている場合は、ssrbool.v のソースは、たとえば以下にあります。\n\n~/.opam/4.07.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrnat.v\n*)\n\n(**\n# successor and predecessor\n\nStandard Coq の S (successor) と pred (predecessor) の構文糖衣(Notation)である。\nnosimpl ではない。後述する .*2 (double) は nosimple です。\ncsm_3_6_3_simpl.v に誤記がありました。\n*)\n\nLocate \".+1\".           (* S n : nat_scope (default interpretation) *)\nPrint S.                (* Inductive nat : Set :=  O : nat | S : nat -> nat *)\n\nLocate \".-1\".    (* Nat.pred n : nat_scope (default interpretation) *)\nPrint Nat.pred.  (* Nat.pred = fun n : nat => match n with | 0 => n | u.+1 => u end *)\n\n(**\n重大な注意\n\nn.+1.-1 = n は、無条件に成立するが、\nn.-1.+1 = n は、n≧1 でなければならない。 0.-1.+1 = 0.+1 = 1 なので。\n*)\n\nCheck succnK : forall n : nat, n = n.+1.-1.\nCheck prednK : forall n : nat, 0 < n -> n.-1.+1 = n. (* 1 <= n *)\n\n(**\nnat_eqType、eqType のインスタンス\n*)\n\nCheck 1 : nat_eqType : eqType.\nCheck 1 : nat        : Type.\n\n(**\n# bin_nat, number\n\n(略)\n*)\n\n\n(**\n# basic arithmetic\n\n## 定義\n\nStandard Soq の Nat.add, Nat.sub. Nat.mul に nosimpl をつけたもの。\n*)\n\nLocate \"m + n\".    (* addn m n : nat_scope (default interpretation) *)\nPrint addn.        (* addn = nosimpl addn_rec *)\nPrint addn_rec.    (* Nat.add *)\nPrint plus.        (* Notation plus := Nat.add (Standard Coq での定義) *)\n\nLocate \"m - n\".    (* subn m n : nat_scope (default interpretation) *)\nPrint subn.        (* subn = nosimpl subn_rec *)\nPrint subn_rec.    (* subn_rec = Nat.sub *)\nPrint minus.       (* Notation minus := Nat.sub (Standard Coq での定義) *)\n\nLocate \"m * n\".    (* muln m n : nat_scope (default interpretation) *)\nPrint muln.        (* muln = nosimpl muln_rec *)\nPrint muln_rec.    (* muln_rec = Nat.mul *)\nPrint mult.        (* Notation mult := Nat.mul (Standard Coq での定義) *)\n\n(**\n## nosimpl とは\n *)\nPrint nosimpl.        (* Notation nosimpl t := (let 'tt := tt in t) *)\n\n(**\nmatch や let: を関数の定義の中で使うと、simplが機能しないことを利用する。\n（定義を展開unfoldすると、simplは機能することに注意）\n\nhttps://coq.inria.fr/refman/proof-engine/ssreflect-proof-language.html#locking-unlocking\nの後半 We found that 以降。\n*)\nDefinition add1 := (match tt with tt => Nat.add end).\nDefinition add2 := (let: tt := tt in Nat.add).\nDefinition add3 := (let tt := tt in Nat.add). (* これは simpl される。 *)\n\n(* どこの simpl で 左辺が2に簡約されるか。 *)\nGoal add1 1 1 = 2. Proof. simpl. rewrite /add1. simpl. reflexivity. Qed.\nGoal add2 1 1 = 2. Proof. simpl. rewrite /add2. simpl. reflexivity. Qed.\nGoal add3 1 1 = 2. Proof. simpl. reflexivity. Qed.\n\n(*\nsimpl (rewrite /=) は、簡約をするタクティクで simplification の略。\nhttps://coq.inria.fr/refman/proof-engine/tactics.html#coq:tacn.simpl\nIn detail, the tactic simpl 以降。\n\nsimpl タクティクは、β簡約またはι簡約をおこなうが、ι簡約できる場合のみδ簡約する\n（δ簡約によって展開することで、ι簡約できるようになった場合のみ、その関数をδ簡約する）\nという性質を使う。以下の例を参照のこと：\n*)\n\n(* 単なるι簡約：常にできる。 *)\nGoal (match 0 with 0 => 1 | _ => 1 end) = 1. Proof. simpl. reflexivity. Qed.\nGoal (match tt with tt => 1 end) = 1. Proof. simpl. reflexivity. Qed.\n\n(* δ簡約して、ι簡約：これはできる。 *)\nDefinition one1 (n : nat) := (match n with 0 => 1 | _ => 1 end).\nGoal one1 0 = 1. Proof. simpl. reflexivity. Qed. (* 1 = 1 *)\n\n(* ι簡約しないなら、δ簡約してくれない。 *)\nDefinition one2 (n : nat) := (match tt with tt => 1 end).\nGoal one2 0 = 1. Proof. simpl. Admitted.    (* one2 0 = 1 *)\n\n(**\n## Standard Coq の関数に変換する。\n\n次の補題が用意されている。 \nStandard Coq の add, sub, mul にも 「+」「-」「*」 が用意されているが、\nデフォルトではないので、%coq_nat と表示される。\n\n一旦 %coq_nat に変換すれば、Standard Coq の omega などが使用できる。\nただし、ltacで定義するのが現実的である。ssr_omega.v 参照のこと。\n*)\n\nCheck plusE  : Nat.add = addn.\nCheck minusE : Nat.sub = subn.\nCheck multE  : Nat.mul = muln.\n\nGoal 1 + 1 = 2. Proof. rewrite -plusE. simpl. reflexivity. Qed. (* (1 + 1)%coq_nat *)\nGoal 1 - 1 = 0. Proof. rewrite -minusE. simpl. reflexivity. Qed. (* (1 - 1)%coq_nat *)\nGoal 1 * 1 = 1. Proof. rewrite -multE. simpl. reflexivity. Qed. (* (1 * 1)%coq_nat *)\n\n(**\n# comparison 比較\n*)\n\n(**\n## MathComp の比較（不等式）\n\nleq m n := (m - n == 0) で定義されている。「<=」は leq の Notation である。\n\n「<」はleqで定義されている。ltn は「<」で定義されている。\n*)\n\nLocate \"m <= n\".    (* leq m n : nat_scope (default interpretation) *)\nCheck leq : nat -> nat -> bool.\nPrint leq.          (* leq = fun m n : nat => m - n == 0 *)\n\nLocate \"m < n\".  (* leq m.+1 n : nat_scope (default interpretation) *)\nCheck ltn : nat -> nat -> bool.\nPrint ltn.       (* [rel m n | m < n] *)\n\n(**\nMathComp の「<=」などの不等式はboolである。leq は、nosimpl でないので、done で証明できる。\n *)\n\n(**\n## Standard Coq の比較（不等式）\n*)\nCheck le : nat -> nat -> Prop.\nCheck lt : nat -> nat -> Prop.\n(*\nStandard Coq の不等式は Prop であり、 <= と < は、%coq_nat と表示される。\nStadnard Coq の不等式は done できない。\n *)\n\n(**\n## 相互変換のための補題：leP と ltP\n\nboolの不等式と、Propの不等式(%coq_nat)の相互変換は、leP と ltP を使う。\n一旦 %coq_nat に変換すれば、Standard Coq の omega などが使用できる。\n*)\nGoal forall n, n <= n.+1.\nProof.\n  move=> n.\n  apply/leP.\n  (* (n <= n.+1)%coq_nat *)\n  Fail done.                     (* done で終わらない。 *)\n  apply/leP.\n  (* n <= n.+1 *)  \n  done.\nQed.\n\nGoal forall n, n < n.+1.\nProof.\n  move=> n.\n  apply/ltP.\n  (* (n < n.+1)%coq_nat *)\n  done.\nQed.  \n\nLocate \"m <= n\". (* leq m n : nat_scope (default interpretation) *)\nLocate \"m < n\".  (* leq m.+1 n : nat_scope (default interpretation) *)\nLocate \"m >= n\". (* leq n m : nat_scope (default interpretation) *)\nLocate \"m > n\".  (* leq n.+1 m : nat_scope (default interpretation) *)\n\n(**\n<= 以外は、<= で定義されている。\nそのため、m.+1 <= n が m < n と表示される場合がある。\nCoqはできるだけNotationを使って表示しようとするためであり、結果として、\n以下のように、< が一番よく使われるので、おどろかないようにする。\n *)\nCheck 1 <= 2.                               (* 0 < 2 *)\nCheck 2 >= 1.                               (* 0 < 2 *)\nCheck 0 <= 1.                               (* 0 <= 1 *)\nCheck 1 >= 0.                               (* 0 <= 1  *)\n\n(**\n## 場合分けのための補題： leqP と ltnP （これは覚えるべき補題）\n\n(leP と ltP と紛らわしいが、別なもの）\n*)\n\nGoal forall m n, (if m <= n then n else m) = maxn n m.\nProof.\n  move=> m n.\n  rewrite /maxn.\n  case: leqP.\n  - done.                                   (* m <= n -> n = n *)\n  - done.                                   (* n < m -> m = m *)\nQed.    \n(* if then else は = より結合度が低いので、括弧がいる。 *)\n\nGoal forall m n, (if m <= n then m else n) = minn n m.\nProof.\n  move=> m n.\n  rewrite /minn.\n  case: ltnP.\n  - done.                                   (* n < m -> n = n *)\n  - done.                                   (* m <= n -> m = m *)\nQed.    \n\n(**\n## 補足説明\n *)\n(**\nm <= n で場合分けする。ちょっとめんどう。\n *)\nGoal forall m n, (if m <= n then n else m) = maxn n m.\nProof.\n  move=> m n.\n  rewrite /maxn.\n  case H : (m <= n).\n  (* n = (if n < m then m else n) *)\n  - rewrite leqNgt ltnS H.\n    done.\n  (* m = (if n < m then m else n) *)\n  - rewrite leqNgt ltnS H.\n    done.\nQed.\n\n(**\nifP で場合分けする。\n *)\nGoal forall m n, (if m <= n then n else m) = maxn n m.\nProof.\n  move=> m n.\n  rewrite /maxn.\n  case: ifP => H.\n  (* m <= n -> n = (if n < m then m else n) *)\n  - rewrite leqNgt ltnS H.\n    done.\n  (* (m <= n) = false -> m = (if n < m then m else n) *)\n  - rewrite leqNgt ltnS H.\n    done.\nQed.    \n\n(**\n# min, max\n*)\n\nPrint minn.       (* minn = fun m n : nat => if m < n then m else n *)\nPrint maxn.       (* maxn = fun m n : nat => if m < n then n else m *)\n\n(* 当然、可換である。 *)\nGoal forall m n, minn m n = minn n m.\nProof.\n  move=> m n.\n    by rewrite minnC.\nQed.\n\nGoal forall m n, n <= m -> minn n m = n.\nProof.\n  move=> m n.\n  rewrite /leq.\n  move/eqP.\n  rewrite minnE.\n  move=> ->.\n    by rewrite subn0.\nQed.\n\nGoal forall m n, n <= m -> maxn m n = m.\nProof.\n  move=> m n.\n  rewrite /leq.\n  move/eqP.\n  rewrite maxnE.\n  move=> ->.\n    by rewrite addn0.\nQed.\n\n(**\n# iter\n\n(略)\n*)\n\n\n(**\n# parity\n\nodd は 「odd(n.+1) -> ~~ odd(n)」 という再帰で定義されている。\nなので、odd か even (= not odd) の証明は、単純な数学的帰納法で証明できる。\n *)\n\nPrint odd.\n(* \nodd = \nfix odd (n : nat) : bool := match n with\n                            | 0 => false\n                            | n'.+1 => ~~ odd n'\n                            end\n *)\n\nLemma oddn2 n : odd n.+2 = odd n.\nProof. rewrite /=. by rewrite negbK. Qed.\n\nLemma oddn1 n : odd n.+1 = ~~ odd n.\nProof. done. Qed.\n  \nLemma odd_pred n : 1 <= n -> odd n.-1 = ~~ odd n.\nProof.\n  elim: n => [// | n IHn H].\n    by rewrite succnK oddn1 negbK.\nQed.\n\n\n(**\n# doubling, halving\n *)\n\nLocate \".*2\".      (* double n : nat_scope (default interpretation) *)\nPrint double.      (* double = nosimpl double_rec *)\n\nLocate \"./2\".        (* half n : nat_scope (default interpretation) *)\nPrint half.          (* half = \n                        fix half (n : nat) : nat := match n with\n                            | 0 => n\n                            | n'.+1 => uphalf n'\n                            end\n                            with uphalf (n : nat) : nat := match n with\n                               | 0 => n\n                               | n'.+1 => (half n').+1\n                               end *)\n\n\n(**\n# exponentiation, factorial\n *)\n\nLocate \"m ^ n\".    (* expn m n : nat_scope (default interpretation) *)\nPrint expn.        (* expn = nosimpl expn_rec *)\n\nLocate \"n `!\".  (* factorial n : nat_scope (default interpretation) *)\nPrint factorial.                    (* factorial = nosimpl fact_rec *)\n\n(**\n# ex_minn, ex_maxn\n\n(略)\n *)\n\n\n(**\n# これだけは憶えておきたい補題\n\n以下も参照してください；\nhttps://staff.aist.go.jp/reynald.affeldt/ssrcoq/ssrnat_doc.pdf\n*)\n\nSection Lemmas.\n  Variables m n p q : nat.\n  \n  Check add0n n : 0 + n = n.          (* left_id 0 addn *)\n  Check addn0 n : n + 0 = n.          (* right_id 0 addn *)\n  Check add1n n : 1 + n = n.+1.       (* .+2 から .+4 も使用可能である。 *)\n  Check addn1 n : n + 1 = n.+1.\n  Check addnn n : n + n = n.*2.\n  Check addSn m n : m.+1 + n = (m + n).+1.\n  Check addnS m n : m + n.+1 = (m + n).+1.\n  Check addSnnS m n : m.+1 + n = m + n.+1.\n  \n  Check addnC m n : m + n = n + m.             (* commutative addn *)\n  Check addnA m n p : m + (n + p) = m + n + p. (* associative addn *)\n  Check addnCA m n p : m + (n + p) = n + (m + p). (* left_commutative addn *)\n  Check addnAC m n p : m + n + p = m + p + n. (* right_commutative addn *)\n  Check addnACA m n p q : m + n + (p + q) = m + p + (n + q). (* interchange addn addn *)\n  Check addKn m n : m + n - m = n.             (* cancel (addn n) (subn^~ n) *)\n  Check addnK m n : n + m - m = n.             (* cancel (addn^~ n) (subn^~ n) *)\n  \n  Check subnn n : n - n = 0.                (* self_inverse *)\n  \n  Check mul0n n : 0 * n = 0.                (* left_zero 0 muln *)\n  Check muln0 n : n * 0 = 0.                (* right_zero 0 muln *)\n  Check mul1n n : 1 * n = n.                (* left_id 1 muln *)\n  Check muln1 n : n * 1 = n.                (* right_id 1 muln *)\n  Check mul2n n : 2 * n = n.*2.\n  Check muln2 n : n * 2 = n.*2.\n  Check mulnn n : n * n = n ^ 2.\n  Check mulSn m n : m.+1 * n = n + m * n.\n  Check mulSnr m n : m.+1 * n = m * n + n.\n  Check mulnS m n : m * n.+1 = m + m * n.\n  Check mulnSr m n : m * n.+1 = m * n + m.\n  \n  Check mulnC m n : m * n = n * m.             (* commutative muln *)\n  Check mulnA m n p : m * (n * p) = m * n * p. (* associative muln *)\n  Check mulnDl m n p : (m + n) * p = m * p + n * p. (* left_distributive muln addn *)\n  Check mulnDr m n p : m * (n + p) = m * n + m * p. (* right_distributive muln addn *)\n  Check mulnBl m n p : (m - n) * p = m * p - n * p. (* left_distributive muln subn *)\n  Check mulnBr m n p : m * (n - p) = m * n - m * p. (* right_distributive muln subn *)\n  Check mulnCA m n p : m * (n * p) = n * (m * p). (* left_commutative muln *)\n  Check mulnAC m n p : m * n * p = m * p * n. (* right_commutative muln *)\n  Check mulnACA m n p q : m * n * (p * q) = m * p * (n * q). (* interchange muln muln *)\nEnd Lemmas.\n\n(**\nつぎの Search は結果がない（left_id で定義されているため）。\nそれらについては、ここで憶えてしまうしかない。\n*)\nSearch _ (0 + _ = _).                       (* add0n は出てこない。 *)\n\n(**\n# 可換なとき、大きな式を扱うコツ\n\naddn の場合\n\n- ?addnA で左結合\n- -?addnA で右結合\n\nに変換できる。?は零回以上の繰り替えしで、すでにそうなっている場合にエラーにしないため。\n*)\n\n(**\n## 3項を逆順にする。\n\n1回の可換則では、隣どうししか入れ替えられないから、\n3項を逆順にするには3回必要\n*)\nGoal 0 + 1 + 2 = 3.\nProof.\n  rewrite ?addnA addnAC.                    (* 2番めを最後に *)\n  rewrite -?addnA addnCA.                   (* 2番めを最初に *)\n  rewrite ?addnA addnAC.                    (* 2番めを最後に *)\n  done.\nQed.\n\n(**\n同上\n *)\nGoal 0 + 1 + 2 = 3.\nProof.\n  rewrite -?addnA addnCA.                   (* 2番めを最初に *)\n  rewrite ?addnA addnAC.                    (* 2番めを最後に *)\n  rewrite -?addnA addnCA.                   (* 2番めを最初に *)\n  rewrite ?addnA.                           (* 左結合にする。 *)\n  done.\nQed.\n\n(**\n## 項を入れ替える\n\n任意の項を先頭または、最後にする方法。内容で項を指定する。\n\n左結合で最後、右結合で先頭、にすれば、その項を取り出せる。\n*)\nGoal 0 + 1 + 2 + (3 + 4 + 5 + 6 + 7) + 8 + 9 = 45.\nProof.\n  rewrite ?addnA.                           (* 左結合にする。 *)\n  rewrite [_ + 4]addnC ?addnA.              (* 4 を先頭にする。 *)\n  rewrite -?addnA.                          (* 右結合にする。 *)\n  rewrite [6 + _]addnC -?addnA.             (* 6 を最後にする。 *)\n  rewrite ?addnA.                           (* 左結合にする。 *)\n  done.\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_4_3_ssrnat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6681402660571506}}
{"text": "Set Warnings \"-extraction-opaque-accessed,-extraction,-notation-overridden\".\nFrom Equations Require Import Equations.\nFrom deriving Require Import deriving.\n\nFrom QuickChick Require Import QuickChick.\nImport GenLow GenHigh.\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nFrom mathcomp Require Import zify. (* coq-mathcomp-zify *)\n\nGlobal Set Bullet Behavior \"None\".\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSet Equations Transparent.\n\nInductive exp :=\n  | ENum (n: nat)\n  | EAdd (e1 e2 : exp)\n  | ESub (e1 e2 : exp)\n  | EMul (e1 e2 : exp)\n  .\n\nDefinition exp_indDef := [indDef for exp_rect].\nCanonical exp_indType := IndType exp exp_indDef.\nDefinition exp_eqMixin := [derive eqMixin for exp].\nCanonical exp_eqType := EqType exp exp_eqMixin.\n\nImplicit Type e : exp.\nDerive (Arbitrary, Show) for exp.\n\nEquations eval e : nat :=\n  eval (ENum n) := n;\n  eval (EAdd el er) := eval el + eval er;\n  eval (EMul el er) := eval el * eval er;\n  eval (ESub el er) := eval el - eval er.\n\n(* ====================== *)\n\nInductive instr :=\n  | IPush (n : nat)\n  | IAdd\n  | ISub\n  | IMul\n  .\n\nImplicit Type i : instr.\nDerive (Arbitrary, Show) for instr.\n\nDefinition prog := seq instr.\nImplicit Type p : prog.\n\nDefinition stack := seq nat.\nImplicit Type s : stack.\n\nEquations run p s : stack :=\n  run [::] s := s;\n  run (IPush n :: p) s := run p (n :: s);\n  run (IAdd :: p) (x :: y :: s) := run p (y+x :: s);\n  run (ISub :: p) (x :: y :: s) := run p (y-x :: s);\n  run (IMul :: p) (x :: y :: s) := run p (y*x :: s);\n  (* run (_ :: p) s := run p s. *)\n  run (_ :: p) s := [::].\n  (* error semantics: if a command does not have prereqs, die. *)\n\nEquations compile e : prog :=\n  compile (ENum n) := [:: IPush n];\n  compile (EAdd el er) := compile el ++ compile er ++ [:: IAdd];\n  compile (ESub el er) := compile el ++ compile er ++ [:: ISub];\n  compile (EMul el er) := compile el ++ compile er ++ [:: IMul].\n\nQuickChick (fun e => \n  run (compile e) [::] == [:: eval e]\n).\n\nRecord stype := mk_stype {\n  inp : nat; (* depth of the stack a prog consumes *)\n  out : nat; (* height of the stack a prog leaves on top of unconsumed *)\n}.\n\nNotation \"i ~~> o\" :=\n  (mk_stype i o)\n  (at level 50, no associativity).\n\nDefinition s_merge st1 st2 : stype :=\n  let: inp1 ~~> out1 := st1 in\n  let: inp2 ~~> out2 := st2 in\n    (inp1 + (inp2 - out1)) ~~> (out2 + (out1 - inp2)).\n\n\nEquations s_infer_i i : stype :=\n  s_infer_i (IPush _) := (0 ~~> 1);\n  s_infer_i IAdd := 2 ~~> 1;\n  s_infer_i ISub := 2 ~~> 1;\n  s_infer_i IMul := 2 ~~> 1.\n\n\nDefinition s_infer p : stype := \n  foldr (fun i st => s_merge (s_infer_i i) st) (0 ~~> 0) p.\n  (* s_infer [::] := 0 ~~> 0;  \n  s_infer (i :: p) := s_infer_i *)\n\nLemma s_mergeA : associative s_merge.\nProof.\n  move=> [i1 o1] [i2 o2] [i3 o3].\n  by congr mk_stype; lia.\nQed.\n\nLemma s_infer_cat p1 p2 : \n  s_infer (p1 ++ p2) = s_merge (s_infer p1) (s_infer p2).\nProof.\n  elim: p1 => /= [| i s IHp1].\n  - case: (s_infer p2) => i o. \n    by congr mk_stype; lia.\n  by rewrite IHp1 s_mergeA.\nQed.\n\nLemma compile_typecheck e :\n  s_infer (compile e) = 0 ~~> 1.\nProof.\n  elim: e=> // e1 IHe1 e2 IHe2 /=;\n  by rewrite !s_infer_cat IHe1 IHe2 //=.\nQed.\n\nLemma run_cat p1 p2 s :\n  inp (s_infer p1) <= seq.size s ->\n    run (p1 ++ p2) s = run p2 (run p1 s).\nProof.\n  elim: p1 s=> // i p1 IHp1 s.\n  case: i=> /=.\n  - case: (s_infer p1) IHp1 => /= i o IHp1 n I1. \n    rewrite IHp1 //=; lia.\n  all: case: (s_infer p1) IHp1 => /= i o IHp1.\n  all: case: s=> [| x [| y s]] //= I1.\n  all: by rewrite IHp1 //=; lia.\nQed.\n\nLemma compile_correct e :\n  run (compile e) [::] = [:: eval e].\nProof.\n  move: [::].\n  elim: e=> //= e1 IHe1 e2 IHe2 s;\n  by rewrite !run_cat ?IHe2 ?IHe1 ?compile_typecheck.\nQed.\n", "meta": {"author": "mxxun", "repo": "lalambda-2021-coq-freestyle", "sha": "84bf4ccb17e92d443985d9a3c30d9258d5b8deab", "save_path": "github-repos/coq/mxxun-lalambda-2021-coq-freestyle", "path": "github-repos/coq/mxxun-lalambda-2021-coq-freestyle/lalambda-2021-coq-freestyle-84bf4ccb17e92d443985d9a3c30d9258d5b8deab/f_second_lang_own.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.6681402464184385}}
{"text": "Set Implicit Arguments.\nFrom TLC Require Import LibTactics LibLogic LibProd LibEpsilon LibContainer\n     LibSet LibRelation LibPer LibMonoid.\nLocal Notation path := rtclosure.\nFrom iris_time.union_find.math Require Import LibNatExtra LibIter LibRewrite\n     LibFunOrd InverseNatNat Ackermann InverseAckermann MiscArith TLCBuffer\n     UnionFind01Data UnionFind11Rank UnionFind21Parent.\n\n(* Following Alstrup et al.'s paper, we now fix a parameter [r] and define\n   variants of the level [k], the index [i], and the potential functions [phi]\n   and [Phi] that depend on [r]. *)\n\n(* -------------------------------------------------------------------------- *)\n\nSection Alstrup.\n\n(* Fix the parameter [r], and assume [r] is at least 1. *)\n\nVariable r : nat.\n\nHypothesis r_geq_1:\n  1 <= r.\n\nSection Potential.\n\n(* In the following, we again assume that [F] is a ranked disjoint set forest\n   with domain [D] and ranks [K]. *)\n\nVariable V : Type.\nVariable D : set V.\nVariable F : binary V.\nVariable K : V -> nat.\nHypothesis is_rdsf_F:\n  is_rdsf D F K.\n\nNotation p := (p F).\n\n(* -------------------------------------------------------------------------- *)\n\n(* Alstrup et al. define the function [alphar] as follows (page 17).\n   Note that their definition of [A] is not the same as ours -- they\n   index [k] from 1 and up, whereas, following Tarjan, we index [k]\n   from 0 and up -- so our definition of [alphar] looks different. *)\n\nDefinition defalphar :=\n  fun k => A k r.\n\nDefinition prealphar n :=\n  alphaf defalphar (n + 1).\n\nDefinition alphar (n : nat) :=\n  prealphar n + 1.\n\n(* [alphar n] is positive. *)\n\nLemma alphar_positive:\n  forall n,\n  alphar n > 0.\nProof using.\n  clear r_geq_1.\n  intros. unfold alphar. lia.\nQed.\n\n(* [alphar] is monotonic. *)\n\nLemma alphar_monotonic:\n  monotonic le le alphar.\nProof using r_geq_1.\n  intros m n ?.\n  unfold alphar, prealphar, defalphar.\n  eapply plus_le_plus.\n  eapply alphaf_monotonic; eauto with monotonic.\n  eapply plus_le_plus.\n  assumption.\nQed.\n\n(* Like [alpha], [alphar] grows at most by one at a time. *)\n\nLemma alphar_grows_one_by_one:\n  forall n,\n  alphar (n + 1) <= alphar n + 1.\nProof using r_geq_1.\n  intro.\n  unfold alphar, prealphar, defalphar.\n  eapply plus_le_plus.\n  eauto using alpha_grows_one_by_one.\nQed.\n\n(* If [r] is 1, then [alphar n] is as follows. *)\n\nLemma alphar_one:\n  r = 1 ->\n  forall n,\n  alphar n = alpha (n + 1) + 1.\nProof using.\n  intros h n. unfold alphar, prealphar, defalphar. rewrite h. reflexivity.\nQed.\n\n(* [alphar r] is 1. (Exploited on page 18.) *)\n\nLemma alphar_r:\n  alphar r = 1.\nProof using r_geq_1.\n  intros. unfold alphar.\n  cut (prealphar r <= 0). { lia. }\n  unfold prealphar, defalphar.\n  eapply alphaf_spec_reciprocal; eauto with monotonic.\n  rewrite (@Abase_eq r). lia.\nQed.\n\n(* If [r] is less than [n], then [alphar n] is at least two (page 17). *)\n\nLemma alphar_geq_two:\n  forall n,\n  r < n ->\n  1 < alphar n.\nProof using r_geq_1.\n  intros.\n  change 1 with (0 + 1). eapply plus_lt_plus.\n  unfold prealphar, defalphar.\n  eapply alphaf_spec_direct_contrapositive; eauto with monotonic.\n  rewrite Abase_eq. lia.\nQed.\n\n(* [A (prealphar n) r] is greater than [n] (page 17). *)\n\nLemma A_prealphar_gt:\n  forall n,\n  n < A (prealphar n) r.\nProof using r_geq_1.\n  intros.\n  cut (n + 1 <= A (prealphar n) r). { lia. }\n  change (A (prealphar n) r) with ((fun k => A k r) (prealphar n)).\n  eapply f_alphaf; eauto with monotonic.\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\n(* The function [rankr x] is just the function obtained by adding [r] to the\n   rank of each node. *)\n\nDefinition rankr x :=\n  K x + r.\n\n(* [rankr x] is of course at least [r]. *)\n\nLemma r_leq_rankr:\n  forall x,\n  r <= rankr x.\nProof using.\n  clear r_geq_1.\n  intros. unfold rankr. lia.\nQed.\n\n(* Hence, [rankr x] is positive. *)\n\nLemma rankr_positive:\n  forall x,\n  rankr x > 0.\nProof using r_geq_1.\n  intros. unfold rankr. lia.\nQed.\n\nHint Resolve rankr_positive : monotonic.\n  (* used in conjunction with Akx_tends_to_infinity_along_k *)\n\n(* [rankr] increases along a path. *)\n\nLemma rankr_increases_along_a_path:\n  forall x y,\n  path F x y ->\n  rankr x <= rankr y.\nProof using is_rdsf_F.\n  intros. unfold rankr. eapply plus_le_plus.\n  eauto using rank_increases_along_a_path.\nQed.\n\n(* The function [alphar . rankr] grows along a path. *)\n\nLemma alphar_rankr_grows_along_a_path:\n  forall x y,\n  path F x y ->\n  alphar (rankr x) <= alphar (rankr y).\nProof using is_rdsf_F r_geq_1.\n  eauto using alphar_monotonic, rankr_increases_along_a_path.\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\nSection NonRoot.\n\n(* Let [x] be a non-root. *)\n\nVariable x : V.\nHypothesis x_non_root: ~ is_root F x.\n\n(* The rankr of [x] is less than the rank of its parent. *)\n\nLemma parent_has_greater_rankr:\n  rankr x < rankr (p x).\nProof using is_rdsf_F x_non_root.\n  clear r_geq_1.\n  unfold rankr.\n  forwards: parent_has_greater_rank; eauto.\n  lia.\nQed.\n\n(* The function [alphar . rankr] grows along edges. *)\n\nLemma alphar_rankr_grows_along_edges:\n  alphar (rankr x) <= alphar (rankr (p x)).\nProof using is_rdsf_F x_non_root r_geq_1.\n  eapply alphar_monotonic.\n  forwards: parent_has_greater_rankr.\n  lia.\nQed.\n\nLemma alphar_rankr_grows_along_edges_corollary:\n  alphar (rankr x) <> alphar (rankr (p x)) ->\n  alphar (rankr x) <  alphar (rankr (p x)).\nProof using is_rdsf_F x_non_root r_geq_1.\n  forwards: alphar_rankr_grows_along_edges. lia.\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\n(* The level of [x] is defined as one plus the largest [k] such that\n   [A k (rankr x)] is less than or equal to [rankr (p x)]. *)\n\nDefinition defk :=\n  fun k => A k (rankr x).\n\nDefinition prek :=\n  betaf defk (rankr (p x)).\n\nDefinition k :=\n  prek + 1.\n\n(* The following lemma proves that [k] is well-defined. *)\n\nLemma k_exists:\n  A 0 (rankr x) <= rankr (p x).\nProof using is_rdsf_F x_non_root.\n  rewrite Abase_eq.\n  eapply parent_has_greater_rankr.\nQed.\n\nLtac k th :=\n  eapply th with (f := defk);\n  try solve [ unfold defk; eauto using k_exists with monotonic ].\n\n(* The level of [x] seems to be a measure of the distance of the rank\n   of [x] and the rank of its parent. In the case where these ranks\n   are closest, [rankr (p x)] is [rankr x + 1], so [k] is 1. *)\n\nLemma k_is_one:\n  K (p x) = K x + 1 ->\n  k = 1.\nProof using r_geq_1.\n  introv h. unfold k, prek.\n  assert (f: rankr (p x) = rankr x + 1). { unfold rankr. lia. }\n  rewrite f.\n  unfold defk.\n  rewrite beta_x_succ_x; eauto using rankr_positive.\nQed.\n\n(* In the case where these ranks are furthest away, [rankr x] is [r] and\n   [rankr (p x)] is, well, whatever it is. We find that the level [k] is\n   less than [alphar (rankr (p x))]. (Page 18.) *)\n\nLemma k_lt_alphar:\n  k < alphar (rankr (p x)).\nProof using is_rdsf_F x_non_root r_geq_1.\n  intros.\n  (* Eliminate the pesky ... + 1 on either side. *)\n  eapply plus_lt_plus.\n  (* By definition of [k], it suffices to prove [rankr (p x) < A (prealphar (rankr (p x)) (rankr x)]. *)\n  unfold prek.\n  k betaf_spec_direct_contrapositive.\n  unfold defk.\n  (* The lemma [A_prealphar_gt] yields [rankr (p x) < A (prealphar (rankr (p x)))],\n     so the goal simplifies as follows. *)\n  eapply Nat.lt_le_trans; [ eapply A_prealphar_gt | ].\n  (* The result now follows from the fact that [A] is monotonic and [r] is less\n     than or equal to [rankr x]. *)\n  eapply Akx_monotonic_in_x. eapply r_leq_rankr.\nQed.\n\n(* Another connection between [rankr] at [x] and at [p x]. *)\n\nLemma rankr_p_x_lt:\n  rankr (p x) < A k (rankr x).\nProof using is_rdsf_F x_non_root r_geq_1.\n  (* This holds by definition of [k]. *)\n  k betaf_spec_reciprocal_contrapositive. (* tchac! *)\n  { unfold k, prek. lia. }\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\n(* The index of [x] is defined as the largest [i] such that [i] iterations of\n   [A prek] take us from [rankr x] to at most [rankr (p x)]. *)\n\nDefinition i :=\n  betaf (fun i => iter i (A prek) (rankr x)) (rankr (p x)).\n  (* If that sounds crazy: it is. *)\n\n(* The following lemmas justify that [i] is well-defined. *)\n\nLemma i_exists:\n  iter 0 (A prek) (rankr x) <= rankr (p x).\nProof using is_rdsf_F x_non_root.\n  clear r_geq_1.\n  simpl. generalize parent_has_greater_rankr. lia.\nQed.\n\nLtac i th :=\n  unfold i; eapply th;\n  eauto using iter_i_Akx_tends_to_infinity_along_i, iter_Ak_monotonic_in_i,\n    i_exists.\n\n(* [i] is at least 1. *)\n\nLemma i_ge_1:\n  1 <= i.\nProof using is_rdsf_F x_non_root r_geq_1.\n  (* By definition of [i], we must show that applying [A prek] once\n     to [rankr x] takes us below or at [rankr (p x)]. *)\n  i betaf_spec_reciprocal. simpl.\n  (* And this is true by definition of [k]. *)\n  k betaf_spec_direct. (* wow *)\nQed.\n\n(* [i] is at most [rankr x]. *)\n\nLemma i_le_rank:\n  i <= rankr x.\nProof using is_rdsf_F x_non_root r_geq_1.\n  (* By definition of [i], we must show that applying [1 + rankr x] times\n     the function [A prek] to [rankr x] takes us above [rankr (p x)]. *)\n  i betaf_spec_direct_contrapositive_le.\n  (* Since [rankr (p x)] is less than [A k (rankr x)], the goal simplifies\n     as follows. *)\n  eapply Nat.lt_le_trans. eapply rankr_p_x_lt.\n  (* Now, by definition of [A], this is in fact an equality. *)\n  unfold k. rewrite Nat.add_comm. rewrite Astep_eq. reflexivity.\nQed.\n\nEnd NonRoot.\n\n(* -------------------------------------------------------------------------- *)\n\n(* The potential of a vertex. *)\n\nDefinition phi x :=\n  If is_root F x then\n     alphar (rankr x) * (rankr x + 1)\n  else If alphar (rankr x) = alphar (rankr (p x)) then\n    (alphar (rankr x) - k x) * (rankr x) - i x + 1\n  else\n    0.\n\n(* The total potential. *)\n\nDefinition Phi :=\n  fold (monoid_make plus 0) phi D.\n\n(* The following lemmas repeat the cases of the definition of [phi]. *)\n\nLemma phi_case_1:\n  forall x,\n  is_root F x ->\n  phi x = alphar (rankr x) * (rankr x + 1).\nProof using.\n  clear r_geq_1 is_rdsf_F.\n  intros. unfold phi. cases_if. eauto.\nQed.\n\nLemma phi_case_2:\n  forall x,\n  ~ is_root F x ->\n  alphar (rankr x) = alphar (rankr (p x)) ->\n  phi x = (alphar (rankr x) - k x) * (rankr x) - i x + 1.\nProof using.\n  clear r_geq_1 is_rdsf_F.\n  intros. unfold phi. repeat cases_if. reflexivity.\nQed.\n\nLemma phi_case_3:\n  forall x,\n  ~ is_root F x ->\n  alphar (rankr x) <> alphar (rankr (p x)) ->\n  phi x = 0.\nProof using.\n  clear r_geq_1 is_rdsf_F.\n  intros. unfold phi. repeat cases_if. reflexivity.\nQed.\n\n(* This lemma unifies the last two cases above. *)\n\nLemma phi_case_2_or_3:\n  forall x,\n  ~ is_root F x ->\n  phi x <= (alphar (rankr x) - k x) * (rankr x) - i x + 1.\nProof using.\n  clear r_geq_1.\n  intros.\n  tests : (alphar (rankr x) = alphar (rankr (p x))).\n  { rewrite phi_case_2 by assumption. reflexivity. }\n  { rewrite phi_case_3 by assumption. lia. }\nQed.\n\n(* In case 2 above, the subtractions are safe: they cannot produce a\n   negative number. The first subtraction always produces at least 1,\n   while the second subtraction always produces at least 0. *)\n\nLemma phi_case_2_safe_k:\n  forall x,\n  ~ is_root F x ->\n  alphar (rankr x) = alphar (rankr (p x)) ->\n  k x < alphar (rankr x).\nProof using is_rdsf_F r_geq_1.\n  introv ? hrank.\n  forwards hk: k_lt_alphar; eauto.\n  lia.\n  (* We note that the equality hypothesis on the ranks is required.\n     Indeed, in case 3, we could have [k x = alphar (rankr x)]. *)\nQed.\n\nLemma phi_case_2_safe_i:\n  forall x,\n  ~ is_root F x ->\n  alphar (rankr x) = alphar (rankr (p x)) ->\n  i x <= (alphar (rankr x) - k x) * (rankr x).\nProof using is_rdsf_F r_geq_1.\n  introv ? hrank.\n  rewrite i_le_rank by eauto.\n  eapply mult_magnifies_left.\n  forwards: phi_case_2_safe_k; eauto.\n  lia.\nQed.\n\n(* In case 1 above, [phi x] is at least 1. (Page 18.) *)\n\n(* This property seems unused, so we do not name it. *)\n\nGoal\n  forall x,\n  is_root F x ->\n  1 <= phi x.\nProof using.\n  clear r_geq_1.\n  intros. rewrite phi_case_1 by assumption.\n  eapply mult_positive.\n  (* [alphar] is positive. *)\n  { eapply alphar_positive. }\n  (* [rankr x + 1] is not zero. *)\n  { lia. }\nQed.\n\n(* In case 2 above, [phi x] is at least 1. (Page 18.) *)\n\nLemma phi_case_2_lower_bound:\n  forall x,\n  ~ is_root F x ->\n  alphar (rankr x) = alphar (rankr (p x)) ->\n  1 <= phi x.\nProof using is_rdsf_F r_geq_1.\n  introv h1 h2. rewrite phi_case_2 by assumption.\n  forwards: phi_case_2_safe_i; eauto.\n  lia.\nQed.\n\n(* Alstrup et al. write, on page, 18, \"if x is a nonroot leaf, then rankr (x) = r\".\n   This appears to be false: in the presence of path compression, a nonroot leaf\n   can have nonzero rank. (Imagine it used to be a root with nonzero rank and (as\n   per the numerous family condition) many descendants; but these descendants were\n   removed by path compression.) Thus, I am unable to conclude that phi x = 0.\n   This does not seem to be a problem: this remark in not exploited anywhere. *)\n\n(* An upper bound on [phi x]. In any case, [phi x] is at most the formula that\n   appears in case 1. *)\n\nLemma phi_upper_bound:\n  forall x,\n  phi x <= alphar (rankr x) * (rankr x + 1).\nProof using.\n  clear r_geq_1 is_rdsf_F.\n  intros. unfold phi. repeat cases_if.\n  (* Case 1. *)\n  { eauto. }\n  (* Case 2. *)\n  { lia_rewrite (alphar (rankr x) - k x <= alphar (rankr x)).\n    assert (0 < alphar (rankr x)). { eapply alphar_positive. }\n    generalize dependent (alphar (rankr x)). intros a ? ?.\n    rewrite Nat.mul_add_distr_l.\n    generalize (a * rankr x). intro ar.\n    lia. }\n  (* Case 3. *)\n  { assert (forall x, 0 <= x). { intros. lia. }\n    eauto. }\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\n(* Check the definitions shown in the paper. *)\n\nGoal\n  forall n,\n  alphar n = LibMin.mmin le (fun k => A k r >= n + 1) + 1.\nProof.\n  reflexivity.\nQed.\n\nGoal\n  forall x,\n  rankr x = K x + r.\nProof.\n  reflexivity.\nQed.\n\nGoal\n  forall x,\n  k x = mmax le (fun k => rankr (p x) >= A k (rankr x)) + 1.\nProof.\n  reflexivity.\nQed.\n\nGoal\n  forall x,\n  i x = mmax le (fun i => rankr (p x) >= iter i (A (k x - 1)) (rankr x)).\nProof.\n  intros.\n  replace (k x - 1) with (prek x) by (unfold k; lia).\n  reflexivity.\nQed.\n\nGoal\n  forall x,\n  phi x =\n    If is_root F x then\n       alphar (rankr x) * (rankr x + 1)\n    else If alphar (rankr x) = alphar (rankr (p x)) then\n      (alphar (rankr x) - k x) * (rankr x) - i x + 1\n    else\n      0.\nProof.\n  reflexivity.\nQed.\n\nGoal\n  Phi = fold (monoid_make plus 0) phi D.\nProof.\n  reflexivity.\nQed.\n\nEnd Potential.\n\n(* -------------------------------------------------------------------------- *)\n\n(* When [D] is empty, [Phi] is zero. *)\n\nLemma Phi_empty:\n  forall V F K,\n  Phi (\\{} : set V) F K = 0.\nProof using.\n  intros. unfold Phi. rewrite fold_empty. reflexivity.\nQed.\n\n(* If [x] is a root and has zero rank, then [phi x] is [r + 1]. *)\n\nLemma phi_root_zero_rank:\n  forall V D F K x,\n  @is_rdsf V D F K ->\n  is_root F x ->\n  K x = 0 ->\n  phi F K x = r + 1.\nProof using r_geq_1.\n  intros.\n  rewrite phi_case_1 by assumption.\n  assert (f: rankr K x = r). { unfold rankr. lia. }\n  rewrite f.\n  rewrite alphar_r by assumption.\n  lia.\nQed.\n\n(* Extending [D] with a new vertex augments [Phi] by [r + 1]. This relies on\n   our invariant, which guarantees that [K] is zero outside [D]. *)\n\nLemma Phi_extend:\n  forall V D F K x,\n  @is_rdsf V D F K ->\n  x \\notin D ->\n  Phi D F K + (r + 1) = Phi (D \\u \\{x}) F K.\nProof using r_geq_1.\n  intros.\n  unfold Phi.\n  rewrite fold_union; eauto with finite typeclass_instances. 2: rew_set in *.\n  rewrite fold_single; eauto with typeclass_instances.\n  simpl.\n  erewrite phi_root_zero_rank by eauto using only_roots_outside_D with is_dsf zero_rank. (* ha! *)\n  reflexivity.\nQed.\n\n\nEnd Alstrup.\n\n(* -------------------------------------------------------------------------- *)\n\n(* Hints. *)\n\nHint Resolve alphar_monotonic : monotonic.\n\nHint Resolve rankr_positive : monotonic.\n  (* used in conjunction with Akx_tends_to_infinity_along_k *)\n\nHint Resolve k_exists : k.\n\nHint Resolve i_exists iter_i_Akx_tends_to_infinity_along_i\niter_Ak_monotonic_in_i : i.\n\nLtac k th :=\n  match goal with |- context[prek ?r ?F ?K ?x] =>\n    eapply th with (f := defk r K x);\n    unfold defk; eauto with k monotonic\n  end.\n\nLtac i th :=\n  match goal with |- context[i ?r ?F ?K ?x] =>\n    eapply th with (f := fun i =>\n      iter i\n        (A (prek r F K x))\n        (rankr r K x)\n    ); eauto with i\n  end.\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/UnionFind41Potential.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6681402376161213}}
{"text": "Require Export Iron.Language.SystemF2Effect.Type.\nRequire Export Iron.Language.SystemF2Effect.Value.\nRequire Export Iron.Language.SystemF2Effect.Store.Bind.\n\n(********************************************************************)\n(* Small Step Evaluation (pure rules)\n   These are pure transitions that don't depend on the store. *)\nInductive StepP : exp  -> exp -> Prop :=\n\n (* Value application. *)\n | SpAppSubst\n   :  forall t11 x12 v2\n   ,  StepP (XApp (VLam t11 x12) v2)\n            (substVX 0 v2 x12)\n\n (* Type application. *)\n | SpAPPSubst\n   :  forall k11 x12 t2\n   ,  StepP (XAPP (VLAM k11 x12) t2)\n            (substTX 0 t2 x12)\n\n (* Take the successor of a natural. *)\n | SpSucc\n   :  forall n\n   ,  StepP (XOp1 OSucc (VConst (CNat n)))\n            (XVal (VConst (CNat (S n))))\n\n (* Test a natural for zero. *)\n | SpIsZero\n   :  forall n\n   ,  StepP (XOp1 OIsZero (VConst (CNat n)))\n            (XVal (VConst (CBool (beq_nat n 0)))).\n\nHint Constructors StepP.\n\n\n(********************************************************************)\n(* Preservation for pure single step rules. *)\nLemma stepp_preservation\n :  forall se sp x x' t e\n ,  StepP  x x'\n -> Forall ClosedT se\n -> TypeX  nil nil se sp x  t e\n -> TypeX  nil nil se sp x' t e.\nProof.\n intros se sp x x' t e HS HC HT. gen t e.\n induction HS; intros; inverts_type; rip.\n\n Case \"SpAppSubst\".\n  eapply subst_val_exp; eauto.\n\n Case \"SpAPPSubst\".\n  rrwrite (TBot KEffect = substTT 0 t2 (TBot KEffect)).\n  have HTE: (nil = substTE 0 t2 nil).\n  have HSE: (se  = substTE 0 t2 se) by (symmetry; auto).\n  rewrite HTE. rewrite HSE.\n  eapply subst_type_exp; eauto.\n   rrwrite (liftTE 0 se = se).\n   snorm.\n\n Case \"SpSucc\".\n  snorm. inverts H5. auto.\n\n Case \"SpIsZero\".\n  snorm. inverts H5. auto.\nQed.\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/Step/Pure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.66804426210941}}
{"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(****************************************************************************)\n(*                                                                          *)\n(*                                                                          *)\n(*                Solange Coupet-Grimal & Line Jakubiec-Jamet               *)\n(*                                                                          *)\n(*                                                                          *)\n(*             Laboratoire d'Informatique Fondamentale de Marseille         *)\n(*                   CMI et Faculté des Sciences de Luminy                  *)\n(*                                                                          *)\n(*           e-mail:{Solange.Coupet,Line.Jakubiec}@lif.univ-mrs.fr          *)\n(*                                                                          *)\n(*                                                                          *)\n(*                            Developped in Coq v6                          *)\n(*                            Ported to Coq v7                              *)\n(*                            Translated to Coq v8                          *)\n(*                                                                          *)\n(*                             July 12nd 2005                               *)\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 Immediate 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.\nintros.\nelim H; auto with arith.\nQed.\nHint Immediate le_mult_cst.\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 Immediate le_mult_csts.\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 Immediate lt_mult_n_Sn.\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 Immediate lt_mult_cst.\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 Immediate lt_mult_csts.\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 Immediate pred_mult.\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\nLemma le_mult_l : forall n m : nat, 0 < m -> n <= m * n.\nintros.\nrewrite (S_pred m 0); trivial.\nsimpl in |- *; auto with arith.\nQed.\nHint Immediate le_mult_l.\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 Immediate le_mult_r.\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 Immediate lt_mult.\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\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\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\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 Immediate mult_plus_distr_left.\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 Immediate mult_minus_distr_left.\n\n\nLemma mult_eq_zero : forall a b : nat, a * b = 0 -> a = 0 \\/ b = 0.\nintros a b; elim a.\nauto.\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 Immediate mult_eq_zero.\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 Immediate lt_mult_S_S.\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\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.\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.\nQed.\nHint Immediate mult_reg_l.\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\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\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 Immediate lt_nm_mult.\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.\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 Immediate same_quotient_order.", "meta": {"author": "coq-contribs", "repo": "fairisle", "sha": "e36087a6b7e52ef3c6dcfdeba1298e8fde1260a0", "save_path": "github-repos/coq/coq-contribs-fairisle", "path": "github-repos/coq/coq-contribs-fairisle/fairisle-e36087a6b7e52ef3c6dcfdeba1298e8fde1260a0/Libraries/Lib_Arithmetic/Lib_Mult.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118068790619, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.6680387119277484}}
{"text": "\n(* week-01_functional-programming-in-Coq.v *)\n(* FPP 2020 - YSC3236 2020-2011, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 15 Aug 2020 *)\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\nRequire Import Arith Bool.\n\nNotation \"A =n= B\" :=\n  (beq_nat A B) (at level 70, right associativity).\n\n(* ********** *)\n\nDefinition test_add (candidate: nat -> nat -> nat) : bool :=\n  (candidate 0 0 =n= 0)\n  &&\n  (candidate 0 1 =n= 1)\n  &&\n  (candidate 1 0 =n= 1)\n  &&\n  (candidate 1 1 =n= 2)\n  &&\n  (candidate 1 2 =n= 3)\n  &&\n  (candidate 2 1 =n= 3)\n  &&\n  (candidate 2 2 =n= 4)\n  &&\n  (candidate 2765 1313 =n= 4078)\n  &&\n  (candidate 2500 2500 =n= 5000)\n  &&\n  (candidate 0 5000 =n= 5000)\n  &&\n  (candidate 5000 0 =n= 5000)\n  &&\n  (candidate 1 4999 =n= 5000)\n  &&\n  (candidate 4999 1 =n= 5000)\n  .\n\nFixpoint add_v1 (i j : nat) : nat :=\n  match i with\n    | O => j\n    | S i' => S (add_v1 i' j)\n  end.\n\nCompute (test_add add_v1).\n\nFixpoint add_v2 (i j : nat) : nat :=\n  match i with\n    | O => j\n    | S i' => add_v2 i' (S j)\n  end.\n\nCompute (test_add add_v2).\n\nDefinition add_v3 (i j : nat) : nat :=\n  let fix visit n :=\n    match n with\n      | O => j\n      | S n' => S (visit n')\n    end\n  in visit i.\n\nCompute (test_add add_v3).\n\nDefinition add_v4 (i j : nat) : nat :=\n  let fix visit n a :=\n    match n with\n      | O => a\n      | S n' => visit n' (S a)\n    end\n  in visit i j.\n\nCompute (test_add add_v4).\n\n(* ***** *)\n\n(* Exercise 1 *)\n\nDefinition test_mul (candidate: nat -> nat -> nat) : bool :=\n  (candidate 0 0 =n= 0)\n  &&\n  (candidate 0 1 =n= 0)\n  &&\n  (candidate 1 0 =n= 0)\n  &&\n  (candidate 1 1 =n= 1)\n  &&\n  (candidate 1 2 =n= 2)\n  &&\n  (candidate 2 1 =n= 2)\n  &&\n  (candidate 2 2 =n= 4)\n  .\n\nFixpoint mul_v1 (i j : nat) : nat :=\n  match i with\n    | O => O\n    | S i' => add_v4 j (mul_v1 i' j)\n  end.\n\nCompute (test_mul mul_v1).\n\nDefinition mul_v2 (i j : nat) : nat :=\n  let fix visit n :=\n    match n with\n      | O => O\n      | S n' => add_v4 j (visit n')\n    end\n  in visit i.\n\nCompute (test_mul mul_v2).\n\nDefinition mul_v3 (i j : nat) : nat :=\n  let fix visit n a :=\n    match n with\n      | O => a\n      | S n' => visit n' (add_v4 j a)\n    end\n  in visit i O.\n\nCompute (test_mul mul_v3).\n\n\n(* ***** *)\n\n\nDefinition test_power (candidate: nat -> nat -> nat) : bool :=\n  (candidate 0 0 =n= 1)\n  &&\n  (candidate 0 1 =n= 0)\n  &&\n  (candidate 1 0 =n= 1)\n  &&\n  (candidate 1 1 =n= 1)\n  &&\n  (candidate 1 2 =n= 1)\n  &&\n  (candidate 2 1 =n= 2)\n  &&\n  (candidate 2 2 =n= 4)\n  &&\n  (candidate 3 2 =n= 9)\n  &&\n  (candidate 2 3 =n= 8)\n  &&\n  (candidate 3 3 =n= 27)\n  .\n  \nFixpoint power_v1 (x n : nat) : nat :=\n  match n with\n    | O => 1\n    | S n' => mul_v3 x (power_v1 x n')\n  end.\n\nCompute (test_power power_v1).\n\nDefinition power_v2 (x n : nat) : nat :=\n  let fix visit i :=\n    match i with\n      | O => 1\n      | S i' => mul_v3 x (visit i')\n    end\n  in visit n.\n\nCompute (test_power power_v2).\n\nDefinition power_v3 (x n: nat) : nat :=\n  let fix visit i a :=\n    match i with\n      | O => a\n      | S i' => visit i' (mul_v3 x a)\n    end\n  in visit n 1.\n\nCompute (test_power power_v3).\n  \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  &&\n  (candidate 4 =n= 24)\n  &&\n  (candidate 5 =n= 120)\n  &&\n  (candidate 6 =n= 720)\n  .\n  \nFixpoint fac_v1 (n : nat) : nat :=\n  match n with\n    | O => 1\n    | S n' => mul_v3 n (fac_v1 n')\n  end.\n\nCompute (test_fac fac_v1).\n\n\nDefinition fac_v2 (n : nat) : nat :=\n  let fix visit i :=\n    match i with\n      | O => 1\n      | S i' => mul_v3 i (visit i')\n    end\n  in visit n.\n\nCompute (test_fac fac_v2).\n\n\nDefinition fac_v3 (n : nat) : nat :=\n  let fix visit i a :=\n    match i with\n      | O => a\n      | S i' => visit i' (mul_v3 i a)\n    end\n  in visit n 1.\n\nCompute (test_fac fac_v3).\n\n\n(* ***** *)\n\n\nDefinition test_fib (candidate: nat -> nat) : bool :=\n  (candidate 0 =n= 0)\n  &&\n  (candidate 1 =n= 1)\n  &&\n  (candidate 2 =n= 1)\n  &&\n  (candidate 3 =n= 2)\n  &&\n  (candidate 4 =n= 3)\n  &&\n  (candidate 5 =n= 5)\n  &&\n  (candidate 6 =n= 8)\n  &&\n  (candidate 7 =n= 13)\n  &&\n  (candidate 8 =n= 21)\n  &&\n  (candidate 9 =n= 34)\n  &&\n  (candidate 10 =n= 55)\n  .\n  \nFixpoint fib_v1 (n : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => match n' with\n                | O => 1\n                | S n'' => add_v3 (fib_v1 n') (fib_v1 n'')\n              end\n  end.\n\nCompute (test_fib fib_v1).\n\nDefinition fib_v2 (n : nat) : nat :=\n  let fix visit n :=\n      match n with\n      | O => O\n      | S n' => match n' with\n                | O => 1\n                | S n'' => add_v3 (visit n') (visit n'')\n                end\n      end\n  in visit n.\n                 \nCompute (test_fib fib_v2).\n\nDefinition fib_v3 (n : nat) : nat :=\n  let fix visit n f0 f1:=\n      match n with\n      | O => f0\n      | S n' => visit n' (add_v3 f0 f1) f0\n      end\n  in visit n 0 1.\n                 \nCompute (test_fib fib_v3).\n  \n\n(* ***** *)\n\nNotation \"A =b= B\" :=\n  (eqb A B) (at level 70, right associativity).\n\n\nDefinition test_even (candidate: nat -> bool) : 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  (candidate 4 =b= true)\n  &&\n  (candidate 5 =b= false)\n  &&\n  (candidate 6 =b= true)\n  &&\n  (candidate 7 =b= false)\n  &&\n  (candidate 8 =b= true)\n  .\n\nFixpoint even_v1 (n : nat) : bool :=\n  match n with\n    | O => true\n    | S n' => negb (even_v1 n')\n  end.\n\nCompute (test_even even_v1).\n\nDefinition even_v2 (n : nat) : bool :=\n  let fix visit n :=\n    match n with\n      | O => true\n      | S n' => negb (visit n')\n    end\n  in visit n.\n\nCompute (test_even even_v2).\n\nDefinition even_v3 (n : nat) : bool :=\n  let fix visit n a :=\n    match n with\n      | O => a\n      | S n' => visit n' (negb a)\n    end\n  in visit n true.\n\nCompute (test_even even_v3).\n\n\n(* ***** *)\n\n\nDefinition test_odd (candidate: nat -> bool) : bool :=\n  (candidate 0 =b= false)\n  &&\n  (candidate 1 =b= true)\n  &&\n  (candidate 2 =b= false)\n  &&\n  (candidate 3 =b= true)\n  &&\n  (candidate 4 =b= false)\n  &&\n  (candidate 5 =b= true)\n  &&\n  (candidate 6 =b= false)\n  &&\n  (candidate 7 =b= true)\n  &&\n  (candidate 8 =b= false)\n  .\n\nFixpoint odd_v1 (n : nat) : bool :=\n  match n with\n    | O => false\n    | S n' => negb (odd_v1 n')\n  end.\n\nCompute (test_odd odd_v1).\n\nDefinition odd_v2 (n : nat) : bool :=\n  let fix visit n :=\n    match n with\n      | O => false\n      | S n' => negb (visit n')\n    end\n  in visit n.\n\nCompute (test_odd odd_v2).\n\nDefinition odd_v3 (n : nat) : bool :=\n  let fix visit n a :=\n    match n with\n      | O => a\n      | S n' => visit n' (negb a)\n    end\n  in visit n false.\n\nCompute (test_odd odd_v3).\n\n(* ********** *)\n\n(* Exercise 2 *)\n\nInductive binary_tree :=\n| Leaf : nat -> binary_tree\n| Node : binary_tree -> binary_tree -> binary_tree.\n\n\nFixpoint beq_binary_tree (t1 t2 : binary_tree) : bool :=\n  match t1 with\n    Leaf n1 =>\n    match t2 with\n      Leaf n2 =>\n      n1 =n= n2\n    | Node t21 t22 =>\n      false\n    end\n  | Node t11 t12 =>\n    match t2 with\n      Leaf n2 =>\n      false\n    | Node t21 t22 =>\n      (beq_binary_tree t11 t21) && (beq_binary_tree t12 t22)\n    end\n  end.\n\nNotation \"A =bt= B\" :=\n  (beq_binary_tree A B) (at level 70, right associativity).\n\n(* Number of nodes of a tree *)\n\n(* Unit test *)\n\nDefinition test_number_of_nodes (candidate: binary_tree -> nat) : bool :=\n  (candidate (Leaf 10) =n= 0)\n  &&\n  (candidate (Node (Leaf 10)\n                   (Leaf 20)) =n= 1)\n  &&\n  (candidate (Node (Leaf 10)\n                   (Node (Leaf 20)\n                         (Leaf 30))) =n= 2)\n  &&\n  (candidate (Node (Node (Leaf 10)\n                            (Leaf 20))\n                   (Leaf 30)) =n= 2)\n  &&\n  (candidate (Node (Node (Node (Leaf 30)\n                               (Leaf 31))\n                         (Leaf 20))\n                   (Node (Leaf 21)\n                         (Node (Leaf 32)\n                               (Leaf 33))))\n   =n= 5)\n  &&\n  (candidate (Node (Node (Node (Leaf 30)\n                               (Node (Leaf 40)\n                                     (Leaf 41)))\n                         (Leaf 20))\n                   (Node (Leaf 21)\n                         (Node (Leaf 31)\n                               (Leaf 21))))\n   =n= 6).\n\n\n(* Definition *)\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\nCompute (test_number_of_nodes number_of_nodes).\n\n\n\n(* Smallest leaf *)\n\n(* Unit test *)\nDefinition test_smallest_leaf (candidate: binary_tree -> nat) : bool :=\n  (candidate (Leaf 10) =n= 10)\n  &&\n  (candidate (Node (Leaf 10)\n                   (Leaf 20)) =n= 10)\n  &&\n  (candidate (Node (Leaf 10)\n                   (Node (Leaf 20)\n                         (Leaf 30))) =n= 10)\n  &&\n  (candidate (Node (Node (Leaf 20)\n                            (Leaf 20))\n                   (Leaf 30)) =n= 20)\n  &&\n  (candidate (Node (Node (Leaf 30)\n                            (Leaf 40))\n                   (Leaf 100)) =n= 30).\n\n\n(* Function *)\n\nFixpoint smallest_leaf (t: binary_tree) : nat :=\n  match t with\n  | Leaf n => n\n  | Node t1 t2 =>\n    min (smallest_leaf t1) (smallest_leaf t2)\n  end.\n\nCompute (test_smallest_leaf smallest_leaf).\n\n\n(* Weight of binary tree - Sum of integers in the leaves *)\n\nDefinition test_weight (candidate: binary_tree -> nat) : bool :=\n  (candidate (Leaf 10) =n= 10)\n  &&\n  (candidate (Node (Leaf 10)\n                   (Leaf 20)) =n= 30)\n  &&\n  (candidate (Node (Leaf 10)\n                   (Node (Leaf 20)\n                         (Leaf 30))) =n= 60)\n  &&\n  (candidate (Node (Node (Leaf 10)\n                            (Leaf 20))\n                   (Leaf 30)) =n= 60)\n  &&\n  (candidate (Node (Node (Leaf 20)\n                            (Leaf 20))\n                   (Leaf 100)) =n= 140).\n\nFixpoint weight (t: binary_tree) : nat :=\n  match t with\n  | Leaf n =>\n    n\n  | Node t1 t2 =>\n    (weight t1) + (weight t2)\n  end.\n\nCompute (test_weight weight).\n\n\n\n(* Height of binary tree *)\n\n(* Unit test *)\n\nDefinition test_height (candidate: binary_tree -> nat) : bool :=\n  (candidate (Leaf 10)\n   =n= 0)\n  &&\n  (candidate (Node (Leaf 10)\n                   (Leaf 20))\n   =n= 1)\n  &&\n  (candidate (Node (Leaf 10)\n                   (Node (Leaf 20)\n                         (Leaf 30)))\n   =n= 2)\n  &&\n  (candidate (Node (Leaf 10)\n                   (Node (Leaf 20)\n                         (Node (Leaf 30)\n                               (Leaf 31))))\n   =n= 3)\n  &&\n  (candidate (Node (Node (Node (Leaf 30)\n                               (Leaf 31))\n                         (Leaf 20))\n                   (Node (Leaf 21)\n                         (Node (Leaf 32)\n                               (Leaf 33))))\n   =n= 3)\n  &&\n  (candidate (Node (Node (Node (Leaf 30)\n                               (Node (Leaf 40)\n                                     (Leaf 41)))\n                         (Leaf 20))\n                   (Node (Leaf 21)\n                         (Node (Leaf 31)\n                               (Leaf 21))))\n   =n= 4)\n  &&\n  (candidate (Node (Leaf 10)\n                   (Node (Leaf 20)\n                         (Node (Leaf 30)\n                               (Node (Leaf 40)\n                                     (Node (Leaf 50)\n                                           (Node (Leaf 60)\n                                                 (Node (Leaf 70)\n                                                       (Leaf 71))))))))\n   =n= 7).\n                                    \n\n(* Function *)\n\nFixpoint height (t: binary_tree) : nat :=\n  match t with\n  | Leaf n =>\n    0\n  | Node t1 t2 =>\n    S(max (height t1) (height t2))\n  end.\n\nCompute (test_height height).\n\n\n(* Well balancedness of a mobile *)\n\nDefinition test_well_balanced (candidate: binary_tree -> bool) : bool :=\n  (candidate (Leaf 1)\n   =b= true)\n  &&\n  (candidate (Node (Leaf 1)\n                   (Leaf 1))\n   =b= true)\n  &&\n  (candidate (Node (Leaf 1)\n                   (Leaf 2))\n   =b= false)\n  &&\n  (candidate (Node (Leaf 2)\n                     (Leaf 1))\n   =b= false)\n  &&\n  (candidate (Node (Node (Leaf 1)\n                         (Leaf 1))\n                   (Leaf 2))\n   =b= true)\n  &&\n  (candidate (Node (Leaf 2)\n                   (Node (Leaf 1)\n                         (Leaf 1)))\n   =b= true)\n  &&\n  (candidate (Node (Node (Leaf 2)\n                         (Node (Leaf 1)\n                               (Leaf 1)))\n                   (Node (Node (Node (Leaf 1)\n                                     (Leaf 1))\n                               (Node (Leaf 1)\n                                     (Leaf 1)))\n                         (Leaf 6)))\n   =b= false)\n  &&\n  (candidate (Node (Node (Leaf 4)\n                         (Node (Leaf 2)\n                               (Leaf 2)))\n                   (Node (Node (Node (Leaf 2)\n                                     (Leaf 1))\n                               (Node (Leaf 1)\n                                     (Leaf 2)))\n                         (Leaf 6)))\n   =b= false).\n    \n\nInductive option :=\n| None : option\n| Some : nat -> option.\n\n\n(* Function *)\n\n(* Lambda dropped version *)\n\nDefinition well_balanced (t: binary_tree) : bool :=\n  let fix visit t :=\n      match t with\n      | Leaf n => Some n\n      | Node t1 t2 =>\n        match visit t1 with\n        | None => None\n        | Some w1 =>\n          (match visit t2 with\n           | None => None\n           | Some w2 =>\n             if w1 =n= w2\n             then Some (w1 + w2)\n             else None\n           end)\n        end\n      end\n  in match visit t with\n     | None => false\n     | Some w => true\n     end.\n\nCompute (test_well_balanced well_balanced).              \n\n(* Mirror *)\nDefinition test_mirror (candidate: binary_tree -> binary_tree) : bool :=\n  (candidate\n     (Leaf 1)\n   =bt= (Leaf 1))\n  &&\n  (candidate\n     (Node (Leaf 10)\n           (Leaf 20))\n   =bt= (Node (Leaf 20)\n           (Leaf 10)))\n  &&\n  (candidate\n     (Node (Leaf 10)\n           (Node (Leaf 20)\n                 (Leaf 30)))\n   =bt= (Node (Node (Leaf 30)\n                 (Leaf 20))\n           (Leaf 10)))\n  &&\n  (candidate\n     (Node (Node (Leaf 10)\n                 (Leaf 20))\n           (Node (Leaf 30)\n                 (Leaf 40)))\n   =bt= (Node (Node (Leaf 40)\n                 (Leaf 30))\n           (Node (Leaf 20)\n                 (Leaf 10)))).\n                 \n\n(* Function *)\nFixpoint mirror (t: binary_tree) : binary_tree :=\n  match t with\n  | Leaf n => Leaf n\n  | Node t1 t2 =>\n    Node (mirror t2) (mirror t1)\n  end.\n\nCompute (test_mirror mirror).\n\n\n(* ********** *)\n\n(* Exercise 3 *)\n\nInductive binary_tree' :=\n| Leaf' : binary_tree'\n| Node' : binary_tree' -> nat -> binary_tree' -> binary_tree'.\n\nDefinition test_number_of_leaves' (candidate: binary_tree' -> nat) : bool :=\n  (candidate Leaf' =n= 1)\n  &&\n  (candidate (Node' Leaf'\n                    42\n                    Leaf') =n= 2)\n  &&\n  (candidate (Node' Leaf'\n                    42\n                    (Node' Leaf'\n                           42\n                           Leaf')) =n= 3)\n  &&\n  (candidate (Node' (Node' Leaf'\n                           42\n                           Leaf')\n                    42\n                    Leaf') =n= 3)\n  &&\n  (candidate (Node' (Node' Leaf'\n                           42\n                           Leaf')\n                    42\n                    (Node' Leaf'\n                           42\n                           Leaf')) =n= 4)\n  &&\n  (candidate (Node' (Node' Leaf'\n                           42\n                           Leaf')\n                    42 (Node' Leaf'\n                              42 (Node' Leaf'\n                                        42\n                                        Leaf'))) =n= 5)\n  &&\n  (candidate (Node' (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           Leaf')\n                    42\n                    (Node' Leaf'\n                           42\n                           Leaf')) =n= 5)\n  &&\n  (candidate (Node' (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           Leaf')\n                    42\n                    (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           Leaf')) =n= 6)\n  &&\n  (candidate (Node' (Node' Leaf'\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))\n                    42\n                    (Node' Leaf'\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))) =n= 6)\n  &&\n  (candidate (Node' (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))\n                    42\n                    (Node' Leaf'\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))) =n= 7)\n  &&\n  (candidate (Node' (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           Leaf')\n                    42\n                    (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))) =n= 7)\n  &&\n  (candidate (Node' (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))\n                    42\n                    (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))) =n= 8)\n  &&\n  (candidate (Node' (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           (Node' Leaf'\n                                  42\n                                  (Node' Leaf'\n                                         42\n                                         Leaf')))\n                    42\n                    (Node' Leaf'\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))) =n= 8)\n  .\n\nFixpoint number_of_leaves'_v0 (t : binary_tree') : nat :=\n  match t with\n  | Leaf' => 1\n  | Node' t1 n t2 => (number_of_leaves'_v0 t1) + (number_of_leaves'_v0 t2)\n  end.\n\nCompute (test_number_of_leaves' number_of_leaves'_v0).\n\nDefinition number_of_leaves'_v1 (t : binary_tree') : nat :=\n  let fix visit t a :=\n      match t with\n      | Leaf' => S a\n      | Node' t1 n t2 => visit t2 (visit t1 a)\n      end\n  in visit t 0.\n\nCompute (test_number_of_leaves' number_of_leaves'_v1).\n  \n  \nDefinition test_number_of_nodes' (candidate: binary_tree' -> nat) : bool :=\n  (candidate Leaf' =n= 0)\n  &&\n  (candidate (Node' Leaf'\n                    42\n                    Leaf') =n= 1)\n  &&\n  (candidate (Node' Leaf'\n                    42\n                    (Node' Leaf'\n                           42\n                           Leaf')) =n= 2)\n  &&\n  (candidate (Node' (Node' Leaf'\n                           42\n                           Leaf')\n                    42\n                    Leaf') =n= 2)\n  &&\n  (candidate (Node' (Node' Leaf'\n                           42\n                           Leaf')\n                    42\n                    (Node' Leaf'\n                           42\n                           Leaf')) =n= 3)\n  &&\n  (candidate (Node' (Node' Leaf'\n                           42\n                           Leaf')\n                    42\n                    (Node' Leaf'\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))) =n= 4)\n  &&\n  (candidate (Node' (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           Leaf')\n                    42\n                    (Node' Leaf'\n                           42\n                           Leaf')) =n= 4)\n  &&\n  (candidate (Node' (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           Leaf')\n                    42\n                    (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           Leaf')) =n= 5)\n  &&\n  (candidate (Node' (Node' Leaf'\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))\n                    42\n                    (Node' Leaf'\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))) =n= 5)\n  &&\n  (candidate (Node' (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))\n                    42\n                    (Node' Leaf'\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))) =n= 6)\n  &&\n  (candidate (Node' (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           Leaf')\n                    42\n                    (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))) =n= 6)\n  &&\n  (candidate (Node' (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))\n                    42\n                    (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))) =n= 7)\n  &&\n  (candidate (Node' (Node' (Node' Leaf'\n                                  42\n                                  Leaf')\n                           42\n                           (Node' Leaf'\n                                  42\n                                  (Node' Leaf'\n                                         42\n                                         Leaf')))\n                    42\n                    (Node' Leaf'\n                           42\n                           (Node' Leaf'\n                                  42\n                                  Leaf'))) =n= 7)\n  .\n\nFixpoint number_of_nodes'_v0 (t : binary_tree') : nat :=\n  match t with\n  | Leaf' => O\n  | Node' t1 n t2 => S ((number_of_nodes'_v0 t1) + (number_of_nodes'_v0 t2))\n  end.\n\nCompute (test_number_of_nodes' number_of_nodes'_v0).\n\nDefinition number_of_nodes'_v1 (t : binary_tree') : nat :=\n  match number_of_leaves'_v1 t with\n  | O => O\n  | S n' => n'\n  end.\n\nCompute (test_number_of_nodes' number_of_nodes'_v1).\n\nDefinition number_of_nodes'_v2 (t : binary_tree') : nat :=\n  let fix visit t a :=\n      match t with\n      | Leaf' => a\n      | Node' t1 n t2 => visit t2 (visit t1 (S a))\n      end\n  in visit t 0.\n\nCompute (test_number_of_nodes' number_of_nodes'_v2).\n\n(* ********** *)\n\n(* Exercise 4 *)\n\nInductive binary_tree'' :=\n| Leaf'' : nat -> binary_tree''\n| Node'' : binary_tree'' -> nat -> binary_tree'' -> binary_tree''.\n\nDefinition test_number_of_leaves'' (candidate: binary_tree'' -> nat) : bool :=\n  (candidate (Leaf'' 21) =n= 1)\n  &&\n  (candidate (Node'' (Leaf'' 21)\n                    42\n                    (Leaf'' 21)) =n= 2)\n  &&\n  (candidate (Node'' (Leaf'' 21)\n                    42\n                    (Node'' (Leaf'' 21)\n                           42\n                           (Leaf'' 21))) =n= 3)\n  &&\n  (candidate (Node'' (Node'' (Leaf'' 21)\n                           42\n                           (Leaf'' 21))\n                    42\n                    (Leaf'' 21)) =n= 3)\n  &&\n  (candidate (Node'' (Node'' (Leaf'' 21)\n                           42\n                           (Leaf'' 21))\n                    42\n                    (Node'' (Leaf'' 21)\n                           42\n                           (Leaf'' 21))) =n= 4)\n  &&\n  (candidate (Node'' (Node'' (Leaf'' 21)\n                           42\n                           (Leaf'' 21))\n                    42 (Node'' (Leaf'' 21)\n                              42 (Node'' (Leaf'' 21)\n                                        42\n                                        (Leaf'' 21)))) =n= 5)\n  &&\n  (candidate (Node'' (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Leaf'' 21))\n                    42\n                    (Node'' (Leaf'' 21)\n                           42\n                           (Leaf'' 21))) =n= 5)\n  &&\n  (candidate (Node'' (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Leaf'' 21))\n                    42\n                    (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Leaf'' 21))) =n= 6)\n  &&\n  (candidate (Node'' (Node'' (Leaf'' 21)\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))\n                    42\n                    (Node'' (Leaf'' 21)\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))) =n= 6)\n  &&\n  (candidate (Node'' (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))\n                    42\n                    (Node'' (Leaf'' 21)\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))) =n= 7)\n  &&\n  (candidate (Node'' (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Leaf'' 21))\n                    42\n                    (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))) =n= 7)\n  &&\n  (candidate (Node'' (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))\n                    42\n                    (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))) =n= 8)\n  &&\n  (candidate (Node'' (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Node'' (Leaf'' 21)\n                                         42\n                                         (Leaf'' 21))))\n                    42\n                    (Node'' (Leaf'' 21)\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))) =n= 8)\n  .\n\nFixpoint number_of_leaves''_v0 (t : binary_tree'') : nat :=\n  match t with\n  | Leaf'' n => 1\n  | Node'' t1 n t2 => (number_of_leaves''_v0 t1) + (number_of_leaves''_v0 t2)\n  end.\n\nCompute (test_number_of_leaves'' number_of_leaves''_v0).\n\nDefinition number_of_leaves''_v1 (t : binary_tree'') : nat :=\n  let fix visit t a :=\n      match t with\n      | Leaf'' n => S a\n      | Node'' t1 n t2 => visit t2 (visit t1 a)\n      end\n  in visit t 0.\n\nCompute (test_number_of_leaves'' number_of_leaves''_v1).\n\nDefinition test_number_of_nodes'' (candidate: binary_tree'' -> nat) : bool :=\n  (candidate (Leaf'' 21) =n= 0)\n  &&\n  (candidate (Node'' (Leaf'' 21)\n                    42\n                    (Leaf'' 21)) =n= 1)\n  &&\n  (candidate (Node'' (Leaf'' 21)\n                    42\n                    (Node'' (Leaf'' 21)\n                           42\n                           (Leaf'' 21))) =n= 2)\n  &&\n  (candidate (Node'' (Node'' (Leaf'' 21)\n                           42\n                           (Leaf'' 21))\n                    42\n                    (Leaf'' 21)) =n= 2)\n  &&\n  (candidate (Node'' (Node'' (Leaf'' 21)\n                           42\n                           (Leaf'' 21))\n                    42\n                    (Node'' (Leaf'' 21)\n                           42\n                           (Leaf'' 21))) =n= 3)\n  &&\n  (candidate (Node'' (Node'' (Leaf'' 21)\n                           42\n                           (Leaf'' 21))\n                    42 (Node'' (Leaf'' 21)\n                              42 (Node'' (Leaf'' 21)\n                                        42\n                                        (Leaf'' 21)))) =n= 4)\n  &&\n  (candidate (Node'' (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Leaf'' 21))\n                    42\n                    (Node'' (Leaf'' 21)\n                           42\n                           (Leaf'' 21))) =n= 4)\n  &&\n  (candidate (Node'' (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Leaf'' 21))\n                    42\n                    (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Leaf'' 21))) =n= 5)\n  &&\n  (candidate (Node'' (Node'' (Leaf'' 21)\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))\n                    42\n                    (Node'' (Leaf'' 21)\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))) =n= 5)\n  &&\n  (candidate (Node'' (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))\n                    42\n                    (Node'' (Leaf'' 21)\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))) =n= 6)\n  &&\n  (candidate (Node'' (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Leaf'' 21))\n                    42\n                    (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))) =n= 6)\n  &&\n  (candidate (Node'' (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))\n                    42\n                    (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))) =n= 7)\n  &&\n  (candidate (Node'' (Node'' (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21))\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Node'' (Leaf'' 21)\n                                         42\n                                         (Leaf'' 21))))\n                    42\n                    (Node'' (Leaf'' 21)\n                           42\n                           (Node'' (Leaf'' 21)\n                                  42\n                                  (Leaf'' 21)))) =n= 7)\n  .\n\nFixpoint number_of_nodes''_v0 (t : binary_tree'') : nat :=\n  match t with\n  | Leaf'' n => O\n  | Node'' t1 n t2 => S ((number_of_nodes''_v0 t1) + (number_of_nodes''_v0 t2))\n  end.\n\nCompute (test_number_of_nodes'' number_of_nodes''_v0).\n\nDefinition number_of_nodes''_v1 (t : binary_tree'') : nat :=\n  match number_of_leaves''_v1 t with\n  | O => O\n  | S n' => n'\n  end.\n\nCompute (test_number_of_nodes'' number_of_nodes''_v1).\n\nDefinition number_of_nodes''_v2 (t : binary_tree'') : nat :=\n  let fix visit t a :=\n      match t with\n      | Leaf'' n => a\n      | Node'' t1 n t2 => visit t2 (visit t1 (S a))\n      end\n  in visit t 0.\n\nCompute (test_number_of_nodes'' number_of_nodes''_v2).\n\n\n(* ********** *)\n\n(* end of week-01_functional-programming-in-Coq.v *)\n\n", "meta": {"author": "TristanKoh", "repo": "FPP", "sha": "bb22748fed28f6b300add2525e15f5cdcedce59b", "save_path": "github-repos/coq/TristanKoh-FPP", "path": "github-repos/coq/TristanKoh-FPP/FPP-bb22748fed28f6b300add2525e15f5cdcedce59b/FPP Week 1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118068790619, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.6680387081065385}}
{"text": "(** CS6225 Spring 2020 @ IITM : Problem Set 7 *)\n\nRequire Import Frap.\n\n(* Authors:\n * Ben Sherman (sherman@csail.mit.edu),\n * Joonwon Choi (joonwonc@csail.mit.edu),\n * Adam Chlipala (adamc@csail.mit.edu)\n *)\n\n(* In this problem set, we will work with the following simple imperative language with\n * a nondeterministic choice operator. Your task is to define both big-step as well as\n * a particular kind of small-step operational semantics for this language\n * (one that is in fact deterministic), and to prove a theorem connecting the two:\n * if the small-step semantics aborts, then the big-step semantics may abort.\n *\n * This is the first problem set so far in this class that is truly open-ended.\n * We want to give you the flexibility to define the operational semantics as\n * you wish, and if you'd like you may even differ from the template shown here\n * if you find it more convenient.\n * Additionally, this is the first problem set where it is *NOT* sufficient to\n * just get the file compiling without any use of [admit] or [Admitted].\n * This will not necessarily guarantee that you have given reasonable semantics\n * for the programming language, and accordingly, will not necessarily\n * guarantee that you will earn full credit. For instance, if you define\n * your small-step semantics as the empty relation (which is incorrect),\n * the theorem you must prove to connect your big-step and small-step\n * semantics will be trivial.\n *)\n\n(** * Syntax *)\n\n(* Basic arithmetic expressions, as we've seen several times in class. *)\nInductive arith : Set :=\n| Const : nat -> arith\n| Var : var -> arith\n| Plus : arith -> arith -> arith\n| Eq : arith -> arith -> arith\n(* should return 1 if the two expressions are equal, and 0 otherwise. *)\n| Lt : arith -> arith -> arith\n(* should return 1 if the first expression is less than then second, and 0 otherwise. *)\n.\n\n(* The simple imperative language with a [Choose] syntax for\n * nondeterminism. The intended meaning of the program\n * [Choose c c'] is that either [c] should run or [c'] should run.\n *)\nInductive cmd :=\n| Assign : var -> arith -> cmd\n| Skip : cmd\n| Seq : cmd -> cmd -> cmd\n| Choose : cmd -> cmd -> cmd (* Here's the main novelty: nondeterministic choice *)\n| If : arith -> cmd (* then *) -> cmd (* else *) -> cmd\n| While : arith -> cmd -> cmd\n| Abort : cmd (* This command should immediately terminate the program *)\n.\n\n(** Notations *)\n\nDelimit Scope cmd_scope with cmd.\n\nCoercion Const : nat >-> arith.\nCoercion Var : var >-> arith.\nInfix \"+\" := Plus : arith_scope.\nInfix \"==\" := Eq (at level 75) : arith_scope.\nInfix \"<\" := Lt : arith_scope.\nDelimit Scope arith_scope with arith.\nNotation \"x <- e\" := (Assign x e%arith) (at level 75) : cmd_scope.\nInfix \"<|>\" := Choose (at level 78) : cmd_scope.\nInfix \";;\" := Seq (at level 80) : cmd_scope.\n\nNotation \"'if_' c 'then' t 'else' f\" := (If c%arith t f) (at level 75) : cmd_scope.\nNotation \"'while' c 'do' p\" := (While c%arith p) (at level 75) : cmd_scope.\n\n\n(** * Examples *)\n\n(* All nondeterministic realizations of [test_prog1] terminate\n * (either normally or by aborting). [test_prog1 5] may abort,\n * but [test_prog1 6] always terminates normally.\n *)\nDefinition test_prog1 (k : nat) : cmd := (\n  \"target\" <- 8 ;;\n  (\"x\" <- 3 <|> \"x\" <- 4) ;;\n  (\"y\" <- 1 <|> \"y\" <- k) ;;\n  if_ \"x\" + \"y\" == \"target\"\n     then Abort\n     else Skip\n  )%cmd.\n\n(* No matter the value of [num_iters], [test_prog2 num_iters]\n * always may potentially fail to terminate, and always\n * may potentially abort.\n *)\nDefinition test_prog2 (num_iters : nat) : cmd := (\n   \"acc\" <- 0 ;;\n   \"n\" <- 0;;\n   while (\"n\" < 1) do (\n     (Skip <|> \"n\" <- 1) ;;\n     \"acc\" <- \"acc\" + 1\n   ) ;;\n   if_ \"acc\" == S num_iters\n     then Abort\n     else Skip\n  )%cmd.\n\n\n(* We've seen the expression language in class a few times,\n * so here we'll just give you the interpreter for that\n * expression language.\n *)\nDefinition valuation := fmap var nat.\n\nFixpoint interp (e : arith) (v : valuation) : nat :=\n  match e with\n  | Const n => n\n  | Var x =>\n    match v $? x with\n    | None => 0\n    | Some n => n\n    end\n  | Plus e1 e2 => interp e1 v + interp e2 v\n  | Eq e1 e2 => if interp e1 v ==n interp e2 v then 1 else 0\n  | Lt e1 e2 => if lt_dec (interp e1 v) (interp e2 v) then 1 else 0\n  end.\n\n(** ** Part 1: Big-step operational semantics *)\n\n(* You should define some result type (say, [result]) for values that commands\n   in the language run to, and define a big-step operational semantics\n   [eval : valuation -> cmd -> result -> Prop]\n   that says when a program *may* run to some result in *some* nondeterministic\n   realization of the program. Then you should also define a predicate\n   [big_aborted : result -> Prop]\n   that describes which results indicate that the program aborted.\n *)\n\nDefinition result : Type.\nAdmitted.\n\n(* 5 points *)\nDefinition eval : valuation -> cmd -> result -> Prop.\nAdmitted.\n\nDefinition big_aborted : result -> Prop.\nAdmitted.\n\n(* Prove that your big-step semantics behaves appropriately\n * for the example program:\n *)\n\n(* 5 points *)\nExample test_prog1_reachable :\n  exists res, eval $0 (test_prog1 5) res /\\ big_aborted res.\nProof.\nAdmitted.\n\n(* 5 points *)\nExample test_prog1_unreachable :\n  forall res, eval $0 (test_prog1 6) res -> big_aborted res -> False.\nProof.\nAdmitted.\n\n  (** ** Part 2: Small-step deterministic operational semantics *)\n\n(* Next, you should define a small-step operational semantics for this\n   language that in some sense tries to run *all* possible nondeterministic\n   realizations and aborts if any possible realization aborts.\n   Define a type [state] that represents the underlying state that the\n   small-step semantics should take steps on, and then define a small-step\n   semantics\n   [step : state -> state -> Prop]\n   .\n\n   Here's the twist: we ask that you define an operational semantics that\n   is *deterministic*, in the sense of the following formal statement:\n   [forall s1 s2 s2', step s1 s2 -> step s1 s2' -> s2 = s2'].\n\n   The operational model that we have in mind in this: when we encounter\n   a nondeterministic choice, we execute the left branch. If the left\n   branch terminates without aborting, we backtrack and try the\n   other nondeterministic choice.\n\n   Note that if any possible realization does not terminate,\n   we allow the deterministic small-step semantics to diverge as well.\n   (It is actually possible to define a semantics that always \"finds\" aborts,\n   even if some branches of nondeterminism diverge!  However, the proof of that\n   variant would likely be significantly more complicated, and we haven't tried\n   it ourselves.)\n\n   Define a function\n   [init : valuation -> cmd -> state]\n   that builds starting states for the small-step semantics,\n   a predicate\n   [small_aborted : state -> Prop]\n   that describes which states are considered aborted, and\n   a predicate\n   [small_terminated : state -> Prop]\n   that describes states that have run to completion without any\n   nondeterministic branch aborting.\n *)\n\nDefinition state : Type.\nAdmitted.\n\n(* 5 points *)\nDefinition step : state -> state -> Prop.\nAdmitted.\n\nDefinition init : valuation -> cmd -> state.\nAdmitted.\n\nDefinition small_aborted : state -> Prop.\nAdmitted.\n\nDefinition small_terminated : state -> Prop.\nAdmitted.\n\n(* Prove that your small-step semantics behaves appropriately\n * for the example program:\n *)\n\n(* 5 points *)\nExample test_prog1_reachable_small :\n  exists st, step^* (init $0 (test_prog1 5)) st /\\ small_aborted st.\nProof.\nAdmitted.\n\n\n(* 5 points *)\nExample test_prog1_unreachable_small :\n  forall st, step^* (init $0 (test_prog1 6)) st -> small_aborted st -> False.\nProof.\nAdmitted.\n\n(** ** Part 3: A lemma on big step semantics *)\n\n(* 10 points *)\nLemma lem: forall c1 c2 c3 v res,\n  eval v (c1;;(c2;;c3))%cmd res ->\n  eval v ((c1;;c2);;c3)%cmd res.\nProof.\nAdmitted.\n\n(** ** Part 4: Connection between big- and small-step semantics *)\n\n(* Prove the following theorem demonstrating the connection between the big-step\n * and small-step semantics:\n *\n * If the small-step semantics aborts, then the big-step semantics may\n * potentially abort.\n *)\n\n(* 40 points *)\nTheorem small_abort_big_may_abort : forall v c s,\n         step^* (init v c) s\n      -> small_aborted s\n      -> exists res, eval v c res /\\ big_aborted res.\nProof.\nAdmitted.\n\n (* As an additional challenge, you  you may want to prove the following\n * theorem. Note that this is *NOT* required for this assignment and\n * will not affect your grade.\n *\n * If the small-step semantics terminates without aborting, then the\n * big-step semantics may *not* abort.\n *)\n\n(*\nTheorem small_terminates_big_will_not_abort :\n       forall v c s,\n         step^* (init v c) s\n      -> small_terminated s\n      -> forall res,\n             eval v c res\n          -> big_aborted res\n          -> False.\nProof.\nAdmitted.\n*)\n", "meta": {"author": "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/pset7/Pset7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.6680387012065129}}
{"text": "(* Test patterns unification *)\n\nLemma l1 : (forall P, (exists x:nat, P x) -> False)\n         -> forall P, (exists x:nat, P x /\\ P x) -> False.\nProof.\nintros; apply (H _ H0).\nQed.\n\nLemma l2 :  forall A:Set, forall Q:A->Set,\n           (forall (P: forall x:A, Q x -> Prop),\n                   (exists x:A, exists y:Q x, P x y) -> False)\n         -> forall (P: forall x:A, Q x -> Prop),\n                   (exists x:A, exists y:Q x, P x y /\\ P x y) -> False.\nProof.\nintros; apply (H _ H0).\nQed.\n\nLemma l3 : (forall P, ~(exists x:nat, P x))\n         -> forall P:nat->Prop, ~(exists x:nat, P x -> P x).\nProof.\nintros; apply H.\nQed.\n\n\n(* Example submitted for Zenon *)\n\nAxiom zenon_noteq : forall T : Type, forall t : T, ((t <> t) -> False).\nAxiom zenon_notall : forall T : Type, forall P : T -> Prop,\n  (forall z : T, (~(P z) -> False)) -> (~(forall x : T, (P x)) -> False).\n\n  (* Must infer \"P := fun x => x=x\" in zenon_notall *)\nCheck (fun _h1 => (zenon_notall nat _ (fun _T_0 =>\n          (fun _h2 => (zenon_noteq _ _T_0 _h2))) _h1)).\n\n\n(* Core of an example submitted by Ralph Matthes (#849)\n\n   It used to fail because of the K-variable x in the type of \"sum_rec ...\"\n   which was not in the scope of the evar ?B. Solved by a head\n   beta-reduction of the type \"(fun _ : unit + unit => L unit) x\" of\n   \"sum_rec ...\". Shall we used more reduction when solving evars (in\n   real_clean)?? Is there a risk of starting too long reductions?\n\n   Note that the example originally came from a non re-typable\n   pretty-printed term (the checked term is actually re-printed the\n   same form it is checked).\n*)\n\nSet Implicit Arguments.\nInductive L (A:Set) : Set := c : A -> L A.\nParameter f: forall (A:Set)(B:Set), (A->B) -> L A -> L B.\nParameter t: L (unit + unit).\n\nCheck (f (fun x : unit + unit =>\n  sum_rec (fun _ : unit + unit => L unit)\n    (fun y => c y) (fun y => c y) x) t).\n\n\n(* Test patterns unification in apply *)\n\nRequire Import Arith.\nParameter x y : nat.\nParameter G:x=y->x=y->Prop.\nParameter K:x<>y->x<>y->Prop.\nLemma l4 : (forall f:x=y->Prop, forall g:x<>y->Prop,\n            match eq_nat_dec x y with left a => f a | right a => g a end)\n   -> match eq_nat_dec x y with left a => G a a | right a => K a a end.\nProof.\nintros.\napply H.\nQed.\n\n\n(* Test unification modulo eta-expansion (if possible) *)\n\n(* In this example, two instances for ?P (argument of hypothesis H) can be\n   inferred (one is by unifying the type [Q true] and [?P true] of the\n   goal and type of [H]; the other is by unifying the argument of [f]);\n   we need to unify both instances up to allowed eta-expansions of the\n   instances (eta is allowed if the meta was applied to arguments)\n\n   This used to fail before revision 9389 in trunk\n*)\n\nLemma l5 :\n   forall f : (forall P, P true), (forall P, f P = f P) ->\n   forall Q, f (fun x => Q x) = f (fun x => Q x).\nProof.\nintros.\napply H.\nQed.\n\n(* Test instanciation of evars by unification *)\n\nGoal (forall x, 0 + x = 0 -> True) -> True.\nintros; eapply H.\nrewrite <- plus_n_Sm. (* should refine ?x with S ?x' *)\nAbort.\n\n(* Check handling of identity equation between evars *)\n(* The example failed to pass until revision 10623 *)\n\nLemma l6 :\n  (forall y, (forall x, (forall z, y = 0 -> y + z = 0) -> y + x = 0) -> True)\n  -> True.\nintros.\neapply H.\nintros.\napply H0. (* Check that equation ?n[H] = ?n[H] is correctly considered true *)\nreflexivity.\nQed.\n\n(* Check treatment of metas erased by K-redexes at the time of turning\n   them to evas *)\n\nInductive nonemptyT (t : Type) : Prop := nonemptyT_intro : t -> nonemptyT t.\nGoal True.\ntry case nonemptyT_intro. (* check that it fails w/o anomaly *)\nAbort.\n\n(* Test handling of return type and when it is decided to make the\n   predicate dependent or not - see \"bug\" #1851 *)\n\nGoal forall X (a:X) (f':nat -> X), (exists f : nat -> X, True).\nintros.\nexists (fun n => match n with O => a | S n' => f' n' end).\nconstructor.\nQed.\n\n(* Check use of types in unification (see Andrej Bauer's mail on\n   coq-club, June 1 2009; it did not work in 8.2, probably started to\n   work after Sozeau improved support for the use of types in unification) *)\n\nGoal (forall (A B : Set) (f : A -> B), (fun x => f x) = f) ->\n forall (A B C : Set) (g : (A -> B) -> C) (f : A -> B), g (fun x => f x) = g f.\nProof.\n  intros.\n  rewrite H with (f:=f0).\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/unification.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.6680387010209143}}
{"text": "(**\nA Constructive Theory of Regular Languages in Coq (pdf)\n\nにおいて\n\nTheorem 4.2 For every NFA (DFA) we can construct a DFA (NFA) accepting the same language.\n\nを証明する箇所を抜粋する。\n*)\n\n(** Authors: Christian Doczkal and Jan-Oliver Kaiser *)\n(** より抜粋 *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype\nssrnat seq choice fintype path fingraph  finfun  finset.\n\nSet Implicit Arguments.\n\nSection FA.\nVariable char : finType.\nDefinition word := seq char.                (* reqexp.word *)\n\n(** * Finite Automata *)\n\n(** ** Deterministic Finite Automata *)\n\nRecord dfa : Type :=\n  {\n    dfa_state :> finType;\n    dfa_s : dfa_state;\n    dfa_fin : pred dfa_state;\n    (* dfa_trans : dfa_state -> char -> dfa_state *)\n    dfa_trans (x : dfa_state) (a : char) : dfa_state\n    (* dfa_trans : {ffun dfa_state -> char -> dfa_state} *)\n  }.\n\n(** For DFAs, we use the direct recursive defintion of acceptance\n    as well as a definition in terms of runs. The latter is used\n    in the translation of DFAs to regular expressions. *)\n\n\nFixpoint dfa_accept {A : dfa} (x : A) w :=\n  if w is a :: w' then dfa_accept (dfa_trans A x a) w' else x \\in dfa_fin A.\n\nArguments dfa_trans [d] x a.\nArguments dfa_accept [A] x w.\n\nSection DFA_Acceptance.\nVariable A : dfa.\n\nLemma dfa_accept_cons (x : A) a w :\n  a :: w \\in dfa_accept x = (w \\in dfa_accept (dfa_trans x a)).\nProof.\n    by rewrite -simpl_predE /=.\nQed.\n(* 必要なものだけ抜粋した。 *)\nEnd DFA_Acceptance.\n\n\nDefinition dfa_lang A := [pred w | dfa_accept (dfa_s A) w].\n\n(** ** Nondeterministic Finite Automata. *)\nRecord nfa : Type :=\n  {\n    nfa_state :> finType;\n    nfa_s : nfa_state;\n    nfa_fin : pred nfa_state;\n    (* nfa_trans : nfa_state -> char -> nfa_state -> bool *)\n    nfa_trans (x : nfa_state) (a : char) (y : nfa_state) : bool\n  }.\n\n(** Non-deterministic acceptance. **)\nFixpoint nfa_accept (A : nfa) (x : A) w :=\n  if w is a :: w' then [exists y, nfa_trans A x a y && nfa_accept A y w']\n                  else x \\in nfa_fin A.\n\nDefinition nfa_lang (A : nfa) := [pred w | nfa_accept A (nfa_s A) w].\n\n\n(** ** Equivalence of DFAs and NFAs *)\n(** We use the powerset construction to obtain\n   a deterministic automaton from a non-deterministic one. **)\nSection PowersetConstruction.\n\nVariable A : nfa.\n\nDefinition nfa_to_dfa : dfa :=\n  {|\n    dfa_s := [set nfa_s A];\n    dfa_fin X := [exists x: A, (x \\in X) && nfa_fin A x];\n    dfa_trans X a := \\bigcup_(x | x \\in X) [set y | nfa_trans A x a y]\n  |}.\nSection TEST.\n  (**\nX : dfa ではなく、 A : nfa, X : {set A}、すなわち dfa≡{set A} とみなす。\nこれが、パワーセット・コンストラクションということなのだろう。\nここで、finSet が出てくるのがポイントである。\n   *)\n  Variable X : {set A}.\n  Variable a : char.\n\n  Check [set nfa_s A] : {set A}.\n  Check [exists x: A, (x \\in X) && nfa_fin A x] : bool.\n  Check \\bigcup_(x | x \\in X) [set y | nfa_trans A x a y] : {set A}.\nEnd TEST.\n\nLemma nfa_to_dfa_aux2 (x : A) w (X : nfa_to_dfa) :\n  x \\in X -> nfa_accept A x w -> dfa_accept X w.\nProof.\n  move => H0.\n  elim: w X x H0 => [|a w IHw] X x H0 /=.\n  - move => H1.\n    apply/existsP.\n    exists x.\n      by rewrite H0.\n  - move => /= /existsP [] y /andP [] H1 H2.\n    apply: (IHw _ y) => //.\n    apply/bigcupP.\n    exists x => //=.\n      by rewrite in_set.\nQed.\n\nCheck @bigcupP : forall (T I : finType) (x : T) (P : pred I) (F : I -> {set T}),\n    reflect (exists2 i : I, P i & x \\in F i) (x \\in \\bigcup_(i | P i) F i).\n\nLemma nfa_to_dfa_aux1 (X : nfa_to_dfa) w :\n  dfa_accept X w -> exists2 x, (x \\in X) & nfa_accept A x w.\nProof.\n  elim: w X => [|a w IHw] X => //=.\n  - move/existsP => [x] /andP [] H0 H1.\n    exists x; assumption.\n  - move/IHw => [] y /bigcupP [x] H0.\n    rewrite inE => H1 H2.\n    exists x.\n    + assumption.\n    + apply/existsP.\n      exists y.\n        by apply/andP.\nQed.\n\nLemma nfa_to_dfa_correct : nfa_lang A =i dfa_lang nfa_to_dfa.\nProof.\n  move => w.\n  apply/idP/idP => /=.\n  (* w \\in nfa_lang A -> w \\in dfa_lang nfa_to_dfa *)\n  - apply: nfa_to_dfa_aux2.\n      by apply/set1P.\n  (* w \\in dfa_lang nfa_to_dfa -> w \\in nfa_lang A *)\n  - by move/nfa_to_dfa_aux1 => [x] /set1P ->.\nQed.\n\nEnd PowersetConstruction.\n\n\n(** Embedding deterministic automata in non-deterministic automata. **)\nSection Embed.\n\nVariable A : dfa.\n\nDefinition dfa_to_nfa : nfa :=\n  {|\n  nfa_s := dfa_s A;\n  nfa_fin := dfa_fin A;\n  nfa_trans x b y := y == dfa_trans x b\n  |}.\n\nLemma dfa_to_nfa_correct : dfa_lang A =i nfa_lang dfa_to_nfa.\nProof.\n  move => w. rewrite /dfa_lang /nfa_lang /=. move: (dfa_s A) => x.\n  elim: w x => [|b w IHw] x //=.\n  rewrite dfa_accept_cons IHw !inE /=. apply/idP/existsP.\n    move => H0. exists (dfa_trans x b). by rewrite eq_refl.\n  by move => [] y /andP [] /eqP ->.\nQed.\n\nEnd Embed.\n\n\n(** sample NFA *)\n\nDefinition nfa_char (a : char) : nfa :=\n  {|\n    nfa_state := bool_finType;\n    nfa_s := false;\n    nfa_fin := id;\n    nfa_trans x b y := [&& (b == a),  ~~ x & y]\n  |}.\nPrint nfa_char.\n\nLemma nfa_char_correct (a : char) : nfa_lang (nfa_char a) =1 pred1 [:: a].\nProof.\n move => [|b w] => //.\n apply/existsP/eqP => [[x] /andP [/and3P [/eqP -> _ Hx]] |[-> ->]].\n - case: w => //= c w /existsP [y] /=. by rewrite Hx andbF.\n - exists true. by rewrite /= eqxx.\nQed.\n\n\n(** sample NFA を DFA に変換する。 *)\n\nDefinition dfa_char' (a : char) : dfa := nfa_to_dfa (nfa_char a).\n\n(** 変換した DFA と等価なDFAと、その証明。 *)\n\nDefinition dfa_char (a : char) : dfa :=\n  {|\n    dfa_state := set_of_finType bool_finType; (* 省いてもよい。 *)\n    dfa_s := [set false];\n    dfa_fin X := [exists x, (x \\in X) && x];\n    dfa_trans X b :=\n      \\bigcup_(x | x \\in X) [set y | nfa_trans (nfa_char a) x b y]\n  |}.\n\nGoal dfa_char' =1 dfa_char.\nProof.\n  move=> a.\n  rewrite /dfa_char' /nfa_to_dfa /dfa_char.\n    by f_equal.\nQed.\n\n(**\nNOTE:\nset_of_finType bool_finType とはなにか？\n\n復習：\n(1) bool_finType は finType のカノニカルなサブタイプである。\n *)\nCheck bool_finType : finType.\n\n(**\n(2) コアーション [Finite.sort] : Finite.type >-> Sortclass\nによって、bool_finType は bool 型に埋め込むことができる。\n *)\n(* Set Printing Coercions. *)\nCheck true : bool_finType.\nCheck true : Finite.sort bool_finType.\n\n(**\n同様に、\n(1) set_of_finType bool_finType は finType のカノニカルなサブタイプである。\n *)\nCheck set_of_finType bool_finType : finType.\n(**\n(2) コアーションによって {set bool_finType} に埋め込むことができる。\n *)\nCheck [set true] : set_of_finType bool_finType. (* set_of_finType の定義から *)\nCheck [set true] : Finite.Pack (Finite.class (set_finType bool_finType)) {set bool_finType}.\nCheck [set true] : set_finType bool_finType.\nCheck [set true] : {set Finite.sort bool_finType}.\nCheck [set true] : {set bool_finType}.\n\nPrint Graph.\nSet Printing Coercions.\n\n(* 型引数は、finType型 *)\nCheck [set true] : set_of_eqType bool_finType.\nCheck [set true] : set_of_choiceType bool_finType.\nCheck [set true] : set_of_countType bool_finType.\nCheck [set true] : set_of_finType bool_finType.\n\n(* 型引数に制限がある。 *)\nCheck [set true] : {set Equality.sort bool_eqType}.\nCheck [set true] : {set Equality.sort bool_choiceType}.\nCheck [set true] : {set Equality.sort bool_countType}.\nCheck [set true] : {set Equality.sort bool_finType}.\nCheck [set true] : {set bool_eqType}.\n\nFail Check [set true] : {set Choice.sort bool_eqType}.\nCheck [set true] : {set Choice.sort bool_choiceType}.\nCheck [set true] : {set Choice.sort bool_countType}.\nCheck [set true] : {set Choice.sort bool_finType}.\nCheck [set true] : {set bool_choiceType}.\n\nFail Check [set true] : {set Countable.sort bool_eqType}.\nFail Check [set true] : {set Countable.sort bool_choiceType}.\nFail Check [set true] : {set Countable.sort bool_countype}.\nCheck [set true] : {set Countable.sort bool_finType}.\nCheck [set true] : {set bool_countType}.\n\nFail Check [set true] : {set Finite.sort bool_eqType}.\nFail Check [set true] : {set Finite.sort bool_choiceType}.\nFail Check [set true] : {set Finite.sort bool_countType}.\nCheck [set true] : {set Finite.sort bool_finType}.\nCheck [set true] : {set bool_finType}.\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/regexp/ssr_nfa_to_dfa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.6680386908564736}}
{"text": "Require Import POrder POrderSet TerminalDogma.premises\n                                TerminalDogma.Extensionality.\nRequire Import Relations.\nRequire Import SetFacility.\n\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(** Canonical structure *)\n\n(** Enter the 'context' by introducing the canonical structures. *)\nImport SubsetOrder.CanonicalStruct.\n\n(** The single item [𝒫(nat)] has coercions to many notions related. *)\nCheck 𝒫(nat).\nCheck 𝒫(nat) : poset.\nCheck 𝒫(nat) : clattice.\nCheck 𝒫(nat) : cpo.\n\nAxiom A : chain (𝒫(nat)).\nCheck (⊔ᶜᵖᵒ A).\n\n(** the type of monotonic functions between [𝒫(nat)] and [𝒫(nat)] *)\nCheck [ 𝒫(nat) ↦ᵐ 𝒫(nat) ].\n\n\n(** The system 'knows' that if we apply monotonic functions to a chain, we get\n    a chain. *)\nAxiom (f : 𝒫(nat) -> 𝒫(nat)) (monof : [ 𝒫(nat) ↦ᵐ 𝒫(nat) ]).\n\nCheck f [<] A : 𝒫( _ ).\nFail Check f [<] A : chain _. \n\nCheck monof [<] A : 𝒫( _ ).\nCheck monof [<] A : chain _.\n\n\n(** nonempty set *)\nCheck 𝒫(nat)₊.\nCheck union : 𝒫(nat) ->  𝒫(nat)-> 𝒫(nat).\n(** Because of canonical structure, [union] 'remembers' its property about \n    nonempty sets. *)\nCheck union : 𝒫(nat)₊ -> 𝒫(nat) -> 𝒫(nat)₊.\n\n\n\n(** Function lifting *)\nSection FunctionLifting.\n\nVariable (T V W: Type) (f : T -> V) (g : T -> V -> W).\n\n(** function lifting of single-variable functions *)\nCheck f : T -> V.\nCheck f[<] : 𝒫(T) -> 𝒫(V).\n\n(** function lifting of multi-variable functions *)\nCheck g                             : T -> V -> W.\nCheck g[<]                          : 𝒫(T) -> 𝒫(V -> W).\nCheck (fun a => g[<]a[>])           : 𝒫(T) -> V -> 𝒫(W).\nCheck (fun a => g[<]a[>][<])        : 𝒫(T) -> 𝒫(V) -> 𝒫(𝒫(W)).\nCheck (fun a b => ⋃(g[<]a[>][<]b))  : 𝒫(T) -> 𝒫(V) -> 𝒫(W).\n\nDefinition g_lifted := (fun a b => ⋃(g[<]a[>][<]b)).\n\n\n\nLemma continuity_f_lifted A : f[<](⋃ A) = ⋃ (f[<][<]A).\nProof. \n    equal_f_comp A.\n    rewrite mapR_bigU_swapF. by [].\n\n    Restart.\n    seteq_killer. \nQed.\n\nLemma continuity_g_lifted A B : g_lifted (⋃ A) (⋃ B) = ⋃ (g_lifted [<] A [><] B).\nProof. \n    rewrite /g_lifted.\n\n    Restart.\n    seteq_killer. \nQed.\n\nEnd FunctionLifting.\n\n\n(** seteq_killer demo *)\n\nLemma Example1 {X Y: Type} (f : X -> 𝒫(𝒫(Y))):\n\n    ⋃ ◦ (⋃ ◦ f)[<] = ⋃ ◦ ⋃ ◦ f[<].\n\nProof.\n    apply functional_extensionality => A.\n    seteq_killer.\n\n    Undo.\n    apply seteqP => x; split.\n    set_simpl.\n    set_move_up.\n    set_move_down.\n    set_simpl.\n    set_move_up.\n    set_move_down.\nQed.\n\nLemma Example2 {X : Type} (A B: 𝒫(𝒫(X))) :\n    \n        ⋃ (A ∪ B) = (⋃ A) ∪ (⋃ B).\n\nProof. \n    seteq_killer.\nQed.\n\n\n(** WARNING: this is not correct. *)\nLemma Example3 {X : Type} (A B: 𝒫(𝒫(X))) :\n    \n        ⋂ (A ∩ B) = (⋂ A) ∩ (⋂ B).\n\nProof. \n    seteq_killer. \nAbort.\n\nLemma Example4 {X Y: Type} (F : 𝒫(X -> Y)) (A : 𝒫(𝒫(X))) :\n\n    ⋃(F [>][<] (⋃ A)) = ⋃ (⋃ (F[>][<][<] A)).\n\nProof.\n    seteq_killer.\nQed.\n\n(** 2023/2/6 \n    git commit: 48aac14771ce40140937bc45fc2f1aeb8123284e *)", "meta": {"author": "LucianoXu", "repo": "Project-Babel", "sha": "92a749468a5ab3f3acb5e0bcbf29800df90be651", "save_path": "github-repos/coq/LucianoXu-Project-Babel", "path": "github-repos/coq/LucianoXu-Project-Babel/Project-Babel-92a749468a5ab3f3acb5e0bcbf29800df90be651/stories/DEMO20230207.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.667980500708251}}
{"text": "Require Import Arith Omega.\n\nSection bounded_forall.\n\n  Implicit Type (P : nat -> Prop).\n\n  Fixpoint bounded_forall P n :=\n    match n with\n      | 0 => True\n      | S n => P 0 /\\ bounded_forall (fun i => P (S i)) n\n    end.\n\n  Fact bounded_forall_spec P n : bounded_forall P n -> forall i, i < n -> P i.\n  Proof.\n    revert P.\n    induction n as [ | n IHn ]; simpl; intros P Hn i Hi; try omega.\n    destruct i as [ | i ]; try tauto.\n    apply IHn with (P := fun i => P (S i)); try tauto.\n    omega.\n  Qed.\n\nEnd bounded_forall. \n\nLemma can_be_brute_forced : forall (n : nat), n < 10 -> n mod 10 = (n ^ 5) mod 10.\nProof.\n  now apply bounded_forall_spec.\nQed.\n", "meta": {"author": "mukeshtiwari", "repo": "CoqUtility", "sha": "3a25343d0a77177adb7530a08b0c7854bb1ed02f", "save_path": "github-repos/coq/mukeshtiwari-CoqUtility", "path": "github-repos/coq/mukeshtiwari-CoqUtility/CoqUtility-3a25343d0a77177adb7530a08b0c7854bb1ed02f/Bounded.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6679804937093183}}
{"text": "Require Export TopologicalSpaces.\nRequire Import ClassicalChoice.\nRequire Import EnsemblesSpec.\n\nSection OpenBasis.\n\nVariable X : TopologicalSpace.\nVariable B : Family (point_set X).\n\nRecord open_basis : Prop :=\n  { open_basis_elements :\n     forall V:Ensemble (point_set X), In B V -> open V;\n    open_basis_cover :\n     forall (x:point_set X) (U:Ensemble (point_set X)),\n        open U -> In U x -> exists V:Ensemble (point_set X),\n        In B V /\\ Included V U /\\ In V x\n  }.\n\nHypothesis Hbasis: open_basis.\n\nLemma coverable_by_open_basis_impl_open:\n  forall U:Ensemble (point_set X),\n    (forall x:point_set X, In U x -> exists V:Ensemble (point_set X),\n     In B V /\\ Included V U /\\ In V x) -> open U.\nProof.\nintros.\nassert (U = FamilyUnion [ V:Ensemble (point_set X) |\n                          In B V /\\ Included V U ]).\napply Extensionality_Ensembles; split; red; intros.\ndestruct (H x H0) as [V].\ndestruct H1 as [? [? ?]].\nexists V; auto.\nconstructor; auto.\ndestruct H0.\ndestruct H0.\ndestruct H0.\nauto with sets.\n\nrewrite H0.\napply open_family_union.\nintros.\ndestruct H1.\ndestruct H1.\napply open_basis_elements; trivial.\nQed.\n\nEnd OpenBasis.\n\nImplicit Arguments open_basis [[X]].\nImplicit Arguments coverable_by_open_basis_impl_open [[X]].\nImplicit Arguments open_basis_elements [[X]].\nImplicit Arguments open_basis_cover [[X]].\n\nSection BuildFromOpenBasis.\n\nVariable X : Type.\nVariable B : Family X.\n\nDefinition open_basis_cond :=\n  forall U V:Ensemble X, In B U -> In B V ->\n    forall x:X, In (Intersection U V) x ->\n      exists W:Ensemble X, In B W /\\ In W x /\\\n                           Included W (Intersection U V).\nDefinition open_basis_cover_cond :=\n  forall x:X, exists U:Ensemble X, In B U /\\ In U x.\n\nHypothesis Hbasis : open_basis_cond.\nHypothesis Hbasis_cover: open_basis_cover_cond.\n\nInductive B_open : Ensemble X -> Prop :=\n  | B_open_intro: forall F:Family X, Included F B ->\n    B_open (FamilyUnion F).\n\nDefinition Build_TopologicalSpace_from_open_basis : TopologicalSpace.\nrefine (Build_TopologicalSpace X B_open _ _ _).\nintros.\npose proof (choice (fun (x:{S:Ensemble X | In F S}) (F:Family X) =>\n  Included F B /\\ proj1_sig x = FamilyUnion F)).\nrefine (let H:=(H0 _) in _).\nintros.\ndestruct x.\npose proof (H x i).\ndestruct H1.\nexists F0.\nsplit; simpl; trivial.\nclear H0.\ndestruct H1.\nassert (FamilyUnion F = FamilyUnion (IndexedUnion x)).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H1.\npose proof (H0 (exist _ _ H1)).\ndestruct H3.\nsimpl in H4.\nrewrite H4 in H2.\ndestruct H2.\nconstructor 1 with S0.\nexists (exist _ _ H1).\nassumption.\nassumption.\n\ndestruct H1.\ndestruct H1.\npose proof (H0 a).\ndestruct H3.\ndestruct a.\nsimpl in H4.\nexists x2.\nassumption.\nrewrite H4.\nexists x1.\nassumption.\nassumption.\n\nrewrite H1.\nconstructor.\nred; intros.\ndestruct H2.\npose proof (H0 a).\ndestruct H3.\nauto with sets.\n\nintros.\nassert (Intersection U V = FamilyUnion\n  [ S:Ensemble X | In B S /\\ Included S (Intersection U V) ]).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H.\ndestruct H0.\ndestruct H1.\ndestruct H1.\ndestruct H2.\npose proof (H _ H1).\npose proof (H0 _ H2).\npose proof (Hbasis _ _ H5 H6).\nassert (In (Intersection S S0) x). constructor; trivial.\napply H7 in H8.\nclear H7.\ndestruct H8.\ndestruct H7 as [? [? ?]].\nexists x0; trivial.\nconstructor.\nsplit; trivial.\nred; intros.\nconstructor.\nexists S; trivial.\npose proof (H9 x1 H10).\ndestruct H11; trivial.\nexists S0; trivial.\npose proof (H9 x1 H10).\ndestruct H11; trivial.\ndestruct H1.\ndestruct H1.\ndestruct H1.\nauto.\n\nrewrite H1.\nconstructor.\nred; intros.\ndestruct H2.\ndestruct H2.\nauto.\n\nassert (Full_set = FamilyUnion B).\napply Extensionality_Ensembles; split; red; intros.\npose proof (Hbasis_cover x).\ndestruct H0.\ndestruct H0.\nexists x0; trivial.\nconstructor.\n\nrewrite H; constructor.\nauto with sets.\nDefined.\n\nLemma Build_TopologicalSpace_from_open_basis_point_set:\n  point_set Build_TopologicalSpace_from_open_basis = X.\nProof.\nreflexivity.\nQed.\n\nLemma Build_TopologicalSpace_from_open_basis_basis:\n  @open_basis Build_TopologicalSpace_from_open_basis B.\nProof.\nconstructor.\nintros.\nsimpl.\nassert (V = FamilyUnion (Singleton V)).\napply Extensionality_Ensembles; split; red; intros.\nexists V; auto with sets.\ndestruct H0.\ndestruct H0; trivial.\nrewrite H0; constructor.\nred; intros.\ndestruct H1; trivial.\nsimpl.\nintros.\ndestruct H.\ndestruct H0.\nexists S; repeat split; auto with sets.\nred; intros.\nexists S; trivial.\nQed.\n\nEnd BuildFromOpenBasis.\n\nImplicit Arguments open_basis_cond [[X]].\nImplicit Arguments open_basis_cover_cond [[X]].\nImplicit Arguments Build_TopologicalSpace_from_open_basis [[X]].\nImplicit Arguments Build_TopologicalSpace_from_open_basis_point_set [[X]].\nImplicit Arguments Build_TopologicalSpace_from_open_basis_basis [[X]].\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/OpenBases.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6679804937093183}}
{"text": "Require Import BenB.\n\nVariable X: R -> Prop.\nVariable Y: R -> Prop.\nVariable Z: R -> Prop.\n\nTheorem getallen_006 :\n  (forall t:R, X t -> Y (t+2))\n->\n    (forall t:R, Y t -> Z (t+3))\n  ->\n    (forall t:R, X t -> Z (t+5)).\nProof.\nimp_i a1.\nimp_i a2.\nall_i a.\nimp_i a3.\nimp_e (Y (a+2)).\nreplace (a+5) with (a+2+3).\nall_e (forall t:R, Y t -> Z (t+3)) (a+2).\nhyp a2.\nlin_solve.\nimp_e (X a).\nall_e (forall t:R, X t -> Y (t + 2)) 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/Taak12/Taak12_real006.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6679510643682153}}
{"text": "Require Import HoTT.\n\n(** We introduce the notion of connected pointed types, which we will use as a tool later.  *)\nDefinition isconn (X : pType) := forall (x : X), merely (point X = x).\nRecord Conn_pType := {ptype_conn_ptype :> pType ; isconn_conn_ptype : isconn ptype_conn_ptype}.\n\nDefinition ptype_prod (X Y : pType) : pType\n  := Build_pType (X * Y) (point _, point _).\n\n\nDefinition conn_ptype_prod (X Y : Conn_pType) : Conn_pType.\nProof.\n  apply (Build_Conn_pType (ptype_prod X Y)).\n  unfold isconn.\n  intros [x y].\n  generalize (isconn_conn_ptype X x). intro p.\n  generalize (isconn_conn_ptype Y y). intro q.\n  strip_truncations. apply tr. exact (path_prod (_,_) (_,_) p q).\nDefined.\n", "meta": {"author": "kalfsvag", "repo": "group_completions", "sha": "cc65e902a68dbb6dc05315651dce3064704a9815", "save_path": "github-repos/coq/kalfsvag-group_completions", "path": "github-repos/coq/kalfsvag-group_completions/group_completions-cc65e902a68dbb6dc05315651dce3064704a9815/conn_ptype.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6678906554028442}}
{"text": "Require Import init.\n\nRequire Export module_category.\nRequire Import set.\n\n(** These are unital associative algebras.  I'm just calling it \"AlgebraObj\"\nbecause unital associative algebras are all I care about for the moment.  I can\nchange names later if I need to.\n*)\nRecord AlgebraObj (F : CRingObj) := make_algebra {\n    algebra_module : ModuleObj F;\n    algebra_mult : Mult (module_V algebra_module);\n    algebra_ldist : @Ldist (module_V algebra_module) (module_plus algebra_module) algebra_mult;\n    algebra_rdist : @Rdist (module_V algebra_module) (module_plus algebra_module) algebra_mult;\n    algebra_mult_assoc : @MultAssoc (module_V algebra_module) algebra_mult;\n    algebra_one : One (module_V algebra_module);\n    algebra_mult_lid : @MultLid (module_V algebra_module) algebra_mult algebra_one;\n    algebra_mult_rid : @MultRid (module_V algebra_module) algebra_mult algebra_one;\n    algebra_scalar_lmult : @ScalarLMult (cring_U F) (module_V algebra_module) algebra_mult (module_scalar algebra_module);\n    algebra_scalar_rmult : @ScalarRMult (cring_U F) (module_V algebra_module) algebra_mult (module_scalar algebra_module);\n}.\nArguments algebra_module {F}.\nArguments algebra_mult {F}.\nArguments algebra_ldist {F}.\nArguments algebra_rdist {F}.\nArguments algebra_mult_assoc {F}.\nArguments algebra_one {F}.\nArguments algebra_mult_lid {F}.\nArguments algebra_mult_rid {F}.\nArguments algebra_scalar_lmult {F}.\nArguments algebra_scalar_rmult {F}.\nDefinition algebra_V {F} (A : AlgebraObj F) := module_V (algebra_module A).\nDefinition algebra_plus {F} (A : AlgebraObj F) := module_plus (algebra_module A).\nDefinition algebra_zero {F} (A : AlgebraObj F) := module_zero (algebra_module A).\nDefinition algebra_neg {F} (A : AlgebraObj F) := module_neg (algebra_module A).\nDefinition algebra_plus_assoc {F} (A : AlgebraObj F) := module_plus_assoc (algebra_module A).\nDefinition algebra_plus_comm {F} (A : AlgebraObj F) := module_plus_comm (algebra_module A).\nDefinition algebra_plus_lid {F} (A : AlgebraObj F) := module_plus_lid (algebra_module A).\nDefinition algebra_plus_linv {F} (A : AlgebraObj F) := module_plus_linv (algebra_module A).\nDefinition algebra_scalar {F} (A : AlgebraObj F) := module_scalar (algebra_module A).\nDefinition algebra_scalar_id {F} (A : AlgebraObj F) := module_scalar_id (algebra_module A).\nDefinition algebra_scalar_ldist {F} (A : AlgebraObj F) := module_scalar_ldist (algebra_module A).\nDefinition algebra_scalar_rdist {F} (A : AlgebraObj F) := module_scalar_rdist (algebra_module A).\nDefinition algebra_scalar_comp {F} (A : AlgebraObj F) := module_scalar_comp (algebra_module A).\n\nGlobal Existing Instances algebra_mult algebra_ldist algebra_rdist\n    algebra_mult_assoc algebra_one algebra_mult_lid algebra_mult_rid\n    algebra_scalar_lmult algebra_scalar_rmult algebra_plus algebra_zero\n    algebra_neg algebra_plus_assoc algebra_plus_comm algebra_plus_lid\n    algebra_plus_linv algebra_scalar algebra_scalar_id algebra_scalar_ldist\n    algebra_scalar_rdist algebra_scalar_comp.\n\nRecord AlgebraObjHomomorphism {R : CRingObj} (A B : AlgebraObj R) := make_algebra_homomorphism {\n    algebra_homo_f :> algebra_V A → algebra_V B;\n    algebra_homo_plus : ∀ u v,\n        algebra_homo_f (u + v) = algebra_homo_f u + algebra_homo_f v;\n    algebra_homo_scalar : ∀ a v,\n        algebra_homo_f (a · v) = a · algebra_homo_f v;\n    algebra_homo_mult : ∀ u v,\n        algebra_homo_f (u * v) = algebra_homo_f u * algebra_homo_f v;\n    algebra_homo_one : algebra_homo_f 1 = 1\n}.\nArguments algebra_homo_f {R A B}.\n\nDefinition algebra_to_module_homomorphism {R : CRingObj} {A B : AlgebraObj R}\n    (f : AlgebraObjHomomorphism A B) :=\n    make_module_homomorphism R (algebra_module A) (algebra_module B)\n    f\n    (algebra_homo_plus _ _ f)\n    (algebra_homo_scalar _ _ f).\n\nTheorem algebra_to_module_homo_eq {R : CRingObj} {A B : AlgebraObj R}\n    (f : AlgebraObjHomomorphism A B) :\n    ∀ x, f x =\n    (algebra_to_module_homomorphism f) x.\nProof.\n    reflexivity.\nQed.\n\nTheorem algebra_homo_zero {R : CRingObj} {M N : AlgebraObj R} :\n    ∀ f : AlgebraObjHomomorphism M N,\n    f 0 = 0.\nProof.\n    intros f.\n    rewrite algebra_to_module_homo_eq.\n    apply module_homo_zero.\nQed.\n\nTheorem algebra_homo_neg {R : CRingObj} {M N : AlgebraObj R} :\n    ∀ f : AlgebraObjHomomorphism M N,\n    ∀ v, f (-v) = -f v.\nProof.\n    intros f v.\n    rewrite algebra_to_module_homo_eq.\n    apply module_homo_neg.\nQed.\n\nTheorem algebra_homomorphism_eq {R : CRingObj} {M N : AlgebraObj R} :\n    ∀ f g : AlgebraObjHomomorphism M N,\n    (∀ x, f x = g x) → f = g.\nProof.\n    intros [f1 plus1 scalar1 mult1 one1] [f2 plus2 scalar2 mult2 one2] f_eq.\n    cbn in *.\n    assert (f1 = f2) as eq.\n    {\n        apply functional_ext.\n        apply f_eq.\n    }\n    subst f2.\n    rewrite (proof_irrelevance plus2 plus1).\n    rewrite (proof_irrelevance scalar2 scalar1).\n    rewrite (proof_irrelevance mult2 mult1).\n    rewrite (proof_irrelevance one2 one1).\n    reflexivity.\nQed.\n\nDefinition algebra_homo_id {R : CRingObj} (A : AlgebraObj R)\n    : AlgebraObjHomomorphism A A := make_algebra_homomorphism R A A\n        (λ x, x)\n        (λ u v, Logic.eq_refl _)\n        (λ a v, Logic.eq_refl _)\n        (λ u v, Logic.eq_refl _)\n        (Logic.eq_refl _).\n\nLemma algebra_homo_compose_plus : ∀ {R : CRingObj} {L M N : AlgebraObj R}\n    {f : AlgebraObjHomomorphism M N} {g : AlgebraObjHomomorphism L M},\n    ∀ a b, f (g (a + b)) = f (g a) + f (g b).\nProof.\n    intros R L M N f g a b.\n    rewrite algebra_homo_plus.\n    apply algebra_homo_plus.\nQed.\nLemma algebra_homo_compose_scalar : ∀ {R : CRingObj} {L M N : AlgebraObj R}\n    {f : AlgebraObjHomomorphism M N} {g : AlgebraObjHomomorphism L M},\n    ∀ a v, f (g (a · v)) = a · f (g v).\nProof.\n    intros R L M N f g a v.\n    rewrite algebra_homo_scalar.\n    apply algebra_homo_scalar.\nQed.\nLemma algebra_homo_compose_mult : ∀ {R : CRingObj} {L M N : AlgebraObj R}\n    {f : AlgebraObjHomomorphism M N} {g : AlgebraObjHomomorphism L M},\n    ∀ a b, f (g (a * b)) = f (g a) * f (g b).\nProof.\n    intros R L M N f g a b.\n    rewrite algebra_homo_mult.\n    apply algebra_homo_mult.\nQed.\nLemma algebra_homo_compose_one : ∀ {R : CRingObj} {L M N : AlgebraObj R}\n    {f : AlgebraObjHomomorphism M N} {g : AlgebraObjHomomorphism L M},\n    f (g 1) = 1.\nProof.\n    intros R L M N f g.\n    rewrite algebra_homo_one.\n    apply algebra_homo_one.\nQed.\nDefinition algebra_homo_compose {R : CRingObj} {L M N : AlgebraObj R}\n    (f : AlgebraObjHomomorphism M N) (g : AlgebraObjHomomorphism L M)\n    : AlgebraObjHomomorphism L N := make_algebra_homomorphism R L N\n        (λ x, f (g x))\n        algebra_homo_compose_plus algebra_homo_compose_scalar\n        algebra_homo_compose_mult algebra_homo_compose_one.\n\n(* begin show *)\nGlobal Program Instance ALGEBRA (R : CRingObj) : Category := {\n    cat_U := AlgebraObj R;\n    cat_morphism M N := AlgebraObjHomomorphism M N;\n    cat_compose {L M N} f g := algebra_homo_compose f g;\n    cat_id M := algebra_homo_id M;\n}.\n(* end show *)\nNext Obligation.\n    apply algebra_homomorphism_eq.\n    intros x.\n    cbn.\n    reflexivity.\nQed.\nNext Obligation.\n    apply algebra_homomorphism_eq.\n    intros x.\n    cbn.\n    reflexivity.\nQed.\nNext Obligation.\n    apply algebra_homomorphism_eq.\n    intros x.\n    cbn.\n    reflexivity.\nQed.\n\nTheorem algebra_to_module_iso {R : CRingObj} {A B : AlgebraObj R} :\n    ∀ f : cat_morphism (ALGEBRA R) A B, isomorphism f →\n    isomorphism (C0 := MODULE R)(algebra_to_module_homomorphism f).\nProof.\n    intros f [g [fg gf]].\n    exists (algebra_to_module_homomorphism g).\n    split.\n    -   apply module_homomorphism_eq.\n        intros x; cbn.\n        inversion fg as [eq].\n        apply (func_eq _ _ eq).\n    -   apply module_homomorphism_eq.\n        intros x; cbn.\n        inversion gf as [eq].\n        apply (func_eq _ _ 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/Algebra/Linear/algebra_category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6678577846333844}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Nat Lia Relations Bool.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac utils_list utils_nat finite.\n\nFrom Undecidability.Shared.Libs.DLW.Vec \n  Require Import pos vec.\n\nFrom Undecidability.FOL.TRAKHTENBROT\n  Require Import notations decidable gfp fol_ops fo_sig fo_terms fo_logic fo_definable fo_sat.\n\nImport fol_notations.\n\nSet Implicit Arguments.\n\nLocal Notation \" e '#>' x \" := (vec_pos e x).\nLocal Notation \" e [ v / x ] \" := (vec_change e x v).\n\n(* ∈ and ⊆ are already used for object level syntax at too low level 59 *)\n\nLocal Infix \"∊\" := In (at level 70, no associativity).\nLocal Infix \"⊑\" := incl (at level 70, no associativity). \n\nLocal Notation \"M , r ⊨ A\" := (fol_sem M r A) (at level 70, format \"M , r  ⊨  A\").\n\nLocal Notation \"f ∘ g\" := (fun x => f (g x)) (at level 55, left associativity).\n\nSection discrete_quotient.\n\n  (* We show the FO bisimilarity/indistinguishability ≡ is both\n      decidable and first order definable, ie there is a FO formula\n      A(.,.) such that\n \n            x ≡ y <-> A(x,y) holds for any x,y in the model M\n\n      We use it to quotient the model M and get a discrete model \n      (based on the finite type pos n) where identity coincides\n      with FO bisimilarity.\n\n      The idea of the construction is the following. We\n      start from a finitary signature Σ to simplify the\n      explanation but the devel below works in a sub-signature \n      of Σ where the list ls bounds usable terms symbols and \n      the list lr usable bound relations symbols.\n\n      So given a finitary Σ and a finite and Boolean model M\n      for Σ, we define the operator \n\n                 F : (M² -> Prop) -> (M² -> Prop) \n\n      transforming a binary relation R : M² -> Prop into F(R).\n\n         x F(R) y iff      t(x)  R  t(y) for any t(.) = s<v(./p)>\n                       and f(x) <-> f(y) for any f(.) = r<v(./p)>\n\n      Then F(.) is monotonic, ω-continuous, and satisfies\n      I ⊆ F(I), (F(R))⁻ ⊆ F(R⁻) and F(R) o F(R) ⊆ F (R o R)\n      hence Kleene's greatest fixpoint gfp(F) exists, is\n      obtained after ω-steps and is an equivalence relation.\n\n      Moreover, F preserves decidability and FO-definability.\n      Now we show that gfp(F) ~ F^n(TT) for a finite n\n      which implies that gfp(F) is decidable and FO-definable.\n      Here TT := fun _ _ => True is the full binary relation\n      over M.\n\n      The sequence n => F^n(TT) is a sequence of decidable\n      (hence also weakly decidable) relations. If \n      F^a(TT) ⊆ F^b(TT) for a < b then we have F^a(TT) ~ F^i(TT)\n      for any i => a and thus for any i >= a F^i(TT) ~ gfp F.\n\n      The sequence n => F^n(TT) belongs to the weak power list \n      of binary relations over M (upto equivalence) which contains\n      all weakly decidable binary relations over M. By the PHP,\n      for n greater that the length of this list (which is\n      2^(m*m) where m is the cardinal of M), we must have\n      F^a(TT) ~ F^b(TT) for a <> b, hence we deduce\n      F^n(TT) ~ gfp F.\n\n      Hence, gfp F is decidable and FO-definable as well.\n  \n  *)  \n \n  Variables (Σ : fo_signature) (ls : list (syms Σ)) (lr : list (rels Σ)).\n\n  (* fo_bisimilar means no FO formula can distinguish x from y. Beware that\n      two free variables might be needed, see the remarks and counter-example \n      below *)\n\n  Definition fo_bisimilar X (M : fo_model Σ X) x y := \n         forall φ, fol_syms φ ⊑ ls -> fol_rels φ ⊑ lr\n                -> forall ρ, M,x·ρ ⊨ φ <-> M,y·ρ ⊨ φ.\n\n  (* Let us assume a finite and Boolean model m *)\n\n  Variables (X : Type) \n            (fin : finite_t X) \n            (M : fo_model Σ X) \n            (dec : fo_model_dec M).\n\n  Infix \"≐\" := (fo_bisimilar M) (at level 70).\n\n  Fact fo_bisimilar_refl x : x ≐ x.\n  Proof. intro; tauto. Qed.\n\n  Fact fo_bisimilar_sym x y : x ≐ y -> y ≐ x.\n  Proof. unfold fo_bisimilar; intros H ? ? ? ?; rewrite H; auto; tauto. Qed.\n\n  Fact fo_bisimilar_trans x y z : x ≐ y -> y ≐ z -> x ≐ z.\n  Proof. unfold fo_bisimilar; intros H ? ? ? ? ?; rewrite H; auto. Qed.\n\n  Implicit Type (R T : X -> X -> Prop).\n\n  (* Construction of the greatest fixpoint of the following operator fom_op.\n      Any prefixpoint R ⊆ fom_op R is a simulation for the model *)\n\n  Local Definition fom_op1 R x y := \n          forall s, s ∊ ls \n       -> forall (v : vec _ (ar_syms Σ s)) i, \n                 R (fom_syms M s (v[x/i])) (fom_syms M s (v[y/i])).\n\n  Local Definition fom_op2 x y := \n          forall s, s ∊ lr \n       -> forall (v : vec _ (ar_rels Σ s)) i, \n                 fom_rels M s (v[x/i]) <-> fom_rels M s (v[y/i]).\n\n  Local Definition fom_op R x y := fom_op1 R x y /\\ fom_op2 x y.\n  \n  (* First we show properties of fom_op \n\n      a) Monotonicity\n      b) preserves Reflexivity, Symmetry and Transitivity\n      c) ω-continuous\n      d) preserves decidability\n      e) preserves FO definability\n\n  *)\n\n  Hint Resolve finite_t_pos finite_t_vec : core.\n\n  (* Monotonicity *)\n \n  Local Fact fom_op_mono R T : (forall x y, R x y -> T x y) -> (forall x y, fom_op R x y -> fom_op T x y).\n  Proof. unfold fom_op, fom_op1, fom_op2; intros ? ? ? []; split; intros; auto. Qed.\n\n  (* Reflexivity, symmetry & transitivity *) \n\n  Local Fact fom_op_id x y : x = y -> fom_op (@eq _) x y.\n  Proof. unfold fom_op, fom_op1, fom_op2; intros []; split; auto; tauto. Qed.\n\n  Local Fact fom_op_sym R x y : fom_op R y x -> fom_op (fun x y => R y x) x y.\n  Proof. unfold fom_op, fom_op1, fom_op2; intros []; split; intros; auto; symmetry; auto. Qed.\n\n  Local Fact fom_op_trans R x z : (exists y, fom_op R x y /\\ fom_op R y z)\n                        -> fom_op (fun x z => exists y, R x y /\\ R y z) x z.\n  Proof.\n    unfold fom_op, fom_op1, fom_op2.\n    intros (y & H1 & H2); split; intros s Hs v p.\n    + exists (fom_syms M s (v[y/p])); split; [ apply H1 | apply H2 ]; auto.\n    + transitivity (fom_rels M s (v[y/p])); [ apply H1 | apply H2 ]; auto.\n  Qed.\n\n  (* ω-continuity *)\n\n  Local Fact fom_op_continuous : gfp_continuous fom_op.\n  Proof.\n    intros f Hf x y H; split; intros s Hs v p.\n    + intros n.\n      generalize (H n); intros (H1 & H2).\n      apply H1; auto.\n    + apply (H 0); auto.\n  Qed.\n\n  Section fom_op_dec.\n\n    (* fom_op is closed under strong decidability, \n       a bit more complicated but we have all \n       the tools to do it the easy way *)\n\n    Let fom_op1_dec R : \n          (forall x y, { R x y } + { ~ R x y })\n       -> (forall x y, { fom_op1 R x y } + { ~ fom_op1 R x y }).\n    Proof.\n      unfold fom_op1.\n      intros HR x y.\n      apply forall_list_sem_dec; intros.\n      do 2 (apply (fol_quant_sem_dec fol_fa); auto; intros).\n    Qed.\n\n    Let fom_op2_dec x y : { fom_op2 x y } + { ~ fom_op2 x y }.\n    Proof.\n      unfold fom_op2.\n      apply forall_list_sem_dec; intros.\n      do 2 (apply (fol_quant_sem_dec fol_fa); auto; intros).\n      apply (fol_bin_sem_dec fol_conj); \n        apply (fol_bin_sem_dec fol_imp); auto.\n    Qed.\n\n    Local Fact fom_op_dec R : \n            (forall x y, { R x y } + { ~ R x y })\n         -> (forall x y, { fom_op R x y } + { ~ fom_op R x y }).\n    Proof using fin dec. intros; apply (fol_bin_sem_dec fol_conj); auto. Qed.\n\n  End fom_op_dec.\n\n  Section fo_definability.\n\n    (* fom_op is closed under FO definability, \n       more complicated but we have all the\n       needed closure properties *)\n\n    Tactic Notation \"solve\" \"with\" \"proj\" constr(t) :=\n      apply fot_def_equiv with (f := fun φ => φ t); fol def; intros; rew vec.\n\n    Let fol_def_fom_op1 R : \n           fol_definable ls lr M (fun ψ => R (ψ 0) (ψ 1))\n        -> fol_definable ls lr M (fun ψ => fom_op1 R (ψ 0) (ψ 1)).\n    Proof.\n      intros H.\n      apply fol_def_list_fa; intros s Hs.\n      apply fol_def_vec_fa.\n      apply fol_def_finite_fa; auto; intro p.\n      apply fol_def_subst2; auto.\n      * apply fot_def_comp; auto; intro q.\n        destruct (pos_eq_dec p q); subst.\n        - solve with proj (ar_syms Σ s).\n        - solve with proj (pos2nat q).\n      * apply fot_def_comp; auto; intro q.\n        destruct (pos_eq_dec p q); subst.\n        - solve with proj (ar_syms Σ s+1).\n        - solve with proj (pos2nat q).\n    Qed.\n\n    Let fol_def_fom_op2 : \n           fol_definable ls lr M (fun ψ => fom_op2 (ψ 0) (ψ 1)).\n    Proof.\n      apply fol_def_list_fa; intros r Hr.\n      apply fol_def_vec_fa.\n      apply fol_def_finite_fa; auto; intro p.\n      apply fol_def_iff.\n      * apply fol_def_atom; auto; intro q.\n        destruct (pos_eq_dec p q); subst.\n        - solve with proj (ar_rels Σ r).\n        - solve with proj (pos2nat q).\n      * apply fol_def_atom; auto; intro q.\n        destruct (pos_eq_dec p q); subst.\n        - solve with proj (ar_rels Σ r+1).\n        - solve with proj (pos2nat q).\n    Qed.\n\n    Local Fact fol_def_fom_op R : \n            fol_definable ls lr M (fun ψ => R (ψ 0) (ψ 1))\n         -> fol_definable ls lr M (fun ψ => fom_op R (ψ 0) (ψ 1)).\n    Proof. intro; apply fol_def_conj; auto. Qed.\n\n    Hint Resolve fol_def_fom_op : core. \n\n    Local Fact fol_def_iter_fom_op R n :\n            fol_definable ls lr M (fun ψ => R (ψ 0) (ψ 1))\n         -> fol_definable ls lr M (fun ψ => iter fom_op R n (ψ 0) (ψ 1)).\n    Proof. revert R; induction n; simpl; auto. Qed.\n\n  End fo_definability.\n\n  (* Now we build the greatest fixpoint fom_eq and show its properties\n\n      a) it is an equivalence relation\n      b) it is a congruence wrt to the model functions and relations\n      c) it is decidable and FO definable\n\n      the reason is that it is obtained after finitely many iterations of fom_op\n\n    *)\n\n  (* We build the greatest bisimulation which is an equivalence \n      and a (pre-)fixpoint for the above operator *) \n\n  Definition fom_eq := gfp fom_op.\n\n  Infix \"≡\" := fom_eq (at level 70, no associativity).\n\n  Hint Resolve fom_op_mono fom_op_id fom_op_sym fom_op_trans \n               fom_op_continuous fom_op_dec : core.\n\n  Local Fact fom_eq_equiv : equiv _ fom_eq.\n  Proof. apply gfp_equiv; eauto. Qed.\n\n  Local Fact fom_eq_refl x : x ≡ x.                         Proof. apply (proj1 fom_eq_equiv). Qed.\n  Local Fact fom_eq_sym x y : x ≡ y -> y ≡ x.               Proof. apply fom_eq_equiv. Qed.\n  Local Fact fom_eq_trans x y z : x ≡ y -> y ≡ z -> x ≡ z.  Proof. apply fom_eq_equiv. Qed.\n\n  Local Fact fom_eq_fix x y : fom_op fom_eq x y <-> x ≡ y.\n  Proof. apply gfp_fix; eauto. Qed.\n\n  Local Fact fom_eq_incl R : \n           (forall x y, R x y -> fom_op R x y)\n        -> (forall x y, R x y -> x ≡ y).\n  Proof. apply gfp_greatest; eauto. Qed.\n\n  (* It is a congruence wrt to the model *)\n\n  Local Fact fom_eq_syms x y s v p : \n          s ∊ ls -> x ≡ y -> fom_syms M s (v[x/p]) ≡ fom_syms M s (v[y/p]).\n  Proof. intros; apply fom_eq_fix; auto. Qed. \n    \n  Local Fact fom_eq_rels x y s v p : \n          s ∊ lr -> x ≡ y -> fom_rels M s (v[x/p]) <-> fom_rels M s (v[y/p]).\n  Proof. intros; apply fom_eq_fix; auto. Qed.\n\n  Hint Resolve fom_eq_refl fom_eq_sym fom_eq_trans fom_eq_syms fom_eq_rels : core.\n\n  Local Theorem fom_eq_syms_full s v w : \n          s ∊ ls -> (forall p, v#>p ≡ w#>p) -> fom_syms M s v ≡ fom_syms M s w.\n  Proof. intro; apply map_vec_pos_equiv; eauto. Qed.\n\n  Local Theorem fom_eq_rels_full s v w : \n          s ∊ lr -> (forall p, v#>p ≡ w#>p) -> fom_rels M s v <-> fom_rels M s w.\n  Proof. intro; apply map_vec_pos_equiv; eauto; tauto. Qed.\n\n  (* And because the signature is finite (ie the symbols and relations) \n                  the model M is finite and composed of decidable relations \n\n      We do have a decidable equivalence here *) \n\n  Local Fact fom_eq_dec x y : { x ≡ y } + { ~ x ≡ y }.\n  Proof using fin dec. apply gfp_decidable; eauto. Qed.\n\n  Section fol_characterization.\n\n    (* We show that the greatest bisimulation is equivalent to FOL undistinguishability. \n        This result is purely for the sake of completeness of the description of fom_eq,\n        it is not used in the reduction below \n\n        It states that x and y are bisimilar iff there is no interpretation of a \n        FO formula that can distinguish x from y *)\n\n    Hint Resolve fom_eq_syms_full fom_eq_rels_full : core.\n\n    Let f : fo_simulation ls lr M M.\n    Proof. exists fom_eq; abstract eauto. Defined.\n\n    Let fom_eq_fol_charac1 φ : \n            fol_syms φ ⊑ ls\n         -> fol_rels φ ⊑ lr\n         -> forall ρ δ, (forall n, n ∊ fol_vars φ -> ρ n ≡ δ n) -> M,ρ ⊨ φ <-> M,δ ⊨ φ.\n    Proof. intros; apply fo_model_simulation with (R := f); auto. Qed.\n\n    (* By fom_eq_form_sem above, we know there is a FO formula\n        A(.,.) in two free variables such that x ≡ y <-> A(x,y).\n\n        One obvious follow up question is can we show\n\n           x ≡ y <-> A(x) <-> A(y) for any A(.) with one free variable\n\n        Another obvious follow up question is, for a given x in the\n        model, can one characterize the class of { y | x ≡ y } with\n        a formula Ax(.) with one free variable.\n\n        Both questions have a negative answer proved in the counter\n        example to be found below. There is a model of Σ = {ø,{=²}}\n        with two distinct values where =² is interpreted by identity\n        and such that A(x) <-> A(y) for any formula with at most one\n        free variable. See theorem FO_does_not_characterize_classes.\n\n      *)\n\n    Let fom_eq_fo_bisimilar x y : x ≡ y -> x ≐ y.\n    Proof.\n      intros ? ? ? ? ?; apply fom_eq_fol_charac1; auto.\n      intros [] _; auto.\n    Qed.\n\n    Let fo_bisimilar_fom_eq x y : x ≐ y -> x ≡ y.\n    Proof.\n      revert x y; apply gfp_greatest; eauto.\n      intros x y H; split.\n      * intros s Hs v p A H1 H2 phi.\n        destruct (fot_vec_env Σ p) as (w & Hw1 & Hw2).\n        set (B := fol_subst (fun n => \n               match n with\n                 | 0   => in_fot s w \n                 | S n => £ (S n + ar_syms Σ s)\n               end) A).\n        assert (HB : forall z, fol_sem M (z·(env_vlift phi v)) B \n                           <-> fol_sem M (fom_syms M s (v[z/p]))·phi A).\n        { intros z; unfold B; rewrite fol_sem_subst; apply fol_sem_ext.\n          intros [ | n] _; rew fot; simpl; f_equal.\n          * apply vec_pos_ext; intros q; rewrite vec_pos_map; apply Hw1.\n          * rewrite env_vlift_fix1; auto. }\n        rewrite <- !HB; apply H.\n        - red; apply Forall_forall, fol_syms_subst.\n          intros [ | n ]; rew fot.\n          + intros _; apply Forall_forall.\n            intros s' [ <- | Hs' ]; auto; apply H1; revert Hs'.\n            rewrite in_flat_map; intros (z & H3 & H4).\n            apply vec_list_inv in H3; destruct H3 as (q & ->).\n            rewrite Hw2 in H4; destruct H4.\n          + constructor.\n          + apply Forall_forall, H1.\n        - unfold B; rewrite fol_rels_subst; auto.\n      * intros r Hr v p; red in H.\n        destruct (fot_vec_env Σ p) as (w & Hw1 & Hw2).\n        set (B := fol_atom r w).\n        assert (HB : forall z, fol_sem M (z·(env_vlift (fun _ => x) v)) B \n                           <-> fom_rels M r (v[z/p])).\n        { intros z; unfold B; simpl; apply fol_equiv_ext; f_equal.\n          apply vec_pos_ext; intros q; rewrite vec_pos_map; apply Hw1. }\n        rewrite <- !HB; apply H.\n        - unfold B; simpl; intros z; rewrite in_flat_map.\n          intros (t & H3 & H4).\n          apply vec_list_inv in H3.\n          destruct H3 as (q & ->).\n          rewrite Hw2 in H4; destruct H4.\n        - unfold B; simpl; intros ? [ <- | [] ]; auto.\n    Qed.\n\n    Hint Resolve fom_eq_fo_bisimilar fo_bisimilar_fom_eq : core.\n\n    Theorem fom_eq_fol_characterization x y : x ≡ y <-> x ≐ y.\n    Proof. split; auto. Qed.\n\n  End fol_characterization.\n\n  (** R is an equivalence relation and a congruence for the interpretations\n      of all the symbols in ls and lr *)\n\n  Definition fo_congruence_upto R := \n      ( (equivalence _ R)\n    * (forall s v w, s ∊ ls -> (forall p, R (v#>p) (w#>p)) -> R (fom_syms M s v) (fom_syms M s w))\n    * (forall r v w, r ∊ lr -> (forall p, R (v#>p) (w#>p)) -> fom_rels M r v <-> fom_rels M r w) )%type.\n\n  Theorem fo_bisimilar_dec_congr : \n            fo_congruence_upto (fun x y => x ≐ y)\n         * (forall x y, decidable (x ≐ y)).\n  Proof using fin dec.\n    lsplit 3.\n    + split; red; [ intros ? | intros ? ? ? | intros ? ?]; \n        rewrite <- !fom_eq_fol_characterization; eauto.\n    + intros ? ? ? ? ?; apply fom_eq_fol_characterization, fom_eq_syms_full; auto.\n      intro; apply fom_eq_fol_characterization; auto.\n    + intros ? ? ? ? ?; apply fom_eq_rels_full; auto.\n      intro; apply fom_eq_fol_characterization; auto.\n    + intros x y.\n      destruct (fom_eq_dec x y); [ left | right ]; \n        rewrite <- fom_eq_fol_characterization; auto.\n  Qed.\n\n  Section build_the_discrete_model.\n\n    (* And now we can build a discrete model with this decidable \n      equivalence. There is a fo_projection from M to Md where\n      Md is a Boolean model based on the ground type pos n.\n\n     *)\n\n    Let l := proj1_sig fin.\n    Let Hl : forall x, x ∊ l := proj2_sig fin.\n\n    Hint Resolve fom_eq_dec : core.\n\n    Let Q : fin_quotient fom_eq.\n    Proof. apply decidable_EQUIV_fin_quotient with (l := l); eauto. Qed.\n\n    Let n := fq_size Q.\n    Let cls := fq_class Q.\n    Let repr := fq_repr Q.\n    Let E1 p : cls (repr p) = p.              Proof. apply fq_surj. Qed.\n    Let E2 x y : x ≡ y <-> cls x = cls y.     Proof. apply fq_equiv. Qed.\n\n    Let Md : fo_model Σ (pos n).\n    Proof.\n      exists.\n      + intros s v; apply cls, (fom_syms M s), (vec_map repr v).\n      + intros s v; apply (fom_rels M s), (vec_map repr v).\n    Defined.\n\n    Let H1 s v : s ∊ ls -> cls (fom_syms M s v) = fom_syms Md s (vec_map cls v).\n    Proof.\n      intros Hs; simpl.\n      apply E2.\n      apply fom_eq_syms_full; auto.\n      intros p; rewrite vec_map_map, vec_pos_map.\n      apply E2; rewrite E1; auto.\n    Qed.\n\n    Let H2 r v : r ∊ lr -> fom_rels M r v <-> fom_rels Md r (vec_map cls v).\n    Proof.\n      intros Hs; simpl.\n      apply fom_eq_rels_full; auto.\n      intros p; rewrite vec_map_map, vec_pos_map.\n      apply E2; rewrite E1; auto.\n    Qed.\n\n    Let f : fo_projection ls lr M Md.\n    Proof. exists cls repr; abstract auto. Defined.\n\n    Let H3 φ ρ :   fol_syms φ ⊑ ls \n                -> fol_rels φ ⊑ lr\n                -> M,ρ ⊨ φ <-> Md,cls∘ρ ⊨ φ.\n    Proof. intros; apply fo_model_projection with (p := f); auto. Qed.\n\n    Let H4 p q : fo_bisimilar Md p q <-> p = q.\n    Proof.\n      split.\n      + intros H.\n        rewrite <- (E1 q), <- (E1 p).\n        apply E2, fom_eq_fol_characterization.\n        intros A Hs Hr phi.\n        specialize (H A Hs Hr (fun p => cls (phi p))).\n        revert H; apply fol_equiv_impl.\n        all: rewrite H3; auto; apply fol_sem_ext; intros []; now simpl.\n      + intros []; red; tauto.\n    Qed.\n\n    (* Every finite & decidable model can be projected to pos n\n        with decidable relations and such that identity is exactly\n        FO undistinguishability *)\n\n    Theorem fo_fin_model_discretize : \n        { n : nat & \n        { Md : fo_model Σ (pos n) &\n        { _ : fo_model_dec Md & \n        { _ : fo_projection ls lr M Md & \n          (forall p q, fo_bisimilar Md p q <-> p = q) } } } }.\n    Proof using E1.\n      exists n, Md.\n      exists; eauto.\n      red; simpl; auto.\n    Qed.\n\n  End build_the_discrete_model.\n\n  (** Additional results on FO definability *)\n\n  Section FO_definability.\n\n    (* Because the fixpoint is reached after finitely many iterations, it is FO definable *)\n\n    Local Fact fom_eq_finite : { n | forall x y, x ≡ y <-> iter fom_op (fun _ _ => True) n x y }.\n    Proof using fin dec. apply gfp_finite_t; eauto. Qed.\n\n    Theorem fo_bisimilar_fol_def : fol_definable ls lr M (fun φ => φ 0 ≐ φ 1).\n    Proof using fin dec.\n      destruct fom_eq_finite as (n & Hn).\n      apply fol_def_equiv with (R := fun φ => iter fom_op (fun _ _ : X => True) n (φ 0) (φ 1)).\n      + intro; rewrite <- fom_eq_fol_characterization, <- Hn; tauto.\n      + apply fol_def_iter_fom_op; fol def.\n    Qed.\n\n  End FO_definability.\n\n  (** We have a much stronger statement than the decidability of ≐.\n      In fact ≐ is first order definable and this follows from the \n      fact that X/M is finite *)\n\n  Section fo_bisimilar_formula.\n\n    (* We build a single FO formula with two variables \n        such that:\n          a) ξ(.,.) only has two free variables, 0 and 1 \n          b) ξ is built using only symbols in ls and lr\n          c) ξ characterize bisimilarity upto ls/lr \n\n                  x ≐ y <-> x ≡ y <-> ξ(x,y) \n     *)\n\n    Let A := proj1_sig fo_bisimilar_fol_def.\n\n    (* Let use remove unused variables by mapping them to £0 *) \n    \n    Definition fo_bisimilar_formula := fol_subst (fun n => match n with 0 => £1 | _ => £0 end) A.\n\n    Notation ξ := fo_bisimilar_formula.\n\n    Fact fo_bisimilar_formula_vars : fol_vars ξ ⊑ 0::1::nil.\n    Proof.\n      unfold fo_bisimilar_formula; rewrite fol_vars_subst.\n      intros n; rewrite in_flat_map; intros (? & _ & H).\n      revert x H; intros [ | [] ]; simpl; tauto.\n    Qed.\n\n    Fact fo_bisimilar_formula_syms : fol_syms ξ ⊑ ls.\n    Proof.\n      unfold fo_bisimilar_formula; red.\n      apply Forall_forall, fol_syms_subst.\n      + intros [ | []]; rew fot; auto.\n      + apply Forall_forall, (proj2_sig fo_bisimilar_fol_def).\n    Qed.\n\n    Fact fo_bisimilar_formula_rels : fol_rels ξ ⊑ lr.\n    Proof.\n      unfold fo_bisimilar_formula; rewrite fol_rels_subst.\n      apply (proj2_sig fo_bisimilar_fol_def).\n    Qed.\n\n    Fact fo_bisimilar_formula_sem φ x y : M,y·x·φ ⊨ ξ <-> x ≐ y.\n    Proof.\n      unfold fo_bisimilar_formula; rewrite fol_sem_subst.\n      apply (proj2_sig fo_bisimilar_fol_def).\n    Qed.\n\n  End fo_bisimilar_formula.\n\nEnd discrete_quotient.\n\nImport ListNotations.\n\nSection counter_model_to_class_FO_definability.\n\n  (* Even though ≐ is FO definable, its equivalence classes are not *)\n\n  (* We show that there is a model over Σ = Σrel 2 = {ø,{=²}}\n      where bisimulation ≐ is identity but x ≐ _ is not definable \n      by a FO formula with a single free variable \n\n      There are two non-equivalent values that cannot be\n      distinguished when using a single variable\n\n      Even though ≐ is FO definable by a formula with two\n      free variables, equivalences classes of ≐ are not \n      FO definable *)\n\n  Let Σ := Σrel 2.\n\n  Let M : fo_model Σ bool.\n  Proof.\n    exists; simpl.\n    + intros [].\n    + exact (fun _ => rel2_on_vec eq).\n  Defined.\n\n  Let M_dec : fo_model_dec M.\n  Proof. intros [] ?; apply bool_dec. Qed.\n\n  Notation α := true.\n  Notation β := false.\n\n  (* A projection of M onto itself which swaps α/β *)\n\n  Let f : @fo_projection Σ [] [tt] _ M _ M.\n  Proof.\n    exists negb negb; simpl.\n    + abstract now intros [].\n    + abstract intros [].\n    + abstract (intros [] v _;\n      vec split v with x; vec split v with y; vec nil v; simpl;\n      revert x y; now intros [] []).\n  Defined.\n\n  Let homeomorphism φ ρ : M,ρ ⊨ φ <-> M,negb∘ρ ⊨ φ.\n  Proof.\n    apply fo_model_projection with (p := f); auto.\n    all: intros []; simpl; auto.\n  Qed.\n\n  Infix \"≐\" := (fo_bisimilar (Σ := Σ) nil [tt] M) (at level 70, no associativity).\n\n  Hint Resolve finite_t_bool : core.\n\n  Let bisim_is_identity x y : x ≐ y <-> x = y.\n  Proof.\n    split.\n    + intros H.\n      now apply (H (@fol_atom Σ tt (£0##£1##ø)))\n        with (ρ := fun n => match n with 0 => y | _ => x end).\n    + intros ->; apply fo_bisimilar_refl.\n  Qed.\n\n (* α/true and β/false are not bisimilar *) \n\n  Let true_is_not_false : ~ α ≐ β.\n  Proof. now rewrite bisim_is_identity. Qed.\n\n  (* No formula using only variable 0 can distinguish α from β *)\n\n  Let no_distinct φ ρ x y : fol_vars φ ⊑ [0] -> M,x·ρ ⊨ φ <-> M,y·ρ ⊨ φ.\n  Proof.\n    revert x y; intros [] [] H; try tauto; [ | symmetry ];\n      rewrite homeomorphism with (ρ := β·ρ) at 1;\n      apply fol_sem_ext; intros n Hn; now apply H in Hn as [ [] | [] ].\n  Qed.\n\n  (** There is a (discrete, finite, decidable) model M over Σ2 with \n      two values α and β such that:\n       1) FO bisimilarity (up to all symbols) is equivalent to identity\n       2) no FO formula with one free variable can distinguish the elements\n          of M, in particular distinguish α from β;\n       3) there is a FO ξ(.,.) with 2 free variables that distinguishes\n          α from β, i.e. ξ(α,α) and not ξ(β,α) (hence particular, α <> β).\n   *)\n\n  Theorem FO_does_not_characterize_classes :\n     exists (M : fo_model Σ bool) (_ : fo_model_dec M) (a b : bool), \n              (forall x y, fo_bisimilar (Σ := Σ) nil [tt] M x y <-> x = y)\n           /\\ (forall x y φ ρ, fol_vars φ ⊑ [0] -> M,x·ρ ⊨ φ <-> M,y·ρ ⊨ φ)\n           /\\ exists ξ, fol_vars ξ ⊑ [0;1] /\\ forall ρ, M,a·a·ρ ⊨ ξ /\\ ~ M,b·a·ρ ⊨ ξ.\n  Proof. \n    exists M, M_dec, true, false; msplit 2; auto. \n    exists (fo_bisimilar_formula (Σ := Σ) nil [tt] finite_t_bool M_dec); split.\n    + apply fo_bisimilar_formula_vars.\n    + intro; rewrite !fo_bisimilar_formula_sem; split; auto; intro; tauto.\n  Qed.\n\nEnd counter_model_to_class_FO_definability.\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/discrete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6678577838695315}}
{"text": "Require Import init.\n\nRequire Export mult_field.\n\n#[universes(template)]\nClass ScalarMult U V := {\n    scalar_mult : U → V → V\n}.\nInfix \"·\" := scalar_mult : algebra_scope.\nArguments scalar_mult : simpl never.\n\nClass ScalarComp U V `{Mult U, ScalarMult U V} := {\n    scalar_comp : ∀ a b v, a · (b · v) = (a * b) · v\n}.\n\nClass ScalarId U V `{One U, ScalarMult U V} := {\n    scalar_id : ∀ v, 1 · v = v\n}.\n\nClass ScalarLdist U V `{Plus V, ScalarMult U V} := {\n    scalar_ldist : ∀ a u v, a · (u + v) = a · u + a · v\n}.\nClass ScalarRdist U V `{Plus U, Plus V, ScalarMult U V} := {\n    scalar_rdist : ∀ a b v, (a + b) · v = a · v + b · v\n}.\n\nClass ScalarLMult U V `{Mult V, ScalarMult U V} := {\n    scalar_lmult : ∀ a u v, (a · u) * v = a · (u * v)\n}.\nClass ScalarRMult U V `{Mult V, ScalarMult U V} := {\n    scalar_rmult : ∀ a u v, u * (a · v) = a · (u * v)\n}.\n\nClass Module U V `{\n    MR : CRing U,\n    MG : AbelianGroup V,\n    SM : ScalarMult U V,\n    SMC : @ScalarComp U V UM SM,\n    SME : @ScalarId U V UE SM,\n    SML : @ScalarLdist U V UP0 SM,\n    SMR : @ScalarRdist U V UP UP0 SM\n}.\n\nClass VectorSpace U V `{\n    VF : Field U,\n    VG : AbelianGroup V,\n    SM : ScalarMult U V,\n    SMC : @ScalarComp U V UM SM,\n    SME : @ScalarId U V UE SM,\n    SML : @ScalarLdist U V UP0 SM,\n    SMR : @ScalarRdist U V UP UP0 SM\n}.\n\nClass Algebra U V `{\n    AR : CRing U,\n    AR : Ring V,\n    SM : ScalarMult U V,\n    SMC : @ScalarComp U V UM SM,\n    SME : @ScalarId U V UE SM,\n    SML : @ScalarLdist U V UP0 SM,\n    SMR : @ScalarRdist U V UP UP0 SM,\n    SMLM : @ScalarLMult U V UM0 SM,\n    SMRM : @ScalarRMult U V UM0 SM\n}.\n\nClass AlgebraField U V `{\n    AF : Field U,\n    AR : Ring V,\n    SM : ScalarMult U V,\n    SMC : @ScalarComp U V UM SM,\n    SME : @ScalarId U V UE SM,\n    SML : @ScalarLdist U V UP0 SM,\n    SMR : @ScalarRdist U V UP UP0 SM,\n    SMLM : @ScalarLMult U V UM0 SM,\n    SMRM : @ScalarRMult U V UM0 SM\n}.\n\n(* begin hide *)\nSection LinearBase.\n\nContext {U V} `{AlgebraField U V}.\n\n(* end hide *)\nTheorem lscalar : ∀ {u v} a, u = v → a · u = a · v.\nProof.\n    intros u v a eq.\n    rewrite eq.\n    reflexivity.\nQed.\nTheorem rscalar : ∀ {a b} v, a = b → a · v = b · v.\nProof.\n    intros u v a eq.\n    rewrite eq.\n    reflexivity.\nQed.\nTheorem lrscalar : ∀ {a b u v}, a = b → u = v → a · u = b · v.\nProof.\n    intros a b u v eq1 eq2.\n    apply lscalar with b in eq2.\n    apply rscalar with u in eq1.\n    rewrite eq1, <- eq2.\n    reflexivity.\nQed.\n\nTheorem scalar_lanni : ∀ v, 0 · v = 0.\nProof.\n    intros v.\n    assert (0 · v = 0 · v) as eq by reflexivity.\n    rewrite <- (plus_lid 0) in eq at 1.\n    rewrite scalar_rdist in eq.\n    apply plus_0_a_ab_b in eq.\n    symmetry; exact eq.\nQed.\n\nTheorem scalar_ranni : ∀ a, a · 0 = 0.\nProof.\n    intros a.\n    assert (a · 0 = a · 0) as eq by reflexivity.\n    rewrite <- (plus_lid 0) in eq at 1.\n    rewrite scalar_ldist in eq.\n    apply plus_0_a_ab_b in eq.\n    symmetry; exact eq.\nQed.\n\nTheorem scalar_lneg : ∀ a b, -a · b = -(a · b).\nProof.\n    intros a b.\n    apply plus_lcancel with (a · b).\n    rewrite <- scalar_rdist.\n    do 2 rewrite plus_rinv.\n    apply scalar_lanni.\nQed.\n\nTheorem scalar_rneg : ∀ a b, a · -b = -(a · b).\nProof.\n    intros a b.\n    apply plus_lcancel with (a · b).\n    rewrite <- scalar_ldist.\n    do 2 rewrite plus_rinv.\n    apply scalar_ranni.\nQed.\n\nTheorem scalar_neg_one : ∀ a, (-(1)) · a = -a.\nProof.\n    intros a.\n    rewrite scalar_lneg.\n    rewrite scalar_id.\n    reflexivity.\nQed.\n\nTheorem scalar_lcancel : ∀ {a b} c, 0 ≠ c → c · a = c · b → a = b.\nProof.\n    intros a b c c_nz eq.\n    apply lscalar with (/c) in eq.\n    do 2 rewrite scalar_comp in eq.\n    rewrite mult_linv in eq by exact c_nz.\n    do 2 rewrite scalar_id in eq.\n    exact eq.\nQed.\n\nTheorem scalar_rcancel : ∀ {a b} c, 0 ≠ c → a · c = b · c → a = b.\nProof.\n    intros a b c c_nz eq.\n    rewrite <- plus_0_anb_a_b in eq.\n    rewrite <- scalar_lneg in eq.\n    rewrite <- scalar_rdist in eq.\n    classic_contradiction contr.\n    rewrite <- (scalar_ranni (a - b)) in eq.\n    apply scalar_lcancel in eq; [>contradiction|].\n    intros contr2.\n    rewrite plus_0_anb_a_b in contr2.\n    contradiction.\nQed.\n\n(* begin hide *)\nEnd LinearBase.\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/Linear/linear_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.6678197886137057}}
{"text": "(**\n10進各桁の和が3の倍数なら、3の倍数であることの証明\n========================\n\n@suharahiromichi\n\n2020/04/10\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 multiple_of_3.\n\n(**\n# 問題\n*)\n\n(**\n任意の自然数が3の倍数であることと、\nその数を10進数で表したときの各桁の和が3の倍数であることは同値である。\n\nたとえば、2019 は 3の倍数で、2+0+1+9=12 も3の倍数ですが、\n2020 は3の倍数でなく、2+0+2+0+4 も3の倍数ではありません。\n*)\n\n(**\n10進数の数値の各桁を ... x3 x2 x1 x0 で表すとします。\n*)\nVariable x : nat -> nat.\n\n(**\n``0*x0 + 10*x1 + 100*x2 + 1000*x3 + ...`` が3で割り切れることと、\n``x0 + x1 + x2 + x3 + ...`` が3で割り切れることが、同値であることを証明します。\n\nMathComp では、x が3で割り切れることを ``3 %| x`` で表します。\n割る数の3が前なのに注意してください。これはbool値の述語です。\n\n同値であるとは、bool値が等しいこと（どちらもtrueか、どちらもfalse）で表します。\n\n数列の和 ``Σ(i=0..n)(x i)`` は、big operator を使って``\\sum_(0 <= i < n.+1)(x i)``\nとなります。\n``\\sum_`` は、演算子と単位元を組み合わせた ``\\bigop[addn/0]`` の略記です。\n\n以上から、\n*)\n\nCheck forall (n : nat), (3 %| \\sum_(0 <= i < n.+1)(10^i * (x i))) =\n                        (3 %| \\sum_(0 <= i < n.+1)(x i)).\n\n(**\nを証明すればよいことになります。\n以下において、0 は 3の倍数であるとします。\n\nまた、``i = 0 to n`` を ``0 <= i < n.+1`` とするのは、\nbig operator の補題 big_nat1 を使えるようにするためです。\n*)\n\n(**\n# 証明\n*)\n\n(**\n## 補題 1.\n\n``0*x0 + 9*x1 + 99*x2 + 999*x3`` は3の倍数である。\n\n3の倍数問題の根幹となる補題です。\n0, 9, 99, 999 に、任意の自然数 xi を掛けたものの和が、3の倍数になることを証明します。\n*)\n\nLemma gt_exp m n : 0 < m -> 0 < m^n.\nProof.\n  move=> H.\n  elim: n => // n IHn.\n    by rewrite expnS -{1}(muln0 m)ltn_pmul2l.\nQed.\n\nLemma dvdn3_99 n : 3 %| (10^n - 1).\nProof.\n  elim: n => //.\n  move=> n IHn.\n  rewrite expnS.\n  have {1}-> : 10 = 9 + 1 by [].\n  rewrite mulnDl mul1n -addnBA.\n  - by rewrite dvdn_addr // dvdn_mulr.\n  - by apply: gt_exp.\nQed.\n\nLemma dvdn3_99x n : 3 %| (10^n - 1) * (x n).\nProof.\n  rewrite dvdn_mulr //.\n    by apply: dvdn3_99.\nQed.\n\n(**\n0*x0, 9*x1, 99*x2 が3の倍数であることが判ったので、\nこれをつかって、補題を証明します。\n *)\n\nLemma dvdn3_s99x (n : nat) : 3 %| \\sum_(0 <= i < n.+1)((10^i - 1) * (x i)).\nProof.\n  elim: n => [| n IHn].\n  - rewrite big_nat1.\n    apply: dvdn_mulr.\n      by apply: dvdn3_99.\n  - rewrite big_nat_recr // dvdn_addl // dvdn_mulr //.\n      by apply: dvdn3_99.\nQed.\n\n(**\n## 補題 ``Σ(f + g) = Σf + Σg``\n\n数列の和について、自明な補題について証明しておきます。\nこれは、bigop.v のなかで、\n可換なop一般に対して証明されているので、それを使います。\n *)\n\nCheck big_split\n  : forall (R : Type) (idx : R) (op : Monoid.com_law idx) \n           (I : Type) (r : seq I) (P : pred I) (F1 F2 : I -> R),\n    \\big[op/idx]_(i <- r | P i) op (F1 i) (F2 i) =\n    op (\\big[op/idx]_(i <- r | P i) F1 i) (\\big[op/idx]_(i <- r | P i) F2 i).\n\nLemma s__s_s (n : nat) (F G : nat -> nat) :\n  \\sum_(0 <= i < n)(F i + G i) = \n  \\sum_(0 <= i < n)(F i) + \\sum_(0 <= i < n)(G i).\nProof.\n    by rewrite big_split /=.\nQed.\n\n(**\n## 補題 2.\n\n``x + 10*x1 + 100*x2 + 1000*x3 = (0*x0 + 9*x1 + 99*x2 + 999*x3) + (x0 + x1 + x2 + x3)``\n\n数列の和の問題として、``x + 10*x1 + 100*x2 + 1000*x3`` が、\n``0*x0 + 9*x1 + 99*x2 + 999*x3`` と``x0 + x1 + x2 + x3`` の和であることを証明します。\n\nこれは一見自明ですが、``Σ(f + g) = Σf + Σg`` を使うために式を変形していきます。\n*)\n\nLemma l_100__99_1 (n : nat) : 10 ^ n = 10 ^ n - 1 + 1.\nProof.\n  rewrite addn1 subn1 prednK //.\n    by apply: gt_exp.\nQed.\n\nLemma l_100x__99x_x (i : nat) : 10^i * (x i) = (10^i - 1) * (x i) + (x i).\nProof.\n  rewrite -{3}[(x i)]mul1n.\n  rewrite -mulnDl.\n    by rewrite -l_100__99_1.\nQed.\n\nLemma s100x__s99x_x (n : nat) :\n  \\sum_(0 <= i < n.+1)(10^i * (x i)) =\n  \\sum_(0 <= i < n.+1)((10^i - 1) * (x i) + (x i)).\nProof.\n  elim: n => [| n IHn].\n  - by rewrite 2!big_nat1 l_100x__99x_x.\n  - rewrite big_nat_recr //=.\n    rewrite [\\sum_(0 <= i < n.+2) ((10 ^ i - 1) * x i + x i)]big_nat_recr //=.\n    have <- : 10 ^ n.+1 * x n.+1 = (10 ^ n.+1 - 1) * x n.+1 + x n.+1\n      by rewrite -{3}[x n.+1]mul1n -[(10 ^ n.+1 - 1) * x n.+1 + 1 * x n.+1]mulnDl\n         -l_100__99_1.\n      by rewrite -IHn.\nQed.\n\nLemma s100x__s99x_sx (n : nat) :\n  \\sum_(0 <= i < n.+1)(10^i * (x i)) =\n  \\sum_(0 <= i < n.+1)((10^i - 1) * (x i)) + \\sum_(0 <= i < n.+1)(x i).\nProof.\n    by rewrite -s__s_s s100x__s99x_x.\nQed.\n\n(**\n## 定理\n\n``x + 10*x1 + 100*x2 + 1000*x3`` が3で割りきれることと、\n``x0 + x1 + x2 + x3`` が3で割りきれることは、同値である。\n\n二つの補題をつかって、定理を証明します。\n *)\n\nTheorem mo3 (n : nat) : (3 %| \\sum_(0 <= i < n.+1)(10^i * (x i))) =\n                      (3 %| \\sum_(0 <= i < n.+1)(x i)).\nProof.\n  rewrite s100x__s99x_sx.\n  rewrite dvdn_addr //.\n    by apply: dvdn3_s99x.\nQed.\n\n(* *************************** *)\n(* 予備の補題                  *)\n(* *************************** *)\n\nLemma test100 (x2 : nat) : (3 %| x2) = (3 %| 100 * x2).\nProof.\n  have -> : 100 = 99 + 1 by [].\n  rewrite mulnDl mul1n.\n  rewrite dvdn_addr => //=.\n    by rewrite dvdn_mulr.\nQed.\n\nLemma test10 x1 : (3 %| x1) = (3 %| 10 * x1).\nProof.\n  have -> : 10 = 9 + 1 by [].\n  rewrite mulnDl mul1n.\n  rewrite dvdn_addr => //=.\n    by rewrite dvdn_mulr.\nQed.\n\nLemma dvdn3_s99 (n : nat) : 3 %| \\sum_(0 <= i < n.+1)(10^i - 1).\nProof.\n  elim: n => [| n IHn].\n  - by rewrite big_nat1.\n  - rewrite big_nat_recr //.\n    rewrite dvdn_addl //.\n      by apply: dvdn3_99.\nQed.\n\nEnd multiple_of_3.\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_multiple_of_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6677784313301228}}
{"text": "\nFixpoint truth_value (x : syntax) : bool\n  := match x with\n     | One  => true\n     | Zero => false\n     | Tensor l r => truth_value l && truth_value r\n     | With l r   => truth_value l && truth_value r\n     | Implication l r => if truth_value l then truth_value r else true\n     | Bang r => truth_value r\n     end.\n\nDefinition truth_value_of_context (ctx : seq syntax) : bool\n  := foldr andb true (map truth_value ctx).\n  \nTheorem model : forall {Ctx P},\n  (Ctx ||- P) -> truth_value_of_context Ctx = true -> truth_value P = true.", "meta": {"author": "harshikaaagrawal", "repo": "game-semantics-for-affine-logic", "sha": "6db365c92e9bff315d61d6262cb1b794100d69ad", "save_path": "github-repos/coq/harshikaaagrawal-game-semantics-for-affine-logic", "path": "github-repos/coq/harshikaaagrawal-game-semantics-for-affine-logic/game-semantics-for-affine-logic-6db365c92e9bff315d61d6262cb1b794100d69ad/Project Documentation/coq-code/model_existence/theorem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6677737963384397}}
{"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(** Here are collected some results about the type sumbool (see INIT/Specif.v)\n   [sumbool A B], which is written [{A}+{B}], is the informative\n   disjunction \"A or B\", where A and B are logical propositions.\n   Its extraction is isomorphic to the type of booleans. *)\n\n(** A boolean is either [true] or [false], and this is decidable *)\n\nDefinition sumbool_of_bool : forall b:bool, {b = true} + {b = false}.\n  destruct b; auto.\nDefined.\n\nHint Resolve sumbool_of_bool: bool.\n\nDefinition bool_eq_rec :\n  forall (b:bool) (P:bool -> Set),\n    (b = true -> P true) -> (b = false -> P false) -> P b.\n  destruct b; auto.\nDefined.\n\nDefinition bool_eq_ind :\n  forall (b:bool) (P:bool -> Prop),\n    (b = true -> P true) -> (b = false -> P false) -> P b.\n  destruct b; auto.\nDefined.\n\n\n(** Logic connectives on type [sumbool] *)\n\nSection connectives.\n\n  Variables A B C D : Prop.\n\n  Hypothesis H1 : {A} + {B}.\n  Hypothesis H2 : {C} + {D}.\n\n  Definition sumbool_and : {A /\\ C} + {B \\/ D}.\n    case H1; case H2; auto.\n  Defined.\n\n  Definition sumbool_or : {A \\/ C} + {B /\\ D}.\n    case H1; case H2; auto.\n  Defined.\n\n  Definition sumbool_not : {B} + {A}.\n    case H1; auto.\n  Defined.\n\nEnd connectives.\n\nHint Resolve sumbool_and sumbool_or: core.\nHint Immediate sumbool_not : core.\n\n(** Any decidability function in type [sumbool] can be turned into a function\n    returning a boolean with the corresponding specification: *)\n\nDefinition bool_of_sumbool :\n  forall A B:Prop, {A} + {B} -> {b : bool | if b then A else B}.\n  intros A B H.\n  elim H; intro; [exists true | exists false]; assumption.\nDefined.\nImplicit Arguments bool_of_sumbool.\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/Bool/Sumbool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6676569494589576}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq path div.\nRequire Import fintype tuple finfun bigop prime finset.\n\n(******************************************************************************)\n(* This files contains the definition of:                                     *)\n(*     n ^_ m == the falling (or lower) factorial of n with m terms, i.e.,    *)\n(*               the product n * (n - 1) * ... * (n - m + 1)                  *)\n(*               Note that n ^_ m = 0 if m > n.                               *)\n(*   'C(n, m) == the binomial coeficient n choose m                           *)\n(*            := n ^_ m %/ fact m                                             *)\n(*                                                                            *)\n(* In additions to the properties of these functions, triangular_sum, Wilson  *)\n(* and Pascal are examples of how to manipulate expressions with bigops.      *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** More properties of the factorial **)\n\nLemma fact_smonotone m n : 0 < m -> m < n -> m`! < n`!.\nProof.\ncase: m => // m _; elim: n m => // n IHn [|m] lt_m_n.\n  by rewrite -[_.+1]muln1 leq_mul ?fact_gt0.\nby rewrite ltn_mul ?IHn.\nQed.\n\nLemma fact_prod n : n`! = \\prod_(1 <= i < n.+1) i.\nProof.\nelim: n => [|n IHn] //; first by rewrite big_nil.\nby apply sym_equal; rewrite factS IHn // !big_add1 big_nat_recr /= mulnC.\nQed.\n\nLemma logn_fact p n : prime p -> logn p n`! = \\sum_(1 <= k < n.+1) n %/ p ^ k.\nProof.\nmove=> p_prime; transitivity (\\sum_(1 <= i < n.+1) logn p i).\n  rewrite big_add1; elim: n => /= [|n IHn]; first by rewrite logn1 big_geq.\n  by rewrite big_nat_recr -IHn /= factS mulnC lognM ?fact_gt0.\ntransitivity (\\sum_(1 <= i < n.+1) \\sum_(1 <= k < n.+1) (p ^ k %| i)).\n  apply: eq_big_nat => i /andP[i_gt0 le_i_n]; rewrite logn_count_dvd //.\n  rewrite -!big_mkcond (big_nat_widen _ _ n.+1) 1?ltnW //; apply: eq_bigl => k.\n  by apply: andb_idr => /dvdn_leq/(leq_trans (ltn_expl _ (prime_gt1 _)))->.\nby rewrite exchange_big_nat; apply: eq_bigr => i _; rewrite divn_count_dvd.\nQed.\n \nTheorem Wilson p : p > 1 -> prime p = (p %| ((p.-1)`!).+1).\nProof.\nhave dFact n: 0 < n -> (n.-1)`! = \\prod_(0 <= i < n | i != 0) i.\n  move=> n_gt0; rewrite -big_filter fact_prod; symmetry; apply: congr_big => //.\n  rewrite /index_iota subn1 -[n]prednK //=; apply/all_filterP.\n  by rewrite all_predC has_pred1 mem_iota.\nmove=> lt1p; have p_gt0 := ltnW lt1p.\napply/idP/idP=> [pr_p | dv_pF]; last first.\n  apply/primeP; split=> // d dv_dp; have: d <= p by exact: dvdn_leq.\n  rewrite orbC leq_eqVlt => /orP[-> // | ltdp].\n  have:= dvdn_trans dv_dp dv_pF; rewrite dFact // big_mkord.\n  rewrite (bigD1 (Ordinal ltdp)) /=; last by rewrite -lt0n (dvdn_gt0 p_gt0).\n  by rewrite orbC -addn1 dvdn_addr ?dvdn_mulr // dvdn1 => ->.\npose Fp1 := Ordinal lt1p; pose Fp0 := Ordinal p_gt0.\nhave ltp1p: p.-1 < p by [rewrite prednK]; pose Fpn1 := Ordinal ltp1p.\ncase eqF1n1: (Fp1 == Fpn1); first by rewrite -{1}[p]prednK -1?((1 =P p.-1) _).\nhave toFpP m: m %% p < p by rewrite ltn_mod.\npose toFp := Ordinal (toFpP _); pose mFp (i j : 'I_p) := toFp (i * j).\nhave Fp_mod (i : 'I_p) : i %% p = i by exact: modn_small.\nhave mFpA: associative mFp.\n  by move=> i j k; apply: val_inj; rewrite /= modnMml modnMmr mulnA.\nhave mFpC: commutative mFp by move=> i j; apply: val_inj; rewrite /= mulnC.\nhave mFp1: left_id Fp1 mFp by move=> i; apply: val_inj; rewrite /= mul1n.\nhave mFp1r: right_id Fp1 mFp by move=> i; apply: val_inj; rewrite /= muln1.\npose mFpLaw := Monoid.Law mFpA mFp1 mFp1r.\npose mFpM := Monoid.operator (@Monoid.ComLaw _ _ mFpLaw mFpC).\npose vFp (i : 'I_p) := toFp (egcdn i p).1.\nhave vFpV i: i != Fp0 -> mFp (vFp i) i = Fp1.\n  rewrite -val_eqE /= -lt0n => i_gt0; apply: val_inj => /=.\n  rewrite modnMml; case: egcdnP => //= _ km -> _; rewrite {km}modnMDl.\n  suffices: coprime i p by move/eqnP->; rewrite modn_small.\n  rewrite coprime_sym prime_coprime //; apply/negP=> /(dvdn_leq i_gt0).\n  by rewrite leqNgt ltn_ord.\nhave vFp0 i: i != Fp0 -> vFp i != Fp0.\n  move/vFpV=> inv_i; apply/eqP=> vFp0.\n  by have:= congr1 val inv_i; rewrite vFp0 /= mod0n.\nhave vFpK: {in predC1 Fp0, involutive vFp}.\n  move=> i n0i; rewrite /= -[vFp _]mFp1r -(vFpV _ n0i) mFpA.\n  by rewrite vFpV (vFp0, mFp1).\nhave le_pmFp (i : 'I_p) m: i <= p + m.\n  by apply: leq_trans (ltnW _) (leq_addr _ _).\nhave eqFp (i j : 'I_p): (i == j) = (p %| p + i - j).\n  by rewrite -eqn_mod_dvd ?(modnDl, Fp_mod).\nhave vFpId i: (vFp i == i :> nat) = xpred2 Fp1 Fpn1 i.\n  symmetry; have [->{i} | /eqP ni0] := i =P Fp0.\n    by rewrite /= -!val_eqE /= -{2}[p]prednK //= modn_small //= -(subnKC lt1p).\n  rewrite 2!eqFp -Euclid_dvdM //= -[_ - p.-1]subSS prednK //.\n  have lt0i: 0 < i by rewrite lt0n.\n  rewrite -addnS addKn -addnBA // mulnDl -{2}(addn1 i) -subn_sqr.\n  rewrite addnBA ?leq_sqr // mulnS -addnA -mulnn -mulnDl.\n  rewrite -(subnK (le_pmFp (vFp i) i)) mulnDl addnCA.\n  rewrite -[1 ^ 2]/(Fp1 : nat) -addnBA // dvdn_addl.\n    by rewrite Euclid_dvdM // -eqFp eq_sym orbC /dvdn Fp_mod eqn0Ngt lt0i.\n  by rewrite -eqn_mod_dvd // Fp_mod modnDl -(vFpV _ ni0) eqxx.\nsuffices [mod_fact]: toFp (p.-1)`! = Fpn1.\n  by rewrite /dvdn -addn1 -modnDml mod_fact addn1 prednK // modnn.\nrewrite dFact //; rewrite ((big_morph toFp) Fp1 mFpM) //; first last.\n- by apply: val_inj; rewrite /= modn_small.\n- by move=> i j; apply: val_inj; rewrite /= modnMm.\nrewrite big_mkord (eq_bigr id) => [|i _]; last by apply: val_inj => /=.\npose ltv i := vFp i < i; rewrite (bigID ltv) -/mFpM [mFpM _ _]mFpC.\nrewrite (bigD1 Fp1) -/mFpM; last by rewrite [ltv _]ltn_neqAle vFpId.\nrewrite [mFpM _ _]mFp1 (bigD1 Fpn1) -?mFpA -/mFpM; last first.\n  rewrite -lt0n -ltnS prednK // lt1p.\n  by rewrite [ltv _]ltn_neqAle vFpId eqxx orbT eq_sym eqF1n1.\nrewrite (reindex_onto vFp vFp) -/mFpM => [|i]; last by do 3!case/andP; auto.\nrewrite (eq_bigl (xpredD1 ltv Fp0)) => [|i]; last first.\n  rewrite andbC -!andbA -2!negb_or -vFpId orbC -leq_eqVlt.\n  rewrite andbA -ltnNge; symmetry; case: (altP eqP) => [->|ni0].\n    by case: eqP => // E; rewrite ?E !andbF.\n  by rewrite vFpK //eqxx vFp0.\nrewrite -{2}[mFp]/mFpM -[mFpM _ _]big_split -/mFpM.\nby rewrite big1 ?mFp1r //= => i /andP[]; auto.\nQed.\n\n(** The falling factorial *)\n\nFixpoint ffact_rec n m := if m is m'.+1 then n * ffact_rec n.-1 m' else 1.\n\nDefinition falling_factorial := nosimpl ffact_rec.\n\nNotation \"n ^_ m\" := (falling_factorial n m)\n  (at level 30, right associativity) : nat_scope.\n\nLemma ffactE : falling_factorial = ffact_rec. Proof. by []. Qed.\n\nLemma ffactn0 n : n ^_ 0 = 1. Proof. by []. Qed.\n\nLemma ffact0n m : 0 ^_ m = (m == 0). Proof. by case: m. Qed.\n\nLemma ffactnS n m : n ^_ m.+1 = n * n.-1 ^_ m. Proof. by []. Qed.\n\nLemma ffactSS n m : n.+1 ^_ m.+1 = n.+1 * n ^_ m. Proof. by []. Qed.\n\nLemma ffactn1 n : n ^_ 1 = n. Proof. exact: muln1. Qed.\n\nLemma ffactnSr n m : n ^_ m.+1 = n ^_ m * (n - m).\nProof.\nelim: n m => [|n IHn] [|m] //=; first by rewrite ffactn1 mul1n.\nby rewrite !ffactSS IHn mulnA.\nQed.\n\nLemma ffact_gt0 n m : (0 < n ^_ m) = (m <= n).\nProof. by elim: n m => [|n IHn] [|m] //=; rewrite ffactSS muln_gt0 IHn. Qed.\n\nLemma ffact_small n m : n < m -> n ^_ m = 0.\nProof. by rewrite ltnNge -ffact_gt0; case: posnP. Qed.\n\nLemma ffactnn n : n ^_ n = n`!.\nProof. by elim: n => [|n IHn] //; rewrite ffactnS IHn. Qed.\n\nLemma ffact_fact n m : m <= n -> n ^_ m * (n - m)`! = n`!.\nProof.\nby elim: n m => [|n IHn] [|m] //= le_m_n; rewrite ?mul1n // -mulnA IHn.\nQed.\n\nLemma ffact_factd n m : m <= n -> n ^_ m = n`! %/ (n - m)`!.\nProof. by move/ffact_fact <-; rewrite mulnK ?fact_gt0. Qed.\n\n(** Binomial coefficients *)\n\nFixpoint binomial_rec n m :=\n  match n, m with\n  | n'.+1, m'.+1 => binomial_rec n' m + binomial_rec n' m'\n  | _, 0 => 1\n  | 0, _.+1 => 0\n  end.\n\nDefinition binomial := nosimpl binomial_rec.\n\nNotation \"''C' ( n , m )\" := (binomial n m)\n  (at level 8, format \"''C' ( n ,  m )\") : nat_scope.\n\nLemma binE : binomial = binomial_rec. Proof. by []. Qed.\n\nLemma bin0 n : 'C(n, 0) = 1. Proof. by case: n. Qed.\n\nLemma bin0n m : 'C(0, m) = (m == 0). Proof. by case: m. Qed.\n\nLemma binS n m : 'C(n.+1, m.+1) = 'C(n, m.+1) + 'C(n, m). Proof. by []. Qed.\n\nLemma bin1 n : 'C(n, 1) = n.\nProof. by elim: n => //= n IHn; rewrite binS bin0 IHn addn1. Qed.\n\nLemma bin_gt0 m n : (0 < 'C(m, n)) = (n <= m).\nProof.\nelim: m n => [|m IHm] [|n] //.\nby rewrite binS addn_gt0 !IHm orbC ltn_neqAle andKb.\nQed.\n\nLemma leq_bin2l m1 m2 n : m1 <= m2 -> 'C(m1, n) <= 'C(m2, n).\nProof.\nelim: m1 m2 n => [m2 | m1 IHm [|m2] //] [|n] le_m12; rewrite ?bin0 //.\nby rewrite !binS leq_add // IHm.\nQed.\n\nLemma bin_small n m : n < m -> 'C(n, m) = 0.\nProof. by rewrite ltnNge -bin_gt0; case: posnP. Qed.\n\nLemma binn n : 'C(n, n) = 1.\nProof. by elim: n => [|n IHn] //; rewrite binS bin_small. Qed.\n\nLemma mul_Sm_binm m n : m.+1 * 'C(m, n) = n.+1 * 'C(m.+1, n.+1).\nProof.\nelim: m n => [|m IHm] [|n] //; first by rewrite bin0 bin1 muln1 mul1n.\nby rewrite mulSn {2}binS mulnDr addnCA !IHm -mulnDr.\nQed.\n\nLemma bin_fact m n : n <= m -> 'C(m, n) * (n`! * (m - n)`!) = m`!.\nProof.\nmove/subnKC; move: (m - n) => m0 <-{m}.\nelim: n => [|n IHn]; first by rewrite bin0 !mul1n.\nby rewrite -mulnA mulnCA mulnA -mul_Sm_binm -mulnA IHn.\nQed.\n\n(* In fact the only exception is n = 0 and m = 1 *)\nLemma bin_factd n m : 0 < n -> 'C(n, m)  = n`! %/ (m`! * (n - m)`!).\nProof.\nmove=> n_gt0; have [/bin_fact <-|lt_n_m] := leqP m n.\n  by rewrite mulnK // muln_gt0 !fact_gt0.\nby rewrite bin_small // divnMA !divn_small ?fact_gt0 // fact_smonotone.\nQed.\n\nLemma bin_ffact n m : 'C(n, m) * m`! = n ^_ m.\nProof.\napply/eqP; have [lt_n_m | le_m_n] := ltnP n m.\n  by rewrite bin_small ?ffact_small.\nby rewrite -(eqn_pmul2r (fact_gt0 (n - m))) ffact_fact // -mulnA bin_fact.\nQed.\n\nLemma bin_ffactd n m : 'C(n, m) = n ^_ m %/ m`!.\nProof. by rewrite -bin_ffact mulnK ?fact_gt0. Qed.\n\nLemma bin_sub n m : m <= n -> 'C(n, n - m) = 'C(n, m).\nProof.\nmove=> le_m_n; apply/eqP; move/eqP: (bin_fact (leq_subr m n)).\nby rewrite subKn // -(bin_fact le_m_n) !mulnA mulnAC !eqn_pmul2r // fact_gt0.\nQed.\n\nLemma binSn n : 'C(n.+1, n) = n.+1.\nProof. by rewrite -bin_sub ?leqnSn // subSnn bin1. Qed.\n\nLemma bin2 n : 'C(n, 2) = (n * n.-1)./2.\nProof.\nby case: n => //= n; rewrite -{3}[n]bin1 mul_Sm_binm mul2n half_double.\nQed.\n\nLemma bin2odd n : odd n -> 'C(n, 2) = n * n.-1./2.\nProof. by case: n => // n oddn; rewrite bin2 -!divn2 muln_divA ?dvdn2. Qed.\n\nLemma prime_dvd_bin k p : prime p -> 0 < k < p -> p %| 'C(p, k).\nProof.\nmove=> p_pr /andP[k_gt0 lt_k_p]; have def_p := ltn_predK lt_k_p.\nhave: p %| p * 'C(p.-1, k.-1) by rewrite dvdn_mulr.\nby rewrite -def_p mul_Sm_binm def_p prednK // Euclid_dvdM // gtnNdvd.\nQed.\n\nLemma triangular_sum n : \\sum_(0 <= i < n) i = 'C(n, 2).\nProof.\nby elim: n => [|n IHn]; [rewrite big_geq | rewrite big_nat_recr IHn binS bin1].\nQed.\n\nLemma textbook_triangular_sum n : \\sum_(0 <= i < n) i = 'C(n, 2).\nProof.\nrewrite bin2; apply: canRL half_double _.\nrewrite -addnn {1}big_nat_rev -big_split big_mkord /= ?add0n.\nrewrite (eq_bigr (fun _ => n.-1)); first by rewrite sum_nat_const card_ord.\nby case: n => [|n] [i le_i_n] //=; rewrite subSS subnK.\nQed.\n\nTheorem Pascal a b n :\n  (a + b) ^ n = \\sum_(i < n.+1) 'C(n, i) * (a ^ (n - i) * b ^ i).\nProof.\nelim: n => [|n IHn]; rewrite big_ord_recl muln1 ?big_ord0 //.\nrewrite expnS {}IHn /= mulnDl !big_distrr /= big_ord_recl muln1 subn0.\nrewrite !big_ord_recr /= !binn !subnn bin0 !subn0 !mul1n -!expnS -addnA.\ncongr (_ + _); rewrite addnA -big_split /=; congr (_ + _).\napply: eq_bigr => i _; rewrite mulnCA (mulnA a) -expnS subnSK //.\nby rewrite (mulnC b) -2!mulnA -expnSr -mulnDl.\nQed.\nDefinition expnDn := Pascal.\n\nLemma Vandermonde k l i :\n  \\sum_(j < i.+1) 'C(k, j) * 'C(l, i - j) = 'C(k + l , i).\nProof.\npose f k i := \\sum_(j < i.+1) 'C(k, j) * 'C(l, i - j).\nsuffices{k i} fxx k i: f k.+1 i.+1 = f k i.+1 + f k i.\n  elim: k i => [i | k IHk [|i]]; last by rewrite -/(f _ _) fxx /f !IHk -binS.\n    by rewrite big_ord_recl big1_eq addn0 mul1n subn0.\n  by rewrite big_ord_recl big_ord0 addn0 !bin0 muln1.\nrewrite {}/f big_ord_recl (big_ord_recl (i.+1)) !bin0 !mul1n.\nrewrite -addnA -big_split /=; congr (_ + _).\nby apply: eq_bigr => j _ ; rewrite -mulnDl.\nQed.\n\nLemma subn_exp m n k :\n  m ^ k - n ^ k = (m - n) * (\\sum_(i < k) m ^ (k.-1 -i) * n ^ i).\nProof.\ncase: k => [|k]; first by rewrite big_ord0.\nrewrite mulnBl !big_distrr big_ord_recl big_ord_recr /= subn0 muln1.\nrewrite subnn mul1n -!expnS subnDA; congr (_ - _).\nset F := fun _ => n * _; rewrite (eq_bigr F) ?addnK {}/F // => i _.\nby rewrite (mulnCA n) -expnS mulnA -expnS subnSK.\nQed.\n\nLemma predn_exp m k : (m ^ k).-1 = m.-1 * (\\sum_(i < k) m ^ i).\nProof.\nrewrite -!subn1 -{1}(exp1n k) subn_exp; congr (_ * _).\nsymmetry; rewrite (reindex_inj rev_ord_inj); apply: eq_bigr => i _ /=.\nby rewrite -subn1 -subnDA exp1n muln1.\nQed.\n\nLemma dvdn_pred_predX n e : (n.-1 %| (n ^ e).-1)%N.\nProof. by rewrite predn_exp dvdn_mulr. Qed.\n\nLemma modn_summ I r (P : pred I) F d :\n  \\sum_(i <- r | P i) F i %% d = \\sum_(i <- r | P i) F i %[mod d].\nProof.\nby apply/eqP; elim/big_rec2: _ => // i m n _; rewrite modnDml eqn_modDl.\nQed.\n\n(* Combinatorial characterizations. *)\n\nSection Combinations.\n\nImplicit Types T D : finType.\n\nLemma card_uniq_tuples T n (A : pred T) :\n  #|[set t : n.-tuple T | all A t & uniq t]| = #|A| ^_ n.\nProof.\nelim: n A => [|n IHn] A.\n  by rewrite (@eq_card1 _ [tuple]) // => t; rewrite [t]tuple0 inE.\nrewrite -sum1dep_card (partition_big (@thead _ _) A) /= => [|t]; last first.\n  by case/tupleP: t => x t; do 2!case/andP.\ntransitivity (#|A| * #|A|.-1 ^_ n)%N; last by case: #|A|.\nrewrite -sum_nat_const; apply: eq_bigr => x Ax.\nrewrite (cardD1 x) [x \\in A]Ax /= -(IHn [predD1 A & x]) -sum1dep_card.\nrewrite (reindex (fun t : n.-tuple T => [tuple of x :: t])) /=; last first.\n  pose ttail (t : n.+1.-tuple T) := [tuple of behead t].\n  exists ttail => [t _ | t /andP[_ /eqP <-]]; first exact: val_inj.\n  by rewrite -tuple_eta.\napply: eq_bigl=> t; rewrite Ax theadE eqxx andbT /= andbA; congr (_ && _).\nby rewrite all_predI all_predC has_pred1 andbC.\nQed.\n\nLemma card_inj_ffuns_on D T (R : pred T) :\n  #|[set f : {ffun D -> T} in ffun_on R | injectiveb f]| = #|R| ^_ #|D|.\nProof.\nrewrite -card_uniq_tuples.\nhave bijFF: {on (_ : pred _), bijective (@Finfun D T)}.\n  by exists val => // x _; exact: val_inj.\nrewrite -(on_card_preimset (bijFF _)); apply: eq_card => t.\nrewrite !inE -(codom_ffun (Finfun t)); congr (_ && _); apply: negb_inj.\nby rewrite -has_predC has_map enumT has_filter -size_eq0 -cardE.\nQed.\n\nLemma card_inj_ffuns D T :\n  #|[set f : {ffun D -> T} | injectiveb f]| = #|T| ^_ #|D|.\nProof.\nrewrite -card_inj_ffuns_on; apply: eq_card => f.\nby rewrite 2!inE; case: ffun_onP => // [].\nQed.\n\nLemma card_draws T k : #|[set A : {set T} | #|A| == k]| = 'C(#|T|, k).\nProof.\nhave [ltTk | lekT] := ltnP #|T| k.\n  rewrite bin_small // eq_card0 // => A.\n  by rewrite inE eqn_leq andbC leqNgt (leq_ltn_trans (max_card _)).\napply/eqP; rewrite -(eqn_pmul2r (fact_gt0 k)) bin_ffact // eq_sym.\nrewrite -sum_nat_dep_const -{1 3}(card_ord k) -card_inj_ffuns -sum1dep_card.\npose imIk (f : {ffun 'I_k -> T}) := f @: 'I_k.\nrewrite (partition_big imIk (fun A => #|A| == k)) /= => [|f]; last first.\n  by move/injectiveP=> inj_f; rewrite card_imset ?card_ord.\napply/eqP; apply: eq_bigr => A /eqP cardAk.\nhave [f0 inj_f0 im_f0]: exists2 f, injective f & f @: 'I_k = A.\n  rewrite -cardAk; exists enum_val; first exact: enum_val_inj.\n  apply/setP=> a; apply/imsetP/idP=> [[i _ ->] | Aa]; first exact: enum_valP.\n  by exists (enum_rank_in Aa a); rewrite ?enum_rankK_in.\nrewrite (reindex (fun p : {ffun _} => [ffun i => f0 (p i)])) /=; last first.\n  pose ff0' f i := odflt i [pick j | f i == f0 j].\n  exists (fun f => [ffun i => ff0' f i]) => [p _ | f].\n    apply/ffunP=> i; rewrite ffunE /ff0'; case: pickP => [j | /(_ (p i))].\n      by rewrite ffunE (inj_eq inj_f0) => /eqP.\n    by rewrite ffunE eqxx.\n  rewrite -im_f0 => /andP[/injectiveP injf /eqP im_f].\n  apply/ffunP=> i; rewrite !ffunE /ff0'; case: pickP => [y /eqP //|].\n  have /imsetP[j _ eq_f0j_fi]: f i \\in f0 @: 'I_k by rewrite -im_f mem_imset.\n  by move/(_ j)=> /eqP[].\nrewrite -ffactnn -card_inj_ffuns -sum1dep_card; apply: eq_bigl => p.\napply/andP/injectiveP=> [[/injectiveP inj_f0p _] i j eq_pij | inj_p].\n  by apply: inj_f0p; rewrite !ffunE eq_pij.\nset f := finfun _.\nhave injf: injective f by move=> i j; rewrite !ffunE => /inj_f0; exact: inj_p.\nsplit; first exact/injectiveP.\nrewrite eqEcard card_imset // cardAk card_ord leqnn andbT -im_f0.\nby apply/subsetP=> x /imsetP[i _ ->]; rewrite ffunE mem_imset.\nQed.\n\nLemma card_ltn_sorted_tuples m n :\n  #|[set t : m.-tuple 'I_n | sorted ltn (map val t)]| = 'C(n, m).\nProof.\nhave [-> | n_gt0] := posnP n; last pose i0 := Ordinal n_gt0.\n  case: m => [|m]; last by apply: eq_card0; case/tupleP=> [[]].\n  by apply: (@eq_card1 _ [tuple]) => t; rewrite [t]tuple0 inE.\nrewrite -{12}[n]card_ord -card_draws.\npose f_t (t : m.-tuple 'I_n) := [set i in t].\npose f_A (A : {set 'I_n}) := [tuple of mkseq (nth i0 (enum A)) m].\nhave val_fA (A : {set 'I_n}) : #|A| = m -> val (f_A A) = enum A.\n  by move=> Am; rewrite -[enum _](mkseq_nth i0) -cardE Am.\nhave inc_A (A : {set 'I_n}) : sorted ltn (map val (enum A)).\n  rewrite -[enum _](eq_filter (mem_enum _)).\n  rewrite -(eq_filter (mem_map val_inj _)) -filter_map.\n  by rewrite (sorted_filter ltn_trans) // unlock val_ord_enum iota_ltn_sorted.\nrewrite -!sum1dep_card (reindex_onto f_t f_A) /= => [|A]; last first.\n  by move/eqP=> cardAm; apply/setP=> x; rewrite inE -(mem_enum (mem A)) -val_fA.\napply: eq_bigl => t; apply/idP/idP=> [inc_t|]; last first.\n  by case/andP; move/eqP=> t_m; move/eqP=> <-; rewrite val_fA.\nhave ft_m: #|f_t t| = m.\n  rewrite cardsE (card_uniqP _) ?size_tuple // -(map_inj_uniq val_inj).\n  exact: (sorted_uniq ltn_trans ltnn).\nrewrite ft_m eqxx -val_eqE val_fA // -(inj_eq (inj_map val_inj)) /=.\napply/eqP; apply: (eq_sorted_irr ltn_trans ltnn) => // y.\nby apply/mapP/mapP=> [] [x t_x ->]; exists x; rewrite // mem_enum inE in t_x *.\nQed.\n\nLemma card_sorted_tuples m n :\n  #|[set t : m.-tuple 'I_n.+1 | sorted leq (map val t)]| = 'C(m + n, m).\nProof.\nset In1 := 'I_n.+1; pose x0 : In1 := ord0.\nhave add_mnP (i : 'I_m) (x : In1) : i + x < m + n.\n  by rewrite -ltnS -addSn -!addnS leq_add.\npose add_mn t i := Ordinal (add_mnP i (tnth t i)).\npose add_mn_nat (t : m.-tuple In1) i := i + nth x0 t i.\nhave add_mnC t: val \\o add_mn t =1 add_mn_nat t \\o val.\n  by move=> i; rewrite /= (tnth_nth x0).\npose f_add t := [tuple of map (add_mn t) (ord_tuple m)].\nrewrite -card_ltn_sorted_tuples -!sum1dep_card (reindex f_add) /=.\n  apply: eq_bigl => t; rewrite -map_comp (eq_map (add_mnC t)) map_comp.\n  rewrite enumT unlock val_ord_enum -{1}(drop0 t).\n  have [m0 | m_gt0] := posnP m.\n    by rewrite {2}m0 /= drop_oversize // size_tuple m0.\n  have def_m := subnK m_gt0; rewrite -{2}def_m addn1 /= {1}/add_mn_nat.\n  move: 0 (m - 1) def_m => i k; rewrite -{1}(size_tuple t) => def_m.\n  rewrite (drop_nth x0) /=; last by rewrite -def_m leq_addl.\n  elim: k i (nth x0 t i) def_m => [|k IHk] i x /=.\n    by rewrite add0n => ->; rewrite drop_size.\n  rewrite addSnnS => def_m; rewrite -addSn leq_add2l -IHk //.\n  by rewrite (drop_nth x0) // -def_m leq_addl.\npose sub_mn (t : m.-tuple 'I_(m + n)) i : In1 := inord (tnth t i - i).\nexists (fun t => [tuple of map (sub_mn t) (ord_tuple m)]) => [t _ | t].\n  apply: eq_from_tnth => i; apply: val_inj.\n  by rewrite /sub_mn !(tnth_ord_tuple, tnth_map) addKn inord_val.\nrewrite inE /= => inc_t; apply: eq_from_tnth => i; apply: val_inj.\nrewrite tnth_map tnth_ord_tuple /= tnth_map tnth_ord_tuple.\nsuffices [le_i_ti le_ti_ni]: i <= tnth t i /\\ tnth t i <= i + n.\n  by rewrite /sub_mn inordK ?subnKC // ltnS leq_subLR.\npose y0 := tnth t i; rewrite (tnth_nth y0) -(nth_map _ (val i)) ?size_tuple //.\ncase def_e: (map _ _) => [|x e] /=; first by rewrite nth_nil ?leq_addr.\nrewrite def_e in inc_t; split.\n  case: {-2}i; rewrite /= -{1}(size_tuple t) -(size_map val) def_e.\n  elim=> //= j IHj lt_j_t; apply: leq_trans (pathP (val i) inc_t _ lt_j_t).\n  by rewrite ltnS IHj 1?ltnW.\nmove: (_ - _) (subnK (valP i)) => k /=.\nelim: k {-2}(val i) => /= [|k IHk] j def_m; rewrite -ltnS -addSn.\n  by rewrite [j.+1]def_m -def_e (nth_map y0) ?ltn_ord // size_tuple -def_m.\nrewrite (leq_trans _ (IHk _ _)) -1?addSnnS //; apply: (pathP _ inc_t).\nrewrite -ltnS (leq_trans (leq_addl k _)) // -addSnnS def_m.\nby rewrite -(size_tuple t) -(size_map val) def_e.\nQed.\n\nLemma card_partial_ord_partitions m n :\n  #|[set t : m.-tuple 'I_n.+1 | \\sum_(i <- t) i <= n]| = 'C(m + n, m).\nProof.\nsymmetry; set In1 := 'I_n.+1; pose x0 : In1 := ord0. \npose add_mn (i j : In1) : In1 := inord (i + j).\npose f_add (t : m.-tuple In1) := [tuple of scanl add_mn x0 t].\nrewrite -card_sorted_tuples -!sum1dep_card (reindex f_add) /=.\n  apply: eq_bigl => t; rewrite -[\\sum_(i <- t) i]add0n.\n  transitivity (path leq x0 (map val (f_add t))) => /=; first by case: map.\n  rewrite -{1 2}[0]/(val x0); elim: {t}(val t) (x0) => /= [|x t IHt] s.\n    by rewrite big_nil addn0 -ltnS ltn_ord.\n  rewrite big_cons addnA IHt /= val_insubd ltnS.\n  have [_ | ltn_n_sx] := leqP (s + x) n; first by rewrite leq_addr.\n  rewrite -(leq_add2r x) leqNgt (leq_trans (valP x)) //=.\n  by rewrite leqNgt (leq_trans ltn_n_sx) ?leq_addr.\npose sub_mn (i j : In1) := Ordinal (leq_ltn_trans (leq_subr i j) (valP j)).\nexists (fun t : m.-tuple In1 => [tuple of pairmap sub_mn x0 t]) => /= t inc_t.\n  apply: val_inj => /=; have{inc_t}: path leq x0 (map val (f_add t)).\n    by move: inc_t; rewrite inE /=; case: map.\n  rewrite [map _ _]/=; elim: {t}(val t) (x0) => //= x t IHt s.\n  case/andP=> le_s_sx /IHt->; congr (_ :: _); apply: val_inj => /=.\n  move: le_s_sx; rewrite val_insubd.\n  case le_sx_n: (_ < n.+1); first by rewrite addKn.\n  by case: (val s) le_sx_n; rewrite ?ltn_ord.\napply: val_inj => /=; have{inc_t}: path leq x0 (map val t).\n  by move: inc_t; rewrite inE /=; case: map.\nelim: {t}(val t) (x0) => //= x t IHt s /andP[le_s_sx inc_t].\nsuffices ->: add_mn s (sub_mn s x) = x by rewrite IHt.\nby apply: val_inj; rewrite /add_mn /= subnKC ?inord_val.\nQed.\n\nLemma card_ord_partitions m n :\n  #|[set t : m.+1.-tuple 'I_n.+1 | \\sum_(i <- t) i == n]| = 'C(m + n, m).\nProof.\nsymmetry; set In1 := 'I_n.+1; pose x0 : In1 := ord0. \npose f_add (t : m.-tuple In1) := [tuple of sub_ord (\\sum_(x <- t) x) :: t].\nrewrite -card_partial_ord_partitions -!sum1dep_card (reindex f_add) /=.\n  by apply: eq_bigl => t; rewrite big_cons /= addnC (sameP maxn_idPr eqP) maxnE.\nexists (fun t : m.+1.-tuple In1 => [tuple of behead t]) => [t _|].\n  exact: val_inj.\ncase/tupleP=> x t; rewrite inE /= big_cons => /eqP def_n.\nby apply: val_inj; congr (_ :: _); apply: val_inj; rewrite /= -{1}def_n addnK.\nQed.\n\nEnd Combinations.\n\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/ssreflect/attic/ssreflect1.4_v8.3/theories/binomial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199032, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6676569338419457}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Solange Coupet-Grimal and William Delobel, 2006-01-09\n- Adam Koprowski, 2007-06-01 added Decidability section\n\nDefinition and properties of lexicographic order on lists of elements\nof a setoid. In particular, proofs that lex 'transmits' strict partial\norder property, and is a lifting.\n*)\n\nFrom CoLoR Require Import RelExtras ListUtil AccUtil LogicUtil.\nFrom Coq Require Peano_dec.\n\nModule LexOrder (ES : Eqset).\n\n  Section Lex.\n\n    Variable r : relation ES.A.\n    \n    Inductive lex : relation (list ES.A) :=\n      | lex1 : forall h h' (l l' : list ES.A),\n\tr h h' -> length l = length l' -> lex (h::l) (h'::l')\n      | lex2 : forall (h : ES.A) (l l' : list ES.A),\n\tlex l l' -> lex (h::l) (h::l').\n    \n    Lemma lex_length : forall ss ts : list ES.A,\n      lex ss ts -> length ss = length ts.\n\n    Proof.\n      induction ss as [ | s ss IHss]; intros ts Hlex.\n      inversion Hlex; trivial.\n      destruct ts as [ | t ts]; inversion Hlex; subst.\n      simpl; auto with arith.\n      simpl; gen (IHss ts H0); auto with arith.\n    Qed.\n    \n    Lemma SPO_to_lex_SPO : forall (ss : list ES.A), \n      (forall s, In s ss ->\n        (forall t u, r s t -> r t u -> r s u) /\\ (r s s -> False)) ->\n      (forall ts us : list ES.A, lex ss ts -> lex ts us -> lex ss us)\n      /\\ (lex ss ss -> False).\n\n    Proof.\n      induction ss as [ | s ss IHss]; intro Hss; split.\n      intros ts us Hss_ts Hts_us; inversion Hss_ts; subst; trivial.\n      intro H; inversion H.\n      intros ts us Hss_ts Hts_us.\n      assert (Hs : In s (s::ss)). \n      left; trivial.\n      elim (Hss s Hs); intros Hss' Hss''.\n      destruct ts as [ | t ts]; inversion Hss_ts; subst.\n      destruct us as [ | u us]; inversion Hts_us; subst.\n      constructor 1.\n      apply Hss' with t; try left; trivial.\n      rewrite H4; trivial.\n      constructor 1; trivial.\n      rewrite H4; apply lex_length; trivial.\n      destruct us as [ | u us]; inversion Hts_us; subst.\n      constructor 1; trivial.\n      rewrite <- H5; apply lex_length; trivial.\n      constructor 2.\n      elim IHss. \n      intros H2 H3; apply (H2 ts); trivial.\n      intros s s_in_ss; split.\n      elim (Hss s); try right; trivial.\n      elim (Hss s); try right; trivial.\n      intro H; inversion H; subst.\n      elim (Hss s); try left; trivial; intros H1 H2.\n      apply H2; hyp.\n      elim IHss. \n      intros H2 H3; apply H3; trivial.\n      intros s' s'_in_ss; apply (Hss s'); try right; trivial.\n    Qed.\n  \n    Lemma irrefl_to_lex_irrefl : forall (ss : list ES.A), \n      (forall s, In s ss -> r s s -> False) -> lex ss ss -> False.\n\n    Proof.\n      intro ss; induction ss as [ | h ss IHss]; intros Hss Hlex;\n        inversion Hlex; subst.\n      apply Hss with h; try left; trivial.\n      apply IHss; trivial.\n      intros s s_in_ss; apply Hss; try right; trivial.\n    Qed.\n\n    Lemma lex_lifting_aux : forall n (l : list ES.A), \n      length l = n -> Accs r l -> Restricted_acc (Accs r) lex l.\n\n    Proof.\n      intro n; induction n as [ | n IHn]; intros l Hl HAccs.\n      destruct l; [constructor | inversion Hl].\n      intros l' Hl' Hlex; inversion Hlex.\n      destruct l as [ | h l]; [inversion Hl | idtac].\n      assert (acc_h : Acc r h).\n      apply HAccs; left; trivial.\n      assert (Accs_l : forall (a : ES.A), In a l -> Acc r a).\n      intros s s_in_l; apply HAccs; right; trivial.\n      assert (Hl2 : length l = n).\n      inversion Hl; trivial.\n      gen (IHn l Hl2 Accs_l).\n      clear Hl HAccs.\n      generalize dependent l.\n      induction acc_h as [h acc_h IHh].\n      intros l Accs_l Hl Hacc.\n      induction Hacc as [l Hacc IHl].\n      constructor.\n      intros l' Hl' Hlex.\n      destruct l' as [ | h' l'].\n      inversion Hlex.\n      assert (Accs_l' : forall (a : ES.A), In a l' -> Acc r a).\n      intros t Ht; apply Hl'; right; trivial.\n      clear Hl'.\n      inversion Hlex; subst.\n      apply IHh; trivial.\n      apply IHn; trivial.\n      apply IHl; trivial.\n      cut (length (h :: l') = length ( h :: l)).\n      simpl; auto with arith.\n      gen Hlex; apply lex_length.\n    Qed.\n    \n    Section Lex_and_one_less.\n\n      Lemma one_less2lex : forall l l', one_less r l l' -> lex l l'.\n\n      Proof.\n        intros l l' H1; inversion H1; subst. \n        generalize dependent l; induction p as [ | p]; intros l Hl H1.\n        destruct l as [|h l]; inversion H1.\n        subst; simpl; constructor; trivial.\n        destruct l as [|h l]; inversion H1.\n        subst; simpl; constructor 2; trivial.\n        apply IHp; trivial.\n        apply (@one_less_cons _ r l (l [p := a']) p a a'); trivial.\n      Qed.\n\n    End Lex_and_one_less.\n\n  End Lex.\n\n  Lemma lex_lifting : forall (r : relation ES.A) (l : list ES.A), \n    Accs r l -> Restricted_acc (Accs r) (lex r) l.\n\n  Proof.\n    intros r l; apply (lex_lifting_aux r (length l) l); trivial.\n  Qed.\n\n  Section Decidability.\n\n    Import Peano_dec.\n\n    Variable eqA_dec : forall a b : ES.A, {a = b} + {~a = b}.\n\n    Lemma lex_dec : forall R l l',\n      (forall a b, In a l -> In b l' -> {R a b} + {~R a b}) ->\n      {lex R l l'} + {~lex R l l'}.\n\n    Proof.\n      induction l; intros.\n      right. intro nil_l. inversion nil_l.\n      revert X; destruct l'; intro.\n      right. intro al_nil. inversion al_nil.\n      destruct (X a a0); auto with datatypes.\n      destruct (eq_nat_dec (length l) (length l')).\n      left. constructor; trivial.\n      right. intro al_nil. inversion al_nil; intuition.\n      apply n. apply lex_length with R. hyp.\n      destruct (eqA_dec a a0).\n      rewrite e. destruct (IHl l'). intuition.\n      left. constructor 2. hyp.\n      right. intro ll'. inversion ll'; intuition.\n      apply n. congruence.\n      right. intro ll'. inversion ll'; intuition.\n    Defined.\n\n  End Decidability.\n\n  Section Homomorphism.\n\n    Variable R : relation ES.A.\n    Variable f : ES.A -> ES.A.\n\n    Lemma lex_homomorphic : forall l l',\n      (forall x x', In x l -> In x' l' -> R x x' -> R (f x) (f x')) ->\n      lex R l l' -> lex R (map f l) (map f l').\n\n    Proof.\n      induction l; intros.\n      inversion H0.\n      destruct l'. inversion H0.\n      simpl. inversion H0.\n      constructor 1. apply H; auto with datatypes.\n      do 2 rewrite map_length. hyp.\n      constructor 2. apply IHl.\n      intros. apply H; intuition. hyp.\n    Qed.\n\n  End Homomorphism.\n\nEnd LexOrder.\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Util/List/ListLex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832332, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.6676569296056862}}
{"text": "Require Import Coq.Init.Prelude.\n\nFixpoint fnd (n : nat) : Prop :=\n  match n with\n  | O => True\n  | S n => True /\\ fnd n\n  end.\n\nFixpoint big_and (xs : list Prop) : Prop :=\n  match xs with\n  | nil => True\n  | cons x xs => and x (big_and xs)\n  end.\nFixpoint typeof_big_conj (xs : list Prop) (P : Prop) : Prop :=\n  match xs with\n  | nil => P\n  | cons x xs => x -> typeof_big_conj xs P\n  end.\nLemma apply_rconj_and xs (P Q : Prop) : P -> typeof_big_conj xs Q -> typeof_big_conj xs (P /\\ Q).\nProof. revert Q; revert P; induction xs; intros; cbn in *; eauto. Qed.\nLemma big_conj xs : typeof_big_conj xs (big_and xs).\nProof. induction xs. exact I. cbn. intros. apply apply_rconj_and; eauto. Qed.\n\nRequire Import Coq.Lists.List.\n\nGoal fnd 1000.\n  Time\n  let n := match goal with |- fnd ?n => n end in\n  let ls := eval cbv in (repeat True n) in\n  let pf := constr:(big_conj ls) in\n  let T := type of pf in\n  let T := eval cbv [typeof_big_conj big_and] in T in\n  pose proof (pf : T) as H; apply H; exact I.\nTime Qed.\n(*\nFinished transaction in 0.207 secs (0.207u,0.s) (successful)\nFinished transaction in 0.047 secs (0.047u,0.s) (successful)\n*)", "meta": {"author": "andres-erbsen", "repo": "coq-experiments", "sha": "2018edd397a23c0429d316c96e86f9be7a9678f1", "save_path": "github-repos/coq/andres-erbsen-coq-experiments", "path": "github-repos/coq/andres-erbsen-coq-experiments/coq-experiments-2018edd397a23c0429d316c96e86f9be7a9678f1/experiments/bench/big_and_1000_true.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894576856559, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.6676373099832158}}
{"text": "Require Import HoTT.\nFrom GR.bicategories Require Import\n     bicategory.bicategory_laws\n     lax_functor.lax_functor\n     lax_transformation.lax_transformation\n     lax_transformation.examples.identity\n     lax_transformation.examples.composition\n     modification.modification.\n\nSection RightIdentity.\n  Context `{Univalence}\n          {C D : BiCategory}\n          {F₁ F₂ : LaxFunctor C D}.\n  Variable (η : LaxTransformation F₁ F₂).\n\n  Local Notation right_identity_mod_d\n    := (fun (A : C) => right_unit (η A) : compose (identity_transformation F₁) η A ==> η A).\n\n  Definition right_identity_is_mod : is_modification right_identity_mod_d.\n  Proof.\n    intros A B f ; cbn in *.\n    unfold bc_whisker_l, bc_whisker_r.\n    rewrite !vcomp_assoc.\n    rewrite <- (vcomp_left_identity (id₂ (η B))).\n    rewrite interchange.\n    rewrite !vcomp_assoc.\n    rewrite triangle_r.\n    rewrite !vcomp_assoc.\n    rewrite (ap (fun z => _ ∘ z) (vcomp_assoc _ _ _)^).\n    rewrite assoc_left.\n    rewrite vcomp_left_identity.\n    rewrite <- !vcomp_assoc.\n    rewrite <- interchange.\n    rewrite left_unit_left.\n    rewrite vcomp_left_identity.\n    rewrite hcomp_id₂.\n    rewrite vcomp_left_identity.\n    pose @right_unit_assoc as p.\n    unfold bc_whisker_l in p.\n    rewrite <- p ; clear p.\n    rewrite right_unit_natural.\n    rewrite vcomp_assoc.\n    rewrite right_unit_assoc.\n    unfold bc_whisker_r.\n    rewrite !vcomp_assoc.\n    rewrite assoc_left.\n    rewrite vcomp_right_identity.\n    reflexivity.\n  Qed.\n\n  Definition right_identity_modification\n    : Modification (compose (identity_transformation F₁) η) η\n    := Build_Modification right_identity_mod_d right_identity_is_mod.\n\n  Definition right_identity_modification_iso\n    : iso_modification right_identity_modification.\n  Proof.\n    intros X ; cbn.\n    apply _.\n  Qed.\n\n  Definition right_identity_mod\n    : IsoModification (composition.compose (identity_transformation F₁) η) η.\n  Proof.\n    make_iso_modification.\n    - exact right_identity_modification.\n    - exact right_identity_modification_iso.\n  Defined.\nEnd RightIdentity.\n", "meta": {"author": "nmvdw", "repo": "groupoids", "sha": "dd54321b2589c7cf31f379bd63b4a86cf9052792", "save_path": "github-repos/coq/nmvdw-groupoids", "path": "github-repos/coq/nmvdw-groupoids/groupoids-dd54321b2589c7cf31f379bd63b4a86cf9052792/bicategories/modification/examples/right_identity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6676372998809986}}
{"text": "Require Import List.\nImport ListNotations.\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\nInductive exp_match {T}: list T -> reg_exp -> Prop :=\n    | MEmpty: exp_match [] EmptySet\n    | MChar x: exp_match [x] (Char x)\n    | MApp s1 re1 s2 re2\n        (H1: exp_match s1 re1) (H2: exp_match s2 re2):\n        exp_match (s1 ++ s2) (App re1 re2)\n    | MUnionL s1 re1 re2 (H1: exp_match s1 re1):\n        exp_match s1 (Union re1 re2)\n    | MUnionR re1 s2 re2 (H1: 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) (H2: 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 regex2: [1; 2] =~ App (Char 1) (Char 2).\nProof.\n    apply (MApp [1] _ [2]).\n    - apply MChar.\n    - apply MChar.\nQed.\n\nFixpoint reg_exp_of_list {T} (l: list T) :=\n    match l with\n    | [] => EmptyStr\n    | x::xs => App (Char x) (reg_exp_of_list xs)\n    end.\n\nLemma empty_is_empty: forall T (s: list T),\n    ~ (s =~ EmptySet).\nProof.\n    intros T s H.\n    inversion H.\nAbort.\n(* 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.\n    intros.\n    destruct H as [P | Q].\n    - apply (MUnionL s re1 re2) in P.\n      apply P.\n    - apply (MUnionR re1 s re2) in Q.\n      apply Q.\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.", "meta": {"author": "Meowcolm024", "repo": "sf", "sha": "8ec734274600d60b0b7e905bb3d861779031bee8", "save_path": "github-repos/coq/Meowcolm024-sf", "path": "github-repos/coq/Meowcolm024-sf/sf-8ec734274600d60b0b7e905bb3d861779031bee8/lf/regex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6675785555060704}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint drop (drop_arg0 : natural) (drop_arg1 : lst) : lst\n           := match drop_arg0, drop_arg1 with\n              | x, Nil => Nil\n              | Zero, x => x\n              | Succ x, Cons y z => drop x z\n              end.\n\nTheorem drop_Nil: forall (x: natural), drop x Nil = Nil.\nProof.\n  induction x ; simpl; reflexivity.\nQed.\n\nTheorem drop_Cons: forall (x n: natural) (l: lst), drop (Succ x) (Cons n l) = drop x l.\n  induction l; induction x; simpl; reflexivity.\nQed.\n\nTheorem drop_Cons_assoc: forall (x1 x2 x3: natural) (l: lst),\n    drop x1 (drop x2 (Cons x3 l)) = drop x2 (drop x1 (Cons x3 l)).\nProof.\n  induction x1; induction x2; try (simpl; reflexivity).\n  + induction l.\n    * rewrite 2 drop_Cons. rewrite <- IHx1.\n      rewrite IHx2. rewrite 2 drop_Cons.\n      induction l.\n      - rewrite IHx1. reflexivity. \n      - rewrite 3 drop_Nil. reflexivity. \n    * simpl. rewrite 2 drop_Nil. reflexivity. \n  + intros. simpl. destruct (drop x1 l); reflexivity. \n  + intros. simpl. destruct (drop x2 l); reflexivity. \nQed.\n\nTheorem drop_assoc : forall (x : natural) (y : natural) (z : lst), eq (drop x (drop y z)) (drop y (drop x z)).\nProof.\n  induction z.\nlfind.  reflexivity.  \nAdmitted.\n\nTheorem theorem0 : forall (x : natural) (y : natural) (w : natural) (z : lst), eq (drop w (drop x (drop y z))) (drop y (drop x (drop w z))).\nProof.\n  intros.\n  rewrite (drop_assoc w x).\n  rewrite (drop_assoc w y).\n  rewrite (drop_assoc x y).\n  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/clam_lf_goal9_drop_assoc_45_drop_Cons_assoc/goal9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6675578254030395}}
{"text": "Require Import Coq.Strings.Ascii Coq.Strings.String Coq.Lists.List.\nRequire Import Coq.QArith.QArith_base.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Crypto.Util.Option.\nRequire Import Crypto.Util.OptionList.\nRequire Import Crypto.Util.Strings.ParseArithmetic.\nRequire Import Crypto.Util.Notations.\nImport ListNotations.\nLocal Open Scope option_scope.\nLocal Open Scope list_scope.\nLocal Open Scope char_scope.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\n\nLocal Open Scope parse_scope.\n\n(** From the Python:\n<<\n# given a string representing one term or \"tap\" in a prime, returns a pair of\n# integers representing the weight and coefficient of that tap\n#    \"2 ^ y\" -> [1, y]\n#    \"x * 2 ^ y\" -> [x, y]\n#    \"x * y\" -> [x*y,0]\n#    \"x\" -> [x,0]\ndef parse_term(t) :\n    if \"*\" not in t and \"^\" not in t:\n        return [int(t),0]\n\n    if \"*\" in t:\n        if len(t.split(\"*\")) > 2: # this occurs when e.g. [w - x * y] has been turned into [w + -1 * x * y]\n            a1,a2,b = t.split(\"*\")\n            a = int(a1) * int(a2)\n        else:\n            a,b = t.split(\"*\")\n        if \"^\" not in b:\n            return [int(a) * int(b),0]\n    else:\n        a,b = (1,t)\n\n    b,e = b.split(\"^\")\n    if int(b) != 2:\n        raise NonBase2Exception(\"Could not parse term, power with base other than 2: %s\" %t)\n    return [int(a),int(e)]\n>> *)\n\n(** given an expression representing one term or \"tap\" in a prime,\n    returns a pair of integers representing the coefficient and weight\n    of that tap:\n    * \"2 ^ y\" -> Some (2^y, 1)\n    * \"x * 2 ^ y\" -> Some (2^y, x)\n    * \"x * y\" -> Some (1,x*y)\n    * \"x\" -> Some (1,x)\n    *)\nFixpoint parse_term_of_Qexpr (v : Qexpr) : option (Z * Z)\n  := match v with\n     | Qv x => q <- Q_to_Z_strict x; Some (1, q)\n     | Qeopp a => v <- parse_term_of_Qexpr a; Some (fst v, -snd v)\n     | Qeadd a b => None\n     | Qesub a b => None\n     | Qemul a b => b <- parse_term_of_Qexpr b;\n                      a <- eval_Qexpr_strict a;\n                      a <- Q_to_Z_strict a;\n                      Some (fst b, a * snd b)\n     | Qediv a b => None\n     | Qepow b e => v <- eval_Qexpr_strict v; v <- Q_to_Z_strict v; Some (v, 1)\n     end%option.\n\nFixpoint Qexpr_to_add_list (v : Qexpr) : list Qexpr\n  := match v with\n     | Qeadd a b => Qexpr_to_add_list a ++ Qexpr_to_add_list b\n     | Qesub a b => Qexpr_to_add_list a ++ [Qeopp b]\n     | v => [v]\n     end.\n\n(** Given a Qexpr which is a sequence of additions and subtractions,\n    we return the value of the first component, and a list of the taps\n    for the negation of the other components *)\nDefinition parse_prime_and_taps_of_Qexpr (v : Qexpr) : option (Z * list (Z * Z))\n  := match Qexpr_to_add_list v with\n     | nil => None\n     | cons p taps\n       => taps <- Option.List.lift (List.map (fun v => parse_term_of_Qexpr (Qeopp v)) taps);\n            p <- eval_Qexpr_strict p;\n            p <- Q_to_Z_strict p;\n            Some (p, taps)\n     end.\n\nDefinition parseZ_arith_to_taps (s : string) : option (Z * list (Z * Z))\n  := v <- parseQexpr_arith s; parse_prime_and_taps_of_Qexpr v.\n\nLocal Coercion QArith_base.inject_Z : Z >-> Q.\nLocal Example parse_v25519 : parse_prime_and_taps_of_Qexpr (2^255 - 19) = Some (2^255, [(1,19)]) := eq_refl.\nLocal Example parse_25519 : parseZ_arith_to_taps \"2^255 - 19\" = Some (2^255, [(1,19)]) := eq_refl.\nLocal Example parse_p521 : parseZ_arith_to_taps \"2^521 - 1\" = Some (2^521, [(1,1)]) := eq_refl.\nLocal Example parse_p448 : parseZ_arith_to_taps \"2^448 - 2^224 - 1\" = Some (2^448, [(2^224,1); (1,1)]) := eq_refl.\nLocal Example parse_p256 : parseZ_arith_to_taps \"2^256 - 2^224 + 2^192 + 2^96 - 1\" = Some (2^256, [(2^224,1); (2^192,-1); (2^96,-1); (1,1)]) := eq_refl.\nLocal Example parse_p434 : parseZ_arith_to_taps \"2^216 * 3^137 - 1\" = Some (2^216 * 3^137, [(1,1)]) := eq_refl.\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/Strings/ParseArithmeticToTaps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6675578241949702}}
{"text": "Require Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Tactics.Consider.\nRequire Import ExtLib.Tactics.Injection.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection Eqpair.\n  Context {T U} (rT : relation T) (rU : relation U).\n\n  Inductive Eqpair : relation (T * U) :=\n  | Eqpair_both : forall a b c d, rT a b -> rU c d -> Eqpair (a,c) (b,d).\n\n  Global Instance Reflexive_Eqpair {RrT : Reflexive rT} {RrU : Reflexive rU}\n  : Reflexive Eqpair.\n  Proof. red. destruct x. constructor; reflexivity. Qed.\n\n  Global Instance Symmetric_Eqpair {RrT : Symmetric rT} {RrU : Symmetric rU}\n  : Symmetric Eqpair.\n  Proof. red. inversion 1; constructor; symmetry; assumption. Qed.\n\n  Global Instance Transitive_Eqpair {RrT : Transitive rT} {RrU : Transitive rU}\n  : Transitive Eqpair.\n  Proof. red. inversion 1; inversion 1; constructor; etransitivity; eauto. Qed.\n\n  Global Instance Injective_Eqpair a b c d : Injective (Eqpair (a,b) (c,d)) :=\n  { result := rT a c /\\ rU b d }.\n  abstract (inversion 1; auto).\n  Defined.\nEnd Eqpair.\n\nSection PairWF.\n  Variables T U : Type.\n  Variable RT : T -> T -> Prop.\n  Variable RU : U -> U -> Prop.\n\n  Inductive R_pair : T * U -> T * U -> Prop :=\n  | L : forall l l' r r',\n    RT l l' -> R_pair (l,r) (l',r')\n  | R : forall l r r',\n    RU r r' -> R_pair (l,r) (l,r').\n\n  Hypothesis wf_RT : well_founded RT.\n  Hypothesis wf_RU : well_founded RU.\n\n  Theorem wf_R_pair : well_founded R_pair.\n  Proof.\n    red. intro x.\n    destruct x. generalize dependent u.\n    apply (well_founded_ind wf_RT (fun t => forall u : U, Acc R_pair (t, u))) .\n    do 2 intro.\n\n    apply (well_founded_ind wf_RU (fun u => Acc R_pair (x,u))). intros.\n    constructor. destruct y.\n    remember (t0,u). remember (x,x0). inversion 1; subst;\n    inversion H4; inversion H3; clear H4 H3; subst; eauto.\n  Defined.\nEnd PairWF.\n\nSection PairParam.\n  Variable T : Type.\n  Variable eqT : T -> T -> Prop.\n  Variable U : Type.\n  Variable eqU : U -> U -> Prop.\n\n  Variable EDT : RelDec eqT.\n  Variable EDU : RelDec eqU.\n\n  Global Instance RelDec_equ_pair : RelDec (fun x y => eqT (fst x) (fst y) /\\ eqU (snd x) (snd y)) :=\n  { rel_dec := fun x y =>\n    if rel_dec (fst x) (fst y) then\n      rel_dec (snd x) (snd y)\n    else false }.\n\n  Variable EDCT : RelDec_Correct EDT.\n  Variable EDCU : RelDec_Correct EDU.\n\n  Global Instance RelDec_Correct_equ_pair : RelDec_Correct RelDec_equ_pair.\n  Proof.\n    constructor; destruct x; destruct y; split; simpl in *; intros;\n      repeat match goal with\n               | [ H : context [ rel_dec ?X ?Y ] |- _ ] =>\n                 consider (rel_dec X Y); intros; subst\n               | [ |- context [ rel_dec ?X ?Y ] ] =>\n                 consider (rel_dec X Y); intros; subst\n             end; intuition.\n  Qed.\nEnd PairParam.\n\nSection PairEq.\n  Variable T : Type.\n  Variable U : Type.\n\n  Variable EDT : RelDec (@eq T).\n  Variable EDU : RelDec (@eq U).\n\n  (** Specialization for equality **)\n  Global Instance RelDec_eq_pair : RelDec (@eq (T * U)) :=\n  { rel_dec := fun x y =>\n    if rel_dec (fst x) (fst y) then\n      rel_dec (snd x) (snd y)\n    else false }.\n\n  Variable EDCT : RelDec_Correct EDT.\n  Variable EDCU : RelDec_Correct EDU.\n\n  Global Instance RelDec_Correct_eq_pair : RelDec_Correct RelDec_eq_pair.\n  Proof.\n    constructor; destruct x; destruct y; split; simpl in *; intros;\n      repeat match goal with\n               | [ H : context [ rel_dec ?X ?Y ] |- _ ] =>\n                 consider (rel_dec X Y); intros; subst\n               | [ |- context [ rel_dec ?X ?Y ] ] =>\n                 consider (rel_dec X Y); intros; subst\n             end; congruence.\n  Qed.\nEnd PairEq.\n\nGlobal Instance Injective_pair T U (a :T) (b:U) c d : Injective ((a,b) = (c,d)) :=\n{| result := a = c /\\ b = d |}.\nProof. abstract (inversion 1; intuition). Defined.", "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/Pair.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.6675578095548136}}
{"text": "Require Import Coq.Program.Tactics.\nRequire Import ProofIrrelevance.\n\nSet Primitive Projections.\n\nRecord Magma {T : Type} :=\n  { mu : T -> T -> T\n  }.\n\n(* Possibly separate this out at some point. *)\n\n(** * Magma homomorphisms.\n\nMust obey this law:\n\\(f (a * b) = f(a) * f(b)\\)\n*)\nRecord MagmaHomomorphism {A B} (M : @Magma A) (N : @Magma B) :=\n  { magma_hom : A -> B;\n    magma_hom_law :\n      forall (a b : A),\n        magma_hom (mu M a b) = mu N (magma_hom a) (magma_hom b)\n  }.\n\n(** * Composition of maps. *)\nProgram Definition magma_hom_composition\n        {T U V : Type}\n        {A : @Magma T}\n        {B : @Magma U}\n        {C : @Magma V}\n        (map1 : MagmaHomomorphism A B)\n        (map2 : MagmaHomomorphism B C) :\n  MagmaHomomorphism A C :=\n  {| magma_hom := fun a => (magma_hom B C map2) ((magma_hom A B map1) a) |}.\nNext Obligation.\nProof.\n  destruct A, B, C, map1, map2.\n  simpl in *.\n  rewrite magma_hom_law0.\n  rewrite magma_hom_law1.\n  trivial.\nQed.\n\n(** * Equality of maps, assuming proof irrelevance. *)\nTheorem magma_hom_eq : forall A B F G (N M : MagmaHomomorphism F G),\n    @magma_hom A B F G N = @magma_hom A B F G M ->\n    N = M.\nProof.\n  intros.\n  destruct N, M.\n  simpl in *.\n  subst.\n  f_equal.\n  intros.\n  apply proof_irrelevance.\nQed.\n\n(** * Associativity of composition of maps. *)\nProgram Definition magma_hom_composition_assoc\n        {T : Type}\n        {A B C D : @Magma T}\n        (f : MagmaHomomorphism A B)\n        (g : MagmaHomomorphism B C)\n        (h : MagmaHomomorphism C D) :\n  magma_hom_composition f (magma_hom_composition g h) =\n  magma_hom_composition (magma_hom_composition f g) h.\nProof.\n  destruct f, g, h.\n  apply magma_hom_eq.\n  simpl.\n  reflexivity.\nQed.\n\n(** * Identity map. *)\nProgram Definition magma_hom_id\n        {A : Type}\n        {M : @Magma A} :\n  MagmaHomomorphism M M :=\n  {| magma_hom := fun a => a |}.", "meta": {"author": "relrod", "repo": "ct", "sha": "abd8b0067e219ee4867f7136bdf1b35885224cb4", "save_path": "github-repos/coq/relrod-ct", "path": "github-repos/coq/relrod-ct/ct-abd8b0067e219ee4867f7136bdf1b35885224cb4/CT/Algebra/Magma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6675523190219004}}
{"text": "Require Import MSets MSetAVL ZArith 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 THIS_ALREADY_EXISTS_IN_STDLIB_SO_LETS_NOT_INTERFERE.\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 *)\nPrint comparison.\n(* Inductive comparison := Eq | Lt | Gt. *)\n\nPrint CompSpec.\n\n\n\nModule Type OrderedType.\n\n  (* The \"Ocaml part\" *)\n\n  Parameter t : Type.\n  Parameter compare : t -> t -> comparison.\n\n  (* The logical specification:\n     [compare] is required to give correct answers with respect to some\n     particular equivalence relation [eq] and strict order [lt]. *)\n\n  Parameter eq : t -> t -> Prop.\n  Parameter lt : t -> t -> Prop.\n  Declare Instance eq_equiv : Equivalence eq. (* reflexive, symmetric, transitive *)\n  Declare Instance lt_strorder : StrictOrder lt. (* irreflexive, transitive *)\n  Declare Instance lt_compat : Proper (eq==>eq==>iff) lt. (* rewriting w.r.t. eq in lt *)\n  Axiom compare_spec : forall x y : t, CompSpec eq lt x y (compare x y).\n\n  (* Artificially, we asks for another function, for OrderedType to be\n     coercible to another interface (see DecidableType).  *)\n\n  Parameter eq_dec : forall x y, { eq x y }+{ ~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 compare := Zcompare.\n\n  Definition eq := @eq Z.\n  Definition lt := Zlt.\n  Instance eq_equiv : Equivalence eq := {}.\n  Instance lt_strorder : StrictOrder lt := {}.\n  Instance lt_compat : Proper (eq==>eq==>iff) lt.\n  Proof. intros x x' Hx y y' Hy; rewrite Hx, Hy; split; auto. Qed.\n  Lemma compare_spec : forall x y, CompSpec eq lt x y (compare x y).\n  Proof. exact Zcompare_spec. Qed.\n\n  Definition eq_dec : forall x y, { eq x y }+{ ~eq x y }.\n  Proof. exact Z_eq_dec. Qed.\n\nEnd Z_as_OT.\n(* /excerpt *)\n\nExtraction Z_as_OT.\n\nEnd THIS_ALREADY_EXISTS_IN_STDLIB_SO_LETS_NOT_INTERFERE.\n\n\n\n(** * Let's now build some sets of [Z] integers ... *)\n\nModule M := MSetAVL.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: *)\n\nCheck (M.elements_spec1 ens3).\n(* elements returns a lists with the same content\n   as the initial set. *)\n\nCheck (M.elements_spec2 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.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.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 raw3_ok : Ok raw3. Proof. unfold raw3, raw1, raw2; auto with *. Qed.\n\nCheck (@R.elements_spec2 raw3 raw3_ok).\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\n\n(*TODO: assert failure\n  Extraction M. *)\n\n\n\n(** * Some sets of sets ... *)\n\nModule MM := MSetAVL.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 := MSetFacts.Facts M.\n\n(* It contains mainly rephrasing of the specifications in alternative styles \n  like equivalences or boolean *)\nCheck MF.add_1.\nCheck MF.add_iff.\nCheck MF.add_b.\n\n(* More complex properties are located in the functors FSetProperties.Properties *)\nModule MP := MSetProperties.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(* TODO: MAPS NOT READY YET\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 := MSetWeakList.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_msets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.6675523170640103}}
{"text": "Require Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Program.Basics.\n\nLemma ex_iff: forall {A: Type} P Q, (forall x: A, P x <-> Q x) -> (ex P <-> ex Q).\nProof.\n  intros.\n  split; intros [x ?]; exists x; firstorder.\nQed.\n\nLemma forall_iff: forall {A: Type} P Q, (forall x: A, P x <-> Q x) -> ((forall x, P x) <-> (forall x, Q x)).\nProof. intros. firstorder. Qed.\n\nLemma and_iff_split: forall A B C D : Prop, (A <-> B) -> (C <-> D) -> (A /\\ C <-> B /\\ D).\nProof. intros. tauto. Qed.\n\nLemma and_iff_compat_l_weak: forall A B C : Prop, (A -> (B <-> C)) -> (A /\\ B <-> A /\\ C).\nProof. intros. tauto. Qed.\n\nLemma and_iff_compat_r_weak: forall A B C : Prop, (A -> (B <-> C)) -> (B /\\ A <-> C /\\ A).\nProof. intros. tauto. Qed.\n\nLemma and_or_distr_r: forall P Q R, P /\\ (Q \\/ R) <-> (P /\\ Q) \\/ (P /\\ R).\nProof.\n  intros.\n  tauto.\nQed.\n\nLemma demorgan_weak: forall P Q: Prop, P \\/ ~ P -> (~ (P /\\ Q) <-> ~ P \\/ ~ Q).\nProof.\n  intros.\n  destruct H; tauto.\nQed.\n\nLemma demorgan_weak': forall P Q: Prop, P \\/ ~ P -> (~ (~ P /\\ Q) <-> P \\/ ~ Q).\nProof.\n  intros.\n  destruct H; tauto.\nQed.\n\nLemma eq_sym_iff: forall {A} (x y: A), x = y <-> y = x.\nProof.\n  intros.\n  split; intro; congruence.\nQed.\n\nLemma sumbool_weaken_right: forall P Q Q': Prop, (Q -> Q') -> ({P} + {Q}) -> ({P} + {Q'}).\nProof.\n  intros.\n  destruct H0; [left | right]; auto.\nQed.\n\nLemma sumbool_weaken_left: forall P P' Q: Prop, (P -> P') -> ({P} + {Q}) -> ({P'} + {Q}).\nProof.\n  intros.\n  destruct H0; [left | right]; auto.\nQed.\n\nDefinition Prop_join {A} (X Y Z: A -> Prop): Prop :=\n  (forall a, Z a <-> X a \\/ Y a) /\\ (forall a, X a -> Y a -> False).\n\nDefinition Decidable (P: Prop) := {P} + {~ P}.\n\nLemma decidable_prop_decidable: forall P: Prop, Decidable P -> P \\/ ~ P.\nProof.\n  intros.\n  destruct H; [left | right]; auto.\nQed.\n\nDefinition DecidablePred (A: Type): Type := {P : A -> Prop & forall a, {P a} + {~ P a}}.\n\nDefinition app_DecidablePred {A: Type} (P: DecidablePred A) (a: A) := projT1 P a.\n\nCoercion app_DecidablePred: DecidablePred >-> Funclass.\n\nTactic Notation \"spec\" hyp(H) :=\n  match type of H with ?a -> _ =>\n    let H1 := fresh in (assert (H1: a); [|generalize (H H1); clear H H1; intro H]) end.\nTactic Notation \"disc\" := (try discriminate).\nTactic Notation \"contr\" := (try contradiction).\nTactic Notation \"congr\" := (try congruence).\nTactic Notation \"inv\" hyp(H) := inversion H; clear H; subst.\nTactic Notation  \"icase\" constr(v) := (destruct v; disc; contr; auto).\nTactic Notation \"copy\" hyp(H) := (generalize H; intro).\n\n(* TODO: This tactic is now duplicated here and in VST.msl.Coqlib2. *)\nLtac super_pattern t x :=\n  let t0 := fresh \"t\" in\n  set (t0 := t);\n  pattern x in t0;\n  cbv beta in (type of t0);\n  subst t0.\n\nRecord bijective {A B} (f: A -> B) (invf: B -> A) : Prop :=\n  {\n    injective: forall x y, f x = f y -> x = y;\n    surjective: forall x, f (invf x) = x;\n  }.\n\nLemma bijective_refl: forall {A: Type}, @bijective A A id id.\nProof. intros. split; auto. Qed.\n\nLemma bijective_sym: forall {A B} (f: A -> B) (invf: B -> A),\n    bijective f invf -> bijective invf f.\nProof.\n  intros. destruct H as [?H ?H]. split; intros.\n  - rewrite <- (H0 x), <- (H0 y), H1, H0. reflexivity.\n  - apply H, H0.\nQed.\n\nLemma bijective_trans:\n  forall {A B C} (f: A -> B) (g: B -> C) (invf: B -> A) (invg: C -> B),\n    bijective f invf -> bijective g invg ->\n    bijective (compose g f) (compose invf invg).\nProof.\n  intros. destruct H, H0. split; intros; unfold compose in *.\n  - apply injective0, injective1. assumption.\n  - rewrite surjective0. apply surjective1.\nQed.\n\nLemma bijective_map: forall {A B} (f: A -> B) (g: B -> A),\n    bijective f g -> bijective (map f) (map g).\nProof.\n  intros. destruct H. split; intros.\n  - revert y H. induction x; intros; destruct y; simpl in H; [|inversion H..]; auto.\n    f_equal. 1: apply injective0; auto. apply IHx; assumption.\n  - induction x; simpl; auto. rewrite IHx. f_equal. apply surjective0.\nQed.\n\nDefinition idempotent {A} (f: A -> A): Prop := forall x, f (f x) = f x.\n", "meta": {"author": "johndoe20190406", "repo": "RamifyCoq", "sha": "72fb538b40ee8ea641e4bf5fe6cd232756d0929c", "save_path": "github-repos/coq/johndoe20190406-RamifyCoq", "path": "github-repos/coq/johndoe20190406-RamifyCoq/RamifyCoq-72fb538b40ee8ea641e4bf5fe6cd232756d0929c/lib/Coqlib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.6674896633082666}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\nFrom compcert Require Import Raux.\nFrom compcert Require Import Defs.\nFrom compcert Require Import Float_prop.\n\nSet Implicit Arguments.\nSet Strongly Strict Implicit.\n\nSection Float_ops.\n\nVariable beta : radix.\n\nNotation bpow e := (bpow beta e).\n\nArguments Float {beta}.\n\nDefinition Falign (f1 f2 : float beta) :=\nlet '(Float m1 e1) := f1 in\nlet '(Float m2 e2) := f2 in\nif Zle_bool e1 e2\nthen (m1, (m2 * Zpower beta (e2 - e1))%Z, e1)\nelse ((m1 * Zpower beta (e1 - e2))%Z, m2, e2).\n\nTheorem Falign_spec :\nforall f1 f2 : float beta,\nlet '(m1, m2, e) := Falign f1 f2 in\nF2R f1 = @F2R beta (Float m1 e) /\\ F2R f2 = @F2R beta (Float m2 e).\nProof. hammer_hook \"Operations\" \"Operations.Falign_spec\".\nunfold Falign.\nintros (m1, e1) (m2, e2).\ngeneralize (Zle_cases e1 e2).\ncase (Zle_bool e1 e2) ; intros He ; split ; trivial.\nnow rewrite <- F2R_change_exp.\nrewrite <- F2R_change_exp.\napply refl_equal.\nomega.\nQed.\n\nTheorem Falign_spec_exp:\nforall f1 f2 : float beta,\nsnd (Falign f1 f2) = Z.min (Fexp f1) (Fexp f2).\nProof. hammer_hook \"Operations\" \"Operations.Falign_spec_exp\".\nintros (m1,e1) (m2,e2).\nunfold Falign; simpl.\ngeneralize (Zle_cases e1 e2);case (Zle_bool e1 e2); intros He.\ncase (Zmin_spec e1 e2); intros (H1,H2); easy.\ncase (Zmin_spec e1 e2); intros (H1,H2); easy.\nQed.\n\nDefinition Fopp (f1 : float beta) : float beta :=\nlet '(Float m1 e1) := f1 in\nFloat (-m1)%Z e1.\n\nTheorem F2R_opp :\nforall f1 : float beta,\n(F2R (Fopp f1) = -F2R f1)%R.\nintros (m1,e1).\napply F2R_Zopp.\nQed.\n\nDefinition Fabs (f1 : float beta) : float beta :=\nlet '(Float m1 e1) := f1 in\nFloat (Z.abs m1)%Z e1.\n\nTheorem F2R_abs :\nforall f1 : float beta,\n(F2R (Fabs f1) = Rabs (F2R f1))%R.\nintros (m1,e1).\napply F2R_Zabs.\nQed.\n\nDefinition Fplus (f1 f2 : float beta) : float beta :=\nlet '(m1, m2 ,e) := Falign f1 f2 in\nFloat (m1 + m2) e.\n\nTheorem F2R_plus :\nforall f1 f2 : float beta,\nF2R (Fplus f1 f2) = (F2R f1 + F2R f2)%R.\nProof. hammer_hook \"Operations\" \"Operations.F2R_plus\".\nintros f1 f2.\nunfold Fplus.\ngeneralize (Falign_spec f1 f2).\ndestruct (Falign f1 f2) as ((m1, m2), e).\nintros (H1, H2).\nrewrite H1, H2.\nunfold F2R. simpl.\nrewrite plus_IZR.\napply Rmult_plus_distr_r.\nQed.\n\nTheorem Fplus_same_exp :\nforall m1 m2 e,\nFplus (Float m1 e) (Float m2 e) = Float (m1 + m2) e.\nProof. hammer_hook \"Operations\" \"Operations.Fplus_same_exp\".\nintros m1 m2 e.\nunfold Fplus.\nsimpl.\nnow rewrite Zle_bool_refl, Zminus_diag, Zmult_1_r.\nQed.\n\nTheorem Fexp_Fplus :\nforall f1 f2 : float beta,\nFexp (Fplus f1 f2) = Z.min (Fexp f1) (Fexp f2).\nProof. hammer_hook \"Operations\" \"Operations.Fexp_Fplus\".\nintros f1 f2.\nunfold Fplus.\nrewrite <- Falign_spec_exp.\nnow destruct (Falign f1 f2) as ((p,q),e).\nQed.\n\nDefinition Fminus (f1 f2 : float beta) :=\nFplus f1 (Fopp f2).\n\nTheorem F2R_minus :\nforall f1 f2 : float beta,\nF2R (Fminus f1 f2) = (F2R f1 - F2R f2)%R.\nProof. hammer_hook \"Operations\" \"Operations.F2R_minus\".\nintros f1 f2; unfold Fminus.\nrewrite F2R_plus, F2R_opp.\nring.\nQed.\n\nTheorem Fminus_same_exp :\nforall m1 m2 e,\nFminus (Float m1 e) (Float m2 e) = Float (m1 - m2) e.\nProof. hammer_hook \"Operations\" \"Operations.Fminus_same_exp\".\nintros m1 m2 e.\nunfold Fminus.\napply Fplus_same_exp.\nQed.\n\nDefinition Fmult (f1 f2 : float beta) : float beta :=\nlet '(Float m1 e1) := f1 in\nlet '(Float m2 e2) := f2 in\nFloat (m1 * m2) (e1 + e2).\n\nTheorem F2R_mult :\nforall f1 f2 : float beta,\nF2R (Fmult f1 f2) = (F2R f1 * F2R f2)%R.\nProof. hammer_hook \"Operations\" \"Operations.F2R_mult\".\nintros (m1, e1) (m2, e2).\nunfold Fmult, F2R. simpl.\nrewrite mult_IZR, bpow_plus.\nring.\nQed.\n\nEnd Float_ops.\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/compcert/Operations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6674896534803484}}
{"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: Mergesort.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\n(** A modular implementation of mergesort (the complexity is O(n.log n) in\n   the length of the list) *)\n\n(* Initial author: Hugo Herbelin, Oct 2009 *)\n\nRequire Import List Setoid Permutation Sorted Orders.\n\n(** Notations and conventions *)\n\nLocal Notation \"[ ]\" := nil.\nLocal Notation \"[ a ; .. ; b ]\" := (a :: .. (b :: []) ..).\n\nOpen Scope bool_scope.\n\nLocal Coercion is_true : bool >-> Sortclass.\n\n(** The main module defining [mergesort] on a given boolean\n    order [<=?]. We require minimal hypotheses : this boolean\n    order should only be total: [forall x y, (x<=?y) \\/ (y<=?x)].\n    Transitivity is not mandatory, but without it one can\n    only prove [LocallySorted] and not [StronglySorted].\n*)\n\nModule Sort (Import X:Orders.TotalLeBool').\n\nFixpoint merge l1 l2 :=\n  let fix merge_aux l2 :=\n  match l1, l2 with\n  | [], _ => l2\n  | _, [] => l1\n  | a1::l1', a2::l2' =>\n      if a1 <=? a2 then a1 :: merge l1' l2 else a2 :: merge_aux l2'\n  end\n  in merge_aux l2.\n\n(** We implement mergesort using an explicit stack of pending mergings.\n    Pending merging are represented like a binary number where digits are\n    either None (denoting 0) or Some list to merge (denoting 1). The n-th\n    digit represents the pending list to be merged at level n, if any.\n    Merging a list to a stack is like adding 1 to the binary number\n    represented by the stack but the carry is propagated by merging the\n    lists. In practice, when used in mergesort, the n-th digit, if non 0,\n    carries a list of length 2^n. For instance, adding singleton list\n    [3] to the stack Some [4]::Some [2;6]::None::Some [1;3;5;5]\n    reduces to propagate the carry [3;4] (resulting of the merge of [3]\n    and [4]) to the list Some [2;6]::None::Some [1;3;5;5], which reduces\n    to propagating the carry [2;3;4;6] (resulting of the merge of [3;4] and\n    [2;6]) to the list None::Some [1;3;5;5], which locally produces\n    Some [2;3;4;6]::Some [1;3;5;5], i.e. which produces the final result\n    None::None::Some [2;3;4;6]::Some [1;3;5;5].\n\n    For instance, here is how [6;2;3;1;5] is sorted:\n\n<<\n       operation             stack                list\n       iter_merge            []                   [6;2;3;1;5]\n    =  append_list_to_stack  [ + [6]]             [2;3;1;5]\n    -> iter_merge            [[6]]                [2;3;1;5]\n    =  append_list_to_stack  [[6] + [2]]          [3;1;5]\n    =  append_list_to_stack  [ + [2;6];]          [3;1;5]\n    -> iter_merge            [[2;6];]             [3;1;5]\n    =  append_list_to_stack  [[2;6]; + [3]]       [1;5]\n    -> merge_list            [[2;6];[3]]          [1;5]\n    =  append_list_to_stack  [[2;6];[3] + [1]     [5]\n    =  append_list_to_stack  [[2;6] + [1;3];]     [5]\n    =  append_list_to_stack  [ + [1;2;3;6];;]     [5]\n    -> merge_list            [[1;2;3;6];;]        [5]\n    =  append_list_to_stack  [[1;2;3;6];; + [5]]  []\n    -> merge_stack           [[1;2;3;6];;[5]]\n    =                                             [1;2;3;5;6]\n>>\n    The complexity of the algorithm is n*log n, since there are\n    2^(p-1) mergings to do of length 2, 2^(p-2) of length 4, ..., 2^0\n    of length 2^p for a list of length 2^p. The algorithm does not need\n    explicitly cutting the list in 2 parts at each step since it the\n    successive accumulation of fragments on the stack which ensures\n    that lists are merged on a dichotomic basis.\n*)\n\nFixpoint merge_list_to_stack stack l :=\n  match stack with\n  | [] => [Some l]\n  | None :: stack' => Some l :: stack'\n  | Some l' :: stack' => None :: merge_list_to_stack stack' (merge l' l)\n  end.\n\nFixpoint merge_stack stack :=\n  match stack with\n  | [] => []\n  | None :: stack' => merge_stack stack'\n  | Some l :: stack' => merge l (merge_stack stack')\n  end.\n\nFixpoint iter_merge stack l :=\n  match l with\n  | [] => merge_stack stack\n  | a::l' => iter_merge (merge_list_to_stack stack [a]) l'\n  end.\n\nDefinition sort := iter_merge [].\n\n(** The proof of correctness *)\n\nLocal Notation Sorted := (LocallySorted leb) (only parsing).\n\nFixpoint SortedStack stack :=\n  match stack with\n  | [] => True\n  | None :: stack' => SortedStack stack'\n  | Some l :: stack' => Sorted l /\\ SortedStack stack'\n  end.\n\nLocal Ltac invert H := inversion H; subst; clear H.\n\nFixpoint flatten_stack (stack : list (option (list t))) :=\n  match stack with\n  | [] => []\n  | None :: stack' => flatten_stack stack'\n  | Some l :: stack' => l ++ flatten_stack stack'\n  end.\n\nTheorem Sorted_merge : forall l1 l2,\n  Sorted l1 -> Sorted l2 -> Sorted (merge l1 l2).\nProof.\ninduction l1; induction l2; intros; simpl; auto.\n  destruct (a <=? a0) as ()_eqn:Heq1.\n    invert H.\n      simpl. constructor; trivial; rewrite Heq1; constructor.\n      assert (Sorted (merge (b::l) (a0::l2))) by (apply IHl1; auto).\n      clear H0 H3 IHl1; simpl in *.\n      destruct (b <=? a0); constructor; auto || rewrite Heq1; constructor.\n    assert (a0 <=? a) by\n      (destruct (leb_total a0 a) as [H'|H']; trivial || (rewrite Heq1 in H'; inversion H')).\n    invert H0.\n      constructor; trivial.\n      assert (Sorted (merge (a::l1) (b::l))) by auto using IHl1.\n      clear IHl2; simpl in *.\n      destruct (a <=? b); constructor; auto.\nQed.\n\nTheorem Permuted_merge : forall l1 l2, Permutation (l1++l2) (merge l1 l2).\nProof.\n  induction l1; simpl merge; intro.\n    assert (forall l, (fix merge_aux (l0 : list t) : list t := l0) l = l)\n    as -> by (destruct l; trivial). (* Technical lemma *)\n    apply Permutation_refl.\n  induction l2.\n    rewrite app_nil_r. apply Permutation_refl.\n    destruct (a <=? a0).\n      constructor; apply IHl1.\n      apply Permutation_sym, Permutation_cons_app, Permutation_sym, IHl2.\nQed.\n\nTheorem Sorted_merge_list_to_stack : forall stack l,\n  SortedStack stack -> Sorted l -> SortedStack (merge_list_to_stack stack l).\nProof.\n  induction stack as [|[|]]; intros; simpl.\n    auto.\n    apply IHstack. destruct H as (_,H1). fold SortedStack in H1. auto.\n      apply Sorted_merge; auto; destruct H; auto.\n      auto.\nQed.\n\nTheorem Permuted_merge_list_to_stack : forall stack l,\n  Permutation (l ++ flatten_stack stack) (flatten_stack (merge_list_to_stack stack l)).\nProof.\n  induction stack as [|[]]; simpl; intros.\n    reflexivity.\n    rewrite app_assoc.\n    etransitivity.\n      apply Permutation_app_tail.\n      etransitivity.\n        apply Permutation_app_comm.\n      apply Permuted_merge.\n    apply IHstack.\n    reflexivity.\nQed.\n\nTheorem Sorted_merge_stack : forall stack,\n  SortedStack stack -> Sorted (merge_stack stack).\nProof.\ninduction stack as [|[|]]; simpl; intros.\n  constructor; auto.\n  apply Sorted_merge; tauto.\n  auto.\nQed.\n\nTheorem Permuted_merge_stack : forall stack,\n  Permutation (flatten_stack stack) (merge_stack stack).\nProof.\ninduction stack as [|[]]; simpl.\n  trivial.\n  transitivity (l ++ merge_stack stack).\n    apply Permutation_app_head; trivial.\n    apply Permuted_merge.\n  assumption.\nQed.\n\nTheorem Sorted_iter_merge : forall stack l,\n  SortedStack stack -> Sorted (iter_merge stack l).\nProof.\n  intros stack l H; induction l in stack, H |- *; simpl.\n    auto using Sorted_merge_stack.\n    assert (Sorted [a]) by constructor.\n    auto using Sorted_merge_list_to_stack.\nQed.\n\nTheorem Permuted_iter_merge : forall l stack,\n  Permutation (flatten_stack stack ++ l) (iter_merge stack l).\nProof.\n  induction l; simpl; intros.\n    rewrite app_nil_r. apply Permuted_merge_stack.\n    change (a::l) with ([a]++l).\n    rewrite app_assoc.\n    etransitivity.\n      apply Permutation_app_tail.\n    etransitivity.\n    apply Permutation_app_comm.\n    apply Permuted_merge_list_to_stack.\n    apply IHl.\nQed.\n\nTheorem Sorted_sort : forall l, Sorted (sort l).\nProof.\nintro; apply Sorted_iter_merge. constructor.\nQed.\n\nCorollary LocallySorted_sort : forall l, Sorted.Sorted leb (sort l).\nProof. intro; eapply Sorted_LocallySorted_iff, Sorted_sort; auto. Qed.\n\nTheorem Permuted_sort : forall l, Permutation l (sort l).\nProof.\nintro; apply (Permuted_iter_merge l []).\nQed.\n\nCorollary StronglySorted_sort : forall l,\n  Transitive leb -> StronglySorted leb (sort l).\nProof. auto using Sorted_StronglySorted, LocallySorted_sort. Qed.\n\nEnd Sort.\n\n(** An example *)\n\nModule NatOrder <: TotalLeBool.\n  Definition t := nat.\n  Fixpoint leb x y :=\n    match x, y with\n    | 0, _ => true\n    | _, 0 => false\n    | S x', S y' => leb x' y'\n    end.\n  Infix \"<=?\" := leb (at level 35).\n  Theorem leb_total : forall a1 a2, a1 <=? a2 \\/ a2 <=? a1.\n  Proof.\n    induction a1; destruct a2; simpl; auto.\n  Qed.\nEnd NatOrder.\n\nModule Import NatSort := Sort NatOrder.\n\nExample SimpleMergeExample := Eval compute in sort [5;3;6;1;8;6;0].\n\n", "meta": {"author": "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/Sorting/Mergesort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.66748965178218}}
{"text": "Set Implicit Arguments.\nRequire Import DblibTactics.\nRequire Import DeBruijn.\nRequire Import Environments.\n\n(* The syntax of types is independent of the syntax of terms, because terms\n   do not refer to types (they are not annotated with types) and types do\n   not refer to terms (there is no dependency). *)\n\n(* ---------------------------------------------------------------------------- *)\n\n(* The syntax of types. *)\n\nInductive ty :=\n\n  (* [TyEpsilon] is the type of a memory range of length zero. *)\n\n| TyEpsilon: ty\n\n  (* [TyConsecutive] is a concatenation operator for types that describe\n     memory ranges. *)\n\n| TyConsecutive: ty -> ty -> ty\n\n  (* [TyUnique T] is the type of a unique pointer to a memory block whose\n     content is described by [T]. Only a base address (i.e., an address\n     whose offset component is zero) can receive this type. *)\n\n| TyUnique: ty -> ty\n\n  (* [TyBorrowed l T] is the type of a borrowed pointer to a range of\n     memory described by [T]. An arbitrary address (i.e., not just a\n     base address) can receive this type. The parameter [l] is a lifetime\n     variable. *)\n\n| TyBorrowed: nat -> ty -> ty\n\n  (* [TyLent l T] is the type of a memory area that has been lent out.\n     The parameter [l] is a lifetime variable. *)\n\n| TyLent: nat -> ty -> ty\n\n.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* The size of types. *)\n\nFixpoint sizeof_ty (T : ty) : nat :=\n  match T with\n  | TyEpsilon =>\n      0\n  | TyConsecutive T U =>\n      sizeof_ty T + sizeof_ty U\n  | TyUnique _ =>\n      1\n  | TyBorrowed _ _ =>\n      1\n  | TyLent _ T =>\n      sizeof_ty T\n  end.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Some types are duplicable; some types are not (i.e., they are linear). *)\n\nFixpoint duplicable (T : ty) : Prop :=\n  match T with\n  | TyEpsilon =>\n      True\n  | TyConsecutive T U =>\n      duplicable T /\\ duplicable U\n  | TyUnique _ =>\n      False\n  | TyBorrowed _ _ =>\n      True\n  | TyLent _ T =>\n      duplicable T\n  end.\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/Types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6674630656311963}}
{"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 Wellfounded.\n\nSet Implicit Arguments.\n\nSection list_length_rect.\n  \n  Variables (X : Type) (P : list X -> Type).\n  \n  Hypothesis HP : forall l, (forall m, length m < length l -> P m) -> P l.\n  \n  Theorem list_length_rect : forall l, P l.\n  Proof.\n    apply well_founded_induction_type \n      with (R := fun l m => length l < length m); auto.\n    apply wf_inverse_image, lt_wf.\n  Qed.\n  \nEnd list_length_rect.\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_induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6674533007426675}}
{"text": "(* Status: success *)\n\nRequire Export ArithRing.\nRequire Export Compare_dec.\nRequire Export Wf_nat.\nRequire Export Arith.\nRequire Export Omega.\n\nTheorem minus_minus : forall a b c : nat, a - b - c = a - (b + c).\nintros a; elim a; auto.\nintros n' Hrec b; case b; auto.\nQed.\n\nRemark expand_mult2 : forall x : nat, 2 * x = x + x.\nintros x; ring.\nQed.\n\nTheorem lt_neq : forall x y : nat, x < y -> x <> y.\nunfold not in |- *; intros x y H H1; elim (lt_irrefl x);\n pattern x at 2 in |- *; rewrite H1; auto.\nQed.\nHint Resolve lt_neq.\n\nTheorem monotonic_inverse :\n forall f : nat -> nat,\n (forall x y : nat, x < y -> f x < f y) ->\n forall x y : nat, f x < f y -> x < y.\nintros f Hmon x y Hlt; case (le_gt_dec y x); auto.\nintros Hle; elim (le_lt_or_eq _ _ Hle).\nintros Hlt'; elim (lt_asym _ _ Hlt); apply Hmon; auto.\nintros Heq; elim (lt_neq _ _ Hlt); rewrite Heq; auto.\nQed.\n\nTheorem mult_lt : forall a b c : nat, c <> 0 -> a < b -> a * c < b * c.\nintros a b c; elim c.\nintros H; elim H; auto.\nintros c'; case c'.\nintros; omega.\nintros c'' Hrec Hneq Hlt;\n repeat rewrite <- (fun x : nat => mult_n_Sm x (S c'')).\nauto with *.\nQed.\n\nRemark add_sub_square_identity :\n forall a b : nat,\n (b + a - b) * (b + a - b) = (b + a) * (b + a) + b * b - 2 * ((b + a) * b).\nintros a b; rewrite minus_plus.\nrepeat rewrite mult_plus_distr_r || rewrite <- (mult_comm (b + a)).\nreplace (b * b + a * b + (b * a + a * a) + b * b) with\n (b * b + a * b + (b * b + a * b + a * a)); try (ring; fail).\nrewrite expand_mult2; repeat rewrite minus_plus; auto with *.\nQed.\n\nTheorem sub_square_identity :\n forall a b : nat, b <= a -> (a - b) * (a - b) = a * a + b * b - 2 * (a * b).\nintros a b H; rewrite (le_plus_minus b a H); apply add_sub_square_identity.\nQed.\n\nTheorem square_monotonic : forall x y : nat, x < y -> x * x < y * y.\nintros x; case x.\nintros y; case y; simpl in |- *; auto with *.\nintros x' y Hlt; apply lt_trans with (S x' * y).\nrewrite (mult_comm (S x') y); apply mult_lt; auto.\napply mult_lt; omega.\nQed.\n\nTheorem root_monotonic : forall x y : nat, x * x < y * y -> x < y.\nexact (monotonic_inverse (fun x : nat => x * x) square_monotonic).\nQed.\n\nRemark square_recompose : forall x y : nat, x * y * (x * y) = x * x * (y * y).\nintros; ring.\nQed.\n\nRemark mult2_recompose : forall x y : nat, x * (2 * y) = x * 2 * y.\nintros; ring.\nQed.\nSection sqrt2_decrease.\nVariables (p q : nat) (pos_q : 0 < q) (hyp_sqrt : p * p = 2 * (q * q)).\n\nTheorem sqrt_q_non_zero : 0 <> q * q.\ngeneralize pos_q; case q.\nintros H; elim (lt_n_O 0); auto.\nintros n H.\nsimpl in |- *; discriminate.\nQed.\nHint Resolve sqrt_q_non_zero.\n\nLtac solve_comparison :=\n  apply root_monotonic; repeat rewrite square_recompose; rewrite hyp_sqrt;\n   rewrite mult2_recompose; apply mult_lt; auto with arith.\n\nTheorem comparison1 : q < p.\nreplace q with (1 * q); try ring.\nreplace p with (1 * p); try ring.\nsolve_comparison.\nQed.\n\nTheorem comparison2 : 2 * p < 3 * q.\nsolve_comparison.\nQed.\n\nTheorem comparison3 : 4 * q < 3 * p.\nsolve_comparison.\nQed.\nHint Resolve comparison1 comparison2 comparison3: arith.\n\nTheorem comparison4 : 3 * q - 2 * p < q.\napply plus_lt_reg_l with (2 * p).\nrewrite <- le_plus_minus; try (simple apply lt_le_weak; auto with arith).\nreplace (3 * q) with (2 * q + q); try ring.\napply plus_lt_le_compat; auto.\nrepeat rewrite (mult_comm 2); apply mult_lt; auto with arith.\nQed.\n\nRemark mult_minus_distr_l : forall a b c : nat, a * (b - c) = a * b - a * c.\nintros a b c; repeat rewrite (mult_comm a); apply mult_minus_distr_r.\nQed.\n\nRemark minus_eq_decompose :\n forall a b c d : nat, a = b -> c = d -> a - c = b - d.\nintros a b c d H H0; rewrite H; rewrite H0; auto.\nQed.\n\nTheorem new_equality :\n (3 * p - 4 * q) * (3 * p - 4 * q) = 2 * ((3 * q - 2 * p) * (3 * q - 2 * p)).\nrepeat rewrite sub_square_identity; auto with arith.\nrepeat rewrite square_recompose; rewrite mult_minus_distr_l.\napply minus_eq_decompose; try rewrite hyp_sqrt; ring.\nQed.\nEnd sqrt2_decrease.\nHint Resolve lt_le_weak comparison2: sqrt.\n\nTheorem sqrt2_not_rational :\n forall p q : nat, q <> 0 -> p * p = 2 * (q * q) -> False.\nintros p q; generalize p; clear p; elim q using (well_founded_ind lt_wf).\nclear q; intros q Hrec p Hneq; generalize (neq_O_lt _ (sym_not_equal Hneq));\n intros Hlt_O_q Heq.\napply (Hrec (3 * q - 2 * p) (comparison4 _ _ Hlt_O_q Heq) (3 * p - 4 * q)).\napply sym_not_equal; apply lt_neq; apply plus_lt_reg_l with (2 * p);\n rewrite <- plus_n_O; rewrite <- le_plus_minus; auto with *.\napply new_equality; auto.\nQed.\n\n", "meta": {"author": "scottviteri", "repo": "ManipulateProofTrees", "sha": "7aeaf156031d80726c7a8cf9b6fce0b4eefd3fe7", "save_path": "github-repos/coq/scottviteri-ManipulateProofTrees", "path": "github-repos/coq/scottviteri-ManipulateProofTrees/ManipulateProofTrees-7aeaf156031d80726c7a8cf9b6fce0b4eefd3fe7/ProofSourceFiles/sqrt2_not_rational.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6674532911072324}}
{"text": "Require Import Arith.\nRequire Import Arith Omega.\nRequire Import NAxioms NSub NZDiv.\nRequire Import region.\nRequire Import option.\nRequire Import clist.\nRequire Import listlist.\n\n(* Permet d'ajouter le prefixe d'une region à l'ensemble des élements d'une liste de region.\n   Exemple: prefix_list (II Z) [OO Z, IO Z] => [ II OO Z, II IO Z] *)\nFixpoint prefix_list(r: region)(l:clist region): clist region :=\nmatch l with\n| nil => l\n| cons n l' => cons (concat_region r n) (prefix_list r l')  \nend.\n\nFixpoint suffix_list(r: region)(l:clist region): clist region :=\nmatch l with\n| nil => l\n| cons n l' => cons (concat_region n r) (suffix_list r l')  \nend.\n\n(* Fixpoint prefix_list_bis(r: region -> region)(l:clist region): clist region :=\nmatch l with\n| nil => l\n| cons n l' => cons (r n) (prefix_list_bis r l')  \nend. *)\n\nEval compute in prefix_list (II Z) [OO Z, IO Z].\n\nFixpoint prefix_mat(r: region)(m:listlist region): listlist region :=\nmatch m with\n| lnil => m\n| lcons v m' => lcons (prefix_list r v) (prefix_mat r m')\nend.\n\nFixpoint suffix_mat(r: region)(m:listlist region): listlist region :=\nmatch m with\n| lnil => m\n| lcons v m' => lcons (suffix_list r v) (suffix_mat r m')\nend.\n\nEval compute in prefix_mat (II Z) '{[OO Z, IO Z],[OI Z]}.\n\n(* Fixpoint prefix_mat_bis(r: region -> region)(m:listlist region): listlist region :=\nmatch m with\n| lnil => m\n| lcons v m' => lcons (prefix_list_bis r v) (prefix_mat_bis r m')\nend. *)\n\n(* Permet d'effectuer la rotation des régions à chaque partitionnement du plan.\n   Voir la fonction f(x) du poly. *)\nDefinition rot_nat (n : nat) : region -> region :=\n    match n mod 4 with\n    | 0 => OO\n    | 1 => OI\n    | 2 => II\n    | 3 => IO\n    | _ => OO\n    end.\n\n(* Quel que soit le niveau de partionnement, on peut récupérer la plus petite matrice\n   contenant 4 regions élementaires. Cette matrice à donc 2 lignes et 2 colonnes.\n   On a deux possibilités pour partionner le plan:\n   - on peut partir de cette matrice pour partionner le plan (approche bottom-up).\n   - on peut partir du partionnement de niveau n et construire le partionnement n+1 en concatenant\n   le préfixe de chaque région élémentaire à la matrice base_matrix (approche top-down). *)\nDefinition get_base_matrix(n:nat) : listlist region := \n'{[ (rot_nat n) Z, rot_nat (n+3) Z ], [(rot_nat (n+1)) Z, (rot_nat (n+2)) Z ] }.\n\n(* Equivalent à: \n(vertcat   (horcat '{[((rot_nat n) Z)]}   '{[(rot_nat (n+1)) Z ]} )\n           (horcat '{[(rot_nat (n+3) Z)]} '{[(rot_nat (n+2)) Z]}  )).\n*)\n\nEval compute in get_base_matrix 0.\n\n(* Approche bottom-up: On part de la matrice de base de niveau n. En concatenant cette matrice \n   sur les 4 quarts d'une nouvelle matrice et en ajoutant à chaque quart la région appopriée de \n   la matrice de base de niveau n-1, on obtient un partitionnement pour la matrice de niveau n-1.\n   En effectuant cette opération n fois on obtient le partitionnement de niveau n. \n   \n   Le parametre r correspond à la première region du partitionnement (soit OO, OI, II ou IO). \n   La fonction auxiliaire sert à différencier le cas n=0 et n= S n. \n   Dans le cas n=0 on renvoi seulement la première region. Dans le cas n=S n on met en place la recursivité \n   sur la matrice de base de niveau n *)\nDefinition mat_part_bup (n:nat)(r: region):listlist region :=\nmatch n with\n| O => '{[r]}\n| S n' => suffix_mat r ((fix from_n_to_0 (n:nat)(m:listlist region):listlist region :=\n          match n with\n          | O => m\n          | S n' => let base := get_base_matrix n' in (\n                    from_n_to_0 n' (vertcat (horcat (suffix_mat (option_elim Z (base _[0,0])) m) (suffix_mat (option_elim Z (base _[0,1])) m ))\n                                            (horcat (suffix_mat (option_elim Z (base _[1,0])) m) (suffix_mat (option_elim Z (base _[1,1])) m ))) )\n          end) n' (get_base_matrix n'))\nend.\n\nEval compute in mat_part_bup 2 (OO Z).\n\n\n(* Approche top-down: On remplace chaque element d'une matrice correspondant à \n   un partitionnement de niveau n-1 par la matrice de base de niveau n. Cette \n   nouvelle matrice correspond au partitionnement de niveau n. \n\n   On commence par définir une fonction qui transforme une liste en une matrice \n   en concatenant le prefixe de chaque élement de la liste à la matrice base_matrix. *)\nFixpoint parse_list (l:clist region)(n:nat): listlist region :=\nmatch l with\n| nil => lnil\n| cons r l' => vertcat (suffix_mat r (get_base_matrix n)) (parse_list l' n)\nend.\n\nEval compute in parse_list [OO (OO Z)] 0.\nEval compute in parse_list [OO Z] 0.\n\n(* On définit une fonction qui transforme la matrice correspondant à un partionnement \n   de niveau n, en une matrice correspondant à un partionnement de niveau n+1.  *)\nFixpoint parse_mat (m:listlist region)(n:nat): listlist region :=\nmatch m with\n| lnil => lnil\n| lcons v m' => horcat (parse_list v n) (parse_mat m' n)\nend.\n\nEval compute in parse_mat '{[OO Z, OI Z],[IO Z, II Z]} 0.\nEval compute in parse_mat '{[OO Z]} 0.\n\n(* Enfin, on définit la fonction inductive de partionnement du plan *)\nDefinition mat_part_tdown (n:nat)(m:listlist region):listlist region :=\n(* La fonction sub sert uniquement à cacher le compteur dans les paramètres de mat_part_tdown *)\n(fix sub(n acc:nat)(m:listlist region):listlist region :=\nmatch n with\n| O => m\n| S n' => sub n' (acc+1) (parse_mat m acc) \nend) n 0 m.\n\nEval compute in mat_part_tdown 1 '{[OO Z]}. \nEval compute in mat_part_tdown 2 '{[OO Z]}.\n\n\n(* Implementation de l'algo du poly. Probleme à détailler. *)\nDefinition mat_part_tdown_poly (n:nat)(m:listlist region):listlist region :=\n  let sub := (fix sub(n acc:nat)(m:listlist region):listlist region :=\n    match n with\n    | O => m\n    | S n' => let upright := (prefix_mat ((rot_nat (acc+3)) Z) m) in (\n              let upleft := (prefix_mat ((rot_nat (acc)) Z) m) in (\n              let downright := (prefix_mat ((rot_nat (acc+2)) Z) m) in(\n              let downleft := (prefix_mat ((rot_nat (acc+1)) Z) m) in (\n                sub (n') (acc+1) (vertcat (horcat upleft upright) (horcat downleft downright))\n              ) ) ) )\n    end ) \n    in sub n 0 m.\n\nEval compute in mat_part_tdown_poly 2 '{[OO Z]}.\n\n\n(* Liste des regions voisines d'une région contenue dans une liste de regions. *)\nDefinition voisins_list (l:clist region)(r:region):clist region :=\nif is_in_list l r then \n(* on peut se permettre de mettre une valeur par défaut de 0 puisqu'on a vérifié \n   que r était dans l. La valeur par défaut ne sera donc jamais utilisée. *)\n  let row := option_elim 0 (get_row_region l r) in ( \n            match (0 <? row), (row+1 <? list_count l) with\n            | true, true => [ get_list_reg l (row-1), get_list_reg l (row+1) ]\n            | true, false => [ get_list_reg l (row-1) ]\n            | false, true => [ get_list_reg l (row+1) ]\n            | false, false => nil\n            end)\nelse\n  nil.\n\n(* le match est equivalent à:\n            if andb (0 <? row) (row <? ((list_count l)-1)) then\n              get_list_reg l (row-1) :: get_list_reg l (row+1) :: nil\n            else if 0 <? row then\n              [ get_list_reg l (row-1) ]\n            else if row <? ((list_count l)-1) then\n              [ get_list_reg l (row+1) ]\n            else\n              nil )\n*)\n\n(* Liste des regions voisines de l'élement situé à la position row d'une liste de regions.\n   La différence avec la fonction ci-dessus est que l'élement à la postion row est inclus \n   dans la liste de regions voisines.\n   Cette distinction est utile pour la fonction ci-après. *)\nDefinition voisins_list_row (l:clist region)(row:nat):clist region :=\nif row <? (list_count l)  then\n           match (0 <? row), (row+1 <? list_count l) with\n            | true, true => [ get_list_reg l (row-1), get_list_reg l row, get_list_reg l (row+1) ]\n            | true, false => [ get_list_reg l (row-1), get_list_reg l row ]\n            | false, true => [ get_list_reg l row, get_list_reg l (row+1) ]\n            | false, false => [ get_list_reg l row ]\n            end\nelse\n  nil.\n\n(* le match equivaut à:\n            if andb (0 <? row) (row <? ((list_count l)-1)) then\n              get_list_reg l (row-1) :: get_list_reg l row :: get_list_reg l (row+1) :: nil\n            else if 0 <? row then\n              get_list_reg l (row-1) :: get_list_reg l row :: nil\n            else if row <? ((list_count l)-1) then\n              get_list_reg l row :: get_list_reg l (row+1) :: nil\n            else\n              get_list_reg l row\n  *)\n\nEval compute in voisins_list [OO Z, OI Z, II Z, IO Z] (II Z). \nEval compute in voisins_list [OO Z, OI Z, II Z, IO Z] (IO Z).  \nEval compute in voisins_list_row [OO Z, OI Z, II Z, IO Z] 3.              \n\n(* Liste des regions voisines d'une région contenue dans le plan. *)\nFixpoint voisins_mat (m:listlist region)(r:region):clist region :=\nif is_in_mat m r then\n  let col := option_elim 0 (get_col_region m r) in (\n    let row := option_elim 0 (get_row_region (get_col m col) r) in (\n      match (0 <? col), (col+1 <? mat_count m) with\n      | true, true => voisins_list_row (get_col m (col-1)) row ++ voisins_list (get_col m col) r ++ voisins_list_row (get_col m (col+1)) row\n      | true, false => voisins_list_row (get_col m (col-1)) row ++ voisins_list (get_col m col) r\n      | false, true => voisins_list (get_col m col) r ++ voisins_list_row (get_col m (col+1)) row\n      | false, false => voisins_list (get_col m col) r \n      end ) )\nelse nil.\n\n(* le match equivaut à :\n    if andb (0 <? col) (col <? ((mat_count m)-1)) then\n      voisins_list_row (get_col m (col-1)) row ++ voisins_list (get_col m col) r ++ voisins_list_row (get_col m (col+1)) row\n    else if 0 <? col then\n              voisins_list_row (get_col m (col-1)) row ++ voisins_list (get_col m col) r\n    else if col <? ((mat_count m)-1) then\n              voisins_list (get_col m col) r ++ voisins_list_row (get_col m (col+1)) row\n    else\n              voisins_list (get_col m col) r ))\n  *)\n\nEval compute in voisins_mat '{[OO Z, II Z, OO Z],[II Z, OI Z, OO Z], [II Z, OO Z, II Z]} (OI Z).\n\nDefinition est_voisin (r1 r2:region)(m:listlist region): bool := \nis_in_list (voisins_mat m r1) r2.\n\nDefinition diff (n m:nat): nat :=\nif (n<?m) then m-n\nelse n-m.\n\nEval compute in diff 2 5.\n\n(* Calcul du nombre de regions élementaires maximum qui séparent 2 régions appartenant à la matrice des régions.\n   Ce maximum est calculé selon l'axe vertical et l'axe horizontal de la matrice.\n   L'interêt de cette fonction est de calculer la largeur minimum du carré contenant 2 régions du plan.\n   La largeur de ce carré permettra de déterminer si une region r1 est dans A0 par rapport à une autre region r2. *)\nFixpoint distance_regions_elem (r1 r2:region)(m: listlist region): option :=\n  let (col1, row1) := get_col_row_region m r1 in (\n  let (col2, row2) := get_col_row_region m r2 in (\n    match col1, col2, row1, row2 with\n    | Some c1, Some c2, Some r1, Some r2 => Some (Nat.max (diff c1 c2) (diff r1 r2))\n    | _, _, _, _ => None \n    end\n  )).\n\nEval compute in (mat_part_tdown 2 '{[OO Z]}).\nEval compute in distance_regions_elem (OO(OO(OI Z))) (OO(OI(IO Z))) (mat_part_tdown 2 '{[OO Z]}).\n\n(* ############# Preuves diverses ############### *)\n\nCheck plus_comm.\nCheck plus_assoc.\n\nLemma mod_exhaustive (n m:nat): \nm <> 0 -> ((n + m) mod m) = (n mod m).\nintros.\nrewrite Nat.add_mod.\nrewrite Nat.mod_same.\nrewrite plus_0_r.\nrewrite Nat.mod_mod.\nreflexivity.\nassumption.\nassumption.\nassumption.\nQed.\n\nTheorem rot_nat_mod_4 (n:nat): \nrot_nat (4+n) = rot_nat n.\nProof. \n  unfold rot_nat. \n  rewrite plus_comm. \n  rewrite mod_exhaustive. \n  reflexivity. \n  discriminate. \nQed.\n\n(* Preuve de l'auto-similarité de la disposition des numéros : toutes les quatre itérations du processus\nde partitionnement, on obtient la même disposition des numéros pour les regions élementaires. *)\nTheorem base_matrix_mod_4 (n:nat): \nget_base_matrix n = get_base_matrix (n+4).\nProof. \n  unfold get_base_matrix. \n  simpl. \n  rewrite <- (plus_comm 4). \n  rewrite <- ?plus_assoc. \n  rewrite ?rot_nat_mod_4. \n  reflexivity.\nQed.\n(* TODO: Montrer qu'une partition est formée à partir de base_matrix ? evident ? *)\n \nCheck nat_ind.\n\n(*\nTheorem foo {A:Type}(m1 m2:listlist A): \nvertcat m1 m2 = { } -> (m1 = lnil) /\\ (m2 = lnil) .\nProof.\n  Admitted. *)\n\nTheorem base_matrix_is_square (n:nat): \nis_square_matrix (get_base_matrix n) = true.\nProof. \n  reflexivity.\nQed.\n\n(* TODO: Preuve que le partionnement est une matrice carré si on commence par OO Z ou n'importe qu'elle matrice carré *)\nTheorem is_partition_square (n:nat)(m:listlist region): is_square_matrix m = true -> is_square_matrix (mat_part_tdown n m) = true .\nProof.\n   Admitted.\n\n(* Check Nat.sub_0_r. \n  \nTheorem get_col_lcons {A:Type}(m:listlist A)(l:clist A)(col:nat): \nget_col (lcons l m)  (S col) = get_col m col .\nProof.\n  simpl.\n  reflexivity. \nQed.\n\nTheorem get_col_0_lcons {A:Type}(m:listlist A)(l:clist A): \nget_col (lcons l m) 0 = l .\nProof.\n  reflexivity.\nQed. \n\nLemma add_l_0 n : n + 0 = n.\n  rewrite plus_comm.\n  apply Nat.add_0_l.\nQed.\n\nLemma O_lt_Sn (n:nat): 0 < S n.\nProof.\n  rewrite Nat.lt_succ_r. \n  apply Nat.le_0_l.\nQed.\n\nLemma O_lt_Sn_bis (n:nat): 0 <? S n = true.\n  rewrite Nat.ltb_lt. \n  apply O_lt_Sn.\nQed. *)", "meta": {"author": "ArthurWenger", "repo": "Coq", "sha": "b782f5f14f8e6d7f4e7a174385c7d2c5434bafb5", "save_path": "github-repos/coq/ArthurWenger-Coq", "path": "github-repos/coq/ArthurWenger-Coq/Coq-b782f5f14f8e6d7f4e7a174385c7d2c5434bafb5/TER L3/Code/partition_plan.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6674532885567178}}
{"text": "Require Import Arith.\n\n(** ** reflexivity\n\nreflexivity は X = X という命題を証明する tactic です。\n\nSSReflect ではふつう <<by []>> などで済ますのであまり使いませんが、\n等式の扱いの説明をするのに都合がいいので説明しましょう。\n\n*)\n\nGoal 0 = 0.\nProof.\n  reflexivity.\n  Show Proof.\n(**\n<<\neq_refl\n>>\n\nなんか、省略されているっぽいので Display all low-level contents を有効にして\nShow Proof をやり直すと、以下のようになります。\n\n<<\n(@eq_refl nat O)\n>>\n\nO というのは 0 です。\n\nCoq の theories/Init/Logic.v をみると、eq は以下のように定義されています。\n\n<<\nInductive eq (A:Type) (x:A) : A -> Prop :=\n    eq_refl : x = x :>A\nwhere \"x = y :> A\" := (@eq A x y) : type_scope.\nNotation \"x = y\" := (x = y :>_) : type_scope.\n>>\n\nちょっといろいろと複雑ですが、これは eq という型と\neq 型の値を構成する eq_refl というコンストラクタを定義しています。\nただし、パラメータがついているので\n単にひとつの型とコンストラクタを定義しているわけではありません。\n\nAbout で eq 定義を調べてみましょう。\n(Display implicit arguments を有効、Display notations を無効にしておきます)\n*)\nAbout eq.\n(**\n<<\neq : forall (A : Type) (_ : A) (_ : A), Prop\n>>\n\nこれをみると、eq は A という型と、A型の値ふたつを受け取って、\n命題を返す関数であることがわかります。\n\nコンストラクタの eq_refl も調べてみましょう。\n*)\nAbout eq_refl.\n(**\n<<\neq_refl : forall (A : Type) (x : A), @eq A x x\n>>\n\neq_refl は A という型と A 型の値 x を受け取って @eq A x x という型の値を返す関数\nであることがわかります。\n\nカリーハワード対応により命題と型は同型なので、\neq が命題を返すというのと、\n@eq A x x が型というのは同じことです。\n\nさて、eq は 3つのパラメータをとるので、\n@eq A a b というように 3つパラメータを与えれば具体的な型になります。\nたとえば、@eq nat 1 2 はひとつの具体的な型です。\nそれに対して、コンストラクタが返す値の型は @eq A x x なので、\n必ず x と y は等しくなります。\nつまり、@eq_refl nat 1 という値の型は @eq nat 1 1 という型であり、\neq_refl で @eq nat 1 2 という型の値を作ることはできません。\n\nそして、eq_refl 以外で eq 型の値を作ることはできません。\n（Inductive というのは帰納ということで、帰納的に定義する、というのはそういうことです。\nまじめに帰納的定義を書くときには「以上のやりかたで作れるものだけがうんたら」などと書きますよね。）\n\nついでにいえば、リストの cons みたいな\n（リスト型の値を引数として受け取る）コンストラクタと違って、\neq_refl は eq 型の値を受け取る引数を持たないので、\neq 型の値を作るには eq_refl を一回使う以外の方法はありません。\n\n結局、@eq A a b という型は、\na と b が等しい場合は eq_refl によって構成されるただひとつの値を持ちます。\nそして、a と b が等しくない場合はまったく値をもちません。\n\nこの性質により、@eq A a b という型に対してその型に適合する値を作れるならば、\na と b は等しいということがいえるわけです。\nつまり、a と b が等しいという命題や証明を eq 型で実現できるわけです。\n*)\nQed.\n\n(**\nさて、ここで問題は「等しい」というのはいったいどういう意味か、という点です。\nまぁ、最初の 0 = 0 のように、完全に同じ形であれば等しいのはそうでしょうが、\n異なる形でも等しいことはないのでしょうか。\nたとえば、2 + 4 = 5 + 1 はどうでしょうか。\n\nということで、試してみましょう。\n*)\n\nGoal 2 + 4 = 5 + 1.\nProof.\n  reflexivity.\n  Show Proof.\n(**\n<<\n(@eq_refl nat (5 + 1))\n>>\n\nどうやら問題なく証明できてしまうようです。\n証明項は (@eq_refl nat (5 + 1)) です。\n\nどうも、reflexivity は等式の右辺を eq_refl の引数にする感じです。\n\nそうでない証明項は許されるのか、exact で証明項を与えて試してみましょう。\n*)\nQed.\n\nGoal 2 + 4 = 5 + 1.\nProof.\n  exact (eq_refl 6).\n  Show Proof.\n(**\n<<\n(@eq_refl nat 6)\n>>\n*)\nQed.\n\n(**\nとくに問題なく証明できました。\n\nつまり、eq_refl 6 という項は\n@eq nat (2 + 4) (5 + 1) という型の値として正しく受け付けられるというわけです。\n\n「eq_refl は A という型と A 型の値 x を受け取って @eq A x x という型の値を返す関数」\nと上で述べましたが、ここで eq_refl の引数として指定した x は 6 です。\nしたがって、eq_refl 6 は @eq nat 6 6 型の値なわけですが、\nCoq はここで、この型が @eq nat (2 + 4) (5 + 1) 型と等しいかどうか確認します。\n具体的には、計算を進めて同じ項になるかどうかを確認します。\n2 + 4 や 5 + 1 は変数が入っていないので計算を最後まで行うことができ、その結果は 6 です。\nそのため、Coq は @eq nat 6 6 型と @eq nat (2 + 4) (5 + 1) 型が等しいことを確認でき、\nerefl 6 が @eq nat (2 + 4) (5 + 1) 型の要素であることを判断できます。\n\nこの、「計算を進めて同じ項になる」ようなものを convertible といいます。\n正確な定義は\n% Coq Reference Manual, 4.3 Conversion rules %\n# <a href=\"https://coq.inria.fr/refman/cic.html&#35;conv-rules\">Coq Reference Manual, 4.3 Conversion rules</a> #\nに書いてあります。\n\n*)\n\n(**\n計算を進めても等しさを確認できない場合もあります。\n*)\n\nSection AddComm.\n\nVariable n : nat.\n\nGoal n + 1 = 1 + n.\nProof.\n  Fail reflexivity.\n(**\nここでは n という自然数の変数があって、n + 1 と 1 + n が等しいことを証明しようとしています。\nところが、残念なことに、reflexivity は失敗します。\n\nCoq で n + 1 と 1 + n がどこまで計算を進められるか、Compute というコマンドで\n実際に計算を行って確かめてみましょう。\n*)\n  Compute n + 1.\n(**\n<<\n     = (fix Ffix (x x0 : nat) {struct x} : nat :=\n          match x with\n          | 0 => x0\n          | S x1 => S (Ffix x1 x0)\n          end) n 1\n     : nat\n>>\nn + 1 というのは、なにか fix とかいうもので始まる関数が展開されて、\nそこで止まってしまいました。\nこの関数は加算の関数で、最初の引数が 0 かそれ以外かで場合分けを行って計算を行います。\nところが、最初の引数は変数の n であり、これが 0 かどうかは不明です。\nそのため、計算がここで止まってしまうのです。\n\n逆に、最初の引数が変数ではなく、具体的な自然数が与えられれば、計算を進めることができます。\n1 + n はその例であり、こちらはもっと計算が進みます。\n*)\n  Compute 1 + n.\n(**\n<<\n     = S n\n     : nat\n>>\n1 + n では、かなり単純な項になるまで計算が進んでいます。\n\nというわけで、n + 1 と 1 + n では、計算を進めても同じ項にたどり着けないので、\nreflexivity は失敗してしまうのです。\n*)\nAbort.\n\nEnd AddComm.\n\n(**\nあと、いちおう注意しておくと、\nreflexivity は完全に計算を進めるわけではありません。\n*)\nGoal 2 ^ 100 = 2 ^ 100.\nProof.\n  reflexivity.\n  Show Proof.\n(**\n<<\n(@eq_refl nat (2 ^ 100))\n>>\n\n2 ^ 100 というのは 2 の 100乗で、本当に計算しようとすると、メモリがあふれてしまいます。\n（Coq の自然数はペアノの自然数なので、2^100 を計算すると、\nS を 2^100 個メモリに並べる必要がありますが、\nこれを素朴に実装すると 64ビットのメモリ空間でも足りません。\nそして、Coq はいまのところ素朴に実装しているのです。\nどうにかしてほしいところですが。）\n\nしかし、ここの reflexivity でメモリがあふれないことからわかるように、\n計算を進めなくても同じ項であることがわかるなら、それは問題なく判断してくれます。\n*)\nQed.\n\n\n", "meta": {"author": "akr", "repo": "coq-curry-howard", "sha": "37a7f3afc07bb17e49ec915be1a1a2ddb67a5ee5", "save_path": "github-repos/coq/akr-coq-curry-howard", "path": "github-repos/coq/akr-coq-curry-howard/coq-curry-howard-37a7f3afc07bb17e49ec915be1a1a2ddb67a5ee5/theories/reflexivity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6674532839089872}}
{"text": "(*******************************************************************************)\n(* Chapter 7.8: Equivalent Categories                                          *)\n(*******************************************************************************)\n\nGeneralizable All Variables.\nRequire Import Notations.\nRequire Import Categories_ch1_3.\nRequire Import Functors_ch1_4.\nRequire Import Isomorphisms_ch1_5.\nRequire Import NaturalIsomorphisms_ch7_5.\n\n(* Definition 7.24 *)\nClass EquivalentCategories `(C:Category)`(D:Category){Fobj}{Gobj}(F:Functor C D Fobj)(G:Functor D C Gobj) :=\n{ ec_forward  : F >>>> G ≃ functor_id C\n; ec_backward : G >>>> F ≃ functor_id D\n}.\n\n\n(* FIXME *)\n(* Definition 7.25: TFAE: F is an equivalence of categories, F is full faithful and essentially surjective *)\n", "meta": {"author": "heades", "repo": "cat-theory", "sha": "e5eabd6983fb79ac25e1a1a2af90a47494620e08", "save_path": "github-repos/coq/heades-cat-theory", "path": "github-repos/coq/heades-cat-theory/cat-theory-e5eabd6983fb79ac25e1a1a2af90a47494620e08/src/EquivalentCategories_ch7_8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6673437871584096}}
{"text": "Require Import Nijn.Nijn.\nOpen Scope poly_scope.\n\nInductive base_types := \n| Ca  \n| Clist.\n\nGlobal Instance decEq_base_types : decEq base_types.\nProof.\n  decEq_finite.\nDefined.\n\n\nDefinition a := Base Ca.\nDefinition list := Base Clist.\n\nInductive fun_symbols := \n| Tcons  \n| Tmap  \n| Tnil.\n\nGlobal Instance decEq_fun_symbols : decEq fun_symbols.\nProof.\n  decEq_finite.\nDefined.\n\n\nDefinition fn_arity fn_symbols := \n  match fn_symbols with\n  | Tcons  =>  a ⟶ list ⟶ list\n  | Tmap  =>  list ⟶ (a ⟶ a) ⟶ list\n  | Tnil => list\n  end.\n\nDefinition cons {C} : tm fn_arity C _ := BaseTm Tcons.\nDefinition map {C} : tm fn_arity C _ := BaseTm Tmap.\nDefinition nil {C} : tm fn_arity C _ := BaseTm Tnil.\n\nProgram Definition rule_0 := \n  make_rewrite\n    (_ ,, ∙) _\n    (map · nil ·  V 0)\n    nil.\n\nProgram Definition rule_1 := \n  make_rewrite\n    (_ ,, _ ,, _ ,, ∙) _\n    (map · (cons ·  V 0 ·  V 1) ·  V 2)\n    (cons · ( V 2 ·  V 0) · (map ·  V 1 ·  V 2)).\n\nDefinition trs := \n  make_afs\n    fn_arity \n    (rule_0 :: rule_1 :: List.nil).\n\nDefinition map_fun_poly fn_symbols : poly ∙ (arity trs fn_symbols) := \n  match fn_symbols with\n  | Tnil => to_Poly (P_const 3)\n  | Tcons  => λP λP let y1 := P_var Vz in\n    to_Poly (P_const 3\n             + P_const 2 * y1)\n  | Tmap  =>  λP let y0 := P_var (Vs Vz) in λP let G1 := P_var Vz in\n    to_Poly (P_const 3 * y0\n             + P_const 3 * y0 * (G1 ·P (y0)))\n  end.\n\nDefinition  trs_isSN : isSN trs.\nProof.\n  solve_poly_SN map_fun_poly.\nQed.\n", "meta": {"author": "nmvdw", "repo": "Nijn", "sha": "9bd88a93cdf0ab521536249fe628e9e63341f473", "save_path": "github-repos/coq/nmvdw-Nijn", "path": "github-repos/coq/nmvdw-Nijn/Nijn-9bd88a93cdf0ab521536249fe628e9e63341f473/Code/Examples/Map.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6673437868535348}}
{"text": "Require Import HoTT.\nRequire Import structures basics.\n\nExport Ring_pr Relation_pr OrderedMagma_pr.\nImport minus1Trunc.\n\nOpen Scope nat_scope.\n\n(* used to avoid polluting with extra instances\neg left_cancel, right_cancel and cancel when just cancel suffices *)\nSection LocalInstances.\n\nFixpoint nplus (n m : nat) : nat := match n with\n  | S k => S (nplus k m)\n  | 0 => m\n  end.\n\nDefinition npred (n : nat) : nat := match n with\n  | S k => k\n  | _ => 0\n  end.\n\nFixpoint nmult (n m : nat) : nat := match n with\n  | S k => nplus m (nmult k m)\n  | 0 => 0\n  end.\n\nInductive nle (n : nat) : nat -> Type :=\n  | nle_n : nle n n\n  | nle_S : forall m : nat, nle n m -> nle n (S m).\n\nDefinition nlt n := nle (S n).\n\nCanonical Structure nat_LLRRR : PreringFull nat\n := BuildLLRRR_Class nat nplus nmult neq nle nlt.\nGlobal Existing Instance nat_LLRRR.\n\nLemma S_0_neq : forall n, S n = 0 -> Empty.\nProof.\nintros. exact (transport (fun s => match s with\n  | 0 => Empty | _ => Unit end) H tt).\nDefined.\n\nDefinition eq_nat_dec : DecidablePaths nat.\nProof.\nred.\ninduction x,y.\n\n- left;reflexivity.\n\n- right. exact (fun H => transport (fun s => match s with\n | 0 => Unit | _ => Empty end) H tt).\n\n- right. exact (fun H => transport (fun s => match s with\n | 0 => Empty | _ => Unit end) H tt).\n\n- destruct (IHx y). left. apply ap;assumption.\n  right. intro;apply n.\n  exact (ap npred H).\nDefined.\n\nGlobal Instance nat_set : IsHSet nat.\nProof.\napply hset_decidable. exact eq_nat_dec.\nDefined.\n\nLemma nplus_0_l : forall n, 0 + n = n.\nProof.\nreflexivity.\nDefined.\n\nLemma nplus_S_l : forall n m, (S n) + m = S (n + m).\nProof.\nintros;reflexivity.\nDefined.\n\nLemma nplus_0_r : forall n, n + 0 = n.\nProof.\ninduction n.\nreflexivity.\napply (ap S). assumption.\nDefined.\n\nLemma nplus_S_r : forall n m, n + (S m) = S (n + m).\nProof.\ninduction n;intros. reflexivity.\napply (ap S). apply IHn.\nDefined.\n\nInstance nplus_comm : Commutative (+).\nProof.\nred. induction y. apply nplus_0_r.\nunfold gop in *. change (x + S y = S (y+x)).\neapply concat;[| apply ap; apply IHy].\napply nplus_S_r.\nDefined.\n\nInstance nplus_assoc : Associative (+).\nProof.\nred. induction x. intros;reflexivity.\nintros;unfold gop. apply (ap S);apply IHx.\nDefined.\n\nInstance nplus_is_sg : IsSemigroup (+). split;apply _. Defined.\n\nInstance n0_is_id : IsId (+) 0.\nProof.\nsplit. intro;reflexivity.\nexact nplus_0_r.\nDefined.\n\nCanonical Structure nplus_identity : Identity (+) := BuildIdentity _ _ _.\nExisting Instance nplus_identity.\n\nInstance nplus_ismono : IsMonoid (+)\n := BuildIsMonoid _ _ nplus_identity.\n\nInstance nplus_left_cancel : forall n : nat, Lcancel (+) n.\nProof.\ninduction n;red;intros.\nassumption.\nunfold gop in H;simpl in H. apply IHn.\napply (ap npred H).\nDefined.\n\nInstance nplus_right_cancel : forall n : nat, Rcancel (+) n.\nProof.\ninduction n;red;intros.\neapply concat;[|eapply concat;[apply H|]].\napply inverse;apply nplus_0_r. apply nplus_0_r.\napply IHn.\nassert (S (b + n) = S (c + n)).\neapply concat. symmetry. apply nplus_S_r. eapply concat. apply H.\napply nplus_S_r.\napply (ap npred X).\nDefined.\n\nInstance nplus_cancel : forall n : nat, Cancel (+) n.\nProof.\nintros. split;apply _.\nDefined.\n\nInstance nplus_cmono : IsCMonoid (+) := BuildIsCMonoid _ _ _.\n\n\nDefinition nmult_0_l : forall m, 0 ° m = 0 := fun _ => idpath.\n\nLemma nmult_0_r : forall n, n ° 0 = 0.\nProof.\ninduction n.\nreflexivity.\nassumption.\nDefined.\n\nLemma nmult_S_l : forall n m, (S n) ° m = m + (n ° m).\nProof.\nintros;reflexivity.\nDefined.\n\nLemma nmult_S_r : forall n m, n ° (S m) = (n ° m) + n.\nProof.\ninduction n;intros.\nreflexivity.\neapply concat;[|symmetry;apply nplus_S_r].\neapply concat;[apply nmult_S_l|].\neapply concat;[apply nplus_S_l|].\napply ap.\neapply concat;[|apply nplus_assoc]. apply ap.\napply IHn.\nDefined.\n\nInstance nmult_comm : Commutative (°).\nProof.\nred. induction y.\n- simpl. apply nmult_0_r.\n- simpl. eapply concat. apply nmult_S_r. eapply concat. apply nplus_comm.\n  eapply concat;[|symmetry;apply nmult_S_l]. apply ap. assumption.\nDefined.\n\nInstance nat_distrib_left : Ldistributes nat_LLRRR.\nProof.\nred. induction a;intros.\nreflexivity.\n\neapply concat;[apply nmult_S_l|].\npattern (a ° (b+c)). eapply transport. symmetry;apply IHa.\npath_via (b + (c + (a°b + a°c))).\neapply concat;[ symmetry;apply nplus_assoc |]. apply ap;apply ap.\napply IHa.\n\neapply concat;[| apply nplus_assoc]. fold nmult. apply ap.\neapply concat;[| apply nplus_comm].\neapply concat;[| apply nplus_assoc]. apply ap.\napply nplus_comm.\nDefined.\n\nInstance nat_distrib_right : Rdistributes nat_LLRRR.\nProof.\nred. intros.\nsimpl.\neapply concat. apply nmult_comm.\neapply concat. apply nat_distrib_left.\napply ap11;[ apply ap |];apply nmult_comm.\nDefined.\n\nInstance nat_distrib : Distributes nat_LLRRR.\nProof.\nsplit;apply _.\nDefined.\n\nInstance nmult_assoc : Associative (°).\nProof.\nred. unfold gop. induction x;intros.\nreflexivity.\neapply concat;[apply nmult_S_l|].\neapply concat;[| symmetry;apply nat_distrib]. fold nmult.\nchange nmult with mult.\napply ap. apply IHx.\nDefined.\n\n\nInstance nmult_issg : IsSemigroup (°) := BuildIsSemigroup _ _ _.\n\nInstance nmult_1_l : Left_id (°) 1.\nProof.\nred. simpl. apply nplus_0_r.\nDefined.\n\nInstance nmult_1_r : Right_id (°) 1.\nProof.\nred. intros. eapply concat. apply nmult_comm.\napply nmult_1_l.\nDefined.\n\nInstance nmult_1_id : IsId (°) 1.\nProof.\nsplit;apply _.\nDefined.\n\nCanonical Structure nmult_identity : Identity (°) := BuildIdentity _ _ _.\nExisting Instance nmult_identity.\n\nInstance nmult_ismono : IsMonoid (°) := BuildIsMonoid _ _ nmult_identity.\n\nGlobal Instance nat_issemiring : IsSemiring nat_LLRRR.\nProof.\napply BuildIsSemiring;apply _.\nDefined.\n\nLemma nplus_0_0_back : forall n m, n + m = 0 -> (n = 0) * (m = 0).\nProof.\nintros.\ndestruct n. destruct m.\nsplit;reflexivity.\napply Empty_rect.\nexact (transport (fun s : nat => match s with\n                                  | 0 => Empty\n                                  | S _ => Unit\n                                  end) H tt).\napply Empty_rect.\nexact (transport (fun s : nat => match s with\n                                  | 0 => Empty\n                                  | S _ => Unit\n                                  end) H tt).\nDefined.\n\nLemma nmult_S_0_back : forall n m, mult (S n) m = 0 -> m = 0.\nProof.\nintros.\ncompute in H. apply nplus_0_0_back in H. apply H.\nDefined.\n\nLemma nmult_integral : forall n m, 0 = mult n m ->\n(0 = n) + (0 = m).\nProof.\nintros n m;intros. destruct n. \n- left;reflexivity.\n- right;symmetry;eapply nmult_S_0_back. symmetry;apply H.\nDefined.\n\nInstance nmult_strict_integral : IsStrictIntegral nat_LLRRR.\nProof.\nred;intros;apply min1;apply nmult_integral;assumption.\nDefined.\n\nInstance nmult_left_cancel : forall n, Lcancel (°) (S n).\nProof.\nintros n m;induction m;simpl in *;intros m' H.\nassert (X:m' + (n°m') = 0). eapply concat. symmetry;apply H.\napply nmult_0_r.\napply nplus_0_0_back in X. symmetry;apply X.\n\ndestruct m'.\nassert (X:(S n) ° (S m)=0). eapply concat. apply H. apply nmult_0_r.\napply inverse in X;apply nmult_integral in X.\ndestruct X as [X | X];apply inverse in X;apply S_0_neq in X;destruct X.\n\napply ap. apply IHm. unfold gop in *.\napply nplus_right_cancel with (S n). unfold gop.\neapply concat;[|eapply concat;[apply H|]].\nunfold mult;simpl. change nmult with mult. change nplus with plus.\nsymmetry. eapply concat. apply ap. apply ap. apply nmult_S_r.\nsymmetry;eapply concat. apply nplus_S_r. apply (ap S).\nsymmetry;apply (associative (+) _).\neapply concat. unfold mult;simpl;apply ap;apply ap. apply nmult_S_r.\nunfold mult;simpl.\nchange nplus with plus;change nmult with mult.\neapply concat;[|symmetry;apply nplus_S_r]. apply ap.\napply associative;apply _.\nDefined.\n\nGlobal Instance nmult_cancel : forall n, Cancel ((°)) (S n).\nProof.\nintro;apply left_cancel_cancel. apply _.\nDefined.\n\nInstance nle_refl : Reflexive (<=) := nle_n.\n\nLemma nle_exists : forall n m : nat, n <= m -> exists k, k + n = m.\nProof.\nintros n m H;induction H.\nexists 0;reflexivity.\nexists (S (projT1 IHnle)).\napply (ap S).\napply projT2.\nDefined.\n\nLemma nplus_nle : forall n k : nat, n <= k + n.\nProof.\ninduction k.\napply nle_n.\nsimpl. apply nle_S. assumption.\nDefined.\n\nDefinition exists_nle : forall n m : nat, (exists k, k + n = m) -> n <= m.\nProof.\nintros.\ndestruct H as [k []].\napply nplus_nle.\nDefined.\n\nLemma nle_exists_nle : forall n m H, nle_exists n m (exists_nle n m H) = H.\nProof.\nintros n m H. destruct H as [k []].\nsimpl. clear m. induction k.\nreflexivity.\npath_via (nle_exists n (S (k + n)) (nplus_nle n (S k))).\nsimpl. fold nplus.\nchange nplus with plus;simpl.\nrewrite IHk.\nreflexivity.\nDefined.\n\nInstance nle_antisymm : Antisymmetric (<=).\nProof.\nintros n m H H0.\napply nle_exists in H. apply nle_exists in H0.\ndestruct H as [k Hk];destruct H0 as [k' Hk'].\ndestruct k. apply Hk.\ndestruct k'. symmetry;apply Hk'.\nsimpl in *.\nassert (H : S (k + S (k' + m)) = m).\npattern (S (k' + m)). eapply transport. symmetry;apply Hk'. apply Hk.\nassert (H' : (S (S (k+ k'))) + m = 0 + m).\nsimpl. eapply concat;[|apply H].\napply (ap S). symmetry. eapply concat;[apply nplus_S_r|]. apply ap.\napply nplus_assoc.\napply nplus_right_cancel in H'.\napply S_0_neq in H'. destruct H'.\nDefined.\n\nLemma nle_n_back : forall n (H : n <= n), H = nle_n n.\nProof.\nassert (H: forall n m (H : n <= m) (p : m = n), transport _ p H = nle_n n).\ninduction H.\nintros. assert (X : p = idpath). apply axiomK_hset. apply _.\npattern p. eapply transport. symmetry. apply X.\nsimpl. reflexivity.\nintros.\nassert (H' : n = m). apply nle_antisymm. assumption.\ndestruct p. apply nle_S. apply nle_n.\nassert (H0 : 1 + m = 0 + m). simpl. path_via n.\nclear H'. apply nplus_right_cancel in H0. apply S_0_neq in H0. destruct H0.\n\nintros. apply (H n n H0 idpath).\nDefined.\n\nLemma nle_S_n_n_not : forall n, ~ (S n) <= n.\nProof.\nred;intros.\nassert (H' : 1 + n = 0 + n).\nsimpl. apply nle_antisymm. assumption.\napply nle_S;apply nle_n.\napply nplus_right_cancel in H'. eapply S_0_neq;apply H'.\nDefined.\n\nLemma nle_S_back : forall n m, n <= m -> forall H : n <= S m,\n exists H', H = nle_S _ _ H'.\nProof.\nassert (X :forall n m (H : n <= m) m0 (p : m = S m0) (H0 : n <= m0), \n exists H' : n <= m0, transport _ p H = nle_S _ _ H').\ninduction H;intros.\napply Empty_rect. apply S_0_neq with 0.\napply nplus_right_cancel with m0. unfold gop.\napply nle_antisymm. pattern (1 + m0);eapply transport. apply p. assumption.\napply nle_S;apply nle_n.\nassert (p' : m = m0). apply (ap npred p). destruct p'.\npattern p. eapply transport. symmetry. apply axiomK_hset. apply _.\nsimpl. exists H;reflexivity.\n\nintros. apply (X n (S m) H0 m idpath H).\nDefined.\n\nLemma exists_nle_exists : forall n m H, exists_nle n m (nle_exists n m H) = H.\nProof.\nintros.\ndestruct (nle_exists n m H).\ndestruct p.\nsimpl.\ninduction x.\nsimpl.\nsymmetry;apply nle_n_back.\nsimpl.\nsimpl in H.\n\ndestruct (nle_S_back n (x+n) (nplus_nle _ _) H).\n pattern (nplus_nle n x). eapply transport. symmetry. apply IHx.\nsymmetry. apply p.\nDefined.\n\nInstance nle_exists_isequiv : forall n m, IsEquiv (nle_exists n m).\nProof.\nintros. apply isequiv_adjointify with (exists_nle n m).\nred;apply nle_exists_nle.\nred;apply exists_nle_exists.\nDefined.\n\nLemma nle_equiv_nplus : forall n m : nat, (n <= m) <~> (exists k, k + n = m).\nProof.\nintros. eapply BuildEquiv. apply _.\nDefined.\n\nInstance nle_prop : forall n m : nat, IsHProp (n <= m).\nProof.\nintros. eapply trunc_equiv'. apply symmetric_equiv.\napply nle_equiv_nplus.\napply hprop_inhabited_contr. intro X.\napply BuildContr with X. intro Y.\ndestruct X as [k Hk];destruct Y as [k' Hk'].\nassert (p : k = k').\napply nplus_right_cancel with n. path_via m.\napply path_sigma with p.\napply nat_set.\nDefined.\n\nLemma nle_0 : forall n, 0 <= n.\nProof.\ninduction n;constructor;auto.\nDefined.\n\nLemma nle_S_S_back : forall n m, S n <= S m -> n <= m.\nProof.\nintros. apply nle_exists in H. apply exists_nle.\ndestruct H as [k H]. exists k.\nassert (X : S (k + n) = S m). path_via (k + S n). symmetry. apply nplus_S_r.\napply (ap npred X).\nDefined.\n\nInstance nle_trans : Transitive (<=).\nProof.\nintros x y z H;revert z;induction H;intros. assumption.\ndestruct z.\nrefine (Empty_rect _ (S_0_neq m _)). apply nle_antisymm. assumption.\napply nle_0.\napply nle_S_S_back in H0. apply IHnle. apply nle_S. assumption.\nDefined.\n\nLemma nlt_not_nle : forall n m : nat, n < m -> ~ m <= n.\nProof.\nred;intros.\nred in H. apply S_0_neq with 0. apply nplus_right_cancel with n.\nsimpl. apply nle_antisymm. eapply nle_trans. apply H. assumption.\napply nle_S;apply nle_n.\nDefined.\n\nLemma nle_S_S : forall n m, n <= m -> (S n) <= (S m).\nProof.\nintros n m H;induction H.\napply nle_n.\napply nle_S;assumption.\nDefined.\n\nDefinition nle_nlt_dec : forall n m : nat, (n <= m) + (m < n).\nProof.\n  intros n m.\n  induction n in m |- *.\n  left. apply nle_0.\n  destruct m.\n  right. apply nle_S_S. apply nle_0.\n  destruct (IHn m).\n  left. apply nle_S_S;assumption.\n  right. apply nle_S_S;assumption.\nDefined.\n\nLemma not_nle_nlt : forall n m : nat, ~ m <= n -> n < m.\nProof.\nintros.\ndestruct (nle_nlt_dec m n). apply Empty_rect;auto.\nassumption.\nDefined.\n\nInstance nle_dec : Decidable (<=).\nProof.\nintros n m;destruct (nle_nlt_dec n m).\nleft;assumption.\nright;apply nlt_not_nle;assumption.\nDefined.\n\nInstance nle_linear : ConstrLinear (<=).\nProof.\nintros n m. destruct (nle_nlt_dec n m). left;assumption.\nright. apply nle_trans with (S m). apply nle_S;apply nle_n.\nassumption.\nDefined.\n\nGlobal Instance nle_total_order : ConstrTotalOrder (<=).\nProof.\nconstructor;[constructor|];apply _.\nDefined.\n\nLemma nlt_iff_nle_neq : forall n m : nat, n<m <-> (n<=m /\\ neq n m).\nProof.\nintros;split;intros H.\nchange (nlt n m) in H. apply nle_exists in H.\ndestruct H as [k H].\nassert (H' : (S k) + n = m). path_via (k + S n).\npath_via (S (k+n)). symmetry. apply nplus_S_r. clear H. destruct H'.\nsplit. apply nplus_nle.\nintro H. change (O+n = S k + n) in H.\napply nplus_right_cancel in H.\neapply S_0_neq. apply inverse;apply H.\ndestruct H as [H H0].\napply nle_exists in H. destruct H as [k H].\ndestruct k. destruct H0.\nassumption.\napply exists_nle. exists k.\npath_via (S k + n). path_via (S (k+n)). apply nplus_S_r.\nDefined.\n\nLemma nle_iff_nlt_eq : forall n m : nat, n<=m <-> (n<m \\/ n=m).\nProof.\nintros;split;intros H.\ndestruct H. right;reflexivity.\nleft. apply nle_S_S. assumption.\ndestruct H. apply transitivity with (S n). apply nle_S. apply nle_n.\nassumption.\ndestruct p;apply nle_n.\nDefined.\n\nLemma nle_iff_not_nlt_flip : forall n m:nat, n<=m <-> ~m<n.\nProof.\nintros;split;intro H.\nintro H'. eapply nlt_not_nle;[apply H'|apply H].\ndestruct (nle_nlt_dec n m). assumption.\ndestruct H;assumption.\nDefined.\n\nInstance nle_nplus_linvariant : IsLInvariant (+ <=).\nProof.\nred;red. unfold gop;unfold rrel. simpl.\nsimpl.\nintros. apply exists_nle. apply nle_exists in H.\ndestruct H as [k []]. exists k.\npath_via ((k+z)+x). apply associative;apply _.\npath_via ((z+k)+x). apply (ap (fun g => g + _)). apply commutative;apply _.\nsymmetry;apply associative;apply _.\nDefined.\n\nGlobal Instance nplus_nle_invariant : IsInvariant (+ <=).\nProof.\napply linvariant_invariant; apply _.\nDefined.\n\nGlobal Instance nplus_nle_compat : IsCompat (+ <=).\nProof.\napply invariant_compat; apply _.\nDefined.\n\nGlobal Instance nplus_nle_regular : forall z, IsRegular (+ <=) z.\nProof.\nassert (forall z, IsLRegular (+ <=) z). red;red.\nunfold rrel;unfold gop;simpl.\nintros ? ? ? H.\napply nle_exists in H;apply exists_nle.\ndestruct H as [k H].\nexists k. apply nplus_cancel with z.\npath_via (k + (z+x)).\npath_via ((z+k)+x). apply associative;apply _.\npath_via ((k+z)+x). apply (ap (fun g => g + _)). apply commutative;apply _.\nsymmetry;apply associative;apply _.\n\nintros;split. apply _.\nred;red.\nintros. apply H with z.\nunfold gop;simpl.\napply (@transport _ (fun k => k ~> z+y) (x+z)).\napply commutative;apply _.\napply (@transport _ (fun k => _ ~> k) (y+z)).\napply commutative;apply _.\nassumption.\nDefined.\n\nLemma not_nlt_nle : forall n m : nat, ~ n < m -> m <= n.\nProof.\nintros.\ndestruct (nle_nlt_dec m n). assumption.\ndestruct X;assumption.\nDefined.\n\nLemma nlt_nle : forall n m : nat, n < m -> n <= m.\nProof.\nintros. apply nle_trans with (S n). apply nle_S;apply nle_n.\nassumption.\nDefined.\n\nGlobal Instance nat_trichotomic : Trichotomic nat_LLRRR.\nProof.\nred. intros.\ndestruct (nle_nlt_dec y x). right. destruct (nle_nlt_dec x y).\nleft. apply nle_antisymm;assumption.\nright;assumption.\nleft;assumption.\nDefined.\n\nGlobal Instance nat_fullpseudoorder : FullPseudoOrder nat_LLRRR.\nProof.\nsplit.\nsplit.\napply neq_apart. apply eq_nat_dec.\nintros;apply iff_refl.\nintros. apply nlt_not_nle in H0. apply H0.\napply nlt_nle. assumption.\n\nred. unfold rrel. intros. apply min1.\ndestruct (nle_nlt_dec z x).\ndestruct (nle_nlt_dec y z).\napply nlt_not_nle in H. destruct H. apply nle_trans with z;assumption.\nright;assumption.\nleft;assumption.\n\nintros. split;intro H.\ndestruct (nat_trichotomic x y) as [H' | [H' | H']];auto.\ndestruct H;assumption.\nintro H'. destruct H'.\ndestruct H as [H|H];apply nlt_iff_nle_neq in H;apply H;reflexivity.\n\nintros. split.\nintros H H';eapply nlt_not_nle;eauto.\napply not_nlt_nle.\nDefined.\n\nLemma nle_not_nlt : forall n m : nat, n <= m -> ~ m < n.\nProof.\nintros ? ? H H'. eapply nlt_not_nle.\napply H'. apply H.\nDefined.\n\nLemma nle_n_S_n : forall n : nat, n <= S n.\nProof.\nintros;apply nle_S;apply nle_n.\nDefined.\n\nGlobal Instance nat_fullpseudo : FullPseudoOrder nat_LLRRR.\nProof.\nsplit;try apply _.\n\nsplit. apply nle_not_nlt.\napply not_nlt_nle.\nDefined.\n\nEnd LocalInstances.\n\nSection nat_to_semiring.\n\nContext {A:Type}.\nVariable (L : Prering A).\nContext {Hg : IsSemiring L}.\n\nFixpoint nat_embed (n : nat) : A := match n with\n  | S k => OneV + (nat_embed k)\n  | 0 => ZeroV\n  end.\n\nGlobal Instance nat_embed_add_morph : Magma.IsMorphism (+) (+) nat_embed.\nProof.\nred.\ninduction x;intros.\n- symmetry. apply Zero.\n- simpl. eapply concat.\n  apply ap. apply IHx.\n  apply (@associative _ (+) _).\nDefined.\n\nGlobal Instance nat_embed_mult_morph : Magma.IsMorphism (°) (°) nat_embed.\nProof.\nred.\ninduction x.\n- intros. simpl.\n  apply inverse. apply rmult_0_l.\n- intros. unfold gop. simpl.\n  eapply concat. apply nat_embed_add_morph.\n  eapply concat. apply ap. apply IHx.\n  path_via ((OneV ° nat_embed y) + nat_embed x ° nat_embed y).\n  unfold gop.\n  apply (@ap _ _ (fun g => g + (nat_embed x ° nat_embed y)) (nat_embed y)).\n  apply inverse. apply One.\n  apply inverse. apply rdistributes;apply _.\nDefined.\n\nEnd nat_to_semiring.\n\n\n\n\n", "meta": {"author": "SkySkimmer", "repo": "HoTT-algebra", "sha": "d5a4627d5d222e0f889591296d84f60234a00daa", "save_path": "github-repos/coq/SkySkimmer-HoTT-algebra", "path": "github-repos/coq/SkySkimmer-HoTT-algebra/HoTT-algebra-d5a4627d5d222e0f889591296d84f60234a00daa/nat_struct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6673437702373485}}
{"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 Ext_Cons.Prod_Cat.Prod_Cat.\nFrom Categories Require Import Functor.Main.\nFrom Categories Require Import Basic_Cons.Product.\n\nLocal Open Scope morphism_scope.\n\n(**\nGiven two objects a and b the exponential (bᵃ, denoted 'Exponential a b' below)\nis intuitively the internal representation of homomorphisms from a to b – it is\nsometimes referred to as the internal hom. The notion of exponential is a\ngeneralization of the notion function space from set theory.\n\nDefinition: bᵃ is an object equipped with an evaluation function eval: bᵃ×a -> b\nsuch that for any other object z with arrow f : z×a -> b, we have a unique arrow\nf^ that makes the following diagram commute:\n\n#\n<pre>\n               eval\n        bᵃ×a ——————————> b\n         ↑             ↗\n  bᵃ     |            /\n  ↑      | <f^,idₐ>  /\n  |      |          /\n  |∃!f̂ ^  |         /\n  |      |        / f\n  z      |       /\n         |      /\n         |     /\n         |    /\n         |   /\n         |  /\n         z×a\n</pre>\n#\nwhere <f, g> is the arrow map of the product functor.\n*)\nRecord Exponential {C : Category} {HP : Has_Products C} (c d : Obj) : Type :=\n{\n  exponential : C;\n\n  eval : ((×ᶠⁿᶜ C) _o (exponential, c))%object –≻ d;\n\n  Exp_morph_ex : ∀ (z : C), (((×ᶠⁿᶜ C) _o (z, c))%object –≻ d) → (z –≻ exponential);\n\n  Exp_morph_com : ∀ (z : C) (f : ((×ᶠⁿᶜ C) _o (z, c))%object –≻ d),\n      f = (eval ∘ ((×ᶠⁿᶜ C) @_a (_, _) (_, _) (Exp_morph_ex z f, id c)))%morphism;\n\n  Exp_morph_unique : ∀ (z : C) (f : ((×ᶠⁿᶜ C) _o (z, c))%object –≻ d)\n                       (u u' : z –≻ exponential),\n      f = (eval ∘ ((×ᶠⁿᶜ C) @_a (_, _) (_, _) (u, id c)))%morphism →\n      f = (eval ∘ ((×ᶠⁿᶜ C) @_a (_, _) (_, _) (u', id c)))%morphism →\n      u = u'\n}.\n\nCoercion exponential : Exponential >-> Obj.\n\nArguments Exponential _ {_} _ _, {_ _} _ _.\n\nArguments exponential {_ _ _ _} _, {_ _} _ _ {_}.\nArguments eval {_ _ _ _} _, {_ _} _ _ {_}.\nArguments Exp_morph_ex {_ _ _ _} _ _ _, {_ _} _ _ {_} _ _.\nArguments Exp_morph_com {_ _ _ _} _ _ _, {_ _} _ _ {_} _ _.\nArguments Exp_morph_unique {_ _ _ _} _ _ _ _ _ _ _, {_ _} _ _ {_} _ _ _ _ _ _.\n\nNotation \"a ⇑ b\" := (Exponential a b) : object_scope.\n\n(** Exponentials are unique up to isomorphism. *)\nTheorem Exponential_iso {C : Category} {HP : Has_Products C} (c d : C)\n        (E E' : (c ⇑ d)%object) : (E ≃ E')%isomorphism.\nProof.\n  eapply\n    (\n      Build_Isomorphism\n        _\n        _\n        _\n        (Exp_morph_ex E' _ (eval E))\n        (Exp_morph_ex E _ (eval E'))\n    );\n  eapply Exp_morph_unique; eauto;\n  simpl_ids;\n  match goal with\n      [|- (_ ∘ ?M)%morphism = _] =>\n      match M with\n        (?U _a (?A ∘ ?B, ?C))%morphism =>\n        assert (M = (U @_a (_, _) (_, _) (A, C))\n                          ∘ (U @_a (_, _) (_, _) (B, C)))%morphism as HM;\n          [simpl_ids; rewrite <- F_compose; simpl; simpl_ids; trivial|rewrite HM]\n      end\n  end;\n  rewrite <- assoc;\n  repeat rewrite <- Exp_morph_com; auto.\nQed.\n\nDefinition Has_Exponentials (C : Category) {HP : Has_Products C} :=\n  ∀ a b, (a ⇑ b)%object.\n\nExisting Class Has_Exponentials.\n\nSection Curry_UnCurry.\n  Context (C : Category) {HP : Has_Products C} {HE : Has_Exponentials C}.\n\n  (** Given a arrow f: a×b -> c in a category with exponentials, the curry of f\n      is f̂f^ in the definition of Exponential above. *)\n  Definition curry :\n    forall {a b c : C},\n      (((×ᶠⁿᶜ C) _o (a, b))%object –≻ c) → (a –≻ (HE b c)) :=\n    fun {a b c : C} (f : ((×ᶠⁿᶜ C) _o (a, b))%object –≻ c) =>\n      Exp_morph_ex (HE b c) _ f.\n\n  (** Given an arrow f: a -> cᵇ, uncurry of f is the arrow\n      (eval_cᵇ ∘ <id_b, f>): a×b -> c.\n      See definition of Exponential above for details. *)\n  Definition uncurry : forall {a b c : C},\n      (a –≻ (HE b c)) → (((×ᶠⁿᶜ C) _o (a, b))%object –≻ c) :=\n    fun {a b c : C} (f : a –≻ (HE b c)) =>\n      ((eval (HE b c)) ∘ ((×ᶠⁿᶜ C) @_a (_, _) (_, _) (f, id C b)))%morphism.\n\n  Section inversion.\n    Context {a b c : C}.\n\n    (** See definition of curry and uncurry above for details.\n        Frollows immediately from the definition of Exponential above. *)\n    Theorem curry_uncurry (f : a –≻ (HE b c)) : curry (uncurry f) = f.\n    Proof.\n      unfold curry, uncurry.\n      eapply Exp_morph_unique; trivial.\n      rewrite <- Exp_morph_com; trivial.\n    Qed.\n\n    (** See definition of curry and uncurry above for details.\n        Follows immediately from the definition of Exponential above. *)\n    Theorem uncurry_curry (f : ((×ᶠⁿᶜ C) _o (a, b))%object –≻ c) :\n      uncurry (curry f) = f.\n    Proof.\n      unfold curry, uncurry.\n      rewrite <- Exp_morph_com; trivial.\n    Qed.\n\n  End inversion.\n\n  Section injectivity.\n    Context {a b c : C}.\n\n    (** See definition of curry above for details. Follows immediately from\n        uncurry_curry above. *)\n    Theorem curry_injective (f g : ((×ᶠⁿᶜ C) _o (a, b))%object –≻ c) :\n      curry f = curry g → f = g.\n    Proof.\n      intros H.\n      rewrite <- (uncurry_curry f); rewrite <- (uncurry_curry g).\n      rewrite H; trivial.\n    Qed.\n\n    (** See definition of uncurry above for details.\n        Follows immediately from curry_uncurry above. *)\n    Theorem uncurry_injective (f g : a –≻ (HE b c)) :\n      uncurry f = uncurry g → f = g.\n    Proof.\n      intros H.\n      rewrite <- (curry_uncurry f); rewrite <- (curry_uncurry g).\n      rewrite H; trivial.\n    Qed.\n\n  End injectivity.\n\n  Section curry_compose.\n    Context {a b c : C}.\n\n    (** composing with curry is equivalent to compose and then curry: *)\n    Lemma curry_compose (f : ((×ᶠⁿᶜ C) _o (a, b))%object –≻ c)\n          {z : C} (g : z –≻ a)\n      : (curry f) ∘ g = curry (f ∘ (Prod_morph_ex _ _ (g ∘ Pi_1) Pi_2)).\n    Proof.\n      unfold curry.\n      eapply Exp_morph_unique; eauto.\n      rewrite <- Exp_morph_com.\n      match goal with\n          [|- ((_ ∘ (_ _a) ?M) ∘ _)%morphism = _] =>\n          match M with\n              ((?N ∘ ?x)%morphism, id ?y) =>\n              replace M with\n              (compose (_ × _) (_, _) (_, _) (_, _) (x, id y) (N,id y)) by\n                  (cbn; auto)\n          end\n      end.\n      rewrite F_compose.\n      cbn; simpl_ids.\n      rewrite assoc_sym.\n      match goal with\n          [|- (?A ∘ ?B = ?C ∘ ?B)%morphism] => cutrewrite (A = C); trivial\n      end.\n      transitivity (uncurry (curry f));\n        [unfold curry, uncurry; cbn; auto|apply uncurry_curry].\n    Qed.\n\n  End curry_compose.\n\nEnd Curry_UnCurry.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/Categories/Basic_Cons/Exponential.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6673331808241052}}
{"text": "Require Import Basics.\nRequire Import Pointed.Core.\nRequire Import Types.\nRequire Import Colimits.Pushout.\nRequire Import Cubical.\n\nLocal Open Scope pointed_scope.\nLocal Open Scope dpath_scope.\n\n(* Definition of smash product *)\n\nDefinition sum_to_prod (X Y : pType) : X + Y -> X * Y\n  := sum_ind _ (fun x => (x, point Y)) (fun y => (point X, y)).\n\nDefinition sum_to_bool X Y : X + Y -> Bool\n  := sum_ind _ (fun _ => false) (fun _ => true).\n\nDefinition Smash (X Y : pType) : pType\n  := [Pushout (sum_to_prod X Y) (sum_to_bool X Y), pushl (point X, point Y)].\n\nSection Smash.\n\n  Context {X Y : pType}.\n\n  Definition sm (x : X) (y : Y) : Smash X Y := pushl (x, y).\n\n  Definition auxl : Smash X Y := pushr false.\n\n  Definition auxr : Smash X Y := pushr true.\n\n  Definition gluel (x : X) : sm x pt = auxl\n    := pglue (f:=sum_to_prod X Y) (g:=sum_to_bool X Y) (inl x).\n\n  Definition gluer (y : Y) : sm pt y = auxr\n    := pglue (f:=sum_to_prod X Y) (g:=sum_to_bool X Y) (inr y).\n\n  Definition gluel' (x x' : X) : sm x pt = sm x' pt\n    := gluel x @ (gluel x')^.\n\n  Definition gluer' (y y' : Y) : sm pt y = sm pt y'\n    := gluer y @ (gluer y')^.\n\n  Definition glue (x : X) (y : Y) : sm x pt = sm pt y\n    := gluel' x pt @ gluer' pt y.\n\n  Definition glue_pt_left (y : Y) : glue pt y = gluer' pt y.\n  Proof.\n    refine (_ @ concat_1p _).\n    apply whiskerR, concat_pV.\n  Defined.\n\n  Definition glue_pt_right (x : X) : glue x pt = gluel' x pt.\n  Proof.\n    refine (_ @ concat_p1 _).\n    apply whiskerL, concat_pV.\n  Defined.\n\n  Definition ap_sm_left {x x' : X} (p : x = x')\n    : ap (fun t => sm t pt) p = gluel' x x'.\n  Proof.\n    destruct p.\n    symmetry.\n    apply concat_pV.\n  Defined.\n\n  Definition ap_sm_right {y y' : Y} (p : y = y')\n    : ap (sm pt) p = gluer' y y'.\n  Proof.\n    destruct p.\n    symmetry.\n    apply concat_pV.\n  Defined.\n\n  Definition Smash_ind {P : Smash X Y -> Type}\n    (Psm : forall a b, P (sm a b)) (Pl : P auxl) (Pr : P auxr)\n    (Pgl : forall a, DPath P (gluel a) (Psm a pt) Pl)\n    (Pgr : forall b, DPath P (gluer b) (Psm pt b) Pr)\n    : forall x : Smash X Y, P x.\n  Proof.\n    srapply Pushout_ind.\n    + intros [a b].\n      apply Psm.\n    + apply (Bool_ind _ Pr Pl).\n    + srapply sum_ind; intro; apply dp_path_transport^-1.\n      - apply Pgl.\n      - apply Pgr.\n  Defined.\n\n  Definition Smash_ind_beta_gluel {P : Smash X Y -> Type}\n    {Psm : forall a b, P (sm a b)} {Pl : P auxl} {Pr : P auxr}\n    (Pgl : forall a, DPath P (gluel a) (Psm a pt) Pl)\n    (Pgr : forall b, DPath P (gluer b) (Psm pt b) Pr) (a : X)\n    : dp_apD (Smash_ind Psm Pl Pr Pgl Pgr) (gluel a) = Pgl a.\n  Proof.\n    apply dp_apD_path_transport.\n    refine (Pushout_ind_beta_pglue P _ _ _ (inl a) @ _).\n    unfold sum_ind.\n    by apply ap.\n  Qed.\n\n  Definition Smash_ind_beta_gluer {P : Smash X Y -> Type}\n    {Psm : forall a b, P (sm a b)} {Pl : P auxl} {Pr : P auxr}\n    (Pgl : forall a, DPath P (gluel a) (Psm a pt) Pl)\n    (Pgr : forall b, DPath P (gluer b) (Psm pt b) Pr) (b : Y)\n    : dp_apD (Smash_ind Psm Pl Pr Pgl Pgr) (gluer b) = Pgr b.\n  Proof.\n    apply dp_apD_path_transport.\n    refine (Pushout_ind_beta_pglue P _ _ _ (inr b) @ _).\n    unfold sum_ind.\n    by apply ap.\n  Qed.\n\n  Definition Smash_ind_beta_gluel' {P : Smash X Y -> Type}\n    {Psm : forall a b, P (sm a b)} {Pl : P auxl} {Pr : P auxr}\n    (Pgl : forall a, DPath P (gluel a) (Psm a pt) Pl)\n    (Pgr : forall b, DPath P (gluer b) (Psm pt b) Pr) (a b : X)\n    : dp_apD (Smash_ind Psm Pl Pr Pgl Pgr) (gluel' a b)\n    = (Pgl a) @Dp ((Pgl b)^D).\n  Proof.\n    unfold gluel'.\n    rewrite dp_apD_pp, dp_apD_V.\n    by rewrite 2 Smash_ind_beta_gluel.\n  Qed.\n\n  Definition Smash_ind_beta_gluer' {P : Smash X Y -> Type}\n    {Psm : forall a b, P (sm a b)} {Pl : P auxl} {Pr : P auxr}\n    (Pgl : forall a, DPath P (gluel a) (Psm a pt) Pl)\n    (Pgr : forall b, DPath P (gluer b) (Psm pt b) Pr) (a b : Y)\n    : dp_apD (Smash_ind Psm Pl Pr Pgl Pgr) (gluer' a b)\n    = (Pgr a) @Dp ((Pgr b)^D).\n  Proof.\n    unfold gluer'.\n    rewrite dp_apD_pp, dp_apD_V.\n    by rewrite 2 Smash_ind_beta_gluer.\n  Qed.\n\n  Definition Smash_ind_beta_glue {P : Smash X Y -> Type}\n    {Psm : forall a b, P (sm a b)} {Pl : P auxl} {Pr : P auxr}\n    (Pgl : forall a, DPath P (gluel a) (Psm a pt) Pl)\n    (Pgr : forall b, DPath P (gluer b) (Psm pt b) Pr) (a : X) (b : Y)\n    : dp_apD (Smash_ind Psm Pl Pr Pgl Pgr) (glue a b)\n    = ((Pgl a) @Dp ((Pgl pt)^D)) @Dp ((Pgr pt) @Dp ((Pgr b)^D)).\n  Proof.\n    by rewrite dp_apD_pp, Smash_ind_beta_gluel', Smash_ind_beta_gluer'.\n  Qed.\n\n  Definition Smash_rec {P : Type} (Psm : X -> Y -> P) (Pl Pr : P)\n    (Pgl : forall a, Psm a pt = Pl) (Pgr : forall b, Psm pt b = Pr)\n    : Smash X Y -> P := Smash_ind Psm Pl Pr\n      (fun x => dp_const (Pgl x)) (fun x => dp_const (Pgr x)).\n\n  Local Open Scope path_scope.\n\n  (* Version of smash_rec that forces (Pgl pt) and (Pgr pt) to be idpath *)\n  Definition Smash_rec' {P : Type} {Psm : X -> Y -> P}\n    (Pgl : forall a, Psm a pt = Psm pt pt) (Pgr : forall b, Psm pt b = Psm pt pt)\n    (ql : Pgl pt = 1) (qr : Pgr pt = 1)\n    : Smash X Y -> P := Smash_rec Psm (Psm pt pt) (Psm pt pt) Pgl Pgr.\n\n  Definition Smash_rec_beta_gluel {P : Type} {Psm : X -> Y -> P} {Pl Pr : P}\n    (Pgl : forall a, Psm a pt = Pl) (Pgr : forall b, Psm pt b = Pr) (a : X)\n    : ap (Smash_rec Psm Pl Pr Pgl Pgr) (gluel a) = Pgl a.\n  Proof.\n    refine (_ @ eissect dp_const (Pgl a)).\n    apply moveL_equiv_V.\n    unfold Smash_rec.\n    refine ((dp_apD_const (Smash_ind Psm Pl Pr (fun x : X => dp_const (Pgl x))\n      (fun x : Y => dp_const (Pgr x))) (gluel a))^ @ _).\n    rapply Smash_ind_beta_gluel.\n  Qed.\n\n  Definition smash_rec_beta_gluer {P : Type} {Psm : X -> Y -> P} {Pl Pr : P}\n    (Pgl : forall a, Psm a pt = Pl) (Pgr : forall b, Psm pt b = Pr) (b : Y)\n    : ap (Smash_rec Psm Pl Pr Pgl Pgr) (gluer b) = Pgr b.\n  Proof.\n    refine (_ @ eissect dp_const (Pgr b)).\n    apply moveL_equiv_V.\n    unfold Smash_rec.\n    refine ((dp_apD_const (Smash_ind Psm Pl Pr (fun x : X => dp_const (Pgl x))\n      (fun x : Y => dp_const (Pgr x))) (gluer b))^ @ _).\n    rapply Smash_ind_beta_gluer.\n  Qed.\n\n  Definition Smash_rec_beta_gluel' {P : Type} {Psm : X -> Y -> P} {Pl Pr : P}\n    (Pgl : forall a, Psm a pt = Pl) (Pgr : forall b, Psm pt b = Pr) (a b : X)\n    : ap (Smash_rec Psm Pl Pr Pgl Pgr) (gluel' a b) = Pgl a @ (Pgl b)^.\n  Proof.\n    rewrite ap_pp, ap_V.\n    by rewrite 2 Smash_rec_beta_gluel.\n  Qed.\n\n  Definition Smash_rec_beta_gluer' {P : Type} {Psm : X -> Y -> P} {Pl Pr : P}\n    (Pgl : forall a, Psm a pt = Pl) (Pgr : forall b, Psm pt b = Pr) (a b : Y)\n    : ap (Smash_rec Psm Pl Pr Pgl Pgr) (gluer' a b) = Pgr a @ (Pgr b)^.\n  Proof.\n    rewrite ap_pp, ap_V.\n    by rewrite 2 smash_rec_beta_gluer.\n  Qed.\n\n  Definition smash_rec_beta_glue {P : Type} {Psm : X -> Y -> P} {Pl Pr : P}\n    (Pgl : forall a, Psm a pt = Pl) (Pgr : forall b, Psm pt b = Pr) (a : X)\n    (b : Y) : ap (Smash_rec Psm Pl Pr Pgl Pgr) (glue a b)\n    = ((Pgl a) @ (Pgl pt)^) @ (Pgr pt @ (Pgr b)^).\n  Proof.\n    by rewrite ap_pp, Smash_rec_beta_gluel', Smash_rec_beta_gluer'.\n  Defined.\n\n  Arguments sm : simpl never.\n  Arguments auxl : simpl never.\n  Arguments gluel : simpl never.\n  Arguments gluer : simpl never.\n\nEnd Smash.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Homotopy/Smash.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.667333179094741}}
{"text": "Require Export XR_R.\nRequire Export XR_Rle.\nRequire Export XR_Rlt_trans.\n\nImplicit Type r : R.\nLocal Open Scope R_scope.\n\nLemma Rle_trans : forall r1 r2 r3,\n  r1 <= r2 -> r2 <= r3 -> r1 <= r3.\nProof.\n  intros x y z.\n  intros hxy hyz.\n  unfold \"<=\" in hxy, hyz.\n  unfold \"<=\".\n  destruct hxy as [ hxy | heq ].\n  {\n    destruct hyz as [ hyz | heq ].\n    {\n      left.\n      apply Rlt_trans with y.\n      { exact hxy. }\n      { exact hyz. }\n    }\n    {\n      subst z.\n      left.\n      exact hxy.\n    }\n  }\n  {\n    subst y.\n    exact hyz.\n  }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rle_trans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6672363492082076}}
{"text": "(* Software Foundations *)\n(* Exercice 3 stars, gen_dep_practice_more *) \n\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nFixpoint snoc{X: Type}(l: list X)(v: X):=\n    match l with\n    |nil  => [v]\n    |h::t => h::(snoc t v)\n    end.\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    generalize dependent n.\n    induction l as [|h t].\n    destruct n as [|n'].\n    intros. simpl. reflexivity.\n    intros contra. simpl in contra. inversion contra.\n    simpl. intros. apply f_equal. \n    induction n as [|n'].\n    inversion H.\n    inversion H. apply IHt in H1. rewrite <- H in H1. apply H1.\nQed.\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter7_Library_MoreCoq/gen_dep_practice_more.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.8006920020959543, "lm_q1q2_score": 0.6672363452449297}}
{"text": "(** * Utils *)\n(** Common definitions including:\n -  theorems about lists and permutation.  \n -  the induction scheme for Strong Induction\n -  some arithmetic results (specially dealing with [max] and [min])\n *)\n\nRequire Export Coq.Relations.Relations.\nRequire Export Coq.Classes.Morphisms.\nRequire Export Permutation.\nRequire Import Coq.Relations.Relations.\nRequire Import Coq.Setoids.Setoid.\nRequire Export Coq.Sorting.PermutSetoid.\nRequire Export Coq.Sorting.PermutEq.\nRequire Import Coq.Program.Equality.\nRequire Export Coq.Lists.List.\nRequire Export Coq.Sorting.Permutation.\nRequire Export Coq.Arith.Arith.\nRequire Export Coq.Init.Nat.\nRequire Import Lia.\n\n\nExport ListNotations.\n\nSet Implicit Arguments.\n\nLemma NatComp : forall x y, x >= y + 1 -> S x - y - 2 = x - y - 1.\nProof with subst;auto. lia.\nQed.  \n  \n\n(** ** Additional results about permutations *)\nSection Permutations.\n\n  Variable A:Type.\n\nLemma ListConsApp (a b: A) : forall L M , a :: L = M ++ [b] -> \n       (L=[]/\\M=[]/\\a=b) \\/ exists X, M = a :: X /\\ L = X++[b].\nProof with subst;auto.\n  induction M; intros...\n  * inversion H...\n  * rewrite <- app_comm_cons in H. \n    inversion H;subst...\n    right.\n    exists M...\n Qed.   \n \n Lemma ListConsApp' (a b: A) : forall L M1 M2 , a :: L = M1 ++ [b] ++ M2 -> \n        (L=M2/\\M1=[]/\\a=b) \\/ \n       exists X, M1 = a :: X /\\ L = X++[b]++M2.\nProof with subst;auto.\n  destruct M1;intros...\n  * inversion H;subst...\n  * rewrite <- app_comm_cons in H. \n    inversion H;subst...\n    right.\n    exists M1...\n Qed. \n\n  Lemma ListConsApp'' (a : A) M1: forall L M2 , a :: L = M1 ++ M2 -> \n       (M1=[ ]/\\M2=a::L) \\/ \n       exists X, M1 = a :: X /\\ L = X++M2.\nProof with subst;auto.\n  induction M1;intros...\n  rewrite <- app_comm_cons in H. \n   inversion H;subst...\n   right.\n   exists M1... \n Qed. \n       \n  Lemma Perm_swap_inv : forall (x y : A) (N M : list A),\n      Permutation (x :: N) (y :: x :: M) ->\n      Permutation N ( y :: M).\n    intros.\n    rewrite perm_swap in H.\n    apply Permutation_cons_inv in H;auto.\n  Qed.\n\n  Lemma Perm_swap_inv_app : forall y N M (x : A) ,\n      Permutation (x :: N) (y ++ x :: M) ->\n      Permutation N ( y ++ M).\n    intros.\n    rewrite  (Permutation_cons_append M x) in H.\n    rewrite  Permutation_cons_append in H.\n    rewrite app_assoc in H.\n    rewrite  <- Permutation_cons_append in H.\n    rewrite  <- (Permutation_cons_append (y ++ M) x ) in H.\n    apply Permutation_cons_inv in H;auto.\n  Qed.\n\n  Theorem PermutConsApp: forall (a : A) l1 b l2,\n      Permutation (a :: l1 ++ b :: l2) (b :: a :: l1 ++ l2).\n    intros.\n    rewrite perm_swap.\n    rewrite <- Permutation_middle.\n    auto.\n  Qed.\n\n  Lemma PermutationInCons : forall (F:A) M N,\n      Permutation (F::M) N -> In F N.\n    intros.\n    eapply Permutation_in with (x:= F) (l':=N);eauto.\n    constructor;auto.\n  Qed.\n\n\n  (** A slightly different version of  [Permutation_map] *)\n  Lemma PermuteMap : forall (L L' : list A) (f: A->Prop),\n      Forall f L -> Permutation L L'-> Forall f L'.\n    intros.\n    apply Permutation_sym in H0.\n    assert(forall x, In x L' -> In x L) by eauto using Permutation_in.\n    rewrite Forall_forall in H.\n    rewrite Forall_forall;intros.\n    firstorder.\n  Qed.\n\n(* Permutation_app_inv *)\n  Lemma Permutation_mid : forall (F:A) l1 l2 l1' l2', \n      Permutation (l1 ++ F :: l2) (l1' ++ F :: l2') ->\n      Permutation (l1 ++ l2) (l1' ++ l2').\n    intros.\n    assert(Permutation (F::l2) (l2 ++ [F]))\n      by  apply Permutation_cons_append.\n    rewrite H0 in H.\n    assert(Permutation (F::l2') (l2' ++ [F]))\n      by  apply Permutation_cons_append.\n    rewrite H1 in H.\n    apply Permutation_app_inv_r with (l:= [F]).\n    do 2 rewrite app_assoc_reverse;auto.\n  Qed.\n  \n (* perm_takeit_5 *)\n  Lemma Permutation_midle : forall  (F:A) l1 l2,\n      Permutation (l1 ++ F :: l2) ( F :: l1  ++ l2).\n    intros.\n    generalize (Permutation_cons_append  l1 F);intro.\n    change (F::l1++l2) with ( (F::l1) ++ l2).\n    rewrite H.\n    assert(l1 ++ F :: l2 = (l1 ++ [F]) ++ l2).\n    rewrite app_assoc_reverse;auto.\n    rewrite H0.\n    auto.\n  Qed.\n\n\n(* Permutation_app_swap_app *)\n  Lemma Permutation_midle_app : forall  (la lb lc: list A),\n      Permutation (la ++ lb ++ lc) ( lb ++ la  ++ lc).\n    intros.\n    rewrite <- app_assoc_reverse. \n    rewrite Permutation_app_comm with (l:=la).\n    rewrite app_assoc_reverse;auto.\n  Qed.\n\n\n  Lemma InPermutation : forall (l:A) L,\n      In l L -> exists L', Permutation L (l :: L').\n    induction L;intros.\n    inversion H.\n    inversion H;subst.\n    exists L;auto.\n    apply IHL in H0.\n    destruct H0 as [L' H0].\n    exists (a :: L').\n    rewrite H0.\n    constructor.\n  Qed.\n  \n\nEnd Permutations.\n\n(** ** Strong Induction *)\n\nSection StrongIndPrinciple.\n\n  Variable P: nat -> Prop.\n\n  Hypothesis P0: P O.\n\n  Hypothesis Pn: forall n, (forall m, m<=n -> P m) -> P (S n).\n\n  Lemma strind_hyp : forall n, (forall m, ((m <= n) -> P m)).\n  Proof.\n    induction n; intros m H;inversion H;auto.\n  Qed.\n  (** Strong induction principle *)\n  Theorem strongind: forall n, P n.\n  Proof.\n    induction n; auto.\n    apply Pn.\n    apply strind_hyp.\n  Qed.\n\nEnd StrongIndPrinciple.\n\n\n(** ** Aditional results on Arithmentic *)\nSection Arithmentic.\n\n  Lemma MaxPlus : forall a b, (max a b <= plus a  b).\n    intros;lia.\n  Qed.\n  \n  Lemma MaxPlus' : forall a b c, (plus a b <= c -> max a b <= c).\n    intros;lia.\n  Qed.\n  \n  \n  Theorem GtExists : forall n, n>0 -> exists n', n = S n'.\n    intros.\n    destruct n;inversion H;subst;eauto.\n  Qed.\n\nEnd Arithmentic.\n\nLtac mgt0 := let H := fresh \"H\" in\n             match goal with [_ :  ?m >= S _ |- _] =>\n                             assert(H : m>0) by lia;\n                             apply GtExists in H;\n                             destruct H;subst\n             end.\n\n\nSection Pairs.\n\nVariable S:Type. (* SubExps *)\nVariable F:Type. (* Formulas *)\n\n\n(* fst (split L) *)\nDefinition first (L:list (S * F)) :=  map fst L.\n(* snd (split L) *)\nDefinition second (L:list (S * F)) := map snd L.\n\n         \nLemma secondApp C1 C2 : second (C1 ++ C2) = second C1 ++ second C2.\nProof.\n  induction C1;simpl.\n  reflexivity.\n  rewrite IHC1.\n  reflexivity. Qed.\n\nLemma firstApp C1 C2 : first (C1 ++ C2) = first C1 ++ first C2.\nProof.\n  induction C1;simpl.\n  reflexivity.\n  rewrite IHC1.\n  reflexivity. Qed.\n\nLemma InFirst c B : In c B -> In (fst c) (first B). \nProof.\n induction B;intros;auto.\n unfold second.\n inversion H;subst;auto;\n simpl;auto.\n Qed.\n \nLemma InSecond c B : In c B -> In (snd c) (second B). \nProof.\n induction B;intros;auto.\n unfold second.\n inversion H;subst;auto;\n simpl;auto.\n Qed.\n \n Lemma InSecondInv i A B : In (i,A) B -> In A (second B). \nProof.\n induction B;intros;auto.\n inversion H;subst;auto;\n simpl;auto.\n Qed.\n \n End Pairs.\n\n   \n", "meta": {"author": "meta-logic", "repo": "MMLL", "sha": "dc4cb8cc9056efb264be3a97e9bfd4c2cf32838e", "save_path": "github-repos/coq/meta-logic-MMLL", "path": "github-repos/coq/meta-logic-MMLL/MMLL-dc4cb8cc9056efb264be3a97e9bfd4c2cf32838e/Misc/Utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245994514082, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.6672363439121963}}
{"text": "(*\nMacBook-Air:~ billw$ /Applications/CoqIDE_8.4pl5.app/Contents/Resources/bin/coqtop\nWelcome to Coq 8.4pl5 (October 2014)\n\nCoq < Require Import Classical.\n\nCoq < Section Exercise_8.\n\nCoq < Goal forall j k b s:Prop, (~(j \\/ k) /\\ (b -> k) /\\ (s -> b)) -> (~s /\\ ~j).\n1 subgoal\n\n  ============================\n   forall j k b s : Prop, ~ (j \\/ k) /\\ (b -> k) /\\ (s -> b) -> ~ s /\\ ~ j\n\nUnnamed_thm < intros.\n1 subgoal\n\n  j : Prop\n  k : Prop\n  b : Prop\n  s : Prop\n  H : ~ (j \\/ k) /\\ (b -> k) /\\ (s -> b)\n  ============================\n   ~ s /\\ ~ j\n\nUnnamed_thm < elim H.\n1 subgoal\n\n  j : Prop\n  k : Prop\n  b : Prop\n  s : Prop\n  H : ~ (j \\/ k) /\\ (b -> k) /\\ (s -> b)\n  ============================\n   ~ (j \\/ k) -> (b -> k) /\\ (s -> b) -> ~ s /\\ ~ j\n\nUnnamed_thm < intro.\n1 subgoal\n\n  j : Prop\n  k : Prop\n  b : Prop\n  s : Prop\n  H : ~ (j \\/ k) /\\ (b -> k) /\\ (s -> b)\n  H0 : ~ (j \\/ k)\n  ============================\n   (b -> k) /\\ (s -> b) -> ~ s /\\ ~ j\n\nUnnamed_thm < intro.\n1 subgoal\n\n  j : Prop\n  k : Prop\n  b : Prop\n  s : Prop\n  H : ~ (j \\/ k) /\\ (b -> k) /\\ (s -> b)\n  H0 : ~ (j \\/ k)\n  H1 : (b -> k) /\\ (s -> b)\n  ============================\n   ~ s /\\ ~ j\n\nUnnamed_thm < apply conj.\n2 subgoals\n\n  j : Prop\n  k : Prop\n  b : Prop\n  s : Prop\n  H : ~ (j \\/ k) /\\ (b -> k) /\\ (s -> b)\n  H0 : ~ (j \\/ k)\n  H1 : (b -> k) /\\ (s -> b)\n  ============================\n   ~ s\n\nsubgoal 2 is:\n ~ j\n\nUnnamed_thm < firstorder.\n1 subgoal\n\n  j : Prop\n  k : Prop\n  b : Prop\n  s : Prop\n  H : ~ (j \\/ k) /\\ (b -> k) /\\ (s -> b)\n  H0 : ~ (j \\/ k)\n  H1 : (b -> k) /\\ (s -> b)\n  ============================\n   ~ j\n\nUnnamed_thm < firstorder.\nNo more subgoals.\n\nUnnamed_thm < Qed.\nintros.\nelim H.\nintro.\nintro.\napply conj.\n firstorder .\n\n firstorder .\n\nUnnamed_thm is defined\n\nCoq <\n*)\n\nRequire Import Classical.\nSection Exercise_8.\nGoal forall j k b s:Prop, (~(j \\/ k) /\\ (b -> k) /\\ (s -> b)) -> (~s /\\ ~j).\nintros.\nelim H.\nintro.\nintro.\napply conj.\n firstorder.\n firstorder.\nQed.\n", "meta": {"author": "billwestfall", "repo": "coq_ide", "sha": "a2985a04f37f9c1c6f23799d543fdb862792d54b", "save_path": "github-repos/coq/billwestfall-coq_ide", "path": "github-repos/coq/billwestfall-coq_ide/coq_ide-a2985a04f37f9c1c6f23799d543fdb862792d54b/concise/07chapt/page0392h.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6672363432632908}}
{"text": "Require Import List.\n\nInductive RoseTree (A : Type) : Type :=\n| E : RoseTree A\n| N : A -> list (RoseTree A) -> RoseTree A.\n\n(** Okazuje się, że [decide_equality] potrafi udowodnić, że [RoseTree A] ma rozstrzygalną równość. *)\nLemma RoseTree_eq_dec :\n  forall\n    (A : Type) (A_eq_dec : forall x y : A, {x = y} + {x <> y})\n      (x y : RoseTree A), {x = y} + {x <> y}.\nProof.\n  fix RoseTree_eq_dec 3.\n  decide equality.\n  apply list_eq_dec. apply RoseTree_eq_dec. assumption.\nDefined.\n\n(** Uwaga: to całkiem dziwne, że poszło aż tak łatwo, bo przecież funkcja którą definiujemy\n    jest użyta rekurencyjnie jako argument [list_eq_dec], tzn. mamy do czynienia z rekursją\n    wyższego rzędu. *)", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/code/CoqSpecific/RoseTree_decide_equality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6672363425794628}}
{"text": "Require Import Coq.Relations.Relation_Definitions.\nRequire Export Coq.Classes.SetoidClass.\nRequire Import Coq.Classes.Equivalence.\n\nRequire Import Quotient.quotient.\nFrom Quotient.Construction Require Import function_util equalizer coequalizer.\n\nOpen Scope equiv_scope.\n\nProgram Definition power_setoid {A: Type} : Setoid (A -> bool) := {| setoid_equiv := @pointwise_equivalence A _ eq _ |}.\n\nDefinition power_exists := forall (A : Type), quotient (A -> bool) power_setoid.\nClass axiom_power_exists :=\n  {\n    proof_power_exists : power_exists\n  }.\n\nSection Power.\n\n  Context {instance_power_exists : axiom_power_exists}.\n\n  Definition power (A : Type) : Type := q_type _ _ (proof_power_exists A).\n  Definition to_power {A : Type} : (A -> bool) -> power A := q_proj _ _ (proof_power_exists A).\n\n  Lemma epi_to_power {A} : epi (@to_power A).\n  Proof.\n    apply quotient_proj_epi.\n  Qed.\n\n  Global Instance to_power_Proper {A} : Proper (Equivalence.equiv ==> eq) (@to_power A).\n  Proof.\n    intros f1 f2 eqf1f2.\n    apply quotient_comp.\n    assumption.\n  Qed.\n  \n  Section Power_Univ.\n    \n    Variable A : Type.\n    Variable T : Type.\n    Variable F : (A -> bool) -> T.\n    Variable F_proper : Proper (Equivalence.equiv ==> eq) F.\n    \n    Definition power_quotient_sig : {f : (power A) -> T | F === f_comp f to_power} :=\n      (quotient_factor _ _ (proof_power_exists A))\n        F F_proper.\n\n    Definition power_quotient_f : (power A) -> T := proj1_sig power_quotient_sig.\n    Definition power_quotient_f_eq : F === f_comp power_quotient_f to_power := proj2_sig power_quotient_sig.\n      \n  End Power_Univ.\n\n  Section Power_of_power.\n    \n    Context {A : Type}.\n    Definition app_bool_inv : A -> (A -> bool) -> bool := fun a f => f a.\n    \n    Lemma app_bool_inv_proper : forall a, Proper (Equivalence.equiv ==> eq) (app_bool_inv a).\n    Proof.\n      intro a.\n      intros p1 p2 eqp.\n      unfold app_bool_inv.\n      apply eqp.\n    Qed.\n    \n    Definition of_power (p : power A) : A -> bool := fun a => power_quotient_f _ _ _ (app_bool_inv_proper a) p.\n    \n    Lemma of_to_power_eq : forall p, of_power (to_power p) === p.\n    Proof.\n      intro p.\n      unfold of_power.\n      intro a.\n      transitivity ((app_bool_inv a) p).\n      rewrite (power_quotient_f_eq A bool (app_bool_inv a) (app_bool_inv_proper a) p).\n      reflexivity.\n      reflexivity.\n    Qed.\n    \n    Lemma to_of_power_eq : forall p, to_power (of_power p) = p.\n    Proof.\n      apply epi_to_power.\n      unfold f_comp.\n      intro p.\n      rewrite of_to_power_eq.\n      reflexivity.\n    Qed.\n    \n  End Power_of_power.\n  \n  Lemma power_extentionality : forall {A} (p1 p2 : power A), (forall a, of_power p1 a = of_power p2 a) -> p1 = p2.\n  Proof.\n    intros A p1 p2 ext.\n    rewrite <- (to_of_power_eq p1).\n    rewrite <- (to_of_power_eq p2).\n    apply to_power_Proper.\n    intro a.\n    apply ext.\n  Qed.\n\n  Lemma power_extentionality_inv : forall {A} (p1 p2 : power A), p1 = p2 -> (forall a, of_power p1 a = of_power p2 a).\n  Proof.\n    intros A p1 p2 ext a.\n    rewrite ext.\n    reflexivity.\n  Qed.\n  \n  Section Power_f.\n    \n    \n    (* power f := S \\subType B |-> { a \\in A | f(a) \\in S } *)\n    Definition power_f {A B : Type} (f : A -> B) : (power B) -> (power A) :=\n      fun pb => to_power (fun a => (of_power pb) (f a)).\n    \n    (* power_epsilon A := { S \\subType A | a \\in S } *)\n    Definition power_epsilon (A : Type) : A -> power (power A) :=\n      fun a => to_power (fun pa => (of_power pa) a).\n    \n    Global Instance power_f_Proper {A B : Type} : Proper ( Equivalence.equiv ==> Equivalence.equiv ) (@power_f A B).\n    Proof.\n      intros f1 f2 eqf.\n      intro pb.\n      apply power_extentionality.\n      intro a.\n      unfold power_f.\n      rewrite of_to_power_eq.\n      rewrite of_to_power_eq.\n      rewrite eqf.\n      reflexivity.\n    Qed.      \n    \n    Lemma power_f_comp_comm :\n      forall {A B C : Type} (f : B -> C) (g : A -> B),\n        power_f (f_comp f g) === f_comp (power_f g) (power_f f).\n    Proof.\n      intros A B C f g.\n      intro pc.      \n      apply power_extentionality.\n      apply f_equiv_eq.\n      unfold power_f.\n      unfold f_comp.\n      intro a.\n      rewrite of_to_power_eq.\n      rewrite of_to_power_eq.\n      rewrite of_to_power_eq.\n      reflexivity.\n    Qed.\n    \n    Lemma power_f_id :\n      forall {A : Type},\n        power_f (@id A) === id.\n    Proof.\n      intro A.\n      unfold power_f.\n      intro pa.\n      unfold id.\n      apply power_extentionality.\n      intro a.\n      rewrite of_to_power_eq.\n      reflexivity.\n    Qed.      \n    \n    Lemma power2_epsilon_natural :\n      forall {A B : Type} (f : A -> B),\n        f_comp (power_epsilon B) f === f_comp (power_f (power_f f)) (power_epsilon A).\n    Proof.\n      intros A B f.\n      intro a.\n      unfold f_comp.\n      unfold power_epsilon.\n      unfold power_f.\n      apply power_extentionality.\n      intro pb.\n      rewrite of_to_power_eq.\n      rewrite of_to_power_eq.\n      rewrite of_to_power_eq.\n      rewrite of_to_power_eq.\n      reflexivity.\n    Qed.\n    \n    Lemma triangle_power_f :\n      forall {A B C D : Type} (f : A -> B) (g : B -> D) (h : A -> C) (i : C -> D),\n        f_comp g f === f_comp i h -> f_comp (power_f f) (power_f g) === f_comp (power_f h) (power_f i).\n    Proof.\n      intros A B C D f g h i eqH.\n      rewrite <- power_f_comp_comm.\n      rewrite <- power_f_comp_comm.\n      rewrite eqH.\n      reflexivity.\n    Qed.\n    \n    Lemma principle_equalizer_eq :\n      forall {A : Type}, f_comp (power_epsilon (power (power A))) (power_epsilon A) === f_comp (power_f (power_f (power_epsilon A))) (power_epsilon A).\n    Proof.\n      intro A.\n      apply power2_epsilon_natural.\n    Qed.      \n    \n    Lemma power_epsilon_unit_counit :\n      forall {A : Type},\n        f_comp (power_f (power_epsilon A)) (power_epsilon (power A)) === id.\n    Proof.\n      intro A.\n      intro pa.\n      unfold f_comp.\n      unfold id.\n      apply power_extentionality.\n      intro a.\n      unfold power_f.\n      rewrite of_to_power_eq.\n      unfold power_epsilon.\n      repeat rewrite of_to_power_eq.\n      reflexivity.\n    Qed.\n      \n  End Power_f.  \n\n  (* empty *)\n  Definition empty_power (A : Type) : power A := to_power (fun a => false).\n  Lemma empty_power_false : forall A a, of_power (empty_power A) a = false.\n  Proof.\n    intros A a.\n    unfold empty_power.\n    rewrite of_to_power_eq.\n    reflexivity.\n  Qed.\n  Lemma power_f_empty_eq_empty : forall {A B : Type} (f : A -> B), power_f f (empty_power B) === empty_power A.\n  Proof.\n    intros A B f.\n    apply power_extentionality.\n    intros a.\n    unfold power_f.\n    rewrite of_to_power_eq.\n    repeat rewrite empty_power_false.\n    reflexivity.\n  Qed.    \n\n  (* subset *)\n  Definition subset {A : Type} (S1 S2 : power A) := forall a, of_power S1 a = true -> of_power S2 a = true.\n  Lemma subset_antisym : forall A (S1 S2 : power A), subset S1 S2 -> subset S2 S1 -> S1 = S2.\n  Proof.\n    unfold subset.\n    intros A S1 S2 subH1 subH2.\n    apply power_extentionality.\n    unfold subset.\n    intro a.\n    remember (of_power S1 a) as b1.\n    destruct b1.\n    symmetry.\n    apply subH1.\n    rewrite Heqb1.\n    reflexivity.\n    symmetry.\n    apply Neqtrue.\n    intro HH.\n    symmetry in Heqb1.\n    apply Neqtrue_inv in Heqb1.\n    apply Heqb1.\n    apply subH2.\n    assumption.\n  Qed.\n    \n  (* Some Axioms *)\n  Definition power_reflects_iso :=\n    forall (A B : Type) (f : A -> B),\n      {Pg | isIsomorphism (power_f f) Pg} ->\n      {g | isIsomorphism f g}.\n  Definition power_f_faithful :=\n    forall (A B : Type) (f1 f2 : A -> B),\n      power_f f1 === power_f f2 -> f1 === f2.\n  Definition preserve_reflexive_equalizer :=\n    forall (A B C : Type) (g : A -> B) (f1 f2 : B -> C) (d : C -> B),\n      isEqualizer f1 f2 g ->\n      (f_comp d f1 === id /\\ f_comp d f2 === id) ->\n      isCoequalizer (power_f f1) (power_f f2) (power_f g).\n\n  Class axiom_power_reflects_iso :=\n    {\n      proof_power_reflects_iso : power_reflects_iso\n    }.\n  Class axiom_power_f_faithful :=\n    {\n      proof_power_f_faithful : power_f_faithful\n    }.\n  Class axiom_preserve_reflexive_equalizer :=\n    {\n      proof_preserve_reflexive_equalizer : preserve_reflexive_equalizer\n    }.\n\nEnd Power.\n\n", "meta": {"author": "k27c8ff627uxz", "repo": "quotient_in_coq", "sha": "b26d7f89d02a8f31092fb463b136f40012a34f71", "save_path": "github-repos/coq/k27c8ff627uxz-quotient_in_coq", "path": "github-repos/coq/k27c8ff627uxz-quotient_in_coq/quotient_in_coq-b26d7f89d02a8f31092fb463b136f40012a34f71/src/Construction/power.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88720460564669, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6671890090820571}}
{"text": "Generalizable All Variables.\nSet Implicit Arguments.\nUnset Strict Implicit.\nRequire Export setoid monoid.\n\nDeclare Scope group_scope.\nDelimit Scope group_scope with grp.\nOpen Scope setoid_scope.\nOpen Scope monoid_scope.\nOpen Scope group_scope.\n\nClass LInvertible {X : Setoid} (op : X -> X -> X) e (inv : X -> X) := {\n  invl : forall x, op (inv x) x == e\n}.\n\nClass RInvertible {X : Setoid} (op : X -> X -> X) e (inv : X -> X) := {\n  invr : forall x, op x (inv x) == e\n}.\n\nClass Invertible `{X : Setoid} (op : X -> X -> X) e (inv : X -> X) := {\n  inv_invl :> LInvertible op e inv;\n  inv_invr :> RInvertible op e inv\n}.\n#[global] Existing Instances inv_invl inv_invr.\n\nClass IsGroup `(mul : Binop supp) (inv : Ope supp) e :=\n{\n  assocg :> Associative mul;\n  identrg :> RIdentical mul e;\n  invrg :> RInvertible mul e inv\n}.\n#[global] Existing Instances assocg identrg invrg.\n\nStructure Group := {\n  gcarrier :> Setoid;\n  mulg : Binop gcarrier;\n  invg : Ope gcarrier;\n  idg : gcarrier;\n\n  groupsprf : IsGroup mulg invg idg\n}.\n#[global] Existing Instance groupsprf.\n\nArguments mulg {_}.\nArguments invg {_}.\nArguments idg {_}.\n\n#[global]\nInstance identlg {G} : LIdentical (@mulg G) idg.\nProof.\n  split. intros x. rewrite <-identr.\n  rewrite <-(invr (invg x)) at 2.\n  now rewrite assoc, <-(assoc idg), invr, identr,\n    <-(invr x), <-assoc, invr, identr.\nQed.\n\nProgram Coercion grps_mnds (G : Group) :=\n  [ gcarrier G | *: mulg, 1: idg ].\nNext Obligation.\n  destruct G as [s mul inv id [A RI RV]]; split;\n  [|split]; intuition.\nDefined.\n\nProgram Definition ensg_ensm {X : Group} (G : {ens X})\n  : {ens grps_mnds X} := G.\n\nNotation \"[ A | *: op , !: inv , 1: id ]\" :=\n  (@Build_Group A op inv id _)\n  (at level 0, A, op, inv, id at level 99) : group_scope.\nNotation \"(  * 'in' G  )\" := (@mulg G) : group_scope.\nNotation \"( * )\" := ( * in _ ) : group_scope.\nNotation \"g * h 'in' G\" := (@mulg G g h)\n  (at level 40, h at next level, left associativity)\n  : group_scope.\nNotation \"g * h\" := (g * h in _) : group_scope.\nNotation \"1 'in' G\" := (@idg G)\n  (at level 0, G at level 99, no associativity) : group_scope.\nNotation \"1\" := (1 in _) : group_scope.\nNotation \"(  ! 'in' G  ) \" := (@invg G) : group_scope.\nNotation \"( ! )\" := ( ! in _ ) : group_scope.\nNotation \"! g 'in' G\" := (@invg G g)\n  (at level 35, g at level 35, right associativity,\n  format \"! g  'in'  G\") : group_scope.\nNotation \"! g\" := ( ! g in _ )\n  (at level 35, right associativity,\n  format \"! g\") : group_scope.\n\nProgram Definition conjg {G : Group} :=\n  dmap (h : G) g => !g * (h * g).\nNext Obligation.\n  intros g1 g2 E1 h1 h2 E2. now rewrite E1, E2.\nDefined. \nNotation \"g ^ h\" := (@conjg _ g h) : group_scope.\n\n#[global]\nInstance invlg {G} : LInvertible ( * in G ) 1 ( ! ).\nProof.\n  split. intros x. rewrite <-identr. rewrite <-(invr (!x)) at 1.\n  now rewrite assoc, <-(assoc _ x), invr, identr, invr.\nQed.\n\nSection GroupTheory.\n  Context {G : Group}.\n  Implicit Types x y g : G.\n  Lemma mulgA : forall {x y z}, x * (y * z) == (x * y) * z.\n  Proof. now destruct G as [a b c d [[e] f g]]. Qed.\n\n  Lemma mulg1 : forall x, x * 1 == x.\n  Proof. now destruct G as [a b c d [e [f] g]]. Qed.\n\n  Lemma mulgV : forall x, x * !x == 1.\n  Proof. now destruct G as [a b c d [e f [g]]]. Qed.\n\n  Lemma mul1g : forall x, 1 * x == x.\n  Proof. now destruct (@identlg G). Qed.\n\n  Lemma mulVg : forall x, !x * x == 1.\n  Proof. now destruct (@invlg G). Qed.\n\n  Lemma mulgI g {x y} : (x == y) == (x * g == y * g).\n  Proof.\n    split; intros H; [|rewrite <-mulg1, <-(mulg1 y),\n    <-(invr g), 2!assoc]; now rewrite H.\n  Qed.\n\n  Lemma mulIg g {x y} : (x == y) == (g * x == g * y).\n  Proof.\n    split; intros H; [|rewrite <-mul1g, <-(mul1g y),\n    <-(invl g), <-2!assoc]; now rewrite H.\n  Qed.\n\n  Lemma mulTg {g x y} : (x == !g * y) == (g * x == y).\n  Proof.\n    split; intros H.\n    - now rewrite H, assoc, mulgV, mul1g.\n    - now rewrite <-H, assoc, mulVg, mul1g.\n  Qed.\n\n  Lemma mulgT {g x y} : (x == y * !g) == (x * g == y).\n  Proof.\n    split; intros H.\n    - now rewrite H, <-assoc, mulVg, mulg1.\n    - now rewrite <-H, <-assoc, mulgV, mulg1.\n  Qed.\n\n  Lemma invgK x : !!x == x.\n  Proof. apply (@mulgI (!x)). now rewrite invl, invr. Qed.\n\n  Lemma eq_invg_sym {x y} : (!x == y) == (x == !y).\n  Proof.\n    split; intros H; now rewrite2 H; rewrite invgK.\n  Qed.\n\n  Lemma invMg {x y} : !(x * y) == !y * !x.\n  Proof.\n    rewrite <-(identr (!x)). apply mulTg, mulTg.\n    now rewrite assoc, invr.\n  Qed.\n\n  Lemma invg1 : !(1 in G) == 1.\n  Proof.\n    rewrite <-(identr (!1)). symmetry; apply mulTg, identl.\n  Qed.\n\n  Lemma invg_inj {x y} : (y == !x) == (x * y == 1).\n  Proof.\n    split; intros H.\n    - now rewrite H, mulgV.\n    - now rewrite <-(mulg1 (!x)), <-H, assoc, mulVg, mul1g.\n  Qed.\n\n  Lemma invJK x y : ((x ^ y) ^ !y) == x.\n  Proof.\n    simpl. now rewrite invgK, !assoc, \n      mulgV, mul1g, <-assoc, mulgV, mulg1.\n  Qed. \nEnd GroupTheory.\n\nClass IsMorph {G H : Group} (f : Map G H) := {\n  morph : forall x y, f (x * y) == (f x) * (f y) in H\n}.\n\nStructure Morph (G H : Group) := {\n  homfun :> Map G H;\n  homprf : IsMorph homfun\n}.\n#[global] Existing Instance homprf.\n\nNotation \"'hom' 'on' f\" := (@Build_Morph _ _ f _)\n  (at level 200, no associativity) : group_scope.\nNotation \"'hom' 'by' f \" := (hom on (map by f))\n  (at level 200, no associativity) : group_scope.\nNotation \" 'hom' x => m \" := (hom by fun x => m)\n  (at level 200, x binder, no associativity) : group_scope.\nNotation \"G ~~> H\" := (@Morph G H)\n  (at level 99, no associativity) : group_scope.\n\nDefinition morpheq {X Y} (f g : Morph X Y) :=\n  homfun f == homfun g.\nProgram Canonical Structure MorphSetoid (X Y : Group) :=\n  [ Morph X Y | ==: morpheq ].\nNotation \"[ G ~> H ]\" := (@MorphSetoid G H)\n  (at level 0, G, H at level 99, no associativity) : group_scope.\n\nStructure Isomorph (G H : Group) := {\n  isofun :> Morph G H;\n  isoprf : Bijective isofun\n}.\n#[global] Existing Instance isoprf.\n\nNotation \"'iso' 'on' f\" := (@Build_Isomorph _ _ f _)\n  (at level 200, no associativity) : group_scope.\nNotation \"'iso' x => m \" := (iso on hom x => m)\n  (at level 200, x binder, no associativity) : group_scope.\nNotation \"G <~> H\" := (@Isomorph G H)\n  (at level 95, no associativity) : group_scope.\n\nProgram Definition homcomp {G1 G2 G3} (f : G1 ~~> G2)\n  (g : G2 ~~> G3) : G1 ~~> G3 := hom on (g o f).\nNext Obligation. split. intros x y. simpl. now rewrite 2!morph. Defined.\nNotation \"g '<o~' f\" := (homcomp f g)\n  (at level 60, right associativity) : group_scope.\n\nProgram Definition isocomp {G1 G2 G3} (f : G1 <~> G2)\n  (g : G2 <~> G3) : G1 <~> G3 := iso on (g <o~ f).\nNext Obligation.\n  split; split; simpl.\n  - intros x y Heq. now repeat apply inj in Heq.\n  - intros z. destruct (surj g z) as [y E1]. \n    destruct (surj f y) as [x E2]. exists x. now rewrite E1, E2.\nDefined.\nNotation \"g '<o>' f\" := (isocomp f g)\n  (at level 60, right associativity) : group_scope.\n\nSection HomTheory.\n  Context `{f: Morph G H}.\n  Lemma morph1 : f 1 == 1.\n  Proof.\n    now rewrite (mulgI (f 1)), <-morph, 2!mul1g.\n  Qed.\n\n  Lemma morphV : forall x, f (!x) == !(f x).\n  Proof.\n    intros x. now rewrite <-(mulg1 (!f x)), mulTg,\n     <-morph, invr, morph1.\n  Qed.\nEnd HomTheory.\n\nClass IsSubg {X : Group} (G : {ens X}) := {\n  fermg : forall x y : G, G (x * !y);\n  idgF : G 1\n}.\n\nStructure Subg (X : Group) := {\n  suppg :> {ens X};\n  groupprf : IsSubg suppg\n}.\n#[global] Existing Instance groupprf.\n\nNotation \"< G >\" := (@Build_Subg _ G _)\n  (at level 200, G at level 0, no associativity) : group_scope.\nNotation \"{ 'subg' X }\" := (@Subg X)\n  (at level 0, format \"{ 'subg'  X }\") : group_scope.\n\nDefinition subg_eq {X} (G H : {subg X}) :=\n  suppg G == suppg H.\nProgram Canonical Structure SubgSetoid (X : Group) :=\n  [ {subg X} | ==: subg_eq ].\nNotation \"[ 'subg' X ]\" := (@SubgSetoid X)\n  (at level 0, format \"[ 'subg'  X ]\") : group_scope.\nProgram Canonical Structure suppgM {X : Group} \n  : Map {subg X} {ens X} := map x => suppg x.\n\nDefinition subgconf `(G : {subg X}) := fun x => (suppg G) x.\n\nSection GroupTheory.\n  Context {X : Group} {G : {subg X}}.\n  Implicit Types x y : G.\n  Lemma invgF x : G (!x).\n  Proof.\n    rewrite <-mul1g, (val_sval idgF). apply fermg.\n  Qed.\n\n  Lemma mulgF x y : G (x * y).\n  Proof.\n    rewrite <-(invgK y), 2!(val_sval (invgF _)).\n    apply fermg.\n  Qed.\nEnd GroupTheory.\n\nProgram Coercion grp_grpS `(G : {subg X}) : Group :=\n  [ G | *: (dmap g h => $[_, mulgF g h]),\n        !: (map g => $[_, invgF g]),\n        1: $[_, idgF] ].\nNext Obligation.\n  intros g g0 Eg h h0 Eh. simpeq. now rewrite Eg, Eh.\nDefined.\nNext Obligation.\n  intros g g0 Eg. simpeq. now rewrite Eg.\nDefined.\nNext Obligation.\n  split; split; intros; simpeq;\n  now rewrite assoc || rewrite mulg1 || rewrite mulgV.\nDefined.\n\nProgram Definition inclhom {X} {H G : {subg X}}\n   (L : H <= G) : H ~~> G := hom on (inclmap L).\nNext Obligation.\n  split. intros x y. now simpeq.\nDefined.\n\nProgram Canonical Structure IsSubgM {X : Group} :=\n  map by (@IsSubg X).\nNext Obligation.\n  intros A A0 E. split; intros [C I]; split; simpl;\n  try (now rewrite map_comap in I; rewrite2_in E I);\n  intros [x Hx] [y Hy]; simpl; rewrite map_comap;\n  rewrite map_comap in Hx; rewrite map_comap in Hy;\n  [rewrite <-E in * | rewrite E in *];\n  simpl in *; sapply (C $[_, Hx] $[_, Hy]).\nDefined.\n\nProgram Definition subgTfor (X : Group) := <(ensTfor X)>.\n\nProgram Definition subgI {X} (H0 H1 : {subg X})\n  := <(H0 :&: H1)>.\nNext Obligation.\n  split.\n  - intros [x [H0x H1x]] [y [H0y H1y]]. split; simpl.\n  + apply (fermg $[_, H0x] $[_, H0y]).\n  + apply (fermg $[_, H1x] $[_, H1y]).\n  - split; simpl; apply idgF.\nDefined.\n\nLemma subgIInf_subg {X : Group} (S : {ens {ens X}}) :\n  (forall U, S U -> @IsSubg X U) -> IsSubg (ensIInf S).\nProof.\n  intros H. split.\n  - intros [x Hx] [y Hy]. simpl in *.\n    intros [U HU]. simpl. destruct (H U HU).\n    sapply (fermg0 $[_, Hx $[_, HU]] $[_, Hy $[_, HU]]).\n  - intros [U HU]. destruct (H $[_, HU]); now simpl.\nDefined.\n\nProgram Definition generated {X : Group} (A : {ens X}) :=\n  <(ensIInf [ B : {ens X} | IsSubg B /\\ A <= B ])>.\nNext Obligation.\n  intros B B0 E. split; intros [H H0]; split;\n  try rewrite map_comap; now rewrite2 E.\nDefined.\nNext Obligation.\n  apply subgIInf_subg. now intros U [Usg AB].\nDefined.\n\nLemma gensubg_eq_subg {X : Group} {A : {ens X}} : \n  IsSubg A -> A == generated A.\nProof.\n  intros H a a0 E. rewrite E. split; intros H0.\n  - intros U. destruct U. destruct m. \n    now pose (d $[_, H0]).\n  - simpl in *. sapply (forall_sigS H0).\n    split; intuition. now destruct x.\nQed.\n\nLemma gen_compat_lt {X : Group} {A B : {ens X}} :\n  A <= B -> generated A <= generated B.\nProof.\n  intros H a U. destruct U. simpl in *.\n  destruct m. destruct a. simpl in *.\n  sigapply m. split; intuition.\n  apply (H1 (inclmap H x)).\nQed.\n\nDefinition conjugate {G : Group} :=\n  dmap21 (imens o1 ((@conjg G)^~)).\nNotation \"A :^ x\" := (conjugate A x)\n  (at level 35, right associativity) : group_scope.\n\nProgram Definition normaliser {G : Group} (A : {ens G})\n  := [ x | A :^ x <= A ].\nNext Obligation.\n  intros x y E. split; intros H [g [a H0]];\n  sigapply H; exists a; now rewrite2 E.\nDefined.\n\nClass IsNormal `(N : {subg G}) := {\n  normal : forall g : G, N :^ g <= N\n}.\n\nStructure Normalsg (X : Group) := {\n  suppsg :> {subg X};\n  nsgprf :> IsNormal suppsg\n}.\n#[global] Existing Instance nsgprf.\n\nNotation \"<| G\" := (@Normalsg G)\n  (at level 70, no associativity) : group_scope.\nNotation \"N <<| G\" := (@Build_Normalsg G N _)\n  (at level 70, no associativity) : group_scope.\n\nDefinition nsg_eq {X} (G H : <| X) :=\n  suppsg G == suppsg H.\nProgram Canonical Structure NormalsgSetoid\n  (X : Group) := [ <| X | ==: nsg_eq ].\nNotation \"[ 'nsg' X ]\" := (@NormalsgSetoid X)\n  (at level 0, format \"[ 'nsg'  X ]\") : group_scope.\nProgram Canonical Structure suppsgM {X : Group}\n  : Map (<| X) {subg X} := map x => suppsg x.\n\nLemma normalJF `{N : <| X} {n g : X} : N n -> N (n ^ g).\nProof.\n  intros Nn. sigapply (normal(g := g)).\n  now existsS n.\nQed.\n\nLemma normalVJF `{N : <|X} {n} g : N (n ^ g) -> N n.\nProof.\n  intros Nng. rewrite <-(invJK _ g). now apply normalJF.\nQed. \n\nProgram Definition imsubg {X Y : Group} :=\n  dmap (f : Morph X Y) (G : {subg X}) => <(f @: G)>.\nNext Obligation.\n  split.\n  - intros [y0 [g0 H0]] [y1 [g1 H1]]. existsS (g0 * !g1).\n    apply fermg. now rewrite morph, morphV, H0, H1.\n  - existsS (1 in X). apply idgF. now rewrite morph1.\nDefined.\nNext Obligation.\n  intros f g H A B. now apply setoid.imens_obligation_2.\nDefined.\n\nNotation \"f <@> G\" := (@imsubg _ _ f G)\n  (at level 24, right associativity) : group_scope.\n\nProgram Definition preimsubg {X Y : Group} :=\n  dmap (f : Morph X Y) (H : {subg Y}) => <(f -@: H)>.\nNext Obligation.\n  split; simpl.\n  - intros [x Hx] [y Hy]. simpl in *. rewrite morph, morphV.\n    apply (mulgF $[_, Hx] $[_, invgF $[_, Hy]]).\n  - rewrite morph1. apply idgF.\nDefined.\nNext Obligation.\n  intros f g H A B. now apply setoid.preimens_obligation_2.\nDefined.\n\nNotation \"f <-@> G\" := (@preimsubg _ _ f G)\n  (at level 24, right associativity) : group_scope.\n\nProgram Definition preimnsg {X Y : Group} :=\n  dmap (f : Morph X Y) (N : <| Y) => (preimsubg f N) <<| X.\nNext Obligation.\n  split. simpl. intros g [h [[a Ha] Hh]]. simpl in *.\n  rewrite Hh, !morph, morphV. now apply normalJF.\nDefined.\nNext Obligation.\n  intros f g H A B. now apply preimsubg_obligation_2.\nDefined.\n\nProgram Definition idnsg {X : Group} := <[ == 1]> <<| X.\nNext Obligation.\n  split; simpl; try reflexivity. intros [a Ha] [b Hb].\n  simpl in *. now rewrite Ha, Hb, identl, invg1.\nDefined.\nNext Obligation.\n  split. intros g [a [[i Hi] HN]]. simpl in *. \n  now rewrite HN, Hi, identl, invl.\nDefined.\n\nNotation \"<1>\" := (idnsg) : group_scope.\n\nProgram Definition kernel {X Y : Group} :=\n  map (f : Morph X Y) => preimnsg f <1>.\nNext Obligation. intros f f0 Ef. now rewrite Ef. Defined.\n\nDefinition coset_eq `{G : {subg X}} (x y : X) :=\n  G (x * !y).\n#[global] Hint Unfold coset_eq : eq.\nProgram Definition Coset `(G : {subg X}) :=\n  [ X | ==: @coset_eq _ G ].\nNext Obligation.\n  split; simpeq.\n  - intros x. rewrite invr. apply idgF.\n  - intros x y H. rewrite <-(invgK y), <-invMg.\n    apply (invgF $[_, H]).\n  - intros x y z H1 H2.\n    rewrite <-(mulg1 x), <-(mulVg y), assoc, <-assoc.\n    apply (mulgF $[_, H1] $[_, H2]).\nDefined.\nNotation \"X / G\" := (@Coset X G) : group_scope.\n\nProgram Definition projmap `{G : {subg X}} : Map X (X / G)\n  := map x => x.\nNext Obligation.\n  intros x x0 E. simpeq. rewrite E, mulgV. apply idgF.\nDefined.\n\nProgram Definition CosetGroup `(N : <| X) :=\n  [ X / N | *: (dmap xN yN => xN * yN),\n            !: (map xN => !xN),\n            1: 1 ].\nNext Obligation.\n  intros x x0 Ex y y0 Ey. simpeq_all.\n  rewrite invMg, assoc, <-(assoc x), <-(assoc).\n  rewrite <-(mulg1 x), <-(mulVg x0), (assoc x), <-(assoc _ x0).\n  sigapply (mulgF $[_, Ex]). rewrite <-(invgK x0) at 1.\n  now apply normalJF.\nDefined.\nNext Obligation.\n  intros x x0 E. simpeq_all. rewrite invgK.\n  apply (normalVJF(g:=!x0)). simpl.\n  rewrite <-assoc, mulgV, mulg1, <-invMg.\n  sapply (invgF $[_, E]).\nDefined.\nNext Obligation.\n  split; split; simpeq; intros.\n  - rewrite assoc, mulgV. apply idgF.\n  - rewrite mulg1, mulgV. apply idgF.\n  - rewrite mulgV, mul1g, invg1. apply idgF.\nDefined.\n\nNotation \"X </> N\" := (@CosetGroup X N)\n  (at level 35, right associativity) : group_scope.\n\nProgram Definition projhom `{N : <| G} : G ~~> G </> N\n  := hom on projmap.\n\n#[global]\nInstance projhom_surj `{N : <| G} : Surjective (@projhom _ N).\nProof.\n  split. intros y. exists y. simpeq. rewrite mulgV. apply idgF.\nQed.\n\nLemma projhom_ker `{N : <| G} (g : G)\n  : N g == (@projhom _ N g == 1).\nProof. simpeq. now rewrite invg1, mulg1. Qed.\n\nProgram Definition Iso1 `(f : G ~~> H) \n  : (G </> kernel f) <~> (f <@> subgTfor G)\n  := iso x => $[f x, _].\nNext Obligation. now existsS x. Defined.\nNext Obligation.\n  intros x x0 E. simpeq_all.\n  now rewrite <-(invgK (f x0)), <-(mul1g (!! f x0)), mulgT,\n  <-morphV, <-morph.\nDefined.\nNext Obligation.\n  split. intros x y. simpeq. apply morph.\nDefined.\nNext Obligation.\n  split; split.\n  - intros x y E. simpeq_all.\n    now rewrite morph, morphV, <-mulgT, mul1g, invgK.\n  - intros [y [[x T] Hx]]. exists x. now simpeq_all.\nDefined.\n\nProgram Definition commg {G : Group} : Binop G :=\n  dmap (x : G) y => !x * x ^ y.\nNext Obligation.\n  intros x x0 E y y0 E0. now rewrite E, E0.\nDefined.\nNotation \"[ g , h ]\" := (@commg _ g h)\n  (at level 0, g, h at level 99, format \"[ g ,  h ]\")\n  : group_scope.\n\nProgram Definition commorig {G : Group} (A B : {ens G}) :=\n  [ g : G | exists (a : A) (b : B), g == [a, b] ].\nNext Obligation.\n  intros C C0 E. simpeq_all. split; intros [a [b H]];\n  exists a, b; now rewrite2 E.\nDefined.\n\nDefinition commutator {G : Group} (A B : {ens G}) :=\n  generated (commorig A B).\nNotation \"[: A , B :]\" := (@commutator _ A B)\n  (at level 0, A, B at level 99, format \"[: A  ,  B :]\")\n  : group_scope. \n\nProgram Definition derived (G : Group) := \n  [:subgTfor G, subgTfor G:] <<| G.\nNext Obligation.\n  split. intros g [h [[a H] E]] U. simpl. pose (H U).\n  rewrite E. simpl. destruct U. destruct m0.\n  pose (Usg := Build_Subg i). simpl in *. \n  pose (forall_sigS d). simpl in m0.\n  assert (sval (!a * (!g * (a * g) ))).\n  { apply m0. now exists (@Build_sigS _ idTmap a I)\n  , (@Build_sigS _ idTmap g I). }\n  pose (@mulgF _ Usg $[_, m] $[_, H0]). simpl in m1.\n  now rewrite assoc, mulgV, mul1g in m1.\nDefined.\n\nClass Commute {X : Setoid} (op : X -> X -> X) := {\n  commute : forall a b, op a b == op b a\n}.\n\nDefinition IsCommgrp (G : Group) := Commute (@mulg G).\n\nLemma CG_commg1 {G : Group}\n : IsCommgrp G == (forall x y : G, [x, y] == 1).\nProof.\n  split; intros H; simpl in *.\n  - intros x y. rewrite sym, !mulTg, mulg1. now destruct H.\n  - split. intros a b. pose (H b a) as H0.\n    now rewrite sym, !mulTg, mulg1 in H0.\nQed.\n\nLemma quotDG_comm (G : Group) : IsCommgrp (G </> derived G).\nProof.\n  split. intros a b.\n  destruct (surj projhom a) as [a0 Ha].\n  destruct (surj projhom b) as [b0 Hb].\n  rewrite Ha, Hb, <-(invgK (_ * projhom a0)), <-(mulg1 (!!_)),\n    mulTg, invMg, <-assoc, <-!morphV, <-!morph, <-projhom_ker.\n  intros [U [H H0]]. sigapply H0. now exists (inT a0), (inT b0).\nDefined.\n\nLemma hom_hold_comm `{f : G ~~> H} {x y : G}\n  : f [x, y] == [f x, f y].\nProof. simpl. now rewrite !morph, !morphV. Qed.\n\nLemma quot_comm_NDG `(N : <| G) : \n  IsCommgrp (G </> N) -> derived G <= N.\nProof.\n  intros H.\n  assert (commorig (subgTfor G) (subgTfor G) <= N). {\n    rewrite CG_commg1 in H.\n    intros a. destruct a. destruct m. destruct e.\n    simpl. rewrite e, projhom_ker.\n    rewrite <-(H (projhom x) (projhom x0)).\n    apply hom_hold_comm.\n  } \n  rewrite (gensubg_eq_subg(A := N));\n  [now apply gen_compat_lt | intuition].\nQed. \n\nRequire Import Sorted.\nCheck HdRel.\n\n(* Definition solvable (G : Group)  *)\n\nClose Scope group_scope.\nClose Scope setoid_scope.", "meta": {"author": "elle-et-noire", "repo": "algtop", "sha": "e1101a19c604f2c6211fcfa1fb9c23a6ac12ecc0", "save_path": "github-repos/coq/elle-et-noire-algtop", "path": "github-repos/coq/elle-et-noire-algtop/algtop-e1101a19c604f2c6211fcfa1fb9c23a6ac12ecc0/theories/group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6671890077299174}}
{"text": "From DEZ.Has Require Export\n  Homomorphism EquivalenceRelation GroupOperation GroupIdentity GroupInverse.\nFrom DEZ.Is Require Export\n  MonoidHomomorphism Group.\nFrom DEZ.ShouldHave Require Import\n  AdditiveGroupNotations.\n\nClass IsGroupHomomorphism {A B : Type}\n  {A_has_eqv : HasEqv A} (A_has_opr : HasOpr A)\n  (A_has_idn : HasIdn A) (A_has_inv : HasInv A)\n  {B_has_eqv : HasEqv B} (B_has_opr : HasOpr B)\n  (B_has_idn : HasIdn B) (B_has_inv : HasInv B)\n  (has_hom : HasHom A B) : Prop := {\n  A_B_opr_idn_opr_idn_hom_is_monoid_homomorphism :>\n    IsMonoidHomomorphism (A := A) (B := B) opr idn opr idn hom;\n  A_opr_idn_inv_is_group :> IsGroup (A := A) opr idn inv;\n  B_opr_idn_inv_is_group :> IsGroup (A := B) opr idn inv;\n}.\n\n(** We can derive these theorems\n    without knowing about the monoidal structure. *)\n\nSection Context.\n\nContext {A B : Type} `{is_group_homomorphism : IsGroupHomomorphism A B}.\n\nTheorem hom_preserves_identity : hom 0 == 0.\nProof.\n  apply (opr_left_injective (hom 0) 0 (hom 0)).\n  rewrite <- (preserves_operation 0 0).\n  rewrite (right_identifiable 0).\n  rewrite (right_identifiable (hom 0)).\n  reflexivity. Qed.\n\nTheorem hom_preserves_inverse : forall x : A,\n  hom (- x) == - hom x.\nProof.\n  intros x.\n  apply (opr_left_injective (hom (- x)) (- hom x) (hom x)).\n  rewrite <- (preserves_operation x (- x)).\n  rewrite (right_invertible x).\n  rewrite (right_invertible (hom x)).\n  rewrite hom_preserves_identity.\n  reflexivity. Qed.\n\nEnd Context.\n", "meta": {"author": "Tuplanolla", "repo": "dez", "sha": "c2eadc2e032094c3504ec3803c000dba4feb547e", "save_path": "github-repos/coq/Tuplanolla-dez", "path": "github-repos/coq/Tuplanolla-dez/dez-c2eadc2e032094c3504ec3803c000dba4feb547e/garbage/prototype/Is/GroupHomomorphism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.667189007284588}}
{"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 Bool.\n\nRequire Import utils pos vec. \nRequire Import subcode sss.\nRequire Import list_bool.\n\nSet Implicit Arguments.\n\nTactic Notation \"rew\" \"length\" := autorewrite with length_db.\n\nLocal Notation \"e #> x\" := (vec_pos e x).\nLocal Notation \"e [ v / x ]\" := (vec_change e x v).\n\n(** * Binary Stack Machines\n   Binary stack machines have n stacks and there are just two instructions\n  \n   1/ POP s p q : pops the value on stack s and\n                  if Empty then jumps to q \n                  if Zero then jumps to p\n                  if One then jumps to next instruction,\n   2/ PUSH s b : pushes the value b on stack s and jumps to next instructions \n\n *)\n\nInductive bsm_instr n : Set :=\n  | bsm_pop  : pos n -> nat -> nat -> bsm_instr n\n  | bsm_push : pos n -> bool -> bsm_instr n\n  .\n\nNotation POP  := bsm_pop.\nNotation PUSH := bsm_push.\n\n\n(** ** Semantics for BSM *)\n\nSection Binary_Stack_Machine.\n\n  Variable (n : nat).\n\n  Definition bsm_state := (nat*vec (list bool) n)%type.\n\n  Inductive bsm_sss : bsm_instr n -> bsm_state -> bsm_state -> Prop :=\n    | in_bsm_sss_pop_E : forall i x p q v,    v#>x = nil      -> POP x p q // (i,v) -1> (  q,v)\n    | in_bsm_sss_pop_0 : forall i x p q v ll, v#>x = Zero::ll -> POP x p q // (i,v) -1> (  p,v[ll/x])\n    | in_bsm_sss_pop_1 : forall i x p q v ll, v#>x = One ::ll -> POP x p q // (i,v) -1> (1+i,v[ll/x])\n    | in_bsm_sss_push  : forall i x b v,                         PUSH x b  // (i,v) -1> (1+i,v[(b::v#>x)/x])\n  where \"i // s -1> t\" := (bsm_sss i s t).\n\n  Ltac mydiscr := \n      match goal with H: ?x = _, G : ?x = _ |- _ => rewrite H in G; discriminate end.\n\n  Ltac myinj := \n      match goal with H: ?x = _, G : ?x = _ |- _ => rewrite H in G; inversion G; subst; auto end.      \n  \n  (* bsm_sss is a functional relation *)\n      \n  Fact bsm_sss_fun i s t1 t2 : i // s -1> t1 -> i // s -1> t2 -> t1 = t2.\n  Proof. intros []; subst; inversion 1; subst; auto; try mydiscr; myinj. Qed.\n\n  (* bsm_sss is an informativelly total relation *) \n  \n  Fact bsm_sss_total ii s : { t | ii // s -1> t }.\n  Proof.\n    destruct s as (i,v).\n    destruct ii as [ x p q | x b ].\n    + case_eq (v#>x); [ intros Hx | intros [] l Hx ].\n      * exists (q,v); constructor; trivial.\n      * exists (1+i,v[l/x]); constructor; trivial.\n      * exists (p,v[l/x]); constructor; trivial.\n    + exists (1+i,v[(b::v#>x)/x]); constructor.\n  Qed.\n\n  Fact bsm_sss_total' ii s : exists t, ii // s -1> t.\n  Proof.\n    destruct (bsm_sss_total ii s); firstorder.\n  Qed.\n  \n  (* Hence computations can only stop at instructions which lie outside the code \n     Stalling means no instruction can be executed anymore. It DOES NOT mean\n     that the state cannot change anymore (this is a strictly lesser requirement).\n  *)\n  \n  Fact bsm_sss_stall : forall P s, sss_step_stall bsm_sss P s -> out_code (fst s) P.\n  Proof.\n    intros (i,P) (q,v) H; unfold fst.\n    red in H.\n    destruct (in_out_code_dec q (i,P)) as [ H1 | ]; auto; exfalso.\n    apply in_code_subcode in H1.\n    destruct H1 as (ii & l & r & H1 & H2).\n    simpl in H1.\n    destruct (bsm_sss_total ii (q,v)) as (t & Ht).\n    apply (H t); subst; apply in_sss_step; auto.\n  Qed.\n \n  Notation \"P // s -[ k ]-> t\" := (sss_steps bsm_sss P k s t).\n  Notation \"P // s ->> t\" := (sss_compute bsm_sss P s t).\n\n  Fact bsm_compute_POP_E P i x p q v st :\n         (i,POP x p q::nil) <sc P\n      -> v#>x = nil\n      -> P // (q,v) ->> st\n      -> P // (i,v) ->> st.\n  Proof.\n    intros H1 H2.\n    apply subcode_sss_compute_trans with (1 := H1).\n    exists 1; apply sss_steps_1.\n    apply in_sss_step with (l := nil).\n    simpl; omega.\n    constructor; auto.\n  Qed.\n\n  Fact bsm_compute_POP_0 P i x p q ll v st :\n         (i,POP x p q::nil) <sc P\n      -> v#>x = Zero::ll\n      -> P // (p,v[ll/x]) ->> st\n      -> P // (i,v) ->> st.\n  Proof.\n    intros H1 H2.\n    apply subcode_sss_compute_trans with (1 := H1).\n    exists 1; apply sss_steps_1.\n    apply in_sss_step with (l := nil).\n    simpl; omega.\n    constructor; auto.\n  Qed.\n\n  Fact bsm_compute_POP_1 P i x p q ll v st :\n         (i,POP x p q::nil) <sc P\n      -> v#>x = One::ll\n      -> P // (1+i,v[ll/x]) ->> st\n      -> P // (i,v) ->> st.\n  Proof.\n    intros H1 H2.\n    apply subcode_sss_compute_trans with (1 := H1).\n    exists 1; apply sss_steps_1.\n    apply in_sss_step with (l := nil).\n    simpl; omega.\n    constructor; auto.\n  Qed.\n\n  Fact bsm_compute_POP_any P i x p q b ll v st :\n         (i,POP x p q::nil) <sc P\n      -> v#>x = b::ll\n      -> p = 1+i\n      -> P // (1+i,v[ll/x]) ->> st\n      -> P // (i,v) ->> st.\n  Proof.\n    destruct b; intros H1 H2 H3.\n    apply bsm_compute_POP_1 with p q; auto.\n    apply bsm_compute_POP_0 with q; subst; auto.\n  Qed.\n\n  Fact bsm_compute_PUSH P i x b v st :\n         (i,PUSH x b::nil) <sc P\n      -> P // (1+i,v[(b::v#>x)/x]) ->> st\n      -> P // (i,v) ->> st.\n  Proof.\n    intros H1.\n    apply subcode_sss_compute_trans with (1 := H1).\n    exists 1; apply sss_steps_1.\n    apply in_sss_step with (l := nil).\n    simpl; omega.\n    constructor; auto.\n  Qed.\n\n  Fact bsm_steps_POP_0_inv a P i x p q ll v st :\n         (i,POP x p q::nil) <sc P\n      -> v#>x = Zero::ll\n      -> st <> (i,v)\n      -> P // (i,v) -[a]-> st\n      -> { b | b < a /\\ P // (p,v[ll/x]) -[b]-> st }.\n  Proof.\n    intros H1 H2 H3 H4.\n    apply sss_steps_inv in H4.\n    destruct H4 as [ (_ & ?) | (b & H4) ]; subst.\n    destruct H3; auto.\n    exists b.\n    destruct H4 as (st2 & ? & H4 & H5); subst.\n    split.\n    omega.\n    apply sss_step_subcode_inv with (1 := H1) in H4.\n    inversion H4; subst; try mydiscr; myinj.\n  Qed.\n\n  Fact bsm_steps_POP_1_inv a P i x p q ll v st :\n         (i,POP x p q::nil) <sc P\n      -> v#>x = One::ll\n      -> st <> (i,v)\n      -> P // (i,v) -[a]-> st\n      -> { b | b < a /\\ P // (1+i,v[ll/x]) -[b]-> st }.\n  Proof.\n    intros H1 H2 H3 H4.\n    apply sss_steps_inv in H4.\n    destruct H4 as [ (_ & ?) | (b & H4) ]; subst.\n    destruct H3; auto.\n    exists b.\n    destruct H4 as (st2 & ? & H4 & H5); subst.\n    split.\n    omega.\n    apply sss_step_subcode_inv with (1 := H1) in H4.\n    inversion H4; subst; try mydiscr; myinj.\n  Qed.\n\n  Fact bsm_steps_POP_any_inv a P i x p q b ll v st :\n         (i,POP x p q::nil) <sc P\n      -> v#>x = b::ll\n      -> p = 1+i\n      -> st <> (i,v)\n      -> P // (i,v) -[a]-> st\n      -> { b | b < a /\\ P // (1+i,v[ll/x]) -[b]-> st }.\n  Proof.\n    intros.\n    destruct b.\n    apply bsm_steps_POP_1_inv with p q; auto.\n    apply bsm_steps_POP_0_inv with i q; subst; auto.\n  Qed.\n\n  Fact bsm_steps_POP_E_inv a P i x p q v st :\n         (i,POP x p q::nil) <sc P\n      -> v#>x = nil\n      -> st <> (i,v)\n      -> P // (i,v) -[a]-> st\n      -> { b | b < a /\\ P // (q,v) -[b]-> st }.\n  Proof.\n    intros H1 H2 H3 H4.\n    apply sss_steps_inv in H4.\n    destruct H4 as [ (? & ?) | (b & H4) ]; subst; auto.\n    destruct H3; auto.\n    exists b.\n    destruct H4 as (st2 & ? & H4 & H5); subst.\n    split.\n    omega.\n    apply sss_step_subcode_inv with (1 := H1) in H4.\n    inversion H4; subst; try mydiscr; myinj.\n  Qed.\n\n  Fact bsm_steps_PUSH_inv k P i x b v st :\n         (i,PUSH x b::nil) <sc P\n      -> st <> (i,v)\n      -> P // (i,v) -[k]-> st\n      -> { a | a < k /\\ P // (1+i,v[(b::v#>x)/x]) -[a]-> st }.\n  Proof.\n    intros H1 H2 H4.\n    apply sss_steps_inv in H4.\n    destruct H4 as [ (? & ?) | (a & H4) ]; subst; auto.\n    destruct H2; auto.\n    exists a.\n    destruct H4 as (st2 & ? & H4 & H5); subst.\n    split.\n    omega.\n    apply sss_step_subcode_inv with (1 := H1) in H4.\n    inversion H4; subst; auto.\n  Qed.\n\nEnd Binary_Stack_Machine.\n\nTactic Notation \"bsm\" \"sss\" \"POP\" \"empty\" \"with\" uconstr(a) constr(b) constr(c) := \n     apply bsm_compute_POP_E with (x := a) (p := b) (q := c); auto.\n\nTactic Notation \"bsm\" \"sss\" \"POP\" \"0\" \"with\" uconstr(a) constr(b) constr(c) uconstr(d) := \n     apply bsm_compute_POP_0 with (x := a) (p := b) (q := c) (ll := d); auto.\n\nTactic Notation \"bsm\" \"sss\" \"POP\" \"1\" \"with\" uconstr(a) constr(b) constr(c) uconstr(d) := \n     apply bsm_compute_POP_1 with (x := a) (p := b) (q := c) (ll := d); auto.\n\nTactic Notation \"bsm\" \"sss\" \"POP\" \"any\" \"with\" uconstr(a) constr(c) constr(d) constr(e) constr(f) := \n     apply bsm_compute_POP_any with (x := a) (p := c) (q := d) (b := e) (ll := f); auto.\n\nTactic Notation \"bsm\" \"sss\" \"PUSH\" \"with\" uconstr(a) constr(q) := \n     apply bsm_compute_PUSH with (x := a) (b := q); auto.\n\nTactic Notation \"bsm\" \"sss\" \"stop\" := exists 0; apply sss_steps_0; auto.\n\nTactic Notation \"bsm\" \"inv\" \"POP\" \"empty\" \"with\" hyp(H) constr(a) constr(b) constr(c) constr(d) :=\n     apply bsm_steps_POP_E_inv with (x := a) (p := b) (q := c) (ll := d) in H; auto.\n\nTactic Notation \"bsm\" \"inv\" \"POP\" \"0\" \"with\" hyp(H) constr(a) constr(b) constr(c) constr(d) :=\n     apply bsm_steps_POP_0_inv with (x := a) (p := b) (q := c) (ll := d) in H; auto.\n\nTactic Notation \"bsm\" \"inv\" \"POP\" \"1\" \"with\" hyp(H) constr(a) constr(b) constr(c) constr(d) :=\n     apply bsm_steps_POP_1_inv with (x := a) (p := b) (q := c) (ll := d) in H; auto.\n\nTactic Notation \"bsm\" \"inv\" \"POP\" \"any\" \"with\" hyp(H) constr(a) constr(c) constr(d) constr(e) constr(f) :=\n     apply bsm_steps_POP_any_inv with (x := a) (p := c) (q := d) (b := e) (ll := f) in H; auto.\n\nTactic Notation \"bsm\" \"inv\" \"PUSH\" \"with\" hyp(H) constr(a) constr(c) :=\n     apply bsm_steps_PUSH_inv with (x := a) (b := c) in H; auto.\n\nHint Immediate bsm_sss_fun.\n\n(* The Halting problem for BSM *)\n  \nDefinition BSM_PROBLEM := { n : nat & { i : nat & { P : list (bsm_instr n) & vec (list bool) n } } }.\n\nLocal Notation \"P // s ↓\" := (sss_terminates (@bsm_sss _) P s).\n\nDefinition BSM_HALTING (P : BSM_PROBLEM) := \n  match P with existT _ n (existT _ i (existT _ P v)) => (i,P) // (i,v) ↓ end.\n\n\n     \n", "meta": {"author": "uds-psl", "repo": "ill-undecidability", "sha": "0bfda1a33cb3411c8f2c0263e15d5c85c090721d", "save_path": "github-repos/coq/uds-psl-ill-undecidability", "path": "github-repos/coq/uds-psl-ill-undecidability/ill-undecidability-0bfda1a33cb3411c8f2c0263e15d5c85c090721d/coq/Bsm/bsm_defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6671384256060131}}
{"text": "Require Export semantics.\nRequire Export typing.\n\n(* Definition 1 : Low Equivalence *)\n\nDefinition lowEquivalentMem (M1 M2: memory):  Prop :=\n (forall x v,\n \t\t(M1 x = Some (vint v low)) <-> (M2 x = Some (vint v low)))\n \t/\\\n (forall x v,\n\t\t(M1 x = Some (varr v low)) <-> (M2 x = Some (varr v low))).\n\n\n(* Definition 2 : Gamma Validity *)\n\nDefinition gammavalid (gamma:environment) (M:memory) : Prop :=\n\tforall x l,\n\t((gamma x = Some (lnat l)) <-> (exists n, (M x = Some (vint n l))))\n\t/\\\n\t((gamma x = Some (larr l)) <-> (exists a, (M x = Some (varr a l)))).\n\n\n\n(* Definition 3 : Memory Trace Obliviousness *)\n\nDefinition memTraceObliv (gamma:environment) (S:program) : Prop :=\n\tforall M1 M2 t1 M1' t2 M2',\n\t(lowEquivalentMem M1 M2) ->\n\t(gammavalid gamma M1) ->\n\t(gammavalid gamma M2) ->\n\t(progSem M1 S t1 M1') ->\n\t(progSem M2 S t2 M2') ->\n\n\t\t((traceequiv t1 t2) /\\ (lowEquivalentMem M1' M2')).", "meta": {"author": "cimbriano", "repo": "mtocoq", "sha": "bd873f7e7c46f97781a06ac42d5c0265e566bf5c", "save_path": "github-repos/coq/cimbriano-mtocoq", "path": "github-repos/coq/cimbriano-mtocoq/mtocoq-bd873f7e7c46f97781a06ac42d5c0265e566bf5c/mto_paper_definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6671384164315086}}
{"text": "Require Import Coq.Classes.Equivalence.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Unicode.Utf8.\nRequire Import Iteration.Lattice.\n\nGeneralizable All Variables.\n\nLocal Open Scope equiv_scope.\n\nDefinition inf {X} `{Lattice A} (G : list (X → A)) (x : X) :=\n  List.fold_right (λ g a, a ⊓ g x) top G.\n\n(* We use the paper's equivalent definition since it's simpler to write *)\nDefinition lower_selection {X} `{Lattice A} (G : list (X → A)) : Prop :=\n  ∀ x, Exists (λ g, g x === inf G x) G.\n\nDefinition fixed_point `{Equivalence A} (f : A → A) (x : A) : Prop :=\n  x === f x.\n\nDefinition least_fixed_point `{Lattice A} (f : A → A) (x : A) : Prop :=\n  fixed_point f x ∧ ∀ y, fixed_point f y → Lattice.le_meet x y.\n\n", "meta": {"author": "Skyb0rg007", "repo": "Policy-Iteration-Coq", "sha": "687dcdc869f3c51f430d4adeaa9fcc7a8da86115", "save_path": "github-repos/coq/Skyb0rg007-Policy-Iteration-Coq", "path": "github-repos/coq/Skyb0rg007-Policy-Iteration-Coq/Policy-Iteration-Coq-687dcdc869f3c51f430d4adeaa9fcc7a8da86115/theories/Selection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6671384144400152}}
{"text": "Require Import init.\n\nRequire Import order_minmax.\n\nRequire Export analysis_norm.\nRequire Import analysis_series.\n\n(* If I ever want to do analysis on an ordered field that's not the real\n * numbers, I'll figure it out then.\n *)\n(* begin hide *)\nSection AnalysisOrder.\n\nExisting Instance abs_metric.\n(* end hide *)\nTheorem seq_lim_pos : ∀ xf x, (∀ n, 0 ≤ xf n) → seq_lim xf x → 0 ≤ x.\nProof.\n    intros xf x xf_pos x_lim.\n    rewrite metric_seq_lim in x_lim.\n    classic_contradiction contr.\n    rewrite nle_lt in contr.\n    apply neg_pos2 in contr.\n    specialize (x_lim _ contr) as [N x_lim].\n    specialize (x_lim N (refl N)).\n    cbn in x_lim.\n    rewrite abs_minus in x_lim.\n    apply (le_lt_trans (abs_le_pos _)) in x_lim.\n    unfold real_neg in x_lim.\n    rewrite <- (plus_lid (-x)) in x_lim at 2.\n    apply lt_plus_rcancel in x_lim.\n    destruct (le_lt_trans (xf_pos N) x_lim); contradiction.\nQed.\n\nTheorem seq_lim_le : ∀ xf yf x y,\n    (∀ n, xf n ≤ yf n) → seq_lim xf x → seq_lim yf y → x ≤ y.\nProof.\n    intros xf yf x y f_leq x_lim y_lim.\n    pose (xyf n := yf n - xf n).\n    apply le_plus_0_anb_b_a.\n    apply (seq_lim_pos xyf).\n    -   intros n; unfold xyf.\n        apply le_plus_0_anb_b_a.\n        apply f_leq.\n    -   apply seq_lim_plus.\n        +   exact y_lim.\n        +   apply seq_lim_neg.\n            exact x_lim.\nQed.\n\nTheorem seq_lim_le_constant : ∀ xf x y,\n    (∀ n, xf n ≤ y) → seq_lim xf x → x ≤ y.\nProof.\n    intros xf x y f_leq x_lim.\n    apply (seq_lim_le xf (λ _, y)).\n    -   exact f_leq.\n    -   exact x_lim.\n    -   apply constant_seq_lim.\nQed.\n\nTheorem seq_lim_ge_constant : ∀ yf x y,\n    (∀ n, x ≤ yf n) → seq_lim yf y → x ≤ y.\nProof.\n    intros yf x y f_leq y_lim.\n    apply (seq_lim_le (λ _, x) yf).\n    -   exact f_leq.\n    -   apply constant_seq_lim.\n    -   exact y_lim.\nQed.\n\nTheorem increasing_seq_converges : ∀ f : nat → real,\n    (∃ M, ∀ n, |f n| ≤ M) → (∀ n, f n ≤ f (nat_suc n)) →\n    seq_converges f.\nProof.\n    intros f [M M_bound] f_inc.\n    assert (∀ m n, m ≤ n → f m ≤ f n) as f_inc2.\n    {\n        intros m n leq.\n        apply nat_le_ex in leq as [c eq].\n        subst n.\n        nat_induction c.\n        -   rewrite plus_rid.\n            apply refl.\n        -   apply (trans IHc).\n            rewrite nat_plus_rsuc.\n            apply f_inc.\n    }\n    pose (S x := ∃ n, f n = x).\n    assert (∃ x, S x) as S_ex by (exists (f 0); exists 0; reflexivity).\n    assert (has_upper_bound le S) as S_bound.\n    {\n        exists M.\n        intros x [n x_eq]; subst x.\n        apply (trans (abs_le_pos _)).\n        apply M_bound.\n    }\n    pose proof (sup_complete S S_ex S_bound) as [x [x_bound x_least]].\n    exists x.\n    rewrite metric_seq_lim.\n    intros ε ε_pos.\n    assert (¬is_upper_bound le S (x - ε)) as xε_lt.\n    {\n        intros contr.\n        specialize (x_least _ contr).\n        rewrite <- (plus_rid x) in x_least at 1.\n        apply le_plus_lcancel in x_least.\n        apply pos_neg2 in ε_pos.\n        destruct (le_lt_trans x_least ε_pos); contradiction.\n    }\n    unfold is_upper_bound in xε_lt.\n    rewrite not_all in xε_lt.\n    destruct xε_lt as [y xε_lt].\n    rewrite not_impl in xε_lt.\n    destruct xε_lt as [[N y_eq] ltq]; subst y.\n    rewrite nle_lt in ltq.\n    exists N.\n    intros n n_geq.\n    cbn.\n    rewrite abs_pos_eq.\n    2: {\n        apply le_plus_0_anb_b_a.\n        apply x_bound.\n        exists n.\n        reflexivity.\n    }\n    apply lt_plus_rrmove.\n    rewrite <- (neg_neg ε).\n    apply lt_plus_llmove.\n    rewrite plus_comm.\n    apply (lt_le_trans ltq).\n    apply f_inc2.\n    exact n_geq.\nQed.\n\nTheorem decreasing_seq_converges : ∀ f : nat → real,\n    (∃ M, ∀ n, |f n| ≤ M) → (∀ n, f (nat_suc n) ≤ f n) →\n    seq_converges f.\nProof.\n    intros f [M M_bound] f_dec.\n    pose (g n := -f n).\n    assert (seq_converges g) as [x x_lim].\n    {\n        apply increasing_seq_converges.\n        -   exists M.\n            unfold g.\n            setoid_rewrite abs_neg.\n            exact M_bound.\n        -   intros n.\n            unfold g.\n            rewrite <- le_neg.\n            apply f_dec.\n    }\n    exists (-x).\n    apply seq_lim_neg in x_lim.\n    unfold g in x_lim.\n    assert ((λ n, --f n) = (λ n, f n)) as f_eq.\n    {\n        apply functional_ext.\n        intros n.\n        apply neg_neg.\n    }\n    rewrite f_eq in x_lim.\n    exact x_lim.\nQed.\n\nTheorem real_complete : complete real.\nProof.\n    intros f f_cauchy.\n    pose (fn m n := f (m + n)).\n    assert (∀ m, cauchy_seq (fn m)) as fn_cauchy.\n    {\n        intros m.\n        intros ε ε_pos.\n        specialize (f_cauchy ε ε_pos) as [N f_cauchy].\n        exists N.\n        intros i j i_ge j_ge.\n        unfold fn.\n        apply f_cauchy.\n        all: rewrite <- (plus_lid N).\n        all: apply le_lrplus.\n        1, 3: apply nat_pos.\n        1, 2: assumption.\n    }\n    assert (∀ m, seq_norm_bounded (fn m)) as fn_bounded.\n    {\n        intros m.\n        apply seq_bounded_norm_bounded.\n        apply cauchy_bounded.\n        apply fn_cauchy.\n    }\n    pose (S m x := ∃ n, x = fn m n).\n    assert (∀ m, ∃ a, is_supremum le (S m) a) as sup_ex.\n    {\n        intros m.\n        apply sup_complete.\n        -   exists (fn m 0).\n            exists 0.\n            reflexivity.\n        -   specialize (fn_bounded m) as [M M_bound].\n            exists M.\n            unfold is_upper_bound; cbn.\n            intros y [n y_eq]; subst y.\n            apply (trans2 (M_bound n)).\n            apply abs_le_pos.\n    }\n    pose (a m := ex_val (sup_ex m)).\n    assert (seq_converges a) as [x x_lim].\n    {\n        apply decreasing_seq_converges.\n        -   pose proof (fn_bounded 0) as [M M_bound].\n            unfold fn in M_bound.\n            setoid_rewrite plus_lid in M_bound.\n            exists M.\n            intros n.\n            unfold a.\n            rewrite_ex_val A A_sup.\n            destruct A_sup as [A_upper A_least].\n            unfold abs; cbn; case_if.\n            +   apply A_least.\n                intros y [m y_eq]; subst y.\n                unfold fn.\n                apply (trans2 (M_bound (n + m))).\n                apply abs_le_pos.\n            +   rewrite nle_lt in n0.\n                assert (S n (fn n 0)) as fn_in by (exists 0; reflexivity).\n                specialize (A_upper (fn n 0) fn_in).\n                apply le_neg in A_upper.\n                apply (trans A_upper).\n                unfold fn.\n                rewrite plus_rid.\n                apply (trans2 (M_bound n)).\n                apply abs_le_neg.\n        -   intros m.\n            unfold a.\n            rewrite_ex_val A [A_upper A_least].\n            rewrite_ex_val B [B_upper B_least].\n            apply A_least.\n            intros y [n y_eq]; subst y.\n            apply B_upper.\n            unfold S, fn.\n            exists (nat_suc n).\n            rewrite nat_plus_lrsuc.\n            reflexivity.\n    }\n    exists x.\n    rewrite metric_seq_lim in *; cbn in *.\n    intros ε ε_pos.\n    pose proof (half_pos ε_pos) as ε2_pos.\n    pose proof (half_pos ε2_pos) as ε4_pos.\n    specialize (f_cauchy _ ε2_pos) as [N1 f_cauchy]; cbn in f_cauchy.\n    specialize (x_lim _ ε4_pos) as [N2 x_lim].\n    pose (N := max N1 N2).\n    exists N.\n    intros n n_ge.\n    assert (∃ n', N ≤ n' ∧ |a N - f n'| < ε/2/2) as [n' [n'_ge af_leq]].\n    {\n        unfold a.\n        rewrite_ex_val A A_sup.\n        destruct A_sup as [A_upper' A_least'].\n        unfold is_upper_bound, S in A_upper'.\n        assert (∀ n, fn N n ≤ A) as A_upper.\n        {\n            intros m.\n            apply A_upper'.\n            exists m.\n            reflexivity.\n        }\n        assert (∀ y, (∀ n, fn N n ≤ y) → A ≤ y) as A_least.\n        {\n            intros y y_leq.\n            apply A_least'.\n            intros z [m z_eq]; subst z.\n            apply y_leq.\n        }\n        clear A_upper' A_least'.\n        classic_contradiction contr.\n        rewrite not_ex in contr.\n        assert (A ≤ A - ε/2/2) as leq.\n        {\n            apply A_least.\n            intros m.\n            unfold fn.\n            specialize (contr (N + m)).\n            rewrite not_and, nle_lt, nlt_le in contr.\n            destruct contr as [contr|contr].\n            -   rewrite <- (plus_rid N) in contr at 2.\n                apply lt_plus_lcancel in contr.\n                contradiction (nat_neg2 contr).\n            -   specialize (A_upper m).\n                unfold fn in A_upper.\n                apply le_plus_0_anb_b_a in A_upper.\n                unfold abs in contr; cbn in contr; case_if; try contradiction.\n                apply le_plus_lrmove.\n                apply le_plus_rrmove in contr.\n                rewrite neg_neg, plus_comm in contr.\n                exact contr.\n        }\n        rewrite <- (plus_rid A) in leq at 1.\n        apply le_plus_lcancel in leq.\n        apply pos_neg in leq.\n        rewrite neg_neg in leq.\n        clear - leq ε4_pos.\n        destruct (lt_le_trans ε4_pos leq); contradiction.\n    }\n    specialize (x_lim N (rmax _ _)).\n    specialize (f_cauchy n' n (trans (lmax _ _) n'_ge) (trans (lmax _ _) n_ge)).\n    clear - f_cauchy x_lim af_leq.\n    pose proof (lt_lrplus x_lim af_leq) as ltq.\n    rewrite plus_half in ltq.\n    apply (le_lt_trans (abs_tri _ _)) in ltq.\n    rewrite <- plus_assoc in ltq.\n    rewrite plus_llinv in ltq.\n    clear - f_cauchy ltq.\n    pose proof (lt_lrplus ltq f_cauchy) as eq.\n    rewrite plus_half in eq.\n    apply (le_lt_trans (abs_tri _ _)) in eq.\n    rewrite <- plus_assoc in eq.\n    rewrite plus_llinv in eq.\n    exact eq.\nQed.\n\nTheorem series_le_converge : ∀ a b,\n    seq_converges (series b) → (∀ n, 0 ≤ a n) → (∀ n, a n ≤ b n) →\n    seq_converges (series a).\nProof.\n    intros a b b_conv a_pos ab.\n    apply cauchy_series_converges.\n    1: exact real_complete.\n    apply series_converges_cauchy in b_conv.\n    intros ε ε_pos.\n    specialize (b_conv ε ε_pos) as [N b_conv].\n    exists N.\n    intros i j leq.\n    specialize (b_conv i j leq).\n    apply (le_lt_trans2 b_conv).\n    clear - a_pos ab.\n    assert (0 ≤ sum a i j) as sum_a_pos.\n    {\n        clear - a_pos.\n        nat_induction j.\n        -   apply refl.\n        -   cbn.\n            specialize (a_pos (i + j)).\n            pose proof (le_lrplus IHj a_pos) as leq.\n            rewrite plus_rid in leq.\n            exact leq.\n    }\n    assert (0 ≤ sum b i j) as sum_b_pos.\n    {\n        clear - a_pos ab.\n        nat_induction j.\n        -   apply refl.\n        -   cbn.\n            specialize (a_pos (i + j)).\n            specialize (ab (i + j)).\n            pose proof (le_lrplus IHj (trans a_pos ab)) as leq.\n            rewrite plus_rid in leq.\n            exact leq.\n    }\n    unfold abs; cbn.\n    case_if; case_if; try contradiction.\n    clear l l0 sum_a_pos sum_b_pos.\n    nat_induction j.\n    -   unfold zero; cbn.\n        apply refl.\n    -   cbn.\n        apply le_lrplus.\n        +   exact IHj.\n        +   apply ab.\nQed.\n\nTheorem seq_squeeze : ∀ an bn cn l, (∀ n, an n ≤ bn n ∧ bn n ≤ cn n) →\n    seq_lim an l → seq_lim cn l → seq_lim bn l.\nProof.\n    intros an bn cn l leqs anl cnl.\n    rewrite metric_seq_lim in *.\n    intros ε ε_pos.\n    cbn in *.\n    specialize (anl ε ε_pos) as [N1 anl].\n    specialize (cnl ε ε_pos) as [N2 cnl].\n    exists (max N1 N2).\n    intros n n_geq.\n    specialize (anl n (trans (lmax N1 N2) n_geq)).\n    specialize (cnl n (trans (rmax N1 N2) n_geq)).\n    specialize (leqs n) as [leq1 leq2].\n    rewrite abs_minus in *.\n    apply abs_lt.\n    apply abs_lt in anl as [anl1 anl2].\n    apply abs_lt in cnl as [cnl1 cnl2].\n    split.\n    -   apply (lt_le_trans anl1).\n        apply le_rplus.\n        exact leq1.\n    -   apply (le_lt_trans2 cnl2).\n        apply le_rplus.\n        exact leq2.\nQed.\n\n(* begin hide *)\nLocal Open Scope nat_scope.\n(* end hide *)\nTheorem alternating_series_test : ∀ an,\n    (∀ n, an (nat_suc n) ≤ an n) →\n    seq_lim an 0 →\n    seq_converges (series (λ n, (-(1))^n * an n)).\nProof.\n    intros an an_dec an0'.\n    pose proof an0' as an0.\n    rewrite metric_seq_lim in an0.\n    pose (an' n := (-(1))^n * an n).\n    fold an'.\n    pose (an'_even n := series an' (2*n)).\n    pose (an'_odd n := series an' (2*n + 1)).\n    assert (∀ n, an'_odd n = an'_even n + an (2*n)) as even_odd.\n    {\n        intros n.\n        unfold an'_odd, an'_even.\n        rewrite plus_comm.\n        change (1 + 2*n) with (nat_suc (2*n)).\n        cbn.\n        rewrite plus_lid.\n        unfold an' at 2.\n        rewrite nat_pow_neg_even.\n        rewrite mult_lid.\n        reflexivity.\n    }\n    assert (∀ m n, an (m + n) ≤ an n) as an_dec2.\n    {\n        intros m n.\n        nat_induction m.\n        -   rewrite plus_lid.\n            apply refl.\n        -   rewrite nat_plus_lsuc.\n            apply (trans2 IHm).\n            apply an_dec.\n    }\n    assert (∀ n, 0 ≤ an n) as an_pos.\n    {\n        intros n.\n        classic_contradiction contr.\n        rewrite nle_lt in contr.\n        apply neg_pos2 in contr.\n        specialize (an0 _ contr) as [N an0].\n        destruct (connex n N) as [leq|leq].\n        -   specialize (an0 N (refl N)).\n            cbn in an0.\n            rewrite plus_lid in an0.\n            apply nat_le_ex in leq as [c eq]; subst N.\n            specialize (an_dec2 c n).\n            apply le_neg in an_dec2.\n            pose proof (lt_le_trans an0 an_dec2) as ltq.\n            pose proof (lt_le_trans contr an_dec2) as pos.\n            rewrite plus_comm in ltq.\n            rewrite abs_pos_eq in ltq by apply pos.\n            destruct ltq; contradiction.\n        -   specialize (an0 n leq).\n            cbn in an0.\n            rewrite plus_lid in an0.\n            rewrite abs_pos_eq in an0 by apply contr.\n            destruct an0; contradiction.\n    }\n    assert (∀ n, 0 ≤ an'_even n) as even_pos.\n    {\n        intros n.\n        nat_induction n.\n        -   unfold an'_even.\n            rewrite mult_ranni.\n            apply refl.\n        -   unfold an'_even.\n            rewrite nat_mult_rsuc.\n            change (2 + 2*n) with (nat_suc (nat_suc (2*n))).\n            cbn.\n            do 2 rewrite plus_lid.\n            rewrite <- (plus_rid 0).\n            rewrite <- plus_assoc.\n            apply le_lrplus; [>exact IHn|].\n            unfold an'.\n            change (nat_suc (2*n)) with (1 + 2*n).\n            rewrite (plus_comm 1 (2*n)).\n            rewrite nat_pow_neg_even.\n            rewrite nat_pow_neg_odd.\n            rewrite mult_lid.\n            rewrite mult_neg_one.\n            apply le_plus_0_anb_b_a.\n            rewrite plus_comm.\n            apply an_dec.\n    }\n    assert (∀ n, 0 ≤ an'_odd n) as odd_pos.\n    {\n        intros n.\n        rewrite even_odd.\n        rewrite <- (plus_rid 0).\n        apply le_lrplus.\n        -   apply even_pos.\n        -   apply an_pos.\n    }\n    assert (seq_converges an'_odd) as [l l_odd].\n    {\n        apply decreasing_seq_converges.\n        -   exists (an 0).\n            intros n.\n            rewrite abs_pos_eq by apply odd_pos.\n            nat_induction n.\n            +   unfold an'_odd.\n                rewrite mult_ranni, plus_lid.\n                unfold one; cbn.\n                do 2 rewrite plus_lid.\n                unfold an'; cbn.\n                rewrite mult_lid.\n                apply refl.\n            +   apply (trans2 IHn).\n                unfold an'_odd.\n                rewrite nat_mult_rsuc.\n                rewrite <- plus_assoc.\n                change (2 + (2*n + 1)) with (nat_suc (nat_suc (2*n + 1))).\n                cbn.\n                do 2 rewrite plus_lid.\n                unfold series.\n                rewrite <- (plus_rid (sum _ _ _)) at 2.\n                rewrite <- plus_assoc.\n                apply le_lplus.\n                unfold an'.\n                change (nat_suc (2 * n + 1)) with (1 + (2*n + 1)) at 1.\n                rewrite (plus_comm 1 (2*n + 1)).\n                rewrite <- plus_assoc.\n                rewrite <- (mult_rid 2) at 4.\n                rewrite <- ldist.\n                rewrite nat_pow_neg_even, nat_pow_neg_odd.\n                rewrite mult_lid, mult_neg_one.\n                apply le_plus_nab_0_b_a.\n                apply an_dec.\n        -   intros n.\n            unfold an'_odd.\n            rewrite nat_mult_rsuc.\n            rewrite <- plus_assoc.\n            change (2 + (2*n + 1)) with (nat_suc (nat_suc (2*n + 1))).\n            cbn.\n            rewrite <- (plus_rid (series _ _)).\n            rewrite <- plus_assoc.\n            apply le_lplus.\n            do 2 rewrite plus_lid.\n            unfold an'.\n            rewrite nat_pow_suc.\n            rewrite nat_pow_neg_odd.\n            do 2 rewrite mult_neg_one.\n            rewrite neg_neg.\n            rewrite mult_lid.\n            apply le_plus_nab_0_b_a.\n            apply an_dec.\n    }\n    assert (seq_lim an'_even l) as l_even.\n    {\n        replace an'_even with (λ n, an'_odd n - an (2 * n)).\n        2: {\n            apply functional_ext; intros n.\n            rewrite <- plus_rrmove.\n            apply even_odd.\n        }\n        rewrite <- (plus_rid l).\n        apply seq_lim_plus; [>exact l_odd|].\n        rewrite <- neg_zero.\n        apply seq_lim_neg.\n        apply (subsequence_lim_eq _ _ _ an0').\n        exists (λ n, 2*n).\n        split; [>|reflexivity].\n        split.\n        -   rewrite nat_mult_rsuc.\n            rewrite <- (plus_lid (2*n)) at 1.\n            apply le_rplus.\n            exact true.\n        -   intros contr.\n            rewrite nat_mult_rsuc in contr.\n            rewrite <- (plus_lid (2*n)) in contr at 1.\n            apply plus_rcancel in contr.\n            inversion contr.\n    }\n    exists l.\n    apply seq_lim_even_odd.\n    -   exact l_even.\n    -   exact l_odd.\nQed.\n(* begin hide *)\nEnd AnalysisOrder.\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/Analysis/Real/analysis_order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.6671246674102174}}
{"text": "(** * Poly: Polymorphism and Higher-Order Functions *)\n\n(* Final reminder: Please do not put solutions to the exercises in\n   publicly accessible places.  Thank you!! *)\n\n(* Suppress some annoying warnings from Coq: *)\nSet Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export Lists.\n\n(* ################################################################# *)\n(** * Polymorphism *)\n\n(** In this chapter we continue our development of basic\n    concepts of functional programming.  The critical new ideas are\n    _polymorphism_ (abstracting functions over the types of the data\n    they manipulate) and _higher-order functions_ (treating functions\n    as data).  We begin with polymorphism. *)\n\n(* ================================================================= *)\n(** ** Polymorphic Lists *)\n\n(** For the last chapter, we've been working with lists\n    containing just numbers.  Obviously, interesting programs also\n    need to be able to manipulate lists with elements from other\n    types -- lists of booleans, lists of lists, etc.  We _could_ just\n    define a new inductive datatype for each of these, for\n    example... *)\n\nInductive boollist : Type :=\n  | bool_nil\n  | bool_cons (b : bool) (l : boollist).\n\n(** ... but this would quickly become tedious, partly because we\n    have to make up different constructor names for each datatype, but\n    mostly because we would also need to define new versions of all\n    our list manipulating functions ([length], [rev], etc.) and all\n    their properties ([rev_length], [app_assoc], etc.) for each\n    new datatype definition. *)\n\n(** To avoid all this repetition, Coq supports _polymorphic_\n    inductive type definitions.  For example, here is a _polymorphic\n    list_ datatype. *)\n\nInductive list (X :Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\n(** This is exactly like the definition of [natlist] from the\n    previous chapter, except that the [nat] argument to the [cons]\n    constructor has been replaced by an arbitrary type [X], a binding\n    for [X] has been added to the function header on the first line,\n    and the occurrences of [natlist] in the types of the constructors\n    have been replaced by [list X].\n\n    What sort of thing is [list] itself?  A good way to think about it\n    is that the definition of [list] is a _function_ from [Type]s to\n    [Inductive] definitions; or, to put it more concisely, [list] is a\n    function from [Type]s to [Type]s.  For any particular type [X],\n    the type [list X] is the [Inductive]ly defined set of lists whose\n    elements are of type [X]. *)\n\nCheck list : Type -> Type.\n\n(** The [X] in the definition of [list] automatically becomes a\n    parameter to the constructors [nil] and [cons] -- that is, [nil]\n    and [cons] are now polymorphic constructors; when we use them, we\n    must now provide a first argument that is the type of the list\n    they are building. For example, [nil nat] constructs the empty\n    list of type [nat]. *)\n\nCheck (nil nat) : list nat.\n\n(** Similarly, [cons nat] adds an element of type [nat] to a list of\n    type [list nat]. Here is an example of forming a list containing\n    just the natural number 3. *)\n\nCheck (cons nat 3 (nil nat)) : list nat.\n\n(** What might the type of [nil] be? We can read off the type\n    [list X] from the definition, but this omits the binding for [X]\n    which is the parameter to [list]. [Type -> list X] does not\n    explain the meaning of [X]. [(X : Type) -> list X] comes\n    closer. Coq's notation for this situation is [forall X : Type,\n    list X]. *)\n\nCheck nil : forall X : Type, list X.\n\n(** Similarly, the type of [cons] from the definition looks like\n    [X -> list X -> list X], but using this convention to explain the\n    meaning of [X] results in the type [forall X, X -> list X -> list\n    X]. *)\n\nCheck cons : forall X : Type, X -> list X -> list X.\n\n(** (A side note on notations: In .v files, the \"forall\"\n    quantifier is spelled out in letters.  In the corresponding HTML\n    files (and in the way some IDEs show .v files, depending on the\n    settings of their display controls), [forall] is usually typeset\n    as the standard mathematical \"upside down A,\" though you'll still\n    see the spelled-out \"forall\" in a few places.  This is just a\n    quirk of typesetting -- there is no difference in meaning.) *)\n\n(** Having to supply a type argument for every single use of a\n    list constructor would be rather burdensome; we will soon see ways\n    of reducing this annotation burden. *)\n\nCheck (cons nat 2 (cons nat 1 (nil nat)))\n      : list nat.\n\n(** We can now go back and make polymorphic versions of all the\n    list-processing functions that we wrote before.  Here is [repeat],\n    for example: *)\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\n(** As with [nil] and [cons], we can use [repeat] by applying it\n    first to a type and then to an element of this type (and a number): *)\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity. Qed.\n\n(** To use [repeat] to build other kinds of lists, we simply\n    instantiate it with an appropriate type parameter: *)\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, standard, optional (mumble_grumble)\n\n    Consider the following two inductively defined types. *)\n\nModule MumbleGrumble.\n\nInductive mumble : Type :=\n  | a\n  | b (x : mumble) (y : nat)\n  | c.\n\nInductive grumble (X:Type) : Type :=\n  | d (m : mumble)\n  | e (x : X).\n\n(** Which of the following are well-typed elements of [grumble X] for\n    some type [X]?  (Add YES or NO to each line.)\n      - [d (b a 5)] \n      - [d mumble (b a 5)] \n      - [d bool (b a 5)]\n      - [e bool true]\n      - [e mumble (b c 0)]\n      - [e bool (b c 0)]\n      - [c]  *)\n(* FILL IN HERE *)\nEnd MumbleGrumble.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Annotation Inference *)\n\n(** Let's write the definition of [repeat] again, but this time we\n    won't specify the types of any of the arguments.  Will Coq still\n    accept it? *)\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0        => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\n(** Indeed it will.  Let's see what type Coq has assigned to [repeat']... *)\n\nCheck repeat'\n  : forall X : Type, X -> nat -> list X.\nCheck repeat\n  : forall X : Type, X -> nat -> list X.\n\n(** It has exactly the same type as [repeat].  Coq was able to\n    use _type inference_ to deduce what the types of [X], [x], and\n    [count] must be, based on how they are used.  For example, since\n    [X] is used as an argument to [cons], it must be a [Type], since\n    [cons] expects a [Type] as its first argument; matching [count]\n    with [0] and [S] means it must be a [nat]; and so on.\n\n    This powerful facility means we don't always have to write\n    explicit type annotations everywhere, although explicit type\n    annotations can still be quite useful as documentation and sanity\n    checks, so we will continue to use them much of the time. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Argument Synthesis *)\n\n(** To use a polymorphic function, we need to pass it one or\n    more types in addition to its other arguments.  For example, the\n    recursive call in the body of the [repeat] function above must\n    pass along the type [X].  But since the second argument to\n    [repeat] is an element of [X], it seems entirely obvious that the\n    first argument can only be [X] -- why should we have to write it\n    explicitly?\n\n    Fortunately, Coq permits us to avoid this kind of redundancy.  In\n    place of any type argument we can write a \"hole\" [_], which can be\n    read as \"Please try to figure out for yourself what belongs here.\"\n    More precisely, when Coq encounters a [_], it will attempt to\n    _unify_ all locally available information -- the type of the\n    function being applied, the types of the other arguments, and the\n    type expected by the context in which the application appears --\n    to determine what concrete type should replace the [_].\n\n    This may sound similar to type annotation inference -- and, indeed,\n    the two procedures rely on the same underlying mechanisms.  Instead\n    of simply omitting the types of some arguments to a function, like\n\n      repeat' X x count : list X :=\n\n    we can also replace the types with holes\n\n      repeat' (X : _) (x : _) (count : _) : list X :=\n\n    to tell Coq to attempt to infer the missing information.\n\n    Using holes, the [repeat] function can be written like this: *)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n(** In this instance, we don't save much by writing [_] instead of\n    [X].  But in many cases the difference in both keystrokes and\n    readability is nontrivial.  For example, suppose we want to write\n    down a list containing the numbers [1], [2], and [3].  Instead of\n    this... *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...we can use holes to write this: *)\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ----------------------------------------------------------------- *)\n(** *** Implicit Arguments *)\n\n(** In fact, we can go further and even avoid writing [_]'s in most\n    cases by telling Coq _always_ to infer the type argument(s) of a\n    given function.\n\n    The [Arguments] directive specifies the name of the function (or\n    constructor) and then lists the (leading) argument names to be\n    treated as implicit, each surrounded by curly braces. *)\n\nArguments nil {X}.\nArguments cons {X}.\nArguments repeat {X}.\n\n(** Now we don't have to supply any type arguments at all in the example: *)\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\n(** Alternatively, we can declare an argument to be implicit\n    when defining the function itself, by surrounding it in curly\n    braces instead of parens.  For example: *)\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0        => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n(** (Note that we didn't even have to provide a type argument to the\n    recursive call to [repeat'''].  Indeed, it would be invalid to\n    provide one, because Coq is not expecting it.)\n\n    We will use the latter style whenever possible, but we will\n    continue to use explicit [Argument] declarations for [Inductive]\n    constructors.  The reason for this is that marking the parameter\n    of an inductive type as implicit causes it to become implicit for\n    the type itself, not just for its constructors.  For instance,\n    consider the following alternative definition of the [list]\n    type: *)\n\nInductive list' {X:Type} : Type :=\n  | nil'\n  | cons' (x : X) (l : list').\n\n(** Because [X] is declared as implicit for the _entire_ inductive\n    definition including [list'] itself, we now have to write just\n    [list'] whether we are talking about lists of numbers or booleans\n    or anything else, rather than [list' nat] or [list' bool] or\n    whatever; this is a step too far. *)\n\n(** Let's finish by re-implementing a few other standard list\n    functions on our new polymorphic lists... *)\n\nFixpoint app {X : Type} (l1 l2 : list X) : list X :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity. Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Supplying Type Arguments Explicitly *)\n\n(** One small problem with declaring arguments [Implicit] is\n    that, once in a while, Coq does not have enough local information\n    to determine a type argument; in such cases, we need to tell Coq\n    that we want to give the argument explicitly just this time.  For\n    example, suppose we write this: *)\n\nFail Definition mynil := nil.\n\n(** (The [Fail] qualifier that appears before [Definition] can be\n    used with _any_ command, and is used to ensure that that command\n    indeed fails when executed. If the command does fail, Coq prints\n    the corresponding error message, but continues processing the rest\n    of the file.)\n\n    Here, Coq gives us an error because it doesn't know what type\n    argument to supply to [nil].  We can help it by providing an\n    explicit type declaration (so that Coq has more information\n    available when it gets to the \"application\" of [nil]): *)\n\nDefinition mynil : list nat := nil.\n\n(** Alternatively, we can force the implicit arguments to be explicit by\n    prefixing the function name with [@]. *)\n\nCheck @nil : forall X : Type, list X.\n\nDefinition mynil' := @nil nat.\n\n(** Using argument synthesis and implicit arguments, we can\n    define convenient notation for lists, as before.  Since we have\n    made the constructor type arguments implicit, Coq will know to\n    automatically infer these when we use the notations. *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** Now lists can be written just the way we'd hope: *)\n\nDefinition list123''' := [1; 2; 3].\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, standard (poly_exercises)\n\n    Here are a few simple exercises, just like ones in the [Lists]\n    chapter, for practice with polymorphism.  Complete the proofs\n    below. *)\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - simpl. rewrite IHl. reflexivity. Qed.\n\nTheorem app_assoc : forall (X:Type) (l m n:list X),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite IHl. reflexivity. Qed. \n\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros.\n  induction l1.\n  - reflexivity.\n  - simpl. rewrite IHl1. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (more_poly_exercises)\n\n    Here are some slightly more interesting ones... *)\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros.\n  induction l1.\n  - simpl. rewrite app_nil_r. reflexivity.\n  - simpl. rewrite IHl1. rewrite app_assoc. reflexivity. Qed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - simpl. rewrite rev_app_distr. rewrite IHl. reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Pairs *)\n\n(** Following the same pattern, the definition for pairs of\n    numbers that we gave in the last chapter can be generalized to\n    _polymorphic pairs_, often called _products_: *)\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\n\nArguments pair {X} {Y}.\n\n(** As with lists, we make the type arguments implicit and define the\n    familiar concrete notation. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** We can also use the [Notation] mechanism to define the standard\n    notation for _product types_ (i.e., the types of pairs): *)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** (The annotation [: type_scope] tells Coq that this abbreviation\n    should only be used when parsing types, not when parsing\n    expressions.  This avoids a clash with the multiplication\n    symbol.) *)\n\n(** It is easy at first to get [(x,y)] and [X*Y] confused.\n    Remember that [(x,y)] is a _value_ built from two other values,\n    while [X*Y] is a _type_ built from two other types.  If [x] has\n    type [X] and [y] has type [Y], then [(x,y)] has type [X*Y]. *)\n\n(** The first and second projection functions now look pretty\n    much as they would in any functional programming language. *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\n(** The following function takes two lists and combines them\n    into a list of pairs.  In other functional languages, it is often\n    called [zip]; we call it [combine] for consistency with Coq's\n    standard library. *)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\n(** **** Exercise: 1 star, standard, optional (combine_checks)\n\n    Try answering the following questions on paper and\n    checking your answers in Coq:\n    - What is the type of [combine] (i.e., what does [Check\n      @combine] print?)\n    - What does\n\n        Compute (combine [1;2] [false;false;true;true]).\n\n      print?\n\n    [] *)\n\n(** **** Exercise: 2 stars, standard (split)\n\n    The function [split] is the right inverse of [combine]: it takes a\n    list of pairs and returns a pair of lists.  In many functional\n    languages, it is called [unzip].\n\n    Fill in the definition of [split] below.  Make sure it passes the\n    given unit test. *)\n\nFixpoint split {X Y : Type} (l : list (X*Y)) : (list X) * (list Y)\n  := match l with\n  | nil => (nil, nil)\n  | z :: t => ((fst z :: fst (split t)), (snd z :: snd (split t)))\n  end.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof.\n  reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Options *)\n\n(** Our last polymorphic type for now is _polymorphic options_,\n    which generalize [natoption] from the previous chapter.  (We put\n    the definition inside a module because the standard library\n    already defines [option] and it's this one that we want to use\n    below.) *)\n\nModule OptionPlayground.\n\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\n\nArguments Some {X}.\nArguments None {X}.\n\nEnd OptionPlayground.\n\n(** We can now rewrite the [nth_error] function so that it works\n    with any type of lists. *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | nil => None\n  | a :: l' => match n with\n               | O => Some a\n               | S n' => nth_error l' n'\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, standard, optional (hd_error_poly)\n\n    Complete the definition of a polymorphic version of the\n    [hd_error] function from the last chapter. Be sure that it\n    passes the unit tests below. *)\n\nDefinition hd_error {X : Type} (l : list X) : option X\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\n(** Once again, to force the implicit arguments to be explicit,\n    we can use [@] before the name of the function. *)\n\nCheck @hd_error : forall X : Type, list X -> option X.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\n (* FILL IN HERE *) Admitted.\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Functions as Data *)\n\n(** Like most modern programming languages -- especially other\n    \"functional\" languages, including OCaml, Haskell, Racket, Scala,\n    Clojure, etc. -- Coq treats functions as first-class citizens,\n    allowing them to be passed as arguments to other functions,\n    returned as results, stored in data structures, etc. *)\n\n(* ================================================================= *)\n(** ** Higher-Order Functions *)\n\n(** Functions that manipulate other functions are often called\n    _higher-order_ functions.  Here's a simple one: *)\n\nDefinition doit3times {X : Type} (f : X->X) (n : X) : X :=\n  f (f (f n)).\n\n(** The argument [f] here is itself a function (from [X] to\n    [X]); the body of [doit3times] applies [f] three times to some\n    value [n]. *)\n\nCheck @doit3times : forall X : Type, (X -> X) -> X -> X.\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity. Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\n\n(* ================================================================= *)\n(** ** Filter *)\n\n(** Here is a more useful higher-order function, taking a list\n    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])\n    and \"filtering\" the list, returning a new list containing just\n    those elements for which the predicate returns [true]. *)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X) : 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\n(** For example, if we apply [filter] to the predicate [even]\n    and a list of numbers [l], it returns a list containing just the\n    even members of [l]. *)\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  (length l) =? 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\n(** We can use [filter] to give a concise version of the\n    [countoddmembers] function from the [Lists] chapter. *)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter odd l).\n\nExample test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity. Qed.\n\n(* ================================================================= *)\n(** ** Anonymous Functions *)\n\n(** It is arguably a little sad, in the example just above, to\n    be forced to define the function [length_is_1] and give it a name\n    just to be able to pass it as an argument to [filter], since we\n    will probably never use it again.  Moreover, this is not an\n    isolated example: when using higher-order functions, we often want\n    to pass as arguments \"one-off\" functions that we will never use\n    again; having to give each of these functions a name would be\n    tedious.\n\n    Fortunately, there is a better way.  We can construct a function\n    \"on the fly\" without declaring it at the top level or giving it a\n    name. *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity. Qed.\n\n(** The expression [(fun n => n * n)] can be read as \"the function\n    that, given a number [n], yields [n * n].\" *)\n\n(** Here is the [filter] example, rewritten to use an anonymous\n    function. *)\n\nExample test_filter2':\n    filter (fun l => (length l) =? 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, standard (filter_even_gt7)\n\n    Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat\n  := filter even (filter (fun n => eqb 0 (minus 8 n)) l) .\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\n  reflexivity. Qed.\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\n  reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (partition)\n\n    Use [filter] to write a Coq function [partition]:\n\n      partition : forall X : Type,\n                  (X -> bool) -> list X -> list X * list X\n\n   Given a set [X], a predicate of type [X -> bool] and a [list X],\n   [partition] should return a pair of lists.  The first member of the\n   pair is the sublist of the original list containing the elements\n   that satisfy the test, and the second is the sublist containing\n   those that fail the test.  The order of elements in the two\n   sublists should be the same as their order in the original list. *)\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X\n   := (filter test l, filter (fun x => match (test x) with \n                  | false => true \n                  | true => false \n                  end) l).\n\nExample test_partition1: partition odd [1;2;3;4;5] = ([1;3;5], [2;4]).\nreflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nreflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Map *)\n\n(** Another handy higher-order function is called [map]. *)\n\nFixpoint map {X Y : Type} (f : X->Y) (l : list X) : list Y :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]\n    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has\n    been applied to each element of [l] in turn.  For example: *)\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\n(** The element types of the input and output lists need not be\n    the same, since [map] takes _two_ type arguments, [X] and [Y]; it\n    can thus be applied to a list of numbers and a function from\n    numbers to booleans to yield a list of booleans: *)\n\nExample test_map2:\n  map odd [2;1;2;5] = [false;true;false;true].\nProof. reflexivity. Qed.\n\n(** It can even be applied to a list of numbers and\n    a function from numbers to _lists_ of booleans to\n    yield a _list of lists_ of booleans: *)\n\nExample test_map3:\n    map (fun n => [even n;odd n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 3 stars, standard (map_rev)\n\n    Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\nLemma map_dist : forall (X Y : Type) (f : X -> Y) (l k : list X),\n  map f (l ++ k) = map f l ++ map f k.\nProof.\n  intros.\n  induction l.\n  - 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.\n  induction l.\n  - reflexivity.\n  - simpl. rewrite map_dist. simpl. rewrite IHl. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (flat_map)\n\n    The function [map] maps a [list X] to a [list Y] using a function\n    of type [X -> Y].  We can define a similar function, [flat_map],\n    which maps a [list X] to a [list Y] using a function [f] of type\n    [X -> list Y].  Your definition should work by 'flattening' the\n    results of [f], like so:\n\n        flat_map (fun n => [n;n+1;n+2]) [1;5;10]\n      = [1; 2; 3; 5; 6; 7; 10; 11; 12].\n*)\n\nFixpoint flat_map {X Y: Type} (f: X -> list Y) (l: list X)\n                   : list Y\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Lists are not the only inductive type for which [map] makes sense.\n    Here is a [map] for the [option] type: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n  | None => None\n  | Some x => Some (f x)\n  end.\n\n(** **** Exercise: 2 stars, standard, optional (implicit_args)\n\n    The definitions and uses of [filter] and [map] use implicit\n    arguments in many places.  Replace the curly braces around the\n    implicit arguments with parentheses, and then fill in explicit\n    type parameters where necessary and use Coq to check that you've\n    done so correctly.  (This exercise is not to be turned in; it is\n    probably easiest to do it on a _copy_ of this file that you can\n    throw away afterwards.)\n*)\n(** [] *)\n\n(* ================================================================= *)\n(** ** Fold *)\n\n(** An even more powerful higher-order function is called\n    [fold].  This function is the inspiration for the \"[reduce]\"\n    operation that lies at the heart of Google's map/reduce\n    distributed programming framework. *)\n\nFixpoint fold {X Y: Type} (f : X->Y->Y) (l : list X) (b : Y) : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(** Intuitively, the behavior of the [fold] operation is to\n    insert a given binary operator [f] between every pair of elements\n    in a given list.  For example, [ fold plus [1;2;3;4] ] intuitively\n    means [1+2+3+4].  To make this precise, we also need a \"starting\n    element\" that serves as the initial second input to [f].  So, for\n    example,\n\n       fold plus [1;2;3;4] 0\n\n    yields\n\n       1 + (2 + (3 + (4 + 0))).\n\n    Some more examples: *)\n\nCheck (fold andb) : list bool -> bool -> bool.\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, standard, optional (fold_types_different)\n\n    Observe that the type of [fold] is parameterized by _two_ type\n    variables, [X] and [Y], and the parameter [f] is a binary operator\n    that takes an [X] and a [Y] and returns a [Y].  Can you think of a\n    situation where it would be useful for [X] and [Y] to be\n    different? *)\n\n(* FILL IN HERE\n\n    [] *)\n\n(* ================================================================= *)\n(** ** Functions That Construct Functions *)\n\n(** Most of the higher-order functions we have talked about so\n    far take functions as arguments.  Let's look at some examples that\n    involve _returning_ functions as the results of other functions.\n    To begin, here is a function that takes a value [x] (drawn from\n    some type [X]) and returns a function from [nat] to [X] that\n    yields [x] whenever it is called, ignoring its [nat] argument. *)\n\nDefinition constfun {X: Type} (x: X) : nat -> X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** In fact, the multiple-argument functions we have already\n    seen are also examples of passing functions as data.  To see why,\n    recall the type of [plus]. *)\n\nCheck plus : nat -> nat -> nat.\n\n(** Each [->] in this expression is actually a _binary_ operator\n    on types.  This operator is _right-associative_, so the type of\n    [plus] is really a shorthand for [nat -> (nat -> nat)] -- i.e., it\n    can be read as saying that \"[plus] is a one-argument function that\n    takes a [nat] and returns a one-argument function that takes\n    another [nat] and returns a [nat].\"  In the examples above, we\n    have always applied [plus] to both of its arguments at once, but\n    if we like we can supply just the first.  This is called _partial\n    application_. *)\n\nDefinition plus3 := plus 3.\nCheck plus3 : nat -> nat.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity. Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity. Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity. Qed.\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\nModule Exercises.\n\n(** **** Exercise: 2 stars, standard (fold_length)\n\n    Many common functions on lists can be implemented in terms of\n    [fold].  For example, here is an alternative definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length].  (Hint: It may help to\n    know that [reflexivity] simplifies expressions a bit more\n    aggressively than [simpl] does -- i.e., you may find yourself in a\n    situation where [simpl] does nothing but [reflexivity] solves the\n    goal.) *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - simpl. rewrite <- IHl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (fold_map)\n\n    We can also define [map] in terms of [fold].  Finish [fold_map]\n    below. *)\n\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y\n  := fold (fun z => cons (f z) ) l nil.\n\n(** Write down a theorem [fold_map_correct] in Coq stating that\n    [fold_map] is correct, and prove it.  (Hint: again, remember that\n    [reflexivity] simplifies expressions a bit more aggressively than\n    [simpl].) *)\n\nTheorem fold_map_correct : forall (X Y : Type )(f : X -> Y) (l : list X),\n  fold_map f l = map f l.\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - simpl. rewrite <- IHl. reflexivity. Qed. \n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_map : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (currying)\n\n    In Coq, a function [f : A -> B -> C] really has the type [A\n    -> (B -> C)].  That is, if you give [f] a value of type [A], it\n    will give you function [f' : B -> C].  If you then give [f'] a\n    value of type [B], it will return a value of type [C].  This\n    allows for partial application, as in [plus3].  Processing a list\n    of arguments with functions that return functions is called\n    _currying_, in honor of the logician Haskell Curry.\n\n    Conversely, we can reinterpret the type [A -> B -> C] as [(A *\n    B) -> C].  This is called _uncurrying_.  With an uncurried binary\n    function, both arguments must be given at once as a pair; there is\n    no partial application. *)\n\n(** We can define currying as follows: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** As an exercise, define its inverse, [prod_uncurry].  Then prove\n    the theorems below to show that the two are inverses. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\n(** As a (trivial) example of the usefulness of currying, we can use it\n    to shorten one of the examples that we saw above: *)\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\n(** Thought exercise: before running the following commands, can you\n    calculate the types of [prod_curry] and [prod_uncurry]? *)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (nth_error_informal)\n\n    Recall the definition of the [nth_error] function:\n\n   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n     match l with\n     | [] => None\n     | a :: l' => if n =? O then Some a else nth_error l' (pred n)\n     end.\n\n   Write a careful informal proof of the following theorem:\n\n   forall X l n, length l = n -> @nth_error X l n = None\n\n   Make sure to state the induction hypothesis _explicitly_.\n*)\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_proof : option (nat*string) := None.\n(** [] *)\n\n(** The following exercises explore an alternative way of defining\n    natural numbers, using the so-called _Church numerals_, named\n    after mathematician Alonzo Church.  We can represent a natural\n    number [n] as a function that takes a function [f] as a parameter\n    and returns [f] iterated [n] times. *)\n\nModule Church.\nDefinition cnat := forall X : Type, (X -> X) -> X -> X.\n\n(** Let's see how to write some numbers with this notation. Iterating\n    a function once should be the same as just applying it.  Thus: *)\n\nDefinition one : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** Similarly, [two] should apply [f] twice to its argument: *)\n\nDefinition two : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** Defining [zero] is somewhat trickier: how can we \"apply a function\n    zero times\"?  The answer is actually simple: just return the\n    argument untouched. *)\n\nDefinition zero : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(** More generally, a number [n] can be written as [fun X f x => f (f\n    ... (f x) ...)], with [n] occurrences of [f].  Notice in\n    particular how the [doit3times] function we've defined previously\n    is actually just the Church representation of [3]. *)\n\nDefinition three : cnat := @doit3times.\n\n(** Complete the definitions of the following functions. Make sure\n    that the corresponding unit tests pass by proving them with\n    [reflexivity]. *)\n\n(** **** Exercise: 1 star, advanced (church_succ) *)\n\n(** Successor of a natural number: given a Church numeral [n],\n    the successor [succ n] is a function that iterates its\n    argument once more than [n]. *)\nDefinition succ (n : cnat) : cnat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample succ_1 : succ zero = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample succ_2 : succ one = two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample succ_3 : succ two = three.\nProof. (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (church_plus) *)\n\n(** Addition of two natural numbers: *)\nDefinition plus (n m : cnat) : cnat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample plus_1 : plus zero one = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample plus_2 : plus two three = plus three two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (church_mult) *)\n\n(** Multiplication: *)\nDefinition mult (n m : cnat) : cnat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample mult_1 : mult one one = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample mult_2 : mult zero (plus three three) = zero.\nProof. (* FILL IN HERE *) Admitted.\n\nExample mult_3 : mult two three = plus three three.\nProof. (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (church_exp) *)\n\n(** Exponentiation: *)\n\n(** (_Hint_: Polymorphism plays a crucial role here.  However,\n    choosing the right type to iterate over can be tricky.  If you hit\n    a \"Universe inconsistency\" error, try iterating over a different\n    type.  Iterating over [cnat] itself is usually problematic.) *)\n\nDefinition exp (n m : cnat) : cnat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample exp_1 : exp two two = plus two two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample exp_2 : exp three zero = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample exp_3 : exp three two = plus (mult two (mult two two)) one.\nProof. (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\nEnd Church.\nEnd Exercises.\n\n(* 2022-01-20 13:18 *)\n", "meta": {"author": "ncantor01", "repo": "programming-proofs", "sha": "18218f076b21e9edaa27e6f33a0add9e42aa73d8", "save_path": "github-repos/coq/ncantor01-programming-proofs", "path": "github-repos/coq/ncantor01-programming-proofs/programming-proofs-18218f076b21e9edaa27e6f33a0add9e42aa73d8/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.6671246643462204}}
{"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(** * matrix_ext: additional properties of matrices *)\n\nRequire Import kleene normalisation ordinal sups.\nRequire Export matrix.\nSet Implicit Arguments.\n\n\n(** * [mx_scal] is an homomorphism  *)\n\nInstance mx_scal_leq `{lattice.laws}: Proper (leq ==> leq) (@mx_scal X).\nProof. intros ? ? H'. apply H'. Qed.\nInstance mx_scal_weq `{lattice.laws}: Proper (weq ==> weq) (@mx_scal X) := op_leq_weq_1.\n\nLemma mx_scal_zer `{lattice.laws}: mx_scal bot == bot.\nProof. reflexivity.  Qed.\n\nLemma mx_scal_one `{laws} n: mx_scal 1 == one n.\nProof. reflexivity.  Qed.\n\nLemma mx_scal_pls `{lattice.laws} (M N: mx X 1 1): \n  mx_scal (M \\cup N) == mx_scal M \\cup mx_scal N.\nProof. reflexivity.  Qed.\n\nLemma mx_scal_dot `{laws} `{BOT+CUP<<l} u (M N: mx (X u u) 1 1): \n  mx_scal (M * N) == mx_scal M * mx_scal N.\nProof. apply cupxb. Qed.\n\nLemma mx_scal_str `{laws} `{BKA<<l} u (M: mx (X u u) 1 1): \n  mx_scal (M^*) == mx_scal M ^*.\nProof. \n  apply str_weq. unfold mx_scal, sub00_mx, tsub_mx, lsub_mx. simpl. \n  setoid_rewrite ord0_unique. apply cupxb. \nQed.\n\n(** * [scal_mx] preserves inclusions/equalities  *)\n\nInstance scal_mx_leq `{lattice.laws}: Proper (leq ==> leq) (@scal_mx X).\nProof. now repeat intro. Qed.\nInstance scal_mx_weq `{lattice.laws}: Proper (weq ==> weq) (@scal_mx X) := op_leq_weq_1.\n\n(** * extracting components of block matrices *)\n\nLemma mx_tsub_col `{lattice.laws} n1 n2 m M1 M2:\n  tsub_mx (@col_mx X n1 n2 m M1 M2) == M1.\nProof. intros i j. unfold tsub_mx, col_mx. now rewrite split_lshift. Qed.\nLemma mx_bsub_col `{lattice.laws} n1 n2 m M1 M2:\n  bsub_mx (@col_mx X n1 n2 m M1 M2) == M2.\nProof. intros i j. unfold bsub_mx, col_mx. now rewrite split_rshift. Qed.\nLemma mx_lsub_row `{lattice.laws} n m1 m2 M1 M2:\n  lsub_mx (@row_mx X n m1 m2 M1 M2) == M1.\nProof. intros i j. unfold lsub_mx, row_mx. now rewrite split_lshift. Qed.\nLemma mx_rsub_row `{lattice.laws} n m1 m2 M1 M2:\n  rsub_mx (@row_mx X n m1 m2 M1 M2) == M2.\nProof. intros i j. unfold rsub_mx, row_mx. now rewrite split_rshift. Qed.\n\nLemma mx_sub00_blk `{lattice.laws} n1 n2 m1 m2 a b c d:\n  sub00_mx (@blk_mx X n1 n2 m1 m2 a b c d) == a.\nProof. setoid_rewrite mx_tsub_col. apply mx_lsub_row. Qed. \nLemma mx_sub01_blk `{lattice.laws} n1 n2 m1 m2 a b c d:\n  sub01_mx (@blk_mx X n1 n2 m1 m2 a b c d) == b.\nProof. setoid_rewrite mx_tsub_col. apply mx_rsub_row. Qed. \nLemma mx_sub10_blk `{lattice.laws} n1 n2 m1 m2 a b c d:\n  sub10_mx (@blk_mx X n1 n2 m1 m2 a b c d) == c.\nProof. setoid_rewrite mx_bsub_col. apply mx_lsub_row. Qed. \nLemma mx_sub11_blk `{lattice.laws} n1 n2 m1 m2 a b c d:\n  sub11_mx (@blk_mx X n1 n2 m1 m2 a b c d) == d.\nProof. setoid_rewrite mx_bsub_col. apply mx_rsub_row. Qed. \n\n\n(** sub-matrices of the empty matrix are empty *)\nLemma blk_mx_0 `{laws} u n1 n2 m1 m2 a b c d: @blk_mx (X u u) n1 n2 m1 m2 a b c d == 0 -> \n  a==0 /\\ b==0 /\\ c==0 /\\ d==0.\nProof. \n  intro Z. split; [|split; [|split]]. \n  rewrite <-(mx_sub00_blk a b c d). intros ? ?. apply Z.\n  rewrite <-(mx_sub01_blk a b c d). intros ? ?. apply Z.\n  rewrite <-(mx_sub10_blk a b c d). intros ? ?. apply Z.\n  rewrite <-(mx_sub11_blk a b c d). intros ? ?. apply Z.\nQed.\n\n\n(** * Kleene star of a block matrix *)\nSection h.\nContext `{L:laws} `{Hl:BKA<<l} (u: ob X).\n\nLocal Instance mx_bka_laws: laws BKA (mx_ops X u) := mx_laws (L:=lower_laws) _.\n\nLemma mx_str_blk' n m (M: mx (X u u) (n+m) (n+m)): \n  M^* == mx_str_build X u n m (mx_str _ _ _) (mx_str _ _ _) M.\nProof. \n  apply str_unique'. \n   apply mx_str_build_unfold_l; apply mx_str_unfold_l. \n   apply mx_str_build_ind_l; intros ? ? ?; apply mx_str_ind_l. \nQed.\n\n(** general result *)\nLemma mx_str_blk n1 n2 \n  (a: mx (X u u) n1 n1) (b: mx (X u u) n1 n2) \n  (c: mx (X u u) n2 n1) (d: mx (X u u) n2 n2):\n  let e := d^* in\n  let f := (a+(b*e)*c)^* in\n  blk_mx a b c d ^* == blk_mx f (f*(b*e)) ((e*c)*f) (e+(e*c*f)*(b*e)).\nProof.\n  intros e f. rewrite mx_str_blk'. unfold mx_str_build.\n  ra_fold (mx_ops X). now rewrite mx_sub00_blk, mx_sub01_blk, mx_sub10_blk, mx_sub11_blk.\nQed.\n\n(** specialisation to trigonal block matrices *)\nLemma mx_str_trigonal n1 n2 \n  (a: mx (X u u) n1 n1) (b: mx (X u u) n1 n2) \n                        (d: mx (X u u) n2 n2):\n  blk_mx a b 0 d ^* == blk_mx (a^*) (a^**(b*d^*)) 0 (d^*).\nProof. rewrite mx_str_blk. apply blk_mx_weq; ra. Qed.\n\n(** and to diagonal block matrices *)\nLemma mx_str_diagonal n1 n2 \n  (a: mx (X u u) n1 n1) (d: mx (X u u) n2 n2):\n  blk_mx a 0 0 d ^* == blk_mx (a^*) 0 0 (d^*).\nProof. rewrite mx_str_trigonal. apply blk_mx_weq; trivial; ra. Qed.\n\n\nLemma mx_str_1 (M: mx (X u u) 1 1): M^* == scal_mx (mx_scal M ^*).\nProof.\n  intros i j. setoid_rewrite ord0_unique. simpl.  \n  unfold mx_str_build, blk_mx, col_mx, row_mx, ordinal.split; simpl. \n  unfold mx_scal, scal_mx, mx_dot, sub00_mx, tsub_mx, lsub_mx; simpl. \n  setoid_rewrite ord0_unique. ra. \nQed.\n\n(** * induction schemes for proving properties of the Kleene star of a matrix *)\n(** (used to show that epsilon and derivatives commute with matrix star in [rmx]) *)\n\nLemma mx_str_ind (P: forall n, mx (X u u) n n -> mx (X u u) n n -> Prop): \n  (forall n, Proper (weq ==> weq ==> iff) (P n)) ->\n  (forall M, P O M M) -> \n  (forall M, P _ M (scal_mx (mx_scal M ^*))) -> \n  (forall n m,\n    (forall M, P n M (M^*)) -> \n    (forall M, P m M (M^*)) -> \n     forall M, P _ M (mx_str_build _ _ n m (fun M => M^*) (fun M => M^*) M)) ->\n  forall n M, P n M (M^*). \nProof.\n  intros HP HO H1 Hplus n M. induction n as [|n IHn].  \n   apply HO.\n   change (M^*) with (mx_str _ _ _ M). unfold mx_str, mx_str_build. ra_fold (mx_ops X). \n   setoid_rewrite <-mx_str_1.\n   revert M; refine (Hplus (S O) n _ _); intro M. \n   rewrite mx_str_1. apply H1. \n   apply IHn. \nQed.\n\nLemma mx_str_ind' (P: forall n, mx (X u u) n n -> mx (X u u) n n -> Prop): \n  (forall n, Proper (weq ==> weq ==> iff) (P n)) ->\n  (forall M, P O M M) -> \n  (forall M, P _ M (scal_mx (mx_scal M ^*))) -> \n  (forall n m a b c d,\n    let e := d^* in\n    let be := b*e in\n    let ec := e*c in\n    let f := (a+be*c)^* in\n    let fbe := f*be in\n    let ecf := ec*f in\n    P m d e -> \n    P n (a+be*c) f -> \n    P _ (blk_mx a b c d) (blk_mx f fbe ecf (e+ecf*be))) ->\n  forall n M, P n M (M^*). \nProof.\n  intros HP HO H1 Hplus. apply (mx_str_ind P HP HO H1). \n  intros n m Hn Hm M. rewrite (to_blk_mx M) at 1. now apply Hplus. \nQed. \n\nEnd h.\n\n\n(** * pointwise extension of a funcion to matrices *)\n\nDefinition mx_map X Y (f: X -> Y) n m (M: mx X n m): mx Y n m := fun i j => f (M i j).\n\nInstance mx_map_leq {X Y: lattice.ops} {f: X -> Y}\n  {Hf: Proper (leq ==> leq) f} n m: Proper (leq ==> leq) (@mx_map _ _ f n m).\nProof. intros M N H i j. apply Hf, H. Qed.\n\nInstance mx_map_weq {X Y: lattice.ops} {f: X -> Y}\n  {Hf: Proper (weq ==> weq) f} n m: Proper (weq ==> weq) (@mx_map _ _ f n m).\nProof. intros M N H i j. apply Hf, H. Qed.\n\nLemma mx_map_blk {X Y l} {HY: lattice.laws l Y} (f: X -> Y) n1 n2 m1 m2 a b c d:\n  mx_map f (@blk_mx _ n1 n2 m1 m2 a b c d) == \n  blk_mx (mx_map f a) (mx_map f b) (mx_map f c) (mx_map f d).\nProof. \n  intros i j. unfold mx_map, blk_mx, col_mx, row_mx. \n  case split; case split; reflexivity. \nQed.\n\nLemma mx_map_scal {X Y} (f: X -> Y) x: mx_map f (scal_mx x) = scal_mx (f x). \nProof. reflexivity. Qed.\n\nLemma scal_mx_map {X} {Y: lattice.ops} (f: X -> Y) M: f (mx_scal M) = mx_scal (mx_map f M). \nProof. reflexivity. Qed.\n\n(** * `functional' matrices, with exactly one [z] per line, and [0] everywhere else *)\n\nDefinition mx_fun {X: lattice.ops} n m f z: mx X n m := \n  fun x y => if eqb_ord y (f x) then z else bot. \n\nLemma mx_dot_fun `{laws} `{BSL<<l} u n m f z p (M: mx (X u u) m p) i j: \n  (mx_fun (n:=n) f z * M) i j == z * M (f i) j.\nProof.\n  simpl. unfold mx_dot. apply antisym. \n  apply leq_supx. intros j' _. unfold mx_fun. case eqb_ord_spec.\n   intros ->. ra.\n   intros _. ra. \n  rewrite <- (leq_xsup _ _ (f i)). 2: apply in_seq.\n  unfold mx_fun. now rewrite eqb_refl.\nQed.\n\nLemma mx_dot_kfun1 `{laws} `{BSL<<l} u n m i p (M: mx (X u u) m p): \n  (mx_fun (n:=n) (fun _ => i) 1 * M) == fun _ j => M i j.\nProof. intros j k. rewrite mx_dot_fun. apply dot1x. Qed.\n\nLemma mx_map_fun {X Y: lattice.ops} {l} {HY: lattice.laws l Y} n m f z g: \n  g bot == bot -> mx_map g (@mx_fun X n m f z) == @mx_fun Y n m f (g z).\nProof. intros Hg i j. unfold mx_map, mx_fun. now case eqb_ord. Qed.\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/matrix_ext.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.6671246622242373}}
{"text": "(* Classical関連の切り出し *)\n\n(* 古典論理における書き換えをiffにして、rewriteで使えるようにしている *)\n\nFrom mathcomp Require Import ssreflect.\n\nRequire Export Classical_Prop.\n\nLemma not_or_and: forall P Q, ~ (P \\/ Q) <-> ~ P /\\ ~ Q.\nProof.\nmove=> P Q.\nsplit.\n- by apply not_or_and.\n- by apply and_not_or.\nQed.\n\nLemma not_and_or: forall P Q, ~ (P /\\ Q) <-> ~ P \\/ ~Q.\nProof.\nmove=> P Q.\nsplit.\n- by apply not_and_or.\n- by apply or_not_and.\nQed.\n\nLemma not_imply: forall P Q: Prop, ~ (P -> Q) <-> P /\\ ~Q.\nProof.\nmove=> P Q.\nsplit => H.\n- by apply imply_to_and.\n- inversion H => HPQ.\n  by apply /H1 /HPQ.\nQed.\n\nLemma not_iff: forall P Q, ~ (P <-> Q) <-> (~P /\\ Q) \\/ (P /\\ ~Q).\nProof.\nmove=> P Q.\nrewrite {2}/iff.\nrewrite not_and_or.\nrewrite 2!not_imply.\nby rewrite or_comm {1}and_comm.\nQed.\n\nLemma forall_iff_not_exists_not: forall {A} (F: A -> Prop),\n  (forall x: A, F x) <-> ~ (exists x: A, ~ F x).\nProof.\nmove=> A F.\nsplit.\n- move=> Hforall.\n  case => x Hnot.\n  by move: (Hforall x).\n- move=> Hexists x.\n  apply NNPP => Hnot.\n  apply Hexists.\n  by exists x.\nQed.\n\nLemma exists_iff_not_forall_not: forall {A} (F: A -> Prop),\n  (exists x: A, F x) <-> ~ (forall x: A, ~ F x).\nProof.\nmove=> A F.\nsplit.\n- move=> Hexists Hforall.\n  move: Hexists.\n  case => x HF.\n  by move: (Hforall x).\n- move=> Hforall.\n  apply NNPP => Hexists.\n  apply Hforall => x HF.\n  apply Hexists.\n  by exists x.\nQed.\n\n\n\n\n\n", "meta": {"author": "soukouki", "repo": "math", "sha": "1c53c5f7ae8235487989dd5cdf4eaee1d55c38bc", "save_path": "github-repos/coq/soukouki-math", "path": "github-repos/coq/soukouki-math/math-1c53c5f7ae8235487989dd5cdf4eaee1d55c38bc/Classical.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6671246581389074}}
{"text": "(*|\n####################################################\nSF Volume 1: Logic: How to prove ``tr_rev <-> rev``?\n####################################################\n\n:Link: https://stackoverflow.com/q/69360955\n|*)\n\n(*|\nQuestion\n********\n\nFrom Software Foundations Volume 1, chapter Logic we see a tail\nrecursive definition of list reversal. It goes like so:\n\n.. coq:: none\n|*)\n\nRequire Import Lists.List Logic.FunctionalExtensionality.\nImport ListNotations.\n\n(*||*)\n\nFixpoint rev_append {X} (l1 l2 : list X) : list X :=\n  match l1 with\n  | [] => l2\n  | x :: l1' => rev_append l1' (x :: l2)\n  end.\n\nDefinition tr_rev {X} (l : list X) : list X :=\n  rev_append l [].\n\n(*|\nWe're, then, asked to prove the equivalence of ``tr_rev`` and ``rev``\nwhich, well, is pretty obvious that they are the same. I'm having a\nhard time completing the induction, though. Would appreciate if the\ncommunity would provide any hints as to how to approach this case.\n\nHere's as far as I got:\n|*)\n\nTheorem tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n  intros X. (* Introduce the type *)\n  apply functional_extensionality. (* Apply extensionality axiom *)\n  intros l. (* Introduce the list *)\n  induction l as [| x l']. (* start induction on the list *)\n  - reflexivity. (* base case for the empty list is trivial *)\n  - (* inductive case seems simple too. We unfold the definition *)\n    unfold tr_rev. simpl. (* simplify it *)\n    unfold tr_rev in IHl'. (* unfold definition in the Hypothesis *)\n    rewrite <- IHl'. (* .unfold *) (* rewrite based on the hypothesis *)\nAbort. (* .none *)\n\n(*|\nNow, ``[] ++ [x]`` is obviously the same as ``[x]`` but ``simpl``\ncan't simplify it and I couldn't come up with a ``Lemma`` that would\nhelp me here. I *did* prove ``app_nil_l`` (i.e. ``forall (X : Type) (x\n: X) (l : list X), [] ++ [x] = [x]``) but when I try to rewrite with\n``app_nil_l`` it'll rewrite both sides of the equation.\n\nI could just define that to be an axiom, but I feel like that's\ncheating :-p\n\nThanks\n|*)\n\n(*|\nAnswer\n******\n\nProving things about definitions with accumulators has a specific\ntrick to it. The thing is, facts about ``tr_rev`` must necessarily be\nfacts about ``rev_append``, but ``rev_append`` is defined on two\nlists, while ``tr_rev`` is defined on only one. The computation of\n``rev_append`` depends on these two lists, and thus the induction\nhypothesis needs to be general enough to include both of these lists.\nHowever, if you fix the second input of ``rev_append`` to always be\nthe empty list (which you implicitly do by stating your result only\nfor ``tr_rev``), then the induction hypothesis will always be too\nweak.\n\nThe way around this is to first prove a general result for\n``rev_append`` by induction on ``l1`` (and generalizing on ``l2``),\nand then specializing this result for the case of ``tr_rev``.\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/sf-volume-1-logic-how-to-prove-tr-rev-rev.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.6671246581389074}}
{"text": "(*This file contains the proof that if we reduce a formula F to a graph G, \n**and G is colorable, then F is satisfiable under valid environments*)\nRequire Import ThreeSatReduction.  \n\n(*collect the free variables of a graph*)\nFixpoint graphFVs G :=\n  match G with\n    |emptyGraph => []\n    |newEdge u v G => u::v::graphFVs G\n    |gunion G1 G2 => graphFVs G1 ++ graphFVs G2\n  end.\n\n(*solve a goal of the form In ?x ?y*)\nLtac solveIn :=\n  match goal with\n      | |- In ?x (?a ++ ?b) => rewrite in_app_iff; \n                            solve[left; solveIn|right; solveIn]\n      | |- In ?a ?b \\/ In ?c ?d => simpl in *; solve[left; solveIn | right; solveIn]\n      | |- In ?a (?b::?c) => simpl; solve[left; auto|right; solveIn]\n      | |- _ => eauto\n  end. \n\n(*color a graph with a smaller environment if the part being removed\n**does not occur free in the graph being colored*)\nTheorem colorStrengthening : forall eta1 eta2 i c j K Gamma C eta G,\n                               setVertices Gamma C 0 eta1 eta ->\n                               setCs eta1 i K eta2 eta ->\n                               coloring (eta1++(j,c)::eta2) G C ->\n                               ~ In j (graphFVs G) ->\n                               coloring (eta1++eta2) G C.\nProof.\n  intros. remember (eta1++(j,c)::eta2). induction H1. \n  {constructor. }\n  {simpl in H2. subst. rewrite in_app_iff in H1. rewrite in_app_iff in H3. \n   inv H1; inv H3.\n   {econstructor; try solveIn; try omega. eapply IHcoloring; eauto. }\n   {econstructor; try solveIn; try omega. simpl in H1. inv H1. invertTupEq. \n    exfalso. apply H2. auto. solveIn. apply IHcoloring; auto. }\n   {simpl in H8. inv H8. invertTupEq. exfalso. apply H2. auto. \n    econstructor; try solveIn. apply IHcoloring; auto. }\n   {simpl in *. inv H8. invertTupEq. exfalso. apply H2. auto. inv H1. invertTupEq. \n    exfalso. apply H2. auto. econstructor; try solveIn. apply IHcoloring; auto. }\n  }\n  {constructor. apply IHcoloring1; auto. intros contra. apply H2. simpl. \n   solveIn. apply IHcoloring2; auto. intros contra. apply H2. simpl. solveIn. }\nQed. \n\nTheorem notInDistribute : forall (A:Type) (x:A) L1 L2, ~ In x L1 -> ~ In x L2 ->\n                                                  ~ In x (L1++L2). \nProof. intros. rewrite in_app_iff. rewrite notDistr. auto. \nQed. \n\n(*If a mapping from u_i to its vertex variables is in Gamma, then x_i is less than the length of Gamma + i*)\nTheorem inGammaLT : forall Gamma C i eta eta' u, In (u,3*u,3*u+1,3*u+2) Gamma -> setVertices Gamma C i eta' eta ->\n                                         3 * u + 2 < 3 * (length Gamma + i). \nProof.\n  intros. induction H0. \n  {inv H. \n   {invertTupEq. simpl. omega. }\n   {eapply IHsetVertices in H2. simpl. omega. }\n  }\n  {inv H. \n   {invertTupEq. simpl. omega. }\n   {eapply IHsetVertices in H2. simpl. omega. }\n  }\n  {inv H. }\nQed. \n\n(*if j is less than the convert_base index, then j is not in the free variables of G*)\nTheorem notInConvertBase : forall Gamma Delta i G j eta C eta',\n                             setVertices Gamma C 0 eta' eta -> j < i -> j >= 3 * length Gamma ->\n                             convert_base Gamma Delta i G ->\n                             ~ In j (graphFVs G). \nProof.\n  intros. induction H2. \n  {intros c. inv c. } \n  {simpl. repeat rewrite notDistr; repeat split; try omega. \n   eapply inGammaLT in H2; eauto; simpl in *. repeat rewrite plus_0_r in *. \n   apply lt_le_trans with(p:=j) in H2; auto. omega. \n   eapply inGammaLT in H2; eauto. simpl in *. repeat rewrite plus_0_r in *. \n   apply lt_le_trans with(p:=j) in H2; auto. omega. auto. }\nQed. \n\n(*if j is less than the convStack index and greater than everything in Gamma, then it\n**is not in the free variables of G*)\nTheorem notInFV : forall Gamma C eta1 eta Delta G j K i eta2, \n                    setVertices Gamma C 0 eta1 eta -> setCs eta1 i K eta2 eta ->\n                    j >= 3 * length Gamma -> j < i -> convStack i Gamma Delta K G -> ~ In j (graphFVs G). \nProof.\n  intros. genDeps {{ j; eta; eta1; eta2 }}. induction H3; intros.\n  {intros c. inv c. }\n  {simpl. apply notInDistribute. inv H1; eapply IHconvStack; eauto;\n   rewrite plus_comm; eauto. destruct F. destruct p. inv H. simpl. \n   destruct e1. destruct e2. destruct e3. simpl.\n   repeat rewrite notDistr; repeat split. inv H12; omega. eapply inGammaLT in H8; eauto. \n   inv H12. simpl in *. repeat rewrite plus_0_r in H8. rewrite plus_0_r in H2. \n   assert(3*u+2 < j). simpl. rewrite plus_0_r. eapply lt_le_trans with(p:=j) in H8. Focus 2. \n   auto. auto. omega. simpl in *. eapply lt_le_trans with (p:=j) in H8. Focus 2. \n   repeat rewrite plus_0_r in *. auto. omega. inv H18; omega. eapply inGammaLT in H9; eauto. inv H18; \n   eapply lt_le_trans with (p:=j) in H9; simpl in *; repeat rewrite plus_0_r in *; auto; \n   omega. inv H20; omega. eapply inGammaLT in H10; eauto.\n   inv H20; eapply lt_le_trans with (p:=j) in H10; simpl in *; repeat rewrite plus_0_r in *; auto; omega. \n   eapply notInConvertBase; eauto. }\nQed. \n\n(*If F reduces to G and G is colorable, then F is satisfiable*)\nTheorem colorImpliesSAT : forall Gamma C eta eta' i U eta'' Delta F G,\n                            setVertices Gamma C 0 eta' eta -> setCs eta' i F eta'' eta ->\n                            coloring (eta'++eta'') G C -> i >= 3 * length Gamma ->\n                            unique U Delta -> \n                            convStack i Gamma Delta F G -> SAT' eta F. \nProof.\n  intros. genDeps {{ U; eta; eta'; eta''; C }}. induction H4; intros. \n  {constructor. } \n  {destruct F. destruct p. inv H3. \n   {inv H13. \n    {constructor. left. constructor. auto. eapply IHconvStack. omega. Focus 3.\n     rewrite plus_comm. eauto. Focus 3. eauto. Focus 2. eauto. \n     eapply colorStrengthening; eauto. inv H1. eauto. eapply notInFV; eauto.\n     rewrite plus_comm in H4. eauto. }\n    {constructor. left. constructor. auto. eapply IHconvStack. Focus 4.\n     rewrite plus_comm. eauto. Focus 3. eauto. Focus 2. eauto. \n     eapply colorStrengthening; eauto. inv H1. eauto. eapply notInFV; eauto.\n     rewrite plus_comm in H4. eauto. omega. eauto. }\n   }\n   {inv H13. \n    {constructor. right. left. constructor. auto. eapply IHconvStack. Focus 4.\n     rewrite plus_comm. eauto. Focus 3. eauto. Focus 2. eauto.  \n     eapply colorStrengthening; eauto. inv H1. eauto. eapply notInFV; eauto.\n     rewrite plus_comm in H4. eauto. omega. eauto. }\n    {constructor. right. left. constructor. auto. eapply IHconvStack. Focus 4.\n     rewrite plus_comm. eauto. omega. Focus 3. eauto. Focus 2. eauto. \n     eapply colorStrengthening; eauto. inv H1. eauto. eapply notInFV; eauto.\n     rewrite plus_comm in H4. eauto. }\n   }\n   {inv H13. \n    {constructor. right. right. constructor. auto. eapply IHconvStack. Focus 4.\n     rewrite plus_comm. eauto. Focus 3. eauto. Focus 3. eauto. omega. \n      eapply colorStrengthening; eauto. inv H1. eauto. eapply notInFV; eauto.\n     rewrite plus_comm in H4. eauto. }\n    {constructor. right. right. constructor. auto. eapply IHconvStack. Focus 4.\n     rewrite plus_comm. eauto. Focus 4. eauto. Focus 3. eauto. omega. \n      eapply colorStrengthening; eauto. inv H1. eauto. eapply notInFV; eauto.\n     rewrite plus_comm in H4. eauto. }\n   }\n  }\nQed. \n\n\n", "meta": {"author": "lexxx320", "repo": "TheoryThinkTank", "sha": "e55c332cecaebf0c7556ca5a7ff74768254db389", "save_path": "github-repos/coq/lexxx320-TheoryThinkTank", "path": "github-repos/coq/lexxx320-TheoryThinkTank/TheoryThinkTank-e55c332cecaebf0c7556ca5a7ff74768254db389/three_sat_to_kcolor_reduction/colorImpliesSAT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503682, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6671246519315944}}
{"text": "Require Import Arith Program.Equality.\n\nInductive le' : nat -> nat -> Prop :=\n| le'_0 (n : nat) : le' 0 n\n| le'_S (n m : nat) : le' n m -> le' (S n) (S m).\n\nFixpoint le'_irrelevant (n m : nat) (p q : le' n m) : p = q.\nProof.\n  dependent destruction p; dependent destruction q.\n  - reflexivity.\n  - f_equal; apply le'_irrelevant.\nDefined.\n", "meta": {"author": "mukeshtiwari", "repo": "CoqUtility", "sha": "3a25343d0a77177adb7530a08b0c7854bb1ed02f", "save_path": "github-repos/coq/mukeshtiwari-CoqUtility", "path": "github-repos/coq/mukeshtiwari-CoqUtility/CoqUtility-3a25343d0a77177adb7530a08b0c7854bb1ed02f/depdestruct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6670341406293675}}
{"text": "Require Export ZArith_base.\nRequire Export XRdefinitions.\n\nFixpoint IPR_2 (p:positive) : R :=\n  match p with\n  | xH => R1 + R1\n  | xO p => (R1 + R1) * IPR_2 p\n  | xI p => (R1 + R1) * (R1 + IPR_2 p)\n  end.\n\nDefinition IPR (p:positive) : R :=\n  match p with\n  | xH => R1\n  | xO p => IPR_2 p\n  | xI p => R1 + IPR_2 p\n  end.\nArguments IPR p%positive : simpl never.\n\nDefinition IZR (z:Z) : R :=\n  match z with\n  | Z0 => R0\n  | Zpos n => IPR n\n  | Zneg n => - IPR n\n  end.\nArguments IZR z%Z : simpl never.", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/Reals/XRZlink.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6670341227920025}}
{"text": "Set Implicit Arguments.\nRequire Export List.\nRequire Export Ltree.\n\n\nRequire Export ZArith.\n\nOpen Scope positive_scope.\n\nCoFixpoint PosTree (p:positive) : LTree positive :=\n  LBin p (PosTree (xO p)) (PosTree (xI p)).\n\n\nEval compute in (LTree_label (PosTree 1) (d0 :: d1 :: nil)).\n\nEval compute in (LTree_label (PosTree 1) (d0 :: d1 :: d1 :: nil)).\n\nEval compute in (LTree_label (PosTree 1) \n                             (d0 :: d1 :: d1 :: d0 :: d0 ::d1 :: nil)).\n\nCoFixpoint graft (A:Set) (t t':LTree A) : LTree A :=\n  match t with\n  | LLeaf => t'\n  | LBin n t1 t2 => LBin n (graft t1 t') (graft t2 t')\n  end.\n\n\n\n\n\n\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/co-inductifs/SRC/building.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6669080350327657}}
{"text": "(* Exercise 61 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_061 : (exists x, ~ R x x) -> (exists x, exists y, ~ R x y).\nProof.\nimp_i a1.\nexi_e (exists x:D, ~R x x) a a2.\nhyp a1.\nexi_i a.\nexi_i a.\nhyp a2.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred061.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6669053113435973}}
{"text": "Set Implicit Arguments.\n\n\nRequire Import Bvector.\nRequire Import List.\nRequire Import Arith.\n\nRequire Import HMAC_functional_prog_new.\nRequire Import Integers.\nRequire Import Coqlib.\n\n(* Require Import List. Import ListNotations. *)\n\nDefinition Blist := list bool.\n\nFixpoint splitVector(A : Set)(n m : nat) : Vector.t A (n + m) -> (Vector.t A n * Vector.t A m) :=\n  match n with\n    | 0%nat => \n      fun (v : Vector.t A (O + m)) => (@Vector.nil A, v)\n    | S n' => \n      fun (v : Vector.t A (S n' + m)) => \n        let (v1, v2) := splitVector _ _ (Vector.tl v) in\n          (Vector.cons _ (Vector.hd v) _ v1, v2)\n  end.\n\nSection HMAC.\n\nSearchAbout Bvector.\nPrint Bvector.\nCheck Bvector 10.\nCheck [true]. \n\n  Variable c p : nat.\n  (* b is block size, c is digest (output) size, p is padding *)\n  Definition b := (c + p)%nat.\n  Check b.\n  \n  (* The compression function *)\n  (* hash_blocks: registers -> block -> registers *)\n  Variable h : Bvector c -> Bvector b -> Bvector c.\n  (* The initialization vector is part of the spec of the hash function. *)\n  (* TODO: is the IV standardized in the spec? does it need to have certain properties for\n   the proof? *)\n  Variable iv : Bvector c.\n  (* The iteration of the compression function gives a keyed hash function on lists of words. *)\n  Definition h_star k (m : list (Bvector b)) :=\n    fold_left h m k.\n  (* The composition of the keyed hash function with the IV gives a hash function on lists of words. *)\n  (* TODO check how this corresponds to SHA *)\n  Definition hash_words := h_star iv.\nCheck hash_words.\nCheck h_star.\n\n  Variable splitAndPad : Blist -> list (Bvector b).\n\n  (* TODO examine this hypothesis *)\n  Hypothesis splitAndPad_1_1 : \n    forall b1 b2,\n      splitAndPad b1 = splitAndPad b2 ->\n      b1 = b2.\n  \n  (* constant-length padding. *)\n  Variable fpad : Bvector p.\n\n  Definition app_fpad (x : Bvector c) : Bvector b :=\n    (Vector.append x fpad).\n  Definition h_star_pad k x :=\n    app_fpad (h_star k x).\n\n  Definition GNMAC k m :=\n    let (k_Out, k_In) := splitVector c c k in\n    h k_Out (app_fpad (h_star k_In m)).\n\n  (* The \"two-key\" version of GHMAC and HMAC. *)\n  (* Concatenate (K xor opad) and (K xor ipad) *)\n  Definition GHMAC_2K (k : Bvector (b + b)) m :=\n    let (k_Out, k_In) := splitVector b b k in (* concat earlier, then split *)\n      let h_in := (hash_words (k_In :: m)) in \n        hash_words (k_Out :: (app_fpad h_in) :: nil).\n  \n  (* b + b comes from ( *)\n  Definition HMAC_2K (k : Bvector (b + b)) (m : Blist) :=\n    GHMAC_2K k (splitAndPad m).\n\nCheck HMAC_2K.\n(* HMAC_2K\n     : Bvector (b + b) -> Blist -> Bvector c *)\nSearchAbout Bvector.\n(* Bvector (b + b) -> Blist -> BVector c *)\n\nPrint splitVector.\n\nTheorem test : forall (k : Bvector (b + b)) (m : Blist),\n  HMAC_2K k m = HMAC_2K k m.\nProof.\n  intros k m.\n  unfold HMAC_2K.               (* splitAndPad is abstract *)\n  unfold GHMAC_2K.\n  unfold hash_words.\n  unfold h_star. \n  (* unfold splitVector. *)\nAbort.\n\nPrint Bvector.                  (* Vector.t bool : nat -> Set *)\n(* Check [true]%(Bvector 1). *)\n(* Cannot compute since Variables are not instantiated  -- TODO, how to instantiate \n(e.g. with SHA256? does it have the right type? \nSHA256 : list Z -> list Z *)\n(* Eval compute in HMAC_2K [true; true] [false]. *)\n\n  (* opad and ipad are constants defined in the HMAC spec. *)\n  Variable opad ipad : Bvector b. (* c + p *)\n  Definition GHMAC (k : Bvector b) :=\n    GHMAC_2K (Vector.append (BVxor _ k opad) (BVxor _ k ipad)).\n\nPrint BVxor.\n\n  (* Doesn't seem to take into account the hash function's input block size (see mkKey in P. spec) *)\n  Definition HMAC (k : Bvector b) :=\n    HMAC_2K (Vector.append (BVxor _ k opad) (BVxor _ k ipad)).\n\nCheck HMAC.                     (*  : Bvector b -> Blist -> Bvector c *)\n\n  (* Bvector or Blist? *)\nCheck HMAC_2K.                  (* TODO confirm that this is actually the right version *)\n\nEnd HMAC.\n\n(* -------------- *)\n\nRequire Import HMAC_functional_prog_2.\n\n(* How to get the other HMAC? *)\n(* TODO: compile HMAC_functional_prog_2 *)\nCheck HMAC_FUN.HMAC.            (* list Z -> list Z -> list Z *)\n\n(* Bvector (plus c p)  *)\n\n(* relationship between a list Z (of bytes) and a Bvector of size (c + p):\ntoBvector (bytes_to_bits k) = K?\n(don't actually need the Bvector, just c + p, or its length) <-- deprecated,\nwant equality\n *)\nInductive bytes_bits_vector (c p : nat) (k : list Z) : Bvector (plus c p) -> Prop :=\n  | test_n : forall (K : Bvector (plus c p)), bytes_bits_vector c p k K (* ?? TODO *)\n.\n\n(* relating list Z to Blist\nbytes_to_bits m = length M\n\nTODO: big-endian, little-endian?\n*)\nInductive bytes_bits_lists (m : list Z) : Blist -> Prop :=\n  | test_n' : forall M : Blist, bytes_bits_lists m M\n.\n\n(* the hashes are \"the same\": list Z vs Bvector c\n\ntoBvector (bytes_to_bits h) = H\nthis is *almost* the same as bytes_bits_vector, except just c, not c + p\n *)\nInductive bytes_bits_vector' (c : nat) (h : list Z) : Bvector c -> Prop :=\n  | test_n'' : forall (H : Bvector c), bytes_bits_vector' h H\n.\n(* TODO: compare to rel1. How do dependent types and inductive props work? *)\n\n\n\n(* TODO:\nDefinition convertByteBits (b: byte) (B: Bvector 8): Prop :=\n  exists b0, ... b7 (*all of type bool*),\n   B = [b0, b1, ... b7] /\\\n   b = (asZ b0) + 2 * (asZ b1) * 4 * (asZ b2) + .. + 128 * (asZ b7).\n\nwhere Definition asZ (x:bool):Z := if x then 1 else 0.\n*)\n\nCheck bytes_bits_vector.\nCheck HMAC_FUN.HMAC.\nCheck HMAC_SHA256.HMAC.         (* ? *)\nCheck HMAC.\n(* HMAC\n     : forall c p : nat,\n       (Bvector c -> Bvector (b c p) -> Bvector c) ->   // compression function h\n       Bvector c ->                          // iv, h's initialization vector\n       (Blist -> list (Bvector (b c p))) ->  // splitAndPad (e.g. generate_and_pad)\n       Bvector p ->                          // fpad, constant-length padding\n       Bvector (b c p) ->                    // opad\n       Bvector (b c p) ->                    // ipad\n\n^ Note: this has to do with the internals of SHA256 and HMAC too\nSHA's compression function, iv, generate_and_pad (with block vectors),\nHMAC's key padding function, HMAC's opad and ipad\n\nHow to convert?\n\nBvector (b c p) -> Blist -> Bvector c        // key, message, outputted hash\nk is of length b\nb = block size\nc = output size\nc + p = output size padded to block size\n\nwhy pad the key? why not just let it be size b?\n *)\n\n(* Is this the theorem we want? Is it useful for the rest of the proofs?\nShould it be more abstract? \n\nalso, no key padding\nadd assumption that the key is padded to the right length (b)\npassword of length b\nmodify?\n*)\n\nPrint Blist.\n\n(* maybe bvector of length 8, convert to Blist later? \nTODO big-endian vs. little-endian *)\n(* Parameter byte_to_bits : Z -> Bvector 8. *)\n  (* Vector.nil bool. TODO *)\nSearchAbout Vector.t.\n\n(* Bvector is little-endian (least significant bit at head; list Z are just translated\nfrom the string (ascii -> nat -> Z); but Int are packed big-endian (with 4 Z -> 1 Int)\n\neach Z is one byte (8 bits) *\n\nbytes -> bits is ok\nbits -> bytes is not ok\n*)\n(*\nDon't have an assurance that 0 <= byte < 256 \nTODO: add isbyteZ (from SHA256.v), 0 <= i <= 256 \n\n1 2 3 4 5 6 7 8\n*)\n\nSearchAbout Z.\nEval compute in zle 5 10.\nCheck zle.\nCheck zle_true.\nSearchAbout nat.\nCheck N.\n\n(* TODO: finish this\n\nThe term \"Vector.append (iterate n' num_new) [bool_digit]\" has type\n \"Vector.t bool (n' + 1)\" while it is expected to have type \n\"Bvector (S n')\".\n\nFunction with proof of equivalence? see hash_blocks\n *)\n\n(*\nFixpoint iterate (n : nat) (byte : nat) : Bvector n :=\n  match n as x return Bvector x with\n    | O => Vector.nil bool\n    | S n' =>\n      let byte_subtract := (byte - NPeano.pow 2 (n - 1))%nat in\n      let bool_digit := leb byte_subtract 0 in\n      let num_new := if bool_digit then byte_subtract else byte in\n      Vector.append (iterate n' num_new) [bool_digit] (* could reverse instead *)\n  end.\n\n(* reverse? \n0 <= byte < 256, integer \n\n[0, 1, 2, 3, 4, 5, 6, 7] <-- bool\n*)\nFixpoint byte_to_bits (byte : Z) : Bvector 8 :=\n  let max_pow_two := 7 in\n  iterate (max_pow_two + 1) (nat_of_Z byte).    (* or iterate 8? *)\n*)\n\nParameter byte_to_bits : Z -> Bvector 8.\n\n(* Or: concatMap byte_to_bit bytes *)\nCheck Bvector.\nSearchAbout Bvector.\nPrint Vector.t.\n\n(* how to prove that it's length bytes * 8? *)\n(* list of bytes? (type) *)\nFixpoint bytes_to_bits (bytes : list Z) : Bvector (length bytes * 8) :=\n  match bytes as x return Bvector (length x * 8) with (* CPDT *)\n    | nil => Vector.nil bool\n    | x :: xs => Vector.append (byte_to_bits x) (bytes_to_bits xs)\n  end.\n\n(* -------------------------------- *)\n\nParameter sha_iv : Bvector (8 * SHA256_.DigestLength).\n\n(* Definition sha_h : list Z -> list Z := SHA256_.Hash. *)\nParameter sha_h : forall (c p : nat) (b:nat -> nat -> nat),\n                    Bvector c -> Bvector (b c p) -> Bvector c.\n(* due to implicit parameters, only requires c or p, and b *)\n\n(* corresponds to block size, b = plus *)\n\n(* TODO: email adam about fpad: it's not padding the key *)\n\n(*  \"Blist -> list (Bvector (b SHA256_.DigestLength c))\" *)\nParameter sha_splitandpad_vector :\n  forall (p : nat), Blist -> list (Bvector ((SHA256_.DigestLength * 8) + p)).\n\nParameter fpad : forall (p : nat), Bvector p.\n\n(* want Bvector b = 512 bits *)\nPrint Byte.int.\nPrint Byte.repr.\nCheck HMAC_SHA256.sixtyfour HMAC_SHA256.Opad.\nCheck Byte.unsigned.\nDefinition opad := bytes_to_bits\n                     (map Byte.unsigned (HMAC_SHA256.sixtyfour HMAC_SHA256.Opad)).\nDefinition ipad := bytes_to_bits\n                     (map Byte.unsigned (HMAC_SHA256.sixtyfour HMAC_SHA256.Ipad)).\n\nCheck HMAC.\n\n(* \nEmail Adam about fpad\nFigure out what parameters are\nFill in the relations\nByte to bits\n\nNew theorem\nParametrize C HMAC by OPAD and IPAD + they need to be different in at least one bit\n   (does adam need this?)\n\nNow, write individual functions (e.g. sha_h, which is still abstract)\nand prove them equivalent? different types....\n\nLennart: update spec, ipad and opad\nemail andrew about lennart coming to meeting + hmac refactoring\n\n *)\n\nCheck sha_h.\n\nModule Equiv.\nDefinition c := (8 * SHA256_.DigestLength)%nat.\nVariable p : nat.\nCheck HMAC (sha_h c plus). \nCheck HMAC (sha_h c plus) sha_iv.\n\n(* c needs to be not forall, should be 8 * digest length *)\nTheorem HMAC_spec_equiv : forall\n                            (c p : nat)\n                            (k m h : list Z)\n                            (K : Bvector (plus c p)) (M : Blist) (H : Bvector c),\n                            \n                            (* assuming k is already padded? *)\n  (8 * (length (HMAC_FUN.mkKey k)))%nat = (c + p)%nat ->\n  bytes_bits_vector c p k K -> bytes_bits_lists m M ->\n  HMAC (sha_h c plus) sha_iv (sha_splitandpad_vector c p) (fpad p) opad ipad K M = H ->\n  HMAC_FUN.HMAC k m = h ->\n  (* TODO fix HMAC h iv splitAndPad fpad opad ipad K M *)\n  bytes_bits_vector' h H.\nProof.\n\nAbort.\n\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/old/HMAC_spec_harvard_old.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.666871897773978}}
{"text": "Require Import Problem ZArith ZArith.Znumtheory.\n\nTheorem solution : task.\nProof.\n  unfold task.\n  intros.\n  unfold Square; unfold Square in H2.\n  remember (Z.sqrt (n * m)) as k.\n  remember (Z.gcd k m) as x.\n  remember (Z.gcd k n) as y.\n  apply (proj2 (Zgcd_1_rel_prime n m)) in H1.\n\n  assert (y * k = n * x).\n  subst x y.\n  rewrite <- Z.gcd_mul_mono_l_nonneg; [|omega].\n  rewrite <- Z.gcd_mul_mono_r_nonneg; [|subst k; apply Z.sqrt_nonneg].\n  rewrite H2.\n  rewrite Z.gcd_comm.\n  auto.\n\n  assert (Z.gcd x y = 1).\n  subst x y.\n  rewrite <- Z.gcd_assoc.\n  rewrite (Z.gcd_comm m).\n  rewrite <- Z.gcd_assoc.\n  rewrite H1.\n  repeat rewrite Z.gcd_1_r.\n  auto.\n\n  assert (n = y * Z.gcd k n).\n  rewrite <- Z.gcd_mul_mono_l_nonneg; [|subst y; apply Z.gcd_nonneg].\n  rewrite H3; clear H3.\n  rewrite Z.mul_comm.\n  rewrite Z.gcd_mul_mono_r_nonneg; [|omega].\n  rewrite H4; clear H4.\n  omega.\n\n  rewrite <- Heqy in H5.\n  replace (Z.sqrt n) with y; [auto|].\n  specialize (Z.gcd_nonneg k n); intro.\n  rewrite <- Heqy in H6.\n  rewrite <- (Z.sqrt_square y H6).\n  subst 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/036/Solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6668705352898285}}
{"text": "Require Import Arith.\nRequire Import Lia.\nRequire Export FOPL.FOPL.\nRequire Export FOPL.Deduction.\nRequire Export FOPL.SetoidL.\nRequire Export FOPL.Tactics.\n\nDefinition theory {L : Lang} (T : Th) := fun p => T ||- p.\n\nDefinition sentence_th {L : Lang} T := sfT T ≡ T.\n\nInductive Null {L : Lang} : Th :=.\nDefinition null {L : Lang} (T : Th) := forall p, ~ T p.\n\nFixpoint Fal {L : Lang} n0 p :=\n  match n0 with\n  | 0 => p\n  | S n => [fal](Fal n p)\n  end.  \n\nSection deduction_facts2.\n  Variable L : Lang.\n\n  Lemma nullNull : null Null.\n  Proof.\n    unfold null.\n    intros. intro.\n    destruct H.\n  Qed.\n\n  Lemma nullT_nullsfT : forall T, null (sfT T) <-> null T.\n  Proof.\n    unfold null.\n    intros.\n    split.\n    intros.\n    specialize(H (sf p)).\n    contradict H.\n    auto.\n    intros. intro.\n    destruct H0.\n    specialize (H p).\n    contradiction.\n  Qed.\n\n  Lemma null_sfT : forall T, null T -> T ≡ (sfT T).\n  Proof.\n    intros.\n    unfold eqvT, incT.\n    split.\n    intros.\n    specialize (H p).\n    contradiction.\n    intros.\n    rewrite <- nullT_nullsfT in H.\n    specialize(H p).\n    contradiction.\n  Qed.\n\n  Lemma fal_Fal : forall p n, [fal] Fal n p = Fal n ([fal] p).\n  Proof.\n    induction n.\n    simpl. auto.\n    simpl.\n    rewrite IHn.\n    auto.\n  Qed.\n\n  Lemma Genp_ps : forall T p s, T ||- (Fal (Ar p) p) [->] p.[s].\n  Proof.\n    assert(forall T n p s, Ar p <= n -> T ||- (Fal n p) [->] p.[s]).\n    - induction n.\n      + simpl.\n        intros.\n        rewrite <- sentence_rew.\n        auto.\n        lia.\n      + simpl.\n        intros.\n        rewrite fal_Fal.\n        ftrans (([fal]p).[fun x :nat => s (S x)]).\n        apply IHn.\n        simpl. lia.\n        simpl.\n        fintro.\n        Tpp.\n        fspecialize H0 (s 0).\n        rewrite nested_rew in H0.\n        assert(p.[ fun x => rewc (s 0; \\0) (('0; fun x0 => sfc (s (S x0))) x)] = p.[s]). {\n          apply rew_rew. unfold sfc.\n          intros. simpl.\n          destruct n0.\n          simpl. auto.\n          simpl.\n          rewrite nested_rewc.\n          simpl.\n          symmetry.\n          apply rewc_id.\n        }\n        rewrite H1 in H0.\n        auto.\n    - intros.\n      apply H.\n      lia.\n  Qed.\n\n  Lemma Null_psfp : forall T p, null T -> (T ||- p) -> (T ||- sf p).\n  Proof.\n    intros.\n    assert(forall n, T ||- Fal n p).\n    - induction n.\n      simpl. auto.\n      simpl.\n      GEN.\n      apply TInclusion with (T:=T).\n      apply null_sfT. auto.\n      auto.\n    - MP (Fal (Ar p) p). auto.\n      unfold sf.\n      apply Genp_ps.\n  Qed.\n\n  Inductive Array (f : nat -> Formula) (n0 : nat) : Th := \n  | array : forall n, n < n0 -> Array f n0 (f n).\n\n  Fixpoint Sum (f : nat -> Formula) (n0 : nat) : Th := \n    match n0 with\n    | 0 => Null\n    | S n => (Sum f n) ¦ (f n)\n    end.\n\n  Lemma Sump : forall f n p, (Sum f n p) -> exists m, m < n /\\ p = f m.\n  Proof.\n    induction n.\n    - simpl. intros.\n      destruct H.\n    - simpl.\n      intros.\n      destruct H.\n      exists n.\n      auto.\n      specialize (IHn q H).\n      destruct IHn as [n0].\n      destruct H0.\n      exists n0. auto.\n  Qed. \n\n  Lemma Sump_inv : forall f n m, m < n -> Sum f n (f m).\n  Proof.\n    induction n.\n    - simpl. intros.\n      lia.\n    - simpl.\n      intros.\n      unfold lt in H.\n      apply le_S_n in H.\n      apply le_lt_or_eq in H.\n      destruct H.\n      auto.\n      rewrite H.\n      auto.\n  Qed.\n\n  Lemma sfSumsfp : forall f n p, (Sum f n ||- p) -> (sfT (Sum f n) ||- sf p).\n  Proof.\n    induction n.\n    - simpl. intros.\n      apply TInclusion with (T:=Null).\n      unfold incT.\n      intros. \n      contradiction.\n      apply Null_psfp.\n      apply nullNull.\n      auto.\n    - simpl. intros.\n      apply sf_dsb.\n      apply deduction_inv.\n      assert(sf(f n [->] p) = sf(f n)[->]sf p). unfold sf. simpl. auto.\n      rewrite <- H0.\n      apply IHn.\n      fintro.\n      auto.\n  Qed.\n\n  Lemma sfTSum : forall f n p, (Sum (fun x => sf (f x)) n ||- p) -> (sfT (Sum f n) ||- p).\n  Proof.\n    induction n.\n    - simpl.\n      intros.\n      apply TInclusion with (T:=Null).\n      apply null_sfT.\n      apply nullNull.\n      auto.\n    - simpl.\n      intros.\n      apply sf_dsb.\n      apply deduction_inv.\n      apply IHn.\n      fintro.\n      auto.\n  Qed.\n\n  Lemma seq_comp : \n    forall f0 f1 n0 n1, \n    let f := (fun x : nat => if x <? n0 then f0 x else f1 (x - n0)) in \n    Sum f0 n0 ⊆ Sum f (n0 + n1) /\\\n    Sum f1 n1 ⊆ Sum f (n0 + n1).\n  Proof.\n    intros.\n    unfold incT.\n    split.\n    - intros.\n      apply Sump in H.\n      destruct H as [m].\n      destruct H.\n      assert(f m = f0 m). {\n        rewrite <- Nat.ltb_lt in H.\n        unfold f.\n        rewrite H.\n        auto.\n      }\n      rewrite H0.\n      rewrite <- H1.\n      apply Sump_inv.\n      lia.\n    - intros.\n      apply Sump in H.\n      destruct H as [m].\n      destruct H.\n      assert(f (n0 + m) = f1 m). {\n        assert(n0 + m <? n0 = false).\n        rewrite <- Bool.not_true_iff_false.\n        intro.\n        rewrite Nat.ltb_lt in H1.\n        lia.\n        unfold f.\n        rewrite H1.\n        assert(n0 + m - n0 = m). lia.\n        rewrite H2.\n        auto.\n      }\n      rewrite H0.\n      rewrite <- H1.\n      apply Sump_inv.\n      lia.\n  Qed.\n\n  Lemma proof_compact : forall T p, (T ||- p) -> exists f n, (Sum f n ⊆ T) /\\ (Sum f n ||- p).\n  Proof.\n    assert(forall T p, (T ||- p) -> exists f n, (forall m, m < n -> T (f m)) /\\ (Sum f n ||- p)).\n    intros.\n    induction H.\n    - destruct IHprovable as [f]. \n      destruct H0 as [n].\n      destruct H0.   \n      exists (fun n => alt (f n)).\n      exists n.\n      split.\n      intros.\n      specialize (H0 m H2).\n      destruct H0.\n      rewrite alt_sf.\n      auto.\n      GEN.\n      apply sfTSum.\n      apply TInclusion with (T:=Sum f n). {\n        unfold incT. intros.\n        apply Sump in H2.\n        destruct H2 as [m].\n        destruct H2.\n        pose (s := fun x => sf (alt (f x))).\n        fold s.\n        assert(s m = f m). {\n          specialize(H0 m H2).\n          unfold s.\n          destruct H0.\n          rewrite alt_sf.\n          auto.\n        }\n        rewrite H3.\n        rewrite <- H4.\n        apply Sump_inv. auto.\n      }\n      auto.\n    - destruct IHprovable1 as [f0].\n      destruct H1 as [n0].\n      destruct H1.\n      destruct IHprovable2 as [f1]. \n      destruct H3 as [n1].\n      destruct H3.\n      pose (f := (fun x : nat => if x <? n0 then f0 x else f1 (x - n0))).\n      exists f. exists (n0 + n1).\n      split.\n      + intros.\n        unfold f.\n        assert(lem := classic (m <? n0 = true)). destruct lem.\n        rewrite H6. apply H1.\n        rewrite <- Nat.ltb_lt. auto.\n        rewrite Bool.not_true_iff_false in H6.\n        rewrite H6. apply H3.\n        rewrite <- Bool.not_true_iff_false in H6.\n        apply NNPP.\n        contradict H6.\n        rewrite Nat.ltb_lt. lia.\n      + assert(Sum f0 n0 ⊆ Sum f (n0 + n1) /\\ Sum f1 n1 ⊆ Sum f (n0 + n1)). {\n          unfold f. apply seq_comp.\n        }\n        destruct H5.\n        MP p.\n        apply TInclusion with (T:=Sum f0 n0). auto. auto. \n        apply TInclusion with (T:=Sum f1 n1). auto. auto.\n    - exists(fun _ => p).\n      exists 1.\n      split. auto.\n      simpl. auto.\n    - exists(fun _ => [O][=][O]).\n      exists 0.\n      split. lia.\n      auto.\n    - exists(fun _ => [O][=][O]).\n      exists 0.\n      split. lia.\n      auto.\n    - exists(fun _ => [O][=][O]).\n      exists 0.\n      split. lia.\n      auto.\n    - exists(fun _ => [O][=][O]).\n      exists 0.\n      split. lia.\n      auto.\n    - exists(fun _ => [O][=][O]).\n      exists 0.\n      split. lia.\n      auto.\n    - exists(fun _ => [O][=][O]).\n      exists 0.\n      split. lia.\n      auto.\n    - exists(fun _ => [O][=][O]).\n      exists 0.\n      split. lia.\n      auto.\n    - exists(fun _ => [O][=][O]).\n      exists 0.\n      split. lia.\n      auto.\n    - intros.\n      specialize (H T p H0).\n      destruct H as [f]. \n      destruct H as [n].\n      exists f. \n      exists n.\n      unfold incT.\n      destruct H.\n      split.\n      intros.\n      apply Sump in H2. destruct H2. \n      destruct H2.\n      rewrite H3. auto.\n      auto. \n  Qed.\n\n  Lemma sfT_inc : forall T U, (T ⊆ U) -> (sfT T ⊆ sfT U).\n  Proof.\n    unfold incT.\n    intros.\n    destruct H0.\n    auto.\n  Qed.\n\n  Lemma sf_add : forall T p, (T ||- p) -> (sfT T ||- sf p).\n  Proof.\n    intros.\n    apply proof_compact in H.\n    destruct H as [f].\n    destruct H as [n].\n    destruct H.\n    apply sfSumsfp in H0.\n    apply TInclusion with (T:=sfT (Sum f n)).\n    apply sfT_inc. auto.\n    auto.\n  Qed.\n\n  Lemma sfT_MP : forall T p q, (T ||- p) -> (sfT T ¦ sf p ||- q) -> (sfT T ||- q).\n  Proof.\n    intros.\n    MP (sf p).\n    apply sf_add. auto.\n    fintro.\n    auto.\n  Qed. \n  \n  Lemma fal_repl : forall T p, \n    ([fal][fal]p) ==(T) ([fal][fal]p.['1;('0;fun x => '(S (S x)))]).\n  Proof.\n    assert(forall T p, T ||- ([fal][fal]p)[->]([fal][fal]p.['1;('0;fun x => '(S (S x)))])).\n    - intros.\n      fintro.\n      GEN.\n      GEN.\n      assert(p.['0;('1;fun x => '(4 + x))]/('1, '0) = p.['1;('0;fun x => '(S (S x)))]). {\n        rewrite nested_rew.\n        apply rew_rew.\n        intros.\n        destruct n.\n        auto.\n        destruct n.\n        auto. auto.\n      }\n      rewrite <- H.\n      apply fal_R2.\n      assert(sf (sf ([fal][fal]p)) = ([fal][fal]p.['0; ('1; fun x => '(4 + x))])). {\n        unfold sf. simpl.\n        apply fal_eq.\n        apply fal_eq.\n        rewrite nested_rew.\n        apply rew_rew.\n        intros. unfold sfc. simpl.\n        destruct n. auto.\n        destruct n. auto.\n        auto.\n      }\n      rewrite <- H0.\n      auto.\n    - intros.\n      fsplit.\n      auto.\n      assert(p = p.['1;('0;fun x => '(S (S x)))].['1;('0;fun x => '(S (S x)))]). {\n        rewrite -> rew_id at 1.\n        rewrite nested_rew.\n        apply rew_rew.\n        intros.\n        destruct n. auto. simpl.\n        destruct n. auto.\n        auto.\n      }\n      rewrite -> H0 at 2.\n      auto.\n  Qed.\n\n  Lemma neq_symm : forall T t u, (T ||- t[=/=]u) -> (T ||- u[=/=]t).\n  Proof.\n    intros.\n    RAA (t[=]u).\n    fsymmetry. auto.\n    WL. auto.\n  Qed.\n\n  Lemma DNE : forall T p, p ==(T) [~][~]p.\n  Proof.\n    unfold equiv. simpl. unfold priff.\n    intros.\n    fsplit.\n    apply pr_NN.\n    apply pr_NNPP.\n  Qed.\n  \nEnd deduction_facts2.\n\nLtac MPsf h := repeat WL; apply (@sfT_MP _ _ h _).", "meta": {"author": "iehality", "repo": "FOPL", "sha": "5ee8175f4eb3f3a807c6e6c5dcb49c4d551d560f", "save_path": "github-repos/coq/iehality-FOPL", "path": "github-repos/coq/iehality-FOPL/FOPL-5ee8175f4eb3f3a807c6e6c5dcb49c4d551d560f/Basic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6668705234084488}}
{"text": "(*** Barrett Reduction *)\n(** This file implements a slightly-generalized version of Barrett\n    Reduction on [Z].  This version follows the Handbook of Applied\n    Cryptography (Algorithm 14.42) rather closely; the only deviations\n    are that we generalize from [k ± 1] to [k ± offset] for an\n    arbitrary offset, and we weaken the conditions on the base [b] in\n    [bᵏ] slightly.  Contrasted with some other versions, this version\n    does reduction modulo [b^(k+offset)] early (ensuring that we don't\n    have to carry around extra precision), but requires more stringint\n    conditions on the base ([b]), exponent ([k]), and the [offset]. *)\nRequire Import Coq.ZArith.ZArith Coq.micromega.Lia.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.ZUtil.Tactics.ZeroBounds.\nRequire Import Crypto.Util.ZUtil.Div.\nRequire Import Crypto.Util.ZUtil.Modulo.\nRequire Import Crypto.Util.ZUtil.Hints.\nRequire Import Crypto.Util.ZUtil.ZSimplify.\n\nLocal Open Scope Z_scope.\n\nSection barrett.\n  (** Quoting the Handbook of Applied Cryptography <http://cacr.uwaterloo.ca/hac/about/chap14.pdf>: *)\n  (** Barrett reduction (Algorithm 14.42) computes [r = x mod m] given\n      [x] and [m]. The algorithm requires the precomputation of the\n      quantity [µ = ⌊b²ᵏ/m⌋]; it is advantageous if many reductions\n      are performed with a single modulus. For example, each RSA\n      encryption for one entity requires reduction modulo that\n      entity’s public key modulus. The precomputation takes a fixed\n      amount of work, which is negligible in comparison to modular\n      exponentiation cost.  Typically, the radix [b] is chosen to be\n      close to the word-size of the processor. Hence, assume [b > 3] in\n      Algorithm 14.42 (see Note 14.44 (ii)). *)\n\n  (** * Barrett modular reduction *)\n  Section barrett_modular_reduction.\n    Context (m b x k μ offset : Z)\n            (m_pos : 0 < m)\n            (base_pos : 0 < b)\n            (k_good : m < b^k)\n            (μ_good : μ = b^(2*k) / m) (* [/] is [Z.div], which is truncated *)\n            (x_nonneg : 0 <= x)\n            (offset_nonneg : 0 <= offset)\n            (k_big_enough : offset <= k)\n            (x_small : x < b^(2*k))\n            (m_small : 3 * m <= b^(k+offset))\n            (** We also need that [m] is large enough; [m] larger than\n                [bᵏ⁻¹] works, but we ask for something more precise. *)\n            (m_large : x mod b^(k-offset) <= m).\n\n    Let q1 := x / b^(k-offset). Let q2 := q1 * μ. Let q3 := q2 / b^(k+offset).\n    Let r1 := x mod b^(k+offset). Let r2 := (q3 * m) mod b^(k+offset).\n    (** At this point, the HAC says \"If [r < 0] then [r ← r + bᵏ⁺¹]\".\n        This is equivalent to reduction modulo [b^(k+offset)], as we\n        prove below.  The version involving modular reduction has the\n        benefit of being cheaper to implement, and making the proofs\n        simpler, so we primarily use that version. *)\n    Let r_mod_3m      := (r1 - r2) mod b^(k+offset).\n    Let r_mod_3m_orig := let r := r1 - r2 in\n                         if r <? 0 then r + b^(k+offset) else r.\n\n    Lemma r_mod_3m_eq_orig : r_mod_3m = r_mod_3m_orig.\n    Proof using base_pos k_big_enough m_pos m_small offset_nonneg r1 r2.\n      assert (0 <= r1 < b^(k+offset)) by (subst r1; auto with zarith).\n      assert (0 <= r2 < b^(k+offset)) by (subst r2; auto with zarith).\n      subst r_mod_3m r_mod_3m_orig; cbv zeta.\n      break_match; Z.ltb_to_lt.\n      { symmetry; apply (Zmod_unique (r1 - r2) _ (-1)); lia. }\n      { symmetry; apply (Zmod_unique (r1 - r2) _ 0); lia. }\n    Qed.\n\n    (** 14.43 Fact By the division algorithm (Definition 2.82), there\n        exist integers [Q] and [R] such that [x = Qm + R] and [0 ≤ R <\n        m]. In step 1 of Algorithm 14.42 (Barrett modular reduction),\n        the following inequality is satisfied: [Q - 2 ≤ q₃ ≤ Q]. *)\n    (** We prove this by providing a more useful form for [q₃]. *)\n    Let Q := x / m.\n    Let R := x mod m.\n    Lemma q3_nice : { b : bool * bool | q3 = Q + (if fst b then -1 else 0) + (if snd b then -1 else 0) }.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg x_nonneg x_small μ_good.\n      assert (0 < b^(k+offset)) by Z.zero_bounds.\n      assert (0 < b^(k-offset)) by Z.zero_bounds.\n      assert (x / b^(k-offset) <= b^(2*k) / b^(k-offset)) by auto with zarith lia.\n      assert (x / b^(k-offset) <= b^(k+offset)) by (autorewrite with pull_Zpow zsimplify in *; assumption).\n      subst q1 q2 q3 Q r_mod_3m r_mod_3m_orig r1 r2 R μ.\n      rewrite (Z.div_mul_diff_exact' (b^(2*k)) m (x/b^(k-offset))) by auto with lia zero_bounds.\n      rewrite (Z_div_mod_eq_full (_ * b^(2*k) / m) (b^(k+offset))).\n      autorewrite with push_Zmul push_Zopp zsimplify zstrip_div zdiv_to_mod.\n      rewrite Z.div_sub_mod_cond, !Z.div_sub_small; auto with zero_bounds zarith.\n      eexists (_, _); reflexivity.\n    Qed.\n\n    Fact q3_in_range : Q - 2 <= q3 <= Q.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg q2 x_nonneg x_small μ_good.\n      rewrite (proj2_sig q3_nice).\n      break_match; lia.\n    Qed.\n\n    (** 14.44 Note (partial justification of correctness of Barrett reduction) *)\n    (** (i) Algorithm 14.42 is based on the observation that [⌊x/m⌋]\n            can be written as [Q =\n            ⌊(x/bᵏ⁻¹)(b²ᵏ/m)(1/bᵏ⁺¹)⌋]. Moreover, [Q] can be\n            approximated by the quantity [q₃ = ⌊⌊x/bᵏ⁻¹⌋µ/bᵏ⁺¹⌋].\n            Fact 14.43 guarantees that [q₃] is never larger than the\n            true quotient [Q], and is at most 2 smaller. *)\n    Lemma x_minus_q3_m_in_range : 0 <= x - q3 * m < 3 * m.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg q2 x_nonneg x_small μ_good.\n      clear k_good.\n      pose proof q3_in_range.\n      assert (0 <= R < m) by (subst R; auto with zarith).\n      assert (0 <= (Q - q3) * m + R < 3 * m) by nia.\n      subst Q R; autorewrite with push_Zmul zdiv_to_mod in *; lia.\n    Qed.\n\n    Lemma r_mod_3m_eq_alt : r_mod_3m = x - q3 * m.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg q2 x_nonneg x_small μ_good.\n      pose proof x_minus_q3_m_in_range.\n      subst r_mod_3m r_mod_3m_orig r1 r2.\n      autorewrite with pull_Zmod zsimplify; reflexivity.\n    Qed.\n\n    (** This version uses reduction modulo [b^(k+offset)]. *)\n    Theorem barrett_reduction_equivalent\n      : r_mod_3m mod m = x mod m.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg r1 r2 x_nonneg x_small μ_good.\n      rewrite r_mod_3m_eq_alt.\n      autorewrite with zsimplify push_Zmod; reflexivity.\n    Qed.\n\n    (** This version, which matches the original in the HAC, uses\n        conditional addition of [b^(k+offset)]. *)\n    Theorem barrett_reduction_orig_equivalent\n      : r_mod_3m_orig mod m = x mod m.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg r_mod_3m x_nonneg x_small μ_good. rewrite <- r_mod_3m_eq_orig; apply barrett_reduction_equivalent. Qed.\n\n    Lemma r_small : 0 <= r_mod_3m < 3 * m.\n    Proof using Q R base_pos k_big_enough m_large m_pos m_small offset_nonneg q3 x_nonneg x_small μ_good.\n      pose proof x_minus_q3_m_in_range.\n      subst Q R r_mod_3m r_mod_3m_orig r1 r2.\n      autorewrite with pull_Zmod zsimplify; lia.\n    Qed.\n\n\n    (** This version uses reduction modulo [b^(k+offset)]. *)\n    Theorem barrett_reduction_small (r := r_mod_3m)\n      : x mod m = let r := if r <? m then r else r-m in\n                  let r := if r <? m then r else r-m in\n                  r.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg r1 r2 x_nonneg x_small μ_good.\n      pose proof r_small. cbv zeta.\n      destruct (r <? m) eqn:Hr, (r-m <? m) eqn:?; subst r; rewrite !r_mod_3m_eq_alt, ?Hr in *; Z.ltb_to_lt; try lia.\n      { symmetry; eapply (Zmod_unique x m q3); lia. }\n      { symmetry; eapply (Zmod_unique x m (q3 + 1)); lia. }\n      { symmetry; eapply (Zmod_unique x m (q3 + 2)); lia. }\n    Qed.\n\n    (** This version, which matches the original in the HAC, uses\n        conditional addition of [b^(k+offset)]. *)\n    Theorem barrett_reduction_small_orig (r := r_mod_3m_orig)\n      : x mod m = let r := if r <? m then r else r-m in\n                  let r := if r <? m then r else r-m in\n                  r.\n    Proof using base_pos k_big_enough m_large m_pos m_small offset_nonneg r_mod_3m x_nonneg x_small μ_good. subst r; rewrite <- r_mod_3m_eq_orig; apply barrett_reduction_small. Qed.\n  End barrett_modular_reduction.\nEnd barrett.\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/BarrettReduction/HAC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094304, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6668200848026005}}
{"text": "Require Export Basics.\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x := \n        match reverse goal with\n        | H : _ |- _ => try move x after H\n        end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) := \n        let H := fresh in \n        assert (x = v) as H by reflexivity;\n        clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) := \n        first [\n          set (x := name); move_to_top x\n        | assert_eq x name; move_to_top x\n        | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n\nTheorem andb_true_elim1: forall b c : bool,\n        andb b c = true -> b = true.\nProof.\n        intros b c H.\n        destruct b.\n        Case \"b = true\".\n        reflexivity.\n        Case \"b = false\".\n        rewrite <- H.\n        reflexivity.\nQed.\n\nTheorem nadb_true_elim2: forall b c: bool,\n        andb b c = true -> c = true.\nProof.\n        intros b c H.\n        destruct c.\n        Case \"c = true\".\n        reflexivity.\n        Case \"c = false\".\n        rewrite <- H.\n        destruct b.\n        SCase \"b = true\".\n        reflexivity.\n        SCase \"b = false\".\n        reflexivity.\nQed.\n\nTheorem plus_0_r: forall n: nat, n + 0 = n.\nProof.\n        intros n.\n        induction n as [| n'].\n        Case \"n = 0\". reflexivity.\n        Case \"n = S n'\". simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem minus_diag: forall n: nat, minus n n = 0.\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_0_r: forall n: nat, n * 0 = 0.\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 plus_n_Sm: forall n m: nat, S (n + m) = n + (S m).\nProof.\n        intros n m.\n        induction n as [| n'].\n        Case \"n = 0\". simpl. reflexivity.\n        Case \"n = S 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'].\n        Case \"n = 0\". simpl. rewrite -> plus_0_r. reflexivity.\n        Case \"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.\n        intros n m p.\n        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.\nLemma double_plus: forall n: nat, 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\nTheorem plus_swap: forall n m p: nat, n + (m + p) = m + (n + p).\nProof.\n        intros n m p.\n        assert (HA: n + (m + p) = (n + m) + p).\n                rewrite -> plus_assoc. reflexivity.\n        rewrite -> HA.\n        assert (HB: (n + m) = (m + n)).\n                rewrite -> plus_comm. reflexivity.\n        rewrite -> HB.\n        rewrite -> plus_assoc.\n        reflexivity.\nQed.\n\nTheorem mult_n_Sm: forall n m: nat, n + (n * m) = n * (S m).\nProof.\n        intros n m.\n        induction n as [| n'].\n        Case \"n = 0\". simpl. reflexivity.\n        Case \"n = S n'\". simpl. rewrite -> plus_swap. rewrite -> IHn'. reflexivity.\nQed.\nTheorem mult_comm: forall m n: nat, m * n = n * m.\nProof.\n        intros n m.\n        induction n as [| n'].\n        rewrite -> mult_0_r. reflexivity.\n        simpl.\n        rewrite <- mult_n_Sm. rewrite -> IHn'. 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/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.8670357683915538, "lm_q1q2_score": 0.6668200834814155}}
{"text": "(* Boxed Polyhedra *)\n\nRequire Import Libs.\nRequire Import Errors.\nRequire Import Polyhedra.\nRequire Import Loops.\nRequire Import Memory.\nRequire Import ArithClasses.\nRequire Import Permutation.\nRequire Import Sorted.\nOpen Scope string_scope.\n(*Set Implicit Arguments.*)\nOpen Scope nat_scope.\n\n\n\n(* set the n-th parameter to 1, and the rest to 0 *)\nProgram Definition nth_param_at_1 depth nbr_global_parameters n\n  : ZVector (depth + nbr_global_parameters) :=\n  let aux :=\n    (* the function will be used only in the case where n <\n       nbr_global_parameters. But it is a pain to pass the prove as an argument,\n       so we \"build\" it locally. This is not a problem because this\n       function is only used in specification (no performance\n       constraint) *)\n    if lt_dec n nbr_global_parameters then\n      ((V0 n) +++ (1%Z ::: V0 (nbr_global_parameters - S n)) <:: Vector nbr_global_parameters)\n    else\n    (* wrong usage. It might be \"cleaner\" to return an option type,\n       but more painful too*)\n      (V0 nbr_global_parameters) in\n  V0 depth +++ aux.\nNext Obligation.\n  omega.\nQed.\n\n\nLemma nth_param_at_1_correct_0: forall depth nbr_global_parameters n p,\n  n < nbr_global_parameters -> p <> (depth + n) ->\n  Vnth (nth_param_at_1 depth nbr_global_parameters n) p = 0%Z.\nProof.\n  intros * INF DIFF.\n  unfold nth_param_at_1.\n  destruct (lt_dec n nbr_global_parameters); [|omegaContradiction].\n\n  destruct (lt_dec p depth); simpl_vect; auto.\n  Case \"depth <= p\".\n    replace p with (depth + (p - depth)) in *; [|omega]. \n    simpl_vect.\n    remember (p-depth) as p' in *. clear Heqp'.\n    destruct (lt_eq_lt_dec p' n) as [[|]|]; try omegaContradiction; simpl_vect; auto.\n    SCase \"n < p\".\n      replace p' with (n + S (p' - n - 1)) by omega.\n      simpl_vect; auto.\nQed.\n\nLemma nth_param_at_1_correct_1: forall depth nbr_global_parameters n,\n  n < nbr_global_parameters ->\n  Vnth (nth_param_at_1 depth nbr_global_parameters n) (depth + n) = 1%Z.\nProof.\n  intros *  INF.\n  unfold nth_param_at_1.\n  destruct (lt_dec n nbr_global_parameters); [|omegaContradiction].\n  simpl_vect.\n  clear INF l.\n  remember (nbr_global_parameters - S n) as m. clear Heqm.\n  unfold_vect. simpl.\n  induction' n as [|n]; auto.\nQed.\n\n\n\n\n(* a constraint that only says the n th param must be equal to x *)\n\nDefinition constraint_nth_param depth nbr_global_parameters n x:=\n  {| constr_vect := nth_param_at_1 depth nbr_global_parameters n;\n     constr_comp := EQ;\n     constr_val := x|}.\n\n\n(* move to lib *)\n\n\n  \n(* if a vector satisfies the constraint, its nth param has value x *)\nLemma satisfies_constraint_nth_param_1:\n  forall depth nbr_global_parameters n (INF: n< nbr_global_parameters) x v,\n  satisfy_constraint v (constraint_nth_param depth nbr_global_parameters n x) ->\n  Vnth (Vdrop_p depth v) n = x.\nProof.\n  intros * INF * SATISF.\n\n  unfold satisfy_constraint, constraint_nth_param, nth_param_at_1 in *. simpl in *.\n  rewrite <- (Vapp_take_drop _ _ v) in SATISF.\n  simpl_vect in *.\n\n  remember (Vdrop_p depth v) as v'. clear Heqv'.\n  clear v.\n\n  destruct (lt_dec n nbr_global_parameters); try contradiction.\n\n\n  assert ((n + (S (nbr_global_parameters - S n)) = nbr_global_parameters)%nat) by omega.\n  dest_vects.  simpl_vect in *. simpl in *.\n  subst.\n\n  clear INF.\n  revert dependent v'.\n  induction' n as [|n']; simpl in *; intros.\n  Case \"O\".\n    destruct v'.\n    simpl in *; omega.\n    rewrite PVprod_repeat_0. \n    simpl.\n    destruct z; omega.\n\n  Case \"S n'\".\n    destruct v'.\n    simpl in *; omega.\n    simpl. apply IHn'; auto.\n    simpl in *. omega.\nQed.\n\n(* if the n-th param is x, then the vector statifies the constraint *)\nLemma satisfies_constraint_nth_param_2: forall depth nbr_global_parameters n (INF: n < nbr_global_parameters) x v,\n  Vnth (Vdrop_p depth v) n = x ->\n  satisfy_constraint v (constraint_nth_param depth nbr_global_parameters n x).\nProof.\n  intros * INF * ACCESS.\n\n  unfold satisfy_constraint, constraint_nth_param, nth_param_at_1 in *. simpl in *.\n  rewrite <- (Vapp_take_drop _ _ v). simpl_vect.\n\n  remember (Vdrop_p depth v) as v'. clear Heqv'.\n  clear v.\n\n  destruct (lt_dec n nbr_global_parameters);[|contradiction].\n\n(*  assert ((n + (S (nbr_global_parameters - S n)) = nbr_global_parameters)%nat) by omega.*)\n\n  dest_vects; simpl_vect in *; simpl in *. clear l.\n\n  remember ((nbr_global_parameters - S n)%nat) as m. clear Heqm. subst.\n\n  revert dependent v'.\n  induction' n as [|n]; intros.\n  Case \"O\".\n    simpl in *.\n    destruct v'; simpl in *; auto.\n    rewrite PVprod_repeat_0. destruct z; omega.\n\n  Case \"S n\".\n    simpl.\n    destruct v'; simpl in *; auto.\n    apply IHn. omega.\nQed.\n\n(* all numbers strictly smaller than len *)\nFixpoint sequence_lesser len : list nat :=\n  match len with\n    | O => []\n    | S len' => len' :: sequence_lesser len'\n  end.\n\n\n(*Notation \"pol1 ∩ pol2\" := (inter_poly pol1 pol2) (at level 65).*)\n\nDefinition poly_containing_params_aux {nbr_global_parameters: nat} depth\n  (params: ZVector nbr_global_parameters)\n   : nat -> Constraint (depth + nbr_global_parameters) :=\n  fun p =>\n    constraint_nth_param depth nbr_global_parameters p\n    (Vnth params p).\n\n(* the polyhedron containing all vectors v of size depth + nbr_global_parameters\n   such that drop_v depth v = params *)\n\nDefinition poly_containing_params {nbr_global_parameters depth: nat}\n  (params: ZVector nbr_global_parameters):\n  Polyhedron (depth + nbr_global_parameters) :=\n  map (poly_containing_params_aux depth params)\n  (sequence_lesser nbr_global_parameters).\n\n(* please note that those functions have pretty bad complexity, but\n   are not meant to be executed. Closure containing them might be\n   created at run time but (if I did nothing wrong :)) should never be\n   run *)\n\n\nLemma map_sequence_lesser_forall_1: forall B (f: nat -> B) P n,\n  list_forall P (map f (sequence_lesser n)) ->\n  forall m, m < n -> P (f m).\nProof.\n  intros *.\n  induction' n as [|n]; intros.\n  Case \"O\".\n    omegaContradiction.\n\n  Case \"S n\".\n  simpl in *. inv H.\n  dest m == n.\n    SCase \"m = n\".\n    subst. auto.\n    SCase \"m <> n\".\n    apply IHn; auto. omega.\nQed.\n\nLemma map_sequence_lesser_forall_2: forall B (f: nat -> B) (P: B -> Prop) n,\n  (forall m, m < n -> P (f m)) ->\n  list_forall P (map f (sequence_lesser n)).\nProof.\n  intros *.\n  induction' n as [|n]; intros FORALL.\n  Case \"O\".\n    simpl. constructor.\n\n  Case \"S n\".\n  simpl. constructor.\n  apply FORALL. omega.\n  apply IHn. intros. apply FORALL. omega.\nQed.\n\nLemma poly_containing_params_list_forall_1 {nbr_global_parameters depth: nat}\n  (params: ZVector nbr_global_parameters) P:\n  list_forall P (poly_containing_params params) ->\n  forall x (INF: (x < nbr_global_parameters)%nat),\n    P (poly_containing_params_aux depth params x).\nProof.\n  intros. eapply (map_sequence_lesser_forall_1 _ _ P); eauto.\nQed.\n\nLemma poly_containing_params_list_forall_2 {nbr_global_parameters depth: nat}\n  (params: ZVector nbr_global_parameters) (P: _ -> Prop):\n  (forall x (INF: (x < nbr_global_parameters)%nat),\n    P (poly_containing_params_aux depth params x)) ->\n  list_forall P (poly_containing_params params).\nProof.\n  intros. eapply (map_sequence_lesser_forall_2 _ _ P); eauto.\nQed.\n\n\n\n(* correctness of poly_containing_params *)\nLemma poly_containing_params_drop_1 {nbr_global_parameters depth: nat}\n  (params: ZVector nbr_global_parameters) (v: ZVector (depth + nbr_global_parameters)):\n  v ∈ poly_containing_params params -> Vdrop_p depth v = params.\nProof.\n  intros IN.\n  apply Vnth_inj.\n  intros.\n  apply (satisfies_constraint_nth_param_1 _ _ _ H).\n  unfold Pol_In, poly_containing_params, poly_containing_params_aux in IN.\n  eapply map_sequence_lesser_forall_1 in IN; eauto.\nQed.\n\nLemma poly_containing_params_drop_2 {nbr_global_parameters depth: nat}\n  (params: ZVector nbr_global_parameters) (v: ZVector (depth + nbr_global_parameters)):\n  Vdrop_p depth v = params -> v ∈ poly_containing_params params.\nProof.\n  intros EQ.\n  unfold Pol_In, poly_containing_params, poly_containing_params_aux in *.\n  apply map_sequence_lesser_forall_2.\n  intros. apply satisfies_constraint_nth_param_2; auto.\n  subst. reflexivity.\nQed.\n\n\n(* the important definition *)\n\n(* add to a polyhedron pol the extra constraint that the nbr_global_parameters\n   last elements of the vector are equal to params by taking the\n   intersection with poly_containing_params*)\n\nDefinition constrain_params {nbr_global_parameters depth: nat}\n  (params: ZVector nbr_global_parameters)\n  (pol: Polyhedron (depth + nbr_global_parameters)):\n  Polyhedron (depth + nbr_global_parameters) :=\n  poly_containing_params params ∩ pol.\n\n\n\n(* any vector in pol that ends with params is in constain_params *)\nLemma in_pol_in_constrain_params: forall (nbr_global_parameters depth: nat)\n  (params: ZVector nbr_global_parameters) (pol: Polyhedron (depth + nbr_global_parameters)) v,\n  (v +++ params) ∈ pol -> (v +++ params) ∈ (constrain_params params pol).\nProof.\n  intros * IN.\n  unfold constrain_params.\n  apply Pol_Included_intersertion; auto.\n  apply poly_containing_params_drop_2.\n  apply Vdrop_p_app.\nQed.\n\nLemma in_pol_in_constrain_params_Vdrop:  forall (nbr_global_parameters depth: nat)\n  (params: ZVector nbr_global_parameters) (pol: Polyhedron (depth + nbr_global_parameters)) v,\n  v ∈ pol -> Vdrop_p depth v = params -> v ∈ (constrain_params params pol).\nProof.\n  intros * IN DROP.\n  unfold constrain_params. apply Pol_Included_intersertion; auto.\n  apply poly_containing_params_drop_2. apply DROP.\nQed.\n\nLemma in_constrain_param_in_pol: forall (nbr_global_parameters depth: nat)\n  (params: ZVector nbr_global_parameters) (pol: Polyhedron (depth + nbr_global_parameters)),\n  (constrain_params params pol) ⊂ pol.\nProof.\n  intros.\n  unfold constrain_params in *.\n  apply Pol_intersection_Included_r.\nQed.\n\nLemma in_constrain_param_suffix: forall (nbr_global_parameters depth: nat)\n  (params: ZVector nbr_global_parameters) (pol: Polyhedron (depth + nbr_global_parameters)) v,\n  v ∈ (constrain_params params pol) ->\n  exists prefix, v = prefix +++ params.\nProof.\n  intros.\n  exists (Vtake_p depth v).\n  rewrite <- (Vapp_take_drop _ _ v) at 1.\n  f_equal; auto.\n  apply poly_containing_params_drop_1.\n  unfold constrain_params in H.\n  apply Pol_intersection_Included_l in H. auto.\nQed.\n\n\n\n(* a boxed Polyhedron is a Polyhedron such that when the params are\n   fixed, it contains a finite number of elements. Those elements are\n   available through the bp_elts function. (in fact, only the prefix\n   of length depth is returned, the \"real\" elements can be obtained by\n   concatenation with the params) *)\n\nRecord Boxed_Polyhedron nbr_global_parameters depth := mk_Boxed_Polyhedron\n  { bp_poly: Polyhedron (depth + nbr_global_parameters);\n    bp_elts: forall params: ZVector nbr_global_parameters, list (ZVector depth);\n\n    (* each element is returned only once *)\n    bp_elts_NoDup: forall params, NoDup (bp_elts params);\n\n    (* all the elements and only the elements are returned *)\n    bp_in_elts_in_poly: forall (vect: ZVector depth) params,\n      In vect (bp_elts params) ->\n      (vect+++params) ∈ bp_poly;\n    bp_in_poly_in_elts: forall (vect: ZVector (depth + nbr_global_parameters)) params,\n      vect ∈ (constrain_params params bp_poly) ->\n      In (Vtake_p depth vect) (bp_elts params)}.\n\nImplicit Arguments bp_poly [[nbr_global_parameters] [depth]].\nImplicit Arguments bp_elts [[nbr_global_parameters] [depth]].\n\nLemma bp_in_elts_in_poly_constrain (nbr_global_parameters depth : nat)\n  (b : Boxed_Polyhedron nbr_global_parameters depth)\n  (vect : ZVector depth) (params : ZVector nbr_global_parameters):\n  In vect (bp_elts b params) ->\n  (vect+++params) ∈ (constrain_params params b.(bp_poly)).\nProof.\n  intros.\n  unfold constrain_params.\n  apply Pol_Included_intersertion.\n  apply poly_containing_params_drop_2. simpl_vect. reflexivity.\n  apply bp_in_elts_in_poly. auto.\nQed.\n", "meta": {"author": "pilki", "repo": "s2sLoop", "sha": "821528456333c518788df2834c674e850d7e7291", "save_path": "github-repos/coq/pilki-s2sLoop", "path": "github-repos/coq/pilki-s2sLoop/s2sLoop-821528456333c518788df2834c674e850d7e7291/src/BoxedPolyhedra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6668200775712115}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_angletrichotomy.\nRequire Export GeoCoq.Elements.OriginalProofs.proposition_18.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_trichotomy1.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma proposition_19 : \n   forall A B C, \n   Triangle A B C -> LtA B C A A B C ->\n   Lt A B A C.\nProof.\nintros.\nassert (nCol A B C) by (conclude_def Triangle ).\nassert (nCol B C A) by (forward_using lemma_NCorder).\nassert (nCol A C B) by (forward_using lemma_NCorder).\nassert (~ Cong A C A B).\n {\n intro.\n assert (Cong A B A C) by (conclude lemma_congruencesymmetric).\n assert (isosceles A B C) by (conclude_def isosceles ).\n assert (CongA A B C A C B) by (conclude proposition_05).\n assert (CongA A C B A B C) by (conclude lemma_equalanglessymmetric).\n assert (CongA B C A A C B) by (conclude lemma_ABCequalsCBA).\n assert (CongA B C A A B C) by (conclude lemma_equalanglestransitive).\n assert (LtA B C A B C A) by (conclude lemma_angleorderrespectscongruence).\n assert (~ LtA B C A B C A) by (conclude lemma_angletrichotomy).\n contradict.\n }\nassert (~ Lt A C A B).\n {\n intro.\n assert (Triangle A C B) by (conclude_def Triangle ).\n assert (LtA C B A A C B) by (conclude proposition_18).\n assert (CongA A B C C B A) by (conclude lemma_ABCequalsCBA).\n assert (LtA A B C A C B) by (conclude lemma_angleorderrespectscongruence2).\n assert (CongA B C A A C B) by (conclude lemma_ABCequalsCBA).\n assert (LtA A B C B C A) by (conclude lemma_angleorderrespectscongruence).\n assert (~ LtA A B C B C A) by (conclude lemma_angletrichotomy).\n contradict.\n }\nassert (CongA A B C A B C) by (conclude lemma_equalanglesreflexive).\nassert (neq A B) by (forward_using lemma_angledistinct).\nassert (neq A C) by (forward_using lemma_angledistinct).\nassert (~ ~ Lt A B A C).\n {\n intro.\n assert (Cong A B A C) by (conclude lemma_trichotomy1).\n assert (Cong A C A B) by (conclude lemma_congruencesymmetric).\n contradict.\n }\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/proposition_19.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6668200768754906}}
{"text": "\nRequire Import List EqNat Arith Omega.\n\n(************* Syntax of Turing machines ***************)\n\n(*** Specification ***)\n\nParameter State: Set.\n\n(*\nDefinition State := nat.\n*)\n\nParameter Sym: Set.\n\n(*\nInductive Sym: Set := blank: Sym\n                    | one: Sym\n                    | zero: Sym.\n*)\n\nInductive Head: Set := R: Head\n                     | L: Head\n                     | W: Sym -> Head.\n\nDefinition Spec: Set := (list (State * Sym * State * Head)).\n\n(*** Tape ***)\n\nCoInductive HTape: Set := Cons: Sym -> HTape -> HTape.\n\nDefinition hd (h:HTape) := match h with | Cons a k => a end.\n\nDefinition tl (h:HTape) := match h with | Cons a k => k end.\n\nInductive Tape: Set := pair: HTape -> HTape -> Tape.\n\n(*** Transition Function ***)\n\nParameter tr: Spec -> State -> Sym -> option (State * Head).\n\n(*\nFixpoint eqsym (a b:Sym) {struct a}: bool :=\n         match a, b with B, B => true\n                    |    one, one => true\n                    |    zero, zero => true\n                    |    _ , _ => false\n         end.\n\nFixpoint eqstate (q p:State) {struct q}: bool :=\n         match q, p with 0, 0 => true\n                    |    (S u), (S v) => (eqstate u v)\n                    |    _, _ => false\n         end.\n\nFixpoint tr (T:Spec) (q:State) (a:Sym) {struct T}: option (State * Head) :=\n         match T with | nil => None\n                      | (cons A T') =>\n         match A with (p, b, r, x) =>\n                      if (eqstate q p)\n                      then if (eqsym b a)\n                           then (Some (r, x))\n                           else (tr T' q a)\n                      else (tr T' q a)\n         end end.\n*)\n", "meta": {"author": "asr", "repo": "tm-coinduction", "sha": "599083b74ffdf0c1032c5c2495fef9bf23a4058c", "save_path": "github-repos/coq/asr-tm-coinduction", "path": "github-repos/coq/asr-tm-coinduction/tm-coinduction-599083b74ffdf0c1032c5c2495fef9bf23a4058c/metatheory/datatypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6668200670017315}}
{"text": "Require Export Ensembles.\nRequire Import EnsemblesImplicit.\nRequire Export Image.\nRequire Import ImageImplicit.\nRequire Export Relation_Definitions.\nRequire Import Relation_Definitions_Implicit.\nRequire Import Description.\nRequire Import ProofIrrelevance.\nRequire Import Proj1SigInjective.\nRequire Export EnsemblesSpec.\n\nSet Implicit Arguments.\nSection Quotient.\nVariable A:Type.\nVariable R:relation A.\nHypothesis equivR:equivalence R.\n\nDefinition equiv_class (x:A) : Ensemble A :=\n  [ y:A | R x y ].\n\nLemma R_impl_equality_of_equiv_class:\n  forall x y:A, R x y -> equiv_class x = equiv_class y.\nProof.\ndestruct equivR.\nintros.\napply Extensionality_Ensembles; split; red; intros z ?.\nconstructor.\ndestruct H0.\napply equiv_trans with x; trivial.\napply equiv_sym; trivial.\ndestruct H0.\nconstructor.\napply equiv_trans with y; trivial.\nQed.\n\nLemma equality_of_equiv_class_impl_R:\n  forall x y:A, equiv_class x = equiv_class y -> R x y.\nProof.\ndestruct equivR.\nintros.\nassert (In (equiv_class x) x).\nconstructor.\napply equiv_refl.\nrewrite H in H0.\ndestruct H0.\napply equiv_sym.\nassumption.\nQed.\n\nDefinition equiv_classes : Ensemble (Ensemble A) :=\n  Im Full_set equiv_class.\nDefinition quotient : Type :=\n  { S:Ensemble A | In equiv_classes S }.\n\nLemma equiv_class_in_quotient: forall x:A,\n  In equiv_classes (equiv_class x).\nProof.\nunfold equiv_classes.\nintro.\napply Im_def.\nconstructor.\nQed.\n\nDefinition quotient_projection (x:A) : quotient :=\n  exist _ (equiv_class x) (equiv_class_in_quotient x).\n\nLemma quotient_projection_correct: forall x:A,\n  proj1_sig (quotient_projection x) = equiv_class x.\nProof.\ntrivial.\nQed.\n\nLemma quotient_projection_surjective: forall xbar:quotient,\n  exists x:A, quotient_projection x = xbar.\nProof.\nintro.\ndestruct xbar.\ndestruct i.\nexists x.\nunfold quotient_projection.\npose proof e.\nsymmetry in H; destruct H.\nf_equal.\napply proof_irrelevance.\nQed.\n\nLemma quotient_projection_collapses_R: forall x1 x2:A,\n  R x1 x2 -> quotient_projection x1 = quotient_projection x2.\nProof.\nintros.\napply subset_eq_compatT.\napply R_impl_equality_of_equiv_class.\nassumption.\nQed.\n\nLemma quotient_projection_minimally_collapses_R: forall x1 x2:A,\n  quotient_projection x1 = quotient_projection x2 -> R x1 x2.\nProof.\nintros.\napply equality_of_equiv_class_impl_R.\nrepeat rewrite <- quotient_projection_correct.\nrewrite H.\nreflexivity.\nQed.\n\nEnd Quotient.\n\nSection InducedFunction.\n\n(* well-defined A->B induces a function A/R->B *)\n\nVariable A B:Type.\nVariable R:Relation A.\nVariable f:A->B.\nHypothesis equiv:equivalence R.\nHypothesis well_defined: forall x y:A, R x y -> f x = f y.\n\nLemma description_of_fbar: forall xbar:quotient R, exists! y:B,\n  exists x:A, quotient_projection R x = xbar /\\ f x = y.\nProof.\nintro.\npose proof (quotient_projection_surjective xbar).\ndestruct H.\nexists (f x).\nunfold unique.\nsplit.\nexists x.\ntauto.\nintros.\ndestruct H0.\ndestruct H0.\nrewrite <- H1.\napply well_defined.\napply equality_of_equiv_class_impl_R; trivial.\ntransitivity (proj1_sig (quotient_projection R x)).\ntrivial.\nrewrite H.\nrewrite <- H0.\ntrivial.\nQed.\n\nDefinition induced_function (xbar:quotient R) : B :=\n  proj1_sig (constructive_definite_description _\n               (description_of_fbar xbar)).\n\nLemma induced_function_correct: forall x:A,\n  induced_function (quotient_projection R x) = f x.\nProof.\nintro.\nunfold induced_function.\ndestruct constructive_definite_description.\nsimpl.\ndestruct e.\ndestruct H.\nrewrite <- H0.\napply well_defined.\napply quotient_projection_minimally_collapses_R; trivial.\nQed.\n\nLemma induced_function_unique: forall fbar:quotient R->B,\n  (forall x:A, fbar (quotient_projection R x) = f x) ->\n  (forall xbar:quotient R, fbar xbar = induced_function xbar).\nProof.\nintros.\ndestruct (quotient_projection_surjective xbar).\nrewrite <- H0.\nrewrite H.\nrewrite induced_function_correct.\nreflexivity.\nQed.\n\nEnd InducedFunction.\n\nSection InducedFunction2.\n\n(* well-defined function A->B induces a function A/R->B/S *)\n\nVariable A B:Type.\nVariable R:relation A.\nVariable S:relation B.\nVariable f:A->B.\nHypothesis equivR: equivalence R.\nHypothesis equivS: equivalence S.\nHypothesis well_defined2: forall a1 a2:A, R a1 a2 -> S (f a1) (f a2).\n\nDefinition projf (a:A) : quotient S :=\n  quotient_projection S (f a).\nLemma projf_well_defined: forall a1 a2:A,\n  R a1 a2 -> projf a1 = projf a2.\nProof.\nintros.\nunfold projf.\napply quotient_projection_collapses_R; trivial.\napply well_defined2.\nassumption.\nQed.\n\nDefinition induced_function2: quotient R -> quotient S :=\n  induced_function projf equivR projf_well_defined.\n\nLemma induced_function2_correct: forall a:A,\n  induced_function2 (quotient_projection R a) =\n  quotient_projection S (f a).\nProof.\nintros.\nunfold induced_function2.\nrewrite induced_function_correct.\nreflexivity.\nQed.\n\nEnd InducedFunction2.\n\nSection InducedFunction2arg.\n\n(* well-defined function A x B -> C induces a function\n   (A/R) x (B/S) -> C *)\n\nVariable A B C:Type.\nVariable R:relation A.\nVariable S:relation B.\nVariable f:A->B->C.\nHypothesis equivR:equivalence R.\nHypothesis equivS:equivalence S.\nHypothesis well_defined_2arg: forall (a1 a2:A) (b1 b2:B),\n  R a1 a2 -> S b1 b2 -> f a1 b1 = f a2 b2.\n\nLemma slices_well_defined: forall (a:A) (b1 b2:B),\n  S b1 b2 -> f a b1 = f a b2.\nProof.\nintros.\napply well_defined_2arg.\napply (equiv_refl equivR).\nassumption.\nQed.\n\nDefinition induced1 (a:A) : quotient S -> C :=\n   induced_function (f a) equivS (slices_well_defined a).\n\nDefinition eq_fn (f g:quotient S->C) :=\n  forall b:quotient S, f b = g b.\nLemma eq_fn_equiv: equivalence eq_fn.\nProof.\nconstructor.\nunfold reflexive.\nunfold eq_fn.\nreflexivity.\nunfold transitive.\nunfold eq_fn.\nintros.\ntransitivity (y b).\napply H.\napply H0.\nunfold symmetric.\nunfold eq_fn.\nsymmetry.\napply H.\nQed.\n\nLemma well_defined_induced1: forall a1 a2:A, R a1 a2 ->\n  eq_fn (induced1 a1) (induced1 a2).\nProof.\nunfold eq_fn.\nintros.\npose proof (quotient_projection_surjective b).\ndestruct H0.\nrewrite <- H0.\nunfold induced1.\nrewrite induced_function_correct.\nrewrite induced_function_correct.\napply well_defined_2arg.\nassumption.\napply (equiv_refl equivS).\nQed.\n\nDefinition induced2 :=\n  induced_function2 induced1 equivR eq_fn_equiv well_defined_induced1.\n\nDefinition eval (b:quotient S) (f:quotient S->C): C := f b.\nLemma well_defined_eval: forall (b:quotient S) (f g:quotient S->C),\n  eq_fn f g -> eval b f = eval b g.\nProof.\nintros.\nunfold eval.\napply H.\nQed.\n\nDefinition induced_eval (b:quotient S) :=\n  induced_function (eval b) eq_fn_equiv (well_defined_eval b).\n\nDefinition induced_function2arg (a:quotient R) (b:quotient S) : C :=\n  induced_eval b (induced2 a).\n\nLemma induced_function2arg_correct: forall (a:A) (b:B),\n  induced_function2arg (quotient_projection R a) (quotient_projection S b) =\n  f a b.\nProof.\nintros.\nunfold induced_function2arg.\nunfold induced_eval.\nunfold induced2.\nrewrite induced_function2_correct.\nrewrite induced_function_correct.\nunfold eval.\nunfold induced1.\nrewrite induced_function_correct.\nreflexivity.\nQed.\n\nEnd InducedFunction2arg.\n\nSection InducedFunction3.\n\n(* well-defined function A x B -> C induces a function\n   (A/R) x (B/S) -> C/T *)\n\nVariable A B C:Type.\nVariable R:relation A.\nVariable S:relation B.\nVariable T:relation C.\nVariable f:A->B->C.\nHypothesis equivR:equivalence R.\nHypothesis equivS:equivalence S.\nHypothesis equivT:equivalence T.\nHypothesis well_defined3: forall (a1 a2:A) (b1 b2:B),\n  R a1 a2 -> S b1 b2 -> T (f a1 b1) (f a2 b2).\n\nDefinition projf2 (a:A) (b:B) :=\n  quotient_projection T (f a b).\n\nLemma projf2_well_defined: forall (a1 a2:A) (b1 b2:B),\n  R a1 a2 -> S b1 b2 -> projf2 a1 b1 = projf2 a2 b2.\nProof.\nintros.\napply quotient_projection_collapses_R; trivial.\napply well_defined3.\nassumption.\nassumption.\nQed.\n\nDefinition induced_function3 : quotient R -> quotient S -> quotient T :=\n  induced_function2arg projf2 equivR equivS projf2_well_defined.\n\nLemma induced_function3_correct: forall (a:A) (b:B),\n  induced_function3 (quotient_projection R a)\n                    (quotient_projection S b) =\n  quotient_projection T (f a b).\nProof.\nintros.\nunfold induced_function3.\nrewrite induced_function2arg_correct.\nreflexivity.\nQed.\n\nEnd InducedFunction3.\n", "meta": {"author": "dschepler", "repo": "coq-zorns-lemma", "sha": "4ad354c50f73758c094f43da5fc0f2c6dd8e3da2", "save_path": "github-repos/coq/dschepler-coq-zorns-lemma", "path": "github-repos/coq/dschepler-coq-zorns-lemma/coq-zorns-lemma-4ad354c50f73758c094f43da5fc0f2c6dd8e3da2/Quotients.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094304, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6668200664465236}}
{"text": "Require Import List Arith Bool Maps FinFun Basics.\n\n\n(** *We try to create a simple data structure to store Graphs, using dependent typing *)\nFixpoint f_maker (a b: nat) := fun (x:nat) => if beq_nat x a then b else 0.\n\n\n(** let us represent edges of graphs using functions ( -> type for -> edges) *)\nDefinition edge_maker (x y:id) :=\n  match x,y with Id x1,Id y1 => \n                 fun (a : id) => match a with Id a1 => Id ((f_maker x1 y1) a1) end\n  end.\n\n(** define some sample points *)\nDefinition V1 := Id 5.\nDefinition V2 := Id 6.\nDefinition V3 := Id 7.\nDefinition V4 := Id 8.\n\n(** sample edges *)\nDefinition f := edge_maker V1 V2.\nDefinition g := edge_maker V2 V3.\nDefinition h := edge_maker V3 V4.\n\nEval compute in (f (Id 5)).     \n\nDefinition nodeList := list id.\nDefinition edgeList := list (id -> id).\n\nCheck compose.\n(** similar to function composition, we get edge composition*)\nDefinition edge_compose (f g : id -> id) := compose g f.\n\nDefinition f_inv := edge_maker (Id 6) (Id 5).\nEval compute in  (edge_compose f f_inv) (Id 5).\n\n(** and we can use edge_compose to get to the last connected vertex *)\nEval compute in ((edge_compose (edge_compose f g) h) (Id 5)).     \n\n(** However the above representation was not very useful, let's put more data in types*)\n\nSection phoas_graph.\n(** a universal constructor for nodes *)\nInductive u (i : id) : Type :=\n  | U : u i.\n\nDefinition v1 := U (Id 5).\nCheck v1.\n\n(** need a new definition for checking equality of nodes *)\nDefinition beq_U  {i j: id} (x : u i) (y : u j) := beq_id i j. \n\n(** need a new way to create edges *)\nDefinition edge_maker2 {i j: id} (x : u i) (y : u j) : u i -> u j :=\n  fun (a : u i) => U j.\n\nDefinition edge_compose2 {i j k : id} (f : u i -> u j) (g : u j -> u k) :=\n  compose g f.\n\nDefinition f1 := edge_maker2 (U V1) (U V2).\nDefinition g1 := edge_maker2 (U V2) (U V3).\nDefinition h1 := edge_maker2 (U V3) (U V4).\n\nCheck f1.\n\nCheck edge_compose2 (edge_compose2 f1 g1) h1.\n\n(** inductive definition for a list of our new edge types. Note that we couldn't use the regular List as it wouldn't accept elements of different types*)\nInductive edge_list : Type :=\n  | ni : edge_list\n  | co {i j : id} : (u i -> u j) -> edge_list -> edge_list.\n\nDefinition ex_edge_list : edge_list := co f1 (co g1 (co h1 ni)).\n\n(** better to use relations than functions, for pattern matching*)\nDefinition fromNode {i j : id} (e : u i -> u j) := i.\n\n(** Now we can even write a function to convert list of edges to adjacency map *)\nFixpoint edgeListToAdjMap (el : edge_list) (m : total_map edge_list) : total_map edge_list :=\n  match el with\n  | ni => m\n  | co hd tl => edgeListToAdjMap tl (t_update m (fromNode hd) tl)\n  end. \n\nEnd phoas_graph.\n", "meta": {"author": "ankitku", "repo": "awotap", "sha": "1354a1f0e2f77c0157398553e666b6ff0be6d1ee", "save_path": "github-repos/coq/ankitku-awotap", "path": "github-repos/coq/ankitku-awotap/awotap-1354a1f0e2f77c0157398553e666b6ff0be6d1ee/Phoas_Graph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6668200578236931}}
{"text": "Inductive tree (Node: Type): Type :=\n| E : tree Node\n| T (l: tree Node) (x: Node) (r: tree Node).\n\nArguments E {_}.\nArguments T {_} _ _ _.\n\nInductive half_tree (Node: Type): Type :=\n| LH (x: Node) (r: tree Node): half_tree Node\n| RH (l: tree Node) (x: Node): half_tree Node.\n\nArguments LH {_} _ _.\nArguments RH {_} _ _.\n\nFixpoint tree_rel {Node1 Node2: Type} (node_rel: Node1 -> Node2 -> Prop)\n                  (t1: tree Node1) (t2: tree Node2): Prop :=\n  match t1, t2 with\n  | E, E => True\n  | T l1 x1 r1, T l2 x2 r2 =>\n    tree_rel node_rel l1 l2 /\\ node_rel x1 x2 /\\ tree_rel node_rel r1 r2\n  | _, _ => False\n  end.\n\n", "meta": {"author": "maoliyuan", "repo": "avltree-verification", "sha": "1258e9bd5fa7d849ba8b387978bca41d56c64c9a", "save_path": "github-repos/coq/maoliyuan-avltree-verification", "path": "github-repos/coq/maoliyuan-avltree-verification/avltree-verification-1258e9bd5fa7d849ba8b387978bca41d56c64c9a/General/BinaryTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.666820053234674}}
{"text": "Require Import GeoCoq.Axioms.parallel_postulates.\nRequire Import GeoCoq.Tarski_dev.Ch12_parallel.\n\nSection playfair_par_trans.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\n(** This is Legendre theorem XXV http://gallica.bnf.fr/ark:/12148/bpt6k202689z/f29.image *)\n\nLemma playfair_implies_par_trans :\n  playfair_s_postulate -> postulate_of_transitivity_of_parallelism.\nProof.\n  intros HP A1 A2 B1 B2 C1 C2 HAB HBC.\n  assert_diffs.\n  destruct (cop_dec A1 A2 C1 B1) as [|HNCop]; [induction (col_dec A1 A2 C1)|].\n\n  - right.\n    destruct (HP B1 B2 C1 C2 A1 A2 C1); Par; Col.\n\n  - left.\n    repeat split; auto.\n    { apply par_symmetry in HBC.\n      destruct HBC; [destruct HAB|]; [|spliter..].\n      - assert_ncols; apply coplanar_pseudo_trans with B1 B2 C1; [Col| | |Cop..];\n          apply coplanar_pseudo_trans with A1 A2 B1; Col; Cop.\n      - apply coplanar_perm_16, col2_cop__cop with B1 B2; Col; Cop.\n      - apply col2_cop__cop with B1 B2; Col; Cop.\n    }\n    intros [X []].\n    destruct (HP B1 B2 A1 A2 C1 C2 X); Par; Col.\n\n  - apply (par_not_col_strict A1 A2 B1 B2 B1) in HAB; [|Col|intro; apply HNCop; Cop].\n    apply (par_not_col_strict B1 B2 C1 C2 C1) in HBC;\n      [|Col|intro; apply HNCop, coplanar_perm_1, col_cop__cop with B2; Cop].\n    destruct (cop_osp__ex_cop2 A1 A2 C1 B1 B2 C1) as [C' [HCop1 [HCop2 HC1C']]]; Cop.\n      apply cop2_os__osp with A1 A2; Cop; Side.\n    assert (HC' : forall X, Coplanar A1 A2 B1 X -> ~ Col X C1 C').\n    { intros X HX1 HX2.\n      apply (par_not_col A1 A2 B1 B2 X HAB).\n      - apply (l9_30 A1 A2 C1 A1 A2 B1 B1); Cop.\n          apply par_strict_not_col_1 with B2, HAB.\n        apply col_cop__cop with C'; Col.\n      - apply (l9_30 A1 A2 B1 B1 B2 C1 C1); Cop.\n          apply par_strict_not_col_1 with C2, HBC.\n        apply col_cop__cop with C'; Col.\n    }\n    left; apply par_strict_col_par_strict with C'; auto.\n    { repeat split; auto.\n      intros [X []].\n      apply HC' with X; Cop.\n    }\n    assert (HBC' : Par_strict B1 B2 C1 C').\n    { repeat split; Col.\n      intros [X []].\n      apply HC' with X; trivial.\n      apply col_cop__cop with B2; Col; Cop.\n    }\n    destruct (HP B1 B2 C1 C2 C1 C' C1); Par; Col.\nQed.\n\nEnd playfair_par_trans.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/GeoCoq/Meta_theory/Parallel_postulates/playfair_par_trans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.666791500577253}}
{"text": "(** Adapted from \"Elements of Set Theory\" Chapter 5 **)\n(** Coq coding by choukh, June 2020 **)\n\nRequire Export ZFC.Elements.EST5_1.\nRequire Import ZFC.Lib.FuncFacts.\n\nLocal Ltac mr := apply mul_ran; auto.\nLocal Ltac ar := apply add_ran; auto.\nLocal Ltac amr := apply add_ran; apply mul_ran; auto.\n\n(*** EST第五章2：整数乘法，整数的序，自然数嵌入 ***)\n\nClose Scope Int_scope.\nOpen Scope omega_scope.\n\nDefinition PreIntMul : set :=\n  PlaneArith ω ω (λ m n p q, <m⋅p + n⋅q, m⋅q + n⋅p>).\nNotation \"a ⋅ᵥ b\" := (PreIntMul[<a, b>])\n  (at level 50) : PreInt_scope.\n\nLemma mul_split : ∀ a b ∈ ω, ∃ m n p q ∈ ω,\n  a = m⋅p + n⋅q ∧ b = m⋅q + n⋅p.\nProof with try apply ω_inductive; nauto.\n  intros a Ha b Hb.\n  exists a. split... exists b. split...\n  exists 1. split... exists 0. split...\n  repeat rewrite mul_1_r, mul_0_r...\n  rewrite add_0_r, add_0_l...\nQed.\n\nLemma preIntMul_maps_onto : PreIntMul: (ω²)² ⟹ ω².\nProof with eauto.\n  apply planeArith_maps_onto.\n  - intros m Hm n Hn p Hp q Hq.\n    apply CPrdI; apply add_ran; apply mul_ran...\n  - intros a Ha b Hb. pose proof mul_split\n      as [m [Hm [n [Hn [p [Hp [q [Hq H1]]]]]]]].\n    apply Ha. apply Hb.\n    exists m. split... exists n. split...\n    exists p. split... exists q. split...\n    apply op_iff...\nQed.\n\nLemma preIntMul_m_n_p_q : ∀ m n p q ∈ ω,\n  <m, n> ⋅ᵥ <p, q> = <m⋅p + n⋅q, m⋅q + n⋅p>.\nProof with auto.\n  intros m Hm n Hn p Hp q Hq.\n  eapply func_ap. destruct preIntMul_maps_onto...\n  apply SepI. apply CPrdI; apply CPrdI;\n    try apply CPrdI; try apply add_ran; try apply mul_ran...\n  zfc_simple...\nQed.\n\nLemma preIntMul_binCompatible :\n  binCompatible (PlaneEquiv ω ω IntEq) ω² PreIntMul.\nProof with auto.\n  split. apply intEquiv_equiv. split.\n  destruct preIntMul_maps_onto as [Hf [Hd Hr]].\n  split... split... rewrite Hr. apply sub_refl.\n  intros x Hx y Hy u Hu v Hv H1 H2.\n  apply CPrdE1 in Hx as [m [Hm [n [Hn Hxeq]]]].\n  apply CPrdE1 in Hy as [p [Hp [q [Hq Hyeq]]]].\n  apply CPrdE1 in Hu as [m' [Hm' [n' [Hn' Hueq]]]].\n  apply CPrdE1 in Hv as [p' [Hp' [q' [Hq' Hveq]]]]. subst.\n  apply planeEquiv in H1... apply planeEquiv in H2...\n  rewrite preIntMul_m_n_p_q, preIntMul_m_n_p_q...\n  apply SepI. apply CPrdI; apply CPrdI;\n    apply add_ran; apply mul_ran... zfc_simple. simpl.\n  unfold IntEq in *.\n  assert (H3: (m+n')⋅p = (m'+n)⋅p) by congruence.\n  rewrite mul_distr', mul_distr' in H3; [|auto..].\n  assert (H4: (m'+n)⋅q = (m+n')⋅q) by congruence.\n  rewrite mul_distr', mul_distr' in H4; [|auto..].\n  assert (H5: m'⋅(p+q') = m'⋅(p'+q)) by congruence.\n  rewrite mul_distr, mul_distr in H5; [|auto..].\n  assert (H6: n'⋅(p'+q) = n'⋅(p+q')) by congruence.\n  rewrite mul_distr, mul_distr in H6; [|auto..].\n  rewrite (add_comm (m'⋅p)) in H3; [|mr;auto..].\n  rewrite (add_comm (m'⋅p)) in H5; [|mr;auto..].\n  assert (H35: m⋅p + n'⋅p + (m'⋅q' + m'⋅p) =\n    n⋅p + m'⋅p + (m'⋅p' + m'⋅q)) by congruence.\n  rewrite (add_comm (n⋅p + m'⋅p)) in H35; [|amr;auto..].\n  rewrite <- add_assoc, <- add_assoc in H35; [|amr|mr|mr|amr|mr..].\n  apply add_cancel in H35; [|ar;[amr|mr]|ar;[amr|mr]|mr].\n  assert (H46: m'⋅q + n⋅q + (n'⋅p' + n'⋅q) =\n               m⋅q + n'⋅q + (n'⋅p + n'⋅q')) by congruence.\n  rewrite (add_comm (m⋅q + n'⋅q)) in H46; [|amr;auto..].\n  rewrite <- add_assoc, <- add_assoc in H46; [|amr|mr|mr|amr|mr..].\n  apply add_cancel in H46; swap 2 4; [|mr|ar;[amr|mr]..].\n  rewrite (add_comm (m⋅p)), add_assoc in H35; [|mr;auto..].\n  assert (H: n'⋅p + (m⋅p + m'⋅q') + (m'⋅q + n⋅q + n'⋅p') =\n    m'⋅p' + m'⋅q + n⋅p + (n'⋅p + n'⋅q' + m⋅q)) by congruence.\n  rewrite add_assoc in H; [|mr|amr|ar;[amr|mr]].\n  rewrite (add_comm (m'⋅p' + m'⋅q + n⋅p)) in H; [|ar;[amr|mr];auto..].\n  rewrite (add_assoc (n'⋅p)) in H; [|mr;auto..].\n  rewrite (add_assoc (n'⋅p)) in H; [|mr|amr|ar;[amr|mr]].\n  apply add_cancel' in H; swap 2 4; [|mr|ar;[ar|ar;[ar|]];mr..].\n  rewrite (add_comm (m'⋅q)) in H; [|mr;auto..].\n  rewrite (add_comm (n⋅q + m'⋅q)) in H; [|amr|mr].\n  rewrite <- add_assoc in H; [|amr|mr|amr].\n  rewrite <- add_assoc in H; [|ar;[ar|];mr|mr..].\n  rewrite (add_comm (m'⋅p' + m'⋅q)) in H; [|amr|mr].\n  rewrite <- add_assoc in H; [|amr|mr|amr].\n  rewrite <- add_assoc in H; [|ar;[ar|];mr|mr..].\n  apply add_cancel in H; swap 2 4; [|mr|ar;[ar;[ar|]|];mr..].\n  rewrite add_assoc; [|mr|mr|amr].\n  rewrite (add_comm (n⋅q)); [|mr|amr].\n  rewrite <- add_assoc, <- add_assoc; swap 2 6; [|amr|mr..].\n  rewrite (add_assoc (m'⋅p')); [|mr|mr|amr].\n  rewrite (add_comm (m'⋅p')); [|mr|ar;[mr|amr]].\n  rewrite <- (add_assoc (n'⋅q')); [|mr;auto..]. apply H.\nQed.\n\nClose Scope omega_scope.\nOpen Scope Int_scope.\n\n(** 整数乘法 **)\nDefinition IntMul : set :=\n  QuotionFunc (PlaneEquiv ω ω IntEq) ω² PreIntMul.\nNotation \"a ⋅ b\" := (IntMul[<a, b>]) : Int_scope.\n\nLemma intMul_maps_onto : IntMul: ℤ × ℤ ⟹ ℤ.\nProof.\n  apply quotionFunc_maps_onto.\n  apply preIntMul_binCompatible.\n  apply preIntMul_maps_onto.\nQed.\n\nLemma intMul_a_b : ∀ a b ∈ ω², [a]~ ⋅ [b]~ = [a ⋅ᵥ b]~.\nProof.\n  intros a Ha b Hb. apply binCompatibleE; auto.\n  apply preIntMul_binCompatible.\nQed.\n\nGlobal Opaque IntMul.\n\nLemma intMul_m_n_p_q : ∀ m n p q ∈ ω,\n  [<m, n>]~ ⋅ [<p, q>]~ = ([<m⋅p + n⋅q, m⋅q + n⋅p>]~)%ω.\nProof with auto.\n  intros m Hm n Hn p Hp q Hq.\n  rewrite intMul_a_b, preIntMul_m_n_p_q...\n  apply CPrdI... apply CPrdI...\nQed.\n\nLemma intMul_0_r_r : ∀a ∈ ℤ, a ⋅ Int 0 = Int 0.\nProof with nauto.\n  intros a Ha.\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]]. subst a.\n  unfold Int. rewrite intMul_m_n_p_q...\n  repeat rewrite mul_0_r...\n  repeat rewrite add_0_r...\nQed.\n\nLemma intMul_ran : ∀ a b ∈ ℤ, a ⋅ b ∈ ℤ.\nProof with auto.\n  intros a Ha b Hb.\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]]. subst a.\n  apply pQuotE in Hb as [p [Hp [q [Hq Hb]]]]. subst b.\n  rewrite intMul_m_n_p_q...\n  apply pQuotI; apply add_ran; apply mul_ran...\nQed.\n\nExample intMul_2_n2 : Int 2 ⋅ -Int 2 = -Int 4.\nProof with nauto.\n  unfold Int. rewrite intAddInv, intAddInv...\n  rewrite intMul_m_n_p_q...\n  rewrite mul_0_l, mul_0_r, mul_0_r, add_0_r, add_0_r...\n  rewrite mul_2_2... apply mul_ran...\nQed.\n\nClose Scope Int_scope.\nOpen Scope omega_scope.\n\nTheorem intMul_comm : ∀ a b ∈ ℤ, (a ⋅ b = b ⋅ a)%z.\nProof with try assumption.\n  intros a Ha b Hb.\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]].\n  apply pQuotE in Hb as [p [Hp [q [Hq Hb]]]]. subst.\n  rewrite intMul_m_n_p_q, intMul_m_n_p_q...\n  rewrite (mul_comm p), (mul_comm n)...\n  rewrite (mul_comm m Hm q), (mul_comm n Hn p)...\n  rewrite (add_comm (q⋅m)); [|apply mul_ran; auto..]. reflexivity.\nQed.\n\nTheorem intMul_assoc : ∀ a b c ∈ ℤ, (a ⋅ b ⋅ c = a ⋅ (b ⋅ c))%z.\nProof.\n  intros a Ha b Hb c Hc.\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]].\n  apply pQuotE in Hb as [p [Hp [q [Hq Hb]]]].\n  apply pQuotE in Hc as [r [Hr [s [Hs Hc]]]]. subst.\n  repeat rewrite intMul_m_n_p_q; [|auto;amr..].\n  apply int_ident; swap 1 5; [|ar;mr;ar;mr..].\n  repeat rewrite mul_distr, mul_distr'; [|auto;mr..].\n  repeat rewrite <- mul_assoc; [|auto..].\n  cut (∀ x1 x2 x3 x4 x5 x6 x7 x8 ∈ ω,\n    x1 + x4 + (x2 + x3) + (x5 + x7 + (x8 + x6)) =\n    x1 + x2 + (x3 + x4) + (x5 + x6 + (x7 + x8))).\n  intros H. apply H; mr; mr.\n  clear Hm Hn Hp Hq Hr Hs m n p q r s.\n  intros x1 H1 x2 H2 x3 H3 x4 H4 x5 H5 x6 H6 x7 H7 x8 H8.\n  rewrite (add_assoc x1), (add_comm x4); [|auto;ar;auto..].\n  rewrite (add_assoc x2), <- (add_assoc x1); [|auto;ar;auto..].\n  rewrite (add_assoc x5), <- (add_assoc x7); [|auto;ar;auto..].\n  rewrite (add_comm (x7+x8)), (add_assoc x5); [|auto;ar;auto..].\n  reflexivity.\nQed.\n\nTheorem intMul_distr : ∀ a b c ∈ ℤ, (a ⋅ (b + c) = a ⋅ b + a ⋅ c)%z.\nProof.\n  intros a Ha b Hb c Hc.\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]].\n  apply pQuotE in Hb as [p [Hp [q [Hq Hb]]]].\n  apply pQuotE in Hc as [r [Hr [s [Hs Hc]]]]. subst.\n  rewrite intAdd_m_n_p_q; [|auto..].\n  rewrite intMul_m_n_p_q, intMul_m_n_p_q, intMul_m_n_p_q; [|auto;ar..].\n  repeat rewrite intAdd_m_n_p_q; [|amr;auto..].\n  apply int_ident; [ar;mr;ar|ar;mr;ar|\n    ar;amr|ar;amr|].\n  repeat rewrite mul_distr; [|auto..].\n  cut (∀ x1 x2 x3 x4 x5 x6 x7 x8 ∈ ω,\n    x1 + x3 + (x2 + x4) + (x5 + x7 + (x6 + x8)) =\n    x1 + x2 + (x3 + x4) + (x5 + x6 + (x7 + x8))).\n  intros H. apply H; mr; auto.\n  clear Hm Hn Hp Hq Hr Hs m n p q r s.\n  intros x1 H1 x2 H2 x3 H3 x4 H4 x5 H5 x6 H6 x7 H7 x8 H8.\n  rewrite (add_assoc x1), <- (add_assoc x3),\n    (add_comm x3), (add_assoc x2), <- (add_assoc x1);\n    swap 2 4; swap 3 15; [|ar|ar|auto..].\n  rewrite (add_assoc x5), <- (add_assoc x7),\n    (add_comm x7), (add_assoc x6), <- (add_assoc x5);\n    swap 2 4; swap 3 15; [|ar|ar|auto..].\n  reflexivity.\nQed.\n\nTheorem intMul_distr' : ∀ a b c ∈ ℤ, ((b + c) ⋅ a = b ⋅ a + c ⋅ a)%z.\nProof with auto.\n  intros a Ha b Hb c Hc.\n  rewrite (intMul_comm (b + c)%z), intMul_distr, intMul_comm,\n    (intMul_comm c)... apply intAdd_ran...\nQed.\n\nTheorem int_suc_neq_0 : ∀ n, Int (S n) ≠ Int 0.\nProof with neauto.\n  intros n H. apply int_ident in H...\n  rewrite add_0_r, add_0_r in H... eapply suc_neq_0...\nQed.\nGlobal Hint Immediate int_suc_neq_0 : number_hint.\n\nTheorem int_no_0_div : ∀ a b ∈ ℤ,\n  (a ⋅ b = Int 0)%z → a = Int 0 ∨ b = Int 0.\nProof with nauto.\n  intros a Ha b Hb Heq.\n  destruct (classic (a = Int 0)) as [|H1];\n  destruct (classic (b = Int 0)) as [|H2]... exfalso.\n  cut ((a ⋅ b)%z ≠ Int 0). intros... clear Heq.\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]].\n  apply pQuotE in Hb as [p [Hp [q [Hq Hb]]]].\n  subst a b. rewrite intMul_m_n_p_q...\n  cut (m⋅p + n⋅q ≠ m⋅q + n⋅p). intros Hnq Heq. apply Hnq.\n  apply int_ident in Heq; [|nauto;amr..]...\n  rewrite add_0_r, add_0_l in Heq; auto; amr...\n  assert (Hmn: m ≠ n). {\n    intros H. apply H1. apply int_ident...\n    rewrite add_0_r, add_0_l...\n  }\n  assert (Hpq: p ≠ q). {\n    intros H. apply H2. apply int_ident...\n    rewrite add_0_r, add_0_l...\n  }\n  clear H1 H2.\n  assert (Hw: m⋅q + n⋅p ∈ ω) by (amr; auto).\n  apply nat_connected in Hmn as [H1|H1];\n  apply nat_connected in Hpq as [H2|H2]; auto;\n  intros Heq; eapply nat_irrefl; revgoals.\n  pose proof (ex4_25 m Hm n Hn p Hp q Hq H1 H2).\n  rewrite Heq in H. apply H. auto.\n  pose proof (ex4_25 m Hm n Hn q Hq p Hp H1 H2).\n  rewrite Heq in H. apply H. auto.\n  pose proof (ex4_25 n Hn m Hm p Hp q Hq H1 H2).\n  rewrite add_comm, (add_comm (n⋅p)), Heq in H; [|mr;auto..]. apply H. auto.\n  pose proof (ex4_25 n Hn m Hm q Hq p Hp H1 H2).\n  rewrite add_comm, (add_comm (n⋅q)), Heq in H; [|mr;auto..]. apply H. auto.\nQed.\n\nClose Scope omega_scope.\nOpen Scope Int_scope.\n\nTheorem intMul_1_r : ∀a ∈ ℤ, a ⋅ Int 1 = a.\nProof with nauto.\n  intros a Ha.\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]]. subst a.\n  unfold Int. rewrite intMul_m_n_p_q...\n  rewrite mul_1_r, mul_1_r, mul_0_r, mul_0_r, add_0_r, add_0_l...\nQed.\n\nCorollary intMul_1_l : ∀a ∈ ℤ, Int 1 ⋅ a = a.\nProof with nauto.\n  intros a Ha. rewrite intMul_comm, intMul_1_r...\nQed.\n\nLemma intMul_addInv : ∀a ∈ ℤ, -Int 1 ⋅ a = -a.\nProof with nauto.\n  intros a Ha.\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]]. subst a.\n  unfold Int. rewrite intAddInv, intAddInv, intMul_m_n_p_q...\n  rewrite mul_0_l, mul_0_l, (mul_comm 1), (mul_comm 1)...\n  rewrite mul_1_r, mul_1_r, add_0_l, add_0_l...\nQed.\n\nLemma intMul_0_l : ∀a ∈ ℤ, Int 0 ⋅ a = Int 0.\nProof.\n  intros a Ha. rewrite intMul_comm, intMul_0_r_r; nauto.\nQed.\n\nLemma intMul_addInv_lr : ∀ a b ∈ ℤ, a ⋅ -b = -a ⋅ b.\nProof with auto.\n  intros a Ha b Hb.\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]]. subst a.\n  apply pQuotE in Hb as [p [Hp [q [Hq Hb]]]]. subst b.\n  rewrite intAddInv, intAddInv, intMul_m_n_p_q, intMul_m_n_p_q,\n    add_comm, (add_comm (m⋅p)%ω); auto; mr; auto.\nQed.\n\nLemma intMul_addInv_r : ∀ a b ∈ ℤ, a ⋅ -b = -(a ⋅ b).\nProof with auto.\n  intros a Ha b Hb.\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]]. subst a.\n  apply pQuotE in Hb as [p [Hp [q [Hq Hb]]]]. subst b.\n  rewrite intAddInv, intMul_m_n_p_q, intMul_m_n_p_q, intAddInv;\n    auto; amr; auto.\nQed.\n\nLemma intMul_addInv_l : ∀ a b ∈ ℤ, -a ⋅ b = -(a ⋅ b).\nProof with auto.\n  intros a Ha b Hb.\n  rewrite <- intMul_addInv_lr, intMul_addInv_r...\nQed.\n\nClose Scope Int_scope.\nOpen Scope omega_scope.\n\n(** 整数的序 **)\n\nLemma int_orderable : ∀ m n m' n' p q p' q',\n  <m, n> ~ <m', n'> → <p, q> ~ <p', q'> →\n  m + q ∈ p + n ↔ m' + q' ∈ p' + n'.\nProof.\n  intros * H1 H2.\n  apply planeEquivE2 in H1 as [H1 [Hm [Hn [Hm' Hn']]]].\n  apply planeEquivE2 in H2 as [H2 [Hp [Hq [Hp' Hq']]]].\n  assert (Hmq: m + q ∈ ω) by (ar; auto).\n  assert (Hpn: p + n ∈ ω) by (ar; auto).\n  assert (Hn'q': n' + q' ∈ ω) by (ar; auto).\n  rewrite (add_preserve_lt _ Hmq _ Hpn _ Hn'q').\n  rewrite (add_assoc m), (add_comm q), <- (add_assoc m),\n  <- (add_assoc m), (add_comm n'), (add_assoc p),\n    (add_comm n), <- (add_assoc p), <- (add_assoc p),\n    H1, H2, (add_assoc m'), (add_comm n), <- (add_assoc m'),\n    (add_assoc (m'+q')), (add_assoc p'), (add_comm q),\n    <- (add_assoc p'), (add_assoc (p'+n')), (add_comm q);\n    [|auto;ar;auto..].\n  assert (Hm'q': m' + q' ∈ ω) by (ar; auto).\n  assert (Hp'n': p' + n' ∈ ω) by (ar; auto).\n  assert (Hnq: n + q ∈ ω) by (ar; auto).\n  rewrite <- (add_preserve_lt _ Hm'q' _ Hp'n' _ Hnq).\n  reflexivity.\nQed.\n\n(* 整数的小于关系 *)\nDefinition IntLt : set := BinRel ℤ (λ a b,\n  let u := IntProj a in let v := IntProj b in\n  let m := π1 u in let n := π2 u in\n  let p := π1 v in let q := π2 v in\n  m + q ∈ p + n\n).\nNotation \"a <𝐳 b\" := (<a, b> ∈ IntLt) (at level 70).\n\nLemma intLtI : ∀ m n p q ∈ ω,\n  m + q ∈ p + n → [<m, n>]~ <𝐳 [<p, q>]~.\nProof with auto.\n  intros m Hm n Hn p Hp q Hq Hlt.\n  apply binRelI. apply pQuotI... apply pQuotI...\n  pose proof (intProj m Hm n Hn)\n    as [m' [Hm' [n' [Hn' [H11 [H12 _]]]]]].\n  pose proof (intProj p Hp q Hq)\n    as [p' [Hp' [q' [Hq' [H21 [H22 _]]]]]].\n  pose proof intEquiv_equiv as [_ [_ [Hsym _]]].\n  rewrite H11, H21. simpl. zfc_simple. eapply int_orderable.\n  apply Hsym. apply H12. apply Hsym. apply H22. apply Hlt.\nQed.\n\nLemma intLtE : ∀ a b, a <𝐳 b → ∃ m n p q ∈ ω,\n  a = [<m, n>]~ ∧ b = [<p, q>]~ ∧ m + q ∈ p + n.\nProof with auto.\n  intros a b Hlt. apply SepE in Hlt as [H1 H2].\n  apply CPrdE2 in H1 as [Ha Hb]. zfc_simple.\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]].\n  apply pQuotE in Hb as [p [Hp [q [Hq Hb]]]]. subst.\n  exists m. split... exists n. split...\n  exists p. split... exists q. split... split... split...\n  pose proof (intProj m Hm n Hn) as [r [Hr [s [Hs [H11 [H12 _]]]]]].\n  pose proof (intProj p Hp q Hq) as [u [Hu [v [Hv [H21 [H22 _]]]]]].\n  rewrite H11, H21 in H2. simpl in H2. zfc_simple.\n  eapply int_orderable; eauto.\nQed.\n\nLemma intLt : ∀ m n p q ∈ ω,\n  [<m, n>]~ <𝐳 [<p, q>]~ ↔ m + q ∈ p + n.\nProof.\n  intros m Hm n Hn p Hp q Hq. split; intros.\n  - apply SepE in H as [H1 H2].\n    apply CPrdE2 in H1 as [Ha Hb]. zfc_simple.\n    pose proof (intProj m Hm n Hn) as [r [Hr [s [Hs [H11 [H12 _]]]]]].\n    pose proof (intProj p Hp q Hq) as [u [Hu [v [Hv [H21 [H22 _]]]]]].\n    rewrite H11, H21 in H2. simpl in H2. zfc_simple.\n    eapply int_orderable; eauto.\n  - apply intLtI; auto.\nQed.\n\nLemma intNeqE : ∀ m n p q ∈ ω,\n  [<m, n>]~ ≠ [<p, q>]~ → m + q ≠ p + n.\nProof with auto.\n  intros m Hm n Hn p Hp q Hq Hnq Heq.\n  apply Hnq. apply int_ident...\nQed.\n\nLemma intLt_trans : tranr IntLt.\nProof with auto.\n  intros x y z H1 H2.\n  assert (H1' := H1). assert (H2' := H2).\n  apply intLtE in H1'\n    as [m [Hm [n [Hn [p [Hp [q [Hq [Hx [Hy _]]]]]]]]]].\n  apply intLtE in H2'\n    as [_ [_ [_ [_ [r [Hr [s [Hs [_ [Hz _]]]]]]]]]]. subst x y z.\n  apply intLt in H1... apply intLt in H2... apply intLt...\n  assert (H1': m + q + s ∈ p + n + s)\n    by (apply add_preserve_lt; auto; ar; auto).\n  assert (H2': p + s + n ∈ r + q + n)\n    by (apply add_preserve_lt; auto; ar; auto).\n  rewrite (add_assoc m), (add_comm q), <- (add_assoc m),\n    (add_assoc p), (add_comm n), <- (add_assoc p) in H1'...\n  rewrite (add_assoc r), (add_comm q), <- (add_assoc r) in H2'...\n  eapply add_preserve_lt; revgoals; swap 1 2; [apply Hq| |ar..].\n  eapply nat_trans; revgoals; eauto; ar; ar.\nQed.\n\nLemma intLt_irrefl : irrefl IntLt.\nProof with auto.\n  intros a Hlt. assert (H := Hlt). apply intLtE in H\n    as [m [Hm [n [Hn [_ [_ [_ [_ [Ha _]]]]]]]]].\n  subst a. apply intLt in Hlt...\n  eapply nat_irrefl; revgoals. apply Hlt. ar...\nQed.\n\nLemma intLt_connected : connected IntLt ℤ.\nProof with auto.\n  intros x Hx y Hy Hnq.\n  apply pQuotE in Hx as [m [Hm [n [Hn Hx]]]].\n  apply pQuotE in Hy as [p [Hp [q [Hq Hy]]]].\n  subst x y. apply intNeqE in Hnq...\n  apply nat_connected in Hnq as []; [| |ar;auto..].\n  + left. apply intLtI...\n  + right. apply intLtI...\nQed.\n\nLemma intLt_trich : trich IntLt ℤ.\nProof.\n  eapply trich_iff. apply binRel_is_binRel.\n  apply intLt_trans. split.\n  apply intLt_irrefl. apply intLt_connected.\nQed.\n\nTheorem intLt_linearOrder : linearOrder IntLt ℤ.\nProof.\n  split. apply binRel_is_binRel. split.\n  apply intLt_trans. apply intLt_trich.\nQed.\n\nClose Scope omega_scope.\nOpen Scope Int_scope.\n\nDefinition intPos : set → Prop := λ a, Int 0 <𝐳 a.\nDefinition intNeg : set → Prop := λ a, a <𝐳 Int 0.\n\nLemma int_neq_0 : ∀a ∈ ℤ, intPos a ∨ intNeg a → a ≠ Int 0.\nProof.\n  intros a Ha [Hpa|Hna]; intros H; subst;\n  eapply intLt_irrefl; eauto.\nQed.\n\nLemma intLt_addInv : ∀ a b ∈ ℤ, a <𝐳 b ↔ -b <𝐳 -a.\nProof with auto.\n  intros a Ha b Hb.\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]].\n  apply pQuotE in Hb as [p [Hp [q [Hq Hb]]]].\n  subst a b. split; intros.\n  - apply intLt in H...\n    rewrite intAddInv, intAddInv... apply intLt...\n    rewrite add_comm, (add_comm n)...\n  - rewrite intAddInv, intAddInv in H... apply intLt in H...\n    apply intLt... rewrite add_comm, (add_comm p)...\nQed.\n\nLemma intPos_neg : ∀ a, intPos a → intNeg (-a).\nProof with nauto.\n  intros. assert (Ha: a ∈ ℤ). {\n    apply SepE in H as [H _]. apply CPrdE2 in H as []...\n  }\n  apply intLt_addInv in H... rewrite intAddInv_0 in H...\nQed.\n\nLemma intNeg_pos : ∀ a, intNeg a → intPos (-a).\nProof with nauto.\n  intros. assert (Ha: a ∈ ℤ). {\n    apply SepE in H as [H _]. apply CPrdE2 in H as []...\n  }\n  apply intLt_addInv in H... rewrite intAddInv_0 in H...\nQed.\n\nClose Scope Int_scope.\nOpen Scope omega_scope.\n\nTheorem intAdd_preserve_lt : ∀ a b c ∈ ℤ,\n  a <𝐳 b ↔ (a + c <𝐳 b + c)%z.\nProof with auto.\n  intros a Ha b Hb c Hc.\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]]. subst a.\n  apply pQuotE in Hb as [p [Hp [q [Hq Hb]]]]. subst b.\n  apply pQuotE in Hc as [r [Hr [s [Hs Hc]]]]. subst c.\n  rewrite (intLt m Hm n Hn p Hp q Hq).\n  rewrite intAdd_m_n_p_q, intAdd_m_n_p_q...\n  assert (Hw1: m + r ∈ ω) by (ar; auto).\n  assert (Hw2: n + s ∈ ω) by (ar; auto).\n  assert (Hw3: p + r ∈ ω) by (ar; auto).\n  assert (Hw4: q + s ∈ ω) by (ar; auto).\n  rewrite (intLt (m+r) Hw1 (n+s) Hw2 (p+r) Hw3 (q+s) Hw4).\n  rewrite (add_assoc m), <- (add_assoc r), (add_comm r),\n    (add_assoc q), <- (add_assoc m),\n    (add_assoc p), <- (add_assoc r), (add_comm r Hr n Hn),\n    (add_assoc n), <- (add_assoc p); [|auto;ar;auto..].\n  apply add_preserve_lt; ar...\nQed.\n\nTheorem intMul_preserve_lt : ∀ a b c ∈ ℤ,\n  intPos c → a <𝐳 b ↔ (a ⋅ c <𝐳 b ⋅ c)%z.\nProof with neauto.\n  cut (∀ a b c ∈ ℤ, intPos c → a <𝐳 b → (a ⋅ c <𝐳 b ⋅ c)%z).\n  intros Hright a Ha b Hb c Hc Hpc. split; intros Hlt.\n  apply Hright... destruct (classic (a = b)).\n  subst. exfalso. eapply intLt_irrefl...\n  apply intLt_connected in H as []... exfalso.\n  eapply (Hright b Hb a Ha c Hc Hpc) in H.\n  eapply intLt_irrefl. eapply intLt_trans...\n  intros a Ha b Hb c Hc Hpc Hlt.\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]]. subst a.\n  apply pQuotE in Hb as [p [Hp [q [Hq Hb]]]]. subst b.\n  apply pQuotE in Hc as [r [Hr [s [Hs Hc]]]]. subst c.\n  apply intLt in Hpc... rewrite add_0_r, add_0_l in Hpc...\n  rewrite (intLt m Hm n Hn p Hp q Hq) in Hlt.\n  rewrite (intMul_m_n_p_q m Hm n Hn r Hr s Hs).\n  rewrite (intMul_m_n_p_q p Hp q Hq r Hr s Hs).\n  assert (Hw1: m ⋅ r + n ⋅ s ∈ ω) by (amr; auto).\n  assert (Hw2: m ⋅ s + n ⋅ r ∈ ω) by (amr; auto).\n  assert (Hw3: p ⋅ r + q ⋅ s ∈ ω) by (amr; auto).\n  assert (Hw4: p ⋅ s + q ⋅ r ∈ ω) by (amr; auto).\n  rewrite (intLt (m⋅r + n⋅s) Hw1 (m⋅s + n⋅r) Hw2\n    (p⋅r + q⋅s) Hw3 (p⋅s + q⋅r) Hw4).\n  rewrite (add_comm (p⋅s)), (add_assoc (m⋅r)),\n    <- (add_assoc (n⋅s)), (add_comm (n⋅s)),\n    (add_assoc (q⋅r)), <- (add_assoc (m⋅r));\n    swap 2 4; swap 3 15; [|amr|amr|mr..]...\n  rewrite (add_comm (m⋅s)), (add_assoc (p⋅r)),\n    <- (add_assoc (q⋅s)), (add_comm (q⋅s)),\n    (add_assoc (n⋅r)), <- (add_assoc (p⋅r));\n    swap 2 4; swap 3 15; [|amr|amr|mr..]...\n  rewrite (mul_comm m), (mul_comm q), (mul_comm n), (mul_comm p),\n    (mul_comm p), (mul_comm n), (mul_comm q), (mul_comm m)...\n  repeat rewrite <- mul_distr...\n  rewrite (add_comm n), (add_comm q)...\n  apply ex4_25; auto; ar...\nQed.\n\nClose Scope omega_scope.\nOpen Scope Int_scope.\n\nCorollary intAdd_preserve_lt_trans : ∀ a b c d ∈ ℤ,\n  a <𝐳 b → c <𝐳 d → a + c <𝐳 b + d.\nProof with auto.\n  intros a Ha b Hb c Hc d Hd H1 H2.\n  apply (intAdd_preserve_lt a Ha b Hb c Hc) in H1.\n  apply (intAdd_preserve_lt c Hc d Hd b Hb) in H2.\n  rewrite (intAdd_comm c), (intAdd_comm d) in H2...\n  eapply intLt_trans; eauto.\nQed.\n\nCorollary intAdd_cancel : ∀ a b c ∈ ℤ, a + c = b + c → a = b.\nProof with eauto.\n  intros a Ha b Hb c Hc Heq.\n  contra.\n  apply intLt_connected in H as []; auto;\n  eapply intAdd_preserve_lt in H; eauto;\n  rewrite Heq in H; eapply intLt_irrefl...\nQed.\n\nCorollary intAdd_cancel' : ∀ a b c ∈ ℤ, c + a = c + b → a = b.\nProof with eauto.\n  intros a Ha b Hb c Hc Heq.\n  eapply intAdd_cancel...\n  rewrite intAdd_comm, (intAdd_comm b)...\nQed.\n\nCorollary intMul_cancel : ∀ a b c ∈ ℤ,\n  c ≠ Int 0 → a ⋅ c = b ⋅ c → a = b.\nProof with neauto.\n  intros a Ha b Hb c Hc Hnq0 Heq.\n  contra.\n  apply intLt_connected in Hnq0 as [Hneg|Hpos]...\n  - apply intNeg_pos in Hneg as Hpos.\n    assert (Heq': a ⋅ -c = b ⋅ -c). {\n      repeat rewrite intMul_addInv_r... congruence.\n    }\n    assert (Hnc: -c ∈ ℤ) by (apply intAddInv_ran; auto).\n    apply intLt_connected in H as [H|H]; [|auto..];\n      eapply intMul_preserve_lt in H; swap 1 5; swap 2 10;\n        [apply Hpos|apply Hpos|auto..];\n      rewrite Heq' in H;\n      eapply intLt_irrefl; [apply H|apply H]...\n  - apply intLt_connected in H as [H|H]; [|auto..];\n      eapply intMul_preserve_lt in H; swap 1 5; swap 2 10;\n        [apply Hpos|apply Hpos|auto..];\n      rewrite Heq in H;\n      eapply intLt_irrefl; [apply H|apply H]...\nQed.\n\nNotation \"a ≤ b\" := (a <𝐳 b ∨ a = b) (at level 70) : Int_scope.\n\nCorollary intAdd_preserve_le : ∀ a b c ∈ ℤ,\n  a ≤ b ↔ a + c ≤ b + c.\nProof with eauto.\n  intros a Ha b Hb c Hc. split; intros [].\n  - left. apply intAdd_preserve_lt...\n  - right. congruence.\n  - left. apply intAdd_preserve_lt in H...\n  - right. apply intAdd_cancel in H...\nQed.\n\nCorollary intMul_preserve_le : ∀ a b c ∈ ℤ,\n  intPos c → a ≤ b ↔ a ⋅ c ≤ b ⋅ c.\nProof with neauto.\n  intros a Ha b Hb c Hc Hpc. split; intros [].\n  - left. apply intMul_preserve_lt...\n  - right. congruence.\n  - left. apply intMul_preserve_lt in H...\n  - right. apply intMul_cancel in H...\n    destruct (classic (c = Int 0))... apply int_neq_0...\nQed.\n\nLemma intLt_iff_le_suc : ∀a b ∈ ℤ, a <𝐳 b ↔ a + Int 1 ≤ b.\nProof with neauto.\n  intros a Ha b Hb.\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]]. subst a.\n  apply pQuotE in Hb as [p [Hp [q [Hq Hb]]]]. subst b.\n  unfold Int. rewrite intAdd_m_n_p_q, add_0_r...\n  assert (Heq: (m + q)%ω⁺ = (m + 1 + q)%ω). {\n    rewrite suc, add_assoc, (add_comm q),\n      <- add_assoc; nauto; ar...\n  } split; intros.\n  - apply intLt in H...\n    destruct (classic (m + 1 + q = p + n)%ω).\n    + right. apply int_ident; auto; ar...\n    + left. apply intLt; auto; [ar|]...\n      apply nat_connected in H0 as []; [| |ar;ar|ar]...\n      exfalso. eapply (ω_not_dense (m + q)%ω); [ar|]...\n      exists (p + n)%ω. split. ar... split... rewrite Heq...\n  - apply intLt... destruct H.\n    + apply intLt in H; auto; [|ar]... rewrite <- Heq in H.\n      eapply nat_trans; revgoals... ar...\n    + apply int_ident in H; auto; [|ar]...\n      assert ((m + q)%ω ∈ (m + q)%ω⁺) by nauto. congruence.\nQed.\n\nLemma intNonNeg_iff : ∀a ∈ ℤ, ¬intNeg a ↔ Int 0 ≤ a.\nProof with neauto.\n  intros a Ha. split; intros H.\n  - destruct (classic (Int 0 = a))...\n    apply intLt_connected in H0 as []... exfalso...\n  - intros Hneg. destruct H; eapply intLt_irrefl.\n    eapply intLt_trans... subst...\nQed.\n\nLemma intNonNeg_ex_nat : ∀a ∈ ℤ, ¬intNeg a → ∃ n, a = Int n.\nProof with nauto.\n  intros a Ha Hnn.\n  apply intNonNeg_iff in Hnn as [Hlt|H0]; [|exists 0|]...\n  apply pQuotE in Ha as [m [Hm [n [Hn Ha]]]]. subst a.\n  apply intLt in Hlt... rewrite add_0_r, add_0_l in Hlt...\n  apply nat_subtr' in Hlt as [d [Hd [Heq _]]]...\n  exists d. apply int_ident...\n  rewrite add_0_r, add_comm, (embed_proj_id d)...\nQed.\n\n(** 自然数嵌入 **)\nDefinition ω_Embed := Func ω ℤ (λ n, [<n, 0>]~).\n\nTheorem ω_embed_function : ω_Embed: ω ⇒ ℤ.\nProof.\n  apply meta_function.\n  intros x Hx. apply pQuotI; nauto.\nQed.\n\nCorollary ω_embed_ran : ∀n ∈ ω, ω_Embed[n] ∈ ℤ.\nProof with auto.\n  pose proof ω_embed_function as [Hf [Hd Hr]].\n  intros n Hn. apply Hr. eapply ranI.\n  apply func_correct... rewrite Hd...\nQed. \n\nTheorem ω_embed_injective : injective ω_Embed.\nProof with nauto.\n  apply meta_injection. intros x Hx. apply pQuotI...\n  intros x1 Hx1 x2 Hx2 Heq. apply int_ident in Heq...\n  rewrite add_0_r, add_0_r in Heq...\nQed.\n\nLemma ω_embed_n : ∀n ∈ ω, ω_Embed[n] = [<n, 0>]~.\nProof with nauto.\n  intros n Hn. unfold ω_Embed. rewrite meta_func_ap...\n  apply ω_embed_function.\nQed.\n\nTheorem ω_embed : ∀ n : nat, ω_Embed[n] = Int n.\nProof. intros. rewrite ω_embed_n; nauto. Qed.\n\nTheorem ω_embed_add : ∀ m n ∈ ω,\n  ω_Embed[(m + n)%ω] = ω_Embed[m] + ω_Embed[n].\nProof with nauto.\n  intros m Hm n Hn.\n  repeat rewrite ω_embed_n; [|auto;ar;auto..].\n  rewrite intAdd_m_n_p_q, add_0_r...\nQed.\n\nTheorem ω_embed_mul : ∀ m n ∈ ω,\n  ω_Embed[(m ⋅ n)%ω] = ω_Embed[m] ⋅ ω_Embed[n].\nProof with nauto.\n  intros m Hm n Hn.\n  repeat rewrite ω_embed_n; [|auto;mr;auto..].\n  rewrite intMul_m_n_p_q, mul_0_r, mul_0_r,\n    mul_0_l, add_0_r, add_0_r... apply mul_ran...\nQed.\n\nTheorem ω_embed_lt : ∀ m n ∈ ω,\n  m ∈ n ↔ ω_Embed[m] <𝐳 ω_Embed[n].\nProof with auto.\n  intros m Hm n Hn.\n  repeat rewrite ω_embed_n...\n  pose proof ω_has_0 as H0.\n  rewrite (intLt m Hm 0 H0 n Hn 0 H0).\n  rewrite add_0_r, add_0_r... reflexivity.\nQed.\n\nTheorem ω_embed_subtr : ∀ m n ∈ ω,\n  [<m, n>]~ = ω_Embed[m] - ω_Embed[n].\nProof with nauto.\n  intros m Hm n Hn.\n  repeat rewrite ω_embed_n...\n  rewrite intAddInv, intAdd_m_n_p_q, add_0_r, add_0_l...\nQed.\n", "meta": {"author": "choukh", "repo": "Set-Theory", "sha": "5677d0d9cc3814adfb9bc1286a826f9d620fcc2e", "save_path": "github-repos/coq/choukh-Set-Theory", "path": "github-repos/coq/choukh-Set-Theory/Set-Theory-5677d0d9cc3814adfb9bc1286a826f9d620fcc2e/Elements/EST5_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.666791500577253}}
{"text": "(**********************************************************************************\n *\n * Model.v\n *\n * A Small Coq model\n *\n * Developed by Kenneth Roe\n * For more information, check out www.cs.jhu.edu/~roe\n *\n **********************************************************************************)\n\nRequire Export SfLib.\nRequire Export SfLibExtras.\n\nInductive Exp :=\n  | Var : nat -> Exp\n  | Const : nat -> Exp\n  | Plus : Exp -> Exp -> Exp\n  | Times : Exp -> Exp -> Exp\n  (*| Ref : Exp -> Exp*)\n  | Find : Exp -> Exp\n  | Ite : Exp -> Exp -> Exp -> Exp.\n\nFixpoint findit a l :=\n    match l with\n    | nil => 0 \n    | (f::r) => if beq_nat a f then (S 0) else match findit a r with\n                                               | 0 => 0\n                                               | (S n) => S (S n)\n                                               end\n    end. \n         \nFixpoint eval e l := \n         match e with\n         | Const v => v \n         | Var n => nth n l 0\n         | Plus a b => (eval a l)+(eval b l)\n         | Times a b => (eval a l)+(eval b l)\n         (*| Ref a => nth (eval a l) l 0*)\n         | Find a => findit (eval a l) l\n         | Ite a b c => match (eval a l) with\n                        | 0 => eval c l\n                        | S _ => eval b l\n                        end\n         end.\n\nFixpoint pop e v :=\n         match e with\n         | Const v => Const v\n         | Var 0 => Const v\n         | Var (S n) => Var n\n         | Plus a b => Plus (pop a v) (pop b v)\n         | Times a b => Times (pop a v) (pop b v)\n         (*| Ref a => Ref (pop a v)*)\n         | Find e => Find (pop e v)\n         | Ite a b c => Ite (pop a v) (pop b v) (pop c v)\n         end.\n\nFixpoint noFind e :=\n    match e with\n    | Const _ => true\n    | Var _ => true\n    | Plus a b => if noFind a then noFind b else false\n    | Times a b => if noFind a then noFind b else false\n    (*| Ref e => noFind e*)\n    | Find e => false\n    | Ite a b c => if noFind a then (if noFind b then noFind c else false) else false\n    end.\n\n(*Fixpoint noRef e :=\n    match e with\n    | Const _ => true\n    | Var _ => true\n    | Plus a b => if noRef a then noRef b else false\n    | Times a b => if noRef a then noRef b else false\n    | Ref e => false\n    | Find e => noRef e\n    | Ite a b c => if noRef a then (if noRef b then noRef c else false) else false\n    end.*)\n\nTheorem popEquiv : forall e v l, (* noRef e=true -> *) noFind e=true -> eval e (v::l)=eval (pop e v) l.\nProof.\n    intro e.\n    induction e.\n\n    simpl. unfold eval. destruct n. reflexivity. reflexivity.\n\n    unfold pop. unfold eval. reflexivity.\n\n    intros. unfold noFind in H. fold noFind in H.  remember (noFind e1). destruct b.\n\n    unfold pop. fold pop. unfold eval. fold eval.\n\n    rewrite IHe1. rewrite IHe2.\n    reflexivity. apply H. reflexivity. inversion H.\n\n\n    intros. unfold noFind in H. fold noFind in H.  remember (noFind e1). destruct b.\n\n    unfold pop. fold pop. unfold eval. fold eval.\n\n    rewrite IHe1. rewrite IHe2.\n    reflexivity. apply H. reflexivity. inversion H.\n\n    intros. unfold noFind in H. inversion H.\n\n    intros. unfold noFind in H. fold noFind in H. remember (noFind e1). destruct b.\n    destruct (noFind e2).\n\n    unfold pop. fold pop. unfold eval. fold eval.\n\n    rewrite IHe1. rewrite IHe2. rewrite IHe3. reflexivity.\n\n    apply H. reflexivity. reflexivity. inversion H. inversion H.\nQed.\n\nInductive Pr :=\n          | Atom : Exp -> Pr\n          | And : Pr -> Pr -> Pr\n          | Or : Pr -> Pr -> Pr\n          | Implies : Pr -> Pr -> Pr.\n\nFixpoint valid p l :=\n    match p with\n    | Atom e => if beq_nat (eval e l) 0 then false else true\n    | And a b => if valid a l then valid b l else false\n    | Or a b => if valid a l then true else valid b l\n    | Implies a b => if valid a l then valid b l else true\n    end.\n\nTheorem validTransitive : forall a b c, (a -> b) -> (b -> c) -> (a ->c).\nProof.\n    intros.\n\n    apply X0. apply X. apply X1.\nQed.\n\nTheorem and1imply : forall a b l, (valid (And a b) l)=true -> valid a l=true.\nProof.\n    intros.\n\n    unfold valid in H. fold valid in H.\n\n    destruct (valid a l). reflexivity. inversion H.\nQed.\n\nTheorem and2imply : forall a b l, (valid (And a b) l)=true -> valid b l=true.\nProof.\n    intros. unfold valid in H. fold valid in H.\n\n    destruct (valid a l). apply H. inversion H.\nQed.\n\nInductive pickElement : Pr -> Pr -> Pr -> Prop :=\n    | Left : forall a b l r, pickElement a l r -> pickElement (And a b) (And l b) r\n    | Right : forall a b l r, pickElement b l r -> pickElement (And a b) (And a l) r\n    | Pick : forall a b, a=b -> pickElement a (Atom (Const 1)) a.\n\nTheorem mergeStep : forall X XX Y YY l e1 e2 Q,\n    pickElement X XX e1 ->\n    pickElement Y YY e2 ->\n    e1=e2 ->\n    (valid XX l=true \\/ valid YY l=true -> valid Q l=true) ->\n    (valid X l=true \\/ valid Y l=true -> valid (And e2 Q) l=true).\nProof.\n    admit.\nQed.\n\nTheorem mergeFinish: forall l, valid (Atom (Const 1)) l=true.\nProof.\n    admit.\nQed.\n\nTheorem mergePredicates: forall e a b c d l,\n    e = b ->\n    valid (And a (And e c)) l=true \\/\n    valid (And b d) l=true ->\n    valid b l=true.\nProof.\n    intros e a b c d l.\n    eapply validTransitive.\n    eapply mergeStep.\n        eapply Right. eapply Left. eapply Pick. reflexivity.\n        eapply Left. eapply Pick. reflexivity. apply H.\n    intros. eapply mergeFinish.\n\n    intros. eapply and1imply. apply H0.\nQed.\n\n\n", "meta": {"author": "kendroe", "repo": "CoqPIE", "sha": "946009445e532dd4632a11a58a64f72a1dd28304", "save_path": "github-repos/coq/kendroe-CoqPIE", "path": "github-repos/coq/kendroe-CoqPIE/CoqPIE-946009445e532dd4632a11a58a64f72a1dd28304/Small/Model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6667914992003203}}
{"text": "Inductive tree (a:Type) : Type :=\n| leaf : a -> tree a\n| node : tree a -> tree a -> tree a\n.\n\nArguments leaf {a} _.\nArguments node {a} _ _.\n\n(*\nCheck tree_ind.\n*)\n\n(* This is not exactly what 'Check tree_ind' returns but equivalent to it *)\nDefinition tree_ind_principle : Prop := forall (a:Type), \n    forall (P:tree a -> Prop),\n    (forall (x:a), P (leaf x))  ->\n    (forall (t1 t2:tree a), P t1 -> P t2 -> P (node t1 t2)) ->\n    forall (t:tree a), P t.\n\n(* building some proof manually of equivalent statement *)\nFixpoint tree_ind_ (a:Type)(t:tree a) : forall (P:tree a -> Prop),\n    (forall (x:a), P (leaf x))                                  ->\n    (forall (t1 t2:tree a), P t1 -> P t2 -> P (node t1 t2))     -> P t :=\n    fun (P:tree a -> Prop)                                                  =>\n        fun (H0:forall (x:a), P (leaf x))                                   =>\n            fun (H1:forall (t1 t2:tree a), P t1 -> P t2 -> P (node t1 t2))  =>\n                match t with\n                | leaf x        => H0 x\n                | node t1 t2    => \n                    H1 t1 t2\n                        (tree_ind_ a t1 P H0 H1)\n                        (tree_ind_ a t2 P H0 H1)\n                end.\n\n(* so we now have a proof of our induction principle *)\nDefinition tree_ind' : tree_ind_principle := \n    fun a P H0 H1 t => tree_ind_ a t P H0 H1.\n\n\n(* one constructor takes argument which is a function returning foo a b *)\nInductive foo (a b:Type) : Type :=\n| bar  : a -> foo a b\n| baz  : b -> foo a b\n| quux : (nat -> foo a b) -> foo a b\n.\n\nArguments bar {a} {b} _.\nArguments baz {a} {b} _.\nArguments quux {a} {b} _.\n\n(*\nCheck foo_ind.\n*)\n\nDefinition foo_ind_principle : Prop := forall (a b:Type),\n    forall (P:foo a b -> Prop),\n    (forall (x:a), P (bar x))                                       ->\n    (forall (y:b), P (baz y))                                       ->\n    (forall (f:nat -> foo a b), (forall n, P (f n)) -> P (quux f))  ->\n    forall (z:foo a b), P z.\n\n\n(* we could drop some requirement, but less likely to be useful *)\n(* same conclusion, but with stronger hypothesis                *)\nDefinition foo_ind_principle_weak : Prop := forall (a b:Type),\n    forall (P:foo a b -> Prop),\n    (forall (x:a), P (bar x))                                       ->\n    (forall (y:b), P (baz y))                                       ->\n    (forall (f:nat -> foo a b), P (quux f)) (* harder to prove *)   ->\n    forall (z:foo a b), P z.\n\nLemma weak_is_weaker : foo_ind_principle -> foo_ind_principle_weak.\nProof.\n    unfold foo_ind_principle_weak. intros H a b P H0 H1 H2 z. apply H.\n    - exact H0.\n    - exact H1.\n    - intros f H'. apply H2.\nQed.\n\n\n\n(* building some proof manually of equivalent statement *)\n(* Why does this terminate ? *)\nFixpoint foo_ind_ (a b:Type) (z:foo a b) : forall (P:foo a b -> Prop),\n    (forall (x:a), P (bar x))                                       ->\n    (forall (y:b), P (baz y))                                       ->\n    (forall (f:nat -> foo a b), (forall n, P (f n)) -> P (quux f))  -> P z :=\n    fun (P:foo a b -> Prop)                                         =>\n        fun (H0:forall (x:a), P (bar x))                            =>\n            fun (H1:forall (y:b), P (baz y))                        =>\n                fun (H2: forall (f:nat -> foo a b),\n                        (forall n, P (f n)) -> P (quux f))          =>\n                            match z with\n                            | bar x     => H0 x\n                            | baz y     => H1 y\n                            | quux f    => H2 f \n                                (fun n => foo_ind_ a b (f n) P H0 H1 H2)   \n                            end.\n\nDefinition foo_ind' (a b:Type) : forall (P:foo a b -> Prop),\n    (forall (x:a), P (bar x))                                       ->\n    (forall (y:b), P (baz y))                                       ->\n    (forall (f:nat -> foo a b), (forall n, P (f n)) -> P (quux f))  ->\n    forall (z:foo a b), P z :=\n    fun P H0 H1 H2 z => foo_ind_ a b z P H0 H1 H2.\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/sf/polymorphism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6667914978233875}}
{"text": "(** * Adjunctions by units and counits *)\nRequire Import Category.Core Functor.Core NaturalTransformation.Core.\nRequire Import Category.Dual Functor.Dual NaturalTransformation.Dual.\nRequire Import Functor.Composition.Core Functor.Identity.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope category_scope.\nLocal Open Scope morphism_scope.\n\nSection Adjunction.\n  (** ** Unit + UMP definition of adjunction *)\n  (** Quoting from Awodey's \"Category Theory\":\n\n      An adjunction between categories [C] and [D] consists of\n      functors\n\n      [F : C <-> D : G]\n\n      and a natural transformation\n\n      [T : 1_C -> G ∘ F]\n\n      with the property:\n\n      (o) For any [c : C], [d : D], and [f : c -> G d], there exists a\n          unique [g : F c -> d] such that [f = (G g) ∘ (T c)] as\n          indicated in\n\n<<\n                g\n     F c ..................> d\n\n                 G g\n     G (F c) --------------> G d\n       ^                    _\n       |                    /|\n       |                  /\n       |                /\n       |              /\n       | T c        /\n       |          /  f\n       |        /\n       |      /\n       |    /\n       |  /\n        c\n>>\n\n     Terminology and notation:\n\n     - [F] is called the left adjoint, [G] is called the right\n       adjoint, and [T] is called the unit of the adjunction.\n\n     - One sometimes writes [F -| G] for ``[F] is left and [G] right\n       adjoint.''\n\n     - The statement (o) is the UMP of the unit [T].\n\n     Note that the situation [F ⊣ G] is a generalization of\n     equivalence of categories, in that a pseudo-inverse is an\n     adjoint. In that case, however, it is the relation between\n     categories that one is interested in. Here, one is concerned with\n     the relation between special functors. That is to say, it is not\n     the relation on categories ``there exists an adjunction,'' but\n     rather ``this functor has an adjoint'' that we are concerned\n     with. *)\n\n  Section unit.\n    Variables C D : PreCategory.\n    Variable F : Functor C D.\n    Variable G : Functor D C.\n\n    Definition AdjunctionUnit :=\n      { T : NaturalTransformation 1 (G o F)\n      | forall (c : C) (d : D) (f : morphism C c (G d)),\n          Contr { g : morphism D (F c) d | G _1 g o T c = f }\n      }.\n  End unit.\n\n  (** ** Counit + UMP definition of adjunction *)\n  (**\n     Paraphrasing and quoting from Awody's \"Category Theory\":\n\n     An adjunction between categories [C] and [D] consists of functors\n\n     [F : C <-> D : G]\n\n     and a natural transformation\n\n     [U : F ∘ G -> 1_D]\n\n     with the property:\n\n     (o) For any [c : C], [d : D], and [g : F c -> d], there exists a\n         unique [f : c -> G d] such that [g = (U d) ∘ (F f)] as\n         indicated in the diagram\n\n<<\n                f\n     c ..................> G d\n\n               F f\n     F c --------------> F (G d)\n      \\                    |\n        \\                  |\n          \\                |\n            \\              |\n              \\            | U d\n             g  \\          |\n                  \\        |\n                    \\      |\n                      \\    |\n                       _\\| V\n                          d\n>>\n\n    Terminology and notation:\n\n    - The statement (o) is the UMP of the counit [U].\n    *)\n  Section counit.\n    Variables C D : PreCategory.\n    Variable F : Functor C D.\n    Variable G : Functor D C.\n\n    Definition AdjunctionCounit :=\n      { U : NaturalTransformation (F o G) 1\n      | forall (c : C) (d : D) (g : morphism D (F c) d),\n          Contr { f : morphism C c (G d) | U d o F _1 f = g }\n      }.\n  End counit.\n\n  (** The counit is just the dual of the unit.  We formalize this here\n      so that we can use it to make coercions easier. *)\n\n  Section unit_counit_op.\n    Variables C D : PreCategory.\n    Variable F : Functor C D.\n    Variable G : Functor D C.\n\n    Definition adjunction_counit__op__adjunction_unit (A : AdjunctionUnit G^op F^op)\n    : AdjunctionCounit F G\n      := exist\n           (fun U : NaturalTransformation (F o G) 1 =>\n              forall (c : C) (d : D) (g : morphism D (F c) d),\n                Contr {f : morphism C c (G d)\n                      | U d o F _1 f = g })\n           (A.1^op)%natural_transformation\n           (fun c d g => A.2 d c g).\n\n    Definition adjunction_counit__op__adjunction_unit__inv (A : AdjunctionUnit G F)\n    : AdjunctionCounit F^op G^op\n      := exist\n           (fun U : NaturalTransformation (F^op o G^op) 1\n            => forall (c : C^op) (d : D^op) (g : morphism D^op ((F^op)%functor c) d),\n                 Contr {f : morphism C^op c ((G^op)%functor d)\n                       | U d o F^op _1 f = g })\n           (A.1^op)%natural_transformation\n           (fun c d g => A.2 d c g).\n\n    Definition adjunction_unit__op__adjunction_counit (A : AdjunctionCounit G^op F^op)\n    : AdjunctionUnit F G\n      := exist\n           (fun T : NaturalTransformation 1 (G o F) =>\n              forall (c : C) (d : D) (f : morphism C c (G d)),\n                Contr { g : morphism D (F c) d\n                      | G _1 g o T c = f })\n           (A.1^op)%natural_transformation\n           (fun c d g => A.2 d c g).\n\n    Definition adjunction_unit__op__adjunction_counit__inv (A : AdjunctionCounit G F)\n    : AdjunctionUnit F^op G^op\n      := exist\n           (fun T : NaturalTransformation 1 (G^op o F^op)\n            => forall (c : C^op) (d : D^op) (f : morphism C^op c ((G^op)%functor d)),\n                 Contr {g : morphism D^op ((F^op)%functor c) d\n                       | G^op _1 g o T c = f })\n           (A.1^op)%natural_transformation\n           (fun c d g => A.2 d c g).\n  End unit_counit_op.\n\n  (** ** Unit + Counit + Zig + Zag definition of adjunction *)\n  (** Quoting Wikipedia on Adjoint Functors:\n\n      A counit-unit adjunction between two categories [C] and [D]\n      consists of two functors [F : C ← D] and [G : C → D] and two\n      natural transformations\n\n<<\n      ε : FG → 1_C\n      η : 1_D → GF\n>>\n\n      respectively called the counit and the unit of the adjunction\n      (terminology from universal algebra), such that the compositions\n\n<<\n          F η            ε F\n      F -------> F G F -------> F\n\n          η G            G ε\n      G -------> G F G -------> G\n>>\n\n      are the identity transformations [1_F] and [1_G] on [F] and [G]\n      respectively.\n\n      In this situation we say that ``[F] is left adjoint to [G]'' and\n      ''[G] is right adjoint to [F]'', and may indicate this\n      relationship by writing [(ε, η) : F ⊣ G], or simply [F ⊣ G].\n\n      In equation form, the above conditions on (ε, η) are the\n      counit-unit equations\n\n<<\n      1_F = ε F ∘ F η\n      1_G = G ε ∘ η G\n>>\n\n      which mean that for each [X] in [C] and each [Y] in [D],\n\n<<\n      1_{FY} = ε_{FY} ∘ F(η_Y)\n      1_{GX} = G(ε_X) ∘ η_{GX}\n>>\n\n      These equations are useful in reducing proofs about adjoint\n      functors to algebraic manipulations.  They are sometimes called\n      the ``zig-zag equations'' because of the appearance of the\n      corresponding string diagrams.  A way to remember them is to\n      first write down the nonsensical equation [1 = ε ∘ η] and then\n      fill in either [F] or [G] in one of the two simple ways which\n      make the compositions defined.\n\n      Note: The use of the prefix ``co'' in counit here is not\n      consistent with the terminology of limits and colimits, because\n      a colimit satisfies an initial property whereas the counit\n      morphisms will satisfy terminal properties, and dually.  The\n      term unit here is borrowed from the theory of monads where it\n      looks like the insertion of the identity 1 into a monoid.  *)\n\n  Section unit_counit.\n    Variables C D : PreCategory.\n    Variable F : Functor C D.\n    Variable G : Functor D C.\n\n    (*Local Reserved Notation \"'ε'\".\n    Local Reserved Notation \"'η'\".*)\n\n    (** Use the per-object version of the equations, so that we don't\n        need the associator in the middle.  Also, explicitly simplify\n        some of the types so that [rewrite] works better. *)\n    Record AdjunctionUnitCounit :=\n      {\n        unit : NaturalTransformation (identity C) (G o F)\n        (*where \"'η'\" := unit*);\n        counit : NaturalTransformation (F o G) (identity D)\n        (*where \"'ε'\" := counit*);\n        unit_counit_equation_1\n        : forall Y : C, (*ε (F Y) ∘ F ₁ (η Y) = identity (F Y);*)\n            Category.Core.compose (C := D) (s := F Y) (d := F (G (F Y))) (d' := F Y)\n                                  (counit (F Y))\n                                  (F _1 (unit Y : morphism _ Y (G (F Y))))\n            = 1;\n        unit_counit_equation_2\n        : forall X : D, (* G ₁ (ε X) ∘ η (G X) = identity (G X) *)\n            Category.Core.compose (C := C) (s := G X) (d := G (F (G X))) (d' := G X)\n                                  (G _1 (counit X : morphism _ (F (G X)) X))\n                                  (unit (G X))\n            = 1\n      }.\n  End unit_counit.\nEnd Adjunction.\n\nDeclare Scope adjunction_scope.\nDelimit Scope adjunction_scope with adjunction.\n\nBind Scope adjunction_scope with AdjunctionUnit.\nBind Scope adjunction_scope with AdjunctionCounit.\nBind Scope adjunction_scope with AdjunctionUnitCounit.\n\nArguments unit [C D]%category [F G]%functor _%adjunction / .\nArguments counit [C D]%category [F G]%functor _%adjunction / .\nArguments AdjunctionUnitCounit [C D]%category (F G)%functor.\nArguments unit_counit_equation_1 [C D]%category [F G]%functor _%adjunction _%object.\nArguments unit_counit_equation_2 [C D]%category [F G]%functor _%adjunction _%object.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Categories/Adjoint/UnitCounit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.666791491939419}}
{"text": "From Equations Require Import Equations.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Lists.List.\n\nRequire Import MirrorSolve.FirstOrder.\nRequire Import MirrorSolve.HLists.\n\nImport ListNotations.\nImport HListNotations.\n\nRequire Import Coq.ZArith.BinInt.\nSet Universe Polymorphism.\n\nSection NFOL.\n  Inductive sorts: Set :=\n  | NS\n  | BS.\n\n  Scheme Equality for sorts.\n\n  Inductive funs: arity sorts -> sorts -> Type :=\n  | NLit: forall (n: nat), funs [] NS\n  | BLit: forall (b: bool), funs [] BS\n  (* | Sub: funs [NS; NS] NS *)\n  | Plus: funs [NS; NS] NS\n  | Mul: funs [NS; NS] NS\n  | Div: funs [NS; NS] NS\n  | Mod: funs [NS; NS] NS\n  | Lte: funs [NS; NS] BS\n  | Lt: funs [NS; NS] BS\n  | Gte: funs [NS; NS] BS\n  | Gt: funs [NS; NS] BS.\n\n  Inductive rels: arity sorts -> Type :=.\n\n  Definition sig: signature :=\n    {| sig_sorts := sorts;\n      sig_funs := funs;\n      sig_rels := rels |}.\n\n  Definition fm ctx := FirstOrder.fm sig ctx.\n  Definition tm ctx := FirstOrder.tm sig ctx.\n\n  Definition mod_sorts (s: sig_sorts sig) : Type :=\n    match s with\n    | NS => nat\n    | BS => bool\n    end.\n\n  Obligation Tactic := idtac.\n  Equations \n    mod_fns params ret (f: sig_funs sig params ret) (args: HList.t mod_sorts params) \n    : mod_sorts ret :=\n    { mod_fns _ _ (BLit b) _ := b;\n      mod_fns _ _ (NLit n) _ := n;\n      (* mod_fns _ _ Sub (l ::: r ::: _) := Nat.sub l r; *)\n      mod_fns _ _ Plus (l ::: r ::: _) := Nat.add l r;\n      mod_fns _ _ Mul (l ::: r ::: _) := Nat.mul l r;\n      mod_fns _ _ Div (l ::: r ::: _) := Nat.div l r;\n      mod_fns _ _ Mod (l ::: r ::: _) := Nat.modulo l r;\n      mod_fns _ _ Lte (l ::: r ::: _) := Nat.leb l r;\n      mod_fns _ _ Lt (l ::: r ::: _) := Nat.ltb l r;\n      mod_fns _ _ Gte (l ::: r ::: _) := Nat.leb r l;\n      mod_fns _ _ Gt (l ::: r ::: _) := Nat.ltb l r;\n    }.\n\n  Definition mod_rels params\n    (args: sig_rels sig params)\n    (env: HList.t mod_sorts params) : Prop :=\n    match args with\n    end.\n\n  Definition fm_model : model sig := {|\n    FirstOrder.mod_sorts := mod_sorts;\n    FirstOrder.mod_fns := mod_fns;\n    FirstOrder.mod_rels := mod_rels;\n  |}.\n\nEnd NFOL.", "meta": {"author": "jsarracino", "repo": "mirrorsolve", "sha": "74fc7790b21952d4f27ea70545b0038f298915b0", "save_path": "github-repos/coq/jsarracino-mirrorsolve", "path": "github-repos/coq/jsarracino-mirrorsolve/mirrorsolve-74fc7790b21952d4f27ea70545b0038f298915b0/src/theories/N.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6667914876205019}}
{"text": "(**\n日本ソフトウェア科学会\nチュートリアル(1) 定理証明支援系Coq入門\n\n講師：アフェルト レナルド 先生\nhttps://staff.aist.go.jp/reynald.affeldt/ssrcoq/coq-jssst2014.pdf\n *)\n\n(**\n首記の講演から興味のもとに抜粋し、例題を追加したものです。\n内容の責任は  @suharahiromichi にあります。\n *)\n\n(**\neqtype.v: 決定可能な同値関係\n *)\nRequire Import ssreflect ssrfun ssrbool.\n\n(** nat を定義する。 *)\nInductive nat : Set :=\n| O\n| S of nat.\n\n(** 同値関係が決定可能なら, ブール値等式として定義ができる *)\nFixpoint eqn (m  n : nat) {struct m} : bool :=\n  match m, n with\n    | O, O => true\n    | S m', S n' => eqn m' n'\n    | _, _ => false\n  end.\n\n(*************************\neqType を使わない場合（普通はこれをしない）\neqtype_sample.v\n *)\nRecord myeq := Eqtype {\n  car : Set ; \n  myequality : car -> car -> bool ;\n  Heq : forall x y : car, myequality x y = true -> x = y }.\nNotation \"a '===' b\" := (myequality _ a b) (at level 70).\n\nLemma myeqnP n m : eqn n m = true -> n = m.\nProof.\n    by elim: n m => [|n IHn] [|m] //= /IHn ->.\nQed.\n\nCheck S O = S O.\nFail Compute S O === S O.                   (* まだ===は使えない。 *)\nCanonical Structure eqtypenat := Eqtype _ _ myeqnP.\nCompute S O === S O.                        (* true *)\n\nCheck (O : car _).\nCheck Heq.\n\n(** 証明 *)\nGoal forall n m : nat, n === m -> n = m.\nProof.\n  move=> n m.\n  move/myeqnP.\n  Undo 1.\n  move/Heq.\n  by [].\nQed.\n\n(*************************\neqType を使う場合\n *)\nRequire Import eqtype. (* eqtypeまで *)\n\n(** そのブール値等式と Leibniz 同値関係の等価性が証明をする。 *)\n(* ここでは、<-> ではなく reflect を使う。 *)\nLemma eqnP : Equality.axiom eqn.            (*  reflect (x = y) (eqn x y) *)\nProof.\n  move=> n m; apply: (iffP idP) => [|<-]; last by elim n.\n    by elim: n m => [|n IHn] [|m] //= /IHn ->.\nQed.\n\n(** その型はeqType として登録できる。 *)\nCheck S O = S O.\nFail Check S O == S O.\nFail Check S O != S O.\nCanonical nat_eqMixin := EqMixin eqnP.\nCanonical nat_eqType := Eval hnf in EqType nat nat_eqMixin.\nCompute S O == S O.\nCompute S O != S O.\n\n(** 証明 *)\nGoal forall n m : nat, n == m <-> n = m.\nProof.\n  move=> n m.\n  by split; move/eqnP.\nQed.\n\n(** リフレクションと書き換えができる。  *)\nGoal forall n m l : nat, n == m -> m == l -> n == l.\nProof.\n  move=> n m l Hnm Hml.\n  apply/eqP.                                (* n = l *)\n  Undo 1.\n  rewrite (eqP Hnm).                        (* m == l *)\n  by [].\nQed.\n\n(** ssrnat のおまけ *)\nLemma eqnE : eqn = eq_op. Proof. by []. Qed.\nLemma eqSS m n : (S m == S n) = (m == n). Proof. by []. Qed.\nLemma nat_irrelevance (x y : nat) (E E' : x = y) : E = E'.\nProof. exact: eq_irrelevance. Qed.\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/jsst2014/ssr_jsst2014_eqtype_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6667914844903983}}
{"text": "(** VCFloat: A Unified Coq Framework for Verifying C Programs with\n Floating-Point Computations. Application to SAR Backprojection.\n \n Version 1.0 (2015-12-04)\n \n Copyright (C) 2015 Reservoir Labs Inc.\n All rights reserved.\n \n This file, which is part of VCFloat, is free software. You can\n redistribute it and/or modify it under the terms of the GNU General\n Public License as published by the Free Software Foundation, either\n version 3 of the License (GNU GPL v3), or (at your option) any later\n version. A verbatim copy of the GNU GPL v3 is included in gpl-3.0.txt.\n \n This file is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See LICENSE for\n more details about the use and redistribution of this file and the\n whole VCFloat library.\n \n This work is sponsored in part by DARPA MTO as part of the Power\n Efficiency Revolution for Embedded Computing Technologies (PERFECT)\n program (issued by DARPA/CMO under Contract No: HR0011-12-C-0123). The\n views and conclusions contained in this work are those of the authors\n and should not be interpreted as representing the official policies,\n either expressly or implied, of the DARPA or the\n U.S. Government. Distribution Statement \"A\" (Approved for Public\n Release, Distribution Unlimited.)\n \n \n If you are using or modifying VCFloat in your work, please consider\n citing the following paper:\n \n Tahina Ramananandro, Paul Mountcastle, Benoit Meister and Richard\n Lethin.\n A Unified Coq Framework for Verifying C Programs with Floating-Point\n Computations.\n In CPP (5th ACM/SIGPLAN conference on Certified Programs and Proofs)\n 2016.\n \n \n VCFloat requires third-party libraries listed in ACKS along with their\n copyright information.\n \n VCFloat depends on third-party libraries listed in ACKS along with\n their copyright and licensing information.\n*)\n(**\nAuthor: Tahina Ramananandro <ramananandro@reservoir.com>\n\nAccumulation of rounding errors for naive summation.\n\nFor more technical information, you can read Section 5.4 of our paper\npublished at ACM/SIGPLAN Certified Programs and Proofs (CPP) 2016:\n\nTahina Ramananandro, Paul Mountcastle, Benoit Meister and Richard\nLethin.\nA Unified Coq Framework for Verifying C Programs with Floating-Point\nComputations\n\n*)\n\nRequire Import Arith ZArith Reals Psatz Morphisms.\nOpen Scope R_scope.\n\nClass Sum (Sf: (nat -> R) -> nat -> R): Prop :=\n  {\n    SfO: forall f, Sf f O = 0;\n    SfS: forall f n, Sf f (S n) = Sf f n + f n\n  }.\n\nSection S.\n\nContext `{SUM: Sum}.\n\nLemma Sf_ext: forall n f1 f2,\n  (forall i, (i < n)%nat -> f1 i = f2 i) ->\n  Sf f1 n = Sf f2 n.\nProof.\n  induction n; intros; simpl.\n  {\n    repeat rewrite SfO. reflexivity.\n  }\n  repeat rewrite SfS.\n  f_equal; auto.\nQed.\n\nLemma Sf_left n:\n  forall f,\n    Sf f (S n) = f O + Sf (fun i => f (S i)) n.\nProof.\n  induction n; intros.\n  {\n    rewrite SfS.\n    repeat rewrite SfO.\n    ring.\n  }\n  rewrite SfS.\n  rewrite IHn.\n  rewrite Rplus_assoc.\n  f_equal.\n  rewrite SfS.\n  reflexivity.\nQed.\n\nLemma Sf_inv n:\n  forall f,\n    Sf f n = Sf (fun i => f (n - S i)%nat) n.\nProof.\n  induction n; intros.\n  {\n    repeat rewrite SfO.\n    reflexivity.\n  }\n  rewrite Sf_left.\n  rewrite SfS.\n  rewrite Rplus_comm.\n  f_equal.\n  {\n    rewrite IHn.\n    apply Sf_ext.\n    intros.\n    f_equal.\n    lia.\n  }\n  f_equal.\n  lia.\nQed.\n\nLemma Sf_scal x f n:\n  Sf f n * x = Sf (fun i => x * f i) n.\nProof.\n  induction n.\n  {\n    repeat rewrite SfO.\n    ring.\n  }\n  repeat rewrite SfS.\n  rewrite Rmult_plus_distr_r.\n  rewrite IHn.\n  ring.\nQed.\n\nDefinition sumOfPowers x := Sf (pow x).\nDefinition sumOfPowersO x: sumOfPowers x O = 0 := SfO _.\nDefinition sumOfPowersS x n: sumOfPowers x (S n) = sumOfPowers x n + x ^ n := SfS _ _.\n\nSection U.\n\nVariable x: R.\nLocal Notation u := (sumOfPowers x).\nLet uO: u O = 0 := sumOfPowersO _.\nLet uS n: u (S n) = u n + x ^ n := sumOfPowersS _ _.\n\nHypothesis x_ne_1: x <> 1.\n\nLemma u_eq n: u n = (1 - x ^ n) / (1 - x).\nProof.\n  induction n.\n  {\n    rewrite uO.\n    simpl.\n    unfold Rdiv.\n    ring.\n  }\n  rewrite uS.\n  rewrite IHn.\n  simpl.\n  field.\n  lra.\nQed.\n\nLemma u_x n:\n  u n * x = u (S n) - 1.\nProof.\n  unfold u. rewrite Sf_left. simpl.\n  match goal with\n  |- _ = ?z => match z with\n    1 + ?y - 1 => replace z with y by ring\n  end end.\n  apply Sf_scal.\nQed.\n\nEnd U.\n\nDefinition sumOfIPowers x := Sf (fun i => INR (S i) * pow x i).\nDefinition sumOfIPowersO x: sumOfIPowers x O = 0 := SfO _.\nDefinition sumOfIPowersS x n: sumOfIPowers x (S n) = sumOfIPowers x n + INR (S n) * x ^ n := SfS _ _.\n\nSection SUMDERIV.\n\nVariable x: R.\nLocal Notation v := (sumOfIPowers x).\nLet v0: v O = 0 := sumOfIPowersO _.\nLet vS n: v (S n) = v n + INR (S n) * pow x n := sumOfIPowersS _ _.\n\nHypothesis x_ne_1: x <> 1.\n\nLemma v_eq n:\n  v n = (INR n * x ^ (S n) - INR (S n) * x ^ n + 1) / (1 - x) ^ 2.\nProof.\n  induction n.\n  {\n    rewrite v0.\n    simpl.\n    field.\n    lra.\n  }\n  rewrite vS.\n  rewrite IHn.\n  repeat rewrite S_INR.\n  simpl.\n  field.\n  lra.\nQed.\n\nEnd SUMDERIV.\n\nClass prop (K L M: R) (D: nat -> R): Prop :=\n  {\n    DO: D O = 0;\n    DS: forall n, D (S n) = D n * M + INR n * L + K\n  }.\n\nContext {D_} {PROP: forall K L M, prop K L M (D_ K L M)}.\n\nSection S.\n\nContext (K L M: R).\n\nLocal Notation D := (D_ K L M).\n\nSection WITH_M_hyp.\n\nHypothesis M_neq_0: M <> 0.\n\nLemma D_eq_aux' n:\n  D (S (S n)) = K * sumOfPowers M (S (S n)) + L * M ^ n * sumOfIPowers (/ M) (S n).\nProof.\n  induction n.\n  {\n    repeat rewrite DS.\n    rewrite DO.\n    repeat rewrite sumOfPowersS.\n    rewrite sumOfPowersO.\n    repeat rewrite sumOfIPowersS.\n    rewrite sumOfIPowersO.\n    simpl.\n    ring.\n  }\n  rewrite DS.\n  rewrite IHn; clear IHn.\n  repeat rewrite sumOfPowersS.\n  repeat rewrite sumOfIPowersS.\n  repeat rewrite S_INR.\n  simpl.\n  rewrite <- Rinv_pow by assumption.\n  ring_simplify.\n  rewrite Rmult_assoc.\n  rewrite u_x.\n  rewrite sumOfPowersS.\n  field.\n  split; auto.\n  apply pow_nonzero.\n  assumption.\nQed.\n\nHypothesis M_neq_1: M <> 1.\n\nLet InvM_neq_1: / M <> 1.\nProof.\n  intro ABS.\n  generalize (f_equal Rinv ABS).\n  rewrite Rinv_involutive by assumption.\n  rewrite Rinv_1.\n  assumption.\nQed.\n\nLemma tech_invert_square u:\n  u / (1 - / M) ^ 2 = u * M ^ 2 / (1 - M) ^ 2.\nProof.\n  field.\n  lra.\nQed.\n\nLemma tech1 n: D (S (S n)) = K * ((1 - M ^ S (S n)) / (1 - M)) + L * (INR (S n) - INR (S (S n)) * M + M ^ S (S n)) / (1 - M) ^ 2.\nrewrite D_eq_aux'.\nrewrite u_eq by assumption.\nrewrite v_eq by assumption.\nf_equal.\nrewrite tech_invert_square.\nunfold Rdiv.\nrewrite Rmult_assoc.\nsymmetry.\nrewrite Rmult_assoc.\nf_equal.\nrewrite <- Rmult_assoc.\nf_equal.\nsymmetry.\nreplace (S (S n)) with (n + 2)%nat at 1 4 by lia.\nrepeat rewrite pow_add.\nrewrite <- (tech_pow_Rmult (/ M) n).\nrepeat rewrite <- Rinv_pow by assumption.\nfield.\nsplit; auto.\napply pow_nonzero.\nassumption.\nQed.\n\nLemma tech2 n:\n  D (S (S n)) = K * ((1 - M ^ S (S n)) / (1 - M)) + L * (INR (S (S n)) - 1 - INR (S (S n)) * M + M ^ S (S n)) / (1 - M) ^ 2.\nProof.\n  rewrite tech1.\n  repeat rewrite S_INR.\n  field.\n  lra.\nQed.\n\nLemma tech3 n:\n D n = K * ((1 - M ^ n) / (1 - M)) + L * (INR n * (1 - M) - 1 + M ^ n) / (1 - M) ^ 2.\nProof.\n  destruct n.\n  {\n    rewrite DO.\n    simpl.\n    unfold Rdiv.\n    ring.\n  }\n  destruct n.\n  {\n    rewrite DS.\n    rewrite DO.\n    simpl.\n    field.\n    lra.\n  }\n  rewrite tech2.\n  field.\n  lra.\nQed.\n\nDefinition E n := (1 - M ^ n) / (1 - M) * (K - L / (1 - M)) + L * INR n / (1 - M).\n\nTheorem D_eq_aux n:\n D n = E n.\nProof.\n  unfold E.\n  rewrite tech3.\n  field.\n  lra.\nQed.\n\nEnd WITH_M_hyp.\n\nTheorem D_eq:\n  M <> 1 ->\n  forall n,\n    D n = E n.\nProof.\n  intros HM n.\n  destruct (Req_dec M 0) as [EQ | ].\n  {\n    unfold E.\n    rewrite EQ.\n    destruct n.\n    {\n      simpl.\n      rewrite DO.\n      field.\n    }\n    rewrite DS.\n    rewrite S_INR.\n    simpl.\n    field.\n  }\n  apply D_eq_aux; auto.\nQed.\n\nEnd S.\n\nLemma ub f M:\n  (forall n, f n <= M) ->\n  forall n, Sf f n <= INR n * M.\nProof.\n  induction n.\n  {\n    rewrite SfO. simpl. apply Req_le. ring.\n  }\n  rewrite SfS. rewrite S_INR.\n  rewrite Rmult_plus_distr_r.\n  rewrite Rmult_1_l.\n  apply Rplus_le_compat; auto.\nQed.\n\nLemma ub_abs f M:\n  (forall n, Rabs (f n) <= M) ->\n  forall n, Rabs (Sf f n) <= INR n * M.\nProof.\n  induction n.\n  {\n    rewrite SfO. simpl. rewrite Rabs_R0.\n    apply Req_le. lra.\n  }\n  rewrite SfS. rewrite S_INR.\n  rewrite Rmult_plus_distr_r.\n  rewrite Rmult_1_l.\n  eapply Rle_trans.\n  {\n    apply Rabs_triang.\n  }\n  apply Rplus_le_compat; auto.\nQed.\n\n(* Total error of a rounded sum of approximate terms *)\n\nTheorem error_rounded_sum_with_approx Q q Q_ q_ d e Mq Mdq Md Me n:\n  Rabs q <= Mq ->\n  Rabs d <= Md ->\n  Rabs e <= Me ->\n  Rabs (q_ - q) <= Mdq ->\n  Rabs Q <= INR n * Mq ->\n  let M := 1 + Md in\n  let L := (Mq * Md) in\n  let K := (Mq * Md + Mdq * (1 + Md) + Me) in\n  Rabs (Q_ - Q) <= D_ K L M n ->\n  Rabs ((Q_ + q_) * (1 + d) + e - (Q + q)) <= D_ K L M (S n). \nProof.\n  intros H H0 H1 H2 H3 M L K H4.\n  pose (dq := q_ - q).\n  assert \n    ((Q_ + q_) * (1 + d) + e - (Q + q)\n     = (Q_ - Q) * (1 + d) + Q * d + (q * d + dq * (1 + d) + e))\n    as V_m_U.\n  {\n    unfold dq.\n    ring.\n  }\n  assert \n  (Rabs ((Q_ + q_) * (1 + d) + e - (Q + q)) <= Rabs (Q_ - Q) * M + INR n * L + K)\n  as V_m_U_le.\n  {\n    unfold K, L, M.\n    rewrite V_m_U.\n    eapply Rle_trans.\n    {\n      apply Rabs_triang.\n    }\n    apply Rplus_le_compat.\n    {\n      eapply Rle_trans.\n      {\n        apply Rabs_triang.\n      }\n      apply Rplus_le_compat.\n      {\n        rewrite Rabs_mult.\n        apply Rmult_le_compat_l; auto using Rabs_pos.\n        eapply Rle_trans.\n        {\n          apply Rabs_triang.\n        }\n        rewrite Rabs_R1.\n        apply Rplus_le_compat_l; auto.\n      }\n      rewrite Rabs_mult.\n      rewrite <- Rmult_assoc.\n      apply Rmult_le_compat; auto using Rabs_pos.\n    }\n    eapply Rle_trans.\n    {\n      apply Rabs_triang.\n    }\n    apply Rplus_le_compat; auto.\n    eapply Rle_trans.\n    {\n      apply Rabs_triang.\n    }\n    apply Rplus_le_compat.\n    {\n      rewrite Rabs_mult.\n      apply Rmult_le_compat; auto using Rabs_pos.\n    }\n    rewrite Rabs_mult.\n    apply Rmult_le_compat; auto using Rabs_pos.\n    eapply Rle_trans.\n    {\n      apply Rabs_triang.\n    }\n    rewrite Rabs_R1.\n    apply Rplus_le_compat_l; auto.\n  }\n  eapply Rle_trans.\n  {\n    apply V_m_U_le.\n  }\n  rewrite DS.\n  apply Rplus_le_compat_r.\n  apply Rplus_le_compat_r.\n  apply Rmult_le_compat_r; auto.\n  unfold M.\n  generalize (Rabs_pos (d)).\n  lra.\nQed.\n\n(* Range of a sum with rounding errors. (We assume that we already know the range of each computed term of the sum.) *)\n\nLemma next_rounded_sum_range Q n q d e Mq Md Me:\n  Rabs q <= Mq ->\n  Rabs d <= Md ->\n  Rabs e <= Me ->\n  let M := 1 + Md in\n  let K' := (Mq * (1 + Md) + Me) in\n  Rabs Q <=  D_ K' 0 M (n) ->\n  Rabs ((Q + q) * (1 + d) + e) <= D_ K' 0 (M) (S n).\nProof.\n  intros H H0 H1 M K' H2.\n  assert (Rabs ((Q + q) * (1 + d) + e) <= Rabs Q * M + INR n * 0 + K') as H3.\n  {\n    replace ((Q + q) * (1 + d) + e) with\n    (Q * (1 + d) + INR n * 0 + (q * (1 + d) + e))\n      by ring.\n    unfold K', M.\n    rewrite Rmult_0_r.\n    repeat rewrite Rplus_0_r.\n    eapply Rle_trans.\n    {\n      apply Rabs_triang.\n    }\n    apply Rplus_le_compat.\n    {\n      rewrite Rabs_mult.\n      apply Rmult_le_compat_l; auto using Rabs_pos.\n      eapply Rle_trans.\n      {\n        apply Rabs_triang.\n      }\n      rewrite Rabs_R1.\n      apply Rplus_le_compat_l; auto.\n    }\n    eapply Rle_trans.\n    {\n      apply Rabs_triang.\n    }\n    apply Rplus_le_compat; auto.\n    rewrite Rabs_mult.\n    apply Rmult_le_compat; auto using Rabs_pos.\n    eapply Rle_trans.\n    {\n      apply Rabs_triang.\n    }\n    rewrite Rabs_R1.\n    apply Rplus_le_compat_l; auto.\n  }\n  eapply Rle_trans.\n  {\n    apply H3.\n  }\n  rewrite DS.\n  apply Rplus_le_compat_r.\n  apply Rplus_le_compat_r.\n  apply Rmult_le_compat_r; auto.   \n  unfold M.\n  generalize (Rabs_pos d).\n  lra.\nQed.\n\nEnd S.\n\n(* Implementations *)\n \nFixpoint Sf (f: nat -> R) (n: nat): R :=\n  match n with\n  | O => 0\n  | S n' => Sf f n' + f n'\n  end.\n\nGlobal Instance: Sum Sf.\nProof.\n  split; reflexivity.\nQed.\n\nFixpoint D (K L M: R) (n: nat): R :=\n  match n with\n  | O => 0\n  | S n' => D K L M n' * M + INR n' * L + K\n  end.\n\nGlobal Instance: forall K L M, prop K L M (D K L M).\nProof.\n  split; reflexivity.\nQed.\n", "meta": {"author": "VeriNum", "repo": "vcfloat", "sha": "9cad8c4b48fe4353d01f02f6dc5bd03e1ea4eb5c", "save_path": "github-repos/coq/VeriNum-vcfloat", "path": "github-repos/coq/VeriNum-vcfloat/vcfloat-9cad8c4b48fe4353d01f02f6dc5bd03e1ea4eb5c/vcfloat/Summation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6667430358085941}}
{"text": "Require Import Bool.\nRequire Import FunInd.\n\nInductive ctx : Set :=\n  | ctx_nil : ctx\n  | ctx_cons : (nat * bool) -> ctx -> ctx.\n\nFixpoint ctx_v (n : nat) (c : ctx) {struct c} : option bool :=\n  match c with\n  | ctx_nil => None\n  | ctx_cons (n', v) c => if Nat.eqb n n' then Some v else ctx_v n c\n  end.\n\nInductive prop : Set :=\n  | p_sym : nat -> prop\n  | p_neg : prop -> prop\n  | p_and : prop -> prop -> prop\n  | p_or : prop -> prop -> prop\n  | p_impl : prop -> prop -> prop.\n\nFunction prop_val (c : ctx) (p : prop) {struct p} : option bool :=\n  match p with\n  | p_sym n => ctx_v n c\n  | p_neg p =>\n      match prop_val c p with\n      | None => None\n      | Some b => Some (negb b)\n      end\n  | p_and p1 p2 =>\n      match prop_val c p1 with\n      | None => None\n      | Some b1 =>\n          match prop_val c p2 with\n          | None => None\n          | Some b2 => Some (andb b1 b2)\n          end\n      end\n  | p_or p1 p2 =>\n      match prop_val c p1 with\n      | None => None\n      | Some b1 =>\n          match prop_val c p2 with\n          | None => None\n          | Some b2 => Some (orb b1 b2)\n          end\n      end\n  | p_impl p1 p2 =>\n      match prop_val c p1 with\n      | None => None\n      | Some b1 =>\n          match prop_val c p2 with\n          | None => None\n          | Some b2 => Some (implb b1 b2)\n          end\n      end\n  end.\n\nLemma prop_val_neg_b : forall c p b,\n  prop_val c p = Some b -> prop_val c (p_neg p) = Some (negb b).\nProof.\n  intros c p b H.\n  rewrite prop_val_equation. rewrite H. reflexivity.\nQed.\n\nLemma prop_val_neg_n : forall c p,\n  prop_val c p = None -> prop_val c (p_neg p) = None.\nProof.\n  intros c p H.\n  rewrite prop_val_equation. rewrite H. reflexivity.\nQed.\n\nLemma prop_val_or_b : forall c p0 p1 b0 b1,\n  prop_val c p0 = Some b0 -> prop_val c p1 = Some b1 ->\n  prop_val c (p_or p0 p1) = Some (orb b0 b1).\nProof.\n  intros c p0 p1 b0 b1 Hprop0 Hprop1.\n  rewrite prop_val_equation. rewrite Hprop0. rewrite Hprop1. reflexivity.\nQed.\n\nLemma prop_val_or_n_l : forall c p0 p1,\n  prop_val c p0 = None -> prop_val c (p_or p0 p1) = None.\nProof.\n  intros c p0 p1 Hprop.\n  rewrite prop_val_equation. rewrite Hprop. reflexivity.\nQed.\n\nLemma prop_val_or_n_r : forall c p0 p1,\n  prop_val c p1 = None -> prop_val c (p_or p0 p1) = None.\nProof.\n  intros c p0 p1 Hprop0.\n  rewrite prop_val_equation. rewrite Hprop0.\n  case_eq (prop_val c p0); auto.\nQed.\n\nLemma prop_val_and_b : forall c p0 p1 b0 b1,\n  prop_val c p0 = Some b0 -> prop_val c p1 = Some b1 ->\n  prop_val c (p_and p0 p1) = Some (andb b0 b1).\nProof.\n  intros c p0 p1 b0 b1 Hprop0 Hprop1.\n  rewrite prop_val_equation. rewrite Hprop0. rewrite Hprop1. reflexivity.\nQed.\n\nLemma prop_val_and_n_l : forall c p0 p1,\n  prop_val c p0 = None -> prop_val c (p_and p0 p1) = None.\nProof.\n  intros c p0 p1 Hprop.\n  rewrite prop_val_equation. rewrite Hprop. reflexivity.\nQed.\n\nLemma prop_val_and_n_r : forall c p0 p1,\n  prop_val c p1 = None -> prop_val c (p_and p0 p1) = None.\nProof.\n  intros c p0 p1 Hprop0.\n  rewrite prop_val_equation. rewrite Hprop0.\n  case_eq (prop_val c p0); auto.\nQed.\n\nLemma prop_val_impl_b : forall c p0 p1 b0 b1,\n  prop_val c p0 = Some b0 -> prop_val c p1 = Some b1 ->\n  prop_val c (p_impl p0 p1) = Some (implb b0 b1).\nProof.\n  intros c p0 p1 b0 b1 Hprop0 Hprop1.\n  rewrite prop_val_equation. rewrite Hprop0. rewrite Hprop1. reflexivity.\nQed.\n\nLemma prop_val_impl_n_l : forall c p0 p1,\n  prop_val c p0 = None -> prop_val c (p_impl p0 p1) = None.\nProof.\n  intros c p0 p1 Hprop.\n  rewrite prop_val_equation. rewrite Hprop. reflexivity.\nQed.\n\nLemma prop_val_impl_n_r : forall c p0 p1,\n  prop_val c p1 = None -> prop_val c (p_impl p0 p1) = None.\nProof.\n  intros c p0 p1 Hprop0.\n  rewrite prop_val_equation. rewrite Hprop0.\n  case_eq (prop_val c p0); auto.\nQed.\n\nInductive seq_l : Set :=\n  | seq_l_nil : seq_l\n  | seq_l_cons : prop -> seq_l -> seq_l.\n\nFunction seq_l_val (c : ctx) (s : seq_l) {struct s} : option bool :=\n  match s with\n  | seq_l_nil => Some true\n  | seq_l_cons p s =>\n      match prop_val c p with\n      | None => None\n      | Some b1 =>\n          match seq_l_val c s with\n          | None => None\n          | Some b2 => Some (andb b1 b2)\n          end\n      end\n  end.\n\nLemma seq_l_val_lem : forall c p s b0 b1,\n  seq_l_val c s = Some b0 -> prop_val c p = Some b1 ->\n  seq_l_val c (seq_l_cons p s) = Some (andb b1 b0).\nProof.\n  intros c p s b0 b1 Hs Hp.\n  rewrite (seq_l_val_equation c (seq_l_cons p s)).\n  rewrite Hp. rewrite Hs. reflexivity.\nQed.\n\nInductive seq_r : Set :=\n  | seq_r_nil : seq_r\n  | seq_r_cons : prop -> seq_r -> seq_r.\n\nFunction seq_r_val (c : ctx) (s : seq_r) {struct s} : option bool :=\n  match s with\n  | seq_r_nil => Some false\n  | seq_r_cons p s =>\n      match prop_val c p with\n      | None => None\n      | Some b1 =>\n          match seq_r_val c s with\n          | None => None\n          | Some b2 => Some (orb b1 b2)\n          end\n      end\n  end.\n\nLemma seq_r_val_lem : forall c p s b0 b1,\n  seq_r_val c s = Some b0 -> prop_val c p = Some b1 ->\n  seq_r_val c (seq_r_cons p s) = Some (orb b1 b0).\nProof.\n  intros c p s b0 b1 Hs Hp.\n  rewrite (seq_r_val_equation c (seq_r_cons p s)).\n  rewrite Hp. rewrite Hs. reflexivity.\nQed.\n\nInductive seq_t : Set :=\n  | seq : seq_l -> seq_r -> seq_t.\n\nDefinition seq_val (c : ctx) (s : seq_t) : option bool :=\n  match s with\n  | seq l r =>\n      match seq_l_val c l with\n      | None => None\n      | Some b1 =>\n          match seq_r_val c r with\n          | None => None\n          | Some b2 => Some (implb b1 b2)\n          end\n      end\n  end.\n\nLemma satisfying_ctx_r : forall c l r b b1 b2,\n  (seq_l_val c l = Some b1 /\\ seq_r_val c r = Some b2 /\\ b = implb b1 b2) ->\n  (seq_val c (seq l r) = Some b).\nProof.\n  intros c l r b b1 b2 [ Hbl [ Hbr Himpl ] ].\n  unfold seq_val. rewrite Hbl. rewrite Hbr. rewrite Himpl. reflexivity.\nQed.\n\n(* `exists` is required as implies is not an injective function *)\nLemma satisfying_ctx_l : forall c l r b,\n  (seq_val c (seq l r) = Some b) ->\n  (exists b1 b2, seq_l_val c l = Some b1 /\\ seq_r_val c r = Some b2 /\\ b = implb b1 b2).\nProof.\n  intros c l r b.\n  unfold seq_val. destruct (seq_l_val c l). destruct (seq_r_val c r).\n  - intros H. inversion H. exists b0. exists b1. repeat split.\n  - intros H. discriminate.\n  - intros H. discriminate.\nQed.\n\nInductive eval_unary : seq_t -> seq_t -> Prop :=\n  | neg_l : forall p l r,\n      eval_unary (seq (seq_l_cons (p_neg p) l) r)\n           (seq l (seq_r_cons p r))\n  | neg_r : forall p l r,\n      eval_unary (seq l (seq_r_cons (p_neg p) r))\n           (seq (seq_l_cons p l) r)\n  | or_r : forall p0 p1 l r,\n      eval_unary (seq l (seq_r_cons (p_or p0 p1) r))\n           (seq l (seq_r_cons p0 (seq_r_cons p1 r)))\n  | impl_r : forall p0 p1 l r,\n      eval_unary (seq l (seq_r_cons (p_impl p0 p1) r))\n          (seq (seq_l_cons p0 l) (seq_r_cons p1 r)).\n\nInductive eval_binary : seq_t -> seq_t -> seq_t -> Prop :=\n  | or_l : forall p0 p1 l r,\n      eval_binary (seq (seq_l_cons (p_or p0 p1) l) r)\n           (seq (seq_l_cons p0 l) r)\n           (seq (seq_l_cons p1 l) r).\n", "meta": {"author": "benmandrew", "repo": "vSequent", "sha": "5afa203dec826424fabca58f8084634582b0cce5", "save_path": "github-repos/coq/benmandrew-vSequent", "path": "github-repos/coq/benmandrew-vSequent/vSequent-5afa203dec826424fabca58f8084634582b0cce5/vsequent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979306, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.6667430285572156}}
{"text": "Require Import A1_Plan A2_Orientation A4_Droite A7_Tactics .\nRequire Import B7_Tactics .\nRequire Import G1_Angles G3_ParticularAngle .\nRequire Import H1_Triangles .\nRequire Import I1_SupplementaryAngle I2_Supplement I4_Tactics .\nRequire Import J1_MidLine J2_MidPoint J3_MidProp J4_Tactics .\nRequire Import K1_RightAngle.\n\nSection MIDLINEandRIGHTANGLE.\n\nLemma RightAngleNotCollinear : forall A B C : Point,\n\tRightAngle A B C ->\n\t~Collinear A B C.\nProof.\n\tintros; intro.\n\tby3SegmentCases1 H0.\n\t elim (RightAngleNotNullAngle A B C H).\n\t   apply OpenRayNullAngle.\n\t  apply (RightAngleDistinctBA A B C H).\n\t  step9 H1.\n\t    apply (RightAngleDistinctBC A B C H).\n\t elim (RightAngleNotNullAngle A B C H).\n\t   apply OpenRayNullAngle.\n\t  apply (RightAngleDistinctBA A B C H).\n\t  immediate9.\n\t elim (RightAngleNotElongatedAngle A B C H).\n\t   apply BetweenElongatedAngle.\n\t   step9 H2.\n\t  apply sym_not_eq; apply (RightAngleDistinctBC A B C H).\n\t  apply (RightAngleDistinctBA A B C H).\nQed.\n\nLemma SupplementaryRightAngle : Supplementary Vv IsAngleVv = Vv.\nProof.\n\tunfold Supplementary in |- *.\n\tassert (H := IsAngleVv); eqToCongruent8.\n\texact RightVvOouU.\nQed.\n\nLemma EqSupplementaryEqRightAngle : forall alpha : Point, forall (H : IsAngle alpha),\n\tSupplementary alpha H = alpha ->\n\talpha = Vv.\nProof.\n\tunfold Supplementary, RightAngle in |- *; intros.\n\tfrom9 3 (TCongruent (Tr alpha Oo uU) (Tr alpha Oo Uu)).\n\t   eqToCongruent8; immediate9.\n\t apply EqVv.\n\t  immediate9.\n\t  elim H; intros.\n\t    contrapose0 H3.\n\t    step9 BetweenUuOouU.\n\t  step9 H1.\nQed.\n\nLemma EqSupplementEqRightAngle : forall A B C : Point,\n\tSupplement A B C A B C ->\n\tRightAngle A B C.\nProof.\n\tintros.\n\tinversion H.\n\tsince9 (Angle A B C Hed Hef = Vv).\n\t apply  (EqSupplementaryEqRightAngle (Angle A B C Hed Hef) (IsAngleAngle A B C Hed Hef)).\n\t  step9 H0.\n\t unfold RightAngle in |- *.\n\t   congruentToEq8.\n\t  exact DistinctOoVv.\n\t  rewrite H1.\n\t    assert (H4 := IsAngleVv).\n\t    step9 H4.\nQed.\n\nLemma SupplementCongruentRightAngle : forall A B C D E F : Point,\n\tCongruentAngle A B C D E F ->\n\tSupplement A B C D E F ->\n\tRightAngle A B C.\nProof.\n\tintros.\n\tapply EqSupplementEqRightAngle.\n\tstep9 H0.\nQed.\n\nLemma RightAngleAIA' : forall A B : Point, forall H : A <> B, \n\tRightAngle A (MidPoint A B H) (LineA (MidLine A B H)).\nProof.\n\tintros.\n\tapply EqSupplementEqRightAngle.\n\tsince9  (CongruentAngle A (MidPoint A B H) (LineA (MidLine A B H)) B (MidPoint A B H) (LineA (MidLine A B H))).\n\t assert (H1 := TCongruentAIA'BIA' A B H).\n\t   step9 H1;  immediate9.\n\t step9 H0.\n\t   since9 (Between A (MidPoint A B H) B).\nQed.\n\nLemma RightAngleAIB' : forall A B : Point, forall H : A <> B, \n\tRightAngle A (MidPoint A B H) (LineB (MidLine A B H)).\nProof.\n\tintros.\n\tapply (CongruentRightAngle A (MidPoint A B H) (LineA (MidLine A B H))).\n\t apply RightAngleAIA'.\n\t step9 (TCongruentAIA'AIB' A B H);  immediate9.\nQed.\n\nLemma RightAngleBIA' : forall A B : Point, forall H : A <> B, \n\tRightAngle B (MidPoint A B H) (LineA (MidLine A B H)).\nProof.\n\tintros.\n\tapply (CongruentRightAngle A (MidPoint A B H) (LineA (MidLine A B H))).\n\t apply RightAngleAIA'.\n\t step9 (TCongruentAIA'BIA' A B H);  immediate9.\nQed.\n\nLemma RightAngleBIB' : forall A B : Point, forall H : A <> B, \n\tRightAngle B (MidPoint A B H) (LineB (MidLine A B H)).\nProof.\n\tintros.\n\tapply (CongruentRightAngle A (MidPoint A B H) (LineB (MidLine A B H))).\n\t apply RightAngleAIB'.\n\t step9 (TCongruentAIB'BIB' A B H);  immediate9.\nQed.\n\nLemma OnMidLineRightAngle : forall A B C : Point, forall H : A <> B, \n\tMidPoint A B H <> C ->\n\tOnLine (MidLine A B H) C ->\n\tRightAngle A (MidPoint A B H) C.\nProof.\n\tintros.\n\tfrom9 1 (TCongruent (Tr A (MidPoint A B H) C) (Tr B (MidPoint A B H) C)).\n\t  step9 H1.\n\t from9 H2 (CongruentAngle A (MidPoint A B H) C B (MidPoint A B H) C).\n\t  apply EqSupplementEqRightAngle.\n\t    step9 H3.\n\t    since9 (Between A (MidPoint A B H) B).\nQed.\n\nLemma OnMidLineEqMidPointRightAngleA : forall A B C D : Point, forall H : A <> B, \n\tC <> D ->\n\tC = MidPoint A B H ->\n\tOnLine (MidLine A B H) D ->\n\tRightAngle A  C D.\nProof.\n\tintros.\n\tsubst.\n\tapply OnMidLineRightAngle; immediate9.\nQed.\n\nLemma OnMidLineEqMidPointRightAngleB : forall A B C D : Point, forall H : A <> B, \n\tC <> D ->\n\tC = MidPoint A B H ->\n\tOnLine (MidLine A B H) D ->\n\tRightAngle B  C D.\nProof.\n\tintros; subst.\n\tapply (CongruentRightAngle A (MidPoint A B H) D).\n\t apply (OnMidLineEqMidPointRightAngleA A B (MidPoint A B H) D H); immediate9.\n\t from9 1 (TCongruent (Tr A (MidPoint A B H) D) (Tr B (MidPoint A B H) D)).\n\t   step9 H2.\n\t  step9 H1.\n\t   immediate9.\n\t   immediate9.\nQed.\n\nLemma RightSupplementUuOoVv :\n\tSupplement Uu Oo Vv Uu Oo Vv.\nProof.\n\tassert (H := IsAngleVv).\n\tcongruentToEq8.\n\t immediate9.\n\t since9  (Supplementary (Angle Uu Oo Vv H0 H1) (IsAngleAngle Uu Oo Vv H0 H1) = Supplementary Vv IsAngleVv).\n\t  rewrite H2; rewrite SupplementaryRightAngle.\n\t    immediate9.\nQed.\n\nLemma RightRightSupplement : forall A B C D E F : Point,\n\tRightAngle A B C ->\n\tRightAngle D E F ->\n\tSupplement A B C D E F.\nProof.\n\tunfold RightAngle in |- *; intros.\n\tstep9 H.\n\tapply SupplementSym; step9 H0.\n\texact RightSupplementUuOoVv.\nQed.\n\nLemma RightSupplement : forall A B C : Point,\n\tRightAngle A B C ->\n\tSupplement A B C A B C.\nProof.\n\tintros; apply RightRightSupplement; immediate9.\nQed.\n\nLemma RightSupplementRight : forall A B C D E F : Point,\n\tRightAngle A B C ->\n\tSupplement A B C D E F ->\n\tRightAngle D E F.\nProof.\n\tintros; apply (CongruentRightAngle A B C D E F H).\n\tapply CongruentAngleSym; step9 H0.\n\tapply RightSupplement; immediate9.\nQed.\n\nLemma OrSupplementRight : forall A B C D E F : Point,\n\tRightAngle A B C \\/ CongruentAngle A B C D E F ->\n\tSupplement A B C D E F ->\n\tRightAngle D E F.\nProof.\n\tintros; destruct H.\n\t apply (RightSupplementRight A B C D E F H H0).\n\t apply (SupplementCongruentRightAngle D E F A B C).\n\t  immediate9.\n\t  apply SupplementSym; immediate9.\nQed.\n\nLemma RightOrRight : forall A B C D E F : Point,\n\tRightAngle A B C ->\n\tSupplement A B C D E F \\/ CongruentAngle A B C D E F ->\n\tRightAngle D E F.\nProof.\n\tintros.\n\tdestruct H0.\n\t apply (RightSupplementRight A B C D E F H H0).\n\t apply (CongruentRightAngle A B C D E F H H0).\nQed.\n\nEnd MIDLINEandRIGHTANGLE.\n", "meta": {"author": "coq-contribs", "repo": "euclidean-geometry", "sha": "06838851a5924918d98e5a9c07ffa84021e13af7", "save_path": "github-repos/coq/coq-contribs-euclidean-geometry", "path": "github-repos/coq/coq-contribs-euclidean-geometry/euclidean-geometry-06838851a5924918d98e5a9c07ffa84021e13af7/K2_MidLineandRightAngle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6667430257309981}}
{"text": "Require Import Ring_theory.\nPrint ring_theory.\n\nInductive V0 (A : Type) : Type := V0Make.\nInductive V1 (A : Type) : Type := V1Make : A -> V1 A.\nInductive V2 (A : Type) : Type := V2Make : A -> A -> V2 A.\nInductive Kron (f : Type -> Type) (g : Type -> Type) (a : Type) := MkKron : (f (g a)) -> Kron f g a.\nInductive DSum (f : Type -> Type) (g : Type -> Type) (a : Type) := MkDSum : f a -> g a -> DSum f g a.\n(* We need to get the ring theory in there. *)\nClass Linear (f : Type -> Type) (A : Type) := {\n                                   vsum : f A -> f A -> f A ;\n                                   smul : A -> f A -> f A;\n                                   vzero : f A\n                                            }.\n\nNotation \"s *^ v\" := (smul s v) (at level 75, right associativity).\nNotation \"v ^+^ w\" := (vsum v w) (at level 70, right associativity).\n\nInstance linearV1 : Linear V1 nat := {\n                         vsum := fun v w => match v,w with\n                                         | (V1Make _ x), (V1Make _ y) => V1Make _ (x + y)\n                                         end;\n                         smul s v := match v with\n                                     | (V1Make _ x) => V1Make _ (s * x)\n                                     end;\n                         vzero := V1Make _ 0\n                                  }.\nInstance linearDSum (f : Type -> Type) (g : Type -> Type) `{Linear f nat} `{Linear g nat}  : Linear (DSum f g) nat := {\n                         vsum := fun v w => match v,w with\n                                         | (MkDSum _ _ _ f g), (MkDSum _ _ _ f' g') => MkDSum _ _ _ (f ^+^ f') (g ^+^ g')\n                                         end;\n                         smul s v := match v with\n                                     | (MkDSum _ _ _ f g) => MkDSum _ _ _ (s *^ f) (s *^ g)\n                                     end;\n                         vzero := MkDSum _ _ _ vzero vzero\n                                  }.\n\nDefinition v1one := V1Make _ 1.\nCompute v1one ^+^ v1one.\nDefinition v2one := MkDSum _ _ _ v1one v1one.\nCompute v2one ^+^ v2one.\n\n\n\n\n\n(*\nClass Ring (A : Type) := {\n           eq :\n           plus \n           theory : ring_theory eq \n\n\n}\n\nRecord LinOp (f : v A -> w A) {\n       is_linear : f (v ^+^ w) = (f v) ^+^ (f w)\n        \n\n}\n\n*)\n(*\n                                   dist_smul : smul s (vsum x y) = vsum (smul s x) (smul s y);\n                                   assoc_vsum : (vsum (vsum x y) z) = vsum (vsum x y) z;\n                                   assoc_smul : smul s (smul s' v) = smul (s * s') v;\n                                   dist_smul : smul (s + s') v = vsum (smul s v) (smul s' v);\n                                   vsum_comm : vsum x y = vsum y x;\n                                   smul_id : smul 1 v = v;\n                                   vzero_id : vsum v vzero = v                                                                                \n                                                        \n                                 *)\n", "meta": {"author": "philzook58", "repo": "coq-vector", "sha": "18b71378556265e239126cf8497aeb1ee7182631", "save_path": "github-repos/coq/philzook58-coq-vector", "path": "github-repos/coq/philzook58-coq-vector/coq-vector-18b71378556265e239126cf8497aeb1ee7182631/vec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.666621548087185}}
{"text": "Require Import Arith.\n\nCoInductive stream :=\n| SCons : nat -> stream -> stream.\n\nCoFixpoint gen m n :=\n  SCons m (if m <? n then gen (S m) n else gen 0 (S n)).\n\nFixpoint Snth n s :=\n  match n with\n  | 0 => match s with SCons h _ => h end\n  | S n' => match s with SCons _ s' => Snth n' s' end\n  end.\n\n(* Show that each natural number occurs infinitely often in [gen 0 0]. *)\nDefinition task :=\n  forall x, forall y, exists z, y <= z /\\ Snth z (gen 0 0) = x.\n", "meta": {"author": "tzik", "repo": "top-prover", "sha": "3f92af1e76e437bee6b49152f11a6dfb3b730a61", "save_path": "github-repos/coq/tzik-top-prover", "path": "github-repos/coq/tzik-top-prover/top-prover-3f92af1e76e437bee6b49152f11a6dfb3b730a61/tasks/050/Problem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6666215362354129}}
{"text": "\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint len (len_arg0 : lst) : natural\n           := match len_arg0 with\n              | Nil => Zero\n              | Cons x y => Succ (len y)\n              end.\n\n\n(* No helper lemma needed. *)\nTheorem theorem0 : forall (x : lst) (y : natural), eq (len (append x (Cons y Nil))) (Succ (len x)).\nProof.\ninduction x.\n- intros. simpl. rewrite IHx. reflexivity.\n- intros. 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/goal53.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.666549065098304}}
{"text": "Require Import List Lia.\nImport ListNotations.\n\nRequire Import ssreflect ssrbool ssrfun.\n\nSet Default Proof Using \"Type\".\nSet Default Goal Selector \"!\".\n\n(* Generic facts *)\n\n(* duplicates argument *)\nFact copy {A : Type} : A -> A * A.\nProof. done. Qed.\n\n(* transforms a goal (A -> B) -> C into goals A and B -> C *)\nLemma unnest : forall (A B C : Type), A -> (B -> C) -> (A -> B) -> C.\nProof. auto. Qed.\n\nLemma iter_plus {X: Type} {f: X -> X} {x: X} {n m: nat} : Nat.iter n f (Nat.iter m f x) = Nat.iter (n + m) f x.\nProof. elim: n; [done | by move=> n /= ->]. Qed.\n\nFact iter_last {X: Type} {f: X -> X} {n x} : Nat.iter n f (f x) = Nat.iter (1+n) f x.\nProof. elim: n x; [done | by move=> n /= + x => ->]. Qed.\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\n(* List facts *)\nLemma Forall_appI {X: Type} {P : X -> Prop} {A B}: Forall P A -> Forall P B -> Forall P (A ++ B).\nProof. move=> ? ?. apply /Forall_app. by constructor. Qed.\n\nLemma incl_nth_error {X: Type} {Gamma Gamma': list X} : \n  incl Gamma Gamma' -> exists ξ, forall x, nth_error Gamma x = nth_error Gamma' (ξ x).\nProof.\n  elim: Gamma Gamma'.\n  - move=> Gamma' _. exists (fun x => length Gamma').\n    move=> [|x] /=; apply /esym; by apply /nth_error_None.\n  - move=> x Gamma IH Gamma'. move=> /Forall_forall /Forall_cons_iff.\n    move=> [/(@In_nth_error _ _ _) [nx] Hnx /Forall_forall /IH] [ξ Hξ].\n    exists (fun y => if y is S y then ξ y else nx). by case.\nQed.\n\nLemma Forall_seqP {P : nat -> Prop} {m n: nat} : \n  Forall P (seq m n) <-> (forall i, m <= i < m + n -> P i).\nProof. rewrite Forall_forall. constructor; move=> H ? ?; apply H; by apply /in_seq. Qed.\n\nLemma Forall2_consE {X Y: Type} {R: X -> Y -> Prop} {x y l1 l2} : \n  Forall2 R (x :: l1) (y :: l2) -> R x y /\\ Forall2 R l1 l2.\nProof. move=> H. by inversion H. Qed.\n\nLemma Forall2_length_eq {X Y: Type} {R: X -> Y -> Prop} {l1 l2} : \n  Forall2 R l1 l2 -> length l1 = length l2.\nProof.\n  elim: l1 l2.\n  - move=> [| ? ?] H; first done. by inversion H.\n  - move=> ? ? IH [| ? ?] /= H; inversion H. congr S. by apply: IH.\nQed.\n\nLemma in_app_l {X: Type} {x: X} {l1 l2: list X} : In x l1 -> In x (l1 ++ l2).\nProof. move=> ?. apply /in_app_iff. by left. Qed.\n\nLemma in_app_r {X: Type} {x: X} {l1 l2: list X} : In x l2 -> In x (l1 ++ l2).\nProof. move=> ?. apply /in_app_iff. by right. Qed.\n\n(* construct choice function for a list over nat *)\nLemma list_choice {P : nat -> nat -> Prop} {l: list nat} : Forall (fun i : nat => exists n : nat, P i n) l ->\n  exists φ, Forall (fun i : nat => P i (φ i)) l.\nProof.\n  elim: l; first by exists id.\n  move=> k l IH /Forall_cons_iff [[n Hkn]] /IH [φ Hφ].\n  exists (fun i => if PeanoNat.Nat.eq_dec i k then n else φ i).\n  constructor; first by case: (PeanoNat.Nat.eq_dec k k).\n  apply: Forall_impl Hφ => i Hi.\n  case: (PeanoNat.Nat.eq_dec i k); [by move=> /= ->|done].\nQed.\n\nLemma map_id' {X: Type} {f: X -> X} {l: list X} : (forall x, f x = x) -> map f l = l.\nProof. move=> ?. rewrite -[RHS]map_id. by apply: map_ext => ?. Qed.\n\nLemma is_trueP {b1 b2: bool} : (is_true b1 <-> is_true b2) <-> b1 = b2.\nProof.\n  case: b1; case: b2; rewrite /is_true; firstorder done.\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/SystemF/Util/Facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.6665444391338499}}
{"text": "  (***************************************************************)\n  (*   This file is part of the static analyses developement -   *)\n  (*   specification of kildall's algorithm, and proof it is a   *)\n  (*   bytecode verifier -                                       *)\n  (*\t\t\t\t\t\t\t         *)\n  (*   File : nat_bounded_list.v\t\t\t         *)\n  (*   Authors : S. Coupet-Grimal, W. Delobel\t\t         *)\n  (*   Content : instanciation of pred_list to list of natural   *)\n  (*             numbers less than a certain bound               *)\n  (***************************************************************)\n\nSection nat_bounded_list.\n  \n  \n  Require Export pred_list.\n  (* bound : *)\n  Variable n : nat.\n  \n  Definition P := fun (e:nat)=>lt e n.\n  Definition nb_list := pred_list nat P.\n  Definition nb_nil := pred_nil P.\n  Definition nb_cons := pred_cons P.\n\n  Definition nb_list_add_element := pred_list_add_element eq_nat_dec (P:=P).\n  Definition nb_list_belong := pred_list_belong (P:=P).\n  Definition nb_list_belong_dec := pred_list_belong_dec eq_nat_dec (P:=P).\n  Definition nb_list_get_witness := pred_list_get_witness (P:=P).\n  Definition nb_list_belong_add := pred_list_belong_add eq_nat_dec (P:=P).\n  Definition nb_list_belong_rem := pred_list_belong_rem eq_nat_dec (P:=P).\n  Definition nb_list_add_already_there := pred_list_add_already_there \n    eq_nat_dec (P:=P).\n  Definition nb_list_add_already_there_added := pred_list_add_already_there_added \n    eq_nat_dec (P:=P).\n  Definition nb_list_belong_added := pred_list_belong_added eq_nat_dec (P:=P).\n  Definition nb_list_remove := pred_list_remove eq_nat_dec (P:=P).\n  Definition nb_length := pred_length (P:=P).\n  Definition nb_list_equiv := pred_list_equiv (P:=P) (Q:=P).\n  Definition lt_nb_length := lt_pred_length (P:=P).\n\n  Definition nb_list_convert (m:nat) := pred_list_convert (P:=P) (Q := fun p:nat => p<m).\n  Definition nb_list_convert_equiv (m:nat) := pred_list_convert_equiv (P:=P) \n    (Q := fun p:nat => p<m).\n  Definition nb_list_convert_length (m:nat) := pred_list_convert_length (P:=P) \n    (Q := fun p:nat => p<m).\n\n  Definition nb_list_belong_convert (m:nat) := pred_list_belong_convert (P:=P) \n    (Q:=fun p:nat => p<m).\n  Definition nb_list_convert_belong (m:nat) := pred_list_convert_belong (P:=P) \n    (Q:=fun p:nat => p<m).\n\n\nEnd nat_bounded_list.\n\nImplicit Arguments nb_nil [n].\nImplicit Arguments nb_cons [n].\nImplicit Arguments nb_list_add_element [n].\nImplicit Arguments nb_list_belong [n].\nImplicit Arguments nb_list_belong_dec [n].\nImplicit Arguments nb_list_get_witness [n].\nImplicit Arguments nb_list_belong_add [n].\nImplicit Arguments nb_list_belong_rem [n].\nImplicit Arguments nb_list_remove [n].\nImplicit Arguments nb_length [n].\nImplicit Arguments lt_nb_length [n].\nImplicit Arguments nb_list_equiv [n].\nImplicit Arguments nb_list_belong_convert [n].\nImplicit Arguments nb_list_convert_belong [n].\n\nNotation \"a 'INnb' l\" := (nb_list_belong l a) (at level 50).\nNotation \"l =nb= m\" := (nb_list_equiv l m) (at level 50).\n\n", "meta": {"author": "coq-contribs", "repo": "kildall", "sha": "87422e1815e22a3f4821b29a1fd7a7f385667b91", "save_path": "github-repos/coq/coq-contribs-kildall", "path": "github-repos/coq/coq-contribs-kildall/kildall-87422e1815e22a3f4821b29a1fd7a7f385667b91/lists/nat_bounded_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.6665444360735623}}
{"text": "\nFrom Coq Require Import Arith OrderedType BinNat.\nFrom mathcomp Require Import ssreflect ssrbool ssrnat div eqtype.\nFrom ssrlib Require Import Types SsrOrder.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n\n\nSection NatLemmas.\n\n  Theorem nat_strong_ind (P : nat -> Prop) :\n    (forall n : nat, (forall k : nat, k < n -> P k) -> P n) ->\n    forall n : nat, P n.\n  Proof.\n    move=> IH. have H0: P 0.\n    { apply: IH. move=> k H; by inversion H. }\n    have H: forall n m, m <= n -> P m.\n    { move=> n; elim: n.\n      - move=> m Hm. rewrite leqn0 in Hm. rewrite (eqP Hm); exact: H0.\n      - move=> n H m Hmn. apply: IH. move=> k Hkm.\n        apply: H. exact: (leq_trans Hkm Hmn). }\n    move=> n. apply: IH. move=> k Hkn. exact: (H _ _ (ltnW Hkn)).\n  Qed.\n\n  Lemma addn_add n m :\n    n + m = (n + m)%coq_nat.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma subn_sub n m :\n    n - m = (n - m)%coq_nat.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma muln_mul n m :\n    n * m = (n * m)%coq_nat.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma leq_le_iff n m : n <= m <-> (n <= m)%coq_nat.\n  Proof.\n    elim: m n => /=.\n    - move=> n; split => H.\n      + rewrite /leq subn0 in H. rewrite (eqP H). done.\n      + inversion_clear H. done.\n    - move=> m IH n; split => H.\n      + apply: (proj1 (Nat.le_pred_le_succ n m)). apply: (proj1 (IH (n.-1))).\n        rewrite -subn1 leq_subLR addnC addn1. exact: H.\n      + rewrite -addn1 addnC -leq_subLR subn1. apply: (proj2 (IH (n.-1))).\n        apply: (proj2 (Nat.le_pred_le_succ n m)). exact: H.\n  Qed.\n\n  Lemma leq_le n m : n <= m -> (n <= m)%coq_nat.\n  Proof.\n    exact: (proj1 (leq_le_iff n m)).\n  Qed.\n\n  Lemma le_leq n m : (n <= m)%coq_nat -> n <= m.\n  Proof.\n    exact: (proj2 (leq_le_iff n m)).\n  Qed.\n\n  Lemma ltn_lt_iff n m : n < m <-> (n < m)%coq_nat.\n  Proof.\n    split => H.\n    - apply: (proj1 (Nat.le_succ_l n m)). apply: leq_le. exact: H.\n    - apply: le_leq. apply: (proj2 (Nat.le_succ_l n m)). exact: H.\n  Qed.\n\n  Lemma ltn_lt n m : n < m -> (n < m)%coq_nat.\n  Proof.\n    exact: (proj1 (ltn_lt_iff n m)).\n  Qed.\n\n  Lemma lt_ltn n m : (n < m)%coq_nat -> n < m.\n  Proof.\n    exact: (proj2 (ltn_lt_iff n m)).\n  Qed.\n\n  Lemma geq_ge_iff n m : n >= m <-> (n >= m)%coq_nat.\n  Proof.\n    split => H.\n    - exact: (leq_le H).\n    - exact: (le_leq H).\n  Qed.\n\n  Lemma geq_ge n m : n >= m -> (n >= m)%coq_nat.\n  Proof.\n    exact: (proj1 (geq_ge_iff n m)).\n  Qed.\n\n  Lemma ge_geq n m : (n >= m)%coq_nat -> n >= m.\n  Proof.\n    exact: (proj2 (geq_ge_iff n m)).\n  Qed.\n\n  Lemma gtn_gt_iff n m : n > m <-> (n > m)%coq_nat.\n  Proof.\n    split => H.\n    - exact: (ltn_lt H).\n    - exact: (lt_ltn H).\n  Qed.\n\n  Lemma gtn_gt n m : n > m -> (n > m)%coq_nat.\n  Proof.\n    exact: (proj1 (gtn_gt_iff n m)).\n  Qed.\n\n  Lemma gt_gtn n m : (n > m)%coq_nat -> n > m.\n  Proof.\n    exact: (proj2 (gtn_gt_iff n m)).\n  Qed.\n\n  Lemma ltn_leq_sub n m :\n    n < m -> n <= m - 1.\n  Proof.\n    rewrite leq_eqVlt. move=> /orP. case => H.\n    - rewrite -(eqP H). rewrite subn1 Nat.pred_succ. exact: leqnn.\n    - move: (leq_sub2r 1 H). rewrite subn1 Nat.pred_succ. exact: ltnW.\n  Qed.\n\n  Lemma subn_gtn : forall n m r, n < m - r -> r < m.\n  Proof.\n    move=> n m r H.\n    have: r < m.\n    - rewrite -(subn_gt0 r m).\n      induction n.\n      + assumption.\n      + by auto.\n    - exact.\n  Qed.\n\n  Lemma lt_subr_addl : forall n m r : nat, (n < m - r) == (n + r < m).\n  Proof.\n    move=> n m r.\n    case Hrm: (r < m).\n    - rewrite -(ltn_add2r r n (m - r)).\n      rewrite (subnK (ltnW Hrm)).\n      exact: eqxx.\n    - (* left is false *)\n      move/negP/negP: (Hrm) => Hle.\n      rewrite -leqNgt in Hle.\n      move: (subn_eq0 m r) => Hsub.\n      rewrite Hle in Hsub.\n      move/idP/eqP: Hsub => Hsub.\n      rewrite Hsub => {Hsub}.\n      rewrite ltn0.\n      (* right is false *)\n      rewrite -(leq_add2l n m r) in Hle.\n      move: (leq_trans (leq_addl n m) Hle) => {Hle} Hle.\n      rewrite (leqNgt m (n + r)) in Hle.\n      move/negPf: Hle => Hle.\n      rewrite Hle.\n      exact: eqxx.\n  Qed.\n\n  Lemma lt_sub1r_add1l : forall n m : nat, (n < m.-1) == (n.+1 < m).\n  Proof.\n    move=> n m.\n    rewrite -{2}addn1 -subn1.\n    exact: (lt_subr_addl n m 1).\n  Qed.\n\n  Lemma lt_sub1l_le (n m : nat) : (n.-1 < m) -> (n <= m).\n  Proof.\n    move=> H. move: (ltn_lt H) => {H} H.\n    move: (Nat.lt_pred_le _ _ H) => {H} /le_leq H. exact: H.\n  Qed.\n\n  Lemma gt0_sub1F :\n    forall n : nat, n > 0 -> n = n - 1 -> False.\n  Proof.\n    move=> n; elim: n.\n    - done.\n    - move=> n IH Hgt Heq.\n      rewrite -add1n addKn add1n in Heq.\n      apply: IH.\n      + rewrite -Heq.\n        assumption.\n      + rewrite -{2}Heq -add1n addKn.\n        reflexivity.\n  Qed.\n\n  Lemma ltn_leq_trans n m p :\n    m < n -> n <= p -> m < p.\n  Proof.\n    move=> Hmn Hnp.\n    move/ltP: Hmn => Hmn.\n    move/leP: Hnp => Hnp.\n    apply/ltP.\n    exact: (Lt.lt_le_trans _ _ _ Hmn Hnp).\n  Qed.\n\n  Lemma ltn_addn m1 m2 n1 n2 : m1 < n1 -> m2 < n2 -> m1 + m2 < n1 + n2.\n  Proof.\n    move=> /ltP H1 /ltP H2. apply/ltP. exact: (Nat.add_lt_mono _ _ _ _ H1 H2).\n  Qed.\n\n  Lemma ltn_leq_addn x y a b : x < a -> y <= b -> x + y < a + b.\n  Proof.\n    move => /ltP H1 /leP H2. apply/ltP. exact: (Nat.add_lt_le_mono _ _ _ _ H1 H2).\n  Qed.\n\n  Lemma leq_ltn_addn x y a b : x <= a -> y < b -> x + y < a + b.\n  Proof.\n    move=> H1 H2. rewrite (addnC x) (addnC a). exact: ltn_leq_addn.\n  Qed.\n\n  Lemma ltb_leq n m : (n <? m) = true -> n <= m.\n  Proof.\n    move=> H. apply/leP. move: (Nat.ltb_lt n m) => [H1 _]. move: (H1 H) => {H1 H} H.\n    auto with arith.\n  Qed.\n\n  Lemma eqn_ltn_gtn_cases :\n    forall (m n : nat), (m == n) || (m < n) || (n < m).\n  Proof.\n    move=> m n. case Heq: (m == n) => /=; first done.\n    move/idP/negP: Heq. rewrite neq_ltn. by apply.\n  Qed.\n\n  Lemma ltn_leq_mul_ltn m1 m2 n1 n2 :\n    0 < m2 ->\n    m1 < n1 -> m2 <= n2 -> m1 * m2 < n1 * n2.\n  Proof.\n    move=> H H1 H2. rewrite leq_eqVlt in H2. move/orP: H2; case => H2.\n    - rewrite -(eqP H2) => {H2}.\n      + rewrite ltn_mul2r H H1. done.\n      + exact: ltn_mul.\n  Qed.\n\n  Lemma ltn_leq_mul_leq m1 m2 n1 n2 :\n    m1 < n1 -> m2 <= n2 -> m1 * m2 <= n1 * n2.\n  Proof.\n    move=> H1 H2. move: (ltnW H1) => {H1} H1. exact: leq_mul.\n  Qed.\n\n  Lemma leq_ltn_mul_ltn m1 m2 n1 n2 :\n    0 < m1 ->\n    m1 <= n1 -> m2 < n2 -> m1 * m2 < n1 * n2.\n  Proof.\n    move=> H H1 H2. rewrite (mulnC m1 m2) (mulnC n1 n2). exact: ltn_leq_mul_ltn.\n  Qed.\n\n  Lemma leq_ltn_mul_leq m1 m2 n1 n2 :\n    m1 <= n1 -> m2 < n2 -> m1 * m2 <= n1 * n2.\n  Proof.\n    move=> H1 H2. move: (ltnW H2) => {H2} H2. exact: leq_mul.\n  Qed.\n\n  Lemma addr_ltn n m : 0 < m -> n < n + m.\n  Proof.\n    move=> Hm. rewrite -{1}(addn0 n) ltn_add2l. assumption.\n  Qed.\n\n  Lemma addl_ltn n m : 0 < m -> n < m + n.\n  Proof.\n    rewrite addnC. exact: addr_ltn.\n  Qed.\n\n  Lemma div2_succ n :\n    Nat.div2 (S n) = Nat.odd n + Nat.div2 n.\n  Proof.\n    case H: (Nat.odd n).\n    - move: (proj1 (Nat.odd_spec n) H) => {H} [m H].\n      rewrite {n}H.\n      have: (((2 * m) + 1).+1 = 2 * (1 + m)) by ring.\n      move=> ->. rewrite Nat.div2_double (plus_comm (2 * m) 1)\n                         Nat.div2_succ_double.\n      reflexivity.\n    - move/negPn: H => H. move: (proj1 (Nat.even_spec n) H) => {H} [m H].\n      rewrite {n}H Nat.div2_double Nat.div2_succ_double.\n      reflexivity.\n  Qed.\n\n  Lemma expn_pow n m : n ^ m = Nat.pow n m.\n  Proof.\n    elim: m.\n    - reflexivity.\n    - move=> m IH. rewrite expnS (Nat.pow_succ_r _ _ (Nat.le_0_l m)) IH.\n      reflexivity.\n  Qed.\n\n  Lemma ssrodd_odd n :\n    odd n = Nat.odd n.\n  Proof.\n    elim: n => /=.\n    - reflexivity.\n    - move=> n IH. rewrite {}IH Nat.odd_succ Nat.negb_odd. reflexivity.\n  Qed.\n\n  Lemma addn_subn a b c :\n    b <= c ->\n    (a + b == c) = (a == c - b).\n  Proof.\n    move=> Hbc. case H: (a == c - b).\n    - move: H. rewrite -(eqn_add2r b) (subnK Hbc). by apply.\n    - move/negP: H => Hne. apply/negP => H. apply: Hne.\n      rewrite -(eqn_add2r b) (subnK Hbc). exact: H.\n  Qed.\n\n  Lemma sub_diff_add_rdiff m n : n - (n - m) + (m - n) = m.\n  Proof.\n    case/orP: (leq_total n m) => H.\n    - rewrite -subn_eq0 in H. rewrite (eqP H) subn0. rewrite subn_eq0 in H.\n      exact: (subnKC H).\n    - rewrite -subn_eq0 in H. rewrite (eqP H) addn0. rewrite subn_eq0 in H.\n      exact: (subKn H).\n  Qed.\n\n  Lemma ssrdiv2_succ n :\n    (n.+1)./2 = odd n + n./2.\n  Proof.\n    rewrite /half -/uphalf -/half uphalf_half.\n    reflexivity.\n  Qed.\n\n  Lemma ssrdiv2_div2 n :\n    n./2 = Nat.div2 n.\n  Proof.\n    elim: n.\n    - reflexivity.\n    - move=> n IH.\n      rewrite div2_succ ssrdiv2_succ ssrodd_odd IH.\n      reflexivity.\n  Qed.\n\n  Lemma modn_muln2_subn1 n : 0 < n -> (n.*2 - 1) %% n = n - 1.\n  Proof.\n    move=> Hn. rewrite -addnn -(addnBA _ Hn) modnDl.\n    apply: modn_small. rewrite subn1 (prednK Hn).\n    exact: leqnn.\n  Qed.\n\n  Lemma divn_muln2_subn1 n : 0 < n -> (n.*2 - 1) %/ n = 1.\n  Proof.\n    move=> Hn. move: (divn_eq (n.*2-1) n).\n    rewrite (modn_muln2_subn1 Hn) -addnn -{1}(addnBA _ Hn).\n    move/eqP => H. rewrite eqn_add2r -{1}(mul1n n) (eqn_pmul2r Hn) in H.\n    apply/eqP. rewrite eq_sym. assumption.\n  Qed.\n\n  Lemma divn01 x n :\n    x < n.*2 -> x %/ n = 0 \\/ x %/ n = 1.\n  Proof.\n    move=> Hx.\n    have Hn: n > 0.\n    { case: n Hx; first by move=> H; inversion H. move=> n _.\n      exact: ltn0Sn. }\n    case Hxn: (x < n).\n    - rewrite (divn_small Hxn). left; reflexivity.\n    - rewrite ltnNge in Hxn. move/negPn: Hxn => Hxn. right.\n      rewrite -add1n in Hx. move: (leq_sub2r 1 Hx).\n      rewrite addKn => {Hx} Hx.\n      move: (leq_div2r n Hx) (leq_div2r n Hxn).\n      rewrite divnn Hn /= (divn_muln2_subn1 Hn) => {Hx Hxn} Hx Hxn.\n      apply/eqP; rewrite eqn_leq. by rewrite Hx Hxn.\n  Qed.\n\n  Lemma odd_divn x n :\n    x < n.*2 -> nat_of_bool (odd (x %/ n)) = x %/ n.\n  Proof.\n    move=> Hx. by case: (divn01 Hx) => ->.\n  Qed.\n\n  Lemma odd_divn_eucl x n :\n    x < n.*2 ->\n    x = odd (x %/ n) * n + x %% n.\n  Proof.\n    move=> H. rewrite (odd_divn H) -(divn_eq x n). reflexivity.\n  Qed.\n\n  Lemma ltn_ltn_addn_divn x y n :\n    x < n -> y < n -> (x + y) %/ n = 0 \\/ (x + y) %/ n = 1.\n  Proof.\n    move=> Hx Hy. apply: divn01. rewrite -addnn. exact: (ltn_addn Hx Hy).\n  Qed.\n\n  Lemma divn_eq0 n m :\n    n %/ m = 0 -> m = 0 \\/ n < m.\n  Proof.\n    move=> Hdivn. move: (divn_eq n m).\n    rewrite Hdivn mul0n add0n. move=> Hmodn. case Hm0: (m == 0).\n    - left; by rewrite (eqP Hm0).\n    - right; rewrite ltnNge. apply/negP => Hmn. rewrite -divn_gt0 in Hmn.\n      + rewrite Hdivn in Hmn; by inversion Hmn.\n      + rewrite ltn_neqAle eq_sym. move/idP/negP: Hm0.\n        move=> H; rewrite H /=. done.\n  Qed.\n\n  Lemma divn_gt0_eq0 n m :\n    n %/ m = 0 -> m > 0 -> n < m.\n  Proof.\n    move=> Hdivn Hm.\n    case: (divn_eq0 Hdivn).\n    - move=> H; rewrite {}H in Hm *. by inversion Hm.\n    - by apply.\n  Qed.\n\n  Lemma ltn_1_2expnS n :\n    1 < 2 ^ n.+1.\n  Proof.\n    rewrite expnS. apply: leq_pmulr. rewrite expn_gt0. done.\n  Qed.\n\n  Lemma modn_muln_modn_l n x y :\n    (n %% (x * y)) %% x = n %% x.\n  Proof.\n    have: (n %% x) = (n %/ (x * y) * (x * y) + n %% (x * y)) %% x.\n    { rewrite -(divn_eq n (x * y)). reflexivity. }\n    rewrite -modnDm.\n    have: (n %/ (x * y) * (x * y)) %% x = 0.\n    { rewrite (mulnC x y) mulnA modnMl. reflexivity. }\n    move=> ->. rewrite add0n. rewrite modn_mod. move=> <-. reflexivity.\n  Qed.\n\n  Lemma modn_muln_modn_r n x y :\n    (n %% (x * y)) %% y = n %% y.\n  Proof.\n    rewrite (mulnC x y). exact: modn_muln_modn_l.\n  Qed.\n\n  Lemma expn2_gt0 n : 0 < 2^n.\n  Proof.\n    by rewrite expn_gt0.\n  Qed.\n\n  Lemma expn2_gt1 n : 1 < 2^n.+1.\n  Proof.\n    rewrite expnS. apply: leq_pmulr. by rewrite expn_gt0.\n  Qed.\n\n  Lemma modn_subn n m : m <= n -> n %% m = (n - m) %% m.\n  Proof.\n    move=> H. apply/eqP. rewrite -(eqn_modDl m).\n    rewrite addnC modnDr. rewrite addnC (subnK H). exact: eqxx.\n  Qed.\n\n  Lemma mod_sub n m :\n    (m <> 0)%coq_nat ->\n    (m <= n)%coq_nat -> ((n mod m) = (n - m) mod m)%coq_nat.\n  Proof.\n    move=> Hm Hmn. rewrite -(Nat.mod_add (n - m) 1 _ Hm).\n    rewrite Nat.mul_1_l (Nat.sub_add _ _ Hmn).\n    reflexivity.\n  Qed.\n\n  Lemma modn_modulo (n m : nat) : m != 0 -> n %% m = Nat.modulo n m.\n  Proof.\n    move=> Hm0. case H: (n < m)%N.\n    - rewrite (modn_small H) Nat.mod_small; first reflexivity.\n      exact: (ltn_lt H).\n    - move/negP/idP: H; rewrite -leqNgt => H.\n      move: m H Hm0. induction n using nat_strong_ind.\n      move=> m Hmn Hm0. have Hne: m <> 0 by move/eqP: Hm0; apply.\n      rewrite (modn_subn Hmn) (mod_sub Hne (leq_le Hmn)).\n      case Hsub: ((n - m) < m)%N.\n      + rewrite (modn_small Hsub) (Nat.mod_small _ _ (ltn_lt Hsub)).\n        reflexivity.\n      + move/negP/idP: Hsub; rewrite -leqNgt => Hsub.\n        apply: H.\n        * rewrite -lt0n in Hm0. rewrite -{2}(subn0 n). apply: ltn_sub2l.\n          -- exact: (ltn_leq_trans Hm0 Hmn).\n          -- exact: Hm0.\n        * exact: Hsub.\n        * exact: Hm0.\n  Qed.\n\n  Lemma divn_div (n m : nat) : n %/ m = Nat.div n m.\n  Proof.\n    case Hm: (m == 0).\n    - rewrite (eqP Hm) divn0 /=. reflexivity.\n    - move/negP/idP: Hm => Hm. have Hne: (m <> 0) by move/eqP: Hm; apply.\n      move: (eq_refl n). rewrite {1}(divn_eq n m).\n      rewrite {3}(Nat.div_mod n m Hne).\n      rewrite -(modn_modulo _ Hm) -addn_add. rewrite eqn_add2r.\n      rewrite -muln_mul mulnC. rewrite -lt0n in Hm. rewrite (eqn_pmul2l Hm).\n      move/eqP=> H. exact: H.\n  Qed.\n\nEnd NatLemmas.\n\n\n\n(** EQTYPE modules. *)\n\nModule NatEqtype <: EQTYPE.\n  Definition t := nat_eqType.\nEnd NatEqtype.\n\nModule OptionNatEqtype <: EQTYPE.\n  Module OptionNat := MakeOptionReflectable(NatEqtype).\n  Definition t := OptionNat.option_eqType.\nEnd OptionNatEqtype.\n\n\n\n(** An ordered type for nat with a Boolean equality in mathcomp. *)\n\nModule NatOrderMinimal <: SsrOrderMinimal.\n\n  Definition t : eqType := nat_eqType.\n\n  Definition eqn : t -> t -> bool := fun x y : t => x == y.\n\n  Definition ltn : t -> t -> bool := fun x y => x < y.\n\n  Global Hint Unfold eqn ltn : core.\n\n  Lemma ltn_trans (x y z : t) : ltn x y -> ltn y z -> ltn x z.\n  Proof. exact: ltn_trans. Qed.\n\n  Lemma ltn_not_eqn (x y : t) : ltn x y -> x != y.\n  Proof. move=> H. by rewrite (ltn_eqF H). Qed.\n\n  Lemma compare (x y : t) : Compare ltn eqn x y.\n  Proof.\n    case H: (Nat.compare x y).\n    - apply: EQ. move: (PeanoNat.Nat.compare_eq_iff x y) => [Hc _].\n      apply/eqP. exact: (Hc H).\n    - apply: LT. move: (PeanoNat.Nat.compare_lt_iff x y) => [Hc _].\n      apply/ltP. exact: (Hc H).\n    - apply: GT. move: (PeanoNat.Nat.compare_gt_iff x y) => [Hc _].\n      apply/ltP. exact: (Hc H).\n  Defined.\n\nEnd NatOrderMinimal.\n\nModule NatOrder <: SsrOrder := MakeSsrOrder NatOrderMinimal.\n\n\n\nLtac deduce_compare_cases H :=\n  match type of H with\n  | is_true (_ < _)%N =>\n    let H1 := fresh in\n    let H2 := fresh in\n    let H3 := fresh in\n    let H4 := fresh in\n    let H5 := fresh in\n    (move: (H) => H1; rewrite ltnNge in H1);\n    (move: (H1) => H2; rewrite leq_eqVlt negb_or in H2; case/andP: H2=> H2 H3);\n    (move/negPf: H3; move/negPf: H2; move/negPf: H1; move=> H1 H2 H3);\n    (move: (ltnW H) => H4);\n    (move: (ltnW H) => /eqP H5)\n  | is_true (_ <= _)%N =>\n    let H1 := fresh in\n    let H2 := fresh in\n    let H3 := fresh in\n    (move: (H) => H1; rewrite leqNgt in H1; move/negPf: H1 => H1);\n    (move: (H); move/eqP=> H2);\n    (move: (H) => H3; rewrite leq_eqVlt in H3)\n  | (?n = ?m)%N =>\n    let H1 := fresh in\n    let H2 := fresh in\n    let H3 := fresh in\n    let H4 := fresh in\n    (move: (ltnn n) => H1; rewrite {2}H in H1);\n    (move: (ltnn m) => H2; rewrite -{2}H in H2);\n    (move: (leqnn n) => H3; rewrite {2}H in H3);\n    (move: (leqnn m) => H4; rewrite -{2}H in H4)\n  end.\n", "meta": {"author": "mht208", "repo": "coq-ssrlib", "sha": "6a3f3140a2641d74efee8dc79fa436057c98d2e4", "save_path": "github-repos/coq/mht208-coq-ssrlib", "path": "github-repos/coq/mht208-coq-ssrlib/coq-ssrlib-6a3f3140a2641d74efee8dc79fa436057c98d2e4/src/Nats.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.6665444358751532}}
{"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.\n\n(* Why3 comment *)\n(* infix_ls is replaced with (x < x1)%R by the coq driver *)\n\n(* Why3 goal *)\nLemma infix_lseq_def : forall (x:R) (y:R), (x <= y)%R <-> ((x < y)%R \\/\n  (x = y)).\nreflexivity.\nQed.\n\n(* Why3 comment *)\n(* infix_pl is replaced with (x + x1)%R by the coq driver *)\n\n(* Why3 comment *)\n(* prefix_mn is replaced with (-x)%R by the coq driver *)\n\n(* Why3 comment *)\n(* infix_as is replaced with (x * x1)%R by the coq driver *)\n\n(* Why3 goal *)\nLemma Assoc : forall (x:R) (y:R) (z:R),\n  (((x + y)%R + z)%R = (x + (y + z)%R)%R).\nProof.\nexact Rplus_assoc.\nQed.\n\n(* Why3 goal *)\nLemma Unit_def_l : forall (x:R), ((0%R + x)%R = x).\nProof.\nexact Rplus_0_l.\nQed.\n\n(* Why3 goal *)\nLemma Unit_def_r : forall (x:R), ((x + 0%R)%R = x).\nProof.\nexact Rplus_0_r.\nQed.\n\n(* Why3 goal *)\nLemma Inv_def_l : forall (x:R), (((-x)%R + x)%R = 0%R).\nProof.\nexact Rplus_opp_l.\nQed.\n\n(* Why3 goal *)\nLemma Inv_def_r : forall (x:R), ((x + (-x)%R)%R = 0%R).\nProof.\nexact Rplus_opp_r.\nQed.\n\n(* Why3 goal *)\nLemma Comm : forall (x:R) (y:R), ((x + y)%R = (y + x)%R).\nProof.\nexact Rplus_comm.\nQed.\n\n(* Why3 goal *)\nLemma Assoc1 : forall (x:R) (y:R) (z:R),\n  (((x * y)%R * z)%R = (x * (y * z)%R)%R).\nProof.\nexact Rmult_assoc.\nQed.\n\n(* Why3 goal *)\nLemma Mul_distr_l : forall (x:R) (y:R) (z:R),\n  ((x * (y + z)%R)%R = ((x * y)%R + (x * z)%R)%R).\nProof.\nintros x y z.\napply Rmult_plus_distr_l.\nQed.\n\n(* Why3 goal *)\nLemma Mul_distr_r : forall (x:R) (y:R) (z:R),\n  (((y + z)%R * x)%R = ((y * x)%R + (z * x)%R)%R).\nProof.\nintros x y z.\napply Rmult_plus_distr_r.\nQed.\n\n(* Why3 goal *)\nLemma infix_mn_def : forall (x:R) (y:R), ((x - y)%R = (x + (-y)%R)%R).\nreflexivity.\nQed.\n\n(* Why3 goal *)\nLemma Comm1 : forall (x:R) (y:R), ((x * y)%R = (y * x)%R).\nProof.\nexact Rmult_comm.\nQed.\n\n(* Why3 goal *)\nLemma Unitary : forall (x:R), ((1%R * x)%R = x).\nProof.\nexact Rmult_1_l.\nQed.\n\n(* Why3 goal *)\nLemma NonTrivialRing : ~ (0%R = 1%R).\nProof.\napply not_eq_sym.\nexact R1_neq_R0.\nQed.\n\n(* Why3 comment *)\n(* inv is replaced with (Reals.Rdefinitions.Rinv x) by the coq driver *)\n\n(* Why3 goal *)\nLemma Inverse : forall (x:R), (~ (x = 0%R)) ->\n  ((x * (Reals.Rdefinitions.Rinv x))%R = 1%R).\nexact Rinv_r.\nQed.\n\n(* Why3 goal *)\nLemma infix_sl_def : forall (x:R) (y:R),\n  ((x / y)%R = (x * (Reals.Rdefinitions.Rinv y))%R).\nreflexivity.\nQed.\n\n(* Why3 goal *)\nLemma add_div : forall (x:R) (y:R) (z:R), (~ (z = 0%R)) ->\n  (((x + y)%R / z)%R = ((x / z)%R + (y / z)%R)%R).\nProof.\nintros.\nfield.\nassumption.\nQed.\n\n(* Why3 goal *)\nLemma sub_div : forall (x:R) (y:R) (z:R), (~ (z = 0%R)) ->\n  (((x - y)%R / z)%R = ((x / z)%R - (y / z)%R)%R).\nProof.\nintros.\nfield.\nassumption.\nQed.\n\n(* Why3 goal *)\nLemma neg_div : forall (x:R) (y:R), (~ (y = 0%R)) ->\n  (((-x)%R / y)%R = (-(x / y)%R)%R).\nProof.\nintros.\nfield.\nassumption.\nQed.\n\n(* Why3 goal *)\nLemma assoc_mul_div : forall (x:R) (y:R) (z:R), (~ (z = 0%R)) ->\n  (((x * y)%R / z)%R = (x * (y / z)%R)%R).\nProof.\nintros x y z _.\napply Rmult_assoc.\nQed.\n\n(* Why3 goal *)\nLemma assoc_div_mul : forall (x:R) (y:R) (z:R), ((~ (y = 0%R)) /\\\n  ~ (z = 0%R)) -> (((x / y)%R / z)%R = (x / (y * z)%R)%R).\nProof.\nintros x y z (Zy, Zz).\nunfold Rdiv.\nrewrite Rmult_assoc.\nnow rewrite Rinv_mult_distr.\nQed.\n\n(* Why3 goal *)\nLemma assoc_div_div : forall (x:R) (y:R) (z:R), ((~ (y = 0%R)) /\\\n  ~ (z = 0%R)) -> ((x / (y / z)%R)%R = ((x * z)%R / y)%R).\nProof.\nintros x y z (Zy, Zz).\nfield.\nnow split.\nQed.\n\n(* Why3 goal *)\nLemma Refl : forall (x:R), (x <= x)%R.\nProof.\nexact Rle_refl.\nQed.\n\n(* Why3 goal *)\nLemma Trans : forall (x:R) (y:R) (z:R), (x <= y)%R -> ((y <= z)%R ->\n  (x <= z)%R).\nProof.\nexact Rle_trans.\nQed.\n\n(* Why3 goal *)\nLemma Antisymm : forall (x:R) (y:R), (x <= y)%R -> ((y <= x)%R -> (x = y)).\nProof.\nexact Rle_antisym.\nQed.\n\n(* Why3 goal *)\nLemma Total : forall (x:R) (y:R), (x <= y)%R \\/ (y <= x)%R.\nProof.\nintros x y.\ndestruct (Rle_or_lt x y) as [H|H].\nnow left.\nright.\nnow apply Rlt_le.\nQed.\n\n(* Why3 goal *)\nLemma ZeroLessOne : (0%R <= 1%R)%R.\nProof.\nexact Rle_0_1.\nQed.\n\n(* Why3 goal *)\nLemma CompatOrderAdd : forall (x:R) (y:R) (z:R), (x <= y)%R ->\n  ((x + z)%R <= (y + z)%R)%R.\nProof.\nintros x y z.\nexact (Rplus_le_compat_r z x y).\nQed.\n\n(* Why3 goal *)\nLemma CompatOrderMult : forall (x:R) (y:R) (z:R), (x <= y)%R ->\n  ((0%R <= z)%R -> ((x * z)%R <= (y * z)%R)%R).\nProof.\nintros x y z H Zz.\nnow apply Rmult_le_compat_r.\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/Real.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.6665444247863713}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint drop (drop_arg0 : natural) (drop_arg1 : lst) : lst\n           := match drop_arg0, drop_arg1 with\n              | x, Nil => Nil\n              | Zero, x => x\n              | Succ x, Cons y z => drop x z\n              end.\n\nTheorem drop_Nil: forall (x: natural), drop x Nil = Nil.\nProof.\n  induction x ; simpl; reflexivity.\nQed.\n\nTheorem drop_Cons: forall (x n: natural) (l: lst), drop (Succ x) (Cons n l) = drop x l.\n  induction l; induction x; simpl; reflexivity.\nQed.\n\nTheorem drop_Cons_assoc: forall (x1 x2 x3: natural) (l: lst),\n    drop x1 (drop x2 (Cons x3 l)) = drop x2 (drop x1 (Cons x3 l)).\nProof.\n  induction x1; induction x2; try (simpl; reflexivity).\n  + induction l.\nlfind.  rewrite <- IHx1. \nAdmitted.\n\nTheorem drop_assoc : forall (x : natural) (y : natural) (z : lst), eq (drop x (drop y z)) (drop y (drop x z)).\nProof.\n  induction z.\n  + rewrite 2 drop_Cons_assoc. reflexivity. \n  + rewrite 3 drop_Nil. reflexivity. \nQed.\n\nTheorem theorem0 : forall (x : natural) (y : natural) (w : natural) (z : lst), eq (drop w (drop x (drop y z))) (drop y (drop x (drop w z))).\nProof.\n  intros.\n  rewrite (drop_assoc w x).\n  rewrite (drop_assoc w y).\n  rewrite (drop_assoc x y).\n  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/clam_lf_goal9_drop_Cons_assoc_32_drop_Cons/goal9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6665329907837974}}
{"text": "\nRecord Cat := mkCat\n  { Obj  : Type\n  ; Hom  : Obj -> Obj -> Type\n  ; id   : forall(x : Obj), Hom x x\n  ; comp : forall{x y z : Obj}, forall(f : Hom y z), forall(g : Hom x y), Hom x z\n  ; assoc_l : forall{w x y z : Obj}, forall(f : Hom y z), forall(g : Hom x y), forall(h : Hom w x), comp (comp f g) h = comp f (comp g h)\n  ; assoc_r : forall{w x y z : Obj}, forall(f : Hom y z), forall(g : Hom x y), forall(h : Hom w x), comp f (comp g h) = comp (comp f g) h\n  ; id_l : forall{x y : Obj}, forall(f : Hom x y), comp (id y) f = f\n  ; id_r : forall{x y : Obj}, forall(f : Hom x y), comp f (id x) = f\n  ; id_id : forall(x : Obj), comp (id x) (id x) = id x\n  ; homK : forall{x y : Obj}, forall{f : Hom x y}, forall(p : f = f), p = eq_refl f\n  }.\n\nArguments Hom {c} x y.\nArguments id {c} x.\nArguments comp {c x y z} f g.\nArguments assoc_l {c w x y z} f g h.\nArguments assoc_r {c w x y z} f g h.\nArguments id_l {c x y} f.\nArguments id_r {c x y} f.\nArguments id_id {c} x.\nArguments homK {c x y f} p.\n\nDefinition Iso {C : Cat} (x y : Obj C) : Prop :=\n  exists(f : Hom x y), exists(g : Hom y x), comp f g = id y /\\ comp g f = id x.\n\nLemma equal_implies_iso {C : Cat} {x y : Obj C} :\n  x = y -> Iso x y.\nProof.\n  intro Heq. unfold Iso. destruct Heq.\n  exists (id x). exists (id x). split; exact (id_id x).\nQed.\n\nRecord Functor (A B : Cat) := mkFun\n  { Fobj  : Obj A -> Obj B\n  ; Fmph  : forall{x y : Obj A}, Hom x y -> Hom (Fobj x) (Fobj y)\n  ; Fid   : forall(x : Obj A), Fmph (id x) = id (Fobj x)\n  ; Fcomp : forall{x y z : Obj A}, forall(f : Hom y z), forall(g : Hom x y), Fmph (comp f g) = comp (Fmph f) (Fmph g)\n  }.\n\nRecord PreCategory := mkPCat\n  { pObj  : Type\n  ; pHom  : pObj -> pObj -> Type\n  ; pid   : forall(x : pObj), pHom x x\n  ; pcomp : forall{x y z : pObj}, forall(f : pHom y z), forall(g : pHom x y), pHom x z\n  ; passoc_l : forall{w x y z : pObj}, forall(f : pHom y z), forall(g : pHom x y), forall(h : pHom w x), pcomp (pcomp f g) h = pcomp f (pcomp g h)\n  ; pid_l : forall{x y : pObj}, forall(f : pHom x y), pcomp (pid y) f = f\n  ; pid_r : forall{x y : pObj}, forall(f : pHom x y), pcomp f (pid x) = f\n  ; phomK : forall{x y : pObj}, forall{f : pHom x y}, forall(p : f = f), p = eq_refl f\n  }.\nDefinition fromPreCat (C : PreCategory) : Cat :=\n  mkCat\n    (pObj C)\n    (pHom C)\n    (pid C)\n    (fun x y z => @pcomp C x y z)\n    (fun w x y z => @passoc_l C w x y z)\n    (fun w x y z f g h => eq_sym (@passoc_l C w x y z f g h))\n    (fun x y => @pid_l C x y)\n    (fun x y => @pid_r C x y)\n    (fun x => @pid_l C x x (pid C x))\n    (fun x y f => @phomK C x y f).\n\nAxiom funext : forall{A B : Type}, forall(f g : A -> B), (forall x, f x = g x) -> f = g.\nRecord S := mkS\n  { Stype : Type\n  ; Sk    : forall{x : Stype}, forall(p : x = x), p = eq_refl x\n  }.\nLemma Sfun (A B : S) : S.\nProof.\n  apply (mkS (Stype A -> Stype B)). intros f p.\n", "meta": {"author": "dwarfmaster", "repo": "categories-in-lp", "sha": "8dda2bd1a71de9c7d767ab95add0964b37028745", "save_path": "github-repos/coq/dwarfmaster-categories-in-lp", "path": "github-repos/coq/dwarfmaster-categories-in-lp/categories-in-lp-8dda2bd1a71de9c7d767ab95add0964b37028745/properties/cats.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.666532989175596}}
{"text": "Require Import FunctionalExtensionality.\n\nSection RealLine.\n\n    Variable R : Set.\n\n    Variable add : R -> R -> R.\n    Variable zero : R.\n    Hypothesis add_zero_l : forall x, add zero x = x.\n    Hypothesis add_comm   : forall x y, add x y = add y x.\n\n    Lemma add_zero_r : forall x, add x zero = x.\n      intro x.\n      transitivity (add zero x).\n      apply add_comm.\n      apply add_zero_l.\n    Qed.\n\n    Hypothesis add_assoc  : forall x y z, add x (add y z) = add (add x y) z.\n    Variable opp : R -> R.\n    Hypothesis add_opp_eq_zero : forall x, add x (opp x) = zero.\n\n    Variable mul : R -> R -> R.\n    Variable one : R.\n    Hypothesis mul_one_l  : forall x, mul one x = x.\n    Hypothesis mul_comm   : forall x y, mul x y = mul y x.\n    Hypothesis mul_assoc  : forall x y z, mul x (mul y z) = mul (mul x y) z.\n    Variable inv : R -> R.\n    Hypothesis mul_inv_eq_one : forall x, x = zero \\/ mul x (inv x) = one.\n\n    Hypothesis zero_neq_one : ~ (zero = one).\n\n    Hypothesis distr : forall x y z, mul x (add y z) = add (mul x y) (mul x z).\n    \n    Variable rlt : R -> R -> Prop.\n \n    Hypothesis ord_trich : forall x y, rlt x y \\/ x = y \\/ rlt y x.\n    Hypothesis ord_trich_lt_not_eq : forall x y, rlt x y -> ~(x = y).\n    Hypothesis ord_trich_lt_not_gt : forall x y, rlt x y -> ~(rlt y x).\n    Hypothesis ord_trich_eq_not_lt : forall x y, x = y -> ~(rlt x y).\n    Hypothesis ord_trans : forall x y z, rlt x y -> rlt y z -> rlt x z.\n    Hypothesis ord_add : forall x y z, rlt x y -> rlt (add x z) (add y z).\n    Hypothesis ord_mul : forall x y z, rlt x y -> rlt z zero -> rlt (mul x z) (mul y z).\n    \n    (* Slopes at 0 -- axioms *)\n\n    Variable slope0 : (R -> R) -> R.\n\n    Let is_slope0 (f : R -> R) (sl : R) : Prop :=\n        forall eps, mul eps eps = zero ->\n          f eps = add (f zero) (mul sl eps).\n \n    Hypothesis koch_lauvere0 : forall f : R -> R, is_slope0 f (slope0 f).\n    \n    Hypothesis slope0_unique :\n      forall f : R -> R,\n        forall sl, is_slope0 f sl -> sl = slope0 f.\n\n    (* Slopes at X0 -- lemmas *)\n\n    Let slide (f : R -> R) (x0 : R) : R -> R := fun x => f (add x x0).\n\n    Let is_slopeX0 (f : R -> R) (sl : R) (x0 : R) : Prop :=\n        forall eps, mul eps eps = zero ->\n          f (add x0 eps) = add (f x0) (mul sl eps).\n\n    Let slopeX0 (f : R -> R) (x0 : R) := slope0 (slide f x0).\n\n    Lemma koch_lauvereX0 : forall f : R -> R, forall x0 : R,\n      is_slopeX0 f (slopeX0 f x0) x0.\n    Proof.\n      intros f x0.\n      intros eps eps_nil.\n      replace (f (add x0 eps)) with (slide f x0 eps).\n        unfold slopeX0.\n        replace (f x0) with (slide f x0 zero).\n        apply koch_lauvere0. assumption.\n        unfold slide. apply f_equal. apply add_zero_l.\n        compute. apply f_equal. apply add_comm.\n    Qed.\n\n    Lemma slopeX0_unique : forall f : R -> R, forall sl: R, forall x0 : R,\n      is_slopeX0 f sl x0 -> sl = slopeX0 f x0.\n    Proof.\n      intros f sl x0 is_sl.\n      unfold is_slopeX0 in is_sl.\n      unfold slopeX0.\n      assert (is_slope0 (slide f x0) sl).\n      intro eps.\n      specialize is_sl with eps.\n      intro eps_nil.\n      replace (slide f x0 zero) with (f x0).\n        unfold slide. rewrite add_comm. apply is_sl. assumption.\n        compute; apply f_equal; symmetry; apply add_zero_l.\n      apply slope0_unique. assumption.\n    Qed.\n\n    (* Areas *)\n\n    Let two := add one one.\n    Let half := inv two.\n    Let halve x := mul x half.\n    Let is_area (area : (R -> R) -> R -> R) : Prop :=\n      forall f x eps, mul eps eps = zero ->\n        area f (add x eps) =\n        add (area f x) (halve\n                          (mul eps\n                               (add (f x) (f (add x eps))))).\n    \n    Lemma two_not_zero : not (add one one = zero).\n      intro H.\n      symmetry in H.\n      apply ord_trich_eq_not_lt in H.\n      assert (rlt zero one).\n      replace one (\n      \n    \n    Lemma halve_x_plus_x :\n      forall x, halve (add x x) = x.\n      intros.\n      unfold halve, half, two.\n      replace (add x x) with (mul x (add one one)).\n      rewrite <- mul_assoc.\n      assert (mul (add one one) (inv (add one one)) = one).\n      destruct (mul_inv_eq_one (add one one)).\n      \n      rewrite <- mul_inv_eq_one.\n      \n                                 \n    Lemma fund_thm_calc1 :\n      forall a f, is_area a -> slopeX0 (a f) = f.\n    Proof.\n      intros a f is_a.\n      apply functional_extensionality.\n      intro x0.\n      symmetry. apply slopeX0_unique.\n      unfold is_slopeX0.\n      intros eps eps_nil.\n\n      replace (add (a f x0) (mul (f x0) eps)) with\n              (add (a f x0)\n                (halve\n                  (mul eps\n                    (add (f x0) (f (add x0 eps)))))).\n      apply is_a.\n      apply eps_nil.\n      \n      assert (\n        (halve (mul eps (add (f x0) (f (add x0 eps)))))\n        =\n        (mul (f x0) eps)\n      ).\n      assert (\n        (mul eps (add (f x0)\n                      (f (add x0 eps))))\n        =\n        (add (mul (f x0) eps)\n             (mul (f x0) eps))\n      ).\n      admit.\n      rewrite H.\n\n      apply f_equal. assumption.\n\n\n      \n\nEnd RealLine.", "meta": {"author": "foones", "repo": "dharma", "sha": "bea2a54256082c9349e267caae318d20e79cf8b6", "save_path": "github-repos/coq/foones-dharma", "path": "github-repos/coq/foones-dharma/dharma-bea2a54256082c9349e267caae318d20e79cf8b6/coq/synthdiffgeom/elem_thm_calc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6665329841328423}}
{"text": "(** * Unitality *)\n\nFrom DEZ Require Export\n  Init.\n\n(** ** Left-Unital Element of a Binary Function *)\n\nFail Fail Class IsUnlElemBinFnL (A B C : Type) (X : C -> C -> Prop)\n  (x : B) (y : C) (k : B -> A -> C) : Prop :=\n  unl_elem_bin_fn_l (z : A) : X (k x z) y.\n\n(** ** Right-Unital Element of a Binary Function *)\n\nFail Fail Class IsUnlElemBinFnR (A B C : Type) (X : C -> C -> Prop)\n  (x : B) (y : C) (k : A -> B -> C) : Prop :=\n  unl_elem_bin_fn_r (z : A) : X (k z x) y.\n\n(** ** Left-Unital Element of a Left Action *)\n(** ** Left-Unital Element of an Action *)\n\nClass IsUnlElemActL (A B : Type) (X : B -> B -> Prop)\n  (x : A) (al : A -> B -> B) : Prop :=\n  unl_elem_act_l (a : B) : X (al x a) a.\n\n(** ** Right-Unital Element of a Right Action *)\n(** ** Right-Unital Element of an Action *)\n\nClass IsUnlElemActR (A B : Type) (X : B -> B -> Prop)\n  (x : A) (ar : B -> A -> B) : Prop :=\n  unl_elem_act_r (a : B) : X (ar a x) a.\n\nSection Context.\n\nContext (A B : Type) (X : B -> B -> Prop)\n  (x : A) (al : A -> B -> B).\n\n(** A left-unital element of an action is a special case\n    of a right-unital element of its flipped version. *)\n\n#[local] Instance unl_elem_act_l_is_unl_elem_act_r_flip\n  `{!IsUnlElemActL X x al} : IsUnlElemActR X x (flip al).\nProof. intros a. unfold flip in *. eauto. Qed.\n\n#[local] Instance unl_elem_act_r_flip_is_unl_elem_act_l\n  `{!IsUnlElemActR X x (flip al)} : IsUnlElemActL X x al.\nProof. intros a. unfold flip in *. eauto. Qed.\n\nEnd Context.\n\n(** ** Left-Unital Element of a Binary Operation *)\n\n(** This has the same shape as [Z.add_0_l]. *)\n\nClass IsUnlElemL (A : Type) (X : A -> A -> Prop)\n  (x : A) (k : A -> A -> A) : Prop :=\n  unl_elem_l (y : A) : X (k x y) y.\n\n(** ** Right-Unital Element of a Binary Operation *)\n\n(** This has the same shape as [Z.add_0_r]. *)\n\nClass IsUnlElemR (A : Type) (X : A -> A -> Prop)\n  (x : A) (k : A -> A -> A) : Prop :=\n  unl_elem_r (y : A) : X (k y x) y.\n\nSection Context.\n\nContext (A : Type) (X : A -> A -> Prop)\n  (x : A) (k : A -> A -> A).\n\n(** A left-unital element of a binary operation is a special case\n    of a right-unital element of its flipped version. *)\n\n#[local] Instance unl_elem_l_is_unl_elem_r_flip\n  `{!IsUnlElemL X x k} : IsUnlElemR X x (flip k).\nProof. intros y. unfold flip in *. eauto. Qed.\n\n#[local] Instance unl_elem_r_flip_is_unl_elem_l\n  `{!IsUnlElemR X x (flip k)} : IsUnlElemL X x k.\nProof. intros y. unfold flip in *. eauto. Qed.\n\nEnd Context.\n\n(** ** Unital Element of a Binary Operation *)\n\nClass IsUnlElem (A : Type) (X : A -> A -> Prop)\n  (x : A) (k : A -> A -> A) : Prop := {\n  unl_elem_is_unl_elem_l :> IsUnlElemL X x k;\n  unl_elem_is_unl_elem_r :> IsUnlElemR X x k;\n}.\n", "meta": {"author": "Tuplanolla", "repo": "dez", "sha": "c2eadc2e032094c3504ec3803c000dba4feb547e", "save_path": "github-repos/coq/Tuplanolla-dez", "path": "github-repos/coq/Tuplanolla-dez/dez-c2eadc2e032094c3504ec3803c000dba4feb547e/fowl/Is/Unital.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.6664645096068593}}
{"text": "\nRequire Export A009prop.\n\n\nInductive ex (X:Type) (P : X->Prop) : Prop :=\n  ex_intro : forall (witness:X), P witness -> ex X P.\n\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\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  intros.\n  inversion H as [m].\n  exists (2 + m).\n  apply H0.\nQed.\n\nLemma exists_example_3 :\n  exists (n:nat), even n /\\ beautiful n.\nProof.\n  exists 8. split. constructor. apply b_sum with (n:=3)(m:=5); constructor.\nQed.\n\n\n(* ex nat (fun n => beautiful (S n)). *)\n(* Means that exists a n:nat, beautiful S n.\n*)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  intros. intro.\n  inversion H0. apply H1. 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.\n  assert (P x \\/ ~P x). apply H.\n  inversion H1. assumption.\n  elimtype False. (* Ex falso quodlibet *)\n\n  apply H0.\n  exists (x). assumption.\nQed.\n\n\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n  (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n  intros.\n  split; intro.\n  inversion H. inversion H0.\n    left. exists witness. assumption.\n    right. exists witness. assumption.\n\n  inversion H; inversion H0.\n    exists witness. left. assumption.\n    exists witness. right. assumption.\nQed.\n\nInductive sumbool (A B : Prop) : Set :=\n | left : A -> sumbool A B\n | right : B -> sumbool A B.\n\nNotation \"{ A } + { B }\" := (sumbool A B) : type_scope.\n\nTheorem eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.\nProof.\n  induction n.\n  destruct m. left. reflexivity.\n              right. intro. inversion H.\n  destruct m. right. intro. inversion H.\n              destruct IHn with m.\n                left. apply f_equal. assumption.\n                right. intro. inversion H. intuition.\nQed.\n\nDefinition override' {X: Type} (f: nat->X) (k:nat) (x:X) : nat->X:=\n  fun (k':nat) => if eq_nat_dec k k' then x else f k'.\n\nTheorem override_same' : forall (X:Type) x1 k1 k2 (f : nat->X),\n  f k1 = x1 ->\n  (override' f k1 x1) k2 = f k2.\nProof.\n  unfold override'. intros.\n  destruct (eq_nat_dec k1 k2).\n    rewrite <- H. apply f_equal. assumption.\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  unfold override'. intros.\n  destruct (eq_nat_dec k1 k2).\n    reflexivity.\n    reflexivity.\nQed.\n\nInductive all {X : Type} (P : X -> Prop) : list X -> Prop :=\n  | all0 : all P []\n  | allI : forall x xs, P x -> all P xs -> all P (x :: xs).\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n    | [] => true\n    | x :: l' => andb (test x) (forallb test l')\n  end.\n\nTheorem forallb_true_imp_all :\n  forall {X} (p : X -> bool) l, forallb p l = true ->\n                                all (fun x => p x = true) l.\nProof.\n  intros.\n  induction l.\n    apply all0.\n    simpl in H.\n      destruct (p x) eqn:px.\n      assert (forallb p l = true).\n      destruct (forallb p l). reflexivity. inversion H.\n      apply IHl in H0. apply allI. assumption. assumption.\n\n      inversion H.\nQed.\n\nInductive appears_in {X:Type} (a:X) : list X -> Prop :=\n  | ai_here : forall l, appears_in a (a::l)\n  | ai_later : forall b l, appears_in a l -> appears_in a (b::l).\n\nLemma appears_in_app : forall (X:Type) (xs ys : list X) (x:X),\n     appears_in x (xs ++ ys) -> appears_in x xs \\/ appears_in x ys.\nProof.\n  intros.\n  induction xs. simpl in H. right. assumption.\n  inversion H. left. constructor.\n  apply IHxs in H1. inversion H1. subst.\n    left. constructor. assumption.\n    right. assumption.\nQed.\n\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  induction H0.\n  apply ai_here.\n  simpl. apply ai_later.\n  apply IHappears_in. left. assumption.\n\n  induction xs. simpl. assumption.\n  simpl. apply ai_later. apply IHxs. right. assumption.\nQed.\n\nDefinition disjoint {X} (xs ys : list X) : Prop :=\n  forall a, appears_in a xs -> ~appears_in a ys.\n\nInductive no_repeats {X} : list X -> Prop :=\n  | nr_null : no_repeats []\n  | nr_cons : forall x xs, no_repeats xs -> ~(appears_in x xs) -> no_repeats (x::xs).\n\nGoal forall {X} (xs ys : list X),\n       no_repeats xs ->\n       no_repeats ys ->\n       disjoint xs ys ->\n       no_repeats (xs ++ ys).\nProof.\n  intros X xs ys Hxs Hys Hdisj.\n  generalize dependent ys.\n  induction Hxs.\n\n  Case \"nr_null []\". intros.\n  assumption.\n\n  Case \"nr_cons, xs = x::xs\".\n  intros ys Hys Hdisj.\n  unfold disjoint in Hdisj.\n  simpl.\n  apply nr_cons.\n  apply IHHxs. assumption.\n  unfold disjoint. intros. apply Hdisj. apply ai_later. assumption.\n\n  intro. apply appears_in_app in H0. inversion H0.\n\n  apply H in H1. inversion H1. inversion H1. subst.\n  unfold not in Hdisj. apply Hdisj with x. apply ai_here.\n  assumption.\n\n  subst.\n  unfold not in Hdisj. apply Hdisj with x. apply ai_here. assumption.\nQed.\n\nInductive nostutter: list nat -> Prop :=\n  | ns0 : nostutter []\n  | ns1 : forall x, nostutter [x]\n  | nsc : forall x x' xs, nostutter (x'::xs) -> x' <> x -> nostutter (x::x'::xs).\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 H5; auto.\nQed.\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros.\n  induction l1. reflexivity.\n  simpl. rewrite IHl1. reflexivity.\nQed.\n\nLemma appears_in_app_split : forall (X:Type) (x:X) (l:list X),\n  appears_in x l ->\n  exists l1, exists l2, l = l1 ++ (x::l2).\nProof.\n  intros.\n  induction H.\n\n  exists []. simpl. exists l. reflexivity.\n  inversion IHappears_in as [xs0]. inversion H0 as [xs1].\n  rewrite H1. exists (b :: xs0). simpl. exists xs1. reflexivity.\nQed.\n\n(* Inductive no_repeats {X} : list X -> Prop := *)\n(*   | nr_null : no_repeats [] *)\n(*   | nr_cons : forall x xs, no_repeats xs -> ~(appears_in x xs) -> no_repeats (x::xs). *)\n\nInductive repeats {X:Type} : list X -> Prop :=\n  | rp_here  : forall x xs, appears_in x xs -> repeats (x :: xs)\n  | rp_later : forall x xs, repeats xs -> repeats (x :: xs).\n\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   lt (length l2) (length l1) ->\n   repeats l1.\nProof.\n  unfold lt.\n  induction l1 as [|x xs]. intros. inversion H1.\n  intros l2 Hem Happ Hlen.\n  destruct Hem with (appears_in x xs).\n  apply rp_here. assumption.\n  (*  so tough... i wanna give it up... 好難QAQ... *)\nAdmitted.\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).\n*)\n", "meta": {"author": "shouya", "repo": "thinking-dumps", "sha": "bfe50272459ddfca95de74a1857e2e649218584e", "save_path": "github-repos/coq/shouya-thinking-dumps", "path": "github-repos/coq/shouya-thinking-dumps/thinking-dumps-bfe50272459ddfca95de74a1857e2e649218584e/software-foundations/A010logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673223709252, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.6664645023824579}}
{"text": "(*\n  Copyright 2022 ZhengPu Shi\n  This file is part of CoqExt. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : common mathematical hierarchy structure by Module Type\n  author    : ZhengPu Shi\n  date      : 2021.05\n\n\n  refrence  :\n  1. https://en.wikipedia.org/wiki/Ring_(mathematics)\n\n  remark    :\n  1. The operations or properties below are not needed by ring structure, \n     just for convenient.\n      \n        Aeqb, Aeqdec, Aeqb_true_iff, Aeqb_false_iff\n    \n     We may construct more elegent algebra structre use Typeclasses.\n\n*)\n\nFrom Coq Require Export Ring Field.\nFrom FCS Require Export BasicConfig.\nFrom FCS Require ZExt QcExt RExt RAST.\n\n\n(* ######################################################################### *)\n(** * Scope of element *)\n\n(** New scope for field. *)\nDeclare Scope A_scope.\nDelimit Scope A_scope with A.\nOpen Scope A_scope.\n\n\n(* ######################################################################### *)\n(** * Ring Structure *)\n\n\n(** ** Ring Signature *)\nModule Type RingSig.\n  \n  (** Carrier and operations *)\n  Parameter A : Type.   (* Carrier Type *)\n  Parameter A0 : A.     (* Additive unit element *)\n  Parameter A1 : A.     (* Multiplicative unit element *)\n  Parameter Aadd : A -> A -> A.    \t(* Addition operation *)\n  Parameter Amul : A -> A -> A.     (* Multiplication operation *)\n  Parameter Aopp : A -> A.          (* Additive inverse *)\n  Parameter Aeqb : A -> A -> bool.\n  \n  (** New scope, and notations *)\n  Bind Scope A_scope with A A0 A1 Aadd Amul Aopp Aeqb.\n  \n  (** Notations for carrier operations *)\n  Notation  \"a =? b\"    := (Aeqb a b)         : A_scope.\n  Infix     \"+\"         := Aadd               : A_scope.\n  Infix     \"*\"         := Amul               : A_scope.\n  Notation  \"- a\"       := (Aopp a)           : A_scope.\n  Notation  Asub        := (fun x y => x + -y).\n  Infix     \"-\"         := Asub               : A_scope.\n\n  (** Equality is decidable *)\n  Parameter Aeqdec : forall (x y : A), {x = y} + {x <> y}.\n\n  (** Reflection of Aeq and Aeqb *)\n  Parameter Aeqb_true_iff : forall x y, (x =? y = true) <-> x = y.\n  Parameter Aeqb_false_iff : forall x y, (x =? y = false) <-> (x <> y).\n  \n  (** Ring tactic requirement *)\n  Parameter Ring_thy : ring_theory A0 A1 Aadd Amul Asub Aopp eq.\n  Add Ring Ring_thy_inst : Ring_thy.\n  \nEnd RingSig.\n\n\n(** ** Ring theory *)\n\n(** Although ring and field tactic is enough automatic, but some cases we also \n  need to manually rewrite. So, we gather and added lots of properties for \n  Ring structure. Thus, no matter what the carrier is, the unified name can be \n  used always. *)\nModule RingThy (E : RingSig).\n  Export E.\n  Notation \"0\" := A0.\n  Notation \"1\" := A1.\n  Infix \"+\" := Aadd.\n  Notation \"- x\" := (Aopp x).\n  Notation \"a - b\" := (a + (-b)).\n  \n  Lemma add_comm : forall a b : A, a + b = b + a.\n  Proof. intros. ring. Qed.\n  \n  Lemma add_assoc : forall a b c : A, (a + b) + c = a + (b + c). \n  Proof. intros. ring. Qed.\n  \n  Lemma add_0_l : forall a : A, 0 + a = a.\n  Proof. intros. ring. Qed.\n  \n  Lemma add_0_r : forall a : A, a + 0 = a.\n  Proof. intros. ring. Qed.\n  \n  Lemma add_opp_l : forall a : A, -a + a = 0.\n  Proof. intros. ring. Qed.\n  \n  Lemma add_opp_r : forall a : A, a - a = 0.\n  Proof. intros. ring. Qed.\n  \n  Lemma opp_opp : forall a : A, - - a = a.\n  Proof. intros. ring. Qed.\n  \n  Lemma add_cancel_l : forall a b1 b2 : A, a + b1 = a + b2 -> b1 = b2.\n  Proof.\n    intros.\n    rewrite <- (add_0_l b1).\n    rewrite <- (add_0_l b2).   (* 0 + b1 = 0 + b2  *)\n    rewrite <- (add_opp_l a).  (* -a + a + b1 = -a + a + b1 *)\n    rewrite ?add_assoc.        (* -a + (a + b1) = -a + (a + b2) *)\n    rewrite H. reflexivity.\n  Qed.\n  \n  Lemma add_cancel_r : forall a1 a2 b : A, a1 + b = a2 + b -> a1 = a2.\n  Proof.\n    intros.\n    rewrite <- (add_0_r a1).\n    rewrite <- (add_0_r a2).\n    rewrite <- (add_opp_r b).\n    rewrite <- ?add_assoc.\n    rewrite H. reflexivity.\n  Qed.\n  \nEnd RingThy.\n\n\n(** ** Ring on Z *)\nModule RingZ.\n\n  Export ZArith.\n  (* Open Scope Z. *)\n\n  Module Export RingDefZ : RingSig\n    with Definition A := Z\n    with Definition A0 := 0%Z\n    with Definition A1 := 1%Z\n    with Definition Aadd := Z.add\n    with Definition Amul := Z.mul\n    with Definition Aopp := Z.opp\n    with Definition Aeqb := Z.eqb\n    .\n\n    Definition A := Z.\n    Definition A0 := 0%Z.\n    Definition A1 := 1%Z.\n    Definition Aadd := Z.add.\n    Definition Amul := Z.mul.\n    Definition Aopp := Z.opp.\n    Definition Aeqb := Z.eqb.\n    \n    Definition Aeqdec := Z.eq_dec.\n    Definition Aeqb_true_iff := Z.eqb_eq.\n    Definition Aeqb_false_iff := Z.eqb_neq.\n    \n    Definition Ring_thy : ring_theory A0 A1 Aadd Amul Z.sub Aopp eq.\n      constructor; intros; try reflexivity.\n      apply Zplus_comm.\n      apply Zplus_assoc.\n      apply Z.mul_1_l.\n      apply Z.mul_comm.\n      apply Z.mul_assoc.\n      apply Z.mul_add_distr_r.\n      apply Z.add_opp_diag_r.\n    Defined.\n    \n    Add Ring Ring_thy_inst : Ring_thy.\n    \n  End RingDefZ.\n  \n  Module Export RingThyZ := RingThy RingDefZ.\n  \nEnd RingZ.\n\n\n(** ** Test for Ring on Z *)\n\nModule RingZ_test.\n\n  Import RingZ.\n  \n  Example ex2 : forall a b c d : A, \n    (a + b) * (c + d) = a * c + a * d + c * b + b * d.\n  Proof.\n    intros. ring. Qed.\n  \nEnd RingZ_test.\n\n\n(** ** Ring on Q *)\n\nModule RingQ.\n\n  Export QExt.\n  \n  (* Open Scope Q_scope. *)\n  Module Export RingDefQ : RingSig\n    with Definition A := Q\n    with Definition A0 := 0\n    with Definition A1 := 1\n    with Definition Aadd := Qplus\n    with Definition Amul := Qmult\n    with Definition Aopp := Qopp\n    with Definition Aeqb := Qeqb\n    .\n\n    Definition A := Q.\n    Definition A0 := 0.\n    Definition A1 := 1.\n    Definition Aadd := Qplus.\n    Definition Amul := Qmult.\n    Definition Aopp := Qopp.\n    Definition Aeqb := Qeqb.\n    Definition Aeqdec := Qeqdec.\n    Definition Aeqb_true_iff := Qeqb_true_iff.\n    Definition Aeqb_false_iff := Qeqb_false_iff.\n    \n    (** Ring Theory *)\n    \n    Definition Ring_thy : ring_theory A0 A1 Aadd Amul Qminus Aopp eq.\n      constructor; intros; try reflexivity; try apply Qeq_iff_eq.\n      apply Qplus_0_l.\n      apply Qplus_comm.\n      apply Qplus_assoc.\n      apply Qmult_1_l.\n      apply Qmult_comm.\n      apply Qmult_assoc.\n      apply Qmult_plus_distr_l.\n      apply Qplus_opp_r.\n    Defined.\n    \n    Add Ring Ring_thy_inst : Ring_thy.\n    \n  End RingDefQ.\n\nEnd RingQ.\n\n\n(** ** Test for Ring on Q *)\n\nModule RingQ_test.\n\n  Import RingQ.\n  Open Scope A_scope.\n  \n  Example ex2 : forall a b c d : A, \n    (a + b) * (c + d) = a * c + a * d + c * b + b * d.\n  Proof.\n    intros. ring. Qed.\n  \nEnd RingQ_test.\n\n\n(** ** Ring on Qc *)\n\nModule RingQc.\n  \n  Export QcExt.\n  (* Open Scope Qc_scope. *)\n\n  Module Export RingDefQc : RingSig\n    with Definition A := Qc\n    with Definition A0 := 0\n    with Definition A1 := 1\n    with Definition Aadd := Qcplus\n    with Definition Amul := Qcmult\n    with Definition Aopp := Qcopp\n    with Definition Aeqb := Qceqb\n    .\n\n    Definition A := Qc.\n    Definition A0 := 0.\n    Definition A1 := 1.\n    Definition Aadd := Qcplus.\n    Definition Amul := Qcmult.\n    Definition Aopp := Qcopp.\n    Definition Aeqb := Qceqb.\n    Definition Aeqdec := Qceqdec.\n    Definition Aeqb_true_iff := Qceqb_true_iff.\n    Definition Aeqb_false_iff := Qceqb_false_iff.\n    \n    (** Ring Theory *)\n    \n    Definition Ring_thy : ring_theory A0 A1 Aadd Amul Qcminus Aopp eq.\n      constructor; intros; try reflexivity.\n      apply Qcplus_0_l.\n      apply Qcplus_comm.\n      apply Qcplus_assoc.\n      apply Qcmult_1_l.\n      apply Qcmult_comm.\n      apply Qcmult_assoc.\n      apply Qcmult_plus_distr_l.\n      apply Qcplus_opp_r.\n    Defined.\n    \n    Add Ring Ring_thy_inst : Ring_thy.\n    \n  End RingDefQc.\n\nEnd RingQc.\n\n\n(** ** Test for Ring on Qc *)\n\nModule RingQc_test.\n\n  Import RingQc.\n  Open Scope A_scope.\n  \n  Example ex2 : forall a b c d : A, \n    (a + b) * (c + d) = a * c + a * d + c * b + b * d.\n  Proof.\n    intros. ring. Qed.\n  \nEnd RingQc_test.\n\n\n(** ** Ring on R *)\n\nModule RingR.\n\n  Export Reals RExt.\n  Open Scope R.\n\n  Module Export RingDefR : RingSig\n    with Definition A := R\n    with Definition A0 := R0\n    with Definition A1 := R1\n    with Definition Aadd := Rplus\n    with Definition Amul := Rmult\n    with Definition Aopp := Ropp\n    with Definition Aeqb := Reqb\n    .\n    \n    Definition A := R.\n    Definition A0 := R0.\n    Definition A1 := R1.\n    Definition Aadd := Rplus.\n    Definition Amul := Rmult.\n    Definition Aopp := Ropp.\n    \n    (** Ring Theory *)\n    \n    Definition Ring_thy : ring_theory A0 A1 Aadd Amul Rminus Aopp eq.\n      constructor; intros; cbv; ring. Defined.\n    \n    Add Ring Ring_thy_inst : Ring_thy.\n\n    Definition Aeqb r1 r2 := Reqb r1 r2.\n    Definition Aeqdec := Req_EM_T.\n    Definition Aeqb_true_iff := Reqb_true_iff.\n    Definition Aeqb_false_iff := Reqb_false_iff.\n\n  End RingDefR.\n\nEnd RingR.\n\n\n(** ** Test for Ring on R *)\n\nModule RingR_test.\n\n  Import RingR.\n  Open Scope A_scope.\n\n  Example ex2 : forall a b c d : A, \n    (a + b) * (c + d) = (a * c + a * d + c * b + b * d).\n  Proof.\n    intros. ring. Qed.\n  \nEnd RingR_test.\n\n\n(** ** Ring on T *)\n\nModule RingT.\n\n  Export RAST.\n  Open Scope T.\n\n  Module Export RingDefT : RingSig\n    with Definition A := T\n    with Definition A0 := T0\n    with Definition A1 := T1\n    with Definition Aadd := Tadd\n    with Definition Amul := Tmul\n    with Definition Aopp := Topp\n    with Definition Aeqb := Teqb\n    .\n    \n    Definition A := T.\n    Definition A0 := T0.\n    Definition A1 := T1.\n    Definition Aadd := Tadd.\n    Definition Amul := Tmul.\n    Definition Aopp := Topp.\n    \n    (** Ring Theory *)\n    \n    Definition Ring_thy := T_ring.\n    Add Ring Ring_thy_inst : Ring_thy.\n\n    Definition Aeqb r1 r2 := Teqb r1 r2.\n    Definition Aeqdec := Teqdec.\n    Axiom Teqb_true_iff : forall x y : T, (x =? y)%T = true <-> x = y.\n    Axiom Teqb_false_iff : forall x y : T, (x =? y)%T = false <-> x <> y.\n    Definition Aeqb_true_iff := Teqb_true_iff.\n    Definition Aeqb_false_iff := Teqb_false_iff.\n\n  End RingDefT.\n\nEnd RingT.\n\n\n(** ** Test for Ring on T *)\n\nModule RingT_test.\n\n  Import RingT.\n\n  Open Scope T.\n  Example ex1 : forall a b c d : T, \n    (a + b) * (c + d) = a * c + a * d + c * b + b * d.\n  Proof. intros. ring. Qed.\n\n  Open Scope A_scope.\n  Example ex2 : forall a b c d : A, \n    (a + b) * (c + d) = (a * c + a * d + c * b + b * d).\n  Proof.\n    intros. ring. Qed. \n  \nEnd RingT_test.\n\n\n(* ######################################################################### *)\n(** * Field Signature *)\n\n\n(** ** Signature for field *)\nModule Type FieldSig <: RingSig.\n  \n  (** Carrier *)\n  Parameter A : Type.\n  \n  (** Operations *)\n  Parameter A0 A1 : A.\n  Parameter Aadd Amul : A -> A -> A.\n  Parameter Aopp Ainv : A -> A.\n  Parameter Aeqb : A -> A -> bool.\n  \n  (** Notations *)\n  Notation \"0\" := A0 : A_scope.\n  Notation \"1\" := A1 : A_scope.\n  Infix \"+\" := Aadd : A_scope.\n  Infix \"*\" := Amul : A_scope.\n  Notation \"- a\" := (Aopp a) : A_scope.\n  Notation \"/ a\" := (Ainv a) : A_scope.\n  Notation Asub := (fun x y => x + -y).\n  Notation Adiv := (fun x y => x * /y).\n  Infix \"-\" := Asub : A_scope.\n  Infix \"/\" := Adiv : A_scope.\n  Notation \"a =? b\" := (Aeqb a b) (at level 70) : A_scope.\n  \n  (** Bind something to the scope *)\n  Bind Scope A_scope with A A0 A1 Aadd Amul Aopp Ainv Aeqb.\n\n  (** Properties *)\n\n  (** Equality is decidable *)\n  Parameter Aeqdec : forall (x y : A), {x = y} + {x <> y}.\n\n  (** Reflection of Aeq and Aeqb *)\n  Parameter Aeqb_true_iff : forall x y, (x =? y = true) <-> x = y.\n  Parameter Aeqb_false_iff : forall x y, (x =? y = false) <-> (x <> y).\n  \n  (** 1 <> 0. *)\n  Parameter A1_neq_A0 : A1 <> A0.\n  \n  (** Ring theory *)\n  Parameter Ring_thy : ring_theory A0 A1 Aadd Amul Asub Aopp eq.\n  Add Ring Ring_thy_inst : Ring_thy.\n\n  (** Field Theory *)\n  Parameter Field_thy: field_theory A0 A1 Aadd Amul Asub Aopp Adiv Ainv eq.\n  Add Field Field_thy_inst : Field_thy.\n\nEnd FieldSig.\n\n\n(** ** Field theory *)\n\nModule FieldThy (E : FieldSig).\n\n  Export E.\n\n  Open Scope A_scope.\n\n  Lemma add_comm : forall a b, a + b = b + a.\n  Proof. intros. ring. Qed.\n  \n  Lemma add_assoc : forall a b c, (a + b) + c = a + (b + c). \n  Proof. intros. ring. Qed.\n  \n  Lemma add_0_l : forall a, 0 + a = a.\n  Proof. intros. ring. Qed.\n  \n  Lemma add_0_r : forall a, a + 0 = a.\n  Proof. intros. ring. Qed.\n  \n  Lemma add_opp_l : forall a, -a + a = 0.\n  Proof. intros. ring. Qed.\n  \n  Lemma add_opp_r : forall a, a - a = 0.\n  Proof. intros. ring. Qed.\n  \n  Lemma opp_opp : forall a, - - a = a.\n  Proof. intros. ring. Qed.\n  \n  Lemma add_cancel_l : forall a b1 b2, a + b1 = a + b2 -> b1 = b2.\n  Proof.\n    intros.\n    rewrite <- (add_0_l b1).\n    rewrite <- (add_0_l b2).   (* 0 + b1 = 0 + b2  *)\n    rewrite <- (add_opp_l a).  (* -a + a + b1 = -a + a + b1 *)\n    rewrite ?add_assoc.        (* -a + (a + b1) = -a + (a + b2) *)\n    rewrite H. reflexivity.\n  Qed.\n  \n  Lemma add_cancel_r : forall a1 a2 b, a1 + b = a2 + b -> a1 = a2.\n  Proof.\n    intros. rewrite <- (add_0_r a1). rewrite <- (add_0_r a2).\n    rewrite <- (add_opp_r b). rewrite <- ?add_assoc. rewrite H. auto.\n  Qed.\n  \n  Lemma mul_comm : forall a b, a * b = b * a.\n  Proof. intros. ring. Qed.\n  \n  Lemma mul_assoc : forall a b c, (a * b) * c = a * (b * c). \n  Proof. intros. ring. Qed.\n  \n  Lemma mul_0_l : forall a, 0 * a = 0.\n  Proof. intros. ring. Qed.\n  \n  Lemma mul_0_r : forall a, a * 0 = 0.\n  Proof. intros. ring. Qed.\n  \n  Lemma mul_1_l : forall a, 1 * a = a.\n  Proof. intros. ring. Qed.\n  \n  Lemma mul_1_r : forall a, a * 1 = a.\n  Proof. intros. ring. Qed.\n  \n  Lemma mul_inv_l : forall a, a <> 0 -> /a * a = 1.\n  Proof. intros. field. auto. Qed.\n  \n  Lemma mul_inv_r : forall a, a <> 0 -> a / a = 1.\n  Proof. intros. field. auto. Qed.\n  \n  Lemma inv_inv : forall a, a <> 0 -> //a = a.\n  Proof. intros. field. split; auto. apply A1_neq_A0. Qed.\n  \n  Lemma mul_cancel_l : forall a b1 b2, a <> 0 -> a * b1 = a * b2 -> b1 = b2.\n  Proof.\n    intros. rewrite <- (mul_1_l b1). rewrite <- (mul_1_l b2).\n    rewrite <- (mul_inv_l a); auto. rewrite ?mul_assoc. f_equal. auto.\n  Qed.\n  \n  Lemma mul_cancel_r : forall a1 a2 b, b <> 0 -> a1 * b = a2 * b -> a1 = a2.\n  Proof.\n    intros. rewrite <- (mul_1_r a1). rewrite <- (mul_1_r a2).\n    rewrite <- (mul_inv_r b); auto. rewrite <- ?mul_assoc. f_equal. auto.\n  Qed.\n  \nEnd FieldThy.\n\n\n\n(** ** Field on Qc *)\n\nModule FieldQc.\n  \n  Export QcExt.\n  Open Scope Qc_scope.\n  \n  Module Export FieldDefQc : FieldSig\n    with Definition A := Qc\n    with Definition A0 := 0\n    with Definition A1 := 1\n    with Definition Aadd := Qcplus\n    with Definition Aopp := Qcopp\n    with Definition Amul := Qcmult\n    with Definition Ainv := Qcinv\n    with Definition Aeqb := Qceqb.\n    \n    Definition A := Qc.\n    Definition A0 := 0.\n    Definition A1 := 1.\n    Definition Aadd := Qcplus.\n    Definition Aopp := Qcopp.\n    Definition Amul := Qcmult.\n    Definition Ainv := Qcinv.\n    Definition Aeqb := Qceqb.\n    Definition Aeqdec := Qceqdec.\n    Definition Aeqb_true_iff := Qceqb_true_iff.\n    Definition Aeqb_false_iff := Qceqb_false_iff.\n    \n    Lemma A1_neq_A0 : A1 <> A0.\n    Proof. intro. discriminate. Qed.\n    \n    Lemma Ring_thy : ring_theory A0 A1 Aadd Amul Qcminus Aopp eq.\n    Proof.\n      constructor; intros; try auto.\n      apply Qcplus_0_l. apply Qcplus_comm. apply Qcplus_assoc.\n      apply Qcmult_1_l. apply Qcmult_comm. apply Qcmult_assoc.\n      apply Qcmult_plus_distr_l. apply Qcplus_opp_r.\n    Qed.\n    Add Ring Ring_thy_inst : Ring_thy.\n    \n    Lemma Field_thy : field_theory A0 A1 Aadd Amul Qcminus Aopp Qcdiv \n      Ainv eq.\n    Proof.\n      constructor; try easy. apply Ring_thy.\n      intros. rewrite Qcmult_comm,Qcmult_inv_r; auto.\n    Qed.\n    Add Field Field_thy_inst : Field_thy.\n\n  End FieldDefQc.\n\n  Module Export FieldThyQc := FieldThy FieldDefQc.\n\nEnd FieldQc.\n\n\n(** ** Test for FieldQc *)\nModule FieldQc_test.\n\n  Import FieldQc.\n  Open Scope A_scope.\n\n  Goal forall a b c : A, (c<>0) -> (a + b) / c = a / c + b / c.\n  Proof. intros. field. auto. Qed.\n\n  Goal forall a b, a <> 0 -> /a * a * b = b.\n  Proof. intros. rewrite mul_inv_l. field. auto. Qed.\n\nEnd FieldQc_test.\n\n\n(** ** Field on R *)\n\nModule FieldR.\n  \n  Export RExt.\n  Open Scope R_scope.\n\n  Module Export FieldDefR : FieldSig\n    with Definition A := R\n    with Definition A0 := 0\n    with Definition A1 := 1\n    with Definition Aadd := Rplus\n    with Definition Aopp := Ropp\n    with Definition Amul := Rmult\n    with Definition Ainv := Rinv\n    with Definition Aeqb := Reqb.\n    \n    Definition A := R.\n    Definition A0 := 0.\n    Definition A1 := 1.\n    Definition Aadd := Rplus.\n    Definition Aopp := Ropp.\n    Definition Amul := Rmult.\n    Definition Ainv := Rinv.\n    Definition Aeqb := Reqb.\n    Definition Aeqdec := Req_EM_T.\n    Definition Aeqb_true_iff := Reqb_true_iff.\n    Definition Aeqb_false_iff := Reqb_false_iff.\n    \n    Lemma A1_neq_A0 : A1 <> A0.\n    Proof. intro. auto with R. Qed.\n    \n    Lemma Ring_thy : ring_theory A0 A1 Aadd Amul Rminus Aopp eq.\n    Proof. constructor; intros; cbv; ring. Qed.\n    Add Ring Ring_thy_inst : Ring_thy.\n    \n    Lemma Field_thy : field_theory A0 A1 Aadd Amul Rminus Aopp Rdiv Ainv eq.\n    Proof.\n      constructor; try easy. apply Ring_thy. apply A1_neq_A0.\n      intros; cbv; field; auto.\n    Qed.\n    Add Field Field_thy_inst : Field_thy.\n\n  End FieldDefR.\n\n  Module Export FieldThyR := FieldThy FieldDefR.\n\nEnd FieldR.\n\n(** ** Test for FieldR *)\nModule FieldR_test.\n\n  Import FieldR.\n  Open Scope A_scope.\n\n  Goal forall a b c : A, (c<>0) -> (a + b) / c = a / c + b / c.\n  Proof. intros. field. auto. Qed.\n\nEnd FieldR_test.\n\n\n(** ** Field on T *)\n\nModule FieldT.\n  \n  Export RAST.\n  Open Scope T_scope.\n  \n  Module Export FieldDefT : FieldSig\n    with Definition A := T\n    with Definition A0 := T0\n    with Definition A1 := T1\n    with Definition Aadd := Tadd\n    with Definition Aopp := Topp\n    with Definition Amul := Tmul\n    with Definition Ainv := Tinv\n    with Definition Aeqb := Teqb.\n    \n    Axiom Teqb_true_iff : forall x y : T, (x =? y)%T = true <-> x = y.\n    Axiom Teqb_false_iff : forall x y : T, (x =? y)%T = false <-> x <> y.\n    \n    Definition A := T.\n    Definition A0 := T0.\n    Definition A1 := T1.\n    Definition Aadd := Tadd.\n    Definition Aopp := Topp.\n    Definition Amul := Tmul.\n    Definition Ainv := Tinv.\n    Definition Aeqb := Teqb.\n    Definition Aeqdec := Teqdec.\n    Definition Aeqb_true_iff := Teqb_true_iff.\n    Definition Aeqb_false_iff := Teqb_false_iff.\n    \n    Lemma A1_neq_A0 : A1 <> A0.\n    Proof. intro. easy. Qed.\n    \n    Lemma Ring_thy : ring_theory A0 A1 Aadd Amul Tsub Aopp eq.\n    Proof. constructor; intros; cbv; ring. Qed.\n    Add Ring Ring_thy_inst : Ring_thy.\n    \n    Lemma Field_thy : field_theory A0 A1 Aadd Amul Tsub Aopp Tdiv Ainv eq.\n    Proof.\n      constructor; try easy. apply Ring_thy.\n      intros; cbv; field; auto.\n    Qed.\n    Add Field Field_thy_inst : Field_thy.\n\n  End FieldDefT.\n  \n  Module Export FieldThyT := FieldThy FieldDefT.\n\nEnd FieldT.\n\n(** ** Test for FieldR *)\nModule FieldT_test.\n\n  Import FieldT.\n  Open Scope A_scope.\n\n  Goal forall a b c : A, (c<>0) -> (a + b) / c = a / c + b / c.\n  Proof. intros. field. auto. Qed.\n\nEnd FieldT_test.\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/CoqExt/Hierarchy_ModuleType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933403143929, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.6664644967373844}}
{"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 Field_theory.\n\n(** * Vector spaces *)\n\nSection Vector_Spaces.\n  Variable (R:Type)\n    (rO:R) (rI:R)\n    (radd rmul rsub : R -> R -> R)\n    (ropp : R -> R)\n    (rdiv : R -> R -> R)\n    (rinv : R -> R)\n    (req : R -> R -> Prop)\n  .\n  Variable Rfield : field_theory rO rI radd rmul rsub ropp rdiv rinv req.\n  Variable (V:Type) (vO:V).\n  Variable vadd : V->V->V.\n  Variable smul : R->V->V.\n  \n  Record vector_space : Type := {\n    vadd_comm := forall x y, vadd x y = vadd y x;\n    vadd_assoc := forall x y z, vadd (vadd x y) z = vadd x (vadd y z);\n    vadd_identity := forall x, vadd vO x = x;\n    vadd_inverse := forall x, exists y, vadd x y = vO;\n  \n    smul_distr_vadd := forall a x y, smul a (vadd x y) = vadd (smul a x) (smul a y);\n    smul_distr_radd := forall a b x, smul (radd a b) x = vadd (smul a x) (smul b x);\n    smul_compat_rmul := forall a b x, smul a (smul b x) = smul (rmul a b) x;\n    smul_identity := forall x, smul rI x = x\n  }.\n  \n  Fixpoint finite_sum (n:nat) (v:nat->V) {struct n} := match n with\n    | 0 => vO\n    | S i => vadd (v n) (finite_sum i v)\n  end.\n  \n  Record Basis (I:Type) (Xi:I->V) : Prop := {\n    basis_spanning : forall x:V, exists n, exists vn : nat -> I,\n      x = finite_sum n (fun n => Xi (vn n));\n    basis_linear_independence : forall n (vn : nat->I) (an : nat->R),\n      (forall i j , i<=n -> j<=n -> vn i = vn j -> i=j) ->\n      finite_sum n (fun m => Xi (vn m)) = vO ->\n      forall i, i<=n -> an i = rO\n  }.\n   \nEnd Vector_Spaces.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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/Topology/Vectors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.6664644915109675}}
{"text": "(** * 基础: Coq中的函数式编程 *)\n\n(* 提示:\n\n          #####################################################\n          ###               请勿公开发布解答                 ###\n          #####################################################\n\n   (原因参见[序言]。)\n*)\n\n(* ################################################################# *)\n(** * 引言 *)\n\n(** 函数式编程是建立在一个简单的日常数学直感之上的: 如果一个过程或方法\n    没有任何副作用，那么（不考虑效率）我们只需要了解它是如何把输入映射到\n    结果的————也就是说，我们可以就把它当作一个具体的计算数学函数的方法。\n    这是“函数式编程”中“函数式”一词的一层原因。程序和简单数学对象之间的\n    直接联系使得关于程序行为的形式的正确性证明和完备的非形式推导成为可能。\n\n    函数式编程之所以是“函数式”的另一层原因在于它强调了把函数（或方法）作为\n    _第一类_值————亦即那些可以被当作实参传递给其他函数，作为返回值，作为\n    数据结构的一部分等等的值。把函数当作数据使得大量实用且强大的编程惯用法\n    得以诞生。\n\n    函数式语言的其他常见特征包括_代数数据类型_和_模式匹配_，它们让创建和\n    操作丰富的数据结构变得更简单。还有支持抽象化和代码重用的复杂的_多态类\n    型系统_。Coq提供所有这些特性。\n    \n    本章的前半介绍Coq的函数式编程语言最基础的组件，_Gallina_。后半介绍一\n    些基本的_策略_，它们可以用来证明Coq程序的性质。*)\n\n(* ################################################################# *)\n(** * 数据与函数 *)\n(* ================================================================= *)\n(** ** 枚举类型 *)\n\n(** Coq一个值得一提的特征就是，它的自带特性_极其_少。举例来说，它并没有提\n    供原子数据类型（布尔，整数，字符串等），而是提供了一个强大的机制来从头\n    定义新数据类型。我们熟悉的这些类型就是例子。\n\n    Coq的发行版自然预载了包含布尔值，数值以及很多常见数据类型定义（如列表\n    和哈希表）的标准库。但这些库中的定义并没有任何神奇或是原始之处。为了证明\n    这一点，我们将回顾在这一课中需要的所有定义，而不是直接从标准库中直接\n    取用。 *)\n\n(* ================================================================= *)\n(** ** 一周之中的日子 *)\n\n(** 为了理解这个定义机制是如何运作的，我们从一个简单的例子开始。下面的定义\n    告诉Coq我们正在定义一套新的数据值————_类型_。 *)\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(** 这个类型叫作[day]， 它的成员有[monday]，[tuesday]等等。第二行开始可以念\n    成“[monday]是一个[day]，[tuesday]是一个[day]...”。\n    \n    定义[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(** 需要注意的一点是，这里的参数和返回类型都是显式定义的。就像大多数函数式语言\n    一样，如果没有显式定义的话，Coq通常可以自己推断出这些类型————也就是说它可\n    以进行_类型推断_————但为了可读性我们通常会加上它们。*)\n\n(** 定义了函数之后，我们应该检查它能否通过一些测试。在Coq中你有三种方法来测试。\n    第一种是用[Compute]命令来求一个使用了[next_weekday]函数的复合表达式的值。*)\n\nCompute (next_weekday friday).\n(* ==> monday : day *)\n\nCompute (next_weekday (next_weekday saturday)).\n(* ==> tuesday : day *)\n\n(** (我们会在注释中写出Coq的输出结果。但如果你手边就有电脑的话，不妨在你最喜欢\n    的IDE里启动Coq的解释器————CoqIde或者Proof General————来自己尝试这些例子。\n    载入这个文件，[Basics_chs.v]，找到上面的例子，提交给Coq，然后观察结果。)\n\n    第二种是用Coq example的形式记录下我们_想要的_结果： *)\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\n(** 这个声明做了两件事：首先它做了一个断言（[saturday]之后的第二个工作日是\n    [tuesday]），然后它给了这个断言一个名字，这样你以后就可以再使用它了。做\n    了这个断言之后，我们就可以像这样让Coq来验证：*)\n\nProof. simpl. reflexivity.  Qed.\n\n(** 细节暂时并不重要（我们之后会提到一点的），但这基本上可以念成“我们刚做的\n    断言可以这样证明：在一些简化之后，观察到等式两边的值相同。”\n\n    第三种是让Coq从我们的[定义]中_提取_出一个使用一些更传统的，并且具有更好\n    的编译器的编程语言（OCaml，Scheme或是Haskell）的程序。这一功能十分有趣，\n    因为它能把我们在Gallina中写的证明过正确性的算法转换成高效的机器码。（当然，\n    我们相信OCaml/Scheme/Haskell编译器，以及Coq提取功能的正确性，但这仍然是\n    与大多数软件的开发方式有很大不同的。）事实上，这是开发Coq的主要用途之一。\n    在后面的章节我们会回到这个话题。*)\n\n(* ================================================================= *)\n(** ** 提交作业的指南 *)\n\n(** 如果你在课程中使用本书，你的老师可能会用一个脚本来给你的作业打分。为了使\n    这些脚本能正确打分（这样你才能有成绩！），请小心遵守如下的准则：\n      - 评分脚本可能是通过提取标记过的区域来打分的。所以请你不要修改限定习题的\n        “标记”：比如习题的标题，名字，结尾的“空白方块”等。不要修改这些标记。\n      - 不要删除习题。如果你不想做某个题（比如它是选做的，或者你不会做），你可\n        以让你的证明处于未完成的状态。但这时请确保它最后有[Admitted]（而不是\n        [Abort]之类的）。 *)\n\n(* ================================================================= *)\n(** ** 布尔 *)\n\n(** 类似地，我们可以定义布尔类型[bool]。它有两个成员，[true]和[false]。*)\n\nInductive bool : Type :=\n  | true : bool\n  | false : bool.\n\n(** 尽管我们为了从头建立一切而定义了布尔，Coq是有自己的布尔实现和一整套有用的\n    函数和引理的。（感兴趣的话可以看看Coq库文档里的[Coq.Init.Datatypes]。）\n    我们会尽可能让我们自己的定义以及定理和标准库里的重名。 \n    \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(** 最后两个定义展示了Coq定义多参数函数的语法。调用多参数函数的语法可以参见下面的\n    “单元测试”。它们为[orb]函数提供了一个完整的规格————真值表。*)\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(** 我们还可以为刚定义的这些布尔函数引入一些熟悉的语法。[Infix]命令可以为一个既存\n的定义指定一个新的符号表示。 *)\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(** _关于符号的说明_: 在[.v]文件中, 我们用方括号来分隔注释中的Coq代码。文档工具\n    [coqdoc]也使用这一规则，这样就把它们和周围的文字区分开了。在HTML版中，这些文\n    字会用[不同字体]显示。\n\n    [Admitted]命令可以在不完整的证明中作为占位符。我们会在习题中使用它，借此来告\n    诉你我们把它留给你了————你需要把[Admitted]改成实际的证明。*)\n\n(** **** 练习: 1星 (nandb)  *)\n(** 删掉“[Admitted.]”并完成该函数的定义；然后确保[Example]断言可以被Coq验证。（删\n    掉“[Admitted.]”，照着上面[orb]的例子完成每个证明。）该函数在至少一个输入为\n    [false]时返回[true]。*)\n\nDefinition nandb (b1:bool) (b2:bool) : bool\n  (* 把这行换成 “:= _你的定义_ .” *). Admitted.\n\nExample test_nandb1:               (nandb true false) = true.\n(* 填空 *) Admitted.\nExample test_nandb2:               (nandb false false) = true.\n(* 填空 *) Admitted.\nExample test_nandb3:               (nandb false true) = true.\n(* 填空 *) Admitted.\nExample test_nandb4:               (nandb true true) = false.\n(* 填空 *) Admitted.\n(** [] *)\n\n(** **** 练习: 1星 (andb3)  *)\n(** 类似地，给[andb3]函数完成定义和断言。 该函数在全部输入均为[true]时返回[true]，\n    否则返回[false]。 *)\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool\n  (* 把这行换成 “:= _你的定义_ .” *). Admitted.\n\nExample test_andb31:                 (andb3 true true true) = true.\n(* 填空 *) Admitted.\nExample test_andb32:                 (andb3 false true true) = false.\n(* 填空 *) Admitted.\nExample test_andb33:                 (andb3 true false true) = false.\n(* 填空 *) Admitted.\nExample test_andb34:                 (andb3 true true false) = false.\n(* 填空 *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** 函数类型 *)\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(** ** Compound Types *)\n\n(** The types we have defined so far are examples of \"enumerated\n    types\": their definitions explicitly enumerate a finite set of\n    elements, each of which is just a bare constructor.  Here is a\n    more interesting type definition, where one of the constructors\n    takes an argument: *)\n\nInductive rgb : Type :=\n  | red : rgb\n  | green : rgb\n  | blue : rgb.\n\nInductive color : Type :=\n  | black : color\n  | white : color\n  | primary : rgb -> color.\n\n(** Let's look at this in a little more detail.\n\n    Every inductively defined type ([day], [bool], [rgb], [color],\n    etc.) contains a set of _constructor expressions_ built from\n    _constructors_ like [red], [primary], [true], [false], [monday],\n    etc.  The definitions of [rgb] and [color] say how expressions in\n    the sets [rgb] and [color] can be built:\n\n    - [reg], [green], and [blue] are the constructors of [rgb];\n    - [black], [white], and [primary] are the constructors of [color];\n    - the expression [red] belongs to the set [rgb], as do the\n      expressions [green] and [blue];\n    - the expressions [black] and [white] belong to the set [color];\n    - if [p] is an expression belonging to the set [rgb], then\n      [primary p] (pronounced \"the constructor [primary] applied to\n      the argument [p]\") is an expression belonging to the set\n      [color]; and\n    - expressions formed in these ways are the _only_ ones belonging\n      to the sets [rgb] and [color]. *)\n\n(** We can define functions on colors using pattern matching just as\n    we have done for [day] and [bool]. *)\n\nDefinition monochrome (c : color) : bool :=\n  match c with\n  | black => true\n  | white => true\n  | primary p => false\n  end.\n\n(** Since the [primary] constructor takes an argument, a pattern\n    matching [primary] should include either a variable (as above) or\n    a constant of appropriate type (as below). *)\n\nDefinition isred (c : color) : bool :=\n  match c with\n  | black => false\n  | white => false\n  | primary red => true\n  | primary _ => false\n  end.\n\n(** The pattern [primary _] here is shorthand for \"[primary] applied\n    to any [rgb] constructor except [red].\"  (The wildcard pattern [_]\n    has the same effect as the dummy pattern variable [p] in the\n    definition of [monochrome].) *)\n\n(* ================================================================= *)\n(** ** 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(** An even more interesting way of defining a type is to allow its\n    constrctors to take arguments from the very same type -- that is,\n    to allow the rules describing its elements to be _inductive_.\n\n    For example, we can define (a unary representation of) natural\n    numbers as follows: *)\n\nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\n(** The clauses of this definition can be read:\n      - [O] is a natural number (note that this is the letter \"[O],\"\n        not the numeral \"[0]\").\n      - [S] can be put in front of a natural number to yield another\n        one -- if [n] is a natural number, then [S n] is too. *)\n\n(** Again, let's look at this in a little more detail.  The definition\n    of [nat] says how expressions in the set [nat] can be built:\n\n    - [O] and [S] are constructors;\n    - the expression [O] belongs to the set [nat];\n    - if [n] is an expression belonging to the set [nat], then [S n]\n      is also an expression belonging to the set [nat]; and\n    - expressions formed in these two ways are the only ones belonging\n      to the set [nat]. *)\n\n(** The same rules apply for our definitions of [day], [bool],\n    [color], etc.\n\n    The above conditions are the precise force of the [Inductive]\n    declaration.  They imply that the expression [O], the expression\n    [S O], the expression [S (S O)], the expression [S (S (S O))], and\n    so on all belong to the set [nat], while other expressions built\n    from data constructors, like [true], [andb true false], [S (S\n    false)], and [O (O (O S))] do not.\n\n    A critical point here is that what we've done so far is just to\n    define a _representation_ of numbers: a way of writing them down.\n    The names [O] and [S] are arbitrary, and at this point they have\n    no special meaning -- they are just two different marks that we\n    can use to write down numbers (together with a rule that says any\n    [nat] will be written as some string of [S] marks followed by an\n    [O]).  If we like, we can write essentially the same definition\n    this way: *)\n\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\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 *)\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n    | O => O\n    | S O => O\n    | S (S n') => n'\n  end.\n\nCompute (minustwo 4).\n  (* ===> 2 : nat *)\n\n(** The constructor [S] has the type [nat -> nat], just like \n    [pred] and functions like [minustwo]: *)\n\nCheck S.\nCheck pred.\nCheck minustwo.\n\n(** These are all things that can be applied to a number to yield a\n    number.  However, there is a fundamental difference between the\n    first one and the other two: functions like [pred] and [minustwo]\n    come with _computation rules_ -- e.g., the definition of [pred]\n    says that [pred 2] can be simplified to [1] -- while the\n    definition of [S] has no such behavior attached.  Although it is\n    like a function in the sense that it can be applied to an\n    argument, it does not _do_ anything at all!  It is just a way of\n    writing down numbers.  (Think about standard 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(** Again, the _ in the first line is a _wildcard pattern_.  Writing\n    [_] in a pattern is the same as writing some variable that doesn't\n    get used on the right-hand side.  This avoids the need to invent a\n    variable 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(** **** 练习: .星 (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  (* 把这行换成 “:= _你的定义_ .” *). Admitted.\n\nExample test_factorial1:          (factorial 3) = 6.\n(* 填空 *) Admitted.\nExample test_factorial2:          (factorial 5) = (mult 10 12).\n(* 填空 *) Admitted.\n(** [] *)\n\n(** We can make numerical expressions a little easier to read and\n    write by introducing _notations_ for addition, multiplication, and\n    subtraction. *)\n\nNotation \"x + y\" := (plus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x - y\" := (minus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x * y\" := (mult x y)\n                       (at level 40, left associativity)\n                       : nat_scope.\n\nCheck ((0 + 1) + 1).\n\n(** (The [level], [associativity], and [nat_scope] annotations\n    control how these notations are treated by Coq's parser.  The\n    details are not important for our purposes, but interested readers\n    can refer to the optional \"More on Notation\" section at the end of\n    this chapter.)\n\n    Note that these do not change the definitions we've already made:\n    they are simply instructions to the Coq parser to accept [x + y]\n    in place of [plus x y] and, conversely, to the Coq pretty-printer\n    to display [plus x y] as [x + y]. *)\n\n(** When we say that Coq comes with almost nothing built-in, we really\n    mean it: even equality testing for numbers is a user-defined\n    operation!  We now define a function [beq_nat], which tests\n    [nat]ural numbers for [eq]uality, yielding a [b]oolean.  Note the\n    use of nested [match]es (we could also have used a simultaneous\n    match, as we did in [minus].) *)\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\n(** The [leb] function tests whether its first argument is less than or\n  equal to its second argument, yielding a boolean. *)\n\nFixpoint leb (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => leb n' m'\n      end\n  end.\n\nExample test_leb1:             (leb 2 2) = true.\nProof. simpl. reflexivity.  Qed.\nExample test_leb2:             (leb 2 4) = true.\nProof. simpl. reflexivity.  Qed.\nExample test_leb3:             (leb 4 2) = false.\nProof. simpl. reflexivity.  Qed.\n\n(** **** 练习: .星 (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  (* 把这行换成 “:= _你的定义_ .” *). Admitted.\n\nExample test_blt_nat1:             (blt_nat 2 2) = false.\n(* 填空 *) Admitted.\nExample test_blt_nat2:             (blt_nat 2 4) = true.\n(* 填空 *) Admitted.\nExample test_blt_nat3:             (blt_nat 4 2) = false.\n(* 填空 *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Proof by Simplification *)\n\n(** Now that we've defined a few datatypes and functions, let's\n    turn to stating and proving properties of their behavior.\n    Actually, we've already started doing this: each [Example] in the\n    previous sections makes a precise claim about the behavior of some\n    function on some particular inputs.  The proofs of these claims\n    were always the same: use [simpl] to simplify both sides of the\n    equation, then use [reflexivity] to check that both sides contain\n    identical values.\n\n    The same sort of \"proof by simplification\" can be used to prove\n    more interesting properties as well.  For example, the fact that\n    [0] is a \"neutral element\" for [+] on the left can be proved just\n    by observing that [0 + n] reduces to [n] no matter what [n] is, a\n    fact that can be read directly off the definition of [plus].*)\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. simpl. reflexivity.  Qed.\n\n(** (You may notice that the above statement looks different in\n    the [.v] file in your IDE than it does in the HTML rendition in\n    your browser, if you are viewing both. In [.v] files, we write the\n    [forall] universal quantifier using the reserved identifier\n    \"forall.\"  When the [.v] files are converted to HTML, this gets\n    transformed into an upside-down-A symbol.)\n\n    This is a good place to mention that [reflexivity] is a bit\n    more powerful than we have admitted. In the examples we have seen,\n    the calls to [simpl] were actually not needed, because\n    [reflexivity] can perform some simplification automatically when\n    checking that two sides are equal; [simpl] was just added so that\n    we could see the intermediate state -- after simplification but\n    before finishing the proof.  Here is a shorter proof of the\n    theorem: *)\n\nTheorem plus_O_n' : forall n : nat, 0 + n = n.\nProof.\n  intros n. reflexivity. Qed.\n\n(** Moreover, it will be useful later to know that [reflexivity]\n    does somewhat _more_ simplification than [simpl] does -- for\n    example, it tries \"unfolding\" defined terms, replacing them with\n    their right-hand sides.  The reason for this difference is that,\n    if reflexivity succeeds, the whole goal is finished and we don't\n    need to look at whatever expanded expressions [reflexivity] has\n    created by all this simplification and unfolding; by contrast,\n    [simpl] is used in situations where we may have to read and\n    understand the new goal that it creates, so we would not want it\n    blindly expanding definitions and leaving the goal in a messy\n    state.\n\n    The form of the theorem we just stated and its proof are almost\n    exactly the same as the simpler examples we saw earlier; there are\n    just a few differences.\n\n    First, we've used the keyword [Theorem] instead of [Example].\n    This difference is mostly a matter of style; the keywords\n    [Example] and [Theorem] (and a few others, including [Lemma],\n    [Fact], and [Remark]) mean pretty much the same thing to Coq.\n\n    Second, we've added the quantifier [forall n:nat], so that our\n    theorem talks about _all_ natural numbers [n].  Informally, to\n    prove theorems of this form, we generally start by saying \"Suppose\n    [n] is some number...\"  Formally, this is achieved in the proof by\n    [intros n], which moves [n] from the quantifier in the goal to a\n    _context_ of current assumptions.\n\n    The keywords [intros], [simpl], and [reflexivity] are examples of\n    _tactics_.  A tactic is a command that is used between [Proof] and\n    [Qed] to guide the process of checking some claim we are making.\n    We will see several more tactics in the rest of this chapter and\n    yet more in future chapters. *)\n\n(** Other similar theorems can be proved with the same pattern. *)\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. reflexivity.  Qed.\n\nTheorem mult_0_l : forall n:nat, 0 * n = 0.\nProof.\n  intros n. reflexivity.  Qed.\n\n(** The [_l] suffix in the names of these theorems is\n    pronounced \"on the left.\" *)\n\n(** It is worth stepping through these proofs to observe how the\n    context and the goal change.  You may want to add calls to [simpl]\n    before [reflexivity] to see the simplifications that Coq performs\n    on the terms before checking that they are equal. *)\n\n(* ################################################################# *)\n(** * Proof by Rewriting *)\n\n(** This theorem is a bit more interesting than the others we've\n    seen: *)\n\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + n = m + m.\n\n(** Instead of making a universal claim about all numbers [n] and [m],\n    it talks about a more specialized property that only holds when [n\n    = m].  The arrow symbol is pronounced \"implies.\"\n\n    As before, we need to be able to reason by assuming we are given such\n    numbers [n] and [m].  We also need to assume the hypothesis\n    [n = m]. The [intros] tactic will serve to move all three of these\n    from the goal into assumptions in the current context.\n\n    Since [n] and [m] are arbitrary numbers, we can't just use\n    simplification to prove this theorem.  Instead, we prove it by\n    observing that, if we are assuming [n = m], then we can replace\n    [n] with [m] in the goal statement and obtain an equality with the\n    same expression on both sides.  The tactic that tells Coq to\n    perform this replacement is called [rewrite]. *)\n\nProof.\n  (* move both quantifiers into the context: *)\n  intros n m.\n  (* move the hypothesis into the context: *)\n  intros H.\n  (* rewrite the goal using the hypothesis: *)\n  rewrite -> H.\n  reflexivity.  Qed.\n\n(** The first line of the proof moves the universally quantified\n    variables [n] and [m] into the context.  The second moves the\n    hypothesis [n = m] into the context and gives it the name [H].\n    The third tells Coq to rewrite the current goal ([n + n = m + m])\n    by replacing the left side of the equality hypothesis [H] with the\n    right side.\n\n    (The arrow symbol in the [rewrite] has nothing to do with\n    implication: it tells Coq to apply the rewrite from left to right.\n    To rewrite from right to left, you can use [rewrite <-].  Try\n    making this change in the above proof and see what difference it\n    makes.) *)\n\n(** **** 练习: .星 (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  (* 填空 *) Admitted.\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  (* 填空 *) Admitted.\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.  (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  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\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\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 convenience.  \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  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  (* 填空 *) Admitted.\n(** [] *)\n\n(** **** 练习: .星 (zero_nbeq_plus_1)  *)\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  (* 填空 *) Admitted.\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(* 填空 *)\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  (* 填空 *) Admitted.\n\n(** Now state and prove a theorem [negation_fn_applied_twice] similar\n    to the previous one but where the second hypothesis says that the\n    function [f] has the property that [f x = negb x].*)\n\n(* 填空 *)\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (andb_eq_orb)  *)\n(** Prove the following theorem.  (Hint: This one can be a bit tricky,\n    depending on how you approach it.  You will probably need both\n    [destruct] and [rewrite], but destructing everything in sight is\n    not the best way.) *)\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  (* 填空 *) Admitted.\n\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\n(* 填空 *)\n(** [] *)\n\n(** $Date: 2017-09-05 11:51:58 -0400 (Tue, 05 Sep 2017) $ *)\n\n", "meta": {"author": "ichirukia1566", "repo": "SF_chs", "sha": "0f6517cc5747fcf1d099a575f48caed99ad93bf7", "save_path": "github-repos/coq/ichirukia1566-SF_chs", "path": "github-repos/coq/ichirukia1566-SF_chs/SF_chs-0f6517cc5747fcf1d099a575f48caed99ad93bf7/Vol1/Basics_chs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.6664591021503394}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrfun.\nFrom mathcomp Require Import ssrnat seq (*bigop*).\nFrom ipcssr Require Import (*prelude*) forms.\n\nSection Weight.\nContext {A : Type}.\n\nFixpoint weight (a : form A) : nat :=\n  match a with\n  | Falsum => 1\n  | Atom _ => 1\n  | AndF a b => (weight a + weight b).+1\n  | OrF Falsum b => (weight b).+1\n  | OrF (Atom _) b => (weight b).+1\n  | OrF a b => (weight b + weight a).+2\n  | Imp a b => weight_neg a + weight b\n  end\nwith weight_neg (a : form A) : nat :=\n  match a with\n  | Falsum => 0\n  | Atom _ => 0\n  | AndF a b => (weight_neg a + weight_neg b).+1\n  | OrF a b => (weight_neg a + weight_neg b).+3\n  | Imp Falsum b => 1\n  | Imp (Atom _) Falsum => 2\n  | Imp (Atom _) (Atom _) => 1\n  | Imp (Atom _) b => (weight_neg b).+3\n  | Imp a b => (weight_neg b + weight a).+4\n  end.\n\nFixpoint weight_goal (a : form A) : nat :=\n  match a with\n  | Falsum => 0\n  | Atom _ => 0\n  | AndF _ _ => 1\n  | OrF _ _ => 1\n  | Imp _ b => (weight_goal b).+1\n  end.\n\nDefinition weight_gamma :=\n  foldr (fun a n => weight a + n) 0.\n\n(*\nLemma weight_gammaE l :\n  weight_gamma l = \\sum_(i <- l) weight i.\nProof. by rewrite /weight_gamma -fusion_map foldrE big_map. Qed.\n*)\n\n(**********************************************************************)\n\nLemma weight_ge_1 a : 0 < weight a.\nProof.\nelim: a=>//=; first by case.\nmove=>f1 H1 f2 H2.\nby apply: ltn_addl.\nQed.\n\nLemma weight_neg_le j a :\n weight_neg (Imp (Atom j) a) <= (weight_neg a).+3.\nProof. by case: a. Qed.\n\nLemma weight_vimp l a : weight (vimp l a) = weight a.\nProof.\nelim: l a=>//= x l IH a.\nby apply: (IH (Imp (Atom x) a)).\nQed.\n\nLemma weight_gamma_weak a b gamma n :\n  weight a < weight b ->\n  weight_gamma (b :: gamma) <= n ->\n  weight_gamma (a :: gamma) < n.\nProof.\nmove=>/= H Hb.\napply/leq_trans/Hb.\nby rewrite ltn_add2r.\nQed.\n\nLemma weight_gamma_weak' a b gamma n :\n  weight a < weight b ->\n  weight b + weight_gamma gamma <= n ->\n  weight a + weight_gamma gamma < n.\nProof. by apply: weight_gamma_weak. Qed.\n\nLemma weight_gamma_weak2 a b c gamma n :\n  weight a + weight b < weight c ->\n  weight_gamma (c :: gamma) <= n -> weight_gamma (a :: b :: gamma) < n.\nProof.\nmove=>/= H Hac.\napply/leq_trans/Hac.\nby rewrite addnA ltn_add2r.\nQed.\n\nLemma weight_gamma_weak2' a b c gamma n :\n  weight a + weight b < weight c ->\n  weight c + weight_gamma gamma <= n ->\n  weight a + (weight b + weight_gamma gamma) < n.\nProof. by apply: weight_gamma_weak2. Qed.\n\nLemma weight_gamma_weak3 a b c d gamma n :\n  weight a + weight b + weight c < weight d ->\n  weight_gamma (d :: gamma) <= n ->\n  weight_gamma (a :: b :: c :: gamma) < n.\nProof.\nmove=>/= H Hd.\napply/leq_trans/Hd.\nby rewrite !addnA ltn_add2r.\nQed.\n\nLemma weight_gamma_weak3' a b c d gamma n :\n  weight a + weight b + weight c < weight d ->\n  weight d + weight_gamma gamma <= n ->\n  weight a + (weight b + (weight c + weight_gamma gamma)) < n.\nProof. by apply: weight_gamma_weak3. Qed.\n\nEnd Weight.\n", "meta": {"author": "clayrat", "repo": "ipc-ssr", "sha": "51090b179172176f1c301df412735655e8ba6328", "save_path": "github-repos/coq/clayrat-ipc-ssr", "path": "github-repos/coq/clayrat-ipc-ssr/ipc-ssr-51090b179172176f1c301df412735655e8ba6328/theories/weight.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6664031993521593}}
{"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(** * 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\nRequire Import ZAxioms ZProperties NZDiv.\n\nModule Type ZDivSpecific (Import Z:ZAxiomsSig')(Import DM : DivMod' Z).\n Axiom mod_bound : forall a b, 0<=a -> 0<b -> 0 <= a mod b < b.\n Axiom mod_opp_l : forall a b, b ~= 0 -> (-a) mod b == - (a mod b).\n Axiom mod_opp_r : forall a b, b ~= 0 -> a mod (-b) == a mod b.\nEnd ZDivSpecific.\n\nModule Type ZDiv (Z:ZAxiomsSig)\n := DivMod Z <+ NZDivCommon Z <+ ZDivSpecific Z.\n\nModule Type ZDivSig := ZAxiomsExtSig <+ ZDiv.\nModule Type ZDivSig' := ZAxiomsExtSig' <+ ZDiv <+ DivModNotation.\n\nModule ZDivPropFunct (Import Z : ZDivSig')(Import ZP : ZPropSig Z).\n\n(** We benefit from what already exists for NZ *)\n\n Module Import NZDivP := NZDivPropFunct Z ZP Z.\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 mod_eq :\n forall a b, b~=0 -> a mod b == a - b*(a/b).\nProof.\nintros.\nrewrite <- add_move_l.\nsymmetry. now apply div_mod.\nQed.\n\n(** A few sign rules (simple ones) *)\n\nLemma mod_opp_opp : forall a b, b ~= 0 -> (-a) mod (-b) == - (a mod b).\nProof. intros. now rewrite mod_opp_r, mod_opp_l. Qed.\n\nLemma div_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) mod b)).\nnow rewrite <- div_mod, mod_opp_l, mul_opp_r, <- opp_add_distr, <- div_mod.\nQed.\n\nLemma div_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 mod (-b))).\nnow rewrite <- div_mod, mod_opp_r, mul_opp_opp, <- div_mod.\nQed.\n\nLemma div_opp_opp : forall a b, b ~= 0 -> (-a)/(-b) == a/b.\nProof. intros. now rewrite div_opp_r, div_opp_l, opp_involutive. Qed.\n\n(** The sign of [a mod b] is the one of [a] *)\n\n(* TODO: a proper sgn function and theory *)\n\nLemma mod_sign : forall a b, b~=0 -> 0 <= (a mod b) * a.\nProof.\nassert (Aux : forall a b, 0<b -> 0 <= (a mod b) * a).\n intros. pos_or_neg a.\n apply mul_nonneg_nonneg; trivial. now destruct (mod_bound a b).\n rewrite <- mul_opp_opp, <- mod_opp_l by order.\n apply mul_nonneg_nonneg; try order. destruct (mod_bound (-a) b); order.\nintros. pos_or_neg b. apply Aux; order.\nrewrite <- mod_opp_r by order. apply Aux; order.\nQed.\n\n\n(** Uniqueness theorems *)\n\nTheorem div_mod_unique : forall b q1 q2 r1 r2 : t,\n  (0<=r1<b \\/ b<r1<=0) -> (0<=r2<b \\/ b<r2<=0) ->\n  b*q1+r1 == b*q2+r2 -> q1 == q2 /\\ r1 == r2.\nProof.\nintros b q1 q2 r1 r2 Hr1 Hr2 EQ.\ndestruct Hr1; destruct Hr2; try (intuition; order).\napply div_mod_unique with b; trivial.\nrewrite <- (opp_inj_wd r1 r2).\napply div_mod_unique with (-b); trivial.\nrewrite <- opp_lt_mono, opp_nonneg_nonpos; tauto.\nrewrite <- opp_lt_mono, opp_nonneg_nonpos; tauto.\nnow rewrite 2 mul_opp_l, <- 2 opp_add_distr, opp_inj_wd.\nQed.\n\nTheorem div_unique:\n forall a b q r, 0<=a -> 0<=r<b -> a == b*q + r -> q == a/b.\nProof. intros; now apply div_unique with r. Qed.\n\nTheorem mod_unique:\n forall a b q r, 0<=a -> 0<=r<b -> a == b*q + r -> r == a mod b.\nProof. intros; now apply mod_unique with q. Qed.\n\n(** A division by itself returns 1 *)\n\nLemma div_same : forall a, a~=0 -> a/a == 1.\nProof.\nintros. pos_or_neg a. apply div_same; order.\nrewrite <- div_opp_opp by trivial. now apply div_same.\nQed.\n\nLemma mod_same : forall a, a~=0 -> a mod a == 0.\nProof.\nintros. rewrite mod_eq, div_same by trivial. nzsimpl. apply sub_diag.\nQed.\n\n(** A division of a small number by a bigger one yields zero. *)\n\nTheorem div_small: forall a b, 0<=a<b -> a/b == 0.\nProof. exact div_small. Qed.\n\n(** Same situation, in term of modulo: *)\n\nTheorem mod_small: forall a b, 0<=a<b -> a mod b == a.\nProof. exact mod_small. Qed.\n\n(** * Basic values of divisions and modulo. *)\n\nLemma div_0_l: forall a, a~=0 -> 0/a == 0.\nProof.\nintros. pos_or_neg a. apply div_0_l; order.\nrewrite <- div_opp_opp, opp_0 by trivial. now apply div_0_l.\nQed.\n\nLemma mod_0_l: forall a, a~=0 -> 0 mod a == 0.\nProof.\nintros; rewrite mod_eq, div_0_l; now nzsimpl.\nQed.\n\nLemma div_1_r: forall a, a/1 == a.\nProof.\nintros. pos_or_neg a. now apply div_1_r.\napply opp_inj. rewrite <- div_opp_l. apply div_1_r; order.\nintro EQ; symmetry in EQ; revert EQ; apply lt_neq, lt_0_1.\nQed.\n\nLemma mod_1_r: forall a, a mod 1 == 0.\nProof.\nintros. rewrite mod_eq, div_1_r; nzsimpl; auto using sub_diag.\nintro EQ; symmetry in EQ; revert EQ; apply lt_neq; apply lt_0_1.\nQed.\n\nLemma div_1_l: forall a, 1<a -> 1/a == 0.\nProof. exact div_1_l. Qed.\n\nLemma mod_1_l: forall a, 1<a -> 1 mod a == 1.\nProof. exact mod_1_l. Qed.\n\nLemma div_mul : forall a b, b~=0 -> (a*b)/b == a.\nProof.\nintros. pos_or_neg a; pos_or_neg b. apply div_mul; order.\nrewrite <- div_opp_opp, <- mul_opp_r by order. apply div_mul; order.\nrewrite <- opp_inj_wd, <- div_opp_l, <- mul_opp_l by order. apply div_mul; order.\nrewrite <- opp_inj_wd, <- div_opp_r, <- mul_opp_opp by order. apply div_mul; order.\nQed.\n\nLemma mod_mul : forall a b, b~=0 -> (a*b) mod b == 0.\nProof.\nintros. rewrite mod_eq, div_mul by trivial. rewrite mul_comm; apply sub_diag.\nQed.\n\n(** * Order results about mod and div *)\n\n(** A modulo cannot grow beyond its starting point. *)\n\nTheorem mod_le: forall a b, 0<=a -> 0<b -> a mod b <= a.\nProof. exact mod_le. Qed.\n\nTheorem div_pos : forall a b, 0<=a -> 0<b -> 0<= a/b.\nProof. exact div_pos. Qed.\n\nLemma div_str_pos : forall a b, 0<b<=a -> 0 < a/b.\nProof. exact div_str_pos. Qed.\n\nLemma div_small_iff : forall a b, b~=0 -> (a/b==0 <-> abs a < abs b).\nProof.\nintros. pos_or_neg a; pos_or_neg b.\nrewrite div_small_iff; try order. rewrite 2 abs_eq; intuition; order.\nrewrite <- opp_inj_wd, opp_0, <- div_opp_r, div_small_iff by order.\n rewrite (abs_eq a), (abs_neq' b); intuition; order.\nrewrite <- opp_inj_wd, opp_0, <- div_opp_l, div_small_iff by order.\n rewrite (abs_neq' a), (abs_eq b); intuition; order.\nrewrite <- div_opp_opp, div_small_iff by order.\n rewrite (abs_neq' a), (abs_neq' b); intuition; order.\nQed.\n\nLemma mod_small_iff : forall a b, b~=0 -> (a mod b == a <-> abs a < abs b).\nProof.\nintros. rewrite mod_eq, <- div_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 div_lt : forall a b, 0<a -> 1<b -> a/b < a.\nProof. exact div_lt. Qed.\n\n(** [le] is compatible with a positive division. *)\n\nLemma div_le_mono : forall a b c, 0<c -> a<=b -> a/c <= b/c.\nProof.\nintros. pos_or_neg a. apply div_le_mono; auto.\npos_or_neg b. apply le_trans with 0.\n rewrite <- opp_nonneg_nonpos, <- div_opp_l by order.\n apply div_pos; order.\n apply div_pos; order.\nrewrite opp_le_mono in *. rewrite <- 2 div_opp_l by order.\n apply div_le_mono; intuition; order.\nQed.\n\n(** With this choice of division,\n    rounding of div is always done toward zero: *)\n\nLemma mul_div_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 div_pos]; order.\napply mul_div_le; order.\nrewrite <- mul_opp_opp, <- div_opp_r by order.\nsplit.\napply mul_nonneg_nonneg; [|apply div_pos]; order.\napply mul_div_le; order.\nQed.\n\nLemma mul_div_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, <-div_opp_l by order.\nrewrite <- opp_nonneg_nonpos in *.\ndestruct (mul_div_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_div_gt: forall a b, 0<=a -> 0<b -> a < b*(S (a/b)).\nProof. exact mul_succ_div_gt. Qed.\n\n(** Similar results with negative numbers *)\n\nLemma mul_pred_div_lt: forall a b, a<=0 -> 0<b -> b*(P (a/b)) < a.\nProof.\nintros.\nrewrite opp_lt_mono, <- mul_opp_r, opp_pred, <- div_opp_l by order.\nrewrite <- opp_nonneg_nonpos in *.\nnow apply mul_succ_div_gt.\nQed.\n\nLemma mul_pred_div_gt: forall a b, 0<=a -> b<0 -> a < b*(P (a/b)).\nProof.\nintros.\nrewrite <- mul_opp_opp, opp_pred, <- div_opp_r by order.\nrewrite <- opp_pos_neg in *.\nnow apply mul_succ_div_gt.\nQed.\n\nLemma mul_succ_div_lt: forall a b, a<=0 -> b<0 -> b*(S (a/b)) < a.\nProof.\nintros.\nrewrite opp_lt_mono, <- mul_opp_l, <- div_opp_opp by order.\nrewrite <- opp_nonneg_nonpos, <- opp_pos_neg in *.\nnow apply mul_succ_div_gt.\nQed.\n\n(** Inequality [mul_div_le] is exact iff the modulo is zero. *)\n\nLemma div_exact : forall a b, b~=0 -> (a == b*(a/b) <-> a mod b == 0).\nProof.\nintros. rewrite mod_eq by order. rewrite sub_move_r; nzsimpl; tauto.\nQed.\n\n(** Some additionnal inequalities about div. *)\n\nTheorem div_lt_upper_bound:\n  forall a b q, 0<=a -> 0<b -> a < b*q -> a/b < q.\nProof. exact div_lt_upper_bound. Qed.\n\nTheorem div_le_upper_bound:\n  forall a b q, 0<b -> a <= b*q -> a/b <= q.\nProof.\nintros.\nrewrite <- (div_mul q b) by order.\napply div_le_mono; trivial. now rewrite mul_comm.\nQed.\n\nTheorem div_le_lower_bound:\n  forall a b q, 0<b -> b*q <= a -> q <= a/b.\nProof.\nintros.\nrewrite <- (div_mul q b) by order.\napply div_le_mono; trivial. now rewrite mul_comm.\nQed.\n\n(** A division respects opposite monotonicity for the divisor *)\n\nLemma div_le_compat_l: forall p q r, 0<=p -> 0<q<=r -> p/r <= p/q.\nProof. exact div_le_compat_l. Qed.\n\n(** * Relations between usual operations and mod and div *)\n\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) mod c <> a mod c] for [a=9,b=-5,c=2] *)\n\nLemma mod_add : forall a b c, c~=0 -> 0 <= (a+b*c)*a ->\n (a + b * c) mod c == a mod c.\nProof.\nassert (forall a b c, c~=0 -> 0<=a -> 0<=a+b*c -> (a+b*c) mod c == a mod c).\n intros. pos_or_neg c. apply mod_add; order.\n rewrite <- (mod_opp_r a), <- (mod_opp_r (a+b*c)) by order.\n rewrite <- mul_opp_opp in *.\n apply 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 mod_opp_l, opp_add_distr, <- mul_opp_l by order. auto.\nQed.\n\nLemma div_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) mod c)).\nrewrite <- div_mod, mod_add by trivial.\nnow rewrite mul_add_distr_l, add_shuffle0, <-div_mod, mul_comm.\nQed.\n\nLemma div_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 div_add.\nQed.\n\n(** Cancellations. *)\n\nLemma div_mul_cancel_r : forall a b c, b~=0 -> c~=0 ->\n (a*c)/(b*c) == a/b.\nProof.\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 div_mul_cancel_r; order.\n rewrite <- div_opp_opp, <- 2 mul_opp_r. apply 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 div_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 div_opp_l, <- mul_opp_l; try order. apply Aux2; order.\nrewrite <- neq_mul_0; intuition order.\nQed.\n\nLemma div_mul_cancel_l : forall a b c, b~=0 -> c~=0 ->\n (c*a)/(c*b) == a/b.\nProof.\nintros. rewrite !(mul_comm c); now apply div_mul_cancel_r.\nQed.\n\nLemma mul_mod_distr_r: forall a b c, b~=0 -> c~=0 ->\n  (a*c) mod (b*c) == (a mod b) * c.\nProof.\nintros.\nassert (b*c ~= 0) by (rewrite <- neq_mul_0; tauto).\nrewrite ! mod_eq by trivial.\nrewrite div_mul_cancel_r by order.\nnow rewrite mul_sub_distr_r, <- !mul_assoc, (mul_comm (a/b) c).\nQed.\n\nLemma mul_mod_distr_l: forall a b c, b~=0 -> c~=0 ->\n  (c*a) mod (c*b) == c * (a mod b).\nProof.\nintros; rewrite !(mul_comm c); now apply mul_mod_distr_r.\nQed.\n\n(** Operations modulo. *)\n\nTheorem mod_mod: forall a n, n~=0 ->\n (a mod n) mod n == a mod n.\nProof.\nintros. pos_or_neg a; pos_or_neg n. apply mod_mod; order.\nrewrite <- ! (mod_opp_r _ n) by trivial. apply mod_mod; order.\napply opp_inj. rewrite <- !mod_opp_l by order. apply mod_mod; order.\napply opp_inj. rewrite <- !mod_opp_opp by order. apply mod_mod; order.\nQed.\n\nLemma mul_mod_idemp_l : forall a b n, n~=0 ->\n ((a mod n)*b) mod n == (a*b) mod n.\nProof.\nassert (Aux1 : forall a b n, 0<=a -> 0<=b -> n~=0 ->\n         ((a mod n)*b) mod n == (a*b) mod n).\n intros. pos_or_neg n. apply mul_mod_idemp_l; order.\n rewrite <- ! (mod_opp_r _ n) by order. apply mul_mod_idemp_l; order.\nassert (Aux2 : forall a b n, 0<=a -> n~=0 ->\n         ((a mod n)*b) mod n == (a*b) mod n).\n intros. pos_or_neg b. now apply Aux1.\n apply opp_inj. rewrite <-2 mod_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 mod_opp_l, <-2 mul_opp_l, <-mod_opp_l by order.\napply Aux2; order.\nQed.\n\nLemma mul_mod_idemp_r : forall a b n, n~=0 ->\n (a*(b mod n)) mod n == (a*b) mod n.\nProof.\nintros. rewrite !(mul_comm a). now apply mul_mod_idemp_l.\nQed.\n\nTheorem mul_mod: forall a b n, n~=0 ->\n (a * b) mod n == ((a mod n) * (b mod n)) mod n.\nProof.\nintros. now rewrite mul_mod_idemp_l, mul_mod_idemp_r.\nQed.\n\n(** addition and modulo\n\n  Generally speaking, unlike with other conventions, we don't have\n       [(a+b) mod n = (a mod n + b mod n) mod n]\n  for any a and b.\n  For instance, take (8 + (-10)) mod 3 = -2 whereas\n  (8 mod 3 + (-10 mod 3)) mod 3 = 1.\n*)\n\nLemma add_mod_idemp_l : forall a b n, n~=0 -> 0 <= a*b ->\n ((a mod n)+b) mod n == (a+b) mod n.\nProof.\nassert (Aux : forall a b n, 0<=a -> 0<=b -> n~=0 ->\n          ((a mod n)+b) mod n == (a+b) mod n).\n intros. pos_or_neg n. apply add_mod_idemp_l; order.\n rewrite <- ! (mod_opp_r _ n) by order. apply 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 mod_opp_l, 2 opp_add_distr, <-mod_opp_l by order.\nrewrite <- opp_nonneg_nonpos in *.\nnow apply Aux.\nQed.\n\nLemma add_mod_idemp_r : forall a b n, n~=0 -> 0 <= a*b ->\n (a+(b mod n)) mod n == (a+b) mod n.\nProof.\nintros. rewrite !(add_comm a). apply add_mod_idemp_l; trivial.\nnow rewrite mul_comm.\nQed.\n\nTheorem add_mod: forall a b n, n~=0 -> 0 <= a*b ->\n (a+b) mod n == (a mod n + b mod n) mod n.\nProof.\nintros a b n Hn Hab. rewrite add_mod_idemp_l, add_mod_idemp_r; trivial.\nreflexivity.\ndestruct (le_0_mul _ _ Hab) as [(Ha,Hb)|(Ha,Hb)];\n destruct (le_0_mul _ _ (mod_sign 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 mod_0_l by order. nzsimpl; order.\n setoid_replace b with 0 by order. rewrite mod_0_l by order. nzsimpl; order.\nQed.\n\n\n(** Conversely, the following result needs less restrictions here. *)\n\nLemma div_div : 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 div_div; order.\n apply opp_inj. rewrite <- 2 div_opp_r, <- mul_opp_r; trivial.\n apply 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 <- div_opp_l, <- 2 div_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 div_opp_l; try order. apply Aux2; order.\nrewrite <- neq_mul_0. tauto.\nQed.\n\n(** A last inequality: *)\n\nTheorem div_mul_le:\n forall a b c, 0<=a -> 0<b -> 0<=c -> c*(a/b) <= (c*a)/b.\nProof. exact div_mul_le. Qed.\n\n(** mod is related to divisibility *)\n\nLemma mod_divides : forall a b, b~=0 ->\n (a mod b == 0 <-> exists c, a == b*c).\nProof.\n intros a b Hb. split.\n intros Hab. exists (a/b). rewrite (div_mod a b Hb) at 1.\n  rewrite Hab; now nzsimpl.\n intros (c,Hc). rewrite Hc, mul_comm. now apply mod_mul.\nQed.\n\nEnd ZDivPropFunct.\n\n", "meta": {"author": "JasonGross", "repo": "category-coq-experience-tests", "sha": "f9949ede618788fd051fe8327f997ee683388e49", "save_path": "github-repos/coq/JasonGross-category-coq-experience-tests", "path": "github-repos/coq/JasonGross-category-coq-experience-tests/category-coq-experience-tests-f9949ede618788fd051fe8327f997ee683388e49/coq/coq-8.3pl5-foundations/theories/Numbers/Integer/Abstract/ZDivTrunc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6664031984288942}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp\nRequire Import ssrfun ssrbool eqtype ssrnat seq choice fintype.\nFrom mathcomp\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; have [-> | _ ltpq] := eqP; first by rewrite size_poly0.\nby case: (size p) => [|s]; rewrite /=  ltpq.\nQed.\n\nLemma leq_rdivp p q : size (rdivp p q) <= size p.\nProof.\nhave [/rdivp_small->|] := ltnP (size p) (size q); first by rewrite size_poly0.\nrewrite /rdivp /rmodp /rscalp unlock.\ncase q0: (q == 0) => /=; first 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 sq: 0 < size q by rewrite size_poly_gt0 q0.\nhave sr: 0 < size r by apply: leq_trans sq hqr.\napply: ihn => //.\n- apply/leq_sizeP => j hnj.\n  rewrite coefB -scalerAl coefZ coefXnM ltn_subRL ltnNge.\n  have hj : (size r).-1 <= j.\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\nVariant comm_redivp_spec m d : nat * {poly R} * {poly R} -> Type :=\n  ComEdivnSpec k (q r : {poly R}) of\n   (GRing.comm d (lead_coef d)%:P -> m * (lead_coef d ^+ k)%:P = q * d + r) &\n   (d != 0 -> size r < size d) : comm_redivp_spec m d (k, q, r).\n\nLemma comm_redivpP m d : comm_redivp_spec m d (redivp m d).\nProof.\nrewrite unlock; 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.\nby rewrite /rdivp /rmodp /rscalp; case: comm_redivpP=> k q1 r1 Hc _; apply: Hc.\nQed.\n\n(* section variables impose an inconvenient order on parameters *)\nLemma eq_rdvdp k q1 p:\n  p * ((lead_coef d)^+ k)%:P = q1 * d -> rdvdp d p.\nProof.\nmove=> he.\nhave Hnq0 := rreg_lead0 Rreg; set lq := lead_coef d.\npose v := rscalp p d; pose m := maxn v k.\nrewrite /rdvdp -(rreg_polyMC_eq0 _ (@rregX _ _ (m - v) Rreg)).\nsuff:\n ((rdivp p d) * (lq ^+ (m - v))%:P  - q1 * (lq ^+ (m - k))%:P) * d +\n  (rmodp p d) * (lq ^+ (m - v))%:P  == 0.\n  rewrite rreg_div0 //; first by case/andP.\n  by rewrite rreg_size ?ltn_rmodp //; 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\nVariant rdvdp_spec p q : {poly R} -> bool -> Type :=\n  | Rdvdp k q1 & p * ((lead_coef q)^+ k)%:P = q1 * q : rdvdp_spec p q 0 true\n  | RdvdpN & rmodp p q != 0 : rdvdp_spec p q (rmodp p q) false.\n\n(* Is that version useable ? *)\n\nLemma rdvdp_eqP p : rdvdp_spec p d (rmodp p d) (rdvdp d p).\nProof.\ncase hdvd: (rdvdp d p); last by apply: RdvdpN; move/rmodp_eq0P/eqP: hdvd.\nmove/rmodp_eq0P: (hdvd)->; apply: (@Rdvdp _ _ (rscalp p d) (rdivp p d)).\nby rewrite rdivp_eq //; move/rmodp_eq0P: (hdvd)->; rewrite addr0.\nQed.\n\nLemma rdvdp_mull p : rdvdp d (p * d).\nProof. by apply: (@eq_rdvdp 0%N p); rewrite expr0 mulr1. Qed.\n\nLemma rmodp_mull p : rmodp (p * d) d = 0.\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. by apply/eqP; apply: rmodpp. Qed.\n\nLemma rdivpK p : rdvdp d p -> \n  (rdivp p d) * d = p * (lead_coef d ^+ rscalp p d)%:P.\nProof. by rewrite rdivp_eq /rdvdp; move/eqP->; rewrite addr0. Qed.\n\nEnd ComRegDivisor.\n\nEnd RingComRreg.\n\nModule RingMonic.\n\nImport CommonRing.\n\nImport RingComRreg.\n\nSection 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) => -> /=; 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.\nby apply: rmodp_mull; rewrite (eqP mond); [apply: commr1 | apply: rreg1].\nQed.\n\nLemma rmodpp : rmodp d d = 0.\nProof.\nby apply: rmodpp; rewrite (eqP mond); [apply: commr1 | apply: rreg1].\nQed.\n\nLemma rmodp_addl_mul_small q r :\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.\nby rewrite -{2}[rmodp _ _]addr0; congr (_ + _); apply: rmodp_mull.\nQed.\n\nLemma rdvdpp : rdvdp d d.\nProof.\nby apply: rdvdpp; rewrite (eqP mond); [apply: commr1 | apply: rreg1].\nQed.\n\n(* section variables impose an inconvenient order on parameters *)\nLemma eq_rdvdp q1 p : p = q1 * d -> rdvdp d p.\nProof.\n(*  this probably means I need to specify impl args for comm_rref_rdvdp *)\nmove=> h; apply: (@eq_rdvdp _ _ _ _ 1%N q1); rewrite (eqP mond).\n- exact: commr1.\n- exact: rreg1.\nby rewrite expr1n mulr1.\nQed.\n\nLemma rdvdp_mull p : rdvdp d (p * d).\nProof.\nby apply: rdvdp_mull; rewrite (eqP mond) //; [apply: commr1 | apply: rreg1].\nQed.\n\nLemma rdvdpP p : reflect (exists qq, p = qq * d) (rdvdp d p).\nProof.\ncase: (monic_comreg mond)=> Hc Hr; apply: (iffP idP).\n  case: rdvdp_eqP=> // k qq; rewrite (eqP mond) expr1n mulr1 => -> _.\n  by exists qq.\nby case=> [qq]; move/eq_rdvdp.\nQed.\n\nLemma rdivpK p : rdvdp d p -> (rdivp p d) * d = p.\nProof. by move=> dvddp; rewrite {2}[p]rdivp_eq rmodp_eq0 ?addr0. 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  by case=> p1 ->; apply: rmodp_mull; apply: 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\nVariant redivp_spec (m d : {poly R}) : nat * {poly R} * {poly R} -> Type :=\n  EdivnSpec k (q r: {poly R}) of\n    (lead_coef d ^+ k) *: m = q * d + r &\n   (d != 0 -> size r < size d) : redivp_spec m d (k, q, r).\n\n\nLemma redivpP m d : redivp_spec m d (redivp m d).\nProof.\nrewrite redivp_def; constructor; last by move=> dn0; rewrite ltn_rmodp.\nby rewrite -mul_polyC mulrC rdivp_eq //= /GRing.comm mulrC.\nQed.\n\nLemma rdivp_eq d p :\n  (lead_coef d ^+ (rscalp p d)) *: p = (rdivp p d) * d + (rmodp p d).\nProof.\nby rewrite /rdivp /rmodp /rscalp; case: redivpP=> k q1 r1 Hc _; apply: Hc.\nQed.\n\nLemma rdvdp_eqP d p : rdvdp_spec p d (rmodp p d) (rdvdp d p).\nProof.\ncase hdvd: (rdvdp d p); last by 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 ->.\nexact/RingMonic.rdvdp_mull/monic_prod_XsubC.\nQed.\n\nEnd UnitRingPseudoDivision.\n\nEnd UnitRing.\n\nModule IdomainDefs.\n\nImport Ring.\n\nSection IDomainPseudoDivisionDefs.\n\nVariable R : idomainType.\nImplicit Type p q r d : {poly R}.\n\nDefinition edivp_expanded_def p q :=\n  let: (k, d, r) as edvpq := redivp p q in\n  if lead_coef q \\in GRing.unit then\n    (0%N, (lead_coef q)^-k *: d, (lead_coef q)^-k *: r)\n  else edvpq.\nFact edivp_key : unit. Proof. by []. Qed.\nDefinition edivp := locked_with edivp_key edivp_expanded_def.\nCanonical edivp_unlockable := [unlockable fun edivp].\n\nDefinition divp p q := ((edivp p q).1).2.\nDefinition modp p q := (edivp p q).2.\nDefinition scalp p q := ((edivp p q).1).1.\nDefinition dvdp p q := modp q p == 0.\nDefinition eqp p q :=  (dvdp p q) && (dvdp q p).\n\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 h: (lead_coef q \\in GRing.unit); rewrite /scalp unlock redivp_def h.\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 : core.\n\nVariant edivp_spec (m d : {poly R}) :\n                                     nat * {poly R} * {poly R} -> bool -> Type :=\n|Redivp_spec k (q r: {poly R}) of\n  (lead_coef d ^+ k) *: m = q * d + r & lead_coef d \\notin GRing.unit &\n  (d != 0 -> size r < size d) : edivp_spec m d (k, q, r) false\n|Fedivp_spec (q r: {poly R}) of m = q * d + r & (lead_coef d \\in GRing.unit) &\n  (d != 0 -> size r < size d) : edivp_spec m d (0%N, q, r) true.\n\n(* There are several ways to state this fact. The most appropriate statement*)\n(* might be polished in light of usage. *)\nLemma edivpP m d : edivp_spec m d (edivp m d) (lead_coef d \\in GRing.unit).\nProof.\nhave hC : GRing.comm d (lead_coef d)%:P by rewrite /GRing.comm mulrC.\ncase ud: (lead_coef d \\in GRing.unit); last first.\n  rewrite edivp_redivp // redivp_def; constructor; rewrite ?ltn_rmodp // ?ud //.\n  by rewrite rdivp_eq.\nhave cdn0: lead_coef d != 0 by apply: contraTneq ud => ->; rewrite unitr0.\nrewrite unlock ud redivp_def; constructor => //.\n  rewrite -scalerAl -scalerDr -mul_polyC.\n  have hn0 : (lead_coef d ^+ rscalp m d)%:P != 0.\n    by rewrite polyC_eq0; apply: expf_neq0.\n  apply: (mulfI hn0); rewrite !mulrA -exprVn !polyC_exp -exprMn -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 apply: 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 //.\n  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. by move=> nzq; rewrite mulrC; apply: mulpK. Qed.\n\nLemma divpp p : p != 0 -> p %/ p = (lead_coef p ^+ scalp p p)%:P.\nProof.\nmove=> np0; have := (divp_eq p p).\nsuff -> : p %% p = 0.\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 : core.\n\nEnd WeakIdomain.\n\nModule CommonIdomain.\n\nImport Ring ComRing UnitRing IdomainDefs WeakIdomain.\n\nSection IDomainPseudoDivision.\n\nVariable R : idomainType.\nImplicit Type p q r d m n : {poly R}.\n\nLemma scalp0 p : scalp p 0 = 0%N.\nProof. by rewrite /scalp unlock lead_coef0 unitr0 unlock eqxx. Qed.\n\nLemma divp_small p q : size p < size q -> p %/ q = 0.\nProof.\nmove=> spq; rewrite /divp unlock redivp_def /=.\nby case: ifP; rewrite rdivp_small // scaler0.\nQed.\n\nLemma leq_divp p q : (size (p %/ q) <= size p).\nProof.\nrewrite /divp unlock redivp_def /=; case: ifP=> /=; 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 : core.\n\nLemma modp_small p q : size p < size q -> p %% q = p.\nProof.\nmove=> spq; rewrite /modp unlock redivp_def; case: ifP; rewrite rmodp_small //.\nby rewrite /= rscalp_small // expr0 /= invr1 scale1r.\nQed.\n\nLemma modpC p c : c != 0 -> p %% c%:P = 0.\nProof.\nmove=> cn0; rewrite /modp unlock redivp_def /=; case: ifP; rewrite ?rmodpC //.\nby rewrite scaler0.\nQed.\n\nLemma modp_mull p q : (p * q) %% q = 0.\nProof.\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 apply: 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 : core.\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 -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)).\n   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 : core.\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 : core.\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 := _ %/ _.\n  have sn0 : c1 * c2 != 0.\n    by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF.\n  move/eqP=> Eq2; apply: (@eq_dvdp _ (c1 *: q2 - c2 *: q1) _ _ sn0).\n  rewrite mulrDl -scaleNr -!scalerAl -Eq1 -Eq2 !scalerA.\n  by rewrite mulNr mulrC scaleNr -scalerBr addrC addKr.\nhave sn0 : c1 * c2 != 0.\n  by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF.\nmove/eqP=> Eq2; apply: (@eq_dvdp _ (c1 *: q2 + c2 *: q1) _ _ sn0).\nby  rewrite mulrDl -!scalerAl -Eq1 -Eq2 !scalerA mulrC addrC scalerDr.\nQed.\n\nLemma dvdp_addl n d m : d %| n -> (d %| m + n) = (d %| m).\nProof. by rewrite addrC; apply: dvdp_addr. Qed.\n\nLemma dvdp_add d m n : d %| m -> d %| n -> d %| m + n.\nProof. by move/dvdp_addr->. Qed.\n\nLemma dvdp_add_eq  d m n : d %| m + n -> (d %| m) = (d %| n).\nProof. by move=> ?; apply/idP/idP; [move/dvdp_addr <-| move/dvdp_addl <-]. Qed.\n\nLemma dvdp_subr d m n : d %| m -> (d %| m - n) = (d %| n).\nProof. by move=> ?; apply dvdp_add_eq; rewrite -addrA addNr simp. Qed.\n\nLemma dvdp_subl  d m n : d %| n -> (d %| m - n) = (d %| m).\nProof. by move/dvdp_addl<-; rewrite subrK. Qed.\n\nLemma dvdp_sub  d m n : d %| m -> d %| n -> d %| m - n.\nProof.  by move=> *; rewrite dvdp_subl. Qed.\n\nLemma dvdp_mod d n m : d %| n -> (d %| m) = (d %| m %% n).\nProof.\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 := _ %/ _.\n  have sn0 : c1 * c2 != 0.\n   by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF.\n  pose quo :=  (c1 * lead_coef n ^+ scalp m n) *: q2 - c2 *: (m %/ n) * q1.\n  move/eqP=> Eq2; apply: (@eq_dvdp _ quo _ _ sn0).\n  rewrite mulrDl mulNr -!scalerAl -!mulrA -Eq1 -Eq2 -scalerAr !scalerA.\n  rewrite mulrC [_ * c2]mulrC mulrA -[((_ * _) * _) *: _]scalerA -scalerBr.\n  by rewrite divp_eq addrC addKr.\nhave sn0 : c1 * c2 * lead_coef n ^+ scalp m n != 0.\n  rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 ?(negPf dn0) ?andbF //.\n  by rewrite (negPf nn0) andbF.\nmove/eqP=> Eq2; apply: (@eq_dvdp _ (c2 *: (m  %/ n) * q1 + c1 *: q2) _ _ sn0).\nrewrite -scalerA divp_eq scalerDr -!scalerA Eq2 scalerAl scalerAr Eq1.\nby rewrite scalerAl mulrDl mulrA.\nQed.\n\nLemma dvdp_trans : transitive (@dvdp R).\nProof.\nmove=> n d m.\ncase: (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; apply: dvdpp. Qed.\n\nLemma dvdp_mulIr p q : q %| p * q.\nProof. by apply: dvdp_mull; apply: 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. by rewrite dvdpE; apply: Ring.rdvdp_XsubCl. Qed.\n\nLemma polyXsubCP p x : reflect (p.[x] = 0) (('X - x%:P) %| p).\nProof. by rewrite dvdpE; apply: Ring.polyXsubCP. Qed.\n\nLemma eqp_div_XsubC p c :\n  (p == (p %/ ('X - c%:P)) * ('X - c%:P)) = ('X - c%:P %| p).\nProof. by rewrite dvdp_eq lead_coefXsubC expr1n scale1r. Qed.\n\nLemma root_factor_theorem p x : root p x = (('X - x%:P) %| p).\nProof. by rewrite dvdp_XsubCl. Qed.\n\nLemma uniq_roots_dvdp p rs : all (root p) rs -> uniq_roots rs ->\n  (\\prod_(z <- rs) ('X - z%:P)) %| p.\nProof.\nmove=> rrs; case/(uniq_roots_prod_XsubC rrs)=> q ->.\nby apply: dvdp_mull; rewrite // (eqP (monic_prod_XsubC _)) unitr1.\nQed.\n\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 : core.\n\nLemma eqp_sym : symmetric (@eqp R).\nProof. by move=> p q; rewrite /eqp andbC. Qed.\n\nLemma eqp_trans : transitive (@eqp R).\nProof.\nmove=> p q r; case/andP=> Dp pD; case/andP=> Dq qD.\nby rewrite /eqp (dvdp_trans Dp) // (dvdp_trans qD).\nQed.\n\nLemma eqp_ltrans : left_transitive (@eqp R).\nProof.\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. by move=> cn0; apply: eqp_dvdr; apply: eqp_scale. Qed.\n\nLemma dvdp_scalel c m n : c != 0 -> (c *: m %| n) = (m %| n).\nProof. by move=> cn0; apply: eqp_dvdl; apply: eqp_scale. Qed.\n\nLemma dvdp_opp d p : d %| (- p) = (d %| p).\nProof. by apply: eqp_dvdr; rewrite -scaleN1r eqp_scale ?oppr_eq0 ?oner_eq0. Qed.\n\nLemma eqp_mul2r r p q : r != 0 -> (p * r %= q * r) = (p %= q).\nProof. by move=> nz_r; rewrite /eqp !dvdp_mul2r. Qed.\n\nLemma eqp_mul2l r p q: r != 0 -> (r * p %= r * q) = (p %= q).\nProof. by move=> nz_r; rewrite /eqp !dvdp_mul2l. Qed.\n\nLemma eqp_mull r p q: (q %= r) -> (p * q %= p * r).\nProof.\ncase/eqpP=> [[c d]] /andP [c0 d0 e]; apply/eqpP; exists (c, d); rewrite ?c0 //.\nby rewrite scalerAr e -scalerAr.\nQed.\n\nLemma eqp_mulr q p r : (p %= q) -> (p * r %= q * r).\nProof. by move=> epq; rewrite ![_ * r]mulrC eqp_mull. Qed.\n\nLemma eqp_exp  p q k : p %= q -> p ^+ k %= q ^+ k.\nProof.\nmove=> pq; elim: k=> [|k ihk]; first by rewrite !expr0 eqpxx.\nby rewrite !exprS (@eqp_trans (q * p ^+ k)) // (eqp_mulr, eqp_mull).\nQed.\n\nLemma polyC_eqp1 (c : R) : (c%:P %= 1) = (c != 0).\nProof.\napply/eqpP/idP => [[[x y]] |nc0] /=.\n  case 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 apply: 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; apply: 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 _ _) _.\nby apply: eqp_trans (gcdp_scalel _ _ _) _ => //; apply: 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. by move/dvdp_gcd_idl => h; apply: eqp_trans h; apply: 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  by move/ltnW; rewrite minnC; move/hwlog=> h; apply: eqp_trans h; apply: gcdpC.\nrewrite (minn_idPl leqmn); move/subnK: leqmn<-; rewrite exprD.\nby apply: eqp_trans (gcdp_mull _ _) _; apply: 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.\nby apply: h; [apply: dvdp_gcdl | apply: dvdp_gcdr].\nQed.\n\nDefinition coprimep p q := size (gcdp p q) == 1%N.\n\nLemma coprimep_size_gcd p q : coprimep p q -> size (gcdp p q) = 1%N.\nProof. by rewrite /coprimep=> /eqP. Qed.\n\nLemma coprimep_def p q : (coprimep p q) = (size (gcdp p q) == 1%N).\nProof. done. Qed.\n\nLemma 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. by rewrite !(coprimep_sym _ p); apply: eqp_coprimepr. Qed.\n\n(* This should be implemented with an extended remainder sequence *)\nFixpoint egcdp_rec p q k {struct k} : {poly R} * {poly R} :=\n  if k is k'.+1 then\n    if q == 0 then (1, 0) else\n    let: (u, v) := egcdp_rec q (p %% q) k' in\n      (lead_coef q ^+ scalp p q *: v, (u - v * (p %/ q)))\n  else (1, 0).\n\nDefinition egcdp p q :=\n  if size q <= size p then egcdp_rec p q (size q)\n    else let e := egcdp_rec q p (size p) in (e.2, e.1).\n\n(* No provable egcd0p *)\nLemma egcdp0 p : egcdp p 0 = (1, 0).\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; apply: 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  by case: (Bezoutp p q) => [[u v] Puv]; exists (u, v); apply: eqp_trans g1.\ncase=> [[u v]]; rewrite eqp_sym=> Puv; rewrite /eqp  (eqp_dvdr _ Puv).\nby rewrite dvdp_addr dvdp_mull ?dvdp_gcdl ?dvdp_gcdr //= dvd1p.\nQed.\n\nLemma coprimep_root p q x : coprimep p q -> root p x -> q.[x] != 0.\nProof.\ncase/Bezout_coprimepP=> [[u v] euv] px0.\nmove/eqpP: euv => [[c1 c2]] /andP /= [c1n0 c2n0 e].\nsuffices: c1 * (v.[x] * q.[x]) != 0.\n  by rewrite !mulf_eq0 !negb_or c1n0 /=; case/andP.\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. by rewrite mulrC; apply: Gauss_dvdpl. Qed.\n\n(* This could be simplified with the introduction of lcmp *)\nLemma Gauss_dvdp m n p : coprimep m n -> (m * n %| p) = (m %| p) && (n %| p).\nProof.\ncase: (eqVneq m 0) => [-> | mn0].\n  by rewrite coprime0p => /eqp_dvdl->; rewrite !mul0r dvd0p dvd1p andbT.\ncase: (eqVneq n 0) => [-> | nn0].\n  by rewrite coprimep0 => /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  by split; apply/coprimepP=> d dp dq; rewrite hp //;\n     [apply/dvdp_mulr | apply/dvdp_mull].\nmove=> d dp dqr; move/(_ _ dp) in hq.\nrewrite Gauss_dvdpl in dqr; first exact: hq.\nby move/coprimep_dvdr: hr; apply.\nQed.\n\nLemma 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); apply: 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\nVariant gdcop_spec q p : {poly R} -> Type :=\n  GdcopSpec r of (dvdp r p) & ((coprimep r q) || (p == 0))\n  & (forall d,  dvdp d p -> coprimep d q -> dvdp d r)\n  : gdcop_spec q p r.\n\nLemma gdcop0 q : gdcop q 0 = (q == 0)%:R.\nProof. by  rewrite /gdcop size_poly0. Qed.\n\nLemma gdcop_recP : 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  exact/(dvdp_trans dr'p')/divp_dvd/dvdp_gcdl.\nmove=> d dp cdq; apply: maxr'; last by rewrite cdq.\ncase dpq: (d %| gcdp p q).\n  move: (dpq); rewrite dvdp_gcd dp /= => dq; apply: dvdUp; 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 : core.\nHint Resolve dvdp0 : core.\n\nEnd CommonIdomain.\n\nModule Idomain.\n\nInclude IdomainDefs.\nExport IdomainDefs.\nInclude WeakIdomain.\nInclude CommonIdomain.\n\nEnd Idomain.\n\nModule IdomainMonic.\n\nImport Ring ComRing UnitRing IdomainDefs Idomain.\n\nSection 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; apply: 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.\ncase/edivpP: (sym_eq (addr0 (q * d))); rewrite // size_poly0 size_poly_gt0.\nby rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->; rewrite unitr0.\nQed.\n\nLemma mulKp q : (d * q) %/ d = q.\nProof. by rewrite mulrC; apply: 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.\nProof. by rewrite -{1}(mul1r d) mulpK. Qed.\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); apply: divp_mulA. Qed.\n\nLemma divp_mulCA p q : d %| p -> d %| q -> p * (q %/ d) = q * (p %/ d).\nProof. by move=> hdp hdq; rewrite mulrC divp_mulAC // divp_mulA. Qed.\n\nLemma modp_mul p q : (p * (q %% d)) %% d = (p * q) %% d.\nProof.\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; apply: 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  by rewrite addrA (mulrC p) mulrA -mulrDl; rewrite -divp_eq //; apply: divp_eq.\nhave pn0 : p != 0.\n  by rewrite -lead_coef_eq0; apply: contraTneq ulcp => ->; rewrite unitr0.\nhave rn0 : r != 0.\n  by rewrite -lead_coef_eq0; apply: contraTneq ulcr => ->; rewrite unitr0.\nhave s : size ((q %/ p) %% r * p +  q %% p) < size (p * r).\n  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; apply: 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).\nby apply: eqp_trans (eqp_modpl _ e1); apply: 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).\nby apply: eqp_trans (eqp_divl _ e1); apply: 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.\nby apply: eqp_div => //; apply: 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=> _ //.\nby apply: ihn => //; apply: eqp_div => //; apply: 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); apply: divp_mulA. Qed.\n\nLemma divp_mulCA d p q : d %| p -> d %| q -> p * (q %/ d) = q * (p %/ d).\nProof. by move=> hdp hdq; rewrite mulrC divp_mulAC // divp_mulA. Qed.\n\nLemma expp_sub d m n : d != 0 -> m >= n -> (d ^+ (m - n))%N = d ^+ m %/ d ^+ n.\nProof. by move=> dn0 /subnK=> {2}<-; rewrite exprD mulpK // expf_neq0. Qed.\n\nLemma divp_pmul2l d q p : d != 0 -> q != 0 -> d * p %/ (d * q) = p %/ q.\nProof.\nby move=> dn0 qn0; apply: IdomainUnit.divp_pmul2l; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma divp_pmul2r d p q : d != 0 -> p != 0 ->  q * d %/ (p * d) = q %/ p.\nProof. by move=> dn0 qn0; rewrite -!(mulrC d) divp_pmul2l. Qed.\n\nLemma divp_divl r p q :  q %/ p %/ r = q %/ (p * r).\nProof.\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\nVariant edivp_spec m d : nat * {poly F} * {poly F} -> Type :=\n  EdivpSpec n q r of\n  m = q * d + r & (d != 0) ==> (size r < size d) : edivp_spec m d (n, q, r).\n\nLemma edivpP m d : edivp_spec m d (edivp m d).\nProof.\nrewrite edivp_def; constructor; first exact: divp_eq.\nby apply/implyP=> dn0; rewrite ltn_modp.\nQed.\n\nLemma edivp_eq d q r : size r < size d -> edivp (q * d + r) d = (0%N, q, r).\nProof.\nmove=> srd; apply: Idomain.edivp_eq; rewrite // unitfE lead_coef_eq0.\nby rewrite -size_poly_gt0; apply: leq_trans srd.\nQed.\n\nLemma modp_mul p q m : (p * (q %% m)) %% m = (p * q) %% m.\nProof.\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; apply: 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=> IHpq; case: (ltnP (size p) (size q)) => [|le_q_p]; first exact: IHpq.\n  rewrite gcdpE (gcdpE p^f) !size_map_poly ltnNge le_q_p /= -map_modp.\n  case: (eqVneq q 0) => [-> | q_nz]; first by rewrite rmorph0 !gcdp0.\n  by rewrite IHpq ?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": "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/polydiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6664031948208885}}
{"text": "Set Implicit Arguments.\n\nRequire Import\n        Discrete.DiscType\n        Discrete.Disjoint\n        Discrete.DupFree\n        Discrete.Filter\n        Discrete.In\n        Discrete.Inclusion\n        Tactics.Tactics.\n\nImport ListNotations.\n\nSection POWER.\n  Variable A : discType.\n  Context {eq_A_dec : eq_dec A}.\n\n  Fixpoint power (xs : list A) : list (list A) :=\n    match xs with\n      | nil => [nil]\n      | y :: ys => power ys ++ map (cons y) (power ys)\n    end.\n\n  Lemma power_incl xs ys :\n    xs el power ys -> xs <<= ys.\n  Proof.\n    revert xs ; induction ys as [ | y ys ] ; simpl ; intros xs D.\n    -\n      destruct* D as [[]|[]]. \n    - apply In_app_iff in D as [E|E]. now auto.\n      apply In_map_iff in E as [zs [E F]]. substs*.\n      apply incl_shift ; eauto.\n  Qed.\n\n  Lemma power_nil xs :\n    nil el power xs.\n  Proof.\n    induction xs ; simpl ; crush.\n    rewrite In_app_iff ; crush.\n  Qed.\n\n  Definition rep (xs ys : list A) : list A :=\n    filter (fun x => x el xs) ys.\n\n  Lemma rep_incl xs ys :\n    rep xs ys <<= xs.\n  Proof.\n    unfold rep. intros x D. apply In_filter_iff in D. apply D.\n  Qed.\n\n  Lemma rep_power xs ys :\n    rep xs ys el power ys.\n  Proof.\n    revert xs. induction ys as [|y ys] ; intros xs.\n    -\n      simpl ; auto.\n    -\n      unfold rep ; simpl ;\n        decide (y el xs) as [E | E]\n        ; rewrite In_app_iff ; specialize (IHys xs) ;\n          unfold rep in IHys ; [right ; eauto | left*].\n  Qed.\n\n  Lemma rep_in x xs ys :\n    xs <<= ys -> x el xs -> x el rep xs ys.\n  Proof.\n    intros D E. apply In_filter_iff ; crush.\n  Qed.\n  \n  Lemma rep_equiv xs ys :\n    xs <<= ys -> rep xs ys === xs.\n  Proof.\n    intros D. split. now apply rep_incl.\n    intros x. apply rep_in, D.\n  Qed.\n\n  Lemma rep_mono xs ys zs :\n    xs <<= ys -> rep xs zs <<= rep ys zs.\n  Proof.\n    intros D.\n    apply filter_pq_mono.\n    auto.\n  Qed.\n\n  Lemma rep_eq' xs ys zs :\n    (forall x, x el zs -> (x el xs <-> x el ys)) -> rep xs zs = rep ys zs.\n  Proof.\n    intros D.\n    apply filter_pq_eq.\n    auto.\n  Qed.\n\n  Lemma rep_eq xs ys zs :\n    xs === ys -> rep xs zs = rep ys zs.\n  Proof.\n    intros D.\n    apply filter_pq_eq.\n    firstorder.\n  Qed.\n\n  Lemma rep_injective xs ys zs :\n    xs <<= zs -> ys <<= zs -> rep xs zs = rep ys zs -> xs === ys.\n  Proof.\n    intros D E F. transitivity (rep xs zs).\n    -\n      symmetry. apply rep_equiv, D.\n    -\n      rewrite F. apply rep_equiv, E.\n  Qed.\n\n  Lemma rep_idempotent xs ys :\n    rep (rep xs ys) ys = rep xs ys.\n  Proof.\n    unfold rep at 1 3. apply filter_pq_eq.\n    intros x D. split.\n    +\n      apply rep_incl.\n    +\n      intros E.\n      apply In_filter_iff.\n      auto.\n  Qed.\n\n  Lemma dup_free_power xs :\n    dup_free xs -> dup_free (power xs).\n  Proof.\n    intros D. induction D as [|x U E D]; simpl.\n    -\n      constructor.\n      now auto.\n      constructor.\n    - apply dup_free_app. \n      + intros [A1 [F G]]. apply In_map_iff in G as [A' [G G']].\n        subst A1. apply E. apply (power_incl F). crush.       \n      + exact IHD.\n      + apply dup_free_map ; congruence.        \n  Qed.\n\n  Lemma dup_free_in_power xs ys :\n    xs el power ys -> dup_free ys -> dup_free xs.\n  Proof.\n    intros E D. revert xs E.\n    induction D as [|x U D D']; simpl; intros xs E ; crush.\n    - apply In_app_iff in E as [E|E] ; crush.\n      apply In_map_iff in E as [A' [E E']]. substs.\n      constructor.\n      *\n        intros F; apply D. apply (power_incl E'), F.\n      *\n        auto.\n  Qed.\n\n  Lemma rep_id xs : rep xs xs = xs.\n  Proof.\n    unfolds.\n    apply filter_id. tauto.\n  Qed.\n\n  Hint Resolve rep_id.\n\n  Lemma rep_nil ys :\n    rep [] ys = [].\n  Proof.\n    unfolds ; induction ys ; crush.\n    decide (False) ; crush.\n  Qed.\n\n  Hint Resolve rep_nil.\n    \n  Lemma rep_dup_free xs ys :\n    dup_free ys -> xs el power ys -> rep xs ys = xs.\n  Proof.\n    intros D ; revert xs.\n    induction D as [|x U E F] ; intros xs G.\n    - \n      destruct* G as [[]|[]].\n    -\n      simpl in G.\n      apply In_app_iff in G as [G|G].\n      +\n        simpl.\n        decide (x el xs) as [H|H].\n        *\n          exfalso.\n          apply E.\n          apply (power_incl G), H.\n        * \n          unfolds.\n          rewrite filter_fst' ; auto.\n          specialize (IHF _ G). crush.\n      +\n        apply In_map_iff in G as [A' [G H]]. subst xs.\n        unfold rep. simpl.\n        decide (x = x \\/ x el A') as [G|G] ; crush. \n        *\n          f_equal. specialize (IHF A' H). unfold rep in IHF. rewrite <- IHF at -2.\n          apply filter_pq_eq. apply power_incl in H.\n          intros z K. split; [|now auto].\n          intros [L|L]; subst; tauto.\n        *\n          exfalso. apply E. apply power_incl in H. eauto.\n  Qed.  \n\n  Lemma power_extensional xs ys zs :\n    dup_free zs -> xs el power zs -> ys el power zs -> xs === ys -> xs = ys.\n  Proof.\n    intros D E F G.\n    rewrite <- (rep_dup_free D E). rewrite <- (rep_dup_free D F).\n    apply rep_eq, G.\n  Qed.\n\nEnd POWER.", "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/Discrete/PowerList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6664031902896175}}
{"text": "(**************************************************************)\n(*   Copyright                                                *)\n(*             Jean-François Monin           [+]              *)\n(*             Dominique Larchey-Wendling    [*]              *)\n(*                                                            *)\n(*            [+] Affiliation VERIMAG - Univ. Grenoble-Alpes  *)\n(*            [*] Affiliation LORIA -- CNRS                   *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(* List traversal from right to left *)\nRequire Import List Utf8.\nImport ListNotations.\n\nRequire Import lr.\n(* The domain of 𝔾_foldl happens to be exactly 𝔻lz as defined in lr_rec *)\nRequire Import lr_rec.\n\n\n(* Here is a reference definition of List.fold_left, which follows the\nsame structural pattern as List.fold_right, but where lists are\ntraversed from right to left.\n\nlet rec foldl_ref f b l = fakematch l with\n  | [] → b\n  | u +: z → f (foldl_ref f b u) z\n\nThis can be actually programmed by reflecting this\ndecomposition of lists from the right using l2r.\n\nlet rec foldl_ref f b l = match l2r l with\n  | Nilr → b\n  | Consr (u, z) → f (foldl_ref f b u) z\n\nThis definition corresponds to the usual informal drawings explaining\nthe expected result. It is of course quite inefficient, however and it\ncan be seen as a specification of fold_left.\n\nlet rec foldl f b l = match l with\n   | [] → b\n   | x :: l → foldl f (f b x) l\n\nThis Coq scripts shows that foldl is actually equivalent to\nfoldl_ref.\n\nThe point is to get a Coq definition of foldl_ref, whereas\nthe recursion is not the usual structural recursion on lists.\nFollowing the method exposed at Braga, we start with an\ninductive graph corresponding to foldl_ref.\n*)\n\n(* -------------------------------------------------------------------------- *)\n(* Relational Graph *)\n\nSection sec_context.\n\nContext {A B: Type}.\nImplicit Type l u v : list A.\nImplicit Type r : lr A.\nImplicit Type x y z : A.\nImplicit Type b : B.\n\nSection sec_params_foldl.\nVariable f: B → A → B.\nVariable b0 : B.\n\n\nReserved Notation \"l '⟼fl' b\" (at level 70, format \"l  ⟼fl  b\").\n\nInductive 𝔾_foldl : list A → B → Prop :=\n| FLnil : [] ⟼fl b0\n| FLcons : ∀ {u z b},    u ⟼fl b   →  u +: z ⟼fl f b z\nwhere \"l ⟼fl b\" := (𝔾_foldl l b).\n\n(* A technical variant of FLcons, for later convenience *)\nDefinition FLcons_lrl {u z b} : lrl u ⟼fl b  →  u +: z ⟼fl f b z.\n  refine (fun G => FLcons _). pattern u. exact (down_llP _ u G).\nDefined.\n\n(* -------------------------------------------------------------------------- *)\n(* Using the Braga method *)\n\n(* foldl conform by construction (or \"packed with conformness\") *)\n\n(* The explicit dependent pattern matching\n\n   match l2r l as x return ** 𝔻lz (r2l x) ... → _ ** with\n\n   ** ... ** added below, is not needed any more for Coq 8.11+ *) \n\n(* Shape of the goal before refine:\n   𝔻lz (r2l (l2r l)) →\n   (∀y, r2l (l2r l) ⟼fl y → l ⟼fl y) →\n   {b | l ⟼fl b} *)\nLet Fixpoint foldl_pwc l (D: 𝔻lz l): {b | l ⟼fl b}.\nProof.\n  gen_help l 𝔾_foldl. apply up_llP in D; revert D.\n  refine (match l2r l as x return 𝔻lz (r2l x) \n                                → (∀ y : B, r2l x ⟼fl y → l ⟼fl y) \n                                → _ with\n          | Nilr      => λ D T,  exist _ b0 _\n          | Consr u z => λ D T,\n                 let (b, Gb) := foldl_pwc u (π_𝔻lz D) in\n                 exist _ (f b z) _\n          end).\n  - apply T; constructor 1.\n  - apply T; constructor 2; exact Gb.\nDefined.\n\n(* Alternative definition, with just an equality in the Trojan horse\n   -->\n   + simpler goal before refine\n   - structural inversion of D obtained after a rewriting step,\n     cannot directly be put in the match\n   - no explicit view of the rewriting steps\n     (rewrite makes no difference between eq_ind and eq_recT)\n*)\nLet Fixpoint foldl_pwc_eq l (D: 𝔻lz l): {b | l ⟼fl b}.\nProof.\n  generalize (lrl_id l).\n  (* r2l (l2r l) = l → {b | l ⟼fl b} *)\n  refine (match l2r l with\n          | Nilr      => λ E,  exist _ b0 _\n          | Consr u z => λ E,\n                  let (b, Gb) := foldl_pwc_eq u _ in\n                  exist _ (f b z) _\n          end); simpl in E.\n  - rewrite <- E in *. constructor 1.\n  - rewrite <- E in D. apply (π_𝔻lz D).\n  - rewrite <- E in *. constructor 2. exact Gb.\nDefined.\n\n(* The reference function for foldl *)\nDefinition foldl_ref l (D : 𝔻lz l) : B :=\n  proj1_sig (foldl_pwc l D).\n\nLemma foldl_ref_corr_partial l (D: 𝔻lz l) :\n  l ⟼fl foldl_ref l D.\nProof.\n  exact (proj2_sig (foldl_pwc l D)).\nQed.\n\n(* -------------------------------------------------------------------------- *)\n(* Version corresponding to OCaml fold_left *)\nFixpoint foldl b l : B :=\n    match l with\n    | [] => b\n    | x :: l => foldl (f b x) l\n    end.\n\n(* foldl is compatible with +: in the following sense *)\nLemma foldl_consr b (u: list A) (z: A) :\n  foldl b (u +: z) = f (foldl b u) z.\nProof.\n  revert b. induction u as [|x u Hu]; intro b; simpl.\n  - reflexivity.\n  - rewrite Hu. reflexivity.\nQed.\n\n(* Completeness of foldl wrt 𝔾_foldl follows *)\nTheorem foldl_compl b l :  l ⟼fl b  →  b = foldl b0 l.\nProof.\n  intro g. induction g as [ | u z b g Hg]; simpl.\n  - reflexivity.\n  - rewrite foldl_consr. rewrite Hg. reflexivity.\nQed.\n(* Corollary for free: 𝔾_foldl is functional; but useless *)\n\n(* Partial conformity wrt 𝔾_foldl: whenever l is in the domain,\n   fold computes a good result *)\n(* Induction on  𝔻lz l *)\nTheorem foldl_corr_partial l : 𝔻lz l  →  l ⟼fl foldl b0 l.\nProof.\n  intro D. induction D as [ | u Gu z].\n  - apply FLnil.\n  - rewrite foldl_consr. apply (FLcons Gu).\nQed.\n\n(* Total conformity wrt 𝔾_foldl follows independently *)\nCorollary foldl_corr l :  l  ⟼fl  foldl b0 l.\nProof.\n  apply foldl_corr_partial. apply 𝔻lz_all.\nQed.\n\nEnd sec_params_foldl.\n\n(* -------------------------------------------------------------------------- *)\n(* Partial conformity wrt foldl_ref: whenever foldl_ref terminates,\n   fold computes the same result *)\nTheorem foldl_equiv_partial :\n     ∀ f b l (D: 𝔻lz l), foldl f b l = foldl_ref f b l D.\nProof.\n  intros. symmetry. apply foldl_compl. apply foldl_ref_corr_partial.\nQed.\n\n(* Total conformity wrt foldl_ref follows independently *)\nCorollary foldl_equiv_total :\n    ∀ f b l, foldl f b l = foldl_ref f b l (𝔻lz_all l).\nProof.\n  intros; apply foldl_equiv_partial.\nQed.\n\n(* Additional remarks\n- conformity of foldl wrt foldl_ref needs its completeness wrt 𝔾_foldl,\n  not its conformity\n- conformity of foldl wrt 𝔾_foldl is technically easier:\n  an induction on the domain;\n  in contrast, the definition foldl_ref requires a stronger recursion,\n  including projective inversions (see lr_rec)\n- as expected, termination is considered separately (with 𝔻lz_all),\n  whatever the approach (using a relational or a functional specification)\n*)\n\nEnd sec_context.\n\n(* -------------------------------------------------------------------------- *)\n(* Extraction *)\n\nRequire Import Extraction.\nExtract Inductive list => \"list\" [ \"[]\" \"(::)\" ].\nRecursive Extraction foldl_ref foldl.\n(*\n\ntype 'a lr =\n| Nilr\n| Consr of 'a list * 'a\n\n(** val l2r : 'a1 list -> 'a1 lr **)\n\nlet rec l2r = function\n| [] -> Nilr\n| x::lr0 ->\n  (match l2r lr0 with\n   | Nilr -> Consr ([], x)\n   | Consr (lg, z) -> Consr ((x::lg), z))\n\n(** val foldl_ref : ('a2 -> 'a1 -> 'a2) -> 'a2 -> 'a1 list -> 'a2 **)\n\nlet rec foldl_ref f b0 l =\n  match l2r l with\n  | Nilr -> b0\n  | Consr (u, z) -> f (foldl_ref f b0 u) z\n\n(** val foldl : ('a2 -> 'a1 -> 'a2) -> 'a2 -> 'a1 list -> 'a2 **)\n\nlet rec foldl f b = function\n| [] -> b\n| x::l0 -> foldl f (f b x) l0\n\n\n*)\n\n\n(* -------------------------------------------------------------------------- *)\n", "meta": {"author": "DmxLarchey", "repo": "The-Braga-Method", "sha": "e4f51add22a73681103454ad94a05aeeda332c50", "save_path": "github-repos/coq/DmxLarchey-The-Braga-Method", "path": "github-repos/coq/DmxLarchey-The-Braga-Method/The-Braga-Method-e4f51add22a73681103454ad94a05aeeda332c50/theories/listz/foldl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.6663669456948353}}
{"text": "From mathcomp Require Import ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nRequire Import Coq.Logic.Decidable. (* Introducing decidable *)\nRequire Import Coq.Sets.Powerset_Classical_facts.\n\nNotation \"x ∈ X\" := (In _ X x) (right associativity, at level 48).\nNotation \"A ⊂ B\" := (Included _ A B) (right associativity, at level 51).\nNotation \"A ⊊ B\" := (Strict_Included _ A B) (right associativity, at level 51).\nNotation \"A ^c\"   := (Complement _ A) (at level 47).\nNotation \"A ∪ B\" := (Union _ A B) (left associativity, at level 50).\nNotation \"A ∩ B\" := (Intersection _ A B) (left associativity, at level 50).\nNotation \"A \\ B\"  := (Setminus _ A B) (left associativity, at level 50).\n\nNotation \"{||}\"  := (Empty_set _).\nNotation \"{| x |}\" := (Singleton _ x).\nNotation \"{| x , y , .. , z |}\" := (Union _ .. (Union _ (Singleton _ x) (Singleton _ y)) .. (Singleton _ z)).\n\nTheorem Axiom_of_EmptySet:\n  forall (U:Type) (X:Ensemble U), X = {||} <-> (forall (x:U), x ∈ X -> False).\n  move => X.\n  rewrite /iff.\n  split.\n  move => HE.\n  rewrite HE.\n  apply Noone_in_empty.\n  move => HF.\n  apply /Extensionality_Ensembles.\n  split => y.\n  move => H0.\n  move: (HF y).\n  case.\n  apply H0.\n  case.\nQed.\n\nTheorem not_empty_set_has_element:\n  forall (U:Type) (X:Ensemble U), ~(X={||}) <-> exists x:U, x ∈ X.\n  Proof.\n    rewrite /iff.\n    split => H.\n    -have L1: Inhabited U X.\n     apply not_empty_Inhabited.\n     apply H.\n     inversion L1.\n     exists x.\n     apply H0.\n    -inversion H as [x].\n     apply Inhabited_not_empty.\n     apply (Inhabited_intro U X x).\n     apply H0.\n  Qed.\n\n(* Axiom of separation { x;U | P(x) } *)\nInductive SchemaOfSeparation (U:Type) (x:U) (P:U -> Prop): Ensemble U :=\n  Definition_of_Schema_Sepatation:\n    forall (x0: U), P x0 -> In U (SchemaOfSeparation x P) x0.\n\nDefinition OrderedPair {U:Type} (a b : U) := {|{|a|},{|a,b|}|}.\n\n(* Axiom of the Power Set *)\nInductive DirectProduct {U:Type} (X Y:Ensemble U) : Ensemble (Ensemble (Ensemble U)) :=\n  Definition_of_DirectProduct:\n    forall (Z: Ensemble (Ensemble U)),\n      (exists x:U, exists y:U, (x ∈ X /\\ y ∈ Y /\\ Z = {|{|x|},{|x,y|}|})) ->\n      In (Ensemble (Ensemble U)) (DirectProduct X Y) Z.\n\n(* 𝔓:Unicode 1D513 *)\nNotation \"𝔓( X )\" := (@Power_set _ X) (at level 47).\n\nNotation \"X × Y\" := (DirectProduct X Y) (at level 47).\nNotation \"(| a , b |)\" := (OrderedPair a b) (at level 48).\n\n(* Binary Relation {z|z=(|x,y|) /\\ x ∈ X /\\ y ∈ Y} *)\n\nInductive FirstOfOrderedPair {U:Type} (XY: (Ensemble (Ensemble U))): Ensemble U :=\n| ordered_pair_first_accessor: forall (x:U), (exists y:U, (|x,y|) = XY) -> FirstOfOrderedPair XY x.\n\nInductive SecondOfOrderedPair {U:Type} (XY: (Ensemble (Ensemble U))): Ensemble U :=\n| ordered_pair_second_accessor: forall (y:U), (exists x:U, (|x,y|) = XY) -> SecondOfOrderedPair XY y.\n\nInductive Pr1 {U:Type} (XY: Ensemble (Ensemble (Ensemble U))) : Ensemble U :=\n| pr1_accessor: forall (x:U), (exists y:U, (|x,y|) ∈ XY) ->  Pr1 XY x.\n\nInductive Pr2 {U:Type} (XY: Ensemble (Ensemble (Ensemble U))) : Ensemble U :=\n| pr2_accessor: forall (y:U), (exists x:U, (|x,y|) ∈ XY) ->  Pr2 XY y.\n\nSection Class_Set.\n\n  Variable U:Type.\n\n  Lemma eq_iff: forall (V:Type) (x y:V), x = y <-> y = x.\n  Proof.\n  +move => V x y.\n   rewrite /iff.\n   split; move => H; rewrite H; reflexivity.\n  Qed.\n\n  Lemma singleton_eq_iff: forall (V:Type) (x y: V), x ∈ {|y|} <-> x = y.\n  Proof.\n    +move => V x y.\n     rewrite /iff.\n     split => H.\n     (* x ∈ {|y|} -> x = y *)\n     ++apply eq_sym.\n       apply Singleton_inv.\n       apply H.\n     (* x = y -> x ∈ {|y|} *)\n     ++rewrite H.\n       apply Singleton_intro.\n       reflexivity.\n  Qed.\n\n  Lemma eq_singleton_eq_element_iff: forall (x y : U), {|x|} = {|y|} <-> x = y.\n  Proof.\n    +move => x y.\n     rewrite /iff.\n     split => H.\n     (* {|x|} = {|y|} -> x = y *)\n     ++apply Singleton_inv.\n       rewrite H.\n       apply singleton_eq_iff.\n       reflexivity.\n     (* x = y -> {|x|} = {|y|} *)\n     ++rewrite H.\n       reflexivity.\n  Qed.\n\n  Theorem theorem_of_pairing: forall (V:Type) (x y z:V), x ∈ {|y,z|} <-> x = y \\/ x = z.\n  Proof.\n    +move => V x y z.\n     rewrite /iff.\n     split.     (* x ∈ {|y,z|} -> x = y \\/ x = z. *)\n     ++case => w H.\n       left.\n       apply singleton_eq_iff.\n       apply H.\n       right.\n       apply singleton_eq_iff.\n       apply H.\n     (*  x = y \\/ x = z -> x ∈ {|y,z|} *)\n     ++case => H; rewrite H.\n       left.\n       reflexivity.\n       right.\n       reflexivity.\n  Qed.\n\n  Theorem T_0: forall (a b c:U), {|a|} = {|b,c|} -> a = b /\\ b = c.\n  Proof.\n    move => a b c H.\n    have L1: b ∈ {|b,c|}.\n    left.\n    apply Singleton_intro.\n    reflexivity.\n    have L2: a=b.\n    rewrite -H in L1.\n    apply Singleton_inv.\n    apply L1.\n    split.\n    apply L2.\n    rewrite -L2.\n    have L3: c ∈ {|b,c|}.\n    right.\n    apply Singleton_intro.\n    reflexivity.\n    rewrite -H in L3.\n    apply Singleton_inv.\n    apply L3.\n  Qed.\n\n  Theorem T_1: forall (a b c d: U), a <> c -> {|a,b|}={|c,d|} -> a = d.\n  Proof.\n    +move => a b c d H0 H1.\n     --have L1: a ∈ {|a,b|}.\n       left.\n       apply Singleton_intro.\n       reflexivity.\n    +rewrite H1 in L1.\n    +move: L1.\n     rewrite theorem_of_pairing.\n     rewrite -imp_not_l.\n     apply.\n     apply H0.\n     apply classic.\n  Qed.\n\n  Theorem T_2: forall (V:Type) (a b c d: V),\n      {|a,b|}={|c,d|} <-> (a = c /\\ b = d) \\/ (a = d /\\ b = c).\n  Proof.\n    move => V.\n    (* x = z \\/ y = z -> x <> z -> y = z *)\n    ++have L0: forall (x y z: V), x = z \\/ y = z -> x <> z -> y = z.\n      move => x y z H.\n      apply or_not_l_iff_2.\n      apply classic.\n      move: H.\n      case => H.\n      left.\n      case.\n      exact H.\n      right.\n      exact H.\n    ++have L1: forall (x y: V), {|x, y|} = {|y, x|}.\n      move => x y.\n      apply /Extensionality_Ensembles.\n      split => z; case => w H.\n      right.\n      apply H.\n      left.\n      apply H.\n      right.\n      apply H.\n      left.\n      apply H.\n    +move => a b c d.\n     rewrite /iff.\n     split.\n     ++move => H.\n       apply imp_not_l.\n       apply classic.\n     --have L2: a <> c \\/ b <> d <-> (a = c /\\ b = d -> False).\n       rewrite /iff.\n       split => H0.\n       apply or_not_and.\n       apply H0.\n       apply not_and_or.\n       rewrite /not.\n       apply H0.\n    ++rewrite -L2.\n      case => H0.\n      split.\n      (* a = c \\/ a = d -> a <> c -> a = d *)\n      ---have L01: a = c \\/ a = d.\n         apply theorem_of_pairing.\n         rewrite -H.\n         left.\n         apply Singleton_intro.\n         reflexivity.\n      ---move: H0.\n         move: L01.\n         rewrite (eq_iff a c).\n         rewrite (eq_iff a d).\n         apply L0.\n      (* a = c \\/ b = c -> a <> c -> b = c *)\n      ---have L02: a = c \\/ b = c.\n         rewrite (eq_iff a c).\n         rewrite (eq_iff b c).\n         apply theorem_of_pairing.\n         rewrite H.\n         left.\n         apply Singleton_intro.\n         reflexivity.\n      ---move: H0.\n         move: L02.\n         apply L0.\n    +split.\n     ++move: H0.\n     (* b = d \\/ a = d -> b <> d -> a = d *)\n       ---have L30: b = d \\/ a = d.\n          rewrite (eq_iff b d).\n          rewrite (eq_iff a d).\n          apply theorem_of_pairing.\n          rewrite L1.\n          rewrite H.\n          right.\n          apply Singleton_intro.\n          reflexivity.\n     ++move: L30.\n       apply L0.\n     (* b = d -> b = c -> b <> d -> b = c *)\n     ++move: H0.\n       ---have L31: b = d \\/ b = c.\n          apply theorem_of_pairing.\n          rewrite L1.\n          rewrite -H.\n          right.\n          apply Singleton_intro.\n          reflexivity.\n     ++move: L31.\n       rewrite (eq_iff b d).\n       rewrite (eq_iff b c).\n       apply L0.\n    +case; case => [H0 H1]; rewrite H0; rewrite H1.\n     ++reflexivity.\n     ++apply L1.\n  Qed.\n\n  Theorem ordered_pair_iff: forall (x y w z: U), (| x , y |) = (| w , z |) <-> x = w /\\ y = z.\n  Proof.\n     unfold OrderedPair.\n    +move => x y w z.\n     rewrite /iff.\n     split.\n     (* {|{|x|}, {|x, y|}|} = {|{|w|}, {|w, z|}|} -> x = w /\\ y = z *)\n     ++move => H0.\n       ---have L1: ({|x|}={|w|}/\\{|x,y|}={|w,z|}) \\/ ({|x|}={|w,z|}/\\{|x,y|}={|w|}).\n          (* {|{|x|}, {|x, y|}|} = {|{|w|}, {|w, z|}|} -> ({|x|}={|w|}/\\{|x,y|}={|w,z|}) \\/ ({|x|}={|w,z|}/\\{|x,y|}={|w|}) *)\n          apply T_2.\n          apply H0.\n     ++move: L1.\n       (* ({|x|} = {|w|} /\\ {|x, y|} = {|w, z|}) \\/ ({|x|} = {|w, z|} /\\ {|x, y|} = {|w|}) -> x = w /\\ y = z *)\n       case.\n       +++case => H00. (* ({|x|} = {|w|} /\\ {|x, y|} = {|w, z|}) -> x = w /\\ y = z *)\n          rewrite T_2.\n          case.\n          apply.\n          case => H01 H02.\n          split.\n          move: H00.\n          apply eq_singleton_eq_element_iff.\n          rewrite -H01.\n          rewrite H02.\n          apply eq_sym.\n          move: H00.\n          apply eq_singleton_eq_element_iff.\n       +++case => H00 H01. (*({|x|} = {|w, z|} /\\ {|x, y|} = {|w|}) -> x = w /\\ y = z *)\n          ----have L1: x = w /\\ w = z.\n              move: H00.\n              apply T_0.\n          ----have L2: w = x /\\ x = y.\n              move: H01.\n          ----have L20: {|x,y|} = {|w|} <-> {|w|} = {|x,y|}.\n              rewrite /iff.\n              split; move => H20; rewrite H20; reflexivity.\n       +++rewrite L20.\n          apply T_0.\n          inversion L1.\n          inversion L2.\n          split.\n          apply H.\n          rewrite -H3.\n          rewrite -H1.\n          apply H.\n     (* x = w /\\ y = z -> {|{|x|}, {|x, y|}|} = {|{|w|}, {|w, z|}|} *)\n     ++case => H0 H1.\n       rewrite H0.\n       rewrite H1.\n       reflexivity.\n  Qed.\n\n  Lemma FirstOfOrderedPairAccess: forall (a b:U), FirstOfOrderedPair ((| a, b |)) = {|a|}.\n  Proof.\n    move => a b.\n    apply /Extensionality_Ensembles.\n    split => z.\n    case => [x [y]].\n    rewrite ordered_pair_iff.\n    case => H0 H1.\n    apply singleton_eq_iff.\n    apply H0.\n    move => H.\n    split.\n    exists b.\n    apply ordered_pair_iff.\n    split.\n    apply singleton_eq_iff.\n    apply H.\n    reflexivity.\n  Qed.\n\n  Lemma SecondOfOrderedPairAccess: forall (a b:U), SecondOfOrderedPair ((| a, b |)) = {|b|}.\n  Proof.\n    move => a b.\n    apply /Extensionality_Ensembles.\n    split => z.\n    case => [y [x]].\n    rewrite ordered_pair_iff.\n    case => Hxa Hyb.\n    apply singleton_eq_iff.\n    apply Hyb.\n    move => H.\n    split.\n    exists a.\n    rewrite ordered_pair_iff.\n    split.\n    reflexivity.\n    apply singleton_eq_iff.\n    apply H.\n  Qed.\n\nEnd Class_Set.\n\nExport Coq.Sets.Powerset_Classical_facts.\nExport Coq.Logic.Decidable.\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/class_set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619393159451, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.6662206657941538}}
{"text": " (* Gabriel Braun April 2013 *)\n\nRequire Export GeoCoq.Tarski_dev.Ch13_2_length.\n\nSection Angles_1.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\n(************************************* angle *****************************)\n\nLemma ang_exists : forall A B C, A <> B -> C <> B -> exists a, Q_CongA a /\\ a A B C.\nProof.\n    intros.\n    exists (fun D E F => CongA A B C D E F).\n    split.\n      unfold Q_CongA.\n      exists A.\n      exists B.\n      exists C.\n      split; auto.\n      split; auto.\n      intros.\n      split.\n        auto.\n      auto.\n    apply conga_refl; auto.\nQed.\n\nLemma ex_points_ang : forall a , Q_CongA a ->  exists A, exists B, exists C, a A B C.\nProof.\n    intros.\n    unfold Q_CongA in H.\n    ex_and H A.\n    ex_and H0 B.\n    ex_and H C.\n    assert(HH:= H1 A B C).\n    destruct HH.\n    exists A.\n    exists B.\n    exists C.\n    apply H2.\n    apply conga_refl; auto.\nQed.\n\nEnd Angles_1.\n\nLtac ang_instance a A B C :=\n  assert(tempo_ang:= ex_points_ang a);\n  match goal with\n    |H: Q_CongA a |-  _ => assert(tempo_H:=H); apply tempo_ang in tempo_H;\n                       elim tempo_H; intros A ; let tempo_HP := fresh \"tempo_HP\" in intro tempo_HP; clear tempo_H;\n                       elim tempo_HP; intro B; let tempo_HQ := fresh \"tempo_HQ\" in intro tempo_HQ ; clear tempo_HP ;\n                       elim tempo_HQ; intro C; intro;  clear tempo_HQ\n  end;\n  clear tempo_ang.\n\nSection Angles_2.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma ang_conga : forall a A B C A' B' C', Q_CongA a -> a A B C -> a A' B' C' -> CongA A B C A' B' C'.\nProof.\n    intros.\n    unfold Q_CongA in H.\n    ex_and H A0.\n    ex_and H2 B0.\n    ex_and H C0.\n    assert(HH:=H3 A B C).\n    assert(HH1:= H3 A' B' C').\n    destruct HH.\n    destruct HH1.\n    apply H5 in H0.\n    apply H7 in H1.\n    eapply conga_trans.\n      apply conga_sym.\n      apply H0.\n    auto.\nQed.\n\nLemma is_ang_conga : forall A B C A' B' C' a, Ang A B C a -> Ang A' B' C' a -> CongA A B C A' B' C'.\nProof.\n    intros.\n    unfold Ang in *.\n    spliter.\n    eapply (ang_conga a); auto.\nQed.\n\nLemma is_ang_conga_is_ang : forall A B C A' B' C' a, Ang A B C a -> CongA A B C A' B' C' -> Ang A' B' C' a.\nProof.\n    intros.\n    unfold Ang in *.\n    spliter.\n    split.\n      auto.\n    unfold Q_CongA in H.\n    ex_and H A0.\n    ex_and H2 B0.\n    ex_and H C0.\n    assert(HH:= H3 A B C).\n    destruct HH.\n    assert(HH1:= H3 A' B' C').\n    destruct HH1.\n    apply H5 in H1.\n    apply H6.\n    eapply conga_trans.\n      apply H1.\n    auto.\nQed.\n\nLemma not_conga_not_ang : forall A B C A' B' C' a , Q_CongA a -> ~(CongA A B C A' B' C') -> a A B C -> ~(a A' B' C').\nProof.\n    intros.\n    intro.\n    assert(HH:=ang_conga a A B C A' B' C' H H1 H2).\n    contradiction.\nQed.\n\nLemma not_conga_is_ang : forall A B C A' B' C' a , ~(CongA A B C A' B' C') -> Ang A B C a -> ~(a A' B' C').\nProof.\n    intros.\n    unfold Ang in H0.\n    spliter.\n    intro.\n    apply H.\n    apply (ang_conga a); auto.\nQed.\n\nLemma not_cong_is_ang1 : forall A B C A' B' C' a , ~(CongA A B C A' B' C') -> Ang A B C a -> ~(Ang A' B' C' a).\nProof.\n    intros.\n    intro.\n    unfold Ang in *.\n    spliter.\n    apply H.\n    apply (ang_conga a); auto.\nQed.\n\nLemma ex_eqa : forall a1 a2, (exists A , exists B, exists C, Ang A B C a1 /\\ Ang A B C a2)  -> EqA a1 a2.\nProof.\n    intros.\n    ex_and H A.\n    ex_and H0 B.\n    ex_and H C.\n    assert(HH:=H).\n    assert(HH0:=H0).\n    unfold Ang in HH.\n    unfold Ang in HH0.\n    spliter.\n    unfold EqA.\n    repeat split; auto; intro.\n      assert(CongA A B C A0 B0 C0).\n        eapply (is_ang_conga _ _ _ _ _ _ a1); auto.\n        split; auto.\n      assert(Ang A0 B0 C0 a2).\n        apply (is_ang_conga_is_ang A B C); auto.\n      unfold Ang in H7.\n      tauto.\n    assert(CongA A B C A0 B0 C0).\n      eapply (is_ang_conga _ _ _ _ _ _ a2); auto.\n      split; auto.\n    assert(Ang A0 B0 C0 a1).\n      apply (is_ang_conga_is_ang A B C); auto.\n    unfold Ang in H7.\n    tauto.\nQed.\n\nLemma all_eqa : forall A B C a1 a2, Ang A B C a1 -> Ang A B C a2 -> EqA a1 a2.\nProof.\n    intros.\n    apply ex_eqa.\n    exists A.\n    exists B.\n    exists C.\n    split; auto.\nQed.\n\nLemma is_ang_distinct : forall A B C a , Ang A B C a -> A <> B /\\ C <> B.\nProof.\n    intros.\n    unfold Ang in H.\n    spliter.\n    unfold Q_CongA in H.\n    ex_and H A0.\n    ex_and H1 B0.\n    ex_and H C0.\n    assert(HH:= H2 A B C).\n    destruct HH.\n    apply H4 in H0.\n    unfold CongA in H0.\n    spliter.\n    tauto.\nQed.\n\n\nLemma null_ang : forall A B C D a1 a2, Ang A B A a1 -> Ang C D C a2 -> EqA a1 a2.\nProof.\n    intros.\n    eapply (all_eqa A B A).\n      apply H.\n    eapply (is_ang_conga_is_ang C D C).\n      auto.\n    eapply l11_21_b.\n      apply out_trivial.\n      apply is_ang_distinct in H0.\n      tauto.\n    apply out_trivial.\n    apply is_ang_distinct in H.\n    tauto.\nQed.\n\nLemma flat_ang : forall A B C A' B' C' a1 a2, Bet A B C -> Bet A' B' C' -> Ang A B C a1 -> Ang A' B' C' a2  -> EqA a1 a2.\nProof.\n    intros.\n    eapply (all_eqa A B C).\n      apply H1.\n    eapply (is_ang_conga_is_ang A' B' C').\n      apply H2.\n    apply is_ang_distinct in H1.\n    apply is_ang_distinct in H2.\n    spliter.\n    eapply conga_line; auto.\nQed.\n\nLemma ang_distinct: forall a A B C, Q_CongA a -> a A B C -> A <> B /\\ C <> B.\nProof.\n    intros.\n    assert(Ang A B C a).\n      split; auto.\n    apply (is_ang_distinct _ _ _ a); auto.\nQed.\n\nLemma ex_ang : forall A B C, B <> A -> B <> C -> exists a, Q_CongA a /\\ a A B C.\nProof.\n    intros.\n    exists (fun X Y Z => CongA A B C X Y Z).\n    unfold Q_CongA.\n    split.\n      exists A.\n      exists B.\n      exists C.\n      split.\n        auto.\n      split.\n        auto.\n      intros.\n      split.\n        intro.\n        auto.\n      intro.\n      auto.\n    apply conga_refl; auto.\nQed.\n\n(************************************* Acute angle *****************************************)\n\nLemma anga_exists : forall A B C, A <> B -> C <> B -> Acute A B C -> exists a, Q_CongA_Acute a /\\ a A B C.\nProof.\n    intros.\n    exists (fun D E F => CongA A B C D E F).\n    split.\n      unfold Q_CongA.\n      exists A.\n      exists B.\n      exists C.\n      split.\n        auto.\n      intros.\n      split; auto.\n    apply conga_refl; auto.\nQed.\n\nLemma anga_is_ang : forall a, Q_CongA_Acute a -> Q_CongA a.\nProof.\n    intros.\n    unfold Q_CongA_Acute in H.\n    unfold Q_CongA.\n    ex_and H A.\n    ex_and H0 B.\n    ex_and H C.\n    exists A.\n    exists B.\n    exists C.\n    apply acute_distincts in H.\n    spliter.\n    split.\n      auto.\n    split.\n      auto.\n    intros.\n    split.\n      intro.\n      assert(Ang X Y Z a).\n        unfold Ang.\n        split.\n          unfold Q_CongA.\n          exists A.\n          exists B.\n          exists C.\n          split.\n            assumption.\n          split.\n            assumption.\n          auto.\n        assert(HH:= H0 X Y Z).\n        apply HH.\n        auto.\n      unfold Ang in H3.\n      spliter.\n      auto.\n    intro.\n    apply H0.\n    auto.\nQed.\n\nLemma ex_points_anga : forall a , Q_CongA_Acute a ->  exists A, exists B, exists C, a A B C.\nProof.\n    intros.\n    assert(HH:=H).\n    apply anga_is_ang in H.\n    ang_instance a A B C.\n    exists A.\n    exists B.\n    exists C.\n    assumption.\nQed.\n\nEnd Angles_2.\n\nLtac anga_instance a A B C :=\n  assert(tempo_anga:= ex_points_anga a);\n  match goal with\n    |H: Q_CongA_Acute a |-  _ => assert(tempo_H:=H); apply tempo_anga in tempo_H;\n                                 elim tempo_H; intros A ;\n                                 let tempo_HP := fresh \"tempo_HP\" in\n                                 intro tempo_HP; clear tempo_H;\n                                 elim tempo_HP; intro B;\n                                 let tempo_HQ := fresh \"tempo_HQ\" in\n                                 intro tempo_HQ ; clear tempo_HP ;\n                        elim tempo_HQ; intro C; intro;  clear tempo_HQ\n  end;\n  clear tempo_anga.\n\nRequire Import Setoid.\n\nSection Angles_3.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma anga_conga : forall a A B C A' B' C', Q_CongA_Acute a -> a A B C -> a A' B' C' -> CongA A B C A' B' C'.\nProof.\n    intros.\n    apply (ang_conga a); auto.\n    apply anga_is_ang.\n    auto.\nQed.\n\nLemma is_anga_to_is_ang : forall A B C a, Ang_Acute A B C a -> Ang A B C a.\nProof.\n    intros.\n    unfold Ang_Acute in H.\n    unfold Ang.\n    spliter.\n    split.\n      apply anga_is_ang.\n      auto.\n    auto.\nQed.\n\nLemma is_anga_conga : forall A B C A' B' C' a, Ang_Acute A B C a -> Ang_Acute A' B' C' a -> CongA A B C A' B' C'.\nProof.\n    intros.\n    unfold Ang_Acute in *.\n    spliter.\n    apply (anga_conga a); auto.\nQed.\n\nLemma is_anga_conga_is_anga : forall A B C A' B' C' a, Ang_Acute A B C a -> CongA A B C A' B' C' -> Ang_Acute A' B' C' a.\nProof.\n    intros.\n    unfold Ang_Acute in *.\n    spliter.\n    split.\n      auto.\n    apply anga_is_ang in H.\n    unfold Q_CongA in H.\n    ex_and H A0.\n    ex_and H2 B0.\n    ex_and H C0.\n    assert(HH:= H3 A B C).\n    destruct HH.\n    assert(HH1:= H3 A' B' C').\n    destruct HH1.\n    apply H5 in H1.\n    apply H6.\n    eapply conga_trans.\n      apply H1.\n    auto.\nQed.\n\nLemma not_conga_is_anga : forall A B C A' B' C' a , ~ CongA A B C A' B' C' -> Ang_Acute A B C a -> ~(a A' B' C').\nProof.\n    intros.\n    unfold Ang_Acute in H0.\n    spliter.\n    intro.\n    apply H.\n    apply (anga_conga a); auto.\nQed.\n\nLemma not_cong_is_anga1 : forall A B C A' B' C' a , ~ CongA A B C A' B' C' -> Ang_Acute A B C a -> ~ Ang_Acute A' B' C' a.\nProof.\n    intros.\n    intro.\n    unfold Ang_Acute in *.\n    spliter.\n    apply H.\n    apply (anga_conga a); auto.\nQed.\n\nLemma ex_eqaa : forall a1 a2, (exists A , exists B, exists C, Ang_Acute A B C a1 /\\ Ang_Acute A B C a2)  -> EqA a1 a2.\nProof.\n    intros.\n    apply ex_eqa.\n    ex_and H A.\n    ex_and H0 B.\n    ex_and H C.\n    exists A.\n    exists B.\n    exists C.\n    split; apply is_anga_to_is_ang; auto.\nQed.\n\nLemma all_eqaa : forall A B C a1 a2, Ang_Acute A B C a1 -> Ang_Acute A B C a2 -> EqA a1 a2.\nProof.\n    intros.\n    apply ex_eqaa.\n    exists A.\n    exists B.\n    exists C.\n    split; auto.\nQed.\n\nLemma is_anga_distinct : forall A B C a , Ang_Acute A B C a -> A <> B /\\ C <> B.\nProof.\n    intros.\n    apply (is_ang_distinct A B C a).\n    apply is_anga_to_is_ang.\n    auto.\nQed.\n\nGlobal Instance eqA_equivalence : Equivalence EqA.\nProof.\nsplit.\nunfold Reflexive.\nintros.\nunfold EqA.\nintros;tauto.\nunfold Symmetric, EqA.\nintros.\nfirstorder.\nunfold Transitive, EqA.\nintros.\nrewrite H.\napply H0.\nQed.\n\nLemma null_anga : forall A B C D a1 a2, Ang_Acute A B A a1 -> Ang_Acute C D C a2 -> EqA a1 a2.\nProof.\n    intros.\n    eapply (all_eqaa A B A).\n      apply H.\n    eapply (is_anga_conga_is_anga C D C).\n      auto.\n    eapply l11_21_b.\n      apply out_trivial.\n      apply is_anga_distinct in H0.\n      tauto.\n    apply out_trivial.\n    apply is_anga_distinct in H.\n    tauto.\nQed.\n\nLemma anga_distinct: forall a A B C, Q_CongA_Acute a -> a A B C -> A <> B /\\ C <> B.\nProof.\n    intros.\n    assert(Ang_Acute A B C a).\n      split; auto.\n    apply (is_anga_distinct _ _ _ a); auto.\nQed.\n\nLemma out_is_len_eq : forall A B C l, Out A B C -> Len A B l -> Len A C l -> B = C.\nProof.\n    intros.\n    assert(Cong A B A C).\n      apply (is_len_cong _ _ _ _ l); auto.\n    assert(A <> C).\n      unfold Out in H.\n      spliter.\n      auto.\n    eapply (l6_11_uniqueness A A C C ); Cong.\n    apply out_trivial.\n    auto.\nQed.\n\nLemma out_len_eq : forall A B C l, Q_Cong l -> Out A B C -> l A B -> l A C -> B = C.\nProof.\n    intros.\n    apply (out_is_len_eq A _ _ l).\n      auto.\n      split; auto.\n    split; auto.\nQed.\n\nLemma ex_anga : forall A B C, Acute A B C -> exists a, Q_CongA_Acute a /\\ a A B C.\nProof.\n    intros.\n    exists (fun X Y Z => CongA A B C X Y Z).\n    unfold Q_CongA_Acute.\n    assert (HH := acute_distincts A B C H).\n    spliter.\n    split.\n      exists A.\n      exists B.\n      exists C.\n      split; auto.\n      intros.\n      intros.\n      split.\n        intro.\n        auto.\n      intro.\n      auto.\n    apply conga_refl; auto.\nQed.\n\nLemma not_null_ang_ang : forall a, Q_CongA_nNull a -> Q_CongA a.\nProof.\n    intros.\n    unfold Q_CongA_nNull  in H.\n    spliter; auto.\nQed.\n\nLemma not_null_ang_def_equiv : forall a, Q_CongA_nNull a <-> (Q_CongA a /\\ exists A, exists B, exists C, a A B C /\\  ~Out B A C).\nProof.\n    intros.\n    split.\n      intro.\n      unfold Q_CongA_nNull in H.\n      spliter.\n      assert(HH:= H).\n      unfold Q_CongA in HH.\n      ex_and HH A.\n      ex_and H1 B.\n      ex_and H2 C.\n      split.\n        auto.\n      exists A.\n      exists B.\n      exists C.\n      assert(HH:= H3 A B C).\n      destruct HH.\n      assert(a A B C).\n        apply H4.\n        apply conga_refl; auto.\n      split.\n        auto.\n      apply (H0 A B C).\n      auto.\n    intros.\n    spliter.\n    ex_and H0 A.\n    ex_and H1 B.\n    ex_and H0 C.\n    unfold Q_CongA_nNull.\n    split; auto.\n    intros.\n    assert(CongA A0 B0 C0 A B C).\n      apply (ang_conga a); auto.\n    intro.\n    apply H1.\n    apply (l11_21_a A0 B0 C0); auto.\nQed.\n\nLemma not_flat_ang_def_equiv : forall a, Q_CongA_nFlat a <-> (Q_CongA a /\\ exists A, exists B, exists C, a A B C /\\  ~Bet A B C).\nProof.\n    intros.\n    split.\n      intro.\n      unfold Q_CongA_nFlat in H.\n      spliter.\n      assert(HH:= H).\n      unfold Q_CongA in HH.\n      ex_and HH A.\n      ex_and H1 B.\n      ex_and H2 C.\n      split.\n        auto.\n      exists A.\n      exists B.\n      exists C.\n      assert(HH:= H3 A B C).\n      destruct HH.\n      assert(a A B C).\n        apply H4.\n        apply conga_refl; auto.\n      split.\n        auto.\n      apply (H0 A B C).\n      auto.\n    intros.\n    spliter.\n    ex_and H0 A.\n    ex_and H1 B.\n    ex_and H0 C.\n    unfold Q_CongA_nFlat.\n    split; auto.\n    intros.\n    assert(CongA A0 B0 C0 A B C).\n      apply (ang_conga a); auto.\n    intro.\n    apply H1.\n    apply (bet_conga__bet A0 B0 C0); auto.\nQed.\n\nLemma ang_const : forall a A B, Q_CongA a -> A <> B -> exists C, a A B C.\nProof.\n    intros.\n    unfold Q_CongA in H.\n    ex_and H A0.\n    ex_and H1 B0.\n    ex_and H C0.\n    apply(swap_diff) in H1.\n    assert(HH:= H2 A0 B0 C0).\n    destruct HH.\n    assert(a A0 B0 C0).\n      apply H3.\n      apply conga_refl; auto.\n    assert(HH :=not_col_exists A B H0).\n    ex_and HH P.\n    induction(eq_dec_points A0 C0).\n      subst C0.\n      exists A.\n      assert(HH:= (H2 A B A)).\n      destruct HH.\n      apply H7.\n      apply conga_trivial_1; auto.\n    assert(HH:=angle_construction_2 A0 B0 C0 A B P H H7 H1).\n    ex_and HH C; auto.\n    exists C.\n    apply H2.\n    auto.\nQed.\n\nEnd Angles_3.\n\nLtac ang_instance1 a A B C :=\n\tassert(tempo_ang:= ang_const a A B);\n        match goal with\n           |H: Q_CongA a |-  _ => assert(tempo_H:= H);apply tempo_ang in tempo_H; ex_elim tempo_H C\n        end;\n        clear tempo_ang.\n\nSection Angles_4.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma ang_sym : forall a A B C, Q_CongA a -> a A B C -> a C B A.\nProof.\n    intros.\n    unfold Q_CongA in H.\n    ex_and H A0.\n    ex_and H1 B0.\n    ex_and H C0.\n    assert(HH:= H2 A B C).\n    destruct HH.\n    apply H4 in H0.\n    apply conga_right_comm in H0.\n    assert(HH:= H2 C B A).\n    destruct HH.\n    apply H5.\n    auto.\nQed.\n\nLemma ang_not_null_lg : forall a l A B C, Q_CongA a -> Q_Cong l -> a A B C -> l A B -> ~ Q_Cong_Null l.\nProof.\n    intros.\n    intro.\n    unfold Q_CongA in H.\n    unfold Q_Cong_Null in H3.\n    spliter.\n    unfold Q_Cong in H0.\n    ex_and H A0.\n    ex_and H5 B0.\n    ex_and H C0.\n    assert(HH:= H6 A B C).\n    destruct HH.\n    assert(CongA A0 B0 C0 A B C).\n      apply H8.\n      auto.\n    apply conga_distinct in H8.\n      spliter.\n      ex_and H0 A1.\n      ex_and H14 B1.\n      assert(HH:= H0 A B).\n      destruct HH.\n      ex_and H4 A'.\n      assert(HH:= H0 A' A').\n      destruct HH.\n      assert(Cong A1 B1 A' A').\n        apply H17.\n        auto.\n      assert(Cong A1 B1 A B).\n        apply H15.\n        auto.\n      apply cong_identity in H17.\n        subst B1.\n        apply cong_symmetry in H19.\n        apply cong_identity in H19.\n        contradiction.\n      auto.\n    auto.\nQed.\n\nLemma ang_distincts : forall a A B C, Q_CongA a -> a A B C -> A <> B /\\ C <> B.\nProof.\n    intros.\n    assert(HH:= ex_lg A B).\n    ex_and HH la.\n    assert(HH:= ex_lg C B).\n    ex_and HH lc.\n    assert(HH:= ang_not_null_lg a la A B C H H1 H0 H2).\n    assert(a C B A).\n      apply ang_sym; auto.\n    assert(HQ:= ang_not_null_lg a lc C B A H H3 H5 H4).\n    split; intro; subst B.\n      apply HH.\n      unfold Q_Cong_Null.\n      split.\n        auto.\n      exists A.\n      auto.\n    apply HQ.\n    unfold Q_Cong_Null.\n    split.\n      auto.\n    exists C.\n    auto.\nQed.\n\nLemma anga_sym : forall a A B C, Q_CongA_Acute a -> a A B C -> a C B A.\nProof.\n    intros.\n    unfold Q_CongA_Acute in H.\n    ex_and H A0.\n    ex_and H1 B0.\n    ex_and H C0.\n    assert(HH:= H1 A B C).\n    destruct HH.\n    apply H3 in H0.\n    apply conga_right_comm in H0.\n    assert(HH:= H1 C B A).\n    destruct HH.\n    apply H4.\n    auto.\nQed.\n\nLemma anga_not_null_lg : forall a l A B C, Q_CongA_Acute a -> Q_Cong l -> a A B C -> l A B -> ~ Q_Cong_Null l.\nProof.\n    intros.\n    intro.\n    unfold Q_CongA_Acute in H.\n    unfold Q_Cong_Null in H3.\n    spliter.\n    unfold Q_Cong in H0.\n    ex_and H A0.\n    ex_and H5 B0.\n    ex_and H C0.\n    assert(HH:= H5 A B C).\n    destruct HH.\n    assert(CongA A0 B0 C0 A B C).\n      apply H7.\n      auto.\n    apply conga_distinct in H8.\n    spliter.\n    ex_and H0 A1.\n    ex_and H13 B1.\n    assert(HH:= H0 A B).\n    destruct HH.\n    ex_and H4 A'.\n    assert(HH:= H0 A' A').\n    destruct HH.\n    assert(Cong A1 B1 A' A').\n      apply H16.\n      auto.\n    assert(Cong A1 B1 A B).\n      apply H14.\n      auto.\n    apply cong_identity in H17.\n    subst B1.\n    apply cong_symmetry in H18.\n    apply cong_identity in H18.\n    contradiction.\nQed.\n\nLemma anga_distincts : forall a A B C, Q_CongA_Acute a -> a A B C -> A <> B /\\ C <> B.\nProof.\n    intros.\n    assert(HH:= ex_lg A B).\n    ex_and HH la.\n    assert(HH:= ex_lg C B).\n    ex_and HH lc.\n    assert(HH:= anga_not_null_lg a la A B C H H1 H0 H2).\n    assert(a C B A).\n      apply anga_sym; auto.\n    assert(HQ:= anga_not_null_lg a lc C B A H H3 H5 H4).\n    split; intro; subst B.\n      apply HH.\n      unfold Q_Cong_Null.\n      split.\n        auto.\n      exists A.\n      auto.\n    apply HQ.\n    unfold Q_Cong_Null.\n    split.\n      auto.\n    exists C.\n    auto.\nQed.\n\nLemma ang_const_o : forall a A B P, ~Col A B P -> Q_CongA a -> Q_CongA_nNull a -> Q_CongA_nFlat a -> exists C, a A B C /\\ OS A B C P.\nProof.\n    intros.\n    assert(HH:= H0).\n    unfold Q_CongA in HH.\n    ex_and HH A0.\n    ex_and H3 B0.\n    ex_and H4 C0.\n    apply(swap_diff) in H4.\n    assert(HH:= H5 A0 B0 C0).\n    destruct HH.\n    assert(a A0 B0 C0).\n      apply H6.\n      apply conga_refl; auto.\n    assert(HH:=ang_distincts a A0 B0 C0 H0 H8).\n    assert(A0 <> C0).\n      intro.\n      subst C0.\n      unfold Q_CongA_nNull in H1.\n      spliter.\n      assert(HH:=H11 A0 B0 A0 H8).\n      apply HH.\n      apply out_trivial; auto.\n    spliter.\n    assert(A <> B).\n      intro.\n      subst B.\n      apply H.\n      Col.\n    assert(HH:=angle_construction_2 A0 B0 C0 A B P H10 H9 H4).\n    ex_and HH C; auto.\n    exists C.\n    assert(a A B C).\n      assert(HH:= H5 A B C).\n      destruct HH.\n      apply H15.\n      auto.\n    split.\n      auto.\n    induction H14.\n      auto.\n    unfold Q_CongA_nNull in H1.\n    spliter.\n    assert(HH:= H16 A B C H15).\n    unfold Q_CongA_nFlat in H2.\n    spliter.\n    assert(Hh:=H17 A B C H15).\n    apply False_ind.\n    assert(HH0:=ang_distincts a A B C H0 H15).\n    spliter.\n    assert(HP:=or_bet_out A B C).\n    induction HP.\n      contradiction.\n    induction H20.\n      contradiction.\n    contradiction.\nQed.\n\nLemma anga_const : forall a A B, Q_CongA_Acute a -> A <> B -> exists C, a A B C.\nProof.\n    intros.\n    apply anga_is_ang in H.\n    apply ang_const; auto.\nQed.\n\nEnd Angles_4.\n\nLtac anga_instance1 a A B C :=\n\tassert(tempo_anga:= anga_const a A B);\n        match goal with\n           |H: Q_CongA_Acute a |-  _ => assert(tempo_H:= H); apply tempo_anga in tempo_H; ex_elim tempo_H C\n        end;\n        clear tempo_anga.\n\nSection Angles_5.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma null_anga_null_anga' : forall a, Q_CongA_Null_Acute a <-> is_null_anga' a.\nProof.\n    intro.\n    split.\n      intro.\n      unfold Q_CongA_Null_Acute in H.\n      unfold is_null_anga'.\n      spliter.\n      split.\n        auto.\n      anga_instance a A B C.\n      assert(HH:= H0 A B C H1).\n      exists A.\n      exists B.\n      exists C.\n      split; auto.\n    intro.\n    unfold is_null_anga' in H.\n    unfold Q_CongA_Null_Acute.\n    spliter.\n    ex_and H0 A.\n    ex_and H1 B.\n    ex_and H0 C.\n    split; auto.\n    intros.\n    assert(CongA A B C A0 B0 C0).\n      apply (anga_conga a); auto.\n    apply (l11_21_a A B C); auto.\nQed.\n\nLemma is_null_anga_out : forall a A B C, Q_CongA_Acute a -> a A B C -> Q_CongA_Null_Acute a -> Out B A C.\nProof.\n    intros.\n    unfold Q_CongA_Null_Acute in H1.\n    spliter.\n    assert(HH:= (H2 A B C)).\n    apply HH.\n    auto.\nQed.\n\n\nLemma acute_not_bet : forall A B C, Acute A B C -> ~Bet A B C.\nProof.\n    intros.\n    unfold Acute in H.\n    ex_and H A0.\n    ex_and H0 B0.\n    ex_and H C0.\n    unfold LtA in H0.\n    spliter.\n    unfold LeA in H0.\n    ex_and H0 P.\n    unfold InAngle in H0.\n    spliter.\n    ex_and H5 X.\n    intro.\n    apply conga_distinct in H2.\n    spliter.\n    assert(A<>C) by (intro; treat_equalities; auto).\n    induction H6.\n      subst X.\n      apply H1.\n      apply conga_line; auto.\n    assert(Bet A0 B0 P).\n      apply (bet_conga__bet A B C); auto.\n    assert(Bet A0 B0 C0).\n      unfold Out in H6.\n      spliter.\n      induction H15.\n        eBetween.\n      eBetween.\n    apply H1.\n    apply (conga_line A B C); auto.\nQed.\n\nLemma anga_acute : forall a A B C , Q_CongA_Acute a -> a A B C -> Acute A B C.\nProof.\n    intros.\n    unfold Q_CongA_Acute in H.\n    ex_and H A0.\n    ex_and H1 B0.\n    ex_and H C0.\n    assert(HH:= acute_lea_acute A B C A0 B0 C0).\n    apply HH.\n      auto.\n    unfold LeA.\n    exists C0.\n    split.\n      unfold InAngle.\n      apply acute_distincts in H.\n      spliter.\n      repeat split; auto.\n      exists C0.\n      split.\n        Between.\n      right.\n      apply out_trivial.\n      auto.\n    assert(HP:= H1 A B C).\n    destruct HP.\n    apply conga_sym.\n    apply H3.\n    auto.\nQed.\n\nLemma not_null_not_col : forall a A B C, Q_CongA_Acute a -> ~ Q_CongA_Null_Acute a -> a A B C -> ~Col A B C.\nProof.\n    intros.\n    intro.\n    apply H0.\n    unfold Q_CongA_Null_Acute.\n    split.\n      auto.\n    assert(Acute A B C).\n      apply (anga_acute a); auto.\n    intros.\n    assert(Out B A C).\n      apply acute_col__out; auto.\n    assert(HH:= anga_conga a A B C A0 B0 C0 H H1 H4).\n    apply (l11_21_a A B C); auto.\nQed.\n\n\nLemma ang_cong_ang : forall a A B C A' B' C', Q_CongA a -> a A B C -> CongA A B C A' B' C' -> a A' B' C'.\nProof.\n    intros.\n    assert(Ang A B C a).\n      unfold Ang.\n      split; auto.\n    assert(Ang A' B' C' a).\n      apply (is_ang_conga_is_ang A B C); auto.\n    unfold Ang in H3.\n    tauto.\nQed.\n\nLemma is_null_ang_out : forall a A B C, Q_CongA a -> a A B C -> Q_CongA_Null a -> Out B A C.\nProof.\n    intros.\n    unfold Q_CongA_Null in H1.\n    spliter.\n    assert(HH:= (H2 A B C)).\n    apply HH.\n    auto.\nQed.\n\nLemma out_null_ang : forall a A B C, Q_CongA a -> a A B C -> Out B A C -> Q_CongA_Null a.\nProof.\n    intros.\n    unfold Q_CongA_Null.\n    split.\n      auto.\n    intros.\n    assert(HH:=l11_21_a A B C A0 B0 C0 H1).\n    apply HH.\n    apply (ang_conga a); auto.\nQed.\n\nLemma bet_flat_ang : forall a A B C, Q_CongA a -> a A B C -> Bet A B C -> Ang_Flat a.\nProof.\n    intros.\n    unfold Ang_Flat.\n    split.\n      auto.\n    intros.\n    assert(HH:=bet_conga__bet A B C A0 B0 C0 H1).\n    apply HH.\n    apply (ang_conga a); auto.\nQed.\n\nLemma out_null_anga : forall a A B C, Q_CongA_Acute a -> a A B C -> Out B A C -> Q_CongA_Null_Acute a.\nProof.\n    intros.\n    unfold Q_CongA_Null_Acute.\n    split.\n      auto.\n    intros.\n    assert(HH:=l11_21_a A B C A0 B0 C0 H1).\n    apply HH.\n    apply (anga_conga a); auto.\nQed.\n\nLemma anga_not_flat : forall a, Q_CongA_Acute a -> Q_CongA_nFlat a.\nProof.\n    intros.\n    unfold Q_CongA_nFlat.\n    split.\n      apply anga_is_ang in H.\n      auto.\n    intros.\n    assert(HH:= anga_acute a A B C H H0).\n    unfold Q_CongA_Acute in H.\n    ex_and H A0.\n    ex_and H1 B0.\n    ex_and H C0.\n    assert(HP:= H1 A B C).\n    apply acute_not_bet.\n    auto.\nQed.\n\n\nLemma anga_const_o : forall a A B P, ~Col A B P -> ~ Q_CongA_Null_Acute a -> Q_CongA_Acute a -> exists C, a A B C /\\ OS A B C P.\nProof.\n    intros.\n    assert(Q_CongA a).\n      apply anga_is_ang; auto.\n    assert(Q_CongA_nNull a).\n      unfold Q_CongA_nNull.\n      split.\n        auto.\n      intros A' B' C' HP.\n      intro.\n      apply H0.\n      eapply (out_null_anga a A' B' C'); auto.\n    assert(Q_CongA_nFlat a).\n      apply anga_not_flat.\n      auto.\n    assert(HH:= ang_const_o a A B P H H2 H3 H4).\n    auto.\nQed.\n\nLemma anga_conga_anga : forall a A B C A' B' C' , Q_CongA_Acute a -> a A B C -> CongA A B C A' B' C' -> a A' B' C'.\nProof.\n    intros.\n    unfold Q_CongA_Acute in H.\n    ex_and H A0.\n    ex_and H2 B0.\n    ex_and H C0.\n    assert(HH := H2 A B C).\n    assert(HP := H2 A' B' C').\n    destruct HH.\n    destruct HP.\n    apply H4 in H0.\n    assert(CongA A0 B0 C0 A' B' C').\n      eapply conga_trans.\n        apply H0.\n      apply H1.\n    apply H5.\n    auto.\nQed.\n\nLemma anga_out_anga : forall a A B C A' C', Q_CongA_Acute a -> a A B C -> Out B A A' -> Out B C C' -> a A' B C'.\nProof.\n    intros.\n    assert(HH:= H).\n    unfold Q_CongA_Acute in HH.\n    ex_and HH A0.\n    ex_and H3 B0.\n    ex_and H4 C0.\n    assert(HP:= H4 A B C).\n    destruct HP.\n    assert(CongA A0 B0 C0 A B C).\n      apply H6.\n      auto.\n    assert(HP:= anga_distincts a A B C H H0).\n    spliter.\n    assert(CongA A B C A' B C').\n      apply out2__conga; apply l6_6; assumption.\n    assert(HH:= H4 A' B C').\n    destruct HH.\n    apply H11.\n    apply (conga_trans _ _ _ A B C); auto.\nQed.\n\nLemma out_out_anga : forall a A B C A' B' C', Q_CongA_Acute a -> Out B A C -> Out B' A' C' -> a A B C -> a A' B' C'.\nProof.\n    intros.\n    assert(CongA A B C A' B' C').\n      apply l11_21_b; auto.\n    apply (anga_conga_anga a A B C); auto.\nQed.\n\nLemma is_null_all : forall a A B, A <> B -> Q_CongA_Null_Acute a -> a A B A.\nProof.\n    intros.\n    unfold Q_CongA_Null_Acute in H0.\n    spliter.\n    assert(HH:= H0).\n    unfold Q_CongA_Acute in HH.\n    ex_and HH A0.\n    ex_and H2 B0.\n    ex_and H3 C0.\n    apply acute_distincts in H2.\n    spliter.\n    apply H3.\n    assert (a A0 B0 C0).\n      apply H3.\n      apply conga_refl; auto.\n    assert(HH:= (H1 A0 B0 C0 H5)).\n    apply l11_21_b; auto.\n    apply out_trivial.\n    auto.\nQed.\n\nLemma anga_col_out : forall a A B C, Q_CongA_Acute a -> a A B C -> Col A B C -> Out B A C.\nProof.\n    intros.\n    assert(Acute A B C).\n      apply (anga_acute a); auto.\n    unfold Col in H1.\n    induction H1.\n      apply acute_not_bet in H2.\n      contradiction.\n    unfold Out.\n    apply (anga_distinct a A B C) in H.\n      spliter.\n      repeat split; auto.\n      induction H1.\n        right.\n        auto.\n      left.\n      Between.\n    auto.\nQed.\n\nLemma ang_not_lg_null : forall a la lc A B C, Q_Cong la -> Q_Cong lc -> Q_CongA a ->\n la A B -> lc C B -> a A B C -> ~ Q_Cong_Null la /\\ ~ Q_Cong_Null lc.\nProof.\n    intros.\n    assert(HH:=ang_distincts a A B C H1 H4).\n    spliter.\n    split.\n      intro.\n      unfold Q_Cong_Null in H7.\n      spliter.\n      ex_and H8 P.\n      assert(HH:= lg_cong la A B P P H H2 H9).\n      apply cong_identity in HH.\n      contradiction.\n    intro.\n    unfold Q_Cong_Null in H7.\n    spliter.\n    ex_and H8 P.\n    assert(HH:= lg_cong lc C B P P H0 H3 H9).\n    apply cong_identity in HH.\n    contradiction.\nQed.\n\nLemma anga_not_lg_null : forall a la lc A B C, Q_Cong la -> Q_Cong lc ->\n Q_CongA_Acute a -> la A B -> lc C B -> a A B C -> ~ Q_Cong_Null la /\\ ~ Q_Cong_Null lc.\nProof.\n    intros.\n    apply anga_is_ang in H1.\n    apply(ang_not_lg_null a la lc A B C); auto.\nQed.\n\nLemma anga_col_null : forall a A B C, Q_CongA_Acute a -> a A B C -> Col A B C -> Out B A C /\\ Q_CongA_Null_Acute a.\nProof.\n    intros.\n    assert(HH:= anga_distincts a A B C H H0).\n    spliter.\n    assert(Out B A C).\n      induction H1.\n        assert(HP:=anga_acute a A B C H H0).\n        assert(HH:=acute_not_bet A B C HP).\n        contradiction.\n      induction H1.\n        unfold Out.\n        repeat split; auto.\n      unfold Out.\n      repeat split; auto.\n      left.\n      Between.\n    split.\n      auto.\n    apply (out_null_anga a A B C); auto.\nQed.\n\nLemma eqA_preserves_ang: forall a b, Q_CongA a -> EqA a b -> Q_CongA b.\nProof.\nintros.\nunfold Q_CongA in *.\ndecompose [ex and] H.\nexists x. exists x0. exists x1.\nsplit.\nassumption.\nsplit.\nassumption.\nintros.\nrewrite H4.\nunfold EqA in H0.\napply H0.\nQed.\n\nLemma eqA_preserves_anga : forall a b, Q_CongA_Acute a -> Q_CongA b -> EqA a b -> Q_CongA_Acute b.\nProof.\n    intros.\n    assert (Q_CongA a).\n        apply eqA_preserves_ang with b;auto.\n        symmetry;auto.\n    unfold EqA in H1.\n    anga_instance a A B C.\n\n    assert(HH:= H1 A B C).\n    destruct HH.\n    unfold Q_CongA_Acute.\n    exists A.\n    exists B.\n    exists C.\n    split.\n      unfold Q_CongA_Acute in H.\n      ex_and H A'.\n      ex_and H6 B'.\n      ex_and H C'.\n      assert(a A' B' C').\n        assert(HP:= H6 A B C).\n        destruct HP.\n        assert(CongA A B C A' B' C') by (apply conga_sym;auto).\n        assert(HP:=is_ang_conga_is_ang A B C A' B' C' a).\n        assert(Ang A' B' C' a).\n          apply HP.\n            split; auto.\n          auto.\n        unfold Ang in H10.\n        spliter.\n        auto.\n      apply (acute_lea_acute _ _ _ A' B' C').\n        auto.\n      unfold LeA.\n      exists C'.\n      split.\n        assert (HH:= acute_distincts A' B' C' H).\n        spliter.\n        apply inangle3123; auto.\n      apply (is_ang_conga _ _ _ _ _ _ a).\n        split; auto.\n      split; auto.\n    intros.\n    split.\n      intro.\n      assert(HH:= H1 X Y Z).\n      destruct HH.\n      assert(Ang X Y Z a).\n        eapply (is_ang_conga_is_ang A B C).\n          split; auto.\n        auto.\n      unfold Ang in H9.\n      spliter.\n      auto.\n    intro.\n    assert(HH:= H1 X Y Z).\n    destruct HH.\n    assert(a X Y Z).\n      auto.\n    apply (is_ang_conga _ _ _ _ _ _ a).\n      split; auto.\n    split; auto.\nQed.\n\nEnd Angles_5.", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Tarski_dev/Ch13_3_angles.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634457, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.6662206556637851}}
{"text": "Require Export XR_R.\nRequire Export XR_Rle.\nRequire Export XR_Rlt_asym.\n\nImplicit Type r : R.\nLocal Open Scope R_scope.\n\nLemma Rle_antisym : forall r1 r2, r1 <= r2 -> r2 <= r1 -> r1 = r2.\nProof.\n  intros x y.\n  intros hxy hyx.\n  unfold \"<=\" in hxy, hyx.\n  destruct hxy as [ hxy | heq ].\n  {\n    destruct hyx as [ hyx | heq ].\n    {\n      exfalso.\n      assert (asym := Rlt_asym x y).\n      unfold \"~\" in asym.\n      apply asym.\n      { exact hxy. }\n      { exact hyx. }\n    }\n    { subst y. reflexivity. }\n  }\n  { subst y. reflexivity. }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rle_antisym.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.6662206369352476}}
{"text": "Definition or_user_2[a:bool]:=<bool->bool>Case a of ([_:bool]true) ([b:bool]b)  end.\n\nParameter c:bool.\nLemma or1:(or_user_2 true c)=true.\nSimpl.\nTrivial.\nSave.\n\nRequire codigoCoq.\nRequire Arith.\n\n(* ===== OPERACIONES DE NUMEROS NATURALES =========*)\n\n\n(* suma de dos naturales, resultado natural *)\nFixpoint sumN[n,m:nat]:nat:=\nCases n m of\nh O=>h\n|h (S i)=>(S (sumN h i))\nend.\n\n(* predecesor de un natural, para el cero es cero *)\nDefinition predN:=[n:nat]Cases n of O=>O | (S i)=>i end.\n\n(* resta de dos naturales, resultado natural *)\nFixpoint restaN[n,m:nat]:nat:=\nCases n m of\nh O=>h\n|h (S k)=>(predN(restaN h k))\nend.\n\n(* resta de dos naturales, resultado natural, VERSION _REC *)\nDefinition mi_restaN:=[n:nat]\n(nat_rec [_:nat]nat n [k,b:nat](predN b)).\n\n\n(* producto de naturales, resultado natural *)\nFixpoint productoN[n,m:nat]:nat:= Cases n m of\n_ O => O\n|k (S l)=> (sumN k (productoN k l))\nend.\n\n(* potencia de naturales, resultado natural *)\nFixpoint potenciaN[n,m:nat]:nat:= Cases n m of\n_ O => (S O)\n|k (S l)=> (productoN k (potenciaN k l))\nend.\n\n\n(* factorial de un natural, resultado natural *)\nFixpoint factorial[n:nat]:nat:=\nCases n of\nO => (S O)\n|(S l)=>(productoN (S l) (factorial l))\nend.\n\n(* factorial de un natural, resultado natural, VERSION _REC *)\nDefinition mifactorial:=\n(nat_rec ([_:nat]nat) (S O) [j:nat][l:nat](productoN (S j) l)).\n\n(* potencia de dos naturales, resultado natural, VERSION _REC *)\nDefinition mipotencia:=[x:nat]\n(nat_rec ([_:nat]nat) (S O) [k:nat][v:nat](productoN x v)).\n\n(* producto de dos naturales, resultado natural, VERSION _REC *)\nDefinition miproducto:=[x:nat]\n(nat_rec ([_:nat]nat) O [k:nat][f:nat](sumN x f)).\n\n(* suma de dos naturales, resultado natural, VERSION _REC *)\nDefinition misuma:=[x:nat]\n(nat_rec ([_:nat]nat) x [k:nat][f:nat](S f)).\n\n\n(* LEMAS DE LAS RESTAS==================*)\n\n\n(* primer lema sobre las restas *)\nLemma restaN_eq1:(n,m:nat)(restaN n m)=(mi_restaN  n m).\nIntros.\nInduction m.\nSimpl.\nTrivial.\nSimpl.\nInduction n.\nRewrite Hrecm.\nTrivial.\nRewrite Hrecm.\nTrivial.\nSave.\n\n(* segundo lema sobre la resta *)\nLemma mi_restaN_1:(n:nat)(mi_restaN O n)=O.\nInduction n.\nSimpl; Trivial.\nSimpl.\nIntros.\nRewrite H.\nSimpl.\nTrivial.\nSave.\n\n(* tercer lema sobre la resta *)\nLemma mi_restaN_2:(n:nat)(mi_restaN n O)=n.\nInduction n.\nSimpl; Trivial.\nSimpl.\nTrivial.\nSave.\n\n(* IGUALDAD ======= *)\n(* igualdad para los naturales *)\nFixpoint egal_nat[n:nat]:nat->bool:=\n[m:nat]\nCases n m of\nO O=>true\n|(S n) (S m)=>(egal_nat n m)\n|_ _=>false\nend.\n\n(* comprobacion de igualdad con cero *)\nDefinition es_cero[n:nat]:=\nCases n of\nO=>true\n|(S n)=>false\nend.\n\n(* igualdad para los naturales, VERSION _REC *)\nDefinition egal_natt:=[n:nat]\n(nat_rec [_:nat]bool (if (es_cero n) then true else false)\n[indice:nat][k:bool](if (k) then false else \n\t\t\t(if (es_cero (minus (S indice) n)) \n\t\t\t\tthen true \n\t\t\t\telse false)\n\t\t    )\t\t\t\n).\n\n\n\n(* ===== DEFINICION DE ENTEROS ===== *)\nInductive Set Z:=\ncero:Z\n|pos:nat->Z\n|neg:nat->Z.\n\n\n(* primera version de opuestos de enteros *)\nDefinition opuestoZ[a:Z]:=\nCases a of\ncero=>cero\n|(pos n)=>(neg n)\n|(neg n)=>(pos n)\nend.\n\n(* segunda version de opuestos de enteros *)\nDefinition opu_Z[a:Z]:=\nCases a of\ncero=>cero\n|(pos n)=>(neg n)\n|(neg n)=>(pos n)\nend.\n\n(* opuesto de un entero, VERSION _REC *)\nDefinition mi_opuesto:=\n(Z_rec ([_:Z]Z) cero [v:nat](neg v) [vn:nat](pos vn)).\n\n\n(* siguiente de un entero *)\nDefinition sigZ[a:Z]:=\nCases a of\ncero=>(pos O)\n|(pos n)=>(pos (S n))\n|(neg O)=>cero\n|(neg (S n))=>(neg n)\nend.\n\n(* predecesor de un entero *)\nDefinition predZ[a:Z]:=\nCases a of\ncero=>(neg O)\n|(pos (S n))=>(pos  n)\n|(pos O)=>cero\n|(neg n)=>(neg (S n))\nend.\n\n\n(* igual a signo(a)*(abs(a)+1) *)\nDefinition absZ[a:Z]:=\nCases a of\ncero=>(pos O)\n|(pos n)=>(pos (S n))\n|(neg n)=>(neg (S n))\nend.\n\n(* proyeccion de nat sobre Z, impares son positivos, pares negativos *)\nFixpoint semantica[n:nat]:Z:=\nCases n of\nO=>cero\n|(S O)=>(pos O)\n|(S(S O))=>(neg O)\n|(S(S n))=>(absZ (semantica n))\nend.\n\n\n(* resta de dos naturales,resultado entero *)\nFixpoint difN[n:nat]:nat->Z:=\nCases n of \nO => ([n2:nat] Cases n2 of O=>cero | (S k)=>(neg k) end)\n|(S l) => ([n2:nat] Cases n2 of O=>(pos l) | (S m)=> (difN l m) end)\nend.\n\n(* suma de dos naturales, resultado entero *)\nFixpoint sumZ[n:nat]:nat->Z:=\nCases n of\nO => ([n2:nat] Cases n2 of O=>cero | (S k)=>(pos k) end)\n|(S l) => ([n2:nat] Cases n2 of O=>(pos l) | (S m)=> (sigZ(sumZ l (S m))) end)\nend.\n\n(* suma de dos enteros, resultado entero *)\nDefinition suma[a,b:Z]:=<Z>Cases (a,b) of\n(cero,v)=>v\n|(v,cero)=>v\n|((pos n),(pos m))=>(sumZ (S n) (S m))\n|((pos n),(neg m))=>(difN (S n) (S m))\n|((neg n),(pos m))=>(difN (S m) (S n))\n|((neg n),(neg m))=>(opu_Z (sumZ (S n) (S m)))\nend.\n\n(* TONTERIAS =================================*)\n\n(* proyeccion de los naturales sobre las expresiones *)\nFixpoint semExpr[e:expr]:Z:=\nCases e of\nCERO => cero\n| UNO => (pos O)\n| (mas a b)=>(suma (semExpr a) (semExpr b))\n| (menos a b)=>(suma (semExpr a) (opu_Z (semExpr b)))\nend.\n\n(* TONTERIAS =================================*)\n(* lemas de los ejercicios *)\nLemma consUno:(n,m:nat)(n=m)->(pos n)=(pos m).\nIntros.\nRewrite H.\nTrivial.\nSave.\n\nLemma consDos:(n,m:nat)(n=m)->(neg n)=(neg m).\nIntros.\nRewrite H.\nTrivial.\nSave.\n\nLemma diffff:(n,m:nat)(difN (S n) (S m))=(difN n m).\nIntros.\nSimpl.\nTrivial.\nSave.\n\n(*======= DEFINICIONES DE LISTAS =================================*)\n(* Seccion de listas *)\n\n(* definicion de las listas *)\nInductive lista[A:Set]:Set:=\nNil:(lista A)\n|Cons:A->(lista A)->(lista A).\n\n(* obtencion de la cola de una lista *)\nDefinition cdr[A:Set;l:(lista A)]:=<lista A>Cases l of\nNil=>(Nil A)\n|(Cons A x)=>x\nend.\n\n(* obtiene la cola de una lista, VERSION _REC *)\nDefinition micdr:=[A:Set]\n(lista_rec A [_:(lista A)](lista A) (Nil A) [_:A][l:(lista A)][_:(lista A)]l).\n\n(* concatena dos listas *)\nFixpoint concat[A:Set;l:(lista A)]:(lista A)->(lista A):=\nCases l of\nNil=>[m:(lista A)]m\n|(Cons x cd)=>[m:(lista A)](Cons A x (concat A cd m))\nend.\n\n(* concatena un elemento a una lista por detras, VERSION _REC *)\nDefinition mi_concatenar:=[A:Set;e:A]\n(lista_rec A [_:(lista A)](lista A)\n\t(Cons A e (Nil A))\n\t[x:A;_:(lista A);l2:(lista A)](Cons A x l2)\n).\n\n(* concatena dos listas, VERSION _REC, NO FUNCIONA *)\n(*\nDefinition mi_concat:=[A:Set;l1:(lista A)]\n(lista_rec A [_:(lista A)](lista A) (invertir A l1)\n\t[x:A;la:(lista A)][l2:(lista A)](Cons A x l2)\n).\n*)\n\n(* comprobacion *)\n(*\nEval Compute in (concat nat (Cons nat (3) (Cons nat (2) (Nil nat))) (Cons nat (1) (Cons nat (0) (Nil nat)))).\n*)\n\n(* obtiene la longitud de una lista *)\nFixpoint longit[A:Set;l:(lista A)]:nat:=\nCases l of\nNil=>O\n|(Cons _ cd)=>(S (longit A cd))\nend.\n\n\n(* obtiene la longitud de una lista , VERSION _REC*)\nDefinition milongit:=[A:Set]\n(lista_rec A ([_:(lista A)]nat) O [_:A][l:(lista A)]S).\n\n(* invierte una lista *)\nFixpoint invertir[A:Set;l:(lista A)]:(lista A):=\nCases l of\nNil => (Nil A)\n|(Cons x l')=>(concat A (invertir A l') (Cons A x (Nil A)))\nend.\n\n(* invierte una lista, VERSION _REC *)\nDefinition miinvertir:=[A:Set]\n(lista_rec A ([_:(lista A)](lista A)) (Nil A) [v:A][l:(lista A)][m:(lista A)]\n(concat A m (Cons A v (Nil A)))).\n\n(* cuenta el numero de ocurrencias de un entero en una lista de enteros *)\nFixpoint nocc[e:nat;l:(lista nat)]:nat:=\nCases l of\nNil => O\n|(Cons x v)=>(if (egal_nat e x) then (S (nocc e v)) else (nocc e v))\nend.\n\n(* cuenta el numero de ocurrencias de un entero en una lista de enteros, VERSION _REC *)\nDefinition mi_nocc:=[e:nat]\n(lista_rec nat [_:(lista nat)]nat O \n\t([i:nat;l:(lista nat);anterior:nat](if (egal_nat anterior e) \n\t\t\t\t\t\tthen (S i)\n\t\t\t\t\t\telse i)\n\t)\n).\n\n(* obtiene la primera posicion de un elemento en una lista,funcion auxiliar *)\nFixpoint posicion_aux[e:nat;l:(lista nat)]:nat->nat:=[i:nat]\nCases l of\nNil=>O\n|(Cons x l')=>(if (egal_nat e x) then (S i) else (posicion_aux e l' (S i)))\nend.\n\n(* obtiene la primera posicion de un elemento en una lista *)\nDefinition posicion:=[e:nat;l:(lista nat)](posicion_aux e l O).\n\n(* obtiene la primera posicion de un elemento en una lista, VERSION _REC *)\nDefinition mi_posicion:=[e:nat]\n(lista_rec nat [_:(lista nat)]nat O\n\t[y:nat;li:(lista nat)][ant:nat](if (egal_nat y e) then (S O)\n\t\t\t\t\telse (if (egal_nat O ant) \n\t\t\t\t\t\tthen O \n\t\t\t\t\t\telse (S ant)\n\t\t\t\t\t      )\n\t\t\t\t\t)\n).\n\n\n\n(*=================================*)\n\n\n(* not de un valor booleano *)\nDefinition mi_not[b:bool]:=\nCase b of false true end.\n\n(* operacion xor sobre booleanos *)\nDefinition mxor[b1,b2:bool]:=\nCases b1 b2 of\nfalse b2=>b2\n|true b2=>(mi_not b2)\nend.\n\n(* operacion xor sobre booleanos, VERSION _REC *)\nDefinition mi_xor:=[b:bool]\n(bool_rec ([_:bool]bool) (mi_not b) b).\n\n(*===== ENTEROS ALTERNATIVOS =================================*)\n(*\nDefinicion de los enteros independientes, para hacer la suma de enteros recursivamente\n*)\nInductive Set ZZ:=\ncc:ZZ\n|pp:ZZ->ZZ\n|nn:ZZ->ZZ.\n\nDefinition sssig[l:ZZ]:=\nCases l of\ncc=>(pp cc)\n|(pp u)=>(pp l)\n|(nn y)=>y\nend.\n\nDefinition pppred[l:ZZ]:=\nCases l of\ncc=>(nn cc)\n|(pp u)=>u\n|(nn y)=>(nn l)\nend.\n\nFixpoint sumaZ[z1:ZZ]:ZZ->ZZ:=\n[z2:ZZ]\nCases z1 of\ncc=>z2\n|(pp k)\t=>(sumaZ k (sssig z2))\n|(nn k)\t=>(sumaZ k (pppred z2))\nend.\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/misc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6662124791415225}}
{"text": "\n\nRequire Export Bool.\nRequire Export Arith.\nRequire Export Compare_dec.\nRequire Export Peano_dec.\nRequire Export MyList.\nRequire Export MyRelations.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n  Definition max_nat (n m : nat) :=\n    match le_gt_dec n m with\n    | left _ => m\n    | right _ => n\n    end.\n\n  Lemma least_upper_bound_max_nat :\n   forall n m p : nat, n <= p -> m <= p -> max_nat n m <= p.\nintros.\nunfold max_nat in |- *.\nelim (le_gt_dec n m); auto with arith.\nQed.\n\n\n\n\n\nRequire Export Relation_Definitions.\n\n  Definition decide (P : Prop) := {P} + {~ P}.\n\n  Hint Unfold decide: core.\n\n\n\n  Inductive Acc3 (A B C : Set) (R : relation (A * (B * C))) :\n  A -> B -> C -> Prop :=\n      Acc3_intro :\n        forall (x : A) (x0 : B) (x1 : C),\n        (forall (y : A) (y0 : B) (y1 : C),\n         R (y, (y0, y1)) (x, (x0, x1)) -> Acc3 R y y0 y1) -> \n        Acc3 R x x0 x1.\n\n\n  Lemma Acc3_rec :\n   forall (A B C : Set) (R : relation (A * (B * C))) (P : A -> B -> C -> Set),\n   (forall (x : A) (x0 : B) (x1 : C),\n    (forall (y : A) (y0 : B) (y1 : C),\n     R (y, (y0, y1)) (x, (x0, x1)) -> P y y0 y1) -> \n    P x x0 x1) ->\n   forall (x : A) (x0 : B) (x1 : C), Acc3 R x x0 x1 -> P x x0 x1.\nProof.\ndo 6 intro.\nfix F 4.\nintros.\napply H; intros.\napply F.\ngeneralize H1.\ncase H0; intros.\napply H2.\nexact H3.\nQed.\n\n  Lemma Acc_Acc3 :\n   forall (A B C : Set) (R : relation (A * (B * C))) (x : A) (y : B) (z : C),\n   Acc R (x, (y, z)) -> Acc3 R x y z. \nProof.\nintros.\nchange\n  ((fun p : A * (B * C) =>\n    match p with\n    | (x2, (x3, x4)) => Acc3 R x2 x3 x4\n    end) (x, (y, z))) in |- *.\nelim H.\nsimple destruct x0.\nsimple destruct p; intros.\napply Acc3_intro; intros.\napply (H1 (y0, (y1, y2))); auto.\nQed.\n\n\nSection Principal.\n\n  Variables (A : Set) (P : A -> Prop) (R : A -> A -> Prop).\n\n  Record ppal (x : A) : Prop := Pp_intro\n    {pp_ok : P x; pp_least : forall y : A, P y -> R x y}.\n\n  Definition ppal_dec : Set := {x : A | ppal x} + {(forall x : A, ~ P x)}.\n\nEnd Principal.\n\n", "meta": {"author": "coq-contribs", "repo": "pts", "sha": "10a0c39b7e62f8a7ec2afbbe516a21289d065be5", "save_path": "github-repos/coq/coq-contribs-pts", "path": "github-repos/coq/coq-contribs-pts/pts-10a0c39b7e62f8a7ec2afbbe516a21289d065be5/General.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7577943767446201, "lm_q1q2_score": 0.6662124767519313}}
{"text": "Section PropositionLanguage.\n\nContext { atom : Type }.\n\nInductive prop : Type :=\n| atom_prop : atom -> prop\n| bot_prop : prop\n| top_prop : prop\n| and_prop : prop -> prop -> prop\n| or_prop : prop -> prop -> prop\n| impl_prop : prop -> prop -> prop.\n\nDefinition not_prop (P : prop) :=\n  impl_prop P bot_prop.\n\nEnd PropositionLanguage.\n\nArguments prop atom : clear implicits.\n\n(*Notation \"⊥\" := bot_prop.\nNotation \"⊤\" := top_prop.*)\nNotation \"¬ P\" := (not_prop P) (at level 51).\nInfix \"∧\" := and_prop (left associativity, at level 52).\nInfix \"∨\" := or_prop (left associativity, at level 53).\nInfix \"⊃\" := impl_prop (right associativity, at level 54).\n", "meta": {"author": "SandorBalazsHU", "repo": "elte-ik-logika-coq", "sha": "de90c589372ab2db675f7b744bf77eaab0506691", "save_path": "github-repos/coq/SandorBalazsHU-elte-ik-logika-coq", "path": "github-repos/coq/SandorBalazsHU-elte-ik-logika-coq/elte-ik-logika-coq-de90c589372ab2db675f7b744bf77eaab0506691/PropLang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6662124623350971}}
{"text": "Inductive Foo : Set :=\n| A : Foo\n| B : nat -> Foo\n| C : Foo -> Foo\n.\n\nCheck Foo_ind.\nCheck Foo_rec.\n\n\nFixpoint Foo_rect' \n    (P:Foo -> Type) \n    (pa:P A)\n    (pb:forall (n:nat), P (B n))\n    (pc: forall (f:Foo), P f -> P (C f)) (f:Foo): P f\n    :=\n    match f with\n    | A     => pa\n    | B n   => pb n\n    | C f'  => pc f' (Foo_rect' P pa pb pc f')\n    end.\n\nCheck Foo_rect.\nCheck Foo_rect'.\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/Inductive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.666167961239152}}
{"text": "Require Import OrderedType Lia.\nRequire Import String.\nRequire Import Utf8_core.\nRequire Import FunInd.\nRequire Import NArith.\n\nModule VarsString <: OrderedType with Definition t := String.string.\n  Definition t:= String.string.\n  Definition eq := @eq t.\n\n  Module M.  (* Just to bypass sort of a bug in rewrite *)\n    Function lt (s1 s2:string) {struct s1} : Prop := \n      match s1,s2 with \n        | EmptyString,EmptyString => False\n        | EmptyString, _ => True \n        | _,EmptyString => False \n        | String c1 s1, String c2 s2 => \n          ((Ascii.nat_of_ascii c1) < (Ascii.nat_of_ascii c2)) \\/ \n          ((c1=c2) /\\ lt s1 s2)\n      end.\n\n    Function compare_digits (l1 l2:list bool) {struct l1} : comparison := \n      match l1,l2 with\n        | nil,nil => Eq\n        | _,nil => Gt\n        | nil,_ => Lt\n        | b1::l1,b2::l2 => \n          match compare_digits l1 l2 with \n            | Eq => match b1,b2 with \n                      | true,true | false,false => Eq\n                      | false,true => Lt \n                      | true,false => Gt\n                    end\n            | v => v\n          end\n      end.\n\n    Definition ascii_compare c1 c2 := \n      match c1,c2 with \n        Ascii.Ascii b1 b2 b3 b4 b5 b6 b7 b8, \n        Ascii.Ascii b1' b2' b3' b4' b5' b6' b7' b8' => \n        compare_digits \n        (b1::b2::b3::b4::b5::b6::b7::b8::nil)\n        (b1'::b2'::b3'::b4'::b5'::b6'::b7'::b8'::nil)\n      end.\n\n    Lemma compare_digits_eq_correct : forall l1 l2, \n      compare_digits l1 l2 = Eq -> l1 = l2.\n    Proof.\n      intros l1 l2.\n      functional induction (compare_digits l1 l2);try discriminate;intros;f_equal;auto.\n      rewrite H in y;tauto.\n    Qed.\n\n    Lemma ascii_compare_eq_correct : \n      forall c1 c2, ascii_compare c1 c2 = Eq -> c1 = c2.\n    Proof.\n      destruct c1 as [b1 b2 b3 b4 b5 b6 b7 b8];\n        destruct c2 as [b1' b2' b3' b4' b5' b6' b7' b8'].\n      unfold ascii_compare. \n      intros H.\n      apply compare_digits_eq_correct in H.\n      injection H;intros;subst;reflexivity.\n    Qed.\n\n    Lemma compare_digits_lt_correct : \n      forall (l1 l2:list bool), \n        List.length l1 = List.length l2 -> \n        compare_digits l1 l2 = Lt -> \n        N.lt (Ascii.N_of_digits l1) (Ascii.N_of_digits l2).\n    Proof.\n      intros l1 l2;functional induction (compare_digits l1 l2);try discriminate.\n\n      destruct l2;tauto||(simpl;discriminate).\n\n      intros Hlength;injection Hlength;clear Hlength;intro Hlength.\n      rewrite (compare_digits_eq_correct _ _ e1).\n      simpl.\n      destruct ( Ascii.N_of_digits l3).\n      vm_compute;reflexivity.\n      intros _.\n      unfold N.lt.\n      simpl.\n      rewrite  Pos.compare_xO_xI.\n      rewrite Pos.compare_refl;auto.\n\n      intros Hlength;injection Hlength;clear Hlength;intro Hlength.\n      intros Heq;rewrite Heq in *.\n      simpl.\n      generalize (IHc Hlength (refl_equal _)).\n      destruct b1;destruct b2;\n      destruct (Ascii.N_of_digits l0); \n        destruct (Ascii.N_of_digits l3); lia.\n    Qed.\n\n    Lemma compare_digits_gt_correct : \n      forall (l1 l2:list bool), \n        List.length l1 = List.length l2 -> \n        compare_digits l1 l2 = Gt -> \n        N.lt (Ascii.N_of_digits l2) (Ascii.N_of_digits l1).\n    Proof.\n      intros l1 l2;functional induction (compare_digits l1 l2);try discriminate.\n\n      destruct l1;tauto||(simpl;discriminate).\n\n      intros Hlength;injection Hlength;clear Hlength;intro Hlength.\n      rewrite (compare_digits_eq_correct _ _ e1).\n      simpl.\n      destruct ( Ascii.N_of_digits l3).\n      vm_compute;reflexivity.\n      lia.\n\n      intros Hlength;injection Hlength;clear Hlength;intro Hlength.\n      intros Heq;rewrite Heq in *.\n      simpl.\n      generalize (IHc Hlength (refl_equal _)).\n      destruct b1;destruct b2;\n      destruct (Ascii.N_of_digits l0); \n        destruct (Ascii.N_of_digits l3); lia.\n    Qed.\n\n\n    Lemma ascii_compare_lt_correct : forall c1 c2, ascii_compare c1 c2 = Lt -> (Ascii.nat_of_ascii c1) < (Ascii.nat_of_ascii c2).\n    Proof.\n      unfold ascii_compare.\n      destruct c1;destruct c2.\n      intros Heq.\n      apply compare_digits_lt_correct in Heq;[|vm_compute;reflexivity].\n      unfold Ascii.nat_of_ascii.\n      assert (forall p q, (p < q)%N -> (N.to_nat p) < (N.to_nat q)) as H by lia.\n      apply H;assumption.\n    Qed.\n\n    Lemma ascii_compare_gt_correct : forall c1 c2, ascii_compare c1 c2 = Gt -> (Ascii.nat_of_ascii c2) < (Ascii.nat_of_ascii c1).\n    Proof.\n      unfold ascii_compare.\n      destruct c1;destruct c2.\n      intros Heq.\n      apply compare_digits_gt_correct in Heq;[|vm_compute;reflexivity].\n      unfold Ascii.nat_of_ascii.\n      assert (forall p q, (p < q)%N -> (N.to_nat p) < (N.to_nat q)) as H by lia.\n      apply H;assumption.\n    Qed.\n\n    Function compare' (s1 s2 : string) {struct s1} : comparison := \n      match s1,s2 with \n        | EmptyString,EmptyString => Eq\n        | EmptyString,_ => Lt\n        | _,EmptyString => Gt\n        | String c1 s1,String c2 s2 =>\n          match ascii_compare c1 c2 with \n            | Eq => compare' s1 s2\n            | v => v\n          end\n      end.\n\n    Lemma compare'_eq_correct : forall s1 s2, compare' s1 s2 = Eq -> s1=s2.\n    Proof.\n      intros s1 s2;functional induction (compare' s1 s2);\n        reflexivity || (try discriminate).\n\n      intros Heq;rewrite (IHc Heq).\n      rewrite (ascii_compare_eq_correct _ _ e1).\n      reflexivity.\n\n      intros Heq;rewrite Heq in y;tauto.\n    Qed.\n\n    Lemma compare'_lt_correct : \n      forall s1 s2, compare' s1 s2 = Lt -> lt s1 s2.\n    Proof.\n      intros s1 s2;functional induction (compare' s1 s2);\n        reflexivity || (try discriminate).\n\n      destruct s2;try tauto.\n\n      intros Heq;assert (IHc':=IHc Heq);clear IHc Heq.\n      simpl.\n      right;rewrite (ascii_compare_eq_correct _ _ e1);tauto.\n\n      intros Heq;clear y.\n      simpl;left;apply ascii_compare_lt_correct;assumption.\n    Qed.\n\n    Lemma compare'_gt_correct : \n      forall s1 s2, compare' s1 s2 = Gt -> lt s2 s1.\n    Proof.\n      intros s1 s2;functional induction (compare' s1 s2);\n        reflexivity || (try discriminate).\n\n      destruct s1;try tauto.\n\n      intros Heq;assert (IHc':=IHc Heq);clear IHc Heq.\n      simpl.\n      right;rewrite (ascii_compare_eq_correct _ _ e1);tauto.\n\n      intros Heq;clear y.\n      simpl;left;apply ascii_compare_gt_correct;assumption.\n    Qed.\n\n  End M.\n  Import M.\n  Definition eq_sym := @Logic.eq_sym t.\n  Definition eq_refl := @Logic.eq_refl t.\n  Definition eq_trans := @Logic.eq_trans t.\n\n\n  Definition lt := M.lt.\n\n\n  Ltac clear_goal := \n    repeat match goal with \n      | h: ?t = ?t  |- _ => clear h\n      | h: Compare_dec.lt_eq_lt_dec _ _ = _  |- _ => clear h\n    end.\n\n  Lemma lt_trans : forall s1 s2 s3, lt s1 s2 -> lt s2 s3 -> lt s1 s3.\n  Proof.\n    unfold lt.\n    intros s1 s2.\n    functional induction (M.lt s1 s2);try tauto.\n    intros s3. revert y;functional induction (M.lt s2 s3);simpl;try tauto.\n    destruct s1;simpl;try tauto.\n    intuition (subst).\n    left;eauto with arith .\n    left;eauto with arith .\n    left;eauto with arith .\n    right;eauto.\n  Qed.\n\n  Lemma lt_not_eq : ∀ x y, lt x y -> not (eq x y).\n  Proof.\n    unfold lt.\n    intros s1 s2; functional induction (M.lt s1 s2);try tauto.\n\n    unfold eq;intros _ abs;subst;tauto.\n\n    intuition.\n    unfold eq in H0;simpl in H0;injection H0;clear H0;intros;subst;lia.\n    subst.\n    injection H0;clear H0;intros;subst;unfold eq in *;auto.\n  Qed.\n\n  Lemma compare : ∀ x y, Compare lt eq x y.\n  Proof.\n    intros x y.\n    case_eq (compare' x y);intros Heq.\n    constructor 2.\n    apply compare'_eq_correct;assumption.\n    constructor 1.\n    apply compare'_lt_correct;assumption.\n    constructor 3.\n    apply compare'_gt_correct;assumption.\n  Defined.\n\n  Function eq_bool (s1 s2: string) {struct s1} : bool := \n    match s1,s2 with \n      | EmptyString,EmptyString => true \n      | String c1 s1,String c2 s2 => \n        if Peano_dec.eq_nat_dec (Ascii.nat_of_ascii c1) (Ascii.nat_of_ascii c2) \n          then eq_bool s1 s2 \n          else false\n      | _,_ => false\n    end.\n\n  Lemma eq_bool_correct : forall s1 s2, eq_bool s1 s2 = true -> eq s1 s2.\n  Proof.\n    intros s1 s2;functional induction (eq_bool s1 s2);try discriminate.\n\n    reflexivity.\n\n    intros H;assert (IHb':=IHb H);clear IHb H.\n    red. f_equal.\n    rewrite <- (Ascii.ascii_nat_embedding c1);\n    rewrite <- (Ascii.ascii_nat_embedding c2);\n    rewrite _x. reflexivity.\n    exact IHb'.\n  Qed.\n\n  Lemma eq_bool_correct_2 : forall s1 s2, eq_bool s1 s2 = false -> ~ eq s1 s2.\n  Proof.\n    intros s1 s2;functional induction (eq_bool s1 s2);try discriminate.\n\n    intros H;assert (IHb':= IHb H);clear e1 IHb H;intro abs;red in abs;injection abs;clear abs;intros;elim IHb';assumption.\n\n    intros _;clear e1;intro abs;red in abs;injection abs;clear abs;intros;elim _x;subst;reflexivity.\n\n    intros _ abs;destruct s1;destruct s2;simpl in y;try tauto;\n    discriminate abs.\n  Qed.\n\n  Definition eq_dec : forall (s1 s2:string), {eq s1 s2}+{~eq s1 s2}.\n  Proof.\n    intros s1 s2.\n    case_eq (eq_bool s1 s2);intro H.\n    left;apply eq_bool_correct;exact H.\n    right;apply eq_bool_correct_2;assumption.\n  Qed.\n\n\nEnd VarsString.\n", "meta": {"author": "Matafou", "repo": "ill_narratives", "sha": "02eee90891ebedf78a1a86e58ad084358d2b028f", "save_path": "github-repos/coq/Matafou-ill_narratives", "path": "github-repos/coq/Matafou-ill_narratives/ill_narratives-02eee90891ebedf78a1a86e58ad084358d2b028f/vars.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.6661679489089288}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Euclid Omega Relations.\n\nRequire Import utils brent_common.\n\nSet Implicit Arguments.\n\nLocal Infix \"div\" := (nat_divides) (at level 70). \n\n(** This is an implementation of Brent's period finding\n    algorithm refined for unary nats. It extracts to\n    the following OCaml code\n\n    type nat = O | S of nat\n    type sumbool = Left | Right\n\n    let brent eqdec f x0 =\n      let rec loop l p m x y =\n        match eqdec x y with\n          | Left -> l\n          | Right -> (match m with\n            | O   -> loop (S O) (S p) p y (f y)\n            | S n -> loop (S l) (S p) n x (f y))\n    in loop (S O) (S O) O x0 (f x0)\n\n*)\n\nSection Brent.\n\n  Variables (X : Type) (eqdec : forall x y : X, { x = y } + { x <> y }).\n  \n  Infix \"=?\" := eqdec (at level 70).\n\n  Variable (f : X -> X) (x0 : X) (Hx0 : exists τ, 0 < τ /\\ f↑τ x0 = f↑(2*τ) x0).\n\n  Inductive bar_br l p : nat -> X -> X ->  Prop :=\n    | in_bar_br_0 : forall m x,   bar_br    l    p      m  x    x \n\n    | in_bar_br_1 : forall x y,   bar_br    1 (S p)     p  y (f y) \n                             ->   bar_br    l    p      0  x    y\n\n    | in_bar_br_2 : forall m x y, bar_br (S l) (S p)    m  x (f y)      \n                             ->   bar_br    l     p  (S m) x    y.\n\n  (* pre explains the meaning of p and l w.r.t. the conventional Brent algorithm\n     which is OK for binary nats but not for unary nats\n\n     - p is 2^q + l - 1   and      m is 2^q - l   \n          for some 1 <= l <= 2^q\n\n     the test l = 2^q is replaced with m = 0\n   *)\n\n  Let pre l p m x y := exists q,\n                     x = f↑(pow2 q-1) x0 \n                  /\\ y = f↑(l+pow2 q-1) x0\n                  /\\ 1 <= l <= pow2 q\n                  /\\ p = pow2 q+l-1\n                  /\\ m = pow2 q-l.\n\n  Let post l p k := exists q,  p <= pow2 q + l - 1 \n                            /\\ 1 <= k <= pow2 q \n                            /\\ f↑(pow2 q - 1) x0 = f↑(k+pow2 q - 1) x0\n                            /\\ forall l', 1 <= l' \n                                       -> f↑(pow2 q - 1) x0 = f↑(l'+pow2 q - 1) x0 \n                                       -> p = pow2 q + l - 1 /\\ (l' < l \\/ k <= l')\n                                       \\/ p < pow2 q + l - 1 /\\ k <= l'. \n\n  (* This is a bit complicated because we need equations m = 0 and m = S n\n     to build the termination certificate *)\n     \n  Let loop : forall l p m x y (Hb : bar_br l p m x y) (Hp : pre l p m x y), { k | post l p k }.\n  Proof.\n    refine (fix loop l p m x y Hb Hp := match x =? y with \n      | left E  => exist _ l _\n      | right C => match m as m' return bar_br l p m' x y -> pre l p m' x y -> _ with \n                     | 0   => fun Hb' Hp' => match loop    1  (S p) p y (f y) _ _ with exist _ k Hk => exist _ k _ end\n                     | S n => fun Hb' Hp' => match loop (S l) (S p) n x (f y) _ _ with exist _ k Hk => exist _ k _ end\n                   end Hb Hp \n    end); trivial.\n    1,2,5: cycle 1.\n\n    (* The two termination certificates *)\n    1,2: revert C; inversion Hb'; trivial; intros []; trivial.\n    \n    2-5: clear Hb Hp; rename Hb' into Hb; rename Hp' into Hp.\n    1,2,4: cycle 1.\n    \n    (* Check the pre-conditions *)\n    \n    * destruct Hp as (q & H1 & H2 & H3 & H4 & H5).\n      exists (S q); repeat split; try (simpl; omega).\n      rewrite H2; f_equal; simpl; omega.\n      rewrite H2.\n      change (f (f↑(l+pow2 q-1) x0)) with (f↑(1+(l+pow2 q-1)) x0).\n      f_equal; simpl; omega.\n     \n    * destruct Hp as (q & H1 & H2 & H3 & H4 & H5).\n      exists q; repeat split; auto; try omega.\n      rewrite H2.\n      change (f (f↑(l+pow2 q-1) x0)) with (f↑(1+(l+pow2 q-1)) x0).\n      f_equal; simpl; omega.\n    \n    (* Check the post-conditions *)\n \n    * destruct Hp as (q & H1 & H2 & H3 & H4 & H5).\n      exists q; repeat split; try omega.\n      rewrite <- H2, <- H1; auto.\n      intros l' _ _; left; omega.\n    \n    * destruct Hk as (q' & H1 & H2 & H3 & H4).\n      exists q'; repeat split; auto; try omega.\n      intros l' Hl' H5; specialize (H4 _ Hl' H5).\n      destruct Hp as (? & _ & _ & ? & _); omega.\n\n    * destruct Hk as (q' & H1 & H2 & H3 & H4).\n      exists q'; repeat split; auto; try omega.\n      intros l' Hl' H5.\n      specialize (H4 _ Hl' H5). \n      destruct H4 as [ (H4 & [ H6 | H6 ]) | (H4 & H6) ]; try omega.\n      destruct (eq_nat_dec l l') as [ H7 | ]; try omega.\n      destruct Hp as (q & G1 & G2 & G3 & G4 & G5).\n      assert (q = q') as H8 by (apply pow2_inj; omega).\n      subst q' l' x y p; destruct C; trivial.\n  Qed.\n  \n  (* Properties of the domain using the 3rd constructor *)\n  \n  Local Fact lex_bar_br_0 l p m x y n : \n         bar_br (n+l) (n+p)   m  x (f↑n y)\n      -> bar_br    l     p (n+m) x      y.\n  Proof.\n    revert l p m x y.\n    induction n as [ | n IHn ]; simpl; auto; intros l p m x y H.\n    constructor 3; apply IHn.\n    eq goal with H; f_equal; try omega.\n    rewrite <- (iter_plus f _ 1), plus_comm; auto.\n  Qed.\n\n  Local Fact lex_bar_br_1 q l1 l2 :\n         l1 <= l2 <= pow2 q\n      -> bar_br l2 (pow2 q+l2-1) (pow2 q-l2) (f↑(pow2 q-1) x0) (f↑(l2+pow2 q-1) x0)\n      -> bar_br l1 (pow2 q+l1-1) (pow2 q-l1) (f↑(pow2 q-1) x0) (f↑(l1+pow2 q-1) x0).\n  Proof.\n    intros H1 H2.\n    replace (pow2 q-l1) with ((l2 - l1)+ (pow2 q-l2)) by omega.\n    apply lex_bar_br_0.\n    eq goal with H2; f_equal; try omega.\n    rewrite <- iter_plus; f_equal; omega.\n  Qed.\n\n  Local Fact lex_bar_br q1 l1 q2 l2 : \n         (q1 < q2 \\/ q1 = q2 /\\ l1 <= l2)\n      -> 1 <= l1 <= pow2 q1\n      -> 1 <= l2 <= pow2 q2\n      -> bar_br l2 (pow2 q2+l2-1) (pow2 q2-l2) (f↑(pow2 q2-1) x0) (f↑(l2+pow2 q2-1) x0)\n      -> bar_br l1 (pow2 q1+l1-1) (pow2 q1-l1) (f↑(pow2 q1-1) x0) (f↑(l1+pow2 q1-1) x0).\n   Proof.\n    intros H1 H3 H4.\n    assert (q1 <= q2) as H by omega.\n    revert H l1 l2 H1 H3 H4.\n    induction 1 as [ | q2 H IH ]; intros l1 l2.\n    * intros [ H1 | (H1 & H2) ] (H3 & _) (_ & H4).\n      + exfalso; omega.\n      + apply lex_bar_br_1; auto.\n    * intros _ H3 H4 H5.\n      apply IH with (l2 := pow2 q2); auto.\n      + destruct (le_lt_dec q2 q1); auto.\n        right; replace q2 with q1; omega.\n      + split; auto; apply pow2_ge1.\n      + rewrite minus_diag.\n        constructor 2.\n        apply lex_bar_br_1 with (l1 := 1) in H5; try omega.\n       eq goal with H5; f_equal; try (simpl; omega).\n       - f_equal; generalize (pow2_ge1 q2); simpl; omega.\n       - f_equal; simpl; omega.\n       - rewrite <- (iter_plus f 1); f_equal; simpl. \n         generalize (pow2_ge1 q2); omega.\n  Qed.\n  \n  Let pre_bar l ppl pml x y : pre l ppl pml x y -> bar_br l ppl pml x y.\n  Proof.\n    intros (q & H1 & H2 & H3 & H4 & H5).\n    destruct brent_cyclicity with (1 := Hx0) (p := q) as (l' & q' & H7 & H8 & H9).\n    rewrite H1, H2, H4, H5.\n    apply lex_bar_br with (3 := H8); auto.\n    rewrite H9; constructor.\n  Qed.\n\n  (* We deduce the full specification of Brent's algorithm which computes the period *)\n\n  Definition brent_una : { μ |   0 < μ \n                         /\\ (exists λ, f↑λ x0 = f↑(λ+μ) x0) \n                         /\\ forall i j, i < j -> f↑i x0 = f↑j x0 -> μ div (j-i) }.\n  Proof. \n    assert (pre 1 1 0 x0 (f x0)) as H.\n    { exists 0; repeat split; auto. }\n    destruct (loop (pre_bar H) H) as (m & Hm).\n    exists m.\n    destruct Hm as (q & H1 & H2 & H3 & H4).\n    split; try omega.\n    assert (forall l', 1 <= l' -> f ↑ (pow2 q - 1) x0 = f ↑ (l' + (pow2 q - 1)) x0 -> m <= l') as H0.\n    { intros l' G1 G2.\n      replace (l' + (pow2 q - 1)) with (l' + pow2 q - 1) in G2 by omega.\n      specialize (H4 _ G1 G2); omega. }\n    clear H4; rename H0 into H4.\n    replace (m + pow2 q - 1) with (m + (pow2 q - 1)) in H3 by omega.\n    revert H1 H2 H3 H4.\n    generalize (pow2 q -1).\n    intros l _ (Hm & _) H3 H4; clear q.\n    split. \n    * exists l; rewrite H3; f_equal; omega.\n    * intros i j H5 H6.\n      destruct (eucl_dev _ Hm (j-i)) as [ q r G1 G2 ].\n      destruct (le_lt_dec 1 r); [ | exists q; omega ].\n      replace j with (r+q*m+i) in H6 by omega.\n      assert (f↑l x0 = f↑(r+(q*m+l)) x0) as G3.\n      { rewrite plus_assoc.\n        apply iter_xchg with (3 := H6) (4 := H3); omega. }\n      rewrite <- iter_loop_gen in G3; auto.\n      apply H4 in G3; omega.\n  Qed.\n\nEnd Brent.\n\nCheck brent_una.\nPrint Assumptions brent_una.\nRecursive Extraction brent_una.\n", "meta": {"author": "DmxLarchey", "repo": "The-Tortoise-and-the-Hare", "sha": "8aa3a897271cf8f61c9d9530bf9efd363eb2a574", "save_path": "github-repos/coq/DmxLarchey-The-Tortoise-and-the-Hare", "path": "github-repos/coq/DmxLarchey-The-Tortoise-and-the-Hare/The-Tortoise-and-the-Hare-8aa3a897271cf8f61c9d9530bf9efd363eb2a574/brent_una.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870013740061, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6661679446976491}}
{"text": "Require Import Coq.micromega.Lia.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Pow2.\nRequire Import Crypto.Util.ZUtil.Log2.\nRequire Import Crypto.Util.ZUtil.Tactics.PeelLe.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.ZUtil.Tactics.ReplaceNegWithPos.\nRequire Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.\nRequire Import Crypto.Util.ZUtil.Tactics.RewriteModSmall.\nRequire Import Crypto.Util.ZUtil.Tactics.LinearSubstitute.\nRequire Import Crypto.Util.ZUtil.Tactics.SplitMinMax.\nRequire Import Crypto.Util.ZUtil.Modulo.PullPush.\nRequire Import Crypto.Util.ZUtil.LandLorShiftBounds.\nRequire Import Crypto.Util.ZUtil.Modulo.\nRequire Import Crypto.Util.ZUtil.Ones.\nRequire Import Crypto.Util.ZUtil.Lnot.\nRequire Import Crypto.Util.ZUtil.Land.\nRequire Import Crypto.Util.Tactics.UniquePose.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma round_lor_land_bound_bounds x\n  : (0 <= x <= Z.round_lor_land_bound x) \\/ (Z.round_lor_land_bound x <= x <= -1).\n  Proof.\n    cbv [Z.round_lor_land_bound]; break_innermost_match; Z.ltb_to_lt.\n    all: constructor; split; try lia; [].\n    all: Z.replace_all_neg_with_pos.\n    all: match goal with |- context[2^Z.log2_up ?x] => pose proof (Z.log2_up_le_full x) end.\n    all: lia.\n  Qed.\n#[global]\n  Hint Resolve round_lor_land_bound_bounds : zarith.\n\n  Lemma round_lor_land_bound_bounds_pos x\n  : (0 <= Z.pos x <= Z.round_lor_land_bound (Z.pos x)).\n  Proof. generalize (round_lor_land_bound_bounds (Z.pos x)); lia. Qed.\n#[global]\n  Hint Resolve round_lor_land_bound_bounds_pos : zarith.\n\n  Lemma round_lor_land_bound_bounds_neg x\n  : Z.round_lor_land_bound (Z.neg x) <= Z.neg x <= -1.\n  Proof. generalize (round_lor_land_bound_bounds (Z.neg x)); lia. Qed.\n#[global]\n  Hint Resolve round_lor_land_bound_bounds_neg : zarith.\n\n  Local Ltac saturate :=\n    repeat first [ progress cbv [Z.round_lor_land_bound Proper respectful Basics.flip] in *\n                 | progress Z.ltb_to_lt\n                 | progress intros\n                 | break_innermost_match_step\n                 | lia\n                 | rewrite !Pos2Z.opp_neg\n                 | match goal with\n                   | [ |- context[Z.log2_up ?x] ]\n                     => unique pose proof (Z.log2_up_nonneg x)\n                   | [ |- context[2^?x] ]\n                     => unique assert (0 <= 2^x) by (apply Z.pow_nonneg; lia)\n                   | [ H : 0 <= ?x |- context[2^?x] ]\n                     => unique assert (0 < 2^x) by (apply Z.pow_pos_nonneg; lia)\n                   | [ H : Pos.le ?x ?y |- context[Z.pos ?x] ]\n                     => unique assert (Z.pos x <= Z.pos y) by lia\n                   | [ H : Pos.le ?x ?y |- context[Z.pos (?x+1)] ]\n                     => unique assert (Z.pos (x+1) <= Z.pos (y+1)) by lia\n                   | [ H : Z.le ?x ?y |- context[?x+1] ]\n                     => unique assert (x+1 <= y+1) by lia\n                   | [ H : Z.le ?x ?y |- context[2^Z.log2_up ?x] ]\n                     => unique assert (2^Z.log2_up x <= 2^Z.log2_up y) by (Z.peel_le; lia)\n                   | [ H : ?a^?b <= ?a^?c |- _ ]\n                     => unique assert (a^(c-b) = a^c/a^b) by auto with zarith;\n                       unique assert (a^c mod a^b = 0) by auto with zarith\n                   end ].\n  Local Ltac do_rewrites_step :=\n    match goal with\n    | [ |- ?R ?x ?x ] => reflexivity\n    (*| [ |- context[Z.land (-2^_) (-2^_)] ]\n      => rewrite <- !Z.lnot_ones_equiv, <- !Z.lnot_lor, !Z.lor_ones_ones, !Z.lnot_ones_equiv\n    | [ |- context[Z.lor (-2^_) (-2^_)] ]\n      => rewrite <- !Z.lnot_ones_equiv, <- !Z.lnot_land, !Z.land_ones_ones, !Z.lnot_ones_equiv\n    | [ |- context[Z.land (2^_-1) (2^_-1)] ]\n      => rewrite !Z.sub_1_r, <- !Z.ones_equiv, !Z.land_ones_ones, !Z.ones_equiv, <- !Z.sub_1_r\n    | [ |- context[Z.lor (2^_-1) (2^_-1)] ]\n      => rewrite !Z.sub_1_r, <- !Z.ones_equiv, !Z.lor_ones_ones, !Z.ones_equiv, <- !Z.sub_1_r\n    | [ |- context[Z.land (2^?x-1) (-2^?y)] ]\n      => rewrite (@Z.land_comm (2^x-1) (-2^y))\n    | [ |- context[Z.lor (2^?x-1) (-2^?y)] ]\n      => rewrite (@Z.lor_comm (2^x-1) (-2^y))\n    | [ |- context[Z.land (-2^_) (2^_-1)] ]\n      => rewrite !Z.sub_1_r, <- !Z.ones_equiv, !Z.land_ones, ?Z.ones_equiv, <- ?Z.sub_1_r by lia\n    | [ |- context[Z.lor (-2^?x) (2^?y-1)] ]\n      => rewrite <- !Z.lnot_ones_equiv, <- (Z.lnot_involutive (2^y-1)), <- !Z.lnot_land, ?Z.lnot_ones_equiv, (Z.lnot_sub1 (2^y)), !Z.ones_equiv, ?Z.lnot_equiv, <- !Z.sub_1_r\n    | [ |- context[-?x mod ?y] ]\n      => rewrite (@Z.opp_mod_mod_push x y) by Z.NoZMod*)\n    | [ |- context[Z.land (2^?y-1) ?x] ]\n      => is_var x; rewrite (Z.land_comm (2^y-1) x)\n    | [ |- context[Z.lor (2^?y-1) ?x] ]\n      => is_var x; rewrite (Z.lor_comm (2^y-1) x)\n    | [ |- context[Z.land (-2^?y) ?x] ]\n      => is_var x; rewrite (Z.land_comm (-2^y) x)\n    | [ |- context[Z.lor (-2^?y) ?x] ]\n      => is_var x; rewrite (Z.lor_comm (-2^y) x)\n    | [ |- context[Z.land _ (2^_-1)] ]\n      => rewrite !Z.sub_1_r, <- !Z.ones_equiv, !Z.land_ones by auto with zarith\n    | [ |- context[Z.land ?x (-2^?y)] ]\n      => is_var x;\n        rewrite <- !Z.lnot_ones_equiv, <- (Z.lnot_involutive x), <- !Z.lnot_lor, !Z.ones_equiv, !Z.lnot_equiv, <- !Z.sub_1_r;\n        let x' := fresh in\n        remember (-x-1) as x' eqn:?; Z.linear_substitute x;\n        rename x' into x\n    | [ |- context[Z.lor ?x (-2^?y)] ]\n      => is_var x;\n        rewrite <- !Z.lnot_ones_equiv, <- (Z.lnot_involutive x), <- !Z.lnot_land, !Z.ones_equiv, !Z.lnot_equiv, <- !Z.sub_1_r;\n        let x' := fresh in\n        remember (-x-1) as x' eqn:?; Z.linear_substitute x;\n        rename x' into x\n    | [ |- Z.lor ?x (?y-1) <= Z.lor ?x (?y'-1) ]\n      => rewrite (Z.div_mod'' (Z.lor x (y-1)) y), (Z.div_mod'' (Z.lor x (y'-1)) y') by auto with zarith\n    | [ |- Z.lor ?x (?y-1) = _ ]\n      => rewrite (Z.div_mod'' (Z.lor x (y-1)) y) by auto with zarith\n    | [ |- context[?m1 - 1 + (?x - ?x mod ?m1)] ]\n      => replace (m1 - 1 + (x - x mod m1)) with ((m1 - x mod m1) + (x - 1)) by lia\n    | _ => progress rewrite ?Z.lor_pow2_div_pow2_r, ?Z.lor_pow2_div_pow2_l, ?Z.lor_pow2_mod_pow2_r, ?Z.lor_pow2_mod_pow2_l by auto with zarith\n    | _ => rewrite !Z.mul_div_eq by lia\n    | _ => progress rewrite ?(Z.add_comm 1) in *\n    | [ |- context[?x mod 2^(Z.log2_up (?x + 1))] ]\n      => rewrite (Z.mod_small x (2^Z.log2_up (x+1))) by (rewrite <- Z.le_succ_l, <- Z.add_1_r, Z.log2_up_le_pow2 by lia; lia)\n    | [ H : ?a^?b <= ?a^?c |- context[?x mod ?a^?b] ]\n      => rewrite (@Z.mod_pow_r_split x a b c) by auto with zarith;\n        (Z.div_mod_to_quot_rem; nia)\n    | _ => progress Z.peel_le\n    (*| [ H : ?x <= ?x |- _ ] => clear H\n    | [ H : ?x < ?y, H' : ?y <= ?z |- _ ] => unique assert (x < z) by lia\n    | [ H : ?x < ?y, H' : ?a <= ?x |- _ ] => unique assert (a < y) by lia\n    | [ H : 2^?x < 2^?y |- context[2^?x mod 2^?y] ]\n      => repeat first [ rewrite (Z.mod_small (2^x) (2^y)) by lia\n                      | rewrite !(@Z_mod_nz_opp_full (2^x) (2^y)) ]\n    | [ H : ?x < ?y, H' : context[?x mod ?y] |- _ ] => rewrite (Z.mod_small x y) in H' by lia\n    | [ |- context[2^?x mod 2^?y] ]\n      => let H := fresh in\n         destruct (@Z.pow2_lt_or_divides x y ltac:(lia)) as [H|H];\n         [ repeat first [ rewrite (Z.mod_small (2^x) (2^y)) by lia\n                        | rewrite !(@Z_mod_nz_opp_full (2^x) (2^y)) ]\n         | rewrite H ]*)\n    | _ => progress autorewrite with zsimplify_fast in *\n    | [ |- context[-(-?x-1)] ] => replace (-(-x-1)) with (1+x) by lia\n    | [ H : 0 > -(1+?x) |- _ ] => assert (0 <= x) by (clear -H; lia); clear H\n    | [ H : 0 > -(?x+1) |- _ ] => assert (0 <= x) by (clear -H; lia); clear H\n    | [ |- ?a - ?b = ?a' - ?b' ] => apply f_equal2; try reflexivity; []\n    | [ |- -?a = -?a' ] => apply f_equal\n    | _ => rewrite <- !Z.sub_1_r\n    | _ => lia\n    end.\n  Local Ltac do_rewrites := repeat do_rewrites_step.\n  Local Ltac fin_t :=\n    repeat first [ progress destruct_head'_and\n                 | match goal with\n                   | [ H : orb _ _ = _ |- _ ]\n                     => progress rewrite ?Bool.orb_true_iff, ?Bool.orb_false_iff, ?Z.ltb_lt, ?Z.ltb_ge in *\n                   end\n                 | break_innermost_match_step\n                 | progress destruct_head'_or\n                 | lia\n                 | progress Z.peel_le ].\n  Local Ltac t :=\n    saturate; do_rewrites.\n\n  Local Instance land_round_Proper_pos_r x\n    : Proper (Pos.le ==> Z.le) (fun y => Z.land x (Z.round_lor_land_bound (Z.pos y))).\n  Proof. t. Qed.\n\n  Local Instance land_round_Proper_pos_l y\n    : Proper (Pos.le ==> Z.le) (fun x => Z.land (Z.round_lor_land_bound (Z.pos x)) y).\n  Proof. t. Qed.\n\n  Local Instance lor_round_Proper_pos_r x\n    : Proper (Pos.le ==> Z.le) (fun y => Z.lor x (Z.round_lor_land_bound (Z.pos y))).\n  Proof. t. Qed.\n\n  Local Instance lor_round_Proper_pos_l y\n    : Proper (Pos.le ==> Z.le) (fun x => Z.lor (Z.round_lor_land_bound (Z.pos x)) y).\n  Proof. t. Qed.\n\n  Local Instance land_round_Proper_neg_r x\n    : Proper (Basics.flip Pos.le ==> Z.le) (fun y => Z.land x (Z.round_lor_land_bound (Z.neg y))).\n  Proof. t. Qed.\n\n  Local Instance land_round_Proper_neg_l y\n    : Proper (Basics.flip Pos.le ==> Z.le) (fun x => Z.land (Z.round_lor_land_bound (Z.neg x)) y).\n  Proof. t. Qed.\n\n  Local Instance lor_round_Proper_neg_r x\n    : Proper (Basics.flip Pos.le ==> Z.le) (fun y => Z.lor x (Z.round_lor_land_bound (Z.neg y))).\n  Proof. t. Qed.\n\n  Local Instance lor_round_Proper_neg_l y\n    : Proper (Basics.flip Pos.le ==> Z.le) (fun x => Z.lor (Z.round_lor_land_bound (Z.neg x)) y).\n  Proof. t. Qed.\n\n  Lemma land_round_lor_land_bound_r x\n    : Z.land x (Z.round_lor_land_bound x) = if (0 <=? x) then x else Z.round_lor_land_bound x.\n  Proof. t. Qed.\n#[global]\n  Hint Rewrite land_round_lor_land_bound_r : zsimplify_fast zsimplify.\n  Lemma land_round_lor_land_bound_l x\n    : Z.land (Z.round_lor_land_bound x) x = if (0 <=? x) then x else Z.round_lor_land_bound x.\n  Proof. rewrite Z.land_comm, land_round_lor_land_bound_r; reflexivity. Qed.\n#[global]\n  Hint Rewrite land_round_lor_land_bound_l : zsimplify_fast zsimplify.\n\n  Lemma lor_round_lor_land_bound_r x\n    : Z.lor x (Z.round_lor_land_bound x) = if (0 <=? x) then Z.round_lor_land_bound x else x.\n  Proof. t. Qed.\n#[global]\n  Hint Rewrite lor_round_lor_land_bound_r : zsimplify_fast zsimplify.\n  Lemma lor_round_lor_land_bound_l x\n    : Z.lor (Z.round_lor_land_bound x) x = if (0 <=? x) then Z.round_lor_land_bound x else x.\n  Proof. rewrite Z.lor_comm, lor_round_lor_land_bound_r; reflexivity. Qed.\n#[global]\n  Hint Rewrite lor_round_lor_land_bound_l : zsimplify_fast zsimplify.\n\n  Lemma land_round_bound_pos_r v x\n    : 0 <= Z.land v (Z.pos x) <= Z.land v (Z.round_lor_land_bound (Z.pos x)).\n  Proof.\n    rewrite Z.land_nonneg; split; [ lia | ].\n    replace (Z.pos x) with (Z.land (Z.pos x) (Z.round_lor_land_bound (Z.pos x))) at 1\n      by now rewrite land_round_lor_land_bound_r.\n    rewrite (Z.land_comm (Z.pos x)), Z.land_assoc.\n    apply Z.land_upper_bound_l; rewrite ?Z.land_nonneg; t.\n  Qed.\n#[global]\n  Hint Resolve land_round_bound_pos_r (fun v x => proj1 (land_round_bound_pos_r v x)) (fun v x => proj2 (land_round_bound_pos_r v x)) : zarith.\n  Lemma land_round_bound_pos_l v x\n    : 0 <= Z.land (Z.pos x) v <= Z.land (Z.round_lor_land_bound (Z.pos x)) v.\n  Proof. rewrite <- !(Z.land_comm v); apply land_round_bound_pos_r. Qed.\n#[global]\n  Hint Resolve land_round_bound_pos_l (fun v x => proj1 (land_round_bound_pos_l v x)) (fun v x => proj2 (land_round_bound_pos_l v x)) : zarith.\n\n  Lemma land_round_bound_neg_r v x\n    : Z.land v (Z.round_lor_land_bound (Z.neg x)) <= Z.land v (Z.neg x) <= v.\n  Proof.\n    assert (0 < 2 ^ Z.log2_up (Z.pos x)) by auto with zarith.\n    split; [ | apply Z.land_le; lia ].\n    replace (Z.round_lor_land_bound (Z.neg x)) with (Z.land (Z.neg x) (Z.round_lor_land_bound (Z.neg x)))\n      by now rewrite land_round_lor_land_bound_r.\n    rewrite !Z.land_assoc.\n    etransitivity; [ apply Z.land_le; cbn; lia | ]; lia.\n  Qed.\n#[global]\n  Hint Resolve land_round_bound_neg_r (fun v x => proj1 (land_round_bound_neg_r v x)) (fun v x => proj2 (land_round_bound_neg_r v x)) : zarith.\n  Lemma land_round_bound_neg_l v x\n    : Z.land (Z.round_lor_land_bound (Z.neg x)) v <= Z.land (Z.neg x) v <= v.\n  Proof. rewrite <- !(Z.land_comm v); apply land_round_bound_neg_r. Qed.\n#[global]\n  Hint Resolve land_round_bound_neg_l (fun v x => proj1 (land_round_bound_neg_l v x)) (fun v x => proj2 (land_round_bound_neg_l v x)) : zarith.\n\n  Lemma lor_round_bound_neg_r v x\n    : Z.lor v (Z.round_lor_land_bound (Z.neg x)) <= Z.lor v (Z.neg x) <= -1.\n  Proof.\n    change (-1) with (Z.pred 0); rewrite <- Z.lt_le_pred.\n    rewrite Z.lor_neg; split; [ | lia ].\n    replace (Z.neg x) with (Z.lor (Z.neg x) (Z.round_lor_land_bound (Z.neg x))) at 2\n      by now rewrite lor_round_lor_land_bound_r.\n    rewrite (Z.lor_comm (Z.neg x)), Z.lor_assoc.\n    cbn; rewrite <- !Z.lnot_ones_equiv, <- (Z.lnot_involutive v), <- (Z.lnot_involutive (Z.neg x)), <- !Z.lnot_land, !Z.ones_equiv, !Z.lnot_equiv, <- !Z.sub_1_r, !Pos2Z.opp_neg.\n    Z.peel_le.\n    apply Z.land_upper_bound_l; rewrite ?Z.land_nonneg; t.\n  Qed.\n#[global]\n  Hint Resolve lor_round_bound_neg_r (fun v x => proj1 (lor_round_bound_neg_r v x)) (fun v x => proj2 (lor_round_bound_neg_r v x)) : zarith.\n  Lemma lor_round_bound_neg_l v x\n    : Z.lor (Z.round_lor_land_bound (Z.neg x)) v <= Z.lor (Z.neg x) v <= -1.\n  Proof. rewrite <- !(Z.lor_comm v); apply lor_round_bound_neg_r. Qed.\n#[global]\n  Hint Resolve lor_round_bound_neg_l (fun v x => proj1 (lor_round_bound_neg_l v x)) (fun v x => proj2 (lor_round_bound_neg_l v x)) : zarith.\n\n  Lemma lor_round_bound_pos_r v x\n    : v <= Z.lor v (Z.pos x) <= Z.lor v (Z.round_lor_land_bound (Z.pos x)).\n  Proof.\n    assert (0 < 2 ^ Z.log2_up (Z.pos (x + 1))) by auto with zarith.\n    split; [ apply Z.lor_lower; lia | ].\n    replace (Z.round_lor_land_bound (Z.pos x)) with (Z.lor (Z.pos x) (Z.round_lor_land_bound (Z.pos x)))\n      by now rewrite lor_round_lor_land_bound_r.\n    rewrite !Z.lor_assoc.\n    etransitivity; [ | apply Z.lor_lower; rewrite ?Z.lor_nonneg; cbn; lia ]; lia.\n  Qed.\n#[global]\n  Hint Resolve lor_round_bound_pos_r (fun v x => proj1 (lor_round_bound_pos_r v x)) (fun v x => proj2 (lor_round_bound_pos_r v x)) : zarith.\n  Lemma lor_round_bound_pos_l v x\n    : v <= Z.lor (Z.pos x) v <= Z.lor (Z.round_lor_land_bound (Z.pos x)) v.\n  Proof. rewrite <- !(Z.lor_comm v); apply lor_round_bound_pos_r. Qed.\n#[global]\n  Hint Resolve lor_round_bound_pos_l (fun v x => proj1 (lor_round_bound_pos_l v x)) (fun v x => proj2 (lor_round_bound_pos_l v x)) : zarith.\n\n  Lemma land_round_bound_pos_r' v x : Z.land v (Z.pos x) <= Z.land v (Z.round_lor_land_bound (Z.pos x)). Proof. auto with zarith. Qed.\n  Lemma land_round_bound_pos_l' v x : Z.land (Z.pos x) v <= Z.land (Z.round_lor_land_bound (Z.pos x)) v. Proof. auto with zarith. Qed.\n  Lemma land_round_bound_neg_r' v x : Z.land v (Z.round_lor_land_bound (Z.neg x)) <= Z.land v (Z.neg x). Proof. auto with zarith. Qed.\n  Lemma land_round_bound_neg_l' v x : Z.land (Z.round_lor_land_bound (Z.neg x)) v <= Z.land (Z.neg x) v. Proof. auto with zarith. Qed.\n  Lemma lor_round_bound_neg_r' v x : Z.lor v (Z.round_lor_land_bound (Z.neg x)) <= Z.lor v (Z.neg x). Proof. auto with zarith. Qed.\n  Lemma lor_round_bound_neg_l' v x : Z.lor (Z.round_lor_land_bound (Z.neg x)) v <= Z.lor (Z.neg x) v. Proof. auto with zarith. Qed.\n  Lemma lor_round_bound_pos_r' v x : Z.lor v (Z.pos x) <= Z.lor v (Z.round_lor_land_bound (Z.pos x)). Proof. auto with zarith. Qed.\n  Lemma lor_round_bound_pos_l' v x : Z.lor (Z.pos x) v <= Z.lor (Z.round_lor_land_bound (Z.pos x)) v. Proof. auto with zarith. 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/LandLorBounds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6660756258138104}}
{"text": "Require Import Classical.\n\nDeclare Scope ordinal_scope.\n\nInductive Ordinal : Type :=\n  | ordS : Ordinal -> Ordinal\n  | ord_sup: forall {I:Type}, (I->Ordinal) -> Ordinal.\n\n(*\nFixpoint ord_le (alpha beta:Ordinal) : Prop :=\n  match alpha with\n  | ordS alpha =>\n                  (fix gt_alpha (beta:Ordinal) : Prop :=\n                  match beta with\n                  | ordS beta => ord_le alpha beta\n                  | ord_sup J beta => exists j:J,\n                    gt_alpha (beta j)\n                  end) beta\n  | ord_sup I0 alpha => forall i:I0, ord_le (alpha i) beta\n  end.\n*)\n\nInductive ord_le : Ordinal -> Ordinal -> Prop :=\n  | ord_le_respects_succ: forall alpha beta:Ordinal,\n    ord_le alpha beta -> ord_le (ordS alpha) (ordS beta)\n  | ord_le_S_sup: forall (alpha:Ordinal) (J:Type)\n    (beta:J->Ordinal) (j:J), ord_le (ordS alpha) (beta j) ->\n    ord_le (ordS alpha) (ord_sup beta)\n  | ord_sup_minimal: forall (I:Type) (alpha:I->Ordinal)\n    (beta:Ordinal), (forall i:I, ord_le (alpha i) beta) ->\n                    ord_le (ord_sup alpha) beta.\n\nDefinition ord_lt (alpha beta:Ordinal) :=\n  ord_le (ordS alpha) beta.\nDefinition ord_eq (alpha beta:Ordinal) :=\n  ord_le alpha beta /\\ ord_le beta alpha.\nDefinition ord_ge (alpha beta:Ordinal) :=\n  ord_le beta alpha.\nDefinition ord_gt (alpha beta:Ordinal) :=\n  ord_lt beta alpha.\n\nOpen Scope ordinal_scope.\nNotation \"alpha < beta\" := (ord_lt alpha beta) : ordinal_scope.\nNotation \"alpha <= beta\" := (ord_le alpha beta) : ordinal_scope.\nNotation \"alpha == beta\" := (ord_eq alpha beta)\n  (at level 70) : ordinal_scope.\nNotation \"alpha > beta\" := (ord_gt alpha beta) : ordinal_scope.\nNotation \"alpha >= beta\" := (ord_ge alpha beta) : ordinal_scope.\n\nLemma ord_le_respects_succ_converse: forall alpha beta:Ordinal,\n  ordS alpha <= ordS beta -> alpha <= beta.\nProof.\nintros.\ninversion_clear H.\nassumption.\nQed.\n\nLemma ord_le_S_sup_converse: forall (alpha:Ordinal)\n  (J:Type) (beta:J->Ordinal), ordS alpha <= ord_sup beta ->\n  exists j:J, ordS alpha <= beta j.\nProof.\nintros.\ninversion H.\nexists j.\nassumption.\nQed.\n\nLemma ord_sup_minimal_converse: forall (I:Type)\n  (alpha:I->Ordinal) (beta:Ordinal),\n  ord_sup alpha <= beta -> forall i:I, alpha i <= beta.\nProof.\nintros.\ninversion H.\nRequire Import Eqdep.\napply inj_pair2 in H2.\ndestruct H2.\napply H3.\nQed.\n\nLemma ord_le_trans: forall alpha beta gamma:Ordinal,\n  alpha <= beta -> beta <= gamma -> alpha <= gamma.\nProof.\ninduction alpha.\ninduction beta.\ninduction gamma.\nintros.\napply ord_le_respects_succ.\napply IHalpha with beta.\napply ord_le_respects_succ_converse; trivial.\napply ord_le_respects_succ_converse; trivial.\nintros.\napply ord_le_S_sup_converse in H1.\ndestruct H1 as [i].\napply ord_le_S_sup with i.\napply H; trivial.\nintros.\npose proof (ord_sup_minimal_converse _ _ _ H1).\napply ord_le_S_sup_converse in H0.\ndestruct H0 as [i].\napply H with i; trivial.\nintros.\npose proof (ord_sup_minimal_converse _ _ _ H0).\nconstructor.\nintro.\napply H with beta; trivial.\nQed.\n\nLemma ord_le_sup: forall (I:Type) (alpha:I->Ordinal) (i:I),\n  alpha i <= ord_sup alpha.\nProof.\nassert (forall beta:Ordinal, beta <= beta /\\\n  forall (I:Type) (alpha:I->Ordinal) (i:I),\n  beta <= alpha i -> beta <= ord_sup alpha).\ninduction beta.\ndestruct IHbeta.\nsplit.\napply ord_le_respects_succ; trivial.\nintros.\napply ord_le_S_sup with i.\ntrivial.\nsplit.\napply ord_sup_minimal.\nintro.\ndestruct (H i).\napply H1 with i; trivial.\nintros J alpha j ?.\napply ord_sup_minimal.\nintro.\ndestruct (H i).\napply H2 with j.\napply ord_le_trans with (ord_sup o).\napply H2 with i; trivial.\ntrivial.\n\nintros.\ndestruct (H (alpha i)).\napply H1 with i; trivial.\nQed.\n\nLemma ord_le_refl: forall alpha:Ordinal, alpha <= alpha.\nProof.\ninduction alpha.\napply ord_le_respects_succ; trivial.\napply ord_sup_minimal.\napply ord_le_sup.\nQed.\n\nLemma ord_le_S: forall alpha:Ordinal, alpha <= ordS alpha.\nProof.\ninduction alpha.\napply ord_le_respects_succ; trivial.\napply ord_sup_minimal.\nintro.\napply ord_le_trans with (ordS (o i)).\napply H.\napply ord_le_respects_succ.\napply ord_le_sup.\nQed.\n\nLemma ord_lt_le: forall alpha beta:Ordinal,\n  alpha < beta -> alpha <= beta.\nProof.\nintros.\napply ord_le_trans with (ordS alpha); trivial.\napply ord_le_S.\nQed.\n\nLemma ord_lt_le_trans: forall alpha beta gamma:Ordinal,\n  alpha < beta -> beta <= gamma -> alpha < gamma.\nProof.\nintros.\napply ord_le_trans with beta; trivial.\nQed.\n\nLemma ord_le_lt_trans: forall alpha beta gamma:Ordinal,\n  alpha <= beta -> beta < gamma -> alpha < gamma.\nProof.\nintros.\napply ord_le_trans with (ordS beta); trivial.\napply ord_le_respects_succ; trivial.\nQed.\n\nLemma ord_lt_trans: forall alpha beta gamma:Ordinal,\n  alpha < beta -> beta < gamma -> alpha < gamma.\nProof.\nintros.\napply ord_lt_le_trans with beta; trivial;\n apply ord_lt_le; trivial.\nQed.\n\nLemma ord_lt_respects_succ: forall alpha beta:Ordinal,\n  alpha < beta -> ordS alpha < ordS beta.\nProof.\nintros.\napply ord_le_respects_succ; trivial.\nQed.\n\nLemma ord_total_order: forall alpha beta:Ordinal,\n  alpha < beta \\/ alpha == beta \\/ alpha > beta.\nProof.\ninduction alpha.\ninduction beta.\ndestruct (IHalpha beta) as [|[|]].\nleft; apply ord_lt_respects_succ; trivial.\nright; left.\nsplit.\napply ord_le_respects_succ; apply H.\napply ord_le_respects_succ; apply H.\nright; right.\napply ord_lt_respects_succ; trivial.\n\ndestruct (classic (exists i:I, ordS alpha < o i)).\ndestruct H0 as [i].\nleft.\napply ord_lt_le_trans with (o i); trivial.\napply ord_le_sup.\ndestruct (classic (exists i:I, ordS alpha == o i)).\ndestruct H1 as [i].\nright; left.\nsplit.\napply ord_le_trans with (o i).\napply H1.\napply ord_le_sup.\napply ord_sup_minimal.\nintro.\ndestruct (H i0) as [|[|]].\ncontradiction H0; exists i0; trivial.\napply H2.\napply ord_lt_le; trivial.\nassert (forall i:I, ordS alpha > o i).\nintros.\ndestruct (H i) as [|[|]].\ncontradiction H0; exists i; trivial.\ncontradiction H1; exists i; trivial.\ntrivial.\nright; right.\napply ord_le_lt_trans with alpha.\napply ord_sup_minimal.\nintro.\napply ord_le_respects_succ_converse.\napply H2.\napply ord_le_refl.\n\ninduction beta.\ncase (classic (exists i:I, o i > ordS beta)); intro.\ndestruct H0 as [i].\nright; right.\napply ord_lt_le_trans with (o i); trivial.\napply ord_le_sup.\ncase (classic (exists i:I, o i == ordS beta)); intro.\nright; left.\ndestruct H1 as [i].\nsplit.\napply ord_sup_minimal.\nintro j.\ndestruct (H j (ordS beta)) as [|[|]].\napply ord_lt_le; trivial.\napply H2.\ncontradiction H0; exists j; trivial.\napply ord_le_trans with (o i).\napply H1.\napply ord_le_sup.\nleft.\napply ord_le_respects_succ.\napply ord_sup_minimal.\nintro.\ndestruct (H i (ordS beta)) as [|[|]].\napply ord_le_respects_succ_converse; trivial.\ncontradiction H1; exists i; trivial.\ncontradiction H0; exists i; trivial.\n\ncase (classic (exists j:I0, ord_sup o < o0 j)); intro.\nleft.\ndestruct H1 as [j].\napply ord_lt_le_trans with (o0 j); trivial.\napply ord_le_sup.\ncase (classic (exists i:I, o i > ord_sup o0)); intro.\ndestruct H2 as [i].\nright; right.\napply ord_lt_le_trans with (o i); trivial.\napply ord_le_sup.\n\nright; left.\nsplit.\napply ord_sup_minimal; intro.\ndestruct (H i (ord_sup o0)) as [|[|]].\napply ord_lt_le; trivial.\napply H3.\ncontradiction H2; exists i; trivial.\napply ord_sup_minimal; intro j.\ndestruct (H0 j) as [|[|]].\ncontradiction H1; exists j; trivial.\napply H3.\napply ord_lt_le; trivial.\nQed.\n\nLemma ordinals_well_founded: well_founded ord_lt.\nProof.\nred; intro alpha.\ninduction alpha.\nconstructor.\nintros beta ?.\napply ord_le_respects_succ_converse in H.\nconstructor; intros gamma ?.\ndestruct IHalpha.\napply H1.\napply ord_lt_le_trans with beta; trivial.\n\nconstructor; intros alpha ?.\napply ord_le_S_sup_converse in H0.\ndestruct H0 as [j].\n\ndestruct (H j).\napply H1; trivial.\nQed.\n\nLemma ord_lt_irrefl: forall alpha:Ordinal, ~(alpha < alpha).\nProof.\nintro; red; intro.\nassert (forall beta:Ordinal, beta <> alpha).\nintro.\npose proof (ordinals_well_founded beta).\ninduction H0.\nred; intro.\nsymmetry in H2; destruct H2.\ncontradiction (H1 alpha H); trivial.\ncontradiction (H0 alpha); trivial.\nQed.\n\nInductive successor_ordinal : Ordinal->Prop :=\n  | intro_succ_ord: forall alpha:Ordinal,\n    successor_ordinal (ordS alpha)\n  | succ_ord_wd: forall alpha beta:Ordinal,\n    successor_ordinal alpha -> alpha == beta ->\n    successor_ordinal beta.\nInductive limit_ordinal : Ordinal->Prop :=\n  | intro_limit_ord: forall {I:Type} (alpha:I->Ordinal),\n    (forall i:I, exists j:I, alpha i < alpha j) ->\n    limit_ordinal (ord_sup alpha)\n  | limit_ord_wd: forall alpha beta:Ordinal,\n    limit_ordinal alpha -> alpha == beta ->\n    limit_ordinal beta.\n\nLemma ord_successor_or_limit: forall alpha:Ordinal,\n  successor_ordinal alpha \\/ limit_ordinal alpha.\nProof.\ninduction alpha.\nleft; constructor.\ndestruct (classic (forall i:I, exists j:I, o i < o j)).\nright; constructor; trivial.\ndestruct (not_all_ex_not _ _ H0) as [i].\nassert (forall j:I, o j <= o i).\nintro.\ndestruct (ord_total_order (o i) (o j)) as [|[|]].\ncontradiction H1; exists j; trivial.\napply H2.\napply ord_lt_le; trivial.\n\nassert (ord_sup o == o i).\nsplit.\napply ord_sup_minimal; trivial.\napply ord_le_sup.\ncase (H i); intro.\nleft; apply succ_ord_wd with (o i); trivial.\nsplit; apply H3.\nright.\napply limit_ord_wd with (o i); trivial.\nsplit; apply H3.\nQed.\n\nLemma successor_ordinal_not_limit: forall alpha:Ordinal,\n  successor_ordinal alpha -> ~ limit_ordinal alpha.\nProof.\nintros; red; intro.\ninduction H.\ninversion_clear H0.\ninduction H as [I beta|].\nassert (ord_sup beta <= alpha).\napply ord_sup_minimal.\nintro.\napply ord_le_respects_succ_converse.\ndestruct (H i) as [j].\napply ord_le_trans with (beta j); trivial.\napply ord_le_trans with (ord_sup beta).\napply ord_le_sup.\napply H1.\n\ncontradiction (ord_lt_irrefl alpha).\napply ord_le_trans with (ord_sup beta); trivial.\napply H1.\n\napply IHlimit_ordinal.\nsplit; apply ord_le_trans with beta;\n  (apply H0 || apply H1).\n\ncontradiction IHsuccessor_ordinal.\napply limit_ord_wd with beta; trivial.\nsplit; apply H1.\nQed.\n", "meta": {"author": "coq-community", "repo": "zorns-lemma", "sha": "aaf46b0c5f7857ce9211cbaaf36f184ca810e0e8", "save_path": "github-repos/coq/coq-community-zorns-lemma", "path": "github-repos/coq/coq-community-zorns-lemma/zorns-lemma-aaf46b0c5f7857ce9211cbaaf36f184ca810e0e8/Ordinals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.6660756202940862}}
{"text": "Require Import Coq.Classes.Morphisms\n  Coq.micromega.Lia Sigma.Algebra.Hierarchy\n  Sigma.Algebra.Monoid Sigma.Algebra.Group\n  Sigma.Algebra.Ring\n  Sigma.Algebra.Integral_domain \n  Sigma.Algebra.Field.\n\nSection Vector_Space.\n\n  (* Underlying Field of Vector Space *)\n  Context \n    {F : Type} \n    {eqf : F -> F -> Prop}\n    {zero one : F} \n    {add mul sub div : F -> F -> F}\n    {opp inv : F -> F}.\n\n\n  \n  (* Vector Element *)\n  Context \n    {V : Type} \n    {eqv : V -> V -> Prop}\n    {vid : V} {vopp : V -> V}\n    {vadd : V -> V -> V} {smul : V -> F -> V}\n    {Hvec: @vector_space F eqf zero one add mul \n      sub div opp inv V eqv vid vopp vadd smul}.\n    \n  Local Infix \"=\" := eqv : type_scope. \n  Local Notation \"a <> b\" := (not (a = b)) : type_scope.\n  Local Infix \"*s\" := smul (at level 40).\n  Local Infix \"+v\" := vadd (at level 50).\n  \n  \n  \n\n  (* smul will be ^ pow function *)\n  Lemma connection_between_vopp_and_fopp : \n    forall u v, vopp (u *s v) = u *s (opp v). \n  Proof.\n    intros ? ?.\n    eapply group_cancel_right with (z := smul u v).\n    rewrite group_is_left_inverse,\n     <-(@vector_space_smul_distributive_fadd F eqf zero one add mul sub div\n      opp inv V eqv vid vopp vadd smul),\n      field_zero_iff_left,\n      vector_space_field_zero;\n      try reflexivity; \n      exact Hvec.\n  Qed.\n\n  Lemma smul_pow_up : \n    forall g x r, (g *s x) *s r = g *s (mul x r).\n  Proof.\n    intros ? ? ?.\n    rewrite (@vector_space_smul_associative_fmul F eqf); \n    try reflexivity; exact Hvec.\n  Qed.\n\n  Lemma smul_pow_mul : \n    forall g x r, smul (smul g x) r = smul g (mul r x).\n  Proof.\n    intros ? ? ?.\n    rewrite smul_pow_up, commutative; \n    reflexivity.\n  Qed.\n\n\n\n\n\nEnd Vector_Space.    \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/Vector_space.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6660653532861049}}
{"text": "(*\n\n   Benedikt Ahrens and Régis Spadotti\n\n   Terminal semantics for codata types in intensional Martin-Löf type theory\n\n   http://arxiv.org/abs/1401.1053\n\n*)\n\n(*\n\n  Content of this file:\n\n  definition of the category of relative comonads over a fixed functor\n\n*)\n\nRequire Import Theory.Category.\nRequire Import Theory.Functor.\nRequire Import Theory.RelativeComonad.\n\nGeneralizable All Variables.\n\n(*------------------------------------------------------------------------------\n  -- ＣＡＴＥＧＯＲＹ  ＯＦ  ＲＥＬＡＴＩＶＥ  ＣＯＭＯＮＡＤＳ\n  ----------------------------------------------------------------------------*)\n(** * Category of Relative comonads **)\n\n(** ** Category definition **)\n\nSection Definitions.\n\n  Context `(F : Functor 𝒞 𝒟).\n\n  Implicit Types (A B C D : RelativeComonad F).\n\n  Import RelativeComonad.Morphism.\n\n  Infix \"⇒\" := Hom.\n  Infix \"∘\" := compose.\n\n  Lemma left_id A B  (f : A ⇒ B) : id ∘ f ≈ f.\n  Proof.\n    intro x; simpl. rewrite left_id. reflexivity.\n  Qed.\n\n  Lemma right_id A B (f : A ⇒ B) : f ∘ id ≈ f.\n  Proof.\n    intro x; simpl. now rewrite right_id.\n  Qed.\n\n  Lemma compose_assoc A B C D (f : A ⇒ B) (g : B ⇒ C) (h : C ⇒ D) : h ∘ g ∘ f ≈ h ∘ (g ∘ f).\n  Proof.\n    intro x; simpl. now rewrite compose_assoc.\n  Qed.\n\n  Canonical Structure 𝑹𝑪𝒐𝒎𝒐𝒏𝒂𝒅 : Category :=\n    mkCategory left_id right_id compose_assoc.\n\nEnd Definitions.\n", "meta": {"author": "rs-", "repo": "Triangles", "sha": "57f10cb6c627c331b2c6e7b344a34ae50838cc67", "save_path": "github-repos/coq/rs--Triangles", "path": "github-repos/coq/rs--Triangles/Triangles-57f10cb6c627c331b2c6e7b344a34ae50838cc67/Category/RComonad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.74316801430083, "lm_q1q2_score": 0.6660653491672232}}
{"text": "From Coq Require Import List.\nFrom Coq Require Import Psatz.\nFrom Coq Require Import ZArith.\nFrom Coq Require Import Znumtheory.\nImport ListNotations.\n\nLocal Open Scope Z.\n\nFixpoint egcd_aux\n        (n : nat)\n        (r0 a0 b0 r1 a1 b1 : Z) {struct n} : Z * Z :=\n  match n with\n  | 0%nat => (0, 0)\n  | S n => let (q, r) := Z.div_eucl r0 r1 in\n           if r =? 0 then\n             (a1, b1)\n           else\n             egcd_aux n r1 a1 b1 r (a0 - q*a1) (b0 - q*b1)\n  end.\n\n(* returns (x, y) such that x*m + y*n = Z.gcd(x, y) *)\nDefinition egcd (m n : Z) : Z * Z :=\n  if m =? 0 then\n    (0, Z.sgn n)\n  else if n =? 0 then\n    (Z.sgn m, 0)\n  else\n    let num_steps := S (Z.to_nat (Z.log2 (Z.abs m) + Z.log2 (Z.abs n))) in\n    if Z.abs m <? Z.abs n then\n      let (x, y) := egcd_aux num_steps (Z.abs n) 1 0 (Z.abs m) 0 1 in\n      (Z.sgn m * y, Z.sgn n * x)\n    else\n      let (x, y) := egcd_aux num_steps (Z.abs m) 1 0 (Z.abs n) 0 1 in\n      (Z.sgn m * x, Z.sgn n * y).\n\nLemma egcd_aux_spec m n steps r0 a0 b0 r1 a1 b1 :\n  Z.log2 r0 + Z.log2 r1 < Z.of_nat steps ->\n  0 < r1 ->\n  r1 <= r0 ->\n  r0 = a0*m + b0*n ->\n  r1 = a1*m + b1*n ->\n  Z.gcd r0 r1 = Z.gcd m n ->\n  let (x, y) := egcd_aux steps r0 a0 b0 r1 a1 b1 in\n  x*m + y*n = Z.gcd m n.\nProof.\n  revert r0 a0 b0 r1 a1 b1.\n  induction steps as [|steps IH];\n    intros r0 a0 b0 r1 a1 b1 enough_steps r1pos r1gt r0eq r1eq is_gcd.\n  {\n    cbn -[Z.add] in enough_steps.\n    pose proof (Z.log2_nonneg r0).\n    pose proof (Z.log2_nonneg r1).\n    lia.\n  }\n  cbn.\n  pose proof (Z_div_mod r0 r1 ltac:(lia)).\n  destruct (Z.div_eucl r0 r1) as [q r].\n  destruct (Z.eqb_spec r 0) as [->|?].\n  - destruct H.\n    rewrite Z.add_0_r in *.\n    rewrite <- r1eq.\n    rewrite <- is_gcd.\n    rewrite H.\n    rewrite Z.gcd_comm.\n    now rewrite Z.gcd_mul_diag_l by lia.\n  - apply IH; auto.\n    + destruct H.\n      destruct q; try lia; cycle 1.\n      assert (r + r1 <= r0).\n      {\n        enough (r1 <= r1 * Z.pos p) by lia.\n        apply Z.le_mul_diag_r; lia.\n      }\n      assert (Z.log2 r1 + Z.log2 r < Z.log2 r0 + Z.log2 r1).\n      {\n        enough (Z.log2 r < Z.log2 r0) by lia.\n        pose proof (Z.log2_le_mono (r*2^1) r0 ltac:(lia)).\n        rewrite <- Z.shiftl_mul_pow2 in H2 by lia.\n        rewrite Z.log2_shiftl in H2 by lia.\n        lia.\n      }\n      lia.\n    + lia.\n    + lia.\n    + rewrite !Z.mul_sub_distr_r.\n      replace (a0 * m - q * a1 * m + (b0 * n - q * b1 * n))\n        with (a0 * m + b0*n + (-1) * (q*(a1*m + b1*n)))\n        by lia.\n      rewrite <- r0eq, <-r1eq.\n      lia.\n    + rewrite <- is_gcd.\n      rewrite (proj1 H).\n      rewrite (Z.gcd_comm (r1 * q + r)).\n      rewrite Z.add_comm, Z.mul_comm.\n      now rewrite Z.gcd_add_mult_diag_r.\nQed.\n\nLemma egcd_spec m n :\n  let (x, y) := egcd m n in\n  m*x + n*y = Z.gcd m n.\nProof.\n  unfold egcd.\n  destruct (Z.eqb_spec m 0) as [->|?].\n  { apply Z.sgn_abs. }\n  destruct (Z.eqb_spec n 0) as [->|?].\n  { rewrite Z.gcd_0_r, Z.add_0_r; apply Z.sgn_abs. }\n  pose proof (Z.log2_nonneg (Z.abs m)).\n  pose proof (Z.log2_nonneg (Z.abs n)).\n  destruct (Z.ltb_spec (Z.abs m) (Z.abs n)).\n  - unshelve epose proof (egcd_aux_spec\n                            (Z.abs n) (Z.abs m)\n                            (S (Z.to_nat (Z.log2 (Z.abs m) + Z.log2 (Z.abs n))))\n                            (Z.abs n) 1 0\n                            (Z.abs m) 0 1\n                            _ _ _ _ _ _).\n    + rewrite Nat2Z.inj_succ.\n      rewrite Z2Nat.id by lia.\n      lia.\n    + lia.\n    + lia.\n    + lia.\n    + lia.\n    + lia.\n    + destruct (egcd_aux _ _ _ _ _ _ _).\n      rewrite !Z.mul_assoc.\n      rewrite Z.gcd_abs_l, Z.gcd_comm, Z.gcd_abs_l in H2.\n      rewrite !Z.sgn_abs.\n      lia.\n  - unshelve epose proof (egcd_aux_spec\n                            (Z.abs m) (Z.abs n)\n                            (S (Z.to_nat (Z.log2 (Z.abs m) + Z.log2 (Z.abs n))))\n                            (Z.abs m) 1 0\n                            (Z.abs n) 0 1\n                            _ _ _ _ _ _).\n    + rewrite Nat2Z.inj_succ.\n      rewrite Z2Nat.id by lia.\n      lia.\n    + lia.\n    + lia.\n    + lia.\n    + lia.\n    + lia.\n    + destruct (egcd_aux _ _ _ _ _ _ _).\n      rewrite !Z.mul_assoc.\n      rewrite Z.gcd_abs_l, Z.gcd_comm, Z.gcd_abs_l, Z.gcd_comm in H2.\n      rewrite !Z.sgn_abs.\n      lia.\nQed.\n\nLemma mul_fst_egcd a n :\n  rel_prime a n ->\n  a * fst (egcd a n) mod n = 1 mod n.\nProof.\n  pose proof (egcd_spec a n).\n  destruct (Z.eqb_spec n 0) as [->|?].\n  { intros. cbn in *. rewrite !Zmod_0_r.\n    rewrite <- Zgcd_1_rel_prime in *.\n    rewrite Z.gcd_0_r in *.\n    unfold egcd. destruct (Z.eqb_spec a 0) as [->|?]; cbn; lia. }\n  intros relprime.\n  destruct (egcd a n) as [x y]; cbn.\n  rewrite (proj2 (Zgcd_1_rel_prime _ _) relprime) in H.\n  replace (a * x) with (1 + (-y)*n) by lia.\n  rewrite <- Z.add_mod_idemp_r by lia.\n  now rewrite Z.mod_mul, Z.add_0_r by lia.\nQed.\n\nLemma egcd_divides a b :\n  b <> 0 ->\n  (b | a) ->\n  egcd a b = (0, Z.sgn b).\nProof.\n  intros b0 divides.\n  unfold egcd.\n  destruct (Z.eqb_spec a 0) as [->|a0]; [easy|].\n  rewrite (proj2 (Z.eqb_neq _ _) b0).\n  assert (Z.abs b <= Z.abs a) by (apply Zdivide_bounds; auto).\n  replace (Z.abs a <? Z.abs b) with false; cycle 1.\n  { now symmetry; apply Z.ltb_ge. }\n  cbn.\n  pose proof (Z_div_mod_full (Z.abs a) (Z.abs b) ltac:(lia)).\n  destruct (Z.div_eucl (Z.abs a) (Z.abs b)) as [q r].\n  rewrite (Zmod_unique_full _ _ _ _ (proj2 H0) (proj1 H0)).\n  apply Z.divide_abs_l, Z.divide_abs_r in divides.\n  rewrite (Zdivide_mod _ _ divides).\n  cbn.\n  now rewrite Z.mul_0_r, Z.mul_1_r.\nQed.\n", "meta": {"author": "AU-COBRA", "repo": "ConCert", "sha": "55ffd996fe89d41677a2ff368d3a5e4be1e997b7", "save_path": "github-repos/coq/AU-COBRA-ConCert", "path": "github-repos/coq/AU-COBRA-ConCert/ConCert-55ffd996fe89d41677a2ff368d3a5e4be1e997b7/examples/boardroomVoting/Egcd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6660653472086051}}
{"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: Permut.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\n(* G. Huet 1-9-95 *)\n\n(** We consider a Set [U], given with a commutative-associative operator [op],\n    and a congruence [cong]; we show permutation lemmas *)\n\nSection Axiomatisation.\n\n  Variable U : Type.\n  Variable op : U -> U -> U.\n  Variable cong : U -> U -> Prop.\n\n  Hypothesis op_comm : forall x y:U, cong (op x y) (op y x).\n  Hypothesis op_ass : forall x y z:U, cong (op (op x y) z) (op x (op y z)).\n\n  Hypothesis cong_left : forall x y z:U, cong x y -> cong (op x z) (op y z).\n  Hypothesis cong_right : forall x y z:U, cong x y -> cong (op z x) (op z y).\n  Hypothesis cong_trans : forall x y z:U, cong x y -> cong y z -> cong x z.\n  Hypothesis cong_sym : forall x y:U, cong x y -> cong y x.\n\n  (** Remark. we do not need: [Hypothesis cong_refl : (x:U)(cong x x)]. *)\n\n  Lemma cong_congr :\n    forall x y z t:U, cong x y -> cong z t -> cong (op x z) (op y t).\n  Proof.\n    intros; apply cong_trans with (op y z).\n    apply cong_left; trivial.\n    apply cong_right; trivial.\n  Qed.\n\n  Lemma comm_right : forall x y z:U, cong (op x (op y z)) (op x (op z y)).\n  Proof.\n    intros; apply cong_right; apply op_comm.\n  Qed.\n\n  Lemma comm_left : forall x y z:U, cong (op (op x y) z) (op (op y x) z).\n  Proof.\n    intros; apply cong_left; apply op_comm.\n  Qed.\n\n  Lemma perm_right : forall x y z:U, cong (op (op x y) z) (op (op x z) y).\n  Proof.\n    intros.\n    apply cong_trans with (op x (op y z)).\n    apply op_ass.\n    apply cong_trans with (op x (op z y)).\n    apply cong_right; apply op_comm.\n    apply cong_sym; apply op_ass.\n  Qed.\n\n  Lemma perm_left : forall x y z:U, cong (op x (op y z)) (op y (op x z)).\n  Proof.\n    intros.\n    apply cong_trans with (op (op x y) z).\n    apply cong_sym; apply op_ass.\n    apply cong_trans with (op (op y x) z).\n    apply cong_left; apply op_comm.\n    apply op_ass.\n  Qed.\n\n  Lemma op_rotate : forall x y z t:U, cong (op x (op y z)) (op z (op x y)).\n  Proof.\n    intros; apply cong_trans with (op (op x y) z).\n    apply cong_sym; apply op_ass.\n    apply op_comm.\n  Qed.\n\n  (** Needed for treesort ... *)\n  Lemma twist :\n    forall x y z t:U, cong (op x (op (op y z) t)) (op (op y (op x t)) z).\n  Proof.\n    intros.\n    apply cong_trans with (op x (op (op y t) z)).\n    apply cong_right; apply perm_right.\n    apply cong_trans with (op (op x (op y t)) z).\n    apply cong_sym; apply op_ass.\n    apply cong_left; apply perm_left.\n  Qed.\n\nEnd Axiomatisation.", "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/Sets/Permut.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6660458978052166}}
{"text": "From mathcomp Require Import all_ssreflect.\n\n(* 6. Sub-Types Terms with properties *)\n(* 6.4 The ordinal subtype *)\n\n(*\nSection MySubTypeKit.\n  Variables (T : Type) (P : pred T).\n  \n  Structure subType : Type :=\n    SubTypeKit {\n        sub_sort :> Type;                   (* projector *)\n        val : sub_sort -> T;                (* constructor *)\n        Sub : forall x, P x -> sub_sort;    (* constructor *)\n        (* elimination rule for sub_sort *)\n        _: forall K (_ : forall x Px, K (@Sub x Px)) u, K u;\n        _: forall x Px, val (@Sub x Px) = x\n      }.\n\n  Notation \"[ ’subType’ ’for’ v ]\" :=\n    (SubType _ v _\n             (fun K K_S u => let (x, Px) as u return K u := u in K_S x Px)\n             (fun x px => erefl x)).\nEnd MySubTypeKit.\n*)\nSection MyOrdinal.\n  Variable n : nat.\n\n  Inductive ordinal : Type := Ordinal m of m < n.\n\n  Print Canonical Projections.\n  Coercion nat_of_ord i := let: @Ordinal m _ := i in m. (* i : 'I_n *)\n  (* _ は、H : m < n である。 *)\n  Print Graph.\n  (* [nat_of_ord] : ordinal >-> nat *)\n  \n  Canonical ordinal_subType := [subType for nat_of_ord].\n  Print ordinal_subType.\n  (*\n    ordinal_subType = \n    [subType for nat_of_ord]\n     : subType (T:=nat) (fun x : nat => x < n)\n   *)\n  Print Canonical Projections.\n  (* nat_of_ord <- val ( ordinal_subType ) *)\n  \n  (* 次の定義には、カノニカルが必要 Canonical ordinal_subType。\n     カノニカルにしないと、\"SubEqMixin ?s\" has type \"Equality.mixin_of ?s\"\n     while it is expected to have type \"Equality.mixin_of ordinal\". *)\n  Definition ordinal_eqMixin := Eval hnf in [eqMixin of ordinal by <:].\n  Set Printing Coercions.\n  Print ordinal_eqMixin.\n  (*\nordinal_eqMixin = \nEqMixin (T:=ordinal) (op:=fun x y : ordinal => nat_of_ord x == nat_of_ord y)\n  (@val_eqP nat_eqType (fun x : nat => x < n) ordinal_subType)\n     : Equality.mixin_of ordinal\n *)\n  \n  Canonical ordinal_eqType := Eval hnf in EqType ordinal ordinal_eqMixin.\n  Print Canonical Projections.\n  (* ordinal <- sort ( ordinal_eqType ) *)\n\n  Definition ord_enum : seq ordinal := pmap insub (iota 0 n).\n\n  Check @pmap : forall aT rT : Type, (aT -> option rT) -> seq aT -> seq rT.\n  (* 要素に関数(この場合は insub : aT -> option rT)を適用して、\n     結果の Some x の Some を外し、None なら捨てる。 *)\n\n  (* ord_enum n から値を取り出した結果は、自然数の0からn-1までのリストと等しい。 *)\n  Lemma val_ord_enum : map val ord_enum = (iota 0 n).\n  Proof.\n    rewrite pmap_filter; last exact: insubK.\n    by apply/all_filterP; apply/allP=> i; rewrite mem_iota isSome_insub.\n  Qed.\n\n  (* 以下の証明において、Canonical ordinal_eqType が必要。カノニカルにしないと、\n  \"ord_enum\" has type \"seq ordinal\" while it is expected to have type \"seq ?T\". *)\n  \n  (* ordinal <- sort ( ordinal_eqType ) *)\n  Check @uniq : forall T : eqType, seq T -> bool.\n  Check ord_enum : seq ordinal.\n  (* ordinal と sort (ordinal_eqType) = eqType のユニファイが可能になる。 *)\n  \n  (* ord_enum n の要素はユニークである。 *)\n  Lemma ord_enum_uniq : uniq ord_enum.\n  Proof.\n      by rewrite pmap_sub_uniq ?iota_uniq.\n  Qed.\n  \n  Lemma ord_inj : injective nat_of_ord.     (* fintype.v から転記 *)\n  Proof.\n    exact: val_inj.\n  Qed.\n  \n  Lemma ltn_ord (i : ordinal) : i < n.      (* fintype.v から転記 *)\n  Proof.\n    exact: valP i.\n  Qed.\n  \n  Lemma mem_ord_enum i : i \\in ord_enum.\n  Proof.\n    Check pmap insub (iota 0 n).\n    Check (mem_map ord_inj).\n    rewrite -(mem_map ord_inj).\n    rewrite val_ord_enum.\n    rewrite mem_iota.\n    rewrite add0n /=.\n    Check ltn_ord.\n    by apply ltn_ord.\n  Qed.\n\nEnd MyOrdinal.\n\n(* Definition p1 : 'I_3. Proof. have : 1 < 3 by []. apply Ordinal. Defined. *)\nDefinition p1 := Ordinal 3 1 is_true_true.\n\nCheck @insub: forall (T : Type) (P : pred T) (sT : subType (T:=T) P), T -> option sT.\n(* サブタイプに含まれるなら Some x、さもなければ None を返す。 *)\nPrint ordinal_subType.\nCheck (fun i : nat => i < 3).\nCheck (fun i : 'I_3 => i < 3).              (* カノニカル効くけど、それじゃない。 *)\nCheck @insub nat.\nCheck @insub nat (fun i : nat => i < 3).\nCheck @insub nat (fun i : nat => i < 3) (ordinal_subType 3).\nCheck @insub nat (fun i : nat => i < 3) (ordinal_subType 3) 1.\nCheck @insub nat (fun i : nat => i < 3) (ordinal_subType 3) 1 = Some p1.\nCheck insub 1 = Some p1.\nGoal insub 1 = Some p1.\nProof.\n  by rewrite insubT.\nQed.\n\n(* *************** *)\nNotation \"''I_' n\" := (ordinal n).\n(* *************** *)\n\n(* ******* *)\n(* SUBTYPE *)\n(* ******* *)\n\n(*\n  Definition ordinal_finMixin :=\n    Eval hnf in UniqFinMixin ord_enum_uniq mem_ord_enum.\n  \n  Canonical ordinal_finType :=\n    Eval hnf in FinType ordinal ordinal_finMixin.\n\n*)\n\nLemma tnth_default {T n} (t : n.-tuple T) : 'I_n -> T.\nProof.\n  rewrite -(size_tuple t).\n  elim: (tval t).\n  - case=> //=.\n  - move=> a l H1 H2.\n    done.\n  Restart.\n    by rewrite -(size_tuple t); case: (tval t) => [|//] [].\nQed.\n\n\nCheck @nth : forall T : Type, T -> seq T -> nat -> T.\nDefinition tnth T n (t : n.-tuple T) (i : 'I_n) : T :=\n  nth (tnth_default t i) t i.\n(* nth の最後の引数 nat に、 'I_n を与えている。 *)\n(* nth の最後から二つ目の引数 seq T に、n.tuple T を与えている。 *)\n\nCheck tnth : forall (T : Type) (n : nat), n.-tuple T -> 'I_n -> T.\n\nLemma Hsize : size [::false;true;false] == 3. Proof. done. Qed.\nCheck Tuple Hsize.\nCheck tnth bool 3 (Tuple Hsize) p1 : bool.\nEval compute in tnth bool 3 (Tuple Hsize) p1. (* true *)\n\nCheck Tuple Hsize : 3.-tuple bool.\nCheck @tnth_default bool 3 (Tuple Hsize) p1 : bool.\nEval compute in @tnth_default bool 3 (Tuple Hsize) p1. (* bool型のなにか *)\nEval compute in tnth_default (Tuple Hsize) p1.         (* bool型のなにか *)\nEval compute in @nth bool (tnth_default (Tuple Hsize) p1) (Tuple Hsize) p1. (* true *)\nEval compute in nth _ (Tuple Hsize) p1. (* true *)\nEval compute in nth _ (Tuple Hsize) 1. (* true *)\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-comp-book/suhara.ch6-ordinal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048443, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6660458934381385}}
{"text": "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.\n    apply eq2.\nQed.\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 eq1 eq2.\n    apply eq2.\n    apply eq1.\nQed.\n\nTheorem silly2a: forall n m: nat,\n    (n,n) = (m,m) -> (forall q r: nat, (q,q) = (r,r) -> [q] = [r]) ->\n    [n] = [m].\nProof.\n    intros n m eq1 eq2.\n    apply eq2.\n    apply eq1.\nQed.\n\nTheorem silly_ex: (forall n, evenb n = true -> oddb (S n) = true) ->\n    evenb 3 = true -> oddb 4 = true.\nProof.\n    intros eq1.\n    apply eq1.\nQed.\n\nTheorem silly3: forall n: nat, true = beq_nat n 5 -> \n    beq_nat (S (S n)) 7 = true.\nProof.\n    intros n H.\n    symmetry.\n    apply 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 eq1 eq2.\n    rewrite -> eq1.\n    rewrite -> eq2.\n    reflexivity.\nQed.\n\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. apply eq2. 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]). apply eq1. apply eq2.\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/MoreCoq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6660458905383485}}
{"text": "Require Import Setoid.\nRequire Import FunctionalExtensionality.\n\n\nLemma uniq_choice : forall (A B : Prop),\n  forall (P : A -> B -> Prop),\n  (forall (a : A), exists! (b : B), P a b)\n  -> (exists (f : A -> B), forall (a : A), P a (f a)).\nProof.\n  intros.\n  exists (fun a => ex_proj1 (H a)).\n  intros.\n  destruct (H a), u.\n  auto.\nQed.\n\n\n(**)\nRecord MRE :=\n{ set : Prop\n; elem : set\n; op : set -> set -> set\n; subset : Prop\n; subset_incl : subset -> set\n; exist_axiom : forall (f : subset -> set), exists! (x : set),\n  f = fun y => op (subset_incl y) x\n}.\n\nDefinition witness_fcn : forall (M : MRE),\n  forall (f : set M -> set M),\n  exists (fn : set M -> set M),\n  forall (x : set M),\n  (fun y => f (op M (subset_incl M y) x))\n  = (fun y => op M (subset_incl M y) (fn x)).\nProof.\n  intros.\n  assert (forall (x : set M), exists! (y : set M),\n    (fun d => f (op M (subset_incl M d) x))\n    = (fun d => op M (subset_incl M d) y)).\n  intro.\n  exact (exist_axiom M (fun d => f (op M (subset_incl M d) x))).\n  pose (pred := fun x => fun y =>\n    (fun d : subset M => f (op M (subset_incl M d) x))\n    = (fun d : subset M => op M (subset_incl M d) y)).\n  exact (uniq_choice (set M ) (set M) pred H).\nDefined.\n\n(* The basic structure of the Rock-Lawvere real numbers *)\n(* There is some redundancy in these axioms, for convenience *)\nRecord SynthReal :=\n{ set : Prop\n\n(* Addition forms an Abelian group *)\n; zero : set\n; add : set -> set -> set\n; add_id : forall (x : set), add x zero = x\n; add_assoc : forall (x y z : set), add (add x y) z = add x (add y z)\n; add_comm : forall (x y : set), add x y = add y x\n; add_inv : forall (x : set),\n  (exists (negx : set), add x negx = zero)\n\n(* Multiplication forms a commutative monoid with inverses except at 0 *)\n; one : set\n; mul : set -> set -> set\n; mul_id : forall (x : set), mul x one = x\n; mul_assoc : forall (x y z : set), mul (mul x y) z = mul x (mul y z)\n; mul_comm : forall (x y : set), mul x y = mul y x\n; mul_inv : forall (x : set), x <> zero\n  -> (exists (invx : set), mul x invx = one)\n\n(* Multiplication distributes over addition *)\n; left_distrib : forall (x y z : set),\n  mul x (add y z) = add (mul x y) (mul x z)\n; right_distrib : forall (x y z : set),\n  mul (add x y) z = add (mul x z) (mul y z)\n\n(* A total ordering which behaves nicely with the field operations *)\n; lessthan : set -> set -> Prop\n; transitive : forall (x y z : set), (lessthan x y) -> (lessthan y z)\n  -> (lessthan x z)\n; zero_less_one : lessthan zero one\n; total : forall (x y : set), x <> y -> lessthan x y \\/ lessthan y x\n; translation : forall(x y z : set),\n  lessthan x y -> lessthan (add x z) (add y z)\n; dilation : forall (x y z : set),\n  (not (lessthan z zero) /\\ lessthan x y) -> lessthan (mul z x) (mul z y)\n\n(* Square roots existence and uniqueness *)\n; sqrt_exist : forall (x : set), (exists (y : set), mul y y = x)\n; sqrt_uniq : forall (x y : set), (lessthan zero y /\\ mul y y = x)\n  -> y = ex_proj1 (sqrt_exist x)\n\n(* Nilsquare infinitesimals are treated as a separate type *)\n(* with an injection into the rest of the field *)\n; nilsquares : Prop\n; nilsquare_incl : nilsquares -> set\n; nilsquare_subset : forall (d1 d2 : nilsquares),\n  nilsquare_incl d1 = nilsquare_incl d2 -> d1 = d2\n; nilsquare_def : forall (d : nilsquares),\n  mul (nilsquare_incl d) (nilsquare_incl d) = zero\n; nilsquare_recl : forall (x : set),\n  forall (nilsqr : mul x x = zero),\n    exists (d : nilsquares), x = nilsquare_incl d\n; nilzero : nilsquares\n; nilzero_def : nilsquare_incl nilzero = zero\n\n(* The Kock-Lawvere axiom! *)\n; KockLawvere : forall (f : nilsquares -> set),\n  (exists (a : set),\n    f = fun d => add (f nilzero) (mul a (nilsquare_incl d)))\n\n}.\n\n\n(* Basic algebra stuff *)\n\n\nFact cancel_add : forall (R: SynthReal),\n  forall (x y z : set R),\n  add R x z = add R y z -> x = y.\nProof.\nintros R x y z hyp.\nrewrite <- (add_id R x).\ndestruct (add_inv R z).\nrewrite <- H.\nrewrite <- (add_assoc R x z x0).\nrewrite -> hyp.\nrewrite -> (add_assoc R y z x0).\nrewrite -> H.\nrewrite -> (add_id R y).\nreflexivity.\nQed.\n\n\nFact mul_zero : forall (R : SynthReal),\n  forall (x : set R),\n  mul R (zero R) x = zero R.\nProof.\nintros R x.\nassert (add R (mul R (zero R) x) (mul R (zero R) x)\n  = add R (zero R) (mul R (zero R) x)).\nrewrite -> (add_comm R (zero R) (mul R (zero R) x)).\nrewrite -> (add_id R).\nrewrite <- (right_distrib R (zero R) (zero R) x).\nrewrite -> (add_id R (zero R)) at 1.\nreflexivity.\nexact (cancel_add R (mul R (zero R) x) (zero R) (mul R (zero R) x) H).\nQed.\n\n\n(* A few utilities before beginning single variable calculus *)\n\n\nDefinition diff (R : SynthReal) (x : set R)\n  (d : nilsquares R) : set R := mul R (nilsquare_incl R d) x.\n\n\nFact nilsquare_diff : forall (R : SynthReal),\n  forall (x : set R),\n  forall (d : nilsquares R),\n  mul R (diff R x d) (diff R x d) = zero R.\nProof.\nintros R x d.\nunfold diff.\nrewrite -> (mul_comm R (nilsquare_incl R d) x) at 1.\nrewrite -> (mul_assoc R x (nilsquare_incl R d) (mul R (nilsquare_incl R d) x)).\nrewrite <- (mul_assoc R (nilsquare_incl R d) (nilsquare_incl R d) x).\nrewrite -> (nilsquare_def R d).\nrewrite -> (mul_zero R).\nrewrite -> (mul_comm R).\nrewrite -> (mul_zero R).\nreflexivity.\nQed.\n\n\nFact linearize_diff : forall (R : SynthReal),\n  forall (x : set R),\n  ex_proj1 (linear_exist R (diff R x)) = x.\nProof.\nintros R x.\nassert (forall (d : nilsquares R),\n  diff R x d = add R (diff R x (nilzero R)) (mul R x (nilsquare_incl R d))).\nintros d.\nunfold diff.\nrewrite -> (nilzero_def R).\nrewrite -> (mul_zero R).\nrewrite -> (add_comm R).\nrewrite -> (add_id R).\nrewrite -> (mul_comm R).\nreflexivity.\nsymmetry.\nexact (linear_uniq R (diff R x) x H).\nQed.\n\n\nLemma microcancellation : forall (R : SynthReal),\n  forall (x y : set R),\n  diff R x = diff R y -> x = y.\nProof.\nintros R x y hyp.\nrewrite <- (linearize_diff R x).\nrewrite <- (linearize_diff R y).\nrewrite -> hyp.\nreflexivity.\nQed.\n\n\n(* Single-variable calculus! *)\n\n(**)\nRemark derivative_w_prf : forall (R : SynthReal),\n  forall (f : set R -> set R),\n  exists (df : set R -> set R),\n  forall (x : set R),\n  forall (d : nilsquares R),\n  f (add R x (nilsquare_incl R d))\n  = add R (f x) (mul R (nilsquare_incl R d) (df x)).\nProof.\nintros R f.\npose (df0 := fun x =>\n  (linear_exist R (fun d => (f (add R x (nilsquare_incl R d)))))).\nexists (fun x => ex_proj1 (df0 x)).\nintros x d.\n(**)\n\n\nDefinition derivative (R : SynthReal)\n  (f : set R -> set R)\n  (x : set R) : set R :=\n  ex_proj1 (linear_exist R (fun d => f (add R x (nilsquare_incl R d)))).\n\n\nFact rewrite_derivative : forall (R : SynthReal),\n  forall (f : set R -> set R),\n  forall (x : set R),\n  forall (d : nilsquares R),\n  f (add R x (nilsquare_incl R d))\n  = add R (f x) (mul R (nilsquare_incl R d) (derivative R f x)).\nProof.\nintros R f x d.\npose (ex_df := fun y =>\n  linear_exist R (fun d0 => f (add R y (nilsquare_incl R d0)))).\nunfold derivative.\nexact (linear_uniq R (fun d1 =>\n  f (add R x (nilsquare_incl R d1))) (derivative R f x) H).\n\n\nProposition product_rule : forall (R : SynthReal),\n  forall (f : set R -> set R),\n  forall (g : set R -> set R),\n  forall (x : set R),\n  derivative R (fun y => mul R (f y) (g y)) x\n  = add R (mul R (derivative R f x) (g x)) (mul R (f x) (derivative R g x)).\nProof.\nintros R f g x.\nunfold derivative at 1.\nfold (derivative R f).\n\n\nTheorem derivative_distrib : forall (R : SynthReal),\n  forall (f : set R -> set R),\n  forall (g : set R -> set R),\n  forall (x : set R),\n  add R (derivative R f x) (derivative R g x)\n  = derivative R (fun y => add R (f y) (g x)) x.\nProof.\nintros R f g x.\nunfold derivative.", "meta": {"author": "Ebanflo42", "repo": "coq-synthgeo", "sha": "2aa518bb39781131ba143f6e36129b8694cd30f0", "save_path": "github-repos/coq/Ebanflo42-coq-synthgeo", "path": "github-repos/coq/Ebanflo42-coq-synthgeo/coq-synthgeo-2aa518bb39781131ba143f6e36129b8694cd30f0/KockLawvere.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6660458803716904}}
{"text": "Require Coq.Init.Datatypes.\nImport Coq.Init.Notations.\nNotation \"A -> B\" := (forall (_ : A), B) : type_scope.\n\nSection inductionExamples.\n\n  Inductive ThreeElementSet:=\n  |zero\n  |one\n  |two.\n\n  Inductive PairOrTriple:=\n  |pair (x y:ThreeElementSet)\n  |triple (x y z:ThreeElementSet).\n\n  Inductive Lst:=\n  |nil\n  |cons (x:ThreeElementSet) (l:Lst).\n\nEnd inductionExamples.\n\nSection functionExamples.\n\n  Definition plusOneModThree (X:ThreeElementSet):\n    ThreeElementSet.\n  Proof.\n    induction X.\n    - apply one.\n    - apply two.\n    - apply zero.\n  Defined.\n\n  Definition constantAtZero (X:ThreeElementSet):\n    ThreeElementSet.\n  Proof.\n    apply zero.\n  Defined.\n\n  Definition plusTwoModThree (X:ThreeElementSet):\n    ThreeElementSet.\n  Proof.\n    induction X.\n    - apply two.\n    - apply zero.\n    - apply one.\n  Defined.\n\n  Definition roundToPair (p:PairOrTriple):\n    PairOrTriple.\n  Proof.\n    induction p.\n    - apply (pair x y).\n    - apply (pair x y).\n  Defined.\n\n  Fixpoint append (l m:Lst):\n    Lst.\n  Proof.\n    destruct l.\n    - apply m.\n    - apply (cons x (append l m)).\n  Defined.\n\nEnd functionExamples.\n\nSection inductionExercises.\n\n  Inductive FourElementSet:=\n  |zero4\n  |one4\n  |two4\n  |three4.\n\n  Inductive Nat:=\n  |base\n  |succ (n:Nat).\n\nEnd inductionExercises.\n\nSection functionExercises.\n\n  Definition constantAtZero4 (x:FourElementSet):\n    FourElementSet.\n  Proof.\n    apply zero4.\n  Defined.\n\n  Definition doubleModThree (x:ThreeElementSet):\n    ThreeElementSet.\n  Proof.\n    induction x.\n    - apply zero.\n    - apply two.\n    - apply one.\n  Defined.\n\n  Definition fourModThree (x:FourElementSet):\n    ThreeElementSet.\n  Proof.\n    induction x.\n    - apply zero.\n    - apply one.\n    - apply two.\n    - apply zero.\n  Defined.\n\n  Fixpoint length (l:Lst):\n    Nat.\n  Proof.\n    destruct l.\n    - apply base.\n    - apply (succ (length l)).\n  Defined.\n\nEnd functionExercises.\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "mwpb", "repo": "introduction-univalence-coq", "sha": "106643b5aea0937740e5ea51993a21da117dca2a", "save_path": "github-repos/coq/mwpb-introduction-univalence-coq", "path": "github-repos/coq/mwpb-introduction-univalence-coq/introduction-univalence-coq-106643b5aea0937740e5ea51993a21da117dca2a/solutions/inductionAndFunctions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6660458731396076}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n(*\n  The following is an algorithm for extracting the path leading to an item v\n  in a binary tree. This path is the code of the item in huffman compression.\n  The algorithm is used only when the given item is is the tree.\n\n    exception Not_found\n    let encode t v = \n       let rec lookup = function\n              Leaf -> raise Not_found\n            | Node(t1,b,t2) -> \n                 if a=b then []\n                 else try L::lookup t1 with\n                      Not_found -> R::lookup t2 \n       in lookup t\n\n  The informal argument is as follows : if the item has not been found in the\n  left branch (the raised exception is catched), then if the item has not\n  been found in the right branch, then nothing has to be done : the raised\n  exception will propagate, which means that the item was not in the current\n  subtree.\n\n  It is not necessary to be aware of this reasoning when building the formal\n  proof: the right proof obligations are automatically generated and are easy\n  to prove.\n\n*)\n\nRequire Import List.\nRequire Extraction.\n\nSection sec_dom.\nVariable dom : Set.\nVariable a : dom.\nAxiom eg : forall a b : dom, {a = b} + {a <> b}.\n\nInductive tree : Set :=\n  | Leaf : tree\n  | Node : tree -> dom -> tree -> tree.\n\nInductive direction : Set :=\n  | L : direction\n  | R : direction. \n\nDefinition ld := list direction.\n\nFixpoint elsewhere (t : tree) : Prop :=\n  match t with\n  | Leaf => True\n  | Node t1 b t2 => elsewhere t1 /\\ a <> b /\\ elsewhere t2\n  end.\n\nInductive path : ld -> tree -> Prop :=\n  | path_leaf : forall t1 t2 : tree, path nil (Node t1 a t2)\n  | path_node1 :\n      forall (t1 t2 : tree) (b : dom) (l : ld),\n      path l t1 -> path (L :: l) (Node t1 b t2)\n  | path_node2 :\n      forall (t1 t2 : tree) (b : dom) (l : ld),\n      path l t2 -> path (R :: l) (Node t1 b t2).\nHint Resolve path_leaf path_node1 path_node2: huffman.\n\nLemma not_elsewhere :\n forall (t : tree) (l : ld), path l t -> elsewhere t -> False.\nintros t l p. elim p; clear p l; simpl in |- *; try tauto.\n(*  Intros t1 t2 (e1,(N,e2)); Case N; Reflexivity. *)\nQed.\n\nRequire Import Mx_defs.\n\nTheorem lookup : forall t : tree, Mx (elsewhere t) {l : ld | path l t}.\nfix 1.\nintro t; case t; clear t.\n  apply Mx_raise. simpl in |- *; trivial.\n  intros t1 b t2; case (eg a b).\n    intro E; apply Mx_unit. exists (nil (A:=direction)); case E; auto with huffman.\n\n    intro N; apply Mx_try with (1 := lookup t1).\n    intros (l, Hl). apply Mx_unit. exists (L :: l); auto with huffman.\n    intro elsewhere_t1. apply Mx_bind with (1 := lookup t2).\n      intros l2; apply Mx_unit; case l2; intros l Hl; exists (R :: l);\n       auto with huffman.\n      intro elsewhere_t2; simpl in |- *; auto. \nDefined.\n\nTheorem encode :\n forall t : tree, (exists l : ld, path l t) -> {l : ld | path l t}.\nintros t Ht.\napply Mx_try with (1 := lookup t).\n  intro x; exact x.\n  intro et; exists (nil (A:=direction)). \n    case Ht; intros l p. case (not_elsewhere t l); assumption. \nDefined.\n\nEnd sec_dom.\n\n(* Extracting terms typed in system F but not in ML *)\n(* In the extracted ML program, you have to\n    - put an Obj.magic in front of each call to mx_try\n      (at least for each recursive (then polymorphic) use of mx_try)\n*)\n\nExtract Inductive sumbool => \"bool\" [ \"true\" \"false\" ].\nExtract Constant eg => \"(=)\".\n\nExtraction \"huff_extr.ml\" Mx_unit Mx_raise Mx_try Mx_bind lookup encode.\nExtraction Inline Mx_bind Mx_unit Mx_raise Mx_try.\nExtraction \"huff_opt_extr.ml\" lookup encode.\n", "meta": {"author": "coq-contribs", "repo": "continuations", "sha": "52115376f182175321b0d9fac9ad7d61db51ddb0", "save_path": "github-repos/coq/coq-contribs-continuations", "path": "github-repos/coq/coq-contribs-continuations/continuations-52115376f182175321b0d9fac9ad7d61db51ddb0/polycont/huffman.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012105, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.6660256365902169}}
{"text": "(* week-05_mystery-functions.v *)\n(* FPP 2020 - YSC3236 2020-2021, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 12 Sep 2020 *)\n\n(* ********** *)\n\n(* Your name: Bobbie Soedirgo\n   Your student ID number: A0181001A\n   Your e-mail address: sram-b@comp.nus.edu.sg\n*)\n\n(* ********** *)\n\n(* Paraphernalia: *)\n\nLtac fold_unfold_tactic name := intros; unfold name; fold name; reflexivity.\n\nRequire Import Arith Bool.\n\nNotation \"A =n= B\" :=\n  (beq_nat A B) (at level 70, right associativity).\n\nNotation \"A =b= B\" :=\n  (eqb A B) (at level 70, right associativity).\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_00 (mf : nat -> nat) :=\n  mf 0 = 1 /\\ forall i j : nat, mf (S (i + j)) = mf i + mf j.\n\n(* ***** *)\n\nProposition there_is_at_most_one_mystery_function_00 :\n  forall f g : nat -> nat,\n    specification_of_mystery_function_00 f ->\n    specification_of_mystery_function_00 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  unfold specification_of_mystery_function_00.\n  intros f g [S_f_O S_f_S] [S_g_O S_g_S] n.\n  induction n as [| n' IHn'].\n  - rewrite -> S_g_O.\n    exact S_f_O.\n  - Search (0 + _ = _).\n    rewrite <- (plus_O_n n').\n    rewrite -> (S_f_S 0 n').\n    rewrite -> (S_g_S 0 n').\n    rewrite -> S_f_O.\n    rewrite -> S_g_O.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\n(* ***** *)\n\nDefinition unit_test_for_mystery_function_00a (mf : nat -> nat) :=\n  (mf 0 =n= 1) (* etc. *).\n\nDefinition unit_test_for_mystery_function_00b (mf : nat -> nat) :=\n  (mf 0 =n= 1) && (mf 1 =n= 2) (* etc. *).\n\nDefinition unit_test_for_mystery_function_00c (mf : nat -> nat) :=\n  (mf 0 =n= 1) && (mf 1 =n= 2) && (mf 2 =n= 3) (* etc. *).\n\nDefinition unit_test_for_mystery_function_00d (mf : nat -> nat) :=\n  (mf 0 =n= 1) && (mf 1 =n= 2) && (mf 2 =n= 3) && (mf 3 =n= 4)\n  (* etc. *).\n\n(* ***** *)\n\nDefinition mystery_function_00 := S.\n\nDefinition less_succinct_mystery_function_00 (n : nat) : nat :=\n  S n.\n\nCompute (unit_test_for_mystery_function_00d mystery_function_00).\n\nTheorem there_is_at_least_one_mystery_function_00 :\n  specification_of_mystery_function_00 mystery_function_00.\nProof.\n  unfold specification_of_mystery_function_00, mystery_function_00.\n  split.\n  - reflexivity.\n  - intros i j.\n    rewrite -> (plus_Sn_m i (S j)).\n    rewrite <- (plus_n_Sm i j).\n    reflexivity.\nQed.\n\n(* ***** *)\n\nDefinition mystery_function_00_alt := fun (n : nat) => n + 1.\n\nTheorem there_is_at_least_one_mystery_function_00_alt :\n  specification_of_mystery_function_00 mystery_function_00_alt.\nProof.\nAbort.\n\n(* ***** *)\n\nTheorem soundness_of_the_unit_test_function_for_mystery_function_00 :\n  forall mf : nat -> nat,\n    specification_of_mystery_function_00 mf ->\n    unit_test_for_mystery_function_00c mf = true.\nProof.\n  unfold specification_of_mystery_function_00.\n  unfold unit_test_for_mystery_function_00c.\n  intros mf [H_O H_S].\n  (* Goal: (mf 0 =n= 1) && (mf 1 =n= 2) && (mf 2 =n= 3) = true *)\n  rewrite -> H_O.\n  (* Goal: (1 =n= 1) && (mf 1 =n= 2) && (mf 2 =n= 3) = true *)\n  rewrite -> (Nat.eqb_refl 1).\n  (* Goal: true && (mf 1 =n= 2) && (mf 2 =n= 3) = true *)\n  rewrite -> (andb_true_l (mf 1 =n= 2)).\n  (* Goal: (mf 1 =n= 2) && (mf 2 =n= 3) = true *)\n  (* etc. *)\n  Check (Nat.add_1_l 0).\n  rewrite <- (Nat.add_1_l 0) at 1.\n  Check (plus_Sn_m 0 0).\n  rewrite -> (plus_Sn_m 0 0).\n  rewrite -> (H_S 0 0).\n  rewrite -> H_O.\n  rewrite -> (Nat.add_1_l 1).\n  Check (Nat.eqb_refl 2).\n  rewrite -> (Nat.eqb_refl 2).\n  rewrite -> (andb_true_l (mf 2 =n= 3)).\n  Check (Nat.add_1_l 1).\n  rewrite <- (Nat.add_1_l 1) at 1.\n  Check (plus_Sn_m 0 1).\n  rewrite -> (plus_Sn_m 0 1).\n  rewrite -> (H_S 0 1).\n  rewrite -> H_O.\n  rewrite <- (Nat.add_1_l 0) at 2.\n  Check (plus_Sn_m 0 0).\n  rewrite -> (plus_Sn_m 0 0).\n  rewrite -> (H_S 0 0).\n  rewrite -> H_O.\n  rewrite -> (Nat.add_1_l 1).\n  rewrite -> (Nat.add_1_l 2).\n  exact (Nat.eqb_refl 3).\nQed.\n\nTheorem soundness_of_the_unit_test_function_for_mystery_function_00b :\n  forall mf : nat -> nat,\n    specification_of_mystery_function_00 mf ->\n    unit_test_for_mystery_function_00b mf = true.\nProof.\n  unfold specification_of_mystery_function_00,\n         unit_test_for_mystery_function_00b.\n  intros mf [H_O H_S].\n  (* Goal: (mf 0 =n= 1) && (mf 1 =n= 2) = true *)\n  rewrite -> H_O.\n  (* Goal: (1 =n= 1) && (mf 1 =n= 2) = true *)\n  rewrite -> (Nat.eqb_refl 1).\n  (* Goal: true && (mf 1 =n= 2) = true *)\n  rewrite -> (andb_true_l (mf 1 =n= 2)).\n  (* Goal: (mf 1 =n= 2) = true *)\n  (* etc. *)\n  Check (Nat.add_1_l 0).\n  rewrite <- (Nat.add_1_l 0) at 1.\n  Check (plus_Sn_m 0 0).\n  rewrite -> (plus_Sn_m 0 0).\n  rewrite -> (H_S 0 0).\n  rewrite -> H_O.\n  Check (plus_Sn_m 0 1).\n  rewrite -> (plus_Sn_m 0 1).\n  Check (Nat.add_1_r 0).\n  rewrite -> (Nat.add_1_r 0).\n  Check (Nat.eqb_refl 2).\n  exact (Nat.eqb_refl 2).\nQed.\n\nTheorem soundness_of_the_unit_test_function_for_mystery_function_00_with_Search :\n  forall mf : nat -> nat,\n    specification_of_mystery_function_00 mf ->\n    unit_test_for_mystery_function_00b mf = true.\nProof.\n  unfold specification_of_mystery_function_00,\n         unit_test_for_mystery_function_00b.\n  intros mf [H_O H_S].\n\n  rewrite -> H_O.\n  Search (beq_nat _  _ = true).\n  Check (Nat.eqb_refl 1).\n  rewrite -> (Nat.eqb_refl 1).\n  Search (true && _ = _).\n  Check (andb_true_l (mf 1 =n= 2)).\n  rewrite -> (andb_true_l (mf 1 =n= 2)).\n\n  Check (Nat.add_1_l 0).\n  rewrite <- (Nat.add_1_l 0) at 1.\n  Check (plus_Sn_m 0 0).\n  rewrite -> (plus_Sn_m 0 0).\n  rewrite -> (H_S 0 0).\n  rewrite -> H_O.\n  Check (plus_Sn_m 0 1).\n  rewrite -> (plus_Sn_m 0 1).\n  Check (Nat.add_1_r 0).\n  rewrite -> (Nat.add_1_r 0).\n  Check (Nat.eqb_refl 2).\n  exact (Nat.eqb_refl 2).\nQed.\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_11 (mf : nat -> nat) :=\n  mf 1 = 1\n  /\\\n  forall i j : nat,\n    mf (i + j) = mf i + 2 * i * j + mf j.\n\nLemma about_mystery_function_11 :\n  forall f : nat -> nat,\n    specification_of_mystery_function_11 f ->\n    f 0 = 0.\nProof.\n  unfold specification_of_mystery_function_11.\n  intros f [S_f_1 S_f_S].\n  Check (S_f_S 0 1).\n  assert (H_f := S_f_S 0 1).\n  rewrite -> (plus_O_n 1) in H_f.\n  Search (_ * 0 = 0).\n  rewrite -> (Nat.mul_0_r 2) in H_f.\n  Search (0 * _ = 0).\n  rewrite -> (Nat.mul_0_l 1) in H_f.\n  Search (_ + 0 = _).\n  rewrite -> (Nat.add_0_r (f 0)) in H_f.\n  rewrite -> (Nat.add_comm (f 0) (f 1)) in H_f.\n  rewrite <- (Nat.add_0_r (f 1)) in H_f at 1.\n  Search (_ + _ = _ -> _ = _).\n  Check (plus_reg_l 0 (f 0) (f 1) H_f).\n  symmetry.\n  exact (plus_reg_l 0 (f 0) (f 1) H_f).\nQed.\n\nTheorem there_is_at_most_one_mystery_function_11 :\n  forall f g : nat -> nat,\n    specification_of_mystery_function_11 f ->\n    specification_of_mystery_function_11 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  unfold specification_of_mystery_function_11.\n  intros f g [S_f_O S_f_S] [S_g_O S_g_S] n.\n  induction n as [| n' IHn'].\n  - Check (about_mystery_function_11 g (conj S_g_O S_g_S)).\n    rewrite -> (about_mystery_function_11 g (conj S_g_O S_g_S)).\n    exact (about_mystery_function_11 f (conj S_f_O S_f_S)).\nAbort.\n\n    \n\n(* ********** *)\n\nDefinition specification_of_mystery_function_04 (mf : nat -> nat) :=\n  mf 0 = 0\n  /\\\n  forall n' : nat,\n    mf (S n') = mf n' + S (2 * n').\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_15 (mf : nat -> nat * nat) :=\n  mf 0 = (0, 1)\n  /\\\n  forall n' : nat,\n    mf (S n') = let (x, y) := mf n'\n                in (S x, y * S x).\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_16 (mf : nat -> nat * nat) :=\n  mf 0 = (0, 1)\n  /\\\n  forall n' : nat,\n    mf (S n') = let (x, y) := mf n'\n                in (y, x + y).\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_17 (mf : nat -> nat) :=\n  mf 0 = 0\n  /\\\n  mf 1 = 1\n  /\\\n  mf 2 = 1\n  /\\\n  forall p q : nat,\n    mf (S (p + q)) = mf (S p) * mf (S q) + mf p * mf q.\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_18 (mf : nat -> nat) :=\n  mf 0 = 0\n  /\\\n  mf 1 = 1\n  /\\\n  mf 2 = 1\n  /\\\n  forall n''' : nat,\n    mf n''' + mf (S (S (S n'''))) = 2 * mf (S (S n''')).\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_03 (mf : nat -> nat -> nat) :=\n  mf 0 0 = 0\n  /\\\n  (forall i j: nat, mf (S i) j = S (mf i j))\n  /\\\n  (forall i j: nat, S (mf i j) = mf i (S j)).\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_42 (mf : nat -> nat) :=\n  mf 1 = 42\n  /\\\n  forall i j : nat,\n    mf (i + j) = mf i + mf j.\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_07 (mf : nat -> nat -> nat) :=\n  (forall j : nat, mf 0 j = j)\n  /\\\n  (forall i : nat, mf i 0 = i)\n  /\\\n  (forall i j k : nat, mf (i + k) (j + k) = (mf i j) + k).\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_08 (mf : nat -> nat -> bool) :=\n  (forall j : nat, mf 0 j = true)\n  /\\\n  (forall i : nat, mf (S i) 0 = false)\n  /\\\n  (forall i j : nat, mf (S i) (S j) = mf i j).\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_23 (mf : nat -> nat) :=\n  mf 0 = 0\n  /\\\n  mf 1 = 0\n  /\\\n  forall n'' : nat,\n    mf (S (S n'')) = S (mf n'').\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_24 (mf : nat -> nat) :=\n  mf 0 = 0\n  /\\\n  mf 1 = 1\n  /\\\n  forall n'' : nat,\n    mf (S (S n'')) = S (mf n'').\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_13 (mf : nat -> nat) :=\n  (forall q : nat, mf (2 * q) = q)\n  /\\\n  (forall q : nat, mf (S (2 * q)) = q).\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_25 (mf : nat -> nat) :=\n  mf 0 = 0\n  /\\\n  (forall q : nat,\n      mf (2 * (S q)) = S (mf (S q)))\n  /\\\n  mf 1 = 0\n  /\\\n  (forall q : nat,\n      mf (S (2 * (S q))) = S (mf (S q))).\n\n(* ****** *)\n\nDefinition specification_of_mystery_function_20 (mf : nat -> nat -> nat) :=\n  (forall j : nat, mf O j = j)\n  /\\\n  (forall i j : nat, mf (S i) j = S (mf i j)).\n\n(* ****** *)\n\nDefinition specification_of_mystery_function_21 (mf : nat -> nat -> nat) :=\n  (forall j : nat, mf O j = j)\n  /\\\n  (forall i j : nat, mf (S i) j = mf i (S j)).\n\n(* ****** *)\n\nDefinition specification_of_mystery_function_22 (mf : nat -> nat -> nat) :=\n  forall i j : nat,\n    mf O j = j\n    /\\\n    mf (S i) j = mf i (S j).\n\n(* ********** *)\n\n(* Binary trees of natural numbers: *)\n\nInductive tree : Type :=\n  | Leaf : nat -> tree\n  | Node : tree -> tree -> tree.\n\nDefinition specification_of_mystery_function_19 (mf : tree -> tree) :=\n  (forall n : nat,\n     mf (Leaf n) = Leaf n)\n  /\\\n  (forall (n : nat) (t : tree),\n     mf (Node (Leaf n) t) = Node (Leaf n) (mf t))\n  /\\\n  (forall t11 t12 t2 : tree,\n     mf (Node (Node t11 t12) t2) = mf (Node t11 (Node t12 t2))).\n\n(* You might not manage to prove\n   that at most one function satisfies this specification (why?),\n   but consider whether the following function does.\n   Assuming it does, what does this function do?\n   And what is the issue here?\n*)\n\nFixpoint mystery_function_19_aux (t a : tree) : tree :=\n  match t with\n  | Leaf n =>\n     Node (Leaf n) a\n  | Node t1 t2 =>\n     mystery_function_19_aux t1 (mystery_function_19_aux t2 a)\n  end.\n\nFixpoint mystery_function_19 (t : tree) : tree :=\n  match t with\n  | Leaf n =>\n     Leaf n\n  | Node t1 t2 =>\n     mystery_function_19_aux t1 (mystery_function_19 t2)\n  end.\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_05 (mf : nat -> nat) :=\n  mf 0 = 1\n  /\\\n  forall i j : nat,\n    mf (S (i + j)) = 2 * mf i * mf j.\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_06 (mf : nat -> nat) :=\n  mf 0 = 2\n  /\\\n  forall i j : nat,\n    mf (S (i + j)) = mf i * mf j.\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_09 (mf : nat -> bool) :=\n  mf 0 = false\n  /\\\n  mf 1 = true\n  /\\\n  forall i j : nat,\n    mf (i + j) = xorb (mf i) (mf j).\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_10 (mf : nat -> bool) :=\n  mf 0 = false\n  /\\\n  mf 1 = true\n  /\\\n  forall i j : nat,\n    mf (i + j) = (mf i =b= mf j).\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_12 (mf : nat -> nat) :=\n  mf 1 = 1\n  /\\\n  forall i : nat,\n    mf (S (S i)) = (S (S i)) * mf (S i).\n\n(* ********** *)\n\nDefinition specification_of_mystery_function_14 (mf : nat -> bool) :=\n  (forall q : nat, mf (2 * q) = true)\n  /\\\n  (forall q : nat, mf (S (2 * q)) = false).\n\n(* ********** *)\n\n(* Simple examples of specifications: *)\n\n(* ***** *)\n\nDefinition specification_of_the_factorial_function (fac : nat -> nat) :=\n  fac 0 = 1\n  /\\\n  forall n' : nat, fac (S n') = S n' * fac n'.\n\n(* ***** *)\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 n'' + fib (S n'').\n\n(* ********** *)\n\n(* end of week-05_mystery-functions.v *)\n", "meta": {"author": "soedirgo", "repo": "fpp", "sha": "5a43df151c5c8bc3f49d449ffd6f3eac67a16eab", "save_path": "github-repos/coq/soedirgo-fpp", "path": "github-repos/coq/soedirgo-fpp/fpp-5a43df151c5c8bc3f49d449ffd6f3eac67a16eab/w05/week-05_mystery-functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.6660256228779124}}
{"text": "Require Import Bool.\nRequire Import Peano.\nRequire Import Omega.           (* I use this to handle a bunch of mundane index calculations*)\n\n(* Summary:\nWe have the following notions of finiteness:\n\nDefinition Eaf (f: nat -> bool) := {n | forall m, m>=n -> f m = false}.\nDefinition StrictlyBounded (f: nat -> bool ):= {n | ((forall k, NrOfTrue k <= n) /\\\n                                    (forall np, (np< n) -> (not ((forall k, NrOfTrue k <= np) ))))}.\nDefinition Bounded (f: nat -> bool) := {n | ((forall k, NrOfTrue k <= n))}.\n\nAnd we also have the following properties:\nDefinition Markovs_Principle:= forall P, DecidableP nat P ->  (({n: nat| P n} -> False)-> False) -> {n: nat| P n}. \nDefinition WLPO := forall g:nat->bool, {forall n,g n=false} + {not (forall n,g n=false)}.\n\nStrictlyBounded also have an equivalent formulation, proven equivalent below:\nDefinition StrictlyBoundedAlternative := {n | ((forall k, NrOfTrue k <= n) /\\\n                                        (not ((forall k, NrOfTrue k < n))))}.\n\nIt is straightforward to see that we have: Eaf->StrictlyBounded->Bounded\n \nIn this file we prove the following:\n(StrictlyBounded->Eaf) <-> Markovs_principle\n(Bounded->StrictlyBounded) <-> WLPO.\n\nOnly the important results are prefixed with Theorem, all the helpers are prefixed with Lemma.\n *)\n\n  Definition WLPO := forall g:nat->bool, {forall n,g n=false} + {not (forall n,g n=false)}.\n\n  Definition WLPOInv := forall g:nat->bool, {forall n,g n=true} + {not (forall n,g n=true)}.\n\n    \n  (* Markovs_Principle *)\n  Definition DecidableP (A: Set)(P: A -> Prop) := forall a: A, {(P a)} + {~(P a)}.\n    \n  Definition Markovs_Principle:= forall P, DecidableP nat P ->  (({n: nat| P n} -> False)-> False) -> {n: nat| P n}. \n  (* A formalization of Markovs principle using streams instead of predicates*)\n  Definition  MP:= (forall g:nat->bool,  (({ n: nat | g n = true} -> False)-> False) -> { n: nat | g n = true}).\n\n  \n  Lemma WLPOImplWPOAlt: WLPO -> WLPOInv.\n  Proof.\n    intro.\n    unfold WLPO in H.\n    set (gneg :=  (fun x=> negb x )).\n    intro.\n    assert ({(forall n : nat, negb (g n) = false)} + {~ (forall n : nat, negb (g n) = false)});auto.\n    elim H0;intros;auto.\n    left;simpl;auto.\n    intro.\n    assert ( negb (g n) = false);auto.\n    assert (true = negb false);auto.\n    rewrite H2.\n    rewrite<- H1;auto.\n    assert (negb (negb (g n)) = g n);auto.\n    apply negb_involutive.\n    right;simpl;auto.\n    intro.\n    apply b.\n    intro.\n    assert (g n = true);auto.\n    assert (false = negb true);auto.\n    rewrite H3.\n    rewrite H2.\n    auto.\n  Qed.\n\n\n  Lemma WLPOAltImplWPO: WLPOInv ->  WLPO.\n  Proof.\n    intro.\n    unfold WLPOInv in H.\n    set (gneg :=  (fun x=> negb x )).\n    intro.\n    assert ({(forall n : nat, negb (g n) = true)} + {~ (forall n : nat, negb (g n) = true)});auto.\n    elim H0;intros;auto with bool.\n    left;simpl;auto with bool.\n    intro.\n    assert ( negb (g n) = true);auto with bool.\n    assert (false = negb true);auto with bool.\n    rewrite H2.\n    rewrite<- H1;auto with bool.\n    assert (negb (negb (g n)) = g n);auto with bool.\n    apply negb_involutive.\n    right;simpl;auto with bool.\n    intro.\n    apply b.\n    intro.\n    assert (g n = false);auto with bool.\n    assert (true = negb false);auto with bool.\n    rewrite H3.\n    rewrite H2.\n    auto.\n  Qed.\n \n  Lemma MarkPrinImplMP: Markovs_Principle -> MP.\n  Proof.\n    intros.\n    intro.\n    intro.\n    apply X;auto.\n    intro.\n    destruct (g a);auto.\n  Qed.\n\n  Lemma MPImplMarkPrinciple(mp:MP): Markovs_Principle .\n    Proof.\n      unfold MP in mp.\n      unfold Markovs_Principle.\n      intros.\n      unfold DecidableP in H.\n      set (decider := (fun x => if (H x) then true else false)).\n      assert ((({n : nat | decider n = true} -> False) -> False) -> {n :nat | decider n = true});auto.\n      assert (forall a, (P a) <-> (decider a = true));auto.\n      intros.\n      split;intros;auto.\n      unfold decider;elim (H a);auto.\n      unfold decider in H2.\n      induction (H a);auto.\n      contradict H2;auto.\n      assert ((({n : nat | decider n = true} -> False) -> False)).\n      firstorder.\n      assert ({n :nat | decider n = true});auto.\n      elim H4;intros.\n      exists x.\n      apply H2;auto.       \n    Qed.\n\n Section notionsOfFiniteness.\n  Variable f: nat -> bool.\n  \n  (* Counts the nr of n s.t n<=m and f n = true *) \n  Fixpoint NrOfTrue (m : nat) : nat :=\n    match m with\n      | 0 => if (f 0) then 1 else 0\n      | S n => if (f (S n)) then (S (NrOfTrue n) ) else (NrOfTrue n)\n    end.\n\n\n  Definition Eaf := {n | forall m, m>=n -> f m = false}.\n  \n  (* Two equivalent versions of strictly bounded (proven equivalent below in \"StrictlyBoundedSTBPredEQ\") *)\n  Definition StrictlyBounded := {n | ((forall k, NrOfTrue k <= n) /\\\n                                    (forall np, (np< n) -> (not ((forall k, NrOfTrue k <= np) ))))}.\n\n  \n  Definition StrictlyBoundedAlternative := {n | ((forall k, NrOfTrue k <= n) /\\\n                                        (not ((forall k, NrOfTrue k < n))))}.\n\n  (* Sigma n. all k. #{i | 0 <= i <= k & f(i)=1} <= n *)\n  Definition Bounded := {n| ((forall k, NrOfTrue k <= n))}.\n\n\n  Lemma decidableF: forall n:nat, f n = true \\/ f n = false.\n  Proof.\n    intros.\n    induction (f n);auto.\n  Qed.\n\n  \n  Lemma NrOfTrueIsMonotoneOneStep:  forall m:nat,   (NrOfTrue  m ) <= (NrOfTrue  (S m)).\n    intros.\n    assert (forall n:nat, f n = true \\/ f n = false).\n    apply decidableF;auto.\n    induction m;auto.\n    unfold NrOfTrue.\n    assert (f 0 = true \\/ f 0 = false);auto.\n    assert (f 1 = true \\/ f 1 = false);auto.\n    simpl.\n    case H0;intro;case H1;auto;intros;rewrite H2;auto;simpl;auto with arith;rewrite H3;auto.    \n    assert (f (S m) = true \\/ f (S m)=false);auto.\n    assert (f (S (S m)) = true \\/ f (S (S m))=false);auto.\n    case H0;intro;case H1;auto;intros. simpl.\n    rewrite H2;rewrite H3;auto.\n    unfold NrOfTrue.\n    rewrite H2;rewrite H3;auto.    \n    unfold NrOfTrue.\n    rewrite H2;rewrite H3;auto.    \n    unfold NrOfTrue.\n    rewrite H2;rewrite H3;auto.    \n  Qed.\n\n  Hint Resolve   NrOfTrueIsMonotoneOneStep.\n\n  Lemma NrOfTrueIsMonotone:  forall m n :nat, m <=n ->  (NrOfTrue  m ) <= (NrOfTrue  n).\n  Proof.\n    intros.\n    induction n;auto with arith.\n    inversion H;auto.\n    elim (eq_nat_dec m n);intros;auto.\n    rewrite a;auto.\n    elim (eq_nat_dec m (S(n)));intros;auto.\n    rewrite a;auto.\n    assert (m<n);auto with arith.\n    omega. \n    assert (NrOfTrue m <= NrOfTrue n);auto.\n    apply IHn.\n    omega.\n    assert (NrOfTrue n <= NrOfTrue (S(n)));auto.\n    firstorder.\n  Qed.\n  Hint Resolve   NrOfTrueIsMonotone.\n\n  \n  Lemma NrOfTrueIsMonotoneConverse:  forall m n :nat, m <=n -> (NrOfTrue  n)  >= (NrOfTrue  m ).\n  Proof.\n    intros.\n    firstorder.\n  Qed.\n  Hint Resolve   NrOfTrueIsMonotoneConverse.\n    \n  \n  Theorem StrictlyBoundedSTBPredEQ: (StrictlyBounded -> StrictlyBoundedAlternative) * (StrictlyBoundedAlternative -> StrictlyBounded).\n  Proof.\n    split;intros H.\n    unfold StrictlyBounded in H.\n    unfold StrictlyBoundedAlternative.\n    elim H;intros x p.\n    pose (zerop x).\n    inversion s.\n    exists x.\n    inversion p;auto.\n    split;auto.\n    intro.\n    pose (H3 1).\n    omega.\n    exists x.\n    inversion p;auto.\n    split;auto.\n    intro.\n    apply  (H2 (pred x)).\n    omega.\n    intro.\n    pose (H3 k).\n    omega.\n    (* Done with (StrictlyBounded -> StrictlyBoundedAlternative) *)\n    unfold StrictlyBoundedAlternative in H.\n    unfold StrictlyBounded.\n    elim H;intros x p.\n    elim p;intros H0 H1.\n    exists x.\n    split;auto.\n    intros. \n    elim (zerop x);intros;auto.\n    omega.\n    intro.\n    apply H1.\n    intro. \n    pose (H3 k).\n    inversion l;auto.\n    rewrite H4.\n    auto.\n    omega.\n  Qed.\n  \n     \n  (* We introduce the x-limit such the nrOfTrue is always smaller than it. \n     We then proceed to show that there is an index such that nrOfTrue is exactly x-limit. For this we use MP. \n     So we need to get a contradiction from the assumption ~ (exists n : nat, NrOfTrue n = x)\n     This assumption lets us proof that forall n : nat, NrOfTrue n <> x, and then forall n : nat, NrOfTrue n < x\n     Then we branch on wether x is 0 or S(p). In the first case it is easy. In the other case we have p<x, giving \n      ~ (forall k : nat, NrOfTrue k <= p), contradicting  forall n : nat, NrOfTrue n < x.\n     \n     Then we let the index be that number + 1, and we need to show that every element of f after this is false. This is proved by induction, and the fact that NrOfTrue is monotone.\n      \n     *)\n  Lemma MarkovsPAndSTBImplEaf:  Markovs_Principle -> (StrictlyBoundedAlternative -> Eaf).\n  Proof.\n    intro mp.\n    intro sd.\n    unfold Markovs_Principle in mp.\n    unfold StrictlyBounded in sd.\n    unfold Eaf.\n    elim sd;intros x p.\n    elim p.\n    intro xlim.\n    intro xsmallest.     \n    assert ({index | NrOfTrue index = x});auto.\n    apply mp.\n    intro.\n    apply eq_nat_dec.\n    intro.\n    assert (forall  n : nat, not (NrOfTrue n = x));auto.\n    intro.\n    intro.\n    apply H.\n    exists n;auto.\n    assert (forall n : nat, NrOfTrue n < x);auto.\n    intros.\n    assert (NrOfTrue n <= x);auto.\n    assert (NrOfTrue n <> x);auto.\n    omega.\n  \n    elim H.\n    intros x0 p0.\n    exists (S(x0)).\n    intros.\n    \n    assert (f m = false \\/ f m = true);auto.\n    induction (f m);auto.\n    elim H1;auto.\n    intros.\n\n    assert (NrOfTrue m <= x);auto.\n    inversion H0.\n    intros.\n    rewrite<- H4 in H2.\n    assert ( NrOfTrue  (S(x0)) <= NrOfTrue  m);auto.\n    assert (m <= S x0);auto.\n    rewrite H4;auto.\n   \n    assert ( NrOfTrue (S x0) = S(x));auto.\n    rewrite<- p0.  \n    simpl.\n    rewrite H2.  \n    omega.\n    rewrite H2.\n    omega.\n    assert ((S x0) < m);auto.\n    omega.\n    assert (x0 < m);auto.\n    assert (NrOfTrue x0 <= NrOfTrue m);auto.\n    apply NrOfTrueIsMonotone.\n    omega.\n    assert (NrOfTrue m = x);auto.\n    rewrite p0 in H8.\n    eauto.\n    omega.\n    assert (exists p, m = S(p));auto.\n    exists (pred m).\n    omega.\n    elim H10.\n    intro p1.\n    intros.\n    assert (NrOfTrue m = S(NrOfTrue p1));auto.\n    compute;simpl;auto.\n    rewrite H11;auto;simpl;auto.\n    rewrite<- H11.\n    rewrite H2.\n    auto.\n    assert ((NrOfTrue p1) < NrOfTrue m);auto.\n    rewrite H12;auto.\n    assert ((NrOfTrue p1) < x);auto.\n    rewrite<- H9;auto.\n    assert (x <= NrOfTrue m);auto.\n    rewrite p0 in H8;auto.\n    assert (p1>=x0);auto.\n    omega.\n    inversion H16.\n    omega.\n    assert (x0 < p1).\n    omega.\n    assert (NrOfTrue x0 <= NrOfTrue p1);auto.\n    assert (NrOfTrue x0 < NrOfTrue m);auto.\n    omega.\n    firstorder.\n   Qed.  \n\n  End notionsOfFiniteness.\n\n  \n\n(* If there exists a positive index in the stream for which the predicate holds, there is a smallest*)\nLemma FindingSmallestInBoundedRange: forall P:nat->bool, {n:nat | P n = true}-> (P 0)=false\n                                                         -> {n | P n = true /\\ P (pred n) = false}.\nProof.\n  intros.\n  elim H.\n  intro upperlimit.\n  intros.\n  induction upperlimit;auto.\n  congruence.\n  assert ({P upperlimit=true} + {P upperlimit = false});auto.\n  elim (P upperlimit);auto.\n  elim H1;intro;auto.\n  exists (S upperlimit);auto.    \nQed.\nHint Resolve   FindingSmallestInBoundedRange.\n\n \n\nLemma FindingSmallestInBoundedRangePred (P:nat->Prop)(decidable: forall n, {P n}+{not (P n)}):  ({ n | P n}) ->  not (P 0) -> {n | P n  /\\ not( P (pred n))}.\nProof.\n  intros.\n  elim H.\n  intro upperlimit.\n  intros.\n  induction upperlimit;auto.\n  congruence.\n  assert ({P upperlimit} + {not (P upperlimit)});auto.\n  elim H1;intro;auto.\n  exists (S upperlimit);auto.    \nQed.\nHint Resolve FindingSmallestInBoundedRangePred.\n\n\n\nLemma trueOrFalse(a b :bool) : {a = b} + {a=negb b}.\nProof.\n  compute.\n  elim a;elim b;intros;auto.\n Qed.\nHint Resolve   trueOrFalse.\n \nLemma inBoundedRangeDecidable (g:nat->bool)(limit:nat)(value:bool):{x | x<=limit /\\ g x = value} + {(forall x, x<=limit -> not (g x = value))}.\nProof.\n  pose (trueOrFalse (g limit) value) as H.\n  pose (trueOrFalse (g 0) value) as H0.\n  elim H;intro limval;elim H0; intro valval;try (rewrite hval);try (rewrite valval).\n  left; exists limit;auto.\n  left; exists limit;auto.\n  left; exists 0;auto.  \n  split;auto.\n  omega.\n  induction limit;auto.\n  right;auto.\n  intros.\n  assert (x=0).\n  omega.\n  rewrite H2.\n  rewrite valval.\n  apply no_fixpoint_negb.\n  assert ({g limit =  value} + {g limit = negb value});auto.\n  elim H1;intros.\n  left.\n  exists limit;auto. \n  assert (            {x : nat| x <= limit /\\ g x = value} +\n            {(forall x : nat, x <= limit -> g x <> value)});auto.\n  elim H2;intros;auto.\n  left.\n  elim a;intros x H3;auto.\n  elim H3.\n  exists x;auto.  \n  assert ({g (S limit) =  value} + {g (S limit) = negb value});auto.\n  elim H3;intros;auto.\n  left.\n  exists (S limit);auto.\n  right.  \n  intros.\n  assert ({x <= limit} + {limit < x}).\n  apply(le_lt_dec x limit);auto.\n  elim H5;auto;intros;auto.\n  assert (x = S limit);auto.\n  omega.\n  rewrite H6;auto.\n  rewrite b1;apply no_fixpoint_negb.\nQed.\nHint Resolve   inBoundedRangeDecidable.\n\nLemma inBoundedRangeDecidableStrict (g:nat->bool)(limit:nat)(value:bool):{x | x<limit /\\ g x = value} + {(forall x, x<limit -> not (g x = value))}.\nProof.\n  pose (zerop limit).\n  inversion s.\n  right.\n  intro.\n  omega.\n  pose (inBoundedRangeDecidable g (pred limit) value) as s0.\n  inversion s0;auto.\n  left.\n  inversion H0.\n  inversion H1.\n  exists x.\n  split;auto.\n  omega.\n  right.\n  intros.\n  pose (H0 x).\n  apply n.\n  omega.\nQed.\nHint Resolve   inBoundedRangeDecidableStrict.\n\n\n\nLemma NrOfTrueWithConstantNegFunction (trues lim:nat )(f : nat-> bool) :  ((NrOfTrue f lim)=trues /\\ forall x, x>lim -> f x = false) -> forall y, y>lim -> (NrOfTrue f y )=trues. \n    Proof.\n      intros.\n      elim H;intros.\n      induction y;auto.\n      contradict H0.\n      omega.\n      assert (f (S y) = false);auto.\n      assert (NrOfTrue f y = trues);auto.\n      elim (eq_nat_dec y lim);intro.\n      rewrite a;auto.\n      apply IHy.\n      omega.\n      unfold NrOfTrue.\n      rewrite H3.\n      auto.\n    Qed.\n      \n\nFixpoint trueOnFirst (g:nat-> bool) (n:nat):  (bool):=\n  match n with\n    | 0 => (g 0)\n    | S n =>  if (g (S n)) then if (inBoundedRangeDecidable g n true ) then false else true   else false\n  end.\n\nLemma nrOftrueIntrueIsLimitedByfalse(g:nat->bool): forall k, (forall x, x<=k ->  g x = false) <->  NrOfTrue  g k=0.\nProof.\nintros.\ninduction k;auto.\nsplit.\nintros.\nassert (g 0 =false);auto.\ncompute.\nrewrite H0;auto.\nintros.\nassert (x=0).\nomega.\nrewrite H1.\nunfold NrOfTrue in H.\ninduction (g 0);auto.\ncontradict H.  \nomega.\n\nsplit.\nintros.\nassert ( NrOfTrue g k = 0);auto.\napply IHk.\nintros.\napply H;auto.\nassert (g ( S k) = false);auto.\ncompute;auto.\nrewrite H1.\nsimpl.\nassert ({k<=0} + {0<k}).\napply (le_lt_dec).\nelim H2;auto.\nintros.\nassert (NrOfTrue g k = 0);auto.\nassert (NrOfTrue g k <= NrOfTrue g (S k));auto.\napply NrOfTrueIsMonotone.\nomega.\nomega.\nassert ((forall x : nat, x <= k -> g x = false));auto.\napply IHk;auto.\n\nassert ({S k<=x} + {x<S k}).\napply (le_lt_dec).\nelim H3;intros;auto.\nassert (x = S k);auto.\nomega.\nrewrite H4.\nunfold NrOfTrue in H.\ninduction (g (S k));auto.\ncontradict H.\nomega.\napply H2.\nomega.\nQed.\nHint Resolve   nrOftrueIntrueIsLimitedByfalse.\n\n\n\nLemma trueOnFirstImplTrueForG(g:nat->bool): (forall x, (trueOnFirst g) x = true -> (g x)=true).\nProof.\nintros.\ninduction x;auto.\nunfold trueOnFirst in H.\ninduction (g (S x));auto.\nQed.\n\nHint Resolve trueOnFirstImplTrueForG.\n\nLemma trueOnFirstAlwaysFalseAfter(g:nat->bool): (forall x, (trueOnFirst g) x = true -> forall y, y>x ->(trueOnFirst g) y = false).\nProof.\n  intro.\n  intro.\n  intro.\n  induction y;intros;auto.\n  contradict H0.\n  omega.\n\n   \n  assert ({x=y}+{x<>y});auto.\n  apply (eq_nat_dec x y);auto.\n  induction H1;intros;auto.\n  assert (g x = true);auto.\n  unfold trueOnFirst.\n  induction (g (S y));auto.\n  induction (inBoundedRangeDecidable g y);auto.\n  intros.\n  assert (x <= y -> g x <> true);auto.\n  rewrite a in H2.\n  assert ( g y <> true);auto.\n  rewrite<- a in H3. \n  contradict H3;auto.\n\n  assert (x < y);auto.\n  omega.  \n  assert (trueOnFirst g y = false);auto.\n  unfold trueOnFirst.\n  induction (g ( S y));auto.\n  induction (inBoundedRangeDecidable g y);auto.\n  intros.\n  assert ( g x <> true).\n  apply b0;auto.\n  omega.\n  contradict H3.\n  apply trueOnFirstImplTrueForG;auto.  \nQed.\nHint Resolve trueOnFirstAlwaysFalseAfter.\n\n\nLemma trueOnFirstConstantFalseImplConstantFalseHelper(g:nat->bool)(lim:nat):(forall x : nat,x<=lim ->  trueOnFirst g x = false) -> ((forall n : nat,n<=lim ->  g n = false)).\nProof.\n  induction lim;intros.\n  assert (n=0).\n  omega.\n  assert (trueOnFirst g 0 = false);auto.\n  rewrite H1.\n  auto.\n  elim (eq_nat_dec n (S lim));intros;auto.\n  rewrite a.\n  assert (trueOnFirst g (S lim) = false);auto.\n  unfold trueOnFirst in H1.\n  induction (g (S lim));auto.\n  induction (inBoundedRangeDecidable g lim true);auto.\n  elim a0;intros x H2;auto.\n  elim H2;intros.\n  assert (g x = false).\n  apply IHlim;intros;auto.\n  rewrite<- H4.\n  rewrite<- H5.\n  auto.\n  assert (n<=lim);auto.\n  omega.\nQed.\nHint Resolve trueOnFirstConstantFalseImplConstantFalseHelper.\n\nLemma trueOnFirstConstantFalseImplConstantFalse(g:nat->bool):(forall x : nat, trueOnFirst g x = false) -> ((forall n : nat, g n = false)).\nProof.\n  intro.\n  intro lim.  \n  assert (((forall n : nat,n<=lim ->  g n = false)));auto.\n  apply trueOnFirstConstantFalseImplConstantFalseHelper;auto.  \nQed.\n\n   \nLemma nrOftrueIntrueOnFirstStays1Succ(g:nat->bool): forall k, NrOfTrue (trueOnFirst g) k=1->NrOfTrue (trueOnFirst g) (S k)=1.\n  Proof.\n    intros.\n    apply (NrOfTrueWithConstantNegFunction 1 k  );auto.\n    split;auto.\n    intros.\n    assert ({x : nat | x <= k /\\ (trueOnFirst g ) x = true} +\n            {(forall x : nat, x <= k -> (trueOnFirst g ) x <> true)});auto.\n    \n    elim H1;intros;auto.\n    elim a.\n    intros x0 H2.\n    elim H2;intros.\n    apply (trueOnFirstAlwaysFalseAfter g x0);auto.\n    omega.\n    assert (forall x : nat, x <= k -> trueOnFirst g x =false );auto.\n    intros.\n    assert (trueOnFirst g x0 <> true);auto.\n    apply (not_true_iff_false);auto.\n    assert (trueOnFirst g 0 = false);auto.\n    apply H2;auto.\n    omega.\n    assert (NrOfTrue (trueOnFirst g) 0 = 0);auto.\n    unfold NrOfTrue.\n    rewrite H3;auto.\n    assert (NrOfTrue (trueOnFirst g) k = 0);auto.\n    apply nrOftrueIntrueIsLimitedByfalse;intros;auto.\n    contradict H;auto.\n    omega.\n  Qed.\nHint Resolve nrOftrueIntrueOnFirstStays1Succ.\n  \nLemma nrOftrueIntrueOnFirstIs1or0(g:nat->bool): forall k, NrOfTrue (trueOnFirst g) k<=1.\nProof.\n  intro.\n  induction k;auto.\n  unfold NrOfTrue.\n  elim (trueOnFirst g 0);auto.\n  elim (lt_eq_lt_dec (NrOfTrue (trueOnFirst g) k) 1 );intro.\n  elim a;auto;intros;auto.\n  assert (NrOfTrue (trueOnFirst g) k=0);auto.\n  omega.\n  unfold NrOfTrue.\n  elim (trueOnFirst g (S k));auto.\n  assert (NrOfTrue (trueOnFirst g) (S k) = 1).\n  apply nrOftrueIntrueOnFirstStays1Succ;auto.\n  omega.\n  contradict IHk.\n  omega.\nQed.  \n\n\nTheorem EafAndSTBImplMarkovsP (arrow: forall f,  StrictlyBoundedAlternative f -> Eaf f) : Markovs_Principle.\n    Proof.\n      apply MPImplMarkPrinciple;auto.\n      unfold MP.\n      unfold StrictlyBoundedAlternative in arrow.\n      unfold Eaf in arrow.\n      intros.\n      assert ( ~ (forall n : nat, not (g n = true)));auto.\n      intro.\n      firstorder.\n      assert ( ~ (forall n : nat, g n = false));auto.\n      intro.\n      apply H0;intros;auto.\n      assert (g n = false);auto.\n      rewrite H2.\n      congruence.\n\n      (* NEW: *)\n      assert {n : nat | forall m : nat, m >= n -> (trueOnFirst g) m = false};auto.\n      apply arrow;auto.\n      exists 1;intros;auto.\n      split;intros;auto.\n      apply (nrOftrueIntrueOnFirstIs1or0).\n      intro.\n      assert (forall k : nat, NrOfTrue (trueOnFirst g) k = 0);intros;auto.\n      pose (H2 k).\n      omega.\n      pose (nrOftrueIntrueIsLimitedByfalse (trueOnFirst g)).\n      assert ( forall k : nat, (forall x : nat, x <= k -> trueOnFirst g x = false) );auto.\n      intro.\n      apply i;auto.\n      pose (trueOnFirstConstantFalseImplConstantFalse g ).\n      apply H1.\n      apply e;auto.\n      intro.\n      apply (H4 x x).\n      auto.\n\n\n      \n      elim H2.\n      intro limit.\n      intros H3.\n      assert {y | (trueOnFirst g y) = true};auto.\n      assert ({x : nat | ( x <= limit /\\ (trueOnFirst g x) = true)} +\n              {(forall x : nat, x <= limit -> (trueOnFirst g x) <> true)}).\n      apply inBoundedRangeDecidable. \n      elim H4;auto.\n       intros.\n       elim a;intros.\n       exists x;auto.\n       firstorder.\n       intros.\n       assert (forall x : nat, x <= limit -> trueOnFirst g x = false);auto.\n       intros.\n       assert (trueOnFirst g x <> true);auto.\n       apply not_true_iff_false;auto.\n       assert (forall x : nat,  trueOnFirst g x = false);auto.\n       intros.\n       elim (lt_eq_lt_dec x limit);intros;auto.\n       elim a;intros;auto.\n       apply H5;auto.\n       omega.\n       apply H5;auto.\n       omega.\n       apply H3;auto.\n       omega.\n       assert (forall n : nat, g n = false);auto.\n       apply trueOnFirstConstantFalseImplConstantFalse;auto.\n       contradict H7;auto.   \n       elim H4.\n       intros.\n       exists x;auto.\n    Qed.\n\n\n    \nTheorem MarkovsPAndSTBImplEafOuter:  Markovs_Principle ->forall f:nat->bool,  (StrictlyBounded f) -> (Eaf f).\n  intros M f.\n  intro.\n  apply (MarkovsPAndSTBImplEaf f M).\n  apply StrictlyBoundedSTBPredEQ.\n  auto.\nQed.\n\n\nLemma WLPOImplBoundedImplSTBPred:  WLPO -> (forall f:nat->bool,  (Bounded f) -> (StrictlyBoundedAlternative f)).\nProof.\n  intros.\n  unfold WLPO in H.\n  unfold Bounded in H0.\n  unfold StrictlyBoundedAlternative.\n  elim H0.\n  intro upperlimit.\n  intro H1.\n\n\n  assert(forall g : nat -> bool,\n           {(forall n : nat, g n = true)} + {~ (forall n : nat, g n = true)});auto.\n  apply  WLPOImplWPOAlt;auto.\n\n  assert (forall pl, (forall n : nat,\n                        ((NrOfTrue f n)<=pl) <->\n                        ((Compare_dec.leb (NrOfTrue f n) pl) = true))).\n\n  intro;auto.\n  split;intros.\n  assert (NrOfTrue f n <= pl);auto.\n  apply leb_correct;auto.\n  assert(Compare_dec.leb (NrOfTrue f n) pl = true);auto.\n  apply leb_complete;auto.\n\n  set (B:=(fun pl k=>  (Compare_dec.leb (NrOfTrue f k) pl))).\n  (* Lets try 0 first. *)\n    \n  assert ((forall k : nat, NrOfTrue f k <= 0) +\n          ~ (forall k : nat, NrOfTrue f k <=  0));auto.\n  \n  elim (H2 (B 0));auto;intros.\n  left;auto.\n  intro.\n  assert (B 0 k = true);auto.\n  unfold B in H4.\n  apply H3;auto.\n  right.\n  unfold not in b.\n  unfold not.\n  unfold B in b.\n  intro.\n  apply b.\n  intros.\n  assert (NrOfTrue f n <= 0);auto.\n  apply H3;auto. \n  elim H4.\n  intro.\n  (*0 is our strict bound if 0 is a bound  *)\n  exists 0;auto.\n  split;auto.\n  intro.\n  pose (H5 1).\n  omega.\n\n  (* We are not in the zero case *)\n  intro notZero.\n  clear H4.\n\n  assert ({n: nat|\n            (forall k : nat, NrOfTrue f k <= n) /\\\n            (~ (forall k : nat, NrOfTrue f k <= pred n))}).\n\n  apply FindingSmallestInBoundedRangePred.\n  intros pl.\n  elim (H2 (B pl));auto;intros.\n  left;auto.\n  intro.\n  assert (B pl k = true);auto.\n  unfold B in H4.\n  apply H3;auto.\n  right.\n  unfold not in b.\n  unfold not.\n  intro.\n  apply b.\n  intro.\n  unfold B.\n  assert (NrOfTrue f n <= pl);auto.\n  apply H3;auto.\n  exists upperlimit.\n  auto.\n  intro.\n  apply notZero;auto.\n  elim H4.\n  intros x H5.\n  exists x.\n  elim H5.\n  intros.\n  split;auto.\n  intro.\n  apply H7.\n  intro.\n  pose (H8 k).\nomega.  \nQed.\n\n\nTheorem WLPOImplBoundedImplSTB:  WLPO -> (forall f:nat->bool,  (Bounded f) -> (StrictlyBounded f)).\nProof.\n  intros  wlpo f bounded.\n  apply (snd (StrictlyBoundedSTBPredEQ f)).\n  apply WLPOImplBoundedImplSTBPred;auto.\nQed.\n    \n\nTheorem BoundedImplSTBImplWLPO:  (forall f:nat->bool,  (Bounded f) -> (StrictlyBoundedAlternative f)) -> WLPO.\nProof.\n  intro arrow.\n  unfold Bounded in arrow.\n  unfold StrictlyBounded in arrow.\n\n    (* The idea: Lets make a function which is true only on the exactly first\n  place where g n = true, and false everywhere else. This has a limit of 1. But\n  is has a limit on exactly 1 iff {~ (forall n : nat, g n = false)} and 0 iff\n  {(forall n : nat, g n = false)}. *)\n\nunfold  WLPO.\nintro g.\n\n\nassert {n : nat |\n            (forall k : nat, NrOfTrue (trueOnFirst g) k <= n) /\\\n             ~ (forall k : nat, NrOfTrue (trueOnFirst g) k < n)};auto.\n\napply arrow;auto.\nexists 1;auto.\nintros;auto.\napply nrOftrueIntrueOnFirstIs1or0.\n\nelim H.\nassert (forall (g : nat -> bool) (k : nat), NrOfTrue (trueOnFirst g) k <= 1);auto.\napply nrOftrueIntrueOnFirstIs1or0.\nintro lim.\nintro H1.\n\nelim H1.\nintros.\nassert (lim <= 1).\nassert (forall k : nat, NrOfTrue (trueOnFirst g) k <=1).\napply nrOftrueIntrueOnFirstIs1or0.\nelim (le_lt_dec lim 1).\nintros.\nauto.\nintro.\ncontradict H3.\nintro.\npose (H4 k).\nomega.\n\n\nelim (lt_eq_lt_dec lim 1 );auto;intros;auto.\nelim a;intros;auto.\nassert (lim=0).\nomega.\nassert ( forall k : nat, NrOfTrue (trueOnFirst g) k <= 0).\nrewrite H5 in H2.\napply H2.\nleft.\nintro n.\nassert (NrOfTrue (trueOnFirst g) n <= 0);auto.\nassert (NrOfTrue (trueOnFirst g) n = 0);auto.\nomega.\nassert ((forall x : nat, x <= n -> trueOnFirst g x = false) );auto.\napply nrOftrueIntrueIsLimitedByfalse;auto.\napply (trueOnFirstConstantFalseImplConstantFalseHelper g n);auto.\n(* Done the case where the limit is 0! *)\n\nright.\nintro.\nassert (forall k, NrOfTrue  g k=0).\nintro.\napply (nrOftrueIntrueIsLimitedByfalse g).\nintros.\napply H5.\nassert (~ (forall k : nat, NrOfTrue (trueOnFirst g) k <= 0));auto.\nintro.\napply H3.\nrewrite b.\nintro.\npose (H7 k).\nomega.\napply H7.\nintro.\nassert ( forall x : nat,   trueOnFirst g x = false);auto.\nintro.\nassert (g x = false);auto.\nassert (trueOnFirst g x = true \\/ trueOnFirst g x =false);auto.\nelim (trueOnFirst g x);auto.\nelim H9;intros;auto.\nassert (g x = true);auto.\nrewrite H8 in H11.\ncontradict H11.\nauto.\nassert (NrOfTrue (trueOnFirst g) k = 0);auto.\napply nrOftrueIntrueIsLimitedByfalse.\nintros;auto.\nomega.\nassert False.\nomega.\ncontradict H5.\n Qed.\n", "meta": {"author": "epa095", "repo": "strictly-bounded-streams", "sha": "70cbe8cbebdb4136ba33c7155c06ac6767364e66", "save_path": "github-repos/coq/epa095-strictly-bounded-streams", "path": "github-repos/coq/epa095-strictly-bounded-streams/strictly-bounded-streams-70cbe8cbebdb4136ba33c7155c06ac6767364e66/strictbounded.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6660254384829413}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq             *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later            *)\nFrom mathcomp Require Import all_ssreflect ssralg fingroup perm finalg matrix.\nFrom mathcomp Require boolp.\nFrom mathcomp Require Import Rstruct.\nRequire Import Reals.\nRequire Import ssrR Reals_ext logb ssr_ext ssralg_ext bigop_ext Rbigop fdist.\nRequire Import proba.\n\n(******************************************************************************)\n(*        Conditional probabilities over joint finite distributions           *)\n(*                                                                            *)\n(*       \\Pr_P [ A | B ] == conditional probability of A given B where P is a *)\n(*                          joint distribution                                *)\n(*  jfdist_cond0 PQ a a0 == The conditional distribution derived from PQ      *)\n(*                          given a; PQ is a joint distribution               *)\n(*                          {fdist A * B}, a0 is a proof that                 *)\n(*                          fdist_fst PQ a != 0, the result is a              *)\n(*                          distribution {fdist B}                            *)\n(*      jfdist_cond PQ a == The conditional distribution derived from PQ      *)\n(*                          given a; same as fdist_cond0 when                 *)\n(*                          fdist_fst PQ a != 0.                              *)\n(*           PQ `(| a |) == notation jfdist_cond PQ a                         *)\n(*                                                                            *)\n(******************************************************************************)\n\nReserved Notation \"\\Pr_ P [ A | B ]\" (at level 6, P, A, B at next level,\n  format \"\\Pr_ P [ A  |  B ]\").\nReserved Notation \"\\Pr_[ A | B ]\" (at level 6, A, B at next level,\n  format \"\\Pr_[ A  |  B ]\").\nReserved Notation \"P `(| a ')'\" (at level 6, a at next level, format \"P `(| a )\").\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope R_scope.\nLocal Open Scope proba_scope.\nLocal Open Scope fdist_scope.\n\nSection conditional_probability.\nVariables (A B : finType) (P : {fdist A * B}).\nImplicit Types (E : {set A}) (F : {set B}).\n\nDefinition jcPr E F := Pr P (E `* F) / Pr (P`2) F.\n\nLocal Notation \"\\Pr_[ E | F ]\" := (jcPr E F).\n\nLemma jcPrE E F : \\Pr_[E | F] = `Pr_P [E `*T | T`* F].\nProof. by rewrite /jcPr -Pr_setTX setTE /cPr EsetT setIX !(setIT,setTI). Qed.\n\nLemma jcPrET E : \\Pr_[E | setT] = Pr P`1 E.\nProof. by rewrite jcPrE TsetT cPrET -Pr_XsetT EsetT. Qed.\n\nLemma jcPrE0 E : \\Pr_[E | set0] = 0.\nProof. by rewrite jcPrE Tset0 cPrE0. Qed.\n\nLemma jcPr_ge0 E F : 0 <= \\Pr_[E | F].\nProof. by rewrite jcPrE. Qed.\n\nLemma jcPr_le1 E F : \\Pr_[E | F] <= 1.\nProof. by rewrite jcPrE; exact: cPr_max. Qed.\n\nLemma jcPr_gt0 E F : 0 < \\Pr_[E | F] <-> \\Pr_[E | F] != 0.\nProof. by rewrite !jcPrE; apply cPr_gt0. Qed.\n\nLemma Pr_jcPr_gt0 E F : 0 < Pr P (E `* F) <-> 0 < \\Pr_[E | F].\nProof.\nsplit.\n- rewrite -{1}(setIT E) -{1}(setIT F) (setIC F) -setIX jcPrE.\n  by move/Pr_cPr_gt0; rewrite -setTE -EsetT.\n- move=> H; rewrite -{1}(setIT E) -{1}(setIT F) (setIC F) -setIX.\n  by apply/Pr_cPr_gt0; move: H; rewrite jcPrE -setTE -EsetT.\nQed.\n\nLemma jcPr_cplt E F : Pr (P`2) F != 0 -> \\Pr_[ ~: E | F] = 1 - \\Pr_[E | F].\nProof.\nby move=> PF0; rewrite 2!jcPrE EsetT setCX cPr_cplt ?EsetT // setTE Pr_setTX.\nQed.\n\nLemma jcPr_diff E1 E2 F : \\Pr_[E1 :\\: E2 | F] = \\Pr_[E1 | F] - \\Pr_[E1 :&: E2 | F].\nProof.\nrewrite jcPrE DsetT cPr_diff jcPrE; congr (_ - _).\nby rewrite 2!EsetT setIX setTI -EsetT jcPrE.\nQed.\n\nLemma jcPr_union_eq E1 E2 F :\n  \\Pr_[E1 :|: E2 | F] = \\Pr_[E1 | F] + \\Pr_[E2 | F] - \\Pr_[E1 :&: E2 | F].\nProof. by rewrite jcPrE UsetT cPr_union_eq !jcPrE IsetT. Qed.\n\nSection total_probability.\nVariables (I : finType) (E : {set A}) (F : I -> {set B}).\nLet P' := fdistX P.\nHypothesis dis : forall i j, i != j -> [disjoint F i & F j].\nHypothesis cov : cover (F @: I) = [set: B].\n\nLemma jtotal_prob_cond : Pr P`1 E = \\sum_(i in I) \\Pr_[E | F i] * Pr P`2 (F i).\nProof.\nrewrite -Pr_XsetT -EsetT.\nrewrite (@total_prob_cond _ _ _ _ (fun i => T`* F i)); last 2 first.\n  - move=> i j ij; rewrite -setI_eq0 !setTE setIX setTI.\n    by move: (dis ij); rewrite -setI_eq0 => /eqP ->; rewrite setX0.\n  - (* TODO: lemma? *) apply/setP => -[a b]; rewrite inE /cover.\n    apply/bigcupP => /=.\n    move: cov; rewrite /cover => /setP /(_ b).\n    rewrite !inE => /bigcupP[b'].\n    move/imsetP => [i _ ->{b'} bFi].\n    exists (T`* F i).\n      by apply/imsetP; exists i.\n    by rewrite inE.\nby apply eq_bigr => i _; rewrite -Pr_setTX -setTE; congr (_ * _); rewrite jcPrE.\nQed.\n\nEnd total_probability.\n\nEnd conditional_probability.\nNotation \"\\Pr_ P [ E | F ]\" := (jcPr P E F) : proba_scope.\n\nSection jPr_Pr.\nVariables (U : finType) (P : fdist U) (A B : finType).\nVariables (X : {RV P -> A}) (Y : {RV P -> B}) (E : {set A}) (F : {set B}).\n\nLemma jPr_Pr : \\Pr_(`p_[% X, Y]) [E | F] = `Pr[X \\in E |Y \\in F].\nProof.\nrewrite /jcPr Pr_fdistmap_RV2/= cpr_eq_setE /cPr; congr (_ / _).\nrewrite Pr_fdist_snd setTE Pr_fdistmap_RV2/=.\nrewrite (_ : [set x | X x \\in [set: A]] = setT) ?setTI//.\nby apply/setP => x; rewrite !inE.\nQed.\n\nEnd jPr_Pr.\n\nSection bayes.\nVariables (A B : finType) (PQ : {fdist A * B}).\nLet P := PQ`1. Let Q := PQ`2. Let QP := fdistX PQ.\nImplicit Types (E : {set A}) (F : {set B}).\n\nLemma jBayes E F : \\Pr_PQ[E | F] = \\Pr_QP [F | E] * Pr P E / Pr Q F.\nProof.\nrewrite 2!jcPrE Bayes /Rdiv -2!mulRA.\nrewrite EsetT Pr_XsetT setTE Pr_setTX /cPr; congr ((_ / _) * (_ / _)).\n  by rewrite EsetT setTE [in RHS]setIX Pr_fdistX setIX.\nby rewrite setTE Pr_fdistX.\nQed.\n\nLemma jBayes_extended (I : finType) (E : I -> {set A}) (F : {set B}) :\n  (forall i j, i != j -> [disjoint E i & E j]) ->\n  cover [set E i | i in I] = [set: A] ->\n  forall i,\n  \\Pr_PQ [E i | F] = (\\Pr_QP [F | E i] * Pr P (E i)) /\n                     \\sum_(j in I) \\Pr_ QP [F | E j] * Pr P (E j).\nProof.\nmove=> dis cov i; rewrite jBayes; congr (_ / _).\nmove: (@jtotal_prob_cond _ _ QP I F E dis cov).\nrewrite {1}/QP fdistX1 => ->.\nby apply eq_bigr => j _; rewrite -/QP {2}/QP fdistX2.\nQed.\n\nEnd bayes.\n\nSection conditional_probability_prop3.\nVariables (A B C : finType) (P : {fdist A * B * C}).\n\nLemma jcPr_TripC12 (E : {set A}) (F : {set B }) (G : {set C}) :\n  \\Pr_(fdistC12 P)[F `* E | G] = \\Pr_P[E `* F | G].\nProof. by rewrite /jcPr Pr_fdistC12 fdistC12_snd. Qed.\n\nLemma jcPr_fdistA_AC (E : {set A}) (F : {set B}) (G : {set C}) :\n  \\Pr_(fdistA (fdistAC P))[E | G `* F] = \\Pr_(fdistA P)[E | F `* G].\nProof.\nrewrite /jcPr 2!Pr_fdistA Pr_fdistAC; congr (_ / _).\nby rewrite fdistA_AC_snd -Pr_fdistX fdistXI.\nQed.\n\nLemma jcPr_fdistA_C12 (E : {set A}) (F : {set B}) (G : {set C}) :\n  \\Pr_(fdistA (fdistC12 P))[F | E `* G] = \\Pr_(fdistA (fdistX (fdistA P)))[F | G `* E].\nProof.\nrewrite /jcPr; congr (_ / _).\n  by rewrite Pr_fdistA Pr_fdistC12 Pr_fdistA -[in RHS]Pr_fdistX fdistXI Pr_fdistA.\nrewrite -/(fdist_proj13 _) -(fdistXI (fdist_proj13 P)) -Pr_fdistX fdistXI; congr Pr.\n(* TODO: lemma? *)\nby rewrite /fdist_proj13 /fdistX /fdist_snd /fdistA !fdistmap_comp.\nQed.\n\nEnd conditional_probability_prop3.\n\nSection product_rule.\n\nSection main.\nVariables (A B C : finType) (P : {fdist A * B * C}).\nImplicit Types (E : {set A}) (F : {set B}) (G : {set C}).\n\nLemma jproduct_rule_cond E F G :\n  \\Pr_P [E `* F | G] = \\Pr_(fdistA P) [E | F `* G] * \\Pr_(fdist_proj23 P) [F | G].\nProof.\nrewrite /jcPr; rewrite !mulRA; congr (_ * _); last by rewrite fdist_proj23_snd.\nrewrite -mulRA -/(fdist_proj23 _) -Pr_fdistA.\ncase/boolP : (Pr (fdist_proj23 P) (F `* G) == 0) => H; last by rewrite mulVR ?mulR1.\nsuff -> : Pr (fdistA P) (E `* (F `* G)) = 0 by rewrite mul0R.\nby rewrite Pr_fdistA; exact/Pr_fdist_proj23_domin/eqP.\nQed.\n\nEnd main.\n\nSection variant.\nVariables (A B C : finType) (P : {fdist A * B * C}).\nImplicit Types (E : {set A}) (F : {set B}) (G : {set C}).\n\nLemma product_ruleC E F G :\n  \\Pr_P [ E `* F | G] = \\Pr_(fdistA (fdistC12 P)) [F | E `* G] * \\Pr_(fdist_proj13 P) [E | G].\nProof. by rewrite -jcPr_TripC12 jproduct_rule_cond. Qed.\n\nEnd variant.\n\nSection prod.\nVariables (A B : finType) (P : {fdist A * B}).\nImplicit Types (E : {set A}) (F : {set B}).\n\nLemma jproduct_rule E F : Pr P (E `* F) = \\Pr_P[E | F] * Pr (P`2) F.\nProof.\nhave [/eqP PF0|PF0] := boolP (Pr (P`2) F == 0).\n  rewrite jcPrE /cPr -{1}(setIT E) -{1}(setIT F) -setIX.\n  rewrite Pr_domin_setI; last by rewrite -Pr_fdistX Pr_domin_setX // fdistX1.\n  by rewrite setIC Pr_domin_setI ?(div0R,mul0R) // setTE Pr_setTX.\nrewrite -{1}(setIT E) -{1}(setIT F) -setIX product_rule.\nrewrite -EsetT setTT cPrET Pr_setT mulR1 jcPrE.\nrewrite /cPr {1}setTE {1}EsetT.\nby rewrite setIX setTI setIT setTE Pr_setTX -mulRA mulVR ?mulR1.\nQed.\n\nEnd prod.\n\nEnd product_rule.\n\nLemma jcPr_fdistmap_r (A B B' : finType) (f : B -> B') (d : {fdist A * B})\n    (E : {set A}) (F : {set B}): injective f ->\n  \\Pr_d [E | F] = \\Pr_(fdistmap (fun x => (x.1, f x.2)) d) [E | f @: F].\nProof.\nmove=> injf; rewrite /jcPr; congr (_ / _).\n- rewrite (@Pr_fdistmap _ _ (fun x => (x.1, f x.2))) /=; last first.\n    by move=> [? ?] [? ?] /= [-> /injf ->].\n  congr (Pr _ _); apply/setP => -[a b]; rewrite !inE /=.\n  apply/imsetP/andP.\n  - case=> -[a' b']; rewrite inE /= => /andP[a'E b'F] [->{a} ->{b}]; split => //.\n    apply/imsetP; by exists b'.\n  - case=> aE /imsetP[b' b'F] ->{b}; by exists (a, b') => //; rewrite inE /= aE.\nby rewrite /fdist_snd fdistmap_comp (@Pr_fdistmap _ _ f) // fdistmap_comp.\nQed.\nArguments jcPr_fdistmap_r [A] [B] [B'] [f] [d] [E] [F] _.\n\nLemma jcPr_fdistmap_l (A A' B : finType) (f : A -> A') (d : {fdist A * B})\n    (E : {set A}) (F : {set B}): injective f ->\n  \\Pr_d [E | F] = \\Pr_(fdistmap (fun x => (f x.1, x.2)) d) [f @: E | F].\nProof.\nmove=> injf; rewrite /jcPr; congr (_ / _).\n- rewrite (@Pr_fdistmap _ _ (fun x => (f x.1, x.2))) /=; last first.\n    by move=> [? ?] [? ?] /= [/injf -> ->].\n  congr (Pr _ _); apply/setP => -[a b]; rewrite !inE /=.\n  apply/imsetP/andP.\n  - case=> -[a' b']; rewrite inE /= => /andP[a'E b'F] [->{a} ->{b}]; split => //.\n    apply/imsetP; by exists a'.\n  - by case=> /imsetP[a' a'E] ->{a} bF; exists (a', b) => //; rewrite inE /= a'E.\nby rewrite /fdist_snd !fdistmap_comp.\nQed.\nArguments jcPr_fdistmap_l [A] [A'] [B] [f] [d] [E] [F] _.\n\nLemma Pr_jcPr_unit (A : finType) (E : {set A}) (P : {fdist A}) :\n  Pr P E = \\Pr_(fdistmap (fun a => (a, tt)) P) [E | setT].\nProof.\nrewrite /jcPr (Pr_set1 _ tt).\nrewrite (_ : _`2 = fdist1 tt) ?fdist1xx ?divR1; last first.\n  rewrite /fdist_snd fdistmap_comp; apply/fdist_ext; case.\n  by rewrite fdistmapE fdist1xx (eq_bigl xpredT) // FDist.f1.\nrewrite /Pr big_setX /=; apply eq_bigr => a _; rewrite (big_set1 _ tt) /=.\nrewrite fdistmapE (big_pred1 a) // => a0; rewrite inE /=.\nby apply/eqP/eqP => [[] -> | ->].\nQed.\n\nSection jfdist_cond0.\nVariables (A B : finType) (PQ : {fdist A * B}) (a : A).\nHypothesis Ha : PQ`1 a != 0.\n\nLet f := [ffun b => \\Pr_(fdistX PQ) [[set b] | [set a]]].\n\nLet f0 b : 0 <= f b. Proof. rewrite ffunE; exact: jcPr_ge0. Qed.\n\nLet f1 : \\sum_(b in B) f b = 1.\nProof.\nunder eq_bigr do rewrite ffunE.\nby rewrite /jcPr -big_distrl /= PrX_snd mulRV // Pr_set1 fdistX2.\nQed.\n\nDefinition jfdist_cond0 : {fdist B} := locked (FDist.make f0 f1).\n\nLemma jfdist_cond0E b : jfdist_cond0 b = \\Pr_(fdistX PQ) [[set b] | [set a]].\nProof. by rewrite /jfdist_cond0; unlock; rewrite ffunE. Qed.\n\nEnd jfdist_cond0.\nArguments jfdist_cond0 {A} {B} _ _ _.\n\nSection jfdist_cond.\nVariables (A B : finType) (PQ : {fdist A * B}) (a : A).\nLet Ha := PQ`1 a != 0.\n\nLet sizeB : #|B| = #|B|.-1.+1.\nProof.\ncase HB: #|B| => //.\nby move: (fdist_card_neq0 PQ); rewrite card_prod HB muln0 ltnn.\nQed.\n\nDefinition jfdist_cond :=\n  match boolP Ha with\n  | AltTrue H => jfdist_cond0 PQ _ H\n  | AltFalse _ => fdist_uniform sizeB\n  end.\n\nLemma jfdist_condE (H : Ha) b : jfdist_cond b = \\Pr_(fdistX PQ) [[set b] | [set a]].\nProof.\nby rewrite /jfdist_cond; destruct boolP; [rewrite jfdist_cond0E|rewrite H in i].\nQed.\n\nLemma jfdist_cond_dflt (H : ~~ Ha) : jfdist_cond = fdist_uniform sizeB.\nProof.\nby rewrite /jfdist_cond; destruct boolP => //; rewrite i in H.\nQed.\n\nEnd jfdist_cond.\nNotation \"P `(| a ')'\" := (jfdist_cond P a).\n\nLemma cPr_1 (U : finType) (P : fdist U) (A B : finType)\n  (X : {RV P -> A}) (Y : {RV P -> B}) a : `Pr[X = a] != 0 ->\n  \\sum_(b <- fin_img Y) `Pr[ Y = b | X = a ] = 1.\nProof.\nrewrite -pr_eq_set1 pr_inE' Pr_set1 -{1}(fst_RV2 _ Y) => Xa0.\nset Q := `p_[% X, Y] `(| a ).\nrewrite -(FDist.f1 Q) [in RHS](bigID (mem (fin_img Y))) /=.\nrewrite [X in _ = _ + X](eq_bigr (fun=> 0)); last first.\n  move=> b bY.\n  rewrite /Q jfdist_condE // /jcPr /Pr !(big_setX,big_set1) /= fdistXE fdistX2 fst_RV2.\n  rewrite -!pr_eqE' !pr_eqE.\n  rewrite /Pr big1 ?div0R // => u.\n  rewrite inE => /eqP[Yub ?].\n  exfalso.\n  move/negP : bY; apply.\n  by rewrite mem_undup; apply/mapP; exists u => //; rewrite mem_enum.\nrewrite big_const iter_addR mulR0 addR0.\nrewrite big_uniq; last by rewrite /fin_img undup_uniq.\napply eq_bigr => b; rewrite mem_undup => /mapP[u _ bWu].\nrewrite /Q jfdist_condE // fdistX_RV2.\nby rewrite jcPrE -cpr_inE' cpr_eq_set1.\nQed.\n\nLemma jcPr_1 (A B : finType) (P : {fdist A * B}) a : P`1 a != 0 ->\n  \\sum_(b in B) \\Pr_(fdistX P)[ [set b] | [set a] ] = 1.\nProof.\nmove=> Xa0; rewrite -(FDist.f1 (P `(| a ))); apply eq_bigr => b _.\nby rewrite jfdist_condE.\nQed.\n\nLemma jfdist_cond_prod (A B : finType) (P : fdist A) (W : A -> fdist B) (a : A) :\n  (P `X W)`1 a != 0 -> W a = (P `X W) `(| a ).\nProof.\nmove=> a0; apply/fdist_ext => b.\nrewrite jfdist_condE // /jcPr setX1 !Pr_set1 fdistXE fdistX2 fdist_prod1.\nrewrite fdist_prodE /= /Rdiv mulRAC mulRV ?mul1R //.\nby move: a0; rewrite fdist_prod1.\nQed.\n\nLemma jcPr_fdistX_prod (A B : finType) (P : fdist A) (W : A -> fdist B) a b :\n  P a <> 0 -> \\Pr_(fdistX (P `X W))[ [set b] | [set a] ] = W a b.\nProof.\nmove=> Pxa.\nrewrite /jcPr setX1 fdistX2 2!Pr_set1 fdistXE fdist_prod1.\nby rewrite fdist_prodE /= /Rdiv mulRAC mulRV ?mul1R //; exact/eqP.\nQed.\n\nSection fdist_split.\nVariables (A B : finType).\n\nDefinition fdist_split (PQ : {fdist A * B}) := (PQ`1, fun x => PQ `(| x )).\n\nLemma fdist_prodK : cancel fdist_split (uncurry (@fdist_prod A B)).\nProof.\nmove=> PQ; apply/fdist_ext => ab; rewrite fdist_prodE.\nhave [Ha|Ha] := eqVneq (PQ`1 ab.1) 0.\n  rewrite Ha mul0R; apply/esym/(dominatesE (Prod_dominates_Joint PQ)).\n  by rewrite fdist_prodE Ha mul0R.\nrewrite jfdist_condE // -fdistX2 mulRC.\nrewrite -(Pr_set1 _ ab.1) -jproduct_rule setX1 Pr_set1 fdistXE.\nby case ab.\nQed.\n\nEnd fdist_split.\n", "meta": {"author": "affeldt-aist", "repo": "infotheo", "sha": "5f9efb859dbadcbcae2330e2e21e76f9b632d879", "save_path": "github-repos/coq/affeldt-aist-infotheo", "path": "github-repos/coq/affeldt-aist-infotheo/infotheo-5f9efb859dbadcbcae2330e2e21e76f9b632d879/probability/jfdist_cond.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6660230567460257}}
{"text": "(* This file contains all basic definitions from Section 4. *)\n\nRequire Export Arith.\nRequire Export Relations.\n\nCoInductive term : Set :=\n| bot : term\n| var : nat -> term\n| app : term -> term -> term\n| abs : term -> term.\n\nCoInductive par_clos (R : relation term) : relation term :=\n| par_clos_base : forall x y, R x y -> par_clos R x y\n| par_clos_bot : par_clos R bot bot\n| par_clos_var : forall n, par_clos R (var n) (var n)\n| par_clos_app : forall x y x' y', par_clos R x x' -> par_clos R y y' -> par_clos R (app x y) (app x' y')\n| par_clos_abs : forall x y, par_clos R x y -> par_clos R (abs x) (abs y).\n\n(* equality (identity) of infinitary terms *)\nDefinition term_eq := par_clos (fun _ _ => False).\n\nNotation \"A == B\" := (term_eq A B) (at level 70).\nNotation \"A != B\" := (~(term_eq A B)) (at level 70).\n\nDefinition morphism (R : relation term) := forall x y, R x y -> forall x' y', x == x' -> y == y' -> R x' y'.\n\nCoFixpoint shift d c t : term :=\n  match t with\n    | bot => bot\n    | var n => var (if c <=? n then n + d else n)\n    | app t1 t2 => app (shift d c t1) (shift d c t2)\n    | abs t1 => abs (shift d (c+1) t1)\n  end.\n\nDefinition shift_closed (R : relation term) :=\n  forall d c t t', R t t' -> R (shift d c t) (shift d c t').\n\nCoFixpoint subst n s t : term :=\n  match t with\n  | bot => bot\n  | var m => if n <? m then var (m - 1) else if n =? m then shift n 0 s else var m\n  | app t1 t2 => app (subst n s t1) (subst n s t2)\n  | abs t' => abs (subst (n+1) s t')\n  end.\n\nNotation \"A [ N := B ]\" := (subst N B A) (at level 50).\n\nDefinition subst_closed (R : relation term) :=\n  forall x x' n y, R x x' -> R (x[n := y]) (x'[n := y]).\n\nInductive beta_redex : relation term :=\n| beta_redex_c : forall x y t1 t2, x == (app (abs t1) t2) -> y == (t1[0 := t2]) ->\n                                   beta_redex x y.\n\nInductive comp_clos (R : relation term) : relation term :=\n| comp_clos_base : forall x y, R x y -> comp_clos R x y\n| comp_clos_app_l : forall x y x' y', comp_clos R x x' -> y == y' -> comp_clos R (app x y) (app x' y')\n| comp_clos_app_r : forall x y x' y', comp_clos R y y' -> x == x' -> comp_clos R (app x y) (app x' y')\n| comp_clos_abs : forall x y, comp_clos R x y -> comp_clos R (abs x) (abs y).\n\n(* beta reduction step *)\nDefinition step_beta := comp_clos beta_redex.\n\nInductive star (R : relation term) : relation term :=\n| star_refl : forall x y, x == y -> star R x y\n| star_step : forall x y z, R x y -> star R y z -> star R x z.\n\n(* finitary beta reduction *)\nDefinition red_beta := star step_beta.\n\nCoInductive inf_clos (R : relation term) : relation term :=\n| inf_clos_bot : forall s, R s bot -> inf_clos R s bot\n| inf_clos_var : forall s n, R s (var n) -> inf_clos R s (var n)\n| inf_clos_app : forall s x y x' y', R s (app x y) -> inf_clos R x x' -> inf_clos R y y' ->\n                                     inf_clos R s (app x' y')\n| inf_clos_abs : forall s x x', R s (abs x) -> inf_clos R x x' -> inf_clos R s (abs x').\n\nDefinition aux_clos (R : relation term) := inf_clos (inf_clos (star R)).\n\n(* infinitary beta reduction *)\nDefinition inf_beta := inf_clos red_beta.\n\n(* weak head reduction step *)\nInductive step_wh : relation term :=\n| wh_base : forall x y, beta_redex x y -> step_wh x y\n| wh_step : forall x x' y y', step_wh x x' -> y == y' -> step_wh (app x y) (app x' y').\n\nDefinition red_wh := star step_wh.\nDefinition inf_wh := inf_clos red_wh.\n\nDefinition is_abs t := match t with abs _ => True | _ => False end.\n\nDefinition is_rnf (t : term) :=\n  match t with\n  | bot => False\n  | var _ => True\n  | abs _ => True\n  | app x y => forall z, inf_beta x z -> ~(is_abs z)\n  end.\n\nDefinition has_rnf t := exists t', is_rnf t' /\\ inf_beta t t'.\nDefinition root_active t := ~(has_rnf t).\n\nDefinition sim (U : term -> Prop) := par_clos (fun x y => U x /\\ U y).\n\nDefinition meaningless (U : term -> Prop) :=\n  (forall x y, U x -> inf_beta x y -> U y) /\\\n  (forall x y n, U x -> U (x[n := y])) /\\\n  (forall x d c, U x -> U (shift d c x)) /\\\n  (forall x y, U (abs x) -> U (app (abs x) y)) /\\\n  (forall x, root_active x -> U x) /\\\n  (forall x y, U x -> sim U x y -> U y).\n\nDefinition strongly_meaningless (U : term -> Prop) :=\n  meaningless U /\\ forall x y, U y -> inf_beta x y -> U x.\n\nDefinition bot_redex (U : term -> Prop) (x y : term) := U x /\\ x != bot /\\ y == bot.\nDefinition beta_bot_redex U x y := beta_redex x y \\/ bot_redex U x y.\nDefinition step_bot U := comp_clos (bot_redex U).\nDefinition step_beta_bot U := comp_clos (beta_bot_redex U).\nDefinition red_beta_bot U := star (step_beta_bot U).\nDefinition inf_beta_bot U := inf_clos (red_beta_bot U).\nDefinition par_beta_bot U := par_clos (beta_bot_redex U).\nDefinition par_bot U := par_clos (bot_redex U).\n\nDefinition nf (R : relation term) (t : term) := forall s, ~(R t s).\nHint Unfold nf.\n\nDefinition nf_beta := nf step_beta.\nDefinition nf_beta_bot U := nf (step_beta_bot U).\n\n(************************************************************************)\n(* Assumed axioms: constructive indefinite description (see cases.v)\n   and some specializations of the excluded middle. *)\n\nAxiom is_rnf_xm : forall t, is_rnf t \\/ ~(is_rnf t).\nAxiom has_rnf_xm : forall t, has_rnf t \\/ ~(has_rnf t).\nAxiom strongly_meaningless_xm : forall U, strongly_meaningless U -> forall t, U t \\/ ~(U t).\n", "meta": {"author": "lukaszcz", "repo": "infinitary-confluence", "sha": "72068701ffb35003f773994d4ed47d1eaadc19ca", "save_path": "github-repos/coq/lukaszcz-infinitary-confluence", "path": "github-repos/coq/lukaszcz-infinitary-confluence/infinitary-confluence-72068701ffb35003f773994d4ed47d1eaadc19ca/defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6660060085687908}}
{"text": "Set Implicit Arguments.\n(** * Possibly terminating streams\n\n    We conceptualize the traditional unix pipeline programs as\n    transformations on streams. These streams are neither traditional\n    lists, which must terminate, nor traditional coinductive streams,\n    which must not, so we use a hybrid of the two. *)\n\nCoInductive pt_stream (A : Type) : Type :=\n| nil : pt_stream A\n| cons : A -> pt_stream A -> pt_stream A.\n\n(** pt_streams are equal when they're bisimulationally-equivalent\n    infinite streams or the same finite stream. *)\nCoInductive pt_stream_eq (A : Type) : pt_stream A -> pt_stream A -> Prop :=\n| pt_stream_eq_nil : pt_stream_eq (nil A) (nil A)\n| pt_stream_eq_cons : forall {a} {tl1} {tl2}, pt_stream_eq tl1 tl2 -> pt_stream_eq (cons a tl1) (cons a tl2).\n\n(** Concatenate two streams *)\nCoFixpoint app {A : Type} (fst : pt_stream A) (snd : pt_stream A) : pt_stream A :=\n  match fst with\n  | nil _ => snd\n  | cons a tl => cons a (app tl snd)\n  end.\n", "meta": {"author": "shlevy", "repo": "cat-fiat", "sha": "151f0cd3272b254bfc7631e4b33846b849cddeec", "save_path": "github-repos/coq/shlevy-cat-fiat", "path": "github-repos/coq/shlevy-cat-fiat/cat-fiat-151f0cd3272b254bfc7631e4b33846b849cddeec/src/PTStream.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6660060062987443}}
{"text": "(** * RIS.algebra : algebraic structures. *)\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import tools.\n\n(** * Definitions *)\nSection algebra.\n  (** Let [A] be some type equipped with an equivalence relation [⩵] and a partial order [≦]. *)\n  Context {A : Type} {eqA: relation A}.\n  Context {equivA : @Equivalence A eqA}.\n\n  Infix \" ⩵ \" := eqA (at level 80).\n\n  (** We introduce some notations. *)\n  Class Un := un : A.\n  Notation \" 𝟭 \" := un.\n\n  Class Zero := zero : A.\n  Notation \" 𝟬 \" := zero.\n  \n  Class Product := prod : A -> A -> A.\n  Infix \" · \" := prod (at level 40).\n\n  Class Join := join : A -> A -> A.\n  Infix \" ∪ \" := join (at level 45).\n\n  Class Star := star : A -> A.\n  Notation \" e ⋆ \" := (star e) (at level 35).\n\n  (** ** Basic properties *)\n  Class Associative (prod : A -> A -> A) :=\n    associative : (forall a b c : A, prod a (prod b c) ⩵ prod (prod a b) c).\n  Class Commutative (prod : A -> A -> A) :=\n    commutative : (forall a b : A, prod a b ⩵ prod b a).\n  Class Idempotent (prod : A -> A -> A) :=\n    idempotent : (forall a : A, prod a a ⩵ a).\n  Class Unit (prod : A -> A -> A) (unit : A) :=\n    {\n      left_unit : forall a : A, prod unit a ⩵ a;\n      right_unit : forall a : A, prod a unit ⩵ a\n    }.\n  Class Absorbing (prod : A -> A -> A) (z : A) :=\n    {\n      left_absorbing : forall a : A, prod z a ⩵ z;\n      right_absorbing : forall a : A, prod a z ⩵ z\n    }.\n\n  (** ** Basic structures *)\n  Class Monoid (prod : A -> A -> A) (unit : A) :=\n    {\n      mon_congr :> Proper (eqA ==> eqA ==> eqA) prod;\n      mon_assoc :> Associative prod;\n      mon_unit :> Unit prod unit;\n    }.\n\n  Class Semilattice (join : A -> A -> A) :=\n    {\n      lat_congr :> Proper (eqA ==> eqA ==> eqA) join;\n      lat_assoc :> Associative join;\n      lat_comm :> Commutative join;\n      lat_idem :> Idempotent join;\n    }.\n  \n  Class Lattice (m j : A -> A -> A) :=\n    {\n      lat_meet_congr :> Proper (eqA ==> eqA ==> eqA) m;\n      lat_meet_assoc :> Associative m;\n      lat_meet_comm :> Commutative m;\n      lat_join_congr :> Proper (eqA ==> eqA ==> eqA) j;\n      lat_join_assoc :> Associative j;\n      lat_join_comm :> Commutative j;\n      lat_join_meet : forall a b, j a (m a b) ⩵ a;\n      lat_meet_join : forall a b, m a (j a b) ⩵ a;\n    }.\n\n  Class SemiRing (prod add : A -> A -> A) (u z : A) :=\n    {\n      semiring_prod :> Monoid prod u;\n      semiring_add :> Monoid add z;\n      semiring_comm :> Commutative add;\n      semiring_zero :> Absorbing prod z;\n      semiring_left_distr : forall a b c, prod a (add b c) ⩵ add (prod a b) (prod a c);\n      semiring_right_distr : forall a b c, prod (add a b) c ⩵ add (prod a c) (prod b c);\n    }.\n\n  (** ** Join semi-lattices *)\n  Section order.\n    Context {j : Join}.\n    Context {S : Semilattice join}.\n    \n    Definition leqA : relation A := (fun x y => y ⩵ x ∪ y).\n    Infix \" ≦ \" := leqA (at level 80).\n\n    Global Instance preA : PreOrder leqA.\n    Proof.\n      destruct S as [p ass comm id];unfold leqA.\n      split.\n      - intro x;symmetry;apply id.\n      - intros x y z e1 e2.\n        rewrite e2 at 2.\n        rewrite (ass x y z),<- e1.\n        apply e2.\n    Qed.\n\n    Global Instance partialA : PartialOrder eqA leqA.\n    Proof.\n      destruct S as [p ass comm id].\n      intros x y;unfold Basics.flip,leqA;split.\n      - intros E;split.\n        + rewrite E,(id y);reflexivity.\n        + rewrite E;symmetry;apply id.\n      - intros (E1&E2).\n        rewrite E1.\n        rewrite E2 at 1.\n        apply comm.\n    Qed.\n    \n    Lemma refactor e f g h : (e ∪ f) ∪ (g ∪ h) ⩵ (e ∪ g) ∪ (f ∪ h).\n    Proof.\n      rewrite (lat_assoc (e∪f) g h).\n      rewrite <- (lat_assoc e f g).\n      rewrite (@lat_comm _ S f g).\n      rewrite (lat_assoc e g f).\n      rewrite (lat_assoc (e∪g) f h).\n      reflexivity.\n    Qed.\n\n    Global Instance proper_join_inf : Proper (leqA ==> leqA ==> leqA) join.\n    Proof.\n      intros x y I x' y' I';unfold leqA in *.\n      rewrite I,I' at 1;apply refactor.\n    Qed.\n\n    Lemma inf_cup_left a b : a ≦ a ∪ b.\n    Proof. unfold leqA; rewrite (lat_assoc _ _ _),(lat_idem _);reflexivity. Qed.\n\n    Lemma inf_cup_right a b : b ≦ a ∪ b.\n    Proof. rewrite (lat_comm a b);apply inf_cup_left. Qed.\n\n    Lemma inf_join_inf a b c : a ≦ c -> b ≦ c -> a ∪ b ≦ c.\n    Proof. intros;rewrite <- (lat_idem c); apply proper_join_inf;assumption. Qed.\n\n    Context {z : Zero} {u : Unit join zero}.\n  \n    Lemma zero_minimal x : zero ≦ x.\n    Proof. unfold leqA;symmetry ;apply left_unit. Qed.\n\n  End order.\n      \n  Infix \" ≦ \" := leqA (at level 80).\n\n\n  (** ** Kleene algebra and Boolean algebra *)\n  Class KleeneAlgebra (j: Join) (p: Product) (z: Zero) (u:Un) (s:Star) :=\n    {\n      ka_star_congr :> Proper (eqA ==> eqA) star;\n      ka_semiring :> SemiRing prod join un zero;\n      ka_idem :> Idempotent join;\n      ka_star_unfold : forall a, 𝟭 ∪ a · a ⋆ ≦ a⋆ ;\n      ka_star_left_ind : forall a b, a · b ≦ b -> a ⋆ · b ≦ b;\n      ka_star_right_ind : forall a b, a · b ≦ a -> a · b ⋆ ≦ a;\n    }.\n\n  Class BooleanAlgebra (t f : A) (n : A -> A) (c d: A -> A -> A) :=\n    {\n      proper_c :> Proper (eqA ==> eqA ==> eqA) c;\n      proper_d :> Proper (eqA ==> eqA ==> eqA) d;\n      proper_n :> Proper (eqA ==> eqA) n;\n      ba_conj_comm :> Commutative c;\n      ba_disj_comm :> Commutative d;\n      ba_true : forall a, c a t ⩵ a;\n      ba_false : forall a, d a f ⩵ a;\n      ba_conj_disj : forall x y z, c x (d y z) ⩵ d (c x y) (c x z);\n      ba_disj_conj : forall x y z, d x (c y z) ⩵ c (d x y) (d x z);\n      ba_neg_conj : forall a, c a (n a) ⩵ f;\n      ba_neg_disj : forall a, d a (n a) ⩵ t;\n    }.\n  \nEnd algebra.\nArguments Zero: clear implicits.\nArguments Un: clear implicits.\nArguments Product: clear implicits.\nArguments Join: clear implicits.\nArguments Star: clear implicits.\nNotation \" 𝟭 \" := un.\nNotation \" 𝟬 \" := zero.\nInfix \" · \" := prod (at level 40).\nInfix \" ∪ \" := join (at level 45).\nNotation \" e ⋆ \" := (star e) (at level 35).\n\nArguments KleeneAlgebra : clear implicits.\nArguments KleeneAlgebra A eqA {j p z u s}.\nArguments SemiRing : clear implicits.\nArguments Semilattice : clear implicits.\nArguments BooleanAlgebra : clear implicits.\nArguments BooleanAlgebra {A} eqA t f n c d.\nArguments leqA : clear implicits.\nArguments leqA {A} eqA {j}.\n\n(** * Facts about boolean algebra *)\nSection booleanAlgebra.\n  Context {A : Type} {eqA: relation A}.\n  Context {equivA : @Equivalence A eqA}.\n\n  Infix \" ⩵ \" := eqA (at level 80).\n  Context {top bot : A} {neg : A -> A} {conj disj : A -> A -> A}.\n  Context `{BooleanAlgebra A eqA top bot neg conj disj}.\n\n  Notation \" ⊤ \" := top.\n  Notation \" ⊥ \" := bot.\n  Notation \" ¬ \" := neg.\n  Infix \" ∧ \" := conj (at level 40).\n  Infix \" ∨ \" := disj (at level 45).\n\n  (** When we defined boolean algebra before, we relied on\n  Huntington's 1904 axiomatization, which differs from the usual way\n  they are defined, but is much more concise. We now show that this\n  axiomatization indeed implies all the properties we expect of a\n  boolean algebra. The following subsection is a straightforward\n  adaptation of the proofs detailed on the wikipedia page of boolean\n  algebra: \n  #<a href=\"https://en.wikipedia.org/wiki/Boolean_algebra_(structure)##Axiomatics\">en.wikipedia.org/wiki/Boolean_algebra_(structure)</a>#.*)\n\n  (** ** Elementary properties *)\n  Lemma UId1 o : (forall x, x ∨ o ⩵ x) -> o ⩵ ⊥.\n  Proof.\n    intros hyp.\n    rewrite <- (ba_false o).\n    rewrite (ba_disj_comm _ _).\n    apply hyp.\n  Qed.\n  \n  Lemma Idm1 x : x ∨ x ⩵ x.\n  Proof.\n    rewrite <- (ba_true (x∨x)),<-(ba_neg_disj x).\n    rewrite <- ba_disj_conj,ba_neg_conj.\n    apply ba_false.\n  Qed.\n\n  Lemma Bnd1 x : x ∨ ⊤ ⩵ ⊤.\n  Proof.\n    rewrite <- (ba_true (x∨⊤)),(ba_conj_comm _ _).\n    rewrite <- (ba_neg_disj x) at 1.\n    rewrite <- ba_disj_conj,ba_true.\n    apply ba_neg_disj.\n  Qed.\n\n  Lemma Abs1 x y : x ∨ (x ∧ y) ⩵ x.\n  Proof.\n    rewrite <- (ba_true x) at 1.\n    rewrite <- ba_conj_disj,(ba_disj_comm _ _),Bnd1.\n    apply ba_true.\n  Qed.\n\n  Lemma UId2 o : (forall x, x ∧ o ⩵ x) -> o ⩵ ⊤.\n  Proof.\n    intros hyp.\n    rewrite <- (ba_true o).\n    rewrite (ba_conj_comm _ _).\n    apply hyp.\n  Qed.\n  \n  Lemma Idm2 x : x ∧ x ⩵ x.\n  Proof.\n    rewrite <- (ba_false (x∧x)),<-(ba_neg_conj x).\n    rewrite <- ba_conj_disj,ba_neg_disj.\n    apply ba_true.\n  Qed.\n\n  Lemma Bnd2 x : x ∧ ⊥ ⩵ ⊥.\n  Proof.\n    rewrite <- (ba_false (x∧⊥)),(ba_disj_comm _ _).\n    rewrite <- (ba_neg_conj x) at 1.\n    rewrite <- ba_conj_disj,ba_false.\n    apply ba_neg_conj.\n  Qed.\n\n  Lemma Abs2 x y : x ∧ (x ∨ y) ⩵ x.\n  Proof.\n    rewrite <- (ba_false x) at 1.\n    rewrite <- ba_disj_conj,(ba_conj_comm _ _),Bnd2.\n    apply ba_false.\n  Qed.\n  \n  Lemma UNg x x' : x ∨ x' ⩵ ⊤ -> x ∧ x' ⩵ ⊥ -> x' ⩵ ¬ x.\n  Proof.\n    intros h1 h2.\n    rewrite <- (ba_true x'),<-(ba_neg_disj x),ba_conj_disj,(ba_conj_comm x' _),(ba_conj_comm x' _).\n    rewrite h2.\n    rewrite <- (ba_neg_conj x),(ba_conj_comm _ _),<-ba_conj_disj.\n    rewrite h1.\n    apply ba_true.\n  Qed.\n\n  Lemma DNg x : ¬(¬ x) ⩵ x.\n  Proof.\n    symmetry;apply UNg.\n    - rewrite (ba_disj_comm _ _);apply ba_neg_disj.\n    - rewrite (ba_conj_comm _ _);apply ba_neg_conj.\n  Qed.\n\n  Lemma A1 x y : x ∨ (¬ x ∨ y) ⩵ ⊤.\n  Proof.\n    rewrite <- (ba_true (x∨_)),(ba_conj_comm _ _),<-(ba_neg_disj x).\n    rewrite <- ba_disj_conj.\n    rewrite Abs2;reflexivity.\n  Qed.\n\n  Lemma A2 x y : x ∧ (¬ x ∧ y) ⩵ ⊥.\n  Proof.\n    rewrite <- (ba_false (x∧_)),(ba_disj_comm _ _),<-(ba_neg_conj x).\n    rewrite <- ba_conj_disj.\n    rewrite Abs1;reflexivity.\n  Qed.\n\n  Lemma B1 x y : (x ∨ y)∨(¬x∧¬y)⩵⊤.\n  Proof.\n    rewrite ba_disj_conj.\n    rewrite (ba_disj_comm _ (¬x)), (ba_disj_comm _ (¬y)).\n    rewrite (ba_disj_comm x y) at 2.\n    rewrite <- (DNg x) at 2.\n    rewrite <- (DNg y) at 3.\n    repeat rewrite A1.\n    apply ba_true.\n  Qed.\n    \n  Lemma B2 x y : (x ∧ y)∧(¬x∨¬y)⩵⊥.\n  Proof.\n    rewrite ba_conj_disj.\n    rewrite (ba_conj_comm _ (¬x)), (ba_conj_comm _ (¬y)).\n    rewrite (ba_conj_comm x y) at 2.\n    rewrite <- (DNg x) at 2.\n    rewrite <- (DNg y) at 3.\n    repeat rewrite A2.\n    apply ba_false.\n  Qed.\n\n  Lemma C1 x y : (x ∨ y)∧ (¬x∧¬y)⩵⊥.\n  Proof.\n    rewrite (ba_conj_comm (x∨_) _),ba_conj_disj.\n    rewrite (ba_conj_comm _ x),(ba_conj_comm _ y).\n    rewrite (ba_conj_comm _ (¬y)) at 2.\n    repeat rewrite A2.\n    apply ba_false.\n  Qed.\n\n  Lemma C2 x y : (x ∧ y)∨ (¬x∨¬y)⩵⊤.\n  Proof.\n    rewrite (ba_disj_comm (x∧_) _),ba_disj_conj.\n    rewrite (ba_disj_comm _ x),(ba_disj_comm _ y).\n    rewrite (ba_disj_comm _ (¬y)) at 2.\n    repeat rewrite A1.\n    apply ba_true.\n  Qed.\n\n  Lemma DMg1 x y : ¬ (x∨y) ⩵ ¬ x ∧ ¬ y.\n  Proof.\n    symmetry;apply UNg.\n    - apply B1.\n    - apply C1.\n  Qed.\n\n  Lemma DMg2 x y : ¬ (x∧y) ⩵ ¬ x ∨ ¬ y.\n  Proof.\n    symmetry;apply UNg.\n    - apply C2.\n    - apply B2.\n  Qed.\n\n  Lemma D1 x y z : (x∨(y∨z))∨¬x⩵⊤.\n  Proof.\n    rewrite (ba_disj_comm _ (¬x)).\n    rewrite <- (DNg x) at 2.\n    apply A1.\n  Qed.\n\n  Lemma D2 x y z : (x∧(y∧z))∧¬x⩵⊥.\n  Proof.\n    rewrite (ba_conj_comm _ (¬x)).\n    rewrite <- (DNg x) at 2.\n    apply A2.\n  Qed.\n\n  Lemma E1 x y z : y∧(x∨(y∨z))⩵ y.\n  Proof.\n    rewrite ba_conj_disj,Abs2,(ba_disj_comm _).\n    apply Abs1.\n  Qed.\n\n  Lemma E2 x y z : y∨(x∧(y∧z))⩵ y.\n  Proof.\n    rewrite ba_disj_conj,Abs1,(ba_conj_comm _).\n    apply Abs2.\n  Qed.\n\n  Lemma F1 x y z : (x∨(y∨z))∨¬y ⩵ ⊤.\n  Proof.\n    rewrite (ba_disj_comm _ (¬ _)).\n    rewrite <- ba_true,(ba_conj_comm _ _),<-(ba_neg_disj y) at 1.\n    rewrite (ba_disj_comm y),<-ba_disj_conj,E1,(ba_disj_comm _ y).\n    apply ba_neg_disj.\n  Qed.\n\n  Lemma F2 x y z : (x∧(y∧z))∧¬y ⩵ ⊥.\n  Proof.\n    rewrite (ba_conj_comm _ (¬ _)).\n    rewrite <- ba_false,(ba_disj_comm _ _),<-(ba_neg_conj y) at 1.\n    rewrite (ba_conj_comm y),<-ba_conj_disj,E2,(ba_conj_comm _ y).\n    apply ba_neg_conj.\n  Qed.\n\n  Lemma G1 x y z : (x ∨(y∨z))∨¬z⩵⊤.\n  Proof. rewrite (ba_disj_comm y z);apply F1. Qed.\n\n  Lemma G2 x y z : (x ∧(y∧z))∧¬z⩵⊥.\n  Proof. rewrite (ba_conj_comm y z);apply F2. Qed.\n\n  Lemma H1 x y z : ¬ ((x∨y)∨z)∧x⩵⊥.\n  Proof.\n    rewrite DMg1,DMg1.\n    rewrite (ba_conj_comm _).\n    rewrite <- ba_false,(ba_disj_comm _).\n    rewrite <- (ba_neg_conj x) at 1.\n    rewrite <- ba_conj_disj,(ba_conj_comm _ (¬z)),E2.\n    apply ba_neg_conj.\n  Qed.\n\n  Lemma H2 x y z : ¬ ((x∧y)∧z)∨x⩵⊤.\n  Proof.\n    rewrite DMg2,DMg2.\n    rewrite (ba_disj_comm _).\n    rewrite <- ba_true,(ba_conj_comm _).\n    rewrite <- (ba_neg_disj x) at 1.\n    rewrite <- ba_disj_conj,(ba_disj_comm _ (¬z)),E1.\n    apply ba_neg_disj.\n  Qed.\n\n  Lemma I1 x y z : ¬ ((x∨y)∨z)∧y⩵⊥.\n  Proof. rewrite (ba_disj_comm x y);apply H1. Qed.\n\n  Lemma I2 x y z : ¬ ((x∧y)∧z)∨y⩵⊤.\n  Proof. rewrite (ba_conj_comm x y);apply H2. Qed.\n\n  Lemma J1 x y z : ¬((x∨y)∨z)∧z⩵⊥.\n  Proof. rewrite DMg1,(ba_conj_comm _),(ba_conj_comm (¬ _));apply A2. Qed.\n\n  Lemma J2 x y z : ¬((x∧y)∧z)∨z⩵⊤.\n  Proof. rewrite DMg2,(ba_disj_comm _),(ba_disj_comm (¬ _));apply A1. Qed.\n\n  Lemma K1 x y z : (x∨(y∨z))∨¬((x∨y)∨z)⩵⊤.\n  Proof.\n    repeat rewrite DMg1.\n    repeat rewrite ba_disj_conj.\n    rewrite D1,F1,G1.\n    repeat rewrite ba_true;reflexivity.\n  Qed.\n  \n  Lemma K2 x y z : (x∧(y∧z))∧¬((x∧y)∧z)⩵⊥.\n  Proof.\n    repeat rewrite DMg2.\n    repeat rewrite ba_conj_disj.\n    rewrite D2,F2,G2.\n    repeat rewrite ba_false;reflexivity.\n  Qed.\n  \n  Lemma L1 x y z : (x∨(y∨z))∧¬((x∨y)∨z) ⩵ ⊥.\n  Proof.\n    rewrite (ba_conj_comm _).\n    repeat rewrite ba_conj_disj.\n    rewrite H1,I1,J1.\n    repeat rewrite ba_false;reflexivity.\n  Qed.\n  \n  Lemma L2 x y z : (x∧(y∧z))∨¬((x∧y)∧z) ⩵ ⊤.\n  Proof.\n    rewrite (ba_disj_comm _).\n    repeat rewrite ba_disj_conj.\n    rewrite H2,I2,J2.\n    repeat rewrite ba_true;reflexivity.\n  Qed.\n\n  Lemma Ass1 x y z : x∨(y∨z)⩵(x∨y)∨z.\n  Proof.\n    rewrite <- (DNg ((x∨y)∨z));apply UNg.\n    - rewrite (ba_disj_comm _);apply K1.\n    - rewrite (ba_conj_comm _);apply L1.\n  Qed.\n\n  Lemma Ass2 x y z : x∧(y∧z)⩵(x∧y)∧z.\n  Proof.\n    rewrite <- (DNg ((x∧y)∧z));apply UNg.\n    - rewrite (ba_disj_comm _);apply L2.\n    - rewrite (ba_conj_comm _);apply K2.\n  Qed.\n\n  (** ** Boolean algebra as other structures*)\n  Global Instance BooleanAlgebra_Join_Lattice : @Lattice A eqA conj disj.\n  Proof.\n    split.\n    - apply H.\n    - intros x y z;apply Ass2.\n    - apply ba_conj_comm.\n    - apply H.\n    - intros x y z;apply Ass1.\n    - apply ba_disj_comm.\n    - apply Abs1.\n    - apply Abs2.\n  Qed.\n  \n  Global Instance BooleanAlgebra_Join_Semilattice : Semilattice A eqA disj.\n  Proof.\n    split.\n    - apply H.\n    - apply lat_join_assoc.\n    - apply lat_join_comm.\n    - intros a;apply Idm1.\n  Qed.\n\n  Global Instance BooleanAlgebra_Meet_Semilattice : Semilattice A eqA conj.\n  Proof.\n    split.\n    - apply H.\n    - apply lat_meet_assoc.\n    - apply lat_meet_comm.\n    - intros a;apply Idm2.\n  Qed.\n\n  Global Instance BooleanAlgebra_Meet_Monoid : @Monoid A eqA conj top.\n  Proof.\n    split.\n    - apply H.\n    - apply lat_meet_assoc.\n    - split.\n      + intro a;etransitivity;[apply lat_meet_comm|apply ba_true].\n      + apply ba_true.\n  Qed.\n\n  Global Instance BooleanAlgebra_Join_Monoid : @Monoid A eqA disj bot.\n  Proof.\n    split.\n    - apply H.\n    - apply lat_join_assoc.\n    - split.\n      + intro a;etransitivity;[apply lat_join_comm|apply ba_false].\n      + apply ba_false.\n  Qed.\n\n  Global Instance BooleanAlgebra_Semiring : SemiRing A eqA conj disj top bot.\n  Proof.\n    split.\n    - eapply BooleanAlgebra_Meet_Monoid;eassumption.\n    - eapply BooleanAlgebra_Join_Monoid;eassumption.\n    - apply lat_join_comm.\n    - split.\n      + intros a;rewrite (ba_conj_comm _);apply Bnd2.\n      + intros a;apply Bnd2.\n    - apply ba_conj_disj.\n    - intros x y z;rewrite (ba_conj_comm _),ba_conj_disj.\n      repeat rewrite (ba_conj_comm z);reflexivity.\n  Qed.\n\nEnd booleanAlgebra.\n  \n\n(** * Kleene algebras *)\nSection ka_facts.\n  Context {A : Type} {eqA: relation A}.\n  Context {equivA : @Equivalence A eqA}.\n  \n  Infix \" ⩵ \" := eqA (at level 80).\n  \n  Context {j: Join A}{p: Product A}{z: Zero A}{u:Un A}{s:Star A}.\n  Context {ka: KleeneAlgebra A eqA}.\n\n  Infix \" ≦ \" := (leqA eqA) (at level 80).\n  \n  Global Instance proper_prod_inf : Proper (leqA eqA ==> leqA eqA ==> leqA eqA) prod.\n  Proof.\n    intros e f I e' f' I'.\n    unfold leqA in *.\n    rewrite I' at 1.\n    rewrite semiring_left_distr.\n    rewrite I at 1.\n    rewrite semiring_right_distr.\n    rewrite <- (mon_assoc _ _ _).\n    rewrite <- semiring_left_distr.\n    rewrite <- I'.\n    reflexivity.\n  Qed.\n  \n  Global Instance join_semilattice : Semilattice A eqA join.\n  Proof. split;apply ka. Qed.\n\n  Lemma ka_star_unfold_eq a : a⋆ ⩵ 𝟭 ∪ a · a ⋆.\n  Proof.\n    apply antisymmetry.\n    - etransitivity;[|apply ka_star_left_ind with (a0:=a)].\n      + rewrite (semiring_left_distr _ _ _). \n        rewrite right_unit. \n        apply inf_cup_left.\n      + rewrite (semiring_left_distr _ _ _).\n        rewrite right_unit.\n        apply inf_join_inf.\n        * rewrite <- inf_cup_right.\n          rewrite <- ka_star_unfold.\n          rewrite (semiring_left_distr _ _ _).\n          rewrite <- inf_cup_left.\n          rewrite right_unit.\n          reflexivity.\n        * rewrite <- ka_star_unfold at 2.\n          rewrite <- inf_cup_right.\n          rewrite (semiring_left_distr _ _ _).\n          rewrite <- inf_cup_right.\n          reflexivity.\n    - apply ka_star_unfold.\n  Qed.\n  \n  Lemma ka_star_dup a : a ⋆ · a ⋆ ⩵ a ⋆.\n  Proof.\n    apply antisymmetry.\n    - apply ka_star_left_ind.\n      rewrite ka_star_unfold_eq at 2.\n      apply inf_cup_right.\n    - rewrite ka_star_unfold_eq at 1.\n      apply inf_join_inf.\n      + rewrite ka_star_unfold_eq.\n        rewrite (semiring_left_distr _ _ _).\n        rewrite (semiring_right_distr _ _ _).\n        rewrite <- inf_cup_left.\n        rewrite <- inf_cup_left.\n        rewrite left_unit.\n        reflexivity.\n      + apply proper_prod_inf;[|reflexivity].\n        rewrite ka_star_unfold_eq.\n        rewrite <- inf_cup_right.\n        rewrite ka_star_unfold_eq.\n        rewrite (semiring_left_distr _ _ _).\n        rewrite <- inf_cup_left.\n        rewrite right_unit.\n        reflexivity.\n  Qed.\n\n  Lemma one_inf_star e : 𝟭 ≦ e⋆.\n  Proof. rewrite ka_star_unfold_eq;apply inf_cup_left. Qed.\n\n  Lemma star_incr e : e ≦ e⋆.\n  Proof. rewrite ka_star_unfold_eq, <- one_inf_star,right_unit;apply inf_cup_right. Qed.\n    \n  Global Instance proper_star_inf : Proper (leqA eqA ==> leqA eqA) star.\n  Proof.\n    intros e f I.\n    transitivity (e⋆·𝟭);[rewrite right_unit;reflexivity|].\n    rewrite (one_inf_star f).\n    apply ka_star_left_ind.\n    rewrite I,(star_incr f),ka_star_dup at 1;reflexivity.\n  Qed.\n  \n  Lemma ka_star_star a : a⋆ ⩵ (a ⋆)⋆.\n  Proof.\n    apply antisymmetry.\n    - apply proper_star_inf.\n      rewrite ka_star_unfold_eq.\n      rewrite <- inf_cup_right.\n      rewrite ka_star_unfold_eq.\n      rewrite (semiring_left_distr _ _ _).\n      rewrite right_unit.\n      apply inf_cup_left.\n    - rewrite ka_star_unfold_eq at 1.\n      apply inf_join_inf.\n      + rewrite ka_star_unfold_eq.\n        apply inf_cup_left.\n      + apply ka_star_right_ind.\n        rewrite ka_star_dup.\n        reflexivity.\n  Qed.        \n  \n  Lemma ka_star_unfold_right a : 𝟭 ∪ a⋆ · a ≦ a⋆.\n  Proof.\n    apply inf_join_inf.\n    - rewrite ka_star_unfold_eq.\n      apply inf_cup_left.\n    - rewrite <- ka_star_dup at 2.\n      apply proper_prod_inf.\n      + reflexivity.\n      + rewrite ka_star_unfold_eq,ka_star_unfold_eq.\n        rewrite semiring_left_distr,right_unit.\n        rewrite <- inf_cup_right.\n        apply inf_cup_left.\n  Qed.\n\n  Lemma star_join e f : (e ∪ f)⋆ ⩵ e ⋆ ∪ f⋆·(e·f⋆)⋆.\n  Proof.\n    apply antisymmetry.\n    - transitivity ((e ∪ f) ⋆ · un);[rewrite right_unit;reflexivity|].\n      transitivity ((e ∪ f) ⋆ · (e ⋆ ∪ f ⋆ · (e · f ⋆) ⋆)).\n      + apply proper_prod_inf;[reflexivity|].\n        etransitivity;[|apply inf_cup_left].\n        apply one_inf_star.\n      + apply ka_star_left_ind.\n        rewrite semiring_left_distr.\n        repeat rewrite semiring_right_distr.\n        repeat apply inf_join_inf.\n        * etransitivity;[|apply inf_cup_left].\n          rewrite (star_incr e) at 1.\n          rewrite ka_star_dup;reflexivity.\n        * etransitivity;[|apply inf_cup_right].\n          apply proper_prod_inf;[apply star_incr|].\n          rewrite <- (one_inf_star f),right_unit;reflexivity.\n        * etransitivity;[|apply inf_cup_right].\n          rewrite <- (one_inf_star f) at 3;rewrite left_unit.\n          rewrite <- (ka_star_dup (e·f⋆)) at 2.\n          rewrite <- (star_incr (e·f⋆)) at 2.\n          rewrite (mon_assoc _ _ _).\n          reflexivity.\n        * etransitivity;[|apply inf_cup_right].\n          rewrite (mon_assoc _ _ _).\n          apply proper_prod_inf;[|reflexivity].\n          rewrite (star_incr f) at 1;rewrite ka_star_dup;reflexivity.\n    - apply inf_join_inf.\n      + apply proper_star_inf,inf_cup_left.\n      + rewrite <- (ka_star_dup (e∪f)).\n        apply proper_prod_inf;[apply proper_star_inf,inf_cup_right|].\n        rewrite (ka_star_star (e∪f)).\n        apply proper_star_inf.\n        rewrite <- (ka_star_dup (e∪f)).\n        apply proper_prod_inf;[|apply proper_star_inf,inf_cup_right].\n        rewrite <- star_incr;apply inf_cup_left.\n  Qed.    \n\n  Lemma un_star : un⋆ ⩵ un.\n  Proof.\n    apply antisymmetry.\n    - transitivity (un⋆·un);[rewrite right_unit;reflexivity|].\n      apply ka_star_left_ind;rewrite left_unit;reflexivity.\n    - apply star_incr.\n  Qed.\n\n  Lemma star_switch_side e : e⋆·e ⩵ e· e⋆.\n  Proof.\n    apply antisymmetry.\n    - transitivity (e⋆·e·e⋆).\n      + rewrite <- one_inf_star at 3.\n        rewrite right_unit;reflexivity.\n      + rewrite <- (mon_assoc _ _ _).\n        apply ka_star_left_ind.\n        rewrite (star_incr e) at 2.\n        rewrite ka_star_dup;reflexivity.\n    - transitivity (e⋆·e·e⋆).\n      + rewrite <- one_inf_star at 2.\n        rewrite left_unit;reflexivity.\n      + apply ka_star_right_ind.\n        rewrite (star_incr e) at 2.\n        rewrite ka_star_dup;reflexivity.\n  Qed.\n\n  Definition Σ l := fold_right (fun e f => join e f) zero l.\n\n  Lemma Σ_distr_l e L : e · Σ L ⩵ Σ (map (prod e) L).\n  Proof.\n    induction L;simpl.\n    - apply right_absorbing.\n    - rewrite <- IHL,semiring_left_distr;reflexivity.\n  Qed.\n  \n  Lemma Σ_distr_r e L : Σ L · e ⩵ Σ (map (fun f => f · e) L).\n  Proof.\n    induction L;simpl.\n    - apply left_absorbing.\n    - rewrite <- IHL,semiring_right_distr;reflexivity.\n  Qed.\n\n  Lemma Σ_app L M : Σ L ∪ Σ M ⩵ Σ (L++M).\n  Proof.\n    induction L;simpl;[|rewrite <- IHL].\n    - apply left_unit.\n    - symmetry;apply mon_assoc.\n  Qed.\n      \n  Lemma Σ_incl L M : L ⊆ M -> Σ L ≦ Σ M.\n  Proof.\n    intro I;unfold leqA;rewrite Σ_app;revert M I;induction L;intros M I.\n    - reflexivity.\n    - simpl;rewrite <- IHL by (rewrite <- I;intro;simpl;tauto).\n      assert (Ia : a ∈ M) by (apply I;now left).\n      clear I L IHL.\n      induction M as [|e L].\n      + simpl in *;tauto.\n      + simpl;destruct Ia as [->|Ia];simpl.\n        * rewrite (mon_assoc _ _ _),(ka_idem _);reflexivity.\n        * rewrite IHL at 1 by assumption.\n          rewrite (mon_assoc _ _ _),(semiring_comm e a),(mon_assoc _ _ _);reflexivity.\n  Qed.  \n  \n  Global Instance Σ_equivalent : Proper (@equivalent _ ==> eqA) Σ.\n  Proof.\n    intros l1 l2 E.\n    apply antisymmetry;apply Σ_incl;rewrite E;reflexivity.\n  Qed.\n\n  Lemma Σ_bigger e L : e ∈ L -> e ≦ Σ L.\n  Proof.\n     intro I;transitivity (Σ [e]).\n     - simpl;apply inf_cup_left.\n     - apply Σ_incl;intros ? [<-|F];simpl in *;tauto.\n  Qed.\n  \n  Lemma Σ_bounded e L : (forall f, f ∈ L -> f ≦ e) <-> Σ L ≦ e.\n  Proof.\n    split.\n    - induction L;simpl;intro I.\n      + apply zero_minimal.\n      + rewrite IHL by (intros ? ?;apply I;now right).\n        rewrite (I a) by now left.\n        rewrite (ka_idem e);reflexivity.\n    - intros E f If.\n      rewrite <- E;apply Σ_bigger,If.\n  Qed.\n\n  Lemma ka_star_mid_split e : e⋆·e·e⋆ ≦ e⋆.\n  Proof.\n    etransitivity;[apply proper_prod_inf;[apply proper_prod_inf;\n                                          [reflexivity|apply star_incr]|reflexivity]|].\n    cut ((e ⋆ · e ⋆) · e ⋆ ⩵ e ⋆);[intros ->;reflexivity|].\n    repeat rewrite ka_star_dup;reflexivity.\n  Qed.\n\n  Lemma ka_zero_star :  𝟬 ⋆ ⩵ 𝟭.\n  Proof.\n    apply antisymmetry.\n    - transitivity (𝟬 ⋆ · 𝟭).\n      + rewrite right_unit;reflexivity.\n      + apply ka_star_left_ind.\n        rewrite left_absorbing;apply zero_minimal.\n    - apply one_inf_star.\n  Qed.\n\nEnd ka_facts.\n\n  \n\n", "meta": {"author": "monstrencage", "repo": "BracketAlgebra", "sha": "98eb06e3b55f9156d08a7ed2fc4eb74b97ee7322", "save_path": "github-repos/coq/monstrencage-BracketAlgebra", "path": "github-repos/coq/monstrencage-BracketAlgebra/BracketAlgebra-98eb06e3b55f9156d08a7ed2fc4eb74b97ee7322/algebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830606, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.6659980083000596}}
{"text": "Require Import nat.\nRequire Import list.\nRequire Import dictionary.\nRequire Import state.\nRequire Import ISA.\n\nFixpoint s_execute (e:State) (stack:list nat)(prog:list sinstr) : list nat :=\n  match prog with\n  | []      => stack  (* returns stack as it currently is *)\n  | (i::is) => match i with\n               | SPush n  => s_execute e (n::stack) is\n               | SLoad k  => s_execute e ((e k)::stack) is\n               | SPlus    => match stack with\n                             | []         => s_execute e stack is (* error *)\n                             | [x]        => s_execute e stack is (* error *)\n                             | x::y::st'  => s_execute e ((y+x)::st') is \n                            end\n               | SMinus   => match stack with\n                             | []         => s_execute e stack is (* error *)\n                             | [x]        => s_execute e stack is (* error *)\n                             | x::y::st'  => s_execute e ((y-x)::st') is \n                            end\n               | SMult    => match stack with\n                             | []         => s_execute e stack is (* error *)\n                             | [x]        => s_execute e stack is (* error *)\n                             | x::y::st'  => s_execute e ((y*x)::st') is \n                            end\n                end\n  end.\n\n\nLemma s_execute_app : forall (e:State) (stack:list nat)(p1 p2:list sinstr),\n  s_execute e stack (p1 ++ p2) = s_execute e (s_execute e stack p1) p2. \nProof.\n  intros e stack p1. revert stack. induction p1 as [|i is IH].\n  - reflexivity.\n  - intros stack p2. destruct i.\n    + simpl. rewrite IH. reflexivity.\n    + simpl. rewrite IH. reflexivity.\n    + destruct stack as [|n stack].  \n      { simpl. rewrite IH. reflexivity. } \n      { destruct stack as [|n' stack].\n        { simpl. rewrite IH. reflexivity. }\n        { simpl. rewrite IH. reflexivity. } } \n    + destruct stack as [|n stack].  \n      { simpl. rewrite IH. reflexivity. } \n      { destruct stack as [|n' stack].\n        { simpl. rewrite IH. reflexivity. }\n        { simpl. rewrite IH. reflexivity. } } \n    + destruct stack as [|n stack].  \n      { simpl. rewrite IH. reflexivity. } \n      { destruct stack as [|n' stack].\n        { simpl. rewrite IH. reflexivity. }\n        { simpl. rewrite IH. reflexivity. } } \nQed.\n          \n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/sf/execute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6659163594573131}}
{"text": "Require Import Strings.String.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.ZArith.BinInt.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\nSection bloomfilter.\n\nVariable Index:Type.\nVariable index_beq: Index -> Index -> bool.\n(*Parameter Index_eq: forall (i j:Index), {i=j} + {i<>j}.*)\n\nVariable index_refl: forall i, index_beq i i = true.\n\nVariable Hash0: Z -> Index.\nVariable Hash1: Z -> Index.\nVariable Hash2: Z -> Index.\n\nDefinition Filter:= Index -> bool.\n\nDefinition upd (F:Filter) (i:Index) (b:bool): Filter :=\n  fun j => if index_beq i j then b else F j.\n\nDefinition empty:Filter := fun _ => false.\n\nDefinition get (F:Filter) (i:Index): bool := F i.\n\nDefinition add0 (F:Filter) (z:Z) :=\n   upd F (Hash0 z) true.\n\nDefinition add1 (F:Filter) (z:Z) :=\n   upd F (Hash1 z) true.\n\nDefinition add2 (F:Filter) (z:Z) :=\n   upd F (Hash2 z) true.\n\nDefinition add (F:Filter * Filter * Filter) (z:Z) :=\nmatch F with (F0, F1, F2) =>\n  (add0 F0 z, add1 F1 z, add2 F2 z)\nend.\n\nDefinition addm (F:Filter * Filter * Filter) (zs:list Z):=\nList.fold_left add zs F.\n\nDefinition query (F:Filter * Filter * Filter) (z:Z) : bool :=\nmatch F with (F0, F1, F2) =>\n  get F0 (Hash0 z) && get F1 (Hash1 z) && get F2 (Hash2 z)\nend.\n\nLemma bf_add_query_true z F: query (add F z) z = true.\ndestruct F as [[F0 F1] F2]. simpl. unfold get, add0, add1, add2, upd.\nrewrite ! index_refl. trivial. Qed.\n\nLemma eqindexP : forall n m, reflect (index_beq n m = true) (index_beq n m).\nProof.\n  intros n m. apply iff_reflect. reflexivity.\nQed.\n\nLemma add0_comm x y F: add0 (add0 F x) y = add0 (add0 F y) x.\nProof.\n  unfold add0, upd.\n  apply functional_extensionality.\n  intros.\n  destruct (eqindexP (Hash0 x) x0) as [H1|H2];\n  destruct (eqindexP (Hash0 y) x0) as [H3|H4];\n  reflexivity.\nQed.\n\nLemma add1_comm x y F: add1 (add1 F x) y = add1 (add1 F y) x.\nProof.\n  unfold add1, upd.\n  apply functional_extensionality.\n  intros.\n  destruct (eqindexP (Hash1 x) x0) as [H1|H2];\n  destruct (eqindexP (Hash1 y) x0) as [H3|H4];\n  reflexivity.\nQed.\n\nLemma add2_comm x y F: add2 (add2 F x) y = add2 (add2 F y) x.\nProof.\n  unfold add2, upd.\n  apply functional_extensionality.\n  intros.\n  destruct (eqindexP (Hash2 x) x0) as [H1|H2];\n  destruct (eqindexP (Hash2 y) x0) as [H3|H4];\n  reflexivity.\nQed.\n\nLemma add_comm x y F: add (add F x) y = add (add F y) x.\nProof.\n  destruct F as [[F0 F1] F2]. simpl.\n  apply pair_equal_spec. split.\n  apply pair_equal_spec. split.\n  apply add0_comm. apply add1_comm. apply add2_comm.\nQed.\n\nLemma addm_add_comm : forall x ys F, addm (add F x) ys = add (addm F ys) x.\nProof.\n  intros. generalize F.\n  induction ys as [|hd tl IH]; unfold addm.\n  - intros. reflexivity.\n  - intros. unfold addm in IH. unfold fold_left in *. rewrite add_comm.\n    rewrite IH. reflexivity.\nQed.\n\nTheorem BFNoFalseNegative z zs F: query (addm (add F z) zs) z  = true.\nProof.\n  rewrite addm_add_comm. apply bf_add_query_true.\nQed.\n\nEnd bloomfilter.\n", "meta": {"author": "verified-network-toolchain", "repo": "VerifiableP4", "sha": "87afa7bef7d88da2e9a642e37c0ddb2412b57509", "save_path": "github-repos/coq/verified-network-toolchain-VerifiableP4", "path": "github-repos/coq/verified-network-toolchain-VerifiableP4/VerifiableP4-87afa7bef7d88da2e9a642e37c0ddb2412b57509/examples/bloomfilter/bloomfilter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6659163527095291}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type :=  Nil : lst | Cons : natural -> lst -> lst .\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint 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. lfind. Admitted.\n              \n\n", "meta": {"author": "ana-brendel", "repo": "coq-benchmarks", "sha": "78b9ca2993b0fb579d814ed17e63c6859e79681c", "save_path": "github-repos/coq/ana-brendel-coq-benchmarks", "path": "github-repos/coq/ana-brendel-coq-benchmarks/coq-benchmarks-78b9ca2993b0fb579d814ed17e63c6859e79681c/testing_results_initial/manual_testing/results/test178_goal80/lfind_goal80.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6659163527095291}}
{"text": "(******************************************************************************)\n(* Chapter 1.4: Functors                                                      *)\n(******************************************************************************)\n(* @suharahiromichi *)\n\n(*\n(0)\n同じディレクトリにある Categories.v を使う。\n\n(1) ベースライン\nhttp://www.megacz.com/berkeley/coq-categories/\nこれをもとに改変。Instance ... Proper を使うようにした。\n *)\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import Notations.\nRequire Import Morphisms.\nRequire Import Categories.\n\nClass Functor `(C1 : Category) `(C2 : Category) (fobj : C1 -> C2) :=\n  {\n    functor_fobj := fobj;\n    fmor                : forall {a b : C1}, a ~> b -> (fobj a) ~> (fobj b);\n    fmor_respects       : forall {a b : C1} {f f' : a ~> b},\n                            f === f' -> fmor f === fmor f';\n    fmor_preserves_id   : forall {a : C1}, @fmor a a id === id;\n(* forall a, fmor (id a) === id (fobj a); *)\n    fmor_preserves_comp : forall {a b c : C1} {f : a ~> b} {g : b ~> c},\n                            (fmor g) \\\\o (fmor f) === fmor (g \\\\o f)\n  }.\nCoercion functor_fobj : Functor >-> Funclass.\n\nCheck functor_fobj : ∀Obj Hom C1 Obj0 Hom0 C2 fobj _ _, C2.\n(* ,の前の最後の「_」は、普通の引数で、C1（の対象） *)\nCheck @fmor        : ∀Obj Hom C1 Obj0 Hom0 C2 fobj _ a b _, fobj a ~> fobj b.\n(* ,の前の最後の「_」は、普通の引数で、a ~> b の型を持つ。 *)\n\n(* fobj と fmor の意味：\nカテゴリ1 C1 = (Obj, Hom)\nカテゴリ2 C2 = (Obj0, Hom0)\n\nfobj : C1 -> C2、カテゴリC1（の対象）からC2（の対象）への写像\nファンクタからのコアーションが効く。\n\nfmor : (a ~> b) -> (fobj a ~> fobj b)\nカテゴリC1（の射）からC2（の射）への写像、\nただし fobj が与えられないと、意味をなさないことに注意！\n *)\n\nCheck @fmor : ∀Obj Hom C1 Obj0 Hom0 C2 fobj _ a b _, fobj a ~> fobj b.\nCheck fmor : _ ~> _ -> _ ~> _.\nAbout fmor.                       (* Set Implicit Arguments の所為で、\n                                     fobj は implicit になっている。 *)\nArguments fmor {Obj Hom Obj0 Hom0 C1 C2} fobj {_ a b} _ : rename.\nCheck fmor.                          (* fobj を指定するようにする。 *)\n\nNotation \"F \\ f\" := (fmor F f) : category_scope.\nOpen Scope category_scope.\n\n(* parametric_morphism_fmor *)\n(* これの証明に、Classの公理に Proper (eqv ==> eqv) fmor が必要なわけではない。 *)\n(* また、(@fmor _ _ .... a b) は fmor と略せない。  *)\nInstance functor_fmor_Proper `(C1 : Category) `(C2 : Category)\n         (Fobj : C1 -> C2) (F : Functor Fobj) (a b : C1) :\n  Proper (@eqv (a ~> b) ==> @eqv (Fobj a ~> Fobj b)) (@fmor _ _ _ _ _ _ _ _ a b).\nProof.\n  move=> x y.                               (* これが肝 *)\n  Check (@fmor_respects _ _ C1 _ _ C2 Fobj F a b x y).\n  by apply (@fmor_respects _ _ C1 _ _ C2 Fobj F a b x y).\nQed.\n\n(* 恒等関手 *)\n(* the identity functor *)\nProgram Instance functor_id `(C : Category) : Functor (fun (x : C) => x) :=\n  {|\n    fmor := fun (a b : C) (f : a ~> b) => f\n  |}.\nObligation 2.                               (* id === id *)\nProof.\n  Check (fun (x : C) => C).                 (* カテゴリC(の対象)から、カテゴリC(の対象)の写像 *)\n  Check (fun (a b : C) (f : a ~> b) => f).  (* カテゴリC(の射)から、カテゴリC(の射)の写像 *)\n  reflexivity.                              (* fmor_preserves_id *)\nDefined.\nObligation 3.                               (* g \\\\o f === g \\\\o f *)\nProof.\n  reflexivity.                              (* fmor_preserves_comp *)\nDefined.\n\n(* 定数関手 *)\n(* the constant functor *)\nProgram Instance functor_const `(C : Category) `{D : Category} (d : D) :\n  Functor (fun (x : C) => d) :=\n  {|\n    fmor := fun (a b : C) (f : a ~> b) => id\n  |}.\nObligation 1.\nProof.\n  Check (fun (x : C) => d). (* カテゴリC(の対象)から、カテゴリD(の対象)の写像 *)\n  Check (fun (a b : C) (f : a ~> b) => id). (* カテゴリC(の射)から、カテゴリD(の射)の写像 *)\n  reflexivity.\nDefined.\nObligation 2.\nProof.\n  reflexivity.\nDefined.\nObligation 3.\nProof.\n  by apply left_identity.\nDefined.\n\nGeneralizable Variables Fobj Gobj.\n\nLocate \"_ ○ _\".                            (* \"f ○ g\" := fun x => f (g x) *)\nLocate \"_ \\o _\".                            (* SSReflect では、こっちを使う。 *)\nLocate \"_ \\\\o _\".                           (* \"f \\\\o g\" := comp f g *)\n\n(* 関手の合成 *)\n(* functors compose *)\nProgram Instance functor_comp `(C1 : Category) `(C2 : Category) `(C3 : Category)\n        `(F : @Functor _ _ C1 _ _ C2 Fobj) `(G : @Functor _ _ C2 _ _ C3 Gobj) :\n  Functor (Gobj \\o Fobj) :=\n  {|\n    fmor := fun a b m => G \\ (F \\ m)\n  |}.\nObligation 1.\nProof.\n  Check F : C1 -> C2.              (* C1の対象からC2の対象への写像  *)\n  Check Fobj : C1 -> C2.           (* C1の対象からC2の対象への写像  *)\n  Check fmor F.                    (* C1の射からC2の射への写像 *)\n  Check G : C2 -> C3.              (* C2の対象からC3の対象への写像  *)\n  Check Gobj : C2 -> C3.           (* C2の対象からC3の対象への写像  *)\n  Check fmor G.                    (* C2の射からC3の射への写像 *)\n  rewrite H.\n  reflexivity.\nDefined.\nObligation 2.\nProof.\n  repeat setoid_rewrite fmor_preserves_id.\n  reflexivity.\nDefined.\nObligation 3.\nProof.\n  repeat setoid_rewrite fmor_preserves_comp.\n  reflexivity.\nDefined.\n\nNotation \"f >>>> g\" := (@functor_comp _ _ _ _ _ _ _ _ _ _ f _ g)   : category_scope.\nOpen Scope category_scope.\n\nGeneralizable Variables Xobj Yobj Zobj a b.\n\n(*\nLemma functor_comp_assoc `{C : Category} `{D : Category} `{E : Category} `{F : Category}\n      `(F1 : @Functor _ _ C _ _ D Xobj)\n      `(F2 : @Functor _ _ D _ _ E Yobj)\n      `(F3 : @Functor _ _ E _ _ F Zobj) :\n  forall (a b : C) (f : a ~> b),\n    ((F1 >>>> F2) >>>> F3) \\ f === (F1 >>>> (F2 >>>> F3)) \\ f.\n      \nLemma functor_comp_assoc `{C':Category}`{D:Category}`{E:Category}`{F:Category}\n  {F1obj}(F1:Functor C' D F1obj)\n  {F2obj}(F2:Functor D E F2obj)\n  {F3obj}(F3:Functor E F F3obj)\n  `(f:a~>b) :\n  ((F1 >>>> F2) >>>> F3) \\ f ~~ (F1 >>>> (F2 >>>> F3)) \\ f.\n  intros; simpl.\n  reflexivity.\n  Qed.\n*)\n\n(* this is like JMEq, but for the particular case of ~~; note it does not require any axioms! *)\n\nInductive heq_morphisms `{C : Category} {a b : C} (f : a ~> b) :\n  forall {a' b' : C}, a' ~> b' -> Prop :=\n| heq_morphisms_intro {f' : a ~> b} :\n    eqv f f' -> @heq_morphisms _ _ C a b f a b f'.\n\nDefinition heq_morphisms_refl `{C : Category} a b f :\n  @heq_morphisms _ _ C a b f a  b  f.\nProof.\n  apply heq_morphisms_intro.\n  reflexivity.\nQed.\nCheck heq_morphisms_refl.\nCheck @heq_morphisms_refl :\n  forall {Obj Hom C} {a b : Obj} {f : a ~> b},\n    heq_morphisms f f.\n\nDefinition heq_morphisms_symm `{C : Category} a b f a' b' f' :\n  @heq_morphisms _ _ C a b f a' b' f' -> @heq_morphisms _ _ C a' b' f' a b f.\nProof.\n  case=> f'' H.\n  apply: heq_morphisms_intro.\n  rewrite H.\n  reflexivity.\nQed.\nCheck heq_morphisms_symm.\nCheck @heq_morphisms_symm :\n  forall {Obj Hom C}\n         {a b : Obj} {f : a ~> b}\n         {a' b' : Obj} {f' : a' ~> b'},\n    heq_morphisms f f' -> heq_morphisms f' f.\n\nDefinition heq_morphisms_tran `{C : Category} a b f a' b' f' a'' b'' f'' :\n  @heq_morphisms _ _ C a b f a' b' f' ->\n  @heq_morphisms _ _ C a' b' f' a'' b'' f'' ->\n  @heq_morphisms _ _ C a b f a'' b'' f''.\nProof.\n  case=> f''' H.\n  case=> f'''' H'.\n  apply: heq_morphisms_intro.\n  rewrite -H'.\n  by apply: H.\nQed.\nCheck heq_morphisms_tran.\nCheck @heq_morphisms_tran :\n  forall {Obj Hom C}\n         {a b : Obj} {f : a ~> b}\n         {a' b' : Obj} {f' : a' ~> b'}\n         {a'' b'' : Obj} {f'' : a'' ~> b''},\n    heq_morphisms f f' -> heq_morphisms f' f'' -> heq_morphisms f f''.\n\n(*\nAdd Parametric Relation  (Ob:Type)(Hom:Ob->Ob->Type)(C:Category Ob Hom)(a b:Ob) : (hom a b) (eqv a b)\n  reflexivity proved by  heq_morphisms_refl\n  symmetry proved by     heq_morphisms_symm\n  transitivity proved by heq_morphisms_tran\n  as parametric_relation_heq_morphisms.\n  Add Parametric Morphism `(c:Category Ob Hom)(a b c:Ob) : (comp a b c)\n  with signature (eqv _ _ ==> eqv _ _ ==> eqv _ _) as parametric_morphism_comp.\n  auto.\n  Defined.\n*)\n\nImplicit Arguments heq_morphisms [ Obj Hom C a b a' b' ].\nHint Constructors heq_morphisms.\n\nDefinition EqualFunctors `{C1 : Category} `{C2 : Category}\n           {F1obj} (F1 : Functor F1obj)\n           {F2obj} (F2 : Functor F2obj) :=\n  forall a b (f f' : hom a b),\n    f === f' -> heq_morphisms (fmor F1 f) (fmor F2 f').\n(* f f' : a~~{C1}~~>b *)\n\nNotation \"f ~~~~ g\" := (EqualFunctors f g) (at level 45).\n\nClass IsomorphicCategories `(C : Category) `(D : Category) :=\n  {\n    ic_f_obj    : C -> D;\n    ic_g_obj    : D -> C;\n    ic_f        : Functor ic_f_obj;\n    ic_g        : Functor ic_g_obj;\n    \n    ic_forward  : ic_f >>>> ic_g ~~~~ functor_id C;\n    ic_backward : ic_g >>>> ic_f ~~~~ functor_id D\n  }.\n\n(* this causes Coq to die: *)\n(* Definition IsomorphicCategories := Isomorphic (CategoryOfCategories). *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/monad/Functors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6658812772003637}}
{"text": "Require Export D.\n\n\n\n(** **** Problem #14 : 3 stars, optional (apply_with_exercise)  \n    Hint: Use the [apply ... with ...] tactic. *)\n\nCheck trans_lt.\n\nExample trans_eq_exercise : forall (n m o p : nat),\n     (minustwo o) < m ->\n     (n + p) < (minustwo o) ->\n     (n + p) < m. \nProof.\n  intros.  apply trans_lt with (m:=minustwo o). apply H0. apply H.\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/P15.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6658812626837733}}
{"text": "(***************************************************************************)\n(*   This is part of FA_3rdCalculus, it is distributed under the terms     *)\n(*         of the GNU Lesser General Public License version 3              *)\n(*                (see file LICENSE for more details)                      *)\n(*                                                                         *)\n(*            Copyright 2020-2022: Yaoshun Fu and Wensheng Yu.             *)\n(***************************************************************************)\n\nRequire Export UnD.\n\nFixpoint N_uni_derivative F f a b n :=\n  match n with\n  | 1 => uni_derivative F f a b\n  | p` => ∃ f1, uni_derivative F f1 a b /\\ N_uni_derivative f1 f a b p\n  end.\n\nDefinition N_uni_derivability F a b n := ∃ f, N_uni_derivative F f a b n.\n\nFact NderNec : ∀ {F f a b n}, N_uni_derivative F f a b n` -> \n  ∃ f1, N_uni_derivative F f1 a b n /\\ uni_derivative f1 f a b.\nProof.\n  intros. generalize dependent F; induction n; intros; \n  destruct H as [f1 [H]]; [eauto|]. destruct (IHn _ H0) as [f2 [H1]].\n  exists f2. split; auto. red; eauto.\nQed.\n\nFact NderSuf : ∀ {F f a b n}, \n  (∃ f1, N_uni_derivative F f1 a b n /\\ uni_derivative f1 f a b) ->\n  N_uni_derivative F f a b n`.\nProof.\n  intros. destruct H as [f0 [H]]. generalize dependent F. induction n; intros.\n  - exists f0; auto.\n  - destruct H as [f1 [H]]. pose proof (IHn _ H1). exists f1. auto.\nQed.\n\nFact Nderf : ∀ {F f1 f2 a b n}, N_uni_derivative F f1 a b n ->\n  (∀ x, x ∈ [a|b] -> f1 x = f2 x) -> N_uni_derivative F f2 a b n.\nProof.\n  intros. generalize dependent F. induction n; intros.\n  - eapply derf; eauto.\n  - destruct H as [f3 [H]]. simpl. eauto.\nQed.\n\nFact NderF : ∀ {F1 F2 f a b n}, N_uni_derivative F1 f a b n ->\n  (∀ x, x ∈ [a|b] -> F1 x = F2 x) -> N_uni_derivative F2 f a b n.\nProof.\n  intros. generalize dependent f. induction n; intros.\n  - simpl in *. eapply derF; eauto.\n  - destruct H as [f3 [H]]. exists f3. split; auto.\n    eapply derF; eauto.\nQed.\n\nFact NderFf : ∀ {F1 F2 f1 f2 a b n}, \n  N_uni_derivative F1 f1 a b n -> (∀ x, x ∈ [a|b] -> F1 x = F2 x) -> \n  (∀ x, x ∈ [a|b] -> f1 x = f2 x) -> N_uni_derivative F2 f2 a b n.\nProof.\n  intros. eapply NderF in H; eauto. eapply Nderf in H; eauto.\nQed.\n\nFact uniNder : ∀ {F f1 f2 a b k}, \n   N_uni_derivative F f1 a b k -> N_uni_derivative F f2 a b k -> \n   ∀ x, x ∈ [a|b] -> f1 x = f2 x.\nProof.\n  intros. generalize dependent F. induction k; intros. \n  - eapply unider; eauto.\n  - destruct H as [f3 [H]], H0 as [f4 [H0]].\n    eapply IHk; eauto. pose proof (unider H0 H). eapply NderF; eauto.\nQed.\n\nFact NderOrdPl : ∀ {F f1 f2 a b n k}, N_uni_derivative F f1 a b n ->\n  N_uni_derivative f1 f2 a b k -> N_uni_derivative F f2 a b (Plus_N n k).\nProof.\n  intros. generalize dependent F; generalize dependent f1; \n  generalize dependent f2; induction k; intros; apply NderSuf; [eauto|].\n  destruct (NderNec H0) as [f3 [H1]]. pose proof (IHk _ _ H1 _ H). eauto.\nQed.\n\nFact NderOrdMi : ∀ {F f1 f2 a b n k}, N_uni_derivative F f1 a b n ->\n  N_uni_derivative F f2 a b (Plus_N n k) -> N_uni_derivative f1 f2 a b k.\nProof.\n  intros. generalize dependent F; generalize dependent f1; \n  generalize dependent f2; induction k; intros.\n  - destruct (NderNec H0) as [f3 [H1]]. apply (derF H2 (uniNder H1 H)).\n  - Simpl_Nin H0. destruct (NderNec H0) as [f3 [H1]].\n    pose proof (IHk _ _ _ H H1). apply NderSuf; eauto.\nQed.\n\nFact NderOP1 : ∀ {F f1 f2 a b n}, N_uni_derivative F f1 a b n ->\n  uni_derivative f1 f2 a b -> N_uni_derivative F f2 a b n`.\nProof. intros. rewrite <- NPl_1. eapply NderOrdPl; eauto. Qed.\n\nFact NderOM1 : ∀ {F f1 f2 a b n}, N_uni_derivative F f1 a b n -> \n  N_uni_derivative F f2 a b n` -> uni_derivative f1 f2 a b.\nProof. intros. rewrite <- NPl_1 in H0. apply (NderOrdMi H H0). Qed.\n\nFact Nder_lt : ∀ {F a b k}, N_uni_derivability F a b k -> a < b.\nProof.\n  intros. destruct H as [f H]. generalize dependent F. induction k; intros.\n  - eapply der_lt; eauto. - destruct H, H; eauto.\nQed.\n\nFact Nderin : ∀ {F f a b c n}, c ∈ [a|b] -> c < b ->\n  N_uni_derivative F f a b n -> N_uni_derivative F f c b n.\nProof.\n  intros. pose proof (ccir H).\n  generalize dependent F; induction n; intros.\n  - eapply dersub; eauto.\n  - destruct H1 as [f1 [H1]]. exists f1; split; auto.\n    eapply dersub; eauto.\nQed.\n\nFact Ndervety : ∀ {F f a b n}, \n  N_uni_derivative F f a b n -> N_uni_derivability F a b n.\nProof.\n  intros. red; eauto.\nQed.\n\nFact Nderpred : ∀ {F a b n},\n  N_uni_derivability F a b n` -> N_uni_derivability F a b n.\nProof.\n  intros. generalize dependent F. induction n; intros.\n  - destruct H as [f [f1 [H]]]. red; eauto.\n  - destruct H as [f [f1 [H]]]. apply Ndervety in H0.\n    destruct (IHn _ H0) as [f2 H1]. red; exists f2. red; eauto.\nQed.\n\nFact Nderltn : ∀ {F a b n k}, ILT_N k n -> \n  N_uni_derivability F a b n -> N_uni_derivability F a b k.\nProof.\n  intros. induction n; [N1F H|]. destruct (Theorem26 _ _ H).\n  - apply Nderpred in H0; auto.\n  - subst k. apply Nderpred; auto.\nQed.\n\nFact Nderlen : ∀ {F a b n m},  ILE_N m n -> \n  N_uni_derivability F a b n -> N_uni_derivability F a b m.\nProof.\n  intros. destruct H. - eapply Nderltn; eauto. - subst m; auto.\nQed.\n\nAxiom cid : ∀ {A :Type} {P :A -> Prop}, (∃ x, P x) -> { x :A | P x }.\n\nDefinition Getele {A :Type} {P :A -> Prop} (Q :∃ x, P x) := proj1_sig (cid Q).\n\nDefinition n_th {F a b n} (H :N_uni_derivability F a b n) \n  := Getele H.\n\nDefinition p_th {F a b n} (H :N_uni_derivability F a b n`) \n  := Getele (Nderpred H).\n\nDefinition k_th {F a b n} k (H :ILT_N k n) \n  (H0 :N_uni_derivability F a b n) := Getele (Nderltn H H0).\n\nDefinition m_th {F a b n} k (H :ILE_N k n) \n  (H0 :N_uni_derivability F a b n) := Getele (Nderlen H H0).\n\nLtac mdg1 f := unfold m_th, Getele; \n  destruct cid as [f ]; simpl proj1_sig.\nLtac mdh1 f H := unfold m_th, Getele in H; \n  destruct cid as [f ]; simpl proj1_sig in H.\nLtac kdg1 f := unfold k_th, Getele; \n  destruct cid as [f ]; simpl proj1_sig.\nLtac kdg2 f l f1 := unfold k_th, Getele; \n  destruct (cid l) as [f ], cid as [f1]; simpl proj1_sig.\nLtac kdh1 f H := unfold k_th, Getele in H; \n  destruct cid as [f ]; simpl proj1_sig in H.\nLtac ndg1 f := unfold n_th, Getele; \n  destruct cid as [f ]; simpl proj1_sig.\nLtac ndh1 f H := unfold n_th, Getele in H; \n  destruct cid as [f ]; simpl proj1_sig in H.\nLtac ndh2 f H H0 := unfold n_th, Getele in H, H0; \n  destruct cid as [f ]; simpl proj1_sig in H, H0.\nLtac ndg2 f l f1 := unfold n_th, Getele; \n  destruct (cid l) as [f ], cid as [f1]; simpl proj1_sig.\nLtac pdg1 f := unfold p_th, Getele; \n  destruct cid as [f ]; simpl proj1_sig.\nLtac pdg2 f l f1 := unfold p_th, Getele; \n  destruct (cid l) as [f ], cid as [f1]; simpl proj1_sig.\n\nFact NderCut : ∀ {F a b n} k l1 (l :N_uni_derivability F a b n), \n  N_uni_derivability (k_th k l1 l) a b (Minus_N n k l1).\nProof.\n  intros. generalize dependent F. induction n; intros; [N1F l1|].\n  destruct (Theorem26 _ _ l1).\n  - inversion l as [f]. destruct (NderNec H0) as [f0 [H1]].\n    pose proof (IHn H _ (Ndervety H1)). kdg1 f1. kdh1 f2 H3.\n    rewrite (NMi7 _ H). destruct H3 as [f3]. exists f. apply NderSuf.\n    exists f3. pose proof (NderOrdPl n1 H3). Simpl_Nin H4.\n    apply @NderF with (F2:=f1) in H3; [|eapply uniNder; eauto].\n    apply @derF with (F2:=f3) in H2; [|eapply uniNder; eauto]. auto.\n  - subst k. Simpl_N. kdg1 f. inversion l as [f1].\n    pose proof (NderOM1 n0 H). red; eauto.\nQed.\n\nFact NderfMu : ∀ {F f a b c n},\n  N_uni_derivative F f a b n ->\n  N_uni_derivative (mult_fun c F) (mult_fun c f) a b n.\nProof.\n  intros. generalize dependent F; induction n; intros.\n  - simpl in *. apply derfMu; auto.\n  - destruct H as [f1 [H]].\n    exists(mult_fun c f1). split; auto. apply derfMu; auto.\nQed.\n\nFact NderFPl : ∀ {F f G g a b n},\n  N_uni_derivative F f a b n -> N_uni_derivative G g a b n -> \n  N_uni_derivative (Plus_Fun F G) (Plus_Fun f g) a b n.\nProof.\n  intros. generalize dependent F; generalize dependent G.\n  induction n; intros.\n  - simpl in *. apply derFPl; auto.\n  - destruct H as [f1 [H]], H0 as [g1 [H0]].\n    exists(Plus_Fun f1 g1). split; auto. apply derFPl; auto.\nQed.\n\nFact NderFMi : ∀ {F f G g a b n},\n  N_uni_derivative F f a b n -> N_uni_derivative G g a b n -> \n  N_uni_derivative (Minus_Fun F G) (Minus_Fun f g) a b n.\nProof.\n  intros. generalize dependent F; generalize dependent G.\n  induction n; intros.\n  - simpl in *. apply derFMi; auto.\n  - destruct H as [f1 [H]], H0 as [g1 [H0]].\n    exists(Minus_Fun f1 g1). split; auto. apply derFMi; auto.\nQed.\n\nFact Nderf_mi : ∀ {F f a b n}, N_uni_derivative F f a b n ->\n  N_uni_derivative (λ x, F(-x)) (λ x, (-(1))^n · f(-x)) (-b) (-a) n.\nProof.\n  intros. generalize dependent f. induction n; intros.\n  - unfold N_uni_derivative in *. unfold Pow. apply derf_mi in H.\n    apply @derf with (f1:=(λ x, -f(-x))); intros; Simpl_R.\n  - pose proof (Nderpred (Ndervety H)).\n    destruct H0 as [f1 H0]. pose proof (IHn _ H0).\n    pose proof (NderOM1 H0 H). apply derf_mi in H2.\n    apply derfMu with (c:=(-(1))^n)  in H2. unfold mult_fun in H2.\n    eapply NderOP1; eauto. apply (derf H2); intros.\n    rewrite PowS, Theorem199; Simpl_R.\nQed.\n\n(*--------------------------------------*)\n\nFact dermxc : ∀ {a b} c m, a < b -> uni_derivative (λ x,m·(x-c)) (λ _,m) a b.\nProof.\n  intros. pattern m at 2. rewrite <- Theorem195. apply derfMu.\n  pose proof (derFMi (derCx 1 H) (derC c H)).\n  apply (derF H0); intros; unfold Minus_Fun; Simpl_R.\nQed.\n\nFact derpow1 : ∀ {a b} c n, a < b ->\n  uni_derivative (λ x, (x-c)^n`)(λ x, n`·(x-c)^n) a b.\nProof.\n  intros. pose proof (dermxc c 1 H). induction n.\n  - pose proof (derFMu H0 H0). cbv beta in H1.\n    apply (derFf H1); unfold Mult_Fun; intros; Simpl_R. rewrite R_T2; auto.\n  - pose proof (derFMu IHn H0). cbv beta in H1.\n    apply (derFf H1); unfold Mult_Fun; intros; Simpl_R.\n    rewrite <- (RN3 (n`)), Theorem201', Theorem199; Simpl_R.\nQed.\n\nFact derrdf1 : ∀ {a b} c n z, a < b ->\n  uni_derivative (λ x, (z·Rdifa ((x-c)^n`) n`))\n  (λ x, (z·Rdifa ((x-c)^n) n)) a b.\nProof.\n  intros. apply derfMu. pose proof (derpow1 c n H).\n  pose proof (derfMu (Rdifa 1 n`) H0). unfold mult_fun in H1.\n  apply (derFf H1); intros; [|unfold Rdifa].\n  - rewrite Theorem194, rdft; Simpl_R.\n  - apply eqTi_R with (z:=factorial n); [apply facun0|Simpl_R].\n    rewrite Theorem194, <- Theorem199, Di_Rt.\n    rewrite <- Theorem199, (Theorem194 _ n`), Di_Rt; Simpl_R.\nQed.\n\nFact Nderrdf1 : ∀ {a b} c z n k l, a < b ->\n  N_uni_derivative (λ x, (z·Rdifa ((x-c)^n) n))\n  (λ x, (z·Rdifa ((x-c)^(Minus_N n k l)) (Minus_N n k l))) a b k.\nProof.\n  intros. pose proof (@derrdf1 a b c).\n  generalize dependent n. induction k; intros.\n  - simpl. pose proof (H0 (Minus_N n 1 l) z H). Simpl_Nin H1.\n  - set (l1:=(N1P' l)). assert (IGT_N (Minus_N n 1 l1) k).\n    { apply Theorem20_1 with (z:=1); Simpl_N. }\n    assert (Minus_N n k` l = Minus_N (Minus_N n 1 l1) k H1).\n    { apply Theorem20_2 with (z:=k`); Simpl_N. } rewrite H2.\n    generalize (IHk _ H1)(Theorem15 _ _ _ (Nlt_S_ k) l); intros.\n    pose proof (derrdf1 c (Minus_N n 1 l1) z H). Simpl_Nin H5. red; eauto.\nQed.\n\nFact Nderrdf2 : ∀ {a b} c z n, a < b ->\n  N_uni_derivative (λ x, (z·Rdifa ((x-c)^n) n)) (λ x, z) a b n.\nProof.\n  intros. induction n.\n  - simpl. pose proof (dermxc c z H).\n    eapply derF; eauto. intros. rewrite rdf_1; auto.\n  - pose proof (derrdf1 c n z H). red; eauto.\nQed.\n", "meta": {"author": "coderfys", "repo": "Analysis", "sha": "1610987e019c90a08db4b788564fb0c2c91eebed", "save_path": "github-repos/coq/coderfys-Analysis", "path": "github-repos/coq/coderfys-Analysis/Analysis-1610987e019c90a08db4b788564fb0c2c91eebed/Calculus_without_limt/HighDer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6658812588022851}}
{"text": "\n\nTheorem ExF003_1 {X  :Type} (P : X -> Prop) (Q : X -> X) (a : X): (forall x, P x -> P (Q x)) /\\ P a -> P (Q (Q a)).\nProof.\n  intros.\n  destruct H.\n  assert (P a -> P (Q a)).\n  + specialize (H a).\n    exact H.\n  + pose proof (H (Q a)) as bla.\n    apply bla.\n    apply H1.\n    exact H0.\nQed.\n\n\nTheorem ExF003_2 {X :Type} (P : X -> Prop) (Q : X -> X) (a : X): (forall x, P x -> P (Q x)) /\\ P a -> P (Q (Q a)).\nProof.\n  intros.\n  destruct H.\n  apply H.\n  apply H.\n  assumption.\nQed.\n\n", "meta": {"author": "SvenWille", "repo": "CoqLogicExercises", "sha": "b4c1aea30abb95dc7ba81fa42ccb914d534d65e5", "save_path": "github-repos/coq/SvenWille-CoqLogicExercises", "path": "github-repos/coq/SvenWille-CoqLogicExercises/CoqLogicExercises-b4c1aea30abb95dc7ba81fa42ccb914d534d65e5/src/FOL/ExF003.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6658812549207961}}
{"text": "Require Export Tactics.\n\n(** Take the minimum of two things which might be [nat]s. *)\nDefinition option_f {A} (f : A -> A -> A) : option A -> option A -> option A\n  := fun a b => match a, b with\n                  | None, _ => b\n                  | _, None => a\n                  | Some a, Some b => Some (f a b)\n                end.\n\n(** The distance between two points is the maximum of the two\n    differences; in Coq, we have that [a - b = 0] if [b ≥ a]. *)\nDefinition abs_minus (x y : nat) :=\n  if le_dec x y then y - x else x - y.\n\nNotation \"∥' x -- y '∥\" := (abs_minus x y) : nat_scope.\n\nDelimit Scope dec_scope with dec.\nInfix \"<=\" := le_lt_dec : dec_scope.\nInfix \"≤\" := le_lt_dec : dec_scope.\nInfix \"=\" := eq_nat_dec : dec_scope.\n\n(** Given a boolean relation, we can find the [f]-most element of a list. *)\nDefinition get_func_bool {T} (f : T -> T -> bool) (*H : forall x y z, f x y = true -> f y z = true -> f x z = true*)\n           (ls : list T)\n: ls <> [] -> T\n  := match ls with\n       | [] => fun H => match H eq_refl : False with end\n       | x::xs => fun _ => fold_right (fun acc pt => if (f acc pt) then acc else pt)\n                                      x\n                                      xs\n     end.\n\nProgram Definition get_func {T} {R} `{f : forall x y : T, Decidable (R x y)} (*`{Transitive _ R}*) (ls : list T)\n: ls <> [] -> T\n  := @get_func_bool _ (fun x y => if f x y then true else false) (*_*) ls.\n(*Next Obligation.\n  abstract (\n      destruct (f x y), (f y z), (f x z); hnf in *; firstorder eauto\n    ).\nDefined.*)\n\nSection spec_get_func.\n  Local Hint Extern 1 => intros; etransitivity; eassumption.\n  Local Hint Extern 1 => eapply Forall_impl; [ | eassumption ].\n  Local Hint Extern 3 => progress case_eq_if.\n  Local Hint Constructors Forall.\n\n  Lemma spec_rel_get_func {T} {R}\n        `{forall x y : T, Decidable (R x y)}\n        `{PartialOrder _ eq R, Total _ R}\n        (ls : list T)\n        (Hls : ls <> [])\n  : List.Forall (fun elem => R (get_func Hls) elem) ls.\n  Proof.\n    destruct ls; auto; simpl.\n    induction ls; auto;\n    try solve [ do 2 (reflexivity || constructor) ].\n    specialize (IHls (fun H => nil_cons (eq_sym H))).\n    constructor; simpl.\n    { eauto. }\n    { constructor; eauto. }\n  Qed.\n\n  Lemma spec_in_get_func {T} {R}\n        `{forall x y : T, Decidable (R x y)}\n        `{PartialOrder _ eq R, Total _ R}\n        (ls : list T)\n        (Hls : ls <> [])\n  : get_func Hls ∈ ls.\n  Proof.\n    destruct ls; eauto.\n    simpl; clear Hls.\n    induction ls; try solve [ intuition ].\n    destruct_head or; simpl in *;\n    rewrite_rev_hyp;\n    case_eq_if;\n    try solve [ intuition ].\n  Qed.\nEnd spec_get_func.\n\nFixpoint take_while A (f : A -> bool) n (v : Vector.t A n) : { x : nat & Vector.t A x }\n  := match v with\n       | Vector.nil => existT _ _ (Vector.nil _)\n       | Vector.cons x _ xs => if f x\n                               then existT _ _ (Vector.cons _ x _ (projT2 (take_while f xs)))\n                               else existT _ _ (Vector.nil _)\n     end.\n\nInfix \"<\" := lt_dec : dec_scope.\nInfix \"<=\" := le_dec : dec_scope.\nInfix \">\" := gt_dec : dec_scope.\nInfix \">=\" := ge_dec : dec_scope.\n\nDefinition option_min : option nat -> option nat -> option nat\n  := fun a b => match a, b with\n                  | None, _ => b\n                  | _, None => a\n                  | Some a, Some b => Some (min a b)\n                end.\n\nNotation \"[]\" := List.nil : list_scope.\n\nNotation \"[]\" := (Vector.nil _) : vector_scope.\nNotation \"h :: t\" := (Vector.cons _ h _ t) (at level 60, right associativity) : vector_scope.\nBind Scope vector_scope with Vector.t.\nDelimit Scope vector_scope with vector.\n\n(** Given a decidable [≤] on [B] and a function [f : A → B], we can\n    take the smaller [A] as decided by [f]. *)\nDefinition min_by {A B P} `{p : forall x y : B, Decidable (P x y)}\n           (f : A -> B)\n: A -> A -> A\n  := fun a b => if p (f a) (f b) then a else b.\n", "meta": {"author": "JasonGross", "repo": "ClosestPoints", "sha": "e8b3c06efa442523ff9e7da198da94f9f05b3593", "save_path": "github-repos/coq/JasonGross-ClosestPoints", "path": "github-repos/coq/JasonGross-ClosestPoints/ClosestPoints-e8b3c06efa442523ff9e7da198da94f9f05b3593/CommonDefinitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.6657819335324727}}
{"text": "Welcome to Coq ciosx:/builds/workspace/coq-8.5pl3-macos,(detached from 2290dbb) (2290dbb9c95b63e693ced647731623e64297f5c8)\n\nCoq < Theorem plus_O_n : forall n : nat, 0 + n = n.\n1 subgoal\n  \n  ============================\n  forall n : nat, 0 + n = n\n\nplus_O_n < Proof.\n1 subgoal\n  \n  ============================\n  forall n : nat, 0 + n = n\n\nplus_O_n < intros n.\n1 subgoal\n  \n  n : nat\n  ============================\n  0 + n = n\n\nplus_O_n < simpl.\n1 subgoal\n  \n  n : nat\n  ============================\n  n = n\n\nplus_O_n < reflexivity.\nNo more subgoals.\n\nplus_O_n < Qed.\nProof.\nintros n.\nsimpl.\nreflexivity.\n\nQed.\nplus_O_n 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/basics009.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6657819315797749}}
{"text": "Require Export FormalMath.Infra.\n\n(** The definition of a category and related concepts and theorems\n    follow Steve Awodey's \"Category Theory\". *)\n\n(** * Chapter 1.3 Definition of a category *)\n\nClass Arrows (O: Type): Type := Arrow: O -> O -> Type.\n#[global] Typeclasses Transparent Arrows.\nInfix \"~>\" := Arrow (at level 90, right associativity): math_scope.\n\nClass CatId O `{Arrows O} := cat_id: forall x, x ~> x.\nClass CatComp O `{Arrows O} := comp: forall x y z, (y ~> z) -> (x ~> y) -> (x ~> z).\n\nArguments cat_id {O arrows CatId x} : rename.\nArguments comp {O arrow CatComp} _ _ _ _ _ : rename.\n\nInfix \">>>\" := (comp _ _ _) (at level 40, left associativity) : math_scope.\n\n#[universes (polymorphic, cumulative)]\n Class Category O `{!Arrows O} `{forall a b: O, Equiv (a ~> b)}\n `{!CatId O} `{!CatComp O}: Prop := {\n    arrow_equiv :> forall a b, Setoid (a ~> b);\n    comp_proper :> forall a b c, Proper ((=) ==> (=) ==> (=)) (comp a b c);\n    comp_assoc : forall `(f: a ~> b) `(g: b ~> c) `(h: c ~> d),\n      h >>> (g >>> f) = (h >>> g) >>> f;\n    left_identity: forall `(f: a ~> b), cat_id >>> f = f;\n    right_identity: forall `(f: a ~> b), f >>> cat_id = f;\n  }.\n\nArguments comp_assoc {O arrows eq CatId CatComp Category a b} _ {c} _ {d} _ : rename.\n\n(** * Chapter 1.4 Examples of categories *)\n\n(** 6: Functor *)\nSection FUNCTOR.\n\n  Context `{Category C} `{Category D}.\n  Context (M: C -> D).\n\n  Class Fmap: Type := fmap: forall {v w: C}, (v ~> w) -> (M v ~> M w).\n\n  Class Functor `(Fmap): Prop := {\n      functor_from: Category C;\n      functor_to: Category D;\n      functor_morphism :> forall a b, Setoid_Morphism (@fmap _ a b);\n      preserves_id: forall {a}, fmap (cat_id: a ~> a) = cat_id;\n      preserves_comp: forall `(g: y ~> z) `(f: x ~> y),\n        fmap (g >>> f) = fmap g >>> fmap f\n    }.\n\n  #[global] Instance fmapEquiv: Equiv Fmap :=\n    fun F1 F2 => forall (v w: C) (ar: v ~> w), F1 v w ar = F2 v w ar.\n\n  #[global] Instance fmapSetoid: Setoid Fmap.\n  Proof.\n    constructor; repeat intro; try easy.\n    specialize (H3 v w ar). specialize (H4 v w ar). now transitivity (y v w ar).\n  Qed.\n\nEnd FUNCTOR.\n\n#[global] Typeclasses Transparent Fmap.\n\nSection IDENTITY_FUNCTOR.\n\n  Context `{Category C}.\n\n  #[global] Instance idFmap: Fmap id := fun _ _ => id.\n\n  #[global] Instance idFunctor: Functor (id: C -> C) _.\n  Proof.\n    constructor; try apply _; try easy.\n    intros. constructor; try apply _; try easy.\n  Qed.\n\nEnd IDENTITY_FUNCTOR.\n\nSection COMPOSE_FUNCTOR.\n\n  Context\n    A B C\n    `{!Arrows A} `{!Arrows B} `{!Arrows C}\n    `{!CatId A} `{!CatId B} `{!CatId C}\n    `{!CatComp A} `{!CatComp B} `{!CatComp C}\n    `{forall a b: A, Equiv (a ~> b)}\n    `{forall a b: B, Equiv (a ~> b)}\n    `{forall a b: C, Equiv (a ~> b)}\n    `{!Functor (f: B -> C) f'} `{!Functor (g: A -> B) g'}.\n\n  #[global] Instance compFmap: Fmap (compose f g) :=\n    fun _ _ => compose (fmap f) (fmap g).\n\n  #[global] Instance compFunctor: Functor (compose f g) _.\n  Proof.\n    pose proof (functor_from g). pose proof (functor_to g). pose proof (functor_to f).\n    constructor; intros; try apply _; unfold fmap, compFmap.\n    - apply setoid_morphism_trans.\n      + apply (functor_morphism g).\n      + apply (functor_morphism f).\n    - unfold compose. repeat rewrite preserves_id; auto.\n    - unfold compose. repeat rewrite preserves_comp; auto.\n  Qed.\n\nEnd COMPOSE_FUNCTOR.\n\n(** * Chapter 1.5 Isomorphisms *)\n\nSection ISOMORPHISM.\n\n  Context `{Category C}.\n\n  (** Definition 1.3 *)\n  Class Isomorphism `(f: A ~> B) (g: B ~> A): Prop := {\n      iso_comp1: g >>> f = cat_id;\n      iso_comp2: f >>> g = cat_id;\n    }.\n\n  Lemma iso_inverse_unique: forall `(f: A ~> B) (g1 g2: B ~> A),\n      Isomorphism f g1 -> Isomorphism f g2 -> g1 = g2.\n  Proof.\n    intros. destruct H1, H2. rewrite <- left_identity.\n    rewrite <- iso_comp5, <- comp_assoc. rewrite iso_comp4. apply right_identity.\n  Qed.\n\n  Lemma isomorphism_sym: forall `(f: A ~> B) (g: B ~> A),\n      Isomorphism f g -> Isomorphism g f.\n  Proof. intros. destruct H1. split; auto. Qed.\n\n  Definition isomorphic (A B: C) := exists (f: A ~> B) (g: B ~> A), Isomorphism f g.\n\nEnd ISOMORPHISM.\n\nInfix \"~=~\" := isomorphic (at level 90, no associativity): math_scope.\n\n(** * Chapter 2.1 Epis and monos *)\n\nSection EPIS_MONOS.\n\n  Context `{Category C}.\n\n  (** Definition 2.1 *)\n  Class Monomorphism `(f: A ~> B): Prop :=\n    mono_comp: forall {D: C} (g h: D ~> A), f >>> g = f >>> h -> g = h.\n\n  Class Epimorphism `(f: A ~> B): Prop :=\n    epi_comp: forall {D: C} (i j: B ~> D), i >>> f = j >>> f -> i = j.\n\n  Lemma id_monic_epic: forall `(f: A ~> B) (g: B ~> A),\n      g >>> f = cat_id -> Monomorphism f /\\ Epimorphism g.\n  Proof.\n    intros. split; repeat intro.\n    - rewrite <- left_identity. rewrite <- (left_identity h).\n      rewrite <- H1. rewrite <- comp_assoc. rewrite H2. apply comp_assoc.\n    - rewrite <- right_identity. rewrite <- (right_identity j).\n      rewrite <- H1. rewrite !comp_assoc. now rewrite H2.\n  Qed.\n\n  (** Proposition 2.6 *)\n  Lemma iso_monic_epic: forall `(f: A ~> B) (g: B ~> A),\n      Isomorphism f g -> Monomorphism f /\\ Epimorphism f.\n  Proof.\n    intros. destruct (id_monic_epic f g iso_comp1).\n    destruct (id_monic_epic g f iso_comp2). now split.\n  Qed.\n\nEnd EPIS_MONOS.\n\n(** * Chapter 2.2 Initial and terminal objects *)\nSection INITIAL_TERMINAL.\n\n  Context `{Category C}.\n\n  Class InitialArrow (o: C): Type := initial_arrow: forall c, o ~> c.\n\n  (** Definition 2.9 *)\n  Class Initial (o: C) `{InitialArrow o}: Prop :=\n    initial_arrow_unique: forall c f', f' = initial_arrow c.\n\n  Class TerminalArrow (o: C): Type := terminal_arrow: forall c, c ~> o.\n\n  Class Terminal (o: C) `{TerminalArrow o}: Prop :=\n    terminal_arrow_unique: forall c f', f' = terminal_arrow c.\n\n  (** Proposition 2.10 *)\n  Lemma initial_unique_iso: forall `(Initial o1) `(Initial o2), o1 ~=~ o2.\n  Proof.\n    intros. exists (initial_arrow o2). exists (initial_arrow o1).\n    constructor; rewrite initial_arrow_unique; symmetry; apply initial_arrow_unique.\n  Qed.\n\n  Lemma terminal_unique_iso: forall `(Terminal o1) `(Terminal o2), o1 ~=~ o2.\n  Proof.\n    intros. exists (terminal_arrow o1). exists (terminal_arrow o2).\n    constructor; rewrite terminal_arrow_unique; symmetry; apply terminal_arrow_unique.\n  Qed.\n\nEnd INITIAL_TERMINAL.\n\n(** * Chapter 1.6 Constructions on categories *)\n\n(** Chapter 1.6.1: product category *)\nSection PRODUCT_CATEGORY.\n\n  Context `{Category C} `{Category D}.\n  Instance prodArrows: Arrows (C * D) :=\n    fun p1 p2 => ((fst p1 ~> fst p2) * (snd p1 ~> snd p2))%type.\n  Instance prodCatEq: forall A B: (C * D), Equiv (A ~> B) :=\n    fun _ _ p1 p2 => fst p1 = fst p2 /\\ snd p1 = snd p2.\n  Instance prodCatId: CatId (C * D) := fun _ => (cat_id, cat_id).\n  Instance prodCatComp: CatComp (C * D) :=\n    fun _ _ _ a1 a2 => (fst a1 >>> fst a2, snd a1 >>> snd a2).\n  Instance prodCatSetoid: forall A B: (C * D), Setoid (A ~> B).\n  Proof.\n    intros. constructor; red; unfold equiv, prodCatEq;\n      intros; split; try easy; destruct H3, H4; firstorder.\n  Qed.\n\n  Instance prodCategory: Category (C * D).\n  Proof.\n    constructor; intros; try apply _.\n    - repeat intro. destruct x, x0, y, y0, H3, H4. unfold comp, prodCatComp.\n      simpl in *. split; simpl.\n      + now rewrite H3, H4.\n      + now rewrite H5, H6.\n    - destruct h, g, f. split; simpl; apply comp_assoc.\n    - unfold comp, prodCatComp. destruct f. split; simpl; apply left_identity.\n    - unfold comp, prodCatComp. destruct f. split; simpl; apply right_identity.\n  Qed.\n\n  Instance fstFmap: Fmap fst := fun _ _ => fst.\n\n  Instance fstFunctor: Functor fst _.\n  Proof.\n    constructor; try apply _; intros.\n    - constructor; try apply _. repeat intro. destruct H3. apply H3.\n    - destruct a. reflexivity.\n    - destruct x, y, z, f, g. easy.\n  Qed.\n\n  Instance sndFmap: Fmap snd := fun _ _ => snd.\n\n  Instance sndFunctor: Functor snd _.\n  Proof.\n    constructor; try apply _; intros.\n    - constructor; try apply _. repeat intro. destruct H3. apply H4.\n    - destruct a. reflexivity.\n    - destruct x, y, z, f, g. easy.\n  Qed.\n\nEnd PRODUCT_CATEGORY.\n\n(** Chapter 1.6.2: opposite category *)\nSection OPPOSITE_CATEGORY.\n\n  Context `{@Category C ArrowsC CatEquivC CatIdC CatCompC}.\n\n  Inductive CatOp A := catop_inject: A -> CatOp A.\n  Arguments catop_inject {_} _.\n\n  #[export] Instance catop_rep {A}: Cast (CatOp A) A :=\n    fun x => match x with catop_inject x => x end.\n\n  #[export] Instance oppoArrows: Arrows (CatOp C) := fun a b => ' b ~> ' a.\n  #[export] Instance oppoCatEq: forall A B: (CatOp C), Equiv (oppoArrows A B) :=\n    fun A B => CatEquivC (' B) (' A).\n  #[export] Instance oppoCatId: CatId (CatOp C) := fun x => CatIdC (' x).\n  #[export] Instance oppoCatComp: CatComp (CatOp C) :=\n    fun a b c => flip (CatCompC (' c) (' b) (' a)).\n  #[export] Instance oppoCatSetoid: forall A B: (CatOp C), Setoid (oppoArrows A B).\n  Proof. intros. change (Setoid (ArrowsC (' B) (' A))). apply arrow_equiv. Qed.\n\n  #[export] Instance oppoCategory: Category (CatOp C).\n  Proof.\n    constructor; try apply _; intros; unfold comp, oppoCatComp, Arrow,\n      oppoArrows, cat_id, oppoCatId, equiv, oppoCatEq, flip.\n    - repeat intro. change (CatCompC (' c) (' b) (' a) x0 x =\n                              CatCompC (' c) (' b) (' a) y0 y). now rewrite H1, H0.\n    - symmetry. apply comp_assoc.\n    - apply right_identity.\n    - apply left_identity.\n  Qed.\n\n  Section INITIAL_TERMINAL_DUAL.\n\n    Parameter (o: C).\n    Context `{!InitialArrow o}.\n\n    Instance oppoTermArrow: TerminalArrow (catop_inject o).\n    Proof. repeat intro. repeat red. exact (initial_arrow (' c)). Defined.\n\n    Lemma initial_op_terminal: Initial o -> Terminal (catop_inject o).\n    Proof.\n      intros. repeat red. repeat red in H0.\n      unfold Arrow, oppoArrows, terminal_arrow, oppoTermArrow, cast.\n      simpl. intros. apply H0.\n    Qed.\n\n    Context `{!TerminalArrow o}.\n\n    Instance oppoInitArrow: InitialArrow (catop_inject o).\n    Proof. repeat intro. repeat red. exact (terminal_arrow (' c)). Defined.\n\n    Lemma terminal_op_initial: Terminal o -> Initial (catop_inject o).\n    Proof.\n      intros. repeat red. repeat red in H0.\n      unfold Arrow, oppoArrows, terminal_arrow, oppoTermArrow, cast.\n      simpl. intros. apply H0.\n    Qed.\n\n  End INITIAL_TERMINAL_DUAL.\n\nEnd OPPOSITE_CATEGORY.\n\n(** Chapter 1.6.3: arrow category *)\nSection ARROW_CATEGORY.\n\n  Context `{Category C}.\n\n  Definition arrowObj := {domcod: C * C & fst domcod ~> snd domcod}.\n\n  Instance arrowArrows: Arrows arrowObj.\n  Proof.\n    intros [[A B] f] [[A' B'] f']. simpl in *.\n    exact {g: (A ~> A') * (B ~> B') | (snd g) >>> f = f' >>> (fst g)}.\n  Defined.\n\n  Instance arrowCatEq: forall (A B: arrowObj), Equiv (A ~> B).\n  Proof.\n    intros [[A B] f] [[A' B'] g]. unfold Arrow, arrowArrows.\n    intros [[g1 g2] ?H] [[g3 g4] ?H].\n    exact ((g1 = g3) /\\ (g2 = g4)).\n  Defined.\n\n  Instance arrowCatId: CatId arrowObj.\n  Proof.\n    intros [[A B] f]. simpl in f. unfold Arrow, arrowArrows.\n    exists (cat_id, cat_id). simpl. now rewrite left_identity, right_identity.\n  Defined.\n\n  Instance arrowCatComp: CatComp arrowObj.\n  Proof.\n    intros [[A1 A2] fA] [[B1 B2] fB] [[C1 C2] fC].\n    intros [[h1 h2] ?H]. intros [[g1 g2] ?H]. unfold Arrow, arrowArrows.\n    exists (h1 >>> g1, h2 >>> g2). simpl in *.\n    now rewrite <- comp_assoc, H2, comp_assoc, H1, comp_assoc.\n  Defined.\n\n  Instance arrowCatSetoid: forall (A B: arrowObj), Setoid (A ~> B).\n  Proof.\n    intros [[A1 A2] fA] [[B1 B2] fB]. unfold Arrow, arrowArrows.\n    constructor; repeat intro.\n    - destruct x as [[g1 g2] ?H]. cbn. now split.\n    - destruct x as [[x1 x2] ?H]. destruct y as [[y1 y2] ?H]. simpl in *. cbn in *.\n      destruct H0. split; now symmetry.\n    - destruct x as [[x1 x2] ?H]. destruct y as [[y1 y2] ?H].\n      destruct z as [[z1 z2] ?H]. simpl in *. cbn in *. destruct H1, H2.\n      split; etransitivity; eauto.\n  Qed.\n\n  Instance arrowCategory: Category arrowObj.\n  Proof.\n    constructor; try apply _; intros.\n    - destruct a as [[a1 a2] fa]. destruct b as [[b1 b2] fb].\n      destruct c as [[c1 c2] fc]. repeat intro. cbn in x, y, x0, y0.\n      destruct x as [[gx1 gx2] ?H]. destruct y as [[gy1 gy2] ?H].\n      destruct x0 as [[gz1 gz2] ?H]. destruct y0 as [[gw1 gw2] ?H]. cbn in *.\n      destruct H1, H2. split.\n      + now rewrite H1, H2.\n      + now rewrite H7, H8.\n    - destruct a as [[a1 a2] fa]. destruct b as [[b1 b2] fb].\n      destruct c as [[c1 c2] fc]. destruct d as [[d1 d2] fd]. cbn in f, g, h.\n      destruct f as [[f1 f2] ?H]. destruct g as [[g1 g2] ?H].\n      destruct h as [[h1 h2] ?H]. cbn in *. split; apply comp_assoc.\n    - destruct a as [[a1 a2] fa]. destruct b as [[b1 b2] fb]. cbn in f.\n      destruct f as [[f1 f2] ?H]. cbn. split; apply left_identity.\n    - destruct a as [[a1 a2] fa]. destruct b as [[b1 b2] fb]. cbn in f.\n      destruct f as [[f1 f2] ?H]. cbn. split; apply right_identity.\n  Qed.\n\n  Instance domFmap: Fmap (C := arrowObj) (compose fst (@projT1 _ _)).\n  Proof.\n    repeat intro. destruct v as [[v1 v2] av]. destruct w as [[w1 w2] aw].\n    exact (fst (proj1_sig X)).\n  Defined.\n\n  Instance domFunctor: Functor (compose fst (@projT1 _ _)) _.\n  Proof.\n    constructor; try apply _; repeat intro.\n    - destruct a as [[a1 a2] aa]. destruct b as [[b1 b2] ab].\n      constructor; try apply _. repeat intro. cbn in x, y. cbn.\n      destruct x as [[x1 x2] ?H]. destruct y as [[y1 y2] ?H]. cbn in H1. simpl in *.\n      destruct H1. easy.\n    - destruct a as [[a1 a2] aa]. cbn. easy.\n    - destruct x as [[x1 x2] ax]. destruct y as [[y1 y2] ay].\n      destruct z as [[z1 z2] az]. cbn in f, g.\n      destruct g as [[g1 g2] ?H]. destruct f as [[f1 f2] ?H]. cbn. easy.\n  Qed.\n\n  Instance codFmap: Fmap (C := arrowObj) (compose snd (@projT1 _ _)).\n  Proof.\n    repeat intro. destruct v as [[v1 v2] av]. destruct w as [[w1 w2] aw].\n    exact (snd (proj1_sig X)).\n  Defined.\n\n  Instance codFunctor: Functor (compose snd (@projT1 _ _)) _.\n  Proof.\n    constructor; try apply _; repeat intro.\n    - destruct a as [[a1 a2] aa]. destruct b as [[b1 b2] ab].\n      constructor; try apply _. repeat intro. cbn in x, y. cbn.\n      destruct x as [[x1 x2] ?H]. destruct y as [[y1 y2] ?H]. cbn in H1. simpl in *.\n      destruct H1. easy.\n    - destruct a as [[a1 a2] aa]. cbn. easy.\n    - destruct x as [[x1 x2] ax]. destruct y as [[y1 y2] ay].\n      destruct z as [[z1 z2] az]. cbn in f, g.\n      destruct g as [[g1 g2] ?H]. destruct f as [[f1 f2] ?H]. cbn. easy.\n  Qed.\n\nEnd ARROW_CATEGORY.\n\n(** Chapter 1.6.4: slice category *)\nSection SLICE_CATEGORY.\n\n  Context `{Category C}.\n\n  Definition sliceObj (o: C) := {dom: C & dom ~> o}.\n\n  Instance sliceArrows (o: C): Arrows (sliceObj o).\n  Proof.\n    intros [A fA] [B fB]. exact {fab: A ~> B | fB >>> fab = fA}.\n  Defined.\n\n  Instance sliceCatEq (o: C): forall A B: (sliceObj o), Equiv (A ~> B).\n  Proof.\n    intros [A fA] [B fB]. unfold Arrow, sliceArrows.\n    intros [fab1 ?H] [fab2 ?H]. exact (fab1 = fab2).\n  Defined.\n\n  Instance sliceCatId (o: C): CatId (sliceObj o).\n  Proof.\n    intros [A f]. unfold Arrow, sliceArrows. exists cat_id. apply right_identity.\n  Defined.\n\n  Instance sliceCatComp (o: C): CatComp (sliceObj o).\n  Proof.\n    intros [X fX] [Y fY] [Z fZ]. cbn.\n    intros [fyz ?H]. intros [fxy ?H]. exists (fyz >>> fxy).\n    rewrite <- H2, <- H1. apply comp_assoc.\n  Defined.\n\n  Instance sliceCatSetoid (o: C): forall (A B: sliceObj o), Setoid (A ~> B).\n  Proof.\n    intros [A fA] [B fB]. cbn. constructor; repeat intro.\n    - destruct x as [f ?H]. now cbn.\n    - destruct x as [fx ?H]. destruct y as [fy ?H]. cbn in *. now symmetry.\n    - destruct x as [fx ?H]. destruct y as [fy ?H]. destruct z as [fz ?H].\n      cbn in *. etransitivity; eauto.\n  Qed.\n\n  Instance sliceCategory (o: C): Category (sliceObj o).\n  Proof.\n    constructor; try apply _; intros.\n    - destruct a as [a fa]. destruct b as [b fb]. destruct c as [c fc].\n      repeat intro. cbn in x, y, x0, y0. destruct x as [fx ?H].\n      destruct y as [fy ?H]. destruct x0 as [fz ?H]. destruct y0 as [fw ?H].\n      cbn in *. now rewrite H1, H2.\n    - destruct a as [a fa]. destruct b as [b fb]. destruct c as [c fc].\n      destruct d as [d fd]. cbn in f, g, h. destruct f as [f ?H].\n      destruct g as [g ?H]. destruct h as [h ?H]. cbn. apply comp_assoc.\n    - destruct a as [a fa]. destruct b as [b fb]. cbn in f. destruct f as [f ?].\n      cbn. apply left_identity.\n    - destruct a as [a fa]. destruct b as [b fb]. cbn in f. destruct f as [f ?].\n      cbn. apply right_identity.\n  Qed.\n\n  (** * Chapter 1.9 Exercises 5 Question 1 *)\n  Instance sliceForgetFmap (o: C): Fmap (C := sliceObj o) (@projT1 _ _).\n  Proof.\n    repeat intro. destruct v as [v av]. destruct w as [w aw]. cbn in X.\n    cbn. exact (proj1_sig X).\n  Defined.\n\n  Instance sliceForgetFunctor (o: C): Functor (C := sliceObj o) (@projT1 _ _) _.\n  Proof.\n    constructor; try apply _; intros.\n    - destruct a as [a fa]. destruct b as [b fb]. constructor; try apply _.\n      repeat intro. cbn in x, y. destruct x as [fx ?H]. destruct y as [fy ?H].\n      cbn in *. easy.\n    - destruct a as [a fa]. cbn. easy.\n    - destruct x as [x fx]. destruct y as [y fy]. destruct z as [z fz].\n      cbn in f, g. destruct g as [fg ?H]. destruct f as [ff ?H]. cbn. easy.\n  Qed.\n\n  (** Example 2.11.6 *)\n  Section SLICE_TERMINAL.\n    Context {c: C}.\n\n    Definition idSlice: (sliceObj c) := existT (fun dom : C => dom ~> c) c cat_id.\n\n    Instance idTermArrow: TerminalArrow idSlice.\n    Proof.\n      repeat intro. destruct c0 as [A fA]. do 2 red. unfold idSlice.\n      exists fA. apply left_identity.\n    Defined.\n\n    Instance idSliceTerminal: Terminal idSlice.\n    Proof.\n      repeat intro. destruct c0 as [A fA]. repeat red in f'. destruct f' as [fab ?H].\n      do 2 red. unfold idSlice. unfold terminal_arrow, idTermArrow. rewrite <- H1.\n      symmetry. apply left_identity.\n    Qed.\n\n  End SLICE_TERMINAL.\n\n  Section SLICE_COMP_FUNCTOR.\n\n    Context {c d: C} {g: c ~> d}.\n\n    Definition gM (f: sliceObj c) : sliceObj d.\n    Proof. destruct f as [X f]. exists X. exact (g >>> f). Defined.\n\n    Instance sliceCompFmap: Fmap gM.\n    Proof.\n      repeat intro. destruct v as [dv fv]. destruct w as [dw fw].\n      cbn. cbn in X. destruct X as [fab ?H]. exists fab.\n      rewrite <- comp_assoc. rewrite H1. easy.\n    Defined.\n\n    Instance sliceCompFunctor: Functor gM _.\n    Proof.\n      constructor; try apply _; intros.\n      - constructor; try apply _. repeat intro.\n        destruct a as [da fa]. destruct b as [db fb]. cbn in x, y.\n        destruct x as [fx ?H]. destruct y as [fy ?H]. cbn. cbn in H1. easy.\n      - destruct a as [da fa]. cbn. easy.\n      - destruct x as [x fx]. destruct y as [y fy]. destruct z as [z fz].\n        cbn in g0, f. destruct g0 as [fg ?H]. destruct f as [ff ?H]. cbn. easy.\n    Qed.\n\n  End SLICE_COMP_FUNCTOR.\n\nEnd SLICE_CATEGORY.\n\n(** Chapter 1.6.4: coslice category *)\nSection COSLICE_CATEGORY.\n\n  Context `{Category C}.\n  Context {o : C}.\n\n  Definition cosliceObj := {cod: C & o ~> cod}.\n\n  Instance cosliceArrows: Arrows cosliceObj.\n  Proof.\n    intros [A fA] [B fB]. exact {fab: A ~> B | fab >>> fA = fB}.\n  Defined.\n\n  Instance cosliceCatEq: forall A B: cosliceObj, Equiv (A ~> B).\n  Proof.\n    intros [A fA] [B fB]. unfold Arrow, cosliceArrows.\n    intros [fab1 ?H] [fab2 ?H]. exact (fab1 = fab2).\n  Defined.\n\n  Instance cosliceCatId: CatId cosliceObj.\n  Proof.\n    intros [A f]. unfold Arrow, cosliceArrows. exists cat_id. apply left_identity.\n  Defined.\n\n  Instance cosliceCatComp: CatComp cosliceObj.\n  Proof.\n    intros [X fX] [Y fY] [Z fZ]. cbn.\n    intros [fyz ?H]. intros [fxy ?H]. exists (fyz >>> fxy).\n    rewrite <- H1, <- H2. symmetry. apply comp_assoc.\n  Defined.\n\n  Instance cosliceCatSetoid: forall (A B: cosliceObj), Setoid (A ~> B).\n  Proof.\n    intros [A fA] [B fB]. cbn. constructor; repeat intro.\n    - destruct x as [f ?H]. now cbn.\n    - destruct x as [fx ?H]. destruct y as [fy ?H]. cbn in *. now symmetry.\n    - destruct x as [fx ?H]. destruct y as [fy ?H]. destruct z as [fz ?H].\n      cbn in *. etransitivity; eauto.\n  Qed.\n\n  Instance cosliceCategory: Category cosliceObj.\n  Proof.\n    constructor; try apply _; intros.\n    - destruct a as [a fa]. destruct b as [b fb]. destruct c as [c fc].\n      repeat intro. cbn in x, y, x0, y0. destruct x as [fx ?H].\n      destruct y as [fy ?H]. destruct x0 as [fz ?H]. destruct y0 as [fw ?H].\n      cbn in *. now rewrite H1, H2.\n    - destruct a as [a fa]. destruct b as [b fb]. destruct c as [c fc].\n      destruct d as [d fd]. cbn in f, g, h. destruct f as [f ?H].\n      destruct g as [g ?H]. destruct h as [h ?H]. cbn. apply comp_assoc.\n    - destruct a as [a fa]. destruct b as [b fb]. cbn in f. destruct f as [f ?].\n      cbn. apply left_identity.\n    - destruct a as [a fa]. destruct b as [b fb]. cbn in f. destruct f as [f ?].\n      cbn. apply right_identity.\n  Qed.\n\n  (** Example 2.11.6 *)\n  Definition idCoslice: cosliceObj := existT (fun dom : C => o ~> dom) o cat_id.\n\n  Instance idInitArrow: InitialArrow idCoslice.\n  Proof.\n    repeat intro. destruct c as [A fA]. do 2 red. unfold idCoslice.\n    exists fA. apply right_identity.\n  Defined.\n\n  Instance idSliceInitial: Initial idCoslice.\n  Proof.\n    repeat intro. destruct c as [A fA]. repeat red in f'. destruct f' as [fab ?H].\n    do 2 red. unfold idCoslice. do 2 red. rewrite <- H1.\n    symmetry. apply right_identity.\n  Qed.\n\nEnd COSLICE_CATEGORY.\n\n(** * Chapter 2.3 Generalized elements *)\n\nSection GENERALIZED_ELEMENTS.\n\n  Context `{Category C}.\n\n  (** Example 2.12.3 *)\n  Lemma arrow_eq_iff: forall {c d: C} (f g: c ~> d),\n      f = g <-> forall {X: C} (x: X ~> c), f >>> x = g >>> x.\n  Proof.\n    intros. split; intros.\n    - now rewrite H1.\n    - specialize (H1 _ cat_id). now rewrite !right_identity in H1.\n  Qed.\n\nEnd GENERALIZED_ELEMENTS.\n", "meta": {"author": "txyyss", "repo": "FormalMath", "sha": "35d2593efbc346433fe586b8f8dbaede046df6dc", "save_path": "github-repos/coq/txyyss-FormalMath", "path": "github-repos/coq/txyyss-FormalMath/FormalMath-35d2593efbc346433fe586b8f8dbaede046df6dc/Category/Category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388040954684, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.6657819262329071}}
{"text": "(** * Poly: Polymorphism and Higher-Order Functions *)\n\n(* Final reminder: Please do not put solutions to the exercises in\n   publicly accessible places.  Thank you!! *)\n\n(* Suppress some annoying warnings from Coq: *)\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Lists.\n\nRequire Import Coq.Arith.EqNat.\n\n(* ################################################################# *)\n(** * Polymorphism *)\n\n(** In this chapter we continue our development of basic\n    concepts of functional programming.  The critical new ideas are\n    _polymorphism_ (abstracting functions over the types of the data\n    they manipulate) and _higher-order functions_ (treating functions\n    as data).  We begin with polymorphism. *)\n\n(* ================================================================= *)\n(** ** Polymorphic Lists *)\n\n(** For the last couple of chapters, we've been working just\n    with lists of numbers.  Obviously, interesting programs also need\n    to be able to manipulate lists with elements from other types --\n    lists of strings, lists of booleans, lists of lists, etc.  We\n    _could_ just define a new inductive datatype for each of these,\n    for example... *)\n\nInductive boollist : Type :=\n  | bool_nil\n  | bool_cons (b : bool) (l : boollist).\n\n(** ... but this would quickly become tedious, partly because we\n    have to make up different constructor names for each datatype, but\n    mostly because we would also need to define new versions of all\n    our list manipulating functions ([length], [rev], etc.) for each\n    new datatype definition. *)\n\n(** To avoid all this repetition, Coq supports _polymorphic_\n    inductive type definitions.  For example, here is a _polymorphic\n    list_ datatype. *)\n\nInductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\n(** This is exactly like the definition of [natlist] from the\n    previous chapter, except that the [nat] argument to the [cons]\n    constructor has been replaced by an arbitrary type [X], a binding\n    for [X] has been added to the header, and the occurrences of\n    [natlist] in the types of the constructors have been replaced by\n    [list X].  (We can re-use the constructor names [nil] and [cons]\n    because the earlier definition of [natlist] was inside of a\n    [Module] definition that is now out of scope.)\n\n    What sort of thing is [list] itself?  One good way to think\n    about it is that [list] is a _function_ from [Type]s to\n    [Inductive] definitions; or, to put it another way, [list] is a\n    function from [Type]s to [Type]s.  For any particular type [X],\n    the type [list X] is an [Inductive]ly defined set of lists whose\n    elements are of type [X]. *)\n\nCheck list.\n(* ===> list : Type -> Type *)\n\n(** The parameter [X] in the definition of [list] automatically\n    becomes a parameter to the constructors [nil] and [cons] -- that\n    is, [nil] and [cons] are now polymorphic constructors; when we use\n    them, we must now provide a first argument that is the type of the\n    list they are building. For example, [nil nat] constructs the\n    empty list of type [nat]. *)\n\nCheck (nil nat).\n(* ===> nil nat : list nat *)\n\n(** Similarly, [cons nat] adds an element of type [nat] to a list of\n    type [list nat]. Here is an example of forming a list containing\n    just the natural number 3. *)\n\nCheck (cons nat 3 (nil nat)).\n(* ===> cons nat 3 (nil nat) : list nat *)\n\n(** What might the type of [nil] be? We can read off the type [list X]\n    from the definition, but this omits the binding for [X] which is\n    the parameter to [list]. [Type -> list X] does not explain the\n    meaning of [X]. [(X : Type) -> list X] comes closer. Coq's\n    notation for this situation is [forall X : Type, list X]. *)\n\nCheck nil.\n(* ===> nil : forall X : Type, list X *)\n\n(** Similarly, the type of [cons] from the definition looks like\n    [X -> list X -> list X], but using this convention to explain the\n    meaning of [X] results in the type [forall X, X -> list X -> list\n    X]. *)\n\nCheck cons.\n(* ===> cons : forall X : Type, X -> list X -> list X *)\n\n(** (Side note on notation: In .v files, the \"forall\" quantifier\n    is spelled out in letters.  In the generated HTML files and in the\n    way various IDEs show .v files (with certain settings of their\n    display controls), [forall] is usually typeset as the usual\n    mathematical \"upside down A,\" but you'll still see the spelled-out\n    \"forall\" in a few places.  This is just a quirk of typesetting:\n    there is no difference in meaning.) *)\n\n(** Having to supply a type argument for each use of a list\n    constructor may seem an awkward burden, but we will soon see\n    ways of reducing that burden. *)\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\n(** (We've written [nil] and [cons] explicitly here because we haven't\n    yet defined the [ [] ] and [::] notations for the new version of\n    lists.  We'll do that in a bit.) *)\n\n(** We can now go back and make polymorphic versions of all the\n    list-processing functions that we wrote before.  Here is [repeat],\n    for example: *)\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\n(** As with [nil] and [cons], we can use [repeat] by applying it\n    first to a type and then to an element of this type (and a number): *)\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity.  Qed.\n\n(** To use [repeat] to build other kinds of lists, we simply\n    instantiate it with an appropriate type parameter: *)\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity.  Qed.\n\n\n(** **** Exercise: 2 stars, standard (mumble_grumble)  \n\n    Consider the following two inductively defined types. *)\n\nModule MumbleGrumble.\n\nInductive mumble : Type :=\n  | a\n  | b (x : mumble) (y : nat)\n  | c.\n\nInductive grumble (X:Type) : Type :=\n  | d (m : mumble)\n  | e (x : X).\n\n(** Which of the following are well-typed elements of [grumble X] for\n    some type [X]?  (Add YES or NO to each line.)\n      - [d (b a 5)]\n      - [d mumble (b a 5)]\n      - [d bool (b a 5)]\n      - [e bool true]\n      - [e mumble (b c 0)]\n      - [e bool (b c 0)]\n      - [c]  *)\n(* FILL IN HERE *)\nEnd MumbleGrumble.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_mumble_grumble : option (nat*string) := None.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Annotation Inference *)\n\n(** Let's write the definition of [repeat] again, but this time we\n    won't specify the types of any of the arguments.  Will Coq still\n    accept it? *)\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0        => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\n(** Indeed it will.  Let's see what type Coq has assigned to [repeat']: *)\n\nCheck repeat'.\n(* ===> forall X : Type, X -> nat -> list X *)\nCheck repeat.\n(* ===> forall X : Type, X -> nat -> list X *)\n\n(** It has exactly the same type as [repeat].  Coq was able\n    to use _type inference_ to deduce what the types of [X], [x], and\n    [count] must be, based on how they are used.  For example, since\n    [X] is used as an argument to [cons], it must be a [Type], since\n    [cons] expects a [Type] as its first argument; matching [count]\n    with [0] and [S] means it must be a [nat]; and so on.\n\n    This powerful facility means we don't always have to write\n    explicit type annotations everywhere, although explicit type\n    annotations are still quite useful as documentation and sanity\n    checks, so we will continue to use them most of the time.  You\n    should try to find a balance in your own code between too many\n    type annotations (which can clutter and distract) and too\n    few (which forces readers to perform type inference in their heads\n    in order to understand your code). *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Argument Synthesis *)\n\n(** To use a polymorphic function, we need to pass it one or\n    more types in addition to its other arguments.  For example, the\n    recursive call in the body of the [repeat] function above must\n    pass along the type [X].  But since the second argument to\n    [repeat] is an element of [X], it seems entirely obvious that the\n    first argument can only be [X] -- why should we have to write it\n    explicitly?\n\n    Fortunately, Coq permits us to avoid this kind of redundancy.  In\n    place of any type argument we can write a \"hole\" [_], which can be\n    read as \"Please try to figure out for yourself what belongs here.\"\n    More precisely, when Coq encounters a [_], it will attempt to\n    _unify_ all locally available information -- the type of the\n    function being applied, the types of the other arguments, and the\n    type expected by the context in which the application appears --\n    to determine what concrete type should replace the [_].\n\n    This may sound similar to type annotation inference -- indeed, the\n    two procedures rely on the same underlying mechanisms.  Instead of\n    simply omitting the types of some arguments to a function, like\n\n      repeat' X x count : list X :=\n\n    we can also replace the types with [_]\n\n      repeat' (X : _) (x : _) (count : _) : list X :=\n\n    to tell Coq to attempt to infer the missing information.\n\n    Using holes, the [repeat] function can be written like this: *)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n(** In this instance, we don't save much by writing [_] instead of\n    [X].  But in many cases the difference in both keystrokes and\n    readability is nontrivial.  For example, suppose we want to write\n    down a list containing the numbers [1], [2], and [3].  Instead of\n    writing this... *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...we can use holes to write this: *)\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ----------------------------------------------------------------- *)\n(** *** Implicit Arguments *)\n\n(** We can go further and even avoid writing [_]'s in most cases by\n    telling Coq _always_ to infer the type argument(s) of a given\n    function.\n\n    The [Arguments] directive specifies the name of the function (or\n    constructor) and then lists its argument names, with curly braces\n    around any arguments to be treated as implicit.  (If some\n    arguments of a definition don't have a name, as is often the case\n    for constructors, they can be marked with a wildcard pattern\n    [_].) *)\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\n(** Now, we don't have to supply type arguments at all: *)\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\n(** Alternatively, we can declare an argument to be implicit\n    when defining the function itself, by surrounding it in curly\n    braces instead of parens.  For example: *)\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0        => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n(** (Note that we didn't even have to provide a type argument to the\n    recursive call to [repeat''']; indeed, it would be invalid to\n    provide one!)\n\n    We will use the latter style whenever possible, but we will\n    continue to use explicit [Argument] declarations for [Inductive]\n    constructors.  The reason for this is that marking the parameter\n    of an inductive type as implicit causes it to become implicit for\n    the type itself, not just for its constructors.  For instance,\n    consider the following alternative definition of the [list]\n    type: *)\n\nInductive list' {X:Type} : Type :=\n  | nil'\n  | cons' (x : X) (l : list').\n\n(** Because [X] is declared as implicit for the _entire_ inductive\n    definition including [list'] itself, we now have to write just\n    [list'] whether we are talking about lists of numbers or booleans\n    or anything else, rather than [list' nat] or [list' bool] or\n    whatever; this is a step too far. *)\n\n(** Let's finish by re-implementing a few other standard list\n    functions on our new polymorphic lists... *)\n\nFixpoint app {X : Type} (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity.  Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity.  Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Supplying Type Arguments Explicitly *)\n\n(** One small problem with declaring arguments [Implicit] is\n    that, occasionally, Coq does not have enough local information to\n    determine a type argument; in such cases, we need to tell Coq that\n    we want to give the argument explicitly just this time.  For\n    example, suppose we write this: *)\n\nFail Definition mynil := nil.\n\n(** (The [Fail] qualifier that appears before [Definition] can be\n    used with _any_ command, and is used to ensure that that command\n    indeed fails when executed. If the command does fail, Coq prints\n    the corresponding error message, but continues processing the rest\n    of the file.)\n\n    Here, Coq gives us an error because it doesn't know what type\n    argument to supply to [nil].  We can help it by providing an\n    explicit type declaration (so that Coq has more information\n    available when it gets to the \"application\" of [nil]): *)\n\nDefinition mynil : list nat := nil.\n\n(** Alternatively, we can force the implicit arguments to be explicit by\n   prefixing the function name with [@]. *)\n\nCheck @nil.\n\nDefinition mynil' := @nil nat.\n\n(** Using argument synthesis and implicit arguments, we can\n    define convenient notation for lists, as before.  Since we have\n    made the constructor type arguments implicit, Coq will know to\n    automatically infer these when we use the notations. *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** Now lists can be written just the way we'd hope: *)\n\nDefinition list123''' := [1; 2; 3].\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, standard, optional (poly_exercises)  \n\n    Here are a few simple exercises, just like ones in the [Lists]\n    chapter, for practice with polymorphism.  Complete the proofs below. *)\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  simpl.\n  rewrite -> IHl.\n  reflexivity.\nQed.\n\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros.\n  induction l.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite -> IHl.\n  reflexivity.\nQed.\n  \n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros.\n  induction l1.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite -> IHl1.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (more_poly_exercises)  \n\n    Here are some slightly more interesting ones... *)\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros.\n  induction l1.\n  simpl.\n  rewrite -> app_nil_r .\n  reflexivity.\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.\n  induction l.\n  simpl. reflexivity.\n  simpl.\n  rewrite -> rev_app_distr .\n  simpl.\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_, often called _products_: *)\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\n\nArguments pair {X} {Y} _ _.\n\n(** As with lists, we make the type arguments implicit and define the\n    familiar concrete notation. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** We can also use the [Notation] mechanism to define the standard\n    notation for product _types_: *)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** (The annotation [: type_scope] tells Coq that this abbreviation\n    should only be used when parsing types.  This avoids a clash with\n    the multiplication symbol.) *)\n\n(** It is easy at first to get [(x,y)] and [X*Y] confused.\n    Remember that [(x,y)] is a _value_ built from two other values,\n    while [X*Y] is a _type_ built from two other types.  If [x] has\n    type [X] and [y] has type [Y], then [(x,y)] has type [X*Y]. *)\n\n(** The first and second projection functions now look pretty\n    much as they would in any functional programming language. *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\n(** The following function takes two lists and combines them\n    into a list of pairs.  In other functional languages, it is often\n    called [zip]; we call it [combine] for consistency with Coq's\n    standard library. *)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\n(** **** Exercise: 1 star, standard, optional (combine_checks)  \n\n    Try answering the following questions on paper and\n    checking your answers in Coq:\n    - What is the type of [combine] (i.e., what does [Check\n      @combine] print?)\n    - What does\n\n        Compute (combine [1;2] [false;false;true;true]).\n\n      print? \n\n    [] *)\n\n(** **** Exercise: 2 stars, standard, recommended (split)  \n\n    The function [split] is the right inverse of [combine]: it takes a\n    list of pairs and returns a pair of lists.  In many functional\n    languages, it is called [unzip].\n\n    Fill in the definition of [split] below.  Make sure it passes the\n    given unit test. *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) :=\n  match l with\n  | nil => (nil , nil)\n  | (x ,y) :: xs => (x :: (fst (split xs)), y :: (snd (split xs)))\n  end.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof.\n reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Options *)\n\n(** One last polymorphic type for now: _polymorphic options_,\n    which generalize [natoption] from the previous chapter.  (We put\n    the definition inside a module because the standard library\n    already defines [option] and it's this one that we want to use\n    below.) *)\n\nModule OptionPlayground.\n\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\n\nArguments Some {X} _.\nArguments None {X}.\n\nEnd OptionPlayground.\n\n(** We can now rewrite the [nth_error] function so that it works\n    with any type of lists. *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if n =? O then Some a else nth_error l' (pred n)\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, standard, optional (hd_error_poly)  \n\n    Complete the definition of a polymorphic version of the\n    [hd_error] function from the last chapter. Be sure that it\n    passes the unit tests below. *)\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n  | nil => None\n  | x :: xs => Some x\n  end.\n\n(** Once again, to force the implicit arguments to be explicit,\n    we can use [@] before the name of the function. *)\n\nCheck @hd_error.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Functions as Data *)\n\n(** Like many other modern programming languages -- including\n    all functional languages (ML, Haskell, Scheme, Scala, Clojure,\n    etc.) -- Coq treats functions as first-class citizens, allowing\n    them to be passed as arguments to other functions, returned as\n    results, stored in data structures, etc. *)\n\n(* ================================================================= *)\n(** ** Higher-Order Functions *)\n\n(** Functions that manipulate other functions are often called\n    _higher-order_ functions.  Here's a simple one: *)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\n(** The argument [f] here is itself a function (from [X] to\n    [X]); the body of [doit3times] applies [f] three times to some\n    value [n]. *)\n\nCheck @doit3times.\n(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity.  Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity.  Qed.\n\n(* ================================================================= *)\n(** ** Filter *)\n\n(** Here is a more useful higher-order function, taking a list\n    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])\n    and \"filtering\" the list, returning a new list containing just\n    those elements for which the predicate returns [true]. *)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | []     => []\n  | h :: t => if test h then h :: (filter test t)\n                        else       filter test t\n  end.\n\n(** For example, if we apply [filter] to the predicate [evenb]\n    and a list of numbers [l], it returns a list containing just the\n    even members of [l]. *)\n\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity.  Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  (length l) =? 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** We can use [filter] to give a concise version of the\n    [countoddmembers] function from the [Lists] chapter. *)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity.  Qed.\n\n(* ================================================================= *)\n(** ** Anonymous Functions *)\n\n(** It is arguably a little sad, in the example just above, to\n    be forced to define the function [length_is_1] and give it a name\n    just to be able to pass it as an argument to [filter], since we\n    will probably never use it again.  Moreover, this is not an\n    isolated example: when using higher-order functions, we often want\n    to pass as arguments \"one-off\" functions that we will never use\n    again; having to give each of these functions a name would be\n    tedious.\n\n    Fortunately, there is a better way.  We can construct a function\n    \"on the fly\" without declaring it at the top level or giving it a\n    name. *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity.  Qed.\n\n(** The expression [(fun n => n * n)] can be read as \"the function\n    that, given a number [n], yields [n * n].\" *)\n\n(** Here is the [filter] example, rewritten to use an anonymous\n    function. *)\n\nExample test_filter2':\n    filter (fun l => (length l) =? 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 2 stars, standard (filter_even_gt7)  \n\n    Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat := \n  filter (fun n => andb (negb (ltb n 7)) (evenb n) ) l .\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity.  Qed.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (partition)  \n\n    Use [filter] to write a Coq function [partition]:\n\n      partition : forall X : Type,\n                  (X -> bool) -> list X -> list X * list X\n\n   Given a set [X], a test function of type [X -> bool] and a [list\n   X], [partition] should return a pair of lists.  The first member of\n   the pair is the sublist of the original list containing the\n   elements that satisfy the test, and the second is the sublist\n   containing those that fail the test.  The order of elements in the\n   two sublists should be the same as their order in the original\n   list. *)\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X :=\n  (filter test l, filter (fun n => negb (test n)) l) .\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity.  Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity.  Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Map *)\n\n(** Another handy higher-order function is called [map]. *)\n\nFixpoint map {X Y: Type} (f:X->Y) (l:list X) : (list Y) :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]\n    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has\n    been applied to each element of [l] in turn.  For example: *)\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** The element types of the input and output lists need not be\n    the same, since [map] takes _two_ type arguments, [X] and [Y]; it\n    can thus be applied to a list of numbers and a function from\n    numbers to booleans to yield a list of booleans: *)\n\nExample test_map2:\n  map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity.  Qed.\n\n(** It can even be applied to a list of numbers and\n    a function from numbers to _lists_ of booleans to\n    yield a _list of lists_ of booleans: *)\n\nExample test_map3:\n    map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 3 stars, standard (map_rev)  \n\n    Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\nLemma map_append : 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.\n  {\n     simpl. reflexivity.\n  }\n  {\n     simpl.\n     rewrite -> IHl1.\n     reflexivity.\n  }\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros.\n  induction l.\n  {\n     simpl. reflexivity.\n  }\n  {\n     simpl.\n     rewrite -> map_append.\n     rewrite -> IHl.\n     simpl.\n     reflexivity.\n}\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, recommended (flat_map)  \n\n    The function [map] maps a [list X] to a [list Y] using a function\n    of type [X -> Y].  We can define a similar function, [flat_map],\n    which maps a [list X] to a [list Y] using a function [f] of type\n    [X -> list Y].  Your definition should work by 'flattening' the\n    results of [f], like so:\n\n        flat_map (fun n => [n;n+1;n+2]) [1;5;10]\n      = [1; 2; 3; 5; 6; 7; 10; 11; 12].\n*)\n\nFixpoint flat_map {X Y: Type} (f: X -> list Y) (l: list X)\n                   : (list Y) :=\n  match l with \n  | nil => nil\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(** [] *)\n\n(** Lists are not the only inductive type for which [map] makes sense.\n    Here is a [map] for the [option] type: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\n(** **** Exercise: 2 stars, standard, optional (implicit_args)  \n\n    The definitions and uses of [filter] and [map] use implicit\n    arguments in many places.  Replace the curly braces around the\n    implicit arguments with parentheses, and then fill in explicit\n    type parameters where necessary and use Coq to check that you've\n    done so correctly.  (This exercise is not to be turned in; it is\n    probably easiest to do it on a _copy_ of this file that you can\n    throw away afterwards.)\n\n    [] *)\n\n(* ================================================================= *)\n(** ** Fold *)\n\n(** An even more powerful higher-order function is called\n    [fold].  This function is the inspiration for the \"[reduce]\"\n    operation that lies at the heart of Google's map/reduce\n    distributed programming framework. *)\n\nFixpoint fold {X Y: Type} (f: X->Y->Y) (l: list X) (b: Y)\n                         : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(** Intuitively, the behavior of the [fold] operation is to\n    insert a given binary operator [f] between every pair of elements\n    in a given list.  For example, [ fold plus [1;2;3;4] ] intuitively\n    means [1+2+3+4].  To make this precise, we also need a \"starting\n    element\" that serves as the initial second input to [f].  So, for\n    example,\n\n       fold plus [1;2;3;4] 0\n\n    yields\n\n       1 + (2 + (3 + (4 + 0))).\n\n    Some more examples: *)\n\nCheck (fold andb).\n(* ===> fold andb : list bool -> bool -> bool *)\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, advanced (fold_types_different)  \n\n    Observe that the type of [fold] is parameterized by _two_ type\n    variables, [X] and [Y], and the parameter [f] is a binary operator\n    that takes an [X] and a [Y] and returns a [Y].  Can you think of a\n    situation where it would be useful for [X] and [Y] to be\n    different? *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_types_different : option (nat*string) := None.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Functions That Construct Functions *)\n\n(** Most of the higher-order functions we have talked about so\n    far take functions as arguments.  Let's look at some examples that\n    involve _returning_ functions as the results of other functions.\n    To begin, here is a function that takes a value [x] (drawn from\n    some type [X]) and returns a function from [nat] to [X] that\n    yields [x] whenever it is called, ignoring its [nat] argument. *)\n\nDefinition constfun {X: Type} (x: X) : nat->X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** In fact, the multiple-argument functions we have already\n    seen are also examples of passing functions as data.  To see why,\n    recall the type of [plus]. *)\n\nCheck plus.\n(* ==> nat -> nat -> nat *)\n\n(** Each [->] in this expression is actually a _binary_ operator\n    on types.  This operator is _right-associative_, so the type of\n    [plus] is really a shorthand for [nat -> (nat -> nat)] -- i.e., it\n    can be read as saying that \"[plus] is a one-argument function that\n    takes a [nat] and returns a one-argument function that takes\n    another [nat] and returns a [nat].\"  In the examples above, we\n    have always applied [plus] to both of its arguments at once, but\n    if we like we can supply just the first.  This is called _partial\n    application_. *)\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity.  Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity.  Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\nModule Exercises.\n\n(** **** Exercise: 2 stars, standard (fold_length)  \n\n    Many common functions on lists can be implemented in terms of\n    [fold].  For example, here is an alternative definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length].  (Hint: It may help to\n    know that [reflexivity] simplifies expressions a bit more\n    aggressively than [simpl] does -- i.e., you may find yourself in a\n    situation where [simpl] does nothing but [reflexivity] solves the\n    goal.) *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n   intros.\n   induction l.\n   {\n      simpl. reflexivity.\n   }\n   {\n      simpl.\n      symmetry in IHl.\n      rewrite -> IHl.\n      reflexivity.\n    }\nQed.\n      \n(** [] *)\n\n(** **** Exercise: 3 stars, standard (fold_map)  \n\n    We can also define [map] in terms of [fold].  Finish [fold_map]\n    below. *)\n\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y :=\n    fold cons (map f l) nil .\n\n(** Write down a theorem [fold_map_correct] in Coq stating that\n   [fold_map] is correct, and prove it.  (Hint: again, remember that\n   [reflexivity] simplifies expressions a bit more aggressively than\n   [simpl].) *)\n\nTheorem fold_map_correct: forall X Y (l : list X) (f : X -> Y), fold_map f l = map f l .\nProof.\n  intros.\n  induction l.\n  {\n    simpl. reflexivity.\n   }\n  {\n    simpl.\n    symmetry in IHl.\n      rewrite -> IHl.\n      reflexivity.\n   }\nQed.\n  \n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_map : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (currying)  \n\n    In Coq, a function [f : A -> B -> C] really has the type [A\n    -> (B -> C)].  That is, if you give [f] a value of type [A], it\n    will give you function [f' : B -> C].  If you then give [f'] a\n    value of type [B], it will return a value of type [C].  This\n    allows for partial application, as in [plus3].  Processing a list\n    of arguments with functions that return functions is called\n    _currying_, in honor of the logician Haskell Curry.\n\n    Conversely, we can reinterpret the type [A -> B -> C] as [(A *\n    B) -> C].  This is called _uncurrying_.  With an uncurried binary\n    function, both arguments must be given at once as a pair; there is\n    no partial application. *)\n\n(** We can define currying as follows: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** As an exercise, define its inverse, [prod_uncurry].  Then prove\n    the theorems below to show that the two are inverses. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z := f (fst p) (snd p) .\n\n(** As a (trivial) example of the usefulness of currying, we can use it\n    to shorten one of the examples that we saw above: *)\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** Thought exercise: before running the following commands, can you\n    calculate the types of [prod_curry] and [prod_uncurry]? *)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  intros.\n  reflexivity.\nQed.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros.\n  destruct p.\n  reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, advanced (nth_error_informal)  \n\n    Recall the definition of the [nth_error] function:\n\n   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n     match l with\n     | [] => None\n     | a :: l' => if n =? O then Some a else nth_error l' (pred n)\n     end.\n\n   Write an informal proof of the following theorem:\n\n   forall X n l, length l = n -> @nth_error X l n = None\n*)\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_proof : option (nat*string) := None.\n(** [] *)\n\n(** The following exercises explore an alternative way of defining\n    natural numbers, using the so-called _Church numerals_, named\n    after mathematician Alonzo Church.  We can represent a natural\n    number [n] as a function that takes a function [f] as a parameter\n    and returns [f] iterated [n] times. *)\n\nModule Church.\nDefinition cnat := forall X : Type, (X -> X) -> X -> X.\n\n(** Let's see how to write some numbers with this notation. Iterating\n    a function once should be the same as just applying it.  Thus: *)\n\nDefinition one : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** Similarly, [two] should apply [f] twice to its argument: *)\n\nDefinition two : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** Defining [zero] is somewhat trickier: how can we \"apply a function\n    zero times\"?  The answer is actually simple: just return the\n    argument untouched. *)\n\nDefinition zero : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(** More generally, a number [n] can be written as [fun X f x => f (f\n    ... (f x) ...)], with [n] occurrences of [f].  Notice in\n    particular how the [doit3times] function we've defined previously\n    is actually just the Church representation of [3]. *)\n\nDefinition three : cnat := @doit3times.\n\n(** Complete the definitions of the following functions. Make sure\n    that the corresponding unit tests pass by proving them with\n    [reflexivity]. *)\n\n(** **** Exercise: 1 star, advanced (church_succ)  *)\n\n(** Successor of a natural number: given a Church numeral [n],\n    the successor [succ n] is a function that iterates its\n    argument once more than [n]. *)\nDefinition succ (n : cnat) : cnat := fun (X : Type) f x => n X f (f x).\n\nExample succ_1 : succ zero = one.\nProof. reflexivity.  Qed.\n\nExample succ_2 : succ one = two.\nProof. reflexivity.  Qed.\n\nExample succ_3 : succ two = three.\nProof. reflexivity.  Qed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (church_plus)  *)\n\n(** Addition of two natural numbers: *)\nDefinition plus (n m : cnat) : cnat :=\n  fun (X : Type) f x => 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(** [] *)\n\n(** **** Exercise: 2 stars, advanced (church_mult)  *)\n\n(** Multiplication: *)\nDefinition mult (n m : cnat) : cnat :=\n  fun (X : Type) f x => m X (fun t => n X f t) x.\n\nExample mult_1 : mult one one = one.\nProof. reflexivity.  Qed.\n\nExample mult_2 : mult zero (plus three three) = zero.\nProof. reflexivity.  Qed.\n\nExample mult_3 : mult two three = plus three three.\nProof. reflexivity.  Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (church_exp)  *)\n\n(** Exponentiation: *)\n\n(** (_Hint_: Polymorphism plays a crucial role here.  However,\n    choosing the right type to iterate over can be tricky.  If you hit\n    a \"Universe inconsistency\" error, try iterating over a different\n    type.  Iterating over [cnat] itself is usually problematic.) *)\n\nDefinition exp (n m : cnat) : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => m (X -> X) (n X ) f x .\n\nExample exp_1 : exp two two = plus two two.\nProof. reflexivity.  Qed.\n\nExample exp_2 : exp three zero = one.\nProof. reflexivity.  Qed.\n\nExample exp_3 : exp three two = plus (mult two (mult two two)) one.\nProof. reflexivity.  Qed.\n\n(** [] *)\n\nEnd Church.\n\nEnd Exercises.\n\n\n(* Wed Jan 9 12:02:44 EST 2019 *)\n", "meta": {"author": "simpadjo", "repo": "coq-excercises", "sha": "7b9657412746b3d64798b840f040403e9c99e83c", "save_path": "github-repos/coq/simpadjo-coq-excercises", "path": "github-repos/coq/simpadjo-coq-excercises/coq-excercises-7b9657412746b3d64798b840f040403e9c99e83c/lf/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173791645582, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.6657819223275115}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrfun.\nFrom mathcomp Require Import eqtype ssrnat seq bigop order.\nFrom ipcssr Require Import prelude.\nImport Order.POrderTheory.\nImport Order.TotalTheory.\nOpen Scope order_scope.\n\nInductive form A : Type :=\n  | Falsum : form A\n  | Atom : A -> form A\n  | AndF : form A -> form A -> form A\n  | OrF : form A -> form A -> form A\n  | Imp : form A -> form A -> form A.\n\nArguments Falsum {A}.\nArguments Atom [A].\nArguments AndF [A].\nArguments OrF [A].\nArguments Imp [A].\n\nSection Form.\nContext {A : Type}.\n\nFixpoint vimp (qs : seq A) (f : form A) : form A :=\n  if qs is q::qs' then vimp qs' (Imp (Atom q) f) else f.\n\nEnd Form.\n\nSection FormEq.\nContext {A : eqType}.\n\nFixpoint eqform (f1 f2 : form A) :=\n  match f1, f2 with\n  | Falsum    , Falsum     => true\n  | Atom i1   , Atom i2    => i1 == i2\n  | AndF l1 r1, AndF l2 r2 => eqform l1 l2 && eqform r1 r2\n  | OrF l1 r1 , OrF l2 r2  => eqform l1 l2 && eqform r1 r2\n  | Imp l1 r1 , Imp l2 r2  => eqform l1 l2 && eqform r1 r2\n  | _         , _          => false\n  end.\n\nLemma eqformP: Equality.axiom eqform.\nProof.\nelim=>[|i1|l1 IHl r1 IHr|l1 IHl r1 IHr|l1 IHl r1 IHr]; case=>[|i2|l2 r2|l2 r2|l2 r2] /=; try by constructor.\n- case: (eqVneq i1 i2)=>[->|N]; constructor=>//.\n  by apply: contra_neq_not N; case.\n- by apply: (equivP (andPP (IHl l2) (IHr r2))); split; [case=>->-> | case].\n- by apply: (equivP (andPP (IHl l2) (IHr r2))); split; [case=>->-> | case].\nby apply: (equivP (andPP (IHl l2) (IHr r2))); split; [case=>->-> | case].\nQed.\n\nCanonical form_eqMixin := EqMixin eqformP.\nCanonical form_eqType := Eval hnf in EqType (form A) form_eqMixin.\n\nFixpoint subst_form (i : A) (a b : form A) : form A :=\n  match b with\n  | Falsum     => Falsum\n  | Atom j     => if i == j then a else Atom j\n  | AndF b0 b1 => AndF (subst_form i a b0) (subst_form i a b1)\n  | OrF  b0 b1 => OrF  (subst_form i a b0) (subst_form i a b1)\n  | Imp  b0 b1 => Imp  (subst_form i a b0) (subst_form i a b1)\n  end.\n\nDefinition subst_list (i : A) (a : form A) (l : seq (form A)) :=\n  map (subst_form i a) l.\n\nLemma subst_onth (i : A) (g : form A) (n : nat) (ctx : seq (form A)) :\n  onth (subst_list i g ctx) n = omap (subst_form i g) (onth ctx n).\nProof. by elim: ctx n=>//= h ctx IH; case. Qed.\n\nEnd FormEq.\n\nSection FormOrd.\nContext {disp : unit} {A : orderType disp}.\n\nFixpoint below_form (a : form A) (i : A) {struct a} : bool :=\n  match a with\n  | Falsum => true\n  | Atom j => (j < i)%O\n  | AndF x y => below_form x i && below_form y i\n  | OrF  x y => below_form x i && below_form y i\n  | Imp  x y => below_form x i && below_form y i\n  end.\n\nDefinition below_list (l : seq (form A)) (i : A) :=\n  all (below_form^~ i) l.\n\nLemma less_below_form_imply (a : form A) (i j : A) :\n  (i < j)%O -> below_form a i ==> below_form a j.\nProof.\nmove=>H; elim: a=>//=.\n- by move=>a; apply/implyP=>Ha; apply/lt_trans/H.\n- by move=>f hf g Hg; apply: implyb_tensor.\n- by move=>f hf g Hg; apply: implyb_tensor.\nby move=>f hf g Hg; apply: implyb_tensor.\nQed.\n\nLemma less_below_list_imply (l : seq (form A)) (i j : A) :\n  (i < j)%O -> below_list l i ==> below_list l j.\nProof.\nmove=>H; rewrite /below_list.\nby apply/implyP/sub_all=>a; apply/implyP/less_below_form_imply.\nQed.\n\nLemma subst_form_below (i : A) (g a : form A) :\n  below_form a i -> subst_form i g a = a.\nProof.\nelim: a=>//=.\n- by move=>a; rewrite lt_neqAle eq_sym=>/andP [/negbTE->].\n- by move=>k IHk l IHl /andP [/IHk->/IHl->].\n- by move=>k IHk l IHl /andP [/IHk->/IHl->].\nby move=>k IHk l IHl /andP [/IHk->/IHl->].\nQed.\n\nLemma subst_list_below (i : A) (g : form A) (l : seq (form A)) :\n  below_list l i -> subst_list i g l = l.\nProof.\nrewrite /below_list /subst_list; elim: l=>//= h l IH.\ncase/andP=>H /IH->.\nby rewrite (subst_form_below _ _ _ H).\nQed.\n\nLemma below_vimp (i : A) (l : seq A) (a b : form A) :\n  (forall j : A, below_form a j ==> below_form b j) ->\n  below_form (vimp l a) i ==> below_form (vimp l b) i.\nProof.\nelim: l =>//= k l IH in a b *; move=>H.\nby apply: IH=>/= j; apply/implyb_tensor.\nQed.\n\nLemma below_vimp_head (i : A) (l : seq A) (a : form A) :\n  below_form (vimp l a) i ==> below_form a i.\nProof.\nelim: l a=>//= h l IH a.\napply/implyb_trans/IH/below_vimp=>/= j.\nby apply/implyP; case/andP.\nQed.\n\nLemma below_vimp_split (j : A) (l : seq A) (a : form A) :\n  {in l, forall i, (i < j)%O} ->\n  below_form a j ==> below_form (vimp l a) j.\nProof.\nelim: l a=>//= h l IH a H.\napply/implyb_trans/IH=>/=; last first.\n- by move=>z Hz; apply: (H z); rewrite inE Hz orbT.\napply/implyP=>->; rewrite andbT.\nby apply: H; rewrite inE eqxx.\nQed.\n\nLemma below_vimp_tail (j : A) (l : seq A) (a : form A) :\n  below_form (vimp l a) j -> {in l, forall i, (i < j)%O}.\nProof.\nelim: l a=>//= h l IH a H z.\nrewrite inE; case/orP=>[/eqP{z}->|]; last by apply: (IH _ H).\nmove: (below_vimp_head j l (Imp (Atom h) a))=>/=.\nby move/implyP=>/(_ H); case/andP.\nQed.\n\nLemma subst_vimp_head (j : A) (l : seq A) (a b : form A) :\n  {in l, forall i, (i < j)%O} ->\n  subst_form j a (vimp l b) = vimp l (subst_form j a b).\nProof.\nelim: l=>//= h l IH in a b *; move=>H.\nrewrite IH /=; last first.\n- by move=>z Hz; apply: (H z); rewrite inE Hz orbT.\ncase: eqP=>// E.\nby move: (H j); rewrite E inE eqxx ltxx /= => /(_ erefl).\nQed.\n\nEnd FormOrd.\n\n(* could be abstracted as ssr num but probably not worth it *)\nSection FormNat.\n\nFixpoint max_int_of_form (f : form nat) : nat :=\n  match f with\n  | Falsum => 0\n  | Atom i => i.+1\n  | AndF f0 f1 => maxn (max_int_of_form f0) (max_int_of_form f1)\n  | OrF  f0 f1 => maxn (max_int_of_form f0) (max_int_of_form f1)\n  | Imp  f0 f1 => maxn (max_int_of_form f0) (max_int_of_form f1)\n  end.\n\nLemma max_int_of_form_below (a : form nat) : below_form a (max_int_of_form a).\nProof.\nelim: a=>//=.\n- by move=>a; rewrite ltEnat /= ltnS.\n- move=>f IHf g IHg.\n  case: (ltngtP (max_int_of_form f) (max_int_of_form g))=>H.\n  - by rewrite IHg andbT; move: IHf; apply/implyP/less_below_form_imply.\n  - by rewrite IHf; move: IHg; apply/implyP/less_below_form_imply.\n  by rewrite IHf /= H.\n- move=>f IHf g IHg.\n  case: (ltngtP (max_int_of_form f) (max_int_of_form g))=>H.\n  - by rewrite IHg andbT; move: IHf; apply/implyP/less_below_form_imply.\n  - by rewrite IHf; move: IHg; apply/implyP/less_below_form_imply.\n  by rewrite IHf /= H.\nmove=>f IHf g IHg.\ncase: (ltngtP (max_int_of_form f) (max_int_of_form g))=>H.\n- by rewrite IHg andbT; move: IHf; apply/implyP/less_below_form_imply.\n- by rewrite IHf; move: IHg; apply/implyP/less_below_form_imply.\nby rewrite IHf /= H.\nQed.\n\nDefinition max_int_of_list (l : seq (form nat)) : nat :=\n  foldr (maxn \\o max_int_of_form) 0 l.\n\nLemma max_int_of_list_below (g : seq (form nat)) : below_list g (max_int_of_list g).\nProof.\nelim: g=>//=h g IH.\nhave H := max_int_of_form_below h.\ncase: (ltngtP (max_int_of_form h) (max_int_of_list g))=>H2.\n- by rewrite IH andbT; move: H; apply/implyP/less_below_form_imply.\n- by rewrite H /=; move: IH; apply/implyP/less_below_list_imply.\nby rewrite H /= H2.\nQed.\n\nEnd FormNat.\n", "meta": {"author": "clayrat", "repo": "ipc-ssr", "sha": "51090b179172176f1c301df412735655e8ba6328", "save_path": "github-repos/coq/clayrat-ipc-ssr", "path": "github-repos/coq/clayrat-ipc-ssr/ipc-ssr-51090b179172176f1c301df412735655e8ba6328/theories/forms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6657764526565363}}
{"text": "(**\n   GEB の TNT で証明された定理を Coq で証明する。\n   2011_10_22\n   *)\n\n\n(** s と 「+」を定義する。*)\nInductive Nat : Set :=\n| O : Nat\n| s : Nat -> Nat.\nVariable add : Nat -> Nat -> Nat.\nInfix \".+\" := add (at level 61, left associativity).\n\n\n(** 公理 *)\nAxiom a_2 : forall a, a .+ O = a.                (* 公理(2) *)\nAxiom a_3 : forall a b, a .+ (s b) = s (a .+ b). (* 公理(3) *)\n\n\n(**\n   「S入れ」は、推論規則とされているが、補題として証明しておく。\n   *)\nLemma s_in : forall r t, r = t -> (s r) = (s t).\nProof.\n  intros.\n  induction r.\n  rewrite H.\n  reflexivity.\n  rewrite H.\n  reflexivity.\nQed.\n\n\n(**\n   [GEB白1985] p.232で証明された定理を証明する。\n   *)\nTheorem t232 : forall a, (O .+ a) = a.\nProof.\n  intro a.                              (* 特殊化 *)\n  induction a as [|b IH].               (* 機能規則 *)\n  Check (a_2 O).                        (* 「ピラミッドの最初の式」 *)\n  apply (a_2 O).                        (* 帰納の二番目の前提 *)\n  Check (a_3 O b).                      (* 式(7) *)\n  rewrite (a_3 O b).                    (* 推移性 *)\n  apply s_in.                           (* S入れ *)\n  apply IH.                             (* 帰納の一番目の前提 *)\nQed.\n\n\n(**\n   補題、式(18)\n   *)\nLemma l18 : forall c,\n  (forall d, d .+ s c = s d .+ c) ->\n  (forall d, d .+ s (s c) = s d .+ s c).\nProof.\n  intros c H d.                             (* 特殊化 *)\n  Check (a_3 d (s c)).                      (* 式(3) *)\n  Check (a_3 (s d) c).                      (* 式(5) *)\n  rewrite (a_3 (s d) c).                    (* 推移性、式(6) *)\n  rewrite (a_3 d (s c)).                    (* 推移性、式(3) *)\n  apply s_in.                               (* S入れ *)\n  apply H.                                  (* 前提 *)\nQed.\n    \n(**\n   補題、式(28)\n   Sは加法において、前や後ろに移動できる。\n   *)\nLemma l28 : forall c d, d .+ s c = s d .+ c.\nProof.\n  induction c as [|c IH].                   (* 帰納規則 *)\n  intros d.                                 (* 特殊化 *)\n  Check (a_3 d O).                          (* 式(19) *)\n  Check (a_2 (s d)).                        (* 式(26) *)\n  rewrite (a_3 d O).                        (* 推移性、式(19) *)\n  rewrite (a_2 (s d)).                      (* 推移性、式(26) *)\n  apply s_in.                               (* S入れ *)\n  apply a_2.                                (* 帰納の前提 *)\n  Check (l18 c).                            (* *** *)\n  apply (l18 c).                            (* *** *)\n  apply IH.                                 (* 帰納の前提 *)\nQed.\n\n\n(**\n   補題、式(49)\n   もしdが任意のcと交換可能なら、同じことがs dについてもいえる。\n   *)\nLemma l49 : forall d,\n  (forall c, c .+ d = d .+ c) ->\n  (forall c, c .+ s d = s d .+ c).\nProof.\n  intros d H.                             (* 特殊化 *)\n  intros c.                               (* 特殊化 *)\n  Check (a_3 c d).                        (* 式(30) *)\n  Check (a_3 d c).                        (* 式(33) *)\n  Check (l28 c d).                        (* 式(35) *)\n  rewrite <- (l28 c d).                   (* 推移性、式(35) *)\n  rewrite (a_3 d c).                      (* 推移性、式(33) *)\n  rewrite (a_3 c d).                      (* 推移性、式(30) *)\n  apply s_in.                             (* S入れ。 *)\n  apply H.                                (* 前提 *)\nQed.\n\n\n(**\n   定理、[GEB白1985] p.234\n   *)\nTheorem geb_tnt_1 : forall d c, c .+ d = d .+ c.\nProof.\n  intros d.                                 (* 特殊化 *)\n  induction d as [|d H].                    (* 帰納規則 *)\n  intros c.                                 (* 特殊化 *)\n  Check (t232 c).                           (* 式(52) *)\n  rewrite (t232 c).                         (* 推移性、式(52) *)\n  apply a_2.                                (* 帰納の前提 *)\n  apply l49.                                (* *** *)\n  apply H.                                  (* 帰納の前提 *)\nQed.\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_geb_tnt_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826789824086, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.665776450622106}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_ray1.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_interior5.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_8_3 : \n   forall A B C D, \n   Per A B C -> Out B C D ->\n   Per A B D.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists E, (BetS A B E /\\ Cong A B E B /\\ Cong A C E C /\\ neq B C)) by (conclude_def Per );destruct Tf as [E];spliter.\nassert (Cong B C B C) by (conclude cn_congruencereflexive).\nassert (Cong C D C D) by (conclude cn_congruencereflexive).\nassert (Cong B A B E) by (forward_using lemma_congruenceflip).\nassert (Cong C A C E) by (forward_using lemma_congruenceflip).\nassert ((BetS B D C \\/ eq C D \\/ BetS B C D)) by (conclude lemma_ray1).\nassert (Per A B D).\nby cases on (BetS B D C \\/ eq C D \\/ BetS B C D).\n{\n assert (Cong B D B D) by (conclude cn_congruencereflexive).\n assert (Cong D C D C) by (conclude cn_congruencereflexive).\n assert (Cong D A D E) by (conclude lemma_interior5).\n assert (Cong A D E D) by (forward_using lemma_congruenceflip).\n assert (neq B D) by (forward_using lemma_betweennotequal).\n assert (Per A B D) by (conclude_def Per ).\n close.\n }\n{\n assert (Per A B D) by (conclude cn_equalitysub).\n close.\n }\n{\n assert (Cong A D E D) by (conclude axiom_5_line).\n assert (neq B D) by (forward_using lemma_betweennotequal).\n assert (Per A B D) by (conclude_def Per ).\n close.\n }\n(** cases *)\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_8_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6657764448484434}}
{"text": "Require Import CT.Category.\nRequire Import CT.Functor.\nRequire Import CT.Instance.Functor.ComposeFunctor.\nRequire Import CT.Instance.Functor.Endofunctor.\nRequire Import CT.Instance.Functor.FaithfulFunctor.\nRequire Import CT.Instance.Functor.FullFunctor.\n\nProgram Definition IdentityFunctor {C : Category} : @Endofunctor C :=\n  {| F_ob := fun x => x;\n     F_mor := fun _ _ f => f;\n  |}.\n\n(** The identity functor is always faithful. *)\nTheorem identity_is_faithful (C : Category) : FaithfulFunctor (@IdentityFunctor C).\nProof.\n  intro.\n  simpl.\n  trivial.\nQed.\n\n(** The identity functor is always full. *)\nTheorem identity_is_full (C : Category) : FullFunctor (@IdentityFunctor C).\nProof.\n  repeat intro.\n  exists f.\n  simpl.\n  reflexivity.\nQed.\n\n(** Composition of [IdentityFunctor]s is still the [IdentityFunctor]. *)\nTheorem comp_identity_identity :\n  forall {C : Category} (F G : @Endofunctor C),\n    F = @IdentityFunctor C ->\n    G = @IdentityFunctor C ->\n    ComposeFunctor F G = @IdentityFunctor C.\nProof.\n  intros.\n  unfold ComposeFunctor.\n  subst.\n  simpl.\n  unfold IdentityFunctor at 5.\n  apply F_eq;\n    reflexivity.\nQed.\n\n(** Composition of anything with the [IdentityFunctor] the original thing. *)\nTheorem comp_identity_right :\n  forall {A B : Category} (F : Functor A B) (G : Functor B B),\n    G = @IdentityFunctor B ->\n    ComposeFunctor F G = F.\nProof.\n  intros.\n  unfold ComposeFunctor.\n  subst.\n  apply F_eq;\n    reflexivity.\nQed.\n\nTheorem comp_identity_left :\n  forall {A B : Category} (F : Functor A B) (G : Functor A A),\n    G = @IdentityFunctor A ->\n    ComposeFunctor G F = F.\nProof.\n  intros.\n  unfold ComposeFunctor.\n  subst.\n  apply F_eq;\n    reflexivity.\nQed.", "meta": {"author": "relrod", "repo": "ct", "sha": "abd8b0067e219ee4867f7136bdf1b35885224cb4", "save_path": "github-repos/coq/relrod-ct", "path": "github-repos/coq/relrod-ct/ct-abd8b0067e219ee4867f7136bdf1b35885224cb4/CT/Instance/Functor/IdentityFunctor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6657764361424556}}
{"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 Bool Lia Eqdep_dec.\n\nFrom Undecidability.Shared.Libs.DLW.Utils\n  Require Import utils_tac utils_list utils_nat finite.\n\nFrom Undecidability.Shared.Libs.DLW.Vec \n  Require Import pos vec.\n\nFrom Undecidability.FOL.TRAKHTENBROT\n  Require Import notations utils fol_ops fo_sig fo_terms fo_logic fo_sat.\n\nImport fol_notations.\n\nSet Implicit Arguments.\n\n(* * Uniformize the arity of relations *)\n\nLocal Notation ø := vec_nil.\n\nSection vec_fill_tail.\n\n  Variable (X : Type) (n : nat) (k : nat) (v : vec X k) (e : X).\n\n  Definition vec_fill_tail : vec X n.\n  Proof using v e.\n    apply vec_set_pos; intros p.\n    destruct (le_lt_dec k (pos2nat p)) as [ | H ].\n    + exact e.\n    + exact (vec_pos v (nat2pos H)).\n  Defined.\n\n  Fact vec_fill_tail_lt p (Hp : pos2nat p < k) : vec_pos vec_fill_tail p = vec_pos v (nat2pos Hp).\n  Proof.\n    unfold vec_fill_tail; rew vec.\n    destruct (le_lt_dec k (pos2nat p)).\n    + exfalso; lia.\n    + do 2 f_equal; apply lt_pirr.\n  Qed.\n\n  Fact vec_fill_tail_ge p : k <= pos2nat p -> vec_pos vec_fill_tail p = e.\n  Proof.\n    intros H; unfold vec_fill_tail; rew vec.\n    destruct (le_lt_dec k (pos2nat p)); auto; exfalso; lia.\n  Qed.\n\nEnd vec_fill_tail.\n\nOpaque vec_fill_tail.\n\nFact vec_map_fill_tail X Y (f : X -> Y) n k v e :\n  vec_map f (@vec_fill_tail X n k v e) = vec_fill_tail n (vec_map f v) (f e).\nProof.\n  apply vec_pos_ext; intros p; rew vec.\n  destruct (le_lt_dec k (pos2nat p)) as [ | Hp ].\n  + do 2 (rewrite vec_fill_tail_ge; auto).\n  + do 2 rewrite vec_fill_tail_lt with (Hp := Hp); rew vec.\nQed.\n\nSection vec_first_half.\n\n  Variable (X : Type) (n : nat) (k : nat) (Hk : k <= n).\n\n  Definition vec_first_half (v : vec X n) : vec X k.\n  Proof using Hk.\n    apply vec_set_pos; intros p.\n    refine (vec_pos v (@nat2pos _ (pos2nat p) _)).\n    apply Nat.lt_le_trans with (2 := Hk), pos2nat_prop.\n  Defined.\n\n  Fact vec_first_half_fill_tail v e : vec_first_half (vec_fill_tail _ v e) = v.\n  Proof.\n    apply vec_pos_ext; intros p.\n    unfold vec_first_half; rew vec.\n    match goal with \n      | |- vec_pos _ ?p = _ => assert (H : pos2nat p < k)\n    end.\n    { rewrite pos2nat_nat2pos; apply pos2nat_prop. }\n    rewrite vec_fill_tail_lt with (Hp := H).\n    revert H.\n    rewrite pos2nat_nat2pos.\n    intros; f_equal; apply nat2pos_pos2nat.\n  Qed.\n\nEnd vec_first_half.\n\nSection Sig_uniformize_rels.\n\n  Variable (Σ : fo_signature) (n : nat) (Hn : forall r, ar_rels Σ r <= n).\n\n  Definition Σunif : fo_signature.\n  Proof using Σ n.\n    exists (syms Σ) (rels Σ).\n    + exact (ar_syms Σ).\n    + exact (fun _ => n).\n  Defined.\n\n  Notation Σ' := Σunif.\n\n  Fixpoint fol_uniformize (A : fol_form Σ) : fol_form Σ' :=\n    match A with\n      | ⊥                => ⊥\n      | @fol_atom _ r v  => @fol_atom Σ' r (vec_fill_tail _ v (£0))\n      | fol_bin c A B    => fol_bin c (fol_uniformize A) (fol_uniformize B)\n      | fol_quant q A    => fol_quant q (fol_uniformize A)\n    end.\n\n  Variable (X : Type) (e : X).\n\n  Section soundness.\n\n    Variables (M : fo_model Σ X).\n\n    Local Definition fom_uniformize : fo_model Σ' X.\n    Proof using M Hn.\n      split.\n      + intros s; apply (fom_syms M s).\n      + intros r v; exact (fom_rels M r (vec_first_half (Hn r) v)).\n    Defined.\n\n    Notation M' := fom_uniformize.\n\n    Theorem fol_uniformize_sound A φ : \n        fol_sem M φ A <-> fol_sem M' φ (fol_uniformize A).\n    Proof.\n      revert φ; induction A as [ | r v | A HA B HB | q A HA ]; simpl; try tauto; intros phi.\n      + apply fol_equiv_ext; f_equal.\n        rewrite vec_map_fill_tail, vec_first_half_fill_tail; auto.\n      + apply fol_bin_sem_ext; auto.\n      + apply fol_quant_sem_ext; auto.\n    Qed.\n\n  End soundness.\n\n  Variable (lr : list (rels Σ)).\n\n  Section completeness.\n  \n    Variable (M' : fo_model Σ' X).\n\n    Local Definition fom_specialize : fo_model Σ X.\n    Proof using M' e.\n      split.\n      + intros s; apply (fom_syms M' s).\n      + intros r v; exact (fom_rels M' r (vec_fill_tail n v e)).\n    Defined.\n\n    Notation M := fom_specialize.\n\n    Section uniform_after.\n\n      Variable (r : rels Σ).\n\n      Let k := ar_rels _ r.\n      \n      Let w1 : vec (fol_term Σ') _ := \n           vec_fill_tail n (vec_set_pos (fun p : pos k => £(2+pos2nat p))) (£ 1).\n      Let w2 : vec (fol_term Σ') _ := \n           vec_fill_tail n (vec_set_pos (fun p : pos k => £(2+pos2nat p))) (£ 0).\n\n      Local Definition fol_uniform_after : fol_form Σ' :=\n           fol_mquant fol_fa k (∀∀ @fol_atom Σ' r w1 ↔ @fol_atom Σ' r w2).\n\n      Local Fact fol_uniform_after_spec φ :\n           fol_sem M' φ fol_uniform_after \n       <-> forall v e1 e2,  fom_rels M' r (@vec_fill_tail _ n k v e1) \n                        <-> fom_rels M' r (vec_fill_tail n v e2).\n      Proof.\n        unfold fol_uniform_after.\n        rewrite fol_sem_mforall. \n        apply forall_equiv; intros v.\n        rewrite fol_sem_quant_fix.\n        apply forall_equiv; intros e1.\n        rewrite fol_sem_quant_fix.\n        apply forall_equiv; intros e2.\n        apply fol_equiv_sem_ext.\n        + apply fol_equiv_ext; f_equal.\n          unfold w1; rewrite vec_map_fill_tail; simpl; f_equal.\n          apply vec_pos_ext; intros p; rew vec; simpl.\n          rewrite env_vlift_fix0; auto.\n        + apply fol_equiv_ext; f_equal.\n          unfold w2; rewrite vec_map_fill_tail; simpl; f_equal.\n          apply vec_pos_ext; intros p; rew vec; simpl.\n          rewrite env_vlift_fix0; auto.\n      Qed.\n\n    End uniform_after.\n\n    Local Definition fol_all_uniform_after : fol_form Σ' :=\n             fol_lconj (map fol_uniform_after lr).\n\n    Let uniform := forall r, In r lr -> forall (v : vec _ (ar_rels _ r)) e1 e2, \n                            fom_rels M' r (vec_fill_tail n v e1) \n                        <-> fom_rels M' r (vec_fill_tail n v e2).\n \n    Local Fact fol_all_uniform_after_spec φ : \n            fol_sem M' φ fol_all_uniform_after <-> uniform.\n    Proof.\n      unfold fol_all_uniform_after.\n      rewrite fol_sem_lconj; unfold uniform.\n      split.\n      + intros H r Hr.\n        apply (fol_uniform_after_spec _ φ), H, in_map_iff.\n        exists r; auto.\n      + intros H f; rewrite in_map_iff.\n        intros (r & <- & Hr); apply fol_uniform_after_spec, H; auto.\n    Qed. \n\n    Hypothesis Hlr : uniform.\n\n    Theorem fol_uniformize_complete A φ : \n          incl (fol_rels A) lr\n       -> fol_sem M φ A <-> fol_sem M' φ (fol_uniformize A).\n    Proof using Hlr.\n      revert φ; induction A as [ | r v | b A HA B HB | q A HA ]; simpl; try tauto; intros phi Hr.\n      + rewrite vec_map_fill_tail; rew fot.\n        apply Hlr, Hr; simpl; auto.\n      + apply fol_bin_sem_ext; auto.\n        * apply HA; intros ? ?; apply Hr, in_app_iff; auto.\n        * apply HB; intros ? ?; apply Hr, in_app_iff; auto.\n      + apply fol_quant_sem_ext; auto.\n    Qed.\n\n  End completeness.\n\n  Variable (A : fol_form Σ) (HA : incl (fol_rels A) lr).\n\n  Definition Σuniformize := fol_all_uniform_after ⟑ fol_uniformize A.\n\n  Theorem Σuniformize_sound : fo_form_fin_dec_SAT_in A X\n                           -> fo_form_fin_dec_SAT_in Σuniformize X.\n  Proof using Hn.\n    intros (M & H1 & H2 & phi & H).\n    exists (fom_uniformize M), H1.\n    exists.\n    { intros ? ?; apply H2. }\n    exists phi; split.\n    + apply fol_all_uniform_after_spec.\n      intros r _ v e1 e2; simpl.\n      do 2 rewrite vec_first_half_fill_tail; tauto.\n    + revert H; apply fol_uniformize_sound.\n  Qed.\n\n  Theorem Σuniformize_complete : fo_form_fin_dec_SAT_in Σuniformize X\n                              -> fo_form_fin_dec_SAT_in A X.\n  Proof using e HA.\n    intros (M' & H1 & H2 & phi & H3 & H4).\n    rewrite fol_all_uniform_after_spec in H3.\n    exists (fom_specialize M'), H1.\n    exists.\n    { intros ? ?; apply H2. }\n    exists phi.\n    revert H4.\n    apply fol_uniformize_complete; auto.\n  Qed.\n\nEnd Sig_uniformize_rels.\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/Sig_uniform.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6657578593483189}}
{"text": "Require Import ZArith.\nRequire Import ASN1FP.Conversion.IEEE_ASN.\n\nOpen Scope Z.\n\n(*\n * auxiliary functions for the most common formats\n * combining partial conversions into one full pass\n *)\n\nSection B32.\n\n  Let prec := 24.\n  Let emax := 128.\n  Let prec_gt_1 : prec > 1.\n  Proof. reflexivity. Qed.\n  Let prec_lt_emax : prec < emax.\n  Proof. subst prec. subst emax. reflexivity. Qed.\n\n  Definition normalize_b32_abstract (m e : Z) :=\n    let '(mx, ex) := normalize_IEEE_finite prec emax (Z.to_pos m) e in\n    (Zpos mx, ex).\n  \n  Definition BER_of_b32_abstract := BER_of_IEEE_exact prec emax.\n\n  Definition b32_of_BER_abstract_exact := IEEE_of_BER_exact prec emax prec_gt_1.\n\n  Definition b32_of_BER_abstract_rounded := IEEE_of_BER_rounded prec emax prec_gt_1 prec_lt_emax.\n\nEnd B32.\n\nSection B64.\n\n  Let prec := 53%Z.\n  Let emax := 1024%Z.\n  Let prec_gt_1 : prec > 1.\n  Proof. reflexivity. Qed.\n  Let prec_lt_emax : prec < emax.\n  Proof. subst prec. subst emax. reflexivity. Qed.\n  \n  Definition normalize_b64_abstract (m e : Z) :=\n    let '(mx, ex) := normalize_IEEE_finite prec emax (Z.to_pos m) e in\n    (Zpos mx, ex).\n\n  Definition BER_of_b64_abstract := BER_of_IEEE_exact prec emax.\n\n  Definition b64_of_BER_abstract_exact := IEEE_of_BER_exact prec emax prec_gt_1.\n\n  Definition b64_of_BER_abstract_rounded := IEEE_of_BER_rounded prec emax prec_gt_1 prec_lt_emax.\n\nEnd B64.\n", "meta": {"author": "digamma-ai", "repo": "asn1fpcoq", "sha": "05094f3824393aeb74e58e4b84f570529a55799c", "save_path": "github-repos/coq/digamma-ai-asn1fpcoq", "path": "github-repos/coq/digamma-ai-asn1fpcoq/asn1fpcoq-05094f3824393aeb74e58e4b84f570529a55799c/coq/Conversion/Full/Abstract.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6657578377916856}}
{"text": "(* First, let us look at some example : *)\n\nLemma P3Q : forall P Q : Prop, (((P->Q)->Q)->Q) -> P -> Q.\nProof.\n intros P Q H p; apply H. \n intro H0;apply H0;assumption. \nQed.\n\nLemma triple_neg : forall P:Prop, ~~~P -> ~P.\nProof.\n intros P ;unfold not; apply P3Q.\nQed.\n\n\nLemma all_perm :\n forall (A:Type) (P:A -> A -> Prop),\n   (forall x y:A, P x y) -> \n   forall x y:A, P y x.\nProof.\nAdmitted.\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.\nAdmitted.\n\n\nLemma not_ex_forall_not : forall (A: Type) (P: A -> Prop),\n                      ~(exists x, P x) <-> forall x, ~ P x.\nProof.\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", "meta": {"author": "wdomitrz", "repo": "Coq-Exercises", "sha": "86d6ae9488901a0f61d45234a6b1c2c684cf60ef", "save_path": "github-repos/coq/wdomitrz-Coq-Exercises", "path": "github-repos/coq/wdomitrz-Coq-Exercises/Coq-Exercises-86d6ae9488901a0f61d45234a6b1c2c684cf60ef/ZPF/Lab19/Lab2/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6656366564384578}}
{"text": "(* Suzuki, Michio - Group Theory. I *)\nFrom mathcomp\n  Require Import ssreflect.\nRequire Import Coq.Logic.Description.\nRequire Import Coq.Logic.FinFun.\nRequire Import Coq.Logic.Classical_Prop.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.JMeq.\nRequire Import Coq.Program.Basics.\n\n(* Definition 1.1. *)\nStructure group : Type := make_group\n{\n  group_carrier : Set;\n  group_inhab : inhabited group_carrier;\n  group_mul : group_carrier -> group_carrier -> group_carrier;\n  group_mul_assoc : forall a b c : group_carrier, group_mul (group_mul a b) c = group_mul a (group_mul b c);\n  group_r_trans : forall a b : group_carrier, exists x : group_carrier, group_mul a x = b;\n  group_l_trans : forall a b : group_carrier, exists y : group_carrier, group_mul y a = b;\n}.\n\nTheorem group_eq (G0 G1 : group) :\n  group_carrier G0 = group_carrier G1\n  -> JMeq (group_mul G0) (group_mul G1)\n  -> G0 = G1.\nProof.\n  move=> Hcarrier Hmul.\n  destruct G0 as [carrier0 inhab0 mul0 mul_assoc0 r_trans0 l_trans0].\n  destruct G1 as [carrier1 inhab1 mul1 mul_assoc1 r_trans1 l_trans1].\n  simpl in * |- *.\n  destruct Hcarrier.\n  apply JMeq_eq in Hmul.\n  destruct Hmul.\n  f_equal; apply proof_irrelevance.\nQed.\n\n(* Definition 1.3. *)\nDefinition is_group_one (G : group) (e : group_carrier G) :=\n  forall g : group_carrier G, group_mul G g e = g /\\ group_mul G e g = g.\n\n(* Theorem 1.2.(ii)' *)\nTheorem group_one_ex_uni (G : group) :\n  exists! group_one : group_carrier G, is_group_one G group_one.\nProof.\n  destruct (group_inhab G) as [a].\n  destruct (group_r_trans G a a) as [e Hae_eq_a].\n  destruct (group_l_trans G a a) as [e' He'a_eq_a].\n  exists e.\n\n  assert (forall g : group_carrier G, group_mul G g e = g) as He_oner.\n  + move=> g.\n    destruct (group_r_trans G a g) as [u Hau_eq_g].\n    destruct (group_l_trans G a g) as [v Hva_eq_g].\n    rewrite -Hva_eq_g.\n    rewrite group_mul_assoc.\n    rewrite Hae_eq_a.\n    by [].\n\n  assert (forall g : group_carrier G, group_mul G e' g = g) as He'_onel.\n  + move=> g.\n    destruct (group_r_trans G a g) as [u Hau_eq_g].\n    destruct (group_l_trans G a g) as [v Hva_eq_g].\n    rewrite -Hau_eq_g.\n    rewrite -group_mul_assoc.\n    rewrite He'a_eq_a.\n    by [].\n\n  assert (e = e') as He_eq_e'.\n  + rewrite -(He_oner e').\n    rewrite (He'_onel e).\n    by [].\n\n  split.\n  + move=> g.\n    split.\n    + apply (He_oner g).\n    + rewrite He_eq_e'.\n      rewrite (He'_onel g).\n      by [].\n  + move=> g Hg_one.\n    destruct (Hg_one e) as [Heg_eq_e Hge_eq_e].\n    rewrite -(He_oner g).\n    rewrite Hge_eq_e.\n    by [].\nQed.\n\nDefinition group_one (G : group) : group_carrier G\n  := let 'exist one Hone := (constructive_definite_description (is_group_one G) (group_one_ex_uni G)) in one.\n\nTheorem group_one_is_group_one (G : group) : is_group_one G (group_one G).\nProof.\n  remember (group_one G) as e eqn: H.\n  unfold group_one in H.\n  destruct (constructive_definite_description (is_group_one G) (group_one_ex_uni G)) as [e' He'] in H.\n  rewrite H.\n  exact He'.\nQed.\n\nDefinition are_mut_inv (G : group) (a a' : group_carrier G) :=\n  group_mul G a a' = group_one G /\\ group_mul G a' a = group_one G.\n\n(* Theorem 1.2.(ii)'' *)\nTheorem group_inv_ex_uni (G : group) (a : group_carrier G) :\n  exists! a' : group_carrier G, are_mut_inv G a a'.\nProof.\n  destruct (group_r_trans G a (group_one G)) as [a' Haa'_eq_one].\n  destruct (group_l_trans G a (group_one G)) as [a'' Ha''a_eq_one].\n\n  assert (a' = a'') as Ha'_eq_a''.\n  + rewrite -(proj1 ((group_one_is_group_one G) a'')).\n    rewrite -Haa'_eq_one.\n    rewrite -(group_mul_assoc G a'' a a').\n    rewrite Ha''a_eq_one.\n    rewrite (proj2 ((group_one_is_group_one G) a')).\n    by [].\n\n  rewrite -Ha'_eq_a'' in Ha''a_eq_one.\n  exists a'.\n\n  split.\n  + split.\n    + exact Haa'_eq_one.\n    + exact Ha''a_eq_one.\n  + move=> a''' [Hax_eq_one Hxa_eq_one].\n    rewrite -(proj1 ((group_one_is_group_one G) a')).\n    rewrite -Hax_eq_one.\n    rewrite -(group_mul_assoc G a' a a''').\n    rewrite Ha''a_eq_one.\n    rewrite (proj2 ((group_one_is_group_one G) a''')).\n    by [].\nQed.\n\nDefinition group_inv (G : group) : group_carrier G -> group_carrier G\n  := fun a => let 'exist a' Ha' := (constructive_definite_description (are_mut_inv G a) (group_inv_ex_uni G a)) in a'.\n\nTheorem group_inv_is_group_inv (G : group) (a : group_carrier G) : are_mut_inv G a (group_inv G a).\nProof.\n  remember (group_inv G a) as a' eqn: H.\n  unfold group_inv in H.\n  destruct (constructive_definite_description (are_mut_inv G a) (group_inv_ex_uni G a)) as [a'' Ha''] in H.\n  rewrite H.\n  exact Ha''.\nQed.\n\nTheorem group_one_mul (G : group) :\n  forall a : group_carrier G,\n  group_mul G (group_one G) a = a.\nProof.\n  move=> a.\n  exact (proj2 ((group_one_is_group_one G) a)).\nQed.\n\nTheorem group_mul_one (G : group) :\n  forall a : group_carrier G,\n  group_mul G a (group_one G) = a.\nProof.\n  move=> a.\n  exact (proj1 ((group_one_is_group_one G) a)).\nQed.\n\nTheorem group_inv_mul (G : group) :\n  forall a : group_carrier G,\n  group_mul G (group_inv G a) a = group_one G.\nProof.\n  move=> a.\n  exact (proj2 ((group_inv_is_group_inv G) a)).\nQed.\n\nTheorem group_mul_inv (G : group) :\n  forall a : group_carrier G,\n  group_mul G a (group_inv G a) = group_one G.\nProof.\n  move=> a.\n  exact (proj1 ((group_inv_is_group_inv G) a)).\nQed.\n\nTheorem group_one_inv (G : group) :\n  group_inv G (group_one G) = group_one G.\nProof.\n  pose proof (group_inv_ex_uni G (group_one G)) as Hex_uni.\n  rewrite <- unique_existence in Hex_uni.\n  destruct Hex_uni as [Hex Huni].\n  apply (Huni (group_inv G (group_one G)) (group_one G)).\n  + exact (group_inv_is_group_inv G (group_one G)).\n  + split; rewrite group_one_mul; reflexivity.\nQed.\n\n(* Theorem 1.2.(iii).1 *)\nTheorem group_r_trans_ex_uni (G : group) :\n  forall a b x : group_carrier G, group_mul G a x = b -> x = group_mul G (group_inv G a) b.\nProof.\n  move=> a b x Hax_eq_b.\n  rewrite -Hax_eq_b.\n  rewrite -group_mul_assoc.\n  rewrite (proj2 (group_inv_is_group_inv G a)).\n  rewrite (proj2 (group_one_is_group_one G x)).\n  reflexivity.\nQed.\n\n(* Theorem 1.2.(iii).2 *)\nTheorem group_l_trans_ex_uni (G : group) :\n  forall a b y : group_carrier G, group_mul G y a = b -> y = group_mul G b (group_inv G a).\nProof.\n  move=> a b y Hya_eq_b.\n  rewrite -Hya_eq_b.\n  rewrite group_mul_assoc.\n  rewrite (proj1 (group_inv_is_group_inv G a)).\n  rewrite (proj1 (group_one_is_group_one G y)).\n  reflexivity.\nQed.\n\n(* Corollary_p4_l7 *)\nStructure group' : Type := make_group'\n{\n  group'_carrier : Set;\n  group'_one : group'_carrier;\n  group'_inv : group'_carrier -> group'_carrier;\n  group'_mul : group'_carrier -> group'_carrier -> group'_carrier;\n  group'_mul_assoc : forall a b c : group'_carrier, group'_mul (group'_mul a b) c = group'_mul a (group'_mul b c);\n  group'_one_mul : forall a : group'_carrier, group'_mul group'_one a = a;\n  group'_mul_one : forall a : group'_carrier, group'_mul a group'_one = a;\n  group'_inv_mul : forall a : group'_carrier, group'_mul (group'_inv a) a = group'_one;\n  group'_mul_inv : forall a : group'_carrier, group'_mul a (group'_inv a) = group'_one;\n}.\n\nTheorem group'_eq (G0 G1 : group') :\n  group'_carrier G0 = group'_carrier G1\n  -> JMeq (group'_mul G0) (group'_mul G1)\n  -> G0 = G1.\nProof.\n  move => Hcarrier Hmul.\n  destruct G0 as [carrier0 one0 inv0 mul0 mul_assoc0 one_mul0 mul_one0 inv_mul0 mul_inv0].\n  destruct G1 as [carrier1 one1 inv1 mul1 mul_assoc1 one_mul1 mul_one1 inv_mul1 mul_inv1].\n  simpl in * |- *.\n  destruct Hcarrier.\n  apply JMeq_eq in Hmul.\n  destruct Hmul.\n\n  assert (one0 = one1) as Hone.\n  + rewrite -(one_mul0 one1).\n    rewrite (mul_one1 one0).\n    reflexivity.\n  destruct Hone.\n\n  assert (inv0 = inv1) as Hinv.\n  + apply functional_extensionality.\n    move=> x.\n    rewrite -(mul_one0 (inv0 x)).\n    rewrite -(mul_inv1 x).\n    rewrite -mul_assoc0.\n    rewrite (inv_mul0 x).\n    rewrite (one_mul0 (inv1 x)).\n    reflexivity.\n  destruct Hinv.\n\n  f_equal; apply proof_irrelevance.\nQed.\n\nDefinition group_to_group' : group -> group'\n  := fun G => (make_group'\n    (group_carrier G)\n    (group_one G)\n    (group_inv G)\n    (group_mul G)\n    (group_mul_assoc G)\n    (fun a => proj2 (group_one_is_group_one G a))\n    (fun a => proj1 (group_one_is_group_one G a))\n    (fun a => proj2 (group_inv_is_group_inv G a))\n    (fun a => proj1 (group_inv_is_group_inv G a))\n  ).\n\nTheorem group'_to_group_sub_r (G' : group') :\n  forall a b : group'_carrier G', exists x : group'_carrier G', group'_mul G' a x = b.\nProof.\n  move=> a b.\n  exists (group'_mul G' (group'_inv G' a) b).\n  rewrite -group'_mul_assoc.\n  rewrite group'_mul_inv.\n  rewrite group'_one_mul.\n  reflexivity.\nQed.\n\nTheorem group'_to_group_sub_l (G' : group') :\n  forall a b : group'_carrier G', exists y : group'_carrier G', group'_mul G' y a = b.\nProof.\n  move=> a b.\n  exists (group'_mul G' b (group'_inv G' a)).\n  rewrite group'_mul_assoc.\n  rewrite group'_inv_mul.\n  rewrite group'_mul_one.\n  reflexivity.\nQed.\n\nDefinition group'_to_group : group' -> group\n  := fun G' => (make_group\n    (group'_carrier G')\n    (inhabits (group'_one G'))\n    (group'_mul G')\n    (group'_mul_assoc G')\n    (group'_to_group_sub_r G')\n    (group'_to_group_sub_l G')\n  ).\n\nTheorem group_to_group'_to_group_is_id :\n  compose group'_to_group group_to_group' = id.\nProof.\n  apply functional_extensionality.\n  move=> G.\n  destruct G.\n  unfold id.\n  unfold compose.\n  unfold group_to_group'.\n  unfold group'_to_group.\n  simpl.\n  f_equal; apply proof_irrelevance.\nQed.\n\nTheorem group'_to_group_to_group'_is_id :\n  compose group_to_group' group'_to_group = id.\nProof.\n  apply functional_extensionality.\n  move=> G'.\n  destruct G'.\n  unfold id.\n  unfold compose.\n  unfold group_to_group'.\n  unfold group'_to_group.\n  apply group'_eq.\n  simpl.\n  reflexivity.\n  simpl.\n  apply JMeq_refl.\nQed.\n\n(* Theorem 1.4.1 *)\nTheorem inv_inv (G : group) :\n  forall a : group_carrier G, group_inv G (group_inv G a) = a.\nProof.\n  move=> a.\n\n  pose proof (group_inv_ex_uni G (group_inv G a)) as H.\n  rewrite <- unique_existence in H.\n  destruct H as [_ Huni].\n\n  pose proof (group_inv_is_group_inv G (group_inv G a)) as Hinvinva.\n\n  pose proof (group_inv_is_group_inv G a) as Ha.\n  unfold are_mut_inv in Ha.\n  rewrite <- and_comm in Ha.\n  fold (are_mut_inv G (group_inv G a) a) in Ha.\n\n  rewrite -(Huni a (group_inv G (group_inv G a)) Ha Hinvinva).\n  reflexivity.\nQed.\n\n(* Theorem 1.4.2 *)\nTheorem group_mul_inv_rev (G : group) :\n  forall a b : group_carrier G, group_inv G (group_mul G a b) = group_mul G (group_inv G b) (group_inv G a).\nProof.\n  move=> a b.\n\n  pose proof (group_inv_ex_uni G (group_mul G a b)) as H.\n  rewrite <- unique_existence in H.\n  destruct H as [_ Huni].\n\n  pose proof (group_inv_is_group_inv G (group_mul G a b)) as H1.\n\n  assert (are_mut_inv G (group_mul G a b) (group_mul G (group_inv G b) (group_inv G a))) as H2.\n  + split.\n    + rewrite (group_mul_assoc G a b (group_mul G (group_inv G b) (group_inv G a))).\n      rewrite -(group_mul_assoc G b (group_inv G b) (group_inv G a)).\n      rewrite (proj1 (group_inv_is_group_inv G b)).\n      rewrite (proj2 (group_one_is_group_one G (group_inv G a))).\n      rewrite (proj1 (group_inv_is_group_inv G a)).\n      reflexivity.\n    + rewrite (group_mul_assoc G (group_inv G b) (group_inv G a) (group_mul G a b)).\n      rewrite -(group_mul_assoc G (group_inv G a) a b).\n      rewrite (proj2 (group_inv_is_group_inv G a)).\n      rewrite (proj2 (group_one_is_group_one G b)).\n      rewrite (proj2 (group_inv_is_group_inv G b)).\n      reflexivity.\n  exact (Huni (group_inv G (group_mul G a b)) (group_mul G (group_inv G b) (group_inv G a)) H1 H2).\nQed.\n\n(* Definition 2.1 *)\nDefinition subset (S : Set) := S -> Prop.\n\nStructure subgroup (G : group) : Type := make_subgroup\n{\n  subgroup_carrier : subset (group_carrier G);\n  subgroup_inhab : inhabited (sig subgroup_carrier);\n  subgroup_mul_mem : forall a b : group_carrier  G, subgroup_carrier a -> subgroup_carrier b -> subgroup_carrier (group_mul G a b);\n  subgroup_inv_mem : forall a : group_carrier G, subgroup_carrier a -> subgroup_carrier (group_inv G a);\n}.\n\n(* (2.2).(a) *)\nTheorem subgroup_one_mem (G : group) (H : subgroup G) :\n  subgroup_carrier G H (group_one G).\nProof.\n  destruct (subgroup_inhab G H) as [Hinhab].\n  destruct Hinhab as [a Ha_in_H].\n\n  pose proof (subgroup_inv_mem G H a Ha_in_H) as Hainv_in_H.\n  pose proof (subgroup_mul_mem G H a (group_inv G a) Ha_in_H Hainv_in_H) as Hmul_in_H.\n  rewrite (proj1 (group_inv_is_group_inv G a)) in Hmul_in_H.\n  exact Hmul_in_H.\nQed.\n\nDefinition subgroup_incl (G : group) (H : subgroup G) :\n  (sig (subgroup_carrier G H)) -> group_carrier G\n  := fun p => let 'exist x Hx := p in x.\n\nTheorem subgroup_incl_is_injective (G : group) (H : subgroup G) :\n  Injective (subgroup_incl G H).\nProof.\n  move=> [x Hx] [y Hy] Heq.\n  unfold subgroup_incl in Heq.\n  move: Hx Hy.\n  rewrite -Heq.\n  move=> Hx Hy.\n  apply f_equal.\n  apply proof_irrelevance.\nQed.\n\nDefinition subgroup_mul (G : group) (H : subgroup G) :\n  (sig (subgroup_carrier G H)) -> (sig (subgroup_carrier G H)) -> (sig (subgroup_carrier G H))\n  := fun p q =>\n    let 'exist a Ha := p in\n    let 'exist b Hb := q in\n      (exist (subgroup_carrier G H) (group_mul G a b) (subgroup_mul_mem G H a b Ha Hb)).\n\nTheorem subgroup_mul_assoc (G : group) (H : subgroup G) :\n  forall a b c : (sig (subgroup_carrier G H)),\n    subgroup_mul G H (subgroup_mul G H a b) c =\n      subgroup_mul G H a (subgroup_mul G H b c).\nProof.\n  move=> [a Ha] [b Hb] [c Hc].\n  apply (subgroup_incl_is_injective G H).\n  unfold subgroup_mul.\n  unfold subgroup_incl.\n  exact (group_mul_assoc G a b c).\nQed.\n\nTheorem subgroup_group_r_trans (G : group) (H : subgroup G) :\n  forall a b : (sig (subgroup_carrier G H)),\n  exists x : (sig (subgroup_carrier G H)),\n  subgroup_mul G H a x = b.\nProof.\n  move=> [a Ha] [b Hb].\n\n  set (c := group_mul G (group_inv G a) b).\n  set (Hc := subgroup_mul_mem G H (group_inv G a) b (subgroup_inv_mem G H a Ha) Hb).\n\n  exists (exist (subgroup_carrier G H) c Hc).\n\n  apply (subgroup_incl_is_injective G H).\n  unfold subgroup_mul.\n  unfold subgroup_incl.\n  unfold c.\n  rewrite -(group_mul_assoc G).\n  rewrite (group_mul_inv G).\n  rewrite (group_one_mul G).\n  reflexivity.\nQed.\n\nTheorem subgroup_group_l_trans (G : group) (H : subgroup G) :\n  forall a b : (sig (subgroup_carrier G H)),\n  exists y : (sig (subgroup_carrier G H)),\n  subgroup_mul G H y a = b.\nProof.\n  move=> [a Ha] [b Hb].\n\n  set (c := group_mul G b (group_inv G a)).\n  set (Hc := subgroup_mul_mem G H b (group_inv G a) Hb (subgroup_inv_mem G H a Ha)).\n\n  exists (exist (subgroup_carrier G H) c Hc).\n\n  apply (subgroup_incl_is_injective G H).\n  unfold subgroup_mul.\n  unfold subgroup_incl.\n  unfold c.\n  rewrite (group_mul_assoc G).\n  rewrite (group_inv_mul G).\n  rewrite (group_mul_one G).\n  reflexivity.\nQed.\n\n(* (2.2).(b) *)\nDefinition subgroup_to_group (G : group) :\n  (subgroup G) -> group\n  := fun H => (make_group\n    (sig (subgroup_carrier G H))\n    (subgroup_inhab G H)\n    (subgroup_mul G H)\n    (subgroup_mul_assoc G H)\n    (subgroup_group_r_trans G H)\n    (subgroup_group_l_trans G H)\n  ).\n\n(* (2.2).(c).1 *)\nTheorem subgroup_one_is_group_one (G : group) (H : subgroup G) :\n  subgroup_incl G H (group_one (subgroup_to_group G H)) = group_one G.\nProof.\n  pose proof (group_one_ex_uni (subgroup_to_group G H)) as Hone_ex_uni.\n  rewrite <- unique_existence in Hone_ex_uni.\n  destruct Hone_ex_uni as [Hone_ex Hone_uni].\n\n  set (one0 := group_one (subgroup_to_group G H)).\n  set (one1 := (exist (subgroup_carrier G H) (group_one G) (subgroup_one_mem G H))).\n  assert (one0 = one1) as Hyp0.\n  + assert (is_group_one (subgroup_to_group G H) one1) as His_one.\n    + move=> x.\n      destruct x as [x Hx].\n      split.\n      + apply subgroup_incl_is_injective.\n        simpl.\n        rewrite (group_mul_one G).\n        reflexivity.\n      + apply subgroup_incl_is_injective.\n        simpl.\n        rewrite (group_one_mul G).\n        reflexivity.\n    + exact (Hone_uni one0 one1 (group_one_is_group_one (subgroup_to_group G H)) His_one).\n\n  rewrite Hyp0.\n  simpl.\n  reflexivity.\nQed.\n\n(* (2.2).(c).2 *)\nTheorem subgroup_inv_is_group_inv (G : group) (H : subgroup G) :\n  compose (subgroup_incl G H) (group_inv (subgroup_to_group G H))\n  = compose (group_inv G) (subgroup_incl G H).\nProof.\n  apply functional_extensionality.\n  move=> [x Hx].\n  unfold compose.\n  simpl.\n\n  pose proof (group_inv_ex_uni (subgroup_to_group G H) (exist (subgroup_carrier G H) x Hx)) as Hinv_ex_uni.\n  rewrite <- unique_existence in Hinv_ex_uni.\n  destruct Hinv_ex_uni as [Hinv_ex Hinv_uni].\n\n  set (inv0 := group_inv (subgroup_to_group G H) (exist (subgroup_carrier G H) x Hx)).\n  set (inv1 := (exist (subgroup_carrier G H) (group_inv G (subgroup_incl G H (exist (subgroup_carrier G H) x Hx))) (subgroup_inv_mem G H x Hx))).\n  assert (inv0 = inv1) as Hyp0.\n  + assert (are_mut_inv (subgroup_to_group G H) (exist (subgroup_carrier G H) x Hx) inv1) as His_inv.\n    + split.\n      + apply subgroup_incl_is_injective.\n        simpl.\n        rewrite (group_mul_inv G).\n        rewrite (subgroup_one_is_group_one G H).\n        reflexivity.\n      + apply subgroup_incl_is_injective.\n        simpl.\n        rewrite (group_inv_mul G).\n        rewrite (subgroup_one_is_group_one G H).\n        reflexivity.\n    + exact (Hinv_uni inv0 inv1 (group_inv_is_group_inv (subgroup_to_group G H) (exist (subgroup_carrier G H) x Hx)) His_inv).\n\n  rewrite Hyp0.\n  simpl.\n  reflexivity.\nQed.\n\n(* (2.3).1 *)\nDefinition maximum_subgroup_carrier (G : group) : subset (group_carrier G)\n  := fun x => True.\n\nTheorem maximum_subgroup_inhab (G : group) :\n  inhabited (sig (maximum_subgroup_carrier G)).\nProof.\n  destruct (group_inhab G) as [x].\n\n  assert (maximum_subgroup_carrier G x) as Hyp.\n  + unfold maximum_subgroup_carrier.\n    exact.\n  exact (inhabits (exist (maximum_subgroup_carrier G) x Hyp)).\nQed.\n\nTheorem maximum_subgroup_mul_mem (G : group) :\n  forall a b : group_carrier G,\n  maximum_subgroup_carrier G a ->\n  maximum_subgroup_carrier G b ->\n  maximum_subgroup_carrier G (group_mul G a b).\nProof.\n  move=> a b Ha Hb.\n  unfold maximum_subgroup_carrier.\n  exact I.\nQed.\n\nTheorem maximum_subgroup_inv_mem (G : group) :\n  forall a : group_carrier G,\n  maximum_subgroup_carrier G a ->\n  maximum_subgroup_carrier G (group_inv G a).\nProof.\n  move=> a Ha.\n  unfold maximum_subgroup_carrier.\n  exact I.\nQed.\n\nDefinition maximum_subgroup (G : group) : subgroup G\n  := (make_subgroup G\n    (maximum_subgroup_carrier G)\n    (maximum_subgroup_inhab G)\n    (maximum_subgroup_mul_mem G)\n    (maximum_subgroup_inv_mem G)\n  ).\n\n(* (2.3).2 *)\nDefinition minimum_subgroup_carrier (G : group) : subset (group_carrier G)\n  := fun x => x = group_one G.\n\nTheorem minimum_subgroup_carrier_sub0 (G : group) :\n  forall x : group_carrier G,\n  minimum_subgroup_carrier G x\n  -> x = group_one G.\nProof.\n  move=> x Hx.\n  unfold minimum_subgroup_carrier in Hx.\n  exact Hx.\nQed.\n\nTheorem minimum_subgroup_inhab (G : group) :\n  inhabited (sig (minimum_subgroup_carrier G)).\nProof.\n  set (one := group_one G).\n  assert (minimum_subgroup_carrier G one) as Hyp.\n  + unfold minimum_subgroup_carrier.\n    unfold one.\n    reflexivity.\n  exact (inhabits (exist (minimum_subgroup_carrier G) one Hyp)).\nQed.\n\nTheorem minimum_subgroup_mul_mem (G : group) :\n  forall a b : group_carrier G,\n  minimum_subgroup_carrier G a ->\n  minimum_subgroup_carrier G b ->\n  minimum_subgroup_carrier G (group_mul G a b).\nProof.\n  unfold minimum_subgroup_carrier.\n  move=> a b Ha Hb.\n  rewrite Ha Hb.\n  rewrite group_mul_one.\n  reflexivity.\nQed.\n\nTheorem minimum_subgroup_inv_mem (G : group) :\n  forall a : group_carrier G,\n  minimum_subgroup_carrier G a ->\n  minimum_subgroup_carrier G (group_inv G a).\nProof.\n  unfold minimum_subgroup_carrier.\n  move=> a Ha.\n  rewrite Ha.\n  exact (group_one_inv G).\nQed.\n\nDefinition minimum_subgroup (G : group) : subgroup G\n  := (make_subgroup G\n    (minimum_subgroup_carrier G)\n    (minimum_subgroup_inhab G)\n    (minimum_subgroup_mul_mem G)\n    (minimum_subgroup_inv_mem G)\n  ).\n\nDefinition is_proper_subset (S : Set) (T : subset S) :=\n  exists s : S, ~(T s).\n\n(* Definition 2.4 *)\nDefinition is_proper_subgroup (G : group) (H : subgroup G) :=\n  is_proper_subset (group_carrier G) (subgroup_carrier G H).\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/Michio Suzuki (1982) Group Theory I/main.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800691997339971, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.665489583715944}}
{"text": "Require Import Coq.Logic.ClassicalFacts.\n\nRequire Import Notation.\nRequire Import GeneralTactics.\nRequire Import Axioms.Classical.\n\nRequire Export Coq.Logic.FunctionalExtensionality.\nRequire Export Coq.Logic.PropExtensionality.\n\n(* Modified from `Coq.Logic.FunctionalExtensionality` to include propositional\n   extensionality\n *)\nTactic Notation \"extensionality\" :=\n  match goal with\n    [ |- ?X = ?Y ] =>\n    (apply (propositional_extensionality X Y) ||\n     apply (@functional_extensionality _ _ X Y) ||\n     apply (@functional_extensionality_dep _ _ X Y) ||\n     apply forall_extensionalityP ||\n     apply forall_extensionalityS ||\n     apply forall_extensionality)\n  end.\n\nTactic Notation \"extensionality\" ident(x) :=\n  match goal with\n    [ |- ?X = ?Y ] =>\n    ((apply (propositional_extensionality X Y); split) ||\n     apply (@functional_extensionality _ _ X Y) ||\n     apply (@functional_extensionality_dep _ _ X Y) ||\n     apply forall_extensionalityP ||\n     apply forall_extensionalityS ||\n     apply forall_extensionality) ; intro x\n  end.\n\n(* Note, LEM and prop extensionality would also follow from assuming \n   degeneracy. Doing so would lessen our number of axioms. However, \n   having both LEM and prop extensionality axiomitzed individually is \n   a better separation of concerns.\n *)\nTheorem prop_degeneracy : forall A: Prop, \n  A = True \\/ A = False.\nProof using.\n  apply prop_ext_em_degen.\n  - exact propositional_extensionality.\n  - exact classic.\nQed.\n\nLemma true_neq_false : True <> False.\nProof using.\n  intro H.\n  now induction H.\nQed.\n\nLemma provable_is_true : forall A: Prop,\n  A = (A = True).\nProof using.\n  intros *.\n  extensionality H.\n  - now (destruct (prop_degeneracy A); subst).\n  - symmetry in H.\n    now induction H.\nQed.\n\nLemma provable_contradiction_is_false : forall A: Prop,\n  (~A) = (A = False).\nProof using.\n  intros *.\n  extensionality H.\n  - now (destruct (prop_degeneracy A); subst).\n  - intros ?.\n    now induction H.\nQed.\n\nLemma false_is_exfalso : False = forall P: Prop, P.\nProof using.\n  extensionality; split; intros ?.\n  - contradiction.\n  - assumption!.\nQed.\n\n(* convenient rewrite rules from LEM + prop extensionality *)\n\nTheorem rew_NNPP: forall P: Prop,\n  (~~P) = P.\nProof using.\n  intros *.\n  extensionality.\n  split.\n  - apply NNPP.\n  - auto.\nQed.\n\nTheorem rew_not_and : forall P Q: Prop,\n  (~ (P /\\ Q)) = ~P \\/ ~Q.\nProof using.\n  intros *.\n  extensionality H.\n  - now apply not_and_or.\n  - now apply or_not_and.\nQed.\n\nTheorem rew_not_or : forall P Q: Prop,\n  (~ (P \\/ Q)) = ~P /\\ ~Q.\nProof using.\n  intros *.\n  extensionality H.\n  - now apply not_or_and.\n  - now apply and_not_or.\nQed.\n\nTheorem rew_imply_or : forall P Q: Prop,\n  (P -> Q) = ~P \\/ Q.\nProof using.\n  intros *.\n  extensionality H.\n  - now apply imply_to_or.\n  - now apply or_to_imply.\nQed.\n\nTheorem rew_not_all : forall U (P:U -> Prop),\n  (~ forall n, P n) = exists n, ~ P n.\nProof using.\n  intros *.\n  extensionality H.\n  - now apply not_all_ex_not.\n  - now apply ex_not_not_all.\nQed.\n\nTheorem rew_not_ex : forall U (P:U -> Prop),\n  (~ exists n, P n) = forall n, ~ P n.\nProof using.\n  intros *.\n  extensionality H.\n  - now apply not_ex_all_not.\n  - now apply all_not_not_ex.\nQed.\n\n", "meta": {"author": "gjurgensen", "repo": "thesis", "sha": "fee5e9e2ba728f3707eee7ad9d90837c25cf7764", "save_path": "github-repos/coq/gjurgensen-thesis", "path": "github-repos/coq/gjurgensen-thesis/thesis-fee5e9e2ba728f3707eee7ad9d90837c25cf7764/Glib/Axioms/Extensionality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6654886950663439}}
{"text": "From Coq Require Import ZArith.\nFrom Coq Require Import ssreflect.\nFrom stdpp Require Import base numbers.\nFrom Perennial.Helpers Require Import Integers.\n\nOpen Scope Z_scope.\nSet Default Goal Selector \"!\".\nSet Default Proof Using \"Type\".\n\nLocal Ltac Zify.zify_post_hook ::= Z.div_mod_to_equations.\n\nLemma mod_add_modulus a k :\n  k ≠ 0 ->\n  a `mod` k = (a + k) `mod` k.\nProof.\n  intros.\n  rewrite -> Z.add_mod by auto.\n  rewrite -> Z.mod_same by auto.\n  rewrite Z.add_0_r.\n  rewrite -> Z.mod_mod by auto.\n  auto.\nQed.\n\nLemma mod_sub_modulus a k :\n  k ≠ 0 ->\n  a `mod` k = (a - k) `mod` k.\nProof.\n  intros.\n  rewrite -> Zminus_mod by auto.\n  rewrite -> Z.mod_same by auto.\n  rewrite Z.sub_0_r.\n  rewrite -> Z.mod_mod by auto.\n  auto.\nQed.\n\nTheorem sum_overflow_check (x y: u64) :\n  int.Z (word.add x y) < int.Z x <-> int.Z x + int.Z y >= 2^64.\nProof.\n  split; intros.\n  - revert H; word_cleanup; intros.\n    rewrite /word.wrap in H1.\n    destruct (decide (int.Z x + int.Z y >= 2^64)); [ auto | exfalso ].\n    lia.\n  - word_cleanup.\n    rewrite /word.wrap.\n    lia.\nQed.\n\nLemma sum_nooverflow_l (x y : u64) :\n  int.Z x ≤ int.Z (word.add x y) →\n  int.Z (word.add x y) = (int.Z x) + (int.Z y).\nProof.\n  intros. word_cleanup. rewrite wrap_small //.\n  split; first word.\n  destruct (Z_lt_ge_dec (int.Z x + int.Z y) (2 ^ 64)) as [Hlt|Hge]; first done.\n  apply sum_overflow_check in Hge.\n  lia.\nQed.\n\nLemma word_add_comm (x y : u64) :\n  word.add x y = word.add y x.\nProof.\n  specialize (@word.ring_theory _ u64_instance.u64 _). intros W.\n  rewrite W.(Radd_comm). done.\nQed.\n\nLemma sum_nooverflow_r (x y : u64) :\n  int.Z y ≤ int.Z (word.add x y) →\n  int.Z (word.add x y) = (int.Z x) + (int.Z y).\nProof.\n  rewrite word_add_comm. intros ?%sum_nooverflow_l.\n  rewrite Z.add_comm //.\nQed.\n\nTheorem word_add1_neq (x: u64) :\n  int.Z x ≠ int.Z (word.add x (U64 1)).\nProof.\n  simpl.\n  destruct (decide (int.Z x + 1 < 2^64)%Z); [ word | ].\n  rewrite word.unsigned_add.\n  change (int.Z (U64 1)) with 1%Z.\n  rewrite /word.wrap.\n  lia.\nQed.\n\n(* avoid leaving it at div_mod_to_equations since it causes some backwards\nincompatibility *)\nLtac Zify.zify_post_hook ::= idtac.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/Helpers/ModArith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6654267570520694}}
{"text": "(** * Poly: Polymorphism and Higher-Order Functions *)\n\n(* Final reminder: Please do not put solutions to the exercises in\n   publicly accessible places.  Thank you!! *)\n\n(* Suppress some annoying warnings from Coq: *)\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Lists_done.\n\n(* ################################################################# *)\n(** * Polymorphism *)\n\n(** In this chapter we continue our development of basic\n    concepts of functional programming.  The critical new ideas are\n    _polymorphism_ (abstracting functions over the types of the data\n    they manipulate) and _higher-order functions_ (treating functions\n    as data).  We begin with polymorphism. *)\n\n(* ================================================================= *)\n(** ** Polymorphic Lists *)\n\n(** For the last couple of chapters, we've been working just\n    with lists of numbers.  Obviously, interesting programs also need\n    to be able to manipulate lists with elements from other types --\n    lists of strings, lists of booleans, lists of lists, etc.  We\n    _could_ just define a new inductive datatype for each of these,\n    for example... *)\n\nInductive boollist : Type :=\n  | bool_nil : boollist\n  | bool_cons : bool -> boollist -> boollist.\n\n(** ... but this would quickly become tedious, partly because we\n    have to make up different constructor names for each datatype, but\n    mostly because we would also need to define new versions of all\n    our list manipulating functions ([length], [rev], etc.) for each\n    new datatype definition. *)\n\n(** To avoid all this repetition, Coq supports _polymorphic_\n    inductive type definitions.  For example, here is a _polymorphic\n    list_ datatype. *)\n\nInductive list (X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\n(** This is exactly like the definition of [natlist] from the\n    previous chapter, except that the [nat] argument to the [cons]\n    constructor has been replaced by an arbitrary type [X], a binding\n    for [X] has been added to the header, and the occurrences of\n    [natlist] in the types of the constructors have been replaced by\n    [list X].  (We can re-use the constructor names [nil] and [cons]\n    because the earlier definition of [natlist] was inside of a\n    [Module] definition that is now out of scope.)\n\n    What sort of thing is [list] itself?  One good way to think\n    about it is that [list] is a _function_ from [Type]s to\n    [Inductive] definitions; or, to put it another way, [list] is a\n    function from [Type]s to [Type]s.  For any particular type [X],\n    the type [list X] is an [Inductive]ly defined set of lists whose\n    elements are of type [X]. *)\n\nCheck list.\n(* ===> list : Type -> Type *)\n\n(** The parameter [X] in the definition of [list] becomes a parameter\n    to the constructors [nil] and [cons] -- that is, [nil] and [cons]\n    are now polymorphic constructors, that need to be supplied with\n    the type of the list they are building. As an example, [nil nat]\n    constructs the empty list of type [nat]. *)\n\nCheck (nil nat).\n(* ===> nil nat : list nat *)\n\n(** Similarly, [cons nat] adds an element of type [nat] to a list of\n    type [list nat]. Here is an example of forming a list containing\n    just the natural number 3.*)\n\nCheck (cons nat 3 (nil nat)).\n(* ===> cons nat 3 (nil nat) : list nat *)\n\n(** What might the type of [nil] be? We can read off the type [list X]\n    from the definition, but this omits the binding for [X] which is\n    the parameter to [list]. [Type -> list X] does not explain the\n    meaning of [X]. [(X : Type) -> list X] comes closer. Coq's\n    notation for this situation is [forall X : Type, list X]. *)\n\nCheck nil.\n(* ===> nil : forall X : Type, list X *)\n\n(** Similarly, the type of [cons] from the definition looks like\n    [X -> list X -> list X], but using this convention to explain the\n    meaning of [X] results in the type [forall X, X -> list X -> list\n    X]. *)\n\nCheck cons.\n(* ===> cons : forall X : Type, X -> list X -> list X *)\n\n(** (Side note on notation: In .v files, the \"forall\" quantifier\n    is spelled out in letters.  In the generated HTML files and in the\n    way various IDEs show .v files (with certain settings of their\n    display controls), [forall] is usually typeset as the usual\n    mathematical \"upside down A,\" but you'll still see the spelled-out\n    \"forall\" in a few places.  This is just a quirk of typesetting:\n    there is no difference in meaning.) *)\n\n(** Having to supply a type argument for each use of a list\n    constructor may seem an awkward burden, but we will soon see\n    ways of reducing that burden. *)\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\n(** (We've written [nil] and [cons] explicitly here because we haven't\n    yet defined the [ [] ] and [::] notations for the new version of\n    lists.  We'll do that in a bit.) *)\n\n(** We can now go back and make polymorphic versions of all the\n    list-processing functions that we wrote before.  Here is [repeat],\n    for example: *)\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\n(** As with [nil] and [cons], we can use [repeat] by applying it\n    first to a type and then to an element of this type (and a number): *)\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity.  Qed.\n\n(** To use [repeat] to build other kinds of lists, we simply\n    instantiate it with an appropriate type parameter: *)\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity.  Qed.\n\n\n\n(** **** Exercise: 2 stars (mumble_grumble)  *)\n(** Consider the following two inductively defined types. *)\n\nModule MumbleGrumble.\n\nInductive mumble : Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\n\nInductive grumble (X:Type) : Type :=\n  | d : mumble -> grumble X\n  | e : X -> grumble X.\n\n(** Which of the following are well-typed elements of [grumble X] for\n    some type [X]?\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 *)\nEnd MumbleGrumble.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_mumble_grumble : option (prod nat string) := None.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Annotation Inference *)\n\n(** Let's write the definition of [repeat] again, but this time we\n    won't specify the types of any of the arguments.  Will Coq still\n    accept it? *)\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0        => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\n(** Indeed it will.  Let's see what type Coq has assigned to [repeat']: *)\n\nCheck repeat'.\n(* ===> forall X : Type, X -> nat -> list X *)\nCheck repeat.\n(* ===> forall X : Type, X -> nat -> list X *)\n\n(** It has exactly the same type as [repeat].  Coq was able\n    to use _type inference_ to deduce what the types of [X], [x], and\n    [count] must be, based on how they are used.  For example, since\n    [X] is used as an argument to [cons], it must be a [Type], since\n    [cons] expects a [Type] as its first argument; matching [count]\n    with [0] and [S] means it must be a [nat]; and so on.\n\n    This powerful facility means we don't always have to write\n    explicit type annotations everywhere, although explicit type\n    annotations are still quite useful as documentation and sanity\n    checks, so we will continue to use them most of the time.  You\n    should try to find a balance in your own code between too many\n    type annotations (which can clutter and distract) and too\n    few (which forces readers to perform type inference in their heads\n    in order to understand your code). *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Argument Synthesis *)\n\n(** To use a polymorphic function, we need to pass it one or\n    more types in addition to its other arguments.  For example, the\n    recursive call in the body of the [repeat] function above must\n    pass along the type [X].  But since the second argument to\n    [repeat] is an element of [X], it seems entirely obvious that the\n    first argument can only be [X] -- why should we have to write it\n    explicitly?\n\n    Fortunately, Coq permits us to avoid this kind of redundancy.  In\n    place of any type argument we can write the \"implicit argument\"\n    [_], which can be read as \"Please try to figure out for yourself\n    what belongs here.\"  More precisely, when Coq encounters a [_], it\n    will attempt to _unify_ all locally available information -- the\n    type of the function being applied, the types of the other\n    arguments, and the type expected by the context in which the\n    application appears -- to determine what concrete type should\n    replace the [_].\n\n    This may sound similar to type annotation inference -- indeed, the\n    two procedures rely on the same underlying mechanisms.  Instead of\n    simply omitting the types of some arguments to a function, like\n\n      repeat' X x count : list X :=\n\n    we can also replace the types with [_]\n\n      repeat' (X : _) (x : _) (count : _) : list X :=\n\n    to tell Coq to attempt to infer the missing information.\n\n    Using implicit arguments, the [repeat] function can be written like\n    this: *)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n(** In this instance, we don't save much by writing [_] instead of\n    [X].  But in many cases the difference in both keystrokes and\n    readability is nontrivial.  For example, suppose we want to write\n    down a list containing the numbers [1], [2], and [3].  Instead of\n    writing this... *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...we can use argument synthesis to write this: *)\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ----------------------------------------------------------------- *)\n(** *** Implicit Arguments *)\n\n(** We can go further and even avoid writing [_]'s in most cases by\n    telling Coq _always_ to infer the type argument(s) of a given\n    function.\n\n    The [Arguments] directive specifies the name of the function (or\n    constructor) and then lists its argument names, with curly braces\n    around any arguments to be treated as implicit.  (If some\n    arguments of a definition don't have a name, as is often the case\n    for constructors, they can be marked with a wildcard pattern\n    [_].) *)\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\n(** Now, we don't have to supply type arguments at all: *)\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\n(** Alternatively, we can declare an argument to be implicit\n    when defining the function itself, by surrounding it in curly\n    braces instead of parens.  For example: *)\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0        => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n(** (Note that we didn't even have to provide a type argument to the\n    recursive call to [repeat''']; indeed, it would be invalid to\n    provide one!)\n\n    We will use the latter style whenever possible, but we will\n    continue to use explicit [Argument] declarations for [Inductive]\n    constructors.  The reason for this is that marking the parameter\n    of an inductive type as implicit causes it to become implicit for\n    the type itself, not just for its constructors.  For instance,\n    consider the following alternative definition of the [list]\n    type: *)\n\nInductive list' {X:Type} : Type :=\n  | nil' : list'\n  | cons' : X -> list' -> list'.\n\n(** Because [X] is declared as implicit for the _entire_ inductive\n    definition including [list'] itself, we now have to write just\n    [list'] whether we are talking about lists of numbers or booleans\n    or anything else, rather than [list' nat] or [list' bool] or\n    whatever; this is a step too far. *)\n\n(** Let's finish by re-implementing a few other standard list\n    functions on our new polymorphic lists... *)\n\nFixpoint app {X : Type} (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity.  Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity.  Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Supplying Type Arguments Explicitly *)\n\n(** One small problem with declaring arguments [Implicit] is\n    that, occasionally, Coq does not have enough local information to\n    determine a type argument; in such cases, we need to tell Coq that\n    we want to give the argument explicitly just this time.  For\n    example, suppose we write this: *)\n\nFail Definition mynil := nil.\n\n(** (The [Fail] qualifier that appears before [Definition] can be\n    used with _any_ command, and is used to ensure that that command\n    indeed fails when executed. If the command does fail, Coq prints\n    the corresponding error message, but continues processing the rest\n    of the file.)\n\n    Here, Coq gives us an error because it doesn't know what type\n    argument to supply to [nil].  We can help it by providing an\n    explicit type declaration (so that Coq has more information\n    available when it gets to the \"application\" of [nil]): *)\n\nDefinition mynil : list nat := nil.\n\n(** Alternatively, we can force the implicit arguments to be explicit by\n   prefixing the function name with [@]. *)\n\nCheck @nil.\n\nDefinition mynil' := @nil nat.\n\n(** Using argument synthesis and implicit arguments, we can\n    define convenient notation for lists, as before.  Since we have\n    made the constructor type arguments implicit, Coq will know to\n    automatically infer these when we use the notations. *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** Now lists can be written just the way we'd hope: *)\n\nDefinition list123''' := [1; 2; 3].\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, optional (poly_exercises)  *)\n(** Here are a few simple exercises, just like ones in the [Lists]\n    chapter, for practice with polymorphism.  Complete the proofs below. *)\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros X l.\n  induction l.\n  - reflexivity.\n  - simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros A l m n.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite IHl. reflexivity.\nQed.\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros X l1 l2.\n  induction l1.\n  - simpl. reflexivity.\n  - simpl. rewrite IHl1. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (more_poly_exercises)  *)\n(** Here are some slightly more interesting ones... *)\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros X l1 l2.\n  induction l1.\n  - simpl. rewrite app_nil_r. reflexivity.\n  - simpl. rewrite IHl1. rewrite app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros X l.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite rev_app_distr. rewrite IHl. simpl. reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Pairs *)\n\n(** Following the same pattern, the type definition we gave in\n    the last chapter for pairs of numbers can be generalized to\n    _polymorphic pairs_, often called _products_: *)\n\nInductive prod (X Y : Type) : Type :=\n| pair : X -> Y -> prod X Y.\n\nArguments pair {X} {Y} _ _.\n\n(** As with lists, we make the type arguments implicit and define the\n    familiar concrete notation. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** We can also use the [Notation] mechanism to define the standard\n    notation for product _types_: *)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** (The annotation [: type_scope] tells Coq that this abbreviation\n    should only be used when parsing types.  This avoids a clash with\n    the multiplication symbol.) *)\n\n(** It is easy at first to get [(x,y)] and [X*Y] confused.\n    Remember that [(x,y)] is a _value_ built from two other values,\n    while [X*Y] is a _type_ built from two other types.  If [x] has\n    type [X] and [y] has type [Y], then [(x,y)] has type [X*Y]. *)\n\n(** The first and second projection functions now look pretty\n    much as they would in any functional programming language. *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\n(** The following function takes two lists and combines them\n    into a list of pairs.  In other functional languages, it is often\n    called [zip]; we call it [combine] for consistency with Coq's\n    standard library. *)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\n(** **** Exercise: 1 star, optional (combine_checks)  *)\n(** Try answering the following questions on paper and\n    checking your answers in Coq:\n    - What is the type of [combine] (i.e., what does [Check\n      @combine] print?)\n    - What does\n\n        Compute (combine [1;2] [false;false;true;true]).\n\n      print? *)\nCheck @combine.\nCompute (combine [1;2] [false;false;true;true]).\n\n(** **** Exercise: 2 stars, recommended (split)  *)\n(** The function [split] is the right inverse of [combine]: it takes a\n    list of pairs and returns a pair of lists.  In many functional\n    languages, it is called [unzip].\n\n    Fill in the definition of [split] below.  Make sure it passes the\n    given unit test. *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) :=\n  match l with\n  | [] => ([], [])\n  | (a, b) :: t => ((a :: fst (split t)), (b :: snd (split t)))\n  end.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Options *)\n\n(** One last polymorphic type for now: _polymorphic options_,\n    which generalize [natoption] from the previous chapter.  (We put\n    the definition inside a module because the standard library\n    already defines [option] and it's this one that we want to use\n    below.) *)\n\nModule OptionPlayground.\n\nInductive option (X:Type) : Type :=\n  | Some : X -> option X\n  | None : option X.\n\nArguments Some {X} _.\nArguments None {X}.\n\nEnd OptionPlayground.\n\n(** We can now rewrite the [nth_error] function so that it works\n    with any type of lists. *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, optional (hd_error_poly)  *)\n(** Complete the definition of a polymorphic version of the\n    [hd_error] function from the last chapter. Be sure that it\n    passes the unit tests below. *)\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n  | [] => None\n  | a :: _ => Some a\n  end.\n\n(** Once again, to force the implicit arguments to be explicit,\n    we can use [@] before the name of the function. *)\n\nCheck @hd_error.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Functions as Data *)\n\n(** Like many other modern programming languages -- including\n    all functional languages (ML, Haskell, Scheme, Scala, Clojure,\n    etc.) -- Coq treats functions as first-class citizens, allowing\n    them to be passed as arguments to other functions, returned as\n    results, stored in data structures, etc.*)\n\n(* ================================================================= *)\n(** ** Higher-Order Functions *)\n\n(** Functions that manipulate other functions are often called\n    _higher-order_ functions.  Here's a simple one: *)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\n(** The argument [f] here is itself a function (from [X] to\n    [X]); the body of [doit3times] applies [f] three times to some\n    value [n]. *)\n\nCheck @doit3times.\n(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity.  Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity.  Qed.\n\n(* ================================================================= *)\n(** ** Filter *)\n\n(** Here is a more useful higher-order function, taking a list\n    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])\n    and \"filtering\" the list, returning a new list containing just\n    those elements for which the predicate returns [true]. *)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | []     => []\n  | h :: t => if test h then h :: (filter test t)\n                        else       filter test t\n  end.\n\n(** For example, if we apply [filter] to the predicate [evenb]\n    and a list of numbers [l], it returns a list containing just the\n    even members of [l]. *)\n\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity.  Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  beq_nat (length l) 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** We can use [filter] to give a concise version of the\n    [countoddmembers] function from the [Lists] chapter. *)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity.  Qed.\n\n(* ================================================================= *)\n(** ** Anonymous Functions *)\n\n(** It is arguably a little sad, in the example just above, to\n    be forced to define the function [length_is_1] and give it a name\n    just to be able to pass it as an argument to [filter], since we\n    will probably never use it again.  Moreover, this is not an\n    isolated example: when using higher-order functions, we often want\n    to pass as arguments \"one-off\" functions that we will never use\n    again; having to give each of these functions a name would be\n    tedious.\n\n    Fortunately, there is a better way.  We can construct a function\n    \"on the fly\" without declaring it at the top level or giving it a\n    name. *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity.  Qed.\n\n(** The expression [(fun n => n * n)] can be read as \"the function\n    that, given a number [n], yields [n * n].\" *)\n\n(** Here is the [filter] example, rewritten to use an anonymous\n    function. *)\n\nExample test_filter2':\n    filter (fun l => beq_nat (length l) 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 2 stars (filter_even_gt7)  *)\n(** Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n => (negb (leb n 7)) && evenb 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\n      partition : forall X : Type,\n                  (X -> bool) -> list X -> list X * list X\n\n   Given a set [X], a test function of type [X -> bool] and a [list\n   X], [partition] should return a pair of lists.  The first member of\n   the pair is the sublist of the original list containing the\n   elements that satisfy the test, and the second is the sublist\n   containing those that fail the test.  The order of elements in the\n   two sublists should be the same as their order in the original\n   list. *)\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X :=\n  (filter test l, filter (fun n => negb (test n)) l).\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity.  Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity.  Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Map *)\n\n(** Another handy higher-order function is called [map]. *)\n\nFixpoint map {X Y: Type} (f:X->Y) (l:list X) : (list Y) :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]\n    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has\n    been applied to each element of [l] in turn.  For example: *)\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** The element types of the input and output lists need not be\n    the same, since [map] takes _two_ type arguments, [X] and [Y]; it\n    can thus be applied to a list of numbers and a function from\n    numbers to booleans to yield a list of booleans: *)\n\nExample test_map2:\n  map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity.  Qed.\n\n(** It can even be applied to a list of numbers and\n    a function from numbers to _lists_ of booleans to\n    yield a _list of lists_ of booleans: *)\n\nExample test_map3:\n    map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 3 stars (map_rev)  *)\n(** Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\nLemma map_distr_app : forall (X Y : Type) (f : X -> Y) (l1 l2 : list X),\n  map f (l1 ++ l2) = map f l1 ++ map f l2.\nProof.\n  intros X Y f l1 l2.\n  induction l1.\n  - simpl. reflexivity.\n  - simpl. rewrite IHl1. reflexivity.\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros X Y f l.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite map_distr_app. simpl. rewrite IHl. 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\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  | a :: t => f a ++ flat_map f t\n  end.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\nProof. reflexivity. Qed.\n(** [] *)\n\n(** Lists are not the only inductive type that we can write a\n    [map] function for.  Here is the definition of [map] for the\n    [option] type: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\n(** **** Exercise: 2 stars, optional (implicit_args)  *)\n(** The definitions and uses of [filter] and [map] use implicit\n    arguments in many places.  Replace the curly braces around the\n    implicit arguments with parentheses, and then fill in explicit\n    type parameters where necessary and use Coq to check that you've\n    done so correctly.  (This exercise is not to be turned in; it is\n    probably easiest to do it on a _copy_ of this file that you can\n    throw away afterwards.)\n*)\n(** [] *)\n\n(* ================================================================= *)\n(** ** Fold *)\n\n(** An even more powerful higher-order function is called\n    [fold].  This function is the inspiration for the \"[reduce]\"\n    operation that lies at the heart of Google's map/reduce\n    distributed programming framework. *)\n\nFixpoint fold {X Y: Type} (f: X->Y->Y) (l: list X) (b: Y)\n                         : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(** Intuitively, the behavior of the [fold] operation is to\n    insert a given binary operator [f] between every pair of elements\n    in a given list.  For example, [ fold plus [1;2;3;4] ] intuitively\n    means [1+2+3+4].  To make this precise, we also need a \"starting\n    element\" that serves as the initial second input to [f].  So, for\n    example,\n\n       fold plus [1;2;3;4] 0\n\n    yields\n\n       1 + (2 + (3 + (4 + 0))).\n\n    Some more examples: *)\n\nCheck (fold andb).\n(* ===> fold andb : list bool -> bool -> bool *)\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, advanced (fold_types_different)  *)\n(** Observe that the type of [fold] is parameterized by _two_ type\n    variables, [X] and [Y], and the parameter [f] is a binary operator\n    that takes an [X] and a [Y] and returns a [Y].  Can you think of a\n    situation where it would be useful for [X] and [Y] to be\n    different? *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_types_different : option (prod nat string) := None.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Functions That Construct Functions *)\n\n(** Most of the higher-order functions we have talked about so\n    far take functions as arguments.  Let's look at some examples that\n    involve _returning_ functions as the results of other functions.\n    To begin, here is a function that takes a value [x] (drawn from\n    some type [X]) and returns a function from [nat] to [X] that\n    yields [x] whenever it is called, ignoring its [nat] argument. *)\n\nDefinition constfun {X: Type} (x: X) : nat->X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** In fact, the multiple-argument functions we have already\n    seen are also examples of passing functions as data.  To see why,\n    recall the type of [plus]. *)\n\nCheck plus.\n(* ==> nat -> nat -> nat *)\n\n(** Each [->] in this expression is actually a _binary_ operator\n    on types.  This operator is _right-associative_, so the type of\n    [plus] is really a shorthand for [nat -> (nat -> nat)] -- i.e., it\n    can be read as saying that \"[plus] is a one-argument function that\n    takes a [nat] and returns a one-argument function that takes\n    another [nat] and returns a [nat].\"  In the examples above, we\n    have always applied [plus] to both of its arguments at once, but\n    if we like we can supply just the first.  This is called _partial\n    application_. *)\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity.  Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity.  Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\nModule Exercises.\n\n(** **** Exercise: 2 stars (fold_length)  *)\n(** Many common functions on lists can be implemented in terms of\n    [fold].  For example, here is an alternative definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length]. *)\n\nLemma fold_cons_S : forall (X : Type) (x : X) (l : list X),\n  fold_length (x :: l) = S (fold_length l).\nProof.\n  intros X x l.\n  destruct l.\n  - reflexivity.\n  - reflexivity.\nQed.\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  - rewrite fold_cons_S. rewrite IHl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (fold_map)  *)\n(** We can also define [map] in terms of [fold].  Finish [fold_map]\n    below. *)\n\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y :=\n  fold (fun x acc => f x :: acc) l [].\n\n(** Write down a theorem [fold_map_correct] in Coq stating that\n   [fold_map] is correct, and prove it. *)\n\nTheorem fold_dist_cons : forall X Y (f : X -> Y -> Y) (x : X) (l : list X) (acc : Y),\n  fold f (x :: l) acc = f x (fold f l acc).\nProof.\n  intros X Y f x l acc.\n  destruct l.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nTheorem fold_map_dist_cons : forall X Y (f : X -> Y) (x : X) (l : list X),\n  fold_map f (x :: l) = f x :: fold_map f l.\nProof.\n  intros X Y f x l.\n  destruct l.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem fold_map_correct : forall X Y (f : X -> Y) (l : list X),\n  fold_map f l = map f l.\nProof.\n  intros X Y f l.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite fold_map_dist_cons. rewrite IHl. reflexivity.\nQed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_map : option (prod nat string) := None.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (currying)  *)\n(** In Coq, a function [f : A -> B -> C] really has the type [A\n    -> (B -> C)].  That is, if you give [f] a value of type [A], it\n    will give you function [f' : B -> C].  If you then give [f'] a\n    value of type [B], it will return a value of type [C].  This\n    allows for partial application, as in [plus3].  Processing a list\n    of arguments with functions that return functions is called\n    _currying_, in honor of the logician Haskell Curry.\n\n    Conversely, we can reinterpret the type [A -> B -> C] as [(A *\n    B) -> C].  This is called _uncurrying_.  With an uncurried binary\n    function, both arguments must be given at once as a pair; there is\n    no partial application. *)\n\n(** We can define currying as follows: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** As an exercise, define its inverse, [prod_uncurry].  Then prove\n    the theorems below to show that the two are inverses. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z :=\n  match p with\n  | (a, b) => f a b\n  end.\n\n(** As a (trivial) example of the usefulness of currying, we can use it\n    to shorten one of the examples that we saw above: *)\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** Thought exercise: before running the following commands, can you\n    calculate the types of [prod_curry] and [prod_uncurry]? *)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  intros X Y Z f x y.\n  reflexivity.\nQed.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros X Y Z f p.\n  destruct p.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (nth_error_informal)  *)\n(** Recall the definition of the [nth_error] function:\n\n   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n     match l with\n     | [] => None\n     | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\n     end.\n\n   Write an informal proof of the following theorem:\n\n   forall X n l, length l = n -> @nth_error X l n = None\n*)\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_proof : option (prod nat string) := None.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (church_numerals)  *)\n(** This exercise explores an alternative way of defining natural\n    numbers, using the so-called _Church numerals_, named after\n    mathematician Alonzo Church.  We can represent a natural number\n    [n] as a function that takes a function [f] as a parameter and\n    returns [f] iterated [n] times. *)\n\nModule Church.\nDefinition nat := forall X : Type, (X -> X) -> X -> X.\n\n(** Let's see how to write some numbers with this notation. Iterating\n    a function once should be the same as just applying it.  Thus: *)\n\nDefinition one : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** Similarly, [two] should apply [f] twice to its argument: *)\n\nDefinition two : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** Defining [zero] is somewhat trickier: how can we \"apply a function\n    zero times\"?  The answer is actually simple: just return the\n    argument untouched. *)\n\nDefinition zero : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(** More generally, a number [n] can be written as [fun X f x => f (f\n    ... (f x) ...)], with [n] occurrences of [f].  Notice in\n    particular how the [doit3times] function we've defined previously\n    is actually just the Church representation of [3]. *)\n\nDefinition three : nat := @doit3times.\n\n(** Complete the definitions of the following functions. Make sure\n    that the corresponding unit tests pass by proving them with\n    [reflexivity]. *)\n\n(** Successor of a natural number: *)\n\nDefinition succ (n : nat) : nat := fun (X : Type) (f : X -> X) (x : X) => f (n X f x).\n\nExample succ_1 : succ zero = one.\nProof. reflexivity. Qed.\n\nExample succ_2 : succ one = two.\nProof. reflexivity. Qed.\n\nExample succ_3 : succ two = three.\nProof. reflexivity. Qed.\n\n(** Addition of two natural numbers: *)\n\nDefinition plus (n m : nat) : nat :=\n  fun (X : Type) (f : X -> X) (x : X) =>\n  n X f (m X f x).\n\nExample plus_1 : plus zero one = one.\nProof. reflexivity. Qed.\n\nExample plus_2 : plus two three = plus three two.\nProof. reflexivity. Qed.\n\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. reflexivity. Qed.\n\n(** Multiplication: *)\n\nDefinition mult (n m : nat) : nat :=\n  fun (X : Type) (f : X -> X) (x : X) =>\n  n X (m X f) x.\n\nExample mult_1 : mult one one = one.\nProof. reflexivity. Qed.\n\nExample mult_2 : mult zero (plus three three) = zero.\nProof. reflexivity. Qed.\n\nExample mult_3 : mult two three = plus three three.\nProof. reflexivity. Qed.\n\n(** Exponentiation: *)\n\n(** (_Hint_: Polymorphism plays a crucial role here.  However,\n    choosing the right type to iterate over can be tricky.  If you hit\n    a \"Universe inconsistency\" error, try iterating over a different\n    type: [nat] itself is usually problematic.) *)\n\nDefinition exp (n m : nat) : nat :=\n  fun (X : Type) (f : X -> X) =>\n  m (X -> X) (fun n' => n X n') (one X f).\n\nExample exp_1 : exp two two = plus two two.\nProof. reflexivity. Qed.\n\nExample exp_2 : exp three two = plus (mult two (mult two two)) one.\nProof. reflexivity. Qed.\n\nExample exp_3 : exp three zero = one.\nProof. reflexivity. Qed.\n\nEnd Church.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_succ_plus_mult_exp : option (prod nat string) := None.\n(** [] *)\n\nEnd Exercises.\n\n\n", "meta": {"author": "maximsmol", "repo": "sf-lf", "sha": "94ea1bb7663d913a2e69201e7a32111b08c75e92", "save_path": "github-repos/coq/maximsmol-sf-lf", "path": "github-repos/coq/maximsmol-sf-lf/sf-lf-94ea1bb7663d913a2e69201e7a32111b08c75e92/Poly_done.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.865224070413529, "lm_q1q2_score": 0.6654267331929372}}
{"text": "(*\n * Source: https://github.com/christ2go/gherkin/blob/main/gentree.v\n *\n *)\n\nRequire Import Nat.\nRequire Import List.\nImport ListNotations.\nRequire Import Relations.\nRequire Import PeanoNat. \n\n(** MTrees are the trees we pickle into\n *)\nInductive Ntree : Type := NLeaf: nat -> Ntree | NBranch:  nat -> list Ntree -> Ntree.\n\nSection correct_ntree_ind.\n\nVariables\n  (A : Set)(P : Ntree -> Prop).\nHypotheses\n  (H : forall (a:nat)(l:list (Ntree)), (forall x, In x l -> P x) -> P (NBranch a l))\n  \n (H1 : forall t:Ntree, P t -> forall l:list (Ntree), (forall x, In x l -> P x) -> (forall x, In x (cons t l) -> P x))\n (H2: forall (n: nat), P(NLeaf n)).\nLemma  H0: forall x, In x [] -> P x.\n  intros x H4.  destruct H4.\n  Qed. \nFixpoint ntree_ind2 (t:Ntree) : P t :=\n  match t as x return P x with\n  | NBranch a l =>\n      H a l\n        (((fix l_ind (l':list (Ntree)) : (forall x, In x l' -> P x) :=\n             match l' as x return forall y, In y x -> P y with\n             | nil => H0\n             | cons t1 tl => H1 t1 (ntree_ind2 t1) tl (l_ind tl)\n             end)) l)\n  | NLeaf x => H2 x\n  end.\n\nEnd correct_ntree_ind.\nDefinition list_eq (A: Type) (f: A -> A -> bool) (l1 l2: list A) :=\n  let fll := fix gh (l1 l2:list A) :=\n                 match (l1, l2) with\n                   (nil ,nil) => true\n                 | (a::xr1, b::xr2) => if f a b then gh xr1 xr2 else false \n                 | _ => false end\n             in fll l1 l2.\nFixpoint ntree_eq_dec (n1 n2: Ntree) : bool :=\n  match (n1, n2) with\n    (NLeaf a ,NLeaf b) => if Nat.eq_dec a b then true else false\n  | (NBranch a xr1, NBranch b xr2) => if Nat.eq_dec a b then list_eq Ntree ntree_eq_dec xr1 xr2 else false \n  | _ => false end.\n\n(**\n   Note: I know that this proof is quite ugly, sorry :-(\n **)\n\nDefinition ntree_equal_dec_lemma: forall (x1 x2: Ntree), x1 = x2 <-> (ntree_eq_dec x1 x2) = true . \nProof.\n  intro.\n  induction x1 using ntree_ind2.\n  - intro x2. destruct x2.\n    split.\n    + intro. congruence.\n    + intro.   simpl ntree_eq_dec in H1.  congruence.\n    + split.\n      intro.\n      inversion H1.\n      simpl ntree_eq_dec.\n      destruct (Nat.eq_dec n n). subst l0. induction l. simpl.  reflexivity.\n      simpl list_eq. enough (ntree_eq_dec a0 a0 = true).\n      rewrite H2. apply IHl. intros x H4. apply H. right. assumption.\n      rewrite H3.\n      reflexivity.\n      apply H.\n      left. auto.\n      reflexivity.\n      congruence.\n      intro H1.\n      simpl ntree_eq_dec in H1.\n      destruct (Nat.eq_dec a n).\n      enough (l = l0).\n      subst a.  subst l. reflexivity.\n      assert (forall (l' l'': list Ntree), (forall x, In x l' -> In x l) -> list_eq Ntree ntree_eq_dec l' l'' = true <-> l' = l'').\n      intro l'.\n      induction l'.\n      *  intro l''. intro Hx. destruct l''. firstorder eauto.\n         split. intro. simpl list_eq in H2.  congruence.  intro. inversion H2.\n      *  intros l'' H2. split.\n         destruct l''.\n         intro. simpl in  H3.  congruence. \n         intro. assert (l' = l'').\n         apply IHl'. intros. apply H2. right. auto.\n         simpl in  H3. destruct (ntree_eq_dec a0 n0). auto.  congruence.\n         assert (a0 = n0).  apply H.  apply H2.  left. auto.\n         simpl in H3. destruct ( ntree_eq_dec a0 n0). reflexivity. congruence.  rewrite H4.  rewrite H5.\n         reflexivity.\n         destruct l''. \n         intro. congruence.\n         intro.\n         simpl list_eq.\n         inversion H3.\n         enough((ntree_eq_dec n0 n0) = true).\n         rewrite H4.\n         inversion H3.  rewrite<- H6.\n         apply IHl'. intros x H10. apply H2. right. auto.\n         reflexivity.\n         apply H. rewrite<- H5.\n         apply H2. left. auto.\n         reflexivity.\n      *   apply H2.   intro. auto.\n          auto.\n      *      congruence.\n  -    intro.       destruct H1.\n       subst x1_2.\n       apply IHx1_1.\n       apply H.  auto.\n  -  intro.\n     destruct x2.\n     + split.\n       intro.\n       inversion H.\n       simpl ntree_eq_dec.  destruct (Nat.eq_dec n0 n0).  reflexivity.\n       congruence.\n       simpl ntree_eq_dec. destruct (Nat.eq_dec n n0). subst n. firstorder eauto.\n       intro. congruence.\n     +  split. intro. congruence.\n        intro. simpl ntree_eq_dec in H. congruence.\nDefined.\n\n(*\n  * We can embed Ltrees / Gentrees (Ltrees are just gentrees with nat as a type)\n  * into lists of (nat * nat) + nat.\n  * The proofs of this equivalence are based on proofs from the stdpp library.\n  *)\nDefinition flatten {A: Type} (l: list (list A)) : list A :=\n  List.fold_right (@app A) [] l. \n\nFixpoint ntree_to_list (t : Ntree ) : list ((nat *  nat) + nat) :=\n  match t with\n  | NLeaf x => [inr x]\n  | NBranch n ts =>  (flatten (List.map ntree_to_list ts )) ++ [ @inl (nat*nat) nat (length ts, n) ]\n  end.\n\nFixpoint ntree_of_list \n    (k : list (Ntree)) (l : list (nat * nat + nat)) : option (Ntree) :=\n  match l with\n  | [] => head k\n  | inr x :: l => ntree_of_list (NLeaf x :: k) l\n  | inl (len,n) :: l =>\n     ntree_of_list (NBranch n (rev' (firstn len k)) :: skipn len k) l\n  end.\n\nTactic Notation \"trans\" constr(A) := transitivity A.\n\nLemma take_app_alt {A: Type} (l: list A) k :  firstn (length l) (l ++ k) = l.\nProof.\n  induction l. \n  - reflexivity. \n  - simpl firstn.  rewrite IHl. reflexivity.\nQed.\n\nLemma drop_app_alt {A: Type} (l: list A) k :  skipn (length l) (l ++ k) = k.\nProof.\n  induction l. \n  - reflexivity. \n  - simpl skipn.  rewrite IHl. reflexivity.\nQed.\n\nLemma ntree_of_to_list k l (t : Ntree) :\n  ntree_of_list k (ntree_to_list t ++ l) = ntree_of_list (t :: k) l.\nProof.\n  revert t k l. fix FIX 1. intros [|n ts] k l; simpl; auto.\n    trans (ntree_of_list (rev' ts ++ k) ([inl (length ts, n)] ++ l)).\n  -   rewrite<- app_assoc. revert k. generalize ([inl (length ts, n)] ++ l).\n      induction ts as [|t ts'' IH]; intros k ts'''; simpl; auto.\n      unfold rev. simpl rev_append.   rewrite<- app_assoc.  rewrite FIX. rewrite IH.\n      unfold rev' at 2. simpl rev_append. rewrite rev_append_rev. rewrite<- app_assoc. simpl app at 3.  repeat rewrite<- app_assoc.  unfold rev'. \n     rewrite rev_append_rev. rewrite app_nil_r . reflexivity.\n  -  simpl.\n     enough ((length ts) = length (rev' ts)).\n     rewrite H. \n     rewrite take_app_alt.\n     rewrite drop_app_alt.\n     unfold rev'. \n     rewrite rev_append_rev.\n     rewrite<- rev_alt. \n     rewrite rev_involutive. \n     enough (ts++[] = ts).\n     rewrite H1.\n     reflexivity.\n     induction ts. simpl. reflexivity. simpl. rewrite IHts.  reflexivity.\n     unfold rev'. \n     rewrite rev_append_rev.\n     enough ((rev ts)++[] = rev ts).\n     rewrite H1.\n     symmetry. apply rev_length.\n     induction (rev ts). simpl. reflexivity. simpl. rewrite IHl0.  reflexivity.\n     symmetry. unfold rev'. \n     rewrite rev_append_rev. rewrite app_nil_r .  apply rev_length.\nQed.\n\n\nRequire Import List.\nImport ListNotations.\n\nDefinition cumulative {X} (L: nat -> list X) :=\n  forall n, exists A, L (S n) = L n ++ A.\n  Global Hint Extern 0 (cumulative _) => intros ?; cbn; eauto : core.\n\nLemma cum_ge {X} {L: nat -> list X} {n m} :\n  cumulative L -> m >= n -> exists A, L m = L n ++ A.\nProof.\n  induction 2 as [|m _ IH].\n  - exists nil. now rewrite app_nil_r.\n  - destruct (H m) as (A&->), IH as [B ->].\n    exists (B ++ A). now rewrite app_assoc.\nQed.\n\nLemma cum_ge' {X} {L: nat -> list X} {x n m} :\n  cumulative L -> In x (L n) -> m >= n -> In x (L m).\nProof.\n  intros ? H [A ->] % (cum_ge (L := L)). apply in_app_iff. eauto. eauto.\nQed.\n\nDefinition list_enumerator {X} (L: nat -> list X) (p : X -> Prop) :=\n  forall x, p x <-> exists m, In x (L m).\nDefinition list_enumerable {X} (p : X -> Prop) :=\n  exists L, list_enumerator L p.\n\nDefinition list_enumerator__T' X f := forall x : X, exists n : nat, In x (f n).\nNotation list_enumerator__T f X := (list_enumerator__T' X f).\nDefinition list_enumerable__T X := exists f : nat -> list X, list_enumerator__T f X.\nDefinition inf_list_enumerable__T X := { f : nat -> list X | list_enumerator__T f X }.\n\nSection enumerator_list_enumerator.\n  Variable X : Type.\n  Variable p : X -> Prop.\n  Variables (e : nat -> option X).\n\n  Let T (n : nat) : list X :=  match e n with Some x => [x] | None => [] end.\n\n  Lemma enumerator_to_list_enumerator : forall x, (exists n, e n = Some x) <-> (exists n, In x (T n)).\n  Proof.\n    split; intros [n H].\n    - exists n. unfold T. rewrite H. firstorder.\n    - unfold T in *. destruct (e n) eqn:E. inversion H; subst. eauto. destruct H1.  destruct H. \n  Qed.\n\nEnd enumerator_list_enumerator.\n\nDefinition enumerable {X} (p : X -> Prop) := exists f, forall x, p x <-> exists n : nat, f n = Some x.\nDefinition enumerable__T X := exists f : nat -> option X, forall x, exists n, f n = Some x.\n\n\nLemma enumerable_list_enumerable {X} {p : X -> Prop} :\n  enumerable p -> list_enumerable p.\nProof.\n  intros [f Hf]. eexists.\n  unfold list_enumerator.\n  intros x. rewrite <- enumerator_to_list_enumerator.\n  eapply Hf.\nQed.\n\nLemma enumerable__T_list_enumerable {X} :\n  enumerable__T X -> list_enumerable__T X.\nProof.\n  intros [f Hf]. eexists.\n  unfold list_enumerator.\n  intros x. rewrite <- enumerator_to_list_enumerator.\n  eapply Hf.\nQed.\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.\nSection enumerator_list_enumerator.\n\n  Variable X : Type.\n  Variables (T : nat -> list X).\n\n  Let e (n : nat) : option X :=\n    let (n, m) := unembed n in\n    nth_error (T n) m.\n\n  Lemma list_enumerator_to_enumerator : forall x, (exists n, e n = Some x) <-> (exists n, In x (T n)).\n  Proof.\n    split; intros [k H].\n    - unfold e in *.\n      destruct (unembed k) as (n, m).\n      exists n. eapply (nth_error_In _ _ H).\n    - unfold e in *.\n      eapply In_nth_error in H as [m].\n      exists (embed (k, m)). now rewrite embedP, H.\n  Qed.\n\nEnd enumerator_list_enumerator.\n\nDefinition enumerator {X} (f : nat -> option X) (P : X -> Prop) : Prop :=\n\t  forall x, P x <-> exists n, f n = Some x.\n\n\nLemma list_enumerator_enumerator {X} {p : X -> Prop} {T} :\n  list_enumerator T p -> enumerator (fun n => let (n, m) := unembed n in\n    nth_error (T n) m) p.\nProof.\n  unfold list_enumerator.\n  intros H x. rewrite list_enumerator_to_enumerator. eauto.\nQed.\n\nLemma list_enumerable_enumerable {X} {p : X -> Prop} :\n  list_enumerable p -> enumerable p.\nProof.\n  intros [T HT]. eexists.\n  unfold list_enumerator.\n  intros x. rewrite list_enumerator_to_enumerator.\n  eapply HT.\nQed.\n\nLemma list_enumerable__T_enumerable {X} :\n  list_enumerable__T X -> enumerable__T X.\nProof.\n  intros [T HT]. eexists.\n  unfold list_enumerator.\n  intros x. rewrite list_enumerator_to_enumerator.\n  eapply HT.\nQed.\n\nLemma enum_enumT {X} :\n  enumerable__T X <-> list_enumerable__T X.\nProof.\n  split.\n  eapply enumerable__T_list_enumerable.\n  eapply list_enumerable__T_enumerable.\nQed.\n\nDefinition to_cumul {X} (L : nat -> list X) := fix f n :=\n  match n with 0 => [] | S n => f n ++ L n end.\n\nLemma to_cumul_cumulative {X} (L : nat -> list X) :\n  cumulative (to_cumul L).\nProof.\n  eauto.\nQed.\n\nLemma to_cumul_spec {X} (L : nat -> list X) x :\n  (exists n, In x (L n)) <-> exists n, In x (to_cumul L n).\nProof.\n  split.\n  - intros [n H].\n    exists (S n). cbn. eapply in_app_iff. eauto.\n  - intros [n H].\n    induction n; cbn in *.\n    + inversion H.\n    + eapply in_app_iff in H as [H | H]; eauto.\nQed.\n\nLemma cumul_In {X} (L : nat -> list X) x n :\n  In x (L n) -> In x (to_cumul L (S n)).\nProof.\n  intros H. cbn. eapply in_app_iff. eauto.\nQed.\n\nLemma In_cumul {X} (L : nat -> list X) x n :\n  In x (to_cumul L n) -> exists n, In x (L n).\nProof.\n  intros H. eapply to_cumul_spec. eauto.\nQed.\n\nLemma Cumul_Step {X} (L : nat -> list X) x n :\n  forall m, n < m -> In x (L n) -> In x (to_cumul L m).\nProof.\n  intros m. intros E. induction E. firstorder eauto.  apply cumul_In. assumption.\n  intro. simpl to_cumul. apply in_app_iff. left. apply IHE. assumption.\nQed.\n\nGlobal Hint Resolve cumul_In In_cumul : core.\n\nLemma list_enumerator_to_cumul {X} {p : X -> Prop} {L} :\n  list_enumerator L p -> list_enumerator (to_cumul L) p. \nProof.\n  unfold list_enumerator.\n  intros. rewrite H.\n  eapply to_cumul_spec.\nQed.\n\nLemma cumul_spec__T {X} {L} :\n  list_enumerator__T L X -> list_enumerator__T (to_cumul L) X.\nProof.\n  unfold list_enumerator__T.\n  intros. now rewrite <- to_cumul_spec.\nQed.\n\nLemma cumul_spec {X} {L} {p : X -> Prop} :\n  list_enumerator L p -> list_enumerator (to_cumul L) p.\nProof.\n  unfold list_enumerator.\n  intros. now rewrite <- to_cumul_spec.\nQed.\n\nModule ListAutomationNotations.\n\n  Notation \"x 'el' L\" := (In x L) (at level 70).\n  Notation \"A '<<=' B\" := (incl A B) (at level 70).\n\n  Notation \"( A × B × .. × C )\" := (list_prod .. (list_prod A B) .. C) (at level 0, left associativity).\n\nEnd ListAutomationNotations.\nImport ListAutomationNotations.\n\n\nLtac in_app n :=\n  (match goal with\n  | [ |- In _ (_ ++ _) ] => \n    match n with\n    | 0 => idtac\n    | 1 => eapply in_app_iff; left\n    | S ?n => eapply in_app_iff; right; in_app n\n    end\n  | [ |- In _ (_ :: _) ] => match n with 0 => idtac | 1 => left | S ?n => right; in_app n end\n  end) || (repeat (try right; eapply in_app_iff; right)).\n\n\nRequire Import Lia Arith.\nLocal Set Implicit Arguments.\nLocal Unset Strict Implicit.\n\nGlobal Hint Extern 4 => \nmatch goal with\n|[ H: ?x el nil |- _ ] => destruct H\nend : core.\n\nGlobal Hint Extern 4 => \nmatch goal with\n|[ H: False |- _ ] => destruct H\n|[ H: true=false |- _ ] => discriminate H\n|[ H: false=true |- _ ] => discriminate H\nend : core.\nLemma incl_nil X (A : list X) :\n  nil <<= A.\nProof. intros x []. Qed.\n\nHint Rewrite <- app_assoc : list.\nHint Rewrite rev_app_distr map_app prod_length : list.\nGlobal Hint Resolve in_eq in_nil in_cons in_or_app : core.\nGlobal Hint Resolve incl_refl incl_tl incl_cons incl_appl incl_appr incl_app incl_nil : core.\n\nLemma app_incl_l X (A B C : list X) :\nA ++ B <<= C -> A <<= C.\nProof.\nfirstorder eauto.\nQed.\n\nLemma app_incl_R X (A B C : list X) :\nA ++ B <<= C -> B <<= C.\nProof.\nfirstorder eauto.\nQed.\n\nLemma cons_incl X (a : X) (A B : list X) : a :: A <<= B -> A <<= B.\nProof.\nintros ? ? ?. eapply H. firstorder.\nQed.\n\nLemma incl_sing X (a : X) A : a el A -> [a] <<= A.\nProof.\nnow intros ? ? [-> | [] ].\nQed.\n\nGlobal Hint Resolve app_incl_l app_incl_R cons_incl incl_sing : core.\n\nGlobal Hint Extern 4 (_ el map _ _) => eapply in_map_iff : core.\nGlobal Hint Extern 4 (_ el filter _ _) => eapply filter_In : core.\n\nSection Inclusion.\n  Variable X : Type.\n  Implicit Types A B : list X.\n\n  Lemma incl_nil_eq A :\n    A <<= nil -> A=nil.\n\n  Proof.\n    intros D. destruct A as [|x A].\n    - reflexivity.\n    - exfalso. apply (D x). auto.\n  Qed.\n\n  Lemma incl_shift x A B :\n    A <<= B -> x::A <<= x::B.\n\n  Proof. auto. Qed.\n\n  Lemma incl_lcons x A B :\n    x::A <<= B <-> x el B /\\ A <<= B.\n  Proof. \n    split. \n    - intros D. split; hnf; auto.\n    - intros [D E] z [F|F]; subst; auto.\n  Qed.\n\n  Lemma incl_rcons x A B :\n    A <<= x::B -> ~ x el A -> A <<= B.\n\n  Proof. intros C D y E. destruct (C y E) as [F|F]; congruence. Qed.\n\n  Lemma incl_lrcons x A B :\n    x::A <<= x::B -> ~ x el A -> A <<= B.\n\n  Proof.\n    intros C D y E.\n    assert (F: y el x::B) by auto.\n    destruct F as [F|F]; congruence.\n  Qed.\n\n  Lemma incl_app_left A B C :\n    A ++ B <<= C -> A <<= C /\\ B <<= C.\n  Proof.\n    firstorder.\n  Qed.\n\nEnd Inclusion.\n\nRequire Import Setoid Morphisms.\n\nInstance incl_preorder X : \n  PreOrder (@incl X).\nProof. \n  constructor; hnf; unfold incl; auto. \nQed.\n\nDefinition equi X (A B : list X) : Prop := incl A B /\\ incl B A.\nLocal Notation \"A === B\" := (equi A B) (at level 70).\nGlobal Hint Unfold equi : core.\n\nInstance equi_Equivalence X : \n  Equivalence (@equi X).\nProof. \n  constructor; hnf; firstorder. \nQed.\n\nInstance incl_equi_proper X : \n  Proper (@equi X ==> @equi X ==> iff) (@incl X).\nProof. \n  hnf. intros A B D. hnf. firstorder. \nQed.\n\nInstance cons_incl_proper X x : \n  Proper (@incl X ==> @incl X) (@cons X x).\nProof.\n  hnf. apply incl_shift.\nQed.\n\nInstance cons_equi_proper X x : \n  Proper (@equi X ==> @equi X) (@cons X x).\nProof. \n  hnf. firstorder.\nQed.\n\nInstance in_incl_proper X x : \n  Proper (@incl X ==> Basics.impl) (@In X x).\nProof.\n  intros A B D. hnf. auto.\nQed.\n\nInstance in_equi_proper X x : \n  Proper (@equi X ==> iff) (@In X x).\nProof. \n  intros A B D. firstorder. \nQed.\n\nInstance app_incl_proper X : \n  Proper (@incl X ==> @incl X ==> @incl X) (@app X).\nProof. \n  intros A B D A' B' E. auto.\nQed.\n\nInstance app_equi_proper X : \n  Proper (@equi X ==> @equi X ==> @equi X) (@app X).\nProof. \n  hnf. intros A B D. hnf. intros A' B' E.\n  destruct D, E; auto.\nQed. \nNotation cumul := (to_cumul).\n\nLtac inv H := inversion H; subst; clear H.\n\nDefinition dec (X: Prop) : Type := {X} + {~ X}.\n\nCoercion dec2bool P (d: dec P) := if d then true else false.\nDefinition is_true (b : bool) := b = true.\n\nExisting Class dec.\n\nDefinition Dec (X: Prop) (d: dec X) : dec X := d.\nArguments Dec X {d}.\n\nLemma Dec_reflect (X: Prop) (d: dec X) :\n  is_true (Dec X) <-> X.\nProof.\n  destruct d as [A|A]; cbv in *; intuition congruence.\nQed.\n\nLemma Dec_auto (X: Prop) (d: dec X) :\n  X -> is_true (Dec X).\nProof.\n  destruct d as [A|A]; cbn; intuition congruence.\nQed.\n\n(* Lemma Dec_auto_not (X: Prop) (d: dec X) : *)\n(*   ~ X -> ~ Dec X. *)\n(* Proof. *)\n(*   destruct d as [A|A]; cbn; tauto. *)\n(* Qed. *)\n\n(* Hint Resolve Dec_auto Dec_auto_not : core. *)\nGlobal Hint Extern 4 =>  (* Improves type class inference *)\nmatch goal with\n  | [  |- dec ((fun _ => _) _) ] => cbn\nend : typeclass_instances.\n\nTactic Notation \"decide\" constr(p) := \n  destruct (Dec p).\nTactic Notation \"decide\" constr(p) \"as\" simple_intropattern(i) := \n  destruct (Dec p) as i.\nTactic Notation \"decide\" \"_\" :=\n  destruct (Dec _).\n\nLemma Dec_true P {H : dec P} : dec2bool (Dec P) = true -> P.\nProof.\n  decide P; cbv in *; firstorder.\nQed.\n\nLemma Dec_false P {H : dec P} : dec2bool (Dec P) = false -> ~P.\nProof.\n  decide P; cbv in *; firstorder.\nQed.\n\nGlobal Hint Extern 4 =>\nmatch goal with\n  [ H : dec2bool (Dec ?P) = true  |- _ ] => apply Dec_true in  H\n| [ H : dec2bool (Dec ?P) = true |- _ ] => apply Dec_false in H\nend : core.\n\n(* Decided propositions behave classically *)\n\nLemma dec_DN X : \n  dec X -> ~~ X -> X.\nProof. \n  unfold dec; tauto. \nQed.\n\nLemma dec_DM_and X Y :  \n  dec X -> dec Y -> ~ (X /\\ Y) -> ~ X \\/ ~ Y.\nProof. \n  unfold dec; tauto. \nQed.\n\nLemma dec_DM_impl X Y :  \n  dec X -> dec Y -> ~ (X -> Y) -> X /\\ ~ Y.\nProof. \n  unfold dec; tauto. \nQed.\n\n(* Propagation rules for decisions *)\n\nFact dec_transfer P Q :\n  P <-> Q -> dec P -> dec Q.\nProof.\n  unfold dec. tauto.\nQed.\n\nInstance True_dec :\n  dec True.\nProof. \n  unfold dec; tauto. \nQed.\n\n\n\nInstance False_dec :\n  dec False.\nProof. \n  unfold dec; tauto. \nQed.\n\nInstance impl_dec (X Y : Prop) :  \n  dec X -> dec Y -> dec (X -> Y).\nProof. \n  unfold dec; tauto. \nQed.\n\nInstance and_dec (X Y : Prop) :  \n  dec X -> dec Y -> dec (X /\\ Y).\nProof. \n  unfold dec; tauto. \nQed.\n\nInstance or_dec (X Y : Prop) : \n  dec X -> dec Y -> dec (X \\/ Y).\nProof. \n  unfold dec; tauto. \nQed.\n\n(* Coq standard modules make \"not\" and \"iff\" opaque for type class inference, \n   can be seen with Print HintDb typeclass_instances. *)\n\nInstance not_dec (X : Prop) : \n  dec X -> dec (~ X).\nProof. \n  unfold not. firstorder eauto.\nQed.\n\nInstance iff_dec (X Y : Prop) : \n  dec X -> dec Y -> dec (X <-> Y).\nProof. \n  unfold iff. firstorder eauto.\nQed.\n\n(* Discrete types *)\nRequire Import PslBase.EqDec. \n\n\nStructure eqType := EqType {\n  eqType_X :> Type;\n  eqType_dec : eq_dec eqType_X }.\n\nArguments EqType X {_} : rename.\n\nCanonical Structure eqType_CS X (A: eq_dec X) := EqType X.\n\nExisting Instance eqType_dec.\n\nInstance unit_eq_dec :\n  eq_dec unit.\nProof.\n  unfold dec. decide equality. \nQed.\n\nInstance bool_eq_dec : \n  eq_dec bool.\nProof.\n  unfold dec. decide equality. \nDefined.\n\nInstance nat_eq_dec : \n  eq_dec nat.\nProof.\n  unfold dec. decide equality.\nDefined.\n\nInstance prod_eq_dec X Y :  \n  eq_dec X -> eq_dec Y -> eq_dec (X * Y).\nProof.\n  unfold dec. decide equality. \nDefined.\n\nInstance list_eq_dec X :  \n  eq_dec X -> eq_dec (list X).\nProof.\n  unfold dec. decide equality. \nDefined.\n\n\nInstance sum_eq_dec X Y :  \n  eq_dec X -> eq_dec Y -> eq_dec (X + Y).\nProof.\n  unfold dec. decide equality. \nDefined.\n\nInstance option_eq_dec X :\n  eq_dec X -> eq_dec (option X).\nProof.\n  unfold dec. decide equality.\nDefined.\n\nInstance Empty_set_eq_dec:\n  eq_dec Empty_set.\nProof.\n  unfold dec. decide equality.\nQed.\n\nInstance True_eq_dec:\n  eq_dec True.\nProof.\n  intros x y. destruct x,y. now left.\nQed.\n\nInstance False_eq_dec:\n  eq_dec False.\nProof.\n  intros [].\nQed.\n\n\n  Notation \"[ s | p ∈ A ',' P ]\" :=\n    (map (fun p => s) (filter (fun p => Dec P) A)) (p pattern).\n\nSection L_list_def.\n  Context {X : Type}.\n  Variable (L : nat -> list X).\n  Import ListAutomationNotations.\n  Notation \"( A × B × .. × C )\" := (list_prod .. (list_prod A B) .. C) (at level 0, left associativity).\n  Notation \"[ s | p ∈ A ]\" :=\n    (map (fun p => s) A) (p pattern).\n\n  Fixpoint L_list (n : nat) : list (list X) :=\n\t  match n\n\t  with\n\t  | 0 => [ [] ]\n\t  | S n => L_list n ++ [x :: L | (x,L) ∈ (cumul L n × L_list n)]\n\t  end.\n\t\n  \nEnd L_list_def.\n\nLemma L_list_cumulative {X} L : cumulative (@L_list X L).\nProof.\n  intros ?; cbn; eauto. \nQed.\n\nLtac in_collect a :=\n  eapply in_map_iff; exists a; split; [ eauto | match goal with\n                                              _ => try (rewrite !in_prod_iff; repeat split) end ].\n\n\nLemma enumerator__T_list {X} L :\n  list_enumerator__T L X -> list_enumerator__T (L_list L) (list X).\nProof.\n  intros H l.\n  induction l.\n  - exists 0. cbn. eauto.\n  - destruct IHl as [n IH].\n    destruct (cumul_spec__T H a) as [m ?].\n    exists (1 + n + m). cbn. intros. in_app 2.\n    in_collect (a,l).\n    all: eapply cum_ge'; eauto using L_list_cumulative; lia.\nQed.\n\nSection L_sum_def.\n  Context {X1 X2 : Type}.\n  Variables (L1 : nat -> list X1) (L2: nat -> list X2).\n  Import ListAutomationNotations.\n  Notation \"( A × B × .. × C )\" := (list_prod .. (list_prod A B) .. C) (at level 0, left associativity).\n  Notation \"[ s | p ∈ A ]\" :=\n    (map (fun p => s) A) (p pattern).\n\n  Definition L_sum_list (n : nat) : list (X1+X2) :=\n\t  (List.map inl (L1 n)) ++ (List.map inr (L2 n))\n\t .\n\t\n  \nEnd L_sum_def.\n\n\nLemma enumerator_sum_list {X1 X2} L1 L2 :\n  list_enumerator__T L1 X1 -> list_enumerator__T L2 X2 -> list_enumerator__T (L_sum_list L1 L2) (X1+X2).\nProof.\n  intros H1 H2.\n  intro.\n  destruct x.\n  - destruct (H1 x) as [n1 Hn1]. \n   exists n1.  unfold L_sum_list. rewrite in_app_iff.\n    left. apply in_map_iff. exists x. firstorder eauto.\n  - destruct (H2 x).    unfold L_sum_list. exists x0. rewrite in_app_iff.\n    right. apply in_map_iff.  exists x. split; firstorder eauto.\nQed.\n\n(* Pickles X1 * X2 *)\nSection L_prod_def.\n  Context {X1 X2 : Type}.\n  Variables (L1 : nat -> list X1) (L2: nat -> list X2).\n  Import ListAutomationNotations.\n  Notation \"( A × B × .. × C )\" := (list_prod .. (list_prod A B) .. C) (at level 0, left associativity).\n  Notation \"[ s | p ∈ A ]\" :=\n    (map (fun p => s) A) (p pattern).\n\n  Definition L_prod_list (n : nat) : list (X1*X2) :=\n\t   ((L1 n) × (L2 n)).\n\t\n  \nEnd L_prod_def.\n\n  Fact list_prod_spec X Y l m c : In c (@list_prod X Y l m) <-> In (fst c) l /\\ In (snd c) m.\n  Proof.\n    revert c; induction l as [ | x l IHl ]; intros c; simpl; try tauto.\n    rewrite in_app_iff, IHl, in_map_iff; simpl.\n    split.\n    + intros [ (y & <- & ?) | (? & ?) ]; simpl; auto.\n    + intros ([ -> | ] & ? ); destruct c; simpl; firstorder.\n  Qed.\n\n  \nLemma enumerator_prod_list {X1 X2} L1 L2 :\n  list_enumerator__T L1 X1 -> list_enumerator__T L2 X2 -> list_enumerator__T (L_prod_list (to_cumul L1) (to_cumul L2)) (X1*X2).\nProof.\n  intros H1 H2.\n  intro.\n  destruct x as [x1 x2].\n  specialize (H1 x1). specialize (H2 x2).\n  destruct H1 as [n1 Hn1]. destruct H2 as [n2 Hn2].\n  exists (S(Nat.max n1 n2)).\n  \n  apply list_prod_spec.\n  split.\n  simpl fst.\n  apply Cumul_Step with n1.\n  lia.\n  auto.\n\n  apply Cumul_Step with n2.\n  lia.\n  exact Hn2.\nQed.\n\n\n\nLemma  enumerable_list {X} : list_enumerable__T X -> list_enumerable__T (list X).\nProof.\n  intros [L H].\n  eexists. now eapply enumerator__T_list.\nQed.\n\n\nLemma  enumerable_sum {X1 X2} : list_enumerable__T X1 -> list_enumerable__T X2 -> list_enumerable__T (X1+X2).\nProof.\n  intros [L1 H1]. intros  [L2 H2].\n  \n  eexists. now eapply enumerator_sum_list.\nQed.\n\nLemma  enumerable_prod {X1 X2} : list_enumerable__T X1 -> list_enumerable__T X2 -> list_enumerable__T (X1*X2).\nProof.\n  intros [L1 H1]. intros  [L2 H2].\n  \n  eexists. now eapply enumerator_prod_list.\nQed.\nLemma enumNatNat: enumerable__T ((nat*nat)+nat).\nProof.\n  enough (H: enumerable__T nat).\n  apply enum_enumT. \n  apply enumerable_sum.\n  apply enum_enumT.\n  apply enum_enumT.\n  \n  apply enumerable_prod. apply enum_enumT. apply H.\n  apply enum_enumT. apply H. apply enum_enumT. apply H.\n  unfold enumerable__T.\n  exists (fun x => Some x).  intro. eauto.\nDefined.\nLemma enumerableDecodeEncode (A B: Type)\n      (code: A -> B)\n      (decode: B -> option A)\n      (H1: forall a, (decode (code a)) = Some a)\n      (enumB: enumerable__T B)\n  : enumerable__T A.\nProof.\n  unfold enumerable__T.\n  destruct enumB as [fb Hb].\n  exists (fun n => match (fb n) with None => None | Some x => (decode x) end).\n  intro a. specialize (H1 a).\n  specialize (Hb (code a)).\n  destruct Hb. exists x. rewrite H. apply H1.\nDefined.\n\nLemma enumLtree: enumerable__T Ntree. \nProof.\n  apply (@enumerableDecodeEncode Ntree (list ((nat*nat)+nat)) ntree_to_list (ntree_of_list [])  ).\n  intro.\n  pose (ntree_of_to_list [] [] a).\n  rewrite app_nil_r in e.\n  rewrite e.\n  simpl ntree_of_list.\n  reflexivity.\n  apply  enum_enumT. \n  apply enumerable_list.\n  apply enum_enumT.\n  apply enumNatNat.\nDefined.\n\n\n(** Ntrees are decidable **)\nInstance Ntree_eq_dec :\n  eq_dec Ntree.\nProof. \n  intros x y.\n  destruct ((ntree_eq_dec x y)) eqn:H.\n  left.\n  apply ntree_equal_dec_lemma.\n  auto.\n  right. intro.  apply ntree_equal_dec_lemma in H1. congruence.\nDefined.\n", "meta": {"author": "uds-psl", "repo": "intuitionistic-epistemic-logic", "sha": "435438f8fb73e3032d71bbd45832650273e7f99a", "save_path": "github-repos/coq/uds-psl-intuitionistic-epistemic-logic", "path": "github-repos/coq/uds-psl-intuitionistic-epistemic-logic/intuitionistic-epistemic-logic-435438f8fb73e3032d71bbd45832650273e7f99a/coq/gentree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6654150025965392}}
{"text": "Require Import GeoCoq.Axioms.parallel_postulates.\nRequire Import GeoCoq.Meta_theory.Parallel_postulates.bachmann_s_lotschnittaxiom_variant.\nRequire Import GeoCoq.Tarski_dev.Annexes.suma.\nRequire Import GeoCoq.Tarski_dev.Ch12_parallel.\n\nSection weak_inverse_projection_postulate_bachmann_s_lotschnittaxiom.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\n(** Formalization of a proof from Bachmann's article \"Zur Parallelenfrage\" *)\n\nLemma weak_inverse_projection_postulate__bachmann_s_lotschnittaxiom_aux :\n  weak_inverse_projection_postulate -> forall A1 A2 B1 B2 C1 C2 Q P R M,\n  Perp A1 A2 B1 B2 -> Perp A1 A2 C1 C2 -> Col A1 A2 Q -> Col B1 B2 Q ->\n  Col A1 A2 P -> Col C1 C2 P -> Col B1 B2 R ->\n  Coplanar Q P R C1 -> Coplanar Q P R C2 -> ~ Col Q P R ->\n  InAngle M P Q R -> CongA M Q P M Q R ->\n  Par_strict B1 B2 C1 C2 /\\ exists S, Out Q M S /\\ Col C1 C2 S.\nProof.\nintro hrap.\nintros A1 A2 B1 B2 C1 C2 Q P R M HPerpAB HPerpAC.\nintros HCol1 HCol2 HCol3 HCol4 HCol5 HCop1 HCop2 HNC HM1 HM2.\nassert_diffs.\nassert (HNCol1 : ~ Col A1 A2 R) by (intro; apply HNC, (col3 A1 A2); auto).\nassert (HNCol2 : ~ Col B1 B2 P) by (intro; apply HNC, (col3 B1 B2); auto).\nassert (HPar : Par_strict B1 B2 C1 C2).\n  {\n  apply par_not_col_strict with P; Col.\n  assert (Col A1 P Q /\\ Col A2 P Q /\\ Col B1 R Q /\\ Col B2 R Q)\n    by (repeat split; [apply col_transitivity_1 with A2|apply (col_transitivity_2 A1)\n                      |apply col_transitivity_1 with B2|apply (col_transitivity_2 B1)]; auto).\n  spliter.\n  assert (Coplanar Q P R A1) by Cop.\n  assert (Coplanar Q P R A2) by Cop.\n  assert (Coplanar Q P R B1) by Cop.\n  assert (Coplanar Q P R B2) by Cop.\n  apply l12_9 with A1 A2; Perp; apply coplanar_pseudo_trans with Q P R; assumption.\n  }\nsplit; [assumption|].\nassert (HNCol3 : ~ Col Q C1 C2) by (apply par_not_col with B1 B2; Par; Col).\nassert (Per P Q R).\n  {\n  apply perp_per_2, perp_col2 with A1 A2; Col;\n  apply perp_sym, perp_col2 with B1 B2; Col; Perp.\n  }\nassert (HSuma : SumA P Q M P Q M P Q R).\n  assert_diffs; apply conga3_suma__suma with P Q M M Q R P Q R; CongA; SumA.\nassert (HAcute : Acute P Q M).\n{ apply nbet_sams_suma__acute with P Q R; auto.\n    intro; apply HNC; Col.\n  assert (LeA P Q M P Q R) by Lea.\n  apply sams_lea2__sams with P Q R P Q R; SumA.\n}\nassert (HC3 : exists C3, Col C1 C2 C3 /\\ OS P Q R C3).\n{ destruct (diff_col_ex3 C1 C2 P) as [C0]; Col; spliter.\n  destruct (cop_not_par_same_side P Q C0 P P R) as [C3 []]; Col.\n    intro; apply HNCol3; ColR.\n    apply coplanar_perm_1, col_cop2__cop with C1 C2; Col; Cop.\n  exists C3; split; [ColR|assumption].\n}\ndestruct HC3 as [C3 [HCol6 HOS]].\ndestruct (hrap P Q M P Q R P C3) as [S [HS1 HS2]]; trivial;\n  [apply out_trivial; auto|apply os_distincts in HOS; spliter; auto|\n  |apply coplanar_trans_1 with R; Col; Cop|].\n{ assert (HP := HPerpAC); destruct HP as [P' [_ [_ [HP1 [HP2 HP3]]]]].\n  assert (P = P'); [|treat_equalities; apply HP3; Col].\n  elim (perp_not_col2 _ _ _ _ HPerpAC); intro;\n  [apply l6_21 with A1 A2 C1 C2|apply l6_21 with A1 A2 C2 C1]; Col.\n}\nexists S; split; [assumption|ColR].\nQed.\n\nLemma weak_inverse_projection_postulate__bachmann_s_lotschnittaxiom :\n  weak_inverse_projection_postulate -> bachmann_s_lotschnittaxiom.\nProof.\nintro hrap.\napply bachmann_s_lotschnittaxiom_aux.\nintros A1 A2 B1 B2 C1 C2 D1 D2 Q P R HQP HQR HPerpAB HPerpAC HPerpBD.\nintros HCol1 HCol2 HCol3 HCol4 HCol5 HCol6 HCop1 HCop2 HCop3 HCop4.\nassert (HNC : ~ Col P Q R).\n  apply per_not_col; auto; apply perp_per_1, (perp_col4 A1 A2 B1 B2); auto.\ndestruct (angle_bisector P Q R) as [M [HM1 HM2]]; auto.\nassert (HSuma : SumA P Q M P Q M P Q R).\n  assert_diffs; apply conga3_suma__suma with P Q M M Q R P Q R; CongA; SumA.\nassert (HAcute : Acute P Q M).\n  {\n  apply nbet_sams_suma__acute with P Q R; auto.\n    intro; apply HNC; Col.\n  assert (LeA P Q M P Q R) by Lea.\n  assert (Per P Q R)\n    by (apply perp_per_2, perp_col2 with A1 A2; Col; apply perp_sym, perp_col2 with B1 B2; Col; Perp).\n  apply sams_lea2__sams with P Q R P Q R; SumA.\n  }\ndestruct (weak_inverse_projection_postulate__bachmann_s_lotschnittaxiom_aux\n    hrap A1 A2 B1 B2 C1 C2 Q P R M) as [HParB [S [HS1 HS2]]]; Col.\ndestruct (weak_inverse_projection_postulate__bachmann_s_lotschnittaxiom_aux\n    hrap B1 B2 A1 A2 D1 D2 Q R P M) as [HParA [T [HT1 HT2]]]; [trivial..|]; [Perp|Cop..|Col| |CongA|].\n  apply l11_24, HM1.\ndestruct (col_dec C1 C2 T).\n  exists T; split; Col.\ndestruct (col_dec D1 D2 S).\n  exists S; split; Col.\nassert (HOut : Out Q S T) by (apply l6_7 with M; Out).\nclear dependent M.\ndestruct HOut as [HSQ [HTQ [HBet|HBet]]].\n- assert (HTS : TS C1 C2 R T).\n  { apply l9_8_2 with Q.\n      repeat split; [apply par_not_col with B1 B2; Par| |exists S; split]; Col.\n    apply l12_6, par_strict_col2_par_strict with B1 B2; Par; Col.\n  }\n  destruct HTS as [_ [_ [I [HI1 HI2]]]].\n  assert (T <> R).\n    intro; treat_equalities; Col.\n  exists I; split; ColR.\n- assert (HTS : TS D1 D2 P S).\n  { apply l9_8_2 with Q.\n      repeat split; [apply par_not_col with A1 A2; Par| |exists T; split]; Col.\n    apply l12_6, par_strict_col2_par_strict with A1 A2; Par; Col.\n  }\n  destruct HTS as [_ [_ [I [HI1 HI2]]]].\n  assert (P <> S).\n    intro; treat_equalities; Col.\n  exists I; split; ColR.\nQed.\n\nEnd weak_inverse_projection_postulate_bachmann_s_lotschnittaxiom.", "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/weak_inverse_projection_postulate_bachmann_s_lotschnittaxiom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6654150011943774}}
{"text": " (* Bruno PICOLO ORTIZ Elyan POUJOL *)\n\nRequire Import Bool.\nRequire Import List.\nImport ListNotations.\nSet Implicit Arguments.\n\n(* Ecriture de la spécification *)\n\nModule Type TABLE.\nParameter Key: Type.\nParameter Val: Type.\nParameter table: Type.\nParameter empty: table.\nParameter put: table -> Key -> Val -> table.\nParameter get: table -> Key -> Val -> Val.\nParameter member: table -> Key -> bool.\nAxiom get_empty: forall key def, get empty key def = def.\nAxiom get_put_eq: forall key val def t, get (put t key val) key def = val.\nAxiom get_put_neq: forall key1 key2 val def t,\n    key1<>key2 -> get (put t key1 val) key2 def = get t key2 def.\nAxiom empty_mem: forall key, member empty key = false.\nAxiom mem_put_eq: forall key val t, member (put t key val) key = true.\nAxiom mem_put_neq: forall key1 key2 val t,\n    key1<>key2 -> member (put t key1 val) key2 = member t key2.\nEnd TABLE.\n\nRequire Import Ascii. (* pour utiliser des caractères *)\nModule Test(T:TABLE with Definition Key:=list ascii with Definition Val:=nat).\n  Local Open Scope char_scope. (* pour pouvoir écrire \"a\" *)\n  Definition test :=\n    let t := T.put T.empty [\"a\"; \"b\"; \"c\"] 10 in\n    if T.member t [\"a\"; \"b\"; \"c\"] then\n      T.get t [\"a\"; \"b\"; \"c\"] 0\n    else\n      0.\nEnd Test.\n\n(* Implémentation de la spécification *)\n\nModule Type ALPHA.\n  Parameter lettre: Type.\n  Parameter eq: forall (x y:lettre), {x=y}+{x<>y}.\nEnd ALPHA.\n\nModule Type TYPE.\n  Parameter t: Type.\nEnd TYPE.\n\nModule Trie (A:ALPHA) (T:TYPE) <:\n  TABLE with Definition Key := list A.lettre with Definition Val := T.t.\n    Definition Key := list A.lettre.\n    Definition Val := T.t.\n    Inductive trie :=\n        Leaf (val: option Val)\n      | Node (val: option Val) (reste: A.lettre -> trie).\n\n    Definition table := trie.\n    Definition empty := Leaf None.\n    Definition isDefined T (v: option T) := (* teste si v <> None *)\n      match v with\n          None => false\n        | _ => true\n      end.\n\n    Definition getValue T (v: option T) def := (* valeur dans Some, def sinon *)\n      match v with\n          None => def\n        | Some u => u\n      end.\n\n    Fixpoint put t key val :=\n      match t with\n        | Leaf v =>\n            match key with\n              | [] => Leaf (Some val)\n              | e::k =>\n                  let t' := put (Leaf None) k val in\n                  Node v ( fun x => if A.eq x e then t' else (Leaf None))\n            end\n        | Node v r =>\n            match key with\n              | [] => Node (Some val) r\n              | e::k =>\n                  let t' := put (r e) k val in\n                  Node v (fun x => if A.eq x e then t' else r e)\n            end\n      end.\n\n    Fixpoint get t key val :=\n      match t with\n        | Leaf v =>\n            match key with\n              | [] => getValue v val\n              | e::k => val\n            end\n        | Node v r =>\n            match key with\n              | [] => getValue v val\n              | e::k => get (r e) k val\n            end\n      end.\n\n\n    Fixpoint member t key :=\n      match key with\n      | [] =>\n          match t with\n            | Leaf None\n            | Node None _ => false\n            | _ => true\n          end\n      | e::k =>\n          match t with\n            | Leaf _=> false\n            | Node _ r => member (r e) k\n          end\n      end.\n\n\n    Theorem empty_mem: forall key, member empty key = false.\n    Proof.\n    destruct key; try tauto.\n    Qed.\n    Print empty_mem.\n\n    Theorem get_empty: forall key def, get empty key def = def.\n    Proof.\n    destruct key; try tauto. \n    Qed.\n    Print get_empty.\n\n    Theorem mem_put_eq: forall key val t, member (put t key val) key = true.\n    Proof.\n    induction key.\n    destruct t; try tauto.\n    destruct t; try tauto.\n    simpl.\n    destruct A.eq; try tauto.\n    rewrite IHkey. auto.\n    simpl.\n    destruct A.eq; try tauto.\n    rewrite IHkey. auto.\n    Qed.\n    Print mem_put_eq.\n\n    Theorem get_put_eq: forall key val def t, get (put t key val) key def = val.\n    Proof.\n    induction key. \n    destruct t; try tauto.\n    destruct t; try tauto.\n    simpl.\n    destruct A.eq; try tauto.\n    rewrite IHkey; try tauto.\n    simpl.\n    destruct A.eq; try tauto.\n    rewrite IHkey; try tauto.\n    Qed.\n    Print get_put_eq.\n\n    Theorem mem_put_neq: forall key1 key2 val t,\n      key1<>key2 -> member (put t key1 val) key2 = member t key2.\n    Proof.\n    induction key1.\n    destruct key2; try tauto.\n    destruct t; try tauto.\n    simpl.\n    destruct t; try tauto.\n    destruct (A.eq a a); try tauto.\n    destruct val0.\n    destruct key2; try tauto.\n    simpl.\n    destruct A.eq; try tauto.\n    rewrite IHkey1; try tauto.\n    destruct key2; try tauto.\n    intro.\n    subst key1.\n    subst l.\n    Admitted.\n\n\n    Theorem get_put_neq: forall key1 key2 val def t,\n      key1<>key2 -> get (put t key1 val) key2 def = get t key2 def.\n    Proof.\n    induction key1.\n    destruct t; try tauto.\n    destruct key2; try tauto.\n    destruct key2; try tauto.\n    simpl.\n    destruct key2; try tauto.\n    destruct t; try tauto.\n    destruct t; try tauto.\n    destruct val0; try tauto.\n    simpl.\n    destruct A.eq; try tauto.\n    subst l.\n    rewrite IHkey1; try tauto.\n    intros.\n    destruct key2; try tauto.\n    intro.\n    Admitted.\nEnd Trie.\n\nInductive option T :=\n  Some (valeur: T)\n  | None.\n\n\nModule StrK.\n  Definition lettre := ascii.\n  Definition eq := ascii_dec.\nEnd StrK.\n\nModule NatV.\n  Definition t := nat.\nEnd NatV.\n\nModule TrieStrNat := Trie StrK NatV.\nModule TestTrieStrNat := Test TrieStrNat.\n\nEval compute in TestTrieStrNat.test.\n\n", "meta": {"author": "BrunoPicolo", "repo": "DM_coq", "sha": "30db5b72557f9b809613fc093f22bf95f791b317", "save_path": "github-repos/coq/BrunoPicolo-DM_coq", "path": "github-repos/coq/BrunoPicolo-DM_coq/DM_coq-30db5b72557f9b809613fc093f22bf95f791b317/TP32_PICOLO-ORTIZ_POUJOL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110483133801, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6654149975622439}}
{"text": "(*\nSet Warnings \"-notation-overridde,-parsing\".\n*)\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\nCheck list.\nCheck (nil nat).\nCheck (cons nat 3 (nil nat)).\nCheck nil.\nCheck cons.\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => (cons X x (repeat X x count'))\n  end.\n\nExample test_repeat1 : \n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity. Qed.\n\nExample test_repeat2 : \n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity. Qed.\n\nModule MumbleGrumble.\n\nInductive mumble : Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\n\nInductive grumble (X : Type) : Type :=\n  | d : mumble -> grumble X\n  | e : X -> grumble X.\n\nCheck b a 5. (* mumble *)\nCheck d. (* forall X : Type, mumble -> grumble X *)\n(* Check d (b a 5). expecting mumble type, not mumble element *)\nCheck d mumble (b a 5). (* grumble mumble *)\nCheck d bool (b a 5). (* grumble bool *)\nCheck e bool true. (* grumble bool *)\nCheck b c 0. (* mumble *)\nCheck e mumble (b c 0). (* grumble mumble *)\n(* Check e bool (b c 0). expecting bool, gets mumble *)\nCheck c. (* mumble *)\n\nEnd MumbleGrumble.\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\nCheck repeat'. (* forall X : Type, X -> nat -> list X *)\nCheck repeat.  (* same type *)\n\nDefinition list123' :=\n  cons _ 1 ( cons _ 2 ( cons _ 3 (nil _))).\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with \n  | 0 => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n(* list' not good because now cannot say list' nat *)\n\nInductive list' {X : Type} : Type :=\n  | nil' : list'\n  | cons' : X -> list' -> list'.\n\n(* Do the type inference at the function level, not the datatype level *)\n\nFixpoint app {X : Type} (l1 l2 : list X) : list X :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X : Type} (l : list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons h t => S (length t)\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = cons 2 (cons 1 nil).\nProof. reflexivity. Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity. Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity. Qed.\n\nFail Definition mynil := nil. (* cannot infer type here *)\nDefinition mynil : list nat := nil. (* enough info *)\nCheck @nil. (* force implicit to explicity *)\nDefinition mynil' := @nil nat.\n\nNotation \"x :: y\" := (cons x y) \n                      (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                      (at level 60, right associativity).\n\nDefinition list123''' := [1;2;3].\n\nTheorem app_assoc : forall (X : Type),\n  forall (l1 l2 l3 : list X), \n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros X l1 l2 l3.\n  induction l1 as [| x l1' IHl1'].\n  - reflexivity.\n  - simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nTheorem app_nil_r : forall (X : Type), \n forall l : list X, l ++ [] = l.\nProof.\n  intros X l. induction l as [| x l' IHl'].\n  - reflexivity. \n  - simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem app_length : forall (X : Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros X l1 l2.\n  induction l1 as [| x 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 X l1 l2.\n  induction l1 as [| x l1' IHl1'].\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite <- app_assoc, IHl1'. 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 [| x l' IHl'].\n  - reflexivity.\n  - simpl. rewrite -> rev_app_distr, IHl'. reflexivity.\nQed.\n\nInductive prod (X Y : Type) : Type :=\n| pair: X -> Y -> prod X Y.\n\nArguments pair {X} {Y} _ _.\nNotation \"( x , y )\" := (pair x y). (* element of pair type *)\nNotation \"X * Y\" := (prod X Y) : type_scope. (* pair type *)\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} (l1 : list X) (l2 : list Y) : list (X*Y) :=\n  match l1,l2 with\n  | [],_ => []\n  | _,[] => [] \n  | hx::tx, hy::ty  => cons (hx,hy) (combine tx ty)\n  end.\n\nCheck @combine. (* forall X Y : Type, list X -> list Y -> list X * Y *)\n\nCompute (combine [1;2] [false; false; true; true]).\n\nFixpoint split {X Y : Type} (l : list (X*Y)) : (list X)*(list Y) :=\n  match l with\n  | [] => ([],[])\n  | h::t => ( (fst h)::(fst (split t)), (snd h)::(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}. Search beq_nat.\n\n(*\nFixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n  match l with\n  | [] => None\n  | h::t => match n with\n            | 0 => Some h\n            | S n' => nth_error t n'\n            end\n  end.\n*)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n  match l with \n  | [] => None  \n  | h::t => if (beq_nat 0 n) then Some h else nth_error t (pred n)\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n  | [] => None\n  | h::t => Some h\n  end.\n\nCheck @hd_error.\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.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\n\nFixpoint filter {X : Type} (test: X->bool) (l : list X) : list X :=\n  match l with\n  | [] => []\n  | h :: t => if (test h) then (h :: (filter test t)) else (filter test t)\n  end.\n\nExample test_filter1: filter 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).\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': filter (fun l => beq_nat (length l) 1) \n                              [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ] = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\nCompute (3 <= 4).\n\nFixpoint ble_nat (n m : nat) : bool :=\n  match n with \n  | 0 => true\n  | S n' => if (beq_nat m 0) then false else ble_nat n' (pred m)\n  end.\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n => andb (ble_nat 8 n) (evenb 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.\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\n\nFixpoint partition {X : Type} (test: X -> bool) (l : list X) : list X * list X :=\n  match l with\n  | [] => ([],[])\n  | h :: t => if test h then (h::(fst (partition test t)),(snd (partition test t)))\n                        else ((fst (partition test t)), h::(snd (partition test t)))\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.\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\nCompute rev [1;2;3].\n\nTheorem map_distr : forall (X Y: Type) (l1 l2 : list X) (f:X->Y), \n  (map f l1) ++ (map f l2) = (map f (l1 ++ l2)).\nProof.\n  intros X Y l1 l2 f. induction l1 as [|n l1' IHl1'].\n  - reflexivity.\n  - simpl. rewrite <- IHl1'. reflexivity.\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f:X->Y) (l:list X), \n  (map f (rev l)) = (rev (map f l)).\nProof.\n  intros X Y f l. induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite <- IHl'. rewrite <- map_distr. reflexivity.\nQed.\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)\n  end.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\nProof. reflexivity. Qed.\n\nFixpoint map_option {X Y : Type} (f:X->Y) (x : option X) : option Y :=\n  match x with\n  | None => None\n  | Some n => Some (f n)\n  end.\n\nFixpoint fold {X Y: Type} (f:X->Y->Y) (l : list X) (y : Y) : Y :=\n  match l with \n  | [] => y\n  | h :: t => f h (fold f t y)\n  end.\n\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;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\nDefinition constfun {X : Type} (x : X): nat -> X :=\n  fun n => x.\n\nDefinition ftrue := constfun true.\nCheck ftrue.\nCompute ftrue 3.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\nCheck plus. \n\nDefinition plus3 := plus 3.\n\nExample test_plus3 : plus3 4 = 7.\nProof. reflexivity. Qed.\nExample test_plus3' : doit3times plus3 0 = 9.\nProof. reflexivity. Qed.\nExample test_plus3'' : doit3times (plus 3) 0 = 9.\nProof. reflexivity. Qed.\n\nModule Exercises.\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\nTheorem fold_length_correct : forall (X : Type) (l : list X),\n  fold_length l = length l.\nProof. intros X l. induction l as [| n l' IHl'].\n- reflexivity.\n- simpl. rewrite <- IHl'. 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  (map f l) = (fold_map f l).\nProof. \n  intros X Y f l. induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nDefinition prod_curry {X Y Z : Type} (f:(X*Y)->Z) (a:X) (b:Y) : Z := \n  f (a,b).\nDefinition prod_uncurry {X Y Z : Type} (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. (* : forall (X Y Z : Type), (X*Y->Z)->(X->Y->Z). *)\nCheck @prod_uncurry. (* : forall (X Y Z : Type), (X->Y->Z)->(X*Y->Z). *)\n\nTheorem pair_parts : forall (X Y : Type) (p:X*Y), \n  (fst p, snd p) = p.\nProof.\n  intros X Y p. destruct p. simpl. reflexivity.\nQed. \n\nTheorem uncurry_curry : 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  unfold prod_curry, prod_uncurry. rewrite -> pair_parts. reflexivity.\nQed.\n\nModule Church.\nDefinition nat := forall X : Type, (X -> X) -> X -> X.\nDefinition one : nat :=\n  fun (X : Type) (f:X->X) (x:X) => f x.\nDefinition two : nat :=\n  fun (X : Type) (f:X->X) (x:X) => f (f x).\nDefinition zero : nat :=\n  fun (X : Type) (f:X->X) (x:X) => x.\n\nDefinition three : nat := @doit3times.\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.\nExample succ_2 : succ one = two.\nProof. reflexivity. Qed.\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) => n X f (m X f x).\n\nExample plus_1 : plus zero one = one.\nProof. reflexivity. Qed.\nExample plus_2 : plus two three = plus three two.\nProof. reflexivity. Qed.\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. reflexivity. Qed.\n\nCheck fun n:nat => plus three n.\nCompute succ (succ zero).\nCompute (plus three) two.\nCompute (plus three zero).\nCompute (plus three).\n\nDefinition mult (n m : nat) : nat :=\n  fun (X : Type) (f:X->X) (x:X) => n X (m X f) x.\n\nExample mult_1 : mult one one = one.\nProof. reflexivity. Qed.\nExample mult_2 : mult zero (plus three three) = zero.\nProof. reflexivity. Qed.\nExample mult_3 : mult two three = plus three three.\nProof. reflexivity. Qed.\n\nCompute fun (X : Type) (f:X->X) => three X f.\n\nEnd Church.\nEnd Exercises.\n", "meta": {"author": "scottviteri", "repo": "CoqProjects", "sha": "57ad9d6840ad3232d442861a0df3a583bef1ee62", "save_path": "github-repos/coq/scottviteri-CoqProjects", "path": "github-repos/coq/scottviteri-CoqProjects/CoqProjects-57ad9d6840ad3232d442861a0df3a583bef1ee62/LogicalFoundationsProblems/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.665252977723851}}
{"text": "(**************************************************************************)\n(*           *                                                            *)\n(*     _     *   The Coccinelle Library / Evelyne Contejean               *)\n(*    <o>    *          CNRS-LRI-Universite Paris Sud                     *)\n(*  -/@|@\\-  *                   A3PAT Project                            *)\n(*  -@ | @-  *                                                            *)\n(*  -\\@|@/-  *      This file is distributed under the terms of the       *)\n(*    -v-    *      CeCILL-C licence                                      *)\n(*           *                                                            *)\n(**************************************************************************)\n\nAdd LoadPath \"basis\". \n\n(**  *Dickson Lemma: the multiset extension of a well-founded ordering is well-founded.\n *)\n\nSet Implicit Arguments. \n\nRequire Export Setoid.\nRequire Import Relations.\nRequire Import List.\nRequire Import closure.\nRequire Import more_list.\nRequire Import Multiset.\nRequire Import list_permut.\nRequire Import ordered_set.\nRequire Import Arith.\n\nLtac dummy a b a_eq_b :=\nassert (Dummy : a = b); [exact a_eq_b | clear a_eq_b; rename Dummy into a_eq_b].\n\nModule Type D.\n\n  Declare Module Import DS : decidable_set.S.\n  Declare Module Import LP : list_permut.S with Definition EDS.A := DS.A \n                                                                  with Definition EDS.eq_A := (@eq DS.A).\n\n(** ** Definition of the multiset extension of a relation. *)\nInductive multiset_extension_step (R : relation A) : list A -> list A -> Prop :=\n  | rmv_case : \n     forall l1 l2 l la a, (forall b, mem EDS.eq_A b la -> R b a) -> \n      permut l1 (la ++ l) -> permut l2 (a :: l) ->\n      multiset_extension_step R l1 l2.\n\n(** [multiset_extension_step] is compatible with permutation. *)\nParameter list_permut_multiset_extension_step_1 :\n  forall R l1 l2 l, permut l1 l2 -> \n  multiset_extension_step R l1 l -> multiset_extension_step R l2 l.\n\nParameter list_permut_multiset_extension_step_2 :\n  forall R l1 l2 l, permut l1 l2 -> \n  multiset_extension_step R l l1 -> multiset_extension_step R l l2.\n\nAdd Parametric Morphism (R : relation A) : (multiset_extension_step R)\n  with signature  permut ==> permut ==> iff \n  as mult_morph.\nAdmitted.\n(** *** Accessibility lemmata. *)\nParameter list_permut_acc :\n  forall R l1 l2, permut l2 l1 -> \n  Acc (multiset_extension_step R) l1 -> Acc (multiset_extension_step R) l2.\n\n(** Main lemma. *)\nParameter dickson : \n  forall R, well_founded R -> well_founded (multiset_extension_step R).\n\nParameter dickson_strong : \n  forall R l, (forall a, In a l -> Acc R a) -> Acc (multiset_extension_step R) l.\n\nParameter context_trans_clos_multiset_extension_step_app1 :\n  forall R l1 l2 l, trans_clos (multiset_extension_step R) l1 l2 ->\n                         trans_clos (multiset_extension_step R) (l ++ l1) (l ++ l2).\n\nFunction consn (ll : list (A * list A)) : list A :=\n  match ll with \n  | nil => nil\n  | (e,_) :: ll => e:: (consn ll)\n  end.\n\nFunction appendn (ll : list (A * list A)) : list A :=\n  match ll with \n  | nil => nil\n  | (_,l) :: ll => l ++ (appendn ll)\n  end.\n\nParameter multiset_closure :\n  forall R, (forall x y, {R x y}+{~R x y}) -> transitive _ R ->\n  forall p q, trans_clos (multiset_extension_step R) p q ->\n  exists l, exists pq,\n  permut p ((appendn l) ++ pq) /\\\n  permut q ((consn l) ++ pq) /\\\n  l <> nil /\\\n  (forall a, forall la, In (a,la) l -> forall b, mem EDS.eq_A b la -> R b a) /\\\n  ((forall a, ~R a a) -> forall a, mem EDS.eq_A a (consn l) -> mem EDS.eq_A a (appendn l) -> False).\n\nEnd D.\n\nModule Make (DS1 : decidable_set.S).\n\nModule Import DS := decidable_set.Convert (DS1).\nModule Import LP := list_permut.Make (DS).\n\n\n\n\n(** ** Definition of the multiset extension of a relation. *)\nInductive multiset_extension_step (R : relation A) : list A -> list A -> Prop :=\n  | rmv_case : \n     forall l1 l2 l la a, (forall b, mem EDS.eq_A b la -> R b a) -> \n      permut l1 (la ++ l) -> permut l2 (a :: l) ->\n      multiset_extension_step R l1 l2.\n\n(** [multiset_extension_step] is compatible with permutation. *)\nLemma list_permut_multiset_extension_step_1 :\n  forall R l1 l2 l, permut l1 l2 -> \n  multiset_extension_step R l1 l -> multiset_extension_step R l2 l.\nProof.\nintros R l1 l2 l P M1; inversion M1 as [ k1 k l1' la a la_R_a P1 P2]; subst.\napply (rmv_case (l1:=l2) (l2:=l) (l:=l1') R la la_R_a); trivial.\napply permut_trans with l1.\napply permut_sym; assumption.\nassumption.\nQed.\n\nLemma list_permut_multiset_extension_step_2 :\n  forall R l1 l2 l, permut l1 l2 -> \n  multiset_extension_step R l l1 -> multiset_extension_step R l l2.\nProof.\nintros R l1 l2 l P M1; inversion M1 as [ k1 k l1' la a la_R_a P1 P2]; subst.\napply (rmv_case (l1:=l) (l2:=l2) (l:=l1') R la la_R_a); trivial.\napply permut_trans with l1.\napply permut_sym; assumption.\nassumption.\nDefined.\n\nAdd Parametric Morphism (R : relation A) : (multiset_extension_step R)\n  with signature  permut ==> permut ==> iff \n  as mult_morph.\nProof.\nintros l1 l2 P12 l3 l4 P34; split; [intro R13 | intro R24].\napply list_permut_multiset_extension_step_2 with l3; trivial.\napply list_permut_multiset_extension_step_1 with l1; trivial.\napply list_permut_multiset_extension_step_2 with l4; auto;\napply list_permut_multiset_extension_step_1 with l2; auto.\nQed.\n\n(** If n << {a} U m, then \n      either, there exists n' such that n = {a} U n' and n' << m,\n      or, there exists k, such that n = k U m, and k << {a}. *)\nLemma two_cases :\n forall R a m n, \n multiset_extension_step R n (a :: m) ->\n (exists n', permut n (a :: n') /\\ \n             multiset_extension_step R n' m) \\/\n (exists k, (forall b, mem EDS.eq_A b k -> R b a) /\\ \n            permut n (k ++ m)).\nProof.\nintros R a m n M; inversion_clear M as [x1 x2 l la b H H0 H1];\ngeneralize (eq_bool_ok a b); case (DS1.eq_bool a b); [intro a_eq_b; subst b | intro a_diff_b].\nrewrite <- permut_cons in H1; [idtac | apply (equiv_refl _ _ eq_proof)].\nright; exists la; split; trivial.\napply permut_trans with (la ++ l).\nassumption.\nrewrite <- permut_app1; auto.\n\nleft; generalize (remove_is_sound b m); case (@remove A eq_bool b m).\nintros m' P; exists (la ++ m'); split.\nrefine (permut_trans H0 _).\napply permut_trans with (la ++ a :: m').\nrefine (proj1 (permut_app1 _ _ _) _).\napply permut_sym.\nrewrite (@permut_cons b b (a :: m') l).\napply permut_trans with (a :: m).\napply permut_sym; rewrite <- (permut_cons_inside (e1 := a) (e2 := a) m (b :: nil) m').\nassumption.\napply (equiv_refl _ _ eq_proof).\nassumption.\napply (equiv_refl _ _ eq_proof).\napply permut_sym; rewrite <- (permut_cons_inside (e1 := a) (e2 := a) (la ++ m') la m').\napply permut_refl.\napply (equiv_refl _ _ eq_proof).\napply (rmv_case (l1:=la ++ m') (l2:= m) (l:= m') R la H); auto; \napply permut_sym; rewrite <- permut_cons_inside; auto.\nintro b_not_mem_m; apply False_rec.\nassert (b_mem_am : mem EDS.eq_A b (a :: m)).\nrewrite (mem_permut_mem b H1); left.\napply (equiv_refl _ _ eq_proof).\nsimpl in b_mem_am; case b_mem_am; clear b_mem_am.\nintro; apply a_diff_b; apply sym_eq; assumption.\nexact b_not_mem_m.\nQed.\n\n\n(** *** Accessibility lemmata. *)\nLemma list_permut_acc :\n  forall R l1 l2, permut l2 l1 -> \n  Acc (multiset_extension_step R) l1 -> Acc (multiset_extension_step R) l2.\nProof.\nintros R l1 l2 Meq A1; apply Acc_intro; intros l M2;\ninversion A1; apply H; subst.\napply list_permut_multiset_extension_step_2 with l2; assumption.\nDefined.\n\n(*\nAdd Parametric Morphism (R : relation A) : \n             Acc (multiset_extension_step R)) : acc_morph.\nProof.\nintros R l1 l2 P; split; [intro A1 | intro A2].\napply list_permut_acc with l1; trivial; rewrite <- P; auto.\napply list_permut_acc with l2; trivial.\nQed.\n*)\n\nLemma dickson_aux1 :\nforall (R : relation A) a,\n (forall b, R b a -> \n  forall m, Acc (multiset_extension_step R) m -> \n            Acc (multiset_extension_step R) (b :: m)) ->\n forall m, Acc (multiset_extension_step R) m -> \n (forall m', (multiset_extension_step R) m' m -> \n             Acc (multiset_extension_step R) (a :: m')) ->\n Acc (multiset_extension_step R) (a :: m).\nProof. \nintros R a IH2_a m Acc_m IHa_M; apply Acc_intro;\nintros n H; elim (two_cases H); clear H.\nintros [n' [P M]]; refine (list_permut_acc P _); apply IHa_M; trivial.\nintros [k [M P]]; refine (list_permut_acc P _); clear P; induction k; trivial; simpl;\napply IH2_a.\napply M; left.\napply (equiv_refl _ _ eq_proof).\napply IHk; intros; apply M; right; trivial.\nDefined.\n\nLemma dickson_aux2 :\nforall R m,\n  Acc (multiset_extension_step R) m ->\n  forall a, (forall b, R b a -> \n             forall m, Acc (multiset_extension_step R) m -> \n                       Acc (multiset_extension_step R) (b :: m)) ->\n   Acc (multiset_extension_step R) (a :: m). \nProof.\nintros R m Acc_m a IH2_a;\napply (Acc_iter  (R:= multiset_extension_step R)\n(fun m => Acc (multiset_extension_step R) m -> \nAcc (multiset_extension_step R) (a :: m))); trivial;\nclear m Acc_m;\nintros m H Acc_m; apply dickson_aux1; trivial;\nintros; apply H; trivial;\napply Acc_inv with m; trivial.\nDefined.\n\nLemma dickson_aux3 :\nforall R a, Acc R a -> forall m, Acc (multiset_extension_step R) m ->\nAcc (multiset_extension_step R) (a :: m).\nProof.\nintros R a Acc_a;\napply (Acc_iter  (R:= R)\n(fun a => Acc R a -> forall m, Acc (multiset_extension_step R) m -> \nAcc (multiset_extension_step R) (a :: m))); trivial;\nclear a Acc_a;\nintros a H Acc_a m Acc_m; apply dickson_aux2; trivial;\nintros; apply H; trivial;\napply Acc_inv with a; trivial.\nDefined.\n\n(** Main lemma. *)\nLemma dickson : \n  forall R, well_founded R -> well_founded (multiset_extension_step R).\nProof.\nintros R Wf_R; unfold well_founded in *;\nintros m; induction m as [ | a m].\napply Acc_intro; intros m H; inversion_clear H;\nabsurd (a :: l = nil).\ndiscriminate.\napply (permut_nil (R := eq_A)).\napply permut_sym; trivial.\napply dickson_aux3; trivial.\nDefined.\n\nLemma dickson_strong : \n  forall R l, (forall a, In a l -> Acc R a) -> Acc (multiset_extension_step R) l.\nProof.\nintros R m; induction m as [ | a m].\nintros _; apply Acc_intro; intros m H; inversion_clear H;\nabsurd (a :: l = nil).\ndiscriminate.\napply (permut_nil (R := eq_A)).\napply permut_sym; trivial.\nintros; apply dickson_aux3.\napply H; left; trivial.\napply IHm; intros; apply H; right; trivial.\nQed.\n\n(** ** More results on transitive closure of mult_step *)\n\nLemma list_permut_trans_clos_multiset_extension_step_1 :\n  forall R l1 l2 l, permut l1 l2 -> \n  (trans_clos (multiset_extension_step R)) l1 l -> \n  (trans_clos (multiset_extension_step R)) l2 l.\nProof.\nintros R l1 l1' l P H; induction H as [ l1 l2 H | l1 l2 l3 H1 H2 H3].\napply t_step; apply list_permut_multiset_extension_step_1 with l1; trivial.\napply t_trans with l2; trivial; apply list_permut_multiset_extension_step_1 with l1; trivial.\nQed.\n\nLemma list_permut_trans_clos_multiset_extension_step_2 :\n  forall R l1 l2 l, permut l1 l2 -> \n  (trans_clos (multiset_extension_step R)) l l1 -> \n  (trans_clos (multiset_extension_step R)) l l2.\nProof.\nintros R l1 l3 l P H; induction H as [ l1 l2 H | l1 l2 l3' H1 H2 H3].\napply t_step; apply list_permut_multiset_extension_step_2 with l2; trivial.\napply t_trans with l2; trivial; apply H3; trivial.\nQed.\n\nLemma context_multiset_extension_step_app1 :\n  forall R l1 l2 l, multiset_extension_step R l1 l2 ->\n                         multiset_extension_step R (l ++ l1) (l ++ l2).\nProof.\nintros R l1 l2 l H; destruct H as [l1 l2 l12 la a H P1 P2].\napply (@rmv_case R (l++l1) (l++l2) (l++l12) la a); trivial.\napply permut_trans with (l ++ la ++ l12).\nrewrite <- permut_app1; trivial.\ndo 2 rewrite <- app_ass; rewrite <- permut_app2; trivial.\napply list_permut_app_app.\napply permut_trans with (l ++ a :: l12).\nrewrite <- permut_app1; trivial.\napply permut_sym; rewrite <- permut_cons_inside.\napply permut_refl.\napply (equiv_refl _ _ eq_proof).\nQed.\n\nLemma context_trans_clos_multiset_extension_step_app1 :\n  forall R l1 l2 l, trans_clos (multiset_extension_step R) l1 l2 ->\n                         trans_clos (multiset_extension_step R) (l ++ l1) (l ++ l2).\nProof.\nintros R l1 l2 l H; induction H.\napply t_step; apply context_multiset_extension_step_app1; trivial.\napply t_trans with (l ++ y); trivial.\napply context_multiset_extension_step_app1; trivial.\nQed.\n\nLemma context_multiset_extension_step_cons :\n  forall R, (forall a, ~R a a) -> \n  forall a l1 l2, multiset_extension_step R (a :: l1) (a :: l2) ->\n                         multiset_extension_step R l1 l2.\nProof.\nintros R irrefl_R a l1 l2 H;\ninversion H as [a_l1 a_l2 lc lb b H' P1 P2 H2 H3]; subst.\nassert (a_mem_blc : mem EDS.eq_A a (b :: lc)).\napply cons_permut_mem with l2 a; trivial.\napply (equiv_refl _ _ eq_proof).\nsimpl in a_mem_blc; destruct a_mem_blc as [a_eq_b | a_mem_lc].\ndummy a b a_eq_b;\nsubst b; assert (a_mem_lb_lc : mem EDS.eq_A a (lb ++ lc)).\napply cons_permut_mem with l1 a; trivial.\napply (equiv_refl _ _ eq_proof).\nrewrite <- mem_or_app in a_mem_lb_lc.\ndestruct a_mem_lb_lc as [a_mem_lb | a_mem_lc].\nabsurd (R a a); [apply (irrefl_R a) | apply H'; trivial].\ngeneralize (mem_split_set _ _ eq_bool_ok _ _ a_mem_lc).\nintros [a' [lc' [lc'' [a_eq_a' [H'' _]]]]]; \ndummy a a' a_eq_a';\nsubst a' lc; apply (rmv_case R (l1:=l1) (l2:= l2) (l:=lc' ++ lc'') lb (a:=a)); trivial.\nrewrite <- app_ass in P1; rewrite <- (permut_cons_inside) in P1.\nrewrite <- ass_app in P1; trivial.\napply (equiv_refl _ _ eq_proof).\nrewrite app_comm_cons in P2; rewrite <- (permut_cons_inside) in P2; trivial.\napply (equiv_refl _ _ eq_proof).\n\ngeneralize (mem_split_set _ _ eq_bool_ok _ _ a_mem_lc).\nintros [a' [lc' [lc'' [a_eq_a' [H'' _]]]]]; \ndummy a a' a_eq_a';\nsubst a' lc; apply (rmv_case R (l1:=l1) (l2:= l2) (l:=lc' ++ lc'') lb (a:=b)); trivial.\nrewrite <- app_ass in P1; rewrite <- (permut_cons_inside) in P1.\nrewrite <- ass_app in P1; trivial.\napply (equiv_refl _ _ eq_proof).\nrewrite app_comm_cons in P2; rewrite <- (permut_cons_inside) in P2.\nsimpl  in P2; trivial.\napply (equiv_refl _ _ eq_proof).\nQed.\n\nLemma remove_context_multiset_extension_step_app1 :\n  forall R,  (forall a, ~R a a) -> \n  forall l1 l2 l, multiset_extension_step R (l ++ l1) (l ++ l2) ->\n                         multiset_extension_step R l1 l2.\nProof.\nintros R irrefl_R l1 l2 l; generalize l1 l2; clear l1 l2; \ninduction l as [ | a l]; trivial.\nintros l1 l2 H; \nassert (H' : multiset_extension_step R (a :: l1) (a :: l2)).\napply IHl.\napply list_permut_multiset_extension_step_2 with ((a :: l) ++ l2).\nsimpl; rewrite <- permut_cons_inside; auto.\napply (equiv_refl _ _ eq_proof).\napply list_permut_multiset_extension_step_1 with ((a :: l) ++ l1); trivial.\nsimpl; rewrite <- permut_cons_inside; auto.\napply (equiv_refl _ _ eq_proof).\napply context_multiset_extension_step_cons with a; trivial.\nQed.\n\nLemma context_multiset_extension_step_app2 :\n  forall R l1 l2 l, multiset_extension_step R l1 l2 ->\n                         multiset_extension_step R (l1 ++ l) (l2 ++ l).\nProof.\nintros R l1 l2 l H; destruct H as [l1 l2 l12 la a H P1 P2].\napply (@rmv_case R (l1++l) (l2++l) (l12++l) la a); trivial.\nrewrite <- app_ass; rewrite <- permut_app2; trivial.\nrewrite app_comm_cons; rewrite <- permut_app2; trivial.\nQed.\n\nFunction consn (ll : list (A * list A)) : list A :=\n  match ll with \n  | nil => nil\n  | (e,_) :: ll => e:: (consn ll)\n  end.\n\nLemma mem_consn : \n  forall a ll, mem EDS.eq_A a (consn ll) <-> exists la, In (a,la) ll.\nProof.\nintros a ll; split; intro H;\nfunctional induction (consn ll) \n   as [ | H1 b lb ll H2 IH].\ncontradiction.\nsimpl in H; destruct H as [a_eq_b | a_in_cnsl].\ndummy a b a_eq_b;\nexists lb; subst; left; trivial.\ndestruct (IH a_in_cnsl) as [la H].\nexists la; right; trivial.\ndestruct H; contradiction.\ndestruct H as [la [ala_eq_blb | ala_in_ll]].\ninjection ala_eq_blb; intros; subst; left; apply (equiv_refl _ _ eq_proof); trivial.\nright; apply IH; exists la; trivial.\nQed.\n\nLemma consn_app :\n forall ll1 ll2, consn (ll1 ++ ll2) = consn ll1 ++ consn ll2.\nProof.\nintros ll1; induction ll1 as [ | [a la] ll1]; simpl; trivial; simpl; \nintros; rewrite IHll1; trivial.\nQed.\n\nFunction appendn (ll : list (A * list A)) : list A :=\n  match ll with \n  | nil => nil\n  | (_,l) :: ll => l ++ (appendn ll)\n  end.\n\nLemma appendn_app :\n forall ll1 ll2, appendn (ll1 ++ ll2) = appendn ll1 ++ appendn ll2.\nProof.\nintros ll1; induction ll1 as [ | [a la] ll1]; simpl; trivial; simpl; \nintros; rewrite IHll1; rewrite ass_app; trivial.\nQed.\n\nLemma in_appendn : \n  forall a ll, mem EDS.eq_A a (appendn ll) -> exists b, exists lb, In (b,lb) ll /\\ mem EDS.eq_A a lb.\nProof.\nintros a ll H; \nfunctional induction (appendn ll) \n   as [ | H1 b lb ll H2 IH].\ncontradiction.\nrewrite <- mem_or_app in H; destruct H as [a_mem_lb | a_mem_appl].\nexists b; exists lb; split; trivial; left; trivial.\ndestruct (IH a_mem_appl) as [c [lc [H1 H2]]]; \nexists c; exists lc; split; trivial; right; trivial.\nQed.\n\nLemma multiset_closure_aux :\n  forall (R : relation A) p q l pq, \n  permut p ((appendn l) ++ pq) ->\n  permut q ((consn l) ++ pq) ->\n  l <> nil ->\n  (forall a, forall la, In (a,la) l -> forall b, mem EDS.eq_A b la -> R b a) ->\n  trans_clos (multiset_extension_step R) p q.\nProof.\nintros R p q l; generalize p q; clear p q; induction l as [ | [x lx] l].\nsimpl; intros p q pq Pp Pq H; absurd (@nil (A * list A) = nil); trivial.\nsimpl; intros p q pq Pp Pq _ H.\nassert (lx_lt_x : forall b, mem EDS.eq_A b lx -> R b x).\napply H; left; trivial.\ndestruct l as [ | [y ly] l]; simpl in *.\nrewrite <- app_nil_end in Pp.\nsimpl in Pq; apply t_step. \nexact (rmv_case R lx lx_lt_x Pp Pq).\napply t_trans with (x :: ly ++ (appendn l) ++ pq).\ndo 2 rewrite app_ass in Pp;\nrefine (rmv_case R lx lx_lt_x Pp (permut_refl _)).\nrefine (list_permut_trans_clos_multiset_extension_step_2  \n                      (permut_sym Pq) _).\napply (@context_trans_clos_multiset_extension_step_app1 R\n            (ly ++ appendn l ++ pq) (y :: consn l ++ pq) (x :: nil)); \napply (@IHl (ly ++ appendn l ++ pq) (y :: consn l ++ pq) pq); auto.\nrewrite ass_app; auto.\ndiscriminate.\nintros a la H1 b b_in_la; apply (H a la); trivial; right; trivial.\nQed.\n\nLemma multiset_closure_aux2 :\n  forall (R : relation A) p q le l pq, \n  permut p ((appendn l) ++ pq) ->\n  permut q (le ++ (consn l) ++ pq) ->\n  l <> nil \\/ le <> nil ->\n  (forall a, forall la, In (a,la) l -> forall b, mem EDS.eq_A b la -> R b a) ->\n  trans_clos (multiset_extension_step R) p q.\nProof.\nintros R p q le l pq Pp Pq H H';\napply (@multiset_closure_aux R p q ((map (fun x => (x, @nil A)) le) ++ l) pq).\napply permut_trans with (appendn l ++ pq).\nassumption.\nrewrite <- permut_app2;\nrewrite appendn_app; clear Pq H; induction le as [ | e le]; simpl; auto.\napply permut_trans with (le ++ consn l ++ pq).\nassumption.\nrewrite ass_app; rewrite <- permut_app2;\nrewrite consn_app; clear Pq H; induction le as [ | e le]; simpl; auto.\nrewrite <- permut_cons; trivial.\napply (equiv_refl _ _ eq_proof).\nintro H''; destruct (app_eq_nil _ _ H'') as [ l_eq_nil le_eq_nil];\ndestruct H as [le_diff_nil | l_diff_nil].\nabsurd (l = nil); trivial.\ndestruct le as [ | e le].\nabsurd (@nil A = nil); trivial.\ndiscriminate.\nclear Pq H; induction le as [ | e le]; simpl; trivial.\nintros a la [H | H] b b_in_la; \n[injection H; intros; subst; contradiction | apply (IHle a la); trivial].\nQed.\n\n\nModule LDS.\n\nDefinition A := (A * (list A))%type.\nDefinition eq_A := @eq A.\n\nLemma eq_proof : equivalence A eq_A.\nunfold eq_A; split.\nintro n; apply refl_equal.\nintros a1 a2 a3 H1 H2; rewrite H1; assumption.\nintros a1 a2 H; rewrite H; apply refl_equal.\nQed.\n\n  Add Relation A eq_A \n  reflexivity proved by (Relation_Definitions.equiv_refl _ _ eq_proof)\n    symmetry proved by (Relation_Definitions.equiv_sym _ _ eq_proof)\n      transitivity proved by (Relation_Definitions.equiv_trans _ _ eq_proof) as EQA.\n\nFixpoint eq_bool_list l1 l2: bool :=\n     match l1, l2 with\n     | nil, nil => true\n     | nil, (_ :: _) => false\n     | (a1 :: l1), nil => false\n     | (a1 :: l1), (a2 :: l2) => if DS1.eq_bool a1 a2 then eq_bool_list l1 l2 else false\n     end.\n\nDefinition eq_bool al1 al2 : bool :=  \n  match al1, al2 with\n  | (e1,l1), (e2,l2) => if DS1.eq_bool e1 e2 then eq_bool_list l1 l2 else false\n  end.\n\nLemma eq_bool_ok : forall al1 al2, match eq_bool al1 al2 with true => al1 = al2 | false => ~al1 = al2 end.\nProof.\nintros [e1 l1] [e2 l2]; simpl.\ngeneralize (DS1.eq_bool_ok e1 e2); case (DS1.eq_bool e1 e2); [intros e1_eq_e2 | intros e1_diff_e2].\nrevert l1 l2.\nassert (H :  forall l1 l2, match eq_bool_list l1 l2 with true => l1 = l2 | false => ~l1 = l2 end).\nfix 1.\nintros [ | a1 l1] [ | a2 l2]; simpl.\napply refl_equal.\ndiscriminate.\ndiscriminate.\ngeneralize (DS1.eq_bool_ok a1 a2); case (DS1.eq_bool a1 a2); [intros a1_eq_a2 | intros a1_diff_a2].\ngeneralize (eq_bool_ok0 l1 l2); case (eq_bool_list l1 l2); [intro l1_eq_l2 | intro l1_diff_l2].\nsubst; apply refl_equal.\nintro E; apply l1_diff_l2; injection E; intros; subst; apply refl_equal.\nintro E; apply a1_diff_a2; injection E; intros; subst; apply refl_equal.\nintros l1 l2; generalize (H l1 l2).\ncase (eq_bool_list l1 l2); [intro l1_eq_l2 | intro l1_diff_l2].\nsubst; apply (equiv_refl _ _ eq_proof).\nintro E; apply l1_diff_l2; injection E; intros; subst; apply refl_equal.\nintro E; apply e1_diff_e2; injection E; intros; subst; apply refl_equal.\nDefined.\n\nEnd LDS.\n\nModule LEDS := decidable_set.Convert(LDS).\nModule LLP := list_permut.Make (LEDS).\n\nLemma permut_consn :\n forall ll1 ll2, LLP.permut ll1 ll2 -> permut (consn ll1) (consn ll2).\nProof.\nintros ll1; induction ll1 as [ | [a la] ll1]; simpl; intros ll2 P.\nrewrite (permut_nil (LLP.permut_sym P)); simpl; auto.\nassert (ala_in_ll2 : In (a,la) ll2).\nrewrite <- (in_permut_in P); left; trivial.\ndestruct (In_split _ _ ala_in_ll2) as [ll2' [ll2'' H]]; subst.\nrewrite <- LLP.permut_cons_inside in P.\nrewrite consn_app; simpl; rewrite <- permut_cons_inside.\nrewrite <- consn_app; apply IHll1; trivial.\napply (equiv_refl _ _ eq_proof).\napply (equiv_refl _ _ LEDS.eq_proof).\nQed.\n\nLemma permut_appendn :\n forall ll1 ll2, LLP.permut ll1 ll2 -> permut (appendn ll1) (appendn ll2).\nProof.\nintros ll1; induction ll1 as [ | [a la] ll1]; simpl; intros ll2 P.\nrewrite (permut_nil (LLP.permut_sym P)); simpl; auto.\nassert (ala_in_ll2 : In (a,la) ll2).\nrewrite <- (in_permut_in P); left; trivial.\ndestruct (In_split _ _ ala_in_ll2) as [ll2' [ll2'' H]]; subst.\nrewrite appendn_app; simpl.\nrefine (permut_trans _ (list_permut_app_app _ _)).\nrewrite <- ass_app.\nrewrite <- permut_app1.\nrefine (permut_trans _ (list_permut_app_app _ _)).\nrewrite <- appendn_app; apply IHll1; trivial.\nrewrite <- LLP.permut_cons_inside in P; trivial.\napply (equiv_refl _ _ LEDS.eq_proof).\nQed.\n\nLemma multiset_closure_aux3 :\n  forall l lc cns, permut (consn l) (lc ++ cns) ->\n               exists ll, exists ll',  LLP.permut l (ll ++ ll') /\\ \n                                           permut (consn ll)  lc /\\ \n                                           permut (consn ll') cns.\nProof.\nassert (H : forall consnl lccns, permut consnl lccns -> \n               forall l lc cns ,  consnl = consn l -> lccns = lc ++ cns ->\n               exists ll, exists ll',  LLP.permut l (ll ++ ll') /\\ \n                                           permut (consn ll)  lc /\\ \n                                           permut (consn ll') cns).\nintros consnl lccns P; induction P as [ | a1 a1' consnl k1 k2 H P].\nintros [ | [a1 l1] l].\nintros [ | c lc].\nintros [ | c' cns] H1 H2.\nexists (@nil (A * list A)); exists (@nil (A * list A)); simpl; repeat split; auto.\ndiscriminate.\nintros cns _ H2; discriminate.\nintros lc cns H1; discriminate.\nintros [ | [b1 l1] l] lc cns H1 H2.\ndiscriminate.\ninjection H1; clear H1; intros; subst.\ngeneralize (split_list _ _ _ _ H2); clear H2; intros [[k [H3 H4]] | [k [H3 H4]]]; subst.\ngeneralize (IHP l lc (k ++ k2) (refl_equal _)); rewrite ass_app.\nintro IH; generalize (IH (refl_equal _)); clear IH.\nintros [ll [ll' [Q1 [Q2 Q3]]]].\nexists ll; exists ((b1,l1) :: ll'); simpl; repeat split; trivial.\nrewrite <- LLP.permut_cons_inside; [assumption | apply refl_equal].\nrewrite <- permut_cons_inside; assumption.\nrevert H4; case k; [idtac | intros a k']; intro H4.\nsimpl in H4; subst.\ngeneralize (IHP l k1 k2 (refl_equal _) (refl_equal _)).\nintros [ll [ll' [Q1 [Q2 Q3]]]].\nexists ll; exists ((b1,l1) :: ll'); repeat split.\nrewrite <- LLP.permut_cons_inside; [assumption | apply refl_equal].\nrewrite <- app_nil_end; assumption.\nsimpl; rewrite <- permut_cons; assumption.\ninjection H4; clear H4; intros; subst a k2.\nassert (IH := IHP l (k1 ++ k') cns (refl_equal _)).\nrewrite ass_app in IH.\ngeneralize (IH (refl_equal _)); clear IH; intros [ll [ll' [Q1 [Q2 Q3]]]].\nexists ((b1, l1) :: ll); exists ll'; repeat split.\nsimpl; rewrite <- LLP.permut_cons; [assumption | apply refl_equal].\nsimpl; rewrite <- permut_cons_inside; assumption.\nassumption.\nintros l lc cns P; apply (H (consn l) (lc ++ cns) P _ _ _ (refl_equal _) (refl_equal _)).\nQed.\n\nLemma multiset_closure :\n  forall R, transitive _ R ->\n  forall p q, trans_clos (multiset_extension_step R) p q ->\n  exists l, exists pq,\n  permut p ((appendn l) ++ pq) /\\\n  permut q ((consn l) ++ pq) /\\\n  l <> nil /\\\n  (forall a, forall la, In (a,la) l -> forall b, mem EDS.eq_A b la -> R b a) /\\\n  ((forall a, ~R a a) -> forall a, mem EDS.eq_A a (consn l) -> mem EDS.eq_A a (appendn l) -> False).\nProof.\nintros R trans_R p q p_lt_q; induction p_lt_q as [p q p_lt_q | p q r p_lt_q q_lt_r].\n(* R_step *)\ndestruct p_lt_q as [p q pq la a la_lt_a Pp Pq].\nexists ((a,la) :: nil); exists pq; simpl; repeat split; auto.\nrewrite <- app_nil_end; auto.\ndiscriminate.\nintros x lx [H | H] b b_in_lx; \n[injection H; intros; subst; apply la_lt_a; trivial | contradiction].\nrewrite <- app_nil_end; intros irrefl_R b [a_eq_b | Abs] b_in_la.\ndummy b a a_eq_b;\nsubst b; apply (irrefl_R a); apply la_lt_a; trivial.\ncontradiction.\n\n(* Transitive step *)\ndestruct p_lt_q as [p q pq la a la_lt_a Pp Pq].\ndestruct IHq_lt_r as [l [qr [Pq' [Pr [l_diff_nil [app_lt_cns app_disj_cns]]]]]].\nassert (a_in_appl_qr : mem EDS.eq_A a ((appendn l) ++ qr)).\napply (proj1 (mem_permut_mem a Pq')).\napply (proj1 (mem_permut_mem a (permut_sym Pq))).\nleft; apply (equiv_refl _ _ eq_proof).\nrewrite <- mem_or_app in a_in_appl_qr.\ngeneralize (mem_bool_ok _ _ EDS.eq_bool_ok a (appendn l)).\ncase (mem_bool EDS.eq_bool a (appendn l)); [intro a_in_appl | intro a_not_in_appl].\ndestruct (in_appendn _ _ a_in_appl) as [x [lx [xlx_in_l a_in_lx]]].\ndestruct (mem_split_set _ _ eq_bool_ok _ _ a_in_lx) as [a' [lx' [lx'' [a_eq_a' [H _]]]]].\nsimpl in a_eq_a'; simpl in H; subst lx.\ndestruct (In_split _ _  xlx_in_l) as [l' [l'' H]]; subst l.\nrewrite appendn_app in Pq'; simpl in Pq'; do 3 rewrite <-  ass_app in Pq'.\nsimpl in Pq'; rewrite ass_app in Pq'.\ngeneralize (permut_trans (permut_sym Pq) Pq'); clear Pq'; intro Pq'.\nrewrite <- permut_cons_inside in Pq'.\nrewrite <- ass_app in Pq'.\ngeneralize (remove_equiv_is_sound (consn (l' ++ l'')) la).\ndestruct (@remove_equiv A eq_bool  (consn (l' ++ l'')) la) as [cns la'].\nintros [lc [Pcns [Pla cns_disj_la']]];\ndestruct (multiset_closure_aux3 (l' ++ l'') lc cns Pcns) as [ll [ll' [P' [H1 H2]]]];\nexists ((x, lx' ++ lx'' ++ la' ++ (appendn ll)) :: ll'); exists (lc ++ qr); split.\napply permut_trans with (la ++ pq).\nassumption.\napply permut_trans with ((lc ++ la') ++ pq).\nrewrite <- permut_app2; trivial.\napply permut_trans with ((lc ++ la') ++ (appendn l' ++ lx' ++ lx'' ++ appendn l'' ++ qr)).\nrewrite <- permut_app1; trivial.\nsimpl; do 5 rewrite ass_app; rewrite <- permut_app2.\nrefine (permut_trans _ (list_permut_app_app _ _)).\ndo 5 rewrite <- ass_app; rewrite <- permut_app1.\nrewrite ass_app.\nrefine (permut_trans (list_permut_app_app _ _) _).\ndo 3 rewrite <- ass_app; do 2 rewrite <- permut_app1.\nrefine (permut_trans (list_permut_app_app _ _) _).\ndo 2 rewrite <- ass_app; rewrite <- permut_app1.\ndo 2 rewrite <- appendn_app; apply permut_appendn; trivial.\nsplit.\nrewrite ass_app.\napply permut_trans with (consn (l' ++ (x, lx' ++ a' :: lx'') :: l'') ++ qr).\nassumption.\nrewrite <- permut_app2;\nrewrite consn_app; simpl; apply permut_sym; \nrewrite <- permut_cons_inside.\napply permut_trans with (cns ++ lc).\nrewrite <- permut_app2; assumption.\nrefine (permut_trans (list_permut_app_app _ _) _).\napply permut_trans with  (consn (l' ++ l'')).\napply permut_sym; assumption.\nrewrite consn_app; auto.\napply (equiv_refl _ _ eq_proof).\nsplit.\ndiscriminate.\nsplit.\nsimpl; intros y ly [yly_eq_xly | yly_in_ll''] b b_in_ly.\ninjection yly_eq_xly; intros; subst y ly; clear yly_eq_xly.\nrewrite ass_app in b_in_ly;\nrewrite <- mem_or_app in b_in_ly.\ndestruct b_in_ly as [b_in_lx | b_in_la_app].\napply (app_lt_cns x (lx' ++ a' :: lx'')); trivial.\napply mem_insert; trivial.\nrewrite <- mem_or_app in b_in_la_app.\ndestruct b_in_la_app as [b_in_la | b_in_app].\napply trans_R with a.\napply la_lt_a.\nrewrite (mem_permut_mem b Pla); rewrite <- mem_or_app; right; trivial.\napply (app_lt_cns x (lx' ++ a' :: lx'')); trivial.\ndestruct (in_appendn _ _ b_in_app) as [y [ly [yly_in_ll b_in_ly]]].\napply trans_R with y.\napply (app_lt_cns y ly); trivial; apply in_insert.\nrewrite (list_permut.in_permut_in P'); apply in_or_app; left; trivial.\nassert (y_in_lc : mem eq_A y lc).\nrewrite <- (mem_permut_mem y H1).\nrewrite mem_consn; exists ly; trivial.\napply trans_R with a.\napply la_lt_a; rewrite (mem_permut_mem y Pla); rewrite <- mem_or_app; left; trivial.\napply (app_lt_cns x (lx' ++ a' :: lx'')).\napply in_or_app; right; left; apply refl_equal.\nrewrite <- mem_or_app; right; left; trivial.\napply (app_lt_cns y ly); trivial; apply in_insert; trivial.\nrewrite (list_permut.in_permut_in P').\napply in_or_app; right; trivial.\nsimpl; intros irrefl_R b [x_eq_b | b_in_cns] b_in_lx_la_app;\ndo 3 rewrite <- ass_app in b_in_lx_la_app; do 2 rewrite ass_app in b_in_lx_la_app.\ndummy b x x_eq_b;\nsubst b; rewrite <- mem_or_app in b_in_lx_la_app.\ndestruct b_in_lx_la_app as [b_in_lx_la | b_in_app].\nrewrite <- mem_or_app in b_in_lx_la.\ndestruct b_in_lx_la as [b_in_lx | b_in_la].\napply (irrefl_R x); apply (app_lt_cns x (lx' ++ a' :: lx'')).\napply in_or_app; right; left; apply refl_equal.\napply mem_insert; trivial.\napply (irrefl_R x); apply trans_R with a.\napply la_lt_a; rewrite (mem_permut_mem x Pla); rewrite <- mem_or_app; right; trivial.\napply (app_lt_cns x (lx' ++ a' :: lx'')).\napply in_or_app; right; left; apply refl_equal.\nrewrite <- mem_or_app; right; left; trivial.\napply (app_disj_cns irrefl_R x).\nrewrite consn_app; rewrite <- mem_or_app; right; left.\napply (equiv_refl _ _ eq_proof).\nrewrite <- appendn_app in b_in_app.\nrewrite <- (mem_permut_mem x (permut_appendn P')) in b_in_app.\nrewrite appendn_app; rewrite <- mem_or_app.\nrewrite appendn_app in b_in_app; rewrite <- mem_or_app in b_in_app.\ndestruct b_in_app as [b_in_app | b_in_app].\nleft; trivial.\nright; simpl; rewrite <- mem_or_app; right; trivial.\nsimpl; rewrite <- mem_or_app in b_in_lx_la_app.\ndestruct b_in_lx_la_app as [b_in_lx_la | b_in_app].\nsimpl; rewrite <- mem_or_app in b_in_lx_la.\ndestruct b_in_lx_la as [b_in_lx | b_in_la].\napply (app_disj_cns irrefl_R b).\nrewrite consn_app; simpl; apply mem_insert; rewrite <- consn_app. \nrewrite (mem_permut_mem b (permut_consn P'));\nrewrite consn_app; rewrite <- mem_or_app; right; trivial.\nrewrite appendn_app; rewrite <- mem_or_app; right;\nsimpl; rewrite <- mem_or_app; left; apply mem_insert; trivial.\napply (cns_disj_la' b); trivial.\nrewrite <- (mem_permut_mem b H2); trivial.\napply (app_disj_cns irrefl_R b).\nrewrite consn_app; simpl; apply mem_insert;\nrewrite <- consn_app; rewrite (mem_permut_mem b (permut_consn P'));\nrewrite consn_app; rewrite <- mem_or_app; right; trivial.\nrewrite <- appendn_app in b_in_app;\nrewrite <- (mem_permut_mem b (permut_appendn P')) in b_in_app.\nrewrite appendn_app; rewrite <- mem_or_app;\nrewrite appendn_app in b_in_app. \nrewrite <- mem_or_app in b_in_app; \ndestruct b_in_app as [b_in_app | b_in_app];\n[left | simpl; right; rewrite <- mem_or_app; right]; trivial.\ntrivial.\nassert (a_in_qr : mem eq_A a qr).\ndestruct a_in_appl_qr as [a_in_appl | a_in_qr]; trivial.\nabsurd (mem eq_A a (appendn l)); trivial.\ndestruct (mem_split_set _ _ eq_bool_ok _ _ a_in_qr) as [a' [qr' [qr'' [a_eq_a' [H _]]]]]; subst qr.\ngeneralize (permut_trans (permut_sym Pq) Pq'); clear Pq'; intro Pq'.\nrewrite ass_app in Pq';\nrewrite <- permut_cons_inside in Pq'; rewrite <- ass_app in Pq'.\ngeneralize (remove_equiv_is_sound (consn l) la);\ndestruct (@remove_equiv A eq_bool (consn l) la) as [cns la'];\nintros [lc [Pcns [Pla cns_disj_la']]];\ndestruct (multiset_closure_aux3 l lc cns Pcns) as [ll [ll' [P' [H1 H2]]]].\nexists ((a, la' ++ (appendn ll)) :: ll'); exists (lc ++ (qr' ++ qr'')); split.\nsimpl; apply permut_trans with (la ++ pq).\nassumption.\napply permut_trans with (la ++ (appendn l ++ qr' ++ qr'')).\nrewrite <- permut_app1.\nassumption.\ndo 4 rewrite ass_app; do 2 rewrite <- permut_app2.\napply permut_trans with ((lc ++ la') ++ appendn l).\nrewrite <- permut_app2; assumption.\nrewrite <- ass_app; refine (permut_trans (list_permut_app_app _ _) _);\nrewrite <- permut_app2; rewrite <- ass_app;\nrewrite <- appendn_app; rewrite <- permut_app1.\napply permut_appendn; assumption.\nsplit.\napply permut_trans with (consn l ++ qr' ++ a' :: qr'').\nassumption.\nsimpl; rewrite ass_app; apply permut_sym; \nrewrite <- permut_cons_inside; trivial.\ndo 2 rewrite ass_app;\ndo 2 rewrite <- permut_app2.\napply permut_trans with (consn ll' ++ consn ll).\nrewrite <- permut_app1; apply permut_sym; assumption.\nrewrite <- consn_app; apply permut_consn.\napply LLP.permut_trans with (ll ++ ll').\napply LLP.list_permut_app_app.\napply LLP.permut_sym; assumption.\nsplit.\ndiscriminate.\nsplit.\nintros y ly [yly_eq_aly | yly_in_ll'] b b_in_ly.\ninjection yly_eq_aly; intros; subst y ly; clear yly_eq_aly.\nrewrite <- mem_or_app in b_in_ly.\ndestruct b_in_ly as [b_in_la' | b_in_app].\napply la_lt_a.\nrewrite (mem_permut_mem b Pla).\nrewrite <- mem_or_app; right; trivial.\ndestruct (in_appendn _ _ b_in_app) as [z [lz [zlz_in_ll b_in_lz]]].\napply trans_R with z.\napply (app_lt_cns z lz); trivial.\nrewrite (list_permut.in_permut_in P').\napply in_or_app; left; trivial.\napply la_lt_a; rewrite (mem_permut_mem z Pla); rewrite <- mem_or_app; left.\nrewrite <- (mem_permut_mem z H1).\nrewrite mem_consn; exists lz; trivial.\napply (app_lt_cns y ly); trivial; \nrewrite (list_permut.in_permut_in P'); apply in_or_app; right; trivial.\nintros irrefl_R; simpl; rewrite <- ass_app; rewrite ass_app;\nintros b b_in_a_cns b_in_la_app.\nrewrite <- mem_or_app in b_in_la_app.\ndestruct b_in_la_app as [b_in_la | b_in_app].\ndestruct b_in_a_cns as [b_eq_a | b_in_cns].\nrewrite <- mem_or_app in b_in_la.\ndestruct b_in_la as [b_in_la' | b_in_app].\napply (irrefl_R a); apply la_lt_a; rewrite (mem_permut_mem a Pla); \nrewrite <- mem_or_app; right; \ndummy b a b_eq_a;\nsubst; trivial.\ndestruct (in_appendn _ _ b_in_app) as [z [lz [zlz_in_ll b_in_lz]]].\napply (irrefl_R a); apply trans_R with z.\napply (app_lt_cns z lz); subst; trivial.\nrewrite (list_permut.in_permut_in P').\napply in_or_app; left; trivial.\napply (mem_eq_mem eq_proof) with b; assumption.\napply la_lt_a; rewrite (mem_permut_mem z Pla); \nrewrite <- mem_or_app; left; rewrite <- (mem_permut_mem z H1).\nrewrite mem_consn; exists lz; trivial.\nrewrite <- mem_or_app in b_in_la.\ndestruct b_in_la as [b_in_la' | b_in_app].\napply (cns_disj_la' b); trivial; rewrite <- (mem_permut_mem b H2); trivial.\napply (app_disj_cns irrefl_R b).\nrewrite (mem_permut_mem b (permut_consn P')); rewrite consn_app; \nrewrite <- mem_or_app; right; trivial.\nrewrite (mem_permut_mem b (permut_appendn P')); rewrite appendn_app; \nrewrite <- mem_or_app; left; trivial.\ndestruct b_in_a_cns as [b_eq_a | b_in_cns].\ndummy b a b_eq_a;\nsubst b.\napply a_not_in_appl;\nrewrite (mem_permut_mem a (permut_appendn P'));\nrewrite appendn_app; rewrite <- mem_or_app; right; trivial.\napply (app_disj_cns irrefl_R b).\nrewrite (mem_permut_mem b (permut_consn P')); rewrite consn_app; \nrewrite <- mem_or_app; right; trivial.\nrewrite (mem_permut_mem b (permut_appendn P')); rewrite appendn_app; \nrewrite <- mem_or_app; right; trivial.\nsimpl; trivial.\nQed.\n\nLemma context_trans_clos_multiset_extension_step_cons :\n  forall R, transitive _ R -> (forall a, ~R a a) -> \n  forall a l1 l2, trans_clos (multiset_extension_step R) (a :: l1) (a :: l2) ->\n                         trans_clos (multiset_extension_step R) l1 l2.\nProof.\nintros R trans_R irrefl_R a l1 l2 H.\ndestruct (multiset_closure trans_R H)\n    as [ll [q [P1 [P2 [p_diff_nil [app_lt_cns cns_disj_app]]]]]].\ngeneralize (mem_bool_ok _ _ eq_bool_ok a q).\ncase (mem_bool DS1.eq_bool a q); [intro a_in_q | intro a_not_in_q].\ndestruct (mem_split_set _ _ eq_bool_ok _ _ a_in_q) as [a' [q' [q'' [a_eq_a' [H' _]]]]]; \nsimpl in a_eq_a'; simpl in H'; subst q.\nrewrite ass_app in P1; rewrite <- permut_cons_inside in P1; \nrewrite <- ass_app in P1.\nrewrite ass_app in P2; rewrite <- permut_cons_inside in P2; \nrewrite <- ass_app in P2.\napply (multiset_closure_aux R (q' ++ q'') P1 P2 p_diff_nil).\nintros a'' la ala'_in_ll; apply app_lt_cns; trivial.\ntrivial.\ntrivial.\napply False_rec; apply (cns_disj_app irrefl_R a).\nassert (a_in_cns_ll_q : mem eq_A a (consn ll ++ q)).\nrewrite <- (mem_permut_mem a P2); left; trivial.\napply (equiv_refl _ _ eq_proof).\nrewrite <- mem_or_app in a_in_cns_ll_q.\ndestruct a_in_cns_ll_q as [a_in_cns_ll | a_in_q]; \n[trivial | absurd (mem eq_A a q); trivial; intro].\nassert (a_in_app_ll_q : mem eq_A a (appendn ll ++ q)).\nrewrite <- (mem_permut_mem a P1); left; trivial.\napply (equiv_refl _ _ eq_proof).\nrewrite <- mem_or_app in a_in_app_ll_q.\ndestruct a_in_app_ll_q as [a_in_app_ll | a_in_q]; \n[trivial | absurd (mem eq_A a q); trivial].\nQed.\n\nLemma remove_context_trans_clos_multiset_extension_step_app1 :\n  forall R, transitive _ R -> (forall a, ~R a a) -> \n  forall l1 l2 l, trans_clos (multiset_extension_step R) (l ++ l1) (l ++ l2) ->\n                         trans_clos (multiset_extension_step R) l1 l2.\nProof.\nintros R trans_R irrefl_R l1 l2 l; generalize l1 l2; clear l1 l2; \ninduction l as [ | a l]; trivial.\nintros l1 l2 H; apply IHl;\napply context_trans_clos_multiset_extension_step_cons with a; trivial.\nQed.\n\nLemma nil_is_the_smallest :\n  forall R e l, trans_clos (multiset_extension_step R) nil (e :: l).\nProof.\nintros R e' l; generalize e'; clear e'; induction l as [ | e l].\nintros e; apply t_step; refine (@rmv_case _ _ _ nil nil e _ _ _); auto; contradiction.\nintros e'; apply trans_clos_is_trans with (e' :: l); trivial.\napply t_step; refine (@rmv_case _ _ _ (e' :: l) nil e _ _ _); auto.\ncontradiction.\nrewrite <- (permut_cons_inside (e1 := e') (e2 := e') (e :: l) (e :: nil) l).\nauto.\napply (equiv_refl _ _ eq_proof).\nQed.\n\nSection Mult.\n\nVariable R : relation A.\nVariable R_bool : A -> A -> bool.\nVariable R_bool_ok : \n   forall a1 a2, \n   match R_bool a1 a2 with\n   | true => R a1 a2\n   | false => ~ R a1 a2\n   end.\n\nDefinition mult (l1 l2 : list A) : comp :=\n  match remove_equiv eq_bool l1 l2 with\n    | (nil, nil) => Equivalent\n    | (l1, l2) => \n\tmatch list_forall (fun t2 => list_exists (fun t1 => R_bool t2 t1) l1) l2 with\n        | true => Greater_than\n\t| false =>\n\t  match list_forall (fun t1 => list_exists (fun t2 => R_bool t1 t2) l2) l1 with\n\t  | true => Less_than\n\t  | false => Uncomparable\n          end\n     end\nend.\n\nLemma greater_case :\n   forall l1 l2, (forall a, mem eq_A a l1 -> mem eq_A a l2 -> False) ->\n  list_forall (fun t2 => list_exists (fun t1 => R_bool t2 t1) l1) l2 = true ->\n   exists le, exists ll, permut l1 (consn ll ++ le) /\\\n                              permut  l2 (appendn ll) /\\\n                              (forall a la, In (a,la) ll -> forall b, mem eq_A b la -> R b a).\nProof. \nintros l1 l2; revert l2 l1.\nfix 1.\nintros [ | a2 l2].\nintros [ | a1 l1]; simpl.\nintros _ _; exists (@nil A);  exists (@nil (A * list A)); simpl; intuition.\nintros _ _; exists (a1 :: l1); exists (@nil (A * list A)); simpl; intuition.\nintros l1 E; simpl.\ngeneralize (list_exists_is_sound (fun t1 : A => R_bool a2 t1) l1);\ncase (list_exists (fun t1 : A => R_bool a2 t1) l1).\nintro H; generalize (proj1 H (refl_equal _)); clear H; \nintros [a1 [a1_in_l1 a2_R_a1]].\nassert (a2_R_a1' : R a2 a1).\ngeneralize (R_bool_ok a2 a1); rewrite a2_R_a1; trivial.\nassert (E' : forall x : A, mem eq_A x l1 -> mem eq_A x l2 -> False).\nintros x x_in_l1 x_in_l2; apply (E x); [idtac | right]; assumption.\ngeneralize (greater_case l2 l1 E'); simpl.\ncase (list_forall (fun t2 : A => list_exists (fun t1 : A => R_bool t2 t1) l1) l2).\ncase_eq l1; [intros l1_eq_nil | intros b1 k1 H]; subst l1.\ncontradiction.\nintros H1 H2; generalize (H1 H2); clear H1 H2; intros [le [ll [P1 [P2 app_lt_cns]]]].\nassert (a1_mem_cns_ll_le : mem eq_A a1 (consn ll ++ le)).\nrewrite <- (mem_permut_mem a1 P1); apply in_impl_mem; trivial.\nintro; apply (equiv_refl _ _ eq_proof).\nrewrite <- mem_or_app in a1_mem_cns_ll_le.\ncase a1_mem_cns_ll_le; [intro a1_mem_cns_ll | intro a1_mem_le].\ngeneralize (proj1 (mem_consn _ _) a1_mem_cns_ll); intros [la ala_in_ll].\ngeneralize (In_split _ _ ala_in_ll); intros [ll' [ll'' H]]; subst ll.\nexists le; exists (ll' ++ (a1, a2 :: la) :: ll''); split.\nrewrite consn_app; simpl; rewrite consn_app in P1; simpl in P1; trivial.\nsplit.\nrewrite appendn_app; simpl; rewrite <- permut_cons_inside;\nrewrite appendn_app in P2; simpl in P2; trivial.\napply (equiv_refl _ _ eq_proof).\nintros x lx xlx_in_ll b b_in_lx;\ncase (in_app_or _ _ _ xlx_in_ll); [intros xlx_ll' | intros [xlx_eq_a1la | xlx_in_ll'']].\napply (app_lt_cns x lx); trivial; apply in_or_app; left; trivial.\ninjection xlx_eq_a1la; intros; subst x lx.\ncase b_in_lx; [intros b_eq_a2 | intros b_in_la];\n [dummy b a2 b_eq_a2; subst b | apply (app_lt_cns a1 la)]; trivial.\napply (app_lt_cns x lx); trivial; apply in_or_app; do 2 right; trivial.\n\ngeneralize (mem_split_set _ _ eq_bool_ok _ _ a1_mem_le); intros [a1' [le' [le'' [a1_eq_a1' [H _]]]]]; \nsimpl in a1_eq_a1'; simpl in H; subst le.\nexists (le' ++ le''); exists ((a1, a2 :: nil) :: ll); split.\nsimpl.\napply permut_trans with (consn ll ++ le' ++ a1' :: le'').\nassumption.\nrewrite ass_app; apply permut_sym;\nrewrite <- permut_cons_inside; trivial.\nrewrite ass_app; auto.\nsplit.\nsimpl; rewrite <- permut_cons; trivial.\napply (equiv_refl _ _ eq_proof).\nintros x lx [xlx_eq_a1_e2 | xlx_in_ll] b b_in_lx.\ninjection xlx_eq_a1_e2; intros; subst x lx;\ncase b_in_lx; [intros b_eq_e2 | intros Abs]; \n[dummy b a2 b_eq_e2; subst b; trivial | contradiction].\napply (app_lt_cns x lx); trivial; right; trivial.\nintros _.\ncase (list_forall\n      (fun t1 : A =>\n       Bool.ifb (R_bool t1 a2) true\n         (list_exists (fun t2 : A => R_bool t1 t2) l2)) l1); case l1; intros; discriminate.\n\nintros _; simpl.\ncase (list_forall\n         (fun t1 : A =>\n          Bool.ifb (R_bool t1 a2) true\n            (list_exists (fun t2 : A => R_bool t1 t2) l2)) l1); case l1; intros; discriminate.\nQed.\n\nLemma mult_is_sound :\n forall l1 l2,\n  match mult l1 l2 with\n  | Equivalent => permut l1 l2\n  | Less_than => trans_clos (multiset_extension_step R) l1 l2\n  | Greater_than => trans_clos (multiset_extension_step R) l2 l1\n  | _ => True\n  end.\nProof.\nintros l1 l2; unfold mult; \ngeneralize (remove_equiv_is_sound l1 l2).\nunfold A in *.\ncase (@remove_equiv DS1.A eq_bool l1 l2); intros k1 k2 [l [P1 [P2 E]]].\nrevert P1 P2 E; case k1; [ idtac| intros e1' l1']; (case k2; [ idtac | intros e2' l2']); intros P1 P2 E.\napply permut_trans with (l ++ nil).\nassumption.\napply permut_sym; assumption.\nsimpl; rewrite <- app_nil_end in P1;\napply (multiset_closure_aux2 R (p := l1) (q := l2) \n                      (le := e2' :: l2') (l := nil) l); simpl; auto.\napply permut_trans with (l ++ e2' :: l2').\nassumption.\nrewrite app_comm_cons; apply list_permut_app_app.\nright; discriminate.\nintros; contradiction.\nsimpl; rewrite <- app_nil_end in P2;\napply (multiset_closure_aux2 R (p := l2) (q := l1) \n                      (le := e1' :: l1') (l := nil) l); simpl; auto.\napply permut_trans with (l ++ e1' :: l1').\nassumption.\nrewrite app_comm_cons; apply list_permut_app_app.\nright; discriminate.\nintros; contradiction.\ngeneralize (greater_case (e1' :: l1') (e2' :: l2') E); unfold A in *.\ncase (list_forall (fun t2 : DS1.A => list_exists (fun t1 : DS1.A => R_bool t2 t1) (e1' :: l1')) (e2' :: l2')).\nintro H; generalize (H (refl_equal _)); clear H; intros [le [ll [P1' [P2' app_lt_cns]]]].\napply (multiset_closure_aux2 R (p := l2) (q := l1) (le := le)  (l := ll) l); simpl; auto.\napply permut_trans with (l ++ e2' :: l2').\nassumption.\napply permut_trans with (l ++ appendn ll).\nrewrite <- permut_app1; assumption.\napply list_permut_app_app.\napply permut_trans with (l ++ e1' :: l1').\nassumption.\napply permut_trans with (l ++ consn ll ++ le).\nrewrite <- permut_app1; assumption.\napply permut_trans with (l ++ le ++ consn ll).\nrewrite <- permut_app1; apply list_permut_app_app.\nrewrite (ass_app le); apply list_permut_app_app.\ndestruct ll as [ | [x lx] ll].\ndestruct le as [ | e le].\ngeneralize (permut_length P1'); simpl; intro; \nabsurd (S (length l1') = 0); trivial; discriminate.\nright; discriminate.\nleft; discriminate.\nassert (E' : forall x : DS1.A, mem eq_A x (e2' :: l2') -> mem eq_A x (e1' :: l1') -> False).\nintros x H2 H1; apply (E x H1 H2).\nintros _; generalize (greater_case (e2' :: l2') (e1' :: l1') E'); unfold A in *;\ncase (list_forall (fun t1 : DS1.A => list_exists (fun t2 : DS1.A => R_bool t1 t2) (e2' :: l2')) (e1' :: l1')).\nintro H; generalize (H (refl_equal _)); clear H; intros [le [ll [P2' [P1' app_lt_cns]]]].\napply (multiset_closure_aux2 R (p := l1) (q := l2) (le := le)  (l := ll) l); simpl; auto.\napply permut_trans with (l ++ e1' :: l1').\nassumption.\napply permut_trans with (l ++ appendn ll).\nrewrite <- permut_app1; assumption.\napply list_permut_app_app.\napply permut_trans with (l ++ e2' :: l2').\nassumption.\napply permut_trans with (l ++ consn ll ++ le).\nrewrite <- permut_app1; assumption.\napply permut_trans with (l ++ le ++ consn ll).\nrewrite <- permut_app1; apply list_permut_app_app.\nrewrite (ass_app le); apply list_permut_app_app.\ndestruct ll as [ | [x lx] ll].\ndestruct le as [ | e le].\ngeneralize (permut_length P2'); simpl; intro; \nabsurd (S (length l2') = 0); trivial; discriminate.\nright; discriminate.\nleft; discriminate.\ntrivial.\nDefined.\n\nLemma mult_is_complete_equiv :\n forall l1 l2, permut l1 l2 -> mult l1 l2 = Equivalent.\nProof.\nintros l1 l2 P; \nassert (P1 : permut l1 (l1 ++ nil)).\nrewrite <- app_nil_end; apply permut_refl.\nassert (P2 : permut l2 (l1 ++ nil)).\nrewrite <- app_nil_end; apply permut_sym; assumption.\nassert (E : forall x : A, mem eq_A x nil -> mem eq_A x nil -> False).\nintros; contradiction.\ngeneralize (@remove_equiv_is_complete l1 l2 l1 nil nil P1 P2 E).\nunfold mult; unfold A in *; case (@remove_equiv DS1.A eq_bool l1 l2); intros k1 k2 [Q1 Q2].\nsimpl in Q1; rewrite (permut_nil Q1).\nsimpl in Q2; rewrite (permut_nil Q2).\napply refl_equal.\nDefined.\n\nLemma mult_is_complete_greater_aux :\n transitive _ R -> (forall a, ~ R a a) ->\n forall l l1 l2, (forall a, mem eq_A a l1 -> mem eq_A a l2 -> False) ->\n   trans_clos (multiset_extension_step R) (l ++ l2) (l ++ l1) -> \n\t(list_forall (fun t2 => list_exists (fun t1 => R_bool t2 t1) l1) l2) = true.\nProof.\nintros trans_R irrefl_R l l1 l2 l2_disj_l1 ll2_lt_ll1.\nassert (l2_lt_l1 := remove_context_trans_clos_multiset_extension_step_app1 trans_R irrefl_R l2 l1 l ll2_lt_ll1).\nclear l ll2_lt_ll1.\ngeneralize (multiset_closure trans_R l2_lt_l1).\nintros [ll [lc [P2 [P1 [ll_diff_nil [app_lt_cns cns_disj_app]]]]]].\ngeneralize (cns_disj_app irrefl_R); clear cns_disj_app; intro cns_disj_app.\nassert (lc_eq_nil : lc = nil).\nrevert P2 P1 cns_disj_app.\ncase lc; clear lc; [intros _ _ _; apply refl_equal | intros c lc P2 P1 cns_disj_app].\napply False_rec.\napply (l2_disj_l1 c).\nrewrite (mem_permut_mem c P1); rewrite <- mem_or_app; right; left; apply (equiv_refl _ _ eq_proof).\nrewrite (mem_permut_mem c P2); rewrite <- mem_or_app; right; left; apply (equiv_refl _ _ eq_proof).\nsubst lc; rewrite <- app_nil_end in P1; rewrite <- app_nil_end in P2.\nassert (Compat : forall ta ta' tb tb' : A, eq_A ta tb -> eq_A ta' tb' -> R_bool ta ta' = R_bool tb tb').\nunfold eq_A; intros a a' b b' a_eq_a' b_eq_b'; subst; apply refl_equal.\nrewrite (permut_list_forall_exists R_bool R_bool Compat P2 P1); \nclear Compat cns_disj_app P1 P2 ll_diff_nil; induction ll as [ | [a la] ll]; simpl; trivial.\nrewrite list_forall_app; rewrite Bool.andb_true_iff; split.\ngeneralize la (app_lt_cns a la (or_introl _ (refl_equal _)));\nclear la app_lt_cns; intros la la_lt_a; induction la as [ | b la]; trivial.\nsimpl; generalize (R_bool_ok b a); case (R_bool b a); [intro b_R_a | intro not_b_R_a]; simpl.\napply IHla; intros; apply la_lt_a; right; assumption.\napply False_rec; apply not_b_R_a; apply la_lt_a; left; apply (equiv_refl _ _ eq_proof).\nrewrite (list_forall_impl (fun t1 : A => list_exists (fun t2 : A => R_bool t1 t2) (consn ll))\n                                        (fun t1 : A =>  Bool.ifb (R_bool t1 a) true\n                                                                             (list_exists (fun t2 : A => R_bool t1 t2) (consn ll)))\n                                        (appendn ll)).\napply refl_equal.\nintros b b_in_all H; case (R_bool b a); simpl; [apply refl_equal | assumption].\napply IHll; intros b lb blb_in_ll; apply app_lt_cns; right; assumption.\nQed.\n\nLemma mult_irrefl :\n transitive _ R -> (forall a, ~ R a a) -> forall l, trans_clos (multiset_extension_step R) l l -> False.\nProof.\nintros trans_R irrefl_R l l_lt_l.\nrewrite (app_nil_end l) in l_lt_l.\nassert (nil_lt_nil := remove_context_trans_clos_multiset_extension_step_app1 trans_R irrefl_R nil nil l l_lt_l).\nclear l l_lt_l.\nassert (H : forall l1 l2, trans_clos (multiset_extension_step R) l1 l2 -> l2 = nil -> False).\nintros l1 l2 T; induction T as [k1 k2 H | k1 k2 k3 H1 H2]; intros; subst.\ninversion H as [l1 l2 l la a la_lt_a P1 P2]; subst.\ngeneralize (permut_length P2); simpl; discriminate.\napply IHH2; apply refl_equal.\napply (H _ _ nil_lt_nil); apply refl_equal.\nQed.\n\nLemma mult_is_complete_greater :\n transitive _ R -> (forall a, ~ R a a) ->\n   forall l1 l2, trans_clos (multiset_extension_step R) l2 l1 -> mult l1 l2 = Greater_than.\nProof.\nintros trans_R irrefl_R l1 l2 l2_lt_l1.\ngeneralize (remove_equiv_is_sound l1 l2); unfold mult; unfold A in *; case_eq (remove_equiv eq_bool l1 l2); \nintros k1 k2 H [l [P1 [P2 k1_disj_k2]]].\nassert (lk2_lt_lk1 : trans_clos (multiset_extension_step R) (l ++ k2) (l ++ k1)).\napply list_permut_trans_clos_multiset_extension_step_1 with l2; [assumption | idtac].\napply list_permut_trans_clos_multiset_extension_step_2 with l1; assumption.\nassert (Dummy := @mult_is_complete_greater_aux trans_R irrefl_R l _ _ k1_disj_k2 lk2_lt_lk1).\nunfold A in Dummy; rewrite Dummy; clear Dummy.\nrevert lk2_lt_lk1; case k1; [idtac | intros _ _ _; apply refl_equal].\ncase k2; [idtac | intros _ _ _; apply refl_equal].\nintro T; apply False_rec.\napply (mult_irrefl trans_R irrefl_R T).\nQed.\n\nLemma mult_is_complete_less_than :\n transitive _ R -> (forall a, ~ R a a) ->\n   forall l1 l2, trans_clos (multiset_extension_step R) l1 l2 -> mult l1 l2 = Less_than.\nProof.\nintros trans_R irrefl_R l1 l2 l1_lt_l2.\ngeneralize (multiset_closure trans_R l1_lt_l2).\nintros [ll [lc [P1 [P2 [ll_diff_nil [app_lt_cns disj]]]]]].\nassert (cns_disj_app := disj irrefl_R); clear disj.\nassert (Q1 : permut l1 (lc ++ appendn ll)).\napply permut_trans with (appendn ll ++ lc).\nassumption.\napply permut_swapp; apply permut_refl.\nassert (Q2 : permut l2 (lc ++ consn ll)).\napply permut_trans with (consn ll ++ lc).\nassumption.\napply permut_swapp; apply permut_refl.\nassert (app_disj_cns : forall x : A, mem eq_A x (appendn ll) -> mem eq_A x (consn ll) -> False).\nintros x x_in_app x_in_cns; apply (cns_disj_app x); assumption.\ngeneralize (remove_equiv_is_complete _ _ _ Q1 Q2 app_disj_cns) (mult_is_sound l1 l2).\nunfold mult; unfold A in *; case (@remove_equiv DS1.A eq_bool l1 l2); simpl; intros k1 k2 [Q1' Q2'].\nassert (Dummy := mult_is_complete_greater_aux trans_R irrefl_R lc k2 k1).\nunfold A in Dummy; rewrite Dummy; clear Dummy.\nrevert ll_diff_nil Q1' Q2'; case k1.\ncase k2.\ncase ll.\nintro ll_diff_nil; apply False_rec; apply ll_diff_nil; apply refl_equal.\nintros [a la] ll' _ _ Q2'; apply False_rec.\nassert (L := permut_length Q2'); discriminate.\nintros; apply refl_equal.\nclear k1; intros a1 k1 ll_diff_nil Q1' Q2'.\ncase (list_forall (fun t2 : DS1.A => list_exists (fun t1 : DS1.A => R_bool t2 t1) (a1 :: k1)) k2).\nintro l2_lt_l1; apply False_rec.\napply (@mult_irrefl trans_R irrefl_R l1).\napply trans_clos_is_trans with l2; assumption.\nintros; apply refl_equal.\n\nintros x x_in_k2 x_in_k1; apply (cns_disj_app x).\nrewrite <- (mem_permut_mem x Q2'); assumption.\nrewrite <- (mem_permut_mem x Q1'); assumption.\napply list_permut_trans_clos_multiset_extension_step_1 with l1.\napply permut_trans with (k1 ++ lc).\napply permut_trans with (appendn ll ++ lc).\nassumption.\nrewrite <- permut_app2; apply permut_sym; assumption.\napply permut_swapp; apply permut_refl.\napply list_permut_trans_clos_multiset_extension_step_2 with l2.\napply permut_trans with (k2 ++ lc).\napply permut_trans with (consn ll ++ lc).\nassumption.\nrewrite <- permut_app2; apply permut_sym; assumption.\napply permut_swapp; apply permut_refl.\nassumption.\nDefined.\n\nLemma mult_is_complete : \n transitive _ R -> (forall a, ~ R a a) ->\n forall l1 l2,\n  match mult l1 l2 with\n  | Uncomparable => ~ permut l1 l2 /\\\n                                      ~trans_clos (multiset_extension_step R) l1 l2 /\\ \n                                      ~trans_clos (multiset_extension_step R) l2 l1\n  | _ => True\n  end.\nProof.\nintros trans_R irrefl_R l1 l2.\ngeneralize (mult_is_sound l1 l2) (@mult_is_complete_equiv l1 l2) \n                    (@mult_is_complete_greater trans_R irrefl_R l1 l2) (@mult_is_complete_less_than trans_R irrefl_R l1 l2).\ncase (mult l1 l2); trivial.\nintros _ H1 H2 H3; repeat split; intro H.\ngeneralize (H1 H); discriminate.\ngeneralize (H3 H); discriminate.\ngeneralize (H2 H); discriminate.\nQed.\n\nEnd Mult.\n\nEnd Make.\n\nModule NatMul := Make (ordered_set.Nat).\n\n(* \n*** Local Variables: ***\n*** coq-prog-name: \"coqtop\" ***\n*** coq-prog-args: (\"-emacs-U\" \"-I\" \"../basis/\") ***\n*** End: ***\n *)", "meta": {"author": "sorinica", "repo": "spike-prover", "sha": "f2d6dd0bcebb647e09dd23048753075551da27eb", "save_path": "github-repos/coq/sorinica-spike-prover", "path": "github-repos/coq/sorinica-spike-prover/spike-prover-f2d6dd0bcebb647e09dd23048753075551da27eb/Coccinelle/Coq8.4/dickson.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6652529733085794}}
{"text": "Require Import Shor NumTheory.\nRequire Import SQIR.ExtractionGateSet.\n\n(* Redefining Shor's alg. using the new gate set *)\n\nFixpoint controlled_rotations n : ucom U :=\n  match n with\n  | 0 | 1 => SKIP\n  | 2     => CU1 (R2 * PI / R2 ^ n) 1 0\n  | S n'  => controlled_rotations n' >> CU1 (R2 * PI / R2 ^ n) n' 0\n  end.\n\nFixpoint QFT n : ucom U :=\n  match n with\n  | 0    => SKIP\n  | 1    => H 0\n  | S n' => H 0 >> controlled_rotations n >> map_qubits S (QFT n')\n  end.\n\nFixpoint reverse_qubits' dim n : ucom U :=\n  match n with\n  | 0    => SKIP\n  | 1    => SWAP 0 (dim - 1)\n  | S n' => reverse_qubits' dim n' >> SWAP n' (dim - n' - 1)\n  end.\nDefinition reverse_qubits n := reverse_qubits' n (n/2)%nat.\nDefinition QFT_w_reverse n := QFT n >> reverse_qubits n.\n\nFixpoint bc2ucom (bc : bccom) : ucom U :=\n  match bc with\n  | bcskip => SKIP\n  | bcx a => X a\n  | bcswap a b => SWAP a b\n  | bccont a bc1 => control a (bc2ucom bc1)\n  | bcseq bc1 bc2 => (bc2ucom bc1) >> (bc2ucom bc2)\n  end.\n\nFixpoint controlled_powers' (f : nat -> bccom) k kmax : bccom :=\n  match k with\n  | O    => bcskip\n  | S O  => bygatectrl (kmax - 1) (f O)\n  | S k' => bcseq (controlled_powers' f k' kmax)\n                 (bygatectrl (kmax - k' - 1) (f k'))\n  end.\nDefinition controlled_powers (f : nat -> bccom) k : ucom U := \n  bc2ucom (controlled_powers' f k k).\n\nDefinition QPE k (f : nat -> bccom) : ucom U :=\n  npar k U_H >>\n  controlled_powers (fun x => map_bccom (fun q => k + q)%nat (f x)) k >>\n  invert (QFT_w_reverse k).\n\nDefinition modexp a x N := a ^ x mod N.\nDefinition modmult_circuit a ainv N n i := \n  RCIR.bcelim (ModMult.modmult_rev N (modexp a (2 ^ i) N) (modexp ainv (2 ^ i) N) n).\n\n(* requires 0 < a < N, gcd a N = 1 *)\nDefinition shor_circuit a N := \n  let m := Nat.log2 (2 * N^2)%nat in\n  let n := Nat.log2 (2 * N) in\n  let ainv := modinv a N in\n  let f i := modmult_circuit a ainv N n i in\n  X (m + n - 1) >> QPE m f.\n\n(* shor_circuit uses:\n   - Nat.log2 (2 * N^2) qubits as input to QFT\n   - Nat.log2 (2 * N) qubits as data in modular exponentiation\n   - modmult_rev_anc (Nat.log2 (2 * N)) qubits as ancilla in modular exponentiation \n\n   The values of the first Nat.log2 (2 * N^2) qubits are inspected at the end\n   of the circuit. *)\nDefinition shor_output_nqs (N : nat) : nat := Nat.log2 (2 * N^2).\nDefinition modmult_data_nqs (N : nat) : nat := Nat.log2 (2 * N).\nDefinition modmult_anc_nqs (N : nat) : nat := modmult_rev_anc (Nat.log2 (2 * N)).\nDefinition modmult_nqs (N : nat) : nat := modmult_data_nqs N + modmult_anc_nqs N.\nDefinition shor_nqs (N : nat) : nat := shor_output_nqs N + modmult_nqs N.\n\n\n(** Proofs **)\n\nLemma controlled_rotations_WF : forall n, well_formed (controlled_rotations n).\nProof.\n  destruct n.\n  constructor; auto.\n  destruct n.\n  constructor; auto.\n  induction n. \n  constructor; auto.\n  constructor. apply IHn.\n  constructor; auto. \nQed.\n\nLocal Transparent SQIR.Rz SQIR.CNOT.\nLemma controlled_rotations_WT : forall n, (n > 0)%nat ->\n  uc_well_typed (to_base_ucom n (controlled_rotations n)).\nProof.\n  intros n Hn.\n  destruct n; try lia.\n  clear Hn.\n  destruct n. constructor. lia.\n  induction n. repeat constructor; lia.\n  replace (controlled_rotations (S (S (S n)))) \n    with (controlled_rotations (S (S n)) >> \n          CU1 (2 * PI / 2 ^ (S (S (S n)))) (S (S n)) 0) \n    by reflexivity.\n  remember (S (S n)) as n'.\n  replace (to_base_ucom (S n') (controlled_rotations n' >> \n           CU1 (2 * PI / 2 ^ S n') n' 0))\n    with (to_base_ucom (S n') (controlled_rotations n') ;\n          to_base_ucom (S n') (CU1 (2 * PI / 2 ^ S n') n' 0))%ucom\n    by reflexivity.\n  constructor.\n  eapply change_dim_WT; try apply IHn.\n  lia.\n  apply controlled_rotations_WF.\n  repeat constructor; lia. \nQed.\nLocal Opaque SQIR.Rz SQIR.CNOT.\n\nLemma controlled_rotations_same : forall n,\n  uc_eval n (controlled_rotations n) = \n    UnitarySem.uc_eval (QPE.controlled_rotations n).\nProof.\n  destruct n; try reflexivity.\n  destruct n; try reflexivity.\n  induction n; try reflexivity.\n  replace (controlled_rotations (S (S (S n)))) \n    with (controlled_rotations (S (S n)) >> \n          CU1 (2 * PI / 2 ^ (S (S (S n)))) (S (S n)) 0) \n    by reflexivity.\n  replace (QPE.controlled_rotations (S (S (S n))))\n    with (cast (QPE.controlled_rotations (S (S n))) (S (S (S n))); \n            UnitaryOps.control (S (S n)) (Rz (2 * PI / 2 ^ (S (S (S n)))) 0))%ucom\n    by reflexivity.\n  remember (S (S n)) as n'.\n  replace (S n') with (n' + 1)%nat by lia.\n  erewrite change_dim.\n  unfold uc_eval in *.\n  simpl.\n  rewrite <- (pad_dims_r (to_base_ucom _ _)).\n  rewrite <- (pad_dims_r (QPE.controlled_rotations _)).\n  rewrite IHn.\n  reflexivity.\n  apply QPE.controlled_rotations_WT.\n  lia.\n  apply controlled_rotations_WT.\n  lia.\nQed.\n\nLocal Opaque controlled_rotations.\nLemma QFT_WF : forall n, well_formed (QFT n).\nProof.\n  destruct n.\n  constructor; auto.\n  induction n.\n  constructor; auto.\n  simpl.\n  constructor.\n  constructor.\n  constructor; auto.\n  apply controlled_rotations_WF.\n  apply map_qubits_WF.\n  apply IHn.\nQed.\n\nLemma QFT_same : forall n,\n  uc_eval n (QFT n) = UnitarySem.uc_eval (QPE.QFT n).\nProof.\n  destruct n; try reflexivity.\n  induction n; try reflexivity.\n  replace (QFT (S (S n))) \n    with (H 0 >> controlled_rotations (S (S n)) >> map_qubits S (QFT (S n))) \n    by reflexivity.\n  replace (QPE.QFT (S (S n))) \n    with (SQIR.H 0 ; QPE.controlled_rotations (S (S n)) ; \n          cast (UnitaryOps.map_qubits S (QPE.QFT (S n))) (S (S n)))%ucom \n    by reflexivity. \n  Local Opaque H controlled_rotations QFT QPE.controlled_rotations QPE.QFT.\n  erewrite change_dim.\n  simpl.\n  apply f_equal2; [ | apply f_equal2]; try reflexivity.\n  rewrite map_qubits_same.\n  specialize (pad_dims_l (to_base_ucom (S n) (QFT (S n))) (S O)) as aux.\n  simpl in aux. \n  replace (fun q : nat => S q) with S in aux by reflexivity.\n  rewrite <- aux; clear aux. \n  specialize (pad_dims_l (QPE.QFT (S n)) (S O)) as aux.\n  simpl in aux. \n  replace (fun q : nat => S q) with S in aux by reflexivity.\n  rewrite <- aux; clear aux. \n  rewrite <- IHn. \n  reflexivity.\n  apply QFT_WF.\n  rewrite <- change_dim.\n  apply controlled_rotations_same.\nQed.\n\nLemma reverse_qubits_same : forall n,\n  uc_eval n (reverse_qubits n) = UnitarySem.uc_eval (QPE.reverse_qubits n).\nProof.\n  assert (H : forall n dim, uc_eval dim (reverse_qubits' dim n) = \n                         UnitarySem.uc_eval (QPE.reverse_qubits' dim n)).\n  { intros n dim.\n    destruct n; try reflexivity.\n    induction n; try reflexivity.\n    unfold uc_eval in *.\n    simpl in *.\n    rewrite IHn.\n    reflexivity. }\n  intro n.\n  unfold reverse_qubits.\n  apply H.\nQed.\n\nLemma reverse_qubits_WF : forall n, well_formed (reverse_qubits n).\nProof.\n  assert (H : forall n dim, well_formed (reverse_qubits' dim n)).\n  { intros n dim.\n    destruct n.\n    constructor; auto.\n    induction n.\n    constructor; auto.\n    simpl. constructor. \n    apply IHn.\n    constructor; auto. }\n  intro. apply H.\nQed.\n\nLemma QFT_w_reverse_same : forall n,\n  uc_eval n (QFT_w_reverse n) = UnitarySem.uc_eval (QPE.QFT_w_reverse n).\nProof.\n  intro n.\n  unfold uc_eval; simpl.\n  rewrite <- QFT_same, <- reverse_qubits_same.\n  reflexivity.\nQed.\n\nLemma QFT_w_reverse_WF : forall n, well_formed (QFT_w_reverse n).\nProof. constructor. apply QFT_WF. apply reverse_qubits_WF. Qed.\n\nLemma bc2ucom_WF : forall bc, well_formed (bc2ucom bc).\nProof.\n  induction bc; repeat constructor; auto.\n  simpl. unfold control. apply control'_WF.\n  assumption.\nQed.\n\nLemma bc2ucom_fresh : forall dim q bc,\n  is_fresh q (to_base_ucom dim (bc2ucom bc)) <->\n  @is_fresh _ dim q (RCIR.bc2ucom bc).\nProof.\n  intros dim q bc.\n  induction bc; try reflexivity.\n  simpl.\n  destruct bc; try reflexivity.\n  rewrite <- UnitaryOps.fresh_control.\n  unfold control.\n  rewrite <- fresh_control'.\n  rewrite IHbc.\n  reflexivity.\n  lia.\n  apply bc2ucom_WF.\n  rewrite <- UnitaryOps.fresh_control.\n  unfold control.\n  rewrite <- fresh_control'.\n  rewrite IHbc.\n  reflexivity.\n  lia.\n  apply bc2ucom_WF.\n  split; intro H; inversion H; subst; simpl.\n  constructor.\n  apply IHbc1; auto.\n  apply IHbc2; auto.\n  constructor.\n  apply IHbc1; auto.\n  apply IHbc2; auto.\nQed.\n\nLemma bc2ucom_correct : forall dim (bc : bccom),\n  uc_eval dim (bc2ucom bc) = UnitarySem.uc_eval (RCIR.bc2ucom bc).\nProof.\n  intros dim bc.\n  induction bc; try reflexivity.\n  simpl.\n  rewrite control_correct.\n  destruct bc; try reflexivity.\n  rewrite CNOT_is_control_X.\n  reflexivity.\n  apply UnitaryOps.control_cong.\n  apply IHbc.\n  apply bc2ucom_fresh. \n  apply UnitaryOps.control_cong.\n  apply IHbc.\n  apply bc2ucom_fresh. \n  apply bc2ucom_WF. \n  unfold uc_eval in *. simpl.\n  rewrite IHbc1, IHbc2.\n  reflexivity.  \nQed.\n\nLocal Transparent SQIR.X SQIR.CNOT SQIR.SWAP SQIR.U1.\nLemma bcfresh_is_fresh : forall {dim} q bc,\n    bcfresh q bc -> @is_fresh _ dim q (to_base_ucom dim (bc2ucom bc)).\nProof.\n  intros dim q bc Hfr. \n  induction bc; simpl; inversion Hfr; repeat constructor; auto.\n  unfold control.\n  apply fresh_control'. lia.\n  apply bc2ucom_WF.\n  split; auto.\nQed.\nLocal Opaque SQIR.X SQIR.CNOT SQIR.SWAP SQIR.U1.\n\nLemma uc_eval_bygatectrl_correct :\n  forall c n dim, @uc_eval dim (bc2ucom (bygatectrl n c)) = @uc_eval dim (control n (bc2ucom c)).\nProof.\n  induction c; intros;\n    try (simpl; easy).\n  rewrite bc2ucom_correct.\n  simpl. do 2 rewrite <- bc2ucom_correct. rewrite IHc1, IHc2.\n  repeat (rewrite control_correct by apply bc2ucom_WF; simpl).\n  rewrite control_correct. simpl. easy.\n  constructor; apply bc2ucom_WF.\nQed.\n\nLemma controlled_powers_same : forall n (f : nat -> bccom) k (f' : nat -> base_ucom n),\n  (k > 0)%nat ->\n  (forall i, uc_eval (k + n) (bc2ucom (f i)) = UnitarySem.uc_eval (cast (f' i) (k + n))) ->\n  (forall i j, (j < k)%nat -> is_fresh j (cast (f' i) (k + n))) ->\n  (forall i j, (j < k)%nat -> bcfresh j (f i)) ->\n  uc_eval (k + n) (controlled_powers f k) = \n    UnitarySem.uc_eval (QPE.controlled_powers_var f' k).\nProof.\n  assert (H : forall n (f : nat -> bccom) (f' : nat -> base_ucom n) k kmax,\n    (kmax > 0)%nat ->\n    (forall i, uc_eval (kmax + n) (bc2ucom (f i)) = \n          UnitarySem.uc_eval (cast (f' i) (kmax + n))) ->\n    (forall i j, (j < kmax)%nat -> is_fresh j (cast (f' i) (kmax + n))) ->\n    (forall i j, (j < kmax)%nat -> bcfresh j (f i)) ->\n    uc_eval (kmax + n) (bc2ucom (controlled_powers' f k kmax)) = \n      UnitarySem.uc_eval (@QPE.controlled_powers_var' n f' k kmax)).\n  { intros n f f' k kmax Hkmax Hfeq Hfr' Hfr.\n    destruct k; try reflexivity.\n    induction k. \n    simpl.\n    rewrite uc_eval_bygatectrl_correct.\n    rewrite control_correct.  \n    rewrite cast_control_commute.\n    apply control_cong.\n    apply Hfeq.\n    split; intro H.\n    apply Hfr'. lia.\n    apply bcfresh_is_fresh.\n    apply Hfr. lia.\n    apply bc2ucom_WF.\n    replace (controlled_powers' f (S (S k)) kmax)\n      with (bcseq (controlled_powers' f (S k) kmax)\n                  (bygatectrl (kmax - (S k) - 1) (f (S k)))) \n      by reflexivity.\n    replace (controlled_powers_var' f' (S (S k)) kmax)\n      with (controlled_powers_var' f' (S k) kmax ;\n            cast (UnitaryOps.control (kmax - (S k) - 1) (f' (S k))) (kmax + n))%ucom \n      by reflexivity.\n    remember (S k) as k'.\n    specialize (uc_eval_bygatectrl_correct (f k')) as G.\n    unfold uc_eval in *.\n    simpl in *.\n    rewrite IHk.\n    apply f_equal2; try reflexivity.\n    specialize control_correct as aux.\n    unfold uc_eval in aux.\n    rewrite G.\n    rewrite aux. clear aux.\n    rewrite cast_control_commute.\n    apply control_cong.\n    apply Hfeq.\n    split; intro H.\n    apply Hfr'. lia.\n    apply bcfresh_is_fresh.\n    apply Hfr. lia.\n    apply bc2ucom_WF. }\n  intros. apply H; auto.\nQed.\n\nLemma map_bccom_eq_map_qubits : forall f bc,\n  bcelim bc <> bcskip ->\n  bc2ucom (map_bccom f (bcelim bc)) = map_qubits f (bc2ucom (bcelim bc)).\nProof.\n  intros f bc H.\n  induction bc; simpl in *; try reflexivity.\n  contradict H; reflexivity.\n  destruct (bcelim bc). contradiction.\n  1-2: try rewrite IHbc by easy; reflexivity.\n  simpl bc2ucom.\n  rewrite map_qubits_control.\n  simpl in IHbc.\n  rewrite IHbc by easy.\n  reflexivity.\n  apply control'_WF.\n  apply bc2ucom_WF.\n  simpl bc2ucom.\n  rewrite map_qubits_control.\n  simpl in IHbc.\n  rewrite IHbc by easy.\n  reflexivity.\n  constructor; apply bc2ucom_WF.\n  destruct (bcelim bc1); destruct (bcelim bc2); try easy;\n    simpl in *; try rewrite IHbc2; try rewrite IHbc1; easy.\nQed.\n\nLocal Opaque npar controlled_powers QFT_w_reverse QPE.QFT_w_reverse.\nLemma QPE_same : forall k n (f : nat -> bccom) (f' : nat -> base_ucom n),\n  (k > 0)%nat -> (n > 0)%nat ->\n  (forall i, bcelim (f i) <> bcskip) ->\n  (forall i, uc_eval n (bc2ucom (bcelim (f i))) = UnitarySem.uc_eval (f' i)) ->\n  uc_eval (k + n) (QPE k (fun i => bcelim (f i))) = \n    UnitarySem.uc_eval (QPE.QPE_var k n f').\nProof.\n  intros k n f f' Hk Hn Hf1 Hf2.\n  unfold uc_eval. simpl.\n  repeat apply f_equal2.\n  - specialize change_dim as H.\n    unfold uc_eval in H.\n    rewrite H with (n:=k). \n    symmetry. apply cast_cong_r.\n    rewrite <- uc_well_typed_invert. \n    apply QFT_w_reverse_WT.\n    assumption.\n    symmetry. \n    specialize invert_same as aux.\n    unfold uc_eval in aux.\n    unfold uc_equiv.\n    rewrite aux. \n    rewrite <- 2 invert_correct.\n    apply f_equal.\n    apply QFT_w_reverse_same.\n    apply QFT_w_reverse_WF.\n  - apply controlled_powers_same; auto.\n    intro i.\n    rewrite map_bccom_eq_map_qubits.\n    rewrite change_dim with (n:=n).\n    unfold uc_eval in *.\n    rewrite map_qubits_same.\n    apply cast_cong_l.\n    apply Hf2.\n    apply bc2ucom_WF.\n    apply Hf1.\n    intros i j Hj.\n    apply map_qubits_fresh; auto.\n    intros i j Hj.\n    apply map_qubits_bcfresh; auto.\n  - specialize change_dim as H.\n    unfold uc_eval in H.\n    rewrite H with (n:=k). \n    symmetry. apply cast_cong_r. \n    apply npar_WT.\n    assumption.\n    symmetry. apply npar_H_same.\nQed.\n\n(* Compute the effect of running (shor_circuit a N) on the all-zero input state. *)\nDefinition run_shor_circuit a N := \n  @Mmult _ _ 1 (uc_eval (shor_nqs N) (shor_circuit a N))\n               (basis_vector (2^(shor_nqs N)) 0).\n\n(* Returns the probability that (shor_circuit a N) outputs x. *)\nDefinition prob_shor_outputs a N x := \n  @prob_partial_meas _ (modmult_nqs N) \n    (basis_vector (2^(shor_output_nqs N)) x) (run_shor_circuit a N).\n\nLocal Opaque genM0 modmult_full reverser bcinv.\nLemma bcelim_modmult_rev_neq_bcskip : forall n M C Cinv,\n  bcelim (modmult_rev M C Cinv n) <> bcskip.\nProof. \n  intros.\n  unfold modmult_rev.\n  assert (bcelim (modmult M C Cinv (S (S n))) <> bcskip).\n  { unfold modmult.\n    assert (bcelim (swapperh1 (S (S n))) <> bcskip).\n    { unfold swapperh1.\n      simpl. \n      destruct (bcelim (swapperh1' n (S (S n)))); easy. }\n    Local Opaque swapperh1.\n    simpl.\n    destruct (bcelim (swapperh1 (S (S n)))); \n    destruct (bcelim (genM0 M (S (S n)))); \n    destruct (bcelim (modmult_full C Cinv (S (S n))));\n    destruct (bcelim (bcinv (swapperh1 (S (S n)); genM0 M (S (S n)))%bccom));\n    easy. }\n  Local Opaque modmult.\n  simpl.\n  destruct (bcelim (bcinv (reverser n))); \n  destruct (bcelim (modmult M C Cinv (S (S n))));\n  destruct (bcelim (reverser n));\n  easy.\nQed.\n\nLemma shor_circuit_same : forall a N, \n  (0 < N)%nat ->\n  let m := shor_output_nqs N in\n  let n := modmult_data_nqs N in\n  let f := Shor.f_modmult_circuit a (modinv a N) N n in\n  uc_eval (shor_nqs N) (shor_circuit a N) = \n    UnitarySem.uc_eval (SQIR.useq (SQIR.X (m + n - 1)) (QPE_var m (modmult_nqs N) f)).\nProof.\n  intros a N H m n f.\n  subst m n.\n  unfold uc_eval, shor_circuit, shor_nqs, modmult_nqs.\n  unfold shor_output_nqs, modmult_data_nqs, modmult_anc_nqs in *.\n  Local Opaque Nat.mul Nat.pow QPE QPE.QPE_var.\n  simpl.\n  remember (Nat.log2 (2 * N ^ 2)) as m.\n  remember (Nat.log2 (2 * N)) as n.\n  assert (0 < n)%nat.\n  { subst. apply Nat.log2_pos. lia. }\n  assert (0 < m)%nat.\n  { subst. \n    assert (1 <= N ^ 2)%nat.\n    rewrite <- (Nat.pow_1_l 2) at 1.\n    apply Nat.pow_le_mono_l. lia.\n    apply Nat.log2_pos. lia. }\n  clear Heqn Heqm.\n  apply f_equal2.\n  apply QPE_same; auto.\n  lia.\n  intro i.\n  apply bcelim_modmult_rev_neq_bcskip.\n  intro i.\n  subst f.\n  unfold f_modmult_circuit, modexp.\n  rewrite bc2ucom_correct.\n  reflexivity.\n  reflexivity.\nQed.\n\nLemma uc_well_typed_shor_circuit : forall a N,\n  (a < N)%nat ->\n  uc_well_typed (to_base_ucom (shor_nqs N) (shor_circuit a N)).\nProof.\n  intros.\n  apply uc_eval_nonzero_iff.\n  specialize (shor_circuit_same a N) as Hsame. \n  unfold uc_eval in Hsame.\n  rewrite Hsame by lia.\n  clear Hsame.\n  apply uc_eval_nonzero_iff.\n  unfold shor_output_nqs, modmult_nqs, modmult_data_nqs, modmult_anc_nqs.\n  constructor.\n  apply uc_well_typed_X. \n  unfold modmult_rev_anc.\n  lia.\n  apply QPE_var_WT.\n  assert (1 <= N ^ 2)%nat.\n  rewrite <- (Nat.pow_1_l 2) at 1.\n  apply Nat.pow_le_mono_l. lia.\n  apply Nat.log2_pos. lia. \n  intro i.\n  assert (Nat.log2 (2 * N) > 0)%nat.\n  apply Nat.log2_pos. lia.\n  apply eWT_uc_well_typed_bcelim. lia.\n  apply modmult_rev_eWT. lia.\nQed.\n\nLemma shor_circuit_same' : forall a N x, \n  (0 < N)%nat ->\n  let m := shor_output_nqs N in\n  let n := modmult_data_nqs N in\n  let anc := modmult_anc_nqs N in\n  let f := Shor.f_modmult_circuit a (modinv a N) N n in\n  prob_shor_outputs a N x = \n    prob_partial_meas (basis_vector (2^m) x) (Shor.Shor_final_state m n anc f).\nProof.\n  intros a N x H m n anc f.\n  unfold prob_shor_outputs, run_shor_circuit.\n  rewrite shor_circuit_same by assumption.\n  subst m n anc.\n  unfold shor_nqs, modmult_nqs.\n  unfold shor_output_nqs, modmult_data_nqs, modmult_anc_nqs in *.\n  remember (Nat.log2 (2 * N ^ 2)) as m.\n  remember (Nat.log2 (2 * N)) as n.\n  assert (0 < n)%nat.\n  { subst. apply Nat.log2_pos. lia. }\n  assert (0 < m)%nat.\n  { subst. \n    assert (1 <= N ^ 2)%nat.\n    rewrite <- (Nat.pow_1_l 2) at 1.\n    apply Nat.pow_le_mono_l. lia.\n    apply Nat.log2_pos. lia. }\n  clear Heqm Heqn.\n  apply f_equal.\n  unfold Shor_final_state.\n  simpl.\n  rewrite Mmult_assoc.\n  rewrite 4 basis_f_to_vec_alt.\n  rewrite f_to_vec_X by lia.\n  rewrite f_to_vec_merge.\n  restore_dims.\n  rewrite f_to_vec_merge.\n  apply f_equal2.\n  reflexivity.\n  rewrite Nat.add_assoc.\n  apply f_to_vec_eq; intros i Hi.\n  bdestruct (i <? m + n).\n  bdestruct (i <? m).\n  rewrite update_index_neq by lia.\n  rewrite 2 nat_to_funbool_0.\n  reflexivity.\n  bdestruct (i =? m + n - 1).\n  subst i.\n  rewrite update_index_eq.\n  rewrite nat_to_funbool_0, nat_to_funbool_1. \n  bdestructΩ (m + n - 1 - m =? n - 1).\n  try reflexivity.\n  rewrite update_index_neq by lia.\n  rewrite nat_to_funbool_0, nat_to_funbool_1. \n  bdestructΩ (i - m =? n - 1).\n  try reflexivity.\n  rewrite update_index_neq by lia.\n  rewrite 2 nat_to_funbool_0.\n  reflexivity.\n  apply pow_positive; lia.\n  apply Nat.pow_gt_1; lia.\n  apply pow_positive; lia.\n  apply pow_positive; lia.\nQed.\n\n\n", "meta": {"author": "inQWIRE", "repo": "SQIR", "sha": "7d2938bf63080e37d47059befa27a57f12cc099c", "save_path": "github-repos/coq/inQWIRE-SQIR", "path": "github-repos/coq/inQWIRE-SQIR/SQIR-7d2938bf63080e37d47059befa27a57f12cc099c/examples/shor/ExtrShor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6652529660354003}}
{"text": "(* This file contains the proof of Hall's marriage theorem on the collection \n   of finite sets (SDR version of Hall's theorem). Let S be a collection of sets.\n   Hall's Marriage theorem then states that,\n\n• S has an SDR iff the union of any k members of S contains at least k elements. \n\n  We prove the following MAIN THEOREM in this file,\n  --------------------------------------------------------------------------------- \n  Theorem The_Halls_Thm:  (forall S: Ensemble (Ensemble U) , Included _ S L ->\n       ( forall m n:nat, (cardinal _ S m /\\ cardinal _ (Union_over S) n) -> m<= n) )\n       <->\n       ( exists Rel': Ensemble U -> U-> Prop,\n         (forall (x:Ensemble U) (y:U), Rel' x y -> In _ x y) /\\\n         ( forall (x y:Ensemble U) (z: U), (Rel' x z /\\ Rel' y z)-> x=y) /\\\n         (forall x: Ensemble U, In _ L x -> (exists y: U, Rel' x y))).     \n  --------------------------------------------------------------------------------- \nNote that the existence of such a relation Rel' assures the existence of a one-one map\nfrom S to X. Moreover, Rel' is contained in the set membership relation;\n because Rel' x y -> In _ x y. Hence, the existence of such relation implies the \nexistence of an SDR and vice-versa.  \n\nThere is one technical difficulty that arises while proving Hall's theorem on sets \nusing Hall's theorem on Bipartite graphs. In a Bipartite graph the members of \nsets L and R are of the same type. It is essential to define them in this way since\nconstructing a poset from graph and applying Dilworth's theorem becomes easy.\nHowever, in the Hall's theorem on sets (SDR) the members of the sets S and X are\nof different types. The members of S are of type Ensemble U while the members of \nX are of type U.  \n\nTherefore it becomes difficult to prove The_Halls_Thm directly using Halls_Thm. \nTo resolve this issue we consider a bipartite graph where the left and right \nvertices are of different types. Let, \n\nVariable L: Ensemble U.\n\nVariable R: Ensemble V.\n\nVariable Rel: U-> V-> Prop.\n\nIn this context we then prove the following statement,\n\nTheorem Marriage_Thm:  (forall (S: Ensemble U), Included _ S L -> \n               (forall m n :nat, (cardinal _ S m /\\ cardinal _ (Ngb S) n) -> m <=n ) )\n                <->\n         ( exists Rel': U-> V-> Prop, Included_in_Rel Rel' /\\ Is_L_Perfect_matching Rel'). \n\nwhere Ngb and Is_L_Perfect_matching are defined as,\n\n Definition Ngb (S: Ensemble U):= fun (y: V)=> exists x:U, In _ S x /\\ Rel x y. \n\n Definition Is_L_Perfect_matching (Rel: U-> V-> Prop):=\n    (forall x: U, In _ L x -> (exists y: V, In _ R y /\\ Rel x y)) /\\\n    ( forall (x y: U)(z: V), (Rel x z /\\ Rel y z) -> x=y).\n\nOnce we have the above result it can be directly used to prove The_Halls_Thm on sets. \nProof of The_Halls_Thm using Marriage_Thm also appears in this file.    *)\n\nRequire Import Halls_Thm.\n\n\nSection Container_datatype.\n\n  Variable U V : Type.\n\n  Definition UV:= sum U V. Check UV.\n\n  Variable L: Ensemble U.\n\n  Variable R: Ensemble V.\n\n  Variable Rel: U-> V-> Prop.\n\n  Definition Ngb (S: Ensemble U):= fun (y: V)=> exists x:U, In _ S x /\\ Rel x y.\n\n  Check Ngb.\n\n  Definition Is_L_Perfect_matching (Rel: U-> V-> Prop):=\n    (forall x: U, In _ L x -> (exists y: V, In _ R y /\\ Rel x y)) /\\\n    ( forall (x y: U)(z: V), (Rel x z /\\ Rel y z) -> x=y).\n\n  Print contains.\n\n  Definition Included_in_Rel (Rel': U -> V-> Prop): Prop := forall (x:U) (y:V), Rel' x y -> Rel x y.\n  Check Included_in_Rel.\n\n  Hypothesis L_inhabited: Inhabited _ L.\n  Hypothesis L_Rel_R: forall (x: U)(y: V), Rel x y -> In _ L x /\\ In _ R y.\n  Hypothesis LR_Finite: Finite _ L /\\ Finite _ R. \n\n  Theorem Marriage_B: ( exists Rel': U-> V-> Prop, Included_in_Rel Rel' /\\ Is_L_Perfect_matching Rel')->\n                      (forall (S: Ensemble U),\n                Included _ S L -> (forall m n :nat, (cardinal _ S m /\\ cardinal _ (Ngb S) n) -> m <=n ) ).\n    Proof.  { intros. destruct H as [Rel' H]. destruct H as [Ha Hb].\n         unfold Is_L_Perfect_matching in Hb. destruct Hb as [Hb Hc].\n         (* unfold Is_a_matching in Hb. *) unfold Included_in_Rel in Ha.\n         pose (N'(S: Ensemble U)(y: V) := exists x:U, In _ S x /\\ Rel' x y).\n\n          assert (T3: Included _ (N' S) ( Ngb S)).\n         { unfold Included. intros. destruct H. unfold Ngb. unfold In.\n           exists x0. split. apply H.  apply Ha.  tauto.  }\n\n         assert (T4: Finite _ (N' S)).\n         { eapply Finite_downward_closed with (A:= (Ngb S)).\n           eapply Finite_downward_closed with (A:= R).\n           { tauto. }  {  unfold Included. intros. unfold In in H.  unfold Ngb in H.\n              destruct H as [x0 H2]. cut (In U L x0 /\\ In V R x).\n              tauto. eapply L_Rel_R. tauto. }\n           { unfold Included. intros. destruct H. unfold Ngb. unfold In.\n             exists x0. split. tauto. apply Ha. tauto. }   }\n\n         apply finite_cardinal in T4. destruct T4 as [m' T4].\n\n         assert (T5: m <= m').\n         { eapply Bijection_Relation5 with (U:=U) (V:=V) ( A:= S) (B:= N' S)(R:= Rel').\n           { intros.\n             assert ( In _ L x). { apply H0. auto. }\n             cut (exists y : V, In V R y /\\ Rel' x y). intros. destruct H3 as [y H3].\n             exists y. split. unfold In. unfold N'. exists x. tauto. tauto. auto. }\n\n           { intros. apply Hc with (z:= b). tauto. }\n           tauto. tauto. } \n\n        \n         assert (T6: m'<= n).\n         { eapply incl_card_le. exact T4. Focus 2. exact T3. tauto. }\n\n         SearchPattern (?m<= ?n -> ?n <= ?p -> ?m <= ?p ).\n         eapply le_trans. exact T5. auto. \n\n          }  Qed. \n  \n  Theorem Marriage_A: (forall (S: Ensemble U),\n                 Included _ S L -> (forall m n :nat, (cardinal _ S m /\\ cardinal _ (Ngb S) n) -> m <=n ) ) ->\n                      ( exists Rel': U-> V-> Prop, Included_in_Rel Rel' /\\ Is_L_Perfect_matching Rel').\n  Proof.   { \n\n    intro H0.\n      assert ( T1: exists l:nat, cardinal _ L l ).\n      { apply finite_cardinal. tauto. } destruct T1 as [l T1].\n      assert (T2: l >0). { eapply inh_card_gt_O. exact L_inhabited. auto. }\n\n      assert (T3: Included _ (Ngb L) R).\n      { unfold Included. intros y H1.\n        unfold In in H1. unfold Ngb in H1. destruct H1 as [ x H1].\n        cut (In U L x /\\ In V R y). tauto. apply L_Rel_R. tauto. } \n      assert (T4: Finite _ (Ngb L)).\n      { eapply Finite_downward_closed with (A:=R). tauto. tauto.  } \n      assert (T5: exists lN: nat, cardinal _ (Ngb L) lN).\n      { apply finite_cardinal. tauto. } destruct T5 as [lN T5].\n      assert (T6: l <= lN).\n      { eapply H0 with (S:=L). unfold Included. trivial. tauto. }\n\n      assert (T7: exists r:nat, cardinal _ R r).\n      { apply finite_cardinal. tauto.  } destruct T7 as [r T7].\n\n      assert (T8: lN <= r).\n      { eapply incl_card_le. exact T5. exact T7.   auto. }\n\n      assert ( T9: r>0).\n      {  assert (T10: 0< lN).\n         { SearchPattern (?m < ?n -> ?n <= ?p -> ?m < ?p ).\n           eapply lt_le_trans. exact T2.  auto. }\n         eapply lt_le_trans. exact T10.  auto. }\n      \n    assert (R_inhabited: Inhabited _ R).\n    (* This is true because |R| >= |Ngb L| >= |L| > 0 *)\n      {  destruct r. inversion T9.\n         apply cardinal_elim with (U:= V)(p:= (S r) )(X:= R).\n         auto. } \n\n      \n\n     \n\n         pose (UV:= sum U V).\n         Print Biper_Graph.\n         Print Finite_Graph. Print Graph.\n\n         pose (L'(x': UV ):= match x' with\n                             |  inl x => In _ L x\n                             |  inr _ => False end ).\n         pose (R' (y' : UV):= match y' with\n                              | inr y => In _ R y\n                              | inl _ => False end ).\n\n         pose ( V':= Union _ L' R').\n\n         pose (Rel' (x': UV )(y': UV) := match (x', y') with\n                                         | (inl x , inr y) => Rel x y\n                                         | (inr _, _ ) => False\n                                         | (_, inl _)=> False end ).\n\n         assert (F0: forall (x:U) (y:V), Rel' (inl x) (inr y) -> Rel x y).\n         { intros x y. intro. unfold Rel' in H. auto. }\n\n         assert (F1: forall x': UV, In _ L' x' -> exists x: U, x'= (inl x) /\\ In _ L x ).\n         { intros. destruct x'.\n           exists u. split. reflexivity. unfold L' in H. tauto.\n           unfold L' in H. unfold In in H. tauto. }\n\n         assert (F2: forall y': UV, In _ R' y' -> exists y: V, y'= (inr y) /\\ In _ R y ).\n         { intros. destruct y'.\n           unfold R' in H. unfold In in H. tauto.\n           exists v.  split. reflexivity.  tauto. }   \n             \n\n         assert (LR_Inhabited': Inhabited _ L' /\\ Inhabited _ R').\n         { Print Inhabited. split.\n           destruct L_inhabited as [x L_Inh]. eapply Inhabited_intro with (x:= (inl x)).\n           unfold L'. unfold In. auto.\n           destruct R_inhabited as [y R_Inh]. Print Inhabited.\n           eapply Inhabited_intro with (x:= (inr y)).\n           unfold R'. unfold In. auto. }  \n\n         assert (NEmpty_cond': Inhabited _ V').\n         { destruct LR_Inhabited' as [ Inh_L Inh_R].\n           destruct Inh_L as [x Inh_L]. eapply Inhabited_intro with (x:= x).\n           unfold V'. apply Union_introl. auto.  }\n\n\n         pose (f1(x: U):= (inl V x) ).\n         pose (f2(y: V):= (inr U y) ).\n\n         assert(f1_one_one: injective _ _ f1).\n         { unfold injective. intros.  unfold f1 in H. injection H. tauto.  }\n         assert (f2_one_one: injective _ _ f2).\n         { unfold injective. intros.  unfold f2 in H. injection H. tauto. }\n\n         assert (Image_LL': L'= Im _ _ L f1).\n         {  cut (Same_set  _ L' (Im _ _ L f1 ) ).\n            eapply Extensionality_Ensembles. unfold Same_set.\n            split.\n            { unfold Included. intros x'. intro.\n              assert (H1: exists x: U, x'= (inl x) /\\ In _ L x). auto.\n              destruct H1 as [x H1]. destruct H1 as [H1 H2].\n              rewrite H1. apply Im_def. auto. }\n\n            { unfold Included. intros x. intro.\n              destruct H. unfold f1 in H1. rewrite H1. unfold In.\n              unfold L'. auto. }   }\n\n         assert (Image_RR': R' = Im _ _ R f2).\n         { cut (Same_set  _ R' (Im _ _ R f2 ) ).\n            eapply Extensionality_Ensembles. unfold Same_set.\n            split.\n             { unfold Included. intros y'. intro.\n              assert (H1: exists y: V, y'= (inr y) /\\ In _ R y). auto.\n              destruct H1 as [y H1]. destruct H1 as [H1 H2].\n              rewrite H1. apply Im_def. auto. }\n\n             { unfold Included. intros x. intro.\n              destruct H. unfold f2 in H1. rewrite H1. unfold In.\n              unfold R'. auto. }   }    \n\n\n         assert (Finite_L': Finite _ L').\n         { rewrite Image_LL'. eapply finite_image. tauto.  }\n\n         assert (Finite_R': Finite _ R').\n         { rewrite Image_RR'. eapply finite_image. tauto.  }\n\n         assert (Finite_V': Finite _ V').\n         { unfold V'. apply Union_preserves_Finite; tauto.  } \n\n         assert (LR_Disj': Disjoint _ L' R').\n         { Print Disjoint. apply Disjoint_intro.\n           intros. intro. destruct H. unfold In in H. unfold In in H1.\n           unfold L' in H. unfold R' in H1. destruct x; contradiction.  } \n\n         assert (LR_Union': V' = Union _ L' R' ).\n         { unfold V'. reflexivity.  }\n\n         assert (LR_Rel': forall x y : UV, Rel' x y -> In _ L' x /\\ In _ R' y).\n         {  intros. destruct x; destruct y.\n            { unfold In;try (inversion H).  }\n            { unfold In;try (inversion H).  simpl. unfold Rel' in H. auto. }\n            { unfold In;try (inversion H).  }\n            { unfold In;try (inversion H).  } }  \n\n         pose (G':= {| Vertices_of := V';\n                          Edge_Rel_of:= Rel' ;\n                          NonEmpty_cond:= NEmpty_cond' |} ).\n\n         pose (FG':=  {| Graph_of_FG := G';\n                         F_Graph_cond := Finite_V' |} ).\n\n  pose (BG':= {| Graph_of_BG := FG';\n                 L_of := L';\n                 R_of := R';\n                 LR_Inhabited := LR_Inhabited';\n                 LR_Disj := LR_Disj';\n                 LR_Union := LR_Union';\n                 LR_Rel := LR_Rel' |}). \n\n \n\n         assert (Fact1: (forall (S: Ensemble UV), Included _ S L' ->\n                 (forall m n :nat, (cardinal _ S m /\\ cardinal _ (N BG' S) n) -> m <=n ) )). \n         { intros S'. intro. intros m' n'. intro.\n           pose (S (x:U):= In _ S' (inl x)).\n           assert (S_Image: S' = Im _ _ S f1).\n           { cut (Same_set _ S' (Im _ _ S f1)).  auto with sets.\n             unfold Same_set.\n             split.\n             { unfold Included. intros x' H2.\n               assert (exists x : U, x' = inl x /\\ In U L x ).\n               apply F1. auto. destruct H3 as [x H3]. destruct H3 as [ H3 H4].\n               rewrite H3 in H2. eapply Im_intro.\n               unfold In. unfold S. exact H2. unfold f1. auto. }\n             { unfold Included. intros. destruct H2. unfold f1 in H3.\n               rewrite H3.  unfold In in H2. unfold S in H2. auto. }  } \n\n           assert (S_Inc: Included _ S L).\n           { unfold Included. intro x. intro.\n             unfold In in H2.  unfold S in H2.\n             assert (H3: In _ L' ( inl x)).\n             unfold Included in H. auto. unfold In in H3.\n             unfold L' in H3. auto.  }\n           \n           assert (S_Finite: Finite _ S). (* since S is included in L *)\n           { eapply Finite_downward_closed with (A:= L); tauto. } \n           apply finite_cardinal in S_Finite. destruct S_Finite as [m S_Card].\n\n           assert (NgbS_in_R: Included _ (Ngb S) R).\n           {  unfold Included. intros. unfold In in H2.  unfold Ngb in H2.\n              destruct H2 as [x0 H2]. cut (In U L x0 /\\ In V R x).\n              tauto. eapply L_Rel_R. tauto.  } \n           \n           assert (NgbS_Finite: Finite _ (Ngb S)). (* since Ngb S is included in R *)\n           { eapply Finite_downward_closed with (A:= R); tauto.  }\n           apply finite_cardinal in NgbS_Finite. destruct NgbS_Finite as [n NgbCard]. \n\n           assert (NgbS_Image: (N BG' S') = Im _ _ (Ngb S) f2).\n           { cut ( Same_set _ (N BG' S') (Im _ _ (Ngb S) f2)).\n             auto with sets. unfold Same_set.\n             split.\n             { unfold Included. intros y. intros. destruct H2.  simpl in H2.\n               assert (H3: In _ L' x).\n               { unfold Included in H. apply H. tauto. }\n               assert (H4: exists x0 : U, x = inl x0 /\\ In U L x0).\n               { apply F1. tauto. } destruct H4 as [x0 H4]. destruct H4 as [H4 H5].\n               \n               assert (H6: In _ R' y).\n               { cut (In UV L' x /\\ In UV R' y). tauto.\n                 apply LR_Rel'.  tauto. } \n               assert (H7: exists y0 : V, y = inr y0 /\\ In _ R y0).\n               { apply F2. tauto. } destruct H7 as [y0 H7]. destruct H7 as [H7 H8].\n               rewrite H7. eapply Im_def. unfold In. unfold Ngb.\n               exists x0. unfold In; unfold S. rewrite <- H4. split. tauto.\n               destruct H2 as [Ha2 Hb2]. rewrite H4 in Hb2. rewrite H7 in Hb2.\n               unfold Rel' in Hb2. tauto.   }\n\n             { unfold Included. intros y. intros. destruct H2 as [y0 H2 y H3].\n               destruct H2 as [x0 H2].\n               assert ( H4: In _ S' (inl x0)). tauto.\n               unfold f2 in H3. unfold In.  unfold N.\n               exists (inl x0). rewrite H3. tauto.  }  } \n\n           assert (Fmm': m' = m).\n           { eapply injective_preserves_cardinal with (f:= f1).  auto.\n             exact S_Card. rewrite <- S_Image. tauto.  } \n\n           assert (Fnn': n' = n).\n           {  eapply injective_preserves_cardinal with (f:= f2).  auto.\n              exact NgbCard. rewrite <- NgbS_Image. tauto.  }\n\n           rewrite Fmm'. rewrite Fnn'.\n           eapply H0. exact S_Inc. tauto.  }\n\n         assert (Fact2: exists Rel': Relation UV, Included_in_Edge BG' Rel' /\\ Is_L_Perfect BG' Rel' ).\n         { eapply Hall_A. apply Fact1.  }\n\n         destruct Fact2 as [Rel0' Fact2].\n\n         \n\n         (* We need to extract a relation Rel1': U -> V-> Prop,  reflecting Rel0'  *)\n          pose (Rel0(x:U)(y:V):= Rel0' (inl x) (inr y) ). \n\n          (* Then we produce this as certificate for Goal and prove the obligations *)\n          exists Rel0.\n          split.\n          { unfold Included_in_Rel. intros x y H1.\n            apply F0. apply Fact2. tauto. } \n          { unfold Is_L_Perfect_matching. \n            split.\n            { intros x H1.\n              assert ( H2: In _ L' (inl x)). { tauto. }\n              assert (H3: exists y': UV, In _ R' y' /\\ Rel0' (inl x) y').\n              { destruct Fact2 as [Fact2 Fact3 ].  unfold Is_L_Perfect in Fact3.\n                destruct Fact3 as [Fact3 Fact4 ]. unfold Is_a_matching in Fact3.\n                assert (H3: exists y : UV, Rel0' (inl x) y).\n                { auto. } destruct H3 as [y H3].\n                exists y.  split. assert (H4: Rel' (inl x) y). apply Fact2. auto.\n                cut ( In _ L' (inl x) /\\ In _ R' y). tauto.  apply LR_Rel'. tauto.\n                tauto. } \n              destruct H3 as [y' H3].\n              assert (H4: exists y : V, y' = inr y /\\ In V R y).\n              { eapply F2. tauto.  }\n              destruct H4 as [y H4]. destruct H4 as [H4 H5].\n              exists y. split. tauto. rewrite H4 in H3. apply H3. }\n            { intros.\n              assert (H1: Rel0' (inl x) (inr z) /\\ Rel0' (inl y) (inr z) ).\n              tauto. destruct Fact2 as [Fact2 Fact3 ].  unfold Is_L_Perfect in Fact3.\n              destruct Fact3 as [Fact3 Fact4 ]. unfold Is_a_matching in Fact3.\n              Print inl.\n              assert( H2: (inl V x) = (inl V y) ).\n              { eapply Fact3. left. exact H1. }\n              injection H2. tauto. }  }\n\n    }    Qed.\n\n  Theorem Marriage_Thm:  (forall (S: Ensemble U),\n               Included _ S L -> (forall m n :nat, (cardinal _ S m /\\ cardinal _ (Ngb S) n) -> m <=n ) ) <->\n                         ( exists Rel': U-> V-> Prop, Included_in_Rel Rel' /\\ Is_L_Perfect_matching Rel').\n    Proof. unfold iff.  split; ( eapply Marriage_A ||  eapply Marriage_B) . Qed. \n\n\nEnd Container_datatype.\n\n\n\n\n\n\n\n\nSection The_Halls_Thm.\n\n  \n  Variable U:Type.\n\n  Variable L: Ensemble (Ensemble U).\n\n   Check L.\n\n   Hypothesis L_Finite: Finite _ L.\n\n   Hypothesis All_S_Finite: forall S: Ensemble U, In _ L S -> Finite _ S.\n\n   Definition R:= Union_over L.\n\n   Definition Rel (S: Ensemble U) (s: U):= In _ S s /\\ In _ L S.\n\n   Lemma LR_Finite:  Finite _ L /\\ Finite _ R.\n   Proof. {  split. apply L_Finite. unfold R.\n           apply Finite_Union_of_Finite_Sets.\n           split. auto. apply All_S_Finite. }  Qed.  \n\n   \n   Lemma L_Rel_R:  forall (S: Ensemble U)(s: U), Rel S s -> In _ L S /\\ In _ R s.\n   Proof. { intros. unfold Rel in H.\n          split.\n          { tauto. }\n          { unfold R. unfold In. unfold Union_over. exists S; tauto. } }  Qed. \n\n  Theorem The_HallsB:  ( exists Rel': Ensemble U -> U-> Prop,\n                        (forall (x:Ensemble U) (y:U), Rel' x y -> In _ x y) /\\\n                        ( forall (x y:Ensemble U) (z: U), (Rel' x z /\\ Rel' y z)-> x=y) /\\\n                        (forall x: Ensemble U, In _ L x -> (exists y: U, Rel' x y))) ->\n                          (forall S: Ensemble (Ensemble U) , Included _ S L ->\n                        ( forall m n:nat, (cardinal _ S m /\\ cardinal _ (Union_over S) n) -> m<= n) ).\n  Proof. { intros. destruct H as [Rel' H]. destruct H as [Ha Hb].\n         unfold Is_L_Perfect_matching in Hb. destruct Hb as [Hb Hc].\n         pose (N'(S: Ensemble (Ensemble U)) (y: U) := exists x: Ensemble U, In _ S x /\\ Rel' x y).\n\n          assert (T3: Included _ (N' S) ( Union_over S)).\n         { unfold Included. intros. destruct H. unfold Union_over. unfold In.\n           exists x0. split. apply H.  apply Ha.  tauto.  }\n\n         assert (T2: Finite _ R).\n         { unfold R. apply Finite_Union_of_Finite_Sets. tauto. }\n\n         assert (T4: Finite _ (N' S)).\n         { eapply Finite_downward_closed with (A:= (Union_over S)).\n           eapply Finite_downward_closed with (A:= R).\n           { tauto. }  {  unfold Included. intros. unfold In in H.  unfold Union_over in H.\n              destruct H as [x0 H2]. cut (In _ L x0 /\\ In _ R x).\n              tauto. eapply L_Rel_R. unfold Rel. split. tauto. apply H0. tauto. }\n           { unfold Included. intros. destruct H. unfold Union_over. unfold In.\n             exists x0. split. tauto. apply Ha. tauto. }   } \n\n         apply finite_cardinal in T4. destruct T4 as [m' T4].\n\n         assert (T5: m <= m').\n         { eapply Bijection_Relation5 with (U:=Ensemble U) (V:=U) ( A:= S) (B:= N' S)(R:= Rel').\n           { intros.\n             assert ( In _ L x). { apply H0. auto. }\n             cut (exists y : U, In _ R y /\\ Rel' x y). intros. destruct H3 as [y H3].\n             exists y. split. unfold In. unfold N'. exists x. tauto. tauto.\n             assert (H3: exists y : U, Rel' x y).\n             { auto. } destruct H3 as [y H3]. exists y. split.\n             cut ( In _ L x /\\ In _ R y). tauto. eapply L_Rel_R. unfold Rel.\n             split. auto. tauto. auto.  } \n\n           { intros. apply Hb with (z:= b). tauto. }\n           tauto. tauto. } \n\n        \n         assert (T6: m'<= n).\n         { eapply incl_card_le. exact T4. Focus 2. exact T3. tauto. }\n\n         SearchPattern (?m<= ?n -> ?n <= ?p -> ?m <= ?p ).\n         eapply le_trans. exact T5. auto. \n\n          }  Qed. \n  \n \n  \n  Theorem The_HallsA: (forall S: Ensemble (Ensemble U) , Included _ S L ->\n                    ( forall m n:nat, (cardinal _ S m /\\ cardinal _ (Union_over S) n) -> m<= n) ) ->\n                    ( exists Rel': Ensemble U -> U-> Prop,\n                        (forall (x:Ensemble U) (y:U), Rel' x y -> In _ x y) /\\\n                        ( forall (x y:Ensemble U) (z: U), (Rel' x z /\\ Rel' y z)-> x=y) /\\\n                        (forall x: Ensemble U, In _ L x -> (exists y: U, Rel' x y))).\n  Proof.  { \n\n   \n    \n      pose (R:= Union_over L).  Check R.\n\n      elim (EM ( Inhabited _ L )).\n\n      (* CASE1: When the collection L is non-empty *)\n      (* Here H:  L is inhabited *)\n      { \n\n        intros H H1.\n        assert ( L_inhabited: Inhabited _ L). auto.\n\n        Check Marriage_A.\n\n        assert ( H2:  exists Rel' : Ensemble U -> U -> Prop,\n                   Included_in_Rel _ _  Rel Rel' /\\ Is_L_Perfect_matching _ _  L R Rel').\n\n        { eapply Marriage_A.\n          auto.\n          apply  L_Rel_R.\n          apply LR_Finite.\n          intros.  apply H1 with (S:= S).\n          auto. split. tauto.\n          assert ( H3: Union_over S = (Ngb _ _ Rel S)).\n          cut ( Same_set _ ( Union_over S) ( Ngb _ _ Rel S)).\n          auto with sets. unfold Same_set.\n          split.\n          { unfold Included. intros. unfold In.  unfold Ngb.\n            unfold In in H3. unfold Union_over in H3.\n            destruct H3. exists x0. unfold Rel.\n            split. tauto. split. tauto. apply H0. tauto. }\n          { unfold Included.  intros. unfold In. unfold Union_over.\n            unfold In in H3. unfold Ngb in H3. unfold Rel in H3.\n            destruct H3 as [S1 H3].  exists S1; tauto.  }\n\n          rewrite H3.  tauto.  }\n\n        destruct H2 as [Rel' H2].\n        destruct H2 as [Ha2 Hb2].\n        unfold Included_in_Rel in Ha2.\n        unfold Is_L_Perfect_matching in Hb2.\n        destruct Hb2 as [Hb2 Hc2]. \n\n        exists Rel'.\n        split.\n        { intros x y H3.\n          assert (H4: Rel x y).\n          unfold Included_in_Rel in Ha2.\n          apply Ha2.  auto. unfold Rel in H4. tauto.  }\n\n        split.\n        { apply Hc2. }\n        { intros.\n          assert ( H3: exists y : U, In U R y /\\ Rel' x y).\n          auto.  destruct H3 as [y H3].\n          exists y.  tauto.  }   } \n        \n\n      (* CASE2: When the collection L is empty *)\n      { intros.  exists (fun (x: Ensemble U) (y: U)=> False).\n        split. tauto. split. tauto.\n        intros x H1. destruct H. Print Inhabited.  eapply Inhabited_intro. exact H1. }\n\n      \n    }  Qed.\n\n\n  Theorem The_Halls_Thm:  (forall S: Ensemble (Ensemble U) , Included _ S L ->\n                    ( forall m n:nat, (cardinal _ S m /\\ cardinal _ (Union_over S) n) -> m<= n) ) <->\n                    ( exists Rel': Ensemble U -> U-> Prop,\n                        (forall (x:Ensemble U) (y:U), Rel' x y -> In _ x y) /\\\n                        ( forall (x y:Ensemble U) (z: U), (Rel' x z /\\ Rel' y z)-> x=y) /\\\n                        (forall x: Ensemble U, In _ L x -> (exists y: U, Rel' x y))).\n\n    Proof. unfold iff. split; (eapply The_HallsA || eapply The_HallsB). Qed. \n\n\n  \nEnd The_Halls_Thm.\n\n\nCheck The_HallsA. ", "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/Marriage_Thm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6652405460442573}}
{"text": "(** This module defines the language algebra without the constant 1, and its finite complete axiomatization.*)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import tools language.\n\nDelimit Scope one_scope with one.\nOpen Scope one_scope.\n\nSection s.\n  (** * Main definitions *)\n  Variable X : Set.\n  Variable dec_X : decidable_set X.\n\n  (** [𝐄' X] is the type of expressions with variables ranging over the\n  type [X]. They are built out of the constant [0], the\n  concatenation (also called sequential product) [⋅], the intersection\n  [∩], the union [+], the mirror image, denoted by the postfix\n  operator [̅], and the non-zero iteration, denoted by [⁺]. *)\n  Inductive 𝐄' : Set :=\n  | 𝐄'_zero : 𝐄'\n  | 𝐄'_var : X -> 𝐄'\n  | 𝐄'_seq : 𝐄' -> 𝐄' -> 𝐄'\n  | 𝐄'_inter : 𝐄' -> 𝐄' -> 𝐄'\n  | 𝐄'_plus : 𝐄' -> 𝐄' -> 𝐄'\n  | 𝐄'_conv : 𝐄' -> 𝐄'\n  | 𝐄'_iter : 𝐄' -> 𝐄'.\n\n  Notation \"x ⋅ y\" := (𝐄'_seq x y) (at level 40) : one_scope.\n  Notation \"x + y\" := (𝐄'_plus x y) (left associativity, at level 50) : one_scope.\n  Notation \"x ∩ y\" := (𝐄'_inter x y) (at level 45) : one_scope.\n  Notation \"x ¯\" := (𝐄'_conv x) (at level 25) : one_scope.\n  Notation \"x ⁺\" := (𝐄'_iter x) (at level 25) : one_scope.\n  Notation \" 0 \" := 𝐄'_zero : one_scope.\n\n  (** The following are the axioms of the algebra of languages over\n  this signature.*)\n  Inductive ax : 𝐄' -> 𝐄' -> Prop :=\n  (** [⟨𝐄',⋅,1⟩] is a monoid. *)\n  | ax_seq_assoc e f g : ax (e⋅(f ⋅ g)) ((e⋅f)⋅g)\n  (** [⟨𝐄',+,0⟩] is a commutative idempotent monoid. *)\n  | ax_plus_com e f : ax (e+f) (f+e)\n  | ax_plus_idem e : ax (e+e) e\n  | ax_plus_ass e f g : ax (e+(f+g)) ((e+f)+g)\n  | ax_plus_0 e : ax (e+0) e\n  (** [⟨𝐄',⋅,+,1,0⟩] is an idempotent semiring. *)\n  | ax_seq_0 e : ax (e⋅0) 0\n  | ax_0_seq e : ax (0⋅e) 0\n  | ax_plus_seq e f g: ax ((e + f)⋅g) (e⋅g + f⋅g)\n  | ax_seq_plus e f g: ax (e⋅(f + g)) (e⋅f + e⋅g)\n  (** [⟨𝐄',∩⟩] is a commutative and idempotent semigroup. *)\n  | ax_inter_assoc e f g : ax (e∩(f ∩ g)) ((e∩f)∩g)\n  | ax_inter_comm e f : ax (e∩f) (f∩e)\n  | ax_inter_idem e : ax (e ∩ e) e\n  (** [⟨𝐄',+,∩⟩] forms a distributive lattice, and [0] is absorbing for\n  [∩]. *)\n  | ax_plus_inter e f g: ax ((e + f)∩g) (e∩g + f∩g)\n  | ax_inter_plus e f : ax ((e∩f)+e) e\n  | ax_inter_0 e : ax (e∩0) 0\n  (** [¯] is an involution that flips concatenations and commutes with\n  every other operation. *)\n  | ax_conv_conv e : ax (e ¯¯) e\n  | ax_conv_0 : ax (0¯) 0\n  | ax_conv_plus e f: ax ((e + f)¯) (e ¯ + f ¯)\n  | ax_conv_seq e f: ax ((e ⋅ f)¯) (f ¯ ⋅ e ¯)\n  | ax_conv_inter e f: ax ((e∩f)¯) (e ¯ ∩ f ¯)\n  | ax_conv_iter e : ax (e⁺¯) (e ¯⁺)\n  (** The axioms for [⁺] are as follow: *)\n  | ax_iter_left e : ax (e⁺) (e + e⋅e⁺)\n  | ax_iter_right e : ax (e⁺) (e + e⁺ ⋅e).\n\n  (** Additionally, we need these two implications: *)\n  Inductive ax_impl : 𝐄' -> 𝐄' -> 𝐄' -> 𝐄' -> Prop:=\n  | ax_right_ind e f : ax_impl (e⋅f + f) f (e⁺⋅f + f) f\n  | ax_left_ind e f : ax_impl (f ⋅ e + f) f (f ⋅e⁺ + f) f.\n\n  (** We use these axioms to generate an axiomatic equivalence\n  relation and an axiomatic order relations. *)\n  Inductive 𝐄'_eq : Equiv 𝐄' :=\n  | eq_refl e : e ≡ e\n  | eq_trans f e g : e ≡ f -> f ≡ g -> e ≡ g\n  | eq_sym e f : e ≡ f -> f ≡ e\n  | eq_plus e f g h : e ≡ g -> f ≡ h -> (e + f) ≡ (g + h)\n  | eq_seq e f g h : e ≡ g -> f ≡ h -> (e ⋅ f) ≡ (g ⋅ h)\n  | eq_inter e f g h : e ≡ g -> f ≡ h -> (e ∩ f) ≡ (g ∩ h)\n  | eq_conv e f : e ≡ f -> (e ¯) ≡ (f ¯)\n  | eq_iter e f : e ≡ f -> (e⁺) ≡ (f⁺)\n  | eq_ax e f : ax e f -> e ≡ f\n  | eq_ax_impl e f g h : ax_impl e f g h -> e ≡ f -> g ≡ h.\n  Global Instance 𝐄'_Equiv : Equiv 𝐄' := 𝐄'_eq.\n\n  Global Instance 𝐄'_Smaller : Smaller 𝐄' := (fun e f => e + f ≡ f).\n\n  Hint Constructors 𝐄'_eq ax ax_impl.\n\n  Global Instance ax_equiv : subrelation ax equiv. \n  Proof. intros e f E;apply eq_ax,E. Qed.\n\n  (** * Some elementary properties of this algebra *)\n\n  (** It is immediate to check that the equivalence we defined is\n  indeed an equivalence relation, that the order relation is a\n  preorder, and that every operator is monotone for both relations. *)\n  Global Instance equiv_Equivalence : Equivalence equiv.\n  Proof. split;intro;eauto. Qed.\n\n  Global Instance inter_equiv :\n    Proper (equiv ==> equiv ==> equiv) 𝐄'_inter.\n  Proof. now intros e f hef g h hgh;apply eq_inter. Qed.\n\n  Global Instance plus_equiv :\n    Proper (equiv ==> equiv ==> equiv) 𝐄'_plus.\n  Proof. now intros e f hef g h hgh;apply eq_plus. Qed.\n\n  Global Instance seq_equiv :\n    Proper (equiv ==> equiv ==> equiv) 𝐄'_seq.\n  Proof. now intros e f hef g h hgh;apply eq_seq. Qed.\n  \n  Global Instance conv_equiv :\n    Proper (equiv ==> equiv) 𝐄'_conv.\n  Proof. now intros e f hef;apply eq_conv. Qed.\n  \n  Global Instance iter_equiv :\n    Proper (equiv ==> equiv) 𝐄'_iter.\n  Proof. now intros e f hef;apply eq_iter. Qed.\n\n  Global Instance smaller_PreOrder : PreOrder smaller.\n  Proof.\n    split;intro;unfold smaller,𝐄'_Smaller;intros.\n    - auto.\n    - transitivity (y + z);[|auto].\n      transitivity (x + y + z);[|auto].\n      transitivity (x + (y + z));[|auto].\n      auto.\n  Qed.\n\n  Global Instance smaller_PartialOrder : PartialOrder equiv smaller.\n  Proof.\n    intros e f;split;unfold smaller,𝐄'_Smaller;unfold Basics.flip.\n    - intros E;split.\n      + rewrite E;auto.\n      + rewrite E;auto.\n    - intros (E1&E2).\n      rewrite <- E1.\n      rewrite <- E2 at 1;auto.\n  Qed.\n\n  Global Instance smaller_equiv : subrelation equiv smaller.\n  Proof. intros e f E;apply smaller_PartialOrder in E as (E&_);apply E. Qed.\nEnd s.\n(* begin hide *)\nArguments 𝐄'_zero {X}.\nHint Constructors 𝐄'_eq ax ax_impl.\n(* end hide *)\nInfix \" ⋅ \" := 𝐄'_seq (at level 40) : one_scope.\nInfix \" + \" := 𝐄'_plus (left associativity, at level 50) : one_scope.\nInfix \" ∩ \" := 𝐄'_inter (at level 45) : one_scope.\nNotation \"x ¯\" := (𝐄'_conv x) (at level 25) : one_scope.\nNotation \"x ⁺\" := (𝐄'_iter x) (at level 25) : one_scope.\nNotation \" 0 \" := 𝐄'_zero : one_scope.\n\n\n  \nSection language.\n  (** * Language interpretation *)\n  Context { X : Set }.\n\n  (** We interpret expressions as languages in the obvious way: *)\n  Global Instance to_lang_𝐄' {Σ}: semantics 𝐄' language X Σ :=\n    fix to_lang_𝐄' σ e:=\n      match e with\n      | 0 => 0%lang\n      | 𝐄'_var a => (σ a)\n      | e + f => ((to_lang_𝐄' σ e) + (to_lang_𝐄' σ f))%lang\n      | e ⋅ f => ((to_lang_𝐄' σ e) ⋅ (to_lang_𝐄' σ f))%lang\n      | e ∩ f => ((to_lang_𝐄' σ e) ∩ (to_lang_𝐄' σ f))%lang\n      | e ¯ => (to_lang_𝐄' σ e)¯%lang\n      | e⁺ => (to_lang_𝐄' σ e)⁺%lang\n      end.\n\n  (* begin hide *)\n  Global Instance semSmaller_𝐄' : SemSmaller (𝐄' X) :=\n    (@semantic_containment _ _ _ _ _).\n  Global Instance semEquiv_𝐄' : SemEquiv (𝐄' X) :=\n    (@semantic_equality _ _ _ _ _).\n  Hint Unfold semSmaller_𝐄' semEquiv_𝐄' : semantics. \n\n  Section rsimpl.\n    Context { Σ : Set }{σ : 𝕬[X→Σ] }.\n    Lemma 𝐄'_union e f : (⟦ e+f ⟧σ) = ((⟦e⟧σ) + ⟦f⟧σ)%lang.\n    Proof. unfold interprete;simpl;auto. Qed.\n    Lemma 𝐄'_prod e f :  (⟦ e⋅f ⟧σ) = ((⟦e⟧σ) ⋅ ⟦f⟧σ)%lang.\n    Proof. unfold interprete;simpl;auto. Qed.\n    Lemma 𝐄'_intersection e f : (⟦ e∩f ⟧σ) = ((⟦e⟧σ) ∩ ⟦f⟧σ)%lang.\n    Proof. unfold interprete;simpl;auto. Qed.\n    Lemma 𝐄'_mirror e :  (⟦ e ¯⟧σ) = (⟦e⟧σ)¯%lang.\n    Proof. unfold interprete;simpl;auto. Qed.\n    Lemma 𝐄'_iter_l e :  (⟦ e⁺⟧σ) = (⟦e⟧σ)⁺%lang.\n    Proof. unfold interprete;simpl;auto. Qed.\n    Lemma 𝐄'_variable a : (⟦𝐄'_var a⟧ σ) = σ a.\n    Proof. unfold interprete;simpl;auto. Qed.\n    Lemma 𝐄'_empty : (⟦0⟧σ) = 0%lang.\n    Proof. unfold interprete;simpl;auto. Qed.\n  End rsimpl.\n  Hint Rewrite @𝐄'_empty @𝐄'_variable @𝐄'_intersection\n       @𝐄'_prod @𝐄'_union @𝐄'_mirror @𝐄'_iter_l\n    : simpl_typeclasses.\n\n  \n  Global Instance sem_incl_𝐄'_plus :\n    Proper (ssmaller ==> ssmaller ==> ssmaller) (@𝐄'_plus X).\n  Proof.\n    intros e f E g h F ? ?;simpl;rsimpl;revert E F;\n      repeat autounfold with semantics;firstorder.\n  Qed.\n  Global Instance sem_incl_𝐄'_fois :\n    Proper (ssmaller ==> ssmaller ==> ssmaller) (@𝐄'_seq X).\n  Proof.\n    intros e f E g h F Σ σ;simpl;revert E F;rsimpl;\n      repeat autounfold with semantics;firstorder.\n  Qed.\n  Global Instance sem_incl_𝐄'_inter :\n    Proper (ssmaller ==> ssmaller ==> ssmaller) (@𝐄'_inter X).\n  Proof.\n    intros e f E g h F Σ σ;simpl;revert E F;rsimpl;\n      repeat autounfold with semantics;firstorder.\n  Qed.\n  Global Instance sem_incl_𝐄'_conv :\n    Proper (ssmaller ==> ssmaller) (@𝐄'_conv X).\n  Proof.\n    intros e f E Σ σ;simpl;revert E;rsimpl;\n      repeat autounfold with semantics;firstorder.\n  Qed.\n  Global Instance sem_incl_𝐄'_iter :\n    Proper (ssmaller ==> ssmaller) (@𝐄'_iter X).\n  Proof.\n    intros e f E Σ σ;simpl.\n    autorewrite with simpl_typeclasses.\n    apply iter_lang_incl,E.\n  Qed.\n  Global Instance sem_eq_𝐄'_plus :\n    Proper (sequiv ==> sequiv ==> sequiv) (@𝐄'_plus X).\n  Proof. eapply (@sem_eq_op _ _ ssmaller);once (typeclasses eauto). Qed.\n  Global Instance sem_eq_𝐄'_seq :\n    Proper (sequiv ==> sequiv ==> sequiv) (@𝐄'_seq X).\n  Proof. eapply (@sem_eq_op _ _ ssmaller);once (typeclasses eauto). Qed.\n  Global Instance sem_eq_𝐄'_inter :\n    Proper (sequiv ==> sequiv ==> sequiv) (@𝐄'_inter X).\n  Proof. eapply (@sem_eq_op _ _ ssmaller);once (typeclasses eauto). Qed.\n  Global Instance sem_eq_𝐄'_conv :\n    Proper (sequiv ==> sequiv) (@𝐄'_conv X).\n  Proof.\n    intros e f E Σ σ;simpl;autounfold;rsimpl.\n    intro w;rewrite (E Σ σ (rev w));tauto.\n  Qed.\n  Global Instance sem_eq_𝐄'_iter :\n    Proper (sequiv ==> sequiv) (@𝐄'_iter X).\n  Proof.\n    intros e f E Σ σ;simpl.\n    autorewrite with simpl_typeclasses.\n    apply iter_lang_eq,E.\n  Qed.\n  Global Instance 𝐄'_sem_equiv :\n    Equivalence (fun e f : 𝐄' X => e ≃ f).\n  Proof. once (typeclasses eauto). Qed.\n  Global Instance 𝐄'_sem_PreOrder :\n    PreOrder (fun e f : 𝐄' X => e ≲ f).\n  Proof. once (typeclasses eauto). Qed.\n  Global Instance 𝐄'_sem_PartialOrder :\n    PartialOrder (fun e f : 𝐄' X => e ≃ f)\n                 (fun e f : 𝐄' X => e ≲ f).\n  Proof.\n    eapply semantic_containment_PartialOrder;once (typeclasses eauto).\n  Qed.\n\n  (* end hide *)\n  \n  Lemma lang_iter_prod_last {Σ}(l: language Σ) n : (l ^{S n} ≃ l ^{n} ⋅ l)%lang.\n  Proof.\n    induction n.\n    - simpl;intros w;split;intros (u&v&I1&I2&->).\n      + rewrite I2,app_nil_r;exists [],u;split;reflexivity||auto.\n      + rewrite I1;exists v,[];rewrite app_nil_r;repeat split;auto.\n    - intros x;split.\n      + intros (u&?&I1&I2&->).\n        apply IHn in I2 as (v&w&I2&I3&->).\n        exists (u++v),w;rewrite app_ass;repeat split;auto.\n        exists u,v;tauto.\n      + intros (?&w&(u&v&I1&I2&->)&I3&->).\n        cut (l^{S n}%lang (v++w));[|apply IHn;exists v,w;tauto].\n        intro I';exists u,(v++w);rewrite app_ass;repeat split;auto.\n  Qed.\n\n  (** This interpretation is sound in the sense that axiomatically\n  equivalent expressions are semantically equivalent. Differently put,\n  the axioms we imposed hold in every algebra of languages. *)\n  Theorem soundness_𝐄' : forall e f : 𝐄' X, e ≡ f ->  e ≃ f.\n  Proof.\n    assert (dumb : forall A (w:list A), rev w = nil <-> w = nil)\n      by (intros A w;split;[intro h;rewrite <-(rev_involutive w),h\n                           |intros ->];reflexivity).\n    intros e f E Σ σ;induction E;rsimpl;try firstorder.\n    - apply iter_lang_eq,IHE.\n    -  destruct H;rsimpl;repeat autounfold with semantics;try (now firstorder).\n       + intro w;firstorder.\n         * rewrite H1,H3;clear x0 w H1 H3;rewrite<- app_ass.\n           eexists;eexists;split;[eexists;eexists;split;[|split]\n                                 |split];eauto.\n         * rewrite H1,H3;clear x w H1 H3;rewrite app_ass.\n           eexists;eexists;split;\n             [|split;[eexists;eexists;split;[|split]|]];eauto.\n       + intro w;rewrite rev_involutive;tauto.\n       + intro w;firstorder.\n         * rewrite <- (rev_involutive w),H1,rev_app_distr;eauto.\n           exists (rev x0);exists (rev x).\n           setoid_rewrite rev_involutive;auto.\n         * rewrite H1,rev_app_distr;eauto.\n       + intros w;split.\n         * intros (n&Iu);exists n.\n           generalize dependent (S n);clear n;intros n;revert w.\n           induction n;intro w;[simpl;apply dumb|].\n           intro I;apply lang_iter_prod_last in I as (u&v&Iu&Iv&E).\n           replace w with (rev v++rev u) in * by (now rewrite <- rev_app_distr,<-E,rev_involutive).\n           clear w E.\n           exists (rev v),(rev u);rewrite rev_involutive.\n           repeat split;auto.\n           apply IHn;rewrite rev_involutive;assumption.\n         * intros (n&Iu);exists n.\n           generalize dependent (S n);clear n;intros n;revert w.\n           induction n;intro w;[simpl;apply dumb|].\n           intro I;apply lang_iter_prod_last in I as (u&v&Iu&Iv&->).\n           exists (rev v),(rev u);rewrite rev_app_distr.\n           repeat split;auto.\n       + intros w;split.\n         * intros ([]&Iu).\n           -- left;destruct Iu as (u'&?&Iu&->&->).\n              rewrite app_nil_r;assumption.\n           -- right;destruct Iu as (u&v&Iu&Iv&->).\n              exists u,v;repeat split;auto.\n              exists n;assumption.\n         * intros [Iu|(u&v&Iu&(m&Iv)&->)].\n           -- exists 0%nat,w,[];rewrite app_nil_r;repeat split;assumption.\n           -- exists (S m),u,v;tauto.\n       + intros w;split.\n         * intros ([]&Iu).\n           -- left;destruct Iu as (u'&?&Iu&->&->).\n              rewrite app_nil_r;assumption.\n           -- apply lang_iter_prod_last in Iu.\n              right;destruct Iu as (u&v&Iu&Iv&->).\n              exists u,v;repeat split;auto.\n              exists n;assumption.\n         * intros [Iu|(u&v&(m&Iu)&Iv&->)].\n           -- exists 0%nat,w,[];rewrite app_nil_r;repeat split;assumption.\n           -- exists (S m);apply lang_iter_prod_last.\n              exists u,v;tauto.\n    - destruct H.\n      + assert (ih : ⟦e⋅f⟧σ≲⟦f⟧σ) by (intros u Iu;apply (IHE u);left;apply Iu);clear IHE.\n        cut (⟦e⁺⋅f⟧σ≲⟦f⟧σ);[intros E u;split;[intros [I|I];[apply E|]|intro;right];assumption|].\n        intros w (u&v&(n&Iu)&Iv&->).\n        revert u v Iu Iv;induction n;intros u v Iu Iv.\n        * destruct Iu as (u'&?&Iu&->&->).\n          rewrite app_nil_r;apply ih;exists u',v;tauto.\n        * apply lang_iter_prod_last in Iu as (u1&u2&Iu1&Iu2&->);rewrite app_ass.\n          apply IHn;[assumption|].\n          apply ih;exists u2,v;tauto.\n      + assert (ih : ⟦f⋅e⟧σ≲⟦f⟧σ) by (intros u Iu;apply (IHE u);left;apply Iu);clear IHE.\n        cut (⟦f⋅e⁺⟧σ≲⟦f⟧σ);[intros E u;split;[intros [I|I];[apply E|]|intro;right];assumption|].\n        intros w (u&v&Iu&(n&Iv)&->).\n        revert u v Iu Iv;induction n;intros u v Iu Iv.\n        * destruct Iv as (v'&?&Iv&->&->).\n          rewrite app_nil_r;apply ih;exists u,v';tauto.\n        * destruct Iv as (v1&v2&Iv1&Iv2&->);rewrite <- app_ass.\n          apply IHn;[|assumption].\n          apply ih;exists u,v1;tauto.\n  Qed.\n\n  (** This extends to ordering as well. *)\n  Lemma soundness_inf_𝐄' (e f : 𝐄' X) : e ≤ f -> e ≲ f.\n  Proof.\n    intro E;apply smaller_equiv,soundness_𝐄' in E.\n    intros Σ σ w I;apply E;rsimpl;left;left;auto.\n  Qed.\n\nEnd language.\nHint Rewrite @𝐄'_empty @𝐄'_variable @𝐄'_intersection\n     @𝐄'_prod @𝐄'_union @𝐄'_mirror @𝐄'_iter_l\n  : simpl_typeclasses.\n", "meta": {"author": "monstrencage", "repo": "LangAlg", "sha": "a33b6e6457cec94eae57d0137b576c9547a4f63e", "save_path": "github-repos/coq/monstrencage-LangAlg", "path": "github-repos/coq/monstrencage-LangAlg/LangAlg-a33b6e6457cec94eae57d0137b576c9547a4f63e/one_free_expr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6652405460442572}}
{"text": "(************************************************************************)\n(* Copyright (c) 2010, Martijn Vermaat <martijn@vermaat.name>           *)\n(*                                                                      *)\n(* Licensed under the MIT license, see the LICENSE file or              *)\n(* http://en.wikipedia.org/wiki/Mit_license                             *)\n(************************************************************************)\n\n\n(** This library defines substition of terms for variables in terms. *)\n\n\nRequire Export List.\nRequire Export FiniteTerm.\nRequire Export Term.\nRequire Import TermEquality.\nRequire Import Equality.\n\n\nSet Implicit Arguments.\n\n\nSection Substitution.\n\nVariable F : signature.\nVariable X : variables.\n\nNotation term := (term F X).\nNotation fterm := (finite_term F X).\n\n(** A substitution is a function from variables to terms. *)\nDefinition substitution := X -> term.\n\n(** Equality of substitutions on a list of variables. *)\nFixpoint substitution_eq (vars : list X) (sigma sigma' : substitution) :=\n  match vars with\n  | nil     => True\n  | x :: xs => (substitution_eq xs sigma sigma') /\\ (sigma x = sigma' x)\n  end.\n\n(** Equality of substitutions on a list of variables is invariant under\n   list inclusion.\n\n   We have not yet proven this lemma. This taints the lemma [step_eq__target]\n   in [Rewriting]. *)\nLemma substitution_eq_incl :\n  forall sigma theta l l',\n    incl l' l ->\n    substitution_eq l sigma theta ->\n    substitution_eq l' sigma theta.\nProof.\nintros sigma theta l l' H1 H2.\nrevert l' H1.\ninduction l as [| x l IH]; intros l' H1; simpl.\ndestruct l' as [| y l'].\nexact I.\nelim (H1 y).\nleft; reflexivity.\n\ninduction l' as [| y l' IH']; simpl.\nexact I.\nsplit.\napply IH'.\nintros z H.\napply H1.\nright.\nassumption.\ndestruct (H1 y).\nleft; reflexivity.\nrewrite H in H2.\napply H2.\nsimpl in H2.\n(** This should not be too hard. (Problem is whether [x] is in [l']. *)\nAdmitted.\n\nLemma substitution_eq_app_left :\n  forall sigma theta l l',\n    substitution_eq (l ++ l') sigma theta ->\n    substitution_eq l sigma theta.\nProof.\nintros sigma theta l l' H.\ninduction l as [| x l IH]; simpl.\nexact I.\nsplit.\napply IH.\napply H.\napply H.\nQed.\n\nLemma substitution_eq_app_right :\n  forall sigma theta l l',\n    substitution_eq (l ++ l') sigma theta ->\n    substitution_eq l' sigma theta.\nProof.\nintros sigma theta l l' H.\ninduction l as [| x l IH]; simpl.\nassumption.\napply IH.\napply H.\nQed.\n\nImplicit Arguments substitution_eq_app_left [l l'].\nImplicit Arguments substitution_eq_app_right [l l'].\n\n(** We show [substitution_eq] is an equivalence. *)\n\nLemma substitution_eq_refl :\n  forall vars sigma, substitution_eq vars sigma sigma.\nProof.\ninduction vars; [simpl | split]; trivial.\nQed.\n\nLemma substitution_eq_symm :\n  forall vars sigma theta,\n    substitution_eq vars sigma theta ->\n    substitution_eq vars theta sigma.\nProof.\nintros vars sigma theta H.\ninduction vars as [| x vars IH]; simpl.\nexact I.\nsplit.\napply IH.\napply H.\nsymmetry.\napply H.\nQed.\n\nLemma substitution_eq_trans :\n  forall vars sigma theta upsilon,\n    substitution_eq vars sigma theta ->\n    substitution_eq vars theta upsilon ->\n    substitution_eq vars sigma upsilon.\nProof.\nintros vars sigma theta upsilon H1 H2.\ninduction vars as [| x vars IH]; simpl.\nexact I.\nsplit.\napply IH.\napply H1.\napply H2.\napply eq_trans with (theta x).\napply H1.\napply H2.\nQed.\n\n(** The identity substitution. *)\nDefinition empty_substitution (x : X) : term := Var x.\n\n(** We define two substitution functions. The first, [substitute], defines\n   substitution on finite terms. The second, [substitute'], defines\n   substitution on infinite terms.\n\n   In principle, [substitute'] works fine and is a generalisation of\n   [substitute]. However, it yields a (potentially) infinite term (of type\n   [term] instead of [finite_term]) and this makes it somewhat painful to\n   work with (corecursive definitions have to be manually unfolded in Coq).\n\n   Since we almost always apply substitutions on finite terms, we define\n   this seperately and provide the more general [substitute'] for\n   completeness. *)\n\n(** Apply a substitution to a finite term. *)\nFixpoint substitute (sigma : substitution) (t : fterm) {struct t} : term :=\n  match t with\n  | FVar x      => sigma x\n  | FFun f args => Fun f (vmap (substitute sigma) args)\n  end.\n\n(** Applying the empty substitution to a finite term gives the trivial\n   infinite term image. The only reason we cannot prove coq-equality here\n   is equality on vectors. *)\nLemma empty_substitution_is_id :\n  forall (t : fterm), substitute empty_substitution t [~] t.\nProof.\ninduction t.\napply term_bis_refl.\nconstructor.\nassumption.\nQed.\n\n(** Applying equal substitutions yields equal terms.\n\n   We have not yet proven this lemma. This taints the lemmas\n   [step_eq_source] and [step_eq_target] in [Rewriting]. *)\nLemma substitution_eq_substitute :\n  forall sigma theta t,\n    substitution_eq (vars t) sigma theta ->\n    substitute sigma t [~] substitute theta t.\nProof.\nintros sigma theta t H.\ninduction t as [x | f args IH]; simpl.\nrewrite (proj2 H).\napply term_bis_refl.\nconstructor.\nintro i.\napply IH; clear IH.\nsimpl in H.\nunfold vmap in H.\ninduction (arity f) as [| n IH]; clear f.\ninversion i.\ndependent destruction i.\nsimpl in H.\nunfold vhead in H.\nunfold vtail in H.\napply (substitution_eq_app_left sigma theta H).\nspecialize IH with (vtail args) i.\napply IH.\nunfold vtail.\n(** Here we are stuck, need some more lemmas on [vector], for example:\n\n[[\nLemma a :\n  forall x n v,\n    In x (vfold nil app (fun i0 : Fin n => vars (v (Next i0)))) ->\n    In x (vfold nil app (fun i : Fin (S n) => vars (v i))).\n]]\n*)\nAdmitted.\n\n(** Apply a substitution to an infinite term. Note that this definition is\n   not in guarded form if we were to use the inductive vector type from the\n   standard library. It is in guarded form here, because we use [vector]\n   from the [Vector] library, where [vmap] is just an abstraction (which\n   ensures the corecursive call to [substitute'] to be guarded). *)\nCoFixpoint substitute' (sigma : substitution) (t : term) : term :=\n  match t with\n  | Var x      => sigma x\n  | Fun f args => Fun f (vmap (substitute' sigma) args)\n  end.\n\n(** Applying the empty substitution to a term gives the same term. *)\nLemma empty_substitution_is_id' :\n  forall (t : term), substitute' empty_substitution t [~] t.\nProof.\ncofix IH.\ndestruct t.\nrewrite (peek_eq (substitute' empty_substitution (Var v))).\napply term_bis_refl.\nrewrite (peek_eq (substitute' empty_substitution (Fun f v))).\nsimpl.\nconstructor.\nintro i.\nunfold vmap.\napply IH.\nQed.\n\n(** We prove that both substitution functions do the same thing (on finite\n   terms). We can almost prove this for coq-equality, but we cannot equate\n   [vmap finite_term_as_term v] and [v]. *)\nLemma substitutions_related :\n  forall (s : substitution) (t : fterm), substitute s t [~] substitute' s t.\nProof.\ninduction t.\nsimpl.\nrewrite (peek_eq (substitute' s (Var v))).\nsimpl.\ndestruct (s v); apply term_bis_refl.\nsimpl.\nrewrite (peek_eq (substitute' s (Fun f (vmap (@finite_term_as_term F X) v)))).\nsimpl.\nconstructor.\nintro i.\nunfold vmap.\napply H.\nQed.\n\nEnd Substitution.\n", "meta": {"author": "martijnvermaat", "repo": "infinitary-rewriting-coq", "sha": "0af6403a39c630de96ab2616ee7f3e01cd67a2f5", "save_path": "github-repos/coq/martijnvermaat-infinitary-rewriting-coq", "path": "github-repos/coq/martijnvermaat-infinitary-rewriting-coq/infinitary-rewriting-coq-0af6403a39c630de96ab2616ee7f3e01cd67a2f5/Substitution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.6651486801512825}}
{"text": "Definition Is_true (b:bool) :=\n  match b with\n    | true => True\n    | false => False\n  end.\n\nLemma bool_dec : forall b1 b2 : bool, {b1 = b2} + {b1 <> b2}.\nProof.\nintros a b.\ndestruct a;destruct b.\nleft. reflexivity.\nright. discriminate.\nright. discriminate.\nleft. reflexivity.\nShow Proof.\nDefined.\n\nLemma diff_true_false : true <> false.\nProof.\ndiscriminate.\nShow Proof.\nPrint False_ind.\nQed.\n\nLemma diff_false_true : false <> true.\nProof.\n  discriminate.\nQed.\n\nLemma eq_true_false_abs : forall b:bool, b = true -> b = false -> False.\nProof.\nintro b.\nintro btrue.\nsubst b.\nintro h.\ndiscriminate.\nShow Proof.\nQed.\n\nLemma not_true_is_false : forall b:bool, b <> true -> b = false.\nProof.\ndestruct b.\nintro h.\napply False_ind.\napply h. reflexivity.\nintro b. reflexivity.\nShow Proof.\nQed.\n\nLemma not_false_is_true : forall b:bool, b <> false -> b = true.\nProof.\nintro b.\nintro h.\nunfold not in h.\ndestruct b.\nreflexivity.\napply False_ind.\napply h. reflexivity.\nQed.\n\nLemma not_true_iff_false : forall b, b <> true <-> b = false.\nProof.\nunfold iff. unfold not.\ndestruct b.\nsplit. intro h. apply False_ind. apply h. apply eq_refl.\nintro h. intro eq. discriminate.\nsplit. intro h. reflexivity.\nintro h. intro hft. discriminate.\nShow Proof.\nQed.\n\nLemma not_false_iff_true : forall b, b <> false <-> b = true.\nProof.\nunfold iff. unfold not.\ndestruct b;split; intros;try(discriminate);try(reflexivity).\ncontradiction.\nQed.\n\nDefinition leb (b1 b2:bool) :=\n  match b1 with\n    | true => b2 = true\n    | false => True\n  end.\n\nLemma leb_implb : forall b1 b2, leb b1 b2 <-> implb b1 b2 = true.\nProof.\nunfold implb. unfold leb. unfold iff.\nintros a b ; destruct a;destruct b;split;try(reflexivity);try(intro;discriminate).\nQed.\n\nDefinition eqb (b1 b2:bool) : bool :=\n  match b1, b2 with\n    | true, true => true\n    | true, false => false\n    | false, true => false\n    | false, false => true\n  end.\n\nLemma eqb_subst :\n  forall (P:bool -> Prop) (b1 b2:bool), eqb b1 b2 = true -> P b1 -> P b2.\nProof.\nunfold eqb. intros P a b.\ndestruct a;destruct b;intros heq pb;try(assumption);try(discriminate).\nQed.\n\nLemma eqb_reflx : forall b:bool, eqb b b = true.\nProof.\nintro b;destruct b;reflexivity.\nQed.\n\nLemma eqb_prop : forall a b:bool, eqb a b = true -> a = b.\nProof.\nintros a b. unfold eqb. destruct a;destruct b;try(reflexivity);intros;try(assumption);try(symmetry;assumption).\nQed.\n\nLemma eqb_true_iff : forall a b:bool, eqb a b = true <-> a = b.\nProof.\nunfold iff. unfold eqb.\nintros a b.\ndestruct a;destruct b;split;intros;try(reflexivity);try(assumption);try(symmetry;assumption).\nQed.\n\nLemma eqb_false_iff : forall a b:bool, eqb a b = false <-> a <> b.\nProof.\nunfold eqb. unfold not.\nunfold iff.\nintros a b;destruct a;destruct b;split;intros;try(discriminate);try(reflexivity);try(contradiction).\nQed.\n\nDefinition ifb (b1 b2 b3:bool) : bool :=\n  match b1 with\n    | true => b2\n    | false => b3\n  end.\n\n\n(****************************)\n(** * De Morgan laws          *)\n(****************************)\n\nLemma negb_orb : forall b1 b2:bool, negb (orb b1 b2) = (andb (negb b1) (negb b2)).\nProof.\nintros a b.\nunfold negb. unfold orb. unfold andb.\ndestruct a;destruct b;reflexivity.\nQed.\n\nLemma negb_andb : forall b1 b2:bool, negb (andb b1 b2) = orb (negb b1) (negb b2).\nProof.\nunfold negb. unfold andb. unfold orb.\nintros a b;destruct a;destruct b;reflexivity.\nShow Proof.\nQed.\n\nLemma negb_involutive : forall b:bool, negb (negb b) = b.\nProof.\nintro b;destruct b;reflexivity.\nQed.\n\nLemma negb_involutive_reverse : forall b:bool, b = negb (negb b).\nProof.\nintro b;destruct b;reflexivity.\nQed.\n\nLemma negb_sym : forall b b':bool, b' = negb b -> b = negb b'.\nProof.\nintros a b;unfold negb;destruct a;destruct b;intros;try(assumption);reflexivity.\nQed.\n\nLemma no_fixpoint_negb : forall b:bool, negb b <> b.\nProof.\nintro b;unfold negb;unfold not;intros;destruct b;discriminate.\nQed.\n\nLemma eqb_negb1 : forall b:bool, eqb (negb b) b = false.\nProof.\nintro b;unfold eqb;unfold negb;destruct b;reflexivity.\nQed.\n\nLemma eqb_negb2 : forall b:bool, eqb b (negb b) = false.\nProof.\nunfold eqb;unfold negb;intro b;destruct b;reflexivity.\nQed.\n\nLemma if_negb :\n  forall (A:Type) (b:bool) (x y:A),\n    (if negb b then x else y) = (if b then y else x).\nProof.\nintros A b x y.\nunfold negb.\ndestruct b;reflexivity.\nQed.\n\nLemma negb_true_iff : forall b, negb b = true <-> b = false.\nProof.\nintro b;unfold iff;unfold negb.\ndestruct b;split;intros;try(symmetry;assumption);try(reflexivity).\nQed.\n\nLemma negb_false_iff : forall b, negb b = false <-> b = true.\nProof.\nunfold iff;unfold negb.\nintro b;destruct b;split;intros;try(reflexivity);try(symmetry;assumption).\nQed.\n\nLemma orb_true_iff :\n  forall b1 b2, orb b1 b2 = true <-> b1 = true \\/ b2 = true.\nProof.\nunfold iff;unfold orb.\nintros a b;destruct a;destruct b;split;intros;try(reflexivity);try(right;reflexivity);try(left;reflexivity);try(right;assumption).\ninversion H;assumption.\nQed.\n\nLemma orb_false_iff :\n  forall b1 b2, orb b1 b2 = false <-> b1 = false /\\ b2 = false.\nProof.\nunfold iff. unfold orb.\nintros a b;destruct a;destruct b;split;intros;try(split);try(assumption);try(reflexivity).\ninversion H;assumption.\ninversion H;try(discriminate).\ninversion H;try(discriminate).\nQed.\n\nLemma orb_true_elim :\n  forall b1 b2:bool, (orb b1 b2) = true -> {b1 = true} + {b2 = true}.\nProof.\nintros a b.\nunfold orb.\ndestruct a;destruct b;intros;try(left;reflexivity);try(right;reflexivity);try(right;assumption).\nDefined.\n\nLemma orb_prop : forall a b:bool, (orb a b) = true -> a = true \\/ b = true.\nProof.\nunfold orb.\nintros a b;destruct a;destruct b;intros;try(right;reflexivity);try(left;reflexivity).\nleft;assumption.\nQed.\n\nLemma orb_true_intro :\n  forall b1 b2:bool, b1 = true \\/ b2 = true -> orb b1 b2 = true.\nProof.\nunfold orb.\nintros a b;destruct a;destruct b;intros;try(reflexivity).\ninversion H;assumption.\nQed.\n\nLemma orb_false_intro :\n  forall b1 b2:bool, b1 = false -> b2 = false -> orb b1 b2 = false.\nProof.\nunfold orb.\nintros a b;destruct a;destruct b;intros;try(reflexivity);try(assumption).\nQed.\n\nLemma orb_false_elim :\n  forall b1 b2:bool, orb b1 b2 = false -> b1 = false /\\ b2 = false.\nProof.\nunfold orb.\nintros a b;destruct a;destruct b;intros;split;try(reflexivity);try(assumption).\nQed.\n\nLemma orb_diag : forall b, orb b b = b.\nProof.\ndestruct b;reflexivity.\nQed.\n\nLemma orb_true_r : forall b:bool, orb b true = true.\nProof.\nintro b;destruct b;reflexivity.\nQed.\n\n\nLemma orb_true_l : forall b:bool, orb true b = true.\nProof.\nintro b;destruct b;reflexivity.\nQed.\n\nLemma orb_false_r : forall b:bool, orb b false = b.\nProof.\nintro b;destruct b;reflexivity.\nQed.\n\nLemma orb_false_l : forall b:bool, orb false b = b.\nProof.\nintro b;destruct b;reflexivity.\nQed.\n\nLemma orb_negb_r : forall b:bool, orb b (negb b) = true.\nProof.\nintro b;destruct b;reflexivity.\nQed.\n\nLemma orb_comm : forall b1 b2:bool, orb b1 b2 = orb b2 b1.\nProof.\nintros a b;destruct a;destruct b;reflexivity.\nQed.\n\nLemma orb_assoc : forall b1 b2 b3:bool, orb b1 (orb b2 b3) = orb (orb b1 b2) b3.\nProof.\nintros a b c;destruct a;destruct b;destruct c;reflexivity.\nQed.\n\nLemma andb_true_iff :\n  forall b1 b2:bool, andb b1 b2 = true <-> b1 = true /\\ b2 = true.\nProof.\nunfold iff,andb.\nintros a b;destruct a;destruct b;split;intros;try(split);try(reflexivity);try(assumption).\ninversion H;discriminate.\ninversion H;discriminate.\ninversion H;assumption.\nQed.\n\nLemma andb_false_iff :\n  forall b1 b2:bool, andb b1 b2 = false <-> b1 = false \\/ b2 = false.\nProof.\nunfold iff, andb.\nintros a b;destruct a;destruct b;split;intros;try(left;assumption);try(right;assumption);try(reflexivity).\ninversion H;assumption.\nQed.\n\nLemma andb_true_eq :\n  forall a b:bool, true = andb a b -> true = a /\\ true = b.\nProof.\nunfold andb.\nintros a b;destruct a;destruct b;intros;split;try(reflexivity);try(assumption).\nDefined.\n\nLemma andb_false_intro1 : forall b1 b2:bool, b1 = false ->andb b1  b2 = false.\nProof.\nunfold andb.\nintros a b;destruct a;destruct b;intros;try(reflexivity);assumption.\nQed.\n\nLemma andb_false_intro2 : forall b1 b2:bool, b2 = false -> andb b1 b2 = false.\nProof.\nunfold andb.\nintros a b;destruct a;destruct b;intros;try(reflexivity);try(assumption).\nQed.\n\nLemma andb_false_r : forall b:bool, andb b false = false.\nProof.\nintro b;destruct b;reflexivity.\nQed.\n\nLemma andb_false_l : forall b:bool, andb false b = false.\nProof.\nintro b. simpl. reflexivity.\nQed.\n\nLemma andb_diag : forall b, andb b b = b.\nProof.\nintro b;destruct b;reflexivity.\nQed.\n\nLemma andb_true_r : forall b:bool, andb b true = b.\nProof.\nintro b;destruct b;reflexivity.\nQed.\n\nLemma andb_true_l : forall b:bool, andb true b = b.\nProof.\nsimpl. reflexivity.\nQed.\n\nLemma andb_false_elim :\n  forall b1 b2:bool, andb b1 b2 = false -> {b1 = false} + {b2 = false}.\nProof.\nunfold andb.\nintros a b;destruct a;destruct b;intros;try(discriminate);try(left;reflexivity).\nright;reflexivity.\nDefined.\n\n\nLemma andb_negb_r : forall b:bool, andb b (negb b) = false.\nProof.\nintro b;destruct b;reflexivity.\nQed.\n\nLemma andb_comm : forall b1 b2:bool, andb b1 b2 = andb b2 b1.\nProof.\nintros a b;destruct a;destruct b;reflexivity.\nQed.\n\n\nLemma andb_assoc : forall b1 b2 b3:bool, andb b1 (andb b2 b3) = andb (andb b1 b2) b3.\nProof.\nintros a b c;destruct a;destruct b;destruct c;reflexivity.\nQed.\n\n(*******************************************)\n(** * Properties mixing [andb] and [orb] *)\n(*******************************************)\n\n(** Distributivity *)\n\nLemma andb_orb_distrib_r :\n  forall b1 b2 b3:bool, andb b1 (orb b2 b3) = orb (andb b1 b2) (andb b1 b3).\nProof.\nintros a b c;destruct a;destruct b;destruct c;reflexivity.\nQed.\n\nLemma andb_orb_distrib_l :\n forall b1 b2 b3:bool, andb (orb b1 b2) b3 = orb (andb b1 b3) (andb b2 b3).\nProof.\nintros a b c;destruct a;destruct b;destruct c;reflexivity.\nQed.\n\nLemma orb_andb_distrib_r :\n  forall b1 b2 b3:bool, orb b1 (andb b2 b3) = andb (orb b1 b2) (orb b1 b3).\nProof.\nintros a b c;destruct a;destruct b;destruct c;reflexivity.\nQed.\n\nLemma orb_andb_distrib_l :\n  forall b1 b2 b3:bool, orb (andb b1 b2) b3 = andb (orb b1 b3) (orb b2 b3).\nProof.\nintros a b c;destruct a;destruct b;destruct c;reflexivity.\nQed.\n\nLemma absorption_andb : forall b1 b2:bool, andb b1 (orb b1 b2) = b1.\nProof.\nintros a b;destruct a;destruct b;reflexivity.\nQed.\n\nLemma absorption_orb : forall b1 b2:bool, orb b1 (andb b1 b2) = b1.\nProof.\nintros a b;destruct a;destruct b;reflexivity.\nQed.\n\nLemma xorb_false_r : forall b:bool, xorb b false = b.\nProof.\nintros a;destruct a;reflexivity.\nQed.\n\nLemma xorb_false_l : forall b:bool, xorb false b = b.\nProof.\nintros a;destruct a;reflexivity.\nQed.\n\nLemma xorb_true_r : forall b:bool, xorb b true = negb b.\nProof.\nintros a;destruct a;reflexivity.\nQed.\n\nLemma xorb_true_l : forall b:bool, xorb true b = negb b.\nProof.\nintros a;destruct a;reflexivity.\nQed.\n\nLemma xorb_nilpotent : forall b:bool, xorb b b = false.\nProof.\nintros a;destruct a;reflexivity.\nQed.\n\n(** Commutativity *)\n\nLemma xorb_comm : forall b b':bool, xorb b b' = xorb b' b.\nProof.\nintros a b;destruct a;destruct b;reflexivity.\nQed.\n\n\nLemma xorb_assoc_reverse :\n  forall b b' b'':bool, xorb (xorb b b') b'' = xorb b (xorb b' b'').\nProof.\nintros a b c;destruct a;destruct b;destruct c;reflexivity.\nQed.\n\nLemma xorb_eq : forall b b':bool, xorb b b' = false -> b = b'.\nProof.\nintros a b;destruct a;destruct b;simpl;intros;try(reflexivity);try(assumption).\nsymmetry;assumption.\nQed.\n\nLemma xorb_move_l_r_1 :\n  forall b b' b'':bool, xorb b b' = b'' -> b' = xorb b b''.\nProof.\nintros a b c.\ndestruct a;destruct b;destruct c;simpl;intros;try(reflexivity);try(assumption);symmetry;assumption.\nQed.\n\nLemma xorb_move_l_r_2 :\n  forall b b' b'':bool, xorb b b' = b'' -> b = xorb b'' b'.\nProof.\nintros a b c;destruct a;destruct b;destruct c;simpl;intros;\ntry(reflexivity);try(assumption);symmetry;assumption.\nQed.\n\nLemma xorb_move_r_l_1 :\n  forall b b' b'':bool, b = xorb b' b'' -> xorb b' b = b''.\nProof.\nintros a b c;destruct a;destruct b;destruct c;simpl;intros;\ntry(reflexivity);try(assumption);symmetry;assumption.\nQed.\n\nLemma xorb_move_r_l_2 :\n  forall b b' b'':bool, b = xorb b' b'' -> xorb b b'' = b'.\nProof.\nintros a b c;destruct a;destruct b;destruct c;simpl;intros;\ntry(reflexivity);try(assumption);symmetry;assumption.\nQed.\n\nLemma negb_xorb_l : forall b b', negb (xorb b b') = xorb (negb b) b'.\nProof.\nintros a b;destruct a;destruct b;simpl;reflexivity.\nQed.\n\nLemma negb_xorb_r : forall b b', negb (xorb b b') = xorb b (negb b').\nProof.\nintros a b;destruct a;destruct b;simpl;reflexivity.\nQed.\n\nLemma xorb_negb_negb : forall b b', xorb (negb b) (negb b') = xorb b b'.\nProof.\nintros a b;destruct a;destruct b;reflexivity.\nQed.\n\nLemma eq_iff_eq_true : forall b1 b2, b1 = b2 <-> (b1 = true <-> b2 = true).\nProof.\nintros a b;destruct a;destruct b;split;try(split);intros;\ntry(reflexivity);try(discriminate).\ninversion H. symmetry. apply H0. reflexivity.\ninversion H. apply H1. reflexivity.\nQed.\n\nLemma eq_true_iff_eq : forall b1 b2, (b1 = true <-> b2 = true) -> b1 = b2.\nProof.\nintros a b h.\ninversion h as [l r].\ndestruct a;destruct b;try(reflexivity).\nsymmetry;apply l;reflexivity.\napply r;reflexivity.\nQed.\n\nLemma eq_true_negb_classical : forall b:bool, negb b <> true -> b = true.\nProof.\nintros b hn.\ndestruct b;try(reflexivity).\nsimpl in hn. contradiction.\nQed.\n\nLemma eq_true_not_negb : forall b:bool, b <> true -> negb b = true.\nProof.\nintros b h.\ndestruct b;simpl;try(reflexivity).\ncontradiction.\nQed.\n\nLemma absurd_eq_bool : forall b b':bool, False -> b = b'.\nProof.\nintros a b.\nintro h.\ncontradiction.\nQed.\n\nLemma absurd_eq_true : forall b, False -> b = true.\nProof.\nintros b F.\ncontradiction.\nQed.\n\nLemma trans_eq_bool : forall x y z:bool, x = y -> y = z -> x = z.\nProof.\nintros x y z.\nintros eqxy eqyz.\nsubst z. subst x. reflexivity.\nQed.\n\nLemma Is_true_eq_true : forall x:bool, Is_true x -> x = true.\nProof.\nintros b h.\nunfold Is_true in h.\ndestruct b;try(reflexivity).\ncontradiction.\nQed.\n\nLemma Is_true_eq_left : forall x:bool, x = true -> Is_true x.\nProof.\nunfold Is_true.\nintros b h.\nsubst b.\napply I.\nQed.\n\nLemma Is_true_eq_right : forall x:bool, true = x -> Is_true x.\nProof.\nunfold Is_true.\nintros b heq.\nsubst b.\napply I.\nQed.\n\nLemma eqb_refl : forall x:bool, Is_true (eqb x x).\nProof.\nunfold Is_true.\nintro b.\ndestruct b;simpl;apply I.\nQed.\n\nLemma eqb_eq : forall x y:bool, Is_true (eqb x y) -> x = y.\nProof.\nintros a b.\nunfold Is_true.\ndestruct a;destruct b;simpl;intros;try(reflexivity);contradiction.\nQed.\n\nLemma orb_prop_elim :\n  forall a b:bool, Is_true (orb a b) -> Is_true a \\/ Is_true b.\nProof.\nintros a b;destruct a;destruct b;simpl;intros.\nleft;apply I.\nleft;apply I.\nright;apply I.\nright;contradiction.\nQed.\n\nLemma orb_prop_intro :\n  forall a b:bool, Is_true a \\/ Is_true b -> Is_true (orb a b).\nProof.\nintros a b;destruct a;destruct b;simpl;intros;try(apply I).\ninversion H;contradiction.\nQed.\n\nLemma andb_prop_intro :\n  forall b1 b2:bool, Is_true b1 /\\ Is_true b2 -> Is_true (andb b1 b2).\nProof.\nintros a b;destruct a;destruct b;simpl;intros h;inversion h as [l r].\napply I.\ncontradiction.\ncontradiction.\ncontradiction.\nQed.\n\nLemma andb_prop_elim :\n  forall a b:bool, Is_true (andb a b) -> Is_true a /\\ Is_true b.\nProof.\nintros a b;destruct a;destruct b;simpl;intros;split;\ntry(apply I);try(contradiction).\nQed.\n\nLemma eq_bool_prop_intro :\n  forall b1 b2, (Is_true b1 <-> Is_true b2) -> b1 = b2.\nProof.\nintros a b;destruct a;destruct b;simpl;intro h;inversion h as [l r];try(reflexivity).\ncontradiction.\ncontradiction.\nQed.\n\nLemma eq_bool_prop_elim : forall b1 b2, b1 = b2 -> (Is_true b1 <-> Is_true b2).\nProof.\nintros a b;destruct a;destruct b;simpl;split;intro h;\ntry(apply I);try(discriminate);try(contradiction).\nQed.\n\nLemma negb_prop_elim : forall b, Is_true (negb b) -> ~ Is_true b.\nProof.\nintros b;destruct b;simpl;intros h n;contradiction.\nQed.\n\nLemma negb_prop_intro : forall b, ~ Is_true b -> Is_true (negb b).\nProof.\nintro b;destruct b;simpl;intro h.\ncontradiction. trivial.\nQed.\n\nLemma negb_prop_classical : forall b, ~ Is_true (negb b) -> Is_true b.\nProof.\nintros b;destruct b;simpl;intro h.\ntrivial.\napply h;trivial.\nQed.\n\nLemma negb_prop_involutive : forall b, Is_true b -> ~ Is_true (negb b).\nProof.\nintro b;destruct b;simpl;intros h n;contradiction.\nQed.\n\nLemma andb_if : forall (A:Type)(a a':A)(b b' : bool),\n  (if (andb b b') then a else a') =\n  (if b then if b' then a else a' else a').\nProof.\nintros A a1 a2 b1 b2.\ndestruct b1;destruct b2;simpl;reflexivity.\nQed.\n\nLemma negb_if : forall (A:Type)(a a':A)(b:bool),\n (if negb b then a else a') =\n (if b then a' else a).\nProof.\nintros A x y b;destruct b;simpl;reflexivity.\nQed.\n\nDefinition andbl (a b:bool) := if a then b else false.\nDefinition orbl (a b:bool) := (if a then true else b).\n\nLemma andb_lazy_alt : forall a b : bool, andb a b = andbl a b.\nProof.\nintros a b;destruct a;destruct b;reflexivity.\nQed.\n\nLemma orb_lazy_alt : forall a b : bool, orb a b = orbl a b.\nProof.\nintros a b;destruct a;destruct b;reflexivity.\nQed.\n\nInductive reflect (P : Prop) : bool -> Set :=\n  | ReflectT : P -> reflect P true\n  | ReflectF : ~ P -> reflect P false.\n\nLemma reflect_iff : forall P b, reflect P b -> (P<->b=true).\nProof.\nintros P b h.\ndestruct b;split;simpl;intro p;try(reflexivity);inversion h;try(assumption);try(reflexivity);try(contradiction);try(discriminate).\nQed.\n\nLemma iff_reflect : forall P b, (P<->b=true) -> reflect P b.\nProof.\nintros P b.\ndestruct b;simpl;intro h;inversion h as [l r].\napply ReflectT. apply r. reflexivity.\napply ReflectF. intro p.\ndiscriminate (l p).\nDefined.\n\nLemma reflect_dec : forall P b, reflect P b -> {P}+{~P}.\nProof.\nintros P b h.\ndestruct b;inversion h.\nleft;assumption.\nright;assumption.\nDefined.", "meta": {"author": "xavierdpt", "repo": "adventures", "sha": "038a17cf71d8f9690ad168b2592b12e61d2e6c32", "save_path": "github-repos/coq/xavierdpt-adventures", "path": "github-repos/coq/xavierdpt-adventures/adventures-038a17cf71d8f9690ad168b2592b12e61d2e6c32/trove/theories/Bool/Bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.6651486768472801}}
{"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\n(* A simple symmetric encryption scheme based on a pseudorandom function, and a proof that the scheme is secure according to IND-CPA. *)\n\nSet Implicit Arguments.\n\nRequire Import FCF.\nRequire Import PRF.\nRequire Import Encryption.\nRequire Import RndInList.\nRequire Import OTP.\nRequire Import WC_PolyTime.\n\nOpaque evalDist.\nOpaque getSupport.\n\nLocal Open Scope nat_scope.\nLocal Open Scope type_scope.\nLocal Open Scope list_scope.\n\nSection PRF_Encryption_concrete.\n  \n  Variable eta : nat.\n  \n  Definition Key := Bvector eta.\n  Definition Plaintext := Bvector eta.\n  Definition Ciphertext := Bvector eta * Bvector eta.\n\n  Variable f : Bvector eta -> Bvector eta -> Bvector eta.\n\n  Definition PRFE_KeyGen := \n    {0, 1} ^ eta.\n  \n  Definition PRFE_Encrypt (k : Key )(p : Plaintext) :=\n    r <-$ {0, 1} ^ eta;\n    pad <- f k r;\n    ret (r, p xor pad).\n  \n  Definition PRFE_Decrypt (k : Key)(c : Ciphertext) :=\n    r <- fst c;\n    pad <- f k r;\n    (snd c) xor pad.\n    \n  Theorem PRF_Encrypt_correct : \n    forall k p c,\n      In c (getSupport (PRFE_Encrypt k p)) ->\n      PRFE_Decrypt k c = p.\n    \n    intuition.\n    unfold PRFE_Encrypt, PRFE_Decrypt in *.\n    repeat simp_in_support.\n\n    simpl.\n    rewrite BVxor_assoc.\n    rewrite BVxor_same_id.\n    rewrite BVxor_id_r.\n    intuition.\n  Qed.\n  \n  Section PRF_Encryption_IND_CPA_concrete.\n  \n    Variable State : Set.\n    Hypothesis State_EqDec : EqDec State.\n    Variable A1 : OracleComp Plaintext Ciphertext (Plaintext * Plaintext * State).\n    Variable A2 : State -> Ciphertext -> OracleComp Plaintext Ciphertext bool.\n\n    Hypothesis A1_wf : well_formed_oc A1.\n    Hypothesis A2_wf : forall x y, well_formed_oc (A2 x y).\n\n    Variable q1 q2 : nat.\n    Hypothesis A1_qam : queries_at_most A1 q1.\n    Hypothesis A2_qam : forall s c, queries_at_most (A2 s c) q2.\n    \n    Definition PRFE_EncryptOracle := EncryptOracle PRFE_Encrypt _.\n    \n    Local Open Scope nat_scope.\n\n    (* Step 1: Inline some definitions and simplify. *)\n    Definition G1 :=\n      key <-$ PRFE_KeyGen;\n      [b, _] <-$2\n      (\n        [p0, p1, s_A] <--$3 A1;\n        b <--$$ {0, 1};\n        pb <- if b then p1 else p0;\n        c <--$$ PRFE_Encrypt key pb;\n        b' <--$ (A2 s_A c);\n        $ ret (eqb b b')\n      )\n      _ _\n      (PRFE_EncryptOracle key) tt;\n      ret b.\n\n    Theorem G1_equiv : \n      Pr[IND_CPA_SecretKey_G PRFE_KeyGen PRFE_Encrypt A1 A2 _] == Pr[G1].\n      reflexivity.\n    \n    Qed.\n\n    (* Step 2 : Replace the PRF with a random function. *)\n\n    Definition PRFE_RandomFunc := @randomFunc (Bvector eta) (Bvector eta) ({0,1}^eta) _.\n\n    Definition RF_Encrypt s p :=\n      r <-$ {0, 1} ^ eta;\n      [pad, s] <-$2 PRFE_RandomFunc s r;\n      ret (r, p xor pad, s).\n    \n    Definition G2 :=\n      [a, o] <-$2 A1 _ _ (RF_Encrypt) nil;\n      [p0, p1, s_A] <-3 a;\n      b <-$ {0, 1};\n      pb <- if b then p1 else p0;\n        [c, o] <-$2 RF_Encrypt o pb;\n        [b', o] <-$2 (A2 s_A c) _ _ RF_Encrypt o;\n        ret (eqb b b').\n\n\n    (* To prove this step, we put the game in the form of a computation that access the PRF as an oracle.  This allows us to apply the PRF definition. *)\n\n    Definition PRFE_Encrypt_OC (x : unit)(p : Plaintext) : OracleComp (Bvector eta) (Bvector eta) (Ciphertext * unit) :=\n        r <--$$ {0, 1} ^ eta;\n        pad <--$ OC_Query _ r;\n        $ (ret (r, p xor pad, tt)).\n\n    Definition PRF_A : OracleComp (Bvector eta) (Bvector eta) bool :=\n      [a, n] <--$2 OC_Run _ _ _ A1 PRFE_Encrypt_OC tt;\n      [p0, p1, s_A] <-3 a;\n      b <--$$ {0, 1};\n      pb <- if b then p1 else p0;\n      r <--$$ {0, 1} ^ eta;\n      pad <--$ OC_Query _ r;\n      c <- (r, pb xor pad);\n      z <--$ OC_Run  _ _ _ (A2 s_A c) PRFE_Encrypt_OC n;\n      [b', _] <-2 z;\n      $ ret (eqb b b').\n\n    (* Later we will need to reason about the cost of PRF_A, so we make an equivalent procedure without some of the complications. *)\n    Definition PRF_A' :=\n      z <--$\n      OC_Run _ _ _ A1 PRFE_Encrypt_OC tt;\n      b <--$$\n      (m <-$ { 0 , 1 }^1; ret Vector.hd m);\n      r <--$$ { 0 , 1 }^eta;\n      pad <--$ OC_Query (Vector.t bool eta) r;\n      z0 <--$\n      OC_Run _ _ _ (A2 (snd (fst z)) (r, \n        (if b then  (snd (fst (fst z)))  else (fst (fst (fst z))))\n        xor pad)) PRFE_Encrypt_OC (snd z);\n       $ ret eqb b (fst z0).\n\n    Theorem PRF_A'_equiv :\n      forall (S : Set)(eqds : EqDec S)(o : S -> (Bvector eta) -> Comp ((Bvector eta) * S)) s x, \n      evalDist (PRF_A _ _ o s) x == evalDist (PRF_A' _ _ o s) x.\n\n      intuition.\n      unfold PRF_A, PRF_A'.\n\n      do 5 (comp_simp; simpl;\n      comp_skip; try eapply eqRat_refl).\n      comp_simp; simpl.\n      comp_simp.\n      intuition.\n\n    Qed.\n\n    Definition f_oracle(k : Bvector eta)(x : unit)(v : Bvector eta) :=\n      ret (f k v, tt).\n   \n    Theorem Ciphertext_inh : \n      Ciphertext.\n\n      apply (oneVector eta, oneVector eta).\n\n    Qed.\n    Hint Resolve Ciphertext_inh : inhabited.\n\n    Theorem PRFE_EncryptOracle_spec : forall a x2 x,\n       comp_spec\n     (fun (y1 : Ciphertext * unit) (y2 : Ciphertext * (unit * unit)) =>\n      fst y1 = fst y2 /\\ snd y1 = fst (snd y2))\n     (PRFE_EncryptOracle x (fst x2) a)\n     (p <-$\n      (PRFE_Encrypt_OC (fst x2) a) unit unit_EqDec (f_oracle x) (snd x2);\n      ret (fst (fst p), (snd (fst p), snd p))).\n\n      intuition.\n      unfold PRFE_EncryptOracle, EncryptOracle, PRFE_Encrypt.\n      simpl.\n\n      prog_inline_l.\n      do 2 prog_inline_r.\n      comp_skip.\n      prog_simp.\n      unfold f_oracle.\n      do 2 (prog_inline_r;\n      prog_simp).\n      eapply comp_spec_ret.\n      simpl.\n      intuition.\n      \n    Qed.\n\n    Theorem RF_EncryptOracle_spec : forall a x2,\n      comp_spec\n      (fun (y1 : Ciphertext * list (Bvector eta * Bvector eta))\n        (y2 : Ciphertext * (unit * list (Bvector eta * Bvector eta))) =>\n        fst y1 = fst y2 /\\ snd y1 = snd (snd y2)) (RF_Encrypt (snd x2) a)\n      (p <-$\n        (PRFE_Encrypt_OC (fst x2) a) (list (Bvector eta * Bvector eta))\n        (list_EqDec (pair_EqDec (Bvector_EqDec eta) (Bvector_EqDec eta)))\n        PRFE_RandomFunc (snd x2); ret (fst (fst p), (snd (fst p), snd p))).\n      \n      intuition.\n      unfold RF_Encrypt, PRFE_RandomFunc, randomFunc.\n      simpl.\n      do 2 prog_inline_r.\n      comp_skip.\n      prog_simp.\n      prog_inline_r.\n      comp_skip.\n      prog_inline_r.\n      prog_simp.\n      eapply comp_spec_ret.\n      simpl.\n      intuition.\n      \n    Qed.\n      \n    Theorem G1_PRF_A_equiv : \n      Pr[G1] == Pr[k <-$ {0, 1}^ eta; [b, _] <-$2 PRF_A _ _ (f_oracle k) tt; ret b].\n\n      Opaque PRFE_Encrypt_OC.\n\n      unfold G1, PRF_A, PRFE_KeyGen.\n      comp_skip.\n\n      simpl.\n      inline_first.\n          \n      eapply comp_spec_impl_eq.\n      eapply (@comp_spec_seq _ _ \n        (fun a1 a2 => fst a1 = fst a2 /\\ snd a1 = fst (snd a2))); eauto with inhabited.\n      \n      eapply (@oc_comp_spec_eq _ _ _ _ _ _ _ _ _ _ _ _ _ _ (fun a b => a = fst b)).\n      trivial.\n      intuition.\n      subst.\n\n      eapply PRFE_EncryptOracle_spec.\n      intuition.\n      destruct b2.\n      simpl in *.\n      subst.\n      \n      prog_simp.\n      simpl.\n     \n      do 2 prog_inline_l.\n      do 2 prog_inline_r.\n      comp_skip.\n      prog_simp.\n\n      unfold PRFE_Encrypt.\n      do 3 prog_inline_l.\n      do 2 (prog_inline_r; prog_simp).\n      comp_skip.\n      prog_simp.\n    \n      unfold f_oracle.\n      prog_inline_l.\n      do 3 (prog_inline_r; prog_simp).\n      \n      eapply comp_spec_seq; eauto with inhabited.\n      eapply (@oc_comp_spec_eq _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n        (fun a b => a = fst b)).\n      trivial.\n      intuition.\n      subst.\n      \n      eapply PRFE_EncryptOracle_spec.\n      intuition.\n      destruct b4; simpl in *; subst.\n      \n      prog_simp.\n      simpl.\n      prog_inline_l; prog_simp.\n      prog_inline_r; prog_simp.\n      eapply comp_spec_ret.\n      intuition.\n      \n    Qed.\n\n    Theorem G1_PRF_A'_equiv : \n      Pr[k <-$ {0, 1}^ eta; [b, _] <-$2 PRF_A _ _ (f_oracle k) tt; ret b] ==\n      Pr[k <-$ {0, 1}^ eta; [b, _] <-$2 PRF_A' _ _ (f_oracle k) tt; ret b].\n\n      intuition.\n      comp_skip.\n      comp_skip.\n      eapply PRF_A'_equiv.\n\n    Qed.\n\n    Theorem G2_PRF_A_equiv : \n      Pr[G2] == Pr[[b, _] <-$2 PRF_A _ _ PRFE_RandomFunc nil; ret b].\n      pose proof RF_EncryptOracle_spec as RFE_spec.\n      \n      unfold G2, PRF_A.\n      simpl.\n      inline_first.\n      \n      eapply comp_spec_impl_eq.\n      eapply (@comp_spec_seq _ _ \n        (fun a1 a2 => fst a1 = fst a2 /\\ snd a1 = snd (snd a2))); eauto with inhabited.\n      \n      eapply comp_spec_consequence.\n      eapply (@oc_comp_spec_eq _ _ _ _ _ _ _ _ _ _ _ _ _ _ (fun a b => a = snd b)).\n      trivial.\n      intuition.\n      subst.\n      \n      eapply RFE_spec.\n      intuition.\n      intuition.\n      prog_simp.\n      simpl.\n      \n      do 2 prog_inline_r.\n      comp_skip.\n      unfold RF_Encrypt at 1.\n      prog_simp.\n      prog_inline_l.\n      do 2 prog_inline_r.\n      comp_skip.\n      prog_simp.\n      simpl in *.\n      subst.\n      \n      prog_inline_l.\n      prog_inline_r.\n      comp_skip.\n      inversion H3; clear H3; subst.\n      do 2 prog_inline_r.\n      eapply comp_spec_seq; eauto with inhabited.\n      eapply (@oc_comp_spec_eq _ _ _ _ _ _ _ _ _ _ _ _ _ _ (fun x y => x = snd y)).\n      trivial.\n      intuition.\n      subst.\n      \n      eapply RFE_spec.\n      intuition.\n      prog_simp.\n      simpl.\n      prog_inline_r.\n      simpl.\n      prog_simp.\n      eapply comp_spec_ret.\n      simpl in *.\n      intuition.\n      subst.\n      intuition.\n      subst; intuition.\n\n    Qed.\n\n    Theorem G2_PRF_A'_equiv : \n      Pr[[b, _] <-$2 PRF_A _ _ PRFE_RandomFunc nil; ret b] ==\n      Pr[[b, _] <-$2 PRF_A' _ _ PRFE_RandomFunc nil; ret b].\n\n      intuition.\n      comp_skip.\n      eapply PRF_A'_equiv.\n\n    Qed.\n      \n    Theorem G1_G2_close : |Pr[G1] - Pr[G2]| == PRF_Advantage ({0, 1}^eta) ({0, 1}^eta) f _ _ PRF_A'.\n      rewrite G1_PRF_A_equiv.\n      rewrite G1_PRF_A'_equiv.\n      rewrite G2_PRF_A_equiv.\n      rewrite G2_PRF_A'_equiv.\n      reflexivity.\n    Qed.\n\n\n    (* Step 3 : replace the PRF output with random value *)\n    (* This is identical to G2 as long as the adversary does not encounter the encryption nonce during a query. *)\n\n    Definition G3 :=\n    [a, o] <-$2 A1 _ _ (RF_Encrypt) nil;\n    [p0, p1, s_A] <-3 a;\n    b <-$ {0, 1};\n    pb <- if b then p1 else p0;\n      r <-$ {0, 1}^eta;\n      pad <-$ {0, 1}^eta;\n      c <- (r, pb xor pad);\n      [b', o] <-$2 (A2 s_A c) _ _ RF_Encrypt o;\n      ret (eqb b b').\n\n    (* start with G2 and move the challenge encryption sampling to the front. *)\n    Definition G2_1 :=\n      r <-$ {0, 1}^eta;\n      [a, o] <-$2 A1 _ _ (RF_Encrypt) nil;\n      [p0, p1, s_A] <-3 a;\n      b <-$ {0, 1};\n      pb <- if b then p1 else p0;\n        [pad, o] <-$2 PRFE_RandomFunc o r;\n        c <- (r, pb xor pad);\n        [b', o] <-$2 (A2 s_A c) _ _ RF_Encrypt o;\n        ret (eqb b b').\n\n    Theorem G2_1_equiv : \n      Pr[G2] == Pr[G2_1].\n\n      unfold G2, G2_1.\n\n      do 2 (comp_swap_r; comp_skip; comp_simp).\n      unfold RF_Encrypt.\n      do 2(inline_first; comp_skip; comp_simp).\n      intuition.\n    Qed.\n\n    (* We will modify the procedure one adversary call at a time.  Start with the first one. *)\n    (* make the bad event visible. *)\n    Definition G2_2 :=\n      r <-$ {0, 1}^eta;\n      [a, o] <-$2 A1 _ _ (RF_Encrypt) nil;\n      bad <- if (arrayLookup _ o r) then true else false;\n      [p0, p1, s_A] <-3 a;\n      b <-$ {0, 1};\n      pb <- if b then p1 else p0;\n        [pad, o] <-$2 PRFE_RandomFunc o r;\n        c <- (r, pb xor pad);\n        [b', o] <-$2 (A2 s_A c) _ _ RF_Encrypt o;\n        ret (eqb b b', bad).\n\n    Theorem G2_1_2_equiv : \n      Pr[G2_1] == Pr[x <-$ G2_2; ret fst x].\n\n      unfold G2_1, G2_2.\n\n      do 5 (inline_first; comp_skip; comp_simp).\n      simpl; intuition.\n    Qed.\n\n    (* When r is not in the domain of the random function, we can sample the pad randomly, then add it to the function. *)\n    \n    Definition G2_3 :=\n      r <-$ {0, 1}^eta;\n      [a, o] <-$2 A1 _ _ (RF_Encrypt) nil;\n      bad <- if (arrayLookup _ o r) then true else false;\n      [p0, p1, s_A] <-3 a;\n      b <-$ {0, 1};\n      pb <- if b then p1 else p0;\n        pad <-$ {0, 1}^ eta;\n        c <- (r, pb xor pad);\n        [b', o] <-$2 (A2 s_A c) _ _ RF_Encrypt ((r, pad) :: o);\n        ret (eqb b b', bad).\n\n    Local Open Scope rat_scope.\n\n    Theorem RF_Encrypt_wf : \n      forall s a,\n        well_formed_comp (RF_Encrypt s a).\n      \n      intuition.\n      unfold RF_Encrypt.\n      wftac.\n      eapply randomFunc_wf.\n      wftac.\n    Qed.\n\n    Hint Resolve RF_Encrypt_wf : wftac.\n\n      \n    Theorem G2_2_3_eq_until_bad : \n      forall z,\n        evalDist G2_2 (z, false) == evalDist G2_3 (z, false).\n      pose proof RF_Encrypt_wf.\n      intuition.\n      unfold G2_2, G2_3.\n\n      do 3 (comp_skip; comp_simp).\n      unfold PRFE_RandomFunc, randomFunc.\n      case_eq (arrayLookup (Bvector_EqDec eta) l x ); intuition.\n      comp_simp.\n\n      comp_irr_r; wftac.\n\n      comp_irr_l; wftac. \n      eapply oc_comp_wf; intuition.\n\n      comp_irr_r; wftac.\n      eapply oc_comp_wf; intuition.\n\n      comp_simp.\n\n      Local Transparent evalDist.\n      Local Transparent getSupport.\n      dist_compute.\n      Local Opaque evalDist.\n      Local Opaque getSupport.\n\n      inline_first.\n      comp_skip.\n\n    Qed.\n\n    Theorem G2_2_3_badness_same : \n      Pr[x <-$ G2_2; ret (snd x)] == Pr[x <-$ G2_3; ret (snd x)].\n      \n      pose proof RF_Encrypt_wf.\n      unfold G2_2, G2_3.\n\n      do 3 (inline_first; comp_skip; comp_simp).\n    \n      comp_inline_l.\n      comp_irr_l; wftac.\n      eapply randomFunc_wf; wftac.\n\n      comp_inline_r.\n      comp_irr_r; wftac.\n      \n      comp_simp.\n      comp_inline_l.\n      comp_irr_l; wftac.\n      eapply oc_comp_wf; intuition.\n\n      comp_inline_r.\n      comp_irr_r; wftac.\n      eapply oc_comp_wf; intuition.\n\n      comp_simp.\n      simpl.\n      intuition.\n\n    Qed.\n\n    (* provide a simplified form of the same with the same probability of badness. *)\n    Definition G2_2_bad :=\n      [a, o] <-$2 A1 _ _ (RF_Encrypt) nil;\n      ls <- fst (split o);\n      r <-$ {0, 1}^eta;\n      ret if (in_dec (EqDec_dec _) r ls) then true else false.\n\n    Theorem arrayLookup_In_split : \n      forall (A B : Set)(eqda : EqDec A)(ls : list (A * B))(a : A)(b : B),\n        arrayLookup _ ls a = Some b ->\n        In a (fst (split ls)).\n      \n      induction ls; intuition; simpl in *.\n      discriminate.\n      case_eq (eqb a a0); intuition.\n      rewrite H0 in H.\n      inversion H; clear H; subst.\n      \n      rewrite eqb_leibniz in H0.\n      subst.\n      remember (split ls) as x.\n      destruct x.\n      simpl.\n      intuition.\n      \n      rewrite H0 in H.\n      remember (split ls) as x.\n      destruct x.\n      simpl.\n      right.\n      eapply IHls.\n      eauto.\n      \n    Qed.\n\n    Theorem arrayLookup_not_In_split : \n      forall (A B : Set)(eqda : EqDec A)(ls : list (A * B))(a : A),\n        arrayLookup _ ls a = None ->\n        ~In a (fst (split ls)).\n      \n      induction ls; intuition; simpl in *.\n      case_eq (eqb a a0); intuition;\n      rewrite H1 in H.\n      discriminate.\n\n      remember (split ls) as x.\n      destruct x.\n      simpl in *.\n      intuition; subst.\n      rewrite eqb_refl in H1.\n      discriminate.\n      eauto.\n    Qed.\n    \n    Theorem G2_2_bad_equiv : \n      Pr[x <-$ G2_2; ret snd x] == Pr[G2_2_bad].\n      pose proof RF_Encrypt_wf.\n      rewrite G2_2_3_badness_same.\n\n      unfold G2_3, G2_2_bad.\n      inline_first.\n      comp_at comp_inline leftc 1%nat.\n      comp_swap_l.\n      comp_skip.\n      comp_simp.\n      comp_skip.\n      do 3 (comp_inline_l;\n      comp_irr_l; wftac).\n      eapply oc_comp_wf; intuition.\n\n      comp_simp.\n      eapply evalDist_ret_eq; simpl.\n      case_eq (arrayLookup (Bvector_EqDec eta) l x); intuition;\n      destruct (in_dec (EqDec_dec (Bvector_EqDec eta)) x (fst (split l))); intuition.\n      exfalso.\n      eauto using arrayLookup_In_split.\n\n      exfalso.\n      eapply (@arrayLookup_not_In_split _ _ (Bvector_EqDec eta)).\n      eauto.\n      trivial.\n      \n    Qed.\n\n    Theorem RF_Encrypt_length_incr : \n      forall a b c d,\n        In (a, b) (getSupport (RF_Encrypt c d)) ->\n        (length b <= 1 + length c)%nat.\n\n      intuition.\n      unfold RF_Encrypt in *.\n      repeat simp_in_support.\n      destruct x0.\n      repeat simp_in_support.\n      unfold PRFE_RandomFunc, randomFunc in *.\n      destruct (arrayLookup (Bvector_EqDec eta) c x); repeat simp_in_support;\n      simpl in *; lia.\n\n    Qed.\n\n      \n    Theorem G2_2_bad_small : Pr[x <-$ G2_2; ret snd x] <= q1 / (2 ^ eta).\n      pose proof RF_Encrypt_wf.\n\n      rewrite G2_2_bad_equiv.\n      unfold G2_2_bad.\n      comp_irr_l.\n      eapply oc_comp_wf; intuition.\n      comp_simp.\n     \n      assert (length l <= q1)%nat.\n\n      eapply qam_count;\n      eauto.\n      eapply RF_Encrypt_length_incr.\n      simpl; intuition.\n\n      eapply RndInList_prob.\n      rewrite split_length_l.\n      trivial.\n    Qed.\n\n    Theorem G2_2_3_close : \n      forall z, \n      | evalDist (x <-$ G2_2; ret fst x) z - evalDist (x <-$ G2_3; ret fst x) z | <=\n         q1 / (2 ^ eta).\n\n      intuition.\n      eapply leRat_trans.\n      eapply fundamental_lemma_h.\n      eapply G2_2_3_badness_same.\n      eapply G2_2_3_eq_until_bad.\n      eapply G2_2_bad_small.\n    Qed.    \n\n    (* Now switch the the second adversary call *)\n    \n    (* for this part we need an oracle that makes the bad event visible *)\n    Definition RF_Encrypt_bad (x : Bvector eta)(z : list (Bvector eta * Bvector eta) * bool) (p : Bvector eta):=\n      [s, bad] <-2 z;\n      r <-$ { 0 , 1 }^eta;\n      z <-$ PRFE_RandomFunc s r; \n      [pad, s0]<-2 z; \n      ret (r, p xor pad, (s0, bad || eqb x r)).\n\n    Definition G2_4 :=\n      r <-$ {0, 1}^eta;\n      [a, o] <-$2 A1 _ _ (RF_Encrypt) nil;\n      [p0, p1, s_A] <-3 a;\n      b <-$ {0, 1};\n      pb <- if b then p1 else p0;\n        pad <-$ {0, 1}^ eta;\n        c <- (r, pb xor pad);\n        [b', o] <-$2 (A2 s_A c) _ _ (RF_Encrypt_bad r) ((r, pad) :: o, false);\n        ret (eqb b b', (snd o)).\n\n    Theorem G2_3_4_equiv : \n      Pr[x <-$ G2_3; ret fst x] == Pr[x <-$ G2_4; ret fst x].\n\n      unfold G2_3, G2_4.\n      \n       do 4 (inline_first; comp_skip; comp_simp).\n\n      inline_first.\n      eapply comp_spec_impl_eq.\n      eapply comp_spec_seq; eauto with inhabited.\n      eapply (@oc_comp_spec_eq _ _ _ _ _ _ _ _ _ _ _ _ _ _ (fun a b => a = fst b)); intuition.\n      destruct x3; simpl in *; subst.\n      unfold RF_Encrypt.\n      clear H2.\n      comp_skip.\n      comp_skip.\n      eapply comp_spec_ret; simpl in *; intuition.\n\n      intuition.\n      simpl in *; subst.\n      prog_simp.\n      eapply comp_spec_ret; simpl in *; intuition.\n    Qed.\n\n     (* When this procedure doesn't go bad, we can remove the challenge pad from the function. *)\n    Definition G2_5 :=\n      r <-$ {0, 1}^eta;\n      [a, o] <-$2 A1 _ _ (RF_Encrypt) nil;\n      [p0, p1, s_A] <-3 a;\n      b <-$ {0, 1};\n      pb <- if b then p1 else p0;\n        pad <-$ {0, 1}^ eta;\n        c <- (r, pb xor pad);\n        [b', o] <-$2 (A2 s_A c) _ _ (RF_Encrypt_bad r) (o, false);\n        ret (eqb b b', snd o).\n\n    Theorem RF_Encrypt_bad_preserved : \n      forall a c d e f g h,\n        In (a, (c, d)) (getSupport (RF_Encrypt_bad e (f, g) h)) ->\n        g = true ->\n        d = true.\n      \n      intuition.\n      unfold RF_Encrypt_bad in *.\n      repeat simp_in_support.\n      destruct x0.\n      repeat simp_in_support.\n      eapply orb_true_l.\n      \n    Qed.\n\n      Theorem RF_Encrypt_bad_wf : \n        forall x a b, \n          well_formed_comp (RF_Encrypt_bad x a b).\n\n        intuition.\n        unfold RF_Encrypt_bad; wftac.\n        eapply randomFunc_wf; wftac.\n     \n      Qed.\n\n    Theorem G2_4_5_eq_until_bad : \n      forall z,\n        evalDist G2_4 (z, false) == evalDist G2_5 (z, false).\n\n      pose proof @RF_Encrypt_bad_preserved as RF_Encrypt_bad_preserved.\n      pose proof @RF_Encrypt_bad_wf as RF_Encrypt_bad_wf.\n      intuition.\n      unfold G2_4, G2_5.\n      do 4 (comp_skip; comp_simp).\n\n      eapply comp_spec_impl_eq.\n      eapply comp_spec_seq; eauto with inhabited.\n      eapply (@oc_comp_spec_eq_until_bad _ _ _ _ _ _ _ _ _ _ _ _ _ \n        (fun a => snd a) (fun a => snd a)\n        (fun a b => forall z,  z <> x -> arrayLookup _ (fst a) z = arrayLookup _ (fst b) z)).\n\n\n      intuition.\n      solve [intros; apply RF_Encrypt_bad_wf].\n      intuition.\n    \n      (* Prove that as long as the procedures don't go bad, the invariant holds *)\n      intuition.\n      simpl in H5; subst.\n      \n      (* TODO: mako this a theorem *)\n      unfold RF_Encrypt_bad, PRFE_RandomFunc, randomFunc.\n      comp_skip.\n      case_eq (eqb x b); intuition.\n   \n      prog_irr_l.\n      destruct (arrayLookup (Bvector_EqDec eta) a b); wftac.\n      prog_irr_r.\n      destruct (arrayLookup (Bvector_EqDec eta) a0 b); wftac.\n      prog_simp.\n      eapply comp_spec_ret; simpl in *; intuition.\n      rewrite orb_true_r in H10.\n      discriminate.\n      rewrite orb_true_r in H10.\n      discriminate.\n\n      case_eq (arrayLookup (Bvector_EqDec eta) a b); intuition.\n      rewrite <- H4.\n      simpl.\n      rewrite H8.\n      prog_simp.\n      eapply comp_spec_ret; simpl in *; intuition.\n      intuition; subst.\n      rewrite eqb_refl in H7.\n      discriminate.\n\n      rewrite <- H4.\n      simpl.\n      rewrite H8.\n      prog_inline_l.\n      prog_inline_r.\n      comp_skip.\n      prog_simp.\n      eapply comp_spec_ret; simpl in *; intuition.\n      case_eq (eqbBvector z0 b); intuition.\n      intuition. subst.\n      rewrite eqb_refl in H7.\n      discriminate.\n      intuition.\n\n      (* Prove that once the oracle goes bad, it stays bad. *)\n      eapply RF_Encrypt_bad_preserved.\n      eapply H5.\n      trivial.\n\n      intuition.\n      eapply RF_Encrypt_bad_preserved.\n      eapply H5.\n      trivial.\n\n      (* prove that the invariant holds on the initial state *)\n      intuition.\n      simpl.\n      case_eq (eqbBvector z0 x); intuition.\n      apply eqbBvector_sound in H5; intuition.\n\n      (* prove that the bad events are the same *)\n      trivial.\n      \n      intuition.\n      prog_simp.\n      eapply comp_spec_ret; simpl in *; intros.\n      destruct p1; simpl in *; subst.\n      intuition.\n      inversion H6; clear H6; subst.\n      intuition.\n      subst.\n      trivial.\n      inversion H6; clear H6; subst.\n      intuition.\n      subst.\n      trivial.\n\n      Unshelve.\n      eauto.\n    Qed.\n    \n    Theorem G2_4_5_badness_same : \n      Pr[x <-$ G2_4; ret (snd x)] == Pr[x <-$ G2_5; ret (snd x)].\n\n      pose proof @RF_Encrypt_bad_wf as RF_Encrypt_bad_wf.\n      pose proof @RF_Encrypt_bad_preserved as RF_Encrypt_bad_preserved.\n      unfold G2_4, G2_5.\n      do 4 (inline_first; comp_skip; comp_simp).\n      inline_first.\n\n      inline_first.\n\n      eapply comp_spec_impl_eq.\n      eapply comp_spec_seq; eauto with inhabited.\n      \n      eapply (@oc_comp_spec_eq_until_bad _ _ _ _ _ _ _ _ _ _ _ _ _ \n        (fun a => snd a) (fun a => snd a)\n        (fun a b => forall z,  z <> x -> arrayLookup _ (fst a) z = arrayLookup _ (fst b) z)).\n      intuition.\n      intuition.\n\n      intuition.\n      simpl in *; subst.\n      clear H2.\n      comp_skip.\n      (* The theorem from before would be helpful here *)\n      unfold PRFE_RandomFunc, randomFunc.\n      case_eq (eqbBvector x b); intuition.\n\n      prog_irr_l.\n      destruct (arrayLookup (Bvector_EqDec eta) a b); wftac.\n      prog_irr_r.\n      destruct ( arrayLookup (Bvector_EqDec eta) a0 b); wftac.\n      prog_simp.\n      eapply comp_spec_ret; simpl in *; intuition.\n      rewrite orb_true_r in H9.\n      discriminate.\n      rewrite orb_true_r in H9.\n      discriminate.\n      \n      case_eq (arrayLookup (Bvector_EqDec eta) a b); intuition.\n      rewrite <- H4.\n      rewrite H7.\n      prog_simp.\n      eapply comp_spec_ret; simpl in *; intuition.\n      intuition; subst.\n      rewrite eqbBvector_complete in H6.\n      discriminate.\n      rewrite <- H4.\n      rewrite H7.\n      prog_inline_l.\n      prog_inline_r.\n      comp_skip.\n      prog_simp.\n      eapply comp_spec_ret; simpl in *; intuition.\n      case_eq (eqbBvector z b); intuition.\n      intuition; subst.\n      rewrite eqbBvector_complete in H6.\n      discriminate.\n\n      intros.\n      destruct c.\n      destruct b.\n      eauto.\n      trivial.\n\n      intros.\n      destruct c.\n      destruct b.\n      eapply RF_Encrypt_bad_preserved .\n      eauto.\n      trivial.\n\n      intuition.\n      simpl.\n      case_eq ( eqbBvector z x); intuition.\n      apply eqbBvector_sound in H5; intuition.\n      \n      trivial.\n\n      intuition.\n      prog_simp.\n      clear H2.\n      eapply comp_spec_ret; simpl in *; intuition.\n      subst.\n      trivial.\n      destruct p1; simpl in *.\n      subst; intuition.\n\n      Unshelve.\n      eauto.\n    Qed.\n    \n      Theorem RF_Encrypt_bad_prob : \n        forall x (a : list (Bvector eta * Bvector eta)) (b : Plaintext),\n          (Pr  [d <-$ RF_Encrypt_bad x (a, false) b; ret snd (snd d) ] <= 1 / (2 ^ eta))%rat.\n\n        intuition.\n        unfold RF_Encrypt_bad.\n        \n        assert ( Pr \n   [d <-$\n    (r <-$ { 0 , 1 }^eta;\n     z <-$ PRFE_RandomFunc a r;\n     [pad, s0]<-2 z; ret (r, b xor pad, (s0, false || eqb x r)));\n    ret snd (snd d) ] ==\n    Pr \n   [r <-$ { 0 , 1 }^eta;\n     ret eqb x r] ).\n\n        inline_first.\n        comp_skip.\n        inline_first.\n        comp_irr_l.\n        eapply randomFunc_wf; wftac.\n        comp_simp.\n        simpl; intuition.\n\n        rewrite H. clear H.\n        (* dist_compute isn't working for some reason *)\n        Local Transparent evalDist.\n        simpl.\n        Local Opaque evalDist.\n\n        rewrite (@sumList_exactly_one _ x).\n        rewrite eqbBvector_complete.\n        destruct (EqDec_dec bool_EqDec true true ); intuition.\n        rewrite ratMult_1_r.\n        eapply leRat_refl.\n        eapply getAllBvectors_NoDup.\n        eapply in_getAllBvectors.\n        intuition.\n        destruct ( EqDec_dec bool_EqDec (eqbBvector x b0) true); intuition.\n        apply eqbBvector_sound in e; subst; intuition.\n        eapply ratMult_0_r.\n      Qed.\n\n    Theorem G2_4_bad_small : Pr[x <-$ G2_4; ret snd x] <= q2 / (2 ^ eta).\n      \n      pose proof @RF_Encrypt_wf as RF_Encrypt_wf.\n      pose proof @RF_Encrypt_bad_prob as RF_Encrypt_bad_prob.\n      pose proof @RF_Encrypt_bad_preserved as RF_Encrypt_bad_preserved.\n      unfold G2_4.\n      inline_first;\n      comp_irr_l; wftac.\n      inline_first;\n      comp_irr_l; wftac.\n      eapply oc_comp_wf; intuition.\n      comp_simp.\n      dist_inline_l.\n      comp_irr_l; wftac.\n      comp_inline_l; comp_irr_l; wftac.\n      comp_inline_l.\n      \n      assert ( Pr \n   [a <-$\n    (A2 s (x, (if x0 then p0 else p) xor x1))\n      (list (Bvector eta * Bvector eta) * bool)%type\n      (pair_EqDec\n         (list_EqDec (pair_EqDec (Bvector_EqDec eta) (Bvector_EqDec eta)))\n         bool_EqDec) (RF_Encrypt_bad x) ((x, x1) :: l, false);\n    x2 <-$ ([b', o]<-2 a; ret (eqb x0 b', snd o)); ret snd x2 ]  ==\n    Pr \n   [a <-$\n    (A2 s (x, (if x0 then p0 else p) xor x1))\n      (list (Bvector eta * Bvector eta) * bool)%type\n      (pair_EqDec\n         (list_EqDec (pair_EqDec (Bvector_EqDec eta) (Bvector_EqDec eta)))\n         bool_EqDec) (RF_Encrypt_bad x) ((x, x1) :: l, false);\n   ret (snd (snd a))] ).\n\n      comp_skip.\n      comp_simp.\n      simpl.\n      intuition.\n      match goal with [H4:_ |- _ ] => rewrite H4; clear H4 end.\n      \n      eapply leRat_trans.\n\n      eapply RndInAdaptive_prob; eauto.\n\n      \n      intros.\n      destruct a.\n      simpl in *; subst.\n      eapply RF_Encrypt_bad_prob.\n\n      intuition.\n      eapply RF_Encrypt_bad_preserved.\n      eauto.\n      trivial.\n\n      eapply eqRat_impl_leRat.\n      rewrite <- ratMult_num_den.\n      eapply eqRat_terms.\n      lia.\n      unfold posnatMult, natToPosnat, posnatToNat.\n      lia.\n    Qed.\n\n    Theorem G2_4_5_close : \n      forall z, \n      | evalDist (x <-$ G2_4; ret fst x) z - evalDist (x <-$ G2_5; ret fst x) z | <=\n        q2 / (2 ^ eta).\n\n      intuition.\n      eapply leRat_trans.\n      eapply fundamental_lemma_h.\n      eapply G2_4_5_badness_same.\n      eapply G2_4_5_eq_until_bad.\n      eapply G2_4_bad_small.\n    Qed.\n\n    Theorem G2_5_G3_equiv :\n      Pr[x <-$ G2_5; ret fst x] == Pr[G3].\n\n      unfold G2_5, G3.\n      intuition.\n      inline_first.\n      comp_at comp_inline leftc 1%nat.\n      comp_swap_l.\n      comp_skip.\n      comp_simp.\n      comp_swap_r.\n      comp_skip.\n      comp_inline_l.\n      comp_skip.\n      inline_first; comp_skip.\n      inline_first.\n      eapply comp_spec_impl_eq.\n      eapply comp_spec_seq; eauto with inhabited.\n      eapply (@oc_comp_spec_eq _ _ _ _ _ _ _ _ _ _ _ _ _ _ (fun a b => fst a = b)); intuition.\n      simpl in *; subst.\n      unfold RF_Encrypt.\n      comp_skip.\n      comp_skip.\n      eapply comp_spec_ret; simpl in *; intuition.\n      \n      intuition.\n      simpl in *; subst.\n      prog_simp.\n      eapply comp_spec_ret; simpl in *; intuition.\n  \n    Qed.    \n  \n   Theorem G2_G3_close : \n    | Pr[G2] - Pr[G3] | <= q1 / (2 ^ eta) + q2 / (2 ^ eta).\n\n     rewrite G2_1_equiv.\n     rewrite G2_1_2_equiv.\n     eapply ratDistance_le_trans.\n     eapply G2_2_3_close.\n     rewrite G2_3_4_equiv.\n     rewrite <- G2_5_G3_equiv.\n     eapply G2_4_5_close.\n   Qed.\n\n   (* Step 4 : apply one-time pad argument to replace ciphertext with random values *)\n   Definition G4 :=\n    [a, o] <-$2 A1 _ _ (RF_Encrypt) nil;\n    [p0, p1, s_A] <-3 a;\n    b <-$ {0, 1};\n    pb <- if b then p1 else p0;\n      r <-$ {0, 1}^eta;\n      pad <-$ {0, 1}^eta;\n      c <- (r, pad);\n      [b', o] <-$2 (A2 s_A c) _ _ RF_Encrypt o;\n      ret (eqb b b').\n\n    (* Put the game into the form expected by the argument. *)\n    Definition G3_1 :=\n    [a, o] <-$2 A1 _ _ (RF_Encrypt) nil;\n    [p0, p1, s_A] <-3 a;\n    b <-$ {0, 1};\n    pb <- if b then p1 else p0;\n      r <-$ {0, 1}^eta;\n      pad <-$ (x <-$ {0, 1}^eta; ret (pb xor x));\n      c <- (r, pad);\n      [b', o] <-$2 (A2 s_A c) _ _ RF_Encrypt o;\n      ret (eqb b b').\n\n    Theorem G3_G3_1_equiv:\n      Pr[G3] == Pr[G3_1].\n\n      unfold G3, G3_1. \n\n      repeat (comp_simp;\n        inline_first;\n        comp_skip).\n    Qed.\n\n    Theorem G3_1_G4_equiv:\n      Pr[G3_1] == Pr[G4].\n\n      unfold G3_1, G4.\n      do 4 (comp_skip;\n      comp_simp).\n      apply xor_OTP_eq.\n      reflexivity.\n    Qed.\n\n    Theorem G3_G4_equiv : \n      Pr[G3] == Pr[G4].\n\n      rewrite G3_G3_1_equiv.\n      eapply G3_1_G4_equiv.\n\n    Qed.\n\n    (* Step 5: Move the coin toss to the end to produce a game that that the adversary obviously wins with probability 1/2. *)\n    Definition G5 :=\n    [a, o] <-$2 A1 _ _ (RF_Encrypt) nil;\n    [p0, p1, s_A] <-3 a;\n    r <-$ {0, 1}^eta;\n    pad <-$ {0, 1}^eta;\n    c <- (r, pad);\n    [b', o] <-$2 (A2 s_A c) _ _ RF_Encrypt o;\n    b <-$ {0, 1};\n    ret (eqb b b').\n\n    Theorem G4_G5_equiv : \n      Pr[G4] == Pr[G5].\n\n      unfold G4, G5.\n      do 3 (comp_skip; comp_simp; comp_swap_l).\n      comp_skip; comp_simp.\n      reflexivity.\n    Qed.\n\n    (* Show that the probability of the adversary winning G5 is 1/2 *)\n    Theorem G5_one_half : \n      Pr[G5] == 1/2.\n\n      pose proof @RF_Encrypt_wf as RF_Encrypt_wf.\n      unfold G5.\n      \n      comp_irr_l.\n      eapply oc_comp_wf; intuition.\n \n      comp_simp.\n      \n      do 3 (comp_irr_l; wftac).\n      eapply oc_comp_wf; intuition.\n\n      comp_simp.\n      \n      Transparent evalDist.\n      Transparent getSupport.\n\n      dist_compute.\n\n      Opaque evalDist.\n      Opaque getSupport.\n      \n    Qed.\n\n    Theorem PRFE_IND_CPA_concrete : \n      IND_CPA_SecretKey_Advantage PRFE_KeyGen PRFE_Encrypt A1 A2 _ <=\n      PRF_Advantage ({0, 1}^eta) ({0, 1}^eta) f _ _ PRF_A' +\n      (q1 / 2^eta + q2 / 2^eta).\n\n      unfold IND_CPA_SecretKey_Advantage.\n      rewrite G1_equiv.      \n      eapply ratDistance_le_trans.\n      eapply eqRat_impl_leRat.\n      eapply G1_G2_close.\n\n      eapply leRat_trans.\n      eapply ratDistance_le_trans.\n      eapply G2_G3_close.\n      eapply eqRat_impl_leRat.\n      rewrite <- ratIdentityIndiscernables.\n      rewrite G3_G4_equiv.\n      rewrite G4_G5_equiv.\n      eapply G5_one_half.\n      eapply eqRat_impl_leRat.\n      symmetry.\n      eapply ratAdd_0_r.\n    Qed.\n    \n    (* Concrete cost of executing the constructed adversary *)\n    Context `{function_cost_model}.\n    Local Open Scope nat_scope.\n\n    Variable A1_cost : nat -> nat.\n    Hypothesis A1_cost_correct : oc_cost cost (comp_cost cost) A1 A1_cost.\n    Variable A2_cost_1 : nat.\n    Hypothesis A2_cost_1_correct : cost (fun p => A2 (fst p) (snd p)) A2_cost_1.\n    Variable A2_cost_2 : nat -> nat.\n    Hypothesis A2_cost_correct : forall x y, oc_cost cost (comp_cost cost) (A2 x y) A2_cost_2.\n\n    Theorem PRFE_Encrypt_OC_cost_1 : \n        cost PRFE_Encrypt_OC 0.\n\n        Transparent PRFE_Encrypt_OC.\n        unfold PRFE_Encrypt_OC.\n        eapply cost_const.     \n      Qed.\n\n      Theorem PRFE_Encrypt_OC_cost_2 : \n        forall x, cost (PRFE_Encrypt_OC x) (2 * eta).\n\n        intuition.\n        Transparent PRFE_Encrypt_OC.\n        unfold PRFE_Encrypt_OC.\n        eapply cost_le.\n        eapply cost_compose_binary; costtac.\n        eapply cost_uncurry_1.\n        eapply cost_compose_binary; costtac.\n        eapply cost_uncurry_1.\n        eapply cost_compose_unary; costtac.\n        eapply cost_compose_unary; costtac.\n        eapply cost_compose_binary; costtac.\n        eapply cost_compose_binary; costtac.\n        eapply cost_compose_binary; costtac.\n        eapply cost_uncurry_1.\n        eapply cost_BVxor.\n        intuition.\n        eapply cost_uncurry_2.\n        eapply cost_BVxor.\n\n        lia.\n       \n      Qed.\n\n      Theorem PRFE_Encrypt_OC_oc_cost : \n         forall (x : unit) (y : Bvector eta),\n           oc_cost cost (comp_cost cost) (PRFE_Encrypt_OC x y) (fun x => x + 3*eta).\n\n        intuition.\n        eapply oc_cost_le.\n        unfold PRFE_Encrypt_OC.\n        costtac.\n        eapply cost_compose_binary; costtac.\n        eapply cost_uncurry_1.\n        eapply cost_compose_unary; costtac.\n        eapply cost_compose_unary; costtac.\n        eapply cost_compose_binary; costtac.\n        eapply cost_compose_binary; costtac.\n        eapply cost_uncurry_2.\n        eapply cost_BVxor.\n        intuition.\n        costtac.\n\n        eapply cost_compose_unary; costtac.\n        eapply cost_compose_unary; costtac.\n        eapply cost_compose_binary; costtac.\n        eapply cost_uncurry_2.\n        eapply cost_BVxor.\n        eapply cost_pair_2.\n        intuition.\n        costtac.\n\n        intuition.\n      Qed.  \n\n    Theorem PRF_A'_cost : \n      oc_cost cost (comp_cost cost) PRF_A' \n       (fun x => (A1_cost (x + (5 * eta))) + (A2_cost_2 (x + (5 * eta))) + \n        x + 5 * A2_cost_1 + 6 + 7 * eta).\n\n      pose proof @PRFE_Encrypt_OC_cost_2 as PRFE_Encrypt_OC_cost_2.\n      pose proof @PRFE_Encrypt_OC_oc_cost as PRFE_Encrypt_OC_oc_cost.\n      unfold PRF_A'.\n\n      eapply oc_cost_le.\n\n      costtac.\n      eauto.\n      \n      eapply PRFE_Encrypt_OC_cost_1.\n      eapply PRFE_Encrypt_OC_cost_2.\n      eapply PRFE_Encrypt_OC_oc_cost.\n      \n      costtac.\n      eapply cost_compose_binary; costtac.\n      eapply cost_uncurry_1.\n      eapply cost_compose_binary; costtac.\n      eapply cost_uncurry_1.\n      eapply cost_compose_binary; costtac.\n      eapply cost_uncurry_1.\n      eapply cost_compose_binary; costtac.\n\n      eapply (@cost_compose _ _ _ _ _ \n        (fun a => (snd (fst (fst (fst a)))))\n        (fun (a : Plaintext * Plaintext * State * unit * bool * Bvector eta *\n            Vector.t bool eta) => (OC_Run\n        unit_EqDec\n        (pair_EqDec (Bvector_EqDec eta) (Bvector_EqDec eta))\n        (Bvector_EqDec eta)\n        (A2 (snd (fst (fst (fst (fst a)))))\n           (snd (fst a),\n           (if snd (fst (fst a))\n            then snd (fst (fst (fst (fst (fst a)))))\n            else fst (fst (fst (fst (fst (fst a)))))) xor \n           snd a)) \n        PRFE_Encrypt_OC ))\n        ); costtac.\n      \n\n      eapply (@cost_compose_unary _ _ _ _ _ \n        (fun a : (Plaintext * Plaintext * State * unit * bool * Bvector eta *\n            Vector.t bool eta) => (A2 (snd (fst (fst (fst (fst a)))))\n           (snd (fst a),\n           (if snd (fst (fst a))\n            then snd (fst (fst (fst (fst (fst a)))))\n            else fst (fst (fst (fst (fst (fst a)))))) xor \n           snd a)))\n\n        (fun x => \n           OC_Run unit_EqDec\n        (pair_EqDec (Bvector_EqDec eta) (Bvector_EqDec eta))\n        (Bvector_EqDec eta) x PRFE_Encrypt_OC)\n        ).\n      \n      eapply cost_compose_binary; costtac.\n      eapply cost_compose_binary; costtac.\n      eapply cost_compose_binary; costtac.\n      eapply cost_if_bool; costtac.\n      eapply cost_uncurry_1.\n      eapply cost_BVxor.\n      eapply cost_uncurry_2.\n      eapply cost_BVxor.\n\n      eapply cost_uncurry_1.\n      eauto.\n      eapply cost_uncurry_2.\n      eauto.\n\n      eapply (@cost_compose _ _ _ _ _ \n        (fun x => _)\n        ( OC_Run unit_EqDec\n        (pair_EqDec (Bvector_EqDec eta) (Bvector_EqDec eta))\n        (Bvector_EqDec eta))\n        ); costtac.\n\n      eapply cost_OC_Run_1.\n      intuition.\n      eapply cost_OC_Run_2.\n      intuition.\n      eapply cost_OC_Run_3.\n\n      eapply cost_uncurry_1.\n      eapply cost_compose_unary; costtac.\n      eapply cost_compose_binary; costtac.\n\n      eapply cost_uncurry_1.\n      eapply cost_eqb_bool.\n      eapply cost_uncurry_2.\n      eapply cost_eqb_bool.\n\n      intuition.\n      costtac.\n      eapply cost_vec_head.\n      intuition.\n      costtac.\n      \n      eapply cost_compose_binary; costtac.\n      eapply cost_uncurry_1.\n      eapply cost_compose_binary; costtac.\n      eapply cost_uncurry_1.\n      eapply cost_compose_binary; costtac.\n      simpl.\n      \n\n      eapply (@cost_compose _ _ _ _ _ \n        (fun a => _)\n        (fun a0 : bool * Bvector eta * Vector.t bool eta =>\n      OC_Run unit_EqDec (pair_EqDec (Bvector_EqDec eta) (Bvector_EqDec eta))\n        (Bvector_EqDec eta)\n        (A2 b0 (snd (fst a0), (if fst (fst a0) then b1 else a) xor snd a0))\n        PRFE_Encrypt_OC)\n\n        ); costtac.\n      \n      eapply (@cost_compose _ _ _ _ _ \n        (fun a => _)\n        (fun a0 : bool * Bvector eta * Vector.t bool eta =>\n      OC_Run unit_EqDec (pair_EqDec (Bvector_EqDec eta) (Bvector_EqDec eta))\n        (Bvector_EqDec eta)\n        (A2 b0 (snd (fst a0), (if fst (fst a0) then b1 else a) xor snd a0)))\n\n        ); costtac.\n      \n      eapply cost_compose_binary; costtac.\n      eapply cost_compose_binary; costtac.\n      eapply cost_if_bool; costtac.\n      eapply cost_uncurry_1.\n      eapply cost_BVxor.\n      intuition.\n      eapply cost_uncurry_2.\n      eapply cost_BVxor.\n      eapply cost_uncurry_2.\n      eauto.\n      eapply cost_OC_Run_1.\n      intuition.\n      eapply cost_OC_Run_2.\n      intuition.\n      eapply cost_OC_Run_3.\n      eapply cost_uncurry_1.\n      eapply cost_compose_unary; costtac.\n      eapply cost_compose_binary; costtac.\n      eapply cost_uncurry_1.\n      eapply cost_eqb_bool.\n      intuition.\n      eapply cost_uncurry_2.\n      eapply cost_eqb_bool.\n\n      intuition.\n      costtac.\n      eapply cost_compose_binary; costtac.\n      eapply cost_uncurry_1.\n      eapply cost_compose_binary; costtac.\n      simpl.\n      \n      eapply (@cost_compose _ _ _ _ _ \n        (fun a => _)\n        (fun a0 : Bvector eta * Vector.t bool eta =>\n      OC_Run unit_EqDec (pair_EqDec (Bvector_EqDec eta) (Bvector_EqDec eta))\n        (Bvector_EqDec eta)\n        (A2 b0 (fst a0, (if y then b1 else a) xor snd a0)) PRFE_Encrypt_OC)\n        ); costtac.\n      \n      eapply (@cost_compose _ _ _ _ _ \n        (fun a => _)\n        (fun a0 : Bvector eta * Vector.t bool eta =>\n      OC_Run unit_EqDec (pair_EqDec (Bvector_EqDec eta) (Bvector_EqDec eta))\n        (Bvector_EqDec eta)\n        (A2 b0 (fst a0, (if y then b1 else a) xor snd a0)))\n        ); costtac.\n      \n      eapply cost_compose_binary; costtac.\n      eapply cost_uncurry_2.\n      eapply cost_BVxor.\n      eapply cost_uncurry_2.\n      eauto.\n      eapply cost_OC_Run_1.\n      intuition.\n      eapply cost_OC_Run_2.\n      intuition.\n      eapply cost_OC_Run_3.\n\n      intuition.\n      costtac.\n      eapply cost_compose_binary; costtac.\n      simpl.\n      eapply (@cost_compose _ _ _  _ _ \n        (fun a => _)\n         (fun a0 : Vector.t bool eta =>\n      OC_Run unit_EqDec (pair_EqDec (Bvector_EqDec eta) (Bvector_EqDec eta))\n        (Bvector_EqDec eta) (A2 b0 (y0, (if y then b1 else a) xor a0))\n        PRFE_Encrypt_OC)\n        ); costtac.\n      \n      eapply (@cost_compose _ _ _  _ _ \n        (fun a => _)\n         (fun a0 : Vector.t bool eta =>\n      OC_Run unit_EqDec (pair_EqDec (Bvector_EqDec eta) (Bvector_EqDec eta))\n        (Bvector_EqDec eta) (A2 b0 (y0, (if y then b1 else a) xor a0))\n        )\n        ); costtac.\n\n      eapply cost_uncurry_2.\n      eapply cost_BVxor.\n      eapply cost_pair_2.\n      eapply cost_uncurry_2.\n      eauto.\n      eapply cost_OC_Run_1.\n      intuition.\n      eapply cost_OC_Run_2.\n      intuition.\n      eapply cost_OC_Run_3.\n      intuition.\n      costtac.\n      simpl.\n      eauto.\n      \n      eapply PRFE_Encrypt_OC_cost_1.\n      eapply PRFE_Encrypt_OC_cost_2.\n      eapply PRFE_Encrypt_OC_oc_cost.\n\n      eapply cost_uncurry_2.\n      eapply cost_eqb_bool.\n      \n      intuition.\n      costtac.\n\n      intuition.\n\n      simpl.\n      repeat rewrite plus_0_r.\n\n      (* lia can't handle the functions -- remove them *)\n      assert (A1_cost (eta + eta + (x + (eta + (eta + eta)))) =\n        A1_cost (x + (eta + (eta + (eta + (eta + eta)))))).\n      f_equal; lia.\n      rewrite H0.\n      clear H0.\n      remember ( A1_cost (x + (eta + (eta + (eta + (eta + eta)))))) as t1.\n      assert (A2_cost_2 (eta + eta + (x + (eta + (eta + eta)))) = \n        A2_cost_2 (x + (eta + (eta + (eta + (eta + eta)))))).\n      f_equal; lia.\n      rewrite H0.\n      clear H0.\n      remember (A2_cost_2 (x + (eta + (eta + (eta + (eta + eta)))))) as t2.\n      lia.\n    Qed.\n      \n  End PRF_Encryption_IND_CPA_concrete.\n\nEnd PRF_Encryption_concrete.\n\nRequire Import Asymptotic.\n\nSection PRF_Encryption.\n\n  Context `{function_cost_model}.\n\n  Local Open Scope nat_scope.\n  \n  Variable f : forall n, Bvector n -> Bvector n -> Bvector n.\n\n  Section PRF_Encryption_IND_CPA.\n\n    Variable State : nat -> Set.\n    Variable A1 : forall n, OracleComp (Plaintext n) (Ciphertext n) (Plaintext n * Plaintext n * State n).\n    Variable A2 : forall n, State n -> Ciphertext n -> OracleComp (Plaintext n) (Ciphertext n) bool.\n\n    Hypothesis A1_admissible : \n      admissible_oc cost _ _ _ A1.\n\n    Hypothesis A2_admissible : \n      admissible_oc_func_2 cost _ _ _ _ _ A2.\n\n    Theorem PRFE_Encrypt_OC_poly_time : \n      poly_time_nonuniform_oc_func_2 cost _ _ _ _ _ PRFE_Encrypt_OC.\n\n      unfold poly_time_nonuniform_oc_func_2.\n      exists (fun x o => o + 3*x).\n      exists (fun x => 2 * x).\n      intuition.\n\n      eapply polynomial_plus; intuition.\n      eapply polynomial_mult.\n      eapply polynomial_const.\n      eapply polynomial_ident.\n\n      eapply polynomial_mult.\n      eapply polynomial_const.\n      eapply polynomial_ident.\n\n      eapply cost_le.\n      eapply cost_curry.\n      eapply (PRFE_Encrypt_OC_cost_1 n).\n      eapply (@PRFE_Encrypt_OC_cost_2 n); eauto.\n      lia.\n\n      eapply PRFE_Encrypt_OC_oc_cost; intuition.\n\n    Qed.\n\n    Theorem PRFE_Encrypt_wf : \n       forall n x (y : Bvector n), well_formed_oc (PRFE_Encrypt_OC x y).\n\n      intuition.\n      econstructor.\n      econstructor.\n      wftac.\n      intuition.\n      econstructor.\n      econstructor.\n      intuition.\n      econstructor.\n      wftac.\n\n    Qed.\n\n    Theorem PRF_A'_wf : \n      forall n, well_formed_oc (PRF_A' (A1 n) (@A2 n)).\n\n      intuition.\n      econstructor.\n      econstructor.\n      eapply A1_admissible.\n      eapply PRFE_Encrypt_wf.\n      intuition.\n      econstructor.\n      econstructor.\n      wftac.\n      intuition.\n      econstructor.\n      econstructor.\n      wftac.\n      intuition.\n      econstructor.\n      econstructor.\n      intuition.\n      econstructor.\n      econstructor.\n      simpl.\n      eapply A2_admissible.\n      intuition.\n      eapply PRFE_Encrypt_wf.\n      intuition.\n      econstructor.\n      wftac.\n\n    Qed.\n  \n    Theorem PRF_A'_poly_time : \n      poly_time_nonuniform_oc cost _ _ _ (fun n => PRF_A' (A1 n) (@A2 n)).\n\n      intuition.\n      unfold PRF_A'.\n      unfold poly_time_nonuniform_oc.\n\n      destruct (PRFE_Encrypt_OC_poly_time).\n      destruct H0.\n      unfold admissible_oc in *.\n      unfold admissible_oc_func_2 in *.\n      intuition.\n      destruct H0.\n      destruct H2.\n      destruct H2.\n      intuition.\n\n      exists (fun x o : nat =>\n     x1 x (o + 5 * x) + x2 x (o + 5 * x) + o + 5 * (x3 x) + 6 +\n     7 * x).\n\n      intuition.\n      eapply polynomial_plus.\n      eapply polynomial_plus.\n      eapply polynomial_plus.\n      eapply polynomial_plus.\n      eapply polynomial_plus.\n      eapply H6.\n      eapply polynomial_plus; intuition.\n      eapply polynomial_mult.\n      eapply polynomial_const.\n      eapply polynomial_ident.\n      eapply H0.\n      eapply polynomial_plus; intuition.\n      eapply polynomial_mult.\n      eapply polynomial_const.\n      eapply polynomial_ident.\n      intuition.\n      eapply polynomial_mult.\n      eapply polynomial_const.\n      intuition.\n      eapply polynomial_const.\n      eapply polynomial_mult.\n      eapply polynomial_const.\n      eapply polynomial_ident.\n\n      eapply oc_cost_le.\n      eapply PRF_A'_cost;\n      eauto.\n      eapply H12.\n      intuition.\n      eapply H12.\n      intuition.\n     \n    Qed.\n\n    Theorem PRFE_Encrypt_OC_qam : \n      forall n x (y : Bvector n), queries_at_most (PRFE_Encrypt_OC x y) 1.\n\n      intuition.\n      unfold PRFE_Encrypt_OC.\n      econstructor.\n      econstructor.\n      econstructor.\n      intuition.\n      econstructor.\n      econstructor.\n      intuition.\n      econstructor.\n\n      lia.\n\n    Qed.\n\n    Theorem PRF_A'_poly_queries : \n      polynomial_queries_oc _ _ _ \n      (fun n  => PRF_A' (A1 n) (@A2 n)).\n\n      unfold admissible_oc, admissible_oc_func_2 in *.\n      intuition.\n      destruct H5.\n      destruct H6.\n      intuition.\n      exists (fun n => x n + (1 + x0 n)).\n      intuition.\n      eapply polynomial_plus; intuition.\n      eapply polynomial_plus; intuition.\n      eapply polynomial_const.\n\n      eapply qam_le.\n      econstructor.\n      econstructor.\n      eauto.\n      intuition.\n\n      eapply PRFE_Encrypt_OC_qam.\n      \n      intuition.\n      econstructor.\n      econstructor.\n      econstructor.\n      intuition.\n      econstructor.\n      econstructor.\n      intuition.\n      econstructor.\n      econstructor.\n      intuition.\n      econstructor.\n      econstructor.\n      econstructor.\n      eapply H8.\n      eapply le_refl.\n      eapply le_refl.\n      intuition.\n      eapply PRFE_Encrypt_OC_qam.\n      intuition.\n      econstructor.\n\n      lia.\n\n    Qed.\n    \n    Theorem PRF_A'_admissible : \n      admissible_oc cost _ _ _ (fun n => PRF_A' (A1 n) (@A2 n)).\n\n      unfold admissible_oc.\n      intuition.\n      eapply PRF_A'_wf.\n      eapply PRF_A'_poly_time.\n      eapply PRF_A'_poly_queries.\n      \n    Qed.\n\n  End PRF_Encryption_IND_CPA. \n\n      \n  Theorem PRFE_IND_CPA : \n    PRF _ _ _ Rnd Rnd f _ _ (admissible_oc cost) -> \n    IND_CPA_SecretKey (fun n => pair_EqDec (Bvector_EqDec n) (Bvector_EqDec n))\n    PRFE_KeyGen (fun n => PRFE_Encrypt (@f n))\n    (admissible_oc cost)\n    (admissible_oc_func_2 cost).\n\n    unfold IND_CPA_SecretKey.\n    intuition.\n\n    destruct H1.\n    destruct H2.\n    intuition.\n    unfold polynomial_queries_oc, polynomial_queries_oc_func_2 in *.\n    destruct H7.\n    destruct H8.\n    intuition.\n\n    eapply negligible_le.\n    intuition.\n    eapply PRFE_IND_CPA_concrete.\n    eauto.\n    eauto.\n    eauto.\n    eauto.\n    eauto.\n\n    eapply negligible_plus.\n    eapply H0.\n    apply PRF_A'_admissible; eauto.\n\n    unfold admissible_oc; intuition.\n    econstructor; eauto.\n    unfold admissible_oc_func_2; intuition.\n    econstructor; eauto.\n\n    eapply negligible_plus.\n    eapply negligible_poly_num; intuition.\n    eapply negligible_poly_num; intuition.\n  Qed.\n\n  (*Print Assumptions PRFE_IND_CPA.*)\n\nEnd PRF_Encryption.\n\n\n\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/examples/PRF_Encryption_IND_CPA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6651048254498969}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Crypto.Util.ZUtil.Notations.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma land_same_r : forall a b, (a &' b) &' b = a &' b.\n  Proof.\n    intros a b; apply Z.bits_inj'; intros n H.\n    rewrite !Z.land_spec.\n    case_eq (Z.testbit b n); intros;\n      rewrite ?Bool.andb_true_r, ?Bool.andb_false_r; reflexivity.\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/Land.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984215, "lm_q2_score": 0.7341195210831258, "lm_q1q2_score": 0.6651048186363848}}
{"text": "Require Import String.\nRequire Import Coq.Structures.Equalities.\nRequire Import Coq.MSets.MSetInterface.\nRequire Import Arith.\nRequire Import Setoid.\nRequire Import SystemF.\nRequire Import Coq.Program.Equality.\nRequire Import Disjointness.\n\nModule MTyping\n       (Import VarTyp : UsualDecidableTypeFull)\n       (Import set : MSetInterface.S).\n  \nModule MDisjointness := MDisjointness(VarTyp)(set).\nExport MDisjointness.\n\n(* Well-formed types *)\n\nInductive WFTyp : context TyEnvSource -> PTyp -> Prop := \n  | WFInt : forall Gamma, WFEnv Gamma -> WFTyp Gamma PInt\n  | WFFun : forall Gamma t1 t2, WFTyp Gamma t1 -> WFTyp Gamma t2 -> WFTyp Gamma (Fun t1 t2)\n  | WFAnd : forall Gamma t1 t2, WFTyp Gamma t1 -> WFTyp Gamma t2 -> Ortho Gamma t1 t2 -> WFTyp Gamma (And t1 t2)\n  | WFVar : forall Gamma x ty, List.In (x,TyDis ty) Gamma -> WFEnv Gamma -> WFTyp Gamma (PFVarT x)\n  | WFForAll : forall L Gamma d t,\n                 (forall x, not (In x L) -> WFTyp (extend x (TyDis d) Gamma) (open_typ_source t (PFVarT x))) ->\n                 PType d ->\n                 WFTyp Gamma (ForAll d t)\n  | WFTop : forall Gamma, WFEnv Gamma -> WFTyp Gamma Top\n  | WFRec : forall Gamma l t, WFTyp Gamma t -> WFTyp Gamma (Rec l t).\n\nHint Constructors WFTyp.\n\nInductive Dir := Inf | Chk.\n\n(* bidirection type-system (algorithmic): \n\nT |- e => t ~> E     (inference mode: infers the type of e producing target E) (use Inf)\nT |- e <= t ~> E     (checking mode: checks the type of e producing target E) (use Chk)\n\nInspiration for the rules:\n\nhttps://www.andres-loeh.de/LambdaPi/LambdaPi.pdf\n\n *)\n\nInductive has_type_source_alg : context TyEnvSource -> PExp -> Dir -> PTyp -> (SExp var) -> Prop :=\n  (* Inference rules *)\n  | ATyTop : forall Gamma, WFEnv Gamma -> has_type_source_alg Gamma PUnit Inf Top (STUnit _)\n  | ATyVar : forall Gamma x ty, WFEnv Gamma -> List.In (x,TermV ty) Gamma -> WFTyp Gamma ty ->\n                      has_type_source_alg Gamma (PFVar x) Inf ty (STFVar _ x) \n  | ATyLit : forall Gamma x, WFEnv Gamma -> has_type_source_alg Gamma (PLit x) Inf PInt (STLit _ x)\n  | ATyApp : forall Gamma A B t1 t2 E1 E2,\n              has_type_source_alg Gamma t1 Inf (Fun A B) E1 ->\n              has_type_source_alg Gamma t2 Chk A E2 ->\n              has_type_source_alg Gamma (PApp t1 t2) Inf B (STApp _ E1 E2)\n  | ATyMerge : forall Gamma A B t1 t2 E1 E2,\n                has_type_source_alg Gamma t1 Inf A E1 ->\n                has_type_source_alg Gamma t2 Inf B E2 ->\n                Ortho Gamma A B ->\n                has_type_source_alg Gamma (PMerge t1 t2) Inf (And A B) (STPair _ E1 E2)\n  | ATyAnn : forall Gamma t1 A E, has_type_source_alg Gamma t1 Chk A E ->\n                         has_type_source_alg Gamma (PAnn t1 A) Inf A E\n  | ATyTApp : forall Gamma t A ty d E,\n                WFTyp Gamma A ->\n                has_type_source_alg Gamma t Inf (ForAll d ty) E ->\n                Ortho Gamma A d -> \n                has_type_source_alg Gamma (PTApp t A) Inf (open_typ_source ty A) (STTApp _ E (|A|))\n  | ATyRec : forall Gamma l t A E,\n               has_type_source_alg Gamma t Inf A E ->\n               has_type_source_alg Gamma (PRec l t) Inf (Rec l A) E\n  | ATyProjR : forall Gamma l t A E,\n                 has_type_source_alg Gamma t Inf (Rec l A) E ->\n                 has_type_source_alg Gamma (PProjR t l) Inf A E\n  (* Checking rules: TODO move ATyTLam here*)\n  | ATyLam : forall L Gamma t A B E,\n               (forall x, not (In x L) -> \n                     has_type_source_alg (extend x (TermV A) Gamma) (open_source t (PFVar x)) Chk B (open E (STFVar _ x))) ->\n               WFTyp Gamma A ->\n               has_type_source_alg Gamma (PLam t) Chk (Fun A B) (STLam _ E)\n  | ATySub : forall Gamma t A B C E,\n               has_type_source_alg Gamma t Inf A E ->\n               sub A B C ->\n               WFTyp Gamma B ->\n               has_type_source_alg Gamma t Chk B (STApp _ C E)\n  | ATyTLam : forall L Gamma t A d E,\n               PType d ->\n               (forall x, not (In x L) -> \n                     has_type_source_alg (extend x (TyDis d) Gamma)\n                                         (open_typ_term_source t (PFVarT x))\n                                         Inf\n                                         (open_typ_source A (PFVarT x))\n                                         (open_typ_term E (STFVarT x))) ->\n               has_type_source_alg Gamma (PTLam d t) Inf (ForAll d A) (STTLam _ E).\n\nHint Constructors has_type_source_alg.\n\n(** Well-formedness of types **)\n\nLemma wf_gives_wfenv : forall Gamma ty, WFTyp Gamma ty -> WFEnv Gamma.\nProof.\n  intros Gamma ty H; induction H; auto.\n  pick_fresh x.\n  assert (Ha : ~ In x L) by not_in_L x.\n  apply H0 in Ha; now inversion Ha.\nQed.\n\nHint Resolve wf_gives_wfenv.\n\nLemma wf_weaken_source : forall G E F ty,\n   WFTyp (E ++ G) ty -> \n   WFEnv (E ++ F ++ G) ->\n   WFTyp (E ++ F ++ G) ty.\nProof.\n  intros.\n  generalize dependent H0.\n  remember (E ++ G) as H'.\n  generalize dependent HeqH'.\n  generalize dependent E.\n  dependent induction H; intros; eauto.  \n  - subst; apply WFAnd.\n    apply IHWFTyp1; auto.\n    apply IHWFTyp2; auto.\n    apply ortho_weaken; auto.\n  (* Var *)\n  - subst.\n    apply WFVar with (ty := ty).\n    apply in_app_or in H.\n    inversion H.\n    apply in_or_app; left; assumption.\n    apply in_or_app; right; apply in_or_app; right; assumption.  \n    assumption.\n  (* ForAll *)\n  - apply_fresh WFForAll as x.\n    intros.\n    intros.\n    unfold open in *; simpl in *.\n    subst.\n    unfold extend; simpl.\n    rewrite app_comm_cons.\n    apply H0.\n    not_in_L x.\n    unfold extend; simpl; reflexivity.\n    rewrite <- app_comm_cons.\n    apply WFPushV.\n    auto.\n    not_in_L x.\n    not_in_L x.\n    rewrite dom_union in H8.\n    rewrite union_spec in H8.\n    inversion H8; contradiction.\n    auto.\nQed.    \n    \nLemma wf_strengthen_source : forall z U E F ty,\n  not (In z (fv_ptyp ty)) ->\n  WFTyp (E ++ ((z,U) :: nil) ++ F) ty ->\n  WFTyp (E ++ F) ty.\nProof.\n  intros.\n  remember (E ++ ((z,U) :: nil) ++ F).\n  \n  generalize dependent Heql.\n  generalize dependent E.\n  \n  induction H0; intros; auto.\n  - apply WFInt.\n    subst.\n    now apply wfenv_remove in H0.\n  - eapply WFFun.\n    subst.\n    apply IHWFTyp1; simpl in *; not_in_L z; reflexivity.\n    subst.\n    apply IHWFTyp2; simpl in *; not_in_L z; reflexivity.\n  - eapply WFAnd.\n    subst.\n    apply IHWFTyp1; simpl in *; not_in_L z; reflexivity.\n    subst.\n    apply IHWFTyp2; simpl in *; not_in_L z; reflexivity.\n    subst; eauto.\n  - subst; eapply WFVar.\n    apply in_or_app.\n    repeat apply in_app_or in H0.\n    inversion H0.\n    left; apply H2.\n    apply in_app_or in H2.\n    inversion H2.\n    inversion H3.\n    inversion H4.\n    subst.\n    exfalso; apply H; simpl.\n    left; reflexivity.\n    inversion H4.\n    auto.\n    now apply wfenv_remove in H1.\n  - subst.\n    apply_fresh WFForAll as x.\n    unfold extend in *; simpl in *; intros.\n    rewrite app_comm_cons.\n    eapply H1.\n    not_in_L x.\n    not_in_L z.\n    apply fv_open_rec_typ_source in H.\n    rewrite union_spec in H.\n    inversion H.\n    auto.\n    assert (NeqXZ : not (In x (singleton z))) by (not_in_L x).\n    simpl in H5.\n    exfalso; apply NeqXZ.\n    apply MSetProperties.Dec.F.singleton_2.\n    apply MSetProperties.Dec.F.singleton_1 in H5.\n    symmetry; assumption.\n    rewrite app_comm_cons.\n    reflexivity.\n    auto.\n  - apply WFTop.\n    subst.\n    now apply wfenv_remove in H0.\n  - eapply WFRec; subst; apply IHWFTyp; simpl in *; not_in_L z; reflexivity.\nQed.\n\nLemma wf_env_comm_source : forall E F G H ty,\n              WFTyp (E ++ F ++ G ++ H) ty ->\n              WFTyp (E ++ G ++ F ++ H) ty.\nProof.\n  intros.\n  remember (E ++ F ++ G ++ H).\n  generalize dependent Heql.\n  generalize dependent E.\n  generalize dependent F.\n  generalize dependent G.\n  dependent induction H0; intros; subst; auto.\n  - apply WFInt.\n    now apply wfenv_middle_comm.\n  - apply WFAnd; auto.\n    now apply ortho_middle_comm.\n  - eapply WFVar.\n    apply in_app_or in H0.\n    inversion H0.\n    apply in_or_app; left; apply H2.\n    apply in_or_app; right.\n    apply in_app_or in H2.\n    inversion H2.\n    apply in_or_app.\n    right; apply in_or_app; left.\n    assumption.\n    apply in_app_or in H3.\n    inversion H3.\n    apply in_or_app; auto.\n    apply in_or_app; right; apply in_or_app; auto.\n    now apply wfenv_middle_comm.\n  - apply_fresh WFForAll as x.\n    unfold extend.\n    intros.\n    simpl.\n    rewrite app_comm_cons.\n    apply H1.\n    not_in_L x.\n    unfold extend; now simpl.\n    auto.\n  - apply WFTop.\n    now apply wfenv_middle_comm in H0.\nQed.\n\nLemma wf_env_comm_extend_source : forall Gamma x y v1 v2 ty,\n              WFTyp (extend x v1 (extend y v2 Gamma)) ty ->\n              WFTyp (extend y v2 (extend x v1 Gamma)) ty.\nProof.\n  unfold extend.\n  intros.\n  rewrite <- app_nil_l with (l := ((x, v1) :: nil) ++ ((y, v2) :: nil) ++ Gamma) in H.\n  apply wf_env_comm_source in H.\n  now rewrite app_nil_l in H.\nQed. \n  \nLemma wf_weaken_extend_source_tydis : forall ty x v Gamma,\n   WFTyp Gamma ty ->\n   not (M.In x (union (dom Gamma) (fv_ptyp v))) ->                            \n   WFTyp ((x,TyDis v) :: Gamma) ty.\nProof.\n  intros.\n  induction H; eauto.\n  - apply WFInt.\n    apply WFPushV; auto.\n    not_in_L x.\n    not_in_L x.\n  - apply WFAnd; auto.\n    rewrite <- app_nil_l with (l := ((x, TyDis v) :: Gamma)).\n    change ((x, TyDis v) :: Gamma) with (((x, TyDis v) :: nil) ++ Gamma).\n    apply ortho_weaken.\n    now rewrite app_nil_l.\n  - eapply WFVar.\n    apply in_cons; apply H.\n    apply WFPushV; auto.\n    not_in_L x.\n    not_in_L x.\n  - apply_fresh WFForAll as x; cbn.\n    unfold extend in H1.\n    intros.\n    apply wf_env_comm_extend_source.\n    apply H1.\n    not_in_L y.\n    simpl; not_in_L x.\n    apply MSetProperties.Dec.F.add_iff in H0.\n    destruct H0.\n    not_in_L y.\n    not_in_L x.\n    auto.\n  - apply WFTop.\n    apply WFPushV; auto.\n    not_in_L x.\n    not_in_L x.\nQed.\n\nLemma wf_weaken_extend_source_termv : forall ty x v Gamma,\n   WFTyp Gamma ty ->\n   not (M.In x (union (dom Gamma) (fv_ptyp v))) ->                            \n   WFTyp ((x,TermV v) :: Gamma) ty.\nProof.\n  intros.\n  induction H; eauto.\n  - apply WFInt.\n    apply WFPushT; auto.\n    not_in_L x.\n  - apply WFAnd; auto.\n    rewrite <- app_nil_l with (l := ((x, TermV v) :: Gamma)).\n    change ((x, TermV v) :: Gamma) with (((x, TermV v) :: nil) ++ Gamma).\n    apply ortho_weaken.\n    now rewrite app_nil_l.\n  - eapply WFVar.\n    apply in_cons; apply H.\n    apply WFPushT; auto.\n    not_in_L x.\n  - apply_fresh WFForAll as x; cbn.\n    unfold extend in H1.\n    intros.\n    apply wf_env_comm_extend_source.\n    apply H1.\n    not_in_L y.\n    simpl; not_in_L x.\n    apply MSetProperties.Dec.F.add_iff in H0.\n    destruct H0.\n    not_in_L y.\n    not_in_L x.\n    auto.\n  - apply WFTop.\n    apply WFPushT; auto.\n    not_in_L x.\nQed.\n\nLemma wf_gives_types_source : forall Gamma ty, WFTyp Gamma ty -> PType ty.\nProof.\n  intros.\n  induction H; auto.\n  - apply_fresh PType_ForAll as x.\n    auto.\n    apply H0.\n    not_in_L x.\nQed.\n\nHint Resolve wf_gives_types_source.\n\nLemma subst_source_wf_typ_not_in :\n  forall Gamma z t u, WFEnv (subst_env Gamma z u) ->\n             WFTyp Gamma u ->\n             WFTyp Gamma t ->\n             ~ In z (fv_ptyp t) ->\n             WFTyp (subst_env Gamma z u) t.\nProof.\n  intros Gamma z t u HWFEnv HWFu HWFt HNotIn.\n  induction HWFt; auto.\n  - simpl in HNotIn; apply WFFun; [ apply IHHWFt1 | apply IHHWFt2 ];\n    auto; not_in_L z.\n  - simpl in HNotIn; apply WFAnd.\n    apply IHHWFt1; auto; not_in_L z.\n    apply IHHWFt2; auto; not_in_L z.\n    apply ortho_subst_not_in; eauto.\n  - apply WFVar with (ty := subst_typ_source z u ty); auto.\n    now apply in_persists_subst_env.\n  - rewrite <- subst_typ_source_fresh with (x := z) (u := u) (t := d).\n    apply_fresh WFForAll as x.\n    apply H0.\n    not_in_L x.\n    simpl; apply WFPushV; auto.\n    unfold not; intros HH; apply fv_subst_source in HH;\n    rewrite union_spec in HH; destruct HH as [HH | HH]; not_in_L x.\n    rewrite dom_subst_id; not_in_L x.\n    apply wf_weaken_extend_source_tydis; auto.\n    not_in_L x.\n    unfold not; intros HH; apply fv_open_rec_typ_source in HH; simpl in *.\n    rewrite union_spec in HH; destruct HH as [HH | HH].\n    not_in_L z.\n    not_in_L x.\n    apply H9; apply MSetProperties.Dec.F.singleton_iff;\n    apply MSetProperties.Dec.F.singleton_iff in HH; auto.\n    rewrite subst_typ_source_fresh.\n    auto.\n    not_in_L z; simpl; rewrite union_spec; auto.\n    not_in_L z; simpl; rewrite union_spec; auto.\n  - simpl in HNotIn; apply WFRec; apply IHHWFt; auto; not_in_L z.\nQed.\n\nLemma subst_source_wf_typ :\n  forall t z u Gamma d, not (In z (fv_ptyp u)) ->\n               MapsTo Gamma z d ->\n               WFEnv (subst_env Gamma z u) ->\n               Ortho Gamma u d ->\n               WFTyp Gamma u ->\n               WFTyp Gamma t ->\n               WFTyp (subst_env Gamma z u) (subst_typ_source z u t).\nProof.\n  intros t z u Gamma d HNotIn HMapsTo HForAll HOrtho HWFu HWFt.\n  induction HWFt; simpl; auto.\n  - apply WFAnd; auto.\n    eapply ortho_subst; eauto.\n  - assert (Ha : sumbool (x = z) (not (x = z))) by apply VarTyp.eq_dec.\n    destruct Ha as [Ha | Ha].\n    + subst; rewrite EqFacts.eqb_refl; auto.\n      apply subst_source_wf_typ_not_in; auto.\n    + apply EqFacts.eqb_neq in Ha.\n      rewrite Ha.\n      apply WFVar with (ty := subst_typ_source z u ty); auto.\n      apply in_persists_subst_env; auto.\n  - \n    apply_fresh WFForAll as x.\n    simpl in H0.\n    rewrite subst_typ_source_open_source_var.\n    apply H0.\n    not_in_L x.\n    eapply MapsTo_extend; auto.\n    not_in_L x.\n    apply WFPushV; auto.\n    unfold not; intros HH; apply fv_subst_source in HH;\n    rewrite union_spec in HH; destruct HH as [HH | HH]; not_in_L x.\n    rewrite dom_subst_id; not_in_L x.\n    rewrite <- app_nil_l with (l := (extend x (TyDis d0) Gamma)).\n    apply ortho_weaken.\n    now simpl.\n    apply wf_weaken_extend_source_tydis.\n    auto.\n    not_in_L x.\n    not_in_L x.\n    now apply wf_gives_types_source in HWFu.\n    apply subst_source_lc; auto.\n    now apply wf_gives_types_source in HWFu.\nQed.\n\nHint Resolve wf_gives_wfenv wf_weaken_source wf_gives_types_source.\n    \nDefinition body_wf_typ t d Gamma :=\n  exists L, forall x, not (In x L) ->\n            WFTyp (extend x (TyDis d) Gamma) (open_typ_source t (PFVarT x)).\n\nLemma forall_to_body_wf_typ : forall d t1 Gamma, \n  WFTyp Gamma (ForAll d t1) -> body_wf_typ t1 d Gamma.\nProof. intros. unfold body_wf_typ. inversion H; subst; eauto. Qed.\n\nLemma open_body_wf_type :\n  forall t d u Gamma, body_wf_typ t d Gamma -> Ortho Gamma u d -> WFTyp Gamma u ->\n             WFTyp Gamma (open_typ_source t u).\nProof.\n  intros. destruct H. pick_fresh y.\n  assert (Ha : not (In y x)) by not_in_L y.\n  apply H in Ha; auto.\n  rewrite <- app_nil_l with (l := Gamma).\n  apply wf_strengthen_source with (z := y) (U := TyDis d).\n  unfold not; intros HH.\n  apply fv_open_rec_typ_source in HH.\n  rewrite union_spec in HH.\n  destruct HH; not_in_L y.\n  rewrite subst_typ_source_intro with (x := y); eauto.\n  change (nil ++ ((y, TyDis d) :: nil) ++ Gamma) with (nil ++ extend y (TyDis d) Gamma).\n  assert (Ha1 : nil ++ (extend y (TyDis d) Gamma) =\n                subst_env (nil ++ (extend y (TyDis d) Gamma)) y u).\n  rewrite subst_env_codom_fresh. reflexivity.\n  not_in_L y.\n  simpl in H4; rewrite union_spec in H4; destruct H4; contradiction.\n  rewrite Ha1.\n  apply subst_source_wf_typ with (d := d); eauto.\n  not_in_L y.\n  unfold MapsTo; simpl; now rewrite EqFacts.eqb_refl.\n  rewrite <- Ha1.\n  now apply wf_gives_wfenv in Ha.\n  apply ortho_weaken.\n  auto.\n  apply wf_weaken_extend_source_tydis; auto.\n  not_in_L y.\n  not_in_L y.\nQed.\n\nLemma WFTyp_to_WFType : forall Gamma ty, WFTyp Gamma ty -> WFType (∥ Gamma ∥) (| ty |).\nProof.\n  intros Gamma ty H.\n  induction H; simpl; auto.\n  - apply wfenv_to_ok in H0.\n    apply WFType_Var; auto.\n    now apply in_persists in H.\n  - apply_fresh WFType_ForAll as x.\n    simpl in *.\n    assert (Ha : not (In x L)) by (not_in_L x).\n    apply H0 in Ha.\n    unfold extend; simpl.\n    unfold open_typ_source in Ha.\n    now rewrite open_rec_typ_eq_source in Ha.\nQed.\n\nHint Resolve WFTyp_to_WFType.\n\nEnd MTyping.", "meta": {"author": "zhiyuanshi", "repo": "intersection", "sha": "825f69cf7f70db7d0b829875f590fa38468bfad1", "save_path": "github-repos/coq/zhiyuanshi-intersection", "path": "github-repos/coq/zhiyuanshi-intersection/intersection-825f69cf7f70db7d0b829875f590fa38468bfad1/polymorphism/Proofs/RecordsTest/Typing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025423, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6649789005609767}}
{"text": "Definition sym (A:Type) (x y :A) (p:x=y) : y = x := \n\teq_ind x (fun y0 => y0=x) eq_refl y p.\n\nDefinition trans (A:Type) (x y z:A) (p1:x=y) (p2:y=z) : x = z := \n\teq_ind y (fun x0 => x=x0) p1 z p2.\n\t\nDefinition cong (A B:Type) (f:A->B) (x y:A) (p:x=y) : f x = f y := \n\teq_ind x (fun x0 => f x = f x0) eq_refl y p.\n\nDefinition P := Prop.\nDefinition T := Type.\n\nCheck (forall p:P, p ) : P.\nFail Check (forall p:T, p ) : T.\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/TPS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.664972679620348}}
{"text": "Require Import graph.\nRequire Import ZArith.\nSet Implicit Arguments.\n\nRequire Import String.\nRequire Import schorr_waite.\n\n(* may need new representation predicate storing also the address of the node? *)\n\nInductive tree :=\n  | Node : Z -> tree -> tree -> tree\n  | Leaf.\nInductive ltree :=\n  | LNode : Z -> Z -> ltree -> ltree -> ltree\n  | LLeaf.\nDefinition ltree_addr t :=\n  match t with\n    | LNode p _ _ _ => p\n    | LLeaf => 0\n  end.\n\nFixpoint rep_ltree (t : ltree) : MapPattern k k :=\n  match t with\n  | LLeaf => emptyP\n  | LNode p v l r =>\n      (constraint (p <> 0) :* p h|-> tree_node v (ltree_addr l) (ltree_addr r)\n       :* rep_ltree l :* rep_ltree r)%pattern\n  end.\n\nFixpoint isConst v t :=\n  match t with\n    | LLeaf => True\n    | LNode _ n l r => n = v /\\ isConst v l /\\ isConst v r\n  end.\n\nFixpoint mark m t :=\n  match t with\n    | LLeaf => LLeaf\n    | LNode p _ l r => LNode p m (mark m l) (mark m r)\n  end.\n\nInductive isWellMarkedPath : ltree -> Prop :=\n  | path1 : forall p l r,\n     isConst 0 l -> isWellMarkedPath r -> isWellMarkedPath (LNode p 1 l r)\n  | path2 : forall p l r,\n     isConst 3 r -> isWellMarkedPath l -> isWellMarkedPath (LNode p 2 l r)\n  | path_leaf : isWellMarkedPath LLeaf\n  .\n\nInductive isWellMarked' (q : ltree) : ltree -> Prop :=\n  | marked0 : forall p l r, isConst 0 l -> isConst 0 r ->\n       isWellMarkedPath q -> isWellMarked' q (LNode p 0 l r)\n  | marked1 : forall p l r, isConst 3 q -> isConst 0 l ->\n       isWellMarkedPath r -> isWellMarked' q (LNode p 1 l r)\n  | marked2 : forall p l r, isConst 3 r -> isConst 3 q ->\n       isWellMarkedPath l -> isWellMarked' q (LNode p 2 l r)\n  | marked_leaf : isConst 3 q -> isWellMarked' q LLeaf\n  .\n\nDefinition isWellMarked a t := isWellMarked' t a.\n\nFixpoint proj0 t :=\n  match t with\n    | LLeaf => Leaf\n    | LNode p _ l r => Node p (proj0 l) (proj0 r)\n  end.\nFixpoint mark3 t :=\n  match t with\n    | Leaf => LLeaf\n    | Node p l r => LNode p 3 (mark3 l) (mark3 r)\n  end.\n\nFixpoint restorePathPointers t q :=\n  match q with\n    | LNode p 1 l r => restorePathPointers (Node p t (proj0 l)) r\n    | LNode p 2 l r => restorePathPointers (Node p (proj0 r) t) l\n    | LNode _ _ _ _ => Leaf (* An error, I think *)\n    | LLeaf => t\n  end.\n\nFixpoint restorePointers p q :=\n  match p with\n  | LNode i 0 l r => restorePathPointers (Node i (proj0 l) (proj0 r)) q\n  | LNode i 1 l r => restorePathPointers (Node i (proj0 q) (proj0 l)) r\n  | LNode i 2 l r => restorePathPointers (Node i (proj0 r) (proj0 q)) l\n  | LNode i 3 l r => restorePathPointers (Node i (proj0 l) (proj0 r)) q\n  | LNode _ _ _ _ => Leaf (* shouldn't hit this *)\n  | LLeaf => proj0 q\n  end.\n\n(* Overall claim:\n   rule <k> $ => return; ...</k>\n         <heap>... swtree(root)(T) => swtree(root)(?T) ...</heap>\n    if isConst(0, marks(T)) /\\ isConst(3, marks(?T))\n       /\\ pointers(T) = pointers(?T) *)\n(* Loop invariant:\n   inv <heap>... swtree(p)(?TP), swtree(q)(?TQ) ...</heap>\n          /\\ isWellMarked(?TP, ?TQ)\n          /\\ pointers(T) = restorePointers(?TP, ?TQ) *)\n\nInductive schorr_waite_spec : Spec kcfg :=\n  schorr_waite_claim : forall c,\n  kcell c = kra schorr_waite_code kdot ->\n  forall t, store c ~= \"root\" s|-> KInt (ltree_addr t) ->\n  forall hframe, heap c |= rep_ltree t :* hframe ->\n    isConst 0 t ->\n  schorr_waite_spec c (fun c' => exists rest,\n          kcell c' = kra SReturnVoid rest\n          /\\ stk_equiv (stack c) (stack c')\n          /\\ functions c ~= functions c'\n          /\\ heap c' |= rep_ltree (mark 3 t) :* hframe)\n| schorr_waite_loop_claim :\n  forall c rest, kcell c = kra schorr_waite_loop rest ->\n  forall r t p q, store c ~= \"root\" s|-> r :* \"t\" s|-> t\n                  :* \"p\" s|-> KInt (ltree_addr p) :* \"q\" s|-> KInt (ltree_addr q) ->\n  isWellMarked p q ->\n  forall hframe, heap c |= rep_ltree p :* rep_ltree q :* hframe ->\n  schorr_waite_spec c (fun c' =>\n          kcell c' = rest\n          /\\ stk_equiv (stack c) (stack c')\n          /\\ functions c ~= functions c'\n          /\\ heap c' |= rep_ltree (mark3 (restorePointers p q)) :* hframe).\n\nLemma schorr_waite_proof : sound kstep schorr_waite_spec.\nstart_proving;(eapply sstep;[step_solver|]).\n\n* (* Overall goal *)\n\ngraph_run.\n\n+ (* Early exit at zero tree *)\ndestruct t; simpl in * |- *;simplify_pat_hyps.\nexfalso. \n  exfalso; tauto.\n  clear e.\n apply ddone. done_solver.\n\n+ (* With nonzero value, have nonempty tree *)\neapply dtrans.\ntrans_solver.\ninstantiate (1:=LLeaf).\nequate_maps.\n(* bash on the isWellMarked precondition *)\n  destruct t. simpl in * |- *. intuition. subst.\n  constructor. assumption. assumption. constructor.\n  constructor. simpl. constructor.\npat_solver.\n\nsimpl. intros. repeat use_graph_cfg_assumptions; simpl in * |- *.\n\neapply dstep. step_solver.\neapply ddone. done_solver.\n\nmatch goal with \n  [H : context [mark3 (restorePointers t LLeaf)] |- _] =>\n  replace (mark3 (restorePointers t LLeaf)) with (mark3 (proj0 t)) in H;\n  [replace (mark3 (proj0 t)) with (mark 3 t) in H|]\nend.\n\nassumption.\n\nclear. induction t;simpl;congruence. \n\nrevert H2. clear.\ninduction t;simpl;intuition;subst;simpl;congruence.\n\n* (* Loop goal *)\n\ngraph_run.\n\n+ (* exits loop *)\ndestruct p;simpl in *|-*;simplify_pat_hyps;subst.\ncongruence.\nclear e.\ninversion_clear H1.\n\napply ddone;done_solver.\nLemma mark_id : forall t, isConst 3 t -> mark3 (proj0 t) = t.\ninduction t;simpl;intuition;congruence.\nQed.\nrewrite mark_id by assumption.\nbreak_join;[eassumption|eassumption|equate_maps].\n\n+\n(* progress into loop, needs help seeing that p\n  is not a non-leaf tree so load can succeed *)\n\ndestruct p;simpl in n;[|congruence].\nsimpl in *|-*;simplify_pat_hyps.\n\ngraph_run.\n\n- (* in true case because mark reached 3 *)\nassert (z0 = 2) by auto with zarith.\nsubst z0; clear e.\ninversion_clear H1.\n\nsimpl Zplus.\neapply dtrans. trans_solver.\nequate_maps. instantiate (1:=(LNode z 3 p2 q)). equate_maps.\n\nLemma well_marked_from_path : forall p q,\n  isWellMarkedPath p -> isConst 3 q -> isWellMarked p q.                             intros.\ninversion_clear H;constructor;try assumption.\nQed.\napply well_marked_from_path;simpl;tauto.\n\n\npat_solver.\n\n(* Now need to finish up after passing things ... *)\nsimpl.\n\nintros. apply ddone. \nprogress decompose record H1;clear H1.\nrepeat split;try assumption.\n\nmatch goal with\n[H : context [(restorePointers p1 (LNode z 3 p2 q))] |- _] =>\nreplace (restorePointers p1 (LNode z 3 p2 q))\n   with (restorePathPointers (Node z (proj0 p2) (proj0 q)) p1)\n     in H\nend.\nassumption.\n\nclear -H6 H7 H8.\ndestruct p1;[|simpl;auto].\ninversion_clear H8;reflexivity.\n\n- (* In false case because left subtree was leaf *)\n\ndestruct p1;\n[exfalso;simpl in H4;simplify_pat_hyps;simpl in e;tauto\n|].\nsimpl in * |- *. clear e. progress simplify_pat_hyps.\n\neapply dtrans.\neapply schorr_waite_loop_claim with (q:=LLeaf);simpl.\nreflexivity.\nequate_maps. instantiate (1:=r). instantiate (1:=LNode z (z0+1) p2 q).\nequate_maps.\n\nunfold isWellMarked.\ninversion H1;subst.\nunfold isWellMarked in H1.\nconstructor;trivial.\nconstructor;trivial.\ndestruct n0;reflexivity.\n\nsimpl. pat_solver.\n\n(* Now we need to use the transitivity result *)\nsimpl.\n\nintros.\napply ddone.\nprogress decompose record H6;clear H6.\ndone_solver.\n\ninversion H1;subst;simpl in H12;assumption.\n\n- { (* Counter not 3, left not null.\n       Need to help it realize the tree exists so we\n       can load the subtree mark *)\n\ndestruct p1;[|destruct n1;reflexivity].\nsimpl in * |- *.\nsimplify_pat_hyps.\n\ngraph_run.\n(* In true branch because left subtree exists and has key zero *)\n\n- eapply dtrans.\n  eapply schorr_waite_loop_claim;simpl.\n\nreflexivity.\n\nequate_maps.\ninstantiate (1:=LNode z1 z2 p1_1 p1_2).\ninstantiate (1:=LNode z (z0+1) p2 q).\nequate_maps.\n\nunfold isWellMarked. inversion H1;subst;simpl in *|-*.\ndecompose record H11. constructor;try assumption;constructor;assumption.\ndecompose record H13. constructor;try assumption;constructor;assumption.\ndestruct n0;reflexivity.\n\npat_solver.\n\n(* Now use result *)\nsimpl in * |- *. intros. apply ddone.\nprogress decompose record H8;clear H8.\ndone_solver.\n\ninversion H1;subst;simpl in H14.\nassumption.\nassumption.\ndestruct n0;reflexivity.\n\n- (* Last case - false branch of if because left child mark not 0,\n     even though root still 3 *)\n\n(* Um, shouldn't this be impossible on a tree? *)\nexfalso.\n\ninversion H1;subst;simpl in *|-*.\ndecompose record H11. congruence.\ndecompose record H13. congruence.\ncongruence.\n}\n\nQed.\n", "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/himp/examples/ex10_schorr_waite/ex1_tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6649726705772603}}
{"text": "Module MarkedAsTypeclass.\n\n  Class Map(K V map: Type) := {\n    empty: map;\n    get: map -> K -> option V;\n    put: map -> K -> V -> map;\n  }.\n\n  Inductive GoodMap{K M: Type}{MI: Map K nat M}: M -> Prop :=\n  | GMEmpty: GoodMap empty\n  | GMAddSmall: forall k n m,\n      n < 10 ->\n      GoodMap m ->\n    GoodMap (put m k n)\n  | GMDouble: forall k n m,\n      get m k = Some n ->\n      GoodMap m ->\n      GoodMap (put m k n).\n\nEnd MarkedAsTypeclass.\n\nModule NotMarkedAsTypeclass.\n\n  Inductive MapFunctions(K V map: Type): Type :=\n  | Build_MapFunctions(empty: map)\n                      (get: map -> K -> option V)\n                      (put: map -> K -> V -> map).\n\n  Definition empty{K V map}(mf: MapFunctions K V map): map :=\n    match mf with\n    | Build_MapFunctions _ _ _ res _ _ => res\n    end.\n\n  Definition get{K V map}(mf: MapFunctions K V map): map -> K -> option V :=\n    match mf with\n    | Build_MapFunctions _ _ _ _ res _ => res\n    end.\n\n  Definition put{K V map}(mf: MapFunctions K V map): map -> K -> V -> map :=\n    match mf with\n    | Build_MapFunctions _ _ _ _ _ res => res\n    end.\n\n  Inductive GoodMap{K M: Type}{mf: MapFunctions K nat M}: M -> Prop :=\n  | GMEmpty: GoodMap (empty mf)\n  | GMAddSmall: forall k n m,\n      n < 10 ->\n      GoodMap m ->\n    GoodMap (put mf m k n)\n  | GMDouble: forall k n m,\n      get mf m k = Some n ->\n      GoodMap m ->\n      GoodMap (put mf m k n).\n\nEnd NotMarkedAsTypeclass.\n", "meta": {"author": "samuelgruetter", "repo": "counterexamples", "sha": "bb699361b12687fdc6323759745e75d3bf8720b8", "save_path": "github-repos/coq/samuelgruetter-counterexamples", "path": "github-repos/coq/samuelgruetter-counterexamples/counterexamples-bb699361b12687fdc6323759745e75d3bf8720b8/nunchaku/DependentTermParam.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6649469752776732}}
{"text": "(* This file tests:\n    forward_for_simple_bound on 64-bit long integers,\n    forward load with 64-bit integer array subscript, and\n    forward store with 64-bit integer array subscript.\n*)\n\nRequire Import VST.floyd.proofauto.\nRequire Import VST.progs.min64.\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs.  mk_varspecs prog. Defined.\n\nRequire Import ZArith.\nRequire Import List.\nImport ListNotations.\nOpen Scope Z.\n\n\nTheorem fold_min_general:\n  forall (al: list Z)(i: Z),\n  In i (al) ->\n  forall x, List.fold_right Z.min x al <= i.\nProof.\ninduction al; intros.\ninversion H.\ndestruct H.\nsubst a.\nsimpl.\napply Z.le_min_l.\nsimpl. rewrite Z.le_min_r.\napply IHal.\napply H.\nQed.\n\nTheorem fold_min:\n  forall (al: list Z)(i: Z),\n  In i (al) ->\n  List.fold_right Z.min (hd 0 al) al <= i.\nProof.\nintros.\napply fold_min_general.\napply H.\nQed.\n\nLemma Forall_fold_min:\n  forall (f: Z -> Prop) (x: Z) (al: list Z),\n    f x -> Forall f al -> f (fold_right Z.min x al).\nProof.\n intros.\n induction H0.\n simpl. auto.\n simpl.\n unfold Z.min at 1.\n destruct (Z.compare x0 (fold_right Z.min x l)) eqn:?; auto.\nQed.\n\nLemma fold_min_another:\n  forall x al y,\n    fold_right Z.min x (al ++ [y]) = Z.min (fold_right Z.min x al) y.\nProof.\n intros.\n revert x; induction al; simpl; intros.\n apply Z.min_comm.\n rewrite <- Z.min_assoc. f_equal.\n apply IHal.\nQed.\n\nLemma is_int_I32_Znth_map_Vint:\n forall i s al,\n  0 <= i < Zlength al ->\n  is_int I32 s (Znth i (map Vint al)).\nProof.\nintros. rewrite Znth_map; auto.\nQed.\n#[export] Hint Extern 3 (is_int I32 _ (Znth _ (map Vint _))) =>\n  (apply  is_int_I32_Znth_map_Vint; rewrite ?Zlength_map; lia) : core.\n\nDefinition minimum_spec :=\n DECLARE _minimum\n  WITH a: val, n: Z, al: list Z\n  PRE [ tptr tint , tlong ]\n    PROP  (1 <= n <= Int64.max_signed; Forall repable_signed al)\n    PARAMS (a; Vlong (Int64.repr n))\n    SEP   (data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a)\n  POST [ tint ]\n    PROP ()\n    RETURN (Vint (Int.repr (fold_right Z.min (hd 0 al) al)))\n    SEP   (data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a).\n\nDefinition Gprog : funspecs :=\n      ltac:(with_library prog [minimum_spec]).\n\n(* First approach from \"Modular Verification for Computer Security\",\n  proved using forward_for_simple_bound *)\n\nLemma body_min: semax_body Vprog Gprog f_minimum minimum_spec.\nProof.\nstart_function.\nassert_PROP (Zlength al = n) by (entailer!; list_solve).\nforward.  (* min = a[0]; *)\nforward_for_simple_bound n\n  (EX i:Z,\n    PROP()\n    LOCAL(temp _min (Vint (Int.repr (fold_right Z.min (Znth 0 al) (sublist 0 i al))));\n          temp _a a;\n          temp _n (Vlong (Int64.repr n)))\n    SEP(data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a)).\n* (* Prove that the precondition implies the loop invariant *)\n  entailer!!.\n* (* Prove that the loop body preserves the loop invariant *)\n forward. (* j = a[i]; *)\n forward. (* a[i] = j; *)\n assert (repable_signed (Znth i al))\n     by (apply Forall_Znth; auto; lia).\n assert (repable_signed (fold_right Z.min (Znth 0 al) (sublist 0 i al)))\n   by (apply Forall_fold_min;\n          [apply Forall_Znth; auto; lia\n          |apply Forall_sublist; auto]).\n autorewrite with sublist.\n subst POSTCONDITION; unfold abbreviate.\n rewrite (sublist_split 0 i (i+1)) by lia.\n rewrite (sublist_one i (i+1) al) by lia.\n rewrite fold_min_another.\n replace  (upd_Znth i (map Vint (map Int.repr al)) (Vint (Int.repr (Znth i al))))\n  with (map Vint (map Int.repr al))\n  by list_solve.\n forward_if.\n +\n forward. (* min = j; *)\n entailer!.\n rewrite Z.min_r; auto; lia.\n +\n forward. (* skip; *)\n entailer!.\n rewrite Z.min_l; auto; lia.\n* (* After the loop *)\n forward. (* return *)\n entailer!!.\n autorewrite with sublist.\n destruct al; simpl; auto.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/verif_min64.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6649469632500746}}
{"text": "(*===========================================================================\n    Macro for multiplication by a constant\n  ===========================================================================*)\nRequire Import ssreflect ssrbool ssrnat eqtype seq fintype.\nRequire Import procstate procstatemonad bitsrep bitsops bitsprops bitsopsprops.\nRequire Import SPred septac spec spectac safe basic basicprog program.\nRequire Import instr instrsyntax instrcodec instrrules reader pointsto cursor basic macros.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(* Generate a sequence that computes r1 + r2*m with result in r1 and r2 trashed *)\nOpen Scope instr_scope.\n(*=add_mulc *)\nFixpoint add_mulc nbits (r1 r2: Reg) (m: nat) :=\n  if nbits is nbits'.+1\n  then if odd m\n       then ADD r1, r2;; SHL r2, 1;; add_mulc nbits' r1 r2 m./2\n       else SHL r2, 1;;              add_mulc nbits' r1 r2 m./2\n  else prog_skip.\n(*=End *)\n\n(*=add_mulcCorrect *)\nLemma add_mulcCorrect nbits : forall (r1 r2: Reg) m, m < 2^nbits ->\n  |-- Forall v, Forall w,\n      basic\n      (r1 ~= v ** r2 ~= w ** OSZCP?)\n      (add_mulc nbits r1 r2 m)\n      (r1 ~= addB v (mulB w (fromNat m)) ** r2? ** OSZCP?).\n(*=End *)\nProof.\n  induction nbits => r1 r2 m LT; rewrite /add_mulc; fold add_mulc; specintros => v w.\n\n  (* nbits = 0 *)\n  destruct m => //. autorewrite with bitsHints push_at.\n  apply: basic_roc_post; last apply basic_skip.\n  rewrite /stateIsAny. sbazooka.\n\n  (* nbits != 0 *)\n  have H: m./2 < 2 ^nbits.\n  rewrite expnS mul2n in LT.\n  rewrite -(odd_double_half m) in LT.\n  rewrite -ltn_double.\n  apply (ltn_addl (odd m)) in LT.\n  by rewrite -(ltn_add2l (odd m)).\n\n  autorewrite with push_at.\n\n  case ODD: (odd m).\n\n(* lsb is 1 *)\n  (* ADD r1, r2 *)\n  basicapply ADD_RR_ruleNoFlags.\n  basicapply SHL_RI_rule => //.\n  try_basicapply IHnbits => //.\n\n  rewrite /iter -addBA shlB_asMul -mulB_muln mul2n.\n  rewrite -{2}(odd_double_half m).\n  by rewrite ODD mulB_addn mulB1.\n\n  basicapply SHL_RI_rule => //.\n  try_basicapply IHnbits => //.\n\n  by rewrite /iter shlB_asMul -mulB_muln mul2n -{2}(odd_double_half m) ODD add0n.\nQed.\n\n\n(* More efficient version that does multi-bit shifts *)\nFixpoint add_mulcAux nbits (c:nat) (r1 r2: Reg) (m: nat) : program :=\n  (if nbits is nbits'.+1\n  then if odd m\n       then\n         if c == 0\n         then ADD r1, r2;; add_mulcAux nbits' 1 r1 r2 m./2\n         else SHL r2, c;; ADD r1, r2;; add_mulcAux nbits' 1 r1 r2 m./2\n       else add_mulcAux nbits' c.+1 r1 r2 m./2\n  else prog_skip)%asm.\n\nLemma add_mulcAuxCorrect nbits : forall (c:nat) (r1 r2: Reg) (m:nat),\n  c+nbits <= 32 ->\n  m < 2^nbits ->\n  |-- Forall v, Forall w,\n  basic\n  (r1 ~= v ** r2 ~= w)\n  (add_mulcAux nbits c r1 r2 m)\n  (r1 ~= addB v (w *# (m*2^c)) ** r2?) @ OSZCP?.\nProof.\n  induction nbits => c r1 r2 m LT1 LT3;\n  rewrite /add_mulcAux; fold add_mulcAux; specintros => v w.\n\n  (* nbits = 0 *)\n  destruct m => //. autorewrite with bitsHints push_at.\n  apply: basic_roc_post; last apply basic_skip.\n  rewrite /stateIsAny. sbazooka.\n\n  (* nbits != 0 *)\n  have H: m./2 < 2 ^nbits.\n  rewrite expnS mul2n in LT3.\n  rewrite -(odd_double_half m) in LT3.\n  rewrite -ltn_double.\n  apply (ltn_addl (odd m)) in LT3.\n  by rewrite -(ltn_add2l (odd m)).\n\n  autorewrite with push_at.\n\n  case ODD: (odd m).\n\n(* lsb is 1 *)\n\n  case ZERO: (c == 0).\n  (* c is 0 *)\n\n  (* ADD r1, r2 *)\n  basicapply ADD_RR_ruleNoFlags.\n\n  basicapply IHnbits => //.\n  rewrite (eqP ZERO).  rewrite expn0 muln1 expn1.\n  rewrite muln2. rewrite -{2}(odd_double_half m) ODD.  rewrite mulB_addn mulB1. rewrite -> addBA.\n  sbazooka.\n\n  rewrite (eqP ZERO) add0n in LT1. by rewrite add1n.\n\n  (* c is not 0 *)\n\n  (* SHL r2, c *)\n  basicapply SHL_RI_rule => //.\n\n  (* ADD r1, r2 *)\n  basicapply ADD_RR_ruleNoFlags.\n\n  basicapply IHnbits => //.\n\n  rewrite expn1 -{2}(odd_double_half m) ODD. rewrite muln2. rewrite -addBA.\n  rewrite mulnDl mul1n. rewrite mulB_addn. rewrite mulnC.\n  rewrite shlB_mul2exp mulB_muln. sbazooka.\n\n  rewrite add1n. rewrite -addn1 addnA addn1 addnC in LT1.\n  apply (ltn_addr c) in LT1. by rewrite -(ltn_add2r c).\n\n  rewrite -(addn1) addnA addn1 in LT1.\n  apply (ltn_addr nbits) in LT1. by rewrite -(ltn_add2r nbits).\n\n\n\n(* lsb is 0 *)\n\n  basicapply IHnbits => //.\n  rewrite expnS.\n  rewrite -{2}(odd_double_half m) ODD add0n.\n  rewrite mulnA. rewrite muln2.\n  sbazooka.\n  by rewrite -(addn1 c) -addnA add1n.\nQed.\n\n(* Now a peephole optimization, using LEA for special cases *)\nDefinition add_mulcOpt (r1 r2: NonSPReg) (m:nat) : program :=\n  (if m == 2\n  then LEA r1, [r1 + r2*2]\n  else\n  if m == 4\n  then LEA r1, [r1 + r2*4]\n  else\n  if m == 8\n  then LEA r1, [r1 + r2*8]\n  else add_mulcAux 32 0 r1 r2 m)%asm.\n\nLemma add_mulcOptCorrect (r1 r2: NonSPReg) (m:nat):\n  m < 2^32 ->\n  |-- Forall v, Forall w,\n  basic\n  (r1 ~= v ** r2 ~= w)\n  (add_mulcOpt r1 r2 m)\n  (r1 ~= addB v (w *# m) ** r2?) @ OSZCP?.\nProof.\nrewrite /add_mulcOpt.\nmove => LT. specintros => v w.\nautorewrite with push_at.\n\ncase EQ2: (m == 2).\n\nbasicapply LEA_ruleSameBase => //.\nrewrite /eval.scaleBy shlB_asMul. rewrite -> addB0. rewrite /stateIsAny (eqP EQ2).\nsbazooka.\n\ncase EQ4: (m == 4).\n\nbasicapply LEA_ruleSameBase => //.\nrewrite /eval.scaleBy !shlB_asMul. rewrite -> addB0. rewrite /stateIsAny (eqP EQ4) -mulB_muln.\nreplace (2*2) with 4 by done. sbazooka.\n\ncase EQ8: (m == 8).\nbasicapply LEA_ruleSameBase => //.\nrewrite /eval.scaleBy !shlB_asMul. rewrite -> addB0. rewrite /stateIsAny (eqP EQ8) -!mulB_muln.\nreplace (2*_) with 8 by done. sbazooka.\n\ntry_basicapply add_mulcAuxCorrect => //.\nby rewrite expn0 muln1.\nQed.\n\n\n(* More efficient version that does multi-bit shifts.\n   Also with clever use of LEA where possible, iterated *)\n(*=add_mulcFast *)\nFixpoint gen nb (c:nat) (r1:Reg) (r2: NonSPReg) m :=\n  if nb is nb'.+1\n  then if odd m then\n    match c with\n    | 0 => ADD r1, r2;;             gen nb' 1 r1 r2 m./2\n    | 1 => LEA r1, [r1 + r2*2];;    gen nb' 2 r1 r2 m./2\n    | 2 => LEA r1, [r1 + r2*4];;    gen nb' 3 r1 r2 m./2\n    | 3 => LEA r1, [r1 + r2*8];;    gen nb' 4 r1 r2 m./2\n    | _ => SHL r2, c;; ADD r1, r2;; gen nb' 1 r1 r2 m./2\n    end else                        gen nb' c.+1 r1 r2 m./2\n  else prog_skip.\nDefinition add_mulcFast (r1:Reg) (r2: NonSPReg) (d:DWORD) :=\n  gen 32 0 r1 r2 (toNat d).\n(*=End *)\n\nLemma genCorrect nbits : forall (c:nat) (r1:Reg) (r2:NonSPReg) (m:nat),\n  c+nbits <= 32 ->\n  m < 2^nbits ->\n  |-- Forall v, Forall w,\n  basic\n  (r1 ~= v ** r2 ~= w)\n  (gen nbits c r1 r2 m)\n  (r1 ~= addB v (w *# (m*2^c)) ** r2?) @ OSZCP?.\nProof.\n  induction nbits => c r1 r2 m LT1 LT3;\n  rewrite /gen; fold gen; specintros => v w.\n  autorewrite with push_at.\n\n  (* nbits = 0 *)\n  destruct m => //. autorewrite with bitsHints.\n  apply: basic_roc_post; last apply basic_skip.\n  rewrite /stateIsAny. sbazooka.\n\n  (* nbits != 0 *)\n  have H: m./2 < 2 ^nbits.\n  rewrite expnS mul2n in LT3.\n  rewrite -(odd_double_half m) in LT3.\n  rewrite -ltn_double.\n  apply (ltn_addl (odd m)) in LT3.\n  by rewrite -(ltn_add2l (odd m)).\n\n  autorewrite with push_at.\n\n  case ODD: (odd m).\n\n(* lsb is 1 *)\n\n  destruct c.\n  (* c is 0 *)\n\n  (* ADD r1, r2 *)\n\n  basicapply ADD_RR_ruleNoFlags.\n\n  try_basicapply IHnbits => //.\n  rewrite expn0 muln1 expn1.\n  rewrite muln2. rewrite -{2}(odd_double_half m) ODD. by rewrite mulB_addn mulB1; rewrite -> addBA.\n\n  destruct c.\n\n  (* c is 1 *)\n  basicapply LEA_ruleSameBase.\n  rewrite -> addB0. rewrite /eval.scaleBy shlB_asMul.\n\n  try_basicapply IHnbits => //.\n  rewrite expn1 -{2}(odd_double_half m) ODD. rewrite muln2. rewrite -addBA.\n  replace (2^2) with (2*2) by done. rewrite mulnA. rewrite -mulB_addn. rewrite !muln2.\n  rewrite -(odd_double_half m). by rewrite ODD mulB_addn.\n\n  destruct c.\n\n  (* c is 2 *)\n  basicapply LEA_ruleSameBase.\n  rewrite -> addB0. rewrite /eval.scaleBy shlB_asMul.\n\n  try_basicapply IHnbits => //.\n  rewrite shlB_asMul.\n  rewrite -addBA. rewrite <-mulBA. rewrite <- (mulBDr w).\n  rewrite 3!expnS expn0 muln1 mulnA.\n  rewrite fromNat_mulBn. rewrite fromNat_addBn. rewrite mulnA. rewrite -mulnDl.\n  replace (2+m./2 * 2 *2) with (true*2 + m./2 * 2 * 2) by done.\n  rewrite -mulnDl.\n  rewrite -ODD. rewrite !muln2. rewrite -> (odd_double_half m).\n  rewrite -!muln2. by rewrite mulnA.\n\n  destruct c.\n\n  (* c is 3 *)\n  basicapply LEA_ruleSameBase.\n  rewrite -> addB0. rewrite /eval.scaleBy !shlB_asMul.\n\n  try_basicapply IHnbits => //.\n  rewrite -addBA. rewrite <-!mulBA. rewrite <- (mulBDr w).\n  rewrite 4!expnS expn0 muln1 mulnA.\n  rewrite 2!fromNat_mulBn. rewrite fromNat_addBn. rewrite 2!mulnA. rewrite -mulnDl.\n  rewrite 2!mulnA.\n  rewrite -mulnDl.\n  replace (2+m./2 * 2 *2) with (true*2 + m./2 * 2 * 2) by done.\n  rewrite -mulnDl.\n  rewrite -ODD. rewrite !muln2. rewrite -> (odd_double_half m).\n  rewrite -!muln2. by rewrite mulnA.\n\n  (* c is something else *)\n\n  (* SHL r2, c *)\n  basicapply SHL_RI_rule => //.\n\n  (* ADD r1, r2 *)\n  basicapply ADD_RR_ruleNoFlags.\n\n  try_basicapply IHnbits => //.\n  rewrite expn1 -{2}(odd_double_half m) ODD. rewrite muln2. rewrite -addBA.\n  rewrite mulnDl mul1n. rewrite mulB_addn. rewrite mulnC.\n  by rewrite shlB_mul2exp mulB_muln.\n\n  rewrite -(add1n nbits) in LT1.\n  apply: leq_trans LT1.\n  rewrite -{1}(add0n (1+nbits)). by rewrite leq_add2r.\n  apply: leq_trans LT1.\n  rewrite -addn1. by rewrite leq_add2l.\n(* lsb is 0 *)\n\n  basicapply IHnbits.\n  rewrite expnS.\n  rewrite -{2}(odd_double_half m) ODD add0n.\n  rewrite mulnA. rewrite muln2.\n  sbazooka.\n  by rewrite -(addn1 c) -addnA add1n.\n  done.\nQed.\n\nLemma add_mulcFastCorrect (r1 r2: NonSPReg) (d:DWORD):\n  |-- Forall v, Forall w,\n  basic\n  (r1 ~= v ** r2 ~= w)\n  (add_mulcFast r1 r2 d)\n  (r1 ~= addB v (mulB w d) ** r2?) @ OSZCP?.\nProof.\nrewrite /add_mulcFast.\nspecintros => v w.\n\nhave LT: toNat d < 2^32 by apply toNatBounded.\nautorewrite with push_at.\ntry_basicapply genCorrect => //. by rewrite expn0 muln1 toNatK.\nQed.\n\nDefinition screenWidth:DWORD := Eval compute in #160.\nEval showinstr in linearize (add_mulcFast EDI EDX screenWidth).\n", "meta": {"author": "jbj", "repo": "x86proved", "sha": "d314fa6d23c064a2be4bf686ac7da16a591fda01", "save_path": "github-repos/coq/jbj-x86proved", "path": "github-repos/coq/jbj-x86proved/x86proved-d314fa6d23c064a2be4bf686ac7da16a591fda01/src/x86/mulc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6649469608783324}}
{"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 Reals.\nRequire Import Psatz.\nRequire Import Tactiques.\nRequire Import Rbase_operations.\n\nOpen Scope R_scope.\n\nLemma Rlt_gt : forall x y : R, x < y -> y > x.\nProof.\nauto with *.\nQed.\nHint Resolve Rlt_gt: real.\n\n\nLemma Rge_minus : forall x y z : R, y <= z -> x - y >= x - z.\nProof.\nintros; lra.\nQed.\nHint Resolve Rge_minus: real.\n\n\nLemma Rlt_add_compatibility : forall x y z : R, x < y + z -> x - y < z. \nProof.\nintros; lra.\nQed.\nHint Resolve Rlt_add_compatibility: real.\n\n\nLemma Rlt_add_compatibility2 : forall x y z : R, x - z < y -> x < y + z.\nProof.\nintros; lra.\nQed.\nHint Resolve Rlt_add_compatibility2: real.\n\n\nLemma Rle_add_compatibility : forall x y z : R, x + y <= z -> x <= z - y.\nProof.\nintros; lra.\nQed.\nHint Resolve Rle_add_compatibility: real.\n\n\nLemma Rle_sub_compatibility : forall x y z : R, x <= z + y -> x - y <= z.\nProof.\nintros; lra.\nQed.\nHint Resolve Rle_sub_compatibility: real. \n\n\nLemma Rle_sub_compatibility2 : forall x y z : R, x - y <= z -> x <= z + y.\nProof.\nintros; lra.\nQed.\nHint Resolve Rle_sub_compatibility2: real.\n\n\nLemma Rlt_add_compatibility3 : forall x y z : R, x < z - y -> x + y < z.\nProof.\nintros; lra.\nQed.\nHint Resolve Rlt_add_compatibility3: real.\n\n\nLemma Rlt_sub_compatibility : forall x y z : R, x + y < z -> x < z - y.\nProof.\nintros; lra.\nQed.\nHint Resolve Rlt_sub_compatibility: real.\n\n\nLemma Rlt_add_compatibility4 : forall x y z : R, x - y < z -> x < y + z.\nProof.\nintros; lra.\nQed.\nHint Resolve Rlt_add_compatibility4: real.\n\n\nLemma Rle_sub_r : forall r r1 r2 : R, r2 <= r1 -> r - r1 <= r - r2.\nProof.\nintros; lra.\nQed.\nHint Resolve Rle_sub_r: real.\n\n\nLemma Rmult_le :\n forall r1 r2 r3 r4 : R,\n r3 >= 0 -> r2 > 0 -> r1 < r2 -> r3 < r4 -> r1 * r3 < r2 * r4.\nProof.\nintros.\napply Rle_lt_trans with (r2 * r3);\n [ apply Rmult_le_compat_r; [ apply Rge_le; auto | auto ]\n | apply Rmult_lt_compat_l; auto ].\napply Rlt_le; auto.\nQed.\nHint Resolve Rmult_le: real.\n\n\nLemma Rlt_r_O : forall r1 r2 r : R, r = 0 -> r1 < r2 + r -> r1 < r2.\nProof.\nintros.\ngeneralize H0; rewrite H; rewrite Rplus_0_r; auto.\nQed.\nHint Resolve Rlt_r_O: real. \n\n\nLemma Rlt_sub_O : forall r1 r2 : R, 0 < r1 - r2 -> r2 < r1.\nProof.\nintros; lra.\nQed.\nHint Resolve Rlt_sub_O: real.\n\n\nLemma mega_nul : forall r r1 r2 : R, 0 < r -> r1 < r * r2 -> r1 * / r < r2.\nProof.\nintros.\napply Rmult_lt_reg_l with r; [ assumption | idtac ].\nrewrite Rmult_comm; rewrite Rmult_assoc; rewrite <- Rinv_l_sym.\nrewrite RIneq.Rmult_1_r; assumption.\napply Rgt_not_eq; apply Rlt_gt; assumption.\nQed.\nHint Resolve mega_nul: real.\n\n\nLemma Rle_Rinv_monotony :\n forall r r1 r2 : R, 0 < r -> r1 <= r * r2 -> / r * r1 <= r2.\nProof.\nintros.\napply Rmult_le_reg_l with r; auto.\nrewrite <- Rmult_assoc; replace (r * / r) with 1.\nrewrite Rmult_comm; rewrite RIneq.Rmult_1_r; auto.\nrewrite Rmult_comm; apply Rinv_l_sym; apply Rgt_not_eq; apply Rlt_gt; auto.\nQed.\nHint Resolve Rle_Rinv_monotony: real. \n\n\nLemma Rlt_Rinv_l_to_r :\n forall r r1 r2 : R, 0 < r -> r1 * r < r2 -> r1 < r2 * / r.\nProof.\nintros.\napply Rmult_lt_reg_l with r; auto.\nrewrite Rmult_comm.\napply Rgt_lt.\nrewrite <- Rmult_assoc; rewrite Rmult_comm; rewrite <- Rmult_assoc;\n rewrite <- Rinv_l_sym.\nrewrite Rmult_comm; rewrite RIneq.Rmult_1_r; apply Rlt_gt; auto.\napply Rgt_not_eq; apply Rlt_gt; auto.\nQed.\nHint Resolve Rlt_Rinv_l_to_r: real.\n\n\nLemma Rmult_lt_pos_bis : forall x y : R, 0 > x -> 0 > y -> 0 < x * y.\nProof.\nintros.\nRingReplace (x * y) (- x * - y); auto with real.\napply Rmult_lt_0_compat; auto with real.\nQed.\nHint Resolve Rmult_lt_pos_bis: real.\n\n\nLemma Rinv_le : forall r r1 : R, 0 < r -> 0 < r1 -> r1 <= r -> / r <= / r1.\nProof.\nintros.\napply Rmult_le_reg_l with r1; auto.\napply Rmult_le_reg_l with r; auto.\nrewrite Rmult_comm; rewrite Rmult_assoc.\nreplace (/ r * r) with 1;\n [ idtac | apply Rinv_l_sym; apply Rgt_not_eq; apply Rlt_gt; auto ].\nreplace (r1 * / r1) with 1;\n [ idtac | apply Rinv_r_sym; apply Rgt_not_eq; apply Rlt_gt; auto ].\ndo 2 rewrite RIneq.Rmult_1_r; auto.\nQed.\nHint Resolve Rinv_le: real.\n\n\nLemma Rle_mult_inv :\n forall r r1 r2 : R, r > 0 -> r1 * r <= r2 -> r1 <= r2 * / r.\nProof.\nintros.\napply Rmult_le_reg_l with r; auto.\nrewrite <- Rmult_assoc.\nreplace (r * r2 * / r) with r2;\n [ rewrite Rmult_comm; auto\n | symmetry  in |- *; apply Rinv_r_simpl_m; apply Rgt_not_eq; auto ].\nQed.\nHint Resolve Rle_mult_inv: 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/Rbase_inegalites.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.6649312772697705}}
{"text": "Require Import Streams.\n\nPrint Stream.\n\nCoFixpoint from n := Cons n (from (n+1)).\n\nRequire Import List.\n\nPrint list.\n\nFixpoint take {A:Type} n (xs : Stream A) :=\n  match (n, xs) with\n    | (0, _) => nil\n    | (S n', Cons x xs) => x :: take n' xs\n  end.\n\nEval compute in take 10 (from 0).\nEval compute in from 0.\n\n(*\nInductive が引数のときには Fixpoint\nCoInductive が返り値のときには CoFixpoint\n *)\n\n(* Inductive MyStream (A : Type) : Type := *)\n(*   SCons : A -> MyStream A -> MyStream A. *)\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/CoInd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.6649312770361969}}
{"text": "Require Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nRequire Export Coq.Strings.String.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nDefinition beq_string x y :=\n  if string_dec x y then true else false.\n\nTheorem beq_string_refl : forall s, true = beq_string s s.\nProof.\n  intros s. unfold beq_string. destruct (string_dec s s) as [|Hs].\n  { reflexivity. }\n  { destruct Hs. reflexivity. }\nQed.\n\nTheorem beq_string_true_iff : \n  forall (x y : string), beq_string x y = true <-> x = y.\nProof.\n  intros x y. unfold beq_string. \n  destruct (string_dec x y) as [|Hs]. \n  { subst. split; reflexivity. }\n  { split. { intros H. inversion H. }\n           { intros H. subst. destruct Hs. reflexivity. }\n}\nQed. \n\nTheorem beq_string_false_iff : forall x y : string,\n  beq_string x y = false <-> x <> y.\nProof.\n  intros x y. rewrite <- beq_string_true_iff.\n  rewrite not_true_iff_false. reflexivity.\nQed.\n\nTheorem false_beq_string : \n  forall x y : string, x <> y -> beq_string x y = false.\nProof.\n  intros x y. rewrite beq_string_false_iff. intros H. apply H.\nQed.\n\nDefinition total_map (A : Type) := string -> A.\n\nDefinition t_empty {A: Type} (v : A) : total_map A :=\n  (fun _ => v).\n\nDefinition t_update {A : Type} \n  (m : total_map A) (x : string) (v : A) :=\nfun x' => if beq_string x x' then v else m x'.\n\nDefinition examplemap :=\n  t_update (t_update (t_empty false) \"foo\" true) \"bar\" true.\n\nNotation \"{ --> d }\" := (t_empty d) (at level 0).\n\nNotation \"m '&' { a --> x }\" :=\n  (t_update m a x) (at level 20).\nNotation \"m '&' { a --> x ; b --> y }\" :=\n  (t_update (m & { a --> x }) b y) (at level 20).\nNotation \"m '&' { a --> x ; b --> y ; c --> z }\" :=\n  (t_update (m & { a --> x ; b --> y }) c z) (at level 20).\nNotation \"m '&' { a --> x ; b --> y ; c --> z ; d --> t }\" :=\n    (t_update (m & { a --> x ; b --> y ; c --> z }) d t) (at level 20).\nNotation \"m '&' { a --> x ; b --> y ; c --> z ; d --> t ; e --> u }\" :=\n    (t_update (m & { a --> x ; b --> y ; c --> z ; d --> t }) e u) (at level 20).\nNotation \"m '&' { a --> x ; b --> y ; c --> z ; d --> t ; e --> u ; f --> v }\" :=\n    (t_update (m & { a --> x ; b --> y ; c --> z ; d --> t ; e --> u }) f v) (at level 20).\n\nDefinition examplemap' :=\n  { --> false } & { \"foo\" --> true ; \"bar\" --> true }.\n\nLemma t_apply_empty : forall (A : Type) (x : string) (v : A),\n  { --> v } x = v.\nProof.\n  intros A x v. unfold t_empty. reflexivity.\nQed.\n\nLemma t_update_eq : forall A (m : total_map A) x v,\n  (m & {x --> v}) x = v.\nProof.\n  intros A m x v. unfold t_update. \n  rewrite <- beq_string_refl. reflexivity.\nQed.\n\nTheorem t_update_neq : forall (X : Type) v x1 x2 (m : total_map X),\n x1 <> x2 -> (m & {x1 --> v}) x2 = m x2.\nProof.\n  intros X v x1 x2 m H. unfold t_update.\n  rewrite false_beq_string.\n  - reflexivity.\n  - apply H.\nQed.\n\nTheorem nested_ifs : \n  forall (P: bool) (A : Type) (X Y Z : A), \n    (if P then X else (if P then Y else Z)) =\n    (if P then X else Z).\nProof.\n  intros P X Y Z. destruct P; reflexivity.\nQed.\n\nTheorem t_update_shadow : forall A (m : total_map A) v1 v2 x,\n  m & {x --> v1 ; x --> v2} = m & {x --> v2}.\nProof.\n  intros A m v1 v2 x. unfold t_update.\n  extensionality i. destruct (beq_string x i); reflexivity.\nQed.\n\nLemma beq_stringP : forall x y, reflect (x = y) (beq_string x y).\nProof.\n", "meta": {"author": "scottviteri", "repo": "CoqProjects", "sha": "57ad9d6840ad3232d442861a0df3a583bef1ee62", "save_path": "github-repos/coq/scottviteri-CoqProjects", "path": "github-repos/coq/scottviteri-CoqProjects/CoqProjects-57ad9d6840ad3232d442861a0df3a583bef1ee62/LogicalFoundationsProblems/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.6649312749349665}}
{"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(*                      Evgeny Makarov, INRIA, 2007                     *)\n(************************************************************************)\n\nRequire Export Decidable.\nRequire Export NAxioms.\nRequire Import NZProperties.\n\nModule NBaseProp (Import N : NAxiomsMiniSig').\n(** First, we import all known facts about both natural numbers and integers. *)\nInclude NZProp N.\n\n(** From [pred_0] and order facts, we can prove that 0 isn't a successor. *)\n\nTheorem neq_succ_0 : forall n, S n ~= 0.\nProof.\n intros n EQ.\n assert (EQ' := pred_succ n).\n rewrite EQ, pred_0 in EQ'.\n rewrite <- EQ' in EQ.\n now apply (neq_succ_diag_l 0).\nQed.\n\nTheorem neq_0_succ : forall n, 0 ~= S n.\nProof.\nintro n; apply neq_sym; apply neq_succ_0.\nQed.\n\n(** Next, we show that all numbers are nonnegative and recover regular\n    induction from the bidirectional induction on NZ *)\n\nTheorem le_0_l : forall n, 0 <= n.\nProof.\nnzinduct n.\nnow apply eq_le_incl.\nintro n; split.\napply le_le_succ_r.\nintro H; apply le_succ_r in H; destruct H as [H | H].\nassumption.\nsymmetry in H; false_hyp H neq_succ_0.\nQed.\n\nTheorem induction :\n  forall A : N.t -> Prop, Proper (N.eq==>iff) A ->\n    A 0 -> (forall n, A n -> A (S n)) -> forall n, A n.\nProof.\nintros A A_wd A0 AS n; apply right_induction with 0; try assumption.\nintros; auto; apply le_0_l. apply le_0_l.\nQed.\n\n(** The theorems [bi_induction], [central_induction] and the tactic [nzinduct]\nrefer to bidirectional induction, which is not useful on natural\nnumbers. Therefore, we define a new induction tactic for natural numbers.\nWe do not have to call \"Declare Left Step\" and \"Declare Right Step\"\ncommands again, since the data for stepl and stepr tactics is inherited\nfrom NZ. *)\n\nLtac induct n := induction_maker n ltac:(apply induction).\n\nTheorem case_analysis :\n  forall A : N.t -> Prop, Proper (N.eq==>iff) A ->\n    A 0 -> (forall n, A (S n)) -> forall n, A n.\nProof.\nintros; apply induction; auto.\nQed.\n\nLtac cases n := induction_maker n ltac:(apply case_analysis).\n\nTheorem neq_0 : ~ forall n, n == 0.\nProof.\nintro H; apply (neq_succ_0 0). apply H.\nQed.\n\nTheorem neq_0_r : forall n, n ~= 0 <-> exists m, n == S m.\nProof.\ncases n. split; intro H;\n[now elim H | destruct H as [m H]; symmetry in H; false_hyp H neq_succ_0].\nintro n; split; intro H; [now exists n | apply neq_succ_0].\nQed.\n\nTheorem zero_or_succ : forall n, n == 0 \\/ exists m, n == S m.\nProof.\ncases n.\nnow left.\nintro n; right; now exists n.\nQed.\n\nTheorem eq_pred_0 : forall n, P n == 0 <-> n == 0 \\/ n == 1.\nProof.\ncases n.\nrewrite pred_0. now split; [left|].\nintro n. rewrite pred_succ.\nsplit. intros H; right. now rewrite H, one_succ.\nintros [H|H]. elim (neq_succ_0 _ H).\napply succ_inj_wd. now rewrite <- one_succ.\nQed.\n\nTheorem succ_pred : forall n, n ~= 0 -> S (P n) == n.\nProof.\ncases n.\nintro H; exfalso; now apply H.\nintros; now rewrite pred_succ.\nQed.\n\nTheorem pred_inj : forall n m, n ~= 0 -> m ~= 0 -> P n == P m -> n == m.\nProof.\nintros n m; cases n.\nintros H; exfalso; now apply H.\nintros n _; cases m.\nintros H; exfalso; now apply H.\nintros m H2 H3. do 2 rewrite pred_succ in H3. now rewrite H3.\nQed.\n\n(** The following induction principle is useful for reasoning about, e.g.,\nFibonacci numbers *)\n\nSection PairInduction.\n\nVariable A : N.t -> Prop.\nHypothesis A_wd : Proper (N.eq==>iff) A.\n\nTheorem pair_induction :\n  A 0 -> A 1 ->\n    (forall n, A n -> A (S n) -> A (S (S n))) -> forall n, A n.\nProof.\nrewrite one_succ.\nintros until 3.\nassert (D : forall n, A n /\\ A (S n)); [ |intro n; exact (proj1 (D n))].\ninduct n; [ | intros n [IH1 IH2]]; auto.\nQed.\n\nEnd PairInduction.\n\n(** The following is useful for reasoning about, e.g., Ackermann function *)\n\nSection TwoDimensionalInduction.\n\nVariable R : N.t -> N.t -> Prop.\nHypothesis R_wd : Proper (N.eq==>N.eq==>iff) R.\n\nTheorem two_dim_induction :\n   R 0 0 ->\n   (forall n m, R n m -> R n (S m)) ->\n   (forall n, (forall m, R n m) -> R (S n) 0) -> forall n m, R n m.\nProof.\nintros H1 H2 H3. induct n.\ninduct m.\nexact H1. exact (H2 0).\nintros n IH. induct m.\nnow apply H3. exact (H2 (S n)).\nQed.\n\nEnd TwoDimensionalInduction.\n\n\nSection DoubleInduction.\n\nVariable R : N.t -> N.t -> Prop.\nHypothesis R_wd : Proper (N.eq==>N.eq==>iff) R.\n\nTheorem double_induction :\n   (forall m, R 0 m) ->\n   (forall n, R (S n) 0) ->\n   (forall n m, R n m -> R (S n) (S m)) -> forall n m, R n m.\nProof.\nintros H1 H2 H3; induct n; auto.\nintros n H; cases m; auto.\nQed.\n\nEnd DoubleInduction.\n\nLtac double_induct n m :=\n  try intros until n;\n  try intros until m;\n  pattern n, m; apply double_induction; clear n m;\n  [solve_proper | | | ].\n\nEnd NBaseProp.\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/Natural/Abstract/NBase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.787931185683219, "lm_q1q2_score": 0.6649312749349665}}
{"text": "Require Export D.\n\nLemma evenb_S : forall n,\n    evenb (S n) = negb (evenb n).\nProof.\n  intros n. induction n as [| n'].\n  - simpl. reflexivity.\n  - rewrite IHn'. simpl. destruct (evenb n') eqn:Heq.\n    + simpl. reflexivity.\n    + simpl. reflexivity.\nQed.\n\nLemma evenb_double_true : forall n,\n    evenb (double n) = true.\nProof.\n  intros n. induction n.\n  - reflexivity.\n  - assumption.\nQed.\n    \nTheorem evenb_double_conv : forall n,\n  exists k, n = if evenb n then double k\n                else S (double k).\nProof.\n  intros. induction n.\n  - simpl. exists 0. reflexivity.\n  - destruct evenb.\n    + destruct IHn. subst. exists x. rewrite evenb_S. rewrite evenb_double_true. reflexivity.\n    + destruct IHn. subst. exists (S x). simpl. rewrite evenb_double_true. reflexivity.\nQed.\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/06/P01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545425, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.6649312708492928}}
{"text": "Require Export XR_R.\nRequire Export XR_Rle.\nRequire Export XR_total_order_T.\n\nImplicit Type r : R.\nLocal Open Scope R_scope.\n\nLemma Rle_lt_dec : forall r1 r2, {r1 <= r2} + {r2 < r1}.\nProof.\n  intros x y.\n  destruct (total_order_T x y) as [ [ hxy | heq ] | hyx ].\n  {\n    left.\n    unfold \"<=\".\n    left.\n    exact hxy.\n  }\n  {\n    subst y.\n    left.\n    unfold \"<=\".\n    right.\n    reflexivity.\n  }\n  {\n    right.\n    exact hyx.\n  }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rlt_lt_dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.6649312605767144}}
{"text": "Definition N := 12.\n\nInductive tree : Type :=\n| Leaf : tree\n| Node : nat -> tree -> tree -> tree.\n\nFixpoint binary_tree c n :=\n  match n with\n  | 0 => Leaf\n  | S n =>\n    let t := binary_tree c n in\n    Node c t t\n  end.\n\nDefinition t0 := Eval vm_compute in binary_tree 0 N.\nDefinition t1 := Eval vm_compute in binary_tree 1 N.\n", "meta": {"author": "eponier", "repo": "compare-eq", "sha": "cc2da184e747d0ad6ada8597e1ebf03377e413e2", "save_path": "github-repos/coq/eponier-compare-eq", "path": "github-repos/coq/eponier-compare-eq/compare-eq-cc2da184e747d0ad6ada8597e1ebf03377e413e2/equality_test/12/type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6649269169168872}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf1 : natural) : natural := Succ y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj257_coqofml_S0wGsT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650403, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6649269167845302}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. You may distribute   *)\n(* under the terms of either the CeCILL-B License or the CeCILL        *)\n(* version 2 License, as specified in the README file.                 *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq fintype.\nRequire Import bigops ssralg matrix poly.\n\n(*****************************************************************************)\n(* This file contains the definitions of:                                    *)\n(*  - char_poly A  : Characteristic polynomial of A                          *)\n(*  - phi : the isomorphism between the rings  M(R[X]) and M(R)[X]           *)\n(*    with R a commutative and                                               *)\n(*     M(R[X]) : matrices with coefficients in the polynomial ring of R      *)\n(*     M(R)[X] : polynomials with coefficients in the matrix ring of R       *)\n(*  - Zpoly : the injection from the polynomial ring to M(R)[X]              *)\n(* In addition to the lemmas relevant to these definitions, this file also   *)\n(* contains a proof of the Cayley-Hamilton Theorem.                          *)\n(*****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nImport GRing.Theory.\nImport Monoid.Theory.\n\nOpen Local Scope ring_scope.\n\nSection Cayley.\n\nVariable R : comRingType.\n\nVariable n : pos_nat.\n\nNotation Local nn := (pos_nat_val n) (only parsing).\nNotation Local \"'R'\" := R\n  (at level 0, format \"'R'\").\nNotation Local \"'R' [ 'X' ]\" := {poly R}\n  (at level 0, format \"'R' [ 'X' ]\").\nNotation Local \"'M' ( 'R' )\" := (matrix R nn nn)\n  (at level 0, format \"'M' ( 'R' )\").\nNotation Local \"'M' ( 'R' [ 'X' ] )\" :=\n  (matrix (poly_ringType R) nn nn)\n  (at level 0, format \"'M' ( 'R' [ 'X' ] )\").\nNotation Local \"'M' ( 'R' ) [ 'X' ]\" := {poly (matrix R n n)}\n  (at level 0, format \"'M' ( 'R' ) [ 'X' ]\").\n\n(* The characteristic polynomial *)\nOpen Scope matrix_scope.\nDefinition matrixC (A : M(R)) : M(R[X]) := \\matrix_(i, j) (A i j)%:P.\n\nDefinition char_poly (A : M(R)) : R[X] := \\det ('X%:M - matrixC A).\n\n(* The isomorhism phi : M(R[X]) <-> M(R)[X] *)\n\nDefinition phi (A : M(R[X])) : M(R)[X] :=\n  \\poly_(k < \\max_i \\max_j size (A i j)) \\matrix_(i, j) (A i j)`_k.\n\nLemma coef_phi : forall A i j k, (phi A)`_k i j = (A i j)`_k.\nProof.\nmove=> A i j k; rewrite coef_poly.\ncase: (ltnP k _) => le_m_k; rewrite mxE // nth_default //.\napply: leq_trans (leq_trans (leq_bigmax i) le_m_k); exact: (leq_bigmax j).\nQed.\n\nLemma phi_polyC : forall A, phi (matrixC A) = A%:P.\nProof.\nmove=> A; apply/polyP=> k; apply/matrixP=> i j.\nby rewrite coef_phi !mxE !coefC; case k; last rewrite /= mxE.\nQed.\n\nLemma phi_zero : phi 0 = 0.\nProof.\napply/polyP=> k; apply/matrixP=> i j.\nby rewrite coef_phi mxE !coef0 mxE.\nQed.\n\nLemma phi_add : forall (A1 A2 : M(R[X])), phi (A1 + A2) = (phi A1) + (phi A2).\nProof.\nmove=> A1 A2; apply/polyP => k; apply/matrixP=> i j.\nby rewrite coef_phi !mxE !coef_add_poly mxE !coef_phi.\nQed.\n\nLemma phi_opp : forall A, phi (- A) = - phi A.\nProof.\nmove=> A; apply/polyP=> k; apply/matrixP=> i j.\nby rewrite coef_phi mxE coef_opp mxE coef_phi coef_opp.\nQed.\n\nLemma phi_one : phi 1 = 1.\nProof.\napply/polyP=> k; apply/matrixP=> i j.\nrewrite coef_phi mxE (fun_if (fun p : {poly _} => p`_k)) coef0 !coefC.\nby case: k => [|k]; rewrite /= !mxE // if_same.\nQed.\n\nLemma phi_mul : forall (A1 A2 : M(R[X])), phi (A1 * A2) = (phi A1) * (phi A2).\nProof.\nmove=> A1 A2; apply/polyP=> k; apply/matrixP=> i j.\nrewrite !coef_phi !mxE !coef_mul summxE coef_sum.\npose F k1 k2 := (A1 i k1)`_k2 * (A2 k1 j)`_(k - k2).\ntransitivity (\\sum_k1 \\sum_(k2 < k.+1) F k1 k2); rewrite {}/F.\n  by apply: eq_bigr=> k1 _; rewrite coef_mul.\nrewrite exchange_big /=; apply: eq_bigr=> k2 _.\nby rewrite mxE; apply: eq_bigr=> k1 _; rewrite !coef_phi.\nQed.\n\n(* Writing a polynomial as a polynomial on matrices *)\n\nDefinition Zpoly (p : R[X]) : M(R)[X] := \\poly_(i < size p) (p`_i)%:M.\n\nLemma coef_Zpoly : forall p k, (Zpoly p)`_k = (p`_k)%:M.\nProof.\nmove=> p k; rewrite coef_poly; case: (ltnP k _) => // le_p_k.\nby rewrite nth_default // scalar_mx0.\nQed.\n\nLemma ZpolyX : Zpoly 'X = 'X.\nProof.\napply/polyP=> k; apply/matrixP=> i j; rewrite coef_Zpoly !coefX.\nby case: (k == _); rewrite !mxE ?if_same.\nQed.\n\nLemma phi_Zpoly : forall p, phi p%:M = Zpoly p.\nProof.\nmove=> p; apply/polyP=> k; apply/matrixP=> i j.\nby rewrite coef_phi coef_Zpoly !mxE; case: (i == j); rewrite ?coef0.\nQed.\n\n(* The theorem in three lines! *)\n\nTheorem Cayley_Hamilton : forall A, (Zpoly (char_poly A)).[A] = 0.\nProof.\nmove=> A; apply/eqP; apply/factor_theorem.\nrewrite -phi_Zpoly -mulmx_adjl phi_mul; move: (phi _) => q; exists q.\nby rewrite phi_add phi_opp phi_Zpoly phi_polyC ZpolyX.\nQed.\n\nEnd Cayley.\n", "meta": {"author": "Wassasin", "repo": "ssreflect", "sha": "45cf056aa48bec1e7e2bbb77cb4458d4bddf43e4", "save_path": "github-repos/coq/Wassasin-ssreflect", "path": "github-repos/coq/Wassasin-ssreflect/ssreflect-45cf056aa48bec1e7e2bbb77cb4458d4bddf43e4/theories/charpoly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6649269049736865}}
{"text": "Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq fintype.\nRequire Import ssralg bigops matrix.\n\nOpen Local Scope ring_scope.\nOpen Local Scope matrix_scope.\nImport GRing.Theory.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nSection GaussianElimination.\nVariable F : fieldType.\nVariables m n : nat.\nNotation Local \"''M_' ( m , n )\" := (matrix F m n) : type_scope.\nImplicit Type A B C : 'M_(m, n).\n\n(* Row Operations *)\nDefinition row_scale A i0 c :=\n \\matrix_(i, j) if i == i0 then c * A i j else A i j.\n\nDefinition row_exch A i1 i2 :=\n \\matrix_(i, j) if i == i1 then A i2 j else if i== i2 then A i1 j else A i j.\n\nDefinition row_repl A i1 i2 c :=\n \\matrix_(i, j) if i == i1 then A i j + c * A i2 j else A i j.\n\n(* RREF operations *)\n(* annihilate all element of a colum expect the pivot *)\nDefinition annihilate_col_fun i j x A :=\n if i != x then row_repl A x i (-(A x j) * (A i j)^-1) else A.\n\nLemma annihilate_col_funE : forall A i j x k l,\n  (annihilate_col_fun i j x A) k l =\n  if (i != x) && (k == x) then A k l - (A k j) * (A i j)^-1 * A i l else A k l.\nProof.\nmove=> A i j x k l; case: ifP; rewrite /annihilate_col_fun.\n  by case/andP=> ->; move/eqP<-; rewrite mxE eq_refl !mulNr.\nby case/nandP; [move/negbTE-> | case: ifP => // _; rewrite mxE; move/negbTE->].\nQed.\n\nDefinition annihilate_col A i j :=\n foldr (annihilate_col_fun i j) A (take m (enum 'I_m)).\n\nLemma annihilate_colE : forall A i j k l,\n (annihilate_col A i j) k l =\n if (k != i) then A k l - (A k j) * (A i j)^-1 * A i l else A k l.\nProof.\nmove=> /= A i j k l; rewrite /annihilate_col.\nelim: {1 4 10}m (leqnn m) (ltn_ord k) A => [// | m' Rm' Lm' Lk A].\nrewrite (take_nth k) 1?size_enum_ord // -cats1 (nth_ord_enum _ (Ordinal Lm')).\nrewrite foldr_cat /=; rewrite ltnS leq_eqVlt orbC in Lk; case/orP: Lk => Lk.\n  rewrite (Rm' (ltnW Lm')) // !annihilate_col_funE.\n  suff -> : k == Ordinal Lm' = false; first by rewrite andbF andNb.\n  apply/eqP; move/(congr1 (@nat_of_ord _)); move/eqP.\n  by rewrite /= eqn_leq andbC leqNgt Lk.\nsuff <- : k = (Ordinal Lm'); [| apply: val_inj]; rewrite /= -(eqP Lk) //{Rm' Lk}.\nelim: {-2}(val k) {m' Lm'} (leqnn k) A => /= [| k' Rk'] Lk A.\n  by rewrite take0 /= annihilate_col_funE eq_refl andbT eq_sym.\nhave Hk' : k' < m by apply (ltn_trans Lk).\nrewrite (take_nth k) 1?size_enum_ord // -cats1 foldr_cat.\nrewrite (nth_ord_enum _ (Ordinal Hk')) /=.\nhave -> : annihilate_col_fun i j (Ordinal Hk') (annihilate_col_fun i j k A) =\n annihilate_col_fun i j k (annihilate_col_fun i j (Ordinal Hk') A).\n  apply/matrixP=> ? ?; rewrite !annihilate_col_funE !andNb.\n  by case: ifP => -> //; case: ifP => ->.\nrewrite (Rk' (ltnW Lk)) !annihilate_col_funE andNb //.\nsuff -> : k == (Ordinal Hk') = false; [by rewrite andbF | apply/eqP].\nby move/(congr1 (@nat_of_ord _)) => /=; move/eqP; rewrite eqn_leq leqNgt Lk.\nQed.\n\nDefinition rref_pred (r : nat) A j :=\n let P := [pred k | forallb l : 'I_m, (r <= l < k) ==> (A l j == 0)] in\n [pred k | [&& (A k j != 0), (r <= k) & P k]].\n\nLemma rref_predP : forall r A j,\n reflect (forall x : 'I_m, r <= x -> A x j = 0) (pred0b (rref_pred r A j)).\nProof.\nmove=> /= r A j; apply: (iffP idP) => H; rewrite /rref_pred; last first.\n  apply/pred0P => /= k /=; case: (leqP r k) => rk; rewrite /= 1?andbF //.\n  by move: (H _ rk); move/eqP->.\nmove/negPn: H; rewrite negb_exists; move/forallP => H /= k.\nelim: {1}(val k) {1 3 4}k (leqnn k) => [| k' Rk'] l Hl Lrl.\n  move: (H l); move: (leq_trans Lrl Hl); move: Hl; rewrite !leqn0; move/eqP->.\n  by move/eqP => -> /=; case/nandP; [move/negPn; move/eqP | case/pred0P => ?].\nrewrite leq_eqVlt ltnS in Hl; case/orP: Hl; last by move=> ?; apply: Rk'.\nmove=> Hl; move: (H l); rewrite Lrl; case/nandP; first by move/negPn; move/eqP.\ncase/existsP => /= l'; rewrite negb_imply (eqP Hl) ltnS; case/andP.\nby case/andP => ? ?; rewrite (Rk' l') 1?eq_refl.\nQed.\n\nDefinition rref_fun (x : nat * 'M_(m, n)) (j : 'I_n) : nat * 'M_(m, n) :=\n let s_i := pick (rref_pred x.1 x.2 j) in\n if (insub x) : option {y | (x.1 < m) } is Some (exist _ Hx) then\n  if s_i is Some i then\n   let A1 := row_exch x.2 (Ordinal Hx) i in\n   let A2 := row_scale A1 (Ordinal Hx) (A1 (Ordinal Hx) j)^-1 in\n   let A3 := annihilate_col A2 (Ordinal Hx) j in\n    ((x.1).+1, A3)\n  else x\n else x.\n\n(* Compute the rref form of a given matrix and it's rank *)\nDefinition rref A j := foldl rref_fun (0%N, A) (take j (enum 'I_n)).\n\nDefinition rank A := (rref A n).1.\nDefinition rref_mx A := (rref A n).2.\n\n(* Definition of rref predicate *)\nDefinition zrow A i j := (forallb k : 'I_n, (k < j) ==> (A i k == 0)).\n\nLemma zrowP : forall A i j,\n reflect (forall k : 'I_n, k < j -> (A i k = 0)) (zrow A i j).\nProof.\nmove=> /= A i j.\napply: (iffP idP) => H; last by apply/forallP=> ?; apply/implyP; move/H->.\nby move=> /= k Hk; move/forallP: H; move/(_ k); rewrite Hk /=; move/eqP.\nQed.\n\n(* getting the pivot *)\nDefinition pivot A i j :=\n pick [pred l | [&& (A i l != 0), (l < j) & (zrow A i l)]].\n\nDefinition zrows_in_bottom A j :=\n forallb i, (zrow A i j) ==> (forallb i' : 'I_m, ((i <= i') ==> zrow A i' j)).\n\nDefinition pivot_eq1 A j :=\n forallb i, if (pivot A i j) is Some l then A i l == 1 else zrow A i j.\n\nDefinition pivot_zcol A j := forallb i,\n if (pivot A i j) is Some l then (forallb k, (k != i) ==> (A k l == 0))\n else true.\n\nDefinition pivot_mono A j := forallb i1,\n if (pivot A i1 j) is Some j1 then\n  forallb i2, if pivot A i2 j is Some j2 then (i1 < i2) ==> (j1 < j2) else true\n else true.\n\nDefinition is_rref A j :=\n [&& zrows_in_bottom A j, pivot_eq1 A j, pivot_zcol A j & pivot_mono A j].\n\nSection InvariantLemmas.\n\nLemma rank_rref_mono : forall A j j', j <= j' -> (rref A j).1 <= (rref A j').1.\nProof.\nmove=> A j; elim=> [| j' Rj']; first by rewrite leqn0; move/eqP->.\nrewrite leq_eqVlt ltnS; case/orP => Ljj'; first by move/eqP: Ljj' ->.\nrewrite (leq_trans (Rj' Ljj')) // /rref.\ncase: (leqP n j') => H; last rewrite (take_nth (Ordinal H)) 1?size_enum_ord //.\n  by rewrite !take_oversize 1?size_enum_ord 1?(leq_trans H).\nrewrite -cats1 foldl_cat /= (nth_ord_enum _ (Ordinal H)) {2}/rref_fun.\nby case: insubP => //= [] [] _ ? _ _; case: pickP => [| ?] /=.\nQed.\n\nLemma rank_rref_leq : forall A j, (rref A j).1 <= minn m j.\nProof.\nmove=> A; elim=> [| j]; rewrite /rref 1?take0 //=.\ncase: (leqP n j) => Hj.\n  rewrite !take_oversize 1?size_enum_ord 1?(leq_trans Hj) // !leq_minr.\n  by case/andP=> -> /= H; apply: (leq_trans H).\nrewrite (take_nth (Ordinal Hj)) 1?size_enum_ord // -cats1 foldl_cat /=.\nrewrite (nth_ord_enum _ (Ordinal Hj)) {2}/rref_fun /=.\ncase: insubP => //= [[] [] _ _ Hm _ _ /=| _]; last first.\n  by rewrite !leq_minr; case/andP => -> /= H; apply: (leq_trans H).\ncase: pickP => [/= k | _]; last first.\n  by rewrite !leq_minr; case/andP => -> /= H; apply: (leq_trans H).\nby case/and3P=> H1 H2 _; rewrite !leq_minr ltnS Hm; case/andP=> _ ->.\nQed.\n\nLemma rref_mx_zcols : forall A (i : 'I_m) (j : 'I_n) j',\n j < j' -> (rref A j').1 <= i -> (rref A j').2 i j = 0.\nProof.\nmove=> A i j j'; elim: j' i j => // j' Rj' i j; rewrite ltnS leq_eqVlt => Ljj'.\ncase: (leqP n j') => Hj'; first move: (Rj' i j (leq_trans (ltn_ord j) Hj')).\n  by rewrite /rref !take_oversize 1?size_enum_ord 1?(leq_trans Hj').\nrewrite /rref (take_nth j) 1?size_enum_ord // -cats1 foldl_cat.\nrewrite (nth_ord_enum _ (Ordinal Hj')) /= {1 3}/rref_fun /=.\ncase: insubP => // [[] [] _ _ H0 _ _ |]; last first.\n  by move=> H1 ?; move: H1; rewrite (leq_ltn_trans _ (ltn_ord i)).\ncase: pickP => /= [k |]; first case/and3P=> H1 H2 _; last first.\n  case/orP: Ljj' => [| ? ? ?]; last by apply: Rj'.\n  move/eqP=> jj'; move/pred0P; move/rref_predP=> H1 H2.\n  by suff -> : j = Ordinal Hj'; [apply: H1 | apply: val_inj].\nrewrite annihilate_colE !mxE eqxx mulVf // !invr1 !mulr1.\ncase: ifP; [move/negbTE=> -> H3 | by move/eqP->; rewrite ltnn].\ncase/orP: Ljj' => Ljj'; first move/eqP: Ljj' => Ljj' ; last first.\n  by rewrite !(Rj' _ j) 1?(ltnW H3) // !mulr0 oppr0 addr0 if_same.\nby suff -> : j = (Ordinal Hj'); [ rewrite mulVf // mulr1 addrN | apply: val_inj].\nQed.\n\nLemma rref_mxE : forall A i j, (rref_mx A) i j = (rref A j.+1).2 i j.\nProof.\nmove=> /= A i j; rewrite /rref_mx.\nelim: {1 5 8}n (leqnn n) j (ltn_ord j) => // n' Rn' Ln j; rewrite ltnS leq_eqVlt.\ncase/orP => [| Ljm']; last rewrite -Rn' // 1?ltnW //; first by move/eqP->.\nrewrite /rref (take_nth j) 1?size_enum_ord // -cats1 foldl_cat.\nrewrite (nth_ord_enum _ (Ordinal Ln)) /= {1}/rref_fun /=.\ncase: insubP=> //= [] [] _ H0 _ _; case: pickP => //= k; case/and3P=> H1 H2 H3.\nrewrite !annihilate_colE !mxE /= eqxx (rref_mx_zcols Ljm') // !mulr0 oppr0 addr0.\ncase: ifP; last by move/eqP->; rewrite eqxx mulr0 rref_mx_zcols.\nby move/negbTE->; case: ifP => //; move/eqP->; rewrite !rref_mx_zcols.\nQed.\n\nLemma zrow_rank_leq : forall A i j, zrow (rref_mx A) i j -> (rref A j).1 <= i.\nProof.\nmove=> /= A i; elim=> [| j]; rewrite /rref 1?take0 // => Rj Zj.\nhave : zrow (rref_mx A) i j.\n  by apply/zrowP => k Hk; move/zrowP: Zj => -> //; apply: (ltn_trans Hk).\ncase : (leqP n j) => Hj; move/Rj.\n  by rewrite !take_oversize 1?size_enum_ord // (leq_trans Hj).\nmove/zrowP: Zj; move/(_ (Ordinal Hj) (ltnSn j)); rewrite rref_mxE /rref.\nrewrite (take_nth (Ordinal Hj)) 1?size_enum_ord // -cats1 foldl_cat.\nrewrite (nth_ord_enum _ (Ordinal Hj)) /= {1 4}/rref_fun /=.\ncase: insubP => //= [] [] _ H0 _ _; case: pickP => //= l; case/and3P=> H1 H2 _.\nrewrite ltn_neqAle andbC annihilate_colE !mxE eqxx mulVf // !invr1 !mulr1.\ncase: ifP; last by move/eqP->; move/eqP; rewrite !eqxx mulVf // oner_eq0.\nby move/negbTE=> H _ -> /=; apply/eqP=> ?; case/eqP: H; apply: val_inj.\nQed.\n\nEnd InvariantLemmas.\n\nLemma zrows_in_bottom_rref : forall A n', zrows_in_bottom (rref_mx A) n'.\nProof.\nmove=> A n'; apply/forallP => /= i; apply/implyP; move/zrowP => Zrn.\napply/forallP => /= i'; apply/implyP => l_ii'; apply/zrowP=> k Hk.\nrewrite rref_mxE rref_mx_zcols 1?(leq_trans _ l_ii') //; apply: zrow_rank_leq.\nby apply/zrowP => ? ?; apply: Zrn; apply: (leq_ltn_trans _ Hk).\nQed.\n\nLemma pivot_eq1_rref : forall A n', pivot_eq1 (rref_mx A) n'.\nProof.\nmove=> A n'; apply/forallP => /= i; rewrite /pivot.\ncase: pickP => /= [j | Pz]; last apply/zrowP => j Hj; last first.\n  elim: n' j Hj Pz => // n' Rn' j Hj Pz; move: (Pz j) => /=.\n  suff -> : zrow (rref_mx A) i j; first by rewrite Hj //= andbT; move/eqP.\n  apply/zrowP=> k Hk; apply: Rn' => [| l /=]; first by rewrite (leq_trans Hk).\n  move: (Pz l); rewrite /= ltnS leq_eqVlt andb_orl andb_orr.\n  by case/norP=> _; move/negbTE.\nrewrite rref_mxE /rref; case/and3P => H1 Hj Zj; move: H1.\nrewrite (take_nth j) 1?size_enum_ord // (nth_ord_enum _ j) -cats1 foldl_cat /=.\nrewrite {1 3}/rref_fun /=; case: insubP => /= [[] [] _ _ H0 _ _|]; last first.\n  by rewrite (leq_ltn_trans _ (ltn_ord i)) => //; apply: zrow_rank_leq.\ncase: pickP => //= [k |]; last move/pred0P; last first.\n  by move/rref_predP; move/(_ i)->; rewrite 1?eq_refl //; apply: zrow_rank_leq.\ncase/and3P => H1 H2 _; rewrite annihilate_colE !mxE eqxx mulVf // !invr1 !mulr1.\nby case: ifP; [move/negbTE-> | move/eqP->]; rewrite 1?addrN eqxx 1?mulVf.\nQed.\n\nLemma pivot_zcol_rref : forall A n', pivot_zcol (rref_mx A) n'.\nProof.\nmove=> A n'; apply/forallP=> /= i; rewrite /pivot.\ncase: pickP => //= j; case/and3P => Hj1 Hj Hj2; apply/forallP=> /= k.\napply/implyP=> Hk; move: Hj1; rewrite !rref_mxE /rref.\nrewrite (take_nth j) 1?size_enum_ord // -cats1 (nth_ord_enum _ j) foldl_cat /=.\nrewrite {1 3}/rref_fun; case: insubP=> /= [[] [] _ _ H0 _ _ |]; last first.\n  by rewrite (leq_ltn_trans _ (ltn_ord i)) //; apply: zrow_rank_leq.\ncase: pickP=> /= [l |]; last move/pred0P; last first.\n  by move/rref_predP; move/(_ i)->; rewrite 1?eq_refl //; apply: zrow_rank_leq.\ncase/and3P=> H1 H2 H3; rewrite !annihilate_colE !mxE eqxx mulVf // !invr1 !mulr1.\nby case: ifP; [move/negbTE-> | move/eqP<-]; rewrite 1?addrN eqxx 1?mulVf 1?Hk.\nQed.\n\nLemma pivot_mono_rref : forall A, pivot_mono (rref_mx A) n.\nProof.\nmove=> A; apply/forallP=> /= i; rewrite /pivot.\ncase: pickP=> //= j; case/and3P=> Hj1 Hj Hj2; apply/forallP=> /= k.\ncase: pickP=> //= l; case/and3P=> Hl1 Hl Hl2; apply/implyP=> ik.\ncase: (ltngtP j l)=> // lj.\n  case/eqP: Hl1; suff : zrow (rref_mx A) k j; first by move/zrowP->.\n  apply/zrowP=> y ?; rewrite rref_mxE rref_mx_zcols 1?(leq_trans _ (ltnW ik)) //.\n  by apply: (leq_trans _ (zrow_rank_leq Hj2)); apply: rank_rref_mono.\nsuff : rref_mx A k l == 0; first by rewrite (negbTE Hl1).\nsuff <- : j = l :> 'I_n; first apply/eqP; last by apply: val_inj.\nmove: Hj1; rewrite !rref_mxE /rref (take_nth j) 1?size_enum_ord // -cats1.\nrewrite (nth_ord_enum _ j) foldl_cat /= {1 3}/rref_fun /=.\ncase: insubP=> //= [[] [] _ _ H0 _ _ |]; last first.\n  by rewrite (leq_ltn_trans _ (ltn_ord i)) //; apply: zrow_rank_leq.\ncase: pickP=> //= [l' |]; last move/pred0P; last first.\n  by move/rref_predP; move/(_ i)->; rewrite 1?eq_refl //; apply: zrow_rank_leq.\ncase/and3P=> H1 H2 H3; rewrite !annihilate_colE !mxE eqxx mulVf // !invr1 !mulr1.\nby case: ifP; [move/negbTE-> | move/eqP<-]; rewrite addrN eqxx neq_ltn orbC 1?ik.\nQed.\n\nLemma is_rref_rref : forall A, is_rref (rref_mx A) n.\nProof.\nmove=> A; rewrite /is_rref.\nby rewrite zrows_in_bottom_rref pivot_eq1_rref pivot_zcol_rref pivot_mono_rref.\nQed.\n\nLemma rank_min : forall A, rank A <= minn m n.\nProof. by move=> A; apply: rank_rref_leq. Qed.\n\nEnd GaussianElimination.\n\nSection LinearSystem.\nVariable F : fieldType.\nNotation Local \"''M_' ( m , n )\" := (matrix F m n) : type_scope.\n\nDefinition system_sol m n (A : 'M_(m, n)) (v : 'M_(m, 1)) :=\n exists u, A *m u == v.\n\n(* equivalent system lemmas : row operations preserves system solution set *)\n\n(* row_scale *)\nLemma rscale_pastemxK : forall m n (A : 'M_(m, n)) (v : 'M_(m, 1)) k c,\n (row_scale (pastemx A v) k c) = pastemx (row_scale A k c) (row_scale v k c).\nProof.\nby move=> *; apply/matrixP=> i j; rewrite !mxE; case: splitP => *; rewrite !mxE.\nQed.\n\nLemma rscale_sys_equiv : forall m n (A : 'M_(m, n)) v k c,\n let A' := (row_scale (pastemx A v) k c) in c != 0 ->\n (system_sol A v <-> (system_sol (lcutmx A') (rcutmx A'))).\nProof.\nmove=> /= m n A v k c Hc; split; case=> u; move/eqP=> Hu; exists u; apply/eqP.\n  rewrite rscale_pastemxK pastemxKl pastemxKr; apply/matrixP=> i j.\n  rewrite !mxE -{2}(mul1r (v i j)) -(fun_if ( *%R^~ (v i j))); move/matrixP: Hu.\n  move/(_ i j)<-; rewrite mxE big_distrr /=; apply: eq_bigr => /= l _.\n  by rewrite mxE -{2}(mul1r (A i l)) -(fun_if ( *%R^~ (A i l))) mulrA.\nrewrite rscale_pastemxK pastemxKl pastemxKr in Hu; apply/matrixP=> i j.\nmove/matrixP: Hu; move/(_ i j); rewrite !mxE -{2}(mul1r (v i j)).\nrewrite -(fun_if ( *%R^~ (v i j))); set c' := if i == k then c else 1.\nmove/(congr1 ( *%R c'^-1)); rewrite mulrA mulVf 1?mul1r => [<- |]; last first.\n  by rewrite /c'; case: ifP => // *; apply: nonzero1r.\nrewrite big_distrr /=; apply: eq_bigr => /= l _; rewrite !mxE.\nrewrite -{3}(mul1r (A i l)) -(fun_if ( *%R^~ (A i l))) !mulrA mulVf 1?mul1r //.\nby rewrite /c'; case: ifP => // *; apply: nonzero1r.\nQed.\n\n(* row exchange *)\nLemma rexchange_pastemxK : forall m n (A : 'M_(m, n)) (v : 'M_(m, 1)) k l,\n (row_exch (pastemx A v) k l) = pastemx (row_exch A k l) (row_exch v k l).\nProof.\nby move=> *; apply/matrixP=> i j; rewrite !mxE; case: splitP => *; rewrite !mxE.\nQed.\n\nLemma rexchange_sys_equiv : forall m n (A : 'M_(m, n)) v k l,\n let A' := (row_exch (pastemx A v) k l) in\n (system_sol A v <-> (system_sol (lcutmx A') (rcutmx A'))).\nProof.\nmove=> /= m n A v k l; split; case=> u; move/eqP=> Hu; exists u; apply/eqP.\n  rewrite rexchange_pastemxK pastemxKl pastemxKr; apply/matrixP=> i j.\n  move/matrixP: Hu => Hu; rewrite !mxE -!Hu !mxE.\n  case: ifP => Pik; first by apply: eq_bigr => x _; rewrite mxE Pik.\n  by case: ifP => Pil; apply: eq_bigr => x _; rewrite mxE Pik Pil.\nrewrite rexchange_pastemxK pastemxKl pastemxKr in Hu; apply/matrixP=> i j.\nmove/matrixP: Hu => Hu; case Pil: (i == l).\n  move: (Hu l j); rewrite !mxE (eqP Pil) eqxx; case: ifP => [Plk <- | Plk _].\n  - by apply: eq_bigr => x _; rewrite mxE Plk.\n  by move: (Hu k j); rewrite !mxE eqxx => <-; apply: eq_bigr => *; rewrite mxE eqxx.\nmove: (Hu i j); rewrite !mxE Pil; case: ifP => [Pik _ | Pik <-]; last first.\n  by apply: eq_bigr => x _; rewrite mxE Pik Pil.\nmove: (Hu l j); rewrite !mxE eqxx -(eqP Pik) eq_sym Pil => <-.\nby apply: eq_bigr => *; rewrite mxE eqxx eq_sym Pil.\nQed.\n\nLemma rrepl_pastemxK : forall m n (A : 'M_(m, n)) (v : 'M_(m, 1)) k l c,\n (row_repl (pastemx A v) k l c) = pastemx (row_repl A k l c) (row_repl v k l c).\nProof.\nby move=> *; apply/matrixP=> i j; rewrite !mxE; case: splitP => *; rewrite !mxE.\nQed.\n\nLemma rrepl_sys_equiv : forall m n (A : 'M_(m, n)) v k l c,\n let A' := (row_repl (pastemx A v) k l c) in l != k ->\n (system_sol A v <-> (system_sol (lcutmx A') (rcutmx A'))).\nProof.\nmove=> /= m n A v k l c Hkl; split; case=> u; move/eqP=> Hu; exists u; apply/eqP.\n  rewrite rrepl_pastemxK pastemxKl pastemxKr; apply/matrixP=> i j.\n  move/matrixP: Hu => Hu; rewrite !mxE -{2}(addr0 (v i j)) -{2}(mulr1 c).\n  rewrite -{2}(mulr0 c) -{2}(mul0r (v l j)) -mulrA -(fun_if ( +%R (v i j))).\n  rewrite -(fun_if ( *%R c)) -(fun_if ( *%R^~ (v l j))) -!Hu !mxE.\n  rewrite !big_distrr -big_split /=; apply: eq_bigr => x _; rewrite mxE.\n  by case: ifP => ->; rewrite ?mul0r ?mulr0 1?addr0 // mul1r mulrA mulr_addl.\nrewrite rrepl_pastemxK pastemxKl pastemxKr in Hu; apply/matrixP=> i j.\nmove/matrixP: Hu => Hu; move: (Hu i j); rewrite !mxE.\ncase: ifP => [ik | ik <-]; last by apply: eq_bigr => /= x _; rewrite mxE ik.\nmove/(congr1 ( +%R^~ (- (c * v l j)))); rewrite -addrA addrN addr0 => <-.\nmove: (Hu l j); rewrite !mxE (negbTE Hkl) => <-; rewrite big_distrr -sumr_sub /=.\napply: eq_bigr => /= *.\nby rewrite !mxE ik (negbTE Hkl) mulr_addl -addrA mulrA addrN addr0.\nQed.\n\nLemma anil_col_sys_equiv : forall m n (A : 'M_(m, n)) v k l,\n let A' := (annihilate_col (pastemx A v) k (lshift 1 l)) in\n (system_sol A v) <-> (system_sol (lcutmx A') (rcutmx A')).\nProof.\nmove=> /= m n A v k l; rewrite /annihilate_col.\nelim: {3 13 23}m A v (leqnn m) => [A v | m' Rm' A v Hm'].\n  by rewrite take0 /= pastemxKl pastemxKr.\nrewrite (take_nth (Ordinal Hm')) 1?size_enum_ord // -cats1.\nrewrite (nth_ord_enum _ (Ordinal Hm')) foldr_cat /= {2 4}/annihilate_col_fun.\ncase: ifP => [Ik | ?]; last by apply: Rm'; apply: ltnW.\nrewrite rrepl_pastemxK -Rm' 1?ltnW // !pastemxEl.\nrewrite (rrepl_sys_equiv _ _ (- A (Ordinal Hm') l / A k l) Ik) rrepl_pastemxK.\nby rewrite pastemxKl pastemxKr.\nQed.\n\nLemma rref_sys_equiv : forall m n (A : 'M_(m, n)) v,\n let A' := (rref (pastemx A v) n).2 in\n (system_sol A v) <-> (system_sol (lcutmx A') (rcutmx A')).\nProof.\nmove=> m n A v /=; elim: {1 9 14}n (leqnn n) => [| n' Rn'] Hn; rewrite /rref.\n  by rewrite take0 /= pastemxKl pastemxKr.\nmove: (Rn' (ltnW Hn)) => {Rn'} Rn'.\nhave Hn' : n' < n + 1 by apply: (ltn_trans Hn); rewrite addn1.\nrewrite (take_nth (Ordinal Hn')) 1?size_enum_ord // -cats1.\nrewrite (nth_ord_enum _ (Ordinal Hn')) foldl_cat /= {1 3}/rref_fun /=.\ncase: insubP=> //= [] [] _ H0 _ _; case: pickP => //= k; case/and3P=> Hk1 Hk Hk2.\nset A' := (rref (pastemx A v) n').2 in Rn' Hk1 Hk2 *.\nset r := (rref (pastemx A v) n').1 in H0 Hk Hk2 *.\nrewrite Rn' (rexchange_sys_equiv _ _ (Ordinal H0) k) cutmxK.\nhave Z1 : ((row_exch A' (Ordinal H0) k) (Ordinal H0) (Ordinal Hn'))^-1 != 0.\n  by rewrite mxE eqxx invr_neq0.\nrewrite (rscale_sys_equiv _ _ (Ordinal H0) Z1) cutmxK.\nrewrite (anil_col_sys_equiv _ _ (Ordinal H0) (Ordinal Hn)) cutmxK.\nby suff -> : (lshift 1 (Ordinal Hn)) = (Ordinal Hn') => //; apply: val_inj.\nQed.\n\nEnd LinearSystem.", "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/gauss_elim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.754914975839675, "lm_q1q2_score": 0.664926897754823}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Lia.\n\nFrom Undecidability.Shared.Libs.DLW.Utils Require Import utils.\nFrom Undecidability.Shared.Libs.DLW.Code Require Import subcode sss compiler.\n\nImport ListNotations.\n\n(* ** Semantic Correctness of Compiled Code *)\n\nSet Implicit Arguments.\nSet Default Goal Selector \"!\".\n\nSection comp.\n\n  (* This is an abstract proof of compiler soundness & completeness \n\n      The principle of this compiler is to map every source individual\n      instruction into a list of target instructions that simulate the\n      source instruction. We describe our assumptions later on ...\n\n    *)\n\n  Variable (X Y : Set)                                  (* X is a small type of source instructions and \n                                                           Y of destination instructions *) \n           (icomp : (nat -> nat) -> nat -> X -> list Y) (* instruction compiler w.r.t. a given linker & a position \n                                                           icomp lnk i x compiles instruction x at position i \n                                                           using linker lnk into a list of target instructions\n                                                         *)\n           (ilen  : X -> nat)                           (* compiled code length does not depend on linker or position,\n                                                           it only depends on the original instruction\n                                                           whether this assumption is strong or not is debatable\n                                                           but we only encountered cases which satisfy this assuption\n                                                         *)\n           (Hilen : forall lnk n x, length (icomp lnk n x) = ilen x)\n           (*Hilen2  : forall x, 1 <= ilen x*).           (* compiled code should not be empty, even if the source\n                                                           instruction is something like NO-OP, to ensure progress\n                                                           in the simulation as source code executes \n                                                           also not a strong requirement\n\n                                                           This can be removed because it can be deduced (where it\n                                                           is used) from Hilen & step_X_tot & Hicomp \n                                                         *)\n\n  (* Semantics for X and Y instructions *)\n\n  Variables (state_X state_Y : Type)\n            (step_X : X -> (nat*state_X) -> (nat*state_X) -> Prop)\n            (step_Y : Y -> (nat*state_Y) -> (nat*state_Y) -> Prop).\n\n  Notation \"ρ '/X/' s -1> t\" := (step_X ρ s t) (at level 70, no associativity).\n  Notation \"P '/X/' s '-[' k ']->' t\" := (sss_steps step_X P k s t) (at level 70, no associativity).\n  Notation \"P '/X/' s '-+>' t\" := (sss_progress step_X P s t) (at level 70, no associativity).\n  Notation \"P '/X/' s ->> t\" := (sss_compute step_X P s t) (at level 70, no associativity).\n  Notation \"P '/X/' s '~~>' t\" := (sss_output step_X P s t) (at level 70, no associativity).\n  Notation \"P '/X/' s ↓\" := (sss_terminates step_X P s)(at level 70, no associativity).\n\n  Notation \"ρ '/Y/' s -1> t\" := (step_Y ρ s t) (at level 70, no associativity).\n  Notation \"P '/Y/' s '-[' k ']->' t\" := (sss_steps step_Y P k s t) (at level 70, no associativity).\n  Notation \"P '/Y/' s '-+>' t\" := (sss_progress step_Y P s t) (at level 70, no associativity).\n  Notation \"P '/Y/' s ->> t\" := (sss_compute step_Y P s t) (at level 70, no associativity).\n  Notation \"P '/Y/' s '~~>' t\" := (sss_output step_Y P s t) (at level 70, no associativity).\n  Notation \"P '/Y/' s ↓\" := (sss_terminates step_Y P s)(at level 70, no associativity).\n\n  (* We assume totality of X semantics, i.e. no instruction can block the computation\n      and functionality of Y semantics \n\n      Totality is not necessary achieved ... think of a HALT instruction \n      what should we do in that case ? It should not be too difficult to\n      embed a partial model of computation into a total one by transforming\n      blocking cases into jumps at a PC value outside of the code.\n    *)\n\n  Hypothesis (step_X_tot : forall I st1, exists st2, I /X/ st1 -1> st2)\n             (step_Y_fun : forall I st st1 st2, I /Y/ st -1> st1 -> I /Y/ st -1> st2 -> st1 = st2).\n\n (* simul is an invariant: simul st_X st_Y means that st_X is simulated by st_Y *)\n\n  Variable (simul : state_X -> state_Y -> Prop).\n\n  Infix \"⋈\" := simul (at level 70, no associativity).\n\n  (* Simulation is preserved by compiled instructions \n      this of course ensures the *semantic correctness of\n      the compilation of individual instructions*\n\n      Notice the important hypothesis of preservation of the +1\n      relative address by the linker otherwise it might not be\n      possible to establish the below predicate.\n\n      If the source language involves other relative addresses like\n      +2 or +d or -d, the present compiler might have to be substantially\n      updated.\n\n      +1 is very likely to be used even implicitly because every instruction\n      that does not branch (like INC or PUSH) implicitly jumps at +1 ...\n    *) \n\n  Definition instruction_compiler_sound := forall lnk I i1 v1 i2 v2 w1, \n                     I /X/ (i1,v1) -1> (i2,v2)\n                  -> lnk (1+i1) = length (icomp lnk i1 I) + lnk i1\n                  -> v1 ⋈ w1\n       -> exists w2, (lnk i1,icomp lnk i1 I) /Y/ (lnk i1,w1) -+> (lnk i2,w2)\n                  /\\ v2 ⋈ w2.\n\n  Hypothesis Hicomp : instruction_compiler_sound.\n\n  Section correctness. \n\n    (* We assume each instruction in P is compiled in Q according to the individual \n        instruction compiler combined with what the linker says for branching. \n        This is a *syntactic correctness criterion* for the whole compiled program Q\n      *)\n\n    Variables (linker : nat -> nat) \n              (P : nat * list X) \n              (Q : nat * list Y)\n              (HPQ : forall i ρ, (i,[ρ]) <sc P \n                              -> (linker i, icomp linker i ρ) <sc Q\n                               /\\ linker (1+i) = ilen ρ + linker i).\n\n    (* From semantic correctness of individually compiled instructions and\n        syntactic correctness of the whole compiled program, we derive\n        soundness and completeness of the compiled program Q wrt the\n        source program P *)\n\n    Definition compiled_sound := forall i₁ v₁ i₂ v₂ w₁,\n                      v₁ ⋈ w₁ /\\ P /X/ (i₁,v₁) ->> (i₂,v₂)\n        -> exists w₂, v₂ ⋈ w₂ /\\ Q /Y/ (linker i₁,w₁) ->> (linker i₂,w₂).\n\n    Theorem compiler_sound : compiled_sound.\n    Proof using HPQ Hilen Hicomp.\n      intros i1 v1 i2 v2 w1.\n      change i1 with (fst (i1,v1)) at 2; change v1 with (snd (i1,v1)) at 1.\n      change i2 with (fst (i2,v2)) at 2; change v2 with (snd (i2,v2)) at 2.\n      generalize (i1,v1) (i2,v2); clear i1 v1 i2 v2.\n      intros st1 st2 (H1 & q & H2); revert H2 w1 H1.\n      induction 1 as [ (i1,v1) | q (i1,v1) (i2,v2) st3 H1 H2 IH2]; simpl; intros w1 H0.\n      + exists w1; split; auto; exists 0; constructor.\n      + destruct H1 as (k & l & I & r & v' & G1 & G2 & G3).\n        inversion G2; subst v' i1; clear G2.\n        destruct (Hicomp linker) with (1 := G3) (3 := H0)\n          as (w2 & G4 & G5).\n        * rewrite Hilen; apply HPQ; subst; exists l, r; auto.\n        * destruct (IH2 _ G5) as (w3 & G6 & G7).\n          exists w3; split; auto.\n          apply sss_compute_trans with (2 := G7); simpl.\n          apply sss_progress_compute.\n          revert G4; apply subcode_sss_progress.\n          apply HPQ; subst; exists l, r; auto.\n    Qed.\n\n    (* When still inside of P, the computation in Q simulates\n       a computation in P *)\n\n    Local Lemma compiler_complete_step p st1 w1 w3 :\n           snd st1 ⋈ snd w1\n        -> linker (fst st1) = fst w1\n        -> in_code (fst st1) P\n        -> out_code (fst w3) Q\n        -> Q /Y/ w1 -[p]-> w3\n        -> exists q st2 w2, snd st2 ⋈ snd w2\n                        /\\ linker (fst st2) = fst w2\n                        /\\ P /X/ st1 ->> st2\n                        /\\ Q /Y/ w2 -[q]-> w3\n                        /\\ q < p.\n    Proof using HPQ Hicomp Hilen step_Y_fun step_X_tot.\n      revert st1 w1 w3; intros (i1,v1) (j1,w1) (j3,w3); simpl fst; simpl snd.\n      intros H1 H2 H3 H4 H5.\n      destruct (in_code_subcode H3) as (I & HI).\n      destruct HPQ with (1 := HI) as (H6 & H7).\n      assert (out_code j3 (linker i1, icomp linker i1 I)) as G2.\n      { revert H4; apply subcode_out_code; auto. }\n      assert (H8 : ilen I <> 0).\n      { intros H.\n        destruct (step_X_tot I (i1,v1)) as ((i2,v2) & Hst).\n        apply (Hicomp linker) with (3 := H1) in Hst; auto.\n        2: rewrite Hilen; auto.\n        destruct Hst as (w2 & (q & Hq1 & Hq2) & _).\n        rewrite <- (Hilen linker i1) in H.\n        destruct (icomp linker i1 I); try discriminate.\n        apply sss_steps_stall, proj1 in Hq2; simpl; lia. }\n      assert (in_code (linker i1) (linker i1, icomp linker i1 I)) as G3.\n      { simpl; rewrite (Hilen linker i1 I); lia. }\n      rewrite <- H2 in H5.\n      destruct (step_X_tot I (i1,v1)) as ((i2,v2) & G4).\n      destruct (Hicomp linker) with (1 := G4) (3 := H1) as (w2 & G5 & G6).\n      * rewrite H7, Hilen; auto.\n      * apply subcode_sss_progress_inv with (3 := H6) (4 := G5) in H5; auto.\n        destruct H5 as (q & H5 & G7).\n        exists q, (i2,v2), (linker i2, w2); simpl; repeat (split; auto).\n        apply subcode_sss_compute with (1 := HI).\n        exists 1; apply sss_steps_1.\n        exists i1, nil, I, nil, v1; repeat (split; auto).\n        f_equal; simpl; lia.\n    Qed.\n\n    (* Termination in Q simulates termination in P *)\n\n    Theorem compiler_complete i1 v1 w1 : \n          v1 ⋈ w1 -> Q /Y/ (linker i1,w1) ↓ -> P /X/ (i1,v1) ↓.\n    Proof using HPQ Hicomp Hilen step_Y_fun step_X_tot.\n      intros H1 (st & (q & H2) & H3). \n      revert i1 v1 w1 H1 H2 H3.\n      induction q as [ q IHq ] using (well_founded_induction lt_wf).\n      intros i1 v1 w1 H1 H2 H3.\n      destruct (in_out_code_dec i1 P) as [ H4 | H4 ].\n      + destruct compiler_complete_step with (5 := H2) (st1 := (i1,v1))\n          as (p & (i2,v2) & (j2,w2) & G1 & G2 & G3 & G4 & G5); auto; simpl in *; subst j2.\n        destruct IHq with (1 := G5) (2 := G1) (3 := G4)\n          as ((i3 & v3) & F3 & F4); auto.\n        exists (i3,v3); repeat (split; auto).\n        apply sss_compute_trans with (1 := G3); auto.\n      + exists (i1,v1); repeat (split; auto).\n        exists 0; constructor.\n    Qed.\n\n    Corollary compiler_complete' : forall i₁ v₁ w₁ st,\n                            v₁ ⋈ w₁ /\\ Q /Y/ (linker i₁,w₁) ~~> st\n        -> exists i₂ v₂ w₂, v₂ ⋈ w₂ /\\ P /X/ (i₁,v₁) ~~> (i₂,v₂)\n                                    /\\ Q /Y/ (linker i₂,w₂) ~~> st. \n    Proof using HPQ Hicomp Hilen step_Y_fun step_X_tot.\n      intros i1 v1 w1 st (H1 & H2).\n      destruct compiler_complete with (1 := H1) (2 := ex_intro (fun x => Q /Y/ (linker i1, w1) ~~> x) _ H2)\n        as ((i2,v2) & H3 & H4).\n      exists i2, v2.\n      destruct (compiler_sound (conj H1 H3)) as (w2 & H5 & H6).\n      exists w2; do 2 (split; auto).\n      1: split; auto.\n      destruct H2 as (H2 & H0); split; auto.\n      apply sss_compute_inv with (3 := H6); auto.\n    Qed.\n\n    Definition compiled_complete := forall i₁ v₁ w₁ j₂ w₂,\n                         v₁ ⋈ w₁ /\\ Q /Y/ (linker i₁,w₁) ~~> (j₂,w₂)\n        -> exists i₂ v₂, v₂ ⋈ w₂ /\\ P /X/ (i₁,v₁) ~~> (i₂,v₂) /\\ j₂ = linker i₂.\n\n  End correctness.\n\n  Record compiler_t := MkGenComp {\n    gc_link     : (nat*list X) -> nat -> nat -> nat;\n    gc_code     : (nat*list X) -> nat -> list Y;\n    gc_fst      : forall P i, gc_link P i (fst P) = i;\n    gc_out      : forall P i j, out_code j P -> gc_link P i j = code_end (i,gc_code P i);  \n    gc_sound    : forall P i, compiled_sound (gc_link P i) P (i,gc_code P i);\n    gc_complete : forall P i, compiled_complete (gc_link P i) P (i,gc_code P i);\n  }.\n\n  Section compiler.\n\n    (* We build a compiler *)\n\n    Implicit Type P : nat*list X.\n\n    Let err P iQ  := iQ+length_compiler ilen (snd P).\n    Let link P iQ := linker ilen P iQ (err P iQ).\n    Let code P iQ := compiler icomp ilen P iQ (err P iQ).\n\n    Local Fact fst_ok : forall P i, link P i (fst P) = i.\n    Proof. intros [] ?; apply linker_code_start. Qed.\n\n    Local Fact out_ok : forall P i j, out_code j P -> link P i j = code_end(i,code P i).\n    Proof using Hilen.\n      intros (iP,cP) iQ j H.\n      unfold link, code_end.\n      rewrite linker_out_err; unfold err; simpl; auto.\n      * unfold code; rewrite compiler_length; auto.\n      * lia.\n    Qed.\n\n    Local Fact sound : forall P i, compiled_sound (link P i) P (i,code P i).\n    Proof using Hilen Hicomp.\n      intros (iP,cP) iQ; apply compiler_sound.\n      intros; apply compiler_subcode; auto.\n    Qed.\n\n    Local Fact complete : forall P i, compiled_complete (link P i) P (i,code P i).\n    Proof using Hilen Hicomp step_Y_fun step_X_tot.\n      intros (iP,cP) iQ; unfold link, code.\n      intros i1 v1 w1 j2 w2 H1.\n      destruct compiler_complete' with (2 := H1) (P := (iP,cP))\n        as (i2 & v2 & w2' & H2 & H3 & H4 & H5); auto.\n      + intros; apply compiler_subcode; auto.\n      + exists i2, v2.\n        match type of H4 with _ /Y/ (?a,?b) ->> (?c,?d) => assert (a = c /\\ b = d) as E end.\n        1:{ apply sss_compute_stop in H4.\n            * inversion H4; auto.\n            * simpl fst.\n              apply linker_out_code; auto.\n              - right; unfold err; lia.\n              - apply H3. }\n        destruct E as [ E -> ]; auto.\n    Qed.\n\n    Hint Resolve fst_ok out_ok sound complete : core.\n\n    Theorem generic_compiler : compiler_t.\n    Proof using Hilen Hicomp step_Y_fun step_X_tot.\n      exists link code; auto. \n    Defined.\n \n  End compiler.\n\n  Theorem compiler_t_output_sound c P i i₁ v₁ i₂ v₂ w₁ : \n                    v₁ ⋈ w₁ /\\ P /X/ (i₁,v₁) ~~> (i₂,v₂)\n      -> exists w₂, v₂ ⋈ w₂ /\\ (i,gc_code c P i) /Y/ (gc_link c P i i₁,w₁) ~~> (gc_link c P i i₂,w₂).\n  Proof using .\n    destruct c as [ lnk code first out sound complete ]; simpl.\n    intros (H1 & H2 & H3).\n    destruct (sound P i i₁ v₁ i₂ v₂ w₁) as (w2 & H4 & H5); auto.\n    exists w2; split; auto; split; auto.\n    apply out with (i := i) in H3.\n    unfold fst in H3 |- *.\n    rewrite H3; right; simpl; lia.\n  Qed.\n\n  Theorem compiler_t_output_sound' c P i v w i' v' : \n              v ⋈ w \n           -> P /X/ (fst P,v) ~~> (i',v') \n           -> exists w', (i,gc_code c P i) /Y/ (i,w) ~~> (code_end (i,gc_code c P i),w') \n                       /\\ v' ⋈ w'.\n  Proof using .\n    intros H H1.\n    destruct (@compiler_t_output_sound c P i) with (1 := conj H H1) as (w1 & H2 & H3).\n    exists w1; split; auto.\n    rewrite gc_fst, gc_out in H3; auto.\n    apply H1.\n  Qed.\n\n  Theorem compiler_t_term_correct (c : compiler_t) P i j v w :\n         v ⋈ w -> P /X/ (j,v) ↓ <-> (i,gc_code c P i) /Y/ (gc_link c P i j,w) ↓.\n  Proof using .\n    destruct c as [ lnk code first out sound complete ]; simpl.\n    intros H; split.\n    + intros ((j',v') & H1 & H2).\n      destruct sound with (1 := conj H H1) (i := i)\n        as (w' & H3 & H4).\n      exists (lnk P i j', w'); split; auto.\n      simpl fst in H2 |- *; rewrite out; simpl; auto.\n    + intros ((j',w') & H1).\n      unfold compiled_complete in complete.\n      generalize (conj H H1); intros H2.\n      apply complete in H2 as (i' & v' & H3 & H4 & H5).\n      exists (i',v'); auto.\n  Qed.\n\n  Theorem compiler_t_term_equiv (c : compiler_t) P i v w :\n         v ⋈ w -> P /X/ (fst P,v) ↓ <-> (i,gc_code c P i) /Y/ (i,w) ↓.\n  Proof using .\n    rewrite <- (gc_fst c P i) at 3.\n    apply compiler_t_term_correct.\n  Qed.\n\nEnd comp.\n\nSection compiler_t_simul_equiv.\n\n  Variables (X Y : Set) (state_X state_Y : Type)\n            (step_X : X -> (nat*state_X) -> (nat*state_X) -> Prop)\n            (step_Y : Y -> (nat*state_Y) -> (nat*state_Y) -> Prop)\n            (sim1 sim2 : state_X -> state_Y -> Prop).\n\n  Theorem compiler_t_simul_equiv : \n            (forall x y, sim1 x y <-> sim2 x y) \n         -> compiler_t step_X step_Y sim1 \n         -> compiler_t step_X step_Y sim2.\n  Proof.\n    intros E [ gc_link gc_code gc_fst gc_out gc_sound gc_complete ].\n    exists gc_link gc_code; auto.\n    + intros P i i1 v1 i2 v2 w1 H1.\n      rewrite <- E in H1.\n      apply (gc_sound _ i) in H1 as (w2 & ?).\n      now exists w2; rewrite <- E.\n    + intros P i i1 v1 w1 j2 w2 H1.\n      rewrite <- E in H1.\n      apply (gc_complete _ i) in H1 as (i2 & v2 & ?).\n      now exists i2, v2; rewrite <- E.\n  Qed.\n\nEnd compiler_t_simul_equiv.\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/Shared/Libs/DLW/Code/compiler_correction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.754914975839675, "lm_q1q2_score": 0.664926897754823}}
{"text": "Require Import rt.util.all.\nRequire Import rt.model.arrival.basic.task rt.model.priority rt.model.schedule.global.workload.\nRequire Import rt.model.schedule.global.jitter.job rt.model.schedule.global.jitter.schedule.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.\n\nModule Interference.\n\n  Import ScheduleOfSporadicTaskWithJitter Priority Workload.\n\n  (* We import some of the basic definitions, but we need to re-define almost everything\n     since the definition of backlogged (and thus the definition of interference)\n     changes with jitter. *)\n  Require Import rt.model.schedule.global.basic.interference.\n  Export Interference.\n  \n  Section InterferenceDefs.\n\n    Context {sporadic_task: eqType}.\n    Context {Job: eqType}.\n    Variable job_arrival: Job -> time.\n    Variable job_cost: Job -> time.\n    Variable job_task: Job -> sporadic_task.\n    Variable job_jitter: Job -> time.\n\n    (* Consider any job arrival sequence...*)\n    Variable arr_seq: arrival_sequence Job.\n\n    (* ... and any schedule of those jobs. *)\n    Context {num_cpus: nat}.\n    Variable sched: schedule Job num_cpus.\n\n    (* Consider any job j that incurs interference. *)\n    Variable j: Job.\n\n    (* Recall the definition of backlogged (pending and not scheduled). *)\n    Let job_is_backlogged := backlogged job_arrival job_cost job_jitter sched j.\n\n    (* First, we define total interference. *)\n    Section TotalInterference.\n      \n      (* The total interference incurred by job j during [t1, t2) is the\n         cumulative time in which j is backlogged in this interval. *)\n      Definition total_interference (t1 t2: time) :=\n        \\sum_(t1 <= t < t2) job_is_backlogged t.\n\n    End TotalInterference.\n    \n    (* Next, we define job interference. *)\n    Section JobInterference.\n\n      (* Let job_other be a job that interferes with j. *)\n      Variable job_other: Job.\n\n      (* The interference caused by job_other during [t1, t2) is the cumulative\n         time in which j is backlogged while job_other is scheduled. *)\n      Definition job_interference (t1 t2: time) :=\n        \\sum_(t1 <= t < t2)\n          \\sum_(cpu < num_cpus)\n            (job_is_backlogged t &&\n            scheduled_on sched job_other cpu t).\n\n    End JobInterference.\n    \n    (* Next, we define task interference. *)\n    Section TaskInterference.\n\n      (* In order to define task interference, consider any interfering task tsk_other. *)\n      Variable tsk_other: sporadic_task.\n    \n      (* The interference caused by tsk during [t1, t2) is the cumulative time\n         in which j is backlogged while tsk is scheduled. *)\n      Definition task_interference (t1 t2: time) :=\n        \\sum_(t1 <= t < t2)\n          \\sum_(cpu < num_cpus)\n            (job_is_backlogged t &&\n            task_scheduled_on job_task sched tsk_other cpu t).\n\n    End TaskInterference.\n\n    (* Next, we define an approximation of the total interference based on\n       each per-task interference. *)\n    Section TaskInterferenceJobList.\n\n      Variable tsk_other: sporadic_task.\n\n      Definition task_interference_joblist (t1 t2: time) :=\n        \\sum_(j <- jobs_scheduled_between sched t1 t2 | job_task j == tsk_other)\n         job_interference j t1 t2.\n\n    End TaskInterferenceJobList.\n\n    (* Now we prove some basic lemmas about interference. *)\n    Section BasicLemmas.\n\n      (* First, we show that total interference cannot be larger than the interval length. *)\n      Lemma total_interference_le_delta :\n        forall t1 t2,\n          total_interference t1 t2 <= t2 - t1.\n      Proof.\n        unfold total_interference; intros t1 t2.\n        apply leq_trans with (n := \\sum_(t1 <= t < t2) 1);\n          first by apply leq_sum; ins; apply leq_b1.\n        by rewrite big_const_nat iter_addn mul1n addn0 leqnn.\n      Qed.\n\n      (* Next, we prove that job interference is bounded by the service of the interfering job. *)\n      Lemma job_interference_le_service :\n        forall j_other t1 t2,\n          job_interference j_other t1 t2 <= service_during sched j_other t1 t2.\n      Proof.\n        intros j_other t1 t2; unfold job_interference, service_during.\n        apply leq_sum; intros t _.\n        unfold service_at; rewrite [\\sum_(_ < _ | scheduled_on _ _ _  _)_]big_mkcond.\n        apply leq_sum; intros cpu _.\n        destruct (job_is_backlogged t); [rewrite andTb | by rewrite andFb].\n        by destruct (scheduled_on sched j_other cpu t).\n      Qed.\n      \n      (* We also prove that task interference is bounded by the workload of the interfering task. *)\n      Lemma task_interference_le_workload :\n        forall tsk t1 t2,\n          task_interference tsk t1 t2 <= workload job_task sched tsk t1 t2.\n      Proof.\n        unfold task_interference, workload; intros tsk t1 t2.\n        apply leq_sum; intros t _.\n        apply leq_sum; intros cpu _.\n        destruct (job_is_backlogged t); [rewrite andTb | by rewrite andFb].\n        unfold task_scheduled_on, service_of_task.\n        by destruct (sched cpu t).\n      Qed.\n\n    End BasicLemmas.\n\n    (* Now we prove some bounds on interference for sequential jobs. *)\n    Section InterferenceSequentialJobs.\n\n      (* If jobs are sequential, ... *)\n      Hypothesis H_sequential_jobs: sequential_jobs sched.\n    \n      (* ... then the interference incurred by a job in an interval\n         of length delta is at most delta. *)\n      Lemma job_interference_le_delta :\n        forall j_other t1 delta,\n          job_interference j_other t1 (t1 + delta) <= delta.\n      Proof.\n        rename H_sequential_jobs into SEQ.\n        unfold job_interference, sequential_jobs in *.\n        intros j_other t1 delta.\n        apply leq_trans with (n := \\sum_(t1 <= t < t1 + delta) 1);\n          last by rewrite big_const_nat iter_addn mul1n addn0 addKn leqnn.\n        apply leq_sum; intros t _.\n        destruct ([exists cpu, scheduled_on sched j_other cpu t]) eqn:EX.\n        {\n          move: EX => /existsP [cpu SCHED].\n          rewrite (bigD1 cpu) // /=.\n          rewrite big_mkcond (eq_bigr (fun x => 0)) /=;\n            first by simpl_sum_const; rewrite leq_b1.\n          intros cpu' _; des_if_goal; last by done.\n          destruct (scheduled_on sched j_other cpu' t) eqn:SCHED'; last by rewrite andbF.\n          move: SCHED SCHED' => /eqP SCHED /eqP SCHED'.\n          by specialize (SEQ j_other t cpu cpu' SCHED SCHED'); rewrite SEQ in Heq.\n        }\n        {\n          apply negbT in EX; rewrite negb_exists in EX.\n          move: EX => /forallP EX.\n          rewrite (eq_bigr (fun x => 0)); first by simpl_sum_const.\n          by intros cpu _; specialize (EX cpu); apply negbTE in EX; rewrite EX andbF.\n        }\n      Qed.\n\n    End InterferenceSequentialJobs.\n\n    (* Next, we show that the cumulative per-task interference bounds the total\n       interference. *)\n    Section BoundUsingPerJobInterference.\n      \n      Lemma interference_le_interference_joblist :\n        forall tsk t1 t2,\n          task_interference tsk t1 t2 <= task_interference_joblist tsk t1 t2.\n      Proof.\n        intros tsk t1 t2.\n        unfold task_interference, task_interference_joblist, job_interference, job_is_backlogged.\n        rewrite [\\sum_(_ <- _ sched _ _ | _) _]exchange_big /=.\n        rewrite big_nat_cond [\\sum_(_ <= _ < _ | true) _]big_nat_cond.\n        apply leq_sum; move => t /andP [LEt _].\n        rewrite exchange_big /=.\n        apply leq_sum; intros cpu _.\n        destruct (backlogged job_arrival job_cost job_jitter sched j t) eqn:BACK;      \n          last by rewrite andFb (eq_bigr (fun x => 0));\n            first by rewrite big_const_seq iter_addn mul0n addn0.\n        rewrite andTb.\n        destruct (task_scheduled_on job_task sched tsk cpu t) eqn:SCHED; last by done.\n        unfold scheduled_on, task_scheduled_on in *.\n        destruct (sched cpu t) as [j' |] eqn:SOME; last by done.\n        rewrite big_mkcond /= (bigD1_seq j') /=; last by apply undup_uniq.\n        {\n          by rewrite SCHED eq_refl.\n        }\n        {\n          unfold jobs_scheduled_between.\n          rewrite mem_undup; apply mem_bigcat_nat with (j := t);\n            first by done.\n          apply mem_bigcat_ord with (j := cpu); first by apply ltn_ord.\n          by unfold make_sequence; rewrite SOME mem_seq1 eq_refl.\n        }\n      Qed.\n        \n    End BoundUsingPerJobInterference.\n    \n  End InterferenceDefs.\n\nEnd Interference.", "meta": {"author": "cd-public", "repo": "rt-proofs", "sha": "ebef0b65460fe009c51f638fe2b459f16a6d1dd5", "save_path": "github-repos/coq/cd-public-rt-proofs", "path": "github-repos/coq/cd-public-rt-proofs/rt-proofs-ebef0b65460fe009c51f638fe2b459f16a6d1dd5/model/schedule/global/jitter/interference.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6649254283783349}}
{"text": "Require Export DataTypes. \nOpen Scope list_scope. \n(*TODO rename *)\n  \n(* Binary fields arithmetics *)\nDefinition B_add (x y : N) : N :=\n  N.lxor x y.\nOpen Scope positive_scope. \nFixpoint B_mod_pos (x y : positive)(ly : nat) : N :=\n  match x with\n  | 1 => \n    match y with\n    | 1 => 0\n    | _ => 1\n    end\n  | p~0 | p~1 =>\n      let r'2 := N.double (B_mod_pos p y ly) in \n      let r := if even (Npos x) then r'2 else (r'2 + 1)%N in\n      if (Nat.eqb (size_nat r) ly) then B_add r (Npos y) else r\n  end. \n\nDefinition B_mod (x y : N) : N :=\n  match x, y with\n  | N0, _ => N0\n  | _, N0 => x\n  | pos xp, pos yp => \n      B_mod_pos xp yp (size_nat y)\n  end. \n\nFixpoint Bp_mul_pos (x : positive)(y : N) : N :=\n  match x with\n  | 1 => y\n  | p~0 => N.double (Bp_mul_pos p y) \n  | p~1 => B_add y (N.double (Bp_mul_pos p y))\n  end. \n\nClose Scope positive_scope. \n\n(* Polynomial Base *)\nDefinition Bp_mul_raw (x y : N) : N :=\n  match x with\n  | N0 => N0\n  | Npos p => Bp_mul_pos p y\n  end. \n\nDefinition Bp_mul (gp x y : N) : N :=\n  B_mod (Bp_mul_raw x y) gp. \n\n(* TODO Consider speeding up *)\nDefinition Bp_sq_raw (x : N) :=\n  Bp_mul_raw x x. \n\nDefinition Bp_sq (gp x : N) :=\n  Bp_mul gp x x. \n\n(* cube *)\nDefinition Bp_cb (gp x : N) :=\n  Bp_mul gp x (Bp_sq gp x). \n\n(* Polynomial Base *)\n(*Definition Bp_pow (m : N)(gp : N)(g : N)(a : N) : N :=\n  power_general g a (N.shiftl 1 m)(Bp_sq gp)(Bp_mul gp). \n\nDefinition Bp_inv (m gp g : N) : N :=\n  Bp_pow m gp g ((N.shiftl 1 m) - 2).\n\nDefinition Bp_div (m gp x y : N) : N :=\n  Bp_mul gp x (Bp_inv m gp y). *)\n\n\n\n(*Lemma id0_inrng (po : prime_order) : 0 < order po. \nProof.\ndestruct po as [p H]. \nsimpl. inversion H.\nassert (h : 0 < 3). { reflexivity. }\napply (lt_trans 0 3 p h (gt_lt p 3 H)).\nQed.    \n\nLemma id1_inrng (po : prime_order) : 1 < order po. \nProof.\ndestruct po as [p H]. \nsimpl. inversion H.\nassert (h : 1 < 3). { reflexivity. }\napply (lt_trans 1 3 p h (gt_lt p 3 H)).\nQed.    \n\nDefinition id0_builder_pf (po : prime_order) : Fpe po :=\n  mkFpe po 0 (id0_inrng po). \n\nDefinition id1_builder_pf (po : prime_order) : Fpe po :=\n  mkFpe po 1 (id1_inrng po). \n  *)\n", "meta": {"author": "sleepycoke", "repo": "ShangMi_Coq", "sha": "0bbfe578c332f87535f2fa2dc595259ba944f206", "save_path": "github-repos/coq/sleepycoke-ShangMi_Coq", "path": "github-repos/coq/sleepycoke-ShangMi_Coq/ShangMi_Coq-0bbfe578c332f87535f2fa2dc595259ba944f206/ECField.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6649254251008206}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\n(* ** Object-level encoding of exponential *)\n\nRequire Import Arith ZArith List.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac sums rel_iter gcd.\n\nFrom Undecidability.H10.Matija \n  Require Import alpha expo_diophantine.\n\nFrom Undecidability.H10.Dio \n  Require Import dio_logic.\n\nSet Implicit Arguments.\n\nLocal Notation power := (mscal mult 1).\nLocal Notation expo := (mscal mult 1).\n\n(* Here one can witness how workable is automation of recognition\n    of Diophantine shapes.\n\n    Notice that alpha_conditions below could probably be optimized\n    from the new Diophantine shapes that include Diophantine\n    functions. *)\n\nLocal Notation \"x ≐ ⌞ n ⌟\" := (df_cst x n) \n      (at level 49, no associativity, format \"x  ≐  ⌞ n ⌟\").\nLocal Notation \"x ≐ y\" := (df_eq x y) \n      (at level 49, no associativity, format \"x  ≐  y\").\nLocal Notation \"x ≐ y ⨢ z\" := (df_add x y z) \n      (at level 49, no associativity, y at next level, format \"x  ≐  y  ⨢  z\").\nLocal Notation \"x ≐ y ⨰ z\" := (df_mul x y z) \n      (at level 49, no associativity, y at next level, format \"x  ≐  y  ⨰  z\").\n\nTheorem dio_rel_alpha a b c : 𝔻F a -> 𝔻F b -> 𝔻F c\n                           -> 𝔻R (fun ν => 3 < b ν /\\ a ν = alpha_nat (b ν) (c ν)).\nProof.\n  dio by lemma (fun v => alpha_diophantine (a v) (b v) (c v)).\nDefined.\n\n#[export] Hint Resolve dio_rel_alpha : dio_rel_db.\n\nLocal Fact dio_rel_alpha_example : 𝔻R (fun ν => 3 < ν 1 /\\ ν 0 = alpha_nat (ν 1) (ν 2)).\nProof. dio auto. Defined.\n\n(* Eval compute in df_size_Z (proj1_sig dio_rel_alpha_example). *)\n\nFact dio_rel_alpha_size : df_size_Z (proj1_sig dio_rel_alpha_example) = 1445%Z.\nProof. reflexivity. Qed.\n\n(* This is Matiyasevich theorem stating that q^r is a Diophantine function. \n    \n    Notice that expo_conditions below could also probably be optimized *)\n\nTheorem dio_fun_expo q r : 𝔻F q -> 𝔻F r -> 𝔻F (fun ν => expo (r ν) (q ν)).\nProof.\n  dio by lemma (fun v => expo_diophantine (v 0) (q v⭳) (r v⭳)).\nDefined.\n\n#[export] Hint Resolve dio_fun_expo : dio_fun_db.\n\nLocal Fact dio_fun_expo_example : 𝔻F (fun ν => expo (ν 0) (ν 1)).\nProof. dio auto. Defined.\n\n(* Eval compute in df_size_Z (proj1_sig dio_fun_expo_example). *)\n\n(* The new Diophantine shapes (w/o build-in polynimoals) \n   build formulas that are a bit bigger ... *)\n\nLocal Fact dio_fun_expo_example_size : df_size_Z (proj1_sig dio_fun_expo_example) = 4903%Z.\nProof. reflexivity. Qed.\n\n(* We use the exponantial to characterize digits *)\n\n(* The is_digit c q i y relation stating that \n     \n       \"y is the i-th digit of c is base q\" \n *)\n\nLocal Fact is_digit_eq c q i y : \n            is_digit c q i y \n        <-> y < q\n         /\\ exists a b p, c = (a*q+y)*p+b \n                       /\\ b < p\n                       /\\ p = power i q.\nProof.\n  split; intros (H1 & a & b & H2).\n  + split; auto; exists a, b, (power i q); repeat split; tauto.\n  + destruct H2 as (p & H2 & H3 & H4).\n    split; auto; exists a, b; subst; auto.\nQed.\n\nLemma dio_rel_is_digit c q i y : 𝔻F c -> 𝔻F q -> 𝔻F i -> 𝔻F y\n                              -> 𝔻R (fun ν => is_digit (c ν) (q ν) (i ν) (y ν)).\nProof.\n  dio by lemma (fun ν => is_digit_eq (c ν) (q ν) (i ν) (y ν)).\nDefined.\n\n#[export] Hint Resolve dio_rel_is_digit : dio_rel_db.\n\nLocal Fact dio_rel_is_digit_example : 𝔻R (fun ν => is_digit (ν 0) (ν 1) (ν 2) (ν 3)).\nProof. dio auto. Defined.\n\n(* Check dio_rel_is_digit_example. *)\n(* Eval compute in df_size_Z (proj1_sig dio_rel_is_digit_example). *)\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/H10/Dio/dio_expo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6648674216660176}}
{"text": "From Test Require Import tactic.\n\nSection FOFProblem.\n\nVariable Universe : Set.\nVariable UniverseElement : Universe.\n\nVariable par_ : Universe -> Universe -> Universe -> Universe -> Prop.\nVariable pG_ : Universe -> Universe -> Universe -> Universe -> Prop.\nVariable eF_ : Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Prop.\nVariable cong_3_ : Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Prop.\nVariable congA_ : Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Prop.\nVariable cong_ : Universe -> Universe -> Universe -> Universe -> Prop.\nVariable col_ : Universe -> Universe -> Universe -> Prop.\nVariable betS_ : Universe -> Universe -> Universe -> Prop.\n\n\nVariable defparallelogram_1 : (forall A B C D : Universe, (pG_ A B C D -> (par_ A B C D /\\ par_ A D B C))).\nVariable defparallelogram2_2 : (forall A B C D : Universe, ((par_ A B C D /\\ par_ A D B C) -> pG_ A B C D)).\nVariable proposition_34_3 : (forall A B C D : Universe, (pG_ A C D B -> (cong_ A B C D /\\ (cong_ A C B D /\\ (congA_ C A B B D C /\\ (congA_ A B D D C A /\\ cong_3_ C A B B D C)))))).\nVariable lemma_congruencesymmetric_4 : (forall A B C D : Universe, (cong_ B C A D -> cong_ A D B C)).\nVariable lemma_congruencetransitive_5 : (forall A B C D E F : Universe, ((cong_ A B C D /\\ cong_ C D E F) -> cong_ A B E F)).\nVariable lemma_parallelsymmetric_6 : (forall A B C D : Universe, (par_ A B C D -> par_ C D A B)).\nVariable lemma_parallelNC_7 : (forall A B C D : Universe, (par_ A B C D -> (~(col_ A B C) /\\ (~(col_ A C D) /\\ (~(col_ B C D) /\\ ~(col_ A B D)))))).\nVariable lemma_NCdistinct_8 : (forall A B C : Universe, (~(col_ A B C) -> (A <> B /\\ (B <> C /\\ (A <> C /\\ (B <> A /\\ (C <> B /\\ C <> A))))))).\nVariable axiom_nocollapse_9 : (forall A B C D : Universe, ((A <> B /\\ cong_ A B C D) -> C <> D)).\nVariable lemma_collinearparallel2_10 : (forall A B C D E F : Universe, ((par_ A B C D /\\ (col_ C D E /\\ (col_ C D F /\\ E <> F))) -> par_ A B E F)).\nVariable proposition_33_11 : (forall A B C D M : Universe, ((par_ A B C D /\\ (cong_ A B C D /\\ (betS_ A M D /\\ betS_ B M C))) -> (par_ A C B D /\\ cong_ A C B D))).\nVariable lemma_parallelflip_12 : (forall A B C D : Universe, (par_ A B C D -> (par_ B A C D /\\ (par_ A B D C /\\ par_ B A D C)))).\nVariable proposition_35_13 : (forall A B C D E F : Universe, ((pG_ A B C D /\\ (pG_ E B C F /\\ (col_ A D E /\\ col_ A D F))) -> eF_ A B C D E B C F)).\nVariable lemma_PGsymmetric_14 : (forall A B C D : Universe, (pG_ A B C D -> pG_ C D A B)).\nVariable lemma_inequalitysymmetric_15 : (forall A B : Universe, (A <> B -> B <> A)).\nVariable lemma_collinear4_16 : (forall A B C D : Universe, ((col_ A B C /\\ (col_ A B D /\\ A <> B)) -> col_ B C D)).\nVariable lemma_collinearorder_17 : (forall A B C : Universe, (col_ A B C -> (col_ B A C /\\ (col_ B C A /\\ (col_ C A B /\\ (col_ A C B /\\ col_ C B A)))))).\nVariable axiom_EFpermutation_18 : (forall A B C D Ca Cb Cc Cd : Universe, (eF_ A B C D Ca Cb Cc Cd -> (eF_ A B C D Cb Cc Cd Ca /\\ (eF_ A B C D Cd Cc Cb Ca /\\ (eF_ A B C D Cc Cd Ca Cb /\\ (eF_ A B C D Cb Ca Cd Cc /\\ (eF_ A B C D Cd Ca Cb Cc /\\ (eF_ A B C D Cc Cb Ca Cd /\\ eF_ A B C D Ca Cd Cc Cb)))))))).\nVariable axiom_EFsymmetric_19 : (forall A B C D Ca Cb Cc Cd : Universe, (eF_ A B C D Ca Cb Cc Cd -> eF_ Ca Cb Cc Cd A B C D)).\nVariable axiom_EFtransitive_20 : (forall A B C D P Q R S Ca Cb Cc Cd : Universe, ((eF_ A B C D Ca Cb Cc Cd /\\ eF_ Ca Cb Cc Cd P Q R S) -> eF_ A B C D P Q R S)).\n\nTheorem proposition_36A_21 : (forall A B C D E F G H M : Universe, ((pG_ A B C D /\\ (pG_ E F G H /\\ (col_ A D E /\\ (col_ A D H /\\ (col_ B C F /\\ (col_ B C G /\\ (cong_ B C F G /\\ (betS_ B M H /\\ betS_ C M E)))))))) -> eF_ A B C D E F G H)).\nProof.\n  time tac.\nQed.\n\nEnd FOFProblem.\n", "meta": {"author": "janicicpredrag", "repo": "Larus", "sha": "a095ca588fbb0e4a64a26d92946485bbf85e1e08", "save_path": "github-repos/coq/janicicpredrag-Larus", "path": "github-repos/coq/janicicpredrag-Larus/Larus-a095ca588fbb0e4a64a26d92946485bbf85e1e08/benchmarks/coq-problems/euclid/proposition_36A.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.6648674214184105}}
{"text": "Require Import init.\n\nRequire Export nat_base.\nRequire Import nat_plus.\nRequire Import nat_mult.\n\nRequire Export order_plus.\nRequire Export order_mult.\nRequire Export order_bounds.\nRequire Export set_order.\n\nGlobal Instance nat_order : Order nat := {\n    le := fix le a b :=\n        match a with\n        | nat_suc a' =>\n            match b with\n            | nat_suc b' => le a' b'\n            | nat_zero => False\n            end\n        | nat_zero => True\n        end\n}.\n\nDefinition nat_to_set_type n := set_type (initial_segment n).\n\nTheorem nat_neg_eq : ∀ {a}, a ≤ 0 → 0 = a.\nProof.\n    intros a eq.\n    nat_destruct a; [>reflexivity|].\n    contradiction eq.\nQed.\nLemma nat_pos : ∀ a, 0 ≤ a.\nProof.\n    intros a.\n    exact true.\nQed.\nTheorem nat_pos2 : ∀ n, 0 < nat_suc n.\nProof.\n    intros n.\n    split; [>apply nat_pos|].\n    intro contr.\n    exact (nat_zero_suc contr).\nQed.\nLemma nat_neg : ∀ {n}, ¬(nat_suc n ≤ 0).\nProof.\n    intros n contr.\n    apply nat_neg_eq in contr.\n    contradiction (nat_zero_suc contr).\nQed.\nLemma nat_neg2 : ∀ {a}, ¬(a < 0).\nProof.\n    intros a [leq neq].\n    apply nat_neg_eq in leq.\n    symmetry in leq; contradiction.\nQed.\n\nDefinition nat_lt_0_false (a : nat_to_set_type 0) := nat_neg2 [|a].\n\nTheorem nat_one_pos : 0 < 1.\nProof.\n    apply nat_pos2.\nQed.\n\nTheorem nat_sucs_le : ∀ a b, nat_suc a ≤ nat_suc b ↔ a ≤ b.\nProof.\n    intros a b.\n    split; intro eq; exact eq.\nQed.\nTheorem nat_sucs_lt : ∀ a b, nat_suc a < nat_suc b ↔ a < b.\nProof.\n    intros a b.\n    unfold strict.\n    rewrite nat_sucs_le.\n    rewrite nat_suc_eq.\n    reflexivity.\nQed.\n\nGlobal Instance nat_le_connex : Connex le.\nProof.\n    split.\n    intros a.\n    nat_induction a; intros b.\n    -   left.\n        apply nat_pos.\n    -   nat_destruct b.\n        +   right.\n            apply nat_pos.\n        +   apply or_to_strong.\n            do 2 rewrite nat_sucs_le.\n            apply or_from_strong.\n            apply IHa.\nQed.\n\nGlobal Instance nat_le_antisymmetric : Antisymmetric le.\nProof.\n    split.\n    intros a.\n    nat_induction a; intros b eq1 eq2.\n    -   exact (nat_neg_eq eq2).\n    -   nat_destruct b.\n        +   contradiction eq1.\n        +   apply f_equal.\n            rewrite nat_sucs_le in eq1, eq2.\n            apply IHa; assumption.\nQed.\n\nGlobal Instance nat_le_transitive : Transitive le.\nProof.\n    split.\n    intros a b c; revert a b.\n    nat_induction c; intros a b eq1 eq2.\n    -   apply nat_neg_eq in eq2.\n        rewrite <- eq2 in eq1.\n        exact eq1.\n    -   nat_destruct b.\n        +   apply nat_neg_eq in eq1.\n            rewrite <- eq1.\n            apply nat_pos.\n        +   nat_destruct a.\n            *   apply nat_pos.\n            *   rewrite nat_sucs_le in *.\n                apply IHc with b; assumption.\nQed.\n\nTheorem nat_le_suc : ∀ a, a ≤ nat_suc a.\nProof.\n    nat_induction a.\n    -   apply nat_one_pos.\n    -   rewrite nat_sucs_le.\n        exact IHa.\nQed.\nTheorem nat_lt_suc : ∀ a, a < nat_suc a.\nProof.\n    nat_induction a.\n    -   exact nat_one_pos.\n    -   rewrite nat_sucs_lt.\n        exact IHa.\nQed.\n\nTheorem nat_le_ex : ∀ {a b}, a ≤ b → ∃ c, a + c = b.\nProof.\n    nat_induction a; intros b ab.\n    -   exists b.\n        apply plus_lid.\n    -   nat_destruct b.\n        +   contradiction (nat_neg ab).\n        +   rewrite nat_sucs_le in ab.\n            specialize (IHa b ab) as [c IHa].\n            exists c.\n            rewrite nat_plus_lsuc.\n            apply f_equal.\n            exact IHa.\nQed.\n\nTheorem nat_lt_ex : ∀ {a b}, a < b → ∃ c, a + nat_suc c = b.\nProof.\n    intros a b [ab ab_neq].\n    pose proof (nat_le_ex ab) as [c eq].\n    nat_destruct c.\n    -   rewrite plus_rid in eq.\n        contradiction.\n    -   exists c.\n        exact eq.\nQed.\n\nGlobal Instance nat_le_lplus : OrderLplus nat.\nProof.\n    split.\n    intros a b c ab.\n    nat_induction c.\n    -   do 2 rewrite plus_lid.\n        exact ab.\n    -   do 2 rewrite nat_plus_lsuc.\n        rewrite nat_sucs_le.\n        exact IHc.\nQed.\n\nGlobal Instance nat_le_plus_lcancel : OrderPlusLcancel nat.\nProof.\n    split.\n    intros a b c eq.\n    nat_induction c.\n    -   do 2 rewrite plus_lid in eq.\n        exact eq.\n    -   apply IHc.\n        do 2 rewrite nat_plus_lsuc in eq.\n        rewrite nat_sucs_le in eq.\n        exact eq.\nQed.\n\nGlobal Instance nat_le_mult : OrderMult nat.\nProof.\n    split.\n    intros.\n    apply nat_pos.\nQed.\n\nTheorem nat_le_lmult : ∀ {a b} c, a ≤ b → c * a ≤ c * b.\nProof.\n    intros a b c ab.\n    nat_induction c.\n    -   do 2 rewrite mult_lanni.\n        apply refl.\n    -   do 2 rewrite nat_mult_lsuc.\n        exact (le_lrplus ab IHc).\nQed.\n\nGlobal Instance nat_le_lmult_class : OrderLmult nat.\nProof.\n    split.\n    intros a b c c_pos.\n    apply nat_le_lmult.\nQed.\n\nTheorem nat_le_rmult : ∀ {a b} c, a ≤ b → a * c ≤ b * c.\nProof.\n    intros a b c.\n    apply le_rmult_pos.\n    apply nat_pos.\nQed.\n\nTheorem nat_le_mult_lcancel : ∀ {a b} c, 0 ≠ c → c * a ≤ c * b → a ≤ b.\nProof.\n    intros a b c c_neq eq.\n    nat_destruct c; [>contradiction|]; clear c_neq.\n    revert b eq.\n    nat_induction a; intros b eq.\n    -   apply nat_pos.\n    -   nat_destruct b.\n        +   exfalso.\n            rewrite mult_ranni in eq.\n            apply nat_neg_eq in eq.\n            exact (nat_neq_suc_mult _ _ eq).\n        +   rewrite nat_sucs_le.\n            apply IHa; clear IHa.\n            do 2 rewrite nat_mult_rsuc in eq.\n            apply le_plus_lcancel in eq.\n            exact eq.\nQed.\n\nGlobal Instance nat_le_mult_lcancel_class : OrderMultLcancel nat.\nProof.\n    split.\n    intros a b c [C c_pos].\n    apply nat_le_mult_lcancel.\n    exact c_pos.\nQed.\n\nTheorem nat_le_mult_rcancel : ∀ {a b} c, 0 ≠ c → a * c ≤ b * c → a ≤ b.\nProof.\n    intros a b c c_pos.\n    apply le_mult_rcancel_pos.\n    split; [>apply nat_pos|exact c_pos].\nQed.\n\nTheorem nat_lt_suc_le : ∀ {a b}, a < nat_suc b ↔ a ≤ b.\nProof.\n    intros a b.\n    split.\n    -   revert b.\n        nat_induction a; intros b eq.\n        +   apply nat_pos.\n        +   rewrite nat_sucs_lt in eq.\n            nat_destruct b.\n            *   exfalso.\n                exact (nat_neg2 eq).\n            *   apply IHa.\n                exact eq.\n    -   intro eq.\n        exact (le_lt_trans eq (nat_lt_suc b)).\nQed.\nTheorem nat_le_suc_lt : ∀ {a b}, nat_suc a ≤ b ↔ a < b.\nProof.\n    intros a b.\n    nat_destruct b.\n    -   split; intros contr.\n        +   contradiction (nat_neg contr).\n        +   contradiction (nat_neg2 contr).\n    -   rewrite nat_sucs_le.\n        symmetry.\n        apply nat_lt_suc_le.\nQed.\n\nTheorem nat_le_self_lplus : ∀ a b, a ≤ b + a.\nProof.\n    intros a b.\n    rewrite <- le_plus_0_a_b_ab.\n    apply nat_pos.\nQed.\nTheorem nat_le_self_rplus : ∀ a b, a ≤ a + b.\nProof.\n    intros a b.\n    rewrite plus_comm.\n    apply nat_le_self_lplus.\nQed.\n\nTheorem nat_lt_one_eq : ∀ n, n < 1 → 0 = n.\nProof.\n    intros n n_lt.\n    unfold one in n_lt; cbn in n_lt.\n    rewrite nat_lt_suc_le in n_lt.\n    apply nat_neg_eq in n_lt.\n    exact n_lt.\nQed.\n\nTheorem nat_le_self_lmult : ∀ a b, 0 ≠ b → a ≤ b * a.\nProof.\n    intros a b b_nz.\n    nat_induction a.\n    -   rewrite mult_ranni.\n        apply refl.\n    -   rewrite nat_mult_rsuc.\n        assert (1 ≤ b) as b_gt.\n        {\n            rewrite <- nlt_le.\n            intro eq.\n            apply nat_lt_one_eq in eq.\n            contradiction.\n        }\n        exact (le_lrplus b_gt IHa).\nQed.\nTheorem nat_le_self_rmult : ∀ a b, 0 ≠ b → a ≤ a * b.\nProof.\n    intros a b.\n    rewrite mult_comm.\n    apply nat_le_self_lmult.\nQed.\n\nTheorem nat_neq0_leq1 : ∀ {a}, 0 ≠ a → 1 ≤ a.\nProof.\n    intros a a_neq.\n    unfold one; cbn.\n    rewrite nat_le_suc_lt.\n    split.\n    -   apply nat_pos.\n    -   exact a_neq.\nQed.\n\nTheorem strong_induction : ∀ S : nat → Prop,\n    (∀ n, (∀ m, m < n → S m) → S n) → ∀ n, S n.\nProof.\n    intros S ind n.\n    pose (T n := ∀ m, m < n → S m).\n    assert (∀ n', T n') as all_T.\n    {\n        nat_induction n'.\n        -   unfold T.\n            intros m m_lt.\n            contradiction (nat_neg2 m_lt).\n        -   unfold T in *.\n            intros m m_lt.\n            apply ind.\n            intros m' m'_eq.\n            apply IHn'.\n            rewrite nat_lt_suc_le in m_lt.\n            exact (lt_le_trans m'_eq m_lt).\n    }\n    apply ind.\n    apply all_T.\nQed.\n\nGlobal Instance nat_wo : WellOrdered le.\nProof.\n    split.\n    intros S [x Sx].\n    classic_contradiction no_least.\n    rewrite not_ex in no_least.\n    assert (∀ x, ¬S x) as none.\n    {\n        clear x Sx.\n        intros x.\n        induction x using strong_induction.\n        intros Sx.\n        specialize (no_least x).\n        rewrite not_and_impl, not_all in no_least.\n        specialize (no_least Sx) as [a a_eq].\n        apply not_impl in a_eq as [Sa a_eq].\n        rewrite nle_lt in a_eq.\n        exact (H _ a_eq Sa).\n    }\n    exact (none _ Sx).\nQed.\n\nDefinition subsequence_seq (f : sequence nat) := ∀ n, f n < f (nat_suc n).\nDefinition subsequence {U} (a b : sequence U) :=\n    ∃ f : sequence nat,\n        subsequence_seq f ∧\n        (∀ n, a (f n) = b n).\n\nTheorem subsequence_seq_leq : ∀ f, subsequence_seq f → ∀ n, n ≤ f n.\nProof.\n    intros f f_sub.\n    unfold subsequence_seq in f_sub.\n    intros n.\n    nat_induction n.\n    -   apply nat_pos.\n    -   rewrite <- nat_lt_suc_le.\n        rewrite nat_sucs_lt.\n        exact (le_lt_trans IHn (f_sub n)).\nQed.\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Number/Nat/nat_order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6648674049430795}}
{"text": "Require Import List Lia.\n\nFrom Undecidability.Shared.Libs.DLW.Utils\n  Require Import utils_tac utils_nat.\n\nFrom Undecidability.Shared.Libs.DLW.Vec\n  Require Import pos vec.\n\nFrom Undecidability.H10 \n  Require Import Dio.dio_single H10 Diophantine.\n\nFrom Undecidability.MuRec.Util \n  Require Import recalg ra_dio_poly MuRec_computable ra_sem_eq ra_recomp.\n\nSet Default Goal Selector \"!\".\nSet Default Proof Using \"Type\".\n\nLemma vec_pos_spec {X} {n} (v : Vector.t X n) (i : Fin.t n) :\n  vec_pos v i = Vector.nth v i.\nProof.\n  induction v; cbn; f_equal.\n  - inversion i.\n  - eapply (Fin.caseS' i); cbn; eauto.\nQed.\n\nFixpoint dio_move {k k'} (P : dio_polynomial (pos k) (pos (S k'))) : dio_polynomial (pos (S k)) (pos k') :=\n  match P with\n  | dp_nat n => dp_nat n\n  | dp_var n => dp_var (Fin.FS n)\n  | dp_par p => Fin.caseS' p _ (dp_var (Fin.F1)) dp_par\n  | dp_comp op P1 P2 => dp_comp op (dio_move P1) (dio_move P2)\n  end.\n\nLemma dio_move_spec {k k'} (P : dio_polynomial (pos k) (pos (S k'))) v w x : \n  dp_eval (vec_pos (x ## v)) (vec_pos w) (dio_move P) =\n  dp_eval (vec_pos v) (vec_pos (x ## w)) P.\nProof.\n  induction P as [n | n | p | op P1 IH1 P2 IH2].\n  - reflexivity.\n  - reflexivity.\n  - unfold dio_move. eapply (Fin.caseS' p); reflexivity.\n  - cbn -[vec_pos]; destruct op; congruence.\nQed.\n\nTheorem Diophantine_to_MuRec_computable {k} (R : Vector.t nat k -> nat -> Prop) :\n  functional R ->\n  Diophantine' R -> MuRec_computable R.\nProof.\n  intros HR (k' & P1 & P2 & H).\n  eapply (MuRec_computable_functional_iff _ HR).\n  unshelve eexists.\n  - eapply ra_comp. 1:  refine (ra_project (Fin.F1)).\n    2: exact (ra_dio_poly_find (dio_move P1) (dio_move P2) ## vec_nil).\n    exact k'. \n  - split.\n    + intros v m. specialize (H (Vector.cons _ m _ v)).\n      cbn -[dp_eval Vector.nth] in H. rewrite H.\n      rewrite <- ra_bs_correct, ra_rel_fix_comp. unfold s_comp.\n      intros (vi & H1 & H2). revert H1 H2.\n      eapply (Vector.caseS' vi). clear vi. intros im.\n      refine (Vector.case0 _ _).\n      intros Hproj Hfind. specialize (Hfind Fin.F1).\n      \n      cbn -[ra_dio_poly_find] in Hfind.\n      eapply ra_dio_poly_find_spec_strong1 in Hfind.\n      eapply ra_project_rel in Hproj. clear H. subst.\n      pose (w := (recomp.project (S k') im)).\n      exists (fun j => vec_pos w (Fin.FS j)).\n      generalize (eq_refl w). unfold w at 1.\n      eapply (Vector.caseS' w). clear w. intros x w Hw.\n      rewrite Hw in Hfind. rewrite !dio_move_spec in Hfind.\n      erewrite dp_eval_ext.\n      * rewrite Hfind. eapply dp_eval_ext.\n        -- intros. reflexivity.\n        -- intros. rewrite vec_pos_spec. cbn [vec_pos vec_head]. rewrite Hw. reflexivity.\n      * intros. reflexivity.\n      * intros. cbn [vec_head]. rewrite Hw. unfold vec_pos at 1. cbn [pos_S_inv]. now rewrite vec_pos_spec.\n   +  intros v m Hvm. specialize (H (Vector.cons _ m _ v)).\n      cbn -[dp_eval Vector.nth] in H. eapply H in Hvm as [ν Hν].\n      erewrite dp_eval_ext in Hν at 1.  1: symmetry in Hν.\n      1: erewrite dp_eval_ext in Hν at 1.  1: symmetry in Hν.\n      1: erewrite <- !dio_move_spec in Hν.\n      1: eapply ra_dio_poly_find_spec_strong2 in Hν as [e Hν].\n      1: eexists.\n      1: rewrite <- ra_bs_correct, ra_rel_fix_comp.  1: unfold s_comp.\n      1: eexists.  1: split.\n      * eapply ra_project_rel. reflexivity.\n      * intros p. eapply (Fin.caseS' p). 2: eapply Fin.case0.\n        rewrite vec_pos_map. \n        instantiate (1 := e ## vec_nil). \n        cbn [vec_pos pos_S_inv]. \n        eassumption.\n      * intros. instantiate (1 := vec_set_pos _). now rewrite vec_pos_set.\n      * intros. now rewrite vec_pos_spec.\n      * intros. now rewrite vec_pos_set.\n      * intros. now rewrite vec_pos_spec. Unshelve. \nQed. ", "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/Reductions/Diophantine_to_MuRec_computable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.7371581684030624, "lm_q1q2_score": 0.6648581958987415}}
{"text": "Require Import ssreflect ssrfun ssrbool eqtype ssrnat div prime.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection TPPMark2014.\n\nImplicit Types a b c : nat.\n\nLocal Open Scope nat_scope.\n\nLemma lemma1 a : (a ^ 2 == 0 %[mod 3]) || (a ^ 2 == 1 %[mod 3]).\nProof. by rewrite -modnXm; case: modn (ltn_mod a 3) => [|[|[|]]]. Qed.\n\nLemma lemma2 a b c : a ^ 2 + b ^ 2 = 3 * c ^ 2 -> [&& 3 %| a, 3 %| b & 3 %| c].\nProof.\nmove=> a2b2_eq_3c2; suff /andP [dvd3a dvd3b] : (3 %| a) && (3 %| b).\n  rewrite dvd3a dvd3b /= -[_ %| _]andbT -(Euclid_dvdX _ 2) //.\n  by rewrite -(@dvdn_pmul2l 3) // -a2b2_eq_3c2 dvdn_add // (@dvdn_exp2r 3 _ 2).\nhave /(congr1 (modn^~ 3)) := a2b2_eq_3c2.\nrewrite -modnDm modnMr -modnXm -[X in _ + X]modnXm /dvdn.\nby move: (a %% 3) (b %% 3) (ltn_mod a 3) (ltn_mod b 3) => [|[|[|?]]] [|[|[|]]].\nQed.\n\nLemma lemma3 a b c : a ^ 2 + b ^ 2 = 3 * c ^ 2 -> [&& a == 0, b == 0 & c == 0].\nProof.\nmove/eqP; elim: c {-2}c (leqnn c) => [|n ihn] c leqcn in a b *.\n  by rewrite leqn0 in leqcn; rewrite (eqP leqcn) addn_eq0 !expn_eq0 andbT.\nmove=> /(fun p => (p, p)) [/eqP /lemma2 /and3P [/divnK<- /divnK<- /divnK<-]].\nrewrite !muln_eq0 !orbF !expnMn mulnA -mulnDl eqn_mul2r; apply: ihn.\nby rewrite (leq_trans (leq_div2r _ leqcn)) // -ltnS ltn_Pdiv.\nQed.\n\nEnd TPPMark2014.\n", "meta": {"author": "KyushuUniversityMathematics", "repo": "TPP2014", "sha": "8439769862a9619cdb4e0af1597d447c7cca2325", "save_path": "github-repos/coq/KyushuUniversityMathematics-TPP2014", "path": "github-repos/coq/KyushuUniversityMathematics-TPP2014/TPP2014-8439769862a9619cdb4e0af1597d447c7cca2325/CyrilCohen/TPPmark2014.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192066862062, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.664858177709178}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrnat div eqtype.\nRequire Import Coq.omega.Omega.\n\nLtac nify :=\n    repeat match goal with\n          | [ H: is_true (leq _ _) |- _ ] => move /ltP in H\n          | [ H: is_true (leq _ _) |- _ ] => move /leP in H\n          | [ |- is_true (leq _ _) ] => apply /ltP\n          | [ |- is_true (leq _ _) ] => apply /leP\n          | [ H: ~ (is_true (leq _ _)) |- _ ] => move /negP/leP in H\n          | [ |- ~ (is_true (leq _ _)) ] => apply /negP/leP\n          | H: is_true (?a == ?b) |- _ => move /eqP in H\n          | |- is_true (?a == ?b) => apply /eqP\n          | H:context [ ?a + ?b ] |- _ => rewrite -plusE in H\n          | |- context [ ?a + ?b ] => rewrite -plusE\n          | H:context [ ?a - ?b ] |- _ => rewrite -minusE in H\n          | |- context [ ?a - ?b ] => rewrite -minusE\n          | H:context [ ?a * ?b ] |- _ => rewrite -multE in H\n          | |- context [ ?a * ?b ] => rewrite -multE\n          | H:context [ ?a / ?b ] |- _ => rewrite -multE in H\n          | |- context [ ?a / ?b ] => rewrite -multE\n          | H:context [ uphalf (double ?a) ] |- _ => rewrite uphalf_double in H\n          | |- context [ uphalf (double ?a) ] => rewrite uphalf_double\n          | H:context [ half (double ?a) ] |- _ => rewrite doubleK in H\n          | |- context [ half (double ?a) ] => rewrite doubleK\n          | H:context [ double ?a ] |- _ => rewrite -addnn in H\n          | |- context [ double ?a ] => rewrite -addnn\n    end.\n\nModule nify_test.\n\nRemark test00 a b c: (a + b + c).*2 = (a + a) + (b - b) + (b - b) + (b + b) + (c + c).\nProof. nify. omega. Qed.\n\nRemark test01 a b c: (a + b + c).*2 * 5 = ((a + a) + (b - b) + (b - b) + (b + b) + (c + c))*5.\nProof. nify. omega. Qed.\n\nRemark test02 a: (a.*2)./2.*2 = a + a.\nProof. nify. omega. Qed.\n\nEnd nify_test.", "meta": {"author": "jtassarotti", "repo": "coq-probrec", "sha": "da6f58013df44dfd2cb5b896837cfc055b362a03", "save_path": "github-repos/coq/jtassarotti-coq-probrec", "path": "github-repos/coq/jtassarotti-coq-probrec/coq-probrec-da6f58013df44dfd2cb5b896837cfc055b362a03/theories/basic/nify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6648086653972682}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_parallelflip.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_parallelsymmetric.\n\nSection Euclid.\n\nContext `{Ax1:euclidean_neutral}.\n\nLemma lemma_PGflip : \n   forall A B C D, \n   PG A B C D ->\n   PG B A D C.\nProof.\nintros.\nassert ((Par A B C D /\\ Par A D B C)) by (conclude_def PG ).\nassert (Par B A D C) by (forward_using lemma_parallelflip).\nassert (Par B C A D) by (conclude lemma_parallelsymmetric).\nassert (PG B A D C) by (conclude_def PG ).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_PGflip.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6648086601656196}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nFrom mathcomp Require Import all_algebra.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Board.\n\nDefinition turn := bool.\nDefinition white := true.\nDefinition black := false.\n\nDefinition flip  t := ~~ t.\n\nLemma flipK : involutive flip.\nProof. by case. Qed.\n\nVariable board : finType.\nVariable init : board.\nVariable moves : turn -> board -> seq board.\nVariable depth : board -> nat.\n\nHypothesis moves_depth : \n  forall t b b1, b1 \\in moves t b -> depth b1 = (depth b).-1.\n\nInductive state := win | loss | draw.\n\nImplicit Type s : state.\n\nCoercion s2n s := \n  match s with \n  | loss => 1\n  | draw => 3\n  | win => 5\n  end.\n\n\nDefinition eqs s1 s2 := (s1 == s2 :> nat).\n\nLemma eqsP : Equality.axiom eqs.\nProof. by do 2!case; constructor. Qed.\n\nCanonical state_eqMixin := EqMixin eqsP.\nCanonical state_eqType := Eval hnf in EqType state state_eqMixin.\n\nDefinition smin s1 s2 := if s1 <= s2 then s1 else s2.\n\nLemma sminC : commutative smin.\nProof. by do 2 case. Qed.\n\nLemma sminA : associative smin.\nProof. by do 3 case. Qed.\n\nLemma sminwn : left_id win smin.\nProof. by case. Qed.\n\nLemma sminnw : right_id win smin.\nProof. by case. Qed.\n\nLemma sminln : left_zero loss smin.\nProof. by case. Qed.\nLemma sminnl : right_zero loss smin.\nProof. by case. Qed.\n\nCanonical smin_monoid := Monoid.Law sminA sminwn sminnw.\nCanonical smin_comoid := Monoid.ComLaw sminC.\n\nDefinition smax s1 s2 := if s1 <= s2 then s2 else s1. \n\nLemma smaxC : commutative smax.\nProof. by do 2 case. Qed.\n\nLemma smaxA : associative smax.\nProof. by do 3 case. Qed.\n\nLemma smaxln : left_id loss smax.\nProof. by case. Qed.\n\nLemma smaxnl : right_id loss smax.\nProof. by case. Qed.\n\nLemma smaxwn : left_zero win smax.\nProof. by case. Qed.\n\nLemma smaxnw : right_zero win smax.\nProof. by case. Qed.\n\nCanonical smax_monoid := Monoid.Law smaxA smaxln smaxnl.\nCanonical smax_comoid := Monoid.ComLaw smaxC.\n\nNotation \"\\smin_ ( i <- l ) F\" := (\\big[smin/win]_(i <- l) F)\n (at level 41, F at level 41, i, l at level 50,\n  format \"\\smin_ ( i  <-  l )  F\").\n\nNotation \"\\smax_ ( i <- l ) F\" := (\\big[smax/loss]_(i <- l) F)\n (at level 41, F at level 41, i, l at level 50,\n  format \"\\smax_ ( i  <-  l )  F\").\n\nDefinition sflip x := \n  if x is win then loss else if x is loss then win else draw.\n\nLemma sflip_inj : injective sflip.\nProof. by case; case. Qed.\n\nLemma sflipK : involutive sflip.\nProof. by case. Qed.\n\nLemma sflip_max s1 s2 : sflip (smax s1 s2) = smin (sflip s1) (sflip s2).\nProof. by case: s1; case: s2. Qed.\n\nLemma sflip_min s1 s2 : sflip (smin s1 s2) = smax (sflip s1) (sflip s2).\nProof. by case: s1; case: s2. Qed.\n\nLemma ge_sminr s1 s2 : smin s1 s2 <= s2.\nProof. by case: s1; case: s2. Qed.\n\nLemma ge_sminl s1 s2 : smin s1 s2 <= s1.\nProof. by case: s1; case: s2. Qed.\n\nLemma le_smaxr s1 s2 : s2 <= smax s1 s2.\nProof. by case: s1; case: s2. Qed.\n\nLemma le_smaxl (s1 s2 : state) : s1 <= smax s1 s2.\nProof. by case: s1; case: s2. Qed.\n\nLemma smin_lel s1 s2 : s1 <= s2 -> smin s1 s2 = s1.\nProof. by case: s1; case: s2. Qed.\n\nLemma smin_ler s1 s2 : s2 <= s1 -> smin s1 s2 = s2.\nProof. by case: s1; case: s2. Qed.\n\nLemma lt_smin s1 s2 s3 : s1 < s2 -> s1 < s3 -> s1 < smin s2 s3.\nProof. by case: s1; case: s2; case: s3. Qed.\n\nLemma ge_winE s : win <= s -> s = win.\nProof. by case: s. Qed.\n \nLemma le_win s : s <= win.\nProof. by case: s. Qed.\n\nLemma le_lossE s : s <= loss -> s = loss.\nProof. by case: s. Qed.\n\nLemma ge_loss s : loss <= s.\nProof. by case: s. Qed.\n\nLemma sle_antisym s1 s2 : s1 <= s2 -> s2 <= s1 -> s1 = s2.\nProof. by case: s1; case: s2. Qed.\n\nLemma sflip_le s1 s2 : (sflip s1 <= sflip s2) = (s2 <= s1).\nProof. by case: s1; case: s2. Qed.\n\nLemma sflip_lt s1 s2 : (sflip s1 < sflip s2) = (s2 < s1).\nProof. by case: s1; case: s2. Qed.\n\nLemma smaxE s1 s2 s3 : (smax s1 s2 == s3) -> ((s1 == s3) || (s2 == s3)).\nProof. by case: s1; case: s2; case: s3. Qed.\n\nLemma le_bigsmax (A : eqType) (f : A -> state) c l : \n  c \\in l -> f c <= \\smax_(i <- l) f i.\nProof.\nelim: l => // a l IH;\n    rewrite big_cons in_cons => /orP[/eqP<-| /IH /leq_trans H].\n  by case: (f) (\\smax_(_ <- _) _) => // [] [].\nby apply: H; case: (f) (\\smax_(_ <- _) _) => // [] [].\nQed.\n\nLemma le_bigsmin (A : eqType) (f : A -> _) c l : \n  c \\in l ->  \\smin_(i <- l) f i <= f c.\nProof.\nelim: l => // a l IH;\n    rewrite big_cons in_cons => /orP[/eqP<-| /IH /leq_trans H].\n  by case: (f) (\\smin_(_ <- _) _) => // [] [].\nby apply: leq_trans (H _ (leqnn _)); \n   case: (f) (\\smin_(_ <- _) _) => // [] [].\nQed.\n\nLemma bigsmax_ex (A : eqType) (f : A -> _) l : \n  l != nil -> exists2 c, c \\in l & \\smax_(i <- l) f i = f c.\nProof.\nelim: l => // a [ _ _|b l /(_ isT) [c H1c H2c] _].\n  exists a; first by rewrite in_cons eqxx.\n  by rewrite big_cons big_nil; case: f.\nhave [faE|] := f a =P \\smax_(i <- [:: a, b & l]) f i.\n  by exists a; rewrite // in_cons eqxx.\nrewrite big_cons H2c => faNE; exists c; first by rewrite in_cons H1c orbT.\nby case: (f a) faNE; case: (f c).\nQed.\n\nLemma bigsmin_ex (A : eqType) (f : A -> _) l : \n  l != nil -> exists2 c, c \\in l & \\smin_(i <- l) f i = f c.\nProof.\nelim: l => // a [ _ _|b l /(_ isT) [c H1c H2c] _].\n  exists a; first by rewrite in_cons eqxx.\n  by rewrite big_cons big_nil; case: f.\nhave [faE|] := f a =P \\smin_(i <- [:: a, b & l]) f i.\n  by exists a; rewrite // in_cons eqxx.\nrewrite big_cons H2c => faNE; exists c; first by rewrite in_cons H1c orbT.\nby case: (f a) faNE; case: (f c).\nQed.\n\nVariable ieval : turn -> board -> option state.\n\nHypothesis liveness : forall t b, (ieval t b == None) = (moves t b != nil).\nHypothesis depth_ieval : forall t b, (ieval t b == None) = (depth b != 0).\n\nFixpoint eval_rec n t b :=\n   if ieval t b is some v then v else\n   if n is n1.+1 then \n     let t1 := flip t in\n     sflip (\\smin_(i <- moves t b) eval_rec n1 t1 i)\n   else draw (* this will never occur if we choose n well *).\n\nDefinition eval t b := eval_rec (depth b) t b.\n\nLemma eval_recE n t b : \n  eval_rec n t b =\n   if ieval t b is some v then v else\n   if n is n1.+1 then \n     let t1 := flip t in\n     sflip (\\smin_(i <- moves t b) eval_rec n1 t1 i)\n   else draw.\nProof. by case: n. Qed.\n\nLemma eval_recS n t b : \n  (depth b <= n)%N -> eval_rec n.+1 t b = eval_rec n t b.\nProof.\nelim: n t b => [/=|n IH] t b Hd.\n  by case: ieval (depth_ieval t b) Hd => //; case: depth.\nrewrite !eval_recE; case: ieval => //.\nelim: moves (@moves_depth t b) => [_ |b1 bs IH1 H1d].\n   by rewrite  /= !big_nil.\nlazy zeta in IH1 |- *; rewrite !big_cons !sflip_min.\nrewrite IH ?IH1 //.\n  by move=> b2 Hb2; apply: H1d; rewrite in_cons Hb2 orbT.\nrewrite H1d; last by rewrite in_cons eqxx.\nby rewrite -ltnS; case: depth Hd.\nQed.\n\nLemma eval_rec_stable m n t b : (depth b <= m <= n)%N ->\n  eval_rec n t b = eval_rec m t b.\nProof.\nmove=> /andP[bLm] /subnK<-; elim: (_ - _) {-2}m bLm => // {m}k IH m bLm.\nby rewrite addSnnS IH // ?eval_recS // (leq_trans bLm).\nQed.\n\nLemma evalE t b : \n  eval t b =\n   if ieval t b is some v then v else\n     let t1 := flip t in\n     sflip (\\smin_(b1 <- moves t b) eval t1 b1).\nProof.\nrewrite /eval;\n   case E : depth (depth_ieval t b) (@moves_depth t b) => [|n] /=;\n   case: ieval => //= _ Hd.\ncongr sflip; elim: moves Hd => [|b1 bs IH] Hd.\n  by rewrite !big_nil.\nrewrite !big_cons IH => [|b2 Hb2]; last by rewrite Hd // in_cons Hb2 orbT.\nrewrite (eval_rec_stable _ (_ : depth b1 <= depth b1 <= n)%nat) //. \nby rewrite leqnn Hd ?leqnn // in_cons eqxx.\nQed.\n\nLemma i_eval t b v : ieval t b = some v -> eval t b = v.\nProof. by rewrite evalE => ->. Qed.\n\n\n(* we get a maximal *)\nLemma le_eval t b1 b2 :\n  b2 \\in moves t b1  -> sflip (eval (flip t) b2) <= eval t b1.\nProof.\nmove=> b2I.\nrewrite [X in _ <= s2n X]evalE.\ncase: ieval (liveness t b1) => [a /(@sym_equal _ _ _) /negbT| _].\n  by rewrite negbK => /eqP H; rewrite H in b2I.\nby lazy zeta; rewrite sflip_le le_bigsmin.\nQed.\n\n(* and the maximum is reached in the sons *)\nLemma peval_next t b : \n  ieval t b = None -> \n  exists2 b1, b1 \\in moves t b & eval t b = sflip (eval (flip t) b1).\nProof.\nmove=> Hi; have := liveness t b; rewrite evalE Hi => /(@sym_equal _ _ _).\nrewrite eqxx => /idP /(bigsmin_ex (eval (flip t))) [c H1c H2c].\nby exists c => //=; rewrite H2c.\nQed.\n\n(* inversion theorem for win *)\nLemma eval_win t b1 b2 :\n  b2 \\in moves t b1 -> eval (flip t) b2 = loss -> eval t b1 = win.\nProof.\nmove=> b2I H2; rewrite evalE; case: ieval (liveness t b1) => [v|_].\n  move/(@sym_equal _ _ _)=> /negbT; rewrite negbK => /eqP H.\n  by rewrite H in b2I.\nelim: moves b2I => //= b3 bs IH.\nrewrite big_cons sflip_min in_cons => /orP[/eqP<-|/IH->].\n  by rewrite H2 smaxwn.\nby rewrite smaxnw.\nQed.\n\n(* inversion theorem for loss *)\nLemma eval_loss t b1 :\n  ieval t b1 = None -> \n  (forall b, b \\in moves t b1 -> eval (flip t) b = win) -> \n  eval t b1 = loss.\nProof.\nrewrite evalE => ->.\nelim: moves => /= [|b2 bs IH H]; first by rewrite big_nil.\nrewrite big_cons sflip_min H ?IH ?in_cons ?eqxx // => b Hb.\nby rewrite H // in_cons Hb orbT.\nQed.\n\n(* Inversion theorem for draw *)\nLemma eval_draw t b1 b2 :\n  b2 \\in moves t b1 -> eval (flip t) b2 = draw -> \n  (forall b, b \\in moves t b1 -> \n             eval (flip t) b = draw \\/ eval (flip t) b = win) -> \n  eval t b1 = draw.\nProof.\nmove=> b2I Hb2 H; rewrite evalE.\ncase: ieval (liveness t b1) => /= [s /(@sym_equal _ _ _) /negbT|_].\n  by rewrite negbK => /eqP H1; rewrite H1 in b2I.\nelim: moves H b2I => //= b3 bs IH H.\nrewrite big_cons sflip_min in_cons => /orP[/eqP<-| /IH->]; last first.\n- by move=> b4 Hb4; apply: H; rewrite in_cons Hb4 orbT.\n- by case (H b3) => [|-> |->] //; rewrite in_cons eqxx.\nrewrite Hb2.\nelim: (bs) H => [|b4 {IH}bs IH H]; first by rewrite big_nil.\nrewrite big_cons sflip_min smaxA [smax (sflip _) _]smaxC -smaxA IH //.\n  by case: (H b4) => [|->|->] //; rewrite !in_cons eqxx orbT.\nmove=> b5 Hb5; apply: H; rewrite !in_cons orbA [(b5 == _) || _]orbC -orbA.\nby rewrite -in_cons Hb5 orbT.\nQed.\n\n(* First refinement we explictly compute the big op *)\nFixpoint process_eval_rec1 (eval : board -> state) res l :=\n  if l is i :: l1 then\n    let res1 := smin (eval i) res in process_eval_rec1 eval res1 l1\n  else sflip res.\n\nFixpoint eval_rec1 n t b := \n  if ieval t b is some v then v else\n  if n is n1.+1 then \n     process_eval_rec1 (eval_rec1 n1 (flip t)) win (moves t b)\n  else draw.\n\nLemma process_eval_rec1_correct f res l l1 :\n  res = \\smin_(i <- l1) f i ->\n  process_eval_rec1 f res l = sflip (\\smin_(i <- l ++ l1) f i).\nProof.\nelim: l l1 res => /= [|i l IH] l1 res resE; first by rewrite resE.\nhave /IH-> : smin (f i) res = \\smin_(i <- (i :: l1)) f i.\n  by rewrite big_cons //= -resE.\nrewrite !(big_cat, big_cons) /=.\nby rewrite sminC -!sminA [X in smin _ X]sminC.\nQed.\n\nLemma eval_rec1_correct n t b : eval_rec1 n t b = eval_rec n t b.\nProof.\nelim: n t b => //= n IH t b.\ncase: ieval => //.\nrewrite -{2}[moves t b]cats0.\nhave H : win= \\smin_(i <- [::]) eval_rec n (flip t) i by rewrite big_nil.\nrewrite {1}H.\nelim: (moves t b) [::]=> //= i l1 IH1 l2.\nhave := IH1 (i :: l2).\nrewrite IH big_cons // => ->; congr sflip.\nby rewrite !(big_cat, big_cons) /= sminC -sminA [X in smin _ X = _]sminC sminA.\nQed.\n\nLemma ge_process_eval_rec1 eval res l : \n    sflip res <= process_eval_rec1 eval res l.\nProof.\nelim: l res =>  /= [res|i l IH res]; first by apply: leqnn.\napply: leq_trans (IH _).\nrewrite sflip_le.\napply: ge_sminr.\nQed.\n\nDefinition eval1 t b := eval_rec1 (depth b) t b.\n\nLemma eval1_correct t b : eval1 t b = eval t b.\nProof. by apply: eval_rec1_correct. Qed.\n\n(* Second refinement we stop on first loss *)\nFixpoint process_eval_rec2 (eval : board -> state) res l :=\n  if l is i :: l1 then\n    let res1 := smin (eval i) res in \n    if res1 is loss then win else process_eval_rec2 eval res1 l1\n  else sflip res.\n\nFixpoint eval_rec2 n t b := \n  if ieval t b is some v then v else\n  if n is n1.+1 then \n     process_eval_rec2 (eval_rec2 n1 (flip t)) win (moves t b)\n  else draw.\n\nLemma process_eval_rec1_loss f l : process_eval_rec1 f loss l = win.\nProof. by elim: l => //= i l H; rewrite sminnl. Qed. \n\nLemma process_eval_rec2_correct f res l :\n  process_eval_rec2 f res l = process_eval_rec1 f res l.\nProof.\nelim: l res => //= i l IH res.\nby case: (f i); case: res; rewrite /= ?process_eval_rec1_loss.\nQed.\n\nLemma eval_rec2_correct n t b : eval_rec2 n t b = eval_rec n t b.\nProof.\nelim: n t b => //= n IH t b.\ncase: ieval => //.\nrewrite process_eval_rec2_correct.\nhave /process_eval_rec1_correct : \n  win = \\smin_(i <- [::]) (eval_rec2 n (flip t)) i by rewrite big_nil.\nmove=> /(_ (moves t b)); rewrite cats0 => ->.\nby congr (sflip _); apply: eq_bigr => *; apply: IH.\nQed.\n\nDefinition eval2 t b := eval_rec2 (depth b) t b.\n\nLemma eval2_correct t b : eval2 t b = eval t b.\nProof. by apply: eval_rec2_correct. Qed.\n\n(* Third refinement we introduce alpha beta *)\n\nFixpoint process_eval_rec3 (eval :  state -> state -> board -> state) \n                            alpha beta res l : state :=\n  if l is i :: l1 then\n    let res1 := eval alpha beta i in\n    if res <= res1 then process_eval_rec3 eval alpha beta res l1 else\n    (* res1 is good *)\n    if beta <= res1 then process_eval_rec3 eval alpha beta res1 l1\n    else \n    (* we improve max *)\n    let beta := res1 in\n    if beta <= alpha then sflip res1 (* cut *) else \n        process_eval_rec3 eval alpha beta res1 l1 \n    else sflip res.\n  \nLemma ge_process_eval_rec3 eval alpha beta res l : \n    sflip res <= process_eval_rec3 eval alpha beta res l.\nProof.\nelim: l alpha beta res => /= [_ _ res |i l IH alpha beta res].\n  by apply: leqnn.\nhave [E1|E1] := leqP res _; first by apply: IH.\nhave {}E1 : eval alpha beta i <= res by case: (eval _ _) E1; case: res.\nhave [E2|E2] := leqP beta _.\n  apply: leq_trans (IH _ _ _).\n  by rewrite sflip_le.\nhave [E3|E3] := leqP _ alpha; first by case: (eval _ _) E1; case: res.\napply: leq_trans (IH _ _ _).\nby rewrite sflip_le.\nQed.\n\nFixpoint eval_rec3 n t alpha beta b := \n  if ieval t b is some v then v else\n  if n is n1.+1 then \n     process_eval_rec3 (eval_rec3 n1 (flip t)) \n                (sflip beta) (sflip alpha) win (moves t b)\n  else draw.\n\nSection ProcessEvalRec3.\n\nVariable alpha : state.\nVariable f1 : board -> state.\nVariable f2 : state -> state -> board -> state.\n\nHypothesis f1Ha : forall i (b : state),\n  f1 i <= alpha < b -> f2 alpha b i <= alpha.\nHypothesis f1Hb : forall i (b : state),\n  alpha < b <= f1 i -> b <= f2 alpha b i.\nHypothesis f1H : forall i (a b : state),\n  a < b -> a <= f1 i <= b -> f2 a b i = f1 i.\n\nLemma process_eval_rec3_correct_a res (beta : state) l :\n  alpha < beta -> \\smin_(i <- l) f1 i <= alpha ->\n  sflip alpha <= process_eval_rec3 f2 alpha beta res l.\nProof.\nelim: l res beta => [|i l IH] res beta aLb.\n  by rewrite big_nil // => /ge_winE->; apply: ge_loss.\nrewrite big_cons /= => H.\nhave [E1|E1] := leqP res (f2 _ _ _). \n  have [E2|E2] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    apply: leq_trans (ge_process_eval_rec3 _ _ _ _ _) => //.\n    rewrite sflip_le.\n    by apply: leq_trans E1 (f1Ha _); rewrite H.\n  rewrite smin_ler in H; last by apply: ltnW.\n  by apply: IH.\nhave [E2|E2] := leqP beta (f2 _ _ _).\n  have [E3|E3] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    apply: leq_trans (ge_process_eval_rec3 _ _ _ _ _) => //.\n    rewrite sflip_le.\n    by apply: f1Ha; rewrite H.\n  rewrite smin_ler in H; last by apply: ltnW.\n  by apply: IH.\nhave [E3|E3] := leqP (f2 _ _ _) alpha; first by rewrite sflip_le.\napply: IH => //.\nhave [E4|/ltnW E4] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n  rewrite ltnNge in E3; case/negP: E3.\n  apply: f1Ha; rewrite aLb andbT.\n  by move: H; rewrite smin_lel.\nby move: H; rewrite smin_ler.\nQed.\n\nLemma process_eval_rec3_correct_b (res beta : state) l :\n  alpha < beta <= res ->\n  beta <= \\smin_(i <- l) f1 i ->\n  process_eval_rec3 f2 alpha beta res l <= sflip beta.\nProof.\nelim: l res beta => /= [| i l IH] res beta /andP[aLb bLr].\n   by rewrite sflip_le.\nrewrite big_cons /= => H.\nhave [E1|E1] := leqP res _.\n  apply: IH => //; first by rewrite aLb.\n  by apply: leq_trans H (ge_sminr _ _).\nhave [E2|E2] := leqP beta (f2 _ _ _).\n  apply: IH => //; first by rewrite aLb.\n  by apply: leq_trans H (ge_sminr _ _).\nrewrite ltnNge in E2; case/negP: E2.\napply: f1Hb => //; rewrite aLb /=.\nby apply: leq_trans H (ge_sminl _ _).\nQed.\n\nLemma process_eval_rec3_correct (res beta : state) l :\n  alpha < beta -> alpha <= beta <= res ->\n  let res1 := \\smin_(i <- l) f1 i in\n  let res2 := process_eval_rec3 f2 alpha beta res l in\n    alpha <= res1 <= beta -> res2 = sflip res1.\nProof.\nelim: l res beta => [|i l IH] res beta aLsb /andP[aLb bLr]; lazy zeta.\n  rewrite big_nil => /andP[_ /ge_winE rEwin].\n  by move: bLr; rewrite rEwin => /ge_winE->.\nrewrite big_cons /= => H; have /andP[H1 H2] := H.\nhave [E1|E1] := leqP res _.\n  have [E2|/ltnW E2] := leqP (\\smin_(j <- l) f1 j) (f1 i).\n    rewrite smin_ler // in H H1 H2 *.\n    by apply: IH => //; rewrite aLb.\n  rewrite smin_lel // in H H1 H2 *.\n  rewrite f1H // in E1.\n  have f1E : f1 i = beta by apply: sle_antisym => //; apply: leq_trans E1.\n  rewrite f1E in E1 E2 H1 H2 *.\n  have rE : res = beta by apply: sle_antisym.\n  rewrite rE. \n  apply: sle_antisym; last first.\n    by rewrite ge_process_eval_rec3.\n  by apply: process_eval_rec3_correct_b E2; rewrite aLsb leqnn.\nhave [E2|E2] := leqP beta _.\n  have [E3|/ltnW E3] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H H1 H2 *.\n    rewrite f1H // in E1 E2 *.\n    apply: sle_antisym; last first.\n      by rewrite ge_process_eval_rec3.\n    have -> : f1 i = beta by apply: sle_antisym.\n    apply: process_eval_rec3_correct_b (leq_trans E2 E3) => //.\n    by rewrite aLsb leqnn.\n  rewrite smin_ler // in H H1 H2 *.\n  by rewrite IH // aLb.\nhave [E3|E3] := leqP (f2 _ _ _) alpha => //.\n  have [E4|E4] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite (smin_lel E4) in H H1 H2 *.\n    by rewrite (f1H aLsb H).\n  rewrite smin_ler // in H H1 H2 *; last by apply: ltnW.\n  have H3 : alpha < f1 i by apply: leq_ltn_trans H1 E4.\n  have H4 : alpha <= f1 i by apply: ltnW.\n  have [E5|E5] := leqP (f1 i) beta.\n    have H4E5 : alpha <= f1 i <= beta by rewrite H4.\n    rewrite (f1H aLsb H4E5) in E1 E2 E3 *.\n    by rewrite ltnNge in H3; case/negP: H3.\n  rewrite ltnNge in E2; case/negP: E2.\n  by apply: f1Hb; rewrite // aLsb /= ltnW.\nhave [E4|E4] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n  rewrite smin_lel // in H H1 H2 *.\n  rewrite (f1H aLsb H) in E1 E2 E3 *.\n  apply: sle_antisym; last by rewrite ge_process_eval_rec3.\n  apply: process_eval_rec3_correct_b E4 => //.\n  by rewrite E3 leqnn.\nrewrite smin_ler // in H H1 H2 *; last by apply: ltnW.\nhave [E5|E5] := leqP (f1 i) beta.\n  have H3 : alpha < f1 i by apply: leq_ltn_trans H1 E4.\n  have H4 : alpha <= f1 i by apply: ltnW.\n  have H4E5 : alpha <= f1 i <= beta by rewrite H4.\n  rewrite (f1H aLsb H4E5) in E1 E2 E3 *.\n  rewrite IH //; last by rewrite H1 ltnW.\n  by rewrite (ltnW E3) leqnn.\nrewrite ltnNge in E2; case/negP: E2.\nby apply: f1Hb; rewrite // aLsb ltnW.\nQed.\n\nEnd ProcessEvalRec3.\n\nLemma eval_rec3_correct n t (alpha beta : state) b :\n  alpha < beta ->\n  [/\\ \n    eval_rec n t b <= alpha -> eval_rec3 n t alpha beta b <= alpha,\n    beta <= eval_rec n t b  -> beta <= eval_rec3 n t alpha beta b &\n    alpha <= eval_rec n t b <= beta ->\n    eval_rec3 n t alpha beta b = eval_rec n t b].\nProof.\nelim: n t alpha beta b => //= n IH t alpha beta b aLb.\ncase: ieval => //; split.\n- rewrite -{1 3}(sflipK alpha) !sflip_le => H.\n  apply: process_eval_rec3_correct_b (H).\n    move=> i b1 /andP[H1 H2]; have [_ ->// _] := IH (flip t) _ _ i H1.\n  by rewrite sflip_lt aLb le_win.\n- rewrite -{1 2}(sflipK beta) !sflip_le => H.\n  apply: process_eval_rec3_correct_a H => //; last first.\n    by rewrite sflip_lt.\n  move=> b1 s1 /andP[H1 H2].\n  by have [/(_ H1)-> _ _] := (IH (flip t) (sflip beta) s1 b1 H2).\nrewrite -{1}(sflipK alpha) -{1}(sflipK beta) !sflip_le => /andP[H1 H2].\napply: process_eval_rec3_correct => //.\n- move=> i a1 /andP[H a1L].\n  by have [_ /(_ a1L)] := IH (flip t) _ a1 i H.\n- move=> i a1 b1 a1Lsb1 /andP[a1Le eLb1].\n  have [_ _ ->//]:= IH (flip t) a1 b1 i a1Lsb1.\n  by rewrite a1Le.\n- by rewrite sflip_lt.\n- by rewrite le_win sflip_le ltnW.\nby rewrite H2.\nQed. \n\nDefinition eval3 t b := eval_rec3 (depth b) t loss win b.\n\nLemma eval3_correct t b : eval3 t b = eval t b.\nProof.\nhave [_ _ H] := eval_rec3_correct (depth b) t b (isT : loss < win).\nby apply: H => //; rewrite ge_loss le_win.\nQed.\n\n(* We are trying to add intermediate *)\n\nInductive estate := eloss | lossdraw | edraw | drawwin | ewin.\n\nCoercion es2n e :=\n  match e with \n  | eloss => 1\n  | lossdraw => 2 \n  | edraw  => 3 \n  | drawwin => 4\n  | ewin => 5\nend.\n\nImplicit Type es : estate.\n\nDefinition eqes es1 es2 := (es1 == es2 :> nat).\n\nLemma eqesP : Equality.axiom eqes.\nProof. by do 2!case; constructor. Qed.\n\nCanonical estate_eqMixin := EqMixin eqesP.\nCanonical estate_eqType := Eval hnf in EqType estate estate_eqMixin.\n\nDefinition esflip e :=\n  match e with \n  | eloss => ewin\n  | lossdraw => drawwin \n  | edraw  => edraw\n  | drawwin => lossdraw\n  | ewin => eloss\nend.\n\nLemma esflipE es1 es2 : (esflip es1 == esflip es2) = (es1 == es2).\nProof. by case: es1; case: es2. Qed.\n\nDefinition es2s e :=\n  match e with \n  | eloss => Some loss\n  | lossdraw => None\n  | edraw  => Some draw\n  | drawwin => None\n  | ewin => Some win\nend.\n\nCoercion s2es e :=\n  match e with \n  | loss => eloss\n  | draw  => edraw\n  | win => ewin\nend.\n\nLemma s2esK e : es2s (s2es e) = Some e.\nProof. by case: e. Qed.\n\nLemma ge_ewinE es : ewin <= es -> es = ewin.\nProof. by case: es. Qed.\n\nLemma le_ewin es : es <= ewin.\nProof. by case: es. Qed.\n\nDefinition esmin es1 es2 := if es1 <= es2 then es1 else es2.\n\nLemma esminnw es : esmin es ewin = es.\nProof. by case: es. Qed.\n\nLemma es2ns2esK s : es2n (s2es s) = s2n s.\nProof. by case: s. Qed.\n\nLemma esle_antisym es1 es2 : es1 <= es2 -> es2 <= es1 -> es1 = es2.\nProof. by case: es1; case: es2. Qed.\n\nLemma ge_esminl es1 es2 : esmin es1 es2 <= es1.\nProof. by case: es1; case: es2. Qed.\n\nLemma ge_esminr es1 es2 : esmin es1 es2 <= es2.\nProof. by case: es1; case: es2. Qed.\n\nLemma esmin_ler es1 es2 : es2 <= es1 -> esmin es1 es2 = es2.\nProof. by case: es1; case: es2. Qed.\n\nLemma esmin_lel es1 es2 : es1 <= es2 -> esmin es1 es2 = es1.\nProof. by case: es1; case: es2. Qed.\n\nLemma esflipK : involutive esflip.\nProof. by case. Qed.\n\nLemma esflip_le es1 es2 : (esflip es1 <= esflip es2) = (es2 <= es1).\nProof. by case: es1; case: es2. Qed.\n\nLemma esflip_lt es1 es2 : (esflip es1 < esflip es2) = (es2 < es1).\nProof. by case: es1; case: es2. Qed.\n\nLemma esminwn : left_id ewin esmin.\nProof. by case. Qed.\n\nLemma s2es_flip s : (sflip s) = esflip s :> estate.\nProof. by case: s. Qed.\n\nLemma es2n_flip s : s2n (sflip s) = es2n (esflip (s2es s)).\nProof. by case: s. Qed.\n\nLemma le_elossE es : es <= eloss -> es = eloss.\nProof. by case: es. Qed.\n\nDefinition etop e :=\n  match e with \n  | eloss => eloss\n  | lossdraw => edraw\n  | edraw  => edraw\n  | drawwin => ewin\n  | ewin => ewin\nend.\n\nDefinition ebot e :=\n  match e with \n  | eloss => eloss\n  | lossdraw => eloss\n  | edraw  => edraw\n  | drawwin => edraw\n  | ewin => ewin\nend.\n\nDefinition is_state e :=\n  match e with \n  | eloss => true\n  | lossdraw => false\n  | edraw  => true\n  | drawwin => false\n  | ewin => true\nend.\n\nLemma is_state_es s : is_state (s2es s).\nProof. by case: s. Qed.\n\nDefinition econtained s es := ebot es <= s <= etop es.\n\nFixpoint process_eval_rec4 (eval :  estate -> estate -> board -> estate) \n                            alpha beta res l : estate :=\n  if l is i :: l1 then\n    let res1 := eval alpha beta i in\n    if res <= res1 then process_eval_rec4 eval alpha beta res l1 else\n    (* res1 is good *)\n    if beta <= res1 then process_eval_rec4 eval alpha beta res1 l1\n    else \n    (* we improve max *)\n    if res1 <= alpha then \n      (if res1 is edraw then \n           if l1 is _ :: _ then drawwin else esflip res1 \n        else esflip res1) (* cut *) else \n        process_eval_rec4 eval alpha res1 res1 l1 \n    else esflip res.\n  \nLemma ge_process_eval_rec4 eval alpha beta res l : \n    esflip res <= process_eval_rec4 eval alpha beta res l.\nProof.\nelim: l alpha beta res => /= [_ _ res |i l IH alpha beta res] //.\nhave [E1|E1] := leqP res _; first by apply: IH.\nhave {}E1 : eval alpha beta i <= res by case: (eval _ _) E1; case: res.\nhave [E2|E2] := leqP beta _.\n  by apply: leq_trans (IH _ _ _); rewrite esflip_le.\nhave [E3|E3] := leqP _ alpha.\n  by case: (eval _ _) E1; case: res; case: (l).\nby apply: leq_trans (IH _ _ _); rewrite esflip_le.\nQed.\n\n\nFixpoint eval_rec4 n t alpha beta b := \n  if ieval t b is some v then s2es v else\n  if n is n1.+1 then \n     process_eval_rec4 (eval_rec4 n1 (flip t)) \n                (esflip beta) (esflip alpha) win (moves t b)\n  else edraw.\n\nSection ProcessEvalRec4.\n\nVariable f1 : board -> state.\nVariable f2 : estate -> estate -> board -> estate.\n\n(** loss draw                                                                 *)\n\nHypothesis H4loss_draw_loss : \n  forall i, f1 i = loss -> f2 eloss edraw i = eloss.\nHypothesis H4loss_draw_draw : \n  forall i, f1 i = draw -> edraw <= f2 eloss edraw i <= drawwin.\nHypothesis H4loss_draw_win : \n  forall i, f1 i = win -> drawwin <= f2 eloss edraw i.\n\nLemma H4loss_draw_ge i : draw <= f1 i -> edraw <= f2 eloss edraw i.\nProof.\ncase: f1 (@H4loss_draw_draw i) (@H4loss_draw_win i) => //.\n  by move=> _ /(_ (refl_equal _)) /(leq_trans _) H _; rewrite H.\nby move=> /(_ (refl_equal _)) /andP[].\nQed.\n\nLemma H4loss_draw_le i : f1 i <= draw -> f2 eloss edraw i <= drawwin.\nProof.\ncase: f1 (@H4loss_draw_loss i) (@H4loss_draw_draw i) => //.\n  by move=> /(_ (refl_equal _))->.\nby move=> _ /(_ (refl_equal _)) /andP[].\nQed.\n\nLemma process_eval_rec4_loss_draw_le (res : estate) l :\n  draw <= res ->\n  draw <= \\smin_(i <- l) f1 i ->\n  process_eval_rec4 f2 eloss edraw res l <= draw.\nProof.\nelim: l res => [|i l IH] res; first by rewrite big_nil (esflip_le _ edraw).\nrewrite big_cons [process_eval_rec4 _ _ _ _ _]/= => H1 H2.\nhave [E1|E1] := leqP res (f2 _ _ _).\n  by apply: IH => //; apply: leq_trans H2 (ge_sminr _ _).\nrewrite ifT; last first.\n  by apply: H4loss_draw_ge; apply: leq_trans H2 (ge_sminl _ _).\napply: IH => //.\n  by apply: H4loss_draw_ge; apply: leq_trans H2 (ge_sminl _ _).\nby apply: leq_trans H2 (ge_sminr _ _).\nQed.\n\nLemma process_eval_rec4_loss_draw_ge (res : estate) l :\n  \\smin_(i <- l) f1 i <= draw ->\n   lossdraw <= process_eval_rec4 f2 eloss edraw res l.\nProof.\nelim: l res => [|i l IH] res; first by rewrite big_nil.\nrewrite big_cons [process_eval_rec4 _ _ _ _ _]/= => H.\nhave [E1|E1] := leqP res (f2 _ _ _).\n  have [E2|/ltnW E2] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    apply: leq_trans (ge_process_eval_rec4 _ _ _ _ _).\n    rewrite (esflip_le drawwin).\n    by apply: leq_trans E1 (H4loss_draw_le _).\n  rewrite smin_ler // in H.\n  by apply: IH.\nhave [E2|E2] := leqP edraw (f2 _ _ _).\n  have [E3|/ltnW E3] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    apply: leq_trans (ge_process_eval_rec4 _ _ _ _ _).\n    rewrite (esflip_le drawwin).\n    by apply: leq_trans _ (H4loss_draw_le _).\n  rewrite smin_ler // in H.\n  by apply: IH.\nhave [E3|E3] := leqP (f2 eloss edraw i) eloss.\n  by rewrite (le_elossE E3).\napply: leq_trans (ge_process_eval_rec4 _ _ _ _ _).\nrewrite (esflip_le drawwin).\nby apply: leq_trans (ltnW E2) _.\nQed.\n\nLemma process_eval_rec4_loss_draw_loss (res : estate) l :\n  \\smin_(i <- l) f1 i = loss ->\n   process_eval_rec4 f2 eloss edraw res l = ewin.\nProof.\nelim: l res => [|i l IH] res; first by rewrite big_nil.\nrewrite big_cons [process_eval_rec4 _ _ _ _ _]/= => H.\nhave [E1|E1] := leqP res (f2 _ _ _).\n  have [E2|/ltnW E2] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    apply: ge_ewinE; rewrite -[ewin]/(esflip eloss).\n    have -> : res = eloss by apply: le_elossE; rewrite -(H4loss_draw_loss H).\n    by apply: ge_process_eval_rec4.\n  rewrite smin_ler // in H.\n  by apply: IH.\nhave [E2|E2] := leqP _ (f2 _ _ _).\n  have [E3|/ltnW E3] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    rewrite H4loss_draw_loss //.\n    apply: ge_ewinE; rewrite -[ewin]/(esflip eloss).\n    by apply: ge_process_eval_rec4.\n  rewrite smin_ler // in H.\n  by apply: IH.\nrewrite H4loss_draw_loss //=.\nby case: f1 (@H4loss_draw_draw i) (@H4loss_draw_win i) => // [_|];\n   move=> /(_ (refl_equal _)); case: f2 E2.\nQed.\n\nLemma process_eval_rec4_loss_draw_draw (res : estate) l :\n  \\smin_(i <- l) f1 i = draw -> draw <= res ->\n   lossdraw <= process_eval_rec4 f2 eloss edraw res l <= draw.\nProof.\nmove=> H1 H2.\nrewrite process_eval_rec4_loss_draw_ge ?H1 //.\nby rewrite process_eval_rec4_loss_draw_le ?H1.\nQed.\n\nLemma process_eval_rec4_loss_draw_win (res : estate) l :\n  \\smin_(i <- l) f1 i = win -> drawwin <= res ->\n   process_eval_rec4 f2 eloss edraw res l <= lossdraw.\nProof.\nelim: l res => [|i l IH] res.\n  by rewrite big_nil /= (esflip_le _ drawwin).\nrewrite big_cons [process_eval_rec4 _ _ _ _ _]/= => H1 H2.\nhave [H3 H4] : f1 i = win /\\ \\smin_(j <- l) f1 j = win.\n  have [E1|/ltnW E1] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H1 *; split => //.\n    by apply: ge_winE; rewrite -{1}H1.\n  rewrite smin_ler // in H1 *; split => //.\n  by apply: ge_winE; rewrite -{1}H1.\nhave [E1|E1] := leqP res (f2 _ _ _).\n  by apply: IH.\nhave [E2|E2] := leqP _ (f2 _ _ _).\n  apply: IH => //.\n  by apply: H4loss_draw_win.\nrewrite ifN.\n  rewrite ltnNge in E2; case/negP: E2.\n  by apply: leq_trans (H4loss_draw_win _).\nrewrite -ltnNge.\nby apply: leq_trans (H4loss_draw_win _).\nQed.\n\n(** draw win *)\n\nHypothesis H4draw_win_win : \n  forall i, f1 i = win -> f2 edraw ewin i = ewin.\nHypothesis H4draw_win_draw : \n  forall i, f1 i = draw -> lossdraw <= f2 edraw ewin i <= edraw.\nHypothesis H4draw_win_loss: \n  forall i, f1 i = loss -> f2 edraw ewin i <= lossdraw.\n\nLemma H4draw_win_le i : f1 i <= draw -> f2 edraw ewin i <= edraw.\nProof.\ncase: f1 (@H4draw_win_loss i) (@H4draw_win_draw i) => //.\n  by move=> /(_ (refl_equal _)) /leq_trans->.\nby move=>  _ /(_ (refl_equal _)) /andP[].\nQed.\n\nLemma H4draw_win_ge i : draw <= f1 i -> lossdraw <= f2 edraw ewin i.\nProof.\ncase: f1 (@H4draw_win_draw i) (@H4draw_win_win i) => //.\n  by move=> _ /(_ (refl_equal _))->.\nby move=> /(_ (refl_equal _)) /andP[].\nQed.\n\nLemma process_eval_rec4_draw_win_le (res : estate) l :\n  \\smin_(i <- l) f1 i <= draw ->\n  edraw <= process_eval_rec4 f2 edraw ewin res l.\nProof.\nelim: l res => [|i l IH] res; first by rewrite big_nil.\nrewrite big_cons [process_eval_rec4 _ _ _ _ _]/= => H.\nhave [E1|E1] := leqP res (f2 _ _ _).\n  have [E2|/ltnW E2] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    apply: leq_trans (ge_process_eval_rec4 _ _ _ _ _).\n    rewrite (esflip_le edraw).\n    by apply: leq_trans E1 (H4draw_win_le _).\n  rewrite smin_ler // in H.\n  by apply: IH.\nhave [E2|E2] := leqP ewin (f2 edraw ewin i).\n  have [E3|/ltnW E3] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    rewrite leqNgt in E2; case/negP: E2.\n    by apply: leq_ltn_trans (H4draw_win_le _) _.\n  rewrite smin_ler // in H.\n  by apply: IH.\nhave [E3|E3] := leqP (f2 _ _ i) draw.\n  by case: f2 E3 => //; case: (l).\nhave [E4|E4] := leqP (f1 i) draw.\n  rewrite ltnNge in E3; case/negP: E3.\n  by apply: H4draw_win_le.\nrewrite H4draw_win_win // in E2.\napply: ge_winE.\nby case: f1 E4.\nQed.\n\nLemma process_eval_rec4_draw_win_ge (res : estate) l :\n  lossdraw <= res ->\n  draw <= \\smin_(i <- l) f1 i ->\n  process_eval_rec4 f2 edraw ewin res l <= drawwin.\nProof.\nelim: l res => [|i l IH] res; first by rewrite big_nil (esflip_le _ lossdraw).\nrewrite big_cons [process_eval_rec4 _ _ _ _ _]/= => H1 H2.\nhave [E1|E1] := leqP res (f2 _ _ _).\n  apply: IH => //.\n  by apply: leq_trans H2 (ge_sminr _ _).\nhave [E2|E2] := leqP ewin (f2 _ _ _).\n  apply: IH => //.\n    apply: H4draw_win_ge.\n    by apply: leq_trans H2 (ge_sminl _ _).\n  by apply: leq_trans H2 (ge_sminr _ _).\nhave [E3|E3] := leqP (f2 edraw ewin i) edraw.\n  have : lossdraw <= (f2 edraw ewin i).\n    apply: H4draw_win_ge (leq_trans H2 (ge_sminl _ _)).\n  by case: f2 => //=; case: (l).\nhave [E4|E4] := leqP (f1 i) draw.\n  rewrite ltnNge in E3; case/negP: E3.\n  by apply: H4draw_win_le.\nrewrite H4draw_win_win // in E2.\napply: ge_winE.\nby case: f1 E4.\nQed.\n\nLemma process_eval_rec4_draw_win_win (res : estate) l :\n  res = win ->\n  \\smin_(i <- l) f1 i = win ->\n   process_eval_rec4 f2 edraw ewin res l = eloss.\nProof.\nelim: l res => [|i l IH] res; first by rewrite big_nil => ->.\nrewrite big_cons [process_eval_rec4 _ _ _ _ _]/= => H1 H2.\nhave [H3 H4] : f1 i = win /\\ \\smin_(j <- l) f1 j = win.\n  have [E1|/ltnW E1] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H2; split => //.\n    by apply: ge_winE; rewrite -{1}H2.\n  rewrite smin_ler // in H2; split => //.\n  by apply: ge_winE; rewrite -{1}H2.\nrewrite H4draw_win_win // H1 /=.\nby apply: IH.\nQed.\n\nLemma process_eval_rec4_draw_win_draw (res : estate) l :\n  \\smin_(i <- l) f1 i = draw -> lossdraw <= res ->\n   edraw <= process_eval_rec4 f2 edraw ewin res l <= drawwin.\nProof.\nmove=> H1 H2.\nrewrite process_eval_rec4_draw_win_ge ?H1 //.\nby rewrite process_eval_rec4_draw_win_le ?H1.\nQed.\n\nLemma process_eval_rec4_draw_win_loss (res : estate) l :\n  \\smin_(i <- l) f1 i = loss ->\n   drawwin <= process_eval_rec4 f2 edraw ewin res l.\nProof.\nelim: l res => [|i l IH] res; first by rewrite big_nil.\nrewrite big_cons [process_eval_rec4 _ _ _ _ _]/= => H.\nhave [E1|E1] := leqP res (f2 _ _ _).\n  have [E2|/ltnW E2] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    apply: leq_trans (ge_process_eval_rec4 _ _ _ _ _).\n    rewrite (esflip_le lossdraw).\n    apply: leq_trans E1 _.\n    by apply: H4draw_win_loss.\n  rewrite smin_ler // in H.\n  by apply: IH.\nhave [E2|E2] := leqP ewin (f2 _ _ _).\n  have [E3|/ltnW E3] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    have := H4draw_win_loss H.\n    by rewrite leqNgt (leq_trans _ E2).\n  rewrite smin_ler // in H.\n  by apply: IH.\nhave [E3|E3] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n  rewrite smin_lel // in H.\n  by case: f2 (H4draw_win_loss H).\nrewrite smin_ler // in H; last by apply: ltnW.\nhave [E4|E4] := leqP (f2 _ _ _) edraw.\n  have : lossdraw <= f2 edraw ewin i.\n    apply: H4draw_win_ge.\n    by move: E3; rewrite H; case: f1.\n  case: f2 E4 => //=.\n  by case: (l) H => //; rewrite big_nil.\nmove: E3 E2; rewrite H.\ncase: f1 (@H4draw_win_draw i) (@H4draw_win_win i) => //.\n  by move=> _ -> //.\nmove=> /(_ (refl_equal _)).\nby rewrite [_ <= edraw]leqNgt E4 andbF.\nQed.\n\n(* loss win *)\n\nHypothesis H4loss_win : forall i, f2 eloss ewin i = f1 i.\n\nLemma process_eval_rec4_loss_win_lt (a res : estate) l :\n  a <= res ->\n  a < \\smin_(i <- l) f1 i -> \n  process_eval_rec4 f2 eloss ewin res l <= esflip a.\nProof.\nelim: l res => [|i l IH] res aLr; first by rewrite big_nil esflip_le.\nrewrite big_cons => /= aLs; rewrite H4loss_win.\nhave [E1|E1] := leqP res _.\n  apply: IH => //.\n  by apply: leq_trans aLs (ge_sminr _ _).\nhave [E2|E2] := leqP ewin _.\n  apply: IH => //.\n    by rewrite (ge_ewinE E2) // le_ewin.\n  by apply: leq_trans aLs (ge_sminr _ _).\nrewrite ifN; last first.\n  rewrite -ltnNge es2ns2esK.\n  apply: leq_ltn_trans _ (leq_trans aLs (ge_sminl _ _)).\n  by case: (a).\nhave [E3|E3] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n  rewrite smin_lel // in aLs *.\n  have H : f1 i = draw.\n    by case: f1 E2 E3 aLs => //; case: (\\smin_(_ <- _) _) => //; case: (a).\n  rewrite H in E1 E3 aLs *.\n  apply: leq_trans (process_eval_rec4_loss_draw_le _ _) _ =>//. \n  rewrite (esflip_le edraw).\n  by apply: ltnW.\nrewrite smin_ler // in aLs *; last by apply: ltnW.\nsuff -> : f1 i = win.\n  by apply: IH => //; apply: le_ewin.\nby case: f1 E3 aLs => //; case: (\\smin_(_ <- _) _) => //; case: (a).\nQed.\n\nLemma process_eval_rec4_loss_win (res : estate) l :\n  \\smin_(i <- l) f1 i <= res ->\n  process_eval_rec4 f2 eloss ewin res l = sflip (\\smin_(i <- l) f1 i).\nProof.\nelim: l res => [|i l IH] res; first by rewrite big_nil /= => /ge_ewinE ->.\nrewrite big_cons [process_eval_rec4 _ _ _ _ _]/= => H.\nrewrite H4loss_win !es2ns2esK.\nhave [E1|E1] := leqP res (f1 i).\n  have [E2|E2] := leqP (\\smin_(j <- l) f1 j) (f1 i).\n    rewrite smin_ler // in H *.\n    by apply: IH.\n  rewrite smin_lel // in H *; last by apply: ltnW.\n  apply: esle_antisym; last first.\n    apply: leq_trans (ge_process_eval_rec4 _ _ _ _ _).\n    by rewrite es2ns2esK es2n_flip esflip_le es2ns2esK.\n  rewrite es2ns2esK es2n_flip.\n  by apply: process_eval_rec4_loss_win_lt; rewrite es2ns2esK.\nrewrite ifN; last first.\n  by rewrite -leqNgt -ltnS (leq_trans E1) // le_ewin.\nhave [E2|E2] := leqP (f1 i) loss.\n  by rewrite (le_lossE E2) /= sminln.\nhave H3 : f1 i = draw.\n  apply: sle_antisym.\n    by case: f1 E1; case: (res).\n  by case: f1 E2.\nrewrite H3 in H E1 *.\nhave [E3|E3] := leqP draw (\\smin_(j <- l) f1 j).\n  rewrite smin_lel // in H *.\n  apply: esle_antisym; rewrite es2ns2esK es2n_flip.\n    by apply: process_eval_rec4_loss_draw_le.\n  by apply: ge_process_eval_rec4.\nsuff H4 : \\smin_(j <- l) f1 j = loss.\n  rewrite H4.\n  by apply: process_eval_rec4_loss_draw_loss.\napply: sle_antisym.\n  by case: (\\smin_(_ <- _) _) E3.\nby apply: ge_loss.\nQed.\n\nEnd ProcessEvalRec4.\n\nLemma eval_rec4_correct n t i :\n  let f1 := eval_rec n t in\n  let f2 := eval_rec4 n t in\n  [/\\ \n    [/\\\n      f1 i = loss -> f2 eloss edraw i = eloss,\n      f1 i = draw -> edraw <= f2 eloss edraw i <= drawwin &\n      f1 i = win -> drawwin <= f2 eloss edraw i],\n    [/\\\n      f1 i = win -> f2 edraw ewin i = ewin,\n      f1 i = draw -> lossdraw <= f2 edraw ewin i <= draw &\n      f1 i = loss -> f2 edraw ewin i <= lossdraw] &\n      f2 eloss ewin i = f1 i].\nProof.\nelim: n t i => /= [|n IH] t i;\n  case: ieval => //; try by case.\nrepeat split => //.\n- rewrite -(sflipK loss) => /sflip_inj H.\n  rewrite -(esflipK eloss).\n  apply: process_eval_rec4_draw_win_win H => // i1.\n  by case:  (IH (flip t) i1) => _ [].\n- rewrite -(sflipK draw) => /sflip_inj H.\n  by apply: process_eval_rec4_draw_win_draw H _ => // i1;\n     case:  (IH (flip t) i1) => _ [].\n- rewrite -(sflipK win) => /sflip_inj H.\n  by apply: process_eval_rec4_draw_win_loss H => // i1;\n     case:  (IH (flip t) i1) => _ [].\n- rewrite -(sflipK win) => /sflip_inj H.\n  by apply: process_eval_rec4_loss_draw_loss H => i1;\n     case:  (IH (flip t) i1) => [] [].\n- rewrite -(sflipK draw) => /sflip_inj H.\n  by apply: process_eval_rec4_loss_draw_draw H _ => // i1;\n     case:  (IH (flip t) i1) => [] [].\n- rewrite -(sflipK loss) => /sflip_inj H.\n  by apply: process_eval_rec4_loss_draw_win H _ => // i1;\n     case:  (IH (flip t) i1) => [] [].\napply: process_eval_rec4_loss_win => //.\n- by move=> i1; case: (IH (flip t) i1) => [] [].\n- by move=> i1; case: (IH (flip t) i1) => [] [].\n- by move=> i1; case: (IH (flip t) i1) => [] [].\n- by move=> i1; case: (IH (flip t) i1) => [] [].\nby rewrite -es2ns2esK; apply: le_ewin.\nQed.\n\nDefinition eval4 t b := eval_rec4 (depth b) t eloss ewin b.\n\nLemma eval4_correct t b : eval4 t b = eval t b.\nProof.\nrewrite /eval4.\nby have [_ _  ->] := eval_rec4_correct (depth b) t b.\nQed.\n\n(* Adding hash table *)\n\nDefinition htable := turn -> board -> option estate.\n\nImplicit Types ht : htable.\nImplicit Types t : turn.\n\nDefinition hget ht t b := ht t b.\n\nDefinition hput ht t b e : htable := \n  fun t1 b1 => if (t1 == t) && (b1 == b) then some e else hget ht t1 b1.\n\nDefinition ht_valid ht := \n    forall b t e, hget ht t b = Some e -> econtained (eval t b) e.\n\nInductive pres : Type := Pres of htable & estate. \n\nCoercion pres2state (p : pres ) := let (_, r) := p in r.\nCoercion pres2table (p : pres ) := let (h, _) := p in h.\n\nLemma hput_correct ht t b e :\n  ht_valid ht -> econtained (eval t b) e -> ht_valid (hput ht t b e).\nProof.\nmove=> Hv He b1 t1 e1.\nrewrite /hget /hput.\ncase: eqP=> [->|_ /Hv] //=.\nby case: eqP=> [-> [<-]|_ /Hv].\nQed.\n\nSection PR5.\n\nVariable eval : estate -> estate -> htable -> board -> pres. \nVariable alpha : estate.\n\nFixpoint process_eval_rec5 beta ht res l : pres :=\n  if l is i :: l1 then\n    let (ht1, res1) := eval alpha beta ht i in\n    if res <= res1 then process_eval_rec5 beta ht1 res l1 else\n    (* res1 is good *)\n    if beta <= res1 then process_eval_rec5 beta ht1 res1 l1\n    else \n    (* we improve max *)\n    if res1 <= alpha then \n      (if res1 is edraw then \n           if l1 is _ :: _ then Pres ht1 drawwin else Pres ht1 (esflip res1) \n        else Pres ht1 (esflip res1)) (* cut *) else \n        process_eval_rec5 res1 ht1 res1 l1 \n    else Pres ht (esflip res).\n\nEnd PR5.\n\nLemma ge_process_eval_rec5 eval alpha beta res ht l : \n    esflip res <= process_eval_rec5 eval alpha beta ht res l.\nProof.\nelim: l beta res ht => /= [_ _ res |i l IH beta res ht] //.\ncase E : eval => [ht1 res1].\nhave [E1|E1] := leqP res _; first by apply: IH.\nhave {}E1 : res1 <= res by apply: ltnW.\nhave [E2|E2] := leqP beta _.\n  by apply: leq_trans (IH _ _ _); rewrite esflip_le.\nhave [E3|E3] := leqP _ alpha.\n  by case: (res1) E1; case: res; case: (l).\nby apply: leq_trans (IH _ _ _); rewrite esflip_le.\nQed.\n\nInductive ares := Ares of bool & estate & estate & estate.\n\nFixpoint eval_rec5 n t alpha beta ht b := \n  if ieval t b is some v then Pres ht (s2es v) else\n  let score := hget ht t b in \n  let (flag, alpha1, beta1, res1) := \n    if score  is Some res then\n      if is_state res then Ares true alpha beta res \n      else\n        if res is drawwin then \n          (* this is drawwin *)\n          if beta is edraw\n            then Ares true alpha beta res\n            else Ares false edraw beta res\n          else \n          (* this is lossdraw *)\n          if alpha is edraw\n            then Ares true alpha beta res\n            else  Ares false alpha edraw res\n    else Ares false alpha beta ewin\n  in\n  if flag then Pres ht res1 else\n  if n is n1.+1 then \n    let (ht1, res2) :=\n     process_eval_rec5 (eval_rec5 n1 (flip t)) \n                (esflip beta1) (esflip alpha1) ht win (moves t b) in\n    let res3 := if some (esflip res2) == score then edraw else res2 in\n    let ht2 := hput ht1 t b res3 in Pres ht2 res3\n  else Pres ht edraw.\n\nSection ProcessEvalRec5.\n\nVariable f1 : board -> state.\nVariable f2 : estate -> estate -> htable -> board -> pres.\n\nDefinition Hiv (l : seq board) :=  \n  [/\\ \n    [/\\\n      forall i ht, i \\in l -> ht_valid ht ->  ht_valid (f2 eloss edraw ht i),\n      forall i ht , i \\in l -> ht_valid ht -> f1 i = loss -> \n        f2 eloss edraw ht i = eloss :> estate,\n      forall i ht , i \\in l -> ht_valid ht -> f1 i = draw -> \n        edraw <= f2 eloss edraw ht i <= drawwin &\n      forall i ht, i \\in l -> ht_valid ht ->  f1 i = win ->\n        drawwin <= f2 eloss edraw ht i],\n    [/\\\n      forall i ht, i \\in l -> ht_valid ht -> ht_valid (f2 edraw ewin ht i),\n      forall i ht, i \\in l -> ht_valid ht -> \n        f1 i = win -> f2 edraw ewin ht i = ewin :> estate,\n      forall i ht, i \\in l -> ht_valid ht ->\n        f1 i = draw -> lossdraw <= f2 edraw ewin ht i <= draw &\n      forall i ht, i \\in l -> ht_valid ht ->\n        f1 i = loss -> f2 edraw ewin ht i <= lossdraw] &\n    ((forall i ht, i \\in l -> \n      ht_valid ht ->  ht_valid (f2 eloss ewin ht i)) /\\\n     forall i ht, i \\in l -> \n      ht_valid ht -> f2 eloss ewin ht i = f1 i :> estate)].\n\nLemma Hiv_cons i l : Hiv (i :: l) -> Hiv l.\nProof.\nmove=> [[H1 H2 H3 H4] [H5 H6 H7 H8] [H9 H10]].\nby  (repeat split) => i1 ht Hi1 *;\n     (apply H1 || apply H2 || apply H3 || apply H4 || apply H5 ||\n      apply H6 || apply H7 || apply H8 || apply H9 || apply H10) => //;\n     rewrite in_cons Hi1 orbT.\nQed.\n\nLemma Hiv_hd i l :\n  Hiv (i :: l) ->\n  [/\\ \n    [/\\\n      forall ht, ht_valid ht -> ht_valid (f2 eloss edraw ht i),\n      forall ht,\n        ht_valid ht -> f1 i = loss -> f2 eloss edraw ht i = eloss :> estate,\n      forall ht,\n        ht_valid ht -> f1 i = draw -> edraw <= f2 eloss edraw ht i <= drawwin &\n      forall ht, \n        ht_valid ht ->  f1 i = win -> drawwin <= f2 eloss edraw ht i],\n    [/\\\n      forall ht, ht_valid ht -> ht_valid (f2 edraw ewin ht i),\n      forall ht, ht_valid ht -> \n        f1 i = win -> f2 edraw ewin ht i = ewin :> estate,\n      forall ht, ht_valid ht ->\n        f1 i = draw -> lossdraw <= f2 edraw ewin ht i <= draw &\n      forall ht, ht_valid ht ->\n        f1 i = loss -> f2 edraw ewin ht i <= lossdraw] &\n    ((forall ht, ht_valid ht ->  ht_valid (f2 eloss ewin ht i)) /\\\n     forall ht, ht_valid ht -> f2 eloss ewin ht i = f1 i :> estate)].\nProof.\nmove=> [[H1 H2 H3 H4] [H5 H6 H7 H8] [H9 H10]].\nby (repeat split) => *;\n     (apply H1 || apply H2 || apply H3 || apply H4 || apply H5 ||\n      apply H6 || apply H7 || apply H8 || apply H9 || apply H10) => //;\n     rewrite in_cons eqxx.\nQed.\n\n\n(** loss draw                                                                 *)\n\nLemma H5loss_draw_table ht i l :\n  Hiv (i :: l) -> ht_valid ht -> ht_valid (f2 eloss edraw ht i).\nProof. by move/Hiv_hd=> [] [H _ _ _] _ _; apply: H. Qed.\n\nLemma H5loss_draw_loss ht i l :\n  Hiv (i :: l) -> \n  ht_valid ht -> f1 i = loss -> f2 eloss edraw ht i = eloss :> estate.\nProof. by move/Hiv_hd=> [] [_ H _ _] _ _; apply: H. Qed.\n\nLemma H5loss_draw_draw ht i l : \n  Hiv (i :: l) -> \n  ht_valid ht -> f1 i = draw -> edraw <= f2 eloss edraw ht i <= drawwin.\nProof. by move/Hiv_hd=> [] [_ _ H _] _ _; apply: H. Qed.\n\nLemma H5loss_draw_win ht i l : \n  Hiv (i :: l) -> \n  ht_valid ht -> f1 i = win -> drawwin <= f2 eloss edraw ht i.\nProof. by move/Hiv_hd=> [] [_ _ _ H] _ _; apply: H. Qed.\n\nLemma H5loss_draw_ge ht i l :\n  Hiv (i :: l) -> \n  ht_valid ht -> draw <= f1 i -> edraw <= f2 eloss edraw ht i.\nProof.\nmove=> Hiv Hv.\ncase: f1 (@H5loss_draw_draw ht i l Hiv Hv) \n         (@H5loss_draw_win ht i l Hiv Hv) => //.\n  by move=> _ /(_ (refl_equal _)) /(leq_trans _) H _; rewrite H.\nby move=> /(_ (refl_equal _)) /andP[].\nQed.\n\nLemma H5loss_draw_le ht i l :\n  Hiv (i :: l) -> \n  ht_valid ht -> f1 i <= draw -> f2 eloss edraw ht i <= drawwin.\nProof.\nmove=> Hiv Hv.\ncase: f1 (@H5loss_draw_loss ht i l Hiv Hv) \n         (@H5loss_draw_draw ht i l Hiv Hv) => //.\n  by move=> /(_ (refl_equal _))->.\nby move=> _ /(_ (refl_equal _)) /andP[].\nQed.\n\nLemma process_eval_rec5_loss_draw_valid ht (res : estate) l :\n  Hiv l -> ht_valid ht -> \n  ht_valid (process_eval_rec5 f2 eloss edraw ht res l).\nProof.\nelim: l ht res => // i l IH ht res HHiv Hv.\nhave HHiv1 := Hiv_cons HHiv.\nrewrite [process_eval_rec5 _ _ _ _ _ _]/=.\ncase E : f2 => [ht1 res1].\nhave -> : res1 = f2 eloss edraw ht i by rewrite E.\nhave -> : ht1 = f2 eloss edraw ht i by rewrite E.\nhave [E1|E1] := leqP res (f2 _ _ _ _).\n  by apply: IH => //; apply: (H5loss_draw_table HHiv).\nhave [E2|E2] := leqP edraw (f2 _ _ _ _).\n  by apply: IH => //; apply: (H5loss_draw_table HHiv).\nhave [E3|E3] := leqP (f2 _ _ _ _) eloss.\n  case: pres2state => //=; try by apply: (H5loss_draw_table HHiv).\n  by case: (l) => *; apply: (H5loss_draw_table HHiv).\ncase E4 : (f1 i).\n- rewrite ltnNge in E2; case/negP: E2.\n  by apply: leq_trans (H5loss_draw_win HHiv Hv E4).\n- by rewrite (H5loss_draw_loss HHiv) // ltnn in E3.\nrewrite ltnNge in E2; case/negP: E2.\nby have /andP[] := H5loss_draw_draw HHiv Hv E4.\nQed.\n\nLemma process_eval_rec5_loss_draw_le ht (res : estate) l :\n  Hiv l -> \n  ht_valid ht ->\n  draw <= res ->\n  draw <= \\smin_(i <- l) f1 i ->\n  process_eval_rec5 f2 eloss edraw ht res l <= edraw.\nProof.\nelim: l ht res => [|i l IH] ht res HHiv Hv.\n  by rewrite big_nil (esflip_le _ edraw).\nrewrite big_cons [process_eval_rec5 _ _ _ _ _ _]/= => H1 H2.\ncase E : f2 => [ht1 res1].\nhave -> : res1 = f2 eloss edraw ht i by rewrite E.\nhave -> : ht1 = f2 eloss edraw ht i by rewrite E.\nhave HHiv1 := Hiv_cons HHiv.\nhave [E1|E1] := leqP res (f2 _ _ _ _).\n  apply: IH => //; first by apply: (H5loss_draw_table HHiv).\n  by apply: leq_trans H2 (ge_sminr _ _).\nrewrite ifT; last first.\n  apply (H5loss_draw_ge HHiv) => //.\n  apply: leq_trans H2 (ge_sminl _ _).\napply: IH => //; first by apply: (H5loss_draw_table HHiv).\n  by apply: (H5loss_draw_ge HHiv) => //; apply: leq_trans H2 (ge_sminl _ _).\nby apply: leq_trans H2 (ge_sminr _ _).\nQed.\n\nLemma process_eval_rec5_loss_draw_ge ht (res : estate) l :\n  Hiv l -> \n  ht_valid ht ->\n  \\smin_(i <- l) f1 i <= draw ->\n   lossdraw <= process_eval_rec5 f2 eloss edraw ht res l.\nProof.\nelim: l ht res => [|i l IH] ht res HHiv Hv; first by rewrite big_nil.\nrewrite big_cons [process_eval_rec5 _ _ _ _ _ _]/= => H.\ncase E : f2 => [ht1 res1].\nhave -> : res1 = f2 eloss edraw ht i by rewrite E.\nhave -> : ht1 = f2 eloss edraw ht i by rewrite E.\nhave HHiv1 := Hiv_cons HHiv.\nhave [E1|E1] := leqP res (f2 _ _ _ _).\n  have [E2|/ltnW E2] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    apply: leq_trans (ge_process_eval_rec5 _ _ _ _ _ _).\n    rewrite (esflip_le drawwin).\n    by apply: leq_trans E1 (H5loss_draw_le HHiv _ _).\n  rewrite smin_ler // in H.\n  by apply: IH => //; apply: (H5loss_draw_table HHiv).\nhave [E2|E2] := leqP edraw (f2 _ _ _ _).\n  have [E3|/ltnW E3] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    apply: leq_trans (ge_process_eval_rec5 _ _ _ _ _ _).\n    rewrite (esflip_le drawwin).\n    by apply: leq_trans _ (H5loss_draw_le HHiv _ _).\n  rewrite smin_ler // in H.\n  by apply: IH => //; apply: (H5loss_draw_table HHiv).\nhave [E3|E3] := leqP (f2 eloss edraw ht i) eloss.\n  by rewrite (le_elossE E3).\napply: leq_trans (ge_process_eval_rec5 _ _ _ _ _ _).\nrewrite (esflip_le drawwin).\nby apply: leq_trans (ltnW E2) _.\nQed.\n\nLemma process_eval_rec5_loss_draw_loss ht (res : estate) l :\n  Hiv l ->\n  ht_valid ht ->\n  \\smin_(i <- l) f1 i = loss ->\n   process_eval_rec5 f2 eloss edraw ht res l = ewin :> estate.\nProof.\nelim: l ht res => [|i l IH] ht res HHiv Hv; first by rewrite big_nil.\nrewrite big_cons [process_eval_rec5 _ _ _ _ _ _]/= => H.\ncase E : f2 => [ht1 res1].\nhave -> : res1 = f2 eloss edraw ht i by rewrite E.\nhave -> : ht1 = f2 eloss edraw ht i by rewrite E.\nhave HHiv1 := Hiv_cons HHiv.\nhave [E1|E1] := leqP res (f2 _ _ _ _).\n  have [E2|/ltnW E2] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    apply: ge_ewinE; rewrite -[ewin]/(esflip eloss).\n    have -> : res = eloss.\n      by apply: le_elossE => //; rewrite -(H5loss_draw_loss HHiv Hv H).\n    by apply: ge_process_eval_rec5.\n  rewrite smin_ler // in H.\n  by apply: IH => //; apply: (H5loss_draw_table HHiv).\nhave [E2|E2] := leqP _ (f2 _ _ _ _).\n  have [E3|/ltnW E3] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    rewrite (H5loss_draw_loss HHiv) //.\n    apply: ge_ewinE; rewrite -[ewin]/(esflip eloss).\n    by apply: ge_process_eval_rec5.\n  rewrite smin_ler // in H.\n  by apply: IH => //; apply: (H5loss_draw_table HHiv).\nrewrite (H5loss_draw_loss HHiv) //=.\nby case: f1 (@H5loss_draw_draw ht i l HHiv Hv)\n            (@H5loss_draw_win ht i l HHiv Hv) => // [_|];\n   move=> /(_ (refl_equal _)); case: f2 E2 => h; case.\nQed.\n\nLemma process_eval_rec5_loss_draw_draw ht (res : estate) l :\n  Hiv l ->\n  ht_valid ht ->\n  \\smin_(i <- l) f1 i = draw -> draw <= res ->\n   lossdraw <= process_eval_rec5 f2 eloss edraw ht res l <= draw.\nProof.\nmove=> HHiv Hv H1 H2.\nrewrite process_eval_rec5_loss_draw_ge ?H1 //.\nby rewrite process_eval_rec5_loss_draw_le ?H1.\nQed.\n\nLemma process_eval_rec5_loss_draw_win ht (res : estate) l :\n  Hiv l ->\n  ht_valid ht ->\n  \\smin_(i <- l) f1 i = win -> drawwin <= res ->\n   process_eval_rec5 f2 eloss edraw ht res l <= lossdraw.\nProof.\nelim: l ht res => [|i l IH] ht res HHiv Hv.\n  by rewrite big_nil /= (esflip_le _ drawwin).\nrewrite big_cons [process_eval_rec5 _ _ _ _ _ _]/= => H1 H2.\ncase E : f2 => [ht1 res1].\nhave -> : res1 = f2 eloss edraw ht i by rewrite E.\nhave -> : ht1 = f2 eloss edraw ht i by rewrite E.\nhave HHiv1 := Hiv_cons HHiv.\nhave [H3 H4] : f1 i = win /\\ \\smin_(j <- l) f1 j = win.\n  have [E1|/ltnW E1] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H1 *; split => //.\n    by apply: ge_winE; rewrite -{1}H1.\n  rewrite smin_ler // in H1 *; split => //.\n  by apply: ge_winE; rewrite -{1}H1.\nhave [E1|E1] := leqP res (f2 _ _ _ _).\n  by apply: IH => //; apply: (H5loss_draw_table HHiv).\nhave [E2|E2] := leqP _ (f2 _ _ _ _).\n  apply: IH => //; first by apply: (H5loss_draw_table HHiv).\n  by apply: (H5loss_draw_win HHiv).\nrewrite ifN.\n  rewrite ltnNge in E2; case/negP: E2.\n  by apply: leq_trans (H5loss_draw_win HHiv _ _).\nrewrite -ltnNge.\nby apply: leq_trans (H5loss_draw_win HHiv _ _).\nQed.\n\n(** draw win *)\n\nLemma H5draw_win_table ht i l : \n  Hiv (i :: l) -> ht_valid ht -> ht_valid (f2 edraw ewin ht i).\nProof. by move/Hiv_hd=> [] _ [H _ _ _] _; apply: H. Qed.\n\nLemma H5draw_win_win ht i l : \n  Hiv (i :: l) -> ht_valid ht -> \n    f1 i = win -> f2 edraw ewin ht i = ewin :> estate.\nProof. by move/Hiv_hd=> [] _ [_ H _ _] _; apply: H. Qed.\n\nLemma H5draw_win_draw ht i l : \n  Hiv (i :: l) -> ht_valid ht -> \n    f1 i = draw -> lossdraw <= f2 edraw ewin ht i <= edraw.\nProof. by move/Hiv_hd=> [] _ [_ _ H _] _; apply: H. Qed.\n\nLemma H5draw_win_loss ht i l : \n  Hiv (i :: l) -> ht_valid ht -> \n  f1 i = loss -> f2 edraw ewin ht i <= lossdraw.\nProof. by move/Hiv_hd=> [] _ [_ _ _ H ] _; apply: H. Qed.\n\nLemma H5draw_win_le ht i l : \n  Hiv (i :: l) -> ht_valid ht -> f1 i <= draw -> f2 edraw ewin ht i <= edraw.\nProof.\nmove=> HHiv Hv.\ncase: f1 (@H5draw_win_loss ht i l HHiv Hv) \n         (@H5draw_win_draw ht i l HHiv Hv) => //.\n  by move=> /(_ (refl_equal _)) /leq_trans->.\nby move=>  _ /(_ (refl_equal _)) /andP[].\nQed.\n\nLemma H5draw_win_ge ht i l : \n  Hiv (i :: l) -> ht_valid ht -> draw <= f1 i -> lossdraw <= f2 edraw ewin ht i.\nProof.\nmove=> HHiv Hv.\ncase: f1 (@H5draw_win_draw ht i l HHiv Hv) \n         (@H5draw_win_win ht i l HHiv Hv) => //.\n  by move=> _ /(_ (refl_equal _))->.\nby move=> /(_ (refl_equal _)) /andP[].\nQed.\n\nLemma process_eval_rec5_draw_win_valid ht (res : estate) l :\n  Hiv l -> ht_valid ht -> ht_valid (process_eval_rec5 f2 edraw ewin ht res l).\nProof.\nelim: l ht res => // i l IH ht res HHiv Hv.\nrewrite [process_eval_rec5 _ _ _ _ _ _]/=.\ncase E : f2 => [ht1 res1].\nhave -> : res1 = f2 edraw ewin ht i by rewrite E.\nhave -> : ht1 = f2 edraw ewin ht i by rewrite E.\nhave HHiv1 := Hiv_cons HHiv.\nhave [E1|E1] := leqP res (f2 _ _ _ _).\n  by apply: IH => //; apply: (H5draw_win_table HHiv).\nhave [E2|E2] := leqP ewin (f2 _ _ _ _).\n  by apply: IH => //; apply: (H5draw_win_table HHiv).\nhave [E3|E3] := leqP (f2 _ _ _ _) edraw.\n  case: pres2state => //=; try by apply: (H5draw_win_table HHiv).\n  by case: (l) => *; apply: (H5draw_win_table HHiv).\ncase E4 : (f1 i).\n- rewrite (H5draw_win_win HHiv) //.\n  by apply: IH => //; apply: (H5draw_win_table HHiv).\n- rewrite ltnNge in E3; case/negP: E3.\n  by apply: (H5draw_win_le HHiv) => //; rewrite E4.\nrewrite ltnNge in E3; case/negP: E3.\nby apply: (H5draw_win_le HHiv) => //; rewrite E4.\nQed.\n\nLemma process_eval_rec5_draw_win_le ht (res : estate) l :\n  Hiv l ->\n  ht_valid ht ->\n  \\smin_(i <- l) f1 i <= draw ->\n  edraw <= process_eval_rec5 f2 edraw ewin ht res l.\nProof.\nelim: l ht res => [|i l IH] ht res HHiv Hv; first by rewrite big_nil.\nrewrite big_cons [process_eval_rec5 _ _ _ _ _ _]/= => H.\ncase E : f2 => [ht1 res1].\nhave -> : res1 = f2 edraw ewin ht i by rewrite E.\nhave -> : ht1 = f2 edraw ewin ht i by rewrite E.\nhave HHiv1 := Hiv_cons HHiv.\nhave [E1|E1] := leqP res (f2 _ _ _ _).\n  have [E2|/ltnW E2] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    apply: leq_trans (ge_process_eval_rec5 _ _ _ _ _ _).\n    rewrite (esflip_le edraw).\n    by apply: leq_trans E1 (H5draw_win_le HHiv _ _).\n  rewrite smin_ler // in H.\n  by apply: IH => //; apply: (H5draw_win_table HHiv).\nhave [E2|E2] := leqP ewin (f2 edraw ewin ht i).\n  have [E3|/ltnW E3] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    rewrite leqNgt in E2; case/negP: E2.\n    by apply: leq_ltn_trans (H5draw_win_le HHiv _ _) _.\n  rewrite smin_ler // in H.\n  by apply: IH => //; apply: (H5draw_win_table HHiv).\nhave [E3|E3] := leqP (f2 _ _ _ i) draw.\n  by case: f2 E3 => // h; case; case: (l).\nhave [E4|E4] := leqP (f1 i) draw.\n  rewrite ltnNge in E3; case/negP: E3.\n  by apply: (H5draw_win_le HHiv).\nrewrite (H5draw_win_win HHiv) // in E2.\napply: ge_winE.\nby case: f1 E4.\nQed.\n\nLemma process_eval_rec5_draw_win_ge ht (res : estate) l :\n  Hiv l ->\n  ht_valid ht ->\n  lossdraw <= res ->\n  draw <= \\smin_(i <- l) f1 i ->\n  process_eval_rec5 f2 edraw ewin ht res l <= drawwin.\nProof.\nelim: l ht res => [|i l IH] ht res HHiv Hv.\n  by rewrite big_nil (esflip_le _ lossdraw).\nrewrite big_cons [process_eval_rec5 _ _ _ _ _ _]/= => H1 H2.\ncase E : f2 => [ht1 res1].\nhave -> : res1 = f2 edraw ewin ht i by rewrite E.\nhave -> : ht1 = f2 edraw ewin ht i by rewrite E.\nhave HHiv1 := Hiv_cons HHiv.\nhave [E1|E1] := leqP res (f2 _ _ _ _).\n  apply: IH => //; first by apply: (H5draw_win_table HHiv).\n  by apply: leq_trans H2 (ge_sminr _ _).\nhave [E2|E2] := leqP ewin (f2 _ _ _ _).\n  apply: IH => //; first by apply: (H5draw_win_table HHiv).\n    apply: (H5draw_win_ge HHiv) => //.\n    by apply: leq_trans H2 (ge_sminl _ _).\n  by apply: leq_trans H2 (ge_sminr _ _).\nhave [E3|E3] := leqP (f2 edraw ewin ht i) edraw.\n  have : lossdraw <= (f2 edraw ewin ht i).\n    apply: (H5draw_win_ge HHiv) (leq_trans H2 (ge_sminl _ _)) => //.\n  by case: pres2state => //= _; case: (l).\nhave [E4|E4] := leqP (f1 i) draw.\n  rewrite ltnNge in E3; case/negP: E3.\n  by apply: (H5draw_win_le HHiv).\nrewrite (H5draw_win_win HHiv) // in E2.\napply: ge_winE.\nby case: f1 E4.\nQed.\n\nLemma process_eval_rec5_draw_win_win ht (res : estate) l :\n  Hiv l ->\n  ht_valid ht ->\n  res = win ->\n  \\smin_(i <- l) f1 i = win ->\n   process_eval_rec5 f2 edraw ewin ht res l = eloss :> estate.\nProof.\nelim: l ht res => [|i l IH] ht res HHiv Hv; first by rewrite big_nil => ->.\nrewrite big_cons [process_eval_rec5  _ _ _ _ _ _]/= => H1 H2.\ncase E : f2 => [ht1 res1].\nhave -> : res1 = f2 edraw ewin ht i by rewrite E.\nhave -> : ht1 = f2 edraw ewin ht i by rewrite E.\nhave HHiv1 := Hiv_cons HHiv.\nhave [H3 H4] : f1 i = win /\\ \\smin_(j <- l) f1 j = win.\n  have [E1|/ltnW E1] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H2; split => //.\n    by apply: ge_winE; rewrite -{1}H2.\n  rewrite smin_ler // in H2; split => //.\n  by apply: ge_winE; rewrite -{1}H2.\nrewrite (H5draw_win_win HHiv) // H1 /=.\nby apply: IH => //; apply: (H5draw_win_table HHiv).\nQed.\n\nLemma process_eval_rec5_draw_win_draw ht (res : estate) l :\n  Hiv l ->\n  ht_valid ht ->\n  \\smin_(i <- l) f1 i = draw -> lossdraw <= res ->\n   edraw <= process_eval_rec5 f2 edraw ewin ht res l <= drawwin.\nProof.\nmove=> HHiv Hv H1 H2.\nrewrite process_eval_rec5_draw_win_ge ?H1 //.\nby rewrite process_eval_rec5_draw_win_le ?H1.\nQed.\n\nLemma process_eval_rec5_draw_win_loss ht (res : estate) l :\n  Hiv l ->\n  ht_valid ht ->\n  \\smin_(i <- l) f1 i = loss ->\n   drawwin <= process_eval_rec5 f2 edraw ewin ht res l.\nProof.\nelim: l ht res => [|i l IH] ht res HHiv Hv; first by rewrite big_nil.\nrewrite big_cons [process_eval_rec5 _ _ _ _ _ _]/= => H.\ncase E : f2 => [ht1 res1].\nhave -> : res1 = f2 edraw ewin ht i by rewrite E.\nhave -> : ht1 = f2 edraw ewin ht i by rewrite E.\nhave HHiv1 := Hiv_cons HHiv.\nhave [E1|E1] := leqP res (f2 _ _ _ _).\n  have [E2|/ltnW E2] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    apply: leq_trans (ge_process_eval_rec5 _ _ _ _ _ _).\n    rewrite (esflip_le lossdraw).\n    apply: leq_trans E1 _.\n    by apply: (H5draw_win_loss HHiv).\n  rewrite smin_ler // in H.\n  by apply: IH => //; apply: (H5draw_win_table HHiv).\nhave [E2|E2] := leqP ewin (f2 _ _ _ _).\n  have [E3|/ltnW E3] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n    rewrite smin_lel // in H.\n    have := H5draw_win_loss HHiv Hv H.\n    by rewrite leqNgt (leq_trans _ E2).\n  rewrite smin_ler // in H.\n  by apply: IH => //; apply: (H5draw_win_table HHiv).\nhave [E3|E3] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n  rewrite smin_lel // in H.\n  by case: pres2state (H5draw_win_loss HHiv Hv H).\nrewrite smin_ler // in H; last by apply: ltnW.\nhave [E4|E4] := leqP (f2 _ _ _ _) edraw.\n  have : lossdraw <= f2 edraw ewin ht i.\n    apply: (H5draw_win_ge HHiv) => //.\n    by move: E3; rewrite H; case: f1.\n  case: pres2state E4 => //=.\n  by case: (l) H => //; rewrite big_nil.\nmove: E3 E2; rewrite H.\ncase: f1 (@H5draw_win_draw ht i l HHiv Hv) \n         (@H5draw_win_win ht i l HHiv Hv) => //.\n  by move=> _ -> //.\nmove=> /(_ (refl_equal _)).\nby rewrite [_ <= edraw]leqNgt E4 andbF.\nQed.\n\n(* loss win *)\n\nLemma H5loss_win_table ht i l : \n  Hiv (i :: l) -> ht_valid ht -> ht_valid (f2 eloss ewin ht i).\nProof. by move/Hiv_hd=> [] _ _ [H _]; apply: H. Qed.\n\n\nLemma H5loss_win ht i l :\n  Hiv (i :: l) -> ht_valid ht -> f2 eloss ewin ht i = f1 i :> estate.\nProof. by move/Hiv_hd=> [] _ _ [_ H]; apply: H. Qed.\n\nLemma process_eval_rec5_loss_win_valid ht (res : estate) l :\n  Hiv l -> ht_valid ht -> ht_valid (process_eval_rec5 f2 eloss ewin ht res l).\nProof.\nelim: l ht res => // i l IH ht res HHiv Hv.\nrewrite [process_eval_rec5 _ _ _ _ _ _]/=.\ncase E : f2 => [ht1 res1].\nhave -> : res1 = f2 eloss ewin ht i by rewrite E.\nhave -> : ht1 = f2 eloss ewin ht i by rewrite E.\nhave HHiv1 := Hiv_cons HHiv.\nhave [E1|E1] := leqP res (f2 _ _ _ _).\n  by apply: IH => //; apply: (H5loss_win_table HHiv).\nhave [E2|E2] := leqP ewin (f2 _ _ _ _).\n  by apply: IH => //; apply: (H5loss_win_table HHiv).\nhave [E3|E3] := leqP (f2 _ _ _ _) eloss.\n  case: pres2state => //=; try by apply: (H5loss_win_table HHiv).\n  by case: (l) => *; apply: (H5loss_win_table HHiv).\nrewrite (H5loss_win HHiv) // in E E1 E2 E3 *.\nhave -> : f1 i = draw by case: f1 E2 E3.\napply: process_eval_rec5_loss_draw_valid => //.\nby apply: (H5loss_win_table HHiv).\nQed.\n\nLemma process_eval_rec5_loss_win_lt ht (a res : estate) l :\n  Hiv l ->\n  ht_valid ht ->\n  a <= res ->\n  a < \\smin_(i <- l) f1 i -> \n  process_eval_rec5 f2 eloss ewin ht res l <= esflip a.\nProof.\nelim: l ht res => [|i l IH] ht res HHiv Hv aLr.\n  by rewrite big_nil esflip_le.\nrewrite big_cons => /= aLs.\ncase E : f2 => [ht1 res1].\nhave -> : res1 = f2 eloss ewin ht i by rewrite E.\nhave -> : ht1 = f2 eloss ewin ht i by rewrite E.\nhave HHiv1 := Hiv_cons HHiv.\nrewrite (H5loss_win HHiv) //.\nhave [E1|E1] := leqP res _.\n  apply: IH => //; first by apply: (H5loss_win_table HHiv).\n  by apply: leq_trans aLs (ge_sminr _ _).\nhave [E2|E2] := leqP ewin _.\n  apply: IH => //; first by apply: (H5loss_win_table HHiv).\n    by rewrite (ge_ewinE E2) // le_ewin.\n  by apply: leq_trans aLs (ge_sminr _ _).\nrewrite ifN; last first.\n  rewrite -ltnNge es2ns2esK.\n  apply: leq_ltn_trans _ (leq_trans aLs (ge_sminl _ _)).\n  by case: (a).\nhave [E3|E3] := leqP (f1 i) (\\smin_(j <- l) f1 j).\n  rewrite smin_lel // in aLs *.\n  have H : f1 i = draw.\n    by case: f1 E2 E3 aLs => //; case: (\\smin_(_ <- _) _) => //; case: (a).\n  rewrite H in E1 E3 aLs *.\n  apply: leq_trans (process_eval_rec5_loss_draw_le HHiv1 _ _ _) _ => //.\n    by apply: (H5loss_win_table HHiv). \n  rewrite (esflip_le edraw).\n  by apply: ltnW.\nrewrite smin_ler // in aLs *; last by apply: ltnW.\nsuff -> : f1 i = win.\n  apply: IH => //; first by apply: (H5loss_win_table HHiv).\n  by apply: le_ewin.\nby case: f1 E3 aLs => //; case: (\\smin_(_ <- _) _) => //; case: (a).\nQed.\n\nLemma process_eval_rec5_loss_win ht (res : estate) l :\n  Hiv l ->\n  ht_valid ht ->\n  \\smin_(i <- l) f1 i <= res ->\n  process_eval_rec5 f2 eloss ewin ht res l = \n    sflip (\\smin_(i <- l) f1 i) :> estate.\nProof.\nelim: l ht res => [|i l IH] ht res HHiv Hv.\n   by rewrite big_nil /= => /ge_ewinE ->.\nrewrite big_cons [process_eval_rec5 _ _ _ _ _ _]/= => H.\ncase E : f2 => [ht1 res1].\nhave -> : res1 = f2 eloss ewin ht i by rewrite E.\nhave -> : ht1 = f2 eloss ewin ht i by rewrite E.\nhave HHiv1 := Hiv_cons HHiv.\nrewrite (H5loss_win HHiv) // !es2ns2esK.\nhave [E1|E1] := leqP res (f1 i).\n  have [E2|E2] := leqP (\\smin_(j <- l) f1 j) (f1 i).\n    rewrite smin_ler // in H *.\n    by apply: IH => //; apply: (H5loss_win_table HHiv).\n  rewrite smin_lel // in H *; last by apply: ltnW.\n  apply: esle_antisym; last first.\n    apply: leq_trans (ge_process_eval_rec5 _ _ _ _ _ _).\n    by rewrite es2ns2esK es2n_flip esflip_le es2ns2esK.\n  rewrite es2ns2esK es2n_flip.\n  apply: process_eval_rec5_loss_win_lt; rewrite ?es2ns2esK //.\n  by apply: (H5loss_win_table HHiv).\nrewrite ifN; last first.\n  by rewrite -leqNgt -ltnS (leq_trans E1) // le_ewin.\nhave [E2|E2] := leqP (f1 i) loss.\n  by rewrite (le_lossE E2) /= sminln.\nhave H3 : f1 i = draw.\n  apply: sle_antisym.\n    by case: f1 E1; case: (res).\n  by case: f1 E2.\nrewrite H3 in H E1 *.\nhave [E3|E3] := leqP draw (\\smin_(j <- l) f1 j).\n  rewrite smin_lel // in H *.\n  apply: esle_antisym; rewrite es2ns2esK es2n_flip.\n    apply: process_eval_rec5_loss_draw_le => //.\n    by apply: (H5loss_win_table HHiv).\n  by apply: ge_process_eval_rec5.\nsuff H4 : \\smin_(j <- l) f1 j = loss.\n  rewrite H4.\n  apply: process_eval_rec5_loss_draw_loss => //.\n  by apply: (H5loss_win_table HHiv).    \napply: sle_antisym.\n  by case: (\\smin_(_ <- _) _) E3.\nby apply: ge_loss.\nQed.\n\nEnd ProcessEvalRec5.\n\nLemma esflip_inj : injective esflip.\nProof. by do 2 case. Qed.\n\nLemma eval_rec5_correct n t ht i :\n  depth i <= n ->\n  let f1 := eval_rec n t in\n  let f2 := eval_rec5 n t in\n  [/\\ \n    [/\\\n      ht_valid ht -> ht_valid (f2 eloss edraw ht i),\n      ht_valid ht -> f1 i = loss -> f2 eloss edraw ht i = eloss :> estate,\n      ht_valid ht -> f1 i = draw -> edraw <= f2 eloss edraw ht i <= drawwin &\n      ht_valid ht ->  f1 i = win -> drawwin <= f2 eloss edraw ht i],\n    [/\\\n      ht_valid ht -> ht_valid (f2 edraw ewin ht i),\n      ht_valid ht -> f1 i = win -> f2 edraw ewin ht i = ewin :> estate,\n      ht_valid ht -> f1 i = draw -> lossdraw <= f2 edraw ewin ht i <= draw &\n      ht_valid ht -> f1 i = loss -> f2 edraw ewin ht i <= lossdraw] &\n    ((ht_valid ht -> ht_valid (f2 eloss ewin ht i)) /\\\n     (ht_valid ht -> f2 eloss ewin ht i = f1 i :> estate))].\nProof.\nelim: n t ht i => [/=|n IH] t ht i Hi.\n  case: ieval (depth_ieval t i); last by rewrite eqxx; case: depth Hi.\n  by case.\nhave HHiv : Hiv (eval_rec n (flip t)) (eval_rec5 n (flip t)) (moves t i).\n  have F i1 : i1 \\in moves t i -> depth i1 <= n.\n    move=> Hi1.\n    rewrite (moves_depth Hi1) -ltnS (leq_trans _ Hi) // prednK //.\n    have := depth_ieval t i; rewrite liveness.\n    by case: depth Hi1 => //; case: moves => //=.\n  by (repeat split) => // i1 ht1 Hi1 Hv1;\n   have [[H1 H2 H3 H4] [H5 H6 H7 H8] [H9 H10]] := IH (flip t) ht1 i1 (F _ Hi1);\n   (apply: H1 || apply: H2 ||apply: H3 ||apply: H4 ||apply: H5 ||\n    apply: H6 ||apply: H7 ||apply: H8 ||apply: H9 || apply: H10).\nhave evalE : eval_rec n.+1 t i = eval t i.\n  by apply: eval_rec_stable; rewrite leqnn.\nrepeat split => //=.\n- move=> Hv; case E1 : ieval => //.\n  rewrite /= E1 in evalE.\n  case: hget (Hv i t) => [|_]; last first.\n  case E2 : process_eval_rec5 => [ht1 res2] /=.\n    apply: hput_correct => //.\n      rewrite -[ht_valid ht1]/(ht_valid (Pres ht1 res2)) -E2.\n      by apply: (process_eval_rec5_draw_win_valid HHiv).\n    rewrite -evalE -[res2]/(Pres ht1 res2 : estate) -E2.\n    case E3 : (\\smin_(_ <- _) _).\n    - by rewrite (process_eval_rec5_draw_win_win HHiv).\n    - have := process_eval_rec5_draw_win_loss win HHiv Hv E3.\n      by case: process_eval_rec5 => h [] //.\n    have := process_eval_rec5_draw_win_draw HHiv Hv E3 (isT : lossdraw <= ewin).\n    by case: process_eval_rec5 => h [] //.\n  move=> es /(_ es (refl_equal _)) Hes.\n  have [//|E2] := boolP (is_state es).\n  case: es Hes E1 E2 => //= He _ _.\n  case E : process_eval_rec5 => [ht1 res2] /=.\n  case: eqP => [[E1]| E1].\n    apply: hput_correct => //.\n      rewrite -[ht_valid ht1]/(ht_valid (Pres ht1 res2)) -E.\n      by apply: (process_eval_rec5_draw_win_valid HHiv) => //.\n    move: E1 He.\n    rewrite -evalE -[res2]/(Pres ht1 res2 : estate) -E.\n    case E3 : (\\smin_(_ <- _) _) => //.\n    by rewrite (process_eval_rec5_draw_win_win HHiv).\n  apply: hput_correct => //.\n    rewrite -[ht_valid ht1]/(ht_valid (Pres ht1 res2)) -E.\n    by apply: (process_eval_rec5_draw_win_valid HHiv) => //.\n  move: E1 He.\n  rewrite -evalE -[res2]/(Pres ht1 res2 : estate) -E.\n  case E3 : (\\smin_(_ <- _) _) => //.\n    by rewrite (process_eval_rec5_draw_win_win HHiv).\n  have := process_eval_rec5_draw_win_draw HHiv Hv E3 (isT : lossdraw <= ewin).\n  by case: process_eval_rec5 => h [].\n- move=> Hv; case E : ieval => [a|]; first by move=>->.\n  move=> /(@sflip_inj _ win) Hs.\n  case: hget (Hv i t) => [|_ ]; last first.\n    case E1 : process_eval_rec5 => [ht1 res2] /=.\n    rewrite -[res2]/(Pres ht1 res2 : estate) -E1.\n    by rewrite (process_eval_rec5_draw_win_win HHiv).\n  move=> es /(_ es (refl_equal _)) Hes.\n  have Hs1 : eval t i = loss by rewrite -evalE /= E Hs.\n  rewrite Hs1 in Hes.\n  have [//|E1] := boolP (is_state es); first by case: es Hes.\n  case: es Hes E1 => // Hes E1.\n    case E2 : process_eval_rec5 => [ht1 res2] /=.\n    rewrite -[res2]/(Pres ht1 res2 : estate) -E2.\n    by rewrite (process_eval_rec5_draw_win_win HHiv).\n- move=> Hv; case E : ieval => [a|]; first by move=>->.\n  move=> /(@sflip_inj _ draw) Hs.\n  case: hget (Hv i t) => [|_ ]; last first.\n    case E1 : process_eval_rec5 => [ht1 res2] /=.\n    rewrite -[res2]/(Pres ht1 res2 : estate) -E1.\n    by rewrite (process_eval_rec5_draw_win_draw HHiv).\n  move=> es /(_ es (refl_equal _)) Hes.\n  have Hs1 : eval t i = draw by rewrite -evalE /= E Hs.\n  rewrite Hs1 in Hes.\n  have [//|E1] := boolP (is_state es); first by case: es Hes.\n  case: es Hes E1 => // _ _.\n  case E1 : process_eval_rec5 => [ht1 res2] /=.\n  rewrite -[res2]/(Pres ht1 res2 : estate) -E1.\n  have := process_eval_rec5_draw_win_draw HHiv Hv Hs (isT : lossdraw <= ewin).\n  by case: process_eval_rec5 => h []. \n- move=> Hv; case E : ieval => [a|]; first by move=>->.\n  move=> /(@sflip_inj _ loss) Hs.\n  case: hget (Hv i t) => [|_ ]; last first.\n    case E1 : process_eval_rec5 => [ht1 res2] /=.\n    rewrite -[res2]/(Pres ht1 res2 : estate) -E1.\n    by rewrite (process_eval_rec5_draw_win_loss win HHiv).\n  move=> es /(_ es (refl_equal _)) Hes.\n  have Hs1 : eval t i = win by rewrite -evalE /= E Hs.\n  rewrite Hs1 in Hes.\n  have [//|E1] := boolP (is_state es); first by case: es Hes.\n  by case: es Hes E1.\n- move=> Hv; case E1 : ieval => //.\n  rewrite /= E1 in evalE.\n  case: hget (Hv i t) => [|_]; last first.\n  case E2 : process_eval_rec5 => [ht1 res2] /=.\n    apply: hput_correct => //.\n      rewrite -[ht_valid ht1]/(ht_valid (Pres ht1 res2)) -E2.\n      by apply: (process_eval_rec5_loss_draw_valid HHiv).\n    rewrite -evalE -[res2]/(Pres ht1 res2 : estate) -E2.\n    case E3 : (\\smin_(_ <- _) _).\n    - have := process_eval_rec5_loss_draw_win HHiv Hv E3 \n                (isT : drawwin <= ewin).\n      by case: process_eval_rec5 => h [] //.\n    - by rewrite (process_eval_rec5_loss_draw_loss ewin HHiv).\n    have := process_eval_rec5_loss_draw_draw HHiv Hv E3 (isT : draw <= ewin).\n    by case: process_eval_rec5 => h [] //.\n  move=> es /(_ es (refl_equal _)) Hes.\n  have [//|E2] := boolP (is_state es).\n  case: es Hes E1 E2 => //= He _ _.\n  case E : process_eval_rec5 => [ht1 res2] /=.\n  case: eqP => [[E1]| E1].\n    apply: hput_correct => //.\n      rewrite -[ht_valid ht1]/(ht_valid (Pres ht1 res2)) -E.\n      by apply: (process_eval_rec5_loss_draw_valid HHiv) => //.\n    move: E1 He.\n    rewrite -evalE -[res2]/(Pres ht1 res2 : estate) -E.\n    case E3 : (\\smin_(_ <- _) _) => //.\n    by rewrite (process_eval_rec5_loss_draw_loss win HHiv).\n  apply: hput_correct => //.\n    rewrite -[ht_valid ht1]/(ht_valid (Pres ht1 res2)) -E.\n    by apply: (process_eval_rec5_loss_draw_valid HHiv) => //.\n  move: E1 He.\n  rewrite -evalE -[res2]/(Pres ht1 res2 : estate) -E.\n  case E3 : (\\smin_(_ <- _) _) => //.\n    by rewrite (process_eval_rec5_loss_draw_loss win HHiv).\n  have := process_eval_rec5_loss_draw_draw HHiv Hv E3 (isT : draw <= ewin).\n  by case: process_eval_rec5 => h [].\n- move=> Hv; case E : ieval => [a|]; first by move=>->.\n  move=> /(@sflip_inj _ loss) Hs.\n  case: hget (Hv i t) => [|_ ]; last first.\n    case E1 : process_eval_rec5 => [ht1 res2] /=.\n    rewrite -[res2]/(Pres ht1 res2 : estate) -E1.\n    by apply: (process_eval_rec5_loss_draw_loss _ HHiv).\n  move=> es /(_ es (refl_equal _)) Hes.\n  have Hs1 : eval t i = win by rewrite -evalE /= E Hs.\n  rewrite Hs1 in Hes.\n  have [//|E1] := boolP (is_state es); first by case: es Hes.\n  case: es Hes E1 => // _ _.\n  case E1 : process_eval_rec5 => [ht1 res2] /=.\n  rewrite -[res2]/(Pres ht1 res2 : estate) -E1.\n  by rewrite (process_eval_rec5_loss_draw_loss _ HHiv).\n- move=> Hv; case E : ieval => [a|]; first by move=>->.\n  move=> /(@sflip_inj _ draw) Hs.\n  case: hget (Hv i t) => [|_ ]; last first.\n    case E1 : process_eval_rec5 => [ht1 res2] /=.\n    rewrite -[res2]/(Pres ht1 res2 : estate) -E1.\n    by apply: (process_eval_rec5_loss_draw_draw HHiv).\n  move=> es /(_ es (refl_equal _)) Hes.\n  have Hs1 : eval t i = draw by rewrite -evalE /= E Hs.\n  rewrite Hs1 in Hes.\n  have [//|E1] := boolP (is_state es); first by case: es Hes.\n  case: es Hes E1 => // _ _.\n  case E1 : process_eval_rec5 => [ht1 res2] /=.\n  rewrite -[res2]/(Pres ht1 res2 : estate) -E1.\n  have := process_eval_rec5_loss_draw_draw HHiv Hv Hs (isT : draw <= ewin).\n  by case: process_eval_rec5 => h [].\n- move=> Hv; case E : ieval => [a|]; first by move=>->.\n  move=> /(@sflip_inj _ win) Hs.\n  case: hget (Hv i t) => [|_ ]; last first.\n    case E1 : process_eval_rec5 => [ht1 res2] /=.\n    rewrite -[res2]/(Pres ht1 res2 : estate) -E1.\n    by apply: (process_eval_rec5_loss_draw_win HHiv).\n  move=> es /(_ es (refl_equal _)) Hes.\n  have Hs1 : eval t i = loss by rewrite -evalE /= E Hs.\n  rewrite Hs1 in Hes.\n  have [//|E1] := boolP (is_state es); first by case: es Hes.\n  by case: es Hes E1.\n- move=> Hv; case E : ieval => //.\n  case: hget (Hv i t) => [|_ ]; last first.\n    case E1 : process_eval_rec5 => [ht1 res2] /=.\n    rewrite -[res2]/(Pres ht1 res2 : estate) -E1.\n      apply: hput_correct => //.\n        rewrite -[ht1]/(Pres ht1 res2 : htable) -E1.\n        by apply: (process_eval_rec5_loss_win_valid HHiv).\n      rewrite (process_eval_rec5_loss_win HHiv) //.\n      by rewrite -evalE /= E; case: sflip.\n    by apply: le_win.\n  move=> es /(_ es (refl_equal _)) Hes.\n  have [//|E1] := boolP (is_state es).\n  case: es Hes E1 => // Hes E1.\n    case E2 : process_eval_rec5 => [ht1 res2] /=.\n    rewrite -[res2]/(Pres ht1 res2 : estate) -E2.\n    case: eqP => [[E3]| E3].\n      apply: hput_correct => //.\n        rewrite -[ht_valid ht1]/(ht_valid (Pres ht1 res2)) -E2.\n        by apply: (process_eval_rec5_draw_win_valid HHiv).\n      move: E3 Hes.\n      case E4 : eval => //.\n      move: E4; rewrite -evalE /= E => /(@sflip_inj _ win) E4.\n      by rewrite (process_eval_rec5_draw_win_win HHiv).\n    apply: hput_correct => //.  \n      rewrite -[ht_valid ht1]/(ht_valid (Pres ht1 res2)) -E2.\n      by apply: (process_eval_rec5_draw_win_valid HHiv).\n    case E4 : process_eval_rec5 => [ht2 res3] /=.\n    rewrite -[res3]/(Pres ht2 res3 : estate) -E4.\n    case E5 : eval Hes => //.\n      move: E5; rewrite -evalE /= E => /(@sflip_inj _ win) E5.\n      by rewrite (process_eval_rec5_draw_win_win HHiv).\n    move: E5; rewrite -evalE /= E => /(@sflip_inj _ draw) E5.\n    have := process_eval_rec5_draw_win_draw HHiv Hv E5 (isT: lossdraw <= ewin).\n    by case: process_eval_rec5 => h [].\n  case E2 : process_eval_rec5 => [ht1 res2] /=.\n  rewrite -[res2]/(Pres ht1 res2 : estate) -E2.\n  case: eqP => [[E3]| E3].\n    apply: hput_correct => //.\n      rewrite -[ht_valid ht1]/(ht_valid (Pres ht1 res2)) -E2.\n      by apply: (process_eval_rec5_loss_draw_valid HHiv).\n    move: E3 Hes.\n    case E4 : eval => //.\n    move: E4; rewrite -evalE /= E => /(@sflip_inj _ loss) E4.\n    by rewrite (process_eval_rec5_loss_draw_loss win HHiv).\n  apply: hput_correct => //.  \n    rewrite -[ht_valid ht1]/(ht_valid (Pres ht1 res2)) -E2.\n    by apply: (process_eval_rec5_loss_draw_valid HHiv).\n  case E4 : process_eval_rec5 => [ht2 res3] /=.\n  rewrite -[res3]/(Pres ht2 res3 : estate) -E4.\n  case E5 : eval Hes => //.\n    move: E5; rewrite -evalE /= E => /(@sflip_inj _ loss) E5.\n    by rewrite (process_eval_rec5_loss_draw_loss win HHiv).\n  move: E5; rewrite -evalE /= E => /(@sflip_inj _ draw) E5.\n  have := process_eval_rec5_loss_draw_draw HHiv Hv E5 (isT: draw <= ewin).\n  by case: process_eval_rec5 => h [].\nmove=> Hv; case E : ieval => [a|] //.\ncase: hget (Hv i t) => [|_ ]; last first.\n  case E1 : process_eval_rec5 => [ht1 res2] /=.\n  rewrite -[res2]/(Pres ht1 res2 : estate) -E1.\n  apply: (process_eval_rec5_loss_win HHiv) => //.\n  by apply: le_win.\nmove=> es /(_ es (refl_equal _)) Hes.\nrewrite -evalE /= E in Hes.\nhave [//|E1] := boolP (is_state es).\n  by case: es Hes => //=; case: sflip.\ncase: es Hes E1 => //.\n  case E1 : (\\smin_(i0 <- moves t i) eval_rec n (flip t) i0) => //= _ _.\n    case E2 : process_eval_rec5 => [ht1 res1] /=.\n    rewrite -[res1]/(Pres ht1 res1 : estate) -E2.\n    by rewrite (process_eval_rec5_draw_win_win HHiv) //.\n  case E2 : process_eval_rec5 => [ht1 res1] /=.\n  rewrite -[res1]/(Pres ht1 res1 : estate) -E2.\n  have := process_eval_rec5_draw_win_draw HHiv Hv E1 (isT : lossdraw <= ewin).\n  by case: process_eval_rec5 => h [].\ncase E1 : (\\smin_(i0 <- moves t i) eval_rec n (flip t) i0) => //= _ _.\n  case E2 : process_eval_rec5 => [ht1 res1] /=.\n  rewrite -[res1]/(Pres ht1 res1 : estate) -E2.\n  by rewrite (process_eval_rec5_loss_draw_loss win HHiv).\ncase E2 : process_eval_rec5 => [ht1 res1] /=.\nrewrite -[res1]/(Pres ht1 res1 : estate) -E2.\nhave := process_eval_rec5_loss_draw_draw HHiv Hv E1 (isT : draw <= ewin).\nby case: process_eval_rec5 => h [].\nQed.\n\nDefinition eval5 t b : estate := eval_rec5 (depth b) t eloss ewin \n                                    (fun=>fun=> None) b.\n\nLemma eval5_correct t b : eval5 t b = eval t b.\nProof.\nrewrite /eval5.\nby have [_ _ [_ ->]] := eval_rec5_correct t  (fun=>fun=> None)\n                          (leqnn (depth b)).\nQed.\n\nEnd Board.\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/tplayer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6647592563567962}}
{"text": "\nRequire Import FiatFormal.Data.List.Base.\nRequire Import FiatFormal.Tactics.\n\n\n(* Select elements that match a given predicate. *)\nFixpoint filter {A: Type} (f: A -> bool) (xx: list A) : list A :=\n  match xx with\n  | nil     => nil\n  | x :: xs\n  => if f x then x :: (filter f xs)\n            else filter f xs\n  end.\n\n\n(********************************************************************)\n(* Lemmas: filter *)\n\n(* The length of a filtered list is the same or smaller than\n   the original list. *)\nLemma filter_length\n :  forall A (xx: list A) (f: A -> bool)\n ,  length xx >= length (filter f xx).\nProof.\n intros. induction xx; auto.\n simpl. breaka (f a). simpl. omega.\nQed.\n", "meta": {"author": "paulkrog", "repo": "formalized-fiat", "sha": "8f9022980c038f500aeea9b2f85062f0bfc33eb6", "save_path": "github-repos/coq/paulkrog-formalized-fiat", "path": "github-repos/coq/paulkrog-formalized-fiat/formalized-fiat-8f9022980c038f500aeea9b2f85062f0bfc33eb6/FiatFormal/Data/List/Filter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.6647592457899107}}
{"text": "Require Import List.\nRequire Import Arith Omega.\nRequire Import Wf_nat.\n\n\nSet Implicit Arguments.\n\nClass Decidable A :=\n  {\n    eq_dec : forall (x y : A), {x = y} + {x <> y}\n  }.\n\nInstance nat_Decidable : Decidable nat.\nconstructor.\ndecide equality.\nDefined.\n\nSection ListUtil.\n  Variable A B : Type.\n  Context `{DA : Decidable A}.\n\n  Definition In_dec : forall (x : A) (xs : list A), {In x xs} + {~In x xs}.\n    intro x.\n    induction xs as [| a xs]; simpl; auto.\n    destruct IHxs; auto.\n    destruct (eq_dec a x); tauto.\n  Defined.\n\n  Definition NoDup_dec : forall xs : list A, {NoDup xs} + {~NoDup xs}.\n  induction xs as [| x xs].\n  - left. apply NoDup_nil.\n  - destruct IHxs.\n    + destruct (In_dec x xs).\n      * right.\n        now inversion 1.\n      * left.\n        now constructor.\n    + right.\n      now inversion 1.\n  Defined.\n\n  Fixpoint map_index_rec\n             (f : nat -> A -> B) (xs : list A) (i : nat) : list B :=\n    match xs with\n    | nil => nil\n    | x :: xs' => f i x :: map_index_rec f xs' (S i)\n    end.\n\n  Definition map_index (f : nat -> A -> B) (xs : list A) : list B :=\n    map_index_rec f xs 0.\n\n\n  Lemma map_index_equation : forall f xs,\n      map_index f xs =\n      match xs with\n      | nil => nil\n      | x :: xs' => f 0 x :: map_index (fun i => f (S i)) xs'\n      end.\n  Proof.\n    intros f xs.\n    unfold map_index.\n    generalize 0 as n.\n    induction xs as [| x xs].\n    - auto.\n    - intro n.\n      simpl.\n      f_equal.\n      rewrite (IHxs (S n)).\n      destruct xs as [| y xs].\n      + auto.\n      + simpl.\n        reflexivity.\n  Qed.\n\n  Lemma map_index_length : forall f xs, length (map_index f xs) = length xs.\n  Proof.\n    intros f xs.\n    revert f.\n    induction xs.\n    - auto.\n    - intro f.\n      rewrite map_index_equation.\n      simpl.\n      rewrite IHxs.\n      reflexivity.\n  Qed.\n\n  Lemma map_index_nth : forall f xs n db da,\n      n < length xs -> nth n (map_index f xs) db = f n (nth n xs da).\n  Proof.\n    intros until da.\n    revert f n.\n    induction xs as [| x xs].\n    - intros f n Hlt.\n      inversion Hlt.\n    - destruct n as [| n].\n      + reflexivity.\n      + intro Hlt.\n        rewrite map_index_equation.\n        simpl.\n        rewrite IHxs; auto.\n        simpl in Hlt.\n        omega.\n  Qed.\n\nEnd ListUtil.\n\nSection NthMod.\n  Variable A : Type.\n  Definition nth_mod (n: nat) (xs: list A) (d : A) : A :=\n    nth (n mod length xs) xs d.\n\n  Lemma nth_mod_indep : forall n xs d d',\n      xs <> nil ->\n      nth_mod n xs d = nth_mod n xs d'.\n  Proof.\n    intros until d'. intro H.\n    unfold nth_mod.\n    apply nth_indep.\n    apply Nat.mod_upper_bound.\n    destruct xs; auto.\n    discriminate.\n  Qed.\nEnd NthMod.\n\nLtac cut_hyp H :=\n  refine ((fun p pq => pq (H p)) _ _); clear H; [| intro H].\n\n\n\nFixpoint nat_sum xs :=\n  match xs with\n  | nil => 0\n  | x :: xs' => x + nat_sum xs'\n  end.\n\nLemma nat_sum_app : forall xs ys, nat_sum (xs ++ ys) = nat_sum xs + nat_sum ys.\nProof.\n  intros.\n  induction xs; simpl; auto.\n  omega.\nQed.\n\n\nLemma nat_sum_in : forall xs x ys, nat_sum (xs ++ x :: ys) = x + nat_sum xs + nat_sum ys.\nProof.\n  intros.\n  rewrite nat_sum_app.\n  simpl.\n  omega.\nQed.\n\nLemma nat_sum_rev : forall xs, nat_sum (rev xs) = nat_sum xs.\nProof.\n  intros.\n  induction xs; simpl; auto.\n  rewrite nat_sum_in; simpl.\n  omega.\nQed.\n\n\n\nLemma map_sum_add {A} : forall (f g : A -> nat) xs,\n    nat_sum (map (fun x => f x + g x) xs) = nat_sum (map f xs) + nat_sum (map g xs).\nProof.\n  intros.\n  induction xs; simpl; auto.\n  rewrite IHxs.\n  omega.\nQed.\n\nLemma map_sum_sub {A} : forall (f g : A -> nat) xs,\n    (forall x, In x xs -> g x <= f x) ->\n    nat_sum (map (fun x => f x - g x) xs) = nat_sum (map f xs) - nat_sum (map g xs).\nProof.\n  intros f g.\n  induction xs; intro Hle; simpl; auto.\n  rewrite IHxs.\n  - rewrite Nat.sub_add_distr.\n    rewrite Nat.add_sub_swap.\n    + rewrite Nat.add_sub_assoc; auto.\n      cut (forall x,In x xs -> g x <= f x); try solve [intuition].\n      clear.\n      induction xs; simpl; auto.\n      intro H.\n      apply le_trans with (f a + nat_sum (map g xs)).\n      * apply Nat.add_le_mono_r.\n        intuition.\n      * apply Nat.add_le_mono_l.\n        apply IHxs.\n        intuition.\n    + apply Hle.\n      simpl.\n      auto.\n  - intros x HIn.\n    apply Hle.\n    simpl.\n    auto.\nQed.\n\nLemma map_sum_mul_distr {A} : forall (f : A -> nat) xs a,\n    nat_sum (map f xs) * a = nat_sum (map (fun x => f x * a) xs).\nProof.\n  intros f xs a.\n  induction xs as [| x xs]; simpl; auto.\n  rewrite <- IHxs.\n  ring.\nQed.\n\nLemma list_length_ind {A} :\n  forall\n    (P : list A -> Prop)\n    (H : forall (l : nat) (IH : forall xs, length xs < l -> P xs),\n        forall xs, length xs = l -> P xs),\n  forall xs, P xs.\nProof.\n  intros P H.\n  intro xs.\n  remember (length xs) as l.\n  revert xs Heql.\n  induction l using lt_wf_ind.\n  intros xs Hl.\n  specialize (H l).\n  apply H; auto.\n  intros l' Hlt.\n  apply (H0 (length l')); auto.\nQed.\n\n\n\nLemma pigeon : forall xs n,\n    n < length xs -> (forall x, In x xs -> x < n) -> ~NoDup xs.\nProof.\n  induction xs using list_length_ind.\n  intros n Hlt Hbound.\n  destruct l as [| l].\n  - destruct xs; simpl in *; omega.\n  - destruct n as [| n].\n    + destruct xs; try discriminate.\n      specialize (Hbound n).\n      simpl in Hbound.\n      intuition.\n    + destruct (In_dec n xs) as [HIn | HnIn].\n      * intro HND.\n        apply in_split in HIn.\n        destruct HIn as (xl & xr & Heqxs). subst.\n        apply NoDup_remove in HND.\n        specialize (IH (xl ++ xr)).\n        rewrite app_length in *.\n        simpl in *.\n        cut_hyp IH; try omega.\n        specialize (IH n).\n        cut_hyp IH; try omega.\n        cut_hyp IH; try tauto.\n        intros x HIn.\n        specialize (Hbound x).\n        rewrite in_app_iff in *.\n        simpl in *.\n        cut_hyp Hbound; try tauto.\n        cut (x <> n); try omega.\n        intro.\n        now subst.\n      * inversion 1 as [|x xs' HnIn' HND]; subst; try discriminate.\n        simpl in *.\n        specialize (IH xs').\n        cut_hyp IH; try omega.\n        specialize (IH n).\n        cut_hyp IH; try omega.\n        cut_hyp IH; try tauto.\n        intros y HIny.\n        specialize (Hbound y).\n        intuition.\n        cut (y <> n); try omega.\n        intro.\n        now subst.\nQed.\n\nLemma inv_pigeon : forall xs,\n    NoDup xs -> (forall x, In x xs -> x < length xs) ->\n    forall x, x < length xs -> In x xs.\nProof.\n  intro xs.\n  remember (length xs) as len.\n  revert xs Heqlen.\n  induction len.\n  - intros.\n    omega.\n  - intros xs Hlen HND Hbound x Hlt.\n    assert (In len xs) as HIn. {\n      destruct (In_dec len xs); auto.\n      contradict HND.\n      apply pigeon with (n := len); try omega.\n      intros x' HIn.\n      specialize (Hbound x' HIn).\n      cut (x' <> len); try omega.\n      intro.\n      now subst.\n    }\n    inversion Hlt; subst; auto.\n    apply in_split in HIn.\n    destruct HIn as (xl & xr & Hxs).\n    subst.\n    specialize (IHlen (xl ++ xr)).\n    rewrite app_length in *.\n    simpl in *.\n    cut_hyp IHlen; try omega.\n    apply NoDup_remove in HND.\n    cut_hyp IHlen; try tauto.\n    cut_hyp IHlen.\n    + intros y HIny.\n      specialize (Hbound y).\n      rewrite in_app_iff in *.\n      simpl in *.\n      cut (y <> len).\n      * intros.\n        cut_hyp Hbound; try tauto.\n        omega.\n      * intro.\n        subst.\n        tauto.\n    + specialize (IHlen x).\n      rewrite in_app_iff in *.\n      simpl.\n      destruct IHlen; auto.\nQed.\n\n\n\nFixpoint maximum (xs : list nat) : nat :=\n  match xs with\n  | nil => 0\n  | x :: xs' => Nat.max x (maximum xs')\n  end.\n\nLemma maximum_spec : forall xs x, In x xs -> x <= maximum xs.\nProof.\n  induction xs as [| x xs]; intro y; simpl; try tauto.\n  destruct 1.\n  - subst.\n    apply Nat.le_max_l.\n  - apply le_trans with (maximum xs); auto.\n    apply Nat.le_max_r.\nQed.\n\nLemma map_nth' : forall {A B} (f : A -> B) xs n da db,\n    n < length xs ->\n    nth n (map f xs) da = f (nth n xs db).\nProof.\n  intros until db.\n  revert xs.\n  induction n; intros xs Hlt.\n  - destruct xs.\n    + inversion Hlt.\n    + reflexivity.\n  - destruct xs.\n    + inversion Hlt.\n    + simpl.\n      rewrite IHn; auto.\n      simpl in Hlt.\n      omega.\nQed.\n\nLemma list_elem_eq {A} : forall xs ys (d : A),\n    length xs = length ys ->\n    (forall i, i < length xs -> nth i xs d = nth i ys d) ->\n    xs = ys.\nProof.\n  induction xs.\n  - destruct ys; simpl in *; try discriminate.\n    reflexivity.\n  - intros ys d Hlen Heq.\n    destruct ys as [|b ys]; simpl in Hlen; try discriminate.\n    specialize (IHxs ys d).\n    cut_hyp IHxs; auto.\n    replace a with b.\n    + rewrite IHxs; auto.\n      intros i Hi.\n      specialize (Heq (S i)).\n      simpl in Heq.\n      apply Heq.\n      omega.\n    + specialize (Heq 0).\n      simpl in Heq.\n      rewrite Heq; auto.\n      omega.\nQed.\n\nLemma sub_sub_add : forall x y z, z <= y -> (x - (y - z)) = x + z - y.\nProof.\n  intros.\n  omega.\nQed.\n", "meta": {"author": "kazkob", "repo": "TPPMark2018", "sha": "5fa783ba7d6e9aead6cef4175c0412dd2d37241a", "save_path": "github-repos/coq/kazkob-TPPMark2018", "path": "github-repos/coq/kazkob-TPPMark2018/TPPMark2018-5fa783ba7d6e9aead6cef4175c0412dd2d37241a/Util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.6647592457899107}}
{"text": "Require Import String.\nRequire Import Ascii.\nRequire Import Orders.\n\nInductive lex_lt: string -> string -> Prop :=\n| lex_lt_lt : forall (c1 c2 : ascii) (s1 s2 : string),\n    nat_of_ascii c1 < nat_of_ascii c2 ->\n    lex_lt (String c1 s1) (String c2 s2)\n| lex_lt_eq : forall (c : ascii) (s1 s2 : string),\n    lex_lt s1 s2 ->\n    lex_lt (String c s1) (String c s2)\n| lex_lt_empty : forall (c : ascii) (s : string),\n    lex_lt EmptyString (String c s).\n\nTheorem lex_lt_not_eq : forall s0 s1,\n    lex_lt s0 s1 -> s0 <> s1.\nProof.\n  induction s0.\n  - intros.\n    inversion H; subst.\n    congruence.\n  - intros.\n    inversion H; subst.\n    * intro H_eq.\n      injection H_eq; intros; subst.\n      contradict H3.\n      auto with arith.\n    * intro H_eq.\n      injection H_eq; intros; subst.\n      specialize (IHs0 s3).\n      apply IHs0 in H3.\n      auto.\nQed.\n\nLemma lex_lt_irrefl : Irreflexive lex_lt.\nProof.\n  intros s0 H_lt.\n  apply lex_lt_not_eq in H_lt.\n  auto.\nQed.\n\nTheorem lex_lt_trans : forall s0 s1 s2,\n    lex_lt s0 s1 -> lex_lt s1 s2 -> lex_lt s0 s2.\nProof.\ninduction s0.\n- intros.  \n  inversion H; subst.\n  inversion H0; subst.\n  * apply lex_lt_empty.\n  * apply lex_lt_empty.\n- intros.\n  inversion H; subst; inversion H0; subst.\n  * apply lex_lt_lt.\n    eauto with arith.\n  * apply lex_lt_lt.\n    assumption.\n  * apply lex_lt_lt.\n    assumption.\n  * apply lex_lt_eq.\n    eapply IHs0; eauto.\nQed.\n\nTheorem lex_lt_strorder : StrictOrder lex_lt.\nProof.\n  exact (Build_StrictOrder _ lex_lt_irrefl lex_lt_trans).\nQed.\n", "meta": {"author": "proofengineering", "repo": "serapi-tests", "sha": "18b1debf9219077210b77ff3e5f0bd3feadeffd9", "save_path": "github-repos/coq/proofengineering-serapi-tests", "path": "github-repos/coq/proofengineering-serapi-tests/serapi-tests-18b1debf9219077210b77ff3e5f0bd3feadeffd9/exact.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6646868820293999}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Import Relation_Operators.\nRequire Import Relation_Definitions.\nRequire Import Transitive_Closure.\n\nSection WfUnion.\nVariable A : Type.\nVariables R1 R2 : relation A.\n\nNotation Union := (union A R1 R2).\n\nRemark strip_commut :\ncommut A R1 R2 ->\nforall x y:A,\nclos_trans A R1 y x ->\nforall z:A, R2 z y ->  exists2 y' : A, R2 y' x & clos_trans A R1 z y'.\nProof. hammer_hook \"Union\" \"Union.strip_commut\".  \ninduction 2 as [x y| x y z H0 IH1 H1 IH2]; intros.\nelim H with y x z; auto with sets; intros x0 H2 H3.\nexists x0; auto with sets.\n\nelim IH1 with z0; auto with sets; intros.\nelim IH2 with x0; auto with sets; intros.\nexists x1; auto with sets.\napply t_trans with x0; auto with sets.\nQed.\n\n\nLemma Acc_union :\ncommut A R1 R2 ->\n(forall x:A, Acc R2 x -> Acc R1 x) -> forall a:A, Acc R2 a -> Acc Union a.\nProof. hammer_hook \"Union\" \"Union.Acc_union\".  \ninduction 3 as [x H1 H2].\napply Acc_intro; intros.\nelim H3; intros; auto with sets.\ncut (clos_trans A R1 y x); auto with sets.\nelimtype (Acc (clos_trans A R1) y); intros.\napply Acc_intro; intros.\nelim H8; intros.\napply H6; auto with sets.\napply t_trans with x0; auto with sets.\n\nelim strip_commut with x x0 y0; auto with sets; intros.\napply Acc_inv_trans with x1; auto with sets.\nunfold union.\nelim H11; auto with sets; intros.\napply t_trans with y1; auto with sets.\n\napply (Acc_clos_trans A).\napply Acc_inv with x; auto with sets.\napply H0.\napply Acc_intro; auto with sets.\nQed.\n\n\nTheorem wf_union :\ncommut A R1 R2 -> well_founded R1 -> well_founded R2 -> well_founded Union.\nProof. hammer_hook \"Union\" \"Union.wf_union\".  \nunfold well_founded.\nintros.\napply Acc_union; auto with sets.\nQed.\n\nEnd WfUnion.\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/Union.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7634837689358858, "lm_q1q2_score": 0.6646868785829697}}
{"text": "Require Import HoTT.\n\nLocal Open Scope nat_scope.\n\n(*\n  Expressions with natural numbers and +.\n*)\nSection plus.\n\nPrivate Inductive ExpP : Type :=\n| val : nat -> ExpP\n| plus : ExpP -> ExpP -> ExpP.\n\nAxiom addE : forall n m, plus (val n) (val m) = val (n + m).\n\nFixpoint ExpP_ind\n  (Y : ExpP -> Type)\n  (vY : forall n : nat, Y(val n))\n  (pY : forall e1 e2 : ExpP, Y e1 -> Y e2 -> Y (plus e1 e2))\n  (aY : forall n m : nat, addE n m # pY (val n) (val m) (vY n) (vY m) = vY (n + m))\n  (x : ExpP)\n  {struct x}\n  : Y x\n  :=\n  (match x return _ -> Y x with\n    | val n => fun _ => vY n\n    | plus e1 e2 => fun _ => pY e1 e2 (ExpP_ind Y vY pY aY e1) (ExpP_ind Y vY pY aY e2)\n  end) aY.\n\nAxiom ExpP_ind_beta_addE : forall\n  (Y : ExpP -> Type)\n  (vY : forall n : nat, Y(val n))\n  (pY : forall e1 e2 : ExpP, Y e1 -> Y e2 -> Y (plus e1 e2))\n  (aY : forall n m : nat, addE n m # pY (val n) (val m) (vY n) (vY m) = vY (n + m))\n  (n m : nat)\n  , apD (ExpP_ind Y vY pY aY) (addE n m) = aY n m.\n\nEnd plus.\n\n(*\n  Evaluates the expression, truncation is needed for images of the path.\n*)\nDefinition evalExp : forall (e : ExpP), exists n : nat, \n  Trunc (trunc_S minus_two) (e = val n).\nProof.\nProof.\nsimple refine (ExpP_ind _ _ _ _); cbn.\n- intros.\n  exists n.\n  apply tr.\n  reflexivity.\n- intros e1 e2 (v1, tp1) (v2, tp2).\n  exists (v1 + v2).\n  (* alternative option:\n        simple refine (_ @ addE v1 v2).\n        simple refine (_ @ ap (plus (val v1)) p2).\n        apply (ap (fun x => plus x e2) p1).\n  *)\n  simple refine (Trunc_ind _ _ tp1).\n  intro p1.\n  simple refine (Trunc_ind _ _ tp2).\n  intro p2.\n  cbn.\n  apply tr.\n  apply (\n    ap (plus e1) p2\n    @ ap (fun x => plus x (val v2)) p1\n    @ addE v1 v2).\n- intros.\n  simple refine (path_sigma _ _ _ _ _).\n  * cbn.\n    simple refine\n      (ap pr1 (@transport_sigma ExpP _ _ _ _ (addE n m) (n + m; tr (1 @ addE n m))) @ _).\n    simple refine \n      (transport_const (addE n m) _ @ _).\n    reflexivity.\n  * enough\n      (forall (e1 e2 : ExpP) (x1 x2 : Trunc (trunc_S minus_two) (e1 = e2)),\n        x1 = x2).\n    apply X.\n    intros.\n    enough (IsHProp (Trunc -1 (e1 = e2))).\n      apply X.\n      apply istrunc_truncation.\nDefined.\n\n(*\n  Value of an expression\n*)\nDefinition value (e : ExpP) := pr1 (evalExp e).\n\n(*\n  For tests, sum from 0 to n\n*)\nFixpoint gauss (n : nat) :=\nmatch n with\n  | 0 => val 0\n  | S n => plus (val (S n)) (gauss n)\nend.\n\n(*\n  Denotational semantics of expressions as natural numbers\n*)\nDefinition denotationalN : ExpP -> nat.\nProof.\nsimple refine (ExpP_ind _ _ _ _); cbn.\n- apply idmap.\n- intros e1 e2 n m.\n  apply (n + m).\n- intros.\n  apply transport_const.\nDefined.\n\n(*\n  Denotational semantics of expressions as loops on circle\n*)\nDefinition denotationalS1 : ExpP -> base = base.\nProof.\nsimple refine (ExpP_ind _ _ _ _); cbn.\n- induction 1.\n  * reflexivity.\n  * apply (loop @ IHn).\n- intros e1 e2 p1 p2.\n  apply (p1 @ p2).\n- intros n m.\n  simple refine (transport_paths_FlFr _ _ @ _).\n  hott_simpl.\n  cbn.\n  induction n ; induction m ; cbn.\n  * reflexivity.\n  * apply concat_1p.\n  * etransitivity.\n    apply concat_p1.\n    cbn in IHn.\n    simple refine (ap (fun p => loop @ p) _).\n    etransitivity.\n      Focus 2.\n      apply IHn.\n\n      symmetry.\n      apply concat_p1.\n  * etransitivity.\n    apply concat_pp_p.\n    simple refine (ap (fun p => loop @ p) _).\n    induction n.\n      apply concat_1p.\n      cbn in *.\n      apply IHn.\nDefined.\n\nDefinition power {A : Type} {x : A} (p : x = x) (n : nat) : x = x.\nProof.\ninduction n.\n- reflexivity.\n- apply (p @ IHn).\nDefined.\n\nLemma power_plus : forall (A : Type) (x : A) (p : x = x) n m, \n  power p (n + m) = (power p n) @ (power p m).\nProof.\ninduction n; simpl.\n- induction m; cbn; hott_simpl.\n- induction m; simpl.\n  * rewrite <- nat_plus_n_O.\n    hott_simpl.\n  * rewrite IHn.\n    hott_simpl.\nDefined.\n\nTheorem sem : forall (e : ExpP), \n  Trunc (trunc_S minus_two) (denotationalS1 e = power loop (denotationalN e)).\nProof.\nsimple refine (ExpP_ind _ _ _ _); simpl.\n- intros.\n  apply tr.\n  reflexivity.\n- intros e1 e2 tp1 tp2.\n  simple refine (Trunc_ind _ _ tp1).\n  intro p1.\n  simple refine (Trunc_ind _ _ tp2).\n  intro p2.\n  simpl.\n  apply tr.\n  assert\n    (power loop (denotationalN (plus e1 e2)) =\n     power loop (denotationalN e1 + denotationalN e2)).\n    { reflexivity. }\n  rewrite X.\n  cbn.\n  rewrite p1; rewrite p2.\n  rewrite power_plus.\n  reflexivity.\n- intros.\n  enough\n    (forall (e1 e2 : base = base) (x1 x2 : Trunc (trunc_S minus_two) (e1 = e2)),\n    x1 = x2).\n  apply X.\n\n  intros.\n  enough (IsHProp (Trunc -1 (e1 = e2))).\n    apply X.\n\n    apply istrunc_truncation.\nDefined.", "meta": {"author": "nmvdw", "repo": "HITs-Examples", "sha": "c6f756a856768e1217a1f12f7a385948f9bacc9b", "save_path": "github-repos/coq/nmvdw-HITs-Examples", "path": "github-repos/coq/nmvdw-HITs-Examples/HITs-Examples-c6f756a856768e1217a1f12f7a385948f9bacc9b/Expressions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6646868717759352}}
{"text": "(* Software Foundations *)\n(* Exercice 2 stars, filter_even_gt7 *)\n\nInductive list(X: Type): Type :=\n|nil: list X\n|cons: X -> list X -> list X.\n\nArguments nil {X}.\nArguments cons {X} _ _.\n\nNotation \"[]\" := nil.\nNotation \"x :: y\" := (cons x y)(at level 60, right associativity).\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint filter{X:Type}(f: X -> bool)(l: list X): list X:=\n    match l with\n    |[]   => []\n    |h::t => if f h then h::(filter f t) else (filter f t)\n    end.\n\n\nDefinition filter_even_gt7(l: list nat): list nat :=\n      filter (fun n => andb (Nat.even n) (Nat.ltb 7 n)) l.\n\nExample test_filter_even_gt7_1: filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity. Qed.\nExample test_filter_even_gt7_2: filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter6_Library_Poly/filter_even_gt7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.6646040245038078}}
{"text": "Require Import XR_Rsqr.\nRequire Import XR_Rminus.\nRequire Import XR_Rmult_plus_distr_l.\nRequire Import XR_Rmult_plus_distr_r.\nRequire Import XR_Rplus_assoc.\nRequire Import XR_Rplus_eq_compat_l.\nRequire Import XR_Ropp_mult_distr_l.\n\nLocal Open Scope R_scope.\n\nLemma Rsqr_minus_plus : forall a b:R, (a - b) * (a + b) = Rsqr a - Rsqr b.\nProof.\n  intros x y.\n  unfold Rminus, Rsqr.\n  rewrite Rmult_plus_distr_l.\n  repeat rewrite Rmult_plus_distr_r.\n  repeat rewrite Rplus_assoc.\n  apply Rplus_eq_compat_l.\n  rewrite <- Ropp_mult_distr_l.\n  rewrite (Rmult_comm y).\n  repeat rewrite <- Rplus_assoc.\n  rewrite Rplus_opp_l.\n  rewrite Rplus_0_l.\n  rewrite <- Ropp_mult_distr_l.\n  reflexivity.\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_minus_plus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6645936116004443}}
{"text": "(* File: My_Nth.v  (last edited on 25/10/2000) (c) Klaus Weich  *)\n\nRequire Export List.\nRequire Export Plus.\n\n\nSection My_Nth.\n\nVariable B : Set.\n\nInductive my_nth : nat -> list B -> B -> Prop :=\n  | My_NthO : forall (l : list B) (a : B), my_nth 0 (a :: l) a\n  | My_NthS :\n      forall (n : nat) (l : list B) (b : B),\n      my_nth n l b -> forall a : B, my_nth (S n) (a :: l) b.\n\n\nLemma inv_nth_nil : forall (n : nat) (a : B), my_nth n nil a -> False.\nintros.\ninversion H.\nQed.\n\n\nLemma inv_nthO :\n forall (a : B) (l : list B) (b : B), my_nth 0 (a :: l) b -> a = b.\nintros.\ninversion H.\ntrivial.\nQed.\n\n\nLemma inv_nthS :\n forall (n : nat) (a : B) (l : list B) (b : B),\n my_nth (S n) (a :: l) b -> my_nth n l b.\nintros.\ninversion H.\nassumption.\nQed.\n\n\nLemma my_nth_rec :\n forall P : nat -> list B -> B -> Set,\n (forall (l : list B) (a : B), P 0 (a :: l) a) ->\n (forall (n : nat) (l : list B) (b : B),\n  my_nth n l b -> P n l b -> forall a : B, P (S n) (a :: l) b) ->\n forall (n : nat) (l : list B) (y : B), my_nth n l y -> P n l y.\nintros P base step n.\nelim n; clear n.\nintros l; case l; clear l.\nintros y nth; elimtype False.\napply (inv_nth_nil 0 y nth).\nintros a l b nth.\n rewrite (inv_nthO a l b nth).\napply base.\n\nintros n ih l.\ncase l; clear l.\nintros y nth; elimtype False.\napply (inv_nth_nil (S n) y nth).\nintros a l b nth.\napply step.\napply (inv_nthS n a l b nth).\napply ih.\napply (inv_nthS n a l b nth).\nQed.\n\n\nLemma nth_in : forall (n : nat) (l : list B) (a : B), my_nth n l a -> In a l.\nintros n l a nth.\nelim nth; clear nth.\nintros.\nsimpl in |- *; left; trivial.\nintros.\nsimpl in |- *; right; assumption.\nQed.\n\n\nLemma nth_app0 :\n forall (n : nat) (l0 l1 : list B) (a : B),\n my_nth n l0 a -> my_nth n (l0 ++ l1) a.\nintros n l0.\ngeneralize n; clear n.\nelim l0; clear l0.\nintros n l1 a nth; elimtype False.\napply (inv_nth_nil n a nth).\nintros a0 l0 ih n.\ncase n; clear n.\nintros l1 a nth.\n rewrite (inv_nthO a0 l0 a nth).\nsimpl in |- *; apply My_NthO.\nintros n l1 a nth.\nsimpl in |- *; apply My_NthS.\napply ih.\napply (inv_nthS n a0 l0 a nth).\nQed.\n\n\nLemma nth_app1 :\n forall (n : nat) (l0 l1 : list B) (a : B),\n my_nth n l1 a -> my_nth (length l0 + n) (l0 ++ l1) a.\nintros n l0; elim l0; clear l0.\nsimpl in |- *; trivial.\nintros a0 l0 ih l1 a nth.\nsimpl in |- *.\napply My_NthS.\napply ih.\nassumption.\nQed.\n\n\nInductive inv_my_nth_app (n : nat) (l0 l1 : list B) (a : B) : Set :=\n  | Inv_Nth_App0 : my_nth n l0 a -> inv_my_nth_app n l0 l1 a\n  | Inv_Nth_App1 :\n      forall n' : nat, my_nth n' l1 a -> inv_my_nth_app n l0 l1 a.\n\nLemma inv_nth_app :\n forall (n : nat) (l0 l1 : list B) (a : B),\n my_nth n (l0 ++ l1) a -> inv_my_nth_app n l0 l1 a.\nintros n l0 l1 a.\ngeneralize n; clear n.\nelim l0; clear l0; simpl in |- *.\nintros n nth.\nright with n.\nassumption.\nintros a0 l0 ih_l0 n.\ncase n; clear n.\nintros nth.\nleft.\n rewrite (inv_nthO a0 (l0 ++ l1) a nth).\napply My_NthO.\nintros n nth.\nelim (ih_l0 n).\nintros nth_l0.\nleft.\napply My_NthS; assumption.\nintros n' nth_l1.\nright with n'; assumption.\napply inv_nthS with a0; assumption.\nQed.\n\n\n\nInductive nth_split (a : B) (l : list B) : Set :=\n    Nth_Split_Intro :\n      forall l1 l2 : list B, l = l1 ++ a :: l2 -> nth_split a l.     \n\nLemma my_nth_split :\n forall (n : nat) (l : list B) (a : B), my_nth n l a -> nth_split a l.\nintros n; elim n; clear n.\nintros l a nth.\napply Nth_Split_Intro with (nil (A:=B)) (tail l).\ninversion_clear nth.\nsimpl in |- *; trivial.\nintros n ih l a. \ncase l; clear l.\nintros nth; elimtype False; inversion_clear nth.\nintros a0 l nth.\nelim (ih l a); clear ih.\nintros l1 l2 H.\napply Nth_Split_Intro with (a0 :: l1) l2.\n rewrite H; simpl in |- *; trivial.\ninversion_clear nth; assumption.\nQed.\n\nLemma in_nth :\n forall (a : B) (l : list B), In a l -> exists n : nat, my_nth n l a.\nintros b l; elim l; clear l.\nintros in_b; inversion_clear in_b.\nintros a l ih in_a.\ninversion_clear in_a.\nexists 0.\n rewrite H.\napply My_NthO.\nelim ih; try assumption.\nintros n nth.\nexists (S n).\napply My_NthS; assumption.\nQed.\n\nEnd My_Nth.", "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/ipc/My_Nth.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.6645795715959862}}
{"text": "Require Import notations decidables Setoid Morphisms.\nRequire Export vectors.\nRequire Import List.\n\nDefinition transp n := prod (fin n) (fin n).\nDefinition perm n := list (transp n).\n\nDefinition vect_transp {A n} (v: vect A n) (t: transp n) := vect_swap (fst t) (snd t) v.\nDefinition vect_perm {A n} (p: perm n) (v: vect A n) := fold_left vect_transp p v.\n\nDefinition transp_eq {n} (t1 t2: transp n) := forall A (v: vect A n), vect_eq (vect_transp v t1) (vect_transp v t2).\nDefinition perm_eq {n} (p1 p2: perm n) := forall A (v: vect A n), vect_eq (vect_perm p1 v) (vect_perm p2 v).\nDefinition perm_mult {n} (p1 p2: perm n): perm n := List.app p1 p2.\nDefinition perm_inv {n} (p: perm n): perm n := List.rev p.\n\nInstance transp_eq_Equiv n: Equivalence (transp_eq (n:=n)).\n split; unfold Reflexive, Symmetric, Transitive, transp_eq; intros;\n [ reflexivity | symmetry | rewrite H ]; auto.\nQed.\nInstance perm_eq_Equiv n: Equivalence (perm_eq (n:=n)).\n split; unfold Reflexive, Symmetric, Transitive, perm_eq; intros;\n [ reflexivity | symmetry | rewrite H ]; auto.\nQed.\n\nInstance vect_transp_Proper A n: Proper (vect_eq ==> transp_eq ==> vect_eq) (vect_transp (A:=A) (n:=n)).\n unfold Proper, respectful, transp_eq, vect_transp; intros; rewrite H; auto.\nQed.\n\nTheorem transp_involutive {n} (t: transp n): perm_eq (t :: t :: nil) nil.\n intros A v; apply vect_swap_involutive. Qed.\nTheorem transp_mult_left {n} (t: transp n) (p: perm n): t :: p = perm_mult (t :: nil) p.\n reflexivity. Qed.\nTheorem transp_mult_rigth {n} (t: transp n) (p: perm n): p ++ t :: nil = perm_mult p (t :: nil).\n reflexivity. Qed.\n\nInstance vect_perm_Proper A n: Proper (perm_eq ==> vect_eq ==> vect_eq) (vect_perm (A:=A) (n:=n)).\n pose proof vect_swap_Proper; unfold Proper, respectful in *; intros.\n assert (forall p v1 v2, vect_eq v1 v2 -> vect_eq (vect_perm (A:=A) (n:=n) p v1) (vect_perm p v2)) by\n  (induction p; intros; simpl; unfold vect_transp; auto).\n etransitivity; auto.\nQed.\n\nTheorem perm_mult_app {A n} (v: vect A n) (p1 p2: perm n): vect_perm (perm_mult p1 p2) v = vect_perm p2 (vect_perm p1 v).\n apply fold_left_app. Qed.\nTheorem perm_mult_assoc {n} (p1 p2 p3: perm n): perm_mult (perm_mult p1 p2) p3 = perm_mult p1 (perm_mult p2 p3).\n unfold perm_eq, vect_eq, perm_mult; rewrite List.app_assoc; auto.\nQed.\nInstance perm_mult_Proper n: Proper (perm_eq ==> perm_eq ==> perm_eq) (perm_mult (n:=n)).\n unfold Proper, respectful, perm_eq; intros.\n repeat rewrite perm_mult_app; rewrite H, H0; reflexivity.\nQed.\n\nTheorem transp_involutive_left {n} (t: transp n) (p: perm n): perm_eq (t :: t :: p) p.\n assert (t :: t :: p = perm_mult (t :: t :: nil) p) by auto.\n rewrite H, transp_involutive; reflexivity.\nQed.\nTheorem transp_involutive_right {n} (t: transp n) (p: perm n): perm_eq (perm_mult p (t :: t :: nil)) p.\n unfold perm_mult; rewrite transp_involutive, app_nil_r; reflexivity.\nQed.\n\nTheorem perm_mult_nil_left {n} (p: perm n): perm_mult nil p = p.\n reflexivity. Qed.\nTheorem perm_mult_nil_right {n} (p: perm n): perm_mult p nil = p.\n apply app_nil_r. Qed.\n\nTheorem perm_mult_inv {n} (p1 p2: perm n): perm_inv (perm_mult p1 p2) = perm_mult (perm_inv p2) (perm_inv p1).\n apply rev_app_distr. Qed.\nTheorem perm_inv_mult_left {n} (p: perm n): perm_eq (perm_mult (perm_inv p) p) nil.\n induction p.\n  reflexivity.\n  rewrite (transp_mult_left a p), perm_mult_inv, perm_mult_assoc; simpl; rewrite transp_involutive_left; auto.\nQed.\nTheorem perm_inv_mult_right {n} (p: perm n): perm_eq (perm_mult p (perm_inv p)) nil.\n induction p.\n  reflexivity.\n  rewrite (transp_mult_left a p), perm_mult_inv, perm_mult_assoc, <- (perm_mult_assoc p), IHp; apply transp_involutive_left.\nQed.\n\nTheorem perm_inv_involutive {n} (p: perm n): perm_eq (perm_inv (perm_inv p)) p.\n unfold perm_inv; rewrite rev_involutive; reflexivity.\nQed.\n\n(*\nDefinition T1 {A n} (v1 v2: vect A n) (t: transp n): vect_eq (vect_transp v1 t) (vect_transp v2 t) -> vect_eq v1 v2.\n intro. unfold vect_transp in *. rewrite <- (twice_transp_is_id t). rewrite <- (twice_transp_is_id t A v2).\n rewrite H. reflexivity.\nQed.\n\nDefinition T2 {A n} (v1 v2: vect A n) (p: perm n): vect_eq (vect_perm p v1) (vect_perm p v2) -> vect_eq v1 v2.\n revert v1 v2. induction p.\n  simpl in *. auto.\n  simpl in *. intros. apply IHp in H. apply T1 with (t:=a). auto.\nQed.\n*)\n\nTheorem T0 {n} (p p1 p2: perm n): perm_eq p1 p2 -> perm_eq (perm_mult p p1) (perm_mult p p2).\n intro; rewrite H; reflexivity.\nQed.\n\nTheorem T1 {n} (p: perm n): perm_eq nil p -> perm_eq (perm_inv p) nil.\n intro; apply (T0 (perm_inv p)) in H; rewrite perm_inv_mult_left, perm_mult_nil_right in H; auto.\nQed.\n\nInstance perm_inv_Proper n: Proper (perm_eq ==> perm_eq) (perm_inv (n:=n)).\n unfold Proper, respectful.\n induction x; intros.\n  symmetry; exact (T1 y H).\n  intros.\n   apply (T0 (a :: nil)) in H; simpl in H; rewrite transp_involutive_left in H; apply IHx in H.\n   rewrite transp_mult_left, perm_mult_inv, H; simpl (perm_inv (a :: nil)).\n   rewrite transp_mult_left, perm_mult_inv, perm_mult_assoc; simpl; rewrite transp_involutive_right; reflexivity.\nQed.\n\n\nInductive parity := even | odd.\nDefinition change_parity p := match p with even => odd | odd => even end.\nDefinition transp_is_id {n} (p: transp n) := eq_dec (fst p).1 (snd p).1.\nDefinition perm_parity {n} (p: perm n) :=\n List.fold_left (fun p t => if transp_is_id t then p else change_parity p) p even.\n", "meta": {"author": "zaarcis", "repo": "linear_algebra_in_Coq", "sha": "9d091fbe61b6895f8e9e2b486e44827cd4c959dc", "save_path": "github-repos/coq/zaarcis-linear_algebra_in_Coq", "path": "github-repos/coq/zaarcis-linear_algebra_in_Coq/linear_algebra_in_Coq-9d091fbe61b6895f8e9e2b486e44827cd4c959dc/permutations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.6645795697894248}}
{"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\n(** * Finite sets library *)\n\n(** This functor derives additional facts from [FSetInterface.S]. These\n  facts are mainly the specifications of [FSetInterface.S] written using\n  different styles: equivalence and boolean equalities.\n  Moreover, we prove that [E.Eq] and [Equal] are setoid equalities.\n*)\n\nRequire Import DecidableTypeEx.\nRequire Export FSetInterface.\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n(** First, a functor for Weak Sets in functorial version. *)\n\nModule WFacts_fun (Import E : DecidableType)(Import M : WSfun E).\n\nNotation eq_dec := E.eq_dec.\nDefinition eqb x y := if eq_dec x y then true else false.\n\n(** * Specifications written using equivalences *)\n\nSection IffSpec.\nVariable s s' s'' : t.\nVariable x y z : elt.\n\nLemma In_eq_iff : E.eq x y -> (In x s <-> In y s).\nProof.\nsplit; apply In_1; auto.\nQed.\n\nLemma mem_iff : In x s <-> mem x s = true.\nProof.\nsplit; [apply mem_1|apply mem_2].\nQed.\n\nLemma not_mem_iff : ~In x s <-> mem x s = false.\nProof.\nrewrite mem_iff; destruct (mem x s); intuition.\nQed.\n\nLemma equal_iff : s[=]s' <-> equal s s' = true.\nProof.\nsplit; [apply equal_1|apply equal_2].\nQed.\n\nLemma subset_iff : s[<=]s' <-> subset s s' = true.\nProof.\nsplit; [apply subset_1|apply subset_2].\nQed.\n\nLemma empty_iff : In x empty <-> False.\nProof.\nintuition; apply (empty_1 H).\nQed.\n\nLemma is_empty_iff : Empty s <-> is_empty s = true.\nProof.\nsplit; [apply is_empty_1|apply is_empty_2].\nQed.\n\nLemma singleton_iff : In y (singleton x) <-> E.eq x y.\nProof.\nsplit; [apply singleton_1|apply singleton_2].\nQed.\n\nLemma add_iff : In y (add x s) <-> E.eq x y \\/ In y s.\nProof.\nsplit; [ | destruct 1; [apply add_1|apply add_2]]; auto.\ndestruct (eq_dec x y) as [E|E]; auto.\nintro H; right; exact (add_3 E H).\nQed.\n\nLemma add_neq_iff : ~ E.eq x y -> (In y (add x s)  <-> In y s).\nProof.\nsplit; [apply add_3|apply add_2]; auto.\nQed.\n\nLemma remove_iff : In y (remove x s) <-> In y s /\\ ~E.eq x y.\nProof.\nsplit; [split; [apply remove_3 with x |] | destruct 1; apply remove_2]; auto.\nintro.\napply (remove_1 H0 H).\nQed.\n\nLemma remove_neq_iff : ~ E.eq x y -> (In y (remove x s) <-> In y s).\nProof.\nsplit; [apply remove_3|apply remove_2]; auto.\nQed.\n\nLemma union_iff : In x (union s s') <-> In x s \\/ In x s'.\nProof.\nsplit; [apply union_1 | destruct 1; [apply union_2|apply union_3]]; auto.\nQed.\n\nLemma inter_iff : In x (inter s s') <-> In x s /\\ In x s'.\nProof.\nsplit; [split; [apply inter_1 with s' | apply inter_2 with s] | destruct 1; apply inter_3]; auto.\nQed.\n\nLemma diff_iff : In x (diff s s') <-> In x s /\\ ~ In x s'.\nProof.\nsplit; [split; [apply diff_1 with s' | apply diff_2 with s] | destruct 1; apply diff_3]; auto.\nQed.\n\nVariable f : elt->bool.\n\nLemma filter_iff :  compat_bool E.eq f -> (In x (filter f s) <-> In x s /\\ f x = true).\nProof.\nsplit; [split; [apply filter_1 with f | apply filter_2 with s] | destruct 1; apply filter_3]; auto.\nQed.\n\nLemma for_all_iff : compat_bool E.eq f ->\n  (For_all (fun x => f x = true) s <-> for_all f s = true).\nProof.\nsplit; [apply for_all_1 | apply for_all_2]; auto.\nQed.\n\nLemma exists_iff : compat_bool E.eq f ->\n  (Exists (fun x => f x = true) s <-> exists_ f s = true).\nProof.\nsplit; [apply exists_1 | apply exists_2]; auto.\nQed.\n\nLemma elements_iff : In x s <-> InA E.eq x (elements s).\nProof.\nsplit; [apply elements_1 | apply elements_2].\nQed.\n\nEnd IffSpec.\n\n(** Useful tactic for simplifying expressions like [In y (add x (union s s'))] *)\n\nLtac set_iff :=\n repeat (progress (\n  rewrite add_iff || rewrite remove_iff || rewrite singleton_iff\n  || rewrite union_iff || rewrite inter_iff || rewrite diff_iff\n  || rewrite empty_iff)).\n\n(**  * Specifications written using boolean predicates *)\n\nSection BoolSpec.\nVariable s s' s'' : t.\nVariable x y z : elt.\n\nLemma mem_b : E.eq x y -> mem x s = mem y s.\nProof.\nintros.\ngeneralize (mem_iff s x) (mem_iff s y)(In_eq_iff s H).\ndestruct (mem x s); destruct (mem y s); intuition.\nQed.\n\nLemma empty_b : mem y empty = false.\nProof.\ngeneralize (empty_iff y)(mem_iff empty y).\ndestruct (mem y empty); intuition.\nQed.\n\nLemma add_b : mem y (add x s) = eqb x y || mem y s.\nProof.\ngeneralize (mem_iff (add x s) y)(mem_iff s y)(add_iff s x y); unfold eqb.\ndestruct (eq_dec x y); destruct (mem y s); destruct (mem y (add x s)); intuition.\nQed.\n\nLemma add_neq_b : ~ E.eq x y -> mem y (add x s) = mem y s.\nProof.\nintros; generalize (mem_iff (add x s) y)(mem_iff s y)(add_neq_iff s H).\ndestruct (mem y s); destruct (mem y (add x s)); intuition.\nQed.\n\nLemma remove_b : mem y (remove x s) = mem y s && negb (eqb x y).\nProof.\ngeneralize (mem_iff (remove x s) y)(mem_iff s y)(remove_iff s x y); unfold eqb.\ndestruct (eq_dec x y); destruct (mem y s); destruct (mem y (remove x s)); simpl; intuition.\nQed.\n\nLemma remove_neq_b : ~ E.eq x y -> mem y (remove x s) = mem y s.\nProof.\nintros; generalize (mem_iff (remove x s) y)(mem_iff s y)(remove_neq_iff s H).\ndestruct (mem y s); destruct (mem y (remove x s)); intuition.\nQed.\n\nLemma singleton_b : mem y (singleton x) = eqb x y.\nProof.\ngeneralize (mem_iff (singleton x) y)(singleton_iff x y); unfold eqb.\ndestruct (eq_dec x y); destruct (mem y (singleton x)); intuition.\nQed.\n\nLemma union_b : mem x (union s s') = mem x s || mem x s'.\nProof.\ngeneralize (mem_iff (union s s') x)(mem_iff s x)(mem_iff s' x)(union_iff s s' x).\ndestruct (mem x s); destruct (mem x s'); destruct (mem x (union s s')); intuition.\nQed.\n\nLemma inter_b : mem x (inter s s') = mem x s && mem x s'.\nProof.\ngeneralize (mem_iff (inter s s') x)(mem_iff s x)(mem_iff s' x)(inter_iff s s' x).\ndestruct (mem x s); destruct (mem x s'); destruct (mem x (inter s s')); intuition.\nQed.\n\nLemma diff_b : mem x (diff s s') = mem x s && negb (mem x s').\nProof.\ngeneralize (mem_iff (diff s s') x)(mem_iff s x)(mem_iff s' x)(diff_iff s s' x).\ndestruct (mem x s); destruct (mem x s'); destruct (mem x (diff s s')); simpl; intuition.\nQed.\n\nLemma elements_b : mem x s = existsb (eqb x) (elements s).\nProof.\ngeneralize (mem_iff s x)(elements_iff s x)(existsb_exists (eqb x) (elements s)).\nrewrite InA_alt.\ndestruct (mem x s); destruct (existsb (eqb x) (elements s)); auto; intros.\nsymmetry.\nrewrite H1.\ndestruct H0 as (H0,_).\ndestruct H0 as (a,(Ha1,Ha2)); [ intuition |].\nexists a; intuition.\nunfold eqb; destruct (eq_dec x a); auto.\nrewrite <- H.\nrewrite H0.\ndestruct H1 as (H1,_).\ndestruct H1 as (a,(Ha1,Ha2)); [intuition|].\nexists a; intuition.\nunfold eqb in *; destruct (eq_dec x a); auto; discriminate.\nQed.\n\nVariable f : elt->bool.\n\nLemma filter_b : compat_bool E.eq f -> mem x (filter f s) = mem x s && f x.\nProof.\nintros.\ngeneralize (mem_iff (filter f s) x)(mem_iff s x)(filter_iff s x H).\ndestruct (mem x s); destruct (mem x (filter f s)); destruct (f x); simpl; intuition.\nQed.\n\nLemma for_all_b : compat_bool E.eq f ->\n  for_all f s = forallb f (elements s).\nProof.\nintros.\ngeneralize (forallb_forall f (elements s))(for_all_iff s H)(elements_iff s).\nunfold For_all.\ndestruct (forallb f (elements s)); destruct (for_all f s); auto; intros.\nrewrite <- H1; intros.\ndestruct H0 as (H0,_).\nrewrite (H2 x0) in H3.\nrewrite (InA_alt E.eq x0 (elements s)) in H3.\ndestruct H3 as (a,(Ha1,Ha2)).\nrewrite (H _ _ Ha1).\napply H0; auto.\nsymmetry.\nrewrite H0; intros.\ndestruct H1 as (_,H1).\napply H1; auto.\nrewrite H2.\nrewrite InA_alt; eauto.\nQed.\n\nLemma exists_b : compat_bool E.eq f ->\n  exists_ f s = existsb f (elements s).\nProof.\nintros.\ngeneralize (existsb_exists f (elements s))(exists_iff s H)(elements_iff s).\nunfold Exists.\ndestruct (existsb f (elements s)); destruct (exists_ f s); auto; intros.\nrewrite <- H1; intros.\ndestruct H0 as (H0,_).\ndestruct H0 as (a,(Ha1,Ha2)); auto.\nexists a; split; auto.\nrewrite H2; rewrite InA_alt; eauto.\nsymmetry.\nrewrite H0.\ndestruct H1 as (_,H1).\ndestruct H1 as (a,(Ha1,Ha2)); auto.\nrewrite (H2 a) in Ha1.\nrewrite (InA_alt E.eq a (elements s)) in Ha1.\ndestruct Ha1 as (b,(Hb1,Hb2)).\nexists b; auto.\nrewrite <- (H _ _ Hb1); auto.\nQed.\n\nEnd BoolSpec.\n\n(** * [E.eq] and [Equal] are setoid equalities *)\n\nInstance E_ST : Equivalence E.eq.\nProof.\nconstructor ; red; [apply E.eq_refl|apply E.eq_sym|apply E.eq_trans].\nQed.\n\nInstance Equal_ST : Equivalence Equal.\nProof.\nconstructor ; red; [apply eq_refl | apply eq_sym | apply eq_trans].\nQed.\n\nInstance In_m : Proper (E.eq ==> Equal ==> iff) In.\nProof.\nunfold Equal; intros x y H s s' H0.\nrewrite (In_eq_iff s H); auto.\nQed.\n\nInstance is_empty_m : Proper (Equal==> Logic.eq) is_empty.\nProof.\nunfold Equal; intros s s' H.\ngeneralize (is_empty_iff s)(is_empty_iff s').\ndestruct (is_empty s); destruct (is_empty s');\n unfold Empty; auto; intros.\nsymmetry.\nrewrite <- H1; intros a Ha.\nrewrite <- (H a) in Ha.\ndestruct H0 as (_,H0).\nexact (H0 (refl_equal true) _ Ha).\nrewrite <- H0; intros a Ha.\nrewrite (H a) in Ha.\ndestruct H1 as (_,H1).\nexact (H1 (refl_equal true) _ Ha).\nQed.\n\nInstance Empty_m : Proper (Equal ==> iff) Empty.\nProof.\nrepeat red; intros; do 2 rewrite is_empty_iff; rewrite H; intuition.\nQed.\n\nInstance mem_m : Proper (E.eq ==> Equal ==> Logic.eq) mem.\nProof.\nunfold Equal; intros x y H s s' H0.\ngeneralize (H0 x); clear H0; rewrite (In_eq_iff s' H).\ngeneralize (mem_iff s x)(mem_iff s' y).\ndestruct (mem x s); destruct (mem y s'); intuition.\nQed.\n\nInstance singleton_m : Proper (E.eq ==> Equal) singleton.\nProof.\nunfold Equal; intros x y H a.\ndo 2 rewrite singleton_iff; split; intros.\napply E.eq_trans with x; auto.\napply E.eq_trans with y; auto.\nQed.\n\nInstance add_m : Proper (E.eq==>Equal==>Equal) add.\nProof.\nunfold Equal; intros x y H s s' H0 a.\ndo 2 rewrite add_iff; rewrite H; rewrite H0; intuition.\nQed.\n\nInstance remove_m : Proper (E.eq==>Equal==>Equal) remove.\nProof.\nunfold Equal; intros x y H s s' H0 a.\ndo 2 rewrite remove_iff; rewrite H; rewrite H0; intuition.\nQed.\n\nInstance union_m : Proper (Equal==>Equal==>Equal) union.\nProof.\nunfold Equal; intros s s' H s'' s''' H0 a.\ndo 2 rewrite union_iff; rewrite H; rewrite H0; intuition.\nQed.\n\nInstance inter_m : Proper (Equal==>Equal==>Equal) inter.\nProof.\nunfold Equal; intros s s' H s'' s''' H0 a.\ndo 2 rewrite inter_iff; rewrite H; rewrite H0; intuition.\nQed.\n\nInstance diff_m : Proper (Equal==>Equal==>Equal) diff.\nProof.\nunfold Equal; intros s s' H s'' s''' H0 a.\ndo 2 rewrite diff_iff; rewrite H; rewrite H0; intuition.\nQed.\n\nInstance Subset_m : Proper (Equal==>Equal==>iff) Subset.\nProof.\nunfold Equal, Subset; firstorder.\nQed.\n\nInstance subset_m : Proper (Equal ==> Equal ==> Logic.eq) subset.\nProof.\nintros s s' H s'' s''' H0.\ngeneralize (subset_iff s s'') (subset_iff s' s''').\ndestruct (subset s s''); destruct (subset s' s'''); auto; intros.\nrewrite H in H1; rewrite H0 in H1; intuition.\nrewrite H in H1; rewrite H0 in H1; intuition.\nQed.\n\nInstance equal_m : Proper (Equal ==> Equal ==> Logic.eq) equal.\nProof.\nintros s s' H s'' s''' H0.\ngeneralize (equal_iff s s'') (equal_iff s' s''').\ndestruct (equal s s''); destruct (equal s' s'''); auto; intros.\nrewrite H in H1; rewrite H0 in H1; intuition.\nrewrite H in H1; rewrite H0 in H1; intuition.\nQed.\n\n\n(* [Subset] is a setoid order *)\n\nLemma Subset_refl : forall s, s[<=]s.\nProof. red; auto. Qed.\n\nLemma Subset_trans : forall s s' s'', s[<=]s'->s'[<=]s''->s[<=]s''.\nProof. unfold Subset; eauto. Qed.\n\nAdd Relation t Subset\n reflexivity proved by Subset_refl\n transitivity proved by Subset_trans\n as SubsetSetoid.\n\nInstance In_s_m : Morphisms.Proper (E.eq ==> Subset ++> Basics.impl) In | 1.\nProof.\n  simpl_relation. eauto with set.\nQed.\n\nAdd Morphism Empty with signature Subset --> Basics.impl as Empty_s_m.\nProof.\nunfold Subset, Empty, Basics.impl; firstorder.\nQed.\n\nAdd Morphism add with signature E.eq ==> Subset ++> Subset as add_s_m.\nProof.\nunfold Subset; intros x y H s s' H0 a.\ndo 2 rewrite add_iff; rewrite H; intuition.\nQed.\n\nAdd Morphism remove with signature E.eq ==> Subset ++> Subset as remove_s_m.\nProof.\nunfold Subset; intros x y H s s' H0 a.\ndo 2 rewrite remove_iff; rewrite H; intuition.\nQed.\n\nAdd Morphism union with signature Subset ++> Subset ++> Subset as union_s_m.\nProof.\nunfold Equal; intros s s' H s'' s''' H0 a.\ndo 2 rewrite union_iff; intuition.\nQed.\n\nAdd Morphism inter with signature Subset ++> Subset ++> Subset as inter_s_m.\nProof.\nunfold Equal; intros s s' H s'' s''' H0 a.\ndo 2 rewrite inter_iff; intuition.\nQed.\n\nAdd Morphism diff with signature Subset ++> Subset --> Subset as diff_s_m.\nProof.\nunfold Subset; intros s s' H s'' s''' H0 a.\ndo 2 rewrite diff_iff; intuition.\nQed.\n\n(* [fold], [filter], [for_all], [exists_] and [partition] cannot be proved morphism\n   without additional hypothesis on [f]. For instance: *)\n\nLemma filter_equal : forall f, compat_bool E.eq f ->\n  forall s s', s[=]s' -> filter f s [=] filter f s'.\nProof.\nunfold Equal; intros; repeat rewrite filter_iff; auto; rewrite H0; tauto.\nQed.\n\nLemma filter_ext : forall f f', compat_bool E.eq f -> (forall x, f x = f' x) ->\n forall s s', s[=]s' -> filter f s [=] filter f' s'.\nProof.\nintros f f' Hf Hff' s s' Hss' x. do 2 (rewrite filter_iff; auto).\nrewrite Hff', Hss'; intuition.\nrepeat red; intros; rewrite <- 2 Hff'; auto.\nQed.\n\nLemma filter_subset : forall f, compat_bool E.eq f ->\n  forall s s', s[<=]s' -> filter f s [<=] filter f s'.\nProof.\nunfold Subset; intros; rewrite filter_iff in *; intuition.\nQed.\n\n(* For [elements], [min_elt], [max_elt] and [choose], we would need setoid\n   structures on [list elt] and [option elt]. *)\n\n(* Later:\nAdd Morphism cardinal ; cardinal_m.\n*)\n\nEnd WFacts_fun.\n\n(** Now comes variants for self-contained weak sets and for full sets.\n    For these variants, only one argument is necessary. Thanks to\n    the subtyping [WS<=S], the [Facts] functor which is meant to be\n    used on modules [(M:S)] can simply be an alias of [WFacts]. *)\n\nModule WFacts (M:WS) := WFacts_fun M.E M.\nModule Facts := WFacts.\n\n\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/FSets/FSetFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.6645795677964033}}
{"text": "(** * 6.887 Formal Reasoning About Programs, Spring 2016 - Pset 1 *)\n\nRequire Import Frap Pset1Sig.\n\n(* Authors: Peng Wang (wangpeng@csail.mit.edu), Adam Chlipala (adamc@csail.mit.edu) *)\n\n\n(** * MapReduce *)\n\nLemma add_positive : forall n m,\n  n > 0\n  -> m > 0\n  -> n + m > 0.\nProof.\n  linear_arithmetic.\nQed.\n\nTheorem allPositive_ok : forall m x,\n  allPositive m\n  -> x > 0\n  -> interp_map m x > 0.\nProof.\n  induct m; simplify; propositional.\n\n  apply add_positive.\n  apply IHm1.\n  trivial.\n  trivial.\n  apply IHm2.\n  trivial.\n  trivial.\n\n  apply IHm1.\n  trivial.\n  apply IHm2.\n  trivial.\n  trivial.\nQed.\n\nLemma fold_left_swap' : forall A (f : A -> A -> A),\n  (forall x y : A, f x y = f y x)\n  (* Operator is commutative. *)\n  -> (forall x y z : A, f (f x y) z = f x (f y z))\n  (* Operator is associative. *)\n  -> forall ls a b,\n      fold_left f ls (f a b) = f (fold_left f ls a) b.\nProof.\n  induct ls; simplify; try equality.\nQed.\n\nLemma fold_left_swap : forall A (f : A -> A -> A),\n  (forall x y : A, f x y = f y x)\n  (* Operator is commutative. *)\n  -> (forall x y z : A, f (f x y) z = f x (f y z))\n  (* Operator is associative. *)\n  -> forall ls1 ls2 init,\n      fold_left f (ls1 ++ ls2) init = fold_left f (ls2 ++ ls1) init.\nProof.\n  induct ls1; simplify.\n  {\n    rewrite app_nil_r.\n    equality.\n  }\n  {\n    rewrite IHls1.\n    rewrite fold_left_app.\n    rewrite fold_left_app.\n    simplify.\n    f_equal.\n    apply fold_left_swap'; trivial.\n  }\nQed.\n\nLemma reduce_swap : forall e ls1 ls2,\n  interp_reduce e (ls1 ++ ls2) = interp_reduce e (ls2 ++ ls1).\nProof.\n  unfold interp_reduce; simplify.\n  cases e; apply fold_left_swap; simplify; linear_arithmetic.\nQed.\n\nLemma interp_swap : forall e ls1 ls2, interp_mr e (ls1 ++ ls2) = interp_mr e (ls2 ++ ls1).\nProof.\n  induct e; simplify.\n  unfold interp_mr; simplify.\n  rewrite map_app.\n  rewrite map_app.\n  apply reduce_swap.\nQed.\n\nLemma fold_left_par' : forall A (f : A -> A -> A) (rzero : A),\n    (forall x y z : A, f (f x y) z = f x (f y z))\n    (* Operator is associative. *)\n    -> (forall x, f x rzero = x)\n    (* [rzero] is a right zero for operator. *)\n    -> forall ls init, fold_left f ls init = f init (fold_left f ls rzero).\nProof.\n  induct ls; simplify; equality.\nQed.\n\nLemma fold_left_par : forall A (f : A -> A -> A) (rzero : A),\n    (forall x y z : A, f (f x y) z = f x (f y z))\n    (* Operator is associative. *)\n    -> (forall x, f x rzero = x)\n    (* [rzero] is a right zero for operator. *)\n    -> forall ls1 ls2 init,\n        fold_left f (ls1 ++ ls2) init = f (fold_left f ls1 init) (fold_left f ls2 rzero).\nProof.\n  induct ls1; simplify; try equality.\n  apply fold_left_par'.\n  trivial.\n  trivial.\nQed.\n\nLemma mapReduce_partition_two : forall m r ls1 ls2,\n    interp_mr (m, r) (ls1 ++ ls2) = interp_reduce r [interp_mr (m, r) ls1; interp_mr (m, r) ls2].\nProof.\n  unfold interp_mr; simplify.\n  cases r; simplify; rewrite map_app; apply fold_left_par; linear_arithmetic.\nQed.\n\nArguments app {_} _ _ .\n\nLemma mapReduce_partition' : forall m r lsls init,\n    interp_mr (m, r) (fold_left app lsls init)\n    = interp_reduce r (interp_mr (m, r) init :: map (interp_mr (m, r)) lsls).\nProof.\n  induct lsls; simplify.\n  {\n    unfold interp_reduce; simplify.\n    cases r; linear_arithmetic.\n  }\n  {\n    rewrite IHlsls.\n    rewrite mapReduce_partition_two.\n    cases r; simplify; linear_arithmetic.\n  }\nQed.\n\nLemma mapReduce_partition : forall m r lsls,\n    interp_mr (m, r) (fold_left app lsls []) = interp_reduce r (map (interp_mr (m, r)) lsls).\nProof.\n  induct lsls; simplify; try equality.\n  apply mapReduce_partition'.\nQed.\n\n\n(** * Constant propagation *)\n\nTheorem constPropArith_ok : forall v1 v2 e,\n  (forall x n, v1 $? x = Some n -> v2 $? x = Some n)\n  -> interp (constPropArith e v1) v2 = interp e v2.\nProof.\n  induct e; simplify; propositional.\n\n  cases (v1 $? x); simplify; try equality.\n  rewrite (H x n); simplify; equality.\n\n  cases (constPropArith e1 v1); simplify; try equality.\n  cases (constPropArith e2 v1); simplify; equality.\n\n  cases (constPropArith e1 v1); simplify; try equality.\n  cases (constPropArith e2 v1); simplify; equality.\n\n  cases (constPropArith e1 v1); simplify; try equality.\n  cases (constPropArith e2 v1); simplify; equality.\nQed.\n\nTheorem effectOf_ok : forall c v1 v2,\n  (forall x n, v1 $? x = Some n -> v2 $? x = Some n)\n  -> (forall x n, effectOf c v1 $? x = Some n\n                  -> exec c v2 $? x = Some n).\nProof.\n  induct c; simplify; try equality.\n\n  apply H.\n  trivial.\n\n  cases (constPropArith e v1).\n  rewrite <- (constPropArith_ok v1).\n  cases (x ==v x0); simplify; try equality.\n  rewrite Heq.\n  simplify.\n  trivial.\n  apply H.\n  trivial.\n  trivial.\n\n  cases (x ==v x0); simplify; try equality.\n  apply H.\n  trivial.\n\n  cases (x ==v x0); simplify; try equality.\n  apply H.\n  trivial.\n\n  cases (x ==v x0); simplify; try equality.\n  apply H.\n  trivial.\n\n  cases (x ==v x0); simplify; try equality.\n  apply H.\n  trivial.\n\n  apply (IHc2 (effectOf c1 v1)).\n  apply IHc1.\n  trivial.\n  trivial.\nQed.\n\nTheorem constProp_ok : forall c v1 v2,\n  (forall x n, v1 $? x = Some n -> v2 $? x = Some n)\n  -> exec (constProp c v1) v2 = exec c v2.\nProof.\n  induct c; simplify; propositional.\n\n  rewrite constPropArith_ok.\n  trivial.\n  trivial.\n\n  rewrite IHc1.\n  rewrite IHc2.\n  trivial.\n  trivial.\n  apply effectOf_ok.\n  trivial.\n  trivial.\n\n  rewrite constPropArith_ok.\n  apply selfCompose_extensional.\n  simplify.\n  apply IHc.\n  simplify.\n  equality.\n  trivial.\nQed.  \n\nTheorem constProp_ok0 : forall c v,\n  exec (constProp c $0) v = exec c v.\nProof.\n  simplify.\n  apply constProp_ok.\n  simplify.\n  equality.\nQed.\n", "meta": {"author": "emzhang", "repo": "887psets", "sha": "7b5c19f2eb0b0e549f10fa7bcbb1c873e5a77918", "save_path": "github-repos/coq/emzhang-887psets", "path": "github-repos/coq/emzhang-887psets/887psets-7b5c19f2eb0b0e549f10fa7bcbb1c873e5a77918/pset1/Pset1Sol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.664517150039778}}
{"text": "Require Import List Bool.\n\nImport ListNotations.\n\nStructure dfa (A B : Type) := {\n  t : A -> B -> A;\n  s : A;\n\n  F : A -> bool;\n}.\n\nArguments t {A} {B}.\nArguments s {A} {B}.\nArguments F {A} {B}.\n\nFixpoint tStar {A B : Type} (M : dfa A B) (q : A) (str : list B) : A :=\n  match str with\n  | []      => q\n  | x :: xs => tStar M (t M q x) xs\n  end.\n\nDefinition accepted {A B : Type} (M : dfa A B) (str : list B) : bool :=\n  F M (tStar M (s M) str).\n\nLemma tStar_step :\n  forall {A B : Type} (M : dfa A B) (str : list B) (q : A) (x : B), \n    tStar M q (str ++ [x]) = t M (tStar M q str) x.\nProof.\nintros A B M str.\n\ninduction str.\nintuition.\n\nintuition.\nsimpl.\nexact (IHstr (t M q a) x).\nQed.\n\nDefinition not_dfa_f {A B : Type} (M : dfa A B) (q : A) : bool := negb (F M q).\n\nDefinition not_dfa {A B : Type} (M : dfa A B) : dfa A B :=\n  Build_dfa A B (t M) (s M) (not_dfa_f M).\n\nLemma not_dfa_mirror {A B : Type} (M : dfa A B) : \n  forall (str : list B), tStar M (s M) str = tStar (not_dfa M) (s M) str.\nProof.\napply rev_ind.\n\nintuition.\n\nintuition.\nrewrite tStar_step, tStar_step.\nsimpl.\nrewrite H.\nreflexivity.\nQed.\n\nTheorem not_dfa_correct :\n  forall {A B : Type} (M : dfa A B) (str : list B),\n   accepted M str = true <-> accepted (not_dfa M) str = false.\nProof.\nintros.\nunfold accepted.\nsimpl.\nrewrite not_dfa_mirror.\nunfold not_dfa_f.\nintuition.\nrewrite H.\nintuition.\ninduction (F M (tStar (not_dfa M) (s M) str)).\nintuition.\nintuition.\nQed.\n\nDefinition and_dfa_trans\n  {A B C : Type} (M : dfa A B) (N : dfa C B) (q : A * C) (s : B) : A * C :=\n  match q with\n  | (qm, qn) => (t M qm s, t N qn s)\n  end.\n\nDefinition and_dfa_f {A B C : Type} (M : dfa A B) (N : dfa C B) (q : A * C) : bool :=\n  match q with\n  | (a,c) => F M a && F N c\n  end.\n\nDefinition and_dfa {A B C : Type} (M : dfa A B) (N : dfa C B) : dfa (A * C) B :=\n  Build_dfa (A * C) B\n            (and_dfa_trans M N) (s M, s N) (and_dfa_f M N).\n\nLemma and_dfa_mirror_m\n  {A B C : Type} (M : dfa A B) (N : dfa C B) :\n    forall (str : list B), tStar M (s M) str = fst (tStar (and_dfa M N) (s (and_dfa M N)) str).\nProof.\napply rev_ind.\n\nintuition.\n\nintros.\n\nrewrite tStar_step, tStar_step.\ndestruct (tStar (and_dfa M N) (s (and_dfa M N)) l).\nunfold and_dfa.\nsimpl.\nrewrite H.\nintuition.\nQed.\n\nLemma and_dfa_mirror_n\n  {A B C : Type} (M : dfa A B) (N : dfa C B) :\n    forall (str : list B), tStar N (s N) str = snd (tStar (and_dfa M N) (s (and_dfa M N)) str).\nProof.\napply rev_ind.\n\nintuition.\n\nintros.\n\nrewrite tStar_step.\nrewrite tStar_step.\ndestruct (tStar (and_dfa M N) (s (and_dfa M N)) l).\nunfold and_dfa.\nsimpl.\nrewrite H.\nintuition.\nQed.\n\nTheorem and_dfa_correct :\n  forall {A B C : Type} (M : dfa A B) (N : dfa C B) (str : list B),\n    accepted (and_dfa M N) str = true <-> accepted M str && accepted N str = true.\nProof.\nintros.\nunfold accepted.\nrewrite (and_dfa_mirror_m M N str).\nrewrite (and_dfa_mirror_n M N str).\ndestruct (tStar (and_dfa M N) (s (and_dfa M N)) str).\nsimpl.\n\nintuition.\nQed.\n", "meta": {"author": "ReedOei", "repo": "FormalModelsOfComputation", "sha": "75d70b89f05781b11a24114a4fc1311f78bf59e6", "save_path": "github-repos/coq/ReedOei-FormalModelsOfComputation", "path": "github-repos/coq/ReedOei-FormalModelsOfComputation/FormalModelsOfComputation-75d70b89f05781b11a24114a4fc1311f78bf59e6/InProgress/quant.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6645171397370848}}
{"text": "Require Import Arith.\nRequire Import List.\nRequire Import Relations.\nRequire Import Wellfounded.\nRequire Import list_util.\nRequire Import FSA.\n\nSet Implicit Arguments.\n\nHint Resolve le_plus_r le_plus_l le_n_S le_S_n.\n\nSection CharType.\n\nVariable C: Set.\nVariable C_eq_dec: forall x y:C, {x=y}+{x<>y}.\n\nInductive RegExp: Set:=\n| Rnil: RegExp\n| Rchar: C -> RegExp\n| Rcons: RegExp -> RegExp -> RegExp\n| Ror: RegExp -> RegExp -> RegExp\n| Rstar: RegExp -> RegExp\n.\n\nInductive Racc: RegExp -> list C -> Prop:=\n|RAchar : forall c, Racc (Rchar c) (c::nil)\n|RAcons : forall l m r s, Racc r l -> Racc s m -> Racc (Rcons r s) (l++m)\n|RAor1  : forall l r s, Racc r l -> Racc (Ror r s) l\n|RAor2  : forall l r s, Racc s l -> Racc (Ror r s) l\n|RAstar1: forall r, Racc (Rstar r) nil\n|RAstar2: forall r l m, Racc r l -> Racc (Rstar r) m -> Racc (Rstar r) (l++m)\n.\nHint Constructors Racc.\n\nDefinition Remp:=Rstar Rnil.\nTheorem Remp_spec: forall w, Racc Remp w<-> w=nil. Proof. unfold Remp. intros; split; intros; [|subst w]; auto. inversion H; auto. inversion H1. Qed.\nTheorem Rnil_spec: forall w, ~Racc Rnil w. Proof. intros w D. inversion D. Qed.\nTheorem Rchar_spec: forall w c, Racc (Rchar c) w <-> w=c::nil. Proof. intros; split; intros. inversion H; auto. subst w; auto. Qed.\nDefinition Rword w:=fold_right (fun c r=>Rcons (Rchar c) r) Remp w.\nTheorem Rword_spec: forall w s, Racc (Rword w) s <-> s=w. Proof. induction w; intros; simpl; split; intros. apply Remp_spec; auto. apply Remp_spec; auto. inversion H. inversion H2. simpl. f_equal. apply IHw; auto. subst s. replace (a::w) with ((a::nil)++w); auto. apply RAcons; auto. apply IHw; auto. Qed.\nHint Resolve Remp_spec Rnil_spec Rchar_spec Rword_spec.\n\nDefinition Rincl: relation RegExp:= fun r s=>forall w, Racc r w -> Racc s w.\nDefinition Req: relation RegExp:= fun r s=> Rincl r s /\\ Rincl s r.\n\nTheorem Rstar_app: forall r l m, Racc (Rstar r) l -> Racc (Rstar r) m -> Racc (Rstar r) (l++m). Proof. intros r l m H H0. revert H0. revert m. remember (Rstar r) as r1. revert Heqr1. induction H; intros; try discriminate Heqr1; simpl; auto. rewrite <- app_assoc. apply RAstar2; auto. Qed.\nTheorem Rstar_one: forall r w, Racc r w -> Racc (Rstar r) w. Proof. intros. destruct w; auto. rewrite <- app_nil_r; apply RAstar2; auto. Qed.\nTheorem Rstar_incl: forall r s, Rincl r s -> Rincl (Rstar r) (Rstar s). Proof. intros. intros w H0. remember (Rstar r) as r1. revert Heqr1. induction H0; intros; try discriminate Heqr1; auto. inversion Heqr1. subst r0. auto. Qed.\nTheorem Rstar_rev': forall r w, Racc (Rstar r) w -> w<>nil -> exists l m, Racc r l /\\ Racc (Rstar r) m /\\ l<>nil /\\ w=l++m. intros r w H. remember (Rstar r) as s. revert Heqs. revert r.  induction H; intros; try discriminate Heqs. contradict H; auto. inversion Heqs. subst r0. clear IHRacc1. destruct (list_eq_dec C_eq_dec m nil). subst m. exists l. exists nil. rewrite app_nil_r in H1. auto. destruct IHRacc2 with (r0:=r) as [l' [m' [H2 [H3 [H4 H5]]]]]; auto. subst m. destruct (list_eq_dec C_eq_dec l nil). subst l. exists l'. exists m'; auto. exists l. exists (l'++m'); auto. Qed.\nHint Resolve Rstar_app Rstar_one Rstar_incl Rstar_rev'.\n\nDefinition Racc_dec: forall r w,{Racc r w}+{~Racc r w}. induction r; intros. right. intros H; inversion H. destruct (list_eq_dec C_eq_dec w (c::nil)); [subst w; left|right]; auto. contradict n; inversion n; auto. destruct (splits w) as [l H _]. destruct (findP (fun p=>Racc r1 (fst p)/\\Racc r2 (snd p)) l) as [[[w1 w2] H0 [H1 H2]]|H0]; [|left|right]. intros p _. destruct (IHr1 (fst p)); [destruct (IHr2 (snd p)); [left|right]|right]; auto; contradict n; destruct n; auto. apply H in H0. subst w; auto. intros D; inversion D. subst r s w. absurd (Racc r1 (fst (l0,m))/\\Racc r2 (snd (l0,m))); auto. apply H0. apply H; auto. destruct (IHr1 w); [left| destruct (IHr2 w);[left|right]]; auto. intros D; inversion D; auto.\n  apply (Fix (well_founded_ltof (list C) (length (A:=C)))) with (P:=fun w=>{Racc (Rstar r) w}+{~Racc (Rstar r) w}). clear w. intros w IH. destruct w. left; auto. destruct (splits w) as [l H _]. destruct (findP (fun p=>Racc r (c::fst p)/\\Racc (Rstar r) (snd p)) l) as [[[w1 w2] H0 [H1 H2]]|H0]; [|left|right]. intros p H0. destruct (IHr (c::fst p)). destruct (IH (snd p)); [|left|right]; auto. unfold ltof. simpl. apply le_n_S. apply H in H0. subst w. rewrite app_length; auto. contradict n; destruct n; auto. right; contradict n; destruct n; auto. apply H in H0. subst w. simpl. replace (c::w1++w2) with ((c::w1)++w2); auto. intros D. destruct (Rstar_rev' D) as [w1 [w2 [H1 [H2 [H3 H4]]]]]. discriminate. destruct w1. contradict H3; auto. inversion H4. subst c0 w. absurd (Racc r (c::fst (w1,w2))/\\Racc (Rstar r) (snd (w1,w2))); auto. apply H0. apply H; auto. Defined.\nDefinition Rshortest: forall r, {w| Racc r w & forall s, Racc r s -> length w <= length s}+{forall w, ~Racc r w}. induction r. right; auto. left; exists (c::nil); auto. intros. apply Rchar_spec in H. subst s; auto. destruct IHr1 as [[w H1 H2]|H1]; [destruct IHr2 as [[s H3 H4]|H3]; [left|right]|right]. exists (w++s); auto. intros. inversion H. subst r s1 s0. repeat rewrite app_length. apply le_trans with (length w+length m). apply plus_le_compat_l; auto. apply plus_le_compat_r; auto. intros t D. inversion D. contradict H6; auto. intros t D. inversion D. contradict H2; auto. destruct IHr1 as [[w H1 H2]|H1]; destruct IHr2 as [[s H3 H4]|H3]. left. destruct (le_lt_dec (length w) (length s)). exists w; auto. intros. inversion H; auto. apply le_trans with (length s); auto.\n  exists s; auto. intros. inversion H; auto. apply le_trans with (length w); auto. left; exists w; auto. intros. inversion H; auto. contradict H6; auto. left; exists s; auto. intros. inversion H; auto. contradict H6; auto. right. intros w D. inversion D; contradict H4; auto. left; exists nil; auto. Defined.\nDefinition Rlang': forall r, {l|forall w, Racc r w <-> In w l}+{forall n, exists w, n<=length w /\\ Racc r w}. induction r. left. exists nil. intros; split; intros; inversion H. left; exists ((c::nil)::nil). intros; split; intros. left. inversion H; auto. destruct H. subst w; auto. destruct H. destruct IHr1 as [[l1 H1]|H1]; destruct IHr2 as [[l2 H2]|H2]. left. exists (all_pair (app (A:=C)) l1 l2). intros; split; intros. inversion H. apply all_pair_spec1; auto. apply H1; auto. apply H2; auto. apply all_pair_spec2 in H. destruct H as [x [y [H3 [H4 H5]]]]. subst w. apply RAcons. apply H1; auto. apply H2; auto. destruct l1 as [|a l1]. left; exists nil. intros; split; intros; inversion H. apply H1 in H4. inversion H4. right. intros. destruct (H2 n) as [w [H3 H4]]. exists (a++w). split; auto. rewrite app_length. apply le_trans with (m:=length w); auto. apply RAcons; auto. apply H1; auto.\n  destruct l2 as [|a l2]. left. exists nil. intros; split; intros; inversion H. apply H2 in H6; inversion H6. right. intros. destruct (H1 n) as [w [H3 H4]]. exists (w++a). split. rewrite app_length. apply le_trans with (length w); auto. apply RAcons; auto. apply H2; auto. right. intros. destruct (H1 n) as [w1 [H3 H4]]. destruct (H2 n) as [w2 [H5 H6]]. exists (w1++w2). split. rewrite app_length. apply le_trans with (length w1); auto. auto. destruct IHr1 as [[l1 H1]|H1]; [destruct IHr2 as [[l2 H2]|H2]|]. left; exists (l1++l2). intros; split; intros. apply in_or_app. inversion H; [left; apply H1|right; apply H2]; auto. apply in_app_or in H. destruct H; [apply H1 in H|apply H2 in H]; auto. right. intros. destruct (H2 n) as [w [H3 H4]]. exists w; auto. right. intros. destruct (H1 n) as [w [H3 H4]]. exists w; auto.\n  destruct IHr as [[l H1]|H1]. destruct (maxf (length (A:=C)) l) as [[x H2 H3]|H2]. destruct x. left. exists (nil::nil). intros; split; intros. cut (w=nil). intros; subst w; auto. remember (Rstar r) as r1. revert Heqr1. induction H; intros; try discriminate Heqr1; auto. inversion Heqr1; subst r0. apply H1 in H. apply H3 in H. destruct l0. auto. inversion H. destruct H. subst w; auto. destruct H. right. intros. apply H1 in H2. clear -H2. induction n. exists (c::x). split; auto. destruct IHn as [w [H3 H4]]. exists ((c::x)++w). split; auto. simpl. apply le_n_S. rewrite app_length. apply le_trans with (length w); auto. subst l. left; exists (nil::nil). intros; split; intros. inversion H. left; auto. apply H1 in H2. inversion H2. destruct H. subst w; auto. destruct H. right. intros. destruct (H1 n) as [w [H3 H4]]. exists w; auto. Defined.\nDefinition Rlang: forall r, {l|forall w, Racc r w <-> In w l}+{forall l, exists w, Racc r w /\\ ~In w l}. intros. destruct (Rlang' r) as [[l H1]|H1]; [left|right]. exists l; auto. intros. destruct (maxf (length (A:=C)) l) as [[x H3 H4]|H3]. destruct (H1 (S (length x))) as [w [H5 H6]]. exists w. split; auto. intros D. apply H4 in D. contradict H5. apply le_not_lt; auto. subst l. destruct (H1 0) as [w [H3 H4]]. exists w. split; auto. Defined.\nDefinition Rlongest: forall r, {w| Racc r w & forall s, Racc r s -> length s <= length w}+{forall n, exists s, Racc r s /\\ n <= length s}+{forall w, ~Racc r w}. intros. destruct (Rlang' r) as [[l H1]|H1]. destruct (maxf (length (A:=C)) l) as [[w H2 H3]|H2]. left; left; exists w; auto. apply H1; auto. intros. apply H3. apply H1; auto. subst l. right. intros. intros D. apply H1 in D. destruct D. left; right. intros. destruct (H1 n) as [w [H2 H3]]. exists w; auto. Defined.\nDefinition sum_is_n: forall n, {pl|forall p, In p pl <-> fst p+snd p =n}. induction n. exists ((0,0)::nil). intros; split; intros. destruct H. subst p; auto. destruct H. destruct p. destruct n. destruct n0; auto. simpl in H. inversion H. simpl in H. inversion H. destruct IHn as [pl H]. exists ((0,S n)::map (fun p=>(S(fst p),snd p)) pl). intros. split; intros. destruct H0. subst p; auto. apply in_map_iff in H0. destruct H0 as [q [H1 H2]]. subst p. simpl. f_equal; apply H; auto. destruct p as [x y]. simpl in H0. destruct x. left; auto. right. inversion H0. apply in_map_iff. exists (x, y). split; simpl; auto. apply H. auto. Defined.\nDefinition Rlang_length: forall r n, {l|forall w, Racc r w/\\length w=n <-> In w l}. intros. revert r. apply (Fix lt_wf) with (P:=fun n=>forall r,{l|forall w, Racc r w/\\length w=n<->In w l}). clear n. intros n IH r. induction r. exists nil. intros; split; intros. destruct H; inversion H. inversion H. destruct (nat_eq_dec n 1). subst n. exists ((c::nil)::nil). intros; split; intros. destruct H. inversion H; auto. destruct H. subst w; auto. destruct H. exists nil. intros; split; intros. destruct H. contradict n0. inversion H. subst w n; auto. destruct H. destruct IHr1 as [l1 H1]. destruct IHr2 as [l2 H2]. remember (fun m=>match lt_dec m n with left _ H => match IH m H r1 with exist _ l _ => l end| right _ _ => l1 end) as f1. remember (fun m=>match lt_dec m n with left _ H => match IH m H r2 with exist _ l _ => l end| right _ _ => l2 end) as f2. destruct (sum_is_n n) as [sl H3].\n  exists (flat_map (fun p=>all_pair (app (A:=C)) (f1 (fst p)) (f2 (snd p))) sl). intros; split; intros. destruct H. inversion H. subst r s w. apply in_flat_map. exists (length l, length m). split. apply H3. subst n; rewrite app_length; auto. apply all_pair_spec1; simpl. subst f1. destruct (lt_dec (length l) n). destruct (IH (length l) l0 r1). apply i; auto. apply H1. split; auto. destruct m. subst n; rewrite app_nil_r; auto. contradict n0; subst n. rewrite app_length. simpl. rewrite <- plus_n_Sm. auto. subst f2. destruct (lt_dec (length m) n). destruct (IH (length m) l0 r2). apply i; auto. apply H2. split; auto. destruct l; subst n; auto. contradict n0. simpl; rewrite app_length; auto. apply in_flat_map in H. destruct H as [[x y] [H5 H4]]. apply H3 in H5. simpl in H5. subst n. apply all_pair_spec2 in H4. simpl in H4. destruct H4 as [s [t [H6 [H7 H8]]]]. subst w. subst f1. destruct (lt_dec x (x+y)). destruct (IH x l r1). apply i in H6. destruct H6. subst x.\n  subst f2. destruct (lt_dec y (length s+y)). destruct (IH y l0 r2). apply i0 in H7. destruct H7. subst y. split; auto. rewrite app_length; auto. apply H2 in H7. destruct H7. split; auto. rewrite app_length. rewrite <- H4. replace (length s) with 0; auto. destruct (length s); auto. contradict n. simpl. apply le_n_S. auto. assert (y=0). destruct y; auto. contradict n. rewrite <- plus_n_Sm; auto. subst y. apply H1 in H6. destruct H6. subst f2. destruct (lt_dec 0 (x+0)). destruct (IH 0 l r2). apply i in H7. destruct H7. destruct t. split; auto. rewrite app_nil_r. auto. inversion H5. apply H2 in H7. destruct H7. split; auto. rewrite app_length. rewrite H0. rewrite H5. replace x with 0; auto. destruct x; auto. contradict n0. simpl. apply le_n_S; auto. destruct IHr1 as [l1 H1]. destruct IHr2 as [l2 H2]. exists (l1++l2). intros; split; intros. destruct H. apply in_or_app. inversion H; [left; apply H1|right; apply H2]; auto. apply in_app_or in H. destruct H;[apply H1 in H|apply H2 in H]; destruct H; auto.\n  destruct n. exists (nil::nil). intros; split; intros. destruct H. destruct w; auto. inversion H0. destruct H. subst w; auto. destruct H. destruct IHr as [l1 H1]. destruct (sum_is_n (S n)) as [sl H2]. remember (fun m=>match lt_dec m (S n) with left _ H  => match IH m H r with exist _ l _ => l end | right _ _ => l1 end) as f1. remember (fun m=>match lt_dec m (S n) with |left _ H => match IH m H (Rstar r) with exist _ l _ => l end | right _ _ => nil end) as f2. exists (flat_map (fun p=> all_pair (app (A:=C)) (f1 (fst p)) (f2 (snd p))) sl). intros; split; intros. destruct H. destruct (Rstar_rev' H) as [w1 [w2 [H3 [H4 [H5 H6]]]]]; auto. destruct w. inversion H0. discriminate. subst w. apply in_flat_map. exists (length w1, length w2). split. apply H2. rewrite <- H0. rewrite app_length; auto.  simpl. apply all_pair_spec1; simpl. subst f1. destruct (lt_dec (length w1) (S n)). destruct (IH (length w1) l r). apply i; auto. apply H1. split; auto. destruct w2. rewrite <- H0. rewrite app_nil_r; auto. contradict n0. rewrite <- H0. rewrite app_length. simpl. rewrite <- plus_n_Sm. apply le_n_S; apply le_plus_l; auto.\n  subst f2. destruct (lt_dec (length w2) (S n)). destruct (IH (length w2) l (Rstar r)); auto. apply i; auto. contradict n0. rewrite <- H0. rewrite app_length. destruct w1. contradict H5; auto. simpl. apply le_n_S; apply le_plus_r. apply in_flat_map in H. destruct H as [[x y] [H3 H4]]. apply H2 in H3. simpl in H3. apply all_pair_spec2 in H4. destruct H4 as [w1 [w2 [H5 [H6 H7]]]]. subst w. subst f1. simpl in H5. destruct (lt_dec x (S n)). destruct (IH x l r). apply i in H5. destruct H5. subst f2. simpl in H6. destruct (lt_dec y (S n)). destruct (IH y l0 (Rstar r)). apply i0 in H6. destruct H6. split. auto. rewrite app_length. subst x y; auto. destruct H6. subst f2. simpl in H6. destruct (lt_dec y (S n)). destruct (IH y l). apply i in H6. destruct H6. apply H1 in H5. destruct H5. destruct y.  destruct w2. rewrite app_nil_r. auto. inversion H0. contradict n0. rewrite <- H3. rewrite <- plus_n_Sm. apply le_n_S; apply le_plus_l. destruct H6. Defined.\nDefinition Rlang_bound: forall r n, {l|forall w, Racc r w/\\length w <=n <-> In w l}. intros. induction n. destruct (Rlang_length r 0) as [l H]. exists l. intros; split; intros. apply H. destruct H0. split; auto. destruct (length w); auto. inversion H1. apply H in H0. destruct H0. split; auto. rewrite <- H1; auto. destruct IHn as [l H1]. destruct (Rlang_length r (S n)) as [m H2]. exists (m++l). intros; split; intros. destruct H. apply in_or_app. inversion H0; [left|right]. apply H2; auto. apply H1; auto. apply in_app_or in H. destruct H. apply H2 in H. destruct H; split; auto. rewrite H0; auto. apply H1 in H. destruct H. split; auto. Defined.\n\nTheorem Rstar_rev: forall r w, Racc (Rstar r) w -> {w1:list C & {w2|w=w1++w2 /\\ w1<>nil /\\ Racc r w1 /\\Racc (Rstar r) w2}}+{w=nil}. intros. destruct (list_eq_dec C_eq_dec w nil). right; auto. left. destruct (splits w) as [wl H1 _]. destruct (findP (fun p=>fst p<>nil/\\Racc r (fst p)/\\Racc (Rstar r) (snd p)) wl) as [[[w1 w2] H2]|H2]. intros p H0. destruct (list_eq_dec C_eq_dec (fst p) nil); [right|]. contradict e. destruct e; auto. destruct (Racc_dec r (fst p)); [|right]. destruct (Racc_dec (Rstar r) (snd p)); [left|right]; auto. contradict n1. destruct n1; destruct H3; auto. contradict n1. destruct n1; destruct H3; auto. destruct a. destruct H3. exists w1. exists w2. split; auto. apply H1 in H2. subst w; auto. exfalso. destruct (Rstar_rev' H) as [l [m [H3 [H4 [H5 H6]]]]]; auto. subst w. cut (In (l,m) wl). intros. apply H2 in H0. contradict H0. simpl; auto. apply H1. auto. Defined.\nTheorem Rstar_dual: forall r, Req (Rstar r) (Rstar (Rstar r)). Proof. intros. split; intros w H. auto. revert H. apply (Fix (well_founded_ltof (list C) (length (A:=C)))) with (P:=fun w=>Racc(Rstar(Rstar r)) w->Racc(Rstar r) w). clear w. intros w IH H. destruct (Rstar_rev H) as [[w1 [w2 [H1 [H2 [H3 H4]]]]]|H1]; auto. subst w. apply Rstar_app; auto. apply IH; auto. unfold ltof. destruct w1. contradict H3; auto. rewrite app_length. apply le_n_S; apply le_plus_r. subst w; auto. Qed.\nTheorem Rstar_dual2: forall r, Req (Rstar r) (Rcons (Rstar r) (Rstar r)). Proof. intros; split; intros w H. rewrite <- app_nil_r; auto. inversion H. apply Rstar_app; auto. Qed.\nTheorem Rstar_or: forall r s, Req (Rstar (Ror r s)) (Rstar (Rcons (Rstar r) (Rstar s))). Proof. intros. split; intros w H; revert H. apply (Fix (well_founded_ltof (list C) (length (A:=C)))) with (P:=fun w=>Racc (Rstar (Ror r s)) w -> Racc (Rstar (Rcons (Rstar r) (Rstar s))) w). clear w. intros w IH H. destruct (Rstar_rev H) as [[w1 [w2 [H1 [H2 [H3 H4]]]]]|H1]. subst w. apply RAstar2; auto. inversion H3. rewrite <- app_nil_r; auto. rewrite <- app_nil_l; auto. apply IH; auto. unfold ltof. rewrite app_length. destruct w1. contradict H2; auto. simpl; auto. subst w; auto.\n  apply (Fix (well_founded_ltof (list C) (length (A:=C)))) with (P:=fun w=>Racc (Rstar (Rcons (Rstar r) (Rstar s))) w->Racc (Rstar (Ror r s)) w). clear w. intros w IH H. destruct (Rstar_rev H) as [[w1 [w2 [H1 [H2 [H3 H4]]]]]|H1]; subst w; auto. inversion H3; auto. subst w1 r0 s0. apply Rstar_app. apply Rstar_app. revert H5. apply Rstar_incl. intros w Hw. auto. revert H7. apply Rstar_incl. intros w Hw. auto. apply IH; auto. unfold ltof. remember (l++m) as w1. destruct w1. contradict H2; auto. rewrite app_length. simpl. auto. Qed.\n\n\nDefinition Rnil_DFA: {d|forall w, Racc Rnil w <-> DFAacc d w}. assert (Ha:forall (c:C) s, In s (0::nil) -> In 0 (0::nil)). intros. left; auto. assert (Hb:In 0 (0::nil)). left; auto. assert (Hc: incl nil (0::nil)). intros x Hx; inversion Hx. exists (mkDFA (fun _ _=>0) 0 Ha Hb Hc). intros; split; intros. inversion H. inversion H. Defined.\nDefinition Rnil_EFA: {e|forall w, Racc Rnil w <-> EFAacc e w}. refine (exist _ (mkEFA (EFAstates:=nil) (fun _ _=>nil) (fun _=>nil) (fun _ _ _=>incl_refl nil) (fun _ _=>incl_refl nil) (incl_refl nil) (incl_refl nil)) _). intros; split; intros. inversion H. inversion H. simpl in H0. inversion H0. Defined.\nDefinition Rchar_DFA: forall c, {d|forall w, Racc (Rchar c) w <-> DFAacc d w}. intros. remember (fun s c'=>if C_eq_dec c' c then if nat_eq_dec s 0 then 1 else 2 else 2) as tr. assert (Ha:forall c s, In s (0::1::2::nil) -> In (tr s c) (0::1::2::nil)). intros c' s H. subst tr. destruct (C_eq_dec c' c). destruct (nat_eq_dec s 0); auto. auto. assert (Hb:In 0 (0::1::2::nil)); auto. assert (Hc:incl (1::nil) (0::1::2::nil)). intros x Hx. destruct Hx. subst x; auto. destruct H. exists (mkDFA tr 0 Ha Hb Hc). intros; split; intros. inversion H. subst c0 w. unfold DFAacc. simpl. left. subst tr. destruct (C_eq_dec c c). destruct (nat_eq_dec 0 0); auto. contradict n; auto. contradict n; auto. unfold DFAacc in H. simpl in H. destruct H; [|destruct H]. destruct w as [|c' w]; simpl in H. inversion H. subst tr. destruct (C_eq_dec c' c). subst c'. destruct (nat_eq_dec 0 0). destruct w; auto. simpl in H. absurd (1=2); auto. rewrite H at 1. clear -w. destruct (C_eq_dec c0 c). induction w; simpl; auto. destruct (C_eq_dec a c); auto. induction w; simpl; auto. destruct (C_eq_dec a c); auto. contradict n; auto. absurd (1=2); auto. rewrite H at 1. clear -n. induction w; simpl; auto. destruct (C_eq_dec a c); auto. Defined.\nDefinition Rchar_EFA: forall c, {e|forall w, Racc (Rchar c) w <-> EFAacc e w}. intros. remember (fun s c'=>if nat_eq_dec s 0 then if C_eq_dec c' c then 1::nil else nil else nil) as tr. remember (fun _:nat=>(nil (A:=nat))) as emp. assert (Htr: forall c s, In s (0::1::nil) -> incl (tr s c) (0::1::nil)). intros d s H x Hx. subst tr. destruct (nat_eq_dec s 0). destruct (C_eq_dec d c). destruct Hx; [subst x|]; auto. destruct Hx. destruct Hx. assert (Hemp: forall s, In s (0::1::nil) -> incl (emp s) (0::1::nil)). intros s H x Hx. subst emp. destruct Hx. assert (Hi: incl (0::nil) (0::1::nil)). intros x Hx. destruct Hx; [subst x|]; auto. assert (He:incl (1::nil) (0::1::nil)). intros x Hx. destruct Hx; [subst x|]; auto. exists (mkEFA tr emp Htr Hemp Hi He). intros w; split; intros. apply Rchar_spec in H. subst w. apply EFAacc_intro with 0 1 (0::1::nil); simpl; auto. apply EFAsteps_cons; auto. subst tr. destruct (nat_eq_dec 0 0). destruct (C_eq_dec c c); auto. contradict n; auto. contradict n; auto. apply Rchar_spec. inversion H; simpl in H0; simpl in H1; simpl in H2. clear H. destruct H0; [subst es|destruct H]. destruct H1; [subst is|destruct H]. inversion H3. subst a l. inversion H4. subst a b l0. destruct l. inversion H1. inversion H1. subst a n l. inversion H2. subst emp. inversion H8. inversion H6. f_equal. subst tr. clear -H8. destruct (nat_eq_dec 0 0). destruct (C_eq_dec c0 c); auto. destruct H8. destruct l. inversion H5. subst a n l0. clear H1 H3 H4 Hi He H5. inversion H2. subst emp; inversion H5. cut (b=1); intros. subst b t. inversion H3. subst emp; inversion H10. subst tr. destruct (nat_eq_dec 1 0). inversion e. inversion H10. subst tr; clear -H5. destruct (nat_eq_dec 0 0). destruct (C_eq_dec c0 c). apply In_one in H5; auto. destruct H5. destruct H5. Defined.\nDefinition EFA_or: forall e1 e2:EFA C, {eo|forall w, EFAacc eo w <-> EFAacc e1 w \\/ EFAacc e2 w}. intros. destruct e1 as [st1 tr1 emp1 ini1 acc1 Htr1 Hemp1 Hini1 Hacc1]. destruct (EFA_map e2 (plus (ubound st1))) as [e3 H0 H1]. intros. apply plus_reg_l with (ubound st1); auto. destruct e3 as [st3 tr3 emp3 ini3 acc3 Htr3 Hemp3 Hini3 Hacc3]. simpl in H0. assert (H2: Disjoint st1 st3). subst st3; auto. remember (fun s c=>if in_dec nat_eq_dec s st1 then tr1 s c else tr3 s c) as tr. assert (Htr: forall c s, In s (st1++st3) -> incl (tr s c) (st1++st3)). subst tr. intros s c H x Hx. apply in_app_or in H. apply in_or_app. destruct (in_dec nat_eq_dec c st1). left. apply Htr1 in Hx; auto. apply Htr3 in Hx; auto. destruct H; auto; contradiction. remember (fun s=>if in_dec nat_eq_dec s st1 then emp1 s else emp3 s) as emp. assert (Hemp: forall s, In s (st1++st3) -> incl (emp s) (st1++st3)). intros s H x Hx. subst emp. apply in_app_or in H. apply in_or_app. destruct (in_dec nat_eq_dec s st1). apply Hemp1 in Hx; auto. apply Hemp3 in Hx; auto. destruct H; auto; contradiction. assert (Hini: incl (ini1++ini3) (st1++st3)). intros x Hx. apply in_or_app. apply in_app_or in Hx. destruct Hx; auto.  assert (Hacc: incl (acc1++acc3) (st1++st3)). intros x Hx. apply in_or_app. apply in_app_or in Hx. destruct Hx; auto. exists (mkEFA tr emp Htr Hemp Hini Hacc). intros; split; intros.\n  inversion H. simpl in H3. simpl in H4. clear H. apply in_app_or in H4. destruct H4; [left|right]. assert (incl l st1). subst tr emp. apply Hini1 in H. inversion H6. subst a l. clear -H5 H Hemp1 Htr1. revert H5 H. revert w is. induction l0; intros. inversion H5. intros x Hx. destruct Hx. subst x s; auto. destruct H1. intros x Hx. destruct Hx. subst x; auto. inversion H5. subst w0 s t l0. simpl in H7. destruct (in_dec nat_eq_dec is st1); [|contradiction]. apply Hemp1 in H7; auto. destruct H0. subst x; auto. apply IHl0 in H4; auto. subst w s t l0. simpl in H7. destruct (in_dec nat_eq_dec is st1); [|contradiction]. apply Htr1 in H7. destruct H0. subst x; auto. apply IHl0 in H4; auto. auto. apply EFAacc_intro with is es l; simpl; intros; auto. apply in_app_or in H3. destruct H3; auto. apply Hacc3 in H3. contradict H3. apply Disjoint_In1 with st1; auto. simpl in H5. apply EFAsteps_incl with (st:=st1) (tr1:=tr) (emp1:=emp); simpl; intros; auto. subst emp. destruct (in_dec nat_eq_dec s st1); auto; contradiction. subst tr. destruct (in_dec nat_eq_dec s st1); auto; contradiction. apply H1. assert (incl l st3). apply Hini3 in H. inversion H6. subst a l emp tr. clear -H H5 Hemp3 Htr3 H2. revert H5 H. revert w is. induction l0; intros. intros x Hx. destruct Hx. subst x; auto. destruct H0. inversion H5. simpl in H7. subst w0 s t l0. destruct (in_dec nat_eq_dec is st1). contradict H. apply Disjoint_In1 with st1; auto. apply Hemp3 in H7. intros x Hx. destruct Hx. subst x; auto. destruct H0. subst x; auto. apply IHl0 in H4; auto. auto. \n  subst w s t l0. simpl in H7. destruct (in_dec nat_eq_dec is st1). contradict H. apply Disjoint_In1 with st1; auto. apply Htr3 in H7. intros x Hx. destruct Hx. subst x; auto. destruct H0. subst x; auto. apply IHl0 in H4; auto. auto. apply EFAacc_intro with is es l; simpl; intros; auto. apply in_app_or in H3. destruct H3; auto. apply Hacc1 in H3. contradict H3. apply Disjoint_In1 with st3; auto. apply EFAsteps_incl with (st:=st3) (tr1:=tr) (emp1:=emp); simpl; intros; auto. subst emp. destruct (in_dec nat_eq_dec s st1); auto. contradict H8; apply Disjoint_In1 with st1; auto. subst tr. destruct (in_dec nat_eq_dec s st1); auto. contradict H8; apply Disjoint_In1 with st1; auto.\n  destruct H. inversion H. apply EFAacc_intro with is es l; simpl; auto. apply in_or_app; auto. apply in_or_app; auto. apply EFAsteps_incl with (tr1:=tr1) (emp1:=emp1) (st:=st1); simpl; intros; auto. apply EFAsteps_const with (s:=is) (st:=st1) in H5; auto. simpl in H3. simpl in H4. simpl in H5. subst emp. destruct (in_dec nat_eq_dec s st1); auto; contradiction. subst tr. destruct (in_dec nat_eq_dec s st1); auto; contradiction. apply H1 in H. inversion H. apply EFAacc_intro with is es l; simpl; auto. apply in_or_app; auto. apply in_or_app; auto. apply EFAsteps_incl with (st:=st3) (tr1:=tr3) (emp1:=emp3); simpl; intros; auto. apply EFAsteps_const with (s:=is) (st:=st3) in H5; auto. subst emp. destruct (in_dec nat_eq_dec s st1); auto. contradict H8. eapply Disjoint_In1; eauto. subst tr. destruct (in_dec nat_eq_dec s st1); auto. contradict H8. eapply Disjoint_In1; eauto. Defined.\nDefinition EFA_cons: forall e1 e2: EFA C, {eo|forall w, EFAacc eo w <-> exists w1 w2, w=w1++w2 /\\ EFAacc e1 w1 /\\ EFAacc e2 w2}. intros. destruct e1 as [st1 tr1 emp1 ini1 acc1 Htr1 Hemp1 Hini1 Hacc1]. destruct (EFA_map e2 (plus (ubound st1))) as [e3 H H0]. intros. eapply plus_reg_l; eauto. destruct e3 as [st3 tr3 emp3 ini3 acc3 Htr3 Hemp3 Hini3 Hacc3]. simpl in H. assert (Disjoint st1 st3). subst st3; auto. remember (fun s c=>if in_dec nat_eq_dec s st1 then tr1 s c else tr3 s c) as tr. remember (fun s=>if in_dec nat_eq_dec s st3 then emp3 s else if in_dec nat_eq_dec s acc1 then emp1 s++ini3 else emp1 s) as emp. assert (Htr: forall c s, In s (st1++st3) -> incl (tr s c) (st1++st3)). intros. intros x Hx. apply in_app_or in H2. subst tr. apply in_or_app. destruct (in_dec nat_eq_dec s st1). apply Htr1 in Hx; auto. apply Htr3 in Hx; auto. destruct H2; auto; contradiction. assert (Hemp: forall s, In s (st1++st3) -> incl (emp s) (st1++st3)). intros. intros x Hx. apply in_or_app. apply in_app_or in H2. subst emp. destruct (in_dec nat_eq_dec s st3). apply Hemp3 in Hx; auto. destruct H2; [|contradiction]. destruct (in_dec nat_eq_dec s acc1). apply in_app_or in Hx. destruct Hx. apply Hemp1 in H3; auto. apply Hini3 in H3; auto. apply Hemp1 in Hx; auto. assert (Hini: incl ini1 (st1++st3)). intros x Hx. apply in_or_app. apply Hini1 in Hx; auto. assert (Hacc: incl acc3 (st1++st3)). intros x Hx. apply in_or_app. apply Hacc3 in Hx; auto. clear H. exists (mkEFA tr emp Htr Hemp Hini Hacc). intros; split; intros.\n  inversion H. simpl in H2. simpl in H3. clear H. assert (incl l (st1++st3)). apply EFAsteps_const with (s:=is) (st:=st1++st3) in H4; auto. destruct (split_until (fun s=>In s st3) l) as [[l1 [is3 [l3 [H7 H8] H9]]]|H7]. intros. apply in_dec. apply nat_eq_dec. subst l. destruct (Tail_dec' l1) as [[es1 H8 _]|H8]. apply EFAsteps_app_s_rev with (s:=es1) in H4; auto. destruct H4 as [w1 [w2 [Ha [Hb Hc]]]]. subst w. exists w1. exists w2. split; auto. inversion Hc. subst w s t l. simpl in H14. clear Hc. assert (In es1 acc1 /\\ In is3 ini3). subst emp. destruct (in_dec nat_eq_dec es1 st3). contradict i. apply Forall_forall with (x:=es1) in H9; auto. destruct (in_dec nat_eq_dec es1 acc1) as [Hi|Hi]. split; auto. apply in_app_or in H14. destruct H14; auto. contradict H7. apply Disjoint_In1 with st1; auto. apply Hemp1 in H4; auto. apply Hemp1 in H14. contradict H7. apply Disjoint_In1 with st1; auto. assert (In es1 (st1++st3)). apply H. apply in_or_app; auto. apply in_app_or in H4. destruct H4; auto; contradiction. destruct H4. clear H14. split; [|apply H0]; clear H0. apply EFAacc_intro with is es1 l1; simpl; auto. apply EFAsteps_incl with (st:=st1) (tr1:=tr) (emp1:=emp); simpl; intros; auto. intros x Hx. assert (In x (st1++st3)). apply H. apply in_or_app; auto. apply in_app_or in H0. destruct H0; auto. contradict H0. apply Forall_forall with (x:=x) in H9; auto. subst emp. destruct (in_dec nat_eq_dec s st3). contradict i. apply Disjoint_In1 with st1; auto. destruct (in_dec nat_eq_dec s acc1); auto. apply in_app_or in H11. destruct H11; auto. apply Hini3 in H11. contradict H11. apply Disjoint_In1 with st1; auto. subst tr. destruct (in_dec nat_eq_dec s st1); auto; contradiction.\n  destruct l1. inversion H5. subst is3. contradict H7. apply Disjoint_In1 with st1; auto. inversion H5; auto. apply EFAacc_intro with is3 es (is3::l3); auto. apply EFAsteps_incl with (st:=st3) (tr1:=tr) (emp1:=emp); simpl; intros; auto. intros x Hx. destruct Hx. subst x; auto. apply Hini3 in H10. subst tr emp. clear -H0 H10 H12 H1 Hemp3 Htr3. revert H12 H10 H0. revert w2 is3 x. induction l3; intros. destruct H0. inversion H12. simpl in H6. subst w2 s t l. destruct (in_dec nat_eq_dec is3 st3); [|contradiction]. apply Hemp3 in H6; auto. destruct H0. subst x; auto. apply IHl3 with (x:=x) in H4; auto. subst w2 s t l. simpl in H6. destruct (in_dec nat_eq_dec is3 st1). contradict H10; apply Disjoint_In1 with st1; auto. apply Htr3 in H6; auto. destruct H0. subst x; auto. apply IHl3 with (x:=x) in H4; auto. subst emp. destruct (in_dec nat_eq_dec s st3); auto; contradiction. subst tr. destruct (in_dec nat_eq_dec s st1); auto. contradict H0. apply Disjoint_In1 with st1; auto. clear -H6. induction l1. auto. apply IHl1. inversion H6. destruct l1; inversion H2. auto. subst w2 s t l. simpl in H14. contradict H7. apply Disjoint_In1 with st1; auto. subst tr. destruct (in_dec nat_eq_dec es1 st1). apply Htr1 in H14; auto. assert (In es1 (st1++st3)). apply H. apply in_or_app; auto. apply in_app_or in H4. destruct H4. contradiction. contradict H4. apply Forall_forall with (x:=es1) in H9; auto. subst l1. inversion H5. subst a is3. contradict H7. apply Disjoint_In1 with st1; auto. apply Hacc3 in H2. contradict H2. apply Forall_forall with (x:=es) in H7; auto.\n  destruct H as [w1 [w2 [Hw [H2 H3]]]]. subst w. apply H0 in H3. clear H0. inversion H2. clear H2. simpl in H0. simpl in H. inversion H3. clear H3. simpl in H2. simpl in H7. apply EFAacc_intro with is es0 (l++l0); simpl; auto. apply EFAsteps_app with es; auto. apply EFAsteps_incl with (st:=st1) (tr1:=tr1) (emp1:=emp1); simpl; intros; auto. apply EFAsteps_const with (s:=is) (st:=st1) in H4; auto. subst emp. destruct (in_dec nat_eq_dec s st3). contradict i. apply Disjoint_In1 with st1; auto. destruct (in_dec nat_eq_dec s acc1). apply in_or_app; auto. auto. subst tr. destruct (in_dec nat_eq_dec s st1); auto; contradiction. inversion H9. subst a l0. apply EFAsteps_empty; simpl; auto. apply EFAsteps_incl with (st:=st3) (tr1:= tr3) (emp1:= emp3); simpl; intros; auto. apply EFAsteps_const with (s:=is0) (st:=st3) in H8; auto. subst emp. destruct (in_dec nat_eq_dec s st3); auto; contradiction. subst tr. destruct (in_dec nat_eq_dec s st1); auto. contradict H3. apply Disjoint_In1 with st1; auto. subst emp. destruct (in_dec nat_eq_dec es st3). contradict i; apply Disjoint_In1 with st1; auto. destruct (in_dec nat_eq_dec es acc1); [|contradiction]. apply in_or_app; auto. inversion H5; simpl; auto. Defined.\nDefinition EFA_Rstar: forall r e, (forall w, Racc r w<-> EFAacc e w) -> {eo| forall w, Racc (Rstar r) w <-> EFAacc eo w}. intros. destruct e as [st tr emp ini acc Htr Hemp Hini Hacc]. remember (ubound st) as n. assert (~In n st). subst n. unfold ubound. destruct (ubound_sig st). intros D. apply l in D. contradict D. apply le_not_lt; auto. clear Heqn. remember (fun s c=>if nat_eq_dec s n then nil else tr s c) as tr'. remember (fun s=> if nat_eq_dec s n then ini else if in_dec nat_eq_dec s acc then n::emp s else emp s) as emp'. assert (Hini': incl (n::nil) (n::st)). intros x Hx. destruct Hx. subst x; auto. destruct H1. assert (Htr': forall c s, In s (n::st) -> incl (tr' s c) (n::st)). intros. intros x Hx. subst tr'. destruct (nat_eq_dec s n). subst s. destruct Hx. right. apply Htr in Hx; auto. destruct H1; auto. contradict n0; auto. assert (Hemp': forall s, In s (n::st) -> incl (emp' s) (n::st)). intros. intros x Hx. subst emp'. destruct (nat_eq_dec s n). subst n. right. apply Hini in Hx; auto. destruct (in_dec nat_eq_dec s acc). destruct Hx. subst x; auto. apply Hemp in H2; auto. apply Hemp in Hx; auto. destruct H1; auto. contradict n0; auto. exists (mkEFA tr' emp' Htr' Hemp' Hini' Hini'). intros; split; intros. revert H1. apply (Fix (well_founded_ltof (list C) (length (A:=C)))) with (P:=fun w=>Racc (Rstar r) w->EFAacc (mkEFA tr' emp' Htr' Hemp' Hini' Hini') w). clear w. intros w IH H1. apply Rstar_rev in H1. destruct H1 as [[w1 [w2 [H3 [H4 [H5 H6]]]]]|H3]. subst w. apply H in H5. clear H. apply IH in H6. clear IH. inversion H5. inversion H6. simpl in H1. simpl in H2. simpl in H. simpl in H8. simpl in H9. clear H5 H6. destruct H8; [|destruct H5]. destruct H9; [|destruct H6]. subst es0 is0. apply EFAacc_intro with n n ((n::l)++l0). simpl; auto. simpl; auto. apply EFAsteps_app with es; auto. inversion H3. subst a l. apply EFAsteps_empty; auto.\n  apply EFAsteps_incl with (st:=st) (tr1:=tr) (emp1:=emp); simpl; intros; auto. apply EFAsteps_const with (s:=is) (st:=st) in H2; auto. subst emp'. destruct (nat_eq_dec s n). subst s. contradiction. destruct (in_dec nat_eq_dec s acc); auto. subst tr'. destruct (nat_eq_dec s n); auto. subst s; contradiction. simpl. subst emp'. destruct (nat_eq_dec n n); auto. contradict n0; auto. inversion H11. subst a l0. apply EFAsteps_empty; auto. simpl. subst emp'. destruct (nat_eq_dec es n). subst es. apply Hacc in H. contradiction. destruct (in_dec nat_eq_dec es acc); auto. contradiction. simpl; auto. clear -H12. simpl. apply Tail_cons. induction l; simpl; auto. unfold ltof. rewrite app_length. destruct w1. contradict H4; auto. simpl. apply le_n_S. apply le_plus_r. subst w. apply EFAacc_intro with n n (n::nil); simpl; auto.\n  inversion H1. simpl in H3. simpl in H2. clear H1. destruct H2; [|contradict H1]. destruct H3; [|contradict H2]. subst es is. revert H4 H5 H6. revert w. apply (Fix (well_founded_ltof (list nat) (length (A:=nat)))) with (P:=fun l=> forall w, EFAsteps tr' emp' w l->Head n l -> Tail n l->Racc (Rstar r) w). clear l. intros l IH w. intros. inversion H2. subst a l. clear H2. inversion H1. subst w s l0. auto. simpl in H7. subst w0 s l0. assert (In t ini). subst emp'. destruct (nat_eq_dec n n); auto. contradict n0; auto. clear H7. destruct (split_until (eq n) (t::l)). intros. apply nat_eq_dec. destruct s as [m1 [x [m2 [Ha Hb] Hc]]]. subst x. clear H1. destruct m1. inversion Hb. subst t. apply Hini in H2; contradiction. inversion Hb. subst n0 l. clear Hb. assert (Ht:incl (t::m1) st). intros x Hx. assert (In x (n::st)). apply EFAsteps_const with (s:=t) (st:=n::st) in H6; simpl; auto. simpl in H6. apply H6.  replace (t::m1++n::m2) with ((t::m1)++n::m2); auto. apply in_or_app; auto. destruct H1; auto. subst x. absurd (n=n); auto. apply Forall_forall with (x:=n) in Hc; auto. replace (t::m1++n::m2) with ((t::m1)++n::m2) in H6; auto. destruct (Tail_dec' (t::m1)) as [[es H4 _]|H4]. apply EFAsteps_app_s_rev with (s:=es) in H6; auto. destruct H6 as [w1 [w2 [Ha [Hb Hd]]]]. subst w. inversion Hd. subst w s t0 l. simpl in H9. clear Hd. assert (In es acc). subst emp'. destruct (nat_eq_dec es n). subst es. apply Hini in H9. contradiction. destruct (in_dec nat_eq_dec es acc); auto. apply Hemp in H9.  contradiction. apply Ht. auto.\n  apply RAstar2; auto. apply H. apply EFAacc_intro with t es (t::m1); auto. apply EFAsteps_incl with (st:=st) (tr1:=tr') (emp1:=emp'); simpl; intros; auto. subst emp'. destruct (nat_eq_dec s n). subst s; contradiction. destruct (nat_eq_dec es n). subst es. contradict H0. apply Ht; auto. destruct (in_dec nat_eq_dec s acc); auto. destruct H6; auto. subst t0; contradiction. subst tr'. destruct (nat_eq_dec s n); auto. destruct H6. apply IH with (n::m2); auto. unfold ltof. simpl. repeat apply le_n_S. rewrite app_length. simpl. rewrite <- plus_n_Sm. auto. clear -H3. inversion H3. subst a b l. inversion H1. destruct m1; inversion H4. subst a b l. clear -H2. induction m1; auto. apply IHm1. inversion H2; auto. destruct m1; inversion H3. simpl in H9. subst tr'. destruct (nat_eq_dec es n). destruct H9. apply Htr in H9. contradiction. apply Ht. auto. inversion H4. clear -H3 f. absurd (n=n); auto. inversion H3. apply Forall_forall with (x:=n) in f; auto. simpl in H7. subst w s l0. subst tr'. clear -H7. destruct (nat_eq_dec n n). destruct H7. contradict n0; auto. Defined.\n\nDefinition RegExp2EFA: forall r, {e|forall w, Racc r w <-> EFAacc e w}. induction r. apply Rnil_EFA. apply (Rchar_EFA c). destruct IHr1 as [e1 H1]. destruct IHr2 as [e2 H2]. destruct (EFA_cons e1 e2) as [e H]. exists e. intros; split; intros. inversion H0. subst w r s. apply H. exists l. exists m. split; auto. split. apply H1; auto. apply H2; auto. apply H in H0. destruct H0 as [w1 [w2 [Ha [Hb Hc]]]]. subst w. apply H1 in Hb. apply H2 in Hc. auto.\n  destruct IHr1 as [e1 H1]. destruct IHr2 as [e2 H2]. destruct (EFA_or e1 e2) as [e H]. exists e. intros; split; intros. apply H. inversion H0; [left; apply H1|right; apply H2]; auto. apply H in H0. destruct H0; [apply H1 in H0|apply H2 in H0]; auto. destruct IHr as [e H]. destruct (EFA_Rstar H) as [eo H0]. exists eo; auto. Defined.\n\n(* RegExp Finite Automaton *)\nRecord RFA: Set:= mkRFA {\n  RFAstates: list nat;\n  RFAtrans: nat -> nat -> RegExp;\n  RFAinit: list nat;\n  RFAaccept: list nat;\n  RFAtrans_const: forall s t w, Racc (RFAtrans s t) w -> In s RFAstates /\\ In t RFAstates;\n  RFAinit_const: incl RFAinit RFAstates;\n  RFAacc_const: incl RFAaccept RFAstates;\n}.\n\nInductive RFAsteps (tr:nat->nat->RegExp): list C -> list nat -> Prop:=\n| RFAsteps_nil: forall s, RFAsteps tr nil (s::nil)\n| RFAsteps_cons: forall s t l w1 w2, RFAsteps tr w2 (t::l) -> Racc (tr s t) w1 -> RFAsteps tr (w1++w2) (s::t::l)\n.\nInductive RFAacc (e:RFA) (w:list C): Prop:= RFAacc_intro: forall l is es, RFAsteps (RFAtrans e) w l -> Head is l -> Tail es l -> In is (RFAinit e) -> In es (RFAaccept e) -> RFAacc e w.\nHint Constructors RFAsteps RFAacc.\n\nTheorem RFAsteps_const: forall tr l w is st, (forall s t w, Racc (tr s t) w -> In s st /\\ In t st) -> RFAsteps tr w l -> Head is l -> In is st -> incl l st. Proof. intros tr l w is st H H0. revert H is. induction H0; intros; intros x Hx. destruct Hx. subst x. inversion H0; subst a s; auto. destruct H2. inversion H2. subst a s l0. destruct Hx. subst x; auto. apply IHRFAsteps with (is:=t) in H4; auto. apply H1 in H. destruct H; auto. Qed.\nTheorem RFAsteps_app: forall tr w1 l1 s w2 l2, RFAsteps tr w1 l1 -> Tail s l1 -> RFAsteps tr w2 (s::l2) -> RFAsteps tr (w1++w2) (l1++l2). Proof. intros tr w1 l1 s w2 l2 H. revert w2 l2 s. induction H; intros. inversion H; simpl. subst a s0; auto. inversion H3. inversion H1. subst a b l0. apply IHRFAsteps in H2; auto. rewrite <- app_assoc. simpl. auto. Qed.\nTheorem RFAsteps_app_s_rev: forall tr w l1 s l2, RFAsteps tr w (l1++l2) -> Tail s l1 -> exists w1 w2, w=w1++w2 /\\ RFAsteps tr w1 l1 /\\ RFAsteps tr w2 (s::l2). Proof. intros tr w l1. revert w. induction l1; intros. inversion H0. inversion H0. subst a a0 l1. exists nil. exists w. simpl in H; auto. subst a0 b l1. clear H0. inversion H. destruct l. inversion H3. inversion H4. subst w s0. destruct l. inversion H3. inversion H1. subst n l0. clear H1. apply IHl1 with (s:=s) in H4; auto. destruct H4 as [wa [wb [Ha [Hb Hc]]]]. subst w2. exists (w1++wa). exists wb. split. rewrite app_assoc; auto. split; auto. Qed.\n\nDefinition EFA2RFA: forall e cset, (forall s c, In s (EFAstates e) -> EFAtrans e s c <> nil -> In c cset) -> {r| forall w, EFAacc e w <-> RFAacc r w}. intros. destruct e as [st tr emp ini acc Htr Hemp Hini Hacc]. simpl in H. assert (tr_chars: forall s t, In s st->In t st->{cs|forall c, In c cs <-> In t (tr s c)}). intros.  exists (filter (dec2b (fun x=>in_dec nat_eq_dec t (tr s x))) cset). intros; split; intros. apply filter_In in H2. destruct H2. apply dec2b_true in H3; auto. apply filter_In. split. apply H with s; auto. contradict H2. rewrite H2. auto. apply dec2b_true; auto.\n  remember (fun s t=>match in_dec nat_eq_dec s st with left _ Hs => match in_dec nat_eq_dec t st with left _ Ht => let (cs,_):=tr_chars s t Hs Ht in let r:=fold_right (fun c r=>Ror (Rchar c) r) Rnil cs in if in_dec nat_eq_dec t (emp s) then Ror Remp r else r  |right _ _ => Rnil end |right _ _ => Rnil end) as tr'. assert (Htr': forall s t w, Racc (tr' s t) w->In s st/\\In t st). intros. subst tr'. destruct (in_dec nat_eq_dec s st). destruct (in_dec nat_eq_dec t st); auto. inversion H0. inversion H0. exists (mkRFA tr' Htr' Hini Hacc). intros; split; intros. inversion H0. simpl in H1. simpl in H2. apply RFAacc_intro with l is es; auto. assert (incl l st). apply EFAsteps_const with (s:=is) (st:=st) in H3; auto. clear H0 H1 H2 H4 H5. subst tr'. induction H3; auto. replace w with (nil++w); auto. apply RFAsteps_cons. apply IHEFAsteps. intros x Hx. apply H6. right; auto. simpl. clear H3 IHEFAsteps Htr'. simpl in H0. destruct (in_dec nat_eq_dec s st). destruct (in_dec nat_eq_dec t st). destruct (tr_chars s t i i0) as [cs H7]. destruct (in_dec nat_eq_dec t (emp s)). apply RAor1. apply Remp_spec; auto. contradiction. contradict n. apply H6; auto. contradict n; auto. replace (c::w) with ((c::nil)++w); auto. apply RFAsteps_cons; auto. apply IHEFAsteps; auto. intros x Hx; apply H6; auto. simpl in H0. simpl. clear H3 IHEFAsteps Htr'. destruct (in_dec nat_eq_dec s st). destruct (in_dec nat_eq_dec t st). destruct (tr_chars s t i i0) as [cs H7]. destruct (in_dec nat_eq_dec t (emp s)). apply RAor2. apply H7 in H0. clear -H0. induction cs. destruct H0. inversion H0. subst a. simpl. apply RAor1. auto. simpl.  apply RAor2. apply IHcs. auto. apply H7 in H0.  clear -H0. induction cs. destruct H0. inversion H0. subst a. simpl. auto. simpl; auto. contradict n; apply H6; auto. contradict n; apply H6; auto.\n  inversion H0. apply EFAacc_intro with is es l; auto. assert (incl l st). apply RFAsteps_const with (is:=is) (st:=st) in H1; auto. clear H0 H2 H3 H4 H5. induction H1; auto. simpl in H0. subst tr'. destruct (in_dec nat_eq_dec s st). destruct (in_dec nat_eq_dec t st). destruct (tr_chars s t i i0) as [cs H2]. simpl in H0. destruct (in_dec nat_eq_dec t (emp s)). inversion H0. apply Remp_spec in H7. subst w1. simpl. apply EFAsteps_empty; simpl; auto. apply IHRFAsteps; auto. intros x Hx. apply H6; auto. subst r s0 l0. cut (exists c, In c cs/\\w1=c::nil). intros. destruct H3 as [c [H3 H4]]. subst w1. simpl. apply EFAsteps_cons; auto. apply IHRFAsteps. intros x Hx. apply H6; auto. simpl. apply H2; auto. clear -H7. induction cs; simpl in H7. inversion H7. inversion H7. inversion H2. exists a; auto. apply IHcs in H2. destruct H2 as [c [H3 H4]]. exists c; auto. clear H1 Htr'. cut (exists c, In c cs /\\ w1=c::nil); intros. destruct H1 as [c [H4 H3]]. subst w1. apply EFAsteps_cons; auto. apply IHRFAsteps. intros x Hx; apply H6; auto. simpl. apply H2; auto. clear -H0. induction cs; simpl in H0. inversion H0. inversion H0. exists a; auto. inversion H3; auto. apply IHcs in H3. destruct H3 as [c [H3 H4]]. exists c; auto. contradict n. apply H6; auto. contradict n. apply H6; auto. Defined.\n\nDefinition RFA2single_edge: forall r, {i:nat &{e:nat &{st:list nat &{r'|forall w, RFAacc r w<-> RFAacc r' w & RFAstates r' = i::e::st /\\ RFAinit r' = i::nil /\\ RFAaccept r' = e::nil/\\ NoDup (i::e::st)/\\ (forall w s,~Racc (RFAtrans r' s i) w) /\\ (forall w t,~Racc (RFAtrans r' e t) w)}}}}. intros. destruct r as [st tr ini acc Htr Hini Hacc]. remember (nodup nat_eq_dec st) as st'. assert (NoDup st'). subst st'. apply NoDup_nodup. assert (forall s, In s st' <-> In s st). intros. subst st'. apply nodup_In. clear Heqst'. remember (ubound st') as e. assert (~In e st'). subst e. unfold ubound. destruct (ubound_sig st'). intros D. apply l in D. contradict D; apply le_not_lt; auto. remember (S e) as i. assert (~In i (e::st')). intros D. destruct D. subst i. contradict H2. clear -e. induction e; auto. subst i e. unfold ubound in H2. destruct (ubound_sig st'). apply l in H2. contradict H2. apply le_not_lt; auto. clear Heqe Heqi. exists i. exists e. exists st'. remember (fun s t=> if nat_eq_dec s i then if in_dec nat_eq_dec t ini then Remp else Rnil else if nat_eq_dec t e then if in_dec nat_eq_dec s acc then Remp else Rnil else tr s t) as tr'. assert (Htr': forall s t w, Racc (tr' s t) w -> In s (i::e::st')/\\In t (i::e::st')). intros. subst tr'. destruct (nat_eq_dec s i). subst s. destruct (in_dec nat_eq_dec t ini). split; auto. apply Hini in i0; auto. apply H0 in i0; auto. inversion H3. destruct (nat_eq_dec t e). subst t. split; auto. destruct (in_dec nat_eq_dec s acc). apply Hacc in i0. apply H0 in i0; auto. inversion H3. apply Htr in H3. destruct H3. apply H0 in H3. apply H0 in H4; auto. assert (Hini':incl (i::nil) (i::e::st')). intros x Hx. destruct Hx. subst x; auto. destruct H3. assert (Hacc': incl (e::nil) (i::e::st')). intros x Hx. destruct Hx. subst x; auto. destruct H3.\n  assert (Hi:forall w s, ~Racc (tr' s i) w). intros w s D. subst tr'. destruct (nat_eq_dec s i). subst s. destruct (in_dec nat_eq_dec i ini). contradict H2. right. apply H0; auto. inversion D. destruct (nat_eq_dec i e). subst e; contradict H2; auto. apply Htr in D. destruct D. contradict H2; right; apply H0; auto. assert (He:forall w s, ~Racc (tr' e s ) w). simpl. intros w s D. subst tr'. destruct (nat_eq_dec e i). subst e; contradict H2; auto. destruct (nat_eq_dec s e). subst s. destruct (in_dec nat_eq_dec e acc). contradict H1; apply H0; auto. inversion D. apply Htr in D. destruct D. contradict H1; apply H0; auto. exists (mkRFA tr' Htr' Hini' Hacc'). intros; split; intros.\n  inversion H3. clear H3. simpl in H7. simpl in H8. apply RFAacc_intro with (i::l++e::nil) i e; simpl; auto. assert (incl l st). apply RFAsteps_const with (is:=is) (st:=st) in H4; auto. inversion H5. subst a l.  simpl. replace w with (nil++w); auto. apply RFAsteps_cons; auto. replace w with (w++nil). replace (is::l0++e::nil) with ((is::l0)++e::nil); auto. apply RFAsteps_app with (s:=es); auto. revert H4. revert H3. generalize (is::l0). intros l Hl Hj. induction Hj; auto. apply RFAsteps_cons. apply IHHj. intros x Hx; apply Hl; auto. simpl. subst tr'. destruct (nat_eq_dec s i). subst s. contradict H2. right. apply H0. apply Hl; auto. destruct (nat_eq_dec t e). subst t. contradict H1. apply H0. apply Hl; auto. simpl in H3; auto. replace nil with (nil (A:=C)++nil) at 1; auto. apply RFAsteps_cons; auto. simpl. subst tr'. destruct (nat_eq_dec es i). subst es. contradict H2. right. apply H0; auto. destruct (nat_eq_dec e e). destruct (in_dec nat_eq_dec es acc). apply Remp_spec; auto. contradiction. contradict n0; auto. rewrite app_nil_r; auto. simpl. subst tr'. destruct (nat_eq_dec i i). destruct (in_dec nat_eq_dec is ini). apply Remp_spec; auto. contradiction. contradict n; auto.\n  assert (Hs:forall l s w, RFAsteps tr' w (s::l) -> ~In i l). clear -Hi. induction l; intros; auto. intros D. destruct D. subst a. inversion H. simpl in H5. contradict H5; auto. contradict H0. inversion H. apply IHl with a w2; auto. assert (Ht:forall l s w, RFAsteps tr' w (l++s::nil) -> ~In e l). clear -He. induction l; intros; auto. intros D. destruct D. subst a. inversion H. destruct l; inversion H3. simpl in H4. contradict H4; auto. contradict H0. inversion H. destruct l; inversion H3. rewrite H1 in H3. apply IHl with s w2; auto.  inversion H3. clear H3. simpl in H7. destruct H7; [subst is|inversion H3]. destruct H8; [subst es|inversion H3]. inversion H5. subst a l. apply Tail_rev in H6. destruct H6 as [l H6]. destruct l. inversion H6. subst e. contradict H2; auto. inversion H6. subst n l0. clear H5 H6. assert (incl l st). intros x Hx. apply H0. assert (In x (i::e::st')). apply RFAsteps_const with (is:=i) (st:=i::e::st') in H4; auto. apply H4. right. apply in_or_app; auto. destruct H3. subst x. absurd (In i (l++e::nil)). apply Hs in H4; auto. apply in_or_app; auto. destruct H3; auto. subst x. absurd (In e (i::l)); auto. replace (i::l++e::nil) with ((i::l)++e::nil) in H4; auto. apply Ht in H4; auto. clear Hs Ht. inversion H4. destruct l; inversion H8. subst w s. simpl in H9. assert (In t ini/\\w1=nil). subst tr'. clear -H9. destruct (nat_eq_dec i i); [|contradict n; auto]. destruct (in_dec nat_eq_dec t ini). apply Remp_spec in H9; auto. inversion H9. destruct H5. subst w1. destruct l as [|is l]. inversion H6. subst t. contradict H1. apply H0; auto. inversion H6. subst t l0. clear H6 H9 H4. destruct (Tail_dec' (is::l)) as [[es H4 _]|H4]; [|inversion H4]. replace (is::l++e::nil) with ((is::l)++e::nil) in H8; auto. apply RFAsteps_app_s_rev with (s:=es) in H8; auto. destruct H8 as [wa [wb [Ha [Hb Hc]]]]. subst w2.\n  assert (In es acc/\\wb=nil). inversion Hc. subst wb s t l0. simpl in H11. clear Hc. subst tr'. destruct (nat_eq_dec es i). subst es. absurd (In i st'). contradict H2; auto. apply H0. apply H3. auto. destruct (nat_eq_dec e e); [|contradict n0; auto]. destruct (in_dec nat_eq_dec es acc). split; auto. apply Remp_spec in H11. subst w1. inversion H9; auto. inversion H11. destruct H6. subst wb. simpl. rewrite app_nil_r. apply RFAacc_intro with (is::l) is es; auto. clear -Hb H3 H0 H1 H2 Heqtr'. revert H3 Hb. revert wa. generalize (is::l). clear l. induction l; intros. inversion Hb. inversion Hb. auto. subst wa a l. apply RFAsteps_cons; auto. apply IHl; auto. intros x Hx. apply H3; auto. simpl. simpl in H7. clear IHl Hb H6. subst tr'. destruct (nat_eq_dec s i).  subst s. absurd (In i st). contradict H2. right. apply H0; auto. apply H3; auto. destruct (nat_eq_dec t e). subst t. absurd (In e st). contradict H1. apply H0; auto. apply H3; auto. auto.\n  split; auto. split; auto. Defined.\n\nDefinition RFAsingle2RegExp: forall st i e r, RFAstates r = i::e::st -> RFAinit r = i::nil -> RFAaccept r = e::nil -> NoDup (i::e::st) -> (forall w s, ~Racc (RFAtrans r s i) w) -> (forall w s, ~Racc (RFAtrans r e s) w) -> {e| forall w, Racc e w <-> RFAacc r w}. induction st as [|p st]; intros. destruct r as [st tr ini acc Htr Hini Hacc]. simpl in H0. subst ini. simpl in H. subst st. simpl in H1. subst acc. simpl in H4. simpl in H3. exists (tr i e). intros; split; intros. apply RFAacc_intro with (i::e::nil) i e; simpl; auto. replace w with (w++nil). apply RFAsteps_cons; auto. rewrite app_nil_r; auto. inversion H. simpl in H6. destruct H6; [subst is|inversion H6]. simpl in H7. destruct H7; [subst es|inversion H6]. clear H. inversion H1. subst a l. inversion H0. subst w l0 s. inversion H5. subst e a. inversion H2. contradict H7; auto. inversion H7. subst w s l0. clear H0. simpl in H9. assert (In t (i::e::nil)). apply Htr in H9. destruct H9; auto. destruct H. subst t. contradict H9; auto. destruct H. subst t. destruct l. inversion H8. rewrite app_nil_r; auto. inversion H8. simpl in H11. contradict H11; auto. destruct H.\n  destruct r as [st' tr ini acc Htr Hini Hacc]. simpl in H. subst st'. simpl in H1. subst acc. simpl in H0. subst ini. simpl in H4. simpl in H3. remember (fun s t=>if nat_eq_dec s p then Rnil else if nat_eq_dec t p then Rnil else Ror (tr s t) (Rcons (tr s p) (Rcons (Rstar (tr p p)) (tr p t))) ) as tr'. assert (Htr': forall s t w, Racc (tr' s t) w -> In s (i::e::st) /\\ In t (i::e::st)). intros. subst tr'. destruct (nat_eq_dec s p). inversion H. destruct (nat_eq_dec t p). inversion H. inversion H. apply Htr in H6. destruct H6. split. destruct H6. subst s; auto. destruct H6. subst e; auto. destruct H6; auto. contradict n; auto. destruct H7. subst t; auto. destruct H7. subst e; auto. destruct H7; auto. contradict n0; auto. subst r s0 l. inversion H6. subst r s0 w. apply Htr in H5. destruct H5. inversion H8. subst r s0 m. apply Htr in H11. destruct H11. clear -H0 H7 n n0. split. destruct H0. subst s; auto. destruct H. subst e; auto. destruct H; auto. contradict n; auto. destruct H7. subst i; auto. destruct H. subst e; auto. destruct H; auto. contradict n0; auto. assert (Hini': incl (i::nil) (i::e::st)). intros x Hx.  destruct Hx. subst x; auto. destruct H. assert (Hacc':incl (e::nil) (i::e::st)). intros x Hx. destruct Hx. subst x; auto. destruct H. destruct (IHst i e (mkRFA tr' Htr' Hini' Hacc')) as [r' H]; simpl; auto. inversion H2. inversion H5. inversion H9. apply NoDup_cons. contradict H1. destruct H1. subst e i x; auto. auto. apply NoDup_cons; auto. intros w s D. subst tr'. destruct (nat_eq_dec s p). inversion D. destruct (nat_eq_dec i p). inversion D. inversion D. contradict H5; auto. inversion H5. inversion H10. contradict H15; auto. intros w s D. subst tr'. destruct (nat_eq_dec e p). inversion D. destruct (nat_eq_dec s p). inversion D. inversion D. contradict H5; auto. inversion H5. contradict H8; auto.\n  exists r'. intros; split; intros. apply H in H0. clear H. inversion H0. clear H0. simpl in H6. destruct H6; [subst is|inversion H0]. simpl in H7. destruct H7; [subst es|inversion H0]. assert (forall l is es w, incl l (i::e::st) -> Head is l->Tail es l->RFAsteps tr' w l -> exists m, Head is m /\\ Tail es m /\\ RFAsteps tr w m). clear H H1 H5 l w. induction l; intros. inversion H0. inversion H5. subst w s l. inversion H0. subst a a0 l. inversion H1. subst a es. exists (is::nil); auto. inversion H8. subst w s l. apply IHl with t es w2 in H9; auto. simpl in H10. destruct H9 as [m [Ha [Hb Hc]]]. clear IHl IHst H5. subst tr'. assert (~In p (i::e::st)). inversion H2. intros D. destruct D. contradict H7; subst x i; auto. inversion H8. destruct H9. subst p. contradict H13; auto. inversion H14; contradiction. destruct (nat_eq_dec a p). subst a. contradict H5. apply H; auto. destruct (nat_eq_dec t p). subst p. contradict H5; apply H; auto. inversion H10. inversion H0. subst a a0 l1. exists (is::m). split; auto. split; auto. subst s r l. inversion Ha. subst a m. apply RFAsteps_cons; auto. subst r s l. inversion H9. subst w1 r s. inversion H12. subst r s m0. clear H9 H12 H10. inversion H0. subst a0 a l2. assert (exists sl, Head p sl /\\ Tail p sl /\\ RFAsteps tr l1 sl). revert H11. apply (Fix (well_founded_ltof (list C) (length (A:=C)))) with (P:=fun l1=>Racc (Rstar (tr p p)) l1->exists sl, Head p sl /\\ Tail p sl/\\ RFAsteps tr l1 sl). clear l1. intros l1 IH H7. apply Rstar_rev in H7. destruct H7 as [[w0 [w1 [Hd [He [Hf Hg]]]]]|Hd]. subst l1. destruct (IH w1) as [sl [Hh [Hi Hj]]]; auto. unfold ltof. destruct w0. contradict He; auto. simpl. apply le_n_S. rewrite app_length; auto. exists (p::sl). split; auto. split; auto. inversion Hh. subst a sl. apply RFAsteps_cons; auto. subst l1. exists (p::nil); auto.\n  destruct H6 as [sl [H9 [H10 H12]]]. exists (is::sl++m). split; auto. split. apply Tail_cons. clear -Hb. induction sl; simpl; auto. rewrite <- app_assoc. inversion H9.  subst a sl. simpl. apply RFAsteps_cons; auto. rewrite <- app_assoc. replace (p::l2++m) with ((p::l2)++m); auto. apply RFAsteps_app with p; auto. inversion Ha. subst a m. apply RFAsteps_cons; auto.  intros x Hx. destruct Hx. subst x. apply H; auto. apply H; auto. inversion H1; auto.  apply H0 with (is:=i) (es:=e) in H; auto. destruct H as [m [Ha [Hb Hc]]]. apply RFAacc_intro with m i e; simpl; auto. apply RFAsteps_const with (is:=i) (st:=i::e::st) in H; auto.\n  apply H. clear H. inversion H0. clear H0. simpl in H6. destruct H6; [subst is|inversion H0]. simpl in H7. destruct H7; [subst es|inversion H0]. assert (forall l is es w, incl l (i::e::p::st) -> Head is l->Tail es l->is<>p->es<>p->RFAsteps tr w l -> RFAsteps tr' w (remove nat_eq_dec p l)). clear H H1 H5 w l r' IHst. intros l. apply (Fix (well_founded_ltof (list nat) (length (A:=nat)))) with (P:=fun l=>forall is es w, incl l (i::e::p::st)->Head is l->Tail es l->is<>p->es<>p->RFAsteps tr w l ->RFAsteps tr' w (remove nat_eq_dec p l)). clear l. intros l IH. intros. inversion H0. subst a l. clear H0. inversion H7. subst w s l0. simpl. destruct (nat_eq_dec p is); auto. contradict H5; auto. subst w s l0. clear H7. simpl in H11. destruct (repeat_head nat_eq_dec p (t::l)) as [[n [u [l' Ha Hb]]]| [n Ha]]. destruct (nat_eq_dec n 0). subst n. simpl in Ha. inversion Ha. subst u l'. apply IH  with (is:=t) (es:=es) in H10; auto. simpl in H10. simpl. destruct (nat_eq_dec p is). contradict H5; auto. destruct (nat_eq_dec p t). contradict Hb; auto. apply RFAsteps_cons; simpl; auto. subst tr'. destruct (nat_eq_dec is p). contradict n; auto. destruct (nat_eq_dec t p). contradict Hb; auto. auto.  unfold ltof. auto. intros x Hx. apply H. auto. inversion H1; auto. rewrite Ha in H10. replace (repeat p n++u::l') with ((repeat p n++u::nil)++l') in H10. apply RFAsteps_app_s_rev with (s:=u) in H10. destruct H10 as [wa [wb [Hd [He Hf]]]]. subst w2. assert (t=p). destruct n. contradict n0; auto. simpl in Ha. inversion Ha; auto. rewrite Ha. subst t. rewrite app_assoc. replace (remove nat_eq_dec p (is::repeat p n++u::l')) with (is::u::remove nat_eq_dec p l'). apply RFAsteps_cons. apply IH with (is:=u) (es:=es) in Hf; auto. simpl in Hf. destruct (nat_eq_dec p u); auto. contradict Hb; auto. unfold ltof. rewrite Ha. simpl; repeat apply le_n_S. rewrite app_length. rewrite plus_comm; auto.\n  intros x Hx. apply H. rewrite Ha. right. apply in_or_app; auto. inversion H1. rewrite Ha in H8. clear -H8. induction n; simpl in H8; auto. apply IHn. inversion H8; auto. destruct n; inversion H2. simpl. clear IH. subst tr'. destruct (nat_eq_dec is p). contradict H5; auto. destruct (nat_eq_dec u p). contradict Hb; auto. apply RAor2. apply RAcons; auto. apply RFAsteps_app_s_rev with (s:=p) in He; auto. destruct He as [w3 [w2 [H7 [H8 H9]]]]. subst wa. apply RAcons; auto. destruct n. contradict n0; auto. clear -H8. simpl in H8. revert H8. revert w3. induction n; intros. simpl in H8. inversion H8. auto. simpl in H8. inversion H8. subst w3 s t l. apply IHn in H2; auto. inversion H9; auto. subst w2 s t l0. inversion H12. subst w4 s. simpl in H14. rewrite app_nil_r; auto. clear -n0. induction n. contradict n0; auto. destruct n; simpl. auto. simpl in IHn. apply Tail_cons; auto. clear -H5 Hb. simpl. destruct (nat_eq_dec p is). contradict H5; auto. f_equal. induction n. simpl. destruct (nat_eq_dec p u). contradict Hb; auto. auto. simpl. destruct (nat_eq_dec p p); auto. contradict n1; auto. clear -n. induction n; simpl; auto. rewrite <- app_assoc. simpl; auto. destruct n. inversion Ha. simpl in Ha. inversion Ha. subst t l. contradict H6. clear -H1. inversion H1. subst a b l. clear H1. induction n; simpl in H2. inversion H2. auto. inversion H1. apply IHn. inversion H2; auto. apply RFAacc_intro with (remove nat_eq_dec p l) i e; simpl; auto. apply H0 with i e; auto. apply RFAsteps_const with (is:=i) (st:=i::e::p::st) in H; auto. inversion H2. contradict H8; subst p; auto. inversion H2. inversion H9. contradict H12; subst p; auto. inversion H1. simpl. destruct (nat_eq_dec p i); auto. inversion H2. contradict H10; subst x p; auto. assert (e<>p). inversion H2. inversion H9. contradict H12; subst p; auto. clear -H5 H6. induction H5. simpl. destruct (nat_eq_dec p a); auto. contradict H6; auto. simpl. destruct (nat_eq_dec p b); auto. Defined.\n\nDefinition EFA2RegExp: forall e cset, (forall s c, In s (EFAstates e) -> EFAtrans e s c<>nil -> In c cset) -> {r| forall w, EFAacc e w <-> Racc r w}. intros. destruct (EFA2RFA e cset H) as [r H0]. destruct (RFA2single_edge r) as [is [es [st [r' H1 [H2 [H3 [H4 [H5 [H6 H7]]]]]]]]]. destruct (RFAsingle2RegExp (st:=st) (i:=is) (e:=es) r') as [ro H8]; auto. intros. exists ro. intros; split; intros. apply H8. apply H1. apply H0; auto. apply H0. apply H1. apply H8; auto. Defined.\n\nFixpoint repeatl {T:Type} n (l:list T) := match n with 0=>nil | S n'=>l++repeatl n' l end.\nLemma pumping: forall r, {n:nat | forall w, Racc r w -> n<=length w ->exists w1 w2 w3, w=w1++w2++w3 /\\ w2<>nil /\\ length w1+length w2<=n /\\ forall i, Racc r (w1++repeatl i w2++w3)}. intros. destruct (RegExp2EFA r) as [e H]. destruct (EFA2NFA e) as [n H0]. exists (length (NFAstates n)). intros. apply H in H1. apply H0 in H1. inversion H1. assert (length l=S(length w)). apply NFAsteps_length in H5; auto. destruct (head_n_split (S (length (NFAstates n))) l) as [l1 [l2 H9 H10]]. subst l. apply le_n_S in H2. rewrite <- H8 in H2. apply H10 in H2. clear H10. assert (incl (l1++l2) (NFAstates n)). inversion H6. rewrite <- H11 in H5. apply NFAsteps_const with (s:=is) (st:=NFAstates n) in H5; auto. apply NFAtrans_const. apply NFAinit_const in H4; auto. assert (incl l1 (NFAstates n)). intros x Hx. apply H9. apply in_or_app; auto. destruct (pegeon_hole nat_eq_dec H10) as [s [l3 [l4 [l5 H11]]]]. rewrite H2; auto. subst l1. rewrite <- app_assoc in H5. simpl in H5. rewrite <- app_assoc in H5. simpl in H5. replace (l3++s::l4++s::l5++l2) with ((l3++s::nil)++l4++s::l5++l2) in H5. apply NFAsteps_app_s_rev with (s:=s) in H5. destruct H5 as [w1 [wa [Ha [Hb Hc]]]]. subst w. exists w1. replace (s::l4++s::l5++l2) with ((s::l4++s::nil)++(l5++l2)) in Hc. apply NFAsteps_app_s_rev with (s:=s) in Hc. destruct Hc as [w2 [w3 [Ha [Hd He]]]]. subst wa. exists w2. exists w3. split; auto. split. apply NFAsteps_length in Hd. simpl in Hd. rewrite app_length in Hd. rewrite plus_comm in Hd. simpl in Hd. inversion Hd. intros D. subst w2. simpl in Hd. inversion H11. split. apply NFAsteps_length in Hb. apply NFAsteps_length in Hd. rewrite app_length in Hb. simpl in Hd. rewrite app_length in Hd. simpl in Hb. simpl in Hd. rewrite plus_comm in Hb. rewrite plus_comm in Hd. inversion Hb. inversion Hd. rewrite app_length in H2. simpl in H2. rewrite app_length in H2. rewrite <- plus_n_Sm in H2. inversion H2. apply plus_le_compat_l. rewrite <- plus_n_Sm. apply le_n_S. apply le_plus_l.\n  intros. apply H. apply H0. apply NFAacc_intro with is es ((l3++s::nil)++repeatl i (l4++s::nil)++l5++l2); auto. apply NFAsteps_app with (s:=s); auto. replace (s::repeatl i (l4++s::nil)++l5++l2) with ((s::repeatl i (l4++s::nil))++l5++l2). apply NFAsteps_app with (s:=s); auto. clear -Hd. induction i; simpl; auto. replace (s::(l4++s::nil)++repeatl i (l4++s::nil)) with ((s::l4++s::nil)++repeatl i (l4++s::nil)). apply NFAsteps_app with (s:=s); auto. simpl; auto. clear -i. induction i; simpl; auto. inversion IHi. rewrite app_nil_r. auto. auto. simpl; auto.  destruct l3. simpl in H6. inversion H6. subst s. simpl. auto. simpl in H6. inversion H6. subst n0. simpl; auto. clear -H7. destruct l2. rewrite app_nil_r in H7. rewrite app_nil_r. destruct l5. rewrite app_nil_r. apply Tail_app_rev in H7. inversion H7. destruct l4; inversion H2. apply Tail_app_rev in H1. inversion H1. subst a b s a0. induction i. simpl. rewrite app_nil_r. auto. simpl. destruct i. rewrite app_nil_r. auto. apply Tail_app_rev in IHi. auto. simpl. destruct l4; discriminate. inversion H5. discriminate. discriminate. apply Tail_app_rev in H7. inversion H7. destruct l4; inversion H2. apply Tail_app_rev in H1. inversion H1; auto. discriminate. discriminate. apply Tail_app_rev in H7; auto. discriminate. auto. simpl. f_equal. rewrite <- app_assoc. f_equal; auto. auto. rewrite <- app_assoc; auto. Defined.\n\nTheorem no_eq_RegEx: forall r a b, a <> b -> ~(forall w, Racc r w <-> exists n, w=repeat a n++repeat b n). Proof. intros. destruct (pumping r) as [s H1]. intros D. assert (Racc r (repeat a (S s)++repeat b (S s))). apply D. exists (S s); auto. apply H1 in H0. destruct H0 as [w1 [w2 [w3 [H2 [H3 [H4 H5]]]]]]. clear H1. rewrite app_assoc in H2. rewrite <- app_length in H4. apply app_rev in H2; auto. destruct H2 as [[[l [Ha Hb] Hc]|[l [Ha Hb] Hc]]|[Ha Hb]]. apply repeat_app in Ha. destruct Ha as [x [y [Hd He] Hf]]. subst w3 l. symmetry in Hd. apply repeat_app in Hd. destruct Hd as [z [v [Hg Hh] Hi]]. subst x w1 w2. assert (Racc r (repeat a z++repeatl 0 (repeat a v)++repeat a y ++ repeat b (S s))); auto. simpl in H0. rewrite app_assoc in H0. rewrite <- repeat_plus in H0. apply D in H0. destruct H0 as [n H0]. apply app_rev in H0; auto. destruct H0 as [[[m [Hd He] Hg]|[m [Hd He] Hg]]|[Hd He]]. destruct m. contradict Hg; auto. destruct n; inversion He. subst c. apply repeat_app in Hd. destruct Hd as [x [u [H7 H8] H9]]. destruct u; inversion H8. contradict H; auto. destruct m. contradict Hg; auto. inversion He. subst c. apply repeat_app in Hd. destruct Hd as [x [u [H7 H8] H9]]. destruct u; inversion H8. contradict H; auto. apply repeat_eq_rev in Hd. subst n. replace (b::repeat b s) with (repeat b (S s)) in He; auto. apply repeat_eq_rev in He. rewrite Hf in He. rewrite <- plus_assoc in He. apply plus_reg_l in He. destruct v. contradict H3; auto. simpl in He. absurd (y<=v+y); auto. apply lt_not_le. rewrite <- He at 2. auto. rewrite Ha in H4. rewrite app_length in H4. rewrite repeat_length in H4. contradict H4. simpl. apply le_not_lt; auto. rewrite <- Ha in H4. contradict H4. rewrite repeat_length. apply le_not_lt; auto. rewrite app_length. rewrite repeat_length. simpl. auto. Qed.\n\n\nEnd CharType.\n", "meta": {"author": "ysfmssk", "repo": "coq", "sha": "07e0aa439df36339e3b6a27c3699a34f6eee4f8a", "save_path": "github-repos/coq/ysfmssk-coq", "path": "github-repos/coq/ysfmssk-coq/coq-07e0aa439df36339e3b6a27c3699a34f6eee4f8a/RegExp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6645171383937196}}
{"text": "(** Fragmento Implicacional da Lógica Proposicional Intuicionista **)\n\n(** Dicas:\n\n    intro: introdução da implicação\n    exact H: a hipótese H corresponde exatamente ao que se quer provar.\n    assumption: o que se quer provar é igual a alguma das hipóteses.\n    apply H: o tipo alvo de H coincide com o que se quer provar. \n    inversion H: aplica o(s) construtor(es) que permitem gerar a hipótese H. Se nenhum construtor pode ser aplicado, a prova é concluída. Também permite concluir que a partir do absurdo (False) se prova qualquer coisa.\n\n*)\n\n(**\n   Nos exercícios abaixos remova o comando 'Admitted' e construa uma prova para as proposições apresentadas.\n *)\n\nSection Exercicios1.\nVariables A B C D: Prop.\n\nLemma exercicio1 : A -> B -> A.\nProof.\nintros A1 B1.\nassumption.\n\nQed.\n\nLemma exercicio2 : (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\n\nintros func1 func2 A1.\n\napply func1.\n\nassumption.\n\napply func2.\n\nexact A1.\n\nQed.\n\nLemma exercicio3 : (A -> B) -> (C -> A) -> C -> B.\nProof.\n\nintros func1 func2 C1.\napply func1.\napply func2.\nexact C1.\n\nQed.\n\nLemma exercicio4 : (A -> B -> C) -> B -> A -> C.\nProof.\n\nintros func1 B1 A1.\napply func1.\nexact A1.\nexact B1.\n\nQed.\n\nLemma exercicio5 : ((((A -> B) -> A) -> A) -> B) -> B. \nProof.\n\nintros func1.\napply func1.\nintros func2.\napply func2.\nintros A1.\napply func1.\nintros func3.\nexact A1.\n\nQed.\n\nLemma exercicio6: (A -> B) -> (B -> C) -> A -> C.\nProof.\n\nintros func1 func2 A1.\napply func2.\napply func1.\nexact A1.\n\nQed.\n\nLemma exercicio7: (A -> B -> C) -> (B -> A -> C).\nProof.\n\nintros func1 func2.\nintros A1.\napply func1.\nexact A1.\nexact func2.\n\nQed.\n\nLemma exercicio8: (A -> C) -> A -> B -> C.\nProof.\nAdmitted.\n\nLemma exercicio9: (A -> A -> B) -> A -> B.\nProof.\nAdmitted.\n\nLemma exercicio10:  (A -> B) -> (A -> A -> B).\nProof.\nAdmitted.\n\nLemma exercicio11: (A -> B) -> (A -> C) -> (B -> C -> D) -> A -> D.\nProof.\nAdmitted.\n\nLemma exercicio12: ((((A -> B) -> A) -> A) -> B) -> B.\nProof.\nAdmitted.\n\nLemma exercicio13: False -> A.\nProof.\n  intro H.\n  inversion H.\nQed.\n\nLemma conj_imp: (A -> B -> C) <-> ((A /\\ B ) -> C).\nProof.\n  split.\n  - admit.\n  - Admitted.\n\n(**\nproof identation\nhttp://poleiro.info/posts/2013-06-27-structuring-proofs-with-bullets.html\nhttp://prl.ccs.neu.edu/blog/2017/02/21/bullets-are-good-for-your-coq-proofs/\nhttps://coq.inria.fr/refman/proof-engine/proof-handling.html\n*)\n\nEnd Exercicios1.\n\nSection Exercicios2.\nVariable P: Prop.\nLemma id_p: P -> P.\nProof.\n  intro H.\n  assumption.\nQed.\n\nPrint id_p.\n\nLemma id_p'': P -> P.\nProof.\n  exact (fun x:P => x).\nQed.\n\n\nEnd Exercicios2.\n\nTheorem id_p': forall P, P -> P.\nProof.\n  intros P.\n  intros P1.\n  assumption.\nQed.\n\nPrint id_p'.\n\nTheorem id_p''': forall P:Prop, P -> P.\nProof.\n  exact (fun (P:Prop) (x:P) => x).\nQed.\n\nPrint id_p'.\n\n\n\nLemma id_PP: forall P, (P -> P) -> (P -> P).\nProof.\n  intros P p1 p2.\n  assumption.\nQed.\n\nPrint id_PP.\n\nLemma id_PP': forall P, (P -> P) -> (P -> P).\nProof.\n  exact (fun (P:Type) (x : P -> P) => x).\nQed.\n\nPrint id_PP'.\n\nLemma imp_trans: forall P Q R, (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n  intros P.\n  intros Q.\n  intros R.\n  intros func1.\n  intros func2.\n  intros Papp.\n  pose (Qapp := func1 Papp).\n  pose (Rapp := func2 Qapp).\n  assumption.\nQed.\n\nLemma imp_trans_ref: forall P Q R, (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n  intros P.\n  intros Q.\n  intros R.\n  intros func1.\n  intros func2.\n  intros Papp.\n  refine (func2 _).\n  refine (func1 _).\n  assumption.\nQed.\n\nLemma imp_perm : forall P Q R, (P -> Q -> R) -> (Q -> P -> R).\nProof.\n  intros P Q R.\n  intros func1.\n  intros Qapp.\n  intros Papp.\n  pose (QRapp := func1 Papp).\n  pose (Rapp := QRapp Qapp).\n  assumption.\nQed.\n\nLemma ignore_Q : forall P Q R, (P -> R) -> P -> Q -> R.\nProof.\n  intros P Q R.\n  intros func1.\n  intros Papp.\n  intros Qapp.\n  pose (Rapp := func1 Papp).\n  assumption.\nQed.\n\nLemma ignore_Q_without_parenthesis : forall P Q R, P -> R -> P -> Q -> R.\nProof.\n  intros P Q R.\n  intros Papp Rapp Papp2 Qapp1.\n  assumption.\nQed.\n\nLemma delta_imp : forall P Q, (P -> P -> Q) -> P -> Q.\nProof.\n  intros P Q.\n  intros func1.\n  intros Papp.\n  pose (PQapp := func1 Papp).\n  pose (Qapp := PQapp Papp).\n  assumption.\nQed.\n\nLemma delta_impR : forall P Q, (P->Q)->(P->P->Q).\nProof.\n  intros P Q.\n  intros func1.\n  intros Papp.\n  intros Papp2.\n  pose (Qapp := func1 Papp).\n  assumption.\nQed.\n\nLemma delta_impR' : forall P Q, (P->Q)->(P->P->Q).\nProof.\n  intros P Q.\n  intros func1.\n  intros Papp.\n  intros Papp2.\n  apply func1.\n  assumption.\nQed.\n\nLemma diamond : forall P Q R T, (P->Q)->(P->R)->(Q->R->T)->P->T.\nProof.\n  intros P Q R T.\n  intros func1.\n  intros func2.\n  intros func3.\n  intros Papp.\n  pose (Qapp := func1 Papp).\n  pose (Rapp := func2 Papp).\n  pose (RTapp := func3 Qapp).\n  pose (Tapp := RTapp Rapp).\n  assumption.\nQed.\n\nLemma weak_peirce : forall P Q, ((((P->Q)->P)->P)->Q)->Q.\nProof.\n  intros P Q.\n  intros func1.\n  apply func1.\n  intro func2.\n  apply func2.\n  intro func3.\n  apply func1.\n  intro func4.\n  exact func3.\nQed.\n\nPrint weak_peirce.\n", "meta": {"author": "acgabriel3", "repo": "confluencia", "sha": "1b1616b0c363d72c11458479e5793b730d78dfed", "save_path": "github-repos/coq/acgabriel3-confluencia", "path": "github-repos/coq/acgabriel3-confluencia/confluencia-1b1616b0c363d72c11458479e5793b730d78dfed/ex1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.6645062543338719}}
{"text": "From Undecidability.Shared.Libs.PSL Require Import FinTypes.\n\nDefinition Cardinality (F: finType) := | elem F |.\n\n(* * Dupfreeness *)\n(* Proofs about dupfreeness *)\n\n\nLemma dupfree_countOne (X: eqType) (A: list X) : (forall x, count A x <= 1) -> dupfree A.\nProof.\n  induction A.\n  - constructor.\n  - intro H. constructor.\n    + cbn in H.  specialize (H a). deq a. assert (count A a = 0) by lia. now apply countZero.\n    + apply IHA. intro x. specialize (H x). cbn in H. dec; lia.\nQed.\n\nLemma dupfree_elements (X: finType) : dupfree (elem X).\nProof.\n  destruct X as [X [A AI]]. assert (forall x, count A x <= 1) as H'.\n  {\n    intro x. specialize (AI x). lia.\n  }\n  now apply dupfree_countOne.  \nQed.\n\nLemma dupfree_length (X: finType) (A: list X) : dupfree A -> |A| <= Cardinality X.\nProof.\n  unfold Cardinality.  intros D.\n  rewrite <- (dupfree_card D). rewrite <- (dupfree_card (dupfree_elements X)).\n  apply card_le. apply allSub.\nQed.\n\nLemma disjoint_concat X (A: list (list X)) (B: list X) : (forall C, C el A -> disjoint B C) -> disjoint B (concat A).\nProof.\n  intros H. induction A.\n  - cbn. auto.\n  - cbn. apply disjoint_symm. apply disjoint_app. split; auto using disjoint_symm.\nQed.\n\nLemma dupfree_concat (X: Type) (A: list (list X)) : (forall B, B el A -> dupfree B) /\\ (forall B C, B <> C -> B el A -> C el A -> disjoint B C) -> dupfree A -> dupfree (concat A).\nProof.\n  induction A.\n  - constructor.\n  - intros [H H'] D. cbn. apply dupfree_app.\n    + apply disjoint_concat. intros C E. apply H'; auto. inv D. intro G; apply H2. now subst a.\n    + now apply H.\n    + inv D; apply IHA; auto.\nQed.     \n\n(* (* * Proofs about Cardinality *) *)\n\n(* Lemma Card_positiv (X: finType) (x:X) : Cardinality X > 0. *)\n(* Proof. *)\n(*   pose proof (elem_spec x).  unfold Cardinality.  destruct (elem X). *)\n(*   - contradiction H. *)\n(*   - cbn. lia. *)\n(* Qed.  *)\n\n(* Lemma Cardinality_card_eq (X: finType): card (elem X) = Cardinality X. *)\n(* Proof. *)\n(*   apply dupfree_card. apply dupfree_elements. *)\n(* Qed. *)\n\n(* Lemma card_upper_bound (X: finType) (A: list X): card A <= Cardinality X. *)\n(* Proof. *)\n(*  rewrite <-  Cardinality_card_eq. apply card_le. apply allSub. *)\n(* Qed.   *)\n\n\n(* Lemma injective_dupfree (X: finType) (Y: Type) (A: list X) (f: X -> Y) : injective f -> dupfree (getImage f). *)\n(* Proof. *)\n(*   intro inj. unfold injective in inj. *)\n(*   unfold getImage. apply dupfree_map. *)\n(*   - firstorder. *)\n(*   - apply dupfree_elements. *)\n(* Qed. *)\n\n(* Theorem pidgeonHole_inj (X Y: finType) (f: X -> Y) (inj: injective f): Cardinality X <= Cardinality Y. *)\n(* Proof. *)\n(*   rewrite <- (getImage_length f). apply dupfree_length. apply (injective_dupfree (elem X) inj). *)\n(* Qed. *)\n\n(* Lemma surj_sub (X Y: finType) (f: X -> Y) (surj: surjective f): elem Y <<= getImage f. *)\n(* Proof. *)\n(* intros y E. specialize (surj y). destruct surj as [x H]. subst y. apply getImage_in. *)\n(* Qed. *)\n\n(* Theorem pidgeonHole_surj (X Y: finType) (f: X -> Y) (surj: surjective f): Cardinality X >= Cardinality Y. *)\n(* Proof. *)\n(*   rewrite <- (getImage_length f). rewrite <- Cardinality_card_eq. *)\n(*     pose proof (card_le (surj_sub surj)) as H. pose proof (card_length_leq (getImage f)) as H'. lia. *)\n(* Qed. *)\n\n(* Lemma eq_iff (x y: nat) : x >= y /\\ x <= y -> x = y. *)\n(* Proof. *)\n(*   lia. *)\n(* Qed. *)\n\n(* Corollary pidgeonHole_bij (X Y: finType) (f: X -> Y) (bij: bijective f): *)\n(*   Cardinality X = Cardinality Y. *)\n(* Proof. *)\n(*   destruct bij as [inj surj]. apply eq_iff. split. *)\n(*   - now eapply pidgeonHole_surj. *)\n(*   - eapply pidgeonHole_inj; eauto. *)\n(* Qed.     *)\n\n(* Lemma Prod_Card (X Y: finType) : Cardinality (X (x) Y) = Cardinality X * Cardinality Y. *)\n(* Proof. *)\n(*   cbn.  unfold prodLists. unfold Cardinality. induction (elem X).  *)\n(*   - reflexivity. *)\n(*   - cbn. rewrite app_length. rewrite IHl. f_equal. apply map_length. *)\n(* Qed.     *)\n\n(* Lemma Option_Card (X: finType) : Cardinality (? X) = S(Cardinality X). *)\n(* Proof. *)\n(*   cbn. now rewrite map_length. *)\n(* Qed. *)\n\n(* Lemma SumCard (X Y: finType) : Cardinality (finType_sum X Y) = Cardinality X + Cardinality Y. *)\n(* Proof. *)\n(*   unfold Cardinality. cbn. rewrite app_length. unfold toSumList1, toSumList2. now  repeat rewrite map_length. *)\n(* Qed. *)\n\n(* Lemma extPow_length X Y L P: |@extensionalPower X Y L P| = | L |. *)\n(* Proof. *)\n(*   induction L. *)\n(*   -  reflexivity. *)\n(*   - simpl. f_equal. apply IHL. *)\n(* Qed. *)\n\n\n(* Lemma concat_map_length (X: Type) (A: list X) (B: list (list X)) : *)\n(* | concat (map (fun x => map (cons x) B) A) |= |A| * |B|. *)\n(* Proof. *)\n(*   induction A. *)\n(*   - reflexivity. *)\n(*   - cbn. rewrite app_length. rewrite map_length. congruence. *)\n(* Qed.     *)\n  \n(* Lemma images_length Y (A: list Y) n : |images A n| = (|A| ^ n)%nat. *)\n(* Proof. *)\n(*   induction n. *)\n(*   - reflexivity. *)\n(*   - cbn. rewrite concat_map_length.  now rewrite IHn. *)\n(* Qed. *)\n\n(* Lemma Vector_Card (X Y: finType): Cardinality (Y ^ X) = (Cardinality Y ^ (Cardinality X ))%nat. *)\n(* Proof. *)\n(*   cbn. rewrite extPow_length. now rewrite images_length. *)\n(* Qed. *)\n\n", "meta": {"author": "uds-psl", "repo": "time-invariance-thesis-for-L", "sha": "41f4eb1f788cc4f096d9c7c286c9ca907588859f", "save_path": "github-repos/coq/uds-psl-time-invariance-thesis-for-L", "path": "github-repos/coq/uds-psl-time-invariance-thesis-for-L/time-invariance-thesis-for-L-41f4eb1f788cc4f096d9c7c286c9ca907588859f/theories/Shared/Libs/PSL/FiniteTypes/Cardinality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.664506254240651}}
{"text": "(* The Universe contains 'Things.', for example: \"I\", \"London\", etc. *)\nParameter U: Set.\n\n(* existence is affirmed or denied, is regarded as the Predicate *)\nDefinition Predicate := U -> Prop.\n\n(*\nA 'Proposition', when in normal form, asserts, as to certain two Classes, which are called its 'Subject' and 'Predicate', either\n\nthat some Members of its Subject are Members of its Predicate;\n\nor that no Members of its Subject are Members of its Predicate;\n\nor that all Members of its Subject are Members of its Predicate.\n\n*)\n\n(* All Members of its Subject are Members of its Predicate; Proposition in A *)\nNotation \"'All' subject 'are' predicate\" := (forall x:U, subject(x) -> predicate(x)) (at level 50).\nNotation \"'All' subject 'is' predicate\" := (forall x:U, subject(x) -> predicate(x)) (at level 50).\n\n(* No Members of its Subject are Members of its Predicate; Proposition in E *)\nNotation \"'No' subject 'are' predicate\" := (forall x:U, subject(x) -> ~predicate(x)) (at level 50).\nNotation \"'No' subject 'is' predicate\" := (forall x:U, subject(x) -> ~predicate(x)) (at level 50).\n\n(* Some Members of its Subject are Members of its Predicate; Proposition in I *)\nNotation \"'Some' subject 'are' predicate\" := (exists x:U, subject(x) /\\ predicate(x)) (at level 50).\nNotation \"'Some' subject 'are' 'not' predicate\" := (exists x:U, subject(x) /\\ ~predicate(x)) (at level 50).\n\n\n\nAxiom contraposition: forall subject predicate: Predicate, (No subject are predicate) -> (No predicate are subject).\nAxiom doubleneg: forall p: Prop, ~~p->p.\n\n\nParameter selfish popular helpful: Predicate.\nAxiom A1: No selfish is popular.\nAxiom A2: All helpful is popular.\nTheorem T1: No selfish is helpful.\n  intros.\n  apply A1 in H.\n  contradict H.\n  apply A2.\n  assumption.\nQed.\n\n\nParameter soldiers valiant brave: Predicate.\nAxiom A3: All soldiers are valiant.\nAxiom A4: Some soldiers are brave.\nTheorem T2: Some valiant are brave.\nProof.\n  destruct A4.\n  destruct H.\n  apply A3 in H.\n  exists x.\n  split.\n  assumption.\n  assumption.\nQed.\n\n\nParameter my_uncles generous gourmet: Predicate.\nAxiom A5: No gourmet is generous.\nAxiom A6: All my_uncles are generous.\nTheorem T3: No my_uncles are gourmet.\n  intros.\n  apply A6 in H.\n  contradict H.\n  apply A5.\n  assumption.\nQed.\n\n\nParameter cats understanding_French chickens: Predicate.\nAxiom A7: All cats are understanding_French.\nAxiom A8: Some chickens are cats.\nTheorem T4: Some chickens are understanding_French.\ndestruct A8.\ndestruct H as [a b].\napply A7 in b.\nexists x.\ntauto.\nQed.\n\n(*\n'To begin with,' said the Cat, 'a dog's not mad. You grant that?'\n'I suppose so,' said Alice.\n'Well, then,' the Cat went on,*\n'you see, a dog growls when it's angry, and wags its tail when it's pleased. \nNow I growl when I'm pleased, and wag my tail when I'm angry.\nTherefore I'm mad.'\n*)\nParameter mad cat dogs angry: Predicate.\nAxiom A9: No dogs are mad.\n(* TODO finish Alice speaks to Cheshire Cat *)", "meta": {"author": "NotBad4U", "repo": "lewis-carroll-coqlang", "sha": "b1add2a154ac7822ca1f1a56b62a011a889526a0", "save_path": "github-repos/coq/NotBad4U-lewis-carroll-coqlang", "path": "github-repos/coq/NotBad4U-lewis-carroll-coqlang/lewis-carroll-coqlang-b1add2a154ac7822ca1f1a56b62a011a889526a0/lewis.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6644510585346405}}
{"text": "Require Export Coq.Unicode.Utf8.\nRequire Export FOmega.\n\n(******************************************************************************)\n(* Kinding relation                                                           *)\n(******************************************************************************)\n\nInductive Kinding (Γ : Env) : Ty → Kind → Prop :=\n  | K_TVar {X K} :\n      lookup_etvar Γ X K → Kinding Γ (tvar X) K\n  | K_Abs {K1 K2 T2} :\n      Kinding (etvar Γ K1) T2 K2 →\n      Kinding Γ (tabs K1 T2) (karr K1 K2)\n  | K_App {K11 K12 T1 T2} :\n      Kinding Γ T1 (karr K11 K12) → Kinding Γ T2 K11 →\n      Kinding Γ (tapp T1 T2) K12\n  | K_Arr {T1 T2} :\n      Kinding Γ T1 star → Kinding Γ T2 star →\n      Kinding Γ (tarr T1 T2) star\n  | K_All {K1 T2} :\n      Kinding (etvar Γ K1) T2 star →\n      Kinding Γ (tall K1 T2) star.\n\n\n(******************************************************************************)\n(* Type equivalence relation.                                                 *)\n(******************************************************************************)\n\nInductive TyEq (Γ : Env) : Ty → Ty → Kind → Prop :=\n  | Q_Arrow {S1 T1 S2 T2} :\n      TyEq Γ S1 T1 star → TyEq Γ S2 T2 star →\n      TyEq Γ (tarr S1 S2) (tarr T1 T2) star\n  | Q_Abs {K1 K2 S2 T2} :\n      TyEq (etvar Γ K1) S2 T2 K2 →\n      TyEq Γ (tabs K1 S2) (tabs K1 T2) (karr K1 K2)\n  | Q_App {K1 K2 S1 T1 S2 T2} :\n      TyEq Γ S1 T1 (karr K1 K2) → TyEq Γ S2 T2 K1 →\n      TyEq Γ (tapp S1 S2) (tapp T1 T2) K2\n  | Q_All {K1 S2 T2} :\n      TyEq (etvar Γ K1) S2 T2 star →\n      TyEq Γ (tall K1 S2) (tall K1 T2) star\n  | Q_AppAbs {K11 K12 T12 T2} :\n      Kinding (etvar Γ K11) T12 K12 → Kinding Γ T2 K11 →\n      TyEq Γ (tapp (tabs K11 T12) T2) (tsubstTy X0 T2 T12) K12\n  | Q_Refl {T K} :\n      Kinding Γ T K → TyEq Γ T T K\n  | Q_Symm {T S K} :\n      TyEq Γ T S K → TyEq Γ S T K\n  | Q_Trans {S U T K} :\n      TyEq Γ S U K → TyEq Γ U T K → TyEq Γ S T K.\n\n(******************************************************************************)\n(* Typing relation.                                                           *)\n(******************************************************************************)\n\nInductive Typing (Γ : Env) : Tm → Ty → Prop :=\n  | T_Var {y T} :\n      lookup_evar Γ y T → Typing Γ (var y) T\n  | T_Abs {t T1 T2} :\n      Kinding Γ T1 star → Typing (evar Γ T1) t T2 →\n      Typing Γ (abs T1 t) (tarr T1 T2)\n  | T_App {t1 t2 T11 T12} :\n      Typing Γ t1 (tarr T11 T12) → Typing Γ t2 T11 →\n      Typing Γ (app t1 t2) T12\n  | T_TAbs {K t T} :\n      Typing (etvar Γ K) t T →\n      Typing Γ (tyabs K t) (tall K T)\n  | T_TApp {t1 K11 T12 T2} :\n      Typing Γ t1 (tall K11 T12) → Kinding Γ T2 K11 →\n      Typing Γ (tyapp t1 T2) (tsubstTy X0 T2 T12)\n  | T_Eq {t S T} :\n      Typing Γ t S → TyEq Γ S T star →\n      Typing Γ t T.\n\n(******************************************************************************)\n(* Type reduction relation.                                                   *)\n(******************************************************************************)\n\nInductive TRed (Γ : Env) : Ty → Ty → Kind → Prop :=\n  | QR_Var {X K} :\n      lookup_etvar Γ X K →\n      TRed Γ (tvar X) (tvar X) K\n  | QR_Arrow {S1 T1 S2 T2} :\n      TRed Γ S1 T1 star → TRed Γ S2 T2 star →\n      TRed Γ (tarr S1 S2) (tarr T1 T2) star\n  | QR_Abs {S2 T2 K1 K2} :\n      TRed (etvar Γ K1) S2 T2 K2 →\n      TRed Γ (tabs K1 S2) (tabs K1 T2) (karr K1 K2)\n  | QR_App {S1 T1 S2 T2 K1 K2} :\n      TRed Γ S1 T1 (karr K2 K1) → TRed Γ S2 T2 K2 →\n      TRed Γ (tapp S1 S2) (tapp T1 T2) K1\n  | QR_All {K1 S2 T2} :\n      TRed (etvar Γ K1) S2 T2 star →\n      TRed Γ (tall K1 S2) (tall K1 T2) star\n  | QR_AppAbs {S1 T1 S2 T2 K1 K2} :\n      TRed (etvar Γ K2) S1 T1 K1 → TRed Γ S2 T2 K2 →\n      TRed Γ (tapp (tabs K2 S1) S2) (tsubstTy X0 T2 T1) K1.\n\nInductive TRedStar (Γ : Env) : Ty → Ty → Kind → Prop :=\n  | QRS_Nil {T K} :\n      Kinding Γ T K → TRedStar Γ T T K\n  | QRS_Cons {S T U K} :\n      TRedStar Γ S T K → TRed Γ T U K → TRedStar Γ S U K.\n", "meta": {"author": "skeuchel", "repo": "metatheory", "sha": "d0df292cbd764f8afeba088e1c9459f0a4298b47", "save_path": "github-repos/coq/skeuchel-metatheory", "path": "github-repos/coq/skeuchel-metatheory/metatheory-d0df292cbd764f8afeba088e1c9459f0a4298b47/fomega/DeclarationTyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6644510237731834}}
{"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  emulC : e_exp -> e_exp -> e_exp |\n  edivC : e_exp -> e_exp -> 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 \"e1 '* e2\" := (emulC e1 e2) (at level 21, right associativity).\n\n(*** Open Scope e_exp_scope. ***)\n\nLocate \"*\".\nCheck (enumC 4) '* (enumC 5 '+ enumC 6).\n\nNotation \"e1 '/ e2\" := (edivC e1 e2) (at level 21, right associativity).\nCheck (enumC 4) '/ (enumC 4).\n\nCoercion enumC : nat >-> e_exp.\nCoercion evarC : string >-> e_exp.\nDefinition x : string := \"x\".\nDefinition y : string := \"y\".\nDefinition z : string := \"z\".\nDefinition k : string := \"k\".\n\nCheck 4 '* (5 '+ 2).\nCheck (5 '+ 4) '* 8.\nCheck x '- 3.\nCheck 5 '+ 4 '* 5.\n\n\n\n(* Boolean Expression `P'*)\nInductive P_exp := \n  PtrueC : P_exp |\n  PlteC : e_exp -> e_exp -> P_exp |\n  PnegC : P_exp -> P_exp |\n  PandC : P_exp -> P_exp -> P_exp |\n  (*non-necesarry expression*)\n  PfalseC : P_exp |\n  PltC : e_exp -> e_exp -> P_exp |\n  PgtC : e_exp -> e_exp -> P_exp |\n  PgteC : e_exp -> e_exp -> P_exp |\n  PeqC : e_exp -> e_exp -> P_exp |\n  PorC : P_exp -> P_exp -> P_exp |\n  PimpC : P_exp -> P_exp -> P_exp\n.\nPrint P_exp.\n\n(* 33 - 41 *)\nNotation \"''tt'\" := PtrueC (at level 35).\nNotation \"e1 '<= e2\" := (PlteC e1 e2) (at level 33).\nNotation \"'~ P\" := (PnegC P) (at level 36).\nNotation \"P1 '/\\ P2\" := (PandC P1 P2) (at level 37, right associativity).\nNotation \"''ff'\" := PfalseC (at level 35).\nNotation \"e1 '< e2\" := (PltC e1 e2) (at level 33).\nNotation \"e1 '> e2\" := (PgtC e1 e2) (at level 33).\nNotation \"e1 '>= e2\" := (PgteC e1 e2) (at level 33).\nNotation \"e1 '= e2\" := (PeqC e1 e2) (at level 33).\nNotation \"P1 '\\/ P2\" := (PorC P1 P2) (at level 37, right associativity).\nNotation \"P1 '-> P2\" := (PimpC P1 P2) (at level 38, right associativity).\n\nLocate \"'/\\\".\nCheck 'tt '-> 'ff.\nCheck 5 '+ x '>= 5 '-> 3 '> 7.\n\n\n(* Evaluation *)\nDefinition state := string -> nat.\n\n(***\n  Definging the evaluation for expressions is for checking the validation of FOL formulas after \n  transformation. \n***)\n\nFixpoint eval_e_exp (e : e_exp) (st : state) : nat :=  \n(* st maps each var name to a value --- it is a state *)\n  match e with\n  | enumC n => n\n  | evarC s => st s\n  | eplusC e1 e2 => (eval_e_exp e1 st) + (eval_e_exp e2 st)\n  | eminusC e1 e2 => (eval_e_exp e1 st) - (eval_e_exp e2 st)\n  | emulC e1 e2 => (eval_e_exp e1 st) * (eval_e_exp e2 st)\n  | edivC e1 e2 => (eval_e_exp e1 st) / (eval_e_exp e2 st)\n  end.\n\n\nFixpoint eval_P_exp (P : P_exp) (st : state) : Prop :=\n  match P with\n  | PtrueC => True\n  | PlteC e1 e2 => (eval_e_exp e1 st) <= (eval_e_exp e2 st)\n  | PnegC P' => ~ (eval_P_exp P' st)\n  | PandC P1 P2 => (eval_P_exp P1 st) /\\ (eval_P_exp P1 st)\n  | PfalseC => False\n  | PltC e1 e2 => (eval_e_exp e1 st) < (eval_e_exp e2 st)\n  | PgtC e1 e2 => (eval_e_exp e1 st) > (eval_e_exp e2 st)\n  | PgteC e1 e2 => (eval_e_exp e1 st) >= (eval_e_exp e2 st)\n  | PeqC e1 e2 => (eval_e_exp e1 st) = (eval_e_exp e2 st)\n  | PorC P1 P2 => (eval_P_exp P1 st) \\/ (eval_P_exp P1 st)\n  | PimpC P1 P2 => (eval_P_exp P1 st) -> (eval_P_exp P1 st)\n  end.\n\n(* =============== Syntax of Event ===================*)\n\n\n(* Event *)\nInductive EvtElement := \n  sigC : string -> e_exp -> EvtElement | (* Signal *)\n  assC : string -> e_exp -> EvtElement  (* Assignment *)\n.\nCheck EvtElement. \n\nNotation \"s ! e\" := (sigC s e) (at level 45).\nNotation \"x :=' e\" := (assC x e) (at level 45).\n\n(* currently we do not make distinguish between variable and clock names, both are strings*)\nDefinition c : string := \"c\".\nDefinition d : string := \"d\".\nDefinition c1 : string := \"c1\".\nDefinition c2 : string := \"c2\".\nDefinition c3 : string := \"c3\".\nDefinition c4 : string := \"c4\".\n\nCheck x :=' 4.\nCheck c ! (x '+ 4).\n\nDefinition Evt := list EvtElement.\n\nCheck Evt.\nCheck (x :=' 4) :: (c!(x '+ 4)) :: nil.\n\n(* ========================= Syntax of program ========================*)\nInductive SEP_exp : Type := \n  skip : SEP_exp | (* skip program $\\varepsilon$ *)\n  evtC : Evt -> SEP_exp | (* Event *)\n  tstC : P_exp -> Evt -> SEP_exp | (* Test *)\n  seqC : SEP_exp -> SEP_exp -> SEP_exp | (* sequence *)\n  choC : SEP_exp -> SEP_exp -> SEP_exp | (* choice *)\n  loopC : SEP_exp -> SEP_exp (* loop *)\n.\n\n\nNotation \"{ a1 | .. | an }\" := (cons a1 .. (cons an nil) .. ) (at level 45). \nNotation \"@ a\" := (evtC a) (at level 46).\nDefinition idle : Evt := nil.\nNotation \"P ? a\" := (tstC P a) (at level 48).\nNotation \"P1 ; P2\" := (seqC P1 P2) (at level 49, left associativity).\nNotation \"P1 'U' P2\" := (choC P1 P2) (at level 51, left associativity).\nNotation \"P **\" := (loopC P) (at level 47, left associativity).\n\nLocate \"**\".\nCheck x :=' 4 :: nil.\nCheck evtC (x :=' 4 :: nil).\nCheck { x :=' 4 | c1 ! 5}.\nCheck @ { x :=' 4 | c1 ! 5 }.\nCheck idle.\nCheck x '> 0 ? {c!4}.\n\n(* ========================================= Syntax of CDL Formula ===============================================*)\n\n(* ================== CCSL ======================== *)\n(* clock relation *)\n(***\n  Currently, we model clocks as `strings', becuase now we don't need to give its semantics. \n  It won't work anymore if we consider its semantics later.\n***)\n\nInductive CRel := \n  crSubClC : string -> string -> CRel |\n  crExclC : string -> string -> CRel |\n  crPrecC : string -> string -> CRel |\n  crCausC : string -> string -> CRel\n.\nCheck CRel.\n\nNotation \"c1 'sub' c2\" := (crSubClC c1 c2) (at level 52).\nNotation \"c1 # c2\" := (crExclC c1 c2) (at level 52).\nNotation \"c1 << c2\" := (crPrecC c1 c2) (at level 52).\nNotation \"c1 <<= c2\" := (crCausC c1 c2) (at level 52).\n\nCheck c1 << c2.\nCheck c1 # c2.\nCheck c1 sub c2.\n\n(* ================== CDL Formula ======================== *)\n(* Clock relation in formula *)\nInductive rel := \n  rRelC : CRel -> rel |\n  rConjC : list CRel -> rel\n.\nPrint rel.\n\nCoercion rRelC : CRel >-> rel.\nCheck c1 << c2.\n\nNotation \"/\\{ c1 , .. , cn }\" := (rConjC (cons c1 .. (cons cn nil) ..)).\nCheck /\\{ c1 << c2 , c2 sub c3 , c1 <<= c3}.\n\n\n(* Arith Expression `E' *)\n(*DEL\n(* define a map that maps each clock/signal to a variable that records the number it has ticked in history. *)\nDefinition CntClk := string -> string. \n\n(* define a map that maps each clock/signal to a variable that records the current state of this clock. *)\nDefinition StClk := string -> string. \nDEL*)\n\nInductive E_exp :=\n  EvarC : string -> E_exp |\n  ECntClkC : string -> E_exp | (* define a map that maps each clock/signal to a variable that records the number it has ticked in history. *)\n  EStClkC : string -> E_exp | (* define a map that maps each clock/signal to a variable that records the current state of this clock. *)\n  EnumC : nat -> E_exp |\n  EplusC : E_exp -> E_exp -> E_exp |\n  (* unecessary expression *)\n  EmulC : E_exp -> E_exp -> E_exp |\n  EminusC : E_exp -> E_exp -> E_exp |\n  EdivC : E_exp -> E_exp -> E_exp\n.\nPrint E_exp. \n\nCoercion EvarC : string >-> E_exp.\nNotation \"n( c )\" := (ECntClkC c) (at level 52). (* the only DIFFERENCE between e_exp and E_exp *)\nNotation \"s( c )\" := (EStClkC c) (at level 52).\nCoercion EnumC : nat >-> E_exp.\nNotation \"e1 +' e2\" := (EplusC e1 e2) (at level 55, right associativity).\nNotation \"e1 *' e2\" := (EmulC e1 e2) (at level 53, right associativity).\nNotation \"e1 -' e2\" := (EminusC e1 e2) (at level 55, right associativity).\nNotation \"e1 /' e2\" := (EdivC e1 e2) (at level 53, right associativity).\n\nCheck 5 +' 3.\nCheck 5 '+ 3.\nCheck 5 *' (3 +' 5).\nCheck n(c) *' 4.\n\n\n\n\n\n(* CDL Formula *)\nInductive CDL_exp := \n  cdl_trueC : CDL_exp |\n  cdl_ltC : E_exp -> E_exp -> CDL_exp |\n  cdl_box1C : SEP_exp -> rel -> CDL_exp |\n  cdl_box2C : SEP_exp -> CDL_exp -> CDL_exp |\n  cdl_negC : CDL_exp -> CDL_exp |\n  cdl_andC : CDL_exp -> CDL_exp -> CDL_exp |\n  cdl_forallC : string -> CDL_exp -> CDL_exp |\n  (* unnecessary expressions *)\n  cdl_falseC : CDL_exp |\n  cdl_lteC : E_exp -> E_exp -> CDL_exp |\n  cdl_gtC : E_exp -> E_exp -> CDL_exp |\n  cdl_gteC : E_exp -> E_exp -> CDL_exp |\n  cdl_eqC : E_exp -> E_exp -> CDL_exp |\n  cdl_dia1C : SEP_exp -> rel -> CDL_exp |\n  cdl_dia2C : SEP_exp -> CDL_exp -> CDL_exp |\n  cdl_orC : CDL_exp -> CDL_exp -> CDL_exp |\n  cdl_impC : CDL_exp -> CDL_exp -> CDL_exp\n.\n\nNotation \"'tt''\" := cdl_trueC (at level 65).\nNotation \"e1 <' e2\" := (cdl_ltC e1 e2) (at level 61).\nNotation \"[ p ]' r\" := (cdl_box1C p r) (at level 63).\nNotation \"[ p ] e\" := (cdl_box2C p e) (at level 63).\nNotation \"~' e\" := (cdl_negC e) (at level 67).\nNotation \"e1 /\\' e2\" := (cdl_andC e1 e2) (at level 69, right associativity).\nNotation \"'all' x , e\" := (cdl_forallC x e) (at level 68).\n(* unnecessary expressions *)\nNotation \"'ff''\" := cdl_falseC (at level 65).\nNotation \"e1 <=' e2\" := (cdl_lteC e1 e2) (at level 61).\nNotation \"e1 >' e2\" := (cdl_gtC e1 e2) (at level 61).\nNotation \"e1 >=' e2\" := (cdl_gteC e1 e2) (at level 61).\nNotation \"e1 =' e2\" := (cdl_eqC e1 e2) (at level 61).\nNotation \"< p >' r\" := (cdl_dia1C p r) (at level 63).\nNotation \"< p > e\" := (cdl_dia2C p e) (at level 63).\nNotation \"e1 \\/' e2\" := (cdl_orC e1 e2) (at level 71, right associativity).\nNotation \"e1 ->' e2\" := (cdl_impC e1 e2) (at level 72, right associativity).\n\nCheck tt'.\nCheck ff'.\nCheck (5 -' 3) <' 2.\nCheck ([skip]' c1 << c2) /\\' 2 >' 5 /\\' tt'.\nCheck [@ {x :=' 4 | c1 ! 5} ; (x '> 0) ? {c2!4} ; @ idle; skip] n(c) >' 0.\nCheck [(@ {x :=' 4 | c1 ! 5} ; (x '> 0) ? {c2!4} ; @ idle; skip)**]' c1<<c2.\nCheck all x , 4 =' 5.\n\n\n\n\n\n(* ===================================================== CDL Calculus ======================================*)\n(*************************** Auxiliary Functions ***************************)\n(*check if a dynamic formula is a pure FOL formula *)\n\nFixpoint CheckPureFOL (e : CDL_exp) : Prop :=\n  match e with\n  | cdl_trueC => True\n  | cdl_ltC e1 e2 => True\n  | cdl_box1C p r => False\n  | cdl_box2C p e' => False\n  | cdl_negC e' => CheckPureFOL e'\n  | cdl_andC e1 e2 => (CheckPureFOL e1) /\\ (CheckPureFOL e2)\n  | cdl_forallC x e' => (CheckPureFOL e')\n  | cdl_falseC => True\n  | cdl_lteC e1 e2 => True\n  | cdl_gtC e1 e2 => True\n  | cdl_gteC e1 e2 => True\n  | cdl_eqC e1 e2 => True\n  | cdl_dia1C p r => False\n  | cdl_dia2C p e' => False\n  | cdl_orC e1 e2 => (CheckPureFOL e1) /\\ (CheckPureFOL e2)\n  | cdl_impC e1 e2 => (CheckPureFOL e1) /\\ (CheckPureFOL e2)\n  end.\n\n\n\n(* a structure of (true, false, `undefined') *)\nInductive Bool :=\n  bBoolC : Prop -> Bool |\n  bUndefC : Bool\n.\n\nNotation \"[ b ]\" := (bBoolC b) (at level 74).\nNotation \"_|_\" := bUndefC (at level 74).\n\n\n(* evaluate a pure FOL formula in CDL formula *)\n\n\n\n\n(*************************** Rules for FOL **********************************)\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\n(***DEL Definition SequentL : Gamma -> CDL_exp -> Delta -> Prop.*)\n\n\n(* we arrange a place special for the dynamic formula we want to verify in the sequent, other formulas in Gamma\nand Delta are pure FOL formulas. \n\nWe define two types of sequent: sequentL and sequentR, where L and R indicate the verifiying formula is on the left\nor right side of the sequent. \n*)\n\nInductive place := \n  pexpC : CDL_exp -> place |\n  pnothingC : place\n.\n\n(*\nNotation \"/ e /\" := (pexpC e) (at level 74).\nNotation \"/ /\" := pnothingC (at level 74).\nCheck / x <=' y /.\n*)\n\n\nReserved Notation \"T , p1 ==> p2 , D\" (at level 75).\n(*Reserved Notation \"T ==> p , D\" (at level 75).*)\n\nLocate \"==>\".\n\n\n(* substitution /single variable*)\nFixpoint E_exp_subs (e : E_exp) (x' : string) (x : string) : E_exp := \n  match e with\n  | EvarC v => if (string_dec v x) then EvarC x' else EvarC v\n  | ECntClkC c => ECntClkC c (* do not consider replacing a clock-related variable *)\n  | EStClkC c => EStClkC c\n  | EnumC n => EnumC n\n  | EplusC e1 e2 => EplusC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | EmulC e1 e2 => EmulC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | EminusC e1 e2 => EminusC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | EdivC e1 e2 => EdivC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  end\n.\n\nCompute E_exp_subs (x +' y) y x.\nCompute E_exp_subs (x *' z) y c.\nCompute E_exp_subs (n(c) *' z) y z.\n\nFixpoint e_exp_subs (e : e_exp) (x' : string) (x : string) : e_exp :=\n  match e with\n  | enumC n => enumC n\n  | evarC s => if (string_dec s x) then evarC x' else evarC s\n  | eplusC e1 e2 => eplusC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | eminusC e1 e2 => eminusC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | emulC e1 e2 => emulC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | edivC e1 e2 => edivC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  end\n.\n\nFixpoint P_exp_subs (P : P_exp) (x' : string) (x : string) : P_exp :=\n  match P with\n  | PtrueC => PtrueC \n  | PlteC e1 e2 => PlteC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | PnegC P' => PnegC (P_exp_subs P' x' x)\n  | PandC P1 P2 => PandC (P_exp_subs P1 x' x) (P_exp_subs P2 x' x)\n  | PfalseC => PfalseC\n  | PltC e1 e2 => PltC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | PgtC e1 e2 => PgtC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | PgteC e1 e2 => PgteC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | PeqC e1 e2 => PeqC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | PorC P1 P2 => PorC (P_exp_subs P1 x' x) (P_exp_subs P2 x' x)\n  | PimpC P1 P2 => PimpC (P_exp_subs P1 x' x) (P_exp_subs P2 x' x)\n  end\n.\n\nFixpoint cdl_subs (e : CDL_exp) (x' : string) (x : string) : CDL_exp := (* e[x'/x] *)\n  match e with\n  | cdl_trueC => cdl_trueC\n  | cdl_ltC e1 e2 => cdl_ltC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | cdl_box1C p r => cdl_box1C (SEP_subs p x' x) r (* do not consider replacing a clock-related variable *)\n  | cdl_box2C p e' => cdl_box2C (SEP_subs p x' x) (cdl_subs e' x' x)\n  | cdl_negC e' => cdl_negC (cdl_subs e' x' x)\n  | cdl_andC e1 e2 => cdl_andC (cdl_subs e1 x' x) (cdl_subs e2 x' x)\n  | cdl_forallC x1 e' => if (string_dec x1 x) then cdl_forallC x1 e' else (cdl_subs e' x' x) \n  | cdl_falseC => cdl_falseC\n  | cdl_lteC e1 e2 => cdl_lteC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | cdl_gtC e1 e2 => cdl_gtC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | cdl_gteC e1 e2 => cdl_gteC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | cdl_eqC e1 e2 => cdl_eqC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | cdl_dia1C p r => cdl_dia1C (SEP_subs p x' x) r (* do not consider replacing a clock-related variable *)\n  | cdl_dia2C p e' => cdl_dia2C (SEP_subs p x' x) (cdl_subs e' x' x)\n  | cdl_orC e1 e2 => cdl_orC (cdl_subs e1 x' x) (cdl_subs e2 x' x)\n  | cdl_impC e1 e2 => cdl_impC (cdl_subs e1 x' x) (cdl_subs e2 x' x)\n  end.\n\n(*&&&&&&&&&&&&&&&&&&&&&&&&&&&& testing &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*)\n(*** as a test, we firstly implement a simple rule here, to check if everything in my mind would work well, \nwe first realize the rule: \n    T[x'/x],x = e[x'/x] => E, D[x'/x]\n    ---------------------------------\n    T => [x := e] E, D\n\nIt is equavalent to realize the rule:\n    forall x'. (x' not free in T, e, D) -> (T[x'/x],x = e[x'/x] => E, D[x'/x]) -> (T => [x := e] E, D)\n***)\n\n\n\nInductive validSeq : sequent -> Type :=\n  tst : forall (T : Gamma) (p : CDL_exp) (D : Delta), (CheckPureFOL p) -> validSeq ( T ==> p , D ).\n\n", "meta": {"author": "zyr-rekcaha", "repo": "CDL", "sha": "eb9ea66875a709247c23d0ac132e57c8fdee3655", "save_path": "github-repos/coq/zyr-rekcaha-CDL", "path": "github-repos/coq/zyr-rekcaha-CDL/CDL-eb9ea66875a709247c23d0ac132e57c8fdee3655/CDLCalculus-191217-2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6644129316881341}}
{"text": "Require Import Coq.Lists.List.\nRequire Import DschingisKhan.Prelude.PreludeInit.\nRequire Import DschingisKhan.Prelude.PreludeMath.\nRequire Import DschingisKhan.Prelude.PreludeUtil.\nRequire Import DschingisKhan.Prelude.PreludeClassic.\nRequire Import DschingisKhan.Math.BasicPosetTheory.\nRequire Import DschingisKhan.Math.BooleanAlgebra.\nRequire Import DschingisKhan.Logic.PropositionalLogic.\n\nModule ClassicalMetaTheoryOnPropositonalLogic.\n\n  Import ListNotations ExcludedMiddle BooleanAlgebra CountableBooleanAlgebra SyntaxOfPL SemanticsOfPL InferenceRulesOfPL LindenbaumBooleanAlgebraOfPL ConstructiveMetaTheoryOnPropositonalLogic.\n\n  Lemma ByAssumption_preserves (Gamma : ensemble formula) (C : formula)\n    (ELEM : C \\in Gamma)\n    : Gamma ⊧ C.\n  Proof with eauto with *.\n    eapply extend_entails with (Gamma := singleton C)...\n    ii. eapply env_satisfies...\n  Qed.\n\n  Lemma ContradictionI_preserves (Gamma : ensemble formula) (A : formula)\n    (ENTAILS1 : Gamma ⊧ A)\n    (ENTAILS2 : Gamma ⊧ NegationF A)\n    : Gamma ⊧ ContradictionF.\n  Proof with (simpl in *; tauto) || eauto with *.\n    ii. pose proof (ENTAILS1 env env_satisfies) as claim1. pose proof (ENTAILS2 env env_satisfies) as claim2.\n    inversion claim1; subst. inversion claim2; subst. econstructor...\n  Qed.\n\n  Lemma ContradictionE_preserves (Gamma : ensemble formula) (A : formula)\n    (ENTAILS1 : Gamma ⊧ ContradictionF)\n    : Gamma ⊧ A.\n  Proof with (simpl in *; tauto) || eauto with *.\n    ii. pose proof (ENTAILS1 env env_satisfies) as claim1.\n    inversion claim1; subst. econstructor...\n  Qed.\n\n  Lemma NegationI_preserves (Gamma : ensemble formula) (A : formula)\n    (ENTAILS1 : insert A Gamma ⊧ ContradictionF)\n    : Gamma ⊧ NegationF A.\n  Proof with (simpl in *; tauto) || eauto with *.\n    ii. econstructor. simpl. intros EVAL_TO_TRUE.\n    assert (claim1 : forall b : formula, member b (insert A Gamma) -> env `satisfies` b).\n    { intros b. rewrite in_insert_iff. intros [A_eq_b | b_in_Gamma]...\n      subst b. econstructor...\n    }\n    pose proof (ENTAILS1 env claim1) as claim2.\n    inversion claim2; subst...\n  Qed.\n\n  Lemma NegationE_preserves (Gamma : ensemble formula) (A : formula)\n    (ENTAILS1 : insert (NegationF A) Gamma ⊧ ContradictionF)\n    : Gamma ⊧ A.\n  Proof with (simpl in *; tauto) || eauto with *.\n    ii. econstructor. eapply NNPP. intros EVAL_TO_FALSE.\n    assert (claim1 : forall b : formula, member b (insert (NegationF A) Gamma) -> env `satisfies` b).\n    { intros b. rewrite in_insert_iff. intros [NegationF_A_eq_b | b_in_Gamma]...\n      subst b. econstructor...\n    }\n    pose proof (ENTAILS1 env claim1) as claim2.\n    inversion claim2; subst...\n  Qed.\n\n  Lemma ConjunctionI_preserves (Gamma : ensemble formula) (A : formula) (B : formula)\n    (ENTAILS1 : Gamma ⊧ A)\n    (ENTAILS2 : Gamma ⊧ B)\n    : Gamma ⊧ ConjunctionF A B.\n  Proof with (simpl in *; tauto) || eauto with *.\n    ii. pose proof (ENTAILS1 env env_satisfies) as claim1. pose proof (ENTAILS2 env env_satisfies) as claim2.\n    inversion claim1; subst. inversion claim2; subst. econstructor...\n  Qed.\n\n  Lemma ConjunctionE1_preserves (Gamma : ensemble formula) (A : formula) (B : formula)\n    (ENTAILS1 : Gamma ⊧ ConjunctionF A B)\n    : Gamma ⊧ A.\n  Proof with (simpl in *; tauto) || eauto with *.\n    ii. pose proof (ENTAILS1 env env_satisfies) as claim1.\n    inversion claim1; subst. econstructor...\n  Qed.\n\n  Lemma ConjunctionE2_preserves (Gamma : ensemble formula) (A : formula) (B : formula)\n    (ENTAILS1 : Gamma ⊧ ConjunctionF A B)\n    : Gamma ⊧ B.\n  Proof with (simpl in *; tauto) || eauto with *.\n    ii. pose proof (ENTAILS1 env env_satisfies) as claim1.\n    inversion claim1; subst. econstructor...\n  Qed.\n\n  Lemma DisjunctionI1_preserves (Gamma : ensemble formula) (A : formula) (B : formula)\n    (ENTAILS1 : Gamma ⊧ A)\n    : Gamma ⊧ DisjunctionF A B.\n  Proof with (simpl in *; tauto) || eauto with *.\n    ii. pose proof (ENTAILS1 env env_satisfies) as claim1.\n    inversion claim1; subst. econstructor...\n  Qed.\n\n  Lemma DisjunctionI2_preserves (Gamma : ensemble formula) (A : formula) (B : formula)\n    (ENTAILS1 : Gamma ⊧ B)\n    : Gamma ⊧ DisjunctionF A B.\n  Proof with (simpl in *; tauto) || eauto with *.\n    ii. pose proof (ENTAILS1 env env_satisfies) as claim1.\n    inversion claim1; subst. econstructor...\n  Qed.\n\n  Lemma DisjunctionE_preserves (Gamma : ensemble formula) (A : formula) (B : formula) (C : formula)\n    (ENTAILS1 : Gamma ⊧ DisjunctionF A B)\n    (ENTAILS2 : insert A Gamma ⊧ C)\n    (ENTAILS3 : insert B Gamma ⊧ C)\n    : Gamma ⊧ C.\n  Proof with (simpl in *; tauto) || eauto with *.\n    ii. econstructor.\n    pose proof (ENTAILS1 env env_satisfies) as claim1.\n    inversion claim1; subst.\n    destruct EVAL_TO_TRUE as [EVAL_TO_TRUE | EVAL_TO_TRUE].\n    - assert (claim2 : forall b : formula, member b (insert A Gamma) -> env `satisfies` b).\n      { intros b. rewrite in_insert_iff. intros [A_eq_b | b_in_Gamma]...\n        subst b. econstructor...\n      }\n      pose proof (ENTAILS2 env claim2) as claim3.\n      inversion claim3; subst...\n    - assert (claim2 : forall b : formula, member b (insert B Gamma) -> env `satisfies` b).\n      { intros b. rewrite in_insert_iff. intros [B_eq_b | b_in_Gamma]...\n        subst b. econstructor...\n      }\n      pose proof (ENTAILS3 env claim2) as claim3.\n      inversion claim3; subst...\n  Qed.\n\n  Lemma ImplicationI_preserves (Gamma : ensemble formula) (A : formula) (B : formula)\n    (ENTAILS1 : insert A Gamma ⊧ B)\n    : Gamma ⊧ ImplicationF A B.\n  Proof with (simpl in *; tauto) || eauto with *.\n    ii. econstructor. simpl. intros EVAL_TO_TRUE.\n    assert (claim1 : forall b : formula, member b (insert A Gamma) -> env `satisfies` b).\n    { intros b. rewrite in_insert_iff. intros [A_eq_b | b_in_Gamma]...\n      subst b. econstructor...\n    }\n    pose proof (ENTAILS1 env claim1) as claim2.\n    inversion claim2; subst...\n  Qed.\n\n  Lemma ImplicationE_preserves (Gamma : ensemble formula) (A : formula) (B : formula)\n    (ENTAILS1 : Gamma ⊧ ImplicationF A B)\n    (ENTAILS2 : Gamma ⊧ A)\n    : Gamma ⊧ B.\n  Proof with (simpl in *; tauto) || eauto with *.\n    ii. pose proof (ENTAILS1 env env_satisfies) as claim1. inversion claim1; subst.\n    econstructor. simpl in EVAL_TO_TRUE. eapply EVAL_TO_TRUE.\n    pose proof (ENTAILS2 env env_satisfies) as claim2. inversion claim2; subst...\n  Qed.\n\n  Lemma BiconditionalI_preserves (Gamma : ensemble formula) (A : formula) (B : formula)\n    (ENTAILS1 : insert A Gamma ⊧ B)\n    (ENTAILS2 : insert B Gamma ⊧ A)\n    : Gamma ⊧ BiconditionalF A B.\n  Proof with (simpl in *; tauto) || eauto with *.\n    ii. econstructor. simpl. split; intros EVAL_TO_TRUE.\n    - assert (claim1 : forall b : formula, member b (insert A Gamma) -> env `satisfies` b).\n      { intros b. rewrite in_insert_iff. intros [A_eq_b | b_in_Gamma]...\n        subst b. econstructor...\n      }\n      pose proof (ENTAILS1 env claim1) as claim2.\n      inversion claim2; subst...\n    - assert (claim1 : forall b : formula, member b (insert B Gamma) -> env `satisfies` b).\n      { intros b. rewrite in_insert_iff. intros [B_eq_b | b_in_Gamma]...\n        subst b. econstructor...\n      }\n      pose proof (ENTAILS2 env claim1) as claim2.\n      inversion claim2; subst...\n  Qed.\n\n  Lemma BiconditionalE1_preserves (Gamma : ensemble formula) (A : formula) (B : formula)\n    (ENTAILS1 : Gamma ⊧ BiconditionalF A B)\n    (ENTAILS2 : Gamma ⊧ A)\n    : Gamma ⊧ B.\n  Proof with (simpl in *; tauto) || eauto with *.\n    ii. pose proof (ENTAILS1 env env_satisfies) as claim1. inversion claim1; subst.\n    econstructor. simpl in EVAL_TO_TRUE. eapply EVAL_TO_TRUE.\n    pose proof (ENTAILS2 env env_satisfies) as claim2. inversion claim2; subst...\n  Qed.\n\n  Lemma BiconditionalE2_preserves (Gamma : ensemble formula) (A : formula) (B : formula)\n    (ENTAILS1 : Gamma ⊧ BiconditionalF A B)\n    (ENTAILS2 : Gamma ⊧ B)\n    : Gamma ⊧ A.\n  Proof with (simpl in *; tauto) || eauto with *.\n    ii. pose proof (ENTAILS1 env env_satisfies) as claim1. inversion claim1; subst.\n    econstructor. simpl in EVAL_TO_TRUE. eapply EVAL_TO_TRUE.\n    pose proof (ENTAILS2 env env_satisfies) as claim2. inversion claim2; subst...\n  Qed.\n\n  Theorem the_propositional_soundness_theorem (X : ensemble formula) (b : formula)\n    (INFERS : X ⊢ b)\n    : X ⊧ b.\n  Proof with eauto.\n    induction INFERS.\n    - eapply ByAssumption_preserves with (C := C)...\n    - eapply ContradictionI_preserves with (A := A)...\n    - eapply ContradictionE_preserves with (A := A)...\n    - eapply NegationI_preserves with (A := A)...\n    - eapply NegationE_preserves with (A := A)...\n    - eapply ConjunctionI_preserves with (A := A) (B := B)...\n    - eapply ConjunctionE1_preserves with (A := A) (B := B)...\n    - eapply ConjunctionE2_preserves with (A := A) (B := B)...\n    - eapply DisjunctionI1_preserves with (A := A) (B := B)...\n    - eapply DisjunctionI2_preserves with (A := A) (B := B)...\n    - eapply DisjunctionE_preserves with (A := A) (B := B) (C := C)...\n    - eapply ImplicationI_preserves with (A := A) (B := B)...\n    - eapply ImplicationE_preserves with (A := A) (B := B)...\n    - eapply BiconditionalI_preserves with (A := A) (B := B)...\n    - eapply BiconditionalE1_preserves with (A := A) (B := B)...\n    - eapply BiconditionalE2_preserves with (A := A) (B := B)...\n  Qed.\n\n  Lemma hasModelIfConsistent (X : ensemble formula)\n    (CONSISTENT : ~ X ⊢ ContradictionF)\n    : isSubsetOf X (MaximalConsistentSet X) /\\ isStructure (MaximalConsistentSet X).\n  Proof with eauto with *. (* Infinitely grateful for Taeseung's advice! *)\n    revert X CONSISTENT.\n    pose proof (lemma1 := @isSubsetOf_singleton_if formula).\n    assert (lemma2 : forall X : ensemble formula, forall x : formula, isSubsetOf X (insert x X)).\n    { ii; ensemble_rewrite. }\n    pose proof (lemma3 := @isSubsetOf_empty_if formula).\n    assert (lemma4 : forall X : ensemble formula, forall x : formula, member x (insert x X)).\n    { ii; ensemble_rewrite. }\n    ii. set (X_dagger := MaximalConsistentSet X).\n    pose proof (theorem_of_1_3_10 X) as [? ? ? ? ?].\n    fold X_dagger in SUBSET, EQUICONSISTENT, CLOSED_infers, META_DN, IMPLICATION_FAITHFUL.\n    pose proof (theorem_of_1_2_14 (Th X) (lemma1_of_1_3_8 X)) as [SUBSET' IS_FILTER' COMPLETE' EQUICONSISTENT'].\n    fold (MaximalConsistentSet X) in SUBSET', IS_FILTER', COMPLETE', EQUICONSISTENT'.\n    fold X_dagger in SUBSET', IS_FILTER', COMPLETE', EQUICONSISTENT'.\n    pose proof (claim1 := Th_isSubsetOf_cl X).\n    pose proof (claim2 := cl_isSubsetOf_Th X).\n    assert (claim3 : equiconsistent (cl X) X_dagger).\n    { split; intros INCONSISTENT.\n      - eapply inconsistent_compatWith_isSubsetOf with (X := Th X)...\n        rewrite <- cl_eq_Th...\n      - eapply inconsistent_compatWith_isSubsetOf with (X := Th X)...\n        eapply EQUICONSISTENT...\n    }\n    assert (claim4 : ~ inconsistent X_dagger).\n    { intros INCONSISTENT. contradiction CONSISTENT.\n      eapply inconsistent_cl_iff, claim3...\n    }\n    assert (claim5 : ~ inconsistent (cl X_dagger)).\n    { intros INCONSISTENT. contradiction claim4.\n      eapply inconsistent_compatWith_isSubsetOf with (X := cl X_dagger)...\n      eapply fact5_of_1_2_8...\n    }\n    assert (\n      forall i : propLetter,\n      AtomF i \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) (AtomF i)\n    ) as caseAtomF.\n    { ii. change (AtomF i \\in X_dagger <-> i \\in preimage AtomF X_dagger).\n      rewrite in_preimage_iff. split...\n      intros [p [? ?]]; subst p...\n    }\n    assert (\n      ContradictionF \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) ContradictionF\n    ) as caseContradictionF.\n    { simpl. rewrite CLOSED_infers, <- inconsistent_cl_iff. tauto. }\n    assert (\n      forall p1 : formula,\n      forall IH1 : p1 \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) p1,\n      NegationF p1 \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) (NegationF p1)\n    ) as caseNegationF.\n    { ii. simpl. rewrite <- IH1, CLOSED_infers. split.\n      - intros INFERS H_in.\n        contradiction claim5.\n        eapply inconsistent_cl_iff. eapply ContradictionI with (A := p1)...\n        eapply CLOSED_infers...\n      - intros H_not_in.\n        eapply CLOSED_infers, META_DN. unnw. intros H_in.\n        eapply CLOSED_infers. eapply ContradictionI with (A := NegationF p1).\n        + enough (claim6 : MaximalConsistentSet X ⊢ ImplicationF p1 ContradictionF).\n          { eapply NegationI. eapply ImplicationE with (A := p1).\n            - eapply extend_infers...\n            - eapply ByAssumption...\n          }\n          eapply CLOSED_infers, IMPLICATION_FAITHFUL. tauto.\n        + eapply ByAssumption...\n    }\n    assert (\n      forall p1 : formula,\n      forall p2 : formula,\n      forall IH1 : p1 \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) p1,\n      forall IH2 : p2 \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) p2,\n      ConjunctionF p1 p2 \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) (ConjunctionF p1 p2)\n    ) as caseConjunctionF.\n    { ii. simpl. rewrite <- IH1, <- IH2. split.\n      - intros H_in. split.\n        + eapply CLOSED_infers, ConjunctionE1, CLOSED_infers...\n        + eapply CLOSED_infers, ConjunctionE2, CLOSED_infers...\n      - intros [H_in1 H_in2].\n        eapply CLOSED_infers, ConjunctionI; eapply CLOSED_infers...\n    }\n    assert (\n      forall p1 : formula,\n      forall p2 : formula,\n      forall IH1 : p1 \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) p1,\n      forall IH2 : p2 \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) p2,\n      DisjunctionF p1 p2 \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) (DisjunctionF p1 p2)\n    ) as caseDisjunctionF.\n    { ii. simpl. rewrite <- IH1, <- IH2. split.\n      - intros H_in. pose proof (classic (X_dagger ⊢ p1)) as [H_yes | H_no].\n        + left. eapply CLOSED_infers...\n        + right. eapply CLOSED_infers.\n          eapply ImplicationE with (A := NegationF p1).\n          { eapply DisjunctionE with (A := p1) (B := p2) (C := ImplicationF (NegationF p1) p2).\n            - eapply CLOSED_infers...\n            - eapply ImplicationI, ContradictionE. eapply ContradictionI with (A := p1).\n              + eapply ByAssumption. right; left...\n              + eapply ByAssumption. left...\n            - eapply ImplicationI, ByAssumption. right; left...\n          }\n          { eapply CLOSED_infers, caseNegationF...\n            simpl. rewrite <- IH1. intros H_false.\n            apply CLOSED_infers in H_false...\n          }\n      - intros [H_in | H_in].\n        + eapply CLOSED_infers, DisjunctionI1, CLOSED_infers...\n        + eapply CLOSED_infers, DisjunctionI2, CLOSED_infers...\n    }\n    assert (\n      forall p1 : formula,\n      forall p2 : formula,\n      forall IH1 : p1 \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) p1,\n      forall IH2 : p2 \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) p2,\n      ImplicationF p1 p2 \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) (ImplicationF p1 p2)\n    ) as caseImplicationF.\n    { ii. rewrite IMPLICATION_FAITHFUL. simpl. unnw. tauto. }\n    assert (\n      forall p1 : formula,\n      forall p2 : formula,\n      forall IH1 : p1 \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) p1,\n      forall IH2 : p2 \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) p2,\n      BiconditionalF p1 p2 \\in X_dagger <-> evalFormula (preimage AtomF X_dagger) (BiconditionalF p1 p2)\n    ) as caseBiconditionalF.\n    { ii. simpl. transitivity (ImplicationF p1 p2 \\in X_dagger /\\ ImplicationF p2 p1 \\in X_dagger).\n      { split.\n        - intros H_in. split.\n          { eapply CLOSED_infers, ImplicationI. eapply BiconditionalE1 with (A := p1) (B := p2).\n            - eapply extend_infers with (Gamma := X_dagger)...\n              eapply CLOSED_infers...\n            - eapply ByAssumption. left...\n          }\n          { eapply CLOSED_infers, ImplicationI. eapply BiconditionalE2 with (A := p1) (B := p2).\n            - eapply extend_infers with (Gamma := X_dagger)...\n              eapply CLOSED_infers...\n            - eapply ByAssumption. left...\n          }\n        - intros [H_in1 H_in2].\n          eapply CLOSED_infers, BiconditionalI.\n          { eapply ImplicationE with (A := p1).\n            - eapply extend_infers with (Gamma := X_dagger)...\n              eapply CLOSED_infers...\n            - eapply ByAssumption. left...\n          }\n          { eapply ImplicationE with (A := p2).\n            - eapply extend_infers with (Gamma := X_dagger)...\n              eapply CLOSED_infers...\n            - eapply ByAssumption. left...\n          }\n      }\n      { split.\n        - intros [H_in1 H_in2]. eapply caseImplicationF in H_in1, H_in2...\n        - intros [H_in1 H_in2]. eapply caseImplicationF in H_in1, H_in2...\n      }\n    }\n    split.\n    { transitivity (Th X)... ii. econstructor. eapply ByAssumption... }\n    { unfold isStructure. induction A... }\n  Qed.\n\n  Theorem the_propositional_completeness_theorem (Gamma : ensemble formula) (C: formula)\n    (ENTAILS : Gamma ⊧ C)\n    : Gamma ⊢ C.\n  Proof with eauto with *.\n    eapply NNPP. intros it_is_false_that_Gamma_infers_C.\n    set (X := insert (NegationF C) Gamma).\n    assert (CONSISTENT : X ⊬ ContradictionF).\n    { intros INCONSISTENT. contradiction it_is_false_that_Gamma_infers_C. eapply NegationE... }\n    pose proof (theorem_of_1_2_14 (Th X) (lemma1_of_1_3_8 X)) as [SUBSET' IS_FILTER' COMPLETE' EQUICONSISTENT'].\n    fold (MaximalConsistentSet X) in SUBSET', IS_FILTER', COMPLETE', EQUICONSISTENT'.\n    pose proof (hasModelIfConsistent X CONSISTENT) as [INCL IS_STRUCTURE].\n    unfold isStructure in IS_STRUCTURE.\n    pose proof (theorem_of_1_3_10 Gamma) as [? ? ? ? ?]; unnw.\n    contradiction it_is_false_that_Gamma_infers_C.\n    eapply completeness_theorem_prototype with (env := preimage AtomF (MaximalConsistentSet X)); trivial.\n    - unfold equiconsistent in *.\n      transitivity (inconsistent (MaximalConsistentSet X))...\n      split; intros [botBA [botBA_in botBA_eq_falseBA]].\n      + exists (botBA). split... eapply IS_STRUCTURE...\n      + exists (botBA). split... eapply IS_STRUCTURE...\n    - transitivity (MaximalConsistentSet X)...\n      ii. eapply IS_STRUCTURE...\n    - eapply isFilter_compatWith_eqProp...\n  Qed.\n\n  Corollary the_propositional_compactness_theorem (Gamma : ensemble formula) (C : formula)\n    : Gamma ⊧ C <-> << FINITE_ENTAILS : exists xs : list formula, exists X : ensemble formula, isFiniteSubsetOf xs Gamma /\\ isListRepOf xs X /\\ X ⊧ C >>.\n  Proof with eauto.\n    unnw. split.\n    - intros ENTAILS.\n      apply the_propositional_completeness_theorem in ENTAILS.\n      apply inference_is_finite in ENTAILS. des. exists (xs), (X').\n      split... split... eapply the_propositional_soundness_theorem...\n    - des. eapply extend_entails... now firstorder.\n  Qed.\n\nEnd ClassicalMetaTheoryOnPropositonalLogic.\n", "meta": {"author": "KiJeong-Lim", "repo": "DschingisKhan", "sha": "b2d663f5c705f9732d44adc2faf49709b6ddec07", "save_path": "github-repos/coq/KiJeong-Lim-DschingisKhan", "path": "github-repos/coq/KiJeong-Lim-DschingisKhan/DschingisKhan-b2d663f5c705f9732d44adc2faf49709b6ddec07/theories/Math/PropositionalLogicExtra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6644129288717935}}
{"text": "(* 2011_01_22 *)\n\n\n(* 依存積 *)\n(* Prop型 *)\nInductive my_ex (A : Type) (P : A -> Prop) : Prop :=\n| my_ex_intro : forall x : A, P x -> my_ex A P.\nNotation \"'exists' x : A, P\" := (my_ex (fun A (x : A) => P x)) (at level 190).\n\n\n(* 関数型 *)\nInductive my_sig (A : Type) (P : A -> Prop) : Type :=\n| my_exist : forall x : A, P x -> my_sig A P.\nNotation \"{ x : A, P }\" := (my_sig (fun A (x : A) => P x)) (at level 190).\n\n\n\n\n(* 依存和 *)\n(* Prop型 （普通の or） *)\nInductive my_or (A B : Prop) : Prop :=\n| my_or_introl : A -> my_or A B\n| my_or_intror : B -> my_or A B.\nNotation \" A \\/ B \" := (my_or A B).\n\n\n(* 関数型 *)\nInductive my_sumbool (A B : Prop) : Set :=\n| my_left  : A -> my_sumbool A B\n| my_right : B -> my_sumbool A B.\nNotation \"{ A } + { B }\" := (my_sumbool A B).\n\n\n(*\n   sumboolで left と rightタクティクスが使える理由：\n   \n   タクティクス left は、constructor 1\n   タクティクス right は、constructor 2\n   の略記で、それぞれ1番めと2番めのコンストラクタをapplyする。\n   my_right, my_left の順番に書くと\n   タクティクス left が、apply my_right になってしまう。\n*)\n\n\n(********)\n(* 応用 *)\n(********)\n\n\n(* exists n, 0 <= n : Prop\n   と同じものを定義する。\n   ただし、my_ex を使ったわけではない。\n   *)\nInductive my_le_zero : nat -> Prop :=\n| my_le_0 : my_le_zero 0\n| my_le_S : forall n : nat,\n  my_le_zero n -> my_le_zero (S n).\n\n\nGoal my_le_zero 1.                          (* 1 *)\nProof.\n  apply my_le_S.\n  apply my_le_0.\nQed.\n\n\n\n\n(* zerop :\n   {n = 0} + {0 < n} と同じものを定義する\n   *)\nRequire Import Arith.                       (* gt_le_S など *)\nDefinition my_zerop n : my_sumbool (n = 0) (0 < n).\ndestruct n.\napply my_left; apply refl_equal.\napply my_right; change (1 <= S n);\n  apply gt_le_S; change (0 < S n);\n    apply lt_O_Sn.\nDefined.                                    (* Defined *)\n\n\nEval compute in (match my_zerop 1 with\n                   | my_left _ => 0\n                   | my_right _ => 100 end). (* 100 *)\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_ex_sig_sumbool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6644129272246488}}
{"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 Basic_Cons.CCC.\nFrom Categories Require Import Coq_Cats.Coq_Cat.\n\n(*\n**********************************************************\n***************                          *****************\n***************     Prop Category        *****************\n***************                          *****************\n**********************************************************\n*)\n\n\n(* The category of Types in Coq's \"Prop\" universe (Coq's Proposits) *)\n\nProgram Definition Prop_Cat : Category := Coq_Cat Prop.\n\nLocal Hint Extern 1 => contradiction.\n\nProgram Instance False_init : (𝟘_ Prop_Cat)%object := {|terminal := False|}.\n\nLocal Hint Extern 1 => match goal with\n                        |- ?A = ?B :> True => destruct A; destruct B\n                      end.\n\nProgram Instance True_term : (𝟙_ Prop_Cat)%object := {terminal := True}.\n\nLocal Hint Extern 1 => match goal with\n                        |- ?A = ?B :> _ ∧ _ => destruct A; destruct B\n                      end.\n\nLocal Hint Extern 1 => tauto.\n\nSection Prod.\n  Context (P Q : Prop).\n\n  Local Notation \"P × Q\" := (Product Prop_Cat P Q) : object_scope.\n  \n  Program Definition Conj_Product : (P × Q)%object := {|product := (P ∧ Q)|}.\n  \n  Local Obligation Tactic := idtac.\n  \n  Next Obligation. (* Prod_morph_unique *)\n  Proof.\n    intros p' r1 r2 f g H1 H2 H3 H4.\n    rewrite <- H3 in H1.\n    rewrite <- H4 in H2.\n    clear H3 H4.\n    extensionality x.\n    apply (fun p => equal_f p x) in H1; apply (fun p => equal_f p x) in H2.\n    cbn in H1, H2.\n  destruct (f x); destruct (g x); cbn in *; subst; trivial.\n  Qed.\n\nEnd Prod.\n  \nProgram Instance Prop_Cat_Has_Products : Has_Products Prop_Cat := Conj_Product.\n\nLocal Hint Extern 1 => match goal with H : _ ∧ _ |- _ => destruct H end.\n\nSection Exp.\n  Context (P Q : Prop_Cat).\n  \n  Program Definition implication_exp : (P ⇑ Q)%object\n    :=\n      {|\n        exponential := (P -> Q)\n      |}.\n\n  Local Obligation Tactic := idtac.\n  \n  Next Obligation. (* Exp_morph_unique *)\n  Proof.\n    intros z f u u' H1 H2.\n    rewrite H1 in H2; clear H1.\n    extensionality a; extensionality x.\n    apply (fun p => equal_f p (conj a x)) in H2.\n    assumption.\n  Qed.\n\nEnd Exp.\n\nProgram Instance Prop_Cat_Has_Exponentials : Has_Exponentials Prop_Cat :=\n  implication_exp.\n\nProgram Instance Prop_Cat_CCC : CCC Prop_Cat.\n\nLocal Hint Extern 1 => match goal with H : _ ∨ _ |- _ => destruct H end.\n\nSection Sum.\n  Context (P Q : Prop).\n\n  Local Notation \"P + Q\" := (Sum Prop_Cat P Q) : object_scope.\n  \n  Program Definition Disj_Sum  : (P + Q)%object := {|product := (P ∨ Q)|}.\n\n  Local Obligation Tactic := idtac.\n\n  Next Obligation. (* Sum_morph_unique *)\n  Proof.\n    intros p' r1 r2 f g H1 H2 H3 H4.\n    rewrite <- H3 in H1.\n    rewrite <- H4 in H2.\n    clear H3 H4.\n    extensionality x.\n    destruct x as [x1|x2].\n    + apply (fun p => equal_f p x1) in H1; auto.\n    + apply (fun p => equal_f p x2) in H2; auto.\n  Qed.\n  \nEnd Sum.\n\nProgram Instance Prop_Cat_Has_Sums : Has_Sums Prop_Cat := Disj_Sum.\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/Coq_Cats/Prop_Cat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6644129239303588}}
{"text": "Require Import HoTT.\nRequire Export structures basics.\n\nOpen Scope path_scope.\n\nImport Magma2_pr.\n\nSection Product.\n\nDefinition law_prod : forall {G G'}, law G -> law G' -> law (G*G') \n  := fun G G' f g x y => match x,y with \n    | (a,b) , (a',b') => (f a a', g b b')\n    end.\n\nCanonical Structure mag_prod : forall (G G' : magma), magma\n := fun G G' => BuildMagma (G*G') (BuildClass (law_prod gop gop)).\n\nInfix \"*\" := mag_prod.\n\nInstance prod_comm : forall {G}, Commutative G ->\nforall {H}, Commutative H -> Commutative (G * H).\nProof.\nred;intros.\ndestruct x,y. unfold gop;simpl.\napply ap11;[apply ap|];auto.\nDefined.\n\nInstance prod_assoc : forall {G}, Associative G ->\nforall {H}, Associative H -> Associative (G * H).\nProof.\nred;intros.\ndestruct x,y,z. unfold gop;simpl.\napply ap11;[apply ap|];auto.\nDefined.\n\nInstance prod_is_sg : forall G {Hsg : IsSemigroup G}\n H {Hsg' : IsSemigroup H}, IsSemigroup (G * H).\nProof.\nintros.\napply BuildIsSemigroup.\napply prod_assoc. apply Hsg. apply Hsg'.\napply prod_comm. apply Hsg. apply Hsg'.\nDefined.\n\nCanonical Structure prod_sg : forall {G H : semigroup}, semigroup\n  := fun G H => BuildSemigroup (G*H) (prod_is_sg _ _).\n\nInstance prod_is_monoid : forall {G} {Hsg : IsMonoid G}\n {H} {Hsg' : IsMonoid H}, IsMonoid (G * H).\nProof.\nintros. apply BuildIsMonoid. apply _. apply BuildIdentity with (gidV, gidV).\napply left_id_id. red. intros [x x'].\nunfold gop;simpl.\napply ap11;[apply ap|];apply gid_id.\nDefined.\n\nCanonical Structure prod_monoid : forall {G H : monoid}, monoid\n  := fun G H => BuildMonoid (G*H) prod_is_monoid.\n\nLemma prod_Lcancel_pair : forall {G H : magma} (a : G) (b : H), \nLcancel a -> Lcancel b -> Lcancel (a, b).\nProof.\nred;intros.\ndestruct b0;destruct c.\nsimpl in X1. apply equiv_path_prod in X1;simpl in X1.\napply path_prod;simpl;[apply X | apply X0];apply X1.\nDefined.\n\nLemma prod_Rcancel_pair : forall {G H : magma} (a : G) (b : H), \nRcancel a -> Rcancel b -> Rcancel (a, b).\nProof.\nred;intros.\ndestruct b0;destruct c.\nsimpl in X1. apply equiv_path_prod in X1;simpl in X1.\napply path_prod;simpl;[apply X | apply X0];apply X1.\nDefined.\n\nLemma prod_Cancel_pair : forall {G H : magma} (a : G) (b : H), \nCancel a -> Cancel b -> Cancel (a, b).\nProof.\nintros;split;\n[apply prod_Lcancel_pair | apply prod_Rcancel_pair];\nfirst [apply X | apply X0].\nDefined.\n\nInstance prod_is_cmonoid : forall {G} {Hsg : IsCMonoid G}\n {H} {Hsg' : IsCMonoid H}, IsCMonoid (G * H).\nProof.\nintros. apply BuildIsCMonoid. apply _.\nintros; destruct a;apply prod_Cancel_pair;apply cmonoid_cancel.\nDefined.\n\nCanonical Structure prod_cmonoid : forall {G H : Cmonoid}, Cmonoid \n := fun G H => BuildCMonoid (G*H) _.\n\nDefinition prod_apart {A B : Type} (f : A -> B) {C D : Type} (g : C -> D) \n : (A*C) -> (B*D) := fun p => let (a,c) := p in (f a, g c).\n\nInstance prod_linverse : forall {G H : monoid}, \nforall x y : G, Linverse x y -> \nforall x' y' : H, Linverse x' y' -> \nLinverse (x,x') (y,y').\nProof.\nintros;red. unfold gop;simpl.\napply ap11;[apply ap;apply X|apply X0].\nDefined.\n\nInstance prod_rinverse : forall {G H : monoid}, \nforall x y : G, Rinverse x y -> \nforall x' y' : H, Rinverse x' y' -> \nRinverse (x,x') (y,y').\nProof.\nintros. apply prod_linverse;assumption.\nDefined.\n\nInstance prod_inverse : forall {G H : monoid}, \nforall x y : G, IsInverse x y -> \nforall x' y' : H, IsInverse x' y' -> \nIsInverse (x,x') (y,y').\nProof.\nintros;split;[apply prod_linverse | apply prod_rinverse];\nfirst [apply X | apply X0].\nDefined.\n\nInstance prod_is_group : forall {G} {Hsg : IsGroup G}\n {H} {Hsg' : IsGroup H}, IsGroup (G * H).\nProof.\nintros. apply easyIsGroup with prod_is_monoid (prod_apart gopp gopp).\nintros [a b]. simpl. apply prod_inverse;apply gopp_correct.\nDefined.\n\nCanonical Structure prod_group : forall {G H : group}, group\n := fun G H => BuildGroup (G*H) _.\n\n\nCanonical Structure mag2_prod : forall (G G' : magma2), magma2\n := fun G G' => BuildMagma2 (G*G') \n(BuildClass (law_prod radd radd)) (BuildClass (law_prod rmult rmult)).\n\nInfix \"*\" := mag2_prod.\n\nInstance prod_left_distrib : forall {G} (Hg : Ldistributes G)\n {H} (Hh : Ldistributes H), Ldistributes (G*H).\nProof.\nintros;red. intros [a1 a2] [b1 b2] [c1 c2].\nunfold rmult;unfold radd;unfold gop;simpl;\napply ap11;[apply ap;apply Hg|apply Hh].\nDefined.\n\nInstance prod_right_distrib : forall {G} (Hg : Rdistributes G)\n {H} (Hh : Rdistributes H), Rdistributes (G*H).\nProof.\nintros;red. intros [a1 a2] [b1 b2] [c1 c2].\nunfold radd;unfold rmult;unfold gop;simpl;\napply ap11;[apply ap;apply Hg|apply Hh].\nDefined.\n\nInstance prod_distrib : forall {G} (Hg : Distributes G)\n {H} (Hh : Distributes H), Distributes (G*H).\nProof.\nintros;split;[apply prod_left_distrib | apply prod_right_distrib];\nfirst [apply Hg | apply Hh].\nDefined.\n\nInstance prod_is_semiring : forall {G} {Hg : IsSemiring G}\n{H} {Hh : IsSemiring H}, IsSemiring (G*H).\nProof.\nintros. apply BuildIsSemiring.\napply (@prod_is_cmonoid (mag2_add G) _ (mag2_add H) _).\napply (@prod_is_monoid (mag2_mult G) _ (mag2_mult H) _).\napply prod_distrib;apply semiring_distributes.\nDefined.\n\nCanonical Structure prod_semiring : forall {G H : semiring}, semiring\n := fun G H => BuildSemiring (G*H) prod_is_semiring.\n\nInstance prod_is_ring : forall {G} {Hg : IsRing G}\n{H} {Hh : IsRing H}, IsRing (G*H).\nProof.\nintros.\napply easyIsRing. apply prod_is_group.\nchange (IsMonoid (mag_prod (mag2_mult G) (mag2_mult H))).\napply prod_is_monoid.\napply prod_distrib;apply _.\nDefined.\n\nCanonical Structure prod_ring : forall {G H : ring}, ring\n := fun G H => BuildRing (G*H) _.\n\nEnd Product.\n\n\n\n", "meta": {"author": "SkySkimmer", "repo": "HoTT-algebra", "sha": "d5a4627d5d222e0f889591296d84f60234a00daa", "save_path": "github-repos/coq/SkySkimmer-HoTT-algebra", "path": "github-repos/coq/SkySkimmer-HoTT-algebra/HoTT-algebra-d5a4627d5d222e0f889591296d84f60234a00daa/operations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6644039943354274}}
{"text": "From mathcomp Require Import all_ssreflect.\n\n(******************************************************************************)\n(*             Definition of a distance on graph                              *)\n(*   connectn r n x == the set of all the elements connected to x in n steps  *)\n(*                                                                            *)\n(*   `d[t1, t2]_r   == the distance between t1 and t2 in r                    *)\n(*                     if they are not connected returns the cardinal of the  *)\n(*                     the subtype                                            *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection gdist.\n\nVariable T : finType.\nVariable r : rel T.\n\nFixpoint connectn n x :=\n  if n is n1.+1 then \\bigcup_(y in (rgraph r x)) connectn n1 y\n  else [set x].\n\nLemma connectnP n x y :\n  reflect \n    (exists p : seq T, [/\\ path r x p, last x p = y & size p = n])\n    (y \\in connectn n x).\nProof.\nelim: n x y =>  [x y|n IH x y /=].\n  rewrite inE; apply: (iffP idP) => [/eqP->|[[|a l] [] //= _ ->//]].\n  by exists [::].\napply: (iffP idP) => [/bigcupP[i]|[[|i p]//= [H1 H2 H3]]].\n- rewrite [i \\in _]rgraphK => iRk /IH [p [H1 H2 H3]].\n  by exists (i :: p); split; rewrite /= ?(iRk, H3).\n- by [].\ncase/andP: H1 => H11 H12.\nhave F : i \\in rgraph r x by rewrite [_ \\in _]rgraphK. \napply: (subsetP (bigcup_sup _ F)).\nby apply/IH; exists p; split => //; case: H3.\nQed.\n\nDefinition gdist t1 t2 :=\n  find (fun n => t2 \\in connectn n t1) (iota 0 #|T|).\n\nLocal Notation \" `d[ t1 , t2 ] \" := (gdist t1 t2)\n  (format \" `d[ t1 ,  t2 ] \").\n\nLemma gdist_eq0 t1 t2 : (`d[t1, t2] == 0) = (t1 == t2).\nProof.\nhave tG : #|T| > 0 by rewrite (cardD1 t1).\nrewrite /gdist.\ncase: #|_| tG => // n _.\nrewrite (iotaD _ 1) /= inE [t2 == _]eq_sym.\nby case: (t1 =P t2).\nQed.\n\nLemma gdist_gt0 t1 t2 : (0 < `d[t1, t2]) = (t1 != t2).\nProof. by rewrite ltnNge leqn0 gdist_eq0. Qed.\n\nLemma gdist0 t : `d[t, t] = 0.\nProof. by apply/eqP; rewrite gdist_eq0. Qed.\n\nLemma gdist_card_le t1 t2 : `d[t1, t2] <= #|T|.\nProof.\nrewrite -[#|T|](size_iota 0).\napply: find_size.\nQed.\n\nLemma gdist_path_le t1 t2 p :\n  path r t1 p -> last t1 p = t2 -> `d[t1, t2] <= size p.\nProof.\nmove=> Hp Hl.\nhave [tLp|pLt] := leqP #|T| (size p).\n  apply: leq_trans tLp.\n  by apply: gdist_card_le.\nhave F : t2 \\in connectn (size p) t1.\n  by apply/connectnP; exists p.\ncase: leqP => // /(before_find _) // /(_ 0).\nby rewrite seq.nth_iota // F.\nQed.\n\nLemma gdist_connect t1 t2 : connect r t1 t2 = (`d[t1,t2] < #|T|).\nProof.\napply/connectP/idP=> [[p /shortenP[p' Hp' Hu _ Ht]]|].\n  apply: leq_trans (_ : size p' < _).\n    by apply: gdist_path_le.\n  rewrite -[_.+1]/(size (t1 :: p')) cardE.\n  apply: uniq_leq_size => // i.\n  by rewrite mem_enum.\nrewrite -[#|_|](size_iota 0) -has_find.\nmove => /hasP[n _ /connectnP [p [H1p H2p H3p]]].\nby exists p.\nQed.\n\nLemma gdist_nconnect t1 t2 : ~~ connect r t1 t2 -> `d[t1,t2] = #|T|.\nProof.\nmove=> H; apply/eqP.\nhave := gdist_card_le t1 t2.\nby rewrite leq_eqVlt -gdist_connect (negPf H) orbF.\nQed.\n\n(* geodesic path *)\nDefinition gpath t1 t2 p :=\n  [&& path r t1 p, last t1 p == t2 & `d[t1, t2] == size p].\n\nLemma gpathP t1 t2 p :\n  reflect ([/\\ path r t1 p, last t1 p = t2 & `d[t1, t2] = size p])\n          (gpath t1 t2 p).\nProof.\napply: (iffP and3P) => [[t1Pp /eqP t1pLt2 /eqP t1t2D]|\n                        [t1Pp t1pLt2 t1t2D]]; first by split.\nby split => //; apply/eqP.\nQed.\n\nLemma gpath_connect t1 t2 : connect r t1 t2 -> {p | gpath t1 t2 p}.\nProof.\nmove=> t1Ct2.\ncase: (pickP [pred p | gpath t1 t2 (p : `d[t1, t2].-tuple T)]) => [p Hp|HC].\n  by exists p.\nmove: (t1Ct2); rewrite gdist_connect => dLT.\nabsurd False => //.\nmove: (dLT); rewrite -[#|_|](size_iota 0) -has_find.\nmove => /(nth_find 0).\nrewrite -[find _ _]/`d[t1, t2].\nrewrite nth_iota // add0n => /connectnP[p [H1p H2p /eqP H3p]].\nhave /idP[] := HC (Tuple H3p).\nby apply/and3P; split=> //=; apply/eqP=> //; rewrite (eqP H3p).\nQed.\n\nLemma gpath_last t1 t2 p : gpath t1 t2 p -> last t1 p = t2.\nProof. by case/gpathP. Qed.\n\nLemma gpath_dist t1 t2 p : gpath t1 t2 p -> `d[t1, t2] = size p.\nProof. by case/gpathP. Qed.\n\nLemma gpath_path t1 t2 p : gpath t1 t2 p -> path r t1 p.\nProof. by case/gpathP. Qed.\n\nLemma last_take (A : Type) (p : seq A) t t1 j : \n  j <= size p -> last t1 (take j p) = nth t (t1 :: p) j.\nProof.\nelim: p t1 j => [t1 [|] //| a l IH t1 [|j]] //= H.\nby apply: IH.\nQed.\n\n(* ugly proof !! *)\nLemma gpath_uniq t1 t2 p : gpath t1 t2 p ->  uniq (t1 :: p).\nProof.\nmove=> gH; apply/(uniqP t1) => i j iH jH.\nwlog : i j iH jH / i <= j.\n  move=> H; case: (leqP i j) => [iLj|jLi]; first by apply: H.\n  by move=> /(@sym_equal _ _ _) /H->; rewrite // ltnW.\nrewrite leq_eqVlt => /orP[/eqP->//|iLj].\ncase/gpathP : gH  => t1Pp t1pLt2 dt1t2E.\ncase: j jH iLj => j // jH iLj.\ncase: i iH iLj => [_ _ t1E | ] //.\n  pose p1 := drop j.+1 p.\n  have t1Pp1 : path r t1 p1.\n    move: (t1Pp); rewrite -[p](cat_take_drop j.+1) cat_path.\n    rewrite /= in t1E.\n    by rewrite (last_take t1) //= -t1E => /andP[].\n  have t1p1L : last t1 p1 = t2.\n    move: (t1pLt2); rewrite -[p](cat_take_drop j.+1) last_cat.\n    rewrite /= in t1E.\n    by rewrite (last_take t1) //= -t1E.\n  have [] := boolP (`d[t1, t2] <= size p1) => [|/negP[]]; last first.\n    by apply: gdist_path_le.\n  rewrite leqNgt => /negP[]. \n  rewrite size_drop dt1t2E.\n  rewrite /= in t1E.\n  by rewrite -{2}[size p](subnK (_ : j < size p)) // addnS ltnS leq_addr.\nmove=> i iH; rewrite ltnS => iLj nE.\npose p1 := take i.+1 p ++ drop j.+1 p.\nhave [] := boolP (`d[t1, t2] <= size p1) => [|/negP[]].\n  rewrite leqNgt => /negP[].\n  rewrite size_cat size_take size_drop ifT //; last first.\n    by rewrite -ltnS in iLj; apply: leq_trans iLj _.\n  rewrite dt1t2E -{2}[size p](subnK (_ : j < size _)) //.\n  by rewrite addnC ltn_add2l.\napply: gdist_path_le.\n  move: t1Pp; rewrite -[p](cat_take_drop i.+1).\n  rewrite -[drop _ _](cat_take_drop (j - i)) !cat_path.\n  case/and3P => [-> _] /=.\n  rewrite !(last_take t1) /=; last first.\n  - rewrite size_drop -subSS.\n    by apply: leq_sub2r.\n  - by apply: leq_trans iLj _; rewrite ltnW //.\n  rewrite drop_drop addnS subnK; last by rewrite ltnW.\n  congr path.\n  move: (nE) => /= ->.\n  rewrite -[j - i]prednK //.\n  by rewrite /= nth_drop -subnS addnC subnK //.\n  by rewrite subn_gt0.\nrewrite last_cat (last_take t1) // nE.\nby rewrite -t1pLt2 -{3}[p](cat_take_drop j.+1) last_cat (last_take t1).\nQed.\n\n\nLemma gpath_catl t1 t2 p1 p2 : \n   gpath t1 t2 (p1 ++ p2) -> gpath t1 (last t1 p1) p1.\nProof.\nmove=> /gpathP[].\nrewrite cat_path last_cat => /andP[t1Pp1 t1p1LPp2] t1p1Lp2Lt2 dt1t2E.\napply/gpathP; split => //. \nhave : `d[t1, last t1 p1] <= size p1 by rewrite gdist_path_le.\nrewrite leq_eqVlt => /orP[/eqP//|dLSp1].\nhave /gpath_connect[p3 /gpathP[H1 H2 H3]] : \n   connect r t1 (last t1 p1) by apply/connectP; exists p1.\nhave : size (p3 ++ p2) < `d[t1, t2] by rewrite dt1t2E !size_cat -H3 ltn_add2r.\nrewrite ltnNge => /negP[].\napply: gdist_path_le; first by rewrite cat_path H1 // H2.\nby rewrite last_cat H2.\nQed.\n\nLemma gpath_catr t1 t2 p1 p2 : \n   gpath t1 t2 (p1 ++ p2) -> gpath (last t1 p1) t2 p2.\nProof.\nmove=> /gpathP[].\nrewrite cat_path last_cat => /andP[t1Pp1 t1p1LPp2] t1p1Lp2Lt2 dt1t2E.\napply/gpathP; split => //. \nhave : `d[last t1 p1, t2] <= size p2 by rewrite gdist_path_le.\nrewrite leq_eqVlt => /orP[/eqP//|dLSp1].\nhave /gpath_connect[p3 /gpathP[H1 H2 H3]] : \n   connect r (last t1 p1) t2 by apply/connectP; exists p2.\nhave : size (p1 ++ p3) < `d[t1, t2] by rewrite dt1t2E !size_cat -H3 ltn_add2l.\nrewrite ltnNge => /negP[].\napply: gdist_path_le; first by rewrite cat_path H1 andbT.\nby rewrite last_cat.\nQed.\n\nLemma gdist_cat t1 t2 p1 p2 : \n   gpath t1 t2 (p1 ++ p2) -> \n   `d[t1,t2] = `d[t1, last t1 p1] + `d[last t1 p1, t2].\nProof.\nmove=> gH.\nrewrite (gpath_dist gH).\nrewrite (gpath_dist (gpath_catl gH)) (gpath_dist (gpath_catr gH)) //.\nby rewrite size_cat.\nQed. \n\nLemma gpath_consl t1 t2 t3 p :  gpath t1 t2 (t3 :: p) -> `d[t1, t3] = 1.\nProof. by move=> /(@gpath_catl _ _ [::t3]) /= /gpathP[]. Qed.\n\nLemma gpath_consr t1 t2 t3 p : gpath t1 t2 (t3 :: p) -> gpath t3 t2 p.\nProof. by move=> /(@gpath_catr _ _ [::t3]). Qed.\n\nLemma gdist_cons t1 t2 t3 p : \n   gpath t1 t2 (t3 :: p) -> `d[t1,t2] = `d[t3, t2].+1.\nProof.\nmove=> gH.\nby rewrite (@gdist_cat _ _ [::t3] p) // (gpath_consl gH).\nQed. \n\nLemma gdist_triangular t1 t2 t3 : `d[t1, t2] <= `d[t1, t3] + `d[t3, t2].\nProof.\nhave [/gpath_connect[p pH]|/gdist_nconnect->] \n         := boolP (connect r t1 t3); last first.\n  by apply: leq_trans (gdist_card_le _ _) (leq_addr _ _).\nhave [/gpath_connect [p2 p2H] |/gdist_nconnect->] \n         := boolP (connect r t3 t2); last first.\n  by apply: leq_trans (gdist_card_le _ _) (leq_addl _ _).\nrewrite (gpath_dist pH) (gpath_dist p2H) -size_cat.\napply: gdist_path_le.\n  rewrite cat_path (gpath_path pH).\n  by rewrite (gpath_last pH) (gpath_path p2H).\nby rewrite last_cat (gpath_last pH) (gpath_last p2H).\nQed.\n\nLemma gdist1 t1 t2 : r t1 t2 -> `d[t1, t2] = (t1 != t2).\nProof.\nmove=> Hr; apply/eqP.\ncase: (t1 =P t2) => [<-|/eqP HE]; first by rewrite gdist_eq0.\nrewrite eqn_leq -{1}[nat_of_bool _]/(size [::t2]) gdist_path_le /= ?andbT //.\nby case: gdist (gdist_eq0 t1 t2); rewrite (negPf HE) .\nQed.\n\nLemma gdist_succ t1 t2 : \n  0 < `d[t1, t2] < #|T| -> {t3 | r t1 t3 /\\ `d[t3, t2] = `d[t1, t2].-1}.\nProof.\ncase/andP => dP dT.\nmove: dT dP.\nrewrite -gdist_connect => /gpath_connect[[|t3 p] pH].\n  by rewrite (gpath_dist pH).\nexists t3; split.\n  by have /andP[] := gpath_path (@gpath_catl _ _ [::t3] _ pH).\nby rewrite (gdist_cons pH). \nQed.\n\nLemma gdist_neighboor t1 t2 t3 : r t1 t2 ->\n  r t2 t1 -> [|| `d[t2, t3] == `d[t1, t3].-1,\n                 `d[t2, t3] == `d[t1, t3] |\n                 `d[t2, t3] == `d[t1, t3].+1].\nProof.\nmove=> t1Rt2 t2Rt1.\nhave : `d[t1, t3] - `d[t1, t2] <= `d[t2, t3] <= `d[t2, t1] + `d[t1, t3].\n  by rewrite leq_subLR !gdist_triangular.\nrewrite (gdist1 t1Rt2) (gdist1 t2Rt1).\n(do 2 case: eqP) => //= E1 E2; rewrite ?subn0.\n- by rewrite -eqn_leq => /eqP->; rewrite eqxx orbT.\n- case/andP=> E3.\n  rewrite leq_eqVlt => /orP[/eqP->|].\n    by rewrite eqxx !orbT.\n  rewrite ltnS => E4.\n  by rewrite [`d[_, _] == `d[_, _]]eqn_leq E3 E4 orbT.\n- case/andP=> E3.\n  rewrite leq_eqVlt => /orP[/eqP->|].\n    by rewrite eqxx !orbT.\n  case: (`d[t1, t3]) E3 => //= d.\n  rewrite subSS subn0 ltnS => E3 E4.\n  by rewrite [_ == d]eqn_leq E3 E4.\ncase/andP=> E3.\nrewrite leq_eqVlt => /orP[/eqP->|].\n  by rewrite eqxx !orbT.\nrewrite ltnS leq_eqVlt => /orP[/eqP->|].\n  by rewrite eqxx !orbT.\ncase: (`d[t1, t3]) E3 => //= d.\nrewrite subSS subn0 ltnS => E3 E4.\nby rewrite [_ == d]eqn_leq E3 E4.\nQed.\n\nEnd gdist.\n\nNotation \" `d[ t1 , t2 ]_ r \" := (gdist r t1 t2) (at level 10,\n  format \"`d[ t1 ,  t2 ]_ r\").\n\nSection gdistProp.\n\nVariable T : finType.\nVariable r : rel T.\n\nLemma eq_connectn (r1 r2 : rel T) : r1 =2 r2 -> connectn r1 =2 connectn r2.\nProof.\nmove=> r1Er2.\nelim => //= n IH y; apply: eq_big => // i.\nby rewrite ![_ \\in _]rgraphK r1Er2.\nQed.\n\nLemma eq_dist (r1 r2 : rel T) : r1 =2 r2 -> gdist r1 =2 gdist r2.\nProof.\nmove=> r1Er2 t1 t2.\napply: eq_find => n.\nby rewrite (eq_connectn r1Er2).\nQed.\n\nLemma gdist_sym t1 t2 :\n `d[t1, t2]_r  =  `d[t2, t1]_(fun z : T => r^~ z).\nProof.\napply: eq_find => i.\napply/connectnP/connectnP => /= [] [p [H1p H2p H3p]].\n  exists (rev (belast t1 p)); split => //.\n  - by rewrite -H2p rev_path.\n  - rewrite -H2p; case: (p) => //= a p1.\n    by rewrite rev_cons last_rcons.\n  by rewrite size_rev size_belast.\nexists (rev (belast t2 p)); split => //.\n- by rewrite -H2p rev_path.\n- rewrite -H2p; case: (p) => //= a p1.\n  by rewrite rev_cons last_rcons.\nby rewrite size_rev size_belast.\nQed.\n\nLemma gpath_rev t1 t2 p : gpath r t1 t2 p -> gpath (fun z : T => r^~ z) t2 t1 (rev (belast t1 p)).\nProof.\nmove=> /gpathP[H1 H2] H3.\napply/gpathP; split => //.\n- by rewrite -rev_path H2 in H1.\n- case: (p) H2 => //= a p1.\n  by rewrite /= rev_cons last_rcons.\nby rewrite size_rev size_belast -gdist_sym.\nQed.\n\nLemma gdistC t1 t2 : symmetric r -> `d[t1, t2]_r  =  `d[t2, t1]_r.\nProof.\nmove=> rSym; rewrite gdist_sym.\nby apply: eq_dist.\nQed.\n\nLemma eq_gpath (e1 e2 : rel T) t1 t2 c :\n    e1 =2 e2 -> gpath e1 t1 t2 c = gpath e2 t1 t2 c.\nProof.\nby move=> e1Ee2; apply/gpathP/gpathP; rewrite (eq_path e1Ee2) (eq_dist e1Ee2).\nQed.\n\nLemma gpathC t1 t2 p : \n symmetric r -> gpath r t1 t2 p -> gpath r t2 t1 (rev (belast t1 p)).\nProof.\nmove=> hIrr /gpath_rev.\nby rewrite (@eq_gpath _ _ _ _ _ (_ : _ =2 r)).\nQed.\n\nEnd gdistProp.\n", "meta": {"author": "thery", "repo": "hanoi", "sha": "257788b06e7a724e023e2aee2122cb1dcc5c702d", "save_path": "github-repos/coq/thery-hanoi", "path": "github-repos/coq/thery-hanoi/hanoi-257788b06e7a724e023e2aee2122cb1dcc5c702d/gdist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6644039930593811}}
{"text": "Require Import Logic.GeneralLogic.Base.\nRequire Import Logic.MinimumLogic.Syntax.\nRequire Import Logic.MinimumLogic.Semantics.Trivial.\nRequire Import Logic.PropositionalLogic.Syntax.\n\nLocal Open Scope logic_base.\nLocal Open Scope syntax.\nImport PropositionalLanguageNotation.\n\nModule Semantics.\n\nDefinition andp {model: Type} (X: Ensemble model) (Y: Ensemble model): Ensemble model :=\n  fun m => X m /\\ Y m.\n\nDefinition orp {model: Type} (X: Ensemble model) (Y: Ensemble model): Ensemble model :=\n  fun m => X m \\/ Y m.\n\nDefinition falsep {model: Type}: Ensemble model := fun m => False.\n\nEnd Semantics.\n\nClass TrivialPropositionalSemantics (L: Language) {minL: MinimumLanguage L} {pL: PropositionalLanguage L} (MD: Model) (SM: Semantics L MD): Type := {\n  denote_andp: forall x y, Same_set _ (denotation (x && y)) (Semantics.andp (denotation x) (denotation y));\n  denote_orp: forall x y, Same_set _ (denotation (x || y)) (Semantics.orp (denotation x) (denotation y));\n  denote_falsep: Same_set _ (denotation FF) Semantics.falsep\n}.\n\nSection Trivial.\n\nContext {L: Language}\n        {minL: MinimumLanguage L}\n        {pL: PropositionalLanguage L}\n        {MD: Model}\n        {SM: Semantics L MD}\n        {tpSM: TrivialPropositionalSemantics L MD SM}.\n\nLemma sat_andp: forall m x y, m |= x && y <-> (m |= x /\\ m |= y).\nProof.\n  intros; simpl.\n  unfold satisfies.\n  destruct (denote_andp x y).\n  split; auto; [apply H | apply H0].\nQed.\n\nLemma sat_orp: forall m x y, m |= x || y <-> (m |= x \\/ m |= y).\nProof.\n  intros; simpl.\n  unfold satisfies.\n  destruct (denote_orp x y).\n  split; auto; [apply H | apply H0].\nQed.\n\nLemma sat_falsep: forall m, m |= FF <-> False.\nProof.\n  intros; simpl.\n  unfold satisfies.\n  destruct denote_falsep.\n  split; auto; [apply H | apply H0].\nQed.\n\nEnd Trivial.\n", "meta": {"author": "QinxiangCao", "repo": "UnifySL", "sha": "cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d", "save_path": "github-repos/coq/QinxiangCao-UnifySL", "path": "github-repos/coq/QinxiangCao-UnifySL/UnifySL-cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d/PropositionalLogic/Semantics/Trivial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.664403990426585}}
{"text": "Inductive light : Set :=\n  | Blue   : light\n  | Yellow : light\n  | Red    : light\n.\n\n\nDefinition next x :=\n  match x with\n  | Blue   => Yellow\n  | Yellow => Red\n  | Red    => Blue\nend.\n\n\nPrint nat.\n\n(*\nInductive nat : Set :=\n  | O : nat\n  | S : nat -> nat\n.\n*)\n\nCheck (S O).\n\nEval compute in next (next Yellow).\n\n\nTheorem light_cycles : forall (l : light), next (next (next l)) = l.\nProof.\n  intro p.\n  destruct p.\n  simpl.\n  reflexivity.\n  simpl.\n  reflexivity.\n  simpl.\n  reflexivity.\nQed.\n\nRequire Import Arith.\n\nTheorem induction_test' : forall n : nat, n + 0 = n.\nProof.\n  intro p.\n  rewrite plus_comm.\n  simpl.\n  reflexivity.\nQed.\n\n\nTheorem induction_test : forall n : nat, n + 0 = n.\nProof.\n  intro p.\n  induction p.\n    simpl.\n    reflexivity.\n\n    simpl.\n    rewrite IHp.\n    reflexivity.\n\nQed.\n\n\n\n\n\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/ind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.867035758084294, "lm_q1q2_score": 0.6644039897482106}}
{"text": "\n(*\nMacBook-Air:~ billw$ /Applications/CoqIDE_8.4pl5.app/Contents/Resources/bin/coqtop\nWelcome to Coq 8.4pl5 (October 2014)\n\nCoq < Section Socrates.\n\nCoq < Variables A B C : Prop.\nA is assumed\nB is assumed\nC is assumed\n\nCoq < Goal (A -> B) /\\ (C -> A) -> (C -> B).\n1 subgoal\n\n  A : Prop\n  B : Prop\n  C : Prop\n  ============================\n   (A -> B) /\\ (C -> A) -> C -> B\n\nUnnamed_thm < intro H.\n1 subgoal\n\n  A : Prop\n  B : Prop\n  C : Prop\n  H : (A -> B) /\\ (C -> A)\n  ============================\n   C -> B\n\nUnnamed_thm < intro HA.\n1 subgoal\n\n  A : Prop\n  B : Prop\n  C : Prop\n  H : (A -> B) /\\ (C -> A)\n  HA : C\n  ============================\n   B\n\nUnnamed_thm < apply H.\n1 subgoal\n\n  A : Prop\n  B : Prop\n  C : Prop\n  H : (A -> B) /\\ (C -> A)\n  HA : C\n  ============================\n   A\n\nUnnamed_thm < apply H.\n1 subgoal\n\n  A : Prop\n  B : Prop\n  C : Prop\n  H : (A -> B) /\\ (C -> A)\n  HA : C\n  ============================\n   C\n\nUnnamed_thm < exact HA.\nNo more subgoals.\n\nUnnamed_thm < Qed.\nintro H.\nintro HA.\napply H.\napply H.\nexact HA.\n\nUnnamed_thm is defined\n\nCoq <\n*)\n\nSection Socrates.\nVariables A B C : Prop.\nGoal (A -> B) /\\ (C -> A) -> (C -> B).\nintro H.\nintro HA.\napply H.\napply H.\nexact HA.\nQed.\n", "meta": {"author": "billwestfall", "repo": "coq_ide", "sha": "a2985a04f37f9c1c6f23799d543fdb862792d54b", "save_path": "github-repos/coq/billwestfall-coq_ide", "path": "github-repos/coq/billwestfall-coq_ide/coq_ide-a2985a04f37f9c1c6f23799d543fdb862792d54b/008chapt/socrates.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.7662936430859598, "lm_q1q2_score": 0.6644039805334244}}
{"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 tuple finfun bigop ssralg poly polydiv.\nFrom mathcomp\nRequire Import finset fingroup morphism quotient perm action zmodp cyclic.\nFrom mathcomp\nRequire Import matrix mxalgebra vector falgebra fieldext separable.\n\n(******************************************************************************)\n(* This file develops some basic Galois field theory, defining:               *)\n(* splittingFieldFor K p E <-> E is the smallest field over K that splits p   *)\n(*                           into linear factors.                             *)\n(*            kHom K E f <=> f : 'End(L) is a ring morphism on E and fixes K. *)\n(*            kAut K E f <=> f : 'End(L) is a kHom K E and f @: E == E.       *)\n(*    kHomExtend E f x y == a kHom K <<E; x>> that extends f and maps x to y, *)\n(*                          when f \\is a kHom K E and root (minPoly E x) y.   *)\n(*                                                                            *)\n(* splittingFieldFor K p E <-> E is splitting field for p over K: p splits in *)\n(*                           E and its roots generate E from K.               *)\n(*   splittingFieldType F == the interface type of splitting field extensions *)\n(*                           of F, that is, extensions generated by all the   *)\n(*                           algebraic roots of some polynomial, or,          *)\n(*                           equivalently, normal field extensions of F.      *)\n(* SplittingField.axiom F L == the axiom stating that L is a splitting field. *)\n(* SplittingFieldType F L FsplitL == packs a proof FsplitL of the splitting   *)\n(*                           field axiom for L into a splitingFieldType F,    *)\n(*                           provided L has a fieldExtType F structure.       *)\n(* [splittingFieldType F of L] == a clone of the canonical splittingFieldType *)\n(*                           structure for L.                                 *)\n(*[splittingFieldType F of L for M] == an L-clone of the canonical            *)\n(*                           splittingFieldType structure on M.               *)\n(*                                                                            *)\n(*              gal_of E == the group_type of automorphisms of E over the     *)\n(*                          base field F.                                     *)\n(*           'Gal(E / K) == the group of automorphisms of E that fix K.       *)\n(*          fixedField s == the field fixed by the set of automorphisms s.    *)\n(*                          fixedField set0 = E when set0 : {set: gal_of E}   *)\n(*      normalField K E <=> E is invariant for every 'Gal(L / K) for every L. *)\n(*           galois K E <=> E is a normal and separable field extension of K. *)\n(*        galTrace K E a == \\sum_(f in 'Gal(E / K)) (f a).                    *)\n(*         galNorm K E a == \\prod_(f in 'Gal(E / K)) (f a).                   *)\n(*                                                                            *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nReserved Notation \"''Gal' ( A / B )\"\n  (at level 8, A at level 35, format \"''Gal' ( A  /  B )\").\n\nImport GroupScope GRing.Theory.\nLocal Open Scope ring_scope.\n\nSection SplittingFieldFor.\n\nVariables (F : fieldType) (L : fieldExtType F).\n\nDefinition splittingFieldFor (U : {vspace L}) (p : {poly L}) (V : {vspace L}) :=\n  exists2 rs, p %= \\prod_(z <- rs) ('X - z%:P) & <<U & rs>>%VS = V.\n\nLemma splittingFieldForS (K M E : {subfield L}) p :\n    (K <= M)%VS -> (M <= E)%VS ->\n  splittingFieldFor K p E -> splittingFieldFor M p E.\nProof.\nmove=> sKM sKE [rs Dp genL]; exists rs => //; apply/eqP.\nrewrite eqEsubv -[in X in _ && (X <= _)%VS]genL adjoin_seqSl // andbT.\nby apply/Fadjoin_seqP; split; rewrite // -genL; apply: seqv_sub_adjoin.\nQed.\n\nEnd SplittingFieldFor.\n\nSection kHom.\n\nVariables (F : fieldType) (L : fieldExtType F).\nImplicit Types (U V : {vspace L}) (K E : {subfield L}) (f g : 'End(L)).\n\nDefinition kHom U V f := ahom_in V f && (U <= fixedSpace f)%VS.\n\nLemma kHomP {K V f} :\n  reflect [/\\ {in V &, forall x y, f (x * y) = f x * f y}\n            & {in K, forall x, f x = x}]\n          (kHom K V f).\nProof.\napply: (iffP andP) => [[/ahom_inP[fM _] /subvP idKf] | [fM idKf]].\n  by split=> // x /idKf/fixedSpaceP.\nsplit; last by apply/subvP=> x /idKf/fixedSpaceP.\nby apply/ahom_inP; split=> //; rewrite idKf ?mem1v.\nQed.\n\nLemma kAHomP {U V} {f : 'AEnd(L)} :\n  reflect {in U, forall x, f x = x} (kHom U V f).\nProof. by rewrite /kHom ahomWin; apply: fixedSpacesP. Qed.\n\nLemma kHom1 U V : kHom U V \\1.\nProof. by apply/kAHomP => u _; rewrite lfunE. Qed.\n\nLemma k1HomE V f : kHom 1 V f = ahom_in V f.\nProof. by apply: andb_idr => /ahom_inP[_ f1]; apply/fixedSpaceP. Qed.\n\nLemma kHom_lrmorphism (f : 'End(L)) : reflect (lrmorphism f) (kHom 1 {:L} f).\nProof. by rewrite k1HomE; apply: ahomP. Qed.\n\nLemma k1AHom V (f : 'AEnd(L)) : kHom 1 V f.\nProof. by rewrite k1HomE ahomWin. Qed.\n\nLemma kHom_poly_id K E f p :\n  kHom K E f -> p \\is a polyOver K -> map_poly f p = p.\nProof.\nby case/kHomP=> _ idKf /polyOverP Kp; apply/polyP=> i; rewrite coef_map /= idKf.\nQed.\n\nLemma kHomSl U1 U2 V f : (U1 <= U2)%VS -> kHom U2 V f -> kHom U1 V f.\nProof. by rewrite /kHom => sU12 /andP[-> /(subv_trans sU12)]. Qed.\n\nLemma kHomSr K V1 V2 f : (V1 <= V2)%VS -> kHom K V2 f -> kHom K V1 f.\nProof. by move/subvP=> sV12 /kHomP[/(sub_in2 sV12)fM idKf]; apply/kHomP. Qed.\n\nLemma kHomS K1 K2 V1 V2 f :\n  (K1 <= K2)%VS -> (V1 <= V2)%VS -> kHom K2 V2 f -> kHom K1 V1 f.\nProof. by move=> sK12 sV12 /(kHomSl sK12)/(kHomSr sV12). Qed.\n\nLemma kHom_eq K E f g :\n  (K <= E)%VS -> {in E, f =1 g} -> kHom K E f = kHom K E g.\nProof.\nmove/subvP=> sKE eq_fg; wlog suffices: f g eq_fg / kHom K E f -> kHom K E g.\n  by move=> IH; apply/idP/idP; apply: IH => x /eq_fg.\ncase/kHomP=> fM idKf; apply/kHomP.\nby split=> [x y Ex Ey | x Kx]; rewrite -!eq_fg ?fM ?rpredM // ?idKf ?sKE.\nQed.\n\nLemma kHom_inv K E f : kHom K E f -> {in E, {morph f : x / x^-1}}.\nProof.\ncase/kHomP=> fM idKf x Ex.\ncase (eqVneq x 0) => [-> | nz_x]; first by rewrite linear0 invr0 linear0.\nhave fxV: f x * f x^-1 = 1 by rewrite -fM ?rpredV ?divff // idKf ?mem1v.\nhave Ufx: f x \\is a GRing.unit by apply/unitrPr; exists (f x^-1).\nby apply: (mulrI Ufx); rewrite divrr.\nQed.\n\nLemma kHom_dim K E f : kHom K E f -> \\dim (f @: E) = \\dim E.\nProof.\nmove=> homKf; have [fM idKf] := kHomP homKf.\napply/limg_dim_eq/eqP; rewrite -subv0; apply/subvP=> v.\nrewrite memv_cap memv0 memv_ker => /andP[Ev]; apply: contraLR => nz_v.\nby rewrite -unitfE unitrE -(kHom_inv homKf) // -fM ?rpredV ?divff ?idKf ?mem1v.\nQed.\n\nLemma kHom_is_rmorphism K E f :\n  kHom K E f -> rmorphism (f \\o vsval : subvs_of E -> L).\nProof.\ncase/kHomP=> fM idKf; split=> [a b|]; first exact: raddfB.\nby split=> [a b|] /=; [rewrite /= fM ?subvsP | rewrite algid1 idKf // mem1v].\nQed.\nDefinition kHom_rmorphism K E f homKEf :=\n  RMorphism (@kHom_is_rmorphism K E f homKEf).\n\nLemma kHom_horner K E f p x :\n  kHom K E f -> p \\is a polyOver E -> x \\in E -> f p.[x] = (map_poly f p).[f x].\nProof.\nmove=> homKf /polyOver_subvs[{p}p -> Ex]; pose fRM := kHom_rmorphism homKf.\nby rewrite (horner_map _ _ (Subvs Ex)) -[f _](horner_map fRM) map_poly_comp.\nQed.\n\nLemma kHom_root K E f p x :\n    kHom K E f -> p \\is a polyOver E -> x \\in E -> root p x ->\n  root (map_poly f p) (f x).\nProof.\nby move/kHom_horner=> homKf Ep Ex /rootP px0; rewrite /root -homKf ?px0 ?raddf0.\nQed.\n\nLemma kHom_root_id K E f p x :\n   (K <= E)%VS -> kHom K E f -> p \\is a polyOver K -> x \\in E -> root p x ->\n  root p (f x).\nProof.\nmove=> sKE homKf Kp Ex /(kHom_root homKf (polyOverSv sKE Kp) Ex).\nby rewrite (kHom_poly_id homKf).\nQed.\n\nSection kHomExtend.\n\nVariables (K E : {subfield L}) (f : 'End(L)) (x y : L).\n\nFact kHomExtend_subproof :\n  linear (fun z => (map_poly f (Fadjoin_poly E x z)).[y]).\nProof.\nmove=> k a b; rewrite linearP /= raddfD hornerE; congr (_ + _).\nrewrite -[rhs in _ = rhs]mulr_algl -hornerZ /=; congr _.[_].\nby apply/polyP => i; rewrite !(coefZ, coef_map) /= !mulr_algl linearZ.\nQed.\nDefinition kHomExtend := linfun (Linear kHomExtend_subproof).\n\nLemma kHomExtendE z : kHomExtend z = (map_poly f (Fadjoin_poly E x z)).[y].\nProof. by rewrite lfunE. Qed.\n\nHypotheses (sKE : (K <= E)%VS) (homKf : kHom K E f).\nLocal Notation Px := (minPoly E x).\nHypothesis fPx_y_0 : root (map_poly f Px) y.\n\nLemma kHomExtend_id z : z \\in E -> kHomExtend z = f z.\nProof. by move=> Ez; rewrite kHomExtendE Fadjoin_polyC ?map_polyC ?hornerC. Qed.\n\nLemma kHomExtend_val : kHomExtend x = y.\nProof.\nhave fX: map_poly f 'X = 'X by rewrite (kHom_poly_id homKf) ?polyOverX.\nhave [Ex | E'x] := boolP (x \\in E); last first.\n  by rewrite kHomExtendE Fadjoin_polyX // fX hornerX.\nhave:= fPx_y_0; rewrite (minPoly_XsubC Ex) raddfB /= map_polyC fX root_XsubC /=.\nby rewrite (kHomExtend_id Ex) => /eqP->.\nQed.\n\nLemma kHomExtend_poly p :\n  p \\in polyOver E -> kHomExtend p.[x] = (map_poly f p).[y].\nProof.\nmove=> Ep; rewrite kHomExtendE (Fadjoin_poly_mod x) //.\nrewrite (divp_eq (map_poly f p) (map_poly f Px)).\nrewrite !hornerE (rootP fPx_y_0) mulr0 add0r.\nhave [p1 ->] := polyOver_subvs Ep.\nhave [Px1 ->] := polyOver_subvs (minPolyOver E x).\nby rewrite -map_modp -!map_poly_comp (map_modp (kHom_rmorphism homKf)).\nQed.\n\nLemma kHomExtendP : kHom K <<E; x>> kHomExtend.\nProof.\nhave [fM idKf] := kHomP homKf.\napply/kHomP; split=> [|z Kz]; last by rewrite kHomExtend_id ?(subvP sKE) ?idKf.\nmove=> _ _ /Fadjoin_polyP[p Ep ->] /Fadjoin_polyP[q Eq ->].\nrewrite -hornerM !kHomExtend_poly ?rpredM // -hornerM; congr _.[_].\napply/polyP=> i; rewrite coef_map !coefM /= linear_sum /=.\nby apply: eq_bigr => j _; rewrite !coef_map /= fM ?(polyOverP _).\nQed.\n\nEnd kHomExtend.\n\nDefinition kAut U V f := kHom U V f && (f @: V == V)%VS.\n\nLemma kAutE K E f : kAut K E f = kHom K E f && (f @: E <= E)%VS.\nProof.\napply/andP/andP=> [[-> /eqP->] // | [homKf EfE]].\nby rewrite eqEdim EfE /= (kHom_dim homKf).\nQed.\n\nLemma kAutS U1 U2 V f : (U1 <= U2)%VS -> kAut U2 V f -> kAut U1 V f.\nProof. by move=> sU12 /andP[/(kHomSl sU12)homU1f EfE]; apply/andP. Qed.\n\nLemma kHom_kAut_sub K E f : kAut K E f -> kHom K E f. Proof. by case/andP. Qed.\n\nLemma kAut_eq K E (f g : 'End(L)) :\n  (K <= E)%VS -> {in E, f =1 g} -> kAut K E f = kAut K E g.\nProof.\nby move=> sKE eq_fg; rewrite !kAutE (kHom_eq sKE eq_fg) (eq_in_limg eq_fg).\nQed.\n\nLemma kAutfE K f : kAut K {:L} f = kHom K {:L} f.\nProof. by rewrite kAutE subvf andbT. Qed.\n\nLemma kAut1E E (f : 'AEnd(L)) : kAut 1 E f = (f @: E <= E)%VS.\nProof. by rewrite kAutE k1AHom. Qed.\n\nLemma kAutf_lker0 K f : kHom K {:L} f -> lker f == 0%VS.\nProof.\nmove/(kHomSl (sub1v _))/kHom_lrmorphism=> fM.\nby apply/lker0P; apply: (fmorph_inj (RMorphism fM)).\nQed.\n\nLemma inv_kHomf K f : kHom K {:L} f -> kHom K {:L} f^-1.\nProof.\nmove=> homKf; have [[fM idKf] kerf0] := (kHomP homKf, kAutf_lker0 homKf).\nhave f1K: cancel f^-1%VF f by apply: lker0_lfunVK.\napply/kHomP; split=> [x y _ _ | x Kx]; apply: (lker0P kerf0).\n  by rewrite fM ?memvf ?{1}f1K.\nby rewrite f1K idKf.\nQed.\n\nLemma inv_is_ahom (f : 'AEnd(L)) : ahom_in {:L} f^-1.\nProof.\nhave /ahomP/kHom_lrmorphism hom1f := valP f.\nexact/ahomP/kHom_lrmorphism/inv_kHomf.\nQed.\n\nCanonical inv_ahom (f : 'AEnd(L)) : 'AEnd(L) := AHom (inv_is_ahom f).\nNotation \"f ^-1\" := (inv_ahom f) : lrfun_scope.\n\nLemma comp_kHom_img K E f g :\n  kHom K (g @: E) f -> kHom K E g -> kHom K E (f \\o g).\nProof.\nmove=> /kHomP[fM idKf] /kHomP[gM idKg]; apply/kHomP; split=> [x y Ex Ey | x Kx].\n  by rewrite !lfunE /= gM // fM ?memv_img.\nby rewrite lfunE /= idKg ?idKf.\nQed.\n\nLemma comp_kHom K E f g : kHom K {:L} f -> kHom K E g -> kHom K E (f \\o g).\nProof. by move/(kHomSr (subvf (g @: E))); apply: comp_kHom_img. Qed.\n\nLemma kHom_extends K E f p U :\n    (K <= E)%VS -> kHom K E f ->\n     p \\is a polyOver K -> splittingFieldFor E p U ->\n  {g | kHom K U g & {in E, f =1 g}}.\nProof.\nmove=> sKE homEf Kp /sig2_eqW[rs Dp <-{U}].\nset r := rs; have rs_r: all (mem rs) r by apply/allP.\nelim: r rs_r => [_|z r IHr /=/andP[rs_z rs_r]] /= in E f sKE homEf *.\n  by exists f; rewrite ?Fadjoin_nil.\nset Ez := <<E; z>>%AS; pose fpEz := map_poly f (minPoly E z).\nsuffices{IHr} /sigW[y fpEz_y]: exists y, root fpEz y.\n  have homEz_fz: kHom K Ez (kHomExtend E f z y) by apply: kHomExtendP.\n  have sKEz: (K <= Ez)%VS := subv_trans sKE (subv_adjoin E z).\n  have [g homGg Dg] := IHr rs_r _ _ sKEz homEz_fz.\n  exists g => [|x Ex]; first by rewrite adjoin_cons.\n  by rewrite -Dg ?subvP_adjoin // kHomExtend_id.\nhave [m DfpEz]: {m | fpEz %= \\prod_(w <- mask m rs) ('X - w%:P)}.\n  apply: dvdp_prod_XsubC; rewrite -(eqp_dvdr _ Dp) -(kHom_poly_id homEf Kp).\n  have /polyOver_subvs[q Dq] := polyOverSv sKE Kp.\n  have /polyOver_subvs[qz Dqz] := minPolyOver E z.\n  rewrite /fpEz Dq Dqz -2?{1}map_poly_comp (dvdp_map (kHom_rmorphism homEf)).\n  rewrite -(dvdp_map [rmorphism of @vsval _ _ E]) -Dqz -Dq.\n  by rewrite minPoly_dvdp ?(polyOverSv sKE) // (eqp_root Dp) root_prod_XsubC.\nexists (mask m rs)`_0; rewrite (eqp_root DfpEz) root_prod_XsubC mem_nth //.\nrewrite -ltnS -(size_prod_XsubC _ id) -(eqp_size DfpEz).\nrewrite size_poly_eq -?lead_coefE ?size_minPoly // (monicP (monic_minPoly E z)).\nby have [_ idKf] := kHomP homEf; rewrite idKf ?mem1v ?oner_eq0.\nQed.\n\nEnd kHom.\n\nNotation \"f ^-1\" := (inv_ahom f) : lrfun_scope.\n\nArguments kHomP {F L K V f}.\nArguments kAHomP {F L U V f}.\nArguments kHom_lrmorphism {F L f}.\n\nModule SplittingField.\n\nImport GRing.\n\nSection ClassDef.\n\nVariable F : fieldType.\n\nDefinition axiom (L : fieldExtType F) :=\n  exists2 p : {poly L}, p \\is a polyOver 1%VS & splittingFieldFor 1 p {:L}.\n\nRecord class_of (L : Type) : Type :=\n  Class {base : FieldExt.class_of F L; _ : axiom (FieldExt.Pack _ base)}.\nLocal Coercion base : class_of >-> FieldExt.class_of.\n\nStructure type (phF : phant F) := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (phF : phant F) (T : Type) (cT : type phF).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\nLet xT := let: Pack T _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition clone c of phant_id class c := @Pack phF T c.\n\nDefinition pack b0 (ax0 : axiom (@FieldExt.Pack F (Phant F) T b0)) :=\n fun bT b & phant_id (@FieldExt.class F phF bT) b =>\n fun   ax & phant_id ax0 ax => Pack (Phant F) (@Class T b ax).\n\nDefinition eqType := @Equality.Pack cT xclass.\nDefinition choiceType := @Choice.Pack cT xclass.\nDefinition zmodType := @Zmodule.Pack cT xclass.\nDefinition ringType := @Ring.Pack cT xclass.\nDefinition unitRingType := @UnitRing.Pack cT xclass.\nDefinition comRingType := @ComRing.Pack cT xclass.\nDefinition comUnitRingType := @ComUnitRing.Pack cT xclass.\nDefinition idomainType := @IntegralDomain.Pack cT xclass.\nDefinition fieldType := @Field.Pack cT xclass.\nDefinition lmodType := @Lmodule.Pack F phF cT xclass.\nDefinition lalgType := @Lalgebra.Pack F phF cT xclass.\nDefinition algType := @Algebra.Pack F phF cT xclass.\nDefinition unitAlgType := @UnitAlgebra.Pack F phF cT xclass.\nDefinition vectType := @Vector.Pack F phF cT xclass.\nDefinition FalgType := @Falgebra.Pack F phF cT xclass.\nDefinition fieldExtType := @FieldExt.Pack F phF cT xclass.\n\nEnd ClassDef.\n\nModule Exports.\n\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion base : class_of >-> FieldExt.class_of.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion unitRingType : type >-> UnitRing.type.\nCanonical unitRingType.\nCoercion comRingType : type >-> ComRing.type.\nCanonical comRingType.\nCoercion comUnitRingType : type >-> ComUnitRing.type.\nCanonical comUnitRingType.\nCoercion idomainType : type >-> IntegralDomain.type.\nCanonical idomainType.\nCoercion fieldType : type >-> Field.type.\nCanonical fieldType.\nCoercion lmodType : type >-> Lmodule.type.\nCanonical lmodType.\nCoercion lalgType : type >-> Lalgebra.type.\nCanonical lalgType.\nCoercion algType : type >-> Algebra.type.\nCanonical algType.\nCoercion unitAlgType : type >-> UnitAlgebra.type.\nCanonical unitAlgType.\nCoercion vectType : type >-> Vector.type.\nCanonical vectType.\nCoercion FalgType : type >-> Falgebra.type.\nCanonical FalgType.\nCoercion fieldExtType : type >-> FieldExt.type.\nCanonical fieldExtType.\n\nNotation splittingFieldType F := (type (Phant F)).\nNotation SplittingFieldType F L ax := (@pack _ (Phant F) L _ ax _ _ id _ id).\nNotation \"[ 'splittingFieldType' F 'of' L 'for' K ]\" :=\n  (@clone _ (Phant F) L K _ idfun)\n  (at level 0, format \"[ 'splittingFieldType'  F  'of'  L  'for'  K ]\")\n  : form_scope.\nNotation \"[ 'splittingFieldType' F 'of' L ]\" :=\n  (@clone _ (Phant F) L _ _ id)\n  (at level 0, format \"[ 'splittingFieldType'  F  'of'  L ]\") : form_scope.\n\nEnd Exports.\nEnd SplittingField.\nExport SplittingField.Exports.\n\nLemma normal_field_splitting (F : fieldType) (L : fieldExtType F) :\n  (forall (K : {subfield L}) x,\n    exists r, minPoly K x == \\prod_(y <- r) ('X - y%:P)) ->\n  SplittingField.axiom L.\nProof.\nmove=> normalL; pose r i := sval (sigW (normalL 1%AS (tnth (vbasis {:L}) i))).\nhave sz_r i: size (r i) <= \\dim {:L}.\n  rewrite -ltnS -(size_prod_XsubC _ id) /r; case: sigW => _ /= /eqP <-.\n  rewrite size_minPoly ltnS; move: (tnth _ _) => x.\n  by rewrite adjoin_degreeE dimv1 divn1 dimvS // subvf.\npose mkf (z : L) := 'X - z%:P.\nexists (\\prod_i \\prod_(j < \\dim {:L} | j < size (r i)) mkf (r i)`_j).\n  apply: rpred_prod => i _; rewrite big_ord_narrow /= /r; case: sigW => rs /=.\n  by rewrite (big_nth 0) big_mkord => /eqP <- {rs}; apply: minPolyOver.\nrewrite pair_big_dep /= -big_filter filter_index_enum -(big_map _ xpredT mkf).\nset rF := map _ _; exists rF; first exact: eqpxx.\napply/eqP; rewrite eqEsubv subvf -(span_basis (vbasisP {:L})).\napply/span_subvP=> _ /tnthP[i ->]; set x := tnth _ i.\nhave /tnthP[j ->]: x \\in in_tuple (r i).\n  by rewrite -root_prod_XsubC /r; case: sigW => _ /=/eqP<-; apply: root_minPoly.\napply/seqv_sub_adjoin/imageP; rewrite (tnth_nth 0) /in_mem/=.\nby exists (i, widen_ord (sz_r i) j) => /=.\nQed.\n\nFact regular_splittingAxiom F : SplittingField.axiom (regular_fieldExtType F).\nProof.\nexists 1; first exact: rpred1.\nby exists [::]; [rewrite big_nil eqpxx | rewrite Fadjoin_nil regular_fullv].\nQed.\n\nCanonical regular_splittingFieldType (F : fieldType) :=\n  SplittingFieldType F F^o (regular_splittingAxiom F).\n\nSection SplittingFieldTheory.\n\nVariables (F : fieldType) (L : splittingFieldType F).\n\nImplicit Types (U V W : {vspace L}).\nImplicit Types (K M E : {subfield L}).\n\nLemma splittingFieldP : SplittingField.axiom L.\nProof. by case: L => ? []. Qed.\n\nLemma splittingPoly : \n  {p : {poly L} | p \\is a polyOver 1%VS & splittingFieldFor 1 p {:L}}.\nProof.\npose factF p s := (p \\is a polyOver 1%VS) && (p %= \\prod_(z <- s) ('X - z%:P)).\nsuffices [[p rs] /andP[]]: {ps | factF F L ps.1 ps.2 & <<1 & ps.2>> = {:L}}%VS.\n  by exists p; last exists rs.\napply: sig2_eqW; have [p F0p [rs splitLp genLrs]] := splittingFieldP.\nby exists (p, rs); rewrite // /factF F0p splitLp.\nQed.\n\nFact fieldOver_splitting E : SplittingField.axiom (fieldOver_fieldExtType E).\nProof.\nhave [p Fp [r Dp defL]] := splittingFieldP; exists p.\n  apply/polyOverP=> j; rewrite trivial_fieldOver.\n  by rewrite (subvP (sub1v E)) ?(polyOverP Fp).\nexists r => //; apply/vspaceP=> x; rewrite memvf.\nhave [L0 [_ _ defL0]] :=  @aspaceOverP _ _ E <<1 & r : seq (fieldOver E)>>.\nrewrite defL0; have: x \\in <<1 & r>>%VS by rewrite defL (@memvf _ L).\napply: subvP; apply/Fadjoin_seqP; rewrite -memvE -defL0 mem1v.\nby split=> // y r_y; rewrite -defL0 seqv_sub_adjoin.\nQed.\nCanonical fieldOver_splittingFieldType E :=\n  SplittingFieldType (subvs_of E) (fieldOver E) (fieldOver_splitting E).\n\nLemma enum_AEnd : {kAutL : seq 'AEnd(L) | forall f, f \\in kAutL}.\nProof.\npose isAutL (s : seq 'AEnd(L)) (f : 'AEnd(L)) := kHom 1 {:L} f = (f \\in s).\nsuffices [kAutL in_kAutL] : {kAutL : seq 'AEnd(L) | forall f, isAutL kAutL f}.\n  by exists kAutL => f; rewrite -in_kAutL k1AHom.\nhave [p Kp /sig2_eqW[rs Dp defL]] := splittingPoly.\ndo [rewrite {}/isAutL -(erefl (asval 1)); set r := rs; set E := 1%AS] in defL *.\nhave [sKE rs_r]: (1 <= E)%VS /\\ all (mem rs) r by split; last apply/allP.\nelim: r rs_r => [_|z r IHr /=/andP[rs_z rs_r]] /= in (E) sKE defL *.\n  rewrite Fadjoin_nil in defL; exists [tuple \\1%AF] => f; rewrite defL inE.\n  apply/idP/eqP=> [/kAHomP f1 | ->]; last exact: kHom1.\n  by apply/val_inj/lfunP=> x; rewrite id_lfunE f1 ?memvf.\ndo [set Ez := <<E; z>>%VS; rewrite adjoin_cons] in defL.\nhave sEEz: (E <= Ez)%VS := subv_adjoin E z; have sKEz := subv_trans sKE sEEz.\nhave{IHr} [homEz DhomEz] := IHr rs_r _ sKEz defL.\nhave Ep: p \\in polyOver E := polyOverSv sKE Kp.\nhave{rs_z} pz0: root p z by rewrite (eqp_root Dp) root_prod_XsubC.\npose pEz := minPoly E z; pose n := \\dim_E Ez.\nhave{pz0} [rz DpEz]: {rz : n.-tuple L | pEz %= \\prod_(w <- rz) ('X - w%:P)}.\n  have /dvdp_prod_XsubC[m DpEz]: pEz %| \\prod_(w <- rs) ('X - w%:P).\n    by rewrite -(eqp_dvdr _ Dp) minPoly_dvdp ?(polyOverSv sKE).\n  suffices sz_rz: size (mask m rs) == n by exists (Tuple sz_rz).\n  rewrite -[n]adjoin_degreeE -eqSS -size_minPoly.\n  by rewrite (eqp_size DpEz) size_prod_XsubC.\nhave fEz i (y := tnth rz i): {f : 'AEnd(L) | kHom E {:L} f & f z = y}.\n  have homEfz: kHom E Ez (kHomExtend E \\1 z y).\n    rewrite kHomExtendP ?kHom1 // lfun1_poly.\n    by rewrite (eqp_root DpEz) -/rz root_prod_XsubC mem_tnth.\n  have splitFp: splittingFieldFor Ez p {:L}.\n    exists rs => //; apply/eqP; rewrite eqEsubv subvf -defL adjoin_seqSr //.\n    exact/allP.\n  have [f homLf Df] := kHom_extends sEEz homEfz Ep splitFp.\n  have [ahomf _] := andP homLf; exists (AHom ahomf) => //.\n  rewrite -Df ?memv_adjoin ?(kHomExtend_val (kHom1 E E)) // lfun1_poly.\n  by rewrite (eqp_root DpEz) root_prod_XsubC mem_tnth.\nexists [seq (s2val (fEz i) \\o f)%AF| i <- enum 'I_n, f <- homEz] => f.\napply/idP/allpairsP => [homLf | [[i g] [_ Hg ->]] /=]; last first.\n  by case: (fEz i) => fi /= /comp_kHom->; rewrite ?(kHomSl sEEz) ?DhomEz.\nhave /tnthP[i Dfz]: f z \\in rz.\n  rewrite memtE /= -root_prod_XsubC -(eqp_root DpEz).\n  by rewrite (kHom_root_id _ homLf) ?memvf ?subvf ?minPolyOver ?root_minPoly.\ncase Dfi: (fEz i) => [fi homLfi fi_z]; have kerfi0 := kAutf_lker0 homLfi.\nset fj := (fi ^-1 \\o f)%AF; suffices Hfj : fj \\in homEz.\n  exists (i, fj) => //=; rewrite mem_enum inE Hfj; split => //.\n  by apply/val_inj; rewrite {}Dfi /= (lker0_compVKf kerfi0).\nrewrite -DhomEz; apply/kAHomP => _ /Fadjoin_polyP[q Eq ->].\nhave homLfj: kHom E {:L} fj := comp_kHom (inv_kHomf homLfi) homLf.\nhave /kHom_lrmorphism fjM := kHomSl (sub1v _) homLfj.\nrewrite -[fj _](horner_map (RMorphism fjM)) (kHom_poly_id homLfj) //=.\nby rewrite lfunE /= Dfz -fi_z lker0_lfunK.\nQed.\n\nLemma splitting_field_normal K x :\n  exists r, minPoly K x == \\prod_(y <- r) ('X - y%:P).\nProof.\npose q1 := minPoly 1 x; pose fx_root q (f : 'AEnd(L)) := root q (f x).\nhave [[p F0p splitLp] [autL DautL]] := (splittingFieldP, enum_AEnd).\nsuffices{K} autL_px q: q != 0 -> q %| q1 -> size q > 1 -> has (fx_root q) autL.\n  set q := minPoly K x; have: q \\is monic := monic_minPoly K x.\n  have: q %| q1 by rewrite minPolyS // sub1v.\n  elim: {q}_.+1 {-2}q (ltnSn (size q)) => // d IHd q leqd q_dv_q1 mon_q.\n  have nz_q: q != 0 := monic_neq0 mon_q.\n  have [|q_gt1|q_1] := ltngtP (size q) 1; last first; last by rewrite polySpred.\n    by exists nil; rewrite big_nil -eqp_monic ?monic1 // -size_poly_eq1 q_1.\n  have /hasP[f autLf /factor_theorem[q2 Dq]] := autL_px q nz_q q_dv_q1 q_gt1.\n  have mon_q2: q2 \\is monic by rewrite -(monicMr _ (monicXsubC (f x))) -Dq.\n  rewrite Dq size_monicM -?size_poly_eq0 ?size_XsubC ?addn2 //= ltnS in leqd.\n  have q2_dv_q1: q2 %| q1 by rewrite (dvdp_trans _ q_dv_q1) // Dq dvdp_mulr.\n  rewrite Dq; have [r /eqP->] := IHd q2 leqd q2_dv_q1 mon_q2.\n  by exists (f x :: r); rewrite big_cons mulrC.\nelim: {q}_.+1 {-2}q (ltnSn (size q)) => // d IHd q leqd nz_q q_dv_q1 q_gt1.\nwithout loss{d leqd IHd nz_q q_gt1} irr_q: q q_dv_q1 / irreducible_poly q.\n  move=> IHq; apply: wlog_neg => not_autLx_q; apply: IHq => //.\n  split=> // q2 q2_neq1 q2_dv_q; rewrite -dvdp_size_eqp // eqn_leq dvdp_leq //=.\n  rewrite leqNgt; apply: contra not_autLx_q => ltq2q.\n  have nz_q2: q2 != 0 by apply: contraTneq q2_dv_q => ->; rewrite dvd0p.\n  have{q2_neq1} q2_gt1: size q2 > 1 by rewrite neq_ltn polySpred in q2_neq1 *.\n  have{leqd ltq2q} ltq2d: size q2 < d by apply: leq_trans ltq2q _.\n  apply: sub_has (IHd _ ltq2d nz_q2 (dvdp_trans q2_dv_q q_dv_q1) q2_gt1) => f.\n  by rewrite /fx_root !root_factor_theorem => /dvdp_trans->.\nhave{irr_q} [Lz [inLz [z qz0]]]: {Lz : fieldExtType F &\n  {inLz : 'AHom(L, Lz) & {z : Lz | root (map_poly inLz q) z}}}.\n- have [Lz0 _ [z qz0 defLz]] := irredp_FAdjoin irr_q.\n  pose Lz := baseField_extFieldType Lz0.\n  pose inLz : {rmorphism L -> Lz} := [rmorphism of in_alg Lz0].\n  have inLzL_linear: linear (locked inLz).\n    move=> a u v; rewrite -(@mulr_algl F Lz) baseField_scaleE.\n    by rewrite -{1}mulr_algl rmorphD rmorphM -lock.\n  have ihLzZ: ahom_in {:L} (linfun (Linear inLzL_linear)).\n    by apply/ahom_inP; split=> [u v|]; rewrite !lfunE (rmorphM, rmorph1).\n  exists Lz, (AHom ihLzZ), z; congr (root _ z): qz0.\n  by apply: eq_map_poly => y; rewrite lfunE /= -lock.\npose imL := [aspace of limg inLz]; pose pz := map_poly inLz p.\nhave in_imL u: inLz u \\in imL by rewrite memv_img ?memvf.\nhave F0pz: pz \\is a polyOver 1%VS.\n  apply/polyOverP=> i; rewrite -(aimg1 inLz) coef_map /= memv_img //.\n  exact: (polyOverP F0p).\nhave{splitLp} splitLpz: splittingFieldFor 1 pz imL.\n  have [r def_p defL] := splitLp; exists (map inLz r) => [|{def_p}].\n    move: def_p; rewrite -(eqp_map [rmorphism of inLz]) rmorph_prod.\n    rewrite big_map; congr (_ %= _); apply: eq_big => // y _.\n    by rewrite rmorphB /= map_polyX map_polyC.\n  apply/eqP; rewrite eqEsubv /= -{2}defL {defL}; apply/andP; split.\n    by apply/Fadjoin_seqP; rewrite sub1v; split=> // _ /mapP[y r_y ->].\n  elim/last_ind: r => [|r y IHr] /=; first by rewrite !Fadjoin_nil aimg1.\n  rewrite map_rcons !adjoin_rcons /=.\n  apply/subvP=> _ /memv_imgP[_ /Fadjoin_polyP[p1 r_p1 ->] ->].\n  rewrite -horner_map /= mempx_Fadjoin //=; apply/polyOverP=> i.\n  by rewrite coef_map (subvP IHr) //= memv_img ?(polyOverP r_p1).\nhave [f homLf fxz]: exists2 f : 'End(Lz), kHom 1 imL f & f (inLz x) = z.\n  pose q1z := minPoly 1 (inLz x).\n  have Dq1z: map_poly inLz q1 %| q1z.\n    have F0q1z i: exists a, q1z`_i = a%:A by apply/vlineP/polyOverP/minPolyOver.\n    have [q2 Dq2]: exists q2, q1z = map_poly inLz q2.\n      exists (\\poly_(i < size q1z) (sval (sig_eqW (F0q1z i)))%:A).\n      rewrite -{1}[q1z]coefK; apply/polyP=> i; rewrite coef_map !{1}coef_poly.\n      by case: sig_eqW => a; case: ifP; rewrite /= ?rmorph0 ?linearZ ?rmorph1.\n    rewrite Dq2 dvdp_map minPoly_dvdp //.\n      apply/polyOverP=> i; have[a] := F0q1z i.\n      rewrite -(rmorph1 [rmorphism of inLz]) -linearZ.\n      by rewrite Dq2 coef_map => /fmorph_inj->; rewrite rpredZ ?mem1v.\n    by rewrite -(fmorph_root [rmorphism of inLz]) -Dq2 root_minPoly.\n  have q1z_z: root q1z z.\n    rewrite !root_factor_theorem in qz0 *.\n    by apply: dvdp_trans qz0 (dvdp_trans _ Dq1z); rewrite dvdp_map.\n  have map1q1z_z: root (map_poly \\1%VF q1z) z.\n    by rewrite map_poly_id => // ? _; rewrite lfunE.\n  pose f0 := kHomExtend 1 \\1 (inLz x) z.\n  have{map1q1z_z} hom_f0 : kHom 1 <<1; inLz x>> f0.\n    by apply: kHomExtendP map1q1z_z => //; apply: kHom1.\n  have{splitLpz} splitLpz: splittingFieldFor <<1; inLz x>> pz imL.\n    have [r def_pz defLz] := splitLpz; exists r => //.\n    apply/eqP; rewrite eqEsubv -{2}defLz adjoin_seqSl ?sub1v // andbT.\n    apply/Fadjoin_seqP; split; last first.\n      by rewrite /= -[limg _]defLz; apply: seqv_sub_adjoin.\n    by apply/FadjoinP/andP; rewrite sub1v memv_img ?memvf.\n  have [f homLzf Df] := kHom_extends (sub1v _) hom_f0 F0pz splitLpz.\n  have [-> | x'z] := eqVneq (inLz x) z.\n    by exists \\1%VF; rewrite ?lfunE ?kHom1.\n  exists f => //; rewrite -Df ?memv_adjoin ?(kHomExtend_val (kHom1 1 1)) //.\n  by rewrite lfun1_poly.\npose f1 := (inLz^-1 \\o f \\o inLz)%VF; have /kHomP[fM fFid] := homLf.\nhave Df1 u: inLz (f1 u) = f (inLz u).\n  rewrite !comp_lfunE limg_lfunVK //= -[limg _]/(asval imL).\n  have [r def_pz defLz] := splitLpz.\n  have []: all (mem r) r /\\ inLz u \\in imL by split; first apply/allP.\n  rewrite -{1}defLz; elim/last_ind: {-1}r {u}(inLz u) => [|r1 y IHr1] u.\n    by rewrite Fadjoin_nil => _ Fu; rewrite fFid // (subvP (sub1v _)).\n  rewrite all_rcons adjoin_rcons => /andP[rr1 ry] /Fadjoin_polyP[pu r1pu ->].\n  rewrite (kHom_horner homLf) -defLz; last exact: seqv_sub_adjoin; last first.\n    by apply: polyOverS r1pu; apply/subvP/adjoin_seqSr/allP.\n  apply: rpred_horner.\n    by apply/polyOverP=> i; rewrite coef_map /= defLz IHr1 ?(polyOverP r1pu).\n  rewrite seqv_sub_adjoin // -root_prod_XsubC -(eqp_root def_pz).\n  rewrite (kHom_root_id _ homLf) ?sub1v //.\n    by rewrite -defLz seqv_sub_adjoin.\n  by rewrite (eqp_root def_pz) root_prod_XsubC.\nsuffices f1_is_ahom : ahom_in {:L} f1.\n  apply/hasP; exists (AHom f1_is_ahom); first exact: DautL.\n  by rewrite /fx_root -(fmorph_root [rmorphism of inLz]) /= Df1 fxz.\napply/ahom_inP; split=> [a b _ _|]; apply: (fmorph_inj [rmorphism of inLz]).\n  by rewrite rmorphM /= !Df1 rmorphM fM ?in_imL.\nby rewrite /= Df1 /= fFid ?rmorph1 ?mem1v.\nQed.\n\nLemma kHom_to_AEnd K E f : kHom K E f -> {g : 'AEnd(L) | {in E, f =1 val g}}.\nProof.\nmove=> homKf; have{homKf} [homFf sFE] := (kHomSl (sub1v K) homKf, sub1v E).\nhave [p Fp /(splittingFieldForS sFE (subvf E))splitLp] := splittingPoly.\nhave [g0 homLg0 eq_fg] := kHom_extends sFE homFf Fp splitLp.\nby apply: exist (Sub g0 _) _ =>  //; apply/ahomP/kHom_lrmorphism.\nQed.\n\nEnd SplittingFieldTheory.\n\n(* Hide the finGroup structure on 'AEnd(L) in a module so that we can control *)\n(* when it is exported. Most people will want to use the finGroup structure   *)\n(* on 'Gal(E / K) and will not need this module.                              *)\nModule Import AEnd_FinGroup.\nSection AEnd_FinGroup.\n\nVariables (F : fieldType) (L : splittingFieldType F).\nImplicit Types (U V W : {vspace L}) (K M E : {subfield L}).\n\nDefinition inAEnd f := SeqSub (svalP (enum_AEnd L) f).\nFact inAEndK : cancel inAEnd val. Proof. by []. Qed.\n\nDefinition AEnd_countMixin := Eval hnf in CanCountMixin inAEndK.\nCanonical AEnd_countType := Eval hnf in CountType 'AEnd(L) AEnd_countMixin.\nCanonical AEnd_subCountType := Eval hnf in [subCountType of 'AEnd(L)].\nDefinition AEnd_finMixin := Eval hnf in CanFinMixin inAEndK.\nCanonical AEnd_finType := Eval hnf in FinType 'AEnd(L) AEnd_finMixin.\nCanonical AEnd_subFinType := Eval hnf in [subFinType of 'AEnd(L)].\n\n(* the group operation is the categorical composition operation *)\nDefinition comp_AEnd (f g : 'AEnd(L)) : 'AEnd(L) := (g \\o f)%AF.\n\nFact comp_AEndA : associative comp_AEnd.\nProof. by move=> f g h; apply: val_inj; symmetry; apply: comp_lfunA. Qed.\n\nFact comp_AEnd1l : left_id \\1%AF comp_AEnd.\nProof. by move=> f; apply/val_inj/comp_lfun1r. Qed.\n\nFact comp_AEndK : left_inverse \\1%AF (@inv_ahom _ L) comp_AEnd.\nProof.  by move=> f; apply/val_inj; rewrite /= lker0_compfV ?AEnd_lker0. Qed.\n\nDefinition AEnd_baseFinGroupMixin :=\n  FinGroup.Mixin comp_AEndA comp_AEnd1l comp_AEndK.\nCanonical AEnd_baseFinGroupType :=\n  BaseFinGroupType 'AEnd(L) AEnd_baseFinGroupMixin.\nCanonical AEnd_finGroupType := FinGroupType comp_AEndK.\n\nDefinition kAEnd U V := [set f : 'AEnd(L) | kAut U V f].\nDefinition kAEndf U := kAEnd U {:L}.\n\nLemma kAEnd_group_set K E : group_set (kAEnd K E).\nProof.\napply/group_setP; split=> [|f g]; first by rewrite inE /kAut kHom1 lim1g eqxx.\nrewrite !inE !kAutE => /andP[homKf EfE] /andP[/(kHomSr EfE)homKg EgE].\nby rewrite (comp_kHom_img homKg homKf) limg_comp (subv_trans _ EgE) ?limgS.\nQed.\nCanonical kAEnd_group K E := group (kAEnd_group_set K E).\nCanonical kAEndf_group K := [group of kAEndf K].\n\nLemma kAEnd_norm K E : kAEnd K E \\subset 'N(kAEndf E)%g.\nProof.\napply/subsetP=> x; rewrite -groupV 2!in_set => /andP[_ /eqP ExE].\napply/subsetP=> _ /imsetP[y homEy ->]; rewrite !in_set !kAutfE in homEy *.\napply/kAHomP=> u Eu; have idEy := kAHomP homEy; rewrite -ExE in idEy.\nby rewrite !lfunE /= lfunE /= idEy ?memv_img // lker0_lfunVK ?AEnd_lker0.\nQed.\n\nLemma mem_kAut_coset K E (g : 'AEnd(L)) :\n  kAut K E g -> g \\in coset (kAEndf E) g.\nProof.\nmove=> autEg; rewrite val_coset ?rcoset_refl //.\nby rewrite (subsetP (kAEnd_norm K E)) // inE.\nQed.\n\nLemma aut_mem_eqP E (x y : coset_of (kAEndf E)) f g : \n  f \\in x -> g \\in y -> reflect {in E, f =1 g} (x == y).\nProof.\nmove=> x_f y_g; rewrite -(coset_mem x_f) -(coset_mem y_g).\nhave [Nf Ng] := (subsetP (coset_norm x) f x_f, subsetP (coset_norm y) g y_g).\nrewrite (sameP eqP (rcoset_kercosetP Nf Ng)) mem_rcoset inE kAutfE.\napply: (iffP kAHomP) => idEfg u Eu.\n  by rewrite -(mulgKV g f) lfunE /= idEfg.\nby rewrite lfunE /= idEfg // lker0_lfunK ?AEnd_lker0.\nQed.\n\nEnd AEnd_FinGroup.\nEnd AEnd_FinGroup.\n\nSection GaloisTheory.\n\nVariables (F : fieldType) (L : splittingFieldType F).\n\nImplicit Types (U V W : {vspace L}).\nImplicit Types (K M E : {subfield L}).\n\n(* We take Galois automorphisms for a subfield E to be automorphisms of the   *)\n(* full field {:L} that operate in E taken modulo those that fix E pointwise. *)\n(* The type of Galois automorphisms of E is then the subtype of elements of   *)\n(* the quotient kAEnd 1 E / kAEndf E, which we encapsulate in a specific      *)\n(* wrapper to ensure stability of the gal_repr coercion insertion.            *)\nSection gal_of_Definition.\n\nVariable V : {vspace L}.\n\n(* The <<_>>, which becomes redundant when V is a {subfield L}, ensures that  *)\n(* the argument of [subg _] is syntactically a group.                         *)\nInductive gal_of := Gal of [subg kAEnd_group 1 <<V>> / kAEndf (agenv V)].\nDefinition gal (f : 'AEnd(L)) := Gal (subg _ (coset _ f)).\nDefinition gal_sgval x := let: Gal u := x in u.\n\nFact gal_sgvalK : cancel gal_sgval Gal. Proof. by case. Qed.\nLet gal_sgval_inj := can_inj gal_sgvalK.\n\nDefinition gal_eqMixin := CanEqMixin gal_sgvalK.\nCanonical gal_eqType := Eval hnf in EqType gal_of gal_eqMixin.\nDefinition gal_choiceMixin := CanChoiceMixin gal_sgvalK.\nCanonical gal_choiceType := Eval hnf in ChoiceType gal_of gal_choiceMixin.\nDefinition gal_countMixin := CanCountMixin gal_sgvalK.\nCanonical gal_countType := Eval hnf in CountType gal_of gal_countMixin.\nDefinition gal_finMixin := CanFinMixin gal_sgvalK.\nCanonical gal_finType := Eval hnf in FinType gal_of gal_finMixin.\n\nDefinition gal_one := Gal 1%g.\nDefinition gal_inv x := Gal (gal_sgval x)^-1.\nDefinition gal_mul x y := Gal (gal_sgval x * gal_sgval y).\nFact gal_oneP : left_id gal_one gal_mul.\nProof. by move=> x; apply/gal_sgval_inj/mul1g. Qed.\nFact gal_invP : left_inverse gal_one gal_inv gal_mul.\nProof. by move=> x; apply/gal_sgval_inj/mulVg. Qed.\nFact gal_mulP : associative gal_mul.\nProof. by move=> x y z; apply/gal_sgval_inj/mulgA. Qed.\n\nDefinition gal_finGroupMixin :=\n  FinGroup.Mixin gal_mulP gal_oneP gal_invP.\nCanonical gal_finBaseGroupType :=\n  Eval hnf in BaseFinGroupType gal_of gal_finGroupMixin.\nCanonical gal_finGroupType := Eval hnf in FinGroupType gal_invP.\n\nCoercion gal_repr u : 'AEnd(L) := repr (sgval (gal_sgval u)).\n\nFact gal_is_morphism : {in kAEnd 1 (agenv V) &, {morph gal : x y / x * y}%g}.\nProof.\nmove=> f g /= autEa autEb; congr (Gal _).\nby rewrite !morphM ?mem_morphim // (subsetP (kAEnd_norm 1 _)).\nQed.\nCanonical gal_morphism := Morphism gal_is_morphism.\n\nLemma gal_reprK : cancel gal_repr gal.\nProof. by case=> x; rewrite /gal coset_reprK sgvalK. Qed.\n\nLemma gal_repr_inj : injective gal_repr.\nProof. exact: can_inj gal_reprK. Qed.\n\nLemma gal_AEnd x : gal_repr x \\in kAEnd 1 (agenv V).\nProof.\nrewrite /gal_repr; case/gal_sgval: x => _ /=/morphimP[g Ng autEg ->].\nrewrite val_coset //=; case: repr_rcosetP => f; rewrite groupMr // !inE kAut1E.\nby rewrite kAutE -andbA => /and3P[_ /fixedSpace_limg-> _].\nQed.\n\nEnd gal_of_Definition.\n\nPrenex Implicits gal_repr.\n\nLemma gal_eqP E {x y : gal_of E} : reflect {in E, x =1 y} (x == y).\nProof.\nby rewrite -{1}(subfield_closed E); apply: aut_mem_eqP; apply: mem_repr_coset.\nQed.\n\nLemma galK E (f : 'AEnd(L)) : (f @: E <= E)%VS -> {in E, gal E f =1 f}.\nProof.\nrewrite -kAut1E -{1 2}(subfield_closed E) => autEf.\napply: (aut_mem_eqP (mem_repr_coset _) _ (eqxx _)).\nby rewrite subgK /= ?(mem_kAut_coset autEf) // ?mem_quotient ?inE.\nQed.\n\nLemma eq_galP E (f g : 'AEnd(L)) :\n   (f @: E <= E)%VS -> (g @: E <= E)%VS ->\n  reflect {in E, f =1 g} (gal E f == gal E g).\nProof.\nmove=> EfE EgE.\nby apply: (iffP gal_eqP) => Dfg a Ea; have:= Dfg a Ea; rewrite !{1}galK.\nQed.\n\nLemma limg_gal E (x : gal_of E) : (x @: E)%VS = E.\nProof. by have:= gal_AEnd x; rewrite inE subfield_closed => /andP[_ /eqP]. Qed.\n\nLemma memv_gal E (x : gal_of E) a : a \\in E -> x a \\in E.\nProof. by move/(memv_img x); rewrite limg_gal. Qed.\n\nLemma gal_id E a : (1 : gal_of E)%g a = a.\nProof. by rewrite /gal_repr repr_coset1 id_lfunE. Qed.\n\nLemma galM E (x y : gal_of E) a : a \\in E -> (x * y)%g a = y (x a).\nProof.\nrewrite /= -comp_lfunE; apply/eq_galP; rewrite ?limg_comp ?limg_gal //.\nby rewrite morphM /= ?gal_reprK ?gal_AEnd.\nQed.\n\nLemma galV E (x : gal_of E) : {in E, (x^-1)%g =1 x^-1%VF}.\nProof.\nmove=> a Ea; apply: canRL (lker0_lfunK (AEnd_lker0 _)) _.\nby rewrite -galM // mulVg gal_id.\nQed.\n\n(* Standard mathematical notation for 'Gal(E / K) puts the larger field first.*)\nDefinition galoisG V U := gal V @* <<kAEnd (U :&: V) V>>.\nLocal Notation \"''Gal' ( V / U )\" := (galoisG V U) : group_scope.\nCanonical galoisG_group E U := Eval hnf in [group of (galoisG E U)].\nLocal Notation \"''Gal' ( V / U )\" := (galoisG_group V U) : Group_scope.\n\nSection Automorphism.\n\nLemma gal_cap U V : 'Gal(V / U) = 'Gal(V / U :&: V).\nProof. by rewrite /galoisG -capvA capvv. Qed.\n\nLemma gal_kAut K E x : (K <= E)%VS -> (x \\in 'Gal(E / K)) = kAut K E x.\nProof.\nmove=> sKE; apply/morphimP/idP=> /= [[g EgE KautEg ->{x}] | KautEx].\n  rewrite genGid !inE kAut1E /= subfield_closed (capv_idPl sKE) in KautEg EgE.\n  by apply: etrans KautEg; apply/(kAut_eq sKE); apply: galK.\nexists (x : 'AEnd(L)); rewrite ?gal_reprK ?gal_AEnd //.\nby rewrite (capv_idPl sKE) mem_gen ?inE.\nQed.\n\nLemma gal_kHom K E x : (K <= E)%VS -> (x \\in 'Gal(E / K)) = kHom K E x.\nProof. by move/gal_kAut->; rewrite /kAut limg_gal eqxx andbT. Qed.\n\nLemma kAut_to_gal K E f :\n  kAut K E f -> {x : gal_of E | x \\in 'Gal(E / K) & {in E, f =1 x}}.\nProof.\ncase/andP=> homKf EfE; have [g Df] := kHom_to_AEnd homKf.\nhave{homKf EfE} autEg: kAut (K :&: E) E g.\n  rewrite /kAut -(kHom_eq (capvSr _ _) Df) (kHomSl (capvSl _ _) homKf) /=.\n  by rewrite -(eq_in_limg Df).\nhave FautEg := kAutS (sub1v _) autEg.\nexists (gal E g) => [|a Ea]; last by rewrite {f}Df // galK // -kAut1E.\nby rewrite mem_morphim /= ?subfield_closed ?genGid ?inE.\nQed.\n\nLemma fixed_gal K E x a :\n  (K <= E)%VS -> x \\in 'Gal(E / K) -> a \\in K -> x a = a.\nProof. by move/gal_kHom=> -> /kAHomP idKx /idKx. Qed.\n\nLemma fixedPoly_gal K E x p :\n  (K <= E)%VS -> x \\in 'Gal(E / K) -> p \\is a polyOver K -> map_poly x p = p.\nProof.\nmove=> sKE galEKx /polyOverP Kp; apply/polyP => i.\nby rewrite coef_map /= (fixed_gal sKE).\nQed.\n\nLemma root_minPoly_gal K E x a :\n  (K <= E)%VS -> x \\in 'Gal(E / K) -> a \\in E -> root (minPoly K a) (x a).\nProof.\nmove=> sKE galEKx Ea; have homKx: kHom K E x by rewrite -gal_kHom.\nhave K_Pa := minPolyOver K a; rewrite -[minPoly K a](fixedPoly_gal _ galEKx) //.\nby rewrite (kHom_root homKx) ?root_minPoly // (polyOverS (subvP sKE)).\nQed.\n\nEnd Automorphism.\n\nLemma gal_adjoin_eq K a x y :\n    x \\in 'Gal(<<K; a>> / K) -> y \\in 'Gal(<<K; a>> / K) ->\n  (x == y) = (x a == y a).\nProof.\nmove=> galKa_x galKa_y; apply/idP/eqP=> [/eqP-> // | eq_xy_a].\napply/gal_eqP => _ /Fadjoin_polyP[p Kp ->].\nby rewrite -!horner_map !(fixedPoly_gal (subv_adjoin K a)) //= eq_xy_a.\nQed.\n\nLemma galS K M E : (K <= M)%VS -> 'Gal(E / M) \\subset 'Gal(E / K).\nProof.\nrewrite gal_cap (gal_cap K E) => sKM; apply/subsetP=> x.\nby rewrite !gal_kAut ?capvSr //; apply: kAutS; apply: capvS.\nQed.\n\nLemma gal_conjg K E x : 'Gal(E / K) :^ x = 'Gal(E / x @: K).\nProof.\nwithout loss sKE: K / (K <= E)%VS.\n  move=> IH_K; rewrite gal_cap {}IH_K ?capvSr //.\n  transitivity 'Gal(E / x @: K :&: x @: E); last by rewrite limg_gal -gal_cap.\n  congr 'Gal(E / _); apply/eqP; rewrite eqEsubv limg_cap; apply/subvP=> a.\n  rewrite memv_cap => /andP[/memv_imgP[b Kb ->] /memv_imgP[c Ec] eq_bc].\n  by rewrite memv_img // memv_cap Kb (lker0P (AEnd_lker0 _) _ _ eq_bc).\nwlog suffices IHx: x K sKE / 'Gal(E / K) :^ x \\subset 'Gal(E / x @: K).\n  apply/eqP; rewrite eqEsubset IHx // -sub_conjgV (subset_trans (IHx _ _ _)) //.\n    by apply/subvP=> _ /memv_imgP[a Ka ->]; rewrite memv_gal ?(subvP sKE).\n  rewrite -limg_comp (etrans (eq_in_limg _) (lim1g _)) // => a /(subvP sKE)Ka.\n  by rewrite !lfunE /= -galM // mulgV gal_id.\napply/subsetP=> _ /imsetP[y galEy ->]; rewrite gal_cap gal_kHom ?capvSr //=.\napply/kAHomP=> _ /memv_capP[/memv_imgP[a Ka ->] _]; have Ea := subvP sKE a Ka.\nby rewrite -galM // -conjgC galM // (fixed_gal sKE galEy).\nQed.\n\nDefinition fixedField V (A : {set gal_of V}) :=\n  (V :&: \\bigcap_(x in A) fixedSpace x)%VS.\n\nLemma fixedFieldP E {A : {set gal_of E}} a :\n  a \\in E -> reflect (forall x, x \\in A -> x a = a) (a \\in fixedField A).\nProof.\nby rewrite memv_cap => ->; apply: (iffP subv_bigcapP) => cAa x /cAa/fixedSpaceP.\nQed.\n\nLemma mem_fixedFieldP E (A : {set gal_of E}) a :\n  a \\in fixedField A -> a \\in E /\\ (forall x, x \\in A -> x a = a).\nProof.\nby move=> fixAa; have [Ea _] := memv_capP fixAa; have:= fixedFieldP Ea fixAa.\nQed.\n\nFact fixedField_is_aspace E (A : {set gal_of E}) : is_aspace (fixedField A).\nProof.\nrewrite /fixedField; elim/big_rec: _ {1}E => [|x K _ IH_K] M.\n  exact: (valP (M :&: _)%AS).\nby rewrite capvA IH_K.\nQed.\nCanonical fixedField_aspace E A : {subfield L} :=\n  ASpace (@fixedField_is_aspace E A).\n\nLemma fixedField_bound E (A : {set gal_of E}) : (fixedField A <= E)%VS.\nProof. exact: capvSl. Qed.\n\nLemma fixedFieldS E (A B : {set gal_of E}) :\n   A \\subset B -> (fixedField B <= fixedField A)%VS.\nProof.\nmove/subsetP=> sAB; apply/subvP => a /mem_fixedFieldP[Ea cBa].\nby apply/fixedFieldP; last apply: sub_in1 cBa.\nQed.\n\nLemma galois_connection_subv K E :\n  (K <= E)%VS -> (K <= fixedField ('Gal(E / K)))%VS.\nProof.\nmove=> sKE; apply/subvP => a Ka; have Ea := subvP sKE a Ka.\nby apply/fixedFieldP=> // x galEx; apply: (fixed_gal sKE).\nQed.\n\nLemma galois_connection_subset E (A : {set gal_of E}):\n  A \\subset 'Gal(E / fixedField A).\nProof.\napply/subsetP => x Ax; rewrite gal_kAut ?capvSl // kAutE limg_gal subvv andbT.\nby apply/kAHomP=> a /mem_fixedFieldP[_ ->].\nQed.\n\nLemma galois_connection K E (A : {set gal_of E}):\n  (K <= E)%VS -> (A \\subset 'Gal(E / K)) = (K <= fixedField A)%VS.\nProof.\nmove=> sKE; apply/idP/idP => [/fixedFieldS | /(galS E)].\n  by apply: subv_trans; apply galois_connection_subv.\nby apply: subset_trans; apply: galois_connection_subset.\nQed.\n\nDefinition galTrace U V a := \\sum_(x in 'Gal(V / U)) (x a).\n\nDefinition galNorm U V a := \\prod_(x in 'Gal(V / U)) (x a).\n\nSection TraceAndNormMorphism.\n\nVariables U V : {vspace L}.\n\nFact galTrace_is_additive : additive (galTrace U V).\nProof.\nby move=> a b /=; rewrite -sumrB; apply: eq_bigr => x _; rewrite rmorphB.\nQed.\nCanonical galTrace_additive := Additive galTrace_is_additive.\n\nLemma galNorm1 : galNorm U V 1 = 1.\nProof. by apply: big1 => x _; rewrite rmorph1. Qed.\n\nLemma galNormM : {morph galNorm U V : a b / a * b}.\nProof.\nby move=> a b /=; rewrite -big_split; apply: eq_bigr => x _; rewrite rmorphM.\nQed.\n\nLemma galNormV : {morph galNorm U V : a / a^-1}.\nProof.\nby move=> a /=; rewrite -prodfV; apply: eq_bigr => x _; rewrite fmorphV.\nQed.\n\nLemma galNormX n : {morph galNorm U V : a / a ^+ n}.\nProof.\nmove=> a; elim: n => [|n IHn]; first by apply: galNorm1.\nby rewrite !exprS galNormM IHn.\nQed.\n\nLemma galNorm_prod (I : Type) (r : seq I) (P : pred I) (B : I -> L) :\n  galNorm U V (\\prod_(i <- r | P i) B i)\n   = \\prod_(i <- r | P i) galNorm U V (B i).\nProof. exact: (big_morph _ galNormM galNorm1). Qed.\n\nLemma galNorm0 : galNorm U V 0 = 0.\nProof. by rewrite /galNorm (bigD1 1%g) ?group1 // rmorph0 /= mul0r. Qed.\n\nLemma galNorm_eq0 a : (galNorm U V a == 0) = (a == 0).\nProof.\napply/idP/eqP=> [/prodf_eq0[x _] | ->]; last by rewrite galNorm0.\nby rewrite fmorph_eq0 => /eqP.\nQed.\n\nEnd TraceAndNormMorphism.\n\nSection TraceAndNormField.\n\nVariables K E : {subfield L}.\n\nLemma galTrace_fixedField a :\n  a \\in E -> galTrace K E a \\in fixedField 'Gal(E / K).\nProof.\nmove=> Ea; apply/fixedFieldP=> [|x galEx].\n  by apply: rpred_sum => x _; apply: memv_gal.\nrewrite {2}/galTrace (reindex_acts 'R _ galEx) ?astabsR //=.\nby rewrite rmorph_sum; apply: eq_bigr => y _; rewrite galM ?lfunE.\nQed.\n\nLemma galTrace_gal a x :\n  a \\in E -> x \\in 'Gal(E / K) -> galTrace K E (x a) = galTrace K E a.\nProof.\nmove=> Ea galEx; rewrite {2}/galTrace (reindex_inj (mulgI x)).\nby apply: eq_big => [b | b _]; rewrite ?groupMl // galM ?lfunE.\nQed.\n\nLemma galNorm_fixedField a :\n  a \\in E -> galNorm K E a \\in fixedField 'Gal(E / K).\nProof.\nmove=> Ea; apply/fixedFieldP=> [|x galEx].\n  by apply: rpred_prod => x _; apply: memv_gal.\nrewrite {2}/galNorm (reindex_acts 'R _ galEx) ?astabsR //=.\nby rewrite rmorph_prod; apply: eq_bigr => y _; rewrite galM ?lfunE.\nQed.\n\nLemma galNorm_gal a x :\n  a \\in E -> x \\in 'Gal(E / K) -> galNorm K E (x a) = galNorm K E a.\nProof.\nmove=> Ea galEx; rewrite {2}/galNorm (reindex_inj (mulgI x)).\nby apply: eq_big => [b | b _]; rewrite ?groupMl // galM ?lfunE.\nQed.\n\nEnd TraceAndNormField.\n\nDefinition normalField U V := [forall x in kAEndf U, x @: V == V]%VS.\n\nLemma normalField_kAut K M E f :\n  (K <= M <= E)%VS -> normalField K M -> kAut K E f -> kAut K M f.\nProof.\ncase/andP=> sKM sME nKM /kAut_to_gal[x galEx /(sub_in1 (subvP sME))Df].\nhave sKE := subv_trans sKM sME; rewrite gal_kHom // in galEx.\nrewrite (kAut_eq sKM Df) /kAut (kHomSr sME) //= (forall_inP nKM) // inE.\nby rewrite kAutfE; apply/kAHomP; apply: (kAHomP galEx).\nQed.\n\nLemma normalFieldP K E :\n  reflect {in E, forall a, exists2 r,\n            all (mem E) r & minPoly K a = \\prod_(b <- r) ('X - b%:P)}\n          (normalField K E).\nProof.\napply: (iffP eqfun_inP) => [nKE a Ea | nKE x]; last first.\n  rewrite inE kAutfE => homKx; suffices: kAut K E x by case/andP=> _ /eqP.\n  rewrite kAutE (kHomSr (subvf E)) //=; apply/subvP=> _ /memv_imgP[a Ea ->].\n  have [r /allP/=srE splitEa] := nKE a Ea.\n  rewrite srE // -root_prod_XsubC -splitEa.\n  by rewrite -(kHom_poly_id homKx (minPolyOver K a)) fmorph_root root_minPoly.\nhave [r /eqP splitKa] := splitting_field_normal K a.\nexists r => //; apply/allP => b; rewrite -root_prod_XsubC -splitKa => pKa_b_0.\npose y := kHomExtend K \\1 a b; have [hom1K lf1p] := (kHom1 K K, lfun1_poly).\nhave homKy: kHom K <<K; a>> y by apply/kHomExtendP; rewrite ?lf1p.\nhave [[g Dy] [_ idKy]] := (kHom_to_AEnd homKy, kHomP homKy).\nhave <-: g a = b by rewrite -Dy ?memv_adjoin // (kHomExtend_val hom1K) ?lf1p.\nsuffices /nKE <-: g \\in kAEndf K by apply: memv_img.\nby rewrite inE kAutfE; apply/kAHomP=> c Kc; rewrite -Dy ?subvP_adjoin ?idKy.\nQed.\n\nLemma normalFieldf K : normalField K {:L}.\nProof.\napply/normalFieldP=> a _; have [r /eqP->] := splitting_field_normal K a.\nby exists r => //; apply/allP=> b; rewrite /= memvf.\nQed.\n\nLemma normalFieldS K M E : (K <= M)%VS -> normalField K E -> normalField M E.\nProof.\nmove=> sKM /normalFieldP nKE; apply/normalFieldP=> a Ea.\nhave [r /allP Er splitKa] := nKE a Ea.\nhave /dvdp_prod_XsubC[m splitMa]: minPoly M a %| \\prod_(b <- r) ('X - b%:P).\n  by rewrite -splitKa minPolyS.\nexists (mask m r); first by apply/allP=> b /mem_mask/Er.\nby apply/eqP; rewrite -eqp_monic ?monic_prod_XsubC ?monic_minPoly.\nQed.\n\nLemma splitting_normalField E K :\n   (K <= E)%VS ->\n  reflect (exists2 p, p \\is a polyOver K & splittingFieldFor K p E)\n          (normalField K E).\nProof.\nmove=> sKE; apply: (iffP idP) => [nKE| [p Kp [rs Dp defE]]]; last first.\n  apply/forall_inP=> g; rewrite inE kAutE => /andP[homKg _].\n  rewrite -dimv_leqif_eq ?limg_dim_eq ?(eqP (AEnd_lker0 g)) ?capv0 //.\n  rewrite -defE aimg_adjoin_seq; have [_ /fixedSpace_limg->] := andP homKg.\n  apply/adjoin_seqSr=> _ /mapP[a rs_a ->].\n  rewrite -!root_prod_XsubC -!(eqp_root Dp) in rs_a *.\n  by apply: kHom_root_id homKg Kp _ rs_a; rewrite ?subvf ?memvf.\npose splitK a r := minPoly K a = \\prod_(b <- r) ('X - b%:P).\nhave{nKE} rK_ a: {r | a \\in E -> all (mem E) r /\\ splitK a r}.\n  case Ea: (a \\in E); last by exists [::].\n  by have /sig2_eqW[r] := normalFieldP _ _ nKE a Ea; exists r.\nhave sXE := basis_mem (vbasisP E); set X : seq L := vbasis E in sXE.\nexists (\\prod_(a <- X) minPoly K a).\n  by apply: rpred_prod => a _; apply: minPolyOver.\nexists (flatten [seq (sval (rK_ a)) | a <- X]).\n  move/allP: sXE; elim: X => [|a X IHX]; first by rewrite !big_nil eqpxx.\n  rewrite big_cons /= big_cat /= => /andP[Ea sXE].\n  by case: (rK_ a) => /= r [] // _ <-; apply/eqp_mull/IHX.\napply/eqP; rewrite eqEsubv; apply/andP; split.\n  apply/Fadjoin_seqP; split=> // b /flatten_mapP[a /sXE Ea].\n  by apply/allP; case: rK_ => r /= [].\nrewrite -{1}(span_basis (vbasisP E)); apply/span_subvP=> a Xa.\napply/seqv_sub_adjoin/flatten_mapP; exists a => //; rewrite -root_prod_XsubC.\nby case: rK_ => /= r [| _ <-]; rewrite ?sXE ?root_minPoly.\nQed.\n\nLemma kHom_to_gal K M E f :\n    (K <= M <= E)%VS -> normalField K E -> kHom K M f ->\n  {x | x \\in 'Gal(E / K) & {in M, f =1 x}}.\nProof.\ncase/andP=> /subvP sKM /subvP sME nKE KhomMf.\nhave [[g Df] [_ idKf]] := (kHom_to_AEnd KhomMf, kHomP KhomMf).\nsuffices /kAut_to_gal[x galEx Dg]: kAut K E g.\n  by exists x => //= a Ma; rewrite Df // Dg ?sME.\nhave homKg: kHom K {:L} g by apply/kAHomP=> a Ka; rewrite -Df ?sKM ?idKf.\nby rewrite /kAut (kHomSr (subvf _)) // (forall_inP nKE) // inE kAutfE.\nQed.\n\nLemma normalField_root_minPoly K E a b :\n    (K <= E)%VS -> normalField K E -> a \\in E -> root (minPoly K a) b ->\n  exists2 x, x \\in 'Gal(E / K) & x a = b.\nProof.\nmove=> sKE nKE Ea pKa_b_0; pose f := kHomExtend K \\1 a b.\nhave homKa_f: kHom K <<K; a>> f.\n  by apply: kHomExtendP; rewrite ?kHom1 ?lfun1_poly.\nhave sK_Ka_E: (K <= <<K; a>> <= E)%VS.\n  by rewrite subv_adjoin; apply/FadjoinP; rewrite sKE Ea.\nhave [x galEx Df] := kHom_to_gal sK_Ka_E nKE homKa_f; exists x => //.\nby rewrite -Df ?memv_adjoin // (kHomExtend_val (kHom1 K K)) ?lfun1_poly.\nQed.\n\nArguments normalFieldP {K E}.\n\nLemma normalField_factors K E :\n   (K <= E)%VS ->\n reflect {in E, forall a, exists2 r : seq (gal_of E),\n            r \\subset 'Gal(E / K)\n          & minPoly K a = \\prod_(x <- r) ('X - (x a)%:P)}\n   (normalField K E).\nProof.\nmove=> sKE; apply: (iffP idP) => [nKE a Ea | nKE]; last first.\n  apply/normalFieldP=> a Ea; have [r _ ->] := nKE a Ea.\n  exists [seq x a | x : gal_of E <- r]; last by rewrite big_map.\n  by rewrite all_map; apply/allP=> b _; apply: memv_gal.\nhave [r Er splitKa] := normalFieldP nKE a Ea.\npose f b := [pick x in 'Gal(E / K) | x a == b].\nexists (pmap f r).\n  apply/subsetP=> x; rewrite mem_pmap /f => /mapP[b _].\n  by case: (pickP _) => // c /andP[galEc _] [->].\nrewrite splitKa; have{splitKa}: all (root (minPoly K a)) r.\n  by apply/allP => b; rewrite splitKa root_prod_XsubC.\nelim: r Er => /= [|b r IHr]; first by rewrite !big_nil.\ncase/andP=> Eb Er /andP[pKa_b_0 /(IHr Er){IHr Er}IHr].\nhave [x galE /eqP xa_b] := normalField_root_minPoly sKE nKE Ea pKa_b_0.\nrewrite /(f b); case: (pickP _) => [y /andP[_ /eqP<-]|/(_ x)/andP[]//].\nby rewrite !big_cons IHr.\nQed.\n\nDefinition galois U V := [&& (U <= V)%VS, separable U V & normalField U V].\n\nLemma galoisS K M E : (K <= M <= E)%VS -> galois K E -> galois M E.\nProof.\ncase/andP=> sKM sME /and3P[_ sepUV nUV].\nby rewrite /galois sME (separableSl sKM) ?(normalFieldS sKM).\nQed.\n\nLemma galois_dim K E : galois K E -> \\dim_K E = #|'Gal(E / K)|.\nProof.\ncase/and3P=> sKE /eq_adjoin_separable_generator-> // nKE.\nset a := separable_generator K E in nKE *.\nhave [r /allP/=Er splitKa] := normalFieldP nKE a (memv_adjoin K a).\nrewrite (dim_sup_field (subv_adjoin K a)) mulnK ?adim_gt0 //.\napply/eqP; rewrite -eqSS -adjoin_degreeE -size_minPoly splitKa size_prod_XsubC.\nset n := size r; rewrite eqSS -[n]card_ord.\nhave x_ (i : 'I_n): {x | x \\in 'Gal(<<K; a>> / K) & x a = r`_i}.\n  apply/sig2_eqW/normalField_root_minPoly; rewrite ?subv_adjoin ?memv_adjoin //.\n  by rewrite splitKa root_prod_XsubC mem_nth.\nhave /card_image <-: injective (fun i => s2val (x_ i)).\n  move=> i j /eqP; case: (x_ i) (x_ j) => y /= galEy Dya [z /= galEx Dza].\n  rewrite gal_adjoin_eq // Dya Dza nth_uniq // => [/(i =P j)//|].\n  by rewrite -separable_prod_XsubC -splitKa; apply: separable_generatorP.\napply/eqP/eq_card=> x; apply/codomP/idP=> [[i ->] | galEx]; first by case: x_.\nhave /(nthP 0) [i ltin Dxa]: x a \\in r.\n  rewrite -root_prod_XsubC -splitKa.\n  by rewrite root_minPoly_gal ?memv_adjoin ?subv_adjoin.\nexists (Ordinal ltin); apply/esym/eqP.\nby case: x_ => y /= galEy /eqP; rewrite Dxa gal_adjoin_eq.\nQed.\n\nLemma galois_factors K E :\n    (K <= E)%VS ->\n  reflect {in E, forall a, exists r, let r_a := [seq x a | x : gal_of E <- r] in\n            [/\\ r \\subset 'Gal(E / K), uniq r_a\n              & minPoly K a = \\prod_(b <- r_a) ('X - b%:P)]}\n          (galois K E).\nProof.\nmove=> sKE; apply: (iffP and3P) => [[_ sepKE nKE] a Ea | galKE].\n  have [r galEr splitEa] := normalField_factors sKE nKE a Ea.\n  exists r; rewrite /= -separable_prod_XsubC !big_map -splitEa.\n  by split=> //; apply: separableP Ea.\nsplit=> //.\n  apply/separableP => a /galKE[r [_ Ur_a splitKa]].\n  by rewrite /separable_element splitKa separable_prod_XsubC.\napply/(normalField_factors sKE)=> a /galKE[r [galEr _ ->]].\nby rewrite big_map; exists r.\nQed.\n\nLemma splitting_galoisField K E :\n  reflect (exists p, [/\\ p \\is a polyOver K, separable_poly p\n                       & splittingFieldFor K p E])     \n          (galois K E).\nProof.\napply: (iffP and3P) => [[sKE sepKE nKE]|[p [Kp sep_p [r Dp defE]]]].\n  rewrite (eq_adjoin_separable_generator sepKE) // in nKE *.\n  set a := separable_generator K E in nKE *; exists (minPoly K a).\n  split; first 1 [exact: minPolyOver | exact/separable_generatorP].\n  have [r /= /allP Er splitKa] := normalFieldP nKE a (memv_adjoin _ _).\n  exists r; first by rewrite splitKa eqpxx.\n  apply/eqP; rewrite eqEsubv; apply/andP; split.\n    by apply/Fadjoin_seqP; split => //; apply: subv_adjoin.\n  apply/FadjoinP; split; first exact: subv_adjoin_seq.\n  by rewrite seqv_sub_adjoin // -root_prod_XsubC -splitKa root_minPoly.\nhave sKE: (K <= E)%VS by rewrite -defE subv_adjoin_seq.\nsplit=> //; last by apply/splitting_normalField=> //; exists p; last exists r.\nrewrite -defE; apply/separable_Fadjoin_seq/allP=> a r_a.\nby apply/separable_elementP; exists p; rewrite (eqp_root Dp) root_prod_XsubC.\nQed.\n\nLemma galois_fixedField K E :\n  reflect (fixedField 'Gal(E / K) = K) (galois K E).\nProof.\napply (iffP idP) => [/and3P[sKE /separableP sepKE nKE] | fixedKE].\n  apply/eqP; rewrite eqEsubv galois_connection_subv ?andbT //.\n  apply/subvP=> a /mem_fixedFieldP[Ea fixEa]; rewrite -adjoin_deg_eq1.\n  have [r /allP Er splitKa] := normalFieldP nKE a Ea.\n  rewrite -eqSS -size_minPoly splitKa size_prod_XsubC eqSS -/(size [:: a]).\n  have Ur: uniq r by rewrite -separable_prod_XsubC -splitKa; apply: sepKE.\n  rewrite -uniq_size_uniq {Ur}// => b; rewrite inE -root_prod_XsubC -splitKa.\n  apply/eqP/idP=> [-> | pKa_b_0]; first exact: root_minPoly.\n  by have [x /fixEa-> ->] := normalField_root_minPoly sKE nKE Ea pKa_b_0.\nhave sKE: (K <= E)%VS by rewrite -fixedKE capvSl.\napply/galois_factors=> // a Ea.\npose r_pKa := [seq x a | x : gal_of E in 'Gal(E / K)].\nhave /fin_all_exists2[x_ galEx_ Dx_a] (b : seq_sub r_pKa) := imageP (valP b).\nexists (codom x_); rewrite -map_comp; set r := map _ _.\nhave r_xa x: x \\in 'Gal(E / K) -> x a \\in r.\n  move=> galEx; have r_pKa_xa: x a \\in r_pKa by apply/imageP; exists x.\n  by rewrite [x a](Dx_a (SeqSub r_pKa_xa)); apply: codom_f.\nhave Ur: uniq r by apply/injectiveP=> b c /=; rewrite -!Dx_a => /val_inj.\nsplit=> //; first by apply/subsetP=> _ /codomP[b ->].\napply/eqP; rewrite -eqp_monic ?monic_minPoly ?monic_prod_XsubC //.\napply/andP; split; last first.\n  rewrite uniq_roots_dvdp ?uniq_rootsE // all_map.\n  by apply/allP=> b _ /=; rewrite root_minPoly_gal.\napply: minPoly_dvdp; last by rewrite root_prod_XsubC -(gal_id E a) r_xa ?group1.\nrewrite -fixedKE; apply/polyOverP => i; apply/fixedFieldP=> [|x galEx].\n  rewrite (polyOverP _) // big_map rpred_prod // => b _.\n  by rewrite polyOverXsubC memv_gal.\nrewrite -coef_map rmorph_prod; congr (_ : {poly _})`_i.\nsymmetry; rewrite (eq_big_perm (map x r)) /= ?(big_map x).\n  by apply: eq_bigr => b _; rewrite rmorphB /= map_polyX map_polyC.\nhave Uxr: uniq (map x r) by rewrite map_inj_uniq //; apply: fmorph_inj.\nhave /leq_size_perm: {subset map x r <= r}.\n  by rewrite -map_comp => _ /codomP[b ->] /=; rewrite -galM // r_xa ?groupM.\nby rewrite (size_map x) perm_eq_sym; case=> // /uniq_perm_eq->.\nQed.\n\nLemma mem_galTrace K E a : galois K E -> a \\in E -> galTrace K E a \\in K.\nProof. by move/galois_fixedField => {2}<- /galTrace_fixedField. Qed.\n\nLemma mem_galNorm K E a : galois K E -> a \\in E -> galNorm K E a \\in K.\nProof. by move/galois_fixedField=> {2}<- /galNorm_fixedField. Qed.\n\nLemma gal_independent_contra E (P : pred (gal_of E)) (c_ : gal_of E -> L) x :\n    P x -> c_ x != 0 ->\n  exists2 a, a \\in E & \\sum_(y | P y) c_ y * y a != 0.\nProof.\nelim: {P}_.+1 c_ x {-2}P (ltnSn #|P|) => // n IHn c_ x P lePn Px nz_cx.\nrewrite ltnS (cardD1x Px) in lePn; move/IHn: lePn => {n IHn}/=IH_P.\nhave [/eqfun_inP c_Px'_0 | ] := boolP [forall (y | P y && (y != x)), c_ y == 0].\n  exists 1; rewrite ?mem1v // (bigD1 x Px) /= rmorph1 mulr1.\n  by rewrite big1 ?addr0 // => y /c_Px'_0->; rewrite mul0r.\nrewrite negb_forall_in => /exists_inP[y Px'y nz_cy].\nhave [Py /gal_eqP/eqlfun_inP/subvPn[a Ea]] := andP Px'y.\nrewrite memv_ker !lfun_simp => nz_yxa; pose d_ y := c_ y * (y a - x a).\nhave /IH_P[//|b Eb nz_sumb]: d_ y != 0 by rewrite mulf_neq0.\nhave [sumb_0|] := eqVneq (\\sum_(z | P z) c_ z * z b) 0; last by exists b.\nexists (a * b); first exact: rpredM.\nrewrite -subr_eq0 -[z in _ - z](mulr0 (x a)) -[in z in _ - z]sumb_0.\nrewrite mulr_sumr -sumrB (bigD1 x Px) rmorphM /= mulrCA subrr add0r.\ncongr (_ != 0): nz_sumb; apply: eq_bigr => z _.\nby rewrite mulrCA rmorphM -mulrBr -mulrBl mulrA.\nQed.\n\nLemma gal_independent E (P : pred (gal_of E)) (c_ : gal_of E -> L) :\n    (forall a, a \\in E -> \\sum_(x | P x) c_ x * x a = 0) ->\n  (forall x, P x -> c_ x = 0).\nProof.\nmove=> sum_cP_0 x Px; apply/eqP/idPn=> /(gal_independent_contra Px)[a Ea].\nby rewrite sum_cP_0 ?eqxx.\nQed.\n\nLemma Hilbert's_theorem_90 K E x a :\n   generator 'Gal(E / K) x -> a \\in E ->\n reflect (exists2 b, b \\in E /\\ b != 0 & a = b / x b) (galNorm K E a == 1).\nProof.\nmove/(_ =P <[x]>)=> DgalE Ea.\nhave galEx: x \\in 'Gal(E / K) by rewrite DgalE cycle_id.\napply: (iffP eqP) => [normEa1 | [b [Eb nzb] ->]]; last first.\n  by rewrite galNormM galNormV galNorm_gal // mulfV // galNorm_eq0.\nhave [x1 | ntx] := eqVneq x 1%g.\n  exists 1; first by rewrite mem1v oner_neq0.\n  by rewrite -{1}normEa1 /galNorm DgalE x1 cycle1 big_set1 !gal_id divr1.\npose c_ y := \\prod_(i < invm (injm_Zpm x) y) (x ^+ i)%g a.\nhave nz_c1: c_ 1%g != 0 by rewrite /c_ morph1 big_ord0 oner_neq0.\nhave [d] := @gal_independent_contra _ (mem 'Gal(E / K)) _ _ (group1 _) nz_c1.\nset b := \\sum_(y in _) _ => Ed nz_b; exists b.\n  split=> //; apply: rpred_sum => y galEy.\n  by apply: rpredM; first apply: rpred_prod => i _; apply: memv_gal.\napply: canRL (mulfK _) _; first by rewrite fmorph_eq0.\nrewrite rmorph_sum mulr_sumr [b](reindex_acts 'R _ galEx) ?astabsR //=.\napply: eq_bigr => y galEy; rewrite galM // rmorphM mulrA; congr (_ * _).\nhave /morphimP[/= i _ _ ->] /=: y \\in Zpm @* Zp #[x] by rewrite im_Zpm -DgalE.\nhave <-: Zpm (i + 1) = (Zpm i * x)%g by rewrite morphM ?mem_Zp ?order_gt1.\nrewrite /c_ !invmE ?mem_Zp ?order_gt1 //= addn1; set n := _.+2.\ntransitivity (\\prod_(j < i.+1) (x ^+ j)%g a).\n  rewrite big_ord_recl gal_id rmorph_prod; congr (_ * _).\n  by apply: eq_bigr => j _; rewrite expgSr galM ?lfunE.\nhave [/modn_small->//||->] := ltngtP i.+1 n; first by rewrite ltnNge ltn_ord.\nrewrite modnn big_ord0; apply: etrans normEa1; rewrite /galNorm DgalE -im_Zpm.\nrewrite morphimEdom big_imset /=; last exact/injmP/injm_Zpm.\nby apply: eq_bigl => j /=; rewrite mem_Zp ?order_gt1.\nQed.\n\nSection Matrix.\n\nVariable (E : {subfield L}) (A : {set gal_of E}).\n\nLet K := fixedField A.\n\nLemma gal_matrix :\n  {w : #|A|.-tuple L | {subset w <= E} /\\ 0 \\notin w &\n    [/\\ \\matrix_(i, j < #|A|) enum_val i (tnth w j) \\in unitmx,\n        directv (\\sum_i K * <[tnth w i]>) &\n        group_set A -> (\\sum_i K * <[tnth w i]>)%VS = E] }.\nProof.\npose nzE (w : #|A|.-tuple L) := {subset w <= E} /\\ 0 \\notin w.\npose M w := \\matrix_(i, j < #|A|) nth 1%g (enum A) i (tnth w j).\nhave [w [Ew nzw] uM]: {w : #|A|.-tuple L | nzE w & M w \\in unitmx}.\n  rewrite {}/nzE {}/M cardE; have: uniq (enum A) := enum_uniq _.\n  elim: (enum A) => [|x s IHs] Uxs.\n    by exists [tuple]; rewrite // flatmx0 -(flatmx0 1%:M) unitmx1.\n  have [s'x Us]: x \\notin s /\\ uniq s by apply/andP.\n  have{IHs} [w [Ew nzw] uM] := IHs Us; set M := \\matrix_(i, j) _ in uM.\n  pose a := \\row_i x (tnth w i) *m invmx M.\n  pose c_ y := oapp (a 0) (-1) (insub (index y s)).\n  have cx_n1 : c_ x = -1 by rewrite /c_ insubN ?index_mem.\n  have nz_cx : c_ x != 0 by rewrite cx_n1 oppr_eq0 oner_neq0.\n  have Px: [pred y in x :: s] x := mem_head x s.\n  have{Px nz_cx} /sig2W[w0 Ew0 nzS] := gal_independent_contra Px nz_cx.\n  exists [tuple of cons w0 w].\n    split; first by apply/allP; rewrite /= Ew0; apply/allP.\n    rewrite inE negb_or (contraNneq _ nzS) // => <-.\n    by rewrite big1 // => y _; rewrite rmorph0 mulr0.\n  rewrite unitmxE -[\\det _]mul1r; set M1 := \\matrix_(i, j < 1 + size s) _.\n  have <-: \\det (block_mx 1 (- a) 0 1%:M) = 1 by rewrite det_ublock !det1 mulr1.\n  rewrite -det_mulmx -[M1]submxK mulmx_block !mul0mx !mul1mx !add0r !mulNmx.\n  have ->: drsubmx M1 = M by apply/matrixP => i j; rewrite !mxE !(tnth_nth 0).\n  have ->: ursubmx M1 - a *m M = 0.\n    by apply/rowP=> i; rewrite mulmxKV // !mxE !(tnth_nth 0) subrr.\n  rewrite det_lblock unitrM andbC -unitmxE uM unitfE -oppr_eq0.\n  congr (_ != 0): nzS; rewrite [_ - _]mx11_scalar det_scalar !mxE opprB /=.\n  rewrite -big_uniq // big_cons /= cx_n1 mulN1r addrC; congr (_ + _).\n  rewrite (big_nth 1%g) big_mkord; apply: eq_bigr => j _.\n  by rewrite /c_ index_uniq // valK; congr (_ * _); rewrite !mxE.\nexists w => [//|]; split=> [||gA].\n- by congr (_ \\in unitmx): uM; apply/matrixP=> i j; rewrite !mxE -enum_val_nth.\n- apply/directv_sum_independent=> kw_ Kw_kw sum_kw_0 j _.\n  have /fin_all_exists2[k_ Kk_ Dk_] i := memv_cosetP (Kw_kw i isT).\n  pose kv := \\col_i k_ i.\n  transitivity (kv j 0 * tnth w j); first by rewrite !mxE.\n  suffices{j}/(canRL (mulKmx uM))->: M w *m kv = 0 by rewrite mulmx0 mxE mul0r.\n  apply/colP=> i; rewrite !mxE; pose Ai := nth 1%g (enum A) i.\n  transitivity (Ai (\\sum_j kw_ j)); last by rewrite sum_kw_0 rmorph0.\n  rewrite rmorph_sum; apply: eq_bigr => j _; rewrite !mxE /= -/Ai.\n  rewrite Dk_ mulrC rmorphM /=; congr (_ * _).\n  by have /mem_fixedFieldP[_ -> //] := Kk_ j; rewrite -mem_enum mem_nth -?cardE.\npose G := group gA; have G_1 := group1 G; pose iG := enum_rank_in G_1.\napply/eqP; rewrite eqEsubv; apply/andP; split.\n  apply/subv_sumP=> i _; apply: subv_trans (asubv _).\n  by rewrite prodvS ?capvSl // -memvE Ew ?mem_tnth.\napply/subvP=> w0 Ew0; apply/memv_sumP.\npose wv := \\col_(i < #|A|) enum_val i w0; pose v := invmx (M w) *m wv.\nexists (fun i => tnth w i * v i 0) => [i _|]; last first.\n  transitivity (wv (iG 1%g) 0); first by rewrite mxE enum_rankK_in ?gal_id.\n  rewrite -[wv](mulKVmx uM) -/v; rewrite mxE; apply: eq_bigr => i _.\n  by congr (_ * _); rewrite !mxE -enum_val_nth enum_rankK_in ?gal_id.\nrewrite mulrC memv_mul ?memv_line //; apply/fixedFieldP=> [|x Gx].\n  rewrite mxE rpred_sum // => j _; rewrite !mxE rpredM //; last exact: memv_gal.\n  have E_M k l: M w k l \\in E by rewrite mxE memv_gal // Ew ?mem_tnth.\n  have Edet n (N : 'M_n) (E_N : forall i j, N i j \\in E): \\det N \\in E.\n    by apply: rpred_sum => sigma _; rewrite rpredMsign rpred_prod.\n  rewrite /invmx uM 2!mxE mulrC rpred_div ?Edet //.\n  by rewrite rpredMsign Edet // => k l; rewrite 2!mxE.\nsuffices{i} {2}<-: map_mx x v = v by rewrite [map_mx x v i 0]mxE.\nhave uMx: map_mx x (M w) \\in unitmx by rewrite map_unitmx.\nrewrite map_mxM map_invmx /=; apply: canLR {uMx}(mulKmx uMx) _.\napply/colP=> i; rewrite !mxE; pose ix := iG (enum_val i * x)%g.\nhave Dix b: b \\in E -> enum_val ix b = x (enum_val i b).\n  by move=> Eb; rewrite enum_rankK_in ?groupM ?enum_valP // galM ?lfunE.\ntransitivity ((M w *m v) ix 0); first by rewrite mulKVmx // mxE Dix.\nrewrite mxE; apply: eq_bigr => j _; congr (_ * _).\nby rewrite !mxE -!enum_val_nth Dix // ?Ew ?mem_tnth.\nQed.\n\nEnd Matrix.\n\nLemma dim_fixedField E (G : {group gal_of E}) : #|G| = \\dim_(fixedField G) E.\nProof.\nhave [w [_ nzw] [_ Edirect /(_ (groupP G))defE]] := gal_matrix G.\nset n := #|G|; set m := \\dim (fixedField G); rewrite -defE (directvP Edirect).\nrewrite -[n]card_ord -(@mulnK #|'I_n| m) ?adim_gt0 //= -sum_nat_const.\ncongr (_ %/ _)%N; apply: eq_bigr => i _.\nby rewrite dim_cosetv ?(memPn nzw) ?mem_tnth.\nQed.\n\nLemma dim_fixed_galois K E (G : {group gal_of E}) :\n    galois K E -> G \\subset 'Gal(E / K) ->\n  \\dim_K (fixedField G) = #|'Gal(E / K) : G|.\nProof.\nmove=> galE sGgal; have [sFE _ _] := and3P galE; apply/eqP.\nrewrite -divgS // eqn_div ?cardSg // dim_fixedField -galois_dim //.\nby rewrite mulnC muln_divA ?divnK ?field_dimS ?capvSl -?galois_connection.\nQed.\n\nLemma gal_fixedField E (G : {group gal_of E}): 'Gal(E / fixedField G) = G.\nProof.\napply/esym/eqP; rewrite eqEcard galois_connection_subset /= (dim_fixedField G).\nrewrite galois_dim //; apply/galois_fixedField/eqP.\nrewrite eqEsubv galois_connection_subv ?capvSl //.\nby rewrite fixedFieldS ?galois_connection_subset.\nQed.\n\nLemma gal_generated E (A : {set gal_of E}) : 'Gal(E / fixedField A) = <<A>>.\nProof.\napply/eqP; rewrite eqEsubset gen_subG galois_connection_subset.\nby rewrite -[<<A>>]gal_fixedField galS // fixedFieldS // subset_gen.\nQed.\n\nLemma fixedField_galois E (A : {set gal_of E}): galois (fixedField A) E.\nProof.\nhave: galois (fixedField <<A>>) E.\n  by apply/galois_fixedField; rewrite gal_fixedField.\nby apply: galoisS; rewrite capvSl fixedFieldS // subset_gen.\nQed.\n\nSection FundamentalTheoremOfGaloisTheory.\n\nVariables E K : {subfield L}.\nHypothesis galKE : galois K E.\n\nSection IntermediateField.\n\nVariable M : {subfield L}.\nHypothesis (sKME : (K <= M <= E)%VS) (nKM : normalField K M).\n\nLemma normalField_galois : galois K M.\nProof.\nhave [[sKM sME] [_ sepKE nKE]] := (andP sKME, and3P galKE).\nby rewrite /galois sKM (separableSr sME).\nQed.\n\nDefinition normalField_cast (x : gal_of E) : gal_of M := gal M x.\n\nLemma normalField_cast_eq x :\n  x \\in 'Gal(E / K) -> {in M, normalField_cast x =1 x}.\nProof.\nhave [sKM sME] := andP sKME; have sKE := subv_trans sKM sME.\nrewrite gal_kAut // => /(normalField_kAut sKME nKM).\nby rewrite kAutE => /andP[_ /galK].\nQed.\n\nLemma normalField_castM :\n  {in 'Gal(E / K) &, {morph normalField_cast : x y / (x * y)%g}}.\nProof.\nmove=> x y galEx galEy /=; apply/eqP/gal_eqP => a Ma.\nhave Ea: a \\in E by have [_ /subvP->] := andP sKME.\nrewrite normalField_cast_eq ?groupM ?galM //=.\nby rewrite normalField_cast_eq ?memv_gal // normalField_cast_eq.\nQed.\nCanonical normalField_cast_morphism := Morphism normalField_castM.\n\nLemma normalField_ker : 'ker normalField_cast = 'Gal(E / M).\nProof.\nhave [sKM sME] := andP sKME.\napply/setP=> x; apply/idP/idP=> [kerMx | galEMx].\n  rewrite gal_kHom //; apply/kAHomP=> a Ma.\n  by rewrite -normalField_cast_eq ?(dom_ker kerMx) // (mker kerMx) gal_id.\nhave galEM: x \\in 'Gal(E / K) := subsetP (galS E sKM) x galEMx.\napply/kerP=> //; apply/eqP/gal_eqP=> a Ma.\nby rewrite normalField_cast_eq // gal_id (fixed_gal sME).\nQed.\n\nLemma normalField_normal : 'Gal(E / M) <| 'Gal(E / K).\nProof. by rewrite -normalField_ker ker_normal. Qed.\n\nLemma normalField_img : normalField_cast @* 'Gal(E / K) = 'Gal(M / K).\nProof.\nhave [[sKM sME] [sKE _ nKE]] := (andP sKME, and3P galKE).\napply/setP=> x; apply/idP/idP=> [/morphimP[{x}x galEx _ ->] | galMx].\n  rewrite gal_kHom //; apply/kAHomP=> a Ka; have Ma := subvP sKM a Ka.\n  by rewrite normalField_cast_eq // (fixed_gal sKE).\nhave /(kHom_to_gal sKME nKE)[y galEy eq_xy]: kHom K M x by rewrite -gal_kHom.\napply/morphimP; exists y => //; apply/eqP/gal_eqP => a Ha.\nby rewrite normalField_cast_eq // eq_xy.\nQed.\n\nLemma normalField_isom :\n  {f : {morphism ('Gal(E / K) / 'Gal(E / M)) >-> gal_of M} |\n     isom ('Gal(E / K) / 'Gal (E / M)) 'Gal(M / K) f\n   & (forall A, f @* (A / 'Gal(E / M)) = normalField_cast @* A)\n  /\\ {in 'Gal(E / K) & M, forall x, f (coset 'Gal (E / M) x) =1 x} }%g.\nProof.\nhave:= first_isom normalField_cast_morphism; rewrite normalField_ker.\ncase=> f injf Df; exists f; first by apply/isomP; rewrite Df normalField_img.\nsplit=> [//|x a galEx /normalField_cast_eq<- //]; congr ((_ : gal_of M) a).\napply: set1_inj; rewrite -!morphim_set1 ?mem_quotient ?Df //.\nby rewrite (subsetP (normal_norm normalField_normal)).\nQed.\n\nLemma normalField_isog : 'Gal(E / K) / 'Gal(E / M) \\isog 'Gal(M / K).\nProof. by rewrite -normalField_ker -normalField_img first_isog. Qed.\n\nEnd IntermediateField.\n\nSection IntermediateGroup.\n\nVariable G : {group gal_of E}.\nHypothesis nsGgalE : G <| 'Gal(E / K).\n\nLemma normal_fixedField_galois : galois K (fixedField G).\nProof.\nhave [[sKE sepKE nKE] [sGgal nGgal]] := (and3P galKE, andP nsGgalE).\nrewrite /galois -(galois_connection _ sKE) sGgal.\nrewrite (separableSr _ sepKE) ?capvSl //; apply/forall_inP=> f autKf.\nrewrite eqEdim limg_dim_eq ?(eqP (AEnd_lker0 _)) ?capv0 // leqnn andbT.\napply/subvP => _ /memv_imgP[a /mem_fixedFieldP[Ea cGa] ->].\nhave /kAut_to_gal[x galEx -> //]: kAut K E f.\n  rewrite /kAut (forall_inP nKE) // andbT; apply/kAHomP.\n  by move: autKf; rewrite inE kAutfE => /kHomP[].\napply/fixedFieldP=> [|y Gy]; first exact: memv_gal.\nby rewrite -galM // conjgCV galM //= cGa // memJ_norm ?groupV ?(subsetP nGgal).\nQed.\n\nEnd IntermediateGroup.\n\nEnd FundamentalTheoremOfGaloisTheory.\n\nEnd GaloisTheory.\n\nPrenex Implicits gal_repr gal gal_reprK.\nArguments gal_repr_inj {F L V} [x1 x2].\n\nNotation \"''Gal' ( V / U )\" := (galoisG V U) : group_scope.\nNotation \"''Gal' ( V / U )\" := (galoisG_group V U) : Group_scope.\n\nArguments fixedFieldP {F L E A a}.\nArguments normalFieldP {F L K E}.\nArguments splitting_galoisField {F L K E}.\nArguments galois_fixedField {F L K E}.\n", "meta": {"author": "palmskog", "repo": "mathcomp-experiment", "sha": "67a6e83c025784b1e6f646a30dde38e0f33060eb", "save_path": "github-repos/coq/palmskog-mathcomp-experiment", "path": "github-repos/coq/palmskog-mathcomp-experiment/mathcomp-experiment-67a6e83c025784b1e6f646a30dde38e0f33060eb/field/galois.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6644039765438793}}
{"text": "Require Import Psatz. \nRequire Import Reals.\n\nRequire Export Matrix.\n\n(* Using our (complex, unbounded) matrices, their complex numbers *)\n\n\n\n(*******************************************)\n(** * Quantum basis states *)\n(*******************************************)\n\n(* Maybe change to IF statements? *)\nDefinition qubit0 : Vector 2 := \n  fun x y => match x, y with \n          | 0, 0 => C1\n          | 1, 0 => C0\n          | _, _ => C0\n          end.\nDefinition qubit1 : Vector 2 := \n  fun x y => match x, y with \n          | 0, 0 => C0\n          | 1, 0 => C1\n          | _, _ => C0\n          end.\n\n(* Ket notation: \\mid 0 \\rangle *)\nNotation \"∣0⟩\" := qubit0.\nNotation \"∣1⟩\" := qubit1.\nNotation \"⟨0∣\" := qubit0†.\nNotation \"⟨1∣\" := qubit1†.\nNotation \"∣0⟩⟨0∣\" := (∣0⟩×⟨0∣).\nNotation \"∣1⟩⟨1∣\" := (∣1⟩×⟨1∣).\nNotation \"∣1⟩⟨0∣\" := (∣1⟩×⟨0∣).\nNotation \"∣0⟩⟨1∣\" := (∣0⟩×⟨1∣).\n\nDefinition bra (x : nat) : Matrix 1 2 := if x =? 0 then ⟨0∣ else ⟨1∣.\nDefinition ket (x : nat) : Matrix 2 1 := if x =? 0 then ∣0⟩ else ∣1⟩.\n\n(* Note the 'mid' symbol for these *)\nNotation \"'∣' x '⟩'\" := (ket x).\nNotation \"'⟨' x '∣'\" := (bra x). (* This gives the Coq parser headaches *)\n\nNotation \"∣ x , y , .. , z ⟩\" := (kron .. (kron ∣x⟩ ∣y⟩) .. ∣z⟩) (at level 0).\n(* Alternative: |0⟩|1⟩. *)\n                                                                       \nTransparent bra.\nTransparent ket.\nTransparent qubit0.\nTransparent qubit1.\n\nDefinition bool_to_ket (b : bool) : Matrix 2 1 := if b then ∣1⟩ else ∣0⟩.\n                                                                     \nDefinition bool_to_matrix (b : bool) : Matrix 2 2 := if b then ∣1⟩⟨1∣ else ∣0⟩⟨0∣.\n\nDefinition bool_to_matrix' (b : bool) : Matrix 2 2 := fun x y =>\n  match x, y with\n  | 0, 0 => if b then 0 else 1\n  | 1, 1 => if b then 1 else 0\n  | _, _ => 0\n  end.  \n  \nLemma bool_to_matrix_eq : forall b, bool_to_matrix b = bool_to_matrix' b.\nProof. intros. destruct b; simpl; solve_matrix. Qed.\n\nLemma bool_to_ket_matrix_eq : forall b,\n    outer_product (bool_to_ket b) (bool_to_ket b) = bool_to_matrix b.\nProof. unfold outer_product. destruct b; simpl; reflexivity. Qed.\n\nDefinition bools_to_matrix (l : list bool) : Square (2^(length l)) := \n  big_kron (map bool_to_matrix l).\n\nLemma ket_decomposition : forall (ψ : Vector 2), \n  WF_Matrix ψ ->\n  ψ = (ψ 0%nat 0%nat) .* ∣ 0 ⟩ .+ (ψ 1%nat 0%nat) .* ∣ 1 ⟩.\nProof.\n  intros.\n  prep_matrix_equality.\n  unfold scale, Mplus.\n  destruct y as [|y']. \n  2:{ rewrite H; try lia. \n      unfold ket, qubit0, qubit1. simpl. \n      repeat (destruct x; try lca). }\n  destruct x as [| [| n]]; unfold ket, qubit0, qubit1; simpl; try lca.  \n  rewrite H; try lia.\n  lca.\nQed. \n\n(****************)\n(** * Unitaries *)\n(****************)\n\nDefinition hadamard : Matrix 2 2 := \n  (fun x y => match x, y with\n          | 0, 0 => (1 / √2)\n          | 0, 1 => (1 / √2)\n          | 1, 0 => (1 / √2)\n          | 1, 1 => -(1 / √2)\n          | _, _ => 0\n          end).\n\nFixpoint hadamard_k (k : nat) : Matrix (2^k) (2^k):= \n  match k with\n  | 0 => I 1\n  | S k' => hadamard ⊗ hadamard_k k'\n  end. \n\nLemma hadamard_1 : hadamard_k 1 = hadamard.\nProof. apply kron_1_r. Qed.\n\n(* Alternative definitions:\nDefinition pauli_x : Matrix 2 2 := fun x y => if x + y =? 1 then 1 else 0.\nDefinition pauli_y : Matrix 2 2 := fun x y => if x + y =? 1 then (-1) ^ x * Ci else 0.\nDefinition pauli_z : Matrix 2 2 := fun x y => if (x =? y) && (x <? 2) \n                                           then (-1) ^ x * Ci else 0.\n*)\n\nDefinition σx : Matrix 2 2 := \n  fun x y => match x, y with\n          | 0, 1 => C1\n          | 1, 0 => C1\n          | _, _ => C0\n          end.\n\nDefinition σy : Matrix 2 2 := \n  fun x y => match x, y with\n          | 0, 1 => -Ci\n          | 1, 0 => Ci\n          | _, _ => C0\n          end.\n\nDefinition σz : Matrix 2 2 := \n  fun x y => match x, y with\n          | 0, 0 => C1\n          | 1, 1 => -C1\n          | _, _ => C0\n          end.\n  \nDefinition control {n : nat} (A : Matrix n n) : Matrix (2*n) (2*n) :=\n  fun x y => if (x <? n) && (y =? x) then 1 else \n          if (n <=? x) && (n <=? y) then A (x-n)%nat (y-n)%nat else 0.\n\n(* Definition cnot := control pauli_x. *)\n(* Direct definition makes our lives easier *)\n(* Dimensions are given their current form for convenient\n   kron_mixed_product applications *)\nDefinition cnot : Matrix (2*2) (2*2) :=\n  fun x y => match x, y with \n          | 0, 0 => C1\n          | 1, 1 => C1\n          | 2, 3 => C1\n          | 3, 2 => C1\n          | _, _ => C0\n          end.          \n\nLemma cnot_eq : cnot = control σx.\nProof.\n  unfold cnot, control, σx.\n  solve_matrix.\nQed.\n\nDefinition notc : Matrix (2*2) (2*2) :=\n  fun x y => match x, y with \n          | 1, 3 => 1%C\n          | 3, 1 => 1%C\n          | 0, 0 => 1%C\n          | 2, 2 => 1%C\n          | _, _ => 0%C\n          end.          \n\n(* Swap Matrices *)\n\nDefinition swap : Matrix (2*2) (2*2) :=\n  fun x y => match x, y with\n          | 0, 0 => C1\n          | 1, 2 => C1\n          | 2, 1 => C1\n          | 3, 3 => C1\n          | _, _ => C0\n          end.\n\nHint Unfold qubit0 qubit1 hadamard σx σy σz control cnot swap bra ket : U_db.\n\n(** ** Rotation Matrices *)\n                              \n(* Standard(?) definition, but it makes equivalence-checking a little annoying \n   because of a global phase.\n\nDefinition rotation (θ ϕ λ : R) : Matrix 2 2 :=\n  fun x y => match x, y with\n             | 0, 0 => (Cexp (-(ϕ + λ)/2)) * (cos (θ/2))\n             | 0, 1 => - (Cexp (-(ϕ - λ)/2)) * (sin (θ/2))\n             | 1, 0 => (Cexp ((ϕ - λ)/2)) * (sin (θ/2))\n             | 1, 1 => (Cexp ((ϕ + λ)/2)) * (cos (θ/2))\n             | _, _ => C0\n             end.\n*)\nDefinition rotation (θ ϕ λ : R) : Matrix 2 2 :=\n  fun x y => match x, y with\n             | 0, 0 => (cos (θ/2))\n             | 0, 1 => - (Cexp λ) * (sin (θ/2))\n             | 1, 0 => (Cexp ϕ) * (sin (θ/2))\n             | 1, 1 => (Cexp (ϕ + λ)) * (cos (θ/2))\n             | _, _ => C0\n             end.\n\n(* z_rotation lemmas are further down *)\nDefinition phase_shift (ϕ : R) : Matrix 2 2 :=\n  fun x y => match x, y with\n          | 0, 0 => C1\n          | 1, 1 => Cexp ϕ\n          | _, _ => C0\n          end.\n\n(* Notation z_rotation := phase_shift. *)\n\nDefinition x_rotation  (θ : R) : Matrix 2 2 :=\n  fun x y => match x, y with\n          | 0, 0 => cos (θ / 2)\n          | 0, 1 => -Ci * sin (θ / 2)\n          | 1, 0 => -Ci * sin (θ / 2)\n          | 1, 1 => cos (θ / 2)\n          | _, _ => 0\n          end.\n\nDefinition y_rotation  (θ : R) : Matrix 2 2 :=\n  fun x y => match x, y with\n          | 0, 0 => cos (θ / 2)\n          | 0, 1 => - sin (θ / 2)\n          | 1, 0 => sin (θ / 2)\n          | 1, 1 => cos (θ / 2)\n          | _, _ => 0\n          end.\n\n(* Shifted by i so x/y_rotation PI = σx/y :\nDefinition x_rotation  (θ : R) : Matrix 2 2 :=\n  fun x y => match x, y with\n          | 0, 0 => Ci * cos (θ / 2)\n          | 0, 1 => sin (θ / 2)\n          | 1, 0 => sin (θ / 2)\n          | 1, 1 => Ci * cos (θ / 2)\n          | _, _ => 0\n          end.\n\nDefinition y_rotation  (θ : R) : Matrix 2 2 :=\n  fun x y => match x, y with\n          | 0, 0 => Ci * cos (θ / 2)\n          | 0, 1 => -Ci * sin (θ / 2)\n          | 1, 0 => Ci * sin (θ / 2)\n          | 1, 1 => Ci * cos (θ / 2)\n          | _, _ => 0\n          end.\n *)\n\nLemma x_rotation_pi : x_rotation PI = -Ci .* σx.\nProof.\n  unfold σx, x_rotation, scale.\n  prep_matrix_equality.\n  destruct_m_eq; \n  autorewrite with trig_db C_db;\n  reflexivity. \nQed.\n\nLemma y_rotation_pi : y_rotation PI = -Ci .* σy.\nProof.\n  unfold σy, y_rotation, scale. \n  prep_matrix_equality.\n  destruct_m_eq; \n  autorewrite with trig_db C_db;\n  try reflexivity. \nQed.\n\nLemma hadamard_rotation : rotation (PI/2) 0 PI = hadamard.\nProof.\n  unfold hadamard, rotation. \n  prep_matrix_equality.\n  destruct_m_eq; try reflexivity; \n  unfold Cexp; apply injective_projections; simpl;\n  autorewrite with R_db;\n  autorewrite with trig_db;\n  autorewrite with R_db;\n  try reflexivity.\n  all: rewrite Rmult_assoc;\n       replace (/2 * /2)%R with (/4)%R by lra;\n       repeat rewrite <- Rdiv_unfold;\n       autorewrite with trig_db;\n       rewrite sqrt2_div2;\n       lra.\nQed.\n\nLemma pauli_x_rotation : rotation PI 0 PI = σx.\nProof.\n  unfold σx, rotation. \n  prep_matrix_equality.\n  destruct_m_eq; try reflexivity;\n  unfold Cexp; apply injective_projections; simpl;\n  autorewrite with trig_db;\n  lra.\nQed.\n\nLemma pauli_y_rotation : rotation PI (PI/2) (PI/2) = σy.\nProof. \n  unfold σy, rotation. \n  prep_matrix_equality.\n  destruct_m_eq; try reflexivity;\n  unfold Cexp; apply injective_projections; simpl;\n  autorewrite with trig_db;\n  lra.\nQed.\n\nLemma pauli_z_rotation : rotation 0 0 PI = σz.\nProof. \n  unfold σz, rotation. \n  prep_matrix_equality.\n  destruct_m_eq; try reflexivity;\n  unfold Cexp; apply injective_projections; simpl;\n  autorewrite with R_db;\n  autorewrite with trig_db;\n  lra.\nQed.\n\nLemma Rx_rotation : forall θ, rotation θ (3*PI/2) (PI/2) = x_rotation θ.\nProof.\n  intros.\n  unfold rotation, x_rotation. \n  prep_matrix_equality.\n  destruct_m_eq;\n  autorewrite with C_db Cexp_db; reflexivity.\nQed.\n\nLemma Ry_rotation : forall θ, rotation θ 0 0 = y_rotation θ.\nProof. \n  intros.\n  unfold rotation, y_rotation. \n  prep_matrix_equality.\n  destruct_m_eq;\n  autorewrite with C_db Cexp_db; try reflexivity.\nQed.\n\n\nLemma phase_shift_rotation : forall θ, rotation 0 0 θ = phase_shift θ.\nProof. \n  intros.\n  unfold phase_shift, rotation. \n  prep_matrix_equality.\n  destruct_m_eq; try reflexivity;\n  unfold Cexp; apply injective_projections; simpl;\n  autorewrite with R_db;\n  autorewrite with trig_db;\n  lra.\nQed.\n\nLemma I_rotation : rotation 0 0 0 = I 2.\nProof.\n  unfold I, rotation. \n  prep_matrix_equality.\n  destruct_m_eq; try reflexivity;\n  unfold Cexp; apply injective_projections; simpl;\n  autorewrite with R_db;\n  autorewrite with trig_db;\n  autorewrite with R_db;\n  try reflexivity.\n  bdestruct (x =? y); bdestruct (S (S x) <? 2); simpl; try reflexivity; lia.\n  destruct (x =? y); destruct (S (S x) <? 2); reflexivity.\nQed.\n\n\n(* Lemmas *)\n\n(* Additional tactics for ∣0⟩, ∣1⟩, cnot and σx. *)\n\nLemma Mmult00 : ⟨0∣ × ∣0⟩ = I 1. Proof. solve_matrix. Qed.\nLemma Mmult01 : ⟨0∣ × ∣1⟩ = Zero. Proof. solve_matrix. Qed.\nLemma Mmult10 : ⟨1∣ × ∣0⟩ = Zero. Proof. solve_matrix. Qed.\nLemma Mmult11 : ⟨1∣ × ∣1⟩ = I 1. Proof. solve_matrix. Qed.\n\nLemma MmultX1 : σx × ∣1⟩ = ∣0⟩. Proof. solve_matrix. Qed.\nLemma Mmult1X : ⟨1∣ × σx = ⟨0∣. Proof. solve_matrix. Qed.\nLemma MmultX0 : σx × ∣0⟩ = ∣1⟩. Proof. solve_matrix. Qed.\nLemma Mmult0X : ⟨0∣ × σx = ⟨1∣. Proof. solve_matrix. Qed.\n\nLemma MmultXX : σx × σx = I 2. Proof. solve_matrix. Qed.\nLemma MmultYY : σy × σy = I 2. Proof. solve_matrix. Qed.\nLemma MmultZZ : σz × σz = I 2. Proof. solve_matrix. Qed.\nLemma MmultHH : hadamard × hadamard = I 2. Proof. solve_matrix. Qed.\nLemma Mplus01 : ∣0⟩⟨0∣ .+ ∣1⟩⟨1∣ = I 2. Proof. solve_matrix. Qed.\nLemma Mplus10 : ∣1⟩⟨1∣ .+ ∣0⟩⟨0∣ = I 2. Proof. solve_matrix. Qed.\n                            \nLemma σx_on_right0 : forall (q : Vector 2), (q × ⟨0∣) × σx = q × ⟨1∣.\nProof. intros. rewrite Mmult_assoc, Mmult0X. reflexivity. Qed.\n\nLemma σx_on_right1 : forall (q : Vector 2), (q × ⟨1∣) × σx = q × ⟨0∣.\nProof. intros. rewrite Mmult_assoc, Mmult1X. reflexivity. Qed.\n\nLemma σx_on_left0 : forall (q : Matrix 1 2), σx × (∣0⟩ × q) = ∣1⟩ × q.\nProof. intros. rewrite <- Mmult_assoc, MmultX0. reflexivity. Qed.\n\nLemma σx_on_left1 : forall (q : Matrix 1 2), σx × (∣1⟩ × q) = ∣0⟩ × q.\nProof. intros. rewrite <- Mmult_assoc, MmultX1. reflexivity. Qed.\n\nLemma cancel00 : forall (q1 : Matrix 2 1) (q2 : Matrix 1 2), \n  WF_Matrix q2 ->\n  (q1 × ⟨0∣) × (∣0⟩ × q2) = q1 × q2.\nProof. \n  intros. \n  rewrite Mmult_assoc. \n  rewrite <- (Mmult_assoc ⟨0∣).\n  rewrite Mmult00.             \n  Msimpl; reflexivity.\nQed.\n\nLemma cancel01 : forall (q1 : Matrix 2 1) (q2 : Matrix 1 2), \n  (q1 × ⟨0∣) × (∣1⟩ × q2) = Zero.\nProof. \n  intros. \n  rewrite Mmult_assoc. \n  rewrite <- (Mmult_assoc ⟨0∣).\n  rewrite Mmult01.             \n  Msimpl_light; reflexivity.\nQed.\n\nLemma cancel10 : forall (q1 : Matrix 2 1) (q2 : Matrix 1 2), \n  (q1 × ⟨1∣) × (∣0⟩ × q2) = Zero.\nProof. \n  intros. \n  rewrite Mmult_assoc. \n  rewrite <- (Mmult_assoc ⟨1∣).\n  rewrite Mmult10.             \n  Msimpl_light; reflexivity.\nQed.\n\nLemma cancel11 : forall (q1 : Matrix 2 1) (q2 : Matrix 1 2), \n  WF_Matrix q2 ->\n  (q1 × ⟨1∣) × (∣1⟩ × q2) = q1 × q2.\nProof. \n  intros. \n  rewrite Mmult_assoc. \n  rewrite <- (Mmult_assoc ⟨1∣).\n  rewrite Mmult11.             \n  Msimpl; reflexivity.\nQed.\n\nHint Rewrite Mmult00 Mmult01 Mmult10 Mmult11 Mmult0X MmultX0 Mmult1X MmultX1 : Q_db.\nHint Rewrite MmultXX MmultYY MmultZZ MmultHH Mplus01 Mplus10 : Q_db.\nHint Rewrite σx_on_right0 σx_on_right1 σx_on_left0 σx_on_left1 : Q_db.\nHint Rewrite cancel00 cancel01 cancel10 cancel11 using (auto with wf_db) : Q_db.\n\nLemma swap_swap : swap × swap = I (2*2). Proof. solve_matrix. Qed.\n\nLemma swap_swap_r : forall (A : Matrix (2*2) (2*2)), \n  WF_Matrix A ->\n  A × swap × swap = A.\nProof.\n  intros.\n  rewrite Mmult_assoc.\n  rewrite swap_swap.\n  Msimpl.\n  reflexivity.\nQed.\n\nHint Rewrite swap_swap swap_swap_r using (auto 100 with wf_db): Q_db.\n\n\n\n(* The input k is really k+1, to appease to Coq termination gods *)\n(* NOTE: Check that the offsets are right *)\n(* Requires: i + 1 < n *)\nFixpoint swap_to_0_aux (n i : nat) {struct i} : Matrix (2^n) (2^n) := \n  match i with\n  | O => swap ⊗ I (2^(n-2))\n  | S i' =>  (I (2^i) ⊗ swap ⊗ I (2^(n-i-2))) × (* swap i-1 with i *)\n            swap_to_0_aux n i' × \n            (I (2^i) ⊗ swap ⊗ I (2^(n-i-2))) (* swap i-1 with 0 *)\n  end.\n\n(* Requires: i < n *)\nDefinition swap_to_0 (n i : nat) : Matrix (2^n) (2^n) := \n  match i with \n  | O => I (2^n) \n  | S i' => swap_to_0_aux n i'\n  end.\n  \n(* Swapping qubits i and j in an n-qubit system, where i < j *) \n(* Requires i < j, j < n *)\nFixpoint swap_two_aux (n i j : nat) : Matrix (2^n) (2^n) := \n  match i with \n  | O => swap_to_0 n j \n  | S i' => I 2 ⊗ swap_two_aux (n-1) (i') (j-1)\n  end.\n\n(* Swapping qubits i and j in an n-qubit system *)\n(* Requires i < n, j < n *)\nDefinition swap_two (n i j : nat) : Matrix (2^n) (2^n) :=\n  if i =? j then I (2^n) \n  else if i <? j then swap_two_aux n i j\n  else swap_two_aux n j i.\n\n(* Simpler version of swap_to_0 that shifts other elements *)\n(* Requires: i+1 < n *)\nFixpoint move_to_0_aux (n i : nat) {struct i}: Matrix (2^n) (2^n) := \n  match i with\n  | O => swap ⊗ I (2^(n-2))\n  | S i' => (move_to_0_aux n i') × (I (2^i) ⊗ swap ⊗ I (2^(n-i-2))) \n                  \n  end.\n             \n(* Requires: i < n *)\nDefinition move_to_0 (n i : nat) : Matrix (2^n) (2^n) := \n  match i with \n  | O => I (2^n) \n  | S i' => move_to_0_aux n i'\n  end.\n \n(* Always moves up in the matrix from i to k *)\n(* Requires: k < i < n *)\nFixpoint move_to (n i k : nat) : Matrix (2^n) (2^n) := \n  match k with \n  | O => move_to_0 n i \n  | S k' => I 2 ⊗ move_to (n-1) (i-1) (k')\n  end.\n\n(*\nEval compute in ((swap_two 1 0 1) 0 0)%nat.\nEval compute in (print_matrix (swap_two 1 0 2)).\n*)\n\n(** Well Formedness of Quantum States and Unitaries **)\n\nLemma WF_bra0 : WF_Matrix ⟨0∣. Proof. show_wf. Qed. \nLemma WF_bra1 : WF_Matrix ⟨1∣. Proof. show_wf. Qed.\nLemma WF_qubit0 : WF_Matrix ∣0⟩. Proof. show_wf. Qed.\nLemma WF_qubit1 : WF_Matrix ∣1⟩. Proof. show_wf. Qed.\nLemma WF_braqubit0 : WF_Matrix ∣0⟩⟨0∣. Proof. show_wf. Qed.\nLemma WF_braqubit1 : WF_Matrix ∣1⟩⟨1∣. Proof. show_wf. Qed.\n\nLemma WF_bra : forall (x : nat), WF_Matrix (bra x).\nProof. intros x. unfold bra. destruct (x =? 0). show_wf. show_wf. \nQed. \n\nLemma WF_ket : forall (x : nat), WF_Matrix (ket x).\nProof. intros x. unfold ket. destruct (x =? 0). show_wf. show_wf. \nQed. \n\nLemma WF_bool_to_ket : forall b, WF_Matrix (bool_to_ket b). \nProof. destruct b; show_wf. Qed.\nLemma WF_bool_to_matrix : forall b, WF_Matrix (bool_to_matrix b).\nProof. destruct b; show_wf. Qed.\nLemma WF_bool_to_matrix' : forall b, WF_Matrix (bool_to_matrix' b).\nProof. destruct b; show_wf. Qed.\n\nLemma WF_bools_to_matrix : forall l, \n  @WF_Matrix (2^(length l)) (2^(length l))  (bools_to_matrix l).\nProof. \n  induction l; auto with wf_db.\n  unfold bools_to_matrix in *; simpl.\n  apply WF_kron; try rewrite map_length; try lia.\n  apply WF_bool_to_matrix.\n  apply IHl.\nQed.\n\nHint Resolve WF_bra0 WF_bra1 WF_qubit0 WF_qubit1 WF_bra WF_ket WF_braqubit0 WF_braqubit1 : wf_db.\nHint Resolve WF_bool_to_ket WF_bool_to_matrix WF_bool_to_matrix' : wf_db.\nHint Resolve WF_bools_to_matrix : wf_db.\n\nLemma WF_hadamard : WF_Matrix hadamard. Proof. show_wf. Qed.\nLemma WF_σx : WF_Matrix σx. Proof. show_wf. Qed.\nLemma WF_σy : WF_Matrix σy. Proof. show_wf. Qed.\nLemma WF_σz : WF_Matrix σz. Proof. show_wf. Qed.\nLemma WF_cnot : WF_Matrix cnot. Proof. show_wf. Qed.\nLemma WF_swap : WF_Matrix swap. Proof. show_wf. Qed.\n\nLemma WF_rotation : forall θ ϕ λ, WF_Matrix (rotation θ ϕ λ). Proof. intros. show_wf. Qed.\nLemma WF_phase : forall ϕ, WF_Matrix (phase_shift ϕ). Proof. intros. show_wf. Qed.\n\n\nLemma WF_control : forall (n : nat) (U : Matrix n n), \n      WF_Matrix U -> WF_Matrix (control U).\nProof.\n  intros n U WFU.\n  unfold control, WF_Matrix in *.\n  intros x y [Hx | Hy];\n  bdestruct (x <? n); bdestruct (y =? x); bdestruct (n <=? x); bdestruct (n <=? y);\n    simpl; try reflexivity; try lia. \n  all: rewrite WFU; [reflexivity|lia].\nQed.\n\nHint Resolve WF_hadamard WF_σx WF_σy WF_σz WF_cnot WF_swap WF_phase : wf_db.\nHint Resolve WF_rotation : wf_db.\n\nHint Extern 2 (WF_Matrix (phase_shift _)) => apply WF_phase : wf_db.\nHint Extern 2 (WF_Matrix (control _)) => apply WF_control : wf_db.\n\n(***************************)\n(** Unitaries are unitary **)\n(***************************)\n\n(* For this section, we could just convert all single-qubit unitaries into their \n   rotation form and use rotation_unitary. *)\n\nDefinition WF_Unitary {n: nat} (U : Matrix n n): Prop :=\n  WF_Matrix U /\\ U † × U = I n.\n\nHint Unfold WF_Unitary : U_db.\n\n(* More precise *)\n(* Definition unitary_matrix' {n: nat} (A : Matrix n n): Prop := Minv A A†. *)\n\nLemma H_unitary : WF_Unitary hadamard.\nProof.\n  split.\n  show_wf.\n  unfold Mmult, I.\n  prep_matrix_equality.\n  autounfold with U_db.\n  destruct x as [| [|x]]; destruct y as [|[|y]]; simpl; autorewrite with C_db; \n    try reflexivity.\n  replace ((S (S x) <? 2)) with false by reflexivity.\n  rewrite andb_false_r.\n  reflexivity.\nQed.\n\nLemma σx_unitary : WF_Unitary σx.\nProof. \n  split.\n  show_wf.\n  unfold Mmult, I.\n  prep_matrix_equality.\n  destruct x as [| [|x]]; destruct y as [|[|y]]; try lca.\n  simpl.\n  replace ((S (S x) <? 2)) with false by reflexivity.\n  rewrite andb_false_r.\n  lca.\nQed.\n\nLemma σy_unitary : WF_Unitary σy.\nProof.\n  split.\n  show_wf.\n  unfold Mmult, I.\n  prep_matrix_equality.\n  destruct x as [| [|x]]; destruct y as [|[|y]]; try lca.\n  simpl.\n  replace ((S (S x) <? 2)) with false by reflexivity.\n  rewrite andb_false_r.\n  lca.\nQed.\n\nLemma σz_unitary : WF_Unitary σz.\nProof.\n  split.\n  show_wf.\n  unfold Mmult, I.\n  prep_matrix_equality.\n  destruct x as [| [|x]]; destruct y as [|[|y]]; try lca.\n  simpl.\n  replace ((S (S x) <? 2)) with false by reflexivity.\n  rewrite andb_false_r.\n  lca.\nQed.\n\nLemma phase_unitary : forall ϕ, @WF_Unitary 2 (phase_shift ϕ).\nProof.\n  intros ϕ.\n  split; [show_wf|].\n  unfold Mmult, I, phase_shift, adjoint, Cexp.\n  prep_matrix_equality.\n  destruct x as [| [|x]]; destruct y as [|[|y]]; try lca.\n  - simpl.\n    Csimpl.\n    unfold Cconj, Cmult.\n    simpl.\n    unfold Rminus.\n    rewrite Ropp_mult_distr_l.\n    rewrite Ropp_involutive.\n    replace (cos ϕ * cos ϕ)%R with ((cos ϕ)²) by easy.\n    replace (sin ϕ * sin ϕ)%R with ((sin ϕ)²) by easy. \n    rewrite Rplus_comm.\n    rewrite sin2_cos2.\n    lca.\n  - simpl. Csimpl.\n    replace ((S (S x) <? 2)) with false by reflexivity.\n    rewrite andb_false_r.\n    lca.\nQed.\n\nLemma rotation_unitary : forall θ ϕ λ, @WF_Unitary 2 (rotation θ ϕ λ).\nProof.\n  intros.\n  split; [show_wf|].\n  unfold Mmult, I, rotation, adjoint, Cexp.\n  prep_matrix_equality.\n  destruct_m_eq; try lca;\n  unfold Cexp, Cconj;\n  apply injective_projections; simpl;\n  autorewrite with R_db;\n  try lra.\n  (* some general rewriting *)\n  all: (repeat rewrite <- Rmult_assoc;\n        repeat rewrite Ropp_mult_distr_l;\n        repeat rewrite <- Rmult_plus_distr_r;\n        repeat rewrite Rmult_assoc;\n        repeat rewrite (Rmult_comm (cos (θ * / 2)));\n        repeat rewrite (Rmult_comm (sin (θ * / 2)));\n        repeat rewrite <- Rmult_assoc;\n        repeat rewrite <- Rmult_plus_distr_r).\n  (* all the cases are about the same; just setting up applications of\n     cos_minus/sin_minus and simplifying *)\n  all: repeat rewrite <- cos_minus.\n  3: (rewrite (Rmult_comm (cos ϕ));\n      rewrite <- (Ropp_mult_distr_l (sin ϕ));\n      rewrite (Rmult_comm (sin ϕ));\n      rewrite <- Rminus_unfold).\n  5: (rewrite (Rmult_comm _ (cos ϕ));\n      rewrite (Rmult_comm _ (sin ϕ));\n      rewrite <- Ropp_mult_distr_r;\n      rewrite <- Rminus_unfold).\n  all: try rewrite <- sin_minus.\n  all: autorewrite with R_db.\n  all: repeat rewrite Rplus_opp_r.\n  all: try (rewrite Ropp_plus_distr;\n            repeat rewrite <- Rplus_assoc;\n            rewrite Rplus_opp_r).\n  all: try (rewrite (Rplus_comm ϕ λ);\n            rewrite Rplus_assoc;\n            rewrite Rplus_opp_r).\n  all: (autorewrite with R_db;\n        autorewrite with trig_db;\n        autorewrite with R_db).\n  all: try lra.\n  all: try (replace (cos (θ * / 2) * cos (θ * / 2))%R with ((cos (θ * / 2))²) by easy;\n            replace (sin (θ * / 2) * sin (θ * / 2))%R with ((sin (θ * / 2))²) by easy).\n  1: rewrite Rplus_comm.\n  all: try (rewrite sin2_cos2; reflexivity).\n  (* two weird left-over cases *)\n  all: (destruct ((x =? y) && (S (S x) <? 2)) eqn:E;\n        try reflexivity).\n  apply andb_prop in E as [_ E].\n  apply Nat.ltb_lt in E; lia.\nQed.\n\nLemma x_rotation_unitary : forall θ, @WF_Unitary 2 (x_rotation θ).\nProof. intros. rewrite <- Rx_rotation. apply rotation_unitary. Qed.\n\nLemma y_rotation_unitary : forall θ, @WF_Unitary 2 (y_rotation θ).\nProof. intros. rewrite <- Ry_rotation. apply rotation_unitary. Qed.\n\n(* caused errors so commenting out for now:\n\n Lemma control_unitary : forall n (A : Matrix n n), \n                          WF_Unitary A -> WF_Unitary (control A). \nProof.\n  intros n A H.\n  destruct H as [WF U].\n  split; auto with wf_db.\n  unfold control, adjoint, Mmult, I.\n  prep_matrix_equality.\n  simpl.\n  bdestruct (x =? y).\n  - subst; simpl.\n    rewrite Csum_sum.\n    bdestruct (y <? n + (n + 0)).\n    + bdestruct (n <=? y).\n      * rewrite Csum_0_bounded. Csimpl.\n        rewrite (Csum_eq _ (fun x => A x (y - n)%nat ^* * A x (y - n)%nat)).\n        ++ unfold control, adjoint, Mmult, I in U.\n           rewrite Nat.add_0_r.\n           eapply (equal_f) in U. \n           eapply (equal_f) in U. \n           rewrite U.\n           rewrite Nat.eqb_refl. simpl.\n           bdestruct (y - n <? n).\n           easy.\n        ++ apply functional_extensionality. intros x.\n           bdestruct (n + x <? n).\n           bdestruct (n <=? n + x).\n           rewrite minus_plus.\n           easy.\n        ++ intros x L.\n           bdestruct (y =? x).\n           rewrite andb_false_r.\n           bdestructΩ (n <=? x).\n           simpl. lca.\n      * rewrite (Csum_unique 1). \n        rewrite Csum_0_bounded.\n        ++ lca.\n        ++ intros.\n           rewrite andb_false_r.\n           bdestruct (n + x <? n).\n           simpl.\n           lca.\n        ++ exists y.\n           repeat rewrite andb_false_r.\n           split. easy.\n           split. \n           rewrite Nat.eqb_refl.\n           bdestructΩ (y <? n).\n           simpl. lca.\n           intros x Ne.\n           bdestruct (y =? x ).\n           repeat rewrite andb_false_r.\n           lca.\n    + rewrite 2 Csum_0_bounded; [lca| |].\n      * intros x L.\n        rewrite WF by (right; lia).\n        bdestructΩ (n + x <? n).\n        bdestructΩ (n <=? n + x).\n        bdestructΩ (n <=? y).\n        lca.\n      * intros x L.\n        bdestructΩ (y =? x).\n        rewrite andb_false_r.\n        bdestructΩ (n <=? x).\n        simpl. lca.\n  - simpl.\n    rewrite Csum_sum.\n    bdestructΩ (y <? n + (n + 0)).\n    + bdestructΩ (n <=? y).\n      * rewrite Csum_0_bounded. Csimpl.\n        bdestructΩ (n <=? x).\n        rewrite (Csum_eq _ (fun z => A z (x - n)%nat ^* * A z (y - n)%nat)).\n        ++ unfold control, adjoint, Mmult, I in U.\n           rewrite Nat.add_0_r.\n           eapply (equal_f) in U. \n           eapply (equal_f) in U. \n           rewrite U.\n           bdestructΩ (x - n =? y - n).\n           simpl.\n           easy.\n        ++ apply functional_extensionality. intros z.\n           bdestructΩ (n + z <? n).\n           bdestructΩ (n <=? n + z).\n           rewrite minus_plus.\n           easy.\n        ++ rewrite Csum_0. easy.\n           intros z.\n           bdestructΩ (n + z <? n).\n           rewrite andb_false_r.\n           Csimpl. easy. \n        ++ intros z L.\n           bdestructΩ (z <? n).\n           bdestructΩ (n <=? z).\n           bdestructΩ (x =? z); bdestructΩ (y =? z); try lca. \n      * bdestructΩ (n <=? x).        \n        ++ rewrite Csum_0_bounded.\n           rewrite Csum_0_bounded. lca.\n           ** intros z L.\n              bdestructΩ (n + z <? n).\n              rewrite andb_false_r.\n              lca.\n           ** intros z L.\n              bdestructΩ (z <? n).\n              rewrite andb_false_r.\n              bdestructΩ (x =? z); bdestructΩ (y =? z); try lca.\n              bdestructΩ (n <=? z).\n              lca.\n        ++ rewrite 2 Csum_0_bounded; [lca| |].\n           ** intros z L.\n              rewrite andb_false_r.\n              bdestructΩ (x =? n + z); bdestructΩ (y =? n + z); rewrite andb_false_r; lca.\n           ** intros z L.\n              rewrite andb_false_r.\n              bdestructΩ (x =? z); bdestructΩ (y =? z); rewrite andb_false_r; lca.\n    + rewrite 2 Csum_0_bounded; [lca| |].\n      * intros z L.\n        bdestructΩ (n + z <? n). \n        bdestructΩ (n <=? n + z). \n        bdestructΩ (n <=? y).\n        rewrite (WF _ (y-n)%nat) by (right; lia).\n        lca.\n      * intros z L.\n        bdestructΩ (y =? z).\n        rewrite andb_false_r.\n        rewrite (WF _ (y-n)%nat) by (right; lia).\n        destruct ((n <=? z) && (n <=? y)); lca.\nQed. *)\n\nLemma transpose_unitary : forall n (A : Matrix n n), WF_Unitary A -> WF_Unitary (A†).\nProof.\n  intros. \n  simpl.\n  split.\n  + destruct H; auto with wf_db.\n  + unfold WF_Unitary in *.\n    rewrite adjoint_involutive.\n    destruct H as [H H0].\n    apply Minv_left in H0 as [_ S]; auto with wf_db.\nQed.\n\n\nLemma cnot_unitary : WF_Unitary cnot.\nProof.\n  split. \n  apply WF_cnot.\n  unfold Mmult, I.\n  prep_matrix_equality.\n  do 4 (try destruct x; try destruct y; try lca).\n  replace ((S (S (S (S x))) <? 4)) with (false) by reflexivity.\n  rewrite andb_false_r.\n  lca.\nQed.\n\nLemma id_unitary : forall n, WF_Unitary (I n). \nProof.\n  split.\n  apply WF_I.\n  unfold WF_Unitary.\n  rewrite id_adjoint_eq.\n  apply Mmult_1_l.\n  apply WF_I.\nQed.\n\nLemma swap_unitary : WF_Unitary swap.\nProof. \n  split.\n  apply WF_swap.\n  unfold WF_Unitary, Mmult, I.\n  prep_matrix_equality.\n  do 4 (try destruct x; try destruct y; try lca).\n  replace ((S (S (S (S x))) <? 4)) with (false) by reflexivity.\n  rewrite andb_false_r.\n  lca.\nQed.\n\nLemma zero_not_unitary : forall n, ~ (WF_Unitary (@Zero (2^n) (2^n))).\nProof.\n  intros n.\n  intros F.\n  destruct F as [_ U].\n  apply (f_equal2_inv 0 0)%nat in U.\n  revert U.\n  rewrite Mmult_0_r.\n  unfold I, Zero.\n  simpl.\n  bdestruct (0 <? 2 ^ n).\n  intros F. inversion F. lra.\n  specialize (pow_positive 2 n) as P.\n  lia.\nQed.\n\nLemma kron_unitary : forall {m n} (A : Matrix m m) (B : Matrix n n),\n  WF_Unitary A -> WF_Unitary B -> WF_Unitary (A ⊗ B).\nProof.\n  intros m n A B [WFA UA] [WFB UB].\n  unfold WF_Unitary in *.\n  split.\n  auto with wf_db.\n  rewrite kron_adjoint.\n  rewrite kron_mixed_product.\n  rewrite UA, UB.\n  rewrite id_kron. \n  easy.\nQed.\n\nLemma Mmult_unitary : forall (n : nat) (A : Square n) (B : Square n),\n  WF_Unitary A ->\n  WF_Unitary B ->\n  WF_Unitary (A × B).  \nProof.\n  intros n A B [WFA UA] [WFB UB].\n  split.\n  auto with wf_db.\n  Msimpl.\n  rewrite Mmult_assoc.\n  rewrite <- (Mmult_assoc A†).\n  rewrite UA.\n  Msimpl.\n  apply UB.\nQed.\n\n(********************)\n(* Self-adjointness *)\n(********************)\n\n(* Maybe change to \"Hermitian?\" *)\n\nDefinition id_sa := id_adjoint_eq.\n\nLemma hadamard_sa : hadamard† = hadamard.\nProof.\n  prep_matrix_equality.\n  repeat (try destruct x; try destruct y; try lca; trivial).\nQed.\n\nLemma σx_sa : σx† = σx.\nProof. \n  prep_matrix_equality. \n  repeat (try destruct x; try destruct y; try lca; trivial).\nQed.\n\nLemma σy_sa : σy† = σy.\nProof.\n  prep_matrix_equality. \n  repeat (try destruct x; try destruct y; try lca; trivial).\nQed.\n\nLemma σz_sa : σz† = σz.\nProof.\n  prep_matrix_equality. \n  repeat (try destruct x; try destruct y; try lca; trivial).\nQed.\n\nLemma cnot_sa : cnot† = cnot.\nProof.\n  prep_matrix_equality. \n  repeat (try destruct x; try destruct y; try lca; trivial).\nQed.\n\nLemma swap_sa : swap† = swap.\nProof.\n  prep_matrix_equality. \n  repeat (try destruct x; try destruct y; try lca; trivial).\nQed.\n\nLemma control_adjoint : forall n (U : Square n), (control U)† = control (U†).\nProof.\n  intros n U.\n  unfold control, adjoint.\n  prep_matrix_equality.\n  rewrite Nat.eqb_sym.\n  bdestruct (y =? x). \n  - subst.\n    bdestruct (x <? n); bdestruct (n <=? x); try lia; simpl; lca.\n  - rewrite 2 andb_false_r.\n    rewrite andb_comm.\n    rewrite (if_dist _ _ _ Cconj).\n    rewrite Cconj_0.\n    reflexivity.\nQed.\n\nLemma control_sa : forall (n : nat) (A : Square n), \n    A† = A -> (control A)† = (control A).\nProof.\n  intros n A H.\n  rewrite control_adjoint.\n  rewrite H.\n  easy.\nQed.  \n\nLemma phase_adjoint : forall ϕ, (phase_shift ϕ)† = phase_shift (-ϕ). \nProof.\n  intros ϕ.\n  unfold phase_shift, adjoint.\n  prep_matrix_equality.\n  destruct_m_eq; try lca.\n  unfold Cexp, Cconj. \n  rewrite cos_neg, sin_neg.\n  easy.\nQed.\n\n(* x and y rotation adjoints aren't x and rotations? *)\n\nLemma rotation_adjoint : forall θ ϕ λ, (rotation θ ϕ λ)† = rotation (-θ) (-λ) (-ϕ).\nProof.\n  intros.\n  unfold rotation, adjoint.\n  prep_matrix_equality.\n  destruct_m_eq; try lca;\n  unfold Cexp, Cconj;\n  apply injective_projections; simpl;\n  try rewrite <- Ropp_plus_distr;\n  autorewrite with R_db;\n  autorewrite with trig_db;\n  try rewrite (Rplus_comm λ ϕ);\n  autorewrite with R_db;\n  reflexivity.\nQed.\n\nLemma braqubit0_sa : ∣0⟩⟨0∣† = ∣0⟩⟨0∣. Proof. lma. Qed.\nLemma braqubit1_sa : ∣1⟩⟨1∣† = ∣1⟩⟨1∣. Proof. lma. Qed.\n\nHint Rewrite hadamard_sa σx_sa σy_sa σz_sa cnot_sa swap_sa braqubit1_sa braqubit0_sa control_adjoint phase_adjoint rotation_adjoint : Q_db.\n\n(* Rather use control_adjoint :\nHint Rewrite control_sa using (autorewrite with M_db; reflexivity) : M_db. *)\n\nLemma cnot_decomposition : ∣1⟩⟨1∣ ⊗ σx .+ ∣0⟩⟨0∣ ⊗ I 2 = cnot.\nProof. solve_matrix. Qed.                                               \n\nLemma notc_decomposition : σx ⊗ ∣1⟩⟨1∣ .+ I 2 ⊗ ∣0⟩⟨0∣ = notc.\nProof. solve_matrix. Qed.                                               \n\n(*********************)\n(** ** Phase Lemmas **)\n(*********************)\n\nLemma phase_0 : phase_shift 0 = I 2.\nProof. \n  unfold phase_shift, I. \n  rewrite Cexp_0.\n  solve_matrix.\nQed.\n\nLemma phase_2pi : phase_shift (2 * PI) = I 2.\n  unfold phase_shift, I. \n  rewrite Cexp_2PI.\n  solve_matrix.\nQed.\n\nLemma phase_pi : phase_shift PI = σz.\nProof.\n  unfold phase_shift, σz.\n  rewrite Cexp_PI.\n  replace (RtoC (-1)) with (Copp (RtoC 1)) by lca.\n  reflexivity.\nQed.\n\nLemma phase_neg_pi : phase_shift (-PI) = σz.\nProof.\n  unfold phase_shift, σz.\n  rewrite Cexp_neg.\n  rewrite Cexp_PI.\n  replace (/ -1) with (Copp (RtoC 1)) by lca.\n  reflexivity.\nQed.\n\nLemma phase_mul : forall θ θ', phase_shift θ × phase_shift θ' = phase_shift (θ + θ').\nProof.\n  intros. solve_matrix. rewrite Cexp_add. reflexivity.\nQed.  \n\n(* Old, can probably remove *)\nLemma phase_PI4_m8 : forall k,\n  phase_shift (IZR k * PI / 4) = phase_shift (IZR (k - 8) * PI / 4).\nProof.\n  intros. unfold phase_shift. rewrite Cexp_PI4_m8. reflexivity.\nQed.\n\nLemma phase_mod_2PI : forall k, phase_shift (IZR k * PI) = phase_shift (IZR (k mod 2) * PI).\nProof.\n  intros. unfold phase_shift. rewrite Cexp_mod_2PI. reflexivity.\nQed.\n\nLemma phase_mod_2PI_scaled : forall (k sc : Z), \n  sc <> 0%Z ->\n  phase_shift (IZR k * PI / IZR sc) = phase_shift (IZR (k mod (2 * sc)) * PI / IZR sc).\nProof.\n  intros. unfold phase_shift. rewrite Cexp_mod_2PI_scaled; easy. \nQed.\n\n\nHint Rewrite phase_0 phase_2pi phase_pi phase_neg_pi : Q_db.\n\n\n(*****************************)\n(* Positive Semidefiniteness *)\n(*****************************)\n\nDefinition positive_semidefinite {n} (A : Square n) : Prop :=\n  forall (z : Vector n), WF_Matrix z -> fst ((z† × A × z) O O) >= 0.  \n\nLemma pure_psd : forall (n : nat) (ϕ : Vector n), (WF_Matrix ϕ) -> positive_semidefinite (ϕ × ϕ†). \nProof.\n  intros n ϕ WFϕ z WFZ.\n  repeat rewrite Mmult_assoc.\n  remember (ϕ† × z) as ψ.\n  repeat rewrite <- Mmult_assoc.\n  rewrite <- (adjoint_involutive _ _ ϕ).\n  rewrite <- Mmult_adjoint.\n  rewrite <- Heqψ.\n  unfold Mmult. simpl.\n  rewrite <- Ropp_mult_distr_l.\n  rewrite Rplus_0_l.\n  unfold Rminus.\n  rewrite Ropp_involutive.\n  replace (fst (z 1%nat 0%nat) * fst (z 1%nat 0%nat))%R with ((fst (z 1%nat 0%nat))²) by easy. \n  replace (snd (z 1%nat 0%nat) * snd (z 1%nat 0%nat))%R with ((snd (z 1%nat 0%nat))²) by easy. \n  apply Rle_ge.\n  apply Rplus_le_le_0_compat; apply Rle_0_sqr.\nQed.\n\nLemma braket0_psd : positive_semidefinite ∣0⟩⟨0∣.\nProof. apply pure_psd. auto with wf_db. Qed.\n\nLemma braket1_psd : positive_semidefinite ∣1⟩⟨1∣.\nProof. apply pure_psd. auto with wf_db. Qed.\n\nLemma H0_psd : positive_semidefinite (hadamard × ∣0⟩⟨0∣ × hadamard).\nProof.\n  repeat rewrite Mmult_assoc.\n  rewrite <- hadamard_sa at 2.\n  rewrite <- Mmult_adjoint.\n  repeat rewrite <- Mmult_assoc.\n  apply pure_psd.\n  auto with wf_db.\nQed.\n\n\n(*************************)\n(* Pure and Mixed States *)\n(*************************)\n\nNotation Density n := (Matrix n n) (only parsing). \n\nDefinition Classical {n} (ρ : Density n) := forall i j, i <> j -> ρ i j = 0.\n\nDefinition Pure_State_Vector {n} (φ : Vector n): Prop := \n  WF_Matrix φ /\\ φ† × φ = I  1.\n\nDefinition Pure_State {n} (ρ : Density n) : Prop := \n  exists φ, Pure_State_Vector φ /\\ ρ = φ × φ†.\n\nInductive Mixed_State {n} : Matrix n n -> Prop :=\n| Pure_S : forall ρ, Pure_State ρ -> Mixed_State ρ\n| Mix_S : forall (p : R) ρ1 ρ2, 0 < p < 1 -> Mixed_State ρ1 -> Mixed_State ρ2 ->\n                                       Mixed_State (p .* ρ1 .+ (1-p)%R .* ρ2).  \n \nLemma WF_Pure : forall {n} (ρ : Density n), Pure_State ρ -> WF_Matrix ρ.\nProof. intros. destruct H as [φ [[WFφ IP1] Eρ]]. rewrite Eρ. auto with wf_db. Qed.\nHint Resolve WF_Pure : wf_db.\n\nLemma WF_Mixed : forall {n} (ρ : Density n), Mixed_State ρ -> WF_Matrix ρ. \nProof. induction 1; auto with wf_db. Qed.\nHint Resolve WF_Mixed : wf_db.\n\nLemma pure0 : Pure_State ∣0⟩⟨0∣. \nProof. exists ∣0⟩. intuition. split. auto with wf_db. solve_matrix. Qed.\n\nLemma pure1 : Pure_State ∣1⟩⟨1∣. \nProof. exists ∣1⟩. intuition. split. auto with wf_db. solve_matrix. Qed.\n\nLemma pure_id1 : Pure_State (I  1).\nProof. exists (I  1). split. split. auto with wf_db. solve_matrix. solve_matrix. Qed.\n\nLemma pure_dim1 : forall (ρ : Square 1), Pure_State ρ -> ρ = I  1.\nProof.\n  intros. \n  assert (H' := H).\n  apply WF_Pure in H'.\n  destruct H as [φ [[WFφ IP1] Eρ]]. \n  apply Minv_flip in IP1; auto with wf_db.\n  rewrite Eρ; easy.\nQed.    \n                              \nLemma pure_state_kron : forall m n (ρ : Square m) (φ : Square n),\n  Pure_State ρ -> Pure_State φ -> Pure_State (ρ ⊗ φ).\nProof.\n  intros m n ρ φ [u [[WFu Pu] Eρ]] [v [[WFv Pv] Eφ]].\n  exists (u ⊗ v).\n  split; [split |]. \n  - replace (S O) with (S O * S O)%nat by reflexivity.\n    apply WF_kron; auto.\n  - Msimpl. rewrite Pv, Pu. Msimpl. easy.\n  - Msimpl. subst. easy.\nQed.\n\nLemma mixed_state_kron : forall m n (ρ : Square m) (φ : Square n),\n  Mixed_State ρ -> Mixed_State φ -> Mixed_State (ρ ⊗ φ).\nProof.\n  intros m n ρ φ Mρ Mφ.\n  induction Mρ.\n  induction Mφ.\n  - apply Pure_S. apply pure_state_kron; easy.\n  - rewrite kron_plus_distr_l.\n    rewrite 2 Mscale_kron_dist_r.\n    apply Mix_S; easy.\n  - rewrite kron_plus_distr_r.\n    rewrite 2 Mscale_kron_dist_l.\n    apply Mix_S; easy.\nQed.\n\nLemma pure_state_trace_1 : forall {n} (ρ : Density n), Pure_State ρ -> trace ρ = 1.\nProof.\n  intros n ρ [u [[WFu Uu] E]]. \n  subst.\n  clear -Uu.\n  unfold trace.\n  unfold Mmult, adjoint in *.\n  simpl in *.\n  match goal with\n    [H : ?f = ?g |- _] => assert (f O O = g O O) by (rewrite <- H; easy)\n  end. \n  unfold I in H; simpl in H.\n  rewrite <- H.\n  apply Csum_eq.\n  apply functional_extensionality.\n  intros x.\n  rewrite Cplus_0_l, Cmult_comm.\n  easy.\nQed.\n\nLemma mixed_state_trace_1 : forall {n} (ρ : Density n), Mixed_State ρ -> trace ρ = 1.\nProof.\n  intros n ρ H. \n  induction H. \n  - apply pure_state_trace_1. easy.\n  - rewrite trace_plus_dist.\n    rewrite 2 trace_mult_dist.\n    rewrite IHMixed_State1, IHMixed_State2.\n    lca.\nQed.\n\n(* The following two lemmas say that for any mixed states, the elements along the \n   diagonal are real numbers in the [0,1] interval. *)\n\nLemma mixed_state_diag_in01 : forall {n} (ρ : Density n) i , Mixed_State ρ -> \n                                                        0 <= fst (ρ i i) <= 1.\nProof.\n  intros.\n  induction H.\n  - destruct H as [φ [[WFφ IP1] Eρ]].\n    destruct (lt_dec i n). \n    2: rewrite Eρ; unfold Mmult, adjoint; simpl; rewrite WFφ; simpl; [lra|lia].\n    rewrite Eρ.\n    unfold Mmult, adjoint in *.\n    simpl in *.\n    rewrite Rplus_0_l.\n    match goal with\n    [H : ?f = ?g |- _] => assert (f O O = g O O) by (rewrite <- H; easy)\n    end. \n    unfold I in H. simpl in H. clear IP1.\n    match goal with\n    [ H : ?x = ?y |- _] => assert (H': fst x = fst y) by (rewrite H; easy); clear H\n    end.\n    simpl in H'.\n    rewrite <- H'.    \n    split.\n    + unfold Rminus. rewrite <- Ropp_mult_distr_r. rewrite Ropp_involutive.\n      rewrite <- Rplus_0_r at 1.\n      apply Rplus_le_compat; apply Rle_0_sqr.    \n    + match goal with \n      [ |- ?x <= fst (Csum ?f ?m)] => specialize (Csum_member_le f n) as res\n      end.\n      simpl in *.\n      unfold Rminus in *.\n      Search (_ * - _)%R.\n      rewrite <- Ropp_mult_distr_r.\n      rewrite Ropp_mult_distr_l.\n      apply res with (x := i); trivial. \n      intros x.\n      unfold Rminus. rewrite <- Ropp_mult_distr_l. rewrite Ropp_involutive.\n      rewrite <- Rplus_0_r at 1.\n      apply Rplus_le_compat; apply Rle_0_sqr.    \n  - simpl.\n    repeat rewrite Rmult_0_l.\n    repeat rewrite Rminus_0_r.\n    split.\n    assert (0 <= p * fst (ρ1 i i)).\n      apply Rmult_le_pos; lra.\n    assert (0 <= (1 - p) * fst (ρ2 i i)).\n      apply Rmult_le_pos; lra.\n    lra.\n    assert (p * fst (ρ1 i i) <= p)%R. \n      rewrite <- Rmult_1_r.\n      apply Rmult_le_compat_l; lra.\n    assert ((1 - p) * fst (ρ2 i i) <= (1-p))%R. \n      rewrite <- Rmult_1_r.\n      apply Rmult_le_compat_l; lra.\n    lra.\nQed.\n\nLemma mixed_state_diag_real : forall {n} (ρ : Density n) i , Mixed_State ρ -> \n                                                        snd (ρ i i) = 0.\nProof.\n  intros.\n  induction H.\n  + unfold Pure_State in H. \n  - destruct H as [φ [[WFφ IP1] Eρ]].\n    rewrite Eρ.\n    simpl. \n    lra.\n  + simpl.\n    rewrite IHMixed_State1, IHMixed_State2.\n    repeat rewrite Rmult_0_r, Rmult_0_l.\n    lra.\nQed.\n\nLemma mixed_dim1 : forall (ρ : Square 1), Mixed_State ρ -> ρ = I  1.\nProof.\n  intros.  \n  induction H.\n  + apply pure_dim1; trivial.\n  + rewrite IHMixed_State1, IHMixed_State2.\n    prep_matrix_equality.\n    lca. \nQed.\n\n(* Useful to be able to normalize vectors *)\n\nDefinition norm {n} (ψ : Vector n) : R :=\n  sqrt (fst ((ψ† × ψ) O O)).\n\n\n\nLemma norm_real : forall {n} (v : Vector n), snd ((v† × v) 0%nat 0%nat) = 0%R. \nProof. intros. unfold Mmult, adjoint.\n       rewrite Csum_snd_0. easy.\n       intros. rewrite Cmult_comm.\n       rewrite Cmult_conj_real.\n       reflexivity.\nQed.\n\n\n\nDefinition normalize {n} (ψ : Vector n) :=\n  / (norm ψ) .* ψ.\n\n\nLemma inner_product_ge_0 : forall {d} (ψ : Vector d),\n  0 <= fst ((ψ† × ψ) O O).\nProof.\n  intros.\n  unfold Mmult, adjoint.\n  apply Csum_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\n\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.\n  rewrite Mscale_adj.\n  distribute_scale.\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.\n\n\nLemma div_real : forall (c : C),\n  snd c = 0 -> snd (/ c) = 0.\nProof. intros. \n       unfold Cinv. \n       simpl. \n       rewrite H. lra. \nQed.\n\n\nLemma Cmod_real : forall (c : C), \n  fst c >= 0 -> snd c = 0 -> Cmod c = fst c. \nProof. intros. \n       unfold Cmod. \n       rewrite H0.\n       simpl. \n       autorewrite with R_db.\n       apply sqrt_square.\n       lra. \nQed.\n\n\nLemma normalized_norm_1 : forall {n} (v : Vector n),\n  norm v <> 0 -> norm (normalize v) = 1.\nProof. intros. \n       unfold normalize.\n       distribute_scale. \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.\n\n\n(** Density matrices and superoperators **)\n\nDefinition Superoperator m n := Density m -> Density n.\n\nDefinition WF_Superoperator {m n} (f : Superoperator m n) := \n  (forall ρ, Mixed_State ρ -> Mixed_State (f ρ)).   \n\nDefinition super {m n} (M : Matrix m n) : Superoperator n m := fun ρ => \n  M × ρ × M†.\n\nLemma super_I : forall n ρ,\n      WF_Matrix ρ ->\n      super (I n) ρ = ρ.\nProof.\n  intros.\n  unfold super.\n  Msimpl.\n  reflexivity.\nQed.\n\nLemma WF_super : forall  m n (U : Matrix m n) (ρ : Square n), \n  WF_Matrix U -> WF_Matrix ρ -> WF_Matrix (super U ρ).\nProof.\n  unfold super.\n  auto with wf_db.\nQed.\n\nHint Resolve WF_super : wf_db.\n\nLemma super_outer_product : forall m (φ : Matrix m 1) (U : Matrix m m), \n    super U (outer_product φ φ) = outer_product (U × φ) (U × φ).\nProof.\n  intros. unfold super, outer_product.\n  autorewrite with M_db Q_db.\n  repeat rewrite Mmult_assoc. reflexivity.\nQed.\n\nDefinition compose_super {m n p} (g : Superoperator n p) (f : Superoperator m n)\n                      : Superoperator m p := fun ρ => g (f ρ).\n\nLemma WF_compose_super : forall m n p (g : Superoperator n p) (f : Superoperator m n) \n  (ρ : Square m), \n  WF_Matrix ρ ->\n  (forall A, WF_Matrix A -> WF_Matrix (f A)) ->\n  (forall A, WF_Matrix A -> WF_Matrix (g A)) ->\n  WF_Matrix (compose_super g f ρ).\nProof.\n  unfold compose_super.\n  auto.\nQed.\n\nHint Resolve WF_compose_super : wf_db.\n\n\nLemma compose_super_correct : forall {m n p} \n                              (g : Superoperator n p) (f : Superoperator m n),\n      WF_Superoperator g -> \n      WF_Superoperator f ->\n      WF_Superoperator (compose_super g f).\nProof.\n  intros m n p g f pf_g pf_f.\n  unfold WF_Superoperator.\n  intros ρ mixed.\n  unfold compose_super.\n  apply pf_g. apply pf_f. auto.\nQed.\n\nDefinition sum_super {m n} (f g : Superoperator m n) : Superoperator m n :=\n  fun ρ => (1/2)%R .* f ρ .+ (1 - 1/2)%R .* g ρ.\n\nLemma sum_super_correct : forall m n (f g : Superoperator m n),\n      WF_Superoperator f -> WF_Superoperator g -> WF_Superoperator (sum_super f g).\nProof.\n  intros m n f g wf_f wf_g ρ pf_ρ.\n  unfold sum_super. \n  set (wf_f' := wf_f _ pf_ρ).\n  set (wf_g' := wf_g _ pf_ρ).\n  apply (Mix_S (1/2) (f ρ) (g ρ)); auto. \n  lra.\nQed.\n\n(* Maybe we shouldn't call these superoperators? Neither is trace-preserving *)\nDefinition SZero {m n} : Superoperator m n := fun ρ => Zero.\nDefinition Splus {m n} (S T : Superoperator m n) : Superoperator m n :=\n  fun ρ => S ρ .+ T ρ.\n\n(* These are *)\nDefinition new0_op : Superoperator 1 2 := super ∣0⟩.\nDefinition new1_op : Superoperator 1 2 := super ∣1⟩.\nDefinition meas_op : Superoperator 2 2 := Splus (super ∣0⟩⟨0∣) (super ∣1⟩⟨1∣).\nDefinition discard_op : Superoperator 2 1 := Splus (super ⟨0∣) (super ⟨1∣).\n\nLemma pure_unitary : forall {n} (U ρ : Matrix n n), \n  WF_Unitary U -> Pure_State ρ -> Pure_State (super U ρ).\nProof.\n  intros n U ρ [WFU H] [φ [[WFφ IP1] Eρ]].\n  rewrite Eρ.\n  exists (U × φ).\n  split.\n  - split; auto with wf_db.\n    rewrite (Mmult_adjoint U φ).\n    rewrite Mmult_assoc.\n    rewrite <- (Mmult_assoc (U†)).\n    rewrite H, Mmult_1_l, IP1; easy.\n  - unfold super.\n    rewrite (Mmult_adjoint U φ).\n    repeat rewrite Mmult_assoc.\n    reflexivity.\nQed.    \n\nLemma mixed_unitary : forall {n} (U ρ : Matrix n n), \n  WF_Unitary U -> Mixed_State ρ -> Mixed_State (super U ρ).\nProof.\n  intros n U ρ H M.\n  induction M.\n  + apply Pure_S.\n    apply pure_unitary; trivial.\n  + unfold WF_Unitary, super in *.\n    rewrite Mmult_plus_distr_l.\n    rewrite Mmult_plus_distr_r.\n    rewrite 2 Mscale_mult_dist_r.\n    rewrite 2 Mscale_mult_dist_l.\n    apply Mix_S; trivial.\nQed.\n\nLemma super_unitary_correct : forall {n} (U : Matrix n n), \n  WF_Unitary U -> WF_Superoperator (super U).\nProof.\n  intros n U H ρ Mρ.\n  apply mixed_unitary; easy.\nQed.\n\nLemma compose_super_assoc : forall {m n p q}\n      (f : Superoperator m n) (g : Superoperator n p) (h : Superoperator p q), \n      compose_super (compose_super f g) h\n    = compose_super f (compose_super g h).\nProof. easy. Qed.\n\nLemma compose_super_eq : forall {m n p} (A : Matrix m n) (B : Matrix n p), \n      compose_super (super A) (super B) = super (A × B).\nProof.\n  intros.\n  unfold compose_super, super.\n  apply functional_extensionality. intros ρ.\n  rewrite Mmult_adjoint.\n  repeat rewrite Mmult_assoc.\n  reflexivity.\nQed.\n\n\n(* This is compose_super_correct \nLemma WF_Superoperator_compose : forall m n p (s : Superoperator n p) (s' : Superoperator m n),\n    WF_Superoperator s ->\n    WF_Superoperator s' ->\n    WF_Superoperator (compose_super s s').\nProof.\n  unfold WF_Superoperator.\n  intros m n p s s' H H0 ρ H1.\n  unfold compose_super.\n  apply H.\n  apply H0.\n  easy.\nQed.\n*)\n\n(**************)\n(* Automation *)\n(**************)\n\nLtac Qsimpl := try restore_dims; autorewrite with M_db_light M_db Q_db.\n\n\n(****************************************)\n(* Tests and Lemmas about swap matrices *)\n(****************************************)\n\nLemma swap_spec : forall (q q' : Vector 2), WF_Matrix q -> \n                                       WF_Matrix q' ->\n                                       swap × (q ⊗ q') = q' ⊗ q.\nProof.\n  intros q q' WF WF'.\n  solve_matrix.\n  - destruct y. lca. \n    rewrite WF by lia. \n    rewrite (WF' O (S y)) by lia.\n    lca.\n  - destruct y. lca. \n    rewrite WF by lia. \n    rewrite (WF' O (S y)) by lia.\n    lca.\n  - destruct y. lca. \n    rewrite WF by lia. \n    rewrite (WF' 1%nat (S y)) by lia.\n    lca.\n  - destruct y. lca. \n    rewrite WF by lia. \n    rewrite (WF' 1%nat (S y)) by lia.\n    lca.\nQed.  \n\nHint Rewrite swap_spec using (auto 100 with wf_db) : Q_db.\n\nExample swap_to_0_test_24 : forall (q0 q1 q2 q3 : Vector 2), \n  WF_Matrix q0 -> WF_Matrix q1 -> WF_Matrix q2 -> WF_Matrix q3 ->\n  swap_to_0 4 2 × (q0 ⊗ q1 ⊗ q2 ⊗ q3) = (q2 ⊗ q1 ⊗ q0 ⊗ q3). \nProof.\n  intros q0 q1 q2 q3 WF0 WF1 WF2 WF3.\n  unfold swap_to_0, swap_to_0_aux.\n  simpl.\n  rewrite Mmult_assoc.\n  repeat rewrite Mmult_assoc.\n  rewrite (kron_assoc q0 q1). Qsimpl.\n  replace 4%nat with (2*2)%nat by reflexivity.\n  repeat rewrite kron_assoc.\n  restore_dims.\n  rewrite <- (kron_assoc q0 q2). Qsimpl.\n  rewrite (kron_assoc q2). Qsimpl.\n  rewrite <- kron_assoc. Qsimpl.\n  repeat rewrite <- kron_assoc.\n  reflexivity.\n  all : auto with wf_db.\nQed.\n\nLemma swap_two_base : swap_two 2 1 0 = swap.\nProof. unfold swap_two. simpl. apply kron_1_r. Qed.\n\nLemma swap_second_two : swap_two 3 1 2 = I 2 ⊗ swap.\nProof.\n  unfold swap_two.\n  simpl.\n  rewrite kron_1_r.\n  reflexivity.\nQed.\n\nLemma swap_0_2 : swap_two 3 0 2 = (I 2 ⊗ swap) × (swap ⊗ I 2) × (I 2 ⊗ swap).\nProof.\n  unfold swap_two.\n  simpl.\n  Qsimpl.\n  reflexivity.\nQed.\n\n(*\nProposition swap_to_0_spec : forall (q q0 : Matrix 2 1) (n k : nat) (l1 l2 : list (Matrix 2 1)), \n   length l1 = (k - 1)%nat ->\n   length l2 = (n - k - 2)%nat ->   \n   @Mmult (2^n) (2^n) 1 (swap_to_0 n k) (⨂ ([q0] ++ l1 ++ [q] ++ l2)) = \n     ⨂ ([q] ++ l1 ++ [q0] ++ l2).\n\nProposition swap_two_spec : forall (q q0 : Matrix 2 1) (n0 n1 n2 n k : nat) (l0 l1 l2 : list (Matrix 2 1)), \n   length l0 = n0 ->\n   length l1 = n1 ->\n   length l2 = n2 ->   \n   n = (n0 + n1 + n2 + 2)%nat ->\n   @Mmult (2^n) (2^n) 1 \n     (swap_two n n0 (n0+n1+1)) (⨂ (l0 ++ [q0] ++ l1 ++ [q] ++ l2)) = \n     ⨂ (l0 ++ [q] ++ l1 ++ [q0] ++ l2).\n*)\n\nExample move_to_0_test_24 : forall (q0 q1 q2 q3 : Vector 2), \n  WF_Matrix q0 -> WF_Matrix q1 -> WF_Matrix q2 -> WF_Matrix q3 ->\n  move_to_0 4 2 × (q0 ⊗ q1 ⊗ q2 ⊗ q3) = (q2 ⊗ q0 ⊗ q1 ⊗ q3). \nProof.\n  intros q0 q1 q2 q3 WF0 WF1 WF2 WF3.\n  unfold move_to_0, move_to_0_aux.\n  repeat rewrite Mmult_assoc.\n  rewrite (kron_assoc q0 q1).\n  simpl.\n  restore_dims.\n  replace 4%nat with (2*2)%nat by reflexivity.\n  Qsimpl.\n  rewrite <- kron_assoc.\n  restore_dims.\n  repeat rewrite (kron_assoc _ q1). \n  Qsimpl.\n  reflexivity.\n  all : auto with wf_db.\nQed.\n\n(* *)\n\n\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/Quantum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6644039712782871}}
{"text": "From mathcomp Require Import ssreflect eqtype.\nFrom deriving Require Import deriving.\n\nRequire Import type.\n\n(* I tried to write the induction principle myself, but it does not work with\n   deriving. *)\nModule induction_try.\n\n(* We have to manually write the right induction behaviour *)\nSection induction.\n\nContext (A : Type) (P : t A -> Type).\nContext\n  (H0 : forall a, P (Leaf _ a))\n  (H1 : P (Node _ nil))\n  (H2 : forall a l, P (Node _ l) -> P (Node _ (a::l))).\n\nLemma t_rect : forall x, P x.\nProof.\n  refine (fix aux x :=\n    match x with\n    | Leaf a => H0 a\n    | Node l =>\n      (fix aux0 (l : list (t A)) :=\n      match l with\n      | nil => H1\n      | cons _ _ => H2 _ _ (aux0 _)\n      end) l\n    end).\nDefined.\n\nLemma list_t_rect : forall l, P (Node _ l).\nProof.\n  refine (fix aux l :=\n    match l with\n    | nil => H1\n    | cons _ _ => H2 _ _ (aux _)\n    end).\nDefined.\n\nCombined Scheme t_list_t_rect from t_rect, list_t_rect.\n\nEnd induction.\n\nEnd induction_try.\n\nModule induction_done_right.\n\n(* see https://github.com/arthuraa/deriving/blob/master/tests/nested.v *)\n\nSection induction.\n\nContext (A : eqType).\n\nDefinition t_rect\n  (P1 : t A -> Type)\n  (P2 : list (t A) -> Type)\n  (HL : forall a, P1 (Leaf _ a))\n  (HR : forall rs, P2 rs -> P1 (Node _ rs))\n  (HN : P2 nil)\n  (HC : forall r, P1 r -> forall rs, P2 rs -> P2 (cons r rs))\n  : forall r, P1 r :=\n  fix rose_rect r :=\n    let fix seq_rose_rect rs : P2 rs :=\n        match rs with\n        | nil => HN\n        | cons r rs => HC r (rose_rect r) rs (seq_rose_rect rs)\n        end in\n    match r with\n    | Leaf a => HL a\n    | Node rs => HR rs (seq_rose_rect rs) end.\n\nDefinition list_t_rect\n  (P1 : t A -> Type)\n  (P2 : list (t A) -> Type)\n  (HL : forall a, P1 (Leaf _ a))\n  (HR : forall rs, P2 rs -> P1 (Node _ rs))\n  (HN : P2 nil)\n  (HC : forall r, P1 r -> forall rs, P2 rs -> P2 (cons r rs))\n  : forall rs, P2 rs :=\n    fix list_t_rect rs : P2 rs :=\n      match rs with\n      | nil => HN\n      | cons r rs => HC r (t_rect _ _ HL HR HN HC r) rs (list_t_rect rs)\n      end.\n\nCombined Scheme t_list_t_rect from t_rect, list_t_rect.\n\nDefinition t_list_t_indDef := [indDef for t_list_t_rect].\nCanonical t_indType := IndType (t A) t_list_t_indDef.\nDefinition t_eqMixin := [derive eqMixin for t A].\nCanonical rose_eqType := EqType (t A) t_eqMixin.\n\nEnd induction.\n\nEnd induction_done_right.\n", "meta": {"author": "eponier", "repo": "compare-eq", "sha": "cc2da184e747d0ad6ada8597e1ebf03377e413e2", "save_path": "github-repos/coq/eponier-compare-eq", "path": "github-repos/coq/eponier-compare-eq/compare-eq-cc2da184e747d0ad6ada8597e1ebf03377e413e2/features/nested/deriving.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.6643840905559244}}
{"text": "Require Import MachineInt.\nRequire Import List.\n\n(** Pris chez Coq 8.5. *)\n\nSection Repeat.\n\n  Variable A : byte.\n  Fixpoint repeat (x : byte) (n: nat ) :=\n    match n with\n      | O => nil\n      | S k => x::(repeat x k)\n    end.\n\n  Theorem repeat_length x n:\n    length (repeat x n) = n.\n  Proof.\n    induction n as [| k Hrec]; simpl; rewrite ?Hrec; reflexivity.\n  Qed.\n\n  Theorem repeat_spec n x y:\n    In y (repeat x n) -> y=x.\n  Proof.\n    induction n as [|k Hrec]; simpl; destruct 1; auto.\n  Qed.\n\nEnd Repeat.", "meta": {"author": "ebtaleb", "repo": "6502Coq", "sha": "e0dfca46375e411ccd0bfc53ab93b08480847694", "save_path": "github-repos/coq/ebtaleb-6502Coq", "path": "github-repos/coq/ebtaleb-6502Coq/6502Coq-e0dfca46375e411ccd0bfc53ab93b08480847694/Repeat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.664384081474586}}
{"text": "(* Basic Propositions *)\n\nVariables P Q R : Prop.\n\n(* simple tautology proof *)\n\nTheorem I : P -> P.\n\nProof.\n  intro H.                      (* to prove P -> Q, assume P and prove Q *)\n  exact H.                      (* current goal is just the assumption *)\nQed.\n\nDefinition I2 : P -> P := fun H : P => H. (* Curry-Howard *)\n\nTheorem K : P -> (Q -> P).\n\nProof.\n  intro H1.\n  intro H2.\n  exact H1.\nQed.\n\nTheorem S : (P -> Q -> R) -> (P -> Q) -> P -> R.\n\nProof.\n  intro pqrH.\n  intro pqH.\n  intro pH.\n  apply pqrH.                   (* MP *)\n  exact pH.\n  apply pqH.                    (* MP *)\n  exact pH.\nQed.", "meta": {"author": "zjhmale", "repo": "MFCS", "sha": "e82b0e2425b4988ce8dfc558901ae2e76e1b23f1", "save_path": "github-repos/coq/zjhmale-MFCS", "path": "github-repos/coq/zjhmale-MFCS/MFCS-e82b0e2425b4988ce8dfc558901ae2e76e1b23f1/intro.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7853085884247212, "lm_q1q2_score": 0.6643258735317232}}
{"text": "\n(** 1 basics **)\n\n(** examples of dependent functions **)\n\n\nDefinition pick_first (a : Type) (b : Type) : Type := a.\n\nCompute pick_first nat bool. \n\nDefinition return_7 (a : Type) (b : Type) : nat := 7.\n\nCompute return_7 nat bool. \n\n\n(** 1a identity **)\n\n\n(** Definition my_id (t : Type) : t -> t := (fun a => a). **)\n\nDefinition my_id : (forall t : Type, t -> t) := (fun t a => a).\n\n(** \nPi _{x : A} B(x) is (forall x : A, B(x))\nfun is a constructor\nevaluation is a desctructor\n**)\n\n\nCompute my_id nat 7.\n\nCheck my_id.\n\n\nTheorem identity_1a : forall t : Type, t -> t.\nProof.\nexact (my_id).\nShow Proof.\nQed.\n\n(** 1b composition **)\n\nDefinition my_composition : (forall a b c : Type, (b -> c) -> (a -> b) -> (a -> c)) \n:= (fun a b c g f av => g (f av)).\n\n\nDefinition add1 : nat -> nat := (fun x => x + 1).\n\nCompute (my_composition nat nat nat add1 add1) 7.\n\n(** 1c introducing functions **)\n\n(** \nPi _{x : A} B(x) is (forall x : A, B(x))\n**)\n\nDefinition my_type : Type := forall x : bool, nat.\nCompute my_type. \n\n(** 2 finite products **)\n\n(** 2a unit type **)\n\nInductive my_unit : Set :=\n    my_star : my_unit.\n\nDefinition type_to_unit : (forall t : Type, t -> my_unit) := (fun t a => my_star).\n\nCompute type_to_unit nat 7.\n\n\n\n\n(** WE WANT CODE TO VERIFY THE UNIQUENESS OF AN ARROW INTO THE UNIT TYPE **)\n\n(** 2b products **)\n\nInductive my_prod (A B:Type) : Type :=\n  my_pair : A -> B -> (my_prod A B).\n\nDefinition my_fst : (forall A B : Type, (my_prod A B) -> A) := \n  (fun A B p => match p with (my_pair _ _ x y) => x end). \n\nDefinition my_snd : (forall A B : Type, (my_prod A B) -> B) := \n  (fun A B p => match p with (my_pair _ _ x y) => y end). \n\nDefinition my_pair_example : my_prod nat bool := my_pair nat bool 7 true.\n\nCompute my_fst nat bool my_pair_example.\n\nDefinition my_intermediary : (forall A B H : Type, (H -> A) -> (H -> B) ->\n (H -> my_prod A B)) := (fun A B H f g hv => my_pair A B (f hv) (g hv)).\n\n\n(** Want to prove universal property **)\n\n(** 3a Empty type **)\n\nInductive my_empty_set : Set :=.\n\nDefinition my_empty_function (A : Type) (x : my_empty_set) : (A : Type) :=\n  match x with end.\n\nCheck my_empty_function nat.\n\n(** 3b Coproduct type **)\n\nInductive my_sum (A B:Type) : Type :=\n  | my_inl : A -> my_sum A B\n  | my_inr : B -> my_sum A B.\n\nCheck my_inl.\n\nCheck my_inl nat bool 7.\n\nDefinition my_coproduct_inter : (forall A B H : Type, (A -> H) -> (B -> H) ->\n  ((my_sum A B) -> H)) := (fun A B H f g n => \n  match n with\n    | (my_inl _ _ x) => (f x)\n    | (my_inr _ _ y) => (g y)\n  end).\n\n(** 4a exponential elimination rule **)\n\nDefinition expo_elim : (forall X Y : Type, (my_prod (X -> Y) X) -> Y) := \n  (fun X Y v => ((my_fst (X -> Y) X v) (my_snd (X -> Y) X v))).\n\n(** 4b exponential introduction rule **)\n\nDefinition expo_intro : (forall A B C : Type, ((my_prod A B) -> C) ->\n  (A -> (B -> C))) := (fun A B C pair_fun av bv =>\n  pair_fun (my_pair A B av bv)).\n\n\n\n\n\n\n(** extra **)\n\nInductive my_nat : Set :=\n  | my_zero : my_nat\n  | my_succ : my_nat -> my_nat.\n\n\n\n(** finish representing Heyting Algebra ideas\ngo fo HoTT representation from book, and encode those rules\n**)\n\n(** ************** **)\n\n(** \nSigma _{x : A} B(x) is like  (exists x : A, B(x))\nCheck ex_intro.\nCheck ex_proj1.\nDefinition my_sigma_val : (exists x : bool, (my_B x)) := ex_intro false 7.\nhttps://coq.inria.fr/stdlib/Coq.Init.Logic.html\n\n**)\n\n\n\nDefinition my_B : bool -> Type := fun b => match b with true => bool | false => nat end.\n\nCheck sigT.\n\nCheck existT.\n\n\nInductive my_sigT (A:Type) (P:A -> Type) : Type :=\n    my_existT : forall x:A, P x -> my_sigT A P.\n\nDefinition my_sigma_val : (my_sigT bool my_B) :=  my_existT bool my_B false 7.\n\nDefinition my_projT1 (A:Type) (P:A -> Type) (x: my_sigT A P) : A := match x with\n                                      | my_existT _ _ a _ => a\n                                      end.\n\n\nCheck my_projT1.\n\nCompute my_projT1 bool my_B my_sigma_val.\n\n\n\n\n(**\nbeware of \nSet Implicit Arguments.\nin\nhttps://coq.inria.fr/stdlib/Coq.Init.Specif.html\n\n**)\n\n(** *** **)\n(* https://coq.inria.fr/library/Coq.Init.Datatypes.html *)\n\nCheck Empty_set.\n\nDefinition Empty_function (A : Type) (x : Empty_set) : (A : Type) :=\n  match x with end.\n\nCheck Empty_function nat.\n\nCheck unit.\n\nCheck tt.\n\nCheck sum.\nCheck inl.\n\nCheck prod.\nCheck pair.\nCheck 7.\n\nDefinition idv (A : Type) (x : A) : A := x.\n\n\nCompute idv nat 7.\n\nDefinition id_strange (t : Type) : t -> t := (fun a => a). \nCompute (id_strange nat 7).\n\n\n\n\n\n", "meta": {"author": "richardsouthwell", "repo": "startcoq", "sha": "d9779af6ddff2b962e30bbd0f1b34920b76a29bc", "save_path": "github-repos/coq/richardsouthwell-startcoq", "path": "github-repos/coq/richardsouthwell-startcoq/startcoq-d9779af6ddff2b962e30bbd0f1b34920b76a29bc/Heyting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6643258598552269}}
{"text": "From mathcomp Require Import ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nRequire Import logic_pred_theories.\nRequire Import class_set.\nRequire Import direct_product_theories.\nRequire Import binary_relation.\n\nInductive GraphOfBinaryRelation {U:Type} (R:BinaryRelation U) (A B: Ensemble U): Ensemble (Ensemble (Ensemble U)) :=\n| Definition_of_Graph: forall (x y:U), R x y /\\ (|x, y|) ∈ A × B -> (|x, y|) ∈ GraphOfBinaryRelation R A B.\n\nInductive DomainOfCorrespondence {U:Type} (f:Ensemble (Ensemble (Ensemble U))) : Ensemble U :=\n| Definition_of_DomainOfCorrespondence: forall (x:U), x ∈ Pr1 f -> x ∈ DomainOfCorrespondence f.\n\nInductive RangeOfCorrespondence {U:Type} (f:Ensemble (Ensemble (Ensemble U))) : Ensemble U :=\n| Definition_of_RangeOfCorrespondence: forall (y:U), y ∈ Pr2 f -> y ∈ RangeOfCorrespondence f.\n\nInductive ImageOfCorrespondence {U:Type} (f:Ensemble (Ensemble (Ensemble U))) (C:Ensemble U) : Ensemble U :=\n  | Definition_of_ImageOfCorrespondence: forall (y:U), (exists x:U, x ∈ C /\\ (|x,y|) ∈ f) -> y ∈ ImageOfCorrespondence f C.\n\nInductive CompoundCorrespondence {U:Type} (g f:Ensemble (Ensemble (Ensemble U))) : Ensemble (Ensemble (Ensemble U)) :=\n| Definition_of_CompoundCorrespondence :\n    forall (x y:U), (exists z:U, (|x,z|) ∈ f /\\ (|z,y|) ∈ g) -> (|x,y|) ∈ CompoundCorrespondence g f.\n\nInductive TransposeOfGraph {U:Type} (f:Ensemble (Ensemble (Ensemble U))) :\n    Ensemble (Ensemble (Ensemble U)) :=\n| Definition_of_InverseCorrespondence :\n    forall (x y: U), (|x,y|) ∈ f -> (|y,x|) ∈ TransposeOfGraph f.\n\n(* ⥴: Unicode 2974 (RIGHTWARDS ARROW ABOVE TILDE OPERATO) *)\n(* ≔ : Unicode 2254 (COLON EQUAL) *)\n(* ⊦ : Unicode 22A6 (ASSERTION) *)\nNotation \"f ≔ R ⊦ A ⥴ B\" := (f = GraphOfBinaryRelation R A B) (at level 44).\n\n(* ∘: Unicode 2218 *)\nNotation \"g ∘ f\" := (CompoundCorrespondence g f) (at level 45).\n\n(* 𝕯: Unicode:1D56F, 𝕽: Unicode:1D57D *)\nNotation \"𝕯( f )\" := (DomainOfCorrespondence f) (at level 45).\nNotation \"𝕽( f )\" := (RangeOfCorrespondence f) (at level 45).\n\nNotation \"f ^-1\" := (TransposeOfGraph f) (at level 44).\n\nNotation \"f '' A\" := (ImageOfCorrespondence f A) (at level 46).\n\nProposition transpose_correspondence_iff:\n  forall (U:Type) (x y:U) (R:BinaryRelation U) (A B:Ensemble U) (f:Ensemble (Ensemble (Ensemble U))),\n      f ≔ R ⊦ A ⥴ B -> (|x,y|) ∈ f <-> (|y,x|) ∈ f^-1.\n  Proof.\n    move => U x y R A B f H.\n    rewrite /iff.\n    split => H0.\n    split.\n    apply H0.\n    inversion H0.\n    apply ordered_pair_swap in H1.\n    rewrite H1 in H2.\n    apply H2.\n  Qed.\n\nSection Correspondence.\n  Variable U: Type.\n  Variable R: BinaryRelation U.\n  Variable A B C D: Ensemble U.\n\n  Proposition graph_is_included_in_direct_product:\n    forall (f:Ensemble (Ensemble (Ensemble U))),\n      f ≔ R ⊦ A ⥴ B -> f ⊂ A × B.\n  Proof.\n    move => f H.\n    rewrite H => X.\n    case => [x y [H0]].\n    apply.\n  Qed.\n\n  Proposition domain_of_graph_is_included_in_source_set:\n    forall (f:Ensemble (Ensemble (Ensemble U))),\n      f ≔ R ⊦ A ⥴ B -> 𝕯( f ) ⊂ A.\n  Proof.\n    move => f H x H0.\n    inversion H0 as [x' H1].\n    inversion H1 as [x0 [y0]].\n    rewrite H in H3.\n    rewrite -H4 in H3.\n    inversion H3.\n    inversion H6.\n    rewrite H5 in H8.\n    apply ordered_pair_in_direct_product_iff_and in H8.\n    inversion H8.\n    rewrite -H4.\n    apply H9.\n  Qed.\n\n  Proposition range_of_graph_is_included_in_source_set:\n    forall (f:Ensemble (Ensemble (Ensemble U))),\n      f ≔ R ⊦ A ⥴ B -> 𝕽( f ) ⊂ B.\n  Proof.\n    move => f H y H0.\n    inversion H0 as [y' [y0 [x]]].\n    rewrite H in H1.\n    inversion H1 as [x1 y1 [HR H3]].\n    rewrite H4 in H3.\n    apply ordered_pair_in_direct_product_iff_and in H3.\n    inversion H3.\n    apply H6.\n  Qed.\n\n  Proposition singleton_image_to_direct_product:\n    forall (f:Ensemble (Ensemble (Ensemble U))),\n      f ≔ R ⊦ A ⥴ B -> forall (x y:U), {|y|} = f '' {|x|} -> (|x,y|) ∈ f.\n  Proof.\n    move => f Hf x y H.\n    rewrite Hf in  H.\n    apply Extension in H.\n    inversion H.\n    rewrite Hf.\n    move: (H0 y).\n    case.\n    apply singleton_eq_iff.\n    reflexivity.\n    move => y0 H2.\n    inversion H2 as [x0 []].\n    apply singleton_eq_iff in H3.\n    rewrite -H3.\n    apply H4.\n  Qed.\n\n  Theorem relation_iff_in_graph:\n    forall (f:Ensemble (Ensemble (Ensemble U))) (x y:U),\n      x ∈ A /\\ y ∈ B /\\ f ≔ R ⊦ A ⥴ B -> R x y <-> (|x,y|) ∈ f.\n  Proof.\n    move => f x y [HA [HB Hf]].\n    rewrite /iff.\n    split => H.\n    rewrite Hf.\n    split.\n    split.\n    apply H.\n    apply ordered_pair_in_direct_product_iff_and.\n    split.\n    apply HA.\n    apply HB.\n    rewrite Hf in H.\n    inversion H.\n    inversion H1.\n    apply ordered_pair_iff in H0.\n    inversion H0.\n    rewrite H4 H5 in H2.\n    apply H2.\n  Qed.\n\n  Theorem union_of_image_of_correspondence_eq:\n    forall (f:Ensemble (Ensemble (Ensemble U))),\n      f ≔ R ⊦ A ⥴ B -> f '' (C ∪ D) = f '' C ∪ f '' D.\n  Proof.\n    move => f H.\n    apply Extensionality_Ensembles.\n    split => z.\n    +case => [y [x [H0 H1]]].\n     inversion H0 as [x' H2|x' H2]; [left|right]; split; exists x; split.\n     ++apply H2.\n       apply H1.\n     ++apply H2.\n       apply H1.\n    +case => z0; case => [y [x [H' H0]]]; split; exists x; split.\n     ++left.\n       apply H'.\n       apply H0.\n     ++right.\n       apply H'.\n       apply H0.\n  Qed.\n\n  Theorem and_image_of_correspondence_included:\n    forall (f:Ensemble (Ensemble (Ensemble U))),\n      f ≔ R ⊦ A ⥴ B -> f '' (C ∩ D) ⊂ (f '' C ∩ f '' D).\n  Proof.\n    move => f H y H0.\n    inversion H0 as [y' [x' [H1 H2]]].\n    inversion H1.\n    split; split; exists x; rewrite H6; split.\n    apply H4.\n    apply H2.\n    apply H5.\n    apply H2.\n  Qed.\n\n  Theorem included_domain_to_included_image:\n    forall (f:Ensemble (Ensemble (Ensemble U))) (V W:Ensemble U),\n      f ≔ R ⊦ A ⥴ B -> V ⊂ W /\\ W ⊂ A -> (f '' V ⊂ f '' W).\n  Proof.\n    move => f V W HF.\n    case => [HVW HWA] y H0.\n    inversion H0 as [y0 [x [H1 H2]]].\n    split.\n    exists x.\n    split.\n    apply HVW.\n    apply H1.\n    apply H2.\n  Qed.\n\n  Proposition double_transpose:\n    forall (f:Ensemble (Ensemble (Ensemble U))),\n      f ≔ R ⊦ A ⥴ B -> (f^-1)^-1 = f.\n  Proof.\n    move => f H.\n    apply /Extensionality_Ensembles.\n    split => Z H0.\n    +inversion H0.\n     rewrite transpose_correspondence_iff.\n     apply H1.\n     apply H.\n    +rewrite H in H0.\n     inversion H0.\n     rewrite -H2 in H0.\n     rewrite -H in H0.\n     split; split.\n     apply H0.\n  Qed.\n\n  Goal forall (f:Ensemble (Ensemble (Ensemble U))),\n      f ≔ R ⊦ A ⥴ B -> f '' (C ∩ D) ⊂ f '' C ∩ f '' D.\n  Proof.\n    move => f H x H0.\n    inversion H0 as [x0 [y' [H1 H2]]].\n    inversion H1.\n    split; split; exists y'; split.\n    +apply H4.\n     apply H2.\n    +apply H5.\n     apply H2.\n  Qed.\n\n  (* g ∘ f (D) = g(f(D)) *)\n  Proposition image_compound_correspondence_eq:\n    forall (F G:BinaryRelation U) (f g:Ensemble (Ensemble (Ensemble U))),\n      f ≔ F ⊦ A ⥴ B /\\ g ≔ G ⊦ B ⥴ C -> g ∘ f '' D = g '' (f '' D).\n  Proof.\n    move => F G f g.\n    case => HF HG.\n    apply Extensionality_Ensembles.\n    split => y H.\n    +inversion H as [y0 [x0 []]].\n     inversion H1 as [x1 y1 [z [H3 H4]]].\n     apply ordered_pair_iff in H5.\n     inversion H5.\n     split.\n     exists z.\n     split.\n     ++split.\n       exists x1.\n       split.\n       rewrite H6.\n       apply H0.\n       apply H3.\n     ++rewrite -H7.\n       apply H4.\n    +inversion H as [y0 [z []]].\n     inversion H0 as [y0' [x []]].\n     split.\n     exists x.\n     split.\n     apply H3.\n     split.\n     exists z.\n     split.\n     apply H4.\n     apply H1.\n  Qed.\n\n  (* h ∘ (g ∘ f) = (h ∘ g) ∘ f *)\n  Theorem compound_correspondence_assoc:\n    forall (X Y Z W:Ensemble U) (F G H:BinaryRelation U) (f g h:Ensemble (Ensemble (Ensemble U))),\n      f ≔ F ⊦ X ⥴ Y /\\ g ≔ G ⊦ Y ⥴ Z /\\ h ≔ H ⊦ Z ⥴ W ->\n      h ∘ (g ∘ f) = (h ∘ g) ∘ f.\n  Proof.\n    move => X Y Z W F G H f g h.\n    case => HF [HG HH].\n    apply Extensionality_Ensembles.\n    split => V H0.\n    +inversion H0 as [x y [z0 []]].\n     inversion H1 as [x0 z0' [z1 []]].\n     apply ordered_pair_iff in H6.\n     inversion H6.\n     split.\n     exists z1.\n     split.\n     rewrite -H7.\n     apply H4.\n     split.\n     exists z0'.\n     split.\n     apply H5.\n     rewrite H8.\n     apply H2.\n    +inversion H0 as [x y [z0 []]].\n     inversion H2 as [z0' y0 [z1 []]].\n     apply ordered_pair_iff in H6.\n     inversion H6.\n     split.\n     exists z1.\n     split.\n     split.\n     exists z0.\n     split.\n     apply H1.\n     rewrite -H7.\n     apply H4.\n     rewrite -H8.\n     apply H5.\n  Qed.\n\n  (* (g ∘ f)^(-1) = f^(-1) ∘ g^(-1) *)\n  Theorem unfold_compound_corrsepondence_inverse:\n    forall (F G:BinaryRelation U) (f g:Ensemble (Ensemble (Ensemble U))),\n      f ≔ F ⊦ A ⥴ B /\\ g ≔ G ⊦ B ⥴ C -> (g ∘ f) ^-1 = f ^-1 ∘ g ^-1.\n  Proof.\n    move => F G f g.\n    case => HF HG.\n    apply Extensionality_Ensembles.\n    split => X H.\n    -inversion H as [x y].\n     inversion H0 as [x0 y0].\n     inversion H2 as [z []].\n     apply ordered_pair_iff in H3.\n     inversion H3.\n     split.\n     exists z.\n     split; split.\n      +rewrite H7 in H5.\n       apply H5.\n      +rewrite H6 in H4.\n       apply H4.\n    -inversion H as [x y].\n     inversion H0 as [z []].\n     split.\n     split.\n     exists z.\n     split.\n     apply (transpose_correspondence_iff y z HF) in H3.\n     apply H3.\n     apply (transpose_correspondence_iff z x HG) in H2.\n     apply H2.\n  Qed.\n\n  Theorem transpose_graph_keep_included:\n    forall (f:Ensemble (Ensemble (Ensemble U))),\n      f ≔ R ⊦ A ⥴ B -> f ⊂ A × B <-> f^-1 ⊂ B × A.\n  Proof.\n    move => f HF.\n    rewrite HF.\n    rewrite /iff.\n    split => H Z H0; inversion H0 as [x y H1].\n    +inversion H1 as [x0 y0].\n     inversion H3.\n     rewrite H4 in H6.\n     apply ordered_pair_in_direct_product_iff_and in H6.\n     inversion H6.\n     apply ordered_pair_in_direct_product_iff_and.\n     split.\n     apply H8.\n     apply H7.\n    +inversion H1.\n     apply H4.\n  Qed.\n\nEnd Correspondence.\n\nRequire Export class_set.\nRequire Export direct_product_theories.\nRequire Export binary_relation.", "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/correspondence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6643258531058357}}
{"text": "Search True.\nSearch False.\nSearch bool.\n\nInductive int : Set :=\n  | Z  : int         (*  0      *)\n  | Zp : int -> int  (*  x + 1  *)\n  | Zn : int -> int. (*  x - 1  *)\n\nFixpoint zplus (x y:int) : int :=\n  match x with\n  | Z    => y              (* 0     + y = y           *)\n  | Zp x => Zp (zplus x y) (* (x+1) + y = (x + y) + 1 *)\n  | Zn x => Zn (zplus x y) (* (x-1) + y = (x + y) - 1 *)\n  end.\n\nFixpoint zminus (x y:int) : int :=\n  match y with\n  | Z    => x               (* x - 0     = x           *)\n  | Zp y => Zn (zminus x y) (* x - (y+1) = (x - y) + 1 *)\n  | Zn y => Zp (zminus x y) (* x - (y-1) = (x - y) - 1 *)\n  end.\n\nTheorem zplus_id_right : forall x:int, zplus x Z = x.\nProof.\n  intros.\n  induction x.\n    simpl. reflexivity.\n    simpl. rewrite IHx. reflexivity.\n    simpl. rewrite IHx. reflexivity.\nQed.\n\nFixpoint zmult (x y:int) : int :=\n  match x with\n  | Z => Z                       (* 0 * y     = 0         *)\n  | Zp x => zplus  (zmult x y) y (* (x+1) * y = (x*y) + y *)\n  | Zn x => zminus (zmult x y) y (* (x-1) * y = (x*y) - y *)\n  end.\n\nTheorem zmult_zero_right : forall x:int, zmult x Z = Z.\nProof.\n  intros.\n  induction x.\n    simpl. reflexivity.\n    simpl. rewrite IHx. reflexivity.\n    simpl. rewrite IHx. reflexivity.\nQed.\n\n(*\n\nN_rec:\n  forall P : N -> Set,\n  P O -> (forall n : N, P n -> P (S n)) -> forall n : N, P n.\n\nbool_rec:\n  forall P : bool -> Set,\n  P true -> P false -> forall b : bool, P b\n\nN_ind:\n  forall P : N -> Prop,\n  P O -> (forall n : N, P n -> P (S n)) -> forall n : N, P n\n\nbool_ind:\n  forall P : bool -> Prop,\n  P true -> P false -> forall b : bool, P b.\n\n*)", "meta": {"author": "Riib11", "repo": "Coq-Work", "sha": "e163edd331fd15549910f0fe0a361bc93ca951d7", "save_path": "github-repos/coq/Riib11-Coq-Work", "path": "github-repos/coq/Riib11-Coq-Work/Coq-Work-e163edd331fd15549910f0fe0a361bc93ca951d7/SoftwareFoundations/Basics/int.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6643258446047197}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Vectors.Fin.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List.\nImport Lia.\nImport EqNotations.\nLocal Open Scope program_scope.\n\nModule List.\nImport ListNotations.\n\nFixpoint lookup {A : Type} (xs : list A) : Fin.t (length xs) -> A :=\n  match xs with\n  | [] => Fin.case0 (fun _ => A)\n  | x :: xs => fun i =>\n    match i in Fin.t (S n) return n = length xs -> A with\n    | F1 => const x\n    | FS j => fun H => lookup xs (rew H in j)\n    end eq_refl\n  end.\n\nFixpoint take {A : Type} (xs : list A) : Fin.t (S (length xs)) -> list A :=\n  match xs with\n  | [] => const []\n  | x :: xs => fun i =>\n    match i in Fin.t (S n) return n = S (length xs) -> list A with\n    | F1 => const []\n    | FS j => fun H => x :: take xs (rew H in j)\n    end eq_refl\n  end.\n\nFixpoint drop {A : Type} (xs : list A) : Fin.t (S (length xs)) -> list A :=\n  match xs with\n  | [] => const []\n  | x :: xs => fun i =>\n    match i in Fin.t (S n) return n = S (length xs) -> list A with\n    | F1 => const (x :: xs)\n    | FS j => fun H => drop xs (rew H in j)\n    end eq_refl\n  end.\n\nLemma Forall_lookup {A : Type} {P : A -> Prop} {xs : list A} (H : Forall P xs) : forall i, P (lookup xs i).\nProof.\n  induction H.\n  - intros.\n    inversion i.\n  - intros.\n    apply (Fin.caseS' i).\n    + apply H.\n    + apply IHForall.\nDefined.\n\nEnd List.\n\nModule Vector.\nImport VectorDef.\nImport VectorNotations.\n\nFixpoint take {A : Type} (m : nat) {n : nat} : VectorDef.t A (m+n) -> VectorDef.t A m :=\n  match m return VectorDef.t A (m + n) -> VectorDef.t A m with\n  | 0 => Basics.const []\n  | S m => fun xs =>\n    match xs in VectorDef.t _ l return l = S m + n -> VectorDef.t A (S m) with\n    | [] => fun H => False_rect _ (O_S _ H)\n    | x :: xs => fun H => x :: take m (rew eq_add_S _ _ H in xs)\n    end eq_refl\n  end.\n\nFixpoint drop {A : Type} (m : nat) {n : nat} : VectorDef.t A (m+n) -> VectorDef.t A n :=\n  match m return VectorDef.t A (m + n) -> VectorDef.t A n with\n  | 0 => id\n  | S m => fun xs =>\n    match xs in VectorDef.t _ l return l = S m + n -> VectorDef.t A n with\n    | [] => fun H => False_rect _ (O_S _ H)\n    | x :: xs => fun H => drop m (rew eq_add_S _ _ H in xs)\n    end eq_refl\n  end.\n\nFixpoint tabulate {A : Type} {n : nat} : (Fin.t n -> A) -> VectorDef.t A n :=\n  match n as m return m = n -> (Fin.t m -> A) -> VectorDef.t A n with\n  | 0 => fun H f => rew H in []\n  | S n' => fun H f => rew H in (f F1 :: tabulate (f ∘ FS))\n  end eq_refl.\n\nDefinition sum_nat {n : nat} : VectorDef.t nat n -> nat :=\n  fun xs => fold_right plus xs 0.\n\nDefinition inner_product {n : nat} : VectorDef.t nat n -> VectorDef.t nat n -> nat :=\n  fun xs ys => sum_nat (map2 mult xs ys).\n\nEnd Vector.\n\nModule Fin.\n\nFixpoint inject1 {n : nat} : Fin.t n -> Fin.t (S n) :=\n  match n return Fin.t n -> Fin.t (S n) with\n  | 0 => Fin.case0 _\n  | S n => fun i =>\n    match i in Fin.t (S m) return m = n -> Fin.t (S (S n)) with\n    | F1 => const F1\n    | FS j => fun H => FS (inject1 (rew H in j))\n    end eq_refl\n  end.\n\nFixpoint sum_Fin {n : nat} : (Fin.t n -> nat) -> nat :=\n  match n with\n  | 0 => const 0\n  | S n => fun f => f F1 + sum_Fin (f ∘ FS)\n  end.\n\nDefinition toNat {n : nat} : Fin.t n -> nat := fun x => proj1_sig (Fin.to_nat x).\n\nEnd Fin.\n\nImport List.\nImport Vector.\nImport Fin.\n\nDefinition solution_set (xs : list Z) :=\n  sigT (fun i : Fin.t (length xs) =>\n  sigT (fun j : Fin.t (length xs) =>\n  sig  (fun k : Fin.t (length xs) =>\n    toNat i < toNat j < toNat k /\\\n    Z.sub (lookup xs j) (lookup xs i) = Z.sub (lookup xs k) (lookup xs j)\n  ))).\n\nDefinition Iso (A B : Type) : Prop :=\n  exists (f : A -> B) (g : B -> A),\n  g ∘ f = id /\\ f ∘ g = id.\n\nDefinition solution_rel (xs : list Z) (n : nat) := Iso (solution_set xs) (Fin.t n).\n\nImport ListNotations.\nFixpoint count (x : Z) (xs : list Z) : nat :=\n  match xs with\n  | [] => 0\n  | y :: xs =>\n    if Z.eq_dec x y\n      then S (count x xs)\n      else count x xs\n  end.\n\n\nDefinition toZ {n : nat} : Fin.t n -> Z := fun x => Z.of_nat (proj1_sig (Fin.to_nat x)).\n\nLocal Open Scope Z_scope.\nDefinition distribution (xs : list Z) (a b : Z) (Hab : a <= b) : VectorDef.t nat (Z.to_nat (b - a)) :=\n  tabulate (fun i : Fin.t (Z.to_nat (b-a)) => count (a + toZ i) xs).\n\nLemma Connex_Z_le_le (x y : Z) : ({x <= y} + {y <= x}).\nProof.\n  destruct (x <=? y) eqn: P;\n  [ left; apply Z.leb_le\n  | right; apply Z.lt_le_incl; apply Z.leb_gt\n  ];\n  assumption.\nDefined.\n\nImport VectorDef.\nImport Vector.\n\nDefinition solution_dec (xs : list Z) (a b : Z) (Hab : a <= b) (H : List.Forall (fun x => a <= x < b) xs) : nat :=\n  sum_Fin (fun i =>\n    let l := Z.to_nat (b-a) in\n    let xs_i := List.take xs (inject1 i) in\n    let xs_k := List.drop xs (FS i) in\n    let xj := lookup xs i in\n    let xj_range : a <= xj < b := Forall_lookup H i in\n      match Connex_Z_le_le (2*xj) (a+b-1) with\n      | left P =>\n        let m := Z.to_nat (2*xj - 2*a + 1) in\n        let m_split : l = (m + (l - m))%nat := ltac: (lia) in\n        let ds_i := take m (rew m_split in distribution xs_i a b Hab) in\n        let ds_k := take m (rew m_split in distribution xs_k a b Hab) in\n        inner_product ds_i (rev ds_k)\n      | right P =>\n        let m := Z.to_nat (2*xj - (a+b-1)) in\n        let m_split : l = (m + (l - m))%nat := ltac: (lia) in\n        let ds_i := drop m (rew m_split in distribution xs_i a b Hab) in\n        let ds_k := drop m (rew m_split in distribution xs_k a b Hab) in\n        inner_product ds_i (rev ds_k)\n      end).\n", "meta": {"author": "damhiya", "repo": "VerifiedBOJ", "sha": "3840907815133d840aa8976d273564ad63c0a8e2", "save_path": "github-repos/coq/damhiya-VerifiedBOJ", "path": "github-repos/coq/damhiya-VerifiedBOJ/VerifiedBOJ-3840907815133d840aa8976d273564ad63c0a8e2/13558/model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.664321382417347}}
{"text": "Require Import SegmentQueue.util.everything.\nFrom Coq Require Import ssreflect.\nRequire Import stdpp.base stdpp.list.\nRequire Import SegmentQueue.util.find_index.\n\nFixpoint count_matching {A} (P: A -> Prop) {H': forall x, Decision (P x)} (l: list A): nat :=\n  match l with\n  | nil => 0\n  | cons x l' => if decide (P x) then S (count_matching P l') else count_matching P l'\n  end%GEN_IF.\n\nDefinition sum := foldr Nat.add 0.\n\nTheorem sum_app a b: sum (a ++ b) = sum a + sum b.\nProof. induction a=> //=. rewrite IHa; lia. Qed.\n\nTheorem count_matching_is_sum_map {A} (P: A -> Prop) {H': forall x, Decision (P x)} l:\n  count_matching P l =\n  sum (map (fun x => if decide (P x) then 1 else 0)%GEN_IF l).\nProof. induction l; auto. simpl. destruct (decide (P a)); simpl; auto. Qed.\n\nTheorem count_matching_app {A} (P: A -> Prop) {H': forall x, Decision (P x)} (l1 l2: list A):\n  count_matching P (l1 ++ l2) = (count_matching P l1 + count_matching P l2)%nat.\nProof. rewrite !count_matching_is_sum_map map_app sum_app //. Qed.\n\nTheorem count_matching_alter\n        {A} (P: A -> Prop) {H': forall x, Decision (P x)}:\n  let to_num x := (if decide (P x) then 1%nat else 0%nat)%GEN_IF in\n  forall v f l i, l !! i = Some v ->\n               count_matching P (alter f i l) =\n               (count_matching P l + (to_num (f v)) - (to_num v))%nat.\nProof.\n  intros ? v f l i HEl. rewrite -[in count_matching P l](take_drop_middle l i v HEl).\n  erewrite take_drop_middle_alter; last done.\n  rewrite !count_matching_is_sum_map.\n  rewrite !map_app !sum_app=> /=. subst to_num. simpl. lia.\nQed.\n\nTheorem count_matching_le_length\n        {A} (P: A -> Prop) {H': forall x, Decision (P x)} (l: list A):\n  (count_matching P l <= length l)%nat.\nProof. induction l; first done. simpl. destruct (decide (P a)); lia. Qed.\n\nTheorem count_matching_complement\n        {A} (P: A -> Prop) {H': forall x, Decision (P x)} (l: list A):\n  count_matching (fun b => not (P b)) l = (length l - count_matching P l)%nat.\nProof.\n  induction l; first done.\n  simpl.\n  destruct (decide (P a)); destruct (decide (not (P a))); try contradiction.\n  done.\n  rewrite -minus_Sn_m; try lia.\n  by apply count_matching_le_length.\nQed.\n\nTheorem count_matching_take\n        {A} (P: A -> Prop) {H': forall x, Decision (P x)} (l: list A):\n  forall i, count_matching P (take i l) =\n       (count_matching P l - count_matching P (drop i l))%nat.\nProof.\n  intros i.\n  replace (count_matching P l) with (count_matching P (take i l ++ drop i l)).\n  2: by rewrite take_drop.\n  rewrite count_matching_app. lia.\nQed.\n\nTheorem count_matching_drop\n        {A} (P: A -> Prop) {H': forall x, Decision (P x)} (l: list A):\n  forall i, count_matching P (drop i l) =\n       (count_matching P l - count_matching P (take i l))%nat.\nProof.\n  intros i.\n  replace (count_matching P l) with (count_matching P (take i l ++ drop i l)).\n  2: by rewrite take_drop.\n  rewrite count_matching_app. lia.\nQed.\n\nTheorem count_matching_all\n  {A} (P: A -> Prop) {H': forall x, Decision (P x)} (l: list A):\n  count_matching P l = length l <-> ∀ i, i ∈ l → P i.\nProof.\n  split.\n  - induction l as [|a l]=> /=.\n    * intros _ i Hi. inversion Hi.\n    * destruct (decide (P a)).\n      + case. intros HOk i Hi.\n        inversion Hi; subst; first done. by apply IHl.\n      + intros HContra.\n        assert (count_matching P l ≤ length l); last lia.\n        apply count_matching_le_length.\n  - intros HEl. induction l as [|a l] => //=.\n    rewrite decide_True; last by apply HEl; constructor.\n    rewrite IHl //.\n    intros i Hi. apply HEl. by constructor.\nQed.\n\nTheorem count_matching_none\n  {A} (P: A -> Prop) {H': forall x, Decision (P x)} (l: list A):\n  count_matching P l = 0 <-> ∀ i, i ∈ l → ¬ P i.\nProof.\n  assert (count_matching P l = 0 <->\n          count_matching (fun b => ¬ (P b)) l = length l) as ->.\n  {\n    rewrite count_matching_complement.\n    assert (count_matching P l ≤ length l).\n    by apply count_matching_le_length.\n    split; lia.\n  }\n  apply count_matching_all.\nQed.\n\nLemma present_cells_in_take_i_if_next_present_is_Si\n  {A: Type} (P: A -> Prop) {H': forall x, Decision (P x)} (i: nat) (l: list A):\n    find_index P l = Some i ->\n    count_matching P (take i l) = O.\nProof.\n  intros HFindSome. apply count_matching_none.\n  apply find_index_Some in HFindSome. intros v HEl.\n  destruct HFindSome as [_ HNotPresent].\n  apply elem_of_list_lookup_1 in HEl. destruct HEl as [i' HEl].\n  destruct (decide (i ≤ i')).\n  by rewrite lookup_take_ge in HEl; last lia.\n  rewrite lookup_take in HEl; last lia.\n  destruct (HNotPresent i') as (v' & HEl' & HProof); first lia.\n  by simplify_eq.\nQed.\n\nLemma present_cells_in_take_1_drop_i_if_next_present_is_Si\n  {A: Type} (P: A -> Prop) {H': forall x, Decision (P x)} (i: nat) (l: list A):\n    find_index P l = Some i ->\n    count_matching P (take 1 (drop i l)) = 1%nat.\nProof.\n  intros HFindSome.\n  apply find_index_Some in HFindSome.\n  destruct HFindSome as [[v [HIn HPresent]] HNotPresent].\n  assert (i < length l)%nat as HLt.\n  { apply lookup_lt_is_Some. by eexists. }\n\n  replace (drop i l) with (v :: drop (S i) l).\n  { simpl. destruct (decide (P v)); try contradiction. done. }\n  assert (i = length (take i l))%nat as HH.\n  by rewrite take_length_le; lia.\n  replace (drop i l) with (drop i (take i l ++ v :: drop (S i) l)).\n  { symmetry. rewrite drop_app_le; last lia. rewrite drop_ge //. lia. }\n  by rewrite take_drop_middle.\nQed.\n\nLemma present_cells_in_take_Si_if_next_present_is_Si\n  {A: Type} (P: A -> Prop) {H': forall x, Decision (P x)} (i: nat) (l: list A):\n    find_index P l = Some i ->\n    count_matching P (take (S i) l) = 1%nat.\nProof.\n  intros HFindSome.\n  change (S i) with (1 + i)%nat.\n  rewrite Nat.add_comm -take_take_drop count_matching_app.\n  rewrite present_cells_in_take_1_drop_i_if_next_present_is_Si //.\n  rewrite present_cells_in_take_i_if_next_present_is_Si //.\nQed.\n\nLemma absent_cells_in_drop_Si_if_next_present_is_i\n  {A: Type} (P: A -> Prop) {H': forall x, Decision (P x)} (i: nat) (l: list A):\n    find_index P l = Some i ->\n  count_matching (λ b, not (P b)) l =\n  (i + count_matching (λ b, not (P b)) (drop (S i) l))%nat.\nProof.\n  intros HFindSome.\n  repeat rewrite count_matching_complement.\n  rewrite drop_length.\n\n  replace (count_matching P l) with\n      (count_matching P (take (S i) l ++ drop (S i) l)).\n  2: by rewrite take_drop.\n\n  rewrite count_matching_app Nat.sub_add_distr.\n  rewrite present_cells_in_take_Si_if_next_present_is_Si; try done.\n\n  repeat rewrite -Nat.sub_add_distr /=.\n  remember (count_matching (_) (drop (S i) _)) as K.\n  rewrite plus_n_Sm.\n  rewrite -(Nat.add_comm (S K)) Nat.sub_add_distr.\n  assert (K <= length l - S i)%nat as HKLt.\n  {\n    rewrite HeqK. eapply transitivity.\n    apply count_matching_le_length.\n    by rewrite drop_length.\n  }\n  assert (i < length l)%nat; try lia.\n  apply find_index_Some in HFindSome.\n  destruct HFindSome as [(v & HEl & _) _].\n  apply lookup_lt_is_Some. eauto.\nQed.\n\nTheorem count_matching_find_index_Some A (P: A -> Prop) (H': forall x, Decision (P x)) l:\n  (count_matching P l > 0)%nat -> is_Some (find_index P l).\nProof.\n  induction l; simpl; first lia.\n  destruct (decide (P a)); first by eauto.\n  destruct (find_index P l); by eauto.\nQed.\n", "meta": {"author": "anonymousPldiSubmitterCQS", "repo": "proofs", "sha": "7dc09221303978c5918b5064ba787bc2268fa0bb", "save_path": "github-repos/coq/anonymousPldiSubmitterCQS-proofs", "path": "github-repos/coq/anonymousPldiSubmitterCQS-proofs/proofs-7dc09221303978c5918b5064ba787bc2268fa0bb/theories/util/count_matching.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6643213777502492}}
{"text": "From mathcomp Require Import ssreflect.\n\nRequire Import classical_predicate_logic.\n\n(*\n  A Collection does not include itself at type theory.\n  For the above reason, we can avoid russel's paradox.\n *)\n(*\n  Collection is aliase of LogicFunction.\n *)\n(*\n  Uはこの世のすべての記号,元を集めた集合.\n  論理関数の判定により,集合を作成する. (分出公理と目的は同じ.).\n *)\n\nDefinition Collection U := LogicFunction U.\n\nDefinition In (U:Type) (X:Collection U) (x:U) : Prop := X x.\n\nNotation \"x ∈ X\" := (In _ X x) (right associativity, at level 35).\nNotation \"x ∉ X\" := (~(In _ X x)) (right associativity, at level 35).\n\nReserved Notation \"A ∪ B\" (right associativity, at level 30).\n(* Unicode of ⋃ is 22c3 *)\nReserved Notation \"⋃ X\" (right associativity, at level 30).\n\nReserved Notation \"A ∩ B\" (right associativity, at level 30).\n(* Unicode of ⋂ is 22c2 *)\nReserved Notation \"⋂ X\"  (right associativity, at level 30).\n\nReserved Notation \"A \\ B\"  (right associativity, at level 30).\n\n(* 内包の公理 *)\nTheorem AxiomOfComprehension:\n  forall U:Type, forall F:LogicFunction U, exists z':Collection U, forall a:U, a ∈ z' <-> F a.\nProof.\n  move => U F.\n  exists F.\n  move => a.\n  rewrite /iff. split => H; apply H.\nQed.\n\n(* 外延性公理 *)\nAxiom AxiomOfExtentionality:\n  forall U:Type, forall {x' y':Collection U},\n      (forall x:U, (x ∈ x' <-> x ∈ y')) -> x' = y'.\n\nTheorem collection_is_unique_existence:\n  forall U:Type, forall F:LogicFunction U, exists! y':Collection U, forall x:U, (x ∈ y') <-> F x.\nProof.\n  move => U F.\n  exists F.\n  rewrite /unique.\n  split. move => x.\n  rewrite /iff. split => H; apply H.\n  move => x' H.\n  apply AxiomOfExtentionality.\n  move => x.\n  apply: iff_sym.\n  apply: (H x).\nQed.\n\nSection Examples.\n  Inductive DayOfTheWeek : Type :=\n  | monday\n  | tuesday\n  | wednesday\n  | thursday\n  | friday\n  | saturday\n  | sunday.\n\n  Definition Weekdays : Collection DayOfTheWeek :=\n    fun d => d = monday \\/ d = tuesday \\/ d = wednesday \\/ d = thursday \\/ d = friday.\n  Definition Holidays : Collection DayOfTheWeek :=\n    fun d => d = saturday \\/ d = sunday.\n\n  Goal monday ∈ Weekdays.\n  Proof.\n    left.\n    reflexivity.\n  Qed.\n\n  Goal forall d:DayOfTheWeek, d ∈ Weekdays <-> Weekdays d.\n  Proof.\n    move => d.\n    rewrite /iff. split => H; apply H.\n  Qed.\n\nEnd Examples.\n\nExport classical_predicate_logic.\n", "meta": {"author": "seisyuu-hantatsushi", "repo": "implement_set_theory_in_coq", "sha": "49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c", "save_path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq", "path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq/implement_set_theory_in_coq-49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c/coq/setsontypetheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6643213736540946}}
{"text": "Require Import Word.\n\nRequire Import Vector.\nRequire Import CoLoR_VecUtil.\n\nRequire Import Equality.\n\nImport BOps.\n\nSet Implicit Arguments.\n\n\nDefinition Distr T f g := forall a b c : T,\n    g a (f b c) = f (g a b) (g a c).\n\nDefinition Comm T (f : T -> T -> T) := forall a b, f a b = f b a.\n\nArguments Distr [T] f g.\nArguments Comm [T] _.\n\nSection Basics.\n\n  Variable f g : bool -> bool -> bool.\n  Variable n : nat.\n\n  Lemma liftDistr : Distr f g -> Distr (@liftBV2 (@Vmap2 _ _ _ f) n)\n                                       (@liftBV2 (@Vmap2 _ _ _ g) n).\n    unfold Distr.\n    intros.\n    destruct a, b, c.\n    unfold Bvector.Bvector in *.\n    simpl.\n    f_equal.\n    induction n.\n    now VOtac.\n    VSntac b0. VSntac b1. VSntac b.\n    simpl.\n    f_equal.\n    apply H.\n    apply IHn0.\n  Qed.\n\n  Lemma liftComm : Comm f -> Comm (@liftBV2 (@Vmap2 _ _ _ f) n).\n    unfold Comm.\n    intros.\n    destruct a, b.\n    unfold Bvector.Bvector in *.\n    simpl.\n    f_equal.\n    induction n.\n    now VOtac.\n    VSntac b0. VSntac b.\n    simpl.\n    f_equal.\n    apply H.\n    apply IHn0.\n  Qed.\n\nEnd Basics.\n\nLemma ntimesCompose A (f : A -> A) n1 n2 a\n  : ntimes f n1 (ntimes f n2 a) = ntimes f (n1 + n2) a.\n  induction n1.\n  trivial.\n  simpl.\n  f_equal.\n  apply IHn1.\nQed.\n\nLemma OrComm n (w1 w2 : Word.t n)\n  : OrW w1 w2 = OrW w2 w1.\n  unfold OrW, BVOr.\n  apply liftComm.\n  unfold Comm.\n  apply Bool.orb_comm.\nQed.\n\nLemma AndComm n (w1 w2 : Word.t n)\n  : AndW w1 w2 = AndW w2 w1.\n  unfold AndW, BVAnd.\n  apply liftComm.\n  unfold Comm.\n  apply Bool.andb_comm.\nQed.\n\nLemma OrDistrAnd n (w1 w2 w3 : Word.t n)\n  : OrW w1 (AndW w2 w3) = AndW (OrW w1 w2) (OrW w1 w3).\n  unfold OrW, BVOr, BVAnd.\n  apply liftDistr.\n  unfold Distr.\n  apply Bool.orb_andb_distrib_r.\nQed.\n\nLemma AndDistrOr n (w1 w2 w3 : Word.t n)\n  : AndW w1 (OrW w2 w3) = OrW (AndW w1 w2) (AndW w1 w3).\n  unfold OrW, BVOr, BVAnd.\n  apply liftDistr.\n  unfold Distr.\n  apply Bool.andb_orb_distrib_r.\nQed.\n\nLemma rotRCompose n r1 r2 (w : Word.t n)\n  : RotRW r1 (RotRW r2 w) = RotRW (r1 + r2) w.\nProof.\n  destruct w.\n  unfold RotRW.\n  simpl liftBV.\n  f_equal.\n  unfold BRotR.\n  apply ntimesCompose.\nQed.\n\nLemma rotRDistrXor n : forall (w1 w2 : Word.t n) r,\n    RotRW r (XorW w1 w2) = XorW (RotRW r w1) (RotRW r w2).\nProof.\n  destruct w1 as [ b1 ].\n  destruct w2 as [ b2 ].\n  intro r.\n  unfold RotRW.\n  unfold XorW.\n  cbn [liftBV liftBV2].\n  f_equal.\n  (* Reduced to assertion on BVectors *)\n  induction r.\n  - unfold BRotR; trivial.\n  - unfold BRotR.\n    unfold Word.BOps.ntimes.\n    fold Word.BOps.ntimes.\n    fold (BRotR r (BVXor b1 b2)).\n    fold (BRotR r b1).\n    fold (BRotR r b2).\n    rewrite IHr.\n    generalize (BRotR r b1) as bv1.\n    generalize (BRotR r b2) as bv2.\n    (* Reduced to the single rotation case *)\n    clear IHr.\n    intros.\n    destruct n.\n    simpl; trivial.\n    VSntac (Vmap2 xorb bv1 bv2).\n    VSntac bv1. VSntac bv2.\n    simpl.\n    (* This assertion does not have an induction by n proof *)\n    f_equal.\n    * destruct n.\n      assert (Vtail bv1 = Vnil).\n      apply VO_eq.\n      rewrite H2.\n      assert (Vtail bv2 = Vnil).\n      apply VO_eq.\n      rewrite H3.\n      trivial.\n\n      assert (n < S n) by auto.\n      repeat rewrite (Vlast_nth _ _ H2).\n      unfold BVXor.\n      rewrite Vnth_map2; trivial.\n    * unfold BVXor.\n      unfold Vmap2 at 1.\n      fold (Vmap2 xorb bv1 bv2).\n      rewrite <- H0.\n      rewrite <- H1.\n      (* Finally down to an assertion that can be proved by induction on n *)\n      clear b1 b2 r H H0 H1.\n      induction n.\n      + apply VO_eq.\n      + VSntac bv1. VSntac bv2.\n\n        unfold Vremove_last at 1.\n        simpl.\n        f_equal.\n        (* Now to rewrite to look like induction hypothesis *)\n        repeat rewrite Vsub_cons.\n        unfold Vmap2 at 1.\n        fold (Vmap2 xorb (Vtail bv1) (Vtail bv2)).\n        rewrite (Vsub_pi (Vremove_last_aux n)).\n        fold (Vremove_last (Vmap2 xorb (Vtail bv1) (Vtail bv2))).\n        rewrite (Vsub_pi (Vremove_last_aux n)).\n        fold (Vremove_last (Vtail bv1)).\n        rewrite (Vsub_pi (Vremove_last_aux n)).\n        fold (Vremove_last (Vtail bv2)).\n\n        apply IHn.\nQed.\n", "meta": {"author": "raaz-crypto", "repo": "verse-coq", "sha": "621f86f4adc3bad53458186f0272425db13d2db7", "save_path": "github-repos/coq/raaz-crypto-verse-coq", "path": "github-repos/coq/raaz-crypto-verse-coq/verse-coq-621f86f4adc3bad53458186f0272425db13d2db7/src/Verse/WordFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6642832539468441}}
{"text": "(* Transition system lemmas. *)\n\nFrom set_theory Require Import lib.\n\n(* Prove a property of a function that emulates a transition system. *)\nSection Self_extending_state_transition_system.\n\n(* A state transition system *)\nVariable State : Type.\nVariable Trans : Type.\nVariable Value : Type.\nVariable step : Trans -> State -> State.\nVariable output : State -> Value.\n\n(* The state output value tracks transition symbols. *)\nVariable Symbol : Type.\nVariable symb : Trans -> Symbol.\nVariable push : Symbol -> Value -> Value.\nVariable peek : Value -> Symbol.\n\n(* The step function encodes the transition into the state output. *)\nHypothesis step_push : ∀s t, output (step t s) = push (symb t) (output s).\nHypothesis peek_push : ∀a v, peek (push a v) = a.\n\n(* A function which takes a number of steps and outputs a value. *)\nVariable f : State -> nat -> Value.\n\n(* State transition used by f. *)\nVariable trans : State -> Trans.\n\n(* f computes transitions. *)\nHypothesis f_step : ∀s n, f s (S n) = f (step (trans s) s) n.\nHypothesis f_output : ∀s, f s 0 = output s.\n\n(* f pushes one transition symbol at each successor. *)\nTheorem self_extending s n :\n  f s (S n) = push (peek (f s (S n))) (f s n).\nProof.\nrevert s; induction n; intros.\n- now rewrite f_step, ?f_output, step_push, peek_push.\n- now rewrite f_step, IHn, peek_push, (f_step s).\nQed.\n\nEnd Self_extending_state_transition_system.\n", "meta": {"author": "bergwerf", "repo": "settheory", "sha": "e3293df1f76ee7d7da46f2bf3993e8b4d9b3d1dd", "save_path": "github-repos/coq/bergwerf-settheory", "path": "github-repos/coq/bergwerf-settheory/settheory-e3293df1f76ee7d7da46f2bf3993e8b4d9b3d1dd/ts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6642832424055155}}
{"text": "Require 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  simpl in H.\n  exfalso.\n  apply (Lt.lt_n_0 0 H).\n  destruct a.\n  simpl in H.\n  assert (exists x : nat, 1 < x /\\ In x xs).\n  apply IHxs.\n  apply (Lt.lt_trans (length xs) (S (length xs)) (sum xs)).\n  apply Lt.lt_n_Sn.\n  exact H.\n  destruct H0.\n  exists x.\n  destruct H0.\n  split.\n  assumption.\n  simpl.\n  right.\n  assumption.\n  destruct a.\n  simpl in H.\n  apply Lt.lt_S_n in H.\n  apply IHxs in H.\n  destruct H.\n  destruct H.\n  exists x.\n  split.\n  assumption.\n  simpl.\n  right.\n  assumption.\n  exists (S (S a)).\n  split.\n  apply Lt.lt_n_S.\n  apply Lt.lt_0_Sn.\n  simpl.\n  left.\n  reflexivity.\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/12.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6642832280103191}}
{"text": "Require Import Omega.\n\nLemma test_nat:\n  forall n, (5 + pred n <= 5 + n).\nProof.\n  intros.\n  zify.\n  omega.\nQed.\n\nLemma test_N:\n  forall n, (5 + N.pred n <= 5 + n)%N.\nProof.\n  intros.\n  zify.\n  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/test-suite/bugs/opened/6602.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6642529029254584}}
{"text": "Add LoadPath \"Category\".\nRequire Import Category Epsilon.\n\nGeneralizable Variables hom obj.\n\nDefinition epimorphism `{Category} {A B} (f : hom A B) :=\n  forall C (g1 g2 : B --> C), g1 • f = g2 • f -> g1 = g2.\n\nDefinition monomorphism `{Category} {A B} (f : hom A B) :=\n  forall C (g1 g2 : hom C A), f • g1 = f • g2 -> g1 = g2.\n\nDefinition isInverse `{Category} {A B} (f : hom A B) (f' : hom B A) := f • f' = 1 /\\ f' • f = 1.\n\nDefinition isomorphism `{Category} {A B} (f : hom A B) :=\n  exists (f' : hom B A), isInverse f f'.\n\nDefinition isomorphic `{Category} (A B : obj) := exists (f : hom A B), isomorphism f.\n\nHint Unfold epimorphism monomorphism isInverse isomorphism isomorphic.\n\nNotation \"A == B\" := (isomorphic A B) (at level 70, right associativity).\n\nLemma isomorphic_symmertric `{Category} {A B}: A == B <-> B ==  A.\nProof.\n  unfold \"==\". autounfold. split; intros [f [f' [L R]]]; exists f', f; split; auto.\nQed.\n\nLemma isoIsMono: forall `{Category} {A B} (f : hom A B), isomorphism f -> monomorphism f.\nProof.\n  autounfold. intros. inversion H0 as [f' [L R]].\n  replace g2 with (1 • g2) by apply idLeft.\n  replace g1 with (1 • g1) by apply idLeft.\n  rewrite <- R. rewrite <- compAssoc. rewrite H1. apply compAssoc.\nQed.\n\nLemma isoIsEpi: forall `{Category} {A B} (f :hom A B), isomorphism f -> epimorphism f.\nProof.\n  autounfold. intros. inversion H0 as [f' [L R]].\n  replace g2 with (g2 • 1) by apply idRight.\n  replace g1 with (g1 • 1) by apply idRight.\n  unfold \"1\" in *.\n  rewrite <- L. rewrite compAssoc. rewrite H1. rewrite compAssoc. reflexivity.\nQed.\n\nLemma inverseUnique: forall `{Category} {A B} (f1 f2 : hom A B) (f : hom B A), \n  isInverse f1 f /\\ isInverse f2 f -> f1 = f2.\nProof.\n  intros obj hom cid comp Cat A B f1 f2 f Inv. \n  destruct Inv as [Inv1 Inv2]. destruct Inv1 as [Inv1L Inv1R].\n  destruct Inv2 as [Inv2L Inv2R].\n  replace f1 with (f1 • 1) by apply idRight. rewrite <- Inv2R. rewrite compAssoc.\n  rewrite Inv1L. apply idLeft.\nQed.\n\nLemma isomorphism_dual : forall `(C : Category obj hom) {A B} (f : hom A B), \n  @isomorphism _ _ _ _ C _ _ f <->\n  @isomorphism _ _ _ _ (Dual C) _ _ f.\nProof.\n  intros. autounfold. unfold \"1\". unfold \"•\". unfold \"-->\". \n  split; intros [f' [L R]]; exists f'; split; auto.\nQed.\n\nLemma isomorphic_dual : forall `(C : Category) {A B},\n  @isomorphic _ _ _ _ C A B <-> @isomorphic _ _ _ _ (Dual C) A B.\nProof.\n  autounfold. intros.\n  split; intros [f [f' [L R]]]; exists f', f; auto. \nQed.\n\nLemma monomorphism_compose : forall `{Category obj hom} \n  {A B C} (f : hom B C) (g : hom A B), \n  monomorphism f -> monomorphism g -> monomorphism (f • g).\nProof.\n  autounfold. intros. apply H1. apply H0. repeat (rewrite compAssoc).\n  apply H2.\nQed.\n\nLemma monomorphism_decompose : forall `{Category obj hom}\n  {A B C} (f : hom B C) (g : hom A B),\n  monomorphism (f • g) -> monomorphism g.\nProof.\n  autounfold. intros. apply H0. repeat (rewrite <- compAssoc).\n  rewrite H1. reflexivity.\nQed.\n\nLemma epimorphism_compose : forall `{Category obj hom} \n  {A B C} (f : hom B C) (g : hom A B), \n  epimorphism f -> epimorphism g -> epimorphism (f • g).\nProof.\n  intros. apply (@monomorphism_compose _ _ _ _ (Dual H)); auto.\nQed.\n\nLemma epimorphism_decompose : forall `{Category obj hom}\n  {A B C} (f : hom B C) (g : hom A B),\n  epimorphism (f • g) -> epimorphism f.\nProof.\n  intros. eapply (@monomorphism_decompose _ _ _ _ (Dual H)).\n  apply H0.\nQed.\n\n(*** Initial and Terminal objects *)\n\nDefinition isTerminal `{C : Category} (T : obj) := forall A, exists ! f : hom A T, True.\n\nDefinition bang `{Category obj} (T : obj) (TH : isTerminal T) (A : obj) : A --> T.\n  unfold isTerminal in TH. specialize TH with A.\n  apply constructive_indefinite_description in TH. destruct TH. apply x.\nDefined.\n\nNotation \"! H A\" := (bang _ H A) (at level 30).\n\nLemma bang_unique `{Category obj} (T : obj) (TH : isTerminal T) :\n  forall A (h : A --> T), h = (bang _ TH A).\nProof.\n  intros. destruct (TH A). destruct H0. assert (x = h).\n  apply H1. constructor. subst. apply H1. constructor.\nQed.\n\nHint Unfold isTerminal.\n\nLemma terminalUniqueIso1 `{C : Category} : \n  forall B1 B2, isTerminal B1 /\\ isTerminal B2 -> B1 == B2.\nProof.\n  autounfold. intros B1 B2 [TermB1 TermB2].\n  pose proof TermB1 as TermB1Copy.\n  pose proof TermB2 as TermB2Copy.\n  destruct TermB1 with B1 as [id1 Uid1]. clear TermB1.\n  destruct TermB2 with B2 as [id2 Uid2]. clear TermB2.\n  destruct TermB1Copy with B2 as [f1 Uf1]. clear TermB1Copy.\n  destruct TermB2Copy with B1 as [f2 Uf2]. clear TermB2Copy.\n  exists f2. exists f1. split.\n  - inversion Uid2. rewrite <- H0 with (f2 • f1) by constructor. rewrite (H0 1) by \n    constructor. reflexivity.\n  - inversion Uid1. rewrite <- H0 with (f1 • f2) by constructor. rewrite (H0 1) by \n    constructor. reflexivity.\nQed.\n\nLemma terminalUniqueIso2 `{C : Category}: \n  forall B1 B2, isTerminal B1 /\\ B1 == B2 -> isTerminal B2.\nProof.\n  autounfold. intros B1 B2 Con. \n  destruct Con as [T [f [f' Inv]]].\n  intros A. assert (exists ! g : hom A B1, True) by apply T.\n  destruct H. exists (f • x). split.\n  - apply I.\n  - intros g' Top. replace g' with (1 • g') by apply idLeft.\n    inversion Inv as [L R]. rewrite <- L. rewrite <- compAssoc. \n    replace (f' • g') with x; try reflexivity.\n    + apply H. constructor.\nQed.\n\nDefinition isInitial `{C : Category} (I : obj) := forall A, exists ! f : hom I A, True.\n\nHint Unfold isInitial.\n\nCorollary initialDualTerminal {obj hom cid comp} `(C : Category obj hom cid comp): \n  forall o, @isTerminal _ _ _ _ C o <-> @isInitial _ _ _ _ (Dual C) o.\nProof.\n  autounfold. intros. split; [intros hI A | intros hT A].\n  - destruct hI with A as [f [[] H]]. \n    exists f. split; try apply I. intros g []. rewrite <- H; auto.\n  - destruct hT with A as [f [[] H]]. \n    exists f. split; try apply I. intros g []. rewrite <- H; auto.\nQed.\n\nLemma initialUniqueIso1 `{C : Category} : forall B1 B2, isInitial B1 /\\ isInitial B2 \n  -> B1 == B2.\nProof.\n  intros.\n  rewrite isomorphic_dual. apply terminalUniqueIso1.\n  destruct H. split; auto.\nQed.\n\nLemma initialUniqueIso2 `{C : Category}: forall B1 B2, \n  isInitial B1 /\\ B1 == B2 -> isInitial B2.\nProof.\n  intros B1 B2 [I E].\n  rewrite <- (initialDualTerminal (Dual C) B2). eapply terminalUniqueIso2.\n  split.\n  - apply I.\n  - rewrite isomorphic_symmertric. rewrite isomorphic_dual.\n    rewrite isomorphic_symmertric. apply E.\nQed.", "meta": {"author": "mirithering", "repo": "coq", "sha": "bff4429c146a998a416f3c177b772b0fefd92d46", "save_path": "github-repos/coq/mirithering-coq", "path": "github-repos/coq/mirithering-coq/coq-bff4429c146a998a416f3c177b772b0fefd92d46/Category/SpecialMorphismsAndObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619306896955, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.6642130699532515}}
{"text": "Require Import GeoCoq.Axioms.parallel_postulates.\nRequire Import GeoCoq.Tarski_dev.Annexes.saccheri.\n\nSection existential_triangle_rah.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma existential_triangle__rah : postulate_of_existence_of_a_triangle_whose_angles_sum_to_two_rights -> postulate_of_right_saccheri_quadrilaterals.\nProof.\n  intro et.\n  destruct et as [A [B [C [D [E [F]]]]]].\n  spliter.\n  apply (t22_14__rah A B C D E F); auto.\nQed.\n\nEnd existential_triangle_rah.", "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/existential_triangle_rah.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6642059253464939}}
{"text": "(* Exercise 55 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_055 : ~(forall x, P x /\\ Q x) /\\ (forall x, Q x) -> ~(forall x, P x).\nProof.\nimp_i a1.\nneg_i (forall x:D, P x /\\ Q x) a2.\ncon_e1 (forall x:D, Q x).\nhyp a1.\nall_i a.\ncon_i.\nall_e (forall x:D, P x) a.\nhyp a2.\nall_e (forall x:D, Q x) a.\ncon_e2 (~(forall x:D, P x /\\ Q x)).\nhyp a1.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred055.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.6641216318750499}}
{"text": "Require Import init.\n\nRequire Export tensor_algebra_defs.\nRequire Export tensor_algebra_base.\nRequire Import algebra_category.\nRequire Import linear_span.\nRequire Import linear_subspace.\nRequire Import linear_grade_sum.\nRequire Import linear_extend.\n\nRequire Import nat.\nRequire Import list.\nRequire Import unordered_list.\n\nSection TensorAlgebraGrade.\n\nContext {F : CRingObj} (V : ModuleObj F).\nLet U := cring_U F.\n\nSection Single.\n\nVariable n : nat.\n\nDefinition tensor_n_base (X : algebra_V (tensor_algebra V)) :=\n    ∃ l, X = list_prod (list_image vector_to_tensor l) ∧ list_size l = n.\n\nDefinition tensor_n_subspace := linear_span_subspace (cring_U F) tensor_n_base.\n\nDefinition tensor_n_module := make_module\n    F\n    (set_type (subspace_set tensor_n_subspace))\n    (subspace_plus_class _)\n    (subspace_zero_class _)\n    (subspace_neg_class _)\n    (subspace_plus_assoc _)\n    (subspace_plus_comm _)\n    (subspace_plus_lid _)\n    (subspace_plus_linv _)\n    (subspace_scalar_class _)\n    (subspace_scalar_id _)\n    (subspace_scalar_ldist _)\n    (subspace_scalar_rdist _)\n    (subspace_scalar_comp _)\n.\n\nEnd Single.\n\nDefinition tensor_n_algebra_module := grade_sum nat tensor_n_module.\n\nDefinition tensor_n_grade := grade_sum_grade nat tensor_n_module\n    : GradedSpace U (module_V tensor_n_algebra_module).\nLocal Existing Instances tensor_n_grade.\n\nDefinition to_tensor_n {k} (X : module_V (tensor_n_module k))\n    := single_to_grade_sum nat tensor_n_module X\n    : module_V tensor_n_algebra_module.\n\nDefinition to_tensor_n_k {m n : nat} (eq : m = n)\n    (X : module_V (tensor_n_module m)) : module_V (tensor_n_module n).\nProof.\n    rewrite <- eq.\n    exact X.\nDefined.\n\nLemma to_tensor_n_k_eq {m n : nat} (eq : m = n) :\n    ∀ X : module_V (tensor_n_module m), to_tensor_n X =\n    to_tensor_n (to_tensor_n_k eq X).\nProof.\n    intros X.\n    unfold to_tensor_n_k.\n    destruct eq; cbn.\n    reflexivity.\nQed.\n\nLemma to_tensor_n_eq : ∀ {k} a b AH BH, a = b →\n    to_tensor_n (k := k) [a|AH] = to_tensor_n (k := k) [b|BH].\nProof.\n    intros k a b AH BH eq.\n    apply f_equal.\n    apply set_type_eq; cbn.\n    exact eq.\nQed.\n\nTheorem to_tensor_n_plus : ∀ {k} (u v : module_V (tensor_n_module k)),\n    to_tensor_n (u + v) = to_tensor_n u + to_tensor_n v.\nProof.\n    intros k u v.\n    unfold to_tensor_n.\n    apply single_to_grade_sum_plus.\nQed.\n\nTheorem to_tensor_n_scalar : ∀ {k} a (v : module_V (tensor_n_module k)),\n    to_tensor_n (a · v) = a · to_tensor_n v.\nProof.\n    intros k a v.\n    unfold to_tensor_n.\n    apply single_to_grade_sum_scalar.\nQed.\n\nLemma vector_to_tensor_n_in :\n    ∀ v, subspace_set (tensor_n_subspace 1) (vector_to_tensor v).\nProof.\n    intros v.\n    cbn.\n    rewrite (span_linear_combination U).\n    assert (linear_combination_set\n        ((one (U := U), vector_to_tensor v) ː ulist_end)) as comb.\n    {\n        unfold linear_combination_set.\n        rewrite ulist_image_add.\n        rewrite ulist_image_end.\n        apply ulist_unique_single.\n    }\n    exists [_|comb].\n    split.\n    -   unfold linear_combination; cbn.\n        rewrite ulist_image_add, ulist_sum_add; cbn.\n        rewrite ulist_image_end, ulist_sum_end.\n        rewrite scalar_id, plus_rid.\n        reflexivity.\n    -   unfold linear_list_in; cbn.\n        rewrite ulist_prop_add; cbn.\n        split; [>|apply ulist_prop_end].\n        exists [v].\n        split.\n        +   rewrite list_image_single.\n            rewrite list_prod_single.\n            reflexivity.\n        +   reflexivity.\nQed.\n\nDefinition vector_to_tensor_n (v : module_V V) :=\n    to_tensor_n [vector_to_tensor v | vector_to_tensor_n_in v]\n    : module_V tensor_n_algebra_module.\n\nTheorem vector_to_tensor_n_plus : ∀ u v,\n    vector_to_tensor_n (u + v) = vector_to_tensor_n u + vector_to_tensor_n v.\nProof.\n    intros u v.\n    unfold vector_to_tensor_n.\n    rewrite <- to_tensor_n_plus.\n    apply f_equal.\n    unfold plus at 3; cbn.\n    apply set_type_eq; cbn.\n    apply vector_to_tensor_plus.\nQed.\n\nTheorem vector_to_tensor_n_scalar : ∀ a v,\n    vector_to_tensor_n (a · v) = a · vector_to_tensor_n v.\nProof.\n    intros a v.\n    unfold vector_to_tensor_n.\n    rewrite <- to_tensor_n_scalar.\n    apply f_equal.\n    unfold scalar_mult at 3; cbn.\n    apply set_type_eq; cbn.\n    apply vector_to_tensor_scalar.\nQed.\n\nLemma tensor_n_algebra_mult_in : ∀ m n a b,\n    subspace_set (tensor_n_subspace m) a → subspace_set (tensor_n_subspace n) b\n    → subspace_set (tensor_n_subspace (m + n)) (a * b).\nProof.\n    intros m n a b a_in b_in.\n    cbn in *.\n    rewrite (span_linear_combination U) in *.\n    destruct a_in as [[u u_comb] [a_eq u_in]]; subst a.\n    destruct b_in as [[v v_comb] [b_eq v_in]]; subst b.\n    unfold linear_list_in in *; cbn in *.\n    unfold linear_combination; cbn.\n    clear u_comb v_comb.\n    induction u as [|a u] using ulist_induction.\n    {\n        rewrite ulist_image_end, ulist_sum_end.\n        rewrite mult_lanni.\n        apply linear_combination_of_zero.\n    }\n    rewrite ulist_prop_add in u_in.\n    destruct u_in as [a_in u_in].\n    specialize (IHu u_in).\n    rewrite ulist_image_add, ulist_sum_add.\n    rewrite rdist.\n    apply linear_combination_of_plus; [>|exact IHu].\n    clear u u_in IHu.\n    induction v as [|b v] using ulist_induction.\n    {\n        rewrite ulist_image_end, ulist_sum_end.\n        rewrite mult_ranni.\n        apply linear_combination_of_zero.\n    }\n    rewrite ulist_prop_add in v_in.\n    destruct v_in as [b_in v_in].\n    specialize (IHv v_in).\n    rewrite ulist_image_add, ulist_sum_add.\n    rewrite ldist.\n    apply linear_combination_of_plus; [>|exact IHv].\n    clear v v_in IHv.\n    destruct a as [α a], b as [β b]; cbn in *.\n    rewrite scalar_lmult, scalar_rmult.\n    do 2 apply linear_combination_of_scalar.\n    destruct a_in as [u [a_eq u_size]]; subst a.\n    destruct b_in as [v [b_eq v_size]]; subst b.\n    assert (linear_combination_set ((one (U := U), list_prod\n        (list_image vector_to_tensor (u + v))) ː ulist_end)) as comb.\n    {\n        unfold linear_combination_set.\n        rewrite ulist_image_add, ulist_image_end.\n        cbn.\n        apply ulist_unique_single.\n    }\n    exists [_|comb].\n    split.\n    -   unfold linear_combination.\n        rewrite ulist_image_add, ulist_image_end.\n        cbn.\n        rewrite ulist_sum_add, ulist_sum_end.\n        rewrite scalar_id, plus_rid.\n        rewrite list_image_conc.\n        rewrite list_prod_mult.\n        reflexivity.\n    -   unfold linear_list_in; cbn.\n        rewrite ulist_prop_add.\n        split; [>|apply ulist_prop_end].\n        cbn.\n        exists (u + v).\n        split; [>reflexivity|].\n        rewrite <- u_size, <- v_size.\n        apply list_size_conc.\nQed.\n\nDefinition tensor_n_mult_base i j\n    (a : module_V tensor_n_algebra_module)\n    (b : module_V tensor_n_algebra_module)\n    (ai : of_grade i a) (bj : of_grade j b)\n    := to_tensor_n\n        [[ex_val ai|] * [ex_val bj|] |\n            tensor_n_algebra_mult_in i j [ex_val ai|] [ex_val bj|]\n                [|ex_val ai] [|ex_val bj]].\n\nLemma tensor_n_mult_tm : ∀ i j a b AH BH,\n    tensor_n_mult_base i j (to_tensor_n a) (to_tensor_n b) AH BH\n    = to_tensor_n [[a|] * [b|] |\n        tensor_n_algebra_mult_in i j [a|] [b|] [|a] [|b]].\nProof.\n    intros i j a b AH BH.\n    unfold tensor_n_mult_base.\n    rewrite_ex_val a' a'_eq.\n    rewrite_ex_val b' b'_eq.\n    unfold to_tensor_n in a'_eq, b'_eq.\n    apply single_to_grade_sum_eq in a'_eq, b'_eq.\n    subst a' b'.\n    reflexivity.\nQed.\n\nTheorem tensor_n_mult_base_ldist :\n    bilinear_extend_ldist_base tensor_n_mult_base.\nProof.\n    intros u' v' w' i j iu jv jw.\n    pose proof iu as [u u_eq].\n    pose proof jv as [v v_eq].\n    pose proof jw as [w w_eq].\n    change (single_to_grade_sum nat tensor_n_module)\n        with (to_tensor_n (k := i)) in u_eq.\n    change (single_to_grade_sum nat tensor_n_module)\n        with (to_tensor_n (k := j)) in v_eq, w_eq.\n    subst u' v' w'.\n    assert (of_grade j (to_tensor_n (v + w))) as vwj.\n    {\n        unfold to_tensor_n.\n        rewrite single_to_grade_sum_plus.\n        apply of_grade_plus; assumption.\n    }\n    rewrite (bilinear_extend_base_req _ _ _ _ _ _ _ _ vwj)\n        by (symmetry; apply single_to_grade_sum_plus).\n    do 3 rewrite tensor_n_mult_tm.\n    unfold to_tensor_n.\n    rewrite <- single_to_grade_sum_plus.\n    apply f_equal.\n    unfold plus at 6; cbn.\n    apply set_type_eq; cbn.\n    apply ldist.\nQed.\n\nTheorem tensor_n_mult_base_rdist :\n    bilinear_extend_rdist_base tensor_n_mult_base.\nProof.\n    intros u' v' w' i j iu iv jw.\n    pose proof iu as [u u_eq].\n    pose proof iv as [v v_eq].\n    pose proof jw as [w w_eq].\n    change (single_to_grade_sum nat tensor_n_module)\n        with (to_tensor_n (k := i)) in u_eq, v_eq.\n    change (single_to_grade_sum nat tensor_n_module)\n        with (to_tensor_n (k := j)) in w_eq.\n    subst u' v' w'.\n    assert (of_grade i (to_tensor_n (u + v))) as uvi.\n    {\n        unfold to_tensor_n.\n        rewrite single_to_grade_sum_plus.\n        apply of_grade_plus; assumption.\n    }\n    rewrite (bilinear_extend_base_leq _ _ _ _ _ _ _ uvi)\n        by (symmetry; apply single_to_grade_sum_plus).\n    do 3 rewrite tensor_n_mult_tm.\n    unfold to_tensor_n.\n    rewrite <- single_to_grade_sum_plus.\n    apply f_equal.\n    unfold plus at 6; cbn.\n    apply set_type_eq; cbn.\n    apply rdist.\nQed.\n\nTheorem tensor_n_mult_base_lscalar :\n    bilinear_extend_lscalar_base tensor_n_mult_base.\nProof.\n    intros a u' v' i j iu jv.\n    pose proof iu as [u u_eq].\n    pose proof jv as [v v_eq].\n    change (single_to_grade_sum nat tensor_n_module)\n        with (to_tensor_n (k := i)) in u_eq.\n    change (single_to_grade_sum nat tensor_n_module)\n        with (to_tensor_n (k := j)) in v_eq.\n    subst u' v'.\n    assert (of_grade i (to_tensor_n (a · u))) as aui.\n    {\n        unfold to_tensor_n.\n        rewrite single_to_grade_sum_scalar.\n        apply of_grade_scalar; assumption.\n    }\n    rewrite (bilinear_extend_base_leq _ _ _ _ _ _ _ aui)\n        by (symmetry; apply single_to_grade_sum_scalar).\n    do 2 rewrite tensor_n_mult_tm.\n    unfold to_tensor_n.\n    rewrite <- single_to_grade_sum_scalar.\n    apply f_equal.\n    unfold scalar_mult at 4; cbn.\n    apply set_type_eq; cbn.\n    apply scalar_lmult.\nQed.\n\nTheorem tensor_n_mult_base_rscalar :\n    bilinear_extend_rscalar_base tensor_n_mult_base.\nProof.\n    intros a u' v' i j iu jv.\n    pose proof iu as [u u_eq].\n    pose proof jv as [v v_eq].\n    change (single_to_grade_sum nat tensor_n_module)\n        with (to_tensor_n (k := i)) in u_eq.\n    change (single_to_grade_sum nat tensor_n_module)\n        with (to_tensor_n (k := j)) in v_eq.\n    subst u' v'.\n    assert (of_grade j (to_tensor_n (a · v))) as avj.\n    {\n        unfold to_tensor_n.\n        rewrite single_to_grade_sum_scalar.\n        apply of_grade_scalar; assumption.\n    }\n    rewrite (bilinear_extend_base_req _ _ _ _ _ _ _ _ avj)\n        by (symmetry; apply single_to_grade_sum_scalar).\n    do 2 rewrite tensor_n_mult_tm.\n    unfold to_tensor_n.\n    rewrite <- single_to_grade_sum_scalar.\n    apply f_equal.\n    unfold scalar_mult at 4; cbn.\n    apply set_type_eq; cbn.\n    apply scalar_rmult.\nQed.\n\nInstance tensor_n_mult : Mult (module_V tensor_n_algebra_module) := {\n    mult A B := bilinear_extend tensor_n_mult_base A B\n}.\n\nLocal Instance tensor_n_mult_ldist : Ldist (module_V tensor_n_algebra_module).\nProof.\n    split.\n    apply bilinear_extend_ldist.\n    -   apply tensor_n_mult_base_ldist.\n    -   apply tensor_n_mult_base_rscalar.\nQed.\nLocal Instance tensor_n_mult_rdist : Rdist (module_V tensor_n_algebra_module).\nProof.\n    split.\n    apply bilinear_extend_rdist.\n    -   apply tensor_n_mult_base_rdist.\n    -   apply tensor_n_mult_base_lscalar.\nQed.\nLocal Instance tensor_n_scalar_lmult\n    : ScalarLMult U (module_V tensor_n_algebra_module).\nProof.\n    split.\n    apply bilinear_extend_lscalar.\n    -   apply tensor_n_mult_base_rdist.\n    -   apply tensor_n_mult_base_lscalar.\nQed.\nLocal Instance tensor_n_scalar_rmult\n    : ScalarRMult U (module_V tensor_n_algebra_module).\nProof.\n    split.\n    apply bilinear_extend_rscalar.\n    -   apply tensor_n_mult_base_ldist.\n    -   apply tensor_n_mult_base_rscalar.\nQed.\n\nTheorem to_tensor_n_mult : ∀ m n a b\n    (ma : subspace_set (tensor_n_subspace m) a)\n    (nb : subspace_set (tensor_n_subspace n) b),\n    to_tensor_n [a|ma] * to_tensor_n [b|nb] =\n    to_tensor_n [a * b|tensor_n_algebra_mult_in m n a b ma nb].\nProof.\n    intros m n a b ma nb.\n    unfold mult at 1; cbn.\n    assert (of_grade (H9 := tensor_n_grade) m (to_tensor_n [a|ma])) as ma'.\n    {\n        exists [a|ma].\n        reflexivity.\n    }\n    assert (of_grade (H9 := tensor_n_grade) n (to_tensor_n [b|nb])) as nb'.\n    {\n        exists [b|nb].\n        reflexivity.\n    }\n    rewrite (bilinear_extend_homo _\n        tensor_n_mult_base_ldist tensor_n_mult_base_rdist\n        tensor_n_mult_base_lscalar tensor_n_mult_base_rscalar _ _ _ _ ma' nb').\n    rewrite tensor_n_mult_tm; cbn.\n    reflexivity.\nQed.\n\nInstance tensor_n_grade_mult : GradedAlgebraObj U (module_V tensor_n_algebra_module).\nProof.\n    split.\n    intros u' v' i j iu vj.\n    destruct iu as [u u_eq]; subst u'.\n    destruct vj as [v v_eq]; subst v'.\n    destruct u as [u u_in], v as [v v_in].\n    rewrite to_tensor_n_mult.\n    pose proof (tensor_n_algebra_mult_in _ _ _ _ u_in v_in) as uv_in.\n    exists [_|uv_in].\n    apply f_equal.\n    apply set_type_eq; reflexivity.\nQed.\n\nLemma tensor_n_one_in : subspace_set (tensor_n_subspace 0) 1.\nProof.\n    cbn.\n    rewrite (span_linear_combination U).\n    assert (linear_combination_set ((one (U := U),\n        one (U := algebra_V (tensor_algebra V))) ː ulist_end)) as comb.\n    {\n        unfold linear_combination_set.\n        rewrite ulist_image_add.\n        rewrite ulist_image_end.\n        apply ulist_unique_single.\n    }\n    exists [_|comb].\n    split.\n    -   unfold linear_combination; cbn.\n        rewrite ulist_image_add, ulist_sum_add; cbn.\n        rewrite ulist_image_end, ulist_sum_end.\n        rewrite scalar_id, plus_rid.\n        reflexivity.\n    -   unfold linear_list_in; cbn.\n        rewrite ulist_prop_add; cbn.\n        split; [>|apply ulist_prop_end].\n        exists [].\n        split.\n        +   rewrite list_image_end.\n            cbn.\n            reflexivity.\n        +   reflexivity.\nQed.\n\nLocal Instance tensor_n_one : One (module_V tensor_n_algebra_module) := {\n    one := to_tensor_n [1|tensor_n_one_in]\n}.\n\nLemma tensor_n_list_in : ∀ l, subspace_set (tensor_n_subspace (list_size l))\n    (list_prod (list_image vector_to_tensor l)).\nProof.\n    intros l.\n    cbn.\n    apply linear_span_sub.\n    exists l.\n    split; reflexivity.\nQed.\n\nLemma to_tensor_n_list : ∀ l, to_tensor_n [_|tensor_n_list_in l] =\n    list_prod (list_image vector_to_tensor_n l).\nProof.\n    intros l.\n    induction l.\n    -   unfold list_image; cbn.\n        rewrite list_prod_end.\n        unfold one; cbn.\n        apply f_equal.\n        apply set_type_eq; reflexivity.\n    -   unfold list_image; fold (list_image vector_to_tensor_n).\n        rewrite list_prod_add.\n        rewrite <- IHl.\n        unfold vector_to_tensor_n.\n        rewrite to_tensor_n_mult.\n        apply f_equal.\n        apply set_type_eq; reflexivity.\nQed.\n\nLemma tensor_n_base_in : ∀ {n} (x : set_type (tensor_n_base n)),\n    subspace_set (tensor_n_subspace n) [x|].\nProof.\n    intros n x.\n    apply linear_span_sub.\n    exact [|x].\nQed.\n\nTheorem tensor_n_sum_grade : ∀ {n} x, of_grade n x →\n    ∃ l : ulist (cring_U F * set_type (tensor_n_base n)),\n        x = ulist_sum (ulist_image\n        (λ p, fst p · to_tensor_n [_|tensor_n_base_in (snd p)]) l).\nProof.\n    intros n x nx.\n    destruct nx as [v x_eq]; subst x.\n    change (single_to_grade_sum nat tensor_n_module v) with (to_tensor_n v).\n    assert (linear_combination_of (tensor_n_base n) [v|]) as v_in.\n    {\n        rewrite <- (span_linear_combination U).\n        exact [|v].\n    }\n    destruct v_in as [[l l_comb] [l_eq l_in]].\n    assert (∃ l' : ulist (cring_U F * set_type (tensor_n_base n)),\n        [v|] = ulist_sum (ulist_image (λ p, fst p · [snd p|]) l')) as [l' l'_eq].\n    {\n        rewrite l_eq.\n        unfold linear_combination; cbn.\n        unfold linear_list_in in l_in; cbn in l_in.\n        clear l_comb l_eq.\n        induction l using ulist_induction.\n        -   exists ulist_end.\n            do 2 rewrite ulist_image_end.\n            reflexivity.\n        -   rewrite ulist_prop_add in l_in.\n            destruct l_in as [a_in l_in].\n            specialize (IHl l_in) as [l' l'_eq].\n            destruct a as [a al]; cbn in *.\n            exists ((a, [_|a_in]) ː l').\n            do 2 rewrite ulist_image_add, ulist_sum_add; cbn.\n            rewrite l'_eq.\n            reflexivity.\n    }\n    clear l l_comb l_eq l_in.\n    assert (∀ x : set_type (tensor_n_base n), subspace_set (tensor_n_subspace n) [x|]) as x_in.\n    {\n        intros x.\n        cbn.\n        apply linear_span_sub.\n        exact [|x].\n    }\n    pose (x_transfer (x : set_type (tensor_n_base n))\n        := [_|x_in x] : module_V (tensor_n_module n)).\n    pose (l := ulist_image (λ x, fst x · x_transfer (snd x)) l').\n    assert (v = ulist_sum l) as u_eq.\n    {\n        unfold l.\n        apply set_type_eq.\n        rewrite l'_eq.\n        clear l.\n        unfold x_transfer.\n        clear x_transfer.\n        clear l'_eq.\n        induction l' using ulist_induction.\n        -   do 2 rewrite ulist_image_end, ulist_sum_end.\n            reflexivity.\n        -   do 2 rewrite ulist_image_add, ulist_sum_add.\n            unfold plus at 2; cbn.\n            rewrite IHl'.\n            apply rplus.\n            unfold scalar_mult at 2; cbn.\n            reflexivity.\n    }\n    subst v.\n    exists l'.\n    unfold l.\n    clear l l'_eq.\n    induction l' as [|a l] using ulist_induction.\n    {\n        do 2 rewrite ulist_image_end, ulist_sum_end.\n        apply single_to_grade_sum_zero.\n    }\n    do 2 rewrite ulist_image_add, ulist_sum_add.\n    rewrite to_tensor_n_plus.\n    rewrite IHl.\n    apply rplus.\n    clear l IHl.\n    destruct a as [a v]; cbn.\n    rewrite to_tensor_n_scalar.\n    apply f_equal.\n    unfold x_transfer.\n    apply f_equal.\n    apply set_type_eq; reflexivity.\nQed.\n\nTheorem tensor_n_sum : ∀ x, ∃ l : ulist (U * list (module_V V)),\n    x = ulist_sum (ulist_image (λ p, fst p · list_prod\n        (list_image vector_to_tensor_n (snd p))) l).\nProof.\n    intros x.\n    induction x as [|u v i iu iv IHx] using grade_induction.\n    {\n        exists ulist_end.\n        rewrite ulist_image_end, ulist_sum_end.\n        reflexivity.\n    }\n    destruct IHx as [vl v_eq].\n    assert (∃ ul : ulist (U * list (module_V V)),\n        u = ulist_sum (ulist_image (λ p, fst p · list_prod\n            (list_image vector_to_tensor_n (snd p))) ul)) as [ul u_eq].\n    {\n        clear v iv vl v_eq.\n        pose proof (tensor_n_sum_grade _ iu) as [l l_eq].\n        subst u.\n        clear iu.\n        exists (ulist_image (λ x, (fst x, ex_val [|snd x])) l).\n        rewrite ulist_image_comp; cbn.\n        apply f_equal.\n        apply f_equal2; [>|reflexivity].\n        apply functional_ext.\n        intros [a v]; cbn.\n        apply f_equal.\n        rewrite <- to_tensor_n_list.\n        clear l.\n        rewrite_ex_val l [v_eq v_size].\n        subst i.\n        apply to_tensor_n_eq.\n        exact v_eq.\n    }\n    exists (ul + vl).\n    subst u v.\n    rewrite ulist_image_conc, ulist_sum_plus.\n    reflexivity.\nQed.\n\nLocal Instance tensor_n_mult_lid : MultLid (module_V tensor_n_algebra_module).\nProof.\n    split.\n    intros a.\n    pose proof (tensor_n_sum a) as [l a_eq]; subst a.\n    induction l as [|[a l] l'] using ulist_induction.\n    {\n        rewrite ulist_image_end, ulist_sum_end.\n        apply mult_ranni.\n    }\n    rewrite ulist_image_add, ulist_sum_add; cbn.\n    rewrite ldist.\n    rewrite IHl'.\n    apply rplus.\n    clear IHl' l'.\n    rewrite scalar_rmult.\n    apply f_equal.\n    rewrite <- to_tensor_n_list.\n    unfold one; cbn.\n    rewrite to_tensor_n_mult.\n    apply f_equal.\n    apply set_type_eq; cbn.\n    apply mult_lid.\nQed.\n\nLocal Instance tensor_n_mult_rid : MultRid (module_V tensor_n_algebra_module).\nProof.\n    split.\n    intros a.\n    pose proof (tensor_n_sum a) as [l a_eq]; subst a.\n    induction l as [|[a l] l'] using ulist_induction.\n    {\n        rewrite ulist_image_end, ulist_sum_end.\n        apply mult_lanni.\n    }\n    rewrite ulist_image_add, ulist_sum_add; cbn.\n    rewrite rdist.\n    rewrite IHl'.\n    apply rplus.\n    clear IHl' l'.\n    rewrite scalar_lmult.\n    apply f_equal.\n    rewrite <- to_tensor_n_list.\n    unfold one; cbn.\n    rewrite to_tensor_n_mult.\n    pose proof (plus_rid (list_size l)) as eq.\n    rewrite (to_tensor_n_k_eq eq).\n    apply f_equal.\n    apply set_type_eq; cbn.\n    destruct eq; cbn.\n    apply mult_rid.\nQed.\n\nLocal Instance tensor_n_mult_assoc\n    : MultAssoc (module_V tensor_n_algebra_module).\nProof.\n    split.\n    intros a b c.\n    pose proof (tensor_n_sum a) as [l a_eq]; subst a.\n    induction l as [|[α a] l] using ulist_induction.\n    {\n        rewrite ulist_image_end, ulist_sum_end.\n        do 3 rewrite mult_lanni.\n        reflexivity.\n    }\n    rewrite ulist_image_add, ulist_sum_add; cbn.\n    change (grade_sum_type nat tensor_n_module) with (module_V (tensor_n_algebra_module)).\n    do 3 rewrite rdist.\n    rewrite IHl.\n    apply rplus.\n    clear l IHl.\n    do 3 rewrite scalar_lmult.\n    apply f_equal; clear α.\n    pose proof (tensor_n_sum b) as [l b_eq]; subst b.\n    induction l as [|[α b] l] using ulist_induction.\n    {\n        rewrite ulist_image_end, ulist_sum_end.\n        rewrite mult_lanni.\n        rewrite mult_ranni.\n        rewrite mult_lanni.\n        reflexivity.\n    }\n    rewrite ulist_image_add, ulist_sum_add; cbn.\n    change (grade_sum_type nat tensor_n_module) with (module_V (tensor_n_algebra_module)).\n    rewrite rdist.\n    do 2 rewrite ldist.\n    rewrite rdist.\n    rewrite IHl.\n    apply rplus.\n    clear l IHl.\n    rewrite scalar_lmult.\n    do 2 rewrite scalar_rmult.\n    rewrite scalar_lmult.\n    apply f_equal; clear α.\n    pose proof (tensor_n_sum c) as [l c_eq]; subst c.\n    induction l as [|[α c] l] using ulist_induction.\n    {\n        rewrite ulist_image_end, ulist_sum_end.\n        do 3 rewrite mult_ranni.\n        reflexivity.\n    }\n    rewrite ulist_image_add, ulist_sum_add; cbn.\n    change (grade_sum_type nat tensor_n_module) with (module_V (tensor_n_algebra_module)).\n    do 3 rewrite ldist.\n    rewrite IHl.\n    apply rplus.\n    clear l IHl.\n    do 3 rewrite scalar_rmult.\n    apply f_equal; clear α.\n    do 3 rewrite <- to_tensor_n_list.\n    do 4 rewrite to_tensor_n_mult.\n    pose proof (plus_assoc (list_size a) (list_size b) (list_size c)) as eq.\n    rewrite (to_tensor_n_k_eq eq).\n    apply f_equal.\n    apply set_type_eq; cbn.\n    destruct eq; cbn.\n    apply mult_assoc.\nQed.\n\nDefinition tensor_algebra_n := make_algebra\n    F\n    tensor_n_algebra_module\n    tensor_n_mult\n    tensor_n_mult_ldist\n    tensor_n_mult_rdist\n    tensor_n_mult_assoc\n    tensor_n_one\n    tensor_n_mult_lid\n    tensor_n_mult_rid\n    tensor_n_scalar_lmult\n    tensor_n_scalar_rmult\n.\n\nEnd TensorAlgebraGrade.\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/Linear/Tensor/Algebra/tensor_algebra_grade1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6640606428212171}}
{"text": "Require Import ZArith.\nRequire Import String.\n\nRequire Export fun_domains.\nRequire Export fun_domains_aux.\n\nSet Implicit Arguments.\n\nInductive kstep : kcfg -> kcfg -> Prop :=\n | k_cool_i : forall i e rest,\n     kcell_step kstep (kra (KInt i) (kra (KFreeze e) rest))\n                      (kra (cool_exp_kitem (ECon i) e) rest)\n | k_cool_b : forall b e rest,\n     kcell_step kstep (kra (KBool b) (kra (KFreeze e) rest))\n                      (kra (cool_exp_kitem (BCon b) e) rest)\n | k_heat_call : forall args v k f rest,\n       first_unevaluated_arg nil args = Some (v, k) ->\n       heat_step kstep (KExp (ECall f args)) v (KFreeze (KExp (ECall f k))) rest\n | k_heat_scall : forall args v k f rest,\n       first_unevaluated_arg nil args = Some (v, k) ->\n       heat_step kstep (KStmt (SCall f args)) v (KFreeze (KStmt (SCall f k))) rest\n | k_next_defn : forall Args Body F P WildVar1 WildVar2, krule kstep [k_cell (write (kra (KPgm (cons (FunDef F Args Body) P)) WildVar1) (kra (KPgm P) WildVar1)); fun_cell (write WildVar2 (kra (KId F) kdot |-> kra (KDefn (FunDef F Args Body)) kdot :* WildVar2))]\n | k_plus : forall I J WildVar1 x1, eq (ExpFromK x1) (Some (EPlus (ECon I) (ECon J))) -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (KInt (Zplus I J)) WildVar1))]\n | k_mult : forall I J WildVar1 x1, eq (ExpFromK x1) (Some (EMult (ECon I) (ECon J))) -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (KInt (Zmult I J)) WildVar1))]\n | k_minus : forall I J WildVar1 x1, eq (ExpFromK x1) (Some (EMinus (ECon I) (ECon J))) -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (KInt (Zminus I J)) WildVar1))]\n | k_neg : forall I WildVar1 x1, eq (ExpFromK x1) (Some (ENeg (ECon I))) -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (KInt (Zopp I)) WildVar1))]\n | k_div : forall I J WildVar1 x1, eq (ExpFromK x1) (Some (EDiv (ECon I) (ECon J))) -> eq (Zneq_bool 0 J) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (KInt (Zdiv I J)) WildVar1))]\n | k_le : forall I J WildVar1 x1, eq (ExpFromK x1) (Some (BLe (ECon I) (ECon J))) -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (KBool (Zle_bool I J)) WildVar1))]\n | k_lt : forall I J WildVar1 x1, eq (ExpFromK x1) (Some (BLt (ECon I) (ECon J))) -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (KBool (Zlt_bool I J)) WildVar1))]\n | k_eq : forall I J WildVar1 x1, eq (ExpFromK x1) (Some (BEq (ECon I) (ECon J))) -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (KBool (Z.eqb I J)) WildVar1))]\n | k_not : forall B WildVar1 x1, eq (ExpFromK x1) (Some (BNot (BCon B))) -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (KBool (negb B)) WildVar1))]\n | k_and_t : forall B WildVar1 x1, eq (ExpFromK x1) (Some (BAnd (BCon true) B)) -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK B) WildVar1))]\n | k_and_f : forall WildVar1 WildVar2 x1, eq (ExpFromK x1) (Some (BAnd (BCon false) WildVar1)) -> krule kstep [k_cell (write (kra x1 WildVar2) (kra (KBool false) WildVar2))]\n | k_or_t : forall WildVar1 WildVar2 x1, eq (ExpFromK x1) (Some (BOr (BCon true) WildVar1)) -> krule kstep [k_cell (write (kra x1 WildVar2) (kra (KBool true) WildVar2))]\n | k_or_f : forall B WildVar1 x1, eq (ExpFromK x1) (Some (BOr (BCon false) B)) -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK B) WildVar1))]\n | k_skip : forall WildVar1, krule kstep [k_cell (write (kra (KStmt Skip) WildVar1) WildVar1)]\n | k_if_t : forall S WildVar1 WildVar2, krule kstep [k_cell (write (kra (KStmt (SIf (BCon true) S WildVar1)) WildVar2) (kra (KStmt S) WildVar2))]\n | k_if_f : forall S WildVar1 WildVar2, krule kstep [k_cell (write (kra (KStmt (SIf (BCon false) WildVar1 S)) WildVar2) (kra (KStmt S) WildVar2))]\n | k_while : forall B S WildVar1, krule kstep [k_cell (write (kra (KStmt (SWhile B S)) WildVar1) (kra (KStmt (SIf B (Seq S (SWhile B S)) Skip)) WildVar1))]\n | k_lookup : forall I V WildVar1 WildVar2 x1 x2, MapEquiv x1 (kra (KId I) kdot |-> kra x2 kdot :* WildVar1) -> eq (KResultFromK x2) (Some V) -> krule kstep [k_cell (write (kra (KId I) WildVar2) (kra (KResultToK V) WildVar2)); env_cell (write x1 (kra (KId I) kdot |-> kra (KResultToK V) kdot :* WildVar1))]\n | k_load : forall Addr V WildVar1 WildVar2 x1 x2 x3, eq (ExpFromK x1) (Some (ELoad (ECon Addr))) -> MapEquiv x2 (kra (KInt Addr) kdot |-> kra x3 kdot :* WildVar2) -> eq (KResultFromK x3) (Some V) -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (KResultToK V) WildVar1)); heap_cell (write x2 (kra (KInt Addr) kdot |-> kra (KResultToK V) kdot :* WildVar2))]\n | k_assign : forall V WildVar1 WildVar2 WildVar3 X x1 x2, eq (KResultFromExp x1) (Some V) -> MapEquiv x2 (kra (KId X) kdot |-> WildVar1 :* WildVar3) -> krule kstep [k_cell (write (kra (KStmt (SAssign X x1)) WildVar2) WildVar2); env_cell (write x2 (kra (KId X) kdot |-> kra (KResultToK V) kdot :* WildVar3))]\n | k_hassign : forall Addr V WildVar1 WildVar2 WildVar3 x1 x2, eq (KResultFromExp x1) (Some V) -> MapEquiv x2 (kra (KInt Addr) kdot |-> WildVar1 :* WildVar3) -> krule kstep [k_cell (write (kra (KStmt (HAssign (ECon Addr) x1)) WildVar2) WildVar2); heap_cell (write x2 (kra (KInt Addr) kdot |-> kra (KResultToK V) kdot :* WildVar3))]\n | k_decl : forall WildVar1 WildVar2 X, krule kstep [k_cell (write (kra (KStmt (Decl X)) WildVar1) WildVar1); env_cell (write WildVar2 (kra (KId X) kdot |-> kra (KUndef undef) kdot :* WildVar2))]\n | k_call : forall Args Body Env F Formals Rest Stk WildVar1 x1 x2, eq (ExpFromK x1) (Some (ECall F Args)) -> MapEquiv x2 (kra (KId F) kdot |-> kra (KDefn (FunDef F Formals Body)) kdot :* WildVar1) -> eq (all_values Args) true -> krule kstep [k_cell (write (kra x1 Rest) (kra (KStmt Body) kdot)); fun_cell (write x2 (kra (KId F) kdot |-> kra (KDefn (FunDef F Formals Body)) kdot :* WildVar1)); env_cell (write Env (mkMap Formals Args)); stk_cell (write Stk (cons (frame Rest Env) Stk))]\n | k_scall : forall Args Body Env F Formals Rest Stk WildVar1 x1, MapEquiv x1 (kra (KId F) kdot |-> kra (KDefn (FunDef F Formals Body)) kdot :* WildVar1) -> eq (all_values Args) true -> krule kstep [k_cell (write (kra (KStmt (SCall F Args)) Rest) (kra (KStmt Body) kdot)); fun_cell (write x1 (kra (KId F) kdot |-> kra (KDefn (FunDef F Formals Body)) kdot :* WildVar1)); env_cell (write Env (mkMap Formals Args)); stk_cell (write Stk (cons (frame Rest Env) Stk))]\n | k_return : forall Env Rest Stk V WildVar1 WildVar2 x1, eq (KResultFromExp x1) (Some V) -> krule kstep [k_cell (write (kra (KStmt (SReturn x1)) WildVar1) (kra (KResultToK V) Rest)); env_cell (write WildVar2 Env); stk_cell (write (cons (frame Rest Env) Stk) Stk)]\n | k_returnv : forall Env Rest Stk WildVar1 WildVar2, krule kstep [k_cell (write (kra (KStmt SReturnVoid) WildVar1) Rest); env_cell (write WildVar2 Env); stk_cell (write (cons (frame Rest Env) Stk) Stk)]\n | k_heat_load : forall E WildVar1 x1, eq (ExpFromK x1) (Some (ELoad E)) -> eq (notKResult (kra (ExpToK E) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK E) (kra (KFreeze (ExpToK (ELoad HOLE_Exp))) WildVar1)))]\n | k_heat_plus_l : forall WildVar1 X Y x1, eq (ExpFromK x1) (Some (EPlus X Y)) -> eq (notKResult (kra (ExpToK X) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK X) (kra (KFreeze (ExpToK (EPlus HOLE_Exp Y))) WildVar1)))]\n | k_heat_plus_r : forall WildVar1 X Y x1, eq (ExpFromK x1) (Some (EPlus X Y)) -> eq (notKResult (kra (ExpToK Y) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK Y) (kra (KFreeze (ExpToK (EPlus X HOLE_Exp))) WildVar1)))]\n | k_heat_minus_l : forall WildVar1 X Y x1, eq (ExpFromK x1) (Some (EMinus X Y)) -> eq (notKResult (kra (ExpToK X) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK X) (kra (KFreeze (ExpToK (EMinus HOLE_Exp Y))) WildVar1)))]\n | k_heat_minus_r : forall WildVar1 X Y x1, eq (ExpFromK x1) (Some (EMinus X Y)) -> eq (notKResult (kra (ExpToK Y) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK Y) (kra (KFreeze (ExpToK (EMinus X HOLE_Exp))) WildVar1)))]\n | k_heat_neg : forall WildVar1 X x1, eq (ExpFromK x1) (Some (ENeg X)) -> eq (notKResult (kra (ExpToK X) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK X) (kra (KFreeze (ExpToK (ENeg HOLE_Exp))) WildVar1)))]\n | k_heat_mult_l : forall WildVar1 X Y x1, eq (ExpFromK x1) (Some (EMult X Y)) -> eq (notKResult (kra (ExpToK X) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK X) (kra (KFreeze (ExpToK (EMult HOLE_Exp Y))) WildVar1)))]\n | k_heat_mult_r : forall WildVar1 X Y x1, eq (ExpFromK x1) (Some (EMult X Y)) -> eq (notKResult (kra (ExpToK Y) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK Y) (kra (KFreeze (ExpToK (EMult X HOLE_Exp))) WildVar1)))]\n | k_heat_div_l : forall WildVar1 X Y x1, eq (ExpFromK x1) (Some (EDiv X Y)) -> eq (notKResult (kra (ExpToK X) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK X) (kra (KFreeze (ExpToK (EDiv HOLE_Exp Y))) WildVar1)))]\n | k_heat_div_r : forall WildVar1 X Y x1, eq (ExpFromK x1) (Some (EDiv X Y)) -> eq (notKResult (kra (ExpToK Y) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK Y) (kra (KFreeze (ExpToK (EDiv X HOLE_Exp))) WildVar1)))]\n | k_heat_le_l : forall WildVar1 X Y x1, eq (ExpFromK x1) (Some (BLe X Y)) -> eq (notKResult (kra (ExpToK X) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK X) (kra (KFreeze (ExpToK (BLe HOLE_Exp Y))) WildVar1)))]\n | k_heat_le_r : forall WildVar1 X Y x1, eq (ExpFromK x1) (Some (BLe X Y)) -> eq (notKResult (kra (ExpToK Y) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK Y) (kra (KFreeze (ExpToK (BLe X HOLE_Exp))) WildVar1)))]\n | k_heat_lt_l : forall WildVar1 X Y x1, eq (ExpFromK x1) (Some (BLt X Y)) -> eq (notKResult (kra (ExpToK X) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK X) (kra (KFreeze (ExpToK (BLt HOLE_Exp Y))) WildVar1)))]\n | k_heat_lt_r : forall WildVar1 X Y x1, eq (ExpFromK x1) (Some (BLt X Y)) -> eq (notKResult (kra (ExpToK Y) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK Y) (kra (KFreeze (ExpToK (BLt X HOLE_Exp))) WildVar1)))]\n | k_heat_eq_l : forall WildVar1 X Y x1, eq (ExpFromK x1) (Some (BEq X Y)) -> eq (notKResult (kra (ExpToK X) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK X) (kra (KFreeze (ExpToK (BEq HOLE_Exp Y))) WildVar1)))]\n | k_heat_eq_r : forall WildVar1 X Y x1, eq (ExpFromK x1) (Some (BEq X Y)) -> eq (notKResult (kra (ExpToK Y) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK Y) (kra (KFreeze (ExpToK (BEq X HOLE_Exp))) WildVar1)))]\n | k_heat_not : forall B WildVar1 x1, eq (ExpFromK x1) (Some (BNot B)) -> eq (notKResult (kra (ExpToK B) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK B) (kra (KFreeze (ExpToK (BNot HOLE_Exp))) WildVar1)))]\n | k_heat_and : forall B C WildVar1 x1, eq (ExpFromK x1) (Some (BAnd B C)) -> eq (notKResult (kra (ExpToK B) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK B) (kra (KFreeze (ExpToK (BAnd HOLE_Exp C))) WildVar1)))]\n | k_heat_or : forall B C WildVar1 x1, eq (ExpFromK x1) (Some (BOr B C)) -> eq (notKResult (kra (ExpToK B) kdot)) true -> krule kstep [k_cell (write (kra x1 WildVar1) (kra (ExpToK B) (kra (KFreeze (ExpToK (BOr HOLE_Exp C))) WildVar1)))]\n | k_heat_assign : forall E V WildVar1, eq (notKResult (kra (ExpToK E) kdot)) true -> krule kstep [k_cell (write (kra (KStmt (SAssign V E)) WildVar1) (kra (ExpToK E) (kra (KFreeze (KStmt (SAssign V HOLE_Exp))) WildVar1)))]\n | k_heat_hassign_l : forall E1 E2 WildVar1, eq (notKResult (kra (ExpToK E1) kdot)) true -> krule kstep [k_cell (write (kra (KStmt (HAssign E1 E2)) WildVar1) (kra (ExpToK E1) (kra (KFreeze (KStmt (HAssign HOLE_Exp E2))) WildVar1)))]\n | k_heat_hassign_r : forall E1 E2 WildVar1, eq (notKResult (kra (ExpToK E2) kdot)) true -> krule kstep [k_cell (write (kra (KStmt (HAssign E1 E2)) WildVar1) (kra (ExpToK E2) (kra (KFreeze (KStmt (HAssign E1 HOLE_Exp))) WildVar1)))]\n | k_heat_if : forall B S1 S2 WildVar1, eq (notKResult (kra (ExpToK B) kdot)) true -> krule kstep [k_cell (write (kra (KStmt (SIf B S1 S2)) WildVar1) (kra (ExpToK B) (kra (KFreeze (KStmt (SIf HOLE_Exp S1 S2))) WildVar1)))]\n | k_heat_return : forall E WildVar1, eq (notKResult (kra (ExpToK E) kdot)) true -> krule kstep [k_cell (write (kra (KStmt (SReturn E)) WildVar1) (kra (ExpToK E) (kra (KFreeze (KStmt (SReturn HOLE_Exp))) WildVar1)))]\n | k_heat_seq : forall S1 S2 WildVar1, krule kstep [k_cell (write (kra (KStmt (Seq S1 S2)) WildVar1) (kra (KStmt S1) (kra (KStmt S2) WildVar1)))]\n.\n", "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/bytewise/fun_steps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6640606406967222}}
{"text": "(* Copyright 2012-2015 by Adam Petcher.\t\t\t\t*\n * Use of this source code is governed by the license described\t*\n * in the LICENSE file at the root of the source tree.\t\t*)\n\n(* Diffie-Hellman definitions. *)\n\nSet Implicit Arguments.\n\nRequire Import FCF.FCF.\nRequire Import FCF.RndNat.\nRequire Export FCF.GroupTheory.\n\nLocal Open Scope group_scope.\n\nSection DDH.\n\n  Section DDH_Concrete.\n\n    Context`{FCG : FiniteCyclicGroup}.\n    Variable A : (GroupElement * GroupElement * GroupElement) -> Comp bool. \n\n    Definition DDH0 :=\n      x <-$ [0 .. order);\n      y <-$ [0 .. order);\n      b <-$ (A (g^x, g^y, g^(x * y)));\n      ret b.\n    \n    Definition DDH1  :=\n      x <-$ [0 .. order);\n      y <-$ [0 .. order);\n      z <-$ [0 .. order);\n      b <-$ (A (g^x, g^y, g^z));\n      ret b.\n\n    Definition DDH_Advantage:= | Pr[DDH0] - Pr[DDH1] |.\n\n  End DDH_Concrete. \n  \n\nEnd DDH.\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/DiffieHellman.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6640606307353016}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Lia. \nOpen Scope Z_scope.\n\nLemma coin_3_5 : forall n : Z, n >= 8 -> exists (x y : Z), 3 * x + 5 * y = n.\nProof. \n  destruct n; try lia.\n  induction p; intros.\n  repeat rewrite Pos2Z.inj_xI in *.\n  assert (Ht2 : Z.pos p = 4 \\/ Z.pos p = 5 \\/\n                Z.pos p = 6 \\/ Z.pos p = 7 \\/\n                Z.pos p >= 8) by lia.\n  destruct Ht2 as [Ht2 | [Ht2 | [Ht2 | [Ht2 | Ht2]]]].\n  rewrite Ht2. exists (-2), 3. lia. \n  rewrite Ht2. exists (-3), 4. lia.\n  rewrite Ht2. exists (-4), 5. lia.\n  rewrite Ht2. exists (-5), 6. lia.\n  apply IHp in Ht2.\n  destruct Ht2 as [x [y Ht]].\n  exists (2 * x - 3), (2 * y + 2). lia.\n\n\n  rewrite Pos2Z.pos_xO in *.\n  assert (Ht2 : Z.pos p = 4 \\/ Z.pos p = 5 \\/\n                Z.pos p = 6 \\/ Z.pos p = 7 \\/\n                Z.pos p >= 8) by lia.\n  destruct Ht2 as [Ht2 | [Ht2 | [Ht2 | [Ht2 | Ht2]]]].\n  rewrite Ht2. exists 1, 1. lia. \n  rewrite Ht2. exists 0, 2. lia.\n  rewrite Ht2. exists 4, 0. lia.\n  rewrite Ht2. exists 3, 1. lia. \n  apply IHp in Ht2.\n  destruct Ht2 as [x [y Ht]].\n  exists (2 * x), (2 * y). lia.\n\n  (* impossible case *)\n  lia.\nQed.\n\n", "meta": {"author": "mukeshtiwari", "repo": "DataStrucutre", "sha": "89a4916114d3681e67f963f5166468c0b1ff2276", "save_path": "github-repos/coq/mukeshtiwari-DataStrucutre", "path": "github-repos/coq/mukeshtiwari-DataStrucutre/DataStrucutre-89a4916114d3681e67f963f5166468c0b1ff2276/Coin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6640606252903334}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_s_conga :\n\tforall A B C a b c U V u v,\n\tOnRay B A U ->\n\tOnRay B C V ->\n\tOnRay b a u ->\n\tOnRay b c v ->\n\tCong B U b u ->\n\tCong B V b v ->\n\tCong U V u v ->\n\tnCol A B C ->\n\tCongA A B C a b c.\nProof.\n\tintros A B C a b c U V u v.\n\tintros OnRay_BA_U.\n\tintros OnRay_BC_V.\n\tintros OnRay_ba_u.\n\tintros OnRay_bc_v.\n\tintros Cong_BU_bu.\n\tintros Cong_BV_bv.\n\tintros Cong_UV_uv.\n\tintros nCol_A_B_C.\n\n\tunfold CongA.\n\texists U, V, u, v.\n\tsplit.\n\texact OnRay_BA_U.\n\tsplit.\n\texact OnRay_BC_V.\n\tsplit.\n\texact OnRay_ba_u.\n\tsplit.\n\texact OnRay_bc_v.\n\tsplit.\n\texact Cong_BU_bu.\n\tsplit.\n\texact Cong_BV_bv.\n\tsplit.\n\texact Cong_UV_uv.\n\texact nCol_A_B_C.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_s_conga.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6640174332229758}}
{"text": "(** The following axiom systems are used to formalize\n    Euclid's proofs of Euclid's Elements.OriginalProofs.statements. *)\n\n\n(** First, we define an axiom system for neutral geometry,\n    i.e. geometry without continuity axioms nor parallel postulate.\n *)\n\nVariable Point: Type.\nVariable Circle: Type.\nVariable Cong : Point -> Point -> Point -> Point -> Prop.\nVariable  BetS : Point -> Point -> Point -> Prop.\nVariable  PA : Point.\nVariable  PB : Point.\nVariable  PC : Point.\nVariable  CI : Circle -> Point -> Point -> Point -> Prop.\nDefinition eq := @eq Point.\nDefinition neq A B := ~ eq A B.\nDefinition  TE A B C := ~ (neq A B /\\ neq B C /\\ ~ BetS A B C).\nDefinition  nCol A B C := neq A B /\\ neq A C /\\ neq B C /\\ ~ BetS A B C /\\ ~ BetS A C B /\\ ~ BetS B A C.\nDefinition  Col A B C := (eq A B \\/ eq A C \\/ eq B C \\/ BetS B A C \\/ BetS A B C \\/ BetS A C B).\nDefinition  Cong_3 A B C a b c := Cong A B a b /\\ Cong B C b c /\\ Cong A C a c.\nDefinition  TS P A B Q := exists X, BetS P X Q /\\ Col A B X /\\ nCol A B P.\nDefinition  Triangle A B C := nCol A B C.\n\nDefinition  OnCirc B J := exists X Y U, CI J U X Y /\\ Cong U B X Y.\nDefinition  InCirc P J := exists X Y U V W, CI J U V W /\\ (eq P U \\/ (BetS U Y X /\\ Cong U X V W /\\ Cong U P U Y)).\nDefinition  OutCirc P J := exists X U V W, CI J U V W /\\ BetS U X P /\\ Cong U X V W.\n\nAxiom  cn_congruencetransitive :\n   forall B C D E P Q, Cong P Q B C -> Cong P Q D E -> Cong B C D E.\nAxiom  cn_congruencereflexive :\n   forall A B, Cong A B A B.\nAxiom  cn_equalityreverse :\n   forall A B, Cong A B B A.\nAxiom  cn_sumofparts :\n   forall A B C a b c, Cong A B a b -> Cong B C b c -> BetS A B C -> BetS a b c -> Cong A C a c.\nAxiom  cn_stability :\n   forall A B, ~ neq A B -> eq A B.\nAxiom  axiom_circle_center_radius :\n   forall A B C J P, CI J A B C -> OnCirc P J -> Cong A P B C.\nAxiom  axiom_lower_dim : nCol PA PB PC.\nAxiom  axiom_betweennessidentity :\n   forall A B, ~ BetS A B A.\nAxiom  axiom_betweennesssymmetry :\n   forall A B C, BetS A B C -> BetS C B A.\nAxiom  axiom_innertransitivity :\n   forall A B C D,\n    BetS A B D -> BetS B C D -> BetS A B C.\nAxiom  axiom_connectivity :\n   forall A B C D,\n    BetS A B D -> BetS A C D -> ~ BetS A B C -> ~ BetS A C B ->\n    eq B C.\nAxiom  axiom_nocollapse :\n   forall A B C D, neq A B -> Cong A B C D -> neq C D.\nAxiom  axiom_5_line :\n   forall A B C D a b c d,\n    Cong B C b c -> Cong A D a d -> Cong B D b d ->\n    BetS A B C -> BetS a b c -> Cong A B a b ->\n    Cong D C d c.\n\nAxiom   postulate_Pasch_inner :\n   forall A B C P Q,\n    BetS A P C -> BetS B Q C -> nCol A C B ->\n    exists X, BetS A X Q /\\ BetS B X P.\nAxiom   postulate_Pasch_outer :\n   forall A B C P Q,\n    BetS A P C -> BetS B C Q -> nCol B Q A ->\n    exists X, BetS A X Q /\\ BetS B P X.\nAxiom   postulate_Euclid2 : forall A B, neq A B -> exists X, BetS A B X.\nAxiom   postulate_Euclid3 : forall A B, neq A B -> exists X, CI X A A B.\n\n(** Second, we enrich the axiom system with line-circle\n     and circle-circle continuity axioms.\n    Those two axioms state that we allow ruler and compass\n    constructions.\n*)\n\nAxiom   postulate_line_circle :\n   forall A B C K P Q,\n    CI K C P Q -> InCirc B K -> neq A B ->\n    exists X Y, Col A B X /\\ BetS A B Y /\\ OnCirc X K /\\ OnCirc Y K /\\ BetS X B Y.\nAxiom   postulate_circle_circle :\n   forall C D F G J K P Q R S,\n    CI J C R S -> InCirc P J ->\n    OutCirc Q J -> CI K D F G ->\n    OnCirc P K -> OnCirc Q K ->\n    exists X, OnCirc X J /\\ OnCirc X K.\n\n(** Third, we introduce the famous fifth postulate of Euclid,\n    which ensures that the geometry is\n    Euclidean (i.e. not hyperbolic).\n *)\n\nAxiom   postulate_Euclid5 :\n   forall a p q r s t,\n    BetS r t s -> BetS p t q -> BetS r a q ->\n    Cong p t q t -> Cong t r t s -> nCol p q s ->\n    exists X, BetS p a X /\\ BetS s q X.\n\n(** Last, we enrich the axiom system with axioms for equality of areas. *)\n\nVariable  EF : Point -> Point -> Point -> Point -> Point -> Point -> Point -> Point -> Prop.\nVariable  ET : Point -> Point -> Point -> Point -> Point -> Point -> Prop.\nAxiom   axiom_congruentequal :\n   forall A B C a b c, Cong_3 A B C a b c -> ET A B C a b c.\nAxiom   axiom_ETpermutation :\n   forall A B C a b c,\n    ET A B C a b c ->\n    ET A B C b c a /\\\n    ET A B C a c b /\\\n    ET A B C b a c /\\\n    ET A B C c b a /\\\n    ET A B C c a b.\nAxiom   axiom_ETsymmetric :\n   forall A B C a b c, ET A B C a b c -> ET a b c A B C.\nAxiom   axiom_EFpermutation :\n   forall A B C D a b c d,\n   EF A B C D a b c d ->\n     EF A B C D b c d a /\\\n     EF A B C D d c b a /\\\n     EF A B C D c d a b /\\\n     EF A B C D b a d c /\\\n     EF A B C D d a b c /\\\n     EF A B C D c b a d /\\\n     EF A B C D a d c b.\nAxiom   axiom_halvesofequals :\n   forall A B C D a b c d, ET A B C B C D ->\n                           TS A B C D -> ET a b c b c d ->\n                           TS a b c d -> EF A B D C a b d c -> ET A B C a b c.\nAxiom   axiom_EFsymmetric :\n   forall A B C D a b c d, EF A B C D a b c d ->\n                           EF a b c d A B C D.\nAxiom   axiom_EFtransitive :\n   forall A B C D P Q R S a b c d,\n     EF A B C D a b c d -> EF a b c d P Q R S ->\n     EF A B C D P Q R S.\nAxiom   axiom_ETtransitive :\n   forall A B C P Q R a b c,\n    ET A B C a b c -> ET a b c P Q R -> ET A B C P Q R.\nAxiom   axiom_cutoff1 :\n   forall A B C D E a b c d e,\n    BetS A B C -> BetS a b c -> BetS E D C -> BetS e d c ->\n    ET B C D b c d -> ET A C E a c e ->\n    EF A B D E a b d e.\nAxiom   axiom_cutoff2 :\n   forall A B C D E a b c d e,\n    BetS B C D -> BetS b c d -> ET C D E c d e -> EF A B D E a b d e ->\n    EF A B C E a b c e.\nAxiom   axiom_paste1 :\n   forall A B C D E a b c d e,\n    BetS A B C -> BetS a b c -> BetS E D C -> BetS e d c ->\n    ET B C D b c d -> EF A B D E a b d e ->\n    ET A C E a c e.\nAxiom   axiom_deZolt1 :\n   forall B C D E, BetS B E D -> ~ ET D B C E B C.\nAxiom   axiom_deZolt2 :\n   forall A B C E F,\n    Triangle A B C -> BetS B E A -> BetS B F C ->\n  ~ ET A B C E B F.\nAxiom   axiom_paste2 :\n   forall A B C D E M a b c d e m,\n    BetS B C D -> BetS b c d -> ET C D E c d e ->\n    EF A B C E a b c e ->\n    BetS A M D -> BetS B M E ->\n    BetS a m d -> BetS b m e ->\n    EF A B D E a b d e.\nAxiom   axiom_paste3 :\n   forall A B C D M a b c d m,\n    ET A B C a b c -> ET A B D a b d ->\n    BetS C M D ->\n    (BetS A M B \\/ eq A M \\/ eq M B) ->\n    BetS c m d ->\n    (BetS a m b \\/ eq a m \\/ eq m b) ->\n    EF A C B D a c b d.\nAxiom   axiom_paste4 :\n   forall A B C D F G H J K L M P e m,\n    EF A B m D F K H G -> EF D B e C G H M L ->\n    BetS A P C -> BetS B P D -> BetS K H M -> BetS F G L ->\n    BetS B m D -> BetS B e C -> BetS F J M -> BetS K J L ->\n    EF A B C D F K M L.", "meta": {"author": "Karnaj", "repo": "DCE", "sha": "b50cb7c70af316f704745dac428be0324d836193", "save_path": "github-repos/coq/Karnaj-DCE", "path": "github-repos/coq/Karnaj-DCE/DCE-b50cb7c70af316f704745dac428be0324d836193/tests/src/simpl_euclidean_axioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6640174313566235}}
{"text": "Require Import Rbase Ranalysis.\nRequire Import Rinterval Rfunctions Rfunction_def.\nRequire Import Ranalysis_def Rfunction_facts.\nRequire Import MyRIneq MyR_dist Lra.\n\nRequire Import Ass_handling.\n\nLocal Open Scope R_scope.\n\n(** * Example of dense domains *)\n\n(* TODO: move this 3 lemmas *)\n\nLemma middle_r_in_Rball : forall c r, 0 < r -> Rball c r (middle c (c + r)).\nProof.\nintros c r r_pos ; apply included_open_interval_Rball2 ; split.\n transitivity c.\n  lra.\n  apply middle_is_in_the_middle ; lra.\n apply middle_is_in_the_middle ; lra.\nQed.\n\nLemma middle_l_in_Rball : forall c r, 0 < r -> Rball c r (middle (c - r) c).\nProof.\nintros c r r_pos ; apply included_open_interval_Rball2 ; split.\n apply middle_is_in_the_middle ; lra.\n transitivity c.\n  apply middle_is_in_the_middle ; lra.\n  lra.\nQed.\n\nLemma Rlt_div_2 : forall x, 0 < x -> x / 2 < x.\nProof.\nintros ; lra.\nQed.\n\nLemma dense_interval: forall lb ub x, lb < ub ->\n  interval lb ub x -> dense (interval lb ub) x.\nProof.\nintros lb ub x Hlt [xlb xub] eps eps_pos ; destruct xlb as [xlb | xeq].\n destruct xub as [xub | xeq].\n  pose (h := Rmin (eps / 2) (interval_dist lb ub x)) ;\n  assert (h_pos : 0 < h).\n   apply Rmin_pos_lt, open_interval_dist_pos ;\n   [lra | split ; assumption].\n  exists (x + h) ; split.\n   split.\n    apply interval_dist_bound ; [split ; left ; assumption |].\n    rewrite Rabs_right ; [apply Rmin_r | left ; assumption].\n    apply Rplus_pos_neq ; assumption.\n   rewrite R_dist_Rplus_compat, Rabs_right ; [| left ; assumption].\n    apply Rle_lt_trans with (eps / 2) ; [apply Rmin_l | lra].\n  pose (h := Rmin (eps / 2) (ub - lb)) ;\n  assert (h_pos : 0 < h) by (apply Rmin_pos_lt ; lra).\n   exists (x - h) ; split. split. split.\n    transitivity (x - (ub - lb)).\n     right ; subst ; ring.\n     apply Rplus_le_compat_l, Ropp_le_contravar, Rmin_r.\n     left ; subst ; apply Rminus_pos_lt ; assumption.\n     subst ; apply Rgt_not_eq, Rminus_pos_lt ; assumption.\n     rewrite R_dist_Rminus_compat, Rabs_right ; [| left ; assumption].\n     apply Rle_lt_trans with (eps / 2) ; [apply Rmin_l | lra].\n  pose (h := Rmin (eps / 2) (ub - lb)) ;\n  assert (h_pos : 0 < h) by (apply Rmin_pos_lt ; lra).\n   exists (x + h) ; split. split. split.\n    left ; rewrite xeq ; apply Rplus_pos_lt ; assumption.\n    transitivity (x + (ub - lb)) ; [| right ; rewrite xeq ; ring].\n     apply Rplus_le_compat_l, Rmin_r.\n     apply Rlt_not_eq, Rplus_pos_lt ; assumption.\n     rewrite R_dist_Rplus_compat, Rabs_right ; [| left ; assumption].\n     apply Rle_lt_trans with (eps / 2) ; [apply Rmin_l | lra].\nQed.\n\nLemma dense_open_interval: forall lb ub x, lb < ub ->\n  interval lb ub x -> dense (open_interval lb ub) x.\nProof.\nintros lb ub x Hlt [xlb xub] eps eps_pos ; assert (lbub : 0 < ub - lb) by lra.\ndestruct xlb as [xlb | xeq].\n destruct xub as [xub | xeq].\n  assert (d_pos : 0 < interval_dist lb ub x / 2).\n   apply Rlt_mult_inv_pos ; [apply open_interval_dist_pos | lra].\n   split ; assumption.\n  pose (h := Rmin (eps / 2) (interval_dist lb ub x / 2)) ;\n  assert (h_pos : 0 < h) by (apply Rmin_pos_lt ; lra).\n  exists (x + h) ; split.\n   split.\n    apply open_interval_dist_bound ; [split ; left ; assumption |].\n    apply Rle_lt_trans with (interval_dist lb ub x / 2).\n    rewrite Rabs_right ; [apply Rmin_r | left ; assumption].\n    lra.\n    apply Rplus_pos_neq ; assumption.\n   rewrite R_dist_Rplus_compat, Rabs_right ; [| left ; assumption].\n    apply Rle_lt_trans with (eps / 2) ; [apply Rmin_l | lra].\n  pose (h := Rmin (eps / 2) ((ub - lb) / 2)) ;\n  assert (h_pos : 0 < h) by (apply Rmin_pos_lt ; [| apply Rlt_mult_inv_pos] ; lra).\n   exists (x - h) ; repeat split.\n    apply Rle_lt_trans with (x - (ub - lb)).\n     right ; subst ; ring.\n     apply Rplus_lt_compat_l, Ropp_lt_contravar.\n     apply Rle_lt_trans with ((ub - lb) / 2) ; [apply Rmin_r | apply Rlt_div_2 ; assumption].\n     subst ; apply Rminus_pos_lt ; assumption.\n     subst ; apply Rgt_not_eq, Rminus_pos_lt ; assumption.\n     rewrite R_dist_Rminus_compat, Rabs_right ; [| left ; assumption].\n     apply Rle_lt_trans with (eps / 2) ; [apply Rmin_l | lra].\n  pose (h := Rmin (eps / 2) ((ub - lb)/2)) ;\n  assert (h_pos : 0 < h) by (apply Rmin_pos_lt ; [| apply Rlt_mult_inv_pos] ; lra).\n   exists (x + h) ; repeat split.\n    rewrite xeq ; apply Rplus_pos_lt ; assumption.\n    apply Rlt_le_trans with (x + (ub - lb)) ; [| right ; rewrite xeq ; ring].\n     apply Rplus_lt_compat_l, Rle_lt_trans with ((ub - lb)/2) ; [apply Rmin_r |].\n     apply Rlt_div_2 ; assumption.\n     apply Rlt_not_eq, Rplus_pos_lt ; assumption.\n     rewrite R_dist_Rplus_compat, Rabs_right ; [| left ; assumption].\n     apply Rle_lt_trans with (eps / 2) ; [apply Rmin_l | lra].\nQed.\n\nLemma dense_Rball : forall c r x, Rball c r x -> dense (Rball c r) x.\nProof.\nintros c r x x_in eps eps_pos ;\n assert (r_pos : 0 < r) by (eapply Rball_radius_pos ; eassumption) ;\n assert (Hlbub : c - r < c + r) by lra ;\n assert (x_in' : interval (c - r) (c + r) x).\n  apply open_interval_interval, included_Rball_open_interval ; assumption.\n destruct (dense_open_interval (c - r) (c + r) x Hlbub x_in' eps eps_pos) as [y [[y_in y_neq] Hy]] ;\n exists y ; repeat split ; [apply included_open_interval_Rball2 | |] ; assumption.\nQed.\n\n(** * Extensionality of growth_rate *)\n\nLemma growth_rate_ext: forall f g x, f == g ->\n  growth_rate f x == growth_rate g x.\nProof.\nintros f g x Heq y ; unfold growth_rate ;\n do 2 rewrite Heq ; reflexivity.\nQed.\n\nLemma growth_rate_ext_strong: forall (D : R -> Prop) f g x, D x ->\n  (forall x, D x -> f x = g x) ->\n  forall y, D y -> growth_rate f x y = growth_rate g x y.\nProof.\nintros D f g x Dx Heq y y_in ; unfold growth_rate ;\n do 2 (rewrite Heq ; [| assumption]) ; reflexivity.  \nQed.\n\n(** * growth_rate is compatible with common operations. *)\n\nLemma growth_rate_mult_real_fct_compat: forall f (l:R) x y, D_x no_cond x y ->\n  growth_rate (mult_real_fct l f)%F x y = l * growth_rate f x y.\nProof.\nintros f l x y Dxy ; unfold growth_rate, mult_real_fct ; field ;\n apply Rminus_eq_contra ; symmetry ; apply Dxy.\nQed.\n\nLemma growth_rate_scal_compat: forall f (l:R) x y, D_x no_cond x y ->\n  growth_rate ((fun _ => l) * f)%F x y = l * growth_rate f x y.\nProof.\nintros f l x y Dxy ; unfold growth_rate, mult_fct ; field ;\n apply Rminus_eq_contra ; symmetry ; apply Dxy.\nQed.\n\nLemma growth_rate_opp_compat: forall f x y, D_x no_cond x y ->\n  growth_rate (- f)%F x y = - growth_rate f x y.\nProof.\nintros f x y Dxy ; unfold growth_rate, opp_fct ; field ;\n apply Rminus_eq_contra ; symmetry ; apply Dxy.\nQed.\n\nLemma growth_rate_plus_compat: forall f g x y, D_x no_cond x y ->\n  growth_rate (f + g)%F x y = growth_rate f x y + growth_rate g x y.\nProof.\nintros f g x y Dxy ; unfold growth_rate, plus_fct ; field ;\n apply Rminus_eq_contra ; symmetry ; apply Dxy.\nQed.\n\nLemma growth_rate_minus_compat: forall f g x y, D_x no_cond x y ->\n  growth_rate (f - g)%F x y = growth_rate f x y - growth_rate g x y.\nProof.\nintros f g x y Dxy ; unfold growth_rate, minus_fct ; field ;\n apply Rminus_eq_contra ; symmetry ; apply Dxy.\nQed.\n\nLemma growth_rate_mult_decomp: forall f g x y, x <> y ->\n  growth_rate (f * g)%F x y =\n (growth_rate f x y) * g x + f y * growth_rate g x y.\nProof.\nintros f g x y Hneq ; unfold growth_rate, mult_fct ; field ;\n apply Rminus_eq_contra ; symmetry ; assumption.\nQed.\n\nLemma growth_rate_inv_decomp: forall f x y,\n  x <> y -> f x <> 0 -> f y <> 0 ->\n  growth_rate (/ f)%F x y =\n  - ((growth_rate f x y) * / (f x * f y)).\nProof.\nintros ; unfold growth_rate, inv_fct ; field ;\n repeat split ; [| | apply Rminus_eq_contra ; symmetry ] ;\n assumption.\nQed.\n\n(** * All the definitions using _in are contravariant in their domain *)\n\nLemma D_x_covariant : forall D E x,\n  included D E -> included (D_x D x) (D_x E x).\nProof.\nintros D E x inc y [y_neq y_in] ; split ; [apply inc |] ; assumption.\nQed. \n\nLemma limit1_in_contravariant : forall D E f x l, included D E ->\n  limit1_in f E x l -> limit1_in f D x l.\nProof.\nintros D E f x l inc Hfxl eps eps_pos ;\n destruct (Hfxl _ eps_pos) as [alp [alp_pos Halp]] ; exists alp ; split.\n  assumption.\n  intros y [Dy y_bd] ; apply Halp ; split ; [apply inc |] ; assumption.\nQed.\n\nLemma continuity_pt_in_contravariant : forall D E f x, included D E ->\n  continuity_pt_in E f x -> continuity_pt_in D f x.\nProof.\nintros D E f x inc f_cont Dx ; apply limit1_in_contravariant with E.\n assumption.\n apply f_cont, inc ; assumption.\nQed.\n\nLemma continuity_in_contravariant : forall D E f, included D E ->\n  continuity_in E f -> continuity_in D f.\nProof.\nintros D E f inc f_cont x ;\n apply continuity_pt_in_contravariant with E, f_cont ; assumption.\nQed.\n\nLemma derivable_pt_lim_in_contravariant : forall D E f x l, included D E ->\n  derivable_pt_lim_in E f x l -> derivable_pt_lim_in D f x l.\nProof.\nintros D E f x l inc f_der ; apply limit1_in_contravariant with (D_x E x).\n apply D_x_covariant ; assumption.\n apply f_der.\nQed.\n\nLemma derivable_pt_in_contravariant : forall D E f x, included D E ->\n  derivable_pt_in E f x -> derivable_pt_in D f x.\nProof.\nintros D E f x inc [l Hl] ; exists l ;\n apply derivable_pt_lim_in_contravariant with E ; assumption.\nQed.\n\nLemma derivable_in_contravariant : forall D E f, included D E ->\n  derivable_in E f -> derivable_in D f.\nProof.\nintros D E f inc f_der x Dx ; apply derivable_pt_in_contravariant with E.\n assumption.\n apply f_der, inc ; assumption.\nQed.\n\nLemma injective_in_contravariant : forall D E f, included D E ->\n  injective_in E f -> injective_in D f.\nProof.\nintros D E f inc f_inj x y x_in y_in Hxy ; apply f_inj ; try apply inc ; assumption.\nQed.\n\nLemma surjective_in_contravariant : forall D E f, included D E ->\n  surjective_in E f -> surjective_in D f.\nProof.\nintros D E f inc f_surj y y_in ; apply f_surj ; try apply inc ; assumption.\nQed.\n\nLemma increasing_in_contravariant : forall D E f, included D E ->\n  increasing_in E f -> increasing_in D f.\nProof.\nintros D E f inc f_inc x y x_in y_in Hxy ; apply f_inc ; try apply inc ; assumption.\nQed.\n\nLemma decreasing_in_contravariant : forall D E f, included D E ->\n  decreasing_in E f -> decreasing_in D f.\nProof.\nintros D E f inc f_dec x y x_in y_in Hxy ; apply f_dec ; try apply inc ; assumption.\nQed.\n\nLemma monotonous_in_contravariant : forall D E f, included D E ->\n  monotonous_in E f -> monotonous_in D f.\nProof.\nintros D E f inc [f_dec | f_inc] ;\n [left ; eapply decreasing_in_contravariant |\n right ; eapply increasing_in_contravariant] ; eassumption.\nQed.\n\nLemma strictly_increasing_in_contravariant : forall D E f, included D E ->\n  strictly_increasing_in E f -> strictly_increasing_in D f.\nProof.\nintros D E f inc f_inc x y x_in y_in Hxy ; apply f_inc ; try apply inc ; assumption.\nQed.\n\nLemma strictly_decreasing_in_contravariant : forall D E f, included D E ->\n  strictly_decreasing_in E f -> strictly_decreasing_in D f.\nProof.\nintros D E f inc f_dec x y x_in y_in Hxy ; apply f_dec ; try apply inc ; assumption.\nQed.\n\nLemma strictly_monotonous_in_contravariant : forall D E f, included D E ->\n  strictly_monotonous_in E f -> strictly_monotonous_in D f.\nProof.\nintros D E f inc [f_dec | f_inc] ;\n [left ; eapply strictly_decreasing_in_contravariant |\n right ; eapply strictly_increasing_in_contravariant] ; eassumption.\nQed.\n\nDefinition reciprocal_in_contravariant : forall D E f g, included D E ->\n  reciprocal_in E f g -> reciprocal_in D f g.\nProof.\nintros D E f g inc Hfg x x_in ; apply Hfg, inc ; assumption.\nQed.\n\n(** * Extensionality of limit1_in *)\n\nLemma limit1_in_ext: forall (D : R -> Prop) f g x l,\n  (forall x, D x -> f x = g x) ->\n  limit1_in f D l x -> limit1_in g D l x.\nProof.\nintros D f g x l Heq Hf eps eps_pos ;\n destruct (Hf _ eps_pos) as [alp [alp_pos Halp]] ;\n exists alp ; split ; [assumption |].\n intros y Hy ; rewrite <- Heq ; [apply Halp |] ; apply Hy.\nQed.\n\nLemma limit1_in_ext_strong: forall (D : R -> Prop) r f g x l, 0 < r ->\n  (forall y, Rball x r y -> D y -> f y = g y) ->\n  limit1_in f D l x -> limit1_in g D l x.\nProof.\nintros D alp f g x l alp_pos Heq Hf eps eps_pos ;\n destruct (Hf _ eps_pos) as [bet [bet_pos Hbet]] ;\n exists (Rmin alp bet) ; split.\n apply Rmin_pos_lt ; assumption.\n intros y [Dy y_bd] ; rewrite <- Heq.\n  apply Hbet ; split ; [assumption | apply Rlt_le_trans with (Rmin alp bet) ;\n  [assumption | apply Rmin_r]].\n apply Rlt_le_trans with (Rmin alp bet) ; [apply y_bd | apply Rmin_l].\n assumption.\nQed.\n\n(* TODO: WTF does this do here? *)\n(** pr_nu_var restricted to a specific interval *)\n\nLemma pr_nu_var2_interv : forall (f g : R -> R) (lb ub x : R) (pr1 : derivable_pt f x)\n       (pr2 : derivable_pt g x),\n       open_interval lb ub x ->\n       (forall h : R, lb < h < ub -> f h = g h) ->\n       derive_pt f x pr1 = derive_pt g x pr2.\nProof.\nintros f g lb ub x Prf Prg x_encad local_eq.\nassert (forall x l, lb < x < ub -> (derivable_pt_abs f x l <-> derivable_pt_abs g x l)).\n intros a l a_encad.\n unfold derivable_pt_abs, derivable_pt_lim.\n split.\n intros Hyp eps eps_pos.\n elim (Hyp eps eps_pos) ; intros delta Hyp2.\n assert (Pos_cond : Rmin delta (Rmin (ub - a) (a - lb)) > 0).\n  clear-a lb ub a_encad delta.\n  apply Rmin_pos_lt ; [exact (delta.(cond_pos)) | apply Rmin_pos_lt ] ;\n  apply Rlt_Rminus ; intuition.\n exists (mkposreal (Rmin delta (Rmin (ub - a) (a - lb))) Pos_cond).\n intros h h_neq h_encad.\n replace (g (a + h) - g a) with (f (a + h) - f a).\n apply Hyp2 ; intuition.\n apply Rlt_le_trans with (r2:=Rmin delta (Rmin (ub - a) (a - lb))).\n assumption. apply Rmin_l.\n assert (local_eq2 : forall h : R, lb < h < ub -> - f h = - g h).\n  intros ; apply Ropp_eq_compat ; intuition.\n rewrite local_eq ; unfold Rminus. rewrite local_eq2. reflexivity.\n assumption.\n assert (Sublemma2 : forall x y, Rabs x < Rabs y -> y > 0 -> x < y).\n  intros m n Hyp_abs y_pos. apply Rlt_le_trans with (r2:=Rabs n).\n   apply Rle_lt_trans with (r2:=Rabs m) ; [ | assumption] ; apply RRle_abs.\n   apply Req_le ; apply Rabs_right ; apply Rgt_ge ; assumption.\n split.\n assert (Sublemma : forall x y z, -z < y - x -> x < y + z).\n  intros ; lra.\n apply Sublemma.\n apply Sublemma2. rewrite Rabs_Ropp.\n apply Rlt_le_trans with (r2:=a-lb) ; [| apply RRle_abs] ;\n apply Rlt_le_trans with (r2:=Rmin (ub - a) (a - lb)) ; [| apply Rmin_r] ;\n apply Rlt_le_trans with (r2:=Rmin delta (Rmin (ub - a) (a - lb))) ; [| apply Rmin_r] ; assumption.\n apply Rlt_le_trans with (r2:=Rmin (ub - a) (a - lb)) ; [| apply Rmin_r] ;\n apply Rlt_le_trans with (r2:=Rmin delta (Rmin (ub - a) (a - lb))) ; [| apply Rmin_r] ; assumption.\n assert (Sublemma : forall x y z, y < z - x -> x + y < z).\n  intros ; lra.\n apply Sublemma.\n apply Sublemma2.\n apply Rlt_le_trans with (r2:=ub-a) ; [| apply RRle_abs] ;\n apply Rlt_le_trans with (r2:=Rmin (ub - a) (a - lb)) ; [| apply Rmin_l] ;\n apply Rlt_le_trans with (r2:=Rmin delta (Rmin (ub - a) (a - lb))) ; [| apply Rmin_r] ; assumption.\n apply Rlt_le_trans with (r2:=Rmin (ub - a) (a - lb)) ; [| apply Rmin_l] ;\n apply Rlt_le_trans with (r2:=Rmin delta (Rmin (ub - a) (a - lb))) ; [| apply Rmin_r] ; assumption.\n intros Hyp eps eps_pos.\n elim (Hyp eps eps_pos) ; intros delta Hyp2.\n assert (Pos_cond : Rmin delta (Rmin (ub - a) (a - lb)) > 0).\n  clear-a lb ub a_encad delta.\n  apply Rmin_pos_lt ; [exact (delta.(cond_pos)) | apply Rmin_pos_lt ] ;\n  apply Rlt_Rminus ; intuition.\n exists (mkposreal (Rmin delta (Rmin (ub - a) (a - lb))) Pos_cond).\n intros h h_neq h_encad.\n replace (f (a + h) - f a) with (g (a + h) - g a).\n apply Hyp2 ; intuition.\n apply Rlt_le_trans with (r2:=Rmin delta (Rmin (ub - a) (a - lb))).\n assumption. apply Rmin_l.\n assert (local_eq2 : forall h : R, lb < h < ub -> - f h = - g h).\n  intros ; apply Ropp_eq_compat ; intuition.\n rewrite local_eq ; unfold Rminus. rewrite local_eq2. reflexivity.\n assumption.\n assert (Sublemma2 : forall x y, Rabs x < Rabs y -> y > 0 -> x < y).\n  intros m n Hyp_abs y_pos. apply Rlt_le_trans with (r2:=Rabs n).\n   apply Rle_lt_trans with (r2:=Rabs m) ; [ | assumption] ; apply RRle_abs.\n   apply Req_le ; apply Rabs_right ; apply Rgt_ge ; assumption.\n split.\n assert (Sublemma : forall x y z, -z < y - x -> x < y + z).\n  intros ; lra.\n apply Sublemma.\n apply Sublemma2. rewrite Rabs_Ropp.\n apply Rlt_le_trans with (r2:=a-lb) ; [| apply RRle_abs] ;\n apply Rlt_le_trans with (r2:=Rmin (ub - a) (a - lb)) ; [| apply Rmin_r] ;\n apply Rlt_le_trans with (r2:=Rmin delta (Rmin (ub - a) (a - lb))) ; [| apply Rmin_r] ; assumption.\n apply Rlt_le_trans with (r2:=Rmin (ub - a) (a - lb)) ; [| apply Rmin_r] ;\n apply Rlt_le_trans with (r2:=Rmin delta (Rmin (ub - a) (a - lb))) ; [| apply Rmin_r] ; assumption.\n assert (Sublemma : forall x y z, y < z - x -> x + y < z).\n  intros ; lra.\n apply Sublemma.\n apply Sublemma2.\n apply Rlt_le_trans with (r2:=ub-a) ; [| apply RRle_abs] ;\n apply Rlt_le_trans with (r2:=Rmin (ub - a) (a - lb)) ; [| apply Rmin_l] ;\n apply Rlt_le_trans with (r2:=Rmin delta (Rmin (ub - a) (a - lb))) ; [| apply Rmin_r] ; assumption.\n apply Rlt_le_trans with (r2:=Rmin (ub - a) (a - lb)) ; [| apply Rmin_l] ;\n apply Rlt_le_trans with (r2:=Rmin delta (Rmin (ub - a) (a - lb))) ; [| apply Rmin_r] ; assumption.\n unfold derivable_pt in Prf.\n  unfold derivable_pt in Prg.\n  elim Prf; intros.\n  elim Prg; intros.\n  assert (Temp := p); rewrite H in Temp.\n  unfold derivable_pt_abs in p.\n  unfold derivable_pt_abs in p0.\n  simpl in |- *.\n  apply (uniqueness_limite g x x0 x1 Temp p0).\n  assumption.\nQed.\n\n(** Simplification lemmas on mult_real_fun *)\n\nLemma mult_real_fct_0: forall f,\n  mult_real_fct 0 f == (fun _ => 0).\nProof.\nintros f x ; unfold mult_real_fct ; apply Rmult_0_l.\nQed.", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/src/Reals/Ranalysis/Ranalysis_def_simpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6640174267868921}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Crypto.Util.Tuple.\nRequire Import Crypto.Util.Decidable.\nRequire Import Crypto.Util.Notations.\n\nDelimit Scope zrange_scope with zrange.\nRecord zrange := { lower : Z ; upper : Z }.\nBind Scope zrange_scope with zrange.\nLocal Open Scope Z_scope.\n\nDefinition ZToZRange (z : Z) : zrange := {| lower := z ; upper := z |}.\n\nLtac inversion_zrange :=\n  let lower := (eval cbv [lower] in (fun x => lower x)) in\n  let upper := (eval cbv [upper] in (fun y => upper y)) in\n  repeat match goal with\n         | [ H : _ = _ :> zrange |- _ ]\n           => pose proof (f_equal lower H); pose proof (f_equal upper H); clear H;\n              cbv beta iota in *\n         end.\n\n(** All of the boundedness properties take an optional bitwidth, and\n    enforce the condition that the range is within 0 and 2^bitwidth,\n    if given. *)\nSection with_bitwidth.\n  Context (bitwidth : option Z).\n\n  Definition is_bounded_by' : zrange -> Z -> Prop\n    := fun bound val\n       => lower bound <= val <= upper bound\n          /\\ match bitwidth with\n             | Some sz => 0 <= lower bound /\\ upper bound < 2^sz\n             | None => True\n             end.\n\n  Definition is_bounded_by {n} : Tuple.tuple zrange n -> Tuple.tuple Z n -> Prop\n    := Tuple.fieldwise is_bounded_by'.\nEnd with_bitwidth.\n\nDefinition is_tighter_than_bool (x y : zrange) : bool\n  := ((lower y <=? lower x) && (upper x <=? upper y))%bool%Z.\n\nGlobal Instance dec_eq_zrange : DecidableRel (@eq zrange) | 10.\nProof.\n  intros [lx ux] [ly uy].\n  destruct (dec (lx = ly)), (dec (ux = uy));\n    [ left; apply f_equal2; assumption\n    | abstract (right; intro H; inversion_zrange; tauto).. ].\nDefined.\n\nModule Export Notations.\n  Delimit Scope zrange_scope with zrange.\n  Notation \"r[ l ~> u ]\" := {| lower := l ; upper := u |}\n                              (format \"r[ l  ~>  u ]\") : zrange_scope.\n  Infix \"<=?\" := is_tighter_than_bool : zrange_scope.\nEnd Notations.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_crypto_defined/src/Util/ZRange.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6640174132699959}}
{"text": "Require Import Logic.Axiom.Extensionality.\n\nRequire Import Logic.Rel.R.\n\nDeclare Scope Rel_Composition_scope.\n\n(* Composition operator.                                                        *)\nDefinition comp (a b c:Type) (s:R b c) (r:R a b) : R a c :=\n    fun (x:a) (z:c) => exists (y:b), r x y /\\ s y z.\n\nArguments comp {a} {b} {c}.\n\n\nNotation \"s ; r\" := (comp s r) \n    (at level 60, right associativity) : Rel_Composition_scope.\n\nOpen Scope Rel_Composition_scope.\n\n(* associativity law.                                                           *)\nLemma comp_assoc : forall (a b c d:Type) (r:R a b) (s:R b c) (t:R c d),\n    (t ; s) ; r = t ; (s ; r).\nProof.\n    intros a b c d r s t. apply Ext. intros x y. unfold comp. split.\n    - intros [x' [H1 [y' [H2 H3]]]]. exists y'. split.\n        + exists x'. split; assumption.\n        + assumption.\n    - intros [y' [[x' [H1 H2]] H3]]. exists x'. split.\n        + assumption.\n        + exists y'. split; 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/Composition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6640174114036437}}
{"text": "\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Export List.\n\nSection Listes.\n\n  Variable A : Set.\n\n  Let List := list A.\n\n\n\n  Inductive item (x : A) : List -> nat -> Prop :=\n    | item_hd : forall l : List, item x (x :: l) 0\n    | item_tl :\n        forall (l : List) (n : nat) (y : A),\n        item x l n -> item x (y :: l) (S n).\n\n  Lemma fun_item :\n   forall (u v : A) (e : List) (n : nat), item u e n -> item v e n -> u = v.\nProof.\nsimple induction 1; intros.\ninversion_clear H0; auto.\n\ninversion_clear H2; auto.\nQed.\n\n\n  Lemma list_item :\n   forall e n, {t : _ | item t e n} + {(forall t, ~ item t e n)}.\nProof.\nfix item_rec 1.\nintros [| h l].\nright; red in |- *; intros t in_nil; inversion in_nil.\n\nintros [| k].\nleft; exists h; constructor.\n\ncase (item_rec l k).\nintros (y, in_tl); left; exists y; constructor; trivial.\n\nintros not_in_tl; right; intros t in_tl_l; inversion_clear in_tl_l;\n red in not_in_tl; eauto.\nDefined.\n\n\n\n  Inductive trunc : nat -> List -> List -> Prop :=\n    | trunc_O : forall e : List, trunc 0 e e\n    | trunc_S :\n        forall (k : nat) (e f : List) (x : A),\n        trunc k e f -> trunc (S k) (x :: e) f.\n\n  Lemma item_trunc :\n   forall (n : nat) (e : List) (t : A),\n   item t e n -> exists f : List, trunc (S n) e f.\nProof.\nsimple induction n; intros.\ninversion_clear H.\nexists l.\napply trunc_S.\napply trunc_O.\n\ninversion_clear H0.\nelim H with l t; intros.\nexists x.\napply trunc_S.\ntrivial.\n\ntrivial.\nQed.\n\n\nEnd Listes.\n\n  Hint Resolve item_hd item_tl trunc_O trunc_S: core.\n\n", "meta": {"author": "coq-contribs", "repo": "pts", "sha": "10a0c39b7e62f8a7ec2afbbe516a21289d065be5", "save_path": "github-repos/coq/coq-contribs-pts", "path": "github-repos/coq/coq-contribs-pts/pts-10a0c39b7e62f8a7ec2afbbe516a21289d065be5/MyList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6640174095372914}}
{"text": "(** * Koindukcja (negatywna, czyli lepsza) *)\n\n(** ** Strumienie *)\n\nCoInductive Stream (A : Type) : Type :=\n{\n    hd : A;\n    tl : Stream A;\n}.\n\nArguments hd {A}.\nArguments tl {A}.\n\nCoFixpoint from' (n : nat) : Stream nat :=\n{|\n    hd := n;\n    tl := from' (S n);\n|}.\n\nCoInductive bisim {A : Type} (s1 s2 : Stream A) : Prop :=\n{\n    hds : hd s1 = hd s2;\n    tls : bisim A (tl s1) (tl s2);\n}.\n\nLemma bisim_refl :\n  forall (A : Type) (s : Stream A), bisim s s.\nProof.\n  cofix CH. constructor; auto.\nQed.\n\nLemma bisim_sym :\n  forall (A : Type) (s1 s2 : Stream A),\n    bisim s1 s2 -> bisim s2 s1.\nProof.\n  cofix CH.\n  destruct 1 as [hds tls]. constructor; auto.\nQed.\n\nLemma bisim_trans :\n  forall (A : Type) (s1 s2 s3 : Stream A),\n    bisim s1 s2 -> bisim s2 s3 -> bisim s1 s3.\nProof.\n  cofix CH.\n  destruct 1 as [hds1 tls1], 1 as [hds2 tls2].\n  constructor; eauto. rewrite hds1. assumption.\nQed.\n\nCoFixpoint evens {A : Type} (s : Stream A) : Stream A :=\n{|\n    hd := hd s;\n    tl := evens (tl (tl s));\n|}.\n\n(** Na tablicy można pisać za pomocą (ko?)równań.\n\n    hd (evens s) := hd s;\n    tl (evens s) := evens (tl (tl s));\n\n*)\n\nCoFixpoint odds {A : Type} (s : Stream A) : Stream A :=\n{|\n    hd := hd (tl s);\n    tl := odds (tl (tl s));\n|}.\n\nDefinition split {A : Type} (s : Stream A)\n  : Stream A * Stream A := (evens s, odds s).\n\nCoFixpoint merge\n  {A : Type} (ss : Stream A * Stream A) : Stream A :=\n{|\n    hd := hd (fst ss);\n    tl := merge (snd ss, tl (fst ss));\n|}.\n\nLemma merge_split :\n  forall (A : Type) (s : Stream A),\n    bisim (merge (split s)) s.\nProof.\n  unfold split.\n  cofix CH.\n  intros. constructor.\n    cbn. reflexivity.\n    cbn. constructor.\n      cbn. reflexivity.\n      cbn. apply CH.\nQed.\n\n(** ** Kolisty *)\n\nCoInductive LList (A : Type) : Type :=\n{\n    uncons : option (A * LList A);\n}.\n\nArguments uncons {A}.\n\nDefinition lnil {A : Type} : LList A := {| uncons := None |}.\n\nDefinition lcons {A : Type} (x : A) (l : LList A) : LList A :=\n  {| uncons := Some (x, l); |}.\n\nCoFixpoint from (n : nat) : LList nat :=\n  lcons n (from (S n)).\n\nInductive Finite {A : Type} : LList A -> Prop :=\n    | Finite_nil : Finite lnil\n    | Finite_cons :\n        forall (h : A) (t : LList A),\n          Finite t -> Finite (lcons h t).\n\nCoInductive Infinite {A : Type} (l : LList A) : Prop :=\n{\n    h : A;\n    t : LList A;\n    p : uncons l = Some (h, t);\n    inf' : Infinite t;\n}.\n\n(** * Indukcja i rekursja dobrze ufundowana *)\n\nModule Wf.\n\nInductive Acc {A : Type} (R : A -> A -> Type) (x : A) : Prop :=\n    | Acc_intro : (forall y : A, R y x -> Acc R y) -> Acc R x.\n\nDefinition well_founded {A : Type} (R : A -> A -> Type) : Prop :=\n  forall x : A, Acc R x.\n\nLemma le_not_Acc :\n  forall n : nat, Acc le n -> False.\nProof.\n  induction 1. apply (H0 x). apply le_n.\nQed.\n\nLemma le_not_wf : ~ well_founded le.\nProof.\n  unfold well_founded. intro.\n  apply le_not_Acc with 0. apply H.\nQed.\n\nLemma lt_wf : well_founded lt.\nProof.\n  unfold well_founded.\n  induction x as [| n']; constructor; inversion 1; subst.\n    assumption.\n    inversion IHn'. apply H0. assumption.\nQed.\n\nTheorem well_founded_induction_type :\n  forall\n    (A : Type) (R : A -> A -> Type)\n    (wf : well_founded R) (P : A -> Type),\n      (forall x : A, (forall y : A, R y x -> P y) -> P x) ->\n        forall x : A, P x.\nProof.\n  intros A R wf P IH x.\n  unfold well_founded in wf.\n  specialize (wf x).\n  induction wf.\n  apply IH.\n  assumption.\nDefined.\n\nEnd Wf.\n\n(** ** Przykład: dzielenie i indukcja funkcyjna *)\n\nRequire Import Arith.\nRequire Import Omega.\n\nDefinition div : nat -> forall k : nat, 0 < k -> nat.\nProof.\n  apply (@well_founded_induction_type nat lt lt_wf\n    (fun n : nat => forall k : nat, 0 < k -> nat)).\n  intros. destruct (le_lt_dec k x).\n    Focus 2. exact 0.\n    apply S. apply (H (x - k)) with k.\n      apply Nat.sub_lt; assumption.\n      assumption.\nDefined.\n\nCompute div 5 2 ltac:(omega).\n\nLemma div_le :\n  forall (n m : nat) (H : 0 < m),\n    div n m H <= n.\nProof.\n  intros. revert n.\n  apply (@well_founded_induction_type nat lt lt_wf).\n  intros n IH.\n  cbn. destruct (le_lt_dec m n).\n    admit.\n    apply le_0_n.\nAbort.\n\nLemma div_lt_n_k :\n  forall (n k : nat) (H : 0 < k),\n    n < k -> div n k H = 0.\nProof.\n  intros. cbn. destruct (le_lt_dec k n).\n    omega.\n    trivial.\nQed.\n\nLemma div_le_k_n :\n  forall (n k : nat) (H : 0 < k),\n    k <= n -> div n k H = S (div (n - k) k H).\nProof.\n  apply (@well_founded_ind nat lt lt_wf\n    (fun n => forall (k : nat) (H : 0 < k),\n      k <= n -> div n k H = S (div (n - k) k H))).\n  intros. cbn. destruct (le_lt_dec k x).\n    f_equal.\nAdmitted.\n\nTheorem div_eq :\n  forall (n k : nat) (H : 0 < k), div n k H =\n    match le_lt_dec k n with\n        | left _ => S (div (n - k) k H)\n        | right _ => 0\n    end.\nProof.\n  intros. destruct (le_lt_dec k n).\n    rewrite div_le_k_n; auto.\n    rewrite div_lt_n_k; auto.\nQed.\n\nLemma div_le :\n  forall (n m : nat) (H : 0 < m),\n    div n m H <= n.\nProof.\n  intros.\n  rewrite div_eq.\n  destruct (le_lt_dec m n).\nAbort.\n\nInductive divR : nat -> nat -> nat -> Prop :=\n    | div_base :\n        forall (n k : nat), 0 < k -> n < k -> divR n k 0\n    | div_rec :\n        forall (n k r : nat), 0 < k -> k <= n ->\n          divR (n - k) k r -> divR n k (S r).\n\nHint Constructors divR.\n\nLemma divR_correct :\n  forall (n k r : nat) (H : 0 < k),\n    div n k H = r -> divR n k r.\nProof.\n  apply (@well_founded_induction nat lt lt_wf\n    (fun n : nat => forall (k r : nat) (H : 0 < k ),\n      div n k H = r -> divR n k r)).\n  intros. rewrite div_eq in H1. destruct (le_lt_dec k x); subst.\n    Focus 2. constructor; auto.\n    constructor; auto. apply H with H0; omega.\nQed.\n\nLemma divR_complete :\n  forall (n k r : nat) (H : 0 < k),\n    divR n k r -> div n k H = r.\nProof.\n  induction 1.\n    apply div_lt_n_k. assumption.\n    rewrite <- IHdivR with H. rewrite div_le_k_n; auto.\nQed.\n\nTheorem div_ind :\n  forall P : nat -> nat -> nat -> Prop,\n    (forall n k : nat, 0 < k -> n < k -> P n k 0) ->\n    (forall (n k : nat) (H : 0 < k), k <= n ->\n      P (n - k) k (div (n - k) k H) -> P n k (S (div (n - k) k H))) ->\n        forall (n k : nat) (H : 0 < k), P n k (div n k H).\nProof.\n  intros. apply divR_ind; intros.\n    apply H; auto.\n    eapply (divR_complete _ _ _ H2) in H4. subst. apply H0; assumption.\n    apply divR_correct with H1. reflexivity.\nQed.\n\nLemma div_le :\n  forall (n m : nat) (H : 0 < m),\n    div n m H <= n.\nProof.\n  apply (div_ind (fun n m r => r <= n)).\n    intros. apply le_0_n.\n    intros. destruct n as [| n'].\n      omega.\n      apply le_n_S. omega.\nQed.\n\nRequire Import Recdef.\n\n(** div' n m = n/(m + 1) *)\nFunction div' (n m : nat) {measure id n} : nat :=\n  if le_lt_dec (S m) n\n  then S (div' (n - S m) m)\n  else 0.\nProof.\n  intros. unfold id. omega.\nDefined.\n\nPrint R_div'.\nCheck R_div'_correct.\nCheck R_div'_complete.\nCheck div'_ind.\n\nLemma div'_le :\n  forall n m : nat, div' n m <= n.\nProof.\n  intros. functional induction (div' n m).\n    omega.\n    apply le_0_n.\nDefined.\n\n(** * Plugin Equations *)\n\n(** Niestety zabrakło czasu na customowy przykład, a głębsze wyjaśnienia nie\n    miały większego sensu. Żeby dowiedzieć się więcej, zrób zadanie 8. *)", "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/w9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.663993262837364}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Frederic Blanqui, 2014-12-11\n\nuseful definitions and lemmas on functions\n*)\n\nSet Implicit Arguments.\n\nFrom CoLoR Require Import LogicUtil.\n\n(****************************************************************************)\n(** Some properties of functions. *)\n\nSection functions.\n\n  Variables (A B : Type) (f : A -> B).\n\n  Definition injective := forall x y, f x = f y -> x = y.\n\n  Definition surjective := forall y, exists x, y = f x.\n\n  Definition bijective := injective /\\ surjective.\n\nEnd functions.\n\n(****************************************************************************)\n(** Function composition. *)\n\nSection comp.\n\n  Variables (A B C : Type) (f : B -> C) (g : A -> B).\n\n  Definition comp x := f (g x).\n\n  Lemma inj_comp : injective f -> injective g -> injective comp.\n\n  Proof.\n    intros f_inj g_inj x y e. apply f_inj in e. apply g_inj in e. hyp.\n  Qed.\n\n  Lemma inj_comp_elim : injective comp -> injective g.\n\n  Proof.\n    intros comp_inj x y e. apply comp_inj. unfold comp. rewrite e. refl.\n  Qed.\n\n  Lemma surj_comp : surjective f -> surjective g -> surjective comp.\n\n  Proof.\n    intros f_surj g_surj z. destruct (f_surj z) as [y hy].\n    destruct (g_surj y) as [x hx]. ex x. subst. refl.\n  Qed.\n\n  Lemma surj_comp_elim : surjective comp -> surjective f.\n\n  Proof.\n    intros comp_surj y. destruct (comp_surj y) as [x e]. subst. ex (g x). refl.\n  Qed.\n\n  Lemma bij_comp : bijective f -> bijective g -> bijective comp.\n\n  Proof.\n    intros f_bij g_bij. split. apply inj_comp; fo. apply surj_comp; fo.\n  Qed.\n\nEnd comp.\n\nInfix \"o\" := comp (at level 70).\n\n(****************************************************************************)\n(** Inverse of a surjective function, using Hilbert's epsilon operator. *)\n\nFrom CoLoR Require Import EpsilonUtil.\n\nSection inverse.\n\n  Variables (A B : Type) (f : A -> B) (f_surj : surjective f).\n\n  Definition inverse : B -> A.\n\n  Proof. intro y. destruct (cid (f_surj y)) as [x _]. exact x. Defined.\n\n  Lemma inverse_eq y : f (inverse y) = y.\n\n  Proof. unfold inverse. destruct (cid (f_surj y)) as [x e]. auto. Qed.\n\n  Lemma inj_inverse : injective inverse.\n\n  Proof.\n    intros x y e. apply (f_equal f) in e. rewrite !inverse_eq in e. hyp.\n  Qed.\n\nEnd inverse.\n\n(****************************************************************************)\n(** Tactics for injectivity, surjective and bijectivity. *)\n\nLtac inj :=\n  match goal with\n    | |- injective (_ o _) => apply inj_comp; inj\n    | |- injective (inverse _) => apply inj_inverse; inj\n    | |- injective _ => auto\n  end.\n\nLtac surj :=\n  match goal with\n    | |- surjective (_ o _) => apply surj_comp; surj\n    | |- surjective _ => auto\n  end.\n\nLtac bij :=\n  match goal with\n    | |- bijective (_ o _) => apply bij_comp; bij\n    | |- bijective _ => hyp || (split; [inj | surj])\n  end.\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Util/Function/FunUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.6639932540316711}}
{"text": "Require Export Complex.\nRequire Export Quantum.\nRequire Export Init.Datatypes.\nRequire Export Coq.Sorting.Permutation.\nRequire Export Coq.Lists.List.\n(** This file provides padding functions to extend a matrix to a larger space.\n   This is useful for describing the effect of 1- and 2-qubit gates on a larger\n   quantum space. *)\n\n(* if_matrix notation + lemmas *)\n\nDefinition if_matrix {n} (b : bool) (u1 u2 : Square n) : Square n :=\n  if b then u1 else u2.\n\nLemma WF_if_matrix : forall (n : nat) (b : bool) (u1 u2 : Square n), \nWF_Matrix u1 -> WF_Matrix u2 -> WF_Matrix (if_matrix b u1 u2).\nProof.\n  intros. destruct b; assumption.\nQed.\n\nNotation \"A <| b |> B\" := (if_matrix b A B) (at level 30).\n\nLemma if_matrix_mul : forall b n (A B C D : Square n),\n    (A <|b|> B) × (C <| b |> D) = (A × C) <| b |> (B × D).\nProof.\n  destruct b; reflexivity.\nQed.\n\n#[export] Hint Resolve WF_if_matrix : wf_db.\n\nDefinition pad {n} (start dim : nat) (A : Square (2^n)) : Square (2^dim) :=\n  if start + n <=? dim then I (2^start) ⊗ A ⊗ I (2^(dim - (start + n))) else Zero.\n\nLemma WF_pad : forall n start dim (A : Square (2^n)),\n  WF_Matrix A ->\n  WF_Matrix (pad start dim A).\nProof.\n  intros n start dim A WFA. unfold pad.\n  bdestruct (start + n <=? dim); auto with wf_db.\nQed.  \n\nLemma pad_mult : forall n dim start (A B : Square (2^n)),\n  pad start dim A × pad start dim B = pad start dim (A × B).\nProof.\n  intros.\n  unfold pad.\n  gridify.\n  reflexivity.\nQed.\n\nLemma pad_id : forall n dim,\n  (n < dim)%nat -> @pad 1 n dim (I 2) = I (2 ^ dim).\nProof. intros. unfold pad. gridify. reflexivity. Qed.\n\nDefinition pad_u (dim n : nat) (u : Square 2) : Square (2^dim) := @pad 1 n dim u.\n\nDefinition pad_ctrl (dim m n: nat) (u: Square 2) :=\n  if (m <? n) then\n    @pad (1+(n-m-1)+1) m dim (∣1⟩⟨1∣ ⊗ I (2^(n-m-1)) ⊗ u .+ ∣0⟩⟨0∣ ⊗ I (2^(n-m-1)) ⊗ I 2)\n  else if (n <? m) then\n    @pad (1+(m-n-1)+1) n dim (u ⊗ I (2^(m-n-1)) ⊗ ∣1⟩⟨1∣ .+ I 2 ⊗ I (2^(m-n-1)) ⊗ ∣0⟩⟨0∣)\n  else\n    Zero.\n\n(* also possible to define this in terms of pad directly *)\nDefinition pad_swap (dim m n: nat) :=\n  pad_ctrl dim m n σx × pad_ctrl dim n m σx × pad_ctrl dim m n σx.\n\n(** Well-formedness *)\n\nLemma WF_pad_u : forall dim n u, WF_Matrix u -> WF_Matrix (pad_u dim n u).\nProof.\n  intros. \n  unfold pad_u.\n  apply WF_pad; easy.\nQed.\n\nLemma WF_pad_ctrl : forall dim m n u, WF_Matrix u -> WF_Matrix (pad_ctrl dim m n u).\n  intros. \n  unfold pad_ctrl.\n  assert (H' : forall n, (2 * 2 ^ n * 2 = 2 ^ (1 + n + 1))%nat).\n  { intros.\n    do 2 rewrite Nat.pow_add_r, Nat.pow_1_r; easy. }\n  bdestruct (m <? n); bdestruct (n <? m); try lia; auto with wf_db.\n  all : apply WF_pad; rewrite H'; apply WF_plus; auto with wf_db.\nQed.\n\nLemma WF_pad_swap : forall dim m n, WF_Matrix (pad_swap dim m n).\n  intros.\n  unfold pad_swap.\n  repeat apply WF_mult; apply WF_pad_ctrl; apply WF_σx.\nQed.\n\n#[export] Hint Resolve WF_pad WF_pad_u WF_pad_ctrl WF_pad_swap : wf_db.\n\n(* pad2x2, embed definition + lemmas about commutation *)\nDefinition pad2x2 {dim : nat} (A : Square 2) (i : nat) : Square (2^dim) :=\n  if (i <? dim) then (I (2^i) ⊗ A ⊗ I (2^(dim - i - 1))) else Zero.\n\nLemma WF_pad2x2 : forall (i dim : nat) (A : Square 2),\nWF_Matrix A -> WF_Matrix (@pad2x2 dim A i).\nProof.\n  intros i dim A WF_A. unfold pad2x2.\n  bdestruct_all; simpl; auto with wf_db.\nQed.\n\n#[export] Hint Resolve WF_pad2x2 : wf_db.\n\nFixpoint embed {dim : nat} (lp : (list ((Square 2) * nat))) : Square (2^dim)  :=\n  match lp with\n  | (A, i) :: lp' => @Mmult (2^dim) (2^dim) (2^dim) (@pad2x2 dim A i) (embed lp')\n  | _         => I (2^dim)\n  end.\n\n\nLemma pad2x2_commutes : forall (A B : Square 2) (i j dim : nat),\ni <> j ->\nWF_Matrix A ->\nWF_Matrix B ->\n@pad2x2 dim A i × @pad2x2 dim B j = @pad2x2 dim B j × @pad2x2 dim A i.\nProof.\n  intros. unfold pad2x2.\n  gridify; trivial.\n  Qed.\n\nLemma WF_embed : forall (dim : nat) (lp : (list ((Square 2) * nat))),\nForall WF_Matrix (map fst lp) -> \nNoDup (map snd lp) ->\nForall (fun n => (n < dim)%nat) (map snd lp) ->\nWF_Matrix (@embed dim lp).\nintros. induction lp. \n+ unfold embed; auto with wf_db.\n+ destruct a. bdestruct (n <? dim); Msimpl; auto with wf_db.\n  - inversion H; subst. inversion H0; subst. inversion H1; subst.\n   simpl. apply WF_mult; auto with wf_db.\n  - inversion H1; subst. lia.\nQed.\n\n#[export] Hint Resolve WF_embed : wf_db.\n\nLemma embed_commutes_base : forall (i j dim : nat)(A B : Square 2) \n(lp : (list ((Square 2) * nat))),\n  i <> j ->\n  WF_Matrix A ->\n  WF_Matrix B ->\n  (i < dim)%nat ->\n  (j < dim)%nat ->\n  @embed dim ((A, i) :: (B, j) :: lp) = @embed dim ((B, j) :: (A, i) :: lp).\n  Proof.\n    intros. simpl. rewrite <- Mmult_assoc. rewrite pad2x2_commutes; trivial.\n    apply Mmult_assoc.\n  Qed.\n\nLemma embed_commutes : forall (dim : nat) (lp1 lp2 : list ((Square 2) * nat)),\n  Forall WF_Matrix (map fst lp1) ->\n  NoDup (map snd lp1) ->\n  Forall (fun n => (n < dim)%nat) (map snd lp1) ->\n  Permutation lp1 lp2 ->\n  @embed dim lp1 = @embed dim lp2.\n  Proof.\n    intros. induction H2; trivial.\n    + simpl. rewrite IHPermutation; trivial. \n      - simpl in *. inversion H; subst.\n      auto.\n      - inversion H0; auto.\n      - simpl in H1. \n        apply Forall_inv_tail in H1.\n        assumption.\n    + destruct x, y. apply embed_commutes_base.\n      - simpl in H0. inversion H0; subst. simpl in *. intros n0eqn. apply H4. auto.\n      - simpl in *. inversion H; subst.\n      auto.\n      - inversion H; subst. inversion H5; subst.\n      auto.\n      - inversion H1; auto.\n      - inversion H1; subst. inversion H5; auto.\n    + pose proof (Permutation_map snd H2_). rewrite IHPermutation1; \n    try rewrite IHPermutation2; trivial.\n      - apply (Permutation_map fst) in H2_. eapply Permutation_Forall; eauto.\n      - apply (Permutation_NoDup H2 H0).\n      - eapply Permutation_Forall; eauto.\n    Qed.\n\nLemma embed_mult : forall (dim : nat) (lp1 lp2 : list ((Square 2) * nat)),\nForall WF_Matrix (map fst lp1) ->\nForall WF_Matrix (map fst lp2) ->\nNoDup (map snd lp1) ->\nNoDup (map snd lp2) ->\nForall (fun n : nat => (n < dim)%nat) (map snd lp1) ->\nForall (fun n : nat => (n < dim)%nat) (map snd lp2) ->\n@embed dim lp1 × @embed dim lp2 = @embed dim (lp1 ++ lp2).\nProof.\n  intros. induction lp1.\n  + simpl. apply Mmult_1_l. apply WF_embed; trivial.\n  + simpl. rewrite <- IHlp1. destruct a. apply Mmult_assoc.\n  inversion H; auto.\n  inversion H1; auto.\n  inversion H3; auto.\nQed.\n\n(* TODO: find function in stdlib *) \nDefinition abs_diff (a b : nat) := Nat.max (a - b) (b - a).\n\nDefinition pad2x2_ctrl (dim m n : nat) (u : Square 2) : Square (2^dim)%nat :=\n  if m =? n then Zero\n  else\n    let b := m <? n in\n    let μ := min m n in\n    let δ := abs_diff m n in\n    (@embed dim\n    ([((∣1⟩⟨1∣ <|b|> u), μ)] ++\n    [((u <|b|> ∣1⟩⟨1∣), (μ + δ)%nat)])) \n    .+ \n    (@embed dim\n    ([((∣0⟩⟨0∣ <|b|> I 2), μ)] ++\n    [((I 2 <|b|> ∣0⟩⟨0∣), (μ + δ)%nat)])).\n\nLtac rem_max_min :=\n   unfold gt, ge, abs_diff in *;\n  repeat match goal with \n  | [ H: (?a < ?b)%nat |- context[Nat.max (?a - ?b) (?b - ?a)] ] => \n    rewrite (Max.max_r (a - b) (b - a)) by lia \n  | [ H: (?a < ?b)%nat |- context[Nat.max (?b - ?a) (?a - ?b)] ] => \n    rewrite (Max.max_l (b - a) (a - b)) by lia \n  | [ H: (?a <= ?b)%nat |- context[Nat.max (?a - ?b) (?b - ?a)] ] => \n    rewrite (Max.max_r (a - b) (b - a)) by lia \n  | [ H: (?a <= ?b)%nat |- context[Nat.max (?b - ?a) (?a - ?b)] ] => \n    rewrite (Max.max_l (b - a) (a - b)) by lia   \n  | [ H: (?a < ?b)%nat |- context[Nat.min ?a ?b] ] => \n    rewrite Min.min_l by lia \n  | [ H: (?a < ?b)%nat |- context[Nat.max ?a ?b] ] => \n    rewrite Max.max_r by lia \n  | [ H: (?a < ?b)%nat |- context[Nat.min ?b ?a] ] => \n    rewrite Min.min_r by lia \n  | [ H: (?a < ?b)%nat |- context[Nat.max ?b ?a] ] => \n    rewrite Max.max_l by lia \n  | [ H: (?a <= ?b)%nat |- context[Nat.min ?a ?b] ] => \n    rewrite Min.min_l by lia \n  | [ H: (?a <= ?b)%nat |- context[Nat.max ?a ?b] ] => \n    rewrite Max.max_r by lia \n  | [ H: (?a <= ?b)%nat |- context[Nat.min ?b ?a] ] => \n    rewrite Min.min_r by lia \n  | [ H: (?a <= ?b)%nat |- context[Nat.max ?b ?a] ] => \n    rewrite Max.max_l by lia \n  end.\n\nDefinition pad2x2_u (dim n : nat) (u : Square 2) : Square (2^dim) := @embed dim [(u,n)].\n\n(* also possible to define this in terms of pad2x2 directly *)\nDefinition pad2x2_swap (dim m n: nat) :=\n  pad2x2_ctrl dim m n σx × pad2x2_ctrl dim n m σx × pad2x2_ctrl dim m n σx.\n\n(** Well-formedness *)\n\nLemma WF_pad2x2_u : forall dim n u, WF_Matrix u -> WF_Matrix (pad2x2_u dim n u).\nProof.\n  intros. \n  unfold pad2x2_u.\n  unfold embed.\n  auto with wf_db. \nQed.\n\nLemma WF_pad2x2_ctrl : forall dim m n u, WF_Matrix u -> WF_Matrix (pad2x2_ctrl dim m n u).\nProof.\n  intros dim m n u WF_u.\n  unfold pad2x2_ctrl, abs_diff. bdestruct_all; simpl; rem_max_min;\n  restore_dims; auto with wf_db.\n  Qed.\n\n\nLemma WF_pad2x2_swap : forall dim m n, WF_Matrix (pad2x2_swap dim m n).\n  intros.\n  unfold pad2x2_swap.\n  repeat apply WF_mult; apply WF_pad2x2_ctrl; apply WF_σx.\nQed.\n\n#[export] Hint Resolve WF_pad2x2 WF_pad2x2_u WF_pad2x2_ctrl WF_pad2x2_swap : wf_db.\n\n(* tactics for NoDup *)\nLtac NoDupity :=\n  repeat match goal with\n  | |- NoDup [?a] => repeat constructor; auto\n  | |- NoDup _=> repeat constructor; intros []; try lia; auto\n  | [ H1: In ?a ?b |- False ] => inversion H1; auto\n  end.\n\n(* Lemmas about commutativity *)\n\nLemma pad2x2_A_B_commutes : forall dim m n A B,\n  m <> n ->\n  (m < dim)%nat ->\n  (n < dim)%nat ->\n  WF_Matrix A ->\n  WF_Matrix B ->\n  pad2x2_u dim m A × pad2x2_u dim n B = pad2x2_u dim n B × pad2x2_u dim m A.\nProof.\n  intros. unfold pad2x2_u. unfold WF_Matrix in *.\n  repeat rewrite embed_mult. apply embed_commutes.\n  all : simpl; try auto with wf_db; NoDupity.\n  constructor.\nQed.\n\n\nLtac comm_pad2x2 :=\n  repeat match goal with\n  | |- context[?A = ?B] => match A with\n      | context[@pad2x2 ?dim ?X ?x × @pad2x2 ?dim ?Y ?y × @pad2x2 ?dim ?Z ?z] =>\n      match B with\n        | context[pad2x2 Z z × pad2x2 X x × pad2x2 Y y] =>\n          try rewrite (pad2x2_commutes Z X z x dim); \n          try rewrite <- (Mmult_assoc (pad2x2 X x) (pad2x2 Z z) (pad2x2 Y y));\n          try rewrite (pad2x2_commutes Y Z y z dim)\n        | context[pad2x2 Y y × pad2x2 Z z × pad2x2 X x] =>\n          try rewrite (Mmult_assoc (pad2x2 Y y) (pad2x2 Z z) (pad2x2 X x));\n          try rewrite (pad2x2_commutes Z X z x dim);\n          try rewrite <- (Mmult_assoc (pad2x2 Y y) (pad2x2 X x) (pad2x2 Z z));\n          try rewrite (pad2x2_commutes Y X y x dim)\n        end\n      | context[@pad2x2 ?dim ?X ?x × (@pad2x2 ?dim ?Y ?y × @pad2x2 ?dim ?Z ?z)] => \n        rewrite <- (Mmult_assoc (pad2x2 X x) (pad2x2 Y y) (pad2x2 Z z))\n      end\n    end.\n\n\nLemma pad2x2_A_ctrl_commutes : forall dim m n o A B,\n  m <> n ->\n  m <> o ->\n  (m < dim)%nat ->\n  (n < dim)%nat ->\n  (o < dim)%nat ->\n  WF_Matrix A ->\n  WF_Matrix B ->\n  pad2x2_u dim m A × pad2x2_ctrl dim n o B = pad2x2_ctrl dim n o B × pad2x2_u dim m A.\nProof.\n  Opaque embed.\n  intros. unfold pad2x2_u, pad2x2_ctrl, abs_diff. bdestruct_all; simpl; rem_max_min;\n  Msimpl; trivial.\n  + repeat rewrite Mmult_plus_distr_l; repeat rewrite Mmult_plus_distr_r.\n  rewrite le_plus_minus_r by (apply Nat.lt_le_incl; trivial).\n  repeat rewrite embed_mult; simpl.\n  rewrite (embed_commutes dim [(A, m); (∣1⟩⟨1∣, n); (B, o)] [(∣1⟩⟨1∣, n); (B, o); (A, m)]).\n  rewrite (embed_commutes dim [(A, m); (∣0⟩⟨0∣, n); (I 2, o)] [(∣0⟩⟨0∣, n); (I 2, o); (A, m)]).\n  trivial.\n  all : simpl; NoDupity; auto with wf_db. \n  all : rewrite perm_swap; apply perm_skip; apply perm_swap.\n\n  + repeat rewrite Mmult_plus_distr_l; repeat rewrite Mmult_plus_distr_r.\n  rewrite le_plus_minus_r by trivial; repeat rewrite embed_mult; simpl.\n  rewrite (embed_commutes dim [(A, m); (B, o); (∣1⟩⟨1∣, n)] [(B, o); (∣1⟩⟨1∣, n); (A, m)]).\n  rewrite (embed_commutes dim [(A, m); (I 2, o); (∣0⟩⟨0∣, n)] [(I 2, o); (∣0⟩⟨0∣, n); (A, m)]).\n  trivial.\n  all : simpl; NoDupity; auto with wf_db.\n  all : rewrite perm_swap; apply perm_skip; apply perm_swap.\n  Qed.\n\n(** Unitarity *)\n\nLemma pad_unitary : forall n (u : Square (2^n)) start dim,\n    (start + n <= dim)%nat -> \n    WF_Unitary u ->\n    WF_Unitary (pad start dim u).\nProof.\n  intros n u start dim B [WF U].\n  split. apply WF_pad; auto.\n  unfold pad.\n  gridify.\n  Msimpl.\n  rewrite U.\n  reflexivity.\nQed.\n\nLemma pad_u_unitary : forall dim n u,\n    (n < dim)%nat ->\n    WF_Unitary u ->\n    WF_Unitary (pad_u dim n u).\nProof. intros. apply pad_unitary. lia. auto. Qed.  \n\nLemma pad_ctrl_unitary : forall dim m n u,\n    m <> n ->\n    (m < dim)%nat ->\n    (n < dim)%nat ->\n    WF_Unitary u ->\n    WF_Unitary (pad_ctrl dim m n u).\nProof.\n  intros dim m n u NE Lm Ln WFU.\n  unfold pad_ctrl, pad.\n  destruct WFU as [WF U].\n  gridify.\n  - split.\n    + apply WF_plus; auto with wf_db.\n    + Qsimpl.\n      gridify.\n      rewrite U.\n      Qsimpl.\n      repeat rewrite <- kron_plus_distr_r.\n      repeat rewrite <- kron_plus_distr_l.\n      Qsimpl.\n      reflexivity.\n  - split.\n    + apply WF_plus; auto with wf_db.\n    + Msimpl.\n      gridify.\n      rewrite U.\n      Qsimpl.\n      repeat rewrite <- kron_plus_distr_r.\n      repeat rewrite <- kron_plus_distr_l.\n      Qsimpl.\n      reflexivity.\nQed.\n\nLemma pad_swap_unitary : forall dim m n,\n    m <> n ->\n    (m < dim)%nat ->\n    (n < dim)%nat ->\n    WF_Unitary (pad_swap dim m n).\nProof. \n  intros. \n  repeat apply Mmult_unitary;\n    apply pad_ctrl_unitary; auto; apply σx_unitary. \nQed.\n\n(** Lemmas about commutation *)\n\nLemma pad_A_B_commutes : forall dim m n A B,\n  m <> n ->\n  WF_Matrix A ->\n  WF_Matrix B ->\n  pad_u dim m A × pad_u dim n B = pad_u dim n B × pad_u dim m A.\nProof.\n  intros.\n  unfold pad_u, pad.\n  gridify; trivial.\nQed.\n\n(* A bit slow, due to six valid subcases *)\nLemma pad_A_ctrl_commutes : forall dim m n o A B,\n  m <> n ->\n  m <> o ->\n  WF_Matrix A ->\n  WF_Matrix B ->\n  pad_u dim m A × pad_ctrl dim n o B = pad_ctrl dim n o B × pad_u dim m A.\nProof.\n  intros.\n  unfold pad_ctrl, pad_u, pad.\n  gridify; trivial.\nQed.\n\n(* Horribly slow due to many subcases.\n   TODO: can we speed this up be tweaking the ordering in gridify? *)\nLemma pad_ctrl_ctrl_commutes : forall dim m n o p A B,\n  m <> o ->\n  m <> p ->\n  n <> o ->\n  n <> p ->\n  WF_Matrix A ->\n  WF_Matrix B ->\n  pad_ctrl dim m n A × pad_ctrl dim o p B = pad_ctrl dim o p B × pad_ctrl dim m n A.\nProof.\n  intros.\n  unfold pad_ctrl, pad.\n  bdestruct_all.  \n  all : try rewrite Mmult_0_r; try rewrite Mmult_0_l; try easy.\n  all: gridify; trivial.\nQed.\n", "meta": {"author": "inQWIRE", "repo": "QuantumLib", "sha": "d97ea40581961d7b53291a4a3dc7885fe7428060", "save_path": "github-repos/coq/inQWIRE-QuantumLib", "path": "github-repos/coq/inQWIRE-QuantumLib/QuantumLib-d97ea40581961d7b53291a4a3dc7885fe7428060/Pad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.6639932501367677}}
{"text": "(****************************************************************\n \n   ACGT.v\n \n   ...mathink\n \n ****************************************************************)\n \nRequire Import Arith.\nRequire Import List.\n \nSet Implicit Arguments.\n \nNotation \"[ A ]\" := (A::nil).\nNotation \"[ X , .. , Y ]\" := (X:: .. (Y::nil) ..).\n \n \n(*\n   all_cons...\n   \n   a, (l1, l2, ... , ln) ~~> (a::l1, a::l2, ... , a::ln) \n*)\nFixpoint all_cons (A: Set)(a: A)(ll: list (list A)) :=\n  match ll with\n    | h::t => (a::h)::(all_cons a t)\n    | nil => nil\n  end.\n \nLemma all_cons_length:\n  forall (A: Set)(a: A) l ll,\n    In l (all_cons a ll) -> 1 <= length l.\nProof.\n  intros A a l ll.\n  generalize a l; clear a l.\n  elim ll; clear ll.\n  simpl; intros; contradiction.\n  simpl.\n  intros l ll IH a l' [Heq | HIn].\n  subst; simpl; auto with arith.\n  apply IH with a; assumption.\nQed.\n \nLemma all_cons_In_gen:\n  forall (A: Set)(a b: A) l ll,\n    In (a::l) (all_cons b ll) -> a=b/\\In l ll.\nProof.\n  intros A a b l ll.\n  elim ll; clear ll.\n  simpl; intros; contradiction.\n  simpl.\n  intros hl ll IH [Heq | HIn].\n  injection Heq; intros; subst; split;\n    [reflexivity | simpl; left; reflexivity].\n  split.\n  destruct (IH HIn) as [Heq _]; assumption.\n  right; destruct (IH HIn) as [_ H]; assumption.\nQed.\n \n(* 出番がない *)\nLemma all_cons_In:\n  forall (A: Set)(a: A) l ll,\n    In (a::l) (all_cons a ll) -> In l ll.\nProof.\n  intros.\n  destruct (all_cons_In_gen _ _ _ _ H) as [_ HIn].\n  assumption.\nQed.\n(* *)\n \nLemma all_cons_In_inv:\n  forall (A: Set)(a: A) l ll,\n    In l ll -> In (a::l) (all_cons a ll).\nProof.\n  intros A a l ll; elim ll; clear ll.\n  simpl; intros; contradiction.\n  simpl; intros hl ll IH [Heq | HIn].\n  subst; left; reflexivity.\n  right; apply IH; assumption.\nQed.\n \n \n(*\n   DNA_base...\n \n   Adenine Cytosine Guanine Thymine\n*)\nInductive base :=\n| A | C | G | T.\n \nDefinition ACGT := [A,C,G,T].\n \nDefinition base_all_cons (ll: list (list base)) :=\n  (all_cons A ll)++(all_cons C ll)++(all_cons G ll)++(all_cons T ll).\n \nLemma bac_length:\n  forall l ll,\n    In l (base_all_cons ll) -> 1 <= length l.\nProof.\n  unfold base_all_cons.\n  intros l ll HIn.\n  repeat rewrite in_app_iff in HIn.\n  destruct HIn as [HIn | [HIn | [HIn | HIn]]];\n    generalize HIn; clear HIn; apply all_cons_length.\nQed.\n \n \n(*\n   generate...\n   \n   list of (list base) including all n-length list\n   ...generate_correct\n*)\nFixpoint generate (n: nat): list (list base) :=\n  match n with\n    | O => [nil]\n    | 1 => [[A],[C],[G],[T]]\n    | S p => base_all_cons (generate p)\n  end.\n \nEval compute in (generate 2).\nEval compute in (length (generate 2)).\n \nLemma generate_length:\n  forall n l,\n    In l (generate n) -> length l = n.\nProof.\n  intro n; elim n; clear n.\n  simpl.\n  intros l [Heq | F]; [subst; simpl; reflexivity | contradiction].\n  intro n; case n; clear n.\n  intros IH l [Heq | [Heq | [Heq | [Heq | F]]]]; subst; try contradiction;\n    simpl; reflexivity.\n  intros n IH l; case l; clear l.\n  simpl.\n  intro HIn.\n  apply bac_length in HIn.\n  elim (le_Sn_0 _ HIn).\n  intros b l HIn.\n  simpl.\n  apply eq_S; apply IH.\n  simpl in HIn; unfold base_all_cons in HIn.\n  repeat rewrite in_app_iff in HIn.\n  destruct HIn as [HIn | [HIn | [HIn | HIn]]];\n    generalize HIn; clear HIn; case b; clear b;\n      simpl; intro HIn;\n        apply all_cons_In_gen in HIn;\n          destruct HIn as [Heq HIn]; try discriminate;\n            unfold base_all_cons; assumption.\nQed.\n \n \nLemma length_0_nil:\n  forall (A: Set)(l: list A), length l = 0 -> l = nil.\nProof.\n  intros A l; case l; clear l;\n    [reflexivity | intros; discriminate].\nQed.\n \n \nLemma generate_all:\n  forall n l,\n    length l = n -> In l (generate n).\nProof.\n  intro n; elim n; clear n.\n  simpl.\n  intros l Heq; apply length_0_nil in Heq; subst; \n    left; reflexivity.\n  intro n; case n; clear n.\n  intros IH l; case l; clear l.\n  simpl; intros; discriminate.\n  simpl; intro b; case b; clear b;\n    intros l Heq; apply eq_add_S in Heq; apply length_0_nil in Heq; subst;\n      [left | right; left | right; right; left | right; right; right; left]; reflexivity.\n  intros n IH l; case l; clear l.\n  intros; discriminate.\n  intros b l Heq; simpl in Heq.\n  apply eq_add_S in Heq.\n  apply IH in Heq.\n  case b; clear b; simpl; unfold base_all_cons;\n    repeat rewrite in_app_iff;\n      [left | right; left | right; right; left | right; right; right];\n      apply all_cons_In_inv; apply IH; apply generate_length; assumption.\nQed.\n \n \nTheorem generate_correct:\n  forall n l,\n    In l (generate n) <-> length l = n.\nProof.\n  intros n l; split;\n    [apply generate_length | apply generate_all].\nQed.\n  \n \n(*\n   nat_part...\n \n   all partitions of n\n   ...\"nat_part_correct\"\n*)\nFixpoint nat_part_aux (n m: nat) :=\n  match n with\n    | O => [(n, m)]\n    | S p => (n, m)::(nat_part_aux p (S m))\n  end.\n \nEval compute in (nat_part_aux 2 5).\n \nDefinition nat_part (n: nat) := nat_part_aux n 0.\n \nEval compute in (nat_part 5).\n \n \nLemma nat_part_aux_trivial_In:\n  forall n m,\n    In (n, m) (nat_part_aux n m).\nProof.\n  intro n; case n; clear n;\n    simpl; left; reflexivity.\nQed.\n \nLemma nat_part_correct_aux:\n  forall n m p q,\n    n <= p ->\n    n + m = p+q ->\n    In (n, m) (nat_part_aux p q).\nProof.\n  intros n m p q Hle;\n    generalize m q; clear m q.\n  elim Hle; clear Hle p.\n  intros m q Heq.\n  apply plus_reg_l in Heq; subst q.\n  apply nat_part_aux_trivial_In.\n  intros p Hle IH m q Heq.\n  rewrite plus_Snm_nSm in Heq.\n  simpl; right.\n  apply (IH _ _ Heq).\nQed.\n \nLemma plus_le:\n  forall n m p,\n    n + m = p -> n <= p.\nProof.\n  intros n m; generalize n; clear n.\n  case m; clear m;\n    simpl; intros; subst; auto with arith.\nQed.\n \n \nTheorem nat_part_correct:\n  forall n m p,\n    n + m = p -> In (n, m) (nat_part p).\nProof.\n  intros n m p Heq.\n  apply nat_part_correct_aux.\n  apply (plus_le _ _ Heq).\n  rewrite plus_0_r; assumption.\nQed.\n \n \n(*\n   all_tupling...\n \n   (a1, a2, ... , an), (b1, b2, ... bm) ~~>\n   ((a1, b1), (a1, b2), ... , (a1, bm), (a2, b1), ... , (an, bm))\n*)\nFixpoint tupling (A B: Set)(a: A)(l: list B) :=\n  match l with\n    | nil => nil\n    | h::t => (a, h)::(tupling a t)\n  end.\n \nFixpoint all_tupling (A B: Set)(al: list A)(bl: list B) :=\n  match al with\n    | nil => nil\n    | h::t => (tupling h bl)++(all_tupling t bl)\n  end.\n \nEval compute in (all_tupling (1::3::5::7::nil) (2::4::6::nil)).\n \nLemma tupling_In:\n  forall (A B: Set)(a: A)(b: B) l,\n    In b l ->\n    In (a, b) (tupling a l).\nProof.\n  intros A B a b l.\n  generalize A a b;\n    clear A a b.\n  elim l; clear l; simpl.\n  intros; contradiction.\n  intros h l IH A a b [Heq | HIn].\n  subst h; left; reflexivity.\n  right; apply IH; assumption.\nQed.\n \nLemma all_tupling_In:\n  forall (A B: Set)(a: A)(b: B) l1 l2,\n    In a l1 ->\n    In b l2 ->\n    In (a, b) (all_tupling l1 l2).\nProof.\n  intros A B a b l1.\n  generalize B a b; clear B a b.\n  elim l1; clear l1.\n  simpl; intros; contradiction.\n  simpl; intros h1 l1 IH B a b l2 [Heq | HIn1] HIn2.\n  subst h1.\n  apply in_app_iff; left.\n  apply tupling_In; assumption.\n  apply in_app_iff; right; apply IH; assumption.\nQed.\n \n \n(*\n   tuplist_generator_aux...\n \n   all combinations of n-length list and m-length list\n*)\nDefinition tuplist_generator_aux (n m: nat) :=\n  all_tupling (generate n) (generate m).\n \nEval compute in (tuplist_generator_aux 2 2).\n \nLemma tuplist_generator_aux_all:\n  forall n m l1 l2,\n    length l1 = n ->\n    length l2 = m ->\n    In (l1, l2) (tuplist_generator_aux n m).\nProof.\n  intros n m l1 l2 Heq1 Heq2.\n  apply all_tupling_In;\n    apply generate_correct; assumption.\nQed.\n \nCheck pair.\n \n(*\n   tuplist_generator_with_l...\n \n   list of all combinations of ....\n*)\nFixpoint tuplist_generator_with_l (l: list (prod nat nat)) :=\n  match l with\n    | nil => nil\n    | (p, q)::t =>\n      (tuplist_generator_aux p q)++(tuplist_generator_with_l t)\n  end.\n \nLemma tuplist_generator_with_l_correct:\n  forall n m l pl,\n    In (n, m) pl->\n    In l (tuplist_generator_aux n m) ->\n    In l (tuplist_generator_with_l pl).\nProof.\n  intros n m l pl;\n    generalize n m l;\n      clear n m l.\n  elim pl; clear pl.\n  simpl; intros; contradiction.\n  simpl.\n  intros [p q] pl IH n m [l1 l2] [Heq | HIn].\n  injection Heq; intros; subst; clear Heq.\n  apply in_app_iff; left; assumption.\n  intros HIn'; apply in_app_iff;\n    right; eapply IH; eassumption.\nQed.\n \n \nLemma tuplist_generator_correct_aux:\n  forall n m p l l1 l2,\n    length l1 = n ->\n    length l2 = m ->\n    n + m = p ->\n    l = nat_part p ->\n    In (l1, l2) (tuplist_generator_with_l l).\nProof.\n  intros n m p l l1 l2 Heq1 Heq2 Heqp Heql.\n  generalize (tuplist_generator_aux_all _ _ Heq1 Heq2).\n  generalize (nat_part_correct _ _ Heqp).\n  rewrite <- Heql.\n  apply tuplist_generator_with_l_correct.\nQed.\n \n(*\n   tuplist_generator...\n \n   all combinations of p-length list and q-length list, with p + q = n\n*)\nDefinition tuplist_generator (n: nat) := tuplist_generator_with_l (nat_part n).\n \nEval compute in (tuplist_generator 3).\n \n \n(*\n   insert...\n \n   l ___ l1 l2 ~~> l1 \\\\ l // l2\n*)\nDefinition insert (A: Set)(l l1 l2: list A) := l1++l++l2.\n \nFixpoint insert_all (A: Set)(l: list A)(pll: list (list A*list A)) :=\n  match pll with\n    | nil => nil\n    | (p,q)::t => (insert l p q)::(insert_all l t)\n  end.\n \nEval compute in (insert_all ACGT (tuplist_generator 1)).\n \nLemma insert_all_app:\n  forall (A: Set)(l: list A) l1 l2,\n    insert_all l (l1++l2) = (insert_all l l1)++(insert_all l l2).\nProof.\n  intros A l l1; elim l1; clear l1.\n  simpl; reflexivity.\n  intros [p1 p2] l1 IH l2.\n  simpl.\n  rewrite (IH l2); reflexivity.\nQed.\n \nLemma insert_In:\n  forall (A: Set)(l1 l2: list A) pl,\n    In (l1, l2) pl ->\n    forall l,\n      In (l1++l++l2) (insert_all l pl).\nProof.\n  intros A l1 l2 pl;\n    generalize l1 l2;\n      clear l1 l2.\n  elim pl; clear pl.\n  simpl; intros; contradiction.\n  intros [p q] pl IH l1 l2.\n  simpl; intros [Heq | HIn].\n  injection Heq; intros; subst p q.\n  left; trivial.\n  intros; right; apply IH.\n  assumption.\nQed.\n \nLemma insert_tuplist_generator_correct:\n  forall l l1 l2 pl,\n    In (l1, l2) (tuplist_generator_with_l pl) ->\n    In (l1++l++l2) (insert_all l (tuplist_generator_with_l pl)).\nProof.\n  intros l l1 l2 pl;\n    generalize l l1 l2;\n      clear l l1 l2.\n  elim pl; clear pl.\n  simpl; intros; contradiction.\n  intros [p q] pl IH l l1 l2.\n  simpl (In (_,_) _); rewrite in_app_iff.\n  intros [HIn | HIn].\n  simpl.\n  generalize (insert_In _ _ _ HIn l).\n  rewrite insert_all_app.\n  rewrite in_app_iff.\n  left; assumption.\n  simpl.\n  rewrite insert_all_app.\n  rewrite in_app_iff; right.\n  apply IH; assumption.\nQed.\n \n \n(*\n   insert_generator...\n \n   all lists of m-length lists including l (m = n + length l)\n   ...\"insert_generator_correct\"\n*)\nDefinition insert_generator (l: list base)(n: nat) := \n  insert_all l (tuplist_generator n).\n \nEval compute in (insert_generator ACGT 1).\n \nLemma insert_generator_correct_aux:\n  forall n m l l1 l2,\n    length l1 = n ->\n    length l2 = m ->\n    In (l1++l++l2) (insert_generator l (n+m)).\nProof.\n  intros n m l l1 l2 Heq1 Heq2.\n  unfold insert_generator.\n  unfold tuplist_generator.\n  apply insert_tuplist_generator_correct.\n  apply (tuplist_generator_correct_aux _ _ Heq1 Heq2 (eq_refl _) (eq_refl _)).\nQed.\n \n \n(*\n   include...\n*)\nDefinition include (A: Set)(l l': list A) :=\n  exists l1, exists l2, l' = l1++l++l2.\n \nLemma include_length:\n  forall (A: Set)(l l': list A),\n    include l l' ->\n    length l <= length l'.\nProof.\n  intros A l l' [l1 [l2 Heq]]; subst.\n  repeat rewrite app_length.\n  rewrite plus_comm; simpl.\n  auto with arith.\nQed.\n \n \nLemma le_plus:\n  forall n p,\n    n <= p -> exists m, n+m=p.\nProof.\n  intros n p Hle.\n  elim Hle; clear Hle p.\n  exists 0; rewrite plus_0_r; reflexivity.\n  intros p Hle [m Heq]; subst; exists (S m).\n  rewrite <- (plus_Snm_nSm n m); simpl; reflexivity.\nQed.\n \nTheorem insert_generator_correct:\n  forall n l l',\n    include l l' ->\n    length l + n = length l' ->\n    In l' (insert_generator l n).\nProof.\n  intros n l l' Hinc.\n  generalize Hinc;\n    intros [l1 [l2 Heq]];\n      apply include_length in Hinc.\n  apply le_plus in Hinc.\n  subst l'.\n  destruct Hinc as [m Heq].\n  intro Heq'.\n  generalize (eq_trans Heq (eq_sym Heq')).\n  intro Heq''.\n  apply plus_reg_l in Heq''; subst n.\n  clear Heq'.\n  repeat rewrite app_length in Heq.\n  rewrite (plus_comm (length l1) _) in Heq.\n  rewrite <- plus_assoc in Heq.\n  apply plus_reg_l in Heq.\n  rewrite plus_comm in Heq.\n  subst m.\n  eapply insert_generator_correct_aux;\n    reflexivity.\nQed.\n \n \n(*\n   AAG_generator\n*)\nDefinition AAG := [A,A,G].\nDefinition AAG_generator (n: nat) := insert_generator AAG n.\n \nTheorem AAG_generator_correct:\n  forall n l,\n    include AAG l ->\n    3 + n = length l ->\n    In l (AAG_generator n).\nProof.\n  intros.\n  apply insert_generator_correct;\n    simpl; assumption.\nQed.\n \nEval compute in (AAG_generator 2).", "meta": {"author": "tmiya", "repo": "coq", "sha": "6944819890670961f5641e89b853c6639f695251", "save_path": "github-repos/coq/tmiya-coq", "path": "github-repos/coq/tmiya-coq/coq-6944819890670961f5641e89b853c6639f695251/totorial20120216/mathlink.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830605, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6638351600882489}}
{"text": "Require Import Coq.Classes.Morphisms.\nRequire Import RamifyCoq.lib.Relation_ext.\nRequire Import RamifyCoq.lib.Equivalence_ext.\nRequire Export Coq.Lists.List.\n\nLocal Open Scope equiv_scope.\n\nSection ListFun2.\n\nContext {A B: Type}.\nContext {RA: relation A}.\nContext {RB: relation B}.\nContext {EqRA: Equivalence RA}.\nContext {EqRB: Equivalence RB}.\n\nInstance proper_fold_left: forall (f: A -> B -> A) {Proper_f: Proper (equiv ==> equiv ==> equiv) f}, Proper (Forall2 equiv ==> equiv ==> equiv) (fold_left f).\nProof.\n  intros.\n  hnf; intros.\n  induction H; hnf; intros; simpl.\n  + auto.\n  + apply IHForall2.\n    apply Proper_f; auto.\nQed.\n\nLemma monoid_fold_left_tail: forall {f: A -> B -> A} {Proper_f: Proper (equiv ==> equiv ==> equiv) f} (e: A) a l,\n  fold_left f (l ++ a :: nil) e === f (fold_left f l e) a.\nProof.\n  intros.\n  simpl.\n  pose proof (proper_fold_left f).\n  revert e; induction l; intros; simpl.\n  + reflexivity.\n  + apply IHl.\nQed.\n\nEnd ListFun2.\n\nSection ListFun1.\n\nContext {A: Type}.\nContext {RA: relation A}.\nContext {EqRA: Equivalence RA}.\n\nLemma monoid_fold_left_head: forall {f} {Proper_f: Proper (equiv ==> equiv ==> equiv) f} (e: A) a l,\n  (forall x, f e x === x) ->\n  (forall x, f x e === x) ->\n  (forall x y z, f (f x y) z === f x (f y z)) ->\n  fold_left f (a :: l) e === f a (fold_left f l e).\nProof.\n  intros.\n  simpl.\n  pose proof (proper_fold_left f).\n  rewrite H.\n  revert a; induction l; intros; simpl.\n  + symmetry; auto.\n  + rewrite (IHl (f a0 a)), H, (IHl a).\n    rewrite H1.\n    reflexivity.\nQed.\n\nLemma monoid_fold_symm: forall {f} {Proper_f: Proper (equiv ==> equiv ==> equiv) f} (e: A) l,\n  (forall x, f e x === x) ->\n  (forall x, f x e === x) ->\n  (forall x y z, f (f x y) z === f x (f y z)) ->\n  fold_left f l e === fold_right f e l.\nProof.\n  intros.\n  pose proof (proper_fold_left f).\n  destruct l.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite H.\n    revert a; induction l; intros; simpl.\n    - symmetry; auto.\n    - rewrite <- H1.\n      apply IHl.\nQed.\n\nLemma monoid_fold_left_app: forall {f} {Proper_f: Proper (equiv ==> equiv ==> equiv) f} (e: A) l l',\n  (forall x, f e x === x) ->\n  (forall x, f x e === x) ->\n  (forall x y z, f (f x y) z === f x (f y z)) ->\n  fold_left f (l ++ l') e === f (fold_left f l e) (fold_left f l' e).\nProof.\n  intros.\n  rewrite fold_left_app.\n  generalize (fold_left f l e) as a; clear l; intros.\n  pose proof @monoid_fold_left_head f _ e a l'.\n  simpl in H2.\n  pose proof (proper_fold_left f).\n  rewrite H in H2.\n  auto.\nQed.\n  \nEnd ListFun1.\n", "meta": {"author": "johndoe20190406", "repo": "RamifyCoq", "sha": "72fb538b40ee8ea641e4bf5fe6cd232756d0929c", "save_path": "github-repos/coq/johndoe20190406-RamifyCoq", "path": "github-repos/coq/johndoe20190406-RamifyCoq/RamifyCoq-72fb538b40ee8ea641e4bf5fe6cd232756d0929c/lib/List_Func_ext.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.6638351526482776}}
{"text": "\n\nTheorem impl : forall A C, A /\\ C -> C.\nProof.\n  intros. \n  inversion H. \n  auto.\nDefined.\n\nTheorem impl2 : forall F S, F /\\ S -> F.\nProof.\n  intros.\n\n  inversion H.\n    intros.\n  inversion H.\n  exact H1.\nexact H0.\nDefined.\n\nTheorem impl3 : forall (A B:Prop), A -> A \\/ B.\n  intros.\n  left.\n  exact H.\nDefined.\n\nTheorem ggg : forall (A B:Prop), A /\\ B -> B /\\ A.\nProof.\n  intros.  \n  split.\n  inversion H.\n  exact H1.\n \n  inversion H.\n  exact H0.\nDefined.\n\nTheorem \n\n\n", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/Breic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6638328825270671}}
{"text": "Require Import mdp fixed_point pmf_monad FiniteType ListAdd Reals.\nRequire Import Coq.Lists.List LibUtils.\nRequire Import micromega.Lra. (*  qlearn. *)\nRequire Import micromega.Lia. (*  qlearn. *)\nRequire Import ClassicalDescription.\nRequire Import RealAdd LibUtilsListAdd EquivDec.\nRequire Import IndefiniteDescription ClassicalDescription.\n\nImport ListNotations.\nSet Bullet Behavior \"Strict Subproofs\".\n\n\n\nSection bellmanQbar.\nOpen Scope R_scope.\nContext {M : MDP} (γ : R).\nContext (σ : dec_rule M) (init : M.(state)) (hγ : (0 <= γ < 1)%R).\nArguments reward {_}.\nArguments outcomes {_}.\nArguments t {_}.\n\nDefinition act_expt_reward : forall s : M.(state), M.(act) s -> R :=\n  (fun s a => expt_value (t s a) (reward s a)).\n\nDefinition Qvalue : forall s: M.(state), (M.(act) s) -> R :=\n  fun s a => act_expt_reward s a + γ*expt_value (t s a) (ltv γ σ).\n\nLemma Qvalue_expt_value : forall s a,\n    Qvalue s a = expt_value (t s a) (fun s' => reward s a s' + γ*(ltv γ σ s')).\nProof.\n  intros; unfold Qvalue.\n  unfold act_expt_reward.\n  rewrite <-expt_value_const_mul.\n  now rewrite expt_value_add.\nQed.\n\nLemma ltv_Qvalue : ltv γ σ init = Qvalue init (σ init).\nProof.\n  now rewrite ltv_corec.\nQed.\n\nDefinition bellmanQbar : Rfct (sigT M.(act)) -> Rfct (sigT M.(act))\n  := fun W => fun sa => let (s,a) := sa in\n                  act_expt_reward s a +\n                  γ*expt_value (t s a)(fun s' => Max_{act_list s'}(fun a => W (existT _ s' a) ) ).\n\nDefinition bellmanQbar_expt_value : forall s a W,\n    bellmanQbar W (existT _ s a) =\n    expt_value (t s a) (fun s' => reward s a s' + γ*(Max_{act_list s'}(fun a => W (existT _ s' a)))).\nProof.\n  intros; unfold bellmanQbar.\n  unfold act_expt_reward.\n  rewrite <-expt_value_const_mul.\n  now rewrite expt_value_add.\nQed.\n\nLemma Rabs_helper : forall a b c : R, Rabs ( (a + b) + -(a + c)) = Rabs (b - c).\nProof.\n  intros.\n  f_equal. lra.\nQed.\n\nTheorem is_contraction_bellmanQbar :\n  @is_contraction (Rfct_UniformSpace (sigT M.(act))) (Rfct_UniformSpace (sigT M.(act)))\n                  bellmanQbar.\nProof.\n  unfold is_contraction.\n  destruct (Req_EM_T γ 0).\n  ++ unfold bellmanQbar.\n     exists (1/2). split; [lra |].\n     unfold is_Lipschitz. split;trivial;[lra |].\n     destruct (fs M) as [ls ?].\n     intros f g r Hr Hfgr.\n     rewrite e. unfold ball_x,ball_y in *.\n     simpl in *. unfold Rmax_ball,Rmax_norm in *.\n     destruct act_finite as [acts ?].\n     rewrite Rmax_list_lt_iff; intros ;\n       try (apply map_not_nil; apply not_nil_exists ;\n            exists (existT _ (ne M) ((na M) (ne M))); auto).\n     rewrite in_map_iff in H.\n     destruct H.\n     unfold minus,plus,opp in H.\n     destruct x0 as [s a].\n     simpl in H. destruct H as [H1 H2].\n     do 2 rewrite Rmult_0_l in H1.\n     subst.\n     apply Rabs_def1 ; ring_simplify.\n     replace (0) with ((1/2)*0) by lra.\n     apply Rmult_lt_compat_l; trivial; lra.\n     rewrite Ropp_mult_distr_l_reverse.\n     eapply Ropp_lt_gt_0_contravar with (r := (1/2)*r).\n     replace (0) with ((1/2)*0) by lra.\n     apply Rmult_lt_compat_l; trivial; lra.\n  ++ exists γ ; split.\n  - now destruct hγ.\n  - unfold is_Lipschitz.\n    unfold ball_x,ball_y. simpl.\n    destruct (fs M) as [ls Hls].\n    split.\n    -- now destruct hγ.\n    -- intros f g r Hr Hx.\n       repeat red in Hx |-.\n       unfold Rmax_ball, Rmax_norm.\n       destruct (act_finite M) as [la Hla].\n       rewrite Rmax_list_lt_iff; intros; try(apply map_not_nil; apply not_nil_exists).\n       rewrite in_map_iff in H.\n       destruct H as [sa [Q HQ]]; subst.\n       unfold minus, plus, opp. simpl.\n       unfold bellmanQbar; destruct sa. rewrite Rabs_helper.\n       rewrite <-Rmult_minus_distr_l.\n       rewrite Rabs_mult.\n       assert (Hrγ : Rabs γ = γ) by (apply Rabs_pos_eq; lra). rewrite Hrγ.\n       apply Rmult_lt_compat_l; try (destruct hγ; lra).\n       rewrite <-expt_value_sub.\n       eapply Rle_lt_trans; eauto.\n       unfold Rmax_norm.\n       eapply Rle_trans. apply expt_value_Rabs_Rle.\n       apply expt_value_bdd; intro s0.\n       unfold act_list.\n       destruct (M s0).\n       eapply Rle_trans. apply Rmax_list_minus_le_abs.\n       rewrite Rmax_list_le_iff; try (rewrite map_not_nil).\n       intros r'.\n       rewrite in_map_iff; intros.\n       destruct H as [a0 [Ha0 Helms]].\n       subst. apply Rmax_spec.\n       rewrite in_map_iff.\n       exists (existT _ s0 a0); now split.\n       rewrite not_nil_exists.\n       generalize (na _ s0); intros a0; now exists a0.\n       generalize (ne M); intros s0.\n       generalize (na M); intros a0.\n       specialize (a0 s0). now exists (existT _ s0 a0).\nQed.\n\nTheorem isContraction_bellmanQbar_gamma (Hg : 0 < γ) :\n  @is_Lipschitz (Rfct_NormedModule (sigT M.(act))) (Rfct_NormedModule (sigT M.(act)))\n                                      bellmanQbar γ.\n  Proof.\n  unfold is_Lipschitz.\n    unfold ball_x,ball_y. simpl.\n    destruct (fs M) as [ls Hls].\n    split.\n    -- now destruct hγ.\n    -- intros f g r Hr Hx.\n       repeat red in Hx |-.\n       unfold Rmax_ball, Rmax_norm.\n       destruct (act_finite M) as [la Hla].\n       rewrite Rmax_list_lt_iff; intros; try(apply map_not_nil; apply not_nil_exists).\n       rewrite in_map_iff in H.\n       destruct H as [sa [Q HQ]]; subst.\n       unfold minus, plus, opp. simpl.\n       unfold bellmanQbar; destruct sa. rewrite Rabs_helper.\n       rewrite <-Rmult_minus_distr_l.\n       rewrite Rabs_mult.\n       assert (Hrγ : Rabs γ = γ) by (apply Rabs_pos_eq; lra). rewrite Hrγ.\n       apply Rmult_lt_compat_l; try (destruct hγ; lra).\n       rewrite <-expt_value_sub.\n       eapply Rle_lt_trans; eauto.\n       unfold Rmax_norm.\n       eapply Rle_trans. apply expt_value_Rabs_Rle.\n       apply expt_value_bdd; intro s0.\n       unfold act_list.\n       destruct (M s0).\n       eapply Rle_trans. apply Rmax_list_minus_le_abs.\n       rewrite Rmax_list_le_iff; try (rewrite map_not_nil).\n       intros r'.\n       rewrite in_map_iff; intros.\n       destruct H as [a0 [Ha0 Helms]].\n       subst. apply Rmax_spec.\n       rewrite in_map_iff.\n       exists (existT _ s0 a0); now split.\n       rewrite not_nil_exists.\n       generalize (na _ s0); intros a0; now exists a0.\n       generalize (ne M); intros s0.\n       generalize (na M); intros a0.\n       specialize (a0 s0). now exists (existT _ s0 a0).\n  Qed.\n\n\nEnd bellmanQbar.\n\nSection bellmanQ.\nOpen Scope R_scope.\nContext {M : MDP} (γ : R).\nContext (σ : dec_rule M) (init : M.(state)) (hγ : (0 <= γ < 1)%R).\nArguments reward {_}.\nArguments outcomes {_}.\nArguments t {_}.\n\n\nDefinition fun_inner_prod {A : Type} (f g : A -> R) (ls : list A) : R :=\n  (list_sum (map (fun a => (f a)*(g a)) ls)).\n\nLemma fun_inner_prod_self {A : Type} (l : list A) (f : A -> R) :\n  fun_inner_prod f f l = list_sum (map (fun a => Rsqr (f a)) l).\nProof.\n  unfold fun_inner_prod.\n  now apply list_sum_map_ext.\nQed.\n\nDefinition Rfct_inner {A : Type} (finA : FiniteType A) (f g : Rfct A) : R :=\n  let (ls, _) := finA in fun_inner_prod f g ls.\n\n\nLemma Rfct_expt_inner {A B : Type} (finA : FiniteType A)\n      (f : B -> Rfct A) (p : Pmf B):\n  let (la, _) := finA in\n  expt_value p (fun b => Rfct_inner _ (f b) (f b)) =\n  list_sum (List.map (fun a => expt_value p (fun b => (f b a)*(f b a))) la).\nProof.\n  unfold Rfct_inner.\n  destruct finA.\n  destruct p as [lp Hlp]. unfold expt_value.\n  simpl. clear Hlp.\n  revert lp.\n  induction lp.\n  + simpl. symmetry.\n    apply list_sum_map_zero.\n  + simpl. rewrite IHlp.\n    rewrite list_sum_map_add.\n    f_equal. rewrite Rmult_comm.\n    unfold fun_inner_prod.\n    rewrite <-list_sum_const_mul.\n    f_equal. apply List.map_ext; intros.\n    lra.\nQed.\n\n\nDefinition bellmanQ : Rfct(sigT M.(act)) -> M.(state) -> Rfct(sigT M.(act))\n  := fun W => fun s' sa => let (s,a) := sa in\n                  reward s a s' + γ*Max_{act_list s'}(fun a => W (existT _ s' a)).\n\n(* Move this to somewhere nice.*)\nLemma expt_value_le_max {A : Type} (finA : FiniteType A) (p : Pmf A) (f : A -> R):\n  let (la,_) := finA in\n  expt_value p f <= Max_{la}(f).\nProof.\n  destruct finA.\n  apply expt_value_bdd.\n  intros. apply Rmax_spec.\n  rewrite List.in_map_iff.\n  exists a. split; auto.\nQed.\n\nLemma Rmax_list_Rsqr_Rabs_1 {A : Type} (f : A -> R) (l : list A):\n[] <> l -> Max_{l}(fun a => Rsqr (f a)) <= Max_{l}(fun a => Rsqr (Rabs (f a))).\nProof.\n  intros Hn.\n  apply Rmax_spec.\n  rewrite in_map_iff.\n  destruct (Rmax_list_map_exist (fun a => Rsqr (f a)) l Hn) as [a [Ha1 Ha2]].\n  exists a.  rewrite <-Rsqr_abs.\n  split; trivial.\nQed.\n\nLemma Rmax_list_Rsqr_Rabs_2 {A : Type} (f : A -> R) (l : list A):\n  [] <> l -> Max_{l}(fun a => Rsqr (Rabs (f a))) <= Rsqr(Max_{l}(fun a => Rabs(f a))).\nProof.\n  intros Hn.\n  destruct (Rmax_list_map_exist (fun a => Rsqr (Rabs (f a))) l Hn) as [a [Ha1 Ha2]].\n  rewrite <-Ha2.\n  apply neg_pos_Rsqr_le; try (apply Rmax_spec ; rewrite in_map_iff ; exists a; split; trivial).\n  replace (Rabs (f a)) with (- (- (Rabs (f a)))) by lra.\n  apply Ropp_le_contravar.\n  transitivity (Rabs (f a)) ; try (apply Rmax_spec ; rewrite in_map_iff ; exists a; split; trivial).\n  rewrite Rminus_le_0.\n  ring_simplify.\n  apply Rmult_le_pos; try (left; apply Rlt_0_2).\n  apply Rabs_pos.\nQed.\n\nLemma Rmax_list_Rsqr_Rabs_3 {A : Type} (f g : A -> R) (l : list A):\n  [] <> l -> (Max_{l}(fun a => Rabs (f a + g a)))² <=\n           (Max_{l}(fun a => Rabs(f a)) + Max_{l}(fun a => Rabs (g a)))².\nProof.\n  intros Hn.\n  apply Rsqr_incr_1; try (apply Rmax_list_map_nonneg).\n  + apply Rmax_list_map_triangle.\n  + intros a.\n    apply Rabs_pos.\n  + replace 0 with (0+0) by lra.\n    apply Rplus_le_compat; apply Rmax_list_map_nonneg; intros; apply Rabs_pos.\nQed.\n\nLemma minus_Rsqr_le (a b : R):\n  a - b² <= a.\nProof.\n  rewrite <-Rminus_0_r.\n  unfold Rminus. apply Rplus_le_compat_l.\n  apply Ropp_le_contravar.\n  rewrite Rsqr_pow2. apply pow2_ge_0.\nQed.\n\n\nDefinition summand_bound W := fun (s : M.(state)) a => let (ls,_) := fs M in\n                      (Max_{ ls}(fun a0 : state M => Rabs ((fun _ : state M => act_expt_reward s a) a0)) +\n     (Max_{ ls} (fun a0 : state M => Rabs ((fun a1 : state M => γ * (Max_{ act_list a1}(fun a2 : act M a1 => W (existT (act M) a1 a2)))) a0))))².\n\n(* Proves that each individual summand is bounded. *)\nLemma summand_bounded W :\n  forall (s : M.(state)) (a: M.(act) s),\n    let (ls,_) := fs M in\n    variance (t s a) (fun s' => act_expt_reward s a + γ*Max_{act_list s'} (fun a => W (existT _ s' a)))\n             <= summand_bound W s a.\nProof.\n  intros s a.\n  unfold summand_bound.\n  generalize (expt_value_le_max (fs M) (t s a)); intros.\n  destruct (fs M) as [ls ?].\n  assert (Hls: [] <> ls) by (apply not_nil_exists; exists (ne M); trivial).\n  eapply Rle_trans; try apply variance_le_expt_value_sqr.\n  eapply Rle_trans; try eapply H.\n  eapply Rle_trans; try (eapply (Rmax_list_Rsqr_Rabs_1) ; trivial).\n  eapply Rle_trans; try (eapply (Rmax_list_Rsqr_Rabs_2) ; trivial).\n  eapply Rle_trans; try (eapply (Rmax_list_Rsqr_Rabs_3) ; trivial).\n  right; trivial.\nQed.\n\n  Lemma Rmax_list_map_add {A} (f g : A -> R) (l : list A):\n    Max_{ l}(fun a : A => (f a + g a)) <=\n    Max_{ l}(fun a : A => (f a)) + (Max_{ l}(fun a : A => (g a))).\n  Proof.\n    destruct (is_nil_dec l).\n    - subst; simpl. lra.\n    - rewrite Rmax_list_le_iff.\n      intros x Hx. rewrite in_map_iff in Hx.\n      destruct Hx as [a [Ha Hina]].\n      rewrite <-Ha.\n      apply Rplus_le_compat; try (apply Rmax_spec; rewrite in_map_iff; exists a; split ; trivial).\n      rewrite map_not_nil.\n      congruence.\n  Qed.\n\n  Lemma Rmax_list_map_indep {A} (l : list A) (c : R):\n    Max_{l}(fun _ => c) = if is_nil_dec l then 0 else c.\n  Proof.\n    destruct (is_nil_dec l); try now subst.\n    apply Rle_antisym.\n    + rewrite Rmax_list_le_iff; try rewrite map_not_nil; try easy.\n      intros x Hx. rewrite in_map_iff in Hx.\n      destruct Hx as [x0 [Hx0 Hx0']].\n      now subst. congruence.\n    + apply Rmax_spec.\n      rewrite in_map_iff.\n      rewrite BasicUtils.ne_symm in n.\n      rewrite not_nil_exists in n.\n      destruct n as [x Hx].\n      exists x; easy.\n  Qed.\n\n\nLemma Rmax_list_const_add' {A}(l : list A) (f : A -> R) (d : R) :\n    Rmax_list (List.map (fun x => f x + d) l) =\n    if (is_nil_dec l) then 0 else ((Rmax_list (map f l)) + d).\nProof.\n  destruct (is_nil_dec l); subst; try easy.\n  induction l.\n    - simpl; intuition reflexivity.\n    - simpl in *.\n      destruct l.\n      + simpl ; reflexivity.\n      + simpl in * ; rewrite IHl.\n        now rewrite Rcomplements.Rplus_max_distr_r.\n        rewrite BasicUtils.ne_symm. rewrite not_nil_exists.\n        exists a0; simpl. now left.\n  Qed.\n\nLemma Q_is_bounded W :\n    let (ls, _) := fs M in\n    let (las,_) := act_finite M in\n    Max_{ls}(fun s' => Max_{las}(bellmanQ W s')) <= Max_{ ls}\n  (fun s' : state M =>\n   Max_{ las}(fun sa : {x : state M & act M x} => let (s, a) := sa in reward s a s')) + γ*Max_{las}(W).\nProof.\n  destruct (fs M) as [states ?].\n  destruct (act_finite M) as [stacts ?].\n  unfold bellmanQ.\n  assert (G1 : [] <> states) by (rewrite not_nil_exists; now exists (@ne M)).\n  assert (H0 : [] <> stacts) by (rewrite not_nil_exists; now exists (existT _ (@ne M) (@na M (@ne M)))).\n  assert (G2 : forall s : M.(state), [] <> act_list s) by (intros s; apply act_list_not_nil).\n  assert (H1 : Max_{states} (fun s' =>\n              Max_{stacts}(fun sa : {x : state M & act M x} => let (s,a):= sa in\n                           reward s a s' + γ*(Max_{ act_list s' }(fun a => W(existT _ s' a))))) <=\n               Max_{states} (fun s' => Max_{stacts}(fun sa : {x : state M & act M x} =>\n                                                   let (s,a):= sa in reward s a s'))\n              +  γ*( Max_{states}(fun s' => Max_{stacts}(fun sa => Max_{ act_list s' }(fun a => W(existT _ s' a)))))).\n  {\n    setoid_rewrite <-Rmax_list_map_const_mul; try lra.\n    eapply Rle_trans.\n    2: apply Rmax_list_map_add. simpl.\n    apply Rmax_list_fun_le; intros s.\n    setoid_rewrite Rmax_list_map_indep; trivial.\n    destruct (is_nil_dec stacts); try subst. intuition.\n    generalize  (γ *(Max_{ act_list s}\n                         (fun a0 : act M s => W (existT (act M) s a0)))); intros.\n    generalize (Rmax_list_map_add (fun sa : {x : state M & act M x} => let (s0, a) := sa in reward s0 a s) (fun _ => r) stacts); intros.\n    rewrite (Rmax_list_map_indep) with (c := r) in H; trivial.\n    match_destr_in H; simpl. intuition.\n    eapply Rle_trans. 2: apply H.\n    right. apply Rmax_list_map_ext.\n    intros a.\n    now destruct a.\n  }\n  eapply Rle_trans; eauto. clear H1.\n  apply Rplus_le_compat.\n  + now right.\n  + apply Rmult_le_compat_l; try lra.\n    setoid_rewrite Rmax_list_map_indep.\n    match_destr; subst. intuition.\n    apply Rmax_spec. rewrite in_map_iff.\n    generalize (Rmax_list_map_exist (fun s' => Max_{ act_list s'}(fun a => W (existT _ s' a))) _ G1); intros.\n    destruct H as [s0 [Hs0 Heq1]].\n    generalize (Rmax_list_map_exist (fun a => W (existT _ s0 a)) _ (G2 s0)); intros.\n    destruct H as [a [Ha1 Heq2]].\n    exists (existT _ s0 a).\n    rewrite <-Heq1. rewrite Heq2.\n    split; trivial.\nQed.\n\nLocal Instance EqDecsigT : EqDec (sigT M.(act)) eq.\nProof.\n  intros x y.\n  apply ClassicalDescription.excluded_middle_informative.\nQed.\n\nDefinition bellmanQ' (sa0 : sigT M.(act)) : Rfct(sigT M.(act)) -> M.(state) -> Rfct(sigT M.(act))\n  := fun W => fun s' sa => if (sa == sa0) then\n                       let (s,a) := sa in\n                       reward s a s' + γ*Max_{act_list s'}(fun a => W (existT _ s' a))\n                       else W sa.\n\nDefinition bellmanQbar' (sa0 : sigT M.(act)) : Rfct (sigT M.(act)) -> Rfct (sigT M.(act))\n  := fun W => fun sa => if (sa == sa0) then\n                  let (s,a) := sa in\n                  act_expt_reward s a +\n                  γ*expt_value (t s a)(fun s' => Max_{act_list s'}(fun a => W (existT _ s' a)))\n                  else let (s,a) := sa in W (existT _ s a).\n\n(* This is w. *)\nDefinition stochasticBellmanQ' (sa0 : sigT M.(act)) :=\n  fun W => fun s' sa => (bellmanQ' sa0 W s' sa - bellmanQbar' sa0 W sa).\n\n(* Lemma 12 *)\nTheorem expt_value_stochasticBellmanQ' W :\n  forall (sa sa0 : sigT M.(act)),\n    let (s,a) := sa in\n    expt_value (t s a) (fun s' => stochasticBellmanQ' sa0 W s' sa) = 0.\nProof.\n  intros.\n  destruct sa.\n  unfold stochasticBellmanQ'.\n  rewrite expt_value_sub.\n  rewrite expt_value_const.\n  unfold bellmanQbar', bellmanQ'.\n  match_destr.\n  + rewrite expt_value_add.\n    rewrite expt_value_const_mul. unfold act_expt_reward. lra.\n  + rewrite expt_value_const; lra.\nQed.\n\n\n Theorem expt_value_bellmanQbar sa0 W :\n   forall sa : sigT M.(act), let (s,a) := sa in\n                        expt_value (t s a) (fun a0 : state M => bellmanQ' sa0 W a0 (existT (act M) s a)) =\n                        (bellmanQbar' sa0 W (existT (act M) s a)).\n Proof.\n   intros [s a].\n   unfold bellmanQbar'.\n   unfold bellmanQ'.\n   match_destr.\n   + now rewrite expt_value_add, expt_value_const_mul.\n   + now rewrite expt_value_const.\n Qed.\n\nTheorem expt_value_rsqr_stochasticBellmanQ' W :\n  forall (sa sa0 : sigT M.(act)),\n    let (s,a) := sa in\n    expt_value (t s a) (fun s' => (stochasticBellmanQ' sa0 W s' sa)²) =\n    expt_value (t s a) (fun s' => (bellmanQ' sa0 W s' sa)²) - (bellmanQbar' sa0 W sa)².\nProof.\n  intros [s a] sa0.\n  unfold stochasticBellmanQ'.\n  setoid_rewrite Rsqr_minus.\n  rewrite expt_value_sub.\n  rewrite expt_value_add.\n  rewrite expt_value_const.\n  setoid_rewrite Rmult_assoc.\n  rewrite expt_value_const_mul.\n  setoid_rewrite Rmult_comm at 4.\n  rewrite expt_value_const_mul.\n  rewrite (expt_value_bellmanQbar sa0 W (existT _ s a)).\n  rewrite <-Rmult_assoc. unfold Rsqr. ring.\nQed.\n\nLemma Rmax_list_const {A : Type} (r : R) (l : list A):\n  [] <> l -> Max_{l}(fun _ => r) = r.\nProof.\n  intros Hl.\n  symmetry.\n  apply Rle_antisym.\n  + apply Rmax_spec.\n    rewrite in_map_iff.\n    rewrite not_nil_exists in Hl.\n    destruct Hl as [a Ha].\n    exists a. split; trivial.\n  + rewrite Rmax_list_le_iff.\n    -- intros a Ha.\n       rewrite in_map_iff in Ha.\n       destruct Ha as [b [? ?]].\n       subst; lra.\n    -- now rewrite map_not_nil.\nQed.\n\nLemma Rmax_list_Rabs_pos {A : Type} (l : list A) (f : A -> R) :\n  0 <= Max_{l} (fun a => Rabs (f a)).\nProof.\n  destruct (is_nil_dec l); try subst.\n  + now simpl.\n  + rewrite BasicUtils.ne_symm in n.\n    generalize (Rmax_list_map_exist (fun a => Rabs(f a)) l n).\n    intros [a [Ha1 Ha2]].\n    rewrite <-Ha2.\n    apply Rabs_pos.\nQed.\n\nLemma Rplus_le_compat_Rsqr {a b c d : R} (hab : 0 <= a <= c) (hbd : 0 <= b <= d) :\n  (a + b)² <= (c + d)².\nProof.\n  do 2 rewrite Rsqr_plus.\n  apply Rplus_le_compat.\n  apply Rplus_le_compat.\n  + apply Rsqr_le_abs_1.\n    rewrite Rabs_right; try rewrite Rabs_right; try intuition lra.\n  + apply Rsqr_le_abs_1.\n    rewrite Rabs_right; try rewrite Rabs_right; try intuition lra.\n  + apply Rmult_le_compat; try intuition lra.\nQed.\n\n(* Move this somewhere else. *)\nLemma Rmax_list_map_dep_prod {A : Type} {B : A -> Type} (la : list A) (lb : forall a, list (B a))\n      (Hb : forall a, [] <> lb a) (f : forall x :A, B x -> R):\n         Max_{ la}(fun a => Max_{lb a} (fun b => f a b)) =\n         Max_{list_dep_prod la lb}(fun ab : {x : A & B x} => let (a,b) := ab in f a b).\n Proof.\n   destruct (is_nil_dec la); subst; try simpl; try easy.\n   assert (Ha : [] <> la) by congruence. clear n.\n   apply Rle_antisym.\n    ++  rewrite Rmax_list_le_iff.\n    -- intros x Hx. eapply (@Rmax_list_ge _ _ x).\n       ** rewrite in_map_iff in *.\n          destruct Hx as [a [Hx' HInx']].\n          set (Hmax := Rmax_list_map_exist (fun b : B a=> f a b) (lb a) (Hb a)).\n          destruct Hmax as [b [Hb1 Hb2]].\n          exists (existT _ a b). simpl. split; [now rewrite <-Hx' |].\n          apply in_dep_prod; trivial.\n       ** now right.\n    -- now rewrite map_not_nil.\n       ++ rewrite Rmax_list_le_iff.\n    * intros x Hx.\n      rewrite in_map_iff in Hx.\n      destruct Hx as [ab [Hab1 HInab1]].\n      eapply Rmax_list_ge.\n      --- rewrite in_map_iff.\n          exists (projT1 ab). split ; trivial.\n          destruct ab; simpl.\n          setoid_rewrite in_dep_prod_iff in HInab1.\n          destruct HInab1 ; trivial.\n      --- eapply (Rmax_list_ge _ _ (f (projT1 ab) (projT2 ab))).\n          +++ rewrite in_map_iff. exists (projT2 ab). split ; trivial.\n              destruct ab as [a b]; simpl.\n              rewrite in_dep_prod_iff in HInab1.\n              destruct HInab1 ; trivial.\n          +++ rewrite <-Hab1; destruct ab; simpl. right ; trivial.\n    * rewrite map_not_nil.\n      rewrite not_nil_exists in Ha.\n      destruct Ha as [a H]. specialize (Hb a).\n      rewrite not_nil_exists in Hb.\n      destruct Hb as [b Hb].\n      rewrite not_nil_exists.\n      exists (existT _ a b). rewrite in_dep_prod_iff; split; trivial.\n Qed.\n\n\n(* Lemma 13. *)\nTheorem noise_variance_bound' (sa0 : sigT M.(act)) W :\n  forall sa : sigT M.(act), let (s,a) := sa in\n                       let (ls,_) := fs M in\n                       variance (t s a) (fun s' => stochasticBellmanQ' sa0 W s' sa) <=\n                       (Max_{ls}(fun s' => Max_{ls}(fun s => Max_{act_list s}( fun a => Rabs (reward s a s')))) +\n                        γ*(Max_{ ls} (fun a0 : state M => Rabs (Max_{ act_list a0}(fun a1 : act M a0 => W (existT (act M) a0 a1))))))².\nProof.\n  intros [s a].\n  assert (Ha : forall s : M.(state), [] <> act_list s) by (intros s0; apply act_list_not_nil).\n  generalize (expt_value_le_max (fs M) (t s a)); intros.\n  destruct (fs M) as [ls ?].\n  assert (Hls: [] <> ls) by (apply not_nil_exists; exists (ne M); trivial).\n  assert (Hγ1 : Rabs (γ) = γ) by (apply Rabs_pos_eq; lra).\n  assert (Hγ2 : 0 <= Rabs γ) by (apply Rabs_pos).\n  destruct (existT _ s a == sa0).\n  rewrite variance_eq.\n  rewrite (expt_value_rsqr_stochasticBellmanQ' W (existT _ s a) sa0).\n  unfold stochasticBellmanQ'. rewrite expt_value_sub.\n  rewrite expt_value_const. rewrite Rsqr_minus at 1.\n  rewrite (expt_value_bellmanQbar sa0 W (existT _ s a)).\n  rewrite Rsqr_pow2. ring_simplify.\n  rewrite <-Rsqr_pow2.\n  eapply Rle_trans; try apply minus_Rsqr_le.\n  eapply Rle_trans; try apply H.\n  eapply Rle_trans; try (eapply (Rmax_list_Rsqr_Rabs_1) ; trivial).\n  eapply Rle_trans; try (eapply (Rmax_list_Rsqr_Rabs_2) ; trivial).\n  unfold bellmanQ'; match_destr.\n  + eapply Rle_trans; try (eapply (Rmax_list_Rsqr_Rabs_3) ; trivial).\n    apply Rplus_le_compat_Rsqr.\n    -- split; [apply Rmax_list_Rabs_pos|].\n       apply Rmax_list_fun_le; intros s'.\n       unfold act_list.\n       rewrite Rmax_list_map_dep_prod.\n       +++  apply Rmax_spec; rewrite in_map_iff.\n            exists (existT _ s a). split; trivial.\n            rewrite in_dep_prod_iff; split; trivial.\n            apply fa.\n       +++ intros. apply act_list_not_nil.\n    -- split; [apply Rmax_list_Rabs_pos|].\n       setoid_rewrite Rabs_mult.\n       rewrite Hγ1. rewrite Rmax_list_map_const_mul; lra.\n  + intuition.\n  + rewrite variance_eq.\n    unfold stochasticBellmanQ', bellmanQ', bellmanQbar'.\n    match_destr. intuition.\n    do 2 rewrite expt_value_const.\n    rewrite Rminus_eq_0.\n    rewrite Rsqr_pow2. apply pow2_ge_0.\nQed.\n\nTheorem noise_total_variance_bound (sa0 : sigT M.(act)) W : exists c : R,\n  let (lsa,_) := act_finite M in\n  list_sum (map (fun sa : {x : state M & _}  => let (s,a) := sa in\n                variance (t s a) (fun s' => stochasticBellmanQ' sa0 W s' sa)) lsa)\n  <= c.\nProof.\n  generalize (noise_variance_bound' sa0 W); intros Hnvb.\n  destruct (fs M) as [ls ?].\n  destruct (act_finite M) as [lsa ?].\n  exists (list_sum (map (fun _ => (Max_{ls}(fun s' => Max_{ls}(fun s => Max_{act_list s}( fun a => Rabs (reward s a s')))) +\n                        γ*(Max_{ ls} (fun a0 : state M => Rabs (Max_{ act_list a0}(fun a1 : act M a0 => W (existT (act M) a0 a1))))))²) lsa)).\n  apply list_sum_le; intros sa.\n  specialize (Hnvb sa).\n  destruct sa as [s a].\n  apply Hnvb.\nQed.\n\n\nTheorem stochasticBellmanQ'_false W :\n  forall (sa sa0 : sigT M.(act)), (sa =/= sa0) -> (forall s', stochasticBellmanQ' sa0 W s' sa = 0).\nProof.\n  intros.\n  unfold stochasticBellmanQ', bellmanQbar'.\n  match_destr. intuition.\n  unfold bellmanQ'.\n  match_destr. intuition.\n  destruct sa; lra.\nQed.\n\nLemma list_sum_split_ind {A : Type} {eq : EqDec A eq} (l : list A) (a0 : A)\n  (f : A -> R):\n  list_sum (map (fun a => if (a == a0) then f a else 0) l) =\n  f a0 * list_sum (map (fun a => if (a == a0) then 1 else 0) l).\nProof.\n  induction l.\n  + simpl. lra.\n  + simpl. match_destr.\n    rewrite Rmult_plus_distr_l.\n    rewrite IHl. rewrite Rmult_1_r.\n    rewrite e. reflexivity.\n    rewrite IHl. lra.\nQed.\n\nLemma list_sum_split {A : Type} {eq : EqDec A eq} (l : list A) (a0 : A)\n  (f : A -> R):\n  list_sum (map f l) = list_sum (map (fun a => if (a == a0) then f a0 else 0) l) +\n                       list_sum (map (fun a => if (a <> a0) then f a else 0) l).\nProof.\n  induction l.\n  + simpl. lra.\n  + simpl. match_destr; case (a <> a0); intros; try intuition; try lra.\n    rewrite IHl. rewrite e; lra.\nQed.\n\nLemma list_sum_ind_count_occ {A : Type} {eq : EqDec A eq}(l : list A)(a0 : A):\n  list_sum (map (fun a => if (a == a0) then 1 else 0) l) =\n  INR (count_occ eq l a0).\nProof.\n  induction l; try now simpl.\n  simpl; match_destr.\n  + match_destr.\n    -- rewrite IHl.\n       rewrite S_INR; lra.\n    -- intuition.\n  + match_destr.\n    -- intuition.\n    -- rewrite Rplus_0_l.\n       assumption.\nQed.\n\nTheorem total_variance_stochasticBellmanQ' (sa0 : sigT M.(act)) W :\n  let (lsa,_) := act_finite M in\n  let lsa_nodup := nodup EqDecsigT lsa in\n  list_sum (map (fun sa : {x : M.(state) & _} => let (s,a) := sa in\n                                              variance (t s a) (fun s' => stochasticBellmanQ' sa0 W s' sa)) lsa_nodup) =\n  let (s0,a0) := sa0 in\nvariance (t s0 a0) (fun s' => stochasticBellmanQ' (existT _ s0 a0) W s' (existT _ s0 a0)).\nProof.\n  destruct (act_finite M) as [lsa ?].\n  intros lsa_nodup.\n  rewrite list_sum_split with (a0 := sa0).\n  rewrite <-Rplus_0_r.\n  f_equal.\n  + destruct sa0 as [s0 a0].\n    rewrite list_sum_split_ind.\n    rewrite <-Rmult_1_r. f_equal.\n    rewrite list_sum_ind_count_occ.\n    replace 1 with (INR 1) by reflexivity.\n    f_equal.\n    generalize (nodup_In EqDecsigT lsa); intros.\n    assert (Hf : forall x, In x (nodup EqDecsigT lsa)).\n    {\n      intros x. rewrite H. apply fin_finite.\n    }\n    revert Hf.\n    generalize (NoDup_count_occ' EqDecsigT lsa_nodup); intros.\n    assert (Hnd : NoDup lsa_nodup) by (apply NoDup_nodup).\n    rewrite H0 in Hnd. apply Hnd.\n    unfold lsa_nodup.\n    rewrite nodup_In. apply fin_finite.\n  + apply list_sum0_is0.\n    rewrite Forall_map.\n    rewrite Forall_forall; intros sa Hsa.\n    match_destr.\n    generalize (stochasticBellmanQ'_false W sa sa0 c); intros Hz.\n    destruct sa as [s a].\n    unfold variance. setoid_rewrite Hz.\n    setoid_rewrite expt_value_zero.\n    setoid_rewrite Rminus_eq_0.\n    setoid_rewrite Rsqr_0. apply expt_value_zero.\nQed.\n\n(* Move these.*)\nLtac solve_exists_in :=\n  match goal with\n  | [a : ?A, fin : forall x : ?A, In x ?ls |- exists a : ?A, In a ?ls] => exists a; try (apply fin)\n  end.\n\nLtac rmax_compare :=\n  match goal with\n    | [ |- Rmax_list _ <= _] => rewrite Rmax_list_le_iff;\n                    [intros ?x [?s [<-?Hs]] %in_map_iff |\n                     rewrite map_not_nil, not_nil_exists; solve_exists_in]\n    | [ |- _ <= Rmax_list _ ] =>  apply Rmax_spec; rewrite in_map_iff; try solve_exists_in\n  end.\n\n\nLemma Q_is_bounded' W sa0 :\n    let (ls, _) := fs M in\n    let (las,_) := act_finite M in\n    Max_{ls} (fun s' => Max_{las}(fun sa => bellmanQ' sa0 W s' sa)) <=\n    Rmax(Max_{ ls}\n  (fun s' : state M =>\n     Max_{ las}(fun sa : {x : state M & act M x} => let (s, a) := sa in reward s a s')) +\n    γ*Max_{las}(W)) (Max_{las}(W)).\nProof.\n  destruct act_finite as [lsa ?].\n  destruct fs as [ls ?].\n  rmax_compare.\n  rmax_compare.\n  unfold bellmanQ'.\n  match_destr.\n  + rewrite e.\n    destruct sa0 as [s1 a1].\n    rewrite Rmax_Rle. left.\n    apply Rplus_le_compat.\n    -- rewrite Rmax_list_map_dep_prod.\n       rmax_compare. exists (existT _ s (existT _ s1 a1)).\n       split; [trivial | intuition].\n       apply in_dep_prod; trivial.\n       intros. rewrite not_nil_exists.\n       now exists s0.\n    -- apply Rmult_le_compat_l; try intuition lra.\n       rmax_compare.\n       generalize (Rmax_list_map_exist (fun a => W (existT _ s a)) (act_list s) (act_list_not_nil s)); intros [a [Ha1 Ha2]].\n       exists (existT _ s a). split; trivial.\n  + rewrite Rmax_Rle. right.\n    rmax_compare. exists s0.\n    split; trivial.\nQed.\n\nEnd bellmanQ.\n", "meta": {"author": "IBM", "repo": "FormalML", "sha": "e399d096f1ad572420dbd1c638d593eee2129cbe", "save_path": "github-repos/coq/IBM-FormalML", "path": "github-repos/coq/IBM-FormalML/FormalML-e399d096f1ad572420dbd1c638d593eee2129cbe/coq/CertRL/qvalues.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.900529778109184, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6638328714233818}}
{"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(*                                podefs_1.v                                *)\n(****************************************************************************)\n\nRequire Import Ensembles.\nRequire Import Relations_1.\nRequire Import podefs.\n\nSection Bounds.\n   Variable U : Type.\n   Variable D : PO U.\n   \n   Let C := Carrier_of U D.\n   \n   Let R := Rel_of U D.\n   \n   Inductive Totally_ordered (B : Ensemble U) : Prop :=\n       Totally_ordered_definition :\n         (Included U B C ->\n          forall x y : U, Included U (Couple U x y) B -> R x y \\/ R y x) ->\n         Totally_ordered B.\n   \n   Inductive Upper_Bound (B : Ensemble U) (x : U) : Prop :=\n       Upper_Bound_definition :\n         In U C x -> (forall y : U, In U B y -> R y x) -> Upper_Bound B x.\n   \n   Inductive Lower_Bound (B : Ensemble U) (x : U) : Prop :=\n       Lower_Bound_definition :\n         In U C x -> (forall y : U, In U B y -> R x y) -> Lower_Bound B x.\n   \n   Inductive Lub (B : Ensemble U) (x : U) : Prop :=\n       Lub_definition :\n         Upper_Bound B x ->\n         (forall y : U, Upper_Bound B y -> R x y) -> Lub B x.\n   \n   Inductive Glb (B : Ensemble U) (x : U) : Prop :=\n       Glb_definition :\n         Lower_Bound B x ->\n         (forall y : U, Lower_Bound B y -> R y x) -> Glb B x.\n   \n   Inductive Bottom (bot : U) : Prop :=\n       Bottom_definition :\n         In U C bot -> (forall y : U, In U C y -> R bot y) -> Bottom bot.\n   \n   Definition Compatible (x y : U) : Prop :=\n     exists z : U,\n       In U C x -> In U C y -> In U C z /\\ Upper_Bound (Couple U x y) z.\n   \n   Inductive Directed (X : Ensemble U) : Prop :=\n       Definition_of_Directed :\n         Included U X C ->\n         Non_empty U X ->\n         (forall x1 x2 : U,\n          Included U (Couple U x1 x2) X ->\n          exists x3 : U, In U X x3 /\\ Upper_Bound (Couple U x1 x2) x3) ->\n         Directed X.\n   \n   Inductive Complete : Prop :=\n       Definition_of_Complete :\n         (exists bot : U, Bottom bot) ->\n         (forall X : Ensemble U, Directed X -> exists bsup : U, Lub X bsup) ->\n         Complete.\n   \n   Definition Cpo : Prop := Complete.\n   \n   Definition Chain : Prop := Totally_ordered C.\n   \n   Inductive Conditionally_complete : Prop :=\n       Definition_of_Conditionally_complete :\n         (forall X : Ensemble U,\n          Included U X C ->\n          (exists maj : U, Upper_Bound X maj) -> exists bsup : U, Lub X bsup) ->\n         Conditionally_complete.\n   \nEnd Bounds.\nHint Unfold Carrier_of.\nHint Unfold Rel_of.\nHint Resolve Totally_ordered_definition Upper_Bound_definition\n  Lower_Bound_definition Lub_definition Glb_definition Bottom_definition\n  Definition_of_Complete Definition_of_Complete\n  Definition_of_Conditionally_complete.", "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/podefs_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048443, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6637462818045353}}
{"text": "Require Import Classes.Morphisms.\nRequire Import Relations.\nRequire Import Structures.Equalities.\nRequire Import Omega.\nRequire Import Unicode.Utf8_core.\nRequire PreOrderTactic.\nNotation \"x ⇒ y\" := (x -> y)\n                      (at level 99, y at level 200, right associativity): type_scope.\n\n(* Dummy module type *)\nModule Type SetTyp <: Typ.\n  Parameter t : Set.\nEnd SetTyp.\n\n(* Module type for the variables: equality has to be decidable *)\nModule Type VariableAlphabet <: UsualDecidableType :=\n  SetTyp <+ HasUsualEq <+ UsualIsEq <+ HasEqDec.\n\nModule Types (𝕍 : VariableAlphabet).\n\n  (* Our type syntax *)\n  Inductive term : Set :=\n  | Var : 𝕍.t ⇒ term\n  | Arrow : term ⇒ term ⇒ term\n  | Inter : term ⇒ term ⇒ term\n  | Union : term ⇒ term ⇒ term\n  | Omega : term.\n  Infix \"⟶\" := (Arrow) (at level 60, right associativity).\n  Notation \"(⟶)\" := Arrow (only parsing).\n  Infix \"∩\" := (Inter) (at level 35, right associativity).\n  Notation \"(∩)\" := (Inter) (only parsing).\n  Infix \"∪\" := (Union) (at level 30, right associativity).\n  Notation \"(∪)\" := (Union) (only parsing).\n  Notation \"'ω'\" := (Omega).\n\n  (* measure on the types *)\n  Fixpoint size (σ : term) : nat :=\n    match σ with\n    | Var α => 0\n    | σ ⟶ τ => S((size σ) + (size τ))\n    | σ ∩ τ => S((size σ) + (size τ))\n    | σ ∪ τ => S((size σ) + (size τ))\n    | ω => 0\n    end.\n  Definition pair_size (x : term * term) : nat :=\n    let (s,t) := x in size s + size t.\n\n  (* Well-foundedness principle for the main algorithm *)\n  Definition main_algo_order : relation (term * term) :=\n    λ x y, pair_size x < pair_size y.\n  Definition wf_main_algo : well_founded main_algo_order := well_founded_ltof _ _.\n\n  Module SubtypeRelation.\n    Reserved Infix \"≤\" (at level 70).\n    Reserved Infix \"~=\" (at level 70).\n\n    (* The subtyping axioms, as defined in the theory Ξ of\n       Barbanera, Franco, Mariangiola Dezani-Ciancaglini, and Ugo Deliguoro. \"Intersection and union types: syntax and semantics.\" Information and Computation 119.2 (1995): 202-230. *)\n    Inductive Subtype : term ⇒ term ⇒ Prop :=\n    | R_InterMeetLeft : ∀ σ τ, σ ∩ τ ≤ σ\n    | R_InterMeetRight : ∀ σ τ, σ ∩ τ ≤ τ\n    | R_InterIdem : ∀ τ, τ ≤ τ ∩ τ\n    | R_UnionMeetLeft : ∀ σ τ, σ ≤ σ ∪ τ\n    | R_UnionMeetRight : ∀ σ τ, τ ≤ σ ∪ τ\n    | R_UnionIdem : ∀ τ, τ ∪ τ ≤ τ\n    | R_InterDistrib : ∀ σ τ ρ,\n        (σ ⟶ ρ) ∩ (σ ⟶ τ) ≤ σ ⟶ ρ ∩ τ\n    | R_UnionDistrib : ∀ σ τ ρ,\n        (σ ⟶ ρ) ∩ (τ ⟶ ρ) ≤ σ ∪ τ ⟶ ρ\n    | R_InterSubtyDistrib: ∀ σ σ' τ τ',\n        σ ≤ σ' ⇒ τ ≤ τ' ⇒ σ ∩ τ ≤ σ' ∩ τ'\n    | R_UnionSubtyDistrib: ∀ σ σ' τ τ',\n        σ ≤ σ' ⇒ τ ≤ τ' ⇒ σ ∪ τ ≤ σ' ∪ τ'\n    | R_InterUnionDistrib: ∀ σ τ ρ,\n        σ ∩ (τ ∪ ρ) ≤ (σ ∩ τ) ∪ (σ ∩ ρ)\n    | R_CoContra : ∀ σ σ' τ τ',\n        σ ≤ σ' ⇒ τ ≤ τ' ⇒ σ' ⟶ τ ≤ σ ⟶ τ'\n    | R_OmegaTop : ∀ σ, σ ≤ ω\n    | R_OmegaArrow : ω ≤ ω ⟶ ω\n    | R_Reflexive : ∀ σ, σ ≤ σ\n    | R_Transitive : ∀ σ τ ρ, σ ≤ τ ⇒ τ ≤ ρ ⇒ σ ≤ ρ\n    where \"σ ≤ τ\" := (Subtype σ τ).\n    Notation \"(≤)\" := (Subtype) (only parsing).\n\n    (* The equivalence relation *)\n    Definition equiv (σ τ : term) : Prop := (σ ≤ τ) ∧ (τ ≤ σ).\n    Notation \"σ ~= τ\" := (equiv σ τ).\n    Notation \"(~=)\" := (equiv) (only parsing).\n\n    (* SubtypeHints database *)\n    Create HintDb SubtypeHints.\n    Hint Constructors Subtype : SubtypeHints.\n    Hint Unfold equiv : SubtypeHints.\n\n    (* Add some useful tactics *)\n    Ltac preorder := PreOrderTactic.preorder.\n    Ltac inv H := inversion H; clear H; subst.\n\n    (* Boost auto *)\n    Local Hint Extern 0 (_ ≠ _) => discriminate.\n    Local Hint Extern 0 => lazymatch goal with\n                     | H : ?x ≠ ?x |- _ => contradiction\n                     end.\n    Local Hint Extern 1 => lazymatch goal with\n                     | H : _ ∧ _ |- _ => destruct H\n                     | H : _ ∨ _ |- _ => destruct H\n                     end.\n\n    (* Unlock all the preorder-related tactics for ≤ *)\n    Instance Subtypes_Reflexive : Reflexive (≤) := R_Reflexive.\n    Instance Subtypes_Transitive : Transitive (≤) := R_Transitive.\n    Instance Subtypes_Preorder : PreOrder (≤) :=\n      {| PreOrder_Reflexive := Subtypes_Reflexive;\n         PreOrder_Transitive := Subtypes_Transitive |}.\n\n    (* Unlock all the equivalence-related tactics for ~= *)\n    Instance equiv_Reflexive: Reflexive (~=).\n    Proof.\n      auto with SubtypeHints.\n    Qed.\n    Hint Immediate equiv_Reflexive : SubtypeHints.\n    Instance equiv_Transitive: Transitive (~=).\n    Proof.\n      compute.\n      intros ? ? ? [? ?] [? ?].\n      split; etransitivity; eassumption.\n    Qed.\n    Instance equiv_Symmetric: Symmetric (~=).\n    Proof.\n      compute; auto.\n    Qed.\n    Hint Immediate equiv_Symmetric : SubtypeHints.\n    Instance equiv_Equivalence: Equivalence (~=) :=\n      {| Equivalence_Reflexive := equiv_Reflexive;\n         Equivalence_Transitive := equiv_Transitive;\n         Equivalence_Symmetric := equiv_Symmetric |}.\n    Instance Subtypes_PartialOrder : PartialOrder (~=) (≤).\n    Proof.\n      compute; auto.\n    Qed.\n\n    (* Let's make the SubtypeHints database bigger *)\n    (* ≤-related facts *)\n    Fact Inter_inf : ∀ σ τ ρ, σ ≤ τ ⇒ σ ≤ ρ ⇒ σ ≤ τ ∩ ρ.\n    Proof with auto with SubtypeHints.\n      intros.\n      transitivity (σ ∩ σ)...\n    Qed.\n    Hint Resolve Inter_inf : SubtypeHints.\n\n    Fact Inter_inf' : ∀ σ τ ρ, σ ≤ τ ∩ ρ ⇒ (σ ≤ τ) ∧ (σ ≤ ρ).\n    Proof with auto with SubtypeHints.\n      intros; split;\n        etransitivity;\n        try eassumption...\n    Qed.\n\n    (* Don't put it in auto or it may be slow *)\n    Fact Inter_inf_dual : ∀ σ τ ρ, (σ ≤ ρ) ∨ (τ ≤ ρ) ⇒ σ ∩ τ ≤ ρ.\n    Proof with auto with SubtypeHints.\n      intros σ τ ? [? | ?];\n        [transitivity σ | transitivity τ]...\n    Qed.\n\n    Fact Union_sup : ∀ σ τ ρ, σ ≤ ρ ⇒ τ ≤ ρ ⇒ σ ∪ τ ≤ ρ.\n    Proof with auto with SubtypeHints.\n      intros.\n      transitivity (ρ ∪ ρ)...\n    Qed.\n    Hint Resolve Union_sup : SubtypeHints.\n\n    Fact Union_sup' : ∀ σ τ ρ, σ ∪ τ ≤ ρ ⇒ (σ ≤ ρ) ∧ (τ ≤ ρ).\n    Proof with auto with SubtypeHints.\n      intros; split;\n        etransitivity;\n        try eassumption...\n    Qed.\n\n    (* Don't put it in auto or it may be slow *)\n    Fact Union_sup_dual : ∀ σ τ ρ, (σ ≤ τ) ∨ (σ ≤ ρ) ⇒ σ ≤ τ ∪ ρ.\n    Proof with auto with SubtypeHints.\n      intros ? τ ρ [? | ?];\n        [transitivity τ | transitivity ρ]...\n    Qed.\n\n    Fact OmegaArrow : ∀ σ τ, ω ≤ τ ⇒ ω ≤ σ ⟶ τ.\n    Proof with auto with SubtypeHints.\n      intro; transitivity (ω ⟶ ω)...\n    Qed.\n    Hint Resolve OmegaArrow : SubtypeHints.\n\n    Fact UnionInterDistrib : ∀ σ τ ρ, (σ ∪ τ) ∩ (σ ∪ ρ) ≤ σ ∪ (τ ∩ ρ).\n    Proof with auto with SubtypeHints.\n      intros.\n      etransitivity; [apply R_InterUnionDistrib|]...\n      apply Union_sup; [apply Union_sup_dual|]...\n      transitivity (ρ ∩ (σ ∪ τ))...\n      etransitivity; [apply R_InterUnionDistrib|]...\n    Qed.\n    Hint Resolve UnionInterDistrib : SubtypeHints.\n\n    (* For more tactics, we show the operators are compatible with the relations *)\n    Instance Inter_Proper_ST : Proper ((≤) ==> (≤) ==> (≤)) (∩).\n    Proof with auto with SubtypeHints.\n      compute...\n    Qed.\n\n    Instance Union_Proper_ST : Proper ((≤) ==> (≤) ==> (≤)) (∪).\n    Proof with auto with SubtypeHints.\n      compute...\n    Qed.\n\n    Instance Arr_Proper_ST : Proper (transp _ (≤) ==> (≤) ==> (≤)) (⟶).\n    Proof with auto with SubtypeHints.\n      compute...\n    Qed.\n\n    Instance Inter_Proper_EQ : Proper ((~=) ==> (~=) ==> (~=)) (∩).\n    Proof with auto with SubtypeHints.\n      compute...\n    Qed.\n\n    Instance Union_Proper_EQ : Proper ((~=) ==> (~=) ==> (~=)) (∪).\n    Proof with auto with SubtypeHints.\n      compute...\n    Qed.\n\n    Instance Arr_Proper_EQ : Proper ((~=) ==> (~=) ==> (~=)) (⟶).\n    Proof with auto with SubtypeHints.\n      compute...\n    Qed.\n\n    (* Help auto use these properties *)\n    Hint Extern 2 (?R _ _ ~= ?R _ _) =>\n    lazymatch R with\n    | (∩) => apply Inter_Proper_EQ\n    | (∪) => apply Union_Proper_EQ\n    | (⟶) => apply Arr_Proper_EQ\n    end : SubtypeHints.\n\n    (* Ask auto to automatically simplify the hypotheses *)\n    Hint Extern 1 (_ ≤ _) =>\n    lazymatch goal with\n    | H : ω ≤ _ |- _ => try rewrite <- H; (clear H) + (try rewrite <- H in *; clear H)\n    | H : ?σ ≤ ?τ ∩ ?ρ |- _ => apply Inter_inf' in H; destruct H\n    | H : ?σ ∪ ?τ ≤ ?ρ |- _ => apply Union_sup' in H; destruct H\n    end : SubtypeHints.\n\n    (* Ask auto to use preorder if the goal is atomic *)\n    Hint Extern 300 (?σ ≤ ?τ) =>\n    lazymatch σ with\n    | _ _ _ => fail\n    | _ => lazymatch τ with\n           | _ _ _ => fail\n           | _ => preorder\n           end\n    end : SubtypeHints.\n\n    (* ~=-related facts *)\n    Fact InterArrowEquiv : ∀ σ1 σ2 τ ρ1 ρ2, σ1 ~= τ ⟶ ρ1 ⇒ σ2 ~= τ ⟶ ρ2 ⇒ σ1 ∩ σ2 ~= τ ⟶ ρ1 ∩ ρ2.\n    Proof.\n      intros ? ? ? ? ? H H'.\n      rewrite H, H'.\n      auto with SubtypeHints.\n    Qed.\n    Hint Resolve InterArrowEquiv : SubtypeHints.\n\n    Fact UnionArrowEquiv : ∀ σ1 σ2 τ1 τ2 ρ, σ1 ~= τ1 ⟶ ρ ⇒ σ2 ~= τ2 ⟶ ρ ⇒ σ1 ∩ σ2 ~= τ1 ∪ τ2 ⟶ ρ.\n    Proof.\n      intros ? ? ? ? ? H H'.\n      rewrite H, H'.\n      auto with SubtypeHints.\n    Qed.\n    Hint Resolve UnionArrowEquiv : SubtypeHints.\n\n    Fact UnionEquiv1 : ∀ σ1 σ2 τ1 τ2 τ3, σ1 ~= τ1 ∪ τ2 ⇒ σ2 ~= τ1 ∪ τ3 ⇒ σ1 ∩ σ2 ~= τ1 ∪ (τ2 ∩ τ3).\n    Proof.\n      intros ? ? ? ? ? H H'.\n      rewrite H, H'.\n      auto with SubtypeHints.\n    Qed.\n    Hint Resolve UnionEquiv1 : SubtypeHints.\n\n    Fact UnionEquiv2 : ∀ σ1 σ2 τ1 τ2 τ3, σ1 ~= τ1 ∪ τ3 ⇒ σ2 ~= τ2 ∪ τ3 ⇒ σ1 ∩ σ2 ~= (τ1 ∩ τ2) ∪ τ3.\n    Proof.\n      intros ? ? ? ? ? H H'.\n      rewrite H, H'.\n      transitivity (τ3 ∪ (τ1 ∩ τ2)); auto with SubtypeHints.\n    Qed.\n    Hint Resolve UnionEquiv2 : SubtypeHints.\n\n    Fact InterEquiv1 : ∀ σ1 σ2 τ1 τ2 τ3, σ1 ~= τ1 ∩ τ2 ⇒ σ2 ~= τ1 ∩ τ3 ⇒ σ1 ∪ σ2 ~= τ1 ∩ (τ2 ∪ τ3).\n    Proof.\n      intros ? ? ? ? ? H H'.\n      rewrite H, H'.\n      auto with SubtypeHints.\n    Qed.\n    Hint Resolve InterEquiv1 : SubtypeHints.\n\n    Fact InterEquiv2 : ∀ σ1 σ2 τ1 τ2 τ3, σ1 ~= τ1 ∩ τ3 ⇒ σ2 ~= τ2 ∩ τ3 ⇒ σ1 ∪ σ2 ~= (τ1 ∪ τ2) ∩ τ3.\n    Proof.\n      intros ? ? ? ? ? H H'.\n      rewrite H, H'.\n      transitivity (τ3 ∩ (τ1 ∪ τ2)); auto with SubtypeHints.\n    Qed.\n    Hint Resolve InterEquiv2 : SubtypeHints.\n\n    Hint Extern 1 (_ ~= _ ) =>\n    repeat lazymatch goal with\n           | H : ?x ~= ω |- context[?x] => rewrite H; clear H\n           | H : ω ~= ?x |- context[?x] => rewrite <- H; clear H\n           | H : ?x ~= _ |- context[?x] => rewrite H; clear H\n           end : SubtypeHints.\n\n    (* Syntactical predicates on terms *)\n\n    (* Generalized intersection and union *)\n    Inductive Generalize (c : term ⇒ term ⇒ term) (P : term ⇒ Prop) : term ⇒ Prop :=\n    | G_nil : ∀ σ, P σ ⇒ Generalize c P σ\n    | G_cons : ∀ σ τ, Generalize c P σ ⇒ Generalize c P τ ⇒ Generalize c P (c σ τ).\n    Hint Constructors Generalize : SubtypeHints.\n\n    (* Notations: [ ⋂ P ] x means x is a generalized intersection of terms verifying P *)\n    Notation \"[ ⋂ P ]\" := (Generalize (∩) P).\n    Notation \"[ ⋃ P ]\" := (Generalize (∪) P).\n\n    Fact general_inheritance : ∀ f g P s, Generalize f P s ⇒ Generalize f (Generalize g P) s.\n    Proof.\n      intros ? ? ? ? H; induction H.\n      - constructor; constructor; assumption.\n      - constructor 2; assumption.\n    Qed.\n    Hint Resolve general_inheritance : SubtypeHints.\n\n    (* Arrow Normal Form *)\n    Inductive ANF : term ⇒ Prop :=\n    | VarisANF : ∀ α, ANF (Var α)\n    | ArrowisANF : ∀ σ τ, [⋂ ANF] σ ⇒ [⋃ ANF] τ ⇒ ANF (σ ⟶ τ)\n    | ArrowisANF' : ∀ τ, [⋃ ANF] τ ⇒ ANF (ω ⟶ τ).\n    Hint Constructors ANF : SubtypeHints.\n\n    (* Conjunctive/Disjunctive Normal Forms *)\n    Definition CANF (σ : term) : Prop := [⋂ [⋃ ANF]] σ ∨ σ = ω.\n    Definition DANF (σ : term) : Prop := [⋃ [⋂ ANF]] σ ∨ σ = ω.\n    Hint Unfold CANF : SubtypeHints.\n    Hint Unfold DANF : SubtypeHints.\n\n    (* Terms without Omega (with one exception, in Of_Arrow1) *)\n    Inductive Omega_free : term ⇒ Prop :=\n    | Of_Var : ∀ α, Omega_free (Var α)\n    | Of_Union : ∀ σ τ, Omega_free σ ⇒ Omega_free τ ⇒ Omega_free (σ ∪ τ)\n    | Of_Inter : ∀ σ τ, Omega_free σ ⇒ Omega_free τ ⇒ Omega_free (σ ∩ τ)\n    | Of_Arrow1 : ∀ σ, Omega_free σ ⇒ Omega_free (ω ⟶ σ)\n    | Of_Arrow2 : ∀ σ τ, Omega_free σ ⇒ Omega_free τ ⇒ Omega_free (σ ⟶ τ).\n    Hint Constructors Omega_free : SubtypeHints.\n    Hint Extern 1 =>\n    match goal with\n    | H : Omega_free ω |- _ => inversion H\n    | H : Omega_free (_ _ _) |- _ => inv H\n    end : SubtypeHints.\n\n    (* Terms on which we'll define filters *)\n    Unset Elimination Schemes.\n    Inductive isFilter : term ⇒ Prop :=\n    | OmegaisFilter : isFilter ω\n    | VarisFilter : ∀ α, isFilter (Var α)\n    | ArrowisFilter : ∀ σ τ, isFilter (σ ⟶ τ)\n    | InterisFilter : ∀ σ τ, isFilter σ ⇒ isFilter τ ⇒ isFilter (σ ∩ τ).\n    Set Elimination Schemes.\n    Hint Constructors isFilter : SubtypeHints.\n\n    Fact InterANF_isFilter : ∀ σ, [ ⋂ ANF] σ ⇒ isFilter σ.\n    Proof.\n      induction 1 as [? H|].\n      inversion H; auto with SubtypeHints.\n      constructor; trivial.\n    Qed.\n    Hint Extern 0 (isFilter ?σ) =>\n    match goal with\n    | H : [ ⋂ ANF] σ |- _ => apply InterANF_isFilter\n    end : SubtypeHints.\n\n    (* Huge tactics that deals with these forms *)\n    Ltac decide_nf :=\n      try (lazymatch goal with\n           | H : ANF _ |- _ => idtac\n           | H : Generalize _ _ _ |- _ => idtac\n           | H : CANF _ |- _ => idtac\n           | H : DANF _ |- _ => idtac\n           | _ => fail\n           end;\n           repeat lazymatch goal with\n                  | H : DANF (_ _ _) |- _ => inversion H as [?|H']; [|inversion H']; subst; clear H\n                  | H : CANF (_ _ _) |- _ => inversion H as [?|H']; [|inversion H']; subst; clear H\n                  | H : [⋃ ANF] (_ ∪ _) |- _ => inversion H as [? H'|]; [inversion H'|]; subst; clear H\n                  | H : [⋃ [⋂ ANF]] (_ ∪ _) |- _ => inversion H as [? H'|];\n                                                    [inversion H' as [? H''|]; inversion H''|];\n                                                    subst; clear H\n                  | H : [⋃ _] (_ ∩ _) |- _ => inv H\n                  | H : [⋃ _] (_ ⟶ _) |- _ => inv H\n                  | H : [⋃ _] (Var _) |- _ => inv H\n                  | H : [⋃ _] ω |- _ => inv H\n                  | H : [⋂ ANF] (_ ∩ _) |- _ => inversion H as [? H'|]; [inversion H'|]; subst; clear H\n                  | H : [⋂ [⋃ ANF]] (_ ∩ _) |- _ => inversion H as [? H'|];\n                                                    [inversion H' as [? H''|]; inversion H''|];\n                                                    subst; clear H\n                  | H : [⋂ _] (_ ∪ _) |- _ => inv H\n                  | H : [⋂ _] (_ ⟶ _) |- _ => inv H\n                  | H : [⋂ _] (Var _) |- _ => inv H\n                  | H : [⋂ _] ω |- _ => inv H\n                  | H : ANF (ω ⟶ _) |- _ => inversion H as [|? ? H'|];\n                                            [inversion H' as [? H''|]; inversion H''|]; subst; clear H\n                  | H : ANF (_ ⟶ _) |- _ => inv H\n                  | H : ANF (_ ∩ _) |- _ => inversion H\n                  | H : ANF (_ ∪ _) |- _ => inversion H\n                  | H : ANF ω |- _ => inversion H\n                  | H : Omega_free (_ _ _) |- _ => inv H\n                  end);\n      repeat lazymatch goal with\n             | H : ?x |- ?x => assumption\n             | |- [⋃ _] (_ ∪ _) => apply G_cons\n             | |- [⋃ _] _ => apply G_cons\n             | |- [⋂ _] (_ ∩ _) => apply G_cons\n             | |- [⋂ _] _ => apply G_nil\n             | |- ANF (Var _) => constructor\n             | |- ANF (ω ⟶ _) => apply ArrowisANF'\n             | |- ANF (_ ⟶ _) => constructor\n             | |- CANF ω => right; reflexivity\n             | |- DANF ω => right; reflexivity\n             | |- CANF (Var _) => left; repeat constructor\n             | |- DANF (Var _) => left; repeat constructor\n             | |- CANF (_ _ _) => left\n             | |- DANF (_ _ _) => left\n             end.\n    Hint Extern 1 (CANF _) => decide_nf : SubtypeHints.\n    Hint Extern 1 (DANF _) => decide_nf : SubtypeHints.\n    Hint Extern 1 (ANF _) => decide_nf : SubtypeHints.\n    Hint Extern 1 (Generalize _ _ _) => decide_nf : SubtypeHints.\n\n    (* The recursion scheme for isFilter uses P ω as an inductive hypothesis *)\n    Lemma isFilter_ind : ∀ P : term ⇒ Prop,\n        P ω ⇒\n        (∀ α : 𝕍.t, P ω ⇒ P (Var α)) ⇒\n        (∀ σ τ : term, P ω ⇒ P (σ ⟶ τ)) ⇒\n        (∀ σ τ : term, isFilter σ ⇒ P σ ⇒ isFilter τ ⇒ P τ ⇒ P ω ⇒ P (σ ∩ τ)) ⇒\n        ∀ σ : term, isFilter σ ⇒ P σ.\n    Proof.\n      intros P fω fα fA fI.\n      exact (fix foo σ Fσ : P σ := match Fσ in isFilter σ return P σ with\n                                   | OmegaisFilter => fω\n                                   | VarisFilter α => fα α fω\n                                   | ArrowisFilter σ τ => fA σ τ fω\n                                   | InterisFilter σ τ Fσ Fτ => fI σ τ Fσ (foo σ Fσ) Fτ (foo τ Fτ) fω\n                                   end).\n    Qed.\n\n    (* Recursion scheme for [⋃ ANF] *)\n    Lemma Uanf_ind : ∀ P : term ⇒ Prop,\n        (∀ α, P (Var α)) ⇒\n        (∀ σ τ, P σ ⇒ P τ ⇒ P (σ ∪ τ)) ⇒\n        (∀ σ τ, P τ ⇒ P (σ ⟶ τ)) ⇒\n        (∀ σ, [⋃ ANF] σ ⇒ P σ).\n      intros P fV fU fA.\n      refine (fix foo (σ : term) := match σ with\n                                    | Var α => λ _, fV α\n                                    | σ ⟶ τ => λ pf, fA _ τ (foo τ _)\n                                    | σ ∪ τ => λ pf, fU σ τ (foo σ _) (foo τ _)\n                                    | σ ∩ τ => λ pf, _\n                                    | ω => λ pf, _\n                                    end);\n        try(inversion pf as [? pf'|]; inv pf'); decide_nf.\n    Qed.\n    Ltac uanf_ind σ :=\n      let foo HH :=\n          repeat match goal with\n                 | H : context[σ] |- _ => lazymatch H with\n                                          | HH => fail\n                                          | _ => revert H\n                                          end\n                 end;\n          revert HH; revert σ;\n          refine (Uanf_ind _ _ _ _); intros\n      in\n      lazymatch goal with\n      | HH : [⋃ ANF] σ |- _ => foo HH\n      | _ =>\n        assert (HH : [⋃ ANF] σ) by (auto with SubtypeHints);\n        foo HH\n      end.\n\n    (* Filters and ideals *)\n    Reserved Notation \"↑[ σ ] τ\" (at level 65).\n    Reserved Notation \"↓[ σ ] τ\" (at level 65).\n    Inductive Filter : term ⇒ term ⇒ Prop :=\n    | F_Refl : ∀ σ : term, isFilter σ ⇒ ↑[σ] σ\n    | F_Inter : ∀ σ τ ρ : term, ↑[σ] τ ⇒ ↑[σ] ρ ⇒ ↑[σ] τ ∩ ρ\n    | F_Union1 : ∀ σ τ ρ : term, ↑[σ] τ ⇒ ↑[σ] τ ∪ ρ\n    | F_Union2 : ∀ σ τ ρ : term, ↑[σ] ρ ⇒ ↑[σ] τ ∪ ρ\n    | F_Arrow1 : ∀ σ1 σ2 τ1 τ2 : term, σ2 ≤ σ1 ⇒ τ1 ≤ τ2 ⇒ ↑[σ1 ⟶ τ1] σ2 ⟶ τ2\n    | F_Arrow2 : ∀ σ1 σ2 τ1 τ2 ρ1 ρ2 : term, ↑[σ1 ∩ σ2] τ1 ⟶ ρ1 ⇒ τ2 ≤ τ1 ⇒ ρ1 ≤ ρ2 ⇒ ↑[σ1 ∩ σ2] τ2 ⟶ ρ2\n    | F_OmegaTopV : ∀ (α : 𝕍.t) (τ : term), ↑[ω] τ ⇒ ↑[Var α] τ\n    | F_OmegaTopA : ∀ σ1 σ2 τ : term, ↑[ω] τ ⇒ ↑[σ1 ⟶ σ2] τ\n    | F_OmegaTopI : ∀ σ1 σ2 τ : term, isFilter (σ1 ∩ σ2) ⇒ ↑[ω] τ ⇒ ↑[σ1 ∩ σ2] τ\n    | F_Omega : ∀ σ τ : term, ↑[ω] τ ⇒ ↑[ω] σ ⟶ τ\n    | F_Inter1 : ∀ σ1 σ2 τ : term, isFilter σ2 ⇒ ↑[σ1] τ ⇒ ↑[σ1 ∩ σ2] τ\n    | F_Inter2 : ∀ σ1 σ2 τ : term, isFilter σ1 ⇒ ↑[σ2] τ ⇒ ↑[σ1 ∩ σ2] τ\n    | F_ArrowInter : ∀ σ1 σ2 τ ρ1 ρ2 : term, ↑[σ1 ∩ σ2] (τ ⟶ ρ1) ∩ (τ ⟶ ρ2) ⇒ ↑[σ1 ∩ σ2] τ ⟶ ρ1 ∩ ρ2\n    | F_ArrowUnion : ∀ σ1 σ2 τ1 τ2 ρ : term, ↑[σ1 ∩ σ2] (τ1 ⟶ ρ) ∩ (τ2 ⟶ ρ) ⇒ ↑[σ1 ∩ σ2] τ1 ∪ τ2 ⟶ ρ\n    where \"↑[ σ ] τ\" := (Filter σ τ).\n    Hint Constructors Filter : SubtypeHints.\n\n    Inductive Ideal : term ⇒ term ⇒ Prop :=\n    | I_Refl : ∀ σ : term,  [⋃ ANF] σ ⇒ ↓[σ] σ\n    | I_Inter1 : ∀ σ τ ρ : term, ↓[σ] τ ⇒ ↓[σ] τ ∩ ρ\n    | I_Inter2 : ∀ σ τ ρ : term, ↓[σ] ρ ⇒ ↓[σ] τ ∩ ρ\n    | I_Union : ∀ σ τ ρ : term, ↓[σ] τ ⇒ ↓[σ] ρ ⇒ ↓[σ] τ ∪ ρ\n    | I_Arrow1 : ∀ σ1 σ2 τ1 τ2 : term, [⋂ ANF] σ1 ⇒ ↑[σ1] σ2 ⇒ ↓[τ1] τ2 ⇒ ↓[σ1 ⟶ τ1] σ2 ⟶ τ2\n    | I_Arrow2 : ∀ σ τ1 τ2 : term, ↑[ω] σ ⇒ ↓[τ1] τ2 ⇒ ↓[ω ⟶ τ1] σ ⟶ τ2\n    | I_Union1 : ∀ σ1 σ2 τ : term, [⋃ ANF] σ2 ⇒ ↓[σ1] τ ⇒ ↓[σ1 ∪ σ2] τ\n    | I_Union2 : ∀ σ1 σ2 τ : term, [⋃ ANF] σ1 ⇒ ↓[σ2] τ ⇒ ↓[σ1 ∪ σ2] τ\n    where \"↓[ σ ] τ\" := (Ideal σ τ).\n    Hint Constructors Ideal : SubtypeHints.\n\n    (* Correctness of filters and ideals *)\n    Theorem Filter_correct : ∀ σ τ, ↑[σ] τ ⇒ σ ≤ τ.\n    Proof with auto using Inter_inf_dual, Union_sup_dual with SubtypeHints.\n      intros ? ? H.\n      induction H...\n      - etransitivity; [eassumption|]...\n      - etransitivity; [|apply R_InterDistrib]...\n      - etransitivity; [|apply R_UnionDistrib]...\n    Qed.\n    Hint Resolve Filter_correct : SubtypeHints.\n    Hint Extern 1 (_ ≤ _) =>\n    lazymatch goal with\n    | H : ↑[ω] _ |- _ => apply (Filter_correct) in H; try rewrite <- H; (clear H) + (try rewrite <- H in *; clear H)\n    end : SubtypeHints.\n\n    Theorem Ideal_correct : ∀ σ τ, ↓[σ] τ ⇒ τ ≤ σ.\n    Proof with auto using Inter_inf_dual, Union_sup_dual with SubtypeHints.\n      intros ? ? H.\n      induction H...\n    Qed.\n    Hint Resolve Ideal_correct : SubtypeHints.\n\n    (* Filters and ideals have some normal form *)\n    Lemma Filter_isFilter: ∀ σ τ, ↑[σ] τ ⇒ isFilter σ.\n    Proof.\n      intros ? ? H; induction H; auto; constructor; auto.\n    Qed.\n    Hint Extern 0 (isFilter ?σ) =>\n      match goal with\n      | H : ↑[?σ] _ |- _ => apply (Filter_isFilter _ _ H)\n      end : SubtypeHints.\n\n    Lemma Ideal_isDANF: ∀ σ τ, ↓[σ] τ ⇒ [⋃ ANF] σ.\n    Proof.\n      intros ? ? H; induction H; auto with SubtypeHints.\n    Qed.\n    Hint Resolve Ideal_isDANF : SubtypeHints.\n    Hint Extern 0 ([⋃ ANF] ?σ) =>\n      match goal with\n      | H : ↓[?σ] _ |- _ => apply (Ideal_isDANF _ _ H)\n      end : SubtypeHints.\n\n    (* Tactic: cast ρ to σ in filter (or ideals) (may produce new goals) *)\n    Ltac cast_filter ρ σ :=\n      lazymatch σ with\n      | ω => match ρ with\n             | Var _ => apply F_OmegaTopV\n             | _ ⟶ _ => apply F_OmegaTopA\n             | _ ∩ _ => apply F_OmegaTopI\n             end\n      | _ => lazymatch ρ with\n             | σ ∩ _ => apply F_Inter1\n             | _ ∩ σ => apply F_Inter2\n             end\n      end.\n    Ltac cast_ideal ρ σ :=\n      lazymatch ρ with\n      | σ ∪ _ => apply I_Union1\n      | _ ∪ σ => apply I_Union2\n      end.\n\n    (* Helper lemmas to destruct filter and ideal hypotheses *)\n    Lemma FilterInter : ∀ σ τ ρ, ↑[σ] τ ∩ ρ ⇒ ↑[σ] τ ∧ ↑[σ] ρ.\n      intros ? ? ? H.\n      assert (Fσ : isFilter σ) by (auto with SubtypeHints).\n      induction Fσ; split; inv H;\n        auto with SubtypeHints;\n        lazymatch goal with\n        (* Inductive case *)\n        | IH : ↑[?σ] ?τ ⇒ _, H : ↑[?σ] ?τ |- ↑[?ρ] _ =>\n          (* cast ρ to σ *)\n          cast_filter ρ σ; trivial;\n            (* apply the inductive hypothesis *)\n            apply IH; trivial\n        end.\n    Qed.\n\n    Lemma IdealInter : ∀ σ τ ρ, ↓[σ] τ ∩ ρ ⇒ ↓[σ] τ ∨ ↓[σ] ρ.\n      intros ? ? ? H.\n      assert (Iσ : [⋃ ANF] σ) by (auto with SubtypeHints).\n      induction Iσ; inv H; auto with SubtypeHints; decide_nf;\n        lazymatch goal with\n        (* Inductive case *)\n        | IH : ↓[?σ] ?τ1 ∩ ?τ2 ⇒ ?prop, H : ↓[?σ] ?τ1 ∩ ?τ2 |- ↓[?ρ] ?τ1 ∨ ↓[?ρ] ?τ2 =>\n          (* apply the inductive hypothesis *)\n          destruct (IH H); [left|right];\n            (* cast ρ to σ *)\n            cast_ideal ρ σ; assumption\n        end.\n    Qed.\n\n    Lemma FilterUnion : ∀ σ τ ρ, ↑[σ] τ ∪ ρ ⇒ ↑[σ] τ ∨ ↑[σ] ρ.\n      intros ? ? ? H.\n      assert (Fσ : isFilter σ) by (auto with SubtypeHints).\n      induction Fσ; inv H; auto;\n        lazymatch goal with\n        (* Inductive case *)\n        | IH : ↑[?σ] ?τ1 ∪ ?τ2 ⇒ ?prop, H : ↑[?σ] ?τ1 ∪ ?τ2 |- ↑[?ρ] ?τ1 ∨ ↑[?ρ] ?τ2 =>\n          (* apply the inductive hypothesis *)\n          destruct (IH H); [left|right];\n            (* cast ρ to σ *)\n            cast_filter ρ σ; assumption\n        end.\n    Qed.\n\n    Lemma IdealUnion : ∀ σ τ ρ, ↓[σ] τ ∪ ρ ⇒ ↓[σ] τ ∧ ↓[σ] ρ.\n      intros ? ? ? H.\n      assert (Iσ : [⋃ ANF] σ) by (auto with SubtypeHints).\n      induction Iσ; split; inv H;\n        auto with SubtypeHints; decide_nf;\n          lazymatch goal with\n          (* Inductive case *)\n          | IH : ↓[?σ] ?τ ⇒ _, H : ↓[?σ] ?τ |- ↓[?ρ] _ =>\n            (* cast ρ to σ *)\n            cast_ideal ρ σ; trivial;\n              (* apply the inductive hypothesis *)\n              apply IH; trivial\n          end.\n    Qed.\n\n    Lemma FilterArrow : ∀ σ σ' τ τ', ↑[σ ⟶ σ'] τ ⟶ τ' ⇒ (↑[ω] τ ⟶ τ' ∨ (τ ≤ σ  ∧ σ' ≤ τ')).\n    Proof.\n      intros ? ? ? ? H; inv H; auto 3 with SubtypeHints.\n    Qed.\n\n    Lemma Filter_omega : ∀ σ τ, isFilter σ ⇒ ↑[ω] τ ⇒ ↑[σ] τ.\n    Proof.\n      induction 1; auto with SubtypeHints.\n    Qed.\n\n    Lemma IdealnoOmega : ∀ σ, ¬ ↓[ σ] ω.\n    Proof.\n      induction σ; intro H; inv H;\n        auto with SubtypeHints; decide_nf.\n    Qed.\n\n    Lemma IdealnoOmegaArrow : ∀ σ, ¬ ↓[ σ] ω ⟶ ω.\n    Proof.\n      induction σ; intro H; inv H;\n        auto with SubtypeHints; decide_nf;\n        eapply IdealnoOmega; eassumption.\n    Qed.\n\n    Hint Extern 1 =>\n    lazymatch goal with\n    | H : ↑[?σ ∩ ?τ] (?ρ ⟶ _) ∩ (?ρ ⟶ _) |- _ => apply F_ArrowInter in H\n    | H : ↑[?σ ∩ ?τ] (_ ⟶ ?ρ) ∩ (_ ⟶ ?ρ) |- _ => apply F_ArrowUnion in H\n    | H : ↑[_] _ ∪ _ |- _ => apply FilterUnion in H; destruct H\n    | H : ↑[_] _ ∩ _ |- _ => apply FilterInter in H; destruct H\n    | H : ↑[_ ⟶ _] _ ⟶ _ |- _ => apply FilterArrow in H; destruct H as [|[ ]]\n    | H : ↑[ω] _ ⟶ _ |- _ => inv H\n    | H : ↑[Var _] _ ⟶ _ |- _ => inv H\n    end : SubtypeHints.\n\n    Ltac destruct_ideal :=\n      repeat lazymatch goal with\n             | H : ↓[_] ω |- _ => apply IdealnoOmega in H; exfalso; trivial\n             | H : ↓[_] ω ⟶ ω |- _ => apply IdealnoOmegaArrow in H; exfalso; trivial\n             | H : ↓[_] _ ∪ _ |- _ => apply IdealUnion in H; destruct H\n             | H : ↓[_] _ ∩ _ |- _ => apply IdealInter in H; destruct H\n             | H : ↓[_ ∪ _] _ ⟶ _ |- _ => inv H\n             | H : ↓[_ ⟶ _] _ ⟶ _ |- _ => inv H\n             | H : ↓[Var _] _ ⟶ _ |- _ => inv H\n             end.\n\n    Lemma FilterArrow' : ∀ σ τ' ρ, ↑[ σ] τ' ⟶ ρ ⇒ ∀ τ ρ', τ ≤ τ' ⇒ ρ ≤ ρ' ⇒ ↑[ σ] τ ⟶ ρ'.\n    Proof.\n      intros ? ? ? H.\n      assert (Fσ : isFilter σ) by (auto with SubtypeHints).\n      induction Fσ.\n      - intros ? ? ? H1.\n        constructor; inv H.\n        induction H1; auto 10 with SubtypeHints.\n      - auto with SubtypeHints.\n      - apply FilterArrow in H; destruct H as [|[ ]]; auto with SubtypeHints.\n      - eauto with SubtypeHints.\n    Qed.\n\n    (* Main properties: filters (resp. ideal) are closed by upcasting (resp. downcasting) *)\n    (* As a result, we get completeness of filters and ideals *)\n    Lemma Filter_closed : ∀ σ τ1 τ2,\n        ↑[σ] τ1 ⇒ τ1 ≤ τ2 ⇒ ↑[σ] τ2.\n    Proof.\n      induction 2; auto with SubtypeHints;\n        solve [eapply FilterArrow'; eassumption|\n               apply Filter_omega; auto with SubtypeHints|\n               assert (Fσ : isFilter σ) by (auto with SubtypeHints);\n               induction Fσ; auto 10 with SubtypeHints].\n    Qed.\n    Hint Extern 0 (↑[?σ] ?τ2) =>\n    lazymatch goal with\n    | H : ↑[σ] ?τ1, H' : ?τ1 ≤ τ2 |- ↑[σ] τ2 => apply (Filter_closed _ _ _ H H')\n    end : SubtypeHints.\n\n    Theorem Filter_complete : ∀ σ, isFilter σ ⇒ ∀ τ, σ ≤ τ ⇒ ↑[σ] τ.\n    Proof.\n      intros; eapply Filter_closed; try eassumption.\n      apply F_Refl; assumption.\n    Qed.\n    Hint Resolve Filter_complete : SubtypeHints.\n\n    Section Ideal_closed.\n      (* This hint is local to the section; and help use the inductive hypotheses *)\n      Hint Extern 1 (↓[?ρ] _) =>\n      (* Because of a bug in auto, auto fails to use the generated hypothesis; so foo helps it *)\n      let foo σ HHH :=\n          lazymatch ρ with\n          | _ ∪ _ => cast_ideal ρ σ; trivial; apply HHH\n          | ω ⟶ _ => apply I_Arrow2; [|apply HHH]\n          | _ ⟶ _ => apply I_Arrow1; [| |apply HHH]\n          end\n      in\n      (* The variable τ of the inductive hypothesis cannot be infered by auto,\n         so this tactic instantiates it *)\n      lazymatch goal with\n      | H : ∀ τ, ↓[?σ] τ ⇒ ∀ τ' : term, τ' ≤ τ ⇒ ↓[?σ] τ', H' : ↓[?σ] ?τ |- _ =>\n      assert (HHH : ∀ τ' : term, τ' ≤ τ ⇒ ↓[ σ] τ') by (exact (H τ H')); clear H H'; foo σ HHH\n    | H : ∀ τ, ↓[?σ] τ ⇒ ∀ τ' : term, τ' ≤ τ ⇒ ↓[?σ] τ', H' : ?τ ≤ ?σ |- _ =>\n      assert (HHH : ↓[ σ] τ) by (refine (H _ (I_Refl _ _) _ H'); trivial); clear H H'; foo σ HHH\n      end.\n\n      Lemma Ideal_closed : ∀ σ, [⋃ ANF] σ ⇒ ∀ τ1, ↓[σ] τ1 ⇒ ∀ τ2, τ2 ≤ τ1 ⇒ ↓[σ] τ2.\n      Proof.\n        intros until 1; uanf_ind σ;\n          lazymatch goal with\n          | H : _ ≤ _ |- _ => induction H;\n                                destruct_ideal;\n                                decide_nf;\n                                auto with SubtypeHints\n          end.\n      Qed.\n    End Ideal_closed.\n\n    Theorem Ideal_complete : ∀ σ, [⋃ ANF] σ ⇒ ∀ τ, τ ≤ σ ⇒ ↓[σ] τ.\n    Proof.\n      intros; eapply Ideal_closed; try eassumption.\n      apply I_Refl; assumption.\n    Qed.\n\n    (* Now we can use filters and ideals to prove lemmas about subtyping *)\n    Lemma Omega_free_Omega : ∀ s, Omega_free s ⇒ ¬ s ~= Omega.\n    Proof.\n      intros ? H [_ H2].\n      apply Filter_complete in H2; trivial with SubtypeHints.\n      induction s; inv H; inv H2; auto with SubtypeHints.\n    Qed.\n\n    Lemma Omega_IUANF : ∀ σ, [ ⋂ [ ⋃ ANF]] σ ⇒ ¬ ω ≤ σ.\n    Proof.\n      induction σ as [|? H1 ? H2|? H1 ? H2|? H1 ? H2|];\n        intros; intro Hyp; (apply Filter_complete in Hyp; [|constructor]); inv Hyp;\n          solve [apply H2; auto 2 with SubtypeHints|\n                 apply H1; auto 2 with SubtypeHints|\n                 decide_nf].\n    Qed.\n\n    (* Rewriting functions *)\n\n    (* First rewriting function: do Omega-related simplifications *)\n    Fixpoint deleteOmega (σ : term) : {τ | τ ~= σ ∧ (Omega_free τ ∨ τ = ω)}.\n      refine(match σ with\n             | σ ⟶ τ => let (σ,pfσ) := deleteOmega σ in\n                        let (τ,pfτ) := deleteOmega τ in\n                        match τ as x return τ = x ⇒ _ with\n                        | ω => λ _, exist _ ω _\n                        | _ => λ _, exist _ (σ ⟶ τ) _\n                        end eq_refl\n             | σ ∩ τ => let (σ,pfσ) := deleteOmega σ in\n                        let (τ,pfτ) := deleteOmega τ in\n                        match σ as x return σ = x ⇒ _ with\n                        | ω => λ _, exist _ τ _\n                        | _ => λ _, match τ as x return τ = x ⇒ _ with\n                                    | ω => λ _, exist _ σ _\n                                        | _ => λ _, exist _ (σ ∩ τ) _\n                                        end eq_refl\n                        end eq_refl\n             | σ ∪ τ => let (σ,pfσ) := deleteOmega σ in\n                        let (τ,pfτ) := deleteOmega τ in\n                        match σ as x return σ = x ⇒ _ with\n                        | ω => λ _, exist _ ω _\n                        | _ => λ _, match τ as x return τ = x ⇒ _ with\n                                        | ω => λ _, exist _ ω _\n                                        | _ => λ _, exist _ (σ ∪ τ) _\n                                        end eq_refl\n                        end eq_refl\n             | Var α => exist _ (Var α) _\n             | ω => exist _ ω _\n             end); clear deleteOmega; subst; simpl in *;\n        first[destruct pfσ as [? [|]];\n              destruct pfτ as [? [|]]; subst|\n              auto with SubtypeHints];\n        first[match goal with | H : Omega_free ω |- _ => inversion H end|\n              discriminate|\n              split; auto with SubtypeHints].\n    Defined.\n\n    (* Distribution functions *)\n    Fixpoint distrArrow (σ τ : term) (pfσ : [⋃ [⋂ ANF]] σ ∨ σ = ω) (pfτ : [⋂ [⋃ ANF]] τ) :\n      {σ' | σ' ~= σ ⟶ τ ∧ [⋂ ANF] σ'}.\n      refine(match σ as x return σ = x ⇒ _ with\n             | σ1 ∪ σ2 => λ _, let (σ1,pfσ1) := distrArrow σ1 τ _ _ in\n                                   let (σ2,pfσ2) := distrArrow σ2 τ _ _ in\n                                   exist _ (σ1 ∩ σ2) _\n             | _ => λ _,\n                      (fix distrArrow' σ τ (pfσ:[⋂ ANF] σ ∨ σ = ω) (pfτ:[⋂ [⋃ ANF]] τ) : {σ' | σ' ~= σ ⟶ τ ∧ [⋂ ANF] σ'} :=\n                         match τ as x return τ = x ⇒ _ with\n                         | τ1 ∩ τ2 => λ _, let (τ1,pfτ1) := distrArrow' σ τ1 _ _ in\n                                               let (τ2,pfτ2) := distrArrow' σ τ2 _ _ in\n                                               exist _ (τ1 ∩ τ2) _\n                         | _ => λ _, exist _ (σ ⟶ τ) _\n                         end eq_refl) σ τ _ pfτ\n             end eq_refl); subst; (destruct pfσ; [|try discriminate]); simpl in *;\n        auto with SubtypeHints.\n    Defined.\n\n    Fixpoint distrUnion (σ τ : term) (pfσ : [⋂ [⋃ ANF]] σ) (pfτ : [⋂ [⋃ ANF]] τ) :\n      {σ' | σ' ~= σ ∪ τ ∧ [⋂ [⋃ ANF]] σ'}.\n      refine(match σ as x return σ = x ⇒ _ with\n             | σ1 ∩ σ2 => λ _, let (σ1,pfσ1) := distrUnion σ1 τ _ _ in\n                                   let (σ2,pfσ2) := distrUnion σ2 τ _ _ in\n                                   exist _ (σ1 ∩ σ2) _\n             | _ => λ _,\n                      (fix distrUnion' σ τ (pfσ:[⋃ ANF] σ) (pfτ:[⋂ [⋃ ANF]] τ) : {σ' | σ' ~= σ ∪ τ ∧ [⋂ [⋃ ANF]] σ'} :=\n                         match τ as x return τ = x ⇒ _ with\n                         | τ1 ∩ τ2 => λ _, let (τ1,pfτ1) := distrUnion' σ τ1 _ _ in\n                                               let (τ2,pfτ2) := distrUnion' σ τ2 _ _ in\n                                               exist _ (τ1 ∩ τ2) _\n                         | _ => λ _, exist _ (σ ∪ τ) _\n                         end eq_refl) σ τ _ pfτ\n             end eq_refl); subst; simpl in *;\n        auto with SubtypeHints.\n    Defined.\n\n    Fixpoint distrInter (σ τ : term) (pfσ : [⋃ [⋂ ANF]] σ) (pfτ : [⋃ [⋂ ANF]] τ) :\n      {σ' | σ' ~= σ ∩ τ ∧ [⋃ [⋂ ANF]] σ'}.\n      refine(match σ as x return σ = x ⇒ _ with\n             | σ1 ∪ σ2 => λ _, let (σ1,pfσ1) := distrInter σ1 τ _ _ in\n                                   let (σ2,pfσ2) := distrInter σ2 τ _ _ in\n                                   exist _ (σ1 ∪ σ2) _\n             | _ => λ _,\n                      (fix distrInter' σ τ (pfσ:[⋂ ANF] σ) (pfτ:[⋃ [⋂ ANF]] τ) : {σ' | σ' ~= σ ∩ τ ∧ [⋃ [⋂ ANF]] σ'} :=\n                         match τ as x return τ = x ⇒ _ with\n                         | τ1 ∪ τ2 => λ _, let (τ1,pfτ1) := distrInter' σ τ1 _ _ in\n                                               let (τ2,pfτ2) := distrInter' σ τ2 _ _ in\n                                               exist _ (τ1 ∪ τ2) _\n                         | _ => λ _, exist _ (σ ∩ τ) _\n                         end eq_refl) σ τ _ pfτ\n             end eq_refl); subst; simpl in *;\n        auto with SubtypeHints.\n    Defined.\n\n    (* Mutually recursive functions for CANF and DANF *)\n    Fixpoint _CANF  (σ : term) : (Omega_free σ ∨ σ = ω) ⇒ {τ | τ ~= σ ∧ CANF τ}\n    with _DANF  (σ : term) : (Omega_free σ ∨ σ = ω) ⇒ {τ | τ ~= σ ∧ DANF τ}.\n    Proof.\n      - refine(match σ with\n               | Var α => λ _, exist _ (Var α) _\n               | σ ⟶ τ => λ pf,\n                            let (σ,pfσ) := _DANF σ _ in\n                            let (τ,pfτ) := _CANF τ _ in\n                            let (σ',pfσ') := distrArrow σ τ _ _ in\n                            exist _ σ' _\n               | σ ∩ τ => λ pf,\n                            let (σ,pfσ) := _CANF σ _ in\n                            let (τ,pfτ) := _CANF τ _ in\n                            exist _ (σ ∩ τ) _\n               | σ ∪ τ => λ pf, let (σ,pfσ) := _CANF σ _ in\n                                let (τ,pfτ) := _CANF τ _ in\n                                let (σ',pfσ') := distrUnion σ τ _ _ in\n                                exist _ σ' _\n               | ω => λ _, exist _ ω _\n               end); try (destruct pf; [|discriminate]); simpl in *;\n          match goal with\n          | |- _ ∨ _ => auto with SubtypeHints\n          | |- _ ∧ _ => split; [trivial|]\n          | _ => idtac\n          end;\n          try (destruct pfσ as [Hσ [?|?]]; [|subst; exfalso; match type of Hσ with\n                                                             | ω ~= ?σ' => apply (Omega_free_Omega σ')\n                                                             end; auto 2 with SubtypeHints; fail]);\n          try (destruct pfτ as [Hτ [?|?]]; [|subst; exfalso; match type of Hτ with\n                                                             | ω ~= ?τ' => apply (Omega_free_Omega τ')\n                                                             end; auto 2 with SubtypeHints; fail]);\n          auto with SubtypeHints.\n      - refine(match σ with\n               | Var α => λ _, exist _ (Var α) _\n               | σ ⟶ τ => λ pf,\n                            let (σ,pfσ) := _DANF σ _ in\n                            let (τ,pfτ) := _CANF τ _ in\n                            let (σ',pfσ') := distrArrow σ τ _ _ in\n                            exist _ σ' _\n               | σ ∪ τ => λ pf,\n                            let (σ,pfσ) := _DANF σ _ in\n                            let (τ,pfτ) := _DANF τ _ in\n                            exist _ (σ ∪ τ) _\n               | σ ∩ τ => λ pf,\n                            let (σ,pfσ) := _DANF σ _ in\n                            let (τ,pfτ) := _DANF τ _ in\n                            let (σ',pfσ') := distrInter σ τ _ _ in\n                            exist _ σ' _\n               | ω => λ _, exist _ ω _\n               end); try (destruct pf; [|discriminate]); simpl in *;\n          match goal with\n          | |- _ ∨ _ => auto with SubtypeHints\n          | |- _ ∧ _ => split; [trivial|]\n          | _ => idtac\n          end;\n          try (destruct pfσ as [Hσ [?|?]]; [|subst; exfalso; match type of Hσ with\n                                                             | ω ~= ?σ' => apply (Omega_free_Omega σ')\n                                                             end; auto 2 with SubtypeHints; fail]);\n          try (destruct pfτ as [Hτ [?|?]]; [|subst; exfalso; match type of Hτ with\n                                                             | ω ~= ?τ' => apply (Omega_free_Omega τ')\n                                                             end; auto 2 with SubtypeHints; fail]);\n          auto with SubtypeHints.\n    Defined.\n\n    (* Main subtyping algorithm *)\n    Definition main_algo : ∀ pair : term * term,\n        DANF (fst pair) ⇒ CANF (snd pair) ⇒\n        {fst pair ≤ snd pair} + {¬ fst pair ≤ snd pair}.\n      refine (Fix wf_main_algo _ _). intros [σ τ] rec.\n      refine (match (σ,τ) as x return x = (σ,τ) ⇒ _ with\n              | (_, ω) => λ eq _ _, left _\n              | (ω, _) => λ eq _ Cτ, right _\n              | (σ1 ∪ σ2, _) => λ eq _ _, match rec (σ1,τ) _ _ _ with\n                                              | left _ => match rec (σ2,τ) _ _ _ with\n                                                          | left _ => left _\n                                                          | right _ => right _\n                                                          end\n                                              | right _ => right _\n                                              end\n              | (_, τ1 ∩ τ2) => λ eq _ _, match rec (σ,τ1) _ _ _ with\n                                              | left _ => match rec (σ,τ2) _ _ _ with\n                                                          | left _ => left _\n                                                          | right _ => right _\n                                                          end\n                                              | right _ => right _\n                                              end\n              | (σ1 ⟶ σ2, τ1 ⟶ τ2) => λ eq Dσ Cτ, match rec (τ1,σ1) _ _ _ with\n                                                      | left _ => match rec (σ2,τ2) _ _ _ with\n                                                                  | left _ => left _\n                                                                  | right HAA => right _\n                                                                  end\n                                                      | right HAA => right _\n                                                      end\n              | (σ1 ∩ σ2, _) => λ eq Dσ Cτ, match rec (σ1,τ) _ _ _ with\n                                                | left _ => left _\n                                                | right _ => match rec (σ2,τ) _ _ _ with\n                                                             | left _ => left _\n                                                             | right _ => right _\n                                                             end\n                                                end\n              | (_, τ1 ∪ τ2) => λ eq Dσ Cτ, match rec (σ,τ1) _ _ _ with\n                                                | left _ => left _\n                                                | right _ => match rec (σ,τ2) _ _ _ with\n                                                             | left _ => left _\n                                                             | right _ => right _\n                                                             end\n                                                end\n              | (Var α, Var β) => λ eq _ _, if 𝕍.eq_dec α β then left _ else right _\n              | _ => λ eq _ _, right _\n              end eq_refl); inv eq; simpl in *;\n        match goal with\n        | |- main_algo_order _ _ => red; simpl; omega\n        | |- ?σ ≤ ?σ => reflexivity\n        | H : ?x |- ?x => assumption\n        | |- CANF _ => auto with SubtypeHints\n        | |- DANF _ => auto with SubtypeHints\n        (* Correctness *)\n        | |- _ ≤ ω => auto with SubtypeHints\n        | |- _ ≤ _ ∩ _ => auto with SubtypeHints\n        | |- _ ∪ _ ≤ _ => auto with SubtypeHints\n        | |- _ ∩ _ ≤ _ => apply Inter_inf_dual; auto\n        | |- _ ≤ _ ∪ _ => apply Union_sup_dual; auto\n        | |- _ ⟶ _ ≤ _ ⟶ _ => apply R_CoContra; trivial\n        (* Completeness *)\n        | |- ¬ ω ≤ _ => apply Omega_IUANF; auto with SubtypeHints\n        | |- ¬ _ ∪ _ ≤ _ => intro; apply Union_sup' in H; auto\n        | |- ¬ _ ≤ _ ∩ _ => intro; apply Inter_inf' in H; auto\n        | |- ¬ ?σ ≤ _ => intro H; apply Ideal_complete in H; [|auto with SubtypeHints];\n                           match σ with\n                           | _ ∩ _ => apply IdealInter in H; inversion H as [H'|H'];\n                                        apply Ideal_correct in H'; auto\n                           | _ ⟶ _ => inv H; [apply HAA; reflexivity| |]; auto with SubtypeHints\n                           | _ => inv H; auto with SubtypeHints\n                           end\n        end.\n    Defined.\n\n    (* Composition of all the previous algorithms *)\n    Definition decide_subtype : ∀ σ τ, {σ ≤ τ} + {¬ σ ≤ τ}.\n    Proof.\n      intros.\n      refine (let (σ1,pfσ) := deleteOmega σ in let (Hσ1,pfσ) := pfσ in\n              let (τ1,pfτ) := deleteOmega τ in let (Hτ1,pfτ) := pfτ in\n              let (σ2,pfσ) := _DANF σ1 pfσ in let (Hσ2,pfσ) := pfσ in\n              let (τ2,pfτ) := _CANF τ1 pfτ in let (Hτ2,pfτ) := pfτ in\n              match main_algo (σ2,τ2) pfσ pfτ with\n              | left H => left _\n              | right H => right _\n              end);\n        rewrite <- Hτ1, <- Hσ1, <- Hτ2, <- Hσ2; assumption.\n    Defined.\n  End SubtypeRelation.\nEnd Types.\n\n(* Module nat_var <: VariableAlphabet. *)\n(*   Definition t := nat. *)\n(*   Definition eq := @eq nat. *)\n(*   Definition eq_equiv : Equivalence eq. *)\n(*   Proof. *)\n(*     constructor. *)\n(*     constructor. *)\n(*     red. *)\n(*     intros. *)\n(*     now symmetry. *)\n(*     red. *)\n(*     intros; etransitivity; eauto. *)\n(*   Defined. *)\n\n(*   Definition eq_dec : ∀ x y : t, {x = y} + {x ≠ y}. *)\n(*     decide equality. *)\n(*   Defined. *)\n(* End nat_var. *)\n\n(* Module foo := nat_var <+ Types. *)\n\n(* Import foo. *)\n(* Definition is_subtype := SubtypeRelation.decide_subtype. *)\n\n(* Definition s1 := Var 0. *)\n(* Definition s2 := Var 1. *)\n(* Definition t1 := Var 2. *)\n(* Definition t2 := Var 3. *)\n\n(* Definition type_1 := (t1 ⟶ s1) ∩ (t2 ⟶ s2). *)\n(* Definition type_2 := (t1 ∪ t2) ⟶ (s1 ∩ s2). *)\n\n(* Eval hnf in (is_subtype type_1 type_2). (* explodes my computer *) *)\n(* Eval hnf in (is_subtype type_2 type_1). (* explodes my computer *) *)\n", "meta": {"author": "cstolze", "repo": "Bull-Subtyping", "sha": "d919199351f7f3b59ff16b86a608acb5f159e537", "save_path": "github-repos/coq/cstolze-Bull-Subtyping", "path": "github-repos/coq/cstolze-Bull-Subtyping/Bull-Subtyping-d919199351f7f3b59ff16b86a608acb5f159e537/coq/Filter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048443, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6637462818045353}}
{"text": "(** * Triangular Numbers over Binary Natural Numbers *)\n\nFrom Coq Require Import\n  Classes.Morphisms Lia Lists.List NArith.NArith.\nFrom DEZ.Justifies Require Export\n  LogicalTheorems NTheorems OptionTheorems ProductTheorems.\nFrom DEZ.Provides Require Import\n  DatatypeTactics RewritingTactics.\n\nImport ListNotations N.\n\n#[local] Open Scope N_scope.\n\n(** A generating function.\n    Sequence A000217. *)\n\nEquations tri (n : N) : N :=\n  tri n := shiftr (n * succ n) 1.\n\nLemma tri_eqn (n : N) : tri n =\n  n * (1 + n) / 2.\nProof. simp tri. arithmetize. auto. Qed.\n\n(** An inverse of the generating function, with a remainder. *)\n\nEquations untri_rem (n : N) : N * N :=\n  untri_rem n := let (s, t) := sqrtrem (succ (shiftl n 3)) in\n    let (q, r) := div_eucl (pred s) 2 in\n    (q, shiftr (t + r * pred (shiftl s 1)) 3).\n\nLemma untri_rem_eqn (n : N) : untri_rem n =\n  let (s, t) := sqrtrem (1 + 8 * n) in\n  let (q, r) := div_eucl (s - 1) 2 in\n  (q, (t + r * (2 * s - 1)) / 8).\nProof.\n  simp untri_rem.\n  arithmetize. destruct_sqrtrem s t est es e0st l1st.\n  arithmetize. destruct_div_eucl q r eqr eq e0qr l1qr.\n  arithmetize. auto.\nQed.\n\n(** A weak inverse of the generating function, rounding down.\n    Sequence A003056. *)\n\nEquations untri (n : N) : N :=\n  untri n := shiftr (pred (sqrt (succ (shiftl n 3)))) 1.\n\nLemma untri_eqn (n : N) : untri n =\n  (sqrt (1 + 8 * n) - 1) / 2.\nProof. simp untri. arithmetize. auto. Qed.\n\n(** A weak inverse of the generating function, rounding up. *)\n\nEquations untri_up (n : N) : N :=\n  untri_up n := match n with\n    | N0 => 0\n    | Npos p => succ (untri (Pos.pred_N p))\n    end.\n\nLemma untri_up_eqn (n : N) : untri_up n =\n  if n =? 0 then 0 else 1 + (sqrt (1 + 8 * (n - 1)) - 1) / 2.\nProof.\n  destruct n as [| p].\n  - auto.\n  - simp untri_up. rewrite pos_pred_spec.\n    arithmetize. rewrite untri_eqn. auto.\nQed.\n\n(** A partial inverse of the generating function. *)\n\nEquations untri_error (n : N) : option N :=\n  untri_error n := let (s, t) := sqrtrem (succ (shiftl n 3)) in\n    if t =? 0 then Some (shiftr (pred s) 1) else None.\n\nLemma untri_error_eqn (n : N) : untri_error n =\n  let (s, t) := sqrtrem (1 + 8 * n) in\n  if t =? 0 then Some ((s - 1) / 2) else None.\nProof.\n  simp untri_error.\n  arithmetize. destruct_sqrtrem s t est es e0st l1st.\n  arithmetize. auto.\nQed.\n\n(** TODO These should emerge from the more general inversion stuff. *)\n\nFrom Coq Require Import Program.Wf.\n\nProgram Fixpoint untri_rem' (a n : N) {measure (to_nat n)} : N * N :=\n  match untri_error n with\n  | Some p => (p, a)\n  | None => untri_rem' (1 + a) (n - 1)\n  end.\nNext Obligation.\n  intros a n f x e.\n  destruct n as [| p].\n  - subst x. inversion e.\n  - lia.\nQed.\n\nProgram Fixpoint untri_down' (n : N) {measure (to_nat n)} : N :=\n  match untri_error n with\n  | Some p => p\n  | None => untri_down' (n - 1)\n  end.\nNext Obligation.\n  intros n f x e.\n  destruct n as [| p].\n  - subst x. inversion e.\n  - lia.\nQed.\n\n(** This is obvious. *)\n\nLemma tri_succ (n : N) : tri (1 + n) = (1 + n) + tri n.\nProof.\n  do 2 rewrite tri_eqn. destruct (Even_mul_consecutive (1 + n)) as [p ep].\n  rewrite ep. rewrite div_Even.\n  destruct (Even_mul_consecutive n) as [q eq].\n  rewrite eq. rewrite div_Even. lia.\nQed.\n\n(** This is strange. *)\n\nLemma tri_what (n p : N) : untri (p + tri (n + p)) = n + p.\nProof.\n  rewrite untri_eqn, tri_eqn.\n  destruct (Even_mul_consecutive (n + p)) as [q eq].\n  rewrite eq. rewrite div_Even.\n  remember (1 + 8 * (p + q)) as r eqn : er.\n  destruct (Even_or_Odd (sqrt r - 1)) as [[s es] | [s es]]; arithmetize.\n  - rewrite es. rewrite div_Even.\n    destruct (sqrt_spec' r) as [l0 l1]; arithmetize. nia.\n  - rewrite es. rewrite div_Odd.\n    destruct (sqrt_spec' r) as [l0 l1]; arithmetize. nia.\nQed.\n\n(** This is also strange. *)\n\nLemma tri_why (a b : N) (l : b <= a) : untri (b + tri a) = a.\nProof.\n  assert (x : exists c : N, a = c + b).\n  { exists (a - b). lia. }\n  destruct x as [c e]. rewrite e. apply tri_what.\nQed.\n\n(** The function [tri] is injective. *)\n\nLemma tri_inj (n p : N) (e : tri n = tri p) : n = p.\nProof.\n  do 2 rewrite tri_eqn in e.\n  destruct (Even_mul_consecutive n) as [q eq],\n  (Even_mul_consecutive p) as [r er]; arithmetize.\n  rewrite eq, er in e. do 2 rewrite div_Even in e. nia.\nQed.\n\n(** The function [tri] is not surjective. *)\n\nLemma tri_nsurj : exists n : N, forall p : N, n <> tri p.\nProof.\n  exists 2. intros p. rewrite tri_eqn.\n  destruct p as [| q _] using peano_ind; arithmetize.\n  - lia.\n  - destruct (Even_mul_consecutive (1 + q)) as [r er]; arithmetize.\n    rewrite er. rewrite div_Even. nia.\nQed.\n\n(** The function [tri] is monotonic. *)\n\nLemma tri_le_mono (n p : N) (l : n <= p) : tri n <= tri p.\nProof.\n  do 2 rewrite tri_eqn.\n  apply div_le_mono; [lia |].\n  apply mul_le_mono; [lia |].\n  apply add_le_mono; [lia |]. lia.\nQed.\n\n(** The function [tri] is strictly monotonic. *)\n\nLemma tri_lt_mono (n p : N) (l : n < p) : tri n < tri p.\nProof.\n  assert (l' : n <= p) by lia.\n  pose proof tri_le_mono n p l' as l''.\n  destruct (eqb_spec (tri n) (tri p)) as [e | f].\n  - apply tri_inj in e.\n    subst p.\n    lia.\n  - lia.\nQed.\n\nLocal Lemma tri_le_expand_le (n p : N) (l : n <= p) :\n  dist n p <= dist (tri n) (tri p).\nProof.\n  pose proof tri_le_mono n p l as l'.\n  do 2 rewrite dist_eqn.\n  destruct (leb_spec n p) as [_ | ?l]; [| lia].\n  destruct (leb_spec (tri n) (tri p)) as [_ | ?l]; [| lia].\n  revert l'.\n  do 2 rewrite tri_eqn.\n  destruct (Even_mul_consecutive n) as [q eq],\n  (Even_mul_consecutive p) as [r er].\n  rewrite eq, er. do 2 rewrite div_Even.\n  intros l'.\n  nia.\nQed.\n\n(** The function [tri] is expansive. *)\n\nLemma tri_le_expand (n p : N) : dist n p <= dist (tri n) (tri p).\nProof.\n  destruct (leb_spec n p) as [l | l].\n  - apply tri_le_expand_le.\n    lia.\n  - rewrite (dist_comm n p), (dist_comm (tri n) (tri p)).\n    apply tri_le_expand_le.\n    lia.\nQed.\n\n(** The function [tri] is expansive around zero. *)\n\nLemma tri_le_expand_0 (n : N) : n <= tri n.\nProof.\n  pose proof tri_le_expand n 0 as l.\n  cbv [dist] in l.\n  change (tri 0) with 0 in l.\n  do 2 rewrite max_0_r in l. do 2 rewrite min_0_r in l.\n  lia.\nQed.\n\n(** The function [untri] is monotonic. *)\n\nLemma untri_le_mono (n p : N) (l : n <= p) : untri n <= untri p.\nProof.\n  do 2 rewrite untri_eqn.\n  apply div_le_mono; [lia |].\n  apply sub_le_mono_r.\n  apply sqrt_le_mono.\n  apply add_le_mono; [lia |].\n  apply mul_le_mono; [lia |]. lia.\nQed.\n\n(** The function [untri] is contractive. *)\n\nLemma untri_le_contract (n p : N) : dist (untri n) (untri p) <= dist n p.\nProof.\n  do 2 rewrite untri_eqn.\n  remember (1 + 8 * n) as q eqn : eq.\n  remember (1 + 8 * p) as r eqn : er. Admitted.\n\n(** The function [untri] is contractive around zero. *)\n\nLemma untri_le_contract_0 (n : N) : untri n <= n.\nProof.\n  rewrite untri_eqn.\n  remember (1 + 8 * n) as p eqn : ep.\n  destruct (Even_or_Odd (sqrt p - 1)) as [[q eq] | [q eq]]; arithmetize.\n  - rewrite eq. rewrite div_Even.\n    destruct (sqrt_spec' p) as [l0 l1]; arithmetize. clear l1; nia.\n  - rewrite eq. rewrite div_Odd.\n    destruct (sqrt_spec' p) as [l0 l1]; arithmetize. clear l1; nia.\nQed.\n\n(** The function [untri] is an inverse of [tri]. *)\n\nTheorem untri_tri (n : N) : untri (tri n) = n.\nProof.\n  rewrite untri_eqn, tri_eqn. destruct (Even_mul_consecutive n) as [p ep].\n  rewrite ep. rewrite div_Even.\n  replace (8 * p) with (4 * (2 * p)) by lia.\n  rewrite <- ep. clear ep.\n  replace (1 + 4 * (n * (1 + n))) with ((1 + 2 * n) * (1 + 2 * n)) by lia.\n  rewrite sqrt_square.\n  replace (1 + 2 * n - 1) with (2 * n) by lia.\n  rewrite div_Even. auto.\nQed.\n\n(** The function [untri_up] is an inverse of [tri]. *)\n\nTheorem untri_up_tri (n : N) : untri_up (tri n) = n.\nProof.\n  rewrite untri_up_eqn.\n  destruct (eqb_spec (tri n) 0) as [e | f].\n  - apply tri_inj. auto.\n  - change 0 with (tri 0) in f. apply f_nequal in f.\n    rewrite tri_eqn. destruct (Even_mul_consecutive n) as [p ep].\n    rewrite ep. rewrite div_Even.\n    remember (1 + 8 * (p - 1)) as q eqn : eq.\n    destruct (Even_or_Odd (sqrt q - 1)) as [[r er] | [r er]]; arithmetize.\n    + rewrite er. rewrite div_Even.\n      destruct (sqrt_spec' q) as [l0 l1]; arithmetize. nia.\n    + rewrite er. rewrite div_Odd.\n      destruct (sqrt_spec' q) as [l0 l1]; arithmetize. nia.\nQed.\n\n(** The function [tri] provides a lower bound for inverses of [untri]. *)\n\nLemma tri_untri (n : N) : tri (untri n) <= n.\nProof.\n  rewrite tri_eqn, untri_eqn.\n  remember (1 + 8 * n) as p eqn : ep.\n  destruct (Even_or_Odd (sqrt p - 1)) as [[q eq] | [q eq]]; arithmetize.\n  - rewrite eq. rewrite div_Even.\n    destruct (Even_mul_consecutive q) as [r er].\n    rewrite er. rewrite div_Even.\n    destruct (sqrt_spec' p) as [l0 l1]; arithmetize. clear l1; nia.\n  - rewrite eq. rewrite div_Odd.\n    destruct (Even_mul_consecutive q) as [r er].\n    rewrite er. rewrite div_Even.\n    destruct (sqrt_spec' p) as [l0 l1]; arithmetize. clear l1; nia.\nQed.\n\n(** The function [tri] provides an upper bound for inverses of [untri]. *)\n\nLemma tri_untri_up (n : N) : n <= tri (untri_up n).\nProof.\n  rewrite tri_eqn, untri_up_eqn.\n  destruct (eqb_spec n 0) as [e | f]; arithmetize.\n  - lia.\n  - remember (1 + 8 * (n - 1)) as p eqn : ep.\n    destruct (Even_or_Odd (sqrt p - 1)) as [[q eq] | [q eq]]; arithmetize.\n    + rewrite eq. rewrite div_Even.\n      destruct (Even_mul_consecutive (1 + q)) as [r er]; arithmetize.\n      rewrite er. rewrite div_Even.\n      destruct (sqrt_spec' p) as [l0 l1]; arithmetize. clear l0; nia.\n    + rewrite eq. rewrite div_Odd.\n      destruct (Even_mul_consecutive (1 + q)) as [r er]; arithmetize.\n      rewrite er. rewrite div_Even.\n      destruct (sqrt_spec' p) as [l0 l1]; arithmetize. clear l0; nia.\nQed.\n\n(** The function [tri] provides bounds\n    for inverses of [untri] and [untri_up]. *)\n\nTheorem tri_untri_untri_up (n : N) : tri (untri n) <= n <= tri (untri_up n).\nProof. auto using tri_untri, tri_untri_up. Qed.\n\n(** The function [untri_rem] can be defined in terms of [tri] and [untri]. *)\n\nLemma untri_rem_tri_untri (n : N) : untri_rem n = (untri n, n - tri (untri n)).\nProof.\n  rewrite untri_rem_eqn, tri_eqn, untri_eqn.\n  repeat rewrite <- sqrtrem_sqrt. cbv [fst snd].\n  destruct_sqrtrem s t est es e0st l1st.\n  clear est es l1st.\n  repeat rewrite <- (div_eucl_div (s - 1) 2). cbv [fst snd].\n  destruct_div_eucl q r eqr eq e0qr l1qr.\n  clear eqr eq. f_equal.\n  destruct (Even_mul_consecutive q) as [u eu].\n  rewrite eu. rewrite div_Even.\n  assert (or' : r = 0 \\/ r = 1) by lia. clear l1qr.\n  (** This case analysis is technically unnecessary,\n      but speeds up [nia] considerably. *)\n  destruct or' as [er | er]; subst r; arithmetize.\n  - change 8 with (2 * (2 * 2)). repeat rewrite <- (div_div _ 2) by lia.\n    rename t into t0.\n    destruct (Even_or_Odd t0) as [[t1 et1] | [t1 et1]]; arithmetize.\n    + rewrite et1. rewrite div_Even.\n      destruct (Even_or_Odd t1) as [[t2 et2] | [t2 et2]]; arithmetize.\n      * rewrite et2. rewrite div_Even.\n        destruct (Even_or_Odd t2) as [[t3 et3] | [t3 et3]]; arithmetize.\n        -- rewrite et3. rewrite div_Even. subst t0 t1 t2. nia.\n        -- rewrite et3. rewrite div_Odd. subst t0 t1 t2. nia.\n      * rewrite et2. rewrite div_Odd.\n        destruct (Even_or_Odd t2) as [[t3 et3] | [t3 et3]]; arithmetize.\n        -- rewrite et3. rewrite div_Even. subst t0 t1 t2. nia.\n        -- rewrite et3. rewrite div_Odd. subst t0 t1 t2. nia.\n    + rewrite et1. rewrite div_Odd.\n      destruct (Even_or_Odd t1) as [[t2 et2] | [t2 et2]]; arithmetize.\n      * rewrite et2. rewrite div_Even.\n        destruct (Even_or_Odd t2) as [[t3 et3] | [t3 et3]]; arithmetize.\n        -- rewrite et3. rewrite div_Even. subst t0 t1 t2. nia.\n        -- rewrite et3. rewrite div_Odd. subst t0 t1 t2. nia.\n      * rewrite et2. rewrite div_Odd.\n        destruct (Even_or_Odd t2) as [[t3 et3] | [t3 et3]]; arithmetize.\n        -- rewrite et3. rewrite div_Even. subst t0 t1 t2. nia.\n        -- rewrite et3. rewrite div_Odd. subst t0 t1 t2. nia.\n  - change 8 with (2 * (2 * 2)). repeat rewrite <- (div_div _ 2) by lia.\n    rewrite add_sub_assoc by lia.\n    remember (t + 2 * s - 1) as t0 eqn : et0.\n    destruct (Even_or_Odd t0) as [[t1 et1] | [t1 et1]]; arithmetize.\n    + rewrite et1. rewrite div_Even.\n      destruct (Even_or_Odd t1) as [[t2 et2] | [t2 et2]]; arithmetize.\n      * rewrite et2. rewrite div_Even.\n        destruct (Even_or_Odd t2) as [[t3 et3] | [t3 et3]]; arithmetize.\n        -- rewrite et3. rewrite div_Even. subst t0 t1 t2. nia.\n        -- rewrite et3. rewrite div_Odd. subst t0 t1 t2. nia.\n      * rewrite et2. rewrite div_Odd.\n        destruct (Even_or_Odd t2) as [[t3 et3] | [t3 et3]]; arithmetize.\n        -- rewrite et3. rewrite div_Even. subst t0 t1 t2. nia.\n        -- rewrite et3. rewrite div_Odd. subst t0 t1 t2. nia.\n    + rewrite et1. rewrite div_Odd.\n      destruct (Even_or_Odd t1) as [[t2 et2] | [t2 et2]]; arithmetize.\n      * rewrite et2. rewrite div_Even.\n        destruct (Even_or_Odd t2) as [[t3 et3] | [t3 et3]]; arithmetize.\n        -- rewrite et3. rewrite div_Even. subst t0 t1 t2. nia.\n        -- rewrite et3. rewrite div_Odd. subst t0 t1 t2. nia.\n      * rewrite et2. rewrite div_Odd.\n        destruct (Even_or_Odd t2) as [[t3 et3] | [t3 et3]]; arithmetize.\n        -- rewrite et3. rewrite div_Even. subst t0 t1 t2. nia.\n        -- rewrite et3. rewrite div_Odd. subst t0 t1 t2. nia.\nQed.\n\n(** The function [untri_rem] truly produces a remainder. *)\n\nLemma tri_untri_untri_rem (n : N) : n - tri (untri n) <= untri n.\nProof.\n  rewrite tri_eqn, untri_eqn.\n  remember (1 + 8 * n) as p eqn : ep.\n  destruct (Even_or_Odd (sqrt p - 1)) as [[q eq] | [q eq]]; arithmetize.\n  - rewrite eq. rewrite div_Even.\n    destruct (Even_mul_consecutive q) as [r er].\n    rewrite er. rewrite div_Even.\n    destruct (sqrt_spec' p) as [l0 l1]; arithmetize. clear l0; nia.\n  - rewrite eq. rewrite div_Odd.\n    destruct (Even_mul_consecutive q) as [r er].\n    rewrite er. rewrite div_Even.\n    destruct (sqrt_spec' p) as [l0 l1]; arithmetize. clear l0; nia.\nQed.\n\n(** The function [untri_rem] is an inverse of [tri]. *)\n\nTheorem untri_rem_tri (n : N) : untri_rem (tri n) = (n, 0).\nProof. rewrite untri_rem_tri_untri. rewrite untri_tri. f_equal. lia. Qed.\n\n(** The function [tri] is an inverse of [untri_rem]. *)\n\nTheorem tri_untri_rem (n : N) : prod_uncurry (flip add o tri) (untri_rem n) = n.\nProof.\n  rewrite untri_rem_tri_untri.\n  cbv [prod_uncurry compose flip fst snd].\n  pose proof tri_untri n as l.\n  lia.\nQed.\n\n(** The function [untri_error] can be defined in terms of [untri_rem]. *)\n\nLemma untri_error_untri_rem (n : N) :\n  untri_error n =\n  let (u, t1) := untri_rem n in\n  if t1 =? 0 then Some u else None.\nProof.\n  pose proof tri_untri n as l. revert l.\n  rewrite untri_error_eqn. rewrite untri_rem_tri_untri.\n  rewrite untri_eqn. rewrite tri_eqn.\n  rewrite <- sqrtrem_sqrt. cbv [fst snd].\n  destruct_sqrtrem s t est es e0st l1st.\n  clear est es.\n  rewrite <- (div_eucl_div (s - 1) 2). cbv [fst snd].\n  destruct_div_eucl q r eqr eq e0qr l1qr.\n  clear eqr eq.\n  destruct (Even_mul_consecutive q) as [u eu].\n  rewrite eu. rewrite div_Even. intros l.\n  assert (or' : r = 0 \\/ r = 1) by lia. clear l1qr.\n  destruct (eqb_spec t 0) as [e0 | f0],\n  (eqb_spec (n - u) 0) as [e1 | f1]; arithmetize.\n  + auto.\n  + exfalso. clear l; nia.\n  + exfalso. clear l; nia.\n  + auto.\nQed.\n\n(** The function [untri_error] is a lifted inverse of [tri]. *)\n\nTheorem untri_error_tri (n : N) : untri_error (tri n) = Some n.\nProof. rewrite untri_error_untri_rem. rewrite untri_rem_tri. auto. Qed.\n\n(** A lifting of the function [tri] is an inverse of [untri_error]. *)\n\nTheorem tri_untri_error (n p : N)\n  (e : option_map tri (untri_error n) = Some p) : n = p.\nProof.\n  rewrite untri_error_untri_rem in e.\n  rewrite untri_rem_tri_untri in e.\n  destruct (eqb_spec (n - tri (untri n)) 0) as [e0 | f0].\n  - cbv [option_map] in e.\n    injection e; intros e1. clear e.\n    rewrite <- e1. clear e1.\n    pose proof sub_add _ _ (tri_untri n) as e2. lia.\n  - cbv [option_map] in e.\n    inversion e.\nQed.\n\n(** An inverse of the generating function,\n    with a remainder as an exact quotient. *)\n\nProgram Definition untri_quotrem (n : N) :\n  {x : N * N $ Squash (let (p, q) := x in tri p + q < tri (1 + p))} :=\n  Sexists _ (untri_rem n) _.\nNext Obligation.\n  intros n. cbv beta. apply squash. rewrite untri_rem_tri_untri.\n  rewrite tri_succ.\n  pose proof tri_untri_untri_rem n as e.\n  lia.\nQed.\n\nGlobal Instance tri_wd : Proper (Logic.eq ==> Logic.eq) tri.\nProof. intros n p e. auto using f_equal. Qed.\n\nGlobal Instance untri_wd : Proper (Logic.eq ==> Logic.eq) untri.\nProof. intros n p e. auto using f_equal. Qed.\n\nGlobal Instance le_tri_wd : Proper (N.le ==> N.le) tri.\nProof. intros n p l. apply tri_le_mono. lia. Qed.\n\nGlobal Instance le_untri_wd : Proper (N.le ==> N.le) untri.\nProof. intros n p l. apply untri_le_mono. lia. Qed.\n", "meta": {"author": "Tuplanolla", "repo": "dez", "sha": "c2eadc2e032094c3504ec3803c000dba4feb547e", "save_path": "github-repos/coq/Tuplanolla-dez", "path": "github-repos/coq/Tuplanolla-dez/dez-c2eadc2e032094c3504ec3803c000dba4feb547e/fowl/Justifies/NTriangularNumbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6637462789147573}}
{"text": "(*|\n################################################\nUnderstanding the ``intros`` keyword work in Coq\n################################################\n\n:Link: https://stackoverflow.com/q/70482977\n|*)\n\n(*|\nQuestion\n********\n|*)\n\nTheorem law_of_contradiction : forall (P Q : Prop), P /\\ ~P -> Q.\nProof.\n  intros P Q P_and_not_P.\n  destruct P_and_not_P as [P_holds not_P].\nAbort. (* .none *)\n\n(*|\nI'm trying to reaaaally understand the ``intros`` keyword. Let's say\nthat we want to prove ``P /\\ ~P -> Q``. Ok, somehow ``intros P Q``\nintroduce ``P`` and ``Q``. But what does it mean? Does it recognize\nthe ``P`` and ``Q`` from the thing to be proven? What about\n``P_and_not_P``? What is it? Why for ``P`` and ``Q`` it uses the same\nname, but for ``P_and_not_P`` is defining a name?\n\nUPDATE:\n=======\n\nIt looks like it's matching term by term:\n|*)\n\nTheorem modus_tollens : forall (P Q : Prop), (P -> Q) -> ~Q -> ~P.\nProof.\n  intro P. intro Q. intro P_implies_Q. intro not_q. intro not_p.\n\n(*| gives |*)\n\n  Show. (* .unfold .messages *)\nAbort. (* .none *)\n\n(*|\nAnswer\n******\n\nWhat ``intro A`` (equivalent to ``intros A``) does: if you have a goal\nof the form ``forall (P : _), ...``, it renames ``P`` to ``A``,\nremoves the ``forall`` from the beginning of the goal and puts an\nassumption ``A`` into the goal.\n|*)\n\nTheorem law_of_contradiction : forall (P Q : Prop), P /\\ ~P -> Q. (* .none *)\nProof. (* .none *)\n  (* Starting goal *)\n  Show. (* .unfold .messages *)\n  (* Goal after [intros A] *)\n  intros A. (* .none *) Show. (* .unfold .messages *)\nAbort. (* .none *)\n\n(*|\nIf you do ``intros P Q``, by picking the names already in the goal, no\nrenaming is necessary so there is no change in names.\n\nThe other cases of ``intros`` you mention are special cases of that\none behavior.\n\n**Implications** in Coq are quantifications where the assumption is\nnot named: ``P /\\ ~ P -> Q`` is equivalent to ``forall (H : P /\\ ~P),\nQ``, noting that ``H`` is not used in the body ``Q``. Hence, when you\ndo ``intros P_and_not_P``, you are renaming ``H``, which is not used\nso you don't see a change in the goal. You can disable pretty printing\nto see that.\n|*)\n\nUnset Printing Notations.\nTheorem law_of_contradiction : forall (P Q : Prop), P /\\ ~P -> Q. (* .none *)\nProof. (* .none *)\n  (* Starting goal; a name that is not used becomes \"_\" *)\n  Show. (* .unfold .messages *)\n  (* After [intros P Q R] *)\n  intros P Q R. (* .none *) Show. (* .unfold .messages *)\nAbort. (* .none *)\n\n(*|\nThe **negation** of ``P``, denoted ``~P``, is defined as ``P ->\nFalse`` in Coq (this is typical in intuitionistic logic, other logics\nmight differ). You can see that in action with the tactic ``unfold\nnot``\n|*)\n\nSet Printing Notations. (* .none *)\nTheorem modus_tollens : forall (P Q : Prop), (P -> Q) -> ~Q -> ~P. (* .none *)\nProof. (* .none *)\n  (* Starting goal *)\n  Show. (* .unfold .messages *)\n  (* After [unfold not] *)\n  unfold not. (* .none *) Show. (* .unfold .messages *)\n  (* After [intros P Q R S T] *)\n  intros P Q R S T. (* .none *) Show. (* .unfold .messages *)\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/understanding-the-intros-keyword-work-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.6637462701042143}}
{"text": "(** matrix_analysis.v: stability analysis for leapfrog integration\n  of a simple harmonic oscillator.\n Copyright (C) 2021-2022  Ariel Eileen Kellison.\n*)\nFrom Coq Require Import ZArith Reals Psatz.\nFrom Coq Require Import Bool Arith.Arith.\nRequire Import real_lemmas real_model matrix_lemmas.\n\nFrom Coquelicot Require Import Coquelicot.\nRequire Import Interval.Tactic.\n\nImport Bool.\n\nSet Bullet Behavior \"Strict Subproofs\". \n\nLemma prod_equal: forall {A B} (x y: A*B) x1 x2 y1 y2,\n  x = (x1,x2) ->\n  y = (y1,y2) ->\n  x1=y1 -> x2 = y2 -> x=y.\nProof.\ndestruct x,y; simpl; intros; congruence.\nQed.\n\nLtac matrix_ext :=\n  lazymatch goal with \n  | |- @eq (matrix _ _) _ _ => idtac\n  | _ => fail \"matrix_ext must be applied to a goal of the form, @eq (matrix _ _) _ _\"\n end;\nrepeat\n(lazymatch goal with |- @eq ?t _ _ =>\n  lazymatch t with \n  | matrix _ _ => idtac\n  | Tn _ _ => idtac\n  | prod _ unit => idtac\n  end\n end;\n eapply prod_equal; [reflexivity | reflexivity | | try apply (eq_refl tt)]).\n\n(** An upper bound σb on the singular values of a square matrix A ∈ Mn(C) \n      is given by an upper bound on the eigenvalues of A'A *)\nDefinition sv_bound (n: nat ) (A : @matrix C n n) (σb : R):=  \n  let ATA := Mmult (matrix_conj_transpose n n A) A (* the Gram matrix A'A *) in\n  let λb := σb^2 in \n  0 <= σb /\\\n  exists (V Λ : @matrix C n n),\n         Mmult ATA V = Mmult V Λ\n      /\\ is_orthogonal_matrix n V\n      /\\ diag_pred n Λ   \n      /\\ (forall (i : nat), (i < n)%nat ->\n         (coeff_mat zero Λ i i) = RtoC (Re (coeff_mat zero Λ i i)) (* elements of Λ are real *)\n         /\\ 0 <= Re (coeff_mat zero Λ i i) <= λb) (* λb is positive and at least as large as all elements of Λ *)\n.\n\n\nDefinition two_norm_bound (n: nat ) (A : @matrix C n n) (σ : R):=  \n  forall (u : @matrix C n 1), \n  vec_two_norm n (Mmult A u) <=  σ * vec_two_norm n u\n.\n\n\n(** any vector x ∈ Cn can be written as a linear combination of columns of an \n    orthogonal matrix V ∈ Cnxn *)\nLemma vectors_in_basis (n : nat) : \n forall (x : @matrix C n 1), \n forall (V : @matrix C n n), is_orthogonal_matrix n V ->\n exists (a: @matrix C n 1),  x = Mmult V a.\nProof.\nintros.\nunfold is_orthogonal_matrix in H; destruct H as (Ha & Hb).\nexists (Mmult (matrix_conj_transpose n n V) x). \nrewrite Mmult_assoc.\nrewrite Hb.\nrewrite Mmult_one_l; auto.\nQed.\n\n(** the leapfrog transition matrix *)\nDefinition M (h: R) : @matrix C 2 2 := \n  let a := 0.5 * h^2 in \n   [ [ (1-a, 0),  (-0.5 * h * (2 - a), 0) ],\n     [ (h, 0),      (1-a, 0) ] ].\n\n(** ideal solution vector *)\nDefinition pq_vector (h: R) (p q : R -> R) (t : R) : @matrix C 2 1 :=\n   [ [ (p t, 0) ] ,\n     [ (q t, 0) ] ].\n\n(** arbitrary solution vector *)\nDefinition s_vector (ic: R * R) : @matrix C 2 1 := \n [ [ (fst ic, 0) ] ,\n   [ (snd ic, 0) ] ].\n\n(** equivalence between matrix update and leapfrog step*)\nLemma transition_matrix_equiv:\n  forall (ic : R * R) (h : R),  \n  Mmult (M h) (s_vector ic) = s_vector (leapfrog_stepR h ic).\nProof.\nintros. destruct ic.\nmatrix_ext; cbv [sum_n sum_n_m Iter.iter_nat Iter.iter coeff_mat]; simpl;\nunfold plus, mult; simpl; unfold Cplus, Cmult, zero; simpl;\nunfold ω; f_equal; nra.\nQed.\n\nLemma transition_matrix_equiv_iternR:\n  forall (ic : R * R) (h : R) (n : nat), \n  Mmult (Mpow 2 n (M h)) (s_vector ic) = s_vector (iternR ic h n).\nProof.\ninduction n.\n-\nunfold Mpow.\nrewrite M_ID_equiv_M1, Mmult_one_l.\nreflexivity.\n-\nchange (S n) with (1+n)%nat.\nrewrite <- Mpow_pows_plus.\nunfold Mpow at 1.\nrewrite M_ID_equiv_M1, Mmult_one_l.\nrewrite <- Mmult_assoc. rewrite IHn.\nrewrite transition_matrix_equiv.\nrewrite step_iternR. auto.\nQed.\n\n(** The eigenvalues of the transition matrix *)\nDefinition lambda_1 (h : R) : C := (1 -0.5 * h^2 , -h * sqrt(2 - h) * 0.5 * sqrt(h + 2)). \nDefinition lambda_2 (h : R) : C := (1 -0.5 * h^2 ,  h * sqrt(2 - h) * 0.5 * sqrt(h + 2)).\nDefinition eigenvalue_vector (h : R) : @matrix C 2 1 :=\n [ [ lambda_1 h ],\n   [ lambda_2 h ] ].\n\nDefinition eigenvalue_matrix (h : R) : @matrix C 2 2 :=\n  [ [ lambda_1 h , C0 ] , [ C0 , lambda_2 h ] ].\n\n(** The eigenvectors of the transition matrix *)\nDefinition eV_1 (h : R) : @matrix C 2 1 :=\n [ [ (0 , -0.5 * sqrt(4 - h^2)) ] ,\n   [ C1 ] ].\n\nDefinition eV_2 (h : R) : @matrix C 2 1 :=\n [ [ (0 ,  0.5 * sqrt(4 - h^2))] ,\n   [ C1 ] ].\n\nDefinition eigenvector_matrix (h : R) : @matrix C 2 2 :=\n [ [ (0 , -0.5 * sqrt(4 - h^2)), (0 ,  0.5 * sqrt(4 - h^2)) ],\n   [ C1,                                 C1 ]].\n\n(** We define the Gram matrix MTM for the transition matrix. The eigenvalues of the matrix MTM are the \n    singular values of the transition matrix *)\nDefinition MTM (h : R) : @matrix C 2 2 :=\n [ [  (0.25 * h^4 + 1, 0), (0.125 * h^3*(2 - h^2),0) ],\n   [ (0.125 * h^3*(2 - h^2),0),  (0.0625 * h^6 - 0.25*h^4 + 1, 0)] ].\n\n(** The eigenvalues of MTM *)\nDefinition MTM_lambda_1 (h : R) : R := \nlet a:= sqrt(h^6 + 64) in\nlet A:= (h^10 - h^7*a + 4*h^6 + 64*h^4 - 4*h^3*a - 32*h*a + 256) * (h^2 -2)^2 in\nlet b:= (h^3 - 8*h + a)^2 in \nA / (2*(h^4  - 4*h^2 + 4) * (b + 16 * (h^2 - 2)^2))\n.\n\nDefinition MTM_lambda_2 (h : R) : R := \nlet a:= sqrt(h^6 + 64) in\nlet A:= (h^10 + h^7*a + 4*h^6 + 64*h^4 + 4*h^3*a + 32*h*a + 256) * (h^2 -2)^2 in\nlet b:= (-h^3 + 8*h + a)^2 in \nA / (2*(h^4  - 4*h^2 + 4) * (b + 16 * (h^2 - 2)^2))\n.\n\nDefinition MTM_eigenvalue_vector (h : R) : @matrix R 2 1 :=\n [ [ MTM_lambda_1 h ],\n   [ MTM_lambda_2 h ] ].\n\nDefinition MTM_eigenvalue_matrix (h : R) : @matrix C 2 2 :=\n  [ [ RtoC (MTM_lambda_1 h), C0 ], \n    [ C0,   RtoC (MTM_lambda_2 h) ] ].\n\n(** The eigenvectors of MTM, numbered to match their eigenvalues *)\nDefinition MTM_eV_1 (h: R) : @matrix C 2 1 := mk_matrix 2 1 ( fun i _ =>\n  if (Nat.eqb i 0) then RtoC((h^3 - 8*h + sqrt(h^6 + 64))/((h^2 - 2)*sqrt(Rabs((h^3 - 8*h + sqrt(h^6 + 64))/(h^2 - 2))^2 + 16))) else\n    RtoC(4/sqrt(Rabs((h^3 - 8*h + sqrt(h^6 + 64))/(h^2 - 2))^2 + 16)))\n.\nDefinition MTM_eV_2 (h: R) : @matrix C 2 1 := mk_matrix 2 1 ( fun i _ =>\n  if (Nat.eqb i 0) then RtoC((h^3 - 8*h - sqrt(h^6 + 64))/((h^2 - 2)*sqrt(Rabs((-h^3 + 8*h + sqrt(h^6 + 64))/(h^2 - 2))^2 + 16))) else\n    RtoC(4/sqrt(Rabs((-h^3 + 8*h + sqrt(h^6 + 64))/(h^2 - 2))^2 + 16)))\n.\n\n(** we use MTM_eigenvector_matrix as the matrix V in e.g. M V = V L , where L is the diagonal matrix of eigenvalues\n   and M is the transition matrix.*)\nDefinition MTM_eigenvector_matrix (h : R) : @matrix C 2 2 :=\n  [ [ coeff_mat zero (MTM_eV_1 h) 0 0,  coeff_mat zero (MTM_eV_2 h) 0 0 ],\n    [ coeff_mat zero (MTM_eV_1 h) 1 0, coeff_mat zero (MTM_eV_2 h) 1 0 ] ].\n\n(* M * V = V * L *)\nLemma eigens_correct (h : R) :\n  0 <= h <= 2 -> \n  Mmult (M h) (eigenvector_matrix h) = \n  Mmult (eigenvector_matrix h) (eigenvalue_matrix h).\nProof.\nintros.\nassert (sqrt (2-h) * sqrt (h+2) = sqrt (4-h*h))\n  by (rewrite <- sqrt_mult by lra; f_equal; lra).\npose proof (sqrt_def (4-h*h) ltac:(nra)).\nmatrix_ext.\nall: change (Init.Nat.pred 2) with (S 0);\nrepeat rewrite sum_Sn;\nrepeat rewrite sum_O;\nunfold M, eigenvector_matrix, eigenvalue_matrix, \n  eV_1, eV_2, lambda_1, lambda_2, matrix_lemmas.C1,\n coeff_mat; simpl.\nall:\nunfold mult, plus; simpl;\nrewrite ?mult_aux1, ?mult_aux2, ?mult_aux3;\nrewrite ?Cmult_0_r, ?Cplus_0_r;\nunfold Cplus; simpl;\nrewrite ?Rmult_0_l, ?Rmult_0_r, ?Rmult_1_r, ?Rplus_0_l, ?Rplus_0_r, ?Rminus_0_l;\nrewrite <- H0 in *;\nf_equal; try nra.\nQed.\n\nLemma MTM_aux  (h : R) :\n  Mmult (matrix_conj_transpose _ _ (M h)) (M h) = MTM h.\nProof.\nunfold MTM.\nmatrix_ext;\nchange (Init.Nat.pred 2) with (S 0);\nrewrite ?sum_Sn, ?sum_O;\nunfold M, matrix_conj_transpose, Cconj;\nrepeat rewrite coeff_mat_bij by lia;\nunfold coeff_mat; simpl;\nunfold plus, mult; simpl;\ncbv [Cmult Cplus]; simpl;\nf_equal; nra.\nQed.\n\nLemma div_eq_0 : \nforall a b , b <> 0 -> a = 0 -> a / b = 0.\nProof.\nintros.\nsubst.\nfield.\nauto.\nQed.\n\nLemma sqr_def : forall x, x^2 = x*x.\nProof. intros; nra. Qed.\n\nLemma pow2'_sqrt : forall x n, \n  0 <= x ->\n  sqrt x ^ (S (S n)) = x * sqrt x ^ n.\nProof.\nintros.\nsimpl.\nrewrite <- Rmult_assoc.\nf_equal.\napply sqrt_def; auto.\nQed.\n\n(* MTM * V = V * L *)\nTheorem MTM_eigens_correct (h : R) :\n  0 < h  < 1.41 -> \n  Mmult (MTM h) (MTM_eigenvector_matrix h) = \n  Mmult (MTM_eigenvector_matrix h) (MTM_eigenvalue_matrix h).\nProof.\nintros.\nmatrix_ext;\nchange (Init.Nat.pred 2) with (S 0);\nrewrite ?sum_Sn, ?sum_O;\nunfold MTM, MTM_eigenvector_matrix, MTM_eigenvalue_matrix;\nrepeat rewrite coeff_mat_bij;\nunfold coeff_mat; simpl;\nchange mult with Cmult;\nchange plus with Cplus;\nunfold RtoC;\ncbv [Cplus Cmult]; simpl;\nrewrite ?Rmult_0_l, ?Rmult_0_r;\nunfold C0;\nrewrite ?Rminus_0_r, ?Rplus_0_r, ?Rmult_1_r.\n-\nf_equal.\nunfold MTM_lambda_1, MTM_eV_1.\nrewrite <- Rabs_mult.\nrepeat match goal with |-context [Rabs( (?a / ?b) * (?a / ?b)) ] =>\nreplace ( (a / b) * (a / b)) with ( (a/b)^2) by nra\nend.\nrepeat rewrite Rabs_sqr_le.\nrepeat rewrite pow2_abs.\napply Rminus_diag_uniq.\nfield_simplify.\nrepeat rewrite pow2_sqrt; try nra.\nfield_simplify.\nreplace (sqrt (h * (h * (h * (h * (h * h)))) + 64))\nwith (sqrt (h ^ 6 + 64)).\nrepeat rewrite Rmult_assoc.\nrepeat rewrite sqrt_def.\nfield_simplify.\napply div_eq_0.\nset (x := sqrt _).\nset (y := sqrt _).\ninterval with ( i_bisect h, i_taylor h, i_degree 7).\nset (x := sqrt _). nra.\nset (x := sqrt _).\nset (y := sqrt _).\ninterval with ( i_bisect h, i_taylor h, i_degree 3).\nall: try repeat split; try interval with ( i_bisect h, i_taylor h, i_degree 3).\nf_equal; nra.\n-\nf_equal.\nunfold MTM_lambda_1, MTM_lambda_2.\nrewrite <- Rabs_mult.\nrepeat match goal with |-context [Rabs( (?a / ?b) * (?a / ?b)) ] =>\nreplace ( (a / b) * (a / b)) with ( (a/b)^2) by nra\nend.\nrepeat rewrite Rabs_sqr_le.\nrepeat rewrite pow2_abs.\napply Rminus_diag_uniq.\nfield_simplify.\nrepeat rewrite pow2_sqrt; try nra.\nfield_simplify.\nreplace (sqrt (h * (h * (h * (h * (h * h)))) + 64))\nwith (sqrt (h ^ 6 + 64)).\nrepeat rewrite Rmult_assoc.\nrepeat rewrite sqrt_def.\nfield_simplify.\napply div_eq_0.\nset (x := sqrt _).\nset (y := sqrt _).\ninterval with ( i_bisect h, i_taylor h, i_degree 3).\nset (x := sqrt _). nra.\nset (x := sqrt _).\nset (y := sqrt _).\ninterval with ( i_bisect h, i_taylor h, i_degree 3).\nall: try repeat split; try interval with ( i_bisect h, i_taylor h, i_degree 3).\nf_equal; nra.\n-\nf_equal.\nunfold MTM_lambda_1, MTM_lambda_2.\nrewrite <- Rabs_mult.\nrepeat match goal with |-context [Rabs( (?a / ?b) * (?a / ?b)) ] =>\nreplace ( (a / b) * (a / b)) with ( (a/b)^2) by nra\nend.\nrepeat rewrite Rabs_sqr_le.\nrepeat rewrite pow2_abs.\napply Rminus_diag_uniq.\nfield_simplify.\nrepeat rewrite pow2_sqrt; try nra.\nfield_simplify.\nreplace (sqrt (h * (h * (h * (h * (h * h)))) + 64))\nwith (sqrt (h ^ 6 + 64)).\nrepeat rewrite Rmult_assoc.\nrepeat rewrite sqrt_def.\nfield_simplify.\napply div_eq_0.\nset (x := sqrt _).\nset (y := sqrt _).\ninterval with ( i_bisect h, i_taylor h, i_degree 3).\nset (x := sqrt _). nra.\nset (x := sqrt _).\nset (y := sqrt _).\ninterval with ( i_bisect h, i_taylor h, i_degree 3).\nall: try repeat split; try interval with ( i_bisect h, i_taylor h, i_degree 3).\nf_equal; nra.\n-\nf_equal.\nunfold MTM_lambda_1, MTM_lambda_2.\nrewrite <- Rabs_mult.\nrepeat match goal with |-context [Rabs( (?a / ?b) * (?a / ?b)) ] =>\nreplace ( (a / b) * (a / b)) with ( (a/b)^2) by nra\nend.\nrepeat rewrite Rabs_sqr_le.\nrepeat rewrite pow2_abs.\napply Rminus_diag_uniq.\nfield_simplify.\nrepeat rewrite pow2_sqrt; try nra.\nfield_simplify.\nreplace (sqrt (h * (h * (h * (h * (h * h)))) + 64))\nwith (sqrt (h ^ 6 + 64)).\nrepeat rewrite Rmult_assoc.\nrepeat rewrite sqrt_def.\nfield_simplify.\napply div_eq_0.\nset (x := sqrt _).\nset (y := sqrt _).\ninterval with ( i_bisect h, i_taylor h, i_degree 3).\nset (x := sqrt _). nra.\nset (x := sqrt _).\nset (y := sqrt _).\ninterval with ( i_bisect h, i_taylor h, i_degree 3).\nall: try repeat split; try interval with ( i_bisect h, i_taylor h, i_degree 3).\nf_equal; nra.\nQed.\n\nLemma Cmod_RtoC (a : R): \n  0 <= a ->\nCmod (RtoC a) = a.\nProof.\nunfold RtoC.\nunfold Cmod, fst, snd.\nrewrite pow_i by lia.\nrewrite Rplus_0_r.\napply sqrt_pow2.\nQed.\n\nLemma sv_vector_implies (A V Λ : matrix 2 2):\n   is_orthogonal_matrix 2 V ->\n   diag_pred 2 Λ ->\n   Mmult (Mmult (matrix_conj_transpose 2 2 A) A) V = Mmult V Λ -> \n  forall (k :nat), (k < 2)%nat ->\n  let x := mk_matrix 2 1\n  (fun i0 _ : nat =>\n     (coeff_mat zero V i0 k)) in\n  (Mmult (matrix_conj_transpose 2 1 x) (Mmult (Mmult (matrix_conj_transpose 2 2 A) A) x)) =\n  (Mmult (matrix_conj_transpose 2 1 x) (mat_coeff_mult (coeff_mat zero Λ k k) 2 1 x)).\nProof.\nintros.\nunfold Mmult at 1 3 in H1.\nrewrite <- mk_matrix_ext in H1.\napply mk_matrix_ext; intros.\napply sum_n_ext_loc => m Hm.\nassert (i = 0)%nat by lia; subst i.\nassert (j = 0)%nat by lia; subst j.\nsubst x.\nred in H0.\nchange (@zero C_AbelianGroup) with (@zero C_Ring) in *.\nunfold Mmult at 1. \nrewrite coeff_mat_bij by lia.\nsimpl.\nf_equal.\netransitivity; [apply H1; lia | simpl ].\nunfold mat_coeff_mult.\nrewrite !coeff_mat_bij by lia.\nrewrite !sum_Sn, !sum_O.\ndestruct m as [|[|]]; try lia;\ndestruct k as [|[|]]; try lia;\nmatch goal with |- context [coeff_mat _ Λ ?x ?y] =>  rewrite (H0 x y) by lia end;\nrewrite ?mult_zero_l, ?mult_zero_r, ?plus_zero_l, ?plus_zero_r;\napply Cmult_comm.\nQed.\n\nLemma orthgonal_matrix_no_zero_columns:\n forall (V: matrix 2 2),\n  is_orthogonal_matrix 2 V ->\n  forall i, \n  (i < 2)%nat ->\n 0 < vec_two_norm 2 [[coeff_mat zero V 0 i], [coeff_mat zero V 1 i]].\nProof.\nintros V H2 i Hi.\nassert (0 <> vec_two_norm 2 [ [ coeff_mat zero V 0 i ] , [ coeff_mat zero V 1 i ] ]).\n2: assert (0 <= vec_two_norm 2 [[coeff_mat zero V 0 i], [coeff_mat zero V 1 i]])\n      by apply sqrt_pos;\n      lra.\nintro.\nassert (   [[coeff_mat zero V 0 i], [coeff_mat zero V 1 i]] = [ [C0], [C0] ]). {\n clear - H.\n set (a := coeff_mat _ _ _ _) in *. clearbody a.\n set (b := coeff_mat _ _ _ _) in *. clearbody b.\n symmetry in H.\n apply sqrt_eq_0 in H; [ | apply sqrt_pos].\n unfold Cmod in H; simpl in H.\n unfold coeff_mat in H; simpl in H.\n apply sqrt_eq_0 in H; [ | nra].\n destruct a as [ar ai], b as [br bi]. simpl in *. unfold C0.\n rewrite ?Rmult_1_r, ?Rplus_0_r in H.\n ring_simplify in H.\n replace (ar^4) with (ar^2 * ar^2) in H by nra.\n replace (br^4) with (br^2 * br^2) in H by nra.\n replace (ai^4) with (ai^2 * ai^2) in H by nra.\n replace (bi^4) with (bi^2 * bi^2) in H by nra.\n assert (ar^2=0 /\\ ai^2=0 /\\ br^2=0 /\\ bi^2=0)\n  by (repeat split; nra).\n clear H; destruct H0 as [? [? [? ?]]].\n repeat f_equal; nra.\n}\nclear H.\ninjection H0; clear H0; intros.\ndestruct H2.\nassert (forall m1 m2 : @matrix C 2 2, m1=m2 -> \n   coeff_mat zero m1 0 0 = coeff_mat zero m2 0 0 /\\\n   coeff_mat zero m1 0 1 = coeff_mat zero m2 0 1 /\\\n   coeff_mat zero m1 1 0 = coeff_mat zero m2 1 0 /\\\n   coeff_mat zero m1 1 1 = coeff_mat zero m2 1 1) \n    by (intros; subst; auto).\napply H3 in H1; destruct H1 as [H1a [H1b [H1c H1d]]].\napply H3 in H2; destruct H2 as [H2a [H2b [H2c H2d]]].\nclear H3.\nset (u := @coeff_mat C_AbelianGroup 2 2 (@zero C_AbelianGroup)\n        (@Mone C_Ring 2)) in *.\nhnf in u. simpl in u. subst u.\nsimpl in *.\nrepeat match goal with H: _ = zero |- _ => clear H end.\nrepeat match goal with H: _ = one |- _ => injection H; clear H; intros end.\nunfold C0 in *.\ndestruct i as [|[|]]; [ | | lia]; clear Hi;\nrewrite H,H0 in *; clear H H0; simpl in *; lra.\nQed.\n\n(* if σ^2 bounds the singular values of A ∈ M(C^2) then σ bounds the two-norm of A *)\nTheorem sv_bound_implies_two_norm_bound   (A : @matrix C 2 2) (σ : R):\n  sv_bound 2 A σ  ->  two_norm_bound 2 A σ.\nProof.\nintros. intro.\nred in H.\ndestruct H as [H0 [V [Λ [H1 [H2 [H3 H6]]]]]].\nassert (exists a : matrix 2 1, u = Mmult V a)\n  by (apply  (vectors_in_basis 2 u V ); auto).\ndestruct H as (a & Hu); subst.\nunfold vec_two_norm.\nrepeat rewrite tranpose_rewrite.\ndo 2 rewrite <- Mmult_assoc.\nreplace (Mmult (matrix_conj_transpose 2 2 A) (Mmult A (Mmult V a))) with\n(Mmult (Mmult (Mmult (matrix_conj_transpose 2 2 A) A) V) a)\nby (repeat rewrite Mmult_assoc; auto).\nrewrite H1.\nreplace (Mmult (matrix_conj_transpose 2 2 V) (Mmult (Mmult V Λ) a)) with\n(Mmult (Mmult (matrix_conj_transpose 2 2 V) V) (Mmult Λ a))\nby (repeat rewrite Mmult_assoc; auto).\nreplace (Mmult (Mmult (matrix_conj_transpose 2 1 a) (matrix_conj_transpose 2 2 V)) (Mmult V a))\nwith \n(Mmult (matrix_conj_transpose 2 1 a) (Mmult (Mmult (matrix_conj_transpose 2 2 V) V) a))\nby (repeat rewrite Mmult_assoc; auto).\ndestruct H2 as (H2 & _).\nrewrite H2.\nrewrite !Mmult_one_l.\nreplace (Mmult Λ a)\nwith \n(mk_matrix 2 1 (fun i _ : nat =>\n  mult (coeff_mat zero Λ i i) (coeff_mat zero a i 0))).\n{\nrewrite <- (sqrt_pow2 σ) by auto.\nrewrite <- sqrt_mult by (try nra; apply Cmod_ge_0).\napply sqrt_le_1_alt.\nrewrite <- (Cmod_RtoC (σ^2)) by nra.\nrewrite <- Cmod_mult.\nunfold Mmult.\nrewrite !coeff_mat_bij; try lia.\nchange (Init.Nat.pred 2) with 1%nat.\nrewrite !sum_Sn.\nrewrite !coeff_mat_bij by lia.\nrewrite !sum_O.\nrewrite !coeff_mat_bij by lia.\nchange plus with Cplus.\nchange mult with Cmult.\nunfold matrix_conj_transpose.\nrewrite !coeff_mat_bij by lia.\nrewrite Cmult_comm.\nrewrite <- Cmult_assoc.\nrewrite C_sqr_ccong.\nrewrite Cmult_comm.\nrewrite Cplus_comm.\nrewrite Cmult_comm.\nrewrite <- Cmult_assoc.\nrewrite C_sqr_ccong.\nrewrite !C_sqr_ccong2.\n\n\npose proof (H6 0%nat ltac:(lia)) as (HL1 & HL2 & HL3).\npose proof (H6 1%nat ltac:(lia)) as (HL4 & HL5 & HL6).\nrewrite HL1. \nrewrite HL4.\n\nrewrite <- !RtoC_mult.\nrewrite <- !RtoC_plus.\nrewrite <- !RtoC_mult.\nrewrite !Cmod_R.\n\nrewrite Rmult_comm.\napply Rabs_pos_le.\napply Rle_plus; auto.\napply Rle_mult; auto.\napply sqr_plus_pos.\napply Rle_mult; auto.\napply sqr_plus_pos.\n\napply Rle_mult; auto; \n  try apply square_pos.\napply Rle_plus; auto; \n  apply sqr_plus_pos.\n\nrewrite Rmult_plus_distr_l.\nrewrite Rplus_comm.\napply Rplus_le_compat.\n*\nrewrite Rmult_comm.\napply Rmult_le_compat_r; auto.\napply sqr_plus_pos.\n*\nrewrite Rmult_comm.\napply Rmult_le_compat_r; auto.\napply sqr_plus_pos.\n}\napply mk_matrix_ext; intros.\nassert (Hj: (j = 0)%nat) by lia; subst.\nchange (Init.Nat.pred 2) with (S 0).\nred in H3.\ndestruct i as [|[|]]; [ | | lia].\n--\nrewrite sum_Sn, sum_O.\nspecialize (H3 0%nat 1%nat ltac:(lia)).\n\nchange ((@coeff_mat (AbelianGroup.sort (Ring.AbelianGroup C_Ring)) 2 2\n        (@zero (Ring.AbelianGroup C_Ring)) Λ 0 1))\nwith \n(@coeff_mat C 2 2 (@zero C_AbelianGroup) Λ 0 1).\nrewrite H3.\nrewrite ?@mult_zero_l, ?@mult_zero_r, ?@plus_zero_l, ?@plus_zero_r.\nauto.\n--\nrewrite sum_Sn, sum_O.\nspecialize (H3 1%nat 0%nat ltac:(lia)).\nchange (@zero C_AbelianGroup) with (@zero C_Ring) in *.\nchange (@coeff_mat _ 2 2  (@zero C_Ring) Λ 1 0)\nwith (@coeff_mat C 2 2 (@zero C_Ring) Λ 1 0).\nsimpl.\nrewrite H3.\nrewrite ?@mult_zero_l, ?@mult_zero_r, ?@plus_zero_l, ?@plus_zero_r.\nauto.\nQed.\n\nLemma MTM_lambda_2_pos (h : R | 0 < h < 1.4): \n0 <= (MTM_lambda_2 (proj1_sig h)).\nProof.\ndestruct h as (h & Hh); simpl.\nunfold MTM_lambda_2.\ninterval with ( i_bisect h, i_taylor h, i_degree 3).\nQed.\n\nLemma MTM_lambda_2_pos_2 (h : R) :\n 0 < h < 1.41-> \n0 <= (MTM_lambda_2 h).\nProof.\nintros.\nunfold MTM_lambda_2.\ninterval with ( i_bisect h, i_taylor h, i_degree 3).\nQed.\n\nLemma MTM_lambda_1_pos_2 (h : R) :\n 0 < h < 1.41 -> \n0 <= (MTM_lambda_1 h).\nProof.\nintros.\nunfold MTM_lambda_1.\ninterval with ( i_bisect h, i_taylor h, i_degree 3).\nQed.\n\nLemma Rdiv_le a b c d :\n  0 < b  -> 0 < d -> \n  a * b <= c * d -> a/d <= c/b.\nProof.\nintros.\napply Rle_div_l in H1 ; auto.\nreplace (a * b / d ) with\n(a / d * b) in H1 by nra.\nrewrite Rle_div_r in H1; auto.\nQed.\n\nLemma Rdiv_le2 a b c  :\n  0 < b  ->\n  a  <= c  -> a/b <= c/b.\nProof.\nintros.\napply Rle_div_l; auto.\nreplace (c / b * b) with c; auto.\nfield. nra.\nQed.\n\nLemma eig_MTM_le (h: R):\n  0 < h < 1.41 -> \n   (MTM_lambda_1 h) <=  (MTM_lambda_2 h).\nProof.\nintros.\nunfold MTM_lambda_1, MTM_lambda_2.\nassert (h ^ 4 - 4 * h ^ 2 + 4 <> 0) by \n  interval with ( i_bisect h, i_taylor h, i_degree 3).\napply Rdiv_le; try\ninterval with ( i_bisect h, i_taylor h, i_degree 3).\nrepeat rewrite pow2_abs.\nfield_simplify; try interval.\nrepeat rewrite pow2_sqrt; try nra.\nfield_simplify; auto. \nmatch goal with |-context [?a ^ 3] =>\nreplace (a^3) with (a^2 * a) by nra\nend.\nrepeat rewrite pow2_sqrt; try nra.\nfield_simplify; auto.\ntry apply Rdiv_le2; try\ninterval with ( i_bisect h, i_taylor h, i_degree 3).\napply Rminus_le.\nfield_simplify.\nunfold Rminus.\nrewrite ?Ropp_mult_distr_l.\nrewrite <- ? Rmult_plus_distr_r.\napply Rmult_le_0_r; try apply sqrt_pos.\nunfold pow.\nrewrite <- ?Rmult_assoc, ?Rmult_1_r.\nrewrite <- ? Rmult_plus_distr_r.\napply Rmult_le_0_r; try nra.\napply Rmult_le_0_r; try nra.\napply Rmult_le_0_r; try nra.\ninterval with ( i_bisect h, i_depth 9, i_taylor h, i_degree 5, i_prec 53).\nQed.\n\nLemma div_eq_1 : \n (forall a b : R, a = b -> b <> 0 -> a / b = 1).\nProof.\nintros; subst. field; auto. Qed.\n\nLemma MTM_eigenvectors_orthogonal_1 (h: R):\n  0 < h < 1.41 -> \nMmult (matrix_conj_transpose 2 2 (MTM_eigenvector_matrix h))\n  (MTM_eigenvector_matrix h) = Mone.\nProof.\nintros.\nunfold MTM_eigenvector_matrix, matrix_conj_transpose.\nrepeat match goal with |- context [(@mk_matrix C 2 2 ?a)] =>\nchange (@mk_matrix C 2 2 a) with \n(@mk_matrix (AbelianGroup.sort C_AbelianGroup) 2 2 a)\nend.\nunfold Mmult, Mone.\napply mk_matrix_ext => i j Hi Hj.\nassert (Hi2: (i = 1)%nat \\/ (i <> 1)%nat) by lia; destruct Hi2;\nassert (Hj2: (j = 1)%nat \\/ (j <> 1)%nat) by lia; destruct Hj2; subst; simpl.\n-\nrepeat rewrite sum_Sn.\nrepeat rewrite sum_O.\nrepeat rewrite coeff_mat_bij; try lia.\nunfold coeff_mat; simpl.\nunfold Cconj,RtoC, MTM_eV_2; simpl.\nchange mult with Cmult.\nchange plus with Cplus.\nchange one with C1.\nrepeat rewrite coeff_mat_bij; try lia.\nsimpl.\ncbv [Cplus Cmult RtoC C1 fst snd].\nf_equal; field_simplify; try nra.\nrepeat rewrite pow2_sqrt.\nfield_simplify.\nrepeat rewrite pow2_abs.\nfield_simplify.\napply div_eq_1.\nrepeat rewrite pow2_sqrt; nra.\nrepeat rewrite pow2_sqrt; try nra.\napply Rgt_not_eq;\nfield_simplify.\ninterval\n with ( i_bisect h, i_depth 7, i_taylor h, i_degree 3).\nsplit. \nall: (try interval\n with ( i_bisect h, i_depth 7, i_taylor h, i_degree 3)).\nrepeat rewrite <- Rabs_mult.\nmatch goal with |-context [?a <> 0] =>\n  field_simplify a\nend.\nrepeat match goal with |-context [Rabs( (?a / ?b) * (?a / ?b)) ] =>\nreplace ( (a / b) * (a / b)) with ( (a/b)^2) by nra\nend.\nrepeat rewrite Rabs_sqr_le.\nrepeat rewrite pow2_abs.\nmatch goal with |-context [?a <> 0] =>\n  field_simplify a; try nra\nend.\nrepeat rewrite pow2_sqrt; try nra.\nmatch goal with |-context [?a <> 0] =>\n  field_simplify a; try nra\nend.\nall: try split; try \ninterval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\n-\nassert (j = 0)%nat by lia; subst.\nrepeat rewrite sum_Sn.\nrepeat rewrite sum_O.\nrepeat rewrite coeff_mat_bij; try lia.\nunfold coeff_mat; simpl.\nunfold Cconj,RtoC, MTM_eV_1; simpl.\nchange mult with Cmult.\nchange plus with Cplus.\nchange one with C1.\nchange zero with C0.\nrepeat rewrite coeff_mat_bij; try lia.\nsimpl.\ncbv [Cplus Cmult RtoC C0 fst snd].\nf_equal; field_simplify; try nra.\nrepeat rewrite pow2_sqrt.\nfield_simplify. \nassert ( forall a, 0/a = 0) by (intros;nra).\napply H0.\nrepeat rewrite Rmult_assoc.\nmatch goal with |-context[h ^ 4 * ?a] =>\nset (y:= a )\nend.\nreplace (h ^ 4 * y - 4 * (h ^ 2 * y) + 4 * y) with\n((h ^ 4 - 4 * h ^ 2  + 4 ) *y) by nra.\napply Rmult_integral_contrapositive_currified.\ninterval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\nsubst y.\ninterval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\ninterval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\nrepeat split; try\ninterval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\nrepeat split; try\ninterval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\n-\nassert (i = 0)%nat by lia; subst.\nrepeat rewrite sum_Sn.\nrepeat rewrite sum_O.\nrepeat rewrite coeff_mat_bij; try lia.\nsimpl.\nunfold Cconj,RtoC, MTM_eV_1, MTM_eV_2; simpl.\nchange mult with Cmult.\nchange plus with Cplus.\nchange one with C1.\nchange zero with C0.\nrepeat rewrite coeff_mat_bij; try lia.\nunfold coeff_mat; simpl.\ncbv [Cplus Cmult RtoC C0 fst snd].\nf_equal; field_simplify; try nra.\nrepeat rewrite pow2_sqrt.\nfield_simplify. \nassert ( forall a, 0/a = 0) by (intros;nra).\napply H1.\nrepeat rewrite Rmult_assoc.\nmatch goal with |-context[h ^ 4 * ?a] =>\nset (y:= a )\nend.\nreplace (h ^ 4 * y - 4 * (h ^ 2 * y) + 4 * y) with\n((h ^ 4 - 4 * h ^ 2  + 4 ) *y) by nra.\napply Rmult_integral_contrapositive_currified.\ninterval\n with ( i_bisect h, i_depth 7, i_taylor h, i_degree 3).\nsubst y.\nrewrite <- sqrt_mult.\ninterval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\ninterval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\ninterval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\ninterval\n with ( i_bisect h, i_depth 7, i_taylor h, i_degree 3).\nrepeat split; try \ninterval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\nrepeat split; try\ninterval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\n-\nassert (i = 0)%nat by lia; subst.\nassert (j = 0)%nat by lia; subst.\nrepeat rewrite sum_Sn.\nrepeat rewrite sum_O.\nrepeat rewrite coeff_mat_bij; try lia.\nunfold coeff_mat; simpl.\nunfold Cconj,RtoC, MTM_eV_1; simpl.\nchange mult with Cmult.\nchange plus with Cplus.\nchange one with C1.\nrepeat rewrite coeff_mat_bij; try lia.\nsimpl.\ncbv [Cplus Cmult RtoC C1 fst snd].\nf_equal; field_simplify; try nra.\nrepeat rewrite pow2_sqrt.\nfield_simplify.\nrepeat rewrite pow2_abs.\nfield_simplify.\napply div_eq_1.\nrepeat rewrite pow2_sqrt; nra.\nrepeat rewrite pow2_sqrt; try nra.\napply Rgt_not_eq;\nfield_simplify.\ninterval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\nrepeat split. \nall: (try repeat split; try interval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7)).\nQed.\n\n\nLemma MTM_eigenvectors_orthogonal_2 (h: R):\n  0 < h < 1.41 -> \nMmult (MTM_eigenvector_matrix h) \n(matrix_conj_transpose 2 2 (MTM_eigenvector_matrix h)) = Mone.\nProof.\nintros.\nunfold MTM_eigenvector_matrix, matrix_conj_transpose.\nrepeat match goal with |- context [(@mk_matrix C 2 2 ?a)] =>\nchange (@mk_matrix C 2 2 a) with \n(@mk_matrix (AbelianGroup.sort C_AbelianGroup) 2 2 a)\nend.\nunfold Mmult, Mone.\napply mk_matrix_ext => i j Hi Hj.\nassert (Hi2: (i = 1)%nat \\/ (i <> 1)%nat) by lia; destruct Hi2;\nassert (Hj2: (j = 1)%nat \\/ (j <> 1)%nat) by lia; destruct Hj2; subst; simpl.\n-\nrepeat rewrite sum_Sn.\nrepeat rewrite sum_O.\nrepeat rewrite coeff_mat_bij; try lia.\nunfold coeff_mat; simpl.\nunfold Cconj,RtoC, MTM_eV_1, MTM_eV_2; simpl.\nchange mult with Cmult.\nchange plus with Cplus.\nchange one with C1.\nrepeat rewrite coeff_mat_bij; try lia.\nsimpl.\ncbv [Cplus Cmult RtoC C1 fst snd].\nf_equal; field_simplify; try nra.\nrepeat rewrite pow2_sqrt.\nfield_simplify.\nrepeat rewrite pow2_abs.\nfield_simplify.\napply div_eq_1.\nrepeat rewrite pow2_sqrt; try nra.\nmatch goal with |-context[sqrt ?a ^ 4] =>\n  replace (sqrt a ^ 4) with\n (sqrt a ^ 2 * sqrt a ^ 2) by nra\nend.\nrepeat rewrite pow2_sqrt; try nra.\nrepeat rewrite pow2_sqrt; try nra.\nall: (try repeat split; try interval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7)).\n-\nassert (j = 0)%nat by lia; subst.\nrepeat rewrite sum_Sn.\nrepeat rewrite sum_O.\nrepeat rewrite coeff_mat_bij; try lia.\nunfold coeff_mat; simpl.\nunfold Cconj,RtoC, MTM_eV_1, MTM_eV_2; simpl.\nchange mult with Cmult.\nchange plus with Cplus.\nchange one with C1.\nchange zero with C0.\nrepeat rewrite coeff_mat_bij; try lia.\nsimpl.\ncbv [Cplus Cmult RtoC C0 fst snd].\nf_equal; field_simplify; try nra.\nrepeat rewrite pow2_sqrt.\nfield_simplify. \nassert ( forall a b, b = 0 -> a<>0 -> b/a = 0) by (intros;nra).\napply H0; try interval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\nall: (try interval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7)).\nrepeat rewrite pow2_abs; field_simplify; try nra.\napply H0; try interval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\nrepeat rewrite pow2_sqrt; field_simplify; try nra.\nrepeat rewrite pow2_abs.\nall: (try split; try apply sep_0_div; \n(try interval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7))).\nall: (try split; try apply sep_0_div; \n(try interval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7))).\n-\nassert (i = 0)%nat by lia; subst.\nrepeat rewrite sum_Sn.\nrepeat rewrite sum_O.\nrepeat rewrite coeff_mat_bij; try lia.\nunfold coeff_mat; simpl.\nunfold Cconj,RtoC, MTM_eV_1, MTM_eV_2; simpl.\nchange mult with Cmult.\nchange plus with Cplus.\nchange one with C1.\nchange zero with C0.\nrepeat rewrite coeff_mat_bij; try lia.\nsimpl.\ncbv [Cplus Cmult RtoC C0 fst snd].\nf_equal; field_simplify; try nra.\nrepeat rewrite pow2_sqrt.\nfield_simplify. \nassert ( forall a b, b = 0 -> a<>0 -> b/a = 0) by (intros;nra).\napply H1.\nrepeat rewrite Rmult_assoc.\nrepeat rewrite pow2_abs; field_simplify; try nra.\napply H1; try interval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\nrepeat rewrite pow2_sqrt; try nra.\nrepeat rewrite pow2_abs. \nmatch goal with |-context[ ?a <> 0] =>\nfield_simplify a;try nra;\nrepeat rewrite pow2_sqrt; try nra\nend.\nmatch goal with |-context[sqrt ?a ^ 4 ] =>\nreplace (sqrt a ^ 4) with\n(sqrt a ^ 2 * sqrt a ^ 2) by nra;\nrepeat rewrite pow2_sqrt; try nra\nend.\nmatch goal with |-context[ ?a <> 0] =>\nfield_simplify a;try nra;\nrepeat rewrite pow2_sqrt; try nra\nend; try interval\n with ( i_bisect h, i_depth 7, i_taylor h, i_degree 3).\napply sep_0_div; try split;\ninterval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\nall : try repeat split; try\ninterval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7).\n-\nassert (i = 0)%nat by lia; subst.\nassert (j = 0)%nat by lia; subst.\nrepeat rewrite sum_Sn.\nrepeat rewrite sum_O.\nrepeat rewrite coeff_mat_bij; try lia.\nunfold coeff_mat; simpl.\nunfold Cconj,RtoC, MTM_eV_1, MTM_eV_2; simpl.\nchange mult with Cmult.\nchange plus with Cplus.\nchange one with C1.\nrepeat rewrite coeff_mat_bij; try lia.\nsimpl.\ncbv [Cplus Cmult RtoC C1 fst snd].\nf_equal; field_simplify; try nra.\nrepeat rewrite pow2_sqrt.\nfield_simplify.\nall : try repeat split; try\ninterval\n with ( i_bisect h, i_depth 7, i_taylor h, i_degree 3).\nrepeat rewrite pow2_abs. \nfield_simplify.\napply div_eq_1.\nrepeat rewrite pow2_sqrt; try nra;\nmatch goal with |-context[sqrt ?a ^ 4 ] =>\nreplace (sqrt a ^ 4) with\n(sqrt a ^ 2 * sqrt a ^ 2) by nra;\nrepeat rewrite pow2_sqrt; try nra\nend.\nrepeat rewrite pow2_sqrt; try nra.\nmatch goal with |-context[ ?a <> 0] =>\nfield_simplify a;try nra;\nrepeat rewrite pow2_sqrt; try nra\nend.\nmatch goal with |-context[sqrt ?a ^ 4 ] =>\nreplace (sqrt a ^ 4) with\n(sqrt a ^ 2 * sqrt a ^ 2) by nra;\nrepeat rewrite pow2_sqrt; try nra\nend.\nall: (try repeat split; try interval\n with ( i_bisect h, i_depth 10, i_taylor h, i_degree 7)).\nQed.\n\nLemma two_norm_bound_lambda2 (h : R | 0 < h < 1.41): \n two_norm_bound 2 (M (proj1_sig h)) (sqrt (MTM_lambda_2 (proj1_sig h))).\nProof.\napply ( sv_bound_implies_two_norm_bound\n  (M (proj1_sig h)) (sqrt (MTM_lambda_2 (proj1_sig h)))).\nunfold sv_bound.\ndestruct h as (h & Hh); simpl; split; try apply sqrt_pos.\nexists (MTM_eigenvector_matrix h), (MTM_eigenvalue_matrix h).\nrepeat split.\n-\nrewrite MTM_aux.\napply (MTM_eigens_correct h Hh).\n-\napply MTM_eigenvectors_orthogonal_1; auto.\n-\napply MTM_eigenvectors_orthogonal_2; auto.\n-\nunfold diag_pred, MTM_eigenvalue_matrix; unfold coeff_mat;\nintros; simpl; try lia.\ndestruct i as [|[|]]; try lia;\ndestruct j as [|[|]]; try lia;\nreflexivity.\n-\nunfold MTM_eigenvalue_matrix, coeff_mat; simpl.\ndestruct i as [|[|]]; try lia; reflexivity.\n-\ndestruct i as [|[|]]; try lia; simpl.\napply MTM_lambda_1_pos_2; auto.\napply MTM_lambda_2_pos_2; auto.\n-\nrewrite Rmult_1_r.\nrewrite sqrt_def by (apply MTM_lambda_2_pos_2; auto).\ndestruct i as [|[|]]; try lia; simpl.\napply eig_MTM_le; auto.\napply Rle_refl.\nQed.\n\nDefinition σ (h: R) := sqrt (MTM_lambda_2 h).\n\nDefinition two_norm_M (h : R | 0 < h < 1.41) :=\n  proj1_sig (exist (two_norm_bound 2 (M (proj1_sig h))) \n                          (sqrt (MTM_lambda_2 (proj1_sig h)))\n                          (two_norm_bound_lambda2 h)).\n\nLemma sigma_eq_two_norm_M:\n  forall h, σ (proj1_sig h) = two_norm_M h.\nProof.\ndestruct h; reflexivity.\nQed.\n\n(* 1.000003814704542914881812976091168820858001708984375 *)\n\nDefinition σb := 1.000003814704543.\n\nLemma sigma_bound: σ h <= σb.\nProof.\nunfold σ, σb, MTM_lambda_2, h.\nmatch goal with |- sqrt ?a <= _ => field_simplify a end.\nmatch goal with |- ?a <= _ => interval_intro a upper end.\neapply Rle_trans.\napply H. nra.\ninterval.\nQed.\n\nLemma M_norm_sub_mult :\n  forall (h : R | 0 < h < 1.41),\n  forall (y : @matrix C 2 1%nat),\n  vec_two_norm_2d (Mmult (M (proj1_sig h)) y) <= (two_norm_M h) * vec_two_norm_2d y.\nProof.\nintros.\nunfold two_norm_M. simpl.\nrepeat rewrite <- two_norms_eq_2d.\napply two_norm_bound_lambda2.\nQed.\n\nLemma matrix_analysis_method_bound_n : \n  forall p q : R,\n  forall n : nat, \n  forall h : {h : R | 0 <  h < 1.41},\n  let Mn := Mpow 2 n (M (proj1_sig h)) in\n  vec_two_norm_2d  (Mmult Mn (s_vector (p, q))) <= \n      (sqrt (Cmod (MTM_lambda_2 (proj1_sig h)))) ^ n * vec_two_norm_2d (s_vector (p,q)).\nProof.\nintros ? ? ? h; intros. \ninduction n.\n- \nsimpl. simpl in Mn.\nrewrite Rmult_1_l. \nsubst Mn.\nrewrite M_ID_equiv_M1.\nrewrite Mmult_one_l.\napply Rle_refl.\n-\nunfold Mpow in Mn.\nfold Mpow in Mn.\nsimpl in IHn.\nsubst Mn. \nreplace (Mmult (Mmult (Mpow 2 n \n  (M (@proj1_sig R (fun h1 : R => 0 < h1 < 1.41) h))) (M (@proj1_sig R (fun h1 : R => 0 < h1 < 1.41) h))) (s_vector (p, q)))\nwith\n( Mmult (M (@proj1_sig R (fun h1 : R => 0 < h1 < 1.41) h)) \n  (Mmult (Mpow 2 n (M (@proj1_sig R (fun h1 : R => 0 < h1 < 1.41) h))) (s_vector (p, q)))).\ndestruct (@Mmult C_Ring 2 2 1 (Mpow 2 n (M (@proj1_sig R (fun h1 : R => 0 < h1 < 1.41) h))) (s_vector (p, q))).\neapply Rle_trans.\npose proof M_norm_sub_mult h (t, t0).\napply H.\neapply Rle_trans.\napply Rmult_le_compat_l.\nunfold two_norm_M; simpl.\napply sqrt_pos.\napply IHn.\nunfold two_norm_M.\nsimpl.\nrewrite Cmod_RtoC; try apply MTM_lambda_2_pos_2; try (destruct h; simpl; auto).\napply Req_le.\nrewrite Rmult_assoc; auto.\nrewrite Mmult_assoc.\nrewrite Mpow_comm; auto.\nQed.\n\nLemma h_bnd_lem :\n0 <  h < 1.41.\nProof.\nsplit; unfold h; unfold ω; try nra.\nQed.\n\nTheorem matrix_bound : \n  forall p q: R,\n  forall n : nat, \n  let Mn := Mpow 2 n (M  h ) in\n  vec_two_norm_2d  (Mmult Mn (s_vector (p, q))) <= \n      σb ^ n * vec_two_norm_2d (s_vector (p,q)).\nProof.\nintros.\nset (j := (exist (fun x => 0 < x < 1.41) h) h_bnd_lem).\npose proof matrix_analysis_method_bound_n p q n j.\nsimpl in H.\neapply Rle_trans.\napply H.\napply Rmult_le_compat_r.\napply Rnorm_pos.\napply pow_incr; split.\napply sqrt_pos.\nrewrite Cmod_RtoC.\napply sigma_bound.\napply MTM_lambda_2_pos_2.\nunfold h. lra.\nQed.\n\nLemma Rprod_norm_vec_two_norm : \n forall ic,   ∥ ic ∥ = vec_two_norm _ (s_vector ic).\nProof.\nintros.\nrewrite two_norms_eq_2d.\nunfold vec_two_norm_2d.\ndestruct ic as [p q]; simpl.\nunfold Rprod_norm; simpl.\nunfold Cmod, coeff_mat; simpl.\nf_equal.\nrewrite ?Rmult_0_l, ?Rplus_0_r, ?Rmult_1_r.\nrewrite ?sqrt_sqrt; auto; nra.\nQed.\n\nLemma iternR_bound : \n  forall p q: R,\n  forall nf : nat, \n  ( nf <=1000)%nat -> \n  ∥iternR (p, q) h nf∥ <= σb ^ nf * ∥(p,q)∥.\nProof.\nintros.\nunfold σb.\napply Rle_trans with (σb ^ nf * vec_two_norm_2d (s_vector (p, q))).\n-\npose proof matrix_bound p q nf.\nsimpl in H0.\nrewrite Rprod_norm_vec_two_norm.\nrewrite <- transition_matrix_equiv_iternR.\nrewrite two_norms_eq_2d. lra.\n-\napply Rmult_le_compat_l. \napply pow_le; try nra.\nunfold vec_two_norm_2d, Rprod_norm.\nunfold fst, snd, Cmod.\nrewrite !pow2_sqrt by apply sqr_plus_pos.\nsimpl.\napply Req_le.\nf_equal; nra.\nQed.\n\nLemma method_norm_bound : \n  forall p q: R,\n  ∥(leapfrog_stepR h (p,q))∥ <= σb * ∥(p,q)∥.\nProof.\nintros.\nassert (H : (1 <= 1000)%nat) by (simpl; lia).\neapply Rle_trans.\napply (iternR_bound p q 1 H).\napply Rmult_le_compat_r; try apply   Rnorm_pos.\nlra.\nQed.\n\nLemma iternR_bound_max_step : \n  forall p q: R,\n  forall nf : nat, \n  ( nf <=1000)%nat -> \n  ∥iternR (p, q) h nf∥ <= 1.003822 * ∥(p,q)∥.\nProof.\nintros.\neapply Rle_trans.\napply (iternR_bound p q nf H).\neapply Rmult_le_compat_r; try apply Rnorm_pos.\neapply Rle_trans.\napply Rle_pow. unfold σb. lra. eassumption.\ninterval with (i_prec 256).\nQed.\n\nClose Scope R_scope. ", "meta": {"author": "VeriNum", "repo": "VerifiedLeapfrog", "sha": "c8d07f86747bd9e44f4cb02f19a691cc895c1279", "save_path": "github-repos/coq/VeriNum-VerifiedLeapfrog", "path": "github-repos/coq/VeriNum-VerifiedLeapfrog/VerifiedLeapfrog-c8d07f86747bd9e44f4cb02f19a691cc895c1279/leapfrog_project/matrix_analysis.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339907, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6637462614348799}}
{"text": "(* week-01_functional-programming-in-Coq.v *)\n(* YSC3236 2017-2018, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 15 Aug 2017 *)\n\n(* ********** *)\n\nCheck 3.\n\n\n\n\n(* Note: \"nat\" is the type of natural numbers. *)\n\nCompute 3.\n\n(* Note: natural numbers are self-evaluating. *)\n\n(* ********** *)\n\nCompute (4 + 6).\n\nCheck (4 + 6).\n\n(* ********** *)\n\nCheck (plus 4 6).\n\n(* Note: infix + is syntactic sugar for plus. *)\n\n(* ********** *)\n\nCheck (plus 4).\n\n(* Note: and plus refers to a library function. *)\n\nCompute (plus 4).\nCompute (plus 3).\nCompute (plus 2).\nCompute (plus 1).\nCompute (plus 0).\n\n(* Note: functions are written as in OCaml,\n   with the keyword \"fun\" followed by the formal parameter\n   (and optionally its type), \"=>\", and the body. *)\n\nCompute (fun m : nat => S m).\n\n(*\n   For comparison,\n     fun m : nat => S m\n   would be written\n     (lambda (m) (1+ n))\n   in Scheme.\n *)\n\nCompute ((fun m : nat => S m) 3).\n\n(* ********** *)\n\nDefinition three := 3.\n\nCheck three.\n\nCompute three.\n\nDefinition ten := 4 + 6.\n\nCheck ten.\n\nCompute ten.\n\n(* ********** *)\n\n(* The following definitions are all equivalent: *)\n\n\nDefinition succ_v0 := fun m : nat => S m.\n\nDefinition succ_v1 := fun m => S m.\n\nDefinition succ_v2 (m : nat) :=\n  S m.\n\nDefinition succ_v3 (m : nat) : nat :=\n  S m.\n\nDefinition succ_v4 m :=\n  S m.\n\n(* Note: the definition of succ_v3 is the recommended one here. *)\n\n(* Note: variables are defined once and for all in a file. *)\n\n(* ********** *)\n\nRequire Import Arith Bool.\n\nNotation \"A =n= B\" :=\n  (beq_nat A B) (at level 70, right associativity).\n\nDefinition test_add (candidate: nat -> nat -> nat) : bool :=\n  (candidate 0 0 =n= 0)\n  &&\n  (candidate 0 1 =n= 1)\n  &&\n  (candidate 1 0 =n= 1)\n  &&\n  (candidate 1 1 =n= 2)\n  &&\n  (candidate 1 2 =n= 3)\n  &&\n  (candidate 2 1 =n= 3)\n  &&\n  (candidate 2 2 =n= 4)\n  (* etc. *)\n  .\n\nFixpoint add_v1 (i j : nat) : nat :=\n  match i with\n    | O => j\n    | S i' => S (add_v1 i' j)\n  end.\n\nCompute (test_add add_v1).\n\nFixpoint add_v2 (i j : nat) : nat :=\n  match i with\n    | O => j\n    | S i' => add_v2 i' (S j)\n  end.\n\nCompute (test_add add_v2).\n\nDefinition add_v3 (i j : nat) : nat :=\n  let fix visit n :=\n    match n with\n      | O => j\n      | S n' => S (visit n')\n    end\n  in visit i.\n\nCompute (test_add add_v3).\n\n(* ********** *)\n\nInductive list_nat : Type :=\n  nil_nat : list_nat\n| cons_nat : nat -> list_nat -> list_nat.\n\nFixpoint beq_list_nat (xs ys : list_nat) : bool :=\n  match xs with\n    nil_nat =>\n    match ys with\n      nil_nat =>\n      true\n    | cons_nat y ys' =>\n      false\n    end\n  | cons_nat x xs' =>\n    match ys with\n      nil_nat =>\n      false\n    | cons_nat y ys' =>\n      (x =n= y) && beq_list_nat xs' ys'\n    end\n  end.\n\nNotation \"A =ns= B\" :=\n  (beq_list_nat A B) (at level 70, right associativity).\n\n(* ***** *)\n\nDefinition test_append (candidate: list_nat -> list_nat -> list_nat) : bool :=\n  (candidate nil_nat nil_nat =ns= nil_nat)\n  &&\n  (candidate nil_nat (cons_nat 10 nil_nat) =ns= (cons_nat 10 nil_nat))\n  &&\n  (candidate (cons_nat 1 nil_nat) (cons_nat 10 nil_nat) =ns= (cons_nat 1 (cons_nat 10 nil_nat)))\n  (* etc. *)\n  .\n\nFixpoint append_v0 (xs ys : list_nat) : list_nat :=\n  match xs with\n  | nil_nat =>\n    ys\n  | cons_nat x xs' =>\n    cons_nat x (append_v0 xs' ys)\n  end.\n\nCompute (test_append append_v0).\n\n(* ***** *)\n\nDefinition test_length (candidate: list_nat -> nat) : bool :=\n  (candidate nil_nat =n= 0)\n  &&\n  (candidate (cons_nat 1 nil_nat) =n= 1)\n  &&\n  (candidate (cons_nat 2 (cons_nat 1 nil_nat)) =n= 2)\n  (* etc. *)\n  .\n\nFixpoint length_v0 (xs : list_nat) : nat :=\n  match xs with\n  | nil_nat =>\n    0\n  | cons_nat x xs' =>\n    S (length_v0 xs')\n  end.\n\nCompute (test_length length_v0).\n\n(* ********** *)\n\nInductive binary_tree : Type :=\n  Leaf : nat -> binary_tree\n| Node : binary_tree -> binary_tree -> binary_tree.\n\nFixpoint beq_binary_tree (t1 t2 : binary_tree) : bool :=\n  match t1 with\n    Leaf n1 =>\n    match t2 with\n      Leaf n2 =>\n      n1 =n= n2\n    | Node t21 t22 =>\n      false\n    end\n  | Node t11 t12 =>\n    match t2 with\n      Leaf n2 =>\n      false\n    | Node t21 t22 =>\n      (beq_binary_tree t11 t21) && (beq_binary_tree t12 t22)\n    end\n  end.\n\nNotation \"A =bt= B\" :=\n  (beq_binary_tree A B) (at level 70, right associativity).\n\n(* ***** *)\n\nDefinition test_number_of_leaves (candidate: binary_tree -> nat) : bool :=\n  (candidate (Leaf 1) =n= 1)\n  &&\n  (candidate (Node (Leaf 1) (Leaf 2)) =n= 2)\n  (* etc. *)\n  .\n\nFixpoint number_of_leaves_v0 (t : binary_tree) : nat :=\n  match t with\n    Leaf n =>\n    1\n  | Node t1 t2 =>\n    (number_of_leaves_v0 t1) + (number_of_leaves_v0 t2)\n  end.\n\nCompute (test_number_of_leaves number_of_leaves_v0).\n\n(* ***** *)\n\nDefinition test_swap (candidate: binary_tree -> binary_tree) : bool :=\n  (candidate (Leaf 1) =bt= (Leaf 1))\n  &&\n  (candidate (Node (Leaf 1) (Leaf 2)) =bt= (Node (Leaf 2) (Leaf 1)))\n  (* etc. *)\n  .\n\n\nDefinition test_flatten (candidate: binary_tree -> list_nat) : bool :=\n  (candidate (Leaf 1) =ns= (cons_nat 1 nil_nat))\n  &&\n  (candidate (Node (Leaf 1) (Leaf 2)) =ns= (cons_nat 1 (cons_nat 2 nil_nat)))\n  (* etc. *)\n  .\n\nFixpoint flatten_v0 (t : binary_tree) : list_nat :=\n    match t with\n    | Leaf n =>\n      cons_nat n nil_nat\n    | Node t1 t2 =>\n      append_v0 (flatten_v0 t1) (flatten_v0 t2)\n    end.\n\nCompute (test_flatten flatten_v0).\n\n(*\nFixpoint flatten_v1 (t : binary_tree) : list_nat :=\n    match t with\n    | Leaf n =>\n      cons_nat n nil_nat\n    | Node t1 t2 =>\n      flatten_v1_aux t1 (flatten_v1 t2)\n    end\nwith flatten_v1_aux (t : binary_tree) (a : list_nat) : list_nat :=\n     append_v0 (flatten_v1 t) a.\n *)\n\nFixpoint flatten_v2 (t : binary_tree) : list_nat :=\n    match t with\n    | Leaf n =>\n      cons_nat n nil_nat\n    | Node t1 t2 =>\n      flatten_v2_aux t1 (flatten_v2 t2)\n    end\nwith flatten_v2_aux (t : binary_tree) (a : list_nat) : list_nat :=\n       match t with\n       | Leaf n =>\n         append_v0 (cons_nat n nil_nat) a\n       | Node t1 t2 =>\n         append_v0 (flatten_v2_aux t1 (flatten_v2 t2)) a\n       end.\n\nCompute (test_flatten flatten_v2).\n\n\n  \n(* ********** *)\n\n(* end of week-01_functional-programming-in-Coq.v *)\n(* Local Variables: *)\n(* End: *)\n\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/Wk1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985637, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6637462468447802}}
{"text": "(* Author: Devendra\n *)\nRequire Import Coq.Lists.List.\n\nRequire Import Coq.Classes.EquivDec.\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(* Definition xlist := [1;1;1;1]. *)\n\n(* Check ([1; 2; 3; 4]). *)\n\n(* Check (var1 [1; 2; 3]). *)\n\n\n\n  \n(* Inductive terms : Set := *)\n(* | var : string -> terms *)\n(* | app : string -> terms list -> terms. *)\n\nInductive term : Set :=\n| var : nat -> term\n| fn  : nat -> term -> term.\n\nCheck fn 1 (fn 1 (var 2)).\n\nInductive form : Set :=\n| eq : term -> term -> form.\n\nNotation \"x -=- y\" := (eq x y)\n                        (at level 60).\n\nCheck (fn 1 (var 2)) -=- (var 2).\n\n(* Check exists  *)\n\n(* Inductive prf (l : list (term * term)) : term -> Prop := *)\n(*   prfrefl (a : term) : (prf l a). *)\n\n\n(* Inductive prf (l : list (term * term)) (a : term) : term -> Prop := *)\n(*   prfrefl : prf l a a *)\n(*   prfsym  : prf l a b -> prf l b a.  *)\n\n\n(* The correctness condition *)\n\nInductive prf (l : list (term * term)) : term -> term -> Prop  :=\n(* | paxm  :  *)  \n| pref : forall t, prf l t t\n| psym : forall s t, prf l s t -> prf l t s\n| ptrs : forall s t u, prf l s t -> prf l t u -> prf l s u\n| pcong : forall (n : nat) s t, prf l s t -> prf l (fn n s) (fn n t).\n\n\nCheck psym [] (var 2) ( var 2) (pref [] (var 2) ).\n\nCheck prf.  \n\n\n\n(* computes all the subterms of a given term. *)\n\nFixpoint subterms (t : term) : list term :=\n  match t with\n  | var n => [var n]\n  | fn n t1 => (fn n t1) :: subterms t1\n  end.\n\n(* give list of tuples of term and its parent *)\n\nFixpoint parent_list (t : term) :=\n  match t with\n  | var _ => []\n  | fn n t => (t, fn n t) :: parent_list t\n  end.\n\nEval compute in parent_list (fn 1 (var 2)).\n\nScheme Equality for term.\n\nCheck term_eq_dec.\n\nEval compute in term_eq_dec (var 2) (fn 1 (var 3)).\n\nEval compute in term_beq (var 2) (var 3).\n\nEval compute in if (term_beq (var 2) (var 2)) then 1 else 0.\n\n\n(* Ignore this *)\n\nDefinition f (t : term) (arg : term*term) :=\n  match arg with\n  | (x, _) => term_beq t x\n  end.\n  \n\n(* gets the parents of a particular term from parent_list *)\n\nDefinition get_parents (t : term) (l : list (term*term)) :=\n  map (fun x => match x with | (_, n) => n end) (filter (f t) l).\n\nEval compute in get_parents (var 2) (parent_list (fn 1 (var 2)) ++ parent_list (fn 3 (var 2))).\n\n\nCheck remove.\n\nCheck List.remove.\n\nCheck last.\n\nEval compute in remove term_eq_dec (var 2) [var 2; var 3; var 4].\n\nDefinition removeT l := remove term_eq_dec (var 2) l.\n\n\n(* Scheme Equality for term*term. *)\n\nDefinition term_pairs_eqb (u v : term * term) :=\n  match (u, v) with\n  | ((a, b), (c, d)) => andb  (term_beq a c) (term_beq b d)\n  end.\n\n\n(* equality for... *)\n(* Definition term_pairs_eq_dec (u v : term * term) := *)\n(*   match (u, v) with *)\n(*   | ((a, b), (c, d)) => (term_eq_dec a c) /\\ (term_eq_dec b d) *)\n(*   end. *)\n\nDefinition removeTP a l := remove term_pairs_eq a l.\n\n(* Setting up the UF datastructure. Will need further modification *)\n\n(* Fixpoint uf_find (l : list (term*term)) (t : term) := *)\n(*   match l with *)\n(*   | [] => var 1000 *)\n(*   | (x, y)::ls => if term_beq x t then (if term_beq x y then x else uf_find l y) else *)\n(*                     uf_find ls t *)\n(*   end. *)\n\n\n(* Fixpoint uf_merge (l : list (term*term)) (u v : term) := *)\n(*   let a := uf_find l u in *)\n(*   let b := uf_find l v in *)\n(*   if term_beq a b then l else remove *)\n\n\n                    \n(* Ignore this *)\n(* Fixpoint get_parents (t : term) (l : list (term*nat)) := *)\n(*   match l with *)\n(*   | [] => [] *)\n(*   | (x,n) :: xs => match t with *)\n(*                    | x => n :: get_parents t xs *)\n(*                    | _ => get_parents t xs *)\n(*                    end *)\n                   \n(*   end. *)\n\n\n\n\n\n\n\n\n", "meta": {"author": "knuthingmuch", "repo": "congruence-closure", "sha": "6a16a22b73b675834adc1463d7e48b886710e74f", "save_path": "github-repos/coq/knuthingmuch-congruence-closure", "path": "github-repos/coq/knuthingmuch-congruence-closure/congruence-closure-6a16a22b73b675834adc1463d7e48b886710e74f/CC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.6637246887021113}}
{"text": "Require Export PropLang.\nRequire Export RelationClasses.\nRequire Export Morphisms.\nRequire Export List.\n\nSection subcontext.\n\nContext {atom : Type}.\n\nDefinition subcontext (Γ₁ Γ₂ : list (prop atom)) : Prop :=\nforall P, In P Γ₁ -> In P Γ₂.\nInfix \"⊆\" := subcontext (no associativity, at level 70).\n\nGlobal Instance subcontext_preord : PreOrder subcontext.\nProof.\nconstructor.\n+ intro Γ. red. trivial.\n+ intros Γ₁ Γ₂ Γ₃; unfold subcontext. auto.\nQed.\n\nLemma subcontext_cons : forall P Γ₁ Γ₂, P :: Γ₁ ⊆ Γ₂ <->\n  In P Γ₂ /\\ Γ₁ ⊆ Γ₂.\nProof.\nsplit; intros; repeat split.\n+ apply H; left; reflexivity.\n+ intros x ?; apply H; right; assumption.\n+ destruct H. intro x; destruct 1; subst; auto.\nQed.\n\nLemma subcontext_cons_r : forall P Γ, Γ ⊆ P :: Γ.\nProof.\nintros P Γ x ?; right; assumption.\nQed.\n\nGlobal Instance subcontext_cons_proper :\n  Proper (eq ==> subcontext ++> subcontext) (@cons (prop atom)).\nProof.\nintros P Q [] Γ₁ Γ₂ ?. rewrite subcontext_cons; split.\n+ left; reflexivity.\n+ rewrite H; apply subcontext_cons_r.\nQed.\n\nEnd subcontext.\n\nInfix \"⊆\" := subcontext (no associativity, at level 70).\n\nLtac prove_In :=\nmatch goal with\n| |- In ?P (?P :: ?Γ) => left; reflexivity\n| |- In ?P (?Q :: ?Γ) => right; prove_In\nend.\nLtac prove_subcontext :=\nmatch goal with\n| |- ?P :: ?Γ ⊆ ?Γ' => rewrite subcontext_cons; split;\n     [ prove_In | prove_subcontext ]\n| |- ?Γ ⊆ ?Γ => reflexivity\n| |- ?Γ ⊆ ?P :: ?Γ' => rewrite <- (subcontext_cons_r P Γ');\n                       prove_subcontext\nend.\n", "meta": {"author": "dschepler", "repo": "coq-sequent-calculus", "sha": "5e87c4f4f61d01ecf990e4e25b9280e6422a73e0", "save_path": "github-repos/coq/dschepler-coq-sequent-calculus", "path": "github-repos/coq/dschepler-coq-sequent-calculus/coq-sequent-calculus-5e87c4f4f61d01ecf990e4e25b9280e6422a73e0/Subcontext.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.6637246760211183}}
{"text": "Require Import Arith Bool List.\nRequire Import Omega.\nSet Implicit Arguments.\n\n\nLemma seq_minimum : forall m n x, In x (seq n m) -> n <= x.\nProof.\n  induction m.\n  - simpl.\n    intro; contradiction.\n  - intros n x.\n    simpl.\n    intro.\n    destruct H; try omega.\n    apply IHm in H.\n    omega.\nQed.\n\nLemma seq_nodup : forall m n, NoDup (seq n m).\nProof.\n  induction m; intros; simpl; constructor.\n  - unfold not; intro.\n    apply seq_minimum in H.\n    omega.\n  - auto.\nQed.\n\nLemma count_occ_app A dec :\n forall (x : A) (ys zs : list A),\n count_occ dec (ys ++ zs) x = count_occ dec ys x + count_occ dec zs x.\nProof.\n  induction ys; auto.\n  intro zs.\n  simpl.\n  rewrite (IHys zs).\n  destruct (dec a x); omega.\nQed.\n\nFixpoint scan_left (A B : Type) (f : A -> B -> A) (bs : list B) \n(a : A): list A :=\n  match bs with\n  | nil => a :: nil\n  | b :: bs' => let a' := f a b in a :: scan_left f bs' a'\n  end.\n\nLemma scanl_exist_tl A B :\n forall (f : A -> B -> A) bs a, exists as', scan_left f bs a = a :: as'.\nProof.\n  intros.\n  destruct bs.\n  - simpl.\n    exists nil.\n    reflexivity.\n  - simpl.\n    exists (scan_left f bs (f a b)).\n    reflexivity.\nQed.\n\nLemma foldl_scanl_last A B :\n forall f (bs : list B) (a : A) d,\n fold_left f bs a = last (scan_left f bs a) d.\nProof.\n  induction bs as [| b bs' IHbs'].\n  - intros a d.\n    reflexivity.\n  - intros.\n    simpl fold_left.\n    specialize (IHbs' (f a b) d).\n    rewrite IHbs'.\n    simpl scan_left.\n    remember (scanl_exist_tl f bs' (f a b)) as Extl; clear HeqExtl.\n    destruct Extl.\n    rewrite H.\n    reflexivity.\nQed.\n\nFixpoint rep A (a : A) (n : nat): list A :=\n  match n with\n  | O => nil\n  | S n' => a :: rep a n'\n  end.\nLemma rep_length A a n : length (@rep A a n) = n.\nProof.\n  induction n; simpl; auto.\nQed.\n\nLemma rep_in A a n : forall x, In x (@rep A a n) -> a = x.\nProof.\n  induction n; simpl; intuition.\nQed.\n\nLemma rep_count A dec a n : count_occ dec (@rep A a n) a = n.\nProof.\n  induction n; auto.\n  simpl.\n  case (dec a a); intro; auto.\n  exfalso; apply n0.\n  reflexivity.\nQed.\n\nLemma rep_count_0 A dec a b n : a <> b -> count_occ dec (@rep A a n) b = 0.\nProof.\n  intro a_ne_b.\n  induction n; auto.\n  simpl.\n  case (dec a b); intro; try contradiction; auto.\nQed.\n", "meta": {"author": "kazkob", "repo": "coq_DFA", "sha": "2338355a0d93a337027ea99525b6381602a2a19b", "save_path": "github-repos/coq/kazkob-coq_DFA", "path": "github-repos/coq/kazkob-coq_DFA/coq_DFA-2338355a0d93a337027ea99525b6381602a2a19b/Util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.8289388019824947, "lm_q1q2_score": 0.6637246689743854}}
{"text": "Require Coq.Logic.Classical_Prop.\nRequire Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.lemma_inequalitysymmetric.\nRequire Import ProofCheckingEuclid.lemma_onray_betweenness.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_onray_orderofpoints_any :\n\tforall A B P,\n\tOnRay A B P ->\n\t(BetS A P B \\/ eq B P \\/ BetS A B P).\nProof.\n\tintros A B P.\n\tintros OnRay_AB_P.\n\n\tassert (~ ~ (BetS A P B \\/ eq B P \\/ BetS A B P)) as BetS_A_P_B_or_eq_B_P_or_BetS_A_B_P.\n\t{\n\t\tintro n_BetS_A_P_B_or_eq_B_P_or_BetS_A_B_P.\n\n\t\tapply Classical_Prop.not_or_and in n_BetS_A_P_B_or_eq_B_P_or_BetS_A_B_P as (\n\t\t\tnBetS_A_P_B & n_eq_B_P_or_BetS_A_B_P\n\t\t).\n\t\tapply Classical_Prop.not_or_and in n_eq_B_P_or_BetS_A_B_P as (neq_B_P & nBetS_A_B_P).\n\t\tpose proof (lemma_inequalitysymmetric _ _ neq_B_P) as neq_P_B.\n\t\tpose proof (lemma_onray_betweenness _ _ _ OnRay_AB_P neq_P_B nBetS_A_P_B) as BetS_A_B_P.\n\n\t\tcontradict BetS_A_B_P.\n\t\texact nBetS_A_B_P.\n\t}\n\tapply Classical_Prop.NNPP in BetS_A_P_B_or_eq_B_P_or_BetS_A_B_P.\n\texact BetS_A_P_B_or_eq_B_P_or_BetS_A_B_P.\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_orderofpoints_any.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695208, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6637246653113347}}
{"text": "From Coq Require Import Arith.Arith.\nFrom Coq Require Import Bool.Bool.\nFrom Coq Require Import Strings.String.\nFrom Coq Require Import Lists.List.\nImport ListNotations.\nRequire Import FunInd FMapInterface.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.FSets.FMapInterface.\nRequire Import Lia.\n\n(* Definition of Pure Lambda Calculus *)\n\nInductive tm : Type :=\n| tm_var   : nat -> tm\n| tm_app   : tm -> tm -> tm\n| tm_abs   : tm -> tm.\n\nInductive value : tm -> Prop :=\n| v_abs : forall t,\n    value (tm_abs t)\n| v_var : forall x,\n    value (tm_var x).\n\nInductive nonvalue : tm -> Prop :=\n| nv_app : forall t1 t2,\n    nonvalue (tm_app t1 t2).\n\nFixpoint isvalue (p:tm) : bool :=\n  match p with\n  | tm_abs _ => true\n  | tm_var _ => true\n  | tm_app _ _ => false\n  end.\n\n(* De Brujin index *)\n\nFixpoint liftX  (n : nat) (t : tm) : tm :=\n  match t with \n  | tm_var ix =>\n    if lt_dec ix n then t else tm_var (S ix)\n  | tm_abs x1 => tm_abs (liftX (S n) x1)\n  | tm_app x1 x2 => tm_app (liftX n x1) (liftX n x2)\n  end.\n\nFixpoint substX (n:  nat) (u:  tm) (t: tm) : tm :=\n  match t with\n  | tm_var ix =>\n    if lt_dec ix n\n    then tm_var ix\n    else if lt_dec n ix\n         then tm_var (ix - 1)\n         else u\n  | tm_abs x2\n    => tm_abs (substX (S n) (liftX 0 u) x2)\n  | tm_app x1 x2 \n    => tm_app (substX n u x1) (substX n u x2)\n  end.\n\nLtac kill_lift :=\n  match goal with \n  | [ |- context [lt_dec ?n ?n'] ]\n    => case (lt_dec n n'); intros\n  | [H: context [lt_dec ?n ?n'] |- _]\n    => destruct (lt_dec n n'); intros\n  end.\n\nLtac solve_lift :=\n  lia || kill_lift || auto using Nat.sub_0_r || simpl.\n\nLemma liftX_liftX: forall t1 n n',\n    liftX n (liftX (n + n') t1) \n    = liftX (1 + (n + n')) (liftX n t1).\nProof with eauto.\n  induction t1; intros; simpl in *...\n  - repeat solve_lift.\n  - rewrite IHt1_1. rewrite IHt1_2...\n  - specialize IHt1 with (S n) n'.\n    assert (S (n + n') = S n + n') by lia.\n    rewrite H.\n    rewrite IHt1...\nQed.\n    \nLemma substX_liftX: forall t1 t2 n,\n    substX n t2 (liftX n t1) = t1.\nProof with eauto.\n  induction t1; intros; simpl...\n  - repeat solve_lift...\n  - rewrite IHt1_1. rewrite IHt1_2. reflexivity.\n  - rewrite IHt1...\nQed.\n\nLemma liftX_substX: forall t1 t2 n n',\n    liftX n (substX (n + n') t2 t1)\n    = substX (1 + n + n') (liftX n t2) (liftX n t1).\nProof with eauto.\n  induction t1; intros; simpl in *...\n  - repeat solve_lift.\n    assert (S (n - 1) = n - 0) by lia.\n    rewrite H...\n  - rewrite <- IHt1_1. rewrite IHt1_2. reflexivity.\n  - specialize IHt1 with (liftX 0 t2) (S n) n'.\n    assert (S (n + n') = S n + n') by lia.\n    rewrite H. rewrite IHt1. simpl.\n    assert (liftX 0 (liftX n t2) = liftX (S n) (liftX 0 t2)). {\n      assert (n = 0 + n) by lia.\n      rewrite H0.\n      rewrite liftX_liftX with t2 0 n.\n      auto.\n    }\n    rewrite H0...\nQed.\n\nLemma liftX_substX': forall t1 t2 n n',\n    liftX (n + n') (substX n t2 t1)\n    = substX n (liftX (n + n') t2) (liftX (1 + n + n') t1).\nProof with eauto.\n  induction t1; intros; simpl in *...\n  - repeat solve_lift.\n    assert (S (n - 1) = n - 0) by lia.\n    rewrite H...\n  - rewrite <- IHt1_1. rewrite IHt1_2...\n  - specialize IHt1 with (liftX 0 t2) (S n) n'.\n    assert (S (n + n') = S n + n') by lia.\n    rewrite H. rewrite IHt1. simpl.\n    assert (liftX (S (n + n')) (liftX 0 t2) = liftX 0 (liftX (n + n') t2)). {\n      assert (n + n' = 0 + (n + n')) by lia.\n      rewrite H0.\n      rewrite liftX_liftX.\n      auto.\n    }\n    rewrite <- H0...\nQed.\n\nLemma substX_substX: forall t1 t2 t3 n m,\n    substX (n + m) t3 (substX n t2 t1)\n    = substX n (substX (n + m) t3 t2)\n             (substX (1 + n + m) (liftX n t3) t1).\nProof with eauto.\n  induction t1; intros; simpl in *...\n  - repeat solve_lift. rewrite substX_liftX...\n  - rewrite IHt1_1. rewrite IHt1_2...\n  - specialize IHt1 with (liftX 0 t2) (liftX 0 t3) (S n) m.\n    assert (S (n + m) = S n + m) by lia.\n    rewrite H. rewrite IHt1. simpl.\n    assert (liftX (S n) (liftX 0 t3) = liftX 0 (liftX n t3)). {\n      assert (S n = 1 + (0 + n)) by lia. rewrite H0.\n      rewrite <- liftX_liftX...\n    }\n    rewrite H0.\n    assert (substX (S (n + m)) (liftX 0 t3) (liftX 0 t2) = liftX 0 (substX (n + m) t3 t2)). {\n      assert (S (n + m) = 1 + 0 + (n + m)) by lia.\n      rewrite H1. rewrite <- liftX_substX...\n    }\n    rewrite H1...\nQed.\n\n(* Evaluation *)\n\n(* Weak Head reduction *)\nInductive step : tm -> tm -> Prop :=\n| ST_AppAbs : forall t1 v2,\n    value v2 ->\n    step (tm_app (tm_abs t1) v2) (substX 0 v2 t1)\n| ST_App1 : forall t1 t1' t2,\n    step t1 t1' ->\n     step (tm_app t1 t2) (tm_app t1' t2)\n| ST_App2 : forall v1 t2 t2',\n    value v1 ->\n    step t2 t2' ->\n    step (tm_app v1 t2) (tm_app v1 t2').\n\n(* Beta reduction *)\nInductive reduce : tm -> tm -> Prop :=\n| Red_Self : forall t, reduce t t\n| Red_Body : forall t1 t2,\n    reduce t1 t2 ->\n    reduce (tm_abs t1) (tm_abs t2)\n| Red_App1 : forall t1 t1' t2 t2',\n    reduce t1 t1' ->\n    reduce t2 t2' ->\n    reduce (tm_app t1 t2) (tm_app t1' t2')\n| Red_App2 : forall t1 t1' v2 v2',\n    value v2 ->\n    reduce t1 t1' ->\n    reduce v2 v2' ->\n    reduce (tm_app (tm_abs t1) v2) (substX 0 v2' t1').\n\n(* Non-head reduction *)\nInductive ireduce : tm -> tm -> Prop :=\n| Int_Self : forall t, ireduce t t\n| Int_Body : forall t1 t2,\n    reduce t1 t2 ->\n    ireduce (tm_abs t1) (tm_abs t2)\n| Int_App1 : forall t1 t1' t2 t2',\n    nonvalue t1 ->\n    ireduce t1 t1' ->\n    reduce t2 t2' ->\n    ireduce (tm_app t1 t2) (tm_app t1' t2')\n| Int_App2 : forall t1 t1' t2 t2',\n    ireduce t1 t1' ->\n    ireduce t2 t2' ->\n    ireduce (tm_app t1 t2) (tm_app t1' t2').\n\nHint Constructors value : core.\nHint Constructors nonvalue : core.\nHint Constructors step :  core.\nHint Constructors reduce : core.\nHint Constructors ireduce : core.\n\nInductive multi {X : Type} (R : relation X) : relation X :=\n| multi_refl : forall (x : X), multi R x x\n| multi_step : forall (x y z : X),\n    R x y ->\n    multi R y z ->\n    multi R x z.\n\nTheorem multi_R : forall (X : Type) (R : relation X) (x y : X),\n    R x y -> (multi R) x y.\nProof.\n  intros X R x y H.\n  apply multi_step with y. apply H. apply multi_refl.\nQed.\n\nTheorem multi_trans :\n  forall (X : Type) (R : relation X) (x y z : X),\n      multi R x y  ->\n      multi R y z ->\n      multi R x z.\nProof.\n  intros X R x y z G H.\n  induction G.\n    - assumption.\n    - apply multi_step with y. assumption.\n      apply IHG. assumption.\nQed.\n\nNotation mstep := (multi step).\nNotation mreduce := (multi reduce).\nNotation mireduce := (multi ireduce).\n\n(* Example *)\n\nExample e1: mstep (tm_app (tm_abs (tm_var 1000)) (tm_var 100)) (tm_var 999).\nProof.\n  apply multi_R.\n  constructor. constructor.\nQed.\n\nInductive halt : tm -> Prop :=\n| Halt : forall t1 t2, mstep t1 t2 -> value t2 -> halt t1.\n\nHint Constructors halt:Core.\n\nInductive val_or_not : tm -> Prop :=\n| Is_Val : forall t, value t -> val_or_not t\n| Not_Val : forall t, nonvalue t -> val_or_not t.\n\nHint Constructors val_or_not:Core.\n\nLemma decide_val : forall t,\n    val_or_not t.\nProof with eauto.\n  destruct t.\n  - apply Is_Val...\n  - apply Not_Val...\n  - apply Is_Val...\nQed.\n\nLemma step_nvalue : forall t1 t2,\n    step t1 t2 -> nonvalue t1.\nProof with eauto.\n  intros. induction H... Qed.\n\n(* Reduction *)\n\nLemma step_implies_reduce : forall t1 t2,\n    step t1 t2 -> reduce t1 t2.\nProof with eauto.\n  intros. induction H... Qed.\n\nLemma mstep_implies_mreduce : forall t1 t2,\n    mstep t1 t2 -> mreduce t1 t2.\nProof with eauto.\n  intros.\n  induction H;\n    eauto using step_implies_reduce, multi_trans, multi_R.\nQed.\n\nLemma reduce_val : forall t1 t2,\n    reduce t1 t2 -> value t1 -> value t2.\nProof with eauto.\n  intros. destruct H0; inversion H; subst; constructor.\nQed.\n\nLemma reduce_compact : forall t1 t2 t2',\n    reduce t2 t2' -> reduce (tm_app t1 t2) (tm_app t1 t2).\nProof with eauto.\n  intros. induction H... Qed.\n\nLemma lift_inv_val : forall t1 n,\n    value t1 <-> value (liftX n t1).\nProof with eauto.\n  intros. split; intros.\n  - induction n; destruct H; simpl;     \n      solve [repeat constructor ||\n                    match goal with\n                    | [|- context[if ?a then _ else ?c]] => destruct a\n                    end].\n  - induction t1... simpl in *. inversion H.\nQed.\n\nLemma lift_inv_nonval : forall t1 n,\n    nonvalue t1 <-> nonvalue (liftX n t1).\nProof with eauto.\n  intros. split; intros.\n  - induction n; destruct H; simpl;\n      try solve [constructor].\n  - induction t1; simpl in H...\n    destruct (lt_dec n0 n); inversion H.\n    inversion H.\nQed.\n\nLemma subst_inv_val : forall t1 t2 n,\n    value t2 ->\n    value t1 <-> value (substX n t2 t1).\nProof with eauto.\n  intros. split; intros.\n  - induction t1; destruct H; simpl;\n      try repeat solve_lift; inversion H0.\n  - induction t1; destruct H; simpl; inversion H0...\nQed.\n\nLemma subst_inv_nval : forall t1 t2 n,\n    value t2 ->\n    nonvalue t1 <-> nonvalue (substX n t2 t1).\nProof with eauto.\n  intros. split; intros.\n  - induction t1; destruct H; simpl;\n      try repeat solve_lift; inversion H0.\n  - induction t1; simpl in *...\n    destruct (lt_dec n0 n) eqn:Eb...\n    destruct (lt_dec n n0) eqn:Eb'...\n    inversion H0.\n    destruct H0. inversion H.\n    inversion H0.\nQed.\n\nLemma step_subst : forall t1 t2 t2' n,\n    step t2 t2' -> value t1 ->\n    step (substX n t1 t2) (substX n t1 t2').\nProof with eauto.\n  intros.\n  generalize dependent t1.\n  generalize dependent n.\n  induction H; intros; simpl in *...\n  + assert (n = 0 + n) by lia.\n    rewrite H1. rewrite substX_substX.\n    constructor. rewrite <- subst_inv_val...\n  + constructor... rewrite <- subst_inv_val...\nQed.\n\nLemma reduce_lift : forall t1 t1' n,\n    reduce t1 t1' ->\n    reduce (liftX n t1) (liftX n t1').\nProof with eauto.\n  intros. generalize dependent n.\n  induction H; intros; simpl in *...\n  - assert (n = 0 + n) by lia.\n    rewrite H2.\n    rewrite liftX_substX'.\n    simpl.\n    constructor...\n    apply lift_inv_val...\nQed.\n\nLemma reduce_subst : forall t1 t1' t2 t2' n, \n    reduce t1 t1' -> reduce t2 t2' -> value t2 ->\n    reduce (substX n t2 t1) (substX n t2' t1').\nProof with eauto using reduce_lift.\n  intros. generalize dependent n.\n  generalize dependent t2. generalize dependent t2'.\n  induction H; simpl in *...\n  - induction t; intros; simpl in *...\n    + repeat solve_lift.\n    + constructor... apply IHt... rewrite <- lift_inv_val...\n  - intros. constructor. apply IHreduce... rewrite <- lift_inv_val...\n  - intros. assert (n = 0 + n) by lia. rewrite H4.\n    rewrite substX_substX. simpl.\n    constructor... rewrite <- subst_inv_val...\n    apply IHreduce1... rewrite <- lift_inv_val...\nQed.\n\nLemma ireduce_subst : forall t1 t1' t2 t2' n, \n    ireduce t1 t1' -> reduce t2 t2' -> value t2 ->\n    ireduce (substX n t2 t1) (substX n t2' t1').\nProof with eauto using reduce_subst, reduce_lift.\n  intros. generalize dependent n.\n  generalize dependent t2. generalize dependent t2'.\n  induction H; simpl in *...\n  - induction t; intros; simpl in *...\n    repeat solve_lift.\n    destruct H1. inversion H0...\n    inversion H0; subst...\n    constructor. apply reduce_subst...\n    rewrite <- lift_inv_val...\n  - intros. constructor. apply reduce_subst...\n    rewrite <- lift_inv_val...\n  - intros. constructor. rewrite <- subst_inv_nval...\n    apply IHireduce...\n    apply reduce_subst...\nQed.\n  \nLemma ireduce_nval : forall t1 t2,\n    ireduce t1 t2 -> nonvalue t1 -> nonvalue t2.\nProof with eauto.\n  intros. induction H... inversion H0. Qed.\n\nLemma ireduce_inv_val : forall t1 t2,\n    ireduce t1 t2 -> value t2 -> value t1.\nProof with eauto.\n  intros. induction H; try solve [inversion H0]... Qed.\n\nLemma ireduce_inv_nval : forall t1 t2,\n    ireduce t1 t2 -> nonvalue t2 -> nonvalue t1.\nProof with eauto.\n  intros. induction H; try solve [inversion H0]... Qed.\n\nLemma mireduce_inv_val : forall t1 t2,\n    mireduce t1 t2 -> value t2 -> value t1.\nProof with eauto.\n  intros. induction H; eauto using ireduce_inv_val.\nQed.\n\nLemma mireduce_inv_nval : forall t1 t2,\n    mireduce t1 t2 -> nonvalue t2 -> nonvalue t1.\nProof with eauto.\n  intros. induction H; eauto using ireduce_inv_nval...\nQed.\n\nLemma ireduce_implies_reduce: forall t1 t2,\n    ireduce t1 t2 -> reduce t1 t2.\nProof with eauto.\n  intros. induction H... Qed.\n\nInductive sreduce : tm -> tm -> Prop :=\n| SRed__z : forall t1 t2,\n    ireduce t1 t2 -> sreduce t1 t2\n| SRed__s : forall t1 t2 t3,\n    reduce t1 t3 -> step t1 t2 -> sreduce t2 t3 -> sreduce t1 t3.\n\nHint Constructors sreduce : Core.\n\nLemma sreduce_implies_reduce : forall t1 t2,\n    sreduce t1 t2 -> reduce t1 t2.\nProof with eauto.\n  intros. induction H... induction H... Qed.\n\n(* Lemma 2 *)\nLemma sreduce_app_nval : forall t1 t1' t2 t2',\n    sreduce t1 t1' -> reduce t2 t2' -> nonvalue t1' ->\n    sreduce (tm_app t1 t2) (tm_app t1' t2').\nProof with eauto.\n  intros. generalize dependent t2. generalize dependent t2'.\n  induction H.\n  - constructor... constructor... eapply ireduce_inv_nval...\n  - intros. eapply IHsreduce in H1. eapply SRed__s in H1... assumption.\nQed.\n\nLemma sreduce_app_val : forall t1 t1' t2 t2',\n    sreduce t1 t1' -> sreduce t2 t2' -> value t1' ->\n    sreduce (tm_app t1 t2) (tm_app t1' t2').\nProof with eauto.\n  intros.\n  generalize dependent t2. generalize dependent t2'.\n  induction H; intros; induction H0; simpl in *;\n    try solve\n        [eapply SRed__s; eauto; constructor; eauto;\n         apply sreduce_implies_reduce; eauto]...\n  - constructor. apply Int_App2...\n  - eapply SRed__s... constructor...\n    apply ireduce_implies_reduce...\n    constructor... eapply ireduce_inv_val in H1...\nQed.\n\n(* Lemma 3 *)\nLemma sreduce_app: forall t1 t1' t2 t2',\n    sreduce t1 t1' -> sreduce t2 t2' ->\n    sreduce (tm_app t1 t2) (tm_app t1' t2').\nProof with eauto.\n  intros. assert (val_or_not t1') by auto using decide_val.\n  inversion H1; subst.\n  - apply sreduce_app_val...\n  - apply sreduce_app_nval...\n    apply sreduce_implies_reduce...\nQed.\n\nLemma sreduce_compact: forall t1 t2 t2' n,\n    sreduce t2 t2' -> value t2 ->\n    sreduce (substX n t2 t1 ) (substX n t2' t1).\nProof with eauto.\n  induction t1; simpl; intros; try repeat solve_lift...\n  - repeat constructor.\n  - repeat constructor.\n  - apply sreduce_app.\n    apply IHt1_1... apply IHt1_2...\n  - constructor. constructor.\n    apply reduce_subst...\n    apply reduce_lift... apply sreduce_implies_reduce...\n    rewrite <- lift_inv_val...\nQed.\n\n(* Lemma 4 *)\nLemma ireduce_sreduce_subst: forall t1 t1' t2 t2' n,\n    ireduce t1 t1' -> sreduce t2 t2' -> value t2 ->\n    sreduce (substX n t2 t1) (substX n t2' t1').\nProof with eauto.\n  intros.\n  generalize dependent t2. generalize dependent t2'.\n  generalize dependent n.\n  induction H; simpl in *...\n  - intros. apply sreduce_compact...\n  - intros. constructor. constructor.\n    apply reduce_subst... apply reduce_lift...\n    apply sreduce_implies_reduce...\n    rewrite <- lift_inv_val...\n  - intros. repeat constructor.\n    rewrite <- subst_inv_nval...\n    apply ireduce_subst...\n    apply sreduce_implies_reduce...\n    apply reduce_subst...\n    apply sreduce_implies_reduce in H2...\n  - intros. constructor. apply sreduce_implies_reduce in H1.\n    apply Int_App2; apply ireduce_subst...\nQed.\n\n(* Lemma 5 *)\nLemma sreduce_subst: forall t1 t1' t2 t2' n,\n    sreduce t1 t1' ->\n    sreduce t2 t2' -> value t2 ->\n    sreduce (substX n t2 t1) (substX n t2' t1').\nProof with eauto.\n  intros.\n  generalize dependent t2. generalize dependent t2'.\n  generalize dependent n.\n  induction H; intros.\n  - apply ireduce_sreduce_subst...\n  - eapply SRed__s.\n    + apply reduce_subst...\n      apply sreduce_implies_reduce...\n    + apply step_subst...\n    + apply IHsreduce...\nQed.\n\nLemma reduce_implies_sreduce: forall t1 t2,\n    reduce t1 t2 -> sreduce t1 t2.\nProof with eauto.\n  intros. induction H.\n  - repeat constructor.\n  - repeat constructor...\n  - apply sreduce_app...\n  - eapply SRed__s.\n    constructor...\n    constructor...\n    apply sreduce_subst...\nQed.\n\nLemma sreduce_implies_mstep_ireduce: forall t1 t3,\n    sreduce t1 t3 -> exists t2, mstep t1 t2 /\\ ireduce t2 t3.\nProof with eauto using multi_R, multi_trans.\n  intros.\n  induction H...\n  - eexists. split... constructor.\n  - destruct IHsreduce. destruct H2.\n    exists x. split...\nQed.\n\n(* Lemma 6: main lemma*)\nLemma reduce_implies_mstep_ireduce: forall t1 t3,\n    reduce t1 t3 -> exists t2, mstep t1 t2 /\\ ireduce t2 t3.\nProof.\n  eauto using sreduce_implies_mstep_ireduce, reduce_implies_sreduce. Qed.\n \nLtac kill_step :=\n  match goal with\n    | [H: step _ _ |- _] => inversion H \n    | [H: step _ _ |- _] => inversion H\n    | [H: value (tm_app ?a ?b) |- _] => inversion H\n    | [H: value ?a, G: step ?a _ |- _] => destruct H; inversion G\n  end.\n\nLtac solve_step :=\n  kill_step || auto || simpl in *.\n\n(* Postponement *)\n\n(* Lemma 7: Postponement *)\nLemma ireduce_step_implies_step_reduce: forall t1 t2 t3,\n    ireduce t1 t2 -> step t2 t3 ->\n    exists t2', step t1 t2' /\\ reduce t2' t3.\nProof with eauto.\n  (* \n    Note: the paper said induction on t1\n    But in fact you will lost information by that\n    So we induct by hypothesis on Coq\n  *)\n  intros. generalize dependent t3.\n  induction H; intros.\n  - eexists...\n  - inversion H0.\n  - apply ireduce_nval in H0 as H'...\n    destruct H'. destruct H.\n    inversion H2; subst...\n    eapply IHireduce in H5...\n    destruct H5. destruct H. eexists. split...\n    inversion H4.\n  - apply ireduce_implies_reduce in H as I.\n    apply ireduce_implies_reduce in H0 as I0.\n    inversion H1; subst... \n    + apply ireduce_inv_val in H as H'...\n      apply ireduce_inv_val in H0 as H''...\n      destruct H'; try solve [inversion H].\n      eexists. split. constructor...\n      inversion H; subst; apply reduce_subst...\n    + apply step_nvalue in H5 as H'.\n      apply ireduce_inv_nval in H...\n      destruct H. destruct H'.\n      apply IHireduce1 in H5.\n      destruct H5. destruct H.\n      eexists. split...\n    + apply IHireduce2 in H6. destruct H6. destruct H2.\n      eexists (tm_app t1 x). split... constructor...\n      apply ireduce_inv_val in H...\nQed.\n\n(* Collary 8 *)\nLemma ireduce_step_implies_mstep_ireduce: forall t1 t2 t3,\n    ireduce t1 t2 -> step t2 t3 ->\n    exists t2', mstep t1 t2' /\\ ireduce t2' t3.\nProof with eauto.\n  intros.\n  eapply ireduce_step_implies_step_reduce in H...\n  destruct H. destruct H.\n  apply reduce_implies_mstep_ireduce in H1.\n  destruct H1. destruct H1.\n  eexists. split...\n  eapply multi_trans...\n  eapply multi_R...\nQed.\n  \nLemma ireduce_mstep_implies_mstep_ireduce: forall t1 t2 t3,\n    ireduce t1 t2 -> mstep t2 t3 ->\n    exists t2', mstep t1 t2' /\\ ireduce t2' t3.\nProof with eauto.\n  intros. revert dependent t1.\n  induction H0; intros.\n  - eexists. split... constructor.\n  - eapply ireduce_step_implies_mstep_ireduce with t1 x y in H1...\n    destruct H1 as [? [?]].\n    apply IHmulti in H2.\n    destruct H2 as [? [?]].\n    eapply multi_trans in H2...\nQed.\n\n(* Evaluation *)\n\nLemma reduce_mstep_implies_mstep_ireduce: forall t1 t2 t3,\n    reduce t1 t2 -> mstep t2 t3 ->\n    exists t2', mstep t1 t2' /\\ ireduce t2' t3.\nProof with eauto.\n  intros. \n  apply reduce_implies_mstep_ireduce in H.\n  destruct H as [? [?]].\n  eapply ireduce_mstep_implies_mstep_ireduce in H1...\n  destruct H1 as [? [?]].\n  eapply multi_trans in H1...\nQed.\n\n(* Lemma 9: Bifurcation *)\nLemma mreduce_implies_mstep_mireduce: forall t1 t3,\n    mreduce t1 t3 ->\n    exists t2, mstep t1 t2 /\\ mireduce t2 t3.\nProof with eauto.\n  intros. induction H...\n  - eexists. split; constructor.\n  - destruct IHmulti as [? [?]].\n    eapply reduce_mstep_implies_mstep_ireduce with x y x0 in H...\n    destruct H as [? [?]].\n    eexists. split...\n    econstructor...  \nQed.\n\n(* Confluence *)\n\nLemma diamond: forall t1 t2 t2',\n    reduce t1 t2 -> reduce t1 t2' ->\n    exists t3, reduce t2 t3 /\\ reduce t2' t3.\nProof with eauto using reduce_val, reduce_subst.\n  intros. generalize dependent t2'.\n  induction H; intros...\n  - inversion H0; subst...\n    apply IHreduce in H2...\n    destruct H2. destruct H1.\n    exists (tm_abs x). split...\n  - inversion H1; subst...\n    + apply IHreduce1 in H4. apply IHreduce2 in H6.\n      destruct H4 as [? [?]]. destruct H6 as [? [?]].\n      exists (tm_app x x0). split...\n    + assert (reduce (tm_abs t0) (tm_abs t1'0)) by auto.\n      apply IHreduce1 in H2. destruct H2 as [? [?]].\n      apply reduce_val in H7 as H7'...\n      apply IHreduce2 in H7. destruct H7 as [? [?]].\n      (* a lot of inversions... *)\n      inversion H; subst; inversion H2; subst; inversion H3; subst;\n        try solve [exists (substX 0 x0 t0); split; eauto using reduce_val, reduce_subst];\n        try solve [exists (substX 0 x0 t3); split; eauto using reduce_val, reduce_subst];\n        try solve [exists (substX 0 x0 t4); split; eauto using reduce_val, reduce_subst].\n  - inversion H2; subst...\n    + apply reduce_val in H7 as H7'...\n      apply IHreduce2 in H7. destruct H7 as [? [?]].\n      inversion H5; subst.\n      * exists (substX 0 x t1'). split...\n      * apply IHreduce1 in H7. destruct H7 as [? [?]].\n        exists (substX 0 x x0). split...\n    + apply IHreduce1 in H6 as H6'. destruct H6' as [? [?]].\n      apply IHreduce2 in H8 as H8'. destruct H8' as [? [?]].\n      exists (substX 0 x0 x). split...\nQed.\n\nLemma strip: forall t1 t2 t2',\n    reduce t1 t2 -> mreduce t1 t2' ->\n    exists t3, mreduce t2 t3 /\\ reduce t2' t3.\nProof with eauto using multi_R.\n  intros. revert dependent t2. induction H0; intros...\n  apply diamond with x y t2 in H as H'... destruct H' as [? [?]].\n  apply IHmulti in H2. destruct H2 as [? [?]].\n  eapply multi_step in H2...\nQed.\n\nLemma confluence: forall t1 t2 t2',\n    mreduce t1 t2 -> mreduce t1 t2' ->\n    exists t3, mreduce t2 t3 /\\ mreduce t2' t3.\nProof with eauto using multi_R.\n  intros. revert dependent t2'. induction H; intros...\n  apply strip with x y t2' in H as H'... destruct H' as [? [?]].\n  apply IHmulti in H2. destruct H2 as [? [?]].\n  eapply multi_step in H3...\nQed.\n\n(* Termincation *)\n\nLemma rhalt_implies_halt : forall t1 t2,\n    mreduce t1 t2 -> value t2 -> halt t1.\nProof with eauto.\n  intros.\n  apply mreduce_implies_mstep_mireduce in H.\n  destruct H as [? [?]].\n  apply mireduce_inv_val in H1...\n  econstructor...\nQed.\n\nLemma reduce_inv_preserves_halt: forall t1 t2,\n    mreduce t1 t2 -> halt t2 -> halt t1.\nProof with eauto.\n  intros. destruct H0.\n  apply mstep_implies_mreduce in H0.\n  eapply multi_trans in H0...\n  eapply rhalt_implies_halt...\nQed.\n\n(* Theorem 10: Adequacy of Reduction *)\nLemma reduce_preserves_halt: forall t1 t2,\n    reduce t1 t2 -> halt t1 -> halt t2.\nProof with eauto.\n  intros. destruct H0.\n  apply mstep_implies_mreduce in H0.\n  eapply strip in H...\n  destruct H as [? [?]].\n  apply reduce_val in H2...\n  eapply rhalt_implies_halt...\nQed.\n\n(* Standardization *)\n\n(* Definition 11 *)\nInductive treduce : tm -> tm -> Prop :=\n| TRed__z : forall t, treduce t t\n| TRed__s : forall t1 t2 t3,\n    step t1 t2 ->\n    treduce t2 t3 ->\n    treduce t1 t3\n| TRed__lam : forall t1 t2,\n    treduce t1 t2 ->\n    treduce (tm_abs t1) (tm_abs t2)\n | TRed__App : forall t1 t1' t2 t2',\n    treduce t1 t1' ->\n    treduce t2 t2' ->\n    treduce (tm_app t1 t2) (tm_app t1' t2').\n\nHint Constructors treduce.\n\nLemma mstep_treduce_trans : forall t1 t2 t3,\n    mstep t1 t2 -> treduce t2 t3 -> treduce t1 t3.\nProof with eauto.\n  intros. induction H... Qed.\n\nLemma mstep_implies_treduce : forall t1 t2,\n    mstep t1 t2 -> treduce t1 t2.\nProof with eauto.\n  intros. eapply mstep_treduce_trans... Qed.\n\nInductive wmireduce : tm -> tm -> Prop :=\n| WMIRed__ident : forall t, wmireduce t t\n| WMIRed__lam : forall t1 t2,\n    mreduce t1 t2 ->\n    wmireduce (tm_abs t1) (tm_abs t2)\n| WMIRed__App : forall t1 t1' t2 t2',\n    mreduce t1 t1' ->\n    mreduce t2 t2' ->\n    wmireduce (tm_app t1 t2) (tm_app t1' t2').\n\nHint Constructors wmireduce.\n\nLtac kill_multi :=\n  match goal with\n  | [H: context[reduce ?t1 ?t2], I: context[mreduce ?t2 ?t3] |- mreduce ?t1 ?t3 ] => \n    eapply multi_trans; eauto; eapply multi_R; eauto\n  end.\n\nLemma ireduce_wmireduce_trans : forall t1 t2 t3,\n    ireduce t1 t2 -> wmireduce t2 t3 -> wmireduce t1 t3.\nProof with eauto.\n  intros. generalize dependent t3. \n  induction H; intros; eauto using multi_R.\n  - inversion H0; subst; constructor;\n      eauto using ireduce_implies_reduce, multi_R.\n    kill_multi.\n  - inversion H2; subst; constructor;\n      eauto using ireduce_implies_reduce, multi_R;\n      apply ireduce_implies_reduce in H0; kill_multi.\n  - inversion H1; subst; constructor;\n      eauto using ireduce_implies_reduce, multi_R;\n      apply ireduce_implies_reduce in H, H0; kill_multi.                                        \nQed.\n\nLemma mireduce_implies_wmireduce : forall t1 t2,\n    mireduce t1 t2 -> wmireduce t1 t2.\nProof with eauto using ireduce_wmireduce_trans.\n  intros. induction H... Qed.\n\n(* Theorem 12 *)\n(* Note: the original twelf method does not work here *)\n(* I followed the idea from paper *)\nLemma mreduce_implies_treduce : forall t1 t2,\n    mreduce t1 t2 -> treduce t1 t2.\nProof with eauto using mstep_implies_treduce.\n  intros. revert dependent t1.\n  induction t2; intros;\n    apply mreduce_implies_mstep_mireduce in H as I;\n    destruct I as [? [?]].\n  - eapply mstep_treduce_trans with x...\n    clear H. clear H0. clear t1.\n    apply mireduce_inv_val in H1 as H1'...\n    destruct H1'.\n    + exfalso.\n      remember (tm_abs t). remember (tm_var n).\n      revert dependent t.\n      induction H1; intros; subst...\n      discriminate Heqt0.\n      inversion H; subst...\n    + remember (tm_var x). remember (tm_var n).\n      revert dependent x. revert dependent n.\n      induction H1; intros; subst...\n      inversion H; subst...\n  - apply mireduce_inv_nval in H1 as H1'... destruct H1'.\n    eapply mstep_treduce_trans with (tm_app t0 t2)... clear H0.\n    apply mireduce_implies_wmireduce in H1.\n    remember (tm_app t2_1 t2_2). remember (tm_app t0 t2).\n    induction H1; intros; subst...\n    + inversion Heqt.\n    + inversion Heqt; inversion Heqt3; subst.\n      clear Heqt. clear Heqt3.\n      constructor...\n  - eapply mstep_treduce_trans with x...\n    clear H. clear H0. clear t1.\n    apply mireduce_inv_val in H1 as H1'...\n    destruct H1'.\n    + constructor...\n      apply mireduce_implies_wmireduce in H1.\n      remember (tm_abs t). remember (tm_abs t2).\n      revert dependent t. revert dependent t2.\n      induction H1; intros; subst...\n      inversion Heqt0...\n      inversion Heqt0. inversion Heqt1. subst...\n      inversion Heqt0.\n    + exfalso.\n      remember (tm_abs t2). remember (tm_var x).\n      revert dependent t2.\n      induction H1; intros; subst...\n      discriminate Heqt.\n      inversion H; subst...\nQed.\n    \nLemma wmireduce_implies_treduce : forall t1 t2,\n    wmireduce t1 t2 -> treduce t1 t2.\nProof with eauto using mreduce_implies_treduce.\n  intros. induction H... Qed.\n\nInductive ctx : Type :=\n| ctxHole: ctx\n| ctxLam: ctx -> ctx\n| ctxApp1: tm -> ctx -> ctx\n| ctxApp2: ctx -> tm -> ctx.\n\nFixpoint fill_context C t :=\n  match C with\n  | ctxHole => t\n  | ctxLam C' => tm_abs (fill_context C' t)\n  | ctxApp1 t1 C' => tm_app t1 (fill_context C' t)\n  | ctxApp2 C' t2 => tm_app (fill_context C' t) t2\n  end.  \n\nLemma mreduce_app2: forall t1 t2 t2',\n    mreduce t2 t2' -> mreduce (tm_app t1 t2) (tm_app t1 t2').\nProof with eauto.\n  intros. induction H...\n  - apply multi_R. econstructor.\n  - eapply multi_trans. apply multi_R.\n    apply Red_App1... assumption.\nQed.\n\nLemma mreduce_app1: forall t1 t1' t2,\n    mreduce t1 t1' -> mreduce (tm_app t1 t2) (tm_app t1' t2).\nProof with eauto.\n  intros. induction H...\n  - apply multi_R. econstructor.\n  - eapply multi_trans. apply multi_R.\n    apply Red_App1... assumption.\nQed.\n\nLemma mreduce_abs: forall t1 t1',\n    mreduce t1 t1' -> mreduce (tm_abs t1) (tm_abs t1').\nProof with eauto.\n  intros. induction H...\n  - apply multi_R. econstructor.\n  - eapply multi_trans. apply multi_R.\n    apply Red_Body... assumption.\nQed.\n\nLemma context_mreduce: forall C t1 t2,\n    mreduce t1 t2 -> mreduce (fill_context C t1) (fill_context C t2).\nProof with eauto.\n  induction C; intros; simpl in *;\n    eauto using mreduce_abs, mreduce_app2, mreduce_app1. \nQed.\n\nLemma contextual_equivalence: forall C t1 t2,\n    mstep t1 t2 -> halt (fill_context C t1) <-> halt (fill_context C t2).\nProof with eauto using\n           value_halt, mreduce_preserves_halt, mreduce_inv_preserves_halt.\n  induction C; split; simpl in *;\n    apply mstep_implies_mreduce in H as H';\n    intros...\n  - inversion H0; subst.\n    eapply mreduce_preserves_halt...\n    apply mreduce_app2.\n    apply context_mreduce...\n  - inversion H0; subst.\n    eapply mreduce_inv_preserves_halt...\n    apply mreduce_app2.\n    apply context_mreduce...\n  - inversion H0; subst.\n    eapply mreduce_preserves_halt...\n    apply mreduce_app1.\n    apply context_mreduce...\n  - inversion H0; subst.\n    eapply mreduce_inv_preserves_halt...\n    apply mreduce_app1.\n    apply context_mreduce...\nQed.\n", "meta": {"author": "erupmi", "repo": "utlc-eval-proof", "sha": "d93eb58f6e0d79db646d56acec3ab241b681589d", "save_path": "github-repos/coq/erupmi-utlc-eval-proof", "path": "github-repos/coq/erupmi-utlc-eval-proof/utlc-eval-proof-d93eb58f6e0d79db646d56acec3ab241b681589d/cbv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6636810824679228}}
{"text": "Parameter set : Type.\nParameter In : set -> set -> Prop.\n\nNotation \"x ∈ y\" := (In x y) (at level 30).\nNotation \"x ∋ y\" := (In y x) (at level 30).\n\nDefinition subset (A B: set) : Prop :=\nforall x:set, x ∈ A -> x ∈ B.\n\nNotation \"x ⊆ y\" := (subset x y) (at level 30).\nNotation \"x ⊇ y\" := (subset y x) (at level 30).\n\nTheorem subset_reflexive : forall (A : set),\nA ⊆ A.\nProof.\nintros. unfold subset. intros.\napply H.\nQed.\n\nTheorem subset_transitive : forall (A B C : set),\nA ⊆ B /\\ B ⊆ C -> A ⊆ C.\nProof.\nintros A B C. unfold subset. intros.\ninversion H. apply H2. apply H1. apply H0.\nQed.\n\nParameter Φ : set.\nAxiom Axiom_of_Existence :\nforall x:set, not (x ∈ Φ).\n\nAxiom Axiom_of_Extensionality :\nforall (A B : set), (forall x:set, x ∈ A <-> x ∈ B) -> A = B.\n\nTheorem subset_antisymmetric : forall (A B : set),\nA ⊆ B /\\ B ⊆ A -> A = B.\nProof.\nintros. apply Axiom_of_Extensionality. \ninversion H. unfold subset in H0. unfold subset in H1.\nintros x. unfold iff. apply conj. apply H0. apply H1.\nQed.\n\nAxiom Axiom_of_Regularity : forall A : set,\n(exists B :set, B ∈ A) -> (exists B : set, B ∈ A /\\ not (exists C : set, C ∈ A /\\ C ∈ B)).\n\nAxiom Axiom_of_Pairing : forall (A B : set),\nexists C, A ∈ C /\\ B ∈ C.\n\nAxiom Axiom_of_Union : forall (A : set),\nexists U, forall (x y: set), x ∈ y /\\ y ∈ A -> x ∈ U.\n\nAxiom Axiom_of_Powerset : forall (A : set),\nexists B, forall (x : set), x ⊆ A -> x ∈ B.\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/Set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6636810703823489}}
{"text": "Require Import ZArith PArith Lia.\nRequire Import ASN1FP.Types.ASN\n        ASN1FP.Aux.Roundtrip ASN1FP.Aux.StructTactics ASN1FP.Aux.Aux\n        ASN1FP.Aux.Tactics ASN1FP.Aux.Option ASN1FP.Aux.StrongInduction.\n\nRequire Import Flocq.Core.Zaux Flocq.IEEE754.Binary Flocq.Core.Defs.\n\nOpen Scope Z.\n\n(*\n *  eqivalence on floats of the same type, returning `true`\n *  for normal equality\n *  or for any two NaN values (NaN payloads not taken into account)\n *)\nDefinition float_eqb_nan_t {prec emax : Z} (x y : binary_float prec emax) : bool :=\n  match Bcompare prec emax x y with\n  | Some Eq => true\n  | None => true\n  | _ => false\n  end.\n\nDefinition binary_bounded_sumbool (prec emax : Z) (m : positive) (e : Z) :=\n  Sumbool.sumbool_of_bool (Binary.bounded prec emax m e).\n\nSection Base2.\n\n  Variable prec emax : Z.\n  Hypothesis prec_gt_1 : prec > 1.\n  Hypothesis Hmax : (prec < emax)%Z.\n\n  (* only radix = 2 is considered for both formats in this section\n   * scaling factor is, therefore, not required in BER\n   * TODO: for arbitrary radix/scaling combinations, refer to another section\n   *)\n  Let r := radix2.\n  Let scl := 0.\n  (* can a given (m,e) pair be represented in IEEE/BER exactly *)\n  Let valid_IEEE := bounded prec emax.\n  Let valid_BER := valid_BER r scl.\n\n  (* aux: apply variables *)\n  Let IEEE_float := binary_float prec emax.\n  Let valid_IEEE_sumbool := binary_bounded_sumbool prec emax.\n  Let BER_finite_b2 := BER_finite r scl.\n  Let valid_BER_sumbool := valid_BER_sumbool r scl.\n\n  (* 1 can always be the payload of a NaN *)\n  Lemma def_NaN :\n    nan_pl prec 1 = true.\n  Proof.\n    unfold nan_pl. simpl.\n    apply Z.ltb_lt, Z.gt_lt, prec_gt_1.\n  Qed.\n\n  Lemma prec_gt_0 : Flocq.Core.FLX.Prec_gt_0 prec.\n  Proof.\n    unfold Flocq.Core.FLX.Prec_gt_0.\n    apply (Z.lt_trans 0 1 prec).\n    - (* 1 < 0 *)\n      reflexivity.\n    - (* 1 < prec *)\n      apply Z.gt_lt.\n      apply prec_gt_1.\n  Qed.\n\n  Section Def.\n\n    (*\n     * given a pair (m,e), return (mx, ex) such that\n     *   m*2^e = mx*2^ex\n     * and\n     *   m is odd\n     *)\n    Definition normalize_BER_finite_nrec (m : positive) (e : Z) : (positive * Z) :=\n      let t := N.log2 (((Pos.lxor m (m-1)) + 1) / 2) in\n      (Pos.shiftr m t, e + (Z.of_N t)).\n\n    Fixpoint normalize_BER_finite (m : positive) (e : Z) : positive * Z :=\n      match m with\n      | xO p => normalize_BER_finite p (e + 1)\n      | _ => (m, e)\n      end.\n\n    (*\n     * given all meaningful parts of a BER real, construct it, if possible\n     * The content is normalized in accordance with [ 11.3.1 ] if possible\n     *)\n    Definition make_BER_finite (s : bool) (m : positive) (e : Z)\n      : option BER_float :=\n      let '(mx, ex) := normalize_BER_finite m e in\n      match valid_BER_sumbool mx ex with\n      | left V => Some (BER_finite_b2 s mx ex V)\n      | right _ => None\n      end.\n    \n    (* TODO: radix, scaling (determine `b` and `ff`) *)\n    (*\n     * exact conversion from IEEE to BER\n     * no rounding is performed: if conversion is impossible without rounding\n     * `None` is returned\n     *)\n    Definition BER_of_IEEE_exact (f : IEEE_float) : option BER_float :=\n      match f with\n      | B754_zero _ _ s => Some (BER_zero s)\n      | B754_infinity _ _ s => Some (BER_infinity s)\n      | B754_nan _ _ _ _ _ => Some (BER_nan)\n      | B754_finite _ _ s m e _ => make_BER_finite s m e\n      end.\n\n    (*\n     * turn any pair (m,e) into a pair (mx,ex), representable in\n     * IEEE 745 if possible. No rounding is performed,\n     * (m,e) remains unchanged if normalization is impossible without rounding\n     *)\n    Definition normalize_IEEE_finite : positive -> Z -> (positive * Z) :=\n      shl_align_fexp prec emax.\n\n    (* given all meaningful parts of an IEEE float, construct it, if possible *)\n    Definition make_IEEE_finite (s : bool) (m : positive) (e : Z) : option IEEE_float :=\n      let '(mx, ex) := normalize_IEEE_finite m e in\n      match (valid_IEEE_sumbool mx ex) with\n      | left V => Some (B754_finite _ _ s mx ex V)\n      | right _ => None\n      end.\n\n    (*\n     * exact conversion from BER to IEEE\n     * radix2 with no scaling asssumed: if input does not match, 'None' returned\n     * no rounding is performed: if conversion is impossible without rounding\n     * `None` is returned\n     *)\n    Definition IEEE_of_BER_exact (f : BER_float) : option IEEE_float := \n      match f with\n      | BER_zero s => Some (B754_zero _ _ s)\n      | BER_infinity s => Some (B754_infinity _ _ s)\n      | BER_nan => Some (B754_nan _ _ false 1 def_NaN)\n      | BER_finite b f s m e _ =>\n        if andb (b =? 2) (f =? 0) then\n          make_IEEE_finite s m e\n        else None\n      end.\n\n    (*\n     *  given a triple (s,m,e) standing for s*m*2^e,\n     *  return a corresponding binary_float,\n     *  correctly rounded in accordance with the specified rounding mode\n     *)\n    Definition round_finite\n               (Hmax : prec < emax) (rounding : mode)\n               (s : bool) (m : positive) (e : Z) : IEEE_float :=\n      binary_normalize\n        prec emax prec_gt_0 Hmax\n        rounding\n        (cond_Zopp s (Zpos m)) e s.\n\n    (*\n     *  for any ASN.1 BER-encoded real number s*m*(b^e)\n     *  return the number's representation in the target IEEE format\n     *  rounded in accordnace with the provided rounding mode if necessary\n     *\n     *  NOTE:\n     *  1) If initial BER encoding has radix /= 2 or scaling factor /= 0\n     *     `None` is returned\n     *  2) If the ASN encoding is a NaN,\n     *     float's NaN payload is set to 1\n     *)\n    Definition IEEE_of_BER_rounded (Hmax : prec < emax)\n               (rounding : mode) (r : BER_float) : option (IEEE_float) :=\n      match r with\n      | BER_zero s => Some (B754_zero _ _ s)\n      | BER_infinity s => Some (B754_infinity _ _ s)\n      | BER_nan => Some (B754_nan _ _ false 1 def_NaN)\n      | BER_finite b f s m e x =>\n        if andb (b =? 2) (f =? 0)\n        then Some (round_finite Hmax rounding s m e)\n        else None\n      end.\n    \n    (*\n     *  given a binary_float and a rounding mode\n     *  convert it to target format, rounding if necessary\n     *\n     *  NaN payload is set to 1 uncoditionally\n     *)\n    Definition IEEE_of_IEEE_round_reset_nan (Hmax : prec < emax)\n               (rounding : mode) (f : IEEE_float) : IEEE_float :=\n      match f with\n      | B754_nan _ _ _ _ _ => B754_nan _ _ false 1 def_NaN\n      | B754_infinity _ _ s => B754_infinity _ _ s\n      | B754_zero _ _ s => B754_zero _ _ s\n      | B754_finite _ _ s m e _ => round_finite Hmax rounding s m e\n      end.\n\n  End Def.\n\n  Section Proof.\n\n    Definition R_of_float (m : positive) (e : Z) :=\n      F2R (Float radix2 (Zpos m) e).\n      \n    Lemma R_of_valid_IEEE_inj {m1 m2 : positive} {e1 e2 : Z} :\n      valid_IEEE m1 e1 = true -> valid_IEEE m2 e2 = true ->\n      R_of_float m1 e1 = R_of_float m2 e2 ->\n      (m1, e1) = (m2,e2).\n    Proof.\n      intros V1 V2 Req.\n      remember (B754_finite prec emax false m1 e1 V1) as f1.\n      remember (B754_finite prec emax false m2 e2 V2) as f2.\n      assert (fin_f1 : is_finite_strict prec emax f1 = true) by (subst; auto).\n      assert (fin_f2 : is_finite_strict prec emax f2 = true) by (subst; auto).\n      generalize (B2R_inj prec emax f1 f2 fin_f1 fin_f2); intros.\n      unfold B2R in H.\n      rewrite Heqf1, Heqf2 in H.\n      apply H in Req.\n      inversion Req.\n      auto.\n    Qed.\n\n    Lemma normalize_IEEE_eq (m : positive) (e : Z) :\n      R_of_float m e =\n      uncurry R_of_float (normalize_IEEE_finite m e).\n    Proof.\n      unfold R_of_float, normalize_IEEE_finite, uncurry.\n      break_let.\n      generalize (shl_align_fexp_correct prec emax m e).\n      intros H; rewrite Heqp in H; apply proj1 in H.\n      apply H.\n    Qed.\n\n    Definition Podd (p : positive) : Prop :=\n      match p with\n      | xO _ => False\n      | _ => True\n      end.\n\n    Lemma p_lt_2p (p : positive) :\n      (p < p~0)%positive.\n    Proof. rewrite <- (Pos.add_diag p); lia. Qed.\n\n    Lemma normalize_BER_odd (m : positive) (e : Z) :\n      let '(mx, ex) := normalize_BER_finite m e in\n      Podd mx.\n    Proof.\n      generalize e.\n      induction m using positive_lt_ind.\n      destruct m; try reflexivity.\n      simpl.\n      assert (H1 : (m < m~0)%positive) by apply p_lt_2p.\n      intros.\n      apply H with (y := m) (e := e0 + 1) in H1.\n      apply H1.\n    Qed.\n\n    Lemma normalize_BER_eq (m : positive) :\n      forall (e : Z),\n      let '(mx, ex) := normalize_BER_finite m e in\n      (mx, ex) = (m, e)\n      \\/\n      exists (d : positive),\n        m = (mx * 2^d)%positive /\\ e = ex - (Zpos d).\n    Proof.\n      clear Hmax valid_IEEE IEEE_float valid_IEEE_sumbool prec emax prec_gt_1 Hmax.\n      clear r valid_BER_sumbool BER_finite_b2 valid_BER.\n\n      induction m using positive_lt_ind.\n      intros.\n      destruct (normalize_BER_finite m e) as (mx,ex) eqn:NB.\n      destruct m; try (simpl in NB; tuple_inversion; left; trivial).\n      rewrite <- Pos.add_diag.\n\n      simpl in NB.\n      assert (H1 : (m < m~0)%positive) by apply p_lt_2p.\n      apply H with (y := m) (e := e + 1) in H1.\n      rewrite NB in H1.\n      destruct H1.\n      - tuple_inversion.\n        right.\n        exists (1%positive). \n        replace (2^1)%positive with 2%positive by trivial.\n        lia.\n      - right.\n        destruct H0 as [d H0].\n        exists (d + 1)%positive.\n        replace (2^(d + 1))%positive with (2 * (2^d))%positive\n          by (rewrite Positive_as_OT.add_1_r, Positive_as_DT.pow_succ_r; trivial).\n        lia.\n    Qed.\n\n    Lemma normalize_BER_spec (m mx : positive) (e ex : Z) :\n      (mx, ex) = normalize_BER_finite m e ->\n      Podd mx\n      /\\\n      ((mx, ex) = (m, e)\n      \\/\n      exists (d : positive),\n        m = (mx * 2^d)%positive /\\ e = ex - (Zpos d)).\n    Proof.\n      intros NB.\n      split.\n      - generalize (normalize_BER_odd m e); intros.\n        rewrite <- NB in H.\n        apply H.\n      - generalize (normalize_BER_eq m e); intros.\n        rewrite <- NB in H.\n        apply H.\n    Qed.\n    \n    Lemma normalize_BER_Req (m : positive) (e : Z) :\n      uncurry R_of_float (normalize_BER_finite m e) =\n      R_of_float m e.\n    Proof.\n      unfold R_of_float, uncurry.\n      break_let.\n      rename p into mx, z into ex, Heqp into H.\n      symmetry in H.\n      apply normalize_BER_spec in H.\n      destruct H as [H0 [H1|H2]].\n      -\n        tuple_inversion.\n        reflexivity.\n      -\n        destruct H2 as [d [H2 H3]].\n        subst.\n        rewrite Pos2Z.inj_mul.\n        rewrite Pos2Z.inj_pow.\n        remember (ex - Z.pos d) as ex'.\n        replace (Z.pos d) with (ex - ex') by lia.\n        apply (Float_prop.F2R_change_exp radix2).\n        lia.\n    Qed.\n\n    Let normalize_roundtrip (m : positive) (e : Z) :=\n      uncurry normalize_IEEE_finite\n              (normalize_BER_finite m e).\n\n    Lemma normalize_roundtrip_eq (m : positive) (e : Z) :\n      uncurry R_of_float (normalize_roundtrip m e) =\n      R_of_float m e.\n    Proof.\n      unfold normalize_roundtrip.\n      rewrite <- normalize_BER_Req.\n      destruct (normalize_BER_finite m e) as (mx,ex) eqn:NB.\n      assert (uncurry normalize_IEEE_finite (mx, ex) = normalize_IEEE_finite mx ex)\n        by (unfold uncurry; reflexivity).\n      rewrite H.\n      rewrite <- normalize_IEEE_eq.\n      auto.\n    Qed.\n\n    Lemma digits2_size (p : positive) :\n      Digits.digits2_pos p = Pos.size p.\n    Proof.\n      induction p; simpl; try rewrite IHp; reflexivity.\n    Qed.\n\n    Lemma normalize_roundtrip_valid (m : positive) (e : Z) :\n      valid_IEEE m e = true ->\n      uncurry valid_IEEE\n              (normalize_roundtrip m e) = true.\n    Proof.\n      (* unfold everything, clean up *)\n      unfold normalize_roundtrip.\n      destruct (normalize_BER_finite m e) as (mx, ex) eqn:NB.\n      destruct (uncurry normalize_IEEE_finite (mx, ex)) as (m', e') eqn:NI.\n      unfold uncurry in *.\n      unfold normalize_IEEE_finite, valid_IEEE, shl_align_fexp, shl_align, \n      bounded, canonical_mantissa, uncurry, FLT.FLT_exp in *.\n      clear r valid_IEEE valid_BER IEEE_float valid_IEEE_sumbool\n            BER_finite_b2 valid_BER_sumbool normalize_roundtrip.\n\n      (* remove bool *)\n      intros H.\n      apply andb_prop in H.\n      destruct H as [H1 H2].\n      debool.\n\n      symmetry in NB. apply normalize_BER_spec in NB.\n      destruct NB as [H3 H4].\n\n      split_andb_goal; debool;\n        rewrite digits2_size, Psize_log_inf, <- Zlog2_log_inf in *.\n      -\n        destruct H4.\n        tuple_inversion.\n        break_match_hyp; try (tuple_inversion; apply H1).\n        + rewrite H1 in Heqz. rewrite Z.sub_diag in Heqz. inversion Heqz.\n        + destruct H as [d [H0 H5]].\n          break_match_hyp.\n          * tuple_inversion; lia.\n          * tuple_inversion.\n            exfalso. (* Heqz vs goal *)\n            unfold Z.max in *.\n            repeat break_match_hyp; simpl; debool; try lia;\n              rewrite Pos2Z.inj_mul, Pos2Z.inj_pow, Z.log2_mul_pow2 in *; lia.\n          *\n            subst.\n            remember (shift_pos p mx) as pm.\n            remember (Z.max (Z.succ (Z.log2 (Z.pos mx)) + ex - prec) (3 - emax - prec)) as pe.\n            inversion NI. clear NI.\n            subst pe pm.\n            apply Pos2Z.inj_iff in H0.\n            rewrite shift_pos_correct in H0.\n            rewrite Pos2Z.inj_mul, Pos2Z.inj_pow, Z.log2_mul_pow2 in *; try lia.\n            rewrite Z.pow_pos_fold in H0.\n            subst.\n            rewrite <- H0. clear m' H0.\n            rewrite Z.mul_comm.\n            rewrite Z.log2_mul_pow2; lia.\n      -\n        destruct H4.\n        + tuple_inversion.\n          break_match_hyp.\n          * tuple_inversion.\n            apply H2.\n          * tuple_inversion.\n            apply H2.\n          * lia.\n        + destruct H as [d [H4 H5]].\n          break_match_hyp.\n          * tuple_inversion.\n            rewrite Pos2Z.inj_mul, Pos2Z.inj_pow, Z.log2_mul_pow2 in *; lia.\n          * tuple_inversion.\n            rewrite Pos2Z.inj_mul, Pos2Z.inj_pow, Z.log2_mul_pow2 in *; lia.\n          *\n            subst.\n            remember (shift_pos p mx) as pm.\n            remember (Z.max (Z.succ (Z.log2 (Z.pos mx)) + ex - prec) (3 - emax - prec)) as pe.\n            inversion NI. clear NI.\n            subst pe pm.\n            apply Pos2Z.inj_iff in H0.\n            rewrite shift_pos_correct in H0.\n            rewrite Pos2Z.inj_mul, Pos2Z.inj_pow, Z.log2_mul_pow2 in *; lia.\n    Qed.\n\n    Theorem arithmetic_roundtrip (m : positive) (e : Z) :\n      valid_IEEE m e = true ->\n      normalize_roundtrip m e = (m, e).\n    Proof.\n      intros H.\n      copy_apply normalize_roundtrip_valid H.\n      unfold normalize_roundtrip, uncurry in *.\n      destruct normalize_BER_finite as (mx,ex) eqn:NB.\n      destruct normalize_IEEE_finite as (m',e') eqn:NI.\n      apply R_of_valid_IEEE_inj.\n      apply H0.\n      apply H.\n      assert (R_of_float m' e' = uncurry R_of_float (normalize_roundtrip m e)) by\n        (unfold uncurry, normalize_roundtrip; rewrite NB, NI; reflexivity).\n      rewrite H1.\n      apply normalize_roundtrip_eq.\n    Qed.\n\n    Ltac inv_make_BER_finite :=\n      match goal with\n      | [ H : make_BER_finite _ _ _ = Some _ |- _ ] =>\n        unfold make_BER_finite in H;\n        destruct normalize_BER_finite;\n        destruct valid_BER_sumbool;\n        inversion H\n    end.\n\n    Ltac bcompare_nrefl :=\n      match goal with\n      | [ H: Bcompare _ _ _ _ = _ |- _] =>\n        assert (H1 := H); rewrite -> Bcompare_swap in H1; rewrite -> H in H1; inversion H1\n      end.\n    \n    Theorem main_roundtrip (scaled : bool) (f : IEEE_float):\n      roundtrip_option\n        IEEE_float BER_float IEEE_float\n        (BER_of_IEEE_exact)\n        IEEE_of_BER_exact\n        (float_eqb_nan_t)\n        f.\n    Proof.\n      intros FPT.\n      unfold bool_het_inverse'; simpl.\n      break_match.\n      - (* forward pass successful *)\n        clear FPT.\n        break_match.\n        + (* backward pass successful *)\n          destruct f; destruct b; simpl in *; repeat try some_inv; try auto.\n          (* structural errors *)\n          * unfold float_eqb_nan_t, Bcompare.\n            repeat break_match; (repeat try some_inv);\n              try compare_nrefl; try reflexivity; try inversion Heqc.\n          * inv_make_BER_finite.\n          * inv_make_BER_finite.\n          * (* arithmetic_roundtrip comes in play *)\n             destruct ((b =? 2) && (f =? 0))%bool; inversion Heqo0; clear H0.\n    \n            (* simplify forward conversions *)\n            unfold make_BER_finite in *.\n            destruct normalize_BER_finite eqn:NB.\n            destruct valid_BER_sumbool; inversion Heqo.\n            clear Heqo; subst.\n    \n            (* simplify backward conversions *)\n            unfold make_IEEE_finite in *.\n            destruct normalize_IEEE_finite eqn:NI.\n            destruct valid_IEEE_sumbool; inversion Heqo0.\n            clear Heqo0; subst.\n    \n            (* apply arithmetic roundtrip *)\n            copy_apply (arithmetic_roundtrip m e) e0.\n            unfold normalize_roundtrip in H.\n            rewrite -> NB in H.\n            simpl in H.\n            rewrite -> NI in H.\n            inversion H; subst.\n            unfold float_eqb_nan_t, Bcompare.\n            repeat break_match; (repeat try some_inv);\n              try compare_nrefl; try reflexivity.\n    \n        + (* backward pass unsuccessful *)\n          destruct f; simpl in Heqo; inversion Heqo; subst; inversion Heqo0.\n          clear H0 H1; exfalso.\n          unfold make_BER_finite in Heqo.\n          destruct normalize_BER_finite eqn:NB, valid_BER_sumbool;\n            inversion Heqo; clear Heqo.\n          subst.\n          unfold BER_finite_b2 in Heqo0.\n          simpl in Heqo0.\n          unfold make_IEEE_finite in Heqo0.\n          destruct normalize_IEEE_finite eqn:NI.\n          destruct valid_IEEE_sumbool; inversion Heqo0; clear Heqo0.\n          copy_apply (arithmetic_roundtrip m e) e0.\n          unfold normalize_roundtrip in H.\n          rewrite -> NB in H.\n          simpl in H.\n          rewrite -> NI in H.\n          inversion H; subst.\n          rewrite e0 in e2; inversion e2.\n      - (* forward pass unsuccessful *)\n        inversion FPT.\n    Qed.\n    \n  End Proof.\n\nEnd Base2.\n", "meta": {"author": "digamma-ai", "repo": "asn1fpcoq", "sha": "05094f3824393aeb74e58e4b84f570529a55799c", "save_path": "github-repos/coq/digamma-ai-asn1fpcoq", "path": "github-repos/coq/digamma-ai-asn1fpcoq/asn1fpcoq-05094f3824393aeb74e58e4b84f570529a55799c/coq/Conversion/IEEE_ASN.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6636810656684045}}
{"text": "(* ******************************************************************************* *)\n(** Unitality laws are inverses\n ********************************************************************************* *)\n\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.PrecategoryBinProduct.\nRequire Import UniMath.Bicategories.Core.Bicat. Import Bicat.Notations.\nRequire Import UniMath.Bicategories.Core.Invertible_2cells.\nRequire Import UniMath.Bicategories.Core.BicategoryLaws.\nRequire Import UniMath.Bicategories.Core.Unitors.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Base.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Map1Cells.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Map2Cells.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Identitor.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Compositor.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.PseudoFunctorBicat.\nRequire Import UniMath.Bicategories.PseudoFunctors.PseudoFunctor.\nImport PseudoFunctor.Notations.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Identity.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Composition.\nRequire Import UniMath.Bicategories.Transformations.PseudoTransformation.\nRequire Import UniMath.Bicategories.Transformations.Examples.Unitality.\nRequire Import UniMath.Bicategories.Modifications.Modification.\n\nLocal Open Scope cat.\n\nSection LeftUnitality.\n  Context {B₁ B₂ : bicat}.\n  Variable (F : psfunctor B₁ B₂).\n\n  Definition lunitor_linvunitor_pstrans_data\n    : invertible_modification_data\n        (comp_pstrans (lunitor_pstrans F) (linvunitor_pstrans F))\n        (id_pstrans _).\n  Proof.\n    intro X.\n    use make_invertible_2cell.\n    - exact (lunitor _).\n    - is_iso.\n  Defined.\n\n  Definition lunitor_linvunitor_pstrans_is_modification\n    : is_modification lunitor_linvunitor_pstrans_data.\n  Proof.\n    intros X Y f ; cbn.\n    rewrite <- lwhisker_vcomp.\n    rewrite !vassocr.\n    rewrite lunitor_lwhisker.\n    rewrite <- rwhisker_vcomp.\n    rewrite !vassocl.\n    etrans.\n    {\n      do 2 apply maponpaths.\n      rewrite !vassocr.\n      rewrite lunitor_triangle.\n      apply maponpaths_2.\n      rewrite !vassocl.\n      rewrite rwhisker_hcomp.\n      rewrite <- triangle_r_inv.\n      rewrite <- lwhisker_hcomp.\n      apply idpath.\n    }\n    rewrite !vassocl.\n    rewrite lwhisker_vcomp.\n    rewrite linvunitor_lunitor, lwhisker_id2, id2_right.\n    rewrite vcomp_lunitor.\n    rewrite runitor_lunitor_identity.\n    apply idpath.\n  Qed.\n\n  Definition lunitor_linvunitor_pstrans\n    : invertible_modification\n        (comp_pstrans (lunitor_pstrans F) (linvunitor_pstrans F))\n        (id_pstrans _).\n  Proof.\n    use make_invertible_modification.\n    - exact lunitor_linvunitor_pstrans_data.\n    - exact lunitor_linvunitor_pstrans_is_modification.\n  Defined.\n\n  Definition linvunitor_lunitor_pstrans_data\n    : invertible_modification_data\n        (comp_pstrans (linvunitor_pstrans F) (lunitor_pstrans F))\n        (id_pstrans _).\n  Proof.\n    intro X.\n    use make_invertible_2cell.\n    - exact (lunitor _).\n    - is_iso.\n  Defined.\n\n  Definition linvunitor_lunitor_pstrans_is_modification\n    : is_modification linvunitor_lunitor_pstrans_data.\n  Proof.\n    intros X Y f ; cbn.\n    rewrite <- lwhisker_vcomp.\n    rewrite !vassocr.\n    rewrite lunitor_lwhisker.\n    rewrite <- rwhisker_vcomp.\n    rewrite !vassocl.\n    etrans.\n    {\n      do 2 apply maponpaths.\n      rewrite !vassocr.\n      rewrite lunitor_triangle.\n      apply maponpaths_2.\n      rewrite !vassocl.\n      rewrite rwhisker_hcomp.\n      rewrite <- triangle_r_inv.\n      rewrite <- lwhisker_hcomp.\n      apply idpath.\n    }\n    rewrite !vassocl.\n    rewrite lwhisker_vcomp.\n    rewrite linvunitor_lunitor, lwhisker_id2, id2_right.\n    rewrite vcomp_lunitor.\n    rewrite runitor_lunitor_identity.\n    apply idpath.\n  Qed.\n\n  Definition linvunitor_lunitor_pstrans\n    : invertible_modification\n        (comp_pstrans (linvunitor_pstrans F) (lunitor_pstrans F))\n        (id_pstrans _).\n  Proof.\n    use make_invertible_modification.\n    - exact linvunitor_lunitor_pstrans_data.\n    - exact linvunitor_lunitor_pstrans_is_modification.\n  Defined.\nEnd LeftUnitality.\n\nSection RightUnitality.\n  Context {B₁ B₂ : bicat}.\n  Variable (F : psfunctor B₁ B₂).\n\n  Definition runitor_rinvunitor_pstrans_data\n    : invertible_modification_data\n        (comp_pstrans (runitor_pstrans F) (rinvunitor_pstrans F))\n        (id_pstrans _).\n  Proof.\n    intro X.\n    use make_invertible_2cell.\n    - exact (lunitor _).\n    - is_iso.\n  Defined.\n\n  Definition runitor_rinvunitor_pstrans_is_modification\n    : is_modification runitor_rinvunitor_pstrans_data.\n  Proof.\n    intros X Y f ; cbn.\n    rewrite <- lwhisker_vcomp.\n    rewrite !vassocr.\n    rewrite lunitor_lwhisker.\n    rewrite <- rwhisker_vcomp.\n    rewrite !vassocl.\n    etrans.\n    {\n      do 2 apply maponpaths.\n      rewrite !vassocr.\n      rewrite lunitor_triangle.\n      apply maponpaths_2.\n      rewrite !vassocl.\n      rewrite rwhisker_hcomp.\n      rewrite <- triangle_r_inv.\n      rewrite <- lwhisker_hcomp.\n      apply idpath.\n    }\n    rewrite !vassocl.\n    rewrite lwhisker_vcomp.\n    rewrite linvunitor_lunitor, lwhisker_id2, id2_right.\n    rewrite vcomp_lunitor.\n    rewrite runitor_lunitor_identity.\n    apply idpath.\n  Qed.\n\n  Definition runitor_rinvunitor_pstrans\n    : invertible_modification\n        (comp_pstrans (runitor_pstrans F) (rinvunitor_pstrans F))\n        (id_pstrans _).\n  Proof.\n    use make_invertible_modification.\n    - exact runitor_rinvunitor_pstrans_data.\n    - exact runitor_rinvunitor_pstrans_is_modification.\n  Defined.\n\n  Definition rinvunitor_runitor_pstrans_data\n    : invertible_modification_data\n        (comp_pstrans (rinvunitor_pstrans F) (runitor_pstrans F))\n        (id_pstrans _).\n  Proof.\n    intro X.\n    use make_invertible_2cell.\n    - exact (lunitor _).\n    - is_iso.\n  Defined.\n\n  Definition rinvunitor_runitor_pstrans_is_modification\n    : is_modification rinvunitor_runitor_pstrans_data.\n  Proof.\n    intros X Y f ; cbn.\n    rewrite <- lwhisker_vcomp.\n    rewrite !vassocr.\n    rewrite lunitor_lwhisker.\n    rewrite <- rwhisker_vcomp.\n    rewrite !vassocl.\n    etrans.\n    {\n      do 2 apply maponpaths.\n      rewrite !vassocr.\n      rewrite lunitor_triangle.\n      apply maponpaths_2.\n      rewrite !vassocl.\n      rewrite rwhisker_hcomp.\n      rewrite <- triangle_r_inv.\n      rewrite <- lwhisker_hcomp.\n      apply idpath.\n    }\n    rewrite !vassocl.\n    rewrite lwhisker_vcomp.\n    rewrite linvunitor_lunitor, lwhisker_id2, id2_right.\n    rewrite vcomp_lunitor.\n    rewrite runitor_lunitor_identity.\n    apply idpath.\n  Qed.\n\n  Definition rinvunitor_runitor_pstrans\n    : invertible_modification\n        (comp_pstrans (rinvunitor_pstrans F) (runitor_pstrans F))\n        (id_pstrans _).\n  Proof.\n    use make_invertible_modification.\n    - exact rinvunitor_runitor_pstrans_data.\n    - exact rinvunitor_runitor_pstrans_is_modification.\n  Defined.\nEnd RightUnitality.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/Bicategories/Modifications/Examples/Unitality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6636810656015796}}
{"text": "(***************************************************************************)\n(* Formalization of the Chou, Gao and Zhang's decision procedure.          *)\n(* Julien Narboux (Julien@narboux.fr)                                      *)\n(* LIX/INRIA FUTURS 2004-2006                                              *)\n(* University of Strasbourg 2008                                           *)\n(***************************************************************************)\n\nRequire Export Bool Peano_dec Eqdep_dec.\nRequire Import Setoid.\nRequire Export ZArithRing Field.\n\n(* We define our own field *)\n\nParameter F : Set.\nParameter F0 : F.\nParameter F1 : F.\nParameter Fplus : F -> F -> F.\nParameter Fmult : F -> F -> F.\nParameter Fopp : F -> F.\nParameter Finv : F -> F. \n\nDefinition Feq (x y : F) : bool := false. \n\nDefinition Fminus (r1 r2 : F) : F := Fplus r1 (Fopp r2).\nDefinition Fdiv (r1 r2 : F) : F := Fmult r1 (Finv r2).\n\n(***************)\n(* Notations  *)\n(***************)\n\nDelimit Scope F_scope with F.\nInfix \"+\" := Fplus : F_scope.\nInfix \"-\" := Fminus : F_scope.\nInfix \"*\" := Fmult : F_scope.\nInfix \"/\" := Fdiv : F_scope.\nNotation \"- x\" := (Fopp x) : F_scope.\n\nNotation \"0\" := F0 : F_scope.\nNotation \"1\" := F1 : F_scope.\nNotation \"2\" := (1 + 1)%F : F_scope. \n\nNotation \"/ x\" := (Finv x) : F_scope.\n\n(*Distfix 30 \"/ _\" Finv : F_scope V8only.*)\n(* Notation \"x <> y\" := ~(eqT F x y) (at level 5) : F_scope. *)\n\nOpen Scope F_scope.\n\n(***********)\n(* Axioms *)\n(***********)\n\n(*********************************************************)\n(*      Addition                                                          *)\n(*********************************************************)\n\nAxiom Fplus_sym : forall r1 r2 : F, r1 + r2 = r2 + r1.\nHint Resolve Fplus_sym: field_hints.\n\nAxiom Fplus_assoc : forall r1 r2 r3 : F, r1 + r2 + r3 = r1 + (r2 + r3).\nHint Resolve Fplus_assoc: field_hints.\n\nAxiom Fplus_Fopp_r : forall r : F, r + - r = 0.\nHint Resolve Fplus_Fopp_r: field_hints.\n\nAxiom Fplus_Ol : forall r : F, 0 + r = r.\nHint Resolve Fplus_Ol: field_hints.\n\n(***********************************************************)       \n(*       Multiplication                                    *)\n(***********************************************************)\n\nAxiom Fmult_sym : forall r1 r2 : F, r1 * r2 = r2 * r1.\nHint Resolve Fmult_sym: field_hints. \n\nAxiom Fmult_assoc : forall r1 r2 r3 : F, r1 * r2 * r3 = r1 * (r2 * r3).\nHint Resolve Fmult_assoc: field_hints.\n\nAxiom Finv_l : forall r : F, r <> 0 -> / r * r = 1.\nHint Resolve Finv_l: field_hints.\n\nAxiom Fmult_1l : forall r : F, 1 * r = r.\nHint Resolve Fmult_1l: field_hints.\n\nAxiom F1_neq_F0 : 1 <> 0.\nHint Resolve F1_neq_F0: field_hints.\n\n(*********************************************************)\n(*      Distributivity                                   *)\n(*********************************************************)\n\nAxiom\n  Fmult_Fplus_distr : forall r1 r2 r3 : F, r1 * (r2 + r3) = r1 * r2 + r1 * r3.\nHint Resolve Fmult_Fplus_distr: field_hints.\n\nLemma Fmult_Fplus_distr_r : forall r2 r3 r1 : F, (r2 + r3) * r1 = r2 * r1 + r3 * r1.\nProof.\nintros.\nrewrite Fmult_sym.\nrewrite (Fmult_sym r2 r1).\nrewrite (Fmult_sym r3 r1).\napply Fmult_Fplus_distr.\nQed.\n\n(*********************************************************)\n(*      Instanciation of the new ring tactic             *)\n(*********************************************************)\n\n\n Lemma FRth : ring_theory 0 1 Fplus Fmult Fminus Fopp (@eq F).\n Proof.\n  constructor. exact Fplus_Ol. exact Fplus_sym.\n  intros;symmetry;apply Fplus_assoc.\n  exact Fmult_1l. exact Fmult_sym.\n  intros;symmetry;apply Fmult_assoc.\n  exact Fmult_Fplus_distr_r. trivial. exact Fplus_Fopp_r.\n Qed.\n\n Lemma Fth : field_theory 0 1 Fplus Fmult Fminus Fopp Fdiv Finv (@eq F).\nProof.\nconstructor.\n exact FRth.\n exact F1_neq_F0.\n reflexivity.\n exact Finv_l.\nQed.\n\nAdd Field Ff : Fth.\n\nLtac Fring := ring || ring_simplify.\n\n(** The new ring tactic is efficient, here is an example \nwhich is very slow with the legacy ring tactic *)\n\nGoal forall a b:F, 2*2*2*2*2*2*a*b=2*2*2*2*2*2*a*b.\nintros.\nFring.\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/area-method/field.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6636810655347543}}
{"text": "Require Import Coq.ZArith.ZArith Coq.micromega.Lia.\nRequire Import Coq.ZArith.Znumtheory.\nRequire Import Crypto.Util.ZUtil.Tactics.CompareToSgn.\nRequire Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.ZUtil.Le.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Hints.ZArith.\nRequire Import Crypto.Util.ZUtil.Hints.PullPush.\nRequire Import Crypto.Util.ZUtil.Hints.\nRequire Import Crypto.Util.ZUtil.ZSimplify.Core.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.ZUtil.Pow.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma div_mul' : forall a b : Z, b <> 0 -> (b * a) / b = a.\n  Proof. intros. rewrite Z.mul_comm. apply Z.div_mul; auto. Qed.\n  Hint Rewrite div_mul' using zutil_arith : zsimplify.\n\n  Local Ltac replace_to_const c :=\n    repeat match goal with\n           | [ H : ?x = ?x |- _ ] => clear H\n           | [ H : ?x = c, H' : context[?x] |- _ ] => rewrite H in H'\n           | [ H : c = ?x, H' : context[?x] |- _ ] => rewrite <- H in H'\n           | [ H : ?x = c |- context[?x] ] => rewrite H\n           | [ H : c = ?x |- context[?x] ] => rewrite <- H\n           end.\n\n  Lemma lt_div_0 n m : n / m < 0 <-> ((n < 0 < m \\/ m < 0 < n) /\\ 0 < -(n / m)).\n  Proof.\n    Z.compare_to_sgn; rewrite Z.sgn_opp; simpl.\n    pose proof (Zdiv_sgn n m) as H.\n    pose proof (Z.sgn_spec (n / m)) as H'.\n    repeat first [ progress intuition auto\n                 | progress simpl in *\n                 | congruence\n                 | lia\n                 | progress replace_to_const (-1)\n                 | progress replace_to_const 0\n                 | progress replace_to_const 1\n                 | match goal with\n                   | [ x : Z |- _ ] => destruct x\n                   end ].\n  Qed.\n\n  Lemma div_add' a b c : c <> 0 -> (a + c * b) / c = a / c + b.\n  Proof. intro; rewrite <- Z.div_add, (Z.mul_comm c); try lia. Qed.\n  Lemma div_add_l' a b c : b <> 0 -> (b * a + c) / b = a + c / b.\n  Proof. intro; rewrite <- Z.div_add_l, (Z.mul_comm b); lia. Qed.\n  Hint Rewrite Z.div_add' Z.div_add_l' using zutil_arith : push_Zdiv.\n  Hint Rewrite <- Z.div_add' Z.div_add_l' using zutil_arith : pull_Zdiv.\n  Hint Rewrite div_add_l' div_add' using zutil_arith : zsimplify.\n\n  Lemma div_sub a b c : c <> 0 -> (a - b * c) / c = a / c - b.\n  Proof. intros; rewrite <- !Z.add_opp_r, <- Z.div_add by lia; apply f_equal2; lia. Qed.\n\n  Lemma div_sub' a b c : c <> 0 -> (a - c * b) / c = a / c - b.\n  Proof. intro; rewrite <- div_sub, (Z.mul_comm c); try lia. Qed.\n\n  Hint Rewrite div_sub div_sub' using zutil_arith : zsimplify.\n\n  Lemma div_add_sub_l a b c d : b <> 0 -> (a * b + c - d) / b = a + (c - d) / b.\n  Proof. rewrite <- Z.add_sub_assoc; apply Z.div_add_l. Qed.\n\n  Lemma div_add_sub_l' a b c d : b <> 0 -> (b * a + c - d) / b = a + (c - d) / b.\n  Proof. rewrite <- Z.add_sub_assoc; apply Z.div_add_l'. Qed.\n\n  Lemma div_add_sub a b c d : c <> 0 -> (a + b * c - d) / c = (a - d) / c + b.\n  Proof. rewrite (Z.add_comm _ (_ * _)), (Z.add_comm (_ / _)); apply Z.div_add_sub_l. Qed.\n\n  Lemma div_add_sub' a b c d : c <> 0 -> (a + c * b - d) / c = (a - d) / c + b.\n  Proof. rewrite (Z.add_comm _ (_ * _)), (Z.add_comm (_ / _)); apply Z.div_add_sub_l'. Qed.\n\n  Hint Rewrite Z.div_add_sub Z.div_add_sub' Z.div_add_sub_l Z.div_add_sub_l' using zutil_arith : zsimplify.\n\n  Lemma div_mul_skip a b k : 0 < b -> 0 < k -> a * b / k / b = a / k.\n  Proof.\n    intros; rewrite Z.div_div, (Z.mul_comm k), <- Z.div_div by lia.\n    autorewrite with zsimplify. reflexivity.\n  Qed.\n\n  Lemma div_mul_skip' a b k : 0 < b -> 0 < k -> b * a / k / b = a / k.\n  Proof.\n    intros; rewrite Z.div_div, (Z.mul_comm k), <- Z.div_div by lia.\n    autorewrite with zsimplify; reflexivity.\n  Qed.\n\n  Hint Rewrite Z.div_mul_skip Z.div_mul_skip' using zutil_arith : zsimplify.\n\n  Lemma div_mul_skip_pow base e0 e1 x y : 0 < y -> 0 < base -> 0 <= e1 <= e0 -> x * base^e0 / y / base^e1 = x * base^(e0 - e1) / y.\n  Proof.\n    intros.\n    assert (0 < base^e1) by auto with zarith.\n    replace (base^e0) with (base^(e0 - e1) * base^e1) by (autorewrite with pull_Zpow zsimplify; reflexivity).\n    rewrite !Z.mul_assoc.\n    autorewrite with zsimplify; lia.\n  Qed.\n  Hint Rewrite div_mul_skip_pow using zutil_arith : zsimplify.\n\n  Lemma div_mul_skip_pow' base e0 e1 x y : 0 < y -> 0 < base -> 0 <= e1 <= e0 -> base^e0 * x / y / base^e1 = base^(e0 - e1) * x / y.\n  Proof.\n    intros.\n    rewrite (Z.mul_comm (base^e0) x), div_mul_skip_pow by lia.\n    auto using f_equal2 with lia.\n  Qed.\n  Hint Rewrite div_mul_skip_pow' using zutil_arith : zsimplify.\n\n  Lemma div_le_mono_nonneg a b c : 0 <= c -> a <= b -> a / c <= b / c.\n  Proof.\n    destruct (Z_zerop c).\n    { subst; simpl; autorewrite with zsimplify; reflexivity. }\n    { intros; apply Z.div_le_mono; lia. }\n  Qed.\n  Hint Resolve div_le_mono_nonneg : zarith.\n\n  Lemma div_le_mono_pow_pos a b c e : a <= b -> a / Z.pos c ^ e <= b / Z.pos c ^ e.\n  Proof. auto with zarith. Qed.\n\n  Lemma div_nonneg a b : 0 <= a -> 0 <= b -> 0 <= a / b.\n  Proof.\n    destruct (Z_zerop b); subst; rewrite ?Zdiv_0_r; [ reflexivity | ].\n    intros; apply Z.div_pos; lia.\n  Qed.\n  Hint Resolve div_nonneg : zarith.\n\n  Lemma div_add_exact x y d : d <> 0 -> x mod d = 0 -> (x + y) / d = x / d + y / d.\n  Proof.\n    intros; rewrite (Z_div_exact_full_2 x d) at 1 by assumption.\n    rewrite Z.div_add_l' by assumption; lia.\n  Qed.\n  Hint Rewrite div_add_exact using zutil_arith : zsimplify.\n\n  Lemma Z_divide_div_mul_exact' a b c : b <> 0 -> (b | a) -> a * c / b = c * (a / b).\n  Proof. intros. rewrite Z.mul_comm. auto using Z.divide_div_mul_exact. Qed.\n\n  Lemma div_sub_mod_exact a b : b <> 0 -> a / b = (a - a mod b) / b.\n  Proof.\n    intro.\n    rewrite (Z.div_mod a b) at 2 by lia.\n    autorewrite with zsimplify.\n    reflexivity.\n  Qed.\n\n  Lemma div_sub_mod_cond x y d\n    : d <> 0\n      -> (x - y) / d\n         = x / d + ((x mod d - y) / d).\n  Proof. clear.\n         intro.\n         replace (x - y) with ((x - x mod d) + (x mod d - y)) by lia.\n         rewrite Z.div_add_exact by (autorewrite with pull_Zmod zsimplify; auto).\n         rewrite <- Z.div_sub_mod_exact by lia; lia.\n  Qed.\n  Hint Resolve div_sub_mod_cond : zarith.\n\n  Lemma div_add_mod_cond_l : forall x y d, d <> 0 -> (x + y) / d = (x mod d + y) / d + x / d.\n  Proof.\n    intros. replace (x + y) with ((x - x mod d) + (x mod d + y)) by lia.\n    rewrite Z.div_add_exact by (autorewrite with pull_Zmod zsimplify; auto).\n    rewrite <- Z.div_sub_mod_exact by lia; lia.\n  Qed.\n\n  Lemma div_add_mod_cond_r : forall x y d, d <> 0 -> (x + y) / d = (x + y mod d) / d + y / d.\n  Proof.\n    intros. rewrite Z.add_comm, div_add_mod_cond_l by auto. repeat (f_equal; try ring).\n  Qed.\n\n  Lemma div_le_zero x y : 0 < y -> x / y <= 0 -> x < y.\n  Proof.\n    clear. intros.\n    apply Z.nle_gt; intro.\n    pose proof (Z.div_str_pos x y ltac:(lia)). lia.\n  Qed.\n\n  Lemma div_between_full n a b :\n    0 < b -> n * b <= a < (1 + n) * b ->\n    a / b = n.\n  Proof.\n    intros.\n    pose proof (Z.div_le_lower_bound a b n ltac:(lia) ltac:(lia)).\n    pose proof (Z.div_lt_upper_bound a b (n+1) ltac:(lia) ltac:(lia)).\n    lia.\n  Qed.\n\n  Lemma mod_small_n_neg n a b : n < 0 -> 0 < b -> n * b <= a < (1 + n) * b ->\n                                a mod b = a - n * b.\n  Proof.\n    intros. rewrite Z.mod_eq, div_between_full with (n:=n) by lia. ring.\n  Qed.\n\n  Lemma div_div_comm : forall x y z,  0 < y -> 0 < z -> x / y / z = x / z / y.\n  Proof.\n    intros; rewrite !Z.div_div by lia.\n    f_equal; ring.\n  Qed.\n\n  Lemma div_lt_upper_bound' a b q : 0 < b -> a < q * b -> a / b < q.\n  Proof. intros; apply Z.div_lt_upper_bound; nia. Qed.\n  Hint Resolve div_lt_upper_bound' : zarith.\n\n  Lemma div_cross_le_abs a b c' d : c' <> 0 -> d <> 0 -> a * Z.sgn c' * Z.abs d <= b * Z.sgn d * Z.abs c' -> a / c' <= b / d.\n  Proof.\n    clear.\n    destruct c', d; cbn [Z.abs Z.sgn];\n      rewrite ?Zdiv_0_r, ?Z.mul_0_r, ?Z.mul_0_l, ?Z.mul_1_l, ?Z.mul_1_r;\n      try lia; intros ?? H;\n        Z.div_mod_to_quot_rem_in_goal;\n        subst.\n    all: repeat match goal with\n                | [ H : context[_ * -1] |- _ ] => rewrite (Z.mul_add_distr_r _ _ (-1)), <- ?(Z.mul_comm (-1)), ?Z.mul_assoc in H\n                | [ H : context[-1 * _] |- _ ] => rewrite (Z.mul_add_distr_l (-1)), <- ?(Z.mul_comm (-1)), ?Z.mul_assoc in H\n                | [ H : context[-1 * Z.neg ?x] |- _ ] => rewrite (Z.mul_comm (-1) (Z.neg x)), <- Z.opp_eq_mul_m1 in H\n                | [ H : context[-1 * ?x] |- _ ] => rewrite (Z.mul_comm (-1) x), <- Z.opp_eq_mul_m1 in H\n                | [ H : context[-Z.neg _] |- _ ] => cbn [Z.opp] in H\n                end.\n    all:lazymatch goal with\n        | [ H : (Z.pos ?p * ?q + ?r) * Z.pos ?p' <= (Z.pos ?p' * ?q' + ?r') * Z.pos ?p |- _ ]\n          => let H' := fresh in\n             assert (H' : q <= q' + (r' * Z.pos p - r * Z.pos p') / (Z.pos p * Z.pos p')) by (Z.div_mod_to_quot_rem_in_goal; nia);\n               revert H'\n        end.\n    all:Z.div_mod_to_quot_rem_in_goal; nia.\n  Qed.\n\n  Lemma div_positive_gt_0 : forall a b, a > 0 -> b > 0 -> a mod b = 0 ->\n    a / b > 0.\n  Proof.\n    intros; rewrite Z.gt_lt_iff.\n    apply Z.div_str_pos.\n    split; intuition auto with lia.\n    apply Z.divide_pos_le; try (apply Zmod_divide); lia.\n  Qed.\n\n  Lemma div_opp_l_complete a b (Hb : b <> 0) : -a/b = -(a/b) - (if Z_zerop (a mod b) then 0 else 1).\n  Proof.\n    destruct (Z_zerop (a mod b)); autorewrite with zsimplify push_Zopp; reflexivity.\n  Qed.\n\n  Lemma div_opp_l_complete' a b (Hb : b <> 0) : -(a/b) = -a/b + (if Z_zerop (a mod b) then 0 else 1).\n  Proof.\n    destruct (Z_zerop (a mod b)); autorewrite with zsimplify pull_Zopp; lia.\n  Qed.\n\n  Hint Rewrite Z.div_opp_l_complete using zutil_arith : pull_Zopp.\n  Hint Rewrite Z.div_opp_l_complete' using zutil_arith : push_Zopp.\n\n  Lemma div_opp a : a <> 0 -> -a / a = -1.\n  Proof.\n    intros; autorewrite with pull_Zopp zsimplify; lia.\n  Qed.\n\n  Hint Rewrite Z.div_opp using zutil_arith : zsimplify.\n\n  Lemma div_sub_1_0 x : x > 0 -> (x - 1) / x = 0.\n  Proof. auto with zarith lia. Qed.\n\n  Hint Rewrite div_sub_1_0 using zutil_arith : zsimplify.\n\n  Lemma div_same' a b : b <> 0 -> a = b -> a / b = 1.\n  Proof.\n    intros; subst; auto with zarith.\n  Qed.\n  Hint Resolve div_same' : zarith.\n\n  Lemma div_opp_r a b : a / (-b) = ((-a) / b).\n  Proof. Z.div_mod_to_quot_rem; nia. Qed.\n  Hint Resolve div_opp_r : zarith.\n\n  Lemma div_floor : forall a b c, 0 < b -> a < b * (Z.succ c) -> a / b <= c.\n  Proof.\n    intros.\n    apply Z.lt_succ_r.\n    apply Z.div_lt_upper_bound; try lia.\n  Qed.\n\n  Lemma mul_div_le x y z\n        (Hx : 0 <= x) (Hy : 0 <= y) (Hz : 0 < z)\n        (Hyz : y <= z)\n    : x * y / z <= x.\n  Proof.\n    transitivity (x * z / z); [ | rewrite Z.div_mul by lia; lia ].\n    apply Z_div_le; nia.\n  Qed.\n  Hint Resolve mul_div_le : zarith.\n\n  Lemma div_mul_diff_exact a b c\n        (Ha : 0 <= a) (Hb : 0 < b) (Hc : 0 <= c)\n    : c * a / b = c * (a / b) + (c * (a mod b)) / b.\n  Proof.\n    rewrite (Z_div_mod_eq a b) at 1 by lia.\n    rewrite Z.mul_add_distr_l.\n    replace (c * (b * (a / b))) with ((c * (a / b)) * b) by lia.\n    rewrite Z.div_add_l by lia.\n    lia.\n  Qed.\n\n  Lemma div_mul_diff_exact' a b c\n        (Ha : 0 <= a) (Hb : 0 < b) (Hc : 0 <= c)\n    : c * (a / b) = c * a / b - (c * (a mod b)) / b.\n  Proof.\n    rewrite div_mul_diff_exact by assumption; lia.\n  Qed.\n\n  Lemma div_mul_diff_exact'' a b c\n        (Ha : 0 <= a) (Hb : 0 < b) (Hc : 0 <= c)\n    : a * c / b = (a / b) * c + (c * (a mod b)) / b.\n  Proof.\n    rewrite (Z.mul_comm a c), div_mul_diff_exact by lia; lia.\n  Qed.\n\n  Lemma div_mul_diff_exact''' a b c\n        (Ha : 0 <= a) (Hb : 0 < b) (Hc : 0 <= c)\n    : (a / b) * c = a * c / b - (c * (a mod b)) / b.\n  Proof.\n    rewrite (Z.mul_comm a c), div_mul_diff_exact by lia; lia.\n  Qed.\n\n  Lemma div_mul_diff a b c\n        (Ha : 0 <= a) (Hb : 0 < b) (Hc : 0 <= c)\n    : c * a / b - c * (a / b) <= c.\n  Proof.\n    rewrite div_mul_diff_exact by assumption.\n    ring_simplify; auto with zarith.\n  Qed.\n\n  Lemma div_mul_le_le a b c\n    :  0 <= a -> 0 < b -> 0 <= c -> c * (a / b) <= c * a / b <= c * (a / b) + c.\n  Proof.\n    pose proof (Z.div_mul_diff a b c); split; try apply Z.div_mul_le; lia.\n  Qed.\n\n  Lemma div_mul_le_le_offset a b c\n    : 0 <= a -> 0 < b -> 0 <= c -> c * a / b - c <= c * (a / b).\n  Proof.\n    pose proof (Z.div_mul_le_le a b c); lia.\n  Qed.\n  Hint Resolve div_mul_le_le_offset : zarith.\n\n  Lemma div_x_y_x x y : 0 < x -> 0 < y -> x / y / x = 1 / y.\n  Proof.\n    intros; rewrite Z.div_div, (Z.mul_comm y x), <- Z.div_div, Z.div_same by lia.\n    reflexivity.\n  Qed.\n  Hint Rewrite div_x_y_x using zutil_arith : zsimplify.\n\n  Lemma sub_pos_bound_div a b X : 0 <= a < X -> 0 <= b < X -> -1 <= (a - b) / X <= 0.\n  Proof.\n    intros H0 H1; pose proof (Z.sub_pos_bound a b X H0 H1).\n    assert (Hn : -X <= a - b) by lia.\n    assert (Hp : a - b <= X - 1) by lia.\n    split; etransitivity; [ | apply Z_div_le, Hn; lia | apply Z_div_le, Hp; lia | ];\n      instantiate; autorewrite with zsimplify; try reflexivity.\n  Qed.\n\n  Hint Resolve (fun a b X H0 H1 => proj1 (Z.sub_pos_bound_div a b X H0 H1))\n       (fun a b X H0 H1 => proj1 (Z.sub_pos_bound_div a b X H0 H1)) : zarith.\n\n  Lemma sub_pos_bound_div_eq a b X : 0 <= a < X -> 0 <= b < X -> (a - b) / X = if a <? b then -1 else 0.\n  Proof.\n    intros H0 H1; pose proof (Z.sub_pos_bound_div a b X H0 H1).\n    destruct (a <? b) eqn:?; Z.ltb_to_lt.\n    { cut ((a - b) / X <> 0); [ lia | ].\n      autorewrite with zstrip_div; auto with zarith lia. }\n    { autorewrite with zstrip_div; auto with zarith lia. }\n  Qed.\n\n  Lemma add_opp_pos_bound_div_eq a b X : 0 <= a < X -> 0 <= b < X -> (-b + a) / X = if a <? b then -1 else 0.\n  Proof.\n    rewrite !(Z.add_comm (-_)), !Z.add_opp_r.\n    apply Z.sub_pos_bound_div_eq.\n  Qed.\n\n  Hint Rewrite Z.sub_pos_bound_div_eq Z.add_opp_pos_bound_div_eq using zutil_arith : zstrip_div.\n\n  Lemma div_small_sym a b : 0 <= a < b -> 0 = a / b.\n  Proof. intros; symmetry; apply Z.div_small; assumption. Qed.\n  Hint Resolve div_small_sym : zarith.\n\n  Lemma mod_eq_le_div_1 a b : 0 < a <= b -> a mod b = 0 -> a / b = 1.\n  Proof. intros; Z.div_mod_to_quot_rem; nia. Qed.\n  Hint Resolve mod_eq_le_div_1 : zarith.\n  Hint Rewrite mod_eq_le_div_1 using zutil_arith : zsimplify.\n\n  Lemma div_small_neg x y : 0 < -x <= y -> x / y = -1.\n  Proof. intros; Z.div_mod_to_quot_rem; nia. Qed.\n  Hint Rewrite div_small_neg using zutil_arith : zsimplify.\n\n  Lemma div_sub_small x y z : 0 <= x < z -> 0 <= y <= z -> (x - y) / z = if x <? y then -1 else 0.\n  Proof.\n    pose proof (Zlt_cases x y).\n    (destruct (x <? y) eqn:?);\n      intros; autorewrite with zsimplify; try lia.\n  Qed.\n  Hint Rewrite div_sub_small using zutil_arith : zsimplify.\n\n  Lemma mul_div_lt_by_le x y z b : 0 <= y < z -> 0 <= x < b -> x * y / z < b.\n  Proof.\n    intros [? ?] [? ?]; eapply Z.le_lt_trans; [ | eassumption ].\n    auto with zarith.\n  Qed.\n  Hint Resolve mul_div_lt_by_le : zarith.\n\n  Definition mul_div_le'\n    := fun x y z w p H0 H1 H2 H3 => @Z.le_trans _ _ w (@Z.mul_div_le x y z H0 H1 H2 H3) p.\n  Hint Resolve mul_div_le' : zarith.\n  Lemma mul_div_le'' x y z w : y <= w -> 0 <= x -> 0 <= y -> 0 < z -> x <= z -> x * y / z <= w.\n  Proof.\n    rewrite (Z.mul_comm x y); intros; apply mul_div_le'; assumption.\n  Qed.\n  Hint Resolve mul_div_le'' : zarith.\n\n  Lemma div_between n a b : 0 <= n -> b <> 0 -> n * b <= a < (1 + n) * b -> a / b = n.\n  Proof. intros; Z.div_mod_to_quot_rem_in_goal; nia. Qed.\n  Hint Rewrite div_between using zutil_arith : zsimplify.\n\n  Lemma div_between_1 a b : b <> 0 -> b <= a < 2 * b -> a / b = 1.\n  Proof. intros; rewrite (div_between 1) by lia; reflexivity. Qed.\n  Hint Rewrite div_between_1 using zutil_arith : zsimplify.\n\n  Lemma div_between_if n a b : 0 <= n -> b <> 0 -> n * b <= a < (2 + n) * b -> (a / b = if (1 + n) * b <=? a then 1 + n else n)%Z.\n  Proof.\n    intros.\n    break_match; Z.ltb_to_lt;\n      apply div_between; lia.\n  Qed.\n\n  Lemma div_between_0_if a b : b <> 0 -> 0 <= a < 2 * b -> a / b = if b <=? a then 1 else 0.\n  Proof. intros; rewrite (div_between_if 0) by lia; autorewrite with zsimplify_const; reflexivity. Qed.\n\n  Lemma div2_split a b c (Hc : 0 < c) :\n  (a + 2 ^ c * b) / 2 = a / 2 + 2 ^ (c - 1) * (b mod 2) + 2 ^ c * (b / 2).\n  Proof.\n    replace (2^c * b) with (2 * (2^(c - 1) * b)).\n    rewrite Div.Z.div_add',  <- (Z.div2_div b) by lia.\n    destruct (Z.odd b) eqn:E; rewrite Zmod_odd, E;\n      rewrite (Zdiv2_odd_eqn b) at 1; rewrite E; ring_simplify;\n        rewrite Pow.Z.pow_mul_base, Z.sub_simpl_r; lia.\n    rewrite Z.mul_assoc, Pow.Z.pow_mul_base, Z.sub_simpl_r; lia. 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/Div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6636725538582408}}
{"text": "(* infotheo (c) AIST. R. Affeldt, M. Hagiwara, J. Senizergues. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice fintype.\nFrom mathcomp Require Import div finfun bigop prime binomial ssralg finset fingroup finalg.\nFrom mathcomp Require Import perm zmodp matrix.\nRequire Import Reals Fourier.\nRequire Import Reals_ext ssr_ext ssralg_ext Rssr log2 Rbigop proba entropy.\nRequire Import binary_entropy_function channel hamming channel_code.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(** * Definition of erasure channel *)\n\nLocal Open Scope channel_scope.\n\nModule EC.\n\nSection EC_sect.\n\nVariable A : finType.\nVariable p : R.\nHypothesis p_01 : 0 <= p <= 1.\n\n(** Definition of n-ary Erasure Channel (EC) *)\n\nDefinition f (a : A) := fun b =>\n  if b is Some a' then\n    if a == a' then 1 - p else 0\n  else p.\n\nLemma f0 a b : 0 <= f a b.\nProof. rewrite /f.\n  case: b => [a'|]; last by case: p_01.\n  case: ifP => _. case: p_01 => ? ?; fourier.\n  fourier.\nQed.\n\nLemma f1 (a : A) : \\rsum_(a' : {:option A}) f a a' = 1.\nProof.\nrewrite (bigD1 None) //=.\nrewrite (bigD1 (Some a)) //=.\nrewrite eqxx /=.\nrewrite -Req_0_rmul. field.\nrewrite /f; case=> [a'| //].\nby case: ifP => /= [/eqP -> | //]; rewrite eqxx.\nQed.\n\nDefinition c : `Ch_1(A, [finType of option A]) :=\n  fun a => makeDist (f0 a) (f1 a).\n\nEnd EC_sect.\n\nSection EC_prob.\n\nVariable X : finType.\nHypothesis card_X : #|X| = 2%nat.\nVariable P : dist X.\nVariable erp : R.\nHypothesis erp_01 : 0 <= erp <= 1.\n\nLet BEC := @EC.c X erp erp_01.\nLocal Notation X0 := (Two_set.val0 card_X).\nLocal Notation X1 := (Two_set.val1 card_X).\nLet q := P(X0).\nLocal Notation W := (EC.f erp).\nLocal Notation P'W := (JointDist.f P BEC).\nLocal Notation PW := (OutDist.f P BEC).\n\nLemma EC_non_flip (a : X)(i : option_finType X):\n(i != None) && (i != Some a) -> 0 = EC.f erp a i.\nProof.\ncase i => a' //=.\ncase: ifP => /eqP; last by [].\nmove=> ->.\nby rewrite eqxx.\nQed.\n\nEnd EC_prob.\n\nEnd EC.\n", "meta": {"author": "johnbender", "repo": "shannon", "sha": "552c66f7c76ad687430f4fb8122a2a2b94b741ee", "save_path": "github-repos/coq/johnbender-shannon", "path": "github-repos/coq/johnbender-shannon/shannon-552c66f7c76ad687430f4fb8122a2a2b94b741ee/erasure_channel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.847967769904032, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6636725482678532}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** * Basic facts about Prop as a type *)\n\n(** An intuitionistic theorem from topos theory [[LambekScott]]\n\nReferences:\n\n[[LambekScott]] Jim Lambek, Phil J. Scott, Introduction to higher\norder categorical logic, Cambridge Studies in Advanced Mathematics\n(Book 7), 1988.\n\n*)\n\nTheorem injection_is_involution_in_Prop\n  (f : Prop -> Prop)\n  (inj : forall A B, (f A <-> f B) -> (A <-> B))\n  (ext : forall A B, A <-> B -> f A <-> f B)\n  : forall A, f (f A) <-> A.\nProof.\nintros.\nenough (f (f (f A)) <-> f A) by (apply inj; assumption).\nsplit; intro H.\n- now_show (f A).\n  enough (f A <-> True) by firstorder.\n  enough (f (f A) <-> f True) by (apply inj; assumption).\n  split; intro H'.\n  + now_show (f True).\n    enough (f (f (f A)) <-> f True) by firstorder.\n    apply ext; firstorder.\n  + now_show (f (f A)).\n    enough (f (f A) <-> True) by firstorder.\n    apply inj; firstorder.\n- now_show (f (f (f A))).\n  enough (f A <-> f (f (f A))) by firstorder.\n  apply ext.\n  split; intro H'.\n  + now_show (f (f A)).\n    enough (f A <-> f (f A)) by firstorder.\n    apply ext; firstorder.\n  + now_show A.\n    enough (f A <-> A) by firstorder.\n    apply inj; firstorder.\nDefined.\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/Logic/PropFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6636664525833326}}
{"text": "\nRequire Export Str.\n\n\n\nSection NFA.\n\n\nRecord sym : Type := mkSym {\n    symb :> finStr;\n    _ : symb ∈ ([set [::x]| x in [set : symbol]] ∪ [set ϵ]);\n}.\n\n\n\nDefinition ϵ_ : sym.\n    apply (mkSym nil).\n    rewrite inE; apply /orP; right.\n    rewrite inE => //.\nQed.\n\nDefinition toSym (a : symbol) : sym.\nProof.\n    apply (mkSym [:: a]).\n    rewrite inE; apply /orP; left.\n    apply /imsetP; exists a => //.\nQed.\n\n\nVariable state : finType.\nVariables Q F : {set state}.\nHypotheses FQ : F ⊂ Q.\nVariable p0 : state.\nHypotheses pQ : p0 ∈ Q.\nVariable δ : state -> sym ->  {set state}.\n\n\n\n\n\n\nReserved Notation \"p -ϵ-> q\"(at level 50).\nInductive Closure : state -> state -> Prop :=\n    | CL_refl p : p -ϵ-> p\n    | CL_single p q : q ∈ δ p ϵ_ -> p -ϵ-> q\n    | CL_trans p q r : p -ϵ-> q -> q -ϵ-> r ->  p -ϵ-> r\n    where \"p -ϵ-> q\" := (Closure p q).\n\nAxiom closure : {set state} -> {set state}.\nAxiom closureP : forall (P : {set state}) q,\n    reflect (forall p, p ∈ P -> p -ϵ-> q) (q ∈ closure P).\n\n\n\n\n\nFixpoint δ' (p : state) (s : finStr) : {set state} :=\n    match s with\n    | [::] => closure [set p]\n    | a :: w => closure (bigcup [set δ x (toSym a) | x in δ' p w])\n    end.\n\nDefinition L := [set w : finStr | (δ' p0 w ∩ F) == ∅].\n\n\nEnd NFA.\n\n \n\n\n\n", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "compiler", "sha": "0ba27418104bb0abc38ca2f9ccdcd7e539629dd2", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-compiler", "path": "github-repos/coq/gaxiiiiiiiiiiii-compiler/compiler-0ba27418104bb0abc38ca2f9ccdcd7e539629dd2/NFA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.663666445336011}}
{"text": "Require Import Reals.\nRequire Import Ensembles.\nRequire Import Lra.\nLocal Open Scope R.\n\n(**Let D be the set [0,1] cup {2} cup [3,4). Show that any function f : D -> R is continuous at 2 *)\n(*must roll my own continuity, to play w Ensembles-as-Types*)\n\nRecord Aset (A : Ensemble R) : Type := mkset {x :> R; inA : A x}.\n\nDefinition D (x : R) :=\n  0 <= x <= 1 \\/ x = 2 \\/ 3 <= x < 4.\n\nLemma two_is_in_D : D 2.\nProof.\n  unfold D.\n  lra.\nQed.\n\nDefinition Aconverges (A : Ensemble R) (Un : nat -> Aset A) (c : Aset A) :=\n  (*convergence of a sequence when every element is a member of a certain set*)\n  forall eps,\n    eps > 0 ->\n    exists N, forall n, (n >= N)%nat -> R_dist (Un n) c < eps.\n\nDefinition continuous_pt (A : Ensemble R) (f : Aset A -> R) (c : Aset A) :=\n  (*sequential characterization of convergence*)\n  (*Un_cv is the standard library definition of convergence on R*)\n  forall (Xn : nat -> Aset A), Aconverges A Xn c -> Un_cv (fun n => f (Xn n)) (f c).\n\nAxiom equality :\n  (*equality in R - Theorem 1.2.6 in Abbott*)\n  forall x y eps, Rabs (x - y) < eps <-> x = y.\n\nAxiom equality' :\n  (*equality in a set A - Theorem 1..2.6 in Abbott*)\n  forall (A : Ensemble R) (x y : Aset A) (eps : R), Rabs (x - y) < eps <-> x = y.\n\nAxiom uniqueness' :\n  (*I feel like this ought to be a part of the theory, so it may not be necessary for me to declare it as an axiom*)\n  forall (A : Ensemble R) (f : Aset A -> R) (x y : Aset A), x = y -> f x = f y.\n\n\nTheorem continuous_at_2 : forall (f : Aset D -> R), continuous_pt D f (mkset D 2 two_is_in_D).\nProof.\n  intros f Xn H.\n  unfold Aconverges in H.\n  unfold Un_cv.\n  intros eps H__eps.\n  specialize (H eps H__eps).\n  destruct H as [N H].\n  exists N.\n  intros n H__n.\n  specialize (H n H__n).\n\n  unfold R_dist in *.\n  apply equality.\n  apply equality' in H.\n  apply uniqueness'.\n  apply H.\nQed.\n", "meta": {"author": "quinn-dougherty", "repo": "rca", "sha": "e5d5344e2880e80a3ac395772db7fc193566a63c", "save_path": "github-repos/coq/quinn-dougherty-rca", "path": "github-repos/coq/quinn-dougherty-rca/rca-e5d5344e2880e80a3ac395772db7fc193566a63c/roll-my-own/6final.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6635968559141882}}
{"text": "Require Import ZArith.\nFrom mathcomp Require Import ssrbool ssreflect.\n\nSet Implicit Arguments.\n\nInductive Typ :=\n| Int\n| Bool.\n\nDefinition const (a : Typ) : Type :=\n  match a with\n  | Int => nat\n  | Bool => bool\n  end.\n\nRecord ref (a : Typ) : Type :=\n  { addr : nat; init : const a }.\n  \nDefinition dec_eq_typ (a b : Typ) : decidable (a = b).\nProof. rewrite /decidable. repeat decide equality. Defined.\n", "meta": {"author": "lastland", "repo": "MonadicReflection", "sha": "0b20a78601e23d2bf40631746a3742897bfb43ab", "save_path": "github-repos/coq/lastland-MonadicReflection", "path": "github-repos/coq/lastland-MonadicReflection/MonadicReflection-0b20a78601e23d2bf40631746a3742897bfb43ab/Typ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6635968319002806}}
{"text": "(* matrices *)\n\nSet Nested Proofs Allowed.\nSet Implicit Arguments.\n\nRequire Import Utf8 Arith Bool.\nImport List List.ListNotations.\nRequire Import Init.Nat.\n\nRequire Import Misc.\nRequire Import RingLike IterAdd IterMul IterAnd.\nRequire Import MyVector Signature.\n\n(* matrices *)\n\nRecord matrix T := mk_mat\n  { mat_list_list : list (list T) }.\n\nDefinition mat_nrows {T} (M : matrix T) := length (mat_list_list M).\nDefinition mat_ncols {T} (M : matrix T) := length (hd [] (mat_list_list M)).\nDefinition mat_el {T} {ro : ring_like_op T} (M : matrix T) i j :=\n  nth (j - 1) (nth (i - 1) (mat_list_list M) []) 0%L.\n\n(* *)\n\nDefinition mat_eqb {T} (eqb : T → T → bool) (A B : matrix T) :=\n  list_eqv (list_eqv eqb) (mat_list_list A) (mat_list_list B).\n\n(* correct_matrix: matrix whose list list is made of non\n   empty lists (rows) of same length *)\n\nDefinition is_correct_matrix {T} (M : matrix T) :=\n  ((mat_ncols M ≠? 0) || (mat_nrows M =? 0)) &&\n  (⋀ (l ∈ mat_list_list M), (length l =? mat_ncols M)).\n\n(* square_matrix: matrix whose list list is mode of non\n   empty lists of same length as the list list  *)\n\nDefinition is_square_matrix {T} (M : matrix T) :=\n  ((mat_ncols M ≠? 0) || (mat_nrows M =? 0)) &&\n  (⋀ (l ∈ mat_list_list M), (length l =? mat_nrows M)).\n\n(* mat_eqb is an equality *)\n\nTheorem mat_eqb_eq : ∀ T (eqb : T → T → bool),\n  equality eqb →\n  ∀ (A B : matrix T),\n  mat_eqb eqb A B = true ↔ A = B.\nProof.\nintros * Heqb *.\nsplit; intros Hab. {\n  unfold mat_eqb in Hab.\n  apply list_eqb_eq in Hab; [ | now apply -> equality_list_eqv ].\n  destruct A as (lla).\n  destruct B as (llb).\n  now cbn in Hab; f_equal.\n} {\n  subst B.\n  apply list_eqb_eq; [ | easy ].\n  now apply -> equality_list_eqv.\n}\nQed.\n\n(* is_correct_matrix (a bool) easier to use with Prop *)\n\nTheorem is_scm_mat_iff {T} : ∀ f (M : matrix T),\n  ((mat_ncols M ≠? 0) || (mat_nrows M =? 0)) &&\n  (⋀ (l ∈ mat_list_list M), (length l =? f)) = true ↔\n  (mat_ncols M = 0 → mat_nrows M = 0) ∧\n  ∀ l, l ∈ mat_list_list M → length l = f.\nProof.\nintros.\nsplit; intros Hm. {\n  apply Bool.andb_true_iff in Hm.\n  destruct Hm as (Hrc, Hc).\n  apply Bool.orb_true_iff in Hrc.\n  split. {\n    intros Hcz.\n    destruct Hrc as [Hrc| Hrc]. {\n      apply negb_true_iff in Hrc.\n      now apply Nat.eqb_neq in Hrc.\n    } {\n      now apply Nat.eqb_eq in Hrc.\n    }\n  }\n  intros l Hl.\n  remember (mat_list_list M) as ll eqn:Hll.\n  clear Hll.\n  induction ll as [| la]; [ easy | cbn ].\n  rewrite and_list_cons in Hc.\n  apply Bool.andb_true_iff in Hc.\n  destruct Hc as (Hla, Hc).\n  apply Nat.eqb_eq in Hla.\n  destruct Hl as [Hl| Hl]; [ now subst l | ].\n  now apply IHll.\n} {\n  destruct Hm as (Hrc & Hc).\n  apply Bool.andb_true_iff.\n  split. {\n    apply Bool.orb_true_iff.\n    destruct (Nat.eq_dec (mat_nrows M) 0) as [Hnz| Hnz]. {\n      now right; apply Nat.eqb_eq.\n    }\n    left.\n    apply negb_true_iff.\n    apply Nat.eqb_neq.\n    intros H.\n    now apply Hnz, Hrc.\n  }\n  remember (mat_list_list M) as ll eqn:Hll.\n  clear Hll.\n  induction ll as [| la]; [ easy | ].\n  rewrite and_list_cons.\n  apply Bool.andb_true_iff.\n  split; [ now apply Nat.eqb_eq, Hc; left | ].\n  apply IHll.\n  intros l Hl.\n  now apply Hc; right.\n}\nQed.\n\nTheorem tail_is_correct_matrix : ∀ {A} (M : matrix A),\n  is_correct_matrix M = true\n  → is_correct_matrix (mk_mat (tl (mat_list_list M))) = true.\nProof.\nintros * Hcm.\napply is_scm_mat_iff in Hcm.\napply is_scm_mat_iff.\ndestruct Hcm as (Hcr, Hcl).\nsplit. {\n  unfold mat_ncols; cbn.\n  intros Hr.\n  apply length_zero_iff_nil in Hr.\n  unfold mat_ncols in Hcr, Hcl.\n  destruct M as (ll); cbn in *.\n  destruct ll as [| la]; [ easy | ].\n  cbn in Hr |-*.\n  destruct ll as [| la']; [ easy | ].\n  cbn in Hr; subst la'; exfalso.\n  cbn in Hcr.\n  specialize (Hcl [] (or_intror (or_introl eq_refl))) as H1.\n  cbn in H1; symmetry in H1.\n  now specialize (Hcr H1).\n} {\n  intros l Hl; cbn in Hl.\n  unfold mat_ncols; cbn.\n  rewrite Hcl. 2: {\n    destruct M as (ll); cbn in Hl |-*.\n    destruct ll as [| la]; [ easy | ].\n    now right.\n  }\n  symmetry.\n  rewrite Hcl. 2: {\n    destruct M as (ll); cbn in Hl |-*.\n    destruct ll as [| la]; [ easy | ].\n    destruct ll as [| la']; [ easy | ].\n    cbn in Hl |-*.\n    now right; left.\n  }\n  easy.\n}\nQed.\n\nTheorem matrix_eq : ∀ T (ro : ring_like_op T) MA MB,\n  (∀ i j, 1 ≤ i ≤ mat_nrows MA → 1 ≤ j ≤ mat_ncols MB →\n   mat_el MA i j = mat_el MB i j)\n  → is_correct_matrix MA = true\n  → is_correct_matrix MB = true\n  → mat_nrows MA = mat_nrows MB\n  → mat_ncols MA = mat_ncols MB\n  → MA = MB.\nProof.\nintros * Hij Ha Hb Hrr Hcc.\ndestruct MA as (lla).\ndestruct MB as (llb).\nf_equal.\ncbn in *.\nremember (length lla) as len eqn:Hr; symmetry in Hr.\nrename Hrr into Hc; symmetry in Hc; move Hc before Hr.\nrevert lla llb Hr Hc Hij Hcc Ha Hb.\ninduction len; intros. {\n  apply length_zero_iff_nil in Hr, Hc; congruence.\n}\ndestruct lla as [| la]; [ easy | ].\ndestruct llb as [| lb]; [ easy | ].\ncbn in Hr, Hc, Hcc.\napply Nat.succ_inj in Hr, Hc.\nf_equal. {\n  apply nth_ext with (d := 0%L) (d' := 0%L); [ easy | ].\n  intros i Hi.\n  unfold mat_ncols in Hij.\n  cbn - [ nth ] in Hij.\n  specialize (Hij 1 (i + 1)).\n  rewrite Nat.add_sub, Nat.sub_diag in Hij; cbn in Hij.\n  apply Hij. {\n    split; [ easy | ].\n    now apply -> Nat.succ_le_mono.\n  }\n  rewrite Nat.add_1_r.\n  split; [ now apply -> Nat.succ_le_mono | ].\n  now rewrite <- Hcc.\n}\napply IHlen; [ easy | easy | | | | ]; cycle 1. {\n  apply is_scm_mat_iff in Ha.\n  apply is_scm_mat_iff in Hb.\n  destruct Ha as (Ha1, Ha2).\n  destruct Hb as (Hb1, Hb2).\n  unfold mat_ncols; cbn.\n  specialize (Ha2 (hd [] lla)).\n  specialize (Hb2 (hd [] llb)).\n  cbn - [ In ] in Ha2, Hb2.\n  destruct lla as [| la']. {\n    cbn in Hr; subst len.\n    now apply length_zero_iff_nil in Hc; subst llb.\n  }\n  destruct llb as [| lb']. {\n    now cbn in Hc; move Hc at top; subst len.\n  }\n  cbn in Ha2, Hb2 |-*.\n  specialize (Ha2 (or_intror (or_introl eq_refl))).\n  specialize (Hb2 (or_intror (or_introl eq_refl))).\n  congruence.\n} {\n  now apply tail_is_correct_matrix in Ha.\n} {\n  now apply tail_is_correct_matrix in Hb.\n}\nintros * Hi Hj.\nunfold mat_ncols in Hij, Hj.\ncbn - [ nth ] in Hij.\ncbn in Hj.\nspecialize (Hij (S i) j) as H1.\nassert (H : 1 ≤ S i ≤ S len). {\n  now split; apply -> Nat.succ_le_mono.\n}\nspecialize (H1 H); clear H.\ndestruct i; [ easy | ].\nrewrite Nat_sub_succ_1 in H1 |-*.\nrewrite List_nth_succ_cons in H1.\napply H1.\nsplit; [ easy | ].\napply is_scm_mat_iff in Hb.\ndestruct Hb as (Hb1, Hb2).\nunfold mat_ncols in Hb2; cbn in Hb2.\ndestruct llb as [| lb']; cbn in Hj; [ flia Hj | ].\nspecialize (Hb2 lb' (or_intror (or_introl eq_refl))).\nnow rewrite Hb2 in Hj.\nQed.\n\nTheorem fold_mat_nrows {T} : ∀ (M : matrix T),\n  length (mat_list_list M) = mat_nrows M.\nProof. easy. Qed.\n\nTheorem fold_mat_ncols {T} : ∀ (M : matrix T),\n  length (hd [] (mat_list_list M)) = mat_ncols M.\nProof. easy. Qed.\n\nTheorem fold_mat_el {T} {ro : ring_like_op T} : ∀ (M : matrix T) i j,\n  nth j (nth i (mat_list_list M) []) 0%L = mat_el M (S i) (S j).\nProof.\nintros.\nunfold mat_el.\nnow do 2 rewrite Nat_sub_succ_1.\nQed.\n\nTheorem eq_mat_nrows_0 {T} : ∀ M : matrix T,\n  mat_nrows M = 0\n  → mat_list_list M = [].\nProof.\nintros * Hr.\nunfold mat_nrows in Hr.\nnow apply length_zero_iff_nil in Hr.\nQed.\n\nTheorem fold_left_mat_fold_left_list_list : ∀ T A (M : matrix T) (l : list A) f,\n  fold_left f l M =\n  mk_mat\n    (fold_left (λ ll k, mat_list_list (f (mk_mat ll) k)) l (mat_list_list M)).\nProof.\nintros.\nrevert M.\ninduction l as [| a]; intros; [ now destruct M | cbn ].\nrewrite IHl; cbn.\nnow destruct M.\nQed.\n\nRecord correct_matrix T := mk_cm\n  { cm_mat : matrix T;\n    cm_prop : is_correct_matrix cm_mat = true }.\n\nTheorem fold_corr_mat_ncols {T} : ∀ (M : matrix T) d,\n  is_correct_matrix M = true\n  → ∀ i, i < mat_nrows M\n  → length (nth i (mat_list_list M) d) = mat_ncols M.\nProof.\nintros * Hm * Him.\napply is_scm_mat_iff in Hm.\ndestruct Hm as (Hcr, Hc).\napply Hc.\napply nth_In.\nnow rewrite fold_mat_nrows.\nQed.\n\nRecord square_matrix n T :=\n  { sm_mat : matrix T;\n    sm_prop : (mat_nrows sm_mat =? n) && is_square_matrix sm_mat = true }.\n\nTheorem square_matrix_eq {n T} : ∀ (MA MB : square_matrix n T),\n  sm_mat MA = sm_mat MB\n  → MA = MB.\nProof.\nintros * Hab.\ndestruct MA as (MA, Ha).\ndestruct MB as (MB, Hb).\ncbn in Hab.\ndestruct Hab.\nf_equal.\napply (Eqdep_dec.UIP_dec Bool.bool_dec).\nQed.\n\nTheorem squ_mat_ncols {T} : ∀ (M : matrix T),\n  is_square_matrix M = true\n  → mat_ncols M = mat_nrows M.\nProof.\nintros * Hm.\napply is_scm_mat_iff in Hm.\ndestruct Hm as (Hcr & Hc).\ndestruct (Nat.eq_dec (mat_nrows M) 0) as [Hnz| Hnz]. {\n  unfold mat_nrows, mat_ncols in Hnz |-*.\n  now apply length_zero_iff_nil in Hnz; rewrite Hnz.\n}\napply Nat.neq_0_lt_0 in Hnz.\nnow apply Hc, List_hd_in.\nQed.\n\nTheorem squ_mat_is_corr {T} : ∀ (M : matrix T),\n  is_square_matrix M = true\n  → is_correct_matrix M = true.\nProof.\nintros * Hsm.\nspecialize (squ_mat_ncols _ Hsm) as Hc.\napply is_scm_mat_iff in Hsm.\napply is_scm_mat_iff.\nsplit; [ easy | ].\nintros l Hl.\ndestruct Hsm as (Hcr & Hc').\nnow rewrite Hc'.\nQed.\n\n(* *)\n\nFixpoint concat_list_in_list {T} (ll1 ll2 : list (list T)) :=\n  match ll1 with\n  | [] => ll2\n  | l1 :: ll1' =>\n       match ll2 with\n       | [] => ll1\n       | l2 :: ll2' => app l1 l2 :: concat_list_in_list ll1' ll2'\n       end\n  end.\n\nSection a.\n\nContext {T : Type}.\nContext (ro : ring_like_op T).\nContext {rp : ring_like_prop T}.\n\n(* addition *)\n\nDefinition mat_add (MA MB : matrix T) : matrix T :=\n  mk_mat (map2 (map2 rngl_add) (mat_list_list MA) (mat_list_list MB)).\n\n(* multiplication *)\n\nDefinition mat_mul_el MA MB i k :=\n   ∑ (j = 1, mat_ncols MA), mat_el MA i j * mat_el MB j k.\n\nDefinition mat_mul (MA MB : matrix T) : matrix T :=\n  mk_mat\n    (map (λ i, map (mat_mul_el MA MB i) (seq 1 (mat_ncols MB)))\n       (seq 1 (mat_nrows MA))).\n\n(* opposite *)\n\nDefinition mat_opp (M : matrix T) : matrix T :=\n  mk_mat (map (map rngl_opp) (mat_list_list M)).\n\n(* subtraction *)\n\nDefinition mat_sub (MA MB : matrix T) :=\n  mat_add MA (mat_opp MB).\n\n(* vector as a matrix nx1 *)\n\nDefinition mat_of_vert_vect (V : vector T) :=\n  mk_mat (map (λ i, [i]) (vect_list V)).\n\n(* vector as a matrix 1xn *)\n\nDefinition mat_of_horiz_vect (V : vector T) :=\n  mk_mat [vect_list V].\n\n(* concatenation of a matrix and a column vector *)\n\nDefinition mat_vect_concat (M : matrix T) V :=\n  mk_mat (map2 (λ row e, row ++ [e]) (mat_list_list M) (vect_list V)).\n\n(* multiplication of a matrix and a vector *)\n\nDefinition mat_mul_vect_r (M : matrix T) (V : vector T) :=\n  mk_vect (map (λ row, vect_dot_mul (mk_vect row) V) (mat_list_list M)).\n\n(*\nDefinition mat_mul_vect_r' (M : matrix T) (V : vector T) :=\n  mk_vect\n    match vect_list V with\n    | nil => []\n    | cons d _ => map (hd d) (mat_list_list (mat_mul M (mat_of_vert_vect V)))\n  end.\n*)\n\n(* multiplication of a vector and a matrix *)\n\n(* to be analyzed and completed\nDefinition mat_mul_vect_l (V : vector T) (M : matrix T) :=\n  mk_vect (map (λ row, vect_dot_mul (mk_vect row) V) (mat_list_list M)).\n*)\n\n(* multiplication of a matrix by a scalar *)\n\nDefinition mat_mul_scal_l s (M : matrix T) :=\n  mk_mat (map (map (rngl_mul s)) (mat_list_list M)).\n\n(* matrix whose k-th column is replaced by a vector *)\n\nDefinition mat_repl_vect k (M : matrix T) (V : vector T) :=\n  mk_mat (map2 (replace_at (k - 1)) (mat_list_list M) (vect_list V)).\n\nTheorem mat_el_repl_vect : ∀ (M : matrix T) V i j k,\n  is_correct_matrix M = true\n  → i ≤ vect_size V\n  → 1 ≤ i ≤ mat_nrows M\n  → 1 ≤ j ≤ mat_ncols M\n  → 1 ≤ k ≤ mat_ncols M\n  → mat_el (mat_repl_vect k M V) i j =\n    if Nat.eq_dec j k then vect_el V i else mat_el M i j.\nProof.\nintros * Hm His Hir Hjc Hkc; cbn.\nrewrite map2_nth with (a := []) (b := 0%L); cycle 1. {\n  rewrite fold_mat_nrows.\n  now apply Nat_1_le_sub_lt.\n} {\n  rewrite fold_vect_size.\n  now apply Nat_1_le_sub_lt.\n}\nunfold replace_at.\ndestruct (Nat.eq_dec j k) as [Hjk| Hjk]. {\n  subst k.\n  rewrite app_nth2. 2: {\n    rewrite firstn_length.\n    rewrite fold_corr_mat_ncols; [ | easy | now apply Nat_1_le_sub_lt ].\n    unfold ge.\n    rewrite Nat.min_l; [ easy | flia Hjc ].\n  }\n  rewrite firstn_length.\n  rewrite fold_corr_mat_ncols; [ | easy | now apply Nat_1_le_sub_lt ].\n  rewrite Nat.min_l; [ | flia Hjc ].\n  now rewrite Nat.sub_diag.\n}\ndestruct (lt_dec j k) as [Hljk| Hljk]. {\n  rewrite app_nth1. 2: {\n    rewrite firstn_length.\n    rewrite fold_corr_mat_ncols; [ | easy | now apply Nat_1_le_sub_lt ].\n    rewrite Nat.min_l; [ | flia Hkc ].\n    apply Nat_1_le_sub_lt.\n    split; [ easy | flia Hjk Hljk ].\n  }\n  rewrite List_nth_firstn; [ easy | flia Hjc Hljk ].\n} {\n  apply Nat.nlt_ge in Hljk.\n  rewrite app_nth2. 2: {\n    rewrite firstn_length.\n    rewrite fold_corr_mat_ncols; [ | easy | now apply Nat_1_le_sub_lt ].\n    rewrite Nat.min_l; [ flia Hjc Hljk | flia Hkc ].\n  }\n  rewrite firstn_length.\n  rewrite fold_corr_mat_ncols; [ | easy | now apply Nat_1_le_sub_lt ].\n  rewrite Nat.min_l; [ | flia Hkc ].\n  rewrite Nat_succ_sub_succ_r; [ | flia Hkc Hjk Hljk ].\n  cbn - [ skipn ].\n  rewrite List_nth_skipn.\n  rewrite Nat.sub_add; [ easy | flia Hkc Hjk Hljk ].\n}\nQed.\n\nTheorem mat_repl_vect_nrows : ∀ k (M : matrix T) V,\n  vect_size V = mat_nrows M\n  → mat_nrows (mat_repl_vect k M V) = mat_nrows M.\nProof.\nintros * Hv; cbn.\nrewrite map2_length.\nrewrite fold_mat_nrows, fold_vect_size, Hv.\napply Nat.min_id.\nQed.\n\nTheorem mat_repl_vect_ncols : ∀ k (M : matrix T) V,\n  1 ≤ k ≤ mat_ncols M\n  → vect_size V = mat_ncols M\n  → mat_ncols (mat_repl_vect k M V) = mat_ncols M.\nProof.\nintros * Hkc Hv.\n(* works with nrows=0 *)\ndestruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]. {\n  unfold mat_nrows in Hrz.\n  apply length_zero_iff_nil in Hrz.\n  unfold mat_ncols; cbn.\n  now rewrite Hrz.\n}\napply Nat.neq_0_lt_0 in Hrz.\n(* works with ncols=0 *)\ndestruct (Nat.eq_dec (mat_ncols M) 0) as [Hcz| Hcz]. {\n  rewrite Hcz in Hv.\n  unfold vect_size in Hv.\n  apply length_zero_iff_nil in Hv.\n  unfold mat_ncols in Hcz.\n  apply length_zero_iff_nil in Hcz.\n  unfold mat_ncols; cbn.\n  rewrite Hv.\n  now rewrite map2_nil_r, Hcz.\n}\napply Nat.neq_0_lt_0 in Hcz.\nunfold mat_ncols.\ncbn - [ skipn ].\nrewrite List_hd_nth_0.\nrewrite map2_nth with (a := []) (b := 0%L); cycle 1. {\n  now rewrite fold_mat_nrows.\n} {\n  now rewrite fold_vect_size, Hv.\n}\nunfold replace_at.\nrewrite app_length.\nrewrite firstn_length.\nrewrite <- List_hd_nth_0.\nrewrite fold_mat_ncols.\nrewrite List_cons_length.\nrewrite skipn_length.\nrewrite fold_mat_ncols.\nflia Hkc.\nQed.\n\nTheorem mat_repl_vect_is_square : ∀ k (M : matrix T) V,\n  1 ≤ k ≤ mat_ncols M\n  → vect_size V = mat_nrows M\n  → is_square_matrix M = true\n  → is_square_matrix (mat_repl_vect k M V) = true.\nProof.\nintros * Hkc Hv Hm.\nspecialize (squ_mat_ncols _ Hm) as Hcn.\napply is_scm_mat_iff in Hm.\napply is_scm_mat_iff.\ndestruct Hm as (Hcr & Hc).\nrewrite mat_repl_vect_nrows; [ | congruence ].\nsplit. {\n  destruct (lt_dec k (mat_ncols M)) as [Hkm| Hkm]. {\n    rewrite mat_repl_vect_ncols; [ easy | easy | congruence ].\n  }\n  apply Nat.nlt_ge in Hkm.\n  rewrite mat_repl_vect_ncols; [ easy | easy | congruence ].\n} {\n  intros la Hla.\n  cbn - [ skipn ] in Hla.\n  apply in_map2_iff in Hla.\n  destruct Hla as (i & Hi & lb & a & Hla).\n  rewrite fold_mat_nrows, fold_vect_size, Hv in Hi.\n  rewrite Nat.min_id in Hi.\n  subst la.\n  unfold replace_at.\n  rewrite app_length.\n  rewrite firstn_length.\n  cbn - [ skipn ].\n  rewrite skipn_length.\n  rewrite fold_corr_mat_ncols; [ | | easy ]. 2: {\n    apply is_scm_mat_iff.\n    split; [ easy | now rewrite Hcn ].\n  }\n  rewrite Nat.min_l; [ | flia Hkc ].\n  rewrite Hcn in Hkc |-*.\n  flia Hkc.\n}\nQed.\n\n(* null matrix of dimension m × n *)\n\nDefinition mZ m n : matrix T :=\n  mk_mat (repeat (repeat 0%L n) m).\n\n(* identity square matrix of dimension n *)\n\nDefinition δ i j := if i =? j then 1%L else 0%L.\nDefinition mI n : matrix T := mk_mat (map (λ i, map (δ i) (seq 0 n)) (seq 0 n)).\n\nTheorem δ_diag : ∀ i, δ i i = 1%L.\nProof.\nintros.\nunfold δ.\nnow rewrite Nat.eqb_refl.\nQed.\n\nTheorem δ_ndiag : ∀ i j, i ≠ j → δ i j = 0%L.\nProof.\nintros * Hij.\nunfold δ.\nrewrite if_eqb_eq_dec.\nnow destruct (Nat.eq_dec i j).\nQed.\n\nTheorem mI_any_seq_start : ∀ sta len,\n  mI len = mk_mat (map (λ i, map (δ i) (seq sta len)) (seq sta len)).\nProof.\nintros.\nunfold mI; f_equal.\nsymmetry.\nrewrite List_map_seq.\napply map_ext_in.\nintros i Hi.\nrewrite List_map_seq.\napply map_ext_in.\nintros j Hj.\ndestruct (Nat.eq_dec i j) as [Hij| Hij]. {\n  now subst j; do 2 rewrite δ_diag.\n}\nrewrite δ_ndiag; [ | flia Hij ].\nnow rewrite δ_ndiag.\nQed.\n\nEnd a.\n\nSection a.\n\nContext {T : Type}.\nContext (ro : ring_like_op T).\nContext {rp : ring_like_prop T}.\nContext {Hop : @rngl_has_opp T ro = true}.\n\nDeclare Scope M_scope.\nDelimit Scope M_scope with M.\n\nArguments δ {T ro} (i j)%nat.\n\nArguments matrix_eq {T}%type {ro} (MA MB)%M.\nArguments mat_add {T ro} MA%M MB%M.\nArguments mat_mul {T ro} MA%M MB%M.\nArguments mat_mul_el {T}%type {ro} (MA MB)%M (i k)%nat.\nArguments mat_mul_scal_l {T ro} s%L M%M.\nArguments mat_list_list [T]%type m%M.\nArguments mat_nrows {T}%type M%M.\nArguments mat_ncols {T}%type M%M.\nArguments mat_el {T}%type {ro} M%M (i j)%nat.\nArguments mat_opp {T}%type {ro}.\nArguments mat_sub {T ro} MA%M MB%M.\nArguments mI {T ro} n%nat.\nArguments mZ {T ro} (m n)%nat.\nArguments minus_one_pow {T ro}.\nArguments vect_zero {T ro} n%nat.\nArguments is_correct_matrix {T}%type M%M.\nArguments is_square_matrix {T}%type M%M.\nArguments Build_square_matrix n%nat [T]%type sm_mat%M.\n\nNotation \"A + B\" := (mat_add A B) : M_scope.\nNotation \"A - B\" := (mat_sub A B) : M_scope.\nNotation \"A * B\" := (mat_mul A B) : M_scope.\nNotation \"μ × A\" := (mat_mul_scal_l μ A) (at level 40) : M_scope.\nNotation \"- A\" := (mat_opp A) : M_scope.\n\nArguments mat_mul_vect_r {T ro} M%M V%V.\n\nNotation \"A • V\" := (mat_mul_vect_r A V) (at level 40) : M_scope.\nNotation \"A • V\" := (mat_mul_vect_r A V) (at level 40) : V_scope.\nNotation \"μ × A\" := (mat_mul_scal_l μ A) (at level 40) : M_scope.\n\nTheorem fold_mat_sub : ∀ (MA MB : matrix T), (MA + - MB = MA - MB)%M.\nProof. easy. Qed.\n\n(* commutativity of addition *)\n\nTheorem mat_add_comm : ∀ (MA MB : matrix T), (MA + MB = MB + MA)%M.\nProof.\nintros.\nunfold mat_add; f_equal.\nremember (mat_list_list MA) as lla eqn:Hlla.\nremember (mat_list_list MB) as llb eqn:Hllb.\nclear MA MB Hlla Hllb.\nrevert llb.\ninduction lla as [| la]; intros; [ now destruct llb | cbn ].\ndestruct llb as [| lb]; [ easy | cbn ].\nrewrite IHlla; f_equal.\nrevert lb.\ninduction la as [| a]; intros; [ now destruct lb | cbn ].\ndestruct lb as [| b]; [ easy | cbn ].\nnow rewrite rngl_add_comm, IHla.\nQed.\n\n(* associativity of addition *)\n\nTheorem mat_add_add_swap : ∀ (MA MB MC : matrix T),\n  (MA + MB + MC = MA + MC + MB)%M.\nProof.\nintros.\nunfold mat_add; f_equal; cbn.\nremember (mat_list_list MA) as lla eqn:Hlla.\nremember (mat_list_list MB) as llb eqn:Hllb.\nremember (mat_list_list MC) as llc eqn:Hllc.\nclear MA MB MC Hlla Hllb Hllc.\nrevert llb llc.\ninduction lla as [| la]; intros; [ easy | cbn ].\ndestruct llb as [| lb]; [ now destruct llc | cbn ].\ndestruct llc as [| lc]; [ easy | cbn ].\nrewrite IHlla; f_equal.\nrevert lb lc.\ninduction la as [| a]; intros; [ easy | cbn ].\ndestruct lb as [| b]; [ now destruct lc | cbn ].\ndestruct lc as [| c]; [ easy | cbn ].\nnow rewrite rngl_add_add_swap, IHla.\nQed.\n\nTheorem mat_add_assoc : ∀ (MA MB MC : matrix T),\n  (MA + (MB + MC) = (MA + MB) + MC)%M.\nProof.\nintros.\nrewrite mat_add_comm.\nrewrite mat_add_add_swap.\nf_equal.\napply mat_add_comm.\nQed.\n\n(* addition to zero *)\n\nTheorem mat_add_0_l {m n} : ∀ (M : matrix T),\n  is_correct_matrix M = true\n  → m = mat_nrows M\n  → n = mat_ncols M\n  → (mZ m n + M)%M = M.\nProof.\nintros * HM Hr Hc.\nsubst m n.\napply is_scm_mat_iff in HM.\ndestruct HM as (_, HM).\nunfold mZ, \"+\"%M, mat_nrows, mat_ncols.\nunfold mat_ncols in HM.\ndestruct M as (ll); cbn in HM |-*; f_equal.\nremember (length (hd [] ll)) as ncols eqn:H.\nclear H.\nrevert ncols HM.\ninduction ll as [| la]; intros; [ easy | cbn ].\nrewrite IHll. 2: {\n  intros l Hl.\n  now apply HM; right.\n}\nf_equal.\nspecialize (HM la (or_introl eq_refl)).\nclear - rp HM.\nrevert ncols HM.\ninduction la as [| a]; intros; [ now destruct ncols | cbn ].\ndestruct ncols; [ easy | cbn ].\nrewrite rngl_add_0_l; f_equal.\napply IHla.\ncbn in HM.\nnow apply Nat.succ_inj in HM.\nQed.\n\nTheorem mat_add_0_r {m n} : ∀ (M : matrix T),\n  is_correct_matrix M = true\n  → m = mat_nrows M\n  → n = mat_ncols M\n  → (M + mZ m n)%M = M.\nProof.\nintros * HM Hr Hc.\nrewrite mat_add_comm.\nnow apply mat_add_0_l.\nQed.\n\n(* addition left and right with opposite *)\n\nTheorem mat_add_opp_l {m n} : ∀ (M : matrix T),\n  is_correct_matrix M = true\n  → m = mat_nrows M\n  → n = mat_ncols M\n  → (- M + M = mZ m n)%M.\nProof.\nintros * HM Hr Hc.\nsubst m n.\napply is_scm_mat_iff in HM.\ndestruct HM as (_, HM).\nunfold \"+\"%M, mZ, mat_nrows, mat_ncols; cbn; f_equal.\nunfold mat_ncols in HM.\ndestruct M as (ll); cbn in HM |-*.\nremember (length (hd [] ll)) as ncols eqn:H; clear H.\ninduction ll as [| la]; [ easy | cbn ].\nrewrite IHll. 2: {\n  intros * Hl.\n  now apply HM; right.\n}\nf_equal.\nclear IHll.\nspecialize (HM la (or_introl eq_refl)).\nrevert ncols HM.\ninduction la as [| a]; intros; cbn; [ now rewrite <- HM | ].\nrewrite rngl_add_opp_l; [ | easy ].\ndestruct ncols; [ easy | ].\ncbn; f_equal.\ncbn in HM.\napply Nat.succ_inj in HM.\nnow apply IHla.\nQed.\n\nTheorem mat_add_opp_r : ∀ (M : matrix T),\n  is_correct_matrix M = true\n  → (M - M = mZ (mat_nrows M) (mat_ncols M))%M.\nProof.\nintros * HM.\nunfold mat_sub.\nrewrite mat_add_comm.\nnow apply mat_add_opp_l.\nQed.\n\nTheorem mat_add_sub :\n  ∀ MA MB : matrix T,\n  is_correct_matrix MA = true\n  → is_correct_matrix MB = true\n  → mat_nrows MA = mat_nrows MB\n  → mat_ncols MA = mat_ncols MB\n  → (MA + MB - MB)%M = MA.\nProof.\nintros * Ha Hb Hrab Hcab.\nunfold mat_sub.\nrewrite <- mat_add_assoc.\nrewrite fold_mat_sub.\nrewrite mat_add_opp_r; [ | easy ].\nnow rewrite mat_add_0_r.\nQed.\n\nTheorem mZ_nrows : ∀ m n, mat_nrows (mZ m n) = m.\nProof.\nintros; cbn.\napply repeat_length.\nQed.\n\nTheorem mZ_ncols : ∀ m n, m ≠ 0 → mat_ncols (mZ m n) = n.\nProof.\nintros * Hmz.\nunfold mZ, mat_ncols; cbn.\ndestruct m; [ easy | cbn ].\napply repeat_length.\nQed.\n\nTheorem mI_nrows : ∀ n, mat_nrows (mI n) = n.\nProof.\nintros.\ndestruct n; cbn - [ \"=?\" ]; [ easy | ].\nnow rewrite List_map_seq_length.\nQed.\n\nTheorem mI_ncols : ∀ n, mat_ncols (mI n) = n.\nProof.\nintros.\ndestruct n; cbn - [ \"=?\" ]; [ easy | ].\nnow rewrite List_map_seq_length.\nQed.\n\nTheorem mat_el_mI_ndiag : ∀ n i j,\n  1 ≤ i\n  → 1 ≤ j\n  → i ≠ j\n  → mat_el (mI n) i j = 0%L.\nProof.\nintros * Hi Hj Hij.\nunfold mat_el, mI; cbn.\ndestruct (Nat.eq_dec n 0) as [Hnz| Hnz]. {\n  subst n; cbn.\n  rewrite Tauto_match_nat_same.\n  now rewrite List_nth_nil.\n}\napply Nat.neq_0_lt_0 in Hnz.\ndestruct (le_dec i n) as [Hin| Hin]. {\n  rewrite List_map_nth' with (a := 0); [ | rewrite seq_length; flia Hi Hin ].\n  destruct (le_dec j n) as [Hjn| Hjn]. {\n    rewrite List_map_nth' with (a := 0). 2: {\n      rewrite seq_length; flia Hj Hjn.\n    }\n    rewrite seq_nth; [ | flia Hi Hin ].\n    rewrite seq_nth; [ cbn | flia Hj Hjn ].\n    unfold δ.\n    rewrite if_eqb_eq_dec.\n    destruct (Nat.eq_dec (i - 1) (j - 1)) as [H| ]; [ | easy ].\n    flia Hi Hj Hij H.\n  }\n  apply Nat.nle_gt in Hjn.\n  apply nth_overflow.\n  rewrite List_map_seq_length.\n  flia Hjn.\n}\napply Nat.nle_gt in Hin.\napply nth_overflow.\nrewrite nth_overflow; [ cbn; flia | ].\nrewrite List_map_seq_length.\nflia Hin.\nQed.\n\nTheorem mat_el_mI_diag : ∀ n i, 1 ≤ i ≤ n → mat_el (mI n) i i = 1%L.\nProof.\nintros * Hin.\nunfold mat_el, mI; cbn.\nrewrite List_map_nth' with (a := 0). 2: {\n  now rewrite seq_length; apply Nat_1_le_sub_lt.\n}\nrewrite List_map_nth' with (a := 0). 2: {\n  now rewrite seq_length; apply Nat_1_le_sub_lt.\n}\nrewrite seq_nth; [ | now apply Nat_1_le_sub_lt ].\nunfold δ.\nnow rewrite Nat.eqb_refl.\nQed.\n\n(* *)\n\nTheorem mat_mul_nrows : ∀ MA MB, mat_nrows (MA * MB) = mat_nrows MA.\nProof.\nintros; cbn.\nnow rewrite List_map_seq_length.\nQed.\n\nTheorem mat_mul_ncols : ∀ MA MB,\n  mat_nrows MA ≠ 0\n  → mat_ncols (MA * MB) = mat_ncols MB.\nProof.\nintros * Hraz; unfold mat_ncols; cbn.\nrewrite (List_map_hd 0). 2: {\n  rewrite seq_length.\n  now apply Nat.neq_0_lt_0.\n}\nnow rewrite map_length, seq_length.\nQed.\n\nTheorem mat_el_mul : ∀ MA MB i j,\n  1 ≤ i ≤ mat_nrows (MA * MB)\n  → 1 ≤ j ≤ mat_ncols (MA * MB)\n  → mat_el (MA * MB) i j =\n    ∑ (k = 1, mat_ncols MA), mat_el MA i k * mat_el MB k j.\nProof.\nintros * Hir Hjc; cbn.\nrewrite mat_mul_nrows in Hir.\nrewrite mat_mul_ncols in Hjc; [ | flia Hir ].\nrewrite (List_map_nth' 0). 2: {\n  now rewrite seq_length; apply Nat_1_le_sub_lt.\n}\nrewrite (List_map_nth' 0). 2: {\n  now rewrite seq_length; apply Nat_1_le_sub_lt.\n}\nrewrite seq_nth; [ | now apply Nat_1_le_sub_lt ].\nrewrite seq_nth; [ | now apply Nat_1_le_sub_lt ].\nrewrite Nat.add_comm, Nat.sub_add; [ | easy ].\nrewrite Nat.add_comm, Nat.sub_add; [ | easy ].\neasy.\nQed.\n\n(* multiplication left and right with identity *)\n\nTheorem mat_mul_1_l {n} : ∀ (M : matrix T),\n  is_correct_matrix M = true\n  → n = mat_nrows M\n  → (mI n * M)%M = M.\nProof.\nintros * HM Hn; subst n.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\napply is_scm_mat_iff in HM.\ndestruct HM as (_, HM).\nunfold \"*\"%M.\nrewrite mI_nrows.\ndestruct M as (ll); cbn in HM |-*.\nf_equal.\nunfold mat_ncols; cbn.\nremember (length (hd [] ll)) as ncols eqn:Hc.\nremember (map _ _) as x.\nrewrite List_map_nth_seq with (d := []); subst x.\nrewrite <- seq_shift.\nrewrite <- seq_shift, map_map.\napply map_ext_in.\nintros i Hi.\nremember (nth i ll []) as la eqn:Hla.\nrewrite List_map_nth_seq with (d := 0%L).\nrewrite (HM la). 2: {\n  rewrite Hla.\n  apply nth_In.\n  now apply in_seq in Hi.\n}\nunfold mat_ncols; cbn.\nrewrite <- Hc.\nrewrite map_map.\napply map_ext_in.\nintros j Hj.\nunfold mat_mul_el.\nrewrite rngl_summation_split3 with (j := S i). 2: {\n  split; [ now apply -> Nat.succ_le_mono | ].\n  apply in_seq in Hi.\n  rewrite mI_ncols; flia Hi.\n}\nrewrite all_0_rngl_summation_0. 2: {\n  intros k Hk.\n  rewrite mat_el_mI_ndiag; [ | flia Hk | flia Hk | flia Hk ].\n  now apply rngl_mul_0_l.\n}\nrewrite rngl_add_0_l.\napply in_seq in Hi.\nrewrite mat_el_mI_diag; [ | flia Hi ].\nrewrite rngl_mul_1_l.\nremember (∑ (k = _, _), _) as x; cbn; subst x.\ndo 2 rewrite Nat.sub_0_r.\nrewrite <- Hla.\nrewrite all_0_rngl_summation_0. 2: {\n  intros k Hk.\n  rewrite mat_el_mI_ndiag; [ | flia Hk | flia Hk | flia Hk ].\n  now apply rngl_mul_0_l.\n}\napply rngl_add_0_r.\nQed.\n\nTheorem mat_mul_1_r {n} : ∀ (M : matrix T),\n  is_correct_matrix M = true\n  → n = mat_ncols M\n  → (M * mI n)%M = M.\nProof.\nintros * HM H; subst n.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\napply is_scm_mat_iff in HM.\ndestruct HM as (_, HM).\nunfold \"*\"%M.\nrewrite mI_ncols.\ndestruct M as (ll); cbn in HM |-*.\nf_equal.\nunfold mat_ncols; cbn.\nremember (length (hd [] ll)) as ncols eqn:Hc.\nremember (map _ _) as x.\nrewrite List_map_nth_seq with (d := []); subst x.\nrewrite <- seq_shift, <- seq_shift, map_map.\napply map_ext_in.\nintros i Hi.\nremember (nth i ll []) as la eqn:Hla.\nrewrite List_map_nth_seq with (d := 0%L).\nrewrite (HM la). 2: {\n  rewrite Hla.\n  apply nth_In.\n  now apply in_seq in Hi.\n}\nunfold mat_ncols; cbn.\nrewrite <- Hc, map_map.\napply map_ext_in.\nintros j Hj.\nunfold mat_mul_el.\nunfold mat_ncols at 1.\ncbn - [ mat_el ].\ndestruct ll as [| lb]; [ easy | ].\ncbn - [ mat_el ].\nrewrite (HM lb (or_introl eq_refl)).\n(* rather use more modern rngl_summation_split3... *)\nrewrite rngl_summation_split with (j := S j). 2: {\n  split; [ now apply -> Nat.succ_le_mono | ].\n  apply -> Nat.succ_le_mono.\n  apply in_seq in Hj.\n  cbn in Hc |-*; rewrite <- Hc.\n  flia Hj.\n}\nrewrite rngl_summation_split_last; [ | now apply -> Nat.succ_le_mono ].\nrewrite all_0_rngl_summation_0. 2: {\n  intros k Hk.\n  rewrite mat_el_mI_ndiag; [ | flia Hk | flia | flia Hk ].\n  now apply rngl_mul_0_r.\n}\nrewrite rngl_add_0_l.\napply in_seq in Hj.\nrewrite mat_el_mI_diag; [ | flia Hj ].\nrewrite rngl_mul_1_r.\nrewrite all_0_rngl_summation_0. 2: {\n  intros k Hk.\n  rewrite mat_el_mI_ndiag; [ | flia Hk | flia | flia Hk ].\n  now apply rngl_mul_0_r.\n}\nrewrite rngl_add_0_r.\nsubst la; cbn.\nnow destruct i, j.\nQed.\n\nTheorem mat_vect_mul_1_l : ∀ n (V : vector T),\n  n = vect_size V\n  → (mI n • V)%M = V.\nProof.\nintros * Hn; subst n.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\napply vector_eq. 2: {\n  now cbn; do 2 rewrite map_length; rewrite seq_length.\n}\ncbn; do 2 rewrite map_length; rewrite seq_length.\nintros i Hi.\nrewrite (List_map_nth' []). 2: {\n  rewrite List_map_seq_length.\n  now apply Nat_1_le_sub_lt.\n}\nrewrite (List_map_nth' 0). 2: {\n  rewrite seq_length.\n  now apply Nat_1_le_sub_lt.\n}\nrewrite seq_nth; [ cbn | now apply Nat_1_le_sub_lt ].\nunfold vect_dot_mul; cbn.\ndestruct V as (l); cbn in Hi |-*.\nrewrite map2_map_l.\ndestruct i; [ easy | ].\nrewrite Nat_sub_succ_1.\nrewrite (List_seq_cut3 i); [ cbn | now apply in_seq ].\nrewrite Nat.sub_0_r.\nrewrite map2_app_l.\nrewrite seq_length.\nerewrite map2_ext_in. 2: {\n  intros j k Hj Hk; apply in_seq in Hj.\n  destruct Hj as (_, Hj); cbn in Hj.\n  rewrite δ_ndiag; [ | flia Hj ].\n  now rewrite rngl_mul_0_l.\n}\nrewrite rngl_summation_list_app.\nrewrite all_0_rngl_summation_list_0. 2: {\n  intros j Hj.\n  apply in_map2_iff in Hj.\n  destruct Hj as (k & Hki & u & v & Hu).\n  easy.\n}\nrewrite rngl_add_0_l.\nremember (skipn i l) as l' eqn:Hl'.\nsymmetry in Hl'.\ndestruct l' as [| a']. {\n  exfalso.\n  revert l Hi Hl'.\n  induction i; intros; [ now cbn in Hl'; subst l | ].\n  destruct l as [| a]; [ easy | ].\n  cbn in Hi, Hl'.\n  apply (IHi l); [ flia Hi | easy ].\n}\ncbn.\nrewrite δ_diag.\nrewrite rngl_mul_1_l.\nerewrite map2_ext_in. 2: {\n  intros j k Hj Hk; apply in_seq in Hj.\n  destruct Hj as (Hj, _).\n  rewrite δ_ndiag; [ | flia Hj ].\n  now rewrite rngl_mul_0_l.\n}\nrewrite rngl_summation_list_cons.\nrewrite all_0_rngl_summation_list_0. 2: {\n  intros j Hj.\n  apply in_map2_iff in Hj.\n  destruct Hj as (k & Hki & u & v & Hu).\n  easy.\n}\nrewrite rngl_add_0_r.\nrevert l Hl' Hi.\ninduction i; intros; [ now cbn in Hl'; subst l | ].\ndestruct l as [| b]; [ easy | ].\ncbn in Hi, Hl' |-*.\napply IHi; [ easy | flia Hi ].\nQed.\n\n(* associativity of multiplication *)\n\nTheorem mat_mul_assoc :\n  ∀ (MA : matrix T) (MB : matrix T) (MC : matrix T),\n  mat_nrows MB ≠ 0\n  → mat_ncols MB ≠ 0\n  → mat_ncols MA = mat_nrows MB\n  → (MA * (MB * MC))%M = ((MA * MB) * MC)%M.\nProof.\nintros * Hrbz Hcbz Hcarb.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\nunfold \"*\"%M.\nf_equal.\nunfold mat_nrows at 5; cbn.\nrewrite List_map_seq_length.\napply map_ext_in.\nintros i Hi.\nunfold mat_ncols at 2; cbn.\nrewrite (List_map_hd 0). 2: {\n  now rewrite seq_length; apply Nat.neq_0_lt_0.\n}\nrewrite List_map_seq_length.\napply map_ext_in.\nintros j Hj.\nmove j before i.\nunfold mat_mul_el.\nunfold mat_ncols at 4.\ncbn.\nrewrite (List_map_hd 0). 2: {\n  rewrite seq_length; apply Nat.neq_0_lt_0.\n  now intros H; rewrite H in Hi.\n}\nrewrite List_map_seq_length.\nrewrite (rngl_summation_shift 1); [ | flia Hcarb Hrbz ].\nrewrite Nat.sub_diag.\nerewrite rngl_summation_eq_compat. 2: {\n  intros k Hk.\n  rewrite List_map_nth' with (a := 0). 2: {\n    rewrite seq_length.\n    rewrite Hcarb in Hk.\n    flia Hrbz Hk.\n  }\n  rewrite List_map_nth' with (a := 0). 2: {\n    rewrite seq_length.\n    apply in_seq in Hj.\n    apply Nat_1_le_sub_lt.\n    flia Hj.\n  }\n  rewrite (rngl_summation_shift 1); [ | flia Hcbz ].\n  rewrite Nat.sub_diag.\n  erewrite rngl_summation_eq_compat. 2: {\n    intros m Hm.\n    rewrite seq_nth; [ | rewrite Hcarb in Hk; flia Hrbz Hk ].\n    rewrite seq_nth. 2: {\n      apply in_seq in Hj.\n      apply Nat_1_le_sub_lt.\n      flia Hj.\n    }\n    easy.\n  }\n  rewrite rngl_mul_summation_distr_l; [ | easy ].\n  erewrite rngl_summation_eq_compat. 2: {\n    intros m Hm.\n    now rewrite rngl_mul_assoc.\n  }\n  rewrite Nat.add_comm, Nat.add_sub, Nat.add_1_r.\n  apply in_seq in Hj.\n  rewrite (Nat.add_comm 1 (j - 1)), Nat.sub_add; [ | easy ].\n  easy.\n}\ncbn.\nsymmetry.\nrewrite (rngl_summation_shift 1); [ | flia Hcbz ].\nrewrite Nat.sub_diag.\nerewrite rngl_summation_eq_compat. 2: {\n  intros k Hk.\n  rewrite Nat.add_comm, Nat.add_sub.\n  rewrite List_map_nth' with (a := 0). 2: {\n    rewrite seq_length.\n    apply in_seq in Hi; flia Hi.\n  }\n  rewrite List_map_nth' with (a := 0). 2: {\n    rewrite seq_length.\n    flia Hcbz Hk.\n  }\n  rewrite (rngl_summation_shift 1); [ | flia Hcarb Hrbz ].\n  rewrite Nat.sub_diag.\n  erewrite rngl_summation_eq_compat. 2: {\n    intros m Hm.\n    rewrite seq_nth; [ | now apply in_seq in Hi; flia Hi ].\n    rewrite seq_nth; [ | flia Hcbz Hk ].\n    easy.\n  }\n  rewrite rngl_mul_summation_distr_r; [ | easy ].\n  apply in_seq in Hi.\n  rewrite Nat.add_comm, Nat.sub_add; [ | easy ].\n  rewrite Nat.add_1_r.\n  easy.\n}\ncbn.\nsymmetry.\napply rngl_summation_summation_list_swap.\nQed.\n\n(* left distributivity of multiplication over addition *)\n\nTheorem mat_mul_add_distr_l :\n  ∀ (MA : matrix T) (MB : matrix T) (MC : matrix T),\n  is_correct_matrix MB = true\n  → is_correct_matrix MC = true\n  → mat_nrows MB ≠ 0\n  → mat_ncols MA = mat_nrows MB\n  → mat_nrows MB = mat_nrows MC\n  → mat_ncols MB = mat_ncols MC\n  → (MA * (MB + MC) = MA * MB + MA * MC)%M.\nProof.\nintros * Hb Hc Hrbz Hcarb Hcrbc Hcbc.\nunfold \"*\"%M, \"+\"%M.\nf_equal; cbn.\nrewrite map2_map_l, map2_map_r, map2_diag.\napply map_ext_in.\nintros i Hi.\nrewrite map2_map_l, map2_map_r, <- Hcbc, map2_diag.\nunfold mat_ncols at 1; cbn.\nrewrite List_hd_nth_0.\nrewrite map2_nth with (a := []) (b := []); cycle 1. {\n  rewrite fold_mat_nrows; flia Hrbz.\n} {\n  rewrite fold_mat_nrows; flia Hrbz Hcrbc.\n}\nrewrite map2_length; cbn.\ndo 2 rewrite <- List_hd_nth_0.\ndo 2 rewrite fold_mat_ncols.\nrewrite <- Hcbc, Nat.min_id.\napply map_ext_in.\nintros j Hj.\nunfold mat_mul_el; cbn.\nrewrite <- rngl_summation_add_distr.\napply rngl_summation_eq_compat.\nintros k Hk.\nrewrite <- rngl_mul_add_distr_l.\nf_equal.\nrewrite map2_nth with (a := []) (b := []); cycle 1. {\n  rewrite fold_mat_nrows.\n  rewrite Hcarb in Hk; flia Hrbz Hk.\n} {\n  rewrite fold_mat_nrows.\n  rewrite Hcarb, Hcrbc in Hk.\n  flia Hrbz Hcrbc Hk.\n}\nrewrite map2_nth with (a := 0%L) (b := 0%L); cycle 1. {\n  apply is_scm_mat_iff in Hb.\n  destruct Hb as (_, Hb).\n  apply in_seq in Hj.\n  rewrite Hb; [ flia Hj | ].\n  apply nth_In.\n  rewrite fold_mat_nrows.\n  rewrite Hcarb in Hk.\n  flia Hrbz Hk.\n} {\n  apply in_seq in Hj.\n  rewrite fold_corr_mat_ncols; [ now rewrite <- Hcbc; flia Hj | easy | ].\n  rewrite <- Hcrbc.\n  rewrite Hcarb in Hk.\n  flia Hrbz Hk.\n}\ndo 2 rewrite fold_mat_el.\napply in_seq in Hj.\nrewrite <- Nat.sub_succ_l; [ | easy ].\nrewrite <- Nat.sub_succ_l; [ | easy ].\nnow do 2 rewrite Nat_sub_succ_1.\nQed.\n\n(* right distributivity of multiplication over addition *)\n\nTheorem mat_mul_add_distr_r :\n  ∀ (MA : matrix T) (MB : matrix T) (MC : matrix T),\n  is_correct_matrix MA = true\n  → is_correct_matrix MB = true\n  → mat_nrows MA ≠ 0\n  → mat_nrows MA = mat_nrows MB\n  → mat_ncols MA = mat_ncols MB\n  → ((MA + MB) * MC = MA * MC + MB * MC)%M.\nProof.\nintros * Ha Hb Hraz Hrarb Hcacb.\nassert (Hcaz : mat_ncols MA ≠ 0). {\n  apply is_scm_mat_iff in Ha.\n  destruct Ha as (Ha, _).\n  intros H; apply Hraz.\n  now apply Ha.\n}\nunfold \"*\"%M, \"+\"%M.\nf_equal; cbn.\nrewrite map2_length.\ndo 2 rewrite fold_mat_nrows.\nrewrite map2_map_l, map2_map_r, <- Hrarb, map2_diag.\nrewrite Nat.min_id.\napply map_ext_in.\nintros i Hi.\nrewrite map2_map_l, map2_map_r, map2_diag.\napply map_ext_in.\nintros j Hj.\nunfold mat_mul_el; cbn.\nrewrite <- Hcacb.\nrewrite <- rngl_summation_add_distr.\nunfold mat_ncols at 1; cbn.\nrewrite List_hd_nth_0.\nrewrite map2_nth with (a := []) (b := []); cycle 1. {\n  rewrite fold_mat_nrows; flia Hraz.\n} {\n  rewrite fold_mat_nrows, <- Hrarb; flia Hraz.\n}\nrewrite map2_length.\ndo 2 rewrite <- List_hd_nth_0.\ndo 2 rewrite fold_mat_ncols.\nrewrite <- Hcacb, Nat.min_id.\napply rngl_summation_eq_compat.\nintros k Hk.\nrewrite map2_nth with (a := []) (b := []); cycle 1. {\n  rewrite fold_mat_nrows.\n  apply in_seq in Hi; flia Hi.\n} {\n  rewrite fold_mat_nrows, <- Hrarb.\n  apply in_seq in Hi; flia Hi.\n}\nrewrite map2_nth with (a := 0%L) (b := 0%L); cycle 1. {\n  apply in_seq in Hi.\n  rewrite fold_corr_mat_ncols; [ flia Hcaz Hk | easy | flia Hi ].\n} {\n  apply in_seq in Hi.\n  rewrite Hrarb in Hi.\n  rewrite fold_corr_mat_ncols; [ | easy | flia Hi ].\n  rewrite <- Hcacb; flia Hcaz Hk.\n}\ndo 2 rewrite fold_mat_el.\napply in_seq in Hi.\nrewrite <- Nat.sub_succ_l; [ | easy ].\nrewrite <- Nat.sub_succ_l; [ | easy ].\ndo 2 rewrite Nat_sub_succ_1.\napply rngl_mul_add_distr_r.\nQed.\n\n(* *)\n\nTheorem mat_mul_scal_l_nrows : ∀ M μ, mat_nrows (μ × M) = mat_nrows M.\nProof. now intros; cbn; rewrite map_length. Qed.\n\nTheorem mat_mul_scal_l_ncols : ∀ M μ, mat_ncols (μ × M) = mat_ncols M.\nProof.\nintros.\nunfold mat_ncols; cbn.\ndestruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]. {\n  unfold mat_nrows in Hrz.\n  apply length_zero_iff_nil in Hrz.\n  now rewrite Hrz.\n}\napply Nat.neq_0_lt_0 in Hrz.\nrewrite (List_map_hd []); [ | now rewrite fold_mat_nrows ].\napply map_length.\nQed.\n\nTheorem is_correct_matrix_mul_scal_l : ∀ M μ,\n  is_correct_matrix M = true\n  → is_correct_matrix (μ × M) = true.\nProof.\nintros * Hm.\napply is_scm_mat_iff in Hm.\napply is_scm_mat_iff.\ndestruct Hm as (Hcr, Hc).\nsplit. {\n  unfold mat_ncols; cbn.\n  rewrite map_length, fold_mat_nrows.\n  intros Hc'.\n  destruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]; [ easy | ].\n  rewrite (List_map_hd []) in Hc'. 2: {\n    rewrite fold_mat_nrows.\n    now apply Nat.neq_0_lt_0 in Hrz.\n  }\n  rewrite map_length in Hc'.\n  rewrite fold_mat_ncols in Hc'.\n  now apply Hcr.\n} {\n  intros la Hla.\n  cbn in Hla.\n  apply in_map_iff in Hla.\n  destruct Hla as (lb & Hla & Hlb).\n  subst la.\n  rewrite map_length.\n  rewrite mat_mul_scal_l_ncols.\n  now apply Hc.\n}\nQed.\n\n(* left distributivity of multiplication by scalar over addition *)\n\nTheorem mat_mul_scal_l_add_distr_r : ∀ a b (M : matrix T),\n  ((a + b)%L × M)%M = (a × M + b × M)%M.\nProof.\nintros.\nunfold \"+\"%M, \"×\"%M.\ncbn; f_equal.\nrewrite map2_map_l, map2_map_r.\nrewrite map2_diag.\napply map_ext_in.\nintros la Hla.\nrewrite map2_map_l, map2_map_r.\nrewrite map2_diag.\napply map_ext_in.\nintros c Hc.\napply rngl_mul_add_distr_r.\nQed.\n\n(* associativity of multiplication by scalar *)\n\nTheorem mat_mul_scal_l_mul_assoc : ∀ a b (M : matrix T),\n  (a × (b × M))%M = ((a * b)%L × M)%M.\nProof.\nintros.\nunfold \"*\"%M, \"×\"%M.\ncbn; f_equal.\nrewrite map_map.\napply map_ext_in.\nintros la Hla.\nrewrite map_map.\napply map_ext_in.\nintros i Hi.\napply rngl_mul_assoc.\nQed.\n\nTheorem mat_mul_scal_l_mul :\n  ∀ a (MA : matrix T) (MB : matrix T),\n  is_correct_matrix MA = true\n  → (a × MA * MB = a × (MA * MB))%M.\nProof.\nintros * Ha.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\nunfold \"*\"%M, \"×\"%M.\ncbn; f_equal.\nrewrite map_length; cbn.\nrewrite fold_mat_nrows.\nrewrite map_map.\napply map_ext_in.\nintros i Hi.\ndestruct (Nat.eq_dec (mat_nrows MA) 0) as [Hraz| Hraz]. {\n  now rewrite Hraz in Hi.\n}\nrewrite map_map.\napply map_ext_in.\nintros j Hj.\nunfold mat_mul_el; cbn.\nunfold mat_ncols at 1; cbn.\nrewrite (List_map_hd []). 2: {\n  now rewrite fold_mat_nrows; apply Nat.neq_0_lt_0.\n}\nrewrite map_length.\nrewrite fold_mat_ncols.\nrewrite rngl_mul_summation_distr_l; [ | easy ].\napply rngl_summation_eq_compat.\nintros k Hk.\nrewrite List_map_nth' with (a := []). 2: {\n  rewrite fold_mat_nrows.\n  apply in_seq in Hi; flia Hi.\n}\nrewrite List_map_nth' with (a := 0%L). 2: {\n  apply is_scm_mat_iff in Ha.\n  destruct Ha as (Harc, Ha).\n  rewrite Ha. 2: {\n    apply nth_In.\n    rewrite fold_mat_nrows.\n    apply in_seq in Hi; flia Hi.\n  }\n  assert (Hcaz : mat_ncols MA ≠ 0). {\n    intros H; apply Hraz.\n    now apply Harc.\n  }\n  flia Hk Hcaz.\n}\nrewrite fold_mat_el.\nsymmetry.\napply in_seq in Hi.\nrewrite <- Nat.sub_succ_l; [ | easy ].\nrewrite <- Nat.sub_succ_l; [ | easy ].\ndo 2 rewrite Nat_sub_succ_1.\napply rngl_mul_assoc.\nQed.\n\nTheorem mat_mul_mul_scal_l :\n  rngl_mul_is_comm = true →\n  ∀ a (MA : matrix T) (MB : matrix T),\n  is_correct_matrix MB = true\n  → mat_ncols MA ≠ 0\n  → mat_ncols MA = mat_nrows MB\n  → (MA * (a × MB) = a × (MA * MB))%M.\nProof.\nintros Hic * Hb Hcaz Hcarb.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\napply Nat.neq_0_lt_0 in Hcaz.\nunfold \"*\"%M, \"×\"%M; cbn.\nf_equal.\nrewrite map_map.\napply map_ext_in.\nintros i Hi.\nunfold mat_ncols at 1; cbn.\nrewrite (List_map_hd []); [ | now rewrite fold_mat_nrows, <- Hcarb ].\nrewrite map_length.\nrewrite fold_mat_ncols.\nrewrite map_map.\napply map_ext_in.\nintros j Hj.\nunfold mat_mul_el; cbn.\nrewrite rngl_mul_summation_distr_l; [ | easy ].\napply rngl_summation_eq_compat.\nintros k Hk.\nrewrite List_map_nth' with (a := []). 2: {\n  rewrite fold_mat_nrows, <- Hcarb.\n  flia Hcaz Hk.\n}\nrewrite List_map_nth' with (a := 0%L). 2: {\n  apply is_scm_mat_iff in Hb.\n  destruct Hb as (Hbzz, Hb).\n  rewrite Hb; [ apply in_seq in Hj; flia Hj | ].\n  apply nth_In.\n  rewrite fold_mat_nrows, <- Hcarb.\n  flia Hcaz Hk.\n}\nrewrite fold_mat_el.\nrewrite rngl_mul_comm; [ | easy ].\nrewrite <- rngl_mul_assoc.\nf_equal.\napply in_seq in Hj.\nrewrite <- Nat.sub_succ_l; [ | easy ].\nrewrite <- Nat.sub_succ_l; [ | easy ].\ndo 2 rewrite Nat_sub_succ_1.\nnow apply rngl_mul_comm.\nQed.\n\nTheorem mat_mul_scal_l_add_distr_l : ∀ a (MA MB : matrix T),\n  (a × (MA + MB) = (a × MA + a × MB))%M.\nProof.\nintros.\nunfold \"+\"%M, \"×\"%M; cbn.\nf_equal.\nrewrite map2_map_l, map2_map_r, map_map2.\napply map2_ext_in.\nrename a into c.\nintros la lb Hla Hlb.\nrewrite map2_map_l, map2_map_r, map_map2.\napply map2_ext_in.\nintros a b Ha Hb.\napply rngl_mul_add_distr_l.\nQed.\n\n(* associativity with multiplication with vector *)\n\nTheorem mat_vect_mul_assoc_as_sums :\n  ∀ (A : matrix T) (B : matrix T) (V : vector T) i,\n  1 ≤ i ≤ mat_nrows A\n  → ∑ (j = 1, mat_ncols A),\n       mat_el A i j *\n       (∑ (k = 1, vect_size V), mat_el B j k * vect_el V k) =\n     ∑ (j = 1, vect_size V),\n       (∑ (k = 1, mat_ncols A), mat_el A i k * mat_el B k j) *\n        vect_el V j.\nProof.\nintros * Hi.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\nerewrite rngl_summation_eq_compat. 2: {\n  intros j Hj.\n  now rewrite rngl_mul_summation_distr_l.\n}\nsymmetry.\nerewrite rngl_summation_eq_compat. 2: {\n  intros j Hj.\n  now rewrite rngl_mul_summation_distr_r.\n}\nsymmetry.\ncbn.\nunfold iter_seq at 1 2.\nrewrite rngl_summation_summation_list_swap.\nrewrite fold_iter_seq.\napply rngl_summation_eq_compat.\nintros j Hj.\napply rngl_summation_eq_compat.\nintros k Hk.\napply rngl_mul_assoc.\nQed.\n\nTheorem mat_vect_mul_assoc :\n  ∀ (A : matrix T) (B : matrix T) (V : vector T),\n  is_correct_matrix A = true\n  → is_correct_matrix B = true\n  → mat_ncols A = mat_nrows B\n  → mat_ncols B = vect_size V\n  → (A • (B • V) = (A * B) • V)%M.\nProof.\nintros * Ha Hb Hcarb Hcbv.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\nunfold \"•\"%M, \"*\"%M; cbn.\nf_equal.\nrewrite map_map.\nrewrite List_map_map_seq with (d := []).\nrewrite fold_mat_nrows.\nsymmetry.\nremember (seq 1 (mat_nrows A)) as x eqn:Hx.\nrewrite <- seq_shift in Hx; subst x.\nrewrite map_map.\nsymmetry.\napply map_ext_in.\nintros i Hi.\nunfold vect_dot_mul; cbn.\nrewrite map2_map_r.\nrewrite map2_map2_seq_l with (d := 0%L).\nrewrite map2_map2_seq_r with (d := []).\napply is_scm_mat_iff in Ha.\ndestruct Ha as (Harc, Ha).\nrewrite Ha. 2: {\n  apply nth_In.\n  rewrite fold_mat_nrows.\n  now apply in_seq in Hi.\n}\nrewrite fold_mat_nrows.\nsymmetry.\nrewrite map2_map2_seq_r with (d := 0%L).\nrewrite fold_vect_size.\nsymmetry.\nrewrite <- Hcarb.\nrewrite map2_diag.\nrewrite rngl_summation_list_map.\nrewrite rngl_summation_seq_summation. 2: {\n  intros H; apply Harc in H.\n  now rewrite H in Hi.\n}\ncbn.\napply is_scm_mat_iff in Hb.\ndestruct Hb as (Hbrc, Hb).\nerewrite rngl_summation_eq_compat. 2: {\n  intros j Hj.\n  rewrite fold_mat_el.\n  unfold vect_dot_mul; cbn.\n  rewrite map2_map2_seq_l with (d := 0%L).\n  rewrite Hb with (l := nth j (mat_list_list B) []). 2: {\n    apply nth_In.\n    rewrite fold_mat_nrows.\n    rewrite <- Hcarb.\n    destruct Hj as (_, Hj).\n    apply Nat.lt_succ_r in Hj.\n    rewrite <- Nat.sub_succ_l in Hj. 2: {\n      apply Nat.le_succ_l.\n      apply Nat.neq_0_lt_0.\n      intros H.\n      apply Harc in H.\n      now rewrite H in Hi.\n    }\n    now rewrite Nat_sub_succ_1 in Hj.\n  }\n  rewrite map2_map2_seq_r with (d := 0%L).\n  rewrite fold_vect_size.\n  rewrite Hcbv.\n  rewrite map2_diag.\n  rewrite rngl_summation_list_map.\n  rewrite rngl_summation_seq_summation. 2: {\n    intros H; rewrite <- Hcbv in H.\n    apply Hbrc in H.\n    rewrite <- Hcarb in H.\n    apply Harc in H.\n    now rewrite H in Hi.\n  }\n  erewrite rngl_summation_eq_compat. 2: {\n    intros k Hk.\n    now rewrite fold_mat_el.\n  }\n  easy.\n}\ncbn.\nrewrite Hcbv.\nrewrite map2_map_l.\nrewrite <- seq_shift.\nrewrite map2_map_l.\nrewrite map2_diag.\nrewrite rngl_summation_list_map.\nrewrite rngl_summation_seq_summation. 2: {\n  intros H; rewrite <- Hcbv in H.\n  apply Hbrc in H.\n  rewrite <- Hcarb in H.\n  apply Harc in H.\n  now rewrite H in Hi.\n}\napply in_seq in Hi.\nrewrite rngl_summation_rshift.\nrewrite <- Nat.sub_succ_l. 2: {\n  destruct (mat_ncols A); [ | flia ].\n  now rewrite Harc in Hi.\n}\nrewrite Nat_sub_succ_1.\nerewrite rngl_summation_eq_compat. 2: {\n  intros j Hj.\n  rewrite rngl_summation_rshift.\n  rewrite <- Nat.sub_succ_l; [ | easy ].\n  rewrite Nat_sub_succ_1.\n  rewrite <- Hcbv.\n  rewrite <- Nat.sub_succ_l. 2: {\n    remember (mat_ncols B) as c eqn:Hc; symmetry in Hc.\n    destruct c; [ exfalso | flia ].\n    rewrite Hbrc in Hcarb; [ | easy ].\n    rewrite Hcarb in Hj; flia Hj.\n  }\n  rewrite Nat_sub_succ_1.\n  erewrite rngl_summation_eq_compat. 2: {\n    intros k Hk.\n    rewrite <- Nat.sub_succ_l; [ | easy ].\n    rewrite Nat_sub_succ_1.\n    easy.\n  }\n  easy.\n}\nrewrite Hcbv.\nrewrite mat_vect_mul_assoc_as_sums; [ | flia Hi ].\nremember (vect_size V) as s eqn:Hs; symmetry in Hs.\ndestruct s. {\n  rewrite rngl_summation_empty; [ | easy ].\n  rewrite rngl_summation_only_one; cbn.\n  rewrite Hbrc in Hcarb; [ | easy ].\n  destruct A as (lla).\n  destruct B as (llb).\n  unfold mat_mul_el; cbn.\n  rewrite Hcarb.\n  rewrite rngl_summation_empty; [ | easy ].\n  symmetry.\n  now apply rngl_mul_0_l.\n}\nrewrite (rngl_summation_shift 1). 2: {\n  split; [ easy | flia ].\n}\nrewrite Nat.sub_diag, Nat.add_0_l, Nat_sub_succ_1.\napply rngl_summation_eq_compat.\nintros j Hj.\nf_equal.\nunfold vect_el.\nnow rewrite Nat.add_comm, Nat.add_sub.\nQed.\n\nTheorem mat_mul_scal_vect_assoc :\n  ∀ a (MA : matrix T) (V : vector T),\n  is_correct_matrix MA = true\n  → mat_ncols MA = vect_size V\n  → (a × (MA • V))%V = ((a × MA) • V)%M.\nProof.\nintros * Ha Hcav.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\nunfold \"×\"%V, \"×\"%M, \"•\"%V; cbn.\nf_equal.\ndo 2 rewrite map_map.\nrewrite List_map_map_seq with (d := []).\nrewrite fold_mat_nrows.\nrewrite List_map_map_seq with (d := []).\nrewrite fold_mat_nrows.\napply map_ext_in.\nintros i Hi.\nunfold vect_dot_mul; cbn.\nrewrite map2_map_l.\nrewrite rngl_mul_summation_list_distr_l; [ | easy ].\nrewrite map2_map2_seq_l with (d := 0%L).\napply is_scm_mat_iff in Ha.\ndestruct Ha as (Harc, Ha).\nrewrite Ha. 2: {\n  apply nth_In.\n  rewrite fold_mat_nrows.\n  now apply in_seq in Hi.\n}\nrewrite map2_map2_seq_r with (d := 0%L).\nrewrite fold_vect_size, Hcav.\nrewrite map2_diag.\nrewrite rngl_summation_list_map.\nrewrite rngl_summation_seq_summation. 2: {\n  rewrite <- Hcav; intros H.\n  apply Harc in H.\n  now rewrite H in Hi.\n}\nerewrite rngl_summation_eq_compat; [ | easy ].\nrewrite map2_map2_seq_l with (d := 0%L).\nrewrite Ha. 2: {\n  apply nth_In.\n  rewrite fold_mat_nrows.\n  now apply in_seq in Hi.\n}\nrewrite map2_map2_seq_r with (d := 0%L).\nrewrite fold_vect_size, Hcav.\nrewrite map2_diag.\nrewrite rngl_summation_list_map.\nrewrite rngl_summation_seq_summation. 2: {\n  rewrite <- Hcav; intros H.\n  apply Harc in H.\n  now rewrite H in Hi.\n}\nsymmetry.\nerewrite rngl_summation_eq_compat; [ | easy ].\nsymmetry.\napply rngl_summation_eq_compat.\nintros j Hj.\napply rngl_mul_assoc.\nQed.\n\nTheorem mat_mul_scal_vect_comm :\n  rngl_mul_is_comm = true →\n  ∀ a (MA : matrix T) V,\n  is_correct_matrix MA = true\n  → mat_ncols MA = vect_size V\n  → (a × (MA • V) = MA • (a × V))%V.\nProof.\nintros Hic * Ha Hcav.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\nunfold \"×\"%V, \"•\"%M; cbn.\nf_equal.\nrewrite map_map.\ndo 2 rewrite List_map_map_seq with (d := []).\nrewrite fold_mat_nrows.\napply map_ext_in.\nintros i Hi.\nunfold vect_dot_mul; cbn.\nrewrite rngl_mul_summation_list_distr_l; [ | easy ].\nrewrite map2_map_r.\nrewrite map2_map2_seq_l with (d := 0%L).\nrewrite map2_map2_seq_r with (d := 0%L).\nrewrite fold_vect_size.\napply is_scm_mat_iff in Ha.\ndestruct Ha as (Harc, Ha).\nrewrite Ha. 2: {\n  apply nth_In.\n  rewrite fold_mat_nrows.\n  now apply in_seq in Hi.\n}\nsymmetry.\nrewrite map2_map2_seq_l with (d := 0%L).\nrewrite map2_map2_seq_r with (d := 0%L).\nrewrite fold_vect_size.\nrewrite Ha. 2: {\n  apply nth_In.\n  rewrite fold_mat_nrows.\n  now apply in_seq in Hi.\n}\nrewrite Hcav.\ndo 2 rewrite map2_diag.\ndo 2 rewrite rngl_summation_list_map.\nassert (Hvz : vect_size V ≠ 0). {\n  intros H; rewrite <- Hcav in H.\n  apply Harc in H.\n  now rewrite H in Hi.\n}\nrewrite rngl_summation_seq_summation; [ | easy ].\nrewrite rngl_summation_seq_summation; [ | easy ].\napply rngl_summation_eq_compat.\nintros j Hj.\ndo 2 rewrite rngl_mul_assoc.\nf_equal.\nnow apply rngl_mul_comm.\nQed.\n\n(* matrix transpose *)\n\nDefinition mat_transp (M : matrix T) : matrix T :=\n  mk_mat\n    (map (λ j, map (λ i, mat_el M i j) (seq 1 (mat_nrows M)))\n       (seq 1 (mat_ncols M))).\n\nNotation \"A ⁺\" := (mat_transp A) (at level 1, format \"A ⁺\") : M_scope.\n\nTheorem fold_mat_transp : ∀ M,\n  mk_mat\n    (map (λ j, map (λ i, mat_el M i j) (seq 1 (mat_nrows M)))\n       (seq 1 (mat_ncols M))) =\n  mat_transp M.\nProof. easy. Qed.\n\nTheorem mat_transp_nrows : ∀ M, mat_nrows M⁺ = mat_ncols M.\nProof.\nintros.\nunfold mat_ncols; cbn.\nnow rewrite map_length, seq_length.\nQed.\n\nTheorem mat_transp_ncols : ∀ M,\n  mat_ncols M⁺ = if mat_ncols M =? 0 then 0 else mat_nrows M.\nProof.\nintros.\nrewrite if_eqb_eq_dec.\ndestruct (Nat.eq_dec (mat_ncols M) 0) as [Hcz| Hcz]. {\n  now unfold mat_ncols; cbn; rewrite Hcz.\n}\napply Nat.neq_0_lt_0 in Hcz.\nunfold mat_ncols; cbn.\nrewrite (List_map_hd 0); [ | now rewrite seq_length ].\nnow rewrite List_map_seq_length.\nQed.\n\nTheorem mat_transp_is_corr : ∀ M,\n  is_correct_matrix M = true\n  → is_correct_matrix M⁺ = true.\nProof.\nintros * Hcm.\napply is_scm_mat_iff in Hcm.\ndestruct Hcm as (H1, H2).\ndestruct (Nat.eq_dec (mat_ncols M) 0) as [Hcz| Hcz]. {\n  specialize (H1 Hcz).\n  unfold mat_transp.\n  now rewrite H1, Hcz.\n}\napply is_scm_mat_iff.\nrewrite mat_transp_ncols.\napply Nat.eqb_neq in Hcz; rewrite Hcz.\napply Nat.eqb_neq in Hcz.\nsplit. {\n  intros Hr.\n  unfold mat_nrows in Hr.\n  unfold mat_ncols in Hcz.\n  apply length_zero_iff_nil in Hr.\n  now rewrite Hr in Hcz.\n} {\n  intros l Hl.\n  unfold mat_transp in Hl; cbn in Hl.\n  apply in_map_iff in Hl.\n  destruct Hl as (j & Hjl & Hj).\n  now rewrite <- Hjl, List_map_seq_length.\n}\nQed.\n\nTheorem mat_mul_is_corr : ∀ A B,\n  is_correct_matrix A = true\n  → is_correct_matrix B = true\n  → mat_nrows B ≠ 0\n  → is_correct_matrix (A * B) = true.\nProof.\nintros * Ha Hb Hbz.\ndestruct (Nat.eq_dec (mat_nrows A) 0) as [Haz| Haz]. {\n  unfold mat_nrows in Haz.\n  apply length_zero_iff_nil in Haz.\n  now destruct A as (lla); cbn in Haz; subst lla.\n}\napply Nat.neq_0_lt_0 in Haz, Hbz.\napply is_scm_mat_iff in Ha.\napply is_scm_mat_iff in Hb.\napply is_scm_mat_iff.\ndestruct Ha as (Hacr & Hac).\ndestruct Hb as (Hbcr & Hbc).\nsplit. {\n  intros Hab.\n  unfold mat_ncols in Hab.\n  cbn in Hab |-*.\n  rewrite List_map_seq_length.\n  rewrite (List_map_hd 0) in Hab; [ | now rewrite seq_length ].\n  rewrite List_map_seq_length in Hab.\n  now rewrite Hbcr in Hbz.\n} {\n  intros lab Hlab.\n  unfold mat_ncols; cbn.\n  rewrite (List_map_hd 0); [ | now rewrite seq_length ].\n  rewrite List_map_seq_length.\n  cbn in Hlab.\n  apply in_map_iff in Hlab.\n  destruct Hlab as (x & Hlab & Hx).\n  now rewrite <- Hlab, List_map_seq_length.\n}\nQed.\n\nTheorem mat_transp_el : ∀ M i j,\n  is_correct_matrix M = true\n  → i ≠ 0\n  → j ≠ 0\n  → mat_el M⁺ i j = mat_el M j i.\nProof.\nintros * Hcm Hiz Hjz.\nunfold mat_el; cbn.\ndestruct (le_dec i (mat_ncols M)) as [Hic| Hic]. 2: {\n  apply Nat.nle_gt in Hic.\n  rewrite nth_overflow. 2: {\n    rewrite nth_overflow; [ easy | ].\n    rewrite List_map_seq_length.\n    flia Hic.\n  }\n  rewrite nth_overflow; [ easy | ].\n  destruct (le_dec j (mat_nrows M)) as [Hjr| Hjr]. {\n    apply is_scm_mat_iff in Hcm.\n    destruct Hcm as (H1, H2).\n    rewrite H2; [ flia Hic | ].\n    apply nth_In; rewrite fold_mat_nrows.\n    flia Hjz Hjr.\n  }\n  apply Nat.nle_gt in Hjr.\n  rewrite nth_overflow; [ easy | ].\n  rewrite fold_mat_nrows.\n  flia Hjz Hjr.\n}\nrewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hiz Hic ].\ndestruct (le_dec j (mat_nrows M)) as [Hjr| Hjr]. {\n  rewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hjz Hjr ].\n  unfold mat_el.\n  rewrite seq_nth; [ cbn | flia Hiz Hic ].\n  rewrite seq_nth; [ cbn | flia Hjz Hjr ].\n  do 2 rewrite Nat.sub_0_r.\n  easy.\n}\napply Nat.nle_gt in Hjr.\nrewrite nth_overflow; [ | rewrite List_map_seq_length; flia Hjr ].\nrewrite nth_overflow; [ easy | ].\ndestruct i; [ easy | cbn ].\nrewrite Nat.sub_0_r.\nrewrite nth_overflow; [ easy | ].\nrewrite fold_mat_nrows; flia Hjz Hjr.\nQed.\n\nTheorem mat_transp_mul :\n  rngl_mul_is_comm = true →\n  ∀ (MA : matrix T) (MB : matrix T),\n  is_correct_matrix MA = true\n  → is_correct_matrix MB = true\n  → mat_nrows MA ≠ 0\n  → mat_nrows MB ≠ 0\n  → mat_ncols MA = mat_nrows MB\n  → ((MA * MB)⁺ = MB⁺ * MA⁺)%M.\nProof.\nintros Hic * Ha Hb Haz Hbz Hcarb.\napply matrix_eq; cycle 1. {\n  apply mat_transp_is_corr.\n  now apply mat_mul_is_corr.\n} {\n  apply mat_mul_is_corr. {\n    now apply mat_transp_is_corr.\n  } {\n    now apply mat_transp_is_corr.\n  }\n  rewrite mat_transp_nrows.\n  intros H.\n  apply is_scm_mat_iff in Ha.\n  destruct Ha as (Hcra, Hcla).\n  now apply Hcra in H.\n} {\n  cbn.\n  unfold mat_ncols; cbn.\n  do 3 rewrite List_map_seq_length.\n  rewrite (List_map_hd 0); [ | now rewrite seq_length; apply Nat.neq_0_lt_0 ].\n  now rewrite List_map_seq_length.\n} {\n  unfold mat_ncols; cbn.\n  do 2 rewrite List_map_seq_length.\n  rewrite (List_map_hd 0). 2: {\n    rewrite seq_length.\n    unfold mat_ncols; cbn.\n    rewrite (List_map_hd 0). 2: {\n      rewrite seq_length.\n      now apply Nat.neq_0_lt_0.\n    }\n    rewrite List_map_seq_length.\n    apply Nat.neq_0_lt_0.\n    intros H.\n    apply is_scm_mat_iff in Hb.\n    now apply Hb in H.\n  }\n  rewrite List_map_seq_length.\n  rewrite (List_map_hd 0). 2: {\n    rewrite seq_length.\n    apply Nat.neq_0_lt_0.\n    intros H.\n    apply is_scm_mat_iff in Hb.\n    now apply Hb in H.\n  }\n  rewrite List_map_seq_length.\n  rewrite mat_transp_ncols.\n  rewrite if_eqb_eq_dec.\n  destruct (Nat.eq_dec _ _) as [Hacz| Hacz]; [ | easy ].\n  apply is_scm_mat_iff in Ha.\n  now apply Ha.\n}\nintros i j Hi Hj.\nrewrite mat_transp_nrows in Hi.\nrewrite mat_transp_el; [ | now apply mat_mul_is_corr | flia Hi | flia Hj ].\nrewrite mat_mul_ncols in Hi; [ | easy ].\nrewrite mat_mul_ncols in Hj; [ | rewrite mat_transp_nrows; flia Hi ].\nrewrite mat_transp_ncols in Hj.\nrewrite if_eqb_eq_dec in Hj.\ndestruct (Nat.eq_dec (mat_ncols MA) 0) as [H1| H1]; [ flia Hj | ].\nrewrite mat_el_mul; cycle 1. {\n  now rewrite mat_mul_nrows.\n} {\n  now rewrite mat_mul_ncols.\n}\nrewrite mat_el_mul; cycle 1. {\n  now rewrite mat_mul_nrows, mat_transp_nrows.\n} {\n  rewrite mat_mul_ncols, mat_transp_ncols. 2: {\n    rewrite mat_transp_nrows; flia Hi.\n  }\n  now apply Nat.eqb_neq in H1; rewrite H1.\n}\nrewrite mat_transp_ncols.\nrewrite if_eqb_eq_dec.\ndestruct (Nat.eq_dec (mat_ncols MB) 0) as [H2| H2]; [ flia Hi H2 | ].\nrewrite <- Hcarb; symmetry.\nerewrite rngl_summation_eq_compat. 2: {\n  intros k Hk.\n  rewrite rngl_mul_comm; [ | easy ].\n  rewrite mat_transp_el; [ | easy | flia Hk | flia Hj ].\n  easy.\n}\ncbn - [ mat_el ].\napply rngl_summation_eq_compat.\nintros k Hk.\nf_equal.\nunfold mat_transp; cbn.\nunfold mat_el.\nrewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hi ].\nrewrite (List_map_nth' 0); [ | rewrite seq_length ]. 2: {\n  rewrite <- Hcarb; flia Hk.\n}\nrewrite seq_nth; [ | flia Hi ].\nrewrite seq_nth; [ | flia Hk Hcarb ].\nrewrite Nat.add_comm, Nat.add_sub.\nrewrite Nat.add_comm, Nat.add_sub.\neasy.\nQed.\n\n(* matrix without row i and column j *)\n\nDefinition subm i j (M : matrix T) :=\n  mk_mat (map (butn (j - 1)) (butn (i - 1) (mat_list_list M))).\n\n(* combinations of submatrix and other operations *)\n\nTheorem mat_nrows_subm : ∀ (M : matrix T) i j,\n  mat_nrows (subm i j M) = mat_nrows M - Nat.b2n (i <=? mat_nrows M).\nProof.\nintros.\ndestruct M as (ll); cbn - [ \"<?\" ].\nrewrite map_length, butn_length.\nunfold Nat.b2n.\nrewrite if_ltb_lt_dec, if_leb_le_dec.\ndestruct (lt_dec _ _) as [H1| H1]. {\n  destruct (le_dec _ _) as [H2| H2]; [ easy | flia H1 H2 ].\n}\ndestruct (le_dec _ _) as [H2| H2]; [ flia H1 H2 | easy ].\nQed.\n\nTheorem mat_ncols_subm : ∀ (M : matrix T) i j,\n  is_correct_matrix M = true\n  → 1 ≤ i ≤ mat_nrows M\n  → 1 ≤ j ≤ mat_ncols M\n  → mat_ncols (subm i j M) = if mat_nrows M =? 1 then 0 else mat_ncols M - 1.\nProof.\nintros * Hcm Hi Hj.\ndestruct M as (ll); cbn in Hi, Hj.\nunfold mat_ncols in Hj |-*; cbn in Hj |-*.\ndestruct i; [ easy | ].\ndestruct j; [ easy | ].\ndestruct Hi as (_, Hi).\ndestruct Hj as (_, Hj).\napply -> Nat.le_succ_l in Hi.\napply -> Nat.le_succ_l in Hj.\ndo 2 rewrite Nat_sub_succ_1.\napply is_scm_mat_iff in Hcm.\nunfold mat_ncols in Hcm; cbn in Hcm.\ndestruct Hcm as (_, Hcl).\ndestruct ll as [| la]; intros; [ easy | ].\ncbn in Hi, Hj |-*.\ncbn - [ In ] in Hcl.\nassert (H : ∀ l, l ∈ ll → length l = length la). {\n  intros l Hl.\n  now apply Hcl; right.\n}\nmove H before Hcl; clear Hcl; rename H into Hcl.\napply Nat.le_succ_l in Hi.\napply Nat.succ_le_mono in Hi.\ndestruct ll as [| lb]. {\n  now apply Nat.le_0_r in Hi; subst i; cbn.\n}\ncbn in Hi |-*.\ndestruct i. {\n  cbn; rewrite butn_length.\n  rewrite Hcl; [ | now left ].\n  now apply Nat.ltb_lt in Hj; rewrite Hj.\n}\napply Nat.succ_le_mono in Hi.\ncbn; rewrite butn_length.\nnow apply Nat.ltb_lt in Hj; rewrite Hj.\nQed.\n\nTheorem is_squ_mat_subm : ∀ (M : matrix T) i j,\n  1 ≤ i ≤ mat_nrows M\n  → 1 ≤ j ≤ mat_nrows M\n  → is_square_matrix M = true\n  → is_square_matrix (subm i j M) = true.\nProof.\nintros * Hi Hj Hm.\napply is_scm_mat_iff.\nspecialize (squ_mat_ncols _ Hm) as Hcm.\ndestruct (Nat.eq_dec (mat_nrows M) 1) as [Hr1| Hr1]. {\n  rewrite Hr1 in Hi, Hj.\n  replace i with 1 by flia Hi.\n  replace j with 1 by flia Hj.\n  cbn.\n  destruct M as (ll); cbn in Hr1 |-*.\n  destruct ll as [| l]; [ easy | ].\n  now destruct ll.\n}\nsplit. {\n  intros Hcs.\n  rewrite <- Hcm in Hj.\n  rewrite mat_ncols_subm in Hcs; [ | | easy | easy ]. 2: {\n    now apply squ_mat_is_corr.\n  }\n  apply Nat.eqb_neq in Hr1; rewrite Hr1 in Hcs.\n  apply Nat.eqb_neq in Hr1.\n  flia Hj Hcm Hr1 Hcs.\n} {\n  intros l Hl.\n  apply is_scm_mat_iff in Hm.\n  destruct Hm as (_ & Hc).\n  clear Hcm Hr1.\n  rewrite mat_nrows_subm.\n  generalize Hi; intros (_, H).\n  apply Nat.leb_le in H; rewrite H; clear H; cbn.\n  destruct M as (ll).\n  cbn in Hc, Hi, Hj |-*.\n  cbn - [ butn ] in Hl.\n  rewrite map_butn in Hl.\n  apply in_butn in Hl.\n  apply in_map_iff in Hl.\n  destruct Hl as (l' & Hjl & Hl).\n  rewrite <- Hjl.\n  rewrite butn_length.\n  unfold Nat.b2n.\n  rewrite if_ltb_lt_dec.\n  destruct (lt_dec _ (length l')) as [Hljl| Hljl]. {\n    f_equal.\n    now apply Hc.\n  }\n  apply Nat.nlt_ge in Hljl.\n  rewrite butn_out in Hjl; [ | easy ].\n  subst l'.\n  rewrite Hc in Hljl; [ | easy ].\n  flia Hj Hljl.\n}\nQed.\n\nTheorem subm_is_corr_mat : ∀ (A : matrix T) i j,\n  mat_ncols A ≠ 1\n  → is_correct_matrix A = true\n  → 1 ≤ i ≤ mat_nrows A\n  → 1 ≤ j ≤ mat_ncols A\n  → is_correct_matrix (subm i j A) = true.\nProof.\nintros * Hc1 Ha Hi Hj.\napply is_scm_mat_iff.\nsplit. {\n  rewrite mat_nrows_subm.\n  generalize Hi; intros (_, H).\n  apply Nat.leb_le in H; rewrite H; clear H; cbn.\n  rewrite mat_ncols_subm; [ | easy | easy | easy ].\n  rewrite if_eqb_eq_dec.\n  destruct (Nat.eq_dec (mat_nrows A) 1) as [Hr1| Hr1]; [ now rewrite Hr1 | ].\n  intros H.\n  flia Hc1 H Hj.\n} {\n  intros l Hl.\n  rewrite mat_ncols_subm; [ | easy | easy | easy ].\n  rewrite if_eqb_eq_dec.\n  destruct (Nat.eq_dec _ _) as [Hr1| Hr1]. {\n    destruct A as (ll).\n    cbn - [ butn ] in *.\n    destruct ll as [| lb]; [ easy | ].\n    destruct ll; [ | easy ].\n    cbn in Hi.\n    now replace i with 1 in Hl by flia Hi.\n  }\n  move Hr1 after Hc1.\n  cbn in Hl.\n  apply in_map_iff in Hl.\n  destruct Hl as (la & Hl & Hla).\n  subst l.\n  rewrite butn_length.\n  unfold Nat.b2n.\n  rewrite if_ltb_lt_dec.\n  apply is_scm_mat_iff in Ha.\n  destruct Ha as (_, Hcl).\n  apply in_butn in Hla.\n  specialize (Hcl _ Hla).\n  destruct (lt_dec _ _) as [Hja| Hja]; [ now rewrite Hcl | ].\n  rewrite Nat.nlt_ge in Hja.\n  rewrite Hcl in Hja.\n  flia Hj Hja.\n}\nQed.\n\nTheorem mat_mul_scal_1_l : ∀ (M : matrix T), (1 × M = M)%M.\nProof.\nintros.\nunfold \"×\"%M.\ndestruct M as (ll).\nf_equal; cbn.\ninduction ll as [| la]; [ easy | cbn ].\nrewrite IHll; f_equal.\ninduction la as [| a]; [ easy | cbn ].\nnow rewrite rngl_mul_1_l, IHla.\nQed.\n\n(* ring of square matrices *)\n\nTheorem smat_nrows : ∀ n (M : square_matrix n T),\n  mat_nrows (sm_mat M) = n.\nProof.\nintros.\ndestruct M as (M & Hmp); cbn.\napply Bool.andb_true_iff in Hmp.\ndestruct Hmp as (Hr & Hmp).\nnow apply Nat.eqb_eq in Hr.\nQed.\n\nTheorem smat_ncols : ∀ n (M : square_matrix n T),\n  mat_ncols (sm_mat M) = n.\nProof.\nintros.\ndestruct M as (M, Hmp); cbn.\napply Bool.andb_true_iff in Hmp.\ndestruct Hmp as (Hr, Hmp).\napply Nat.eqb_eq in Hr.\napply is_scm_mat_iff in Hmp.\ndestruct Hmp as (Hrc, Hc).\ndestruct (Nat.eq_dec n 0) as [Hnz| Hnz]. {\n  move Hnz at top; subst n.\n  unfold mat_ncols.\n  unfold mat_nrows in Hr.\n  apply length_zero_iff_nil in Hr.\n  now rewrite Hr.\n}\nunfold mat_ncols.\nrewrite <- Hr.\napply Hc.\napply List_hd_in.\nunfold mat_nrows in Hr.\nrewrite Hr.\nnow apply Nat.neq_0_lt_0.\nQed.\n\nTheorem mI_is_square_matrix : ∀ n, is_square_matrix (mI n) = true.\nProof.\nintros.\napply is_scm_mat_iff.\ndestruct (Nat.eq_dec n 0) as [Hnz| Hnz]; [ now subst n | ].\napply Nat.neq_0_lt_0 in Hnz.\nsplit. {\n  unfold mat_ncols.\n  cbn; rewrite map_length, seq_length.\n  rewrite (List_map_hd 0); [ | now rewrite seq_length ].\n  now rewrite map_length, seq_length.\n}\nintros la Hla.\ncbn in Hla.\napply in_map_iff in Hla.\ndestruct Hla as (i & Hin & Hi).\nsubst la; cbn.\nnow do 2 rewrite List_map_seq_length.\nQed.\n\nTheorem mI_is_correct_matrix : ∀ n, is_correct_matrix (mI n) = true.\nProof.\nintros.\napply squ_mat_is_corr, mI_is_square_matrix.\nQed.\n\nTheorem mZ_is_correct_matrix : ∀ m n,\n  n ≠ 0\n  → is_correct_matrix (mZ m n) = true.\nProof.\nintros * Hnz.\ndestruct (Nat.eq_dec m 0) as [Hmz| Hmz]; [ now subst m | ].\napply is_scm_mat_iff.\nsplit. {\n  intros Hc.\n  now rewrite mZ_ncols in Hc.\n}\nintros l Hl.\nrewrite mZ_ncols; [ | easy ].\ncbn in Hl.\napply repeat_spec in Hl.\nsubst l.\napply repeat_length.\nQed.\n\nTheorem mat_opp_is_correct : ∀ M,\n  is_correct_matrix M = true\n  → is_correct_matrix (- M) = true.\nProof.\nintros * Hm.\napply is_scm_mat_iff in Hm.\napply is_scm_mat_iff.\ndestruct Hm as (Hcr, Hc).\ndestruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]. {\n  apply eq_mat_nrows_0 in Hrz.\n  unfold is_correct_matrix.\n  unfold mat_ncols, mat_nrows; cbn.\n  now rewrite Hrz; cbn.\n}\napply Nat.neq_0_lt_0 in Hrz.\nunfold is_correct_matrix.\nunfold mat_ncols, mat_nrows; cbn.\nrewrite (List_map_hd []); [ | easy ].\ndo 2 rewrite map_length.\nrewrite fold_mat_nrows, fold_mat_ncols.\nsplit; [ easy | ].\nintros la Hla.\napply in_map_iff in Hla.\ndestruct Hla as (lb & Hla & Hlb); subst la.\nrewrite map_length.\nnow apply Hc.\nQed.\n\nTheorem squ_mat_add_is_squ : ∀ (MA MB : matrix T),\n  is_square_matrix MA = true\n  → is_square_matrix MB = true\n  → is_square_matrix (MA + MB) = true.\nProof.\nintros * Ha Hb.\napply is_scm_mat_iff; cbn.\napply is_scm_mat_iff in Ha.\napply is_scm_mat_iff in Hb.\ndestruct Ha as (Hcra & Hca).\ndestruct Hb as (Hcrb & Hcb).\nsplit. {\n  intros Hcc.\n  rewrite map2_length.\n  do 2 rewrite fold_mat_nrows.\n  unfold mat_ncols in Hcc; cbn in Hcc.\n  destruct (Nat.eq_dec (mat_nrows MA) 0) as [Hraz| Hraz]. {\n    now rewrite Hraz, Nat.min_0_l.\n  }\n  destruct (Nat.eq_dec (mat_nrows MB) 0) as [Hrbz| Hrbz]. {\n    now rewrite Hrbz, Nat.min_0_r.\n  }\n  apply Nat.neq_0_lt_0 in Hraz, Hrbz.\n  rewrite List_hd_nth_0 in Hcc.\n  rewrite map2_nth with (a := []) (b := []) in Hcc; [ | easy | easy ].\n  rewrite map2_length in Hcc.\n  do 2 rewrite <- List_hd_nth_0 in Hcc.\n  do 2 rewrite fold_mat_ncols in Hcc.\n  apply Nat.le_0_r, Nat.min_le in Hcc.\n  destruct Hcc as [Hc| Hc]; apply Nat.le_0_r in Hc. {\n    now rewrite Hcra in Hraz.\n  } {\n    now rewrite Hcrb in Hrbz.\n  }\n} {\n  intros l Hl.\n  apply in_map2_iff in Hl.\n  destruct Hl as (i & Him & a & b & Hl).\n  subst l.\n  do 2 rewrite map2_length.\n  do 2 rewrite fold_mat_nrows in Him |-*.\n  apply Nat.min_glb_lt_iff in Him.\n  rewrite Hca; [ | now apply nth_In; rewrite fold_mat_nrows ].\n  rewrite Hcb; [ | now apply nth_In; rewrite fold_mat_nrows ].\n  easy.\n}\nQed.\n\nTheorem squ_mat_mul_is_squ : ∀ (MA MB : matrix T),\n  is_square_matrix MA = true\n  → is_square_matrix MB = true\n  → mat_nrows MA = mat_nrows MB\n  → is_square_matrix (MA * MB) = true.\nProof.\nintros * Ha Hb Hrab.\napply is_scm_mat_iff; cbn.\nrewrite List_map_seq_length.\nrewrite (squ_mat_ncols MB); [ | easy ].\nsplit. {\n  intros Hcc.\n  unfold mat_ncols in Hcc; cbn in Hcc.\n  rewrite squ_mat_ncols in Hcc; [ | easy ].\n  rewrite <- Hrab in Hcc.\n  apply length_zero_iff_nil in Hcc.\n  destruct (Nat.eq_dec (mat_nrows MA) 0) as [Hrz| Hrz]; [ easy | ].\n  apply Nat.neq_0_lt_0 in Hrz.\n  rewrite (List_map_hd 0) in Hcc; [ | now rewrite seq_length ].\n  apply map_eq_nil in Hcc.\n  now apply List_seq_eq_nil in Hcc.\n} {\n  intros l Hl.\n  apply in_map_iff in Hl.\n  destruct Hl as (i & Hil & Hi).\n  subst l.\n  now rewrite List_map_seq_length.\n}\nQed.\n\nTheorem square_matrix_add_is_square : ∀ n (MA MB : square_matrix n T),\n  is_square_matrix (sm_mat MA + sm_mat MB)%M = true.\nProof.\nintros.\ndestruct MA as (MA & Ha).\ndestruct MB as (MB & Hb); cbn.\napply Bool.andb_true_iff in Ha, Hb.\nnow apply squ_mat_add_is_squ.\nQed.\n\nTheorem square_matrix_mul_is_square : ∀ n (MA MB : square_matrix n T),\n  is_square_matrix (sm_mat MA * sm_mat MB) = true.\nProof.\nintros.\ndestruct MA as (MA & Ha).\ndestruct MB as (MB & Hb); cbn.\napply Bool.andb_true_iff in Ha, Hb.\napply squ_mat_mul_is_squ; [ easy | easy | ].\ndestruct Ha as (Ha, _).\ndestruct Hb as (Hb, _).\napply Nat.eqb_eq in Ha.\napply Nat.eqb_eq in Hb.\ncongruence.\nQed.\n\nTheorem square_matrix_opp_is_square : ∀ n (M : square_matrix n T),\n  is_square_matrix (- sm_mat M)%M = true.\nProof.\nintros.\napply is_scm_mat_iff.\nsplit. {\n  intros Hco; cbn.\n  rewrite map_length.\n  rewrite fold_mat_nrows.\n  rewrite smat_nrows.\n  destruct (Nat.eq_dec n 0) as [Hnz| Hnz]; [ easy | exfalso ].\n  apply Nat.neq_0_lt_0 in Hnz.\n  unfold mat_ncols in Hco.\n  cbn in Hco.\n  apply length_zero_iff_nil in Hco.\n  rewrite (List_map_hd []) in Hco. 2: {\n    now rewrite fold_mat_nrows, smat_nrows.\n  }\n  apply map_eq_nil in Hco.\n  apply (f_equal length) in Hco.\n  rewrite fold_mat_ncols in Hco.\n  rewrite smat_ncols in Hco.\n  now rewrite Hco in Hnz.\n} {\n  intros l Hl.\n  destruct M as (M & Hrc); cbn in Hl |-*.\n  apply Bool.andb_true_iff in Hrc.\n  destruct Hrc as (Hr, Hsm).\n  apply Nat.eqb_eq in Hr.\n  apply is_scm_mat_iff in Hsm.\n  destruct Hsm as (Hrc, Hc).\n  rewrite Hr in Hrc, Hc.\n  rewrite map_length, fold_mat_nrows, Hr.\n  apply in_map_iff in Hl.\n  destruct Hl as (la & Hlm & Hla).\n  subst l.\n  rewrite map_length.\n  now apply Hc.\n}\nQed.\n\nTheorem squ_mat_mul_scal_l_is_squ : ∀ (M : matrix T) μ,\n  is_square_matrix M = true\n  → is_square_matrix (μ × M) = true.\nProof.\nintros * Hm.\napply is_scm_mat_iff in Hm.\napply is_scm_mat_iff.\ndestruct Hm as (Hcr & Hc).\ncbn; rewrite map_length, fold_mat_nrows.\nsplit. {\n  intros H1.\n  destruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]; [ easy | ].\n  apply Nat.neq_0_lt_0 in Hrz.\n  apply Hcr.\n  unfold mat_ncols in H1 |-*; cbn in H1 |-*.\n  rewrite (List_map_hd []) in H1; [ | easy ].\n  now rewrite map_length in H1.\n}\nintros la Hla.\napply in_map_iff in Hla.\ndestruct Hla as (lb & Hla & Hi); subst la.\nrewrite map_length.\nnow apply Hc.\nQed.\n\nTheorem square_matrix_is_correct : ∀ n (M : square_matrix n T),\n  is_correct_matrix (sm_mat M) = true.\nProof.\nintros.\ndestruct M as (M, Hm); cbn.\napply Bool.andb_true_iff in Hm.\ndestruct Hm as (Hr, Hm).\nnow apply squ_mat_is_corr.\nQed.\n\n(*\nTheorem mat_opt_eq_dec :\n  if rngl_has_dec_eq then ∀ MA MB : matrix T, {MA = MB} + {MA ≠ MB}\n  else not_applicable.\nProof.\nremember rngl_has_dec_eq as de eqn:Hde; symmetry in Hde.\ndestruct de; [ | easy ].\nintros MA MB.\ndestruct MA as (lla).\ndestruct MB as (llb).\nspecialize (list_eq_dec (list_eq_dec (rngl_eq_dec Hde)) lla llb) as H1.\ndestruct H1 as [H1| H1]; [ now subst lla; left | ].\nright.\nintros H; apply H1; clear H1.\nnow injection H.\nQed.\n\nTheorem mat_eq_dec :\n  rngl_has_dec_eq = true\n  → ∀ MA MB : matrix T, {MA = MB} + {MA ≠ MB}.\nProof.\nintros * Hde *.\nspecialize mat_opt_eq_dec as H1.\nrewrite Hde in H1.\napply H1.\nQed.\n*)\n\nTheorem mat_add_nrows : ∀ MA MB : matrix T,\n  mat_nrows (MA + MB) = min (mat_nrows MA) (mat_nrows MB).\nProof.\nintros.\nunfold mZ, \"+\"%M, mat_nrows.\ndestruct MA as (lla).\ndestruct MB as (llb); cbn.\napply map2_length.\nQed.\n\nTheorem mat_add_ncols : ∀ MA MB : matrix T,\n  mat_ncols (MA + MB) = min (mat_ncols MA) (mat_ncols MB).\nProof.\nintros.\nunfold mZ, \"+\"%M, mat_ncols.\ndestruct MA as (lla).\ndestruct MB as (llb); cbn.\ndestruct lla as [| la]; [ easy | cbn ].\ndestruct llb as [| lb]; cbn; [ symmetry; apply Nat.min_r; flia | ].\napply map2_length.\nQed.\n\nTheorem mat_el_add : ∀ (MA MB : matrix T) i j,\n  is_correct_matrix MA = true\n  → is_correct_matrix MB = true\n  → 1 ≤ i ≤ mat_nrows MA\n  → 1 ≤ i ≤ mat_nrows MB\n  → 1 ≤ j ≤ mat_ncols MA\n  → 1 ≤ j ≤ mat_ncols MB\n  → mat_el (MA + MB) i j = (mat_el MA i j + mat_el MB i j)%L.\nProof.\nintros * Ha Hb Hia Hib Hja Hjb.\nunfold \"+\"%M; cbn.\nrewrite map2_nth with (a := []) (b := []); cycle 1. {\n  rewrite fold_mat_nrows; flia Hia.\n} {\n  rewrite fold_mat_nrows; flia Hib.\n}\nrewrite map2_nth with (a := 0%L) (b := 0%L); cycle 1. {\n  apply is_scm_mat_iff in Ha.\n  destruct Ha as (Hcra & Hca).\n  rewrite Hca; [ flia Hja | ].\n  apply nth_In.\n  rewrite fold_mat_nrows; flia Hia.\n} {\n  apply is_scm_mat_iff in Hb.\n  destruct Hb as (Hcrb & Hcb).\n  rewrite Hcb; [ flia Hjb | ].\n  apply nth_In.\n  rewrite fold_mat_nrows; flia Hib.\n}\neasy.\nQed.\n\nTheorem List_repeat_as_map : ∀ A (a : A) n,\n  repeat a n = map (λ _, a) (seq 0 n).\nProof.\nintros.\ninduction n; [ easy | cbn ].\nf_equal.\nnow rewrite <- seq_shift, map_map.\nQed.\n\nTheorem mat_vect_mul_0_r : ∀ m n (M : matrix T),\n  m = mat_nrows M\n  → n = mat_ncols M\n  → (M • vect_zero n = vect_zero m)%V.\nProof.\nintros * Hr Hc.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\nsubst m n.\nunfold \"•\"%V, vect_zero; cbn; f_equal.\nunfold vect_dot_mul; cbn.\nrewrite (List_repeat_as_map _ (mat_nrows _)).\ndestruct M as (lla); cbn.\nrewrite (List_map_nth_seq lla) with (d := []) at 1.\nrewrite map_map.\napply map_ext_in.\nintros i Hi.\napply all_0_rngl_summation_list_0.\nintros j Hj.\nunfold mat_ncols in Hj; cbn in Hj.\napply in_map2_iff in Hj.\ndestruct Hj as (k & Hkm & a & b & Hk).\nsubst j.\nrewrite List_nth_repeat; cbn.\nrewrite repeat_length in Hkm.\napply Nat.min_glb_lt_iff in Hkm.\ndestruct (lt_dec k (length (hd [] lla))) as [H| H]; [ | flia Hkm H ].\nnow apply rngl_mul_0_r.\nQed.\n\nNotation \"A ⁺\" := (mat_transp A) (at level 1, format \"A ⁺\") : M_scope.\n\nTheorem mat_subm_transp :\n  ∀ i j (M : matrix T),\n  is_square_matrix M = true\n  → 1 ≤ i ≤ mat_ncols M\n  → 1 ≤ j ≤ mat_nrows M\n  → ((subm j i M)⁺ = subm i j M⁺)%M.\nProof.\nintros * Hsm Hi Hj.\nspecialize (squ_mat_ncols _ Hsm) as Hcr.\ndestruct (Nat.eq_dec (mat_ncols M) 1) as [Hc1| Hc1]. {\n  rewrite Hc1 in Hi.\n  rewrite <- Hcr, Hc1 in Hj.\n  replace i with 1 by flia Hi.\n  replace j with 1 by flia Hj.\n  clear i j Hi Hj.\n  unfold subm, mat_transp.\n  rewrite Nat.sub_diag.\n  cbn - [ butn ].\n  f_equal.\n  rewrite map_length.\n  rewrite butn_length.\n  rewrite fold_mat_nrows, <- Hcr, Hc1.\n  cbn - [ butn ].\n  destruct M as (ll); cbn.\n  destruct ll as [| l]; [ easy | ].\n  cbn in Hc1.\n  destruct ll as [| l']; [ easy | ].\n  cbn.\n  destruct l as [| a]; [ easy | ].\n  destruct l; [ | easy ].\n  cbn in Hcr; flia Hcr.\n}\nassert (Hcm : is_correct_matrix M = true) by now apply squ_mat_is_corr.\nassert (Hcmt : is_correct_matrix M⁺ = true) by now apply mat_transp_is_corr.\nassert (Hit : 1 ≤ i ≤ mat_nrows M⁺) by now rewrite mat_transp_nrows.\nassert (Hjt : 1 ≤ j ≤ mat_ncols M⁺). {\n  rewrite mat_transp_ncols.\n  rewrite if_eqb_eq_dec.\n  destruct (Nat.eq_dec (mat_ncols M) 0) as [H| H]; [ | easy ].\n  flia H Hi.\n}\napply matrix_eq; cycle 1. {\n  apply mat_transp_is_corr, subm_is_corr_mat; try easy.\n} {\n  apply subm_is_corr_mat; [ | easy | easy | easy ].\n  rewrite mat_transp_ncols.\n  rewrite if_eqb_eq_dec.\n  rewrite Hcr in Hc1.\n  now destruct (Nat.eq_dec (mat_ncols M) 0).\n} {\n  rewrite mat_transp_nrows.\n  rewrite mat_nrows_subm.\n  rewrite mat_ncols_subm; [ | easy | easy | easy ].\n  generalize Hc1; intros H.\n  rewrite Hcr in H.\n  apply Nat.eqb_neq in H; rewrite H; clear H.\n  rewrite mat_transp_nrows; cbn.\n  generalize Hi; intros (_, H).\n  now apply Nat.leb_le in H; rewrite H.\n} {\n  rewrite mat_transp_ncols.\n  rewrite mat_ncols_subm; [ | easy | easy | easy ].\n  generalize Hc1; intros H.\n  rewrite Hcr in H.\n  apply Nat.eqb_neq in H; rewrite H; clear H.\n  rewrite if_eqb_eq_dec.\n  destruct (Nat.eq_dec (mat_ncols M - 1) 0) as [H| H]; [ flia Hi H Hc1 | ].\n  clear H.\n  rewrite mat_ncols_subm; [ | easy | easy | easy ].\n  rewrite mat_transp_nrows.\n  generalize Hc1; intros H.\n  apply Nat.eqb_neq in H; rewrite H; clear H.\n  rewrite mat_transp_ncols.\n  rewrite if_eqb_eq_dec.\n  destruct (Nat.eq_dec (mat_ncols M) 0) as [H| H]; [ flia Hi H Hc1 | ].\n  clear H.\n  rewrite mat_nrows_subm.\n  generalize Hj; intros (_, H).\n  now apply Nat.leb_le in H; rewrite H.\n}\nintros u v Hu Hv.\nrewrite mat_transp_el; [ | now apply subm_is_corr_mat | flia Hu | flia Hv ].\nunfold mat_transp; cbn.\nrewrite (List_map_nth' []). 2: {\n  rewrite butn_length.\n  rewrite fold_mat_nrows.\n  rewrite mat_ncols_subm in Hv; [ | easy | easy | easy ].\n  rewrite mat_transp_nrows in Hv.\n  rewrite mat_transp_ncols in Hv.\n  enough (H : v < mat_nrows M). {\n    destruct v; [ easy | ].\n    destruct (mat_nrows M); [ easy | ].\n    rewrite Nat_sub_succ_1.\n    apply Nat.succ_lt_mono in H.\n    unfold Nat.b2n.\n    rewrite if_ltb_lt_dec.\n    destruct (lt_dec (j - 1) (S n)); flia H.\n  }\n  generalize Hc1; intros H.\n  apply Nat.eqb_neq in H; rewrite H in Hv; clear H.\n  rewrite if_eqb_eq_dec in Hv.\n  destruct (Nat.eq_dec (mat_ncols M) 0) as [H| H]; [ flia Hi H | ].\n  flia Hv.\n}\nrewrite (List_map_nth' []). 2: {\n  rewrite butn_length.\n  rewrite List_map_seq_length.\n  rewrite mat_transp_nrows in Hu.\n  rewrite mat_ncols_subm in Hu; [ | easy | easy | easy ].\n  enough (H : u < mat_ncols M). {\n    destruct u; [ easy | ].\n    destruct (mat_ncols M); [ easy | ].\n    rewrite Nat_sub_succ_1.\n    apply Nat.succ_lt_mono in H.\n    unfold Nat.b2n.\n    rewrite if_ltb_lt_dec.\n    destruct (lt_dec (i - 1) (S n)); flia H.\n  }\n  generalize Hc1; intros H.\n  rewrite Hcr in H.\n  apply Nat.eqb_neq in H; rewrite H in Hu; clear H.\n  flia Hu.\n}\ndo 4 rewrite nth_butn.\nrewrite mat_transp_nrows in Hu.\nrewrite mat_ncols_subm in Hu; [ | easy | easy | easy ].\nrewrite mat_ncols_subm in Hv; [ | easy | easy | easy ].\nrewrite mat_transp_nrows in Hv.\nrewrite mat_transp_ncols in Hv.\nassert (H : (mat_nrows M =? 1) = false) by (apply Nat.eqb_neq; congruence).\nrewrite H in Hu; clear H.\nassert (H : (mat_ncols M =? 1) = false) by now apply Nat.eqb_neq.\nrewrite H in Hv; clear H.\nassert (H : (mat_ncols M =? 0) = false) by (apply Nat.eqb_neq; flia Hi).\nrewrite H in Hv; clear H.\nrewrite (List_map_nth' 0). 2: {\n  rewrite seq_length.\n  unfold Nat.b2n; rewrite if_leb_le_dec.\n  destruct (le_dec (i - 1) (u - 1)); flia Hu.\n}\nrewrite (List_map_nth' 0). 2: {\n  rewrite seq_length.\n  unfold Nat.b2n; rewrite if_leb_le_dec.\n  destruct (le_dec (j - 1) (v - 1)); flia Hv.\n}\nrewrite seq_nth. 2: {\n  unfold Nat.b2n; rewrite if_leb_le_dec.\n  destruct (le_dec (j - 1) (v - 1)); flia Hv.\n}\nrewrite seq_nth. 2: {\n  unfold Nat.b2n; rewrite if_leb_le_dec.\n  destruct (le_dec (i - 1) (u - 1)); flia Hu.\n}\nunfold mat_el.\nrewrite Nat.add_assoc, (Nat.add_comm 1 (u - 1)).\nrewrite Nat.sub_add; [ | easy ].\nrewrite Nat.add_sub_swap; [ | easy ].\nf_equal.\nrewrite Nat.add_assoc, (Nat.add_comm 1 (v - 1)).\nrewrite Nat.sub_add; [ | easy ].\nrewrite Nat.add_sub_swap; [ | easy ].\neasy.\nQed.\n\nTheorem mat_transp_is_square : ∀ M,\n  is_square_matrix M = true\n  → is_square_matrix M⁺ = true.\nProof.\nintros * Hsm.\nspecialize (squ_mat_ncols _ Hsm) as Hc.\napply is_scm_mat_iff in Hsm.\napply is_scm_mat_iff.\ndestruct Hsm as (Hcr & Hcl).\ncbn; rewrite List_map_seq_length.\nsplit. {\n  intros Hct.\n  destruct (Nat.eq_dec (mat_ncols M) 0) as [Hcz| Hcz]; [ easy | ].\n  rewrite mat_transp_ncols in Hct.\n  apply Nat.eqb_neq in Hcz; rewrite Hcz in Hct.\n  congruence.\n} {\n  intros l Hl.\n  apply in_map_iff in Hl.\n  destruct Hl as (i & Hi & Hic).\n  now rewrite <- Hi, map_length, seq_length.\n}\nQed.\n\nTheorem mat_transp_involutive : ∀ M,\n  is_correct_matrix M = true\n  → (M⁺⁺)%M = M.\nProof.\nintros * Hcm.\ndestruct (Nat.eq_dec (mat_ncols M) 0) as [Hcz| Hcz]. {\n  destruct M as (ll); cbn.\n  unfold mat_ncols in Hcz; cbn in Hcz.\n  apply length_zero_iff_nil in Hcz.\n  destruct ll as [| l]; [ easy | ].\n  cbn in Hcz; subst l; cbn.\n  unfold mat_transp, mat_ncols; cbn; f_equal.\n  apply is_scm_mat_iff in Hcm.\n  unfold mat_ncols in Hcm; cbn in Hcm.\n  destruct Hcm as (Hcr, _).\n  now specialize (Hcr eq_refl).\n}\ndestruct M as (ll); cbn.\nunfold mat_transp, mat_ncols; cbn; f_equal.\nrewrite (List_map_nth_seq ll []) at 2.\nrewrite List_map_seq_length.\nrewrite (List_map_hd 0). 2: {\n  rewrite seq_length.\n  unfold mat_ncols in Hcz.\n  cbn in Hcz.\n  now apply Nat.neq_0_lt_0.\n}\nrewrite List_map_seq_length.\nrewrite <- seq_shift, map_map.\napply map_ext_in.\nintros i Hi; apply in_seq in Hi.\ndestruct Hi as (_, Hi); cbn in Hi.\nerewrite map_ext_in. 2: {\n  intros j Hj; apply in_seq in Hj.\n  cbn in Hj.\n  rewrite Nat_sub_succ_1.\n  rewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hj ].\n  rewrite (List_map_nth' 0); [ | now rewrite List_map_seq_length ].\n  rewrite seq_shift.\n  rewrite seq_nth; [ | flia Hj ].\n  rewrite seq_nth; [ | easy ].\n  now do 2 rewrite Nat.add_comm, Nat.add_sub.\n}\ndestruct ll as [| l]; [ easy | ].\nunfold mat_ncols in Hcz; cbn in Hcz.\ncbn - [ nth ].\nrewrite (List_map_nth_seq (nth i (l :: ll) []) 0%L) at 1.\napply is_scm_mat_iff in Hcm.\nunfold mat_ncols in Hcm; cbn - [ In ] in Hcm.\ndestruct Hcm as (_, Hcl).\nrewrite <- seq_shift, map_map.\nerewrite map_ext_in. 2: {\n  now intros; rewrite Nat_sub_succ_1.\n}\nsymmetry.\nrewrite Hcl; [ easy | ].\nnow apply nth_In.\nQed.\n\nEnd a.\n\nModule matrix_Notations.\n\nDeclare Scope M_scope.\nDelimit Scope M_scope with M.\n\nArguments Build_square_matrix n%nat [T]%type sm_mat%M.\nArguments is_correct_matrix {T}%type M%M.\nArguments is_square_matrix {T}%type M%M.\nArguments mat_add_0_l {T}%type {ro rp} {m n}%nat M%M.\nArguments mat_add_0_r {T}%type {ro rp} {m n}%nat M%M.\nArguments mat_add_add_swap {T}%type {ro rp} (MA MB MC)%M.\nArguments mat_add_assoc {T}%type {ro rp} (MA MB MC)%M.\nArguments mat_add_comm {T}%type {ro rp} (MA MB)%M.\nArguments mat_add_opp_r {T}%type {ro rp} Hop M%M.\nArguments mat_add_sub {T}%type {ro rp} Hop (MA MB)%M.\nArguments mat_add {T}%type {ro} (MA MB)%M.\nArguments mat_el {T}%type {ro} M%M (i j)%nat.\nArguments mat_list_list {T}%type m%M.\nArguments mat_mul_1_l {T}%type {ro rp} Hop {n}%nat M%M.\nArguments mat_mul_1_r {T}%type {ro rp} Hop {n}%nat M%M.\nArguments mat_mul_add_distr_l {T}%type {ro rp} (MA MB MC)%M.\nArguments mat_mul_assoc {T}%type {ro rp} Hop (MA MB MC)%M.\nArguments mat_mul_el {T}%type {ro} (MA MB)%M (i k)%nat.\nArguments mat_mul_mul_scal_l {T}%type {ro rp} Hop Hic a%L (MA MB)%M.\nArguments mat_mul_scal_1_l {T}%type {ro rp} M%M.\nArguments mat_mul_scal_l_add_distr_l {T}%type {ro rp} a%L (MA MB)%M.\nArguments mat_mul_scal_l_add_distr_r {T}%type {ro rp} (a b)%L M%M.\nArguments mat_mul_scal_l_mul_assoc {T}%type {ro rp} (a b)%L M%M.\nArguments mat_mul_scal_l_mul {T}%type {ro rp} Hop a%L (MA MB)%M.\nArguments mat_mul_scal_l {T ro} s%L M%M.\nArguments mat_mul_scal_vect_assoc {T}%type {ro rp} Hop a%L MA%M V%V.\nArguments mat_mul_scal_vect_comm {T}%type {ro rp} Hop Hic a%L MA%M V%V.\nArguments mat_mul {T}%type {ro} (MA MB)%M.\nArguments mat_mul_vect_r {T ro} M%M V%V.\nArguments mat_ncols {T}%type M%M.\nArguments mat_nrows {T}%type M%M.\nArguments mat_opp {T ro} M%M.\nArguments mat_repl_vect_is_square {T}%type {ro} [k]%nat M%M V%V.\nArguments mat_repl_vect_ncols {T ro} [k]%nat M%M V%V.\nArguments matrix_eq {T ro} (MA MB)%M.\nArguments mat_subm_transp {T ro} [i j]%nat.\nArguments mat_sub {T ro} MA%M MB%M.\nArguments mat_transp_is_square {T ro} M%M.\nArguments mat_transp_mul {T ro rp} _ (MA MB)%M.\nArguments mat_transp_nrows {T}%type {ro} M%M.\nArguments mat_transp {T ro} M%M.\nArguments mat_vect_mul_0_r {T}%type {ro rp} Hop [m n]%nat M%M.\nArguments mat_vect_mul_1_l {T}%type {ro rp} Hop {n}%nat V%V.\nArguments mat_vect_mul_assoc {T}%type {ro rp} Hop (A B)%M V%V.\nArguments mI_any_seq_start {T ro} (sta len)%nat.\nArguments mI_is_correct_matrix {T}%type {ro} n%nat.\nArguments minus_one_pow {T ro}.\nArguments mI {T ro} n%nat.\nArguments mZ {T ro} (m n)%nat.\nArguments squ_mat_ncols {T}%type M%M.\nArguments subm {T} i%nat j%nat M%M.\nArguments δ {T}%type {ro} (i j)%nat.\n\nNotation \"A + B\" := (mat_add A B) : M_scope.\nNotation \"A - B\" := (mat_sub A B) : M_scope.\nNotation \"A * B\" := (mat_mul A B) : M_scope.\nNotation \"μ × A\" := (mat_mul_scal_l μ A) (at level 40) : M_scope.\nNotation \"- A\" := (mat_opp A) : M_scope.\nNotation \"A ⁺\" := (mat_transp A) (at level 1, format \"A ⁺\") : M_scope.\nNotation \"A • V\" := (mat_mul_vect_r A V) (at level 40) : M_scope.\nNotation \"A • V\" := (mat_mul_vect_r A V) (at level 40) : V_scope.\n\nEnd matrix_Notations.\n", "meta": {"author": "roglo", "repo": "coq_sensitivity", "sha": "398291aa86a447f0f35b4918043e94d9eb703c12", "save_path": "github-repos/coq/roglo-coq_sensitivity", "path": "github-repos/coq/roglo-coq_sensitivity/coq_sensitivity-398291aa86a447f0f35b4918043e94d9eb703c12/main/Matrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6635516096922808}}
{"text": "Set Implicit Arguments.\n\nRequire Import Init.Logic.\n\nAxiom LEM: forall A: Prop, A ∨ ~A.\n\n(* Some Corollaries of LEM *)\nSection LEM.\n  Variable P Q R S: Prop.\n\n  Lemma nn_i: P → ~~P.\n  Proof.\n    intros P1 P2.\n    apply (P2 P1).\n  Qed.\n\n  Lemma nn_e: ~~P → P.\n  Proof.\n    intros P1.\n    destruct (LEM P) as [P2 | P2].\n    + apply P2.\n    + apply (bot_e _ (P1 P2)).\n  Qed.\n\n  Lemma imp_e: (P → Q) → ~P ∨ Q.\n  Proof.\n    intros P1.\n    destruct (LEM P) as [P2 | P2].\n    + right.\n      apply (P1 P2).\n    + left.\n      apply P2.\n  Qed.\n\n  Lemma nimp_e: ~(P → Q) → P ∧ ~Q.\n  Proof.\n    intros P1.\n    split.\n    + destruct (LEM P) as [P2 | P2].\n      - apply P2.\n      - apply bot_e.\n        apply P1.\n        intros P3.\n        apply bot_e.\n        apply (P2 P3).\n    + intros P2.\n      apply P1.\n      intros _.\n      apply P2.\n  Qed.\n    \n  Lemma contraposition1: (P → Q) → (~Q → ~P).\n  Proof.\n    intros P1 P2 P3.\n    apply (P2 (P1 P3)).\n  Qed.\n\n  Lemma contraposition2: (~P → Q) → (~Q → P).\n  Proof.\n    intros P1 P2.\n    destruct (LEM P) as [P3 | P3].\n    + apply P3.\n    + apply (bot_e _ (P2 (P1 P3))).\n  Qed.\n\n  Lemma contraposition3: (P → ~Q) → (Q → ~P).\n  Proof.\n    intros P1 P2.\n    destruct (LEM P) as [P3 | P3].\n    + apply (bot_e _ (P1 P3 P2)).\n    + apply P3.\n  Qed.\n\n  Lemma contraposition4: (~P → ~Q) → (Q → P).\n  Proof.\n    intros P1 P2.\n    destruct (LEM P) as [P3 | P3].\n    + apply P3.\n    + apply (bot_e _ (P1 P3 P2)).\n  Qed.\n\n  Lemma not_and_or: ~(P ∧ Q) → (~P ∨ ~Q).\n  Proof.\n    intros P1.\n    destruct (LEM P) as [P2 | P2].\n    + destruct (LEM Q) as [P3 | P3].\n      - apply (bot_e _ (P1 (and_i P2 P3))).\n      - right.\n        apply P3.\n    + left.\n      apply P2.\n  Qed.\n\n  Lemma not_or_and: ~(P ∨ Q) → ~P ∧ ~Q.\n  Proof.\n    intros P1.\n    split.\n    + destruct (LEM P) as [P2 | P2].\n      - destruct (P1 (or_il _ P2)).\n      - apply P2.\n    + destruct (LEM Q) as [P2 | P2].\n      - destruct (P1 (or_ir _ P2)).\n      - apply P2.\n  Qed.\n\n  Lemma and_not_or: ~P ∧ ~Q → ~(P ∨ Q).\n  Proof.\n    intros [P1 P2] [P3 | P3].\n    + apply (P1 P3).\n    + apply (P2 P3).\n  Qed.\n\n  Lemma or_not_and: ~P ∨ ~Q → ~(P ∧ Q).\n  Proof.\n    intros [P1 | P1] [P2 P3].\n    + apply (P1 P2).\n    + apply (P1 P3).\n  Qed.\nEnd LEM.\n\nLemma not_ex_all_not: ∀ₚ P, ~(∃ x, P x) → (∀ x, ~(P x)).\nProof.\n  intros P P1 A P2.\n  apply (P1 (ex_i P A P2)).\nQed.\n\nLemma not_all_ex_not: ∀ₚ P, ~(∀ x, P x) → (∃ x, ~(P x)).\nProof.\n  intros P.\n  apply contraposition2.\n  intros P1 A.\n  apply nn_e.\n  apply (not_ex_all_not _ P1 A).\nQed.\n\nLemma all_not_not_ex: ∀ₚ P, (∀ x, ~(P x)) → ~(∃ x, P x).\nProof.\n  intros P P1 [x P2].\n  apply (P1 x).\n  apply P2.\nQed.\n\nLemma ex_not_not_all: ∀ₚ P, (∃ x, ~(P x)) → ~(∀ x, P x).\nProof.\n  intros P [x P1] P2.\n  apply P1.\n  apply P2.\nQed.\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/Classical.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6635515980169875}}
{"text": "(* From mathcomp Require Import all_ssreflect. *)\nSet Implicit Arguments.\n(* Unset Strict Implicit. *)\n(* Import Prenex Implicits. *)\n\n(* Require Import Ensembles. *)\n\n(* 集合 *)\n(* R(a) ⇔ a ∈ {x ∈ M | R(x)} *)\nDefinition mySet (M: Type) := M -> Prop.\n(* 部分集合 *)\nDefinition belong {M: Type}(A: mySet M)(x: M) :Prop\n := A x.\nNotation \"x ∈ A\" := (belong A x) (at level 11).\n(* 補集合の補集合は元の集合 *)\nAxiom axiom_mySet : forall (M: Type)(A: mySet M),\n forall (x: M), (x ∈ A) \\/ ~(x ∈ A).\n(* 包含関係*)\nDefinition mySub {M} := fun (A B : mySet M) =>\n (forall (x: M), (x ∈ A) -> (x ∈ B)).\nNotation \"A ⊂ B\" := (mySub A B) (at level 11).\n(* 空集合 *)\nDefinition myEmptySet {M: Type} : mySet M :=\n fun _ => False.\n(* 母集合 *)\nDefinition myMotherSet {M: Type} : mySet M :=\n fun _ => True.\n\nSection 包含関係.\nVariable M: Type.\n\nLemma Sub_Mother (A : mySet M) : A ⊂ myMotherSet.\nProof.\n unfold mySub.\n unfold belong.\n unfold myMotherSet.\n intros.\n trivial.\nQed.\n\nLemma Sub_Empty (A : mySet M) : myEmptySet ⊂ A.\nProof. \n unfold mySub.\n unfold belong.\n unfold myEmptySet.\n intros.\n contradiction.\nQed.\n\nLemma rfl_Sub (A :mySet M) : (A ⊂ A).\nProof.\n unfold mySub.\n unfold belong.\n intros.\n assumption. (* trivial *)\nQed.\n\nLemma transitive_Sub (A B C : mySet M) :\n  (A ⊂ B) -> (B ⊂ C) -> (A ⊂ C).\nProof. \nintros h1 h2.\nintros x.\nintros h3.\napply h2.\napply h1.\napply h3.\nQed.\nEnd 包含関係.\n\n(* 集合の等号 *)\nDefinition eqmySet {M: Type} :=\n fun (A B: mySet M) => (A ⊂ B /\\ B ⊂ A).\nAxiom axiom_ExteqmySet : forall {M: Type}(A B: mySet M),\n eqmySet A B -> A = B.\n\nSection 等号.\nVariable Mother: Type.\n\nLemma rfl_eqS (A: mySet Mother) : eqmySet A A.\nProof. \nunfold eqmySet.\nsplit.\napply rfl_Sub.\napply rfl_Sub.\nQed.\n\nLemma sym_eqS (A B : mySet Mother) : eqmySet A B -> eqmySet B A.\nProof.\nunfold eqmySet.\nintros H.\nsplit.\ndestruct H. (* as [H H0] *)\napply H0.\napply H.\nQed.\nEnd 等号.\n\n(* 補集合 *)\nDefinition myComplement {M: Type}(A: mySet M) : mySet M :=\n fun (x : M) => ~(A x).\nNotation \"A ^c\" := (myComplement A)(at level 11).\n(* 和集合 *)\nDefinition myCup {M: Type} (A B: mySet M) : mySet M :=\n fun (x : M) => (x ∈ A) \\/ (x ∈ B).\nNotation \"A ∪ B\" := (myCup A B)(at level 11).  \n\nSection 演算.\nVariable M: Type.\n\nLemma cEmpty_Mother : (@myEmptySet M)^c = myMotherSet.\nProof.\napply axiom_ExteqmySet.\nunfold eqmySet.\nunfold mySub.\nunfold myComplement.\nunfold myMotherSet.\nunfold belong.\nunfold myEmptySet.\nsplit. \nintros x h.\ntrivial.\nintros x.\nintros.\nauto. (* intuition. *)\nQed.\n\nLemma cc_cancel (A : mySet M) : (A^c)^c = A.\nProof.\napply axiom_ExteqmySet.\nunfold eqmySet.\nunfold mySub.\nunfold myComplement.\nsplit.\nintros.\ngeneralize (axiom_mySet A x).\n(* intros. *)\nintuition.\ncontradiction.\n\nintuition.\nintros H0.\ncontradiction.\nQed.\n\nLemma cMother_Empty : (@myMotherSet M)^c = myEmptySet.\nProof.\nrewrite <- cEmpty_Mother.\napply cc_cancel.\nQed.\nEnd 演算.\n\n(* 集合間の写像 *)\nDefinition myMap {M1 M2: Type}\n(A: mySet M1)(B: mySet M2)(f: M1 -> M2) :=\n  (forall (x : M1), (x ∈ A) -> ((f x) ∈ B)).\nNotation \" f ∈Map A \\to B\" := (myMap A B f) (at level 11).\n\nDefinition MapCompo {M1 M2 M3 : Type}\n(f: M2 -> M3)(g: M1 -> M2) : M1 -> M3 := \n  fun (x: M1) => f (g x).\nNotation \"f ・ g\" := (MapCompo f g)(at level 11).\n\n(* \bImage: f(x) *)\nDefinition ImgOf {M1 M2: Type}(f: M1 -> M2)\n{A: mySet M1}{B: mySet M2}\n(_: f ∈Map A \\to B) : mySet M2 :=\n  fun (y: M2) => (exists (x: M1), y = f x /\\ x ∈ A).\n\n(* Injection *)\nDefinition mySetInj {M1 M2: Type}(f: M1 -> M2)\n(A: mySet M1)(B: mySet M2)\n(_: f ∈Map A \\to B) :=\n forall (x y: M1), (x ∈ A) -> (y ∈ A) -> (f x = f y) -> (x = y).\n\n(* Surjection *)\nDefinition mySetSur {M1 M2: Type}(f: M1 -> M2)\n{A: mySet M1}{B: mySet M2}\n(_: f ∈Map A \\to B) :=\n forall (y : M2), (y ∈ B) -> (exists (x : M1), (x ∈ A) -> (f x = y)).\n\n(* Bijection *)\nDefinition mySetBi {M1 M2: Type}(f: M1 -> M2)\n(A: mySet M1)(B: mySet M2)\n(fAB: f ∈Map A \\to B) :=\n  (mySetInj fAB) /\\ (mySetSur fAB).\n\nSection 写像.\nVariable M1 M2 M3: Type.\nVariable f: M2 -> M3.\nVariable g: M1 -> M2.\nVariable A: mySet M1.\nVariable B: mySet M2.\nVariable C: mySet M3.\nHypothesis gAB: g ∈Map A \\to B.\nHypothesis fBC: f ∈Map B \\to C.\n\nLemma transitive_Inj (fgAC: (f ・ g) ∈Map A \\to C) :\nmySetInj fBC -> mySetInj gAB -> mySetInj fgAC.\nProof.\nunfold mySetInj.\nintros.\napply (H0 x y H1 H2).\napply (H (g x)(g y)).\napply gAB.\napply H1.\napply gAB.\napply H2.\napply H3.\nQed.\n\nLemma CompoTrans : (f ・ g) ∈Map A \\to C.\nProof.\nunfold MapCompo.\nunfold myMap.\nintros.\nrevert gAB. (* generalize gAB x H *)\nrevert fBC. (* generalize fBC x H *)\nauto.\nQed.\n\n(* ImSub: Im g ⊂ B *)\nLemma ImSub : (ImgOf gAB) ⊂ B.\nProof.\nunfold mySub.\nunfold belong.\nunfold ImgOf.\nintros.\ndestruct H.\nintuition.\nrewrite H0.\napply gAB.\nassumption.\nQed.\nEnd 写像.", "meta": {"author": "tyvutt", "repo": "Mathematical_Components", "sha": "64a7961d7f78186475f463dc63fe34eaa0799833", "save_path": "github-repos/coq/tyvutt-Mathematical_Components", "path": "github-repos/coq/tyvutt-Mathematical_Components/Mathematical_Components-64a7961d7f78186475f463dc63fe34eaa0799833/mySet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6635258917711173}}
{"text": "\nRequire Export Lambda.\nHint Unfold iff: core.\n\n(* Girard's reducibility candidates: up to system F *)\n\n  Definition CR := term -> Prop.\n\n  (* Weak candidates *)\n  Record weak_cand (X : CR) : Prop := \n    {wk_sn  : forall t, X t -> sn t;\n     wk_red : forall t u, X t -> red t u -> X u;\n     wk_wit : exists w, X w}.\n\n  Definition weak_chain t : CR := fun u => red t u.\n\nLemma weakest_cands :\n  forall t, sn t -> weak_cand (weak_chain t).\nunfold weak_chain.\nsplit; intros.\n eauto using sn_red_sn.\n\n transitivity t0; trivial.\n\n eauto using refl_red.\nQed.\n\n\n  (* The exact definition of is_cand is not used outside this module. *)\n  Record is_cand (X : CR) : Prop := \n    {incl_sn : forall t, X t -> sn t;\n     clos_red : forall t u, X t -> red t u -> X u;\n     clos_exp : forall t, neutral t -> (forall u, red1 t u -> X u) -> X t}. \n\n  Instance is_cand_morph : Proper (pointwise_relation _ iff ==> iff) is_cand.\nProof.\ndo 2 red; intros.\nsplit; destruct 1; split; intros.\n rewrite <- H in H0; auto.\n\n rewrite <- H in H0 |-*; eauto.\n\n rewrite <- H; apply clos_exp0; intros; trivial.\n rewrite H; auto.\n\n rewrite H in H0; auto.\n\n rewrite H in H0 |-*; eauto.\n\n rewrite H; apply clos_exp0; intros; trivial.\n rewrite <- H; auto.\nQed.\n\n\n  Lemma cand_sn : is_cand sn.\nconstructor; intros; auto with coc.\n\napply sn_red_sn with t; auto with coc.\n\nred in |- *; apply Acc_intro; auto with coc.\nQed.\n\n  Hint Resolve  incl_sn cand_sn: coc.\n\n  Lemma var_in_cand : forall n X, is_cand X -> X (Ref n).\nintros.\napply (clos_exp X); auto with coc.\n exact I.\n\n intros.\n inversion H0.\nQed.\n\n  Lemma weaker_cand : forall X, is_cand X -> weak_cand X.\nintros.\ncase H; split; trivial.\nexists (Ref 0).\napply (var_in_cand _ X); trivial.\nQed.\n\n  Lemma sat1_in_cand : forall n X u,\n    is_cand X -> sn u -> X (App (Ref n) u).\ninduction 2; intros.\napply (clos_exp X); trivial.\n exact I.\nintros.\ninversion_clear H2; auto.\ninversion H3.\nQed.\n\n\n  Lemma cand_sat X m u :\n    is_cand X ->\n    boccur 0 m=true \\/ sn u ->\n    X (subst u m) ->\n    X (App (Abs m) u).\nProof.\nintros.\nassert (snu : sn u).\n destruct H0; trivial.\n apply (incl_sn _ H) in H1.\n apply sn_subst_inv_l in H1; trivial.\nclear H0; revert m H1.\n(* induction on (sn u) *)\nelim snu.\nclear u snu; intros u _ IHu; unfold transp in *.\n(* induction on (sn m) *)\nintros m m_in_X.\ngeneralize m_in_X.\ncut (sn m). \n2: apply sn_subst with u; apply (incl_sn _ H); trivial.\nsimple induction 1.\nclear m m_in_X H0; intros m _ IHm m_in_X; unfold transp in *.\n(* by case on the reduction *)\napply (clos_exp _ H). exact I.\nintros x red_redex.\ninversion_clear red_redex; [idtac|inversion_clear H0|idtac].\n(* head-reduction *)\ntrivial.\n(* reduction in body *)\napply IHm; trivial.\napply clos_red with (subst u m); trivial.\nunfold subst; auto with coc.\n(* reduction in arg *)\napply IHu; auto with coc.\napply clos_red with (subst u m); trivial.\nunfold subst; auto with coc.\nQed.\n\n\n  (* equality on CR *)\n\n  Definition eq_cand (X Y:CR) := forall t : term, X t <-> Y t.\n\n  Hint Unfold eq_cand: coc.\n\n  Lemma eq_cand_incl : forall t X Y, eq_cand X Y -> X t -> Y t.\nProof.\nintros.\nelim H with t; auto with coc.\nQed.\n\n(* Intersection of candidates *)\n\n  Definition Inter (X:Type) (F:X->CR) t :=\n    sn t /\\ forall x, F x t.\n\n  Lemma eq_can_Inter :\n    forall X Y (F:X->term->Prop) (G:Y->term->Prop),\n    (forall x, exists y, eq_cand (F x) (G y)) /\\\n    (forall y, exists x, eq_cand (F x) (G y)) ->\n    eq_cand (Inter _ F) (Inter _ G).\nunfold eq_cand, Inter; intros.\ndestruct H.\nsplit; intros.\n destruct H1; split; trivial; intros.\n destruct (H0 x).\n rewrite <- H3; trivial.\n\n destruct H1; split; trivial; intros.\n destruct (H x).\n rewrite H3; trivial.\nQed.\n\n  Lemma is_can_Inter :\n    forall X F, (forall x:X, is_cand (F x)) -> is_cand (Inter X F).\nunfold Inter; intros.\nconstructor.\n destruct 1; trivial.\n\n intros.\n destruct H0.\n split; intros.\n  apply sn_red_sn with t; trivial.\n\n  apply (clos_red _ (H x)) with t; auto.\n\n split; intros.\n  constructor; intros.\n  destruct (H1 y); trivial.\n\n  apply (clos_exp _ (H x)); intros; trivial.\n  destruct (H1 u); trivial.\nQed.  \n\n  Lemma is_can_Inter' :\n    forall X F, (forall x:X, is_cand (fun t => sn t /\\ F x t)) -> is_cand (Inter X F).\nunfold Inter; intros.\nconstructor.\n destruct 1; trivial.\n\n intros.\n destruct H0.\n split; intros.\n  apply sn_red_sn with t; trivial.\n\n  apply (clos_red _ (H x)) with t; auto.\n\n split; intros.\n  constructor; intros.\n  destruct (H1 y); trivial.\n\n  apply (clos_exp _ (H x)); intros; trivial.\n  destruct (H1 u); auto.\nQed.  \n\n  Lemma is_can_weak : forall X,\n    is_cand X -> is_cand (fun t => sn t /\\ X t).\nintros.\ngeneralize H.\napply is_cand_morph; red; intros.\nsplit; intros.\n apply H0.\n\n split; trivial.\n apply (incl_sn X); trivial.\nQed.\n\n(*\n  Definition InterSubset (X:Type) (P:X->Prop) (f:X->CR) :=\n    Inter {x|P x} (fun x => f (proj1_sig x)).\n\n  Definition Neutral := InterSubset _ is_cand (fun C => C).\n\n  Lemma is_cand_neutral : is_cand Neutral.\nAdmitted.\n*)\n\n(* Explicit definition of the CR of neutral terms *)\n  Definition Neu : CR := fun t =>\n    sn t /\\ exists2 u, red t u & nf u /\\ neutral u.\n\nLemma neutral_is_cand : is_cand Neu.\nsplit; intros.\n destruct H; trivial.\n\n destruct H.\n destruct H1.\n split.\n  apply sn_red_sn with t; auto with coc.\n\n  exists x; trivial.\n  destruct H2.\n  elim confluence with (1:=H1) (2:=H0); intros.\n  replace x with x0; trivial.\n  revert H2; elim H4; trivial; intros.\n  rewrite H6 in H7; trivial.\n  elim nf_norm with (2:=H7); trivial.\n\n assert (sn t).\n  constructor; intros.\n  destruct (H0 y); auto.\n split; trivial.\n destruct (red1_dec t).\n  destruct s.\n  specialize H0 with (1:=r).\n  destruct H0.\n  destruct H2.\n  exists x0; trivial.\n  transitivity x; auto with coc.\n\n  exists t; auto with *.\nQed.\n\n(* Completion: work in progress *)\n\nSection Completion.\n\n  Variable P : term -> Prop.\n\n  Definition compl : CR :=\n    fun t => forall C, is_cand C -> (forall u, sn u -> P u -> C u) -> C t.\n\n  Lemma is_can_compl : is_cand compl.\nsplit.\n intros.\n apply (H sn); auto.\n apply cand_sn.\n\n red; intros.\n apply (clos_red C) with t; auto.\n apply (H C); trivial.\n\n red; intros.\n apply (clos_exp C); trivial; intros.\n apply H0; trivial.\nQed.\n\n  Lemma compl_intro : forall t, sn t -> P t -> compl t.\nred; intros; auto.\nQed.\n\n  Lemma compl_elim : forall t,\n    compl t ->\n    (exists2 u, conv t u & compl u /\\ P u) \\/ Neu t.\nintros.\napply (@proj2 (sn t)).\napply H; intros.\n split; intros.\n  destruct H0; trivial.\n\n  destruct H0.\n  split.\n   apply sn_red_sn with t0; trivial.\n\n   destruct H2.\n    left.\n    destruct H2.\n    exists x; trivial.\n    apply trans_conv_conv with t0; auto.\n    apply red_sym_conv; trivial.\n\n    right.\n    apply (clos_red Neu) with t0; trivial.\n    apply neutral_is_cand.\n\n  split.\n   constructor; intros.\n   destruct (H1 y); auto.\n\n   assert ((exists u, red1 t0 u) \\/ normal t0).\n    destruct (red1_dec t0).\n     destruct s as (u,?); left; exists u; trivial.\n     right; red; intros; apply nf_norm; trivial.\n   destruct H2.\n    destruct H2.\n    destruct (H1 x); auto.\n    destruct H4.\n     left.\n     destruct H4.\n     exists x0; trivial.\n     apply trans_conv_conv with x; trivial.\n     apply red_conv; auto with coc.\n\n     right.\n     destruct H4.\n     destruct H5.\n     split.\n      constructor; intros; apply H1; trivial.\n\n      exists x0; trivial.\n      apply red_trans with x; auto.\n      apply one_step_red; auto.\n\n    right.\n    split.\n     constructor; intros.\n     elim (H2 y); trivial.\n\n     exists t0; auto with *.\n     split; trivial.\n     apply nf_sound; trivial.\n\n split; trivial.\n left.\n exists u.\n  constructor.\n\n  split; trivial.\n  red; auto.\nQed.\n\nEnd Completion.\n\n  Lemma eq_can_compl : forall X Y,\n    eq_cand X Y -> eq_cand (compl X) (compl Y).\nunfold eq_cand; simpl; split; intros.\n red; intros.\n apply (H0 C); trivial; intros.\n rewrite H in H4; auto.\n\n red; intros.\n apply (H0 C); trivial; intros.\n rewrite <- H in H4; auto.\nQed.\n\n(* Interpreting non dependent products *)\n\n  Definition Arr (X Y:CR) : CR :=\n    fun t => forall u, X u -> Y (App t u).\n\n  Lemma eq_can_Arr :\n   forall X1 Y1 X2 Y2,\n   eq_cand X1 X2 -> eq_cand Y1 Y2 -> eq_cand (Arr X1 Y1) (Arr X2 Y2).\nunfold eq_cand, Arr; split; intros.\n rewrite <- H0; rewrite <- H in H2; auto.\n rewrite H0; rewrite H in H2; auto.\nQed.\n\n  Lemma weak_cand_Arr : forall (X Y:CR),\n    weak_cand X ->\n    is_cand Y ->\n    is_cand (Arr X Y).\nunfold Arr in |- *; intros X Y Hne Y_cand.\nconstructor.\n intros t app_in_can.\n destruct (wk_wit _ Hne) as (w,?).\n apply subterm_sn with (App t w); auto with coc.\n apply (incl_sn Y); auto with coc.\n\n intros.\n apply (clos_red Y) with (App t u0); auto with coc.\n\n intros t t_neutr clos_exp_t u u_in_X.\n apply (clos_exp Y); auto with coc.\n  exact I.\n\n  generalize u_in_X.\n  assert (u_sn: sn u).\n   apply (wk_sn X); auto with coc.\n  clear u_in_X.\n  elim u_sn.\n  intros v _ v_Hrec v_in_X w red_w.\n  revert t_neutr.\n  inversion_clear red_w; intros; auto with coc.\n   destruct t_neutr.\n\n   apply (clos_exp Y); intros; auto with coc.\n    exact I.\n\n    apply v_Hrec with N2; auto with coc.\n    apply (wk_red X) with v; auto with coc.\nQed.\n\n  Lemma weak_Abs_sound_Arr :\n   forall (X Y:CR) m,\n   (forall t, X t -> sn t) ->\n   is_cand Y ->\n   (forall n, X n -> Y (subst n m)) ->\n   Arr X Y (Abs m).\nunfold Arr in |- *; intros.\napply (clos_exp Y); intros; auto with coc.\n exact I.\n\n apply clos_red with (App (Abs m) u); auto with coc.\n apply (cand_sat Y); auto with coc.\nQed.\n\n\n  Lemma is_cand_Arr :\n   forall X Y, is_cand X -> is_cand Y -> is_cand (Arr X Y).\nintros.\napply weak_cand_Arr; trivial.\napply weaker_cand; trivial.\nQed.\n\n  Lemma Abs_sound_Arr :\n   forall X Y m,\n   is_cand X ->\n   is_cand Y ->\n   (forall n, X n -> Y (subst n m)) ->\n   Arr X Y (Abs m).\nunfold Arr in |- *; intros.\napply (clos_exp Y); intros; auto with coc.\n exact I.\n\n apply clos_red with (App (Abs m) u); auto with coc.\n apply (cand_sat Y); auto with coc.\n right; apply (incl_sn X); auto with coc.\nQed.\n\n\n(* Interpreting non dependent products *)\n\n  Definition Pi (X:CR) (Y:term->CR) : CR :=\n    fun t => forall u u', conv u' u -> X u -> X u' -> Y u' (App t u).\n\n  Lemma eq_can_Pi :\n   forall X1 X2 (Y1 Y2:term->CR),\n   eq_cand X1 X2 ->\n   (forall u, eq_cand (Y1 u) (Y2 u)) ->\n   eq_cand (Pi X1 Y1) (Pi X2 Y2).\nunfold eq_cand, Pi; split; intros.\n rewrite <- H0; rewrite <- H in H3,H4; auto.\n rewrite H0; rewrite H in H3,H4; auto.\nQed.\n\n  Lemma is_cand_Pi : forall X (Y:term->CR),\n   is_cand X ->\n   (forall u, is_cand (Y u)) ->\n   is_cand (Pi X Y).\nunfold Pi in |- *; intros X Y X_can Y_can.\nconstructor.\n intros t app_in_can.\n apply subterm_sn with (App t (Ref 0)); auto with coc.\n apply (incl_sn (Y (Ref 0))); auto with coc.\n apply app_in_can; auto with coc.\n  apply var_in_cand with (X:=X); auto with coc.\n  apply var_in_cand with (X:=X); auto with coc.\n\n intros.\n apply (clos_red (Y u')) with (App t u0); auto with coc.\n\n intros t t_neutr clos_exp_t u u' redu u_in_X u'_in_X.\n apply (clos_exp (Y u')); auto with coc.\n  exact I.\n\n  assert (u_sn: sn u).\n   apply (incl_sn X); auto with coc.\n  revert u' redu u_in_X u'_in_X.\n  elim u_sn.\n  intros v _ v_Hrec u' redu v_in_X u'_in_X w red_w.\n  revert t_neutr.\n  inversion_clear red_w; intros; auto with coc.\n   destruct t_neutr.\n\n   apply (clos_exp (Y u')); intros; auto with coc.\n    exact I.\n\n    apply v_Hrec with N2; eauto with coc.\n    apply (clos_red X) with v; auto with coc.\nQed.\n\n  Lemma Abs_sound_Pi :\n   forall X Y m,\n   is_cand X ->\n   (forall u, is_cand (Y u)) ->\n   (forall n n', X n -> X n' -> conv n' n -> Y n' (subst n m)) ->\n   Pi X Y (Abs m).\nunfold Pi in |- *; intros.\napply (clos_exp (Y u')); intros; auto with coc.\n exact I.\n\n apply clos_red with (App (Abs m) u); auto with coc.\n apply (cand_sat (Y u')); auto with coc.\n right; apply (incl_sn X); auto with coc.\nQed.\n\n\n  (* Union of 2 candidates of reducibility *)\n\n  Definition Union (X Y:CR) : CR := compl (fun t => X t \\/ Y t).\n\n  Lemma eq_can_union : forall X Y X' Y',\n    eq_cand X X' -> eq_cand Y Y' ->\n    eq_cand (Union X Y) (Union X' Y').\nunfold Union; intros.\napply eq_can_compl.\nred; intros.\nred in H, H0.\nrewrite H; rewrite H0; reflexivity.\nQed.\n\n  Lemma is_cand_union : forall X Y, is_cand (Union X Y).\nunfold Union; intros.\napply is_can_compl.\nQed.\n\n Lemma is_cand_union1 : forall (X Y:CR) t,\n   is_cand X -> X t -> Union X Y t.\nred; red; intros.\napply H2; auto.\napply (incl_sn X); trivial.\nQed.\n\n Lemma is_cand_union2 : forall (X Y:CR) t,\n   is_cand Y -> Y t -> Union X Y t.\nred; red; intros.\napply H2; auto.\napply (incl_sn Y); trivial.\nQed.\n\n\n(******************************************************************************)\n\n  Lemma cand_context : forall u u' v,\n    (forall X, is_cand X -> X u -> X u') ->\n    forall X, is_cand X -> X (App u v) -> X (App u' v).\nintros.\nassert (sn v).\n apply subterm_sn with (App u v); auto.\n apply (incl_sn X); trivial.\nassert (Arr (weak_chain v) X u').\n apply H.\n  apply weak_cand_Arr; trivial.\n  apply weakest_cands; trivial.\n\n  red; intros. \n  apply (clos_red X) with (App u v); auto with *.\nred in H3.\napply H3; auto with *.\nQed.\n\n  Lemma cand_sat1 X m u v :\n    is_cand X ->\n    boccur 0 m = true \\/ sn u ->\n    X (App (subst u m) v) ->\n    X (App2 (Abs m) u v).\nintros.\napply cand_context with (X:=X) (u:=subst u m); intros; auto.\napply cand_sat with (X:=X0); trivial.\nQed.\n\n  Lemma cand_sat2 X m u v w :\n    is_cand X ->\n    boccur 0 m = true \\/ sn u ->\n    X (App2 (subst u m) v w) ->\n    X (App2 (App (Abs m) u) v w).\nintros.\napply cand_context with (X:=X) (u:=App (subst u m) v); intros; auto.\napply cand_sat1 with (X:=X0); trivial.\nQed.\n\n  Lemma cand_sat3 X m u v w x :\n    is_cand X ->\n    boccur 0 m = true \\/ sn u ->\n    X (App2 (App (subst u m) v) w x) ->\n    X (App2 (App2 (Abs m) u v) w x).\nintros.\napply cand_context with (X:=X) (u:=App2 (subst u m) v w); intros; auto.\napply cand_sat2 with (X:=X0); trivial.\nQed.\n", "meta": {"author": "barras", "repo": "cic-model", "sha": "dcc38f3104048aa50d230f819085131b16702d3d", "save_path": "github-repos/coq/barras-cic-model", "path": "github-repos/coq/barras-cic-model/cic-model-dcc38f3104048aa50d230f819085131b16702d3d/Can.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637397236823, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6635258588103341}}
{"text": "From mathcomp Require Import all_ssreflect ssralg matrix ssrnum vector reals order.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nModule Type KnuthAxioms.\nSection Dummy.\n\nVariable R : realType.\nDefinition Plane := pair_vectType (regular_vectType R) (regular_vectType R).\nParameter OT : Plane -> Plane -> Plane -> bool.\n\n(*Knuth's axioms are given by the following variables.  But axiom 4 is not used in Jarvis' algorithm and axiom 3 is a property of the data, not of the\n  plane. *)\nAxiom Axiom1 : forall p q r, OT p q r -> OT q r p.\n\nAxiom Axiom2 : forall p q r, OT p q r -> ~ OT p r q.\n\nAxiom Axiom4 : forall p q r t, OT t q r -> OT p t r -> OT p q t -> OT p q r.\n\nAxiom Axiom5 :\n forall t s p q r, OT t s p -> OT t s q -> OT t s r ->\n    OT t p q -> OT t q r -> OT t p r.\n\nLocal Open Scope order_scope.\nAxiom Axiom5' : forall (pivot p q r : Plane),\n  (pivot : R *l R) < p ->\n  (pivot : R *l R) < q ->\n  (pivot : R *l R) < r ->\n  OT pivot p q ->\n  OT pivot q r ->\n  OT pivot p r.\n\nEnd Dummy.\nEnd KnuthAxioms.\n", "meta": {"author": "math-comp", "repo": "trajectories", "sha": "cc6e1298208a93592230f5b4ee3228a024aa03e7", "save_path": "github-repos/coq/math-comp-trajectories", "path": "github-repos/coq/math-comp-trajectories/trajectories-cc6e1298208a93592230f5b4ee3228a024aa03e7/theories/axiomsKnuth.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.6634579432608956}}
{"text": "(* Exercise 31 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\nTheorem exercise_031 : ~(A /\\ (B /\\ C)) -> A -> (B -> ~C).\nProof.\nimp_i a1.\nimp_i a2.\nimp_i a3.\nneg_i (A /\\ B /\\ C) a4.\nhyp a1.\ncon_i.\nhyp a2.\ncon_i.\nhyp a3.\nhyp a4.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop031.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6634175899638092}}
{"text": "Require Import HoTT.\n\nDefinition myinv : forall (A:Type) (x y:A) (p:x=y), y=x.\nintros A x y p.\ninduction p.\nexact idpath.\nDefined.\n\nSection ex_2_1.\n  Context `{Funext}.\n  Definition comp_stmt:=\n    forall (A:Type) (x y z:A), x=y -> y=z -> x=z.\n  Definition comp_pr1: comp_stmt. (* induction on p *)\n    intros A x y z p q.\n    induction p.\n    exact q.\n  Defined.\n  Definition comp_pr2: comp_stmt. (* induction on q *)\n    intros A x y z p q.\n    induction q.\n    exact p.\n  Defined.\n  Definition comp_pr3: comp_stmt. (* induction on p,q *)\n    intros A x y z p q.\n    induction p.\n    induction q.\n    exact idpath.\n  Defined.\n  Definition comp_pr12: comp_pr1 = comp_pr2.\n    unfold comp_pr1, comp_pr2.\n    apply path_forall; intro A.\n    apply path_forall; intro x.\n    apply path_forall; intro y.\n    apply path_forall; intro z.\n    apply path_forall; intro p.\n    induction p.\n    apply path_forall; intro q.\n    induction q.\n    reflexivity.\n  Defined.\n  Definition comp_pr23: comp_pr2 = comp_pr3.\n    unfold comp_pr2, comp_pr3.\n    apply path_forall; intro A.\n    apply path_forall; intro x.\n    apply path_forall; intro y.\n    apply path_forall; intro z.\n    apply path_forall; intro p.\n    induction p.\n    apply path_forall; intro q.\n    induction q.\n    reflexivity.\n  Defined.\n  Definition comp_pr13: comp_pr1 = comp_pr3.\n    unfold comp_pr3, comp_pr1.\n    apply path_forall; intro A.\n    apply path_forall; intro x.\n    apply path_forall; intro y.\n    apply path_forall; intro z.\n    apply path_forall; intro p.\n    induction p.\n    apply path_forall; intro q.\n    induction q.\n    reflexivity.\n  Defined.\nEnd ex_2_1.\n\nSection ex_2_2.\n  Context `{Funext}.\n  Goal (comp_pr12 @ comp_pr23) = comp_pr13.\n    unfold comp_pr12, comp_pr13, comp_pr23.\n    Admitted.\nEnd ex_2_2.\nSection ex_2_5.\n  Definition map236: forall (A B:Type)(x y:A) (p:x=y)(f:A->B),\n    f x = f y -> transport (const B) p (f x) = f y.\n    intros A B x y p f fp.\n    exact (transport_const p (f x) @ fp).\n  Defined.\n  Definition map237 (A B:Type)(x y:A) (p:x=y)(f:A->B)\n    (tp : transport (const B) p (f x) = f y) : f x = f y :=\n      (transport_const p (f x))^ @ tp.\n  Lemma ididq:(forall A (x y:A) (q:x=y), paths (idpath @ q) q).\n    induction q.\n    auto.\n  Defined.\n  Lemma isequiv_map236: forall A B x y p f, IsEquiv (map236 A B x y p f).\n    intros A B x y p f.\nPrint IsEquiv.\n  Check eisretr.\n    refine ({| equiv_inv:=map237 A B x y p f;eisretr:=_; eissect:=_; eisadj:=_ |}).\n\n    intro x0.\n  Admitted.\nEnd ex_2_5.\n\nSection ex_2_6.\n  Goal forall A (x y z:A) (p:x = y), IsEquiv (concat p : y = z -> x = z).\n  intros A x y z p.\n  refine ({| equiv_inv:=concat (p^);eisretr:=_; eissect:=_; eisadj:=_ |}).\n  unfold Sect.\n  induction x0.\n  induction p.\n  simpl.\n  Admitted.\nEnd ex_2_6.\n", "meta": {"author": "koba-e964", "repo": "HoTT-exercise", "sha": "9b0836fc78e1bf3d8d9616c4e69b790498bf3585", "save_path": "github-repos/coq/koba-e964-HoTT-exercise", "path": "github-repos/coq/koba-e964-HoTT-exercise/HoTT-exercise-9b0836fc78e1bf3d8d9616c4e69b790498bf3585/Ex2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927012, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6634152166531431}}
{"text": "Require Import Coq.Reals.Rdefinitions.\nRequire Import Coq.Reals.RIneq.\nRequire Import Logic.Logic.\nRequire Import Logic.ArithFacts.\n\nOpen Scope HP_scope.\nOpen Scope string_scope.\n\n(* The distance traveled starting with velocity\n   v, acceleration a, traveling for time t. *)\nDefinition tdist (v:Term) (a:Term) (t:Term) : Term :=\n  v*t + (/2)%R*a*t^^2.\n\n(* Some useful lemmas about tdist. *)\n\nLemma tdist_incr : forall v1 v2 a1 a2 d1 d2,\n  |-- v1 <= v2 -->> a1 <= a2 -->> d1 <= d2 -->>\n      0 <= a2 -->> 0 <= d1 -->>\n      0 <= tdist v2 a2 d2 -->>\n      tdist v1 a1 d1 <= tdist v2 a2 d2.\nProof.\n  breakAbstraction; simpl; unfold eval_comp; simpl; intros.\n  repeat match goal with\n         | [ _ : context [eval_term ?t ?s1 ?s2] |- _ ]\n           => generalize dependent (eval_term t s1 s2)\n         end; intros;\n  repeat match goal with\n         | [ _ : context [eval_term ?t ?s1 ?s2] |- _ ]\n           => generalize dependent (eval_term t s1 s2)\n         end; intros.\n  match goal with\n    |- (?e <= _)%R\n    => destruct (Rle_dec 0 e)\n  end; solve_linear.\n  destruct H4;\n    repeat match goal with\n           | [ H : @eq R _ _ |- _ ] =>\n             rewrite <- H\n           end; solve_linear.\n  apply Rle_trans with (r2:=((r3 + /2*r2*r0)*r0)%R);\n    solve_linear.\n  apply Rle_trans with (r2:=((r1 + /2*r*r4)*r4)%R);\n    solve_linear.\n  apply Rmult_le_compat; solve_linear.\n  - eapply Rmult_le_lt_0; eauto; solve_linear.\n  - solve_nonlinear.\nQed.\n\nLemma tdist_vel_neg : forall v a t,\n  |-- 0 <= t -->> v <= 0 -->> v + a*t <= 0 -->>\n     tdist v a t <= 0.\nProof. solve_nonlinear. Qed.\n\nLemma tdist_neg : forall v1 v2 a1 a2 d1 d2,\n  |-- v1 <= v2 -->> a1 <= a2 -->> d1 <= d2 -->>\n     0 <= a2 -->> 0 <= d1 -->>\n     tdist v2 a2 d2 <= 0 -->>\n     tdist v1 a1 d1 <= 0.\nProof.\n  breakAbstraction; simpl; unfold eval_comp; simpl; intros.\n  repeat match goal with\n           | [ _ : context [eval_term ?t ?s1 ?s2] |- _ ]\n             => generalize dependent (eval_term t s1 s2)\n         end; intros;\n  repeat match goal with\n           | [ _ : context [eval_term ?t ?s1 ?s2] |- _ ]\n             => generalize dependent (eval_term t s1 s2)\n           end; intros.\n  match goal with\n      |- (?e <= _)%R\n      => destruct (Rle_dec 0 e)\n  end; solve_linear.\n  destruct H4;\n    repeat match goal with\n             | [ H : @eq R _ _ |- _ ] =>\n               rewrite <- H\n           end; solve_linear.\n  apply Rle_trans with (r2:=((r3 + /2*r2*r0)*r0)%R);\n    solve_linear.\n  apply Rle_trans with (r2:=((r1 + /2*r*r4)*r4)%R);\n    solve_linear.\n  apply Rmult_le_compat; solve_linear.\n  - eapply Rmult_le_lt_0; eauto; solve_linear.\n  - solve_nonlinear.\nQed.\n\nLemma tdist_pos :\n  forall v a t,\n    |-- 0 <= v -->>\n        0 <= a -->>\n        0 <= t -->>\n        0 <= tdist v a t.\nProof. solve_nonlinear. Qed.\n\nLemma tdist_incr_acc :\n  forall a1 a2 v t,\n    |-- a1 <= a2 -->>\n        tdist v a1 t <= tdist v a2 t.\nProof. solve_nonlinear. Qed.\n\n(* Generic parameters of the height shims. *)\nModule Type SdistParams.\n\n  (* Our breaking acceleration. *)\n  Variable amin : R.\n  Hypothesis amin_lt_0 : (amin < 0)%R.\n\nEnd SdistParams.\n\n(* Definitions for implementing the height shims\n   in the source language. *)\nModule SdistUtil (Import Params : SdistParams).\n\n  (* The distance traveled before stopping when\n     applying acceleration amin, starting with\n     velocity v. *)\n  Definition sdist (v:Term) : Term :=\n    (v^^2)*(--(/2)%R)*(/Params.amin)%R.\n\n  (* Some useful lemmas about sdist. *)\n\n  Lemma tdist_sdist_incr : forall v1 v2 a1 a2 d1 d2,\n      |-- v1 <= v2 -->> a1 <= a2 -->> d1 <= d2 -->>\n          0 <= a2 -->> 0 <= d1 -->>\n          0 <= v1 + a1*d1 -->>\n          tdist v1 a1 d1 + sdist (v1 + a1*d1) <=\n          tdist v2 a2 d2 + sdist (v2 + a2*d2).\n  Proof.\n    pose proof Params.amin_lt_0.\n    breakAbstraction; unfold eval_comp; simpl; intros.\n    repeat match goal with\n             | [ _ : context [eval_term ?t ?s1 ?s2] |- _ ]\n               => generalize dependent (eval_term t s1 s2)\n           end; intros;\n    repeat match goal with\n             | [ _ : context [eval_term ?t ?s1 ?s2] |- _ ]\n               => generalize dependent (eval_term t s1 s2)\n           end; intros.\n    apply Rplus_le_algebra.\n    apply Rmult_neg_le_algebra with (r2:=Params.amin);\n      auto.\n    rewrite Rminus_0_l.\n    apply Rmult_pos_ge_algebra with (r2:=(2)%R);\n      solve_linear.\n    R_simplify; simpl; solve_linear.\n    solve_nonlinear.\n  Qed.\n\n  Lemma sdist_tdist : forall v t,\n    |-- tdist v Params.amin t <= sdist v.\n  Proof.\n    pose proof Params.amin_lt_0.\n    breakAbstraction; simpl; unfold eval_comp; simpl;\n    intros.\n    apply Rplus_le_algebra.\n    apply Rmult_neg_le_algebra with (r2:=Params.amin);\n      auto.\n    apply Rmult_neg_ge_algebra with (r2:=(-4)%R);\n      solve_linear.\n    R_simplify; solve_linear.\n    solve_nonlinear.\n  Qed.\n\n  Lemma sdist_tdist_tdist : forall v t,\n    |-- tdist v Params.amin t + sdist (v + Params.amin*t) <= sdist v.\n  Proof.\n    pose proof Params.amin_lt_0.\n    breakAbstraction; simpl; unfold eval_comp; simpl;\n    intros.\n    apply Rplus_le_algebra.\n    apply Rmult_neg_le_algebra with (r2:=Params.amin);\n      auto.\n    apply Rmult_neg_ge_algebra with (r2:=(-4)%R);\n      solve_linear.\n    R_simplify; solve_linear.\n  Qed.\n\n  Lemma sdist_incr : forall v1 v2,\n    |-- 0 <= v1 <= v2 -->>\n        sdist v1 <= sdist v2.\n  Proof.\n    pose proof Params.amin_lt_0.\n    breakAbstraction; simpl; unfold eval_comp; simpl;\n    intros. do 2 rewrite (Rmult_assoc _ (0 - / 2) (/ Params.amin))%R.\n    apply Rmult_le_compat; solve_linear.\n    - apply Rmult_0_le; solve_linear.\n    - assert (/ Params.amin < 0)%R by solve_linear.\n      solve_linear.\n    - apply Rmult_le_compat; solve_linear.\n  Qed.\n\n  Lemma sdist_gt_0 :\n    forall v, |-- 0 <= sdist v.\n  Proof.\n    breakAbstraction. intros.\n    pose proof Params.amin_lt_0.\n    assert (/Params.amin < 0)%R by solve_linear.\n    assert (0 - / 2 < 0)%R by solve_linear.\n    generalize dependent (/Params.amin)%R.\n    generalize dependent (0 - / 2)%R.\n    clear H0. solve_nonlinear.\n  Qed.\n\nEnd SdistUtil.\n", "meta": {"author": "dricketts", "repo": "quadcopter", "sha": "62bb21915612a141e1ffabc73df3dc2d931c54ce", "save_path": "github-repos/coq/dricketts-quadcopter", "path": "github-repos/coq/dricketts-quadcopter/quadcopter-62bb21915612a141e1ffabc73df3dc2d931c54ce/examples/UtilPosition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314707995591, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6634152053470633}}
{"text": "(* This file is part of the Linear Logic formalization in Coq:\nhttps://github.com/brunofx86/LL *)\n\n(** ** Syntax of Linear Logic \n\nFormulas in LL are build from the following syntax\n\n<<\nF:= A | A ^ | ⊤ | ⊥ | 0 | 1 | F ** F | F $ F | F ⊕ F | F & F | ! F | ? F \n    | E{ FX} | F{ FX}\n>>\n\nwhere \n - [A] is an atom. \n - [A ^] is the negation of the atom [A].\n - [⊤,⊥,0,1] are the units\n - [F ** F] is multiplicative conjunction (tensor)\n - [F $ F] is multiplicative disjunction (par)\n - [F & F] is additive conjunction (oplus)\n - [F ⊕ F] is additive disjunction (oplus)\n - [!, ?] are the exponentials. \n - [E {FX}] existential quantifier\n - [F {FX}] universal quantifier\n\nThe usual dualities, moving negation inwards,  can be computed by [Dual_LExp] (notation [A°]). \n\nThe linear implication [F -o F] is defined as [A° $ B]. \n\n\nThe weight (or complexity) of a formula can be obtained via [Lexp_weight]. \n\nThis file also defines the polarity of formulas following Andreoli's focused system (https://www.cs.cmu.edu/~fp/courses/15816-s12/misc/andreoli92jlc.pdf). Many lemmas on polarities are proved in Section [Polarities].\n\n *)\n\nRequire Export Bool.\nRequire Export Arith.\nRequire Export Nat.\nRequire Import AuxResults.\nRequire Export Multisets.\nRequire Export Coq.Relations.Relations.\nRequire Export Coq.Classes.Morphisms.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Arith.EqNat.\nRequire Import StrongInduction.\nRequire Export Eqset.\nExport ListNotations.\nSet Implicit Arguments.\n\nModule Syntax_LL (DT : Eqset_dec_pol).\n  Export DT.\n  \n\n  (** ** Parametric HOAS\n      Take a look on #< a href=\"http://adam.chlipala.net/cpdt/html/Hoas.html\">Library Hoas</a>#. \n   *)\n  Section Sec_lExp.\n    Variable T : Type. (* Parametric HOAS *)\n\n    Inductive term  :=\n    |var (t: T) (* variables *)\n    |cte (e:A) (* constants from the domain DT.A *)\n    |fc1 (n:nat) (t: term) (* family of functions of 1 argument *)\n    |fc2 (n:nat) (t1 t2: term). (* family of functions of 2 argument *)\n    \n    Inductive aprop := (* atomic propositions *)\n    | a0 : nat -> aprop (* 0-ary predicates *)\n    | a1 : nat -> term -> aprop (* unary predicates *)\n    | a2 : nat -> term -> term -> aprop. (* binary predicates *)\n    \n    Inductive lexp  :=\n    | atom (a :aprop) (* atoms *)\n    | perp (a: aprop) (* negated atoms *)\n    | top | bot | zero | one  (* constants *)\n    | tensor (F G : lexp)\n    | par    (F G : lexp)\n    | plus   (F G : lexp)\n    | witH   (F G : lexp)\n    | bang   (F : lexp)\n    | quest  (F : lexp) \n    | ex     (f : T ->lexp) (* quantifiers *)\n    | fx     (f : T ->lexp) .\n  End Sec_lExp.\n  \n  (***** Avoiding The parameter T ***********)\n  Arguments var [T].   Arguments cte [T].\n  Arguments fc1 [T].   Arguments fc2 [T].\n  Arguments a0 [T]. Arguments a1 [T]. Arguments a2 [T]. \n  Arguments atom [T]. Arguments perp [T].\n  Arguments top [T]. Arguments one [T]. Arguments bot [T]. Arguments zero [T].\n  Arguments tensor [T]. Arguments par [T]. Arguments plus [T]. Arguments witH [T].\n  Arguments bang [T]. Arguments quest [T].\n  Arguments ex [T]. Arguments fx [T].\n  (*****************************************)\n\n  (**************************************************)\n  (* Types for lexp *)\n  (* all of them closed terms (forall T:Type ... ) *)\n  (**************************************************)\n  Definition Term := forall T:Type,  term T. (* type for terms *)\n  Definition AProp := forall T:Type, aprop T. (* type for atomic propositions *)\n  Definition Lexp := forall T:Type, lexp T. (* Type for formulas *)\n  Definition Subs := forall T:Type,  T -> lexp T. (* Type for substitutions *)\n  Definition SubsL := list Subs. (* Type for substitutions on lists *)\n\n  (* Useful Constructors (poly version of the connectives) *)\n  Definition Cte (t : A) : Term := fun _ => cte t.\n  Definition FC1 (n:nat) (t:Term): Term := fun _ => fc1 n (t _).\n  Definition FC2 (n:nat) (t t':Term): Term := fun _ => fc2 n (t _) (t' _).\n  Definition A0 (n : nat) : AProp := fun _ => a0 n.\n  Definition A1 (n : nat) (t:Term) : AProp := fun _ => a1 n (t _).\n  Definition A2 (n : nat) (t t':Term) : AProp := fun _ => a2 n (t _) (t' _).\n  Definition Atom  (P: AProp) :Lexp :=  fun _ => atom (P _).\n  Definition Perp  (P: AProp) :Lexp :=  fun _ => perp(P _). \n  Definition Top   :Lexp := fun _ => top .\n  Definition Bot   :Lexp := fun _ => bot.\n  Definition One   :Lexp := fun _ => one.\n  Definition Zero   :Lexp := fun _ => zero .\n  Definition Tensor  (F G: Lexp) :Lexp :=  fun _ => tensor (F _) (G _).\n  Definition Par  (F G: Lexp) :Lexp :=  fun _  => par (F _) (G _).\n  Definition Plus  (F G: Lexp) :Lexp :=  fun _ => plus (F _) (G _).\n  Definition With  (F G: Lexp) :Lexp :=  fun _ => witH (F _) (G _).\n  Definition Bang  (F: Lexp) :Lexp :=  fun _ => bang (F _ ).\n  Definition Quest  (F: Lexp) :Lexp :=  fun _ => quest (F _ ).\n  Definition Ex  (Fx : Subs) : Lexp := fun _ => ex (Fx _).\n  Definition Fx  (Fx : Subs) : Lexp := fun _ => fx (Fx _).\n\n  (** Closed Terms *)\n  Inductive ClosedT : Term -> Prop :=\n  | cl_cte: forall C, ClosedT (Cte C)\n  | cl_fc1: forall n t1, ClosedT t1 -> ClosedT (FC1 n t1)\n  | cl_fc2: forall n t1 t2, ClosedT t1 -> ClosedT t2 -> ClosedT (FC2 n t1 t2).\n  \n  (** Closed Atomic Propositions *)\n  Inductive ClosedA : AProp -> Prop :=\n  | cl_a0 : forall n, ClosedA (A0 n)\n  | cl_a1 : forall n t, ClosedT t -> ClosedA (fun _ => a1 n (t _))\n  | cl_a2 : forall n t t', ClosedT t -> ClosedT t' -> ClosedA (fun _ => a2 n (t _) (t' _)).\n\n  (** Closed Formulas *)\n  Inductive Closed : Lexp -> Prop :=\n  | cl_atom : forall A, ClosedA A -> Closed (Atom A )\n  | cl_perp : forall A, ClosedA A -> Closed (Perp A )\n  | cl_one : Closed One\n  | cl_bot : Closed Bot\n  | cl_zero : Closed Zero\n  | cl_top : Closed Top\n  | cl_tensor : forall F G, Closed F -> Closed G -> Closed (Tensor F G)\n  | cl_par : forall F G, Closed F -> Closed G -> Closed (Par F G)\n  | cl_plus : forall F G, Closed F -> Closed G -> Closed (Plus F G)\n  | cl_with : forall F G, Closed F -> Closed G -> Closed (With F G)\n  | cl_bang : forall F, Closed F -> Closed (Bang F)\n  | cl_quest : forall F, Closed F -> Closed (Quest F)\n  | cl_ex : forall FX, Closed (Ex FX)\n  | cl_fx : forall FX, Closed (Fx FX).\n\n  (** Axioms of Closedeness *)\n  Axiom ax_closedT : forall X:Term, ClosedT X.\n  Axiom ax_closedA : forall A: AProp, ClosedA A.\n  Axiom ax_closed : forall F:Lexp, Closed F.\n\n  (** We assume equality on formulas to be decidable *)\n  Axiom FEqDec : forall (F G: Lexp ),  {F = G} + {F <> G}.\n  Lemma not_eqLExp_sym : forall x y: Lexp,  x <> y -> y <> x.\n  Proof. intuition.\n  Qed.\n\n  (* Case analysis on a formula *)\n  Ltac caseLexp F :=\n    let Hx := fresh \"HF\" in\n    assert(Hx : Closed F) by (apply ax_closed);\n    inversion Hx.\n  (* Induction on a formula *)\n  Ltac indLexp F :=\n    let Hx := fresh \"HF\" in\n    assert(Hx : Closed F) by (apply ax_closed);\n    induction Hx.\n  (* Dealing with equality on LExp *)\n  Ltac lexp_contr H :=\n    eapply @equal_f_dep with (x:=unit) in H;\n    inversion H.\n  Ltac lexp_contr_unit H :=\n    eapply @equal_f_dep with (x:=unit) in H;\n    inversion H.\n  Ltac LexpContr :=\n    try(match goal with [H : ?F = ?G |- _] =>\n                        assert(False) by lexp_contr_unit H;contradiction\n        end).\n  \n  \n  (************************************)\n  (* Dualities on formulas *)\n  (************************************)\n  Section Dualities.\n    Variable T: Type.\n    (** Dualilities   *)\n    Fixpoint dual_LExp (X: lexp T) :=\n      match X with\n      | atom A \t => perp A \n      | perp A \t => atom A\n      | one => bot\n      | bot => one\n      | zero => top\n      | top => zero  \n      | tensor F G => par (dual_LExp F) (dual_LExp G)\n      | par F G    => tensor (dual_LExp F) (dual_LExp G)\n      | plus F G => witH (dual_LExp F) (dual_LExp G)\n      | witH F G    => plus (dual_LExp F) (dual_LExp G)\n      | bang F   => quest (dual_LExp F) \n      | quest F  => bang (dual_LExp  F)\n      | ex X => fx (fun x => dual_LExp (X x))\n      | fx X => ex (fun x => dual_LExp (X x))\n      end.\n\n    Theorem ng_involutive: forall F: lexp T, F = dual_LExp (dual_LExp F).\n    Proof.\n      intro. \n      induction F; simpl; auto;\n        try( try(rewrite <- IHF1); try(rewrite <- IHF2); try(rewrite <- IHF);auto);\n        try(assert (f = fun x =>  dual_LExp (dual_LExp (f x))) by\n               (extensionality t; apply H); rewrite <- H0; auto).\n    Qed.\n\n    (** Linear implication *)\n    Definition imp (A B: lexp T): lexp T := par (dual_LExp A) B.\n  End Dualities.\n\n  Arguments dual_LExp [T].\n  \n  Definition Imp (A B : Lexp) : Lexp := fun _ => imp (A _) (B _).\n  Definition Dual_LExp (X: Lexp) : Lexp := fun _ => dual_LExp (X _).\n\n  (**************************************)\n  (* Notation on Formulas *)\n  (**************************************)\n  Module LLNotation.\n    Notation \"⊥\" := Bot.\n    Notation \"⊤\" := Top.\n    Notation \"0\" := Zero.\n    Notation \"1\" := One.\n    Notation \"A ** B\" := (Tensor A B) (at level 50) .\n    Notation \"A $ B\" := (Par A B) (at level 50) .\n    Notation \"A ⊕ B\" := (Plus A B) (at level 50).\n    Notation \"A & B\" := (With A B) (at level 50) .\n    Notation \"! A\" := (Bang A) (at level 50) .\n    Notation \"? A\" := (Quest A) (at level 50) .\n    Notation \"A ⁺\" := (Atom A) (at level 10) .\n    Notation \"A ⁻\" := (Perp A) (at level 10) .\n    Notation \"'F{' FX '}'\" := (Fx FX) (at level 10) .\n    Notation \"'E{' FX '}'\" := (Ex FX) (at level 10) .\n    Notation \"P °\" := (Dual_LExp P) (at level 1, left associativity, format \"P °\").\n    Notation\"A -o B\"    := (Imp A B) (at level 70).\n  End LLNotation.\n\n  Export LLNotation.\n\n  Lemma one_bot : 1° = ⊥.\n  Proof. auto. Qed.\n  Lemma bot_one : ⊥° = 1.\n  Proof. auto. Qed.  \n  Lemma top_zero : ⊤° = 0.\n  Proof. auto. Qed.\n  Lemma zero_top : 0° = ⊤.\n  Proof. auto. Qed.\n\n\n  Lemma atom_perp A: (A ⁺)° = A ⁻.\n  Proof. auto. Qed.  \n  Lemma perp_atom A: (A ⁻)° = A ⁺.\n  Proof. auto. Qed. \n  \n  Lemma tensor_par A B: (A ** B)° = A° $ B°.\n  Proof. extensionality T.  apply @equal_f_dep. auto. Qed.\n  Lemma par_tensor A B: (A $ B)° = A° ** B°.\n  Proof. extensionality T.  apply @equal_f_dep. auto. Qed.\n  Lemma with_plus A B: (A & B)° = A° ⊕ B°.\n  Proof. extensionality T.  apply @equal_f_dep. auto. Qed.\n  Lemma plus_with A B: (A ⊕ B)° = A° & B°.\n  Proof. extensionality T.  apply @equal_f_dep. auto. Qed.\n  \n  Lemma bang_quest A: (! A)° = ? A°.\n  Proof. auto. Qed.  \n  Lemma quest_bang A: (? A )° = ! A°.\n  Proof. auto. Qed. \n  \n  Lemma fx_ex FX: F{FX}° = Ex (fun _ x => dual_LExp(FX _ x)).\n  Proof. extensionality T.  apply @equal_f_dep. auto. Qed.\n  Lemma ex_fx FX: E{FX}° = Fx (fun _ x => dual_LExp(FX _ x)).\n  Proof. extensionality T.  apply @equal_f_dep. auto. Qed.\n\n  Lemma AtomNeg : forall A, (A ⁻)° = A ⁺.\n    intro.\n    reflexivity.\n  Qed.\n  Lemma AtomPos : forall A, (A ⁺)° = A ⁻.\n    intro.\n    reflexivity.\n  Qed.\n  \n  \n  \n  Lemma Neg2pos: forall A, Atom A = Dual_LExp (Perp A).\n  Proof. intro; reflexivity. Qed.\n  \n  Theorem Ng_involutive: forall F: Lexp, F = Dual_LExp (Dual_LExp F).\n  Proof.\n    intro.\n    unfold Dual_LExp.\n    extensionality T.\n    rewrite <- ng_involutive with (T:=T).\n    reflexivity.\n  Qed.\n  \n  Hint Rewrite Neg2pos Ng_involutive.\n\n  \n\n  (**********************************************)\n  (* Substitutions *)\n  (**********************************************)\n  Section Substitution.\n    Variable T : Type.\n    Fixpoint flattenT   (t : term ( (term T))) : term T :=\n      match t with\n      | var x => x\n      | cte x => cte x\n      | fc1 n x => fc1 n (flattenT x)\n      | fc2 n x y => fc2 n (flattenT x) (flattenT y)\n      end.\n    \n    Fixpoint flatten   (e : lexp ( (term T))) : lexp ( T) :=\n      match e with\n      | atom (a0 n) => atom (a0 n)\n      | atom (a1 n t) => atom (a1 n (flattenT t))\n      | atom (a2 n t t') => atom (a2 n (flattenT t) (flattenT t'))\n      | perp (a0 n) => perp (a0 n)\n      | perp (a1 n t) => perp (a1 n (flattenT t))\n      | perp (a2 n t t') => perp (a2 n (flattenT t) (flattenT t'))\n      | top => top\n      | bot => bot\n      | zero => zero\n      | one => one\n      | tensor F G => tensor (flatten F)  (flatten G)\n      | par F G => par (flatten F)  (flatten G)\n      | plus F G => plus (flatten F)  (flatten G)\n      | witH F G => witH (flatten F)  (flatten G)\n      | bang F => bang (flatten F)  \n      | quest F => quest (flatten F)  \n      | ex FX => ex (fun x => flatten (FX  (var x)))\n      | fx FX => fx (fun x => flatten (FX  (var x)))\n      end.\n  End Substitution.\n\n  (* Poly version of substitutions *)\n  Definition Subst   (S : Subs ) (X : Term)  : Lexp :=\n    fun T:Type  => flatten (S (term T) (X T)).\n\n  Fixpoint SubstL   (S : SubsL ) (X : Term)  : list Lexp := map (fun s => Subst s X) S.\n  \n  \n\n  \n  (************************************************)\n  (* Equality On LExp Formulas *)\n  (************************************************)\n\n  Section EqualityFormulas. \n    Lemma AtomEq: forall A A', Atom A = Atom A' -> A = A'.\n      intros.\n      extensionality T. apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n    Lemma PerpEq: forall A A', Perp A = Perp A' -> A = A'.\n      intros.\n      extensionality T. apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n    \n    (*Lemma A1eq : forall n n' t t', A1 n t = A1 n' t' -> t = t'.\n      intros.\n      extensionality T. apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n    Lemma A1eqn : forall n n' t t', A1 n t = A1 n' t' -> n = n'.\n      intros.\n      apply @equal_f_dep with (x:=unit) in H.\n      inversion H. auto.\n    Qed.\n\n    \n    Lemma A2eq : forall n t1 t2 t1' t2', A2 n t1 t2 = A2 n t1' t2' -> t1 = t1'.\n      intros.\n      extensionality T. apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n    Lemma A2eq' : forall n t1 t2 t1' t2', A2 n t1 t2 = A2 n t1' t2' -> t2 = t2'.\n      intros.\n      extensionality T. apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.*)\n    \n    Lemma ParEq1 : forall F G F0 G0,  F0 $ G0 = F $ G -> F = F0.\n      intros.\n      extensionality T. apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n    Lemma ParEq2 : forall F G F0 G0,  F0 $ G0 = F $ G -> G = G0.\n      intros. extensionality T.\n      apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n    \n    Lemma WithEq1 : forall F G F0 G0,  F0 & G0 = F & G -> F = F0.\n      intros.\n      extensionality T. apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n    Lemma WithEq2 : forall F G F0 G0,  F0 & G0 = F & G -> G = G0.\n      intros. extensionality T.\n      apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n    \n    Lemma TensorEq1 : forall F G F0 G0,  F0 ** G0 = F ** G -> F = F0.\n      intros.\n      extensionality T. apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n    Lemma TensorEq2 : forall F G F0 G0,  F0 ** G0 = F ** G -> G = G0.\n      intros. extensionality T.\n      apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n    \n    Lemma PlusEq1 : forall F G F0 G0,  F0 ⊕ G0 = F ⊕ G -> F = F0.\n      intros.\n      extensionality T. apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n    Lemma PlusEq2 : forall F G F0 G0,  F0 ⊕ G0 = F ⊕ G -> G = G0.\n      intros. extensionality T.\n      apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n    \n    Lemma BangEq : forall F F',  ! F = ! F'-> F = F'.\n      intros.\n      extensionality T. apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n    \n    \n    Lemma QuestEq : forall F F',  ? F = ? F'-> F = F'.\n      intros.\n      extensionality T. apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n    \n    Lemma FxEq : forall F F',  F{ F } = F{ F' }-> F = F'.\n      intros.\n      extensionality T. apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n\n    Lemma ExEq : forall F F',  E{ F } = E{ F' }-> F = F'.\n      intros.\n      extensionality T. apply @equal_f_dep with (x:=T) in H.\n      inversion H. auto.\n    Qed.\n\n    Lemma CteEqt : forall t t',  Cte t = Cte t' -> t = t'.\n      intros.\n      apply @equal_f_dep with (x:=unit) in H.\n      inversion H;auto.\n    Qed.\n\n\n    Lemma F1Eqn : forall n n' t t',  FC1 n t = FC1 n' t' -> n = n'.\n      intros.\n      apply @equal_f_dep with (x:=unit) in H.\n      inversion H;auto.\n    Qed.\n\n    Lemma F1Eqt : forall n n' t t',  FC1 n t = FC1 n' t' -> t = t'.\n      intros.\n      extensionality T.\n      apply @equal_f_dep with (x:=T) in H.\n      inversion H;auto.\n    Qed.\n\n    Lemma F2Eqn : forall n1 n2 t1 t1' t2 t2',  FC2 n1 t1 t2 = FC2 n2 t1' t2' -> n1 = n2.\n      intros.\n      apply @equal_f_dep with (x:=unit) in H.\n      inversion H;auto.\n    Qed.\n\n\n    Lemma F2Eqt1 : forall n1 n2 t1 t1' t2 t2',  FC2 n1 t1 t2 = FC2 n2 t1' t2' -> t1 = t1'.\n      intros.\n      extensionality T.\n      apply @equal_f_dep with (x:=T) in H.\n      inversion H;auto.\n    Qed.\n\n    Lemma F2Eqt2 : forall n1 n2 t1 t1' t2 t2',  FC2 n1 t1 t2 = FC2 n2 t1' t2' -> t2 = t2'.\n      intros.\n      extensionality T.\n      apply @equal_f_dep with (x:=T) in H.\n      inversion H;auto.\n    Qed.\n\n    Lemma Terms_cte_fc1 : forall t n t', Cte t <> FC1 n t'.\n      intros t n t' Hn.\n      apply @equal_f_dep with (x:=unit) in Hn.\n      inversion Hn.\n    Qed.\n\n    Lemma Terms_cte_fc2 : forall t n t' t'', Cte t <> FC2 n t' t''.\n      intros t n t' t'' Hn.\n      apply @equal_f_dep with (x:=unit) in Hn.\n      inversion Hn.\n    Qed.\n\n    Lemma Terms_fc1_fc2 : forall t n t' t'' n', FC1 n t <> FC2 n' t' t''.\n      intros t n t' t'' n' Hn.\n      apply @equal_f_dep with (x:=unit) in Hn.\n      inversion Hn.\n    Qed.\n\n    Lemma A0Inv : forall n m, A0 n = A0 m -> n = m.\n      intros.\n      unfold A0 in H.\n      apply @equal_f_dep with (x:=unit) in H.\n      inversion H;auto.\n    Qed.\n\n    Lemma A1InvN : forall n m t t', A1 n t = A1 m t' -> n = m.\n      intros.\n      unfold A1 in H.\n      apply @equal_f_dep with (x:=unit) in H.\n      inversion H;auto.\n    Qed.\n\n    Lemma A1InvT : forall n m t t', A1 n t = A1 m t' -> t = t'.\n      intros.\n      unfold A1 in H.\n      extensionality T.\n      apply @equal_f_dep with (x:=T) in H.\n      inversion H;auto.\n    Qed.\n\n    Lemma A2InvN : forall n m t1 t1' t2 t2', A2 n t1 t2 = A2 m t1' t2' -> n = m.\n      intros.\n      unfold A2 in H.\n      apply @equal_f_dep with (x:=unit) in H.\n      inversion H;auto.\n    Qed.\n\n    Lemma A2InvT1 : forall n m t1 t1' t2 t2', A2 n t1 t2 = A2 m t1' t2' -> t1 = t1'.\n      intros.\n      unfold A2 in H.\n      extensionality T.\n      apply @equal_f_dep with (x:=T) in H.\n      inversion H;auto.\n    Qed.\n\n    Lemma A2InvT2 : forall n m t1 t1' t2 t2', A2 n t1 t2 = A2 m t1' t2' -> t2 = t2'.\n      intros.\n      unfold A2 in H.\n      extensionality T.\n      apply @equal_f_dep with (x:=T) in H.\n      inversion H;auto.\n    Qed.\n\n\n\n  End EqualityFormulas. \n  \n  (* Inversion on Hypotheses of the shape F:Lexp = G:Lexp *)\n  Ltac LexpSubst :=\n    match goal with\n    | [H : A0 ?n = A0 ?m  |- _] =>\n      assert (n = m) by ( apply A0Inv in H;auto);\n      subst\n    | [H : A1 ?n ?F = A1 ?m ?F' |- _] =>\n      assert (F = F') by ( apply A1InvT in H;auto);\n      assert (n = m) by ( apply A1InvN in H;auto);\n      subst\n    | [H : A2 ?n ?F1 ?F2 = A2 ?m ?F1' ?F2' |- _] =>\n      assert (F1 = F1') by ( apply A2InvT1 in H;auto);\n      assert (F2 = F2') by ( apply A2InvT2 in H;auto);\n      assert (n = m) by ( apply A2InvN in H;auto);\n      subst\n    | [H : Atom ?F = Atom ?F' |- _] =>\n      assert (F = F') by ( apply AtomEq in H;auto);\n      subst\n    | [H : Perp ?F = Perp ?F' |- _] =>\n      assert (F = F') by ( apply PerpEq in H;auto);\n      subst  \n    | [H : ?F ** ?G = ?F' ** ?G' |- _] =>\n      assert (F = F') by ( apply TensorEq1 in H;auto);\n      assert (G = G') by ( apply TensorEq2 in H;auto);\n      subst; clear H\n    | [H : ?F ⊕ ?G = ?F' ⊕ ?G' |- _] =>\n      assert (F = F') by ( apply PlusEq1 in H;auto);\n      assert (G = G') by ( apply PlusEq2 in H;auto);\n      subst; clear H\n    | [H : ?F $ ?G = ?F' $ ?G' |- _] =>\n      assert (F = F') by ( apply ParEq1 in H;auto);\n      assert (G = G') by ( apply ParEq2 in H;auto);\n      subst; clear H\n    | [H : ?F & ?G = ?F' & ?G' |- _] =>\n      assert (F = F') by ( apply WithEq1 in H;auto);\n      assert (G = G') by ( apply WithEq2 in H;auto);\n      subst; clear H\n    | [H : F{ ?F }= F{ ?F'} |- _] =>\n      assert (F = F') by ( apply FxEq in H;auto);\n      subst\n    | [H : E{ ?F }= E{ ?F'} |- _] =>\n      assert (F = F') by ( apply ExEq in H;auto);\n      subst\n    | [H :  ! ?F = ! ?F' |- _] =>\n      assert (F = F') by ( apply BangEq in H;auto);\n      subst\n    | [H :  ? ?F = ? ?F' |- _] =>\n      assert (F = F') by ( apply QuestEq in H;auto);\n      subst\n    end.\n  \n  (************************************************)\n  \n\n  (********************************************)\n  (* Measures (weight/complexity) on Formulas *)\n  (* For the proof of Cut-elimination  *)\n  (********************************************)\n  Section Measures.\n\n    Fixpoint lexp_weight (P:lexp unit) : nat :=\n      match P with\n      | atom X | perp X => 0\n      | one | bot | zero | top => 0\n      | tensor X Y => 1 + (lexp_weight X) + (lexp_weight Y)\n      | par X Y => 1 + (lexp_weight X) + (lexp_weight Y)\n      | plus X Y => 1 + (lexp_weight X) + (lexp_weight Y)\n      | witH X Y  => 1 + (lexp_weight X) + (lexp_weight Y)\n      | bang X => 1 + lexp_weight X\n      | quest X  => 1 + lexp_weight X\n      | ex FX => 1 + lexp_weight (FX tt)\n      | fx FX => 1 + lexp_weight (FX tt)\n      end.\n\n    Definition Lexp_weight (P : Lexp) :nat := lexp_weight (P _).\n\n    Hint Unfold Lexp_weight Dual_LExp.\n\n    Theorem WeightDestruct0 : forall F:Lexp, 0%nat = Lexp_weight F ->\n                                             (exists A, F = Atom A) \\/ (exists A, F = Perp A) \\/\n                                             F = One \\/ F = Bot \\/ F = Zero \\/ F = Top.\n      autounfold.\n      intros.\n      caseLexp F;firstorder; try(rewrite <- H2 in H; inversion H);\n        try(rewrite <- H1 in H; inversion H);\n        try(rewrite <- H0 in H; inversion H).\n      left;eauto.\n      right;left;eauto.\n      \n    Qed.\n\n    Definition eq_wt F G:= Lexp_weight F = Lexp_weight G.\n    \n    Lemma wt_refl : forall F, eq_wt F F.\n    Proof. unfold eq_wt; auto. Qed.\n    \n    Lemma wt_symm : forall F G, eq_wt F G -> eq_wt G F.\n    Proof. unfold eq_wt; auto. Qed. \n    \n    Lemma wt_trans: forall F G T, eq_wt F G -> eq_wt G T -> eq_wt F T.\n    Proof. unfold eq_wt; intros; rewrite H, H0; auto. Qed. \n    \n    Hint Resolve wt_refl wt_symm wt_trans.\n    \n    Add Parametric Relation : (Lexp) eq_wt \n        reflexivity proved by wt_refl\n        symmetry proved by wt_symm\n        transitivity proved by wt_trans as wt_linear.\n\n    Lemma wt_eq : forall F G, F = G -> Lexp_weight F = Lexp_weight G.\n      intros. rewrite H. auto.\n    Qed.\n\n\n    Lemma lweight_dual_unit : forall FX:Subs, lexp_weight (FX unit tt) = lexp_weight (dual_LExp (FX unit tt)).\n    Proof.\n      intros.\n      induction (FX unit tt);try(reflexivity);\n        try(simpl;try(rewrite IHl);try(rewrite IHl1);try(rewrite IHl2);reflexivity);\n        (simpl; generalize (H tt);intro HH; rewrite HH; reflexivity).\n    Qed.\n    \n    Lemma lweight_dual : forall F: Lexp , Lexp_weight F = Lexp_weight (Dual_LExp F).\n    Proof.\n      intro.\n      indLexp F;try (reflexivity);autounfold in *;\n        try(simpl; try(rewrite IHHF1);try(rewrite IHHF2);auto);\n        rewrite lweight_dual_unit;auto.\n    Qed.\n\n    \n    Lemma lweight_dual_plus : forall F G, Lexp_weight F + Lexp_weight G = Lexp_weight (Dual_LExp F) + Lexp_weight (Dual_LExp G).\n    Proof.\n      intros.\n      rewrite lweight_dual with (F:=F).\n      rewrite lweight_dual with (F:=G).\n      auto.\n    Qed.\n  End Measures.\n  \n\n  (*************************************************)\n  (** Equality UpTo Atoms *)\n  (*************************************************)\n  Section EqUpTo.\n    Variable T T':Type.\n    Inductive xVariantT : term T -> term T'-> Prop :=\n    | xvt_var : forall x y, xVariantT (var x) (var y)\n    | xvt_cte : forall c, xVariantT (cte c) (cte c)\n    | xvt_fc1 : forall n t t', xVariantT t t' -> xVariantT (fc1 n t) (fc1 n t')\n    | xvt_fc2 : forall n t1 t2 t1' t2', xVariantT t1 t1' -> xVariantT t2 t2' ->  xVariantT (fc2 n t1 t2) (fc2 n t1' t2').\n    \n    Inductive xVariantA : aprop T -> aprop T'-> Prop :=\n    | xva_eq : forall n, xVariantA (a0 n) (a0 n)\n    | xva_a1 : forall n t t', xVariantT t t' -> xVariantA (a1 n t) (a1 n t')\n    | xva_a2 : forall n t1 t2 t1' t2', xVariantT t1 t1' -> xVariantT t2 t2' -> xVariantA (a2 n t1 t2) (a2 n t1' t2').\n\n    Inductive EqualUptoAtoms : lexp T -> lexp T' -> Prop :=\n    | eq_atom : forall A A', xVariantA A A' ->  EqualUptoAtoms (atom A) (atom A')\n    | eq_perp : forall A A', xVariantA A A' -> EqualUptoAtoms (perp A) (perp A')\n    | eq_top : EqualUptoAtoms top top\n    | eq_bot : EqualUptoAtoms bot bot\n    | eq_zero : EqualUptoAtoms zero zero\n    | eq_one : EqualUptoAtoms one one\n    | eq_tensor : forall F G F' G', EqualUptoAtoms F F' -> EqualUptoAtoms G G' -> EqualUptoAtoms (tensor F G) (tensor F' G')\n    | eq_par : forall F G F' G', EqualUptoAtoms F F' -> EqualUptoAtoms G G' -> EqualUptoAtoms (par F G) (par F' G')\n    | eq_plus : forall F G F' G', EqualUptoAtoms F F' -> EqualUptoAtoms G G' -> EqualUptoAtoms (plus F G) (plus F' G')\n    | eq_with : forall F G F' G', EqualUptoAtoms F F' -> EqualUptoAtoms G G' -> EqualUptoAtoms (witH F G) (witH F' G')\n    | eq_bang : forall F F', EqualUptoAtoms F F' -> EqualUptoAtoms (bang F) (bang F')\n    | eq_quest : forall F F', EqualUptoAtoms F F' -> EqualUptoAtoms (quest F) (quest F')\n    | eq_ex : forall FX FX' ,  (forall t t', EqualUptoAtoms (FX t) (FX' t')) -> EqualUptoAtoms (ex (FX )) (ex (FX'))\n    | eq_fx : forall FX FX' , (forall t t', EqualUptoAtoms (FX t) (FX' t')) ->  EqualUptoAtoms (fx (FX )) (fx (FX')).\n\n    Inductive EqualUptoAtomsL : list (lexp T) -> list (lexp T') -> Prop :=\n    | eq_nil : EqualUptoAtomsL nil nil\n    | eq_cons : forall F F' L L', EqualUptoAtoms F F' -> EqualUptoAtomsL L L' -> EqualUptoAtomsL (F :: L) (F' :: L').\n  End EqUpTo. \n\n\n  (** We assume that substitutions cannot do pattern-matching nor in the type T nor in the term t *)\n  Axiom ax_subs_uptoAtoms  : forall (T T':Type) (t:T) (t' :T') (FX:Subs), EqualUptoAtoms (FX T t) (FX T' t').\n  Axiom ax_lexp_uptoAtoms  : forall (T T':Type)  (F :Lexp), EqualUptoAtoms (F T) (F T').\n\n  Theorem  subs_uptoAtomsL  : forall (T T':Type) (t:T) (t' :T') (FX:SubsL),\n      EqualUptoAtomsL  (map (fun s => (s T t) )  FX)  (map (fun s => (s T' t') )  FX).\n    intros.\n    induction FX.\n    +simpl;constructor.\n    +simpl.\n     constructor. apply ax_subs_uptoAtoms.\n     apply IHFX.\n  Qed.\n\n  (**************************************)\n  (** Basic Definition for Focusing *)\n  (*************************************)\n  Section Polarities. \n    (* Asynchronous formulas *)\n    Definition asynchronousF (F :lexp unit) :=\n      match F with\n      | atom _ | perp _ => false \n      | top => true\n      | bot => true\n      | zero => false\n      | one => false\n      | tensor _ _ => false\n      | par _ _ => true\n      | plus _ _ => false\n      | witH _ _ => true\n      | bang _ => false\n      | quest _ => true\n      | ex _ => false\n      | fx _ => true\n      end.\n    Definition AsynchronousF (F:Lexp) : bool := asynchronousF (F _).\n    Hint Unfold AsynchronousF.\n    \n    Inductive Asynchronous : Lexp -> Prop :=\n    | aTop :   Asynchronous Top\n    | aBot :   Asynchronous Bot\n    | aPar :   forall F G, Asynchronous (Par F G)\n    | aWith :  forall F G, Asynchronous (With F G)\n    | aQuest : forall F  , Asynchronous (Quest F)\n    | aForall : forall FX  , Asynchronous (Fx FX).\n    \n    Hint Constructors Asynchronous.\n\n    Theorem AsyncEqL : forall F:Lexp , Asynchronous F -> AsynchronousF F = true.\n    Proof.\n      intros.\n      inversion H;try(reflexivity).\n    Qed.\n    \n    Theorem AsyncEqR : forall F: Lexp, AsynchronousF F = true -> Asynchronous F.\n    Proof.\n      intros.\n      caseLexp F;auto;\n        try( rewrite <- H1 in H); \n        try( rewrite <- H0 in H); \n        try( rewrite <- H2 in H); inversion H.\n    Qed.\n\n    Theorem AsyncEq : forall F:Lexp , Asynchronous F <-> AsynchronousF F = true.\n      split. apply AsyncEqL. apply AsyncEqR.\n    Qed.\n    \n\n    (* Negative Atoms *)\n    Inductive IsNegativeAtom : Lexp -> Prop :=\n    | IsNA0 : forall n, true = isPositive n -> IsNegativeAtom (Perp (A0 n ))\n    | IsNA0' : forall n, false = isPositive n -> IsNegativeAtom (Atom (A0 n ))\n    | IsNA1 : forall n t, true = isPositive n -> IsNegativeAtom (Perp (A1 n t ))\n    | IsNA1' : forall n t, false = isPositive n -> IsNegativeAtom (Atom (A1 n t))\n    | IsNA2 : forall n t t', true = isPositive n -> IsNegativeAtom (Perp (A2 n t t'))\n    | IsNA2'' : forall n t t', false = isPositive n -> IsNegativeAtom (Atom (A2 n t t')).\n    \n    Hint Constructors IsNegativeAtom.\n    \n    (* Positive Atoms *)\n    Inductive IsPositiveAtom : Lexp -> Prop :=\n    | IsPA0 : forall n, false = isPositive n -> IsPositiveAtom (Perp (A0 n ))\n    | IsPA0' : forall n, true = isPositive n -> IsPositiveAtom (Atom (A0 n ))\n    | IsPA1 : forall n t, false = isPositive n -> IsPositiveAtom (Perp (A1 n t ))\n    | IsPA1' : forall n t, true = isPositive n -> IsPositiveAtom (Atom (A1 n t))\n    | IsPA2 : forall n t t', false = isPositive n -> IsPositiveAtom (Perp (A2 n t t'))\n    | IsPA2'' : forall n t t', true = isPositive n -> IsPositiveAtom (Atom (A2 n t t')).\n    \n    Hint Constructors IsPositiveAtom.\n    \n    (* Complexity of formulas for the focused system *)\n    Fixpoint exp_weight (P:lexp unit) : nat :=\n      match P with\n      | atom _ | perp _ | one | bot | zero | top => 1\n      | tensor X Y => 1 + (exp_weight X) + (exp_weight Y)\n      | par X Y => 1 + (exp_weight X) + (exp_weight Y)\n      | plus X Y => 1 + (exp_weight X) + (exp_weight Y)\n      | witH X Y  => 1 + (exp_weight X) + (exp_weight Y)\n      | bang X => 1 + exp_weight X\n      | quest X  => 1 + exp_weight X\n      | ex FX  => 1 + exp_weight (FX tt)\n      | fx FX  => 1 + exp_weight (FX tt)\n      end.\n\n    Definition Exp_weight (F:Lexp) :nat := exp_weight(F _).\n    Hint Unfold Exp_weight.\n\n    Theorem exp_weight0 : forall  F:Lexp , Exp_weight F > 0.\n      intros.\n      unfold Exp_weight.\n      induction F;simpl;omega.\n    Qed.\n\n    Theorem exp_weight0F : forall  F:Lexp , Exp_weight F = 0%nat -> False.\n    Proof.\n      intros.\n      generalize(exp_weight0 F).\n      intro.\n      rewrite H in H0.\n      inversion H0.\n    Qed.\n\n    (* Complexity of list of formulas  *)\n    Fixpoint L_weight (L: list Lexp) : nat :=\n      match L with\n      | nil => 0\n      | H :: L' => (Exp_weight H) + (L_weight L')\n      end.\n    \n    Theorem exp_weight0LF : forall l L, 0%nat = Exp_weight l + L_weight L -> False.\n    Proof.\n      intros.\n      assert(Exp_weight l > 0%nat) by (apply exp_weight0).\n      omega.\n    Qed.\n    \n    Theorem L_weightApp : forall L M, L_weight (L ++M) = L_weight L + L_weight M.\n    Proof.\n      intros.\n      induction L; auto.\n      simpl.\n      rewrite IHL.\n      omega.\n    Qed.\n    \n    Lemma WeightLeq: forall w l L, S w = L_weight (l :: L) -> L_weight L <= w.\n    Proof.\n      intros.\n      simpl in H.\n      generalize (exp_weight0 l);intro.\n      apply GtZero in H0.\n      destruct H0.\n      rewrite H0 in H.\n      omega.\n    Qed.\n    \n    Lemma FlattenAtom : forall T, forall (A : aprop (term T)), exists A' ,  flatten (atom A) = atom A'.\n      intros.\n      destruct A3;simpl;eauto.\n    Qed.\n    \n    Lemma FlattenPerp : forall T, forall (A : aprop (term T)), exists A' ,  flatten (perp A) = perp A'.\n      intros.\n      destruct A3;simpl;eauto.\n    Qed.\n\n    Lemma subs_weight_weak:  forall (FX:Subs) x, Exp_weight (Subst FX x) = exp_weight (FX unit tt) .\n      intros.\n      autounfold. unfold Subst.\n      assert (ClosedT x) by apply ax_closedT.\n      inversion H. \n      + assert(EqualUptoAtoms (FX (term unit) (Cte C unit)) (FX unit tt)) by apply ax_subs_uptoAtoms.\n        induction H1;simpl; try(destruct A3);auto.\n      + assert(EqualUptoAtoms (FX (term unit) (FC1 n t1 unit)) (FX unit tt)) by apply ax_subs_uptoAtoms.\n        induction H2;simpl; try(destruct A3);auto.\n      + assert(EqualUptoAtoms (FX (term unit) (FC2 n t1 t2 unit)) (FX unit tt)) by apply ax_subs_uptoAtoms.\n        induction H3;simpl; try(destruct A3);auto.\n    Qed.\n    \n    Theorem subs_weight : forall (FX : Subs) x y, Exp_weight(Subst FX x) = Exp_weight(Subst FX y).\n      intros.\n      rewrite subs_weight_weak.\n      rewrite subs_weight_weak.\n      auto.\n    Qed.\n\n    Lemma subs_weight_weak':  forall (FX:Subs) x, Lexp_weight (Subst FX x) = (lexp_weight (FX unit tt)) .\n      intros.\n      unfold Lexp_weight.\n      unfold Subst.\n      \n      assert (ClosedT x) by apply ax_closedT.\n      inversion H. \n      + assert(EqualUptoAtoms (FX (term unit) (Cte C unit)) (FX unit tt)) by apply ax_subs_uptoAtoms.\n        induction H1;simpl ; try(destruct A3); unfold Lexp_weight; auto.\n      + assert(EqualUptoAtoms (FX (term unit) (FC1 n t1 unit)) (FX unit tt)) by apply ax_subs_uptoAtoms.\n        induction H2;simpl; try(destruct A3);auto.\n      + assert(EqualUptoAtoms (FX (term unit) (FC2 n t1 t2 unit)) (FX unit tt)) by apply ax_subs_uptoAtoms.\n        induction H3;simpl; try(destruct A3);auto.\n    Qed. \n    \n    Theorem subs_weight' : forall (FX : Subs) x y, Lexp_weight(Subst FX x) = Lexp_weight(Subst FX y).\n      intros.\n      rewrite subs_weight_weak'.\n      rewrite subs_weight_weak'.\n      auto.\n    Qed.\n    \n    Lemma Flatten_dual : forall T (F: lexp (term T)), flatten F = dual_LExp(flatten ( dual_LExp F)).\n      intros.\n      induction F;simpl;try(destruct a);try(reflexivity);\n        try(simpl;rewrite IHF1;rewrite IHF2; intuition);\n        try(simpl;rewrite IHF; intuition).\n      \n      assert(Hs : (fun x : T => flatten (f (var x))) =  (fun x : T => dual_LExp (flatten (dual_LExp (f (var x))))))\n        by (extensionality x; generalize(H (var x));auto);rewrite Hs; reflexivity.\n      assert(Hs : (fun x : T => flatten (f (var x))) =  (fun x : T => dual_LExp (flatten (dual_LExp (f (var x))))))\n        by (extensionality x; generalize(H (var x));auto);rewrite Hs; reflexivity.\n    Qed.\n\n    Theorem SubsDual: forall (FX1 FX2 : Subs) t, (E{ FX1})° = F{ FX2} -> (Subst FX1 t)  = (Subst FX2 t)°.\n      intros.\n      unfold Dual_LExp in *.\n      simpl in *. \n      change  ( (fun T : Type => fx (fun x : T => dual_LExp (FX1 T x))))\n      with (F{ fun _ x => dual_LExp(FX1 _ x)}) in H.\n      LexpSubst.\n      unfold Subst.\n      extensionality T.\n      eapply Flatten_dual.\n    Qed.\n    \n    Theorem SubsDual': forall (FX1 FX2 : Subs) t, (F{ FX1})° = E{ FX2} -> (Subst FX1 t)  = (Subst FX2 t)°.\n      intros.\n      unfold Dual_LExp in *.\n      simpl in *.\n      change  ( (fun T : Type => ex (fun x : T => dual_LExp (FX1 T x))))\n      with (E{ fun _ x => dual_LExp(FX1 _ x)}) in H.\n      LexpSubst.\n      unfold Subst.\n      extensionality T.\n      eapply Flatten_dual.\n    Qed.\n    \n\n    \n    Theorem WeightEF (FX1 FX2 : Subs) w t : \n      S w = Lexp_weight (E{ FX1}) -> \n      (E{ FX1})° = F{ FX2} -> Lexp_weight (Subst FX2 t) <= w.\n    Proof.\n      intros Hw Eq.\n      assert (Lexp_weight (E{ FX1})° = Lexp_weight (F{ FX2})) by\n          solve [rewrite Eq; auto].\n      inversion H. inversion Hw.\n      rewrite subs_weight_weak'.\n      rewrite <- H1. rewrite lweight_dual_unit. auto. \n    Qed.\n\n    Theorem WeightFE (FX1 FX2 : Subs) w t : \n      S w = Lexp_weight (F{ FX1}) -> \n      (F{ FX1})° = E{ FX2} -> Lexp_weight (Subst FX2 t) <= w.\n    Proof.\n      intros Hw Eq.\n      assert (Lexp_weight (F{ FX1})° = Lexp_weight (E{ FX2})) by\n          solve [rewrite Eq; auto].\n      inversion H. inversion Hw.\n      rewrite subs_weight_weak'.\n      rewrite <- H1. rewrite lweight_dual_unit. auto. \n    Qed.\n    \n\n\n    (* Lists of positive formulas *)\n    Fixpoint LexpPos (l: list Lexp) : Prop :=\n      match l with\n      | nil => True\n      | H :: T' => (AsynchronousF H = false) /\\ LexpPos T' \n      end.\n    \n    Fixpoint BlexpPos (l: list Lexp) : bool :=\n      match l with\n      | nil => true\n      | H :: T => andb (negb (AsynchronousF H)) ( BlexpPos T)\n      end.\n    \n    Theorem PosBool : forall l, BlexpPos l = true <-> LexpPos l.\n    Proof.\n      intros.\n      split;induction l;simpl;auto.\n      - intro.\n        split.\n        rewrite andb_true_iff in H.\n        destruct H.\n        auto.\n        rewrite negb_true_iff in H.\n        auto.\n        rewrite andb_true_iff in H.\n        destruct H.\n        auto.\n      - intro.\n        destruct H.\n        apply IHl in H0.\n        rewrite H.\n        simpl.\n        auto.\n    Qed.\n\n    Inductive LexpPos' : list Lexp -> Prop :=\n    | l_nil : LexpPos' []\n    | l_sin : forall a, (AsynchronousF a = false) -> LexpPos' [a]\n    | l_cos : forall a l, LexpPos' [a] -> LexpPos' l -> LexpPos' (a::l).\n    \n    Hint Resolve l_nil l_sin l_cos.\n\n    (* Properties of lexpPos *)\n    Lemma lexpPosUnion a L: LexpPos [a] -> LexpPos L -> LexpPos ([a] ++ L).\n    Proof.\n      intros.\n      simpl; firstorder.\n    Qed.  \n\n    Lemma lexpPosUnion_inv a L: LexpPos ([a] ++ L) -> LexpPos [a] /\\ LexpPos L.\n    Proof.\n      intros.\n      simpl in H.\n      split; firstorder.\n    Qed.\n\n    Lemma lexpPos_lexpPos' M: LexpPos' M <-> LexpPos M.\n    Proof.\n      split; intros.\n      * induction H;\n          try solve [simpl; auto].\n        apply lexpPosUnion; auto.\n      * induction M; intros; auto.\n        apply lexpPosUnion_inv in H.\n        destruct H.\n        apply l_cos; auto.\n        apply l_sin; firstorder.\n    Qed.\n\n    Lemma AsynchronousFlexpPos : forall  l, AsynchronousF l = false -> LexpPos [l].\n    Proof.\n      intros.\n      constructor;auto.\n      constructor.\n    Qed.\n\n    Lemma NegPosAtom : forall F, IsNegativeAtom F -> IsPositiveAtom F° .\n      intros.\n      inversion H;try(constructor);auto.\n    Qed.\n\n    \n    Inductive release : lexp unit-> Prop :=\n    | RelNA1 : forall n, false = isPositive n -> release (perp (a0 n))\n    | RelNA1' : forall n, true = isPositive n -> release (atom (a0 n))\n    | RelNA2 : forall n t, false = isPositive n -> release (perp (a1 n t))\n    | RelNA2' : forall n t, true = isPositive n -> release (atom (a1 n t))\n    | RelNA3 : forall n t t', false = isPositive n -> release (perp (a2 n t t'))\n    | RelNA3' : forall n t t', true = isPositive n -> release (atom (a2 n t t'))\n    | RelTop : release top\n    | RelBot : release bot\n    | RelPar : forall F G, release (par F G)\n    | RelWith : forall F G, release (witH F G)\n    | RelQuest : forall F, release (quest F)\n    | RelForall : forall FX, release (fx FX).\n\n    Definition Release (F:Lexp) := release (F _).\n    Hint Unfold Release.\n    Hint Constructors release.\n\n    Lemma IsPositiveAtomRelease: forall F, IsPositiveAtom F -> Release F.\n      intros.\n      inversion H;\n        constructor;auto.\n    Qed.\n\n    \n    (* Some definitions for the proof of completeness *)\n    Inductive NotAsynchronous : Lexp -> Prop :=\n    | NAAtomP :  forall v,  NotAsynchronous (Atom v)\n    | NAAtomN :  forall v,  NotAsynchronous (Perp v)\n    | NAZero :  NotAsynchronous Zero\n    | NAOne :  NotAsynchronous One\n    | NATensor : forall F G,  NotAsynchronous ( F ** G)\n    | NAPlus : forall F G,  NotAsynchronous ( Plus F  G)\n    | NABang : forall F,  NotAsynchronous ( ! F )\n    | NAExists : forall FX,  NotAsynchronous ( Ex FX ).\n    Hint Constructors NotAsynchronous.\n    \n    Theorem AsynchronousEquiv : forall F, NotAsynchronous F <-> ~ Asynchronous F.\n    Proof.\n      intros.\n      split;intro.\n      + inversion H;intro Hc;inversion Hc; apply @equal_f_dep with (x:=unit) in H2; inversion H2.\n      + indLexp F;try(constructor);\n          match goal with [H : ~Asynchronous ?F |- _]\n                          => assert(Asynchronous F) by auto; contradiction end.\n    Qed.\n\n    Theorem AsyncEqNeg : forall F:Lexp , ~ Asynchronous F <-> AsynchronousF F = false.\n      split;intro H.\n      + rewrite <- AsynchronousEquiv in  H.\n        inversion H;reflexivity.\n      + intro HN.\n        apply AsyncEqL in HN.\n        rewrite H in HN.\n        intuition.\n    Qed.\n\n    Inductive posOrNegAtom : lexp unit -> Prop :=\n    | PPAtom1 :  forall n,  false = isPositive n -> posOrNegAtom (atom (a0 n))\n    | PPAtom1' :  forall n,  true = isPositive n -> posOrNegAtom (perp (a0 n))\n    | PPAtom2 :  forall n t,  false = isPositive n -> posOrNegAtom (atom (a1 n t))\n    | PPAtom2' :  forall n t,  true = isPositive n -> posOrNegAtom (perp (a1 n t))\n    | PPAtom3 :  forall n t t',  false = isPositive n -> posOrNegAtom (atom (a2 n t t'))\n    | PPAtom3' :  forall n t t',  true = isPositive n -> posOrNegAtom (perp (a2 n t t'))\n    | PPZero :  posOrNegAtom zero\n    | PPOne :  posOrNegAtom one\n    | PPTensor : forall F G,  posOrNegAtom ( tensor F G)\n    | PPPlus : forall F G,  posOrNegAtom ( plus F  G)\n    | PPBang : forall F,  posOrNegAtom ( bang F )\n    | PPExists : forall FX,  posOrNegAtom ( ex FX).\n    Hint Constructors posOrNegAtom.\n    Definition PosOrNegAtom (F:Lexp) := posOrNegAtom (F _).\n    Hint Unfold PosOrNegAtom.\n\n    (* ~ Asynchronous (Subst FX t)*)\n    Inductive posFormula : lexp unit -> Prop :=\n    | PFZero :  posFormula zero\n    | PFOne :  posFormula one\n    | PFTensor : forall F G,  posFormula ( tensor F G)\n    | PFPlus : forall F G,  posFormula ( plus F  G)\n    | PFBang : forall F,  posFormula ( bang F )\n    | PFExists : forall FX,  posFormula ( ex FX).\n    Hint Constructors posFormula.\n    Definition PosFormula (F:Lexp) := posFormula (F _).\n    Hint Unfold PosFormula.\n\n    Lemma PosFormulaPosOrNegAtom : forall F, PosFormula F -> PosOrNegAtom F.\n      intros.\n      unfold PosOrNegAtom.\n      inversion H;constructor.\n    Qed.\n\n    Lemma ApropPosNegAtom : forall A: AProp, IsPositiveAtom (Atom A) \\/ IsNegativeAtom(Atom A).\n      intros.\n      assert(HC : ClosedA A3) by apply ax_closedA.\n      inversion HC;remember(isPositive n); destruct b;intuition.\n      left;constructor;auto.\n      right;constructor;auto.\n      left;constructor;auto.\n      right;constructor;auto.\n    Qed.\n\n    Lemma ApropPosNegAtom' : forall A: AProp, IsPositiveAtom (Perp A) \\/ IsNegativeAtom(Perp A).\n      intros.\n      assert(HC : ClosedA A3) by apply ax_closedA.\n      inversion HC;remember(isPositive n); destruct b;intuition.\n      right;constructor;auto.\n      left;constructor;auto.\n      right;constructor;auto.\n      left;constructor;auto.\n    Qed.\n    \n    Lemma NotAsynchronousPosAtoms : forall F, ~ Asynchronous  F -> PosFormula F \\/ IsPositiveAtom F \\/ IsNegativeAtom F.\n      intros.\n      caseLexp F;intuition;try (assert(False) by ( apply H; rewrite<- H0; auto); contradiction);\n        try(assert(False) by ( apply H; rewrite<- H2; auto); contradiction);\n        try(assert(False) by ( apply H; rewrite<- H1; auto); contradiction);\n        try(left;constructor).\n      generalize( ApropPosNegAtom  A3); intro HA3. destruct HA3;intuition.\n      generalize( ApropPosNegAtom'  A3); intro HA3. destruct HA3;intuition.\n    Qed.\n    \n    Lemma NegPosAtomContradiction: forall F, PosOrNegAtom F ->  IsPositiveAtom F -> False.\n      intros.\n      inversion H0;\n        rewrite <- H2 in H;\n        inversion H;\n        rewrite <- H4  in H1;\n        intuition.\n    Qed.\n    \n    Lemma  IsNegativePosOrNegAtom : forall F,  IsNegativeAtom F -> PosOrNegAtom F.\n    Proof. \n      intros.\n      inversion H;constructor;auto.\n    Qed.\n    \n    Lemma PosOrNegAtomAsync : forall F, PosOrNegAtom F ->  AsynchronousF F = false.\n    Proof.\n      intros.\n      inversion H;autounfold in *;\n        try(rewrite <- H0) ; try(rewrite <- H1) ;simpl;auto.\n    Qed.\n\n\n    Lemma NotAsyncAtom : forall A, ~ Asynchronous (A ⁺).\n      intros A3 Hn.\n      inversion Hn;auto;LexpContr.\n    Qed.\n\n    Lemma NotAsyncAtom' : forall A, ~ Asynchronous (A ⁻).\n      intros A3 Hn.\n      inversion Hn;auto;LexpContr.\n    Qed.\n\n    Lemma NotAsyncOne :  ~ Asynchronous (One).\n      intro Hn.\n      inversion Hn;auto;LexpContr.\n    Qed.\n\n    Lemma NotAsyncZero :  ~ Asynchronous (Zero).\n      intro Hn.\n      inversion Hn;auto;LexpContr.\n    Qed.\n\n    Lemma NotAsyncTensor : forall F G,  ~ Asynchronous (Tensor F G).\n      intros F G Hn.\n      inversion Hn;auto;LexpContr.\n    Qed.\n\n    Lemma NotAsyncPlus : forall F G,  ~ Asynchronous (Plus F G).\n      intros F G Hn.\n      inversion Hn;auto;LexpContr.\n    Qed.\n\n    Lemma NotAsyncBang : forall F ,  ~ Asynchronous (Bang F).\n      intros F Hn.\n      inversion Hn;auto;LexpContr.\n    Qed.\n    \n    Lemma NotAsyncEx : forall FX ,  ~ Asynchronous (Ex FX).\n      intros FX Hn.\n      inversion Hn;auto;LexpContr.\n    Qed.\n\n    Lemma NotPATop :  ~IsPositiveAtom (Top).\n      intros  Hn.\n      inversion Hn;LexpContr.\n    Qed.\n\n    Lemma NotPABot :  ~IsPositiveAtom (Bot).\n      intros  Hn.\n      inversion Hn;LexpContr.\n    Qed.\n\n    Lemma NotPAOne :  ~IsPositiveAtom (One).\n      intros  Hn.\n      inversion Hn;LexpContr.\n    Qed.\n\n    Lemma NotPAZero :  ~IsPositiveAtom (Zero).\n      intros  Hn.\n      inversion Hn;LexpContr.\n    Qed.\n\n    Lemma NotPATensor : forall F G, ~IsPositiveAtom (Tensor F G).\n      intros F G Hn.\n      inversion Hn;LexpContr.\n    Qed.\n\n    Lemma NotPAPar : forall F G, ~IsPositiveAtom (Par F G).\n      intros F G Hn.\n      inversion Hn;LexpContr.\n    Qed.\n\n    Lemma NotPAPlus : forall F G, ~IsPositiveAtom (Plus F G).\n      intros F G Hn.\n      inversion Hn;LexpContr.\n    Qed.\n\n    Lemma NotPAWith : forall F G, ~IsPositiveAtom (With F G).\n      intros F G Hn.\n      inversion Hn;LexpContr.\n    Qed.\n\n    Lemma NotPABang : forall F , ~IsPositiveAtom (Bang F).\n      intros F Hn.\n      inversion Hn;LexpContr.\n    Qed.\n\n    Lemma NotPAQuest : forall F , ~IsPositiveAtom (Quest F).\n      intros F Hn.\n      inversion Hn;LexpContr.\n    Qed.\n\n    Lemma NotPAExists : forall FX, ~IsPositiveAtom (Ex FX).\n      intros FX Hn.\n      inversion Hn;LexpContr.\n    Qed.\n\n    Lemma NotPAForall : forall FX, ~IsPositiveAtom (Fx FX).\n      intros FX Hn.\n      inversion Hn;LexpContr.\n    Qed.\n\n    Lemma IsNegativeOne :  ~ IsNegativeAtom One.\n      intro Hn;inversion Hn;LexpContr.\n    Qed.\n    Lemma IsNegativeBot :  ~ IsNegativeAtom Bot.\n      intro Hn;inversion Hn;LexpContr.\n    Qed.\n    Lemma IsNegativeZero :  ~ IsNegativeAtom Zero.\n      intro Hn;inversion Hn;LexpContr.\n    Qed.\n    Lemma IsNegativeTop :  ~ IsNegativeAtom Top.\n      intro Hn;inversion Hn;LexpContr.\n    Qed.\n    Lemma IsNegativeTensor : forall F G, ~ IsNegativeAtom (Tensor F G).\n      intros F G Hn.\n      inversion Hn;LexpContr.\n    Qed.\n    Lemma IsNegativePar : forall F G, ~ IsNegativeAtom (Par F G).\n      intros F G Hn.\n      inversion Hn;LexpContr.\n    Qed.\n    Lemma IsNegativeWith : forall F G, ~ IsNegativeAtom (With F G).\n      intros F G Hn.\n      inversion Hn;LexpContr.\n    Qed.\n    Lemma IsNegativePlus : forall F G, ~ IsNegativeAtom (Plus F G).\n      intros F G Hn.\n      inversion Hn;LexpContr.\n    Qed.\n    Lemma IsNegativeBang : forall F, ~ IsNegativeAtom (! F).\n      intros F Hn.\n      inversion Hn;LexpContr.\n    Qed.\n    Lemma IsNegativeQuest : forall F, ~ IsNegativeAtom (? F).\n      intros F Hn.\n      inversion Hn;LexpContr.\n    Qed.\n    Lemma IsNegativeEx : forall F, ~ IsNegativeAtom (Ex F).\n      intros F Hn;inversion Hn;LexpContr.\n    Qed.\n    Lemma IsNegativeFx : forall F, ~ IsNegativeAtom (Fx F).\n      intros F Hn;inversion Hn;LexpContr.\n    Qed.\n\n    Lemma NotRelTensor: forall F G, ~ Release (F ** G).\n      intros F G Hn; inversion Hn.\n    Qed.\n    Lemma NotRelPlus: forall F G, ~ Release (F ⊕ G).\n      intros F G Hn; inversion Hn.\n    Qed.\n    Lemma NotRelBang: forall F , ~ Release (! F).\n      intros F Hn; inversion Hn.\n    Qed.\n    Lemma NotRelEx: forall F, ~ Release ( Ex F).\n      intros F Hn; inversion Hn.\n    Qed.\n    Lemma NotRelOne: ~ Release One.\n      intros Hn; inversion Hn.\n    Qed.\n    Lemma NotRelZero: ~ Release Zero.\n      intros Hn; inversion Hn.\n    Qed.\n\n    Hint Resolve NotRelTensor NotRelPlus NotRelBang NotRelEx NotRelOne NotRelZero NotAsyncAtom NotAsyncAtom'.\n\n    Lemma  IsPositiveAtomNotAssync : forall F,  IsPositiveAtom F -> ~ Asynchronous F.\n    Proof.\n      intros.\n      inversion H;auto.\n    Qed.\n\n    Lemma NotAsynchronousPosAtoms' : forall G, ~Asynchronous G -> IsPositiveAtom G \\/ (PosFormula G \\/ IsNegativeAtom G).\n      intros G HG.\n      apply NotAsynchronousPosAtoms in HG;tauto.\n    Qed.\n    \n    Lemma PosFNegAtomPorOrNegAtom: forall G,  PosFormula G \\/ IsNegativeAtom G -> PosOrNegAtom G.\n    Proof.\n      intros.\n      destruct H.\n      inversion H; unfold PosOrNegAtom; rewrite <- H1; auto.\n      inversion H; unfold PosOrNegAtom;constructor;auto.\n    Qed.\n    \n    Lemma AsyncRelease: forall F, Asynchronous F -> Release F.\n    Proof.\n      intros.\n      inversion H; constructor.\n    Qed.\n    \n    Lemma AsIsPosRelease: forall F, (Asynchronous F \\/ IsPositiveAtom F ) -> Release F.\n    Proof.\n      intros.\n      destruct H;auto using AsyncRelease.\n      inversion H;constructor;auto.\n    Qed.\n\n    Lemma PositiveNegativeAtom : forall At, IsPositiveAtom (At ⁺) -> IsNegativeAtom (At ⁻).\n    Proof.\n      intros.\n      inversion H; try(LexpSubst);try(LexpContr);try(constructor);auto.\n    Qed.\n    \n    \n\n    \n    Lemma PositiveNegativeAtomNeg : forall At, IsPositiveAtom (At ⁺) -> ~ IsPositiveAtom (At ⁻).\n    Proof.\n      intros.\n      inversion H;intro; try(LexpSubst);\n        apply PositiveNegativeAtom in H;\n        apply IsNegativePosOrNegAtom in H;\n        eapply NegPosAtomContradiction;eauto.\n    Qed.\n\n    \n    Lemma NegativePositiveAtomNeg : forall At, IsNegativeAtom (At ⁺) -> ~ IsPositiveAtom (At ⁺).\n    Proof.\n      intros.\n      inversion H;intro; try(LexpSubst);try(LexpContr);try(constructor);auto;\n        apply PositiveNegativeAtom in H2;\n        apply IsNegativePosOrNegAtom in H2;\n        eapply NegPosAtomContradiction;eauto.\n    Qed.\n\n    \n\n    Lemma PositiveNegative : forall A, IsPositiveAtom A -> ~ IsNegativeAtom A.\n    Proof.\n      intros.\n\n      inversion H;intro; try(LexpSubst);try(LexpContr);try(constructor);auto;\n        inversion H2;try(LexpContr);\n          try(do 2 LexpSubst); try( rewrite <- H4  in H0); intuition.\n    Qed.\n    \n\n    Lemma PosFIsNegAAsync : forall G, PosFormula G \\/ IsNegativeAtom G -> ~ Asynchronous G.\n    Proof.\n      intros.\n      destruct H.\n      caseLexp G ;try(LexpSubst);try(LexpContr);try(constructor);auto; try( rewrite <- H0 in H; inversion H);\n        try( rewrite <- H2 in H; inversion H);\n        try( rewrite <- H1 in H; inversion H);\n        inversion H;intro HA; inversion HA ;LexpContr.\n      inversion H;intro HA; inversion HA ;LexpContr.\n    Qed.\n\n  End Polarities.\n\n  (* Solves goals when there is an hypothesis IsNegativeAtom(F) and F cannot be a negative atom *)\n  Ltac invNegAtom :=\n    try(\n        match goal with\n        | [H: IsNegativeAtom ?F |- _] => assert(~ IsNegativeAtom F)\n            by (try(apply IsNegativeOne) ;\n                try(apply IsNegativeBot) ;\n                try(apply IsNegativeTop) ;\n                try(apply IsNegativeZero) ;\n                try(apply IsNegativeTensor) ;\n                try(apply IsNegativePlus) ;\n                try(apply IsNegativeWith) ;\n                try(apply IsNegativePar) ;\n                try(apply IsNegativeBang) ;\n                try(apply IsNegativeQuest) ;\n                try(apply IsNegativeEx);\n                try(apply IsNegativeFx)\n               ) ; contradiction\n                     \n        end\n      ).\n\n  (* Solves goals when there is an hipthesis Release(F) and F cannot be released. *)\n  Ltac invRel :=\n    try(\n        match goal with\n        | [H: Release ?F |- _] => assert(~ Release F)\n            by (\n                try(apply NotRelTensor);\n                try(apply NotRelPlus);\n                try(apply NotRelBang);\n                try(apply NotRelEx);\n                try(apply NotRelOne);\n                try(apply NotRelZero)\n              );contradiction\n        end).\n\nEnd Syntax_LL. \n\n\n(*****************************************)\n(* Module to be imported for LL Formulas *)\n(*****************************************) \nModule FormulasLL (DT : Eqset_dec_pol).\n  Module Export Sy := Syntax_LL DT.\n  \n  Module lexp_eq <: Eqset_dec.\n    Definition A := Lexp.\n    Definition eqA_dec := FEqDec.\n  End lexp_eq.  \n  \n  Hint Rewrite Neg2pos Ng_involutive.\n  Hint Resolve wt_refl wt_symm wt_trans.\n  Hint Constructors Asynchronous.\n  Hint Resolve l_nil l_sin l_cos.\n  Hint Constructors release.\n  Hint Constructors NotAsynchronous.\n  Hint Constructors posOrNegAtom.\n\n  Declare Module Export MSetList : MultisetList lexp_eq.\n\n  (* Some aditional Properties using multisets of formulas *)\n  Lemma LPos1 (L M :list Lexp)  : L =mul= M -> LexpPos L -> LexpPos M.\n  Proof.\n    intros P H.\n    apply lexpPos_lexpPos'.\n    apply lexpPos_lexpPos' in H.\n    apply Permutation_meq in P.\n    induction P; subst.\n    * apply l_nil.\n    * inversion H; subst.\n      apply l_cos; auto.\n      apply l_cos; auto.\n    * inversion_clear H.\n      inversion_clear H1. \n      apply l_cos; auto.\n      apply l_cos; auto.\n    * apply IHP2.\n      apply IHP1;auto.\n  Qed.\n\n  Instance lexpPos_morph : Proper (meq ==> iff) (LexpPos ).\n  Proof.\n    intros L M Heq .\n    split;intro.\n    + eapply LPos1;eauto.\n    + apply LPos1 with (L:=M);auto.\n  Qed.\n  \n  Lemma LPos2 : forall M N L, L =mul= M ++ N -> LexpPos L -> LexpPos M.\n  Proof.\n    induction M;intros;simpl;auto.\n    assert (L =mul= M ++ (a::N)) by solve[rewrite H; solve_permutation].\n    apply IHM in H1;auto.\n    firstorder.\n    apply LPos1 in H;auto.\n    inversion H;auto.\n  Qed.\n\n  Lemma LPos3:  forall M N L, L =mul= M ++ N -> LexpPos L -> LexpPos N .\n  Proof.\n    intros.\n    rewrite union_comm in H.\n    eapply LPos2 ;eassumption.\n  Qed.\n\n  Lemma LexpPosConc : forall M F, LexpPos M -> ~ Asynchronous F ->  LexpPos (M ++ [F]).\n    intros.\n    assert(M ++ [F] =mul= [F] ++ M) by solve_permutation.\n    rewrite H1.\n    constructor;auto.\n    apply AsyncEqNeg;auto.\n  Qed.\n\n  Lemma LexpPosCons : forall F L, LexpPos (F :: L) -> LexpPos L.\n    intros.\n    inversion H.\n    auto.\n  Qed.\n  \n\n  Lemma LexpPosOrNegAtomConc : forall M F,  LexpPos M ->  PosOrNegAtom F ->  LexpPos (M ++ [F]).\n    intros.\n    assert(HS : M ++ [F] =mul= [F] ++ M) by solve_permutation.\n    rewrite HS.\n    constructor;auto using PosOrNegAtomAsync.\n  Qed.\n  \nEnd FormulasLL.\n\n\n\n", "meta": {"author": "brunofx86", "repo": "LL", "sha": "683f743c9e2dc6b796b2e3a071594a59d0b53923", "save_path": "github-repos/coq/brunofx86-LL", "path": "github-repos/coq/brunofx86-LL/LL-683f743c9e2dc6b796b2e3a071594a59d0b53923/FOLL/LL/SyntaxLL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.6634073958926536}}
{"text": "From Coq Require Import Arith.\nFrom Coq Require Import Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.Classical_Prop.\nRequire Import Classical_Prop Classical_Pred_Type.\nRequire Import Logic.Classical_Prop.\nRequire Import Classical.\nFrom Coq Require Import omega.Omega.\nRequire Import Nat.\nRequire Import List.\nRequire Import FunInd.\nRequire Import Recdef.\nRequire Export Coq.Program.Wf.\n\n\n\n\n\nLtac inv H := inversion H; clear H; subst.\n\nLemma exists_not_forall : forall (X : Type) (P : X -> Prop),\n  (exists x, ~ P x) -> ~ (forall x, P x).\nProof.\n  intros. intro. inversion H. auto.\nQed.\n\nLemma not_forall_exists : forall (X : Type) (P : X -> Prop),\n  ~ (forall x, P x) -> (exists x, ~ P x).\nProof.\n  intros. apply Peirce. intros. exfalso.\n  unfold not in H. apply H. intros.\n  apply Peirce. intros. exfalso. apply H0.\n  exists x. auto.\nQed.\n\nLemma not_exists_forall : forall (X : Type) (P : X -> Prop),\n  ~ (exists x, P x) -> (forall x, ~ P x).\nProof.\n  intros. destruct (classic (P x)).\n  - assert (exists x, P x). exists x. auto.\n  contradiction.\n  - auto.\nQed.\n\nLemma not_false_true : forall (P : Prop),\n  (~ (P -> False)) -> P.\nProof.\n  intros. unfold not in H. destruct (classic P).\n  auto. unfold not in H0. apply H in H0. contradiction.\nQed.\n\n\n\n(* Maps *)\n\nDefinition total_map (A : Type) := nat -> A.\n\nDefinition t_empty {A : Type} (v : A) : total_map A :=\n  (fun _ => v).\n\nDefinition t_update {A : Type} (m : total_map A)\n                    (x : nat) (v : A) :=\n  fun x' => if beq_nat x x' then v else m x'.\n\nNotation \"'_' '!->' v\" := (t_empty v)\n  (at level 100, right associativity).\n\nNotation \"x '!->' v ';' m\" := (t_update m x v)\n                              (at level 100, v at next level, right associativity).\n\n\nLemma t_apply_empty : forall (A : Type) (x : nat) (v : A),\n    (_ !-> v) x = v.\nProof.\n  intros. auto. Qed.\n\n\nLemma t_update_eq : forall (A : Type) (m : total_map A) x v,\n    (x !-> v ; m) x = v.\nProof.\n  intros. unfold t_update. rewrite <- beq_nat_refl. auto.\nQed.\n\nLemma eqb_true_iff : forall (x y : nat), x = y -> (x =? y) = true.\nProof.\n  intros. rewrite H. rewrite Nat.eqb_refl. auto.\nQed.\n\nLemma eqb_false_iff : forall (x y : nat), x <> y -> (x =? y) = false.\nProof.\n  intros. pose (Nat.eqb_neq x y). destruct i. apply H1 in H. auto.\nQed.\n\n\nTheorem t_update_neq : forall (A : Type) (m : total_map A) x1 x2 v,\n    x1 <> x2 ->\n    (x1 !-> v ; m) x2 = m x2.\nProof.\n  intros. unfold t_update. rewrite eqb_false_iff. auto. auto.\nQed.\n\nLemma t_update_shadow : forall (A : Type) (m : total_map A) x v1 v2,\n    (x !-> v2 ; x !-> v1 ; m) = (x !-> v2 ; m).\nProof.\n  intros. apply functional_extensionality_dep.\n  intros. unfold t_update. pose (classic (x = x0)).\n  destruct o.\n  - subst. rewrite <- beq_nat_refl. auto.\n  - apply eqb_false_iff in H. rewrite H. auto.\nQed.\n\n\n\nTheorem t_update_same : forall (A : Type) (m : total_map A) x,\n    (x !-> m x ; m) = m.\nProof.\n  intros. apply functional_extensionality_dep.\n  intros. pose (classic (x = x0)). destruct o; unfold t_update.\n  - rewrite eqb_true_iff; auto.\n  - rewrite eqb_false_iff; auto.\nQed.\n\n\n\nTheorem t_update_permute : forall (A : Type) (m : total_map A)\n                                  v1 v2 x1 x2,\n    x2 <> x1 ->\n    (x1 !-> v1 ; x2 !-> v2 ; m)\n    =\n    (x2 !-> v2 ; x1 !-> v1 ; m).\nProof.\n  intros. apply functional_extensionality_dep.\n  intros. destruct (classic (x = x1)); destruct (classic (x = x2)); subst.\n  - destruct H. auto.\n  - repeat (rewrite t_update_eq). rewrite t_update_neq. rewrite t_update_eq; auto. auto.\n  - rewrite t_update_neq; auto. rewrite t_update_eq. rewrite t_update_eq. auto.\n  - repeat (rewrite t_update_neq; auto).\nQed.\n\n\nDefinition partial_map (A : Type) := total_map (option A).\n\nDefinition empty {A : Type} : partial_map A :=\n  t_empty None.\n\nDefinition update {A : Type} (m : partial_map A)\n           (x : nat) (v : A) :=\n  (x !-> Some v ; m).\n\n(** We introduce a similar notation for partial maps: *)\nNotation \"x '|->' v ';' m\" := (update m x v)\n  (at level 100, v at next level, right associativity).\n\n(** We can also hide the last case when it is empty. *)\nNotation \"x '|->' v\" := (update empty x v)\n  (at level 100).\n\nLemma update_eq : forall (A : Type) (m : partial_map A) x v,\n    (x |-> v ; m) x = Some v.\nProof.\n  intros. unfold update. rewrite t_update_eq.\n  reflexivity.\nQed.\n\nTheorem update_neq : forall (A : Type) (m : partial_map A) x1 x2 v,\n    x2 <> x1 ->\n    (x2 |-> v ; m) x1 = m x1.\nProof.\n  intros A m x1 x2 v H.\n  unfold update. rewrite t_update_neq. reflexivity.\n  apply H. Qed.\n\nLemma update_shadow : forall (A : Type) (m : partial_map A) x v1 v2,\n    (x |-> v2 ; x |-> v1 ; m) = (x |-> v2 ; m).\nProof.\n  intros A m x v1 v2. unfold update. rewrite t_update_shadow.\n  reflexivity.\nQed.\n\nTheorem update_same : forall (A : Type) (m : partial_map A) x v,\n    m x = Some v ->\n    (x |-> v ; m) = m.\nProof.\n  intros A m x v H. unfold update. rewrite <- H.\n  apply t_update_same.\nQed.\n\nTheorem update_permute : forall (A : Type) (m : partial_map A)\n                                x1 x2 v1 v2,\n    x2 <> x1 ->\n    (x1 |-> v1 ; x2 |-> v2 ; m) = (x2 |-> v2 ; x1 |-> v1 ; m).\nProof.\n  intros A m x1 x2 v1 v2. unfold update.\n  apply t_update_permute.\nQed.\n\n\nDefinition eq_context (A : Type) (c1 c2 : partial_map A) :=\n  forall (n : nat), (c1 n) = (c2 n).\n\nDefinition contained (A : Type) (c1 c2 : partial_map A) :=\n  forall (n : nat) (a : A), c1 n = Some a -> c2 n = Some a.\n\nLemma eq_context_eq : forall (A : Type) (c1 c2 : partial_map A),\n  eq_context A c1 c2 -> c1 = c2.\nProof.\n  intros. apply functional_extensionality_dep. unfold eq_context in H.\n   auto.\nQed.\n\n\n(************************* L1 ******************************)\n\n\n(* Abstract Syntax *)\n\nInductive op :=\n  | op_arith : (nat -> nat -> nat) -> op\n  | op_comp  : (nat -> nat -> bool) -> op.\n\nInductive type : Type :=\n  | type_nat : type\n  | type_bool : type\n  | type_fun : type -> type -> type.\n\n\nInductive term :=\n  | t_num  : nat -> term\n  | t_bool : bool -> term\n  | t_op   : term -> op -> term -> term\n  | t_if   : term -> term -> term -> term\n  | t_var  : nat -> term\n  | t_app  : term -> term -> term\n  | t_fun  : nat -> type -> term -> term\n  | t_let  : nat -> type -> term -> term -> term\n  | t_rec  : nat -> type -> type -> nat -> term -> term -> term.\n\nInductive value : term -> Prop :=\n  | val_nat : forall n : nat , value (t_num n)\n  | val_bool : forall b : bool, value (t_bool b)\n  | val_fun : forall (x: nat) (t: type), forall e: term, value (t_fun x t e).\n\n\n\n(* Substitution *)\nReserved Notation \"'[' x ':=' s ']' t\" (at level 20).\nFixpoint f_subst (x : nat) (s : term) (t : term) : term :=\n  match t with\n  | (t_num n) => t_num n\n  | (t_bool b) => t_bool b\n  | (t_op t1 op t2) => t_op ([x:=s]t1) op ([x:=s]t2)\n  | (t_if t1 t2 t3) => t_if ([x:=s]t1) ([x:=s]t2) ([x:=s]t3)\n  | (t_var y) => if beq_nat x y then s else t\n  | (t_app t1 t2) => t_app ([x:=s]t1) ([x:=s]t2)\n  | (t_fun y T f) => if beq_nat x y then t else t_fun y T ([x:=s]f)\n  | (t_let y T t1 t2) => if beq_nat x y then t_let y T ([x:=s]t1) t2 else t_let y T ([x:=s]t1) ([x:=s]t2)\n  | (t_rec f T1 T2 y e1 e2) => t_rec f T1 T2 y (if beq_nat x f then e1 else\n    (if beq_nat x y then e1 else ([x:=s] e1)) ) (if beq_nat x y then e2 else ([x:=s] e2))\nend\n\nwhere \"'[' x ':=' s ']' t\" := (f_subst x s t).\n\n\n\n\n(* Operational Semantics *)\n\nReserved Notation \"A ---> B\" (at level 90, no associativity).\nInductive step : term -> term -> Prop :=\n  | e_op1      : forall (o : op), forall (e1 e2 e1' : term),\n      e1 ---> e1' -> (t_op e1 o e2) ---> (t_op e1' o e2)\n\n  | e_op2      : forall (o : op), forall (e1 e2 e2' : term),\n      e2 ---> e2' -> value e1 -> (t_op e1 o e2) ---> (t_op e1 o e2')\n\n  | e_op_arith : forall (n1 n2 : nat) (f : (nat -> nat -> nat)),\n      (t_op (t_num n1) (op_arith f) (t_num n2)) ---> t_num (f n1 n2)\n\n  | e_op_comp  : forall (n1 n2 : nat) (f : (nat -> nat -> bool)),\n      (t_op (t_num n1) (op_comp f) (t_num n2)) ---> t_bool (f n1 n2)\n\n  | e_if_t     : forall (e2 e3 : term), (t_if (t_bool true) e2 e3) ---> e2\n  | e_if_f     : forall (e2 e3 : term), (t_if (t_bool false) e2 e3) ---> e3\n  | e_if       : forall (e1 e1' e2 e3 : term),\n      e1 ---> e1' -> (t_if e1 e2 e3) ---> (t_if e1' e2 e3)\n\n  | e_beta     : forall (x : nat) (T : type) (e v : term), value v -> t_app (t_fun x T e) v ---> [x:=v]e\n  | e_app2     : forall (e1 e2 e2' : term),\n      e2 ---> e2' -> value e1 -> (t_app e1 e2) ---> (t_app e1 e2')\n\n  | e_app1     : forall (e1 e2 e1' : term),\n      e1 ---> e1' -> (t_app e1 e2) ---> (t_app e1' e2)\n\n  | e_let1     : forall (x : nat), forall (T : type), forall (v e : term),\n      value v -> t_let x T v e ---> [x:=v]e\n\n  | e_let2     : forall (x : nat), forall (T : type), forall (e1 e1' e2 : term),\n      e1 ---> e1' -> t_let x T e1 e2 ---> t_let x T e1' e2\n\n  | e_rec      : forall (f y : nat) (T1 T2 : type) (e1 e2 : term),\n      t_rec f T1 T2 y e1 e2 ---> [f:=(t_fun y T1 (t_rec f T1 T2 y e1 e1))]e2\n\nwhere \"A ---> B\" := (step A B).\n\n\n\n\n(* Type system *)\n\n\nDefinition context := partial_map type.\n\n\nReserved Notation \"G |: A ===> B\" (at level 90, no associativity).\nInductive check : context -> term -> type -> Prop :=\n  | tp_num   : forall (n : nat) (g : context), g |: t_num n ===> type_nat\n\n  | tp_bool  : forall (b : bool) (g : context), g |: t_bool b ===> type_bool\n\n  | tp_arith : forall (f : nat -> nat -> nat) (g : context) (e1 e2 : term),\n      (g |: e1 ===> type_nat) -> (g |: e2 ===> type_nat) -> \n       g |: (t_op e1 (op_arith f) e2) ===> type_nat\n\n  | tp_comp  : forall (f : nat -> nat -> bool) (g : context) (e1 e2 : term),\n      (g |: e1 ===> type_nat) -> (g |: e2 ===> type_nat) ->\n       g |: (t_op e1 (op_comp f) e2) ===> type_bool\n\n  | tp_if    : forall (t1 t2 t3 : term) (g : context) (T : type),\n      (g |: t1 ===> type_bool) -> (g |: t2 ===> T) -> (g |: t3 ===> T) -> g |: t_if t1 t2 t3 ===> T\n  | tp_var   : forall (n : nat) (g : context) (T : type), g n = Some T -> g |: t_var n ===> T\n  | tp_fun   : forall (x : nat) (g : context) (T T' : type) (e : term),\n      (x |-> T ; g) |: e ===> T' -> g |: (t_fun x T e) ===> (type_fun T T')\n  | tp_app   : forall (e1 e2 : term) (g : context) (T T' : type),\n      g |: e1 ===> (type_fun T T') -> g |: e2 ===> T -> g |: (t_app e1 e2) ===> T'\n  | tp_let   : forall (x : nat) (e1 e2 : term) (T T' : type) (g : context),\n      g |: e1 ===> T -> (x |-> T ; g) |: e2 ===> T' -> g |: (t_let x T e1 e2) ===> T'\n  | tp_rec   : forall (f x : nat) (T1 T2 T : type) (e1 e2 : term) (G : context),\n      f <> x ->\n      (x |-> T1 ; (f |-> type_fun T1 T2; G)) |: e1 ===> T2 ->\n      (f |-> type_fun T1 T2 ; G) |: e2 ===> T ->\n      G |: t_rec f T1 T2 x e1 e2 ===> T\n\nwhere \"G |: A ===> B\" := (check G A B).\n\n\n\n\n\n(* Properties *)\n\n\n\n\nLemma value_nat_is_num : forall (g : context) (t : term),\n  g |: t ===> type_nat -> value t -> exists n: nat, t = t_num n.\nProof.\n  intros. inversion H0; subst. exists n. auto.\n  inversion H. inversion H.\nQed.\n\nLemma value_bool_is_bool : forall (g : context) (t : term),\n  g |: t ===> type_bool -> value t -> (t = t_bool true) \\/ (t = t_bool false).\nProof.\n  intros. inversion H0; subst.\n  - inversion H.\n  - destruct b. auto. auto.\n  - inversion H.\nQed.\n\nLemma value_fun_is_fun : forall (g : context) (t : term) (T T' : type),\n  g |: t ===> (type_fun T T') -> value t ->\n  exists (x : nat) (e : term), t = (t_fun x T e).\nProof.\n  intros. inversion H0; subst.\n  - inversion H.\n  - inversion H.\n  - exists x. exists e. assert (T = t0).\n    + inversion H. subst. auto.\n    +  subst. auto.\nQed.\n\n\nTheorem progress: forall (t : term) (T : type),\n  empty |: t ===> T -> value t \\/ exists t':term, t ---> t'.\nProof.\nHint Constructors step.\nHint Constructors check.\nHint Constructors term.\nHint Constructors value.\nHint Constructors type.\nHint Constructors op.\n\n\n\n  intros. remember (@empty type) as gamma. induction H; auto;\n  right; auto; try (pose (IHcheck1 Heqgamma)); try (pose (IHcheck2 Heqgamma));\n  try (pose (IHcheck3 Heqgamma)).\n  - destruct o; destruct o0; clear IHcheck1; clear IHcheck2.\n    + subst. eapply value_nat_is_num in H1. eapply value_nat_is_num in H2.\n      inv H1. inv H2. exists (t_num (f x x0)). auto. apply H0. apply H.\n    + subst. inv H2. exists (t_op e1 (op_arith f) x). auto.\n    + subst. inv H1. exists (t_op x (op_arith f) e2). auto.\n    + inv H1. exists (t_op x (op_arith f) e2). auto.\n  - subst. destruct o; destruct o0; clear IHcheck1; clear IHcheck2.\n    + eapply value_nat_is_num in H; eapply value_nat_is_num in H0; auto.\n      inv H0. inv H. exists (t_bool (f x0 x)). auto.\n    + inv H2. exists (t_op e1 (op_comp f) x). auto.\n    + inv H1. exists (t_op x (op_comp f) e2). auto.\n    + inv H1. exists (t_op x (op_comp f) e2). auto.\n  - destruct o. eapply value_bool_is_bool in H2.\n    destruct H2. exists t2. rewrite H2. auto.\n    exists t3. rewrite H2. auto. apply H.\n    inv H2. exists (t_if x t2 t3). auto.\n  - subst. inv H.\n  - destruct o; destruct o0; clear IHcheck1; clear IHcheck2.\n    apply value_fun_is_fun with (g := empty) (T := T) (T' := T') in H1.\n    inv H1. inv H3. exists ([x:=e2]x0). auto.\n    subst. auto. inv H2. exists (t_app e1 x). auto.\n    inv H1. exists (t_app x e2). auto.\n    inv H1. exists (t_app x e2). auto.\n  - destruct o; clear IHcheck1; clear IHcheck2.\n    + exists ([x:=e1]e2). auto.\n    + inv H1. exists (t_let x T x0 e2). auto.\n  - subst. clear IHcheck1; clear IHcheck2.\n    exists ([f:=(t_fun x T1 (t_rec f T1 T2 x e1 e1))]e2).\n    auto.\nQed.\n\n\nInductive appears_free_in : nat -> term -> Prop :=\n  | afi_var  : forall x, appears_free_in x (t_var x)\n  | afi_op1  : forall x t1 t2 o,\n      appears_free_in x t1 -> appears_free_in x (t_op t1 o t2)\n  | afi_op2  : forall x t1 t2 o,\n      appears_free_in x t2 -> appears_free_in x (t_op t1 o t2)\n  | afi_if1  : forall x t1 t2 t3,\n      appears_free_in x t1 -> appears_free_in x (t_if t1 t2 t3)\n  | afi_if2  : forall x t1 t2 t3,\n      appears_free_in x t2 -> appears_free_in x (t_if t1 t2 t3)\n  | afi_if3  : forall x t1 t2 t3,\n      appears_free_in x t3 -> appears_free_in x (t_if t1 t2 t3)\n  | afi_app1 : forall x t1 t2,\n      appears_free_in x t1 -> appears_free_in x (t_app t1 t2)\n  | afi_app2 : forall x t1 t2,\n      appears_free_in x t2 -> appears_free_in x (t_app t1 t2)\n  | afi_fun  : forall f x T t,\n      f <> x -> appears_free_in x t ->\n      appears_free_in x (t_fun f T t)\n  | afi_let1 : forall x e T t1 t2,\n      appears_free_in x t1 ->\n      appears_free_in x (t_let e T t1 t2)\n  | afi_let2 : forall x e T t1 t2,\n      e <> x ->\n      appears_free_in x t2 ->\n      appears_free_in x (t_let e T t1 t2)\n  | afi_rec1 : forall x f T1 T2 y e1 e2,\n      y <> x ->\n      f <> x ->\n      appears_free_in x e1 ->\n      appears_free_in x (t_rec f T1 T2 y e1 e2)\n  | afi_rec2 : forall x f T1 T2 y e1 e2,\n      f <> x ->\n      appears_free_in x e2 ->\n      appears_free_in x (t_rec f T1 T2 y e1 e2).\n\nDefinition closed (t: term) :=\n  forall x, ~ (appears_free_in x t).\n\n\nLemma free_in_context : forall x t T Gamma,\n  appears_free_in x t ->\n  Gamma |: t ===> T ->\n  exists T', Gamma x = Some T'.\nProof.\n  intros. generalize dependent Gamma.\n  generalize dependent T.\n  induction H; intros; try solve [inversion H0; eauto].\n  - inversion H1; subst. apply IHappears_free_in in H7.\n    rewrite update_neq in H7; auto.\n  - inversion H1; subst. apply IHappears_free_in in H9.\n    rewrite update_neq in H9; auto.\n  - inversion H2; subst. apply IHappears_free_in in H12; auto.\n    rewrite update_neq in H12; auto. rewrite update_neq in H12; auto.\n  - inversion H1; subst. apply IHappears_free_in in H12.\n    rewrite update_neq in H12; auto.\nQed.\n\nCorollary typable_empty_closed : forall t T,\n    empty |: t ===> T  ->\n    closed t.\nProof.\n  intros. unfold closed. intros. intro. generalize dependent T.\n  induction H0; intros; try inversion H; subst; auto; try (solve [inversion H2]);\n    eapply IHappears_free_in; eauto.\n  - inversion H1; subst; auto. pose (free_in_context x t T' (f |-> T) H0 H7).\n    inversion e; subst; auto. unfold update in H2. unfold t_update in H2.\n    Search eqb. apply eqb_false_iff in H. rewrite H in H2.\n    inversion H2.\n  - inversion H1; subst; auto. pose (free_in_context x t2 T0 (e|->T) H0\n    H9). inversion e0. unfold update in H2. unfold t_update in H2.\n    apply eqb_false_iff in H. rewrite H in H2. inversion H2.\n  - inversion H2; subst; auto.\n    apply free_in_context with (T := T2) (Gamma := (y |-> T1; f |-> type_fun T1 T2)) in H1.\n    inv H1. rewrite update_neq in H3. rewrite update_neq in H3. inv H3.\n    auto. auto. auto.\n  - inv H1. apply free_in_context with (T := T) (Gamma := (f |-> type_fun T1 T2)) in H0.\n    inv H0. rewrite update_neq in H1. inv H1. auto. auto.\n  Unshelve. apply T. apply T. apply T. apply T. Qed.\n\n  \n  \n  \n  \n\nLemma context_invariance : forall Gamma Gamma' t T,\n     Gamma |: t ===> T  ->\n     (forall x, appears_free_in x t -> Gamma x = Gamma' x) ->\n     Gamma' |: t ===> T.\nProof.\n  intros. generalize dependent Gamma'.  induction H; intros; auto.\n  - apply tp_arith; [apply IHcheck1 | apply IHcheck2]; intros; apply H1;\n    [apply afi_op1 | apply afi_op2]; auto.\n  - apply tp_comp; [apply IHcheck1 | apply IHcheck2]; intros; apply H1;\n    [apply afi_op1 | apply afi_op2]; auto.\n  - apply tp_if; [apply IHcheck1 | apply IHcheck2 | apply IHcheck3]; intros;\n    apply H2; [apply afi_if1 | apply afi_if2 | apply afi_if3];\n    auto.\n  - apply tp_var. rewrite <- H0. auto.\n    apply afi_var.\n  - apply tp_fun. apply IHcheck. intros.\n    unfold update. unfold t_update. destruct eqb eqn:eqxx0.\n    auto. apply H0. apply afi_fun. rewrite Nat.eqb_neq in eqxx0.\n    auto. auto.\n  - apply tp_app with (T := T) (T' := T').\n    apply IHcheck1. intros. apply H1. apply afi_app1.\n    auto. apply IHcheck2. intros. apply H1. apply afi_app2.\n    auto.\n  - apply tp_let. apply IHcheck1. intros. apply H1.\n    apply afi_let1. auto. apply IHcheck2.\n    intros. unfold update. unfold t_update.\n    destruct eqb eqn:eqxx0. auto. apply H1. apply afi_let2.\n    rewrite Nat.eqb_neq in eqxx0. auto. auto.\n  - apply tp_rec. auto. apply IHcheck1. intros.\n    unfold update. unfold t_update. destruct (x =? x0) eqn:eqxx0;\n    destruct (f =? x0) eqn:eqfx0.\n    auto. auto. auto. apply H2. apply afi_rec1. rewrite <- Nat.eqb_neq.\n    auto. rewrite <- Nat.eqb_neq. auto. auto.\n    apply IHcheck2. intros. unfold update. unfold t_update.\n    destruct (f =? x0) eqn:eqfx0. auto. apply H2.\n    apply afi_rec2. rewrite <- Nat.eqb_neq. auto. auto.\nQed.\n\n\n\nLemma substitution_lemma : forall Gamma x U t v T,\n  (x |-> U ; Gamma) |: t ===> T ->\n  empty |: v ===> U   ->\n  Gamma |: [x:=v]t ===> T.\nProof.\n  intros. generalize dependent T. generalize dependent Gamma.\n  induction t; intros; auto; simpl.\n  - eapply context_invariance. apply H. intros.\n    inv H1.\n  - eapply context_invariance. apply H. intros.\n    inv H1.\n  - inv H; [eapply tp_arith; apply IHt1 in H6; auto | eapply tp_comp; apply IHt2 in H7; auto].\n  - inv H. apply tp_if; [apply IHt1 in H5 |\n    apply IHt2 in H7 | apply IHt3 in H8]; auto.\n  - destruct (x =? n) eqn:Heqx. rewrite Nat.eqb_eq in Heqx.\n    subst. inv H. rewrite update_eq in H3. inv H3.\n    eapply context_invariance in H0. apply H0.\n    intros. apply typable_empty_closed in H0.\n    unfold closed in H0. apply H0 in H. inv H.\n    eapply context_invariance in H. apply H.\n    intros. rewrite Nat.eqb_neq in Heqx.\n    inv H1. rewrite update_neq; auto.\n  - inv H. eapply tp_app. apply IHt1. apply H4.\n    apply IHt2. auto.\n  - destruct (x =? n) eqn:Heq. rewrite Nat.eqb_eq in Heq.\n    subst. inv H. eapply tp_fun. rewrite update_shadow in H6.\n    auto. inv H. eapply tp_fun. apply IHt.\n    rewrite Nat.eqb_neq in Heq. rewrite update_permute.\n    auto. auto.\n  - destruct (x =? n) eqn:Heq. rewrite Nat.eqb_eq in Heq.\n    subst. eapply tp_let. apply IHt1. inv H.\n    apply H7. inv H. rewrite update_shadow in H8. auto.\n    rewrite Nat.eqb_neq in Heq. eapply tp_let. apply IHt1.\n    inv H. auto. apply IHt2. inv H. rewrite update_permute.\n    auto. auto.\n  - destruct (x =? n) eqn:Heq1; destruct (x =? n0) eqn:Heq2.\n    + rewrite Nat.eqb_eq in Heq1. rewrite Nat.eqb_eq in Heq2.\n      subst. inv H. destruct H9. auto.\n    + rewrite Nat.eqb_eq in Heq1. subst.\n      inv H. eapply tp_rec. auto. rewrite update_shadow in H10.\n      auto. apply IHt2. clear Heq2.\n      eapply context_invariance.\n      apply H11. intros. rewrite update_same in H11. Admitted.\n\n\nTheorem preservation : forall (t t' : term) (T : type),\n  empty |: t ===> T -> t ---> t' -> empty |: t' ===> T.\nProof.\n  intros t t' T Ht. remember (@empty type) as g. generalize dependent t'.\n  induction Ht; intros t' He; try subst g; subst;\n  try solve [inversion He; subst; auto].\n  - pose (IHHt1 eq_refl). pose (IHHt2 eq_refl).\n    inversion He; subst.\n    Admitted.\n\n\nNotation \"A :: B\" := (cons A B).\nNotation \"[]\" := nil.\nNotation \"[[ A ]]\" := (A :: nil).\n\n\n\nDefinition ident := nat.\nDefinition int := nat.\n\nDefinition lookup_list (A : Type) := list (ident * A).\n\n\nFixpoint lookup (A : Type) (x: ident) (l : lookup_list A) : option A :=\n  match l with\n  | nil => None\n  | ((y, v) :: ys) => if (beq_nat x y) then Some v\n    else lookup A x ys\n  end.\n\nInductive Instruction : Type :=\n  | INT : int -> Instruction\n  | BOOL : bool -> Instruction\n  | POP : Instruction\n  | COPY : Instruction\n  | ADD : Instruction\n  | EQ : Instruction\n  | GT : Instruction\n  | AND : Instruction\n  | NOT : Instruction\n  | JUMP : nat -> Instruction\n  | JUMPIFTRUE : nat -> Instruction\n  | VAR : ident -> Instruction\n  | FUN : ident -> list Instruction -> Instruction\n  | RFUN : ident -> ident -> list Instruction -> Instruction\n  | APPLY : Instruction.\n\n\nInductive StorableValue : Type :=\n  | st_int : int -> StorableValue\n  | st_bool : bool -> StorableValue\n  | st_clos : Environment -> ident -> list Instruction -> StorableValue\n  | st_rec_clos : Environment -> ident -> ident -> list Instruction -> StorableValue\n  with Environment : Type :=\n  | env : (lookup_list StorableValue) -> Environment.\n\nDefinition Code := list Instruction.\n\nFixpoint code_length (c : Code) : nat :=\n  length c.\n\nFixpoint env_length (e: Environment) : nat :=\n  match e with\n  | env e' => length e'\n  end.\n\nFixpoint sv_size (sv : StorableValue) : nat :=\n  match sv with\n  | st_int _ => 1\n  | st_bool _ => 1\n  | st_clos e _ c => 1 + (env_length e) + (code_length c)\n  | st_rec_clos e _ _ c => 1 + (env_length e) + (code_length c)\n  end.\n\nDefinition Stack := list StorableValue.\nDefinition Dump := list (Code * Stack * Environment).\nDefinition State : Type := (Code * Stack * Environment * Dump).\n\nDefinition initial_state (c: Code) : State :=\n  (c, [], env [], []).\n\n\n\nScheme sv_mut := Induction for StorableValue Sort Prop\nwith env_mut := Induction for Environment Sort Prop.\n\n\nReserved Notation \"A |> B\" (at level 90, no associativity).\nInductive SSM_OP : State -> State -> Prop :=\n  | push_int : forall (z : int), forall (c : list Instruction),\n           forall (s : Stack), forall (e : Environment),\n           forall (d : Dump),\n    ((cons (INT z) c), s, e, d) |> (c, cons (st_int z) s, e, d)\n  | push_bool : forall (b : bool), forall (c : list Instruction),\n           forall (s : Stack), forall (e : Environment),\n           forall (d : Dump),\n    ((cons (BOOL b) c), s, e, d) |> ( c, cons (st_bool b) s, e, d)\n  | pop_value : forall (c : list Instruction),\n                forall (sv : StorableValue), forall (s : Stack),\n                forall (e : Environment), forall (d : Dump),\n    ( (cons POP c), cons sv s, e, d) |> ( c, s, e, d)\n  | copy_value : forall (c : list Instruction),\n                forall (sv : StorableValue), forall (s : Stack),\n                forall (e : Environment), forall (d : Dump),\n    ( (cons COPY c), cons sv s, e, d) |> ( c, cons sv (cons sv s), e, d)\n  | add_value : forall (c : list Instruction),\n                forall (z1 z2 : int), forall (s : Stack),\n                forall (e: Environment), forall (d: Dump),\n     ( (cons ADD c), cons (st_int z1) (cons (st_int z2) s), e, d)\n     |> ( c, cons (st_int (z1 + z2)) s, e, d)\n  \n  | eq_value :  forall (c : list Instruction),\n                forall (z1 z2 : int), forall (s : Stack),\n                forall (e: Environment), forall (d: Dump),\n                ( (EQ :: c), st_int z1 :: st_int z2 :: s, e, d)\n                |> ( c, st_bool (beq_nat z1 z2) :: s, e, d)\n\n  | gt_value: forall (c: list Instruction),\n              forall (z1 z2 : int), forall (s: Stack),\n              forall (e: Environment), forall (d: Dump),\n              ( (GT :: c), st_int z1 :: st_int z2 :: s, e, d)\n              |> ( c, st_bool (negb (z1 <? z2)) :: s, e, d)\n\n  | and_value : forall (c : list Instruction),\n              forall (b1 b2 : bool), forall (s: Stack),\n              forall (e: Environment), forall (d: Dump),\n              ( (AND :: c), st_bool b1 :: st_bool b2 :: s, e, d)\n              |> ( c, st_bool (andb b1 b2) :: s, e, d)\n  | not_value : forall (c : list Instruction),\n              forall (b : bool), forall (s: Stack),\n              forall (e: Environment), forall (d: Dump),\n              ( (NOT :: c), st_bool b :: s, e, d)\n              |> ( c, st_bool (negb b) :: s, e, d)\n   | jump:    forall (c : list Instruction),\n              forall (s : Stack), forall (e: Environment),\n              forall (d : Dump), forall (n : nat),\n              (List.length c) >= n+1 ->\n              ( (JUMP n :: c), s, e, d) |>\n              ( (List.skipn n c), s, e, d)\n   | jump_true : forall (c : list Instruction),\n              forall (s : Stack), forall (e: Environment),\n              forall (d : Dump), forall (n : nat),\n              List.length c >= n+1 ->\n              ( (JUMPIFTRUE n :: c), st_bool true :: s, e, d)\n              |> ( (List.skipn n c), s, e, d)\n   | jump_false : forall (c : list Instruction),\n              forall (s : Stack), forall (e: Environment),\n              forall (d : Dump), forall (n : nat),\n              ( (JUMPIFTRUE n :: c), st_bool false :: s, e, d)\n              |> ( c, s, e, d)\n   | var_lookup : forall (c : list Instruction),\n              forall (s : Stack), forall (e: lookup_list StorableValue),\n              forall (d: Dump), forall (x : ident),\n              forall (sv : StorableValue), lookup StorableValue x e = Some sv -> \n              ( (VAR x :: c), s, env e, d) |>\n              ( c, sv :: s, env e, d)\n   | closure : forall (c : list Instruction), forall (c' : Code),\n              forall (x : ident), forall (e: lookup_list StorableValue), forall (d: Dump),\n              forall (s : Stack), ( (FUN x c' :: c), s, (env e), d) |>\n              ( c, (st_clos (env e) x c') :: s, (env e), d)\n   | r_closure : forall (c : list Instruction), forall (c' : Code),\n              forall (x f : ident), forall (e: lookup_list StorableValue), forall (d: Dump),\n              forall (s : Stack), ( (RFUN f x c' :: c), s, env e, d) |>\n              ( c, (st_rec_clos (env e) f x c') :: s, (env e), d)\n   | apply_normal : forall (c: list Instruction) (e' : lookup_list StorableValue)\n              (x : ident) (c' : Code) (sv : StorableValue) (s : Stack)\n              (e : Environment) (d : Dump),\n              ( (APPLY :: c), (st_clos (env e') x c') :: sv :: s, e, d)\n              |>\n              (c', nil, env ((x, sv) :: e'), ( c, s, e) :: d)\n    | apply_rec : forall (c: list Instruction) (e' : lookup_list StorableValue)\n              (x f : ident) (c' : Code) (sv : StorableValue) (s : Stack)\n              (e : Environment) (d : Dump),\n              ( (APPLY :: c), (st_rec_clos (env e') f x c') :: sv :: s, e, d)\n              |>\n              (c', nil, env ((f, st_rec_clos (env e') f x c') :: (x,sv) :: e'), ( c, s, e) :: d)\n    | pop_closure : forall (sv : StorableValue) (s' : Stack) (e e' : Environment)\n                    (c' : Code) (d : Dump),\n                    ( nil, sv :: nil, e, (c', s', e') :: d) |>\n                    (c', sv :: s', e', d)\n\n\nwhere \"A |> B\" := (SSM_OP A B).\n\nInductive state_value : State -> Prop :=\n  | s_value : forall (sv : StorableValue) (e  : Environment), \n  state_value ( nil, sv :: nil, e, nil).\n\nReserved Notation \"A |>* B\" (at level 90, no associativity).\nInductive SSM_OP_Star : State -> State -> Prop :=\n  | sos_refl : forall (s : State), s |>* s\n  | sos_trans : forall (s1 s2 s3 : State), s1 |> s2 -> s2 |>* s3 -> s1 |>* s3\nwhere \"A |>* B\" := (SSM_OP_Star A B).\n\n\n\n\nDefinition which_comp (op : nat -> nat -> bool) :=\n  match (op 1 1) with\n  | true => EQ\n  | false => GT\n  end.\n\nLemma which_comp_value : forall f, which_comp f = EQ \\/ which_comp f = GT.\nProof. intros. unfold which_comp. destruct (f 1 1). left. auto. right. auto.\nQed.\n\n\n\nFixpoint compile (t : term) : Code :=\nmatch t with\n  | t_num n =>  [[INT n]]\n  | t_bool b =>  [[BOOL b]]\n  | t_op t1 (op_arith _) t2 =>  (( (compile t1)) ++ ( (compile t2)) ++ [[ ADD ]])\n  | t_op t1 (op_comp c) t2 =>  (( (compile t1)) ++ ( (compile t2)) ++ [[ (which_comp c)]])\n  | t_if e1 e2 e3 =>  (\n                            ( (compile e1)) ++\n                            [[JUMPIFTRUE (code_length (compile e3))]] ++\n                            ( (compile e3)) ++\n                            [[JUMP (code_length (compile e2))]] ++\n                            ( (compile e2))\n                           )\n  | t_var x => [[VAR x]]\n  | t_app e1 e2 => (\n                          ( (compile e2)) ++\n                          ( (compile e1)) ++\n                          [[APPLY]]\n                        )\n  | t_fun y T e1 => [[FUN y (compile e1)]]\n  | t_let y T e1 e2 => (\n                              ( (compile e1)) ++\n                              [[FUN y (compile e2)]] ++\n                              [[APPLY]]\n                            )\n  | t_rec f T1 T2 y e1 e2 => (\n                                    (RFUN f y (compile e1)) ::\n                                    (FUN f (compile e2)) ::\n                                    APPLY :: nil)\nend.\n\nInductive multi_cost_language : term -> nat -> term -> Prop :=\n  | multi_costl_refl : forall (t: term), multi_cost_language t 0 t\n  | multi_costl_trans: forall (t1 t2 t3: term) (n: nat),\n      (t1 ---> t2) -> multi_cost_language t2 n t3 -> multi_cost_language t1 (n+1) t3.\n\nInductive multi_cost_code : State -> nat -> State -> Prop :=\n  | multi_costc_refl : forall (s : State), multi_cost_code s 0 s\n  | multi_costc_trans: forall (s1 s2 s3 : State) (n: nat),\n    (s1 |> s2) -> multi_cost_code s2 n s3 -> multi_cost_code s1 (n+1) s3.\n\nPrint term.\n\nInductive term_has_recursion : term -> Prop :=\n  | rec_has_rec : forall x t1 t2 y t3 t4, term_has_recursion (t_rec x t1 t2 y t3 t4)\n  | op_has_rec1 : forall t1 op t2, term_has_recursion t1 -> term_has_recursion (t_op t1 op t2)\n  | op_has_rec2 : forall t1 op t2, term_has_recursion t2 -> term_has_recursion (t_op t1 op t2)\n  | app_has_rec1 : forall t1 t2, term_has_recursion t1 -> term_has_recursion (t_app t1 t2)\n  | app_has_rec2 : forall t1 t2, term_has_recursion t2 -> term_has_recursion (t_app t1 t2)\n  | fun_has_rec : forall x tp t, term_has_recursion t -> term_has_recursion (t_fun x tp t)\n  | let_has_rec1 : forall x tp t1 t2, term_has_recursion t1 -> term_has_recursion (t_let x tp t1 t2)\n  | let_has_rec2 : forall x tp t1 t2, term_has_recursion t2 -> term_has_recursion (t_let x tp t1 t2)\n  | if_has_rec1 : forall t1 t2 t3, term_has_recursion t1 -> term_has_recursion (t_if t1 t2 t3)\n  | if_has_rec2 : forall t1 t2 t3, term_has_recursion t2 -> term_has_recursion (t_if t1 t2 t3)\n  | if_has_rec3 : forall t1 t2 t3, term_has_recursion t3 -> term_has_recursion (t_if t1 t2 t3).\n\nLemma not_rec_subst : forall x t1 t2, ~ term_has_recursion t1 -> ~ term_has_recursion t2 ->\n  ~ term_has_recursion ([x := t1] t2).\nProof.\n  induction t2.\n  - intros. intro. simpl in H1. inv H1.\n  - intros. intro. simpl in H1. inv H1.\n  - intros. assert (~ term_has_recursion t2_1). intro. apply H0. apply op_has_rec1. auto.\n    assert (~ term_has_recursion t2_2). intro. apply H0. apply op_has_rec2. auto.\n    apply IHt2_1 in H1. apply IHt2_2 in H2. intro. simpl in H3. inv H3. apply H1; auto.\n    apply H2; auto. auto. auto.\n  - intros. assert (~ term_has_recursion t2_1). intro. apply H0. apply if_has_rec1. auto.\n    assert (~ term_has_recursion t2_2). intro. apply H0. apply if_has_rec2. auto.\n    assert (~ term_has_recursion t2_3). intro. apply H0. apply if_has_rec3. auto.\n    intro. simpl in H4. inv H4. apply IHt2_1 in H1. apply H1. auto. auto.\n    apply IHt2_2 in H2. apply H2. auto. auto. apply IHt2_3. auto. auto.\n    auto.\n  - intros. intro. simpl in H1. destruct (x =? n) eqn:eq. apply H; auto.\n    apply H0; auto.\n  - intros. simpl. intro. assert (~ term_has_recursion t2_1). intro. apply H0.\n    apply app_has_rec1. auto. assert (~ term_has_recursion t2_2). intro. apply H0.\n    apply app_has_rec2. auto. inv H1. apply IHt2_1; auto. apply IHt2_2; auto.\n  - intros. simpl. intro. assert (~ term_has_recursion t2). intro. apply H0.\n    apply fun_has_rec. auto. destruct (x =? n) eqn:eq. apply H0; auto. inv H1.\n    apply IHt2. auto. auto. auto.\n  - intros. simpl. intro. assert (~ term_has_recursion t2_1). intro. apply H0.\n    apply let_has_rec1; auto. assert (~ term_has_recursion t2_2). intro. apply H0.\n    apply let_has_rec2; auto. destruct (x=?n). inv H1. apply IHt2_1; auto.\n    apply H3; auto. inv H1. apply IHt2_1; auto. apply IHt2_2; auto.\n  - intros. intro. apply H0. apply rec_has_rec. Qed.\n\nLemma not_rec_preservation : forall t t', ~ term_has_recursion t ->\n  t ---> t' -> ~ term_has_recursion t'.\nProof.\n  induction t.\n  - intros. inv H0.\n  - intros. inv H0.\n  - intros. inv H0. assert (~ term_has_recursion t1 /\\ ~ term_has_recursion t2). split;\n    intro; apply H; [apply op_has_rec1 | apply op_has_rec2]; auto. destruct H0.\n    eapply IHt1 in H0. intro. inv H2. destruct H0. eauto. destruct H1; auto. auto.\n    intro. inv H0. apply H. apply op_has_rec1. auto. eapply IHt2.\n    intro. apply H. apply op_has_rec2. auto. apply H5. auto. assert (~ term_has_recursion (t_num n1)\n    /\\ ~ term_has_recursion (t_num n2)). split; intro; apply H; [apply op_has_rec1 | apply op_has_rec2];\n    auto. destruct H0. intro. inv H2. intro. inv H0.\n  - intros. assert (~ term_has_recursion t1 /\\ ~ term_has_recursion t2 /\\ ~ term_has_recursion t3).\n    split. intro. apply H. eapply if_has_rec1. auto. split; intro; apply H; [eapply if_has_rec2 |\n    eapply if_has_rec3]; eauto. destruct H1. destruct H2. inversion H0. subst. auto. subst.\n    auto. subst. intro. inv H4. eapply IHt1. auto. apply H8. auto.\n    apply H2; auto. apply H3; auto.\n  - intros. inv H0.\n  - intros. assert (~ term_has_recursion t1 /\\ ~ term_has_recursion t2). split; intro;\n    apply H; [apply app_has_rec1 | apply app_has_rec2]; auto. destruct H1.\n    inv H0. apply not_rec_subst; auto. intro. apply H1. apply fun_has_rec. auto.\n    intro. apply IHt2 in H5. inv H0; auto. auto. intro. inv H0; auto.\n    apply IHt1 in H6. apply H6; auto. auto.\n  - intros. inv H0.\n  - intros. assert (~ term_has_recursion t2). intro. apply H. apply let_has_rec1; auto.\n    assert (~ term_has_recursion t3). intro. apply H. apply let_has_rec2; auto.\n    inv H0. apply not_rec_subst; auto. apply IHt1 in H8; auto. intro.\n    inv H0; auto.\n  - intros. assert (term_has_recursion (t_rec n t1 t2 n0 t3 t4)). apply rec_has_rec.\n    destruct H. auto. Qed.\n\n\nTheorem cost_relation : forall t n m t' c', ~ term_has_recursion t ->\n  multi_cost_language t n t' ->\n  value t' ->\n  multi_cost_code (initial_state (compile t)) m c' ->\n  state_value c' ->\n  m <= 10*n + 10.\nProof. induction t.\n  - intros. assert (t' = (t_num n)). inv H0. auto. inv H4. subst.\n    assert (n0 = 0). inv H0. auto. inv H4. subst. simpl. inv H2. omega.\n    inv H4. inv H5. omega. inv H2.\n  - intros. inv H0. inv H2. omega. inv H0. inv H4. omega. inv H0. inv H4.\n  - intros. Admitted.\n\n\n\n\n\nFixpoint term_size (t: term) : nat :=\n  match t with\n  | t_num _ => 1\n  | t_bool _ => 1\n  | t_op t1 _ t2 => 1 + (term_size t1) + (term_size t2)\n  | t_if t1 t2 t3 => 1 + (term_size t1) + (term_size t2) + (term_size t3)\n  | t_var _ => 1\n  | t_app t1 t2 => 1 + (term_size t2) + (term_size t1)\n  | t_fun _ _ t1 => 2 + (term_size t1)\n  | t_let _ _ t1 t2 => 2 + (term_size t1) + (term_size t2)\n  | t_rec _ _ _ _ t1 t2 => 3 + (term_size t1) + (term_size t2)\n  end.\n\n\nFixpoint add_list (l: list nat) : nat :=\n  match l with\n  | [] => 0\n  | n :: l' => n + (add_list l')\n  end.\n\nFixpoint inst_depth (i: Instruction) : nat :=\n  match i with\n  | FUN _ l => 1 + (add_list (map inst_depth l))\n  | RFUN _ _ l => 1 + (add_list (map inst_depth l))\n  | _ => 1\n  end.\n\nDefinition code_depth (c: Code) := add_list (map inst_depth c).\nDefinition code_depth_plus (c: Code) := (length c) + (add_list (map inst_depth c)).\n\n\nFunction code_size (c: Code) {measure code_depth c} : nat :=\n  match c with\n  | [] => 0\n  | INT _ :: c' => 2 + (code_size c')\n  | BOOL _ :: c' => 2 + (code_size c')\n  | JUMP _ :: c' => 2 + (code_size c')\n  | JUMPIFTRUE _ :: c' => 2 + (code_size c')\n  | VAR _ :: c' => 2 + (code_size c')\n  | FUN _ ci :: c' => 2 + (code_size ci) + (code_size c')\n  | RFUN _ _ ci :: c' => 3 + (code_size ci) + (code_size c')\n  | _ :: c' => 1 + (code_size c')\n  end.\nProof.\n  - intros; subst; auto.\n  - intros; subst; auto.\n  - intros; subst; auto.\n  - intros; subst; auto.\n  - intros; subst; auto.\n  - intros; subst. unfold code_depth. simpl. omega.\n  - intros; subst; auto.\n  - intros; subst. unfold code_depth. simpl. omega.\n  - intros; subst. unfold code_depth. simpl. omega.\n  - intros; subst; auto.\n  - intros; subst; auto.\n  - intros; subst; auto.\n  - intros; subst. unfold code_depth. simpl. omega.\n  - intros; subst. unfold code_depth. simpl. omega.\n  - intros; subst; auto. unfold code_depth. simpl. omega.\n  - intros; subst; auto. unfold code_depth. simpl. omega.\n  - intros; subst; auto.\nDefined.\n\n\nLemma length_distr : forall A (l1 l2 : list A), length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros. induction l1; induction l2; auto.\n  - simpl. Search app. rewrite <- app_nil_end. auto.\n  - simpl. rewrite IHl1. simpl. auto. Qed.\n\nLemma code_size_distr1 : forall a c, code_size (a :: c) = code_size [[a]] + code_size c.\nProof.\n  intros. induction a; rewrite code_size_equation; auto. simpl. assert (code_size [[FUN i l]] =\n  2 + (code_size l)). rewrite code_size_equation. auto. rewrite H. auto.\n  assert (code_size [[RFUN i i0 l]] = 3 + code_size l). rewrite code_size_equation. auto.\n  rewrite H. auto. Qed.\n\nLemma code_size_distr : forall c1 c2, code_size (c1 ++ c2) = (code_size c1) + (code_size c2).\nProof.\n  intros. induction c1; auto. destruct a; rewrite code_size_equation; simpl;\n  rewrite IHc1; rewrite code_size_distr1; auto.\n  assert (code_size [[FUN i l]] = 2 + code_size l). rewrite code_size_equation. auto.\n  rewrite H. omega. assert (code_size [[RFUN i i0 l]] = 3 + code_size l). rewrite code_size_equation.\n  auto. rewrite H. omega. Qed.\n\n\n\nTheorem length_relation :\n  forall t, (code_size (compile t)) < 3 * (term_size t).\nProof.\n  intros. induction t; try (solve [simpl; unfold code_size; simpl; omega]).\n  - destruct o.\n    + simpl compile. repeat (rewrite code_size_distr). simpl term_size.\n      assert (code_size [[ADD]] = 1). auto. rewrite H. omega.\n    + simpl compile. repeat (rewrite code_size_distr). simpl term_size.\n      pose (which_comp_value b). destruct o; rewrite H. cbn. omega. cbn. omega.\n  - simpl compile. rewrite code_size_distr. rewrite  code_size_distr1. rewrite code_size_distr.\n    assert (code_size (JUMP (code_length (compile t2)) :: compile t2) =\n    code_size [[JUMP (code_length (compile t2))]] + code_size (compile t2)).\n    apply code_size_distr1. rewrite H. clear H. cbn. omega.\n  - simpl compile. repeat (rewrite code_size_distr). cbn; omega.\n  - simpl compile. rewrite code_size_equation. cbn. omega.\n  - simpl compile. rewrite code_size_distr. rewrite code_size_distr1.\n    simpl term_size. assert (code_size [[FUN n (compile t3)]] = 2 + code_size (compile t3)).\n    rewrite code_size_equation. auto. rewrite H; clear H. cbn. omega.\n  - simpl compile. rewrite code_size_distr1. assert (code_size (FUN n (compile t4) :: [[APPLY]]) =\n    code_size [[FUN n (compile t4)]] + code_size [[APPLY]]). apply code_size_distr1.\n    rewrite H; clear H. assert (code_size [[RFUN n n0 (compile t3)]] = 3 + code_size (compile t3)).\n    rewrite code_size_equation. auto. rewrite H; clear H. assert (code_size [[FUN n (compile t4)]] =\n    2 + code_size (compile t4)). rewrite code_size_equation; auto. rewrite H; clear H.\n    cbn; omega.\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", "meta": {"author": "bfbonatto", "repo": "TCC", "sha": "8dd36e8c1e7af062df071c6c8a0590aa5a12a581", "save_path": "github-repos/coq/bfbonatto-TCC", "path": "github-repos/coq/bfbonatto-TCC/TCC-8dd36e8c1e7af062df071c6c8a0590aa5a12a581/coq/l1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430520409023, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.6634073925541694}}
{"text": "Require Export GeoCoq.Tarski_dev.Ch13_6_Desargues_Hessenberg.\n\nSection T14_sum.\n\nContext `{T2D:Tarski_2D}.\nContext `{TE:@Tarski_euclidean Tn TnEQD}.\n\nLemma Pj_exists : forall A B C,\n exists D, Pj A B C D.\nProof.\n    intros.\n    unfold Pj in *.\n    elim (eq_dec_points A B);intro.\n      subst.\n      exists C.\n      tauto.\n    assert (T:=parallel_existence A B C H).\n    decompose [and ex] T;clear T.\n    exists x0.\n    induction (eq_dec_points C x0).\n      tauto.\n    eauto using par_col2_par with col.\nQed.\n\nLemma sum_to_sump : forall O E E' A B C, Sum O E E' A B C -> Sump O E E' A B C.\nProof.\n    intros.\n    unfold Sum in H.\n    unfold Ar2 in H.\n    spliter.\n    repeat split; Col.\n    ex_and H0 A'.\n    ex_and H4 C'.\n    exists A'.\n    exists C'.\n    assert(O <> E /\\ O <> E').\n      repeat split; intro; subst O; apply H; Col.\n    spliter.\n    assert(HH:=parallel_existence1 O E A' H8).\n    ex_and HH P'.\n    exists P'.\n    assert( E <> E').\n      intro.\n      subst E'.\n      apply H.\n      Col.\n    repeat split; Col.\n      intro.\n      induction H12.\n        apply H12.\n        exists E'.\n        split; Col.\n      spliter.\n      contradiction.\n      unfold Pj in H0.\n      induction H0.\n        left.\n        apply par_symmetry.\n        assumption.\n      right.\n      auto.\n      apply par_distincts in H10.\n      spliter.\n      auto.\n      intro.\n      assert(Par O E O E').\n        apply (par_trans _ _ A' P'); auto.\n      induction H13.\n        apply H13.\n        exists O.\n        split; Col.\n      spliter.\n      apply H.\n      Col.\n      unfold Pj in H5.\n      induction H5.\n        assert(Par A' C' A' P').\n          apply (par_trans _ _ O E).\n            apply par_symmetry.\n            auto.\n          auto.\n        induction H12.\n          apply False_ind.\n          apply H12.\n          exists A'.\n          split; Col.\n        spliter.\n        Col.\n      subst C'.\n      Col.\n      unfold Pj in H6.\n      induction H6.\n        left.\n        apply par_symmetry.\n        auto.\n      right.\n      auto.\n      intro.\n      induction H12.\n        apply H12.\n        exists E.\n        split; Col.\n      spliter.\n      contradiction.\n    unfold Pj in H7.\n    induction H7.\n      left.\n      apply par_symmetry.\n      apply par_left_comm.\n      auto.\n    tauto.\nQed.\n\n\nLemma sump_to_sum : forall O E E' A B C, Sump O E E' A B C -> Sum O E E' A B C.\nProof.\n    intros.\n    unfold Sump in H.\n    spliter.\n    ex_and H1 A'.\n    ex_and H2 C'.\n    ex_and H1 P'.\n    unfold Sum.\n    split.\n      repeat split; Col.\n        intro.\n        unfold Proj in H1.\n        spliter.\n        apply H7.\n        right.\n        repeat split; Col.\n      unfold Proj in H4.\n      spliter.\n      Col.\n    exists A'.\n    exists C'.\n    unfold Pj.\n    repeat split.\n      unfold Proj in H1.\n      spliter.\n      induction H8.\n        left.\n        apply par_symmetry.\n        auto.\n      tauto.\n      unfold Proj in H1.\n      tauto.\n      induction(eq_dec_points A' C').\n        tauto.\n      left.\n      unfold Proj in H3.\n      spliter.\n      apply (par_col_par _  _ _ P'); Col.\n      unfold Proj in H3.\n      spliter.\n      induction H8.\n        left.\n        apply par_symmetry.\n        auto.\n      tauto.\n    unfold Proj in H4.\n    spliter.\n    induction H8.\n      left.\n      apply par_symmetry.\n      apply par_right_comm.\n      auto.\n    tauto.\nQed.\n\n(* a inclure dans project.v *)\n\nLemma project_col_project : forall A B C P P' X Y,\n  A <> C -> Col A B C ->\n  Proj P P' A B X Y ->\n  Proj P P' A C X Y.\nProof.\n    intros.\n    unfold Proj in *.\n    spliter.\n    repeat split; auto.\n      intro.\n      apply H3.\n      eapply (par_col_par_2 _ C); Col; Par.\n    (*perm_apply (par_col_par X Y A C).*)\n    ColR.\nQed.\n\nLemma project_trivial : forall P A B X Y,\n  A <> B -> X <> Y ->\n  Col A B P -> ~ Par A B X Y ->\n  Proj P P A B X Y.\nProof.\n    intros.\n    unfold Proj.\n    repeat split; Col.\nQed.\n\nLemma pj_col_project : forall P P' A B X Y,\n A <> B -> X <> Y ->\n Col P' A B ->\n ~ Par A B X Y ->\n Pj X Y P P' ->\n Proj P P' A B X Y.\nProof.\n    intros.\n    unfold Pj in H3.\n    induction H3.\n      unfold Proj.\n      repeat split; Col.\n      left.\n      apply par_symmetry.\n      assumption.\n    subst P'.\n    apply project_trivial; Col.\nQed.\n\n(** Lemma 14.6 *)\n\nSection Grid.\n\nVariable O E E' : Tpoint.\n\nVariable grid_ok : ~ Col O E E'.\n\nLemma sum_exists : forall A B,\n Col O E A -> Col O E B ->\n exists C, Sum O E E' A B C.\nProof.\n    intros.\n    assert(NC:= grid_ok).\n    assert(O <> E).\n      intro.\n      subst E.\n      apply NC.\n      Col.\n    assert(O <> E').\n      intro.\n      subst E'.\n      apply NC.\n      Col.\n    induction(eq_dec_points O A).\n      subst A.\n      exists B.\n      unfold Sum.\n      split.\n        unfold Ar2.\n        split; Col.\n      exists O.\n      exists B.\n      unfold Pj.\n      repeat split.\n        right.\n        auto.\n        Col.\n        induction(eq_dec_points O B).\n          right; auto.\n        left.\n        right.\n        repeat split; Col.\n        right; auto.\n      right; auto.\n    assert(exists! A' , Proj A A' O E' E E').\n      apply(project_existence A O E' E E'); intro; try (subst E' ; apply NC; Col).\n      induction H4.\n        apply H4.\n        exists E'.\n        split; Col.\n      spliter.\n      apply NC.\n      Col.\n    ex_and H4 A'.\n    assert(HH:=parallel_existence1 O E A' H1).\n    ex_and HH P.\n    unfold unique in H5.\n    spliter.\n    assert(A <> A').\n      intro.\n      subst A'.\n      apply project_col in H5.\n      apply NC.\n      apply (col_transitivity_1 _ A); Col.\n    induction(eq_dec_points B O).\n      subst B.\n      exists A.\n      unfold Sum.\n      split.\n        unfold Ar2.\n        repeat split; Col.\n      exists A'.\n      exists A'.\n      unfold Pj.\n      unfold Proj in H5.\n      spliter.\n      repeat split.\n        spliter.\n        induction H11.\n          left.\n          apply par_symmetry.\n          auto.\n        contradiction.\n        Col.\n        right.\n        auto.\n        left.\n        right.\n        repeat split; Col.\n        intro.\n        subst A'.\n        induction H11.\n          induction H11.\n            apply H11.\n            exists E.\n            split; Col.\n          spliter.\n          contradiction.\n        contradiction.\n      induction H11.\n        left.\n        apply par_symmetry.\n        apply par_comm.\n        auto.\n      contradiction.\n    assert(exists! C', Proj B C' A' P O E').\n      apply(project_existence B A' P O E'); auto.\n      apply par_distincts in H4.\n      spliter.\n      auto.\n      intro.\n      assert(Par O E O E').\n        apply (par_trans _ _ A' P).\n          auto.\n        apply par_symmetry.\n        auto.\n      induction H10.\n        apply H10.\n        exists O.\n        split; Col.\n      spliter.\n      apply NC.\n      Col.\n    ex_and H9 C'.\n    unfold unique in H10.\n    spliter.\n    assert(exists! C : Tpoint, Proj C' C O E A A').\n      apply(project_existence C' O E A A'); auto.\n      intro.\n      induction H11.\n        apply H11.\n        exists A.\n        split; Col.\n      spliter.\n      assert(HH:=project_par_dir A A' O E' E E' H11 H5).\n      assert(Col E A A').\n        ColR.\n      induction HH.\n        apply H16.\n        exists E.\n        split; Col.\n      spliter.\n      apply NC.\n      apply col_permutation_2.\n      apply(col_transitivity_1 _ A'); Col.\n      intro.\n      subst A'.\n      clean_trivial_hyps.\n      unfold Proj in H5.\n      spliter.\n      apply NC.\n      Col.\n    ex_and H11 C.\n    unfold unique in H12.\n    spliter.\n    unfold Proj in *.\n    spliter.\n    exists C.\n    unfold Sum.\n    split.\n      unfold Ar2.\n      repeat split; Col.\n    exists A'.\n    exists C'.\n    unfold Pj.\n    repeat split.\n      left.\n      induction H24.\n        apply par_symmetry.\n        auto.\n      contradiction.\n      Col.\n      left.\n      eapply (par_col_par _ _ _ P).\n        intro.\n        subst C'.\n        induction H16.\n          induction H16.\n            apply H16.\n            exists A'.\n            split; Col.\n          spliter.\n          induction H20.\n            induction H20.\n              apply H20.\n              exists A'.\n              split; Col.\n            spliter.\n            apply NC.\n            apply (col_transitivity_1 _ B); Col.\n          subst A'.\n          apply H14.\n          right.\n          repeat split; ColR.\n        subst A'.\n        apply H14.\n        right.\n        repeat split; ColR.\n        assumption.\n      ColR.\n      induction H20.\n        left.\n        apply par_symmetry.\n        auto.\n      right; auto.\n    induction H24.\n      induction H16.\n        left.\n        apply (par_trans _ _ A A').\n          apply par_symmetry.\n          apply par_right_comm.\n          auto.\n        apply par_symmetry.\n        auto.\n      subst C'.\n      right.\n      auto.\n    contradiction.\nQed.\n\n(** We are not faithful to Tarski's def because for uniqueness we do not need the assumption that\n A and B are on line OE as it is implied by the definition of sum. *)\n\nLemma sum_uniqueness : forall A B C1 C2,\n Sum O E E' A B C1 ->\n Sum O E E' A B C2 ->\n C1 = C2.\nProof.\n    intros.\n    apply sum_to_sump in H.\n    apply sum_to_sump in H0.\n    unfold Sump in H.\n    unfold Sump in H0.\n    spliter.\n    clean_duplicated_hyps.\n    ex_and H4 A'.\n    ex_and H0 C'.\n    ex_and H1 P'.\n    ex_and H2 A''.\n    ex_and H6 C''.\n    ex_and H2 P''.\n    assert(A'=A'').\n      apply(project_uniqueness A A' A'' O E' E E');auto.\n    subst A''.\n    assert(Col A' P' P'').\n      assert(Par A' P' A' P'').\n        apply (par_trans _ _ O E).\n          apply par_symmetry.\n          auto.\n        auto.\n      induction H9.\n        apply False_ind.\n        apply H9.\n        exists A'.\n        split; Col.\n      spliter.\n      Col.\n    assert(Proj B C'' A' P' O E').\n      eapply (project_col_project _ P''); Col.\n      unfold Proj in H4.\n      tauto.\n    assert(C' = C'').\n      apply(project_uniqueness B C' C'' A' P' O E');auto.\n    subst C''.\n    apply(project_uniqueness C' C1 C2 O E E E');auto.\nQed.\n\nLemma opp_exists : forall A,\n Col O E A ->\n exists MA, Opp O E E' A MA.\nProof.\n    intros.\n    assert(NC:= grid_ok).\n    induction(eq_dec_points A O).\n      subst A.\n      exists O.\n      unfold Opp.\n      unfold Sum.\n      split.\n        unfold Ar2.\n        repeat split; Col.\n      exists O.\n      exists O.\n      repeat split; Col; try right; auto.\n    prolong A O MA A O.\n    exists MA.\n    unfold Opp.\n    apply sump_to_sum.\n    unfold Sump.\n    repeat split.\n      apply bet_col in H1.\n      apply (col_transitivity_1 _ A);Col.\n      Col.\n    assert(E <> E' /\\ O <> E').\n      split; intro; subst E'; apply NC; Col.\n    spliter.\n    assert(exists! P' : Tpoint, Proj MA P' O E' E E').\n      apply(project_existence MA O E' E E'); auto.\n      intro.\n      induction H5.\n        apply H5.\n        exists E'.\n        split; Col.\n      spliter.\n      apply NC.\n      Col.\n    ex_and H5 A'.\n    unfold unique in H6.\n    spliter.\n    exists A'.\n    assert(O <> E).\n      intro.\n      subst E.\n      apply NC.\n      Col.\n    assert(HH:= parallel_existence1 O E A' H7).\n    ex_and HH P'.\n    assert(exists! C' : Tpoint, Proj A C' A' P' O E').\n      apply(project_existence A A' P' O E'); auto.\n      apply par_distincts in H8.\n      spliter.\n      auto.\n      intro.\n      assert(Par O E O E').\n        apply (par_trans _ _ A' P').\n          auto.\n        apply par_symmetry; auto.\n      induction H10.\n        apply H10.\n        exists O.\n        split; Col.\n      spliter.\n      apply NC.\n      Col.\n    ex_and H9 C'.\n    unfold unique in H10.\n    spliter.\n    exists C'.\n    exists P'.\n    split; auto.\n    split; auto.\n    split; auto.\n    unfold Proj in H5.\n    spliter.\n    unfold Proj.\n    repeat split; Col.\n      intro.\n      induction H15.\n        apply H15.\n        exists E.\n        split; Col.\n      apply NC.\n      tauto.\n    left.\n    unfold Proj in H9.\n    spliter.\n    assert(Par O E' O A').\n      right.\n      repeat split; Col.\n      intro.\n      subst A'.\n      clean_trivial_hyps.\n      induction H14.\n        induction H13.\n          apply H13.\n          exists E.\n          split; Col.\n          apply col_permutation_1.\n          apply bet_col in H1.\n          apply(col_transitivity_1 _ A); Col.\n        apply NC.\n        tauto.\n      subst MA.\n      apply cong_symmetry in H2.\n      apply cong_identity in H2.\n      contradiction.\n    assert(Plg A C' A' O).\n      apply pars_par_plg.\n        induction H18.\n          assert(Par A C' A' O).\n            apply (par_trans _ _ O E').\n              Par.\n            Par.\n          induction H20.\n            auto.\n          spliter.\n          apply False_ind.\n          apply NC.\n          apply (col_transitivity_1 _ A'); Col.\n          apply (col_transitivity_1 _ A); Col.\n        subst C'.\n        apply False_ind.\n        induction H8.\n          apply H8.\n          exists A.\n          split; Col.\n        spliter.\n        apply NC.\n        apply (col_transitivity_1 _ A'); Col.\n          intro.\n          subst A'.\n          apply par_distincts in H19.\n          tauto.\n        apply col_permutation_2.\n        apply (col_transitivity_1 _ P'); Col.\n      apply par_comm.\n      apply (par_col_par _ _ _ P').\n        intro.\n        subst C'.\n        induction H18.\n          induction H18.\n            apply H18.\n            exists A'.\n            split; Col.\n          spliter.\n          apply NC.\n          apply (col_transitivity_1 _ A); Col.\n        subst A'.\n        induction H19.\n          apply H18.\n          exists O.\n          split; Col.\n        spliter.\n        apply NC.\n        apply (col_transitivity_1 _ A); Col.\n        apply par_symmetry.\n        apply (par_col_par _ _ _ E); Col.\n        apply par_symmetry.\n        Par.\n      Col.\n    assert(Parallelogram A O MA O).\n      right.\n      unfold Parallelogram_flat.\n      repeat split; Col; Cong.\n      left.\n      intro.\n      subst MA.\n      apply between_identity in H1.\n      contradiction.\n    apply plg_to_parallelogram in H20.\n    apply plg_permut in H20.\n    apply plg_comm2 in H21.\n    assert(Parallelogram C' A' MA O).\n      assert(HH:= plg_pseudo_trans C' A' O A O MA H20 H21).\n      induction HH.\n        auto.\n      spliter.\n      subst MA.\n      apply cong_symmetry in H2.\n      apply cong_identity in H2.\n      contradiction.\n    apply plg_par in H22.\n      spliter.\n      induction H14.\n        apply (par_trans _ _ A' MA).\n          auto.\n        Par.\n      subst MA.\n      apply par_distincts in H23.\n      tauto.\n      intro.\n      subst C'.\n      unfold Parallelogram in H20.\n      induction H20.\n        unfold Parallelogram_strict in H20.\n        spliter.\n        apply par_distincts in H23.\n        tauto.\n      unfold Parallelogram_flat in H20.\n      spliter.\n      apply cong_symmetry in H24.\n      apply cong_identity in H24.\n      subst A.\n      tauto.\n    intro.\n    subst MA.\n    unfold Parallelogram in H21.\n    induction H21.\n      unfold Parallelogram_strict in H21.\n      spliter.\n      unfold TS in H21; unfold Parallelogram.\n      spliter; Col.\n    unfold Parallelogram_flat in H21.\n    spliter.\n    apply NC.\n    apply (col_transitivity_1 _ A); Col.\n    apply (col_transitivity_1 _ A'); Col.\n    intro.\n    subst A'.\n    apply cong_identity in H24.\n    subst A.\n    tauto.\nQed.\n\nLemma opp0 : Opp O E E' O O.\nProof.\n    assert(NC:=grid_ok).\n    assert(O <> E' /\\ E <> E').\n      split; intro ; subst E'; apply NC; Col.\n    spliter.\n    assert(O <> E).\n      intro.\n      subst E.\n      apply NC; Col.\n    unfold Opp.\n    apply sump_to_sum.\n    unfold Sump.\n    repeat split; Col.\n    exists O.\n    exists O.\n    exists E.\n    split.\n      apply project_trivial; Col.\n      intro.\n      induction H2.\n        apply H2.\n        exists E'.\n        split; Col.\n      spliter.\n      contradiction.\n    split.\n      apply par_reflexivity; auto.\n    split.\n      apply project_trivial; Col.\n      intro.\n      induction H2.\n        apply H2.\n        exists O.\n        split; Col.\n      spliter.\n      apply NC.\n      Col.\n    apply project_trivial; Col.\n    intro.\n    induction H2.\n      apply H2.\n      exists E.\n      split; Col.\n    spliter.\n    contradiction.\nQed.\n\nLemma pj_trivial : forall A B C, Pj A B C C.\nProof.\n    intros.\n    unfold Pj.\n    right.\n    auto.\nQed.\n\nLemma sum_O_O : Sum O E E' O O O.\nProof.\n    unfold Sum.\n    assert(O <> E' /\\ E <> E').\n      split; intro ; subst E'; apply grid_ok; Col.\n    split.\n      spliter.\n      unfold Ar2.\n      repeat split; Col.\n    exists O.\n    exists O.\n    repeat split;try (apply pj_trivial).\n    Col.\nQed.\n\nLemma sum_A_O : forall A, Col O E A -> Sum O E E' A O A.\nProof.\n    intros.\n    unfold Sum.\n    split.\n      repeat split; Col.\n    assert(O <> E' /\\ E <> E').\n      split; intro; subst E'; apply grid_ok; Col.\n    spliter.\n    induction (eq_dec_points A O).\n      exists O.\n      exists O.\n      repeat split;  Col; unfold Pj ; try auto.\n    assert(~ Par E E' O E').\n      intro.\n      induction H3.\n        apply H3.\n        exists E'.\n        split; Col.\n      spliter.\n      apply grid_ok.\n      Col.\n    assert(HH:= project_existence A O E' E E' H1 H0 H3).\n    ex_and HH A'.\n    unfold unique in H4.\n    spliter.\n    exists A'.\n    exists A'.\n    unfold Proj in H4.\n    spliter.\n    repeat split; Col.\n      unfold Pj.\n      induction H9.\n        left.\n        apply par_symmetry.\n        Par.\n      tauto.\n      unfold Pj.\n      tauto.\n      unfold Pj.\n      left.\n      right.\n      repeat split; Col.\n      intro.\n      subst A'.\n      induction H9.\n        induction H9.\n          apply H9.\n          exists E.\n          split; Col.\n        spliter.\n        contradiction.\n      contradiction.\n    unfold Pj.\n    induction H9.\n      left.\n      apply par_symmetry.\n      Par.\n    right.\n    auto.\nQed.\n\nLemma sum_O_B : forall B, Col O E B -> Sum O E E' O B B.\nProof.\n    intros.\n    induction(eq_dec_points B O).\n      subst B.\n      apply sum_O_O.\n    unfold Sum.\n    split.\n      repeat split; Col.\n    assert(O <> E' /\\ E <> E').\n      split; intro; subst E'; apply grid_ok; Col.\n    spliter.\n    assert(~ Par E E' O E').\n      intro.\n      induction H3.\n        apply H3.\n        exists E'.\n        split; Col.\n      spliter.\n      apply grid_ok.\n      Col.\n    exists O.\n    exists B.\n    repeat split; try(apply pj_trivial).\n      Col.\n    left.\n    right.\n    repeat split; Col.\n    intro.\n    subst E.\n    apply grid_ok.\n    Col.\nQed.\n\nLemma opp0_uniqueness : forall M, Opp O E E' O M -> M = O.\nProof.\n    intros.\n    assert(NC:= grid_ok).\n    unfold Opp in H.\n    apply sum_to_sump in H.\n    unfold Sump in H.\n    spliter.\n    ex_and H1 A'.\n    ex_and H2 C'.\n    ex_and H1 P'.\n    unfold Proj in *.\n    spliter.\n    induction H8.\n      induction H12.\n        assert(Par O E' E E').\n          apply (par_trans _ _ C' O).\n            apply par_symmetry.\n            Par.\n          Par.\n        apply False_ind.\n        induction H17.\n          apply H17.\n          exists E'.\n          split; Col.\n        spliter.\n        contradiction.\n      subst C'.\n      apply par_distincts in H8.\n      tauto.\n    subst C'.\n    assert( A' = O).\n      apply (l6_21 O E E' O); Col.\n      induction H2.\n        apply False_ind.\n        apply H2.\n        exists O.\n        split; Col.\n      spliter.\n      apply col_permutation_1.\n      apply(col_transitivity_1 _ P'); Col.\n    subst A'.\n    induction H16.\n      induction H8.\n        apply False_ind.\n        apply H8.\n        exists E.\n        split; Col.\n      spliter.\n      contradiction.\n    assumption.\nQed.\n\nLemma proj_pars : forall A A' C' , A <> O -> Col O E A -> Par O E A' C' -> Proj A A' O E' E E' -> Par_strict O E A' C'.\nProof.\n    intros.\n    unfold Par_strict.\n    assert(HH:=grid_ok).\n    split.\n      apply all_coplanar.\n    intro.\n    ex_and H3 X.\n    unfold Proj in H2.\n    spliter.\n    induction H1.\n      apply H1.\n      exists X.\n      split; Col.\n    spliter.\n    assert(Col A' O E).\n      apply (col_transitivity_1 _ C'); Col.\n    induction(eq_dec_points A' O).\n      subst A'.\n      clean_trivial_hyps.\n      induction H8.\n        induction H7.\n          apply H7.\n          exists E.\n          split; Col.\n        spliter.\n        contradiction.\n      contradiction.\n    apply grid_ok.\n    apply(col_transitivity_1 _ A'); Col.\nQed.\n\nLemma proj_col : forall A A' C' , A = O -> Col O E A -> Par O E A' C' -> Proj A A' O E' E E' -> A' = O.\nProof.\n    intros.\n    assert(HH:=grid_ok).\n    unfold Proj in H2.\n    spliter.\n    subst A.\n    induction H6.\n      apply False_ind.\n      apply H4.\n      apply par_symmetry.\n      eapply (par_col_par _ _ _ A'); Col.\n      apply par_symmetry.\n      Par.\n    auto.\nQed.\n\nLemma grid_not_par : ~Par O E E E' /\\ ~Par O E O E' /\\ ~Par O E' E E' /\\ O <> E /\\ O <> E' /\\ E <> E'.\nProof.\n    repeat split.\n      intro.\n      unfold Par in H.\n      induction H.\n        apply H.\n        exists E.\n        split; Col.\n      spliter.\n      contradiction.\n      intro.\n      induction H.\n        apply H.\n        exists O.\n        split; Col.\n      spliter.\n      apply grid_ok.\n      Col.\n      intro.\n      induction H.\n        apply H.\n        exists E'.\n        split; Col.\n      spliter.\n      contradiction.\n      intro.\n      subst E.\n      apply grid_ok.\n      Col.\n      intro.\n      subst E'.\n      apply grid_ok.\n      Col.\n    intro.\n    subst E'.\n    apply grid_ok.\n    Col.\nQed.\n\nLemma proj_id : forall A A', Proj A A' O E' E E' -> Col O E A -> Col O E A' -> A = O.\nProof.\n    intros.\n    assert(HH:=grid_not_par).\n    spliter.\n    unfold Proj in H.\n    spliter.\n    induction H11.\n      apply(l6_21 O E E' O); Col.\n        assert(Col O A' A).\n          apply(col_transitivity_1 _ E); Col.\n        apply col_permutation_2.\n        apply (col_transitivity_1 _ A'); Col.\n        intro.\n        subst A'.\n        induction H11.\n          apply H11.\n          exists E.\n          split; Col.\n        spliter.\n        contradiction.\n    subst.\n    apply(l6_21 O E E' O); Col.\nQed.\n\nLemma sum_O_B_eq : forall B C, Sum O E E' O B C -> B = C.\nProof.\n    intros.\n    assert (HS:=H).\n    unfold Sum in H.\n    spliter.\n    unfold Ar2 in H.\n    spliter.\n    assert(HH:=sum_O_B B H2).\n    apply (sum_uniqueness O B); auto.\nQed.\n\nLemma sum_A_O_eq : forall A C, Sum O E E' A O C -> A = C.\nProof.\n    intros.\n    assert (HS:=H).\n    unfold Sum in H.\n    spliter.\n    unfold Ar2 in H.\n    spliter.\n    assert(HH:=sum_A_O A H1).\n    apply (sum_uniqueness A O); auto.\nQed.\n\nLemma sum_par_strict : forall A B C A' C', Ar2 O E E' A B C -> A <> O -> Pj E E' A A' -> Col O E' A' -> Pj O E A' C' -> Pj O E' B C' -> Pj E' E C' C\n                                           -> A' <> O /\\ (Par_strict O E A' C' \\/ B = O).\nProof.\n    intros.\n    assert(Sum O E E' A B C).\n      unfold Sum.\n      split.\n        auto.\n      exists A'.\n      exists C'.\n      repeat split; auto.\n    unfold Ar2 in H.\n    unfold Pj in *.\n    spliter.\n    assert(A' <> O).\n      intro.\n      subst A'.\n      induction H3.\n        induction H3.\n          apply H3.\n          exists O.\n          split; Col.\n        spliter.\n        induction H1.\n          induction H1.\n            apply H1.\n            exists E.\n            split; Col.\n          spliter.\n          apply grid_ok.\n          apply(col_transitivity_1 _ A); Col.\n        contradiction.\n      subst C'.\n      induction H1.\n        induction H1.\n          apply H1.\n          exists E.\n          split; Col.\n        spliter.\n        apply grid_ok.\n        apply(col_transitivity_1 _ A); Col.\n      contradiction.\n    split.\n      auto.\n    induction(eq_dec_points B O).\n      tauto.\n    left.\n    induction H3.\n      induction H3.\n        assumption.\n      spliter.\n      apply False_ind.\n      apply grid_ok.\n      assert(Col A' O E ).\n        apply(col_transitivity_1 _ C'); Col.\n      apply(col_transitivity_1 _ A'); Col.\n    subst C'.\n    apply False_ind.\n    induction H4.\n      induction H3.\n        apply H3.\n        exists A'.\n        split; Col.\n      spliter.\n      assert(Col O B E').\n        apply (col_transitivity_1 _ A'); Col.\n      apply grid_ok.\n      apply (col_transitivity_1 _ B); Col.\n    subst A'.\n    assert(HH:= grid_not_par).\n    spliter.\n    induction H5.\n      apply H3.\n      apply par_symmetry.\n      apply (par_col_par _ _ _ B); Col.\n      apply par_right_comm.\n      apply (par_col_par _ _ _ C); Par.\n      apply col_permutation_1.\n      apply(col_transitivity_1 _ E); Col.\n    subst C.\n    apply grid_ok.\n    apply(col_transitivity_1 _ B); Col.\nQed.\n\nLemma sum_A_B_A : forall A B, Sum O E E' A B A -> B = O.\nProof.\n    intros.\n    unfold Sum in H.\n    spliter.\n    ex_and H0 A'.\n    ex_and H1 C'.\n    assert(HH:= grid_not_par).\n    spliter.\n    induction(eq_dec_points A O).\n      subst A.\n      unfold Pj in *.\n      unfold Ar2 in H.\n      spliter.\n      induction H0.\n        induction H0.\n          apply False_ind.\n          apply H0.\n          exists E'.\n          split; Col.\n        spliter.\n        apply False_ind.\n        apply grid_ok.\n        ColR.\n      subst A'.\n      induction H2.\n        induction H4.\n          apply False_ind.\n          apply H5.\n          apply (par_trans _ _ O C') ; Par.\n        subst C'.\n        apply par_distincts in H0.\n        tauto.\n      subst C'.\n      induction H3.\n        induction H0.\n          apply False_ind.\n          apply H0.\n          exists O.\n          split; Col.\n        spliter.\n        induction(eq_dec_points B O).\n          auto.\n        apply False_ind.\n        apply grid_ok.\n        ColR.\n      assumption.\n    assert(A' <> O /\\ (Par_strict O E A' C' \\/ B = O)).\n      apply(sum_par_strict A B A A' C');auto.\n    spliter.\n    induction(eq_dec_points B O).\n      auto.\n    induction H13.\n      unfold Pj in *.\n      unfold Ar2 in H.\n      spliter.\n      induction H0.\n        induction H4.\n          assert(Par A A' A C').\n            apply (par_trans _ _ E E'); Par.\n          apply False_ind.\n          induction H18.\n            apply H18.\n            exists A.\n            split; Col.\n          spliter.\n          apply H13.\n          exists A.\n          split; Col.\n        subst C'.\n        apply False_ind.\n        apply H13.\n        exists A.\n        split; Col.\n      subst A'.\n      apply False_ind.\n      apply grid_ok.\n      apply(col_transitivity_1 _ A);Col.\n    contradiction.\nQed.\n\nLemma sum_A_B_B : forall A B, Sum O E E' A B B -> A = O.\nProof.\n    intros.\n    unfold Sum in H.\n    spliter.\n    ex_and H0 A'.\n    ex_and H1 C'.\n    assert(HH:= grid_not_par).\n    spliter.\n    unfold Pj in *.\n    unfold Ar2 in H.\n    spliter.\n    induction H3.\n      induction H4.\n        apply False_ind.\n        apply H7.\n        apply(par_trans _ _ B C'); Par.\n      subst C'.\n      apply par_distincts in H3.\n      tauto.\n    subst C'.\n    induction(eq_dec_points A O).\n      auto.\n    assert(A' <> O /\\ (Par_strict O E A' B \\/ B = O)).\n      apply(sum_par_strict A B B A' B);auto.\n        repeat split; auto.\n      unfold Pj.\n      auto.\n    spliter.\n    induction H15.\n      apply False_ind.\n      apply H15.\n      exists B.\n      split; Col.\n    subst B.\n    induction H2.\n      induction H2.\n        apply False_ind.\n        apply H2.\n        exists O.\n        split; Col.\n      spliter.\n      apply False_ind.\n      apply H.\n      ColR.\n    subst A'.\n    tauto.\nQed.\n\nLemma sum_uniquenessB : forall A X Y C, Sum O E E' A X C -> Sum O E E' A Y C -> X = Y.\nProof.\n    intros.\n    induction (eq_dec_points A O).\n      subst A.\n      assert(X = C).\n        apply(sum_O_B_eq X C H).\n      assert(Y = C).\n        apply(sum_O_B_eq Y C H0).\n      subst X.\n      subst Y.\n      auto.\n    assert(HSx:= H).\n    assert(HSy:= H0).\n    unfold Sum in H.\n    unfold Sum in H0.\n    spliter.\n    assert(Hx:=H).\n    assert(Hy:=H0).\n    unfold Ar2 in H.\n    unfold Ar2 in H0.\n    spliter.\n    ex_and H2 A''.\n    ex_and H10 C''.\n    ex_and H3 A'.\n    ex_and H14 C'.\n    clean_duplicated_hyps.\n    assert(A' <> O /\\ (Par_strict O E A' C' \\/ X = O)).\n      apply(sum_par_strict A X C A' C'); auto.\n    assert(A'' <> O /\\ (Par_strict O E A'' C'' \\/ Y = O)).\n      apply(sum_par_strict A Y C A'' C''); auto.\n    spliter.\n    unfold Pj in *.\n    induction(eq_dec_points X O).\n      subst X.\n      assert(HH:=sum_A_O A H7).\n      assert(C = A).\n        apply (sum_uniqueness A O); auto.\n      subst C.\n      assert(Y=O).\n        apply (sum_A_B_A A ); auto.\n      subst Y.\n      auto.\n    induction H2.\n      induction H3.\n        assert(Par A A' A A'').\n          apply (par_trans _ _ E E'); Par.\n        induction H19.\n          apply False_ind.\n          apply H19.\n          exists A.\n          split; Col.\n        spliter.\n        assert(A' = A'').\n          apply (l6_21 O E' A A'); Col.\n          intro.\n          apply grid_ok.\n          apply(col_transitivity_1 _ A); Col.\n        subst A''.\n        induction H4.\n          induction H6.\n            assert(Par A' C' A' C'').\n              apply(par_trans _ _ O E); left; Par.\n            induction H23.\n              apply False_ind.\n              apply H23.\n              exists A'.\n              split; Col.\n            spliter.\n            induction H13.\n              induction H17.\n                assert(Par C C' C C'').\n                  apply(par_trans _ _ E' E); Par.\n                induction H27.\n                  apply False_ind.\n                  apply H27.\n                  exists C.\n                  split; Col.\n                spliter.\n                assert(C' = C'').\n                  apply (l6_21 A' C' C C'); Col.\n                  intro.\n                  apply H6.\n                  exists C.\n                  split; Col.\n                subst C''.\n                clean_trivial_hyps.\n                induction H12.\n                  induction H16.\n                    assert(Par Y C' X C').\n                      apply (par_trans _ _ O E'); Par.\n                    induction H21.\n                      apply False_ind.\n                      apply H21.\n                      exists C'.\n                      split; Col.\n                    spliter.\n                    apply(l6_21 O E C' X); Col.\n                    intro.\n                    apply H4.\n                    exists C'.\n                    split; Col.\n                  subst X.\n                  clean_duplicated_hyps.\n                  apply False_ind.\n                  apply H6.\n                  exists C'.\n                  split; Col.\n                subst Y.\n                apply False_ind.\n                apply H6.\n                exists C'.\n                split; Col.\n              subst C'.\n              clean_duplicated_hyps.\n              clean_trivial_hyps.\n              apply False_ind.\n              apply H6.\n              exists C.\n              split; Col.\n            subst C''.\n            apply False_ind.\n            apply H4.\n            exists C.\n            split; Col.\n          subst X.\n          tauto.\n        subst Y.\n        assert(A = C).\n          apply(sum_A_O_eq A C HSy).\n        subst C.\n        clean_duplicated_hyps.\n        clean_trivial_hyps.\n        apply(sum_A_B_A A); auto.\n      subst A'.\n      clean_duplicated_hyps.\n      induction H15.\n        induction H6.\n          apply False_ind.\n          apply H3.\n          exists A.\n          split; Col.\n        subst X.\n        tauto.\n      subst C'.\n      induction H6.\n        apply False_ind.\n        apply H.\n        exists A.\n        split; Col.\n      contradiction.\n    subst A''.\n    induction H4.\n      apply False_ind.\n      apply H2.\n      exists A.\n      split; Col.\n    subst Y.\n    assert(A = C).\n      apply (sum_A_O_eq A C HSy).\n    subst C.\n    apply (sum_A_B_A A _ HSx).\nQed.\n\nLemma sum_uniquenessA : forall B X Y C, Sum O E E' X B C -> Sum O E E' Y B C -> X = Y.\nProof.\n    intros.\n    induction (eq_dec_points B O).\n      subst B.\n      assert(X = C).\n        apply(sum_A_O_eq X C H).\n      subst X.\n      assert(Y = C).\n        apply(sum_A_O_eq Y C H0).\n      subst Y.\n      auto.\n    assert(HSx:= H).\n    assert(HSy:= H0).\n    unfold Sum in H.\n    unfold Sum in H0.\n    spliter.\n    assert(Hx:=H).\n    assert(Hy:=H0).\n    unfold Ar2 in H.\n    unfold Ar2 in H0.\n    spliter.\n    ex_and H2 A''.\n    ex_and H10 C''.\n    ex_and H3 A'.\n    ex_and H14 C'.\n    clean_duplicated_hyps.\n    unfold Pj in *.\n    induction(eq_dec_points X O).\n      subst X.\n      assert(HH:=sum_O_B B H8).\n      assert(B = C).\n        apply (sum_uniqueness O B); auto.\n      subst C.\n      apply sym_equal.\n      apply (sum_A_B_B Y B); auto.\n    induction(eq_dec_points Y O).\n      subst Y.\n      assert(HH:=sum_O_B B H8).\n      assert(B = C).\n        apply (sum_uniqueness O B); auto.\n      subst C.\n      apply (sum_A_B_B X B); auto.\n    assert(A' <> O /\\ (Par_strict O E A' C' \\/ B = O)).\n      apply(sum_par_strict X B C A' C'); auto.\n    assert(A'' <> O /\\ (Par_strict O E A'' C'' \\/ B = O)).\n      apply(sum_par_strict Y B C A'' C''); auto.\n    spliter.\n    induction H12.\n      induction H16.\n        assert(Par B C' B C'').\n          apply (par_trans _ _ O E'); Par.\n        induction H20.\n          apply False_ind.\n          apply H20.\n          exists B.\n          split; Col.\n        spliter.\n        clean_trivial_hyps.\n        induction H13.\n          induction H17.\n            assert(Par C C' C C'').\n              apply (par_trans _ _ E E'); Par.\n            induction H22.\n              apply False_ind.\n              apply H22.\n              exists C.\n              split; Col.\n            spliter.\n            assert(C' = C'').\n              apply(l6_21 C C' B C'); Col.\n              intro.\n              induction H19.\n                apply H19.\n                exists C'.\n                split.\n                  assert(Col O B C).\n                    apply (col_transitivity_1 _ E); Col.\n                    intro.\n                    apply grid_ok.\n                    subst E.\n                    Col.\n                  assert(Col E B C).\n                    apply (col_transitivity_1 _ O); Col.\n                    intro.\n                    apply grid_ok.\n                    subst E.\n                    Col.\n                  apply(col3 B C); Col.\n                  intro.\n                  subst C.\n                  clean_trivial_hyps.\n                  apply(sum_A_B_B) in HSx.\n                  contradiction.\n                Col.\n              contradiction.\n            subst C''.\n            clean_trivial_hyps.\n            induction H19.\n              induction H18.\n                assert(Par A' C' A'' C').\n                  apply (par_trans _ _ O E);left; Par.\n                induction H23.\n                  apply False_ind.\n                  apply H23.\n                  exists C'.\n                  split; Col.\n                spliter.\n                assert(A'= A'').\n                  apply (l6_21 O E' C' A'); Col.\n                  intro.\n                  induction H16.\n                    apply H16.\n                    exists C'.\n                    split; Col.\n                  spliter.\n                  apply H1.\n                  apply (l6_21 O E C' O); Col.\n                    intro.\n                    apply grid_ok.\n                    ColR.\n                  intro.\n                  subst C'.\n                  clean_trivial_hyps.\n                  apply H18.\n                  exists O.\n                  split; Col.\n                subst A''.\n                clean_trivial_hyps.\n                clean_duplicated_hyps.\n                induction H2.\n                  induction H3.\n                    assert(Par Y A' X A').\n                      apply(par_trans _ _ E E'); Par.\n                    induction H6.\n                      apply False_ind.\n                      apply H6.\n                      exists A'.\n                      split; Col.\n                    spliter.\n                    apply (l6_21 O E A' X); Col.\n                    intro.\n                    apply H19.\n                    exists A'.\n                    split; Col.\n                  subst X.\n                  apply False_ind.\n                  apply H19.\n                  exists A'.\n                  split; Col.\n                subst Y.\n                apply False_ind.\n                apply H19.\n                exists A'.\n                split; Col.\n              contradiction.\n            contradiction.\n          subst C'.\n          apply False_ind.\n          induction H16.\n            apply H16.\n            exists O.\n            split.\n              Col.\n            apply(col3 O E); Col.\n            intro.\n            subst E.\n            apply grid_ok; Col.\n          spliter.\n          apply grid_ok.\n          apply(colx B C); Col.\n        subst C''.\n        apply False_ind.\n        induction H12.\n          apply H12.\n          exists O.\n          split.\n            Col.\n          apply(col3 O E); Col.\n          intro.\n          subst E.\n          apply grid_ok; Col.\n        spliter.\n        apply grid_ok.\n        apply(colx B C); Col.\n      apply False_ind.\n      subst C'.\n      induction H19.\n        apply H16.\n        exists B.\n        split; Col.\n      contradiction.\n    subst C''.\n    apply False_ind.\n    induction H18.\n      apply H12.\n      exists B.\n      split; Col.\n    contradiction.\nQed.\n\nLemma sum_B_null : forall A B, Sum O E E' A B A -> B = O.\nProof.\n    intros.\n    assert(HS:=H).\n    unfold Sum in H.\n    spliter.\n    unfold Ar2 in H.\n    spliter.\n    assert(HP:= sum_A_O A H1).\n    apply(sum_uniquenessB A B O A); auto.\nQed.\n\nLemma sum_A_null : forall A B, Sum O E E' A B B -> A = O.\nProof.\n    intros.\n    assert(HS:=H).\n    unfold Sum in H.\n    spliter.\n    unfold Ar2 in H.\n    spliter.\n    assert(HP:= sum_O_B B H2).\n    apply(sum_uniquenessA B A O B); auto.\nQed.\n\nLemma sum_plg : forall A B C, Sum O E E' A B C -> (A <> O ) \\/ ( B <> O) -> exists A', exists C', Plg O B C' A' /\\ Plg C' A' A C.\nProof.\n    intros.\n    assert(HS:=H).\n    unfold Sum in H.\n    spliter.\n    ex_and H1 A'.\n    ex_and H2 C'.\n    exists A'.\n    exists C'.\n    unfold Pj in *.\n    unfold Ar2 in H.\n    assert(HH:= grid_not_par).\n    spliter.\n    induction(eq_dec_points O B).\n      subst B.\n      assert(HH:=sum_A_O A H12).\n      assert(HP:=sum_uniqueness A O C A HS HH).\n      subst C.\n      induction H4.\n        induction H4.\n          apply False_ind.\n          apply H4.\n          exists O.\n          split; Col.\n        spliter.\n        induction H3.\n          induction H3.\n            apply False_ind.\n            apply H3.\n            exists O.\n            split.\n              Col.\n            apply (col_transitivity_1 _ E'); Col.\n          spliter.\n          apply False_ind.\n          apply grid_ok.\n          assert(Col C' O E).\n            ColR.\n          ColR.\n        subst C'.\n        split; apply parallelogram_to_plg; apply plg_trivial1.\n          auto.\n        intro.\n        subst A'.\n        apply H.\n        ColR.\n      subst C'.\n      apply False_ind.\n      induction H5.\n        apply H6.\n        apply par_symmetry.\n        apply (par_col_par _ _ _ A); Col; Par.\n      subst A.\n      induction H0; tauto.\n    induction(eq_dec_points A O).\n      subst A.\n      assert(HH:=sum_O_B B H13 ).\n      assert(HP:=sum_uniqueness O B C B HS HH).\n      subst C.\n      clean_trivial_hyps.\n      induction H1.\n        induction H1.\n          apply False_ind.\n          apply H1.\n          exists E'.\n          split; Col.\n        spliter.\n        apply False_ind.\n        apply H.\n        apply (col_transitivity_1 _ A'); Col.\n      subst A'.\n      clean_trivial_hyps.\n      induction H5.\n        induction H4.\n          apply False_ind.\n          apply H8.\n          apply (par_trans _ _ B C'); Par.\n        subst C'.\n        split; apply parallelogram_to_plg; apply plg_trivial; auto.\n      subst C'.\n      split; apply parallelogram_to_plg; apply plg_trivial; auto.\n    assert(A' <> O).\n      intro.\n      subst A'.\n      induction H1.\n        apply H6.\n        apply par_symmetry.\n        apply (par_col_par _ _ _ A); Col;Par.\n      contradiction.\n    assert(A' <> O /\\ (Par_strict O E A' C' \\/ B = O)).\n      apply(sum_par_strict A B C A' C');auto.\n      repeat split; auto.\n    spliter.\n    induction H19.\n      assert(Par O B C' A').\n        apply par_symmetry.\n        apply (par_col_par _ _ _ E); Par.\n      assert(Par_strict O B C' A').\n        induction H20.\n          auto.\n        spliter.\n        apply False_ind.\n        apply H19.\n        exists O.\n        split; Col.\n      (*Par O A' B C'*)\n      induction H4.\n        assert(Par O A' B C').\n          apply par_symmetry.\n          apply (par_col_par _ _ _ E'); Par; Col.\n        assert(HX:= pars_par_plg O B C' A' H21 H22).\n        assert(Par C' A' A C).\n          apply(par_col_par _ _ _ O).\n            intro.\n            subst C.\n            apply H15.\n            apply sym_equal.\n            apply(sum_A_B_A A); auto.\n            apply par_right_comm.\n            apply(par_col_par _ _ _ B).\n              auto.\n              Par.\n            ColR.\n          ColR.\n        assert(Par_strict C' A' A C).\n          induction H23.\n            auto.\n          spliter.\n          apply False_ind.\n          apply H19.\n          exists C'.\n          split.\n            ColR.\n          Col.\n        induction H1.\n          induction H5.\n            assert(Par C' C A' A).\n              apply (par_trans _ _ E E'); Par.\n            assert(HY:= pars_par_plg C' A' A C H24 H25).\n            split; auto.\n          subst C'.\n          assert_diffs;contradiction.\n        split; Col.\n        subst A'.\n        assert_diffs.\n        contradiction.\n      subst C'.\n      assert_diffs.\n      contradiction.\n    subst B.\n    tauto.\nQed.\n\nLemma sum_cong : forall A B C, Sum O E E' A B C -> (A <> O \\/ B <> O) -> Parallelogram_flat O A C B.\nProof.\n    intros.\n    induction(eq_dec_points A O).\n      subst A.\n      assert(HP:= (sum_O_B_eq B C H)).\n      subst C.\n      induction H0.\n        tauto.\n      assert(Parallelogram O O B B).\n        apply plg_trivial1; auto.\n      induction H1.\n        apply False_ind.\n        unfold Parallelogram_strict in H1.\n        spliter.\n        apply par_distincts in H2.\n        tauto.\n      assumption.\n    assert(exists A' C' : Tpoint, Plg O B C' A' /\\ Plg C' A' A C).\n      apply(sum_plg A B C); auto.\n    ex_and H2 A'.\n    ex_and H3 C'.\n    apply plg_to_parallelogram in H2.\n    apply plg_to_parallelogram in H3.\n    apply plgf_permut.\n    assert(HH:=plg_pseudo_trans O B C' A' A C H2 H3).\n    induction HH.\n      induction H4.\n        apply False_ind.\n        apply H4.\n        unfold Sum in H.\n        spliter.\n        unfold Ar2 in H.\n        spliter.\n        assert_diffs.\n        ColR.\n      apply plgf_comm2.\n      auto.\n    spliter.\n    subst A.\n    apply False_ind.\n    subst C.\n    tauto.\nQed.\n\nLemma sum_cong2 : forall A B C,\n  Sum O E E' A B C ->\n  (A <> O \\/ B <> O) ->\n  (Cong O A B C /\\ Cong O B A C).\nProof.\nintros.\napply sum_cong in H.\nunfold Parallelogram_flat in *.\nspliter;split;Cong.\nassumption.\nQed.\n\nLemma sum_comm : forall A B C, Sum O E E' A B C -> Sum O E E' B A C.\nProof.\n    intros.\n    induction (eq_dec_points B O).\n      subst B.\n      assert(Col O E A).\n        unfold Sum in H.\n        spliter.\n        unfold Ar2 in H.\n        tauto.\n      assert(C = A).\n        apply (sum_uniqueness A O).\n          auto.\n        apply sum_A_O.\n        auto.\n      subst C.\n      apply sum_O_B.\n      auto.\n    induction(eq_dec_points A O).\n      subst A.\n      assert(Col O E B).\n        unfold Sum in H.\n        spliter.\n        unfold Ar2 in H.\n        tauto.\n      assert(B = C).\n        apply (sum_uniqueness O B).\n          apply sum_O_B.\n          Col.\n        auto.\n      subst C.\n      apply sum_A_O.\n      Col.\n    assert(A <> O \\/ B <> O).\n      left.\n      auto.\n    assert(HH:=grid_not_par).\n    spliter.\n    assert(HH := sum_plg A B C H H2).\n    ex_and HH A'.\n    ex_and H9 C'.\n    assert(exists ! P' : Tpoint, Proj B P' O E' E E').\n      apply(project_existence B O E' E E'); auto.\n      intro.\n      apply H5.\n      Par.\n    unfold unique in H11.\n    ex_and H11 B'.\n    clear H12.\n    assert(HH:= parallel_existence1 O E B' H6).\n    ex_and HH P'.\n    assert(exists! P : Tpoint, Proj A P B' P' O E').\n      apply(project_existence A B' P' O E'); auto.\n      apply par_distincts in H12.\n      spliter.\n      auto.\n      intro.\n      apply H4.\n      apply(par_trans _ _ B' P'); Par.\n    unfold unique in H13.\n    ex_and H13 D'.\n    clear H14.\n    assert( Ar2 O E E' A B C).\n      unfold Sum in H.\n      tauto.\n    assert(HH:= sum_to_sump O E E' A B C H).\n    unfold Sump in H13.\n    apply sump_to_sum.\n    unfold Sump.\n    unfold Ar2 in H14.\n    spliter.\n    repeat split; Col.\n    exists B'.\n    exists D'.\n    exists P'.\n    split; auto.\n    split; auto.\n    split; auto.\n    assert(Par_strict O E B' P').\n      induction H12.\n        auto.\n      spliter.\n      apply False_ind.\n      assert(HA:=H11).\n      unfold Proj in H11.\n      spliter.\n      assert(Col B' O E).\n        apply (col_transitivity_1 _ P'); Col.\n      assert(B' <> O).\n        intro.\n        subst B'.\n        apply project_id in HA.\n          contradiction.\n        induction H24.\n          induction H24.\n            apply False_ind.\n            apply H24.\n            exists E.\n            split; Col.\n          spliter.\n          contradiction.\n        contradiction.\n      apply grid_ok.\n      apply (col_transitivity_1 _ B'); Col.\n    assert(Par O A B' D').\n      apply (par_col_par _ _ _ P').\n        intro.\n        subst D'.\n        unfold Proj in *.\n        spliter.\n        induction H22.\n          induction H22.\n            apply H22.\n            exists B'.\n            split; Col.\n          spliter.\n          apply grid_ok.\n          apply (col_transitivity_1 _ A); Col.\n        subst B'.\n        apply H18.\n        exists A.\n        split; Col.\n        apply par_symmetry.\n        apply (par_col_par _ _ _ E); Col; Par.\n      unfold Proj in H13.\n      spliter.\n      Col.\n    assert(Par_strict O A B' D').\n      induction H19.\n        auto.\n      spliter.\n      apply False_ind.\n      apply H18.\n      unfold Proj in H13.\n      spliter.\n      exists O.\n      split.\n        Col.\n      apply col_permutation_2.\n      apply (col_transitivity_1 _ D'); Col.\n    assert(Par O B' A D').\n      unfold Proj in H13.\n      spliter.\n      induction H24.\n        apply par_symmetry.\n        apply(par_col_par _ _ _ E'); Par.\n          intro.\n          subst B'.\n          apply H20.\n          exists O.\n          split;Col.\n        unfold Proj in H11.\n        spliter.\n        auto.\n      subst D'.\n      apply False_ind.\n      apply H20.\n      exists A.\n      split; Col.\n    assert(Plg O A D' B').\n      apply(pars_par_plg O A D' B' ); Par.\n    assert(HT:=sum_cong A B C H H2).\n    assert(Parallelogram D' B' B C \\/ D' = B' /\\ O = A /\\ C = B /\\ D' = C).\n      apply(plg_pseudo_trans D' B' O A C B).\n        apply plg_to_parallelogram in H22.\n        apply plg_permut in H22.\n        apply plg_permut in H22.\n        auto.\n      right.\n      auto.\n    induction H23.\n      repeat split; auto.\n      apply plg_permut in H23.\n      apply plg_par in H23.\n        unfold Proj in *.\n        spliter.\n        induction H32.\n          left.\n          apply (par_trans _ _ B B'); Par.\n        subst B'.\n        apply par_distincts in H23.\n        tauto.\n        intro.\n        subst B'.\n        apply H20.\n        exists B.\n        split.\n          ColR.\n        Col.\n      intro.\n      subst C.\n      assert(HN:= sum_A_null A B H).\n      contradiction.\n    spliter.\n    subst A.\n    tauto.\nQed.\n\nLemma cong_sum : forall A B C,\n  O <> C \\/ B <> A -> Ar2 O E E' A B C ->\n  Cong O A B C -> Cong O B A C ->\n  Sum O E E' A B C.\nProof.\n    intros A B C.\n    intro Hor.\n    intros.\n    induction (eq_dec_points A O).\n      subst A.\n      unfold Ar2 in H.\n      spliter.\n      apply cong_symmetry in H0.\n      apply cong_identity in H0.\n      subst C.\n      apply sum_O_B; Col.\n    induction (eq_dec_points B O).\n      subst B.\n      unfold Ar2 in H.\n      spliter.\n      apply cong_symmetry in H1.\n      apply cong_identity in H1.\n      subst C.\n      apply sum_A_O; Col.\n    unfold Sum.\n    split; auto.\n    unfold Ar2 in H.\n    assert(HH:=grid_not_par).\n    spliter.\n    assert(exists ! P' : Tpoint, Proj A P' O E' E E').\n      apply(project_existence A O E' E E'); auto.\n      intro.\n      apply H6.\n      Par.\n    ex_and H13 A'.\n    unfold unique in H14.\n    spliter.\n    clear H14.\n    unfold Proj in H13.\n    spliter.\n    clean_duplicated_hyps.\n    assert(HH:=parallel_existence1 O E A' H7).\n    ex_and HH P'.\n    assert(exists ! C' : Tpoint, Proj B C' A' P' O E').\n      apply(project_existence B A' P' O E'); auto.\n      apply par_distincts in H.\n      spliter.\n      auto.\n      intro.\n      apply H5.\n      apply(par_trans _ _ A' P'); Par.\n    ex_and H13 C'.\n    unfold unique in H14.\n    spliter.\n    clear H14.\n    unfold Proj in H13.\n    spliter.\n    exists A'.\n    exists C'.\n    assert(A' <> O).\n      intro.\n      subst A'.\n      induction H17.\n        induction H17.\n          apply H17.\n          exists E.\n          split; Col.\n        spliter.\n        contradiction.\n      contradiction.\n    assert(Par_strict O E A' P').\n      unfold Par_strict.\n      repeat split; auto; try apply all_coplanar.\n      intro.\n      ex_and H21 X.\n      induction H.\n        apply H.\n        exists X.\n        split; Col.\n      spliter.\n      apply grid_ok.\n      ColR.\n    assert(A <> A').\n      intro.\n      subst A'.\n      apply H21.\n      exists A.\n      split; Col.\n    repeat split; Col.\n      induction H17.\n        left; Par.\n      right; auto.\n      left.\n      apply (par_col_par _ _ _ P').\n        intro.\n        subst C'.\n        induction H19.\n          induction H19.\n            apply H19.\n            exists A'.\n            split; Col.\n          spliter.\n          apply grid_ok.\n          ColR.\n        subst A'.\n        apply H21.\n        exists B.\n        split; Col.\n        Par.\n      Col.\n      induction H19.\n        left.\n        Par.\n      right.\n      auto.\n    assert(A' <> C').\n      intro.\n      subst C'.\n      induction H19.\n        induction H19.\n          apply H19.\n          exists A'.\n          split; Col.\n        spliter.\n        apply grid_ok.\n        ColR.\n      subst A'.\n      apply H21.\n      exists B.\n      split; Col.\n    assert(Plg O B C' A').\n      apply(pars_par_plg O B C' A').\n        apply par_strict_right_comm.\n        apply(par_strict_col_par_strict _ _ _ P').\n          auto.\n          apply par_strict_symmetry.\n          apply(par_strict_col_par_strict _ _ _ E).\n            auto.\n            Par.\n          Col.\n        Col.\n      induction H19.\n        apply par_symmetry.\n        apply(par_col_par _ _ _ E').\n          auto.\n          Par.\n        Col.\n      subst C'.\n      apply False_ind.\n      apply H21.\n      exists B.\n      split; Col.\n    assert(Plg O B C A).\n      apply(parallelogram_to_plg).\n      right.\n      unfold Parallelogram_flat.\n      repeat split; try ColR.\n        Cong.\n        Cong.\n      auto.\n    apply plg_to_parallelogram in H24.\n    apply plg_to_parallelogram in H25.\n    assert(Parallelogram A C C' A').\n      assert(Parallelogram C A A' C' \\/ C = A /\\ O = B /\\ C' = A' /\\ C = C').\n        apply(plg_pseudo_trans C A O B C' A').\n          apply plg_permut.\n          apply plg_permut.\n          assumption.\n        assumption.\n      induction H26.\n        apply plg_comm2.\n        assumption.\n      spliter.\n      subst C'.\n      subst A'.\n      tauto.\n    apply plg_par in H26.\n      spliter.\n      induction H17.\n        left.\n        apply(par_trans _ _ A A'); Par.\n      contradiction.\n      intro.\n      subst C.\n      apply cong_identity in H1.\n      subst B.\n      tauto.\n    intro.\n    subst C'.\n    apply plg_permut in H26.\n    induction H19.\n      induction H19.\n        apply H19.\n        exists O.\n        split; Col.\n        ColR.\n      spliter.\n      apply grid_ok.\n      ColR.\n    subst C.\n    apply H21.\n    exists B.\n    split; Col.\nQed.\n\nLemma sum_iff_cong : forall A B C,\n  Ar2 O E E' A B C -> (O <> C \\/ B <> A) ->\n ((Cong O A B C /\\ Cong O B A C) <-> Sum O E E' A B C).\nProof.\nintros.\nsplit.\nintros.\napply cong_sum;intuition idtac.\nintros.\napply sum_cong2.\nassumption.\ndestruct H.\nelim (eq_dec_points A O); intro.\nsubst.\nright.\nintro.\nsubst.\nassert (T:= sum_O_O).\ndestruct H0.\napply H0.\neauto using sum_uniqueness.\nintuition.\nintuition.\nQed.\n\nLemma opp_comm : forall X Y, Opp O E E' X Y -> Opp O E E' Y X.\nProof.\n    intros.\n    unfold Opp in *.\n    apply sum_comm.\n    auto.\nQed.\n\nLemma opp_uniqueness :\n forall A MA1 MA2,\n Opp O E E' A MA1 ->\n Opp O E E' A MA2 ->\n MA1 = MA2.\nProof.\n    intros.\n    unfold Opp in *.\n    apply sum_comm in H.\n    apply sum_comm in H0.\n    induction(eq_dec_points A O).\n      subst A.\n      assert(HH:=sum_uniquenessB O MA1 MA2 O H H0).\n      assumption.\n    apply sum_plg in H.\n      apply sum_plg in H0.\n        ex_and H A'.\n        ex_and H2 C'.\n        ex_and H0 A''.\n        ex_and H3 C''.\n        apply plg_to_parallelogram in H.\n        apply plg_to_parallelogram in H0.\n        apply plg_to_parallelogram in H2.\n        apply plg_to_parallelogram in H3.\n        assert(Parallelogram C' A' A'' C'' \\/ C' = A' /\\ A = O /\\ C'' = A'' /\\ C' = C'').\n          apply(plg_pseudo_trans C' A' A O C'' A''); auto.\n          apply plg_permut.\n          apply plg_permut.\n          auto.\n        induction H4.\n          assert(Parallelogram O MA1 C'' A'' \\/ O = MA1 /\\ C' = A' /\\ A'' = C'' /\\ O = A'').\n            apply(plg_pseudo_trans O MA1 C' A' A'' C''); auto.\n          induction H5.\n            assert(Parallelogram O MA1 MA2 O \\/ O = MA1 /\\ C'' = A'' /\\ O = MA2 /\\ O = O).\n              apply(plg_pseudo_trans O MA1 C'' A'' O MA2); auto.\n              apply plg_permut.\n              apply plg_permut.\n              assumption.\n            induction H6.\n              unfold Parallelogram in H6.\n              induction H6.\n                unfold Parallelogram_strict in H6.\n                spliter.\n                unfold TS in H6.\n                spliter.\n                apply False_ind.\n                apply H9.\n                Col.\n              unfold Parallelogram_flat in H6.\n              spliter.\n              apply cong_symmetry in H9.\n              apply cong_identity in H9.\n              auto.\n            spliter.\n            subst MA1.\n            subst MA2.\n            auto.\n          spliter.\n          subst MA1.\n          subst C''.\n          subst A''.\n          subst C'.\n          unfold Parallelogram in H0.\n          induction H0.\n            unfold Parallelogram_strict in H0.\n            spliter.\n            apply par_distincts in H5.\n            tauto.\n          unfold Parallelogram_flat in H0.\n          spliter.\n          apply cong_identity in H6.\n          auto.\n        spliter.\n        contradiction.\n      left; auto.\n    left; auto.\nQed.\n\nEnd Grid.\n\nLemma pj_uniqueness : forall O E E' A A' A'', ~Col O E E' -> Col O E A -> Col O E' A' -> Col O E' A'' -> Pj E E' A A' -> Pj E E' A A'' -> A' = A''.\nProof.\n    intros.\n    unfold Pj in *.\n    induction(eq_dec_points A O).\n      subst A.\n      assert(HH:= grid_not_par O E E' H).\n      spliter.\n      induction H3.\n        apply False_ind.\n        apply H7.\n        apply par_symmetry.\n        apply (par_col_par _ _ _ A'); Col.\n      subst A'.\n      induction H4.\n        apply False_ind.\n        apply H7.\n        apply par_symmetry.\n        apply (par_col_par _ _ _ A''); Col.\n      auto.\n    induction H3; induction H4.\n      assert(Par A A' A A'').\n        apply (par_trans _ _ E E'); Par.\n      induction H6.\n        apply False_ind.\n        apply H6.\n        exists A.\n        split; Col.\n      spliter.\n      apply(l6_21 O E' A A'); Col.\n      intro.\n      apply H.\n      ColR.\n      auto.\n      subst A''.\n      apply False_ind.\n      apply H.\n      ColR.\n      auto.\n      subst A'.\n      apply False_ind.\n      apply H.\n      ColR.\n    congruence.\nQed.\n\nLemma pj_right_comm : forall A B C D, Pj A B C D -> Pj A B D C.\nProof.\n    intros.\n    unfold Pj in *.\n    induction H.\n      left.\n      Par.\n    right.\n    auto.\nQed.\n\nLemma pj_left_comm : forall A B C D, Pj A B C D -> Pj B A C D.\nProof.\n    intros.\n    unfold Pj in *.\n    induction H.\n      left.\n      Par.\n    right.\n    auto.\nQed.\n\nLemma pj_comm : forall A B C D, Pj A B C D -> Pj B A D C.\nProof.\n    intros.\n    apply pj_left_comm.\n    apply pj_right_comm.\n    auto.\nQed.\n\n(** Lemma 14.13 *)\n(** Parallel projection on the second axis preserves sums. *)\n\nLemma proj_preserves_sum :\n forall O E E' A B C A' B' C',\n Sum O E E' A B C ->\n Ar1 O E' A' B' C' ->\n Pj E E' A A' ->\n Pj E E' B B' ->\n Pj E E' C C' ->\n Sum O E' E A' B' C'.\nProof.\n    intros.\n    assert(HH:= H).\n    unfold Sum in HH.\n    spliter.\n    ex_and H5 A0.\n    ex_and H6 C0.\n    unfold Ar2 in H4.\n    spliter.\n    assert(HH:= grid_not_par O E E' H4).\n    unfold Ar1 in H0.\n    spliter.\n    induction(eq_dec_points A O).\n      subst A.\n      unfold Pj in H1.\n      induction H1.\n        apply False_ind.\n        apply H15.\n        apply par_symmetry. (* TODO ameliorier perm apply pour gerer les _ *)\n        apply (par_col_par _ _ _ A');Col.\n      subst A'.\n      assert(B = C).\n        apply (sum_O_B_eq O E E'); auto.\n      subst C.\n      assert(B' = C').\n        apply (pj_uniqueness O E E' B); Col.\n      subst C'.\n      apply sum_O_B; Col.\n    induction(eq_dec_points B O).\n      subst B.\n      unfold Pj in H2.\n      induction H2.\n        apply False_ind.\n        apply H15.\n        apply par_symmetry.\n        apply (par_col_par _ _ _ B'); Col.\n      subst B'.\n      assert(A = C).\n        apply (sum_A_O_eq O E E'); auto.\n      subst C.\n      assert(A' = C').\n        apply (pj_uniqueness O E E' A); Col.\n      subst C'.\n      apply sum_A_O; Col.\n    assert(A' <> O).\n      intro.\n      subst A'.\n      unfold Pj in H1.\n      induction H1.\n        apply H13.\n        apply par_symmetry.\n        apply (par_col_par _ _ _ A); Par; Col.\n      contradiction.\n    assert(B' <> O).\n      intro.\n      subst B'.\n      unfold Pj in H2.\n      induction H2.\n        apply H13.\n        apply par_symmetry.\n        apply (par_col_par _ _ _ B); Par.\n        Col.\n      contradiction.\n    unfold Sum.\n    spliter.\n    split.\n      repeat split; Col.\n    assert(HH:=plg_existence A O B' H22).\n    ex_and HH D.\n    exists A.\n    exists D.\n    assert(HP:= H26).\n    apply plg_par in H26.\n      spliter.\n      repeat split; Col.\n        apply pj_comm; auto.\n        left.\n        apply par_symmetry.\n        apply(par_col_par _ _ _ B'); Col.\n        left.\n        apply par_symmetry.\n        apply(par_col_par _ _ _ A); Par; Col.\n      assert(Parallelogram_flat O A C B).\n        apply(sum_cong O E E' H4 A B C H).\n        left; auto.\n      assert(Parallelogram B' D C B \\/ B' = D /\\ A = O /\\ B = C /\\ B' = B).\n        apply(plg_pseudo_trans B' D A O B C).\n          apply plg_permut.\n          apply plg_permut.\n          auto.\n        apply plg_comm2.\n        right.\n        auto.\n      induction H29.\n        apply plg_par in H29.\n          spliter.\n          induction H2.\n            induction H3.\n              assert(Par B B' C C').\n                apply (par_trans _ _ E E'); Par.\n              assert(Par C D C C').\n                apply(par_trans _ _ B B'); Par.\n              induction H32.\n                apply False_ind.\n                apply H32.\n                exists C.\n                split; Col.\n              spliter.\n              left.\n              apply par_right_comm.\n              apply (par_col_par _ _ _ C); Col; Par.\n              intro.\n              subst D.\n              induction H29.\n                apply H29.\n                exists O.\n                split; ColR.\n              spliter.\n              apply H25.\n              apply(l6_21 O E E' O); ColR.\n            subst C'.\n            left.\n            apply (par_trans _ _ B B'); Par.\n          subst B'.\n          apply par_distincts in H30.\n          tauto.\n          intro.\n          subst D.\n          apply par_distincts in H26.\n          tauto.\n        intro.\n        subst D.\n        induction H27.\n          apply H27.\n          exists O.\n          split; ColR.\n        spliter.\n        apply H4.\n        apply (col_transitivity_1 _ A).\n          auto.\n          Col.\n        apply (col_transitivity_1 _ B'); Col.\n      spliter.\n      contradiction.\n      intro.\n      subst.\n      intuition.\n    intuition.\nQed.\n\n(** Lemma 14.14 *)\nLemma sum_assoc_1 : forall O E E' A B C AB BC ABC,\n  Sum O E E' A B AB -> Sum O E E' B C BC -> Sum O E E' A BC ABC ->\n  Sum O E E' AB C ABC.\nProof.\n    intros.\n    assert(HS1:=H).\n    assert(HS2:=H0).\n    assert(HS3:=H1).\n    unfold Sum in H.\n    unfold Sum in H0.\n    unfold Sum in H1.\n    spliter.\n    assert(HA1:= H).\n    assert(HA2:= H0).\n    assert(HA3 := H1).\n    unfold Ar2 in H.\n    unfold Ar2 in H0.\n    unfold Ar2 in H1.\n    clear H2.\n    clear H3.\n    clear H4.\n    spliter.\n    clean_duplicated_hyps.\n    induction (eq_dec_points A O).\n      subst A.\n      assert(HH:= sum_O_B_eq O E E' H B AB HS1).\n      subst AB.\n      assert(HH:= sum_O_B_eq O E E' H BC ABC HS3).\n      subst BC.\n      auto.\n    induction (eq_dec_points B O).\n      subst B.\n      assert(HH:= sum_A_O_eq O E E' H A AB HS1).\n      subst AB.\n      assert(HH:= sum_O_B_eq O E E' H C BC HS2).\n      subst BC.\n      auto.\n    induction (eq_dec_points C O).\n      subst C.\n      assert(HH:= sum_A_O_eq O E E' H B BC HS2).\n      subst BC.\n      assert(HH:=sum_uniqueness O E E' A B AB ABC HS1 HS3).\n      subst AB.\n      apply sum_A_O; Col.\n    assert(HH:= grid_not_par O E E' H).\n    spliter.\n    apply sum_comm in HS1; auto.\n    apply sum_comm in HS3; auto.\n    assert(S1:=HS1).\n    assert(S2:=HS2).\n    assert(S3:=HS3).\n    unfold Sum in HS1.\n    unfold Sum in HS2.\n    unfold Sum in HS3.\n    spliter.\n    ex_and H20 B1'.\n    ex_and H21 A1.\n    ex_and H18 B1''.\n    ex_and H25 C1.\n    ex_and H16 BC3'.\n    ex_and H29 A3.\n    assert(B1'=B1'').\n      apply (pj_uniqueness O E E' B B1' B1''); Col.\n    subst B1''.\n    clean_duplicated_hyps.\n    assert(HH:=sum_par_strict O E E' H B A AB B1' A1 H19 H1 H20 H21 H22 H23 H24).\n    spliter.\n    assert(Par_strict O E B1' A1).\n      induction H25.\n        auto.\n      contradiction.\n    clear H25.\n    clear H22.\n    assert(HH:=grid_not_par O E E' H).\n    spliter.\n    assert(exists ! P' : Tpoint, Proj AB P' O E' E E').\n      apply(project_existence AB O E' E E' H37 H36).\n      intro.\n      apply H34.\n      Par.\n    ex_and H38 AB2'.\n    unfold unique in H39.\n    spliter.\n    clear H39.\n    unfold Proj in H38.\n    spliter.\n    clean_duplicated_hyps.\n    assert(A <> AB).\n      intro.\n      subst AB.\n      apply sum_A_B_B in S1.\n        contradiction.\n      auto.\n    assert(ABC <> AB).\n      intro.\n      subst ABC.\n      assert(HP := sum_uniquenessA O E E' H A BC B AB S3 S1).\n      subst BC.\n      apply sum_A_B_A in S2; auto.\n    assert(HH:=plg_existence C O AB2' H2).\n    ex_and HH C2.\n    induction H42.\n      assert(AB <> AB2').\n        intro.\n        subst AB2'.\n        apply par_distincts in H35.\n        tauto.\n      assert(Pl:=H34).\n      assert(O <> AB2').\n        intro.\n        subst AB2'.\n        assert(HH:=plg_trivial C O H2).\n        assert(HP:= plg_uniqueness C O O C C2 HH Pl).\n        subst C2.\n        induction H35.\n          apply H35.\n          exists E.\n          split; Col.\n        spliter.\n        contradiction.\n      apply plg_par in H34; auto.\n      spliter.\n      repeat split; Col.\n      exists AB2'.\n      exists C2.\n      repeat split.\n        left; Par.\n        Col.\n        left.\n        apply (par_trans _ _ O C);Par.\n        right.\n        repeat split; Col.\n        left.\n        apply (par_trans _ _ O AB2'); Par.\n        right.\n        repeat split; Col.\n      assert(Parallelogram O BC ABC A).\n        right.\n        apply(sum_cong O E E' H BC A ABC S3);auto.\n      assert(Parallelogram O B AB A).\n        right.\n        apply(sum_cong O E E' H B A AB S1); auto.\n      assert(Parallelogram O B BC C ).\n        right.\n        apply(sum_cong O E E' H B C BC); auto.\n      assert( Parallelogram B AB ABC BC \\/ B = AB /\\ A = O /\\ BC = ABC /\\ B = BC).\n        apply(plg_pseudo_trans B AB A O BC ABC).\n          apply plg_permut.\n          assumption.\n        apply plg_permut.\n        apply plg_permut.\n        apply plg_permut.\n        assumption.\n      assert(Parallelogram B AB ABC BC).\n        induction H43.\n          assumption.\n        spliter.\n        contradiction.\n      clear H43.\n      assert(Parallelogram O C ABC AB \\/ O = C /\\ BC = B /\\ AB = ABC /\\ O = AB).\n        apply(plg_pseudo_trans O C BC B AB ABC).\n          apply plg_permut.\n          apply plg_comm2.\n          assumption.\n        apply plg_permut.\n        apply plg_permut.\n        apply plg_permut.\n        assumption.\n      assert(Parallelogram O C ABC AB).\n        induction H43.\n          assumption.\n        spliter.\n        subst C.\n        tauto.\n      clear H43.\n      assert(Parallelogram ABC AB AB2' C2 \\/ ABC = AB /\\ O = C /\\ C2 = AB2' /\\ ABC = C2).\n        apply(plg_pseudo_trans ABC AB O C C2 AB2').\n          apply plg_permut.\n          apply plg_permut.\n          assumption.\n        apply plg_comm2.\n        assumption.\n      assert(Parallelogram ABC AB AB2' C2).\n        induction H43.\n          assumption.\n        spliter.\n        subst C.\n        tauto.\n      clear H43.\n      apply plg_par in H46; auto.\n      spliter.\n      left.\n      apply(par_trans _ _ AB AB2'); Par.\n    subst AB2'.\n    assert(AB = O).\n      apply(l6_21 O E E' O); Col.\n    subst AB.\n    assert(HH:= plg_trivial C O H2).\n    assert(Hp:= plg_uniqueness C O O C C2 HH H34).\n    subst C2.\n    assert(Parallelogram_flat O B BC C).\n      apply(sum_cong O E E' H B C BC);auto.\n    assert(Parallelogram_flat O BC ABC A).\n      apply(sum_cong O E E' H BC A ABC);auto.\n    assert(Parallelogram_flat O B O A).\n      apply(sum_cong O E E' H B A O); auto.\n    assert(Parallelogram BC C A O \\/ BC = C /\\ O = B /\\ O = A /\\ BC = O).\n      apply(plg_pseudo_trans BC C O B O A).\n        apply plg_permut.\n        apply plg_permut.\n        right; assumption.\n      right; assumption.\n    assert(Parallelogram BC C A O).\n      induction H38.\n        assumption.\n      spliter.\n      subst A.\n      tauto.\n    clear H38.\n    assert(Parallelogram O BC ABC A).\n      right; assumption.\n    apply plg_permut in H38.\n    apply plg_permut in H38.\n    apply plg_permut in H38.\n    apply plg_permut in H39.\n    apply plg_permut in H39.\n    assert(HP:=plg_uniqueness A O BC C ABC H39 H38).\n    subst ABC.\n    apply sum_O_B; Col.\nQed.\n\nLemma sum_assoc_2 : forall O E E' A B C AB BC ABC,\n Sum O E E' A B AB ->\n Sum O E E' B C BC ->\n Sum O E E' AB C ABC ->\n Sum O E E' A BC ABC.\nProof.\n    intros.\n    assert(HS1:=H).\n    assert(HS2:=H0).\n    assert(HS3:=H1).\n    unfold Sum in H.\n    unfold Sum in H0.\n    unfold Sum in H1.\n    spliter.\n    unfold Ar2 in H.\n    spliter.\n    clean_duplicated_hyps.\n    apply sum_comm; auto.\n    apply(sum_assoc_1 O E E' C B A BC AB ABC ).\n      apply sum_comm; auto.\n      apply sum_comm; auto.\n    apply sum_comm; auto.\nQed.\n\nLemma sum_assoc : forall O E E' A B C AB BC ABC,\n  Sum O E E' A B AB ->\n  Sum O E E' B C BC ->\n  (Sum O E E' A BC ABC <-> Sum O E E' AB C ABC).\nProof.\n    intros.\n    split; intro.\n      apply(sum_assoc_1 O E E' A B C AB BC ABC); auto.\n    apply(sum_assoc_2 O E E' A B C AB BC ABC); auto.\nQed.\n\n(** Lemma 14.15 *)\n(** The choice of E' does not affect sum. *)\nLemma sum_y_axis_change :\n forall O E E' E'' A B C,\n  Sum O E E' A B C ->\n  ~ Col O E E'' ->\n  Sum O E E'' A B C.\nProof.\n    intros.\n    assert(HS:= H).\n    assert(Ar2 O E E' A B C).\n      unfold Sum in H.\n      tauto.\n    assert(HA:=H1).\n    unfold Ar2 in H1.\n    spliter.\n    assert(HH:=grid_not_par O E E' H1).\n    spliter.\n    induction(eq_dec_points A O).\n      subst A.\n      apply sum_O_B_eq in H; Col.\n      subst C.\n      apply sum_O_B; Col.\n    induction(eq_dec_points B O).\n      subst B.\n      apply sum_A_O_eq in H; Col.\n      subst C.\n      apply sum_A_O; Col.\n    apply sum_plg in H; auto.\n    ex_and H A'.\n    ex_and H13 C'.\n    assert(exists ! P' : Tpoint, Proj A P' O E'' E E'').\n      apply(project_existence A O E'' E E''); intro; try (subst E''; apply H0; Col).\n      induction H14.\n        apply H14.\n        exists E''.\n        split; Col.\n      spliter.\n      apply H0.\n      Col.\n    ex_and H14 A''.\n    unfold unique in H15.\n    spliter.\n    clear H15.\n    unfold Proj in H14.\n    spliter.\n    assert(Par A A'' E E'').\n      induction H18; auto.\n      subst A''.\n      apply False_ind.\n      apply H0.\n      ColR.\n    clear H18.\n    assert(HH:= plg_existence B O A'' H12).\n    ex_and HH C''.\n    apply plg_to_parallelogram in H.\n    apply plg_to_parallelogram in H13.\n    assert(A'' <> O).\n      intro.\n      subst A''.\n      induction H19.\n        apply H19.\n        exists E.\n        split; Col.\n      spliter.\n      contradiction.\n    repeat split; Col.\n    exists A''.\n    exists C''.\n    repeat split.\n      left.\n      Par.\n      Col.\n      apply plg_par in H18; auto.\n      spliter.\n      left.\n      apply par_symmetry.\n      apply (par_col_par _ _ _ B); Par; Col.\n      apply plg_par in H18; auto.\n      spliter.\n      left.\n      apply par_symmetry.\n      apply (par_col_par _ _ _ A''); Par; Col.\n    left.\n    assert(Parallelogram_flat O A C B).\n      apply(sum_cong O E E' H1 A B C HS).\n      left; auto.\n    assert(Parallelogram O A C B).\n      right; auto.\n    assert(Parallelogram C'' A'' A C \\/ C'' = A'' /\\ O = B /\\ C = A /\\ C'' = C).\n      apply(plg_pseudo_trans C'' A'' O B C A).\n        apply plg_comm2.\n        apply plg_permut.\n        apply plg_permut.\n        assumption.\n      apply plg_permut in H22.\n      apply plg_comm2.\n      apply plg_permut.\n      apply plg_permut.\n      assumption.\n    assert(Parallelogram C'' A'' A C).\n      induction H23.\n        assumption.\n      spliter.\n      subst B.\n      tauto.\n    clear H23.\n    assert(A <> C).\n      intro.\n      subst C.\n      assert(Parallelogram O A A O).\n        apply(plg_trivial O A); auto.\n      assert(HH:=plg_uniqueness O A A O B H23 H22).\n      subst B.\n      tauto.\n    assert(A <> A'').\n      intro.\n      subst A''.\n      apply par_distincts in H19.\n      tauto.\n    assert(A'' <> C'').\n      intro.\n      subst C''.\n      assert(Parallelogram A'' A'' A A).\n        apply(plg_trivial1); auto.\n      assert(HH:= plg_uniqueness A'' A'' A A C H26 H24).\n      contradiction.\n    apply plg_par in H24; auto.\n    spliter.\n    apply(par_trans _ _ A'' A); Par.\nQed.\n\n(** Lemma 14.16 *)\n(** The choice of E does not affect sum. *)\nLemma sum_x_axis_unit_change :\n forall O E E' U A B C,\n Sum O E E' A B C ->\n Col O E U ->\n U <> O ->\n Sum O U E' A B C.\nProof.\n    intros.\n    induction (eq_dec_points U E).\n      subst U.\n      assumption.\n    assert(HS:= H).\n    assert(Ar2 O E E' A B C).\n      unfold Sum in H.\n      tauto.\n    assert(HA:=H3).\n    unfold Ar2 in H3.\n    spliter.\n    assert(HH:=grid_not_par O E E' H3).\n    spliter.\n    assert(~Col O U E').\n      intro.\n      apply H3.\n      ColR.\n    assert(HH:=grid_not_par O U E' H13).\n    spliter.\n    induction(eq_dec_points A O).\n      subst A.\n      apply sum_O_B_eq in H; Col.\n      subst C.\n      apply sum_O_B; Col.\n      ColR.\n    induction(eq_dec_points B O).\n      subst B.\n      apply sum_A_O_eq in H; Col.\n      subst C.\n      apply sum_A_O; Col.\n      ColR.\n    apply sum_plg in H; auto.\n    ex_and H A'.\n    ex_and H22 C'.\n    apply plg_to_parallelogram in H.\n    apply plg_to_parallelogram in H22.\n    assert(Ar2 O U E' A B C).\n      repeat split ; auto; ColR.\n    assert(HB:= H23).\n    unfold Ar2 in H23.\n    spliter.\n    clean_duplicated_hyps.\n    assert(exists ! P' : Tpoint, Proj A P' O E' U E').\n      apply(project_existence A O E' U E' H19 H11 ).\n      intro.\n      apply H16.\n      Par.\n    ex_and H18 A''.\n    unfold unique in H23.\n    spliter.\n    clear H23.\n    unfold Proj in H18.\n    spliter.\n    clean_duplicated_hyps.\n    assert(Par A A'' U E').\n      induction H29.\n        assumption.\n      subst A''.\n      apply False_ind.\n      apply H3.\n      ColR.\n    clear H29.\n    assert(HH:= plg_existence B O A'' H21).\n    ex_and HH C''.\n    assert(O <> A'').\n      intro.\n      subst A''.\n      assert(HH:=plg_trivial B O H21).\n      assert(B = C'').\n        apply (plg_uniqueness B O O B C''); auto.\n      subst C''.\n      induction H18.\n        apply H18.\n        exists U.\n        split; Col.\n      spliter.\n      apply H3.\n      ColR.\n    assert(HP1:=H23).\n    apply plg_par in H23; auto.\n    spliter.\n    repeat split; auto.\n    exists A''.\n    exists C''.\n    repeat split.\n      left.\n      Par.\n      Col.\n      left.\n      assert(Par O U B O).\n        right.\n        repeat split; Col.\n      apply (par_trans _ _ B O); Par.\n      left.\n      assert(Par O E' O A'').\n        right.\n        repeat split; Col.\n      apply(par_trans _ _ O A''); Par.\n    assert(Parallelogram_flat O A C B).\n      apply(sum_cong O E E' H3 A B C HS); auto.\n    assert(Parallelogram O A C B).\n      right.\n      assumption.\n    assert(Parallelogram A C C'' A'' \\/ A = C /\\ B = O /\\ A'' = C'' /\\ A = A'').\n      apply(plg_pseudo_trans A C B O A'' C'').\n        apply plg_permut.\n        assumption.\n      assumption.\n    assert(Parallelogram A C C'' A'').\n      induction H32.\n        assumption.\n      spliter.\n      contradiction.\n    clear H32.\n    apply plg_par in H33.\n      left.\n      spliter.\n      apply(par_trans _ _ A A''); Par.\n      intro.\n      subst C.\n      apply sum_B_null in HS.\n        contradiction.\n      auto.\n    intro.\n    subst C''.\n    induction H23.\n      apply H23.\n      exists C.\n      split; Col.\n      ColR.\n    spliter.\n    apply H3.\n    ColR.\nQed.\n\nLemma change_grid_sum_0 :\n forall O E E' A B C O' A' B' C',\n  Par_strict O E O' E' ->\n  Ar1 O E A B C ->\n  Ar1 O' E' A' B' C' ->\n  Pj O O' E E' ->\n  Pj O O' A A' ->\n  Pj O O' B B' ->\n  Pj O O' C C' ->\n  Sum O E E' A B C ->\n  A = O ->\n  Sum O' E' E A' B' C'.\nProof.\n    intros.\n    assert(HS:= H6).\n    induction H6.\n    ex_and H8 A1.\n    ex_and H9 C1.\n    unfold Ar1 in *.\n    unfold Ar2 in H6.\n    spliter.\n    subst A.\n    clean_duplicated_hyps.\n    assert(A' = O').\n      apply(l6_21 O' E' O O');Col.\n        intro.\n        apply H.\n        exists O.\n        split; Col.\n        intro.\n        apply H.\n        subst O'.\n        exists O.\n        split; Col.\n      unfold Pj in H3.\n      induction H3.\n        induction H3.\n          apply False_ind.\n          apply H3.\n          exists O.\n          split; Col.\n        spliter.\n        Col.\n      subst A'.\n      Col.\n    subst A'.\n    assert(Sum O E E' O B B).\n      apply sum_O_B. assumption. Col.\n    unfold Sum in H7.\n      assert(B = C).\n        apply(sum_uniqueness O E E' O B); auto.\n      subst C.\n      assert(B' = C').\n        apply(l6_21 O' E' B B'); Col.\n          intro.\n          apply H.\n          exists B.\n          split; Col.\n          intro.\n          subst B'.\n          apply H.\n          exists B.\n          split; Col.\n        induction H5.\n          induction H4.\n            assert(Par B C' B B').\n              apply(par_trans _ _ O O'); Par.\n            induction H13.\n              apply False_ind.\n              apply H13.\n              exists B.\n              split; Col.\n            spliter.\n            Col.\n          subst B'.\n          Col.\n        subst C'.\n        Col.\n      subst C'.\n      apply sum_O_B;Col.\n      assert_ncols; Col.\nQed.\n\nLemma change_grid_sum :\n forall O E E' A B C O' A' B' C',\n  Par_strict O E O' E' ->\n  Ar1 O E A B C ->\n  Ar1 O' E' A' B' C' ->\n  Pj O O' E E' ->\n  Pj O O' A A' ->\n  Pj O O' B B' ->\n  Pj O O' C C' ->\n  Sum O E E' A B C ->\n  Sum O' E' E A' B' C'.\nProof.\n    intros.\n    induction(eq_dec_points A O).\n      subst A.\n      apply(change_grid_sum_0 O E E' O B C); auto.\n    assert(HS:= H6).\n    induction H6.\n    ex_and H8 A1.\n    ex_and H9 C1.\n    unfold Ar1 in *.\n    unfold Ar2 in H6.\n    spliter.\n    assert(HG:=grid_not_par O E E' H6).\n    spliter.\n    assert(~Col O' E' E).\n      intro.\n      apply H.\n      exists E.\n      split; Col.\n    assert(HG:=grid_not_par O' E' E H28).\n    spliter.\n    clean_duplicated_hyps.\n    induction(eq_dec_points B O).\n      subst B.\n      apply sum_comm; Col.\n      apply sum_comm in HS; Col.\n      apply(change_grid_sum_0 O E E' O A C); auto.\n        repeat split; auto.\n      repeat split; auto.\n    assert(A' <> O).\n      intro.\n      subst A'.\n      induction H3.\n        induction H3.\n          apply H3.\n          exists O.\n          split; Col.\n        spliter.\n        apply H.\n        exists O'.\n        split; Col.\n        ColR.\n      contradiction.\n    assert(~Col O A A').\n      intro.\n      apply H.\n      exists A'.\n      split; Col.\n      ColR.\n    assert(A' <> O').\n      intro.\n      subst A'.\n      induction H3.\n        induction H3.\n          apply H3.\n          exists O'.\n          split; Col.\n        spliter.\n        contradiction.\n      subst A.\n      apply H15.\n      Col.\n    assert(Parallelogram_flat O A C B).\n      apply(sum_cong O E E' H6 A B C HS).\n      left.\n      auto.\n    unfold Parallelogram_flat in H32.\n    spliter.\n    assert(Proj O O' O' E' E E').\n      unfold Proj.\n      repeat split; Col.\n        intro.\n        apply H29.\n        Par.\n      induction H2.\n        left; Par.\n      subst E'.\n      tauto.\n    assert(Proj A A' O' E' E E').\n      unfold Proj.\n      repeat split; Col.\n        intro.\n        apply H29.\n        Par.\n      induction H3.\n        left.\n        induction H2.\n          apply (par_trans _ _ O O'); Par.\n        subst E'.\n        tauto.\n      subst A'.\n      right.\n      auto.\n    assert(Proj C C' O' E' E E').\n      unfold Proj.\n      repeat split; Col.\n        intro.\n        apply H29.\n        Par.\n      induction H5.\n        left.\n        induction H2.\n          apply (par_trans _ _ O O'); Par.\n        subst E'.\n        tauto.\n      right.\n      auto.\n    assert(Proj B B' O' E' E E').\n      unfold Proj.\n      repeat split; Col.\n        intro.\n        apply H29.\n        Par.\n      induction H4.\n        left.\n        induction H2.\n          apply (par_trans _ _ O O'); Par.\n        subst E'.\n        tauto.\n      right.\n      auto.\n    assert(EqV O A B C).\n      unfold EqV.\n      left.\n      right.\n      apply plgf_permut.\n      unfold Parallelogram_flat.\n      repeat split; Col; Cong.\n        ColR.\n      induction H38.\n        right.\n        auto.\n      left.\n      auto.\n    assert(HH:=project_preserves_eqv O A B C O' A' B' C' O' E' E E' H43 H39 H40 H42 H41).\n    unfold EqV in HH.\n    induction HH.\n      assert(Parallelogram_flat O' A' C' B').\n        induction H44.\n          induction H44.\n          unfold TS in H44.\n          spliter.\n          apply False_ind.\n          apply H47.\n          ColR.\n        assumption.\n      unfold Parallelogram_flat in H45.\n      spliter.\n      apply cong_sum; auto.\n        induction H49.\n          left; auto.\n        right; auto.\n        repeat split; Col.\n        Cong.\n      Cong.\n    spliter.\n    subst A'.\n    tauto.\nQed.\n\nLemma double_null_null : forall O E E' A, Sum O E E' A A O -> A = O.\nProof.\n    intros.\n    induction (eq_dec_points A O).\n      assumption.\n    assert(HS:= H).\n    unfold Sum in H.\n    spliter.\n    unfold Ar2 in H.\n    spliter.\n    assert(Parallelogram_flat O A O A).\n      apply(sum_cong O E E' H A A O HS).\n      left; auto.\n    unfold Parallelogram_flat in H5.\n    tauto.\nQed.\n\nLemma not_null_double_not_null : forall O E E' A C, Sum O E E' A A C -> A <> O -> C <> O.\nProof.\n    intros.\n    intro.\n    subst C.\n    apply double_null_null in H.\n    contradiction.\nQed.\n\nLemma double_not_null_not_nul : forall O E E' A C, Sum O E E' A A C -> C <> O -> A <> O.\nProof.\n    intros.\n    intro.\n    subst A.\n    assert(HS:= H).\n    unfold Sum in H.\n    spliter.\n    unfold Ar2 in H.\n    spliter.\n    assert(HH:= sum_O_O O E E' H).\n    apply H0.\n    apply (sum_uniqueness O E E' O O); assumption.\nQed.\n\nLemma diff_ar2 : forall O E E' A B AMB, Diff O E E' A B AMB -> Ar2 O E E' A B AMB.\nProof.\n    intros.\n    unfold Diff in H.\n    ex_and H MA.\n    unfold Opp in H.\n    unfold Sum in *.\n    spliter.\n    unfold Ar2 in *.\n    spliter.\n    repeat split; auto.\nQed.\n\nLemma diff_null : forall O E E' A, ~Col O E E' -> Col O E A -> Diff O E E' A A O.\nProof.\n    intros.\n    unfold Diff.\n    assert(Hop:=opp_exists O E E' H A H0).\n    ex_and Hop MB.\n    exists MB.\n    split; auto.\n    unfold Opp in H1.\n    apply sum_comm; auto.\nQed.\n\nLemma diff_exists : forall O E E' A B, ~Col O E E' -> Col O E A -> Col O E B ->  exists D, Diff O E E' A B D.\nProof.\n    intros.\n    assert(Hop:=opp_exists O E E' H B H1).\n    ex_and Hop MB.\n    assert(Col O E MB).\n      unfold Opp in H2.\n      unfold Sum in H2.\n      spliter.\n      unfold Ar2 in H2.\n      tauto.\n    assert(HS:=sum_exists O E E' H A MB H0 H3).\n    ex_and HS C.\n    exists C.\n    unfold Diff.\n    exists MB.\n    split; assumption.\nQed.\n\nLemma diff_uniqueness : forall O E E' A B D1 D2, Diff O E E' A B D1 -> Diff O E E' A B D2 -> D1 = D2.\nProof.\n    intros.\n    assert(Ar2 O E E' A B D1).\n      apply (diff_ar2); assumption.\n    unfold Ar2 in H1.\n    spliter.\n    unfold Diff in *.\n    ex_and H MB1.\n    ex_and H0 MB2.\n    assert(MB1 = MB2).\n      apply (opp_uniqueness O E E' H1 B); assumption.\n    subst MB2.\n    apply(sum_uniqueness O E E'  A MB1); assumption.\nQed.\n\nLemma sum_ar2 : forall O E E' A B C, Sum O E E' A B C -> Ar2 O E E' A B C.\nProof.\n    intros.\n    unfold Sum in H.\n    tauto.\nQed.\n\nLemma diff_A_O : forall O E E' A, ~Col O E E' -> Col O E A ->  Diff O E E' A O A.\nProof.\n    intros.\n    unfold Diff.\n    exists O.\n    split.\n      unfold Opp.\n      apply sum_O_O; auto.\n    apply sum_A_O;auto.\nQed.\n\nLemma diff_O_A : forall O E E' A mA,\n  ~ Col O E E' -> Opp O E E' A mA -> Diff O E E' O A mA.\nProof.\n    intros.\n    assert (Col O E A) by (unfold Opp, Sum, Ar2 in *; spliter; auto).\n    assert (Col O E mA) by (unfold Opp, Sum, Ar2 in *; spliter; auto).\n    revert H0; revert H1; revert H2; intros.\n    unfold Diff.\n    exists mA.\n    split.\n      assumption.\n    apply sum_O_B; auto.\nQed.\n\nLemma diff_O_A_opp : forall O E E' A mA, Diff O E E' O A mA -> Opp O E E' A mA.\nProof.\n    intros.\n    assert(Ar2 O E E' O A mA).\n      apply diff_ar2;auto.\n    unfold Diff in H.\n    ex_and H A'.\n    assert(Ar2 O E E' O A' mA).\n      apply sum_ar2; auto.\n    unfold Ar2 in *.\n    spliter.\n    clean_duplicated_hyps.\n    assert(Sum O E E' O A' A').\n      apply (sum_O_B); auto.\n    assert(mA = A').\n      apply(sum_uniqueness O E E' O A'); auto.\n    subst A'.\n    assumption.\nQed.\n\nLemma diff_uniquenessA : forall O E E' A A' B C,\n  Diff O E E' A B C -> Diff O E E' A' B C -> A = A'.\nProof.\n    intros.\n    assert(Ar2 O E E' A B C).\n      apply diff_ar2; auto.\n    assert(Ar2 O E E' A' B C).\n      apply diff_ar2; auto.\n    unfold Ar2 in *.\n    spliter.\n    clean_duplicated_hyps.\n    unfold Diff in *.\n    ex_and H mB.\n    ex_and H0 mB'.\n    assert(mB = mB').\n      apply(opp_uniqueness O E E' H1 B); auto.\n    subst mB'.\n    apply (sum_uniquenessA O E E' H1 mB A A' C); auto.\nQed.\n\nLemma diff_uniquenessB : forall O E E' A B B' C,\n  Diff O E E' A B C -> Diff O E E' A B' C -> B = B'.\nProof.\n    intros.\n    assert(Ar2 O E E' A B C).\n      apply diff_ar2; auto.\n    assert(Ar2 O E E' A B' C).\n      apply diff_ar2; auto.\n    unfold Ar2 in *.\n    spliter.\n    clean_duplicated_hyps.\n    unfold Diff in *.\n    ex_and H mB.\n    ex_and H0 mB'.\n    assert(mB = mB').\n      apply (sum_uniquenessA O E E' H1 A mB mB' C); apply sum_comm; auto.\n    subst mB'.\n    apply (opp_uniqueness O E E' H1 mB); apply opp_comm; auto.\nQed.\n\nLemma diff_null_eq : forall O E E' A B, Diff O E E' A B O -> A = B.\nProof.\n    intros.\n    assert(Ar2 O E E' A B O).\n      apply diff_ar2; auto.\n    unfold Ar2 in H0.\n    spliter.\n    clear H3.\n    assert(Diff O E E' A A O).\n      apply diff_null; Col.\n    apply (diff_uniquenessB O E E' A _ _ O); auto.\nQed.\n\nLemma midpoint_opp: forall O E E' A B,\n  Ar2 O E E' O A B -> Midpoint O A B -> Opp O E E' A B.\nProof.\n    intros.\n    unfold Ar2.\n    unfold Ar2 in H.\n    spliter.\n    clear H1.\n    unfold Midpoint in H0.\n    spliter.\n    induction (eq_dec_points A B).\n      subst B.\n      apply between_identity in H0.\n      subst A.\n      apply opp0; auto.\n    unfold Opp.\n    apply cong_sum; auto.\n      unfold Ar2.\n      repeat split; Col.\n      Cong.\n    Cong.\nQed.\n\nLemma sum_diff : forall O E E' A B S, Sum O E E' A B S -> Diff O E E' S A B.\nProof.\n    intros.\n    assert(Ar2 O E E' A B S).\n      apply sum_ar2; auto.\n    unfold Ar2 in H0.\n    spliter.\n    assert(HH:=opp_exists O E E' H0 A H1).\n    ex_and HH mA.\n    exists mA.\n    split; auto.\n    unfold Opp in H4.\n    assert(Ar2 O E E' mA A O).\n      apply sum_ar2; auto.\n    unfold Ar2 in H5.\n    spliter.\n    clean_duplicated_hyps.\n    clear H8.\n    induction(eq_dec_points A O).\n      subst A.\n      assert(B = S).\n        apply (sum_uniqueness O E E' O B); auto.\n        apply sum_O_B; auto.\n      subst S.\n      assert(mA = O).\n        apply (sum_uniqueness O E E' mA O); auto.\n        apply sum_A_O; auto.\n      subst mA.\n      apply sum_A_O; auto.\n    induction(eq_dec_points B O).\n      subst B.\n      assert(A = S).\n        apply (sum_uniqueness O E E' A O); auto.\n        apply sum_A_O; auto.\n      subst S.\n      apply sum_comm; auto.\n    apply sum_cong in H; auto.\n    apply sum_cong in H4; auto.\n    assert(E <> O).\n      intro.\n      subst E.\n      apply H0.\n      Col.\n    assert(Parallelogram O mA B S \\/ O = mA /\\ O = A /\\ S = B /\\ O = S).\n      apply(plg_pseudo_trans O mA O A S B); auto.\n        right; auto.\n      right; auto.\n    induction H9.\n      induction H9.\n        apply False_ind.\n        unfold Parallelogram_strict in H9.\n        spliter.\n        unfold TS in H9.\n        spliter.\n        apply H12.\n        ColR.\n      unfold Parallelogram_flat in H.\n      unfold Parallelogram_flat in H4.\n      unfold Parallelogram_flat in H9.\n      spliter.\n      apply cong_sum; auto.\n        repeat split; Col.\n        Cong.\n      Cong.\n    spliter.\n    subst A.\n    tauto.\nQed.\n\nLemma diff_sum : forall O E E' A B S, Diff O E E' S A B -> Sum O E E' A B S.\nProof.\nintros.\nassert(Ar2 O E E' S A B).\napply diff_ar2; auto.\nunfold Ar2 in H0.\nspliter.\ninduction(eq_dec_points A O).\nsubst A.\nassert(HH:=diff_A_O O E E' S H0 H1).\nassert(S = B).\napply (diff_uniqueness O E E' S O); auto.\nsubst B.\napply sum_O_B; auto.\nunfold Diff in H.\nex_and H mA.\nassert(mA <> O).\nintro.\nsubst mA.\nassert(HH:=opp0 O E E' H0).\napply H4.\napply (opp_uniqueness O E E' H0 O); auto.\napply opp_comm; auto.\nunfold Opp in H.\ninduction(eq_dec_points S O).\nsubst S.\nassert(mA = B).\napply (sum_O_B_eq O E E'); auto.\nsubst mA.\napply sum_comm; auto.\napply sum_cong in H; auto.\napply sum_cong in H5; auto.\nassert(E <> O).\nintro.\nsubst E.\napply H0.\nCol.\nassert(Parallelogram O A S B \\/ O = A /\\ O = mA /\\ B = S /\\ O = B).\napply(plg_pseudo_trans O A O mA B S).\napply plg_permut.\napply plg_permut.\nright.\nassumption.\napply plg_comm2.\napply plg_permut.\napply plg_permut.\napply plg_permut.\nright.\nauto.\ninduction H9.\ninduction H9.\napply False_ind.\nunfold Parallelogram_strict in H9.\nspliter.\nunfold TS in H9.\nspliter.\napply H12.\nColR.\nunfold Parallelogram_flat in H.\nunfold Parallelogram_flat in H5.\nunfold Parallelogram_flat in H9.\nspliter.\napply cong_sum; Cong.\nrepeat split; Col.\nspliter.\nsubst A.\ntauto.\nQed.\n\nLemma diff_opp : forall O E E' A B AmB BmA,\n  Diff O E E' A B AmB -> Diff O E E' B A BmA -> Opp O E E' AmB BmA.\nProof.\n    intros.\n    assert(Ar2 O E E' A B AmB).\n      apply diff_ar2; auto.\n    assert(Ar2 O E E' B A BmA).\n      apply diff_ar2; auto.\n    unfold Ar2 in *.\n    spliter.\n    clean_duplicated_hyps.\n    apply diff_sum in H.\n    apply diff_sum in H0.\n    induction(eq_dec_points A O).\n      subst A.\n      assert(BmA = B).\n        apply(sum_O_B_eq O E E'); auto.\n      subst BmA.\n      unfold Opp.\n      assumption.\n    induction(eq_dec_points B O).\n      subst B.\n      assert(AmB = A).\n        apply(sum_O_B_eq O E E'); auto.\n      subst AmB.\n      unfold Opp.\n      apply sum_comm; auto.\n    apply sum_cong in H0; auto.\n    apply sum_cong in H; auto.\n    assert(Parallelogram A O BmA B).\n      apply plg_comm2.\n      right.\n      assumption.\n    apply plg_permut in H4.\n    apply plg_permut in H4.\n    apply plg_permut in H4.\n    assert(Parallelogram AmB O BmA O \\/ AmB = O /\\ B = A /\\ O = BmA /\\ AmB = O).\n      apply(plg_pseudo_trans AmB O  B A O BmA).\n        apply plg_permut.\n        apply plg_permut.\n        apply plg_permut.\n        right; assumption.\n      assumption.\n    assert(E <> O).\n      intro.\n      subst E.\n      apply H1.\n      Col.\n    induction H9.\n      induction H9.\n        apply False_ind.\n        unfold Parallelogram_strict in H9.\n        unfold TS in H9.\n        spliter.\n        apply H13.\n        ColR.\n      unfold Parallelogram_flat in H.\n      unfold Parallelogram_flat in H0.\n      unfold Parallelogram_flat in H9.\n      spliter.\n      unfold Opp.\n      apply cong_sum; Cong.\n        right.\n        intro.\n        subst BmA.\n        tauto.\n      repeat split; Col.\n    spliter.\n    subst AmB.\n    subst BmA.\n    unfold Opp.\n    apply sum_O_O; auto.\nQed.\n\nLemma sum_stable : forall O E E' A B C S1 S2 , A = B -> Sum O E E' A C S1 -> Sum O E E' B C S2 -> S1 = S2.\nProof.\n    intros.\n    subst B.\n    apply (sum_uniqueness O E E' A C); auto.\nQed.\n\nLemma diff_stable : forall O E E' A B C D1 D2 , A = B -> Diff O E E' A C D1 -> Diff O E E' B C D2 -> D1 = D2.\nProof.\n    intros.\n    subst B.\n    apply(diff_uniqueness O E E' A C); auto.\nQed.\n\nLemma plg_to_sum : forall O E E' A B C, Ar2 O E E' A B C ->Parallelogram_flat O A C B -> Sum O E E' A B C.\nProof.\n    intros.\n    induction(eq_dec_points A B).\n      subst B.\n      unfold Parallelogram_flat in H0.\n      spliter.\n      assert(O = C \\/ Midpoint A O C).\n        apply(l7_20 A O C H0).\n        Cong.\n      induction H5.\n        subst C.\n        tauto.\n      apply cong_sum; auto.\n        unfold Ar2 in H.\n        tauto.\n        unfold Midpoint in H5.\n        tauto.\n      unfold Midpoint in H5.\n      tauto.\n    unfold Ar2 in H.\n    unfold Parallelogram_flat in H0.\n    spliter.\n    apply cong_sum; auto.\n      repeat split; auto.\n      Cong.\n    Cong.\nQed.\n\nLemma opp_midpoint :\n forall O E E' A MA,\n Opp O E E' A MA ->\n Midpoint O A MA.\nProof.\n    intros.\n    unfold Opp in H.\n    assert(HS:=H).\n    unfold Sum in H.\n    spliter.\n    unfold Ar2 in H.\n    spliter.\n    induction (eq_dec_points A O).\n      subst A.\n      assert(HH:= sum_A_O_eq O E E' H MA O HS).\n      subst MA.\n      unfold Midpoint.\n      split; Cong.\n      apply between_trivial.\n    assert(Parallelogram_flat O MA O A).\n      apply(sum_cong O E E' H MA A O HS).\n      tauto.\n    unfold Parallelogram_flat in H5.\n    spliter.\n    assert(A = MA \\/ Midpoint O A MA).\n      apply(l7_20 O A MA).\n        Col.\n      Cong.\n    induction H10.\n      subst MA.\n      tauto.\n    assumption.\nQed.\n\nLemma diff_to_plg : forall O E E' A B dBA, A <> O \\/ B <> O -> Diff O E E' B A dBA -> Parallelogram_flat O A B dBA.\nProof.\n    intros.\n    assert(Ar2 O E E' B A dBA).\n      apply diff_ar2; auto.\n    unfold Ar2 in H1.\n    spliter.\n    apply diff_sum in H0.\n    induction(eq_dec_points A O).\n      subst A.\n      assert(dBA = B).\n        apply(sum_O_B_eq O E E'); auto.\n      subst dBA.\n      apply plgf_permut.\n      apply plgf_trivial.\n      induction H; tauto.\n    assert(E <> O).\n      intro.\n      subst E.\n      apply H1.\n      Col.\n    induction(eq_dec_points B O).\n      subst B.\n      assert(Opp O E E' dBA A).\n        unfold Opp.\n        auto.\n      apply opp_midpoint in H7.\n      unfold Midpoint in H7.\n      spliter.\n      unfold Parallelogram_flat.\n      repeat split; Col.\n        Cong.\n        Cong.\n        assert_diffs; auto.\n    apply sum_cong in H0; auto.\nQed.\n\nLemma sum3_col : forall O E E' A B C S, sum3 O E E' A B C S -> ~Col O E E' /\\ Col O E A /\\ Col O E B /\\ Col O E C /\\ Col O E S.\nProof.\n    intros.\n    unfold sum3 in H.\n    ex_and H AB.\n    assert(Ar2 O E E' A B AB).\n      apply sum_ar2; auto.\n    assert(Ar2 O E E' AB C S).\n      apply sum_ar2; auto.\n    unfold Ar2 in *.\n    spliter.\n    repeat split; auto.\nQed.\n\nLemma sum3_permut : forall O E E' A B C S, sum3 O E E' A B C S -> sum3 O E E' C A B S.\nProof.\n    intros.\n    assert(~Col O E E' /\\ Col O E A /\\ Col O E B /\\ Col O E C /\\ Col O E S).\n      apply sum3_col; auto.\n    spliter.\n    unfold sum3 in H.\n    ex_and H AB.\n    assert(HH:= sum_exists O E E' H0 A C H1 H3).\n    ex_and HH AC.\n    unfold sum3.\n    exists AC.\n    split.\n      apply sum_comm; auto.\n    apply sum_comm in H5; auto.\n    apply sum_comm in H6; auto.\n    assert(HH:=sum_assoc O E E' C A B AC AB S H6 H).\n    destruct HH.\n    apply H7; auto.\nQed.\n\nLemma sum3_comm_1_2 : forall O E E' A B C S, sum3 O E E' A B C S -> sum3 O E E' B A C S.\nProof.\n    intros.\n    assert(~Col O E E' /\\ Col O E A /\\ Col O E B /\\ Col O E C /\\ Col O E S).\n      apply sum3_col; auto.\n    spliter.\n    unfold sum3 in H.\n    ex_and H AB.\n    unfold sum3.\n    exists AB.\n    split.\n      apply sum_comm; auto.\n    auto.\nQed.\n\nLemma sum3_comm_2_3 : forall O E E' A B C S, sum3 O E E' A B C S -> sum3 O E E' A C B S.\nProof.\n    intros.\n    apply sum3_permut in H.\n    apply sum3_comm_1_2 in H.\n    assumption.\nQed.\n\nLemma sum3_exists : forall O E E' A B C, Ar2 O E E' A B C -> exists S, sum3 O E E' A B C S.\nProof.\n    intros.\n    unfold Ar2 in *.\n    spliter.\n    assert(HH:=sum_exists O E E' H A B H0 H1).\n    ex_and HH AB.\n    assert(Ar2 O E E' A B AB).\n      apply sum_ar2; auto.\n    unfold Ar2 in H4.\n    spliter.\n    clean_duplicated_hyps.\n    assert(HH:=sum_exists O E E' H AB C H7 H2).\n    ex_and HH ABC.\n    exists ABC.\n    unfold sum3.\n    exists AB.\n    split; auto.\nQed.\n\nLemma sum3_uniqueness : forall O E E' A B C S1 S2, sum3 O E E' A B C S1 -> sum3 O E E' A B C S2 -> S1 = S2.\nProof.\n    intros.\n    unfold sum3 in H.\n    unfold sum3 in H0.\n    ex_and H AB1.\n    ex_and H0 AB2.\n    assert(AB1 = AB2).\n      apply(sum_uniqueness O E E' A B); auto.\n    subst AB2.\n    apply (sum_uniqueness O E E' AB1 C); auto.\nQed.\n\nLemma sum4_col : forall O E E' A B C D S, Sum4 O E E' A B C D S ->  ~Col O E E' /\\ Col O E A /\\ Col O E B /\\ Col O E C /\\ Col O E D /\\ Col O E S.\nProof.\n    intros.\n    unfold Sum4 in H.\n    ex_and H ABC.\n    assert(HH:=sum3_col O E E' A B C ABC H).\n    assert(Ar2 O E E' ABC D S).\n      apply sum_ar2; auto.\n    unfold Ar2 in *.\n    spliter.\n    repeat split; auto.\nQed.\n\nLemma sum22_col : forall O E E' A B C D S, sum22 O E E' A B C D S ->  ~Col O E E' /\\ Col O E A /\\ Col O E B /\\ Col O E C /\\ Col O E D /\\ Col O E S.\nProof.\n    intros.\n    unfold sum22 in H.\n    ex_and H AB.\n    ex_and H0 CD.\n    assert(Ar2 O E E' A B AB).\n      apply sum_ar2; auto.\n    assert(Ar2 O E E' C D CD).\n      apply sum_ar2; auto.\n    assert(Ar2 O E E' AB CD S).\n      apply sum_ar2; auto.\n    unfold Ar2 in *.\n    spliter.\n    repeat split; auto.\nQed.\n\nLemma sum_to_sum3 : forall O E E' A B AB X S, Sum O E E' A B AB -> Sum O E E' AB X S -> sum3 O E E' A B X S.\nProof.\n    intros.\n    unfold sum3.\n    exists AB.\n    split; auto.\nQed.\n\nLemma sum3_to_sum4 : forall O E E' A B C X ABC S , sum3 O E E' A B C ABC -> Sum O E E' ABC X S -> Sum4 O E E' A B C X S.\nProof.\n    intros.\n    assert(~Col O E E' /\\ Col O E A /\\ Col O E B /\\ Col O E C /\\ Col O E ABC).\n      apply sum3_col; auto.\n    assert(Ar2 O E E' ABC X S).\n      apply sum_ar2; auto.\n    unfold Ar2 in H2.\n    spliter.\n    clean_duplicated_hyps.\n    unfold Sum4.\n    exists ABC.\n    split; auto.\nQed.\n\nLemma sum_A_exists : forall O E E' A AB, Ar2 O E E' A AB O -> exists B, Sum O E E' A B AB.\nProof.\n    intros.\n    unfold Ar2 in *.\n    spliter.\n    assert(HH:=diff_exists O E E' AB A H H1 H0).\n    ex_and HH B.\n    exists B.\n    apply diff_sum in H3.\n    assumption.\nQed.\n\nLemma sum_B_exists : forall O E E' B AB, Ar2 O E E' B AB O -> exists A, Sum O E E' A B AB.\nProof.\n    intros.\n    unfold Ar2 in *.\n    spliter.\n    assert(HH:=diff_exists O E E' AB B H H1 H0).\n    ex_and HH A.\n    exists A.\n    apply diff_sum in H3.\n    apply sum_comm; auto.\nQed.\n\nLemma sum4_equiv : forall O E E' A B C D S, Sum4 O E E' A B C D S <-> sum22 O E E' A B C D S.\nProof.\n    intros.\n    split.\n      intro.\n      assert(~Col O E E' /\\ Col O E A /\\ Col O E B /\\ Col O E C /\\ Col O E D /\\ Col O E S).\n        apply sum4_col; auto.\n      spliter.\n      assert(HS1:= sum_exists O E E' H0 A B H1 H2).\n      assert(HS2:= sum_exists O E E' H0 C D H3 H4).\n      ex_and HS1 AB.\n      ex_and HS2 CD.\n      unfold sum22.\n      exists AB.\n      exists CD.\n      assert(Ar2 O E E' A B AB).\n        apply sum_ar2; auto.\n      assert(Ar2 O E E' C D CD).\n        apply sum_ar2; auto.\n      unfold Ar2 in *.\n      spliter.\n      clean_duplicated_hyps.\n      split; auto.\n      split; auto.\n      unfold Sum4 in H.\n      ex_and H ABC.\n      unfold sum3 in H.\n      ex_and H AB'.\n      assert(AB' = AB).\n        apply(sum_uniqueness O E E' A B); auto.\n      subst AB'.\n      assert(HH:= sum_assoc O E E' AB C D ABC CD S H9 H7).\n      destruct HH.\n      apply H11.\n      assumption.\n    intro.\n    unfold sum22 in H.\n    ex_and H AB.\n    ex_and H0 CD.\n    assert(Ar2 O E E' A B AB).\n      apply sum_ar2; auto.\n    assert(Ar2 O E E' C D CD).\n      apply sum_ar2; auto.\n    assert(Ar2 O E E' AB CD S).\n      apply sum_ar2; auto.\n    unfold Ar2 in *.\n    spliter.\n    clean_duplicated_hyps.\n    unfold Sum4.\n    assert(HS:=sum_exists O E E' H2 AB C H13 H8).\n    ex_and HS ABC.\n    exists ABC.\n    split.\n      unfold sum3.\n      exists AB.\n      split; auto.\n    assert(HH:= sum_assoc O E E' AB C D ABC CD S H3 H0).\n    destruct HH.\n    apply H4.\n    assumption.\nQed.\n\nLemma sum4_permut: forall O E E' A B C D S, Sum4 O E E' A B C D S -> Sum4 O E E' D A B C S.\nProof.\n    intros.\n    assert( ~Col O E E' /\\ Col O E A /\\ Col O E B /\\ Col O E C /\\ Col O E D /\\ Col O E S).\n      apply sum4_col; auto.\n    spliter.\n    assert(HH:=sum4_equiv O E E' A B C D S).\n    destruct HH.\n    assert(sum22 O E E' A B C D S).\n      apply H6; auto.\n    unfold sum22 in H8.\n    ex_and H8 AB.\n    ex_and H9 CD.\n    apply sum_comm in H9; auto.\n    apply sum_comm in H10; auto.\n    unfold Sum4 in H.\n    ex_and H ABC.\n    assert(HH:= sum_assoc O E E' D C AB CD ABC S H9).\n    assert(HP:=sum3_permut O E E' A B C ABC H).\n    unfold sum3 in HP.\n    ex_and HP AC.\n    assert(HP:= sum_assoc O E E' C A B AC AB ABC H12 H8).\n    destruct HP.\n    assert(Sum O E E' C AB ABC).\n      apply H15; auto.\n    apply HH in H16.\n    destruct H16.\n    assert(Sum O E E' D ABC S).\n      apply H17; auto.\n    assert(HP:= sum_exists O E E' H0 D A H4 H1); auto.\n    ex_and HP AD.\n    assert(Ar2 O E E' D A AD).\n      apply sum_ar2; auto.\n    unfold Ar2 in H20.\n    spliter.\n    clean_trivial_hyps.\n    assert(HP:= sum_exists O E E' H0 AD B H23 H2); auto.\n    ex_and HP ABD.\n    assert(HP:= sum_assoc O E E' D A B  AD AB ABD H19 H8).\n    destruct HP.\n    apply H26 in H24.\n    unfold Sum4.\n    exists ABD.\n    split.\n      unfold sum3.\n      exists AD.\n      split; auto.\n    unfold sum3 in H.\n    ex_and H AB'.\n    assert(AB'=AB).\n      apply (sum_uniqueness O E E' A B); auto.\n    subst AB'.\n    assert(HP:= sum_assoc O E E' D AB C ABD ABC S H24 H27).\n    destruct HP.\n    apply H28.\n    auto.\nQed.\n\n(* a + b + c + d = d + a + b + c *)\nLemma sum22_permut : forall O E E' A B C D S, sum22 O E E' A B C D S -> sum22 O E E' D A B C S.\nProof.\n    intros.\n    assert(HH:= sum4_equiv O E E' A B C D S).\n    destruct HH.\n    assert(Sum4 O E E' A B C D S).\n      apply H1; auto.\n    assert(Sum4 O E E' D A B C S).\n      apply sum4_permut; auto.\n    assert(HH:= sum4_equiv O E E' D A B C S).\n    destruct HH.\n    apply H4.\n    auto.\nQed.\n\nLemma sum4_comm : forall O E E' A B C D S, Sum4 O E E' A B C D S -> Sum4 O E E' B A C D S.\nProof.\n    intros.\n    assert(~Col O E E' /\\ Col O E A /\\ Col O E B /\\ Col O E C /\\ Col O E D /\\ Col O E S).\n      apply sum4_col; auto.\n    spliter.\n    assert(HH:= sum4_equiv O E E' A B C D S).\n    destruct HH.\n    apply H6 in H.\n    unfold sum22 in H.\n    ex_and H AB.\n    ex_and H8 CD.\n    apply sum_comm in H; auto.\n    assert(sum22 O E E' B A C D S).\n      unfold sum22.\n      exists AB.\n      exists CD.\n      split; auto.\n    assert(HH:= sum4_equiv O E E'  B A C D S).\n    destruct HH.\n    apply H12; auto.\nQed.\n\n(* a + b + c + d = b + a + c + d *)\nLemma sum22_comm : forall O E E' A B C D S, sum22 O E E' A B C D S -> sum22 O E E' B A C D S.\nProof.\n    intros.\n    assert(~Col O E E' /\\ Col O E A /\\ Col O E B /\\ Col O E C /\\ Col O E D /\\ Col O E S).\n      apply sum22_col; auto.\n    spliter.\n    unfold sum22 in H.\n    ex_and H AB.\n    ex_and H6 CD.\n    unfold sum22.\n    exists AB.\n    exists CD.\n    split; auto.\n    apply sum_comm; auto.\nQed.\n\n(* a + b + c + d = b  c + a + d *)\nLemma sum_abcd : forall O E E' A B C D AB CD BC AD S,\n  Sum O E E' A B AB -> Sum O E E' C D CD -> Sum O E E' B C BC ->\n  Sum O E E' A D AD -> Sum O E E' AB CD S ->\n  Sum O E E' BC AD S.\nProof.\n    intros.\n    assert(Ar2 O E E' A B AB).\n      apply sum_ar2;auto.\n    assert(Ar2 O E E' C D CD).\n      apply sum_ar2;auto.\n    assert(Ar2 O E E' B C BC).\n      apply sum_ar2;auto.\n    assert(Ar2 O E E' A D AD).\n      apply sum_ar2;auto.\n    assert(Ar2 O E E' AB CD S).\n      apply sum_ar2;auto.\n    unfold Ar2 in *.\n    spliter.\n    clean_duplicated_hyps.\n    assert(sum22 O E E' A B C D S).\n      unfold sum22.\n      exists AB.\n      exists CD.\n      split; auto.\n    apply sum22_permut in H5.\n    unfold sum22 in H5.\n    ex_and H5 AD'.\n    ex_and H6 BC'.\n    assert(AD' = AD).\n      apply sum_comm in H2; auto.\n      apply (sum_uniqueness O E E' D A); auto.\n    subst AD'.\n    assert(BC' = BC).\n      apply (sum_uniqueness O E E' B C); auto.\n    subst BC'.\n    apply sum_comm; auto.\nQed.\n\n(* (b - a) + (c - b) = (c - a) *)\nLemma sum_diff_diff_a : forall O E E' A B C dBA dCB dCA,\n  Diff O E E' B A dBA -> Diff O E E' C B dCB -> Diff O E E' C A dCA ->\n  Sum O E E' dCB dBA dCA.\nProof.\n    intros.\n    assert(Ar2 O E E' B A dBA).\n      apply diff_ar2; auto.\n    assert(Ar2 O E E' C B dCB).\n      apply diff_ar2; auto.\n    assert(Ar2 O E E' C A dCA).\n      apply diff_ar2; auto.\n    unfold Ar2 in *.\n    spliter.\n    clean_duplicated_hyps.\n    unfold Diff in H.\n    ex_and H mA.\n    unfold Diff in H0.\n    ex_and H0 mB.\n    unfold Diff in H1.\n    ex_and H1 mA'.\n    assert(mA' = mA).\n      apply (opp_uniqueness O E E' H2 A); auto.\n    subst mA'.\n    assert(HH:=sum_exists O E E' H2 dBA dCB H13 H10).\n    ex_and HH Sd.\n    assert(sum22 O E E' B mA C mB Sd).\n      unfold sum22.\n      exists dBA.\n      exists dCB.\n      split; auto.\n    apply sum22_permut in H9.\n    unfold sum22 in H9.\n    ex_and H9 O'.\n    ex_and H14 dCA'.\n    assert(O' = O).\n      apply (sum_uniqueness O E E' mB B); auto.\n    subst O'.\n    assert(dCA'=dCA).\n      apply (sum_uniqueness O E E' C mA); auto.\n      apply sum_comm; auto.\n    subst dCA'.\n    assert(dCA=Sd).\n      apply (sum_O_B_eq O E E'); auto.\n    subst Sd.\n    apply sum_comm; auto.\nQed.\n\nLemma sum_diff_diff_b : forall O E E' A B C dBA dCB dCA,\n  Diff O E E' B A dBA -> Diff O E E' C B dCB -> Sum O E E' dCB dBA dCA ->\n  Diff O E E' C A dCA.\nProof.\n    intros.\n    assert(Ar2 O E E' B A dBA).\n      apply diff_ar2; auto.\n    assert(Ar2 O E E' C B dCB).\n      apply diff_ar2; auto.\n    assert(Ar2 O E E' dCB dBA dCA).\n      apply sum_ar2; auto.\n    unfold Ar2 in *.\n    spliter.\n    clean_duplicated_hyps.\n    unfold Diff in H.\n    ex_and H mA.\n    unfold Diff in H0.\n    ex_and H0 mB.\n    assert(sum22 O E E' B mA C mB dCA).\n      unfold sum22.\n      exists dBA.\n      exists dCB.\n      split; auto.\n      split; auto.\n      apply sum_comm; auto.\n    apply sum22_permut in H5.\n    unfold sum22 in H5.\n    ex_and H5 O'.\n    ex_and H6 dCA'.\n    assert(O'=O).\n      apply (sum_uniqueness O E E' mB B); auto.\n    subst O'.\n    assert(dCA' = dCA).\n      apply(sum_O_B_eq O E E'); auto.\n    subst dCA'.\n    unfold Diff.\n    exists mA.\n    split; auto.\n    apply sum_comm; auto.\nQed.\n\n(* (x + y) - (a + b) = (x - a) + (y - b) *)\nLemma sum_diff2_diff_sum2_a : forall O E E' A B C X Y Z dXA dYB dZC,\n  Sum O E E' A B C -> Sum O E E' X Y Z -> Diff O E E' X A dXA ->\n  Diff O E E' Y B dYB -> Sum O E E' dXA dYB dZC ->\n  Diff O E E' Z C dZC.\nProof.\n    intros.\n    assert(Ar2 O E E' A B C).\n      apply sum_ar2; auto.\n    assert(Ar2 O E E' X Y Z).\n      apply sum_ar2; auto.\n    assert(Ar2 O E E' dXA dYB dZC).\n      apply sum_ar2; auto.\n    unfold Ar2 in *.\n    spliter.\n    clean_duplicated_hyps.\n    apply diff_sum in H1.\n    apply diff_sum in H2.\n    apply sum_diff.\n    assert(HH:=sum_exists O E E' H4 C dZC H15 H9); auto.\n    ex_and HH Z'.\n    assert(sum22 O E E' A B dXA dYB Z').\n      unfold sum22.\n      exists C.\n      exists dZC.\n      auto.\n    apply sum22_comm in H6.\n    apply sum22_permut in H6.\n    apply sum22_comm in H6.\n    unfold sum22 in H6.\n    ex_and H6 Y'.\n    ex_and H16 X'.\n    assert(X' = X).\n      apply(sum_uniqueness O E E' A dXA); auto.\n    subst X'.\n    assert(Y'=Y).\n      apply(sum_uniqueness O E E' B dYB); auto.\n    subst Y'.\n    assert( Z'= Z).\n      apply(sum_uniqueness O E E' X Y); auto.\n      apply sum_comm; auto.\n    subst Z'.\n    assumption.\nQed.\n\nLemma sum_diff2_diff_sum2_b : forall O E E' A B C X Y Z dXA dYB dZC,\n  Sum O E E' A B C -> Sum O E E' X Y Z -> Diff O E E' X A dXA ->\n  Diff O E E' Y B dYB -> Diff O E E' Z C dZC ->\n  Sum O E E' dXA dYB dZC .\nProof.\n    intros.\n    assert(Ar2 O E E' A B C).\n      apply sum_ar2; auto.\n    assert(Ar2 O E E' X Y Z).\n      apply sum_ar2; auto.\n    assert(Ar2 O E E' X A dXA).\n      apply diff_ar2; auto.\n    assert(Ar2 O E E' Y B dYB).\n      apply diff_ar2; auto.\n    assert(Ar2 O E E' Z C dZC).\n      apply diff_ar2; auto.\n    unfold Ar2 in *.\n    spliter.\n    clean_duplicated_hyps.\n    assert(HH:=sum_exists O E E' H4 dXA dYB H17 H14).\n    ex_and HH dZC'.\n    assert(HH:=sum_diff2_diff_sum2_a O E E' A B C X Y Z dXA dYB dZC' H H0 H1 H2 H5).\n    assert( dZC' = dZC).\n      apply(diff_uniqueness O E E' Z C); auto.\n    subst dZC'.\n    assumption.\nQed.\n\nLemma sum_opp : forall O E E' X MX, Sum O E E' X MX O -> Opp O E E' X MX.\nProof.\nintros O E E' X MX HSum.\napply diff_O_A_opp; apply sum_diff; auto.\nQed.\n\nLemma sum_diff_diff : forall O E E' AX BX CX AXMBX AXMCX BXMCX,\n  Diff O E E' AX BX AXMBX -> Diff O E E' AX CX AXMCX ->\n  Diff O E E' BX CX BXMCX ->\n  Sum O E E' AXMBX BXMCX AXMCX.\nProof.\nintros O E E' AX BX CX AXMBX AXMCX BXMCX HAXMBX HAXMCX HBXMCX.\nassert (HNC : ~ Col O E E')\n  by (unfold Diff, Sum, Ar2 in *; destruct HAXMBX; spliter; auto).\nassert (HColAX : Col O E AX)\n  by (unfold Diff, Sum, Ar2 in *; destruct HAXMBX; spliter; auto).\nassert (HColBX : Col O E BX)\n  by (unfold Diff, Sum, Ar2 in *; destruct HBXMCX; spliter; auto).\nassert (HColCX : Col O E CX)\n  by (unfold Diff, Opp, Sum, Ar2 in *; destruct HBXMCX; spliter; auto).\nassert (HColAXMBX : Col O E AXMBX)\n  by (unfold Diff, Sum, Ar2 in *; destruct HAXMBX; spliter; auto).\nassert (HColAXMCX : Col O E AXMCX)\n  by (unfold Diff, Sum, Ar2 in *; destruct HAXMCX; spliter; auto).\nassert (HColBXMCX : Col O E BXMCX)\n  by (unfold Diff, Sum, Ar2 in *; destruct HBXMCX; spliter; auto).\ndestruct (opp_exists O E E' HNC BX) as [MBX HMBX]; Col.\nassert (HSum1 : Sum O E E' AX MBX AXMBX).\n  {\n  apply diff_sum in HAXMBX; apply sum_assoc_1 with AXMBX BX O;\n  apply sum_comm; auto; apply sum_O_B; Col.\n  }\ndestruct (opp_exists O E E' HNC CX) as [MCX HMCX]; Col.\nassert (HSum2 : Sum O E E' BX MCX BXMCX).\n  {\n  apply diff_sum in HBXMCX; apply sum_assoc_1 with BXMCX CX O;\n  apply sum_comm; auto; apply sum_O_B; Col.\n  }\napply sum_assoc_1 with AX MBX MCX; auto.\n\n  {\n  apply sum_assoc_2 with BX MCX O; auto; apply sum_O_B; Col.\n  unfold Opp, Sum, Ar2 in *; spliter; Col.\n  }\n\n  {\n  apply diff_sum in HAXMCX; apply sum_assoc_1 with AXMCX CX O;\n  apply sum_comm; auto; apply sum_O_B; Col.\n  }\nQed.\n\nEnd T14_sum.", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Tarski_dev/Ch14_sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757312, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.6634073798921019}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import cl.\n\nSet Implicit Arguments.\n\nSection cl_equivalence.\n\n  (* Now the definition of equivalence between the terms\n     of combinatory algebras. It is the least equivalence\n     relation (reflexive, symmetry and transitive) which\n     is congruent with composition o and such that\n       I o x ~~ x, K o x o y ~~ x and \n       S o x o y o z ~~ x o z o (y o z)\n  *)\n\n  Reserved Notation \"x '~cl' y\" (at level 70).\n\n  Inductive cl_eq : clterm -> clterm -> Prop :=\n  \n    | in_cl_eq_I : forall x,               I o x ~cl x \n    \n    | in_cl_eq_K : forall x y,         K o x o y ~cl x\n    \n    | in_cl_eq_S : forall x y z,   S o x o y o z ~cl x o z o (y o z)\n\n    | in_cl_eq_0 : forall x,                   x ~cl x\n    \n    | in_cl_eq_1 : forall x y,                 x ~cl y \n                              ->               y ~cl x\n                             \n    | in_cl_eq_2 : forall x y z,               x ~cl y \n                              ->               y ~cl z \n                              ->               x ~cl z\n                              \n    | in_cl_eq_3 : forall x y z,           x     ~cl y \n                              ->           x o z ~cl y o z\n                              \n    | in_cl_eq_4 : forall x y z,               y ~cl     z \n                              ->           x o y ~cl x o z\n                                \n  where \"x ~cl y\" := (cl_eq x y).\n  \n  (* Some exercices with cl_term equivalence *)\n  \n  Fact cl_eq_refl f g : f = g -> f ~cl g.\n  Proof.\n    intro H.\n    rewrite H.\n    constructor 4.\n  Qed.\n  \n  Definition cl_eq_sym := in_cl_eq_1.\n\n  Definition cl_eq_trans := in_cl_eq_2.\n  \n  Fact cl_eq_app x y a b : x ~cl y -> a ~cl b -> x o a ~cl y o b.\n  Proof.\n    intros H0 H1; induction H0.\n    \n    apply cl_eq_trans with (x o a);\n      try (apply in_cl_eq_3; constructor 1);\n      try (apply in_cl_eq_4; auto).\n    \n    apply cl_eq_trans with (x o a);\n      try (apply in_cl_eq_3; constructor 2);\n      try (apply in_cl_eq_4; auto).\n    \n    apply cl_eq_trans with (x o z o (y o z) o a);\n      try (apply in_cl_eq_3; constructor 3);\n      try (apply in_cl_eq_4; auto).\n    \n    apply in_cl_eq_4; auto.\n    \n    apply cl_eq_trans with (x o a);\n      try (apply in_cl_eq_3; apply cl_eq_sym; auto);\n      try (apply in_cl_eq_4; auto).\n    \n    apply cl_eq_trans with (x o b);\n      try (apply in_cl_eq_4; auto);\n      try (apply in_cl_eq_3; apply cl_eq_trans with y; auto).\n    \n    apply cl_eq_trans with (y o z o a);\n      try (do 2 apply in_cl_eq_3; auto);\n      try (apply in_cl_eq_4; auto).\n    \n    apply cl_eq_trans with (x o z o a);\n      try (apply in_cl_eq_3; auto; apply in_cl_eq_4; auto);\n      try (apply in_cl_eq_4; auto).\n  Qed.\n  \n  Fact cl_I_prop x : I o x ~cl x.\n  Proof.\n    apply in_cl_eq_I.\n  Qed.\n  \n  Fact cl_K_prop x y : K o x o y ~cl x.\n  Proof.\n    apply in_cl_eq_K.\n  Qed.\n  \n  Fact cl_S_prop x y z : S o x o y o z ~cl x o z o (y o z).\n  Proof.\n    apply in_cl_eq_S.\n  Qed. \n  \n  Fact cl_SKI_prop x : S o K o I o x ~cl x.\n  Proof.\n    apply cl_eq_trans with (1 := cl_S_prop _ _ _).\n    apply cl_K_prop.\n  Qed.\n  \n  Corollary cl_SKI_I : forall x, S o K o I o x ~cl I o x.\n  Proof.\n    intros.\n    apply cl_eq_trans with (1 := cl_S_prop _ _ _).\n    apply cl_eq_trans with (1 := cl_K_prop _ _).\n    apply cl_eq_sym.\n    constructor 1.\n  Qed.\n\n  Definition cl_D := S o I o I.\n  \n  Notation D := cl_D.\n  \n  Fact cl_D_prop x : D o x ~cl x o x.\n  Proof.\n    unfold cl_D.\n    apply cl_eq_trans with (I o x o (I o x)).\n    apply cl_S_prop.\n    apply cl_eq_trans with (x o (I o x));\n      try apply in_cl_eq_3;\n      try apply in_cl_eq_4;\n    constructor 1.\n  Qed.\n  \n  Definition cl_B := S o (K o S) o K.\n  \n  Notation B := cl_B.\n  \n  Hint Resolve in_cl_eq_0.\n  \n  Fact cl_B_prop f g x : B o f o g o x ~cl f o (g o x).\n  Proof.\n    unfold cl_B.\n    apply cl_eq_trans with (K  o S o f o (K o f) o g o x).\n    do 2 (apply cl_eq_app; auto); apply cl_S_prop.\n    apply cl_eq_trans with (S o (K o f) o g o x).\n    do 3 (apply cl_eq_app; auto); apply cl_K_prop.\n    apply cl_eq_trans with (1 := cl_S_prop _ _ _).\n    apply cl_eq_app; auto.\n    apply cl_K_prop.\n  Qed.\n  \n  Definition cl_L := D o (B o D o D).\n  \n  Notation L := cl_L.\n  \n  Fact cl_L_prop : L ~cl L o L.\n  Proof.\n    unfold cl_L.\n    apply cl_eq_trans with ((B o D o D) o (B o D o D));\n      try apply cl_D_prop.\n    do 2 (\n      apply cl_eq_trans with (D o (D o (B o D o D)));\n        try apply cl_D_prop;\n        try (apply cl_B_prop; constructor 4)\n    ).\n  Qed.\n  \nEnd cl_equivalence.\n\nNotation \"x '~cl' y\" := (cl_eq x y) (at level 70).", "meta": {"author": "sT4R3K", "repo": "Combinatory-Logic", "sha": "d0dca977c75eba7834dd1c4c181d6832ea82ab5a", "save_path": "github-repos/coq/sT4R3K-Combinatory-Logic", "path": "github-repos/coq/sT4R3K-Combinatory-Logic/Combinatory-Logic-d0dca977c75eba7834dd1c4c181d6832ea82ab5a/cl_eq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6633351401028613}}
{"text": "Require Import Coq.micromega.Lia.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.QArith.QArith.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Rewriter.Util.Option Rewriter.Util.Strings.ParseArithmetic.\nRequire Import Rewriter.Rewriter.Examples.PerfTesting.Harness.\nRequire Import Rewriter.Util.plugins.RewriterBuild.\nRequire Rewriter.Rewriter.Examples.PerfTesting.Sample.\nRequire Export Rewriter.Rewriter.Examples.PerfTesting.Settings.\nLocal Open Scope Z_scope.\n\nDefinition iter_plus_acc (m : nat) (acc v : Z) :=\n  @nat_rect\n    (fun _ => Z -> Z)\n    (fun acc => acc)\n    (fun _ rec acc => rec (acc + v))\n    m\n    acc.\n\nDefinition make_tree (n : nat) (m : nat) (v : Z) (acc : Z) :=\n  Eval cbv [iter_plus_acc pred] in\n    @nat_rect\n      (fun _ => Z * Z -> Z)\n      (fun '(v, acc) => iter_plus_acc m (acc + acc) v)\n      (fun _ rec '(v, acc) => iter_plus_acc m (rec (v, acc) + rec (v, acc)) v)\n      n\n      (v, acc).\n\nDefinition eval_Z_to_nat n : Z.to_nat ('n) = '(Z.to_nat n).\nProof. reflexivity. Qed.\n\nTime Make myrew := Rewriter For (Z.add_0_r, eval_Z_to_nat, eval_rect nat, eval_rect prod).\n\nNotation goal n m := (forall acc, make_tree n m 0 acc = acc) (only parsing).\nLtac start _ := cbv [make_tree]; intros.\nLtac verify_form term :=\n  lazymatch term with\n  | ?x + ?x => verify_form x\n  | _ => is_var term\n  end.\nLtac verify _ :=\n  lazymatch goal with\n  | [ |- ?lhs = ?acc ]\n    => is_var acc; verify_form lhs\n  end.\n\n(* size(iter_plus_acc(m, acc, v)) := size(acc) + m * (1 + size(v))\n   size(make_tree(0, m, v, acc)) := size(iter_plus_acc(m, 1+2*size(acc), v))\n   size(make_tree(1+n,m,v, acc)) := size(iter_plus_acc(m, 1+2*size(make_tree(n,m,v,acc)), v)) *)\n(* RSolve[{mt[0, m, v, acc] == ipa[m, 1 + 2*acc, v],\n   mt[n, m, v, acc] == ipa[m, 1 + 2*mt[n - 1, m, v, acc], v]} /.\n  ipa[m_, acc_, v_] :> acc + m*(1 + v), mt[n, m, v, acc], n]\n *)\n(* mt[n, m, v, acc] -> -1 + 2^(1 + n) + 2^(1 + n) acc - m + 2^(1 + n) m -\n   m v + 2^(1 + n) m v *)\n(* mt[n, m, 1, 1] -> 1 + 2 (2^(n + 1) - 1) (m + 1) *)\nDefinition input_num_nodes (n : Z) (m : Z) : Z\n  := (1 + 2 * (2^(n+1) - 1) * (m + 1))%Z.\n\n(* size(iter_plus_acc(m, acc)) := size(acc)\n   size(make_tree(0, m, v, acc)) := size(iter_plus_acc(m, 1+2*size(acc), v))\n   size(make_tree(1+n,m,v, acc)) := size(iter_plus_acc(m, 1+2*size(make_tree(n,m,v,acc)), v)) *)\n(* RSolve[{mt[0, m, v, acc] == ipa[m, 1 + 2*acc, v],\n   mt[n, m, v, acc] == ipa[m, 1 + 2*mt[n - 1, m, v, acc], v]} /.\n  ipa[m_, acc_, v_] :> acc, mt[n, m, v, acc], n]\n *)\n(* mt[n, m, v, acc] -> -1 + 2^(1 + n) + 2^(1 + n) acc *)\n(* mt[n, m, _, 1] -> -1 + 2^(2 + n) *)\nDefinition output_num_nodes (n : Z) (m : Z) : Z\n  := (2^(n+2)-1)%Z.\n\n(* #0s(iter_plus_acc(m, acc, v)) := #0s(acc) + m * #0s(v)\n   #0s(make_tree(0, m, v, acc)) := #0s(iter_plus_acc(m, 2*#0s(acc), v))\n   #0s(make_tree(1+n,m,v, acc)) := #0s(iter_plus_acc(m, 2*#0s(make_tree(n,m,v,acc)), v)) *)\n(* RSolve[{mt[0, m, v, acc] == ipa[m, 2*acc, v],\n   mt[n, m, v, acc] == ipa[m, 2*mt[n - 1, m, v, acc], v]} /.\n  ipa[m_, acc_, v_] :> acc + m*v, mt[n, m, v, acc], n]\n *)\n(* mt[n, m, v, acc] -> 2^(1 + n) acc - m v + 2^(1 + n) m v *)\n(* mt[n, m, 1, 0] -> (-1 + 2^(n + 1)) m *)\nDefinition output_num_rewrites (n : Z) (m : Z) : Z\n  := ((2^(n+1) - 1) * m)%Z.\n\nDefinition size_of_arg (arg : Z * Z) : Z\n  := Eval cbv [output_num_nodes output_num_rewrites] in\n      output_num_rewrites (fst arg) (snd arg).\n\nDefinition invert_size_of_arg_dumb (v : Z) : Z * Z\n  := (0%Z, v).\n\nLocal Lemma invert_size_of_arg_dumb_correct v\n  : size_of_arg (invert_size_of_arg_dumb v) = v.\nProof. cbv [size_of_arg invert_size_of_arg_dumb]; cbn [fst snd]; vm_compute Z.pow; lia. Qed.\n\nLocal Instance Z_prod_has_compress : Sample.has_compress (Z * Z) Z := size_of_arg.\nLocal Instance Z_prod_has_make : Sample.has_make (Z * Z) Z := { make_T := invert_size_of_arg_dumb ; make_T_correct := invert_size_of_arg_dumb_correct }.\n\nModule Import instances.\n  Import Coq.QArith.QArith Coq.QArith.Qround Coq.QArith.Qabs Coq.QArith.Qminmax.\n  Import Sample.\n  Local Open Scope Z_scope.\n  Local Set Warnings Append \"-ambiguous-paths\".\n  Local Coercion N.of_nat : nat >-> N.\n  Local Coercion N.to_nat : N >-> nat.\n  Local Coercion Z.of_N : N >-> Z.\n  Local Coercion inject_Z : Z >-> Q.\n  Local Coercion Npos : positive >-> N.\n\n  Definition allocate_points_for (n : Z) (min max : Z) (max_points : N) : list (Z * Z)\n    := let v : Z := compress_T (n:Z, 1) in\n       List.map (fun m => (n:Z, m))\n                (Zrange_max_points (Qceiling (min / v))\n                                   (Qfloor (max / v))\n                                   max_points).\n  Fixpoint alloc_down_from (points_remaining : N) (min max : Z) (n : nat) : list (Z * Z)\n    := match points_remaining with\n       | 0%N => []\n       | 1%N => [(0, max)]\n       | 2%N => [(0, min); (0, max)]\n       | _\n         => let max_cur_points := (points_remaining / S n)%N in\n            let cur_points := allocate_points_for n min max max_cur_points in\n            match n with\n            | O => []\n            | S n' => alloc_down_from (points_remaining - List.length cur_points) min max n'\n            end\n              ++ cur_points\n       end.\n\n  (** If we don't have enough points, start going through from the smallest value of [n] and filling in all possible points *)\n  Fixpoint extra_alloc_at_bottom (extra_points_remaining : N)\n           (min max : Z)\n           (sparse_points dense_points : list (Z * Z))\n           (cur_n : nat)\n           (fuel : nat)\n    : list (Z * Z)\n    := if ((extra_points_remaining =? 0)%N || (max <? min))\n       then dense_points ++ sparse_points\n       else\n         let '(removed_points, sparse_points) := List.partition (fun '(n, m) => (n =? cur_n)) sparse_points in\n         let extra_points_remaining := (extra_points_remaining + List.length removed_points)%N in\n         let new_points := allocate_points_for extra_points_remaining min max cur_n in\n         let extra_points_remaining := (extra_points_remaining - List.length new_points)%N in\n         let dense_points := dense_points ++ new_points in\n         match fuel with\n         | O => dense_points ++ sparse_points\n         | S fuel\n           => extra_alloc_at_bottom extra_points_remaining min max sparse_points dense_points (S cur_n) fuel\n         end.\n\n  Definition extra_alloc_if_necessary\n             (max_n : Z)\n             (min max : Z)\n             (n_points : N)\n             (cur_points : list (Z * Z))\n    := extra_alloc_at_bottom (n_points - List.length cur_points) min max cur_points [] O (Z.to_nat max_n).\n\n  Global Instance Z_prod_has_alloc : has_alloc (Z * Z)\n  := { alloc_T min max n\n       := match n with\n          | 0%N => []\n          | 1%N => [max]\n          | 2%N => [min; max]\n          | _\n            => (let min := compress_T min in\n                let max := compress_T max in\n                let max_n := (* max = (2^(n+1) - 1) * m; m = 1 *) Z.log2 (max + 1) - 1 in\n                if max_n + 1 <=? (1 + (n+1)/3)\n                then\n                   (* we want all the possible values of the first pair *)\n                  alloc_down_from n min max (Z.to_nat max_n)\n                else\n                  extra_alloc_if_necessary\n                    max_n min max n\n                    (List.flat_map\n                       (fun v => allocate_points_for v min max 3)\n                       (alloc_T 0 max_n (1 + (n+1)/3))))%Z\n          end }.\nEnd instances.\n\nInductive rewrite_strat_kind := topdown | bottomup.\nInductive kind_of_rewrite := kind_rewrite_strat (_ : rewrite_strat_kind) | kind_setoid_rewrite | kind_rewrite | kind_autorewrite | kind_ssr_rewrite | kind_rewrite_lhs_for.\n\nLocal Notation \"'eta_kind' ( k' => f ) k\"\n  := match k with\n     | kind_rewrite_strat topdown\n       => subst! (kind_rewrite_strat topdown) for k' in f\n     | kind_rewrite_strat bottomup\n       => subst! (kind_rewrite_strat bottomup) for k' in f\n     | kind_setoid_rewrite => subst! kind_setoid_rewrite for k' in f\n     | kind_rewrite => subst! kind_rewrite for k' in f\n     | kind_autorewrite => subst! kind_autorewrite for k' in f\n     | kind_ssr_rewrite => subst! kind_ssr_rewrite for k' in f\n     | kind_rewrite_lhs_for => subst! kind_rewrite_lhs_for for k' in f\n     end\n       (only parsing, at level 70, k' ident).\n\nLocal Lemma sanity : forall T f k, eta_kind (k => f k) k = f k :> T.\nProof. intros; repeat match goal with |- context[match ?e with _ => _ end] => destruct e end; reflexivity. Qed.\n\n(* datastr = <....>;\ntbl = Map[\n   Map[(If[StringLength[#] == 0, Null,\n        If[StringMatchQ[#, NumberString], ToExpression[#], #]]) &,\n     StringSplit[#, \",\", All]] &, StringSplit[datastr, \"\\n\"]];\ncols = Transpose[tbl] /. {x_String, ___} :>\n    Sequence[] /;\n     Not[StringMatchQ[x, \"param-\" ~~ ___] ||\n       StringMatchQ[x, ___ ~~ \"-regression-\" ~~ ___ ~~ \"-real\"]];\ndata = Map[{#[[1]],\n      Transpose[{Drop[cols[[1]], 1], Drop[#, 1]}] /. {_, Null} :>\n        Sequence[]} &, cols] /. {x_String, _} :>\n    Sequence[] /; StringMatchQ[x, \"param-\" ~~ ___];\ndata3D = Map[{#[[1]],\n      Transpose[{Drop[cols[[2]], 1], Drop[cols[[3]], 1],\n         Drop[#, 1]}] /. {_, _, Null} :> Sequence[]} &,\n    cols] /. {x_String, _} :>\n    Sequence[] /; StringMatchQ[x, \"param-\" ~~ ___];\nfits = Map[{#[[1]],\n     NonlinearModelFit[#[[2]],\n      a + b X + c Y + d X Y + e X^2 + f Y^2 + g X^3 + h X^2 Y +\n        i X Y^2 + j Y^3 /. {X -> 2^n, Y -> m}, {a, b, c, d, e, f, g,\n       h, i, j}, {n, m}]} &, data3D];\nfits2 = Map[{#[[1]],\n     NonlinearModelFit[#[[2]],\n      a + b X + c Y + d X Y + e X^2 + f Y^2 /. {X -> 2^n, Y -> m}, {a,\n        b, c, d, e, f}, {n, m}]} &, data3D];\nListPlot[Map[#[[2]] &, data], PlotLegends -> Map[#[[1]] &, data], PlotRange -> Full]\nListPointPlot3D[Map[#[[2]] &, data3D],\n PlotLegends -> Map[#[[1]] &, data3D], PlotRange -> Full,\n AxesLabel -> {n, m, z}]\nTable[Function[{d}, {Show[\n     ListPointPlot3D[Map[#[[2]] &, data3D[[{d}]]],\n      PlotLegends -> Map[#[[1]] &, data3D[[{d}]]],\n      PlotRange -> {Full, Full, {0, 10}}, AxesLabel -> {n, m, z}],\n     Plot3D[fits[[d]][[2]][n, m], {n, 0, 10}, {m, 0, 1500}(*,\n      PlotLegends\\[Rule]{Normal[fits[[d]][[2]]]}*)],\n     ImageSize -> Large], Normal[fits[[d]][[2]]]}][d], {d, 1,\n  Length[data3D]}]\nMap[{#[[1]], Normal[#[[2]]] /. n -> 0 /. m -> x} &, fits]\nMap[{#[[1]], Normal[#[[2]]] /. n -> 0 /. m -> x} &, fits2]\n(*ExpandAll[\n Map[{#[[1]], Normal[#[[2]]] /. n -> Log2[x + 1] - 1 /. m -> 1} &,\n  fits]]*)\n *)\n\nLocal Notation parse x := (invert_Some (parseQ_arith_strict x)) (only parsing).\nLocal Notation parse_poly_expr p x := (invert_Some (parseQexpr_arith_with_vars [(\"x\"%string, x)] p)) (only parsing).\nLocal Notation red_vm_compute x := (ltac:(let z := (eval vm_compute in x) in\n                                          exact z)) (only parsing).\nLocal Notation parse_poly p x := (invert_Some (eval_Qexpr_strict (red_vm_compute (parse_poly_expr p x)))) (only parsing).\n\nDefinition size_of_kind (k : kind_of_rewrite) (arg : Z * Z) : Q\n  := let termsize := size_of_arg arg in\n     let x := inject_Z termsize in\n     let '(n, m) := (fst arg, inject_Z (snd arg)) in\n     match k with\n     | kind_rewrite_strat bottomup\n       => (*-0.218 + 3.68E-03*x + 6.64E-06*x^2*)\n       parse_poly \"-0.964971 + 0.00567641*x + 0.000133294*x^2\"%string x\n(*       -0.0419087 - 0.015458 * 2^n - 0.000126407 * 2^(2 * n) -\n 1.08304E-7 * 2^(3 * n) - 0.0248191 * m + 0.00639815 * 2^n * m +\n 0.00021925 * 2^(2 * n) * m + 0.000265979 * m^2 + 0.000269755 * 2^n * m^2 -\n 3.14699E-6 * m^3*)\n     | kind_rewrite_strat topdown\n       => (*0.141 + -8.55E-04*x + 3.28E-06*x^2*)\n       parse_poly \"-0.151224 + 0.000230063*x + 4.83713E-6*x^2 + 4.31671E-10*x^3\"%string x\n(*       -0.144716 - 0.00652151 * 2^n + 0.0000138788 * 2^(2 * n) -\n 7.77221E-9 * 2^(3 * n) - 0.00374702 * m + 0.00397668 * 2^n * m +\n 4.03926E-7 * 2^(2 * n) * m - 0.0000288226 * m^2 + 0.0000336598 * 2^n * m^2 +\n 4.31671E-10 * m^3*)\n     | kind_setoid_rewrite\n       => (*3.51E-03 + 4.45E-04*x + 3.73E-06*x^2*)\n       parse_poly \"-0.169646 + 0.00123046*x + 8.46486E-6*x^2\"%string x\n(*       -0.0916119 - 0.0127236 * 2^n + 0.0000322477 * 2^(2 * n) -\n 7.57294E-8 * 2^(3 * n) - 0.00446198 * m + 0.00482246 * 2^n * m +\n 0.0000287754 * 2^(2 * n) * m - 0.0000508636 * m^2 + 0.0000606788 * 2^n * m^2 -\n 5.46448E-10 * m^3*)\n     | kind_rewrite\n       => (*5.67E-03 + 1.33E-04*x + 1.1E-06*x^2*)\n       parse_poly \"-0.0698785 + 0.000620073*x + 3.63E-6*x^2 + 9.61722E-10*x^3\"%string x\n(*       -0.0683191 - 0.00156502 * 2^n + 5.57927E-6 * 2^(2 * n) -\n 1.73021E-9 * 2^(3 * n) - 0.000478266 * m + 0.00110145 * 2^n * m -\n 3.1091E-6 * 2^(2 * n) * m - 0.0000256011 * m^2 + 0.0000292311 * 2^n * m^2 +\n 9.61722E-10 * m^3*)\n     | kind_autorewrite\n       => (*0.0219 + 2.31E-04*x + 1.02E-06*x^2*)\n       parse_poly \"-0.0585252 + 0.00014934*x + 4.96778E-6*x^2 + 2.96753E-10*x^3\"%string x\n(*       -0.0586838 + 0.000158133 *2^n + 4.35038E-7 *2^(2* n) +\n 5.13011E-10 *2^(3* n) - 0.000282043 * m + 0.000432666 *2^n* m -\n 1.28322E-6 *2^(2 *n) *m - 0.0000307768 *m^2 + 0.0000357446 * 2^n * m^2 +\n 2.96753E-10 *m^3*)\n     | kind_ssr_rewrite\n       => (*3.98E-03 + 2.32E-04*x + 2.01E-06*x^2*)\n       parse_poly \"-0.0684302 + 0.000469109*x + 7.5704E-6*x^2 + 5.51547E-10*x^3\"%string x\n(*       -0.0667915 - 0.00164326 * 2^n + 4.56044E-6 * 2^(2 * n) -\n 1.29764E-9 * 2^(3 * n) - 0.000935073 * m + 0.00140678 * 2^n * m -\n 2.59326E-6 * 2^(2 * n) * m - 0.0000493663 * m^2 + 0.0000569367 * 2^n * m^2 +\n 5.51547E-10 * m^3*)\n     | kind_rewrite_lhs_for\n       => parse_poly \"0.256649 - 8.2992E-7 *x + 7.03001E-10 *x^2\"%string x\n     end%Q.\n\nDefinition max_input_of_kind (k : kind_of_rewrite) : option (Z * Z)\n  := match k with\n     | kind_rewrite_strat _\n       => None\n     | kind_setoid_rewrite\n       => None\n     | kind_rewrite\n       => None\n     | kind_autorewrite\n       => None\n     | kind_ssr_rewrite\n       => None\n     | kind_rewrite_lhs_for\n       => None\n     end%Z.\n\nDefinition args_of_size_by_sample' (k : kind_of_rewrite) (s : size) : list (Z * Z)\n  := Eval cbv beta iota in\n      eta_size\n        (s'\n         => if match s' with Sanity => true | _ => false end\n            then [(0, 1); (0, 2); (0, 3); (1, 1); (0, 4); (0, 5); (0, 6); (1, 2)]\n            else eta_kind\n                   (k'\n                    => Sample.generate_inputs\n                         (T:=Z*Z)\n                         (0, 1)\n                         (size_of_kind k')\n                         (Qseconds_of_size s')\n                         (Qstandard_max_seconds_of_size s')\n                         Sample.default_max_points\n                         (max_input_of_kind k'))\n                   k)\n        s.\nLocal Set NativeCompute Profiling.\nLocal Set NativeCompute Timing.\n(* Takes about 2 seconds *)\nTime Definition args_of_size_by_sample (k : kind_of_rewrite) (s : size)\n  := Eval native_compute in eta_size (s' => eta_kind (k' => args_of_size_by_sample' k' s') k) s.\n\nDefinition compat_args_of_size' (test_tac_n : nat) (s : size)\n  := let ls\n         := match test_tac_n, s with\n            | 0, SuperFast => [(11, 2); (7, 4)]\n            | 1, SuperFast => [(12, 3)]\n            | 2, SuperFast => [(8, 3)]\n            | 3, SuperFast => [(9, 3)]\n            | 4, SuperFast => [(7, 3)]\n            | 0, Fast => [(14, 5); (13, 20); (9, 1000)]\n            | 1, Fast => [(14, 2); (13, 3); (9, 18); (5, 50); (4, 130); (3, 200); (2, 340); (1, 600)]\n            | 2, Fast => [(10, 2); (9, 3); (8, 5); (7, 9); (6, 15); (5, 30); (4, 40); (3, 95); (2, 180); (1, 380)]\n            | 3, Fast => [(10, 1); (9, 3); (8, 7); (7, 15); (6, 25); (5, 50); (4, 80); (3, 150); (2, 270); (1, 550)]\n            | 4, Fast => [(9, 1); (8, 2); (7, 3); (6, 5); (5, 11); (4, 30); (3, 60); (2, 110); (1, 260)]\n            | 0, Medium => [(16, 3); (12, 100)]\n            | 1, Medium => [(15, 3); (9, 40)]\n            | 2, Medium => [(11, 2); (10, 3); (9, 10)]\n            | 3, Medium => [(11, 2); (10, 3); (9, 12)]\n            | 4, Medium => [(9, 2); (8, 3); (10, 1)]\n            | 0, Slow => [(16, 4)] (* ??? *)\n            | 1, Slow => [(16, 4)] (* ??? *)\n            | 2, Slow => [(12, 4)] (* ? (11, 3) is 122.176s *)\n            | 3, Slow => [(12, 4)] (* ? (11, 3) is 165.575s *)\n            | 4, Slow => [(9, 3); (10, 2); (11, 1)] (* ? should we have more for smaller fst of the pair? *)\n            | _, VerySlow => [(1000, 1000)] (* ??? *)\n            | _, _ => []\n            end%nat in\n     Zsort_by_fst\n       (List.flat_map\n          (fun '(n_count, m_count)\n           => List.flat_map (fun n => let n := Z.of_nat n in List.map (fun m => (n, Z.of_nat m)) (seq 1 m_count)) (seq 1 n_count))\n          ls).\n\nDefinition kind_to_compat (k : kind_of_rewrite) : option nat\n  := match k with\n     | kind_rewrite_lhs_for => Some 0\n     | kind_rewrite => Some 1\n     | kind_setoid_rewrite => Some 2\n     | kind_rewrite_strat topdown => Some 3\n     | kind_rewrite_strat bottomup => Some 4\n     | kind_autorewrite => None\n     | kind_ssr_rewrite => None\n     end%nat.\n\nDefinition compat_args_of_size (k : kind_of_rewrite) (s : size)\n  := match kind_to_compat k, s with\n     | _, (Sanity | Slow | VerySlow)\n     | None, _\n       => args_of_size_by_sample k s\n     | Some n, _ => compat_args_of_size' n s\n     end.\n\nTime Definition args_of_size (k : kind_of_rewrite) (s : size)\n  := Eval native_compute in eta_size (s' => eta_kind (k' => compat_args_of_size k' s') k) s.\n\nLtac mkgoal kind nm\n  := let Z_to_nat := (eval vm_compute in Z.to_nat) in\n     lazymatch nm with\n     | (?n, ?m)\n       => let n := constr:(id Z_to_nat n) in\n          let m := constr:(id Z_to_nat m) in\n          constr:(goal n m)\n     end.\nLtac redgoal _ := start ().\nLtac describe_goal nm :=\n  lazymatch nm with\n  | (?n, ?m)\n    => let sz := (eval vm_compute in (size_of_arg nm)) in\n       let input_num_nodes := (eval vm_compute in (input_num_nodes n m)) in\n       let output_num_nodes := (eval vm_compute in (output_num_nodes n m)) in\n       let num_rewrites := (eval vm_compute in (output_num_rewrites n m)) in\n       idtac \"Params: 0-nm=\" sz \", 1-n=\" n \", 2-m=\" m \", 3-input-size=\" input_num_nodes \", 4-output-size=\" output_num_nodes \", 5-num-rewrites=\" num_rewrites\n  end.\n\n#[global] Hint Rewrite Z.add_0_r : mydb.\n\nLtac do_coq_rewrite _ := rewrite -> !Z.add_0_r.\n\nRequire Import Coq.ssr.ssreflect.\n\nLtac do_ssr_rewrite _ := rewrite !Z.add_0_r.\n\nLtac time_solve_goal kind\n  := let Z_to_nat := (eval cbv in Z.to_nat) in\n     let change_Z_to_nat _ := (change (id Z_to_nat) with Z.to_nat) in\n     lazymatch kind with\n     | kind_rewrite_strat topdown\n       => fun nm\n          => time \"rewrite_strat(topdown)-regression-cubic\"\n                  (cbv [nat_rect id]; repeat rewrite_strat topdown hints mydb)\n     | kind_rewrite_strat bottomup\n       => fun nm\n          => time \"rewrite_strat(bottomup)-regression-cubic\"\n                  (cbv [nat_rect id]; repeat rewrite_strat bottomup hints mydb)\n     | kind_setoid_rewrite\n       => fun nm\n          => time \"setoid_rewrite-regression-cubic\"\n                  (cbv [nat_rect id]; repeat setoid_rewrite Z.add_0_r)\n     | kind_rewrite\n       => fun nm\n          => time \"rewrite!-regression-cubic\"\n                  (cbv [nat_rect id]; do_coq_rewrite ())\n     | kind_ssr_rewrite\n       => fun nm\n          => time \"ssr-rewrite!-regression-cubic\"\n                  (cbv [nat_rect id]; do_ssr_rewrite ())\n     | kind_autorewrite\n       => fun nm\n          => time \"autorewrite-regression-cubic\"\n                  (cbv [nat_rect id]; repeat autorewrite with mydb)\n     | kind_rewrite_lhs_for\n       => fun nm\n          => time \"Rewrite_lhs_for-regression-quadratic\" (change_Z_to_nat (); Rewrite_lhs_for myrew)\n     end.\n\n(**\n<<<\n\n#!/usr/bin/env python3\n\nprint(r'''(**\n<<<\n''')\nprint(open(__file__, 'r').read())\nprint(r'''>>>\n *)''')\n\nfor i, c in enumerate(('kind_rewrite_strat topdown', 'kind_rewrite_strat bottomup', 'kind_setoid_rewrite', 'kind_rewrite', 'kind_ssr_rewrite', 'kind_autorewrite')):\n    print(f'Ltac mkgoal{i} := mkgoal constr:({c}).\\nLtac time_solve_goal{i} := time_solve_goal constr:({c}).\\nLtac run{i} sz := Harness.runtests_verify_sanity (args_of_size ({c})) describe_goal mkgoal{i} redgoal time_solve_goal{i} verify sz.\\n')\n\n>>>\n *)\nLtac mkgoal0 := mkgoal constr:(kind_rewrite_strat topdown).\nLtac time_solve_goal0 := time_solve_goal constr:(kind_rewrite_strat topdown).\nLtac run0 sz := Harness.runtests_verify_sanity (args_of_size (kind_rewrite_strat topdown)) describe_goal mkgoal0 redgoal time_solve_goal0 verify sz.\n\nLtac mkgoal1 := mkgoal constr:(kind_rewrite_strat bottomup).\nLtac time_solve_goal1 := time_solve_goal constr:(kind_rewrite_strat bottomup).\nLtac run1 sz := Harness.runtests_verify_sanity (args_of_size (kind_rewrite_strat bottomup)) describe_goal mkgoal1 redgoal time_solve_goal1 verify sz.\n\nLtac mkgoal2 := mkgoal constr:(kind_setoid_rewrite).\nLtac time_solve_goal2 := time_solve_goal constr:(kind_setoid_rewrite).\nLtac run2 sz := Harness.runtests_verify_sanity (args_of_size (kind_setoid_rewrite)) describe_goal mkgoal2 redgoal time_solve_goal2 verify sz.\n\nLtac mkgoal3 := mkgoal constr:(kind_rewrite).\nLtac time_solve_goal3 := time_solve_goal constr:(kind_rewrite).\nLtac run3 sz := Harness.runtests_verify_sanity (args_of_size (kind_rewrite)) describe_goal mkgoal3 redgoal time_solve_goal3 verify sz.\n\nLtac mkgoal4 := mkgoal constr:(kind_ssr_rewrite).\nLtac time_solve_goal4 := time_solve_goal constr:(kind_ssr_rewrite).\nLtac run4 sz := Harness.runtests_verify_sanity (args_of_size (kind_ssr_rewrite)) describe_goal mkgoal4 redgoal time_solve_goal4 verify sz.\n\nLtac mkgoal5 := mkgoal constr:(kind_autorewrite).\nLtac time_solve_goal5 := time_solve_goal constr:(kind_autorewrite).\nLtac run5 sz := Harness.runtests_verify_sanity (args_of_size (kind_autorewrite)) describe_goal mkgoal5 redgoal time_solve_goal5 verify sz.\n\nLtac mkgoal6 := mkgoal constr:(kind_rewrite_lhs_for).\nLtac time_solve_goal6 := time_solve_goal constr:(kind_rewrite_lhs_for).\nLtac run6 sz := Harness.runtests_verify_sanity (args_of_size (kind_rewrite_lhs_for)) describe_goal mkgoal6 redgoal time_solve_goal6 verify sz.\n\n#[global] Hint Opaque Z.add : rewrite typeclass_instances.\n\nGlobal Instance : forall {A}, Proper (eq ==> eq ==> Basics.flip Basics.impl) (@eq A) := _.\nGlobal Instance : Proper (eq ==> eq ==> eq) Z.add := _.\nGlobal Instance : forall {acc}, @ProperProxy Z (@eq Z) acc := _.\nGlobal Instance : forall {A}, subrelation (@eq A) (@eq A) := _.\n\nGlobal Set NativeCompute Timing.\nGlobal Open Scope Z_scope.\n\n(*\nGoal True.\n  run3 Sanity.\n*)\n", "meta": {"author": "mit-plv", "repo": "rewriter", "sha": "77c76a43689ce532921ccfa200b44083bc52dc21", "save_path": "github-repos/coq/mit-plv-rewriter", "path": "github-repos/coq/mit-plv-rewriter/rewriter-77c76a43689ce532921ccfa200b44083bc52dc21/src/Rewriter/Rewriter/Examples/PerfTesting/Plus0Tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6633351364884363}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_supplementsymmetric.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_oppositesidesymmetric.\nRequire Export GeoCoq.Elements.OriginalProofs.proposition_27.\n\nSection Euclid.\nContext `{Ax:euclidean_neutral_ruler_compass}.\nLemma proposition_28B : \n   forall A B C D G H, \n   BetS A G B -> BetS C H D -> RT B G H G H D -> OS B D G H ->\n   Par A B C D.\nProof.\nintros.\nassert (OS D B G H) by (forward_using lemma_samesidesymmetric).\nlet Tf:=fresh in\nassert (Tf:exists a b c d e, (Supp a b c e d /\\ CongA B G H a b c /\\ CongA G H D e b d)) by (conclude_def RT );destruct Tf as [a[b[c[d[e]]]]];spliter.\nassert (CongA a b c B G H) by (conclude lemma_equalanglessymmetric).\nassert (neq G H) by (forward_using lemma_angledistinct).\nassert (CongA e b d G H D) by (conclude lemma_equalanglessymmetric).\nassert (eq H H) by (conclude cn_equalityreflexive).\nassert (Out G H H) by (conclude lemma_ray4).\nassert (Supp A G H H B) by (conclude_def Supp ).\nassert (Supp B G H H A) by (conclude lemma_supplementsymmetric).\nassert (CongA e b d H G A) by (conclude lemma_supplements).\nassert (CongA G H D e b d) by (conclude lemma_equalanglessymmetric).\nassert (CongA G H D H G A) by (conclude lemma_equalanglestransitive).\nassert (nCol H G A) by (conclude lemma_equalanglesNC).\nassert (CongA H G A A G H) by (conclude lemma_ABCequalsCBA).\nassert (CongA G H D A G H) by (conclude lemma_equalanglestransitive).\nassert (CongA A G H G H D) by (conclude lemma_equalanglessymmetric).\nassert (eq G G) by (conclude cn_equalityreflexive).\nassert (Col G H G) by (conclude_def Col ).\nassert (nCol A G H) by (conclude lemma_equalanglesNC).\nassert (~ Col G H A).\n {\n intro.\n assert (Col A G H) by (forward_using lemma_collinearorder).\n contradict.\n }\nassert (TS A G H B) by (conclude_def TS ).\nassert (TS B G H A) by (conclude lemma_oppositesidesymmetric).\nassert (TS D G H A) by (conclude lemma_planeseparation).\nassert (TS A G H D) by (conclude lemma_oppositesidesymmetric).\nassert (Par A B C D) by (conclude proposition_27).\nclose.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/proposition_28B.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.6633007075571139}}
{"text": "\nFrom Coq Require Import ssreflect.\nRequire Import Bool.\n\nDefinition truthtable c1 c2 c3 :=\n  match c1, c2, c3 with\n  | true, true, true => true\n  | _, _, _ => false\n  end.\n\nGoal forall (c1 c2 c3 : bool), truthtable c1 c2 c3 = c1 && c2 && c3.\n  case.\n  - case.\n    + case.\n      * done.\n      * done.\n    + case.\n      * done.\n      * done.\n  - case.\n    + case.\n      * done.\n      * done.\n    + case.\n      * done.\n      * done.\nQed.        \n", "meta": {"author": "morita-hm", "repo": "mbd_coq", "sha": "cd5cd9d9666721ca253b10a435007cac63bec194", "save_path": "github-repos/coq/morita-hm-mbd_coq", "path": "github-repos/coq/morita-hm-mbd_coq/mbd_coq-cd5cd9d9666721ca253b10a435007cac63bec194/TruthTable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480666, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6632983898898346}}
{"text": "Require Import CT.Category.\nRequire Import CT.Algebra.Magma.\nRequire Import CT.Algebra.Monoid.\nRequire Import CT.Algebra.Semigroup.\n\n(** The category for a given monoid. A monoid is exactly a category with one\n    object.\n *)\nProgram Definition MonoidCategory {T} (M : Monoid) : Category :=\n  {| ob := unit;\n     mor := fun _ _ => T;\n     comp := fun _ _ _ => mu M;\n     id := fun a => one M;\n  |}.\nNext Obligation.\nProof. apply semigroup_assoc. Qed.\nNext Obligation.\nProof. symmetry. apply semigroup_assoc. Qed.", "meta": {"author": "relrod", "repo": "ct", "sha": "abd8b0067e219ee4867f7136bdf1b35885224cb4", "save_path": "github-repos/coq/relrod-ct", "path": "github-repos/coq/relrod-ct/ct-abd8b0067e219ee4867f7136bdf1b35885224cb4/CT/Instance/Category/MonoidCategory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6631785753921151}}
{"text": "Variables P Q R T : Prop.\n\nSection Minimal_propositional_logic.\n\n  (* Using explicit tactics *)\n  Theorem imp_trans : (P -> Q) -> (Q -> R) -> P -> R.\n  Proof.\n    intros H H' p.\n    apply H'.\n    apply H.\n    assumption.\n  Qed.\n\n  (* Getting Coq to help us *)\n  Theorem imp_trans' : (P -> Q) -> (Q -> R) -> P -> R.\n  Proof.\n    auto.\n  Qed.\nEnd Minimal_propositional_logic.\n\nSection example_of_assumption.\n  Hypothesis H : P -> Q -> R.\n\n  (* More assumptions! *)\n  Lemma L1 : P -> Q -> R.\n  Proof.\n    assumption.\n  Qed.\nEnd example_of_assumption.\n\nSection taken_to_the_extreme.\n  (* We can also define proofs in terms of functions.\n   * Thanks Curry and Howard!\n   *)\n  Theorem delta : (P -> P -> Q) -> P -> Q.\n  (* Note that inline proofs are not recommended by Bertot *)\n  Proof (fun (H:P->P->Q)(p:P) => H p p).\nEnd taken_to_the_extreme.\n\nPrint imp_trans.\nPrint imp_trans'.\nPrint L1.\nPrint delta.\n\n(* Regular ol' tactics *)\nTheorem compose_example : (P -> Q -> R) -> (P -> Q) -> (P -> R).\nProof.\n  intros H H' p.\n  apply H.\n  apply p.\n  apply H'.\n  assumption.\nQed.\n\n(* 'Tacticals', or, higher-order tactics. *)\nTheorem compose_example' : (P -> Q -> R) -> (P -> Q) -> (P -> R).\nProof.\n  intros H H' p.\n  apply H;[assumption | apply H'; assumption].\nQed.\n\n(* Regular ol' tactics *)\nLemma L3 : (P->Q)->(P->R)->(P->Q->R->T)->P->T.\nProof.\n  intros H H0 H1 p.\n  apply H1.\n  assumption.\n  apply H.\n  assumption.\n  apply H0.\n  assumption.\nQed.\n\n(* 'Tacticals', or, higher-order tactics. Featuring ID. *)\nLemma L3' : (P->Q)->(P->R)->(P->Q->R->T)->P->T.\nProof.\n  intros H H0 H1 p.\n  apply H1;[idtac | apply H | apply H0]; assumption.\nQed.", "meta": {"author": "dogonthehorizon", "repo": "coq_practice", "sha": "df0b3b0ddb6475a01ad227fbffad7db09e0fda4f", "save_path": "github-repos/coq/dogonthehorizon-coq_practice", "path": "github-repos/coq/dogonthehorizon-coq_practice/coq_practice-df0b3b0ddb6475a01ad227fbffad7db09e0fda4f/coqart/ch3/simple_tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6631376050346097}}
{"text": "Require Import Coq.funind.FunInd.\nRequire Import Coq.Lists.List Coq.Lists.SetoidList. Import ListNotations.\nRequire Import Coq.Numbers.BinNums Coq.NArith.BinNat.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Algebra.Monoid Crypto.Algebra.ScalarMult.\nRequire Import Crypto.Util.Option.\nRequire Import Crypto.Util.Tactics.BreakMatch.\n\nSection AddChainExp.\n  (* TODO: rewrite this.\n     - use CPS and Loop\n     - use an inner loop for repeated squaring\n     - connect to something that abstracts over F.pow, Z.pow, N.pow NOT scalarmult\n  *)\n\n  Function fold_chain {T} (id:T) (op:T->T->T) (is:list (nat*nat)) (acc:list T) {struct is} : T :=\n    match is with\n    | nil =>\n      match acc with\n      | nil => id\n      | ret::_ => ret\n      end\n    | (i,j)::is' =>\n      let ijx := op (nth_default id acc i) (nth_default id acc j) in\n      fold_chain id op is' (ijx::acc)\n    end.\n\n  Example wikipedia_addition_chain : fold_chain 0 plus [\n  (0, 0); (* 2 = 1 + 1 *) (* the indices say how far back the chain to look *)\n  (0, 1); (* 3 = 2 + 1 *)\n  (0, 0); (* 6 = 3 + 3 *)\n  (0, 0); (* 12 = 6 + 6 *)\n  (0, 0); (* 24 = 12 + 12 *)\n  (0, 2); (* 30 = 24 + 6 *)\n  (0, 6)] (* 31 = 30 + 1 *)\n  [1] = 31. reflexivity. Qed.\nEnd AddChainExp.\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/AdditionChainExponentiation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6631375874468941}}
{"text": "Require Import List ZArith.\nImport ListNotations.\n\nRequire Import formal_av1.basic_types.\nRequire Import formal_av1.entropy.bitstream_position.\n\n(* AV-1 spec 4.10. Descriptors *)\n\nInductive descriptor : Set :=\n  | descriptor_f : nat -> descriptor\n  | descriptor_uvlc : descriptor\n  | descriptor_le : nat -> descriptor\n  | descriptor_leb128 : descriptor\n  | descriptor_su : nat -> descriptor\n  | descriptor_ns : nat -> descriptor\n  | descriptor_L : nat -> descriptor\n  | descriptor_S : descriptor\n  | descriptor_NS : nat -> descriptor.\n\nDefinition bit_to_nat (b : bit) : nat :=\n  match b with\n  | bit_0 => 0\n  | bit_1 => 1\n  end.\n\n(* AV-1 spec 4.10.2. f(n) *)\n(* AV-1 spec 8.1. Parsing process for f(n) *)\n\nInductive f_decode_relation : nat -> list bit -> nat -> Prop :=\n  | f_decode_relation_nil :\n    f_decode_relation 0 [] 0\n  | f_decode_relation_next :\n    forall n bs b x,\n    f_decode_relation n bs x ->\n    f_decode_relation (S n) (bs ++ [b]) (2 * x + (bit_to_nat b)).\n\n(* AV-1 spec 4.10.3. uvlc() *)\n\nInductive uvlc_decode_relation : list bit -> nat -> Prop :=\n  | uvlc_decode_less_32 :\n    forall leading_zeros, leading_zeros < 32 ->\n    forall value l, f_decode_relation leading_zeros l value ->\n    uvlc_decode_relation\n      ((repeat bit_0 leading_zeros) ++ [bit_1] ++ l)\n      (value + 2 ^ leading_zeros - 1)\n  | uvlc_decode_over_32 :\n    forall leading_zeros, leading_zeros >= 32 ->\n    uvlc_decode_relation\n      ((repeat bit_0 leading_zeros) ++ [bit_1])\n      (2 ^ 32 - 1).\n\n(* AV-1 spec 4.10.4. le(n) *)\n\nInductive le_decode_relation : nat -> list bit -> nat -> Prop :=\n  | le_decode_relation_nil :\n    le_decode_relation 0 [] 0\n  | le_decode_relation_next :\n    forall n l_0 l_more x_0 x_more,\n    f_decode_relation byte.bits_count l_0 x_0 ->\n    le_decode_relation n l_more x_more ->\n    le_decode_relation \n      (S n)\n      (l_0 ++ l_more)\n      (x_0 + 2 ^ byte.bits_count * x_more).\n\n(* AV-1 spec 4.10.5. leb128() *)\n(* Continuation bit can only be 1, if i < 7. *)\n\nInductive leb128_helper (i : nat) : list bit -> nat -> Prop :=\n  | leb128_helper_stop_bit :\n    forall data_bits x, f_decode_relation 7 data_bits x ->\n    leb128_helper i ([bit_0] ++ data_bits) x\n  | leb128_helper_more :\n    i < 7 ->\n    forall data_bits x, f_decode_relation 7 data_bits x ->\n    forall bits_more x_more, leb128_helper (S i) bits_more x_more ->\n    leb128_helper i ([bit_1] ++ data_bits ++ bits_more) (x + 2 ^ 7 * x_more).\n\nInductive leb128_decode_relation (bits : list bit) (x : nat) : Prop :=\n  | leb128_decode_relation_intro :\n    x < 2 ^ 32 ->\n    leb128_helper 0 bits x ->\n    leb128_decode_relation bits x.\n\n(* AV-1 spec 4.10.6. su(n) *)\n\nInductive su_decode_relation : nat -> list bit -> Z -> Prop :=\n  | su_decode_non_negative :\n    forall i bits x,\n    f_decode_relation i bits x ->\n    su_decode_relation (S i) ([bit_0] ++ bits) (Z.of_nat x)\n  | su_decode_negative :\n    forall i bits x,\n    f_decode_relation i bits x ->\n    su_decode_relation\n      (S i)\n      ([bit_1] ++ bits)\n      (- (2 ^ (Z.of_nat i)) + Z.of_nat x).\n\n(* AV-1 spec 4.10.7. ns(n) *)\n\nInductive ns_w_relation (n w : nat) : Prop :=\n  | ns_w_intro :\n    2 ^ (w - 1) <= n ->\n    n < 2 ^ w ->\n    ns_w_relation n w.\n\nInductive ns_m_relation (n : nat) : nat -> Prop :=\n  | ns_m_intro :\n    forall w, ns_w_relation n w ->\n    ns_m_relation n (2 ^ w - n).\n\nInductive ns_decode_relation (n : nat) : list bit -> nat -> Prop :=\n  | ns_decode_short :\n    forall w, ns_w_relation n w ->\n    forall m, ns_m_relation n m ->\n    forall x, x < m ->\n    forall bits, f_decode_relation (w - 1) bits x ->\n    ns_decode_relation n bits x\n  | ns_decode_long :\n    forall w, ns_w_relation n w ->\n    forall m, ns_m_relation n m ->\n    forall x, x >= m ->\n    (* note: 2 * m <= m + x < 2 ^ w *)\n    forall bits, f_decode_relation w bits (m + x) ->\n    ns_decode_relation n bits x.\n", "meta": {"author": "domin144", "repo": "formal_av1", "sha": "595de6587bff6ffd6f8b9089f715dcab0c62ac5a", "save_path": "github-repos/coq/domin144-formal_av1", "path": "github-repos/coq/domin144-formal_av1/formal_av1-595de6587bff6ffd6f8b9089f715dcab0c62ac5a/entropy/descriptors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6631259266651417}}
{"text": "Require Import CT.Algebra.Magma.\nRequire Import CT.Algebra.Group.\nRequire Import CT.Category.\n\n(** * Grp: The category of groups\n\n*)\nProgram Definition Grp (T : Type) : Category :=\n  {| ob := @Group T;\n     mor := GroupHomomorphism;\n     comp := fun _ _ _ => group_hom_composition;\n     id := fun _ => group_hom_id;\n     assoc := fun _ _ _ _ => group_hom_composition_assoc\n  |}.\nNext Obligation.\nProof.\n  symmetry.\n  apply group_hom_composition_assoc.\nQed.\nNext Obligation.\nProof.\n  apply group_hom_eq.\n  reflexivity.\nQed.\nNext Obligation.\nProof.\n  apply group_hom_eq.\n  reflexivity.\nQed.\n", "meta": {"author": "relrod", "repo": "ct", "sha": "abd8b0067e219ee4867f7136bdf1b35885224cb4", "save_path": "github-repos/coq/relrod-ct", "path": "github-repos/coq/relrod-ct/ct-abd8b0067e219ee4867f7136bdf1b35885224cb4/CT/Instance/Algebra/Grp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6631259142449469}}
{"text": "Require Import prosa.classic.util.all.\nRequire Import prosa.classic.model.arrival.basic.task prosa.classic.model.arrival.basic.job prosa.classic.model.arrival.basic.arrival_sequence\n               prosa.classic.model.schedule.uni.schedule prosa.classic.model.schedule.uni.response_time.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.\n\nModule Schedulability.\n\n  Import Job SporadicTaskset ArrivalSequence UniprocessorSchedule ResponseTime.\n\n  (* In this section, we define the notion of deadline miss. *)\n  Section DeadlineMisses.\n\n    Context {Job: eqType}.\n    Variable job_arrival: Job -> time.\n    Variable job_cost: Job -> time.\n    Variable job_deadline: Job -> time.    \n\n    Context {Task: eqType}.\n    Variable job_task: Job -> Task.\n\n    (* Consider any job arrival sequence... *)\n    Variable arr_seq: arrival_sequence Job.\n\n    (* ...and any uniprocessor schedule of these jobs. *)\n    Variable sched: schedule Job.\n\n    (* For simplicity, let's define some local names. *)\n    Let job_completed_by := completed_by job_cost sched.\n    Let response_time_bounded_by :=\n      is_response_time_bound_of_task job_arrival job_cost job_task arr_seq sched.\n\n    Section Definitions.\n\n      (* In this section, we define the notion of deadline miss for a job. *)\n      Section JobLevel.\n  \n         (* We say that a job j...*)\n        Variable j: Job.\n\n        (* ...misses no deadline if it completes by its absolute deadline.*)\n        Definition job_misses_no_deadline :=\n          job_completed_by j (job_arrival j + job_deadline j).\n          \n      End JobLevel.\n\n      (* Next, we define the notion of deadline miss for a task. *)\n      Section TaskLevel.\n\n        (* We say that a task tsk... *)\n        Variable tsk: Task.\n\n        (* ...misses no deadline if all of its jobs complete by their absolute deadline. *)\n        Definition task_misses_no_deadline :=\n          forall j,\n            arrives_in arr_seq j ->\n            job_task j = tsk ->\n            job_misses_no_deadline j.\n        \n      End TaskLevel.\n\n      (* Next, we define the notion of deadline miss for a task set. *)\n      Section TaskSetLevel.\n\n        (* We say that a task set ts... *)\n        Variable ts: seq Task.\n\n        (* ...misses no deadline if all of its tasks do not miss any deadlines. *)\n        Definition taskset_misses_no_deadline :=\n          forall tsk,\n            tsk \\in ts ->\n            task_misses_no_deadline tsk.\n        \n      End TaskSetLevel.\n      \n    End Definitions.\n\n    (* In this section, we prove some lemmas related to schedulability. *)\n    Section Lemmas.\n\n      Variable task_cost: Task -> time.\n      Variable task_deadline: Task -> time.\n\n      (* First, we infer schedulability from the response-time bounds of a task. *)\n      Section ResponseTimeIsBounded.\n\n        (* Assume that all jobs in the arrival sequence have the same deadline\n           as their tasks. *)\n        Hypothesis H_job_deadline_eq_task_deadline:\n          forall j,\n            arrives_in arr_seq j ->\n            job_deadline_eq_task_deadline task_deadline job_deadline job_task j.\n        \n        (* Also assume that jobs don't execute after completion. *)\n        Hypothesis H_completed_jobs_dont_execute: completed_jobs_dont_execute job_cost sched.\n\n        (* Let tsk be any task.*)\n        Variable tsk: Task.\n\n        (* If tsk has response-time bound R that is no larger than its deadline, ... *)\n        Variable R: time.\n        Hypothesis H_R_le_deadline: R <= task_deadline tsk.\n        Hypothesis H_response_time_bounded: response_time_bounded_by tsk R.\n\n        (* ...then tsk misses no deadline. *)\n        Lemma task_completes_before_deadline:\n          task_misses_no_deadline tsk.\n        Proof.\n          unfold valid_sporadic_job, valid_realtime_job in *.\n          intros j ARRj JOBtsk.\n          apply completion_monotonic with (t := job_arrival j + R);\n            last by apply H_response_time_bounded.\n          rewrite leq_add2l.\n          apply: (leq_trans H_R_le_deadline).\n            by rewrite H_job_deadline_eq_task_deadline // -JOBtsk leqnn.\n       Qed.\n\n     End ResponseTimeIsBounded.\n      \n   End Lemmas.\n\n  End DeadlineMisses.\n  \nEnd Schedulability.", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/classic/model/schedule/uni/schedulability.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938414, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6631259099436267}}
{"text": "Require Import CPidgin.Control.Functor.\nRequire Import CPidgin.Data.Maybe.\n\nModule MaybeFunctorLaws.\n\nImport Functor.\nImport Maybe.Maybe.\n\n(* Helper function to act as an id function. *)\nDefinition id' {A : Type} (x : A): A :=\n    x.\n\n(* Functor Law 1: Identity. *)\nLemma MaybeFunctorPreservesIdentityMorphisms:\n    forall (A : Type) (x : Maybe A),\n        id' <$> x = x.\nProof.\n    intros.\n    unfold fmap.\n    unfold maybeFunctor.\n    unfold id'.\n    destruct x.\n    trivial.\n    trivial.\nQed.\n\n(* Functor Law 2: Composition. *)\nLemma MaybeFunctorPreservesCompositionOfMorphisms:\n    forall (A B C : Type) (x : Maybe A) (f : A -> B) (g : B -> C),\n        (fun a => g (f a)) <$> x\n            = g <$> (f <$> x).\nProof.\n    intros.\n    unfold fmap.\n    unfold maybeFunctor.\n    destruct x.\n    trivial.\n    trivial.\nQed.\n\nEnd MaybeFunctorLaws.\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/MaybeFunctorLaws.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.6630414728478475}}
{"text": "From mathcomp Require Import ssreflect ssrfun seq ssrnat ssrbool.\nFrom mf Require Import all_mf.\nRequire Import FunctionalExtensionality ClassicalChoice ChoiceFacts.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection pointwise.\n  Context (I: Type).\n  Definition mf_ptw R T (f: R ->> T):= make_mf (fun rs ts =>\n    forall (i: I), f (rs i) (ts i)).\n\n  Lemma ptw_sur R T (f: R ->> T): f \\is_cototal -> (mf_ptw f) \\is_cototal.\n  Proof.\n    move => cotot ts.\n    have /choice [rs prp] := cotot.\n    exists (rs \\o_f ts) => i; exact/prp.\n  Qed.\n\n  Lemma ptw_sing R T (f: R ->> T):\n    f \\is_singlevalued -> (mf_ptw f) \\is_singlevalued.\n  Proof.\n    move => sing rs ts t's val val'.\n    apply/functional_extensionality => i.\n    exact/sing/val'/val.\n  Qed.\n\n  Definition ptw R T (f: R -> T) (rs: I -> R) i := f (rs i).\n  \n  Lemma ptw_comp R T (f: R -> T) rs: (ptw f rs) =1 f \\o_f rs.\n  Proof. done. Qed.\n\n  Lemma F2MF_ptw R T (f: R -> T):\n    mf_ptw (F2MF f) =~= F2MF (ptw f).\n  Proof.\n    move => rs ts /=; split => [prp | <-]//.\n    exact/functional_extensionality.\n  Qed.\n  \n  Definition ptw_op R S T (op: R -> S -> T) (rs: I -> R) (ss: I -> S) i:=\n    op (rs i) (ss i).\n\n  Lemma ptwA R (op: R -> R -> R): associative op -> associative (ptw_op op).\n  Proof.\n    by move => ass x y z; apply/functional_extensionality => n; apply/ass.\n  Qed.\n\n  Lemma ptwC R (op: R -> R -> R): commutative op -> commutative (ptw_op op).\n  Proof.\n    by move => ass x y; apply/functional_extensionality => n; apply/ass.\n  Qed.\n\n  Lemma ptwDl R (op op': R -> R -> R):\n    left_distributive op op' -> left_distributive (ptw_op op) (ptw_op op').\n  Proof.\n    by move => ass x y z; apply/functional_extensionality => n; apply/ass.\n  Qed.\n\n  Lemma ptwDr R (op op': R -> R -> R):\n    right_distributive op op' -> right_distributive (ptw_op op) (ptw_op op').\n  Proof.\n    by move => ass x y z; apply/functional_extensionality => n; apply/ass.\n  Qed.  \n  \n  Definition uncurry R S T (f: R -> S -> T) rs := f rs.1 rs.2.\nEnd pointwise.\nNotation ptwn_op := (@ptw_op nat).\nNotation ptwn := (@ptw nat).\n", "meta": {"author": "FlorianSteinberg", "repo": "metric", "sha": "b34f29091173ffe079b4d4b6eab21061b81a930c", "save_path": "github-repos/coq/FlorianSteinberg-metric", "path": "github-repos/coq/FlorianSteinberg-metric/metric-b34f29091173ffe079b4d4b6eab21061b81a930c/pointwise.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324587033253, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.663041449579127}}
{"text": "Require Import Coq.Strings.Ascii\n        Coq.Bool.Bool\n        Coq.Lists.List.\n\nRequire Export Coq.Vectors.Vector\n        Coq.omega.Omega\n        Coq.Strings.Ascii\n        Coq.Bool.Bool\n        Coq.Bool.Bvector\n        Coq.Lists.List.\n\nRequire Import Fiat.ADT\n        Fiat.ADTRefinement.GeneralBuildADTRefinements.\n\n\n(* A specification of what it means to choose a number that is not in a particular list *)\nDefinition notInList (ls : list nat) :=\n  {n : nat | ~In n ls}%comp.\n\nLtac refines := intros; repeat computes_to_econstructor; repeat computes_to_inv; subst.\nLtac arithmetic := intros;\n  repeat match goal with\n         | [ |- context[max ?a ?b] ] => let Heq := fresh \"Heq\" in\n                                        destruct (Max.max_spec a b) as [ [? Heq] | [? Heq] ];\n                                          rewrite Heq in *; clear Heq\n         end; omega.\n\n\n(* We can use a simple property to justify a decomposition of the original spec. *)\nTheorem notInList_decompose : forall ls,\n  refine (notInList ls) (upper <- {upper | forall n, In n ls -> upper >= n};\n                         {beyond | beyond > upper}).\nProof.\n  refines.\n  firstorder.\nQed.\n\n(* A simple traversal will find the maximum list element, which is a good upper bound. *)\nDefinition listMax := fold_right max 0.\n\n(* ...and we can prove it! *)\nTheorem listMax_upperBound : forall init ls,\n  forall n, In n ls -> fold_right max init ls >= n.\nProof.\n  induction ls; simpl; intuition.\n  arithmetic.\n  apply IHls in H0.\n  arithmetic.\nQed.\n\n(* Now we restate that result as a computation refinement. *)\nTheorem listMax_refines : forall ls,\n  refine {upper | forall n, In n ls -> upper >= n} (ret (listMax ls)).\nProof.\n  refines.\n  apply listMax_upperBound.\nQed.\n\n(* An easy way to find a number higher than another: add 1! *)\nTheorem increment_refines : forall n,\n  refine {higher | higher > n} (ret (n + 1)).\nProof.\n  refines.\n  arithmetic.\nQed.\n\nLtac begin := eexists; intro; set_evars.\n\nLtac monad_simpl := autosetoid_rewrite with refine_monad;\n                   try simplify_with_applied_monad_laws; simpl.\n\n(* Let's derive an efficient implementation. *)\n\nTheorem implementation : { f : list nat -> Comp nat | forall ls, refine (notInList ls) (f ls) }.\nProof.\n  begin.\n  rewrite notInList_decompose.\n  rewrite listMax_refines.\n  setoid_rewrite increment_refines. (* Different tactic here to let us rewrite under a binder! *)\n  monad_simpl.\n  finish honing.\nDefined.\n\n(* We can extract the program that we found as a standlone, executable Gallina term. *)\nDefinition impl := Eval simpl in proj1_sig implementation.\nPrint impl.\n\nEval compute in impl (1 :: 7 :: 8 :: 2 :: 13 :: 6 :: nil).\n", "meta": {"author": "PRECISE", "repo": "smedl-fiat-code", "sha": "0c382ae9aa40df08c982fe0659a09544c69dc479", "save_path": "github-repos/coq/PRECISE-smedl-fiat-code", "path": "github-repos/coq/PRECISE-smedl-fiat-code/smedl-fiat-code-0c382ae9aa40df08c982fe0659a09544c69dc479/fiat/src/Examples/Tutorial/NotInList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6630157269308458}}
{"text": "(** This file was originally written by Niels van der Weide and Dan Frumin.  *)\nRequire Import HoTT.\n\n(** We look at heterogeneous equality.\n    This is equality between inhabitants of different types.\n    We follow the paper 'Cubical Methods in SYnthetic Homotopy Theory.\n *)\n\n(** The first definition is via an inductive tyoe. *)\nInductive heq : forall {A B : Type} (p : A = B) (a : A) (b : B), Type :=\n| heq_refl : forall {A : Type} (a : A), heq idpath a a.\n\n(** The second definition uses path induction *)\nDefinition heq_pi {A B : Type} (p : A = B)\n  : A -> B -> Type\n  := match p with\n     | idpath => fun a b => a = b\n     end.\n\nSection equivalences.\n  (** Heterogenous equality can be understood as a homogeneous equality.\n      For that we need to coerce along the type equality.\n      This gives an equivalent definition.\n   *)\n  Definition heq_to_path_coe\n             {A B : Type}\n             {p : A = B}\n             {a : A} {b : B}\n             (q : heq p a b)\n    : transport idmap p a = b\n    := match q with\n       | heq_refl _ _ => idpath\n       end.\n\n  Definition path_coe_to_heq\n             {A B : Type}\n             {p : A = B}\n    : forall {a : A} {b : B} (q : transport idmap p a = b), heq p a b\n    := match p with\n       | idpath => fun a b q => transport (heq 1 a) q (heq_refl a)\n       end.\n\n  Global Instance heq_to_path_coeq\n         {A B : Type}\n         {p : A = B}\n         {a : A} {b : B}\n    : IsEquiv (heq_to_path_coe (A := A) (B := B) (p := p) (a := a) (b := b)).\n  Proof.\n    simple refine (isequiv_adjointify _ (@path_coe_to_heq A B p a b) _ _).\n    - intros x.\n      induction p, x ; reflexivity.\n    - intros x.\n      induction x ; reflexivity.\n  Defined.\n\n  (** Alternatively, we can coerce along the inverse of the type equality.\n      This gives an equivalent definition as well.\n   *)\n  Definition heq_to_path_coe_V\n             {A B : Type}\n             {p : A = B}\n             {a : A} {b : B}\n             (q : heq p a b)\n    : a = transport idmap p^ b\n    := match q with\n       | heq_refl _ _ => idpath\n       end.\n\n  Definition path_coe_V_to_heq\n             {A B : Type}\n             {p : A = B}\n    : forall {a : A} {b : B} (q : a = transport idmap p^ b), heq p a b\n    := match p with\n       | idpath => fun a b q => transport (heq 1 a) q (heq_refl a)\n       end.\n\n  Global Instance heq_to_path_coeq_V\n         {A B : Type}\n         {p : A = B}\n         {a : A} {b : B}\n    : IsEquiv (heq_to_path_coe_V (A := A) (B := B) (p := p) (a := a) (b := b)).\n  Proof.\n    simple refine (isequiv_adjointify _ (@path_coe_V_to_heq A B p a b) _ _).\n    - intros x.\n      induction p ; cbn in x ; induction x.\n      reflexivity.\n    - intros x.\n      induction x ; reflexivity.\n  Defined.\n\n  (** Lastly, the two definitions of heterogeneous equality given in the beginning, are equivalent.\n   *)\n  Definition heq_to_heq_pi\n             {A B : Type}\n             {p : A = B}\n             {a : A} {b : B}\n             (q : heq p a b)\n    : heq_pi p a b\n    := match q with\n       | heq_refl _ _ => idpath\n       end.\n\n  Definition heq_pi_to_heq\n             {A B : Type}\n             {p : A = B}\n    : forall {a : A} {b : B} (q : heq_pi p a b), heq p a b\n    := match p with\n       | idpath => fun a b q => transport (heq idpath a) q (heq_refl _)\n       end.\n\n  Global Instance heq_to_heq_pi_is_equiv\n             {A B : Type}\n             {p : A = B}\n             {a : A} {b : B}\n    : IsEquiv (heq_to_heq_pi (A := A) (B := B) (p := p) (a := a) (b := b)).\n  Proof.\n    simple refine (isequiv_adjointify _ (heq_pi_to_heq (A := A) (B := B) (p := p) (a := a) (b := b)) _ _).\n    - intros x.\n      induction p, x.\n      reflexivity.\n    - intros x.\n      induction x.\n      reflexivity.\n  Defined.\nEnd equivalences.", "meta": {"author": "kalfsvag", "repo": "group_completions", "sha": "cc65e902a68dbb6dc05315651dce3064704a9815", "save_path": "github-repos/coq/kalfsvag-group_completions", "path": "github-repos/coq/kalfsvag-group_completions/group_completions-cc65e902a68dbb6dc05315651dce3064704a9815/cquot/basics/heterogeneous_equality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6630157242677536}}
{"text": "(* \n  Autor(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\n(* * Solvability of finite multiset constraints FMsetC_SAT  *)\n\n(* \n  Problem:\n    Finite Multiset Constraint Solvability (FMsetC_SAT)\n\n  Finite multisets with one constant 0 and one unary constructor h.\n  A finite multiset A is represented by a list of its elements.\n  The element (h^n 0) is represented by the natural number n.\n\n  Constraints are of shape:\n    x ≐ [0]\n    x ≐ y ⊍ z\n    x ≐ h (y) \n\n  Constraint semantics:\n    φ(y ⊍ z) = φ(y) ++ φ(z)\n    φ(h (y)) = map h (φ(y))\n\n  FMsetC:\n    Given a list of constraints,\n    is there a valuation φ : nat -> list nat such that\n    for each constraint c we have\n      if c is x ≐ [0], then φ(x) ≡ [0]\n      if c is x ≐ y ⊍ z, then φ(x) ≡ φ(y) ++ φ(z)\n      if c is x ≐ h (y), then φ(x) ≡ map S (φ(y))\n    where ≡ is equality up to permutation?\n  \n  References:\n    [1] Paliath Narendran: Solving Linear Equations over Polynomial Semirings.\n      LICS 1996: 466-472, doi: 10.1109/LICS.1996.561463\n*)\n\nRequire Import PeanoNat List.\nImport ListNotations.\n\n(* list equality up to permutation *)\nDefinition mset_eq (A B: list nat) : Prop := \n  forall c, count_occ Nat.eq_dec A c = count_occ Nat.eq_dec B c.\nLocal Notation \"A ≡ B\" := (mset_eq A B) (at level 65).\n\n(* constraints *)\nInductive msetc : Set :=\n  | msetc_zero : nat -> msetc\n  | msetc_sum : nat -> nat -> nat -> msetc\n  | msetc_h : nat -> nat -> msetc.\n\n(* constraint semantics *)\nDefinition msetc_sem (φ: nat -> list nat) (c: msetc) :=\n  match c with\n    | msetc_zero x => φ x ≡ [0]\n    | msetc_sum x y z => φ x ≡ (φ y) ++ (φ z)\n    | msetc_h x y => φ x ≡ map S (φ y)\n  end.\n\n(* given a list l of constraints, \n  is there a valuation φ satisfying each constraint? *)\nDefinition FMsetC_SAT (l : list msetc) := exists φ, forall c, In c l -> msetc_sem φ c.\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/SetConstraints/FMsetC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6630157136153841}}
{"text": "Require Import Function.\nRequire Import Functor.\n\nClass Adjunction (L R : Type -> Type) := {\n    left_functor :> Functor L;\n    right_functor :> Functor R;\n\n    (** Adjoints *)\n    leftAdjoint : forall {A B : Type}, (L A -> B) -> A -> R B;\n\n    rightAdjoint : forall {A B : Type}, (A -> R B) -> L A -> B;\n\n    (** Laws/Properties *)\n\n    (** Adjoint Isomorphism *)\n\n    adjoint_bijection_1\n        : forall {A B : Type} (g : A -> R B) (a : A)\n        , (leftAdjoint (rightAdjoint g)) a = g a;\n\n    adjoint_bijection_2\n        : forall {A B : Type} (f : L A -> B) (la : L A)\n        , (rightAdjoint (leftAdjoint f)) la = f la;\n\n    (** Adjoint Naturality *)\n\n    adjoint_natural_1\n        : forall {A B C : Type} (f : L A -> B) (k : B -> C) (a : A)\n        , (leftAdjoint (compose k f)) a = fmap k (leftAdjoint f a);\n\n    adjoint_natural_2\n        : forall {A B C : Type} (f : L B -> C) (h : A -> B) (a : A)\n        , (leftAdjoint (compose f (fmap h))) a = (leftAdjoint f (h a));\n\n    adjoint_natural_3\n        : forall {A B C : Type} (g : B -> R C) (h : A -> B) (la : L A)\n        , (rightAdjoint (compose g h)) la = (rightAdjoint g (fmap h la));\n\n    adjoint_natural_4\n        : forall {A B C : Type} (g : A -> R B) (k : B -> C) (la : L A)\n        , rightAdjoint (compose (fmap k) g) la = k (rightAdjoint g la)\n}.\n\n(* unit, counit, join and duplicate *)\n\nDefinition adjoint_unit {F G : Type -> Type} {adjunction : Adjunction F G} {A : Type} : A -> G (F A) :=\n    leftAdjoint id.\n\nDefinition adjoint_counit {F G : Type -> Type} {adjunction : Adjunction F G} {B : Type} : F (G B) -> B :=\n    rightAdjoint id.\n\nDefinition adjoint_join {F G : Type -> Type} {adjunction : Adjunction F G} {A : Type} : G (F (G (F A))) -> G (F A) :=\n    fmap adjoint_counit.\n\nDefinition adjoint_duplicate {F G : Type -> Type} {adjunction : Adjunction F G} {A : Type} : F (G A) -> F (G (F (G A))) :=\n    fmap adjoint_unit.\n\n(* Theorems *)\n\nTheorem adjoint_bijection_1_pointfree\n        : forall (F G : Type -> Type) (A B : Type) (adjunction : Adjunction F G) (g : A -> G B)\n        , (leftAdjoint (rightAdjoint g)) = g.\nProof.\n    intros.\n    assert (forall (x : A), leftAdjoint (rightAdjoint g) x = g x).\n    intros.\n    apply adjoint_bijection_1.\n    apply extensional_equality in H.\n    assumption.\nQed.\n\nTheorem adjoint_bijection_2_pointfree\n        : forall (F G : Type -> Type) (adjunction : Adjunction F G) (A B : Type) (f : F A -> B)\n        , (rightAdjoint (leftAdjoint f)) = f.\nProof.\n    intros.\n    assert (forall (fa : F A), rightAdjoint (leftAdjoint f) fa = f fa).\n    intros.\n    apply adjoint_bijection_2.\n    apply extensional_equality in H.\n    assumption.\nQed.\n\nTheorem adjoint_natural_1_pointfree\n        : forall (F G : Type -> Type) (A B C : Type) (adjunction : Adjunction F G) (f : F A -> B) (k : B -> C)\n        , (leftAdjoint (compose k f)) = compose (fmap k) (leftAdjoint f).\nProof.\n    intros.\n    apply extensional_equality.\n    intros.\n    apply adjoint_natural_1.\nQed.\n\nTheorem adjoint_natural_2_pointfree\n    : forall (F G : Type -> Type) (A B C : Type) (adjunction : Adjunction F G) (f : F B -> C) (h : A -> B)\n    , (leftAdjoint (compose f (fmap h))) = compose (leftAdjoint f) h.\nProof.\n    intros.\n    apply extensional_equality.\n    intros.\n    unfold compose at 2.\n    apply adjoint_natural_2.\nQed.\n\nTheorem adjoint_natural_3_pointfree\n    : forall (F G : Type -> Type) (A B C : Type) (adjunction : Adjunction F G) (g : B -> G C) (h : A -> B)\n    , (rightAdjoint (compose g h)) = compose (rightAdjoint g) (fmap h).\nProof.\n    intros.\n    apply extensional_equality.\n    unfold compose at 2.\n    intros.\n    apply adjoint_natural_3.\nQed.\n\nTheorem adjoint_natural_4_pointfree\n    : forall (F G : Type -> Type) (A B C : Type) (adjunction : Adjunction F G) (g : A -> G B) (k : B -> C)\n    , rightAdjoint (compose (fmap k) g) = compose k (rightAdjoint g).\nProof.\n    intros.\n    apply extensional_equality.\n    intros.\n    unfold compose at 2.\n    apply adjoint_natural_4.\nQed.\n\nTheorem adjoint_unit_left_identity\n    : forall (F G : Type -> Type) (A : Type) (adjunction : Adjunction F G)\n    , compose adjoint_join adjoint_unit = @id (G (F A)).\nProof.\n    intros.\n    apply extensional_equality.\n    intros.\n    unfold id.\n    unfold compose.\n    unfold adjoint_join.\n    unfold adjoint_unit.\n    unfold adjoint_counit.\n    rewrite <- adjoint_natural_1.\n    rewrite -> compose_right_identity.\n    rewrite -> adjoint_bijection_1.\n    unfold id.\n    reflexivity.\nQed.\n\nTheorem adjoint_unit_right_identity\n    : forall (F G : Type -> Type) (A : Type) (adjunction : Adjunction F G)\n    , compose adjoint_join (fmap (fmap adjoint_unit)) = @id (G (F A)).\nProof.\n    intros.\n    apply extensional_equality.\n    intros.\n    unfold id.\n    unfold compose.\n    unfold adjoint_join.\n    rewrite -> functors_preserve_composition.\n    unfold adjoint_counit.\n    unfold adjoint_unit.\n    rewrite <- adjoint_natural_3_pointfree.\n    rewrite -> compose_left_identity.\n    rewrite -> adjoint_bijection_2_pointfree.\n    rewrite -> functor_id_law.\n    unfold id.\n    reflexivity.\nQed.\n\nLemma adjoint_counit_squared\n    : forall (F G : Type -> Type) (A : Type) (adjunction : Adjunction F G)\n    , compose adjoint_counit adjoint_counit = compose adjoint_counit (fmap (@adjoint_join F G adjunction A)).\nProof.\n    intros.\n    apply extensional_equality.\n    unfold adjoint_counit at 3.\n    unfold compose at 2.\n    intros.\n    rewrite <- adjoint_natural_3.\n    rewrite -> compose_left_identity.\n    unfold compose.\n    unfold adjoint_counit at 2.\n    assert (rightAdjoint (compose (fmap adjoint_counit) id) x = adjoint_counit (rightAdjoint id x)).\n    apply adjoint_natural_4.\n    rewrite <- H.\n    rewrite -> compose_right_identity.\n    unfold adjoint_join.\n    reflexivity.\nQed.\n\nTheorem adjoint_join_associative\n    : forall (F G : Type -> Type) (A : Type) (adjunction : Adjunction F G)\n    , compose adjoint_join (@adjoint_join F G adjunction (G (F A))) = compose adjoint_join ((compose fmap fmap) adjoint_join).\nProof.\n    intros.\n    apply extensional_equality.\n    intros.\n    unfold compose.\n    unfold adjoint_join at 3.\n    rewrite -> functors_preserve_composition.\n    unfold adjoint_join at 1.\n    unfold adjoint_join at 1.\n    rewrite -> functors_preserve_composition.\n    rewrite -> adjoint_counit_squared.\n    reflexivity.\nQed.\n", "meta": {"author": "domdere", "repo": "haskell-coq", "sha": "83c7ffec0fb78a246d350621ff5c76577916d417", "save_path": "github-repos/coq/domdere-haskell-coq", "path": "github-repos/coq/domdere-haskell-coq/haskell-coq-83c7ffec0fb78a246d350621ff5c76577916d417/src/classes/Adjunction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.663015712907098}}
{"text": "Require Import Init.Init.\nRequire Import Relation.Relation.\n\nDefinition binop (A R: J) := R ∈ (A ⨉ A) ↦ A.\nNotation   \"x +[ R ] y\"   := (R[⟨x, y⟩]).\n\nDefinition assoc (A R: J) := ∀ x, ∀ y, ∀ z, x ∈ A → y ∈ A → z ∈ A\n  → x +[R] y +[R] z = x +[R] (y +[R] z).\n\nDefinition identr (A R e: J) := e ∈ A ∧ ∀ x, x ∈ A → x +[R] e = x.\nDefinition identl (A R e: J) := e ∈ A ∧ ∀ x, x ∈ A → e +[R] x = x.\nDefinition ident  (A R e: J) := e ∈ A ∧ ∀ x, x ∈ A → x +[R] e = x ∧ e +[R] x = x.\n\nDefinition inver (A R e: J) := ∀ x, ∃ y, x ∈ A\n  → y ∈ A ∧ x +[R] y = e ∧ y +[R] x = e.\n\nDefinition commu (A R: J) := ∀ x, ∀ y, x ∈ A → y ∈ A → x +[R] y = y +[R] x.\n\nLemma ident_er: ∀ A, ∀ R, ∀ e, ident A R e → identr A R e.\nProof.\n  intros A R e [P1 P2].\n  split.\n  + apply P1.\n  + intros x P3.\n    apply (P2 _ P3).\nQed.\n\nLemma ident_el: ∀ A, ∀ R, ∀ e, ident A R e → identl A R e.\nProof.\n  intros A R e [P1 P2].\n  split.\n  + apply P1.\n  + intros x P3.\n    apply (P2 _ P3).\nQed.\n\nLemma binop_close: ∀ A, ∀ R, ∀ m, ∀ n, binop A R → m ∈ A → n ∈ A → m +[R] n ∈ A.\nProof.\n  intros A R m n P1 P2 P3.\n  apply (fval_codom _ _ _ _ P1).\n  apply (cp_i _ _ _ _ P2 P3).\nQed.\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/Structure/Binary_Op.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6630157089974849}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  zNil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nLemma append_assoc: forall l1 l2 l3, \n  append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\ninduction l1.\n  - simpl. intros. rewrite IHl1. reflexivity.\n  - reflexivity.\nQed.\n\nLemma lem: forall l n, Cons n (rev l) = rev (append l (Cons n Nil)).\nProof.\nintros. induction l.\n  - simpl. rewrite <- IHl. reflexivity.\n  - reflexivity.\nQed.\n\nLemma lem2: forall l, rev (rev l) = l.\nProof.\ninduction l.\n  - simpl. rewrite <- lem. rewrite IHl. reflexivity.\n  - reflexivity.\nQed.\n\nLemma lem3: forall l, append l Nil = l.\nProof.\ninduction l.\n  - simpl. rewrite IHl. reflexivity.\n  - reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : lst) (y : lst), eq (rev (append (rev x) (rev y))) (append y x).\nProof.\n induction x.\n - intros. simpl. rewrite <- append_assoc. simpl. \n   rewrite lem.  rewrite IHx. lfind.  reflexivity. \nAdmitted.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal11_theorem0_56_append_assoc/goal11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6630157089974849}}
{"text": "Set Implicit Arguments.\n\nRequire Import ZArith List Bool MSets.\n\nDefinition node := positive.\n\nModule mset := MSetAVL.Make Positive_as_OT.\n\nNotation node_set := mset.t.\n\nPrint mset. (*Functions over sets!*)\n\nDefinition add := Pos.add.\n\nDefinition node_eqb := Pos.eqb.\n\nLemma node_eqb_eq :\n  forall x y : node,\n    node_eqb x y = true <-> x = y.\nProof.\n  intros x y; unfold node_eqb.\n  apply Pos.eqb_eq.\nQed.\n\nLemma node_eqb_refl :\n  forall x,\n    node_eqb x x = true.\nProof.\n  intros x; unfold node_eqb.\n  apply Pos.eqb_refl.\nQed.  \n\nLemma node_eqbP :\n  forall x y : node,\n    reflect (x = y) (node_eqb x y).\nProof.\n  intros.\n  destruct (node_eqb x y) eqn:H.\n  rewrite node_eqb_eq in H. constructor; auto.\n  constructor; intros H2; rewrite H2, node_eqb_refl in H.\n  congruence.\nQed.  \n\n(** Undirected Graphs *)\nInductive tgraph : Type :=\n|Leaf : tgraph\n|tNode : node -> node_set -> tgraph -> tgraph -> tgraph.\n\n \n\n\nInductive graph : Type :=\n| Empty : graph\n| Node :\n    node -> (** this node's id *)\n    node_set -> (** its neighbors *)\n    graph -> (** the rest of the graph *)\n    graph.\nCheck graph.\nLocal Open Scope positive_scope.\nRequire Import MSets.MSetInterface.\n\nNotation \"[ ]\" := mset.empty.\n\nNotation \"[ elt0 , .. , eltn ]\" := (mset.add elt0 .. (mset.add eltn (mset.empty )) .. ) (at level 60, right associativity).\n\nExample RefSet: node_set :=\n  mset.add 4( mset.add 5 ( mset.add 4 mset.empty)).\n\nCompute mset.elements RefSet.\nPrint RefSet.\nCheck mset.empty.\n\nCompute mset.exists_ (fun y  =>  Pos.eqb y 4) RefSet. \n\nExample ex1 : graph :=\n  Node 1 ([2,  3])\n       (Node 2 ([3])\n             (Node 3 [] Empty)).\n\nExample tree1 : tgraph :=\n  tNode 1 ([2,3]) Leaf (tNode 2 ([1]) Leaf (tNode 3 [] Leaf Leaf)).\n\nExample ex2 : graph :=\n  Node 3 ([2,1])\n       (Node 2 ([1])\n             (Node 1 ([5])\n                   (Node 5 [] Empty))).\n\n(** Return the adjacency list associated by graph g\n    with node x. *)\nFixpoint adj_of (x : node) (g : graph) : node_set :=\n  match g with\n  | Empty => mset.empty\n  | Node y adj g' =>\n    if node_eqb x y then  adj\n    else adj_of x g'\n  end.\n\nCompute mset.elements (adj_of 3 ex2).\n\n(** Return all neighbors in g of node x. *)\nDefinition nodeset_contains (x : node) (s : node_set) :=\n  mset.mem x s.\n\nLemma nodelist_containsP :\n  forall (x : node) (s : node_set),\n    reflect (mset.In x s) (nodeset_contains x s).\nProof.\n  intros.\n  apply iff_reflect.\n  unfold nodeset_contains.\n  symmetry.\n  apply mset.mem_spec.\nQed.\n\nFixpoint neighbors_of (x : node) (g : graph) : node_set:=\n  match g with\n  | Empty => mset.empty\n  | Node y adj g' =>\n    if node_eqb x y then  mset.union adj (neighbors_of x g')\n    else if nodeset_contains x adj then mset.add y (neighbors_of x g')\n         else neighbors_of x g'\n  end.\n\nDefinition is_neighbor (x y : node) (g : graph) : bool :=\n  nodeset_contains x (neighbors_of y g).\n\n\nFixpoint tgraph_contains (x : node) (g : tgraph) : bool :=\n  match g with\n  |Leaf =>  false\n  |tNode x' adj lgraph rgraph => if node_eqb x x' then true\n                                else orb (tgraph_contains x lgraph) (tgraph_contains x rgraph)\n  end.\n\nFixpoint graph_contains (x : node) (g : graph) : bool :=\n  match g with\n  | Empty => false\n  | Node y adj g' =>\n    if node_eqb x y then true\n    else graph_contains x g'\n  end.\n\nInductive graph_Contains : node -> graph ->  Prop :=\n| gc_inst : forall x g l, graph_Contains x (Node x l g) \n| gc_subg : forall x g, graph_Contains x g ->\n          forall y l, graph_Contains x (Node y l g).\n\nLemma graph_containsP : forall x g,\n  reflect (graph_Contains x g) (graph_contains x g).\nProof.\n  intros x g.\n  induction g.\n  constructor.\n  intros h.\n  inversion h.\n  simpl.\n  case_eq (node_eqb x n);\n  intros h.\n  apply node_eqb_eq in h.\n  subst.\n  constructor.\n  constructor.\n  case_eq (graph_contains x g);\n  intros h1.\n  apply ReflectT.\n  apply gc_subg.\n  destruct IHg; auto.\n  inversion h1.\n  constructor.\n  intros h2.\n  inversion h2; subst.\n  rewrite node_eqb_refl in h.\n  inversion h.\n  apply reflect_iff in IHg.\n  apply IHg in H1.\n  rewrite H1 in h1.\n  inversion h1.\nQed.\n\nInductive is_Neighbor : node -> node -> graph -> Prop :=\n| IN_inl : forall x y l g, mset.In y l -> is_Neighbor x y (Node x l g)\n| IN_inr : forall x y l g, mset.In x l -> is_Neighbor x y (Node y l g)\n| IN_subg : forall x y g, is_Neighbor x y g ->\n              forall z l, is_Neighbor x y (Node z l g).\n\nLemma is_Neighbor_symm x y g :\n  is_Neighbor x y g -> is_Neighbor y x g.\nProof.\n  induction g; intros h;\n  inversion h; subst;\n  constructor; auto.\nQed.\n\nLemma is_NeighborP : forall x y g,\n  reflect (is_Neighbor x y g) (is_neighbor x y g).\nProof.\n  intros x y g.\n  induction g.\n  constructor.\n  intros h.\n  inversion h.\n  apply iff_reflect.\n  split; intros h.\n  inversion h; subst.\n  {\n    unfold is_neighbor.\n    apply (reflect_iff (mset.In n (neighbors_of y (Node n t g)))).\n    apply nodelist_containsP.\n    unfold neighbors_of.\n    destruct node_eqb;\n    fold neighbors_of.\n    apply mset.union_spec.\n    \n    right.\n    unfold neighbors_of.\n    admit.\n  (*   apply (reflect_iff (In y l) (nodelist_contains y l)) in  H2. *)\n  (*   rewrite H2. simpl; left; auto. *)\n  (*   apply nodelist_containsP. *)\n  (* } *)\n  (* { *)\n    admit.\n  }\n  {\n    admit.\n  }\n  {\n    admit. \n  }\nAdmitted.\n\nInductive graph_ok : graph -> Prop :=\n| EmptyOk : graph_ok Empty\n| NodeOk :\n    forall (x : node) (adj : node_set) (g : graph),\n      graph_contains x g = false ->\n      mset.for_all (fun y => graph_contains y g) adj = true -> (** No self-loops! *)\n      graph_ok g ->\n      graph_ok (Node x adj g).\n\nCompute mset.elements ([1, 1, 2]).\n\n(** A so-called \"smart constructor\" for \"Node\". \n    We enforce the following two properties: \n      1) \"x\" is not already in the graph; \n      2) every node in \"adj\" is in the graph. *)\nDefinition add_node (x : node) (adj : node_set) (g : graph) : graph :=\n  if negb (graph_contains x g)\n          && negb (nodeset_contains x adj)\n          && mset.for_all (fun y => graph_contains y g) adj\n  then Node x adj g\n  else g.\n\nLemma add_node_ok :\n  forall x adj g,\n    graph_ok g ->\n    graph_ok (add_node x adj g).\nProof.\n  intros x adj g H.\n  unfold add_node.\n  destruct (negb (graph_contains x g)) eqn:H3;\n  destruct (negb (nodeset_contains x adj)) eqn:H4;\n  destruct (mset.for_all (fun y : mset.elt => graph_contains y g) adj) eqn:H0; auto. simpl.\n  apply NodeOk; auto.\n  apply negb_true_iff. auto.\nQed.\n\nLemma ex1_graph_ok : graph_ok ex1.\nProof.\n  unfold ex1; repeat (constructor; auto).\n  (* apply NodeOk. auto. *)\n  (* apply NodeOk; auto. *)\n  (* apply NodeOk; auto. *)\n  (* apply EmptyOk. *)\nQed.  \n\nLemma msetfilter_property :\n  forall (s : node_set) (f : mset.elt -> bool),\n    mset.for_all f ( mset.filter f s) = true.\nProof.\n  intros s f.\n  rewrite mset.for_all_spec.\n  unfold mset.For_all.\n  intros x H0.\n  unfold mset.for_all.\n  rewrite mset.filter_spec in H0.\n  destruct H0 as [_ H0].\n  auto. unfold respectful;\n  unfold Proper; intros; apply f_equal; auto.\n  unfold respectful;\n  unfold Proper; intros; apply f_equal; auto.\nQed.\n\nDefinition remove (x : node) (adj : node_set) : node_set :=\n  mset.filter (fun z => negb (node_eqb x z)) adj.\n\nLemma remove_union :\n  forall x s1 s2,\n    remove x (mset.union s1 s2) = mset.union (remove x s1) (remove x s2).\nProof.\nAdmitted.\n\nFixpoint remove_node (x : node) (g : graph) : graph :=\n  match g with\n  | Empty => Empty\n  | Node y adj g' =>\n    if node_eqb x y then remove_node x g'\n    else Node y (remove x adj) (remove_node x g')\n  end.\nCompute remove 1 [].\nLemma remove_node_neighbors_of :\n  forall x y g,\n    x <> y -> \n    neighbors_of y (remove_node x g) = remove x (neighbors_of y g).\nProof.\n  intros x y g H.\nAdmitted.  \n  \n  \n\n  \n(* Old proof for my reference while I go through. *)\n(*   intros x y g H; induction g; auto. *)\n(*   simpl.  *)\n(*   destruct (node_eqb x n) eqn:H2. *)\n(*   { rewrite node_eqb_eq in H2; subst n. *)\n(*     destruct (node_eqb y x) eqn:H3. *)\n(*     { rewrite node_eqb_eq in H3; subst y. *)\n(*       exfalso; apply H; auto. } *)\n(*     rewrite IHg. *)\n(*     destruct (nodelist_contains _ _); auto. *)\n(*     simpl. rewrite node_eqb_refl. auto. } *)\n(*   destruct (node_eqb y n) eqn:H3. *)\n(*   { simpl; rewrite H3; auto. *)\n(*     rewrite IHg, remove_app; auto. } *)\n(*   simpl. rewrite H3. *)\n(*   destruct (nodelist_containsP y (remove x l)). *)\n(*   { destruct (nodelist_containsP y l). *)\n(*     simpl. rewrite H2. simpl. rewrite IHg. auto. *)\n(*     destruct (nodelist_containsP y l). congruence. *)\n(*     destruct (nodelist_containsP y (remove x l)); [|congruence]. *)\n(*     apply In_remove_weaken in i; contradiction. } *)\n(*   destruct (nodelist_containsP y l); auto. *)\n(*   simpl. rewrite H2. simpl. rewrite IHg. *)\n(*   exfalso. apply H. apply not_In_remove_eq in n0; auto. *)\n(* Qed.     *)\n\nLemma remove_node_contains :\n  forall x y g,\n    x <> y -> \n    graph_contains y (remove_node x g) = graph_contains y g.\nProof.\n  intros x y g H; induction g; auto.\n  simpl.\n  destruct (node_eqb x n) eqn:H2.\n  { rewrite node_eqb_eq in H2; subst n.\n    destruct (node_eqb y x) eqn:H2.\n    { rewrite node_eqb_eq in H2; subst y.\n      exfalso; apply H; auto. }\n    auto. }\n  destruct (node_eqb y n) eqn:H3.\n  rewrite node_eqb_eq in H3; subst n.\n  simpl. rewrite node_eqb_refl; auto.\n  simpl. rewrite H3. auto.\nQed.  \n\n(* Lemma remove_NoDup x l : *)\n(*   NoDup l -> *)\n(*   NoDup (removeL x l). *)\n(* Proof. *)\n(*   induction l; auto. *)\n(*   inversion 1; subst. *)\n(*   simpl. destruct (negb _). constructor; auto. *)\n(*   intros H4. apply In_remove_weaken in H4; contradiction. *)\n(*   auto. *)\n(* Qed. *)\n\nLemma In_remove_weaken :\n  forall x y (s : node_set),\n  mset.In y (remove x s) -> mset.In y s.\nProof.\n  intros.\n  unfold remove in H.\n  apply mset.filter_spec in H.\n  destruct H. auto.\n  unfold respectful; unfold Proper; auto;\n  intros. f_equal. rewrite H1. auto.\nQed.\n  \nLemma In_remove_eq :\n  forall x y (s : node_set),\n  mset.In y (remove x s) -> x <> y.\nProof.\n  intros.\n  unfold remove in H.\n  apply mset.filter_spec in H.\n  destruct H. unfold node_eqb in H0.\n  apply Pos.eqb_neq.\n  apply negb_true_iff in H0. auto.\n  unfold respectful. unfold Proper; auto.\n  intros. f_equal. rewrite H1. auto.\nQed.\n\nLemma remove_node_ok :\n  forall x g,\n    graph_ok g ->\n    graph_ok (remove_node x g).\nProof.\n  intros x g H.\n  induction g.\n  { simpl; auto. }\n  simpl.\n  destruct (node_eqb x n) eqn:H2.\n  { rewrite node_eqb_eq in H2.\n    subst n.\n    inversion H; subst; auto. }\n  apply NodeOk.\n  { inversion H; subst.\n    rewrite remove_node_contains; auto.\n    intros H3; subst x. rewrite node_eqb_refl in H2. congruence. }\n  { inversion H; subst.\n    specialize (IHg H6). \n    apply mset.for_all_spec.\n    unfold respectful.\n    unfold Proper.\n    intros. f_equal. auto.\n    rewrite mset.for_all_spec in H5.\n    unfold mset.For_all.\n    intros.\n    rewrite remove_node_contains.\n    unfold mset.For_all in H5.\n    apply H5. apply  In_remove_weaken in H0. auto.\n    apply In_remove_eq in H0. auto.\n    unfold respectful.\n    unfold Proper.\n    intros. f_equal. auto.\n  }\n  inversion H. auto.\nQed.  \n\nInductive path (g : graph) : node -> node -> list node -> Prop :=\n| start : forall x, graph_Contains x g -> path g x x (x::nil)\n| step  : forall x y z l,\n            graph_Contains x g ->\n            path g y z (y::l) ->\n            is_Neighbor x y g ->\n              path g x z (x::y::l).\n\nLemma path_ex1 : path ex1 3 1 (3::2::1::nil).\nProof.\n  apply step.\n  do 2 apply gc_subg.\n  apply gc_inst.\n  apply step.\n  apply gc_subg.\n  apply gc_inst.\n  apply start.\n  apply gc_inst.\n  apply IN_inr.\n  apply mset.mem_spec. (*might want to find out how to do this a different way*)\n  unfold mset.mem.\n  simpl. auto.\n  apply IN_subg.\n  apply IN_inr.\n  apply mset.mem_spec; auto.\nQed.\n\nInductive independent_Set : list node -> graph -> Prop :=\n| IS_nil : forall g, independent_Set nil g\n| IS_cons : forall x l g,\n              graph_Contains x g ->\n              independent_Set l g ->\n              (forall y, In y l -> ~ is_Neighbor x y g) ->\n                independent_Set (x :: l) g.\n\nFixpoint vertices (g : graph) : list node :=\n  match g with\n  |Empty => nil\n  |Node n adj g' => n :: vertices g'\n  end.\n\nFixpoint edges (g : graph) : list (node * node) :=\n  match g with\n  |Empty => nil\n  |Node n adj g' => app (map (fun (elem : node) => (n, elem)) (mset.elements adj)) (edges g')\n  end.\n\nFixpoint isSortedG (g : graph) : bool :=\n  match g with\n    |Empty => true\n    |Node x adj g' => match g' with\n                     |Empty => true\n                     |Node n adj1 g'' =>  (Pos.ltb x n) && (isSortedG g')(*if negb (Pos.ltb x n) then isSortedG g'\n                                        else false*)\n                     end\n  end.\n\n(** Other potential operators/predicates/definitions: \n    - definition of paths from x <-> y\n    - does such a path exist between x <-> y? \n    - graph union \n    - set of vertices \n    - set of edges \n    - induced graph for a given set of vertices \n    - graph isomorphism (predicate over a labeling from \n      one graph to the other)\n    - definitions of independent sets, maximal independent sets, etc. \n\n    Other possible projects: \n    - Is there a graph invariant that implies: \n      \"graph isomorphism implies syntactic equality\"?\n    - Abstract interface over \"inductive graphs\", together with \n      associated induction principle, plus faster implementation\n *)", "meta": {"author": "gstew5", "repo": "coq-tutorial-summer2016", "sha": "a68f81725388326f953a94c9143176075a90fe9e", "save_path": "github-repos/coq/gstew5-coq-tutorial-summer2016", "path": "github-repos/coq/gstew5-coq-tutorial-summer2016/coq-tutorial-summer2016-a68f81725388326f953a94c9143176075a90fe9e/graphs_mset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017536, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6630157024247787}}
{"text": "Require Import XR_Rsqr.\nRequire Import XR_Rdiv.\nRequire Import XR_R0.\nRequire Import XR_Rmult_assoc.\nRequire Import XR_Rmult_eq_compat_l.\nRequire Import XR_Rmult_eq_compat_r.\nRequire Import XR_Rinv_mult_distr.\n\nLocal Open Scope R_scope.\n\nLemma Rsqr_div : forall x y:R, y <> R0 -> Rsqr (x / y) = Rsqr x / Rsqr y.\nProof.\n  intros x y h.\n  unfold Rsqr.\n  unfold Rdiv.\n  repeat rewrite Rmult_assoc.\n  apply Rmult_eq_compat_l.\n  rewrite Rinv_mult_distr.\n  {\n    repeat rewrite <- Rmult_assoc.\n    apply Rmult_eq_compat_r.\n    rewrite Rmult_comm.\n    reflexivity.\n  }\n  { exact h. }\n  { exact h. }\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_div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6630156997616863}}
{"text": "(* summations on a ring *)\n(* I also made SRsummation.v for sommations in a semiring (not having\n   opposite) which is more general; normally, this Rsummation.v should\n   disappear one day *)\n\nRequire Import Utf8 Arith.\nImport List.\nRequire Import Misc deprecat_Ring2.\n\nFixpoint summation_aux {α} {r : ring_op α} b len g :=\n  match len with\n  | O => 0%Rng\n  | S len₁ => (g b + summation_aux (S b) len₁ g)%Rng\n  end.\n\nDefinition summation {α} {r : ring_op α} b e g := summation_aux b (S e - b) g.\n\n(* the notation Σ have different implentations for historical reasons;\n   here with \"summation\", but elsewhere with \"fold_left\"; I'd like to\n   change that, but it is not so simple to make it work *)\nNotation \"'Σ' ( i = b , e ) , g\" := (summation b e (λ i, (g)))\n  (at level 45, i at level 0, b at level 60, e at level 60) : ring_scope.\n(*\nNotation \"'Σ' ( i = b , e ) , g\" :=\n  (fold_left (λ c i, c + g) (seq b (S e - b)) 0)%Rng\n  (at level 45, i at level 0, b at level 60, e at level 60) : ring_scope.\n*)\n\nTheorem fold_left_rng_add_fun_from_0 {A} {ro : ring_op A} {rp : ring_prop} :\n  ∀ a l (f : nat → _),\n  (fold_left (λ c i, c + f i) l a =\n   a + fold_left (λ c i, c + f i) l 0)%Rng.\nProof.\nintros.\nrevert a.\ninduction l as [| x l]; intros; [ symmetry; apply rng_add_0_r | cbn ].\nrewrite IHl; symmetry; rewrite IHl.\nrewrite rng_add_0_l.\napply rng_add_assoc.\nQed.\n\nTheorem fold_left_is_summation {A} {ro : ring_op A} {rp : ring_prop} :\n  ∀ b e g,\n  (fold_left (λ c i, c + g i) (seq b (S e - b)) 0 =\n   summation b e g)%Rng.\nProof.\nintros.\nunfold summation.\nremember (S e - b) as len.\nclear Heqlen.\nrevert g b.\ninduction len; intros; [ easy | cbn ].\nrewrite fold_left_rng_add_fun_from_0.\nrewrite IHlen.\nnow rewrite rng_add_0_l.\nQed.\n\nSection theorems_summation.\n\nContext {α : Type}.\nContext {ro : ring_op α}.\nContext {rp : ring_prop}.\n\nOpen Scope nat_scope.\n\nTheorem summation_aux_compat : ∀ g h b₁ b₂ len,\n  (∀ i, 0 ≤ i < len → (g (b₁ + i)%nat = h (b₂ + i)%nat)%Rng)\n  → (summation_aux b₁ len g = summation_aux b₂ len h)%Rng.\nProof.\nintros g h b₁ b₂ len Hgh.\nrevert b₁ b₂ Hgh.\ninduction len; intros; [ reflexivity | simpl ].\nrewrite (IHlen _ (S b₂)).\n apply rng_add_compat_r.\n assert (0 ≤ 0 < S len) as H.\n  split; [ reflexivity | apply Nat.lt_0_succ ].\n\n  apply Hgh in H.\n  do 2 rewrite Nat.add_0_r in H; assumption.\n\n intros i Hi.\n do 2 rewrite Nat.add_succ_l, <- Nat.add_succ_r.\n apply Hgh.\n split; [ apply Nat.le_0_l | idtac ].\n apply lt_n_S.\n destruct Hi; assumption.\nQed.\n\nTheorem summation_compat : ∀ g h b k,\n  (∀ i, b ≤ i ≤ k → (g i = h i)%Rng)\n  → (Σ (i = b, k), g i = Σ (i = b, k), h i)%Rng.\nProof.\nintros g h b k Hgh.\napply summation_aux_compat.\nintros i (_, Hi).\napply Hgh.\nsplit; [ apply Nat.le_add_r | idtac ].\napply Nat.lt_add_lt_sub_r, le_S_n in Hi.\nrewrite Nat.add_comm; assumption.\nQed.\n\nTheorem summation_mul_comm : ∀ g h b k,\n  (Σ (i = b, k), g i * h i\n   = Σ (i = b, k), h i * g i)%Rng.\nProof.\nintros g h b len.\napply summation_compat; intros i Hi.\napply rng_mul_comm.\nQed.\n\nTheorem all_0_summation_aux_0 : ∀ g b len,\n  (∀ i, (b ≤ i < b + len) → (g i = 0)%Rng)\n  → (summation_aux b len (λ i, g i) = 0)%Rng.\nProof.\nintros g b len H.\nrevert b H.\ninduction len; intros; [ reflexivity | simpl ].\nrewrite H; [ idtac | split; auto ].\n rewrite rng_add_0_l, IHlen; [ reflexivity | idtac ].\n intros i (Hbi, Hib); apply H.\n rewrite Nat.add_succ_r, <- Nat.add_succ_l.\n split; [ apply Nat.lt_le_incl; auto | auto ].\n\n rewrite Nat.add_succ_r.\n apply le_n_S, le_plus_l.\nQed.\n\nTheorem all_0_summation_0 : ∀ g i₁ i₂,\n  (∀ i, i₁ ≤ i ≤ i₂ → (g i = 0)%Rng)\n  → (Σ (i = i₁, i₂), g i = 0)%Rng.\nProof.\nintros g i₁ i₂ H.\napply all_0_summation_aux_0.\nintros i (H₁, H₂).\napply H.\nsplit; [ assumption | idtac ].\ndestruct (le_dec i₁ (S i₂)) as [H₃| H₃].\n rewrite Nat.add_sub_assoc in H₂; auto.\n rewrite minus_plus in H₂.\n apply le_S_n; auto.\n\n apply not_le_minus_0 in H₃.\n rewrite H₃, Nat.add_0_r in H₂.\n apply Nat.nle_gt in H₂; contradiction.\nQed.\n\nTheorem summation_aux_succ_last : ∀ g b len,\n  (summation_aux b (S len) g =\n   summation_aux b len g + g (b + len)%nat)%Rng.\nProof.\nintros g b len.\nrevert b.\ninduction len; intros.\n simpl.\n rewrite rng_add_0_l, rng_add_0_r, Nat.add_0_r.\n reflexivity.\n\n remember (S len) as x; simpl; subst x.\n rewrite IHlen.\n simpl.\n rewrite rng_add_assoc, Nat.add_succ_r.\n reflexivity.\nQed.\n\nTheorem summation_aux_rtl : ∀ g b len,\n  (summation_aux b len g =\n   summation_aux b len (λ i, g (b + len - 1 + b - i)%nat))%Rng.\nProof.\nintros g b len.\nrevert g b.\ninduction len; intros; [ reflexivity | idtac ].\nremember (S len) as x.\nrewrite Heqx in |- * at 1.\nsimpl; subst x.\nrewrite IHlen.\nrewrite summation_aux_succ_last.\nrewrite Nat.add_succ_l, Nat_sub_succ_1.\ndo 2 rewrite Nat.add_succ_r; rewrite Nat_sub_succ_1.\nrewrite Nat.add_sub_swap, Nat.sub_diag; auto.\nrewrite rng_add_comm.\napply rng_add_compat_r, summation_aux_compat.\nintros; reflexivity.\nQed.\n\nTheorem summation_rtl : ∀ g b k,\n  (Σ (i = b, k), g i = Σ (i = b, k), g (k + b - i)%nat)%Rng.\nProof.\nintros g b k.\nunfold summation.\nrewrite summation_aux_rtl.\napply summation_aux_compat; intros i (Hi, Hikb).\ndestruct b; simpl.\n rewrite Nat.sub_0_r; reflexivity.\n\n rewrite Nat.sub_0_r.\n simpl in Hikb.\n eapply Nat.le_lt_trans in Hikb; eauto .\n apply lt_O_minus_lt, Nat.lt_le_incl in Hikb.\n remember (b + (k - b))%nat as x eqn:H .\n rewrite Nat.add_sub_assoc in H; auto.\n rewrite Nat.add_sub_swap in H; auto.\n rewrite Nat.sub_diag in H; subst x; reflexivity.\nQed.\n\nTheorem summation_aux_mul_swap : ∀ a g b len,\n  (summation_aux b len (λ i, a * g i) =\n   a * summation_aux b len g)%Rng.\nProof.\nintros a g b len; revert b.\ninduction len; intros; simpl.\n rewrite rng_mul_0_r; reflexivity.\n\n rewrite IHlen, rng_mul_add_distr_l.\n reflexivity.\nQed.\n\nTheorem summation_aux_summation_aux_mul_swap : ∀ g₁ g₂ g₃ b₁ b₂ len,\n  (summation_aux b₁ len\n     (λ i, summation_aux b₂ (g₁ i) (λ j, g₂ i * g₃ i j))\n   = summation_aux b₁ len\n       (λ i, g₂ i * summation_aux b₂ (g₁ i) (λ j, g₃ i j)))%Rng.\nProof.\nintros g₁ g₂ g₃ b₁ b₂ len.\nrevert b₁ b₂.\ninduction len; intros; [ reflexivity | simpl ].\nrewrite IHlen.\napply rng_add_compat_r.\napply summation_aux_mul_swap.\nQed.\n\nTheorem summation_summation_mul_swap : ∀ g₁ g₂ g₃ k,\n  (Σ (i = 0, k), (Σ (j = 0, g₁ i), g₂ i * g₃ i j)\n   = Σ (i = 0, k), g₂ i * Σ (j = 0, g₁ i), g₃ i j)%Rng.\nProof.\nintros g₁ g₂ g₃ k.\napply summation_aux_summation_aux_mul_swap.\nQed.\n\nTheorem summation_only_one_non_0 : ∀ g b v k,\n  (b ≤ v ≤ k)\n  → (∀ i, (b ≤ i ≤ k) → (i ≠ v) → (g i = 0)%Rng)\n    → (Σ (i = b, k), g i = g v)%Rng.\nProof.\nintros g b v k (Hbv, Hvk) Hi.\nunfold summation.\nrewrite Nat.sub_succ_l; [ idtac | etransitivity; eassumption ].\nremember (k - b) as len.\nreplace k with (b + len) in * .\n clear k Heqlen.\n revert b v Hbv Hvk Hi.\n induction len; intros.\n  simpl.\n  rewrite rng_add_0_r.\n  replace b with v ; [ reflexivity | idtac ].\n  rewrite Nat.add_0_r in Hvk.\n  apply Nat.le_antisymm; assumption.\n\n  remember (S len) as x; simpl; subst x.\n  destruct (eq_nat_dec b v) as [H₁| H₁].\n   subst b.\n   rewrite all_0_summation_aux_0.\n    rewrite rng_add_0_r; reflexivity.\n\n    intros j (Hvj, Hjv).\n    simpl in Hjv.\n    apply le_S_n in Hjv.\n    apply Hi; [ split; auto; apply Nat.lt_le_incl; auto | idtac ].\n    intros H; subst j.\n    revert Hvj; apply Nat.nle_succ_diag_l.\n\n   rewrite Nat.add_succ_r, <- Nat.add_succ_l in Hvk.\n   rewrite Hi; auto.\n    rewrite rng_add_0_l.\n    apply IHlen; auto; [ apply Nat_le_neq_lt; auto | idtac ].\n    intros j (Hvj, Hjvl) Hjv.\n    rewrite Nat.add_succ_l, <- Nat.add_succ_r in Hjvl.\n    apply Hi; auto; split; auto.\n    apply Nat.lt_le_incl; auto.\n\n    split; auto.\n    apply Nat.le_sub_le_add_l.\n    rewrite Nat.sub_diag.\n    apply Nat.le_0_l.\n\n subst len.\n eapply Nat.le_trans in Hvk; eauto .\n rewrite Nat.add_sub_assoc; auto.\n rewrite Nat.add_comm.\n apply Nat.add_sub.\nQed.\n\nTheorem summation_shift : ∀ b g k,\n  b ≤ k\n  → (Σ (i = b, k), g i =\n     Σ (i = 0, k - b), g (b + i)%nat)%Rng.\nProof.\nintros b g k Hbk.\nunfold summation.\nrewrite Nat.sub_0_r.\nrewrite Nat.sub_succ_l; [ idtac | assumption ].\napply summation_aux_compat; intros j Hj.\nreflexivity.\nQed.\n\nTheorem summation_summation_shift : ∀ g k,\n  (Σ (i = 0, k), (Σ (j = i, k), g i j) =\n   Σ (i = 0, k), Σ (j = 0, k - i), g i (i + j)%nat)%Rng.\nProof.\nintros g k.\napply summation_compat; intros i Hi.\nunfold summation.\nrewrite Nat.sub_0_r.\nrewrite Nat.sub_succ_l; [ idtac | destruct Hi; assumption ].\napply summation_aux_compat; intros j Hj.\nrewrite Nat.add_0_l; reflexivity.\nQed.\n\nTheorem summation_only_one : ∀ g n, (Σ (i = n, n), g i = g n)%Rng.\nProof.\nintros g n.\nunfold summation.\nrewrite Nat.sub_succ_l; [ idtac | reflexivity ].\nrewrite Nat.sub_diag; simpl.\nrewrite rng_add_0_r; reflexivity.\nQed.\n\nTheorem summation_split_last : ∀ g b k,\n  (b ≤ S k)\n  → (Σ (i = b, S k), g i = Σ (i = b, k), g i + g (S k))%Rng.\nProof.\nintros g b k Hbk.\nunfold summation.\nrewrite Nat.sub_succ_l; [ idtac | assumption ].\nrewrite summation_aux_succ_last.\nrewrite Nat.add_sub_assoc; [ idtac | assumption ].\nrewrite Nat.add_comm, Nat.add_sub.\nreflexivity.\nQed.\n\nTheorem summation_aux_succ_first : ∀ g b len,\n  summation_aux b (S len) g = (g b + summation_aux (S b) len g)%Rng.\nProof. reflexivity. Qed.\n\nTheorem summation_split_first : ∀ g b k,\n  b ≤ k\n  → (Σ (i = b, k), g i)%Rng = (g b + Σ (i = S b, k), g i)%Rng.\nProof.\nintros g b k Hbk.\nunfold summation.\nrewrite Nat.sub_succ.\nrewrite <- summation_aux_succ_first.\nrewrite <- Nat.sub_succ_l; [ reflexivity | assumption ].\nQed.\n\nTheorem summation_empty : ∀ g b k,\n  k < b → (Σ (i = b, k), g i = 0)%Rng.\nProof.\nintros * Hkb.\nunfold summation.\nnow replace (S k - b) with 0 by flia Hkb.\nQed.\n\nTheorem summation_split : ∀ j g b k,\n  b ≤ S j ≤ S k\n  → (Σ (i = b, k), g i = Σ (i = b, j), g i + Σ (i = j+1, k), g i)%Rng.\nProof.\nintros * (Hbj, Hjk).\nunfold summation.\nremember (S j - b) as len1 eqn:Hlen1.\nremember (S k - b) as len2 eqn:Hlen2.\nmove len2 before len1.\nreplace (S k - (j + 1)) with (len2 - len1) by flia Hlen1 Hlen2 Hbj.\nreplace (j + 1) with (b + len1) by flia Hlen1 Hbj.\nassert (Hll : len1 ≤ len2) by flia Hlen1 Hlen2 Hjk.\nclear - rp Hll.\nrevert b len2 Hll.\ninduction len1; intros. {\n  cbn.\n  now rewrite rng_add_0_l, Nat.add_0_r, Nat.sub_0_r.\n}\ncbn.\ndestruct len2; [ flia Hll | ].\napply Nat.succ_le_mono in Hll.\ncbn.\nrewrite IHlen1; [ | easy ].\nrewrite rng_add_assoc.\nnow rewrite Nat.add_succ_comm.\nQed.\n\nTheorem summation_add_distr : ∀ g h b k,\n  (Σ (i = b, k), (g i + h i) =\n   Σ (i = b, k), g i + Σ (i = b, k), h i)%Rng.\nProof.\nintros g h b k.\ndestruct (le_dec b k) as [Hbk| Hbk].\n revert b Hbk.\n induction k; intros.\n  destruct b.\n   do 3 rewrite summation_only_one; reflexivity.\n\n   unfold summation; simpl; rewrite rng_add_0_r; reflexivity.\n\n  rewrite summation_split_last; [ idtac | assumption ].\n  rewrite summation_split_last; [ idtac | assumption ].\n  rewrite summation_split_last; [ idtac | assumption ].\n  destruct (eq_nat_dec b (S k)) as [H₂| H₂].\n   subst b.\n   unfold summation; simpl.\n   rewrite Nat.sub_diag; simpl.\n   do 2 rewrite rng_add_0_l; rewrite rng_add_0_l.\n   reflexivity.\n\n   apply Nat_le_neq_lt in Hbk; [ idtac | assumption ].\n   apply Nat.succ_le_mono in Hbk.\n   rewrite IHk; [ idtac | assumption ].\n   do 2 rewrite <- rng_add_assoc.\n   apply rng_add_compat_l.\n   rewrite rng_add_comm.\n   rewrite <- rng_add_assoc.\n   apply rng_add_compat_l.\n   rewrite rng_add_comm.\n   reflexivity.\n\n unfold summation.\n apply Nat.nle_gt in Hbk.\n replace (S k - b) with O by flia Hbk; simpl.\n rewrite rng_add_0_r; reflexivity.\nQed.\n\nTheorem summation_summation_exch : ∀ g k,\n  (Σ (j = 0, k), (Σ (i = 0, j), g i j) =\n   Σ (i = 0, k), Σ (j = i, k), g i j)%Rng.\nProof.\nintros g k.\ninduction k; [ reflexivity | idtac ].\nrewrite summation_split_last; [ idtac | apply Nat.le_0_l ].\nrewrite summation_split_last; [ idtac | apply Nat.le_0_l ].\nrewrite summation_split_last; [ idtac | apply Nat.le_0_l ].\nrewrite IHk.\nrewrite summation_only_one.\nrewrite rng_add_assoc.\napply rng_add_compat_r.\nrewrite <- summation_add_distr.\napply summation_compat; intros i (_, Hi).\nrewrite summation_split_last; [ reflexivity | idtac ].\napply Nat.le_le_succ_r; assumption.\nQed.\n\nTheorem summation_aux_ub_add : ∀ g b k₁ k₂,\n  (summation_aux b (k₁ + k₂) g =\n   summation_aux b k₁ g + summation_aux (b + k₁) k₂ g)%Rng.\nProof.\nintros g b k₁ k₂.\nrevert b k₁.\ninduction k₂; intros.\n simpl.\n rewrite Nat.add_0_r, rng_add_0_r; reflexivity.\n\n rewrite Nat.add_succ_r, <- Nat.add_succ_l.\n rewrite IHk₂; simpl.\n rewrite <- Nat.add_succ_r.\n rewrite rng_add_assoc.\n apply rng_add_compat_r.\n clear k₂ IHk₂.\n revert b.\n induction k₁; intros; simpl.\n  rewrite Nat.add_0_r.\n  apply rng_add_comm.\n\n  rewrite <- rng_add_assoc.\n  rewrite IHk₁.\n  rewrite Nat.add_succ_r, <- Nat.add_succ_l; reflexivity.\nQed.\n\nTheorem summation_ub_add : ∀ g k₁ k₂,\n  (Σ (i = 0, k₁ + k₂), g i =\n   Σ (i = 0, k₁), g i + Σ (i = S k₁, k₁ + k₂), g i)%Rng.\nProof.\nintros g k₁ k₂.\nunfold summation.\ndo 2 rewrite Nat.sub_0_r.\nrewrite <- Nat.add_succ_l.\nrewrite summation_aux_ub_add; simpl.\nrewrite Nat.add_comm, Nat.add_sub; reflexivity.\nQed.\n\nTheorem summation_aux_mul_summation_aux_summation_aux : ∀ g k n,\n  (summation_aux 0 (S k * S n) g =\n   summation_aux 0 (S k)\n     (λ i, summation_aux 0 (S n) (λ j, g (i * S n + j)%nat)))%Rng.\nProof.\nintros g k n.\nrevert n; induction k; intros.\n simpl; rewrite Nat.add_0_r, rng_add_0_r; reflexivity.\n\n remember (S n) as x.\n remember (S k) as y.\n simpl; subst x y.\n rewrite Nat.add_comm.\n rewrite summation_aux_ub_add, IHk.\n symmetry; rewrite rng_add_comm.\n symmetry.\n rewrite summation_aux_succ_first.\n rewrite rng_add_add_swap, rng_add_comm.\n symmetry.\n replace (S k) with (k + 1)%nat by flia.\n rewrite summation_aux_ub_add.\n rewrite <- rng_add_assoc.\n apply rng_add_compat_l.\n simpl.\n rewrite rng_add_comm.\n apply rng_add_compat_l.\n symmetry; rewrite Nat.add_comm; simpl.\n rewrite Nat.add_0_r, rng_add_0_r.\n apply rng_add_compat_l.\n apply summation_aux_compat; intros i Hi; simpl.\n rewrite Nat.add_succ_r; reflexivity.\nQed.\n\nTheorem summation_mul_summation_summation : ∀ g n k,\n  (0 < n)%nat\n  → (0 < k)%nat\n    → (Σ (i = 0, k * n - 1), g i =\n       Σ (i = 0, k - 1), Σ (j = 0, n - 1), g (i * n + j)%nat)%Rng.\nProof.\nintros g n k Hn Hk.\nunfold summation.\ndo 2 rewrite Nat.sub_0_r.\ndestruct n; [ exfalso; revert Hn; apply Nat.lt_irrefl | clear Hn ].\ndestruct k; [ exfalso; revert Hk; apply Nat.lt_irrefl | clear Hk ].\nrewrite Nat.sub_succ, Nat.sub_0_r.\nrewrite <- Nat.sub_succ_l, Nat.sub_succ, Nat.sub_0_r.\n rewrite summation_aux_mul_summation_aux_summation_aux.\n apply summation_aux_compat; intros i Hi.\n rewrite Nat.sub_succ, Nat.sub_0_r, Nat.sub_0_r.\n reflexivity.\n\n simpl; apply le_n_S, Nat.le_0_l.\nQed.\n\nTheorem inserted_0_summation : ∀ g h k n,\n  n ≠ O\n  → (∀ i, i mod n ≠ O → (g i = 0)%Rng)\n    → (∀ i, (g (n * i)%nat = h i)%Rng)\n      → (Σ (i = 0, k * n), g i = Σ (i = 0, k), h i)%Rng.\nProof.\nintros g h k n Hn Hf Hfg.\ndestruct k.\n rewrite Nat.mul_0_l.\n apply summation_compat; intros i (_, Hi).\n apply Nat.le_0_r in Hi; subst i.\n rewrite <- Hfg, Nat.mul_0_r; reflexivity.\n\n destruct n; [ exfalso; apply Hn; reflexivity | clear Hn ].\n replace (S k * S n)%nat with (S k * S n - 1 + 1)%nat.\n  rewrite summation_ub_add.\n  rewrite summation_mul_summation_summation; try apply Nat.lt_0_succ.\n  rewrite Nat_sub_succ_1, Nat.add_comm, summation_only_one.\n  simpl; do 2 rewrite Nat.sub_0_r.\n  symmetry.\n  rewrite <- Nat.add_1_r, summation_ub_add, Nat.add_1_r.\n  rewrite summation_only_one, rng_add_comm, <- Hfg.\n  symmetry.\n  rewrite rng_add_comm.\n  apply rng_add_compat; [ symmetry; rewrite Nat.mul_comm; reflexivity |  ].\n  apply summation_compat; intros i Hi.\n  rewrite summation_only_one_non_0 with (v := 0).\n   rewrite Nat.add_0_r, Nat.mul_comm; apply Hfg.\n\n   split; [ reflexivity | apply Nat.le_0_l ].\n\n   intros j Hjn Hj.\n   rewrite Hf; [ reflexivity |  ].\n   rewrite Nat.add_comm.\n   rewrite Nat.mod_add; [  | apply Nat.neq_succ_0 ].\n   intros H; apply Hj; clear Hj.\n   apply Nat.mod_divides in H; auto.\n   destruct H as (c, Hc).\n   destruct c.\n    rewrite Nat.mul_0_r in Hc; assumption.\n\n    rewrite Hc in Hjn.\n    rewrite Nat.mul_comm in Hjn.\n    simpl in Hjn.\n    destruct Hjn as (_, H).\n    apply Nat.nlt_ge in H.\n    exfalso; apply H.\n    apply le_n_S, Nat.le_add_r.\n\n  rewrite Nat.sub_add; [ apply eq_refl |  ].\n  simpl; apply le_n_S, Nat.le_0_l.\n\nQed.\n\nTheorem summation_add_add_sub : ∀ g b k n,\n  (Σ (i = b, k), g i = Σ (i = b + n, k + n), g (i - n)%nat)%Rng.\nProof.\nintros g b k n.\nunfold summation.\nreplace (S (k + n) - (b + n))%nat with (S k - b)%nat by flia.\napply summation_aux_compat.\nintros i Hi.\nreplace (b + n + i - n)%nat with (b + i)%nat by flia.\nreflexivity.\nQed.\n\nTheorem summation_succ_succ : ∀ b k g,\n  (Σ (i = S b, S k), g i = Σ (i = b, k), g (S i))%Rng.\nProof.\nintros b k g.\nunfold summation.\nrewrite Nat.sub_succ.\nremember (S k - b)%nat as len; clear Heqlen.\nrevert b.\ninduction len; intros; [ reflexivity | simpl ].\nrewrite IHlen; reflexivity.\nQed.\n\nTheorem rng_mul_summation_distr_l : ∀ a b e f,\n  (a * (Σ (i = b, e), f i) = Σ (i = b, e), a * f i)%Rng.\nProof.\nintros.\nunfold summation.\nremember (S e - b) as n eqn:Hn.\nrevert e a b Hn.\ninduction n; intros; [ apply rng_mul_0_r | cbn ].\nrewrite rng_mul_add_distr_l.\nrewrite (IHn e); [ easy | flia Hn ].\nQed.\n\nEnd theorems_summation.\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/old/deprecat_Rsummation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6629715029845162}}
{"text": "Set Implicit Arguments.\nRequire Import Relations List Sorted Arith.\nFrom hydras Require Import Restriction.\nRequire Import Lia.\n\n\n(* begin snippet tDef *)\nDefinition t (A:Type) := list (A * nat).\n(* end snippet tDef *)\n\n(* begin snippet AGiven *)\n\nSection A_given.\n\n  Variable A: Type.\n  Variable LtA : relation A.\n  (* end snippet AGiven *)\n\n  (* begin snippet lexpowerDef *)\n\n\n  Inductive lexpower: relation (t A) :=\n    lex1: forall a n l,  lexpower nil ((a,n)::l)\n  | lex2: forall a n p l l',  n < p -> lexpower ((a,n)::l) ((a,p)::l')\n  | lex3: forall a b n p l l',  LtA a b -> lexpower ((a,n)::l) ((b,p)::l')\n  | lex4: forall a n l l',  lexpower l l' -> lexpower ((a,n)::l) ((a,n)::l').\n  \nEnd A_given.\n(* end snippet lexpowerDef *)\n\n(* begin snippet notWfa:: no-out *)\nSection Counter_Example.\n  Let R := lexpower  lt.\n  Hypothesis Hwf : well_founded R.\n  \n  Definition seq (n:nat) := repeat (0,0) n ++ ((2,0)::nil).\n\n  Lemma decr_seq : forall n, R (seq (S n)) (seq n).\n  (* end snippet notWfa *)\n  Proof.\n    induction n.\n    -  constructor 3; auto with arith. \n    - constructor 4; apply IHn.\n  Qed. \n\n  Lemma not_acc : forall a b, R a b -> ~ Acc R a -> ~ Acc R b.\n  Proof.\n    intros a b H H0 H1; absurd (Acc R a); auto.\n  Qed.\n\n  (* begin snippet notWfb:: no-out *)\n  Let is_in_seq l := exists i, l = seq i.\n\n  Lemma is_in_seq_not_Acc : forall x,  is_in_seq x -> ~ Acc R x.\n  Proof. \n    intro x; pattern x; apply well_founded_ind with R; [assumption | ].\n    (* ... *)\n    (* end snippet notWfb *)\n    clear x; intros x IHx [i Hi]; subst x.\n    specialize (IHx _  (decr_seq i)); destruct IHx.\n    exists (S i);auto.\n    apply Hwf.\n  Qed. \n\n  (* begin snippet notWfc:: no-out *)\n  Lemma contrad: False.\n  Proof. \n    apply (@is_in_seq_not_Acc (seq 0)).\n    exists 0; trivial.\n    apply Hwf.\n  Qed. \n  \nEnd Counter_Example.\n(* end snippet notWfc *)\n\n(** Lists in normal form *)\n\n(* begin snippet lexnfDef *)\nDefinition lexnf {A: Type}(ltA : relation A) (l: t A)\n  := LocallySorted (Basics.flip ltA) (map fst l).\n(* end snippet lexnfDef *)\n\n(* begin snippet lexltDef *)\nDefinition lexlt {A}(ltA : relation A) :=\n  restrict (lexnf ltA) (lexpower ltA).\n(* end snippet lexltDef *)\n\n(* begin snippet bigProofa:: no-out *)\nSection ProofOfLexwf.\n  Variables (A: Type)\n            (ltA : relation A).\n  Hypothesis HwfA : well_founded ltA.\n  \n  #[local] Notation NF := (lexnf ltA).\n  #[local] Notation LT := (lexlt ltA).\n  (* end snippet bigProofa *)\n\n  (* begin snippet theStatement:: no-out *)\n  Theorem lexwf:\n    forall l,  NF l -> Acc LT l.\n  (* end snippet theStatement *)\n\n  (* begin snippet BadProof:: no-out *)\n  Proof.\n    induction l.\n    - split; destruct 1 as [_ [H1 _]]. inversion H1.\n      (* end snippet BadProof *)\n     (* begin snippet BadProofb:: -.h#A -.h#ltA -.h#A -.h#H  *)\n    - (* .no-out *) split; split; intros; destruct a as [a n].\n      (* end snippet BadProofb *)\n      (* begin snippet BadProofc *)\n  Abort.\n  (* end snippet BadProofc *)\n\n\n\n  (* begin snippet NFInv1:: no-out *)\n  Lemma NF_inv1 : forall a n l, NF ((a,n)::l) -> NF l.\n  (* end snippet NFInv1 *)\n  Proof.\n    destruct l.\n    - constructor.\n    - inversion_clear 1; assumption. \n  Qed. \n\n  (* begin snippet NFInv2:: no-out *)\n  Lemma NF_inv2 : forall a n b p l,  NF((a,n)::(b,p)::l) -> ltA b a.\n    (* end snippet NFInv2 *)\n    inversion_clear 1. assumption.\n  Qed.\n\n  (* begin snippet LTInv:: no-out *)\n  Lemma LT_inv : forall a n l l',\n      LT l' ((a,n)::l) ->\n      l' = nil \\/\n      (exists b p l'', l'= ((b,p)::l'') /\\ ltA b a) \\/\n      (exists l'',  l'=(a,n)::l'' /\\ LT l'' l) \\/\n      (exists  p l'', l'= ((a,p)::l'') /\\ p < n).\n  (* end snippet LTInv *)\n  Proof.\n    destruct 1.\n    destruct l'.\n    - now left.\n    - right.\n      destruct H0 as [H0 H1]; inversion H0. \n      + subst; right; right; exists n0, l'; split; auto. \n      + subst; left; exists a0, n0, l'; split; auto. \n      + subst; right;left; exists l'; split; auto. \n        split; auto. \n        eapply NF_inv1 ; eauto.\n        split; auto. \n        eapply NF_inv1 ; eauto.\n  Qed. \n\n  (* begin snippet AccsDef *)\n  Let Accs (a:A) := forall n l, NF ((a,n)::l) ->\n                                Acc LT ((a,n)::l).\n  (* end snippet AccsDef *)\n  \n  (* begin snippet AccNil:: no-out *)\n  Lemma Acc_nil : Acc LT nil.\n  Proof.  \n    split; destruct 1 as [_ [H _]]; inversion H.\n  Qed.\n  (* end snippet AccNil *)\n\n  (* begin snippet LAccsa *)\n  Lemma Accs_all: forall a:A, Accs a. (* .no-out *)\n  Proof. (* .no-out *)\n    unfold Accs; intros a; pattern a; \n      eapply  well_founded_induction with (R:= ltA); [assumption|];\n        clear a ; intros a  IHa.\n    (* end snippet LAccsa *)\n    \n    (** let us prepare an induction on l *)\n    (* begin snippet Laccsb:: no-out *)\n    assert (Hl: forall n l, NF ((a,n)::l) -> Acc LT l).\n    (* we skip the proof of Hl ... *)\n    (* end snippet Laccsb *)\n    {\n      destruct l. \n      - intro; apply Acc_nil.\n      - destruct p as [a0 n0]; intro H; apply IHa.\n        + now inversion_clear H. \n        + eapply NF_inv1; eauto.\n          (* begin snippet Laccsg:: no-in unfold -.h#* .h#IHa  .h#Hl *)\n    }\n    (* end snippet Laccsg *)\n    (* begin snippet Laccsc:: no-out  *)\n    intro n; pattern n; apply (well_founded_induction lt_wf).\n    (* end snippet Laccsc *)\n    (* begin snippet Laccsd:: -.h#A -.h#ltA -.h#Accs -.h#HwfA  *)\n    clear n; intros n Hn l H0.\n    (* end snippet Laccsd *)\n    \n    (* begin snippet Laccse:: -.h#A -.h#ltA -.h#HwfA -.h#Accs -.h#Hl  *)\n    assert (H1: Acc LT l) by (eapply Hl; eauto); \n      revert H0; pattern l; eapply Acc_ind with LT; [| eauto];\n        intros x0 H0 H2 H3.\n    (* end snippet Laccse *)\n    (* begin snippet Laccsf:: -.h#* .h#IHa .h#Hn .h#H0 .h#H2 .h#H2 .h#H3 .h#H4 *)\n    split; intros y H4. \n    destruct (LT_inv H4) as [H5 | [H6 | [H7 | H8]]]. (* .no-out *)\n    (* end snippet Laccsf *)\n    (* begin snippet case1:: -.h#* .h#H5  *)\n    + (* .no-in .unfold *) subst; apply Acc_nil. (* .no-out *)\n    (* end snippet case1 *)\n      \n    + (* begin snippet case2:: -.h#* .h#IHa .h#H7  .h#H4 *)\n      destruct H6 as [b [p [l'' [H6 H7]]]];  subst y. (* .no-in .unfold *)\n      apply IHa;  auto.\n      now destruct H4.\n    (* end snippet case2 *)\n    + (* begin snippet case3:: -.h#*  .h#H7  .h#H4 .h#H6 .h#H2 *)\n      destruct H7 as [l'' [H6 H7]];  subst. (* .no-in .unfold *)\n      apply H2; auto. \n      now destruct H4.\n    (* end snippet case3 *)        \n    + (* begin snippet case4:: -.h#*  .h#H7  .h#Hn .h#H4 .h#H6  *)\n      destruct H8 as [p [l'' [H6 H7]]]; subst; apply Hn; auto. \n      (* end snippet case4 *)   \n      now destruct H4.\n  Qed. \n\n(* begin snippet NFAcc:: no-out  *)\n  Lemma NF_Acc : forall l: t A, NF l -> Acc LT l.\n  Proof.\n    destruct l. \n    -  intro; apply Acc_nil.\n    -  destruct p; intro;  now apply Accs_all.\n  Qed.\n  \nEnd ProofOfLexwf.\n(* end snippet NFAcc  *)\n\n(* begin snippet lexwf:: no-out  *)\nTheorem lexwf {A}( ltA : relation A) :\n  well_founded ltA ->\n  forall l,  lexnf ltA l -> Acc (lexlt ltA) l. (* .no-out *)\nProof. apply NF_Acc.  Qed.\n(* end snippet lexwf  *)\n\n(* begin snippet Examples:: no-out *)\n\nExample Ex1 : lexpower  lt  ((2,7)::nil) ((3,0):: nil).\nProof.\n  constructor 3; auto with arith.\nQed.\n\nExample Ex2 : lexpower  lt  ((2,7)::(1,0)::(0,33)::nil) ((2,7)::(1,6)::nil).\nProof.\n  constructor 4.\n  constructor 2; auto with arith.\nQed.\n\nExample Ex3 : lexnf lt ((2,7)::(1,0)::(0,33)::nil).\nProof.\n  repeat constructor.\nQed.\n\n(* end snippet Examples *)\n\n(* begin snippet Impossibility1:: no-out *)\nSection Impossibility1.\n  Variable m : t nat -> nat.\n  Hypothesis mDecr : forall l l': t nat,  lexlt lt l l' -> m l <  m l'.\n\n  Definition iota (n:nat) := (0, n)::nil.\n  Let x := m ((1,0)::nil).\n  Let y := m (iota x).\n  \n  Fact F1 : y < x.\n  (* end snippet Impossibility1 *)\n  Proof.\n    apply mDecr; unfold x,iota; cbn.    \n    split.\n    - red; constructor. \n    - split. \n      + constructor; auto with arith. \n      + red; constructor. \n  Qed. \n(* begin snippet Impossibility1a:: no-out *)  \n  Fact F2 : x <= y.\n  (* end snippet Impossibility1a *)\n  Proof.\n    unfold y in *; clear y; induction x.\n    - auto with arith.\n    -  assert (m (iota n) < m (iota (S n))).  \n       { apply mDecr; unfold iota; simpl.\n         split.   \n         - constructor.\n         - split.\n           + constructor 2; auto with arith. \n           + constructor.\n       }\n       lia.\n  Qed.\n\n  (* begin snippet Impossibility1b:: no-out *)  \n  Lemma impossible_nat : False.\n  Proof.  generalize F1, F2; lia.   Qed. \n  \nEnd Impossibility1.\n(* end snippet Impossibility1b *)\n\n\n\n", "meta": {"author": "coq-community", "repo": "hydra-battles", "sha": "2d211e0b5030d5f77aaaf6366b01fc64ed998c61", "save_path": "github-repos/coq/coq-community-hydra-battles", "path": "github-repos/coq/coq-community-hydra-battles/hydra-battles-2d211e0b5030d5f77aaaf6366b01fc64ed998c61/theories/ordinals/solutions_exercises/MultisetWf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6629714927090307}}
{"text": "Require Export ProjectiveGeometry.Dev.projective_plane_axioms.\nRequire Export ProjectiveGeometry.Dev.fano_plane.\n\n(** Fano's plane **)\n(** also known as PG(2,2). **)\n\n(** To show that our axiom system is consistent we build a finite model. **)\n\nSection s_fanoPlaneModel.\n\n(** We define point and line by an inductive type representing the seven possibilities. **)\n(** We can not use directly the inductive type for a technical reason related to Coq's implementation. **)\n\nInductive ind_Point : Set := A | B | C | D | E | F | G.\nInductive ind_line : Set := ABF | BCD | CAE | ADG | BEG | CFG | DEF.\n\nDefinition Point : Set := ind_Point.\nDefinition Line : Set := ind_line.\n\nDefinition Incid_bool : Point -> Line -> bool := fun P l =>\n match P with\n| A =>\n    match l with\n    | ABF => true\n    | BCD => false\n    | CAE => true\n    | ADG => true\n    | BEG => false\n    | CFG => false\n    | DEF => false\n    end\n| B =>\n    match l with\n    | ABF => true\n    | BCD => true\n    | CAE => false\n    | ADG => false\n    | BEG => true\n    | CFG => false\n    | DEF => false\n    end\n| C =>\n    match l with\n    | ABF => false\n    | BCD => true\n    | CAE => true\n    | ADG => false\n    | BEG => false\n    | CFG => true\n    | DEF => false\n    end\n| D =>\n    match l with\n    | ABF => false\n    | BCD => true\n    | CAE => false\n    | ADG => true\n    | BEG => false\n    | CFG => false\n    | DEF => true\n    end\n| E =>\n    match l with\n    | ABF => false\n    | BCD => false\n    | CAE => true\n    | ADG => false\n    | BEG => true\n    | CFG => false\n    | DEF => true\n    end\n| F =>\n    match l with\n    | ABF => true\n    | BCD => false\n    | CAE => false\n    | ADG => false\n    | BEG => false\n    | CFG => true\n    | DEF => true\n    end\n| G =>\n    match l with\n    | ABF => false\n    | BCD => false\n    | CAE => false\n    | ADG => true\n    | BEG => true\n    | CFG => true\n    | DEF => false\n    end\nend.\n\nDefinition Incid : Point -> Line -> Prop := fun P L => (Incid_bool P L = true).\n\nHint Unfold Incid Incid_bool.\n\nLemma incid_dec : forall (A:Point) (l:Line), {Incid A l} + {~Incid A l}.\nProof.\nintros.\nunfold Incid.\nelim l;elim A0;unfold Incid_bool;simpl;auto;right;discriminate.\nQed.\n\nLtac solve_ex L := solve [exists L;auto].\n\n(** A tactic which tries all possible lines **)\nLtac solve_ex_l := first [solve_ex ABF\n     |  solve_ex BCD\n     |  solve_ex CAE\n     |  solve_ex ADG\n     |  solve_ex BEG\n     |  solve_ex CFG\n     |  solve_ex DEF\n ].\n\n(** A tactic which tries all possible points **)\nLtac solve_ex_p := first [\n        solve_ex A\n     |  solve_ex B\n     |  solve_ex C\n     |  solve_ex D\n     |  solve_ex E\n     |  solve_ex F\n     |  solve_ex G\n ].\n\n(** A1 : any two points lie on a unique line **) \nLemma a1_exist : forall ( A B :Point) ,{l:Line | Incid A l /\\ Incid B l}.\nProof.\nintros.\nelim A0;elim B0;solve_ex_l.\nQed.\n\nLemma degen_point: forall A:Point, forall P: Prop, ~A=A -> P.\nProof.\nintuition.\nQed.\n\nLemma degen_line: forall A:Line, forall P: Prop, A<>A -> P.\nProof.\nintuition.\nQed.\n\nLtac remove_degen := match goal with\n| H: ~ ?A=?A |- ?G => apply (degen_point A G H)\n| H: ?A<>?A |- ?G => apply (degen_line A G H)\nend.\n\nLemma uniqueness : forall A B :Point, forall l m : Line,\n Incid A l -> Incid B l  -> Incid A m -> Incid B m -> A=B\\/l=m.\nProof.\nintros P Q l m H1 H2 H3 H4.\ninduction P; induction Q; try (left;reflexivity);\ninduction l; try discriminate;\ninduction m; try discriminate; try (left; reflexivity) ; try (right; reflexivity); try remove_degen.\nQed.\n\nLemma a1_unique:forall (A B :Point)(l1 l2:Line), \n  ~A=B -> Incid A l1 -> Incid B l1 -> Incid A l2 -> Incid B l2 -> l1=l2.\nProof.\nintros X Y l1 l2 HXY H1 H2 H3 H4.\ninduction X;induction Y; try remove_degen;\ninduction l1;try discriminate; induction l2; discriminate || reflexivity.\nQed.\n\nLemma a2_unique : forall(l1 l2 :Line)(A B :Point), \n  ~l1=l2 -> Incid A l1 -> Incid A l2 -> Incid B l1 -> Incid B l2 -> A=B.\nProof.\nintros l1 l2 X Y H H1 H2 H3 H4.\n induction X;induction Y;try reflexivity;\n induction l1;try discriminate;\n induction l2;try discriminate;try remove_degen.\nQed.\n\n(** A2 : any two lines meet in a unique point **)\nLemma a2_exist : forall (l1 l2:Line), {A:Point | Incid A l1 /\\ Incid A l2}.\nProof.\nintros.\ninduction l1;induction l2;\nsolve_ex_p.\nQed.\n\n(** A3 : there exist four points with no three collinear **)\nLemma a3 : {A:Point & {B :Point & {C:Point & {D :Point |\n  (forall l :Line, ~A = B /\\ ~A = C /\\ ~A = D /\\ ~B = C /\\ ~B = D /\\ ~C = D /\\ \n    (Incid A l /\\ Incid B l -> ~Incid C l /\\ ~Incid D l)\n    /\\ (Incid A l /\\ Incid C l -> ~Incid B l /\\ ~Incid D l)\n    /\\  (Incid A l /\\ Incid D l -> ~Incid C l /\\ ~Incid B l)\n    /\\  (Incid C l /\\ Incid B l -> ~Incid A l /\\ ~Incid D l)\n    /\\ (Incid D l /\\ Incid B l -> ~Incid C l /\\ ~Incid A l)\n    /\\  (Incid C l /\\ Incid D l -> ~Incid B l /\\ ~Incid A l))}}}}.\nProof.\nexists A.\nexists B.\nexists C.\nexists G.\nintros.\nsplit.\nintuition;discriminate.\nelim l;unfold Incid, Incid_bool;intuition;discriminate.\nQed.\n\nInstance ObjectPointFano : ObjectPoint := {\nPoint := Point\n}.\n\nInstance ProjectiveStructureFano : ProjectiveStructure ObjectPointFano := {\nLine := Line;\nIncid := Incid;\nincid_dec := incid_dec\n}.\n\nInstance ProjectiveStructureLEFano : ProjectiveStructureLE ProjectiveStructureFano := {\na1_exist := a1_exist\n}.\n\nInstance ProjectiveStructureLEUFano : ProjectiveStructureLEU ProjectiveStructureLEFano := {\nuniqueness := uniqueness\n}.\n\nInstance PreProjectivePlaneFano : PreProjectivePlane ProjectiveStructureLEUFano := {\na2_exist := a2_exist\n}.\n\nInstance ProjectivePlaneFano : ProjectivePlane PreProjectivePlaneFano := {\na3 := a3\n}.\n\nEnd s_fanoPlaneModel.\n\n\nModule fano_plane_inst : fano_plane\n\nwith Definition Point:= Point\nwith Definition A:= A\nwith Definition B:= B\nwith Definition C:= C\nwith Definition D:= D\nwith Definition E:= E\nwith Definition F:= F\nwith Definition G := G\n\nwith Definition Line:= Line\n\nwith Definition ABF := ABF\nwith Definition BCD := BCD\nwith Definition CAE := CAE\nwith Definition ADG := ADG\nwith Definition BEG := BEG\nwith Definition CFG := CFG\nwith Definition DEF := DEF\nwith Definition Incid := Incid\n.\n\nDefinition Point:= Point.\n\nDefinition A:= A.\nDefinition B:= B.\nDefinition C:= C.\nDefinition D:= D.\nDefinition E:= E.\nDefinition F:= F.\nDefinition G := G.\n\nDefinition Line:= Line.\n\nDefinition ABF := ABF.\nDefinition BCD := BCD.\nDefinition CAE := CAE.\nDefinition ADG := ADG.\nDefinition BEG := BEG.\nDefinition CFG := CFG.\nDefinition DEF := DEF.\n\nDefinition Incid := Incid.\n\nLemma is_only_7_pts : forall P:Point, {P=A}+{P=B}+{P=C}+{P=D}+{P=E}+{P=F}+{P=G}.\nProof.\nintros.\nelim P;\nintuition.\nQed.\n\nLemma is_only_7_lines : forall P:Line, {P=ABF}+{P=BCD}+{P=CAE}+{P=ADG}+{P=BEG}+{P=CFG}+{P=DEF}.\nProof.\nintros.\nelim P;\nintuition.\nQed.\n\nDefinition is_fano_plane A B C D E F G ABF BCD CAE ADG BEG CFG DEF :=\n(~A=B /\\ ~A=C /\\ ~A=D /\\ ~A=E /\\ ~A=F /\\ ~A=G /\\\n~B=C /\\ ~B=D /\\ ~B=E /\\ ~B=F /\\ ~B=G /\\\n~C=D /\\ ~C=E /\\ ~C=F /\\ ~C=G /\\\n~D=E /\\ ~D=F /\\ ~D=G /\\\n~E=F /\\ ~E=G /\\\n~F=G) /\\\n(ABF<>BCD /\\ ABF <>CAE /\\ ABF <>ADG /\\ ABF<>BEG /\\ ABF<>CFG /\\ ABF<>DEF /\\ \nBCD<>CAE /\\ BCD<>ADG /\\ BCD<>BEG /\\ BCD<>CFG /\\ BCD<>DEF /\\\nCAE<>ADG /\\ CAE<>BEG /\\ CAE<>CFG /\\ CAE<>DEF /\\\nADG<>BEG /\\ ADG<>CFG /\\ADG<>DEF /\\\nBEG<>CFG /\\ BEG<>DEF /\\\nCFG<>DEF )/\\ \n\n( Incid A ABF /\\ Incid B ABF /\\ ~ Incid C ABF /\\ ~ Incid D ABF /\\ ~ Incid E ABF /\\ Incid F ABF /\\ ~ Incid G  ABF /\\\n ~ Incid A BCD /\\ Incid B BCD /\\ Incid C BCD /\\ Incid D BCD /\\ ~ Incid E BCD /\\ ~ Incid F BCD /\\ ~ Incid G  BCD /\\\n Incid A CAE /\\ ~ Incid B CAE /\\ Incid C CAE /\\ ~ Incid D CAE /\\ Incid E CAE /\\ ~ Incid F CAE /\\ ~ Incid G  CAE /\\\n Incid A ADG /\\ ~ Incid B ADG /\\ ~ Incid C ADG /\\ Incid D ADG /\\ ~ Incid E ADG /\\ ~ Incid F ADG /\\ Incid G  ADG /\\\n ~ Incid A BEG /\\ Incid B BEG /\\ ~ Incid C BEG /\\ ~ Incid D BEG /\\  Incid E BEG /\\ ~ Incid F BEG /\\ Incid G  BEG /\\\n ~ Incid A CFG /\\ ~ Incid B CFG /\\ Incid C CFG /\\ ~ Incid D CFG /\\ ~ Incid E CFG /\\ Incid F CFG /\\ Incid G  CFG /\\\n ~ Incid A DEF /\\ ~ Incid B DEF /\\ ~ Incid C DEF /\\ Incid D DEF /\\ Incid E DEF /\\ Incid F DEF /\\ ~ Incid G  DEF).\n\nLemma is_fano_plane_inst :  is_fano_plane A B C D E F G ABF BCD CAE ADG BEG CFG DEF.\nProof.\nunfold is_fano_plane.\nrepeat split; try discriminate.\nQed.\n\nEnd fano_plane_inst.\n\n\nModule Import Desargues := Desargues fano_plane_inst.\n\nDefinition on_line := fun A B C l => Incid A l /\\ Incid B l /\\ Incid C l.\nDefinition collinear A B C :=  exists l, Incid A l /\\ Incid B l /\\ Incid C l.\n\n\nTheorem Desargues_fano :  \nforall O P Q R P' Q' R' alpha beta gamma lP lQ lR lPQ lPR lQR lP'Q' lP'R' lQ'R',\n((on_line P Q gamma lPQ) /\\ (on_line P' Q' gamma lP'Q')) /\\\n((on_line P R beta lPR) /\\ (on_line P' R' beta lP'R')) /\\\n((on_line Q R alpha lQR) /\\ (on_line Q' R' alpha lQ'R')) /\\\n((on_line O P P' lP) /\\ (on_line O Q Q' lQ) /\\(on_line O R R' lR)) /\\ \n~collinear O P Q /\\  ~collinear O P R /\\ ~collinear O Q R /\\ \n~collinear P Q R /\\ ~collinear P' Q' R' /\\ ((P<>P')\\/(Q<>Q')\\/(R<>R')) ->\ncollinear alpha beta gamma.\nProof.\nintros.\nunfold on_line in *; decompose [and] H;clear H.\nassert (T:=Desargues.Desargues).\nunfold M2.collinear, M2.on_line in *.\nunfold fano_plane_inst.Incid,  fano_plane_inst.Line, fano_plane_inst.Point \nin *.\napply (T O P Q R P' Q' R' alpha beta gamma lP lQ lR lPQ lPR lQR lP'Q' lP'R' lQ'R').\nrepeat split;auto.\nQed.\n", "meta": {"author": "ProjectiveGeometry", "repo": "ProjectiveGeometry", "sha": "4f7f4e6c14580833c91fdef38d048259fb454b88", "save_path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry", "path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry/ProjectiveGeometry-4f7f4e6c14580833c91fdef38d048259fb454b88/Dev/fano_plane_model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6629714867804648}}
{"text": "(** * MoreCoq: More About Coq's Tactics *)\n\n\nRequire Export Poly.\n\n(** This chapter introduces several more proof strategies and\n    tactics that, together, allow us to prove theorems about the\n    functional programs we have been writing. In particular, we'll\n    reason about functions that work with natural numbers and lists.\n\n    In particular, we will see:\n    - how to use auxiliary lemmas, in both forwards and backwards reasoning;\n    - how to reason about data constructors, which are injective and disjoint;\n    - how to create a strong induction hypotheses (and when\n      strengthening is required); and\n    - how to reason by case analysis.\n *)\n\n(* ###################################################### *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    exactly the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n  (* At this point, we could finish with\n     \"[rewrite -> eq2. reflexivity.]\" as we have\n     done several times above. But we can achieve the\n     same effect in a single step by using the\n     [apply] tactic instead: *)\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** You may find it instructive to experiment with this proof\n    and see if there is a way to complete it using just [rewrite]\n    instead of [apply]. *)\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] binding some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex)  *)\n(** Complete the following proof without using [simpl]. *)\n\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 3 = true ->\n     oddb 4 = true.\nProof.\n  intros H H0.\n  apply H0.\nQed.\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal _exactly_ -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  simpl.\n  (* Here we cannot use [apply] directly *)\nAbort.\n\n(** In this case we can use the [symmetry] tactic, which switches the\n    left and right sides of an equality in the goal. *)\n\nTheorem silly3 : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  symmetry.\n  simpl. (* Actually, this [simpl] is unnecessary, since\n            [apply] will perform simplification first. *)\n  apply H.  Qed.\n\n(** **** Exercise: 3 stars (apply_exercise1)  *)\n(** Hint: you can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [SearchAbout] is\n    your friend. *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  intros.\n  induction l.\n    - rewrite H. symmetry. apply rev_involutive.\n    - simpl. symmetry. rewrite snoc_rev. rewrite H. apply rev_involutive.\nQed.\n(** **** Exercise: 1 star, optional (apply_rewrite)  *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  Are there situations where both can usefully be\n    applied?\n  (* FILL IN HERE *)\n*)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might\n    abstract it out as a lemma recording once and for all\n    the fact that equality is transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to\n    prove the above example.  However, to do this we need\n    a slight refinement of the [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  (* If we simply tell Coq [apply trans_eq] at this point,\n     it can tell (by matching the goal against the\n     conclusion of the lemma) that it should instantiate [X]\n     with [[nat]], [n] with [[a,b]], and [o] with [[e,f]].\n     However, the matching process doesn't determine an\n     instantiation for [m]: we have to supply one explicitly\n     by adding [with (m:=[c,d])] to the invocation of\n     [apply]. *)\n  apply trans_eq with (m:=[c;d]). apply eq1. apply eq2.   Qed.\n\n(**  Actually, we usually don't have to include the name [m]\n    in the [with] clause; Coq is often smart enough to\n    figure out which instantiation we're giving. We could\n    instead write: [apply trans_eq with [c,d]]. *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o).\nProof.\n  intros n m o p H H0.\n  apply trans_eq with m. apply H0. apply H.\nQed.\n\n(* ###################################################### *)\n(** * The [inversion] tactic *)\n\n(** Recall the definition of natural numbers:\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n    It is clear from this definition that every number has one of two\n    forms: either it is the constructor [O] or it is built by applying\n    the constructor [S] to another number.  But there is more here than\n    meets the eye: implicit in the definition (and in our informal\n    understanding of how datatype declarations work in other\n    programming languages) are two other facts:\n\n    - The constructor [S] is _injective_.  That is, the only way we can\n      have [S n = S m] is if [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n]. *)\n\n(** Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor is\n    injective and [nil] is different from every non-empty list.  For\n    booleans, [true] and [false] are unequal.  (Since neither [true]\n    nor [false] take any arguments, their injectivity is not an issue.) *)\n\n(** Coq provides a tactic called [inversion] that allows us to exploit\n    these principles in proofs.\n\n    The [inversion] tactic is used like this.  Suppose [H] is a\n    hypothesis in the context (or a previously proven lemma) of the\n    form\n      c a1 a2 ... an = d b1 b2 ... bm\n    for some constructors [c] and [d] and arguments [a1 ... an] and\n    [b1 ... bm].  Then [inversion H] instructs Coq to \"invert\" this\n    equality to extract the information it contains about these terms:\n\n    - If [c] and [d] are the same constructor, then we know, by the\n      injectivity of this constructor, that [a1 = b1], [a2 = b2],\n      etc.; [inversion H] adds these facts to the context, and tries\n      to use them to rewrite the goal.\n\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory.  That is, a false assumption has crept\n      into the context, and this means that any goal whatsoever is\n      provable!  In this case, [inversion H] marks the current goal as\n      completed and pops it off the goal stack. *)\n\n(** The [inversion] tactic is probably easier to understand by\n    seeing it in action than from general descriptions like the above.\n    Below you will find example theorems that demonstrate the use of\n    [inversion] and exercises to test your understanding. *)\n\nTheorem eq_add_S : forall (n m : nat),\n     S n = S m ->\n     n = m.\nProof.\n  intros n m eq. inversion eq. reflexivity.  Qed.\n\nTheorem silly4 : forall (n m : nat),\n     [n] = [m] ->\n     n = m.\nProof.\n  intros n o eq. inversion eq. reflexivity.  Qed.\n\n(** As a convenience, the [inversion] tactic can also\n    destruct equalities between complex values, binding\n    multiple variables as it goes. *)\n\nTheorem silly5 : forall (n m o : nat),\n     [n;m] = [o;o] ->\n     [n] = [m].\nProof.\n  intros n m o eq. inversion eq. reflexivity. Qed.\n\n(** **** Exercise: 1 star (sillyex1)  *)\nExample sillyex1 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = z :: j ->\n     y :: l = x :: j ->\n     x = y.\nProof.\n  intros X x y z l j H H0.\n  inversion H0.\n  reflexivity.\nQed.\n\nTheorem silly6 : forall (n : nat),\n     S n = O ->\n     2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. 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 H H0.\n  inversion H0.\n  inversion H.\nQed.\n\n(** While the injectivity of constructors allows us to reason\n    [forall (n m : nat), S n = S m -> n = m], the reverse direction of\n    the implication is an instance of a more general fact about\n    constructors and functions, which we will often find useful: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n    x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.\n\n\n(** **** Exercise: 2 stars, optional (practice)  *)\n(** A couple more nontrivial but not-too-complicated proofs to work\n    together in class, or for you to work as exercises. *)\n\n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  intros n H.\n  inversion H.\n  destruct n.\n  reflexivity. inversion H1.\nQed.\n\nTheorem beq_nat_0_r : forall n,\n   beq_nat n 0 = true -> n = 0.\nProof.\n  intros n H.\n  apply beq_nat_0_l.\n  destruct n. reflexivity. inversion H.\nQed.\n\n(* ###################################################### *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic [simpl in H] performs simplification in\n    the hypothesis named [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     beq_nat (S n) (S m) = b  ->\n     beq_nat n m = b.\nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, the tactic [apply L in H] matches some\n    conditional statement [L] (of the form [L1 -> L2], say) against a\n    hypothesis [H] in the context.  However, unlike ordinary\n    [apply] (which rewrites a goal matching [L2] into a subgoal [L1]),\n    [apply L in H] matches [H] against [L1] and, if successful,\n    replaces it with [L2].\n\n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\" -- from [L1 -> L2] and a hypothesis matching [L1], it\n    gives us a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\" -- it says that if we know [L1->L2] and we\n    are trying to prove [L2], it suffices to prove [L1].\n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\nTheorem silly3' : forall (n : nat),\n  (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->\n     true = beq_nat n 5  ->\n     true = beq_nat (S (S n)) 7.\nProof.\n  intros n eq H.\n  symmetry in H. apply eq in H. symmetry in H.\n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, Coq tends to favor backward reasoning, but in some\n    situations the forward style can be easier to use or to think\n    about.  *)\n\n(** **** Exercise: 3 stars (plus_n_n_injective)  *)\n(** Practice using \"in\" variants in this exercise. *)\n\nTheorem plus_n_n_injective : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n    (* Hint: use the plus_n_Sm lemma *)\n    - intros m H. SearchAbout nat. inversion H. destruct m.\n      + reflexivity.\n      + rewrite <- plus_n_Sm in H1.\n        rewrite H1.\nAdmitted.\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\n'\". inversion eq.\n  Case \"n = S n'\".\n    (* Notice that both the goal and the induction\n       hypothesis have changed: the goal asks us to prove\n       something more general (i.e., to prove the\n       statement for _every_ [m]), but the IH is\n       correspondingly more flexible, allowing us to\n       choose any [m] we like when we apply the IH.  *)\n    intros m eq.\n    (* Now we choose a particular [m] and introduce the\n       assumption that [double n = double m].  Since we\n       are doing a case analysis on [n], we need a case\n       analysis on [m] to keep the two \"in sync.\" *)\n    destruct m as [| m'].\n    SCase \"m = O\".\n      (* The 0 case is trivial *)\n      inversion eq.\n    SCase \"m = S m'\".\n      apply f_equal.\n      (* At this point, since we are in the second\n         branch of the [destruct m], the [m'] mentioned\n         in the context at this point is actually the\n         predecessor of the one we started out talking\n         about.  Since we are also in the [S] branch of\n         the induction, this is perfect: if we\n         instantiate the generic [m] in the IH with the\n         [m'] that we are talking about right now (this\n         instantiation is performed automatically by\n         [apply]), then [IHn'] gives us exactly what we\n         need to finish the proof. *)\n      apply IHn'. inversion eq. reflexivity. Qed.\n\n(** What this teaches us is that we need to be careful about using\n    induction to try to prove something too specific: If we're proving\n    a property of [n] and [m] by induction on [n], we may need to\n    leave [m] generic. *)\n\n(** The proof of this theorem (left as an exercise) has to be treated similarly: *)\n\n(** **** Exercise: 2 stars (beq_nat_true)  *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  induction n.\n  - destruct m.\n    + reflexivity.\n    + intros H. inversion H.\n  - intros. destruct m.\n    + inversion H.\n    + simpl in H. apply IHn in H. rewrite H. reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, advanced (beq_nat_true_informal)  *)\n(** Give a careful informal proof of [beq_nat_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** The strategy of doing fewer [intros] before an [induction] doesn't\n    always work directly; sometimes a little _rearrangement_ of\n    quantified variables is needed.  Suppose, for example, that we\n    wanted to prove [double_injective] by induction on [m] instead of\n    [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  Case \"m = O\". simpl. intros eq. destruct n as [| n'].\n    SCase \"n = O\". reflexivity.\n    SCase \"n = S n'\". inversion eq.\n  Case \"m = S m'\". intros eq. destruct n as [| n'].\n    SCase \"n = O\". inversion eq.\n    SCase \"n = S n'\".  apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (If we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce\n    [n] for us!)   *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    will work, but it's not nice: We don't want to have to mangle the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them -- we want to state them in the most clear and\n    natural way. *)\n\n(**  What we can do instead is to first introduce all the\n    quantified variables and then _re-generalize_ one or more of\n    them, taking them out of the context and putting them back at\n    the beginning of the goal.  The [generalize dependent] tactic\n    does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m.\n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  Case \"m = O\". simpl. intros n eq. destruct n as [| n'].\n    SCase \"n = O\". reflexivity.\n    SCase \"n = S n'\". inversion eq.\n  Case \"m = S m'\". intros n eq. destruct n as [| n'].\n    SCase \"n = O\". inversion eq.\n    SCase \"n = S n'\". apply f_equal.\n      apply IHm'. inversion eq. reflexivity. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n_Theorem_: For any nats [n] and [m], if [double n = double m], then\n  [n = m].\n\n_Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n  any [n], if [double n = double m] then [n = m].\n\n  - First, suppose [m = 0], and suppose [n] is a number such\n    that [double n = double m].  We must show that [n = 0].\n\n    Since [m = 0], by the definition of [double] we have [double n =\n    0].  There are two cases to consider for [n].  If [n = 0] we are\n    done, since this is what we wanted to show.  Otherwise, if [n = S\n    n'] for some [n'], we derive a contradiction: by the definition of\n    [double] we would have [double n = S (S (double n'))], but this\n    contradicts the assumption that [double n = 0].\n\n  - Otherwise, suppose [m = S m'] and that [n] is again a number such\n    that [double n = double m].  We must show that [n = S m'], with\n    the induction hypothesis that for every number [s], if [double s =\n    double m'] then [s = m'].\n\n    By the fact that [m = S m'] and the definition of [double], we\n    have [double n = S (S (double m'))].  There are two cases to\n    consider for [n].\n\n    If [n = 0], then by definition [double n = 0], a contradiction.\n    Thus, we may assume that [n = S n'] for some [n'], and again by\n    the definition of [double] we have [S (S (double n')) = S (S\n    (double m'))], which implies by inversion that [double n' = double\n    m'].\n\n    Instantiating the induction hypothesis with [n'] thus allows us to\n    conclude that [n' = m'], and it follows immediately that [S n' = S\n    m'].  Since [S n' = n] and [S m' = m], this is just what we wanted\n    to show. [] *)\n\n\n\n(** Here's another illustration of [inversion] and using an\n    appropriately general induction hypothesis.  This is a slightly\n    roundabout way of stating a fact that we have already proved\n    above.  The extra equalities force us to do a little more\n    equational reasoning and exercise some of the tactics we've seen\n    recently. *)\n\nTheorem length_snoc' : forall (X : Type) (v : X)\n                              (l : list X) (n : nat),\n     length l = n ->\n     length (snoc l v) = S n.\nProof.\n  intros X v l. induction l as [| v' l'].\n\n  Case \"l = []\".\n    intros n eq. rewrite <- eq. reflexivity.\n\n  Case \"l = v' :: l'\".\n    intros n eq. simpl. destruct n as [| n'].\n    SCase \"n = 0\". inversion eq.\n    SCase \"n = S n'\".\n      apply f_equal. apply IHl'. inversion eq. reflexivity. Qed.\n\n(** It might be tempting to start proving the above theorem\n    by introducing [n] and [eq] at the outset.  However, this leads\n    to an induction hypothesis that is not strong enough.  Compare\n    the above to the following (aborted) attempt: *)\n\nTheorem length_snoc_bad : forall (X : Type) (v : X)\n                              (l : list X) (n : nat),\n     length l = n ->\n     length (snoc l v) = S n.\nProof.\n  intros X v l n eq. induction l as [| v' l'].\n\n  Case \"l = []\".\n    rewrite <- eq. reflexivity.\n\n  Case \"l = v' :: l'\".\n    simpl. destruct n as [| n'].\n    SCase \"n = 0\". inversion eq.\n    SCase \"n = S n'\".\n      apply f_equal. Abort. (* apply IHl'. *) (* The IH doesn't apply! *)\n\n\n(** As in the double examples, the problem is that by\n    introducing [n] before doing induction on [l], the induction\n    hypothesis is specialized to one particular natural number, namely\n    [n].  In the induction case, however, we need to be able to use\n    the induction hypothesis on some other natural number [n'].\n    Retaining the more general form of the induction hypothesis thus\n    gives us more flexibility.\n\n    In general, a good rule of thumb is to make the induction hypothesis\n    as general as possible. *)\n\n(** **** Exercise: 3 stars (gen_dep_practice)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem index_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     index n l = None.\nProof.\n  intros n X l H.\n  generalize dependent n.\n  induction l as [|h t].\n    - intros. simpl. reflexivity.\n    - intros. simpl in H. destruct n.\n      + inversion H.\n      + inversion H. apply IHt in H1. apply IHt. rewrite <- pred_Sn. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, advanced, optional (index_after_last_informal)  *)\n(** Write an informal proof corresponding to your Coq proof\n    of [index_after_last]:\n\n     _Theorem_: For all sets [X], lists [l : list X], and numbers\n      [n], if [length l = n] then [index n l = None].\n\n     _Proof_:\n     (* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (gen_dep_practice_more)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem length_snoc''' : forall (n : nat) (X : Type)\n                              (v : X) (l : list X),\n     length l = n ->\n     length (snoc l v) = S n.\nProof.\n  intros n X v l.\n  generalize dependent n.\n  induction l.\n    - intros. simpl. rewrite <- H. simpl. reflexivity.\n    - intros. destruct n.\n      + inversion H.\n      + simpl in H. inversion H. rewrite H1. simpl. apply IHl in H1.\n        rewrite H1. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, optional (app_length_cons)  *)\n(** Prove this by induction on [l1], without using [app_length]\n    from [Lists]. *)\n\nLemma length_S: forall (X: Type) (x : X) (l: list X), length (x :: l) = S (length l).\nProof. intros. simpl. reflexivity. 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.\n  induction l1.\n    - intros. simpl. destruct l2.\n      + simpl. rewrite <- H. simpl. reflexivity.\n      + rewrite nil_app in H.\n        rewrite length_S in H. apply H.\n    - intros. simpl in H.\nAdmitted.\n\n(** **** Exercise: 4 stars, optional (app_length_twice)  *)\n(** Prove this by induction on [l], without using app_length. *)\n\nTheorem app_length_twice : forall (X:Type) (n:nat) (l:list X),\n     length l = n ->\n     length (l ++ l) = n + n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 3 stars, optional (double_induction)  *)\n(** Prove the following principle of induction over two naturals. *)\n\nTheorem double_induction: forall (P : nat -> nat -> Prop),\n  P 0 0 ->\n  (forall m, P m 0 -> P (S m) 0) ->\n  (forall n, P 0 n -> P 0 (S n)) ->\n  (forall m n, P m n -> P (S m) (S n)) ->\n  forall m n, P m n.\nProof.\n  intros P H H0 H1 H2.\n  generalize dependent H.\n  induction m as [|m'].\n    - intros. induction n.\n      + apply H.\n      + apply H1, IHn.\n    - intros. destruct n; [ apply H0 | apply H2]; apply IHm'.\nQed.\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.\n  unfold override. destruct (beq_nat k1 k2).\n    - reflexivity.\n    - destruct k2; reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, optional (combine_split)  *)\n(** Complete the proof below *)\n\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  induction l.\n    - intros. inversion H. reflexivity.\n    - destruct l1.\n      + intros.\nAdmitted.\n\n(** Sometimes, doing a [destruct] on a compound expression (a\n    non-variable) will erase information we need to complete a proof. *)\n(** For example, suppose\n    we define a function [sillyfun1] like this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** And suppose that we want to convince Coq of the rather\n    obvious observation that [sillyfun1 n] yields [true] only when [n]\n    is odd.  By analogy with the proofs we did with [sillyfun] above,\n    it is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAbort.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution peformed by [destruct] is too brutal -- it threw\n    away every occurrence of [beq_nat n 3], but we need to keep some\n    memory of this expression and how it was destructed, because we\n    need to be able to reason that since, in this branch of the case\n    analysis, [beq_nat n 3 = true], it must be that [n = 3], from\n    which it follows that [n] is odd.\n\n    What we would really like is to substitute away all existing\n    occurences of [beq_nat n 3], but at the same time add an equation\n    to the context that records which case we are in.  The [eqn:]\n    qualifier allows us to introduce such an equation (with whatever\n    name we choose). *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got stuck\n    above, except that the context contains an extra equality\n    assumption, which is exactly what we need to make progress. *)\n    Case \"e3 = true\". apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    Case \"e3 = false\".\n     (* When we come to the second equality test in the body of the\n       function we are reasoning about, we can use [eqn:] again in the\n       same way, allow us to finish the proof. *)\n      destruct (beq_nat n 5) eqn:Heqe5.\n        SCase \"e5 = true\".\n          apply beq_nat_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        SCase \"e5 = false\". inversion eq.  Qed.\n\n\n(** **** Exercise: 2 stars (destruct_eqn_practice)  *)\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  intros f b.\n  destruct (f b) eqn:H.\n    - destruct b.\n      + rewrite H. apply H.\n      + destruct (f true) eqn:H'.\n        * apply H'.\n        * rewrite H. reflexivity.\n    - destruct b.\n      + destruct (f false) eqn:H'.\n        * rewrite H. reflexivity.\n        * rewrite H'. reflexivity.\n      + rewrite H. apply H.\nQed.\n\nPrint bool_fn_applied_thrice.\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 H.\n  unfold override.\n  destruct (beq_nat k1 k2) eqn:HH.\n    - apply beq_nat_true in HH. rewrite <- HH, H. reflexivity.\n    - reflexivity.\nQed.\n\nPrint override_same.\n\n(* ################################################################## *)\n(** * Review *)\n\n(** We've now seen a bunch of Coq's fundamental tactics.  We'll\n    introduce a few more as we go along through the coming lectures,\n    and later in the course we'll introduce some more powerful\n    _automation_ tactics that make Coq do more of the low-level work\n    in many cases.  But basically we've got what we need to get work\n    done.\n\n    Here are the ones we've seen:\n\n      - [intros]:\n        move hypotheses/variables from goal to context\n\n      - [reflexivity]:\n        finish the proof (when the goal looks like [e = e])\n\n      - [apply]:\n        prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]:\n        apply a hypothesis, lemma, or constructor to a hypothesis in\n        the context (forward reasoning)\n\n      - [apply... with...]:\n        explicitly specify values for variables that cannot be\n        determined by pattern matching\n\n      - [simpl]:\n        simplify computations in the goal\n\n      - [simpl in H]:\n        ... or a hypothesis\n\n      - [rewrite]:\n        use an equality hypothesis (or lemma) to rewrite the goal\n\n      - [rewrite ... in H]:\n        ... or a hypothesis\n\n      - [symmetry]:\n        changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]:\n        changes a hypothesis of the form [t=u] into [u=t]\n\n      - [unfold]:\n        replace a defined constant by its right-hand side in the goal\n\n      - [unfold... in H]:\n        ... or a hypothesis\n\n      - [destruct... as...]:\n        case analysis on values of inductively defined types\n\n      - [destruct... eqn:...]:\n        specify the name of an equation to be added to the context,\n        recording the result of the case analysis\n\n      - [induction... as...]:\n        induction on values of inductively defined types\n\n      - [inversion]:\n        reason by injectivity and distinctness of constructors\n\n      - [assert (e) as H]:\n        introduce a \"local lemma\" [e] and call it [H]\n\n      - [generalize dependent x]:\n        move the variable [x] (and anything else that depends on it)\n        from the context back to an explicit hypothesis in the goal\n        formula\n*)\n\n(* ###################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (beq_nat_sym)  *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Proof:\n   (* FILL IN HERE *)\n[]\n *)\n\n(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine)  *)\n(** We have just proven that for all lists of pairs, [combine] is the\n    inverse of [split].  How would you formalize the statement that\n    [split] is the inverse of [combine]? When is this property true?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?)  *)\n\nDefinition split_combine_statement : Prop :=\n(* FILL IN HERE *) admit.\n\nTheorem split_combine : split_combine_statement.\nProof.\n(* FILL IN HERE *) Admitted.\n\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars (override_permute)  *)\nTheorem override_permute : forall (X:Type) x1 x2 k1 k2 k3 (f : nat->X),\n  beq_nat k2 k1 = false ->\n  (override (override f k2 x2) k1 x1) k3 = (override (override f k1 x1) k2 x2) k3.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise)  *)\n(** This one is a bit challenging.  Pay attention to the form of your IH. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof. Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (forall_exists_challenge)  *)\n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n\n      forallb evenb [0;2;4;5] = false\n\n      forallb (beq_nat 5) [] = true\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n      existsb (beq_nat 5) [0;2;3;6] = false\n\n      existsb (andb true) [true;true;false] = true\n\n      existsb oddb [1;0;0;0;0;3] = true\n\n      existsb evenb [] = false\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n\n    Prove theorem [existsb_existsb'] that [existsb'] and [existsb] have\n    the same behavior.\n*)", "meta": {"author": "dredozubov", "repo": "sf", "sha": "e48b559c657036e567df689d183903702f6e580e", "save_path": "github-repos/coq/dredozubov-sf", "path": "github-repos/coq/dredozubov-sf/sf-e48b559c657036e567df689d183903702f6e580e/MoreCoq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929053683038, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.6629714867804648}}
{"text": "(**********************************************************************)\n(* Equations                                                          *)\n(* Copyright (c) 2009-2016 Matthieu Sozeau <matthieu.sozeau@inria.fr> *)\n(**********************************************************************)\n(* This file is distributed under the terms of the                    *)\n(* GNU Lesser General Public License Version 2.1                      *)\n(**********************************************************************)\n\n(** An example development of the [fin] datatype using [equations]. *)\n\nRequire Import Coq.Program.Program Equations.Equations.\n\n(** [fin n] is the type of naturals smaller than [n]. *)\n\nInductive fin : nat -> Set :=\n| fz : forall {n}, fin (S n)\n| fs : forall {n}, fin n -> fin (S n).\n\n(** We can inject it into [nat]. *)\n\nEquations(nocomp) fog {n} (f : fin n) : nat :=\nfog {n:=?(S n)} (fz n) := 0 ; \nfog (fs n f) := S (fog f).\n\n(** The injection preserves the number: *)\nRequire Import FunctionalInduction.\n\n\nLemma fog_inj {n} (f : fin n) : fog f < n.\nProof with auto with arith. intros.\n  depind f; simp fog...\nQed.\n\n(** Of course it has an inverse. *)\n\nEquations(nocomp) gof n : fin (S n) :=\ngof O := fz ;\ngof (S n) := fs (gof n).\n\nLemma fog_gof n : fog (gof n) = n.\nProof with auto with arith. intros.\n  funind (gof n) gofn; simp fog gof...\nQed.\n\n(** Let's do some arithmetic on [fin] *)\n\n(* Equations_nocomp fin_plus {n m} (x : fin n) (y : fin m) : fin (n + m) := *)\n(* fin_plus ?(S n) ?(S m) (fz n) (fz m) := fz ; *)\n(* fin_plus ?(S n) ?(S m) (fs n x) y := fs (fin_plus x y) ; *)\n(* fin_plus ?(S n) ?(S m) (fz n) (fs m y) := fs (fin_plus fz y).  *)\n\n(** Won't pass the guardness check which diverges anyway. *)\n\nInductive finle : forall (n : nat) (x : fin n) (y : fin n), Prop :=\n| leqz : forall {n j}, finle (S n) fz j\n| leqs : forall {n i j}, finle n i j -> finle (S n) (fs i) (fs j).\n\nScheme finle_ind_dep := Induction for finle Sort Prop.\n\nInstance finle_ind_pack n x y : DependentEliminationPackage (finle n x y) :=\n  { elim_type := _ ; elim := finle_ind_dep }.\n\nArguments finle {n}.\n\nRequire Vectors.Vector.\nArguments Vector.nil {A}.\nArguments Vector.cons {A} _ {n}.\nNotation vnil := Vector.nil.\nNotation vcons := Vector.cons.\n\nEquations(nocomp) nth {A} {n} (v : Vector.t A n) (f : fin n) : A :=\nnth (vcons a _ v) fz := a ;\nnth (vcons a _ v) (fs n f) := nth v f.\n\nEquations(nocomp) tabulate {A} {n} (f : fin n -> A) : Vector.t A n :=\ntabulate {n:=O} f := vnil ;\ntabulate {n:=(S n)} f := vcons (f fz) (tabulate (f ∘ fs)).\n\n(** NoConfusion For [fin]. *)\n\nDerive NoConfusion for fin.\n\n(** [Below] recursor for [fin]. *)\n\nEquations(nocomp noind) Below_fin (P : forall n, fin n -> Type) {n} (v : fin n) : Type :=\nBelow_fin P fz := unit ;\nBelow_fin P (fs n f) := (P n f * Below_fin P f)%type.\n\nHint Rewrite Below_fin_equation_2 (* Below_fin_equation_3 *) : Below.\n\nEquations(nocomp noeqns noind) below_fin (P : forall n, fin n -> Type)\n  (step : forall n (v : fin n), Below_fin P v -> P n v)\n  {n} (v : fin n) : Below_fin P v :=\nbelow_fin P step fz := tt ;\nbelow_fin P step (fs n f) := \n  let bf := below_fin P step f in\n    (step n f bf, bf).\n\nGlobal Opaque Below_fin.\n\nDefinition rec_fin (P : forall n, fin n -> Type) {n} v\n  (step : forall n (v : fin n), Below_fin P v -> P n v) : P n v :=\n  step n v (below_fin P step v).\n\nImport Equations.Below.\n\nInstance fin_Recursor n : Recursor (fin n) :=\n  { rec_type := fun v => forall (P : forall n, fin n -> Type) step, P n v;\n    rec := fun v P step => rec_fin P v step }.\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/user-contrib/Equations/Fin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563824, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6629714778876155}}
{"text": "(***************************************************************************\n* Safety for STLC in Wright & Felleisen style - Definitions                *\n* Arthur Chargueraud, July 2007                                            *\n***************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibLN.\n\n(** Grammar of types. *)\n\nInductive typ : Set :=\n  | typ_var   : var -> typ\n  | typ_arrow : typ -> typ -> typ.\n\n(** Grammar of pre-terms. *)\n\nInductive trm : Set :=\n  | trm_bvar : nat -> trm\n  | trm_fvar : var -> trm\n  | trm_abs  : trm -> trm\n  | trm_app  : trm -> trm -> trm.\n\n(** Opening up abstractions *)\n\nFixpoint open_rec (k : nat) (u : trm) (t : trm) {struct t} : trm :=\n  match t with\n  | trm_bvar i    => If k = i then u else (trm_bvar i)\n  | trm_fvar x    => trm_fvar x\n  | trm_abs t1    => trm_abs (open_rec (S k) u t1)\n  | trm_app t1 t2 => trm_app (open_rec k u t1) (open_rec k u t2)\n  end.\n\nDefinition open t u := open_rec 0 u t.\n\nNotation \"{ k ~> u } t\" := (open_rec k u t) (at level 67).\nNotation \"t ^^ u\" := (open t u) (at level 67).\nNotation \"t ^ x\" := (open t (trm_fvar x)).\n\n(** Terms are locally-closed pre-terms *)\n\nInductive term : trm -> Prop :=\n  | term_var : forall x,\n      term (trm_fvar x)\n  | term_abs : forall L t1,\n      (forall x, x \\notin L -> term (t1 ^ x)) ->\n      term (trm_abs t1)\n  | term_app : forall t1 t2,\n      term t1 -> \n      term t2 -> \n      term (trm_app t1 t2).\n\n(** Environment is an associative list mapping variables to types. *)\n\nDefinition env := LibEnv.env typ.\n\n(** Typing relation *)\n\nReserved Notation \"E |= t ~: T\" (at level 69).\n\nInductive typing : env -> trm -> typ -> Prop :=\n  | typing_var : forall E x T,\n      ok E ->\n      binds x T E ->\n      E |= (trm_fvar x) ~: T\n  | typing_abs : forall L E U T t1,\n      (forall x, x \\notin L -> \n        (E & x ~ U) |= t1 ^ x ~: T) ->\n      E |= (trm_abs t1) ~: (typ_arrow U T)\n  | typing_app : forall S T E t1 t2,\n      E |= t1 ~: (typ_arrow S T) -> \n      E |= t2 ~: S ->\n      E |= (trm_app t1 t2) ~: T\n\nwhere \"E |= t ~: T\" := (typing E t T).\n\n(** Definition of values (only abstractions are values) *)\n\nInductive value : trm -> Prop :=\n  | value_abs : forall t1,\n      term (trm_abs t1) -> value (trm_abs t1).\n\n(** Reduction contexts *)\n\nInductive ctx : Set :=\n  | ctx_hole : ctx\n  | ctx_app_1 : forall (C : ctx) t2,\n      term t2 -> ctx\n  | ctx_app_2 : forall t1 (C : ctx),\n      value t1 -> ctx.\n\nFixpoint ctx_of (C : ctx) (t : trm) {struct C} : trm :=\n  match C with\n  | ctx_hole         => t\n  | ctx_app_1 C t2 _ => trm_app (ctx_of C t) t2\n  | ctx_app_2 t1 C _ => trm_app t1 (ctx_of C t)\n  end.\n\n(** Reduction relation - one step in call-by-value *)\n\nInductive red : trm -> trm -> Prop :=\n  | red_beta : forall t1 t2,\n      term (trm_abs t1) -> \n      value t2 ->\n      red (trm_app (trm_abs t1) t2) (t1 ^^ t2)\n  | red_ctx : forall C t t',\n      red t t' ->\n      red (ctx_of C t) (ctx_of C t').\n\nNotation \"t --> t'\" := (red t t') (at level 68).\n\n(** Goal is to prove preservation and progress *)\n\nDefinition preservation := forall E t t' T,\n  E |= t ~: T ->\n  t --> t' ->\n  E |= t' ~: T.\n\nDefinition progress := forall t T, \n  empty |= t ~: T ->\n     value t \n  \\/ exists t', t --> t'.\n\n", "meta": {"author": "charguer", "repo": "formalmetacoq", "sha": "0f24ffe7416352c1a275671d8d857f8aa6a5bb39", "save_path": "github-repos/coq/charguer-formalmetacoq", "path": "github-repos/coq/charguer-formalmetacoq/formalmetacoq-0f24ffe7416352c1a275671d8d857f8aa6a5bb39/ln/STLC_Core_WF_Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563824, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6629714735406955}}
{"text": "(**********************************************************************\n\n Categories enriched over posets\n\n In this file, we study categories enriched over posets. We provide\n an elementary definition for both enrichments of categories and of\n functors and we prove the equivalence of these notions with the\n general notion of enrichments via the cartesian monoidal category of\n posets.\n\n Enrichments of posets for categories means that every hom-set is\n equipped with the structure of a poset and that composition is\n monotone, while enrichment for functors means that the action on\n morphisms is monotone.\n\n Contents\n 1. The monoidal category is faithful\n 2. Elementary definition of poset enrichments\n 3. Equivalence of enrichments with the elementary definition\n 4. Elementary definition of poset enriched functors\n 5. Equivalence of functor enrichments with elementary definition\n\n **********************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.Combinatorics.Posets.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.CategoryTheory.Core.Univalence.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Examples.CategoryOfPosets.\nRequire Import UniMath.CategoryTheory.Monoidal.WhiskeredBifunctors.\nRequire Import UniMath.CategoryTheory.Monoidal.Categories.\nRequire Import UniMath.CategoryTheory.Monoidal.Structure.Cartesian.\nRequire Import UniMath.CategoryTheory.Monoidal.Examples.PosetsMonoidal.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Enrichment.\nRequire Import UniMath.CategoryTheory.EnrichedCats.EnrichmentFunctor.\n\nLocal Open Scope cat.\n\n(**\n 1. The monoidal category is faithful\n *)\nDefinition poset_faithful_moncat\n  : faithful_moncat poset_monoidal_cat.\nProof.\n  intros R₁ R₂ f g p.\n  use eq_monotone_function.\n  intro x.\n  assert (is_monotone unit_PartialOrder (pr2 R₁) (λ _, x)) as H.\n  {\n    intros w₁ w₂ q.\n    apply refl_PartialOrder.\n  }\n  exact (eqtohomot (maponpaths pr1 (p ((λ _, x) ,, H))) tt).\nQed.\n\n(**\n 2. Elementary definition of poset enrichments\n *)\nDefinition poset_enrichment_data\n           (C : category)\n  : UU\n  := ∏ (x y : C), PartialOrder (homset x y).\n\nDefinition poset_enrichment_laws\n           {C : category}\n           (PEC : poset_enrichment_data C)\n  : UU\n  := (∏ (x y z : C)\n        (f₁ f₂ : x --> y)\n        (g : y --> z)\n        (p : PEC x y f₁ f₂),\n      PEC x z (f₁ · g) (f₂ · g))\n     ×\n     (∏ (x y z : C)\n        (f : x --> y)\n        (g₁ g₂ : y --> z)\n        (p : PEC y z g₁ g₂),\n      PEC x z (f · g₁) (f · g₂)).\n\nProposition isaprop_poset_enrichment_laws\n            {C : category}\n            (PEC : poset_enrichment_data C)\n  : isaprop (poset_enrichment_laws PEC).\nProof.\n  use isapropdirprod ; (repeat (use impred ; intro)) ; apply propproperty.\nQed.\n\nDefinition poset_enrichment\n           (C : category)\n  : UU\n  := ∑ (PEC : poset_enrichment_data C), poset_enrichment_laws PEC.\n\nDefinition poset_enrichment_hom_poset\n           {C : category}\n           (PEC : poset_enrichment C)\n           (x y : C)\n  : PartialOrder (x --> y ,, homset_property C x y)\n  := pr1 PEC x y.\n\nCoercion poset_enrichment_hom_poset : poset_enrichment >-> Funclass.\n\nProposition poset_enrichment_comp_l\n            {C : category}\n            (PEC : poset_enrichment C)\n            {x y z : C}\n            {f₁ f₂ : x --> y}\n            (g : y --> z)\n            (p : PEC x y f₁ f₂)\n  : PEC x z (f₁ · g) (f₂ · g).\nProof.\n  exact (pr12 PEC x y z f₁ f₂ g p).\nQed.\n\nProposition poset_enrichment_comp_r\n            {C : category}\n            (PEC : poset_enrichment C)\n            {x y z : C}\n            (f : x --> y)\n            {g₁ g₂ : y --> z}\n            (p : PEC y z g₁ g₂)\n  : PEC x z (f · g₁) (f · g₂).\nProof.\n  exact (pr22 PEC x y z f g₁ g₂ p).\nQed.\n\n(**\n 3. Equivalence of enrichments with the elementary definition\n *)\nSection MakePosetEnrichment.\n  Context (C : category)\n          (PEC : poset_enrichment C).\n\n  Definition make_enrichment_over_poset_data\n    : enrichment_data C poset_monoidal_cat.\n  Proof.\n    simple refine (_ ,, _ ,, _ ,, _ ,, _).\n    - exact (λ x y, _ ,, PEC x y).\n    - refine (λ x, (λ _, identity _) ,, _).\n      abstract\n        (cbn ; intros t₁ t₂ p ;\n         apply refl_PartialOrder).\n    - simple refine (λ x y z, _ ,, _) ; cbn in *.\n      + exact (λ fg, pr2 fg · pr1 fg).\n      + abstract\n          (intros fg₁ fg₂ p ; cbn in * ;\n           exact (trans_PartialOrder\n                    _\n                    (poset_enrichment_comp_l PEC _ (pr2 p))\n                    (poset_enrichment_comp_r PEC _ (pr1 p)))).\n    - refine (λ x y f, (λ _, f) ,, _).\n      abstract\n        (intros t₁ t₂ p ; cbn in * ;\n         apply refl_PartialOrder).\n    - exact (λ x y f, pr1 f tt).\n  Defined.\n\n  Proposition make_enrichment_over_poset_laws\n    : enrichment_laws make_enrichment_over_poset_data.\n  Proof.\n    repeat split.\n    - intros x y.\n      use eq_monotone_function.\n      intro a ; cbn.\n      rewrite id_right.\n      apply idpath.\n    - intros x y.\n      use eq_monotone_function.\n      intro a ; cbn.\n      rewrite id_left.\n      apply idpath.\n    - intros w x y z.\n      use eq_monotone_function.\n      intro a ; cbn.\n      rewrite assoc.\n      apply idpath.\n    - intros x y f.\n      use eq_monotone_function.\n      intro a ; cbn in *.\n      apply maponpaths.\n      apply isapropunit.\n  Qed.\n\n  Definition make_enrichment_over_poset\n    : enrichment C poset_monoidal_cat\n    := make_enrichment_over_poset_data ,, make_enrichment_over_poset_laws.\nEnd MakePosetEnrichment.\n\nSection FromPosetEnrichment.\n  Context (C : category)\n          (E : enrichment C poset_monoidal_cat).\n\n  Definition make_poset_enrichment_rel\n             (x y : C)\n    : hrel (x --> y).\n  Proof.\n    refine (λ f g, _).\n    use make_hProp.\n    - exact (pr12 (E ⦃ x , y ⦄)\n                  (pr1 (enriched_from_arr E f) tt)\n                  (pr1 (enriched_from_arr E g) tt)).\n    - apply (pr12 (E ⦃ x , y ⦄)).\n  Defined.\n\n  Definition make_poset_enrichment_data\n    : poset_enrichment_data C.\n  Proof.\n    intros x y.\n    simple refine (_ ,, ((_ ,, _) ,, _)).\n    - exact (make_poset_enrichment_rel x y).\n    - intros f g h p q.\n      exact (trans_PartialOrder (pr2 (E ⦃ x , y ⦄)) p q).\n    - intros f.\n      exact (refl_PartialOrder (pr2 (E ⦃ x , y ⦄)) _).\n    - cbn.\n      intros f g p q.\n      rewrite <- (enriched_to_from_arr E f).\n      rewrite <- (enriched_to_from_arr E g).\n      apply maponpaths.\n      use eq_monotone_function.\n      intro w.\n      induction w.\n      exact (antisymm_PartialOrder (pr2 (E ⦃ x , y ⦄)) p q).\n  Defined.\n\n  Proposition make_poset_enrichment_laws\n    : poset_enrichment_laws make_poset_enrichment_data.\n  Proof.\n    repeat split.\n    - intros x y z f₁ f₂ g p ; cbn.\n      rewrite !enriched_from_arr_comp ; cbn.\n      pose (Ef₁ := enriched_from_arr E f₁ : monotone_function _ _).\n      pose (Ef₂ := enriched_from_arr E f₂ : monotone_function _ _).\n      pose (Eg := enriched_from_arr E g : monotone_function _ _).\n      use (pr2 (enriched_comp E x y z) (Eg tt ,, Ef₁ tt) (Eg tt ,, Ef₂ tt)).\n      split.\n      + apply refl_PartialOrder.\n      + exact p.\n    - intros x y z f g₁ g₂ p ;cbn.\n      rewrite !enriched_from_arr_comp ; cbn.\n      pose (Ef := enriched_from_arr E f : monotone_function _ _).\n      pose (Eg₁ := enriched_from_arr E g₁ : monotone_function _ _).\n      pose (Eg₂ := enriched_from_arr E g₂ : monotone_function _ _).\n      use (pr2 (enriched_comp E x y z) (Eg₁ tt ,, Ef tt) (Eg₂ tt ,, Ef tt)).\n      split.\n      + exact p.\n      + apply refl_PartialOrder.\n  Qed.\n\n  Definition make_poset_enrichment\n    : poset_enrichment C\n    := make_poset_enrichment_data ,, make_poset_enrichment_laws.\nEnd FromPosetEnrichment.\n\nSection EnrichmentOverPosetInverse.\n  Context {C : category}\n          (E : enrichment C poset_monoidal_cat).\n\n  Definition enrichment_over_poset_weq_poset_enrichment_inv_iso\n             (x y : C)\n    : z_iso\n        ((pr11 (make_enrichment_over_poset C (make_poset_enrichment C E))) x y)\n        (E ⦃ x , y ⦄).\n  Proof.\n    use make_z_iso ; cbn.\n    - simple refine (_ ,, _).\n      + exact (λ f, pr1 (enriched_from_arr E f) tt).\n      + abstract\n          (cbn ;\n           intros f g p ;\n           apply p).\n    - simple refine (_ ,, _).\n      + refine (λ f, enriched_to_arr E _).\n        simple refine (_ ,, _).\n        * exact (λ _, f).\n        * abstract\n            (cbn ;\n             intros t₁ t₂ p ;\n             apply refl_PartialOrder).\n      + abstract\n          (intros f₁ f₂ p ; cbn ;\n           rewrite !enriched_from_to_arr ; cbn ;\n           exact p).\n    - split.\n      + abstract\n          (use eq_monotone_function ;\n           intro f ; cbn in * ;\n           refine (_ @ enriched_to_from_arr E f) ;\n           apply maponpaths ;\n           use eq_monotone_function ;\n           intro t ; cbn ;\n           apply maponpaths ;\n           apply isapropunit).\n      + abstract\n          (use eq_monotone_function ;\n           intro f ; cbn in * ;\n           assert (is_monotone unit_PartialOrder (pr2 (E ⦃ x, y ⦄)) (λ _ : unit, f)) as H ;\n           [ intros t₁ t₂ p ;\n             apply refl_PartialOrder\n           | ] ;\n           refine (_ @ eqtohomot (maponpaths pr1 (enriched_from_to_arr E (_ ,, H))) tt) ;\n           cbn ;\n           apply maponpaths_2 ;\n           do 3 apply maponpaths ;\n           apply isaprop_is_monotone).\n  Defined.\n\n  Definition enrichment_over_poset_weq_poset_enrichment_inv_1\n    : make_enrichment_over_poset C (make_poset_enrichment C E) = E.\n  Proof.\n    use subtypePath.\n    {\n      intro.\n      apply isaprop_enrichment_laws.\n    }\n    use (invweq (total2_paths_equiv _ _ _)).\n    use (invmap (enrichment_data_hom_path _ _ _)).\n    {\n      exact is_univalent_category_of_posets.\n    }\n    simple refine (_ ,, _ ,, _ ,, _ ,, _).\n    - exact enrichment_over_poset_weq_poset_enrichment_inv_iso.\n    - abstract\n        (intro x ;\n         use eq_monotone_function ;\n         intro w ; cbn ;\n         rewrite enriched_from_arr_id ;\n         apply maponpaths ;\n         apply isapropunit).\n    - abstract\n        (intros x y z ;\n         use eq_monotone_function ;\n         intro w ; cbn ;\n         rewrite enriched_from_arr_comp ; cbn ;\n         apply idpath).\n    - abstract\n        (intros x y f ;\n         use eq_monotone_function ;\n         intro w ; cbn ;\n         apply maponpaths ;\n         apply isapropunit).\n    - abstract\n        (intros x y f ;\n         cbn ;\n         refine (!_) ;\n         refine (_ @ enriched_to_from_arr E (pr1 f tt)) ;\n         apply maponpaths ;\n         use eq_monotone_function ;\n         intro w ; cbn ;\n         induction w ;\n         apply idpath).\n  Defined.\nEnd EnrichmentOverPosetInverse.\n\nDefinition enrichment_over_poset_weq_poset_enrichment_inv_2\n           {C : category}\n           (E : poset_enrichment C)\n  : make_poset_enrichment C (make_enrichment_over_poset C E) = E.\nProof.\n  use subtypePath.\n  {\n    intro.\n    apply isaprop_poset_enrichment_laws.\n  }\n  use funextsec ; intro x.\n  use funextsec ; intro y.\n  use subtypePath.\n  {\n    intro.\n    apply isaprop_isPartialOrder.\n  }\n  apply idpath.\nQed.\n\nDefinition enrichment_over_poset_weq_poset_enrichment\n           (C : category)\n  : enrichment C poset_monoidal_cat ≃ poset_enrichment C.\nProof.\n  use weq_iso.\n  - exact (make_poset_enrichment C).\n  - exact (make_enrichment_over_poset C).\n  - exact enrichment_over_poset_weq_poset_enrichment_inv_1.\n  - exact enrichment_over_poset_weq_poset_enrichment_inv_2.\nDefined.\n\n(**\n 4. Elementary definition of poset enriched functors\n *)\nDefinition functor_poset_enrichment\n           {C₁ C₂ : category}\n           (P₁ : poset_enrichment C₁)\n           (P₂ : poset_enrichment C₂)\n           (F : C₁ ⟶ C₂)\n  : UU\n  := ∏ (x y : C₁)\n       (f g : x --> y),\n     P₁ x y f g → P₂ (F x) (F y) (#F f) (#F g).\n\n(**\n 5. Equivalence of functor enrichments with elementary definition\n *)\nDefinition make_functor_poset_enrichment\n           {C₁ C₂ : category}\n           (P₁ : poset_enrichment C₁)\n           (P₂ : poset_enrichment C₂)\n           (F : C₁ ⟶ C₂)\n           (HF : functor_enrichment\n                   F\n                   (make_enrichment_over_poset C₁ P₁)\n                   (make_enrichment_over_poset C₂ P₂))\n  : functor_poset_enrichment P₁ P₂ F.\nProof.\n  intros x y f g p.\n  pose (eqtohomot (maponpaths pr1 (functor_enrichment_from_arr HF f)) tt) as pf.\n  pose (eqtohomot (maponpaths pr1 (functor_enrichment_from_arr HF g)) tt) as pg.\n  cbn in pf, pg.\n  rewrite pf, pg.\n  exact (pr2 (HF x y) f g p).\nQed.\n\nDefinition make_functor_enrichment_over_poset\n           {C₁ C₂ : category}\n           (P₁ : poset_enrichment C₁)\n           (P₂ : poset_enrichment C₂)\n           (F : C₁ ⟶ C₂)\n           (HF : functor_poset_enrichment P₁ P₂ F)\n  : functor_enrichment\n      F\n      (make_enrichment_over_poset C₁ P₁)\n      (make_enrichment_over_poset C₂ P₂).\nProof.\n  simple refine (_ ,, _).\n  - refine (λ x y, (λ f, #F f) ,, λ f g p, _).\n    exact (HF x y f g p).\n  - repeat split.\n    + abstract\n        (intros x ;\n         use eq_monotone_function ;\n         intro w ; cbn ;\n         apply functor_id).\n    + abstract\n        (intros x y z ;\n         use eq_monotone_function ;\n         intro w ; cbn ;\n         apply functor_comp).\n    + abstract\n        (intros x y z ;\n         use eq_monotone_function ;\n         intro w ; cbn ;\n         apply idpath).\nDefined.\n\nDefinition functor_enrichment_over_poset_weq_poset_enrichment\n           {C₁ C₂ : category}\n           (P₁ : poset_enrichment C₁)\n           (P₂ : poset_enrichment C₂)\n           (F : C₁ ⟶ C₂)\n  : functor_enrichment\n      F\n      (make_enrichment_over_poset C₁ P₁)\n      (make_enrichment_over_poset C₂ P₂)\n    ≃\n    functor_poset_enrichment P₁ P₂ F.\nProof.\n  use weq_iso.\n  - exact (make_functor_poset_enrichment P₁ P₂ F).\n  - exact (make_functor_enrichment_over_poset P₁ P₂ F).\n  - abstract\n      (intro EF ;\n       use subtypePath ; [ intro ; apply isaprop_is_functor_enrichment | ] ;\n       use funextsec ; intro x ;\n       use funextsec ; intro y ;\n       use eq_monotone_function ;\n       intro f ;\n       cbn ;\n       exact (eqtohomot (maponpaths pr1 (functor_enrichment_from_arr EF f)) tt)).\n  - abstract\n      (intros EF ;\n       use funextsec ; intro x ;\n       use funextsec ; intro y ;\n       use funextsec ; intro f ;\n       use funextsec ; intro g ;\n       use funextsec ; intro p ;\n       apply propproperty).\nDefined.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/CategoryTheory/EnrichedCats/Examples/PosetEnriched.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.662928082212841}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint drop (drop_arg0 : natural) (drop_arg1 : lst) : lst\n           := match drop_arg0, drop_arg1 with\n              | x, Nil => Nil\n              | Zero, x => x\n              | Succ x, Cons y z => drop x z\n              end.\n\nTheorem drop_Nil: forall (x: natural), drop x Nil = Nil.\nProof.\n  induction x ; simpl; reflexivity.\nQed.\n\nTheorem drop_Cons: forall (x n: natural) (l: lst), drop (Succ x) (Cons n l) = drop x l.\n  induction l; induction x; simpl; reflexivity.\nQed.\n\nTheorem drop_Cons_assoc: forall (x1 x2 x3: natural) (l: lst),\n    drop x1 (drop x2 (Cons x3 l)) = drop x2 (drop x1 (Cons x3 l)).\nProof.\n  induction x1; induction x2; try (simpl; reflexivity).\n  + induction l.\n    * rewrite 2 drop_Cons. rewrite <- IHx1.\n      rewrite IHx2. rewrite 2 drop_Cons.\n      induction l.\n      - rewrite IHx1. reflexivity. \n      - rewrite 3 drop_Nil. reflexivity. \n    * simpl. lfind.  reflexivity.  \nAdmitted.\n\nTheorem drop_assoc : forall (x : natural) (y : natural) (z : lst), eq (drop x (drop y z)) (drop y (drop x z)).\nProof.\n  induction z.\n  + rewrite 2 drop_Cons_assoc. reflexivity. \n  + rewrite 3 drop_Nil. reflexivity. \nQed.\n\nTheorem theorem0 : forall (x : natural) (y : natural) (w : natural) (z : lst), eq (drop w (drop x (drop y z))) (drop y (drop x (drop w z))).\nProof.\n  intros.\n  rewrite (drop_assoc w x).\n  rewrite (drop_assoc w y).\n  rewrite (drop_assoc x y).\n  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/clam_lf_goal9_drop_Cons_assoc_37_drop_Nil/goal9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6629280765170018}}
{"text": "Require Export Category.\nRequire Import Common.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope category_scope.\nLocal Open Scope morphism_scope.\n\nDefinition UniqueUpToUniqueIsomorphism (C : PreCategory) (P : C -> Type) :=\n  forall x (_ : P x) x' (_ : P x'),\n    { c : Contr (Morphism C x x')\n    | IsIsomorphism (center (Morphism C x x')) }.\n\n(** A terminal object is an object with a unique morphism from every\n    other object. *)\nNotation IsTerminalObject C x :=\n  (forall x' : Object C, Contr (Morphism C x' x)).\n\nRecord TerminalObject (C : PreCategory) :=\n  {\n    TerminalObject_Object :> C;\n    TerminalObject_IsTerminalObject :> IsTerminalObject C TerminalObject_Object\n  }.\n\nExisting Instance TerminalObject_IsTerminalObject.\n\n(** An initial object is an object with a unique morphism from every\n    other object. *)\nNotation IsInitialObject C x :=\n  (forall x' : Object C, Contr (Morphism C x x')).\n\nRecord InitialObject (C : PreCategory) :=\n  {\n    InitialObject_Object :> C;\n    InitialObject_IsInitialObject :> IsInitialObject C InitialObject_Object\n  }.\n\nExisting Instance InitialObject_IsInitialObject.\n\nArguments UniqueUpToUniqueIsomorphism [C] P.\n\nSection CategoryObjectsTheorems.\n  Variable C : PreCategory.\n\n  Ltac unique :=\n   repeat first [ intro\n                 | exists _\n                 | exists (center (Morphism C _ _))\n                 | etransitivity; [ symmetry | ]; apply contr\n                 ].\n\n  (** The terminal object is unique up to unique isomorphism. *)\n  Theorem TerminalObjectUnique\n  : UniqueUpToUniqueIsomorphism (fun x => IsTerminalObject C x).\n  Proof.\n    unique.\n  Qed.\n\n  (** The initial object is unique up to unique isomorphism. *)\n  Theorem InitialObjectUnique\n  : UniqueUpToUniqueIsomorphism (fun x => IsInitialObject C x).\n  Proof.\n    unique.\n  Qed.\nEnd CategoryObjectsTheorems.\n", "meta": {"author": "CategoricalData", "repo": "HoTT-categories", "sha": "31230d90405631c07d58c9e6ac74fe329237de69", "save_path": "github-repos/coq/CategoricalData-HoTT-categories", "path": "github-repos/coq/CategoricalData-HoTT-categories/HoTT-categories-31230d90405631c07d58c9e6ac74fe329237de69/theories/Categories/Category/Objects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6627946684263943}}
{"text": "Theorem LogicBot_10_14_2021 : (forall a b:Prop, ~((a /\\ (b <-> b)) <-> ~a)).\nintros A B H.\ndestruct H.\nassert (a:A).\napply H0.\nintro a.\napply H.\nsplit.\napply a.\napply iff_refl.\napply a.\napply H.\nsplit.\napply a.\napply iff_refl.\napply a.\nOptimize Proof.\nDefined.\n\nPrint LogicBot_10_14_2021.\n(*\nfun (A B : Prop) (H : A /\\ (B <-> B) <-> ~ A) =>\nmatch H with\n| conj H0 H1 =>\n    let a : A :=\n      let H2 : ~ A -> A := fun H2 : ~ A => match H1 H2 with\n                                           | conj x _ => x\n                                           end in\n      H2 (fun a : A => H0 (conj a (iff_refl B)) a) in\n    H0 (conj a (iff_refl B)) a\nend\n*)", "meta": {"author": "bowtochris", "repo": "CoqStuff", "sha": "80ffef00b18a23b85f66fcb5b198d2730a49a362", "save_path": "github-repos/coq/bowtochris-CoqStuff", "path": "github-repos/coq/bowtochris-CoqStuff/CoqStuff-80ffef00b18a23b85f66fcb5b198d2730a49a362/LogicBot_10_14_2021.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6627946532713405}}
{"text": "Inductive Ord : Set :=\n|  zero : Ord\n|  succ : Ord -> Ord\n| limit : (nat->Ord)->Ord.\n\n\nFixpoint nat2ord (n:nat) : Ord :=\n match n with 0 => zero\n            | S p => succ (nat2ord p)\n end.\n\n\nFixpoint plus (o1 o2:Ord){struct o2} :=\n  match o2 with zero => o1\n              | succ o2' => succ (plus o1  o2')\n              | limit f => limit (fun n => plus o1 (f n))\n  end.\nNotation  \"o1 + o2\" := (plus o1 o2):o_scope.\nOpen Scope o_scope.\n\nCoercion nat2ord : nat >-> Ord.\n\nDefinition omega := limit (fun n => n).\n\n\nCheck (succ 23).\nCheck (omega = 2+omega).\n\nCheck (succ (3+5)).\n\nEval compute in (succ (3+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/newstuff/SRC/nat2ord.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121366457407, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6627946440941982}}
{"text": "\nRequire Import Helix.Util.VecUtil.\nRequire Import Helix.Util.VecSetoid.\nRequire Import Helix.Util.Misc.\nRequire Import Helix.HCOL.CarrierType.\n\nRequire Import Helix.HCOL.HCOL.\nRequire Import Helix.HCOL.HCOLImpl.\nRequire Import Helix.HCOL.THCOL.\nRequire Import Helix.HCOL.THCOLImpl.\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.Arith.Peano_dec.\nRequire Import Coq.Program.Program.\n\nRequire Import Helix.Tactics.HelixTactics.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(* CoRN MathClasses *)\nRequire Import MathClasses.interfaces.abstract_algebra MathClasses.interfaces.orders.\nRequire Import MathClasses.orders.minmax MathClasses.orders.orders MathClasses.orders.rings.\nRequire Import MathClasses.theory.rings.\n\n\nImport VectorNotations.\nOpen Scope vector_scope.\n\nSection HCOLBreakdown.\n\n  Context `{CAPROPS: CarrierProperties}.\n  Add Ring RingA: (stdlib_ring_theory CarrierA).\n\n  Lemma Vmap2Indexed_to_VMap2 `{Setoid A} {n} {a b: vector A n}\n        (f:A->A->A)\n  :\n    Vmap2 f a b = Vmap2Indexed (IgnoreIndex2 f) a b.\n  Proof.\n    vec_index_equiv i ip.\n    rewrite Vnth_Vmap2Indexed.\n    rewrite Vnth_map2.\n    reflexivity.\n  Qed.\n\n  Theorem breakdown_ScalarProd: forall (n:nat) (a v: avector n),\n      ScalarProd (a,v) =\n      ((Reduction (+) 0) ∘ (BinOp (IgnoreIndex2 mult))) (a,v).\n  Proof.\n    intros n a v.\n    unfold compose, BinOp, Reduction, ScalarProd.\n    rewrite Vmap2Indexed_to_VMap2.\n    reflexivity.\n  Qed.\n\n  Fact breakdown_OScalarProd: forall {h:nat},\n      HScalarProd (h:=h)\n      =\n      ((HReduction  (+) 0) ∘ (HBinOp (IgnoreIndex2 mult))).\n  Proof.\n    intros h.\n    apply HOperator_functional_extensionality; intros v.\n    unfold HScalarProd, HReduction, HBinOp.\n    unfold vector2pair, compose, Lst, Vectorize.\n    apply Vcons_single_elim.\n    destruct (Vbreak v).\n    apply breakdown_ScalarProd.\n  Qed.\n\n  Theorem breakdown_EvalPolynomial: forall (n:nat) (a: avector (S n)) (v: CarrierA),\n      EvalPolynomial a v = (\n        ScalarProd ∘ (pair a) ∘ (MonomialEnumerator n)\n      ) v.\n  Proof.\n    intros n a v.\n    unfold compose.\n    induction n.\n    - simpl (MonomialEnumerator 0 v).\n      rewrite EvalPolynomial_reduce.\n      dep_destruct (Vtail a).\n      simpl.\n      ring.\n\n    - rewrite EvalPolynomial_reduce, MonomialEnumerator_cons, ScalarProd_reduce.\n      unfold Ptail.\n      rewrite ScalarProd_comm.\n\n      Opaque Scale ScalarProd.\n      simpl.\n      Transparent Scale ScalarProd.\n\n      rewrite ScalarProduct_hd_descale, IHn, mult_1_r, ScalarProd_comm.\n      reflexivity.\n  Qed.\n\n  Fact breakdown_OEvalPolynomial: forall (n:nat) (a: avector (S n)),\n      HEvalPolynomial a =\n      (HScalarProd ∘\n                   ((HPrepend  a) ∘\n                                  (HMonomialEnumerator n))).\n  Proof.\n    intros n a.\n    apply HOperator_functional_extensionality; intros v.\n    unfold HEvalPolynomial, HScalarProd, HPrepend, HMonomialEnumerator.\n    unfold vector2pair, compose, Lst, Scalarize.\n    rewrite Vcons_single_elim, Vbreak_app.\n    apply breakdown_EvalPolynomial.\n  Qed.\n\n  Theorem breakdown_TInfinityNorm: forall (n:nat) (v:avector n),\n      InfinityNorm (n:=n) v = ((Reduction max 0) ∘ (HPointwise (IgnoreIndex abs))) v.\n  Proof.\n    intros n v.\n    unfold InfinityNorm, Reduction, compose, IgnoreIndex, HPointwise.\n    rewrite Vmap_as_Vbuild.\n    reflexivity.\n  Qed.\n\n  Fact breakdown_OTInfinityNorm:  forall (n:nat),\n      HInfinityNorm =\n      (HReduction max 0 (i:=n) ∘ (HPointwise (IgnoreIndex abs))).\n  Proof.\n    intros n.\n    apply HOperator_functional_extensionality; intros v.\n    apply Vcons_single_elim.\n    apply breakdown_TInfinityNorm.\n  Qed.\n\n  Theorem breakdown_MonomialEnumerator:\n    forall (n:nat) (x: CarrierA),\n      MonomialEnumerator n x = Induction (S n) (.*.) 1 x.\n  Proof.\n    intros n x.\n    induction n.\n    - reflexivity.\n    - rewrite MonomialEnumerator_cons.\n      rewrite_clear IHn.\n      symmetry.\n      rewrite Induction_cons.\n      unfold Scale.\n      f_equiv.\n      setoid_replace (fun x0 : CarrierA => mult x0 x) with (mult x).\n      reflexivity.\n      +\n        intros a b E.\n        rewrite E.\n        apply mult_comm.\n  Qed.\n\n  Fact breakdown_OMonomialEnumerator:\n    forall (n:nat),\n      HMonomialEnumerator n =\n      HInduction (S n) (.*.) 1.\n  Proof.\n    intros n.\n    apply HOperator_functional_extensionality; intros v.\n    apply breakdown_MonomialEnumerator.\n  Qed.\n\n  Theorem breakdown_ChebyshevDistance:  forall (n:nat) (ab: (avector n)*(avector n)),\n      ChebyshevDistance ab = (InfinityNorm ∘ VMinus) ab.\n  Proof.\n    intros.\n    unfold compose, ChebyshevDistance, VMinus.\n    destruct ab.\n    reflexivity.\n  Qed.\n\n  Fact breakdown_OChebyshevDistance:  forall (n:nat),\n      HChebyshevDistance n = (HInfinityNorm ∘ HVMinus).\n  Proof.\n    intros n.\n    apply HOperator_functional_extensionality; intros v.\n    unfold Lst, compose.\n    apply Vcons_single_elim.\n    apply breakdown_ChebyshevDistance.\n  Qed.\n\n  Theorem breakdown_VMinus:  forall (n:nat) (ab: (avector n)*(avector n)),\n      VMinus ab = BinOp (IgnoreIndex2 sub) ab.\n  Proof.\n    intros.\n    unfold VMinus, BinOp.\n    break_let.\n    unfold sub.\n    rewrite Vmap2Indexed_to_VMap2.\n    reflexivity.\n  Qed.\n\n  Fact breakdown_OVMinus:  forall (n:nat),\n      HVMinus = HBinOp (o:=n) (IgnoreIndex2 sub).\n  Proof.\n    intros n.\n    apply HOperator_functional_extensionality; intros v.\n    unfold HVMinus.\n    unfold vector2pair.\n    apply breakdown_VMinus.\n  Qed.\n\n  Fact breakdown_OTLess_Base: forall\n      {i1 i2 o}\n      `{o1pf: !HOperator (o1: avector i1 -> avector o)}\n      `{o2pf: !HOperator (o2: avector i2 -> avector o)},\n      HTLess o1 o2 = (HBinOp (IgnoreIndex2 Zless) ∘ HCross o1 o2).\n  Proof.\n    intros i1 i2 o o1 po1 o2 po2.\n    apply HOperator_functional_extensionality; intros v.\n    unfold HTLess, HBinOp, HCross.\n    unfold compose, BinOp.\n    cbn.\n    rewrite vp2pv.\n    repeat break_let.\n    unfold vector2pair in Heqp.\n    rewrite Heqp in Heqp1.\n    tuple_inversion.\n    tuple_inversion.\n    rewrite Vmap2Indexed_to_VMap2.\n    reflexivity.\n  Qed.\n\nEnd HCOLBreakdown.\n\n\n\n", "meta": {"author": "vzaliva", "repo": "helix", "sha": "5d0a71df99722d2011c36156f12b04875df7e1cb", "save_path": "github-repos/coq/vzaliva-helix", "path": "github-repos/coq/vzaliva-helix/helix-5d0a71df99722d2011c36156f12b04875df7e1cb/coq/HCOL/HCOLBreakdown.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.662765455253414}}
{"text": "(***********************************************************************)\n(* version 2 License, as specified in the README file.                 *)\n(*                                                                     *)\n(***********************************************************************)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq div choice.\nRequire Import fintype finfun finset groups morphisms automorphism.\n\n(***********************************************************************)\n(* This file contains the definitions of:                              *)\n(*                                                                     *)\n(*   coset_of H           == right cosets by the group H (see below)   *)\n(*   coset_groupType H    == the groupType induced by 'N(H) / H        *)\n(*   coset H              == the canonical projection induced by H     *)\n(*   A / B                == the quotient of A by B,                   *)\n(*                               made to coincide w/ (A :&: 'N(B)) / B *)\n(*   quotm (nHG: H <| G) (nGf : f@* G = G) (nHf : f@*H = H)            *)\n(*                        == the quotient morphism induced by f and H  *)\n(***********************************************************************)\n(* Lemmas for these notions, plus the three isomorphism theorems, and  *)\n(* counting lemmas for morphisms.                                      *)\n(***********************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nImport GroupScope.\n\n(********************************************************************)\n(*       Cosets are right cosets of elements in the normaliser      *)\n(********************************************************************)\n\nSection Cosets.\n\nVariables (gT : finGroupType) (Q A : {set gT}).\n\n(* We let cosets coerce to GroupSet.sort, so they inherit the group  *)\n(* subset base group structure. Later we will define a proper group  *)\n(* structure on cosets, which will then hide the inherited structure *)\n(* once coset_of unifies with FinGroup.sort; the coercion to         *)\n(* GroupSet.sort will no longer be used.                             *)\n(*   Note that for Hx Hy : coset_of H, Hx * Hy : {set gT} can mean   *)\n(*      either set_of_coset (mulg Hx Hy)                             *)\n(*          OR mulg (set_of_coset Hx) (set_of_coset Hy)              *)\n(* However, since the two terms are actually convertible, we can     *)\n(* live with this ambiguity.                                         *)\n(*   We take great care that neither the type coset_of H, its        *)\n(* finGroupType structure, nor the coset H morphism depend on the    *)\n(* actual group structure of H. Otherwise, rewriting would be        *)\n(* extremely awkward because all our equalities are stated at the    *)\n(* set level.                                                        *)\n(*   The trick we use is to interpret coset_of A, when A is any set, *)\n(* as the type of cosets of the group <A> generated by A, in the     *)\n(* group <A, N(A)> generated by A and its normaliser. This coincides *)\n(* with the type of bilateral cosets of A when A is a group. We      *)\n(* restrict the domain of coset_of A to 'N(A), so that we get almost *)\n(* all the same conversion equalities as if we had forced A to be a  *)\n(* group in the first place -- the only exception is that            *)\n(*      1 : coset_of A : set _ = <<A>> rather than A,                *)\n(* is covered by the genGid lemma.                                   *)\n\nNotation H := <<A>>.\nDefinition coset_range := [pred B \\in rcosets H 'N(A)].\n\nRecord coset_of : Type :=\n  Coset { set_of_coset :> GroupSet.sort gT; _ : coset_range set_of_coset }.\n\nCanonical Structure coset_subType :=\n  Eval hnf in [subType for set_of_coset by coset_of_rect].\nDefinition coset_eqMixin := Eval hnf in [eqMixin of coset_of by <:].\nCanonical Structure coset_eqType := Eval hnf in EqType coset_eqMixin.\nDefinition coset_choiceMixin := [choiceMixin of coset_of by <:].\nCanonical Structure coset_choiceType :=\n  Eval hnf in ChoiceType coset_choiceMixin.\nDefinition coset_countMixin := [countMixin of coset_of by <:].\nCanonical Structure coset_countType := Eval hnf in CountType coset_countMixin.\nCanonical Structure coset_subCountType :=\n  Eval hnf in [subCountType of coset_of].\nDefinition coset_finMixin := [finMixin of coset_of by <:].\nCanonical Structure coset_finType := Eval hnf in FinType coset_finMixin.\nCanonical Structure coset_subFinType := Eval hnf in [subFinType of coset_of].\n\n(* We build a new (canonical) structure of groupType for cosets.      *)\n(* When A is a group, this is the largest possible quotient 'N(A) / A *)\n\nLemma coset_one_proof : coset_range H.\nProof. by apply/rcosetsP; exists (1 : gT); rewrite (group1, mulg1). Qed.\nDefinition coset_one := Coset coset_one_proof.\n\nLet nNH := subsetP (norm_gen A).\n\nLemma coset_range_mul : forall B C : coset_of, coset_range (B * C).\nProof.\ncase=> B /=; case/rcosetsP=> x Nx ->{B} [C] /=; case/rcosetsP=> y Ny ->{C}.\nby apply/rcosetsP; exists (x * y); rewrite !(groupM, rcoset_mul, nNH).\nQed.\n\nDefinition coset_mul B C := Coset (coset_range_mul B C).\n\nLemma coset_range_inv : forall B : coset_of, coset_range B^-1.\nProof.\ncase=> B /=; case/rcosetsP=> x Nx ->{B}.\nrewrite norm_rlcoset ?nNH // invg_lcoset.\nby apply/rcosetsP; exists x^-1; rewrite ?groupV.\nQed.\n\nDefinition coset_inv B := Coset (coset_range_inv B).\n\nLemma coset_mulP : associative coset_mul.\nProof. by move=> B C D; apply: val_inj; rewrite /= mulgA. Qed.\n\nLemma coset_oneP : left_id coset_one coset_mul.\nProof.\ncase=> B coB; apply: val_inj => /=; case/rcosetsP: coB => x Hx ->{B}.\nby rewrite mulgA mulGid.\nQed.\n\nLemma coset_invP : left_inverse coset_one coset_inv coset_mul.\nProof.\ncase=> B coB; apply: val_inj => /=; case/rcosetsP: coB => x Hx ->{B}.\nrewrite invg_rcoset -mulgA (mulgA H) mulGid.\nby rewrite norm_rlcoset ?nNH // -lcosetM mulVg mul1g.\nQed.\n\nDefinition coset_of_groupMixin :=\n  FinGroup.Mixin coset_mulP coset_oneP coset_invP.\n\nCanonical Structure coset_baseGroupType :=\n  Eval hnf in BaseFinGroupType coset_of_groupMixin.\nCanonical Structure coset_groupType := FinGroupType coset_invP.\n\n(* Projection of the initial group type over the cosets groupType  *)\n\nDefinition coset x : coset_of := insubd (1 : coset_of) (H :* x).\n\n(* This is a primitive lemma -- we'll need to restate it for *)\n(* the case where A is a group. *)\nLemma val_coset_prim : forall x, x \\in 'N(A) -> coset x :=: H :* x.\nProof.\nby move=> x Nx; rewrite val_insubd /= mem_rcosets -{1}(mul1g x) mem_mulg.\nQed.\n\nLemma coset_morphM : {in 'N(A) &, {morph coset : x y / x * y}}.\nProof.\nmove=> x y Nx Ny; apply: val_inj.\nby rewrite /= !val_coset_prim ?groupM //= rcoset_mul ?nNH.\nQed.\n\nCanonical Structure coset_morphism := Morphism coset_morphM.\n\nLemma ker_coset_prim : 'ker coset = 'N_H(A).\nProof.\napply/setP=> z; rewrite !in_setI andbC 2!inE -val_eqE /=.\ncase Nz: (z \\in 'N(A)); rewrite ?andbF ?val_coset_prim // !andbT.\nby apply/eqP/idP=> [<-| Az]; rewrite (rcoset_refl, rcoset_id).\nQed.\n\nImplicit Type xbar : coset_of.\n\nLemma coset_mem : forall y xbar, y \\in xbar -> coset y = xbar.\nProof.\nmove=> y [/= Hx NHx] /= Hxy; apply: val_inj=> /=.\ncase/rcosetsP: NHx (NHx) Hxy => x Nx -> NHx Hxy.\nby rewrite val_insubd /= (rcoset_transl Hxy) NHx.\nQed.\n\n(* coset is an inverse to repr *)\n\nLemma mem_repr_coset : forall xbar, repr xbar \\in xbar.\nProof. case=> xbar /=; case/rcosetsP=> x _ ->; exact: mem_repr_rcoset. Qed.\n\nLemma repr_coset1 : repr (1 : coset_of) = 1.\nProof. exact: repr_group. Qed.\n\nLemma coset_reprK : cancel (fun xbar => repr xbar) coset.\nProof. move=> xbar; exact: coset_mem (mem_repr_coset xbar). Qed.\n\n(* cosetP is slightly stronger than using repr because we only *)\n(* guarantee  repr xbar \\in 'N(A) when A is a group.           *)\nLemma cosetP : forall xbar, {x | x \\in 'N(A) & xbar = coset x}.\nProof.\nmove=> xbar; pose x := repr 'N_xbar(A).\nhave [xbar_x Nx]: x \\in xbar /\\ x \\in 'N(A).\n  apply/setIP; rewrite {}/x; case: xbar => Hy /=.\n  by case/rcosetsP=> y Ny ->; apply: (@mem_repr _ y); rewrite inE rcoset_refl.\nby exists x; last rewrite (coset_mem xbar_x).\nQed.\n\nLemma coset_id : forall x, x \\in A -> coset x = 1.\nProof. move=> x Ax; apply: coset_mem; exact: mem_gen. Qed.\n\nLemma coset_imT : coset @* 'N(A) = setT.\nProof.\nby apply/setP=> xbar; case: (cosetP xbar) => x Nx ->; rewrite inE mem_morphim.\nQed.\n\nLemma coset_im : forall C : {set coset_of}, C \\subset coset @* 'N(A).\nProof. by move=> C; rewrite coset_imT subsetT. Qed.\n\nDefinition quotient : {set coset_of} := coset @* Q.\n\nLemma quotientE : quotient = coset @* Q. Proof. by []. Qed.\n\nEnd Cosets.\n\nPrenex Implicits coset_of coset.\nArguments Scope quotient [_ group_scope group_scope].\n\nBind Scope group_scope with coset_of.\n\nNotation \"A / B\" := (quotient A B) : group_scope.\n\nSection CosetOfGroupTheory.\n\nVariables (gT : finGroupType) (H : {group gT}).\nImplicit Types A B : {set gT}.\nImplicit Types G K : {group gT}.\nImplicit Types xbar yb : coset_of H.\nImplicit Types C D : {set coset_of H}.\nImplicit Types L M : {group coset_of H}.\n\nCanonical Structure quotient_group G A : {group coset_of A} :=\n  Eval hnf in [group of G / A].\n\nInfix \"/\" := quotient_group : subgroup_scope.\n\nLemma val_coset : forall x, x \\in 'N(H) -> coset H x :=: H :* x.\nProof. by move=> x Nx; rewrite val_coset_prim // genGid. Qed.\n\nLemma coset_default : forall x, (x \\in 'N(H)) = false -> coset H x = 1.\nProof.\nmove=> x Nx; apply: val_inj.\nby rewrite val_insubd /= mem_rcosets /= genGid mulSGid ?normG ?Nx.\nQed.\n\nLemma coset_norm : forall xbar, xbar \\subset 'N(H).\nProof.\ncase=> Hx /=; case/rcosetsP=> x Nx ->.\nby rewrite genGid mul_subG ?sub1set ?normG.\nQed.\n\nLemma ker_coset : 'ker (coset H) = H.\nProof. by rewrite ker_coset_prim genGid (setIidPl _) ?normG. Qed.\n\nLemma coset_idr : forall x, x \\in 'N(H) -> coset H x = 1 -> x \\in H.\nProof. by move=> x Nx Hx1; rewrite -ker_coset mem_morphpre //= Hx1 set11. Qed.\n\nLemma repr_coset_norm : forall xbar, repr xbar \\in 'N(H).\nProof. move=> xbar; exact: subsetP (coset_norm _) _ (mem_repr_coset _). Qed.\n\nLemma imset_coset : forall G, coset H @: G = G / H.\nProof.\nmove=> G; apply/eqP; rewrite eqEsubset andbC imsetS ?subsetIr //=.\napply/subsetP=> xbar; case/imsetP=> x Gx -> {xbar}.\nby case Nx: (x \\in 'N(H)); rewrite ?(coset_default Nx) ?mem_morphim ?group1.\nQed.\n\nLemma val_quotient : forall A, val @: (A / H) = rcosets H 'N_A(H).\nProof.\nmove=> A; apply/setP=> B; apply/imsetP/rcosetsP=> [[xbar Axbar]|[x ANx]] ->{B}.\n  case/morphimP: Axbar => x Nx Ax ->{xbar}.\n  by exists x; [rewrite inE Ax | rewrite /= val_coset].\ncase/setIP: ANx => Ax Nx.\nby exists (coset H x); [apply/morphimP; exists x | rewrite /= val_coset].\nQed.\n\nLemma card_quotient_subnorm : forall A, #|A / H| = #|'N_A(H) : H|.\nProof. by move=> A; rewrite -(card_imset _ val_inj) val_quotient. Qed.\n\nLemma card_quotient : forall A, A \\subset 'N(H) -> #|A / H| = #|A : H|.\nProof. by move=> A nHA; rewrite card_quotient_subnorm (setIidPl nHA). Qed.\n\n(* Specializing all the morphisms lemmas that have different assumptions    *)\n(* (e.g., because 'ker (coset H) = H), or conclusions (e.g., because we use *)\n(* A / H rather than coset H @* A). We may want to reevaluate later, and    *)\n(* eliminate variants that aren't used                                  .   *)\n\n(* Variant of morph1; no specialization for other morph lemmas. *)\nLemma coset1 : coset H 1 :=: H.\nProof. by rewrite morph1 /= genGid. Qed.\n\n(* Variant of kerE. *)\nLemma cosetpre1 : coset H @*^-1 1 = H.\nProof. by rewrite -kerE ker_coset. Qed.\n\n(* Variant of morphimEdom; mophimE[sub] covered by imset_coset. *)\n(* morph[im|pre]Iim are also covered by quotientT.              *)\nLemma quotientT : 'N(H) / H = setT.\nProof. exact: coset_imT. Qed.\n\n(* Variant of morphimIdom. *)\nLemma quotientInorm : forall A, 'N_A(H) / H = A / H.\nProof. by move=> A; rewrite /quotient setIC morphimIdom. Qed.\n\nLemma mem_quotient : forall x G, x \\in G -> coset H x \\in G / H.\nProof. by move=> x G Gx; rewrite -imset_coset mem_imset. Qed.\n\nLemma quotientS : forall A B, A \\subset B -> A / H \\subset B / H.\nProof. exact: morphimS. Qed.\n\nLemma quotient0 : set0 / H = set0.\nProof. exact: morphim0. Qed.\n\nLemma quotient_set1 : forall x, x \\in 'N(H) -> [set x] / H = [set coset H x].\nProof. exact: morphim_set1. Qed.\n\nLemma quotient1 : 1 / H = 1.\nProof. exact: morphim1. Qed.\n\nLemma quotientV : forall A, A^-1 / H = (A / H)^-1.\nProof. exact: morphimV. Qed.\n\nLemma quotientMl : forall A B,\n  A \\subset 'N(H) -> A * B / H = (A / H) * (B / H).\nProof. exact: morphimMl. Qed.\n\nLemma quotientMr : forall A B,\n  B \\subset 'N(H) -> A * B / H = (A / H) * (B / H).\nProof. exact: morphimMr. Qed.\n\nLemma cosetpreM : forall C D,\n  coset H @*^-1 (C * D) = coset H @*^-1 C * coset H @*^-1 D.\nProof. by move=> C D; rewrite morphpreMl ?coset_im. Qed.\n\nLemma quotientJ : forall A x, x \\in 'N(H) -> A :^ x / H = (A / H) :^ coset H x.\nProof. exact: morphimJ. Qed.\n\nLemma quotientU : forall A B, (A :|: B) / H = A / H :|: B / H.\nProof. exact: morphimU. Qed.\n\nLemma quotientI : forall A B, (A :&: B) / H \\subset A / H :&: B / H.\nProof. exact: morphimI. Qed.\n\nLemma coset_kerl : forall x y, x \\in H -> coset H (x * y) = coset H y.\nProof.\nmove=> x y Hx; case Ny: (y \\in 'N(H)); first by rewrite mkerl ?ker_coset.\nby rewrite !coset_default ?groupMl // (subsetP (normG H)).\nQed.\n\nLemma coset_kerr : forall x y, y \\in H -> coset H (x * y) = coset H x.\nProof.\nmove=> x y Hy; case Nx: (x \\in 'N(H)); first by rewrite mkerr ?ker_coset.\nby rewrite !coset_default ?groupMr // (subsetP (normG H)).\nQed.\n\nLemma rcoset_kercosetP : forall x y,\n  x \\in 'N(H) -> y \\in 'N(H) -> reflect (coset H x = coset H y) (x \\in H :* y).\nProof. rewrite -{6}ker_coset; exact: rcoset_kerP. Qed.\n\nLemma kercoset_rcoset : forall x y,\n  x \\in 'N(H) -> y \\in 'N(H) ->\n    coset H x = coset H y -> exists2 z, z \\in H & x = z * y.\nProof. move=> x y Gx Gy eqfxy; rewrite -ker_coset; exact: ker_rcoset. Qed.\n\nLemma quotientGI : forall G A, H \\subset G -> (G :&: A) / H = G / H :&: A / H.\nProof. rewrite -{1}ker_coset; exact: morphimGI. Qed.\n\nLemma quotientIG : forall A G, H \\subset G -> (A :&: G) / H = A / H :&: G / H.\nProof. rewrite -{1}ker_coset. exact: morphimIG. Qed.\n\nLemma quotientD : forall A B, A / H :\\: B / H \\subset (A :\\: B) / H.\nProof. exact: morphimD. Qed.\n\nLemma quotientDG : forall A G, H \\subset G -> (A :\\: G) / H = A / H :\\: G / H.\nProof. rewrite -{1}ker_coset; exact: morphimDG. Qed.\n\nLemma quotientK : forall A, A \\subset 'N(H) -> coset H @*^-1 (A / H) = H * A.\nProof. rewrite -{8}ker_coset; exact: morphimK. Qed.\n\nLemma quotientGK : forall G, H <| G -> coset H @*^-1 (G / H) = G.\nProof. move=> G; case/andP; rewrite -{1}ker_coset; exact: morphimGK. Qed.\n\nLemma cosetpre_set1 : forall x,\n  x \\in 'N(H) -> coset H @*^-1 [set coset H x] = H :* x.\nProof. by rewrite -{9}ker_coset; exact: morphpre_set1. Qed.\n\nLemma cosetpre_set1_coset : forall xbar, coset H @*^-1 [set xbar] = xbar.\nProof.\nmove=> xbar; case: (cosetP xbar) => x Nx ->.\nby rewrite cosetpre_set1 ?val_coset.\nQed.\n\nLemma cosetpreK : forall C, coset H @*^-1 C / H = C.\nProof. by move=> C; rewrite /quotient morphpreK ?coset_im. Qed.\n\n(* Variant of morhphim_ker *)\nLemma trivg_quotient : H / H = 1.\nProof. by rewrite -{3}ker_coset /quotient morphim_ker. Qed.\n\nLemma sub_cosetpre : forall M, H \\subset coset H @*^-1 M.\nProof. rewrite -{3}ker_coset; exact: ker_sub_pre. Qed.\n\nLemma normal_cosetpre : forall M, H <| coset H @*^-1 M.\nProof. rewrite -{3}ker_coset; exact: ker_normal_pre. Qed.\n\nLemma cosetpreSK : forall C D,\n  (coset H @*^-1 C \\subset coset H @*^-1 D) = (C \\subset D).\nProof. by move=> C D; rewrite morphpreSK ?coset_im. Qed.\n\nLemma sub_quotient_pre : forall A C,\n  A \\subset 'N(H) -> (A / H \\subset C) = (A \\subset coset H @*^-1 C).\nProof. by move=> A C; exact: sub_morphim_pre. Qed.\n\nLemma sub_cosetpre_quo : forall C G,\n  H <| G -> (coset H @*^-1 C \\subset G) = (C \\subset G / H).\nProof. by move=> C G nHG; rewrite -cosetpreSK quotientGK. Qed.\n\n(* Variant of ker_trivg_morphim. *)\nLemma quotient_sub1 : forall A,\n  A \\subset 'N(H) -> (A / H \\subset [1]) = (A \\subset H).\nProof. by move=> A nHA /=; rewrite -{10}ker_coset ker_trivg_morphim nHA. Qed.\n\nLemma quotientSK : forall A B,\n  A \\subset 'N(H) -> (A / H \\subset B / H) = (A \\subset H * B).\nProof. by move=> A B nHA; rewrite morphimSK ?ker_coset. Qed.\n\nLemma quotientSGK : forall A G,\n  A \\subset 'N(H) -> H \\subset G -> (A / H \\subset G / H) = (A \\subset G).\nProof. rewrite -{2}ker_coset; exact: morphimSGK. Qed.\n\nLemma quotient_injG :\n  {in [pred G : {group gT} | H <| G] &, injective (fun G => G / H)}.\nProof. rewrite /normal -{1}ker_coset; exact: morphim_injG. Qed.\n\nLemma quotient_inj : forall G1 G2,\n   H <| G1 -> H <| G2 -> G1 / H = G2 / H -> G1 :=: G2.\nProof. rewrite /normal -{1 3}ker_coset; exact: morphim_inj. Qed.\n\nLemma quotient_gen : forall A, A \\subset 'N(H) -> <<A>> / H = <<A / H>>.\nProof. exact: morphim_gen. Qed.\n\nLemma cosetpre_gen : forall C,\n  1 \\in C -> coset H @*^-1 <<C>> = <<coset H @*^-1 C>>.\nProof. by move=> C C1; rewrite morphpre_gen ?coset_im. Qed.\n\nLemma quotientR : forall A B,\n  A \\subset 'N(H) -> B \\subset 'N(H) -> [~: A, B] / H = [~: A / H, B / H].\nProof. exact: morphimR. Qed.\n\nLemma quotient_norm : forall A, 'N(A) / H \\subset 'N(A / H).\nProof. exact: morphim_norm. Qed.\n\nLemma quotient_norms : forall A B, A \\subset 'N(B) -> A / H \\subset 'N(B / H).\nProof. exact: morphim_norms. Qed.\n\nLemma quotient_subnorm : forall A B, 'N_A(B) / H \\subset 'N_(A / H)(B / H).\nProof. exact: morphim_subnorm. Qed.\n\nLemma quotient_normal : forall A B, A <| B -> A / H <| B / H.\nProof. exact: morphim_normal. Qed.\n\nLemma quotient_cent1 : forall x, 'C[x] / H \\subset 'C[coset H x].\nProof.\nmove=> x; case Nx: (x \\in 'N(H)); first exact: morphim_cent1.\nby rewrite coset_default // cent11T subsetT.\nQed.\n\nLemma quotient_cent1s : forall A x,\n  A \\subset 'C[x] -> A / H \\subset 'C[coset H x].\nProof.\nmove=> A x sAC; exact: subset_trans (quotientS sAC) (quotient_cent1 x).\nQed.\n\nLemma quotient_subcent1 : forall A x,\n  'C_A[x] / H \\subset 'C_(A / H)[coset H x].\nProof.\nmove=> A x; exact: subset_trans (quotientI _ _) (setIS _ (quotient_cent1 x)).\nQed.\n\nLemma quotient_cent : forall A, 'C(A) / H \\subset 'C(A / H).\nProof. exact: morphim_cent. Qed.\n\nLemma quotient_cents : forall A B,\n  A \\subset 'C(B) -> A / H \\subset 'C(B / H).\nProof. exact: morphim_cents. Qed.\n\nLemma quotient_abelian : forall A, abelian A -> abelian (A / H).\nProof. exact: morphim_abelian. Qed.\n\nLemma quotient_subcent : forall A B, 'C_A(B) / H \\subset 'C_(A / H)(B / H).\nProof. exact: morphim_subcent. Qed.\n\nLemma cosetpre_normal : forall C D,\n  (coset H @*^-1 C <| coset H @*^-1 D) = (C <| D).\nProof. by move=> C D; rewrite morphpre_normal ?coset_im. Qed.\n\nLemma quotient_normG : forall G, H <| G -> 'N(G) / H = 'N(G / H).\nProof.\nmove=> G; case/andP=> sHG nHG.\nby rewrite [_ / _]morphim_normG ?ker_coset // coset_imT setTI.\nQed.\n\nLemma quotient_subnormG : forall A G,\n   H <| G -> 'N_A(G) / H = 'N_(A / H)(G / H).\nProof.\nby move=> A G; case/andP=> sHG nHG; rewrite -morphim_subnormG ?ker_coset.\nQed.\n\nLemma cosetpre_cent1 : forall x,\n  'C_('N(H))[x] \\subset coset H @*^-1 'C[coset H x].\nProof.\nmove=> x; case Nx: (x \\in 'N(H)); first by rewrite morphpre_cent1.\nby rewrite coset_default // cent11T morphpreT subsetIl.\nQed.\n\nLemma cosetpre_cent1s : forall C x,\n  coset H @*^-1 C \\subset 'C[x] -> C \\subset 'C[coset H x].\nProof.\nmove=> C x sC; rewrite -cosetpreSK; apply: subset_trans (cosetpre_cent1 x).\nby rewrite subsetI subsetIl.\nQed.\n\nLemma cosetpre_subcent1 : forall C x,\n  'C_(coset H @*^-1 C)[x] \\subset coset H @*^-1 'C_C[coset H x].\nProof.\nmove=> C x; rewrite -morphpreIdom -setIA setICA morphpreI setIS //.\nexact: cosetpre_cent1.\nQed.\n\nLemma cosetpre_cent : forall A, 'C_('N(H))(A) \\subset coset H @*^-1 'C(A / H).\nProof. exact: morphpre_cent. Qed.\n\nLemma cosetpre_cents : forall A C,\n  coset H @*^-1 C \\subset 'C(A) -> C \\subset 'C(A / H).\nProof. by move=> A C; apply: morphpre_cents; rewrite ?coset_im. Qed.\n\nLemma cosetpre_subcent : forall C A,\n  'C_(coset H @*^-1 C)(A) \\subset coset H @*^-1 'C_C(A / H).\nProof. exact: morphpre_subcent. Qed.\n\nSection InverseImage.\n\nVariables (G : {group gT}) (Kbar : {group coset_of H}).\n\nHypothesis nHG : H <| G.\n\nCoInductive inv_quotient_spec (P : pred {group gT}) : Prop :=\n  InvQuotientSpec K of Kbar :=: K / H & H \\subset K & P K.\n\nLemma inv_quotientS :\n  Kbar \\subset G / H -> inv_quotient_spec (fun K => K \\subset G).\nProof.\ncase/andP: nHG => sHG nHG' sKbarG.\nhave sKdH: Kbar \\subset 'N(H) / H by rewrite (subset_trans sKbarG) ?morphimS.\nexists (coset H @*^-1 Kbar)%G; first by rewrite cosetpreK.\n  by rewrite -{1}ker_coset morphpreS ?sub1G.\nby rewrite sub_cosetpre_quo.\nQed.\n\nLemma inv_quotientN : Kbar <| G / H -> inv_quotient_spec (fun K => K <| G).\nProof.\nmove=> nKbar; case/inv_quotientS: (normal_sub nKbar) => K defKbar sHK sKG.\nexists K => //; rewrite defKbar -cosetpre_normal !quotientGK // in nKbar.\nexact: normalS nHG.\nQed.\n\nEnd InverseImage.\n\nLemma quotient_mulg : forall A, A * H / H = A / H.\nProof.\nmove=> A; rewrite [_ /_]morphimMr ?normG //= -!quotientE.\nby rewrite trivg_quotient mulg1.\nQed.\n\nLemma quotient_mulgr : forall A, H * A / H = A / H.\nProof.\nmove=> A; rewrite [_ /_]morphimMl ?normG //= -!quotientE.\nby rewrite trivg_quotient mul1g.\nQed.\n\nLemma quotient_mulgen : forall G, G \\subset 'N(H) -> G <*> H / H = G / H.\nProof.\nmove=> G nHG; rewrite -genM_mulgen quotientE morphim_gen -?quotientE.\n  by rewrite quotient_mulg genGid.\nby rewrite -(mulSGid nHG) mulgS ?normG.\nQed.\n\nSection Injective.\n\nVariables (G : {group gT}).\nHypotheses (nHG : G \\subset 'N(H)) (trGH : G :&: H = 1).\n\nLemma quotient_isom : isom G (G / H) (restrm nHG (coset H)).\nProof.\nby apply/isomP; rewrite ker_restrm ker_coset morphim_restrm setIid trGH.\nQed.\n\nLemma quotient_isog : isog G (G / H).\nProof. exact: isom_isog quotient_isom. Qed.\n\nEnd Injective.\n\nEnd CosetOfGroupTheory.\n\nNotation \"A / H\" := (quotient_group A H) : subgroup_scope.\n\nSection Quotient1.\n\nVariables (gT : finGroupType) (A : {set gT}).\n\nLemma coset1_injm : 'injm (@coset gT 1).\nProof. by rewrite ker_coset /=. Qed.\n\nLemma quotient1_isom : isom A (A / 1) (coset 1).\nProof. by apply: sub_isom coset1_injm; rewrite ?norms1. Qed.\n\nLemma quotient1_isog : isog A (A / 1).\nProof. apply: isom_isog quotient1_isom; exact: norms1. Qed.\n\nEnd Quotient1.\n\nSection QuotientMorphism.\n\nVariable (gT : finGroupType) (G H : {group gT}) (f : {morphism G >-> gT}).\n\nImplicit Types A : {set gT}.\nImplicit Types B : {set (coset_groupType H)}.\nHypotheses (nHG : H <| G) (nGf : f @* G = G) (nHf : f @* H = H).\n\nNotation fH := (coset H \\o f).\n\nLemma quotm_restr_proof : G \\subset 'dom fH.\nProof. by rewrite -sub_morphim_pre // nGf; case/andP: nHG. Qed.\n\nNotation fH_G := (restrm quotm_restr_proof fH).\n\nLemma quotm_fact_proof1 : G \\subset 'N(H).\nProof. by case/andP: nHG. Qed.\n\nLemma quotm_fact_proof2 : 'ker (coset H) \\subset 'ker fH_G.\nProof.\ncase/andP: nHG => sHG _; rewrite ker_restrm ker_comp ker_coset subsetI.\nby rewrite -sub_morphim_pre sHG ?nHf /=.\nQed.\n\nDefinition quotm := factm quotm_fact_proof1 quotm_fact_proof2.\nCanonical Structure quotm_morphism := Eval hnf in [morphism of quotm].\n\nLemma morphim_quotm : forall A, quotm @* (A / H) = f @* A / H.\nProof.\ncase/andP: nHG => sHG nHG' A.\nby rewrite morphim_factm morphim_restrm morphim_comp morphimIdom.\nQed.\n\nLemma cosetpre_quotm : forall A,\n  quotm @*^-1 (A / H) = f @*^-1 A / H.\nProof.\ncase/andP: nHG => sHG nHG' A; rewrite morphpre_factm morphpre_restrm.\nrewrite morphpre_comp morphpreIdom quotientE -(morphimIdom _ A) /= -quotientE.\nrewrite morphimK ?subsetIl // ker_coset morphpreMl ?nGf // -{3}nHf morphimK //.\nrewrite -morphpreIim setIA -(morphpreIim _ A) !nGf (setIidPl nHG').\nrewrite [_ * H]normC; last by apply: subset_trans nHG'; rewrite subsetIl.\nby rewrite -mulgA quotient_mulgr -morphpreMl (mul1g, sub1G).\nQed.\n\nLemma ker_quotm : 'ker quotm = 'ker f / H.\nProof. by rewrite -cosetpre_quotm /quotient morphim1. Qed.\n\nLemma injm_quotm : 'injm f -> 'injm quotm.\nProof. by move/trivgP=> /= kf1; rewrite ker_quotm kf1 quotientE morphim1. Qed.\n\nEnd QuotientMorphism.\n\nSection FirstIsomorphism.\n\nVariables aT rT : finGroupType.\n\nLemma first_isom : forall (G : {group aT}) (f : {morphism G >-> rT}),\n  {g : {morphism G / 'ker f >-> rT} | 'injm g &\n      forall A : {set aT}, g @* (A / 'ker f) = f @* A}.\nProof.\nmove=> G f; have nkG := ker_norm f.\nhave skk: 'ker (coset ('ker f)) \\subset 'ker f by rewrite ker_coset.\nexists (factm_morphism nkG skk) => /=; last exact: morphim_factm.\nby rewrite ker_factm -quotientE trivg_quotient.\nQed.\n\nVariables (G H : {group aT}) (f : {morphism G >-> rT}).\nHypothesis sHG : H \\subset G.\n\nLemma first_isog : (G / 'ker f) \\isog (f @* G).\nProof.\nby case: (first_isom f) => g injg im_g; apply/isogP; exists g; rewrite ?im_g.\nQed.\n\nLemma first_isom_loc : {g : {morphism H / 'ker_H f >-> rT} |\n 'injm g & forall A : {set aT}, A \\subset H -> g @* (A / 'ker_H f) = f @* A}.\nProof.\ncase: (first_isom (restrm_morphism sHG f)).\nrewrite ker_restrm => g injg im_g; exists g => // A sAH.\nby rewrite im_g morphim_restrm (setIidPr sAH).\nQed.\n\nLemma first_isog_loc : (H / 'ker_H f) \\isog (f @* H).\nProof.\nby case: first_isom_loc => g injg im_g; apply/isogP; exists g; rewrite ?im_g.\nQed.\n\nEnd FirstIsomorphism.\n\nSection SecondIsomorphism.\n\nVariables (gT : finGroupType) (H K : {group gT}).\n\nHypothesis nKH : H \\subset 'N(K).\n\nLemma second_isom : {f : {morphism H / (K :&: H) >-> coset_of K} |\n  'injm f & forall A : {set gT}, A \\subset H -> f @* (A / (K :&: H)) = A / K}.\nProof.\nhave ->: K :&: H = 'ker_H (coset K) by rewrite ker_coset setIC.\nexact: first_isom_loc.\nQed.\n\nLemma second_isog : H / (K :&: H) \\isog H / K.\nProof. rewrite setIC -{1 3}(ker_coset K); exact: first_isog_loc. Qed.\n\nLemma weak_second_isog : H / (K :&: H) \\isog H * K / K.\nProof. rewrite quotient_mulg; exact: second_isog. Qed.\n\nEnd SecondIsomorphism.\n\nSection ThirdIsomorphism.\n\nVariables (gT : finGroupType) (G H K : {group gT}).\n\nHypothesis sHK : H \\subset K.\nHypothesis snHG : H <| G.\nHypothesis snKG : K <| G.\n\nTheorem third_isom : {f : {morphism (G / H) / (K / H) >-> coset_of K} | 'injm f\n   & forall A : {set gT}, A \\subset G -> f @* (A / H / (K / H)) = A / K}.\nProof.\ncase/andP: snKG => sKG nKG; case/andP: snHG => sHG nHG.\nhave sHker: 'ker (coset H) \\subset 'ker (restrm nKG (coset K)).\n  by rewrite ker_restrm !ker_coset subsetI sHG.\nhave:= first_isom_loc (factm_morphism nHG sHker) (subxx _) => /=.\nrewrite ker_factm_loc ker_restrm ker_coset !(setIidPr sKG) /= -!quotientE.\ncase=> f injf im_f; exists f => // A sAG; rewrite im_f ?morphimS //.\nby rewrite morphim_factm morphim_restrm (setIidPr sAG).\nQed.\n\nTheorem third_isog : (G / H / (K / H)) \\isog (G / K).\nProof.\nby case: third_isom => f inj_f im_f; apply/isogP; exists f; rewrite ?im_f.\nQed.\n\nEnd ThirdIsomorphism.\n\nLemma char_from_quotient : forall (gT : finGroupType) (G H K : {group gT}),\n  H <| K -> H \\char G -> K / H \\char G / H -> K \\char G.\nProof.\nmove=> gT G H K; case/andP=> sHK nHK chHG; case/charP=> sKG chKG.\nhave nHG := char_normal chHG; case: (andP nHG) => sHG nHG'.\nrewrite -(ker_coset H) in sHK; rewrite morphimSGK ?ker_coset // in sKG.\napply/charP; split=> // f injf Gf; apply/morphim_fixP => //.\nhave{chHG} Hf: f @* H = H by case/charP: chHG => _; apply.\nrewrite -(morphimSGK _ sHK) -?quotientE; last first.\n  by apply: subset_trans nHG'; rewrite -{3}Gf morphimS.\nrewrite -(morphim_quotm nHG Gf Hf) {}chKG // ?injm_quotm //.\nby rewrite morphim_quotm Gf.\nQed.\n\n(* Counting lemmas for morphisms. *)\n\nSection CardMorphism.\n\nVariables (aT rT : finGroupType) (D : {group aT}) (f : {morphism D >-> rT}).\nImplicit Types G H : {group aT}.\nImplicit Types L M : {group rT}.\n\nLemma card_morphim : forall G, #|f @* G| = #|D :&: G : 'ker f|.\nProof.\nmove=> G; rewrite -morphimIdom -indexgI -card_quotient; last first.\n  by rewrite normsI ?normG ?subIset ?ker_norm.\nby apply: esym (isog_card _); rewrite first_isog_loc ?subsetIl.\nQed.\n\nLemma dvdn_morphim :  forall G, #|f @* G| %| #|G|.\nProof.\nmove=> G; rewrite card_morphim (dvdn_trans (dvdn_indexg _ _)) //.\nby rewrite cardSg ?subsetIr.\nQed.\n\nLemma index_morphim_ker : forall G H,\n    H \\subset G -> G \\subset D ->\n  (#|f @* G : f @* H| * #|'ker_G f : H|)%N = #|G : H|.\nProof.\nmove=> G H sHG sGD; apply/eqP.\nrewrite -(eqn_pmul2l (cardG_gt0 (f @* H))) mulnA LaGrange ?morphimS //.\nrewrite !card_morphim (setIidPr sGD) (setIidPr (subset_trans sHG sGD)).\nrewrite -(eqn_pmul2l (cardG_gt0 ('ker_H f))) /=.\nby rewrite -{1}(setIidPr sHG) setIAC mulnCA mulnC mulnA !LaGrangeI LaGrange.\nQed.\n\nLemma index_morphim : forall G H,\n  G :&: H \\subset D -> #|f @* G : f @* H| %| #|G : H|.\nProof.\nmove=> G H dGH; rewrite -(indexgI G) -(setIidPr dGH) setIA.\napply: dvdn_trans (indexSg (subsetIl _ H) (subsetIr D G)).\nrewrite -index_morphim_ker ?subsetIl ?subsetIr ?dvdn_mulr //= morphimIdom.\nby rewrite indexgS ?morphimS ?subsetIr.\nQed.\n\nLemma index_injm : forall G H,\n  'injm f -> G \\subset D -> #|f @* G : f @* H| = #|G : H|.\nProof.\nmove=> G H injf dG; rewrite -{2}(setIidPr dG) -(indexgI _ H) /=.\nrewrite -index_morphim_ker ?subsetIl ?subsetIr //= setIAC morphimIdom setIC.\nrewrite injmI ?subsetIr // indexgI /= morphimIdom setIC ker_injm //.\nby rewrite -(indexgI (1 :&: _)) /= -setIA !(setIidPl (sub1G _)) indexgg muln1.\nQed.\n\nLemma card_morphpre : forall L,\n  L \\subset f @* D -> #|f @*^-1 L| = (#|'ker f| * #|L|)%N.\nProof.\nmove=> L; move/morphpreK=> defL; rewrite -{2}defL card_morphim morphpreIdom.\nby rewrite LaGrange // morphpreS ?sub1G.\nQed.\n\nLemma index_morphpre : forall L M,\n  L \\subset f @* D -> #|f @*^-1 L : f @*^-1 M| = #|L : M|.\nProof.\nmove=> L M dL; rewrite -!divgI -morphpreI card_morphpre //.\nhave: L :&: M \\subset f @* D by rewrite subIset ?dL.\nby move/card_morphpre->; rewrite divn_pmul2l ?cardG_gt0.\nQed.\n\nEnd CardMorphism.\n\nSection CardCosetpre.\n\nVariables (gT : finGroupType) (G H K : {group gT}) (L M : {group coset_of H}).\n\nLemma dvdn_quotient : #|G / H| %| #|G|.\nProof. exact: dvdn_morphim. Qed.\n\nLemma index_quotient_ker :\n     K \\subset G -> G \\subset 'N(H) ->\n  (#|G / H : K / H| * #|G :&: H : K|)%N = #|G : K|.\nProof. rewrite -{5}(ker_coset H); exact: index_morphim_ker. Qed.\n\nLemma index_quotient : G :&: K \\subset 'N(H) -> #|G / H : K / H| %| #|G : K|.\nProof. exact: index_morphim. Qed.\n\nLemma index_quotient_eq :\n    G :&: H \\subset K -> K \\subset G -> G \\subset 'N(H) ->\n #|G / H : K / H| = #|G : K|.\nProof.\nmove=> sGH_K sKG sGN; rewrite -index_quotient_ker {sKG sGN}//.\nby rewrite -(indexgI _ K) (setIidPl sGH_K) indexgg muln1.\nQed.\n\nLemma card_cosetpre : #|coset H @*^-1 L| = (#|H| * #|L|)%N.\nProof. by rewrite card_morphpre ?ker_coset ?coset_im. Qed.\n\nLemma index_cosetpre : #|coset H @*^-1 L : coset H @*^-1 M| = #|L : M|.\nProof. by rewrite index_morphpre ?coset_im. Qed.\n\nEnd CardCosetpre.\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/normal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6627654421715591}}
{"text": "\nRequire Import SfLib.\n\nRequire Import Smallstep.\n\nRequire Import Coq.Relations.Relation_Definitions.\n\n\nInductive Context {type : Type} : Type :=\n| empty : Context\n| update : id -> type -> Context -> Context.\n\nHint Constructors Context.\n\nFixpoint byContext {type : Type} (ctx : Context) (i : id) : option type :=\nmatch ctx with \n    | empty => None\n    | update x Ty ctx' =>\n        if (eq_id_dec i x) then Some Ty else byContext ctx' i\n        end.\n\n\nDefinition context_equivalence {type : Type}  : relation Context :=\n        fun (x y : Context (type := type)) => forall i, byContext x i = byContext y i.\n    \n    Notation \"x '=-=' y\" := (context_equivalence x y) (at level 40).\n    \n    \n    Print reflexive.\n    Print equiv.\n\n    \n    Theorem refl_ctxeq {x : Type}:\n        reflexive _ (context_equivalence (type := x )).\n        unfold reflexive; unfold context_equivalence. auto.\n    Qed.\n    \n    Hint Unfold reflexive.\n\n    Theorem symm_ctxeq {x : Type}:\n        symmetric _ (context_equivalence (type := x)).\n        unfold symmetric; unfold context_equivalence. auto.\n    Qed.\n\n    Hint Unfold symmetric.\n    Theorem trans_ctxeq {x : Type}:\n    transitive _ (context_equivalence (type :=x)).\n\n    unfold transitive.\n    \n    unfold context_equivalence.\n    intros. rewrite H; auto.\nQed.\n\nHint Unfold transitive.\n\nTheorem equiv_ctxeq {x : Type}:\n    equiv _ (context_equivalence (type := x)).\n\n    unfold equiv.\n    pose (refl_ctxeq (x := x)). pose (symm_ctxeq (x := x)). pose (trans_ctxeq (x:= x)).\n    tauto.\nQed.\n    \n    Theorem update_shadow {z : Type}:\n        forall i (x y : z) (U V : Context (type := z)),\n            U =-= V ->\n            update i x (update i y U) =-= update i x V.\n            \n        unfold context_equivalence. intros.\n        cbn. destruct (eq_id_dec i0 i); auto.\n    \n    Qed.\n    \n    Theorem update_permute {z : Type}:\n        forall i j (x y : z) U V,\n            i <> j ->\n            U =-= V ->\n            update i x (update j y U) =-= update j y (update i x U).\n    \n        unfold context_equivalence. \n        intros. cbn. destruct (eq_id_dec i0 i); destruct (eq_id_dec i0 j); auto; subst.\n        destruct (H eq_refl).\n    Qed.\n    \n    Theorem update_inc {z : Type}:\n        forall i (x: z) U V,\n            U =-= V ->\n            update i x U =-= update i x V.\n    \n        unfold context_equivalence.\n        intros. cbn. destruct (eq_id_dec i0 i); subst; auto.\n    Qed.\n\n\n\n\nModule STLCARITH.\n\n\nInductive ty : Type :=\n    | TArrow : ty -> ty -> ty\n    | TNat : ty.\n\n    Hint Constructors ty.\nInductive tm : Type :=\n    | tvar : id -> tm \n    | tapp : tm -> tm -> tm\n    | tabs : id -> ty -> tm -> tm \n    | tnat : nat -> tm \n    | tsucc : tm -> tm \n    | tpred : tm -> tm \n    | tmult : tm -> tm -> tm \n    | tif0 : tm -> tm -> tm -> tm.\n\n(* Weak Typing. 0 as False, others are true. *)\n\n    Hint Constructors tm.\n\nReserved Notation \"Gamma '|=' t '\\in' T\" (at level 40).            \n\nInductive has_type : Context -> tm -> ty -> Prop :=\n    | tyVar : \n        forall G i T,\n            byContext G i = Some T ->\n            G |= tvar i \\in T\n    | tyApp :\n        forall Gamma a b G T,\n        Gamma |= a \\in TArrow G T ->\n        Gamma |= b \\in G ->\n        Gamma |= tapp a b \\in T\n    | tyAbs :\n        forall Gamma i x G T,\n        update i G Gamma |= x \\in T ->\n        Gamma |= tabs i G x \\in TArrow G T\n    | tyNat :\n        forall i Gamma,\n        Gamma |= tnat i \\in TNat\n    | tySucc :\n        forall x Gamma,\n        Gamma |= x \\in TNat ->\n        Gamma |= tsucc x \\in TNat\n    | tyPred :\n        forall x Gamma,\n        Gamma |= x \\in TNat ->\n        Gamma |= tpred x \\in TNat\n    | tyMult :\n        forall x y Gamma,\n        Gamma |= x \\in TNat ->\n        Gamma |= y \\in TNat ->\n        Gamma |= tmult x y \\in TNat\n    | tyIf :\n        forall t t0 t1 Gamma T,\n        Gamma |= t0 \\in T ->\n        Gamma |= t1 \\in T ->\n        Gamma |= t \\in TNat ->\n        Gamma |= tif0 t t0 t1 \\in T\n    where \"Gamma '|=' t '\\in' T \" := (has_type Gamma t T).\n\n    Hint Constructors has_type.\n    Reserved Notation \"'[' x ':=' s ']' t\" (at level 20).\n    \n    \n\nFixpoint subst (i : id) (t org : tm) : tm :=\n    match org with\n        | tvar j => if(eq_id_dec i j) then t else org\n        | tapp a b => tapp ([i := t] a) ([i := t] b)\n        | tabs x T y => tabs x T (if (eq_id_dec x i) then y else ([i := t] y))\n        | tsucc x => tsucc ([i := t] x)\n        | tpred y => tpred ([i := t] y)\n        | tmult x y => tmult ([i := t] x) ([i := t] y)\n        | tif0 x t0 t1 => tif0 ([i := t] x) ([i := t] t0) ([i := t] t1)\n        | _ => org\n        end\n        where \"'[' x ':=' s ']' t\" := (subst x s t).\n\n\nInductive value : tm -> Prop :=\n    | vnat : \n        forall n,\n            value (tnat n)\n    | vabs :\n        forall x T y,\n            value (tabs x T y).\n\nReserved Notation \"t '==>' t'\" (at level 40).\n        \n    Hint Constructors value.\nInductive step : tm -> tm -> Prop :=\n    | ST_AppAbs :\n        forall abs abs' arg,\n        abs ==> abs' ->\n        tapp abs arg ==> tapp abs' arg\n    | ST_AppArg :\n        forall abs arg arg',\n        value abs ->\n        arg ==> arg' ->\n        tapp abs arg ==> tapp abs arg'\n    | ST_App :\n        forall x T y arg,\n        value arg ->\n        tapp (tabs x T y) arg ==> [x := arg] y\n    | ST_Succ0 :\n        forall n n',\n        n ==> n' ->\n        tsucc n ==> tsucc n'\n    | ST_Succ1 :\n        forall n,\n        tsucc (tnat n) ==> tnat (S n)\n    | ST_Pred0 :\n        forall n n',\n        n ==> n' ->\n        tpred n ==> tpred n'\n    | ST_Pred1 :\n        forall n,\n        tpred (tnat n) ==> tnat (pred n)\n    | ST_Mult0 :\n        forall n0 n0' n1,\n        n0 ==> n0' ->\n        tmult n0 n1 ==> tmult n0' n1\n    | ST_Mult1 :\n        forall n0 n1 n1',\n        value n0 ->\n        n1 ==> n1' ->\n        tmult n0 n1 ==> tmult n0 n1'\n    | ST_Mult2 :\n        forall n0 n1,\n        tmult (tnat n0) (tnat n1) ==> tnat (n0 * n1)\n    | ST_If0 :\n        forall t t' t0 t1,\n        t ==> t' ->\n        tif0 t t0 t1 ==> tif0 t' t0 t1\n    | ST_IfFalse :\n        forall t0 t1,\n        tif0 (tnat 0) t0 t1 ==> t1\n    | ST_IfTrue :\n        forall t t0 t1,\n        t <> 0 ->\n        tif0 (tnat t) t0 t1 ==> t0\n    where \"t '==>' t'\" := (step t t').\n\n    Hint Constructors step.\n\n    Theorem deterministic_step :\n        deterministic step.\n    \n    unfold deterministic.\n    intros x y1 y2 h.\n    generalize dependent y2.\n    elim h; intros.\n\n    inversion H1; subst. pose (H0 _ H5). rewrite e; auto.\n    inversion H4; subst. inversion H.\n\n    Abort.\n\n    Lemma value_cant_step:\n        forall n n',\n        value n ->\n        n ==> n' ->\n        False.\n    intros n n' h.\n    generalize dependent n'.\n    elim h; subst; intros.\n    inversion H. inversion H.\nQed.\n\n\n\nLtac value_no_stepping_ :=\n    match goal with\n     | [ H1 : tabs ?X ?T ?Y ==> ?Z |- _ ] => inversion H1\n     | [ H1 : tnat ?N ==> ?Z |- _ ] => inversion H1\n     | [ H1 : value ?X, H2 : ?X ==> ?Z |- _ ] => destruct (value_cant_step _ _ H1 H2)\n     end.\n\nLtac value_no_stepping := repeat value_no_stepping_.\n\nTheorem deterministic_step :\n     deterministic step.\n     \n     unfold deterministic.\n     intros x y1 y2 h.\n     generalize dependent y2.\n     elim h; intros until y2; intro HH;\n     inversion HH; subst; try value_no_stepping; auto.\n\n     pose (H0 _ H4). rewrite e; auto.\n\n     pose (H1 _ H6). rewrite e; auto.\n\n     rewrite (H0 _ H2); auto.\n\n     rewrite (H0 _ H2); auto.\n\n     rewrite (H0 _ H4); auto.\n\n     rewrite (H1 _ H6); auto.\n\n     rewrite (H0 _ H5); auto.\n\n     destruct (H3 eq_refl).\n     destruct (H eq_refl).\n\nQed.\n\nLemma canonical_forms_bool :\n    forall t,\n    empty |= t \\in TNat ->\n    value t ->\n    (exists i, t = tnat i).\n\n    intros. inversion H0; subst. \n    exists n; auto.\n    inversion H; subst.\nQed.\n\nLemma canonical_forms_fun :\n    forall t G T,\n        empty |= t \\in TArrow G T ->\n        value t ->\n        (exists x v, t = tabs x G v).\n\n    intros. inversion H0; subst.\n    inversion H.\n    exists x. exists y. inversion H; subst. auto.\n\nQed.\n\nHint Unfold byContext.\n\nTheorem progress :\n    forall t T,\n        empty |= t \\in T ->\n        value t \\/ (exists t', t ==> t').\n\n    intro. elim t; intros.\n    inversion H; subst.  inversion H2.\n\n    inversion H1; subst. \n    right.\n    destruct (H _ H5). \n    destruct (H0 _ H7). \n    inversion H2; subst. inversion H5.\n    exists ([x := t1] y). eauto.\n\n    destruct H3. exists (tapp t0 x). eauto.\n    destruct H2. exists (tapp x t1). eauto.\n    \n    left; eauto.\n    left; eauto.\n\n    right. inversion H0; subst. \n    destruct (H _ H3). \n    inversion H1; subst.\n    exists (tnat (S n)). eauto.\n    inversion H3.\n    destruct H1.\n    exists (tsucc x). eauto.\n\n    right. inversion H0; subst.\n    destruct (H _ H3). inversion H1; subst.\n    exists (tnat (pred n)); eauto.\n    inversion H3.\n\n    destruct H1.\n    exists (tpred x). eauto.\n\n    right. inversion H1; subst.\n    destruct  (H _ H5). destruct (H0 _ H7).\n    inversion H2; inversion H3; subst.\n    exists (tnat (n * n0)); eauto.\n\n    inversion H7. inversion H5. inversion H5.\n\n    destruct H3.\n    exists (tmult t0 x). eauto.\n\n    destruct H2.\n    exists (tmult x t1). eauto.\n\n    right. inversion H2; subst. \n    destruct (H _ H10). inversion H3; subst.\n    destruct n. exists t2; eauto.\n    assert (S n <> 0); eauto.\n    inversion H10. \n    destruct H3.\n    exists (tif0 x t1 t2); eauto.\nQed.\n\nTheorem preservation :\n    forall t t' T,\n        empty |= t \\in T ->\n        step t t' ->\n        empty |= t' \\in T.\n\n    intro. elim t; intros.\n    inversion H0.\n    \n    inversion H1; inversion H2; subst; eauto.\n\n    Abort.\n\nLemma app_preserv:\n    forall t x y T G U,\n        U |= tabs x T t \\in TArrow T G ->\n        empty |= y \\in T ->\n        U |= [x := y] t \\in G.\n    intro t. elim t; intros.\n    inversion H; subst. unfold subst.\n    inversion H3; subst. unfold byContext in *. \n    destruct (eq_id_dec i x); subst. inversion H4; subst.\n    rewrite eq_id_dec_id.\n\n    Abort.\n\n\n(*\nTheorem update_shadow:\n    forall U i x y,\n    update i x (update i y U) =-= update i x U.\n\n    unfold context_equivalence.\n    intro. induction U; intros.\n    unfold byContext in *.\n    destruct (eq_id_dec i0 i); subst; auto.\n\n    unfold byContext in *.\n    destruct (eq_id_dec i1 i0); subst; auto.\n\nQed.\n\nTheorem update_permute:\n    forall U i j x y,\n    i <> j ->\n    update i x (update j y U) =-= update j y (update i x U).\n\n    intro. \n    \n    induction U; intros.\n    unfold context_equivalence. intros.\n    unfold byContext in *. destruct (eq_id_dec i0 i); destruct (eq_id_dec i0 j); subst; eauto.\n    destruct (H eq_refl).\n\n    destruct (eq_id_dec i j); subst.\n    Abort.\n\nPrint relation.\nPrint equiv.\n\nTheorem equiv_ctx_eq:\n    equiv context_equivalence.\n*)\n\n\n\nInductive occurs_free : id -> tm -> Prop :=\n    | occurs_free_var :\n        forall i,\n            occurs_free i (tvar i)\n    | occurs_free_abs :\n        forall i j x T,\n            occurs_free i x ->\n            i <> j ->\n            occurs_free i (tabs j T x)\n    | occurs_free_app1 :\n        forall i x y,\n            occurs_free i x ->\n            occurs_free i (tapp x y)\n    | occurs_free_app2 :\n        forall i x y,\n            occurs_free i y ->\n            occurs_free i (tapp x y)\n    | occurs_free_succ :\n        forall i x,\n            occurs_free i x ->\n            occurs_free i (tsucc x)\n    | occurs_free_pred :\n        forall i x,\n            occurs_free i x ->\n            occurs_free i (tpred x)\n    | occurs_free_mult1 :\n        forall i x y,\n            occurs_free i x ->\n            occurs_free i (tmult x y)\n    | occurs_free_mult2 :\n        forall i x y,\n            occurs_free i y ->\n            occurs_free i (tmult x y)\n    | occurs_free_if0 :\n        forall i t t0 t1,\n            occurs_free i t ->\n            occurs_free i (tif0 t t0 t1)\n    | occurs_free_if1 :\n        forall i t t0 t1,\n            occurs_free i t0 ->\n            occurs_free i (tif0 t t0 t1)\n    | occurs_free_if2 :\n        forall i t t0 t1,\n            occurs_free i t1 ->\n            occurs_free i (tif0 t t0 t1).\n\n    Hint Constructors occurs_free.\nTheorem occurs_dec:\n    forall i x,\n    {occurs_free i x} + {~occurs_free i x}.\n\n    intros i x. generalize dependent i.\n    induction x; eauto.\n    intros. \n    destruct (eq_id_dec i0 i); subst. \n    left; eauto.\n    right; intros H; inversion H; subst. destruct (n eq_refl).\n\n    intros. destruct (IHx1 i). left; eauto.\n    destruct (IHx2 i). left; eauto.\n    right; intro. inversion H; subst; eauto.\n\n    intro. destruct (IHx i0). destruct (eq_id_dec i0 i); subst.\n    right; intro HH; inversion HH; subst. destruct (H4 eq_refl).\n    left; eauto.\n\n    right; intro HH; inversion HH; subst; eauto.\n\n    intros; right; intro HH; inversion HH.\n\n    intros i; destruct (IHx i). left; eauto. right; intro HH; inversion HH; subst; eauto.\n\n    intros i; destruct (IHx i). left; eauto. right; intro HH; inversion HH; subst; eauto.\n    \n    intros i; destruct (IHx1 i).\n    left; eauto. destruct (IHx2 i). left; eauto.\n    right; intro HH; inversion HH; subst; eauto.\n\n    intros i; destruct (IHx1 i).\n    left; eauto. destruct (IHx2 i). left; eauto.\n    destruct (IHx3 i). left; eauto.\n    right; intro HH; inversion HH; subst; eauto.\nQed.\n\nDefinition closed (x : tm) :=\n    forall i, ~ occurs_free i x.\n\nTheorem ctx_swap:\n    forall x U V T ,\n        U |= x \\in T ->\n        U =-= V ->\n        V |= x \\in T.\n\n    intros x U V T h.\n    generalize dependent V.\n    induction h; unfold context_equivalence; intros; eauto.\n    eapply tyVar. rewrite <- H0. auto.\n\n    eapply tyAbs. \n    pose (update_inc (z := ty)).\n    pose (update_inc i G _ _ H).\n    eauto.\nQed.\n\nTheorem non_occurs_free_ctx_rm:\n    forall v i x U T,\n    update i x U |= v \\in T ->\n    (~occurs_free i v) ->\n    U |= v \\in T.\n\n    intros v i x U T h.\n    remember (update i x U) as u.\n    generalize Hequ.\n    induction h; subst; eauto.\n    intros. cbn in H. \n    destruct (eq_id_dec i0 i); subst. destruct (H0 (occurs_free_var i)).\n    eauto.\n\n    intros. \n    pose (contrapositive _ _ (occurs_dec _ _) (occurs_free_app1 i a b)).\n    pose (contrapositive _ _ (occurs_dec _ _) (occurs_free_app2 i a b)).\n\n    pose (IHh2 eq_refl eq_refl).\n    pose (IHh1 eq_refl eq_refl).\n    eapply tyApp; eauto.\n\n    intros. destruct (occurs_dec i x0). \n    destruct (eq_id_dec i i0); subst.\n    \n    pose (update_shadow i0 G x U U (refl_ctxeq _ )).\n    pose (ctx_swap _ _ _ _ h c).\n    eauto.\n\n    assert (occurs_free i (tabs i0 G x0)) as HH; eauto.\n    destruct (H HH).\n\n    eauto.\n    Abort.\n\n\nTheorem non_occurs_free_ctx_rm:\n    forall v i x U T,\n    update i x U |= v \\in T ->\n    (~occurs_free i v) ->\n    U |= v \\in T.\n\n    intro v; induction v; eauto.\n    intros. inversion H; subst.\n    cbn in H3. destruct (eq_id_dec i i0); subst.\n    destruct (H0 (occurs_free_var i0)).\n    eauto.\n\n    intros. \n    pose (contrapositive _ _ (occurs_dec _ _) (occurs_free_app1 i v1 v2)).\n    pose (contrapositive _ _ (occurs_dec _ _) (occurs_free_app2 i v1 v2)).\n    inversion H; subst. eapply tyApp; eauto.\n\n    intros. inversion H; subst.\n    destruct (occurs_dec i0 v);\n    destruct (eq_id_dec i0 i); subst. inversion H; subst.\n    \n    pose (update_shadow i t x U U (refl_ctxeq _ )).\n    pose (ctx_swap _ _ _ _ H6 c).\n    eauto.\n\n    assert (occurs_free i0 (tabs i t v)) as HH; eauto.\n    destruct (H0 HH).\n\n    inversion H; subst. \n    pose (update_shadow i t x U U (refl_ctxeq _ )).\n    pose (ctx_swap _ _ _ _ H6 c).\n    eauto.\n    pose (update_permute i0 i x t U U n0 (refl_ctxeq _)).\n    Print symm_ctxeq.\n    pose (symm_ctxeq _ _ c).\n    pose (ctx_swap _ _ _ _ H6 c0).\n    eauto.\n\n    intros. inversion H; subst. eauto.\n\n    intros. inversion H; subst.\n    Print occurs_free_succ. \n    pose (contrapositive _ _ (occurs_dec _ _) (occurs_free_succ i v)).\n    eauto.\n\n    intros. inversion H; subst.\n    pose (contrapositive _ _ (occurs_dec _ _) (occurs_free_pred i v)).\n    eauto.\n\n    intros. inversion H; subst.\n    pose (contrapositive _ _ (occurs_dec _ _) (occurs_free_mult1 i v1 v2)).\n    pose (contrapositive _ _ (occurs_dec _ _) (occurs_free_mult2 i v1 v2)).\n    eapply tyMult; eauto.\n\n    intros.\n     inversion H; subst.\n     pose (contrapositive _ _ (occurs_dec _ _) (occurs_free_if0 i v1 v2 v3)).\n     pose (contrapositive _ _ (occurs_dec _ _) (occurs_free_if1 i v1 v2 v3)).\n     pose (contrapositive _ _ (occurs_dec _ _) (occurs_free_if2 i v1 v2 v3)).\n     eapply tyIf; eauto.\n\nQed.\n\n   \nLemma occurs_free_is_in_ctx:\nforall i x U T,\n    U |= x \\in T ->\n    occurs_free i x ->\n    (exists K, byContext U i = Some K).\n\nintros i x U T h0 h.\ngeneralize dependent U.\ngeneralize dependent T.\ninduction h; intros; eauto; try (inversion h0; subst; eauto).\n\ninversion h0; subst. \ndestruct (IHh _ _ H5).\ncbn in H0. destruct (eq_id_dec i j); subst; eauto.\ndestruct (H eq_refl).\nQed.\n\n\n\nTheorem empty_means_closed:\n    forall t T,\n        empty |= t \\in T ->\n        closed t.\n\n    unfold closed.\n    intros t.\n    induction t; intros; intro.\n    inversion H; subst. inversion H3.\n\n    inversion H; subst. inversion H0; subst. \n    destruct ((IHt1 _ H4 i) H3).\n    destruct ((IHt2 _ H6 i) H3).\n\n \n\n    inversion H; subst; inversion H0; subst.\n    destruct (occurs_free_is_in_ctx _ _ _ _ H H0).\n    inversion H1.\n\n    inversion H0. \n\n    inversion H; inversion H0; subst; eauto.\n    eapply IHt. apply H3. apply H7.\n\n    inversion H; inversion H0; subst; eapply IHt. apply H3. apply H7.\n    inversion H; inversion H0; subst. eapply IHt1; eauto. eapply IHt2; eauto.\n    inversion H; inversion H0; subst. eapply IHt1; eauto. eapply IHt2; eauto. eapply IHt3; eauto.\n\nQed.\n\n\nTheorem empty_is_strong:\n    forall x T U,\n        empty |= x \\in T ->\n        U |= x \\in T.\n\n    intros x T U. \n    generalize dependent x;\n    generalize dependent T.\n    induction U; intros; auto.\n    pose (empty_means_closed x T H).\n    unfold closed in c.\n    pose (c i).\n    Print non_occurs_free_ctx_rm.\n    Abort.\n\nTheorem occurs_free_ctx_add :\n    forall i j x T U,\n    U |= x \\in T ->\n    ~(occurs_free i x) ->\n    update i j U |= x \\in T.\n\n    intros i j x.\n    generalize dependent i;\n    generalize dependent j.\n\n    induction x; eauto.\n    intros. inversion H; subst.\n    eapply tyVar. cbn.\n    destruct (eq_id_dec i i0); subst.\n    destruct (H0 (occurs_free_var i0)).\n    auto.\n\n    intros. inversion H; subst. eapply tyApp; eauto.\n\n    intros. inversion H; subst. \n    destruct (occurs_dec i0 x); subst.\n    destruct (eq_id_dec i0 i); subst.\n    eapply tyAbs. \n    eapply ctx_swap. eapply H6. eapply symm_ctxeq.\n    eapply update_shadow. eapply refl_ctxeq.\n    assert (occurs_free i0 (tabs i t x)). eauto.\n    destruct (H0 H1).\n    destruct (eq_id_dec i0 i); subst.\n    eapply tyAbs. eapply ctx_swap. eapply H6.\n    eapply symm_ctxeq. eapply update_shadow. eapply refl_ctxeq.\n    eapply tyAbs. eapply ctx_swap. eapply IHx. eapply H6. eauto.\n    eapply update_permute; eauto. eapply refl_ctxeq.\n\n    intros. inversion H; subst; eauto.\n\n    intros. inversion H; subst; eauto. eapply tySucc; eauto.\n\n    intros. inversion H; subst;eauto. eapply tyPred; eauto.\n\n    intros. inversion H; subst; eauto. eapply tyMult; eauto.\n\n    intros. inversion H; subst; eauto. eapply tyIf; eauto.\nQed.\n\nTheorem empty_is_strong:\nforall x T U,\n    empty |= x \\in T ->\n    U |= x \\in T.\n\nintros x T U. \ngeneralize dependent x;\ngeneralize dependent T.\ninduction U; intros; auto.\npose (empty_means_closed x T H).\nunfold closed in c.\npose (c i).\neapply occurs_free_ctx_add; eauto.\nQed.\n\n\nLemma app_preserv:\nforall t x y T G U,\n    U |= tabs x T t \\in TArrow T G ->\n    empty |= y \\in T ->\n    U |= [x := y] t \\in G.\nintro t. elim t; intros.\ninversion H; subst. unfold subst.\ninversion H3; subst. cbn in H4.\ndestruct (eq_id_dec i x); subst. inversion H4; subst.\nrewrite eq_id_dec_id. eapply empty_is_strong; eauto.\ndestruct (eq_id_dec x i); subst. destruct (n eq_refl).\neapply tyVar; auto.\n\ninversion H1; subst.\nchange (U |= tapp ([x := y] t0) ([x := y] t1) \\in G).\ninversion H5; subst. \neapply tyApp; eauto.\n\nchange (U |= tabs i t0 (if eq_id_dec i x then t1 else [x := y] t1) \\in G).\ninversion H0; subst. inversion H4; subst.\ndestruct (eq_id_dec i x); subst.\neapply tyAbs. eapply ctx_swap. apply H8. eapply update_shadow. eapply refl_ctxeq.\neapply tyAbs. eapply H. eapply tyAbs. eapply ctx_swap. eapply H8. eapply update_permute; eauto. eapply refl_ctxeq. auto.\n\ninversion H; subst. inversion H3; subst. unfold subst. eauto.\n\ninversion H0; subst. inversion H4; subst. \nchange (U |= tsucc ([x := y] t0) \\in TNat).\neapply tySucc. eapply H; eauto.\n\ninversion H0; subst. inversion H4; subst.\nchange (U |= tpred ([x := y] t0) \\in TNat).\neauto.\n\ninversion H1; subst. inversion H5; subst.\nchange (U |= tmult ([ x:= y] t0) ([x := y] t1) \\in TNat).\neapply tyMult; eauto.\n\ninversion H2; subst. inversion H6; subst.\nchange (U |= tif0 ([x := y] t0) ([x := y] t1) ([x := y] t2) \\in G).\neapply tyIf; eauto.\n\nQed.\n\n\nTheorem preservation :\nforall t t' T,\n    empty |= t \\in T ->\n    step t t' ->\n    empty |= t' \\in T.\n\nintro. elim t; intros.\ninversion H0.\n\ninversion H1; inversion H2; subst; eauto. inversion H6; subst.\neapply app_preserv; eauto.\n\ninversion H1.\n\ninversion H0.\n\ninversion H1; subst. inversion H0; subst. eauto.\n\ninversion H0; subst. eauto.\n\ninversion H1; subst; inversion H0; subst; eauto.\n\ninversion H1; subst; inversion H2; subst; eauto.\n\ninversion H2; subst; inversion H3; subst; eauto.\nQed.\n\nDefinition stuck (t: tm) : Prop :=\n(normal_form step) t /\\ ~ value t.\n\nNotation \"t '==>*' t'\" := (multi step t t') (at level 40).\n\n\nCorollary soundness : \n    forall t t' T,\n        empty |= t \\in T ->\n        t ==>* t' ->\n        ~(stuck t').\n\n    intros t t' T h0 h. generalize dependent T.\n    unfold stuck. unfold normal_form.\n    induction h; intros; auto; intro.\n    destruct H.\n    Print progress.\n    destruct (progress _ _ h0); eauto.\n    Print preservation.\n    pose (preservation _ _ _ h0 H). \n    destruct ((IHh _ h1) H0).\nQed.\n\nTheorem types_unique:\n    forall x T G U,\n    U |= x \\in T ->\n    U |= x \\in G ->\n    T = G.\n    intro x; induction x; eauto; intros; (try (inversion H; inversion H0; subst; eauto)).\n    inversion H; inversion H0; subst. rewrite H7 in H3. inversion H3; subst. auto.\n\n    inversion H; inversion H0; subst; eauto.\n    pose (IHx1 _ _ _ H4 H10). inversion e; subst; auto.\n\n    inversion H; inversion H0; subst. rewrite (IHx _ _ _ H6 H12); eauto.\n\nQed.\n    \nEnd STLCARITH.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n        ", "meta": {"author": "DKXXXL", "repo": "SoftwareFoundations-AfterCh15", "sha": "f9fbacb555970fdf42dd834f29c4a6289d5acb59", "save_path": "github-repos/coq/DKXXXL-SoftwareFoundations-AfterCh15", "path": "github-repos/coq/DKXXXL-SoftwareFoundations-AfterCh15/SoftwareFoundations-AfterCh15-f9fbacb555970fdf42dd834f29c4a6289d5acb59/STLCWA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6627654344228355}}
{"text": "Require Import ExtLib.Core.Type.\n\nGlobal Instance type_Prop : type Prop :=\n{ equal := iff\n; proper := fun _ => True\n}.\n\nGlobal Instance typeOk_Prop : typeOk type_Prop.\nProof.\n  constructor; compute; firstorder.\nQed.\n\n(** NOTE: These should fit into a larger picture, e.g. lattices or monoids **)\n(** And/Conjunction **)\nLemma and_True_iff : forall P, (P /\\ True) <-> P.\nProof. intuition. Qed.\n\nLemma and_and_iff : forall P, (P /\\ P) <-> P.\nProof. intuition. Qed.\n\nLemma and_assoc : forall P Q R, (P /\\ Q /\\ R) <-> ((P /\\ Q) /\\ R).\nProof. intuition. Qed.\n\nLemma and_comm : forall P Q, (P /\\ Q) <-> (Q /\\ P).\nProof. intuition. Qed.\n\nLemma and_False_iff : forall P, (P /\\ False) <-> False.\nProof. intuition. Qed.\n\nLemma and_cancel\n: forall P Q R : Prop, (P -> (Q <-> R)) -> ((P /\\ Q) <-> (P /\\ R)).\nProof. intuition. Qed.\n\nLemma and_iff\n: forall P Q R S : Prop,\n    (P <-> R) ->\n    (P -> (Q <-> S)) ->\n    ((P /\\ Q) <-> (R /\\ S)).\nProof. clear; intuition. Qed.\n\n(** Or/Disjunction **)\nLemma or_False_iff : forall P, (P \\/ False) <-> P.\nProof. intuition. Qed.\n\nLemma or_or_iff : forall P, (P \\/ P) <-> P.\nProof. intuition. Qed.\n\nLemma or_assoc : forall P Q R, (P \\/ Q \\/ R) <-> ((P \\/ Q) \\/ R).\nProof. intuition. Qed.\n\nLemma or_comm : forall P Q, (P \\/ Q) <-> (Q \\/ P).\nProof. intuition. Qed.\n\nLemma or_True_iff : forall P, (P \\/ True) <-> True.\nProof. intuition. Qed.\n\n(** Implication **)\nLemma impl_True_iff : forall (P : Prop), (True -> P) <-> P.\nProof.\n  clear; intros; tauto.\nQed.\n\nLemma impl_iff\n: forall P Q R S : Prop,\n    (P <-> R) ->\n    (P -> (Q <-> S)) ->\n    ((P -> Q) <-> (R -> S)).\nProof. clear. intuition. Qed.\n\nLemma impl_eq : forall (P Q : Prop), P = Q -> (P -> Q).\nProof. clear. intros; subst; auto. Qed.\n\nLemma uncurry : forall (P Q R : Prop),\n    (P /\\ Q -> R) <-> (P -> Q -> R).\nProof. clear. tauto. Qed.\n\n\n(** Forall **)\nLemma forall_iff : forall T P Q,\n                     (forall x,\n                        P x <-> Q x) ->\n                     ((forall x : T, P x) <-> (forall x : T, Q x)).\nProof.\n   intros. setoid_rewrite H. reflexivity.\nQed.\n\nLemma forall_impl : forall {T} (P Q : T -> Prop),\n                      (forall x, P x -> Q x) ->\n                      (forall x, P x) -> (forall x, Q x).\nProof.\n  clear. intuition.\nQed.\n\n\n(** Exists **)\nLemma exists_iff : forall T P Q,\n                     (forall x,\n                        P x <-> Q x) ->\n                     ((exists x : T, P x) <-> (exists x : T, Q x)).\nProof.\n   intros. setoid_rewrite H. reflexivity.\nQed.\n\nLemma exists_impl : forall {T} (P Q : T -> Prop),\n                      (forall x, P x -> Q x) ->\n                      (exists x, P x) -> (exists x, Q x).\nProof.\n  clear. intuition.\n  destruct H0; eauto.\nQed.\n\nLemma iff_eq : forall (P Q : Prop), P = Q -> (P <-> Q).\nProof. clear. intros; subst; reflexivity. Qed.", "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/coq-ext-lib/theories/Data/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6627180819781299}}
{"text": "(* week-02_programming-and-proving.v *)\n(* YSC3236 2017-2018, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 25 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 regexp :=\n  | empty : regexp\n  | atom : nat -> regexp\n  | any : regexp\n  | seq : regexp -> regexp -> regexp\n  | disj : regexp -> regexp -> regexp\n  | star : regexp -> regexp\n  | plus : regexp -> regexp.\n\nLemma seq_re_empty :\n  forall re : regexp,\n    seq re empty = re.\nProof.\nAdmitted.\n\nLemma seq_empty_re :\n  forall re : regexp,\n    seq empty re = re.\nProof.\nAdmitted.\n\nLemma seq_assoc :\n  forall re1 re2 re3 : regexp,\n    seq re1 (seq re2 re3) = seq (seq re1 re2) re3.\nProof.\nAdmitted.\n\n(* ***** *)\n\n(* Prove the following proposition using seq_empty_re: *)\n\nProposition about_regular_expressions_1 :\n  seq empty (seq empty empty) = seq (seq empty empty) empty.\nProof.\n  Check (seq_re_empty empty).\n  rewrite -> (seq_re_empty empty).\n  reflexivity.\n  \nRestart.\n\n(* Prove the same proposition using seq_assoc: *)\n\n  apply (seq_assoc empty empty empty).\n\n\nProposition about_regular_expressions_2 :\n  seq empty (seq empty empty) = seq (seq empty empty) empty.\nProof.\n\n  Check (seq_assoc empty empty empty). \n  rewrite -> (seq_assoc empty empty empty).\n  \nAbort.\n\n(* The Restart tactic: *)\n\nProposition about_regular_expressions_1_and_2 :\n  seq empty (seq empty empty) = seq (seq empty empty) empty.\nProof.\n  (* put here your proof of about_regular_expressions_1 *)\n  \n\n\n\n  \n  Restart.\n\n  (* put here your proof of about_regular_expressions_2 *)\n\nAbort.\n\n(* ***** *)\n\n(* Exercise 1 of Week 02 in the PL lecture notes: *)\n\nProposition Exercise_1_of_Week_02_a :\n  (seq (atom 1) (seq (atom 2) (seq (atom 3) (seq (atom 4) (empty)))))\n  =\n  (seq (atom 1) (seq (atom 2) (seq (atom 3) (atom 4)))).\nProof.\n  Check (seq_re_empty (atom 4)).\n  rewrite -> (seq_re_empty (atom 4)).\n  reflexivity.\nAbort.\n\nProposition Exercise_1_of_Week_02_b :\n  (seq (atom 1) (seq (atom 2) (seq (atom 3) (atom 4))))\n  =\n  (seq (seq (empty) (seq (atom 1) (atom 2))) (seq (empty) (seq (atom 3) (atom 4)))).\nProof.\n\n  \n\n\n\nAbort.\n\nProposition Exercise_1_of_Week_02_c :\n  (seq (seq (empty) (seq (atom 1) (atom 2))) (seq (empty) (seq (atom 3) (atom 4))))\n  =\n  (seq (seq (seq (atom 1) (atom 2)) (atom 3)) (atom 4)).\nProof.\nAbort.\n\nProposition Exercise_1_of_Week_02_d :\n  (seq (seq (seq (atom 1) (atom 2)) (atom 3)) (atom 4))\n  =\n  (seq (seq (seq (seq (empty) (atom 1)) (atom 2)) (atom 3)) (atom 4)).\nProof.\nAbort.\n\nProposition Exercise_1_of_Week_02_e :\n  (seq (seq (seq (seq (empty) (atom 1)) (atom 2)) (atom 3)) (atom 4))\n  =\n  (seq (atom 1) (seq (atom 2) (seq (atom 3) (seq (atom 4) (empty))))).\nProof.\nAbort.\n\n(* Re-prove Proposition Exercise_1_of_Week_02_e\n   as a corollary of the previous exercises,\n   Exercise_1_of_Week_02_a to Exercise_1_of_Week_02_d: *)\n\nCorollary Exercise_1_of_Week_02_e' :\n  (seq (seq (seq (seq (empty) (atom 1)) (atom 2)) (atom 3)) (atom 4))\n  =\n  (seq (atom 1) (seq (atom 2) (seq (atom 3) (seq (atom 4) (empty))))).\nProof.\nAbort.\n\n(* ********** *)\n\nDefinition test_add (candidate: nat -> nat -> nat) :=\n  (candidate 0 0 =n= 0)\n  &&\n  (candidate 0 1 =n= 1)\n  &&\n  (candidate 1 0 =n= 1)\n  &&\n  (candidate 1 1 =n= 2)\n  &&\n  (candidate 1 2 =n= 3)\n  &&\n  (candidate 2 1 =n= 3)\n  &&\n  (candidate 2 2 =n= 4)\n  .\n\nFixpoint add_v1 (i j : nat) : nat :=\n  match i with\n  | O => j\n  | S i' => S (add_v1 i' j)\n  end.\n\nCompute (test_add add_v1).\n\n(* Canonical unfold lemmas for recursive definitions: *)\n\nLemma unfold_add_v1_0 :\n  forall j : nat,\n    add_v1 0 j = j.\nProof.\n  unfold_tactic add_v1.\nQed.\n\nLemma unfold_add_v1_S :\n  forall i' j : nat,\n    add_v1 (S i') j = S (add_v1 i' j).\nProof.\n  unfold_tactic add_v1.\nQed.\n\nProposition add_v1_0_n :\n  forall n : nat,\n    add_v1 0 n = n.\nProof.\nAbort.\n\nProposition add_v1_n_0 :\n  forall n : nat,\n    add_v1 n 0 = n.\nProof.\nAbort.\n\nLemma add_v1_assoc :\n  forall x y z : nat,\n    add_v1 x (add_v1 y z) =\n    add_v1 (add_v1 x y) z.\nProof.\n  intro x.\n  induction x as [ | x' IHx'].\n\n  intros y z.\n  rewrite -> (unfold_add_v1_0 (add_v1 y z)).\n  rewrite -> (unfold_add_v1_0 y).\n  reflexivity.\n\n  intros y z.\n  rewrite -> (unfold_add_v1_S x' (add_v1 y z)).\n  rewrite -> (unfold_add_v1_S x' y).\n  rewrite -> (unfold_add_v1_S (add_v1 x' y)).\n  rewrite -> (IHx' y z).\n  reflexivity.\nQed.\n\n(* ***** *)\n\nFixpoint add_v2 (i j : nat) : nat :=\n  match i with\n  | O => j\n  | S i' => add_v2 i' (S j)\n  end.\n\nCompute (test_add add_v2).\n\n(* Canonical unfold lemmas for recursive definitions: *)\n\nLemma unfold_add_v2_0 :\n  forall j : nat,\n    add_v2 0 j = j.\nProof.\n  unfold_tactic add_v2.\nQed.\n\nLemma unfold_add_v2_S :\n  forall i' j : nat,\n    add_v2 (S i') j = add_v2 i' (S j).\nProof.\n  unfold_tactic add_v2.\nQed.\n\n(* ***** *)\n\nProposition equivalence_of_add_v1_and_add_v2 :\n  forall i j : nat,\n    add_v1 i j = add_v2 i j.\nProof.\nAbort.\n\nProposition add_v2_0_n :\n  forall n : nat,\n    add_v2 0 n = n.\nProof.\nAbort.\n\nProposition add_v2_n_0 :\n  forall n : nat,\n    add_v2 n 0 = n.\nProof.\nAbort.\n\nLemma add_v2_assoc :\n  forall x y z : nat,\n    add_v2 x (add_v2 y z) =\n    add_v2 (add_v2 x y) z.\nProof.\nAbort.\n\n(* ********** *)  \n\nDefinition test_min (candidate : nat -> nat -> nat) : bool :=\n  (candidate 0 3 =n= 0)\n  &&\n  (candidate 3 0 =n= 0)\n  &&\n  (candidate 2 3 =n= 2)\n  &&\n  (candidate 3 2 =n= 2)\n  &&\n  (candidate 3 3 =n= 3)\n  .\n\n(* ***** *)\n\n(* Lambda-dropped version of min_v1: *)\n\nFixpoint visit_min_v1 (m_init n_init m n : nat) : nat :=\n  match m with\n  | 0 => m_init\n  | S m' => match n with\n            | 0 => n_init\n            | S n' => visit_min_v1 m_init n_init m' n'\n            end\n  end.\n\nDefinition min_v1 (m_init n_init : nat) : nat :=\n  visit_min_v1 m_init n_init m_init n_init.\n\nCompute (test_min min_v1).\n\nFixpoint min_v2 (m n : nat) : nat :=\n  match m with\n  | 0 => 0\n  | S m' => match n with\n            | 0 => 0\n            | S n' => S (min_v2 m' n')\n            end\n  end.\n\nCompute (test_min min_v2).\n\n(* ***** *)\n\n(* Canonical unfold lemmas for recursive definitions: *)\n\nLemma unfold_visit_min_v1_0 :\n  forall m_init n_init n : nat,\n    visit_min_v1 m_init n_init 0 n = m_init.\nProof.\n  unfold_tactic visit_min_v1.\nQed.\n\nLemma unfold_visit_min_v1_S :\n  forall m_init n_init m' n : nat,\n    visit_min_v1 m_init n_init (S m') n =\n    match n with\n    | 0 => n_init\n    | S n' => visit_min_v1 m_init n_init m' n'\n    end.\nProof.\n  unfold_tactic visit_min_v1.\nQed.\n\nLemma unfold_min_v2_0 :\n  forall n : nat,\n    min_v2 0 n = 0.\nProof.\n  unfold_tactic min_v2.\nQed.\n\nLemma unfold_min_v2_S :\n  forall m' n : nat,\n    min_v2 (S m') n =\n    match n with\n    | 0 => 0\n    | S n' => S (min_v2 m' n')\n    end.\nProof.\n  unfold_tactic min_v2.\nQed.\n\n(* ***** *)\n\nProposition equivalence_of_min_v1_and_min_v2 :\n  forall m n : nat,\n    min_v1 m n = min_v2 m n.\nProof.\nAbort.\n\n(* ********** *)\n\nDefinition test_evenp (candidate : nat -> bool) : bool :=\n  (eqb (candidate 0) true)\n  &&\n  (eqb (candidate 1) false)\n  &&\n  (eqb (candidate 7) false)\n  &&\n  (eqb (candidate 8) true)\n  &&\n  (eqb (candidate 17) false)\n  .\n\nFixpoint evenp_v1 (n : nat) : bool :=\n  match n with\n  | 0 => true\n  | S n' => match n' with\n            | 0 => false\n            | S n'' => evenp_v1 n''\n            end\n  end.\n\nCompute (test_evenp evenp_v1).\n\n(* With an inherited attribute, lambda-lifted: *)\n\nFixpoint visit_evenp_v2 (n : nat) (a : bool) : bool :=\n  match n with\n  | 0 => a\n  | S n' => visit_evenp_v2 n' (negb a)\n  end.\n\nDefinition evenp_v2 (n : nat) : bool :=\n  visit_evenp_v2 n true.\n\nCompute (test_evenp evenp_v2).\n\nFixpoint evenp_v3 (n : nat) : bool :=\n  match n with\n  | 0 => true\n  | S n' => negb (evenp_v3 n')\n  end.\n\nCompute (test_evenp evenp_v3).\n\nProposition equivalence_of_evenp_v1_and_evenp_v2 :\n  forall n : nat,\n    evenp_v1 n = evenp_v2 n.\nProof.\nAbort.\n\nProposition equivalence_of_evenp_v2_and_evenp_v3 :\n  forall n : nat,\n    evenp_v2 n = evenp_v3 n.\nProof.\nAbort.\n\nProposition equivalence_of_evenp_v1_and_evenp_v3 :\n  forall n : nat,\n    evenp_v1 n = evenp_v3 n.\nProof.\nAbort.\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\nFixpoint fac_v1 (n : nat) : nat :=\n  match n with\n  | 0 => 1\n  | S n' =>  n * (fac_v1 n')\n  end.\n\nCompute (test_fac fac_v1).\n\nFixpoint visit_fac_v2 (n a : nat) : nat :=\n  match n with\n  | 0 => a\n  | S n' => (visit_fac_v2 n' (n * a))\n  end.\n\nDefinition fac_v2 (n : nat) : nat :=\n  visit_fac_v2 n 1.\n\nCompute (test_fac fac_v2).\n\nProposition equivalence_of_fac_v1_and_fac_v2 :\n  forall n : nat,\n    fac_v1 n = fac_v2 n.\nProof.\nAbort.\n\n(* ********** *)\n\nDefinition test_fib (candidate: nat -> nat) : bool :=\n  (candidate 0 =n= 0)\n  && \n  (candidate 1 =n= 1)\n  && \n  (candidate 2 =n= 1)\n  && \n  (candidate 3 =n= 2)\n  && \n  (candidate 4 =n= 3)\n  && \n  (candidate 5 =n= 5)\n  && \n  (candidate 6 =n= 8)\n  && \n  (candidate 7 =n= 13)\n  && \n  (candidate 8 =n= 21)\n  .\n\nFixpoint fib_v1 (n : nat) : nat :=\n  match n with\n  | 0 => O\n  | S n' => match n' with\n            | O => 1\n            | S n'' => (fib_v1 n') + (fib_v1 n'')\n            end\n  end.\n\nCompute (test_fib fib_v1).\n\nFixpoint visit_fib_v2 (n a1 a2 : nat) : nat :=\n  match n with\n  | 0 => a1\n  | S n' => (visit_fib_v2 n' a2 (a1 + a2))\n  end.\n\nDefinition fib_v2 (n : nat) : nat :=\n  visit_fib_v2 n 0 1.\n\nCompute (test_fib fib_v2).\n\nFixpoint visit_fib_v3 (n : nat) : nat * nat :=\n  match n with\n  | 0 => (0, 1)\n  | S n' => match visit_fib_v3 n' with\n              | (a1, a2) => (a2, a1 + a2)\n            end\n  end.\n\nDefinition fib_v3 (n : nat) : nat :=\n  match visit_fib_v3 n with\n    | (a1, a2) => a1\n  end.\n\nCompute (test_fib fib_v3).\n\nProposition equivalence_of_fib_v1_and_fib_v2 :\n  forall n : nat,\n    fib_v1 n = fib_v2 n.\nProof.\nAbort.\n\nProposition equivalence_of_fib_v1_and_fib_v3 :\n  forall n : nat,\n    fib_v1 n = fib_v3 n.\nProof.\nAbort.\n\n(* ********** *)\n\nInductive list_nat : Type :=\n  nil_nat : list_nat\n| cons_nat : nat -> list_nat -> list_nat.\n\nFixpoint beq_list_nat (xs ys : list_nat) : bool :=\n  match xs with\n    nil_nat =>\n    match ys with\n      nil_nat =>\n      true\n    | cons_nat y ys' =>\n      false\n    end\n  | cons_nat x xs' =>\n    match ys with\n      nil_nat =>\n      false\n    | cons_nat y ys' =>\n      (x =n= y) && beq_list_nat xs' ys'\n    end\n  end.\n\nNotation \"A =ns= B\" :=\n  (beq_list_nat A B) (at level 70, right associativity).\n\n(* ***** *)\n\nDefinition test_append_list_nat (candidate: list_nat -> list_nat -> list_nat) :=\n  (candidate nil_nat nil_nat =ns= nil_nat)\n  &&\n  (candidate nil_nat (cons_nat 10 nil_nat) =ns= (cons_nat 10 nil_nat))\n  &&\n  (candidate (cons_nat 1 nil_nat) (cons_nat 10 nil_nat) =ns= (cons_nat 1 (cons_nat 10 nil_nat)))\n  (* etc. *)\n  .\n\nFixpoint append_list_nat (xs ys : list_nat) : list_nat :=\n  match xs with\n  | nil_nat =>\n    ys\n  | cons_nat x xs' =>\n    cons_nat x (append_list_nat xs' ys)\n  end.\n\nCompute (test_append_list_nat append_list_nat).\n\n(* Canonical unfold lemmas for recursive definitions: *)\n\nLemma unfold_append_list_nat_nil_nat :\n  forall ys : list_nat,\n    append_list_nat nil_nat ys = ys.\nProof.\n  unfold_tactic append_list_nat.\nQed.\n\nLemma unfold_append_list_nat_cons_nat :\n  forall (x : nat) (xs' ys : list_nat),\n    append_list_nat (cons_nat x xs') ys =\n    cons_nat x (append_list_nat xs' ys).\nProof.\n  unfold_tactic append_list_nat.\nQed.\n\nLemma append_nil_nat_ys :\n  forall ys : list_nat,\n    append_list_nat nil_nat ys = ys.\nProof.\nAbort.\n\nLemma append_ys_nil_nat :\n  forall xs : list_nat,\n    append_list_nat xs nil_nat = xs.\nProof.\nAbort.\n\nLemma append_list_nat_assoc :\n  forall xs ys zs : list_nat,\n    append_list_nat xs (append_list_nat ys zs) =\n    append_list_nat (append_list_nat xs ys) zs.\nProof.\nAbort.\n\n(* ***** *)\n\nDefinition test_length_list_nat (candidate: list_nat -> nat) :=\n  (candidate nil_nat =n= 0)\n  &&\n  (candidate (cons_nat 1 nil_nat) =n= 1)\n  &&\n  (candidate (cons_nat 2 (cons_nat 1 nil_nat)) =n= 2)\n  (* etc. *)\n  .\n\nFixpoint length_list_nat_v1 (xs : list_nat) : nat :=\n  match xs with\n  | nil_nat =>\n    0\n  | cons_nat x xs' =>\n    S (length_list_nat_v1 xs')\n  end.\n\nCompute (test_length_list_nat length_list_nat_v1).\n\nFixpoint visit_length_list_nat_v2 (xs : list_nat) (a : nat) : nat :=\n  match xs with\n  | nil_nat =>\n    a\n  | cons_nat x xs' =>\n    visit_length_list_nat_v2 xs' (S a)\n  end.\n\nDefinition length_list_nat_v2 (xs : list_nat) : nat :=\n  visit_length_list_nat_v2 xs 0.\n\nCompute (test_length_list_nat length_list_nat_v2).\n\nProposition equivalence_of_length_list_nat_v1_and_length_list_nat_v2 :\n  forall xs : list_nat,\n    length_list_nat_v1 xs = length_list_nat_v2 xs.\nProof.\nAbort.\n\n(* ********** *)\n\nProposition append_and_length_commute_with_each_other :\n  forall xs ys : list_nat,\n    length_list_nat_v1 (append_list_nat xs ys) =\n    (length_list_nat_v1 xs) + (length_list_nat_v1 ys).\nProof.\nAbort.\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_v1 (t : binary_tree) : nat :=\n  match t with\n    Leaf n =>\n    1\n  | Node t1 t2 =>\n    (number_of_leaves_v1 t1) + (number_of_leaves_v1 t2)\n  end.\n\nCompute (test_number_of_leaves number_of_leaves_v1).\n\nFixpoint visit_number_of_leaves_v2 (t : binary_tree) (a : nat) : nat :=\n  match t with\n    Leaf n =>\n    S a\n  | Node t1 t2 =>\n    visit_number_of_leaves_v2 t1 (visit_number_of_leaves_v2 t2 a)\n  end.\n\nDefinition number_of_leaves_v2 (t : binary_tree) : nat :=\n  visit_number_of_leaves_v2 t 0.\n\nCompute (test_number_of_leaves number_of_leaves_v1).\n\nProposition equivalence_of_number_of_leaves_v1_and_number_of_leaves_v2 :\n  forall t : binary_tree,\n    number_of_leaves_v1 t = number_of_leaves_v2 t.\nProof.\nAbort.\n\n(* ********** *)\n\n(* end of week-02_programming-and-proving.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-02_programming-and-proving.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.6627180684883925}}
{"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(*                                                                          *)\n(*                         Naive Set Theory in Coq                          *)\n(*                                                                          *)\n(*                     INRIA                        INRIA                   *)\n(*              Rocquencourt                        Sophia-Antipolis        *)\n(*                                                                          *)\n(*                                 Coq V6.1                                 *)\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 Gerard Huet\t\t\t\t    *)\n(*\t\t\t\t\t\t\t\t\t    *)\n(*\t\t\t\t\t\t\t\t\t    *)\n(*                                                                          *)\n(* Acknowledgments: This work was started in July 1993 by F. Prost. Thanks  *)\n(* to the Newton Institute for providing an exceptional work environment    *)\n(* in Summer 1995. Several developments by E. Ledinot were an inspiration.  *)\n(****************************************************************************)\n\n(*i $Id: Finite_sets_facts.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\nRequire Export Finite_sets.\nRequire Export Constructive_sets.\nRequire Export Classical_Type.\nRequire Export Classical_sets.\nRequire Export Powerset.\nRequire Export Powerset_facts.\nRequire Export Powerset_Classical_facts.\nRequire Export Gt.\nRequire Export Lt.\n\nSection Finite_sets_facts.\n  Variable U : Type.\n\n  Lemma finite_cardinal :\n    forall X:Ensemble U, Finite U X ->  exists n : nat, cardinal U X n.\n  Proof.\n    induction 1 as [| A _ [n H]].\n    exists 0; auto with sets.\n    exists (S n); auto with sets.\n  Qed.\n\n  Lemma cardinal_finite :\n    forall (X:Ensemble U) (n:nat), cardinal U X n -> Finite U X.\n  Proof.\n    induction 1; auto with sets.\n  Qed.\n\n  Theorem Add_preserves_Finite :\n    forall (X:Ensemble U) (x:U), Finite U X -> Finite U (Add U X x).\n  Proof.\n    intros X x H'.\n    elim (classic (In U X x)); intro H'0; auto with sets.\n    rewrite (Non_disjoint_union U X x); auto with sets.\n  Qed.\n\n  Theorem Singleton_is_finite : forall x:U, Finite U (Singleton U x).\n  Proof.\n    intro x; rewrite <- (Empty_set_zero U (Singleton U x)).\n    change (Finite U (Add U (Empty_set U) x)) in |- *; auto with sets.\n  Qed.\n\n  Theorem Union_preserves_Finite :\n    forall X Y:Ensemble U, Finite U X -> Finite U Y -> Finite U (Union U X Y).\n  Proof.\n    intros X Y H; induction H as [|A Fin_A Hind x].\n    rewrite (Empty_set_zero U Y). trivial.\n    intros.\n    rewrite (Union_commutative U (Add U A x) Y).\n    rewrite <- (Union_add U Y A x).\n    rewrite (Union_commutative U Y A).\n    apply Add_preserves_Finite.\n    apply Hind. assumption.\n  Qed.\n\n  Lemma Finite_downward_closed :\n    forall A:Ensemble U,\n      Finite U A -> forall X:Ensemble U, Included U X A -> Finite U X.\n  Proof.\n    intros A H'; elim H'; auto with sets.\n    intros X H'0.\n    rewrite (less_than_empty U X H'0); auto with sets.\n    intros; elim Included_Add with U X A0 x; auto with sets.\n    destruct 1 as [A' [H5 H6]].\n    rewrite H5; auto with sets.\n  Qed.\n\n  Lemma Intersection_preserves_finite :\n    forall A:Ensemble U,\n      Finite U A -> forall X:Ensemble U, Finite U (Intersection U X A).\n  Proof.\n    intros A H' X; apply Finite_downward_closed with A; auto with sets.\n  Qed.\n\n  Lemma cardinalO_empty :\n    forall X:Ensemble U, cardinal U X 0 -> X = Empty_set U.\n  Proof.\n    intros X H; apply (cardinal_invert U X 0); trivial with sets.\n  Qed.\n\n  Lemma inh_card_gt_O :\n    forall X:Ensemble U, Inhabited U X -> forall n:nat, cardinal U X n -> n > 0.\n  Proof.\n    induction 1 as [x H'].\n    intros n H'0.\n    elim (gt_O_eq n); auto with sets.\n    intro H'1; generalize H'; generalize H'0.\n    rewrite <- H'1; intro H'2.\n    rewrite (cardinalO_empty X); auto with sets.\n    intro H'3; elim H'3.\n  Qed.\n\n  Lemma card_soustr_1 :\n    forall (X:Ensemble U) (n:nat),\n      cardinal U X n ->\n      forall x:U, In U X x -> cardinal U (Subtract U X x) (pred n).\n  Proof.\n    intros X n H'; elim H'.\n    intros x H'0; elim H'0.\n    clear H' n X.\n    intros X n H' H'0 x H'1 x0 H'2.\n    elim (classic (In U X x0)).\n    intro H'4; rewrite (add_soustr_xy U X x x0).\n    elim (classic (x = x0)).\n    intro H'5.\n    absurd (In U X x0); auto with sets.\n    rewrite <- H'5; auto with sets.\n    intro H'3; try assumption.\n    cut (S (pred n) = pred (S n)).\n    intro H'5; rewrite <- H'5.\n    apply card_add; auto with sets.\n    red in |- *; intro H'6; elim H'6.\n    intros H'7 H'8; try assumption.\n    elim H'1; auto with sets.\n    unfold pred at 2 in |- *; symmetry  in |- *.\n    apply S_pred with (m := 0).\n    change (n > 0) in |- *.\n    apply inh_card_gt_O with (X := X); auto with sets.\n    apply Inhabited_intro with (x := x0); auto with sets.\n    red in |- *; intro H'3.\n    apply H'1.\n    elim H'3; auto with sets.\n    rewrite H'3; auto with sets.\n    elim (classic (x = x0)).\n    intro H'3; rewrite <- H'3.\n    cut (Subtract U (Add U X x) x = X); auto with sets.\n    intro H'4; rewrite H'4; auto with sets.\n    intros H'3 H'4; try assumption.\n    absurd (In U (Add U X x) x0); auto with sets.\n    red in |- *; intro H'5; try exact H'5.\n    lapply (Add_inv U X x x0); tauto.\n  Qed.\n\n  Lemma cardinal_is_functional :\n    forall (X:Ensemble U) (c1:nat),\n      cardinal U X c1 ->\n      forall (Y:Ensemble U) (c2:nat), cardinal U Y c2 -> X = Y -> c1 = c2.\n  Proof.\n    intros X c1 H'; elim H'.\n    intros Y c2 H'0; elim H'0; auto with sets.\n    intros A n H'1 H'2 x H'3 H'5.\n    elim (not_Empty_Add U A x); auto with sets.\n    clear H' c1 X.\n    intros X n H' H'0 x H'1 Y c2 H'2.\n    elim H'2.\n    intro H'3.\n    elim (not_Empty_Add U X x); auto with sets.\n    clear H'2 c2 Y.\n    intros X0 c2 H'2 H'3 x0 H'4 H'5.\n    elim (classic (In U X0 x)).\n    intro H'6; apply f_equal with nat.\n    apply H'0 with (Y := Subtract U (Add U X0 x0) x).\n    elimtype (pred (S c2) = c2); auto with sets.\n    apply card_soustr_1; auto with sets.\n    rewrite <- H'5.\n    apply Sub_Add_new; auto with sets.\n    elim (classic (x = x0)).\n    intros H'6 H'7; apply f_equal with nat.\n    apply H'0 with (Y := X0); auto with sets.\n    apply Simplify_add with (x := x); auto with sets.\n    pattern x at 2 in |- *; rewrite H'6; auto with sets.\n    intros H'6 H'7.\n    absurd (Add U X x = Add U X0 x0); auto with sets.\n    clear H'0 H' H'3 n H'5 H'4 H'2 H'1 c2.\n    red in |- *; intro H'.\n    lapply (Extension U (Add U X x) (Add U X0 x0)); auto with sets.\n    clear H'.\n    intro H'; red in H'.\n    elim H'; intros H'0 H'1; red in H'0; clear H' H'1.\n    absurd (In U (Add U X0 x0) x); auto with sets.\n    lapply (Add_inv U X0 x0 x); [ intuition | apply (H'0 x); apply Add_intro2 ].\n  Qed.\n\n  Lemma cardinal_Empty : forall m:nat, cardinal U (Empty_set U) m -> 0 = m.\n  Proof.\n    intros m Cm; generalize (cardinal_invert U (Empty_set U) m Cm).\n    elim m; auto with sets.\n    intros; elim H0; intros; elim H1; intros; elim H2; intros.\n    elim (not_Empty_Add U x x0 H3).\n  Qed.\n\n  Lemma cardinal_unicity :\n    forall (X:Ensemble U) (n:nat),\n      cardinal U X n -> forall m:nat, cardinal U X m -> n = m.\n  Proof.\n    intros; apply cardinal_is_functional with X X; auto with sets.\n  Qed.\n\n  Lemma card_Add_gen :\n    forall (A:Ensemble U) (x:U) (n n':nat),\n      cardinal U A n -> cardinal U (Add U A x) n' -> n' <= S n.\n  Proof.\n    intros A x n n' H'.\n    elim (classic (In U A x)).\n    intro H'0.\n    rewrite (Non_disjoint_union U A x H'0).\n    intro H'1; cut (n = n').\n    intro E; rewrite E; auto with sets.\n    apply cardinal_unicity with A; auto with sets.\n    intros H'0 H'1.\n    cut (n' = S n).\n    intro E; rewrite E; auto with sets.\n    apply cardinal_unicity with (Add U A x); auto with sets.\n  Qed.\n\n  Lemma incl_st_card_lt :\n    forall (X:Ensemble U) (c1:nat),\n      cardinal U X c1 ->\n      forall (Y:Ensemble U) (c2:nat),\n\tcardinal U Y c2 -> Strict_Included U X Y -> c2 > c1.\n  Proof.\n    intros X c1 H'; elim H'.\n    intros Y c2 H'0; elim H'0; auto with sets arith.\n    intro H'1.\n    elim (Strict_Included_strict U (Empty_set U)); auto with sets arith.\n    clear H' c1 X.\n    intros X n H' H'0 x H'1 Y c2 H'2.\n    elim H'2.\n    intro H'3; elim (not_SIncl_empty U (Add U X x)); auto with sets arith.\n    clear H'2 c2 Y.\n    intros X0 c2 H'2 H'3 x0 H'4 H'5; elim (classic (In U X0 x)).\n    intro H'6; apply gt_n_S.\n    apply H'0 with (Y := Subtract U (Add U X0 x0) x).\n    elimtype (pred (S c2) = c2); auto with sets arith.\n    apply card_soustr_1; auto with sets arith.\n    apply incl_st_add_soustr; auto with sets arith.\n    elim (classic (x = x0)).\n    intros H'6 H'7; apply gt_n_S.\n    apply H'0 with (Y := X0); auto with sets arith.\n    apply sincl_add_x with (x := x0).\n    rewrite <- H'6; auto with sets arith.\n    pattern x0 at 1 in |- *; rewrite <- H'6; trivial with sets arith.\n    intros H'6 H'7; red in H'5.\n    elim H'5; intros H'8 H'9; try exact H'8; clear H'5.\n    red in H'8.\n    generalize (H'8 x).\n    intro H'5; lapply H'5; auto with sets arith.\n    intro H; elim Add_inv with U X0 x0 x; auto with sets arith.\n    intro; absurd (In U X0 x); auto with sets arith.\n    intro; absurd (x = x0); auto with sets arith.\n  Qed.\n\n  Lemma incl_card_le :\n    forall (X Y:Ensemble U) (n m:nat),\n      cardinal U X n -> cardinal U Y m -> Included U X Y -> n <= m.\n  Proof.\n    intros; elim Included_Strict_Included with U X Y; auto with sets arith; intro.\n    cut (m > n); auto with sets arith.\n    apply incl_st_card_lt with (X := X) (Y := Y); auto with sets arith.\n    generalize H0; rewrite <- H2; intro.\n    cut (n = m).\n    intro E; rewrite E; auto with sets arith.\n    apply cardinal_unicity with X; auto with sets arith.\n  Qed.\n\n  Lemma G_aux :\n    forall P:Ensemble U -> Prop,\n      (forall X:Ensemble U,\n\tFinite U X ->\n\t(forall Y:Ensemble U, Strict_Included U Y X -> P Y) -> P X) ->\n      P (Empty_set U).\n  Proof.\n    intros P H'; try assumption.\n    apply H'; auto with sets.\n    clear H'; auto with sets.\n    intros Y H'; try assumption.\n    red in H'.\n    elim H'; intros H'0 H'1; try exact H'1; clear H'.\n    lapply (less_than_empty U Y); [ intro H'3; try exact H'3 | assumption ].\n    elim H'1; auto with sets.\n  Qed.\n\n  Lemma Generalized_induction_on_finite_sets :\n    forall P:Ensemble U -> Prop,\n      (forall X:Ensemble U,\n\tFinite U X ->\n\t(forall Y:Ensemble U, Strict_Included U Y X -> P Y) -> P X) ->\n      forall X:Ensemble U, Finite U X -> P X.\n  Proof.\n    intros P H'0 X H'1.\n    generalize P H'0; clear H'0 P.\n    elim H'1.\n    intros P H'0.\n    apply G_aux; auto with sets.\n    clear H'1 X.\n    intros A H' H'0 x H'1 P H'3.\n    cut (forall Y:Ensemble U, Included U Y (Add U A x) -> P Y); auto with sets.\n    generalize H'1.\n    apply H'0.\n    intros X K H'5 L Y H'6; apply H'3; auto with sets.\n    apply Finite_downward_closed with (A := Add U X x); auto with sets.\n    intros Y0 H'7.\n    elim (Strict_inclusion_is_transitive_with_inclusion U Y0 Y (Add U X x));\n      auto with sets.\n    intros H'2 H'4.\n    elim (Included_Add U Y0 X x);\n      [ intro H'14\n\t| intro H'14; elim H'14; intros A' E; elim E; intros H'15 H'16; clear E H'14\n\t| idtac ]; auto with sets.\n    elim (Included_Strict_Included U Y0 X); auto with sets.\n    intro H'9; apply H'5 with (Y := Y0); auto with sets.\n    intro H'9; rewrite H'9.\n    apply H'3; auto with sets.\n    intros Y1 H'8; elim H'8.\n    intros H'10 H'11; apply H'5 with (Y := Y1); auto with sets.\n    elim (Included_Strict_Included U A' X); auto with sets.\n    intro H'8; apply H'5 with (Y := A'); auto with sets.\n    rewrite <- H'15; auto with sets.\n    intro H'8.\n    elim H'7.\n    intros H'9 H'10; apply H'10 || elim H'10; try assumption.\n    generalize H'6.\n    rewrite <- H'8.\n    rewrite <- H'15; auto with sets.\n  Qed.\n\nEnd Finite_sets_facts.\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/Sets/Finite_sets_facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.6626758451857404}}
{"text": "\n\n  (*                                                                                  *)\n  (* To convert cons to append in proofs *)\n  (*\n  Lemma cons_append {A:Type} : forall (head:A) (tail:LO A), cons head tail = append (cons head nil) tail.\n  Proof.\n    intros head tail.\n    simpl.\n    reflexivity.\n  Qed.\n  *)\n\n\n  (* Simplification lemma to remove empty lists on the right of append *)\n  (*\n  Lemma append_nil {A:Type} : forall l : LO A, append l nil = l.\n  Proof.\n    (* We will work on that list *)\n    intro l.\n    (* We proceed by induction over the list *)\n    induction l as [| head tail ih].\n    (* Base case *)\n    {\n      (* Simple evaluation of the fixpoint *)\n      simpl.\n      (* We have equality *)\n      reflexivity.\n    }\n    (* Induction case *)\n    {\n      (* Evaluation *)\n      simpl.\n      (* By induction, appending nil to the tail gives back the tail *)\n      rewrite ih.\n      (* So we have equality *)\n      reflexivity.\n    }\n  Qed.\n  *)\n\n  (* Associativity of append *)\n  (*\n  Lemma append_assoc {A:Type} : associative (append (A:=A)) .\n  Proof.\n    (* We unfold the definition of associativity *)\n    red.\n    (* We introduce our three lists *)\n    intros x y z.\n    (* And we proceed by induction over x *)\n    induction x as [|head tail ih].\n    (* Base case *)\n    {\n      (* Simple evaluation on both sides *)\n      simpl.\n      (* And we have equality *)\n      reflexivity.\n    }\n    (* Induction case *)\n    {\n      (* Simple evaluation on both sides *)\n      simpl.\n      (* We can use our induction hypothesis *)\n      rewrite ih.\n      (* And we have equality *)\n      reflexivity.\n    }\n  Qed.\n  *)\n\n  (* Simple lemmas to eliminate the left part on append when it is the same *)\n  (*\n  Lemma append_intro_l {A:Type} : forall (l m n: LO A), m = n -> append l m = append l n.\n  Proof.\n    (* Introduce the three lists *)\n    intros l m n.\n    (* Introduce the equality hypothesis *)\n    intro heq.\n    (* Replace m with n *)\n    subst m.\n    (* And we have equality *)\n    reflexivity.\n  Qed.\n  *)\n\n  (* Same for the right part on append *)\n  (*\n  Lemma append_intro_r (A:Type) : forall (l m n: LO A), m = n -> append m l = append n l.\n  Proof.\n    intros l m n heq. subst m. reflexivity.\n  Qed.\n  *)\n\n\n\n\n\n\n\n\n  (* This lemma shows that isnatural is conserved by append *)\n(*\n  Lemma append_natural : forall l m, isnatural l -> isnatural m -> isnatural (append l m).\n  Proof.\n    intros l m.\n    unfold isnatural.\n    unfold allnil.\n    (* The induction is actually quite simple, so no comments *)\n    induction l as [|head tail ih].\n    { simpl. intros _ h. exact h. }\n    {\n      simpl.\n      intros [hnil hmatch].\n      intro hm.\n      split.\n      { exact hnil. }\n      { apply ih.\n        { exact hmatch. }\n        { exact hm. }\n      }\n    }\n  Qed.\n*)\n\n\n\n\n\n\n  (* The set of natural numbers is a commutative monoid for addition and multiplication *)\n  (*\n  Theorem N_commutative_monoid : commutative_monoid NN Nplus /\\ commutative_monoid NN Nmult.\n  Proof.\n    split.\n    {\n      red.\n      repeat split.\n      { apply Nplus_assoc. }\n      { apply Nplus_comm. }\n      { exists Nzero.\n        intro a.\n        split.\n        { rewrite Nplus_zero_l. reflexivity. }\n        { rewrite Nplus_zero_r. reflexivity. }\n      }\n    }\n      red.\n      repeat split.\n      { apply Nmult_assoc. }\n      { apply Nmult_comm. }\n      { exists None.\n        intro a.\n        split.\n        { rewrite Nmult_one_l. reflexivity. }\n        { rewrite Nmult_one_r. reflexivity. }\n      }\n  Qed.\n*)\n\n  (* (next n) + m = n + (next m) *)\n  Lemma Nplus_next: forall (n m:NN), Nplus (Nnext n) m = Nplus n (Nnext m).\n  Proof.\n    intros n m.\n    rewrite Nplus_next_l.\n    rewrite Nplus_next_r.\n    reflexivity.\n  Qed.\n\n\n\n\n\n\n\n  (* n <= n + m *)\n  Lemma Nle_plus_l : forall n m, Nle n (Nplus n m).\n  Proof.\n\n  Admitted.\n\n\n\n\n\n\n\n\n  (* To converts \"<\" back to \"<=\" in proofs *)\n  Lemma Nlt_le: forall n m, Nle (Nnext n) m -> Nlt n m.\n  Proof.\n    intros n m h.\n    unfold Nlt.\n    exact h.\n  Qed.\n\n\n  (* Length of a list *)\n  Fixpoint length {A:Type} (l : List A) : NN := match l with\n  | nil => Nzero\n  | cons _ tail => Nnext (length tail)\n  end.\n\n  (* A type is infinite if for any (finite) list of elements of that type,\n     it's possible to find another element that is not in the list *)\n  Definition is_infinite (A:Type) := forall (l:List A), exists (a:A), not (inlist l a).\n\n\n  (* Sum of a list *)\n  Fixpoint Nsum (l:List NN) := match l with\n  | nil => Nzero\n  | cons head tail => Nplus head (Nsum tail)\n  end.\n\n  (* If the sum of a list is zero, then all its elements are zero *)\n  Lemma sum_zero : forall (l:List NN), Nsum l = Nzero -> forall a, inlist l a -> a = Nzero.\n  Proof.\n    intro l.\n    induction l as [|head tail ih].\n    (* Base case *)\n    {\n      (* We can't find anything in an empty list *)\n      simpl.\n      intros _.\n      intros a f.\n      inversion f.\n    }\n    {\n      simpl.\n      intro heq.\n      (* head = 0 and sum tail = 0 *)\n      apply Nplus_zero in heq.\n      destruct heq as [hl hr].\n      subst head.\n      specialize (ih hr).\n      clear hr.\n      intro a.\n      specialize (ih a).\n      intro h.\n      (* a = 0 or a is in the tail *)\n      destruct h as [hr | hl].\n      (* a=0 *)\n      {\n        (* therefore a=0 *)\n        exact hr.\n      }\n      (* a is in the tail *)\n      {\n        (* then the induction hypothesis says that a=0 *)\n        specialize (ih hl).\n        exact ih.\n      }\n    }\n  Qed.\n\n  (* Any element in a list is less than their sum *)\n  Lemma sum_lt : forall (l:List NN), forall a, inlist l a -> Nle a (Nsum l).\n  Proof.\n  intro l.\n  induction l as [|head tail ih].\n  (* Base case *)\n  { (* There are no elements in an empty list *)\n    intros a h. simpl in h. inversion h.\n  }\n  {\n    (* Assuming it's true for the tail, we just need to get rid of the head of the list *)\n    intros a h.\n    simpl in *.\n    destruct h as [hl|hr].\n    (* a is the head *)\n    {\n      subst a. simpl.\n      apply Nle_plus_l.\n    }\n    (* a is in the tail *)\n    {\n      specialize (ih _ hr).\n      apply Nle_trans with (Nsum tail).\n      { exact ih. }\n      {\n        simpl.\n        rewrite Nplus_comm.\n        apply Nle_plus_l.\n      }\n    }\n  }\n  Qed.\n\n\n  (* If an element is bigger than any element of the list, then it is not in the list *)\n  Lemma lt_notin_list : forall (l:List NN) (a:NN), (forall x, inlist l x -> Nlt a x) -> not (inlist l a).\n  Proof.\n    intro l.\n    induction l as [|head tail ih].\n    {\n      (* There are no elements in an empty list *)\n      simpl.\n      intros _ _.\n      unfold not.\n      intro f. exact f.\n    }\n    {\n      (* if a is in the list, then we can show that a<a *)\n      intros a h.\n      unfold not.\n      intro hin.\n      unfold not in ih.\n      specialize (h _ hin).\n      apply Nlt_irrefl in h.\n      inversion h.\n    }\n  Qed.\n\n  (* The sum of the elements of a list + 1 is not in the list *)\n  Lemma sum1_not_in_list : forall (l:List NN), not (inlist l (Nplus (Nsum l) None)).\n  Proof.\n\n    (* The sum + 1 of a list is bigger than any elements of the list *)\n    assert(thm:=sum_lt).\n\n    (* We will work on that list *)\n    intro l.\n    specialize (thm l).\n\n    (* Let's call the sum 'S' *)\n    set (S:=Nplus (Nsum l) None). \n\n    (* Negation means proving False *)\n    unfold not in *.\n\n    (* We assume that S in in the list, then derive a contradiction *)\n    intro h.\n\n    (* We can apply thm on S *)\n    specialize (thm S).\n    specialize (thm h).\n    clear h.\n\n    (* Now we can use irreflexivity of \"<\" to derive a contradiction *)\n    eapply Nlt_irrefl with S.\n    subst S.\n    unfold Nlt.\n    rewrite <- Nnext_eq.\n    apply Nle_next_intro.\n    rewrite <- Nnext_eq in thm.\n    exact thm.\n  Qed.\n\n  (* The set of naturals is infinite *)\n  Theorem Ninfinite : is_infinite NN.\n  Proof.\n    (* Being infinite means that for any finite list l of elements of type T,\n       we can find an element of type T that is not in the list *)\n    red.\n    (* We will work on that list *)\n    intro l.\n    (* And in particular, the sum of the list + 1 is not in the list *)\n    exists (Nplus (Nsum l) None).\n    (* This it what we proved just above *)\n    apply sum1_not_in_list.\n  Qed.\n\n\n  Definition divides d n := exists d', Nmult d d' = n.\n\n  Lemma divides_zero_n : forall n:NN, divides n Nzero.\n  Proof.\n    intro n.\n    red.\n    exists Nzero.\n    rewrite Nmult_zero_r.\n    reflexivity.\n  Qed.\n\n  Lemma divides_n_zero : forall n:NN, divides Nzero n -> n = Nzero.\n  Proof.\n    intro n.\n    pattern n;apply Ninduction.\n    (* n = 0 *)\n    { intros _. reflexivity. }\n    (* n > 0 => impossible *)\n    {\n      clear n. intro n.\n      intro ih. clear ih.\n      intro h.\n      unfold divides in *.\n      destruct h as [d h].\n      rewrite Nmult_zero_l in h.\n      (* inversion is kind of magic here, but it will try to match nil against cons head tail and find it can't *)\n      inversion h.\n    }\n  Qed.\n\n  Lemma divides_one_n : forall n:NN, divides None n.\n  Proof.\n    intro n.\n    unfold divides.\n    exists n.\n    rewrite Nmult_one_l.\n    reflexivity.\n  Qed.\n\n  (* n + m = 1 -> (n = 1 and m = 0) or (n = 0 and m = 1) *)\n  Lemma plus_eq_one : forall (n m:NN), Nplus n m = None -> n = None /\\ m = Nzero \\/ n = Nzero /\\ m = None.\n  Proof.\n    (* Induction on n *)\n    intro n.\n    pattern n;apply Ninduction.\n    (* Base case *)\n    {\n      (* n = 0 -> m = 1 *)\n      intros m h.\n      rewrite Nplus_zero_l in h.\n      subst m.\n      (* The right part of the disjunction applies *)\n      right.\n      split.\n      { reflexivity. }\n      { reflexivity. }\n    }\n    (* Induction case *)\n    {\n      (* n and induction hypothesis *)\n      clear n. intro n. intro ih.\n      (* m and equality hypothesis *)\n      intro m. intro h.\n      (* We can deduce n = 0 and m = 0 *)\n      rewrite Nplus_next_l in h.\n      unfold None in h.\n      apply Nnext_elim in h.\n      apply Nplus_zero in h.\n      destruct h as [ hl hr ].\n      (* Substitute n and m with zero *)\n      subst n. subst m.\n      (* Prepare the induction hypothesis *)\n      specialize (ih None).\n      rewrite Nplus_zero_l in ih.\n      specialize (ih (eq_refl _)).\n      (* Examine each \"possibility\" *)\n      destruct ih as [hl | hr].\n      (* The left case is impossible *)\n      {\n        destruct hl as [hl hr].\n        inversion hl.\n      }\n      (* The right case is obvious *)\n      {\n        clear hr.\n        left.\n        split.\n        { unfold None. reflexivity. }\n        { reflexivity. }\n      }\n    }\n  Qed.\n\n  (* n * m = 1 -> n = 1 and m = 1 *)\n  Theorem Nmult_one : forall n m : NN, Nmult n m = None -> n = None /\\ m = None.\n  Proof.\n    (* Induction over n *)\n    intro n.\n    pattern n;apply Ninduction.\n    (* Base case *)\n    {\n      (* n = 0 -> impossible *)\n      intros m h.\n      rewrite Nmult_zero_l in h.\n      inversion h.\n    }\n    (* Induction case *)\n    {\n      (* We don't need the induction hypothesis *)\n      clear n. intro n'. intro ih. clear ih.\n      intro m. intro  h.\n      (* We can deduce that m = 0 or m = 1 *)\n      rewrite Nnext_eq in h.\n      rewrite Nplus_mult_distr_r in h.\n      rewrite Nmult_one_l in h.\n      apply plus_eq_one in h.\n      destruct h as [hl | hr ].\n      (* m = 0 -> impossible *)\n      {\n        destruct hl as [hl hr].\n        subst m.\n        rewrite Nmult_zero_r in hl.\n        inversion hl.\n      }\n      (* m = 1 *)\n      {\n        (* so n' must be zero *)\n        destruct hr as [hl hr].\n        subst m.\n        rewrite Nmult_one_r in hl.\n        subst n'.\n        (* And now it's obvious *)\n        split.\n        { unfold None. reflexivity . }\n        { reflexivity. }\n      }\n    }\n  Qed.\n\n  Lemma divides_n_one : forall n:NN, divides n None -> n = None.\n  Proof.\n  intros n h.\n  unfold divides in h.\n  destruct h as [d h].\n  generalize dependent d.\n  (* Induction over n *)\n  pattern n;apply Ninduction.\n  (* Base case *)\n  {\n    intros d h.\n    rewrite Nmult_zero_l in h.\n    inversion h.\n  }\n  (* Induction case *)\n  {\n    (* We don't need the induction hypothesis *)\n    clear n. intro n'. intro ih. clear ih.\n    intro d. intro h.\n    (* From h, we can deduce that n' = zero, and therefore n = 1 *)\n    apply Nmult_one in h.\n    destruct h as [hl hr].\n    subst d.\n    unfold None in hl.\n    apply Nnext_elim in hl.\n    subst n'.\n    unfold None.\n    reflexivity.\n  }\n  Qed.\n\n  Lemma divides_n_n : forall n, divides n n.\n  Proof.\n    intro n.\n    unfold divides.\n    exists None.\n    rewrite Nmult_one_r.\n    reflexivity.\n  Qed.\n\n  Definition isprime n := forall d, divides d n -> d<>n -> d = None.\n\n  Lemma zero_not_eq_one : Nzero = None -> False.\n  Proof.\n    intro h.\n    inversion h.\n  Qed.\n\n  Lemma two_not_eq_one : Ntwo = None -> False.\n  Proof.\n    intro h.\n    inversion h.\n  Qed.\n\n  Lemma next_zero : Nnext Nzero = None.\n  Proof. unfold None. reflexivity. Qed.\n\n  Lemma zero_not_prime : not (isprime Nzero).\n  Proof.\n    unfold not. intro h.\n    unfold isprime in h.\n    (* For d = zero, we would prove 0 = 1, which is impossible *)\n    specialize (h Ntwo).\n    apply two_not_eq_one.\n    apply h.\n    (* Two divides zero indeed *)\n    clear h.\n    apply divides_zero_n.\n    unfold not. intro heq. inversion heq.\n  Qed.\n\n  Lemma isprime_one : isprime None.\n  Proof.\n    unfold isprime.\n    intro d.\n    intro h.\n    unfold divides in h.\n    destruct h as [d' heq].\n    apply Nmult_one in heq.\n    destruct heq as [hl _].\n    subst d.\n    intros _.\n    reflexivity.\n  Qed.\n\n\n  Lemma plus_eq_two : forall (n m:NN), Nplus n m = Ntwo -> (n = Nzero /\\ m = Ntwo) \\/ (n = None /\\ m = None) \\/ (n = Ntwo /\\ m = Nzero).\n  Proof.\n  intro n.\n  pattern n;apply Ninduction.\n  {\n    intros m h.\n    rewrite Nplus_zero_l in h.\n    subst m.\n    left. split.\n    { reflexivity. }\n    { reflexivity. }\n  }\n  {\n    intros n' ih. clear ih.\n    intros m heq.\n    rewrite Nnext_eq in heq.\n    unfold Ntwo in heq.\n    rewrite Nnext_eq in heq.\n    rewrite (Nplus_comm n') in heq.\n    repeat rewrite <- Nplus_assoc in heq.\n    apply Nplus_elim_l in heq.\n    apply plus_eq_one in heq.\n    destruct heq as [heql | heqr].\n    {\n      destruct heql as [hn hm].\n      subst m.\n      subst n'.\n      right. right.\n      split.\n      { unfold Ntwo. reflexivity. }\n      { reflexivity. }\n    }\n    {\n      destruct heqr as [hn hm].\n      subst n'. subst m.\n      right. left. split.\n      { unfold None. reflexivity. }\n      { reflexivity. }\n    }\n  }\n  Qed.\n\n  Lemma Nmult_zero : forall n m, Nmult n m = Nzero -> n = Nzero \\/ m = Nzero.\n  Proof.\n  intro n.\n  pattern n;apply Ninduction.\n  {\n    intro m. intro heq. clear heq.\n    left. reflexivity.\n  }\n  {\n    clear n. intro n'. intro ih. clear ih.\n    intro m. intro heq.\n    rewrite Nnext_eq in heq.\n    rewrite Nplus_mult_distr_r in heq.\n    rewrite Nmult_one_l in heq.\n    apply Nplus_zero in heq.\n    destruct heq as [hl hr].\n    subst m.\n    right.\n    reflexivity.\n  }\n  Qed.\n\n  Lemma isprime_two : isprime Ntwo.\n  Proof.\n    unfold isprime.\n    intro d.\n    intro h.\n    intro hneq.\n    unfold divides in h.\n    destruct h as [d' heq].\n    generalize dependent d'.\n    generalize dependent hneq.\n    pattern d;apply Ninduction.\n    {\n      intros hneq d' heq.\n      rewrite Nmult_zero_l in heq.\n      inversion heq.\n    }\n    {\n      clear d. intro d. intro ih.\n      intro hneq. intro d'. intro heq.\n      rewrite Nnext_eq in heq.\n      rewrite Nplus_mult_distr_r in heq.\n      rewrite Nmult_one_l in heq.\n      apply plus_eq_two in heq.\n      destruct heq as [h02 | [h11 | h20]].\n      {\n        destruct h02 as [hl hr].\n        subst d'.\n        apply Nmult_zero in hl.\n        destruct hl as [hl | hr].\n        {\n          subst d.\n          unfold None.\n          reflexivity.\n        }\n        { inversion hr. }\n      }\n      {\n        destruct h11 as [hl hr].\n        subst d'.\n        rewrite Nmult_one_r in hl.\n        subst d.\n        clear ih.\n        exfalso.\n        apply hneq.\n        unfold Ntwo.\n        reflexivity.\n      }\n      {\n        destruct h20 as [hl hr].\n        subst d'.\n        rewrite Nmult_zero_r in hl.\n        inversion hl.\n      }\n    }\n  Qed.\n\n  Lemma zero_neq_two : Nzero = Ntwo -> False.\n  Proof.\n    intro i. inversion i.\n  Qed.\n\n  Lemma one_neq_two : None = Ntwo -> False.\n  Proof.\n    intro h.\n    inversion h.\n  Qed.\n\n  Lemma Nplus_elim_one_r : forall n m p:NN, Nplus n m = Nplus p None ->\n    (exists n', Nplus n' m  = p) \\/\n    (exists m', Nplus n  m' = p).\n  Proof.\n    intro n.\n    pattern n;apply Ninduction.\n    {\n      intro m.\n      intro p.\n      intro heq.\n      rewrite Nplus_zero_l in heq.\n      subst m.\n      right.\n      exists p.\n      rewrite Nplus_zero_l.\n      reflexivity.\n    }\n    {\n      clear n. intro n'. intro ih.\n      intro m. intro p. intro heq.\n      specialize (ih (Nnext m)).\n      specialize (ih p).\n      rewrite Nplus_next_l in heq.\n      rewrite <- Nplus_next_r in heq.\n      specialize (ih heq).\n      destruct ih as [hl | hr].\n      {\n        destruct hl as [z hz].\n        left.\n        exists (Nnext z).\n        rewrite Nplus_next_l.\n        rewrite <- Nplus_next_r.\n        exact hz.\n      }\n      {\n        destruct hr as [z hz].\n        rewrite Nplus_next_r in heq.\n        rewrite <- Nnext_eq in heq.\n        apply Nnext_elim in heq.\n        rewrite <- heq in hz.\n        apply Nplus_elim_l in hz.\n        subst z.\n        left.\n        exists n'.\n        exact heq.\n      }\n    }\n  Qed.\n\n  Definition three := Nnext Ntwo.\n\n  Lemma isprime_three : isprime three.\n  Proof.\n\n  Admitted.\n\n  Definition Neven (n:NN) := divides Ntwo n.\n  Definition Nodd (n:NN) := not (Neven n).\n\n  Lemma mult_two_r : forall n, Nmult n Ntwo = Nplus n n.\n  Proof.\n    intro n.\n    unfold Ntwo.\n    rewrite Nnext_eq.\n    rewrite Nplus_mult_distr_l.\n    repeat rewrite Nmult_one_r.\n    reflexivity.\n  Qed.\n\n  Lemma mult_two_l : forall n, Nmult Ntwo n = Nplus n n.\n  Proof.\n    intro n.\n    rewrite Nmult_comm.\n    apply mult_two_r.\n  Qed.\n\n  Lemma not_even_odd : forall (n:NN), not (Neven n /\\ Nodd n).\n  Proof.\n    intro n.\n    unfold not.\n    intros [heven hodd].\n    unfold Nodd in hodd.\n    apply hodd.\n    exact heven.\n  Qed.\n\n  Lemma Neven_2k : forall (k:NN), Neven (Nmult Ntwo k).\n  Proof.\n  intro k.\n  pattern k;apply Ninduction.\n  { unfold Neven. rewrite Nmult_zero_r. apply divides_zero_n. }\n  {\n    clear k. intro k'. intro ih. clear ih.\n    unfold Neven.\n    unfold divides.\n    exists (Nnext k').\n    reflexivity.\n  }\n  Qed.\n  \n  Lemma Ndestruct : forall n:NN, n = Nzero \\/ exists n', n = Nnext n'.\n  Proof.\n    intro n.\n    pattern n;apply Ninduction.\n    { left. reflexivity. }\n    {\n      clear n. intro n'. intro ih.\n      destruct ih as [hl | hr].\n      {\n        subst n'.\n        right.\n        exists Nzero.\n        reflexivity.\n      }\n      {\n        destruct hr as [n'' heq].\n        subst n'.\n        right.\n        exists (Nnext n'').\n        reflexivity.\n      }\n    }\n  Qed.\n    \n\n  Lemma Nodd_2k1 : forall (k:NN), Nodd (Nnext (Nmult Ntwo k)).\n  Proof.\n  intro k.\n  pattern k;apply Ninduction.\n  {\n    rewrite Nmult_zero_r.\n    unfold Nodd.\n    unfold not.\n    intro heven.\n    unfold Neven in heven.\n    unfold divides in heven.\n    destruct heven as [e he].\n    clear k.\n    generalize dependent he.\n    pattern e;apply Ninduction.\n    {\n      intro h.\n      rewrite Nmult_zero_r in h.\n      inversion h.\n    }\n    {\n      clear e. intro e'. intro hi. clear hi. intro h.\n      rewrite mult_two_l in h.\n      fold None in h.\n      apply plus_eq_one in h.\n      destruct h as [h | h].\n      { destruct h as [hl hr]. rewrite hr in hl. inversion hl. }\n      { destruct h as [hl hr]. rewrite hr in hl. inversion hl. }\n    }\n  }\n  {\n    clear k. intro k'. intro ih.\n    unfold Nodd.\n    unfold not.\n    intro heq.\n    unfold Neven in heq.\n    unfold divides in heq.\n    destruct heq as [d heq].\n    unfold Nodd in ih.\n    unfold not in ih.\n    apply ih.\n    clear ih.\n    unfold Neven.\n    unfold divides.\n    rewrite mult_two_l in heq.\n    rewrite mult_two_l in heq.\n    rewrite Nplus_next_r in heq.\n    rewrite Nplus_next_l in heq.\n    rewrite mult_two_l.\n    assert (hd:=Ndestruct d).\n    {\n      destruct hd as [hz | he].\n      { subst d. rewrite Nplus_zero_l in heq. inversion heq. }\n      {\n        destruct he as [d' heq']. subst d.\n        rewrite Nplus_next_r in heq.\n        rewrite Nplus_next_l in heq.\n        apply Nnext_elim in heq.\n        apply Nnext_elim in heq.\n        exists d'.\n        rewrite mult_two_l.\n        exact heq.\n      }\n    }\n  }\n  Qed.\n\n  Lemma Ndestruct_odd_even : forall n:NN, (exists k, n = Nmult Ntwo k) \\/ (exists k, n = Nnext (Nmult Ntwo k)).\n  Proof.\n  intro n.\n  pattern n;apply Ninduction.\n  {\n    left.\n    exists Nzero.\n    rewrite Nmult_zero_r.\n    reflexivity.\n  }\n  {\n    clear n. intro n'. intro ih.\n    destruct ih as [h|h].\n    {\n      destruct h as [k h].\n      subst n'.\n      right.\n      exists k.\n      reflexivity.\n    }\n    {\n      destruct h as [k h].\n      subst n'.\n      left.\n      exists (Nnext k).\n      rewrite mult_two_l.\n      rewrite mult_two_l.\n      rewrite Nplus_next_r.\n      rewrite Nplus_next_l.\n      reflexivity.\n    }\n  }\n  Qed.\n\n  Lemma next_not_eq : forall n:NN, n = Nnext n -> False.\n  Proof.\n    intro n.\n    pattern n;apply Ninduction.\n    { intro heq. inversion heq. }\n    {\n      clear n. intro n'. intro ih.\n      intro hneq.\n      apply Nnext_elim in hneq.\n      apply ih.\n      exact hneq.\n    }\n  Qed.\n\n  Lemma even_or_odd : forall (n:NN), Neven n \\/ Nodd n.\n  Proof.\n    intro n.\n    assert (h:=Ndestruct_odd_even n).\n    destruct h as [h | h].\n    {\n      destruct h as [k h].\n      left.\n      unfold Neven.\n      unfold divides.\n      exists k.\n      subst n.\n      reflexivity.\n    }\n    {\n      destruct h as [k h].\n      right.\n      unfold Nodd.\n      unfold not.\n      intro heven.\n      unfold Neven in heven.\n      unfold divides in heven.\n      destruct heven as [k' h'].\n      rewrite <- h' in h.\n      clear h'. clear n.\n      rename k into m.\n      rename k' into n.\n      repeat rewrite mult_two_l in h.\n      generalize dependent m.\n      pattern n;apply Ninduction.\n      {\n        intro m.\n        rewrite Nplus_zero_l.\n        intro h.\n        inversion h.\n      }\n      {\n        clear n. intros n' ih. intros m heq.\n        rewrite Nplus_next_r in heq.\n        rewrite Nplus_next_l in heq.\n        apply Nnext_elim in heq.\n        assert (dm:=Ndestruct m).\n        destruct dm as [hl | hr].\n        { subst m. rewrite Nplus_zero_l in heq. inversion heq. }\n        {\n          destruct hr as [m' heq'].\n          subst m.\n          specialize (ih m').\n          apply ih.\n          rewrite Nplus_next_r in heq.\n          rewrite Nplus_next_l in heq.\n          apply Nnext_elim in heq.\n          exact heq.\n        }\n      }\n    }\n  Qed.\n\n\n\n\n\n\n\n\n  Lemma min_nm : forall n m, Nle (Nmin n m) n /\\ Nle (Nmin n m) m.\n  Proof.\n    intros n m.\n    split.\n    {\n      unfold Nmin.\n      destruct (Nle_dec n m).\n      { apply Nle_refl. }\n      { exact n0. }\n    }\n    {\n      unfold Nmin.\n      destruct (Nle_dec n m).\n      { exact n0. }\n      { apply Nle_refl. }\n    }\n  Qed.\n\n\n  Lemma plus_min_minus_max : forall n m, Nplus (Nmin n m) (Nrest n m) = Nmax n m.\n  \n  Proof.\n    intro n.\n    pattern n;apply Ninduction;clear n.\n    {\n      intro m.\n      rewrite Nmin_zero_l.\n      rewrite Nrest_zero_l.\n      rewrite Nplus_zero_l.\n      rewrite Nmax_zero_l.\n      reflexivity.\n    }\n    {\n      intros n' ih.\n      intro m.\n      destruct (Ndestruct m).\n      {\n        subst m.\n        rewrite Nmin_zero_r.\n        rewrite Nrest_zero_r.\n        rewrite Nmax_zero_r.\n        rewrite Nplus_zero_l.\n        reflexivity.\n      }\n      {\n        destruct H. subst m. rename x into m.\n        rewrite Nmin_next.\n        rewrite Nrest_next.\n        rewrite Nmax_next.\n        rewrite Nplus_next_l.\n        apply f_eq.\n        apply ih.\n      }\n    }\n  Qed.\n\n  Lemma zero_eq : forall (h:isnatural _Nzero), exist _ _Nzero h = Nzero.\n  Proof.\n    intro h.\n    apply proof_irrelevance.\n    simpl. reflexivity.\n  Qed.\n\n\n\n  Lemma destruct_min_le_n : forall n m, (Nle n m /\\ Nmin n m = n) \\/ (Nle m n /\\ Nmin n m = m).\n  Proof.\n    intro n.\n    pattern n;apply Ninduction;clear n.\n    {\n      intro m.\n      rewrite Nmin_zero_l.\n      left.\n      split.\n      { apply Nle_zero_l. }\n      { reflexivity. }\n    }\n    {\n      intros n' ih.\n      intro m.\n      destruct (Ndestruct m).\n      {\n        subst m. rewrite Nmin_zero_r. right. split.\n        { apply Nle_zero_l. }\n        { reflexivity. }\n      }\n      {\n        destruct H. subst m. rename x into m'.\n        rewrite Nmin_next.\n        specialize (ih m').\n        destruct ih as [ih|ih].\n        {\n          destruct ih as [hle heq]. left. split.\n          { apply Nle_next_intro. exact hle. }\n          { apply f_eq. exact heq. }\n        }\n        {\n          destruct ih as [hle heq]. right. split.\n          { apply Nle_next_intro. exact hle. }\n          { apply f_eq. exact heq. }\n        }\n      }\n    }\n  Qed.\n\n\n  Lemma min_nm_neq_n : forall n m, Nmin n m <> n -> Nmin n m = m.\n  Proof.\n    intro n.\n    pattern n;apply Ninduction;clear n.\n    { intro m. rewrite Nmin_zero_l. intro h. exfalso. apply h. reflexivity. }\n    {\n    intros n' ih m h.\n    destruct (Ndestruct m).\n    { subst m. rewrite Nmin_zero_r. reflexivity. }\n    {\n    destruct H. subst m. rename x into m'.\n    rewrite Nmin_next.\n    apply f_eq.\n    specialize (ih m').\n    apply ih.\n    intro heq.\n    apply h.\n    rewrite Nmin_next.\n    apply f_eq.\n    exact heq.\n    }\n    }\nQed.\n\n\n\n  Lemma Nrest_one : forall n:NN, n <> Nzero -> Nnext (Nrest n None) = n.\n  Proof.\n    intros n.\n    induction n using Ninduction.\n    { intro i. contradiction i. reflexivity. }\n    { intros _. unfold None. rewrite Nrest_next. rewrite Nrest_zero_r. reflexivity. }\n  Qed.\n\n  Definition Ndestruct_dec n : sumbool (n=Nzero) (exists n', n = Nnext n').\n  Proof.\n    destruct (Neq_dec n Nzero) as [d|d].\n    { left. exact d. }\n    { right. exists (Nrest n None). rewrite Nrest_one. reflexivity. exact d. }\n  Qed.\n\n\n\n  Lemma Nneq_zero_lt : forall x:NN, x <> Nzero -> Nlt Nzero x.\n  Proof.\n    intros x h.\n    unfold Nlt.\n    destruct (Ndestruct x).\n    { subst x. contradiction h. reflexivity. }\n    { destruct H. subst x. apply Nle_next_intro. apply Nle_zero_l. }\n  Qed.\n\n  Lemma xxx : forall x y ,x <> y -> Nle x y -> Nlt x y.\nintro x.\ninduction x using Ninduction.\n{ intros. unfold Nlt. destruct (Ndestruct y).\n{ subst y. contradiction H. reflexivity. }\n{ destruct H1. subst y. apply Nle_next_intro. apply Nle_zero_l. }\n}\n{ intros. unfold Nlt in *.\ndestruct (Ndestruct y).\n{ subst y. inversion H0. }\n{ destruct H1. subst y. apply Nle_next_intro.\napply IHx.\nintro. subst x0. apply H. reflexivity.\napply Nle_next_elim. assumption.\n}\n}\nQed.\n\n  Definition Nlt_dec x y : sumbool (Nle x y) (Nlt y x).\n    destruct (Neq_dec x y).\n    { subst y. left. apply Nle_refl. }\n    { destruct (Nle_dec x y).\n      { left. assumption. }\n      { right. apply xxx. intro. subst y. apply n. reflexivity. assumption. }\n    }\n  Defined.\n\nDefinition computational_eq {m n} (opaque_eq:m=n) : m = n :=\nmatch Neq_dec m n with\n| left transparent_eq => transparent_eq\n| _ => opaque_eq\nend.\n\n\nDefinition Npred (n:NN) (h:Nlt Nzero n) := Nrest n None.\n\nLemma Nnext_pred : forall n h, Nnext (Npred n h) = n.\nProof.\n  intro n.\n  induction n using Ninduction.\n  { intros. inversion h. }\n  {\n    intros. unfold Npred.\n    unfold None. rewrite Nrest_next. rewrite Nrest_zero_r.\n    reflexivity.\n  }\nQed.\n\nDefinition uu : forall x : NN, (forall y : NN, Nlt y x -> NN -> NN) -> NN -> NN.\nintros. apply Nzero.\nDefined.\nPrint uu.\n\nLemma vv x (r:Nzero <> x) : Nlt (Nrest x None) x.\nProof.\nunfold Nlt.\nunfold None.\nassert (u:=Nnext_pred).\nspecialize (u x).\nassert (v:Nlt Nzero x).\napply Nneq_zero_lt. intro heq. subst x. apply r. reflexivity.\nspecialize (u v).\npattern x at 1;rewrite <- u. rewrite Nrest_next. rewrite Nrest_zero_r.\nrewrite u. apply Nle_refl.\nDefined.\n\nDefinition _Nfact_main (x:NN) (f : forall y : NN, Nlt y x -> NN) : NN.\ndestruct (Neq_dec Nzero x).\n{ apply None. }\n{\n  specialize (f (Nrest x None)).\n  assert (Nlt (Nrest x None) x).\n  { apply vv. exact n. }\n  specialize (f H).\n  apply (Nmult x f).\n}\nDefined.\n\nDefinition Nfact := Fix Nlt_wf _ _Nfact_main.\n\nLemma Nfact_zero : Nfact Nzero = None.\nunfold Nfact. unfold Fix. simpl.\nunfold _Nfact_main. simpl. reflexivity.\nQed.\n\nLemma Nfact_one: Nfact None = None.\nProof.\nunfold Nfact.\nassert (h:=Fix_eq).\nspecialize (h NN Nlt Nlt_wf).\nspecialize (h _ _Nfact_main).\nrewrite h.\n{\nunfold _Nfact_main. rewrite Nmult_one_l. rewrite Nrest_cancel.\nrewrite h.\n{\nunfold _Nfact_main. simpl. reflexivity. }\n{\nclear h.\nintros.\nunfold _Nfact_main.\ndestruct (Neq_dec _).\n{ reflexivity. }\n{ rewrite H. reflexivity. }\n}\n}\nclear h.\nintros.\nunfold _Nfact_main.\ndestruct (Neq_dec _).\n{ reflexivity. }\n{ rewrite H. reflexivity. }\nQed.\n\nLemma Nfact_r : forall n, Nfact (Nnext n) = Nmult (Nnext n) (Nfact n).\nProof.\nintro n.\ninduction n using Ninduction.\n{\nrewrite Nfact_zero. rewrite Nmult_one_r.\nfold None. rewrite Nfact_one. reflexivity.\n}\n{\nrename IHn into ih.\nremember (Nfact n) as fn.\nremember (Nfact (Nnext n)) as fnn.\nremember (Nfact (Nnext (Nnext n))) as fnnn.\nunfold Nfact in Heqfnnn.\nrewrite Fix_eq in Heqfnnn.\n{\nunfold _Nfact_main in Heqfnnn.\ndestruct (Neq_dec _) in Heqfnnn.\n{ inversion e. }\n{\nunfold Nfact in Heqfnn.\nunfold _Nfact_main in Heqfnn.\nunfold None at 3 in Heqfnnn.\nrewrite Nrest_next in Heqfnnn.\nrewrite Nrest_zero_r in Heqfnnn.\nrewrite <- Heqfnn in Heqfnnn.\nrewrite Heqfnnn.\nreflexivity.\n}\n}\n{\nclear. intros.\nunfold _Nfact_main.\ndestruct (Neq_dec _).\n{ reflexivity. }\n{ rewrite H. reflexivity. }\n}\n}\nQed.\n\n  (* If allmatch is true for two lists, then it is true for their concatenation *)\n  (*\n  Theorem allmatch_append {A:Type} : forall (l m:LO A) (P:A->Prop),\n    allmatch l P -> allmatch m P -> allmatch (append l m) P.\n  Proof.\n    (* We introduce both lists and the predicate *)\n    intros l m P.\n    (* And we will proceed by induction *)\n    induction l as [|head tail ih].\n    (* Base case *)\n    {\n      (* We don't need that *)\n      intros _.\n      (* This is the allmatch hypothesis for m *)\n      intro hm.\n      (* Simple evaluation *)\n      simpl.\n      (* And that's exactly our hypothesis *)\n      exact hm.\n    }\n    (* Induction case *)\n    {\n      (* Hypotheses on n and m *)\n      intros hn hm.\n      (* Simple evaluation in goal and hypotheses *)\n      simpl in *.\n      (* The predicate applies to the head and to the tail *)\n      destruct hn as [hhead htail].\n      (* And we have to prove that the predicate applies to th ehead, the tail and m. *)\n      split.\n      (* We already know this *)\n      { exact hhead. }\n      (* Here we have to use the induction hypothesis *)\n      {\n        clear hhead.\n        (* The predicate applies to the tail because htail *)\n        specialize (ih htail). clear htail.\n        (* And it applies to m because hm *)\n        specialize (ih hm). clear hm.\n        (* And therefore, we have our goal *)\n        exact ih.\n      }\n    }\n  Qed.\n  *)\n\n  (* In an empty list of lists, all elements are empty *)\n  (*\n  Lemma allnil_nil {A:Type} : allnil (nil (A:=LOLO A)).\n  Proof.\n    red.\n    simpl.\n    trivial.\n  Qed.\n  *)\n\n  (* In a list of lists, if all elements are the empty list, then append commutes for these two lists *)\n  (*\n  Lemma allnil_append_comm {A:Type} : forall (l m : LOLO A), allnil l -> allnil m -> append l m = append m l.\n  Proof.\n    (* Induction on l *)\n    intros l m.\n    induction l as [|head tail ih].\n    (* Base case *)\n    {\n      (* We don't care about the hypotheses for that case *)\n      intros _ _.\n      (* Left is simplified by definition of the fixpoint for append *)\n      simpl.\n      (* For the right side, we need our previous theorem *)\n      rewrite append_nil.\n      (* And we have equality *)\n      reflexivity.\n    }\n    (* Induction case *)\n    {\n      (* First, we introduce and massage the hypotheses *)\n      simpl in *.\n      intros hx hy.\n      red in hx, hy.\n      simpl in *.\n      destruct hx as [hnil hmatch].\n      red in hnil.\n      subst head.\n      (* Then we prepare to use the induction hypothese *)\n      unfold allnil in ih.\n      specialize (ih hmatch). clear hmatch.\n      specialize (ih hy).\n      (* And we use it for rewrite *)\n      rewrite ih. clear ih.\n      (* Now we proceed by induction over m *)\n      induction m as [|mhead mtail ih].\n      (* Base case for m *)\n      { simpl. reflexivity. }\n      (* Induction case for m *)\n      {\n        (* Again we massage the hypotheses *)\n        simpl.\n        simpl in hy.\n        destruct hy as [hnil hmatch'].\n        red in hnil.\n        subst mhead.\n        (* Prepare the induction hypothese *)\n        specialize (ih hmatch').\n        (* Use it for rewrite *)\n        rewrite ih. clear ih.\n        (* And we have equality *)\n        reflexivity.\n      }\n    }\n  Qed.\n  *)", "meta": {"author": "xavierdpt", "repo": "xdcoq", "sha": "e17c739a571f0fc6c5a7fd912bc93a5b18c22f02", "save_path": "github-repos/coq/xavierdpt-xdcoq", "path": "github-repos/coq/xavierdpt-xdcoq/xdcoq-e17c739a571f0fc6c5a7fd912bc93a5b18c22f02/Remnants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673223709252, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.6626758434312935}}
{"text": "Require Import Exception.\n\nDefinition boolᵉ : TYPE := mkTYPE bool.\n\nDefinition trueᵉ : El boolᵉ := mkPack _ true true.\nDefinition falseᵉ : El boolᵉ := mkPack _ true false.\n\nLtac val := refine (mkPack _ true _).\n\nDefinition bool_caseᵉ : El (Πᵉ (P : El Typeᵉ) (p0 : El P) (p1 : El P) (b : El boolᵉ), P).\nProof.\nval; intros P.\nval; intros p0.\nval; intros p1.\nval; intros b.\ndestruct b as [[|] b].\n+ destruct b as [|]; [exact p0|exact p1].\n+ apply empty.\nDefined.\n\nCheck eq_refl : (fun P p0 p1 => Appᵉ (Appᵉ (Appᵉ (Appᵉ bool_caseᵉ P) p0) p1) trueᵉ) = fun P p0 p1 => p0.\nCheck eq_refl : (fun P p0 p1 => Appᵉ (Appᵉ (Appᵉ (Appᵉ bool_caseᵉ P) p0) p1) falseᵉ) = fun P p0 p1 => p1.\n\nDefinition bool_rectᵉ : El (Πᵉ (P : El (Πᵉ (b : El boolᵉ), Typeᵉ))\n  (p0 : El (Appᵉ P trueᵉ)) (p1 : El (Appᵉ P falseᵉ)) (b : El boolᵉ), Appᵉ P b).\nProof.\nval; intros P.\nval; intros p0.\nval; intros p1.\nval; intros b.\ndestruct b as [[|] b].\n+ destruct b as [|]; [exact p0|exact p1].\n+ apply empty.\nDefined.\n\nCheck eq_refl : (fun P p0 p1 => Appᵉ (Appᵉ (Appᵉ (Appᵉ bool_rectᵉ P) p0) p1) trueᵉ) = fun P p0 p1 => p0.\nCheck eq_refl : (fun P p0 p1 => Appᵉ (Appᵉ (Appᵉ (Appᵉ bool_rectᵉ P) p0) p1) falseᵉ) = fun P p0 p1 => p1.\n", "meta": {"author": "CoqHott", "repo": "coq-effects", "sha": "8059d06b525c944c8da241d2e6dd18a0c9080999", "save_path": "github-repos/coq/CoqHott-coq-effects", "path": "github-repos/coq/CoqHott-coq-effects/coq-effects-8059d06b525c944c8da241d2e6dd18a0c9080999/theories/exception/Bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.662626971521648}}
{"text": "Load \"4_bag_functions\".\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n  | []        => []\n  | cons x s' => match (Nat.eqb x v) with\n                 | true  => s'\n                 | false => cons x (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.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_remove_one2 : count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_remove_one3 : count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_remove_one4 : count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n  match s with\n  | []        => []\n  | cons x s' => match (Nat.eqb x v) with\n                 | true  => remove_all v s'\n                 | false => cons x (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.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n  | []         => true\n  | cons x s1' => match (member x s2) with\n                  | true  => subset s1' (remove_one x s2)\n                  | false => false\n                  end\n  end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n", "meta": {"author": "FengZiGG", "repo": "coqlf", "sha": "73aea6d263b0e05d8e25c5ce1f6609faf8e3956c", "save_path": "github-repos/coq/FengZiGG-coqlf", "path": "github-repos/coq/FengZiGG-coqlf/coqlf-73aea6d263b0e05d8e25c5ce1f6609faf8e3956c/3_Lists/5_bag_more_functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.6626268748360773}}
{"text": "(** * Uprop.v : Properties of operators on [[0,1]] *)\nSet Implicit Arguments.\nUnset Standard Proposition Elimination Names.\nRequire Export Arith.\nRequire Export Omega.\nRequire Export Ubase.\nModule Univ_prop (Univ:Universe).\nImport Univ.\n\nHint Resolve Ueq_refl.\nHint Resolve Upos Unit Udiff_0_1 Unth_prop Ueq_le.\nHint Resolve Uplus_sym Uplus_assoc Umult_sym Umult_assoc.\nHint Resolve Uinv_one Uinv_opp_left Uinv_plus_left.\nHint Resolve Uplus_zero_left Umult_one_left Udistr_plus_right Udistr_inv_right.\nHint Resolve Uplus_le_compat_left Umult_le_compat_left Uinv_le_compat.\nHint Resolve lub_le le_lub lub_eq_mult lub_eq_plus_cte_right.\nHint Resolve Ule_total Ule_class.\nHint Immediate Ueq_sym Ule_antisym.\nOpen Scope nat_scope.\nOpen Scope U_scope.\n\n(** ** Direct consequences of axioms  *)\n\nLemma Ueq_class : forall x y, class (x==y).\nred; intros.\napply Ule_antisym;\napply Ule_class; intuition.\nQed.\n\nLemma Ueq_double_neg : forall x y : U, ~ ~x == y -> x == y.\nexact Ueq_class.\nQed.\nHint Resolve Ueq_class.\nHint Immediate Ueq_double_neg.\n\nLemma Ule_orc : forall x y, orc (x<=y) (~ x<=y).\nauto.\nQed.\nImplicit Arguments Ule_orc [].\n\nLemma Ueq_orc : forall x y, orc (x==y) (~ x==y).\nauto.\nQed.\nImplicit Arguments Ueq_orc [].\n\nLemma Ule_0_1 : 0 <= 1.\nauto.\nQed.\n\nLemma Ule_refl : forall x:U,x <= x.\nauto.\nQed.\nHint Resolve Ule_refl.\n\nAdd Relation  U Ule reflexivity proved by Ule_refl transitivity proved by Ule_trans as Ule_Relation.\n\n(** ** Properties of == derived from properties of $\\le$ *)\n\nLemma Ueq_trans : forall x y z:U, x == y -> y == z -> x == z.\nintros; apply Ule_antisym; apply Ule_trans with y; auto.\nQed.\nHint Resolve Ueq_trans.\n\nLemma Uplus_eq_compat_left : forall x y z:U, x == y -> (x + z) == (y + z).\nintros; apply Ule_antisym; auto.\nQed.\n\nHint Resolve Uplus_eq_compat_left.\n\nLemma Uplus_eq_compat_right : forall x y z:U, x == y -> (z + x) == (z + y).\nintros; apply Ueq_trans with (x + z); auto.\napply Ueq_trans with (y + z); auto.\nQed.\n\nLemma Umult_eq_compat_left : forall x y z:U, x == y -> (x * z) == (y * z).\nintros;  apply Ule_antisym; auto.\nQed.\nHint Resolve Umult_eq_compat_left.\n\nLemma Umult_eq_compat_right :  forall x y z:U, x == y -> (z * x) == (z * y).\nintros; apply Ueq_trans with (x * z); auto.\napply Ueq_trans with (y * z); auto.\nQed.\n\nHint Resolve Uplus_eq_compat_right Umult_eq_compat_right.\n\nLemma Uinv_opp_right : forall x, x + [1-] x == 1.\nintros; apply Ueq_trans with ([1-] x + x); auto.\nQed.\nHint Resolve Uinv_opp_right.\n\n(** ** [U] is a setoid *)\n\nLemma Usetoid : Setoid_Theory U Ueq.\nsplit; red ; auto. apply Ueq_trans.\nQed.\n\nAdd Setoid U Ueq Usetoid as U_setoid.\n\nAdd Morphism Uplus with signature Ueq ==> Ueq ==> Ueq as Uplus_eq_compat.\nintros x1 x2 eq1 x3 x4 eq2; apply Ueq_trans with (x1+x4); auto.\nQed.\n\nAdd Morphism Umult with signature Ueq ==> Ueq ==> Ueq as Umult_eq_compat.\nintros x1 x2 eq1 x3 x4 eq2; apply Ueq_trans with (x1 * x4); auto.\nQed.\n\nHint Immediate Umult_eq_compat Uplus_eq_compat.\n\nAdd Morphism Uinv with signature Ueq ==> Ueq as Uinv_eq_compat.\nintros; apply Ule_antisym; auto.\nQed.\n\nAdd Morphism Ule with signature Ueq ==> Ueq ==> iff as Ule_eq_compat_iff.\nintros x1 x2 eq1 x3 x4 eq2; split; intro Hle.\napply Ule_trans with x1; auto.\napply Ule_trans with x3; auto.\napply Ule_trans with x2; auto.\napply Ule_trans with x4; auto.\nQed.\n\nLemma Ule_eq_compat : \nforall x1 x2 : U, x1 == x2 -> forall x3 x4 : U, x3 == x4 -> x1 <= x3 -> x2 <= x4.\nintros x1 x2 eq1 x3 x4 eq2; elim (Ule_eq_compat_iff eq1 eq2); auto.\nQed.\n\n(** ** Definition and properties of $x<y$ *)\nDefinition Ult (r1 r2:U) : Prop := ~ (r2 <= r1).\n\nInfix \"<\" := Ult : U_scope.\n\nHint Unfold Ult.\n\n\nAdd Morphism Ult with signature Ueq ==> Ueq ==> iff as Ult_eq_compat_iff.\nunfold Ult, not; intros x1 x2 eq1 x3 x4 eq2.\ngeneralize (Ule_eq_compat_iff eq2 eq1); intuition.\nQed.\n\nLemma Ult_eq_compat : \nforall x1 x2 : U, x1 == x2 -> forall x3 x4 : U, x3 == x4 -> x1 < x3 -> x2 < x4.\nintros x1 x2 eq1 x3 x4 eq2; elim (Ult_eq_compat_iff eq1 eq2); auto.\nQed.\n\nLemma Ult_class : forall x y, class (x<y).\nunfold Ult; auto.\nQed.\nHint Resolve Ult_class.\n\n(* begin hide *)\n(** Tactic for left normal form with respect to associativity *)\nLtac norm_assoc_left := \n     match goal with \n      | |- context [(Uplus ?X1 (Uplus ?X2 ?X3))] \n        => (setoid_rewrite (Uplus_assoc X1 X2 X3))\n     end.\n\nLtac norm_assoc_right := \n     match goal with \n      | |- context [(Uplus (Uplus ?X1 ?X2) ?X3)] \n        => (setoid_rewrite <- (Uplus_assoc X1 X2 X3))\n     end.\n(* end hide *)\n\n(** *** Properties of $x \\leq y$ *)\n\nLemma Ule_zero_eq :  forall x, x <= 0 -> x == 0.\nintros; apply Ule_antisym; auto.\nQed.\n\nLemma Uge_one_eq : forall x, 1 <= x -> x == 1.\nintros; apply Ule_antisym; auto.\nQed.\n\nHint Immediate Ule_zero_eq Uge_one_eq.\n\n(** *** Properties of $x < y$ *)\n\nLemma Ult_neq : forall x y:U, x < y -> ~x == y.\nunfold Ult; red; auto.\nQed.\n\nLemma Ult_neq_rev : forall x y:U, x < y -> ~y == x.\nunfold Ult; red; auto.\nQed.\n\nLemma Ult_trans : forall x y z, x<y -> y<z -> x <z.\nrepeat red; intros.\napply (Ule_total y z); intros; auto.\napply H; apply Ule_trans with z; auto.\nQed.\n\nLemma Ult_le : forall x y:U, x < y -> x <= y.\nunfold Ult; intros; apply Ule_class; repeat red; intros.\nassert (x < x).\napply Ult_trans with y; auto.\napply H1; auto. \nQed.\n\nLemma Ule_diff_lt : forall x y : U,  x <= y -> ~x==y -> x < y.\nred; intuition.\nQed.\n\nHint Immediate Ult_neq Ult_neq_rev Ult_le.\nHint Resolve Ule_diff_lt.\n\nLemma Ult_neq_zero : forall x, ~(0==x) -> 0 < x.\nauto.\nQed.\n\nHint Resolve Ule_total Ult_neq_zero.\n\n(** ** Properties of $+$ and $\\times$  *)\n\nLemma Udistr_plus_left :  forall x y z, y <= [1-] z -> (x * (y + z)) == (x * y + x * z).\nintros.\nsetoid_rewrite (Umult_sym x (y+z)); setoid_rewrite (Umult_sym x y); \nsetoid_rewrite (Umult_sym x z);auto.\nQed.\n\nLemma Udistr_inv_left :  forall x y, [1-](x * y) == (x * ([1-] y)) + [1-] x.\nintros.\nsetoid_rewrite (Umult_sym x y).\nsetoid_rewrite (Udistr_inv_right y x); auto.\nQed.\n\nHint Resolve Uinv_eq_compat Udistr_plus_left Udistr_inv_left.\n\nLemma Uplus_perm2 : forall x y z:U, x + (y + z) == y + (x + z).\nintros; setoid_rewrite (Uplus_assoc x y z).\nsetoid_rewrite (Uplus_sym x y); auto.\nQed.\n\nLemma Umult_perm2 : forall x y z:U, x * (y * z) == y * (x * z).\nintros; setoid_rewrite (Umult_assoc x y z).\nsetoid_rewrite (Umult_sym x y); auto.\nQed.\n\nLemma Uplus_perm3 : forall x y z : U, (x + (y + z)) == z + (x + y).\nintros; setoid_rewrite (Uplus_assoc x y z); auto.\nQed.\n\nLemma Umult_perm3 : forall x y z : U, (x * (y * z)) == z * (x * y).\nintros; setoid_rewrite (Umult_assoc x y z); auto.\nQed.\n\nHint Resolve Uplus_perm2 Umult_perm2 Uplus_perm3 Umult_perm3.\n\nLemma Uplus_le_compat_right : forall x y z:U, (x <= y) -> (z + x <= z + y).\nintros; setoid_rewrite (Uplus_sym z x);\nsetoid_rewrite (Uplus_sym z y);auto.\nQed.\n\nHint Resolve Uplus_le_compat_right.\n\nLemma Uplus_le_compat : forall x y z t:U, x <= y -> z <= t -> (x + z <= y + t).\nintros; apply Ule_trans with (y + z); auto.\nQed.\nHint Immediate Uplus_le_compat.\n\nLemma Uplus_zero_right : forall x:U, x + 0 == x.\nintros; setoid_rewrite (Uplus_sym x 0); auto.\nQed.\nHint Resolve Uplus_zero_right.\n\n(* ** Properties of [1-] *)\n\nLemma Uinv_zero : [1-] 0 == 1.\napply Ueq_trans with (([1-] (0 + 0))+0); auto.\napply Ueq_trans with ([1-] (0 + 0)); auto.\nsetoid_rewrite (Uplus_zero_right 0); auto.\nQed.\nHint Resolve Uinv_zero.\n\n\nLemma Uinv_inv : forall x : U, [1-] [1-] x == x.\nintros; apply Ueq_trans with ([1-] (x + [1-] x) + x); auto.\napply Ueq_sym; auto.\nsetoid_rewrite (Uinv_opp_right x); setoid_rewrite Uinv_one; auto.\nQed.\nHint Resolve Uinv_inv.\n\nLemma Uinv_simpl :  forall x y : U, [1-] x == [1-] y -> x == y.\nintros; setoid_rewrite <- (Uinv_inv x); \n setoid_rewrite <- (Uinv_inv y); auto.\nQed.\n\nHint Immediate Uinv_simpl.\n\n(** ** More properties on [+] and [*]  and [Uinv] *)\n\nLemma Umult_le_compat_right :  forall x y z: U,  x <= y -> (z * x) <= (z * y).\nintros; setoid_rewrite (Umult_sym z x); setoid_rewrite (Umult_sym z y).\napply Umult_le_compat_left; trivial.\nQed.\n\nHint Resolve Umult_le_compat_right.\n\nAdd Morphism Umult with signature Ule ++> Ule ++> Ule as Umult_le_compat.\nintros x1 x2 H1 x3 x4 H2; apply Ule_trans with (x1 * x4); auto.\nQed.\nHint Immediate Umult_le_compat.\n\nLemma Umult_one_right : forall x:U, (x * 1) == x.\nintros; setoid_rewrite (Umult_sym x 1); auto.\nQed.\nHint Resolve Umult_one_right.\n\n\nLemma Udistr_plus_left_le :  forall x y z : U, x * (y + z) <= x * y + x * z.\nintros; apply (Ule_total y ([1-]z)); intros; auto.\nsetoid_replace (y+z) with ([1-]z+z); auto.\nrewrite Udistr_plus_left; auto.\napply Ule_antisym; auto.\nrewrite Uinv_opp_left; auto.\nQed.\n\nLemma Uplus_eq_simpl_right : \nforall x y z:U, z <= [1-] x -> z <= [1-] y -> (x + z) == (y + z) -> x == y.\nintros; apply Ule_antisym.\napply Uplus_le_simpl_right with z; auto.\napply Uplus_le_simpl_right with z; auto.\nQed.\n\nLemma Ule_plus_right : forall x y, x <= x + y.\nintros; apply Ule_eq_compat with (x + 0) (x + y); auto.\nQed.\n\nLemma Ule_plus_left : forall x y, y <= x + y.\nintros; apply Ule_eq_compat with (0 + y) (x + y); auto.\nQed.\nHint Resolve Ule_plus_right Ule_plus_left.\n\nLemma Ule_mult_right : forall x y, x * y <= x .\nintros; apply Ule_eq_compat with (x * y) (x * 1); auto.\nQed.\n\nLemma Ule_mult_left : forall x y, x * y <= y.\nintros; apply Ule_eq_compat with (x * y) (1 * y); auto.\nQed.\nHint Resolve Ule_mult_right Ule_mult_left.\n\nLemma Uinv_le_perm_right : forall x y:U, x <= [1-] y -> y <= [1-] x.\nintros; apply Ule_trans with ([1-] ([1-] y)); auto.\nQed.\nHint Resolve Uinv_le_perm_right.\n\nLemma Uinv_le_perm_left :  forall x y:U, [1-] x <= y -> [1-] y <= x.\nintros; apply Ule_trans with ([1-] ([1-] x)); auto.\nQed.\nHint Resolve Uinv_le_perm_left.\n\nLemma Uinv_eq_perm_left :  forall x y:U, x == [1-] y -> [1-] x == y.\nintros; apply Ueq_trans with ([1-] ([1-] y)); auto.\nQed.\nHint Immediate Uinv_eq_perm_left.\n\nLemma Uinv_eq_perm_right :  forall x y:U, [1-] x == y ->  x == [1-] y.\nintros; apply Ueq_trans with ([1-] ([1-] x)); auto.\nQed.\n\nHint Immediate Uinv_eq_perm_right.\n\nLemma Uinv_plus_right : forall x y, y <= [1-] x -> [1-] (x + y) + y == [1-] x.\nintros; setoid_rewrite (Uplus_sym x y); auto.\nQed.\nHint Resolve Uinv_plus_right.\n\nLemma Uplus_eq_simpl_left : \nforall x y z:U, x <= [1-] y -> x <= [1-] z -> (x + y) == (x + z) -> y == z.\nintros x y z H1 H2; setoid_rewrite (Uplus_sym x y); setoid_rewrite (Uplus_sym x z); auto.\nintros; apply Uplus_eq_simpl_right with x; auto.\nQed.\n\nLemma Uplus_eq_zero_left : forall x y:U, x <= [1-] y -> (x + y) == y -> x == 0.\nintros; apply Uplus_eq_simpl_right with y; auto.\nsetoid_rewrite H0; auto.\nQed.\n\nLemma Uinv_le_trans : forall x y z t, x <= [1-] y -> z<=x -> t<=y -> z<= [1-] t.\nintros; apply Ule_trans with x; auto.\napply Ule_trans with ([1-] y); auto.\nQed.\n\n\nLemma Uinv_plus_left_le : forall x y, [1-]y <= [1-](x+y) +x.\nintros; apply (Ule_total y ([1-]x)); auto; intros.\nrewrite Uinv_plus_left; auto.\napply Ule_trans with x; auto.\nQed.\n\nLemma Uinv_plus_right_le : forall x y, [1-]x <= [1-](x+y) +y.\nintros; apply (Ule_total y ([1-]x)); auto; intros.\nrewrite Uinv_plus_right; auto.\napply Ule_trans with y; auto.\nQed.\n\nHint Resolve Uinv_plus_left_le Uinv_plus_right_le.\n\n(** ** Disequality *)\n\nLemma neq_sym : forall x y, ~x==y -> ~y==x.\nred; intros; apply H; auto.\nQed.\nHint Immediate neq_sym.\n\nLemma Uinv_neq_compat : forall x y, ~x == y -> ~ [1-] x == [1-] y.\nred; intros; apply H; auto.\nQed.\n\nLemma Uinv_neq_simpl : forall x y, ~ [1-] x == [1-] y-> ~x == y.\nred; intros; apply H; auto.\nQed.\n\nHint Resolve Uinv_neq_compat.\nHint Immediate Uinv_neq_simpl.\n\nLemma Uinv_neq_left : forall x y, ~x == [1-] y -> ~ [1-] x == y.\nred; intros; apply H; auto.\nQed.\n\nLemma Uinv_neq_right : forall x y, ~ [1-] x == y -> ~x == [1-] y.\nred; intros; apply H; auto.\nQed.\n\n(** *** Properties of [<]  *)\n\nLemma Ult_antirefl : forall x:U, ~x < x.\nunfold Ult; intuition.\nQed.\n\nLemma Ult_0_1 : (0 < 1).\nred; intuition.\nQed.\n\nLemma Ule_lt_trans : forall x y z:U, x <= y -> y < z -> x < z.\nunfold Ult; intuition.\napply H0; apply Ule_trans with x; trivial.\nQed.\n\nLemma Ult_le_trans : forall x y z:U, x < y -> y <= z -> x < z.\nunfold Ult; intuition.\napply H; apply Ule_trans with z; trivial.\nQed.\n\nHint Resolve Ult_0_1 Ult_antirefl.\n\n\nLemma Uplus_neq_zero_left : forall x y, ~(0 == x) -> ~(0 == x+y).\nintros; apply Ult_neq.\napply Ult_le_trans with x; auto.\nQed.\n\nLemma Uplus_neq_zero_right : forall x y, ~(0 == y) -> ~(0 == x+y).\nintros; apply Ult_neq.\napply Ult_le_trans with y; auto.\nQed.\n\nLemma not_Ult_le : forall x y, ~x < y -> y <= x.\nintros; apply Ule_class; auto.\nQed.\n\nLemma Ule_not_lt : forall x y, x <= y -> ~y < x.\nrepeat red; intros.\napply H0; auto.\nQed.\n\nHint Immediate not_Ult_le Ule_not_lt.\n\nTheorem Uplus_le_simpl_left : forall x y z : U, z <= [1-] x -> z + x <= z + y -> x <= y.\nintros.\napply Uplus_le_simpl_right with z; auto.\napply Ule_trans with (z + x); auto.\napply Ule_trans with (z + y); auto.\nQed.\n\n\nLemma Uplus_lt_compat_left : forall x y z:U, z <= [1-] y -> x < y -> (x + z) < (y + z).\nunfold Ult; intuition.\napply H0; apply Uplus_le_simpl_right with z; trivial.\nQed.\n\n\nLemma Uplus_lt_compat_right : forall x y z:U, z <= [1-] y -> x < y -> (z + x) < (z + y).\nintros; setoid_rewrite (Uplus_sym z x).\nintros; setoid_rewrite (Uplus_sym z y).\napply Uplus_lt_compat_left; auto.\nQed.\n\nHint Resolve Uplus_lt_compat_right Uplus_lt_compat_left.\n\nLemma Uplus_lt_compat :\nforall x y z t:U, z <= [1-] x -> t <= [1-] y -> x < y -> z < t -> (x + z) < (y + t).\nintros; apply Ult_trans with (y + z); auto.\napply Uplus_lt_compat_left; auto.\napply Ule_trans with t; auto.\nQed.\n\nHint Immediate Uplus_lt_compat.\n\nLemma Uplus_lt_simpl_left : forall x y z:U, z <= [1-] y -> (z + x) < (z + y) -> x < y.\nunfold lt; repeat red; intros.\napply H0; auto.\nQed.\n\nLemma Uplus_lt_simpl_right : forall x y z:U, z <= [1-] y -> (x + z) < (y + z) -> x < y.\nunfold lt; repeat red; intros.\napply H0; auto.\nQed.\n\nLemma Uplus_one_le : forall x y, x + y == 1 -> [1-] y <= x.\nintros; apply Ule_class; red; intros.\nassert (x < [1-] y); auto.\nassert (x + y < [1-] y + y); auto.\nassert (x + y < 1); auto.\nsetoid_rewrite <- (Uinv_opp_left y); auto. \nQed.\nHint Immediate Uplus_one_le.\n\nTheorem Uplus_eq_zero : forall x, x <= [1-] x -> (x + x) == x -> x == 0.\nintros x H1 H2; apply Uplus_eq_simpl_left with x; auto.\nsetoid_rewrite H2; auto.\nQed.\n\nLemma Umult_zero_left : forall x, 0 * x == 0.\nintros; apply Uinv_simpl.\nsetoid_rewrite (Udistr_inv_right 0 x); auto.\nsetoid_rewrite Uinv_zero.\nsetoid_rewrite (Umult_one_left x); auto.\nQed.\nHint Resolve Umult_zero_left.\n\nLemma Umult_zero_right : forall x, (x * 0) == 0.\nintros; setoid_rewrite (Umult_sym x 0); auto.\nQed.\nHint Resolve Uplus_eq_zero Umult_zero_right.\n\n(** *** Compatibility of operations with respect to order. *)\n\nLemma Umult_le_simpl_right : forall x y z, ~(0 == z) -> (x * z) <= (y * z) -> x <= y.\nintros; apply Umult_le_simpl_left with z; auto.\nsetoid_rewrite (Umult_sym z x); \nsetoid_rewrite (Umult_sym z y);trivial.\nQed.\nHint Resolve Umult_le_simpl_right.\n\nLemma Umult_simpl_right : forall x y z, ~(0 == z) -> (x * z) == (y * z) -> x == y.\nintros; apply Ule_antisym; auto.\napply Umult_le_simpl_right with z; auto.\napply Umult_le_simpl_right with z; auto.\nQed.\n\nLemma Umult_simpl_left : forall x y z, ~(0 == x) -> (x * y) == (x * z) -> y == z.\nintros; apply Ule_antisym; auto.\napply Umult_le_simpl_left with x; auto.\napply Umult_le_simpl_left with x; auto.\nQed.\n\nLemma Umult_lt_compat_left : forall x y z, ~(0 == z)-> x < y -> (x * z) < (y * z).\nunfold Ult,not;intros.\napply H0; apply Umult_le_simpl_right with z; auto.\nQed.\n\nLemma Umult_lt_compat_right : forall x y z, ~(0 == z) -> x < y -> (z * x) < (z * y).\nunfold Ult,not;intros.\napply H0; apply Umult_le_simpl_left with z; auto.\nQed.\n\n\nLemma Umult_lt_simpl_right : forall x y z, ~(0 == z) -> (x * z) < (y * z) -> x < y.\nunfold Ult,not;intros.\napply H0; auto.\nQed.\n\nLemma Umult_lt_simpl_left : forall x y z, ~(0 == z) -> (z * x) < (z * y) -> x < y.\nunfold Ult,not;intros.\napply H0; auto.\nQed.\n\nHint Resolve Umult_lt_compat_left Umult_lt_compat_right.\n\nLemma Umult_zero_simpl_right : forall x y, 0 == x*y -> ~(0 == x) -> (0 == y).\nintros.\napply Umult_simpl_left with x; auto.\nrewrite (Umult_zero_right x); trivial.\nQed.\n\nLemma Umult_zero_simpl_left : forall x y, 0 == x*y -> ~(0 == y) -> 0 == x.\nintros.\napply Umult_simpl_right with y; auto.\nrewrite (Umult_zero_left y); trivial.\nQed.\n\n\nLemma Umult_neq_zero : forall x y, ~(0 == x) -> ~(0 == y) -> ~(0 == x*y).\nred; intros.\napply H0; apply Umult_zero_simpl_right with x; trivial.\nQed.\nHint Resolve Umult_neq_zero.\n\nLemma Umult_lt_zero : forall x y, 0 < x -> 0 < y -> 0 < x*y.\nauto.\nQed.\nHint Resolve Umult_lt_zero.\n\nLemma Umult_lt_compat : forall x y z t, x < y -> z < t -> x * z < y * t.\nintros.\nassert (0<y); auto.\napply Ule_lt_trans with x; auto.\nassert (0<t); auto.\napply Ule_lt_trans with z; auto.\napply (Ueq_orc 0 z); auto; intros.\nrewrite <- H3.\nrewrite Umult_zero_right; auto.\napply Ult_trans with (y * z); auto.\nQed.\n\n(** *** More Properties *)\n\nLemma Uplus_one : forall x y, [1-] x <= y -> x + y == 1.\nintros; apply Ule_antisym; auto.\napply Ule_trans with (x + [1-] x); auto.\nQed.\nHint Resolve Uplus_one.\n\nLemma Uplus_one_right : forall x, x + 1 == 1.\nauto.\nQed.\n\nLemma Uplus_one_left : forall x:U, 1 + x == 1.\nauto.\nQed.\nHint Resolve Uplus_one_right Uplus_one_left. \n\nLemma Uinv_mult_simpl : forall x y z t, x <= [1-] y -> (x * z) <= [1-] (y * t).\nintros; apply Ule_trans with x; auto.\nintros; apply Ule_trans with ([1-] y); auto.\nQed.\nHint Resolve Uinv_mult_simpl.\n\nLemma Umult_inv_plus :   forall x y, x * [1-] y + y == x + y * [1-] x.\nintros; apply Ueq_trans with (x * [1-] y + y * ([1-] x + x)).\nsetoid_rewrite (Uinv_opp_left x); auto.\nassert (H:[1-] x <= [1-] x); auto.\nsetoid_rewrite (Udistr_plus_left y H).\napply Ueq_trans with (x * [1-] y + y * x + y * [1-] x).\nnorm_assoc_right; auto.\nsetoid_rewrite (Umult_sym y x).\nassert (H1:[1-] y <= [1-] y); auto.\nsetoid_rewrite <- (Udistr_plus_left x H1).\nsetoid_rewrite (Uinv_opp_left y); auto.\nQed.\nHint Resolve Umult_inv_plus.\n\nLemma Umult_inv_plus_le : forall x y z, y <= z -> x * [1-] y + y <= x * [1-] z + z.\nintros.\nsetoid_rewrite (Umult_inv_plus x y); \nsetoid_rewrite (Umult_inv_plus x z); auto.\nQed.\nHint Resolve Umult_inv_plus_le.\n\nLemma Uplus_lt_Uinv :   forall x y, x+y < 1 -> x <= [1-] y.\nintros; apply (Ule_total x ([1-]y)); intro; auto.\ncase H.\nrewrite Uplus_one; auto. \nQed.\n\nLemma Uinv_lt_perm_left: forall x y : U, [1-] x < y -> [1-] y < x.\nunfold Ult; intuition.\nQed.\n\nLemma Uinv_lt_perm_right: forall x y : U, x < [1-] y -> y < [1-] x.\nunfold Ult; intuition.\nQed.\n\nHint Immediate Uinv_lt_perm_left Uinv_lt_perm_right.\n\nLemma Uinv_lt_one : forall x, 0 < x -> [1-]x < 1.\nintro; setoid_replace 0 with ([1-]1); auto.\nQed.\n\nLemma Uinv_lt_zero : forall x, x < 1 -> 0 < [1-]x.\nintro; setoid_replace 1 with ([1-]0); auto.\nQed.\n\nHint Resolve Uinv_lt_one Uinv_lt_zero.\n\nLemma Umult_lt_right : forall p q, p <1 -> 0 < q -> p * q < q.\nintros.\napply Ult_le_trans with (1 * q); auto.\nQed.\n\nLemma Umult_lt_left : forall p q, 0 < p -> q < 1 -> p * q < p.\nintros.\napply Ult_le_trans with (p * 1); auto.\nQed.\n\nHint Resolve Umult_lt_right Umult_lt_left.\n\n(** ** Definition of $x^n$ *)\nFixpoint Uexp (x:U) (n:nat) {struct n} : U :=\n   match n with 0 => 1 | (S p) => x * Uexp x p end.\n\nInfix \"^\" := Uexp : U_scope.\n\nLemma Uexp_1 : forall x, x^1==x.\nsimpl; auto.\nQed.\n\nLemma Uexp_0 : forall x, x^0==1.\nsimpl; auto.\nQed.\n\nLemma Uexp_zero : forall n, (0<n)%nat -> 0^n==0.\ndestruct n; simpl; intro; auto.\ncasetype False; omega.\nQed.\n\nLemma Uexp_one : forall n, 1^n==1.\ninduction n; simpl; auto.\nrewrite IHn; auto.\nQed.\n\nLemma Uexp_le_compat : \n      forall x n m, (n<=m)%nat -> x^m <= x^n.\ninduction 1; simpl; auto.\napply Ule_trans with (x^m); auto.\nQed.\n\nLemma Uexp_Ule_compat : \n      forall x y n,  x<=y -> x^n <= y^n.\ninduction n; simpl; intros; auto.\napply Ule_trans with (x * (y^n)); auto.\nQed.\n\nAdd Morphism Uexp with signature Ueq ==> (@eq nat) ==> Ueq as Uexp_eq_compat.\nintros; apply Ule_antisym; apply Uexp_Ule_compat; auto.\nQed.\n\nLemma Uexp_inv_S : forall x n, ([1-]x^(S n))==x*([1-]x^n)+[1-]x.\nsimpl; auto.\nQed.\n\nLemma Uexp_lt_compat : forall p q n, (O<n)%nat->(p<q)->(p^n<q^n).\ninduction n; simpl; intros; auto.\ncasetype False; omega.\ndestruct n; auto.\napply Umult_lt_compat; auto with arith.\nQed.\n\nHint Resolve Uexp_lt_compat.\n\nLemma Uexp_lt_zero : forall p n, (0<p)->(0<p^n).\ndestruct n; intros; auto.\nrewrite <- (Uexp_zero (n:=S n)); auto with arith.\nQed.\nHint Resolve Uexp_lt_zero.\n\nLemma Uexp_lt_one : forall p n, (0<n)%nat->(p<1)->(p^n<1).\nintros; rewrite <- (Uexp_one n); auto with arith.\nQed.\nHint Resolve Uexp_lt_one.\n\nLemma Uexp_lt_antimon: forall p n m, (n<m)%nat-> 0<p -> p < 1 -> p^m < p^n.\ninduction 1; simpl; intros; auto with arith. \napply Ult_trans with (p*p^n); auto with arith. \nQed.\nHint Resolve Uexp_lt_antimon.\n\n(** ** Definition and properties of $x \\& y$\n   A conjonction operation which coincides with min and mult \n   on 0 and 1, see Morgan & McIver *)\n\nDefinition Uesp (x y:U) := [1-] ([1-] x + [1-] y).\n\nInfix \"&\" := Uesp  (left associativity, at level 40) : U_scope.\n\nLemma Uinv_plus_esp : forall x y, [1-] (x + y) == [1-] x & [1-] y.\nunfold Uesp; intros.\nsetoid_rewrite (Uinv_inv x); setoid_rewrite (Uinv_inv y); auto.\nQed.\nHint Resolve Uinv_plus_esp.\n\nLemma Uinv_esp_plus : forall x y, [1-] (x & y) == [1-] x + [1-] y.\nunfold Uesp; intros.\nsetoid_rewrite (Uinv_inv ([1-] x + [1-] y)); trivial.\nQed.\nHint Resolve Uinv_esp_plus.\n\n\nLemma Uesp_sym : forall x y : U, x & y == y & x.\nintros; unfold Uesp; auto.\nQed.\n\nLemma Uesp_one_right : forall x : U, x & 1 == x.\nintro; unfold Uesp.\nsetoid_rewrite Uinv_one.\nsetoid_rewrite (Uplus_zero_right ([1-] x)); auto.\nQed.\n\nLemma Uesp_one_left : forall x : U, 1 & x  == x.\nintros; rewrite Uesp_sym; apply Uesp_one_right.\nQed.\n\nLemma Uesp_zero : forall x y, x <= [1-] y -> x & y == 0.\nintros; unfold Uesp.\nsetoid_rewrite <- Uinv_one; auto.\nQed.\n\nHint Resolve Uesp_sym Uesp_one_right Uesp_one_left Uesp_zero.\n\nLemma Uesp_zero_right : forall x : U, x & 0 == 0.\nauto.\nQed.\n\nLemma Uesp_zero_left : forall x : U, 0 & x == 0.\nauto.\nQed.\n\nHint Resolve Uesp_zero_right Uesp_zero_left.\n\nAdd Morphism Uesp with signature Ueq ==> Ueq ==> Ueq as  Uesp_eq_compat.\nunfold Uesp; intros.\napply Uinv_eq_compat.\nrewrite H; rewrite H0; auto.\nQed.\n\nLemma Uesp_le_compat : forall x y z t, x<=y -> z <=t -> x&z <= y&t.\nunfold Uesp; intros.\napply Uinv_le_compat.\napply Uplus_le_compat; auto.\nQed.\n\nHint Immediate Uesp_le_compat Uesp_eq_compat.\n\n\nLemma Uesp_le_left : forall x y, x & y <= x.\nunfold Uesp; intros.\napply Uinv_le_perm_left; auto.\nQed.\n\nLemma Uesp_le_right : forall x y, x & y <= y.\nunfold Uesp; intros.\napply Uinv_le_perm_left; auto.\nQed.\n\nHint Resolve Uesp_le_left Uesp_le_right.\n\nLemma Uesp_plus_inv : forall x y, [1-] y <= x -> x == x & y + [1-] y.\nunfold Uesp; intros.\nrewrite Uinv_plus_right; auto.\nQed.\nHint Resolve Uesp_plus_inv.\n\nLemma Uesp_le_plus_inv : forall x y, x <= x & y + [1-] y.\nintros; apply (Ule_total ([1-]y) x); intros; auto.\nrewrite Uesp_zero; auto.\nrewrite Uplus_zero_left; auto.\nQed.\nHint Resolve Uesp_le_plus_inv.\n\nLemma Uplus_inv_le_esp : forall x y z, x <= y + ([1-] z) -> x & z <= y.\nintros; unfold Uesp.\napply Uinv_le_perm_left.\napply Ule_trans with ([1-](y+[1-]z) + [1-]z); auto.\nQed.\nHint Immediate Uplus_inv_le_esp.\n\n(** ** Definition and properties of $x - y$ *)\n\nDefinition Uminus (x y:U) := [1-] ([1-] x + y).\n\nInfix \"-\" := Uminus : U_scope.\n\nLemma Uminus_le_compat_left : forall x y z, x <= y -> x - z <= y - z.\nunfold Uminus; auto.\nQed.\n\nLemma Uminus_le_compat_right :  forall x y z, y <= z -> x - z <= x - y.\nunfold Uminus; auto.\nQed.\n\nHint Resolve Uminus_le_compat_left Uminus_le_compat_right.\n\nLemma Uminus_le_compat : forall x y z t, x <= y ->  t <= z -> x - z <= y - t.\nintros; apply Ule_trans with (x-t); auto.\nQed.\n\nHint Immediate Uminus_le_compat.\n\nAdd Morphism Uminus with signature Ueq ==> Ueq ==> Ueq as Uminus_eq_compat.\nintros x1 x2 eq1 x3 x4 eq2; apply Ule_antisym;\napply Ule_trans with (x1-x4); auto.\nQed.\nHint Immediate Uminus_eq_compat.\n\nLemma Uminus_zero_right : forall x, x - 0 == x.\nunfold Uminus; intros.\nsetoid_rewrite (Uplus_zero_right ([1-] x)); auto.\nQed.\n\nLemma Uminus_one_left : forall x, 1 - x == [1-] x.\nunfold Uminus; intros.\nsetoid_rewrite Uinv_one; auto.\nQed.\n\nLemma Uminus_le_zero : forall x y, x <= y -> x - y == 0.\nunfold Uminus; intros.\nsetoid_rewrite <- Uinv_one.\napply Uinv_eq_compat.\napply Ule_antisym; auto.\napply Ule_trans with ([1-] y + y); auto.\nQed.\n\nHint Resolve Uminus_zero_right Uminus_one_left Uminus_le_zero.\n\nLemma Uminus_eq : forall x, x-x == 0.\nauto.\nQed.\nHint Resolve Uminus_eq.\n\nLemma Uminus_le_left : forall x y, x - y <= x.\nunfold Uminus; auto.\nQed.\n\nHint Resolve Uminus_le_left.\n\n\nLemma Uminus_le_inv : forall x y, x - y <= [1-]y.\nintros.\nunfold Uminus.\napply Uinv_le_compat; auto.\nQed.\nHint Resolve Uminus_le_inv.\n\nLemma Uminus_plus_simpl : forall x y, y <= x -> (x - y) + y == x.\nunfold Uminus; intros.\nassert (H1:y <= [1-] ([1-] x)); auto.\nsetoid_rewrite (Uinv_plus_right H1); auto.\nQed.\n\nLemma Uminus_plus_zero : forall x y, x <= y -> (x - y) + y == y.\nintros; setoid_rewrite (Uminus_le_zero H); auto.\nQed.\n\nHint Resolve Uminus_plus_simpl Uminus_plus_zero.\n\n\nLemma Uesp_minus_distr_left : forall x y z, (x & y) - z  == (x - z) & y.\nunfold Uesp, Uminus; intros.\napply Uinv_eq_compat.\nsetoid_rewrite (Uinv_inv ([1-] x + [1-] y)).\nsetoid_rewrite (Uinv_inv (([1-] x) + z)).\nrepeat norm_assoc_right; auto.\nQed.\n\nLemma Uesp_minus_distr_right : forall x y z, (x & y) - z  == x & (y - z).\nintros; setoid_rewrite (Uesp_sym x y); \nsetoid_rewrite (Uesp_sym x (y - z)); \napply Uesp_minus_distr_left.\nQed.\n\nHint Resolve Uesp_minus_distr_left Uesp_minus_distr_right.\n\nLemma Uesp_minus_distr : forall x y z t, (x & y) - (z + t) == (x - z) & (y - t).\nunfold Uesp, Uminus; intros.\napply Uinv_eq_compat.\nsetoid_rewrite (Uinv_inv ([1-] x + [1-] y)).\nsetoid_rewrite (Uinv_inv ([1-] x + z)).\nsetoid_rewrite (Uinv_inv ([1-] y + t)).\nrepeat norm_assoc_right; auto.\nQed.\nHint Resolve Uesp_minus_distr.\n \nLemma Uminus_esp_simpl_left : forall x y, [1-]x <= y -> x - (x & y) == [1-]y.\nunfold Uesp,Uminus; intros.\napply Uinv_eq_compat.\nrewrite (Uplus_sym ([1-]x)).\nrewrite Uinv_plus_left; auto.\nQed.\n\nLemma Uplus_esp_simpl : forall x y, (x - (x & y))+y == x+y.\nintros; apply (Ule_total ([1-]x) y); auto; intros.\nrewrite Uminus_esp_simpl_left; auto.\nrewrite (@Uplus_one x y); auto.\nrewrite (@Uesp_zero x y); auto.\nQed.\nHint Resolve Uminus_esp_simpl_left Uplus_esp_simpl.\n\nLemma Uminus_esp_le_inv  : forall x y, x - (x & y) <= [1-]y.\nintros; apply (Ule_total ([1-]x) y); auto; intros.\nrewrite (@Uesp_zero x y); auto.\nrewrite Uminus_zero_right; auto.\nQed.\n\nHint Resolve Uminus_esp_le_inv.\n\nLemma Uplus_esp_inv_simpl : forall x y, x <= [1-]y -> (x + y) & [1-]y == x.\nunfold Uesp; intros.\napply Uinv_eq_perm_left.\nrewrite Uinv_inv; auto.\nQed.\nHint Resolve Uplus_esp_inv_simpl.\n\nLemma Uplus_inv_esp_simpl : forall x y, x <= y -> (x + [1-]y) & y == x.\nintros.\napply Ueq_trans with ((x + [1-] y) & [1-][1-]y); auto.\nrewrite Uinv_inv; auto.\nQed.\nHint Resolve Uplus_inv_esp_simpl.\n\n\n(** ** Definition and properties of max *)\n\nDefinition max (x y : U) : U := (x - y) + y.\n\nLemma max_eq_right : forall x y : U, y <= x -> max x y == x.\nunfold max; auto.\nQed.\n\nLemma max_eq_left : forall x y : U, x <= y -> max x y == y.\nunfold max; auto.\nQed.\n\nHint Resolve max_eq_right max_eq_left.\n\nLemma max_eq_case : forall x y : U, orc (max x y == x) (max x y == y).\nintros; apply (Ule_total x y); auto.\nQed.\n\nAdd Morphism max with signature Ueq ==> Ueq ==> Ueq as max_eq_compat.\nunfold max; intros.\napply Uplus_eq_compat; auto.\nQed.\n\nLemma max_le_right : forall x y : U, x <= max x y.\nintros; apply (Ule_total x y); intros; auto.\nrewrite max_eq_left; auto.\nrewrite max_eq_right; auto.\nQed.\n\nLemma max_le_left : forall x y : U, y <= max x y.\nintros; apply (Ule_total x y); intros; auto.\nrewrite max_eq_left; auto.\nrewrite max_eq_right; auto.\nQed.\n\nHint Resolve max_le_right max_le_left.\n\nLemma max_le : forall x y z : U, x <= z -> y <= z -> max x y <= z.\nintros; apply (Ule_total x y); intros; auto.\nrewrite max_eq_left; auto.\nrewrite max_eq_right; auto.\nQed.\n\n(** ** Definition and properties of min *)\n\nDefinition min (x y : U) : U := [1-] ((y - x) + [1-]y).\n\nLemma min_eq_right : forall x y : U, x <= y -> min x y == x.\nunfold min, Uminus; intros.\napply Uinv_eq_perm_left; auto.\nQed.\n\nLemma min_eq_left : forall x y : U, y <= x -> min x y== y.\nunfold min; intros.\nrewrite Uminus_le_zero; auto.\nQed.\n\nHint Resolve min_eq_right min_eq_left.\n\nLemma min_eq_case : forall x y : U, orc (min x y == x) (min x y == y).\nintros; apply (Ule_total x y); auto.\nQed.\n\nAdd Morphism min with signature Ueq ==> Ueq ==> Ueq as min_eq_compat.\nunfold min; intros.\napply Uinv_eq_compat; auto.\napply Uplus_eq_compat; auto.\nQed.\n\nLemma min_le_right : forall x y : U, min x y <=x.\nintros; apply (Ule_total x y); intros; auto.\nrewrite min_eq_left; auto.\nQed.\n\nLemma min_le_left : forall x y : U, min x y <= y.\nintros; apply (Ule_total x y); intros; auto.\nrewrite min_eq_right; auto.\nQed.\n\nHint Resolve min_le_right min_le_left.\n\nLemma min_le : forall x y z : U, z <= x -> z <= y -> z <= min x y.\nintros; apply (Ule_total x y); intros; auto.\nrewrite min_eq_right; auto.\nrewrite min_eq_left; auto.\nQed.\n\nLemma Uinv_min_max : forall x y, [1-](min x y)==max ([1-]x) ([1-]y).\nintros; apply (Ule_total x y); intros; auto.\nrewrite min_eq_right; auto; rewrite max_eq_right; auto.\nrewrite min_eq_left; auto; rewrite max_eq_left; auto.\nQed.\n\nLemma Uinv_max_min : forall x y, [1-](max x y)==min ([1-]x) ([1-]y).\nintros; apply (Ule_total x y); intros; auto.\nrewrite min_eq_left; auto; rewrite max_eq_left; auto.\nrewrite min_eq_right; auto; rewrite max_eq_right; auto.\nQed.\n\nLemma min_mult : forall x y k, \n    min (k * x) (k * y) == k * (min x y).\nintros; apply (Ule_total x y); intros; auto.\nrewrite min_eq_right; auto; rewrite min_eq_right; auto.\nrewrite min_eq_left; auto; rewrite min_eq_left; auto.\nQed.\nHint Resolve min_mult.\n\nLemma min_plus : forall x1 x2 y1 y2, \n    (min x1 x2)  + (min y1 y2) <= min (x1+y1) (x2+y2).\nintros; apply min_le; auto.\nQed.\nHint Resolve min_plus.\n\nLemma min_plus_cte : forall x y k, min (x + k) (y + k) == (min x y) + k.\nintros; apply (Ule_total x y); intros; auto.\nrewrite min_eq_right; auto; rewrite min_eq_right; auto.\nrewrite min_eq_left; auto; rewrite min_eq_left; auto.\nQed.\nHint Resolve min_plus_cte.\n\nLemma min_le_compat : forall x1 x2 y1 y2, \n      x1<=y1 -> x2 <=y2 -> min x1 x2 <= min y1 y2.\nintros; apply min_le.\napply Ule_trans with x1; auto.\napply Ule_trans with x2; auto.\nQed.\n\nLemma min_sym : forall x y, min x y == min y x.\nintros; apply (Ule_total x y); intros; auto.\nrewrite min_eq_right; auto.\nrewrite min_eq_left; auto.\nrewrite min_eq_left; auto.\nrewrite min_eq_right; auto.\nQed.\nHint Resolve min_sym.\n\n\nDefinition incr (f:nat->U) := forall n, f n <= f (S n).\n\nLemma incr_mon : forall f, incr f -> forall n m, (n<=m)%nat -> f n <= f m.\ninduction 2; auto.\napply Ule_trans with (f m); auto.\nQed.\nHint Resolve incr_mon.\n\nLemma incr_decomp_aux : forall f g, incr f -> incr g -> \n     forall n1 n2, (forall m, ~ ((n1<=m)%nat /\\ f n1 <= g m))\n           -> (forall m, ~((n2<=m)%nat /\\ g n2<= f m)) -> (n1<=n2)%nat -> False.\nintros; assert (absurd:~ g n2 < g n2); auto.\nassert (~(f n1 <= g n2)).\napply not_and_elim_left with (1:= H1 n2); auto.\nassert (~(g n2 <= f n2)); auto.\napply not_and_elim_left with (1:= H2 n2); auto.\napply absurd; apply Ult_le_trans with (f n1); auto.\napply Ule_trans with (f n2); auto.\nQed.\n\nLemma incr_decomp : forall f g, incr f -> incr g -> \n     orc (forall n, exc (fun m => (n<=m)%nat /\\ f n <= g m)) \n           (forall n, exc (fun m => (n<=m)%nat /\\ g n <= f m)).\nintros f g incrf incrg; apply orc_intro; intros.\napply H; clear H; intros.\napply exc_intro_class; intros.\napply H0; clear H0; intros.\napply exc_intro_class; intros.\ncase (dec_le n n0); intro.\napply (incr_decomp_aux incrf incrg) with (n1:=n) (n2:=n0); auto.\napply (incr_decomp_aux incrg incrf) with (n1:=n0) (n2:=n); auto; omega.\nQed.\n\n\n\n(** ** Other properties *)\nLemma Uplus_minus_simpl_right : forall x y, y <= [1-] x -> (x + y) - y == x.\nunfold Uminus; intros.\nsetoid_rewrite (Uinv_plus_right H); auto.\nQed.\nHint Resolve Uplus_minus_simpl_right.\n\nLemma Uplus_minus_simpl_left : forall x y, y <= [1-] x -> (x + y) - x == y.\nintros; setoid_rewrite (Uplus_sym x y); auto.\nQed.\n\nLemma Uminus_assoc_left : forall x y z, (x - y) - z == x - (y + z).\nunfold Uminus; intros.\napply Uinv_eq_compat.\nsetoid_rewrite (Uinv_inv ([1-] x + y)); auto.\nQed.\n\nHint Resolve Uminus_assoc_left.\n\nLemma Uminus_perm : forall x y z, (x - y) - z == (x - z) - y.\nintros; rewrite Uminus_assoc_left.\nrewrite (Uplus_sym y z); auto.\nQed.\nHint Resolve Uminus_perm.\n\nLemma Uminus_le_perm_left : forall x y z, y <= x -> x - y <= z -> x <= z + y.\nintros; setoid_rewrite <- (Uminus_plus_simpl H); auto.\nQed.\n\nLemma Uplus_le_perm_left : forall x y z, y <= x -> x <= y + z  -> x - y <= z.\nintros; apply Uplus_le_simpl_left with y.\nunfold Uminus; setoid_rewrite (Uinv_inv ([1-] x + y)); auto.\nsetoid_rewrite (Uplus_sym y (x-y)); setoid_rewrite (Uminus_plus_simpl H); auto.\nQed.\n\nLemma Uminus_eq_perm_left : forall x y z, y <= x -> x - y == z -> x == z + y.\nintros; setoid_rewrite <- (Uminus_plus_simpl H); auto.\nQed.\n\nLemma Uplus_eq_perm_left : forall x y z, y <= [1-] z -> x == y + z  -> x - y == z.\nintros; setoid_rewrite H0; auto.\nsetoid_rewrite (Uplus_sym y z); auto.\nQed.\n\nHint Resolve Uminus_le_perm_left Uminus_eq_perm_left.\nHint Resolve Uplus_le_perm_left Uplus_eq_perm_left.\n\nLemma Uminus_le_perm_right : forall x y z, z <= y -> x <= y - z -> x + z <= y.\nintros; setoid_rewrite <- (Uminus_plus_simpl H); auto.\nQed.\n\nLemma Uplus_le_perm_right : forall x y z, z <= [1-] x -> x + z <= y  -> x <= y - z.\nintros; apply Uplus_le_simpl_right with z; auto.\nQed.\nHint Resolve Uminus_le_perm_right Uplus_le_perm_right.\n\nLemma Uminus_le_perm : forall x y z, z <= y -> x <= [1-] z -> x <= y - z -> z <= y - x.\nintros; apply Uplus_le_perm_right; auto.\nsetoid_rewrite (Uplus_sym z x); auto.\nQed.\nHint Resolve Uminus_le_perm.\n\nLemma Uminus_eq_perm_right : forall x y z, z <= y -> x == y - z -> x + z == y.\nintros; apply Ueq_trans with (y - z + z); auto.\nQed.\nHint Resolve Uminus_eq_perm_right.\n\nLemma Uminus_plus_perm : forall x y z, y <= x -> z <= [1-]x -> x - y + z == x + z - y.\nintros; apply Uminus_eq_perm_right.\napply Ule_trans with (y + z - y); auto.\nrewrite Uplus_minus_simpl_left; auto.\napply Ule_trans with ([1-]x); auto.\nrewrite Uminus_perm.\nrewrite Uplus_minus_simpl_right; auto.\nQed.\n\nLemma Uminus_zero_le : forall x y, x - y == 0 -> x <= y.\nintros x y; unfold Uminus; intros.\nsetoid_rewrite <- (Uinv_inv x).\napply Uplus_one_le.\nsetoid_rewrite <- Uinv_zero; auto.\nsetoid_rewrite <- H; auto.\nsetoid_rewrite (Uinv_inv ([1-] x + y)); auto.\nQed.\n\nLemma Uminus_lt_non_zero : forall x y, x < y -> ~(0 == y - x).\nred; intros.\napply H; auto.\napply Uminus_zero_le; auto.\nQed.\nHint Immediate Uminus_zero_le Uminus_lt_non_zero.\n\nLemma Ult_le_nth : forall x y, x < y -> exc (fun n => x <= y - [1/]1+n).\nintros; apply (archimedian (x:=(y - x))); intros; auto.\napply exc_intro with x0.\napply Uminus_le_perm; auto.\napply Ule_trans with (y - x); auto. \nQed.\n\nLemma Uminus_distr_left : forall x y z, (x - y) * z == (x * z) - (y * z).\nintros; apply (Ule_total x y); intros; auto.\n(* first case x <= y, left and right hand side equal 0 *)\nsetoid_rewrite (Uminus_le_zero H).\nsetoid_rewrite (Umult_zero_left z).\nassert (x * z <= y * z); auto.\nsetoid_rewrite (Uminus_le_zero H0); auto.\n(* second case y <= x, use simplification *)\nunfold Uminus; intros; auto.\napply Uplus_eq_simpl_right with (y * z); auto.\nassert ([1-] ([1-] x + y) <= [1-] y); auto.\nsetoid_rewrite <- (Udistr_plus_right z H0); auto.\nassert (y <= [1-] ([1-] x)); auto.\nsetoid_rewrite (Uinv_plus_right H1).\nsetoid_rewrite (Uinv_inv x); auto.\nQed.\n\nHint Resolve Uminus_distr_left.\n\nLemma Uminus_distr_right : forall x y z,  x * (y - z) == (x * y) - (x * z).\nintros; setoid_rewrite (Umult_sym x y).\nsetoid_rewrite (Umult_sym x z).\nsetoid_rewrite (Umult_sym x (y - z)); auto.\nQed.\n\nHint Resolve Uminus_distr_right.\n\n\nLemma Uminus_assoc_right :  forall x y z, y <= x -> z <= y -> x - (y - z) == (x - y) + z.\nintros.\napply Uplus_eq_perm_left; auto.\nunfold Uminus at 1; apply Uinv_le_compat.\napply Ule_trans with (1 - y + z); auto.\napply Ueq_trans with ((y - z) + z + (x - y)).\nsetoid_rewrite (Uminus_plus_simpl H0).\nsetoid_rewrite (Uplus_sym y (x - y)); auto.\nnorm_assoc_right; auto.\nQed.\n\nLemma Uplus_minus_assoc_right : forall x y z, y <= [1-]x -> z <= y -> x + (y - z) == (x + y) - z.\nintros; unfold Uminus.\napply Ueq_trans with ([1-] (x + ([1-] (x + y) + z)) + x).\nrewrite Uplus_assoc.\nrewrite (Uplus_sym x ([1-] (x + y))).\nrewrite Uinv_plus_left; auto.\nrewrite Uinv_plus_left; auto.\napply Ule_trans with ([1-] (x + y) + y); auto.\nQed.\n\n(** ** Definition and properties of generalized sums *)\n\nDefinition sigma (alpha : nat -> U) (n:nat) := comp Uplus 0 alpha n.\n\nLemma sigma_0 : forall (f : nat -> U), sigma f 0 == 0.\ntrivial.\nQed.\n\nLemma sigma_S : forall (f :nat -> U) (n:nat), sigma f (S n) = (f n) + (sigma f n).\ntrivial.\nQed.\n\nLemma sigma_1 : forall (f : nat -> U), sigma f (S 0) == f O.\nintros; rewrite sigma_S; auto.\nQed.\n\nLemma sigma_S_lift : forall (f :nat -> U) (n:nat), \n          sigma f (S n) == (f O) + (sigma (fun k => f (S k)) n).\nintros f n; generalize f; induction n; simpl; intros; auto.\nrewrite sigma_S.\nrewrite IHn.\nrewrite sigma_S.\nrewrite Uplus_assoc.\nrewrite (Uplus_sym (f0 (S n)) (f0 O)); auto.\nQed.\n\nLemma sigma_incr : forall (f : nat -> U) (n m:nat), (n <= m)%nat -> (sigma f n) <= (sigma f m).\nintros f n m H; induction H; auto.\nintros; rewrite sigma_S.\napply Ule_trans with (1:=IHle); auto.\nQed.\n\nHint Resolve sigma_incr.\n\nLemma sigma_eq_compat : forall (f g: nat -> U) (n:nat), \n (forall k, (k < n)%nat -> f k == g k) -> (sigma f n) == (sigma g n).\ninduction n; auto.\nintros; repeat rewrite sigma_S.\napply Ueq_trans with (g n + sigma f n); auto with arith.\nQed.\n\nLemma sigma_le_compat : forall (f g: nat -> U) (n:nat), \n (forall k, (k < n)%nat -> f k <= g k) -> (sigma f n) <= (sigma g n).\ninduction n; auto.\nintros; repeat rewrite sigma_S.\napply Ule_trans with (g n + sigma f n); auto with arith.\nQed.\n\nLemma sigma_zero : forall f n, (forall k, (k<n)%nat -> f k ==0)->(sigma f n)==0.\ninduction n; simpl; intros; auto.\nrewrite sigma_S.\nrewrite (H n); auto.\nrewrite IHn; auto.\nQed.\n\nLemma sigma_not_zero : forall f n k, (k<n)%nat -> 0 < f k -> 0 < sigma f n.\ninduction n; simpl; intros; auto.\ncasetype False; omega.\nrewrite sigma_S.\nassert (k < n \\/ k = n)%nat.\nomega.\ncase H1; intros; subst; auto.\napply Ult_le_trans with (sigma f n); auto.\napply (IHn k); auto.\napply Ult_le_trans with (f n); auto.\nQed.\n\nLemma sigma_zero_elim : forall f n, (sigma f n)==0->forall k, (k<n)%nat -> f k ==0.\nintros; apply Ueq_class; red; intros.\nassert (0 < sigma f n); auto.\napply sigma_not_zero with k; auto.\nQed.\n\nHint Resolve sigma_eq_compat sigma_le_compat sigma_zero.\n\nLemma sigma_le : forall f n k, (k<n)%nat -> f k <= sigma f n.\ninduction n; simpl; intros.\ncasetype False; omega.\nrewrite sigma_S.\nassert (k < n \\/ k = n)%nat.\nomega.\ncase H0; intros; subst; auto.\napply Ule_trans with (sigma f n); auto.\nQed.\n\nLemma sigma_minus_decr : forall f n, (forall k, f (S k) <= f k) ->\n         sigma (fun k => f k - f (S k)) n == f O - f n.\nintros f n fmon;induction n; simpl.\nrewrite sigma_0; auto.\nrewrite sigma_S; rewrite IHn.\nrewrite Uplus_sym.\nrewrite Uplus_minus_assoc_right; auto.\nrewrite Uminus_plus_simpl; auto.\nelim n; intros; auto.\napply Ule_trans with (f n0); auto.\nQed.\n\nLemma sigma_minus_incr : forall f n, (forall k, f k <= f (S k)) ->\n         sigma (fun k => f (S k) - f k) n == f n - f O.\nintros f n fmon;induction n; simpl.\nrewrite sigma_0; auto.\nrewrite sigma_S; rewrite IHn.\nrewrite Uplus_minus_assoc_right; auto.\nrewrite Uminus_plus_simpl; auto.\nelim n; intros; auto.\napply Ule_trans with (f n0); auto.\nQed.\n\nDefinition sigma_inf (f : nat -> U) : U := lub (sigma f).\n\n(** ** Definition and properties of generalized products *)\n\nDefinition prod (alpha : nat -> U) (n:nat) := comp Umult 1 alpha n.\n\nLemma prod_0 : forall (f : nat -> U), prod f 0 = 1.\ntrivial.\nQed.\n\nLemma prod_S : forall (f :nat -> U) (n:nat), prod f (S n) = (f n) * (prod f n).\ntrivial.\nQed.\n\nLemma prod_1 : forall (f : nat -> U), prod f (S 0) == f O.\nintros; rewrite prod_S; auto.\nQed.\n\nLemma prod_S_lift : forall (f :nat -> U) (n:nat), \n          prod f (S n) == (f O) * (prod (fun k => f (S k)) n).\nintros f n; generalize f; induction n; simpl; intros; auto.\nrewrite prod_S.\nrewrite IHn.\nrewrite prod_S.\nrewrite Umult_assoc.\nrewrite (Umult_sym (f0 (S n)) (f0 O)); auto.\nQed.\n\nLemma prod_decr : forall (f : nat -> U) (n m:nat), (n <= m)%nat -> (prod f m) <= (prod f n).\nintros f n m H; induction H; auto.\nintros; rewrite prod_S.\napply Ule_trans with (2:=IHle); auto.\nQed.\n\nHint Resolve prod_decr.\n\nLemma prod_eq_compat : forall (f g: nat -> U) (n:nat), \n (forall k, (k < n)%nat -> f k == g k) -> (prod f n) == (prod g n).\ninduction n; auto.\nintros; repeat rewrite prod_S.\napply Ueq_trans with (g n * prod f n); auto with arith.\nQed.\n\nLemma prod_le_compat : forall (f g: nat -> U) (n:nat), \n (forall k, (k < n)%nat -> f k <= g k) -> prod f n <= prod g n.\ninduction n; auto.\nintros; repeat rewrite prod_S.\napply Ule_trans with (g n * prod f n); auto with arith.\nQed.\n\nLemma prod_zero : forall f n k, (k<n)%nat -> f k ==0 -> prod f n==0.\ninduction n; simpl; intros; auto.\nabsurd ((k < 0)%nat); auto with arith.\nrewrite prod_S.\nassert (k < n \\/ k = n)%nat.\nomega.\ncase H1; intros; subst; auto.\nrewrite (IHn k); auto.\nrewrite H0; auto.\nQed.\n\nLemma prod_not_zero : forall f n, (forall k, (k<n)%nat -> 0 < f k )-> 0 < prod f n.\ninduction n; simpl; intros; auto.\nrewrite prod_S; auto with arith.\nQed.\n\nLemma prod_zero_elim : forall f n, prod f n==0 -> exc (fun k => (k<n)%nat /\\ f k ==0).\nintros; apply class_exc; red; intros.\nassert (forall k, (k<n)%nat -> 0 < f k); intros.\nred; intro.\napply H0.\napply exc_intro with k; auto.\nabsurd (0 < prod f n); auto.\napply prod_not_zero; auto.\nQed.\n\nHint Resolve prod_eq_compat prod_le_compat prod_not_zero.\n\nLemma prod_le : forall f n k, (k<n)%nat -> prod f n <= f k.\ninduction n; simpl; intros.\ncasetype False; omega.\nrewrite prod_S.\nassert (k < n \\/ k = n)%nat.\nomega.\ncase H0; intros; subst; auto.\napply Ule_trans with (prod f n); auto.\nQed.\n\nLemma prod_minus : forall f n, prod f n - prod f (S n) == ([1-]f n)  * prod f n.\nintros f n; rewrite prod_S.\napply Ueq_trans with (1 * prod f n - f n * prod f n).\nrewrite Umult_one_left; auto.\nrewrite <- Uminus_distr_left; auto.\nQed.\n\n\n(** ** Properties of [Unth] *)\nLemma Unth_zero : [1/]1+0 == 1.\nsetoid_rewrite (Unth_prop 0); auto.\nQed.\n\nNotation \"[1/2]\" := (Unth 1).\n\nLemma Unth_one : [1/2] == [1-] [1/2].\napply Ueq_trans with (1:=Unth_prop 1); simpl; auto.\nQed.\n\nHint Resolve Unth_zero Unth_one.\n\nLemma Unth_one_plus : [1/2] + [1/2] == 1.\napply Ueq_trans with  ([1/2] + [1-][1/2]); auto.\nQed.\nHint Resolve Unth_one_plus.\n\nLemma Unth_not_null : forall n, ~ (0 == [1/]1+n).\nred; intros.\napply Udiff_0_1.\napply Ueq_trans with ([1/]1+n); auto.\napply Ueq_trans with ([1-] (sigma (fun k => [1/]1+n) n)).\napply (Unth_prop n).\napply Ueq_trans with ([1-] (sigma (fun k => 0) n)).\napply Uinv_eq_compat.\napply sigma_eq_compat; auto.\napply Ueq_trans with ([1-] 0); auto.\nQed.\nHint Resolve Unth_not_null.\n\nLemma Unth_lt_zero : forall n, 0 < [1/]1+n.\nauto.\nQed.\nHint Resolve Unth_lt_zero.\n\nLemma Unth_inv_lt_one : forall n, [1-][1/]1+n<1.\nintro; setoid_replace 1 with ([1-]0); auto.\nQed.\nHint Resolve Unth_inv_lt_one.\n\nLemma Unth_not_one : forall n, ~ (1 == [1-][1/]1+n).\nauto.\nQed.\nHint Resolve Unth_not_one.\n\nLemma Unth_prop_sigma : forall n, [1/]1+n == [1-] (sigma (fun k => [1/]1+n) n).\nexact Unth_prop.\nQed.\nHint Resolve Unth_prop_sigma.\n\nLemma Unth_sigma_n : forall n : nat, ~ (1 == sigma (fun k => [1/]1+n) n).\nintros; apply Uinv_neq_simpl.\nsetoid_rewrite Uinv_one.\nsetoid_rewrite <- (Unth_prop_sigma n); auto.\nQed.\n\nLemma Unth_sigma_Sn : forall n : nat, 1 == sigma (fun k => [1/]1+n) (S n).\nintros; rewrite sigma_S.\napply Ueq_trans with \n([1-] (sigma (fun k => [1/]1+n) n) + (sigma (fun k => [1/]1+n) n));auto.\nQed.\n\nHint Resolve Unth_sigma_n Unth_sigma_Sn.\n\n\nLemma Unth_decr : forall n, [1/]1+(S n) < [1/]1+n.\nrepeat red; intros.\napply (Unth_sigma_n (S n)).\napply Ule_antisym; auto.\napply Ule_trans with (sigma (fun _ : nat => [1/]1+n) (S n)); auto.\nQed.\nHint Resolve Unth_decr.\n\nLemma Unth_anti_mon : \nforall n m, (n <= m)%nat -> [1/]1+m <= [1/]1+n.\ninduction 1; auto.\napply Ule_trans with ([1/]1+m); auto.\nQed.\nHint Resolve Unth_anti_mon.\n\nLemma Unth_le_half : forall n, [1/]1+(S n) <= [1/2].\nauto with arith.\nQed.\nHint Resolve Unth_le_half.\n\n(** *** Mean of two numbers : $\\frac{1}{2}x+\\frac{1}{2}y$*)\nDefinition mean (x y:U) := [1/2] * x + [1/2] * y.\n\nLemma mean_eq : forall x:U, mean x x ==x.\nunfold mean; intros.\nassert (H : ([1/2] <= [1-] ([1/2]))); auto.\nsetoid_rewrite <- (Udistr_plus_right x H); auto.\nsetoid_rewrite Unth_one_plus; auto.\nQed.\n\nLemma mean_le_compat_right : forall x y z, y <= z -> mean x y <= mean x z.\nunfold mean; intros.\napply Uplus_le_compat_right; auto.\nQed.\n\nLemma mean_le_compat_left : forall x y z, x <= y -> mean x z <= mean y z.\nunfold mean; intros.\napply Uplus_le_compat_left; auto.\nQed.\n\nHint Resolve mean_eq mean_le_compat_left mean_le_compat_right.\n\nLemma mean_lt_compat_right : forall x y z, y < z -> mean x y < mean x z.\nunfold mean; intros.\napply Uplus_lt_compat_right; auto.\nQed.\n\nLemma mean_lt_compat_left : forall x y z, x < y -> mean x z < mean y z.\nunfold mean; intros.\napply Uplus_lt_compat_left; auto.\nQed.\n\nHint Resolve mean_eq mean_le_compat_left mean_le_compat_right.\nHint Resolve mean_lt_compat_left mean_lt_compat_right.\n\nLemma mean_le_up : forall x y, x <= y -> mean x y <= y.\nintros; apply Ule_trans with (mean y y); auto. \nQed.\n\nLemma mean_le_down : forall x y, x <= y -> x <= mean x y.\nintros; apply Ule_trans with (mean x x); auto. \nQed.\n\nLemma mean_lt_up : forall x y, x < y -> mean x y < y.\nintros; apply Ult_le_trans with (mean y y); auto. \nQed.\n\nLemma mean_lt_down : forall x y, x < y -> x < mean x y.\nintros; apply Ule_lt_trans with (mean x x); auto. \nQed.\n\nHint Resolve mean_le_up mean_le_down mean_lt_up mean_lt_down.\n\n(** *** Properties of $\\frac{1}{2}$ *)\n\nLemma le_half_inv : forall x, x <= [1/2] -> x <= [1-] x.\nintros; apply Ule_trans with ([1/2]); auto.\nsetoid_rewrite Unth_one; auto.\nQed.\n\nHint Immediate le_half_inv.\n\nLemma ge_half_inv : forall x, [1/2] <= x  -> [1-] x <= x.\nintros; apply Ule_trans with ([1/2]); auto.\nsetoid_rewrite Unth_one; auto.\nQed.\n\nHint Immediate ge_half_inv.\n\nLemma Uinv_le_half_left : forall x, x <= [1/2] -> [1/2] <= [1-] x.\nintros; setoid_rewrite Unth_one; auto.\nQed.\n\nLemma Uinv_le_half_right : forall x, [1/2] <= x -> [1-] x <= [1/2].\nintros; setoid_rewrite Unth_one; auto.\nQed.\n\nHint Resolve Uinv_le_half_left Uinv_le_half_right.\n\nLemma half_twice : forall x,  (x <= [1/2]) -> ([1/2]) * (x + x) == x.\nintros; assert (H1 : x <= [1-] x); auto. \nsetoid_rewrite (Udistr_plus_left ([1/2]) H1).\nexact (mean_eq x).\nQed.\n\nLemma half_twice_le : forall x, ([1/2]) * (x + x) <= x.\nintros; apply (Ule_total x ([1/2])); intros; auto.\nsetoid_rewrite (half_twice H); trivial.\nassert (x+x==1); auto.\nsetoid_rewrite H0.\nsetoid_rewrite (Umult_one_right ([1/2])); auto.\nQed.\n\nLemma Uinv_half : forall x, ([1/2]) * ([1-] x)  + ([1/2]) == [1-] (([1/2]) * x).\nintros; setoid_rewrite (Udistr_inv_left ([1/2]) x).\nsetoid_rewrite Unth_one; auto.\nQed.\n\nLemma half_esp : \nforall x, ([1/2] <= x) -> ([1/2]) * (x & x) + [1/2] == x.\nintros; unfold Uesp.\nsetoid_rewrite (Uinv_half ([1-] x + [1-] x)).\nassert (H1:[1-] x <= [1/2]).\nsetoid_rewrite Unth_one; auto.\nsetoid_rewrite (half_twice H1); auto.\nQed.\n\nLemma half_esp_le : forall x, x <= ([1/2]) * (x & x) + [1/2].\nintros; apply (Ule_total ([1/2]) x); intros; auto.\nsetoid_rewrite (half_esp H); trivial.\nassert (x & x == 0); auto.\nsetoid_rewrite H0.\nsetoid_rewrite (Umult_zero_right ([1/2])).\nsetoid_rewrite (Uplus_zero_left ([1/2])); auto.\nQed.\nHint Resolve half_esp_le.\n\n\nLemma half_le : forall x y, y <= [1-] y -> x <= y + y -> ([1/2]) * x <= y.\nintros.\napply not_Ult_le; red; intros.\nassert (y + y < x); auto.\nsetoid_replace x with (mean x x); auto.\nunfold mean; apply Uplus_lt_compat; auto.\nQed.\n\nLemma half_Unth: forall n, ([1/2])*([1/]1+n) <= [1/]1+(S n).\nintros; apply half_le; auto.\nsetoid_rewrite (Unth_prop_sigma n).\napply Ule_trans with ([1-] (sigma (fun _ : nat => [1/]1+(S n)) n)).\napply Uinv_le_compat.\napply sigma_le_compat; auto.\napply Ule_trans with \n([1-] (sigma (fun _ : nat => [1/]1+(S n)) (S n)) + [1/]1+(S n)); auto.\nrewrite sigma_S.\nassert (sigma (fun _ : nat => [1/]1+(S n)) n <= [1-] ([1/]1+(S n))).\napply Ule_trans with (sigma (fun _ : nat => [1/]1+(S n)) (S n)); auto.\nsetoid_rewrite (Uinv_plus_left H); auto.\nQed.\nHint Resolve half_le half_Unth.\n\nLemma half_exp : forall n, [1/2]^n == [1/2]^(S n) + [1/2]^(S n).\nintros; simpl; apply Ueq_sym; exact (mean_eq ([1/2]^n)).\nQed.\n\n(** ** Density *)\nLemma Ule_lt_lim : forall x y,  (forall t, t < x -> t <= y) -> x <= y.\nintros; apply Ule_class; red; intros.\npose (z:= mean y x).\nassert (y < z); unfold z; auto.\napply H1; apply H; unfold z; auto.\nQed.\n\n(** ** Properties of least upper bounds *)\n\nSection lubs.\n\nLemma lub_le_stable : forall f g, (forall n, f n <= g n) -> lub f <= lub g.\nintros; apply lub_le; intros.\napply Ule_trans with (g n); auto.\nQed.\n\nHint Resolve lub_le_stable.\n\nLemma lub_eq_stable : forall f g, (forall n, f n == g n) -> lub f == lub g.\nintros; apply Ule_antisym; auto.\nQed.\n\nHint Resolve lub_eq_stable.\n\nLemma lub_zero : (lub (fun n => 0)) == 0.\napply Ule_antisym; auto.\nQed.\n\nLemma lub_un : (lub (fun n => 1)) == 1.\napply Ule_antisym; auto.\napply le_lub with (f:=fun _ : nat => 1) (n:=O); auto.\nQed.\n\nLemma lub_cte : forall c:U, (lub (fun n => c)) == c.\nintro; apply Ueq_trans with (lub (fun n => c * 1)); auto.\napply Ueq_trans with (c * (lub (fun n => 1))); auto.\nsetoid_rewrite lub_un; auto.\nQed.\n\nHint Resolve lub_zero lub_un lub_cte.\n\nLemma lub_eq_plus_cte_left : forall (f : nat -> U) (k:U), lub (fun n => k + (f n)) == k + (lub f).\nintros; apply Ueq_trans with ((lub f)+k); auto.\napply Ueq_trans with (lub (fun n => (f n) + k)); auto.\nQed.\nHint Resolve lub_eq_plus_cte_left.\n\n\nLemma min_lub_le : forall f g, \n         lub (fun n => min (f n) (g n)) <= min (lub f) (lub g).\nintros; apply min_le.\napply lub_le.\nintro; apply Ule_trans with (f n); auto.\napply lub_le.\nintro; apply Ule_trans with (g n); auto.\nQed.\n\nLemma min_lub_le_incr_aux : forall f g, incr f -> \n         (forall n, exc (fun m => (n<=m)%nat /\\ f n <= g m)) \n         -> min (lub f) (lub g) <= lub (fun n => min (f n) (g n)).\nintros; apply Ule_trans with (lub f); auto.\napply lub_le; intros.\napply (H0 n); auto; intros m (H1,H2).\napply Ule_trans with (min (f m) (g m)); auto.\napply min_le; auto.\napply le_lub with (f:=fun k : nat => min (f k) (g k)) ; auto.\nQed.\n\nLemma min_lub_le_incr : forall f g, incr f -> incr g -> \n         min (lub f) (lub g) <= lub (fun n => min (f n) (g n)).\nintros f g incrf incrg; apply (incr_decomp incrf incrg); auto; intros.\napply (min_lub_le_incr_aux g incrf); auto.\nrewrite min_sym.\napply Ule_trans with (lub (fun n : nat => min (g n) (f n))); auto.\napply (min_lub_le_incr_aux f incrg); auto.\nQed.\n\nLemma lub_eq_esp_right : \n  forall (f : nat -> U) (k : U), lub (fun n : nat => f n & k) == lub f & k.\nintros; apply Ule_antisym.\napply lub_le; auto.\napply Uplus_inv_le_esp.\nrewrite <- lub_eq_plus_cte_right.\napply lub_le_stable; auto.\nQed.\nHint Resolve lub_eq_esp_right.\n\n(** ** Greatest lower bounds *)\n\nDefinition glb (f:nat->U) := [1-]lub (fun n => [1-](f n)).\n\nDefinition prod_inf (f : nat -> U) : U := glb (prod f).\n\nLemma glb_le_stable:\n  forall f g : nat -> U, (forall n : nat, f n <= g n) -> glb f <= glb g.\nintros; unfold glb; auto.\nQed.\nHint Resolve glb_le_stable.\n\nLemma glb_eq_stable:\n  forall f g : nat -> U, (forall n : nat, f n == g n) -> glb f == glb g.\nintros; apply Ule_antisym; auto.\nQed.\nHint Resolve glb_eq_stable.\n\nLemma glb_cte: forall c : U, glb (fun _ : nat => c) == c.\nintros; unfold glb; auto.\nQed.\nHint Resolve glb_cte.\n\nLemma glb_eq_plus_cte_right:\n  forall (f : nat -> U) (k : U), glb (fun n : nat => f n + k) == glb f + k.\nunfold glb; intros.\napply Ueq_trans with ([1-] lub (fun n => ([1-]f n) & [1-] k)); auto.\napply Ueq_trans with ([1-] (lub (fun n => [1-]f n) & [1-] k)).\napply Uinv_eq_compat; apply (lub_eq_esp_right (fun n => [1-]f n) ([1-]k)).\nrewrite Uinv_esp_plus; auto.\nQed.\n\nLemma glb_eq_mult:\n  forall (k : U) (f : nat -> U), glb (fun n : nat => k * f n) == k * glb f.\nunfold glb; intros; auto.\napply Ueq_trans with ([1-] lub (fun n : nat => k * [1-] (f n) + [1-]k)); auto.\napply Ueq_trans with ([1-] (lub (fun n : nat => k * [1-] (f n)) + [1-]k)).\napply Uinv_eq_compat.\napply lub_eq_plus_cte_right with (f:=fun n : nat => k * [1-] f n).\nrewrite (lub_eq_mult k (fun n : nat =>  [1-] f n)).\napply Uinv_eq_perm_left; auto.\nrewrite Udistr_inv_left; auto.\nQed.\n\nLemma glb_le:   forall (f : nat -> U) (n : nat), glb f <= (f n).\nunfold glb; intros; apply Uinv_le_perm_left.\napply le_lub with (f:=fun n => [1-]f n); auto.\nQed.\n\nLemma le_glb: forall (f : nat -> U) (x:U), (forall n : nat, x <= f n)-> x <= glb f.\nunfold glb; intros; apply Uinv_le_perm_right.\napply lub_le with (f:=fun n => [1-]f n); auto.\nQed.\nHint Resolve glb_le.\n\n(*\nmin_lub_le_incr:\n  forall f g : nat -> U,\n  incr f ->\n  incr g -> min (lub f) (lub g) <= lub (fun n : nat => min (f n) (g n))\nmin_lub_le_incr_aux:\n  forall f g : nat -> U,\n  incr f ->\n  (forall n : nat, exc (fun m : nat => (n <= m)%nat /\\ f n <= g m)) ->\n  min (lub f) (lub g) <= lub (fun n : nat => min (f n) (g n))\nmin_lub_le:\n  forall f g : nat -> U,\n  lub (fun n : nat => min (f n) (g n)) <= min (lub f) (lub g)\n*)\nLemma glb_le_esp :  forall f g, (glb f) & (glb g) <= glb (fun n => (f n) & (g n)).\nintros; apply le_glb; auto.\nQed.\nHint Resolve glb_le_esp.\n\nLemma Uesp_min : forall a1 a2 b1 b2, min a1 b1 & min a2 b2 <= min (a1 & a2) (b1 & b2).\nintros; apply min_le.\napply Uesp_le_compat; auto.\napply Uesp_le_compat; auto.\nQed.\n\nLemma mon_seq_Succ : forall f : nat -> U, (forall n, f n <= f (S n)) -> mon_seq Ule f.\nred; intros.\nelim H0; auto.\nQed.\nHint Immediate mon_seq_Succ.\n\nVariables f g : nat -> U.\n\nHypothesis monf : forall n, f n <= f (S n).\nHypothesis mong : forall n, g n <= g (S n).\n\nLemma mon_seqf : mon_seq Ule f.\nauto.\nQed.\n\nLemma mon_seqg : mon_seq Ule g.\nauto.\nQed.\n\nHint Resolve mon_seqf mon_seqg.\n\nLemma lub_lift : forall n,  (lub f) == (lub (fun k => f (n+k)%nat)).\nintro; apply Ule_antisym; auto.\napply lub_le_stable; auto with arith.\nQed.\n\nHint Resolve lub_lift.\n\nLet sum := fun n => f n + g n.\n\nLemma mon_sum : mon_seq Ule sum.\nunfold mon_seq,sum in *; intros; apply Uplus_le_compat; auto.\nQed.\n\nHint Resolve mon_sum.\n\nLemma lub_eq_plus : lub (fun n => (f n) + (g n)) == (lub f) + (lub g).\napply Ule_antisym.\napply lub_le; auto.\napply Ule_trans with (lub (fun n => lub f + g n)); auto.\napply lub_le; intros.\napply Ule_trans with (lub (fun m => f (n+m)) + g n); auto.\nsetoid_rewrite <- (lub_eq_plus_cte_right (fun m : nat => f (n + m)) (g n)).\napply lub_le; intros.\napply Ule_trans with (f (n + n0) + g (n + n0)); auto with arith.\napply le_lub with (f:=fun n : nat => f n + g n) (n:=(n+n0)%nat).\nQed.\nHint Resolve lub_eq_plus.\n\n\n\n\nVariables k : U.\nLet prod := fun n => k * f n.\n\nLemma mon_prod : mon_seq Ule prod.\nunfold mon_seq,prod in *; intros.\napply Umult_le_compat_right; auto.\nQed.\n\nLet inv:= fun n => [1-] (g n).\n\nLemma lub_inv : (forall n, f n <= inv n) -> lub f <= [1-] (lub g).\nunfold inv; intros.\napply Uinv_le_perm_right.\napply lub_le; intros.\napply Uinv_le_perm_right.\napply Ule_trans with (lub (fun k => f (n+k)%nat)); auto.\napply lub_le; intros.\napply Ule_trans with ([1-] (g (n+n0))); auto with arith.\nQed.\n\nVariable h : nat -> U.\nHypothesis dech : forall n, h (S n) <= h n.\n\nLemma dec_sech : forall n m, (n <= m)%nat -> h m <= h n.\ninduction 1; auto.\napply Ule_trans with (h m); auto.\nQed.\nHint Resolve dec_sech.\n\nLemma glb_lift : forall n,  (glb h) == (glb (fun k => h (n+k)%nat)).\nintro; apply Ule_antisym.\napply le_glb; auto.\napply glb_le_stable; auto with arith.\nQed.\n\nHint Resolve glb_lift.\n\nLemma lub_glb_le : (forall n, f n <= h n) -> lub f <= glb h.\nintros; apply lub_le; intros.\napply Ule_trans with (glb (fun k => h (n+k)%nat)); auto.\napply le_glb; intros.\napply Ule_trans with (f (n+n0)); auto with arith.\nQed.\n\nEnd lubs.\n\nLemma double_lub_simpl : forall h : nat -> nat -> U,\n     (forall n m, h n m <= h (S n) m) ->  (forall n m, h n m <= h n (S m)) \n     -> lub (fun n => lub (h n)) == lub (fun n => h n n). \nintros; apply Ule_antisym.\napply lub_le; intros.\nrewrite (lub_lift (h n) (H0 n) n); intros.\napply lub_le; intros.\napply Ule_trans with (h (n + n0)%nat (n+n0)%nat); auto.\napply (@mon_seq_Succ (fun p => h p (n+n0)%nat) (fun p => H p (n+n0)%nat)); auto with arith.\napply le_lub with (f:=fun p => h p p) (n:=(n + n0)%nat).\napply lub_le; intros.\napply Ule_trans with (lub (h n)); auto.\napply le_lub with (f:=fun n0 : nat => lub (h n0)) (n:=n).\nQed.\n\nLemma double_lub_exch_le : forall h : nat -> nat -> U,\n lub (fun n => lub (fun m => h n m)) <= lub (fun m => lub (fun n => h n m)).\nintros; apply lub_le; intros.\napply lub_le; intros.\napply Ule_trans with (lub (fun m : nat => h n m)).\napply (le_lub (fun m => h n m)).\napply lub_le_stable; intros.\napply (le_lub (fun n2 : nat => h n2 n1)).\nQed.\nHint Resolve double_lub_exch_le.\n\nHint Resolve double_lub_exch_le.\n\nLemma double_lub_exch : forall h : nat -> nat -> U,\n lub (fun n => lub (fun m => h n m)) == lub (fun m => lub (fun n => h n m)).\nintros; apply Ule_antisym; auto.\nQed.\n\nHint Resolve double_lub_exch.\n\n(** *** Definitions *)\nDefinition fle (A:Type) (f g:A->U) : Prop := forall x:A, (f x) <=  (g x).\nDefinition feq (A:Type) (f g:A->U) : Prop := forall x:A, (f x) ==  (g x).\nHint Unfold fle feq.\nDefinition fplus (A:Type) (f g:A->U) (x:A) : U := (f x) + (g x).\nDefinition fesp (A:Type) (f g:A->U) (x:A) : U := (f x) & (g x).\nDefinition fminus (A:Type) (f g:A->U) (x:A) : U := (f x) - (g x).\nDefinition finv (A:Type) (f:A->U) (x:A) : U := Uinv (f x).\nDefinition fmult (A:Type) (k:U) (f:A->U) (x:A) : U := k * (f x).\nDefinition f_one (A:Type) (x : A) : U := U1.\nDefinition f_zero (A:Type) (x : A) : U := U0.\nDefinition f_cte (A:Type) (c:U) (x : A) : U := c.\nDefinition flub (A:Type) (fn:nat->A->U) (x : A) : U := lub (fun n => fn n x).\nDefinition fglb (A:Type) (fn:nat->A->U) (x : A) : U := glb (fun n => fn n x).\nDefinition increase (A:Type)(fn : nat -> A -> U) := forall n, fle (fn n) (fn (S n)).\nDefinition decrease (A:Type)(fn : nat -> A -> U) := forall n, fle (fn (S n)) (fn n).\n\nImplicit Arguments f_one [].\nImplicit Arguments f_zero [].\nImplicit Arguments f_cte [].\n\n(** *** Elementary properties *)\n\nLemma feq_refl : forall (A:Type) (f : A->U), feq f f.\nauto.\nQed.\nHint Resolve feq_refl.\n\nLemma feq_sym : forall (A:Type) (f g : A->U), feq f g -> feq g f.\nauto.\nQed.\n\nLemma feq_trans : forall (A:Type) (f g h : A->U), feq f g -> feq g h -> feq f h.\nunfold feq; intros; apply Ueq_trans with (g x); auto.\nQed.\n\nLemma fSetoid : forall (A:Type), Setoid_Theory (A->U) (@feq A).\nsplit; red; auto.\nexact (@feq_trans A).\nQed.\n\nAdd Parametric Setoid A : (A->U) (@feq A) (@fSetoid A) as f_Setoid.\n\nLemma feq_fle : forall (A:Type) (f g : A->U), feq f g -> fle f g.\nauto.\nQed.\n\nLemma feq_fle_sym : forall (A:Type) (f g : A->U), feq f g -> fle g f.\nauto.\nQed.\nHint Immediate feq_fle feq_fle_sym.\n\nLemma fle_le : forall (A:Type) (f g : A->U), fle f g -> forall x, f x <= g x.\nauto.\nQed.\n\nLemma fle_refl : forall (A:Type) (f:A->U), fle f f.\nauto.\nQed.\n\nLemma fle_trans : forall (A:Type) (f g h : A->U), fle f g -> fle g h -> fle f h.\nunfold fle; intros; apply Ule_trans with (g x); auto.\nQed.\n\nAdd Parametric Relation A : (A->U) (@fle A) \n   reflexivity proved by (@fle_refl A) transitivity proved by (@fle_trans A) as fle_Relation.\n\nLemma fle_feq_trans : forall (A:Type) (f g h : A->U), fle f g -> feq g h -> fle f h.\nunfold fle; intros; apply Ule_trans with (g x); auto.\nQed.\n\nLemma feq_fle_trans : forall (A:Type) (f g h : A->U), feq f g -> fle g h -> fle f h.\nunfold fle; intros; apply Ule_trans with (g x); auto.\nQed.\n\nLemma fle_antisym : forall (A:Type) (f g : A->U), fle f g -> fle g f -> feq f g.\nauto.\nQed.\nHint Resolve fle_antisym.\n\nAdd Parametric Morphism A : (@fle A) with signature  (@feq A) ==> (@feq A) ==> iff as  fle_feq_compat. \nsplit; intros.\napply feq_fle_trans with x; auto.\napply fle_feq_trans with x0; auto.\napply feq_fle_trans with y; auto.\napply fle_feq_trans with y0; auto.\nQed.\n\nLemma fle_fplus_left : forall (A:Type) (f g : A->U), fle f (fplus f g).\nunfold fle,fplus; auto.\nQed.\n\nLemma fle_fplus_right : forall (A:Type) (f g : A->U), fle g (fplus f g).\nunfold fle,fplus; auto.\nQed.\n\nLemma fle_fmult : forall (A:Type) (k:U)(f : A->U), fle (fmult k f) f.\nunfold fle,fmult; auto.\nQed.\n\nLemma fle_zero : forall (A:Type) (f : A->U), fle (f_zero A) f.\nunfold fle,f_zero; auto.\nQed.\n\nLemma fle_one : forall (A:Type) (f : A->U), fle f (f_one A).\nunfold fle,f_one; auto.\nQed.\n\nLemma feq_finv_finv : forall (A:Type) (f : A->U), feq (finv (finv f)) f.\nunfold feq,finv; auto.\nQed.\n\nLemma fle_fesp_left : forall (A:Type) (f g : A->U), fle (fesp f g) f.\nunfold fle,fesp; auto.\nQed.\n\nLemma fle_fesp_right : forall (A:Type) (f g : A->U), fle (fesp f g) g.\nunfold fle,fesp; auto.\nQed.\n\n(** *** Defining morphisms *)\n\nAdd Parametric Morphism A : (@fplus A) with signature (@feq A) ==> (@feq A) ==> (@feq A) as fplus_feq_compat.\nunfold feq,fplus; auto.\nQed.\n\nAdd Parametric Morphism A : (@fplus A) with signature (@fle A) ++> (@fle A) ++> (@fle A) as fplus_fle_compat.\nunfold fle,fplus; auto.\nQed.\n\nAdd Parametric Morphism A : (@finv A) with signature (@feq A) ==> (@feq A) as finv_feq_compat.\nunfold feq,finv; auto.\nQed.\n\nAdd Parametric Morphism A : (@finv A) with signature (@fle A) --> (@fle A) as finv_fle_compat.\nunfold fle,finv; auto.\nQed.\n\nAdd Parametric Morphism A : (@fmult A) with signature Ueq ==> (@feq A) ==> (@feq A) as fmult_feq_compat.\nunfold feq,fmult; auto.\nQed.\n\nAdd Parametric Morphism A : (@fmult A) with signature Ule ++> (@fle A) ++> (@fle A) as fmult_fle_compat.\nunfold fle,fmult; auto.\nQed.\n\nAdd Parametric Morphism A : (@fminus A) with signature (@feq A) ==> (@feq A) ==> (@feq A) as fminus_feq_compat.\nunfold feq,fminus; auto.\nQed.\n\nAdd Parametric Morphism A : (@fminus A) with signature (@fle A) ++> (@fle A) --> (@fle A) as fminus_fle_compat.\nunfold fle,fminus; auto.\nQed.\n\n\nAdd Parametric Morphism A : (@fesp A) with signature (@feq A) ==> (@feq A) ==> (@feq A) as fesp_feq_compat.\nunfold feq,fesp; auto.\nQed.\n\nAdd Parametric Morphism A : (@fesp A) with signature (@fle A) ++> (@fle A) ++> (@fle A) as fesp_fle_compat.\nunfold fle,fesp; auto.\nQed.\n\nHint Immediate feq_sym fplus_fle_compat fplus_feq_compat \nfmult_fle_compat fmult_feq_compat fminus_fle_compat fminus_feq_compat.\n\nHint Resolve fle_fplus_left  fle_fplus_right fle_zero  fle_one feq_finv_finv finv_fle_compat\nfle_fmult fle_fesp_left fle_fesp_right.\n\nHint Resolve finv_feq_compat finv_fle_compat.\n\n(** ** Fixpoints of functions of type $A\\ra\\U$ *)\nSection FixDef.\nVariable A :Type.\n\nVariable F : (A->U) -> A -> U.\nDefinition Fmonotonic :=  forall f g, (fle f g) -> fle (F f) (F g).\nDefinition Fstable :=  forall f g, (feq f g) -> feq (F f) (F g).\n\nLemma Fmonotonic_stable : Fmonotonic -> Fstable.\nunfold Fmonotonic, Fstable; auto.\nQed.\n\nLemma Fmonotonic_fle : Fmonotonic -> forall f g, fle f g -> fle (F f) (F g).\nauto.\nQed.\n\nLemma Fmonotonic_le : Fmonotonic -> forall f g, fle f g -> forall x, F f x <= F g x.\nauto.\nQed.\n\nLemma Fstable_feq : Fstable -> forall f g, feq f g -> feq (F f) (F g).\nauto.\nQed.\n\nLemma Fstable_eq : Fstable -> forall f g, feq f g -> forall x, F f x == F g x.\nauto.\nQed.\n\nHint Resolve Fmonotonic_fle Fstable_feq Fmonotonic_le  Fstable_eq.\n\nHypothesis Fmon : Fmonotonic.\n\nFixpoint muiter (n:nat) (x:A) {struct n} : U := \n        match n with O => 0 | S p => F (muiter p) x end.\n\nFixpoint nuiter (n:nat) (x:A) {struct n} : U := \n        match n with O => 1 | S p => F (nuiter p) x end.\n\nDefinition mufix (x:A) := lub (fun n => muiter n x).\nDefinition nufix (x:A) := glb (fun n => nuiter n x).\n\nLemma mufix_inv : forall f, fle (F f) f -> fle mufix f.\nunfold mufix; red; intros; apply lub_le.\nintro n; generalize x; induction n; simpl; intros; auto.\napply Ule_trans with (F f x0); auto.\nQed.\nHint Resolve mufix_inv.\n\nLemma nufix_inv : forall f, fle f (F f) -> fle f nufix.\nunfold nufix; red; intros; apply le_glb.\nintro n; generalize x; induction n; simpl; intros; auto.\napply Ule_trans with (F f x0); auto.\nQed.\nHint Resolve nufix_inv.\n\nLemma mufix_le : fle mufix (F mufix).\nunfold mufix at 1; red; intros; apply lub_le.\ndestruct n; simpl; auto.\napply Fmon.\nunfold mufix; intros.\nred; intro x0; apply (le_lub (fun n0 : nat => muiter n0 x0)).\nQed.\nHint Resolve mufix_le.\n\nLemma nufix_sup : fle (F nufix) nufix.\nunfold nufix at 2; red; intros; apply le_glb.\ndestruct n; simpl; auto.\napply Fmon.\nunfold nufix; intros.\nintro x0; apply (glb_le (fun n0 : nat => nuiter n0 x0)).\nQed.\nHint Resolve nufix_sup.\n\nDefinition Fcontlub := forall (fn : nat -> A -> U), increase fn ->\n           fle (F (flub fn)) (flub (fun n => F (fn n))).\nDefinition Fcontglb := forall (fn : nat -> A -> U), decrease fn ->\n           fle (fglb (fun n => F (fn n))) (F (fglb fn)).\n\nLemma Fcontlub_fle : Fcontlub -> forall (fn : nat -> A -> U), increase fn ->\n           fle (F (flub fn)) (flub (fun n => F (fn n))).\nauto.\nQed.\n\nLemma Fcontglb_fle : Fcontglb -> forall (fn : nat -> A -> U), decrease fn ->\n           fle (fglb (fun n => F (fn n))) (F (fglb fn)).\nauto.\nQed.\n\n\nHypothesis muFcont : forall (fn : nat -> A -> U), increase fn ->\n           fle (F (flub fn)) (flub (fun n => F (fn n))).\n\nHypothesis nuFcont : forall (fn : nat -> A -> U), decrease fn -> \n           fle (fglb (fun n => F (fn n))) (F (fglb fn)).\n\nImplicit Arguments muFcont [].\nImplicit Arguments nuFcont [].\n\nLemma incr_muiter : increase muiter.\nred; intros; induction n; red; simpl; intros; auto.\nQed.\n\nLemma decr_nuiter : decrease nuiter.\nred; intros; induction n; red; simpl; intros; auto.\nQed.\n\nHint Resolve incr_muiter decr_nuiter.\n\nLemma mufix_sup : forall x, F mufix x <= mufix x.\nintros; apply Ule_trans with (lub (fun n => F (muiter n) x)); auto.\napply (muFcont muiter) with (x:=x); auto.\nunfold mufix.\napply lub_le.\nintro n; apply (le_lub (fun n0 : nat => muiter n0 x) (S n)); auto .\nQed.\nHint Resolve mufix_sup.\n\nLemma nufix_le : forall x, nufix x <= F nufix x.\nintros; apply Ule_trans with (glb (fun n => F (nuiter n) x)); auto.\nunfold nufix.\napply le_glb.\nintro n; apply (glb_le (fun n0 : nat => nuiter n0 x) (S n)); auto .\napply (nuFcont nuiter) with (x:=x); auto.\nQed.\nHint Resolve nufix_le.\n\nLemma mufix_eq : forall x, mufix x == F mufix x.\nintros; apply Ule_antisym; auto.\nQed.\nHint Resolve mufix_eq.\n\nLemma nufix_eq : forall x, nufix x == F nufix x.\nintros; apply Ule_antisym; auto.\nQed.\nHint Resolve nufix_eq.\n\nEnd FixDef.\nHint Unfold Fmonotonic.\nHint Resolve Fmonotonic_stable.\nHint Resolve Fmonotonic_fle Fstable_feq Fmonotonic_le  Fstable_eq.\nHint Resolve Fcontlub_fle Fcontglb_fle.\n\nDefinition Fcte (A:Type) (f:A->U) := fun (_:A->U) => f.\nLemma Fcte_mon : forall (A:Type) (f:A->U), Fmonotonic (Fcte f).\nrepeat red; unfold Fcte; auto.\nQed.\n\nLemma mufix_cte : forall (A:Type) (f:A->U), feq (mufix (Fcte f)) f.\nred; intros; unfold mufix.\napply Ule_antisym.\napply lub_le; intros.\ngeneralize x; induction n; unfold Fcte; simpl; intros; auto.\napply Ule_trans with (muiter (Fcte f) (S O) x); auto.\napply le_lub with (f:=fun n : nat => muiter (Fcte f) n x) (n:=S O).\nQed.\n\nLemma nufix_cte : forall (A:Type) (f:A->U), feq (nufix (Fcte f)) f.\nred; intros; unfold nufix.\napply Ule_antisym.\napply Ule_trans with (nuiter (Fcte f) (S O) x); auto.\napply glb_le with (f:=fun n : nat => nuiter (Fcte f) n x) (n:=S O).\napply le_glb; intros.\ngeneralize x; induction n; unfold Fcte; simpl; intros; auto.\nQed.\n\nHint Resolve mufix_cte nufix_cte.\n\n(** ** Properties of barycenter of two points *)\nSection Barycenter.\nVariables a b : U.\nHypothesis sum_le_one : a <= [1-] b.\n\nLemma Uinv_bary : \n   forall x y : U, [1-] (a * x + b * y) == a * [1-] x + b * [1-] y + [1-] (a + b).\nintros.\napply Uplus_eq_simpl_left with (a * x); auto.\napply Uinv_le_perm_right.\nsetoid_rewrite (Udistr_inv_left a x).\nrepeat norm_assoc_right.\napply Uplus_le_compat_right.\napply Ule_trans with (b + [1-] (a + b)); auto.\napply Ule_trans with ([1-] (a + b) + b); auto.\napply Ueq_trans with ([1-] (b * y)).\napply Ueq_trans with \n   ([1-] (a * x + b * y) + a * x); auto.\nsetoid_rewrite (Udistr_inv_left b y); auto.\napply Ueq_trans with  \n ((a * x + a * [1-] x) + b * [1-] y + [1-] (a + b)).\nassert (x <= ([1-] ([1-] x))); auto.\nsetoid_rewrite <- (Udistr_plus_left a H); auto.\nsetoid_rewrite (Uinv_opp_right x).\nsetoid_rewrite (Umult_one_right a).\napply Ueq_trans with (b * [1-] y + ([1-] (a + b) + a)).\nassert (b <= ([1-] a)); auto.\nsetoid_rewrite (Uinv_plus_left H0); auto.\nsetoid_rewrite (Uplus_sym a (b * [1-] y)); auto.\napply Ueq_trans with \n(b * [1-] y + (a + [1-] (a + b))); auto.\napply Ueq_trans with \n(((a * x + a * [1-] x) + (b * [1-] y + [1-] (a + b)))); auto.\napply Ueq_trans with \n(((a * x + (a * [1-] x + (b * [1-] y + [1-] (a + b)))))); auto.\nQed.\n\nLemma Uinv_bary_le : \n   forall x y : U,   a * [1-] x + b * [1-] y <= [1-] (a * x + b * y).\nintros; rewrite Uinv_bary; auto.\nQed.\n\nEnd Barycenter.\nHint Resolve Uinv_bary_le.\n\nLemma Uinv_half_bary : \n   forall x y : U, [1-] ([1/2] * x + [1/2] * y) == [1/2] * [1-] x + [1/2] * [1-] y.\nintros; rewrite Uinv_bary; auto.\nrewrite Unth_one_plus; rewrite Uinv_one; auto.\nQed.\nHint Resolve Uinv_half_bary.\n\n(** ** Properties of generalized sums [sigma] *)\nLemma sigma_plus : forall (f g : nat -> U) (n:nat), \n   (sigma (fun k => (f k) + (g k)) n) == (sigma f n) + (sigma g n).\nintros; induction n; simpl; auto.\nrepeat rewrite sigma_S; setoid_rewrite IHn.\nrepeat norm_assoc_right; apply Uplus_eq_compat_right.\nsetoid_rewrite (Uplus_sym (g n) ((sigma f n) + (sigma g n))).\nrepeat norm_assoc_right; apply Uplus_eq_compat_right; auto.\nQed.\n\n\nDefinition retract (f : nat -> U) (n : nat) := forall k, (k < n)%nat -> (f k) <= [1-] (sigma f k).\n\nLemma retract0 : forall (f : nat -> U), retract f 0.\nred; intros; absurd (k < O)%nat; auto with arith.\nQed.\n\nLemma retract_pred : forall (f : nat -> U) (n : nat), retract f (S n) -> retract f n.\nunfold retract; auto with arith.\nQed.\n\nLemma retractS: forall (f : nat -> U) (n : nat), retract f (S n) -> f n <= [1-] (sigma f n).\nunfold retract; auto with arith.\nQed.\n\nLemma retractS_intro: forall (f : nat -> U) (n : nat), \n   retract f n -> f n <= [1-] (sigma f n)->retract f (S n).\nunfold retract; intros.\nassert ((k<n)%nat \\/ k=n); try omega; intuition; subst; auto.\nQed.\n\nHint Resolve retract0 retractS_intro.\nHint Immediate retract_pred retractS.\n\nLemma retract_lt : forall (f : nat -> U) (n : nat),  (sigma f n) < 1 -> retract f n.\ninduction n; simpl; auto.\nrewrite sigma_S.\nintros;assert ((sigma f n)<1).\napply Ule_lt_trans with (f n + sigma f n); auto.\nassert (f n <= [1-](sigma f n)); auto.\napply Uplus_lt_Uinv; auto.\nQed.\n\nLemma sigma_mult : \n  forall (f : nat -> U) n c, retract f n -> (sigma (fun k => c * (f k)) n) == c * (sigma f n).\nintros; induction n; simpl; auto.\nrepeat rewrite sigma_S.\nassert (H1: retract f n); auto.\nsetoid_rewrite (IHn H1).\nsetoid_rewrite (Udistr_plus_left c (retractS H)); auto.\nQed.\nHint Resolve sigma_mult.\n\nLemma sigma_prod_maj :  forall (f g : nat -> U) n, \n   (sigma (fun k => (f k) * (g k)) n) <= (sigma f n).\nauto.\nQed.\n\nHint Resolve sigma_prod_maj.\n\nLemma sigma_prod_le :  forall (f g : nat -> U) (c:U), (forall k, (f k) <= c) \n   -> forall n, (retract g n) -> (sigma (fun k => (f k) * (g k)) n) <= c * (sigma g n).\ninduction n; simpl; intros; auto.\nrepeat rewrite sigma_S.\napply Ule_trans with ((f n) * (g n) + (c * sigma g n)); auto.\napply Ule_trans with ( c * (g n) + (c * sigma g n)); auto.\nsetoid_rewrite (Udistr_plus_left c (retractS H0)); auto.\nQed.\n\nLemma sigma_prod_ge :  forall (f g : nat -> U) (c:U), (forall k, c <= (f k)) \n   -> forall n, (retract g n) -> c * (sigma g n) <= (sigma (fun k => (f k) * (g k)) n).\ninduction n; simpl; intros; auto.\nrepeat rewrite sigma_S.\nsetoid_rewrite (Udistr_plus_left c (retractS H0)); auto.\napply Ule_trans with (c * (g n) + sigma (fun k : nat => f k * g k) n); auto.\nQed.\n\nHint Resolve sigma_prod_maj sigma_prod_le  sigma_prod_ge.\n\nLemma sigma_inv : forall (f g : nat -> U) (n:nat), (retract f n) ->\n  [1-] (sigma (fun k => f k * g k) n) == (sigma (fun k => f k * [1-] (g k)) n) + [1-] (sigma f n).\nintros; induction n; simpl; repeat rewrite sigma_S; auto.\napply Uplus_eq_simpl_right with ((f n) * (g n)).\nsetoid_rewrite \n (Uinv_inv (f n * g n + sigma (fun k : nat => f k * g k) n));auto.\napply Uinv_le_perm_right.\nsetoid_rewrite (Udistr_inv_left (f n) (g n)).\nrepeat norm_assoc_right; apply Uplus_le_compat_right.\napply Ule_trans with \n  (sigma f n + [1-] (f n + sigma f n)); auto.\nassert (sigma f n <= [1-] (f n)); auto.\nsetoid_rewrite <- (Uinv_plus_right H0); auto.\n\nassert (sigma (fun k : nat => f k * g k) n <= [1-] (f n * g n)).\napply Ule_trans with (sigma f n); auto.\napply Ule_trans with ([1-] (f n)); auto.\nsetoid_rewrite (Uinv_plus_left H0).\napply Ueq_trans with (1:=IHn (retract_pred H)).\nsetoid_rewrite (Uplus_sym (f n * [1-] (g n))\n                          (sigma (fun k : nat => f k * [1-] (g k)) n)).\nrepeat norm_assoc_right; apply Uplus_eq_compat_right.\nsetoid_rewrite (Uplus_sym  ([1-] (f n + sigma f n)) (f n * g n)).\nrepeat norm_assoc_left.\nassert ([1-] (g n) <= [1-] (g n)); auto.\n\nsetoid_rewrite <- (Udistr_plus_left (f n) H1).\nsetoid_rewrite (Uinv_opp_left (g n)).\nsetoid_rewrite (Umult_one_right (f n)); auto.\nsetoid_rewrite (Uplus_sym (f n) ([1-] (f n + sigma f n))).\napply Ueq_sym; apply Uinv_plus_left; auto.\nQed.\n\n\n(** ** Product by an integer *)\n\n(** *** Definition of [Nmult n x] written [n */ x] *)\nFixpoint Nmult (n: nat) (x : U) {struct n} : U := \n   match n with O => 0 | (S O) => x | S p => x + (Nmult p x) end.\n\n(** *** Condition for [n */ x] to be exact : $n = 0$ or $x\\leq \\frac{1}{n}$ *)\nDefinition Nmult_def (n: nat) (x : U) := \n   match n with O => True | S p => x <= [1/]1+p end.\n\nLemma Nmult_def_O : forall x, Nmult_def O x.\nsimpl; auto.\nQed.\nHint Resolve Nmult_def_O.\n\nLemma Nmult_def_1 : forall x, Nmult_def (S O) x.\nsimpl; intro; rewrite Unth_zero; auto.\nQed.\nHint Resolve Nmult_def_1.\n\nLemma Nmult_def_intro : forall n x , x <= [1/]1+n -> Nmult_def (S n) x.\ndestruct n; simpl; auto.\nQed.\nHint Resolve Nmult_def_intro.\n\nLemma Nmult_def_Unth: forall n , Nmult_def (S n) ([1/]1+n).\nauto.\nQed.\nHint Resolve Nmult_def_Unth.\n\nLemma Nmult_def_pred : forall n x, Nmult_def (S n) x -> Nmult_def n x.\nintros n x; case n; simpl; intros; auto.\napply Ule_trans with ([1/]1+(S n0)); auto.\nQed.\n\nHint Immediate Nmult_def_pred.\n\nLemma Nmult_defS : forall n x, Nmult_def (S n) x -> x <= [1/]1+n.\ndestruct n; simpl; intros; auto.\nQed.\nHint Immediate Nmult_defS.\n\nLemma Nmult_def_class : forall n p, class (Nmult_def n p).\nunfold class; destruct n; intuition.\nQed.\nHint Resolve Nmult_def_class.\n\nAdd Morphism Nmult_def with signature (@eq _) ==> Ueq ==> iff as Nmult_def_eq_compat.\n\nInfix \"*/\" := Nmult (at level 60) : U_scope.\nunfold Nmult_def; destruct y; intuition.\nrewrite <- H; auto.\nrewrite H; auto.\nQed.\n\nLemma Nmult_def_zero : forall n, Nmult_def n 0.\ndestruct n; auto.\nQed.\nHint Resolve Nmult_def_zero.\n\n(** *** Properties of [n */ x] *)\n\nLemma Nmult_0 : forall (x:U), O*/x = 0.\ntrivial.\nQed.\n\nLemma Nmult_1 : forall (x:U), (S O)*/x = x.\ntrivial.\nQed.\n\nLemma Nmult_zero : forall n, n */ 0 == 0.\ninduction n; simpl; auto.\ndestruct n; auto.\nQed.\n\nLemma Nmult_SS : forall (n:nat) (x:U), S (S n) */x = x + (S n */ x).\ndestruct n; simpl; auto.\nQed.\n\nLemma Nmult_2 : forall (x:U), 2*/x = x + x.\ntrivial.\nQed.\n\nLemma Nmult_S : forall (n:nat) (x:U), S n */ x == x + (n*/x).\ndestruct n; simpl; auto.\nQed.\n\nHint Resolve Nmult_1 Nmult_SS Nmult_2 Nmult_S.\n\nAdd Morphism Nmult with signature (@eq _) ==> Ueq ==> Ueq as Nmult_eq_compat.\nintros n x1 x2 eq1; induction n; simpl; auto; intros.\ndestruct n; repeat rewrite Nmult_SS; trivial.\napply Uplus_eq_compat; auto.\nQed.\nHint Resolve Nmult_eq_compat.\n\nLemma Nmult_eq_compat_right : forall (n m:nat) (x:U), (n = m)%nat -> n */ x == m */ x.\nintros; subst n; trivial.\nQed.\nHint Resolve Nmult_eq_compat_right.\n\nLemma Nmult_le_compat_right :  forall n x y, x <= y -> n */ x <= n */ y.\nintros; induction n; auto.\nrewrite (Nmult_S n x); rewrite (Nmult_S n y);auto.\nQed.\n\nLemma Nmult_le_compat_left : forall n m x, (n <= m)%nat -> n */ x <= m */ x.\ninduction 1; trivial.\nrewrite (Nmult_S m x); auto.\napply Ule_trans with (m */ x); auto.\nQed.\n\nLemma Nmult_sigma : forall (n:nat) (x:U), n */ x == sigma (fun k => x) n.\nintros n x; induction n; simpl; auto.\ndestruct n; auto.\nunfold sigma; simpl; auto.\nrewrite IHn; auto.\nQed.\n\nHint Resolve Nmult_eq_compat_right Nmult_le_compat_right \nNmult_le_compat_left Nmult_sigma.\n\nLemma Nmult_Unth_prop : forall n:nat, [1/]1+n == [1-] (n*/ ([1/]1+n)).\nintro.\nrewrite (Nmult_sigma n ([1/]1+n)).\nexact (Unth_prop n).\nQed.\nHint Resolve Nmult_Unth_prop.\n\nLemma Nmult_n_Unth: forall n:nat, n */ [1/]1+n == [1-] ([1/]1+n).\nintro; apply Uinv_eq_perm_right; auto.\nQed.\n\nLemma Nmult_Sn_Unth: forall n:nat, S n */ [1/]1+n == 1.\nintro; rewrite (Nmult_S n ([1/]1+n)).\nrewrite (Nmult_n_Unth n); auto.\nQed.\n\nHint Resolve Nmult_n_Unth Nmult_Sn_Unth.\n\nLemma Nmult_ge_Sn_Unth: forall n k, (S n <= k)%nat -> k */ [1/]1+n == 1.\ninduction 1; auto.\nrewrite (Nmult_S m ([1/]1+n)); rewrite IHle; auto.\nQed.\n\nLemma Nmult_le_n_Unth: forall n k, (k <= n)%nat -> k */ [1/]1+n <= [1-] ([1/]1+n).\nintros; apply Ule_trans with (n */ [1/]1+n); auto.\nQed.\n\nHint Resolve Nmult_ge_Sn_Unth Nmult_le_n_Unth.\n\n\nLemma Nmult_Umult_assoc_left : forall n x y, Nmult_def n x -> n*/(x*y) == (n*/x)*y.\nintros n x y; induction n; auto; intros.\ndestruct n; auto.\nrepeat rewrite Nmult_SS.\nassert(Nmult_def (S n) x); auto.\nsetoid_rewrite (IHn H0).\nassert (x <= [1-] ((S n) */ x)). \napply Uinv_le_perm_right.\napply Ule_trans with ([1-] ([1/]1+(S n))); auto.\napply Ule_trans with ((S n) */ ([1/]1+(S n))); auto.\napply Ueq_sym; auto.\nQed.\n\nHint Resolve Nmult_Umult_assoc_left.\n\nLemma Nmult_Umult_assoc_right : forall n x y, Nmult_def n y -> n*/(x*y) == x*(n*/y).\nintros; rewrite (Umult_sym x y); rewrite (Nmult_Umult_assoc_left n y x H); auto.\nQed.\n\nHint Resolve Nmult_Umult_assoc_right.\n\nLemma plus_Nmult_distr : forall n m x, (n + m) */ x== (n */ x) + (m */ x).\nintros n m x; induction n; auto; intros.\nrewrite plus_Sn_m.\nrewrite (Nmult_S (n + m) x).\nsetoid_rewrite IHn.\nrewrite (Nmult_S n x); auto.\nQed.\n\nLemma Nmult_Uplus_distr : forall n x y, n */ (x + y) == (n */ x) + (n */ y).\nintros n x y; induction n.\nsimpl; auto.\nrewrite (Nmult_S n (x+y)).\nrewrite IHn.\nnorm_assoc_right.\nrewrite (Uplus_perm2 y (n */ x) (n */ y)).\nrewrite <- (Nmult_S n y).\nnorm_assoc_left.\napply Uplus_eq_compat; auto.\nQed.\n\nLemma Nmult_mult_assoc : forall n m x, (n * m) */ x == n */ (m */ x).\nintros n m x; induction n; intros; auto.\nsimpl mult.\nrewrite (plus_Nmult_distr m (n * m) x).\nrewrite IHn; auto.\nQed.\n\nLemma Nmult_Unth_simpl_left : forall n x, (S n) */ ([1/]1+n * x) == x.\nintros.\nrewrite (Nmult_Umult_assoc_left (S n) ([1/]1+n) x (Nmult_def_Unth n)).\nrewrite (Nmult_Sn_Unth n); auto.\nQed.\n\nLemma Nmult_Unth_simpl_right : forall n x, (S n) */ (x * [1/]1+n) == x.\nintros.\nrewrite (Nmult_Umult_assoc_right (S n) x ([1/]1+n) (Nmult_def_Unth n)).\nrewrite (Nmult_Sn_Unth n); auto.\nQed.\n\nHint Resolve Nmult_Unth_simpl_left Nmult_Unth_simpl_right.\n\nLemma Uinv_Nmult : forall k n, [1-] (k */ [1/]1+n) == ((S n) - k)  */ [1/]1+n.\nintros k n; case (le_lt_dec (S n) k); intro.\nrewrite (Nmult_ge_Sn_Unth l).\nreplace (S n - k)%nat with O; auto.\nomega.\ninduction k; intros.\nrewrite Nmult_0; rewrite Uinv_zero.\nreplace (S n - O)%nat with (S n); auto with arith.\nrewrite (Nmult_S k ([1/]1+n)).\napply Uplus_eq_simpl_right with ([1/]1+n); auto.\napply Uinv_le_perm_right.\napply Nmult_le_n_Unth.\nomega.\napply Ueq_trans with (((S n - S k) + (S O)) */ [1/]1+n).\nreplace ((S n - S k) + (S O))%nat with (S n - k)%nat.\napply Ueq_trans with ([1-] (k */ [1/]1+n)); auto with arith.\napply Uinv_plus_left.\napply Nmult_le_n_Unth; omega.\nomega.\nrewrite (plus_Nmult_distr (S n - S k) (S O) ([1/]1+n)); auto.\nQed.\n\nLemma Nmult_neq_zero : forall n x, ~(0==x) -> ~(0==S n */ x).\nintros; rewrite (Nmult_S n x); auto.\napply Uplus_neq_zero_left; trivial.\nQed.\nHint Resolve Nmult_neq_zero.\n\n\nLemma Nmult_le_simpl :  forall (n:nat) (x y:U), \n   Nmult_def (S n) x -> Nmult_def (S n) y -> (S n */ x) <= (S n */ y) -> x <= y.\nintros; apply Umult_le_simpl_left with (S n */ [1/]1+n).\nauto.\nassert (Nmult_def (S n) ([1/]1+n)); auto.\nrewrite <- (Nmult_Umult_assoc_left (S n) ([1/]1+n) x H2).\nrewrite <- (Nmult_Umult_assoc_left (S n) ([1/]1+n) y H2).\nrewrite (Nmult_Umult_assoc_right (S n) ([1/]1+n) y H0).\nrewrite (Nmult_Umult_assoc_right (S n) ([1/]1+n) x H).\napply Ule_trans with ([1/]1+n * (S n */ x)); auto.\nQed.\n\nLemma Nmult_Unth_le : forall (n1 n2 m1 m2:nat), \n   (n2 * S n1<= m2 * S m1)%nat -> n2 */ [1/]1+m1 <= m2 */ [1/]1+n1.\nintros.\napply Ule_trans with ((n2 * S n1) */ ([1/]1+m1 * [1/]1+n1)).\nrewrite (Nmult_mult_assoc n2 (S n1) ([1/]1+m1 * [1/]1+n1)).\napply Nmult_le_compat_right.\nrewrite (Nmult_Unth_simpl_right n1 ([1/]1+m1)); auto.\napply Ule_trans with ((m2 * S m1) */ [1/]1+m1 * [1/]1+n1); auto.\nrewrite (Nmult_mult_assoc m2 (S m1) ([1/]1+m1 * [1/]1+n1)).\napply Nmult_le_compat_right.\nrewrite (Nmult_Unth_simpl_left m1 ([1/]1+n1)); auto.\nQed.\n\nLemma Nmult_Unth_eq : \n   forall (n1 n2 m1 m2:nat), \n   (n2 * S n1= m2 * S m1)%nat -> n2 */ [1/]1+m1 == m2 */ [1/]1+n1.\nintros.\napply Ueq_trans with ((n2 * S n1) */ ([1/]1+m1 * [1/]1+n1)).\nrewrite (Nmult_mult_assoc n2 (S n1) ([1/]1+m1 * [1/]1+n1)).\napply Nmult_eq_compat; trivial.\nrewrite (Nmult_Unth_simpl_right n1 ([1/]1+m1)); auto.\nrewrite H.\nrewrite (Nmult_mult_assoc m2 (S m1) ([1/]1+m1 * [1/]1+n1)).\napply Nmult_eq_compat; trivial.\nQed.\n\nHint Resolve Nmult_Unth_le Nmult_Unth_eq.\n\nLemma Nmult_def_lt : forall n x, n */ x <1 -> Nmult_def n x.\nred; destruct n; intros; auto.\napply (Ule_total x ([1/]1+n)); intros; auto.\ncase H.\napply Ule_trans with (S n */ [1/]1+n); auto.\nQed.\n\nHint Immediate Nmult_def_lt.\n\n(** ** Conversion from booleans to U *)\n\nDefinition B2U (b:bool) :U := if b then 1 else 0.\nDefinition NB2U (b:bool) :U := if b then 0 else 1.\n\nLemma B2Uinv : feq NB2U (finv B2U).\nunfold NB2U,feq,finv,B2U; intro b; case b; auto.\nQed.\n\nLemma NB2Uinv : feq B2U (finv NB2U).\nunfold NB2U,feq,finv,B2U; intro b; case b; auto.\nQed.\n\nHint Resolve B2Uinv NB2Uinv.\n\n(** ** Particular sequences *)\n  (**  $pmin (p)(n) = p - \\frac{1}{2^n}$ *)\n\nDefinition pmin (p:U) (n:nat) :=  p - ([1/2]^n).\n\nAdd Morphism pmin with signature Ueq ==> (@eq _) ==> Ueq as pmin_eq_compat.\nunfold pmin; auto.\nQed.\n\n(** *** Properties of the invariant *)\nLemma pmin_esp_S : forall p n, pmin (p & p) n == pmin p (S n) & pmin p (S n).\nunfold pmin at 1; intros.\nsetoid_rewrite (half_exp n).\nsetoid_rewrite (Uesp_minus_distr p p ([1/2]^(S n)) ([1/2]^(S n))); auto.\nQed.\n\nLemma pmin_esp_le : forall p n,  pmin p (S n) <= [1/2] * (pmin (p & p) n) + [1/2].\nintros; setoid_rewrite (pmin_esp_S p n); auto.\nQed.\n\nLemma pmin_plus_eq :  forall p n, p <= [1/2] -> pmin p (S n) == [1/2] * (pmin (p + p) n).\nintros; unfold pmin at 2.\nsetoid_rewrite (Uminus_distr_right [1/2] (p + p) ([1/2]^n)).\nsetoid_rewrite (half_twice H); auto.\nQed.\n\nLemma pmin_0 : forall p:U, pmin p O == 0.\nunfold pmin; simpl; auto.\nQed.\n\nLemma pmin_le : forall (p:U) (n:nat), p - ([1/]1+n) <= pmin p n.\nunfold pmin; intros.\napply Uminus_le_compat_right.\ninduction n; simpl; intros; auto.\napply Ule_trans with ([1/2] * ([1/]1+n)); auto.\nQed.\n\nHint Resolve pmin_0 pmin_le.\n\nLemma le_p_lim_pmin : forall p, p <= lub (pmin p).\nintro; apply Ule_lt_lim; intros.\nassert (exc (fun n : nat => t <= p - [1/]1+n)).\napply Ult_le_nth; trivial.\napply H0; auto; intros n H1.\napply Ule_trans with (p - [1/]1+n); auto.\napply Ule_trans with (pmin p n); auto.\nQed.\n\nLemma le_lim_pmin_p : forall p, lub (pmin p) <= p.\nintro; apply lub_le; unfold pmin; auto.\nQed.\nHint Resolve le_p_lim_pmin le_lim_pmin_p.\n\nLemma eq_lim_pmin_p : forall p, lub (pmin p) == p.\nintros; apply Ule_antisym; auto.\nQed.\n\nHint Resolve eq_lim_pmin_p.\n\n(** Particular case where p = 1 *)\n\nDefinition U1min := pmin 1.\n\nLemma eq_lim_U1min : lub U1min == 1.\nunfold U1min; auto.\nQed.\n\nLemma U1min_S : forall n, U1min (S n) == [1/2]*(U1min n) + [1/2].\nintros; unfold U1min at 2,pmin.\nrewrite (Uminus_distr_right [1/2] 1 ([1/2]^n)).\nrewrite Umult_one_right.\nrewrite Uminus_plus_perm; auto.\nrewrite Unth_one_plus; auto.\nQed.\n\nLemma U1min_0 : U1min O == 0.\nunfold U1min; auto.\nQed.\n\nHint Resolve eq_lim_U1min U1min_S U1min_0.\n\n(** ** Tactic for simplification of goals *)\n\nLtac Usimpl :=  match goal with \n    |- context [(Uplus 0 ?x)]     => setoid_rewrite (Uplus_zero_left x)\n |  |- context [(Uplus ?x 0)]     => setoid_rewrite (Uplus_zero_right x)\n |  |- context [(Uplus 1 ?x)]     => setoid_rewrite (Uplus_one_left x)\n |  |- context [(Uplus ?x 1)]     => setoid_rewrite (Uplus_one_right x)\n |  |- context [(Umult 0 ?x)]     => setoid_rewrite (Umult_zero_left x)\n |  |- context [(Umult ?x 0)]     => setoid_rewrite (Umult_zero_right x)\n |  |- context [(Umult 1 ?x)]     => setoid_rewrite (Umult_one_left x)\n |  |- context [(Umult ?x 1)]     => setoid_rewrite (Umult_one_right x)\n |  |- context [(Uesp 0 ?x)]     => setoid_rewrite (Uesp_zero_left x)\n |  |- context [(Uesp ?x 0)]     => setoid_rewrite (Uesp_zero_right x)\n |  |- context [(Uesp 1 ?x)]     => setoid_rewrite (Uesp_one_left x)\n |  |- context [(Uesp ?x 1)]     => setoid_rewrite (Uesp_one_right x)\n |  |- context [(Uminus 0 ?x)]    => setoid_rewrite (Uminus_le_zero 0 x); \n                                        [apply (Upos x)| idtac]\n |  |- context [(Uminus ?x 0)]    => setoid_rewrite (Uminus_zero_right x)\n |  |- context [(Uminus ?x 1)]    => setoid_rewrite (Uminus_le_zero x 1);\n                                        [apply (Unit x)| idtac]\n |  |- context [([1-] ([1-] ?x))] => setoid_rewrite (Uinv_inv x)\n |  |- context [([1-] 1)] => setoid_rewrite Uinv_one\n |  |- context [([1-] 0)] => setoid_rewrite Uinv_zero\n |  |- context [([1/]1+O)]        => setoid_rewrite Unth_zero\n |  |- context [?x^O] => setoid_rewrite (Uexp_0 x)\n |  |- context [?x^(S O)] => setoid_rewrite (Uexp_1 x)\n |  |- context [0^(?n)] => setoid_rewrite Uexp_zero; [omega|idtac]\n |  |- context [U1^(?n)] => setoid_rewrite Uexp_one\n |  |- context [(Nmult 0 ?x)]     => setoid_rewrite (Nmult_0 x)\n |  |- context [(Nmult 1 ?x)]     => setoid_rewrite (Nmult_1 x)\n |  |- context [(Nmult ?n 0)]     => setoid_rewrite (Nmult_zero n)\n |  |- context [(sigma ?f O)]     => setoid_rewrite (sigma_0 f)\n |  |- context [(sigma ?f (S O))]     => setoid_rewrite (sigma_1 f)\n |  |- (Ule (Uplus ?x ?y) (Uplus ?x ?z)) => apply Uplus_le_compat_right\n |  |- (Ule (Uplus ?x ?z) (Uplus ?y ?z)) => apply Uplus_le_compat_left\n |  |- (Ule (Uplus ?x ?z) (Uplus ?z ?y)) => setoid_rewrite (Uplus_sym z y); \n\t\t\t\t\t      apply Uplus_le_compat_left\n |  |- (Ule (Uplus ?x ?y) (Uplus ?z ?x)) => setoid_rewrite (Uplus_sym x y); \n                                              apply Uplus_le_compat_left\n |  |- (Ule (Uinv ?y) (Uinv ?x)) => apply Uinv_le_compat\n |  |- (Ule (Uminus ?x ?y) (Uplus ?x ?z)) => apply Uminus_le_compat_right\n |  |- (Ule (Uminus ?x ?z) (Uplus ?y ?z)) => apply Uminus_le_compat_left\n |  |- (Ueq (Uinv ?x) (Uinv ?y)) => apply Uinv_eq_compat\n |  |- (Ueq (Uplus ?x ?y) (Uplus ?x ?z)) => apply Uplus_eq_compat_right\n |  |- (Ueq (Uplus ?x ?z) (Uplus ?y ?z)) => apply Uplus_eq_compat_left\n |  |- (Ueq (Uplus ?x ?z) (Uplus ?z ?y)) => setoid_rewrite (Uplus_sym z y); \n                                             apply Uplus_eq_compat_left\n |  |- (Ueq (Uplus ?x ?y) (Uplus ?z ?x)) => setoid_rewrite (Uplus_sym x y); \n\t\t\t\t\t     apply Uplus_eq_compat_left\n |  |- (Ueq (Uminus ?x ?y) (Uplus ?x ?z)) => apply Uminus_eq_compat;[apply Ueq_refl|idtac]\n |  |- (Ueq (Uminus ?x ?z) (Uplus ?y ?z)) => apply Uminus_eq_compat;[idtac|apply Ueq_refl]\n |  |- (Ule (Umult ?x ?y) (Umult ?x ?z)) => apply Umult_le_compat_right\n |  |- (Ule (Umult ?x ?z) (Umult ?y ?z)) => apply Umult_le_compat_left\n |  |- (Ule (Umult ?x ?z) (Umult ?z ?y)) => setoid_rewrite (Umult_sym z y); \n                                             apply Umult_le_compat_left\n |  |- (Ule (Umult ?x ?y) (Umult ?z ?x)) => setoid_rewrite (Umult_sym x y); \n                                             apply Umult_le_compat_left\n |  |- (Ueq (Umult ?x ?y) (Umult ?x ?z)) => apply Umult_eq_compat_right\n |  |- (Ueq (Umult ?x ?z) (Umult ?y ?z)) =>  apply Umult_eq_compat_left\n |  |- (Ueq (Umult ?x ?z) (Umult ?z ?y)) => setoid_rewrite (Umult_sym z y); \n                                             apply Umult_eq_compat_left\n |  |- (Ueq (Umult ?x ?y) (Umult ?z ?x)) => setoid_rewrite (Umult_sym x y); \n                                             apply Umult_eq_compat_left\nend.\n\n(** ** Intervals *)\n\n(** *** Definition *)\nRecord IU : Type := mk_IU {low:U; up:U; proper:low <= up}.\n\nHint Resolve proper.\n\n(** the all set : [[0,1]] *)\nDefinition full := mk_IU (Upos 1).\n(** singleton : [[x]] *)\nDefinition singl (x:U) := mk_IU (Ule_refl x).\n(** down segment : [[0,x]] *)\nDefinition inf (x:U) := mk_IU (Upos x).\n(** up segment : [[x,1]] *)\nDefinition sup (x:U) := mk_IU (Unit x).\n\n(** *** Relations *)\nDefinition Iin (x:U) (I:IU) := low I <= x /\\ x <= up I.\n\nDefinition Iincl I J := low J <= low I /\\ up I <= up J.\n\nDefinition Ieq I J := low I == low J /\\ up I == up J.\nHint Unfold Iin Iincl Ieq.\n\n(** *** Properties *)\nLemma Iin_low : forall I, Iin (low I) I.\nauto.\nQed.\n\nLemma Iin_up : forall I, Iin (up I) I.\nauto.\nQed.\n\nHint Resolve Iin_low Iin_up.\n\nLemma Iin_singl_elim : forall x y, Iin x (singl y) -> x == y.\nunfold Iin; intuition (simpl; auto).\nQed.\n\n\nLemma Iin_inf_elim : forall x y, Iin x (inf y) -> x <= y.\nunfold Iin; intuition (simpl; auto).\nQed.\n\nLemma Iin_sup_elim : forall x y, Iin x (sup y) -> y <= x.\nunfold Iin; intuition (simpl; auto).\nQed.\n\nLemma Iin_singl_intro : forall x y, x == y -> Iin x (singl y).\nauto.\nQed.\n\nLemma Iin_inf_intro : forall x y, x <= y -> Iin x (inf y).\nauto.\nQed.\n\nLemma Iin_sup_intro : forall x y, y <= x -> Iin x (sup y).\nauto.\nQed.\n\nHint Immediate Iin_inf_elim Iin_sup_elim Iin_singl_elim.\nHint Resolve Iin_inf_intro Iin_sup_intro Iin_singl_intro.\n\nLemma Iin_class : forall I x, class (Iin x I).\nunfold class, Iin; split.\napply Ule_class; intuition.\napply Ule_class; intuition.\nQed.\n\nLemma Iincl_class : forall I J, class (Iincl I J).\nunfold class, Iincl; split.\napply Ule_class; intuition.\napply Ule_class; intuition.\nQed.\n\nLemma Ieq_class : forall I J, class (Ieq I J).\nunfold class, Ieq; split.\napply Ueq_class; intuition.\napply Ueq_class; intuition.\nQed.\nHint Resolve Iin_class Iincl_class Ieq_class.\n\nLemma Iincl_in : forall I J, Iincl I J -> forall x, Iin x I -> Iin x J.\nunfold Iin,Iincl; intuition.\napply Ule_trans with (low I); auto.\napply Ule_trans with (up I); auto.\nQed.\n\nLemma Iincl_low : forall I J, Iincl I J -> low J <= low I.\nunfold Iincl; intuition.\nQed.\n\nLemma Iincl_up : forall I J, Iincl I J -> up I <= up J.\nunfold Iincl; intuition.\nQed.\n\nHint Immediate Iincl_low Iincl_up.\n\nLemma Iincl_refl : forall I, Iincl I I.\nunfold Iincl; intuition.\nQed.\nHint Resolve Iincl_refl.\n\nLemma Iincl_trans : forall I J K, Iincl I J -> Iincl J K -> Iincl I K.\nunfold Iincl; intuition.\napply Ule_trans with (low J); auto.\napply Ule_trans with (up J); auto.\nQed.\n\nLemma Ieq_incl : forall I J, Ieq I J -> Iincl I J.\nunfold Ieq,Iincl; intuition.\nQed.\n\nLemma Ieq_incl_sym : forall I J, Ieq I J -> Iincl J I.\nunfold Ieq,Iincl; intuition.\nQed.\nHint Immediate Ieq_incl Ieq_incl_sym.\n\nLemma lincl_eq_compat : forall I J K L,\n     Ieq I J -> Iincl J K -> Ieq K L -> Iincl I L.\nintros; apply Iincl_trans with J; auto.\nintros; apply Iincl_trans with K; auto.\nQed.\n\nLemma lincl_eq_trans : forall I J K,\n     Iincl I J -> Ieq J K -> Iincl I K.\nintros; apply lincl_eq_compat with I J; auto.\nQed.\n\nLemma Ieq_incl_trans : forall I J K,\n     Ieq I J -> Iincl J K -> Iincl I K.\nintros; apply lincl_eq_compat with J K; auto.\nQed.\n\nLemma Iincl_antisym : forall I J, Iincl I J -> Iincl J I -> Ieq I J.\nunfold Iincl; intuition.\nQed.\nHint Immediate Iincl_antisym.\n\nLemma Ieq_refl : forall I, Ieq I I.\nunfold Ieq; auto.\nQed.\nHint Resolve Ieq_refl.\n\nLemma Ieq_sym : forall I J, Ieq I J -> Ieq J I.\nunfold Ieq; intuition.\nQed.\nHint Immediate Ieq_sym.\n\nLemma Ieq_trans : forall I J K, Ieq I J -> Ieq J K -> Ieq I K.\nunfold Ieq; intuition.\napply Ueq_trans with (low J); auto.\napply Ueq_trans with (up J); auto.\nQed.\n\nLemma Isingl_eq : forall x y, Iincl (singl x) (singl y) -> x==y.\nunfold Iincl, singl; intuition.\nQed.\nHint Immediate Isingl_eq.\n\nLemma Iincl_full : forall I, Iincl I full.\nunfold Iincl, full; intuition.\nQed.\nHint Resolve Iincl_full.\n\n(** *** Operations on intervals *)\n\nDefinition Iplus I J := mk_IU (Uplus_le_compat (proper I) (proper J)).\n\nLemma low_Iplus : forall I J, low (Iplus I J)=low I + low J.\ntrivial.\nQed.\n\nLemma up_Iplus : forall I J, up (Iplus I J)=up I + up J.\ntrivial.\nQed.\n\nLemma Iplus_in : forall I J x y, Iin x I -> Iin y J -> Iin (x+y) (Iplus I J).\nunfold Iin,Iplus; intuition (simpl; auto).\nQed.\n\nLemma lplus_in_elim : \nforall I J z, low I <= [1-]up J -> Iin z (Iplus I J) \n                -> exc (fun x => Iin x I /\\\n                                                   exc (fun y => Iin y J /\\ z==x+y)).\nintros I J z H (H1,H2); simpl in H1,H2; intros.\nassert (low I <= z).\napply Ule_trans with (low I + low J); auto.\napply (Ule_total (z-low I)  (up J)); intros.\napply class_exc.\n(* case [z-low I <= up j] *)\napply exc_intro with (low I); split; auto.\napply exc_intro with (z-low I); split; auto.\nassert (low I <= [1-]low J).\napply Ule_trans with ([1-]up J); auto.\nsplit; auto.\napply Uplus_le_perm_right; auto.\nrewrite Uplus_sym; auto.\n(* case [up j <= z-low I] *)\nassert (up J <= z); auto.\napply Ule_trans with (z - low I); auto.\napply exc_intro with (z-up J); split; auto.\nsplit; auto.\napply Uplus_le_perm_left; auto.\nrewrite Uplus_sym; auto.\napply exc_intro with (up J); auto.\nQed.\n\nDefinition Imult I J := mk_IU (Umult_le_compat (proper I) (proper J)).\n\nLemma low_Imult : forall I J, low (Imult I J) = low I * low J.\ntrivial.\nQed.\n\nLemma up_Imult : forall I J, up (Imult I J) = up I * up J.\ntrivial.\nQed.\n\n\nDefinition Imultk p I := mk_IU (Umult_le_compat_right p (proper I)).\n\nLemma low_Imultk : forall p I, low (Imultk p I) = p * low I.\ntrivial.\nQed.\n\nLemma up_Imultk : forall p I, up (Imultk p I) = p * up I.\ntrivial.\nQed.\n\nLemma Imult_in : forall I J x y, Iin x I -> Iin y J -> Iin (x*y) (Imult I J).\nunfold Iin; intuition (simpl; auto).\nQed.\n\nLemma Imultk_in : forall p I x , Iin x I -> Iin (p*x) (Imultk p I).\nunfold Iin; intuition (simpl; auto).\nQed.\n\n(** *** limits *)\n\nDefinition lim : forall I:nat->IU, (forall n, Iincl (I (S n)) (I n)) -> IU.\nintros; exists (lub (fun n => low (I n))) (glb (fun n => up (I n))).\nunfold glb; apply lub_inv; intros; auto.\nDefined.\n\nLemma low_lim : forall (I:nat->IU) (Idec : forall n, Iincl (I (S n)) (I n)),\n             low (lim I Idec) = lub (fun n => low (I n)).\ntrivial.\nQed.\n\nLemma up_lim : forall (I:nat->IU) (Idec : forall n, Iincl (I (S n)) (I n)),\n             up (lim I Idec) = glb (fun n => up (I n)).\ntrivial.\nQed.\n\nLemma lim_Iincl :  forall (I:nat->IU) (Idec : forall n, Iincl (I (S n)) (I n)),\n             forall n, Iincl (lim I Idec) (I n).\nunfold lim,Iincl; simpl; split.\napply le_lub with (f:=fun n0 : nat => low (I n0)).\napply glb_le with (f:=fun n0 : nat => up (I n0)).\nQed.\nHint Resolve lim_Iincl.\n\nLemma Iincl_lim :  forall J (I:nat->IU) (Idec : forall n, Iincl (I (S n)) (I n)),\n             (forall n, Iincl J (I n)) -> Iincl J (lim I Idec).\nunfold lim,Iincl; simpl; split.\napply lub_le with (f:=fun n0 : nat => low (I n0)); intro.\ncase (H n); auto.\napply le_glb with (f:=fun n0 : nat => up (I n0)); intro.\ncase (H n); auto.\nQed.\n\nLemma Iim_incl_stable : forall I J (Idec : forall n, Iincl (I (S n)) (I n)) \n               (Jdec : forall n, Iincl (J (S n)) (J n)), \n               (forall n, Iincl (I n) (J n)) -> Iincl (lim I Idec) (lim J Jdec).\nintros; apply Iincl_lim. \nintros; apply Iincl_trans with (I n); auto.\nQed.\nHint Resolve Iim_incl_stable.\n\n(** *** Fixpoints *)\nSection Ifixpoint.\nVariable A : Type.\nVariable F : (A -> IU) -> A -> IU.\nHypothesis Fmon : forall I J, (forall x, Iincl (I x) (J x)) -> forall x, Iincl (F I x) (F J x).\n\nFixpoint Iiter (n:nat) : A -> IU := \n     match n with O => fun x => full | S m => F (Iiter  m) end.\n\nLemma Iiter_decr : forall x n, Iincl (Iiter (S n) x) (Iiter n x).\nintros x n; generalize x; induction n; simpl; auto.\nQed.\nHint Resolve Iiter_decr.\n\nDefinition Ifix (x:A) := lim (fun n => Iiter n x) (Iiter_decr x).\n\nLemma Iincl_fix : forall (x:A), Iincl (F Ifix x) (Ifix x).\nunfold Ifix at 2; intros.\napply Iincl_lim.\ndestruct n; simpl; auto.\napply Fmon.\nunfold Ifix; intros.\napply (lim_Iincl (fun n0 : nat => Iiter n0 x0)).\nQed.\n\nLemma Iincl_inv : forall f, (forall x, Iincl (f x) (F f x)) -> forall x, Iincl (f x) (Ifix x).\nunfold Ifix; intros; apply Iincl_lim.\nintro n; generalize x; induction n; simpl; intros; auto.\napply Iincl_trans with (F f x0); auto.\nQed.\n\nEnd Ifixpoint.\nEnd Univ_prop.\n\n", "meta": {"author": "coq-contribs", "repo": "random", "sha": "e29ddb2860344bcaa750476ba26b786ee84afa4e", "save_path": "github-repos/coq/coq-contribs-random", "path": "github-repos/coq/coq-contribs-random/random-e29ddb2860344bcaa750476ba26b786ee84afa4e/Uprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.6626268748360772}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp\nRequire Import ssrbool ssrfun eqtype ssrnat seq choice fintype.\nFrom mathcomp\nRequire Import div path bigop prime finset fingroup.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** tentative formalization of the theorem V.3.1 of\n    [Arnaudies&Fraysse]\n    Arnaudies, J.M., Fraysse, H.: Cours de mathematiques 1, Algebre, Dunod Universite, 1987\n\n    to illustrate the Mathematiques Components library\n*)\n\n(** Sect. 2: Basics of Coq *)\n\nLemma andC :\n  forall P Q : Prop, P /\\ Q -> Q /\\ P.\nProof.\nmove=> P Q.\nby case.\nShow Proof.\n(*exact (fun P Q PandQ => match PandQ with\n  conj p q => conj q p end).*)\nQed.\n\nLemma andbC :\n  forall P Q : bool, andb P Q = true -> andb Q P = true.\nProof.\ncase.\n- by case.\n- by case.\n(*exact (fun P Q => match P with\n| true => match Q with\n          | true => id\n          | false => id\n          end\n| false => match Q with\n          | true => id\n          | false => id\n          end\n      end).*)\nQed.\n\n(** Sect. 5: Overview of Finite Groups *)\n\nLocal Open Scope group_scope.\n\nModule Sect5.\nSection sect5.\n\nVariable gT : finGroupType.\nVariables G : {group gT}.\nVariables g h : gT.\nHypotheses (gG : g \\in G) (hG : h \\in G).\nCheck g * h : gT.\nCheck groupM gG hG : g * h \\in G.\n\nEnd sect5.\nEnd Sect5.\n\nSection coset_bijection.\n\nVariable gT : finGroupType.\nVariables G H : {group gT}.\nHypothesis HG : H \\subset G.\n\n(** Sect. 6: Left-cosets are disjoint *)\n\nLemma coset_disjoint L0 L1 :\n  L0 \\in lcosets H G ->\n  L1 \\in lcosets H G ->\n  L0 :&: L1 != set0 -> L0 = L1.\nProof.\ncase/lcosetsP => g0 g0G ->{L0}.\ncase/lcosetsP => g1 g1G ->{L1}.\nmove=> g0_g1_disj.\napply/lcoset_eqP.\ncase/set0Pn : g0_g1_disj => /= g.\nrewrite in_setI => /andP[].\nrewrite 3!mem_lcoset => g_g0 g_g1.\nrewrite -(mul1g g0).\nrewrite -(mulgV g).\nrewrite 2!mulgA.\nrewrite -mulgA.\nrewrite groupM //.\nrewrite groupVl //.\nrewrite invMg.\nby rewrite invgK.\nQed.\n\n(** Sect. 7: Injection into the set of left-cosets *)\n\nDefinition reprs := repr @: lcosets H G.\n\nLemma mem_repr_coset x : x \\in G -> repr (x *: H) \\in G.\nProof.\nmove=> xG.\nrewrite /repr.\ncase: ifPn => // x1.\ncase: pickP => /=.\n  move=> g0.\n  case/lcosetP => g1 g1H ->.\n  rewrite groupM //.\n  by move/subsetP : (HG); apply.\nmove/(_ x).\nby rewrite lcoset_refl.\nQed.\n\nLemma repr_form x : x \\in G -> repr (x *: H) *: H = x *: H.\nProof.\nmove=> xG.\napply coset_disjoint.\n- apply/lcosetsP.\n  exists (repr (x *: H)) => //.\n  by apply mem_repr_coset.\n- apply/lcosetsP.\n  by exists x.\n- apply/set0Pn => /=.\n  exists (repr (x *: H)) => //.\n  rewrite in_setI.\n  rewrite lcoset_refl /=.\n  rewrite (mem_repr x) //.\n  by rewrite lcoset_refl.\nQed.\n\nLemma reprs_subset : reprs \\subset G.\nProof.\napply/subsetP => g.\ncase/imsetP => /= gs.\ncase/lcosetsP => g' g'H ->{gs} ->{g}.\nby rewrite mem_repr_coset.\nQed.\n\nLemma injective_coset :\n  {in reprs &, injective (fun g => g *: H)}.\nProof.\nmove=> /= g g' /imsetP[] /= L LHG gL.\nmove=> /imsetP[] /= K KHG g'K abs.\nsuff : L = K.\n  move=> LK.\n  rewrite LK in gL.\n  by rewrite gL g'K.\ncase/lcosetsP : LHG => g0 g0G g0L.\nrewrite {}g0L {L} in gL *.\ncase/lcosetsP : KHG => g1 g1G g1K.\nrewrite {}g1K {K} in g'K *.\nhave <- : g *: H = g0 *: H.\n  apply coset_disjoint.\n  - apply/lcosetsP.\n    exists g => //.\n    by rewrite gL mem_repr_coset.\n  - apply/lcosetsP.\n    by exists g0.\n  - apply/set0Pn.\n    exists (repr (g0 *: H)).\n    by rewrite !inE -gL lcoset_refl /= gL (mem_repr g0) // lcoset_refl.\nsuff : g' *: H = g1 *: H.\n  by move=> <-.\napply coset_disjoint => //.\n- apply/lcosetsP.\n  exists g' => //.\n  by rewrite g'K mem_repr_coset.\n- apply/lcosetsP.\n  by exists g1.\n- apply/set0Pn.\n  exists (repr (g1 *: H)).\n  by rewrite inE -g'K lcoset_refl /= g'K (mem_repr g1) // lcoset_refl.\nQed.\n\nLemma surjective_coset : (fun x => x *: H) @: reprs = lcosets H G.\nProof.\napply/eqP.\nrewrite eqEsubset.\napply/andP; split.\n- apply/subsetP => i.\n  case/imsetP => g.\n  case/imsetP => L HL ->{g} ->{i}.\n  apply/lcosetsP.\n  exists (repr L) => //.\n  case/lcosetsP : HL => x xG ->.\n  by apply mem_repr_coset.\n- apply/subsetP => i.\n  case/lcosetsP => x xG ->{i}.\n  apply/imsetP.\n  exists (repr (x *: H)).\n    rewrite /reprs.\n    apply/imsetP.\n    exists (x *: H) => //.\n    apply/lcosetsP.\n    by exists x.\n  by rewrite repr_form.\nQed.\n\nEnd coset_bijection.\n\n(** Sect. 8: Transitivity of the group index *)\n\nNotation \"#| G : H |\" := #| lcosets H G |.\n\nSection index.\n\nVariable gT : finGroupType.\nVariables G H K : {group gT}.\nHypotheses (HG : H \\subset G) (KG : K \\subset G) (HK : K \\proper H).\n\nLemma index_trans : #| G : K | = (#| G : H | * #| H : K |)%nat.\nProof.\nrewrite /=.\nset calG := reprs G H.\nhave calG_H_inj : {in calG &, injective (fun x => x *: H)}.\n  by apply: injective_coset HG.\nset calH := reprs H K.\nhave calH_K_inj : {in calH &, injective (fun x=> x *: K)}.\n  apply: injective_coset.\n  by move/proper_sub : HK.\npose phi := fun gh : gT * gT => let: (g, h) := gh in (g * h) *: K.\n(* [Arnaudies&Fraysse] injectivite de phi:\n   Si ghK = g'h'K avec g, g' \\in calG et h, h' \\in calH,\n   on en deduit g'^-1ghK = h'K \\proper H.\n   Donc g'^-1gH \\cap H n'est pas vide puisque h'K \\proper H\n   et h'K \\proper g'^-1gH, et puisque g'^-1gH et H sont deux classes\n   a gauche mod (H), necessairement g'^-1gH = H, d'ou gH = g'H,\n   d'ou g = g' puisque alpha est bijective.\n   On en deduit: hK = h'K, d'ou h = h' puisque beta est bijective,\n   et finalement (g,h)=(g'.h'). *)\nhave phi_injective : {in setX calG calH & , injective phi}.\n  case => g h.\n  rewrite inE /=.\n  case => g' h' /andP[gG hH].\n  rewrite /phi inE /= => /andP[g'G h'H] ghK.\n  have step1 : (g'^-1 * g * h) *: K = h' *: K.\n    move: ghK.\n    move/(congr1 (fun X => g'^-1 *: X)).\n    by rewrite -2!lcosetM !mulgA mulVg mul1g.\n  have step2 : h' *: K \\proper H.\n    apply/properP; split.\n      apply/subsetP => x.\n      case/lcosetP => x0 Hx0 ->.\n      rewrite groupM //.\n        by move/proper_sub : (HK) => /reprs_subset /subsetP; apply.\n      move/proper_sub : HK => /subsetP; by apply.\n    case/properP : HK => HK' [x xH xK].\n    exists (h' * x) => //.\n    rewrite groupM //.\n      by move/proper_sub : (HK) => /reprs_subset /subsetP; apply.\n    apply: contra xK.\n    case/lcosetP => x0 x0K.\n    by move/mulgI => ->.\n  have {step2}step3 : (g'^-1 * g *: H) :&: H != set0.\n    have step3 : h' *: K \\proper (g'^-1 * g) *: H.\n      rewrite -step1.\n      apply/properP; split.\n        rewrite sub_lcoset -lcosetM mulgA mulVg mul1g.\n        apply/subsetP => x.\n        case/lcosetP => x0 x0K ->.\n        rewrite groupM //.\n          by move/proper_sub : (HK) => /reprs_subset /subsetP; apply.\n        by move/proper_sub : HK => /subsetP; apply.\n      case/properP : HK => HK' [x xH xK].\n      exists ((g'^-1 * g) * (h * x)) => //.\n        rewrite mem_lcoset mulgA mulVg mul1g groupM //.\n        by move/proper_sub : (HK) => /reprs_subset /subsetP; apply.\n      rewrite mem_lcoset -(mulgA g'^-1 g (h * x)) (mulgA g h x).\n      by rewrite (mulgA g'^-1 (g * h) x) (mulgA g'^-1 g h) mulgA mulVg mul1g.\n    apply/set0Pn; exists h'.\n    rewrite in_setI.\n    apply/andP; split.\n      move/proper_sub/subsetP : step3; apply.\n      by rewrite mem_lcoset mulVg group1.\n    move/proper_sub/subsetP : step2; apply.\n    by rewrite mem_lcoset mulVg group1.\n  have {step3}step4 : (g'^-1 * g) *: H = H.\n    case/set0Pn : step3 => x.\n    rewrite in_setI.\n    case/andP.\n    case/lcosetP => x0 Hx0 -> Htmp.\n    rewrite lcoset_id //.\n    by rewrite -(mulg1 g) -(mulgV x0) !mulgA groupM // groupVl // invgK.\n  have {step4}step5 : g *: H = g' *: H.\n    by rewrite -{2}step4 -lcosetM mulgA mulgV mul1g.\n  have {step5}step6 : g = g'.\n    by apply calG_H_inj.\n  have step7 : h *: K = h' *: K.\n    by rewrite -step1 step6 mulVg mul1g.\n  have {step7}step8 : h = h'.\n    by apply calH_K_inj.\n  by rewrite step6 step8.\nhave calG_H_surj : (fun x => x *: H) @: calG = lcosets H G.\n  by apply surjective_coset.\nhave calH_K_surj : (fun x => x *: K) @: calH = lcosets K H.\n  apply surjective_coset.\n  by move/proper_sub : (HK); apply.\n(* [Arnaudies&Fraysse] surjectivite de phi:\n   Soit l \\in calG; alors lH \\in (G/H)_g.\n   On a donc un g \\in calG tel que lH = gH;\n   alors g^-1lH = H, donc g^-1l \\in H.\n   On a donc un h \\in calH tel que g^-1lK = hK.\n   On en deduit lK = ghK = phi(g, h). *)\nhave phi_surjective : phi @: (setX calG calH) = lcosets K G.\n  apply/eqP.\n  rewrite eqEsubset.\n  apply/andP; split; apply/subsetP => i.\n    case/imsetP => /=; case=> [x1 x2].\n    rewrite !inE /= => /andP[Hx1 Hx2] ->{i}.\n    apply/lcosetsP.\n    exists (x1 * x2) => //.\n    rewrite groupM //.\n      by move : (HG) => /reprs_subset /subsetP; apply.\n    move/subsetP : HG; apply.\n    apply/subsetP: x2 Hx2.\n    by apply/reprs_subset/proper_sub.\n  case/lcosetsP => l lG ->{i}.\n  apply/imsetP => /=.\n  have [g [gcalG gHlH]] : exists g, g \\in calG /\\ g *: H = l *: H.\n    exists (repr (l *: H)).\n    split.\n      apply/imsetP.\n      exists (l *: H) => //.\n      apply/lcosetsP.\n      by exists l.\n    by rewrite (repr_form HG).\n  have step1 : (g^-1 * l) *: H = H.\n    move/(congr1 (fun x => g^-1 *: x)) : gHlH.\n    by rewrite -!lcosetM mulVg lcoset1.\n  have {step1}step2 : g^-1 * l \\in H.\n    by rewrite -step1 lcoset_refl.\n  have [h [hcalH glKhK]] : exists h, h \\in calH /\\ (g^-1 * l) *: K = h *: K.\n    exists (repr ((g^-1 * l) *: K)).\n    split.\n      apply/imsetP.\n      exists ((g^-1 * l) *: K) => //.\n      apply/lcosetsP.\n      by exists (g^-1 * l).\n    rewrite (repr_form KG) // groupM // groupVl // invgK //.\n    by move: (reprs_subset HG) => /subsetP; apply.\n  exists (g, h).\n    by rewrite in_setX gcalG.\n  move/(congr1 (fun x => g *: x)) : glKhK.\n  by rewrite -!lcosetM mulgA mulgV mul1g => ->.\nrewrite -phi_surjective -calG_H_surj -calH_K_surj.\nrewrite (card_in_imset phi_injective) cardsX.\nby rewrite (card_in_imset calG_H_inj) (card_in_imset calH_K_inj).\nQed.\n\nEnd index.\n\n(* Sect. 9: Lagrange Theorem *)\n\nSection lagrange.\n\nVariable gT : finGroupType.\nVariables G H : {group gT}.\nHypotheses (HG : H \\subset G).\n\nLemma coset1 g : g *: (1%G : {group gT}) = [set g].\nProof.\napply/eqP; rewrite eqEsubset; apply/andP; split; apply/subsetP => j.\n  case/lcosetP => x.\n  rewrite !inE => /eqP ->.\n  by rewrite mulg1 => /eqP.\nrewrite in_set1 => /eqP ->.\napply/lcosetP.\nexists 1 => //.\nby rewrite mulg1.\nQed.\n\nLemma lcosets1 (K : {group gT}) : lcosets 1%G K = (set1) @: K.\nProof.\napply/eqP; rewrite eqEsubset; apply/andP; split; apply/subsetP => i.\n  case/lcosetsP => g gK ->{i}.\n  apply/imsetP.\n  exists g => //.\n  by apply coset1.\ncase/imsetP => g gK ->{i}.\napply/lcosetsP.\nexists g => //.\nby rewrite coset1.\nQed.\n\nTheorem Lagrange : #| G | = (#| H | * #| G : H |)%nat.\nProof.\ncase/boolP : (1%G \\proper H) => H1; last first.\n  suff -> : H = 1%G.\n    rewrite cards1 mul1n lcosets1 // card_imset //.\n    exact: set1_inj.\n  apply/trivGP.\n  move: H1.\n  by rewrite proper1G negbK => /eqP ->.\nhave G1 : 1%G \\subset G.\n  apply/subsetP => h.\n  by rewrite inE => /eqP ->.\nmove: (index_trans HG G1 H1).\nrewrite lcosets1 (card_imset _ set1_inj).\nrewrite mulnC lcosets1 card_imset //.\nexact: set1_inj.\nQed.\n\nEnd lagrange.\n", "meta": {"author": "affeldt", "repo": "mathcomp-intro", "sha": "9d8640bfe4a31c0b32e1ad672baf7eeface26288", "save_path": "github-repos/coq/affeldt-mathcomp-intro", "path": "github-repos/coq/affeldt-mathcomp-intro/mathcomp-intro-9d8640bfe4a31c0b32e1ad672baf7eeface26288/index.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.6626268676310644}}
{"text": "Require Import Com.\nRequire Import Big_Step.\nRequire Import Star.\nLocal Open Scope Z_scope.\n\nInductive instr :=\n| LOADI : Z -> instr\n| LOAD : vname -> instr\n| ADD : instr\n| STORE : vname -> instr\n| JMP : Z -> instr\n| JMPLESS : Z -> instr\n| JMPGE : Z -> instr.\n\nDefinition stack := list val.\nDefinition config : Set := Z * state * stack.\n\nDefinition iexec (ins : instr) (cfg : config) : config :=\n  match cfg with\n  | (i, s, stk) =>\n    match ins with\n    | LOADI n => (i + 1, s, n :: stk)\n    | LOAD x => (i + 1, s, s x :: stk)\n    | ADD => (i + 1, s, hd 0 (tl stk) + hd 0 stk :: tl (tl stk))\n    | STORE x => (i + 1, update s x (hd 0 stk), tl stk)\n    | JMP n => (i + 1 + n, s, stk)\n    | JMPLESS n => (if (hd 0 (tl stk)) <? hd 0 stk then i + 1 + n else i + 1, s, tl (tl stk))\n    | JMPGE n => (if (hd 0 (tl stk)) >=? hd 0 stk then i + 1 + n else i + 1, s, tl (tl stk))\n    end\n  end.\n\nDefinition size (P : list instr) := Z.of_nat (length P).\nDefinition znth {A} (n : Z) (l : list A) (x : A) := nth (Z.to_nat n) l x.\n\nDefinition exec1 (P : list instr) (c c' : config) : Prop :=\n  exists i s stk, c = (i,s,stk) /\\ c' = iexec (znth i P ADD) (i,s,stk)\n                  /\\ i >= 0 /\\ i < size P.\n\nDefinition exec P := star (exec1 P).\nHint Unfold exec : yhints.\n\nLemma lem_exec1I :\n  forall P i s stk c', c' = iexec (znth i P ADD) (i,s,stk) ->\n                       0 <= i -> i < size P ->\n                       exec1 P (i,s,stk) c'.\nProof.\n  Reconstr.hobvious Reconstr.Empty\n                    (@Coq.ZArith.BinInt.Z.lt_nge)\n                    (@Coq.ZArith.BinInt.Z.ge, @znth, @exec1, @Coq.ZArith.BinInt.Z.lt).\nQed.\n\n(* Helper instruction list functions *)\n\nLemma lem_n_succ_znth :\n  forall {A} n (a : A) xs x, 0 <= n -> znth (n + 1) (a :: xs) x = znth n xs x.\nProof.\n  induction n; sauto.\n  - Reconstr.htrivial Reconstr.AllHyps\n                      (@Coq.PArith.Pnat.Pos2Nat.inj_succ, @Coq.PArith.BinPos.Pos.add_1_r)\n                      Reconstr.Empty.\n  - Reconstr.htrivial Reconstr.AllHyps\n                      (@Coq.PArith.BinPos.Pos.add_1_r, @Coq.PArith.Pnat.Pos2Nat.inj_succ,\n                       @Coq.ZArith.Znat.Z2Nat.inj_pos, @Coq.Init.Peano.eq_add_S)\n                      (@znth).\nQed.\n\nLemma lem_znth_app :\n  forall xs ys i x, i >= 0 -> znth (size xs + i) (xs ++ ys) x = znth i ys x.\nProof.\n  assert (forall n (xs ys : list instr) i x, i >= 0 -> n = length xs ->\n                                             znth (Z.of_nat n + i) (xs ++ ys) x = znth i ys x);\n    [idtac | scrush].\n  induction n.\n  - scrush.\n  - assert (HH: Z.of_nat (S n) = Z.of_nat n + 1) by\n        Reconstr.htrivial Reconstr.Empty\n                          (@Coq.ZArith.Znat.Nat2Z.inj_succ)\n                          (@Coq.ZArith.BinIntDef.Z.succ).\n    rewrite HH; clear HH.\n    intros xs ys i x H1 H2.\n    assert (0 <= Z.of_nat n + i) by omega.\n    assert (HH: Z.of_nat n + 1 + i = (Z.of_nat n + i) + 1) by omega.\n    rewrite HH; clear HH.\n    destruct xs; [ scrush | simpl ].\n    rewrite lem_n_succ_znth by scrush.\n    scrush.\nQed.\n\nLemma lem_size_succ :\n  forall a xs, size (a :: xs) = size xs + 1.\nProof.\n  assert (forall n a xs, n = size xs -> size (a :: xs) = n + 1); [idtac | scrush].\n  induction n; sauto.\n  - scrush.\n  - Reconstr.htrivial Reconstr.AllHyps\n                      (@Coq.PArith.BinPos.Pplus_one_succ_r, @Coq.ZArith.Znat.Zpos_P_of_succ_nat,\n                       @Coq.ZArith.BinInt.Pos2Z.inj_succ)\n                      (@Coq.ZArith.BinIntDef.Z.succ, @size).\n  - scrush.\nQed.\n\nLemma lem_nth_append :\n  forall xs ys i x, 0 <= i ->\n                    znth i (xs ++ ys) x =\n                    (if i <? size xs then znth i xs x else znth (i - size xs) ys x).\nProof.\n  induction xs.\n  - sauto.\n    + Reconstr.hcrush Reconstr.AllHyps\n                  (@Coq.ZArith.BinInt.Z.ltb_ge)\n                  Reconstr.Empty.\n    + scrush.\n  - intros.\n    assert (HH: i = 0 \\/ exists i', i = i' + 1 /\\ 0 <= i') by\n        Reconstr.hcrush Reconstr.AllHyps\n                        (@Coq.ZArith.BinInt.Z.lt_le_pred, @Coq.ZArith.BinInt.Z.lt_eq_cases,\n                         @Coq.ZArith.BinInt.Z.succ_pred)\n                        (@Coq.ZArith.BinIntDef.Z.succ).\n    destruct HH as [ ? | HH ].\n    scrush.\n    destruct HH as [ i' HH ].\n    destruct HH.\n    subst; simpl.\n    repeat rewrite lem_n_succ_znth by scrush.\n    repeat rewrite lem_size_succ.\n    sauto.\n    + assert ((i' <? size xs) = true).\n      Reconstr.hcrush Reconstr.AllHyps\n                      (@Coq.ZArith.BinInt.Z.le_gt_cases, @Coq.Bool.Bool.diff_true_false,\n                       @Coq.ZArith.BinInt.Z.ltb_ge, @Coq.ZArith.Zbool.Zlt_is_lt_bool,\n                       @Coq.ZArith.BinInt.Z.add_le_mono_r)\n                      (@size).\n      scrush.\n    + assert ((i' <? size xs) = false).\n      Reconstr.heasy Reconstr.AllHyps\n                     (@Coq.ZArith.BinInt.Z.ltb_nlt, @Coq.ZArith.BinInt.Z.add_lt_mono_r)\n                     (@size).\n      assert (i' + 1 - (size xs + 1) = i' - size xs) by auto with zarith.\n      scrush.\nQed.\n\nLemma lem_size_app : forall xs ys, size (xs ++ ys) = size xs + size ys.\nProof.\n  Reconstr.htrivial Reconstr.Empty\n                    (@Coq.ZArith.Znat.Nat2Z.inj_add, @Coq.Lists.List.app_length)\n                    (@size).\nQed.\n\nLemma lem_size_app_le : forall xs ys, size xs <= size (xs ++ ys).\nProof.\n  Reconstr.hobvious Reconstr.Empty\n                    (@Coq.Arith.Plus.le_plus_l, @Coq.ZArith.Znat.Nat2Z.inj_le, @Coq.Lists.List.app_length)\n                    (@size).\nQed.\n\n(* Verification infrastructure *)\n\nLemma lem_iexec_shift :\n  forall x n i i' s s' stk stk',\n    (n+i',s',stk') = iexec x (n+i,s,stk) <->\n    (i',s',stk') = iexec x (i,s,stk).\nProof.\n  split; intro H.\n  - assert (forall n i i' k, n + i' = n + i + k -> i' = i + k) by auto with zarith.\n    assert (forall n i i' k, n + i' = n + i + 1 + k -> i' = i + 1 + k) by auto with zarith.\n    scrush.\n  - assert (forall n i i' k, i' = i + k -> n + i' = n + i + k) by auto with zarith.\n    assert (forall n i, n + (i + 1) = n + i + 1) by auto with zarith.\n    scrush. (* takes 25s *)\nQed.\n\nLemma lem_exec1_hlp1 :\n  forall n P P', 0 <= n -> n < size P ->\n                 znth n P ADD = znth n (P ++ P') ADD.\nProof.\n  induction n.\n  - scrush.\n  - Reconstr.hcrush Reconstr.Empty\n                    (@lem_size_succ, @lem_nth_append, @Coq.ZArith.Zbool.Zlt_is_lt_bool)\n                    Reconstr.Empty.\n  - scrush.\nQed.\n\nLemma lem_exec1_appendR :\n  forall P P' c c', exec1 P c c' -> exec1 (P ++ P') c c'.\nProof.\n  unfold exec1.\n  intros; simp_hyps.\n  exists i.\n  exists s.\n  exists stk.\n  rewrite <- lem_exec1_hlp1 by auto with zarith.\n  assert (i < size (P ++ P')) by\n      Reconstr.heasy Reconstr.AllHyps\n                     (@lem_size_app_le, @Coq.ZArith.BinInt.Z.le_lt_trans,\n                      @Coq.ZArith.BinInt.Z.nle_gt, @Coq.ZArith.BinInt.Z.lt_ge_cases)\n                     (@size).\n  scrush.\nQed.\n\nLemma lem_exec_appendR : forall P P' c c', exec P c c' -> exec (P ++ P') c c'.\nProof.\n  unfold exec.\n  intros P P' c c' H.\n  induction H.\n  - scrush.\n  - pose @star_step; pose lem_exec1_appendR; scrush.\nQed.\n\nLemma lem_exec1_appendL :\n  forall i i' P P' s s' stk stk', exec1 P (i,s,stk) (i',s',stk') ->\n                                  exec1 (P' ++ P) (size P' + i,s,stk) (size P' + i',s',stk').\nProof.\n  unfold exec1.\n  intros; simp_hyps.\n  exists (size P' + i0).\n  exists s0.\n  exists stk0.\n  rewrite lem_znth_app by scrush.\n  split; [ scrush | split ].\n  - Reconstr.htrivial Reconstr.AllHyps\n                      (@lem_iexec_shift)\n                      Reconstr.Empty.\n  - split.\n    + Reconstr.hobvious Reconstr.AllHyps\n                        (@Coq.ZArith.Zorder.Zle_0_nat, @Coq.ZArith.BinInt.Z.nle_gt,\n                         @Coq.ZArith.BinInt.Z.add_neg_cases)\n                        (@size, @Coq.ZArith.BinInt.Z.ge, @Coq.ZArith.BinInt.Z.lt).\n    + Reconstr.hobvious Reconstr.AllHyps\n                        (@lem_size_app, @Coq.ZArith.BinInt.Z.add_lt_mono_l)\n                        (@size).\nQed.\n\nLemma lem_exec_appendL :\n  forall i i' P P' s s' stk stk', exec P (i,s,stk) (i',s',stk') ->\n                                  exec (P' ++ P) (size P' + i,s,stk) (size P' + i',s',stk').\nProof.\n  assert (forall c c' P, exec P c c' ->\n                       forall i i' P' s s' stk stk',\n                         c = (i,s,stk) -> c' = (i',s',stk') ->\n                         exec (P' ++ P) (size P' + i,s,stk) (size P' + i',s',stk')); [idtac|scrush].\n  unfold exec.\n  intros c c' P H.\n  induction H.\n  - scrush.\n  - intros; simp_hyps; subst.\n    destruct y as [ p stk0 ].\n    destruct p as [ i0 s0 ].\n    pose @star_step; pose lem_exec1_appendL; scrush.\nQed.\n\nLemma lem_exec_Cons_1 :\n  forall ins P j s t stk stk',\n    exec P (0,s,stk) (j,t,stk') ->\n    exec (ins :: P) (1,s,stk) (1+j,t,stk').\nProof.\n  intros ins P j.\n  assert (HH: ins :: P = (ins :: nil) ++ P) by auto with datatypes.\n  rewrite HH; clear HH.\n  assert (HH: 1 + j = size (ins :: nil) + j) by scrush.\n  rewrite HH; clear HH.\n  assert (HH: 1 = size (ins :: nil) + 0) by scrush.\n  rewrite HH; clear HH.\n  pose lem_exec_appendL; scrush.\nQed.\n\nLemma lem_exec_appendL_if :\n  forall i i' j P P' s s' stk stk',\n    size P' <= i -> exec P (i - size P',s,stk) (j,s',stk') -> i' = size P' + j ->\n    exec (P' ++ P) (i,s,stk) (i',s',stk').\nProof.\n  intros.\n  pose (k := i - size P').\n  assert (HH: i = size P' + k) by\n      Reconstr.htrivial Reconstr.Empty\n                        (@Coq.ZArith.BinInt.Zplus_minus)\n                        (@k).\n  rewrite HH; clear HH.\n  pose lem_exec_appendL; scrush.\nQed.\n\nLemma lem_exec_append_trans :\n  forall i' i'' j'' P P' s s' s'' stk stk' stk'',\n    exec P (0,s,stk) (i',s',stk') -> size P <= i' ->\n    exec P' (i' - size P,s',stk') (i'',s'',stk'') ->\n    j'' = size P + i'' ->\n    exec (P ++ P') (0,s,stk) (j'',s'',stk'').\nProof.\n  intros.\n  assert (exec (P ++ P') (i',s',stk') (j'',s'',stk'')) by\n      (apply lem_exec_appendL_if with (j := i''); sauto).\n  assert (exec (P ++ P') (0,s,stk) (i',s',stk')) by\n      (apply lem_exec_appendR; sauto).\n  pose @lem_star_trans; scrush.\nQed.\n\nLtac escrush := unfold exec; pose @star_step; pose @star_refl; scrush.\n\nLtac exec_tac :=\n  match goal with\n  | [ |- exec ?A (?i, ?s, ?stk) ?B ] =>\n    assert (exec1 A (i, s, stk) B) by\n        (unfold exec1; exists i; exists s; exists stk; sauto);\n    escrush\n  end.\n\nLtac exec_append_tac :=\n  intros; assert (H_exec_append_tac: forall l, size l - size l = 0) by (intro; omega);\n  match goal with\n  | [ |- exec (?l1 ++ ?l2) (0,?s,?stk) (size(?l1 ++ ?l2), ?s, ?a :: ?b :: ?stk) ] =>\n    rewrite lem_size_app;\n    apply lem_exec_append_trans with\n    (i' := size(l1)) (i'' := size(l2)) (s' := s) (stk' := b :: stk);\n    solve [ omega | ycrush | scrush ]\n  | [ H1 : exec ?l1 (0,?s,?stk) (size(?l1), ?s1, ?stk1),\n      H2 : exec ?l2 (0,?s1,?stk1) (size(?l2), ?s2, ?stk2)\n      |- exec (?l1 ++ ?l2) (0,?s,?stk) (size(?l1 ++ ?l2), ?s2, ?stk2) ] =>\n    rewrite lem_size_app;\n    apply lem_exec_append_trans with\n    (i' := size(l1)) (i'' := size(l2)) (s' := s1) (stk' := stk1);\n    solve [ omega | ycrush | scrush ]\n  | [ H1 : exec ?l1 (0,?s,?stk) (size(?l1), ?s1, ?stk1),\n      H2 : exec ?l2 (0,?s1,?stk1) (size(?l2) + ?i, ?s2, ?stk2)\n      |- exec (?l1 ++ ?l2) (0,?s,?stk) (size(?l1 ++ ?l2) + ?i, ?s2, ?stk2) ] =>\n    rewrite lem_size_app;\n    apply lem_exec_append_trans with\n    (i' := size(l1)) (i'' := size(l2) + i) (s' := s1) (stk' := stk1);\n    solve [ omega | ycrush | scrush ]\n  end;\n  clear H_exec_append_tac.\n\nLtac exec_append3_tac :=\n  intros;\n  match goal with\n  | [ H2: exec ?l2 (0,?s1,?stk1) (size(?l2),?s2,?stk2),\n      H3: exec ?l3 (0,?s2,?stk2) (size(?l3),?s3,?stk3)\n      |- exec (?l1 ++ ?l2 ++ ?l3) (0,?s,?stk) (size(?l1 ++ ?l2 ++ ?l3), ?s3, ?stk3) ] =>\n    assert (exec (l2 ++ l3) (0,s1,stk1) (size(l2 ++ l3),s3,stk3)) by exec_append_tac;\n    exec_append_tac\n  | [ H2: exec ?l2 (0,?s1,?stk1) (size(?l2),?s2,?stk2),\n      H3: exec ?l3 (0,?s2,?stk2) (size(?l3) + ?i,?s3,?stk3)\n      |- exec (?l1 ++ ?l2 ++ ?l3) (0,?s,?stk) (size(?l1 ++ ?l2 ++ ?l3) + ?i, ?s3, ?stk3) ] =>\n    assert (exec (l2 ++ l3) (0,s1,stk1) (size(l2 ++ l3) + i,s3,stk3)) by exec_append_tac;\n    exec_append_tac\n  end.\n\n(* Compilation *)\n\nFixpoint acomp (a : aexpr) : list instr :=\n  match a with\n  | Anum n => LOADI n :: nil\n  | Avar x => LOAD x :: nil\n  | Aplus a1 a2 => acomp a1 ++ acomp a2 ++ (ADD :: nil)\n  end.\n\nLemma lem_acomp_correct :\n  forall a s stk, exec (acomp a) (0, s, stk) (size(acomp a), s, aval s a :: stk).\nProof.\n  induction a; sauto.\n  - exec_tac.\n  - exec_tac.\n  - assert (exec (acomp a1 ++ acomp a2) (0,s,stk)\n                 (size(acomp a1 ++ acomp a2),s,aval s a2 :: aval s a1 :: stk)) by exec_append_tac.\n    assert (exec (ADD :: nil) (0,s,aval s a2 :: aval s a1 :: stk) (1,s,(aval s a1 + aval s a2) :: stk)) by\n        exec_tac.\n    assert (forall l, size l - size l = 0) by (intro; omega);\n    assert (HH: exec ((acomp a1 ++ acomp a2) ++ ADD :: nil) (0, s, stk)\n                     (size ((acomp a1 ++ acomp a2) ++ ADD :: nil), s, aval s a1 + aval s a2 :: stk)) by\n        (apply lem_exec_append_trans with\n         (i' := size(acomp a1 ++ acomp a2)) (s' := s) (stk' := aval s a2 :: aval s a1 :: stk) (i'' := 1);\n         solve [ sauto | ycrush | rewrite lem_size_app; scrush ]).\n    clear -HH; scrush.\nQed.\n\nLemma lem_acomp_append :\n   forall a1 a2 s stk, exec (acomp a1 ++ acomp a2) (0, s, stk)\n                            (size (acomp a1 ++ acomp a2), s, aval s a2 :: aval s a1 :: stk).\nProof.\n  pose lem_acomp_correct; exec_append_tac.\nQed.\n\nFixpoint bcomp (b : bexpr) (f : bool) (n : Z) : list instr :=\n  match b with\n  | Bval v => if eqb v f then JMP n :: nil else nil\n  | Bnot b' => bcomp b' (negb f) n\n  | Band b1 b2 =>\n    let cb2 := bcomp b2 f n in\n    let m := if f then size cb2 else size cb2 + n in\n    let cb1 := bcomp b1 false m in\n    cb1 ++ cb2\n  | Bless a1 a2 =>\n    acomp a1 ++ acomp a2 ++ (if f then JMPLESS n :: nil else JMPGE n :: nil)\n  end.\n\nLemma lem_bcomp_correct :\n  forall b f n s stk, 0 <= n ->\n                      exec (bcomp b f n) (0,s,stk)\n                           (size(bcomp b f n) + (if eqb f (bval s b) then n else 0),s,stk).\nProof.\n  induction b; simpl; intros f n s stk H.\n  - sauto; try exec_tac;\n      Reconstr.hsimple Reconstr.AllHyps\n                       (@Coq.Bool.Bool.eqb_false_iff, @Coq.Bool.Bool.eqb_prop)\n                       Reconstr.Empty.\n  - assert (HH: (if eqb f (negb (bval s b)) then n else 0) =\n                (if eqb (negb f) (bval s b) then n else 0)) by\n        Reconstr.hsimple Reconstr.Empty\n                         (@Coq.Bool.Bool.eqb_negb2, @Coq.Bool.Bool.negb_false_iff,\n                          @Coq.Bool.Bool.negb_true_iff, @Coq.Bool.Bool.no_fixpoint_negb,\n                          @Coq.Bool.Bool.negb_involutive, @Coq.Bool.Bool.diff_true_false,\n                          @Coq.Bool.Bool.eqb_false_iff, @Coq.Bool.Bool.eqb_prop)\n                         (@Coq.Bool.Bool.eqb, @Coq.Init.Datatypes.negb).\n    rewrite HH; clear HH.\n    scrush.\n  - pose (m := if f then size (bcomp b2 f n) else size (bcomp b2 f n) + n); fold m.\n    assert (H0: 0 <= m) by\n        (unfold m; clear -H; sauto; unfold size; omega).\n    destruct (bval s b1) eqn:H1; simpl.\n    + apply lem_exec_append_trans with\n      (i' := size (bcomp b1 false m))\n        (s' := s) (stk' := stk)\n        (i'' := size (bcomp b2 f n) + (if eqb f (bval s b2) then n else 0)).\n      * generalize (IHb1 false m s stk); scrush.\n      * auto with zarith.\n      * assert (HH: size (bcomp b1 false m) - size (bcomp b1 false m) = 0) by omega.\n        rewrite HH; clear HH.\n        auto.\n      * rewrite lem_size_app; auto with zarith.\n    + rewrite lem_size_app.\n      assert (HH: size (bcomp b2 f n) + (if eqb f false then n else 0) = m) by\n          (unfold m; destruct f; simpl; omega).\n      rewrite <- ZArith.BinInt.Z.add_assoc; rewrite HH; clear HH.\n      apply lem_exec_appendR.\n      assert (HH: size (bcomp b1 false m) + m =\n                  size (bcomp b1 false m) + if eqb false (bval s b1) then m else 0) by scrush.\n      rewrite HH; clear HH.\n      auto.\n  - assert (HH: aval s a >=? aval s a0 = negb (aval s a <? aval s a0)) by\n        Reconstr.htrivial Reconstr.Empty\n                          (@Coq.ZArith.BinInt.Z.geb_leb, @Coq.Bool.Bool.negb_true_iff,\n                           @Coq.ZArith.BinInt.Z.leb_antisym)\n                          Reconstr.Empty.\n    assert (exec (if f then JMPLESS n :: nil else JMPGE n :: nil) (0, s, aval s a0 :: aval s a :: stk)\n                 (size (if f then JMPLESS n :: nil else JMPGE n :: nil) +\n                  (if eqb f (aval s a <? aval s a0) then n else 0), s, stk)) by\n        (sauto; exec_tac).\n    clear HH.\n    assert (HH: forall (l1 l2 l3 : list instr), l1 ++ l2 ++ l3 = (l1 ++ l2) ++ l3) by scrush.\n    repeat rewrite HH; clear HH.\n    pose proof (lem_acomp_append a a0 s stk).\n    exec_append_tac.\nQed.\n\nFixpoint ccomp (c : com) : list instr :=\n  match c with\n  | Skip => nil\n  | Assign x a => acomp a ++ STORE x :: nil\n  | Seq c1 c2 => ccomp c1 ++ ccomp c2\n  | If b c1 c2 =>\n    let cc1 := ccomp c1 in\n    let cc2 := ccomp c2 in\n    let cb := bcomp b false (size cc1 + 1) in\n    cb ++ cc1 ++ JMP (size cc2) :: cc2\n  | While b c0 =>\n    let cc := ccomp c0 in\n    let cb := bcomp b false (size cc + 1) in\n    cb ++ cc ++ JMP (-(size cb + size cc + 1)) :: nil\n  end.\n\n(* Preservation of semantics *)\n\nRequire Import Program.Equality.\n\nLtac assert_exec_bcomp_tac :=\n  intros;\n  match goal with\n  | [ H0: bval ?s ?b = ?B |- exec ((bcomp ?b false ?k) ++ ?l) (0,?s,?stk) ?c ] =>\n    let n := fresh \"n\" in\n    let H := fresh \"H\" in\n    pose (n := k); fold n;\n    assert (H: exec (bcomp b false n) (0, s, stk)\n                    (size (bcomp b false n) + if eqb false (bval s b) then n else 0, s, stk)) by\n        (apply lem_bcomp_correct;\n         Reconstr.hyelles 4 Reconstr.Empty\n                          (@Coq.ZArith.BinInt.Z.pred_succ, @Coq.ZArith.BinInt.Z.lt_le_incl,\n                           @Coq.ZArith.BinInt.Z.lt_le_pred, @Coq.ZArith.Zorder.Zle_0_nat)\n                          (@Coq.ZArith.BinIntDef.Z.succ, @size, @n);\n         Reconstr.htrivial Reconstr.AllHyps\n                           (@Coq.ZArith.BinInt.Z.lt_succ_r)\n                           (@Coq.ZArith.BinIntDef.Z.succ, @size, @n));\n    rewrite H0 in H; cbn in H; autorewrite with yhints in H\n  end.\n\nLemma lem_ccomp_bigstep :\n  forall c s t, (c, s) ==> t -> forall stk, exec (ccomp c) (0, s, stk) (size (ccomp c), t, stk).\nProof.\n  intros c s t H.\n  dependent induction H; intro stk; sauto.\n  - assert (exec (STORE x :: nil) (0, s, (aval s a) :: stk)\n                 (size (STORE x :: nil), update s x (aval s a), stk)) by\n        exec_tac.\n    assert (exec (acomp a) (0, s, stk) (size (acomp a), s, aval s a :: stk)) by\n        Reconstr.hobvious Reconstr.Empty (@lem_acomp_correct) Reconstr.Empty.\n    exec_append_tac.\n  - assert (exec (ccomp c1) (0, s, stk) (size (ccomp c1), s2, stk)) by scrush.\n    assert (exec (ccomp c2) (0, s2, stk) (size (ccomp c2), s3, stk)) by scrush.\n    exec_append_tac.\n  - assert_exec_bcomp_tac.\n    assert (exec (ccomp c1) (0, s, stk) (size (ccomp c1), s', stk)) by scrush.\n    assert (exec (JMP (size (ccomp c2)) :: ccomp c2) (0, s', stk)\n                 (size (JMP (size (ccomp c2)) :: ccomp c2), s', stk)) by\n        (rewrite lem_size_succ; exec_tac).\n    exec_append3_tac.\n  - assert_exec_bcomp_tac.\n    assert (exec (ccomp c2) (0, s, stk) (size (ccomp c2), s', stk)) by scrush.\n    assert (exec (bcomp b false n ++ ccomp c1 ++ JMP (size (ccomp c2)) :: nil) (0, s, stk)\n                 (size (bcomp b false n ++ ccomp c1 ++ JMP (size (ccomp c2)) :: nil), s, stk)) by\n        (unfold n in *; repeat rewrite lem_size_app; pose lem_exec_appendR; scrush).\n    assert (exec ((bcomp b false n ++ ccomp c1 ++ JMP (size (ccomp c2)) :: nil) ++ ccomp c2) (0, s, stk)\n                 (size ((bcomp b false n ++ ccomp c1 ++ JMP (size (ccomp c2)) :: nil) ++ ccomp c2),\n                  s', stk)) by\n        exec_append_tac.\n    scrush.\n  - assert_exec_bcomp_tac.\n    repeat rewrite lem_size_app; sauto;\n    apply lem_exec_appendR; unfold n in H0; scrush.\n  - assert_exec_bcomp_tac.\n    assert (exec (ccomp c0) (0, s, stk) (size (ccomp c0), s2, stk)) by scrush.\n    assert (HH1: exec (ccomp (While b c0)) (0, s2, stk) (size (ccomp (While b c0)), s3, stk)) by scrush.\n    cbn in HH1; fold n in HH1.\n    pose (k := size (bcomp b false n) + size (ccomp c0)); fold k; fold k in HH1.\n    assert (exec (JMP (-(k+1)) :: nil) (0, s2, stk) (-k, s2, stk)) by\n        (assert (1 + -(k+1) = -k) by omega; exec_tac).\n    assert (Heq: size (JMP (-(k+1)) :: nil) + -(k+1) = -k) by\n        (assert (Hs: size (JMP (-(k+1)) :: nil) = 1) by scrush; rewrite Hs; omega).\n    assert (exec (JMP (-(k+1)) :: nil) (0, s2, stk) (size (JMP (-(k+1)) :: nil) + -(k+1), s2, stk)) by\n        (rewrite Heq; assumption).\n    assert (HH2: exec (bcomp b false n ++ ccomp c0 ++ JMP (- (k + 1)) :: nil) (0, s, stk)\n                     (size (bcomp b false n ++ ccomp c0 ++ JMP (- (k + 1)) :: nil) + -(k+1), s2, stk)) by\n        exec_append3_tac.\n    repeat rewrite lem_size_app in HH2.\n    assert (Heq2: size (bcomp b false n) +\n                  (size (ccomp c0) + size (JMP (- (k + 1)) :: nil)) + -(k+1) = 0) by\n        (rewrite Zplus_assoc; rewrite Zplus_assoc_reverse; rewrite Heq; unfold k; omega).\n    rewrite Heq2 in HH2; clear Heq2.\n    clear -HH1 HH2.\n    unfold exec in *; pose @lem_star_trans; scrush.\nQed.\n", "meta": {"author": "lukaszcz", "repo": "COQ-IMP", "sha": "2caaab1d568be095c6a35de778146310e6542f02", "save_path": "github-repos/coq/lukaszcz-COQ-IMP", "path": "github-repos/coq/lukaszcz-COQ-IMP/COQ-IMP-2caaab1d568be095c6a35de778146310e6542f02/Compiler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.662592017648808}}
{"text": "(** DEC Library Coq Implementation *)\n\nFrom Coq Require ZArith.\n\nModule Export Inequalities.\n\nSet Warnings \"-undo-batch-mode\".\n\nImport ZArith Z.\n\nOpen Scope Z_scope.\n\nNotation \"'(|' x '|)'\" := (abs x).\n\nLemma le_refl : forall x : Z,\n  x <= x.\nProof.\n  intros x. apply le_refl. Qed.\n\nCorollary le_refl_add : forall x y : Z,\n  x + y <= x + y.\nProof. intros x y. apply le_refl. Qed.\n\nCorollary le_refl_sub : forall x y : Z,\n  x - y <= x - y.\nProof. intros x y. apply le_refl. Qed.\n\nCorollary le_refl_abs_add : forall x y : Z,\n  (|x + y|) <= (|x + y|).\nProof. intros x y. apply le_refl. Qed.\n\nCorollary le_refl_abs_sub : forall x y : Z,\n  (|x - y|) <= (|x - y|).\nProof. intros x y. apply le_refl. Qed.\n\nCorollary le_refl_add_abs : forall x y : Z,\n  (|x|) + (|y|) <= (|x|) + (|y|).\nProof. intros x y. apply le_refl. Qed.\n\nCorollary le_refl_sub_abs : forall x y : Z,\n  (|x|) - (|y|) <= (|x|) - (|y|).\nProof. intros x y. apply le_refl. Qed.\n\nCorollary le_refl_abs_add_abs : forall x y : Z,\n  (|(|x|) + (|y|)|) <= (|(|x|) + (|y|)|).\nProof. intros x y. apply le_refl. Qed.\n\nCorollary le_refl_abs_sub_abs : forall x y : Z,\n  (|(|x|) - (|y|)|) <= (|(|x|) - (|y|)|).\nProof. intros x y. apply le_refl. Qed.\n\nLemma le_abs : forall x : Z,\n  x <= (|x|).\nProof.\n  intros x. apply abs_le. apply le_refl. Qed.\n\nCorollary le_abs_add : forall x y : Z,\n  x + y <= (|x + y|).\nProof. intros x y. apply le_abs. Qed.\n\nCorollary le_abs_sub : forall x y : Z,\n  x - y <= (|x - y|).\nProof. intros x y. apply le_abs. Qed.\n\nCorollary le_abs_add_abs : forall x y : Z,\n  (|x|) + (|y|) <= (|(|x|) + (|y|)|).\nProof. intros x y. apply le_abs. Qed.\n\nCorollary le_abs_sub_abs : forall x y : Z,\n  (|x|) - (|y|) <= (|(|x|) - (|y|)|).\nProof. intros x y. apply le_abs. Qed.\n\nTheorem abs_triangle : forall x y : Z,\n  (|x + y|) <= (|x|) + (|y|).\nProof.\n  intros x y.\n  destruct (abs_spec (x + y)) as [[_ Hexy] | [_ Hexy]].\n  - rewrite Hexy. destruct (abs_spec x) as [[_ Hex] | [_ Hex]].\n    + rewrite Hex.\n      apply add_le_mono_l. apply le_abs.\n    + destruct (abs_spec y) as [[_ Hey] | [_ Hey]].\n      * rewrite Hey. apply add_le_mono_r. apply le_abs.\n      * apply add_le_mono.\n        -- apply le_abs.\n        -- apply le_abs.\n  - rewrite Hexy. destruct (abs_spec x) as [[_ Hex] | [_ Hex]].\n    + destruct (abs_spec y) as [[_ Hey] | [_ Hey]].\n      * rewrite (opp_add_distr x y). rewrite <- (abs_opp x), <- (abs_opp y).\n        apply add_le_mono.\n        -- apply le_abs.\n        -- apply le_abs.\n      * rewrite Hey. rewrite (opp_add_distr x y). rewrite <- (abs_opp x).\n        apply add_le_mono_r. apply le_abs.\n    + rewrite Hex. rewrite (opp_add_distr x y). rewrite <- (abs_opp y).\n      apply add_le_mono_l. apply le_abs. Qed.\n\nTheorem abs_opp_triangle : forall x y : Z,\n  (|x - y|) <= (|x|) + (|y|).\nProof.\n  intros x y.\n  rewrite <- (add_opp_r x y). rewrite <- (abs_opp y).\n  remember (- y) as z eqn : Hez.\n  apply abs_triangle. Qed.\n\nTheorem abs_sub_triangle : forall x y : Z,\n  (|x|) - (|y|) <= (|x - y|).\nProof.\n  intros x y. apply (add_le_mono_r _ _ (|y|)).\n  rewrite (sub_add _ _). remember (x - y) as z eqn : Hez.\n  rewrite <- (sub_add y x). rewrite <- Hez.\n  apply abs_triangle. Qed.\n\nTheorem abs_opp_sub_triangle : forall x y : Z,\n  (|x|) - (|y|) <= (|x + y|).\nProof.\n  intros x y.\n  rewrite <- (abs_opp y). rewrite <- (sub_opp_r x y).\n  remember (- y) as z eqn : Hez.\n  apply abs_sub_triangle. Qed.\n\nLemma abs_sub_comm : forall x y : Z,\n  (|x - y|) = (|y - x|).\nProof.\n  intros x y. destruct (abs_spec (x - y)) as [[Hlxy Hexy] | [Hlxy Hexy]].\n  - rewrite Hexy. rewrite <- (add_opp_l x y). rewrite <- (opp_sub_distr y x).\n    apply eq_sym. apply abs_neq.\n    apply (le_sub_le_add_l y x 0). rewrite (add_0_r x).\n    rewrite <- (add_0_r y). apply (le_add_le_sub_l y x 0).\n    apply Hlxy.\n  - apply lt_le_incl in Hlxy.\n    rewrite Hexy. rewrite (opp_sub_distr x y). rewrite (add_opp_l y x).\n    apply eq_sym. apply abs_eq.\n    apply (le_add_le_sub_l x y 0). rewrite (add_0_r x).\n    rewrite <- (add_0_r y). apply (le_sub_le_add_l x y 0).\n    apply Hlxy. Qed.\n\nTheorem abs_rev_triangle : forall x y : Z,\n  (|(|x|) - (|y|)|) <= (|x - y|).\nProof.\n  intros x y. apply abs_le. split.\n  - apply opp_le_mono.\n    rewrite (opp_sub_distr _ _). rewrite (add_opp_l _ _).\n    rewrite (opp_involutive _). rewrite (abs_sub_comm x y).\n    apply abs_sub_triangle.\n  - apply abs_sub_triangle. Qed.\n\nTheorem abs_opp_rev_triangle : forall x y : Z,\n  (|(|x|) - (|y|)|) <= (|x + y|).\nProof.\n  intros x y.\n  rewrite <- (abs_opp y). rewrite <- (sub_opp_r x y).\n  remember (- y) as z eqn : Hez.\n  apply abs_rev_triangle. Qed.\n\nTheorem abs_quadrangle : forall x y : Z,\n  (|x|) - (|y|) <= (|x|) + (|y|).\nProof.\n  intros x y. apply (le_trans _ (|x - y|) _).\n  - apply abs_sub_triangle.\n  - apply abs_opp_triangle. Restart.\n  intros x y. apply (le_trans _ (|x + y|) _).\n  - apply abs_opp_sub_triangle.\n  - apply abs_triangle. Qed.\n\nTheorem abs_rev_quadrangle : forall x y : Z,\n  (|(|x|) - (|y|)|) <= (|x|) + (|y|).\nProof.\n  intros x y. apply (le_trans _ (|x - y|) _).\n  - apply abs_rev_triangle.\n  - apply abs_opp_triangle. Restart.\n  intros x y. apply (le_trans _ (|x + y|) _).\n  - apply abs_opp_rev_triangle.\n  - apply abs_triangle. Qed.\n\nTheorem abs_pre_triangle : forall x y : Z,\n  x + y <= (|x|) + (|y|).\nProof.\n  intros x y. apply (le_trans _ (|x + y|) _).\n  - apply le_abs.\n  - apply abs_triangle. Qed.\n\nTheorem abs_opp_pre_triangle : forall x y : Z,\n  x - y <= (|x|) + (|y|).\nProof.\n  intros x y.\n  rewrite <- (add_opp_r x y). rewrite <- (abs_opp y).\n  remember (- y) as z eqn : Hez.\n  apply abs_pre_triangle. Qed.\n\nTheorem abs_le_add_abs : forall x y : Z,\n  (|(|x|) + (|y|)|) <= (|x|) + (|y|).\nProof.\n  intros x y. apply (le_stepl ((|x|) + (|y|)) _ _).\n  - apply le_refl.\n  - apply eq_sym. apply abs_eq. apply (le_trans _ (|x + y|) _).\n    + apply abs_nonneg.\n    + apply abs_triangle. Qed.\n\nTheorem abs_triangle_abs : forall x y : Z,\n  (|x + y|) <= (|(|x|) + (|y|)|).\nProof.\n  intros x y. apply (le_trans _ ((|x|) + (|y|)) _).\n  - apply abs_triangle.\n  - apply le_abs. Qed.\n\nTheorem abs_opp_triangle_abs : forall x y : Z,\n  (|x - y|) <= (|(|x|) + (|y|)|).\nProof.\n  intros x y. apply (le_trans _ ((|x|) + (|y|)) _).\n  - apply abs_opp_triangle.\n  - apply le_abs. Qed.\n\nTheorem abs_quadrangle_abs : forall x y : Z,\n  (|x|) - (|y|) <= (|(|x|) + (|y|)|).\nProof.\n  intros x y. apply (le_trans _ ((|x|) + (|y|)) _).\n  - apply abs_quadrangle.\n  - apply le_abs. Qed.\n\nTheorem abs_rev_quadrangle_abs : forall x y : Z,\n  (|(|x|) - (|y|)|) <= (|(|x|) + (|y|)|).\nProof.\n  intros x y. apply (le_trans _ ((|x|) + (|y|)) _).\n  - apply abs_rev_quadrangle.\n  - apply le_abs. Qed.\n\nTheorem abs_pre_triangle_abs : forall x y : Z,\n  x + y <= (|(|x|) + (|y|)|).\nProof.\n  intros x y. apply (le_trans _ ((|x|) + (|y|)) _).\n  - apply abs_pre_triangle.\n  - apply le_abs. Qed.\n\nTheorem abs_opp_pre_triangle_abs : forall x y : Z,\n  x - y <= (|(|x|) + (|y|)|).\nProof.\n  intros x y.\n  rewrite <- (add_opp_r x y). rewrite <- (abs_opp y).\n  remember (- y) as z eqn : Hez.\n  apply abs_pre_triangle_abs. Qed.\n\nEnd Inequalities.\n", "meta": {"author": "Tuplanolla", "repo": "dez", "sha": "c2eadc2e032094c3504ec3803c000dba4feb547e", "save_path": "github-repos/coq/Tuplanolla-dez", "path": "github-repos/coq/Tuplanolla-dez/dez-c2eadc2e032094c3504ec3803c000dba4feb547e/garbage/mock/ZTriangle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.6625289290466714}}
{"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 :=\nmatch d with \n|monday => tuesday\n|tuesday => wednesday\n|wednesday => thursday\n|thursday => friday\n|friday => monday\n|saturday => monday\n|sunday => monday\nend.\n\n\nCompute (next_weekday friday).\nCompute (next_weekday (next_weekday saturday)).\n\n\nExample test_next_weekday:\n(next_weekday (next_weekday saturday)) = tuesday.\nProof. simpl. reflexivity. Qed.\n\n\n", "meta": {"author": "ayushpandey8439", "repo": "CoqProofs", "sha": "a5e7c8ed86eed738a1b70a6a047a5408fdaa6c7b", "save_path": "github-repos/coq/ayushpandey8439-CoqProofs", "path": "github-repos/coq/ayushpandey8439-CoqProofs/CoqProofs-a5e7c8ed86eed738a1b70a6a047a5408fdaa6c7b/daysOfWeek.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6625289285796601}}
{"text": "Add LoadPath \"C:/Coq/buffer\".\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.\n\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  (* forall P : aexp -> Prop,\n     (forall n : P (Anum n)) ->\n     (forall a : aexp, P a -> (forall b : aexp, P b ->  (APlus a b))) ->\n     (forall a : aexp, P a -> (forall b : aexp, P b -> (AMinus a b))) ->\n     (forall a : aexp, P a -> (forall b : aexp, P b -> (AMult a b))) ->\n     forall a : exp, P a *)\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  (* forall P : bexp -> Prop,\n     P BTrue -> P BFalse ->\n     (forall a a0 : aexp, P (BEq a a0)) ->\n     (forall a a0 : aexp, P (BLe a a0)) ->\n     (forall b : bexp, P b -> P (BNot b)) ->\n     (forall b : bexp, P b -> forall b0 : bexp, P b0 -> P (BAnd b b0)) ->\n     forall b : bexp, P b *)\n\n  Fixpoint 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  Fixpoint beval (b : bexp) : bool :=\n  match b with\n  | BTrue => true\n  | BFalse => false\n  | BEq a b => beq_nat (aeval a) (aeval b)\n  | BLe a b => leb (aeval a) (aeval b)\n  | BNot b => negb (beval b)\n  | BAnd a b => andb (beval a) (beval b)\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  Proof. reflexivity. Qed.\n\n  Theorem optimize_0plus_sound : forall a,\n      aeval (optimize_0plus a) = aeval a.\n  Proof.\n    intros a. induction a.\n    -reflexivity.\n    -destruct a1.\n     +destruct n.\n      * apply IHa2.\n      * simpl. 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. simpl in IHa1. simpl in IHa2. rewrite IHa1. rewrite IHa2. reflexivity.\n    -simpl. simpl in IHa1. simpl in IHa2. rewrite IHa1. rewrite IHa2. reflexivity.\n  Qed.\n\n  Theorem silly1 : forall ae, aeval ae = aeval ae.\n  Proof. try reflexivity. Qed.\n\n  Theorem silly2 : forall (P : Prop), P -> P.\n  Proof.\n    intros P HP.\n    try reflexivity.\n    apply HP.\n  Qed.\n\n  Lemma foo : forall n, leb 0 n = true.\n  Proof.\n    intros.\n    destruct n.\n    -simpl. reflexivity.\n    -simpl. reflexivity.\n  Qed.\n\n  Lemma foo' : forall n, leb 0 n = true.\n  Proof.\n    intros.\n    destruct n; simpl; reflexivity.\n  Qed.\n\n  Theorem optimize_0plus_sound' : forall a : aexp,\n      aeval (optimize_0plus a) = aeval a.\n  Proof. intros a. induction a;\n           try ( simpl; rewrite IHa1; rewrite IHa2; reflexivity).\n         - reflexivity.\n         - destruct a1;\n           try (simpl; simpl in IHa1; rewrite IHa1;\n                rewrite IHa2; reflexivity).\n           + destruct n;\n             simpl; rewrite IHa2; reflexivity. Qed.\n\n  Theorem optimize_0plus_sound'' : forall a : aexp,\n      aeval (optimize_0plus a) = aeval a.\n  Proof.\n    intros a.\n    induction a;\n      try (simpl; rewrite IHa1; rewrite IHa2; reflexivity);\n      try reflexivity.\n    - destruct a1; try (simpl; simpl in IHa1; rewrite IHa1;\n                        rewrite IHa2; reflexivity).\n      +destruct n;\n        simpl; rewrite IHa2; reflexivity. Qed.\n\n  Theorem In10 : In 10 [1;2;3;4;5;6;7;8;9;10].\n  Proof.\n    repeat (try (left; reflexivity); right).\n  Qed.\n\n  Fixpoint optimize_0plus_b (b : bexp) : bexp :=\n    match b with\n    | BEq a b => BEq (optimize_0plus a) (optimize_0plus b)\n    | BLe a b => BLe (optimize_0plus a) (optimize_0plus b)\n    | b => b\n    end.\n\n  Theorem optimize_0plus_b_sound : forall b,\n      beval (optimize_0plus_b b) = beval b.\n  Proof. intros b.\n         induction b;\n           try (reflexivity);\n           try (simpl; rewrite IHb1; rewrite IHb2; reflexivity);\n           try (simpl; repeat rewrite optimize_0plus_sound; reflexivity).\n  Qed.\n\n  Example silly_presburger_example : forall m n o p,\n      m + n <= n + o /\\ o + 3 = p + 3 ->\n      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)\n                             (at level 50, left associativity)\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\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. intros a n. split.\n         -intros H. induction H.\n          +reflexivity.\n          +simpl. rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.\n          +simpl. rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.\n          +simpl. rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.\n         -generalize dependent n. induction a;\n            simpl; intros; subst; constructor;\n            try apply IHa1; try apply IHa2; reflexivity.\n          Qed.\n  \n  Inductive bevalR : bexp -> bool -> Prop :=\n  | E_BTrue : bevalR BTrue true\n  | E_BFalse : bevalR BFalse false\n  | E_BEq : forall (n0 n1 : nat) (a0 a1 : aexp),\n      a0 \\\\ n0 -> a1 \\\\ n1 -> bevalR (BEq a0 a1) (beq_nat n0 n1)\n  | E_BLe : forall (n0 n1 : nat) (a0 a1 : aexp),\n      a0 \\\\ n0 -> a1 \\\\ n1 -> bevalR (BLe a0 a1) (leb n0 n1)\n  | E_BNot : forall (B : bexp) (b : bool), bevalR B b -> bevalR (BNot B) (negb b)  \n  | E_BAnd : forall (B0 B1 : bexp) (b0 b1 : bool),\n      bevalR B0 b0 -> bevalR B1 b1 -> bevalR (BAnd B0 B1) (andb b0 b1).\n  \n  Theorem beval_iff_bevalR : forall (b : bexp) (bv : bool),\n      bevalR b bv <-> beval b = bv.\n  Proof. intros b bv. split.\n         -intros H. induction H;\n           try (simpl; reflexivity);\n           try (simpl; rewrite aeval_iff_aevalR in H;\n                rewrite aeval_iff_aevalR in H0; subst;\n                reflexivity);\n           try (simpl; subst; reflexivity).\n         -intros H. generalize dependent bv. induction b;\n            intros; destruct bv;\n            try (inversion H; constructor; rewrite aeval_iff_aevalR; reflexivity).\n            simpl in H.\n          ++replace true with (negb false). apply E_BNot. apply IHb.\n           apply negb_true_iff in H. apply H. reflexivity.\n          *replace false with (negb true). apply E_BNot. apply IHb.\n           simpl in H. apply negb_false_iff in H. apply H. reflexivity.\n          *simpl in H. rewrite <- H. apply E_BAnd.\n           **apply IHb1. reflexivity.\n           **apply IHb2. reflexivity.\n          *simpl in H. rewrite <- H. apply E_BAnd.\n           **apply IHb1. reflexivity.\n           **apply IHb2. reflexivity.\n  Qed.\n\nEnd AExp.\n\nModule 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  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  | 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                                        \n  where \" e \\\\ n \" := (aevalR e n) : type_scope.\n\nEnd aevalR_division.\n\nModule aevalR_extended.\n\n  Reserved Notation \"e \\\\ n\" (at level 50, left associativity).\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  Inductive aevalR : aexp -> nat -> Prop :=\n  | E_AAny : forall (n : nat), AAny \\\\ n\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                                      \n  where \" e \\\\ n \" := (aevalR e n) : type_scope.\n\nEnd aevalR_extended.\n\nDefinition state := total_map nat.\n\nDefinition empty_state : state := t_empty 0.\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)\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 => 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\nExample aexp1 :\n  aeval (t_update empty_state X 5)\n        (APlus (ANum 3) (AMult (AId X) (ANum 2))) = 13.\nProof. reflexivity. Qed.\n\nExample bexp1 :\n  beval (t_update empty_state X 5)\n        (BAnd BTrue (BNot (BLe (AId X) (ANum 4)))) = 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\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' 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\nFixpoint ceval_fun_no_while (st : state) (c : com) : state :=\n  match c with\n  | SKIP => st\n  | x ::= a1 => t_update 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\nReserved Notation \"c '/' st '\\\\' st'\" (at level 40, st at level 39).\n\nInductive ceval_funR : com -> state -> state -> Prop :=\n| E_Skip : forall s,\n    SKIP / s \\\\ s\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 c1 c2 b st st',\n    c1 / st \\\\ st' ->\n    beval st b = true ->\n    IFB b THEN c1 ELSE c2 FI / st \\\\ st'\n| E_IfFalse : forall c1 c2 b st st',\n    c2 / st \\\\ st' ->\n    beval st b = false ->\n    IFB b THEN c1 ELSE c2 FI/ st \\\\ st'        \n| E_WhileEnd : forall c1 b st,\n    beval st b = false ->\n    WHILE b DO c1 END / st \\\\ st\n| E_WhileLoop : forall c1 b st st' st'',\n    beval st b = true ->\n    c1 / st \\\\ st' ->\n    WHILE b DO c1 END / st' \\\\ st'' ->\n    WHILE b DO c1 END / st \\\\ st''          \n\n    where \" c '/' st '\\\\' st' \" := (ceval_funR c st st') : type_scope.\n\nExample ceval_example2 :\n  (X ::= ANum 0;; Y ::= ANum 1;; Z ::= ANum 2) / empty_state \\\\\n  (t_update (t_update (t_update empty_state X 0) Y 1) Z 2).\nProof. apply E_Seq with (st' := (t_update empty_state X 0)).\n       apply E_Ass. reflexivity.\n       apply E_Seq with (st' := (t_update (t_update empty_state X 0) Y 1)).\n       apply E_Ass. reflexivity.\n       apply E_Ass. reflexivity.\nQed.\n\nDefinition pup_to_n : com :=\n  (Y ::= ANum 0;;\n   WHILE (BNot (BEq (AId X) (ANum 0))) 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 / (t_update empty_state X 2) \\\\\n           t_update (t_update (t_update (t_update (t_update (t_update\n           empty_state X 2) Y 0) Y 2) X 1) Y 3) X 0.\nProof. unfold pup_to_n.\n       apply E_Seq with (st' := (t_update (t_update empty_state X 2) Y 0)).\n       -apply E_Ass. reflexivity.\n       -apply E_WhileLoop with (st' := (t_update (t_update (t_update (t_update empty_state X 2) Y 0) Y 2) X 1)).\n        reflexivity.\n        apply E_Seq with (st' := (t_update (t_update (t_update\n                          empty_state X 2) Y 0) Y 2)).\n        apply E_Ass. reflexivity. apply E_Ass. reflexivity.\n        apply E_WhileLoop with (st' := (t_update (t_update (t_update (t_update (t_update (t_update\n                                empty_state X 2) Y 0) Y 2) X 1) Y 3) X 0)).\n        reflexivity.\n        apply E_Seq with (st' := (t_update (t_update (t_update (t_update (t_update\n                          empty_state X 2) Y 0) Y 2) X 1) Y 3)).\n        apply E_Ass. reflexivity.\n        apply E_Ass. reflexivity.\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. intros c st st1 st2 E1 E2.\n       generalize dependent st2.\n       induction E1; intros st2 E2; inversion E2; subst.\n       -reflexivity.\n       -reflexivity.\n       -assert (st' = st'0) as EQ1.\n        { apply IHE1_1; assumption. }\n        subst st'0.\n        apply IHE1_2. assumption.\n       -apply IHE1. assumption.\n       -rewrite H in H6. inversion H6.\n       -rewrite H in H6. inversion H6.\n       - apply IHE1. assumption.\n       - reflexivity.\n       - rewrite H in H2. inversion H2.\n       - rewrite H in H4. inversion H4.\n       - apply IHE1_1 in H3. rewrite <- H3 in H6.\n         apply IHE1_2 in H6. apply H6.\nQed.\n\nDefinition plus2 : com :=\n  X ::= (APlus (AId X) (ANum 2)).\nTheorem plus2_spec : forall st n st',\n    st X = n ->\n    plus2 / st \\\\ st' ->\n    st' X = n + 2.\nProof. intros st n st' HX Heval. inversion Heval.\n       subst. clear Heval. simpl. apply t_update_eq. Qed.\n\nDefinition XtimesYinZ : com :=\n  Z ::= (AMult (AId X) (AId Y)).\nTheorem XtimesYinZ_spec : forall st st' n n',\n    st X = n -> st Y = n' ->\n    XtimesYinZ / st \\\\ st' ->\n    st' Z = n * n'.\nProof. intros st st' n n' HX HY Heval.\n       inversion Heval. subst. simpl. apply t_update_eq.\nQed.\n\nDefinition loop : com :=\n  WHILE BTrue DO SKIP END.\nTheorem loop_never_stops : forall st st',\n    ~ (loop / st \\\\ st').\nProof. intros st st' contra. unfold loop in contra.\n       remember(WHILE BTrue DO SKIP END) as loopdef\n                eqn:Heqloopdef.\n       induction contra; try inversion Heqloopdef.\n       +rewrite H1 in H. inversion H.\n       +apply IHcontra2. apply Heqloopdef.\nQed.\n\nFixpoint no_whiles (c : com) : bool :=\n  match c with\n  | SKIP\n  | _ ::= _ => true\n  | c1 ;; c2\n  | IFB _ THEN c1 ELSE c2 FI => andb (no_whiles c1) (no_whiles c2)\n  | WHILE _ DO _ END => false\n  end.\n\nInductive no_whilesR : com -> Prop :=\n| no_whiles_SKIP : no_whilesR SKIP\n| no_whiles_CAss : forall i x, no_whilesR (i ::= x)\n| no_whiles_CSeq : forall x1 x2,\n    no_whilesR x1 -> no_whilesR x2 -> no_whilesR (x1 ;; x2)\n| no_whiles_CIFB :  forall x1 x2,\n    no_whilesR x1 -> no_whilesR x2 -> (forall b, no_whilesR (IFB b THEN x1 ELSE x2 FI)).\n\n(* first in front of [ ] notation *)\nTheorem no_whiles_eqv :\n  forall c, no_whiles c = true <-> no_whilesR c.\nProof. intros c. split; intros H. induction c.\n       - apply no_whiles_SKIP.\n       - apply no_whiles_CAss.\n       - simpl in H. rewrite andb_true_iff in H. destruct H. apply no_whiles_CSeq.\n            apply IHc1. apply H. apply IHc2. apply H0.\n       - simpl in H. rewrite andb_true_iff in H. destruct H. apply no_whiles_CIFB.\n            apply IHc1. apply H. apply IHc2. apply H0.\n       - inversion H.\n       - induction c; try (simpl; reflexivity).\n         * inversion H. subst. apply IHc1 in H2. apply IHc2 in H3.\n           simpl. apply andb_true_iff. split. apply H2. apply H3.\n         * inversion H. subst. apply IHc1 in H2. apply IHc2 in H4.\n           simpl. apply andb_true_iff. split. apply H2. apply H4.\n         * inversion H.\nQed.\n(*dependent pattern matching / when to use eqn\n  Searching for proofs : ctrl-c ctrl-a then ctrl-a\n*)\nTheorem no_whiles_terminating : forall c, no_whilesR c ->\n        (forall s1, (exists s2, c / s1 \\\\ s2)).\nProof. intros c H. induction H; intros.\n       -exists s1. constructor.\n       -exists (t_update s1 i (aeval s1 x)). constructor. reflexivity.\n       -destruct IHno_whilesR1 with (s1 := s1).\n        destruct IHno_whilesR2 with (s1 := x). exists x0.\n        apply E_Seq with (st' := x). apply H1. apply H2.\n       -destruct (beval s1 b) eqn:?;\n        [destruct IHno_whilesR1 with (s1:=s1) | destruct IHno_whilesR2 with (s1:=s1)];\n        exists x; [apply E_IfTrue | apply E_IfFalse]; try apply H1; try apply Heqb0.\nQed.\n\nInductive sinstr : Type :=\n| SPush : nat -> sinstr\n| SLoad : id -> sinstr\n| SPlus : sinstr\n| SMinus : sinstr\n| SMult : sinstr.\n\nFixpoint s_execute (st : state) (stack : list nat)\n                   (prog : list sinstr)\n                   : list nat :=\n  match prog, stack with\n  | SPush n :: t, _  => s_execute st (n :: stack) t\n  | SLoad i :: t, _  => s_execute st (st i :: stack) t\n  | SPlus :: t, h :: h' :: t' => s_execute st ((h' + h) :: t') t\n  | SMinus :: t, h :: h' :: t' => s_execute st ((h' - h) :: t') t\n  | SMult :: t, h :: h' :: t' => s_execute st ((h' * h) :: t') t\n  | _ , _ => stack\n  end.\n\nExample s_execute1 :\n  s_execute empty_state []\n            [SPush 5; SPush 3; SPush 1; SMinus]\n  = [2 ; 5].\nProof. reflexivity. Qed.\n\nExample s_execute2 :\n  s_execute (t_update empty_state X 3) [3 ; 4]\n            [SPush 4; SLoad X; SMult; SPlus]\n  = [15 ; 4].\nProof. reflexivity. Qed.\n\nFixpoint s_compile (e : aexp) : list sinstr :=\n  match e with\n  | ANum n => SPush n :: nil\n  | AId i => SLoad i :: nil\n  | APlus a b => (s_compile a) ++ (s_compile b) ++ [SPlus]\n  | AMinus a b => (s_compile a) ++ (s_compile b) ++ [SMinus]\n  | AMult a b => (s_compile a) ++ (s_compile b) ++ [SMult]                       \n  end.\n\nExample s_compile1 :\n  s_compile (AMinus (AId X) (AMult (ANum 2) (AId Y)))\n  = [SLoad X; SPush 2; SLoad Y; SMult; SMinus].\nProof. reflexivity. Qed.\n(* this is too hard to prove!\nLemma s_compile_plus : forall (st : state) (a b a' b': aexp) (na nb : list nat),\n    s_execute st na (s_compile a) = [aeval st a'] ->\n    s_execute st nb (s_compile b) = [aeval st b'] ->\n    s_execute st (na ++ nb) (s_compile a ++ s_compile b ++ [SPlus]) = [aeval st (APlus a' b')].\nProof. intros st a b a' b' na nb Ha Hb. \n *)\n\nLemma s_execute_args : forall (st : state) (e : aexp) (l : list nat) (p : list sinstr),\n    s_execute st l (s_compile e ++ p) =\n    s_execute st (s_execute st [] (s_compile e) ++ l) p.\nProof. intros st e. induction e.\n       -reflexivity.\n       -reflexivity.\n       -intros l p. simpl. \n\n\nLemma s_execute_nat : forall (st : state) (e : aexp),\n    (exists n : nat, s_execute st [] (s_compile e) = [n]).\nProof. intros st e. induction e as [ n | i | | IHe1 | IHe2];\n         [exists n | exists (st i) | | | ]; try reflexivity.\n       -\n               \nTheorem s_compile_correct : forall (st : state) (e : aexp),\n    s_execute st [] (s_compile e) = [ aeval st e ].\nProof. intros st e. \n      \n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.6625289233621308}}
{"text": "Require Export GSM. \n\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nInductive form :=\n    | Var : var -> form    \n    | Bot : form \n    | Imp : form -> form -> form\n    | AX : act -> form -> form \n    | AG : form -> form \n    | EG : form -> form.\n\nDefinition Not A := Imp A Bot.\nDefinition Top := Not Bot.\nDefinition Or A B := Imp (Not A) B.\nDefinition And A B := Not (Imp A (Not B)).\nDefinition EX a A := Not (AX a (Not A)).\nDefinition AF A := Not (EG (Not A)).\n\n\n\nInductive step (a : act) : state -> state -> Prop :=\n    | here s : step a s s\n    | there b s t r : trans a s t -> step b t r -> step a s r.\n\n\nFixpoint eval (e : form) (s : state) : Prop :=\n    match e with \n    | Var n => valuation n s\n    | Bot => False\n    | Imp e1 e2 => eval e1 s -> eval e2 s\n    | AX a e' => forall s', trans a s s' -> eval e' s'\n    | AG e' => forall a s', step a s s' -> eval e' s'\n    | EG e' => exists a s', eval e' s' /\\ (forall t, step a s t -> step a t s' -> eval e' t)\n    end.  \n\n\nNotation \"s |= e\" := (eval e s)(at level 80).\nNotation \"⊤\" := Top.\nNotation \"⊥\" := Bot.\nNotation \"¬ e\" := (Not e)(at level 10).\nNotation \"e1 ∧ e2\" := (And e1 e2) (at level 30).\nNotation \"e1 ∨ e2\" := (Or e1 e2) (at level 30).\nNotation \"[ a ] e\" :=(AX a e)(at level 20).\nNotation \"< a > e\" := (EX a e) (at level 20).\nNotation \"e1 → e2\" := (Imp e1 e2) (at level 50).\n\n\n\n\n\n\n\n", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "GovernmentStateMachine", "sha": "4474833f55984d5b7139d3884bd18affedbcceef", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-GovernmentStateMachine", "path": "github-repos/coq/gaxiiiiiiiiiiii-GovernmentStateMachine/GovernmentStateMachine-4474833f55984d5b7139d3884bd18affedbcceef/Semantic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.6625040513483768}}
{"text": "Require Import Basics.\nRequire Import Types.\nRequire Import Colimits.Pushout.\nRequire Import Colimits.SpanPushout.\nRequire Import HoTT.Truncations.\nRequire Import Homotopy.Join.\nRequire Import Homotopy.Suspension.\nRequire Import Homotopy.BlakersMassey.\n\nImport TrM.\n\n(** * The Freudenthal Suspension Theorem *)\n\n(** The Freudenthal suspension theorem is a fairly trivial corollary of the Blakers-Massey theorem.  The only real work is to relate the span-pushout that we used for Blakers-Massey to the naive pushout that we used to define suspension. *)\n\nGlobal Instance freudenthal `{Univalence} (n : trunc_index)\n           (X : Type) `{IsConnected n.+1 X}\n  : IsConnMap (n +2+ n) (@merid X).\nProof.\n  pose (blakers_massey n n (fun (u v:Unit) => X) tt tt).\n  pose (f := equiv_pushout (equiv_contr_sigma (fun _ : Unit * Unit => X))^-1\n                           (equiv_idmap Unit) (equiv_idmap Unit)\n                           (fun x : X => idpath) (fun x : X => idpath)\n        : Susp X <~> SPushout (fun (u v:Unit) => X)).\n  srefine (@cancelR_equiv_conn_map (n +2+ n) _ _ _ _\n             (equiv_ap' f North South)\n             (@conn_map_homotopic _ _ _ _ _ _\n               (blakers_massey n n (fun (u v:Unit) => X) tt tt))).\n  intros x.\n  refine (_ @ (equiv_pushout_pglue\n                 (equiv_contr_sigma (fun _ : Unit * Unit => X))^-1\n                 (equiv_idmap Unit) (equiv_idmap Unit)\n                 (fun x : X => idpath) (fun x : X => idpath) x)^).\n  exact ((concat_p1 _ @ concat_1p _)^).\nDefined.\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/theories/Homotopy/Freudenthal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6624878633883542}}
{"text": "Require Export Arith.\nRequire Export ArithRing.\nRequire Export Wf_nat.\nRequire Export fib_ind fib_positive.\n\n(* The preliminary theorems are already in the exercise fib_positive. *)\n \nTheorem div2_rec:\n forall (P : nat ->  Set),\n P 0 -> P 1 -> (forall n, P n ->  P (S (S n))) -> forall (n : nat),  P n.\nProof.\nintros P H0 H1 Hrec n; assert (P n * P (S n))%type.\n- elim n; intuition.\n- intuition.\nQed.\n \nTheorem div2_spec:\n forall n,  ({x : nat | 2 * x = n}) + ({x : nat | 2 * x + 1 = n}).\nProof. \n  intros n; induction n as  [| | n IHn]  using div2_rec.\n  - left; now exists 0. \n  - right; now exists 0.\n  - destruct IHn as  [[x Heq]|[x Heq]].\n    + left; exists (S x); rewrite <- Heq; ring.\n    + right; exists (S x); rewrite <- Heq; ring.\nQed.\n \nTheorem half_smaller0: forall n x, 2 * x = S n ->  (x < S n).\nProof.\nintros; omega.\nQed.\n \nTheorem half_smaller1: forall n x, 2 * x + 1 = n ->  (x < n).\nProof.\nintros; omega.\nQed.\n \nDefinition fib_log_F:\n forall (x : nat),\n (forall (y : nat),\n  y < x ->  ({u : nat & {v : nat | u = fib y /\\ v = fib (S y)}})) ->\n  ({u : nat & {v : nat | u = fib x /\\ v = fib (S x)}}).\nintros [|x'].\n- intros _; exists 1, 1; auto.\n- destruct (div2_spec (S x')) as [[half_sx' Heq]|[half_x' Heq]]; intros fib_log.\n  + destruct (fib_log half_sx' (half_smaller0 _ _ Heq)) as [u [v [Heq1 Heq2]]].\n    rewrite <- Heq;exists (u * u + (v - u) * (v - u)),\n                          ((2 * u) * v - u * u).\n    rewrite Heq1; rewrite Heq2; split.\n    *  replace (S half_sx') with (half_sx' + 1) by ring. \n    now rewrite <- fib_2n.\n    *  replace (S half_sx') with (half_sx' + 1) by ring.\n       rewrite <- fib_2n_plus_1;\n         replace (2 * half_sx' + 1) with (S (2 * half_sx')) by ring.\n       trivial.\n  + destruct (fib_log half_x' (half_smaller1 _ _ Heq)) as [u [v [Heq1 Heq2]]].\n   rewrite <- Heq.\n   exists ((2 * u) * v - u * u), (v * v + u * u).\n   rewrite Heq1; rewrite Heq2; split.\n   * replace (S half_x') with (half_x' + 1) by ring.\n     now rewrite <- fib_2n_plus_1.\n   * replace (S half_x') with (half_x' + 1) by ring.\n     now rewrite <- fib_2n_plus_2.\nQed.\n \nDefinition fib_log :\n  forall (x : nat),  ({u : nat & {v : nat | u = fib x /\\ v = fib (S x)}}) :=\n   well_founded_induction\n    lt_wf (fun x => {u : nat & {v : nat | u = fib x /\\ v = fib (S x)}})\n    fib_log_F.\n\n\n(** Test : \nRecursive Extraction fib_log.\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/fib_log.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6624203920121376}}
{"text": "Require Import List.\nRequire Import Max.\nRequire Import Omega.\n\nAxiom LEM : forall (P : Prop), P \\/ ~ P.\n\nParameter A : Set.\n\nInductive T :=\n  | zero : T\n  | act : A -> T\n  | plus : T -> T -> T\n  | mult : T -> T -> T\n  | star : T -> T -> T.\n\nNotation \"0\" := zero.\nNotation \"p + q\" := (plus p q).\nNotation \"p · q\" := (mult p q) (at level 45, right associativity).\nNotation \"p * q\" := (star p q).\n\nInductive V :=\n  | term : V\n  | emb : T -> V.\n\nInductive step : V -> A -> V -> Prop := \n  | step_act : forall (a : A), step (emb (act a)) a term\n  | step_plus_left : forall (p q : T) (v : V) (a : A), \n    step (emb p) a v -> step (emb (p + q)) a v\n  | step_plus_right : forall (p q : T) (v : V) (a : A),\n    step (emb q) a v -> step (emb (p + q)) a v\n  | step_mult_left : forall (p q p' : T) (a : A),\n    step (emb p) a (emb p') -> step (emb (p · q)) a (emb (p' · q))\n  | step_mult_right : forall (p q : T) (a : A),\n    step (emb p) a term -> step (emb (p · q)) a (emb q)\n  | step_star_left : forall (p q p' : T) (a : A),\n    step (emb p) a (emb p') -> step (emb (p * q)) a (emb (p' · (p * q)))\n  | step_star_term : forall (p q : T) (a : A),\n    step (emb p) a term -> step (emb (p * q)) a (emb (p * q))\n  | step_star_right : forall (p q : T) (a : A) (v : V),\n    step (emb q) a v -> step (emb (p * q)) a v.\n\nNotation \"p '-(' a ')->' q\" := (step p a q) (at level 30).\n\nDefinition bisim (u v : V) : Prop := exists (R : V -> V -> Prop),\n  R u v /\\ forall (x y : V), R x y -> \n    (x = term <-> y = term) /\\\n    (forall (a : A) (x' : V), x -(a)-> x' ->\n      exists (y' : V), y -(a)-> y' /\\ R x' y') /\\\n    (forall (a : A) (y' : V), y -(a)-> y' ->\n      exists (x' : V), x -(a)-> x' /\\ R x' y').\n\nInductive ax : T -> T -> Prop :=\n  | refl : forall (x : T), ax x x\n  | symm : forall (x y : T), ax x y -> ax y x\n  | trans : forall (x y z : T), ax x y -> ax y z -> ax x z\n  | comp_plus : forall (w x y z : T), ax w y -> ax x z -> ax (w + x) (y + z)\n  | comp_mult : forall (w x y z : T), ax w y -> ax x z -> ax (w · x) (y · z)\n  | comp_star : forall (w x y z : T), ax w y -> ax x z -> ax (w * x) (y * z)\n  | B1 : forall (x y : T), ax (x + y) (y + x)\n  | B2 : forall (x y z : T), ax ((x + y) + z) (x + (y + z))\n  | B3 : forall (x : T), ax (x + x) x\n  | B4 : forall (x y z : T), ax ((x + y) · z) (x · z + y · z)\n  | B5 : forall (x y z : T), ax ((x · y) · z) (x · (y · z))\n  | B6 : forall (x : T), ax (x + 0) x\n  | B7 : forall (x : T), ax (0 · x) 0\n  | BKS1 : forall (x y : T), ax (x · (x * y) + y) (x * y)\n  | BKS2 : forall (x y z : T), ax ((x * y) · z) (x * (y · z))\n  | RSP : forall (x y z : T), ax x (y · x + z) -> ax x (y * z).\n\nNotation \"u '<=>' v\" := (bisim u v) (at level 25).\nNotation \"p '==' q\"  := (ax p q) (at level 25).\n\nFixpoint sum (L : list (A * V)) : T :=\n  match L with\n  | nil => 0\n  | (a, u) :: L' => match u with\n                   | term => act a + sum L'\n                   | emb p => act a · p + sum L'\n                   end\n  end.\n\nFixpoint mult_list (L : list (A * V)) (q : T) : list (A * V) :=\n  match L with\n  | nil => nil\n  | (a, u) :: L' => match u with\n                    | term => (a, emb q) :: mult_list L' q\n                    | emb p => (a, emb (p · q)) :: mult_list L' q\n                    end\n  end.\n\nInductive clos_step : T -> T -> Prop :=\n  | clos_refl : forall (p : T), clos_step p p\n  | clos_trans : forall (p q r : T) (a : A),\n    emb p -(a)-> emb q -> clos_step q r -> clos_step p r.\n\nDefinition clos_plus (p r : T) : Prop :=\n  exists (a : A) (q : T), emb p -(a)-> emb q /\\ clos_step q r.\n\nNotation \"p '-->*' q\" := (clos_step p q) (at level 25).\nNotation \"p '-->+' q\" := (clos_plus p q) (at level 25).\n\nDefinition congr (p q : T) : Prop :=\n  forall (t : T), p -->+ t -> emb (t · q) <=> emb q -> False.\n\nFixpoint depth (p : T) : nat :=\n  match p with\n  | 0 => 0 % nat\n  | act a => 0 % nat\n  | r + s => max (depth r) (depth s)\n  | r · s => max (depth r) (depth s)\n  | r * s => max (1 + depth r) (depth s)\n  end.\n\nDefinition bisimR (R : V -> V -> Prop) :=\n  forall (u v : V), R u v ->\n    (u = term <-> v = term) /\\\n    (forall (a : A) (u' : V), u -(a)-> u' ->\n      exists (v' : V), v -(a)-> v' /\\ R u' v') /\\\n    (forall (a : A) (v' : V), v -(a)-> v' ->\n      exists (u' : V), u -(a)-> u' /\\ R u' v').\n\nFixpoint Rclos (R : V -> V -> Prop) (n : nat) (x z : V) : Prop :=\n  match n with\n  | 0%nat => R x z\n  | S n => exists (y : V), Rclos R n x y /\\ R y z\n  end.\n\nDefinition exRclos (R : V -> V -> Prop) (x y : V) : Prop :=\n  exists (n : nat), Rclos R n x y.\n\nFixpoint nf_mult (p q : T) : Prop :=\n  match p with\n  | 0 => True\n  | act a => True\n  | r + s => nf_mult r q /\\ nf_mult s q\n  | r · s => nf_mult r (s · q) /\\ nf_mult s q\n  | r * s => nf_mult r (r * s · q) /\\ nf_mult s q /\\ congr r (r * s · q)\n  end.\n\nFixpoint nf (p : T) : Prop :=\n  match p with\n  | 0 => True\n  | act a => True\n  | r + s => nf r /\\ nf s\n  | r · s => nf_mult r s /\\ nf s\n  | r * s => nf_mult r (r * s) /\\ nf s /\\ congr r (r * s)\n  end.\n\nDefinition eqlist (M N : list (A * V)) : Prop :=\n  forall (a : A) (u : V), In (a, u) M <-> In (a, u) N.\n\nDefinition mult' (u : V) (q : T) : T :=\n  match u with\n  | term => q\n  | emb p => p · q\n  end.\n\nDefinition teq (u v : V) : Prop :=\n  match (u, v) with\n  | (term, term) => True\n  | (emb p, emb q) => p == q\n  | _ => False\n  end.\n\nLemma strong_ind : forall (P : nat -> Prop),\n  (forall (n : nat), (forall (m : nat), m < n -> P m) -> P n) ->\n    forall (n : nat), P n.\nProof.\n  intros P H n ; apply H ; induction n ; intros m H' ; inversion H' ; auto.\nQed.\n\nLemma step_plus_fmt : forall (p q : T) (a : A) (u : V),\n  emb (p + q) -(a)-> u -> emb p -(a)-> u \\/ emb q -(a)-> u.\nProof.\n  intros p q a u H ; inversion H ; auto.\nQed.\n\nLemma step_mult_fmt : forall (p q : T) (a : A) (u : V), emb (p · q) -(a)-> u ->\n  (exists (p' : T), u = emb (p' · q) /\\ emb p -(a)-> emb p') \\/\n  emb p -(a)-> term /\\ u = emb q.\nProof.\n  intros p q a u H ; inversion H ; eauto.\nQed.\n\nLemma step_star_fmt : forall (p q : T) (a : A) (u : V),\n  emb (p * q) -(a)-> u ->\n    (exists (p' : T), u = emb (p' · (p * q)) /\\ emb p -(a)-> emb p') \\/\n    (u = emb (p * q) /\\ emb p -(a)-> term) \\/\n    emb q -(a)-> u.\nProof.\n  intros p q a u H ; inversion H ; eauto.\nQed.\n\nLemma step_gen_cases : forall (p : T) (a : A) (u : V), emb p -(a)-> u -> \n  (exists (p' : T), u = emb p' /\\ emb p -(a)-> emb p') \\/ u = term.\nProof.\n  intro p ; induction p ; intros a' u H ; solve [ inversion H ; eauto ] || auto.\n  apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply IHp1 in H ; destruct H as [ H | H ] ; eauto.\n  destruct H as [ p' [ Heq Hstep ] ] ; rewrite Heq in *.\n  left ; exists p' ; split ; apply step_plus_left || auto ; auto.\n  apply IHp2 in H ; destruct H as [ H | H ] ; eauto.\n  destruct H as [ p' [ Heq Hstep ] ] ; rewrite Heq in *.\n  left ; exists p' ; split ; apply step_plus_right || auto ; auto.\n  apply step_mult_fmt in H ; destruct H as [ H | H ] ; eauto.\n  destruct H as [ p' [ Heq Hstep ] ] ; rewrite Heq in *.\n  left ; exists (p' · p2) ; split ; apply step_mult_left || auto ; auto.\n  destruct H as [ Hstep Heq ] ; left ; exists p2 ; split ;\n    apply step_mult_right || auto ; auto.\n  apply step_star_fmt in H ; destruct H as [ H | [ H | H ] ].\n  destruct H as [ p' [ Heq Hstep ] ] ; rewrite Heq in *.\n  left ; exists (p' · p1 * p2) ; split ;\n    apply step_star_left || auto ; auto.\n  destruct H as [ Heq Hstep ] ; rewrite Heq in *.\n  left ; exists (p1 * p2) ; split ; apply step_star_term || auto ; auto.\n  apply IHp2 in H ; destruct H as [ H | H ] ; auto.\n  destruct H as [ p' [ Heq Hstep ] ] ; rewrite Heq in *.\n  left ; exists p' ; split ; apply step_star_right || auto ; auto.\nQed.\n\nLemma bisim_next : forall (u v : V),\n  (u = term <-> v = term) ->\n  (forall (a : A) (u' : V), u -(a)-> u' ->\n    exists (v' : V), v -(a)-> v' /\\ u' <=> v') ->\n  (forall (a : A) (v' : V), v -(a)-> v' ->\n    exists (u' : V), u -(a)-> u' /\\ u' <=> v') -> u <=> v.\nProof.\n  intros u v Hiff Hltr Hrtl.\n  exists (fun x y => x = u /\\ y = v \\/ x <=> y) ; split ; auto.\n  intros x y H ; destruct H as [ [ Hu Hv ] | H ].\n  rewrite Hu, Hv in * ; split ; auto ; split.\n  intros a u' H ; apply Hltr in H ; destruct H as [ v' [ Hstep H ] ] ; eauto.\n  intros a v' H ; apply Hrtl in H ; destruct H as [ u' [ Hstep H ] ] ; eauto.\n  destruct H as [ R [ HinR HrelR ] ] ; apply HrelR in HinR ; split ; try tauto.\n  split ; [ intros a x' H | intros a y' H ] ; apply HinR in H.\n  destruct H as [ y' [ H HR ] ] ; exists y' ; split ; auto.\n  right ; exists R ; split ; auto.\n  destruct H as [ x' [ H HR ] ] ; exists x' ; split ; auto.\n  right ; exists R ; split ; auto.\nQed.\n\nLemma bisim_fwd : forall (u v : V), u <=> v ->\n  (u = term <-> v = term) /\\\n  (forall (a : A) (u' : V), u -(a)-> u' ->\n    exists (v' : V), v -(a)-> v' /\\ u' <=> v') /\\ \n  (forall (a : A) (v' : V), v -(a)-> v' ->\n    exists (u' : V), u -(a)-> u' /\\ u' <=> v').\nProof.\n  intros u v H ; destruct H as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  split ; [ tauto | split ].\n  intros a u' H ; apply HinR in H.\n  destruct H as [ v' [ H HR ] ] ; exists v' ; split ; auto.\n  exists R ; split ; auto.\n  intros a v' H ; apply HinR in H.\n  destruct H as [ u' [ H HR ] ] ; exists u' ; split ; auto.\n  exists R ; split ; auto.\nQed.\n\nLemma bisim_refl : forall (u : V), u <=> u.\nProof.\n  intro u ; exists (fun x y => x = y) ; split ; auto.\n  intros x y H ; rewrite H in * ; split ; [ tauto | split ] ; intros ; eauto.\nQed.\n\nLemma bisim_symm : forall (u v : V), u <=> v -> v <=> u.\nProof.\n  intros u v H ; destruct H as [ R [ HinR HrelR ] ].\n  exists (fun x y => R y x) ; split ; auto.\n  intros x y H ; apply HrelR in H ; split ; [ tauto | split ].\n  intros a x' H' ; apply H in H' ; eauto.\n  intros a y' H' ; apply H in H' ; eauto.\nQed.\n\nLemma bisim_trans : forall (u v w : V), \n  u <=> v -> v <=> w -> u <=> w.\nProof.\n  intros u v w H H'.\n  destruct H as [ R [ HinR HrelR ] ].\n  destruct H' as [ R' [ HinR' HrelR' ] ].\n  exists (fun x z => exists (y : V), R x y /\\ R' y z) ; split ; eauto.\n  intros x z H ; destruct H as [ y [ HR HR' ] ].\n  apply HrelR in HR ; apply HrelR' in HR' ; split ; [ tauto | split ].\n  intros a x' H ; apply HR in H ; destruct H as [ y' [ H HRxy ] ].\n  apply HR' in H ; destruct H as [ z' [ H HRyz ] ] ; eauto.\n  intros a z' H ; apply HR' in H ; destruct H as [ y' [ H HRzy ] ].\n  apply HR in H ; destruct H as [ x' [ H HRyx ] ] ; eauto.\nQed.\n\nLemma bisim_comp_plus : forall (p q r s : T),\n  emb p <=> emb r -> emb q <=> emb s -> emb (p + q) <=> emb (r + s).\nProof.\n  intros p q r s H H' ; apply bisim_fwd in H ; apply bisim_fwd in H'.\n  apply bisim_next ; [ split ; intro H'' ; inversion H'' | | ].\n  intros a u Hstep ; apply step_plus_fmt in Hstep.\n  destruct Hstep as [ Hstep | Hstep ].\n  apply H in Hstep ; destruct Hstep as [ r' [ Hstep Hbisim ] ].\n  exists r' ; split ; auto ; apply step_plus_left ; auto.\n  apply H' in Hstep ; destruct Hstep as [ s' [ Hstep Hbisim ] ].\n  exists s' ; split ; auto ; apply step_plus_right ; auto.\n  intros a u Hstep ; apply step_plus_fmt in Hstep.\n  destruct Hstep as [ Hstep | Hstep ].\n  apply H in Hstep ; destruct Hstep as [ p' [ Hstep Hbisim ] ].\n  exists p' ; split ; auto ; apply step_plus_left ; auto.\n  apply H' in Hstep ; destruct Hstep as [ q' [ Hstep Hbisim ] ].\n  exists q' ; split ; auto ; apply step_plus_right ; auto.\nQed.\n \nLemma bisim_comp_mult : forall (p q r s : T),\n  emb p <=> emb r -> emb q <=> emb s -> emb (p · q) <=> emb (r · s).\nProof.\n  intros p q r s H H'.\n  destruct H as [ R [ HinR HrelR ] ].\n  destruct H' as [ R' [ HinR' HrelR' ] ].\n  exists (fun u v => (exists (p' q' : T), u = emb (p' · q) /\\ \n    v = emb (q' · s) /\\ R (emb p') (emb q')) \\/ R' u v) ; split.\n  left ; exists p ; exists r ; tauto.\n  intros u v H ; destruct H as [ H | H ].\n  destruct H as [ p' [ q' [ Heq_u [ Heq_v HR ] ] ] ].\n  rewrite Heq_u, Heq_v in * ; split ; [ | split ] ; clear Heq_u Heq_v u v.\n  split ; intro H ; inversion H.\n  intros a u H ; apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ p'' [ Heq H ] ] ; rewrite Heq in *.\n  apply HrelR in HR ; apply HR in H.\n  destruct H as [ v [ H HR' ] ].\n  apply step_gen_cases in H ; destruct H as [ H | H ].\n  destruct H as [ q'' [ Heq_v H ] ] ; rewrite Heq_v in *.\n  exists (emb (q'' · s)) ; split ; eauto.\n  apply step_mult_left ; auto.\n  left ; exists p'' ; exists q'' ; split ; auto.\n  rewrite H in * ; apply HrelR in HR'.\n  assert (term = term) as H' by auto.\n  apply HR' in H' ; inversion H'.\n  destruct H as [ H Heq_u ] ; rewrite Heq_u in *.\n  apply HrelR in HR ; apply HR in H.\n  destruct H as [ v [ H HR' ] ].\n  assert (emb q' -(a)-> v) as Hstep_bak by auto.\n  apply step_gen_cases in H ; destruct H as [ H | H ].\n  destruct H as [ q'' [ Heq_v H ] ] ; rewrite Heq_v in *.\n  apply HrelR in HR' ; assert (term = term) as H' by auto.\n  apply HR' in H' ; inversion H'.\n  rewrite H in * ; exists (emb s) ; split ; auto.\n  apply step_mult_right ; auto.\n  intros a u H ; apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ q'' [ Heq H ] ] ; rewrite Heq in *.\n  apply HrelR in HR ; apply HR in H.\n  destruct H as [ v [ H HR' ] ].\n  apply step_gen_cases in H ; destruct H as [ H | H ].\n  destruct H as [ p'' [ Heq_v H ] ] ; rewrite Heq_v in *.\n  exists (emb (p'' · q)) ; split ; eauto.\n  apply step_mult_left ; auto.\n  left ; exists p'' ; exists q'' ; split ; auto.\n  rewrite H in * ; apply HrelR in HR'.\n  assert (term = term) as H' by auto.\n  apply HR' in H' ; inversion H'.\n  destruct H as [ H Heq_u ] ; rewrite Heq_u in *.\n  apply HrelR in HR ; apply HR in H.\n  destruct H as [ v [ H HR' ] ].\n  assert (emb p' -(a)-> v) as Hstep_bak by auto.\n  apply step_gen_cases in H ; destruct H as [ H | H ].\n  destruct H as [ p'' [ Heq_v H ] ] ; rewrite Heq_v in *.\n  apply HrelR in HR' ; assert (term = term) as H' by auto.\n  apply HR' in H' ; inversion H'.\n  rewrite H in * ; exists (emb q) ; split ; auto.\n  apply step_mult_right ; auto.\n  apply HrelR' in H ; split ; [ tauto | split ].\n  intros a u' H' ; apply H in H'.\n  destruct H' as [ v' [ H' HR' ] ] ; exists v' ; split ; auto.\n  intros a u' H' ; apply H in H'.\n  destruct H' as [ v' [ H' HR' ] ] ; exists v' ; split ; auto.\nQed.\n\nLemma bisim_comp_star : forall (p q r s : T),\n  emb p <=> emb r -> emb q <=> emb s -> emb (p * q) <=> emb (r * s).\nProof.\n  intros p q r s H H'.\n  destruct H as [ R [ HinR HrelR ] ].\n  destruct H' as [ R' [ HinR' HrelR' ] ].\n  exists (fun u v => u = emb (p * q) /\\ v = emb (r * s) \\/\n    (exists (p' r' : T), u = emb (p' · p * q) /\\ v = emb (r' · r * s) /\\\n      R (emb p') (emb r')) \\/ R' u v) ; split ; auto.\n  intros u v H ; destruct H as [ H | [ H | H ] ].\n  destruct H as [ Heq_u Heq_v ] ; rewrite Heq_u, Heq_v in *.\n  clear Heq_u Heq_v u v ; split ; [ | split ].\n  split ; intro H ; inversion H.\n  intros a u H ; apply step_star_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ p' [ Heq H ] ] ; rewrite Heq in *.\n  apply HrelR in HinR ; apply HinR in H.\n  destruct H as [ v [ Hstep HR ] ].\n  apply step_gen_cases in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ r' [ Heq' Hstep ] ] ; rewrite Heq' in *.\n  exists (emb (r' · r * s)) ; split ; eauto.\n  apply step_star_left ; auto.\n  right ; left ; eauto.\n  rewrite H in HR ; apply HrelR in HR.\n  assert (term = term) as H' by auto ; apply HR in H' ; inversion H'.\n  destruct H as [ [ Heq Hstep ] | Hstep ].\n  exists (emb (r * s)) ; split ; auto.\n  apply HrelR in HinR ; apply HinR in Hstep.\n  destruct Hstep as [ v [ Hstep HR ] ].\n  assert (emb r -(a)-> v) as Hstep_bak by auto.\n  apply step_gen_cases in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ r' [ Heq' Hstep ] ] ; rewrite Heq' in *.\n  apply HrelR in HR ; assert (term = term) as H by auto.\n  apply HR in H ; inversion H.\n  rewrite H in * ; apply step_star_term ; auto.\n  apply HrelR' in HinR' ; apply HinR' in Hstep.\n  destruct Hstep as [ v [ Hstep HR' ] ].\n  exists v ; split ; auto.\n  apply step_star_right ; auto.\n  intros a u H ; apply step_star_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ r' [ Heq H ] ] ; rewrite Heq in *.\n  apply HrelR in HinR ; apply HinR in H.\n  destruct H as [ v [ Hstep HR ] ].\n  apply step_gen_cases in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ p' [ Heq' Hstep ] ] ; rewrite Heq' in *.\n  exists (emb (p' · p * q)) ; split ; eauto.\n  apply step_star_left ; auto.\n  right ; left ; eauto.\n  rewrite H in HR ; apply HrelR in HR.\n  assert (term = term) as H' by auto ; apply HR in H' ; inversion H'.\n  destruct H as [ [ Heq Hstep ] | Hstep ].\n  exists (emb (p * q)) ; split ; auto.\n  apply HrelR in HinR ; apply HinR in Hstep.\n  destruct Hstep as [ v [ Hstep HR ] ].\n  assert (emb p -(a)-> v) as Hstep_bak by auto.\n  apply step_gen_cases in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ p' [ Heq' Hstep ] ] ; rewrite Heq' in *.\n  apply HrelR in HR ; assert (term = term) as H by auto.\n  apply HR in H ; inversion H.\n  rewrite H in * ; apply step_star_term ; auto.\n  apply HrelR' in HinR' ; apply HinR' in Hstep.\n  destruct Hstep as [ v [ Hstep HR' ] ].\n  exists v ; split ; auto.\n  apply step_star_right ; auto.\n  destruct H as [ p' [ r' [ Heq_u [ Heq_v HR ] ] ] ].\n  rewrite Heq_u, Heq_v in * ; clear Heq_u Heq_v u v ; split ; [ | split ].\n  split ; intro H ; inversion H.\n  intros a u H ; apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ p'' [ Heq Hstep ] ] ; rewrite Heq in *.\n  apply HrelR in HR ; apply HR in Hstep.\n  destruct Hstep as [ v [ Hstep HR' ] ].\n  apply step_gen_cases in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ r'' [ Heq' Hstep ] ] ; rewrite Heq' in *.\n  exists (emb (r'' · r * s)) ; split ; eauto.\n  apply step_mult_left ; auto.\n  right ; left ; eauto.\n  rewrite H in * ; apply HrelR in HR'.\n  assert (term = term) as H' by auto.\n  apply HR' in H' ; inversion H'.\n  destruct H as [ Hstep Heq ] ; rewrite Heq in *.\n  apply HrelR in HR ; apply HR in Hstep.\n  destruct Hstep as [ v [ Hstep HR' ] ].\n  assert (emb r' -(a)-> v) as Hstep_bak by auto.\n  apply step_gen_cases in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ r'' [ Heq' Hstep ] ] ; rewrite Heq' in *.\n  apply HrelR in HR' ; assert (term = term) as H' by auto.\n  apply HR' in H' ; inversion H'.\n  rewrite H in * ; exists (emb (r * s)) ; split ; auto.\n  apply step_mult_right ; auto.\n  intros a u H ; apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ r'' [ Heq Hstep ] ] ; rewrite Heq in *.\n  apply HrelR in HR ; apply HR in Hstep.\n  destruct Hstep as [ v [ Hstep HR' ] ].\n  apply step_gen_cases in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ p'' [ Heq' Hstep ] ] ; rewrite Heq' in *.\n  exists (emb (p'' · p * q)) ; split ; eauto.\n  apply step_mult_left ; auto.\n  right ; left ; eauto.\n  rewrite H in * ; apply HrelR in HR'.\n  assert (term = term) as H' by auto.\n  apply HR' in H' ; inversion H'.\n  destruct H as [ Hstep Heq ] ; rewrite Heq in *.\n  apply HrelR in HR ; apply HR in Hstep.\n  destruct Hstep as [ v [ Hstep HR' ] ].\n  assert (emb p' -(a)-> v) as Hstep_bak by auto.\n  apply step_gen_cases in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ p'' [ Heq' Hstep ] ] ; rewrite Heq' in *.\n  apply HrelR in HR' ; assert (term = term) as H' by auto.\n  apply HR' in H' ; inversion H'.\n  rewrite H in * ; exists (emb (p * q)) ; split ; auto.\n  apply step_mult_right ; auto.\n  apply HrelR' in H ; split ; [ tauto | split ].\n  intros a u' Hstep ; apply H in Hstep.\n  destruct Hstep as [ v' [ Hstep HR' ] ].\n  exists v' ; split ; auto.\n  intros a v' Hstep ; apply H in Hstep.\n  destruct Hstep as [ u' [ Hstep HR' ] ].\n  exists u' ; split ; auto.\nQed.\n\nLemma B1_sound : forall (p q : T), emb (p + q) <=> emb (q + p).\nProof.\n  intros p q ; apply bisim_next.\n  split ; intro H ; inversion H.\n  intros a u H ; inversion H.\n  exists u ; split ; apply bisim_refl || auto.\n  apply step_plus_right ; auto.\n  exists u ; split ; apply bisim_refl || auto.\n  apply step_plus_left ; auto.\n  intros a u H ; inversion H.\n  exists u ; split ; apply bisim_refl || auto.\n  apply step_plus_right ; auto.\n  exists u ; split ; apply bisim_refl || auto.\n  apply step_plus_left ; auto.\nQed.\n\nLemma B2_sound : forall (p q r : T), \n  (emb ((p + q) + r)) <=> (emb (p + (q + r))).\nProof.\n  intros p q r ; apply bisim_next.\n  split ; intro H ; inversion H.\n  intros a u H ; exists u ; split ; apply bisim_refl || auto.\n  apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply step_plus_left ; auto.\n  apply step_plus_right ; apply step_plus_left ; auto.\n  apply step_plus_right ; apply step_plus_right ; auto.\n  intros a u H ; exists u ; split ; apply bisim_refl || auto.\n  apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply step_plus_left ; apply step_plus_left ; auto.\n  apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply step_plus_left ; apply step_plus_right ; auto.\n  apply step_plus_right ; auto.\nQed.\n\nLemma B3_sound : forall (p : T), (emb (p + p)) <=> (emb p).\nProof.\n  intro p ; apply bisim_next.\n  split ; intro H ; inversion H.\n  intros a u H ; inversion H ; exists u ; \n    split ; apply bisim_refl || auto.\n  intros a u H ; exists u ; split ; apply bisim_refl ||\n    apply step_plus_left ; auto.\nQed.\n\nLemma B4_sound : forall (p q r : T), \n  (emb ((p + q) · r)) <=> (emb (p · r + q · r)).\nProof.\n  intros p q r ; apply bisim_next.\n  split ; intro H ; inversion H.\n  intros a u H ; exists u ; split ; apply bisim_refl || auto.\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ p' [ Heq H ] ] ; rewrite Heq in *.\n  apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply step_plus_left ; apply step_mult_left ; auto.\n  apply step_plus_right ; apply step_mult_left ; auto.\n  destruct H as [ H Heq ] ; rewrite Heq in *.\n  apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply step_plus_left ; apply step_mult_right ; auto.\n  apply step_plus_right ; apply step_mult_right ; auto.\n  intros a u H ; apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ p' [ Heq H ] ] ; rewrite Heq in *.\n  exists (emb (p' · r)) ; split ; apply bisim_refl || auto.\n  apply step_mult_left ; apply step_plus_left ; auto.\n  destruct H as [ H Heq ] ; rewrite Heq in *.\n  exists (emb r) ; split ; apply bisim_refl || auto.\n  apply step_mult_right ; apply step_plus_left ; auto.\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ q' [ Heq H ] ] ; rewrite Heq in *.\n  exists (emb (q' · r)) ; split ; apply bisim_refl || auto.\n  apply step_mult_left ; apply step_plus_right ; auto.\n  destruct H as [ H Heq ] ; rewrite Heq in *.\n  exists (emb r) ; split ; apply bisim_refl || auto.\n  apply step_mult_right ; apply step_plus_right ; auto.\nQed.\n\nLemma B5_sound : forall (p q r : T),\n  (emb ((p · q) · r)) <=> (emb (p · (q · r))).\nProof.\n  intros p q r ; exists (fun u v => (exists (p' : T), u = emb ((p' · q) · r) /\\ \n    v = emb (p' · q · r)) \\/ u = v) ; split ; eauto.\n  intros u v H ; destruct H as [ [ p' [ Heq_u Heq_v ] ] | H ].\n  rewrite Heq_u, Heq_v in * ; split ; [ | split ] ; clear Heq_u Heq_v u v.\n  split ; intro H ; inversion H.\n  intros a u H ; apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ v [ Heq Hstep ] ] ; rewrite Heq in *.\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ p'' [ Heq' Hstep ] ].\n  exists (emb (p'' · q · r)) ; split.\n  apply step_mult_left ; auto.\n  left ; exists p'' ; split ; auto.\n  replace v with (p'' · q) in * by ( inversion Heq' ; auto ) ; auto.\n  destruct H as [ Hstep Heq' ].\n  replace v with q in * by ( inversion Heq' ; auto ).\n  exists (emb (q · r)) ; split ; auto.\n  apply step_mult_right ; auto.\n  destruct H as [ Hstep Heq ] ; inversion Hstep.\n  intros a u H ; apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ p'' [ Heq Hstep ] ].\n  exists (emb ((p'' · q) · r)) ; split ; eauto.\n  apply step_mult_left ; apply step_mult_left ; auto.\n  destruct H as [ Hstep Heq ] ; rewrite Heq in *.\n  exists (emb (q · r)) ; split ; auto.\n  apply step_mult_left ; apply step_mult_right ; auto.\n  rewrite H in * ; split ; [ tauto | split ] ; intros ; eauto.\nQed.\n\nLemma B6_sound : forall (p : T), (emb (p + 0)) <=> emb p.\nProof.\n  intro p ; apply bisim_next.\n  split ; intro H ; inversion H.\n  intros a u H ; inversion H.\n  exists u ; split ; apply bisim_refl || auto.\n  assert (emb 0 -(a)-> u) as H' by auto ; inversion H'.\n  intros a u H ; exists u ; split ; apply bisim_refl ||\n    apply step_plus_left ; auto.\nQed.\n\nLemma B7_sound : forall (p : T), (emb (0 · p)) <=> emb 0.\nProof.\n  intro p ; apply bisim_next.\n  split ; intro H ; inversion H.\n  intros a u H ; inversion H.\n  assert (exists (x : T), emb 0 -(a)-> emb x) as H' by eauto.\n  destruct H' as [ x H' ] ; inversion H'.\n  assert (emb 0 -(a)-> term) as H' by auto ; inversion H'.\n  intros a u H ; inversion H.\nQed.\n\nLemma BKS1_sound : forall (p q : T), emb (p · (p * q) + q) <=> emb (p * q).\nProof.\n  intros p q ; apply bisim_next.\n  split ; intro H ; inversion H.\n  intros a u H ; apply step_plus_fmt in H ; destruct H as [ H | H ].\n  exists u ; split ; apply bisim_refl || auto.\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ p' [ Heq H ] ] ; rewrite Heq in *.\n  apply step_star_left ; auto.\n  destruct H as [ H Heq ] ; rewrite Heq in *.\n  apply step_star_term ; auto.\n  exists u ; split ; apply bisim_refl || auto.\n  apply step_star_right ; auto.\n  intros a u H ; apply step_star_fmt in H.\n  destruct H as [ H | [ H | H ] ].\n  destruct H as [ p' [ Heq H ] ] ; rewrite Heq in *.\n  exists (emb (p' · p * q)) ; split ; apply bisim_refl || auto.\n  apply step_plus_left ; apply step_mult_left ; auto.\n  destruct H as [ Heq H ] ; rewrite Heq in *.\n  exists (emb (p * q)) ; split ; apply bisim_refl || auto.\n  apply step_plus_left ; apply step_mult_right ; auto.\n  exists u ; split ; apply bisim_refl || auto.\n  apply step_plus_right ; auto.\nQed.\n\nLemma BKS2_sound : forall (p q r : T), emb ((p * q) · r) <=> emb (p * (q · r)).\nProof.\n  intros p q r.\n  exists (fun u v => u = emb (p * q · r) /\\ v = emb (p * (q · r)) \\/ \n    (exists (p' : T), u = emb ((p' · p * q) · r) /\\ \n      v = emb (p' · p * (q · r))) \\/ u = v) ; split ; auto.\n  intros u v H ; destruct H as [ H | [ H | H ] ].\n  destruct H as [ Heq_u Heq_v ] ; rewrite Heq_u, Heq_v in *.\n  clear Heq_u Heq_v u v ; split ; [ | split ].\n  split ; intro H ; inversion H.\n  intros a u H ; apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ s [ Heq H ] ] ; apply step_star_fmt in H.\n  destruct H as [ H | H ].\n  destruct H as [ p' [ Heq' Hstep ] ].\n  replace s with (p' · p * q) in * by ( inversion Heq' ; auto ).\n  exists (emb (p' · p * (q · r))) ; split ; eauto.\n  apply step_star_left ; auto.\n  destruct H as [ [ Heq' Hstep ] | Hstep ].\n  exists (emb (p * (q · r))) ; split ; auto.\n  apply step_star_term ; auto.\n  replace s with (p * q) in * by ( inversion Heq' ; auto ) ; auto.\n  exists (emb (s · r)) ; split ; auto.\n  apply step_star_right ; apply step_mult_left ; auto.\n  exists (emb r) ; split ; tauto || auto.\n  apply step_star_right ; destruct H as [ Hstep Heq ].\n  inversion Hstep ; apply step_mult_right ; auto.\n  intros a u H ; apply step_star_fmt in H.\n  destruct H as [ H | [ H | H ] ].\n  destruct H as [ p' [ Heq Hstep ] ].\n  exists (emb ((p' · p * q) · r)) ; split ; eauto.\n  apply step_mult_left ; apply step_star_left ; auto.\n  destruct H as [ Heq Hstep ].\n  exists (emb (p * q · r)) ; split ; auto.\n  apply step_mult_left ; apply step_star_term ; auto.\n  exists u ; split ; auto.\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ q' [ Heq Hstep ] ] ; rewrite Heq in *.\n  apply step_mult_left ; apply step_star_right ; auto.\n  destruct H as [ Hstep Heq ] ; rewrite Heq in *.\n  apply step_mult_right ; apply step_star_right ; auto.\n  destruct H as [ p' [ Heq_u Heq_v ] ] ; rewrite Heq_u, Heq_v in *.\n  clear Heq_u Heq_v u v ; split ; [ | split ].\n  split ; intro H ; inversion H.\n  intros a u H ; apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ s [ Heq Hstep ] ] ; rewrite Heq in *.\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ p'' [ Heq' Hstep ] ].\n  replace s with (p'' · p * q) in * by ( inversion Heq' ; auto ).\n  exists (emb (p'' · p * (q · r))) ; split ; eauto.\n  apply step_mult_left ; auto.\n  destruct H as [ Hstep Heq' ].\n  replace s with (p * q) in * by ( inversion Heq' ; auto ).\n  exists (emb (p * (q · r))) ; split ; auto.\n  apply step_mult_right ; auto.\n  destruct H as [ Hstep Heq ] ; inversion Hstep.\n  intros a u H ; apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ p'' [ Heq Hstep ] ] ; rewrite Heq in *.\n  exists (emb ((p'' · p * q) · r)) ; split ; eauto.\n  apply step_mult_left ; apply step_mult_left ; auto.\n  destruct H as [ Hstep Heq ] ; rewrite Heq in *.\n  exists (emb (p * q · r)) ; split ; auto.\n  apply step_mult_left ; apply step_mult_right ; auto.\n  rewrite H in * ; split ; [ tauto | split ] ; intros ; eauto.\nQed.\n\nLemma ex_clos_bisim : forall (R : V -> V -> Prop),\n  bisimR R -> bisimR (exRclos R).\nProof.\n  intros R HbisimR ; unfold bisimR in *.\n  intros u v H ; destruct H as [ n HexR ] ; revert HexR ; revert u v.\n  induction n ; intros u v HexR.\n  simpl in HexR ; apply HbisimR in HexR ; split ; [ | split ] ; try tauto.\n  intros a u' Hstep ; apply HexR in Hstep.\n  destruct Hstep as [ v' [ Hstep HR ] ] ; exists v' ; split ; auto.\n  exists 0%nat ; simpl ; auto.\n  intros a v' Hstep ; apply HexR in Hstep.\n  destruct Hstep as [ u' [ Hstep HR ] ] ; exists u' ; split ; auto.\n  exists 0%nat ; simpl ; auto.\n  simpl in HexR ; destruct HexR as [ w [ Hclos HR ] ].\n  apply IHn in Hclos ; apply HbisimR in HR.\n  split ; [ | split ] ; try tauto.\n  intros a u' Hstep ; apply Hclos in Hstep.\n  destruct Hstep as [ w' [ Hstep Hclos' ] ].\n  apply HR in Hstep ; destruct Hstep as [ v' [ Hstep HR' ] ].\n  exists v' ; split ; auto.\n  destruct Hclos' as [ k Hclos' ].\n  exists (S k) ; simpl ; eauto.\n  intros a v' Hstep ; apply HR in Hstep.\n  destruct Hstep as [ w' [ Hstep HR' ] ].\n  apply Hclos in Hstep ; destruct Hstep as [ u' [ Hstep Hclos' ] ].\n  exists u' ; split ; auto.\n  destruct Hclos' as [ k Hclos' ].\n  exists (S k) ; simpl ; eauto.\nQed.\n\nLemma RSP_sound : forall (p q r : T), \n  emb p <=> emb (q · p + r) -> emb p <=> emb (q * r).\nProof.\n  intros p q r H ; destruct H as [ R [ HinR HrelR ] ].\n  assert (bisimR (exRclos R)) as Hex_bisim.\n  apply ex_clos_bisim ; unfold bisimR ; auto.\n  exists (fun u v => u = emb p /\\ v = emb (q * r) \\/\n    (exists (p' q' : T), u = emb p' /\\ v = emb (q' · q * r) /\\\n      exRclos R (emb p') (emb (q' · p))) \\/\n    (exists (p' : T), u = emb p' /\\ v = emb (q * r) /\\\n      exRclos R (emb p') (emb p)) \\/ exRclos R u v) ; split ; auto.\n\n  (* Start case, i.e. p and q * r *)\n  intros u v H ; destruct H as [ [ Heq_u Heq_v ] | H ].\n  rewrite Heq_u, Heq_v in * ; clear Heq_u Heq_v u v ; split ; [ | split ].\n  split ; intro H ; inversion H.\n  intros a u Hstep ; apply HrelR in HinR ; apply HinR in Hstep.\n  destruct Hstep as [ v [ Hstep HR ] ] ; apply step_plus_fmt in Hstep.\n  destruct Hstep as [ Hstep | Hstep ].\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ q' [ Heq Hstep ] ] ; rewrite Heq in *.\n  exists (emb (q' · q * r)) ; split.\n  apply step_star_left ; auto.\n  destruct u as [ | p' ].\n  apply HrelR in HR ; assert (term = term) as H by auto.\n  apply HR in H ; inversion H.\n  right ; left ; exists p' ; exists q' ; split ; [ | split ] ; auto.\n  exists 0%nat ; simpl ; auto.\n  destruct H as [ Hstep_q Heq ] ; rewrite Heq in *.\n  destruct u as [ | p' ].\n  apply HrelR in HR ; assert (term = term) as H by auto.\n  apply HR in H ; inversion H.\n  exists (emb (q * r)) ; split ; apply step_star_term || auto ; auto.\n  right ; right ; left ; exists p' ; split ; [ | split ] ; auto.\n  exists 0%nat ; simpl ; auto.\n  exists v ; split ; apply step_star_right || auto ; auto.\n  right ; right ; right ; exists 0%nat ; simpl ; auto.\n  intros a v H ; apply step_star_fmt in H ; destruct H as [ H | [ H | ] ].\n  destruct H as [ q' [ Heq Hstep ] ] ; rewrite Heq in *.\n  assert (emb (q · p + r) -(a)-> emb (q' · p)) as Hstep_qp by\n    ( apply step_plus_left ; apply step_mult_left ; auto ).\n  apply HrelR in HinR ; apply HinR in Hstep_qp.\n  destruct Hstep_qp as [ u [ Hstep_p HR ] ].\n  destruct u as [ | p' ] ; [ apply HrelR in HR | ].\n  assert (term = term) as H by auto ; apply HR in H ; inversion H.\n  exists (emb p') ; split ; auto.\n  right ; left ; exists p' ; exists q' ; split ; [ | split ] ; auto.\n  exists 0%nat ; simpl ; auto.\n  destruct H as [ Heq Hstep_q ] ; rewrite Heq in *.\n  assert (emb (q · p + r) -(a)-> emb p) as H by\n    ( apply step_plus_left ; apply step_mult_right ; auto ).\n  apply HrelR in HinR ; apply HinR in H.\n  destruct H as [ u [ Hstep_p HR ] ].\n  destruct u as [ | p' ] ; [ apply HrelR in HR | ].\n  assert (term = term) as H by auto ; apply HR in H ; inversion H.\n  exists (emb p') ; split ; auto.\n  right ; right ; left ; exists p' ; split ; [ | split ] ; auto.\n  exists 0%nat ; simpl ; auto.\n  assert (emb (q · p + r) -(a)-> v) as Hstep by\n    ( apply step_plus_right ; auto ).\n  apply HrelR in HinR ; apply HinR in Hstep.\n  destruct Hstep as [ u [ Hstep HR ] ] ; exists u ; split ; auto.\n  right ; right ; right ; exists 0%nat ; simpl ; auto.\n\n  (* Case for (p', q'q * r) such that (p', q'p) in R-closure *)\n  destruct H as [ H | H ].\n  destruct H as [ p' [ q' [ Heq_u [ Heq_v HRclos ] ] ] ].\n  rewrite Heq_u, Heq_v in * ; clear Heq_u Heq_v u v.\n  apply Hex_bisim in HRclos ; split ; [ | split ].\n  split ; intro H ; inversion H.\n  intros a u Hstep ; apply HRclos in Hstep.\n  destruct Hstep as [ v [ Hstep HexR ] ].\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ q'' [ Heq Hstep ] ] ; rewrite Heq in *.\n  exists (emb (q'' · q * r)) ; split ; auto.\n  apply step_mult_left ; auto.\n  destruct u as [ | p'' ] ; [ apply Hex_bisim in HexR | ].\n  assert (term = term) as H by auto ; apply HexR in H ; inversion H.\n  right ; left ; exists p'' ; exists q'' ; split ; [ | split ] ; auto.\n  destruct H as [ Hstep Heq ] ; rewrite Heq in *.\n  exists (emb (q * r)) ; split ; auto.\n  apply step_mult_right ; auto.\n  destruct u as [ | p'' ] ; [ apply Hex_bisim in HexR | ].\n  assert (term = term) as H by auto ; apply HexR in H ; inversion H.\n  right ; right ; left ; exists p'' ; split ; [ | split ] ; auto.\n  intros a v H ; apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ q'' [ Heq Hstep ] ] ; rewrite Heq in *.\n  assert (emb (q' · p) -(a)-> emb (q'' · p)) as H by\n    ( apply step_mult_left ; auto ).\n  apply HRclos in H ; destruct H as [ u [ Hstep' HclosR ] ].\n  destruct u as [ | p'' ].\n  apply ex_clos_bisim in HclosR ; auto.\n  assert (term = term) as H by auto ; apply HclosR in H ; inversion H.\n  exists (emb p'') ; split ; auto.\n  right ; left ; exists p'' ; exists q'' ; split ; auto.\n  destruct H as [ Hstep_q' Heq ] ; rewrite Heq in *.\n  assert (emb (q' · p) -(a)-> emb p) as H by ( apply step_mult_right ; auto ).\n  apply HRclos in H ; destruct H as [ u [ Hstep_p' Hclos' ] ].\n  destruct u as [ | p'' ].\n  apply ex_clos_bisim in Hclos' ; auto.\n  assert (term = term) as H by auto ; apply Hclos' in H ; inversion H.\n  exists (emb p'') ; split ; auto.\n  right ; right ; left ; eauto.\n\n  (* Case for (p', q * r) such that (p', p) in R-closure *)\n  destruct H as [ H | H ].\n  destruct H as [ p' [ Heq_u [ Heq_v Hclos ] ] ].\n  rewrite Heq_u, Heq_v in * ; clear Heq_u Heq_v u v ; split ; [ | split ].\n  split ; intro H ; inversion H.\n  intros a u Hstep ; apply ex_clos_bisim in Hclos ; auto.\n  apply Hclos in Hstep ; destruct Hstep as [ v [ Hstep Hclos' ] ].\n  apply HrelR in HinR ; apply HinR in Hstep.\n  destruct Hstep as [ w [ Hstep HR' ] ].\n  apply step_plus_fmt in Hstep ; destruct Hstep as [ H | Hstep ].\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ q' [ Heq Hstep_q ] ] ; rewrite Heq in *.\n  exists (emb (q' · q * r)) ; split ; auto.\n  apply step_star_left ; auto.\n  right ; left ; destruct u as [ | p'' ].\n  destruct v as [ | r' ].\n  apply HrelR in HR' ; assert (term = term) as H by auto.\n  apply HR' in H ; inversion H.\n  apply ex_clos_bisim in Hclos' ; auto.\n  assert (term = term) as H by auto ; apply Hclos' in H ; inversion H.\n  exists p'' ; exists q' ; split ; [ | split ] ; eauto.\n  destruct Hclos' as [ k H ] ; exists (S k) ; simpl ; eauto.\n  destruct H as [ Hstep Heq ] ; rewrite Heq in *.\n  exists (emb (q * r)) ; split ; [ apply step_star_term | ] ; auto.\n  right ; right ; left ; destruct u as [ | p'' ].\n  destruct v as [ | r' ].\n  apply HrelR in HR' ; assert (term = term) as H by auto.\n  apply HR' in H ; inversion H.\n  apply ex_clos_bisim in Hclos' ; auto.\n  assert (term = term) as H by auto ; apply Hclos' in H ; inversion H.\n  exists p'' ; split ; [ | split ] ; auto.\n  destruct Hclos' as [ k Hclos' ].\n  exists (S k) ; simpl ; eauto.\n  exists w ; split ; [ apply step_star_right | ] ; auto.\n  right ; right ; right.\n  destruct Hclos' as [ k Hclos' ].\n  exists (S k) ; simpl ; eauto.\n  intros a v Hstep ; apply step_star_fmt in Hstep.\n  destruct Hstep as [ H | [ H | H ] ].\n  destruct H as [ q' [ Heq Hstep ] ] ; rewrite Heq in *.\n  assert (emb (q · p + r) -(a)-> emb (q' · p)) as H by\n    ( apply step_plus_left ; apply step_mult_left ; auto ).\n  apply HrelR in HinR ; apply HinR in H.\n  destruct H as [ u [ Hstep' HR' ] ].\n  apply Hex_bisim in Hclos ; apply Hclos in Hstep'.\n  destruct Hstep' as [ w [ Hstep' Hclos' ] ] ; exists w ; split ; auto.\n  right ; left ; destruct w as [ | p'' ].\n  destruct u as [ | r' ] ; apply HrelR in HR' ; auto.\n  assert (term = term) as H by auto ; apply HR' in H ; inversion H.\n  apply Hex_bisim in Hclos' ; assert (term = term) as H by auto.\n  apply Hclos' in H ; inversion H.\n  exists p'' ; exists q' ; split ; [ | split ] ; auto.\n  destruct Hclos' as [ k Hclos' ] ; exists (S k) ; simpl ; eauto.\n  destruct H as [ Heq Hstep ] ; rewrite Heq in *.\n  assert (emb (q · p + r) -(a)-> emb p) as H by\n    ( apply step_plus_left ; apply step_mult_right ; auto ).\n  apply HrelR in HinR ; apply HinR in H.\n  destruct H as [ u [ Hstep' HR' ] ].\n  apply Hex_bisim in Hclos ; apply Hclos in Hstep'.\n  destruct Hstep' as [ w [ Hstep' Hclos' ] ] ; exists w ; split ; auto.\n  right ; right ; left ; destruct w as [ | p'' ].\n  destruct u as [ | r' ] ; apply HrelR in HR'.\n  assert (term = term) as H by auto ; apply HR' in H ; inversion H.\n  apply Hex_bisim in Hclos' ; assert (term = term) as H by auto.\n  apply Hclos' in H ; inversion H.\n  exists p'' ; split ; [ | split ] ; auto.\n  destruct Hclos' as [ k Hclos' ] ; exists (S k) ; simpl ; eauto.\n  assert (emb (q · p + r) -(a)-> v) as Hstep by\n    ( apply step_plus_right ; auto ).\n  apply HrelR in HinR ; apply HinR in Hstep.\n  destruct Hstep as [ u [ Hstep HR' ] ].\n  apply Hex_bisim in Hclos ; apply Hclos in Hstep.\n  destruct Hstep as [ w [ Hstep Hclos' ] ].\n  exists w ; split ; auto.\n  right ; right ; right ; destruct Hclos' as [ k Hclos' ].\n  exists (S k) ; simpl ; eauto.\n\n  (* Final and simplest case: (u,v) in R-closure *)\n  apply Hex_bisim in H ; split ; [ | split ] ; tauto || auto.\n  intros a u' Hstep ; apply H in Hstep.\n  destruct Hstep as [ v' [ Hstep Hclos ] ] ; exists v' ; split ; auto.\n  intros a v' Hstep ; apply H in Hstep.\n  destruct Hstep as [ u' [ Hstep Hclos ] ] ; exists u' ; split ; auto.\nQed.\n\nLemma soundness : forall (p q : T), p == q -> emb p <=> emb q.\nProof.\n  intros p q H ; induction H.\n  apply bisim_refl.\n  apply bisim_symm ; auto.\n  apply bisim_trans with (emb y) ; auto.\n  apply bisim_comp_plus ; auto.\n  apply bisim_comp_mult ; auto.\n  apply bisim_comp_star ; auto.\n  apply B1_sound.\n  apply B2_sound.\n  apply B3_sound.\n  apply B4_sound.\n  apply B5_sound.\n  apply B6_sound.\n  apply B7_sound.\n  apply BKS1_sound.\n  apply BKS2_sound.\n  apply RSP_sound ; auto.\nQed.\n\nLemma in_mult_list_term : forall (L : list (A * V)) (a : A) (q : T),\n  In (a, term) L -> In (a, emb q) (mult_list L q).\nProof.\n  intro L ; induction L as [ | [ a u ] ] ; intros a' q Hin ; simpl in * ; auto.\n  destruct u as [ | p ] ; [ destruct Hin as [ H | H ] | ].\n  replace a' with a in * by ( inversion H ; auto ) ; simpl ; auto.\n  apply IHL with (q := q) in H ; simpl ; auto.\n  destruct Hin as [ H | H ] ; [ inversion H | simpl ; right ; auto ].\nQed.\n\nLemma in_mult_list_mult : forall (L : list (A * V)) (a : A) (p q : T),\n  In (a, emb p) L -> In (a, emb (p · q)) (mult_list L q).\nProof.\n  intro L ; induction L as [ | [ a u ] ] ; intros a' p q Hin ; simpl in *; auto.\n  destruct u as [ | r ] ; [ destruct Hin as [ H | H ] ; [ inversion H | ] | ].\n  apply IHL with (q := q) in H ; simpl ; auto.\n  destruct Hin as [ H | H ] ; [ | simpl ; right ; auto ].\n  replace r with p in * by ( inversion H ; auto ).\n  replace a' with a in * by ( inversion H ; auto ).\n  simpl in * ; auto.\nQed.\n\nLemma in_mult_list_cases : forall (L : list (A * V)) (a : A) (u : V) (q : T),\n  In (a, u) (mult_list L q) -> u = emb q /\\ In (a, term) L \\/\n    exists (p : T), u = emb (p · q) /\\ In (a, emb p) L.\nProof.\n  intro L ; induction L as [ | [ a v ] L ] ; \n    intros a' u q Hin ; simpl in * ; contradiction || auto.\n  destruct v as [ | s ] ; simpl in *.\n  destruct Hin as [ H | H ] ; auto.\n  replace a' with a in * by ( inversion H ; auto ).\n  replace u with (emb q) in * by ( inversion H ; auto ) ; tauto.\n  apply IHL in H ; destruct H as [ H | H ] ; [ tauto | ].\n  destruct H as [ p [ Heq Hin ] ] ; rewrite Heq in * ; eauto.\n  destruct Hin as [ H | H ].\n  replace a' with a in * by ( inversion H ; auto ).\n  replace u with (emb (s · q)) in * by ( inversion H ; auto ).\n  right ; exists s ; split ; auto.\n  apply IHL in H ; destruct H as [ H | H ] ; [ tauto | ].\n  destruct H as [ p [ Heq Hin ] ] ; rewrite Heq in *.\n  right ; exists p ; split ; auto.\nQed.\n  \nLemma sum_app : forall (M N : list (A * V)), sum (M ++ N) == (sum M + sum N).\nProof.\n  intro M ; induction M as [ | [ a u ] M ] ; intro N ; simpl.\n  apply symm ; apply trans with (sum N + 0) ; apply B1 || apply B6.\n  destruct u as [ | p ].\n  apply trans with (act a + (sum M + sum N)).\n  apply comp_plus ; apply refl || auto.\n  apply symm ; apply B2.\n  apply trans with (act a · p + (sum M + sum N)).\n  apply comp_plus ; apply refl || auto.\n  apply symm ; apply B2.\nQed.\n\nLemma sum_mult_list : forall (M : list (A * V)) (q : T),\n  sum (mult_list M q) == (sum M · q).\nProof.\n  intro M ; induction M as [ | [ a u ] ] ; intro q ; simpl.\n  apply symm ; apply B7.\n  destruct u as [ | p ] ; simpl.\n  apply trans with (act a · q + sum M · q).\n  apply comp_plus ; apply refl || auto.\n  apply symm ; apply B4.\n  apply trans with ((act a · p) · q + sum M · q).\n  apply comp_plus ; auto.\n  apply symm ; apply B5.\n  apply symm ; apply B4.\nQed.\n\nLemma summation : forall (p : T), exists (L : list (A * V)), \n  (forall (a : A) (u :V), emb p -(a)-> u <-> In (a, u) L) /\\ sum L == p.\nProof.\n  intro p ; induction p.\n  exists nil ; split ; simpl ; apply refl || auto.\n  intros a u ; split ; intro H ; contradiction || inversion H.\n  exists ((a, term) :: nil) ; split ; simpl ; [ | apply B6 ].\n  intros a' u ; split ; intro H ; [ inversion H ; auto | ].\n  destruct H as [ H | H ] ; contradiction || auto.\n  replace a' with a in * by ( inversion H ; auto ).\n  replace u with term in * by ( inversion H ; auto ).\n  apply step_act ; auto.\n\n  (* Case for p1 + p2 starts here *)\n  destruct IHp1 as [ L1 [ Hiff_L1 Hsum_L1 ] ].\n  destruct IHp2 as [ L2 [ Hiff_L2 Hsum_L2 ] ].\n  exists (L1 ++ L2) ; split.\n  intros a u ; split ; intro H.\n  apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply in_or_app ; left ; apply Hiff_L1 ; auto.\n  apply in_or_app ; right ; apply Hiff_L2 ; auto.\n  apply in_app_or in H ; destruct H as [ H | H ].\n  apply step_plus_left ; apply Hiff_L1 ; auto.\n  apply step_plus_right ; apply Hiff_L2 ; auto.\n  apply trans with (sum L1 + sum L2) ; [ apply sum_app | ].\n  apply comp_plus ; auto.\n\n  (* Case for p1 · p2 starts here *)\n  destruct IHp1 as [ L1 [ Hiff_L1 Hsum_L1 ] ].\n  exists (mult_list L1 p2) ; split.\n  intros a u ; split ; intro H.\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ p' [ Heq H ] ] ; rewrite Heq in *.\n  apply in_mult_list_mult ; apply Hiff_L1 in H ; auto.\n  destruct H as [ H Heq ] ; rewrite Heq in *.\n  apply in_mult_list_term ; apply Hiff_L1 ; auto.\n  apply in_mult_list_cases in H.\n  destruct H as [ [ Heq H ] | [ p [ Heq H ] ] ] ; rewrite Heq in *.\n  apply Hiff_L1 in H ; apply step_mult_right ; auto.\n  apply step_mult_left ; apply Hiff_L1 ; auto.\n  apply trans with (sum L1 · p2).\n  apply sum_mult_list.\n  apply comp_mult ; apply refl || auto.\n\n  (* Case for p1 * p2 starts here *)\n  destruct IHp1 as [ L1 [ Hiff_L1 Hsum_L1 ] ].\n  destruct IHp2 as [ L2 [ Hiff_L2 Hsum_L2 ] ].\n  exists (mult_list L1 (p1 * p2) ++ L2) ; split.\n  intros a u ; split ; intro H.\n  apply step_star_fmt in H ; destruct H as [ H | [ H | H ] ].\n  destruct H as [ p' [ Heq H ] ] ; rewrite Heq in *.\n  apply in_or_app ; left ; apply in_mult_list_mult ; apply Hiff_L1 ; auto.\n  destruct H as [ Heq H ] ; rewrite Heq in *.\n  apply in_or_app ; left ; apply in_mult_list_term ; apply Hiff_L1 ; auto.\n  apply in_or_app ; right ; apply Hiff_L2 ; auto.\n  apply in_app_or in H ; destruct H as [ H | H ].\n  apply in_mult_list_cases in H ; destruct H as [ H | H ].\n  destruct H as [ Heq H ] ; rewrite Heq in *.\n  apply Hiff_L1 in H ; apply step_star_term ; auto.\n  destruct H as [ p [ Heq H ] ] ; rewrite Heq in *.\n  apply step_star_left ; apply Hiff_L1 ; auto.\n  apply step_star_right ; apply Hiff_L2 ; auto.\n  apply trans with (p1 · p1 * p2 + p2) ; [ | apply BKS1 ].\n  apply trans with (sum (mult_list L1 (p1 * p2)) + sum L2) ; \n    [ apply sum_app | apply comp_plus ; auto ].\n  apply trans with (sum L1 · p1 * p2).\n  apply sum_mult_list ; auto.\n  apply comp_mult ; apply refl || auto.\nQed.\n\nLemma clos_end_step : forall (p q r : T) (a : A),\n  p -->+ q -> emb q -(a)-> emb r -> p -->+ r.\nProof.\n  intros p q r a H H'.\n  destruct H as [ a' [ s [ Hstep Htr ] ] ].\n  exists a' ; exists s ; split ; auto.\n  clear Hstep p a' ; revert H' ; revert a r.\n  induction Htr ; intros a' s Hstep.\n  apply clos_trans with s a' ; apply clos_refl || auto.\n  apply IHHtr in Hstep.\n  apply clos_trans with q a ; auto.\nQed.\n\nLemma congruence : forall (p q r : T), emb (p · r) <=> emb (q · r) ->\n  congr (p + q) r -> emb p <=> emb q.\nProof.\n  intros p q r Hbisim Hcongr.\n  destruct Hbisim as [ R [ HinR HrelR ] ].\n  exists (fun u v => u = term /\\ v = term \\/ u = emb p /\\ v = emb q \\/\n    exists (p' q' : T), u = emb p' /\\ v = emb q' /\\ p -->+ p' /\\\n      q -->+ q' /\\ R (emb (p' · r)) (emb (q' · r))) ; split ; auto.\n  intros x y H ; destruct H as [ H | [ H | H ] ].\n  destruct H as [ Heq_x Heq_y ] ; rewrite Heq_x, Heq_y in *.\n  split ; [ tauto | split ; intros a u H ; inversion H ].\n\n  (* Case for p, q (i.e. start case) *)\n  destruct H as [ Heq_x Heq_y ] ; rewrite Heq_x, Heq_y in *.\n  split ; [ split ; intro H ; inversion H | split ].\n  intros a u H ; assert (emb p -(a)-> u) as Hstep_bak by auto.\n  apply step_gen_cases in H.\n  destruct H as [ H | H ].\n  destruct H as [ p' [ Heq H ] ] ; rewrite Heq in *.\n  assert (emb (p · r) -(a)-> emb (p' · r)) as Hstep by\n    ( apply step_mult_left ; auto ).\n  apply HrelR in HinR ; apply HinR in Hstep.\n  destruct Hstep as [ v [ Hstep HR ] ].\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H' | H' ].\n  destruct H' as [ q' [ Heq' Hstep ] ] ; rewrite Heq' in *.\n  exists (emb q') ; split ; auto.\n  right ; right ; exists p' ; exists q' ; split ; auto ; split ; auto ; split.\n  exists a ; exists p' ; split ; auto ; apply clos_refl.\n  split ; [ exists a ; exists q' ; split ; auto ; apply clos_refl | auto ].\n  destruct H' as [ Hstep Heq' ] ; rewrite Heq' in *.\n  assert (emb (p' · r) <=> emb r) as Hbisim by ( exists R ; split ; auto ).\n  apply Hcongr in Hbisim ; contradiction || auto.\n  exists a ; exists p' ; split ; apply clos_refl || auto.\n  apply step_plus_left ; auto.\n  rewrite H in * ; clear H u.\n  assert (emb (p · r) -(a)-> emb r) as Hstep by \n    ( apply step_mult_right ; auto ).\n  apply HrelR in HinR ; apply HinR in Hstep.\n  destruct Hstep as [ v [ Hstep HR ] ].\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ q' [ Heq Hstep ] ] ; rewrite Heq in *.\n  assert (emb (q' · r) <=> emb r) as Hbisim.\n  apply bisim_symm ; exists R ; split ; auto.\n  apply Hcongr in Hbisim ; contradiction || auto.\n  exists a ; exists q' ; split ; apply clos_refl || auto.\n  apply step_plus_right ; auto.\n  destruct H as [ Hstep Heq ] ; rewrite Heq in *.\n  exists term ; split ; auto.\n  intros a u H ; assert (emb q -(a)-> u) as Hstep_bak by auto.\n  apply step_gen_cases in H.\n  destruct H as [ H | H ].\n  destruct H as [ q' [ Heq H ] ] ; rewrite Heq in *.\n  assert (emb (q · r) -(a)-> emb (q' · r)) as Hstep by\n    ( apply step_mult_left ; auto ).\n  apply HrelR in HinR ; apply HinR in Hstep.\n  destruct Hstep as [ v [ Hstep HR ] ].\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H' | H' ].\n  destruct H' as [ p' [ Heq' Hstep ] ] ; rewrite Heq' in *.\n  exists (emb p') ; split ; auto.\n  right ; right ; exists p' ; exists q' ; split ; auto ; split ; auto ; split.\n  exists a ; exists p' ; split ; auto ; apply clos_refl.\n  split ; [ exists a ; exists q' ; split ; auto ; apply clos_refl | auto ].\n  destruct H' as [ Hstep Heq' ] ; rewrite Heq' in *.\n  assert (emb (q' · r) <=> emb r) as Hbisim by \n    ( apply bisim_symm ; exists R ; split ; auto ).\n  apply Hcongr in Hbisim ; contradiction || auto.\n  exists a ; exists q' ; split ; apply clos_refl || auto.\n  apply step_plus_right ; auto.\n  rewrite H in * ; clear H u.\n  assert (emb (q · r) -(a)-> emb r) as Hstep by \n    ( apply step_mult_right ; auto ).\n  apply HrelR in HinR ; apply HinR in Hstep.\n  destruct Hstep as [ v [ Hstep HR ] ].\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ p' [ Heq Hstep ] ] ; rewrite Heq in *.\n  assert (emb (p' · r) <=> emb r) as Hbisim by ( exists R ; split ; auto ).\n  apply Hcongr in Hbisim ; contradiction || auto.\n  exists a ; exists p' ; split ; apply clos_refl || auto.\n  apply step_plus_left ; auto.\n  destruct H as [ Hstep Heq ] ; rewrite Heq in *.\n  exists term ; split ; auto.\n\n  (* Case for p',q' (i.e. such that R (p'r) (q'r) *)\n  destruct H as [ p' [ q' [ Heq_x [ Heq_y H ] ] ] ].\n  rewrite Heq_x, Heq_y in * ; destruct H as [ Hp [ Hq HR ] ].\n  split ; [ split ; intro H ; inversion H | split ].\n  intros a u H ; assert (emb p' -(a)-> u) as Hstep_bak by auto.\n  apply step_gen_cases in H.\n  destruct H as [ [ p'' [ Heq_u H ] ] | Heq_u ].\n  assert (emb (p' · r) -(a)-> emb (p'' · r)) as Hstep by\n    ( apply step_mult_left ; auto ).\n  apply HrelR in HR ; apply HR in Hstep.\n  destruct Hstep as [ v [ Hstep HR' ] ].\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H' | H' ].\n  destruct H' as [ q'' [ Heq_v Hstep ] ] ; rewrite Heq_v in *.\n  exists (emb q'') ; split ; auto ; right ; right.\n  exists p'' ; exists q'' ; repeat split ; auto.\n  apply clos_end_step with p' a ; auto.\n  apply clos_end_step with q' a ; auto.\n  destruct H' as [ Hstep Heq_v ] ; rewrite Heq_v in *.\n  assert (emb (p'' · r) <=> emb r) as Hbisim by\n    ( exists R ; split ; auto ).\n  apply Hcongr in Hbisim ; contradiction || auto.\n  apply clos_end_step with p' a ; auto.\n  destruct Hp as [ a' [ s [ Hstep' Htr ] ] ].\n  exists a' ; exists s ; split ; auto.\n  apply step_plus_left ; auto.\n  rewrite Heq_u in *.\n  assert (emb (p' · r) -(a)-> emb r) as Hstep by\n    ( apply step_mult_right ; auto ).\n  apply HrelR in HR ; apply HR in Hstep.\n  destruct Hstep as [ v [ Hstep HR' ] ].\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ q'' [ Heq_v Hstep ] ] ; rewrite Heq_v in *.\n  assert (emb (q'' · r) <=> emb r) as Hbisim by\n    ( apply bisim_symm ; exists R ; split ; auto ).\n  apply Hcongr in Hbisim ; contradiction || auto.\n  apply clos_end_step with q' a ; auto.\n  destruct Hq as [ a' [ s [ Hstep' Htr ] ] ].\n  exists a' ; exists s ; split ; apply step_plus_right || auto ; auto.\n  destruct H as [ Hstep Heq_v ] ; rewrite Heq_v in *.\n  exists term ; split ; auto.\n  intros a u H ; assert (emb q' -(a)-> u) as Hstep_bak by auto.\n  apply step_gen_cases in H.\n  destruct H as [ [ q'' [ Heq_u H ] ] | Heq_u ].\n  assert (emb (q' · r) -(a)-> emb (q'' · r)) as Hstep by\n    ( apply step_mult_left ; auto ).\n  apply HrelR in HR ; apply HR in Hstep.\n  destruct Hstep as [ v [ Hstep HR' ] ].\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H' | H' ].\n  destruct H' as [ p'' [ Heq_v Hstep ] ] ; rewrite Heq_v in *.\n  exists (emb p'') ; split ; auto ; right ; right.\n  exists p'' ; exists q'' ; repeat split ; auto.\n  apply clos_end_step with p' a ; auto.\n  apply clos_end_step with q' a ; auto.\n  destruct H' as [ Hstep Heq_v ] ; rewrite Heq_v in *.\n  assert (emb (q'' · r) <=> emb r) as Hbisim by\n    ( apply bisim_symm ; exists R ; split ; auto ).\n  apply Hcongr in Hbisim ; contradiction || auto.\n  apply clos_end_step with q' a ; auto.\n  destruct Hq as [ a' [ s [ Hstep' Htr ] ] ].\n  exists a' ; exists s ; split ; auto.\n  apply step_plus_right ; auto.\n  rewrite Heq_u in *.\n  assert (emb (q' · r) -(a)-> emb r) as Hstep by\n    ( apply step_mult_right ; auto ).\n  apply HrelR in HR ; apply HR in Hstep.\n  destruct Hstep as [ v [ Hstep HR' ] ].\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ p'' [ Heq_v Hstep ] ] ; rewrite Heq_v in *.\n  assert (emb (p'' · r) <=> emb r) as Hbisim by\n    ( exists R ; split ; auto ).\n  apply Hcongr in Hbisim ; contradiction || auto.\n  apply clos_end_step with p' a ; auto.\n  destruct Hp as [ a' [ s [ Hstep' Htr ] ] ].\n  exists a' ; exists s ; split ; apply step_plus_left || auto ; auto.\n  destruct H as [ Hstep Heq_v ] ; rewrite Heq_v in *.\n  exists term ; split ; auto.\nQed.\n\nLemma comp_plus_left : forall (p q r : T), \n  congr p r -> congr q r -> congr (p + q) r.\nProof.\n  intros p q r Hp Hq t Hplus Hbisim.\n  destruct Hplus as [ a [ s [ Hstep Htr ] ] ].\n  apply step_plus_fmt in Hstep ; destruct Hstep as [ Hstep | Hstep ].\n  apply Hp with t ; auto.\n  exists a ; exists s ; split ; auto.\n  apply Hq with t ; auto.\n  exists a ; exists s ; split ; auto.\nQed.\n\nLemma congr_right_compat : forall (p q r : T),\n  congr p q -> emb q <=> emb r -> congr p r.\nProof.\n  intros p q r Hcongr Hbisim t Hplus Hbisim' ; apply Hcongr with t ; auto.\n  apply bisim_trans with (emb r) ; [ | apply bisim_symm ; auto ].\n  apply bisim_trans with (emb (t · r)) ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || auto.\nQed.\n\nLemma nf_mult_right_compat : forall (p q r : T),\n  nf_mult p q -> emb q <=> emb r -> nf_mult p r.\nProof.\n  intro p ; induction p ; intros q r Hnf Hbisim ; simpl ; auto.\n  simpl in Hnf ; destruct Hnf as [ Hp1 Hp2 ] ; split.\n  apply IHp1 with q ; auto.\n  apply IHp2 with q ; auto.\n  simpl in Hnf ; destruct Hnf as [ Hp1 Hp2 ] ; split.\n  apply IHp1 with (p2 · q) ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply IHp2 with q ; auto.\n  simpl in Hnf ; destruct Hnf as [ Hp1 [ Hp2 Hcongr ] ] ; split ; [ | split ].\n  apply IHp1 with (p1 * p2 · q) ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply IHp2 with q ; auto.\n  apply congr_right_compat with (p1 * p2 · q) ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || auto.\nQed.\n\nLemma clos_init_cases : forall (p r : T), p -->* r -> p = r \\/\n  exists (a : A) (q : T), emb p -(a)-> emb q /\\ q -->* r.\nProof.\n  intros p r H ; inversion H ; eauto.\nQed.\n\nLemma star_plus_zero_bisim : forall (p q : T),\n  emb ((p * q) * 0) <=> emb ((p + q) * 0).\nProof.\n  intros p q ; apply bisim_symm ; apply RSP_sound.\n  apply bisim_trans with (emb (p * q · (p + q) * 0)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (p * (q · (p + q) * 0))) ; \n    [ | apply bisim_symm ; apply BKS2_sound ].\n  apply RSP_sound ; apply bisim_trans with (emb ((p + q) · (p + q) * 0)).\n  apply bisim_trans with (emb ((p + q) · (p + q) * 0 + 0)) ; \n    apply B6_sound || auto.\n  apply bisim_symm ; apply BKS1_sound.\n  apply B4_sound.\nQed.\n\nLemma star_order_zero_bisim : forall (p q : T),\n  emb ((p · q) * 0) <=> emb (p · (q · p) * 0).\nProof.\n  intros p q ; apply bisim_symm ; apply RSP_sound.\n  apply bisim_trans with (emb ((p · q) · p · (q · p) * 0)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (p · q · p · (q · p) * 0)) ;\n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply bisim_trans with (emb ((q · p) · (q · p) * 0 + 0)).\n  apply bisim_symm ; apply BKS1_sound.\n  apply bisim_trans with (emb ((q · p) · (q · p) * 0)) ; \n    apply B6_sound || apply B5_sound.\nQed.\n\nLemma nf_mult_pres_step : forall (p q r : T) (a : A),\n  nf_mult p r -> emb p -(a)-> emb q -> nf_mult q r.\nProof.\n  intro p ; induction p ; intros q r a' Hnf H ; solve [ inversion H ] || auto.\n  simpl in Hnf ; apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply IHp1 with a' ; tauto.\n  apply IHp2 with a' ; tauto.\n  simpl in Hnf ; apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ p' [ Heq Hstep ] ].\n  replace q with (p' · p2) in * by ( inversion Heq ; auto ).\n  simpl ; split ; try tauto.\n  apply IHp1 with a' ; tauto.\n  destruct H as [ _ H ].\n  replace q with p2 in * by ( inversion H ; auto ) ; tauto.\n  apply step_star_fmt in H ; destruct H as [ H | [ H | H ] ].\n  destruct H as [ p' [ Heq Hstep ] ].\n  replace q with (p' · p1 * p2) in * by ( inversion Heq ; auto ).\n  simpl ; simpl in Hnf ; repeat split ; try tauto.\n  apply IHp1 with a' ; tauto.\n  destruct H as [ H _ ].\n  replace q with (p1 * p2) in * by ( inversion H ; auto ) ; auto.\n  apply IHp2 with a' ; simpl in * ; tauto.\nQed.\n\nLemma nf_mult_pres_clos : forall (p q r : T),\n  nf_mult p r -> p -->* q -> nf_mult q r.\nProof.\n  intros p q r Hnf Htr ; induction Htr ; auto.\n  apply IHHtr ; apply nf_mult_pres_step with (r := r) in H ; auto.\nQed.\n\nLemma nf_mult_pres_plus : forall (p q r : T),\n  nf_mult p r -> p -->+ q -> nf_mult q r.\nProof.\n  intros p q r Hnf H ; destruct H as [ a [ s [ Hstep Htr ] ] ].\n  apply nf_mult_pres_step with (r := r) in Hstep ; auto.\n  apply nf_mult_pres_clos with (r := r) in Htr ; auto.\nQed.\n\nLemma clos_clos : forall (p q r : T),\n  p -->* q -> q -->* r -> p -->* r.\nProof.\n  intros p q r H H' ; induction H ; auto.\n  apply clos_trans with q a ; auto.\nQed.\n\nLemma plus_plus_clos : forall (p q r : T),\n  p -->+ q -> q -->+ r -> p -->+ r.\nProof.\n  intros p q r Hplus H ; destruct H as [ a [ s [ Hstep Htr ] ] ].\n  assert (p -->+ s) as Hplus'.\n  apply clos_end_step with q a ; auto.\n  destruct Hplus' as [ a' [ t [ Hstep' Htr' ] ] ].\n  exists a' ; exists t ; split ; auto.\n  apply clos_clos with s ; auto.\nQed.\n\nLemma congr_pres_plus : forall (p q r : T),\n  congr p r -> p -->+ q -> congr q r.\nProof.\n  intros p q r Hcongr Hplus t Hplus' Hbisim.\n  apply Hcongr with t ; auto.\n  apply plus_plus_clos with q ; auto.\nQed.\n\nLemma depth_pres_step : forall (p q : T) (a : A),\n  emb p -(a)-> emb q -> depth q <= depth p.\nProof.\n  intro p ; induction p ; intros q a' H ; solve [ inversion H ] || auto.\n  apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply IHp1 in H ; simpl ; transitivity (depth p1) ; apply le_max_l || auto.\n  apply IHp2 in H ; simpl ; transitivity (depth p2) ; apply le_max_r || auto.\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ p' [ Heq Hstep ] ] ; apply IHp1 in Hstep.\n  replace q with (p' · p2) in * by ( inversion Heq ; auto ).\n  simpl ; apply max_lub ; apply le_max_r || auto.\n  transitivity (depth p1) ; apply le_max_l || auto.\n  destruct H as [ _ H ].\n  replace q with p2 in * by ( inversion H ; auto ).\n  simpl ; apply le_max_r.\n  apply step_star_fmt in H ; destruct H as [ H | [ H | H ] ].\n  destruct H as [ p' [ Heq Hstep ] ].\n  replace q with (p' · p1 * p2) in * by ( inversion Heq ; auto ).\n  simpl ; destruct (depth p2) as [ | m ] ; apply max_lub ; auto.\n  apply IHp1 in Hstep ; transitivity (depth p1) ; omega || auto.\n  apply IHp1 in Hstep ; transitivity (depth p1) ; auto.\n  rewrite succ_max_distr ; transitivity (S (depth p1)) ; apply le_max_l || auto.\n  destruct H as [ H _ ].\n  replace q with (p1 * p2) in * by ( inversion H ; auto ) ; auto.\n  apply IHp2 in H ; simpl ; destruct (depth p2) as [ | m ] ; omega || auto.\n  transitivity (S m) ; auto.\n  rewrite succ_max_distr ; apply le_max_r.\nQed.\n\nLemma depth_pres_clos : forall (p q : T),\n  p -->* q -> depth q <= depth p.\nProof.\n  intros p q H ; induction H ; auto.\n  apply depth_pres_step in H ; omega.\nQed.\n\nLemma depth_pres_plus : forall (p q : T),\n  p -->+ q -> depth q <= depth p.\nProof.\n  intros p q H ; destruct H as [ a [ r [ Hstep Htr ] ] ].\n  apply depth_pres_step in Hstep ; apply depth_pres_clos in Htr ; omega.\nQed.\n\nLemma mult_clos_fmt : forall (p q r : T), (p · q) -->* r ->\n  (exists (p' : T), r = p' · q /\\ p -->* p') \\/ q -->* r.\nProof.\n  intros p q r H ; assert (exists (s : T), s = p · q) as H' by eauto.\n  destruct H' as [ s Heq ] ; rewrite <- Heq in * ; revert Heq ; revert p q.\n  induction H ; intros t u Heq ; rewrite Heq in *.\n  left ; exists t ; split ; apply clos_refl || auto.\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ v [ Heq' Hstep ] ].\n  replace q with (v · u) in * by ( inversion Heq' ; auto ).\n  destruct (IHclos_step v u) as [ H | H ] ; auto.\n  destruct H as [ w [ Heq'' Htr ] ] ; rewrite Heq'' in *.\n  left ; exists w ; split ; auto.\n  apply clos_trans with v a ; auto.\n  destruct H as [ Hstep Heq' ].\n  replace q with u in * by ( inversion Heq' ; auto ) ; auto.\nQed.\n\nLemma mult_plus_fmt : forall (p q r : T), (p · q) -->+ r ->\n  (exists (p' : T), r = p' · q /\\ p -->+ p') \\/ q = r \\/ q -->+ r.\nProof.\n  intros p q r Hplus ; destruct Hplus as [ a [ s [ Hstep Htr ] ] ].\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ t [ Heq Hstep ] ].\n  replace s with (t · q) in * by ( inversion Heq ; auto ).\n  apply mult_clos_fmt in Htr ; destruct Htr as [ H | H ].\n  destruct H as [ u [ Heq' Htr ] ] ; rewrite Heq' in *.\n  left ; exists u ; split ; auto.\n  exists a ; exists t ; split ; auto.\n  apply clos_init_cases in H ; auto.\n  destruct H as [ Hstep Heq ].\n  replace s with q in * by ( inversion Heq ; auto ).\n  apply clos_init_cases in Htr ; auto.\nQed.\n\nLemma star_clos_fmt_helper : forall (t p q r s : T), \n  (s = p * q \\/ s = t · p * q /\\ p -->+ t) -> s -->* r ->\n    (exists (u : T), p -->+ u /\\ r = u · p * q) \\/ r = p * q \\/ q -->+ r.\nProof.\n  intros t p q r s Hor H ; revert Hor ; revert p q t.\n  induction H ; intros x y t H' ; destruct H' as [ H' | H' ] ; auto.\n  destruct H' as [ Heq Hplus ] ; rewrite Heq in * ; eauto.\n  rewrite H' in * ; apply step_star_fmt in H ; destruct H as [ H | [ H | H ] ].\n  destruct H as [ u [ Heq Hstep ] ].\n  replace q with (u · x * y) in * by ( inversion Heq ; auto ).\n  destruct (IHclos_step x y u) as [ H | [ H | H ] ] ; auto.\n  right ; split ; auto.\n  exists a ; exists u ; split ; apply clos_refl || auto.\n  destruct H as [ Heq Hstep ].\n  replace q with (x * y) in * by ( inversion Heq ; auto ).\n  destruct (IHclos_step x y x) as [ H | [ H | H ] ] ; auto.\n  right ; right ; exists a ; exists q ; split ; auto.\n  destruct H' as [ Heq Hplus ] ; rewrite Heq in *.\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ u [ Heq' Hstep ] ].\n  replace q with (u · x * y) in * by ( inversion Heq' ; auto ).\n  destruct (IHclos_step x y u) as [ H | [ H | H ] ] ; auto.\n  right ; split ; auto.\n  apply clos_end_step with t a ; auto.\n  destruct H as [ Hstep Heq' ].\n  replace q with (x * y) in * by ( inversion Heq' ; auto ).\n  destruct (IHclos_step x y x) as [ H | [ H | H ] ] ; auto.\nQed.\n\nLemma star_clos_fmt : forall (p q r : T), (p * q) -->* r ->\n  (exists (t : T), r = t · p * q /\\ p -->+ t) \\/ r = p * q \\/ q -->+ r.\nProof.\n  intros p q r H ; apply clos_init_cases in H ; destruct H as [ H | H ] ; auto.\n  destruct H as [ a [ s [ Hstep Htr ] ] ].\n  apply step_star_fmt in Hstep ; destruct Hstep as [ H | [ H | H ] ].\n  destruct H as [ p' [ Heq Hstep ] ].\n  replace s with (p' · p * q) in * by ( inversion Heq ; auto ).\n  apply star_clos_fmt_helper with (t := p') (p := p) (q := q) in Htr ; auto.\n  destruct Htr as [ H | H ].\n  destruct H as [ u [ Hplus Heq' ] ] ; rewrite Heq' in * ; eauto.\n  destruct H as [ H | H ] ; [ rewrite H in * | ] ; auto.\n  right ; split ; auto.\n  exists a ; exists p' ; split ; apply clos_refl || auto.\n  destruct H as [ Heq Hstep ].\n  replace s with (p * q) in * by ( inversion Heq ; auto ).\n  apply star_clos_fmt_helper with (t := p) (p := p) (q := q) in Htr ; auto.\n  destruct Htr as [ H | [ H | H ] ] ; auto.\n  destruct H as [ u [ Hplus Heq' ] ] ; eauto.\n  right ; right ; exists a ; exists s ; split ; auto.\nQed.\n\nLemma star_plus_fmt : forall (p q r : T), (p * q) -->+ r ->\n  (exists (t : T), r = t · p * q /\\ p -->+ t) \\/ r = p * q \\/ q -->+ r.\nProof.\n  intros p q r Hplus ; destruct Hplus as [ a [ s [ Hstep Htr ] ] ].\n  apply step_star_fmt in Hstep ; destruct Hstep as [ H | [ H | H ] ].\n  destruct H as [ p' [ Heq Hstep ] ].\n  replace s with (p' · p * q) in * by ( inversion Heq ; auto ).\n  apply star_clos_fmt_helper with (t := p') (p := p) (q := q) in Htr ; auto.\n  destruct Htr as [ H | [ H | H ] ] ; auto.\n  destruct H as [ u [ Hplus Heq' ] ] ; rewrite Heq' in * ; eauto.\n  right ; split ; auto.\n  exists a ; exists p' ; split ; apply clos_refl || auto.\n  destruct H as [ Heq Hstep ].\n  replace s with (p * q) in * by ( inversion Heq ; auto ).\n  apply star_clos_fmt in Htr ; destruct Htr as [ H | [ H | H ] ] ; auto.\n  right ; right ; exists a ; exists s ; split ; auto.\nQed.\n\nLemma comp_mult_ex : forall (p q r : T), nf_mult (p · q) r -> congr q r ->\n  (exists (s : T), emb (p · q · r) <=> emb (s · r) /\\ nf_mult s r /\\\n    congr s r /\\ depth s <= depth (p · q)) \\/\n  (exists (s : T), emb r <=> emb (s · 0) /\\ nf (s · 0) /\\ \n    depth s <= 1 + depth (p · q)).\nProof.\n  intro p ; assert (exists (d : nat), depth p <= d) as H by eauto.\n  destruct H as [ d Heq_depth ] ; revert Heq_depth ; revert p.\n  induction d using strong_ind ; rename H into IHdepth.\n  intro p ; induction p ; intros Heq_depth q r Hnf Hcongr.\n  left ; exists 0 ; split ; [ | split ; [ | split ] ] ; simpl ; omega || auto.\n  apply bisim_trans with (emb 0) ; [ | apply bisim_symm ] ; apply B7_sound.\n  intros t H ; destruct H as [ a [ s [ H _ ] ] ] ; inversion H.\n\n  (* Case for a \\in A *)\n  left ; destruct (LEM (emb (q · r) <=> emb r)) as [ Hbisim | Hnot_bisim ].\n  exists (act a) ; split ; [ | split ; [ | split ] ] ; simpl ; omega || auto.\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  intros t Hplus Hbisim' ; destruct Hplus as [ a' [ s [ H _ ] ] ] ; inversion H.\n  exists (act a · q) ; split ; [ | split ; [ | split ] ] ; \n    simpl ; omega || auto.\n  apply bisim_symm ; apply B5_sound.\n  intros t Hplus Hbisim ; destruct Hplus as [ a' [ s [ Hstep Htr ] ] ].\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ u [ _ H ] ] ; inversion H.\n  destruct H as [ Hstep Heq ].\n  apply clos_init_cases in Htr ; destruct Htr as [ H | H ].\n  rewrite <- H in *.\n  replace s with q in * by ( inversion Heq ; auto ) ; contradiction.\n  destruct H as [ a'' [ u [ Hstep' Htr ] ] ].\n  apply Hcongr with t ; auto.\n  exists a'' ; exists u ; split ; auto.\n  replace s with q in * by ( inversion Heq ; auto ) ; auto.\n\n  (* Case for p1 + p2 *)\n  simpl in Hnf ; destruct Hnf as [ [ Hnf_p1 Hnf_p2 ] Hnf_q ].\n  destruct IHp1 with (q := q) (r := r) as [ [ s1 Hs1 ] | Hs1 ] ; \n    solve [ simpl in * ; tauto ] || auto.\n  transitivity (depth (p1 + p2)) ; apply le_max_l || auto.\n  destruct IHp2 with (q := q) (r := r) as [ [ s2 Hs2 ] | Hs2 ] ; \n    solve [ simpl in * ; tauto ] || auto.\n  transitivity (depth (p1 + p2)) ; apply le_max_r || auto.\n  destruct Hs1 as [ Hbisim_s1 [ Hnf_s1 [ Hcongr_s1 Hleq_s1 ] ] ].\n  destruct Hs2 as [ Hbisim_s2 [ Hnf_s2 [ Hcongr_s2 Hleq_s2 ] ] ].\n  left ; exists (s1 + s2) ; split ; [ | split ; [ | split ] ].\n  apply bisim_trans with (emb (p1 · q · r + p2 · q · r)) ; \n    apply B4_sound || auto.\n  apply bisim_trans with (emb (s1 · r + s2 · r)) ;\n    [ | apply bisim_symm ; apply B4_sound ].\n  apply bisim_comp_plus ; auto.\n  simpl ; split ; auto.\n  apply comp_plus_left ; auto.\n  simpl ; apply max_lub.\n  transitivity (depth (p1 · q)) ; simpl ; auto.\n  rewrite <- max_assoc ; rewrite (max_comm (depth p2)).\n  rewrite max_assoc ; apply le_max_l.\n  transitivity (depth (p2 · q)) ; simpl ; auto.\n  rewrite <- max_assoc ; apply le_max_r.\n  destruct Hs2 as [ s [ Hbisim [ Hnf Hleq ] ] ].\n  right ; exists s ; split ; [ | split ] ; auto.\n  transitivity ((1 + (depth (p2 · q)))%nat) ; auto.\n  assert (depth (p2 · q) <= depth ((p1 + p2) · q)) ; omega || auto.\n  simpl ; apply max_lub ; apply le_max_r || auto.\n  rewrite <- max_assoc ; rewrite (max_comm (depth p2)) ; \n    rewrite max_assoc ; apply le_max_r.\n  destruct Hs1 as [ s [ Hbisim [ Hnf Hleq ] ] ].\n  right ; exists s ; split ; [ | split ] ; auto.\n  transitivity (1 + depth (p1 · q))%nat ; auto.\n  assert (depth (p1 · q) <= depth ((p1 + p2) · q)) ; omega || auto.\n  simpl ; apply max_lub ; apply le_max_r || auto.\n  rewrite <- max_assoc ; apply le_max_l.\n\n  (* Case for p1 · p2 *)\n  simpl in Hnf ; destruct Hnf as [ [ Hnf_p1 Hnf_p2 ] Hnf_q ].\n  destruct IHp2 with (q := q) (r := r) as [ [ s2 H ] | Hs2_top ] ; \n    solve [ simpl in * ; tauto ] || auto.\n  transitivity (depth (p1 · p2)) ; apply le_max_r || auto.\n  destruct H as [ Hbisim_s2 [ Hnf_s2 [ Hcongr_s2 Hleq_s2 ] ] ].\n  destruct IHp1 with (q := s2) (r := r) as [ [ s1 H ] | Hs1_top ] ; \n    solve [ simpl in * ; tauto ] || auto.\n  transitivity (depth (p1 · p2)) ; apply le_max_l || auto.\n  simpl ; split ; auto.\n  apply nf_mult_right_compat with (p2 · q · r) ; auto.\n  destruct H as [ Hbisim_s1 [ Hnf_s1 [ Hcongr_s1 Hleq_s1 ] ] ].\n  left ; exists s1 ; split ; [ | split ; [ | split ] ] ; auto.\n  apply bisim_trans with (emb (p1 · p2 · q · r)) ; apply B5_sound || auto.\n  apply bisim_trans with (emb (p1 · s2 · r)) ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  transitivity (depth (p1 · s2)) ; auto.\n  simpl ; apply max_lub.\n  rewrite <- max_assoc ; apply le_max_l.\n  transitivity (depth (p2 · q)) ; auto.\n  simpl ; apply max_lub ; apply le_max_r || auto.\n  rewrite (max_comm (depth p1)) ; rewrite <- max_assoc ; apply le_max_l.\n  destruct Hs1_top as [ s [ Hbisim [ Hnf Hleq ] ] ].\n  right ; exists s ; split ; [ | split ] ; auto.\n  transitivity (1 + depth (p1 · s2))%nat ; auto.\n  assert (depth (p1 · s2) <= depth ((p1 · p2) · q)) ; omega || auto.\n  simpl ; apply max_lub.\n  rewrite <- max_assoc ; apply le_max_l.\n  transitivity (depth (p2 · q)) ; auto.\n  simpl ; apply max_lub ; apply le_max_r || auto.\n  rewrite <- max_assoc ; rewrite (max_comm (depth p2)) ;\n    rewrite max_assoc ; apply le_max_r.\n  destruct Hs2_top as [ s [ Hbisim [ Hnf Hleq ] ] ].\n  right ; exists s ; split ; [ | split ] ; auto.\n  transitivity (1 + depth (p2 · q))%nat ; auto.\n  assert (depth (p2 · q) <= depth ((p1 · p2) · q)) ; omega || auto.\n  simpl ; apply max_lub ; apply le_max_r || auto.\n  rewrite <- max_assoc ; rewrite (max_comm (depth p2)) ;\n    rewrite max_assoc ; apply le_max_r.\n\n  (* Case for p1 * p2 *)\n  rename p1 into p ; destruct IHp2 with (q := q) (r := r) as [ [ q2 H ] | H ] ; \n    solve [ simpl in * ; tauto ] || auto.\n  transitivity (depth (p * p2)) ; apply le_max_r || auto.\n  destruct H as [ Hbisim_q2 [ Hnf_q2 [ Hcongr_q2 Hleq_q2 ] ] ] ; \n    clear IHp1 IHp2.\n  assert (emb (p * p2 · q · r) <=> emb (p * q2 · r)) as Hbasic_eq.\n  apply bisim_trans with (emb (p * (p2 · q · r))) ; apply BKS2_sound || auto.\n  apply bisim_trans with (emb (p * (q2 · r))) ;\n    [ | apply bisim_symm ; apply BKS2_sound ].\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  destruct (LEM (emb (p * q2 · r) <=> emb r)) as [ Hbisim_r | Hnot_bisim_r ].\n\n  (* Case for p * q2 · r <=> r *)\n  assert (emb ((p + q2) * 0) <=> emb (p * q2 · r)) as Hplus_eq.\n  apply bisim_trans with (emb ((p * q2) * 0)).\n  apply bisim_symm ; apply star_plus_zero_bisim.\n  apply bisim_trans with (emb r) ; [ | apply bisim_symm ; auto ].\n  apply bisim_symm ; apply RSP_sound.\n  apply bisim_trans with (emb (p * q2 · r)) ; apply bisim_symm ;\n    apply B6_sound || auto.\n  assert (emb ((p + q2) * 0) <=> emb ((p + q2) * 0 · 0)) as Hhelp_eq.\n  apply bisim_trans with (emb ((p + q2) * (0 · 0))).\n  apply bisim_comp_star ; apply bisim_refl || \n    apply bisim_symm ; apply B7_sound.\n  apply bisim_symm ; apply BKS2_sound.\n  right ; exists ((p + q2) * 0) ; split ; [ | split ] ; auto.\n  apply bisim_trans with (emb (p * q2 · r)) ; [ apply bisim_symm | ] ; auto.\n  apply bisim_trans with (emb ((p + q2) * 0)) ; auto.\n  apply bisim_symm ; auto.\n  simpl ; repeat split ; auto.\n  simpl in Hnf ; apply nf_mult_right_compat with (p * p2 · q · r) ; \n    tauto || auto.\n  apply bisim_trans with (emb (p * q2 · r)) ; auto.\n  apply bisim_trans with (emb ((p + q2) * 0)) ; auto.\n  apply bisim_symm ; auto.\n  apply nf_mult_right_compat with r ; auto.\n  apply bisim_trans with (emb ((p + q2) * 0)) ; auto.\n  apply bisim_trans with (emb (p * q2 · r)) ; apply bisim_symm ; auto.\n  apply comp_plus_left.\n  simpl in Hnf ; apply congr_right_compat with (p * p2 · q · r) ; \n    tauto || auto.\n  apply bisim_trans with (emb (p * q2 · r)) ; auto.\n  apply bisim_trans with (emb ((p + q2) * 0)) ; auto.\n  apply bisim_symm ; auto.\n  apply congr_right_compat with r ; auto.\n  apply bisim_trans with (emb (p * q2 · r)) ; [ apply bisim_symm | ] ; auto.\n  apply bisim_trans with (emb ((p + q2) * 0)) ; auto.\n  apply bisim_symm ; auto.\n  simpl in * ; destruct (depth p2) as [ | m ].\n  assert (max (depth p) (depth q2) <= max (S (depth p)) (depth q)) ; try omega.\n  apply max_lub.\n  transitivity (S (depth p)) ; apply le_max_l || omega.\n  rewrite max_0_l in Hleq_q2.\n  transitivity (depth q) ; apply le_max_r || auto.\n  assert (max (depth p) (depth q2) <= max (S (max (depth p) m)) (depth q)) ;\n    omega || apply max_lub.\n  transitivity (S (max (depth p) m)) ; apply le_max_l || auto.\n  rewrite succ_max_distr.\n  transitivity (S (depth p)) ; apply le_max_l || omega.\n  transitivity (max (S m) (depth q)) ; auto.\n  apply max_lub ; apply le_max_r || auto.\n  transitivity (S (max (depth p) m)) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; apply le_max_r.\n\n  (* Case where NOT p * q2 · r <=> r *)\n  destruct (LEM (exists (t : T), p -->+ t /\\ \n    emb (t · p * q2 · r) <=> emb r)) as [ Hplus_ex | Hplus_not_ex ].\n  destruct Hplus_ex as [ t [ Hplus Hbisim ] ].\n\n  (* Case where p -->+ t such that t · p * q2 · r <=> r exists *)\n  assert (emb ((t · p * q2) * 0) <=> emb r) as HRSP_eq.\n  apply bisim_symm ; apply RSP_sound.\n  apply bisim_trans with (emb ((t · p * q2) · r)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (t · p * q2 · r)).\n  apply bisim_symm ; auto.\n  apply bisim_symm ; apply B5_sound.\n  assert (emb ((p * q2 · t) * 0) <=> emb ((p + q2 · t) * 0)) as Hplus_eq.\n  apply bisim_trans with (emb ((p * (q2 · t)) * 0)).\n  apply bisim_comp_star ; apply bisim_refl || apply BKS2_sound.\n  apply star_plus_zero_bisim.\n  assert (emb (t · (p + q2 · t) * 0) <=> emb r) as Hplus_eq'.\n  apply bisim_trans with (emb ((t · p * q2) * 0)) ; auto.\n  apply bisim_trans with (emb (t · (p * q2 · t) * 0)).\n  apply bisim_comp_mult ; apply bisim_refl || apply bisim_symm ; auto.\n  apply bisim_symm ; apply star_order_zero_bisim.\n  destruct (LEM (exists (u : T), q2 -->+ u /\\\n    emb (u · t · p * q2 · r) <=> emb (p * q2 · r))) as [ Hu | Hnot_u ].\n \n  (* Case where q2 -->+ u such that u · t · p * q2 · r <=> p * q2 · r *)\n  destruct Hu as [ u [ Hplus' Hbisim_u ] ].\n  assert (emb ((u · t) · p * q2 · r + 0) <=> emb (p * q2 · r)) as Hstar_eq.\n  apply bisim_trans with (emb ((u · t) · p * q2 · r)) ; apply B6_sound || auto.\n  apply bisim_trans with (emb (u · t · p * q2 · r)) ; apply B5_sound || auto.\n  apply bisim_symm in Hstar_eq ; apply RSP_sound in Hstar_eq.\n  assert (emb (t · (u · t) * 0) <=> emb r) as HRSP_eq'.\n  apply bisim_trans with (emb (t · p * q2 · r)) ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || apply bisim_symm ; auto.\n  assert (emb ((t · u) * 0) <=> emb r) as HRSP_eq''.\n  apply bisim_trans with (emb (t · (u · t) * 0)) ; auto.\n  apply star_order_zero_bisim.\n  destruct IHdepth with (m := depth t) (p := t) \n    (q := u) (r := r) as [ H | H ] ; auto.\n  assert (depth t < depth (p * p2)) ; omega || auto.\n  simpl ; destruct (depth p2) as [ | m ].\n  assert (depth t <= depth p) ; omega || auto.\n  apply depth_pres_plus ; auto.\n  assert (depth t <= max (depth p) m) ; omega || auto.\n  transitivity (depth p) ; apply le_max_l || auto.\n  apply depth_pres_plus ; auto.\n  simpl ; split.\n  apply nf_mult_pres_plus with p ; auto.\n  simpl in Hnf ; apply nf_mult_right_compat with (p * p2 · q · r) ; \n    tauto || auto.\n  apply bisim_trans with (emb (p * q2 · r)) ; auto.\n  apply bisim_trans with (emb (u · t · p * q2 · r)).\n  apply bisim_symm ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply nf_mult_pres_plus with q2 ; auto. \n  apply congr_pres_plus with q2 ; auto.\n  \n  (* Case where s is now normalized w.r.t. (t · u) * 0 *)\n  destruct H as [ s [ Hbisim_s [ Hnf_s [ Hcongr_s Hleq_s ] ] ] ].\n  assert (emb (s * 0) <=> emb r) as Hstar_eq'.\n  apply bisim_symm ; apply RSP_sound.\n  apply bisim_trans with (emb (s · r)) ; \n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (t · u · r)) ; auto.\n  apply bisim_trans with (emb ((t · u) * 0)) ;\n    [ apply bisim_symm ; auto | ].\n  apply bisim_trans with (emb (t · u · (t · u) * 0)).\n  apply bisim_trans with (emb ((t · u) · (t · u) * 0)) ; apply B5_sound || auto.\n  apply bisim_trans with (emb ((t · u) · (t · u) * 0 + 0)) ;\n    apply B6_sound || auto.\n  apply bisim_symm ; apply BKS1_sound.\n  apply bisim_trans with (emb ((t · u) · (t · u) * 0)) ;\n    [ apply bisim_symm ; apply B5_sound | ].\n  apply bisim_trans with (emb ((t · u) · r)) ; apply B5_sound || auto.\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  right ; exists (s * 0) ; split ; [ | split ] ; auto.\n  apply bisim_trans with (emb (s * 0)) ; [ apply bisim_symm ; auto | ].\n  apply bisim_trans with (emb (s * (0 · 0))).\n  apply bisim_comp_star ; apply bisim_refl || \n    apply bisim_symm ; apply B7_sound.\n  apply bisim_symm ; apply BKS2_sound.\n  simpl ; repeat split ; auto.\n  apply nf_mult_right_compat with r ; auto.\n  apply bisim_trans with (emb (s * 0)) ; [ apply bisim_symm | ] ; auto.\n  apply bisim_trans with (emb (s * (0 · 0))) ; apply BKS2_sound || auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply bisim_symm ; apply BKS2_sound.\n  apply congr_right_compat with r ; auto.\n  apply bisim_trans with (emb (s * 0)) ; [ apply bisim_symm | ] ; auto.\n  apply bisim_trans with (emb (s * (0 · 0))) ; auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply bisim_symm ; apply BKS2_sound.\n  simpl in * ; destruct (depth p2) as [ | m ].\n  assert (depth s <= max (S (depth p)) (depth q)) ; omega || auto.\n  transitivity (depth (t · u)) ; auto.\n  simpl ; apply max_lub ; destruct (depth q) as [ | n ].\n  transitivity (depth p) ; omega || auto.\n  apply depth_pres_plus ; auto.\n  rewrite succ_max_distr.\n  transitivity (S (depth p)) ; apply le_max_l || auto.\n  transitivity (depth p) ; omega || apply depth_pres_plus ; auto.\n  rewrite max_0_l in Hleq_q2.\n  assert (depth u <= 0) ; omega || auto.\n  transitivity (depth q2) ; auto.\n  apply depth_pres_plus ; auto.\n  transitivity (depth q2) ; auto.\n  apply depth_pres_plus ; auto.\n  rewrite succ_max_distr.\n  transitivity (S n) ; apply le_max_r || auto.\n  assert (depth s <= max (S (max (depth p) m)) (depth q)) ; omega || auto.\n  transitivity (max (depth t) (depth u)) ; apply max_lub || auto.\n  transitivity (S (max (depth p) m)) ; apply le_max_l || auto.\n  rewrite succ_max_distr.\n  transitivity (S (depth p)) ; apply le_max_l || auto.\n  transitivity (depth p) ; omega || apply depth_pres_plus ; auto.\n  transitivity (depth q2).\n  apply depth_pres_plus ; auto.\n  transitivity (max (S m) (depth q)) ; auto.\n  apply max_lub ; apply le_max_r || auto.\n  transitivity (S (max (depth p) m)) ; apply le_max_l || auto.\n  assert (m <= max (depth p) m) by ( apply le_max_r) ; omega.\n\n  (* Case where depth-induction results in an r-equivalent nf (s · 0) *)\n  destruct H as [ s [ Hbisim_s [ Hnf_s Hleq_s ] ] ].\n  right ; exists s ; split ; [ | split ] ; auto.\n  transitivity (1 + depth (t · u))%nat ; auto.\n  assert (depth (t · u) <= depth (p * p2 · q)) ; omega || auto.\n  simpl in * ; apply max_lub ; destruct (depth p2) as [ | m ].\n  transitivity (S (depth p)) ; apply le_max_l || auto.\n  transitivity (depth p) ; omega || apply depth_pres_plus ; auto.\n  transitivity (S (max (depth p) m)) ; apply le_max_l || auto.\n  rewrite succ_max_distr.\n  transitivity (S (depth p)) ; apply le_max_l || auto.\n  transitivity (depth p) ; omega || apply depth_pres_plus ; auto.\n  transitivity (depth q2).\n  apply depth_pres_plus ; auto.\n  rewrite max_0_l in Hleq_q2.\n  transitivity (depth q) ; apply le_max_r || auto.\n  transitivity (depth q2).\n  apply depth_pres_plus ; auto.\n  transitivity (max (S m) (depth q)) ; auto.\n  apply max_lub ; apply le_max_r || auto.\n  transitivity (S (max (depth p) m)) ; apply le_max_l || auto.\n  assert (m <= max (depth p) m) by ( apply le_max_r ) ; omega.\n\n  (* Case where q2 -->+ u with u · t · p* q2 · r <=> p * q2 · r NOT exists *)\n  right ; exists (t · (p + q2 · t) * 0) ; split ; [ | split ] ; auto.\n  apply bisim_trans with (emb (t · (p + q2 · t) * 0)).\n  apply bisim_symm ; auto.\n  apply bisim_trans with (emb (t · (p + q2 · t) * 0 · 0)) ;\n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply bisim_trans with (emb ((p + q2 · t) * (0 · 0))) ;\n    apply BKS2_sound || auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply bisim_symm ; apply BKS2_sound.\n  simpl ; repeat split ; auto.\n  apply nf_mult_pres_plus with p ; auto.\n  simpl in Hnf.\n  apply nf_mult_right_compat with (p * p2 · q · r) ; tauto || auto.\n  apply bisim_trans with (emb (p * q2 · r)) ; auto.\n  apply bisim_trans with (emb ((p + q2 · t) * (0 · 0))) ;\n    [ | apply bisim_symm ; apply BKS2_sound ].\n  apply bisim_trans with (emb ((p * q2 · t) * 0)).\n  apply RSP_sound.\n  apply bisim_trans with (emb ((p * q2 · t) · p * q2 · r)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (p * q2 · t · p * q2 · r)) ;\n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || apply bisim_symm ; auto.\n  apply bisim_trans with (emb ((p + q2 · t) * 0)) ; auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  simpl in Hnf.\n  apply nf_mult_right_compat with (p * p2 · q · r) ; tauto || auto.\n  apply bisim_trans with (emb (p * q2 · r)) ; auto.\n  apply bisim_trans with (emb ((p + q2 · t) * (0 · 0))) ;\n    [ | apply bisim_symm ; apply BKS2_sound ].\n  apply bisim_trans with (emb ((p * q2 · t) * 0)).\n  apply RSP_sound.\n  apply bisim_trans with (emb ((p * q2 · t) · p * q2 · r)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (p * q2 · t · p * q2 · r)) ;\n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || apply bisim_symm ; auto.\n  apply bisim_trans with (emb ((p + q2 · t) * 0)) ; auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply nf_mult_right_compat with r ; auto.\n  apply bisim_trans with (emb (t · (p + q2 · t) * 0)) ;\n    [ apply bisim_symm ; auto | ].\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply bisim_trans with (emb ((p + q2 · t) * (0 · 0))) ;\n    [ | apply bisim_symm ; apply BKS2_sound ].\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  simpl in Hnf.\n  apply nf_mult_pres_plus with p ; auto.\n  apply nf_mult_right_compat with (p * p2 · q · r) ; tauto || auto.\n  apply bisim_trans with (emb (p * q2 · r)) ; auto.\n  apply bisim_trans with (emb ((p + q2 · t) * (0 · 0))) ;\n    [ | apply bisim_symm ; apply BKS2_sound ].\n  apply bisim_trans with (emb ((p * q2 · t) * 0)).\n  apply RSP_sound.\n  apply bisim_trans with (emb ((p * q2 · t) · p * q2 · r)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (p * q2 · t · p * q2 · r)) ;\n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || apply bisim_symm ; auto.\n  apply bisim_trans with (emb ((p + q2 · t) * 0)) ; auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply comp_plus_left.\n  apply congr_right_compat with (p * p2 · q · r) ;\n    solve [ simpl in * ; tauto ] || auto.\n  apply bisim_trans with (emb (p * q2 · r)) ; auto.\n  apply bisim_trans with (emb ((p + q2 · t) * (0 · 0))) ;\n    [ | apply bisim_symm ; apply BKS2_sound ].\n  apply bisim_trans with (emb ((p * q2 · t) * 0)).\n  apply RSP_sound.\n  apply bisim_trans with (emb ((p * q2 · t) · p * q2 · r)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (p * q2 · t · p * q2 · r)) ;\n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || apply bisim_symm ; auto.\n  apply bisim_trans with (emb ((p + q2 · t) * 0)) ; auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply congr_right_compat with (p * q2 · r).\n  intros v Hplus_v Hbisim'.\n  apply mult_plus_fmt in Hplus_v.\n  destruct Hplus_v as [ H | [ H | H ] ].\n  destruct H as [ q' [ Heq Hplus_q2 ] ] ; rewrite Heq in *.\n  apply Hnot_u ; exists q' ; split ; auto.\n  apply bisim_trans with (emb ((q' · t) · p * q2 · r)) ; auto.\n  apply bisim_symm ; apply B5_sound.\n  rewrite <- H in * ; simpl in Hnf.\n  destruct Hnf as [ [ _ [ _ Hcongr' ] ] _ ].\n  apply Hcongr' with t ; auto.\n  apply bisim_trans with (emb (t · p * q2 · r)).\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply bisim_trans with (emb (p * q2 · r)) ; auto.\n  apply bisim_symm ; auto.\n  simpl in Hnf ; destruct Hnf as [ [ _ [ _ Hcongr' ] ] _ ].\n  apply Hcongr' with v ; auto.\n  apply plus_plus_clos with t ; auto.\n  apply bisim_trans with (emb (v · p * q2 · r)).\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply bisim_trans with (emb (p * q2 · r)) ; auto.\n  apply bisim_symm ; auto.\n  apply bisim_trans with (emb ((p + q2 · t) * (0 · 0))) ;\n    [ | apply bisim_symm ; apply BKS2_sound ].\n  apply bisim_trans with (emb ((p * q2 · t) * 0)).\n  apply RSP_sound.\n  apply bisim_trans with (emb ((p * q2 · t) · p * q2 · r)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (p * q2 · t · p * q2 · r)) ;\n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || apply bisim_symm ; auto.\n  apply bisim_trans with (emb ((p + q2 · t) * 0)) ; auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  simpl in * ; apply max_lub ; destruct (depth p2) as [ | m ].\n  rewrite succ_max_distr.\n  transitivity (S (S (depth p))) ; apply le_max_l || auto.\n  transitivity (depth p) ; omega || apply depth_pres_plus ; auto.\n  rewrite succ_max_distr.\n  transitivity (S (S (max (depth p) m))) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; rewrite succ_max_distr.\n  transitivity (S (S (depth p))) ; apply le_max_l || auto.\n  transitivity (depth p) ; omega || apply depth_pres_plus ; auto.\n  rewrite succ_max_distr ; rewrite succ_max_distr ;\n    rewrite succ_max_distr ; apply max_lub.\n  transitivity (S (S (depth p))) ; apply le_max_l || omega.\n  apply max_lub.\n  rewrite max_0_l in Hleq_q2.\n  transitivity (S (depth q)) ; omega || apply le_max_r.\n  transitivity (S (S (depth p))) ; apply le_max_l || auto.\n  assert (depth t <= depth p) by ( apply depth_pres_plus ; auto) ; omega.\n  rewrite succ_max_distr ; apply max_lub.\n  rewrite succ_max_distr.\n  transitivity (S (S (max (depth p) m))) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; rewrite succ_max_distr.\n  transitivity (S (S (depth p))) ; apply le_max_l || omega.\n  rewrite succ_max_distr ; apply max_lub.\n  transitivity (S (max (S m) (depth q))) ; omega || auto.\n  rewrite succ_max_distr ; apply max_lub.\n  rewrite succ_max_distr.\n  transitivity (S (S (max (depth p) m))) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; rewrite succ_max_distr ; apply le_max_r.\n  rewrite succ_max_distr ; apply le_max_r.\n  transitivity (S (depth p)).\n  assert (depth t <= depth p) by ( apply depth_pres_plus ; auto ) ; omega.\n  rewrite succ_max_distr.\n  transitivity (S (S (max (depth p) m))) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; rewrite succ_max_distr.\n  transitivity (S (S (depth p))) ; apply le_max_l || omega.\n\n  (* Case where p -->+ t and t · p * q2 · r <=> r does NOT exist *)\n  left ; exists (p * q2) ; split ; [ | split ; [ | split ] ] ; auto.\n  simpl ; split ; [ | split ] ; auto.\n  simpl in Hnf ; apply nf_mult_right_compat with (p * p2 · q · r) ;\n    tauto || auto.\n  simpl in Hnf ; apply congr_right_compat with (p * p2 · q · r) ;\n    tauto || auto.\n  intros t Hplus Hbisim' ; apply star_plus_fmt in Hplus.\n  destruct Hplus as [ H | [ H | H ] ].\n  destruct H as [ t' [ Heq Hplus ] ] ; rewrite Heq in *.\n  apply Hplus_not_ex ; exists t' ; split ; auto.\n  apply bisim_trans with (emb ((t' · p * q2) · r)) ; auto.\n  apply bisim_symm ; apply B5_sound.\n  rewrite H in * ; apply Hnot_bisim_r ; auto.\n  apply Hcongr_q2 with t ; auto.\n  simpl in * ; destruct (depth q2) as [ | m ] ; \n    destruct (depth p2) as [ | n ] ; apply le_max_l || auto.\n  transitivity (S (max (depth p) n)) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; apply le_max_l.\n  rewrite succ_max_distr ; apply max_lub ; apply le_max_l || auto.\n  rewrite max_0_l in Hleq_q2.\n  transitivity (depth q) ; apply le_max_r || auto.\n  rewrite succ_max_distr ; apply max_lub.\n  transitivity (S (max (depth p) n)) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; apply le_max_l.\n  transitivity (max (S n) (depth q)) ; auto.\n  apply max_lub ; apply le_max_r || auto.\n  transitivity (S (max (depth p) n)) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; apply le_max_r.\n\n  (* Case where IHp2 results in an r-equivalent in (s * 0) - form *)\n  destruct H as [ s [ Hbisim_s [ Hnf_s Hleq_s ] ] ].\n  right ; exists s ; split ; [ | split ] ; auto.\n  transitivity (1 + (depth (p2 · q)))%nat ; auto.\n  assert (depth (p2 · q) <= depth (p * p2 · q)) ; omega || auto.\n  simpl ; destruct (depth p2) as [ | m ].\n  rewrite max_0_l ; apply le_max_r.\n  apply max_lub ; apply le_max_r || auto.\n  transitivity (S (max (depth p) m)) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; apply le_max_r.\nQed.\n\nLemma congr_ex : forall (p r : T), nf_mult p r -> \n  (exists (q : T), emb (p · r) <=> emb (q · r) /\\ nf_mult q r /\\ \n    congr q r /\\ depth q <= depth p) \\/\n  (exists (q : T), emb r <=> emb (q · 0) /\\ nf (q · 0) /\\ \n    depth q <= 1 + depth p).\nProof.\n  intro p ; induction p ; intros r Hnf_mult.\n  left ; exists 0 ; split ; [ | split ; [ | split ] ] ; \n    simpl ; apply bisim_refl || auto.\n  intros t H ; destruct H as [ a [ s [ H _ ] ] ] ; inversion H.\n  left ; exists (act a) ; split ; [ | split ; [ | split ] ] ;\n    simpl ; apply bisim_refl || auto.\n  intros t H ; destruct H as [ a' [ s [ H _ ] ] ] ; inversion H.\n\n  (* Case for p1 + p2 *)\n  simpl in Hnf_mult ; destruct Hnf_mult as [ Hp1 Hp2 ].\n  destruct (IHp1 r Hp1) as \n    [ [ q1 [ Hbisim_q1 [ Hnf_q1 [ Hcongr_q1 Hleq_q1 ] ] ] ] | Hp1_top ].\n  destruct (IHp2 r Hp2) as\n    [ [ q2 [ Hbisim_q2 [ Hnf_q2 [ Hcongr_q2 Hleq_q2 ] ] ] ] | Hp2_top ].\n  left ; exists (q1 + q2) ; split ; [ | split ; [ | split ] ].\n  apply bisim_trans with (emb (p1 · r + p2 · r)) ; apply B4_sound || auto.\n  apply bisim_trans with (emb (q1 · r + q2 · r)) ; auto.\n  apply bisim_comp_plus ; auto.\n  apply bisim_symm ; apply B4_sound.\n  simpl ; split ; auto.\n  apply comp_plus_left ; auto.\n  simpl ; apply max_lub.\n  transitivity (depth p1) ; apply le_max_l || auto.\n  transitivity (depth p2) ; apply le_max_r || auto.\n  \n  destruct Hp2_top as [ q [ Hbisim [ Hnf Hleq ] ] ].\n  right ; exists q ; split ; [ | split ] ; auto.\n  transitivity (1 + depth p2)%nat ; apply le_max_r || auto.\n  assert (depth p2 <= depth (p1 + p2)) ; omega || auto.\n  simpl ; apply le_max_r || auto.\n  destruct Hp1_top as [ q [ Hbisim [ Hnf Hleq ] ] ].\n  right ; exists q ; split ; [ | split ] ; auto.\n  transitivity (1 + depth p1)%nat ; auto.\n  assert (depth p1 <= depth (p1 + p2)) ; omega || auto.\n  simpl ; apply le_max_l.\n\n  (* Case for p1 · p2 *)\n  simpl in Hnf_mult ; destruct Hnf_mult as [ Hp1 Hp2 ].\n  destruct (IHp2 r Hp2) as \n    [ [ q2 [ Hbisim_q2 [ Hnf_q2 [ Hcongr_q2 Hleq_q2 ] ] ] ] | Hp2_top ].\n  destruct (comp_mult_ex p1 q2 r) as [ [ s H ] | Hp1_top ] ; auto.\n  simpl ; split ; auto.\n  apply nf_mult_right_compat with (p2 · r) ; auto.\n  destruct H as [ Hbisim_s [ Hnf_s [ Hcongr_s Hleq_s ] ] ].\n  left ; exists s ; split ; [ | split ; [ | split ] ] ; auto.\n  apply bisim_trans with (emb (p1 · p2 · r)) ; apply B5_sound || auto.\n  apply bisim_trans with (emb (p1 · q2 · r)) ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  transitivity (depth (p1 · q2)) ; auto.\n  simpl ; apply max_lub ; apply le_max_l || auto.\n  transitivity (depth p2) ; apply le_max_r || auto.\n  destruct Hp1_top as [ s [ Hbisim [ Hnf Hleq ] ] ].\n  right ; exists s ; split ; [ | split ] ; auto.\n  transitivity (1 + depth (p1 · q2))%nat ; auto.\n  assert (depth (p1 · q2) <= depth (p1 · p2)) ; omega || auto.\n  simpl ; apply max_lub ; apply le_max_l || auto.\n  transitivity (depth p2) ; apply le_max_r || auto.\n  destruct Hp2_top as [ s [ Hbisim [ Hnf Hleq ] ] ].\n  right ; exists s ; split ; [ | split ] ; auto.\n  transitivity (1 + depth p2)%nat ; auto.\n  assert (depth p2 <= depth (p1 · p2)) ; omega || auto.\n  simpl ; apply le_max_r.\n\n  (* Case for p1 * p2 *)\n  destruct (IHp2 r) as [ [ q H ] | H ] ; solve [ simpl in * ; tauto ] || auto.\n  destruct H as [ Hbisim_q [ Hnf_q [ Hcongr_q Hleq_q ] ] ].\n  rename p1 into p ; clear IHp1 IHp2.\n  destruct (LEM (emb (p * q · r) <=> emb r)) as [ Hbisim_star | Hbisim_star ].\n\n  (* Case where p * q · r <=> r *)\n  assert (emb (p * q · r + 0) <=> emb r) as Hstar_eq.\n  apply bisim_trans with (emb (p * q · r)) ; apply B6_sound || auto.\n  apply bisim_symm in Hstar_eq ; apply RSP_sound in Hstar_eq.\n  assert (emb r <=> emb ((p + q) * 0)) as Hstar_eq'.\n  apply bisim_trans with (emb (p * q * 0)) ; auto.\n  apply star_plus_zero_bisim.\n  right ; exists ((p + q) * 0) ; split ; [ | split ].\n  apply bisim_trans with (emb ((p + q) * 0)) ; auto.\n  apply bisim_trans with (emb ((p + q) * (0 · 0))) ; auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply bisim_symm ; apply BKS2_sound.\n  simpl ; repeat split ; auto.\n  simpl in Hnf_mult.\n  apply nf_mult_right_compat with (p * p2 · r) ; tauto || auto.\n  apply bisim_trans with (emb (p * q · r)).\n  apply bisim_trans with (emb (p * (p2 · r))) ; apply BKS2_sound || auto.\n  apply bisim_trans with (emb (p * (q · r))) ; auto.\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  apply bisim_symm ; apply BKS2_sound.\n  apply bisim_trans with (emb r) ; auto.\n  apply bisim_trans with (emb ((p + q) * 0)) ; auto.\n  apply bisim_trans with (emb ((p + q) * (0 · 0))) ; auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply bisim_symm ; apply BKS2_sound.\n  apply nf_mult_right_compat with r ; auto.\n  apply bisim_trans with (emb ((p + q) * 0)) ; auto.\n  apply bisim_trans with (emb ((p + q) * (0 · 0))) ; auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply bisim_symm ; apply BKS2_sound.\n  apply comp_plus_left.\n  simpl in Hnf_mult.\n  apply congr_right_compat with (p * p2 · r) ; tauto || auto.\n  apply bisim_trans with (emb (p * q · r)).\n  apply bisim_trans with (emb (p * (p2 · r))) ; apply BKS2_sound || auto.\n  apply bisim_trans with (emb (p * (q · r))) ; auto.\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  apply bisim_symm ; apply BKS2_sound.\n  apply bisim_trans with (emb r) ; auto.\n  apply bisim_trans with (emb ((p + q) * 0)) ; auto.\n  apply bisim_trans with (emb ((p + q) * (0 · 0))) ; auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply bisim_symm ; apply BKS2_sound.\n  apply congr_right_compat with r ; auto.\n  apply bisim_trans with (emb ((p + q) * 0)) ; auto.\n  apply bisim_trans with (emb ((p + q) * (0 · 0))) ; auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply bisim_symm ; apply BKS2_sound.\n  simpl ; destruct (depth p2) as [ | m ].\n  replace (depth q) with 0%nat in * by omega.\n  rewrite max_0_r ; omega.\n  assert (max (depth p) (depth q) <= S (max (depth p) m)) ; omega || auto.\n  apply max_lub ; rewrite succ_max_distr.\n  transitivity (S (depth p)) ; omega || apply le_max_l.\n  transitivity (S m) ; omega || apply le_max_r.\n\n  (* Case where NOT p * q · r <=> r *)\n  destruct (LEM (exists (t : T), p -->+ t /\\ emb (t · p * q · r) <=> emb r)) as \n    [ Hplus_ex | Hplus_ex ].\n\n  (* Case where p -->+ t such that t · p * q · r <=> r exists *)\n  destruct Hplus_ex as [ t [ Hplus Hbisim_t ] ].\n  assert (emb ((t · p * q) · r + 0) <=> emb r) as Hstar_eq.\n  apply bisim_trans with (emb ((t · p * q) · r)) ; apply B6_sound || auto.\n  apply bisim_trans with (emb (t · p * q · r)) ; apply B5_sound || auto.\n  apply bisim_symm in Hstar_eq ; apply RSP_sound in Hstar_eq.\n  assert (emb r <=> emb (t · (p * q · t) * 0)) as Hstar_eq'.\n  apply bisim_trans with (emb ((t · p * q) * 0)) ; auto.\n  apply star_order_zero_bisim.\n  assert (emb ((p * q · t) * 0) <=> emb ((p + q · t) * 0)) as Hplus_eq.\n  apply bisim_trans with (emb ((p * (q · t)) * 0)).\n  apply bisim_comp_star ; apply bisim_refl || apply BKS2_sound.\n  apply star_plus_zero_bisim.\n  destruct (comp_mult_ex q t ((p * q · t) * 0)) as [ [ s H ] | H ].\n  simpl ; split.\n  apply nf_mult_right_compat with r ; auto.\n  apply nf_mult_pres_plus with p ; auto.\n  simpl in Hnf_mult ; apply nf_mult_right_compat with (p * p2 · r) ; \n    tauto || auto.\n  apply bisim_trans with (emb (p * q · r)).\n  apply bisim_trans with (emb (p * (p2 · r))) ; apply BKS2_sound || auto.\n  apply bisim_trans with (emb (p * (q · r))).\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  apply bisim_symm ; apply BKS2_sound.\n  apply RSP_sound.\n  apply bisim_trans with (emb ((p * q · t) · p * q · r)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (p * q · t · p * q · r)) ;\n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply bisim_symm ; auto.\n  simpl in Hnf_mult.\n  apply congr_pres_plus with p ; auto.\n  apply congr_right_compat with (p * p2 · r) ; tauto || auto.\n  apply bisim_trans with (emb (p * q · r)).\n  apply bisim_trans with (emb (p * (p2 · r))) ; apply BKS2_sound || auto.\n  apply bisim_trans with (emb (p * (q · r))) ; auto.\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  apply bisim_symm ; apply BKS2_sound.\n  apply RSP_sound.\n  apply bisim_trans with (emb ((p * q · t) · p * q · r)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (p * q · t · p * q · r)) ;\n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply bisim_symm ; auto.\n  destruct H as [ Hbisim_s [ Hnf_s [ Hcongr_s Hleq_s ] ] ].\n  assert (emb ((p + s) * 0) <=> emb (p * q · r)) as Hcomp_eq.\n  apply bisim_symm ; apply RSP_sound.\n  apply bisim_trans with (emb ((p + s) · p * q · r)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (p · p * q · r + s · p * q · r)) ;\n    [ | apply bisim_symm ; apply B4_sound ].\n  apply bisim_trans with (emb ((p · p * q + q) · r)).\n  apply bisim_comp_mult ; apply bisim_refl ||\n    apply bisim_symm ; apply BKS1_sound.\n  apply bisim_trans with (emb ((p · p * q) · r + q · r)) ;\n    apply B4_sound || auto.\n  apply bisim_comp_plus ; apply B5_sound || auto.\n  apply bisim_trans with (emb (q · t · (p * q · t) * 0)).\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply bisim_trans with (emb (s · (p * q · t) * 0)) ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply bisim_symm ; apply RSP_sound.\n  apply bisim_trans with (emb ((p * q · t) · p * q · r)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (p * q · t · p * q · r)) ;\n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || \n    apply bisim_symm ; auto.\n  right ; exists (t · (p + s) * 0) ; split ; [ | split ].\n  apply bisim_trans with (emb (t · (p + s) * 0 · 0)) ; \n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_trans with (emb (t · (p + s) * (0 · 0))) ; apply B5_sound || auto.\n  apply bisim_trans with (emb (t · (p + s) * 0)).\n  apply bisim_trans with (emb ((t · p * q) * 0)) ; auto.\n  apply bisim_trans with (emb (t · (p * q · r))).\n  apply bisim_symm ; apply RSP_sound.\n  apply bisim_trans with (emb ((t · p * q) · t · p * q · r)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb ((t · p * q) · r)) ; \n    [ apply bisim_symm ; apply B5_sound | ].\n  apply bisim_comp_mult ; apply bisim_refl || apply bisim_symm ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || apply bisim_symm ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply bisim_symm ; apply BKS2_sound.\n  simpl ; repeat split ; auto.\n  apply nf_mult_pres_plus with p ; auto.\n  simpl in Hnf_mult.\n  apply nf_mult_right_compat with (p * p2 · r) ; tauto || auto.\n  apply bisim_trans with (emb (p * q · r)).\n  apply bisim_trans with (emb (p * (p2 · r))) ; apply BKS2_sound || auto.\n  apply bisim_trans with (emb (p * (q · r))) ;\n    [ | apply bisim_symm ; apply BKS2_sound ].\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  apply bisim_trans with (emb ((p + s) * 0)) ; auto.\n  apply bisim_symm ; auto.\n  apply bisim_trans with (emb ((p + s) * (0 · 0))).\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply bisim_symm ; apply BKS2_sound.\n  simpl in Hnf_mult.\n  apply nf_mult_right_compat with (p * p2 · r) ; tauto || auto.\n  apply bisim_trans with (emb (p * q · r)).\n  apply bisim_trans with (emb (p * (p2 · r))) ; apply BKS2_sound || auto.\n  apply bisim_trans with (emb (p * (q · r))) ;\n    [ | apply bisim_symm ; apply BKS2_sound ].\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  apply bisim_trans with (emb ((p + s) * 0)) ; [ apply bisim_symm ; auto | ].\n  apply bisim_trans with (emb ((p + s) * (0 · 0))).\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply bisim_symm ; apply BKS2_sound.\n  apply nf_mult_right_compat with ((p * q · t) * 0) ; auto.\n  apply bisim_trans with (emb (p * q · r)).\n  apply bisim_symm ; apply RSP_sound.\n  apply bisim_trans with (emb ((p * q · t) · p * q · r)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (p * q · t · p * q · r)) ;\n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || apply bisim_symm ; auto.\n  apply bisim_trans with (emb ((p + s) * 0)) ; [ apply bisim_symm | ] ; auto.\n  apply bisim_trans with (emb ((p + s) * (0 · 0))) ; apply BKS2_sound || auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply bisim_symm ; apply BKS2_sound.\n  apply comp_plus_left.\n  simpl in Hnf_mult.\n  apply congr_right_compat with (p * p2 · r) ; tauto || auto.\n  apply bisim_trans with (emb (p * q · r)) ; [ | apply bisim_symm ] ; auto.\n  apply bisim_trans with (emb (p * (p2 · r))) ; apply BKS2_sound || auto.\n  apply bisim_trans with (emb (p * (q · r))) ;\n    [ | apply bisim_symm ; apply BKS2_sound ].\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  apply bisim_trans with (emb ((p + s) * 0)) ; auto.\n  apply bisim_trans with (emb ((p + s) * (0 · 0))) ; apply BKS2_sound || auto.\n  apply bisim_comp_star ; apply bisim_refl || apply B7_sound.\n  apply congr_right_compat with ((p * q · t) * 0) ; auto.\n  apply bisim_trans with (emb (p * q · r)).\n  apply bisim_symm ; apply RSP_sound.\n  apply bisim_trans with (emb ((p * q · t) · p * q · r)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (p * q · t · p * q · r)) ;\n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || apply bisim_symm ; auto.\n  apply bisim_trans with (emb ((p + s) * 0)) ; [ apply bisim_symm | ] ; auto.\n  apply bisim_trans with (emb ((p + s) * (0 · 0))) ;\n    apply BKS2_sound || auto.\n  apply bisim_comp_star ; apply bisim_refl ||\n    apply bisim_symm ; apply B7_sound.\n  apply bisim_symm ; apply BKS2_sound.\n  simpl ; destruct (depth p2) as [ | m ].\n  apply max_lub.\n  transitivity (depth p) ; omega || auto.\n  apply depth_pres_plus ; auto.\n  assert (max (depth p) (depth s) <= S (depth p)) ; omega || auto.\n  apply max_lub ; omega || auto.\n  simpl in Hleq_s.\n  replace (depth q) with 0%nat in * by omega.\n  rewrite max_0_l in Hleq_s.\n  transitivity (depth t) ; auto.\n  transitivity (depth p) ; auto.\n  apply depth_pres_plus ; auto.\n  apply max_lub.\n  assert (depth t <= max (depth p) m) ; omega || auto.\n  transitivity (depth p) ; apply le_max_l || auto.\n  apply depth_pres_plus ; auto.\n  assert (max (depth p) (depth s) <= S (max (depth p) m)) ; omega || auto.\n  apply max_lub.\n  rewrite succ_max_distr.\n  transitivity (S (depth p)) ; omega || apply le_max_l.\n  transitivity (depth (q · t)) ; auto.\n  simpl ; apply max_lub.\n  rewrite succ_max_distr.\n  transitivity (S m) ; apply le_max_r || auto.\n  rewrite succ_max_distr.\n  transitivity (depth p).\n  apply depth_pres_plus ; auto.\n  transitivity (S (depth p)) ; apply le_max_l || auto.\n\n  (* Invocation of comp_mult_ex results in a different nf *)\n  destruct H as [ s [ Hbisim_s [ Hnf_s Hleq_s ] ] ].\n  right ; exists (t · s) ; split ; [ | split ].\n  apply bisim_trans with (emb (t · p * q · r)) ; \n    [ apply bisim_symm | ] ; auto.\n  apply bisim_trans with (emb (t · s · 0)) ;\n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply bisim_trans with (emb ((p * q · t) * 0)) ; auto.\n  apply RSP_sound.\n  apply bisim_trans with (emb ((p * q · t) · p * q · r)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (p * q · t · p * q · r)) ;\n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || apply bisim_symm ; auto.\n  simpl ; repeat split ; auto.\n  apply nf_mult_pres_plus with p ; auto.\n  simpl in Hnf_mult.\n  apply nf_mult_right_compat with (p * p2 · r) ; tauto || auto.\n  apply bisim_trans with (emb (p * q · r)) ; auto.\n  apply bisim_trans with (emb (p * (p2 · r))) ; apply BKS2_sound || auto.\n  apply bisim_trans with (emb (p * (q · r))) ;\n    [ | apply bisim_symm ; apply BKS2_sound ].\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  apply bisim_trans with (emb ((p * q · t) * 0)) ; auto.\n  apply RSP_sound.\n  apply bisim_trans with (emb ((p * q · t) · p * q · r)) ;\n    [ | apply bisim_symm ; apply B6_sound ].\n  apply bisim_trans with (emb (p * q · t · p * q · r)) ; \n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || apply bisim_symm ; auto.\n  simpl in Hnf_s ; tauto.\n  simpl ; destruct (depth p2) as [ | m ] ; apply max_lub.\n  transitivity (depth p) ; omega || auto.\n  apply depth_pres_plus ; auto.\n  simpl in Hleq_s ; replace (depth q) with 0%nat in * by omega.\n  rewrite max_0_l in Hleq_s ; transitivity (S (depth t)) ; auto.\n  assert (depth t <= depth p) by ( apply depth_pres_plus ; auto ) ; omega.\n  assert (depth t <= max (depth p) m) ; omega || auto.\n  transitivity (depth p) ; apply le_max_l || auto.\n  apply depth_pres_plus ; auto.\n  transitivity (1 + (depth (q · t)))%nat ; simpl ; auto.\n  assert (max (depth q) (depth t) <= S (max (depth p) m)) ; omega || auto.\n  apply max_lub.\n  transitivity (S m) ; auto.\n  assert (m <= max (depth p) m) ; omega || apply le_max_r.\n  transitivity (depth p).\n  apply depth_pres_plus ; auto.\n  rewrite succ_max_distr.\n  transitivity (S (depth p)) ; apply le_max_l || auto.\n\n  (* Case where p -->+ t such that t · p * q · r <=> r does NOT exist *)\n  left ; exists (p * q) ; split ; [ | split ; [ | split ] ].\n  apply bisim_trans with (emb (p * (p2 · r))) ; apply BKS2_sound || auto.\n  apply bisim_trans with (emb (p * (q · r))) ;\n    [ | apply bisim_symm ; apply BKS2_sound ].\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  simpl ; simpl in Hnf_mult ; repeat split ; auto.\n  apply nf_mult_right_compat with (p * p2 · r) ; tauto || auto.\n  apply bisim_trans with (emb (p * (p2 · r))) ; apply BKS2_sound || auto.\n  apply bisim_trans with (emb (p * (q · r))) ;\n    [ | apply bisim_symm ; apply BKS2_sound ].\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  apply congr_right_compat with (p * p2 · r) ; tauto || auto.\n  apply bisim_trans with (emb (p * (p2 · r))) ; apply BKS2_sound || auto.\n  apply bisim_trans with (emb (p * (q · r))) ; \n    [ | apply bisim_symm ; apply BKS2_sound ].\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  intros t Hplus Hbisim'.\n  apply star_plus_fmt in Hplus ; destruct Hplus as [ H | [ H | H ] ].\n  destruct H as [ t' [ Heq Hplus ] ] ; rewrite Heq in *.\n  apply Hplus_ex ; exists t' ; split ; auto.\n  apply bisim_trans with (emb ((t' · p * q) · r)) ; auto.\n  apply bisim_symm ; apply B5_sound.\n  rewrite H in * ; contradiction.\n  apply Hcongr_q in H ; contradiction.\n  simpl ; destruct (depth q) as [ | m ] ; \n    destruct (depth p2) as [ | n ] ; omega || auto.\n  assert (depth p <= max (depth p) n) ; omega || apply le_max_l.\n  assert (max (depth p) m <= max (depth p) n) ; omega || auto.\n  apply max_lub ; apply le_max_l || auto.\n  transitivity n ; omega || apply le_max_r.\n\n  (* Case where IHp2 results in a different nf *)\n  destruct H as [ q [ Hbisim_q [ Hnf_q Hleq_q ] ] ].\n  right ; exists q ; split ; [ | split ] ; auto.\n  simpl ; destruct (depth p2) as [ | m ] ; omega || auto.\n  transitivity (S (S m)) ; omega || auto.\n  assert (m <= max (depth p1) m) ; omega || apply le_max_r.\nQed. \n\nLemma nf_mult_ex : forall (p r : T), exists (q : T), \n  emb (p · r) <=> emb (q · r) /\\ nf_mult q r /\\ depth q <= depth p.\nProof.\n  intro p ; induction p ; intro r.\n  exists 0 ; split ; [ | split ] ; simpl ; apply bisim_refl || auto.\n  exists (act a) ; split ; [ | split ] ; simpl ; apply bisim_refl || auto.\n\n  (* Case for p1 + p2 *)\n  destruct (IHp1 r) as [ q1 [ Hbisim_q1 [ Hnf_q1 Hleq_q1 ] ] ].\n  destruct (IHp2 r) as [ q2 [ Hbisim_q2 [ Hnf_q2 Hleq_q2 ] ] ].\n  exists (q1 + q2) ; split ; [ | split ] ; simpl ; try tauto.\n  apply bisim_trans with (emb (p1 · r + p2 · r)) ; apply B4_sound || auto.\n  apply bisim_trans with (emb (q1 · r + q2 · r)) ; auto.\n  apply bisim_comp_plus ; auto.\n  apply bisim_symm ; apply B4_sound.\n  apply max_lub.\n  transitivity (depth p1) ; apply le_max_l || auto.\n  transitivity (depth p2) ; apply le_max_r || auto.\n\n  (* Case for p1 · p2 *)\n  destruct (IHp1 (p2 · r)) as [ q1 [ Hbisim_q1 [ Hnf_q1 Hleq_q1 ] ] ].\n  destruct (IHp2 r) as [ q2 [ Hbisim_q2 [ Hnf_q2 Hleq_q2 ] ] ].\n  exists (q1 · q2) ; split ; [ | split ] ; auto.\n  apply bisim_trans with (emb (p1 · p2 · r)) ; apply B5_sound || auto.\n  apply bisim_trans with (emb (q1 · q2 · r)) ; auto.\n  apply bisim_trans with (emb (q1 · p2 · r)) ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply bisim_symm ; apply B5_sound.\n  simpl ; split ; auto.\n  apply nf_mult_right_compat with (p2 · r) ; auto.\n  simpl ; apply max_lub.\n  transitivity (depth p1) ; apply le_max_l || auto.\n  transitivity (depth p2) ; apply le_max_r || auto.\n\n  (* Case for p1 * p2 *)\n  destruct (IHp2 r) as [ q2 [ Hbisim_q2 [ Hnf_q2 Hleq_q2 ] ] ].\n  destruct (IHp1 (p1 * p2 · r)) as [ q1 [ Hbisim_q1 [ Hnf_q1 Hleq_q1 ] ] ].\n  assert (emb (p1 * p2 · r) <=> emb (q1 · p1 * p2 · r + p2 · r)) as Hstar_eq.\n  apply bisim_trans with (emb ((p1 · p1 * p2 + p2) · r)).\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply bisim_symm ; apply BKS1_sound.\n  apply bisim_trans with (emb ((p1 · p1 * p2) · r + p2 · r)).\n  apply B4_sound.\n  apply bisim_comp_plus ; apply bisim_refl || auto.\n  apply bisim_trans with (emb (p1 · p1 * p2 · r)) ; apply B5_sound || auto.\n  apply RSP_sound in Hstar_eq.\n  destruct (congr_ex q1 (q1 * p2 · r)) as [ [ s H ] | H ].\n  apply nf_mult_right_compat with (p1 * p2 · r) ; auto.\n  apply bisim_trans with (emb (q1 * (p2 · r))) ; auto.\n  apply bisim_symm ; apply BKS2_sound.\n  destruct H as [ Hbisim_s [ Hnf_s [ Hcongr_s Hleq_s ] ] ].\n  assert (emb (s * p2 · r) <=> emb (q1 * p2 · r)) as Hstar_eq'.\n  apply bisim_trans with (emb (s * (p2 · r))).\n  apply BKS2_sound.\n  apply bisim_symm ; apply RSP_sound.\n  apply bisim_trans with (emb (q1 · q1 * p2 · r + p2 · r)).\n  apply bisim_trans with (emb ((q1 · q1 * p2 + p2) · r)).\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply bisim_symm ; apply BKS1_sound.\n  apply bisim_trans with (emb ((q1 · q1 * p2) · r + p2 · r)).\n  apply B4_sound.\n  apply bisim_comp_plus ; apply bisim_refl || apply B5_sound.\n  apply bisim_comp_plus ; apply bisim_refl || auto.\n  exists (s * q2) ; split ; [ | split ] ; auto.\n  apply bisim_trans with (emb (q1 * (p2 · r))) ; auto.\n  apply bisim_trans with (emb (q1 * p2 · r)).\n  apply bisim_symm ; apply BKS2_sound.\n  apply bisim_symm ; auto.\n  apply bisim_trans with (emb (s * p2 · r)) ; auto.\n  apply bisim_trans with (emb (s * (q2 · r))) ; apply BKS2_sound || auto.\n  apply bisim_trans with (emb (s * (p2 · r))).\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  apply bisim_symm ; auto.\n  apply bisim_symm ; apply BKS2_sound.\n  simpl ; split ; [ | split ] ; auto.\n  apply nf_mult_right_compat with (q1 * p2 · r) ; auto.\n  apply bisim_trans with (emb (s * p2 · r)) ; auto.\n  apply bisim_symm ; auto.\n  apply bisim_trans with (emb (s * (p2 · r))) ; apply BKS2_sound || auto.\n  apply bisim_trans with (emb (s * (q2 · r))).\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  apply bisim_symm ; apply BKS2_sound.\n  apply congr_right_compat with (q1 * p2 · r) ; auto.\n  apply bisim_trans with (emb (s * p2 · r)) ; auto.\n  apply bisim_symm ; auto.\n  apply bisim_trans with (emb (s * (p2 · r))) ; apply BKS2_sound || auto.\n  apply bisim_trans with (emb (s * (q2 · r))) ; auto.\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  apply bisim_symm ; apply BKS2_sound.\n  simpl ; destruct (depth q2) as [ | m ] ; \n    destruct (depth p2) as [ | n ] ; omega || auto.\n  assert (depth s <= max (depth p1) n) ; omega || auto.\n  transitivity (depth q1) ; auto.\n  transitivity (depth p1) ; apply le_max_l || auto.\n  assert (max (depth s) m <= max (depth p1) n) ; omega || auto.\n  apply max_lub.\n  transitivity (depth q1) ; auto.\n  transitivity (depth p1) ; apply le_max_l || auto.\n  transitivity n ; omega || apply le_max_r.\n\n  (* Congruence derivation results in a different nf *)\n  destruct H as [ s [ Hbisim_s [ Hnf_s Hleq_s ] ] ].\n  exists (s · 0) ; split ; [ | split ] ; auto.\n  apply bisim_trans with (emb (s · 0)) ; auto.\n  apply bisim_trans with (emb (q1 * (p2 · r))) ; auto.\n  apply bisim_trans with (emb (q1 * p2 · r)) ; auto.\n  apply bisim_symm ; apply BKS2_sound.\n  apply bisim_trans with (emb (s · 0 · r)).\n  apply bisim_comp_mult ; apply bisim_refl || \n    apply bisim_symm ; apply B7_sound.\n  apply bisim_symm ; apply B5_sound.\n  simpl in * ; split ; auto.\n  apply nf_mult_right_compat with 0 ; tauto || auto.\n  apply bisim_symm ; apply B7_sound.\n  simpl ; destruct (depth p2) as [ | m ] ; rewrite max_0_r.\n  transitivity (1 + depth q1)%nat ; simpl ; omega || auto.\n  transitivity (1 + depth q1)%nat ; simpl ; omega || auto.\n  assert (depth q1 <= max (depth p1) m) ; omega || auto.\n  transitivity (depth p1) ; apply le_max_l || auto.\nQed.\n\nLemma normalization : forall (p : T),\n  exists (q : T), emb p <=> emb q /\\ nf q /\\ depth q <= depth p.\nProof.\n  intro p ; induction p.\n  exists 0 ; split ; [ | split ] ; simpl ; apply bisim_refl || auto.\n  exists (act a) ; split ; [ | split ] ; simpl ; apply bisim_refl || auto.\n\n  (* Case for p1 + p2 *)\n  destruct IHp1 as [ q1 [ Hbisim_q1 [ Hnf_q1 Hleq_q1 ] ] ].\n  destruct IHp2 as [ q2 [ Hbisim_q2 [ Hnf_q2 Hleq_q2 ] ] ].\n  exists (q1 + q2) ; split ; [ | split ] ; simpl ; try tauto.\n  apply bisim_comp_plus ; auto.\n  apply max_lub.\n  transitivity (depth p1) ; [ auto | apply le_max_l ].\n  transitivity (depth p2) ; [ auto | apply le_max_r ].\n\n  (* Case for p1 · p2 *)\n  destruct IHp2 as [ q2 [ Hbisim_q2 [ Hnf_q2 Hleq_q2 ] ] ].\n  destruct (nf_mult_ex p1 q2) as [ q1 [ Hbisim_q1 [ Hnf_q1 Hleq_q1 ] ] ].\n  exists (q1 · q2) ; split ; [ | split ] ; simpl ; try tauto.\n  apply bisim_trans with (emb (p1 · q2)) ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || auto.\n  apply max_lub.\n  transitivity (depth p1) ; [ auto | apply le_max_l ].\n  transitivity (depth p2) ; [ auto | apply le_max_r ].\n\n  (* Case for p1 * p2 *)\n  destruct IHp2 as [ q2 [ Hbisim_q2 [ Hnf_q2 Hleq_q2 ] ] ].\n  destruct (nf_mult_ex p1 (p1 * p2)) as [ q1 [ Hbisim_q1 [ Hnf_q1 Hleq_q1 ] ] ].\n  assert (emb (p1 * p2) <=> emb (q1 · p1 * p2 + p2)) as Hstar_eq.\n  apply bisim_trans with (emb (p1 · p1 * p2 + p2)).\n  apply bisim_symm ; apply BKS1_sound.\n  apply bisim_comp_plus ; apply bisim_refl || auto.\n  apply RSP_sound in Hstar_eq.\n  destruct (congr_ex q1 (q1 * p2)) as [ H | H ] ; auto.\n  apply nf_mult_right_compat with (p1 * p2) ; auto.\n  destruct H as [ s [ Hbisim_s [ Hnf_s [ Hcongr_s Hleq_s ] ] ] ].\n  assert (emb (q1 * p2) <=> emb (s * p2)) as Hstar_eq'.\n  assert (emb (q1 * p2) <=> emb (s · q1 * p2 + p2)) as H.\n  apply bisim_trans with (emb (q1 · q1 * p2 + p2)).\n  apply bisim_symm ; apply BKS1_sound.\n  apply bisim_comp_plus ; apply bisim_refl || auto.\n  apply RSP_sound in H ; auto.\n  exists (s * q2) ; split ; [ | split ] ; auto.\n  apply bisim_trans with (emb (q1 * p2)) ; auto.\n  apply bisim_trans with (emb (s * p2)) ; auto.\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  simpl ; split ; [ | split ] ; auto.\n  apply nf_mult_right_compat with (q1 * p2) ; auto.\n  apply bisim_trans with (emb (s * p2)) ; auto.\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  apply congr_right_compat with (q1 * p2) ; auto.\n  apply bisim_trans with (emb (s * p2)) ; auto.\n  apply bisim_comp_star ; apply bisim_refl || auto.\n  simpl ; destruct (depth q2) as [ | m ] ; \n    destruct (depth p2) as [ | n ] ; omega || auto.\n  assert (depth s <= max (depth p1) n) ; omega || auto.\n  transitivity (depth q1) ; auto.\n  transitivity (depth p1) ; apply le_max_l || auto.\n  assert (max (depth s) m <= max (depth p1) n) ; omega || auto.\n  apply max_lub.\n  transitivity (depth q1) ; auto.\n  transitivity (depth p1) ; apply le_max_l || auto.\n  transitivity n ; apply le_max_r || omega.\n\n  (* Congruence derivation results in different nf *)\n  destruct H as [ q [ Hbisim_q [ Hnf_q Hleq_q ] ] ].\n  exists (q · 0) ; split ; [ | split ] ; auto.\n  apply bisim_trans with (emb (q1 * p2)) ; auto.\n  simpl ; destruct (depth p2) as [ | m ] ; rewrite max_0_r.\n  transitivity (1 + depth q1)%nat ; omega.\n  transitivity (1 + depth q1)%nat ; simpl ; auto.\n  assert (depth q1 <= max (depth p1) m) ; omega || auto.\n  transitivity (depth p1) ; apply le_max_l || auto.\nQed.\n\nLemma next_term_in : forall (N : list (A * V)) (a : A),\n  In (a, term) N -> sum N == (sum N + act a).\nProof.\n  intro N ; induction N as [ | [ a' u ] N ] ; \n    intros a Hin ; simpl in * ; contradiction || auto.\n  destruct Hin as [ H | Hin ].\n  replace a' with a in * by ( inversion H ; auto ).\n  replace u with term in * by ( inversion H ; auto ).\n  apply trans with (act a + (act a + sum N)) ; apply B1 || auto.\n  apply trans with (act a + act a + sum N) ; apply B2 || auto.\n  apply comp_plus ; apply refl || apply symm ; apply B3.\n  destruct u as [ | p ].\n  apply trans with (act a' + (sum N + act a)) ; \n    [ | apply symm ; apply B2 ].\n  apply comp_plus ; apply refl || apply IHN ; auto.\n  apply trans with (act a' · p + (sum N + act a)) ;\n    [ | apply symm ; apply B2 ].\n  apply comp_plus ; apply refl || apply IHN ; auto.\nQed.\n\nLemma next_emb_in : forall (N : list (A * V)) (a : A) (p : T),\n  In (a, emb p) N -> sum N == (sum N + act a · p).\nProof.\n  intro N ; induction N as [ | [ a' u ] N ] ;\n    intros a p Hin ; simpl in * ; contradiction || auto.\n  destruct Hin as [ H | Hin ].\n  replace a' with a in * by ( inversion H ; auto ).\n  replace u with (emb p) in * by ( inversion H ; auto ).\n  apply trans with (act a · p + (act a · p + sum N)) ; apply B1 || auto.\n  apply trans with (act a · p + act a · p + sum N) ; apply B2 || auto.\n  apply comp_plus ; apply refl || apply symm ; apply B3.\n  destruct u as [ | q ].\n  apply trans with (act a' + (sum N + act a · p)) ; \n    [ | apply symm ; apply B2 ].\n  apply comp_plus ; apply refl || apply IHN ; auto.\n  apply trans with (act a' · q + (sum N + act a · p)) ;\n    [ | apply symm ; apply B2 ].\n  apply comp_plus ; apply refl || apply IHN ; auto.\nQed.\n\nLemma next : forall (p q : T),\n  (forall (a : A) (u : V), emb p -(a)-> u ->\n    exists (v : V), emb q -(a)-> v /\\ teq u v) ->\n  (forall (a : A) (v : V), emb q -(a)-> v ->\n    exists (u : V), emb p -(a)-> u /\\ teq u v) -> p == q.\nProof.\n  assert (forall (M N : list (A * V)), \n    (forall (a : A) (u : V), In (a, u) M ->\n      exists (v : V), In (a, v) N /\\ teq u v) -> \n    (sum M + sum N) == sum N) as Hmain.\n  intro M ; induction M as [ | [ a u ] M ] ; intros N Hcond.\n  simpl ; apply trans with (sum N + 0) ; apply B1 || apply B6.\n  destruct u as [ | p ] ; simpl.\n  apply trans with (sum N + act a).\n  apply trans with (act a + sum N) ; apply B1 || auto.\n  apply trans with (act a + (sum M + sum N)) ; [ apply B2 | ].\n  apply comp_plus ; apply refl || apply IHM.\n  intros a' u' Hin ; apply Hcond ; simpl ; auto.\n  apply symm ; apply next_term_in.\n  assert (In (a, term) ((a, term) :: M)) as H by ( simpl ; auto ).\n  apply Hcond in H ; destruct H as [ v [ Hin Hteq ] ].\n  destruct v as [ | q ] ; auto.\n  unfold teq in Hteq ; contradiction.\n  assert (In (a, emb p) ((a, emb p) :: M)) as H by ( simpl ; auto ).\n  apply Hcond in H ; destruct H as [ v [ Hin Hteq ] ].\n  destruct v as [ | q ] ; [ unfold teq in * ; contradiction | ].\n  apply trans with (sum N + act a · q).\n  apply trans with (act a · q + sum N) ; apply B1 || auto.\n  apply trans with (act a · p + (sum M + sum N)) ; apply B2 || auto.\n  apply comp_plus ; auto.\n  apply comp_mult ; apply refl || unfold teq in * ; auto.\n  apply IHM ; intros a' u' Hin'.\n  apply Hcond ; simpl ; auto.\n  apply symm ; apply next_emb_in ; auto.\n  intros p q Hltr Hrtl.\n  destruct (summation p) as [ Np [ Hiff_p Heq_p ] ].\n  destruct (summation q) as [ Nq [ Hiff_q Heq_q ] ].\n  apply trans with (sum Np) ; [ apply symm ; auto | ].\n  apply trans with (sum Nq) ; [ | auto ].\n  apply trans with (sum Np + sum Nq) ; [ apply symm | ].\n  apply trans with (sum Nq + sum Np) ; apply B1 || auto.\n  apply Hmain ; intros a u Hin.\n  apply Hiff_q in Hin ; apply Hrtl in Hin.\n  destruct Hin as [ v [ Hstep Hteq ] ].\n  apply Hiff_p in Hstep ; exists v ; split ; auto.\n  destruct u as [ | p' ] ; destruct v as [ | q' ] ; auto.\n  unfold teq in * ; apply symm ; auto.\n  apply Hmain ; intros a u Hin.\n  apply Hiff_p in Hin ; apply Hltr in Hin.\n  destruct Hin as [ v [ Hstep Hteq ] ].\n  apply Hiff_q in Hstep ; exists v ; split ; auto.\nQed.\n\nLemma sum_step : forall (M : list (A * V)) (a : A) (u : V),\n  emb (sum M) -(a)-> u -> In (a, u) M.\nProof.\n  intro M ; induction M as [ | [ a' u' ] M ] ; intros a u Hstep.\n  simpl in Hstep ; inversion Hstep.\n  simpl in Hstep ; destruct u' as [ | p' ] ; simpl.\n  apply step_plus_fmt in Hstep ; destruct Hstep as [ H | H ].\n  replace a' with a in * by ( inversion H ; auto ).\n  replace u with term in * by ( inversion H ; auto ) ; auto.\n  apply IHM in H ; auto.\n  apply step_plus_fmt in Hstep ; destruct Hstep as [ Hstep | H ].\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ p'' [ _ H ] ] ; inversion H.\n  destruct H as [ H Heq ] ; rewrite Heq in *.\n  replace a' with a in * by ( inversion H ; auto ) ; auto.\n  apply IHM in H ; auto.\nQed.\n\nLemma step_sum : forall (M : list (A * V)) (a : A) (u : V),\n  In (a, u) M -> emb (sum M) -(a)-> u.\nProof.\n  intro M ; induction M as [ | [ a' u' ] M ] ; intros a u Hin.\n  simpl in Hin ; contradiction.\n  simpl in Hin ; destruct Hin as [ H | Hin ] ; simpl ; destruct u' as [ | q ].\n  replace a' with a in * by ( inversion H ; auto ).\n  replace u with term in * by ( inversion H ; auto ).\n  apply step_plus_left ; apply step_act.\n  replace a' with a in * by ( inversion H ; auto ).\n  replace u with (emb q) in * by ( inversion H ; auto ).\n  apply step_plus_left ; apply step_mult_right ; apply step_act.\n  apply IHM in Hin ; apply step_plus_right ; auto.\n  apply IHM in Hin ; apply step_plus_right ; auto.\nQed.\n\nLemma eq_list_eq_sum : forall (M N : list (A * V)),\n  eqlist M N -> sum M == sum N.\nProof.\n  intros M N Heqlist ; apply next.\n  intros a u Hstep ; apply sum_step in Hstep.\n  apply Heqlist in Hstep ; exists u ; split ; auto.\n  apply step_sum ; auto.\n  destruct u ; unfold teq ; apply refl || auto.\n  intros a u Hstep ; apply sum_step in Hstep.\n  apply Heqlist in Hstep ; exists u ; split ; auto.\n  apply step_sum ; auto.\n  destruct u ; unfold teq ; apply refl || auto.\nQed.\n\nLemma single_split : forall (M : list (A * V)) (p : T),\n  exists (N : list (A * V)), forall (a : A) (u : V),\n    In (a, u) N <-> In (a, u) M /\\ exists (v : V), emb p -(a)-> v /\\ u <=> v.\nProof.\n  intro M ; induction M as [ | [ a w ] M ] ; intro p.\n  exists nil ; intros a u ; split ; intro H ; simpl in * ; try tauto.\n  destruct (IHM p) as [ N Hiff ].\n  destruct (LEM (exists (v : V), emb p -(a)-> v /\\ w <=> v)) as [ H | H ].\n  destruct H as [ v [ Hstep Hbisim ] ].\n  exists ((a, w) :: N) ; intros a' u ; split ; intro H.\n  simpl in H ; destruct H as [ H | H ].\n  simpl ; split ; auto.\n  replace a' with a in * by ( inversion H ; auto ).\n  exists v ; split ; auto.\n  replace w with u in * by ( inversion H ; auto ) ; auto.\n  apply Hiff in H ; simpl ; split ; tauto || auto.\n  simpl in H ; destruct H as [ [ H | H ] Hex ].\n  simpl ; auto.\n  simpl ; right ; apply Hiff ; split ; auto.\n  exists N ; intros a' u ; split ; intro H'.\n  apply Hiff in H' ; destruct H' as [ Hin Hex ].\n  simpl ; split ; auto.\n  simpl in H' ; destruct H' as [ [ H' | H' ] Hex ].\n  replace a' with a in * by ( inversion H' ; auto ).\n  replace w with u in * by ( inversion H' ; auto ) ; contradiction.\n  apply Hiff ; split ; auto.\nQed.\n\nLemma single_split_mult : forall (M : list (A * V)) (p q : T),\n  exists (N : list (A * V)), forall (a : A) (u : V),\n    In (a, u) N <-> In (a, u) M /\\ exists (v : V), emb p -(a)-> v /\\ \n      emb (mult' u q) <=> v.\nProof.\n  intro M ; induction M as [ | [ a w ] M ] ; intros p q.\n  exists nil ; intros a u ; split ; intro H ; simpl in * ; try tauto.\n  destruct (IHM p q) as [ N Hiff ].\n  destruct (LEM (exists (v : V), emb p -(a)-> v /\\ \n    emb (mult' w q) <=> v)) as [ H | H ].\n  destruct H as [ v [ Hstep Hbisim ] ].\n  exists ((a, w) :: N) ; intros a' u ; split ; intro H.\n  simpl in H ; destruct H as [ H | H ].\n  simpl ; split ; auto.\n  replace a' with a in * by ( inversion H ; auto ).\n  exists v ; split ; auto.\n  replace w with u in * by ( inversion H ; auto ) ; auto.\n  apply Hiff in H ; simpl ; split ; tauto || auto.\n  simpl in H ; destruct H as [ [ H | H ] Hex ].\n  simpl ; auto.\n  simpl ; right ; apply Hiff ; split ; auto.\n  exists N ; intros a' u ; split ; intro H'.\n  apply Hiff in H' ; destruct H' as [ Hin Hex ].\n  simpl ; split ; auto.\n  simpl in H' ; destruct H' as [ [ H' | H' ] Hex ].\n  replace a' with a in * by ( inversion H' ; auto ).\n  replace w with u in * by ( inversion H' ; auto ) ; contradiction.\n  apply Hiff ; split ; auto.\nQed.\n\nLemma double_split : forall (p q r : T) (M N : list (A * V)),\n  emb (sum M · p + sum N) <=> emb (q + r) -> exists (Mq Mr Nq Nr : list (A * V)),\n    eqlist M (Mq ++ Mr) /\\ eqlist N (Nq ++ Nr) /\\\n      emb (sum Mq · p + sum Nq) <=> emb q /\\\n      emb (sum Mr · p + sum Nr) <=> emb r.\nProof.\n  intros p q r M N Hbisim.\n  destruct (single_split_mult M q p) as [ Mq Hiff_Mq ].\n  destruct (single_split_mult M r p) as [ Mr Hiff_Mr ].\n  destruct (single_split N q) as [ Nq Hiff_Nq ].\n  destruct (single_split N r) as [ Nr Hiff_Nr ].\n  exists Mq ; exists Mr ; exists Nq ; exists Nr ;\n    split ; [ | split ; [ | split ] ].\n\n  (* eqlist M (Mq ++ Mr) *)\n  intros a u ; split ; intro Hin.\n  destruct u as [ | s ].\n  assert (emb (sum M · p + sum N) -(a)-> emb p) as Hstep.\n  apply step_plus_left ; apply step_mult_right ; apply step_sum ; auto.\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  apply HinR in Hstep ; destruct Hstep as [ v [ Hstep HR ] ].\n  apply step_plus_fmt in Hstep ; destruct Hstep as [ Hstep | Hstep ].\n  apply in_or_app ; left ; apply Hiff_Mq ; split ; auto.\n  exists v ; split ; auto.\n  simpl ; exists R ; split ; auto.\n  apply in_or_app ; right ; apply Hiff_Mr ; split ; auto.\n  exists v ; split ; auto.\n  simpl ; exists R ; split ; auto.\n  assert (emb (sum M · p + sum N) -(a)-> emb (s · p)) as Hstep.\n  apply step_plus_left ; apply step_mult_left ; apply step_sum ; auto.\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  apply HinR in Hstep ; destruct Hstep as [ v [ Hstep HR ] ].\n  apply step_plus_fmt in Hstep ; destruct Hstep as [ Hstep | Hstep ].\n  apply in_or_app ; left ; apply Hiff_Mq ; split ; auto.\n  exists v ; split ; simpl ; auto.\n  exists R ; split ; auto.\n  apply in_or_app ; right ; apply Hiff_Mr ; split ; auto.\n  exists v ; split ; simpl ; auto.\n  exists R ; split ; auto.\n  apply in_app_or in Hin ; destruct Hin as [ Hin | Hin ].\n  apply Hiff_Mq in Hin ; tauto.\n  apply Hiff_Mr in Hin ; tauto.\n\n  (* eqlist N (Nq ++ Nr) *)\n  intros a u ; split ; intro Hin.\n  assert (emb (sum M · p + sum N) -(a)-> u) as Hstep.\n  apply step_plus_right ; apply step_sum ; auto.\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  apply HinR in Hstep ; destruct Hstep as [ v [ Hstep HR ] ].\n  apply step_plus_fmt in Hstep ; destruct Hstep as [ Hstep | Hstep ].\n  apply in_or_app ; left ; apply Hiff_Nq ; split ; auto.\n  exists v ; split ; auto.\n  exists R ; split ; auto.\n  apply in_or_app ; right ; apply Hiff_Nr ; split ; auto.\n  exists v ; split ; auto.\n  exists R ; split ; auto.\n  apply in_app_or in Hin ; destruct Hin as [ Hin | Hin ].\n  apply Hiff_Nq in Hin ; tauto.\n  apply Hiff_Nr in Hin ; tauto.\n\n  (* sum Mq · p + sum Nq <=> q *)\n  apply bisim_next.\n  split ; intro H ; inversion H.\n  intros a u H ; apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ s [ Heq Hstep ] ] ; rewrite Heq in *.\n  apply sum_step in Hstep ; apply Hiff_Mq in Hstep.\n  destruct Hstep as [ _ [ v [ Hstep Hbisim' ] ] ].\n  exists v ; split ; simpl in * ; auto.\n  destruct H as [ Hstep Heq ] ; rewrite Heq in *.\n  apply sum_step in Hstep ; apply Hiff_Mq in Hstep.\n  destruct Hstep as [ _ [ v [ Hstep Hbisim' ] ] ].\n  exists v ; split ; simpl in * ; auto.\n  apply sum_step in H ; apply Hiff_Nq in H.\n  destruct H as [ _ [ v [ Hstep Hbisim' ] ] ].\n  exists v ; split ; auto.\n  intros a v Hstep ; assert (emb (q + r) -(a)-> v) as H by\n    ( apply step_plus_left ; auto ).\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  apply HinR in H ; destruct H as [ u [ H HR ] ].\n  apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ s [ Heq H ] ] ; rewrite Heq in *.\n  apply sum_step in H ; exists (emb (s · p)) ; split.\n  apply step_plus_left ; apply step_mult_left ; apply step_sum.\n  apply Hiff_Mq ; split ; auto.\n  exists v ; split ; auto.\n  simpl ; exists R ; split ; auto.\n  simpl ; exists R ; split ; auto.\n  destruct H as [ Hstep' Heq ] ; rewrite Heq in *.\n  exists (emb p) ; split ; auto.\n  apply step_plus_left ; apply step_mult_right.\n  apply step_sum ; apply Hiff_Mq.\n  apply sum_step in Hstep' ; split ; auto.\n  exists v ; split ; auto.\n  simpl ; exists R ; split ; auto.\n  simpl ; exists R ; split ; auto.\n  exists u ; split ; auto.\n  apply step_plus_right ; apply step_sum.\n  apply Hiff_Nq ; apply sum_step in H ; split ; auto.\n  exists v ; split ; auto.\n  exists R ; split ; auto.\n  exists R ; split ; auto.\n\n  (* sum Mr · p + sum Nr <=> r *)\n  apply bisim_next.\n  split ; intro H ; inversion H.\n  intros a u H ; apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ s [ Heq Hstep ] ] ; rewrite Heq in *.\n  apply sum_step in Hstep ; apply Hiff_Mr in Hstep.\n  destruct Hstep as [ _ [ v [ Hstep Hbisim' ] ] ].\n  exists v ; split ; simpl in * ; auto.\n  destruct H as [ Hstep Heq ] ; rewrite Heq in *.\n  apply sum_step in Hstep ; apply Hiff_Mr in Hstep.\n  destruct Hstep as [ _ [ v [ Hstep Hbisim' ] ] ].\n  exists v ; split ; simpl in * ; auto.\n  apply sum_step in H ; apply Hiff_Nr in H.\n  destruct H as [ _ [ v [ Hstep Hbisim' ] ] ].\n  exists v ; split ; auto.\n  intros a v Hstep ; assert (emb (q + r) -(a)-> v) as H by\n    ( apply step_plus_right ; auto ).\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  apply HinR in H ; destruct H as [ u [ H HR ] ].\n  apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ s [ Heq H ] ] ; rewrite Heq in *.\n  apply sum_step in H ; exists (emb (s · p)) ; split.\n  apply step_plus_left ; apply step_mult_left ; apply step_sum.\n  apply Hiff_Mr ; split ; auto.\n  exists v ; split ; auto.\n  simpl ; exists R ; split ; auto.\n  simpl ; exists R ; split ; auto.\n  destruct H as [ Hstep' Heq ] ; rewrite Heq in *.\n  exists (emb p) ; split ; auto.\n  apply step_plus_left ; apply step_mult_right.\n  apply step_sum ; apply Hiff_Mr.\n  apply sum_step in Hstep' ; split ; auto.\n  exists v ; split ; auto.\n  simpl ; exists R ; split ; auto.\n  simpl ; exists R ; split ; auto.\n  exists u ; split ; auto.\n  apply step_plus_right ; apply step_sum.\n  apply Hiff_Nr ; apply sum_step in H ; split ; auto.\n  exists v ; split ; auto.\n  exists R ; split ; auto.\n  exists R ; split ; auto.\nQed.\n\nLemma teq_symm : forall (u v : V), teq u v -> teq v u.\nProof.\n  intros u v H ; destruct u as [ | p ] ; destruct v as [ | q ] ; auto.\n  unfold teq in * ; apply symm ; auto.\nQed.\n\nLemma RSP_inv_sound : forall (p q r : T),\n  emb p <=> emb (q * r) -> emb p <=> emb (q · p + r).\nProof.\n  intros p q r H ; apply bisim_trans with (emb (q * r)) ; auto.\n  apply bisim_trans with (emb (q · q * r + r)).\n  apply bisim_symm ; apply BKS1_sound.\n  apply bisim_comp_plus ; apply bisim_refl || auto.\n  apply bisim_comp_mult ; apply bisim_refl || apply bisim_symm ; auto.\nQed.\n\nLemma complete_split_mult : forall (p q r s t : T) (M N : list (A * V)),\n  emb (sum M · p * q + sum N) <=> emb (r · s) -> nf (p * q) ->\n  (forall (u v : V) (a : A), emb q -(a)-> u -> u <=> v -> teq u v) ->\n  (forall (x y : T), depth x < depth (p * q) -> emb x <=> emb y -> x == y) ->\n  (forall (t u : V) (a : A), In (a, t) N -> t <=> u -> teq t u) ->\n  p -->* t -> (forall (a : A) (u : V), In (a, u) M -> emb t -(a)-> u) ->\n  (forall (M' N' : list (A * V)) (u : T), \n    emb (sum M' · p * q + sum N') <=> emb s -> p -->* u ->\n    (forall (a : A) (v : V), In (a, v) M' -> emb u -(a)-> v) ->\n    (forall (v w : V) (a : A), In (a, v) N' -> v <=> w -> teq v w) ->\n    (sum M' · p * q + sum N') == s) ->\n  (sum M · p * q + sum N) == (r · s).\nProof.\n  intros p q r ; revert p q ; induction r ;\n    intros p q s t M N Hbisim Hnf Hleft_top IHprov IHN Hclos HM Hright_top.\n\n  (* Case for 0 *)\n  apply next ; apply bisim_fwd in Hbisim.\n  intros a u Hstep ; apply Hbisim in Hstep.\n  destruct Hstep as [ v [ Hstep Hbisim' ] ].\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ x [ Heq Hstep ] ] ; inversion Hstep.\n  destruct H as [ H _ ] ; inversion H.\n  intros a v Hstep ; apply step_mult_fmt in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ x [ _ H ] ] ; inversion H.\n  destruct H as [ H _ ] ; inversion H.\n\n  (* Case for a \\in A *)\n  assert (forall (a' : A) (u v : V),\n    emb (sum M · p * q + sum N) -(a')-> u -> \n    emb (act a · s) -(a')-> v -> u <=> v -> teq u v) as Hnext.\n  intros a' u v Hstep_l Hstep_r Hbisim'.\n  apply step_mult_fmt in Hstep_r ; destruct Hstep_r as [ H | H ].\n  destruct H as [ x [ Heq Hstep ] ] ; rewrite Heq in * ; inversion Hstep.\n  destruct H as [ Hstep Heq ] ; rewrite Heq in *.\n  apply step_plus_fmt in Hstep_l ; destruct Hstep_l as [ H | H ].\n  replace a' with a in * by ( inversion Hstep ; auto ).\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ p' [ Heq' Hstep' ] ] ; rewrite Heq' in *.\n  unfold teq ; destruct (summation p') as [ K [ Hiff_K Heq_K ] ].\n  apply trans with (sum K · p * q).\n  apply comp_mult ; apply refl || apply symm ; auto.\n  apply trans with (sum K · p * q + sum nil) ; \n    [ apply symm ; apply B6 | ].\n  apply Hright_top with p'.\n  simpl ; apply bisim_trans with (emb (sum K · p * q)) ; apply B6_sound || auto.\n  apply bisim_trans with (emb (p' · p * q)) ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || apply soundness ; auto.\n  apply sum_step in Hstep' ; apply HM in Hstep'.\n  apply clos_clos with t ; auto.\n  apply clos_trans with p' a ; apply clos_refl || auto.\n  intros a'' w Hin ; apply Hiff_K ; auto.\n  intros u' v' a'' Hin ; simpl in Hin ; contradiction.\n  destruct H as [ Hstep' Heq' ] ; rewrite Heq' in * ; unfold teq.\n  apply trans with (p · p * q + q) ; [ apply symm ; apply BKS1 | ].\n  destruct (summation p) as [ K [ Hiff_K Heq_K ] ].\n  destruct (summation q) as [ L [ Hiff_L Heq_L ] ].\n  apply trans with (sum K · p * q + sum L).\n  apply comp_plus ; [ | apply symm ; auto ].\n  apply comp_mult ; apply refl || apply symm ; auto.\n  apply Hright_top with p ; apply clos_refl || auto.\n  apply bisim_trans with (emb (p · p * q + q)) ; auto.\n  apply bisim_comp_plus ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || apply soundness ; auto.\n  apply soundness ; auto.\n  apply bisim_trans with (emb (p * q)) ; apply BKS1_sound || auto.\n  intros a'' w Hin ; apply Hiff_K ; auto.\n  intros u' v' a'' Hin Hbisim''.\n  apply Hleft_top with a'' ; auto.\n  apply Hiff_L ; auto.\n  apply sum_step in H.\n  apply IHN with a' ; auto.\n  apply bisim_fwd in Hbisim ; apply next.\n  intros a' x Hstep_x.\n  assert (emb (sum M · p * q + sum N) -(a')-> x) as Hstep by auto.\n  apply Hbisim in Hstep ; destruct Hstep as [ y [ Hstep_y Hbisim' ] ].\n  exists y ; split ; auto.\n  apply Hnext with a' ; auto.\n  intros a' y Hstep_y.\n  assert (emb (act a · s) -(a')-> y) as Hstep by auto.\n  apply Hbisim in Hstep ; destruct Hstep as [ x [ Hstep_x Hbisim' ] ].\n  exists x ; split ; auto.\n  apply Hnext with a' ; auto.\n\n  (* Case for r1 + r2 *)\n  apply trans with (r1 · s + r2 · s) ; [ | apply symm ; apply B4 ].\n  destruct (double_split (p * q) (r1 · s) (r2 · s) M N) as\n    [ M1 [ M2 [ N1 [ N2 H ] ] ] ] ; auto.\n  apply bisim_trans with (emb ((r1 + r2) · s)) ; apply B4_sound || auto.\n  destruct H as [ HMeqlist [ HNeqlist [ Hbisim_r1 Hbisim_r2 ] ] ].\n  apply trans with (sum M1 · p * q + sum N1 + (sum M2 · p * q + sum N2)).\n  apply trans with (sum M1 · p * q + sum N1 + sum M2 · p * q + sum N2) ;\n    [ | apply B2 ].\n  apply trans with (sum M1 · p * q + sum M2 · p * q + sum N1 + sum N2).\n  apply trans with (sum M1 · p * q + sum M2 · p * q + (sum N1 + sum N2)) ;\n    [ | apply symm ; apply B2 ].\n  apply comp_plus.\n  apply trans with ((sum M1 + sum M2) · p * q) ; apply B4 || auto.\n  apply comp_mult ; apply refl || auto.\n  apply trans with (sum (M1 ++ M2)) ; apply sum_app || auto.\n  apply eq_list_eq_sum ; auto.\n  apply trans with (sum (N1 ++ N2)) ; apply sum_app || auto.\n  apply eq_list_eq_sum ; auto.\n  apply comp_plus ; apply refl || auto.\n  apply trans with (sum M1 · p * q + (sum M2 · p * q + sum N1)) ;\n    [ apply B2 | ].\n  apply trans with (sum M1 · p * q + (sum N1 + sum M2 · p * q)) ;\n    [ | apply symm ; apply B2 ].\n  apply comp_plus ; apply refl || apply B1.\n  apply comp_plus ; [ apply IHr1 with t | apply IHr2 with t ] ; auto.\n  intros u v a Hin Hbisim' ; apply IHN with a ; auto.\n  apply HNeqlist ; apply in_or_app ; auto.\n  intros a u Hin ; apply HM ; auto.\n  apply HMeqlist ; apply in_or_app ; auto.\n  intros u v a Hin Hbisim' ; apply IHN with a ; auto.\n  apply HNeqlist ; apply in_or_app ; auto.\n  intros a u Hin ; apply HM ; auto.\n  apply HMeqlist ; apply in_or_app ; auto.\n \n  (* Case for r1 · r2 *)\n  apply trans with (r1 · r2 · s) ; [ | apply symm ; apply B5 ].\n  apply IHr1 with t ; auto.\n  apply bisim_trans with (emb ((r1 · r2) · s)) ; apply B5_sound || auto.\n  intros M' N' u Hbisim' Hclos' HM' HN'.\n  apply IHr2 with u ; auto.\n\n  (* Case for r1 * r2 *)\n  apply trans with (r1 * (r2 · s)) ; [ | apply symm ; apply BKS2 ].\n  apply RSP.\n  destruct (double_split (p * q) (r1 · (sum M · p * q + sum N)) (r2 · s) M N) as\n    [ M1 [ M2 [ N1 [ N2 H ] ] ] ] ; auto.\n  assert (emb (sum M · p * q + sum N) <=> emb (r1 * (r2 · s))) as Hbisim_inv.\n  apply bisim_trans with (emb (r1 * r2 · s)) ; apply BKS2_sound || auto.\n  apply RSP_inv_sound in Hbisim_inv ; auto.\n  destruct H as [ HeqlistM [ HeqlistN [ Hbisim_r1 Hbisim_r2 ] ] ].\n  apply trans with (sum M1 · p * q + sum N1 + (sum M2 · p * q + sum N2)).\n  apply trans with (sum M1 · p * q + sum N1 + sum M2 · p * q + sum N2) ;\n    apply B2 || auto.\n  apply trans with (sum M1 · p * q + sum M2 · p * q + sum N1 + sum N2).\n  apply trans with (sum M1 · p * q + sum M2 · p * q + (sum N1 + sum N2)) ;\n    [ | apply symm ; apply B2 ].\n  apply comp_plus.\n  apply trans with ((sum M1 + sum M2) · p * q) ; apply B4 || auto.\n  apply comp_mult ; apply refl || auto.\n  apply trans with (sum (M1 ++ M2)) ; apply sum_app || auto.\n  apply eq_list_eq_sum ; auto.\n  apply trans with (sum (N1 ++ N2)) ; apply sum_app || auto.\n  apply eq_list_eq_sum ; auto.\n  apply comp_plus ; apply refl || auto.\n  apply trans with (sum M1 · p * q + (sum M2 · p * q + sum N1)) ;\n    [ apply B2 | ].\n  apply trans with (sum M1 · p * q + (sum N1 + sum M2 · p * q)) ; \n    [ | apply symm ; apply B2 ].\n  apply comp_plus ; apply refl || apply B1.\n  apply comp_plus.\n  apply IHr1 with t ; auto.\n  intros u v a Hin Hbisim'.\n  apply IHN with a ; auto.\n  apply HeqlistN ; apply in_or_app ; auto.\n  intros a u Hin ; apply HM.\n  apply HeqlistM ; apply in_or_app ; auto.\n\n  (* Congruence application *)\n  intros M' N' u Hbisim' Hclos' IHM' IHN'.\n  assert (forall (a : A) (u v : V), emb (sum M' · p * q + sum N') -(a)-> u ->\n    emb (sum M · p * q + sum N) -(a)-> v -> u <=> v -> teq u v) as Hnext.\n  intros a w v H H' Hbisim''.\n  apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply step_plus_fmt in H' ; destruct H' as [ H' | H' ].\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ x [ Heq_x Hstep_x ] ] ; rewrite Heq_x in *.\n  apply sum_step in Hstep_x ; apply IHM' in Hstep_x.\n  apply step_mult_fmt in H' ; destruct H' as [ H' | H' ].\n  destruct H' as [ y [ Heq_y Hstep_y ] ] ; rewrite Heq_y in *.\n  apply sum_step in Hstep_y ; apply HM in Hstep_y.\n  unfold teq ; apply comp_mult ; apply refl || auto.\n  apply IHprov ; auto.\n  assert (depth x <= depth p) as Hpx.\n  apply depth_pres_plus.\n  apply clos_init_cases in Hclos' ; destruct Hclos' as [ H | H ].\n  rewrite <- H in * ; exists a ; exists x ; split ; apply clos_refl || auto.\n  destruct H as [ a' [ p' [ Hstep Htr ] ] ].\n  exists a' ; exists p' ; split ; auto.\n  apply clos_clos with u ; auto.\n  apply clos_trans with x a ; apply clos_refl || auto.\n  assert (depth p < depth (p * q)) ; omega || auto.\n  simpl ; destruct (depth q) ; auto.\n  rewrite succ_max_distr.\n  assert (S (depth p) <= max (S (depth p)) (S n)) ; omega || apply le_max_l.\n  apply congruence with (p * q) ; auto.\n  apply comp_plus_left.\n  apply congr_pres_plus with p ; solve [ simpl in * ; tauto ] || auto.\n  apply clos_init_cases in Hclos' ; destruct Hclos' as [ H | H ].\n  rewrite <- H in * ; exists a ; exists x ; split ; apply clos_refl || auto.\n  destruct H as [ a' [ p' [ Hstep Htr ] ] ].\n  exists a' ; exists p' ; split ; auto.\n  apply clos_clos with u ; auto.\n  apply clos_trans with x a ; apply clos_refl || auto.\n  apply congr_pres_plus with p ; solve [ simpl in * ; tauto ] || auto.\n  apply clos_init_cases in Hclos ; destruct Hclos as [ H | H ].\n  rewrite <- H in * ; exists a ; exists y ; split ; apply clos_refl || auto.\n  destruct H as [ a' [ p' [ Hstep Htr ] ] ].\n  exists a' ; exists p' ; split ; auto.\n  apply clos_clos with t ; auto.\n  apply clos_trans with y a ; apply clos_refl || auto.\n  destruct H' as [ Hstep Heq ] ; rewrite Heq in *.\n  assert (congr p (p * q)) as Hcongr by ( simpl in * ; tauto ).\n  apply Hcongr in Hbisim'' ; contradiction || auto.\n  apply clos_init_cases in Hclos' ; destruct Hclos' as [ H | H ].\n  rewrite <- H in * ; exists a ; exists x ; split ; apply clos_refl || auto.\n  destruct H as [ a' [ p' [ Hstep' Htr ] ] ].\n  exists a' ; exists p' ; split ; auto.\n  apply clos_clos with u ; auto.\n  apply clos_trans with x a ; apply clos_refl || auto.\n  destruct H as [ Hstep Heq ] ; rewrite Heq in *.\n  apply step_mult_fmt in H' ; destruct H' as [ H' | H' ].\n  destruct H' as [ y [ Heq' Hstep' ] ] ; rewrite Heq' in *.\n  apply sum_step in Hstep' ; apply HM in Hstep'.\n  assert (congr p (p * q)) as Hcongr by ( simpl in * ; tauto ).\n  apply bisim_symm in Hbisim'' ; apply Hcongr in Hbisim'' ; contradiction || auto.\n  apply clos_init_cases in Hclos ; destruct Hclos as [ H | H ].\n  rewrite <- H in * ; exists a ; exists y ; split ; apply clos_refl || auto.\n  destruct H as [ a' [ p' [ Hstep'' Htr ] ] ].\n  exists a' ; exists p' ; split ; auto.\n  apply clos_clos with t ; auto.\n  apply clos_trans with y a ; apply clos_refl || auto.\n  destruct H' as [ Hstep' Heq' ] ; rewrite Heq' in *.\n  unfold teq ; apply refl.\n  apply sum_step in H' ; apply teq_symm ; apply IHN with a ;\n    apply bisim_symm || auto ; auto.\n  apply IHN' with a ; apply sum_step in H ; auto.\n\n  (* Application of theorem next using the previous assertion *)\n  apply next ; apply bisim_fwd in Hbisim'.\n  intros a x Hstep ; auto.\n  assert (emb (sum M' · p * q + sum N') -(a)-> x) as Hstep_x by auto.\n  apply Hbisim' in Hstep ; destruct Hstep as [ y [ Hstep_y Hbisim'' ] ].\n  exists y ; split ; auto.\n  apply Hnext with a ; auto.\n  intros a y Hstep ; auto.\n  assert (emb (sum M · p * q + sum N) -(a)-> y) as Hstep_y by auto.\n  apply Hbisim' in Hstep ; destruct Hstep as [ x [ Hstep_x Hbisim'' ] ].\n  exists x ; split ; auto.\n  apply Hnext with a ; auto.\n\n  (* Solve the r2 case *)\n  apply IHr2 with t ; auto.\n  intros u v a Hin Hbisim' ; apply IHN with a ; auto.\n  apply HeqlistN ; apply in_or_app ; auto.\n  intros a u Hin ; apply HM.\n  apply HeqlistM ; apply in_or_app ; auto.\nQed.\n\nLemma complete_split : forall (p q r s : T) (M N : list (A * V)),\n  emb (sum M · p * q + sum N) <=> emb r -> nf (p * q) ->\n  (forall (u v : V) (a : A), emb q -(a)-> u -> u <=> v -> teq u v) ->\n  (forall (x y : T), depth x < depth (p * q) -> emb x <=> emb y -> x == y) ->\n  (forall (t u : V) (a : A), In (a, t) N -> t <=> u -> teq t u) ->\n  p -->* s -> (forall (a : A) (u : V), In (a, u) M -> emb s -(a)-> u) ->\n  (sum M · p * q + sum N) == r.\nProof.\n  intros p q r ; revert p q ; induction r ;\n    intros p q s M N Hbisim Hnf Hleft_top IHprov IHN Hclos HM.\n \n  (* Case for 0 *)\n  apply next ; apply bisim_fwd in Hbisim.\n  intros a u Hstep ; apply Hbisim in Hstep.\n  destruct Hstep as [ v [ H _ ] ] ; inversion H.\n  intros a v H ; inversion H.\n\n  (* Case for a \\in A *)\n  apply next ; apply bisim_fwd in Hbisim.\n  intros a' u Hstep ; apply Hbisim in Hstep.\n  destruct Hstep as [ v [ Hstep Hbisim' ] ].\n  replace a' with a in * by ( inversion Hstep ; auto ).\n  replace v with term in * by ( inversion Hstep ; auto ).\n  exists term ; split ; auto.\n  destruct u as [ | t ] ; unfold teq ; auto.\n  destruct Hbisim' as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  intros a' v Hstep ; assert (emb (act a) -(a')-> v) as Hstep_act by auto.\n  apply Hbisim in Hstep ; destruct Hstep as [ u [ Hstep Hbisim' ] ].\n  replace a' with a in * by ( inversion Hstep_act ; auto ).\n  replace v with term in * by ( inversion Hstep_act ; auto ).\n  exists u ; split ; auto.\n  destruct u as [ | t ] ; unfold teq ; auto.\n  destruct Hbisim' as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n\n  (* Case for r1 + r2 *)\n  destruct (double_split (p * q) r1 r2 M N) as \n    [ Mr1 [ Mr2 [ Nr1 [ Nr2 H ] ] ] ] ; auto.\n  destruct H as [ HeqM [ HeqN [ Hbisim_r1 Hbisim_r2 ] ] ].\n  apply trans with (sum Mr1 · p * q + sum Nr1 + (sum Mr2 · p * q + sum Nr2)).\n  apply trans with (sum Mr1 · p * q + sum Nr1 + sum Mr2 · p * q + sum Nr2) ;\n    apply B2 || auto.\n  apply trans with (sum Mr1 · p * q + sum Mr2 · p * q + sum Nr1 + sum Nr2).\n  apply trans with (sum Mr1 · p * q + sum Mr2 · p * q + (sum Nr1 + sum Nr2)) ;\n    [ apply comp_plus | apply symm ; apply B2 ].\n  apply trans with ((sum Mr1 + sum Mr2) · p * q) ; apply B4 || auto.\n  apply comp_mult ; apply refl || auto.\n  apply trans with (sum (Mr1 ++ Mr2)) ; apply sum_app || auto.\n  apply eq_list_eq_sum ; auto.\n  apply trans with (sum (Nr1 ++ Nr2)) ; apply sum_app || auto.\n  apply eq_list_eq_sum ; auto.\n  apply comp_plus ; apply refl || auto.\n  apply trans with (sum Mr1 · p * q + (sum Mr2 · p * q + sum Nr1)) ;\n    [ apply B2 | ].\n  apply trans with (sum Mr1 · p * q + (sum Nr1 + sum Mr2 · p * q)) ;\n    [ | apply symm ; apply B2 ].\n  apply comp_plus ; apply refl || apply B1.\n  apply comp_plus ; [ apply IHr1 with s | apply IHr2 with s ] ; auto.\n  intros t u a Hin Hbisim' ; apply IHN with a ; auto.\n  apply HeqN ; apply in_or_app ; auto.\n  intros a u Hin ; apply HM ; apply HeqM ; apply in_or_app ; auto.\n  intros t u a Hin Hbisim' ; apply IHN with a ; auto.\n  apply HeqN ; apply in_or_app ; auto.\n  intros a u Hin ; apply HM ; apply HeqM ; apply in_or_app ; auto.\n\n  (* Case for r1 · r2 *)\n  apply complete_split_mult with s ; auto.\n  intros M' N' u Hbisim' Hclos' HM' IHN'.\n  apply IHr2 with u ; auto.\n\n  (* Case for r1 * r2 *)\n  apply RSP.\n  destruct (double_split (p * q) (r1 · (sum M · p * q + sum N)) r2 M N) as\n    [ M1 [ M2 [ N1 [ N2 H ] ] ] ].\n  apply RSP_inv_sound in Hbisim ; auto.\n  destruct H as [ HMeqlist [ HNeqlist [ Hbisim_left Hbisim_right ] ] ].\n  apply trans with (sum M1 · p * q + sum N1 + (sum M2 · p * q + sum N2)).\n  apply trans with (sum M1 · p * q + sum N1 + sum M2 · p * q + sum N2) ;\n    apply B2 || auto.\n  apply trans with (sum M1 · p * q + sum M2 · p * q + sum N1 + sum N2).\n  apply trans with (sum M1 · p * q + sum M2 · p * q + (sum N1 + sum N2)) ;\n    [ | apply symm ; apply B2 ].\n  apply comp_plus.\n  apply trans with ((sum M1 + sum M2) · p * q) ; apply B4 || auto.\n  apply comp_mult ; apply refl || auto.\n  apply trans with (sum (M1 ++ M2)) ; apply sum_app || auto.\n  apply eq_list_eq_sum ; auto.\n  apply trans with (sum (N1 ++ N2)) ; apply sum_app || auto.\n  apply eq_list_eq_sum ; auto.\n  apply comp_plus ; apply refl || auto.\n  apply trans with (sum M1 · p * q + (sum M2 · p * q + sum N1)) ;\n    apply B2 || auto.\n  apply trans with (sum M1 · p * q + (sum N1 + sum M2 · p * q)) ;\n    [ | apply symm ; apply B2 ].\n  apply comp_plus ; apply refl || apply B1.\n  apply comp_plus.\n  apply complete_split_mult with s ; auto.\n  intros t u a Hin Hbisim' ; apply IHN with a ; auto.\n  apply HNeqlist ; apply in_or_app ; auto.\n  intros a u Hin ; apply HM ; apply HMeqlist ; apply in_or_app ; auto.\n  \n  (* Congruence application *)\n  intros M' N' u Hbisim' Hclos' IHM' IHN'.\n  assert (forall (a : A) (u v : V), emb (sum M' · p * q + sum N') -(a)-> u ->\n    emb (sum M · p * q + sum N) -(a)-> v -> u <=> v -> teq u v) as Hnext.\n  intros a w v H H' Hbisim''.\n  apply step_plus_fmt in H ; destruct H as [ H | H ].\n  apply step_plus_fmt in H' ; destruct H' as [ H' | H' ].\n  apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ x [ Heq_x Hstep_x ] ] ; rewrite Heq_x in *.\n  apply sum_step in Hstep_x ; apply IHM' in Hstep_x.\n  apply step_mult_fmt in H' ; destruct H' as [ H' | H' ].\n  destruct H' as [ y [ Heq_y Hstep_y ] ] ; rewrite Heq_y in *.\n  apply sum_step in Hstep_y ; apply HM in Hstep_y.\n  unfold teq ; apply comp_mult ; apply refl || auto.\n  apply IHprov ; auto.\n  assert (depth x <= depth p) as Hpx.\n  apply depth_pres_plus.\n  apply clos_init_cases in Hclos' ; destruct Hclos' as [ H | H ].\n  rewrite <- H in * ; exists a ; exists x ; split ; apply clos_refl || auto.\n  destruct H as [ a' [ p' [ Hstep Htr ] ] ].\n  exists a' ; exists p' ; split ; auto.\n  apply clos_clos with u ; auto.\n  apply clos_trans with x a ; apply clos_refl || auto.\n  assert (depth p < depth (p * q)) ; omega || auto.\n  simpl ; destruct (depth q) ; auto.\n  rewrite succ_max_distr.\n  assert (S (depth p) <= max (S (depth p)) (S n)) ; omega || apply le_max_l.\n  apply congruence with (p * q) ; auto.\n  apply comp_plus_left.\n  apply congr_pres_plus with p ; solve [ simpl in * ; tauto ] || auto.\n  apply clos_init_cases in Hclos' ; destruct Hclos' as [ H | H ].\n  rewrite <- H in * ; exists a ; exists x ; split ; apply clos_refl || auto.\n  destruct H as [ a' [ p' [ Hstep Htr ] ] ].\n  exists a' ; exists p' ; split ; auto.\n  apply clos_clos with u ; auto.\n  apply clos_trans with x a ; apply clos_refl || auto.\n  apply congr_pres_plus with p ; solve [ simpl in * ; tauto ] || auto.\n  apply clos_init_cases in Hclos ; destruct Hclos as [ H | H ].\n  rewrite <- H in * ; exists a ; exists y ; split ; apply clos_refl || auto.\n  destruct H as [ a' [ p' [ Hstep Htr ] ] ].\n  exists a' ; exists p' ; split ; auto.\n  apply clos_clos with s ; auto.\n  apply clos_trans with y a ; apply clos_refl || auto.\n  destruct H' as [ Hstep Heq ] ; rewrite Heq in *.\n  assert (congr p (p * q)) as Hcongr by ( simpl in * ; tauto ).\n  apply Hcongr in Hbisim'' ; contradiction || auto.\n  apply clos_init_cases in Hclos' ; destruct Hclos' as [ H | H ].\n  rewrite <- H in * ; exists a ; exists x ; split ; apply clos_refl || auto.\n  destruct H as [ a' [ p' [ Hstep' Htr ] ] ].\n  exists a' ; exists p' ; split ; auto.\n  apply clos_clos with u ; auto.\n  apply clos_trans with x a ; apply clos_refl || auto.\n  destruct H as [ Hstep Heq ] ; rewrite Heq in *.\n  apply step_mult_fmt in H' ; destruct H' as [ H' | H' ].\n  destruct H' as [ y [ Heq' Hstep' ] ] ; rewrite Heq' in *.\n  apply sum_step in Hstep' ; apply HM in Hstep'.\n  assert (congr p (p * q)) as Hcongr by ( simpl in * ; tauto ).\n  apply bisim_symm in Hbisim'' ; apply Hcongr in Hbisim'' ; contradiction || auto.\n  apply clos_init_cases in Hclos ; destruct Hclos as [ H | H ].\n  rewrite <- H in * ; exists a ; exists y ; split ; apply clos_refl || auto.\n  destruct H as [ a' [ p' [ Hstep'' Htr ] ] ].\n  exists a' ; exists p' ; split ; auto.\n  apply clos_clos with s ; auto.\n  apply clos_trans with y a ; apply clos_refl || auto.\n  destruct H' as [ Hstep' Heq' ] ; rewrite Heq' in *.\n  unfold teq ; apply refl.\n  apply sum_step in H' ; apply teq_symm ; apply IHN with a ;\n    apply bisim_symm || auto ; auto.\n  apply IHN' with a ; apply sum_step in H ; auto.\n\n  (* Application of theorem next using the previous assertion *)\n  apply next ; apply bisim_fwd in Hbisim'.\n  intros a x Hstep ; auto.\n  assert (emb (sum M' · p * q + sum N') -(a)-> x) as Hstep_x by auto.\n  apply Hbisim' in Hstep ; destruct Hstep as [ y [ Hstep_y Hbisim'' ] ].\n  exists y ; split ; auto.\n  apply Hnext with a ; auto.\n  intros a y Hstep ; auto.\n  assert (emb (sum M · p * q + sum N) -(a)-> y) as Hstep_y by auto.\n  apply Hbisim' in Hstep ; destruct Hstep as [ x [ Hstep_x Hbisim'' ] ].\n  exists x ; split ; auto.\n  apply Hnext with a ; auto.\n\n  (* Solve the r2-equality *)\n  apply IHr2 with s ; auto.\n  intros t u a Hin Hbisim'.\n  apply IHN with a ; auto.\n  apply HNeqlist ; apply in_or_app ; auto.\n  intros a u Hin ; apply HM.\n  apply HMeqlist ; apply in_or_app ; auto.\nQed.\n\nLemma complete_star_step_nf : forall (q r s : T) (a : A) (w : V),\n  emb (mult' w (q * r)) <=> emb s -> nf (q * r) -> emb q -(a)-> w ->\n  (forall (x y : T), depth x < depth (q * r) -> emb x <=> emb y -> x == y) -> \n  (forall (u v : V) (a : A), emb r -(a)-> u -> u <=> v -> teq u v) ->\n  (mult' w (q * r)) == s.\nProof.\n  intros q r s a w Hbisim Hnf Hstep IHprov Htop ; destruct w as [ | t ] ; simpl.\n  apply trans with (q · q * r + r) ; [ apply symm ; apply BKS1 | ].\n  destruct (summation r) as [ N [ Hiff_N Heq_N ] ].\n  apply trans with (q · q * r + sum N).\n  apply comp_plus ; apply refl || apply symm ; auto.\n  destruct (summation q) as [ M [ Hiff_M Heq_M ] ].\n  apply trans with (sum M · q * r + sum N).\n  apply comp_plus ; apply refl || auto.\n  apply comp_mult ; apply refl || apply symm ; auto.\n  apply complete_split with q ; apply clos_refl || tauto || auto.\n  simpl in Hbisim ; apply bisim_trans with (emb (sum M · q * r + r)).\n  apply bisim_comp_plus ; apply bisim_refl || apply soundness ; auto.\n  apply bisim_trans with (emb (q · q * r + r)).\n  apply bisim_comp_plus ; apply bisim_refl || auto.\n  apply bisim_comp_mult ; apply bisim_refl || apply soundness ; auto.\n  apply bisim_trans with (emb (q * r)) ; apply BKS1_sound || auto.\n  intros t u a' Hin Hbisim' ; apply Htop with a' ; auto.\n  apply Hiff_N ; auto.\n  intros a' u Hin ; apply Hiff_M ; auto.\n  destruct (summation t) as [ M [ Hiff_M Heq_M ] ].\n  apply trans with (sum M · q * r).\n  apply comp_mult ; apply refl || apply symm ; auto.\n  apply trans with (sum M · q * r + sum nil) ; [ apply symm ; apply B6 | ].\n  apply complete_split with t ; auto.\n  simpl ; apply bisim_trans with (emb (sum M · q * r)) ; apply B6_sound || auto.\n  simpl in Hbisim ; apply bisim_trans with (emb (t · q * r)) ; auto.\n  apply bisim_comp_mult ; apply bisim_refl || apply soundness ; auto.\n  intros v u a' Hin ; simpl in Hin ; contradiction.\n  apply clos_trans with t a ; apply clos_refl || auto.\n  intros a' u Hin ; apply Hiff_M ; auto.\nQed.\n\nLemma complete_mult_nf : forall (p q r : T), \n  emb (p · r) <=> emb q -> nf (p · r) ->\n  (forall (x y : T), depth x < depth (p · r) -> emb x <=> emb y -> x == y) -> \n  (forall (u v : V) (a : A), emb r -(a)-> u -> u <=> v -> teq u v) ->\n  (p · r) == q.\nProof.\n  intros p q r Hbisim Hnf IHprov Htop.\n  assert (forall (u v : V) (a : A),\n    emb p -(a)-> u -> emb (mult' u r) <=> v -> teq (emb (mult' u r)) v) as Hnext.\n  clear Hbisim ; revert Hnf IHprov Htop ; revert r ; clear q.\n  induction p ; intros r Hnf IHprov Htop u v a' Hstep_p Hbisim ;\n    solve [ inversion Hstep_p ] || auto.\n\n  (* Case for a \\in A *)\n  replace u with term in * by ( inversion Hstep_p ; auto ) ; simpl.\n  destruct v as [ | q ].\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  unfold teq ; apply next.\n  intros a'' w Hstep_r ; assert (emb r -(a'')-> w) as Hstep by auto.\n  simpl in Hbisim ; apply bisim_fwd in Hbisim ; apply Hbisim in Hstep.\n  destruct Hstep as [ v [ Hstep_q Hbisim' ] ] ; exists v ; split ; auto.\n  apply Htop with a'' ; auto.\n  intros a'' v Hstep_q ; assert (emb q -(a'')-> v) as Hstep by auto.\n  simpl in Hbisim ; apply bisim_fwd in Hbisim ; apply Hbisim in Hstep.\n  destruct Hstep as [ w [ Hstep_r Hbisim' ] ] ; exists w ; split ; auto.\n  apply Htop with a'' ; auto.\n\n  (* Case for p1 + p2 *)\n  apply step_plus_fmt in Hstep_p ; destruct Hstep_p as [ Hstep_p | Hstep_p ].\n  destruct v as [ | q ].\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  apply IHp1 with a' ; solve [ simpl in * ; tauto ] || auto.\n  intros x y Hless Hbisim' ; apply IHprov ; auto.\n  assert (depth (p1 · r) <= depth ((p1 + p2) · r)) ; omega || auto.\n  simpl ; apply max_lub ; apply le_max_r || \n    rewrite <- max_assoc ; apply le_max_l.\n  apply IHp2 with a' ; solve [ simpl in * ; tauto ] || auto.\n  intros x y Hless Hbisim' ; apply IHprov ; auto.\n  assert (depth (p2 · r) <= depth ((p1 + p2) · r)) ; omega || auto.\n  simpl ; apply max_lub ; apply le_max_r || auto.\n  rewrite (max_comm (depth p1)) ; rewrite <- max_assoc ; apply le_max_l.\n\n  (* Case for p1 · p2 *)\n  apply step_mult_fmt in Hstep_p ; destruct Hstep_p as [ H | H ].\n  destruct H as [ p' [ Heq Hstep_p1 ] ] ; rewrite Heq in *.\n  destruct v as [ | q ].\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  simpl ; unfold teq.\n  apply trans with (p' · p2 · r) ; apply B5 || auto.\n  assert (teq (emb (mult' (emb p') (p2 · r))) (emb q)) as Hcond.\n  apply IHp1 with a' ; solve [ simpl in * ; tauto ] || auto.\n  intros x y Hless Hbisim' ; apply IHprov ; auto.\n  assert (depth (p1 · p2 · r) <= depth ((p1 · p2) · r)) ; omega || auto.\n  simpl ; rewrite <- max_assoc ; auto.\n  intros w v a Hstep Hbisim'.\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ p'' [ Heq' Hstep_p2 ] ] ; rewrite Heq' in *.\n  destruct v as [ | q' ].\n  destruct Hbisim' as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  assert (teq (emb (mult' (emb p'') r)) (emb q')) as Hcond.\n  apply IHp2 with a ; solve [ simpl in * ; tauto ] || auto.\n  intros x y Hless Hbisim'' ; apply IHprov ; auto.\n  assert (depth (p2 · r) <= depth ((p1 · p2) · r)) ; omega || auto.\n  simpl ; apply max_lub ; apply le_max_r || auto.\n  rewrite (max_comm (depth p1)) ; rewrite <- max_assoc ; apply le_max_l.\n  simpl in Hcond ; auto.\n  destruct H as [ Hstep_p2 Heq' ] ; rewrite Heq' in *.\n  destruct v as [ | q' ].\n  destruct Hbisim' as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  apply next ; apply bisim_fwd in Hbisim'.\n  intros a'' u' Hstep_r ; assert (emb r -(a'')-> u') as Hstep by auto.\n  apply Hbisim' in Hstep ; destruct Hstep as [ v' [ Hstep_q Hbisim'' ] ].\n  exists v' ; split ; auto.\n  apply Htop with a'' ; auto.\n  intros a'' v' Hstep_q ; assert (emb q' -(a'')-> v') as Hstep by auto.\n  apply Hbisim' in Hstep ; destruct Hstep as [ u' [ Hstep_r Hbisim'' ] ].\n  exists u' ; split ; auto.\n  apply Htop with a'' ; auto.\n  simpl in Hbisim ; simpl.\n  apply bisim_trans with (emb ((p' · p2) · r)) ; auto.\n  apply bisim_symm ; apply B5_sound.\n  simpl in Hcond ; unfold teq in Hcond ; auto.\n  destruct H as [ Hstep_p1 Heq ] ; rewrite Heq in *.\n  destruct v as [ | q ].\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  simpl in Hbisim ; unfold teq ; simpl.\n  apply next ; apply bisim_fwd in Hbisim.\n  intros a w H ; apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ p' [ Heq' Hstep_p2 ] ] ; rewrite Heq' in *.\n  assert (emb p2 -(a)-> emb p') as Hstep by auto.\n  assert (emb (p2 · r) -(a)-> emb (p' · r)) as Hstep' by\n    ( apply step_mult_left ; auto ).\n  apply Hbisim in Hstep' ; destruct Hstep' as [ v [ Hstep_q Hbisim' ] ].\n  exists v ; split ; auto.\n  destruct v as [ | q' ].\n  destruct Hbisim' as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  assert (teq (emb (mult' (emb p') r)) (emb q')) as Hcond.\n  apply IHp2 with a ; solve [ simpl in * ; tauto ] || auto.\n  intros x y Hless Hbisim'' ; apply IHprov ; auto.\n  assert (depth (p2 · r) <= depth ((p1 · p2) · r)) ; omega || auto.\n  simpl ; apply max_lub ; apply le_max_r || auto.\n  rewrite (max_comm (depth p1)) ; rewrite <- max_assoc ; apply le_max_l.\n  simpl in Hcond ; auto.\n  destruct H as [ Hstep_p2 Heq' ] ; rewrite Heq' in *.\n  assert (emb (p2 · r) -(a)-> emb r) as Hstep by ( apply step_mult_right ; auto ).\n  apply Hbisim in Hstep ; destruct Hstep as [ v [ Hstep_q Hbisim' ] ].\n  destruct v as [ | q' ].\n  destruct Hbisim' as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  exists (emb q') ; split ; auto.\n  unfold teq ; apply next ; apply bisim_fwd in Hbisim'.\n  intros a'' x Hstep_r ; assert (emb r -(a'')-> x) as Hstep by auto.\n  apply Hbisim' in Hstep ; destruct Hstep as [ y [ Hstep_q' Hbisim'' ] ].\n  exists y ; split ; auto.\n  apply Htop with a'' ; auto.\n  intros a'' y Hstep_q' ; assert (emb q' -(a'')-> y) as Hstep by auto.\n  apply Hbisim' in Hstep ; destruct Hstep as [ x [ Hstep_r Hbisim'' ] ].\n  exists x ; split ; auto.\n  apply Htop with a'' ; auto.\n  intros a v Hstep_q ; assert (emb q -(a)-> v) as Hstep by auto.\n  apply Hbisim in Hstep ; destruct Hstep as [ w [ Hstep Hbisim' ] ] ;\n    exists w ; split ; auto.\n  apply step_mult_fmt in Hstep ; destruct Hstep as [ H | H ].\n  destruct H as [ p' [ Heq' Hstep_p2 ] ] ; rewrite Heq' in *.\n  assert (teq (emb (mult' (emb p') r)) v) as Hcond.\n  destruct v as [ | q' ].\n  destruct Hbisim' as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  apply IHp2 with a ; solve [ simpl in * ; tauto ] || auto.\n  intros x y Hless Hbisim'' ; apply IHprov ; auto.\n  assert (depth (p2 · r) <= depth ((p1 · p2) · r)) ; omega || auto.\n  simpl ; apply max_lub ; apply le_max_r || auto.\n  rewrite (max_comm (depth p1)) ; rewrite <- max_assoc ; apply le_max_l.\n  simpl in Hcond ; auto.\n  destruct H as [ Hstep_p2 Heq' ] ; rewrite Heq' in *.\n  destruct v as [ | q' ].\n  destruct Hbisim' as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  unfold teq ; apply next ; apply bisim_fwd in Hbisim'.\n  intros a'' x Hstep_r ; assert (emb r -(a'')-> x) as Hstep by auto.\n  apply Hbisim' in Hstep ; destruct Hstep as [ y [ Hstep_q' Hbisim'' ] ].\n  exists y ; split ; auto.\n  apply Htop with a'' ; auto.\n  intros a'' y Hstep_q' ; assert (emb q' -(a'')-> y) as Hstep by auto.\n  apply Hbisim' in Hstep ; destruct Hstep as [ x [ Hstep_r Hbisim'' ] ].\n  exists x ; split ; auto.\n  apply Htop with a'' ; auto.\n\n  (* Case for p1 * p2 *)\n  apply step_star_fmt in Hstep_p ; destruct Hstep_p as [ H | [ H | H ] ].\n  destruct H as [ p' [ Heq Hstep_p1 ] ] ; rewrite Heq in *.\n  destruct v as [ | q ].\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  assert ((mult' (emb p') (p1 * (p2 · r))) == q) as Hcond.\n  apply complete_star_step_nf with a' ; solve [ simpl in * ; tauto ] || auto.\n  simpl in Hbisim ; simpl.\n  apply bisim_trans with (emb ((p' · p1 * p2) · r)) ; auto.\n  apply bisim_trans with (emb (p' · p1 * p2 · r)) ;\n    [ | apply bisim_symm ; apply B5_sound ].\n  apply bisim_comp_mult ; apply bisim_refl || \n    apply bisim_symm ; apply BKS2_sound.\n  simpl ; repeat split ; solve [ simpl in * ; tauto ] || auto.\n  apply nf_mult_right_compat with (p1 * p2 · r) ;\n    solve [ simpl in * ; tauto ] || apply BKS2_sound.\n  apply congr_right_compat with (p1 * p2 · r) ;\n    solve [ simpl in * ; tauto ] || apply BKS2_sound.\n  intros x y Hless Hbisim' ; apply IHprov ; auto.\n  assert (depth (p1 * (p2 · r)) <= depth (p1 * p2 · r)) ; omega || auto.\n  simpl ; destruct (depth p2) as [ | m ].\n  rewrite max_0_l ; destruct (depth r) as [ | n ] ; apply le_max_l || auto.\n  destruct (depth r) as [ | n ] ; simpl ; auto.\n  rewrite succ_max_distr ; rewrite succ_max_distr ; apply max_lub.\n  rewrite succ_max_distr.\n  transitivity (S (max (depth p1) m)) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; apply le_max_l.\n  rewrite succ_max_distr ; apply max_lub ; apply le_max_r || auto.\n  transitivity (S (max (depth p1) m)) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; apply le_max_r.\n  intros w v a Hstep Hbisim' ; apply step_mult_fmt in Hstep.\n  destruct Hstep as [ [ p'' [ Heq' Hstep_p2 ] ] | H ] ; [ rewrite Heq' in * | ].\n  assert (teq (emb (mult' (emb p'') r)) v) as Hcond.\n  apply IHp2 with a ; solve [ simpl in * ; tauto ] || auto.\n  intros x y Hless Hbisim'' ; apply IHprov ; auto.\n  assert (depth (p2 · r) <= depth (p1 * p2 · r)) ; omega || auto.\n  simpl ; destruct (depth p2) as [ | m ].\n  rewrite max_0_l ; apply le_max_r.\n  apply max_lub ; apply le_max_r || auto.\n  transitivity (S (max (depth p1) m)) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; apply le_max_r.\n  simpl in Hcond ; auto.\n  destruct H as [ Hstep_p2 Heq' ] ; rewrite Heq' in *.\n  destruct v as [ | q' ].\n  destruct Hbisim' as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  apply next ; apply bisim_fwd in Hbisim'.\n  intros a'' x Hstep_r ; assert (emb r -(a'')-> x) as Hstep by auto.\n  apply Hbisim' in Hstep ; destruct Hstep as [ y [ Hstep_q' Hbisim'' ] ].\n  exists y ; split ; auto.\n  apply Htop with a'' ; auto.\n  intros a'' y Hstep_q' ; assert (emb q' -(a'')-> y) as Hstep by auto.\n  apply Hbisim' in Hstep ; destruct Hstep as [ x [ Hstep_r Hbisim'' ] ].\n  exists x ; split ; auto.\n  apply Htop with a'' ; auto.\n  simpl ; simpl in Hcond ; unfold teq.\n  apply trans with (p' · p1 * (p2 · r)) ; auto.\n  apply trans with (p' · p1 * p2 · r) ; apply B5 || auto.\n  apply comp_mult ; apply refl || apply BKS2.\n  destruct H as [ Heq Hstep_p1 ] ; rewrite Heq in *.\n  destruct v as [ | q ].\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  assert ((mult' term (p1 * (p2 · r))) == q) as Hcond.\n  apply complete_star_step_nf with a' ; auto.\n  simpl ; simpl in Hbisim.\n  apply bisim_trans with (emb (p1 * p2 · r)) ; auto.\n  apply bisim_symm ; apply BKS2_sound.\n  simpl ; repeat split ; solve [ simpl in * ; tauto ] || auto.\n  apply nf_mult_right_compat with (p1 * p2 · r) ;\n    solve [ simpl in * ; tauto ] || apply BKS2_sound.\n  apply congr_right_compat with (p1 * p2 · r) ;\n    solve [ simpl in * ; tauto ] || apply BKS2_sound.\n  intros x y Hless Hbisim' ; apply IHprov ; auto.\n  assert (depth (p1 * (p2 · r)) <= depth (p1 * p2 · r)) ; omega || auto.\n  simpl ; destruct (depth p2) as [ | m ].\n  rewrite max_0_l ; destruct (depth r) as [ | n ] ; apply le_max_l || auto.\n  destruct (depth r) as [ | n ] ; simpl ; auto.\n  rewrite succ_max_distr ; apply max_lub ; rewrite succ_max_distr.\n  transitivity (S (max (depth p1) m)) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; apply le_max_l.\n  rewrite succ_max_distr ; apply max_lub ; apply le_max_r || auto.\n  transitivity (S (max (depth p1) m)) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; apply le_max_r.\n  intros w v a H Hbisim' ; apply step_mult_fmt in H ; destruct H as [ H | H ].\n  destruct H as [ p' [ Heq' Hstep_p2 ] ] ; rewrite Heq' in *.\n  assert (teq (emb (mult' (emb p') r)) v) as Hcond.\n  apply IHp2 with a ; solve [ simpl in * ; tauto ] || auto.\n  intros x y Hless Hbisim'' ; apply IHprov ; auto.\n  assert (depth (p2 · r) <= depth (p1 * p2 · r)) ; omega || auto.\n  simpl ; destruct (depth p2) as [ | m ].\n  rewrite max_0_l ; apply le_max_r.\n  apply max_lub ; apply le_max_r || auto.\n  transitivity (S (max (depth p1) m)) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; apply le_max_r.\n  simpl in Hcond ; auto.\n  destruct H as [ Hstep_p2 Heq' ] ; rewrite Heq' in *.\n  destruct v as [ | q' ].\n  destruct Hbisim' as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  unfold teq ; apply next ; apply bisim_fwd in Hbisim'.\n  intros a'' x Hstep_r ; assert (emb r -(a'')-> x) as Hstep by auto.\n  apply Hbisim' in Hstep ; destruct Hstep as [ y [ Hstep_q' Hbisim'' ] ].\n  exists y ; split ; auto.\n  apply Htop with a'' ; auto.\n  intros a'' y Hstep_q' ; assert (emb q' -(a'')-> y) as Hstep by auto.\n  apply Hbisim' in Hstep ; destruct Hstep as [ x [ Hstep_r Hbisim'' ] ].\n  exists x ; split ; auto.\n  apply Htop with a'' ; auto.\n  unfold teq ; simpl in * ; apply trans with (p1 * (p2 · r)) ; apply BKS2 || auto.\n  apply IHp2 with a' ; solve [ simpl in * ; tauto ] || auto.\n  intros x y Hless Hbisim' ; apply IHprov ; auto.\n  assert (depth (p2 · r) <= depth (p1 * p2 · r)) ; omega || auto.\n  simpl ; destruct (depth p2) as [ | m ].\n  rewrite max_0_l ; apply le_max_r.\n  apply max_lub ; apply le_max_r || auto.\n  transitivity (S (max (depth p1) m)) ; apply le_max_l || auto.\n  rewrite succ_max_distr ; apply le_max_r.\n\n  (* Use assertion and Lemma next to prove this lemma *)\n  assert (forall (a : A) (u v : V), emb (p · r) -(a)-> u ->\n    emb q -(a)-> v -> u <=> v -> teq u v) as Happl.\n  intros a u v H Hstep_q Hbisim' ; apply step_mult_fmt in H ;  \n    destruct H as [ H | H ].\n  destruct H as [ p' [ Heq Hstep_p ] ] ; rewrite Heq in *.\n  destruct v as [ | q' ].\n  destruct Hbisim' as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  assert (teq (emb (mult' (emb p') r)) (emb q')) as Hcond.\n  apply Hnext with a ; auto.\n  simpl in Hcond ; auto.\n  destruct H as [ Hstep_p Heq ] ; rewrite Heq in *.\n  destruct v as [ | q' ].\n  destruct Hbisim' as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  apply next ; apply bisim_fwd in Hbisim'.\n  intros a' x Hstep_r ; assert (emb r -(a')-> x) as H by auto.\n  apply Hbisim' in H ; destruct H as [ y [ Hstep_q' Hbisim'' ] ].\n  exists y ; split ; auto.\n  apply Htop with a' ; auto.\n  intros a' y Hstep_q' ; assert (emb q' -(a')-> y) as H by auto.\n  apply Hbisim' in H ; destruct H as [ x [ Hstep_r Hbisim'' ] ].\n  exists x ; split ; auto.\n  apply Htop with a' ; auto.\n  apply next ; apply bisim_fwd in Hbisim.\n  intros a u Hstep_pr ; assert (emb (p · r) -(a)-> u) as H by auto.\n  apply Hbisim in H ; destruct H as [ v [ Hstep_q Hbisim' ] ].\n  exists v ; split ; auto.\n  apply Happl with a ; auto.\n  intros a v Hstep_q ; assert (emb q -(a)-> v) as H by auto.\n  apply Hbisim in H ; destruct H as [ u [ Hstep_pr Hbisim' ] ].\n  exists u ; split ; auto.\n  apply Happl with a ; auto.\nQed.\n\nLemma complete_nf : forall (p q : T), emb p <=> emb q -> nf p ->\n  (forall (r s : T), depth r < depth p -> emb r <=> emb s -> r == s) -> p == q.\nProof.\n  intros p q Hbisim Hnf IHprov.\n  assert (forall (u v : V) (a : A), \n    emb p -(a)-> u -> u <=> v -> teq u v) as Hnext.\n  clear Hbisim ; revert Hnf IHprov ; clear q.\n  induction p ; intros Hnf IHprov u v a' Hstep_p Hbisim ;\n    solve [ inversion Hstep_p ] || auto.\n  replace u with term in * by ( inversion Hstep_p ; auto ).\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; rewrite H ; auto.\n\n  (* Case for p1 + p2 in asertion *)\n  apply step_plus_fmt in Hstep_p ; destruct Hstep_p as [ Hstep_p | Hstep_p ].\n  apply IHp1 with a' ; solve [ simpl in * ; tauto ] || auto.\n  intros r s Hless Hbisim' ; apply IHprov ; auto.\n  assert (depth p1 <= depth (p1 + p2)) by ( simpl ; apply le_max_l ) ; omega.\n  apply IHp2 with a' ; solve [ simpl in * ; tauto ] || auto.\n  intros r s Hless Hbisim' ; apply IHprov ; auto.\n  assert (depth p2 <= depth (p1 + p2)) by ( simpl ; apply le_max_r ) ; omega.\n\n  (* Case for p1 · p2 in assertion *)\n  apply step_mult_fmt in Hstep_p ; destruct Hstep_p as [ H | H ].\n  destruct H as [ p' [ Heq Hstep_p1 ] ] ; rewrite Heq in *.\n  destruct v as [ | q ].\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  unfold teq ; apply complete_mult_nf ; auto.\n  simpl ; split ; solve [ simpl in * ; tauto ] || auto.\n  apply nf_mult_pres_step with p1 a' ; solve [ simpl in * ; tauto ] || auto.\n  intros x y Hless Hbisim' ; apply IHprov ; auto.\n  assert (depth (p' · p2) <= depth (p1 · p2)) ; omega || auto.\n  simpl ; apply max_lub ; apply le_max_r || auto.\n  transitivity (depth p1) ; apply le_max_l || \n    apply depth_pres_step with a' ; auto.\n  intros w v a Hstep Hbisim' ; apply IHp2 with a ;\n    solve [ simpl in * ; tauto ] || auto.\n  intros r s Hless Hbisim'' ; apply IHprov ; auto.\n  assert (depth p2 <= depth (p1 · p2)) ; omega || simpl ; apply le_max_r.\n  destruct H as [ Hstep_p1 Heq ] ; rewrite Heq in *.\n  destruct v as [ | q ].\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  apply next ; apply bisim_fwd in Hbisim.\n  intros a w Hstep ; assert (emb p2 -(a)-> w) as Hstep_p2 by auto.\n  apply Hbisim in Hstep ; destruct Hstep as [ v [ Hstep_q Hbisim' ] ].\n  exists v ; split ; auto.\n  apply IHp2 with a ; solve [ simpl in * ; tauto ] || auto.\n  intros r s Hless Hbisim'' ; apply IHprov ; auto.\n  assert (depth p2 <= depth (p1 · p2)) ; omega || simpl ; apply le_max_r.\n  intros a v Hstep_q ; assert (emb q -(a)-> v) as Hstep by auto.\n  apply Hbisim in Hstep ; destruct Hstep as [ w [ Hstep_p2 Hbisim' ] ].\n  exists w ; split ; auto.\n  apply IHp2 with a ; solve [ simpl in * ; tauto ] || auto.\n  intros r s Hless Hbisim'' ; apply IHprov ; auto.\n  assert (depth p2 <= depth (p1 · p2)) ; omega || simpl ; apply le_max_r.\n\n  (* Case for p1 * p2 in assertion *)\n  apply step_star_fmt in Hstep_p ; destruct Hstep_p as [ H | [ H | H ] ].\n  destruct H as [ p' [ Heq Hstep_p1 ] ] ; rewrite Heq in *.\n  destruct v as [ | q ].\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  unfold teq ; assert (emb (mult' (emb p') (p1 * p2)) <=> emb q) as H by\n    ( unfold mult' ; simpl ; auto ).\n  apply complete_star_step_nf with (a := a') in H ; auto.\n  intros w v a Hstep_p2 Hbisim' ; apply IHp2 with a ; \n    solve [ simpl in * ; tauto ] || auto.\n  intros r s Hless Hbisim'' ; apply IHprov ; auto.\n  assert (depth p2 <= depth (p1 * p2)) ; omega || auto. \n  simpl ; destruct (depth p2) as [ | m ] ; omega || auto.\n  rewrite succ_max_distr ; apply le_max_r.\n  destruct H as [ Heq Hstep_p1 ] ; rewrite Heq in *.\n  destruct v as [ | q ].\n  destruct Hbisim as [ R [ HinR HrelR ] ] ; apply HrelR in HinR.\n  assert (term = term) as H by auto ; apply HinR in H ; inversion H.\n  unfold teq ; assert (emb (mult' term (p1 * p2)) <=> emb q) as H by\n    ( unfold mult' ; simpl ; auto ).\n  apply complete_star_step_nf with (a := a') in H ; auto.\n  intros w v a Hstep_p2 Hbisim' ; apply IHp2 with a ; \n    solve [ simpl in * ; tauto ] || auto.\n  intros r s Hless Hbisim'' ; apply IHprov ; auto.\n  assert (depth p2 <= depth (p1 * p2)) ; omega || auto.\n  simpl ; destruct (depth p2) as [ | m ] ; omega || auto.\n  rewrite succ_max_distr ; apply le_max_r.\n  apply IHp2 with a' ; solve [ simpl in * ; tauto ] || auto.\n  intros r s Hless Hbisim' ; apply IHprov ; auto.\n  assert (depth p2 <= depth (p1 * p2)) ; omega || auto.\n  simpl ; destruct (depth p2) as [ | m ] ; omega || auto.\n  rewrite succ_max_distr ; apply le_max_r.\n\n  (* Use assertion and Lemma next to prove lemma *)\n  apply next ; apply bisim_fwd in Hbisim.\n  intros a u Hstep_p ; assert (emb p -(a)-> u) as Hstep by auto.\n  apply Hbisim in Hstep ; destruct Hstep as [ v [ Hstep_q Hbisim' ] ].\n  exists v ; split ; auto.\n  apply Hnext with a ; auto.\n  intros a v Hstep_q ; assert (emb q -(a)-> v) as Hstep by auto.\n  apply Hbisim in Hstep ; destruct Hstep as [ u [ Hstep_p Hbisim' ] ].\n  exists u ; split ; auto.\n  apply Hnext with a ; auto.\nQed.\n\nTheorem completeness : forall (p q : T), emb p <=> emb q -> p == q.\nProof.\n  intro p ; assert (exists (n : nat), n = depth p) as H by eauto.\n  destruct H as [ n Heq ] ; revert Heq ; revert p.\n  induction n using strong_ind ; intros p Heq q Hbisim.\n  destruct (normalization p) as [ r [ Hbisim' [ Hnf Hleq ] ] ].\n  apply trans with r ; [ apply symm | ] ; apply complete_nf ; auto.\n  apply bisim_symm ; auto.\n  intros t u Hleq' Hbisim'' ; apply H with (depth t) ; omega || auto.\n  apply bisim_trans with (emb p) ; [ apply bisim_symm | ] ; auto.\n  intros t u Hleq' Hbisim'' ; apply H with (depth t) ; omega || auto.\nQed.\n", "meta": {"author": "allanvanhulst", "repo": "mscs", "sha": "15f624ab0f4d721cd4c93aac68d550f84817deec", "save_path": "github-repos/coq/allanvanhulst-mscs", "path": "github-repos/coq/allanvanhulst-mscs/mscs-15f624ab0f4d721cd4c93aac68d550f84817deec/bin_kstar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6624203774985026}}
{"text": "(* Fermat の小定理 *)\n\n(* 2014_3_30 *)\n\n(* suahrahiromichi@gmail.com *)\n\n\nFrom mathcomp Require Import eqtype ssrnat fintype div bigop prime binomial.\n\nRequire Import ssreflect ssrfun ssrbool.\n\n\n\n\n(**\n\n 全体の証明は、\n\n http://ja.wikipedia.org/wiki/フェルマーの小定理\n\n 証明(1) に沿う、つもり。\n\n *)\n\n\n\n(* この補題は、Coqによる定理証明 2013 12, p.14 *)\n\n(* 乱数列の網羅性 著者：坂口和彦さん *)\n\nLemma expSS a p :\n\n  a.+1 ^ p.+1 =\n\n  (a ^ p.+1).+1 + \\sum_(1 <= k < p.+1 | 0 < k < p.+1) 'C(p.+1, k) * a ^ k.\n\nProof.\n\n  rewrite -add1n Pascal big_ord_recl big_ord_recr /= /bump /= !add1n\n\n                 bin0 binn subn0 subnn !mul1n exp1n add1n -addnS addnC.\n\n  rewrite -big_nat.\n\n  rewrite (big_addn 0 p.+1 1) subn1 /= big_mkord.\n\n  by congr (_ + _); apply eq_bigr => m _; rewrite exp1n add1n addn1 mul1n.\n\nQed.\n\n\n\n(* pが素数なら、二項定理を使って (m + 1) ^ p を展開したときの、\n\n  m^p + C + 1 の 「C」がpで割りきれることを証明する。 *)\n\nLemma bino_body__p m p :\n\n  prime p ->\n\n  (\\sum_(1 <= i < p | 0 < i < p) 'C(p, i) * m ^ i) %% p == 0.\n\nProof.\n\n  apply big_ind => //.\n\n    by rewrite mod0n.\n\n  move=> m1 m2 H1 H2 Hp.\n\n    by apply dvdn_add; [apply H1, Hp | apply H2, Hp].\n\n  move=> i H0 Hp.\n\n    by apply dvdn_mulr, prime_dvd_bin. \n\nQed.\n\n\n\nLemma mod_m_1p__mp_1 m p :\n\n  prime p.+1 -> m.+1 ^ p.+1 = (m ^ p.+1).+1 %[mod p.+1].\n\nProof.\n\n  move=> Hp.\n\n  apply/eqP.\n\n  rewrite expSS addSn (eqn_modDl 1)\n\n  -{2}(addn0 (m ^ p.+1)) (eqn_modDl (m ^ p.+1)).\n\n  apply/eqP.\n\n  have H := (bino_body__p m p.+1 Hp).\n\n  move/eqP in H.\n\n  by rewrite mod0n.\n\nQed.\n\n\n\nLemma mod_1n a b p : a = b %[mod p] -> a.+1 = b.+1 %[mod p].\n\nProof.\n\n  move=> /eqP H.                            (* move/eqP => H *)\n\n  apply/eqP.\n\n  by rewrite -(addn1 a) -(addn1 b) (eqn_modDr 1 a b p).\n\nQed.\n\n\n\nTheorem Fermat a p:\n\n  prime p.+1 -> a ^ p.+1 = a %[mod p.+1].\n\nProof.\n\n  move=> Hp.\n\n  elim: a => [|a].\n\n  (* a = 0 *)\n\n  by rewrite exp0n.\n\n  elim: a => [|a] H0.\n\n  (* a = 1 *)\n\n  by rewrite exp1n.\n\n  move=> H1 {H0} {H1}.\n\n  elim: a => [|a].\n\n  (* a = 2 *)\n\n  rewrite (mod_m_1p__mp_1 1 p); last done.  (* last は prime p *)\n\n    by rewrite exp1n.\n\n  (* a = k + 1 *)\n\n  move=> H2.\n\n  rewrite (mod_m_1p__mp_1 a.+2); last done. (* last は prime p *)\n\n  rewrite -addn3.\n\n  Check (mod_1n (a.+2 ^ p.+1) (a + 2) p.+1).\n\n  rewrite (mod_1n (a.+2 ^ p.+1) (a + 2) p.+1).\n\n    by rewrite addn2 addn3.\n\n      by rewrite addn2.\n\nQed.\n\n\n\n(* 使わなかった補題 *)\n\nLemma mod_2_3n a b p : a = b.+2 %[mod p] -> a.+1 = b.+3 %[mod p].\n\nProof.\n\n  move=> H.\n\n  apply/eqP.\n\n  move/eqP in H.\n\n  Check eqn_modDr 1 a b.+2 p.\n\n  rewrite -(eqn_modDr 1 a b.+2 p) in H.\n\n  rewrite -addn2 in H.\n\n  rewrite -(addnA b 2 1) in H.\n\n  rewrite addn3 in H.\n\n  rewrite addn1 in H.\n\n  done.\n\nQed.\n\n\n\nLemma modn_trans l m n d :\n\n  l = m %[mod d] -> m = n %[mod d] -> l = n %[mod d].\n\nProof.\n\n  move=> Hlm Hmn.\n\n  by rewrite Hlm.\n\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/Fermat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6624203774985026}}
{"text": "(****************************************************************************)\n(* Copyright 2020 The Project Oak Authors                                   *)\n(*                                                                          *)\n(* Licensed under the Apache License, Version 2.0 (the \"License\")           *)\n(* you may not use this file except in compliance with the License.         *)\n(* You may obtain a copy of the License at                                  *)\n(*                                                                          *)\n(*     http://www.apache.org/licenses/LICENSE-2.0                           *)\n(*                                                                          *)\n(* Unless required by applicable law or agreed to in writing, software      *)\n(* distributed under the License is distributed on an \"AS IS\" BASIS,        *)\n(* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *)\n(* See the License for the specific language governing permissions and      *)\n(* limitations under the License.                                           *)\n(****************************************************************************)\n\nRequire Import Coq.Init.Byte.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.Lists.List.\nRequire Import Coq.micromega.Lia.\nRequire Import Cava.Util.Tactics.\nRequire Coq.Vectors.Vector. (* not imported due to name collisions with List *)\n\nRequire Import Cava.Util.BitArithmetic.\nRequire Import Cava.Util.BitArithmeticProperties.\nRequire Import Cava.Util.List.\nRequire Import Cava.Util.Vector.\nRequire Import AesSpec.Polynomial.\nRequire Import AesSpec.PolynomialProperties.\nImport Vector.VectorNotations.\nImport ListNotations.\nLocal Open Scope list_scope.\n\nSection ByteField.\n  (* Representation of bytes as polynomials with boolean coefficients;\n     relies on N2Bv being little-endian *)\n  Definition byte_to_poly (b : byte) : poly bool :=\n    Vector.to_list (N2Bv_sized 8 (Byte.to_N b)).\n  Definition poly_to_byte (x : poly bool) : byte :=\n    match Byte.of_N (N.of_list_bits x) with\n    | Some b => b\n    | None => Byte.x00 (* error; should not get here! *)\n    end.\n\n  (* Operations in GF(2) *)\n  Local Instance bitops : FieldOperations bool :=\n    {| fzero := false;\n       fone := true;\n       fis_zero := negb;\n       fopp := fun b => b;\n       fadd := xorb;\n       fsub := xorb;\n       fmul := andb;\n       fdiv := fun b1 _ => b1; (* divisor must be 1, otherwise division by 0 *)\n       fmodulo := fun b1 b2 => xorb b1 (andb b2 b1); (* b1 mod b2 = b1 - b2 * (b1 / b2) *)\n    |}.\n\n  (* FIPS 197: 4.2 Multiplication\n\n     In the polynomial representation, multiplication in GF(2^8) (denoted by •)\n     corresponds with the multiplication of polynomials modulo an irreducible\n     polynomial of degree 8. A polynomial is irreducible if its only divisors\n     are one and itself. For the AES algorithm, this irreducible polynomial is\n\n                             m(x) = x^8 + x^4 + x^3 + x + 1                (4.1)\n\n     or {01}{1b} in hexadecimal notation. *)\n\n  (* Modulus for GF(2^8): m(x) = x^8 + x^4 + x^3 + x + 1 *)\n  Definition m : poly bool :=\n    [true; true; false; true; true; false; false; false; true].\n\n  (* Operations in GF(2^8) *)\n  Local Instance byteops : FieldOperations byte :=\n    {| fzero := Byte.x00;\n       fone := Byte.x01;\n       fis_zero := Byte.eqb x00;\n       fopp := fun b => b;\n       fadd :=\n         fun a b => poly_to_byte (add_poly (byte_to_poly a) (byte_to_poly b));\n       fsub :=\n         fun a b => poly_to_byte (sub_poly (byte_to_poly a) (byte_to_poly b));\n       fmul :=\n         fun a b =>\n           let ab := mul_poly (byte_to_poly a) (byte_to_poly b) in\n           poly_to_byte (modulo_poly ab m);\n       fdiv :=\n         fun a b => poly_to_byte (div_poly (byte_to_poly a) (byte_to_poly b));\n       fmodulo :=\n         fun a b => poly_to_byte (modulo_poly (byte_to_poly a) (byte_to_poly b));\n    |}.\n\n  (* Test case from FIPS : {57} ∘ {83} = {c1} *)\n  Goal (let b57 : byte := Byte.x57 in\n        let b83 : byte := Byte.x83 in\n        let bc1 : byte := Byte.xc1 in\n        fmul b57 b83 = bc1).\n  Proof. vm_compute. reflexivity. Qed.\nEnd ByteField.\n\nSection Spec.\n  Context (bytes_per_word := 4%nat) {Nb : nat}.\n  Local Notation column := (Vector.t byte bytes_per_word).\n  Local Notation state := (Vector.t column Nb).\n  Local Existing Instance byteops.\n\n  (* Convert columns to and from polynomials with coeffs in GF(2^8) *)\n  Definition column_to_poly : column -> poly byte := Vector.to_list.\n  Definition poly_to_column (c : poly byte) : column :=\n    resize_default fzero _ (Vector.of_list c).\n\n  (* Modulus : x^4 + 1 *)\n  Definition modulus := [x01; x00; x00; x00; x01]%list.\n\n  (* Multiplication modulo x^4 + 1 *)\n  Definition mulmod (x y : poly byte) : poly byte :=\n    modulo_poly (mul_poly x y) modulus.\n\n  (* 5.1.3 MixColumns() Transformation\n\n     The MixColumns() transformation operates on the State column-by-column,\n     treating each column as a four-term polynomial as described in\n     Sec. 4.3. The columns are considered as polynomials over GF(2^8) and\n     multiplied modulo x^4 + 1 with a fixed polynomial a(x), given by\n\n               a(x) = {03}x^3 + {01}x^2 + {01}x + {02} (5.5)\n\n\n     [...]\n     As a result of this multiplication, the four bytes in a column are replaced\n     by the following:\n\n\n               c'0 = ({02} ∙ c0) ⊕ ({03} ∙ c1) ⊕ c2 ⊕ c3\n               c'1 = c0 ⊕ ({02} ∙ c1) ⊕ ({03} ∙ c2) ⊕ c3\n               c'2 = c0 ⊕ c1 ⊕ ({02} ∙ c2) ⊕ ({03} ∙ c3)\n               c'3 = ({03} ∙ c0) ⊕ c1 ⊕ c2 ⊕ ({02} ∙ c3)\n\n     (∙ and ⊕ above are multiplication and addition in GF(2^8), respectively)\n   *)\n\n  (* MixColumns on a single column using matrix-based formula *)\n  Definition mix_single_column (c : column) : column :=\n    let sum := Vector.fold_left fadd fzero in\n    let prod := Vector.map2 fmul in\n    [ sum (prod [x02; x03; x01; x01]%vector c);\n      sum (prod [x01; x02; x03; x01]%vector c);\n      sum (prod [x01; x01; x02; x03]%vector c);\n      sum (prod [x03; x01; x01; x02]%vector c)\n    ]%vector.\n\n  (* Polynomial version (slower but possibly helpful for proofs) :*)\n  Definition mix_single_column_poly (c : column) : column :=\n    let a : poly byte := [x02;x01;x01;x03] in\n    let c := column_to_poly c in\n    let ac := mulmod a c in\n    poly_to_column ac.\n\n  Definition mix_columns : state -> state := Vector.map mix_single_column.\n\n  (* 5.3.3 InvMixColumns() Transformation\n\n     InvMixColumns() is the inverse of the MixColumns() transformation.\n     InvMixColumns() operates on the State column-by-column, treating each\n     column as a four- term polynomial as described in Sec. 4.3. The columns are\n     considered as polynomials over GF(2^8) and multiplied modulo x^4 + 1 with a\n     fixed polynomial a^(-1)(x), given by\n\n              a^(-1)(x) = {0b}x 3 + {0d}x 2 + {09}x + {0e}.                (5.9)\n\n     [...]\n     As a result of this multiplication, the four bytes in a column are replaced\n     by the following:\n\n\n               c'0 = ({0e} ∙ c0) ⊕ ({0b} ∙ c1) ⊕ ({0d} ∙ c2) ⊕ ({09} ∙ c3)\n               c'1 = ({09} ∙ c0) ⊕ ({0e} ∙ c1) ⊕ ({0b} ∙ c2) ⊕ ({0d} ∙ c3)\n               c'2 = ({0d} ∙ c0) ⊕ ({09} ∙ c1) ⊕ ({0e} ∙ c2) ⊕ ({0b} ∙ c3)\n               c'3 = ({0b} ∙ c0) ⊕ ({0d} ∙ c1) ⊕ ({09} ∙ c2) ⊕ ({0e} ∙ c3)\n *)\n\n  (* InvMixColumns on a single column using matrix-based formula *)\n  Definition inv_mix_single_column (c : column) : column :=\n    let sum := Vector.fold_left fadd fzero in\n    let prod := Vector.map2 fmul in\n    [ sum (prod [x0e; x0b; x0d; x09]%vector c);\n      sum (prod [x09; x0e; x0b; x0d]%vector c);\n      sum (prod [x0d; x09; x0e; x0b]%vector c);\n      sum (prod [x0b; x0d; x09; x0e]%vector c)\n    ]%vector.\n\n  Definition inv_mix_columns : state -> state := Vector.map inv_mix_single_column.\nEnd Spec.\n\nSection MixColumnsTests.\n  Existing Instance byteops.\n  Local Open Scope vector_scope.\n\n  (* Check that mix_single_column with polynomials is the same as with matrices *)\n  Goal (let c := [x00; x01; x02; x03] in\n        mix_single_column_poly c = mix_single_column c).\n  Proof. vm_compute. reflexivity. Qed.\n\n  (* test state :\n     0\n     1\n     2\n     3 *)\n  Goal (let st := [ [x00; x01; x02; x03] ] in (* column-major form *)\n        inv_mix_columns (mix_columns st) = st).\n  Proof. vm_compute. reflexivity. Qed.\n\n  (* test state :\n     0 4 8  12\n     1 5 9  13\n     2 6 10 14\n     3 7 11 15 *)\n  Goal ((* state, in column-major form *)\n        let st :=\n            [ [x00; x01; x02; x03];\n              [x04; x05; x06; x07];\n              [x08; x09; x0a; x0b];\n              [x0c; x0d; x0e; x0f] ] in\n        inv_mix_columns (mix_columns st) = st).\n  Proof. vm_compute. reflexivity. Qed.\nEnd MixColumnsTests.\n\nSection ByteFieldProperties.\n  Existing Instances bitops byteops.\n  Local Infix \"*\" := fmul.\n  Local Infix \"+\" := fadd.\n  Local Infix \"-\" := fsub.\n\n  (* Declare a full ring because we need subtraction for some goals *)\n  Definition bit_theory : ring_theory (R:=bool) fzero fone fadd fmul fsub fopp eq\n    := BoolTheory.\n  Add Ring bitring : bit_theory.\n\n  (* Declare semi-ring for polynomial proof preconditions *)\n  Definition BitTheory : semi_ring_theory (R:=bool) fzero fone fadd fmul eq.\n  Proof.\n    constructor; intros; cbn [fzero fone fadd fmul bitops];\n      repeat match goal with x : bool |- _ => destruct x end; reflexivity.\n  Qed.\n\n  Lemma poly_to_byte_to_poly p :\n    (length p = 8)%nat -> byte_to_poly (poly_to_byte p) = p.\n  Proof.\n    cbv [poly_to_byte byte_to_poly]; intros.\n    destruct_lists_by_length.\n    repeat match goal with x : bool |- _ => destruct x end;\n      vm_compute; reflexivity.\n  Qed.\n\n  Lemma poly_to_byte_to_poly_strip_zeroes p n :\n    length p = 8%nat ->\n    byte_to_poly (poly_to_byte (p ++ repeat false n)) = p.\n  Proof.\n    cbv [poly_to_byte byte_to_poly]; intros.\n    rewrite N_of_list_bits_app, N_of_list_bits_zero.\n    rewrite N.mul_0_r, N.add_0_r.\n    apply poly_to_byte_to_poly; auto.\n  Qed.\n\n  Lemma byte_to_poly_length b : length (byte_to_poly b) = 8%nat.\n  Proof. cbv [byte_to_poly]; length_hammer. Qed.\n\n  Lemma byte_to_poly_inj b1 b2 : byte_to_poly b1 = byte_to_poly b2 -> b1 = b2.\n  Proof.\n    cbv [byte_to_poly]. intro Heq.\n    apply to_list_inj in Heq.\n    assert (forall b, N.size_nat (Byte.to_N b) <= 8%nat)\n      by (intro b; destruct b; vm_compute; lia).\n    apply N2Bv_sized_eq_iff in Heq; [ | solve [auto] .. ].\n    apply Byte.to_of_N_iff in Heq.\n    rewrite Byte.of_to_N in Heq.\n    congruence.\n  Qed.\n\n  (* Extra hints for length_hammer *)\n  Hint Rewrite @add_poly_length byte_to_poly_length\n       using solve [eauto] : push_length.\n  Hint Rewrite @mul_poly_length\n       using (try apply BitTheory; try apply length_pos_nonnil; length_hammer)\n    : push_length.\n  Hint Resolve byte_to_poly_length : length.\n\n  (* Some lemmas to simplify boolean expressions *)\n  Lemma if_id (b : bool) : (if b then true else false) = b.\n  Proof. destruct b; reflexivity. Qed.\n  Lemma if_negb (b : bool) : (if b then false else true) = negb b.\n  Proof. destruct b; reflexivity. Qed.\n  Lemma if_false_formula (b : bool) : (if b then negb b else b) = false.\n  Proof. destruct b; reflexivity. Qed.\n\n  (* Complete formula for multiplication of 8-bit vectors in GF(2^8) *)\n  Definition mul8 (p q : list bool) : list bool :=\n    let p0 := nth 0 p false in\n    let p1 := nth 1 p false in\n    let p2 := nth 2 p false in\n    let p3 := nth 3 p false in\n    let p4 := nth 4 p false in\n    let p5 := nth 5 p false in\n    let p6 := nth 6 p false in\n    let p7 := nth 7 p false in\n    let q0 := nth 0 q false in\n    let q1 := nth 1 q false in\n    let q2 := nth 2 q false in\n    let q3 := nth 3 q false in\n    let q4 := nth 4 q false in\n    let q5 := nth 5 q false in\n    let q6 := nth 6 q false in\n    let q7 := nth 7 q false in\n    [ (p0 * q0);\n    (p0 * q1) + (p1 * q0);\n    (p0 * q2) + (p1 * q1) + (p2 * q0);\n    (p0 * q3) + (p1 * q2) + (p2 * q1) + (p3 * q0);\n    (p0 * q4) + (p1 * q3) + (p2 * q2) + (p3 * q1) + (p4 * q0);\n    (p0 * q5) + (p1 * q4) + (p2 * q3) + (p3 * q2) + (p4 * q1) + (p5 * q0);\n    (p0 * q6) + (p1 * q5) + (p2 * q4) + (p3 * q3) + (p4 * q2) + (p5 * q1) + (p6 * q0);\n    (p0 * q7) + (p1 * q6) + (p2 * q5) + (p3 * q4) + (p4 * q3) + (p5 * q2) + (p6 * q1) + (p7 * q0);\n    (p1 * q7) + (p2 * q6) + (p3 * q5) + (p4 * q4) + (p5 * q3) + (p6 * q2) + (p7 * q1);\n    (p2 * q7) + (p3 * q6) + (p4 * q5) + (p5 * q4) + (p6 * q3) + (p7 * q2);\n    (p3 * q7) + (p4 * q6) + (p5 * q5) + (p6 * q4) + (p7 * q3);\n    (p4 * q7) + (p5 * q6) + (p6 * q5) + (p7 * q4);\n    (p5 * q7) + (p6 * q6) + (p7 * q5);\n    (p6 * q7) + (p7 * q6);\n    (p7 * q7)\n    ].\n\n  Lemma mul8_correct p q :\n    length p = 8%nat -> length q = 8%nat ->\n    mul_poly (ops:=bitops) p q = mul8 p q.\n  Proof.\n    intros; destruct_lists_by_length.\n    vm_compute. rewrite !if_id, !if_negb.\n    reflexivity.\n  Qed.\n\n  (* Modular reduction with modulus m and 15-bit input:\n\n    round 1 (a[14]):\n    a[6] -= a[14]\n    a[7] -= a[14]\n    a[9] -= a[14]\n    a[10] -= a[14]\n\n    round 2 (a[13]):\n    a[5] -= a[13]\n    a[6] -= a[13]\n    a[8] -= a[13]\n    a[9] -= a[13]\n\n    round 3 (a[12]):\n    a[4] -= a[12]\n    a[5] -= a[12]\n    a[7] -= a[12]\n    a[8] -= a[12]\n\n    round 4 (a[11]):\n    a[3] -= a[11]\n    a[4] -= a[11]\n    a[6] -= a[11]\n    a[7] -= a[11]\n\n    round 5 (a[10]):\n    a[2] -= a[10]\n    a[3] -= a[10]\n    a[5] -= a[10]\n    a[6] -= a[10]\n\n    round 6 (a[9]):\n    a[1] -= a[9]\n    a[2] -= a[9]\n    a[4] -= a[9]\n    a[5] -= a[9]\n\n    round 7 (a[8]):\n    a[0] -= a[8]\n    a[1] -= a[8]\n    a[3] -= a[8]\n    a[4] -= a[8]\n\n    final in terms of initial:\n\n    a'[8]  = a[8]  - a[13] - a[12]\n    a'[9]  = a[9]  - a[14] - a[13]\n    a'[10] = a[10] - a[14]\n\n    a[0] = a[0] - a'[8]\n    a[1] = a[1] - a'[9] - a'[8]\n    a[2] = a[2] - a'[10] - a'[9]\n    a[3] = a[3] - a[11] - a'[10] - a'[8]\n    a[4] = a[4] - a[12] - a[11]  - a'[9]  - a'[8]\n    a[5] = a[5] - a[13] - a[12]  - a'[10] - a'[9]\n    a[6] = a[6] - a[14] - a[13]  - a[11] - a'[10]\n    a[7] = a[7] - a[14] - a[12]  - a[11]\n\n   *)\n  Definition modulo15 (p : list bool) : list bool :=\n    let p0 := nth 0 p false in\n    let p1 := nth 1 p false in\n    let p2 := nth 2 p false in\n    let p3 := nth 3 p false in\n    let p4 := nth 4 p false in\n    let p5 := nth 5 p false in\n    let p6 := nth 6 p false in\n    let p7 := nth 7 p false in\n    let p8 := nth 8 p false in\n    let p9 := nth 9 p false in\n    let p10 := nth 10 p false in\n    let p11 := nth 11 p false in\n    let p12 := nth 12 p false in\n    let p13 := nth 13 p false in\n    let p14 := nth 14 p false in\n    (* redefine p8, p9, and p10 to their final values *)\n    let p8 := p8 - p13 - p12 in\n    let p9 := p9 - p14 - p13 in\n    let p10 := p10 - p14 in\n    [ p0 - p8;\n    p1 - p9 - p8;\n    p2 - p10 - p9;\n    p3 - p11 - p10 - p8;\n    p4 - p12 - p11 - p9 - p8;\n    p5 - p13 - p12 - p10 - p9;\n    p6 - p14 - p13 - p11 - p10;\n    p7 - p14 - p12 - p11\n    ].\n\n  Lemma modulo15_correct p :\n    length p = 15%nat -> byte_to_poly (poly_to_byte (modulo_poly p m)) = modulo15 p.\n  Proof.\n    intros. set (X:=modulo_poly p m).\n    destruct_lists_by_length.\n    vm_compute in X. subst X.\n    (* simplify boolean expressions *)\n    rewrite !Tauto.if_same, !if_id, !if_negb, !if_false_formula.\n    (* strip zeroes *)\n    match goal with\n    | |- byte_to_poly\n          (poly_to_byte\n             [?x0;?x1;?x2;?x3;?x4;?x5;?x6;?x7;\n              false;false;false;false;false;false;false]) = _ =>\n      let H := fresh in\n      pose proof\n           (poly_to_byte_to_poly_strip_zeroes\n              [x0;x1;x2;x3;x4;x5;x6;x7] 7) as H;\n        cbn [repeat app] in H; rewrite H by reflexivity;\n          clear H\n    end.\n    cbv [modulo15 nth].\n    fequal_list; clear;\n      repeat match goal with b : bool |- _ => destruct b end;\n      vm_compute; reflexivity.\n  Qed.\n\n  (* Explicit formula for addition of two 8-bit vectors *)\n  Definition add8 (p q : list bool) : list bool :=\n    let p0 := nth 0 p false in\n    let p1 := nth 1 p false in\n    let p2 := nth 2 p false in\n    let p3 := nth 3 p false in\n    let p4 := nth 4 p false in\n    let p5 := nth 5 p false in\n    let p6 := nth 6 p false in\n    let p7 := nth 7 p false in\n    let q0 := nth 0 q false in\n    let q1 := nth 1 q false in\n    let q2 := nth 2 q false in\n    let q3 := nth 3 q false in\n    let q4 := nth 4 q false in\n    let q5 := nth 5 q false in\n    let q6 := nth 6 q false in\n    let q7 := nth 7 q false in\n    [ p0 + q0;\n    p1 + q1;\n    p2 + q2;\n    p3 + q3;\n    p4 + q4;\n    p5 + q5;\n    p6 + q6;\n    p7 + q7\n    ].\n\n  Lemma add8_correct p q :\n    length p = 8%nat -> length q = 8%nat ->\n    add_poly p q = add8 p q.\n  Proof. intros; destruct_lists_by_length; reflexivity. Qed.\n\n  Local Ltac generalize_bytes_as_polynomials :=\n    repeat lazymatch goal with\n           | |- context [byte_to_poly ?b] =>\n             pose proof (byte_to_poly_length b);\n             generalize dependent (byte_to_poly b);\n             intros\n           end.\n\n  Lemma byte_mul_assoc (a b c : byte) :\n    fmul a (fmul b c) = fmul (fmul a b) c.\n  Proof.\n    cbv [fmul fadd byteops]. apply byte_to_poly_inj.\n    rewrite !modulo15_correct, !mul8_correct by length_hammer.\n    generalize_bytes_as_polynomials. destruct_lists_by_length.\n    lazy [mul8 nth modulo15].\n    (* use ring to prove that each element of the list is equal *)\n    fequal_list; clear.\n    Time all:ring.\n  Qed.\n\n  Lemma byte_mul_distr_l (a b c : byte) :\n    fmul (fadd a b) c = fadd (fmul a c) (fmul b c).\n  Proof.\n    cbv [fmul fadd byteops].\n    apply byte_to_poly_inj.\n    rewrite !modulo15_correct by length_hammer.\n    rewrite !mul8_correct by length_hammer.\n    rewrite !add8_correct by length_hammer.\n    rewrite !poly_to_byte_to_poly by reflexivity.\n    pose proof (byte_to_poly_length a).\n    pose proof (byte_to_poly_length b).\n    pose proof (byte_to_poly_length c).\n    generalize dependent (byte_to_poly a); intros A ?.\n    generalize dependent (byte_to_poly b); intros B ?.\n    generalize dependent (byte_to_poly c); intros C ?.\n    destruct_lists_by_length.\n    lazy [mul8 add8 nth modulo15].\n    (* use ring to prove that each element of the list is equal *)\n    fequal_list; clear; ring.\n  Qed.\n\n  Definition ByteTheory : semi_ring_theory (R:=byte) fzero fone fadd fmul eq.\n  Proof.\n    constructor; cbn [fadd fmul byteops].\n    { intro b; destruct b; reflexivity. }\n    { intros. f_equal. apply @add_poly_comm, BitTheory. }\n    { intros. rewrite !poly_to_byte_to_poly by length_hammer.\n      f_equal. apply @add_poly_assoc, BitTheory. }\n    { intro b; destruct b; vm_compute; reflexivity. }\n    { intro b; destruct b; vm_compute; reflexivity. }\n    { intros; do 2 f_equal. apply @mul_poly_comm, BitTheory. }\n    { apply byte_mul_assoc. }\n    { apply byte_mul_distr_l. }\n  Qed.\nEnd ByteFieldProperties.\nHint Rewrite @add_poly_length byte_to_poly_length\n     using solve [eauto] : push_length.\n\nSection Properties.\n  Existing Instance byteops.\n  Add Ring bytering : ByteTheory.\n  Local Open Scope poly_scope.\n\n  Definition sum (p : poly byte) : byte := List.fold_left fadd p fzero.\n  Definition prod (p q : poly byte) : poly byte := map2 fmul p q.\n\n  (* multiplication modulo x^4-1 for 4-digit polynomials *)\n  Definition matrix_mulmod (p q : poly byte) : poly byte :=\n    let p0 := nth 0 p fzero in\n    let p1 := nth 1 p fzero in\n    let p2 := nth 2 p fzero in\n    let p3 := nth 3 p fzero in\n    let q0 := nth 0 q fzero in\n    let q1 := nth 1 q fzero in\n    let q2 := nth 2 q fzero in\n    let q3 := nth 3 q fzero in\n    [ sum (prod [q0;q3;q2;q1] [p0;p1;p2;p3]);\n      sum (prod [q1;q0;q3;q2] [p0;p1;p2;p3]);\n      sum (prod [q2;q1;q0;q3] [p0;p1;p2;p3]);\n      sum (prod [q3;q2;q1;q0] [p0;p1;p2;p3])\n    ].\n\n  Hint Unfold matrix_mulmod sum prod nth map2 fold_left : matrix_mulmod.\n\n  Lemma matrix_mulmod_assoc a b c :\n    length a = 4%nat -> length b = 4%nat -> length c = 4%nat ->\n    matrix_mulmod a (matrix_mulmod b c) = matrix_mulmod (matrix_mulmod a b) c.\n  Proof.\n    intros; destruct_lists_by_length.\n    autounfold with matrix_mulmod.\n    fequal_list; ring.\n  Qed.\n\n  Lemma matrix_mulmod_1_l p :\n    length p = 4%nat ->\n    matrix_mulmod [fone;fzero;fzero;fzero] p = p.\n  Proof.\n    intros; destruct_lists_by_length.\n    autounfold with matrix_mulmod.\n    fequal_list; ring.\n  Qed.\n\n  Lemma matrix_mulmod_distr_l a b c :\n    length a = 4%nat -> length b = 4%nat -> length c = 4%nat ->\n    matrix_mulmod a (map2 fadd b c)\n    = map2 fadd (matrix_mulmod a b) (matrix_mulmod a c).\n  Proof.\n    intros; destruct_lists_by_length.\n    autounfold with matrix_mulmod.\n    fequal_list; ring.\n  Qed.\n\n  Lemma mix_single_column_is_matrix_mulmod d c :\n    mix_single_column c = of_list_sized d 4%nat\n                                        (matrix_mulmod [x02;x01;x01;x03]\n                                                       (Vector.to_list c)).\n  Proof.\n    cbv [mix_single_column]. constant_vector_simpl c.\n    autorewrite with push_to_list.\n    autounfold with matrix_mulmod.\n    cbv [of_list_sized Vector.of_list].\n    rewrite resize_default_id.\n    fequal_vector; ring.\n  Qed.\n\n  Lemma inv_mix_single_column_is_matrix_mulmod d c :\n    inv_mix_single_column c = of_list_sized d 4%nat\n                                            (matrix_mulmod [x0e;x09;x0d;x0b]\n                                                           (Vector.to_list c)).\n  Proof.\n    cbv [inv_mix_single_column]. constant_vector_simpl c.\n    autorewrite with push_to_list.\n    autounfold with matrix_mulmod.\n    cbv [of_list_sized Vector.of_list].\n    rewrite resize_default_id.\n    fequal_vector; try ring.\n  Qed.\n\n  Lemma inverse_mix_single_column c :\n    inv_mix_single_column (mix_single_column c) = c.\n  Proof.\n    rewrite inv_mix_single_column_is_matrix_mulmod with (d:=fzero).\n    rewrite mix_single_column_is_matrix_mulmod with (d:=fzero).\n    autorewrite with push_to_list.\n    rewrite matrix_mulmod_assoc by length_hammer.\n    match goal with\n    | |- context [matrix_mulmod (cons ?a0 ?a) (cons ?b0 ?b)] =>\n      compute_expr (matrix_mulmod (cons a0 a) (cons b0 b))\n    end.\n    rewrite matrix_mulmod_1_l by length_hammer.\n    rewrite of_list_sized_to_list; reflexivity.\n  Qed.\n\n  Lemma inverse_mix_columns {Nb} (state : Vector.t (Vector.t byte 4) Nb) :\n    inv_mix_columns (mix_columns state) = state.\n  Proof.\n    cbv [inv_mix_columns mix_columns].\n    rewrite Vector.map_map.\n    apply map_id_ext.\n    apply inverse_mix_single_column.\n  Qed.\n\n  (* add in this field is the same as add_round_key *)\n  Lemma inv_mix_columns_add_comm\n        {Nb} (x y : Vector.t (Vector.t byte 4) Nb) :\n    Vector.map2 (Vector.map2 fadd) (inv_mix_columns x) (inv_mix_columns y)\n    = inv_mix_columns (Vector.map2 (Vector.map2 fadd) x y).\n  Proof.\n    cbv [inv_mix_columns]. rewrite map2_map, map_map2.\n    apply map2_ext; intros.\n    rewrite !inv_mix_single_column_is_matrix_mulmod with (d:=fzero).\n    apply to_list_inj. autorewrite with push_to_list.\n    rewrite matrix_mulmod_distr_l by length_hammer.\n    reflexivity.\n  Qed.\nEnd Properties.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/silveroak-opentitan/aes/Spec/MixColumns.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6624203774977406}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_parallelNC.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_NCdistinct.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_parallelflip.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_collinearparallel.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_collinearparallel2 : \n   forall A B C D E F, \n   Par A B C D -> Col C D E -> Col C D F -> neq E F ->\n   Par A B E F.\nProof.\nintros.\nassert (neq F E) by (conclude lemma_inequalitysymmetric).\nassert (nCol A C D) by (forward_using lemma_parallelNC).\nassert (neq C D) by (forward_using lemma_NCdistinct).\nassert (neq D C) by (conclude lemma_inequalitysymmetric).\nassert (Col D C E) by (forward_using lemma_collinearorder).\nassert (Col D C F) by (forward_using lemma_collinearorder).\nassert (Col C E F) by (conclude lemma_collinear4).\nassert (Col C F E) by (forward_using lemma_collinearorder).\nassert (Par A B D C) by (forward_using lemma_parallelflip).\nassert (Par A B E F).\nby cases on (eq E D \\/ neq E D).\n{\n assert (neq D F) by (conclude cn_equalitysub).\n assert (neq F D) by (conclude lemma_inequalitysymmetric).\n assert (Par A B F D) by (conclude lemma_collinearparallel).\n assert (Par A B D F) by (forward_using lemma_parallelflip).\n assert (Col C F D) by (forward_using lemma_collinearorder).\n assert (Col C F E) by (forward_using lemma_collinearorder).\n assert (Col F D E).\n by cases on (eq C F \\/ neq C F).\n {\n  assert (Col C D E) by (forward_using lemma_collinearorder).\n  assert (Col F D E) by (conclude cn_equalitysub).\n  close.\n  }\n {\n  assert (Col F D E) by (conclude lemma_collinear4).\n  close.\n  }\n(** cases *)\n assert (Col D F E) by (forward_using lemma_collinearorder).\n assert (Par A B E F) by (conclude lemma_collinearparallel).\n close.\n }\n{\n assert (Par A B E D) by (conclude lemma_collinearparallel).\n assert (Par A B D E) by (forward_using lemma_parallelflip).\n assert (Col D E F) by (conclude lemma_collinear4).\n assert (Par A B F E) by (conclude lemma_collinearparallel).\n assert (Par A B E F) by (forward_using lemma_parallelflip).\n close.\n }\n(** cases *)\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_collinearparallel2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6624203726601161}}
{"text": "Require Import Basics.\nRequire Import Types.\nRequire Import Diagrams.Graph.\nRequire Import Diagrams.Diagram.\nRequire Import Diagrams.Cocone.\n\n(** Parallel pairs *)\n\nDefinition parallel_pair_graph : Graph.\nProof.\n  srapply (Build_Graph Bool).\n  intros i j.\n  exact (if i then if j then Empty else Bool else Empty).\nDefined.\n\n(** Parallel pair diagram *)\n\nDefinition parallel_pair {A B : Type} (f g : A -> B)\n  : Diagram parallel_pair_graph.\nProof.\n  srapply Build_Diagram.\n  1: intros []; [exact A | exact B].\n  intros [] [] []; [exact f | exact g].\nDefined.\n\n(** Cones on [parallel_pair]s *)\n\nDefinition Build_parallel_pair_cocone {A B Q} {f g : B -> A}\n  `(q: A -> Q) (Hq: q o g == q o f)\n  : Cocone (parallel_pair f g) Q.\nProof.\n  srapply Build_Cocone.\n  1: intros []; [exact (q o f) | exact q].\n  intros [] [] []; [reflexivity | exact Hq].\nDefined.", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Diagrams/ParallelPair.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6623899701102213}}
{"text": "\nAxiom excluded_middle : forall (P : Prop), P \\/ ~P.\n\nLemma double_negation_elimination (P : Prop) :\n  ~~P -> P.\nProof.\n  intros H. destruct (excluded_middle P) as [Hp | Hnp].\n  - assumption.\n  - contradiction.\nQed.\n", "meta": {"author": "fondefjobn", "repo": "S5-Formalization-in-Coq", "sha": "4141f570a4156afb25e291c8ecb987cfc85822ab", "save_path": "github-repos/coq/fondefjobn-S5-Formalization-in-Coq", "path": "github-repos/coq/fondefjobn-S5-Formalization-in-Coq/S5-Formalization-in-Coq-4141f570a4156afb25e291c8ecb987cfc85822ab/source/prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6623899683661759}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *         Copyright INRIA, CNRS and contributors             *)\n(* <O___,, * (see version control and CREDITS file for authors & dates) *)\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 Fairness.OrderedType.\nRequire Import ZArith_base.\nRequire Import PeanoNat.\nRequire Import Ascii String.\nRequire Import NArith Ndec.\nRequire Import Compare_dec.\n\n(** * Examples of Ordered Type structures. *)\n\n(** First, a particular case of [OrderedTypeLarge] where\n    the equality is the usual one of Coq. *)\n\nModule Type UsualOrderedTypeLarge.\n Parameter Inline t : Type.\n Definition eq := @eq t.\n Parameter Inline lt : t -> t -> Prop.\n Definition eq_refl := @eq_refl t.\n Definition eq_sym := @eq_sym t.\n Definition eq_trans := @eq_trans t.\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 Parameter compare : forall x y : t, Compare lt eq x y.\n Parameter eq_dec : forall x y : t, { eq x y } + { ~ eq x y }.\nEnd UsualOrderedTypeLarge.\n\n(** a [UsualOrderedTypeLarge] is in particular an [OrderedTypeLarge]. *)\n\nModule UOT_to_OT (U:UsualOrderedTypeLarge) <: OrderedTypeLarge := U.\n\n(** [nat] is an ordered type with respect to the usual order on natural numbers. *)\n\nModule Nat_as_OT <: UsualOrderedTypeLarge.\n\n  Definition t := nat.\n\n  Definition eq := @eq nat.\n  Definition eq_refl := @eq_refl t.\n  Definition eq_sym := @eq_sym t.\n  Definition eq_trans := @eq_trans t.\n\n  Definition lt := lt.\n\n  Lemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z.\n  Proof. unfold lt; intros; apply lt_trans with y; auto. Qed.\n\n  Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y.\n  Proof. unfold lt, eq; intros ? ? LT ->; revert LT; apply Nat.lt_irrefl. Qed.\n\n  Definition compare x y : Compare lt eq x y.\n  Proof.\n    case_eq (Nat.compare x y); intro.\n    - apply EQ. now apply nat_compare_eq.\n    - apply LT. now apply nat_compare_Lt_lt.\n    - apply GT. now apply nat_compare_Gt_gt.\n  Defined.\n\n  Definition eq_dec := eq_nat_dec.\n\nEnd Nat_as_OT.\n\n\n(** [Z] is an ordered type with respect to the usual order on integers. *)\n\nLocal Open Scope Z_scope.\n\nModule Z_as_OT <: UsualOrderedTypeLarge.\n\n  Definition t := Z.\n  Definition eq := @eq Z.\n  Definition eq_refl := @eq_refl t.\n  Definition eq_sym := @eq_sym t.\n  Definition eq_trans := @eq_trans t.\n\n  Definition lt (x y:Z) := (x<y).\n\n  Lemma lt_trans : forall x y z, x<y -> y<z -> x<z.\n  Proof. exact Z.lt_trans. Qed.\n\n  Lemma lt_not_eq : forall x y, x<y -> ~ x=y.\n  Proof. intros x y LT ->; revert LT; apply Z.lt_irrefl. Qed.\n\n  Definition compare x y : Compare lt eq x y.\n  Proof.\n    case_eq (x ?= y); intro.\n    - apply EQ. now apply Z.compare_eq.\n    - apply LT. assumption.\n    - apply GT. now apply Z.gt_lt.\n  Defined.\n\n  Definition eq_dec := Z.eq_dec.\n\nEnd Z_as_OT.\n\n(** [positive] is an ordered type with respect to the usual order on natural numbers. *)\n\nLocal Open Scope positive_scope.\n\nModule Positive_as_OT <: UsualOrderedTypeLarge.\n  Definition t:=positive.\n  Definition eq:=@eq positive.\n  Definition eq_refl := @eq_refl t.\n  Definition eq_sym := @eq_sym t.\n  Definition eq_trans := @eq_trans t.\n\n  Definition lt := Pos.lt.\n\n  Definition lt_trans := Pos.lt_trans.\n\n  Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y.\n  Proof.\n  intros x y H. contradict H. rewrite H. apply Pos.lt_irrefl.\n  Qed.\n\n  Definition compare x y : Compare lt eq x y.\n  Proof.\n  case_eq (x ?= y); intros H.\n  - apply EQ. now apply Pos.compare_eq.\n  - apply LT; assumption.\n  - apply GT. now apply Pos.gt_lt.\n  Defined.\n\n  Definition eq_dec := Pos.eq_dec.\n\nEnd Positive_as_OT.\n\n\n(** [N] is an ordered type with respect to the usual order on natural numbers. *)\n\nModule N_as_OT <: UsualOrderedTypeLarge.\n  Definition t:=N.\n  Definition eq:=@eq N.\n  Definition eq_refl := @eq_refl t.\n  Definition eq_sym := @eq_sym t.\n  Definition eq_trans := @eq_trans t.\n\n  Definition lt := N.lt.\n  Definition lt_trans := N.lt_trans.\n  Definition lt_not_eq := N.lt_neq.\n\n  Definition compare x y : Compare lt eq x y.\n  Proof.\n  case_eq (x ?= y)%N; intro.\n  - apply EQ. now apply N.compare_eq.\n  - apply LT. assumption.\n  - apply GT. now apply N.gt_lt.\n  Defined.\n\n  Definition eq_dec := N.eq_dec.\n\nEnd N_as_OT.\n\n\n(** From two ordered types, we can build a new OrderedTypeLarge\n   over their cartesian product, using the lexicographic order. *)\n\nModule PairOrderedTypeLarge(O1 O2:OrderedTypeLarge) <: OrderedTypeLarge.\n Module MO1:=OrderedTypeLargeFacts(O1).\n Module MO2:=OrderedTypeLargeFacts(O2).\n\n Definition t := prod O1.t O2.t.\n\n Definition eq x y := O1.eq (fst x) (fst y) /\\ O2.eq (snd x) (snd y).\n\n Definition lt x y :=\n    O1.lt (fst x) (fst y) \\/\n    (O1.eq (fst x) (fst y) /\\ O2.lt (snd x) (snd y)).\n\n Lemma eq_refl : forall x : t, eq x x.\n Proof.\n intros (x1,x2); red; simpl; auto with ordered_type.\n Qed.\n\n Lemma eq_sym : forall x y : t, eq x y -> eq y x.\n Proof.\n intros (x1,x2) (y1,y2); unfold eq; simpl; intuition.\n Qed.\n\n Lemma eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z.\n Proof.\n intros (x1,x2) (y1,y2) (z1,z2); unfold eq; simpl; intuition eauto with ordered_type.\n Qed.\n\n Lemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z.\n Proof.\n intros (x1,x2) (y1,y2) (z1,z2); unfold eq, lt; simpl; intuition.\n left; eauto with ordered_type.\n left; eapply MO1.lt_eq; eauto.\n left; eapply MO1.eq_lt; eauto.\n right; split; eauto with ordered_type.\n Qed.\n\n Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y.\n Proof.\n intros (x1,x2) (y1,y2); unfold eq, lt; simpl; intuition.\n apply (O1.lt_not_eq H0 H1).\n apply (O2.lt_not_eq H3 H2).\n Qed.\n\n Definition compare : forall x y : t, Compare lt eq x y.\n intros (x1,x2) (y1,y2).\n destruct (O1.compare x1 y1).\n apply LT; unfold lt; auto.\n destruct (O2.compare x2 y2).\n apply LT; unfold lt; auto.\n apply EQ; unfold eq; auto.\n apply GT; unfold lt; auto with ordered_type.\n apply GT; unfold lt; auto.\n Defined.\n\n Definition eq_dec : forall x y : t, {eq x y} + {~ eq x y}.\n Proof.\n intros; elim (compare x y); intro H; [ right | left | right ]; auto.\n auto using lt_not_eq.\n assert (~ eq y x); auto using lt_not_eq, eq_sym.\n Defined.\n\nEnd PairOrderedTypeLarge.\n\n\n(** Even if [positive] can be seen as an ordered type with respect to the\n  usual order (see above), we can also use a lexicographic order over bits\n  (lower bits are considered first). This is more natural when using\n  [positive] as indexes for sets or maps (see FSetPositive and FMapPositive. *)\n\nModule PositiveOrderedTypeLargeBits <: UsualOrderedTypeLarge.\n  Definition t:=positive.\n  Definition eq:=@eq positive.\n  Definition eq_refl := @eq_refl t.\n  Definition eq_sym := @eq_sym t.\n  Definition eq_trans := @eq_trans t.\n\n  Fixpoint bits_lt (p q:positive) : Prop :=\n   match p, q with\n   | xH, xI _ => True\n   | xH, _ => False\n   | xO p, xO q => bits_lt p q\n   | xO _, _ => True\n   | xI p, xI q => bits_lt p q\n   | xI _, _ => False\n   end.\n\n  Definition lt:=bits_lt.\n\n  Lemma bits_lt_trans :\n    forall x y z : positive, bits_lt x y -> bits_lt y z -> bits_lt x z.\n  Proof.\n  induction x.\n  induction y; destruct z; simpl; eauto; intuition.\n  induction y; destruct z; simpl; eauto; intuition.\n  induction y; destruct z; simpl; eauto; intuition.\n  Qed.\n\n  Lemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z.\n  Proof.\n  exact bits_lt_trans.\n  Qed.\n\n  Lemma bits_lt_antirefl : forall x : positive, ~ bits_lt x x.\n  Proof.\n  induction x; simpl; auto.\n  Qed.\n\n  Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y.\n  Proof.\n  intros; intro.\n  rewrite <- H0 in H; clear H0 y.\n  unfold lt in H.\n  exact (bits_lt_antirefl x H).\n  Qed.\n\n  Definition compare : forall x y : t, Compare lt eq x y.\n  Proof.\n  induction x; destruct y.\n  - (* I I *)\n    destruct (IHx y) as [l|e|g].\n    apply LT; auto.\n    apply EQ; rewrite e; red; auto.\n    apply GT; auto.\n  - (* I O *)\n    apply GT; simpl; auto.\n  - (* I H *)\n    apply GT; simpl; auto.\n  - (* O I *)\n    apply LT; simpl; auto.\n  - (* O O *)\n    destruct (IHx y) as [l|e|g].\n    apply LT; auto.\n    apply EQ; rewrite e; red; auto.\n    apply GT; auto.\n  - (* O H *)\n    apply LT; simpl; auto.\n  - (* H I *)\n    apply LT; simpl; auto.\n  - (* H O *)\n    apply GT; simpl; auto.\n  - (* H H *)\n    apply EQ; red; auto.\n  Qed.\n\n  Lemma eq_dec (x y: positive): {x = y} + {x <> y}.\n  Proof.\n  intros. case_eq (x ?= y); intros.\n  - left. now apply Pos.compare_eq.\n  - right. intro. subst y. now rewrite (Pos.compare_refl x) in *.\n  - right. intro. subst y. now rewrite (Pos.compare_refl x) in *.\n  Qed.\n\nEnd PositiveOrderedTypeLargeBits.\n\nModule Ascii_as_OT <: UsualOrderedTypeLarge.\n  Definition t := ascii.\n\n  Definition eq := @eq ascii.\n  Definition eq_refl := @eq_refl t.\n  Definition eq_sym := @eq_sym t.\n  Definition eq_trans := @eq_trans t.\n\n  Definition cmp : ascii -> ascii -> comparison := Ascii.compare.\n\n  Lemma cmp_eq (a b : ascii):\n    cmp a b = Eq  <->  a = b.\n  Proof.\n    unfold cmp, Ascii.compare.\n    rewrite N.compare_eq_iff.\n    split. 2:{ intro. now subst. }\n    intro H.\n    rewrite<- (ascii_N_embedding a).\n    rewrite<- (ascii_N_embedding b).\n    now rewrite H.\n  Qed.\n\n  Lemma cmp_lt_nat (a b : ascii):\n    cmp a b = Lt  <->  (nat_of_ascii a < nat_of_ascii b)%nat.\n  Proof.\n    unfold cmp. unfold nat_of_ascii, Ascii.compare.\n    rewrite N2Nat.inj_compare.\n    rewrite Nat.compare_lt_iff.\n    reflexivity.\n  Qed.\n\n  Lemma cmp_antisym (a b : ascii):\n    cmp a b = CompOpp (cmp b a).\n  Proof.\n    unfold cmp.\n    apply N.compare_antisym.\n  Qed.\n\n  Definition lt (x y : ascii) := (N_of_ascii x < N_of_ascii y)%N.\n\n  Lemma lt_trans (x y z : ascii):\n    lt x y -> lt y z -> lt x z.\n  Proof.\n    apply N.lt_trans.\n  Qed.\n\n  Lemma lt_not_eq (x y : ascii):\n     lt x y -> x <> y.\n  Proof.\n    intros L H. subst.\n    exact (N.lt_irrefl _ L).\n  Qed.\n\n  Local Lemma compare_helper_eq {a b : ascii} (E : cmp a b = Eq):\n    a = b.\n  Proof.\n    now apply cmp_eq.\n  Qed.\n\n  Local Lemma compare_helper_gt {a b : ascii} (G : cmp a b = Gt):\n    lt b a.\n  Proof.\n    now apply N.compare_gt_iff.\n  Qed.\n\n  Definition compare (a b : ascii) : Compare lt eq a b :=\n    match cmp a b as z return _ = z -> _ with\n    | Lt => fun E => LT E\n    | Gt => fun E => GT (compare_helper_gt E)\n    | Eq => fun E => EQ (compare_helper_eq E)\n    end Logic.eq_refl.\n\n  Definition eq_dec (x y : ascii): {x = y} + { ~ (x = y)} := ascii_dec x y.\nEnd Ascii_as_OT.\n\n(** [String] is an ordered type with respect to the usual lexical order. *)\n\nModule String_as_OT <: UsualOrderedTypeLarge.\n\n  Definition t := string.\n\n  Definition eq := @eq string.\n  Definition eq_refl := @eq_refl t.\n  Definition eq_sym := @eq_sym t.\n  Definition eq_trans := @eq_trans t.\n\n  Inductive lts : string -> string -> Prop :=\n    | lts_empty : forall a s, lts EmptyString (String a s)\n    | lts_tail : forall a s1 s2, lts s1 s2 -> lts (String a s1) (String a s2)\n    | lts_head : forall (a b : ascii) s1 s2,\n        lt (nat_of_ascii a) (nat_of_ascii b) ->\n        lts (String a s1) (String b s2).\n\n  Definition lt := lts.\n\n  Lemma nat_of_ascii_inverse a b : nat_of_ascii a = nat_of_ascii b -> a = b.\n  Proof.\n    intro H.\n    rewrite <- (ascii_nat_embedding a).\n    rewrite <- (ascii_nat_embedding b).\n    apply f_equal; auto.\n  Qed.\n\n  Lemma lts_tail_unique a s1 s2 : lt (String a s1) (String a s2) ->\n    lt s1 s2.\n  Proof.\n    intro H; inversion H; subst; auto.\n    remember (nat_of_ascii a) as x.\n    apply lt_irrefl in H1; inversion H1.\n  Qed.\n\n  Lemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z.\n  Proof.\n    induction x; intros y z H1 H2.\n    - destruct y as [| b y']; inversion H1.\n      destruct z as [| c z']; inversion H2; constructor.\n    - destruct y as [| b y']; inversion H1; subst;\n        destruct z as [| c z']; inversion H2; subst.\n      + constructor. eapply IHx; eauto.\n      + constructor; assumption.\n      + constructor; assumption.\n      + constructor. eapply lt_trans; eassumption.\n  Qed.\n\n  Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y.\n  Proof.\n    induction x; intros y LT.\n    - inversion LT. intro. inversion H.\n    - inversion LT; subst; intros EQ.\n      * specialize (IHx s2 H2).\n        inversion EQ; subst; auto.\n        apply IHx; unfold eq; auto.\n      * inversion EQ; subst; auto.\n        apply Nat.lt_irrefl in H2; auto.\n  Qed.\n\n  Definition cmp : string -> string -> comparison := String.compare.\n\n  Lemma cmp_eq (a b : string):\n    cmp a b = Eq  <->  a = b.\n  Proof.\n    revert b.\n    induction a, b; try easy.\n    cbn.\n    remember (Ascii.compare _ _) as c eqn:Heqc. symmetry in Heqc.\n    destruct c; split; try discriminate;\n      try rewrite Ascii_as_OT.cmp_eq in Heqc; try subst;\n      try rewrite IHa; intro H.\n    { now subst. }\n    { now inversion H. }\n    { inversion H; subst. rewrite<- Heqc. now rewrite Ascii_as_OT.cmp_eq. }\n    { inversion H; subst. rewrite<- Heqc. now rewrite Ascii_as_OT.cmp_eq. }\n  Qed.\n\n  Lemma cmp_antisym (a b : string):\n    cmp a b = CompOpp (cmp b a).\n  Proof.\n    revert b.\n    induction a, b; try easy.\n    cbn. rewrite IHa. clear IHa.\n    remember (Ascii.compare _ _) as c eqn:Heqc. symmetry in Heqc.\n    destruct c; rewrite Ascii_as_OT.cmp_antisym in Heqc;\n      destruct Ascii_as_OT.cmp; cbn in *; easy.\n  Qed.\n\n  Lemma cmp_lt (a b : string):\n    cmp a b = Lt  <->  lt a b.\n  Proof.\n    revert b.\n    induction a as [ | a_head a_tail ], b; try easy; cbn.\n    { split; trivial. intro. apply lts_empty. }\n    remember (Ascii.compare _ _) as c eqn:Heqc. symmetry in Heqc.\n    destruct c; split; intro H; try discriminate; trivial.\n    {\n      rewrite Ascii_as_OT.cmp_eq in Heqc. subst.\n      apply String_as_OT.lts_tail.\n      apply IHa_tail.\n      assumption.\n    }\n    {\n      rewrite Ascii_as_OT.cmp_eq in Heqc. subst.\n      inversion H; subst. { rewrite IHa_tail. assumption. }\n      exfalso. apply (Nat.lt_irrefl (nat_of_ascii a)). assumption.\n    }\n    {\n      apply String_as_OT.lts_head.\n      rewrite<- Ascii_as_OT.cmp_lt_nat.\n      assumption.\n    }\n    {\n      exfalso. inversion H; subst.\n      {\n         assert(X: Ascii.compare a a = Eq). { apply Ascii_as_OT.cmp_eq. trivial. }\n         rewrite Heqc in X. discriminate.\n      }\n      rewrite<- Ascii_as_OT.cmp_lt_nat in *.\n      unfold Ascii_as_OT.cmp in *.\n      rewrite Heqc in *. discriminate.\n    }\n  Qed.\n\n  Local Lemma compare_helper_lt {a b : string} (L : cmp a b = Lt):\n    lt a b.\n  Proof.\n    now apply cmp_lt.\n  Qed.\n\n  Local Lemma compare_helper_gt {a b : string} (G : cmp a b = Gt):\n    lt b a.\n  Proof.\n    rewrite cmp_antisym in G.\n    rewrite CompOpp_iff in G.\n    now apply cmp_lt.\n  Qed.\n\n  Local Lemma compare_helper_eq {a b : string} (E : cmp a b = Eq):\n    a = b.\n  Proof.\n    now apply cmp_eq.\n  Qed.\n\n  Definition compare (a b : string) : Compare lt eq a b :=\n    match cmp a b as z return _ = z -> _ with\n    | Lt => fun E => LT (compare_helper_lt E)\n    | Gt => fun E => GT (compare_helper_gt E)\n    | Eq => fun E => EQ (compare_helper_eq E)\n    end Logic.eq_refl.\n\n  Definition eq_dec (x y : string): {x = y} + { ~ (x = y)} := string_dec x y.\nEnd String_as_OT.\n", "meta": {"author": "snu-sf", "repo": "fairness", "sha": "170bd1ade88d32ac6ab661ed0c272af8a00d9ea1", "save_path": "github-repos/coq/snu-sf-fairness", "path": "github-repos/coq/snu-sf-fairness/fairness-170bd1ade88d32ac6ab661ed0c272af8a00d9ea1/src/lib/OrderedTypeEx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321936479701, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.6623820363259957}}
{"text": "(** 二項関係「<」が整礎であることの証明 *)\n(* 2015_01_08 @suharahiromichi *)\n\nRequire Import ssreflect ssrbool ssrnat eqtype seq ssrfun.\nRequire Import div prime.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* well_founded の引数は Prop である必要がある。\nコアーションが効いて (n < m) = true になる。\nだから、well_founded ltn ではだめである。 *)\nLemma well_founded_ltn : well_founded (fun n m => n < m).\nProof.\n  move=> x.\n  elim: x {1 3}x (leqnn x) => [| n IHn] x H; apply: Acc_intro.\n  - by case: x H.\n  - by move=> y H0; apply/IHn/(leq_trans H0 H).\nDefined.                                    (* Qedでも。 *)\n\n(** Prop の場合は、lt_wf として定理があるが、自分で証明してみる。 *)\nSearch well_founded.\n\nRequire Import Arith.                       (* Lt *)\n(* Coq/Arith/ の定理を使っている。 *)\n\nLemma well_founded_lt : well_founded lt.\nProof.\n  move=> x.\n  elim: x {1 3}x (le_refl x) => [| n IHn] x H; apply: Acc_intro.\n  - case: x H => [|x] H1 x' H2.\n    + by inversion H2.\n    + exfalso.\n      apply le_not_lt in H1.\n      apply H1.\n      by apply lt_0_Sn.\n  - move=> y H0.\n    apply IHn.\n    apply lt_n_Sm_le.\n    by apply (lt_le_trans y x n.+1 H0 H).\nDefined.                                    (* Qedでも。 *)\n\n(* 整礎帰納法の使い方の例 *)\nGoal forall c : nat, c ^ 2 >= 0.\nProof.\n  move=> c.\n  move: c (well_founded_ltn c).\n  refine (Acc_ind _ _) => c.\n  case: c.\n    (* \n   (forall y : nat, y < 0 -> Acc (fun n m : nat => n < m) y) ->\n   (forall y : nat, y < 0 -> 0 <= y ^ 2) -> 0 <= 0 ^ 2\n     *)\n  by [].\n    (* \n   forall n : nat,\n   (forall y : nat, y < n.+1 -> Acc (fun n0 m : nat => n0 < m) y) ->\n   (forall y : nat, y < n.+1 -> 0 <= y ^ 2) -> 0 <= n.+1 ^ 2\n     *)\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/ssr/ssr_well_founded.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6623820340806917}}
{"text": "(*\n  Copyright 2022 ZhengPu Shi\n  This file is part of CoqMatrix. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : Vector Theory implemented with NatFun\n  author    : ZhengPu Shi\n  date      : 2021.12\n*)\n\n\nRequire Export VectorTheory.\nRequire Import NatFun.MatrixTheoryNF.\n\n\n(* ######################################################################### *)\n(** * Basic vector theory implemented with NatFun *)\n\nModule BasicVectorTheoryNF (E : ElementType).\n\n  (* ==================================== *)\n  (** ** Also contain matrix theory *)\n  Module Export BasicMatrixTheoryNF := BasicMatrixTheoryNF E.\n\n  (* ==================================== *)\n  (** ** Vector element type *)\n  Export E.\n\n  Infix \"==\" := (eqlistA Aeq) : list_scope.\n\n  Open Scope nat_scope.\n  Open Scope A_scope.\n  Open Scope vec_scope.\n  \n  (* ==================================== *)\n  (** ** Vector type *)\n  \n  Definition vec n := mat n 1.\n\n  (** matrix equality *)\n  Definition veq {n} (v1 v2 : vec n) := @meq n 1 v1 v2.\n  Infix \"==\" := veq : vec_scope.\n\n  (** meq is equivalence relation *)\n  Lemma veq_equiv : forall n, Equivalence (veq (n:=n)).\n  Proof.\n    intros. unfold veq. unfold meq.\n    (* apply meq_equiv. *)\n    (* Qed. *)\n    (* Tips: a bit different to other models. *)\n  Admitted.\n\n  (** Get element of vector *)\n  Definition vnth {n} (v : vec n) i : A := @mnth n 1 v i 0.\n  Notation \"v ! i\" := (vnth v i) : vec_scope.\n\n  (** veq and mnth should satisfy this constraint *)\n  Lemma veq_iff_vnth : forall {n : nat} (v1 v2 : vec n),\n      (v1 == v2) <-> (forall i, i < n -> (vnth v1 i == vnth v2 i)%A).\n  Proof.\n    intros.\n  Admitted.\n  \n\n  (* ==================================== *)\n  (** ** Convert between list and vector *)\n  Definition v2l {n} (v : vec n) : list A := @Matrix.mcol _ n 1 0 v.\n  Definition l2v {n} (l : list A) : vec n := l2m (row2col l).\n  \n  Lemma v2l_length : forall {n} (v : vec n), length (v2l v) = n.\n  Admitted.\n  \n  Lemma v2l_l2v_id : forall {n} (l : list A),\n    length l = n -> (@v2l n (@l2v n l) == l)%list.\n  Admitted.\n\n  Lemma l2v_v2l_id : forall {n} (v : vec n), l2v (v2l v) == v.\n  Admitted.\n  \n  (* ==================================== *)\n  (** ** Convert between tuples and vector *)\n  Definition t2v_2 (t : @T2 A) : vec 2 :=\n    let '(a,b) := t in l2m [[a];[b]].\n  Definition t2v_3 (t : @T3 A) : vec 3 :=\n    let '(a,b,c) := t in l2m [[a];[b];[c]].\n  Definition t2v_4 (t : @T4 A) : vec 4 :=\n    let '(a,b,c,d) := t in l2m [[a];[b];[c];[d]].\n\n  Definition v2t_2 (v : vec 2) : @T2 A := (v!0, v!1).\n  Definition v2t_3 (v : vec 3) : @T3 A := (v!0, v!1, v!2).\n  Definition v2t_4 (v : vec 4) : @T4 A := (v!0, v!1, v!2, v!3).\n  \n  Lemma v2t_t2v_id_2 : forall (t : A * A), v2t_2 (t2v_2 t) = t.\n  Proof.\n    intros. destruct t. simpl. unfold v2t_2. f_equal.\n  Qed.\n  \n  Lemma t2v_v2t_id_2 : forall (v : vec 2), t2v_2 (v2t_2 v) == v.\n  Proof.\n    intros. apply veq_iff_vnth. intros i Hi. simpl.\n    repeat (try destruct i; auto; try lia); easy.\n  Qed.\n  \n  (** mapping of a vector *)\n  Definition vmap {n} (v : vec n) f : vec n := mmap f v.\n  \n  (** folding of a vector *)\n(*   Definition vfold : forall {B : Type} {n} (v : vec n) (f : A -> B) (b : B), B. *)\n  \n  (** mapping of two matrices *)\n  Definition vmap2 {n} (v1 v2 : vec n) f : vec n := mmap2 f v1 v2.\n  \nEnd BasicVectorTheoryNF.\n\n\n(* ######################################################################### *)\n(** * Ring vector theory implemented with NatFun *)\n\n(** zero vector, vector addition, opposition, substraction, scalar multiplication,\n    dot product *)\nModule RingVectorTheoryNF (E : RingElementType) <: RingVectorTheory E.\n\n  (* ==================================== *)\n  (** ** Also contain matrix theory *)\n  Module Export RingMatrixTheoryNF := RingMatrixTheoryNF E.\n\n  Export E.\n  Include (BasicVectorTheoryNF E).\n\n  (** ** Zero vector *)\n  Definition vec0 {n} : vec n := mat0 n 1.\n\n  (* (** Assert that a vector is an zero vector. *) *)\n  (* Definition vzero {n} (v : vec n) : Prop := v = vec0. *)\n\n  (* (** Assert that a vector is an non-zero vector. *) *)\n  (* Definition vnonzero {n} (v : vec n) : Prop := ~(vzero v). *)\n  \n  (* (** vec0 is equal to mat0 with column 1 *) *)\n  (* Lemma vec0_eq_mat0 : forall n, vec0 = mat0 n 1. *)\n  (* Proof. *)\n  (*   intros. easy. *)\n  (* Qed. *)\n\n  (* (** It is decidable that if a vector is zero vector. *) *)\n  (* Lemma vzero_dec : forall {n} (v : vec n), {vzero v} + {vnonzero v}. *)\n  (* Proof. *)\n  (*   intros. apply meq_dec. *)\n  (* Qed. *)\n  \n  \n  (** *** Vector addition *)\n\n  Definition vadd {n} (v1 v2 : vec n) : vec n := @madd n 1 v1 v2.\n  Infix \"+\" := vadd.\n\n  (** v1 + v2 = v2 + v1 *)\n  Lemma vadd_comm : forall {n} (v1 v2 : vec n), (v1 + v2) == (v2 + v1).\n  Proof.\n    intros. apply (@madd_comm n 1).\n  Qed.\n\n  (** (v1 + v2) + v3 = v1 + (v2 + v3) *)\n  Lemma vadd_assoc : forall {n} (v1 v2 v3 : vec n), (v1 + v2) + v3 == v1 + (v2 + v3).\n  Proof.\n    intros. apply (@madd_assoc n 1).\n  Qed.\n\n  (** vec0 + v = v *)\n  Lemma vadd_0_l : forall {n} (v : vec n), vec0 + v == v.\n  Proof.\n    intros. apply (@madd_0_l n 1).\n  Qed.\n\n  (** v + vec0 = v *)\n  Lemma vadd_0_r : forall {n} (v : vec n), v + vec0 == v.\n  Proof.\n    intros. apply (@madd_0_r n 1).\n  Qed.\n\n  \n  (** *** Vector opposite *)\n  \n  Definition vopp {n} (v : vec n) : vec n := @mopp n 1 v.\n  Notation \"- v\" := (vopp v).\n\n  (** v + (- v) = vec0 *)\n  Lemma vadd_opp_r : forall {n} (v : vec n), v + (- v) == vec0.\n  Proof.\n    intros. apply (@madd_opp n 1).\n  Qed.\n  \n  (** (- v) + v = vec0 *)\n  Lemma vadd_opp_l : forall {n} (v : vec n), (- v) + v == vec0.\n  Proof.\n    intros. rewrite vadd_comm. apply (@madd_opp n 1).\n  Qed.\n  \n\n  (** *** Vector subtraction *)\n\n  Definition vsub {n} (v1 v2 : vec n) : vec n := v1 + (- v2).\n  Infix \"-\" := vsub.\n\n\n  (** *** Vector scalar multiplication *)\n\n  Definition vcmul {n} a (v : vec n) : vec n := @mcmul n 1 a v.\n  Definition vmulc {n} (v : vec n) a : vec n := @mmulc n 1 v a.\n  Infix \"c*\" := vcmul.\n  Infix \"*c\" := vmulc.\n\n  (** v *c a = a c* v *)\n  Lemma vmulc_eq_vcmul : forall {n} a (v : vec n), (v *c a) == (a c* v).\n  Proof.\n    intros. apply (@mmulc_eq_mcmul n 1).\n  Qed.\n\n  (** a c* (b c* v) = (a * b) c* v *)\n  Lemma vcmul_assoc : forall {n} a b (v : vec n), a c* (b c* v) == (a * b) c* v.\n  Proof.\n    intros. apply (@mcmul_assoc n 1).\n  Qed.\n\n  (** a c* (b c* v) = b c* (a c* v) *)\n  Lemma vcmul_perm : forall {n} a b (v : vec n), a c* (b c* v) == b c* (a c* v).\n  Proof.\n    intros. apply (@mcmul_perm n 1).\n  Qed.\n\n  (** (a + b) c* v = (a c* v) + (b c* v) *)\n  Lemma vcmul_add_distr_l : forall {n} a b (v : vec n), \n    (a + b)%A c* v == (a c* v) + (b c* v).\n  Proof.\n    intros. apply (@mcmul_add_distr_r n 1).\n  Qed.\n\n  (** a c* (v1 + v2) = (a c* v1) + (a c* v2) *)\n  Lemma vcmul_add_distr_r : forall {n} a (v1 v2 : vec n), \n    a c* (v1 + v2) == (a c* v1) + (a c* v2).\n  Proof.\n    intros. unfold vadd. apply (@mcmul_add_distr_l n 1).\n  Qed.\n\n  (** 1 c* v = v *)\n  Lemma vcmul_1_l : forall {n} (v : vec n), A1 c* v == v.\n  Proof.\n    intros. apply (@mcmul_1_l n 1).\n  Qed.\n\n  (** 0 c* v = vec0 *)\n  Lemma vcmul_0_l : forall {n} (v : vec n), A0 c* v == vec0.\n  Proof.\n    intros. apply (@mcmul_0_l n 1).\n  Qed.\n  \n  \n  (** *** Vector dot product *)\n  \n  (** dot production of two vectors.\n      Here, we use matrix multiplication to do it, and it is a different way to \n      general situation. *)\n\nDefinition vdot {n : nat} (v1 v2 : vec n) :=\n    scalar_of_mat (@mmul 1 n 1 (@mtrans n 1 v1) v2)%mat.\n  \nEnd RingVectorTheoryNF.\n\n\n(* ######################################################################### *)\n(** * Decidable-field vector theory implemented with NatFun  *)\n\nModule DecidableFieldVectorTheoryNF (E : DecidableFieldElementType)\n<: DecidableFieldVectorTheory E.\n\n  (* ==================================== *)\n  (** ** Also contain matrix theory *)\n  Module Export DecidableFieldMatrixTheoryNF := DecidableFieldMatrixTheoryNF E.\n\n  Export E.\n  Include (RingVectorTheoryNF E).\n\n  (** veq is decidable *)\n  Lemma veq_dec : forall (n : nat), Decidable (veq (n:=n)).\n  Proof. intros. apply (@meq_dec n 1). Qed.\n\nEnd DecidableFieldVectorTheoryNF.\n\n\n(* ######################################################################### *)\n(** * Test  *)\nModule Test.\n\n  Module Import VectorR := RingVectorTheoryNF RingElementTypeR.\n  Import Reals.\n  Open Scope R.\n  \n  Definition v1 := @l2v 3 [1;2;3].\n  Definition v2 := @l2v 3 [4;5;6].\n  Example vdot_ex1 : vdot v1 v2 = (4+10+18)%R.\n  Proof.\n    compute. ring.\n  Qed.\n  \nEnd Test.\n\n  \n(** ** Others, later ... *)\n(* \n\n  Lemma vec_eq_vcmul_imply_coef_neq0 : forall {n} (v1 v2 : V n) k,\n    vnonzero v1 -> vnonzero v2 -> v1 = k c* v2 -> k <> X0.\n  Proof.\n    intros. intro. subst. rewrite vcmul_0_l in H. destruct H. easy.\n  Qed.\n  \n  (* ==================================== *)\n  (** ** 2-dim vector operations *)\n\n  Definition vlen2 (v : V 2) : X :=\n    let '(x,y) := v2t_2 v in\n      (x * x + y * y)%X.\n  \n  (* ==================================== *)\n  (** ** 3-dim vector operations *)\n\n  Definition vlen3 (v : V 3) : X :=\n    let '(x,y,z) := v2t_3 v in\n      (x * x + y * y + z * z)%X.\n      \n  Definition vdot3 (v0 v1 : V 3) : X :=\n    let '(a0,b0,c0) := v2t_3 v0 in\n    let '(a1,b1,c1) := v2t_3 v1 in\n      (a0 * a1 + b0 * b1 + c0 * c1)%X.\n\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/NatFun/VectorTheoryNF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891261650248, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.6623820293058366}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Sorted lists                                                            *\n**************************************************************************)\n\nSet Implicit Arguments.\nGeneralizable Variables A B.\nRequire Import LibTactics LibLogic LibRelation LibWf LibList\n LibOrder LibNat.\n\n\n(* ********************************************************************** *)\n(** * Permutations of lists *)\n\nSection Permutation.\nVariable A : Type.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition *)\n\n(** We could define permutation in terms of multisets,\n    but this would impose additional constraints on the\n    type of elements. So instead, we use a definition\n    in terms of permutation of two inner segment of lists,\n    taking the reflexive-transitive closure. *)\n\nInductive permut_one : list A -> list A -> Prop :=\n  | permut_one_intro : forall l1 l2 l3 l4,\n      permut_one (l1++l2++l3++l4) (l1++l3++l2++l4).\n\nHint Constructors permut_one.\n\nDefinition permut := rtclosure permut_one.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties *)\n\n(** Permutation is an equivalence *)\n\nLemma permut_refl : forall l,\n  permut l l.\nProof using. intros. apply rtclosure_refl. Qed.\n\nLemma permut_sym : forall l1 l2,\n  permut l1 l2 -> permut l2 l1.\nProof using.\n  intros. induction H.\n  apply permut_refl.\n  applys rtclosure_last. apply IHrtclosure. inverts~ H.\nQed.\n\nLemma permut_trans : forall l2 l1 l3,\n  permut l1 l2 -> permut l2 l3 -> permut l1 l3.\nProof using. intros. apply* rtclosure_trans. Qed.\n\n(** Permutation is a congruence with respect to [++] and [::] *)\n\nLemma permut_flip : forall l1 l2,\n  permut (l1++l2) (l2++l1).\nProof using.\n  intros. lets: (permut_one_intro nil l1 l2 nil).\n  rew_app in *. apply~ rtclosure_once.\nQed.\n\nLemma permut_app_l : forall l1 l1' l2,\n  permut l1 l1' ->\n  permut (l1 ++ l2) (l1' ++ l2).\nProof using.\n  introv H. gen l2. induction H; intros.\n  apply permut_refl.\n  specializes IHrtclosure l2. inverts H.\n   rew_app in *. eapply permut_trans.\n   applys* rtclosure_step. apply permut_refl.\nQed.\n\nLemma permut_app_r : forall l1 l2 l2',\n  permut l2 l2' ->\n  permut (l1 ++ l2) (l1 ++ l2').\nProof using.\n  introv H. gen l1. induction H; intros.\n  apply permut_refl.\n  specializes IHrtclosure l1. inverts H.\n   rewrite <- app_assoc in *. eapply permut_trans.\n   applys* rtclosure_step. apply permut_refl.\nQed.\n\nLemma permut_app_lr : forall l1 l1' l2 l2',\n  permut l1 l1' -> permut l2 l2' ->\n  permut (l1 ++ l2) (l1' ++ l2').\nProof using.\n  intros. applys rtclosure_trans.\n  sapply* permut_app_l.\n  apply* permut_app_r.\nQed.\n\nLemma permut_cons : forall x l1 l1',\n  permut l1 l1' ->\n  permut (x::l1) (x::l1').\nProof using.\n  intros. lets: (@permut_app_r (x::nil) _ _ H).\n  rew_app in *. auto.\nQed.\n\n(** Permutation are stable through list reversal *)\n\nLemma permut_rev : forall l,\n  permut l (rev l).\nProof using.\n  induction l. apply permut_refl. rew_rev.\n  lets: (@permut_flip (a::nil) (rev l)). rew_app in *.\n  apply~ (@permut_trans (a::rev l)). apply~ permut_cons.\nQed.\n\n(** Properties of elements are preserved by permutation *)\n\nLemma Forall_permut_one : forall (P:A->Prop) l1 l2,\n  Forall P l1 -> permut_one l1 l2 -> Forall P l2.\nProof using.\n  introv F Per. inverts Per.\n  lets F0 F345: (Forall_app_inv _ _ F).\n  lets F3 F45: (Forall_app_inv _ _ F345).\n  lets F4 F5: (Forall_app_inv _ _ F45).\n  apply~ Forall_app. apply~ Forall_app. apply~ Forall_app.\nQed.\n\nLemma Forall_permut : forall (P:A->Prop) l1 l2,\n  Forall P l1 -> permut l1 l2 -> Forall P l2.\nProof using.\n  introv F1 Per. gen F1. induction Per.\n  auto.\n  autos* Forall_permut_one.\nQed.\n\nEnd Permutation.\n\nHint Resolve permut_refl permut_flip\n             permut_app_lr permut_cons.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Permutation tactic *)\n\nSection PermutationTactic.\nVariable A : Type.\nImplicit Types l : list A.\n\nLemma permut_get_1 : forall l1 l2,\n  permut (l1 ++ l2) (l1 ++ l2).\nProof using. intros. apply permut_refl. Qed.\nLemma permut_get_2 : forall l1 l2 l3,\n  permut (l1 ++ l2 ++ l3) (l2 ++ l1 ++ l3).\nProof using.\n  intros. apply rtclosure_once.\n  applys (@permut_one_intro _ nil l1 l2 l3).\nQed.\nLemma permut_get_3 : forall l1 l2 l3 l4,\n  permut (l1 ++ l2 ++ l3 ++ l4) (l2 ++ l3 ++ l1 ++ l4).\nProof using.\n  intros. do 2 rewrite <- (@app_assoc _ l2).\n  apply permut_get_2.\nQed.\nLemma permut_get_4 : forall l1 l2 l3 l4 l5,\n  permut (l1 ++ l2 ++ l3 ++ l4 ++ l5)\n         (l2 ++ l3 ++ l4 ++ l1 ++ l5).\nProof using.\n  intros. do 2 rewrite <- (@app_assoc _ l2).\n  apply permut_get_3.\nQed.\nLemma permut_get_5 : forall l1 l2 l3 l4 l5 l6,\n  permut (l1 ++ l2 ++ l3 ++ l4 ++ l5 ++ l6)\n         (l2 ++ l3 ++ l4 ++ l5 ++ l1 ++ l6).\nProof using.\n  intros. do 2 rewrite <- (@app_assoc _ l2).\n  apply permut_get_4.\nQed.\nLemma permut_get_6 : forall l1 l2 l3 l4 l5 l6 l7,\n  permut (l1 ++ l2 ++ l3 ++ l4 ++ l5 ++ l6 ++ l7)\n         (l2 ++ l3 ++ l4 ++ l5 ++ l6 ++ l1 ++ l7).\nProof using.\n  intros. do 2 rewrite <- (@app_assoc _ l2).\n  apply permut_get_5.\nQed.\n\nLemma permut_tactic_setup : forall l1 l2,\n  permut (nil ++ l1 ++ nil) (l2 ++ nil) -> permut l1 l2.\nProof using. intros. rew_list~ in H. Qed.\n\nLemma permut_tactic_keep : forall l1 l2 l3 l4,\n  permut ((l1 ++ l2) ++ l3) l4 ->\n  permut (l1 ++ (l2 ++ l3)) l4.\nProof using. intros. rew_list~ in H. Qed.\n\nLemma permut_tactic_simpl : forall l1 l2 l3 l4,\n  permut (l1 ++ l3) l4 ->\n  permut (l1 ++ (l2 ++ l3)) (l2 ++ l4).\nProof using.\n  intros. eapply permut_trans.\n  apply permut_get_2. apply~ permut_app_r.\nQed.\n\nLemma permut_tactic_trans : forall l1 l2 l3,\n  permut l3 l2 -> permut l1 l3 -> permut l1 l2.\nProof using. introv P1 P2. apply~ (permut_trans P2 P1). Qed.\n\nEnd PermutationTactic.\n\n\n(** [permut_prepare] applies to a goal of the form [permut l l']\n    and sets [l] and [l'] in the form [l1 ++ l2 ++ .. ++ nil],\n    (some of the lists [li] are put in the form [x::nil]). *)\n(* todo: improve so as to ensure no rewrite inside elements *)\n\nHint Rewrite app_assoc app_nil_l app_nil_r : permut_rew.\n\nLtac permut_lemma_get n :=\n  match nat_from_number n with\n  | 1 => constr:(permut_get_1)\n  | 2 => constr:(permut_get_2)\n  | 3 => constr:(permut_get_3)\n  | 4 => constr:(permut_get_4)\n  | 5 => constr:(permut_get_5)\n  end.\n\nLtac permut_isolate_cons :=\n  do 20 try (* todo : repeat *)\n    match goal with |- context [?x::?l] =>\n      match l with\n      | nil => fail 1\n      | _ => rewrite <- (@app_cons_one _ x l)\n      end\n    end.\n\nLtac permut_simpl_prepare :=\n   autorewrite with permut_rew;\n   permut_isolate_cons;\n   autorewrite with permut_rew;\n   apply permut_tactic_setup;\n   repeat rewrite app_assoc.\n\n\n(** [permut_simplify] simplifies a goal of the form\n    [permut l l'] where [l] and [l'] are lists built with\n    concatenation and consing, by cancelling syntactically\n    equal elements *)\n\nLtac permut_index_of l lcontainer :=\n  match constr:(lcontainer) with\n  | l ++ _ => constr:(1)\n  | _ ++ l ++ _ => constr:(2)\n  | _ ++ _ ++ l ++ _ => constr:(3)\n  | _ ++ _ ++ _ ++ l ++ _ => constr:(4)\n  | _ ++ _ ++ _ ++ _ ++ l ++ _ => constr:(5)\n  | _ ++ _ ++ _ ++ _ ++ _ ++ l ++ _ => constr:(6)\n  | _ => constr:(0) (* not found *)\n  end.\n\nLtac permut_simpl_once :=\n  match goal with\n  | |- permut (_ ++ nil) _ => fail 1\n  | |- permut (_ ++ (?l ++ _)) ?l' =>\n     match permut_index_of l l' with\n     | 0 => apply permut_tactic_keep\n     | ?n => let F := permut_lemma_get n in\n            eapply permut_tactic_trans;\n            [ apply F\n            | apply permut_tactic_simpl ]\n     end\n  end.\n\nLtac permut_simpl :=\n  permut_simpl_prepare;\n  repeat permut_simpl_once;\n  autorewrite with permut_rew;\n  try apply permut_refl.\n\n(* todo: permut rewrite *)\n\n\n(* ********************************************************************** *)\n(** * Sorted lists *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition *)\n\nSection Sorted.\nVariable A : Type.\nImplicit Types le : binary A.\n\nInductive sorted le : list A -> Prop :=\n  | sorted_nil : sorted le nil\n  | sorted_one : forall x, sorted le (x::nil)\n  | sorted_two : forall x y l,\n     sorted le (y::l) -> le x y ->\n     sorted le (x::y::l).\n\nDefinition rsorted le := sorted (flip le).\n\nDefinition head_of_le le x l :=\n  match l with\n  | nil => True\n  | h::_ => le x h\n  end.\n\nDefinition head_le le l1 l2 :=\n  match l1,l2 with\n  | _,nil => True\n  | nil,_ => True\n  | h1::_,h2::_ => le h1 h2\n  end.\n\nEnd Sorted.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties about sorted *)\n\nImplicit Arguments sorted [A].\nHint Unfold rsorted.\n\nSection SortedProperties.\nHint Constructors sorted.\n\nVariables (A : Type).\nVariable le : binary A.\nHint Resolve sorted_nil sorted_one.\n\nLemma sorted_inv : forall x l,\n  sorted le (x::l) -> head_of_le le x l /\\ sorted le l.\nProof using. introv H. inverts H; simpls~. Qed.\n\nLemma sorted_sub : forall x l,\n  sorted le (x::l) -> sorted le l.\nProof using. introv H. inverts~ H. Qed.\n\nLemma sorted_cons : forall l,\n  sorted le l -> forall x,\n  head_of_le le x l -> sorted le (x::l).\nProof using. introv S Hd. inverts~ S. Qed.\n\nLemma head_le_from_sorted : forall x l1 l2,\n  sorted le (x::l2) ->\n  head_le le l1 (x::l2) ->\n  head_le le (x::l1) l2.\nProof using.\n  intros. destruct l2; simpl. auto. inverts~ H.\nQed.\n\nLemma sorted_cons_head_of : forall x l,\n  sorted le (x::l) -> head_of_le le x l.\nProof using. introv H. inverts H; simpls~. Qed.\n\nLemma head_le_nil_l : forall l,\n  head_le le nil l.\nProof using. intros. unfolds. destruct~ l. Qed.\n\nLemma head_le_nil_r : forall l,\n  head_le le l nil.\nProof using. intros. unfolds. destruct~ l. Qed.\n\nLemma sorted_cons_head : forall l1 l2 x,\n  head_le le (x::l1) l2 ->\n  sorted le l2 ->\n  sorted le (x::l2).\nProof using. introv H S2. destruct l2. auto. apply~ sorted_cons. Qed.\n\nLemma head_le_flip : forall l1 l2,\n  head_le (flip le) l1 l2 = head_le le l2 l1.\nProof using. destruct l1; destruct l2; auto. Qed.\n\nLemma head_le_flip_1 : forall l1 l2,\n  head_le (flip le) l1 l2 -> head_le le l2 l1.\nProof using. intros. rewrite~ <- head_le_flip. Qed.\n\nLemma head_le_flip_2 : forall l1 l2,\n  head_le le l2 l1 -> head_le (flip le) l1 l2.\nProof using. intros. rewrite~ head_le_flip. Qed.\n\nLemma sorted_Forall_le : forall x l,\n  total_preorder le ->\n  head_of_le le x l -> sorted le l -> Forall (le x) l.\nProof using.\n  induction l; simpl; introv Tot LeH Sl. auto. constructor~.\n  lets: (sorted_sub Sl). constructor~. apply~ IHl.\n  destruct~ l; simpls~. inverts Sl. sapply* total_preorder_trans.\nQed.\n\nLemma head_of_le_Forall_le : forall x l,\n  Forall (le x) l -> head_of_le le x l.\nProof using. introv H. destruct l; simpls. auto. inverts~ H. Qed.\n\nLemma sorted_flip_flip : forall l,\n  sorted le l ->\n  sorted (flip (flip le)) l.\nProof using.\n  introv H. rewrite flip_flip. induction H.\n   constructor. constructor. apply~ sorted_cons.\nQed.\n\nEnd SortedProperties.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties about rsorted *)\n\nSection RSortedProperties.\nVariables (A : Type).\nVariable le : binary A.\nHint Resolve sorted_nil sorted_one.\nHint Constructors sorted.\n\nLemma rsorted_inv : forall x l,\n  rsorted le (x::l) -> head_of_le (flip le) x l /\\ rsorted le l.\nProof using. introv H. inverts H; simpls~. Qed.\n\nLemma head_le_from_rsorted : forall x l1 l2,\n  rsorted le (x::l2) ->\n  head_le (flip le) l1 (x::l2) ->\n  head_le (flip le) (x::l1) l2.\nProof using.\n  intros. destruct l2; simpl. auto. inverts~ H.\nQed.\n\nLemma rsorted_cons_head : forall l1 l2 x,\n  head_le (flip le) (x::l1) l2 ->\n  rsorted le l2 ->\n  rsorted le (x::l2).\nProof using. introv H S2. destruct~ l2. Qed.\n\nLemma sorted_app : forall l1 l2,\n  head_le le l1 l2 -> rsorted le l1 -> sorted le l2 ->\n  sorted le ((rev l1) ++ l2).\nProof using.\n  introv. gen l2. induction l1; introv Hd S1 S2; rew_rev. auto.\n  lets Hd1 S1': (rsorted_inv S1). clear S1.\n  apply IHl1. destruct~ l1. auto.\n  apply sorted_cons. auto. destruct~ l2.\nQed.\n\nEnd RSortedProperties.\n\nLemma rsorted_app : forall (A : Type) (le : binary A) l1 l2,\n  head_le le l2 l1 -> sorted le l1 -> rsorted le l2 ->\n  rsorted le ((rev l1) ++ l2).\nProof using.\n  unfold rsorted. intros. apply sorted_app.\n    rewrite~ head_le_flip.\n    unfolds. apply~ sorted_flip_flip.\n    auto.\nQed.\n\n\n(* ********************************************************************** *)\n(** * Sorting of a list *)\n\nSection Sorts.\nVariables (A : Type).\nImplicit Types le : binary A.\nHint Resolve sorted_nil sorted_one.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition *)\n\nDefinition sorts le l l' :=\n  permut l l' /\\ sorted le l'.\n\nDefinition rsorts le := sorts (flip le).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties *)\n\nLemma sorts_refl : forall le l,\n  sorted le l -> sorts le l l.\nProof using. split. apply permut_refl. auto. Qed.\n\nLemma rsorts_refl : forall le l,\n  rsorted le l -> rsorts le l l.\nProof using. intros. apply~ sorts_refl. Qed.\n\nLemma sorts_app_rev : forall le l1 l2,\n head_le le l1 l2 -> rsorted le l1 -> sorted le l2 ->\n sorts le (l1 ++ l2) (rev l1 ++ l2).\nProof using.\n  introv H S1 S2. split.\n  apply permut_app_l. apply permut_rev.\n  apply~ sorted_app.\nQed.\n\nLemma rsorts_app_rev : forall le l1 l2,\n head_le le l2 l1 -> sorted le l1 -> rsorted le l2 ->\n rsorts le (l1 ++ l2) (rev l1 ++ l2).\nProof using.\n  introv H S1 S2. split.\n  apply permut_app_l. apply permut_rev.\n  apply~ rsorted_app.\nQed.\n\nLemma sorts_permut : forall l1 l2 l' le,\n  sorts le l1 l' -> permut l2 l1 ->\n  sorts le l2 l'.\nProof using.\n  introv [P1 S1] Per. split~.\n  apply* (@permut_trans _ l1).\nQed.\n\nLemma rsorts_permut : forall l1 l2 l' le,\n  rsorts le l1 l' -> permut l2 l1 ->\n  rsorts le l2 l'.\nProof using. intros. apply~ (@sorts_permut l1). Qed.\n\nLemma sorts_cons : forall le l l' x,\n  sorts le l l' -> head_of_le le x l' ->\n  sorts le (x::l) (x::l').\nProof using.\n  introv [P S] Hd. split.\n  apply~ permut_cons. apply~ sorted_cons.\nQed.\n\nLemma sorts_2 : forall le l x1 x2,\n  permut l (x1::x2::nil) ->\n  le x1 x2 ->\n  sorts le l (x1::x2::nil).\nProof using.\n  intros. apply~ (@sorts_permut (x1::x2::nil)).\n  apply sorts_refl. apply sorted_cons.\n  apply sorted_one. simpls~.\nQed.\n\nLemma sorts_3 : forall le l x1 x2 x3,\n  permut l (x1::x2::x3::nil) ->\n  le x1 x2 -> le x2 x3 ->\n  sorts le l (x1::x2::x3::nil).\nProof using.\n  intros.\n   apply~ (@sorts_permut (x1::x2::x3::nil)).\n   apply sorts_refl. apply sorted_cons.\n   apply sorted_cons. apply sorted_one.\n   simpls~. simpls~.\nQed.\n\nLemma rsorts_2 : forall le l x1 x2,\n  permut l (x1::x2::nil) ->\n  le x2 x1 ->\n  rsorts le l (x1::x2::nil).\nProof using.\n  intros.\n   apply~ (@rsorts_permut (x1::x2::nil)).\n   apply rsorts_refl. applys sorted_cons.\n   apply sorted_one. unfold flip. simpls~.\nQed.\n\nLemma rsorts_3 : forall le l x1 x2 x3,\n  permut l (x1::x2::x3::nil) ->\n  le x2 x1 -> le x3 x2 ->\n  rsorts le l (x1::x2::x3::nil).\nProof using.\n  intros.\n   apply~ (@rsorts_permut (x1::x2::x3::nil)).\n   apply rsorts_refl. applys sorted_cons.\n   apply sorted_cons. apply sorted_one.\n   simpls~. simpls~.\nQed.\n\nLemma sorts_length_lt_2 : forall le l,\n  length l < 2 -> sorts le l l.\nProof using.\n  intros. apply sorts_refl. destruct~ l.\n  destruct~ l. rew_length in *. false. nat_math.\nQed.\n\nEnd Sorts.\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/LibListSorted.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.662382028978994}}
{"text": "(** Jamile Lima Leite **)\n\n(** * INITIATION A COQ *)\n\n(**\nLe début de ce fichier a été présenté en cours.\nIl est demandé de le réviser à la maison et de le terminer\nen préparation du TD suivant.\n- Lire attentivement les commentaires explicatifs\n- sous emacs/Proof-general,\n  - pour avancer d'une étape, faire C-c C-n\n  - pour reculer, C-c C-p\n  - pour aller d'un coup à la position du curseur, C-c RET.\n  D'autres raccourcis sont disponibles, regarder les menus Proof-General et Coq.\n*)\n\n\n(** ** Généralités *)\n\n(** Coq est primitivement un langage de programmation particulier.\n    Comme OCaml, c'est un langage fonctionnel typé.\n    Son système de types est beaucoup plus riche que celui de OCaml,\n    ce qui permet en particulier d'énoncer des formules logiques,\n    et éventuellement de les démontrer.\n\n    Dans un premier temps, on se focalise sur l'aspect programmation,\n    et les formules logiques considérées sont de simples égalités.\n *)\n\n(** Un script Coq est une suite de déclarations de types, de valeurs,\n    (très souvent : des fonctions), d'énoncés de théorèmes suivis\n    de leur preuve.\n\n    On a également des requêtes pour obtenir des informations,\n    calculer des expressions.\n*)\n\n(** À RETENIR : EN COQ, TOUT FINIT PAR UN POINT '.' *)\n\n(** ** Types énumérés *)\n\n(** Le type qui s'écrirait en OCaml\ntype coulfeu =\n  | Vert\n  | Orange\n  | Rouge\n\nse définit en Coq presque de la même façon.\n*)\n\nInductive coulfeu : Set :=\n  | Vert : coulfeu\n  | Orange : coulfeu\n  | Rouge : coulfeu\n.\n\n(** Comme en OCaml, [blabla : machin] se lit \"[blabla] a pour type [machin]\".\n    Ainsi la déclaration précédente indique que [Vert], [Orange] et [Rouge]\n    sont de type coulfeu.\n    Par ailleurs, en Coq tout a un type ; la déclaration ci-dessus indique que\n    le type de [coulfeu] est [Set], cf. notes de cours.\n*)\n\n(** ** Définition d'une valeur fonctionnelle *)\n\nDefinition coul_suiv : coulfeu -> coulfeu :=\n  fun c =>\n    match c with\n    | Vert => Orange\n    | Orange => Rouge\n    | Rouge => Vert\n    end.\n\n(** La commande Check permet d'obtenir le type d'une expression.\n    Elle vérifie que l'expression est bien typée. *)\n\nCheck coul_suiv.\nCheck (coul_suiv Vert).\n\n(** La commande Eval permet de calculer une expression. *)\n\nEval compute in (coul_suiv Vert).\n\n(** Raccourci *)\nCompute (coul_suiv Vert).\n\n(** ** Premier théorème, tactiques cbn et reflexivity *)\n\nTheorem ex1_coul_suiv : coul_suiv (coul_suiv Vert) = Rouge.\nProof. cbn [coul_suiv]. reflexivity. Qed.\n\n(** Remarque : on peut énoncer une théorème à prouver au moyen d'autres\nmots-clé, notamment Lemma (pour un résultat auxiliaure) ou Example\n(pour un théorème très simple servant à tester le résultat d'une fonction\nsur une entrée particulière.\nCes mots-clé sont équivalents, le choix de l'un ou l'autre est affaire de\nconvention ou d'usage.\nIci on aurait donc plutôt utilisé  Example.\nExample ex1_coul_suiv : coul_suiv (coul_suiv Vert) = Rouge.\n*)\n\n\n(** Une *tactique* est une commande permettant de faire progresser une preuve *)\n\n(** On a utilisé ci-dessus les tactiques suivantes :\n    - cbn [nom_de_fonction] : évaluation (partielle) de [nom_de_fonction]\n    - reflexivity : reconnaissance que les deux membres de l'égalité\n                    à prouver sont identiques (preuve de x = x).\n *)\n\n(** ATTENTION À BIEN TERMINER PAR \"Qed.\" *)\n\n(** ** Variables *)\n\n(** Les preuves par réflexivité fonctionnent non seulement\n    entre des expressions constantes identiques, mais aussi\n    entre des expressions comportant des variables. *)\n\n(** On a la possibilité en Coq (mais pas en OCaml) de déclarer\n    des variables :\n    ce sont des noms dont on connaît simplement le type.\n    Il faut que ces noms soient déclarés dans une portée\n    (domaine de visibilité) définie par une section.\n*)\n\n(** Ouverture d'une section dans laquelle on va faire quelques\n    preuves par réflexivité. *)\n\nSection sec_refl.\n  Variable c : coulfeu.\n  (** Signification intuitive : \"soit [c] une [coulfeu] inconnue\". *)\n\n  Theorem th1_refl_simple : c = c.\n  (** Remarquer que le but contient un environnement comportant\n      l'hypothèse [c : coulfeu]. *)\n  Proof. reflexivity. Qed.\n\n  Check c.\n\n(** Fermeture de la section,\n    ce qui clôt la portée des variables, ici [c : coulfeu]. *)\nEnd sec_refl.\n\nFail Check c.\nFail Definition x := Vert + 2.\n\n(* -------------------------------------------------------------------  *)\n(** Vu jusqu'ici dans ls CM1 2020, en fait juste avant le End sec_refl. *)\n(* -------------------------------------------------------------------  *)\n\n(** ** Principe de Leibniz : tactique rewrite *)\n\nSection sec_reec.\n  Variable c : coulfeu.\n  Hypothesis crou : c = Rouge.\n  (** Signification intuitive, par analogie avec la ligne d'avant :\n      \"soit [crou] une preuve inconnue de [c = Rouge]\". *)\n\n  Theorem coul_suiv_Rouge : coul_suiv c = Vert.\n  Proof.\n    rewrite crou.\n    cbn [coul_suiv].\n    reflexivity.\n  Qed.\n\nEnd sec_reec.\n\n(** ** Raisonnement par cas : tactique destruct *)\n\nSection sec_cas.\n  Variable c : coulfeu.\n\n  Theorem th3_coul_suiv : coul_suiv (coul_suiv (coul_suiv c)) = c.\n  Proof.\n    (** reflexivity ne fonctionne pas. *)\n    Fail reflexivity.\n    (** Il faut raisonner par cas sur les trois valeurs de [c] possibles *)\n    (** Cela va donner lieu à trois sous-buts, un pour chaque cas. *)\n    destruct c as [ (*Vert*) | (*Orange*) | (*Rouge*) ].\n    - cbn [coul_suiv]. reflexivity.\n    - cbn [coul_suiv]. reflexivity.\n    - cbn [coul_suiv]. reflexivity.\n  Qed.\n\nEnd sec_cas.\n\n(** ** Raisonnement universel : tactique intro *)\n\n(** Il est possible d'énoncer des formules quantifiées universellement.\n    Par exemple : [forall c : coulfeu, c = c].\n *)\n\nTheorem th_refl_gen : forall c : coulfeu, c = c.\nProof.\n  (** Pour la démontrer, la première étape consiste à dire\n      \"soit [c0] une couleur arbitraire, démontrons [c0 = c0].\" *)\n  intro c0.\n  (** Remarquer que intro a introduit l'hypothèse [c0 : coulfeu]. *)\n  (** On a déjà vu que reflexivity fonctionne dans cette situation. *)\n  reflexivity.\nQed.\n\n(** La tactique intro sert également à démontrer une implication. *)\nTheorem th_crou_gen : forall c : coulfeu, c = Rouge -> coul_suiv c = Vert.\nProof.\n  intro c0.\n  (** Pour démontrer [c0 = Rouge -> coul_suiv c0 = Vert],\n      on suppose [c0 = Rouge]\n      et on doit alors prouver [coul_suiv c0 = Vert]\n      sous cette hypothèse supplémentaire ;\n      lorsque l'on introduit une hypothèse, on lui donne un nom. *)\n  intro c0rou.\n  (** Le raisonnement sous-jacent est :\n      soit c0rou une preuve arbitraire (inconnue) de [c0 = Rouge],\n      on peut s'en servir pour démontrer coul_suiv [c0 = Vert]. *)\n  rewrite c0rou. cbn [coul_suiv]. reflexivity.\nQed.\n\n(** Remarque : on est souvent amené à effectuer plusieurs introductions\n    successives. On emploie alors le raccourci intros (au pluriel).\n    Sur l'exemple précédent cela donne ceci : *)\nTheorem th_crou_gen_bis : forall c : coulfeu, c = Rouge -> coul_suiv c = Vert.\nProof.\n  intros c0 c0rou.\n  rewrite c0rou. cbn [coul_suiv]. reflexivity.\nQed.\n\n(** * Début du travail à faire à la maison *)\n\n(** *** Exercice: Variante du précédent avec section *)\n\nSection sec_variante_th_crou_gen.\n  Variable c : coulfeu.\n  Theorem th_crou_demi_gen : c = Rouge -> coul_suiv c = Vert.\n  Proof.\n    (** à compléter *)\n    intro c0.\n    rewrite c0.\n    cbn [coul_suiv].\n    reflexivity.\n  (* Quand une démonstration est incomplète, on peut passer à la suite\n   * à l'aide de Admitted  au lieu de Qed.\n   * Ne pas oublier de remplacer Admitted par Qed quand on a réussi ! *)\n  Qed.\n\nEnd sec_variante_th_crou_gen.\n\n(** *** Exercice: Preuve par cas d'un théorème avec forall *)\n\nLemma suivsuivsuiv_id : forall c:coulfeu, coul_suiv (coul_suiv (coul_suiv c))=c.\nProof.\n  (** à compléter ici *)\n  intro c0.\n  destruct c0 as [(*Rouge*) | (*Orange*) | (*Vert*)].\n  - cbn [coul_suiv]. reflexivity.\n  - cbn [coul_suiv]. reflexivity.\n  - cbn [coul_suiv]. reflexivity.\nQed.\n\n(** ** Type inductif et récurrence structurelle : arbres binaires tricolores *)\n\nInductive arbin : Set :=\n  | F : coulfeu -> arbin\n  | N : arbin -> arbin -> arbin.\n\n(**type arbin =\n|F of coulfeu\n|N of arbin * arbin **)\n\n(**\nPour définir une fonction récursive (l'équivalent de let rec\nen OCaml) on utilise le mot clé [Fixpoint].\n *)\n\nFixpoint renva a : arbin :=\n  match a with\n  | F c => F c\n  | N g d => N (renva d) (renva g)\n  end.\n\n(** *** Exercice: prouver que renverser deux fois un arbre rend le même arbre *)\nTheorem renva_renva : forall a, renva (renva a) = a.\nProof.\n  intro a.\n  (** Tentative de raisonnement par cas sur a *)\n  (** Les noms mis dans chaque cas (c pour le premier, a2 a2 pour le second)\n      désignent les composantes des constructeurs respectivement F puis N *)\n  destruct a as [ (* F *) c\n                | (* N *) a1 a2 ].\n  - cbn [renva]. reflexivity.\n  - cbn [renva]. Fail reflexivity.\n    (** Il apparaît qu'un simple raisonnement par cas est insuffisant, *)\n    (** donc on arrete tout... *)\n Abort.\n\n(** ... et on recommence en raisonnant par récurrence structurelle *)\nTheorem renva_renva : forall a, renva (renva a) = a.\nProof.\n  intro a.\n  (** récurrence structurelle sur le type inductif arbin *)\n  (** Remarquer l'analogie avec l'utilisation de la tactique destruct :\n      les noms mis dans chaque cas (c pour le premier, a2 a2 pour le second)\n      désignent les composantes des constructeurs respectivement F puis N\n      mais en complément, on ajoute deux noms pour les hypothèses de récurrence,\n       Hrec_a1 pour celle sur a1 et Hrec_a2 pour celle sur a2 *)\n  induction a as [ (* F *) c\n                 | (* N *) a1 Hrec_a1 a2 Hrec_a2 ].\n  (** à completer ici **)\n  - cbn [renva]. reflexivity.\n  - cbn [renva]. rewrite Hrec_a1. rewrite Hrec_a2. reflexivity.\nQed.\n\n(** Fin du travail à faire à la maison. *)\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/B_A_BA/coq1_B_A_BA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.8740772384450967, "lm_q1q2_score": 0.6623708209153455}}
{"text": "Require Import Setoid.\nRequire Import IndefiniteDescription.\n\n\nLemma ex_iff_ex:\n  forall T (P Q : T -> Prop),\n    (forall x, P x <-> Q x) ->\n    ex P <-> ex Q.\nProof.\n  intuition.\n  - destruct H0 as [witness H0].\n    exists witness.\n    apply H.\n    easy.\n  - destruct H0 as [witness H0].\n    exists witness.\n    apply H.\n    easy.\nQed.\n\nLemma all_iff_all:\n  forall T (P Q : T -> Prop),\n    (forall x, P x <-> Q x) ->\n    all P <-> all Q.\nProof.\n  unfold all.\n  intros.\n  setoid_rewrite H.\n  reflexivity.\nQed.\n\nLemma forall_exists_to_exists_forall:\n  forall T U (P : T -> U -> Prop),\n    (forall (x:T), exists (y:U), P x y) <->\n    (exists (f : T -> U), forall (x:T), P x (f x)).\nProof.\n  intuition.\n  - apply functional_choice.\n    easy.\n  - destruct H as [f H].\n    exists (f x).\n    easy.\nQed.\n", "meta": {"author": "Calvin-L", "repo": "snf", "sha": "fc711b00ea8a509a1cdbfe207b0cafc376d5850d", "save_path": "github-repos/coq/Calvin-L-snf", "path": "github-repos/coq/Calvin-L-snf/snf-fc711b00ea8a509a1cdbfe207b0cafc376d5850d/src/MiscFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6623708138387151}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(**********************************************************************\n    Pepin.v\n\n    Pepin's Test for Fermat Number\n\n    Definition: PepinTest\n  **********************************************************************)\nRequire Import ZArith.\nRequire Import ZCAux.\nRequire Import Pocklington.\n\nOpen Scope Z_scope.\n\nDefinition FermatNumber n := 2^(2^(Z_of_nat n)) + 1.\n\nTheorem Fermat_pos: forall n, 1 < FermatNumber n.\n  unfold FermatNumber; intros n.\n  solve [ auto with zarith (* 8.14 *) |\n          (apply Z.le_lt_trans with (2 ^ 2 ^(Z_of_nat n)); auto with zarith;\n          rewrite <- (Zpower_0_r 2); auto with zarith;\n          apply Zpower_le_monotone; try split; auto with zarith)].\nQed.\n\nTheorem PepinTest: forall n, let Fn := FermatNumber n in (3 ^ ((Fn - 1) / 2) + 1) mod Fn = 0 -> prime Fn.\nintros n Fn H.\nassert (Hn: 1 < Fn).\nunfold Fn; apply Fermat_pos.\napply PocklingtonCorollary1 with (F1 := 2^(2^(Z_of_nat n))) (R1 := 1). 2: auto with zarith.\n2: unfold Fn, FermatNumber; auto with zarith.\napply Z.lt_le_trans with (2 ^ 1).\nrewrite Zpower_1_r; auto with zarith.\napply Zpower_le_monotone. 2: split. 1-2: auto with zarith.\nrewrite <- (Zpower_0_r 2); apply Zpower_le_monotone; try split; auto with zarith.\nunfold Fn, FermatNumber.\nassert (H1: 2 <= 2 ^ 2 ^ Z_of_nat n).\npattern 2 at 1; rewrite <- (Zpower_1_r 2) by auto with zarith.\napply Zpower_le_monotone; split. auto with zarith.\nrewrite <- (Zpower_0_r 2); apply Zpower_le_monotone; try split; auto with zarith.\napply Z.lt_le_trans with  (2 * 2 ^2 ^Z_of_nat n).\nassert (tmp: forall p, 2 * p = p + p); auto with zarith.\napply Zmult_le_compat_r; auto with zarith.\nassert (Hd: (2 | Fn - 1)).\nexists (2 ^ (2^(Z_of_nat n) - 1)).\npattern 2 at 3; rewrite <- (Zpower_1_r 2).\nrewrite <- Zpower_exp. 3: auto with zarith.\nassert (tmp: forall p, p = (p - 1) +1) by auto with zarith; rewrite <- tmp.\nunfold Fn, FermatNumber; ring.\nassert (0 < 2 ^ Z_of_nat n); auto with zarith.\nintros p Hp Hp1; exists 3; split. auto with zarith. split.\nrewrite (Zdivide_Zdiv_eq  2 (Fn -1)) by auto with zarith.\nrewrite Zmult_comm. rewrite Zpower_mult. 3: auto with zarith.\nrewrite Zpower_mod by auto with zarith.\nassert (tmp: forall p, p = (p + 1) -1) by auto with zarith; rewrite (fun x => (tmp (3 ^ x))).\nrewrite Zminus_mod by auto with zarith.\nrewrite H.\nrewrite (Zmod_small 1) by auto with zarith.\nrewrite <- Zpower_mod by auto with zarith.\nrewrite Zmod_small. auto with zarith.\nsimpl; unfold Zpower_pos; simpl; auto with zarith.\napply Z_div_pos; auto with zarith.\napply Zis_gcd_gcd. auto with zarith.\napply Zis_gcd_intro. 1-2: auto with zarith.\nintros x HD1 HD2.\nassert (Hd1: p = 2).\napply prime_div_Zpower_prime with (4 := Hp1). 1-2: auto with zarith.\napply prime_2.\nassert (Hd2: (x | 2)).\nreplace 2 with ((3 ^ ((Fn - 1) / 2) + 1) - (3 ^ ((Fn - 1) / 2) - 1)) by auto with zarith.\napply Zdivide_minus_l; auto.\napply Z.divide_trans with (1 := HD2).\napply Zmod_divide; auto with zarith.\nrewrite <- Hd1; auto.\nreplace 1 with (Fn - (Fn - 1)) by auto with zarith.\napply Zdivide_minus_l; auto.\napply Z.divide_trans with (1 := Hd2); auto.\nQed.\n\n(* An optimized version with Zpow_mod *)\n\nDefinition pepin_test n :=\n  let Fn := FermatNumber n in if  Z.eq_dec (Zpow_mod 3  ((Fn - 1) / 2) Fn)  (Fn - 1) then true else false.\n\nTheorem PepinTestOp: forall n, pepin_test n = true -> prime (FermatNumber n).\nintros n; unfold pepin_test.\nmatch goal with |- context[if ?X then _ else _] => case X end; try (intros; discriminate).\nintros H1 _; apply PepinTest.\ngeneralize (Fermat_pos n); intros H2.\nrewrite Zplus_mod; auto with zarith.\nrewrite <- Zpow_mod_Zpower_correct; auto with zarith.\nrewrite H1.\nrewrite (Zmod_small 1); auto with zarith.\nreplace (FermatNumber n - 1 + 1) with (FermatNumber n); auto with zarith.\napply Zdivide_mod; auto with zarith.\napply Z_div_pos; auto with zarith.\nQed.\n\nTheorem prime5: prime 5.\nexact (PepinTestOp 1 (refl_equal _)).\nQed.\n\nTheorem prime17: prime 17.\nexact (PepinTestOp 2 (refl_equal _)).\nQed.\n\nTheorem prime257:  prime 257.\nexact (PepinTestOp 3 (refl_equal _)).\nQed.\n\nTheorem prime65537:  prime 65537.\nexact (PepinTestOp 4 (refl_equal _)).\nQed.\n\n(* Too tough !!\nTheorem prime4294967297:  prime 4294967297.\nrefine (PepinTestOp 5 (refl_equal _)).\nQed.\n*)\n", "meta": {"author": "thery", "repo": "coqprime", "sha": "431d7a66877cbe8688fc8864ef892369401440e1", "save_path": "github-repos/coq/thery-coqprime", "path": "github-repos/coq/thery-coqprime/coqprime-431d7a66877cbe8688fc8864ef892369401440e1/src/Coqprime/PrimalityTest/Pepin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6623708063814979}}
{"text": "(************************************************************************)\n(* Copyright (c) 2010, Martijn Vermaat <martijn@vermaat.name>           *)\n(*                     Dimitri Hendriks <diem@cs.vu.nl>                 *)\n(*                                                                      *)\n(* Licensed under the MIT license, see the LICENSE file or              *)\n(* http://en.wikipedia.org/wiki/Mit_license                             *)\n(************************************************************************)\n\n\n(** This library defines two equalities on infinite terms:\n    - Bisimilarity by [term_bis]\n    - Pointwise equality by [term_eq]\n\n    These two relations are proved to be the same and to be equivalences.\n\n    In the last section, a third equality via positions is introduced,\n    but it is not yet proven equal to the first two. *)\n\n\nRequire Import Signature.\nRequire Import Variables.\nRequire Import Term.\nRequire Import Equality.\n\n\nSet Implicit Arguments.\n\n\nSection TermEquality.\n\nVariable F : signature.\nVariable X : variables.\n\nNotation term := (term F X).\nNotation terms := (vector term).\n\n(** Bisimilarity on terms. *)\nCoInductive term_bis : term -> term -> Prop :=\n  | Var_bis : forall x, term_bis (Var x) (Var x)\n  | Fun_bis : forall f v w,\n              (forall i, term_bis (v i) (w i)) ->\n              term_bis (Fun f v) (Fun f w).\n\n(** Equality of infinite terms up to a given depth. *)\nInductive term_eq_up_to : nat -> term -> term -> Prop :=\n  | teut_0   : forall t u, term_eq_up_to 0 t u\n  | teut_var : forall d x, term_eq_up_to d (Var x) (Var x)\n  | teut_fun : forall d f v w,\n               (forall i, term_eq_up_to d (v i) (w i)) ->\n               term_eq_up_to (S d) (Fun f v) (Fun f w).\n\n(** Pointwise equality by generalising equality up to a given depth. *)\nDefinition term_eq (t u : term) :=\n  forall d, term_eq_up_to d t u.\n\n(** Some inversion lemmas on pointwise equality. *)\n\nLemma teut_fun_inv :\n  forall d f v w,\n  term_eq_up_to (S d) (Fun f v) (Fun f w) ->\n  forall i, term_eq_up_to d (v i) (w i).\nProof.\nintros d f v w H.\ndependent destruction H.\nassumption.\nQed.\n\nLemma term_eq_fun_inv :\n  forall f v w,\n  term_eq (Fun f v) (Fun f w) ->\n  forall i, term_eq (v i) (w i).\nProof.\nintros f v w H i n.\napply teut_fun_inv with (1 := H (S n)).\nQed.\n\nLemma term_eq_fun_inv_symbol :\n  forall (f g : F) (v : terms (arity f)) (w : terms (arity g)),\n  term_eq (Fun f v) (Fun g w) -> f = g.\nProof.\nintros f g v w H.\nassert (H0 := H 1).\ninversion_clear H0; simpl.\nreflexivity.\nQed.\n\n(** We now prove that bisimilarity is the same as pointwise equality. *)\n\n(** Bisimilarity implies pointwise equality. *)\nLemma term_bis_implies_term_eq :\n  forall (t u : term), term_bis t u -> term_eq t u.\nProof.\nintros t u H d.\ngeneralize t u H; clear H t u.\ninduction d as [| d IHd]; intros t u H.\nconstructor.\ndestruct H.\nconstructor.\nconstructor.\nintro i.\napply IHd with (1:=(H i)).\nQed.\n\n(** Pointwise equality implies bisimilarity. *)\nLemma term_eq_implies_term_bis : forall (t u : term), term_eq t u -> term_bis t u.\nProof.\ncofix eq2bis.\nintros [x|f v] [y|g w] H.\nassert (H0 := H 7); inversion_clear H0.\nconstructor.\nassert (H0 := H 1); inversion_clear H0.\nassert (H0 := H 1); inversion_clear H0.\nassert (H0 := term_eq_fun_inv_symbol H).\ndependent destruction H0.\napply Fun_bis.\nintro i.\nassert (H0 := term_eq_fun_inv H).\napply eq2bis.\napply H0.\nQed.\n\nLemma term_bis_term_eq :\n  forall (t u : term), term_bis t u <-> term_eq t u.\nProof.\nsplit.\napply term_bis_implies_term_eq.\napply term_eq_implies_term_bis.\nQed.\n\n(** Pointwise equality is an equivalence. *)\n\nLemma term_eq_up_to_trans :\n  forall d t u v,\n    term_eq_up_to d t u ->\n    term_eq_up_to d u v ->\n    term_eq_up_to d t v.\nProof.\ninduction d as [| d IH].\nconstructor.\nintros t u v H1.\ninversion_clear H1; intro H2.\nassumption.\ndependent destruction H2.\nconstructor.\nintro i.\napply IH with (u := w i); trivial.\nQed.\n\nLemma term_eq_up_to_refl :\n  forall d t,\n    term_eq_up_to d t t.\nProof.\ninduction d as [| d IH]; intro t.\nconstructor.\ndestruct t.\nconstructor.\nconstructor.\nintro.\napply IH.\nQed.\n\nLemma term_eq_up_to_symm :\n  forall d t u,\n    term_eq_up_to d t u ->\n    term_eq_up_to d u t.\nProof.\ninduction d as [| d IH]; intros t u H.\nconstructor.\ninversion_clear H.\nconstructor.\nconstructor.\nintro.\napply IH.\napply H0.\nQed.\n\nLemma term_eq_refl : forall t, term_eq t t.\nProof.\nintros t d.\napply (term_eq_up_to_refl d t).\nQed.\n\nLemma term_eq_symm :\n  forall t u, term_eq t u -> term_eq u t.\nProof.\nintros t u H d.\napply (term_eq_up_to_symm (H d)).\nQed.\n\nLemma term_eq_trans :\n  forall t u v, term_eq t u -> term_eq u v -> term_eq t v.\nProof.\nintros t u v H1 H2 d.\napply (term_eq_up_to_trans (H1 d) (H2 d)).\nQed.\n\n(** Bisimilarity is an equivalence. *)\n\nLemma term_bis_refl :\n  forall t, term_bis t t.\nProof.\ncofix.\ndestruct t as [x|f v]; constructor.\nintro i.\napply term_bis_refl.\nQed.\n\nLemma term_bis_symm :\n  forall t u, term_bis t u -> term_bis u t.\nProof.\ncofix.\ndestruct 1 as [x|f v w H]; constructor.\nintro i.\napply term_bis_symm.\napply H.\nQed.\n\nLemma term_bis_trans :\n  forall s t u, term_bis s t -> term_bis t u -> term_bis s u.\nProof.\ncofix.\ndestruct 1 as [x|f xs ys H1].\nintro. assumption.\nintro H2.\ndependent destruction H2.\nrename w into zs, H into H2.\nconstructor; intro i.\napply term_bis_trans with (1:=(H1 i)) (2:=(H2 i)).\nQed.\n\n(** Two weakening lemmas on pointwise equality follow. *)\n\nLemma term_eq_up_to_weaken :\n  forall t u d, term_eq_up_to (S d) t u -> term_eq_up_to d t u.\nProof.\nintros t u d H.\nrevert t u H.\ninduction d; intros t u H.\nconstructor.\ninversion_clear H.\napply term_eq_up_to_refl.\nconstructor.\nintro i.\napply IHd.\napply H0.\nQed.\n\nLemma term_eq_up_to_weaken_generalized :\n  forall t u n m,\n    n <= m ->\n    term_eq_up_to m t u ->\n    term_eq_up_to n t u.\nProof.\ninduction 1 as [| m H IH]; intro.\nassumption.\napply IH.\napply term_eq_up_to_weaken.\nassumption.\nQed.\n\n(** Cauchy-converence for a sequence of terms. This is used in the definition\n   of rewrite sequences in the library [Rewriting]. *)\nDefinition converges (f : nat -> term) (t : term) : Prop :=\n  forall d, exists n, forall m,\n    n <= m ->\n    term_eq_up_to d (f m) t.\n\nEnd TermEquality.\n\n\nInfix \" [~] \" := term_bis (no associativity, at level 70).\nInfix \" [=] \" := term_eq (no associativity, at level 70).\n\n\nSection PositionEquality.\n\n(** We introduce a third equality via positions, but we did not yet succeed\n   at proving it equal to the first two. *)\n\nVariable F : signature.\nVariable X : variables.\n\nNotation term := (term F X).\nNotation terms := (vector term).\n\n(** Equality of terms at a given position. *)\nDefinition pos_eq (p : position) (t u : term) :=\n  match subterm t p, subterm u p with\n  | None,   None   => True\n  | Some t, Some u => root t = root u\n  | _,      _      => False\n  end.\n\n(** Equality of terms at all positions. *)\nDefinition all_pos_eq (t u : term) :=\n  forall p : position, pos_eq p t u.\n\n(**\n   Didn't really bother to complete this...\n\n[[\nLemma all_pos_eq_fun_inv :\n  forall f v w,\n    all_pos_eq (Fun f v) (Fun f w) ->\n    forall i, all_pos_eq (v i) (w i).\nProof.\nintros f v w H i.\nrevert v w H.\ndependent destruction i; intros v w H1 p.\nassert (H' := H1 (0 :: p)).\nunfold pos_eq in H'.\nunfold subterm in H'.\ndestruct (Bool_nat.lt_ge_dec 0 (arity f)).\nunfold pos_eq.\nunfold subterm.\nassert (vnth_fact : vnth l v = v i0 /\\ vnth l w = w i0).\nadmit. (** vnth should do this *)\nrewrite (proj1 vnth_fact), (proj2 vnth_fact) in H'.\nassumption.\nassert (Habsurd : arity f = 0).\nauto with arith.\nrewrite Habsurd in *|-.\n(** The ugly thing is that dependent destruction i uses different names x0\n   (Coq 8.3) and H (Coq 8.2). *)\ndiscriminate.\n(** I don't know if we're on the right track here. *)\n]]\n\n[[\nLemma all_pos_eq_implies_term_bis :\n  forall (t u : term), all_pos_eq t u -> t [~] u.\nProof.\ncofix pos2bis.\nintros t u H.\nassert (H1 := H nil).\nunfold pos_eq in H1.\nunfold subterm in H1.\ndestruct t; destruct u. (* \"destruct t, u.\" syntax is Coq 8.3 only *)\ninjection H1; intro e; rewrite e; apply term_bis_refl.\ndiscriminate H1.\ndiscriminate H1.\ndependent destruction H1. (* injection H1; clear H1; intro e; rewrite e. *)\nconstructor.\nintro i.\napply pos2bis.\napply (all_pos_eq_fun_inv H).\nQed.\n]]\n\n[[\nLemma term_bis_implies_all_pos_eq :\n  forall (t u : term), t [~] u -> all_pos_eq t u.\nProof.\nintros t u H p.\nrevert t u H.\ninduction p as [| a p IH]; intros t u [x | f v w H].\nreflexivity.\nreflexivity.\nexact I.\nunfold pos_eq; simpl; destruct (Bool_nat.lt_ge_dec a (arity f)).\n(** vnth should do this of course *)\nassert (vnth_fact : exists i : Fin (arity f), vnth l v = v i /\\ vnth l w = w i).\nadmit.\ndestruct vnth_fact as [i [H1 H2]].\nrewrite H1, H2.\nassert (Hp := IH (v i) (w i) (H i)).\nunfold pos_eq in Hp.\ndestruct (subterm (v i) p); destruct (subterm (w i) p); assumption.\nexact I.\nQed.\n]]\n*)\n\nEnd PositionEquality.\n", "meta": {"author": "martijnvermaat", "repo": "infinitary-rewriting-coq", "sha": "0af6403a39c630de96ab2616ee7f3e01cd67a2f5", "save_path": "github-repos/coq/martijnvermaat-infinitary-rewriting-coq", "path": "github-repos/coq/martijnvermaat-infinitary-rewriting-coq/infinitary-rewriting-coq-0af6403a39c630de96ab2616ee7f3e01cd67a2f5/TermEquality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6623708040860522}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import Psatz.\n\n(*\nPozor:\nAli je:\nle_ge_dec n m : {n <= m} + {n >= m}.\npravilno definiran?\n\nMounosti nista izklucujoce, \nampak vedno pa velja vsaj nekaj.\nAmpak tu je dec, mogoce bi bilo \nboljse drugacno ime?\n*)\n\n(**\nZaradi definicije naslednika se mora suma odvijati \npo prvem elementu. Sicer povsod problemi z indukcijo.\n**)\nFixpoint sum (n : nat) {struct n} : (forall i, i < n -> nat) -> nat :=\n  match n with\n  | 0 => (fun f => 0)\n  | S m => \n    (fun (f : forall i, i < S m -> nat) => \n      f m (le_n (S m)) + \n      sum m (fun (i : nat) (p : i < m) => \n        f i (Nat.lt_trans i m (S m) p (le_n (S m)))))\n  end.\n\nDefinition sum' (n : nat) (f : nat -> nat) := sum n (fun i _ => f i).\n\n(** Given a decidable predicate [P] on [nat], we can count how many numbers up to [n] satisfy [P]. *)\nDefinition count (n : nat) {P : nat -> Prop} (decP : forall x, {P x} + {~ P x})  :=\n  sum' n (fun x => if decP x then 1 else 0).\n\n(* AAA *)\n(* verjetno gre v izbiris *)\nDefinition countA (n : nat) (P : nat -> Prop) (decP : forall x, {P x} + {~ P x}) :=\n  sum' n (fun x => if decP x then 1 else 0).\n\nLemma change_sum (n : nat) (f g : forall i, i < n -> nat) :\n  (forall j (p : j < n), f j p = g j p) ->\n  sum n f = sum n g.\nProof.\n  intro E.\n  induction n.\n  - reflexivity.\n  - simpl.\n    f_equal.\n    + apply E.\n    + apply IHn.\n      intros j p.\n      apply E.\nQed.\n\nLemma change_sum' (n : nat) (f g : nat -> nat) :\n  (forall j (p : j < n), f j = g j) ->\n  sum' n f = sum' n g.\nProof.\n  unfold sum'.\n  apply change_sum.\nQed.\n\nLemma sum'_S (n : nat) (f : nat -> nat) :\n  sum' (S n) f = f n + sum' n f.\nProof.\n  unfold sum'.\n  reflexivity.\nQed.\n\nLemma same_sum' (n c : nat) (f : nat -> nat) :\n  (forall j (p : j < n), f j = c) ->\n  sum' n f = n * c.\nProof.\n  induction n.\n  - intro H.\n    auto.\n  - rewrite sum'_S.\n    intro H.\n    rewrite IHn.\n    + rewrite H.\n      * lia.\n      * omega.\n    + auto.\nQed.\n\nLtac simpl_sum :=\n  try (rewrite sum'_S in *) ; simpl in *.\n\n\n\nLemma sum_n_krat_k (n : nat) (k : nat):\n  sum' n (fun y => k) = n * k.\nProof.\n  induction n.\n  - auto.\n  - simpl_sum.\n    rewrite IHn.\n    omega.\nQed.\n\nLemma sum_n_krat_1 (n : nat) (k : nat):\n  sum' n (fun y => 1) = n.\nProof.\n  rewrite (sum_n_krat_k n 1).\n  omega.\nQed.\n\n\n\n\n(* AAA *)\nLemma vsota_funkcij (n : nat) (f g : nat -> nat) :\n  sum' n (fun x => (f x) + (g x)) = sum' n f + sum' n g.\nProof.\n  induction n.\n  - auto.\n  - rewrite sum'_S.\n    rewrite IHn.\n    rewrite sum'_S.\n    rewrite sum'_S.\n    omega.\nQed.\n\n(* \nmalo je smesno da rabim tole lemo le da zrcali cez enacaj \nkako se da drugace?\n*)\nLemma vsota_funkcij_rv (n : nat) (f g : nat -> nat) :\n  sum' n f + sum' n g = sum' n (fun x => (f x) + (g x)).\nProof.\n  rewrite vsota_funkcij.\n  auto.\nQed.\n\n\n\n\nLemma krajsanje_izraza (An_ A_n Ann M Q : nat) :\n  A_n + M = Q -> An_ + A_n + Ann + M = Ann + An_ + Q.\nProof.\n  omega.\nQed.\n\nLemma sum_sum_ULD_part (n : nat) (f : nat -> nat -> nat) :\n  sum' n (fun x => (sum' x (fun y => f x y) + \n                    sum' x (fun y => f y x) + \n                    f x x)) =\n  sum' n (fun x => sum' n (fun y => f x y)).\nProof.\n  induction n.\n  - auto.\n  - rewrite sum'_S.\n    rewrite IHn.\n    rewrite sum'_S.\n    rewrite sum'_S.\n    set (Ann := f n n).\n    set (An_ := sum' n (fun y : nat => f n y)).\n    set (A_n := sum' n (fun y : nat => f y n)).\n    set (M := sum' n (fun x : nat => sum' n (fun y : nat => f x y))).\n    set (Q := sum' n (fun x : nat => sum' (S n) (fun y : nat => f x y))).\n    apply (krajsanje_izraza An_ A_n Ann M Q).\n    unfold A_n.\n    unfold M.\n    unfold Q.\n    rewrite (vsota_funkcij_rv n \n      (fun y : nat => f y n)\n      (fun x : nat => sum' n (fun y : nat => f x y))).\n    apply change_sum.\n    intros j p.\n    rewrite sum'_S.\n    auto.\nQed.\n\nLemma sum_sum_ULD (n : nat) (f : nat -> nat -> nat) :\n  sum' n (fun x => (sum' x (fun y => f x y))) + \n  sum' n (fun x => (sum' x (fun y => f y x))) + \n  sum' n (fun x => (f x x)) =\n  sum' n (fun x => sum' n (fun y => f x y)).\nProof.\n  do 2 rewrite vsota_funkcij_rv.\n  apply sum_sum_ULD_part.\nQed.\n\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/kernel_numeric.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6623704871717461}}
{"text": "Definition or_comm_aux P Q (H : P \\/ Q) : Q \\/ P :=\n  match H with\n  | or_introl H0 => or_intror H0\n  | or_intror H0 => or_introl H0\n  end.\n\nDefinition or_comm : forall P Q , P \\/ Q -> Q \\/ P :=\nfun (P Q : Prop) (PorQ : P \\/ Q) =>\nmatch PorQ with\n| or_introl P_holds => or_intror P_holds\n| or_intror Q_holds => or_introl Q_holds\nend.", "meta": {"author": "xidulu", "repo": "coq_last_hw", "sha": "57a6a8cbeb17c5bea0837d4a187f28e1adb744c6", "save_path": "github-repos/coq/xidulu-coq_last_hw", "path": "github-repos/coq/xidulu-coq_last_hw/coq_last_hw-57a6a8cbeb17c5bea0837d4a187f28e1adb744c6/task2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6623704822764299}}
{"text": "Require Import SMTCoq.SMTCoq.\nLocal Open Scope Z_scope.\n\nImport FArray.\nLocal Open Scope farray_scope.\n\nParameter fset: Type -> Type.\nParameter contains: forall {E: Type}, fset E -> E -> Prop.\n\nSection DomAndRange.\n  Context {K V: Type}.\n  Context {orderedInst: OrdType K}.\n  Context {kcomp: Comparable K}.\n  Context {inhInstOptV: Inhabited (option V)}.\n\n  Parameter domain: farray K (option V) -> fset K.\n  Parameter range: farray K (option V) -> fset V.\n\n  Lemma in_domain: forall a k v,\n    a[k] = Some v -> contains (domain a) k.\n  Proof.\n    (* smt. *)\n  Abort.\n\n  Lemma in_range: forall a k v,\n    a[k] = Some v -> contains (range a) v.\n  Proof.\n    (* smt. *)\n  Abort.\n\nEnd DomAndRange.\n", "meta": {"author": "samuelgruetter", "repo": "counterexamples", "sha": "bb699361b12687fdc6323759745e75d3bf8720b8", "save_path": "github-repos/coq/samuelgruetter-counterexamples", "path": "github-repos/coq/samuelgruetter-counterexamples/counterexamples-bb699361b12687fdc6323759745e75d3bf8720b8/SMTCoq/Range.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6623704822764299}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural := Succ y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj208_coqofml_5WvnH0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6623704777593982}}
{"text": "From Coq Require Import List Arith.\nOpen Scope nat_scope.\n\n(* Universidade de Brasília\n    Instituto de Ciências Exatas \n    Departamento de Ciência da Computação\n    Projeto e Análise de Algoritmos - turma B - 2020/2 \n    Professor: Flávio L. C. de Moura *)\n\n(*\n  Nome: Lucas Dalle Rocha\n  Matrícula: 17/0016641\n  Nome: Matheus Breder Branquinho\n  Matrícula: 17/0018997\n*)\n\n(** * A correção do algoritmo mergesort *)\n\n(** O algoritmo mergesort é um algoritmo de ordenação que utiliza a técnica de divisão e conquista, que consiste das seguintes etapas:\n%\\begin{enumerate}\n   \\item {\\bf Divisão}: O algoritmo divide a lista $l$ recebida como argumento ao meio, obtendo as listas $l_1$ e $l_2$. \n   \\item {\\bf Conquista}: O algoritmo é aplicado recursivamente às listas $l_1$ e $l_2$ gerando, respectivamente, as listas ordenadas $l_1'$ e $l_2'$.\n   \\item {\\bf Combinação}: O algoritmo combina as listas $l_1'$ e $l_2'$ através da função merge que então gera a saída do algoritmo.\n \\end{enumerate}%\nPor exemplo, ao receber a lista (4 :: 2 :: 1 :: 3 :: nil), este algoritmo inicialmente divide esta lista em duas sublistas, a saber (4 :: 2 :: nil) e (1 :: 3 :: nil). O algoritmo é aplicado recursivamente às duas sublistas para ordená-las, e ao final deste processo, teremos duas listas ordenadas (2 :: 4 :: nil) e (1 :: 3 :: nil). Estas listas são, então, combinadas para gerar a lista de saída (1 :: 2 :: 3 :: 4 :: nil). *)\n\n(** * Descrição do projeto *)\n\n(** A prova da correção de um algoritmo de ordenação consiste de duas etapas. Inicialmente, provaremos que o algoritmo efetivamente ordena os elementos da lista dada como argumento, e em seguida mostraremos que a lista de saída é uma permutação da lista de entrada. Neste projeto trabalharemos com listas de números naturais. *)\n\n(* begin hide *)\nRequire Import Arith List Recdef.\nRequire Import Coq.Program.Wf.\nRequire Import Permutation.\n(* end hide *)\n\n\n(** ** Primeira parte: *)\n\n(** Nesta primeira etapa do projeto, apresentaremos as definições e lemas relacionados à noção de ordenação de listas de números naturais. Para isto, precisamos inicialmente definir formalmente o que entendemos por \"lista ordenada\". O predicado [sorted] a seguir consiste na definição formal de ordenação que utilizaremos neste projeto. Note que este predicado é definido indutivamente e que possui três construtores, ou três regras como veremos a seguir: *)\n\nInductive sorted :list nat -> Prop :=\n  | nil_sorted : sorted nil\n  | one_sorted: forall n:nat, sorted (n :: nil)\n  | all_sorted : forall (x y: nat) (l:list nat), sorted (y :: l) -> x <= y -> sorted (x :: y :: l).\n\n(** O predicado [sorted] possui três construtores, a saber [nil_sorted], [one_sorted] and [all_sorted]. Os dois primeiros construtores são axiomas que afirmam que a lista vazia e que listas unitárias estão ordenadas: \n %\\begin{mathpar} \\inferrule*[Right={$(nil\\_sorted)$}]{~}{sorted\\ nil} \\and\n  \\inferrule*[Right={$(one\\_sorted)$}]{~}{\\forall n, sorted (n :: nil)} \\end{mathpar}%\nO terceiro construtor, i.e. [all_sorted] estabelece as condições para que uma lista com pelo menos dois elementos esteja ordenada. Assim, quaisquer que sejam os elementos $x$ e $y$, e a lista $l$, temos:\n%\\begin{mathpar} \\inferrule*[Right={$(all\\_sorted)$}]{sorted (y :: l) \\and x \\leq y}{sorted (x :: y :: l)}\\end{mathpar}%\nOu seja, para provarmos que a lista $x :: y :: l$ está ordenada, precisamos provar que $x \\leq y$ e que a lista $y :: l$ também está ordenada.\n *)\n\n(** Agora que temos um definição formal da noção de ordenação, vamos explorar algumas noções auxiliares que serão utilizadas na formalização. A primeira delas é o predicado [le_all] que recebe um natural [x] e uma lista [l] como argumentos, e a fórmula [le_all x l] possui uma prova quando [x] é menor ou igual a todos os elementos de [l]. *)\n\nDefinition le_all x l := forall y, In y l -> x <= y.\n\n(** printing <=* $\\leq *$ *)\n(** Escreveremos  [x <=* l] ao invés de [le_all x l]. *)\n(* begin hide *)\nInfix \"<=*\" := le_all (at level 70, no associativity).\n(* end hide *)\n\n(** Lemas são resultados auxiliares que podem ser usados em outras provas. É importante se lembrar dos lemas que ficaram para trás porque eles podem ser úteis em diversas provas. O primeiro lema auxiliar que veremos afirma que se a lista (a :: l) está ordenada então a sua cauda (tail) também está ordenada. A prova é feita por análise de casos. *)\n\nLemma tail_sorted: forall l a, sorted (a :: l) -> sorted l.\n(* begin hide *)\nProof.\n  intro l.\n  case l.\n  - intros a H.  \n    apply nil_sorted.  \n  - intros n l' a H.  \n    inversion H; subst.\n    assumption.  \nQed.  \n\n(** OBS: Seguem alguns exemplos de busca de teoremas com o comando [Search]: *)\n(** Search (_ > _ -> _ <= _). *)\n(** Search (~ _ <= _ -> _). *)\n(** Search \"lt_sub_lt_add\". *)\n(** Search ( ( _ / _) < _). *)\n(** Search ( ( _ / _) <= _). *)\n(** Search (0 < ( _ / _) ).*)\n(** Search (1 < 2). *)\n(** Search (0 < 2). *)\n(** Search ( _ - _ < _). *)\n(** Search (S _ + _ = S _).*)\n(* end hide *)\n\n(** *** Questão 1: *)\n(** A primeira questão consiste em provar que se [a] é menor ou igual a todo elemento de [l], e [l] é uma lista ordenada então a lista (a :: l) também está ordenada: *)\n\nLemma le_all_sorted: forall l a, a <=* l -> sorted l -> sorted (a :: l).\nProof.\n  intros l a H H0.\n  induction l.\n  - apply one_sorted.\n  - apply all_sorted.\n    + exact H0.\n    + destruct H with (y := a0).\n      * simpl.\n        left.\n        apply eq_refl.\n      * apply Nat.le_refl.\n      * apply le_S.\n        exact l0.\nQed.\n      \n(** O lema a seguir é bem parecido com o lema [tail_sorted] visto anteriormente, mas ao invés de remover o primeiro elemento de uma lista ordenada, este lema remove o segundo elemento de uma lista ordenada (com pelo menos dois elementos), e após esta remoção a lista resultante ainda está ordenada. Veja que a prova é por análise de casos. *)\n\nLemma remove_sorted: forall l a1 a2, sorted (a1 :: a2 :: l) -> sorted (a1 :: l).\n(* begin hide *)\nProof.\n  intro l; case l.\n  - intros a1 a2 H.\n    apply one_sorted.\n  - intros n l' a1 a2 H.\n    inversion H; subst.\n    inversion H2; subst.\n    apply all_sorted.\n    + assumption.\n    + apply Nat.le_trans with a2; assumption.\nQed.\n(* end hide *)\n\n(** *** Questão 2 *)\n(** A segunda questão consiste em provar que, se a lista [(a :: l)] está ordenada então [a] é menor ou igual a todo elemento de [l]. A dica é fazer indução na estrutura da lista [l]. *)\n\nLemma sorted_le_all: forall l a, sorted(a :: l) -> a <=* l.\nProof.\n  induction l.\n  - intros a H y H0.\n    destruct H0.\n  - intros a0 H y H0.\n    destruct H0.\n    + inversion H; subst.\n      exact H5.\n    + apply remove_sorted in H.\n      apply IHl in H.\n      unfold \"<=*\" in H.\n      apply H in H0.\n      exact H0.\nQed.\n\n(** ** Segunda parte: *)\n(** Agora definiremos a noção de permutação e apresentaremos alguns lemas relacionados. A noção de permutação que será utilizada neste projeto é baseada no número de ocorrências de um elemento. A função recursiva [num_oc n l] retorna o número de ocorrências do natural [n] na lista [l]. A palavra reservada [Fixpoint] é usada para definir funções recursivas, enquanto que [Definition] é usada para funções não-recursivas como foi o caso do predicado [le_all] visto anteriormente. *)\n\nFixpoint num_oc n l  :=\n  match l with\n    | nil => 0\n    | h :: tl =>\n      if n =? h then S(num_oc n tl) else  num_oc n tl\n  end.\n\n(** Dizemos então que duas listas [l] e [l'] são permutações uma da outra se qualquer natural [n] possui o mesmo número de ocorrências em ambas as listas. *)\n\nDefinition perm l l' := forall n:nat, num_oc n l = num_oc n l'.\n\n(** A reflexividade é uma propriedade que pode ser obtida a partir desta definição: uma lista é sempre permutação dela mesma. *)\n\nLemma perm_refl: forall l, perm l l.\n(* begin hide *)\nProof.\nintro l. unfold perm. intro. reflexivity.\nQed.\n(* end hide *)\n\n(** O lema a seguir é um resultado técnico, mas que pode ser utilizado em provas futuras. Ele diz que o número de ocorrências de um natural [n] no append das listas [l1] e [l2] (notação [l1 ++ l2]) é igual à soma das ocorrências de [n] em [l1] com as ocorrências de [n] em [l2]: *)\n\nLemma num_oc_append: forall n l1 l2, num_oc n l1 + num_oc n l2 = num_oc n (l1 ++ l2).\n(* begin hide *)\nProof.\n  intros. induction l1.\n  - simpl num_oc. trivial.\n  - simpl. destruct (n =? a).\n    + rewrite <- IHl1. apply Peano.plus_Sn_m.\n    + assumption.\nQed.\n(* end hide *)\n\n(** *** Terceira parte: *)\n(** Nesta parte definiremos o algoritmo mergesort. Iniciaremos pela função [merge] que faz a etapa de combinação descrita anteriormente. A função [merge] recebe como argumento um par de listas de naturais ordenadas e gera uma nova lista ordenada contendo exatamente os elementos das duas listas recebidas como argumento. Iniciamos então com a definição do predicado [sorted_pair_lst] que recebe um par de listas e retorna a conjunção expressando o fato de que cada lista que compõe o par está ordenada: *)\n\nDefinition sorted_pair_lst (p: list nat * list nat) :=\nsorted (fst p) /\\ sorted (snd p).\n\n(** Agora necessitamos de uma métrica para definirmos a função [merge]. Esta métrica consiste no tamanho do par que contém duas listas e é definido como sendo a soma do comprimento de cada uma das listas: *)\n\nDefinition len (p: list nat * list nat) :=\n   length (fst p) + length (snd p).\n\n(** Agora podemos definir a função recursiva [merge]. Dado um par [p] de listas de naturais, se alguma das listas que compõem este par é a lista vazia então a função simplesmente retorna o outro elemento do par. Quando ambas as listas que compõem o par são não-vazias então os primeiros elementos de cada lista são comparados e o menor deles será o colocado na lista final, e o processo se repete recursivamente para o par sem este menor elemento. Para garantirmos que esta função está bem definida, precisamos que as chamadas recursivas se aproximem do ponto de parada (chamadas sem recursão) que ocorre quando alguma das listas do par é a lista vazia. Esta garantia é dada pelo medida (ou métrica) definida anteriormente: o comprimento do par que [merge] recebe como argumento: *)\n(* printing *)\n(** printing <=? $\\leq ?$ *)\n\nFunction merge (p: list nat * list nat) {measure len p} :=\nmatch p with\n  | (nil, l2) => l2\n  | (l1, nil) => l1\n  | ((hd1 :: tl1) as l1, (hd2 :: tl2) as l2) =>\nif hd1 <=? hd2 then hd1 :: merge (tl1, l2)\n      else hd2 :: merge (l1, tl2)\n   end.\n\n(** A palavra reservada [Function] é utilizada para definir funções recursivas mais sofisticadas, ou seja, para funções recursivas cuja boa definição não pode ser inferida automaticamente pelo Coq. Neste caso, precisamos provar que nossa medida realmente decresce nas chamadas recursivas. *)\n(* begin hide *)\nProof.\n  - intros. unfold len. unfold fst. unfold snd. simpl length.\n    apply plus_lt_compat_r. auto.\n  - intros. unfold len. unfold fst. unfold snd. simpl length.\n    apply plus_lt_compat_l. auto.  \nQed.\n(* end hide *)\n\n(** O lema [merge_in] a seguir será bastante útil em provas futuras. Ele estabelece que se [y] é um elemento da lista [merge p] então [y] está em alguma das listas que compõem o par [p]. *)\n\nLemma merge_in: forall y p, In y (merge p) -> In y (fst p) \\/ In y (snd p).\n(* begin hide *)\nProof.\nintros. functional induction (merge p).\n  - right. unfold snd. assumption.\n    - left. unfold fst. assumption.\n    - simpl in H. destruct H as [H1 | H2].\n    + left. unfold fst. unfold In. left. assumption.\n        + destruct IHl.\n        * assumption.\n          * left. unfold fst. unfold fst in H. simpl In. right. assumption.\n          * right. simpl. simpl in H. assumption.\n    - simpl in H. destruct H as [H1 | H2].\n    + right. simpl snd. simpl In. left. assumption.\n        + destruct IHl.\n        * assumption.\n          * left. unfold fst. unfold fst in H. assumption.\n          * right. simpl. simpl in H. right. assumption.\nQed.\n(* end hide *)\n\n(** *** Questão 3 *)\n(** Esta questão é a mais importante do projeto. Ela estabelece que se as listas que compõem o par [p] estão ordenadas então [merge p] também está ordenada. Como [merge] é uma função recursiva mais sofisticada, as propriedades envolvendo esta função também terão provas mais complexas. Como você pode ver, esta prova é composta de quatro casos, dos quais dois estão provados, e dois fazem parte do exercício. Cada caso deixado como exercício é semelhante ao caso anterior, então use estas subprovas que estão feitas como ideias para completar a prova deste teorema. Os lemas anteriores também podem ser úteis! *)\n\nTheorem merge_sorts: forall p, sorted_pair_lst p -> sorted (merge p).\n(* begin hide *)\nProof.\n  intro p. functional induction (merge p).\n  - unfold sorted_pair_lst. intro. destruct H.\n    unfold snd in H0. assumption.\n  - unfold sorted_pair_lst. intro. destruct H.\n    unfold fst in H. assumption.\n  - intro. apply le_all_sorted.\n    + unfold le_all. intro. intro. apply merge_in in H0.\n      destruct H0 as [H1 | H2].\n      * simpl fst in H1. unfold sorted_pair_lst in H. destruct H as [H2 H3].\n        simpl fst in H2. apply sorted_le_all in H2. unfold le_all in H2.\n        apply H2. assumption.    \n      * simpl snd in H2. apply Nat.le_trans with hd2.\n        -- apply Nat.leb_le. assumption.\n        -- unfold sorted_pair_lst in H. destruct H as [H3 H4]. simpl snd in H4.\n           apply sorted_le_all in H4. simpl In in H2. destruct H2 as [H5 | H6].\n           ** rewrite H5. trivial.\n           ** unfold le_all in H4. apply H4. assumption.\n    + apply IHl. unfold sorted_pair_lst. split.\n      * simpl fst. unfold sorted_pair_lst in H. destruct H as [H1 H2].\n        simpl fst in H1. apply tail_sorted in H1. assumption.\n      * simpl snd. unfold sorted_pair_lst in H. destruct H as [H1 H2].\n        simpl snd in H2. assumption.  \n  - intro. apply le_all_sorted.\n    + unfold le_all. intro. intro. apply merge_in in H0.\n      destruct H0 as [H1 | H2].\n      * simpl fst in H1. unfold sorted_pair_lst in H. destruct H as [H2 H3].\n        simpl fst in H2. apply sorted_le_all in H2. unfold le_all in H2.\n        simpl in H1. destruct H1 as [H4 | H5].\n        ** rewrite <- H4. apply leb_complete_conv in e0. apply Nat.lt_le_incl in e0. assumption.\n        ** apply H2 in H5. apply leb_complete_conv in e0. apply Nat.lt_le_incl in e0. rewrite <- H5. assumption.\n      * simpl snd in H2. apply Nat.le_trans with hd2.\n        -- trivial.\n        -- unfold sorted_pair_lst in H. destruct H as [H3 H4]. simpl snd in H4.\n           apply sorted_le_all in H4. unfold le_all in H4. apply H4 in H2. assumption.\n    + apply IHl. unfold sorted_pair_lst. split.\n      * simpl fst. unfold sorted_pair_lst in H. destruct H as [H1 H2].\n        simpl fst in H1. assumption.\n      * simpl snd. unfold sorted_pair_lst in H. destruct H as [H1 H2].\n        simpl snd in H2. apply tail_sorted in H2. assumption.  \nQed.\n\n(* end hide *)\n\n(** Agora vamos definir a função [mergesort] que recebe uma lista [l] como argumento. Se esta lista for vazia ou unitária, o algoritmo não faz nada. Caso contrário, a lista é dividida ao meio, cada sublista é ordenada recursivamente, e no final as sublistas ordenadas são fundidas com a função [merge]. *)\n\nFunction mergesort (l: list nat) {measure length l}:=\n  match l with\n  | nil => nil\n  | hd :: nil => l\n  | hd :: tail =>\n     let n := length(l) / 2 in\n     let l1 := firstn n l in\n     let l2 := skipn n l in\n     let sorted_l1 := mergesort(l1) in\n     let sorted_l2 := mergesort(l2) in\n     merge (sorted_l1, sorted_l2)\n  end.\n\n(** Analogamente à definição da função [merge], precisamos provar que [mergesort] está bem definida. *)\n(* begin hide *)\nProof.\n- intros. rewrite skipn_length. apply Nat.sub_lt.\n  + apply Nat.lt_le_incl. apply Nat.div_lt.\n    * simpl. apply Nat.lt_0_succ.\n      * apply Nat.lt_1_2.\n    + apply Nat.div_str_pos. simpl. split.\n    * apply Nat.lt_0_2.\n      * apply Peano.le_n_S. apply Peano.le_n_S. apply Peano.le_0_n.  \n  - intros. rewrite firstn_length. rewrite min_l.\n  + apply Nat.div_lt.\n    * simpl. apply Nat.lt_0_succ.\n      * apply Nat.lt_1_2.\n    + apply Nat.lt_le_incl. apply Nat.div_lt.\n    * simpl. apply Nat.lt_0_succ.\n      * apply Nat.lt_1_2.  \nDefined.\n(* end hide *)\n\n(** *** Questão 4 *)\n(** Agora prove que a função [mergesort] realmente ordena a lista recebida como argumento. *)\n\nTheorem mergesort_sorts: forall l, sorted (mergesort l).\nProof.\n  induction l.\n  - apply nil_sorted.\n  - functional induction (mergesort (a :: l)).\n    + apply nil_sorted.\n    + apply one_sorted.\n    + apply merge_sorts.\n      unfold sorted_pair_lst.\n      split.\n      * unfold fst.\n        assumption.\n      * unfold snd.\n        assumption.\nQed.\n\n(** O lema a seguir é um lema técnico que pode ser usado nas questões seguintes. Este lema estabelece que o número de ocorrências de um elemento [n] no par de listas [p] é igual à soma das ocorrências de [n] em cada lista do par. *)\n\nLemma merge_num_oc: forall n p, num_oc n (merge p) = num_oc n (fst p) + num_oc n (snd p).\n(* begin hide *)\nProof.\nintros. functional induction (merge p).\n  - simpl fst. simpl snd. simpl num_oc. trivial.\n  - simpl fst. simpl snd. simpl num_oc. trivial.\n  - simpl fst. simpl snd. simpl num_oc at 1 2. destruct (n =? hd1).\n    + rewrite IHl. apply Peano.plus_Sn_m.\n    + rewrite IHl. simpl fst. simpl snd. trivial.\n  - simpl fst. simpl snd. simpl num_oc at 1 3. (destruct (n =? hd2)).\n      + rewrite IHl. simpl fst. simpl snd. apply Peano.plus_n_Sm.\n      + rewrite IHl. simpl fst. simpl snd. trivial.\nQed.\n(* end hide *)\n\n(** *** Questão 5 *)\n(** Prove que [mergesort] gera uma permutação da lista recebida como argumento. *)\n\nTheorem mergesort_is_perm: forall l, perm l (mergesort l).\nProof.\n  intros. functional induction (mergesort l).\n  - apply perm_refl.\n  - apply perm_refl.\n  - unfold perm. intros. rewrite merge_num_oc.\n    unfold fst. unfold snd.\n    replace (num_oc n (mergesort (firstn (length (hd :: tail) / 2) (hd :: tail)))) with (num_oc n (firstn (length (hd :: tail) / 2) (hd :: tail))).\n    replace (num_oc n (mergesort (skipn (length (hd :: tail) / 2) (hd :: tail)))) with (num_oc n (skipn (length (hd :: tail) / 2) (hd :: tail))).\n    + rewrite num_oc_append. rewrite firstn_skipn. reflexivity.\n    + destruct mergesort.\n      * unfold perm in *. rewrite -> IHl1. reflexivity.\n      * unfold perm in *. rewrite -> IHl1. reflexivity.\n    + unfold perm in *. rewrite -> IHl0. reflexivity.\nQed.\n\n(** *** Questão 6 *)\n(** Por fim, prove que [mergesort] é correto. *)\n\nTheorem mergesort_is_correct: forall l, perm l (mergesort l) /\\ sorted (mergesort l).\nProof.\n  split.\n  - apply mergesort_is_perm.\n  - apply mergesort_sorts.\nQed.\n\n(** ** Extração de código *)\n(** Uma das vantagens de formalizar um algoritmo é que você pode extrair o código certificado do algoritmo. O algoritmo de extração garante que o código extraído satisfaz todas as propriedades provadas. Vamos extrair automaticamente o código do algoritmo mergesort? *)\n\nRequire Extraction.\n\n(** As opções de linguagens fornecidas pelo Coq são: OCaml, Haskell, Scheme e JSON. *)\n\nExtraction Language OCaml.\n\n(** Extração apenas da função [mergesort]: *)\n\nExtraction mergesort.\n\n(** Extração do programa inteiro: *)\n\nRecursive Extraction mergesort.\n\n(** Extração para um arquivo: *)\n\nExtraction \"mergesort\" mergesort.\n", "meta": {"author": "xDalle", "repo": "PAA-2020", "sha": "58a89939fa4bc44a29ad0b09764b9ec42b7eeac7", "save_path": "github-repos/coq/xDalle-PAA-2020", "path": "github-repos/coq/xDalle-PAA-2020/PAA-2020-58a89939fa4bc44a29ad0b09764b9ec42b7eeac7/mergesort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.6623704630734499}}
{"text": "Require Import Init.Init.\nRequire Import Relation.Relation.\nRequire Import Structure.Structure.\nRequire Import Nat.Inductive.\nRequire Import Nat.Nature.\nRequire Import Nat.Recursion.\nRequire Import Nat.Arith.\n\n(* Order *)\nDefinition nat_order := {x: ω ⨉ ω| ∃ m, ∃ n, x = ⟨m, n⟩ ∧ m ∈ n}.\nNotation   \"m <ₙ n\"  := (m <[nat_order] n).\nNotation   \"m ≮ₙ n\"  := (m ≮[nat_order] n).\nNotation   \"m ≤ₙ n\"  := (m ≤[nat_order] n).\nNotation   \"m ≰ₙ n\"  := (m ≰[nat_order] n).\n\nLemma nat_less_e: ∀ m, ∀ n, m <ₙ n → m ∈ n.\nProof.\n  intros m n P1.\n  destruct (sub_e _ _ _ P1) as [_ [m' [n' [P4 P5]]]].\n  apply (eq_cr (λ x, x ∈ _) (opair_eq_el _ _ _ _ P4)).\n  apply (eq_cr (λ x, _ ∈ x) (opair_eq_er _ _ _ _ P4)).\n  apply P5.\nQed.\n\nLemma nat_less_i: ∀ m, ∀ n, m ∈ ω → n ∈ ω → m ∈ n → m <ₙ n.\nProof.\n  intros m n P1 P2 P3.\n  apply sub_i.\n  + apply (cp_i _ _ _ _ P1 P2).\n  + exists m.\n    exists n.\n    apply (and_i (eq_r _) P3).\nQed.\n\nLemma suc_less_i: ∀ m, ∀ n, m ∈ ω → n ∈ ω → m <ₙ n → S(m) <ₙ S(n).\nProof.\n  intros m n P1 P2 P3.\n  pose (λ k, ∀ p, p ∈ ω → p <ₙ k → S(p) <ₙ S(k)) as P.\n  assert (P 𝟢) as I1.\n  { intros m1 _ Q1.\n    apply bot_e.\n    apply (empty_i _ (nat_less_e _ _ Q1)). }\n  assert (induction_step P) as I2.\n  { intros k Q1 Q2 m2 Q3 Q4.\n    destruct (suc_e _ _ (nat_less_e _ _ Q4)) as [Q5 | Q5].\n    + apply (eq_cr (λ x, S(x) <ₙ _) Q5).\n      apply (nat_less_i _ _ (suc_is_nat _ Q1) (suc_is_nat _ (suc_is_nat _ Q1))).\n      apply suc_i1.\n    + apply (nat_less_i _ _ (suc_is_nat _ Q3) (suc_is_nat _ (suc_is_nat _ Q1))).\n      apply (nat_is_trans _ (suc_is_nat _ (suc_is_nat _ Q1)) _ (S(k))).\n      - apply (nat_less_e _ _ (Q2 _ Q3 (nat_less_i _ _ Q3 Q1 Q5))).\n      - apply suc_i1. }\n  apply (induction_principle _ I1 I2 _ P2 _ P1 P3).\nQed.\n\nLemma nat_less_suc: ∀ m, ∀ n, m ∈ ω → n ∈ ω → m <ₙ S(n) → m ≤ₙ n.\nProof.\n  intros m n P1 P2 P3.\n  pose (nat_less_e _ _ P3) as P4.\n  destruct (suc_e _ _ P4) as [P5 | P5].\n  + right.\n    apply P5.\n  + left.\n    apply (nat_less_i _ _ P1 P2 P5).\nQed.\n\nLemma less_suc: ∀ m, m ∈ ω → m <ₙ S(m).\nProof.\n  intros m P1.\n  apply (nat_less_i _ _ P1 (suc_is_nat _ P1)).\n  apply suc_i1.\nQed.\n\nLemma suc_le_nat: ∀ m, ∀ n, m ∈ ω → n ∈ ω → m <ₙ n → S(m) ≤ₙ n.\nProof.\n  intros m n P1 P2 P3.\n  destruct (suc_e n (S(m))) as [P4 | P4].\n  + apply nat_less_e.\n    apply (suc_less_i _ _ P1 P2 P3).\n  + right.\n    apply P4.\n  + left.\n    apply (nat_less_i _ _ (suc_is_nat _ P1) P2 P4).\nQed.\n\nLemma suc_less_e: ∀ m, ∀ n, m ∈ ω → n ∈ ω → S(m) <ₙ S(n) → m <ₙ n.\nProof.\n  intros m n P1 P2 P3.\n  destruct (nat_less_suc _ _ (suc_is_nat _ P1) P2 P3) as [P4 | P4].\n  + apply (nat_less_i _ _ P1 P2).\n    apply (nat_is_trans _ P2 _ (S(m)) (suc_i1 _) (nat_less_e _ _ P4)).\n  + apply (eq_cl (λ x, m <ₙ x) P4).\n    apply (less_suc _ P1).\nQed.\n\nLemma nat_less_trans: r_trans nat_order ω.\nProof.\n  intros m n p P1 P2 P3 P4 P5.\n  pose (nat_less_e _ _ P4) as P6.\n  pose (nat_less_e _ _ P5) as P7.\n  apply (nat_less_i _ _  P1 P3).\n  apply (nat_is_trans _ P3 _ _ P6 P7).\nQed.\n\nLemma nat_less_irrefl: r_irrefl nat_order ω.\nProof.\n  intros n P1 P2.\n  apply (nin_self n).\n  apply (nat_less_e _ _ P2).\nQed.\n\nLemma nat_less_tricho_weak: tricho_weak nat_order ω.\nProof.\n  intros m n P1 P2.\n  pose (λ k, k ∈ ω → k <ₙ n ∨ k = n ∨ n <ₙ k) as P.\n  assert (P 𝟢) as I1.\n  { intros Q1.\n    destruct (LEM (n = 𝟢)) as [Q2 | Q2].\n    + right. left.\n      apply (eq_s Q2).\n    + left.\n      apply (nat_less_i _ _ empty_is_nat P2 (empty_in_nat _ P2 Q2)). }\n  assert (induction_step P) as I2.\n  { intros k Q1 Q2 Q3.\n    destruct (Q2 Q1) as [Q4 | [Q4 | Q4]].\n    + destruct (suc_le_nat _ _ Q1 P2 Q4) as [Q5 | Q5].\n      - left.\n        apply Q5.\n      - right. left.\n        apply Q5.\n    + right. right.\n      apply (eq_cl (λ x, x <ₙ S(k)) Q4).\n      apply (less_suc _ Q1).\n    + right. right.\n      apply (nat_less_i _ _ P2 Q3).\n      apply (nat_is_trans _ Q3 _ _ (nat_less_e _ _ Q4) (suc_i1 _)). }\n  apply (induction_principle _ I1 I2 _ P1 P1).\nQed.\n\nLemma nat_less_tricho: tricho nat_order ω.\nProof.\n  apply weak_to_tricho.\n  + apply nat_less_tricho_weak.\n  + apply nat_less_irrefl.\n  + apply nat_less_trans.\nQed.\n\nLemma empty_less: ∀ n, n ∈ ω → n ≠ 𝟢 → 𝟢 <ₙ n.\nProof.\n  intros n P1 P2.\n  apply (nat_less_i _ _ empty_is_nat P1).\n  apply (empty_in_nat _ P1 P2).\nQed.\n\nLemma not_less_empty: ∀ n, n ∈ ω → n ≠ 𝟢 → n ≮ₙ 𝟢.\nProof.\n  intros n P1 P2.\n  destruct (nat_less_tricho _ _ empty_is_nat P1)\n    as [[_ [_ Q1]] | [[_ [Q1 _]] | [Q1 _]]].\n  + apply Q1.\n  + apply bot_e.\n    apply (P2 (eq_s Q1)).\n  + apply bot_e.\n    apply (Q1 (empty_less _ P1 P2)).\nQed.\n\nLemma nat_po: po nat_order ω.\nProof.\n  split.\n  + apply nat_less_trans.\n  + apply nat_less_irrefl.\nQed.\n\nLemma nat_lo: lo nat_order ω.\nProof.\n  split.\n  + apply nat_less_trans.\n  + apply nat_less_tricho.\nQed.\n\nLemma nat_less_least_prop: least_prop nat_order ω.\nProof.\n  intros S P1 P2.\n  apply nn_e.\n  intros P3.\n  (*pose (ω \\ S) as K.*)\n  pose (λ k, k ∈ ω → ∀ k', k' ∈ ω → k' <ₙ k → k' ∉ S) as P.\n  assert (P 𝟢) as I1.\n  { intros Q1 k' Q2 Q3 Q4.\n    destruct (LEM (k' = 𝟢)) as [Q5 | Q5].\n    + apply (nat_less_irrefl _ Q2).\n      apply (eq_cr (λ x, k' <ₙ x) Q5 Q3).\n    + apply (not_less_empty _ Q2 Q5 Q3). }\n  assert (induction_step P) as I2.\n  { intros k Q1 Q2 Q3 k' Q4 Q5 Q6.\n    apply P3.\n    exists k'.\n    split.\n    + apply Q6.\n    + intros x Q7.\n      apply (lo_nl_e _ _ _ _ nat_lo (P1 _ Q7) Q4).\n      intros Q8.\n      destruct (nat_less_suc _ _ Q4 Q1 Q5) as [Q9 | Q9].\n      - apply (Q2 Q1 _ (P1 _ Q7)\n          (l_l_t _ _ _ _ _ nat_less_trans (P1 _ Q7) Q4 Q1 Q8 Q9)).\n        apply Q7.\n      - apply (Q2 Q1 _ (P1 _ Q7) (eq_cl (λ y, x <ₙ y) Q9 Q8)).\n        apply Q7. }\n  apply P2.\n  apply empty_unique.\n  intros x P4.\n  pose (P1 _ P4) as P5.\n  apply (induction_principle _ I1 I2 _ (suc_is_nat _ P5)\n    (suc_is_nat _ P5) _ P5 (less_suc _ P5)).\n  apply P4.\nQed.\n\nLemma nat_wo: wo nat_order ω.\nProof.\n  split.\n  + apply nat_lo.\n  + apply nat_less_least_prop.\nQed.\n\nLemma nat_l_l_t: ∀ m, ∀ n, ∀ p, m ∈ ω → n ∈ ω → p ∈ ω → m <ₙ n → n <ₙ p\n  → m <ₙ p.\nProof.\n  intros m n p.\n  apply (l_l_t _ _ _ _ _ nat_less_trans).\nQed.\n\nLemma nat_le_l_t: ∀ m, ∀ n, ∀ p, m ∈ ω → n ∈ ω → p ∈ ω → m ≤ₙ n → n <ₙ p\n  → m <ₙ p.\nProof.\n  intros m n p.\n  apply (le_l_t _ _ _ _ _ nat_less_trans).\nQed.\n\nLemma nat_l_le_t: ∀ m, ∀ n, ∀ p, m ∈ ω → n ∈ ω → p ∈ ω → m <ₙ n → n ≤ₙ p\n  → m <ₙ p.\nProof.\n  intros m n p.\n  apply (l_le_t _ _ _ _ _ nat_less_trans).\nQed.\n\nLemma nat_le_le_t: ∀ m, ∀ n, ∀ p, m ∈ ω → n ∈ ω → p ∈ ω → m ≤ₙ n → n ≤ₙ p\n  → m ≤ₙ p.\nProof.\n  intros m n p.\n  apply (le_le_t _ _ _ _ _ nat_less_trans).\nQed.\n(*----------------------------------------------------------------------------*)\n\n(* Arith *)\nLemma nat_add_l: ∀ m, ∀ p, m ∈ ω → p ∈ ω → m <ₙ m +ₙ S(p).\nProof.\n  intros m p P1 P2.\n  apply (eq_cr (λ x, m <ₙ x) (nat_add_redr _ _ P1 P2)).\n  pose (λ k, m <ₙ S(m +ₙ k)) as P.\n  assert (P 𝟢) as I1.\n  { apply (eq_cr (λ x, m <ₙ S(x)) (nat_add_zeror _ P1)).\n    apply (less_suc _ P1). }\n  assert (induction_step P) as I2.\n  { intros k Q1 Q2.\n    pose (suc_is_nat _ (nat_add_close _ _ P1 Q1)) as Q3.\n    apply (eq_cr (λ x, m <ₙ S(x)) (nat_add_redr _ _ P1 Q1)).\n    apply (l_l_t _ _ _ _ _ nat_less_trans P1 Q3 (suc_is_nat _ Q3)).\n    + apply Q2.\n    + apply (less_suc _ Q3). }\n  apply (induction_principle _ I1 I2 _ P2).\nQed.\n\nLemma nat_add_le: ∀ m, ∀ p, m ∈ ω → p ∈ ω → m ≤ₙ m +ₙ p.\nProof.\n  intros m p P1 P2.\n  destruct (LEM (p = 𝟢)) as [P3 | P3].\n  + apply (eq_cr (λ x, m ≤ₙ(m +ₙ x)) P3).\n    apply (eq_cr (λ x, m ≤ₙ x) (nat_add_zeror _ P1)).\n    right.\n    apply eq_r.\n  + destruct (nat_is_suc _ P2 P3) as [x [P4 P5]].\n    apply (eq_cr (λ x, m ≤ₙ (m +ₙ x)) P5).\n    left.\n    apply (nat_add_l _ _ P1 P4).\nQed.\n\nLemma nat_add_ex_l: ∀ m, ∀ n, ∀ p, m ∈ ω → n ∈ ω → p ∈ ω → m +ₙ S(p) = n\n  → m <ₙ n.\nProof.\n  intros m n p P1 P2 P3 P4.\n  apply (eq_cl (λ x, m <ₙ x) P4).\n  apply (nat_add_l _ _ P1 P3).\nQed.\n\nLemma nat_add_l_ex: ∀ m, ∀ n, m ∈ ω → n ∈ ω → m <ₙ n\n  → ∃ p, p ∈ ω ∧ m +ₙ S(p) = n.\nProof.\n  intros m n P1 P2 P3.\n  pose (λ k, k <ₙ m ∨ m = k ∨ ∃ p, p ∈ ω ∧ m +ₙ S(p) = k) as P.\n  assert (P 𝟢) as I1.\n  { destruct (LEM (m = 𝟢)) as [P4 | P4].\n    + right. left.\n      apply P4.\n    + left.\n      apply (empty_less _ P1 P4). }\n  assert (induction_step P) as I2.\n  { intros k Q1 [Q2 | [Q2 | Q2]].\n    + destruct (suc_le_nat _ _ Q1 P1 Q2) as [Q3 | Q3].\n      - left.\n        apply Q3.\n      - right. left.\n        apply (eq_s Q3).\n    + right. right.\n      exists 𝟢.\n      split.\n      - apply empty_is_nat.\n      - apply (eq_cr (λ x, x = _) (nat_add_redr _ _ P1 empty_is_nat)).\n        apply (eq_cr (λ x, S(x) = _) (nat_add_zeror _ P1)).\n        apply (eq_cr (λ x, S(x) = _) Q2).\n        apply eq_r.\n    + destruct Q2 as [p [Q3 Q4]].\n      right. right.\n      exists (S(p)).\n      split.\n      - apply (suc_is_nat _ Q3).\n      - apply (eq_cr (λ x, x = S(k)) (nat_add_redr _ _ P1 (suc_is_nat _ Q3))).\n        apply (eq_cr (λ x, S(x) = S(k)) Q4).\n        apply eq_r. }\n  destruct (induction_principle _ I1 I2 _ P2) as [P4 | [P4 | P4]].\n  + apply bot_e.\n    apply (nat_less_irrefl _ P1 (nat_l_l_t _ _ _ P1 P2 P1 P3 P4)).\n  + apply bot_e.\n    apply (nat_less_irrefl _ P1 (eq_cr (λ x, m <ₙ x) P4 P3)).\n  + apply P4.\nQed.\n\nLemma nat_add_l_cancel: ∀ m, ∀ n, ∀ p, m ∈ ω → n ∈ ω → p ∈ ω\n  → m +ₙ p <ₙ n +ₙ p → m <ₙ n.\nProof.\n  intros m n p P1 P2 P3 P4.\n  destruct (nat_add_l_ex _ _ \n    (nat_add_close _ _ P1 P3) (nat_add_close _ _ P2 P3) P4) as [r [P5 P6]].\n  apply (nat_add_ex_l _ _ r P1 P2 P5).\n  apply (nat_add_cancel _ _ _ \n    (nat_add_close _ _ P1 (suc_is_nat _ P5)) P2 P3).\n  apply (eq_t (nat_add_132 _ _ _ P1 (suc_is_nat _ P5) P3) P6).\nQed.\n\nLemma nat_add_l_eqr: ∀ m, ∀ n, ∀ p, m ∈ ω → n ∈ ω → p ∈ ω → m <ₙ n\n  → m +ₙ p <ₙ n +ₙ p.\nProof.\n  intros m n p P1 P2 P3 P4.\n  pose (λ k, (m +ₙ k) <ₙ (n +ₙ k)) as P.\n  assert (P 𝟢) as I1.\n  { red.\n    apply (eq_cr (λ x, x <ₙ _) (nat_add_zeror _ P1)).\n    apply (eq_cr (λ x, _ <ₙ x) (nat_add_zeror _ P2)).\n    apply P4. }\n  assert (induction_step P) as I2.\n  { intros k Q1 Q2.\n    red.\n    apply (eq_cr (λ x, x <ₙ _) (nat_add_redr _ _ P1 Q1)).\n    apply (eq_cr (λ x, _ <ₙ x) (nat_add_redr _ _ P2 Q1)).\n    apply (suc_less_i _ _ (nat_add_close _ _ P1 Q1) (nat_add_close _ _ P2 Q1)).\n    apply Q2. }\n  apply (induction_principle _ I1 I2 _ P3).\nQed.\n\nLemma nat_add_l_eql: ∀ m, ∀ n, ∀ p, m ∈ ω → n ∈ ω → p ∈ ω → m <ₙ n\n  → p +ₙ m <ₙ p +ₙ n.\nProof.\n  intros m n p P1 P2 P3 P4.\n  apply (eq_cr (λ x, x <ₙ _) (nat_add_commu _ _ P3 P1)).\n  apply (eq_cr (λ x, _ <ₙ x) (nat_add_commu _ _ P3 P2)).\n  apply (nat_add_l_eqr _ _ _ P1 P2 P3 P4).\nQed.\n\nLemma nat_add_l_preserve: ∀ m, ∀ n, ∀ p, ∀ q, m ∈ ω → n ∈ ω → p ∈ ω → q ∈ ω\n  → m <ₙ n → p <ₙ q → m +ₙ p <ₙ n +ₙ q.\nProof.\n  intros m n p q P1 P2 P3 P4 P5 P6.\n  pose (nat_add_l_eqr _ _ _ P1 P2 P3 P5) as P7.\n  pose (nat_add_l_eql _ _ _ P3 P4 P2 P6) as P8.\n  apply (nat_l_l_t _ (n +ₙ p)).\n  all: is_nat.\nQed.\n\nLemma nat_mul_l: ∀ m, ∀ n, ∀ p, m ∈ ω → n ∈ ω → p ∈ ω → m <ₙ n → 𝟢 <ₙ p\n  → m ×ₙ p <ₙ n ×ₙ p.\nProof.\n  intros m n p P1 P2 P3 P4 P5.\n  pose (λ k, k = 𝟢 ∨ m ×ₙ k <ₙ n ×ₙ k) as P.\n  assert (P 𝟢) as I1.\n  { left.\n    apply eq_r. }\n  assert (induction_step P) as I2.\n  { intros k Q1 [Q2 | Q2].\n    + right.\n      apply (eq_cr (λ k, _ ×ₙ S(k) <ₙ _ ×ₙ S(k)) Q2).\n      apply (eq_cr (λ x, x <ₙ _) (nat_mul_oner _ P1)).\n      apply (eq_cr (λ x, _ <ₙ x) (nat_mul_oner _ P2)).\n      apply P4.\n    + right.\n      apply (eq_cr (λ x, x <ₙ _) (nat_mul_redr _ _ P1 Q1)).\n      apply (eq_cr (λ x, _ <ₙ x) (nat_mul_redr _ _ P2 Q1)).\n      apply nat_add_l_preserve.\n      all: is_nat. }\n  destruct (induction_principle _ I1 I2 _ P3) as [P6 | P6].\n  + apply bot_e.\n    apply (nat_less_irrefl _ P3).\n    apply (eq_cr (λ x, x <ₙ _) P6 P5).\n  + apply P6.\nQed.\n\n(*Lemma less_nat_preserve: ∀ m, ∀ n, m ∈ ω → n < ω → 𝟢 < m → 𝟢 < n → 0 < m ×ₙ m.*)\n(*Lemma mul_order_l: ∀ m, ∀ n, ∀ p, ∀ q, m ∈ ω → n ∈ ω → p ∈ ω → q ∈ ω →*)\n  (*m <ₙ n → p <ₙ q → m ×ₙ q +ₙ n ×ₙ p <ₙ m ×ₙ p +ₙ n ×ₙ q.*)\n(*Proof.*)\n  (*intros m n p q P1 P2 P3 P4 P5 P6.*)\n  (*destruct (less_ex _ _ P1 P2 P5) as [s1 [P7 P8]].*)\n  (*destruct (less_ex _ _ P3 P4 P6) as [s2 [P9 P10]].*)\n  (*apply (eq_cl (λ x, _ ×ₙ x +ₙ _ <ₙ _ +ₙ n ×ₙ x) P10).*)\n  (*apply (eq_cr (λ x, x +ₙ _ <ₙ _) (distr_l _ _ _ P1 P3 (suc_is_nat _ P9))).*)\n  (*apply (eq_cr (λ x, _ <ₙ _ +ₙ x) (distr_l _ _ _ P2 P3 (suc_is_nat _ P9))).*)\n  (*apply (eq_cl (λ x, x <ₙ _) (add_assoc _ _ _ (mul_is_nat _ _ P1 P3)*)\n    (*(mul_is_nat _ _ P1 (suc_is_nat _ P9)) (mul_is_nat _ _ P2 P3))).*)\n  (*apply (less_add_eq_l).*)\n  (*all: is_nat.*)\n  (*apply (eq_cr (λ x, x <ₙ _) (add_commu _ _*)\n    (*(mul_is_nat _ _ P1 (suc_is_nat _ P9)) (mul_is_nat _ _ P2 P3))).*)\n  (*apply (less_add_eq_l).*)\n  (*all: is_nat.*)\n  (*apply (eq_cl (λ x, _ <ₙ x ×ₙ _) P8).*)\n  (*apply (eq_cr (λ x, _ <ₙ x) (distr_r _ _ _ P1 (suc_is_nat _ P7)*)\n    (*(suc_is_nat _ P9))).*)\n  (*apply (eq_cl (λ x, x <ₙ _) (add_zero _ (mul_is_nat _ _ P1 (suc_is_nat _ P9)))).*)\n  (*apply (less_add_eq_l).*)\n  (*all: is_nat.*)\n  (*destruct (nat_less_tricho_weak _ _ empty_is_nat (mul_is_nat _ _ (suc_is_nat _ P7) (suc_is_nat _ P9))) as [Q1 | [Q1 | Q1]].*)\n  (*+ apply Q1.*)\n  (*+ destruct (mul_eq_zero _ _ (suc_is_nat _ P7) (suc_is_nat _ P9) (eq_s Q1)) as [Q2 | Q2].*)\n    (*- *)\n\n\n  (*rewrite <- P10.*)\n  (*rewrite (distributive_l (m +ₙ S(s1)) p (S(s2))).*)\n  (*rewrite (distributive_l m p (S(s2))).*)\n  (*rewrite (distributive_r m (S(s1)) p).*)\n  (*rewrite (distributive_r m (S(s1)) (S(s2))).*)\n  (*rewrite (add_associative (m ×ₙ p +ₙ S( s1) ×ₙ p) (m ×ₙ S( s2)) (S( s1) ×ₙ S( s2))).*)\n  (*rewrite (add_commutative (m ×ₙ p +ₙ S( s1) ×ₙ p) (m ×ₙ S( s2))).*)\n  (*rewrite (add_associative (m ×ₙ p)*)\n    (*(m ×ₙ S( s2) +ₙ (m ×ₙ p +ₙ S( s1) ×ₙ p)) (S( s1) ×ₙ S( s2))).*)\n  (*rewrite (add_associative (m ×ₙ p) (m ×ₙ S( s2)) (m ×ₙ p +ₙ S( s1) ×ₙ p)).*)\n  (*rewrite (multi_red _ _ (suc_is_nat _ P7) P9).*)\n  (*rewrite (add_associative ((m ×ₙ p +ₙ m ×ₙ S( s2)) +ₙ (m ×ₙ p +ₙ S( s1) ×ₙ p))*)\n    (*(S(s1)) (S(s1) ×ₙ s2)).*)\n  (*apply (less_le_less _ *)\n    (*(((m ×ₙ p +ₙ m ×ₙ S( s2)) +ₙ (m ×ₙ p +ₙ S( s1) ×ₙ p)) +ₙ S( s1)) _).*)\n  (*all: is_nat.*)\n  (*apply add_less.*)\n  (*all: is_nat.*)\n  (*apply add_less_equal.*)\n  (*all: is_nat.*)\n(*Qed.*)\n\n\n(*Lemma less_multi_eq: forall m n p, m ∈ ω -> n ∈ ω -> p ∈ ω -> m <ₙ n ->*)\n  (*(m ×ₙ S(p)) <ₙ (n ×ₙ S(p)).*)\n(*Proof.*)\n  (*intros m n p P1 P2 P3 P4.*)\n  (*pose (fun k => (m ×ₙ S(k)) <ₙ (n ×ₙ S(k))) as P.*)\n  (*assert (P 𝟢) as I1.*)\n  (*{ red. *)\n    (*rewrite (multi_one _ P1).*)\n    (*rewrite (multi_one _ P2).*)\n    (*apply P4. }*)\n  (*assert (induction_step P) as I2.*)\n  (*{ intros k Q1 Q2.*)\n    (*red.*)\n    (*rewrite (multi_red _ _ P1 (suc_is_nat _ Q1)).*)\n    (*rewrite (multi_red _ _ P2 (suc_is_nat _ Q1)).*)\n    (*apply (less_add_less m n (m ×ₙ S(k)) (n ×ₙ S(k))).*)\n    (*all: is_nat. }*)\n  (*apply (induction_principle _ I1 I2 _ P3).*)\n(*Qed.*)\n\n(*Lemma equal_less_less: forall m n p q, m ∈ ω -> n ∈ ω -> p ∈ ω -> q ∈ ω ->*)\n  (*(m +ₙ p) = (n +ₙ q) -> m <ₙ n -> q <ₙ p.*)\n(*Proof.*)\n  (*intros m n p q P1 P2 P3 P4 P5 P6.*)\n  (*destruct (less_ex _ _ P1 P2 P6) as [r [P7 P8]].*)\n  (*rewrite <- P8 in P5.*)\n  (*rewrite (add_commutative _ _ P1 P3) in P5.*)\n  (*rewrite (add_commutative _ _ P1 (suc_is_nat _ P7)) in P5.*)\n  (*rewrite (add_cyc _ _ _ (suc_is_nat _ P7) P1 P4) in P5.*)\n  (*rewrite (add_commutative _ _ (suc_is_nat _ P7) P4) in P5.*)\n  (*symmetry in P5.*)\n  (*apply (ex_less _ _ r P4 P3 P7).*)\n  (*apply (add_cancellation _ _ _ *)\n    (*(add_is_nat _ _ P4 (suc_is_nat _ P7)) P3 P1 P5).*)\n(*Qed.*)\n\n(*Lemma less_multi_cancellation: forall m n p, m ∈ ω -> n ∈ ω -> p ∈ ω -> *)\n  (*(m ×ₙ S(p)) <ₙ (n ×ₙ S(p)) -> m <ₙ n.*)\n(*Proof.*)\n  (*intros m n p P1 P2 P3 P4.*)\n  (*destruct (nat_trichotomy _ _ P1 P2) as [[P5 _] | [[_ [P5 _]] | [_ [_ P5]]]].*)\n  (*+ apply P5.*)\n  (*+ rewrite P5 in P4.*)\n    (*pose (nat_not_in_self _ (multi_is_nat _ _ P2 (suc_is_nat _ P3))) as P6.*)\n    (*contradiction.*)\n  (*+ pose (less_multi_eq _ _ _ P2 P1 P3 P5) as P6.*)\n    (*absurd (m ×ₙ S( p) <ₙ m ×ₙ S( p)).*)\n    (*- apply nat_not_in_self.*)\n      (*is_nat.*)\n    (*- apply (less_less_less _ (n ×ₙ S(p)) _).*)\n      (*all: is_nat.*)\n(*Qed.*)\n\n(*Lemma not_equal_less: forall m n, m ∈ ω -> n ∈ ω -> m <> n -> *)\n  (*m <ₙ n \\/ n <ₙ m.*)\n(*Proof.*)\n  (*intros m n P1 P2 P3.*)\n  (*destruct (nat_trichotomy _ _ P1 P2) as [P4|[P4|P4]].*)\n  (*+ destruct P4 as [P4 _].*)\n    (*left. *)\n    (*apply P4.*)\n  (*+ destruct P4 as [_ [P4 _]].*)\n    (*contradiction.*)\n  (*+ destruct P4 as [_ [_ P4]].*)\n    (*right.*)\n    (*apply P4.*)\n(*Qed.*)\n\n(*Lemma less_not_equal_1: forall m n, m ∈ ω -> n ∈ ω -> m <ₙ n ->*)\n  (*m <> n.*)\n(*Proof.*)\n  (*intros m n P1 P2 P3.*)\n  (*destruct (nat_trichotomy _ _ P1 P2) as [P4|[P4|P4]].*)\n  (*+ destruct P4 as [_ [P4 _]].*)\n    (*apply P4.*)\n  (*+ destruct P4 as [P4 _].*)\n    (*contradiction.*)\n  (*+ destruct P4 as [_ [P4 _]].*)\n    (*apply P4.*)\n(*Qed.*)\n\n(*Lemma less_not_equal_2: forall m n, m ∈ ω -> n ∈ ω -> m <ₙ n ->*)\n  (*n <> m.*)\n(*Proof.*)\n  (*intros m n P1 P2 P3 P4.*)\n  (*symmetry in P4.*)\n  (*apply (less_not_equal_1 _ _ P1 P2 P3 P4).*)\n(*Qed.*)\n\n(*Lemma multi_cancellation: forall m n p, m ∈ ω -> n ∈ ω -> p ∈ ω ->*)\n  (*m ×ₙ S(p) = n ×ₙ S(p) -> m = n.*)\n(*Proof.*)\n  (*intros m n p P1 P2 P3 P4.*)\n  (*destruct (nat_trichotomy _ _ P1 P2) as [[P5 _] | [[_ [P5 _]] | [_ [_ P5]]]].*)\n  (*+ absurd (m ×ₙ S(p) = n ×ₙ S(p)).*)\n    (*- apply less_not_equal_1.*)\n      (*all: is_nat.*)\n      (*apply (less_multi_eq _ _ p P1 P2 P3 P5).*)\n    (*- apply P4.*)\n  (*+ apply P5.*)\n  (*+ absurd (m ×ₙ S(p) = n ×ₙ S(p)).*)\n    (*- apply less_not_equal_2.*)\n      (*all: is_nat.*)\n      (*apply (less_multi_eq _ _ p P2 P1 P3 P5).*)\n    (*- apply P4.*)\n(*Qed.*)\n\n(*Lemma not_equal_cyc_equal: forall m n p q, m ∈ ω -> n ∈ ω -> p ∈ ω -> q ∈ ω ->*)\n  (*p <> q -> m ×ₙ p +ₙ n ×ₙ q = m ×ₙ q +ₙ n ×ₙ p -> m = n.*)\n(*Proof.*)\n  (*intros m n p q P1 P2 P3 P4 P5 P6.*)\n  (*destruct (not_equal_less _ _ P3 P4 P5) as [P7|P7].*)\n  (*+ destruct (less_ex _ _ P3 P4 P7) as [x [P8 P9]].*)\n    (*rewrite <- P9 in P6.*)\n    (*rewrite (distributive_l n p (S(x))) in P6.*)\n    (*rewrite (add_associative (m ×ₙ p) (n ×ₙ p) (n ×ₙ S( x))) in P6.*)\n    (*rewrite (add_commutative (m ×ₙ p +ₙ n ×ₙ p) (n ×ₙ S( x))) in P6.*)\n    (*rewrite (distributive_l m p (S(x))) in P6.*)\n    (*rewrite (add_cyc (m ×ₙ p) (m ×ₙ S( x)) (n ×ₙ p)) in P6.*)\n    (*rewrite (add_commutative (m ×ₙ p +ₙ n ×ₙ p) (m ×ₙ S( x))) in P6.*)\n    (*assert (n ×ₙ S( x) = m ×ₙ S( x)) as P10.*)\n    (*{ apply (add_cancellation _ _ (m ×ₙ p +ₙ n ×ₙ p)).*)\n      (*all: is_nat. }*)\n    (*symmetry.*)\n    (*apply (multi_cancellation _ _ x).*)\n    (*all: is_nat.*)\n  (*+ destruct (less_ex _ _ P4 P3 P7) as [x [P8 P9]].*)\n    (*rewrite <- P9 in P6.*)\n    (*rewrite (distributive_l m q (S(x))) in P6.*)\n    (*rewrite (add_cyc (m ×ₙ q) (m ×ₙ S(x)) (n ×ₙ q)) in P6.*)\n    (*rewrite (add_commutative (m ×ₙ q +ₙ n ×ₙ q) (m ×ₙ S(x))) in P6.*)\n    (*rewrite (distributive_l n q (S(x))) in P6.*)\n    (*rewrite (add_associative (m ×ₙ q) (n ×ₙ q) (n ×ₙ S( x))) in P6.*)\n    (*rewrite (add_commutative (m ×ₙ q +ₙ n ×ₙ q) (n ×ₙ S( x))) in P6.*)\n    (*assert (m ×ₙ S( x) = n ×ₙ S( x)) as P10.*)\n    (*{ apply (add_cancellation _ _ (m ×ₙ q +ₙ n ×ₙ q)).*)\n      (*all: is_nat. }*)\n    (*apply (multi_cancellation _ _ x).*)\n    (*all: is_nat.*)\n(*Qed.*)\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/Nat/Order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.662331623436819}}
{"text": "Require Import BigO.Notation.\nRequire Import BigO.Util.DecField.\nRequire Import BigO.Util.Vectorspace.\nRequire Import MathClasses.interfaces.abstract_algebra.\nRequire Import MathClasses.interfaces.canonical_names.\nRequire Import MathClasses.interfaces.orders.\nRequire Import MathClasses.interfaces.vectorspace.\nRequire Import MathClasses.orders.semirings.\nRequire Import MathClasses.orders.dec_fields.\n\n(**\n All notations absorb constant multiples.\n *)\n\nSection Constants.\n  Context `{@SemiNormedSpace\n              K V\n              Ke Kle Kzero Knegate Kabs Vnorm Ke Kplus Kmult Kzero Kone Knegate Krecip\n              Ve Vop Vunit Vnegate smkv\n           }.\n  Context `{!FullPseudoSemiRingOrder Kle Klt}.\n  Context `{forall x y : K, Decision (x = y)}.\n\n  Lemma big_O_absorbs_constants : ∀ f g : (V → V),\n      f ∈ O(g) -> forall c : K, 0 < c -> (fun n => c · f n) ∈ O(g).\n    intros f g f_O_g c.\n    destruct f_O_g as [k [zero_lt_k [n0 [zero_lt_n0 f_O_h]]]].\n    unfold big_O.\n    exists (c * k); split; try now apply (pseudo_srorder_pos_mult_compat c k).\n    exists n0; split; try assumption.\n    intros n n0_le_n.\n    rewrite sm_and_mult; try assumption.\n    rewrite <- associativity.\n    apply order_preserving_mult_le; try assumption.\n    now apply f_O_h.\n  Qed.\n\n  Lemma big_Omega_absorbs_constants : ∀ f g : (V → V),\n      f ∈ Ω(g) -> forall c : K, 0 < c -> (fun n => c · f n) ∈ Ω(g).\n    intros f g f_O_g c.\n    destruct f_O_g as [k [zero_lt_k [n0 [zero_lt_n0 f_O_h]]]].\n    unfold big_Omega.\n    exists (c * k); split; try now apply (pseudo_srorder_pos_mult_compat c k).\n    exists n0; split; try assumption.\n    intros n n0_le_n.\n    rewrite sm_and_mult; try assumption.\n    rewrite <- associativity.\n    apply order_preserving_mult_le; try assumption.\n    now apply f_O_h.\n  Qed.\n\n  Lemma dec_recip_inverse_gt : ∀ c : K, 0 < c -> c / c = 1.\n    intros c zero_lt_c.\n    apply dec_recip_inverse.\n    apply trivial_apart.\n    apply apart_iff_total_lt.\n    now right.\n  Qed.\n\n  Lemma little_o_absorbs_constants : ∀ f g : (V → V),\n      f ∈ o(g) -> forall c : K, 0 < c -> (fun n => c · f n) ∈ o(g).\n    intros f g f_o_g c zero_lt_c.\n    unfold little_o.\n    intros k zero_lt_k.\n    destruct (f_o_g (/c * k)) as [n0 [zero_lt_n0 f_o_g']].\n    - (apply pos_mult_compat; try trivial; try now apply pos_dec_recip_compat).\n    - exists n0; split; try assumption.\n      intros n n0_le_n.\n      assert (∥ f n ∥ ≤ /c * k * (∥ g n ∥)) by (now apply f_o_g').\n      rewrite sm_and_mult; try assumption.\n      setoid_replace k with (1 * k) by (now rewrite left_identity).\n      setoid_replace 1 with (c * /c) by (symmetry; now apply dec_recip_inverse_gt).\n      do 2 (rewrite <- associativity).\n      apply (order_preserving_mult_le (∥ f n ∥) (/ c * (k * (∥ g n ∥))) c);\n        try assumption.\n      now rewrite associativity.\n  Qed.\n\n  Lemma little_omega_absorbs_constants : ∀ f g : (V → V),\n      f ∈ ω(g) -> forall c : K, 0 < c -> (fun n => c · f n) ∈ ω(g).\n    intros f g f_ω_g c zero_lt_c.\n    unfold little_omega.\n    intros k zero_lt_k.\n    destruct (f_ω_g (/c * k)) as [n0 [zero_lt_n0 f_ω_g']].\n    - (apply pos_mult_compat; try trivial; try now apply pos_dec_recip_compat).\n    - exists n0; split; try assumption.\n      intros n n0_le_n.\n      assert (/c * k * (∥g n∥) ≤ ∥f n∥) by (now apply f_ω_g').\n      rewrite sm_and_mult; try assumption.\n      setoid_replace k with (1 * k) by (now rewrite left_identity).\n      setoid_replace 1 with (c * /c) by (symmetry; now apply dec_recip_inverse_gt).\n      do 2 (rewrite <- associativity).\n      apply (order_preserving_mult_le (/ c * (k * (∥ g n ∥))) (∥f n∥) c);\n        try assumption.\n      now rewrite associativity.\n  Qed.\nEnd Constants.", "meta": {"author": "langston-barrett", "repo": "coq-big-o", "sha": "8042cc068b02574ac94de469a55a9f89268616c3", "save_path": "github-repos/coq/langston-barrett-coq-big-o", "path": "github-repos/coq/langston-barrett-coq-big-o/coq-big-o-8042cc068b02574ac94de469a55a9f89268616c3/src/Facts/Constants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137296, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.6622969430021771}}
{"text": "Require Import Basics.\nRequire Import Pointed.Core.\nRequire Import Colimits.Pushout.\n\n(* Here we define the Wedge sum of two pointed types *)\n\nLocal Open Scope pointed_scope.\n\nDefinition Wedge (X Y : pType) : pType\n  := Build_pType\n    (Pushout (fun _ : Unit => point X) (fun _ => point Y))\n    (pushl (point X)).\n\nNotation \"X \\/ Y\" := (Wedge X Y) : pointed_scope.\n\nDefinition wglue {X Y : pType}\n  : pushl (point X) = (pushr (point Y) : X \\/ Y) := pglue tt.\n\nDefinition wedge_incl {X Y : pType} : X \\/ Y -> X * Y :=\n Pushout_rec _ (fun x => (x, point Y)) (fun y => (point X, y)) \n  (fun _ : Unit => idpath).\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/Homotopy/Wedge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676514011486, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6622969361867703}}
{"text": "(**************************************************************************)\n(*  Copyright 2010 2011, Thomas Braibant                                  *)\n(*                                                                        *)\n(**************************************************************************)\n\n(** Generalized n-ary disjoint sums  *)\n\nRequire Import Common EqT Finite. \nRequire List. \n\nSection Sumn. \n  Variable A : Type. \n\n  Fixpoint sumn (n : nat) : Type :=\n    match n with \n      | 0 => zero\n      | S n => (A + sumn n  )%type\n    end.\n\n  \n  Definition expand  n  (x : sumn  (S n) ) : (A + sumn   n)%type := id x.\n  Definition compact n (x : A + sumn  n) : sumn (S n) := id x. \n\n  Fixpoint  sumn_add x y {struct x}:\n    sumn x + sumn  y ->  sumn  (x+y) :=\n    match x with \n      | 0 => fun e => match e with inl e => match e with end | inr e => e end\n      | S p => fun e => \n        match e with \n          |inl asp => \n            let asp := expand p asp in\n              match asp with\n                | inl el => inl  el\n                | inr t => inr  (sumn_add _ _ (inl t))\n              end\n          |inr ay => inr  (sumn_add _ _ (inr  ay))\n      end         \n  end. \n\n  \n  Fixpoint sumn_add' x y {struct x}:   sumn (x+y) -> sumn  x + sumn  y :=\n    match x with \n      | 0 => fun e => inr  e\n      | S p => fun e => \n        match e with\n          | inl e => inl (inl  e)\n          | inr t => \n            let t' := sumn_add' _ _ t in \n              match t' with\n                | inl t0 => inl  (inr t0)\n                | inr t0 => inr t0\n              end\n        end\n    end. \n\n \n  Definition sumn_1 : sumn  1 -> A := fun e => \n    match e with \n      | inl e => e\n      | inr e => match e with end\n    end.\n\n \nEnd Sumn. \n\n\nNotation \" ! \" := (zero_rect _ _).\n\nSection ops. \n  Variable A B : Type. \n  Definition sumn_zip  n : sumn A n + sumn B n -> sumn (A+B) n.\n  Proof. \n    induction n; firstorder. \n  Defined.\n  \n  Definition sumn_unzip n : sumn (A + B) n -> sumn A n + sumn B n. \n  Proof.\n    induction n; firstorder. \n  Defined.\n  \n  Definition sumn_forget_left n: sumn A n -> sumn (A + B) n . \n  Proof. \n    induction n. \n    intros []. \n    intros X; apply compact; apply expand in X; destruct X as [X |X]. \n    repeat left; apply X. \n    right. apply (IHn X).\n  Defined. \n  \n  Definition sumn_forget_right n : sumn B n -> sumn (A + B) n . \n  Proof. \n    induction n. \n    intros []. \n    intros X; apply compact; apply expand in X; destruct X as [X |X]. \n    auto. \n    auto. \n  Defined. \n\n  Fixpoint sumn_map n (f : A -> B): sumn A n -> sumn B n  :=\n    match n with \n      | 0 => fun e => match e with end\n      | S p => fun e => match expand A p e with \n                     | inl e => inl (f e)\n                     | inr e => inr (sumn_map p f e)\n                      end\n    end.\n  \n  Fixpoint sumn_repeat n : sumn A n -> A := \n    match n with \n      | 0 => fun e => match e with end\n      | S p => fun e => match expand A p e with \n                        | inl e => e\n                        | inr e => sumn_repeat p e \n                      end\n    end.\n                                             \n  \nEnd ops. \n\nSection Eq. \n  Context `{eqT}. \n  \n  Fixpoint eqb_sumn n : sumn A n -> sumn A n -> bool := (* bug avec Program : insere des obligations *)\n    match n with \n      | 0 => fun x _ => match x with end \n      | S p => fun x y => match x, y with\n                          | inl a, inl b => equal a b\n                          | inr a, inr b => eqb_sumn p a b\n                          | _ , _  => false\n                        end\n    end.\n  \n  Lemma eqb_sumn_reflect n : \n      forall x y : sumn A n, Bool.reflect (x = y) (eqb_sumn n x y).\n  Proof. \n        induction n.\n    simpl; intros; tauto.\n    simpl sumn. \n    intros [x|x] [y|y];\n    simpl eqb_sumn. \n    case (_eqr); intros Hxy; constructor. \n    subst. reflexivity. \n    intros H'.  injection H'. clear H'; intros H'; subst; tauto. \n  \n    constructor. discriminate. \n    constructor. discriminate. \n    specialize (IHn x y).\n    revert IHn. \n    case (eqb_sumn n x y); intros H'; inversion H'.  subst. constructor. reflexivity. \n\n    constructor. \n    intros H''.  injection H''. clear H''; intros H''; subst; tauto. \n  Qed.\n  Global Instance eqT_sumn {n}: eqT (sumn A n) :=\n    {| equal := eqb_sumn n|}.\n  Proof. \n    apply eqb_sumn_reflect.\n  Defined.\n\nEnd Eq. \n\nFixpoint flatten A (l : list (list A)) : list A :=\n    match l with \n      | nil => nil\n      | cons t q => List.app t (flatten A q)\n    end.\n  \nSection Fin_sumn.\n  Context {A : Type} {F : Fin A}.\n \n  Fixpoint enum_sumn n : list (sumn A n) :=\n    match n with \n      | 0 => [ :: ]%list\n      | S p => enum_sum (enum A) (enum_sumn p)\n    end. \n  Instance local {n}: eqT (sumn A n) :=\n    let f := F in match f with\n                    | {| eq_fin := eq_fin |} => eqT_sumn\n                  end.\n\n  Lemma fin_sumn_axiom n:  forall x : sumn A n, count (equal x) (enum_sumn n) = 1.\n  Proof. \n        induction n. simpl; tauto. \n    simpl.\n    intros [x|x];\n    unfold enum_sum;\n    rewrite count_app.\n    assert (H' := @axiom A F x). \n    rewrite <- H'. \n    match goal with \n      |- ?x + ?y = _ => replace y with 0\n    end. \n    Require Import Arith. \n    rewrite plus_0_r. \n    apply count_map. \n    intros a.\n    do 2 case _eqr; try  reflexivity; intros; subst; try tauto. \n    injection e. tauto. \n\n    symmetry. \n    clear. induction (enum_sumn n); simpl; try reflexivity.   \n    case _eqr.     intros; discriminate. intros. auto. \n\n    match goal with \n      |- ?y + ?x = _ => replace y with 0\n    end. \n    Require Import Arith. \n    rewrite plus_0_l. \n    rewrite <- (IHn x). \n    apply count_map. \n    intros a.\n    do 2 case _eqr; try  reflexivity; intros; subst; try tauto. \n    injection e. tauto. \n\n    symmetry. \n    clear. induction (enum A); simpl; try reflexivity.   \n    case _eqr.     intros; discriminate. intros. auto.  \n  Qed.\n  Global Instance Fin_sumn {n} : Fin (sumn A n) :=\n    {| \n      eq_fin := local;\n      enum := enum_sumn n\n    |}.\n  Proof. \n    apply fin_sumn_axiom.\n  Defined.\nEnd Fin_sumn. \n", "meta": {"author": "joaopizani", "repo": "coquet-2013", "sha": "d7e5ef42ff1d61507246908565091d2adc754b99", "save_path": "github-repos/coq/joaopizani-coquet-2013", "path": "github-repos/coq/joaopizani-coquet-2013/coquet-2013-d7e5ef42ff1d61507246908565091d2adc754b99/Sumn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6622228049361701}}
{"text": "Require Import List.\nImport ListNotations.\n\n(* elementary category *)\nDefinition elem_cat: Type := nat.\n\nInductive formula :=\n| var (a: elem_cat)\n| leftDiv (a b: formula)\n| rightDiv (a b: formula)\n| mul (a b: formula).\n\nNotation \"x ° y\" := (mul x y) (at level 40, left associativity).\nNotation \"x // y\" := (rightDiv x y) (at level 40, no associativity).\nNotation \"x \\\\ y\" := (leftDiv x y) (at level 40, no associativity).\n\nDefinition str := list formula.\nDefinition sequent: Type := (str * formula).\n\nDefinition nonEmptySequent (s: sequent) :=\n  match s with\n    (x, A) => x <> []\n  end.\n\nNotation \"s ⇒ c\" := (s, c) (at level 50, no associativity).\n\nInductive genProof (Γ: list sequent): sequent -> Prop :=\n| inGamma (s: sequent) (_: In s Γ) (_: nonEmptySequent s): genProof Γ s\n| identity (a: formula): genProof Γ ([a], a)\n| leftArrow (y: str) (X: formula) (x: str) (A B: formula) (z: str) (C: formula)\n            (p1: genProof Γ ((X::x) ⇒ A))\n            (p2: genProof Γ ((y ++ B :: z) ⇒ C))\n  : genProof Γ ((y ++ (X::x) ++ (A \\\\ B) :: z) ⇒ C)\n| arrowLeft (X: formula) (x: str) (A B: formula) (p: genProof Γ ((A :: X :: x), B))\n  : genProof Γ ((X::x) ⇒ A \\\\ B)\n| rightArrow (y: str) (B A: formula) (X: formula) (x z: str) (C: formula)\n             (p1: genProof Γ ((X::x) ⇒ A))\n             (p2: genProof Γ ((y ++ B::z) ⇒ C))\n  : genProof Γ ((y ++ (B // A) :: X :: x ++ z) ⇒ C)\n| arrowRight (X: formula) (x: str) (A B: formula) (p: genProof Γ ((X :: x ++ [A]) ⇒ B))\n  : genProof Γ ((X::x) ⇒ B // A)\n| mulArrow (x: str) (A B: formula) (y: str) (C: formula)\n           (p: genProof Γ ((x ++ A :: B :: y) ⇒ C))\n  : genProof Γ ((x ++ (A ° B) :: y) ⇒ C)\n| arrowMul (X: formula) (x: str) (Y: formula) (y: str) (A B: formula)\n           (p1: genProof Γ ((X::x) ⇒ A))\n           (p2: genProof Γ ((Y::y) ⇒ B))\n  : genProof Γ ((X :: x ++ Y :: y) ⇒ A ° B).\n\nDefinition proofWithNonEmptyPremises (Γ: list sequent) (s: sequent): Prop :=\n  (forall (s': sequent), In s' Γ -> nonEmptySequent s') /\\\n  genProof Γ s.\n\nNotation \"Γ ⊢ s\" := (proofWithNonEmptyPremises Γ s) (at level 60, no associativity).\n", "meta": {"author": "gogabr", "repo": "lambekMikulas", "sha": "12f2cf11fe3e4dc65cf6ba8fb5a331c42198fbd3", "save_path": "github-repos/coq/gogabr-lambekMikulas", "path": "github-repos/coq/gogabr-lambekMikulas/lambekMikulas-12f2cf11fe3e4dc65cf6ba8fb5a331c42198fbd3/src/LambekSyntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6622227917755303}}
{"text": "Module RedBlackTree.\n\nInductive Color: Set := Red | Black.\n\nInductive Node {T: Type}: Type :=\n  | make_node: Color -> T -> Node.\n\nDefinition GetColor {T: Type} (n: @Node T): Color :=\n  match n with\n  | make_node Red _ => Red\n  | make_node Black _ => Black\n  end.\n\nDefinition NatNode: Set := @Node nat.\n\nExample redTwo: NatNode := make_node Red 2.\nExample blackThree: NatNode := make_node Black 3.\n\nCompute GetColor redTwo.\nCompute GetColor blackThree.\n\nRecord Tree (T: Type): Type := make_tree {\n  get_root: @Node T\n}.\n\nExample twoTree: Tree nat := make_tree nat redTwo.\n\n\n\n", "meta": {"author": "visavishesh", "repo": "puzzlcrawl", "sha": "efa1f2117e007c995b727670753d59fd001e6a74", "save_path": "github-repos/coq/visavishesh-puzzlcrawl", "path": "github-repos/coq/visavishesh-puzzlcrawl/puzzlcrawl-efa1f2117e007c995b727670753d59fd001e6a74/RedBlackTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6622227888537037}}
{"text": "Require Import HSet WildCat.\nRequire Import Groups.QuotientGroup Groups.ShortExactSequence.\nRequire Import AbelianGroup AbGroups.Biproduct AbHom.\nRequire Import Homotopy.ExactSequence Pointed.\nRequire Import Modalities.ReflectiveSubuniverse.\n\nLocal Open Scope pointed_scope.\nLocal Open Scope type_scope.\nLocal Open Scope mc_add_scope.\n\n(** * Short exact sequences of abelian groups *)\n\n(** A short exact sequence of abelian groups consists of a monomorphism [i : A -> E] and an epimorphism [p : E -> B] such that the image of [i] equals the kernel of [p]. Later we will consider short exact sequences up to isomorphism by 0-truncating the type [AbSES] defined below. An isomorphism class of short exact sequences is called an extension. *)\n\nDeclare Scope abses_scope.\nLocal Open Scope abses_scope.\n\n(** The type of short exact sequences [A -> E -> B] of abelian groups. We decorate it with (') to reserve the undecorated name for the structured version. *)\nRecord AbSES' {B A : AbGroup@{u}} := Build_AbSES {\n    middle :  AbGroup@{u};\n    inclusion : A $-> middle;\n    projection : middle $-> B;\n    isembedding_inclusion : IsEmbedding inclusion;\n    issurjection_projection : IsSurjection projection;\n    isexact_inclusion_projection : IsExact (Tr (-1)) inclusion projection;\n  }.\n\n(** Given a short exact sequence [A -> E -> B : AbSES B A], we coerce it to [E]. *)\nCoercion middle : AbSES' >-> AbGroup.\n\nGlobal Existing Instances isembedding_inclusion issurjection_projection isexact_inclusion_projection.\n\nArguments AbSES' B A : clear implicits.\nArguments Build_AbSES {B A}.\n\n(** TODO Figure out why printing this term eats memory and seems to never finish. *)\nLocal Definition issig_abses_do_not_print {B A : AbGroup} : _ <~> AbSES' B A := ltac:(issig).\n\n(** [make_equiv] is slow if used in the context of the next result, so we give the abstract form of the goal here. *)\nLocal Definition issig_abses_helper {AG : Type} {P : AG -> Type} {Q : AG -> Type}\n      {R : forall E, P E -> Type} {S : forall E, Q E -> Type} {T : forall E, P E -> Q E -> Type}\n  : {X : {E : AG & P E * Q E} & R _ (fst X.2) * S _ (snd X.2) * T _ (fst X.2) (snd X.2)}\n      <~> {E : AG & {H0 : P E & {H1 : Q E & {_ : R _ H0 & {_ : S _ H1 & T _ H0 H1}}}}}\n  := ltac:(make_equiv).\n\n(** A more useful organization of [AbSES'] as a sigma-type. *)\nDefinition issig_abses {B A : AbGroup}\n  : {X : {E : AbGroup & (A $-> E) * (E $-> B)} &\n           (IsEmbedding (fst X.2)\n            * IsSurjection (snd X.2)\n            * IsExact (Tr (-1)) (fst X.2) (snd X.2))}\n      <~> AbSES' B A\n  := issig_abses_do_not_print oE issig_abses_helper.\n\nDefinition iscomplex_abses {A B : AbGroup} (E : AbSES' B A)\n  : IsComplex (inclusion E) (projection E)\n  := cx_isexact.\n\n(** [AbSES' B A] is pointed by the split sequence [A -> A+B -> B]. *)\nGlobal Instance ispointed_abses {B A : AbGroup@{u}}\n  : IsPointed (AbSES' B A).\nProof.\n  rapply (Build_AbSES (ab_biprod A B) ab_biprod_inl ab_biprod_pr2).\n  snrapply Build_IsExact.\n  - srapply phomotopy_homotopy_hset; reflexivity.\n  - intros [[a b] p]; cbn; cbn in p.\n    rapply contr_inhabited_hprop.\n    apply tr.\n    exists a.\n    rapply path_sigma_hprop; cbn.\n    exact (path_prod' idpath p^).\nDefined.\n\n(** The pointed type of short exact sequences. *)\nDefinition AbSES (B A : AbGroup@{u}) : pType\n  := [AbSES' B A, _].\n\n(** ** Paths in [AbSES B A] *)\n\nDefinition abses_path_data_iso\n  {B A : AbGroup@{u}} (E F : AbSES B A)\n  := {phi : GroupIsomorphism E F\n            & (phi $o inclusion _ == inclusion _)\n              * (projection _ == projection _ $o phi)}.\n\n(** Having the path data in a slightly different form is useful for [equiv_path_abses_iso]. *)\nLocal Lemma shuffle_abses_path_data_iso `{Funext}\n  {B A : AbGroup@{u}} (E F : AbSES B A)\n  : (abses_path_data_iso E F)\n      <~> {phi : GroupIsomorphism E F\n                 & (phi $o inclusion _ == inclusion _)\n                   * (projection _ $o grp_iso_inverse phi\n                      == projection _)}.\nProof.\n  srapply equiv_functor_sigma_id; intro phi.\n  srapply equiv_functor_prod'.\n  1: exact equiv_idmap.\n  srapply (equiv_functor_forall' phi^-1); intro e; cbn.\n  apply equiv_concat_r.\n  exact (ap _ (eisretr _ _)).\nDefined.\n\n(** Paths in [AbSES] correspond to isomorphisms between the [middle]s respecting [inclusion] and [projection]. Below we prove the stronger statement [equiv_path_abses], which uses this result. *)\nProposition equiv_path_abses_iso `{Univalence}\n  {B A : AbGroup@{u}} {E F : AbSES' B A}\n  : abses_path_data_iso E F <~> E = F.\nProof.\n  refine (_ oE shuffle_abses_path_data_iso E F).\n  refine (equiv_ap_inv issig_abses _ _ oE _).\n  refine (equiv_path_sigma_hprop _ _ oE _).\n  refine (equiv_path_sigma _ _ _ oE _).\n  srapply equiv_functor_sigma'.\n  1: exact equiv_path_abgroup.\n  intro q; lazy beta.\n  snrefine (equiv_concat_l _ _ oE _).\n  1: exact (q $o inclusion _, projection _ $o grp_iso_inverse q).\n  2: { refine (equiv_path_prod _ _ oE _).\n       exact (equiv_functor_prod'\n                equiv_path_grouphomomorphism\n                equiv_path_grouphomomorphism). }\n  refine (transport_prod _ _ @ _).\n  apply path_prod'.\n  - apply transport_iso_abgrouphomomorphism_from_const.\n  - apply transport_iso_abgrouphomomorphism_to_const.\nDefined.\n\n(** It follows that [AbSES B A] is 1-truncated. *)\nGlobal Instance istrunc_abses `{Univalence} {B A : AbGroup@{u}}\n  : IsTrunc 1 (AbSES B A).\nProof.\n  intros E F.\n  refine (istrunc_equiv_istrunc _ equiv_path_abses_iso (n:=0)).\n  rapply istrunc_sigma.\n  apply ishset_groupisomorphism.\nDefined.\n\nDefinition path_abses_iso `{Univalence} {B A : AbGroup@{u}}\n  {E F : AbSES B A}\n  (phi : GroupIsomorphism E F) (p : phi $o inclusion _ == inclusion _)\n  (q : projection _ == projection _ $o phi)\n  : E = F := equiv_path_abses_iso (phi; (p,q)).\n\n(** Given [p] and [q], the map [phi] just above is automatically an isomorphism. Showing this requires the \"short five lemma.\" *)\n\n(** A special case of the \"short 5-lemma\" where the two outer maps are (definitionally) identities. *)\nLemma short_five_lemma {B A : AbGroup@{u}}\n  {E F : AbSES B A} (phi : GroupHomomorphism E F)\n  (p0 : phi $o inclusion E == inclusion F) (p1 : projection E == projection F $o phi)\n  : IsEquiv phi.\nProof.\n  apply isequiv_surj_emb.\n  - intro f.\n    rapply contr_inhabited_hprop.\n    (** Since [projection E] is epi, we can pull [projection F f] back to [e0 : E].*)\n    assert (e0 : Tr (-1) (hfiber (projection E) (projection F f))).\n    1: apply issurjection_projection.\n    strip_truncations.\n    (** The difference [f - (phi e0.1)] is sent to [0] by [projection F], hence lies in [A]. *)\n    assert (a : Tr (-1) (hfiber (inclusion F) (f + (- phi e0.1)))).\n    1: { refine (isexact_preimage (Tr (-1)) (inclusion F) (projection F) _ _).\n         refine (grp_homo_op _ _ _ @ _).\n         refine (ap _ (grp_homo_inv _ _) @ _).\n         apply (grp_moveL_1M)^-1.\n         exact (e0.2^ @ p1 e0.1). }\n    strip_truncations.\n    refine (tr (inclusion E a.1 + e0.1; _)).\n    refine (grp_homo_op _ _ _ @ _).\n    refine (ap (fun x => x + phi e0.1) (p0 a.1 @ a.2) @ _).\n    refine ((grp_assoc _ _ _)^ @ _).\n    refine (ap _ (left_inverse (phi e0.1)) @ _).\n    apply grp_unit_r.\n  - apply isembedding_grouphomomorphism.\n    intros e p.\n    assert (a : Tr (-1) (hfiber (inclusion E) e)).\n    1: { refine (isexact_preimage _ (inclusion E) (projection E) _ _).\n         exact (p1 e @ ap (projection F) p @ grp_homo_unit _). }\n    strip_truncations.\n    refine (a.2^ @ ap (inclusion E ) _ @ grp_homo_unit (inclusion E)).\n    rapply (isinj_embedding (inclusion F) _ _).\n    refine ((p0 a.1)^ @ (ap phi a.2) @ p @ (grp_homo_unit _)^).\nDefined.\n\n(** Below we prove that homomorphisms respecting [projection] and [inclusion] correspond to paths in [AbSES B A]. We refer to such homomorphisms simply as path data in [AbSES B A]. *)\nDefinition abses_path_data {B A : AbGroup@{u}} (E F : AbSES B A)\n  := {phi : GroupHomomorphism E F\n            & (phi $o inclusion _ == inclusion _)\n              * (projection _ == projection _ $o phi)}.\n\nDefinition abses_path_data_to_iso `{Funext} {B A : AbGroup@{u}} (E F: AbSES B A)\n  : abses_path_data E F -> abses_path_data_iso E F.\nProof.\n  - intros [phi [p q]].\n    exact ({| grp_iso_homo := phi; isequiv_group_iso := short_five_lemma phi p q |}; (p, q)).\nDefined.\n\nProposition equiv_path_abses_data `{Funext} {B A : AbGroup@{u}} (E F: AbSES B A)\n  : abses_path_data E F <~> abses_path_data_iso E F.\nProof.\n  srapply equiv_adjointify.\n  - apply abses_path_data_to_iso.\n  - srapply (functor_sigma (grp_iso_homo _ _)).\n    exact (fun _ => idmap).\n  - intros [phi [p q]].\n    apply path_sigma_hprop.\n    by apply equiv_path_groupisomorphism.\n  - reflexivity.\nDefined.\n\nDefinition equiv_path_abses `{Univalence} {B A : AbGroup@{u}} {E F : AbSES B A}\n  : abses_path_data E F <~> E = F\n  := equiv_path_abses_iso oE equiv_path_abses_data E F.\n\nDefinition path_abses `{Univalence} {B A : AbGroup@{u}}\n  {E F : AbSES B A} (phi : middle E $-> F)\n  (p : phi $o inclusion _ == inclusion _) (q : projection _ == projection _ $o phi)\n  : E = F := equiv_path_abses (phi; (p,q)).\n\n(** *** The wildcat of short exact sequences *)\n\nGlobal Instance isgraph_abses_path_data {A B : AbGroup@{u}} (E F : AbSES B A)\n  : IsGraph (abses_path_data_iso E F)\n  := isgraph_induced (grp_iso_homo _ _ o pr1).\n\nGlobal Instance is01cat_abses_path_data {A B : AbGroup@{u}} (E F : AbSES B A)\n  : Is01Cat (abses_path_data_iso E F)\n  := is01cat_induced (grp_iso_homo _ _ o pr1).\n\nGlobal Instance is0gpd_abses_path_data {A B : AbGroup@{u}} (E F : AbSES B A)\n  : Is0Gpd (abses_path_data_iso E F)\n  := is0gpd_induced (grp_iso_homo _ _ o pr1).\n\nGlobal Instance isgraph_abses {A B : AbGroup@{u}} : IsGraph (AbSES B A)\n  := Build_IsGraph _ abses_path_data_iso.\n\n(** The path data corresponding to [idpath]. *)\nDefinition abses_path_data_1 {B A : AbGroup@{u}} (E : AbSES B A)\n  : E $-> E := (grp_iso_id; (fun _ => idpath, fun _ => idpath)).\n\n(** We can compose path data in [AbSES B A]. *)\nDefinition abses_path_data_compose {B A : AbGroup@{u}} {E F G : AbSES B A}\n           (p : E $-> F) (q : F $-> G) : E $-> G\n  := (q.1 $oE p.1; ((fun x => ap q.1 (fst p.2 x) @ fst q.2 x),\n                     (fun x => snd p.2 x @ snd q.2 (p.1 x)))).\n\nGlobal Instance is01cat_abses {A B : AbGroup@{u}}\n  : Is01Cat (AbSES B A)\n  := Build_Is01Cat _ _ abses_path_data_1\n       (fun _ _ _ q p => abses_path_data_compose p q).\n\nDefinition abses_path_data_inverse\n  {B A : AbGroup@{u}} {E F : AbSES B A}\n  : (E $-> F) -> (F $-> E).\nProof.\n  intros [phi [p q]].\n  srefine (_; (_,_)).\n  - exact (grp_iso_inverse phi).\n  - intro a.\n    exact (ap _ (p a)^ @ eissect _ (inclusion E a)).\n  - intro a; simpl.\n    exact (ap (projection F) (eisretr _ _)^ @ (q _)^).\nDefined.\n\nGlobal Instance is0gpd_abses\n  {A B : AbGroup@{u}} : Is0Gpd (AbSES B A)\n  := {| gpd_rev := fun _ _ => abses_path_data_inverse |}.\n\nGlobal Instance is2graph_abses\n  {A B : AbGroup@{u}} : Is2Graph (AbSES B A)\n  := fun E F => isgraph_abses_path_data E F.\n\n(** [AbSES B A] forms a 1Cat *)\nGlobal Instance is1cat_abses {A B : AbGroup@{u}}\n  : Is1Cat (AbSES B A).\nProof.\n  snrapply Build_Is1Cat.\n  1: intros ? ?; apply is01cat_abses_path_data.\n  1: intros ? ?; apply is0gpd_abses_path_data.\n  3-5: cbn; reflexivity.\n  1,2: intros E F G f;\n  srapply Build_Is0Functor;\n  intros p q h e; cbn.\n  - exact (ap f.1 (h e)).\n  - exact (h (f.1 e)).\nDefined.\n\nGlobal Instance is1gpd_abses {A B : AbGroup@{u}}\n  : Is1Gpd (AbSES B A).\nProof.\n  rapply Build_Is1Gpd;\n    intros E F p e; cbn.\n  - apply eissect.\n  - apply eisretr.\nDefined.\n\nGlobal Instance hasmorext_abses `{Funext} {A B : AbGroup@{u}}\n  : HasMorExt (AbSES B A).\nProof.\n  srapply Build_HasMorExt;\n    intros E F f g.\n  srapply isequiv_homotopic'; cbn.\n  1: exact (((equiv_path_groupisomorphism _ _)^-1%equiv)\n              oE (equiv_path_sigma_hprop _ _)^-1%equiv).\n  intro p; by induction p.\nDefined.\n\n(** *** Path data lemmas *)\n\n(** We need to be able to work with path data as if they're paths. Our preference is to state things in terms of [abses_path_data_iso], since this lets us keep track of isomorphisms whose inverses compute. The \"abstract\" inverses produced by [short_five_lemma] do not compute well. *)\n\nDefinition equiv_path_abses_1 `{Univalence} {B A : AbGroup@{u}} {E : AbSES B A}\n  : equiv_path_abses_iso (abses_path_data_1 E) = idpath.\nProof.\n  apply (equiv_ap_inv' equiv_path_abses_iso).\n  refine (eissect _ _ @ _).\n  srapply path_sigma_hprop; simpl.\n  srapply equiv_path_groupisomorphism.\n  reflexivity.\nDefined.\n\nDefinition equiv_path_absesV_1 `{Univalence} {B A : AbGroup@{u}} {E : AbSES B A}\n  : (@equiv_path_abses_iso _ B A E E)^-1 idpath = Id E.\nProof.\n  apply moveR_equiv_M; symmetry.\n  apply equiv_path_abses_1.\nDefined.\n\nDefinition abses_path_data_V `{Univalence} {B A : AbGroup@{u}} {E F : AbSES B A}\n           (p : abses_path_data_iso E F)\n  : (equiv_path_abses_iso p)^ = equiv_path_abses_iso (abses_path_data_inverse p).\nProof.\n  revert p.\n  equiv_intro (equiv_path_abses_iso (E:=E) (F:=F))^-1 p; induction p.\n  refine (ap _ (eisretr _ _) @ _); symmetry.\n  nrefine (ap (equiv_path_abses_iso o abses_path_data_inverse) equiv_path_absesV_1 @ _).\n  refine (ap equiv_path_abses_iso gpd_strong_rev_1 @ _).\n  exact equiv_path_abses_1.\nDefined.\n\n(** Composition of path data corresponds to composition of paths. *)\nDefinition abses_path_compose_beta `{Univalence} {B A : AbGroup@{u}} {E F G : AbSES B A}\n          (p : E = F) (q : F = G)\n : p @ q = equiv_path_abses_iso\n             (abses_path_data_compose\n                (equiv_path_abses_iso^-1 p) (equiv_path_abses_iso^-1 q)).\nProof.\n  induction p, q.\n  refine (equiv_path_abses_1^ @ _).\n  apply (ap equiv_path_abses_iso).\n  apply path_sigma_hprop.\n  by apply equiv_path_groupisomorphism.\nDefined.\n\n(** A second beta-principle where you start with path data instead of actual paths. *)\nDefinition abses_path_data_compose_beta `{Univalence} {B A : AbGroup@{u}} {E F G : AbSES B A}\n           (p : abses_path_data_iso E F) (q : abses_path_data_iso F G)\n  : equiv_path_abses_iso p @ equiv_path_abses_iso q\n    = equiv_path_abses_iso (abses_path_data_compose p q).\nProof.\n  generalize p, q.\n  equiv_intro ((equiv_path_abses_iso (E:=E) (F:=F))^-1) x.\n  equiv_intro ((equiv_path_abses_iso (E:=F) (F:=G))^-1) y.\n  refine ((eisretr _ _ @@ eisretr _ _) @ _).\n  rapply abses_path_compose_beta.\nDefined.\n\n(** *** Homotopies of path data *)\n\nDefinition equiv_path_data_homotopy `{Univalence} {X : Type} {B A : AbGroup@{u}}\n           (f g : X -> AbSES B A) : (f $=> g) <~> f == g.\nProof.\n  srapply equiv_functor_forall_id; intro x; cbn.\n  srapply equiv_path_abses_iso.\nDefined.\n\nDefinition pmap_abses_const {B' A' B A : AbGroup@{u}} : AbSES B A -->* AbSES B' A'\n  := Build_BasepointPreservingFunctor (const pt) (Id pt).\n\nDefinition to_pointed `{Univalence} {B' A' B A : AbGroup@{u}}\n  : (AbSES B A -->* AbSES B' A') -> (AbSES B A ->* AbSES B' A')\n  := fun f => Build_pMap _ _ f (equiv_path_abses_iso (bp_pointed f)).\n\nLemma pmap_abses_const_to_pointed `{Univalence} {B' A' B A : AbGroup@{u}}\n  : pconst ==* to_pointed (@pmap_abses_const B' A' B A).\nProof.\n  srapply Build_pHomotopy.\n  1: reflexivity.\n  apply moveL_pV.\n  refine (concat_1p _ @ _).\n  apply equiv_path_abses_1.\nDefined.\n\nLemma abses_ap_fmap `{Univalence} {B0 B1 A0 A1 : AbGroup@{u}}\n      (f : AbSES B0 A0 -> AbSES B1 A1) `{!Is0Functor f, !Is1Functor f}\n      {E F : AbSES B0 A0} (p : E $== F)\n  : ap f (equiv_path_abses_iso p) = equiv_path_abses_iso (fmap f p).\nProof.\n  revert p.\n  apply (equiv_ind equiv_path_abses_iso^-1%equiv);\n    intro p.\n  induction p.\n  refine (ap (ap f) (eisretr _ _) @ _).\n  nrefine (_ @ ap equiv_path_abses_iso _).\n  2: { rapply path_hom.\n       srefine (_ $@ fmap2 _ _).\n       2: exact (Id E).\n       2: intro x; reflexivity.\n       exact (fmap_id f _)^$. }\n  exact equiv_path_abses_1^.\nDefined.\n\nDefinition to_pointed_compose `{Univalence} {B0 B1 B2 A0 A1 A2 : AbGroup@{u}}\n           (f : AbSES B0 A0 -->* AbSES B1 A1) (g : AbSES B1 A1 -->* AbSES B2 A2)\n           `{!Is1Functor f, !Is1Functor g}\n  : to_pointed g o* to_pointed f ==* to_pointed (g $o* f).\nProof.\n  srapply Build_pHomotopy.\n  1: reflexivity.\n  lazy beta.\n  nrapply moveL_pV.\n  nrefine (concat_1p _ @ _).\n  unfold pmap_compose, Build_pMap, pointed_fun, point_eq, dpoint_eq.\n  refine (_ @ ap (fun x => x @ _) _^).\n  2: apply (abses_ap_fmap g).\n  nrefine (_ @ (abses_path_data_compose_beta _ _)^).\n  nrapply (ap equiv_path_abses_iso).\n  rapply path_hom.\n  reflexivity.\nDefined.\n\nDefinition equiv_ptransformation_phomotopy `{Univalence} {B' A' B A : AbGroup@{u}}\n           {f g : AbSES B A -->* AbSES B' A'}\n  : f $=>* g <~> to_pointed f ==* to_pointed g.\nProof.\n  refine (issig_pforall _ _ oE _).\n  apply (equiv_functor_sigma' (equiv_path_data_homotopy f g)); intro h.\n  refine (equiv_concat_r _ _ oE _).\n  1: exact ((abses_path_data_compose_beta _ _)^ @ ap (fun x => _ @ x) (abses_path_data_V _)^).\n  refine (equiv_ap' equiv_path_abses_iso _ _ oE _).\n  refine (equiv_path_sigma_hprop _ _ oE _).\n  apply equiv_path_groupisomorphism.\nDefined.\n\n(** *** Characterisation of loops of short exact sequences *)\n\n(** Endomorphisms of the trivial short exact sequence in [AbSES B A] correspond to homomorphisms [B -> A]. *)\nLemma abses_endomorphism_trivial `{Funext} {B A : AbGroup@{u}}\n  : {phi : GroupHomomorphism (point (AbSES B A)) (point (AbSES B A)) &\n             (phi o inclusion _ == inclusion _)\n             * (projection _ == projection _ o phi)}\n      <~> (B $-> A).\nProof.\n  srapply equiv_adjointify.\n  - intros [phi _].\n    exact (ab_biprod_pr1 $o phi $o ab_biprod_inr).\n  - intro f.\n    snrefine (_;_).\n    + refine (ab_biprod_rec ab_biprod_inl _).\n      refine (ab_biprod_corec f grp_homo_id).\n    + split; intro x; cbn.\n      * apply path_prod; cbn.\n        -- exact (ap _ (grp_homo_unit f) @ right_identity _).\n        -- exact (right_identity _).\n      * exact (left_identity _)^.\n  - intro f.\n    rapply equiv_path_grouphomomorphism; intro b; cbn.\n    exact (left_identity _).\n  - intros [phi [p q]].\n    apply path_sigma_hprop; cbn.\n    rapply equiv_path_grouphomomorphism; intros [a b]; cbn.\n    apply path_prod; cbn.\n    + rewrite (ab_biprod_decompose a b).\n      refine (_ @ (grp_homo_op (ab_biprod_pr1 $o phi) _ _)^).\n      apply grp_cancelR; symmetry.\n      exact (ap fst (p a)).\n    + rewrite (ab_biprod_decompose a b).\n      refine (_ @ (grp_homo_op (ab_biprod_pr2 $o phi) _ _)^); cbn; symmetry.\n      exact (ap011 _ (ap snd (p a)) (q (group_unit, b))^).\nDefined.\n\n(** Consequently, the loop space of [AbSES B A] is [GroupHomomorphism B A]. (In fact, [B $-> A] are the loops of any short exact sequence, but the trivial case is easiest to show.) *)\nDefinition loops_abses `{Univalence} {A B : AbGroup}\n  : (B $-> A) <~> loops (AbSES B A)\n  := equiv_path_abses oE abses_endomorphism_trivial^-1.\n\n(** We can transfer a loop of the trivial short exact sequence to any other. *)\nDefinition hom_loops_data_abses `{Univalence} {A B : AbGroup} (E : AbSES B A)\n  : (B $-> A) -> abses_path_data E E.\nProof.\n  intro phi.\n  srefine (_; (_, _)).\n  - exact (ab_homo_add grp_homo_id (inclusion E $o phi $o projection E)).\n  - intro a; cbn.\n    refine (ap (fun x => _ + inclusion E (phi x)) _ @ _).\n    1: apply iscomplex_abses.\n    refine (ap (fun x => _ + x) (grp_homo_unit (inclusion E $o phi)) @ _).\n    apply grp_unit_r.\n  - intro e; symmetry.\n    refine (grp_homo_op (projection E) _ _ @ _); cbn.\n    refine (ap (fun x => _ + x) _ @  _).\n    1: apply iscomplex_abses.\n    apply grp_unit_r.\nDefined.\n\n(** ** Morphisms of short exact sequences *)\n\n(** A morphism between short exact sequences is a natural transformation between the underlying diagrams. *)\nRecord AbSESMorphism {A X B Y : AbGroup@{u}}\n  {E : AbSES B A} {F : AbSES Y X} := {\n    component1 : A $-> X;\n    component2 : middle E $-> middle F;\n    component3 : B $-> Y;\n    left_square : (inclusion _) $o component1 == component2 $o (inclusion _);\n    right_square : (projection _) $o component2 == component3 $o (projection _);\n  }.\n\nArguments AbSESMorphism {A X B Y} E F.\nArguments Build_AbSESMorphism {_ _ _ _ _ _} _ _ _ _ _.\n\nDefinition issig_AbSESMorphism {A X B Y : AbGroup@{u}}\n           {E : AbSES B A} {F : AbSES Y X}\n  : { f : (A $-> X) * (middle E $-> middle F) * (B $-> Y)\n          & ((inclusion _) $o (fst (fst f)) == (snd (fst f)) $o (inclusion _))\n            * ((projection F) $o (snd (fst f)) == (snd f) $o (projection _)) }\n      <~> AbSESMorphism E F := ltac:(make_equiv).\n\n(** The identity morphism from [E] to [E]. *)\nLemma abses_morphism_id {A B : AbGroup@{u}} (E : AbSES B A)\n  : AbSESMorphism E E.\nProof.\n  snrapply (Build_AbSESMorphism grp_homo_id grp_homo_id grp_homo_id).\n  1,2: reflexivity.\nDefined.\n\nDefinition absesmorphism_compose {A0 A1 A2 B0 B1 B2 : AbGroup@{u}}\n           {E : AbSES B0 A0} {F : AbSES B1 A1} {G : AbSES B2 A2}\n           (g : AbSESMorphism F G) (f : AbSESMorphism E F)\n  : AbSESMorphism E G.\nProof.\n  rapply (Build_AbSESMorphism (component1 g $o component1 f)\n                              (component2 g $o component2 f)\n                              (component3 g $o component3 f)).\n  - intro x; cbn.\n    exact (left_square g _ @ ap _ (left_square f _)).\n  - intro x; cbn.\n    exact (right_square g _ @ ap _ (right_square f _)).\nDefined.\n\n(** ** Characterization of split short exact sequences *)\n\n(* We characterize trivial short exact sequences in [AbSES] as those for which [projection] splits. *)\n\n(** If [projection E] splits, we get an induced map [fun e => e - s (projection E e)] from [E] to [ab_kernel (projection E)]. *)\nDefinition projection_split_to_kernel {B A : AbGroup} (E : AbSES B A)\n           {s : B $-> E} (h : projection _ $o s == idmap)\n  : (middle E) $-> (@ab_kernel E B (projection _)).\nProof.\n  snrapply (grp_kernel_corec (G:=E) (A:=E)).\n  - refine (ab_homo_add grp_homo_id\n              (grp_homo_compose ab_homo_negation (s $o (projection _)))).\n  - intro x; simpl.\n    refine (grp_homo_op (projection _) x _ @ _).\n    refine (ap (fun y => (projection _) x + y) _ @ right_inverse ((projection _) x)).\n    refine (grp_homo_inv _ _ @ ap (-) _ ).\n    apply h.\nDefined.\n\n(** The composite [A -> E -> ab_kernel (projection E)] is [grp_cxfib]. *)\nLemma projection_split_to_kernel_beta {B A : AbGroup} (E : AbSES B A)\n      {s : B $-> E} (h : (projection _) $o s == idmap)\n  : (projection_split_to_kernel E h) $o (inclusion _) == grp_cxfib cx_isexact.\nProof.\n  intro a.\n  apply path_sigma_hprop; cbn.\n  apply grp_cancelL1.\n  refine (ap (fun x => - s x) _ @ _).\n  1: rapply cx_isexact.\n  exact (ap _ (grp_homo_unit _) @ negate_mon_unit).\nDefined.\n\n(** The induced map [E -> ab_kernel (projection E) + B] is an isomorphism. We suffix it with 1 since it is the first composite in the desired isomorphism [E -> A + B]. *)\nDefinition projection_split_iso1 {B A : AbGroup} (E : AbSES B A)\n           {s : GroupHomomorphism B E} (h : (projection _) $o s == idmap)\n  : GroupIsomorphism E (ab_biprod (@ab_kernel E B (projection _)) B).\nProof.\n  srapply Build_GroupIsomorphism.\n  - refine (ab_biprod_corec _ (projection _)).\n    exact (projection_split_to_kernel E h).\n  - srapply isequiv_adjointify.\n    + refine (ab_biprod_rec _ s).\n      rapply subgroup_incl.\n    + intros [a b]; simpl.\n      apply path_prod'.\n      * srapply path_sigma_hprop; cbn.\n        refine ((associativity _ _ _)^ @ _).\n        apply grp_cancelL1.\n        refine (ap _ _ @ right_inverse _).\n        apply (ap (-)).\n        apply (ap s).\n        refine (grp_homo_op (projection _) a.1 (s b) @ _).\n        exact (ap (fun y => y + _) a.2 @ left_identity _ @ h b).\n      * refine (grp_homo_op (projection _) a.1 (s b) @ _).\n        exact (ap (fun y => y + _) a.2 @ left_identity _ @ h b).\n    + intro e; simpl.\n      by apply grp_moveR_gM.\nDefined.\n\n(** The full isomorphism [E -> A + B]. *)\nDefinition projection_split_iso {B A : AbGroup@{u}}\n  (E : AbSES B A) {s : GroupHomomorphism B E}\n  (h : (projection _) $o s == idmap)\n  : GroupIsomorphism E (ab_biprod A B).\nProof.\n  etransitivity (ab_biprod (ab_kernel _) B).\n  - exact (projection_split_iso1 E h).\n  - srapply (equiv_functor_ab_biprod\n               (grp_iso_inverse _) grp_iso_id).\n    rapply grp_iso_cxfib.\nDefined.\n\nProposition projection_split_beta {B A : AbGroup} (E : AbSES B A)\n            {s : B $-> E} (h : (projection _) $o s == idmap)\n  : projection_split_iso E h o (inclusion _) == ab_biprod_inl.\nProof.\n  intro a.\n  refine (ap _ (ab_corec_beta _ _ _ _) @ _).\n  refine (ab_biprod_functor_beta _ _ _ _ _ @ _).\n  nrapply path_prod'.\n  2: rapply cx_isexact.\n  refine (ap _ (projection_split_to_kernel_beta E h a) @ _).\n  apply eissect.\nDefined.\n\n(** A short exact sequence [E] in [AbSES B A] is trivial if and only if [projection E] splits. *)\nProposition iff_abses_trivial_split `{Univalence}\n  {B A : AbGroup@{u}} (E : AbSES B A)\n  : {s : B $-> E & (projection _) $o s == idmap}\n    <-> (E = point (AbSES B A)).\nProof.\n  refine (iff_compose _ (iff_equiv equiv_path_abses_iso)); split.\n  - intros [s h].\n    exists (projection_split_iso E h).\n    split.\n    + nrapply projection_split_beta.\n    + reflexivity.\n  - intros [phi [g h]].\n    exists (grp_homo_compose (grp_iso_inverse phi) ab_biprod_inr).\n    intro x; cbn.\n    exact (h _ @ ap snd (eisretr _ _)).\nDefined.\n\n(** ** Constructions of short exact sequences *)\n\n(** Any inclusion [i : A $-> E] determines a short exact sequence by quotienting. *)\nDefinition abses_from_inclusion `{Univalence}\n  {A E : AbGroup@{u}} (i : A $-> E) `{IsEmbedding i}\n  : AbSES (QuotientAbGroup E (grp_image_embedding i)) A.\nProof.\n  srapply (Build_AbSES E i).\n  1: exact grp_quotient_map.\n  1: exact _.\n  srapply Build_IsExact.\n  - srapply phomotopy_homotopy_hset.\n    intro x.\n    apply qglue; cbn.\n    exists (-x).\n    exact (grp_homo_inv _ _ @ (grp_unit_r _)^).\n  - snrapply (conn_map_homotopic (Tr (-1)) (B:=grp_kernel (@grp_quotient_map E _))).\n    + exact (grp_kernel_quotient_iso _ o ab_image_in_embedding i).\n    + intro a.\n      by rapply (isinj_embedding (subgroup_incl _)).\n    + rapply conn_map_isequiv.\nDefined.\n\n(** Conversely, given a short exact sequence [A -> E -> B], [A] is the kernel of [E -> B]. (We don't need exactness at [B], so we drop this assumption.) *)\nLemma abses_kernel_iso `{Funext} {A E B : AbGroup} (i : A $-> E) (p : E $-> B)\n  `{IsEmbedding i, IsExact (Tr (-1)) _ _ _ i p}\n  : GroupIsomorphism A (ab_kernel p).\nProof.\n  snrapply Build_GroupIsomorphism.\n  - apply (grp_kernel_corec i).\n    rapply cx_isexact.\n  - apply isequiv_surj_emb.\n    2: rapply (cancelL_mapinO _ (grp_kernel_corec _ _) _).\n    intros [y q].\n    assert (a : Tr (-1) (hfiber i y)).\n    1: by rapply isexact_preimage.\n    strip_truncations; destruct a as [a r].\n    rapply contr_inhabited_hprop.\n    refine (tr (a; _)); cbn.\n    apply path_sigma_hprop; cbn.\n    exact r.\nDefined.\n\n(** A computation rule for the inverse of [abses_kernel_iso i p]. *)\nLemma abses_kernel_iso_inv_beta `{Funext} {A E B : AbGroup} (i : A $-> E) (p : E $-> B)\n  `{IsEmbedding i, IsExact (Tr (-1)) _ _ _ i p}\n  : i o (abses_kernel_iso i p)^-1 == subgroup_incl _.\nProof.\n  rapply (equiv_ind (abses_kernel_iso i p)); intro a.\n  exact (ap i (eissect (abses_kernel_iso i p) _)).\nDefined.\n\n(* Any surjection [p : E $-> B] induces a short exact sequence by taking the kernel. *)\nLemma abses_from_surjection {E B : AbGroup@{u}} (p : E $-> B) `{IsSurjection p}\n  : AbSES B (ab_kernel p).\nProof.\n  srapply (Build_AbSES E _ p).\n  1: exact (subgroup_incl _).\n  1: exact _.\n  snrapply Build_IsExact.\n  - apply phomotopy_homotopy_hset.\n    intros [e q]; cbn.\n    exact q.\n  - rapply conn_map_isequiv.\nDefined.\n\n(** Conversely, given a short exact sequence [A -> E -> B], [B] is the cokernel of [A -> E]. In fact, we don't need exactness at [A], so we drop this from the statement. *)\nLemma abses_cokernel_iso `{Funext}\n  {A E B : AbGroup@{u}} (f : A $-> E) (g : GroupHomomorphism E B)\n  `{IsSurjection g, IsExact (Tr (-1)) _ _ _ f g}\n  : GroupIsomorphism (ab_cokernel f) B.\nProof.\n  snrapply Build_GroupIsomorphism.\n  - snrapply (quotient_abgroup_rec _ _ g).\n    intros e; rapply Trunc_rec; intros [a p].\n    refine (ap _ p^ @ _).\n    rapply cx_isexact.\n  - apply isequiv_surj_emb.\n    1: rapply cancelR_conn_map.\n    apply isembedding_isinj_hset.\n    srapply Quotient_ind_hprop; intro x.\n    srapply Quotient_ind_hprop; intro y.\n    intro p.\n    apply qglue; cbn.\n    refine (isexact_preimage (Tr (-1)) _ _ (-x + y) _).\n    refine (grp_homo_op _ _ _ @ _).\n    rewrite grp_homo_inv.\n    apply grp_moveL_M1^-1.\n    exact p^.\nDefined.\n\nDefinition abses_cokernel_iso_inv_beta `{Funext}\n  {A E B : AbGroup} (f : A $-> E) (g : GroupHomomorphism E B)\n  `{IsSurjection g, IsExact (Tr (-1)) _ _ _ f g}\n  : (abses_cokernel_iso f g)^-1 o g == grp_quotient_map.\nProof.\n  intro x; by apply moveR_equiv_V.\nDefined.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Algebra/AbSES/Core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6622227888288625}}
{"text": "(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*   Assia.Mahboubi@inria.fr, Laurence.Rideau@inria.fr       *)\n(*  Laurent.Thery@inria.fr Yves.Bertot Frederique.Guilhot    *)\n(*  &all    Inria, 2006                                      *)\n(*************************************************************)\n\nRequire Export Reals.\nRequire Export Field.\nRequire Export Fourier.\nOpen Scope R_scope.\nHint Resolve fact_neq_0 prod_neq_R0 :real.\n \nLtac RReplace a b := replace a with b; [idtac | ring || auto with real].\n \nLtac NReplace a b := replace a with b; [idtac | omega || auto with arith].\n \nLemma C_nn: forall (n : nat),  C n n = 1.\nintros; unfold C; simpl.\nNReplace (n - n)%nat 0%nat.\nsimpl; field.\nRReplace (INR (fact n) * 1) (INR (fact n)).\nauto with real.\nQed.\n \nLemma C_n0: forall (n : nat),  C n O = 1.\nintros.\nrewrite <- (C_nn n).\nrewrite pascal_step1.\nNReplace (n - 0)%nat n; auto.\nomega.\nQed.\n\nLemma util_C:\n forall (n i j : nat),\n (i <= j)%nat -> (j <= n)%nat ->  C n i * C (n - i) (j - i) = C j i * C n j.\nintros.\nassert (i <= n)%nat.\nomega.\nunfold C.\nreplace  ((n - i) - (j - i))%nat with (n - j)%nat;[ | omega].\nfield.\nrepeat split; auto with real.\nQed.\n \nLemma pow_Rmult: forall (x y : R) (n : nat),  (x * y) ^ n = x ^ n * y ^ n.\nintros; (induction n; simpl).\nauto with real.\nRReplace ((x * x ^ n) * (y * y ^ n)) ((x * y) * (x ^ n * y ^ n)).\nrewrite <- IHn.\nring.\nQed.\n \nLemma sum_f_permute:\n forall (f : nat -> nat ->  R) (n p : nat),\n  sum_f_R0 (fun (i : nat) => sum_f_R0 (fun (j : nat) => f i j) p) n =\n  sum_f_R0 (fun (j : nat) => sum_f_R0 (fun (i : nat) => f i j) n) p.\nintros f; induction n; simpl; intros.\napply sum_eq; intros; auto.\nrewrite IHn.\nrewrite <- sum_plus.\napply sum_eq; intros; auto.\nQed.\n \nDefinition reverse (p : nat) (b : nat ->  R) := fun (i : nat) => b (p - i)%nat.\n \nLemma sigma_reverse:\n forall (p : nat) (b : nat ->  R),  sum_f_R0 b p = sum_f_R0 (reverse p b) p.\ninduction p; intros.\nsimpl; unfold reverse.\nNReplace (0 - 0)%nat 0%nat; auto.\nrewrite tech5; auto.\nrewrite (tech2 (reverse (S p) b) 0 (S p)); auto.\nsimpl; unfold reverse.\nNReplace (S p - 0)%nat (S p)%nat.\nNReplace (p - 0)%nat p.\nassert (sum_f_R0 b p = sum_f_R0 (fun (i : nat) => b (S p - S i)%nat) p).\nrewrite IHp.\napply sum_eq; intros; unfold reverse.\nNReplace (S p - S i)%nat (p - i)%nat; auto.\nrewrite H; ring.\nomega.\nQed.\n(* Formalisation de l'algorithme qui permet de calculer a partir de la liste b des coefficients de P\n   dans la base RBern (l r) ses coefficients dans la base RBern (l m)*)\n \nFixpoint coef_algo (b : nat ->  R) (A B : R) (n : nat) {struct n} : nat ->  R :=\n match n with\n   0 => b\n  | S i =>\n      fun (j : nat) => A * coef_algo b A B i j + B * coef_algo b A B i (j + 1)\n end.\n(* l'input de l'algorithme correspond a la premiere ligne\n  l'output de l'algorithme correspond a la premiere colonne*)\n \nDefinition output b A B := fun (i : nat) => coef_algo b A B i 0%nat.\n(* l'output2 de l'algorithme correspond a l'hypotenuse du triangle*)\n \nDefinition output2 p b A B := fun (i : nat) => coef_algo b A B (p - i) i.\n(* linearite de l'algorithme *)\n \nLemma add_coef_algo:\n forall k b c A B n,\n  coef_algo (fun (j : nat) => b j + c j) A B k n =\n  coef_algo b A B k n + coef_algo c A B k n.\ninduction k; intros; simpl; auto.\nrewrite IHk.\nrewrite IHk.\nring.\nQed.\n \nLemma scal_coef_algo:\n forall k b A B x n,\n  coef_algo (fun (j : nat) => x * b j) A B k n = x * coef_algo b A B k n.\ninduction k; intros; simpl; auto.\nrewrite IHk.\nrewrite IHk.\nring.\nQed.\n \nLemma output_add:\n forall k b c A B,\n  output (fun (j : nat) => b j + c j) A B k = output b A B k + output c A B k.\nintros; unfold output.\nrewrite add_coef_algo; auto.\nQed.\n \nLemma output_scal:\n forall k b A B x,  output (fun (j : nat) => x * b j) A B k = x * output b A B k.\nintros; unfold output.\nrewrite scal_coef_algo; auto.\nQed.\n(* (fi) avec i<=n est une famille de suites, formalisation de la suite k ->(f0 + .....+fn) (k)*)\n \nDefinition sum_suite (f : nat -> nat ->  R) (n : nat) :=\n   fun (k : nat) => sum_f_R0 (fun (i : nat) => f i k) n.\n(* l'output d'une somme finie de listes correspond a la somme finie des outputs de chacune des listes*)\n \nLemma output_sumsuite:\n forall n f A B k,\n  output (sum_suite f n) A B k =\n  sum_f_R0 (fun (i : nat) => output (fun (j : nat) => f i j) A B k) n.\nunfold sum_suite.\ninduction n; intros; simpl; auto.\nrewrite (output_add\n          k (fun (k0 : nat) => sum_f_R0 (fun (i : nat) => f i k0) n)\n          (fun (j : nat) => f (S n) j)).\nrewrite IHn; auto.\nQed.\n(* formalisation des suites delta i*)\n \nDefinition delta (n p : nat) :=\n   match eq_nat_dec n p with left _ => 1 | right _ => 0 end.\n \nLemma delta_ii: forall (i : nat),  delta i i = 1.\nintros; unfold delta.\nelim (eq_nat_dec i i); auto.\nintuition.\nQed.\n \nLemma delta_ij: forall (i j : nat), i <> j ->  delta i j = 0.\nintros; unfold delta.\nelim (eq_nat_dec i j); auto.\nintuition.\nQed.\n \nLemma decompose_sum_3:\n forall (f : nat ->  R) (n p : nat),\n (p < n)%nat ->\n (0 < p)%nat ->\n  sum_f_R0 f n =\n  (sum_f_R0 f (pred p) +\n   (f p + sum_f_R0 (fun (i : nat) => f (S p + i)%nat) (n - S p)))%R.\nintros.\nrewrite (tech2 f p n); auto.\nrewrite (sum_N_predN f p); auto.\nring.\nQed.\n \nDefinition ps_delta (f : nat ->  R) :=\n   fun (k : nat) => fun (i : nat) => f k * delta k i.\n(* f0, f1 ,....,fn une liste peut s'ecrire comme somme des fi * delta i*)\n \nTheorem decompose_delta:\n forall (f : nat ->  R) (n k : nat),\n (k <= n)%nat ->  sum_suite (ps_delta f) n k = f k.\nintros; unfold sum_suite, ps_delta.\ncase (zerop n); intros.\nrewrite e; simpl.\nNReplace k 0%nat.\nrewrite delta_ii; ring.\ncase (le_lt_eq_dec k n); auto; intros H1.\ncase (zerop k); intros H2.\nrewrite decomp_sum; auto.\nrewrite H2.\nrewrite delta_ii.\nassert (sum_f_R0 (fun (i : nat) => f (S i) * delta (S i) 0) (pred n) = 0).\napply sum_eq_R0; intros.\nrewrite delta_ij; auto with arith.\nring.\nrewrite H0; ring.\nrewrite (decompose_sum_3 (fun (i : nat) => f i * delta i k) n k); auto.\nassert (sum_f_R0 (fun (i : nat) => f i * delta i k) (pred k) = 0).\napply sum_eq_R0; intros.\nrewrite delta_ij; (try omega).\nring.\nassert\n (sum_f_R0 (fun (i : nat) => f (S k + i)%nat * delta (S k + i) k) (n - S k) = 0).\napply sum_eq_R0; intros.\nrewrite delta_ij; (try omega).\nring.\nrewrite H3; rewrite H0; rewrite delta_ii; ring.\nrewrite sum_N_predN; auto.\nrewrite H1.\nassert (sum_f_R0 (fun (i : nat) => f i * delta i n) (pred n) = 0).\napply sum_eq_R0; intros.\nrewrite delta_ij; (try omega).\nring.\nrewrite H0; rewrite delta_ii; ring.\nQed.\n(* application de l'algorithme a delta (i+1)*)\n \nLemma translation_delta:\n forall k A B i j,\n  coef_algo (delta (S i)) A B k (S j) = coef_algo (delta i) A B k j.\ninduction k; intros; simpl.\nelim (eq_nat_dec i j); intros.\nrewrite a.\n(repeat rewrite delta_ii); auto.\nrepeat (rewrite delta_ij; intuition).\nrewrite IHk.\nrewrite IHk; auto.\nQed.\n(* algorithme applique a delta_i (colonne j > i)*)\n \nLemma coef_algo_delta_col_supi:\n forall k A B i j, (j > i)%nat ->  coef_algo (delta i%nat) A B k j = 0.\ninduction k; intros; simpl.\nrewrite delta_ij; intuition.\nrewrite IHk; intuition.\nrewrite IHk; intuition.\nring.\nQed.\n(* algorithme applique a delta_i (ligne n ,colonne  i)*)\n \nLemma coef_algo_delta_col_i:\n forall n i A B,  coef_algo (delta i%nat) A B n i = A ^ n.\ninduction n; intros; simpl.\nrewrite delta_ii; auto.\nrewrite IHn.\nrewrite coef_algo_delta_col_supi; intuition.\nring.\nQed.\n(* algorithme applique a delta_i (colonne k avec k < i - j, ligne j avec j < i)*)\n \nLemma coef_algo_delta_ligne_infi_k:\n forall j i A B,\n (j < i)%nat ->\n forall k, (k < i - j)%nat ->  coef_algo (delta i%nat) A B j k = 0.\ninduction j; intros; simpl.\nrewrite delta_ij; intuition.\nrewrite IHj; intuition.\nrewrite IHj; intuition.\nring.\nQed.\n(* algorithme applique a delta_i (colonne 0, ligne j avec j < i)*)\n \nLemma coef_algo_delta_ligne_infi:\n forall j i A B, (j < i)%nat ->  coef_algo (delta i) A B j 0%nat = 0.\ninduction j; intros; simpl.\nrewrite delta_ij; intuition.\nrewrite IHj; intuition.\nrewrite coef_algo_delta_ligne_infi_k; intuition.\nring.\nQed.\n(* algorithme applique a delta_i (colonne 0, ligne i + k )*)\n \nLemma coef_algo_delta_ligne_sup_i:\n forall i k A B,\n  coef_algo (delta i) A B (i + k) 0%nat = (C (k + i) i * A ^ k) * B ^ i.\ninduction i; intros; simpl.\nrewrite coef_algo_delta_col_i.\nrewrite C_n0.\nring.\nrewrite translation_delta.\nrewrite IHi.\nelim k; simpl.\nNReplace (i + 0)%nat i.\nrewrite coef_algo_delta_ligne_infi_k; (try omega).\nrepeat rewrite C_nn.\nring.\nintros.\nNReplace (i + S n)%nat (S (i + n))%nat.\nsimpl.\nrewrite translation_delta.\nrewrite IHi.\nrewrite H.\nrewrite <- (pascal (n + S i) i); auto.\nNReplace (S (n + i))%nat (n + S i)%nat.\nring.\nomega.\nQed.\n(*ouput de delta i*)\n \nTheorem output_delta_infi:\n forall i j A B, (j < i)%nat ->  output (delta i) A B j = 0.\nintros; unfold output.\nrewrite coef_algo_delta_ligne_infi; auto.\nQed.\n \nTheorem output_delta_supi:\n forall i j A B,\n (j >= i)%nat ->  output (delta i) A B j = (C j i * A ^ (j - i)) * B ^ i.\nintros; unfold output.\npattern j at 1.\nNReplace j (i + (j - i))%nat.\nrewrite (coef_algo_delta_ligne_sup_i i (j - i)).\nNReplace ((j - i) + i)%nat j; auto.\nQed.\n(*avec une liste f0,....,fn, on peut calculer un \"triangle\" de coefficients du tableau *)\n \nLemma coef_algo_comp_eq:\n forall f g A B n,\n (forall k, (k <= n)%nat ->  f k = g k) ->\n forall i j,\n (i <= n)%nat -> (j <= n - i)%nat ->  coef_algo f A B i j = coef_algo g A B i j.\ninduction i; intros; simpl; auto.\nrewrite H; auto.\nomega.\nrewrite IHi; auto.\nrewrite IHi; auto.\nomega.\nomega.\nomega.\nomega.\nQed.\n \nLemma output_comp_eq:\n forall f g A B n,\n (forall k, (k <= n)%nat ->  f k = g k) ->\n forall i, (i <= n)%nat ->  output f A B i = output g A B i.\nintros; unfold output.\nrewrite (coef_algo_comp_eq _ _ A B _ H); auto.\nomega.\nQed.\n(* output b comme somme des output delta i *)\n \nLemma sum_output_delta:\n forall b A B n k,\n (k <= n)%nat ->\n  output b A B k = sum_f_R0 (fun (i : nat) => b i * output (delta i) A B k) n.\nintros.\nassert (output b A B k = output (sum_suite (ps_delta b) n) A B k).\napply (output_comp_eq b (sum_suite (ps_delta b) n) A B n); auto.\nintros; rewrite decompose_delta; auto.\nrewrite H0.\nrewrite output_sumsuite; auto.\nunfold ps_delta.\napply sum_eq; intros.\nrewrite (output_scal k (delta i) A B (b i)); auto.\nQed.\n(* algorithme applique a la suite inversee*)\n \nLemma algo_reverse:\n forall b A B p i k,\n (i <= p)%nat ->\n (k <= p - i)%nat ->\n  coef_algo (reverse p b) B A i k = coef_algo b A B i (p - (i + k)).\ninduction i; intros.\nunfold reverse; simpl; auto.\nsimpl.\nrewrite IHi; (try omega).\nrewrite IHi; (try omega).\nNReplace (p - (i + k))%nat ((p - S (i + k)) + 1)%nat.\nNReplace (p - (i + (k + 1)))%nat (p - S (i + k))%nat.\nring.\nQed.\n(* output2 en fonction de output de la suite inversee*)\n \nLemma ouput_reverse:\n forall b A B p i,\n (i <= p)%nat ->  output2 p b A B i = reverse p (output (reverse p b) B A) i.\nintros.\nchange (output2 p b A B i = output (reverse p b) B A (p - i)).\nunfold output, output2.\nrewrite algo_reverse; (try omega).\nNReplace (p - ((p - i) + 0))%nat i; auto.\nQed.\n(*Polynomes de Bernstein (l,r)*)\nDefinition RBern p i l r X :=\n  C p i *  (Rdiv (X - l) (r - l) ^ i * Rdiv (r - X) (r - l) ^ (p - i)).\n \nLemma\n   RBern_def :\n   forall p i l r X,\n   (i <= p)%nat ->\n   r - l <> 0 ->\n    RBern p i l r X =\n    C p i * (Rdiv (X - l) (r - l) ^ i * Rdiv (r - X) (r - l) ^ (p - i)).\nintros; reflexivity.\nQed.\n\nLemma RBern_rl:\n forall p i l r X,\n (i <= p)%nat -> r - l <> 0 ->  RBern p i r l X = RBern p (p - i) l r X.\nintros.\nrepeat (rewrite RBern_def; auto).\nNReplace (p - (p - i))%nat i.\nrewrite pascal_step1; auto.\nRReplace ((X - l) / (r - l)) ((l - X) / (l - r)).\nRReplace ((r - X) / (r - l)) ((X - r) / (l - r)).\nring.\nfield.\nauto with real.\nfield.\nauto with real.\nomega.\nauto with real.\nQed.\n \nLemma reverse_RBern:\n forall b p l r X P,\n r - l <> 0 ->\n P = sum_f_R0 (fun (i : nat) => b i * RBern p i l r X) p ->\n  P = sum_f_R0 (fun (i : nat) => reverse p b i * RBern p i r l X) p.\nintros.\nrewrite H0.\nrewrite sigma_reverse.\napply sum_eq; intros; unfold reverse.\nrewrite <- RBern_rl; auto.\nQed.\n \nSection RBernstein.\nVariables X l r m : R.\nHypothesis neq_rl : r - l <> 0.\nHypothesis neq_ml : m - l <> 0.\nHypothesis neq_rm : r - m <> 0.\n \nDefinition A := Rdiv (r - m) (r - l).\n \nDefinition B := Rdiv (m - l) (r - l).\nHint Unfold A B :real.\n \nLemma pow_Xl_k:\n forall k,  Rdiv (X - l) (r - l) ^ k = B ^ k * Rdiv (X - l) (m - l) ^ k.\nintros; unfold B.\nrewrite <- pow_Rmult.\nreplace ((X - l) / (r - l)) with (((m - l) / (r - l)) * ((X - l) / (m - l)));\n auto.\nfield.\nauto.\nQed.\n \nLemma dev_rX:\n Rdiv (r - X) (r - l) = A * Rdiv (X - l) (m - l) + Rdiv (m - X) (m - l).\nunfold A.\nfield.\nauto.\nQed.\n \nLemma pow_rX_n:\n forall n,\n  Rdiv (r - X) (r - l) ^ n =\n  sum_f_R0\n   (fun (i : nat) =>\n    (C n i * (A ^ i * Rdiv (X - l) (m - l) ^ i)) *\n    Rdiv (m - X) (m - l) ^ (n - i)) n.\nintros.\nrewrite dev_rX.\nrewrite binomial.\napply sum_eq; intros.\nrewrite pow_Rmult; auto.\nQed.\n \nLemma RBern_sum:\n forall p k,\n (k <= p)%nat ->\n  RBern p k l r X =\n  C p k *\n  sum_f_R0\n   (fun (i : nat) =>\n    (C (p - k) i * (A ^ i * (B ^ k * Rdiv (X - l) (m - l) ^ (i + k)))) *\n    Rdiv (m - X) (m - l) ^ ((p - k) - i)) (p - k).\nintros.\nrewrite RBern_def; auto.\nrewrite pow_Xl_k.\nrewrite pow_rX_n.\nrewrite scal_sum.\napply Rmult_eq_compat_l.\napply sum_eq; intros.\nrewrite pow_add.\nring.\nQed.\n \nLemma RBern_lr_sum_RBern_lm:\n forall p k,\n (k <= p)%nat ->\n  RBern p k l r X =\n  sum_f_R0\n   (fun (i : nat) => (C (i + k) k * (A ^ i * B ^ k)) * RBern p (i + k) l m X)\n   (p - k).\nintros.\nrewrite RBern_sum; auto.\nrewrite scal_sum.\napply sum_eq; intros.\nrewrite RBern_def; auto.\nNReplace (p - (i + k))%nat ((p - k) - i)%nat.\nRReplace (((C (p - k) i * (A ^ i * (B ^ k * ((X - l) / (m - l)) ^ (i + k)))) *\n           ((m - X) / (m - l)) ^ ((p - k) - i)) * C p k)\n         (((B ^ k * (A ^ i * (C p k * C (p - k) i))) *\n           ((m - X) / (m - l)) ^ ((p - k) - i)) * ((X - l) / (m - l)) ^ (i + k)).\nreplace (C (p - k) i) with (C (p - k) ((i + k) - k)).\nrewrite (util_C p k (i + k)); (try omega).\nring.\nNReplace ((i + k) - k)%nat i; auto.\nomega.\nQed.\n(* Ce theoreme exprime les RBern(l r) comme somme finie des Rbern (l m)*)\n \nTheorem RBern_lr_sum_k_n_RBern_lm:\n forall p i,\n (i <= p)%nat ->\n  RBern p i l r X =\n  sum_f i p (fun (j : nat) => (C j i * (A ^ (j - i) * B ^ i)) * RBern p j l m X).\nintros; unfold sum_f.\nrewrite RBern_lr_sum_RBern_lm; auto.\napply sum_eq; intros j; intros.\nNReplace ((j + i) - i)%nat j; auto.\nQed.\n \nLemma RBern_sigma_coef_algo:\n forall (p k : nat),\n (k <= p)%nat ->\n  RBern p k l r X =\n  sum_f_R0\n   (fun (i : nat) => output (delta k) A B (i + k) * RBern p (i + k) l m X)\n   (p - k).\nintros; unfold output.\nrewrite RBern_lr_sum_RBern_lm; auto.\napply sum_eq; intros.\npattern (i + k)%nat at 3.\nNReplace (i + k)%nat (k + i)%nat.\nrewrite coef_algo_delta_ligne_sup_i; ring.\nQed.\n \nLemma RBern_sigma_p:\n forall (p k : nat),\n (k <= p)%nat ->\n  RBern p k l r X =\n  sum_f_R0 (fun (i : nat) => output (delta k) A B i * RBern p i l m X) p.\nintros.\nrewrite RBern_sigma_coef_algo; auto.\ncase (zerop k); intros.\nrewrite e.\nNReplace (p - 0)%nat p.\napply sum_eq; intros.\nNReplace (i + 0)%nat i; auto.\nrewrite (tech2\n          (fun (i : nat) => output (delta k) A B i * RBern p i l m X) (k - 1) p);\n auto.\nassert\n (sum_f_R0 (fun (i : nat) => output (delta k) A B i * RBern p i l m X) (k - 1) =\n  0).\napply sum_eq_R0; intros.\nrewrite output_delta_infi; (try omega).\nring.\nrewrite H0.\nNReplace (S (k - 1))%nat k.\nring_simplify.\napply sum_eq; intros.\nNReplace (k + i)%nat (i + k)%nat; auto.\nomega.\nQed.\n(*input : b0,....,bp : calul explicite de l'output*)\n \nLemma output_sum_C:\n forall (b : nat ->  R) (p k : nat),\n (k <= p)%nat ->\n  output b A B k =\n  sum_f_R0 (fun (i : nat) => b i * ((C k i * A ^ (k - i)) * B ^ i)) k.\nintros.\nrewrite (sum_output_delta b A B p); auto.\nelim (eq_nat_dec k p); intros.\nrewrite a.\napply sum_eq; intros.\nrewrite output_delta_supi; auto.\nrewrite (tech2 (fun (i : nat) => b i * output (delta i) A B k) k p).\nassert\n (sum_f_R0\n   (fun (i : nat) => b (S k + i)%nat * output (delta (S k + i)) A B k) (p - S k)\n  = 0).\napply sum_eq_R0; intros.\nrewrite output_delta_infi; (try omega).\nring.\nrewrite H0.\nring_simplify.\napply sum_eq; intros.\nrewrite output_delta_supi; auto.\nomega.\nQed.\n(* si b0,....,bp sont les coefficients du polynome P dans la base Bern(l,r)\n   alors (output b)0,....,(output b)p sont les coefficients de P dans la base Bern(l,m)*)\n \nTheorem algo_correct:\n forall (b : nat ->  R) (p : nat) (P : R),\n P = sum_f_R0 (fun (i : nat) => b i * RBern p i l r X) p ->\n  P = sum_f_R0 (fun (i : nat) => (output b A B) i * RBern p i l m X) p.\nintros.\npose (f:=\n fun (j : nat) =>\n fun (i : nat) => b i * (output (delta i) A B j * RBern p j l m X)).\nassert\n (sum_f_R0 (fun (i : nat) => b i * RBern p i l r X) p =\n  sum_f_R0 (fun (i : nat) => sum_f_R0 (fun (j : nat) => f i j) p) p).\nrewrite sum_f_permute.\napply sum_eq; intros k; intros.\nrewrite RBern_sigma_p; auto.\nrewrite scal_sum.\napply sum_eq; intros i; intros.\nunfold f; ring.\nrewrite H; rewrite H0.\napply sum_eq; intros i; intros.\nrewrite (sum_output_delta b A B p i); auto.\nrewrite Rmult_comm.\nrewrite scal_sum.\napply sum_eq; intros j; intros.\nunfold f; ring.\nQed.\n \nEnd RBernstein.\n \nLemma A_rl: forall l r m, l - r <> 0 ->  A r l m = B l r m.\nunfold A, B; intros.\nfield.\nauto with real.\nQed.\n \nLemma B_rl: forall l r m, l - r <> 0 ->  B r l m = A l r m.\nunfold A, B; intros.\nfield.\nauto with real.\nQed.\n(* si b0,....,bp sont les coefficients du polynome P dans la base Bern(l,r)\n   alors (output2 b)0,....,(output2 b)p sont les coefficients de P dans la base Bern(m,r)*)\n \nTheorem algo_correct2:\n forall (X l r m P : R) (b : nat ->  R) (p : nat),\n l - r <> 0 ->\n m - r <> 0 ->\n P = sum_f_R0 (fun (i : nat) => b i * RBern p i l r X) p ->\n  P =\n  sum_f_R0\n   (fun (i : nat) => output2 p b (A l r m) (B l r m) i * RBern p i m r X) p.\nintros.\nassert\n (P =\n  sum_f_R0\n   (fun (i : nat) => output2 p b (A l r m) (B l r m) i * RBern p (p - i) r m X)\n   p).\nassert (P = sum_f_R0 (fun (i : nat) => reverse p b i * RBern p i r l X) p).\nrewrite (reverse_RBern b p l r X P); auto with real.\nrewrite (algo_correct X r l m H H0 (reverse p b) p P); auto.\nrewrite sigma_reverse; auto.\napply sum_eq; intros.\nchange\n (output (reverse p b) (A r l m) (B r l m) (p - i) * RBern p (p - i) r m X =\n  output2 p b (A l r m) (B l r m) i * RBern p (p - i) r m X).\nrewrite ouput_reverse; auto.\nrewrite B_rl; auto with real.\nrewrite A_rl; auto with real.\nrewrite H2; auto.\napply sum_eq; intros.\nrewrite <- RBern_rl; auto with real.\nQed.\n(* si b0,....,bp sont les coefficients du polynome P dans la base Bern(l,r)\n   alors l'algorithme donnent les coefficients de P dans la base Bern(l,m) et dans la base Bern(m,r)*)\n \nTheorem conclusion:\n forall (X l r m P : R) (b : nat ->  R) (p : nat),\n l - r <> 0 ->\n m - l <> 0 ->\n m - r <> 0 ->\n P = sum_f_R0 (fun (i : nat) => b i * RBern p i l r X) p ->\n  and\n   (P =\n    sum_f_R0\n     (fun (i : nat) => output b (A l r m) (B l r m) i * RBern p i l m X) p)\n   (P =\n    sum_f_R0\n     (fun (i : nat) => output2 p b (A l r m) (B l r m) i * RBern p i m r X) p).\nintros.\nsplit.\napply algo_correct; auto with real.\napply algo_correct2; auto with real.\nQed.\n", "meta": {"author": "math-comp", "repo": "trajectories", "sha": "cc6e1298208a93592230f5b4ee3228a024aa03e7", "save_path": "github-repos/coq/math-comp-trajectories", "path": "github-repos/coq/math-comp-trajectories/trajectories-cc6e1298208a93592230f5b4ee3228a024aa03e7/attic/Bernstein/bernstein.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6622227830100504}}
{"text": "From mathcomp Require Import ssreflect.\n\nRequire Import relation.\n\n(* Axiom Of Extentionality in setontypetheory *)\n\nAxiom AxiomOfEmpty: forall U:Type, exists z':Collection U, (forall x:U, x ∉ z').\n\nInductive EmptyCollection (U:Type) : Collection U := .\nInductive FullCollection (U:Type) : Collection U :=\n| intro_full_collection: forall x:U, x ∈ FullCollection U.\n\nNotation \"`Ø`\" :=  (EmptyCollection _) (at level 10).\n\nDefinition ComplementOfCollection (U:Type) (X:Collection U) : Collection U :=\n  fun x:U => x ∉ X.\n\nNotation \"A ^c\" := (ComplementOfCollection _ A) (at level 15).\n\nTheorem noone_in_empty:\n  forall U:Type, forall x:U, x ∉ `Ø`.\nProof.\n  move => U x.\n  case.\nQed.\n\nTheorem same_empty_collection_is_exsitance:\n  forall U:Type, exists a':Collection U, (forall x:U, x ∉ a') <-> (a' = `Ø`).\nProof.\n  move => U.\n  case: (AxiomOfEmpty U) => e' HAE.\n  exists e'.\n  rewrite /iff. split => H.\n  apply: AxiomOfExtentionality => x0.\n  rewrite /iff. split => H0.\n  case: (HAE x0). by [].\n  case: (noone_in_empty U x0). by [].\n  by [].\nQed.\n\nTheorem noone_in_collection_to_empty_collection:\n  forall U:Type, forall {a':Collection U}, (forall x:U, x ∉ a') -> a' = `Ø`.\nProof.\n  move => U a' HE.\n  apply AxiomOfExtentionality.\n  rewrite /iff. split => H.\n  case: (HE x). by[].\n  case: (noone_in_empty U x). by [].\nQed.\n\nTheorem empty_collection_to_noone_in_collection:\n  forall U:Type, forall a':Collection U, a' = `Ø` -> (forall x:U, x ∉ a').\nProof.\n  move => U a' H.\n  rewrite H.\n  apply noone_in_empty.\nQed.\n\nTheorem empty_collection_is_noone_in_collection:\n  forall U:Type, forall a':Collection U, a' = `Ø` <-> (forall x:U, x ∉ a').\nProof.\n  move => U a'.\n  rewrite /iff. split.\n  apply empty_collection_to_noone_in_collection.\n  apply noone_in_collection_to_empty_collection.\nQed.\n\nTheorem not_empty_collection_to_exists_element_in_collection:\n  forall U:Type, forall a':Collection U, a' <> `Ø` -> (exists x:U, x ∈ a').\nProof.\n  move => U a' HaNE.\n  apply DoubleNegativeElimination => H.\n  have L1: forall x:U, x ∉ a'.\n  apply DeMorganNotExists.\n  trivial.\n  apply empty_collection_is_noone_in_collection in L1.\n  apply HaNE.\n  trivial.\nQed.\n\nTheorem exists_element_in_collection_to_not_empty_collection:\n  forall U:Type, forall a':Collection U, (exists x:U, x ∈ a') -> a' <> `Ø`.\nProof.\n  move => U a' HexA HxA.\n  move: HexA.\n  apply DeMorganNotExists.\n  apply empty_collection_is_noone_in_collection.\n  trivial.\nQed.\n\nTheorem not_empty_collection_has_least_a_element:\n  forall U:Type, forall a':Collection U, a' <> `Ø` <-> (exists x:U, x ∈ a').\nProof.\n  move => U a'.\n  rewrite /iff. split.\n  apply not_empty_collection_to_exists_element_in_collection.\n  apply exists_element_in_collection_to_not_empty_collection.\nQed.\n\nTheorem empty_collection_is_unique:\n  forall U:Type, forall {a' b':Collection U}, (forall x: U, x ∉ a') -> (forall x: U, x ∉ b') -> a' = b'.\nProof.\n  move => U a' b' HNa HNb.\n  apply (noone_in_collection_to_empty_collection U) in HNa.\n  apply (noone_in_collection_to_empty_collection U) in HNb.\n  rewrite HNa HNb.\n  reflexivity.\nQed.\n\nTheorem all_collection_included_empty:\n  forall U:Type, forall A:(Collection U), `Ø` ⊂ A.\nProof.\n  move => U A x H.\n  case: (noone_in_empty U x). by[].\nQed.\n\nTheorem collection_is_subcollect_of_fullcollection:\n  forall U:Type, forall A:(Collection U), A ⊂ FullCollection U.\nProof.\n  move => U A x H.\n  split.\nQed.\n\nTheorem element_in_empty_collection_to_empty_collection_eq:\n  forall (U:Type) (A:Collection U),\n    (forall x:U, x ∈ A -> x ∈ `Ø`) -> A = `Ø`.\nProof.\n  move => U A H.\n  apply mutally_included_to_eq.\n  split;[trivial|apply all_collection_included_empty].\nQed.\n\nTheorem complement_of_complement_collect_is_self:\n  forall U:Type, forall A:Collection U, A = (A^c)^c.\nProof.\n  move => U A.\n  apply mutally_included_to_eq.\n  split => x H.\n  case. by [].\n  apply DoubleNegativeElimination in H. by [].\nQed.\n\nTheorem LawOfExcludedMiddleAtComplementCollection:\n  forall U:Type, forall A:Collection U, forall x:U, x ∈ A \\/ x ∈ A^c.\nProof.\n  move => U A x.\n  apply LawOfExcludedMiddle.\nQed.\n\nTheorem notin_collect_iff_in_complement:\n  forall U:Type, forall A:Collection U, forall x:U, x ∉ A <-> x ∈ A^c.\nProof.\n  move => U A x.\n  rewrite /iff. split; apply.\nQed.\n", "meta": {"author": "seisyuu-hantatsushi", "repo": "implement_set_theory_in_coq", "sha": "49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c", "save_path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq", "path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq/implement_set_theory_in_coq-49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c/coq/axiom_of_empty.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6622225363281429}}
{"text": "Definition FizzBuzzInteger := {n : N | n mod 5 <> 0 /\\ n mod 3 <> 0}.\n\n\nInductive FizzBuzzEntry : Set :=\n| Shadow : FizzBuzzShadow -> FizzBuzzEntry\n| Num : FizzBuzzInteger -> FizzBuzzEntry\n.\n\n\nInductive FizzBuzzShadow : Set :=\n| Fizz : {n : N | n mod 3 = 0 /\\ n mod 5 <> 0} -> FizzBuzzShadow\n| Buzz : {n : N | n mod 3 <> 0 /\\ n mod 5 = 0} -> FizzBuzzShadow\n| FizzBuzz : {n : N | n mod 3 = 0 /\\ n mod 5 = 0} -> FizzBuzzShadow\n.\n\n\nDefinition initial : FizzBuzzEntry.\n  refine (Num (exist _ 1 _)).\n  split.\n  * assert (1 mod 3 = 1).\n    ** auto.\n    ** rewrite H.\n       zify. omega.\n  *  assert (1 mod 5 = 1).\n    ** auto.\n    ** rewrite H.\n       zify. omega.\nQed.\n\n\nDefinition toNat (previousEntry : FizzBuzzEntry): N :=\n  match previousEntry with\n  | Shadow (Fizz (exist _ shadowed _))     => shadowed\n  | Shadow (Buzz (exist _ shadowed _))     => shadowed\n  | Shadow (FizzBuzz (exist _ shadowed _)) => shadowed\n  | Num (exist _ n _)                      => n\n  end.\n\n\nDefinition next (previousEntry : FizzBuzzEntry): FizzBuzzEntry :=\n  fromNat (toNat previousEntry + 1).\n\n\nDefinition fromNat (n : N): FizzBuzzEntry.\n  refine (match (n mod 3 ?= 0, n mod 5 ?= 0)\n                as cmp\n                return (n mod 3 ?= 0, n mod 5 ?= 0) = cmp -> FizzBuzzEntry with\n          | (Eq, Eq) => fun pf => _\n          | (Eq, Gt) => fun pf => _\n          | (Gt, Eq) => fun pf => _\n          | (Gt, Gt) => fun pf => _\n          | _ => _\n          end eq_refl).\n  * apply pair_equal_spec in pf.\n    destruct pf.\n    apply N.compare_eq_iff in H.\n    apply N.compare_eq_iff in H0.\n    assert (n mod 3 = 0 /\\ n mod 5 = 0); auto.\n    apply (Shadow (FizzBuzz (exist _ n H1))).\n  * intros.\n    apply pair_equal_spec in H.\n    destruct H.\n    destruct H.\n    exfalso.\n    apply N.compare_lt_iff in H0.\n    assert (0 <= (n mod 5)).\n    ** apply N.mod_bound_pos.\n       *** destruct n.\n           **** zify. omega.\n           **** apply N.lt_succ_r. apply N.compare_gt_iff. auto.\n       *** zify. omega.\n    ** assert (n mod 5 < 0).\n       *** auto.\n       *** assert ((n mod 5 ?= 0) <> Lt).\n           **** apply N.compare_0_r.\n           **** contradiction.\n  * apply pair_equal_spec in pf.\n    destruct pf.\n    apply N.compare_eq_iff in H.\n    apply N.compare_gt_iff in H0.\n    assert (n mod 3 = 0 /\\ n mod 5 <> 0).\n    ** intuition.\n    ** apply (Shadow (Fizz (exist _ n H1))).\n  * intros.\n    apply pair_equal_spec in H.\n    destruct H.\n    exfalso.\n    *** assert ((n mod 3 ?= 0) <> Lt).\n        **** apply N.compare_0_r.\n        **** contradiction.\n  * apply pair_equal_spec in pf.\n    destruct pf.\n    apply N.compare_eq_iff in H0.\n    apply N.compare_gt_iff in H.\n    assert (n mod 3 <> 0 /\\ n mod 5 = 0).\n    ** intuition.\n    ** apply (Shadow (Buzz (exist _ n H1))).\n  * intros.\n    apply pair_equal_spec in H.\n    destruct H.\n    exfalso.\n    *** assert ((n mod 5 ?= 0) <> Lt).\n        **** apply N.compare_0_r.\n        **** contradiction.\n  * apply pair_equal_spec in pf.\n    destruct pf.\n    apply N.compare_gt_iff in H0.\n    apply N.compare_gt_iff in H.\n    assert (n mod 3 <> 0 /\\ n mod 5 <> 0).\n    ** intuition.\n    ** apply (Num (exist _ n H1)).\nDefined.\n", "meta": {"author": "radrow", "repo": "fizzbuzz-coq", "sha": "c4f4f29777a7295c8ce407b3a04d65cebaa7e946", "save_path": "github-repos/coq/radrow-fizzbuzz-coq", "path": "github-repos/coq/radrow-fizzbuzz-coq/fizzbuzz-coq-c4f4f29777a7295c8ce407b3a04d65cebaa7e946/FizzBuzz.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254318, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6622225176447418}}
{"text": "Definition T := nat.\n\nDefinition le := le.\n\nHint Unfold le.\n\nLemma le_refl : forall n : nat, le n n.\n  auto.\nQed.\n\nRequire Import Le.\n\nLemma le_trans : forall n m k : nat, le n m -> le m k -> le n k.\n   eauto with arith.\nQed.\n\nLemma le_antis : forall n m : nat, le n m -> le m n -> n = m.\n   eauto with arith.\nQed.", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/test-suite/modules/Nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6622225123179766}}
{"text": "Require Import String.\nRequire Import ZArith.\nRequire Import List.\nImport ListNotations.\nDefinition Identifier := string.\nDefinition id_eq_dec := string_dec.\nInductive Term : Set :=\n  | Var : Identifier -> Term\n  | Bool : bool -> Term\n  | Eq : Term -> Term -> Term\n  | And : Term -> Term -> Term\n  | Or : Term -> Term -> Term\n  | Not : Term -> Term\n  | If : Term -> Term -> Term -> Term\n  | Int : Z -> Term\n  | Plus : Term -> Term -> Term\n  | Times : Term -> Term -> Term\n  | Minus : Term -> Term -> Term\n  | Choose : Identifier -> Term -> Term.\nDefinition extendEnv {Value} (env : Identifier -> Value) \n  (var : Identifier) (newValue : Value) : Identifier -> Value :=\n  fun id => if id_eq_dec id var then newValue else env id.\nRecord EpsilonLogic :=\n mkLogic {Value : Type;\n          value_eq_dec : forall v1 v2 : Value, {v1 = v2} + {v1 <> v2};\n          eval : (Identifier -> Value) -> Term -> Value;\n          evalVar : forall env id, eval env (Var id) = env id;\n          evalIntConst :\n           forall env1 env2 i, eval env1 (Int i) = eval env2 (Int i);\n          evalIntInj :\n           forall env i j, i <> j -> eval env (Int i) <> eval env (Int j);\n          evalBoolConst :\n           forall env1 env2 b, eval env1 (Bool b) = eval env2 (Bool b);\n          evalBoolInj :\n           forall env, eval env (Bool true) <> eval env (Bool false);\n          evalEqTrue :\n           forall env a b,\n           eval env a = eval env b <->\n           eval env (Eq a b) = eval env (Bool true);\n          evalEqFalse :\n           forall env a b,\n           eval env a <> eval env b <->\n           eval env (Eq a b) = eval env (Bool false);\n          evalIfTrue :\n           forall env cond a b,\n           eval env cond = eval env (Bool true) ->\n           eval env (If cond a b) = eval env a;\n          evalIfFalse :\n           forall env cond a b,\n           eval env cond = eval env (Bool false) ->\n           eval env (If cond a b) = eval env b;\n          evalAnd :\n           forall env a b,\n           eval env (And a b) = eval env (If a b (Bool false));\n          evalOr :\n           forall env a b, eval env (Or a b) = eval env (If a (Bool true) b);\n          evalNot :\n           forall env a,\n           eval env (Not a) = eval env (If a (Bool false) (Bool true));\n          evalPlus :\n           forall env iE jE i j,\n           eval env iE = eval env (Int i) ->\n           eval env jE = eval env (Int j) ->\n           eval env (Plus iE jE) = eval env (Int (i + j));\n          evalMinus :\n           forall env iE jE i j,\n           eval env iE = eval env (Int i) ->\n           eval env jE = eval env (Int j) ->\n           eval env (Minus iE jE) = eval env (Int (i - j));\n          evalTimes :\n           forall env iE jE i j,\n           eval env iE = eval env (Int i) ->\n           eval env jE = eval env (Int j) ->\n           eval env (Times iE jE) = eval env (Int (i * j));\n          evalChoose :\n           forall env x P,\n           (exists value,\n              eval (extendEnv env x value) P = eval env (Bool true)) ->\n           eval (extendEnv env x (eval env (Choose x P))) P =\n           eval env (Bool true);\n          evalChooseDet :\n           forall env x P Q,\n           eval env P = eval env (Bool true) <->\n           eval env Q = eval env (Bool true) ->\n           eval env (Choose x P) = eval env (Choose x Q)}.\nDefinition isTheorem (L : EpsilonLogic) (t : Term) :=\n  forall env, L.(eval) env t = L.(eval) env (Bool true).\nFixpoint identity (t : Term) : Term :=\n  match t with\n  | Var x => Var x\n  | Bool b => Bool b\n  | Eq a b => Eq (identity a) (identity b)\n  | And a b => And (identity a) (identity b)\n  | Or a b => Or (identity a) (identity b)\n  | Not a => Not (identity a)\n  | If a b c => If (identity a) (identity b) (identity c)\n  | Int i => Int i\n  | Plus a b => Plus (identity a) (identity b)\n  | Times a b => Times (identity a) (identity b)\n  | Minus a b => Minus (identity a) (identity b)\n  | Choose x P => Choose x (identity P)\n  end.\nTheorem eval_eq_true_or_false :\n  forall (L : EpsilonLogic) env (t1 t2 : Term),\n  L.(eval) env (Eq t1 t2) = L.(eval) env (Bool true) \\/\n  L.(eval) env (Eq t1 t2) = L.(eval) env (Bool false).\nProof.\n(intros).\n(destruct (L.(value_eq_dec) (L.(eval) env t1) (L.(eval) env t2))).\n-\nleft.\napply -> L.(evalEqTrue).\nassumption.\n-\nright.\napply -> L.(evalEqFalse).\nassumption.\nQed.\nTheorem identity_correct :\n  forall (L : EpsilonLogic) (t : Term), isTheorem L (Eq t (identity t)).\nProof.\n(unfold isTheorem).\n(induction t; intros; simpl in *).\n-\napply -> evalEqTrue.\nreflexivity.\n-\napply -> evalEqTrue.\nreflexivity.\n-\napply -> evalEqTrue.\nspecialize IHt1 with env.\nspecialize IHt2 with env.\napply <- evalEqTrue in IHt1.\napply <- evalEqTrue in IHt2.\n(destruct (eval_eq_true_or_false L env t1 t2)).\n+\n(rewrite H).\n(apply evalEqTrue in H).\n(rewrite H in IHt1).\n(rewrite IHt1 in IHt2).\nsymmetry.\napply -> evalEqTrue.\nassumption.\n+\n(rewrite H).\n(apply evalEqFalse in H).\n(assert (eval L env (identity t1) <> eval L env (identity t2)) by congruence).\nsymmetry.\napply -> evalEqFalse.\nassumption.\nAdmitted.\nFixpoint free_vars (t : Term) : list Identifier :=\n  match t with\n  | Var x => [x]\n  | Int _ => []\n  | Bool _ => []\n  | Eq a b => free_vars a ++ free_vars b\n  | And a b => free_vars a ++ free_vars b\n  | Or a b => free_vars a ++ free_vars b\n  | Not a => free_vars a\n  | If a b c => free_vars a ++ free_vars b ++ free_vars c\n  | Plus a b => free_vars a ++ free_vars b\n  | Times a b => free_vars a ++ free_vars b\n  | Minus a b => free_vars a ++ free_vars b\n  | Choose x P =>\n      filter (fun y => if id_eq_dec x y then false else true) (free_vars P)\n  end.\nAxiom (fresh_var : list Identifier -> Identifier).\nAxiom (fresh_var_unique : forall exclude, ~ In (fresh_var exclude) exclude).\nDefinition Divide (t1 : Term) (t2 : Term) :=\n  let x := fresh_var (free_vars t1 ++ free_vars t2) in\n  Choose x (Eq t1 (Times (Var x) t2)).\nLemma extendEnv_eq :\n  forall Value env x (val : Value), (extendEnv env x val) x = val.\nProof.\n(intros).\n(unfold extendEnv).\n(destruct (id_eq_dec x x); congruence).\n(* Auto-generated comment: Succeeded. *)\n\n", "meta": {"author": "uwplse", "repo": "analytics-data", "sha": "64d3fccac3a25230d1adb59fcf1aded3f375029a", "save_path": "github-repos/coq/uwplse-analytics-data", "path": "github-repos/coq/uwplse-analytics-data/analytics-data-64d3fccac3a25230d1adb59fcf1aded3f375029a/diffs-annotated-fixed-2/5/user-5-session-19.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6622225119431676}}
{"text": "(** * Poly: Polymorphism and Higher-Order Functions *)\n\n(* Final reminder: Please do not put solutions to the exercises in\n   publicly accessible places.  Thank you!! *)\n\nRequire Export Lists.\n\n(* ################################################################# *)\n(** * Polymorphism *)\n\n(** In this chapter we continue our development of basic\n    concepts of functional programming.  The critical new ideas are\n    _polymorphism_ (abstracting functions over the types of the data\n    they manipulate) and _higher-order functions_ (treating functions\n    as data).  We begin with polymorphism. *)\n\n(* ================================================================= *)\n(** ** Polymorphic Lists *)\n\n(** For the last couple of chapters, we've been working just\n    with lists of numbers.  Obviously, interesting programs also need\n    to be able to manipulate lists with elements from other types --\n    lists of strings, lists of booleans, lists of lists, etc.  We\n    _could_ just define a new inductive datatype for each of these,\n    for example... *)\n\nInductive boollist : Type :=\n  | bool_nil : boollist\n  | bool_cons : bool -> boollist -> boollist.\n\n(** ... but this would quickly become tedious, partly because we\n    have to make up different constructor names for each datatype, but\n    mostly because we would also need to define new versions of all\n    our list manipulating functions ([length], [rev], etc.) for each\n    new datatype definition. *)\n\n(** To avoid all this repetition, Coq supports _polymorphic_\n    inductive type definitions.  For example, here is a _polymorphic\n    list_ datatype. *)\n\nInductive list (X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\n(** This is exactly like the definition of [natlist] from the\n    previous chapter, except that the [nat] argument to the [cons]\n    constructor has been replaced by an arbitrary type [X], a binding\n    for [X] has been added to the header, and the occurrences of\n    [natlist] in the types of the constructors have been replaced by\n    [list X].  (We can re-use the constructor names [nil] and [cons]\n    because the earlier definition of [natlist] was inside of a\n    [Module] definition that is now out of scope.) \n\n    What sort of thing is [list] itself?  One good way to think\n    about it is that [list] is a _function_ from [Type]s to\n    [Inductive] definitions; or, to put it another way, [list] is a\n    function from [Type]s to [Type]s.  For any particular type [X],\n    the type [list X] is an [Inductive]ly defined set of lists whose\n    elements are of type [X]. *)\n\n(** With this definition, when we use the constructors [nil] and\n    [cons] to build lists, we need to tell Coq the type of the\n    elements in the lists we are building -- that is, [nil] and [cons]\n    are now _polymorphic constructors_.  Observe the types of these\n    constructors: *)\n\nCheck nil.\n(* ===> nil : forall X : Type, list X *)\nCheck cons.\n(* ===> cons : forall X : Type, X -> list X -> list X *)\n\n(** (Side note on notation: In .v files, the \"forall\" quantifier\n    is spelled out in letters.  In the generated HTML files and in the\n    way various IDEs show .v files (with certain settings of their\n    display controls), [forall] is usually typeset as the usual\n    mathematical \"upside down A,\" but you'll still see the spelled-out\n    \"forall\" in a few places.  This is just a quirk of typesetting:\n    there is no difference in meaning.) *)\n\n(** The \"[forall X]\" in these types can be read as an additional\n    argument to the constructors that determines the expected types of\n    the arguments that follow.  When [nil] and [cons] are used, these\n    arguments are supplied in the same way as the others.  For\n    example, the list containing [2] and [1] is written like this: *)\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\n(** (We've written [nil] and [cons] explicitly here because we haven't\n    yet defined the [ [] ] and [::] notations for the new version of\n    lists.  We'll do that in a bit.) *)\n\n(** We can now go back and make polymorphic versions of all the\n    list-processing functions that we wrote before.  Here is [repeat],\n    for example: *)\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\n(** As with [nil] and [cons], we can use [repeat] by applying it\n    first to a type and then to its list argument: *)\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity.  Qed.\n\n(** To use [repeat] to build other kinds of lists, we simply\n    instantiate it with an appropriate type parameter: *)\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity.  Qed.\n\n\nModule MumbleGrumble.\n\n(** **** Exercise: 2 stars (mumble_grumble)  *)\n(** Consider the following two inductively defined types. *)\n\nInductive mumble : Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\n\nInductive grumble (X:Type) : Type :=\n  | d : mumble -> grumble X\n  | e : X -> grumble X.\n\n(** Which of the following are well-typed elements of [grumble X] for\n    some type [X]?\n      - [d (b a 5)]\n      - [d mumble (b a 5)]\n      - [d bool (b a 5)]\n      - [e bool true]\n      - [e mumble (b c 0)]\n      - [e bool (b c 0)]\n      - [c]\n(* FILL IN HERE *)\n*)\n(** [] *)\n\nEnd MumbleGrumble.\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Annotation Inference *)\n\n(** Let's write the definition of [repeat] again, but this time we\n    won't specify the types of any of the arguments.  Will Coq still\n    accept it? *)\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0        => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\n(** Indeed it will.  Let's see what type Coq has assigned to [repeat']: *)\n\nCheck repeat'.\n(* ===> forall X : Type, X -> nat -> list X *)\nCheck repeat.\n(* ===> forall X : Type, X -> nat -> list X *)\n\n(** It has exactly the same type type as [repeat].  Coq was able\n    to use _type inference_ to deduce what the types of [X], [x], and\n    [count] must be, based on how they are used.  For example, since\n    [X] is used as an argument to [cons], it must be a [Type], since\n    [cons] expects a [Type] as its first argument; matching [count]\n    with [0] and [S] means it must be a [nat]; and so on.\n\n    This powerful facility means we don't always have to write\n    explicit type annotations everywhere, although explicit type\n    annotations are still quite useful as documentation and sanity\n    checks, so we will continue to use them most of the time.  You\n    should try to find a balance in your own code between too many\n    type annotations (which can clutter and distract) and too\n    few (which forces readers to perform type inference in their heads\n    in order to understand your code). *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Argument Synthesis *)\n\n(** To use a polymorphic function, we need to pass it one or\n    more types in addition to its other arguments.  For example, the\n    recursive call in the body of the [repeat] function above must\n    pass along the type [X].  But since the second argument to\n    [repeat] is an element of [X], it seems entirely obvious that the\n    first argument can only be [X] -- why should we have to write it\n    explicitly?\n\n    Fortunately, Coq permits us to avoid this kind of redundancy.  In\n    place of any type argument we can write the \"implicit argument\"\n    [_], which can be read as \"Please try to figure out for yourself\n    what belongs here.\"  More precisely, when Coq encounters a [_], it\n    will attempt to _unify_ all locally available information -- the\n    type of the function being applied, the types of the other\n    arguments, and the type expected by the context in which the\n    application appears -- to determine what concrete type should\n    replace the [_].\n\n    This may sound similar to type annotation inference -- indeed, the\n    two procedures rely on the same underlying mechanisms.  Instead of\n    simply omitting the types of some arguments to a function, like\n\n      repeat' X x count : list X :=\n\n    we can also replace the types with [_]\n\n      repeat' (X : _) (x : _) (count : _) : list X :=\n\n    to tell Coq to attempt to infer the missing information.\n\n    Using implicit arguments, the [count] function can be written like\n    this: *)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n(** In this instance, we don't save much by writing [_] instead of\n    [X].  But in many cases the difference in both keystrokes and\n    readability is nontrivial.  For example, suppose we want to write\n    down a list containing the numbers [1], [2], and [3].  Instead of\n    writing this... *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...we can use argument synthesis to write this: *)\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ----------------------------------------------------------------- *)\n(** *** Implicit Arguments *)\n\n(** We can go further and even avoid writing [_]'s in most cases by\n    telling Coq _always_ to infer the type argument(s) of a given\n    function.  The [Arguments] directive specifies the name of the\n    function (or constructor) and then lists its argument names, with\n    curly braces around any arguments to be treated as implicit.  (If\n    some arguments of a definition don't have a name, as is often the\n    case for constructors, they can be marked with a wildcard pattern\n    [_].) *)\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\n(** Now, we don't have to supply type arguments at all: *)\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\n(** Alternatively, we can declare an argument to be implicit\n    when defining the function itself, by surrounding it in curly\n    braces instead of parens.  For example: *)\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0        => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n(** (Note that we didn't even have to provide a type argument to the\n    recursive call to [repeat''']; indeed, it would be invalid to\n    provide one!)\n\n    We will use the latter style whenever possible, but we will\n    continue to use use explicit [Argument] declarations for\n    [Inductive] constructors.  The reason for this is that marking the\n    parameter of an inductive type as implicit causes it to become\n    implicit for the type itself, not just for its constructors.  For\n    instance, consider the following alternative definition of the\n    [list] type: *)\n\nInductive list' {X:Type} : Type :=\n  | nil' : list'\n  | cons' : X -> list' -> list'.\n\n(** Because [X] is declared as implicit for the _entire_ inductive\n    definition including [list'] itself, we now have to write just\n    [list'] whether we are talking about lists of numbers or booleans\n    or anything else, rather than [list' nat] or [list' bool] or\n    whatever; this is a step too far. *)\n\n(** Let's finish by re-implementing a few other standard list\n    functions on our new polymorphic lists... *)\n\nFixpoint app {X : Type} (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity.  Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity.  Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Supplying Type Arguments Explicitly *)\n\n(** One small problem with declaring arguments [Implicit] is\n    that, occasionally, Coq does not have enough local information to\n    determine a type argument; in such cases, we need to tell Coq that\n    we want to give the argument explicitly just this time.  For\n    example, suppose we write this: *)\n\nFail Definition mynil := nil.\n\n(** (The [Fail] qualifier that appears before [Definition] can be\n    used with _any_ command, and is used to ensure that that command\n    indeed fails when executed. If the command does fail, Coq prints\n    the corresponding error message, but continues processing the rest\n    of the file.)\n\n    Here, Coq gives us an error because it doesn't know what type\n    argument to supply to [nil].  We can help it by providing an\n    explicit type declaration (so that Coq has more information\n    available when it gets to the \"application\" of [nil]): *)\n\nDefinition mynil : list nat := nil.\n\n(** Alternatively, we can force the implicit arguments to be explicit by\n   prefixing the function name with [@]. *)\n\nCheck @nil.\n\nDefinition mynil' := @nil nat.\n\n(** Using argument synthesis and implicit arguments, we can\n    define convenient notation for lists, as before.  Since we have\n    made the constructor type arguments implicit, Coq will know to\n    automatically infer these when we use the notations. *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** Now lists can be written just the way we'd hope: *)\n\nDefinition list123''' := [1; 2; 3].\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, optional (poly_exercises)  *)\n(** Here are a few simple exercises, just like ones in the [Lists]\n    chapter, for practice with polymorphism.  Complete the proofs below. *)\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  (* FILL IN HERE *) Admitted.\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(** [] *)\n\n(** **** Exercise: 2 stars, optional (more_poly_exercises)  *)\n(** Here are some slightly more interesting ones... *)\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Pairs *)\n\n(** Following the same pattern, the type definition we gave in\n    the last chapter for pairs of numbers can be generalized to\n    _polymorphic pairs_, often called _products_: *)\n\nInductive prod (X Y : Type) : Type :=\n| pair : X -> Y -> prod X Y.\n\nArguments pair {X} {Y} _ _.\n\n(** As with lists, we make the type arguments implicit and define the\n    familiar concrete notation. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** We can also use the [Notation] mechanism to define the standard\n    notation for product _types_: *)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** (The annotation [: type_scope] tells Coq that this abbreviation\n    should only be used when parsing types.  This avoids a clash with\n    the multiplication symbol.) *)\n\n(** It is easy at first to get [(x,y)] and [X*Y] confused.\n    Remember that [(x,y)] is a _value_ built from two other values,\n    while [X*Y] is a _type_ built from two other types.  If [x] has\n    type [X] and [y] has type [Y], then [(x,y)] has type [X*Y]. *)\n\n(** The first and second projection functions now look pretty\n    much as they would in any functional programming language. *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\n(** The following function takes two lists and combines them\n    into a list of pairs.  In other functional languages, it is often\n    called [zip]; we call it [combine] for consistency with Coq's\n    standard library. *)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\n(** **** Exercise: 1 star, optional (combine_checks)  *)\n(** Try answering the following questions on paper and\n    checking your answers in coq:\n    - What is the type of [combine] (i.e., what does [Check\n      @combine] print?)\n    - What does\n\n        Compute (combine [1;2] [false;false;true;true]).\n\n      print? *)\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (split)  *)\n(** The function [split] is the right inverse of [combine]: it takes a\n    list of pairs and returns a pair of lists.  In many functional\n    languages, it is called [unzip].\n\n    Fill in the definition of [split] below.  Make sure it passes the\n    given unit test. *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Options *)\n\n(** One last polymorphic type for now: _polymorphic options_,\n    which generalize [natoption] from the previous chapter: *)\n\nInductive option (X:Type) : Type :=\n  | Some : X -> option X\n  | None : option X.\n\nArguments Some {X} _.\nArguments None {X}.\n\n(** We can now rewrite the [nth_error] function so that it works\n    with any type of lists. *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, optional (hd_error_poly)  *)\n(** Complete the definition of a polymorphic version of the\n    [hd_error] function from the last chapter. Be sure that it\n    passes the unit tests below. *)\n\nDefinition hd_error {X : Type} (l : list X) : option X \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.\n\n(** Once again, to force the implicit arguments to be explicit,\n    we can use [@] before the name of the function. *)\n\nCheck @hd_error.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\n (* FILL IN HERE *) Admitted.\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Functions as Data *)\n\n(** Like many other modern programming languages -- including\n    all functional languages (ML, Haskell, Scheme, Scala, Clojure,\n    etc.) -- Coq treats functions as first-class citizens, allowing\n    them to be passed as arguments to other functions, returned as\n    results, stored in data structures, etc.*)\n\n(* ================================================================= *)\n(** ** Higher-Order Functions *)\n\n(** Functions that manipulate other functions are often called\n    _higher-order_ functions.  Here's a simple one: *)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\n(** The argument [f] here is itself a function (from [X] to\n    [X]); the body of [doit3times] applies [f] three times to some\n    value [n]. *)\n\nCheck @doit3times.\n(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity.  Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity.  Qed.\n\n(* ================================================================= *)\n(** ** Filter *)\n\n(** Here is a more useful higher-order function, taking a list\n    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])\n    and \"filtering\" the list, returning a new list containing just\n    those elements for which the predicate returns [true]. *)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | []     => []\n  | h :: t => if test h then h :: (filter test t)\n                        else       filter test t\n  end.\n\n(** For example, if we apply [filter] to the predicate [evenb]\n    and a list of numbers [l], it returns a list containing just the\n    even members of [l]. *)\n\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity.  Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  beq_nat (length l) 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** We can use [filter] to give a concise version of the\n    [countoddmembers] function from the [Lists] chapter. *)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity.  Qed.\n\n(* ================================================================= *)\n(** ** Anonymous Functions *)\n\n(** It is arguably a little sad, in the example just above, to\n    be forced to define the function [length_is_1] and give it a name\n    just to be able to pass it as an argument to [filter], since we\n    will probably never use it again.  Moreover, this is not an\n    isolated example: when using higher-order functions, we often want\n    to pass as arguments \"one-off\" functions that we will never use\n    again; having to give each of these functions a name would be\n    tedious.\n\n    Fortunately, there is a better way.  We can construct a function\n    \"on the fly\" without declaring it at the top level or giving it a\n    name. *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity.  Qed.\n\n(** The expression [(fun n => n * n)] can be read as \"the function\n    that, given a number [n], yields [n * n].\" *)\n\n(** Here is the [filter] example, rewritten to use an anonymous\n    function. *)\n\nExample test_filter2':\n    filter (fun l => beq_nat (length l) 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 2 stars (filter_even_gt7)  *)\n(** Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\n (* FILL IN HERE *) Admitted.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (partition)  *)\n(** Use [filter] to write a Coq function [partition]:\n\n      partition : forall X : Type,\n                  (X -> bool) -> list X -> list X * list X\n\n   Given a set [X], a test function of type [X -> bool] and a [list\n   X], [partition] should return a pair of lists.  The first member of\n   the pair is the sublist of the original list containing the\n   elements that satisfy the test, and the second is the sublist\n   containing those that fail the test.  The order of elements in the\n   two sublists should be the same as their order in the original\n   list. *)\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\n(* FILL IN HERE *) Admitted.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Map *)\n\n(** Another handy higher-order function is called [map]. *)\n\nFixpoint map {X Y:Type} (f:X->Y) (l:list X) : (list Y) :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]\n    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has\n    been applied to each element of [l] in turn.  For example: *)\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** The element types of the input and output lists need not be\n    the same, since [map] takes _two_ type arguments, [X] and [Y]; it\n    can thus be applied to a list of numbers and a function from\n    numbers to booleans to yield a list of booleans: *)\n\nExample test_map2:\n  map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity.  Qed.\n\n(** It can even be applied to a list of numbers and\n    a function from numbers to _lists_ of booleans to\n    yield a _list of lists_ of booleans: *)\n\nExample test_map3:\n    map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 3 stars (map_rev)  *)\n(** Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (flat_map)  *)\n(** The function [map] maps a [list X] to a [list Y] using a function\n    of type [X -> Y].  We can define a similar function, [flat_map],\n    which maps a [list X] to a [list Y] using a function [f] of type\n    [X -> list Y].  Your definition should work by 'flattening' the\n    results of [f], like so:\n\n        flat_map (fun n => [n;n+1;n+2]) [1;5;10]\n      = [1; 2; 3; 5; 6; 7; 10; 11; 12].\n*)\n\nFixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X)\n                   : (list Y) \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Lists are not the only inductive type that we can write a\n    [map] function for.  Here is the definition of [map] for the\n    [option] type: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\n(** **** Exercise: 2 stars, optional (implicit_args)  *)\n(** The definitions and uses of [filter] and [map] use implicit\n    arguments in many places.  Replace the curly braces around the\n    implicit arguments with parentheses, and then fill in explicit\n    type parameters where necessary and use Coq to check that you've\n    done so correctly.  (This exercise is not to be turned in; it is\n    probably easiest to do it on a _copy_ of this file that you can\n    throw away afterwards.)  [] *)\n\n(* ================================================================= *)\n(** ** Fold *)\n\n(** An even more powerful higher-order function is called\n    [fold].  This function is the inspiration for the \"[reduce]\"\n    operation that lies at the heart of Google's map/reduce\n    distributed programming framework. *)\n\nFixpoint fold {X Y:Type} (f: X->Y->Y) (l:list X) (b:Y)\n                         : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(** Intuitively, the behavior of the [fold] operation is to\n    insert a given binary operator [f] between every pair of elements\n    in a given list.  For example, [ fold plus [1;2;3;4] ] intuitively\n    means [1+2+3+4].  To make this precise, we also need a \"starting\n    element\" that serves as the initial second input to [f].  So, for\n    example,\n\n       fold plus [1;2;3;4] 0\n\n    yields\n\n       1 + (2 + (3 + (4 + 0))).\n\n    Some more examples: *)\n\nCheck (fold andb).\n(* ===> fold andb : list bool -> bool -> bool *)\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, advanced (fold_types_different)  *)\n(** Observe that the type of [fold] is parameterized by _two_ type\n    variables, [X] and [Y], and the parameter [f] is a binary operator\n    that takes an [X] and a [Y] and returns a [Y].  Can you think of a\n    situation where it would be useful for [X] and [Y] to be\n    different? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ================================================================= *)\n(** ** Functions That Construct Functions *)\n\n(** Most of the higher-order functions we have talked about so\n    far take functions as arguments.  Let's look at some examples that\n    involve _returning_ functions as the results of other functions.\n    To begin, here is a function that takes a value [x] (drawn from\n    some type [X]) and returns a function from [nat] to [X] that\n    yields [x] whenever it is called, ignoring its [nat] argument. *)\n\nDefinition constfun {X: Type} (x: X) : nat->X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** In fact, the multiple-argument functions we have already\n    seen are also examples of passing functions as data.  To see why,\n    recall the type of [plus]. *)\n\nCheck plus.\n(* ==> nat -> nat -> nat *)\n\n(** Each [->] in this expression is actually a _binary_ operator\n    on types.  This operator is _right-associative_, so the type of\n    [plus] is really a shorthand for [nat -> (nat -> nat)] -- i.e., it\n    can be read as saying that \"[plus] is a one-argument function that\n    takes a [nat] and returns a one-argument function that takes\n    another [nat] and returns a [nat].\"  In the examples above, we\n    have always applied [plus] to both of its arguments at once, but\n    if we like we can supply just the first.  This is called _partial\n    application_. *)\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity.  Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity.  Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\nModule Exercises.\n\n(** **** Exercise: 2 stars (fold_length)  *)\n(** Many common functions on lists can be implemented in terms of\n   [fold].  For example, here is an alternative definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length]. *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\n(* FILL IN HERE *) Admitted.\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  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.\n\n(** Write down a theorem [fold_map_correct] in Coq stating that\n   [fold_map] is correct, and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (currying)  *)\n(** In Coq, a function [f : A -> B -> C] really has the type [A\n    -> (B -> C)].  That is, if you give [f] a value of type [A], it\n    will give you function [f' : B -> C].  If you then give [f'] a\n    value of type [B], it will return a value of type [C].  This\n    allows for partial application, as in [plus3].  Processing a list\n    of arguments with functions that return functions is called\n    _currying_, in honor of the logician Haskell Curry.\n\n    Conversely, we can reinterpret the type [A -> B -> C] as [(A *\n    B) -> C].  This is called _uncurrying_.  With an uncurried binary\n    function, both arguments must be given at once as a pair; there is\n    no partial application. *)\n\n(** We can define currying as follows: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** As an exercise, define its inverse, [prod_uncurry].  Then prove\n    the theorems below to show that the two are inverses. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.\n\n(** As a (trivial) example of the usefulness of currying, we can use it\n    to shorten one of the examples that we saw above: *)\n\nExample test_map2: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** Thought exercise: before running the following commands, can you\n    calculate the types of [prod_curry] and [prod_uncurry]? *)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (nth_error_informal)  *)\n(** Recall the definition of the [nth_error] function:\n\n   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n     match l with\n     | [] => None\n     | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\n     end.\n\n   Write an informal proof of the following theorem:\n\n   forall X n l, length l = n -> @nth_error X l n = None\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (church_numerals)  *)\n(** This exercise explores an alternative way of defining natural\n    numbers, using the so-called _Church numerals_, named after\n    mathematician Alonzo Church.  We can represent a natural number\n    [n] as a function that takes a function [f] as a parameter and\n    returns [f] iterated [n] times. *)\n\nModule Church.\nDefinition nat := forall X : Type, (X -> X) -> X -> X.\n\n(** Let's see how to write some numbers with this notation. Iterating\n    a function once should be the same as just applying it.  Thus: *)\n\nDefinition one : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** Similarly, [two] should apply [f] twice to its argument: *)\n\nDefinition two : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** Defining [zero] is somewhat trickier: how can we \"apply a function\n    zero times\"?  The answer is actually simple: just return the\n    argument untouched. *)\n\nDefinition zero : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(** More generally, a number [n] can be written as [fun X f x => f (f\n    ... (f x) ...)], with [n] occurrences of [f].  Notice in\n    particular how the [doit3times] function we've defined previously\n    is actually just the Church representation of [3]. *)\n\nDefinition three : nat := @doit3times.\n\n(** Complete the definitions of the following functions. Make sure\n    that the corresponding unit tests pass by proving them with\n    [reflexivity]. *)\n\n(** Successor of a natural number: *)\n\nDefinition succ (n : nat) : nat \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.\n\nExample succ_1 : succ zero = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample succ_2 : succ one = two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample succ_3 : succ two = three.\nProof. (* FILL IN HERE *) Admitted.\n\n(** Addition of two natural numbers: *)\n\nDefinition plus (n m : nat) : nat \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.\n\nExample plus_1 : plus zero one = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample plus_2 : plus two three = plus three two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. (* FILL IN HERE *) Admitted.\n\n(** Multiplication: *)\n\nDefinition mult (n m : nat) : nat \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.\n\nExample mult_1 : mult one one = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample mult_2 : mult zero (plus three three) = zero.\nProof. (* FILL IN HERE *) Admitted.\n\nExample mult_3 : mult two three = plus three three.\nProof. (* FILL IN HERE *) Admitted.\n\n(** Exponentiation: *)\n\n(** (_Hint_: Polymorphism plays a crucial role here.  However,\n    choosing the right type to iterate over can be tricky.  If you hit\n    a \"Universe inconsistency\" error, try iterating over a different\n    type: [nat] itself is usually problematic.) *)\n\nDefinition exp (n m : nat) : nat \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.\n\nExample exp_1 : exp two two = plus two two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample exp_2 : exp three two = plus (mult two (mult two two)) one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample exp_3 : exp three zero = one.\nProof. (* FILL IN HERE *) Admitted.\n\nEnd Church.\n(** [] *)\n\nEnd Exercises.\n\n(** $Date: 2016-09-20 23:50:11 +0900 (2016年09月20日 (火)) $ *)\n\n", "meta": {"author": "hkrsnd", "repo": "coq", "sha": "199cec72dd10c5b08b32f4bd14679a1b544d758f", "save_path": "github-repos/coq/hkrsnd-coq", "path": "github-repos/coq/hkrsnd-coq/coq-199cec72dd10c5b08b32f4bd14679a1b544d758f/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.8705972700870909, "lm_q1q2_score": 0.6622203911582674}}
{"text": "Require Import Setoid.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Program.Equality.\nImport ListNotations.\nRequire Import Lib.EqDec.\n\nClass LinearOrder (A: Type) := {\n  ord      : A -> A -> bool;\n  refl     : forall x: A, ord x x = true;\n  anti_sym : forall x y: A, ord x y = true -> ord y x = true -> x = y;\n  trans    : forall x y z: A, ord x y = true -> ord y z = true -> ord x z = true;\n  full     : forall x y, ord x y = true \\/ ord y x = true;\n}.\n\nGlobal Instance LO_is_EqDec (A: Type) `{LinearOrder A}: EqDec A.\nProof.\n  exists (fun x y => andb (ord x y) (ord y x)). intros x y. \n  destruct (andb (ord x y) (ord y x)) eqn:e; constructor.\n  - rewrite Bool.andb_true_iff in e. destruct e. apply anti_sym; auto.\n  - intros E. subst. rewrite refl in e. cbn in *. inversion e.\nDefined.\n\nInductive Sorted {A: Type} `{LinearOrder A} : list A -> Prop :=\n  | SortedNil : Sorted []\n  | SortedSing : forall h: A, Sorted [h]\n  | SortedCons : forall h h' : A, forall t: list A,\n      Sorted (h' :: t) -> ord h h' = true -> Sorted (h :: h' :: t).\n\nFixpoint count {A: Type} (p: A -> bool) (l: list A): nat :=\n  match l with\n  | nil => O\n  | cons h t => if p h then S (count p t) else count p t\n  end.\n\nDefinition permutation {A: Type} (a b : list A) :=\n  forall p : A -> bool, count p a = count p b.\n\n\nLemma sorted_without_head {A: Type} `{LinearOrder A} : forall l: list A, forall a: A,\n  Sorted (a::l) -> Sorted l.\nProof.\n  intros l. induction l; intro h.\n  - intros _. constructor.\n  - intro s. dependent destruction s. assumption.\nQed.\n\nLemma sorted_with_head {A: Type} `{LinearOrder A} : forall l: list A, forall a h: A,\n  Sorted (h::l) -> ord a h = true -> Sorted (a::h::l).\nProof.\n  intros l a h sort o. constructor.\n  - trivial.\n  - assumption.\nQed. \n\nLemma sorted_head_relation {A: Type} `{L: LinearOrder A} :\n  forall l: list A, forall h: A, Sorted (h::l) -> forall x: A, In x (h :: l) ->\n  ord h x = true.\nProof.\n  intros l. induction l; intros h sort x H.\n  - cbn in H. destruct H.\n    + subst. apply refl.\n    + contradiction.\n  - cbn in H. destruct H.\n    + subst. apply refl.\n    + assert (ord a x = true).\n      { apply IHl.\n        - apply (sorted_without_head _ h). assumption.\n        - assumption.\n      }\n      dependent destruction sort; try discriminate.\n      apply (trans h a x); assumption.\nQed.\n\nTheorem perm_sym {A: Type} : forall l l': list A, permutation l l' <-> permutation l' l.\nProof.\n  intros l l'. unfold permutation. split; intros H p; symmetry; apply (H p).\nQed.\n\nTheorem perm_trans {A: Type} : forall x y z: list A, \n  permutation x y -> permutation y z -> permutation x z.\nProof.\n  intros x y z H H0. unfold permutation in *. intro p. specialize (H p). specialize (H0 p).\n  transitivity (count p y); assumption.\nQed.\n\nLemma perm_without_head {A: Type} : forall l l': list A, forall a: A,\n  permutation (cons a l) (cons a l') -> permutation l l'.\nProof.\n  - intros l l' a H. unfold permutation in *. intro p. specialize (H p). cbn in H.\n    destruct (p a).\n    + inversion H. reflexivity. \n    + assumption.\nQed.\n\nLemma perm_with_head {A: Type} : forall l l': list A, forall a: A,\n  permutation l l' -> permutation (a::l) (a::l').\nProof.\n  intros l l' a perm. unfold permutation in *. intro p. specialize (perm p).\n  cbn. destruct (p a).\n  - destruct perm. trivial.\n  - assumption.\nQed.\n\nTheorem perm_for_element {A: Type} : forall l l': list A, forall x: A,\n  permutation l l' -> In x l' -> In x l.\nProof.\n  unfold permutation. intros l. induction l; intros l' x perm H.\n  - destruct l'.\n    + cbn in H. destruct H.\n    + specialize (perm (fun x => true)). cbn in perm. discriminate.\n  - destruct l'.\n    + cbn in H. destruct H.\n    + cbn. cbn in H. destruct H.\n      * subst. left.\nAbort.\n\nLemma singleton_perm {A: Type} `{L: LinearOrder A} (x y: A) :\n   x = y <-> permutation [x] [y].\nProof.\n  split.\n  - intros [] p. auto.\n  - intros perm. specialize (perm (eqf x)). cbn [count] in *. rewrite eqf_refl in perm.\n    destruct (eqf x y) eqn:e.\n    + rewrite <- eqf_iff in e; auto.\n    + inversion perm.\nQed.\n\nLemma week_eqf_in {A: Type} `{L: EqDec A} :\n  forall x: A, forall l: list A, In x l <-> count (eqf x) l <> O.\nProof.\n  intros x l. split.\n  - intros H. induction l.\n    + cbn in H. contradiction.\n    + cbn. destruct (eqf x a) eqn:eq.\n      * apply PeanoNat.Nat.neq_succ_0.\n      * apply IHl. destruct H; auto. subst. rewrite eqf_refl in eq.\n        inversion eq.\n  - intro H. induction l.\n    + cbn in H. contradiction.\n    + cbn. destruct (eqf x a) eqn:eq.\n      * left. apply eqf_iff. rewrite eqf_sym. assumption.\n      * right. apply IHl. cbn in H. rewrite eq in H. assumption.\nQed.\n\nTheorem weak_perm_in {A: Type} `{L: EqDec A} : forall l l': list A, forall x: A,  \n  permutation l l' -> In x l' -> In x l.\nProof.\n  unfold permutation. intros l l' x perm H. specialize (perm (eqf x)). cut (count (eqf x) l' <> O).\n  - intro H0. rewrite <- perm in H0. rewrite week_eqf_in. assumption.\n  - apply week_eqf_in. assumption.\nQed.\n\nLemma sorted_head_eq {A: Type} `{L: LinearOrder A} : forall l l': list A, forall a a': A, \n  permutation (a :: l) (a' :: l') -> Sorted (a :: l) -> Sorted (a' :: l') -> a = a'.\nProof.\n  intros l l' h h' perm s1 s2.\n  destruct (full h h').\n  - assert (In h (h'::l')).\n    + apply (weak_perm_in (h'::l') (h :: l) h); try apply perm_sym; auto.\n      cbn. left. reflexivity.\n    + assert (ord h' h = true) by (apply (sorted_head_relation l' h'); auto).\n      apply anti_sym; auto.\n  - assert (In h' (h::l)).\n    + apply (weak_perm_in (h::l) (h' :: l') h'); auto.\n      cbn. left. reflexivity.\n    + assert (ord h h' = true) by (apply (sorted_head_relation l h); auto).\n      apply anti_sym; auto.\nQed.\n\n(* Unique *)\n\nTheorem sorted_unique_representation {A: Type} `{L: LinearOrder A} :\n  forall l l': list A, permutation l l' -> Sorted l -> Sorted l' -> l = l'.\nProof.\n  intros l. induction l; intros l' perm sort sort'.\n  - destruct l'; auto. specialize (perm (fun _ => true)). cbn in perm. discriminate.\n  - destruct l'.\n    + specialize (perm (fun _ => true)). cbn in perm. discriminate.\n    + assert (a = a0) by (apply (sorted_head_eq l l'); auto). subst.\n      f_equal. apply IHl.\n      * apply (perm_without_head _ _ a0); auto.\n      * apply (sorted_without_head _ a0). auto.\n      * apply (sorted_without_head _ a0). auto.\nQed.", "meta": {"author": "speederking07", "repo": "magisterka", "sha": "602d1e328ac4a396c282e241744d129573a65381", "save_path": "github-repos/coq/speederking07-magisterka", "path": "github-repos/coq/speederking07-magisterka/magisterka-602d1e328ac4a396c282e241744d129573a65381/backup/Lib/Sorted.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6622203898813404}}
{"text": "(** * Tactics: More Basic Tactics *)\n\n\n(** This chapter introduces several more proof strategies and\n    tactics that allow us to prove more interesting properties of\n    functional programs.  We will see:\n\n    - how to use auxiliary lemmas in both \"forward-style\" and\n      \"backward-style\" proofs;\n    - how to reason about data constructors (in particular, how to use\n      the fact that they are injective and disjoint);\n    - how to create a strong induction hypothesis (and when such\n      strengthening is required); and\n    - more details on how to reason by case analysis. *)\n\nRequire Export Poly.\n\n(* ################################################################# *)\n\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    exactly the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n\n(** At this point, we could finish with \"[rewrite -> eq2.\n    reflexivity.]\" as we have done several times before.  We can\n    achieve the same effect in a single step by using the [apply]\n    tactic instead: *)\n\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** You may find it instructive to experiment with this proof\n    and see if there is a way to complete it using just [rewrite]\n    instead of [apply]. *)\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] that binds some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex)  *)\n(** Complete the following proof without using [simpl]. *)\n\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 3 = true ->\n     oddb 4 = true.\nProof.\n  intros. apply H. apply H0.\nQed.\n\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal exactly -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  simpl.\n  (* Here we cannot use [apply] directly *)\nAbort.\n\n(** In this case we can use the [symmetry] tactic, which switches the\n    left and right sides of an equality in the goal. *)\n\nTheorem silly3 : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  symmetry.\n  simpl. (* Actually, this [simpl] is unnecessary, since\n            [apply] will perform simplification first. *)\n  apply H.  Qed.\n\n(** **** Exercise: 3 stars (apply_exercise1)  *)\n(** (_Hint_: You can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [SearchAbout] is\n    your friend.) *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  intros. induction l'.\n  - simpl. rewrite H. symmetry. apply rev_involutive.\n  - simpl. intros. rewrite H. rewrite rev_involutive. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, optional (apply_rewrite)  *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  What are the situations where both can usefully be\n    applied?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(* ################################################################# *)\n(** * The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might like to pull it out\n    as a lemma recording, once and for all, the fact that equality is\n    transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to prove the above\n    example.  However, to do this we need a slight refinement of the\n    [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n\n(** If we simply tell Coq [apply trans_eq] at this point, it can\n    tell (by matching the goal against the conclusion of the lemma)\n    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and\n    [o] with [[e,f]].  However, the matching process doesn't determine\n    an instantiation for [m]: we have to supply one explicitly by\n    adding [with (m:=[c,d])] to the invocation of [apply]. *)\n\n  apply trans_eq with (m:=[c;d]). apply eq1. apply eq2.   Qed.\n\n(** Actually, we usually don't have to include the name [m] in\n    the [with] clause; Coq is often smart enough to figure out which\n    instantiation we're giving. We could instead write: [apply\n    trans_eq with [c;d]]. *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o).\nProof.\n  intros. apply trans_eq with (n:=n+p) (m:=m).\n  - apply H0.\n  - apply H.\nQed.\n\n\n(* ################################################################# *)\n(** * The [inversion] Tactic *)\n\n(** Recall the definition of natural numbers:\n\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n\n    It is obvious from this definition that every number has one of\n    two forms: either it is the constructor [O] or it is built by\n    applying the constructor [S] to another number.  But there is more\n    here than meets the eye: implicit in the definition (and in our\n    informal understanding of how datatype declarations work in other\n    programming languages) are two more facts:\n\n    - The constructor [S] is _injective_.  That is, if [S n = S m], it\n      must be the case that [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n]. *)\n\n(** Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor\n    is injective and [nil] is different from every non-empty list.\n    For booleans, [true] and [false] are different.  (Since neither\n    [true] nor [false] take any arguments, their injectivity is not an\n    issue.)  And so on. *)\n\n(** Coq provides a tactic called [inversion] that allows us to\n    exploit these principles in proofs. To see how to use it, let's\n    show explicitly that the [S] constructor is injective: *)\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n\n(** By writing [inversion H] at this point, we ask Coq to\n    generate all equations that it can infer from [H] as additional\n    hypotheses, replacing variables in the goal as it goes. In the\n    present example, this amounts to adding a new hypothesis [H1 : n =\n    m] and replacing [n] by [m] in the goal. *)\n\n  inversion H. reflexivity.  Qed.\n\n(** Here's a more interesting example that shows how multiple\n    equations can be derived at once. *)\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity. Qed.\n\n(** It is possible to name the equations that [inversion]\n    generates with an [as ...] clause: *)\n\nTheorem inversion_ex2 : forall (n m : nat),\n  [n] = [m] ->\n  n = m.\nProof.\n  intros n o H. inversion H as [Hno]. reflexivity.  Qed.\n\n(** **** Exercise: 1 star (inversion_ex3)  *)\nExample inversion_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  intros. inversion H. inversion H0. symmetry. apply H2.\nQed.\n\n(** [] *)\n\n(** While the injectivity of constructors allows us to reason\n    that [forall (n m : nat), S n = S m -> n = m], the converse of\n    this implication is an instance of a more general fact about\n    constructors and functions, which we will find useful below: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.\n\n(** When used on a hypothesis involving an equality between\n    _different_ constructors (e.g., [S n = O]), [inversion] solves the\n    goal immediately. To see why this makes sense, consider the\n    following proof: *)\n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  intros n.\n\n(** We can proceed by case analysis on [n]. The first case is\n    trivial. *)\n\n  destruct n as [| n'].\n  - (* n = 0 *)\n    intros H. reflexivity.\n\n(** However, the second one doesn't look so simple: assuming\n    [beq_nat 0 (S n') = true], we must show [S n' = 0], but the latter\n    clearly contradictory!  The way forward lies in the assumption.\n    After simplifying the goal state, we see that [beq_nat 0 (S n') =\n    true] has become [false = true]: *)\n\n  - (* n = S n' *)\n    simpl.\n\n(** If we use [inversion] on this hypothesis, Coq notices that\n    the subgoal we are working on is impossible, and therefore removes\n    it from further consideration. *)\n\n    intros H. inversion H. Qed.\n\n(** This is an instance of a general logical principle known as\n    the _principle of explosion_, which asserts that a contradiction\n    entails anything, even false things.  For instance: *)\n\nTheorem inversion_ex4 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem inversion_ex5 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. inversion contra. Qed.\n\n(** If you find the principle of explosion confusing, remember\n    that these proofs are not actually showing that the conclusion of\n    the statement holds.  Rather, they are arguing that the situation\n    described by the premise can never arise, so the implication is\n    vacuous.  We'll explore the principle of explosion of more detail\n    in the next chapter. *)\n\n(** **** Exercise: 1 star (inversion_ex6)  *)\nExample inversion_ex6 : forall (X : Type)\n                          (x y z : X) (l j : list X),\n  x :: y :: l = [] ->\n  y :: l = z :: j ->\n  x = z.\nProof.\n  intros. inversion H.\nQed.\n\n(** [] *)\n\n(** To summarize this discussion, suppose [H] is a hypothesis in the\n    context or a previously proven lemma of the form\n\n      c a1 a2 ... an = d b1 b2 ... bm\n\n    for some constructors [c] and [d] and arguments [a1 ... an] and\n    [b1 ... bm].  Then [inversion H] has the following effect:\n\n    - If [c] and [d] are the same constructor, then, by the\n      injectivity of this constructor, we know that [a1 = b1], [a2 =\n      b2], etc.; [inversion H] adds these facts to the context, and\n      tries to use them to rewrite the goal.\n\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory, and the current goal doesn't have to be\n      considered. In this case, [inversion H] marks the current goal\n      as completed and pops it off the goal stack. *)\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, [apply L in H] matches some conditional statement\n    [L] (of the form [L1 -> L2], say) against a hypothesis [H] in the\n    context.  However, unlike ordinary [apply] (which rewrites a goal\n    matching [L2] into a subgoal [L1]), [apply L in H] matches [H]\n    against [L1] and, if successful, replaces it with [L2].\n\n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\": from [L1 -> L2] and a hypothesis matching [L1], it\n    produces a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\": it says that if we know [L1->L2] and we are\n    trying to prove [L2], it suffices to prove [L1].\n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\nTheorem silly3' : forall (n : nat),\n  (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->\n  true = beq_nat n 5  ->\n  true = beq_nat (S (S n)) 7.\nProof.\n  intros n eq H.\n  symmetry in H. apply eq in H. symmetry in H.\n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, idiomatic use of Coq tends to favor backward reasoning,\n    but in some situations the forward style can be easier to think\n    about.  *)\n\n(** **** Exercise: 3 stars, recommended (plus_n_n_injective)  *)\n(** Practice using \"in\" variants in this exercise.  (Hint: use\n    [plus_n_Sm].) *)\n\nTheorem plus_n_n_injective : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  - intros. destruct m.\n    + reflexivity.\n    + inversion H.\n  - simpl. intros. destruct m.\n    + rewrite <- plus_n_O in H. inversion H.\n    + rewrite <- plus_n_Sm in H. simpl in H. rewrite <- plus_n_Sm in H.\n      inversion H. rewrite (IHn' _ H1). reflexivity.\nQed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Varying the Induction Hypothesis *)\n\n(** Sometimes it is important to control the exact form of the\n    induction hypothesis when carrying out inductive proofs in Coq.\n    In particular, we need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose\n    we want to show that the [double] function is injective -- i.e.,\n    that it always maps different arguments to different results:\n\n    Theorem double_injective: forall n m, \n      double n = double m -> n = m.\n\n    The way we _start_ this proof is a bit delicate: if we begin with\n\n      intros n. induction n.\n\n    all is well.  But if we begin it with\n\n      intros n m. induction n.\n\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  - (* n = O *) simpl. intros eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n  - (* n = S n' *) intros eq. destruct m as [| m'].\n    + (* m = O *) inversion eq.\n    + (* m = S m' *)  apply f_equal.\n\n(** At this point, the induction hypothesis, [IHn'], does not give us\n    [n' = m'] -- there is an extra [S] in the way -- so the goal is\n    not provable. *)\n\n      Abort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context --\n    intuitively, we have told Coq, \"Let's consider some particular [n]\n    and [m]...\" and we now have to prove that, if [double n = double\n    m] for _these particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove, for\n    _all_ [n], that the proposition\n\n      - [P n] = \"if [double n = double m], then [n = m]\"\n\n    holds, by showing\n\n      - [P O]\n\n         (i.e., \"if [double O = double m] then [O = m]\") and\n\n      - [P n -> P (S n)]\n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: it says that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help at all with proving\n    [R]!  (If we tried to prove [R] from [Q], we would start with\n    something like \"Suppose [double (S n) = 10]...\" but then we'd be\n    stuck: knowing that [double (S n)] is [10] tells us nothing about\n    whether [double n] is [10], so [Q] is useless.) *)\n\n(** 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    then trying to prove a relation involving _every_ [n] but just a\n    _single_ [m]. *)\n\n(** The good proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  - (* n = O *) simpl. intros m eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n\n  - (* n = S n' *) simpl.\n\n(** Notice that both the goal and the induction hypothesis are\n    different this time: the goal asks us to prove something more\n    general (i.e., to prove the statement for _every_ [m]), but the IH\n    is correspondingly more flexible, allowing us to choose any [m] we\n    like when we apply the IH. *)\n\n    intros m eq.\n\n(** Now we've chosen a particular [m] and introduced the assumption\n    that [double n = double m].  Since we are doing a case analysis on\n    [n], we also need a case analysis on [m] to keep the two \"in sync.\" *)\n\n    destruct m as [| m'].\n    + (* m = O *) simpl.\n\n(** The 0 case is trivial: *)\n\n      inversion eq.\n\n    + (* m = S m' *)\n      apply f_equal.\n\n(** At this point, since we are in the second branch of the [destruct\n    m], the [m'] mentioned in the context is the predecessor of the\n    [m] we started out talking about.  Since we are also in the [S]\n    branch of the induction, this is perfect: if we instantiate the\n    generic [m] in the IH with the current [m'] (this instantiation is\n    performed automatically by the [apply] in the next step), then\n    [IHn'] gives us exactly what we need to finish the proof. *)\n\n      apply IHn'. inversion eq. reflexivity. Qed.\n\n(** What you should take away from all this is that we need to be\n    careful about using induction to try to prove something too\n    specific: If we're proving a property of [n] and [m] by induction\n    on [n], we may need to leave [m] generic. *)\n\n(** The following exercise requires the same pattern. *)\n\n(** **** Exercise: 2 stars (beq_nat_true)  *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  induction n.\n  - intros. destruct m.\n    + reflexivity.\n    + inversion H.\n  - intros. destruct m.\n    + inversion H.\n    + simpl in H. rewrite (IHn m H). reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (beq_nat_true_informal)  *)\n(** Give a careful informal proof of [beq_nat_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** The strategy of doing fewer [intros] before an [induction] to\n    obtain a more general IH doesn't always work by itself; sometimes\n    a little _rearrangement_ of quantified variables is needed.\n    Suppose, for example, that we wanted to prove [double_injective]\n    by induction on [m] instead of [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  - (* m = O *) simpl. intros eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *)  apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem here 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 .  This\n    will work, but it's not nice: We don't want to have to twist the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them -- 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 quantified\n    variables and then _re-generalize_ one or more of them,\n    selectively taking variables out of the context and putting them\n    back at the beginning of the goal.  The [generalize dependent]\n    tactic does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m.\n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros n eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *) apply f_equal.\n      apply IHm'. inversion eq. reflexivity. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n    _Theorem_: For any nats [n] and [m], if [double n = double m], then\n      [n = m].\n\n    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n      any [n], if [double n = double m] then [n = m].\n\n      - First, suppose [m = 0], and suppose [n] is a number such\n        that [double n = double m].  We must show that [n = 0].\n\n        Since [m = 0], by the definition of [double] we have [double n =\n        0].  There are two cases to consider for [n].  If [n = 0] we are\n        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']\n        for some [n'], we derive a contradiction: by the definition of\n        [double], we can calculate [double n = S (S (double n'))], but\n        this contradicts the assumption that [double n = 0].\n\n      - Second, suppose [m = S m'] and that [n] is again a number such\n        that [double n = double m].  We must show that [n = S m'], with\n        the induction hypothesis that for every number [s], if [double s =\n        double m'] then [s = m'].\n\n        By the fact that [m = S m'] and the definition of [double], we\n        have [double n = S (S (double m'))].  There are two cases to\n        consider for [n].\n\n        If [n = 0], then by definition [double n = 0], a contradiction.\n\n        Thus, we may assume that [n = S n'] for some [n'], and again by\n        the definition of [double] we have [S (S (double n')) =\n        S (S (double m'))], which implies by inversion that [double n' =\n        double m'].  Instantiating the induction hypothesis with [n'] thus\n        allows us to conclude that [n' = m'], and it follows immediately\n        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just\n        what we wanted to show. [] *)\n\n(** Before we close this section and move on to some exercises, let's\n    digress briefly and use [beq_nat_true] to prove a similar property\n    about identifiers that we'll need in later chapters: *) \n\nTheorem beq_id_true : forall x y,\n  beq_id x y = true -> x = y.\nProof.\n  intros [m] [n]. simpl. intros H.\n  assert (H' : m = n). { apply beq_nat_true. apply H. }\n  rewrite H'. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, recommended (gen_dep_practice)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     nth_error l n = None.\nProof.\n  intros.\n  generalize dependent n.\n  induction l.\n  - simpl. intros. reflexivity.\n  - intros. simpl in H. destruct n.\n    + inversion H.\n    + inversion H. simpl. rewrite H1. apply IHl. apply H1.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (app_length_cons)  *)\n(** Prove this by induction on [l1], without using [app_length]\n    from [Lists]. *)\n\nTheorem app_length_cons : forall (X : Type) (l1 l2 : list X)\n                                  (x : X) (n : nat),\n     length (l1 ++ (x :: l2)) = n ->\n     S (length (l1 ++ l2)) = n.\nProof.\n  induction l1.\n  - simpl. intros. apply H.\n  - destruct n.\n    + simpl. intros. inversion H.\n    + simpl. intros. inversion H. rewrite (IHl1 _ _ _ H1). symmetry. apply H.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (app_length_twice)  *)\n(** Prove this by induction on [l], without using [app_length] from [Lists]. *)\n\nTheorem app_length_twice : forall (X:Type) (n:nat) (l:list X),\n     length l = n ->\n     length (l ++ l) = n + n.\nProof.\n  intros.\n  generalize dependent n.\n  induction l.\n  - simpl. intros. rewrite <- H. reflexivity.\n  - simpl. intros. destruct n.\n    + inversion H.\n    + inversion H. simpl. \n      rewrite <- plus_n_Sm. rewrite <- IHl by reflexivity.\n      apply f_equal with (f:=S). symmetry. apply app_length_cons with (x:=x).\n      reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (double_induction)  *)\n(** Prove the following principle of induction over two naturals. *)\n\nTheorem double_induction: forall (P : nat -> nat -> Prop),\n  P 0 0 ->\n  (forall m, P m 0 -> P (S m) 0) ->\n  (forall n, P 0 n -> P 0 (S n)) ->\n  (forall m n, P m n -> P (S m) (S n)) ->\n  forall m n, P m n.\nProof.\n  intros P H H1 H2 H3 m. induction m.\n  + induction n.\n    * apply H.\n    * apply H2. apply IHn.\n  + induction n.\n    * apply H1. apply IHm.\n      * apply H3. apply IHm.\nQed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Unfolding Definitions *)\n\n(** It sometimes happens that we need to manually unfold a Definition\n    so that we can manipulate its right-hand side.  For example, if we\n    define... *)\n\nDefinition square n := n * n.\n\n(** ... and try to prove a simple fact about [square]... *)\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\n  simpl.\n\n(** ... we get stuck: [simpl] doesn't simplify anything at this point,\n    and since we haven't proved any other facts about [square], there\n    is nothing we can [apply] or [rewrite] with.\n\n    To make progress, we can manually [unfold] the definition of\n    [square]: *)\n\n  unfold square.\n\n(** Now we have plenty to work with: both sides of the equality are\n    expressions involving multiplication, and we have lots of facts\n    about multiplication at our disposal.  In particular, we know that\n    it is commutative and associative, and from these facts it is not\n    hard to finish the proof. *)\n  \n  rewrite mult_assoc.\n  assert (H : n * m * n = n * n * m).\n  { rewrite mult_comm. apply mult_assoc. }\n  rewrite H. rewrite mult_assoc. reflexivity.\nQed.\n\n(** At this point, a deeper discussion of unfolding and simplification\n    is in order.\n\n    You may already have observed that tactics like [simpl],\n    [reflexivity], and [apply] will often unfold the definitions of\n    functions automatically when it 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 finish the proof is to explicitly\n    tell Coq to unfold [bar]. *)\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n\n(** Now it is apparent that we are stuck on the [match] expressions on\n    both sides of the [=], and we can use [destruct] to finish the\n    proof without thinking too hard. *)\n\n  destruct m.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where [destruct] is used to\n    perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (beq_nat n 3).\n    - (* beq_nat n 3 = true *) reflexivity.\n    - (* beq_nat n 3 = false *) destruct (beq_nat n 5).\n      + (* beq_nat n 5 = true *) reflexivity.\n      + (* beq_nat n 5 = false *) reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (beq_nat n 3) then ... else ...].  But either\n    [n] is equal to [3] or it isn't, so we can use [destruct (beq_nat\n    n 3)] to let us reason about the two cases.\n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c]. *)\n\n(** **** Exercise: 3 stars, optional (combine_split)  *)\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  intros X Y. induction l.\n  - intros. inversion H. reflexivity.\n  - simpl. destruct (split l). intros. destruct x.\n    inversion H. simpl. apply f_equal with (f:=cons (x,y)).\n    apply IHl. 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(** For example, suppose we define a function [sillyfun1] like\n    this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** Now suppose that we want to convince Coq of the (rather\n    obvious) fact that [sillyfun1 n] yields [true] only when [n] is\n    odd.  By analogy with the proofs we did with [sillyfun] above, it\n    is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAbort.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution performed by [destruct] is too brutal -- it threw\n    away every occurrence of [beq_nat n 3], but we need to keep some\n    memory of this expression and how it was destructed, because we\n    need to be able to reason that, since [beq_nat n 3 = true] in this\n    branch of the case analysis, it must be that [n = 3], from which\n    it follows that [n] is odd.\n\n    What we would really like is to substitute away all existing\n    occurences of [beq_nat n 3], but at the same time add an equation\n    to the context that records which case we are in.  The [eqn:]\n    qualifier allows us to introduce such an equation, giving it a\n    name that we choose. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got\n     stuck above, except that the context contains an extra\n     equality assumption, which is exactly what we need to\n     make progress. *)\n    - (* e3 = true *) apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    - (* e3 = false *)\n     (* When we come to the second equality test in the body\n        of the function we are reasoning about, we can use\n        [eqn:] again in the same way, allow us to finish the\n        proof. *)\n      destruct (beq_nat n 5) eqn:Heqe5.\n        + (* e5 = true *)\n          apply beq_nat_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + (* e5 = false *) inversion eq.  Qed.\n\n(** **** Exercise: 2 stars (destruct_eqn_practice)  *)\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  intros. destruct (f b) eqn:H1.\n  - destruct (f true) eqn:H2.\n    + destruct (f true) eqn:H3.\n      * reflexivity.\n      * inversion H2.\n    + destruct (f false) eqn:H3.\n      * reflexivity.\n      * destruct b. rewrite H1 in H2. inversion H2. rewrite H1 in H3. inversion H3.\n  - destruct (f false) eqn:H2.\n    + destruct b.\n      * rewrite H1. reflexivity.\n      * rewrite H1 in H2. inversion H2.\n    + apply H2.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Review *)\n\n(** We've now seen many of Coq's most fundamental tactics.  We'll\n    introduce a few more in the coming chapters, and later on we'll\n    see some more powerful _automation_ tactics that make Coq help us\n    with low-level details.  But basically we've got what we need to\n    get work done.\n\n    Here are the ones we've seen:\n\n      - [intros]: move hypotheses/variables from goal to context\n\n      - [reflexivity]: finish the proof (when the goal looks like [e =\n        e])\n\n      - [apply]: prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: apply a hypothesis, lemma, or constructor to\n        a hypothesis in the context (forward reasoning)\n\n      - [apply... with...]: explicitly specify values for variables\n        that cannot be determined by pattern matching\n\n      - [simpl]: simplify computations in the goal\n\n      - [simpl in H]: ... or a hypothesis\n\n      - [rewrite]: use an equality hypothesis (or lemma) to rewrite\n        the goal\n\n      - [rewrite ... in H]: ... or a hypothesis\n\n      - [symmetry]: changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]: changes a hypothesis of the form [t=u] into\n        [u=t]\n\n      - [unfold]: replace a defined constant by its right-hand side in\n        the goal\n\n      - [unfold... in H]: ... or a hypothesis\n\n      - [destruct... as...]: case analysis on values of inductively\n        defined types\n\n      - [destruct... eqn:...]: specify the name of an equation to be\n        added to the context, recording the result of the case\n        analysis\n\n      - [induction... as...]: induction on values of inductively\n        defined types\n\n      - [inversion]: reason by injectivity and distinctness of\n        constructors\n\n      - [assert (e) as H]: introduce a \"local lemma\" [e] and call it\n        [H]\n\n      - [generalize dependent x]: move the variable [x] (and anything\n        else that depends on it) from the context back to an explicit\n        hypothesis in the goal formula *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (beq_nat_sym)  *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  induction n.\n  - intros. destruct m.\n    + reflexivity.\n    + reflexivity.\n  - intros. destruct m.\n    + intros. reflexivity.\n    + simpl. apply IHn.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Proof:\n   (* FILL IN HERE *)\n[]\n*)\n\nLemma beq_same : forall n, beq_nat n n = true.\nProof.\n  induction n.\n  - reflexivity.\n  - simpl. apply IHn.\nQed.\n\n(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof.\n  intros. induction n.\n  - simpl. rewrite (beq_nat_0_l _ H) in H0. rewrite (beq_nat_0_l _ H0). reflexivity.\n  - simpl. rewrite (beq_nat_true _ _ H0) in H. rewrite <- (beq_nat_true _ _ H).\n    apply beq_same.\nQed.\n\n(** [] *)\n\n\n(** **** Exercise: 3 stars, advanced (split_combine)  *)\n(** We proved, in an exercise above, that for all lists of pairs,\n    [combine] is the inverse of [split].  How would you formalize the\n    statement that [split] is the inverse of [combine]?  When is this\n    property true?\n\n    When the lengths of l1 and l2 are the same.\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\nTheorem split_combine : \n  forall (X Y : Type) (l1 : list X) (l2 : list Y),\n  length l1 = length l2 -> split (combine l1 l2) = (l1,l2).\nProof.\n  induction l1.\n  - simpl. intros. destruct l2.\n    + reflexivity.\n    + simpl in H. inversion H.\n  - simpl. intros. destruct l2.\n    + simpl in H. inversion H.\n    + simpl in H. inversion H. simpl. rewrite (IHl1 _ H1). reflexivity.\nQed.\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise)  *)\n(** This one is a bit challenging.  Pay attention to the form of your\n    induction hypothesis. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  induction l.\n  - simpl. intros. inversion H.\n  - simpl. intros. destruct (test x0) eqn:H1.\n    + inversion H. rewrite H2 in H1. apply H1.\n    + apply (IHl _ H).\nQed.\n\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge)  *)\n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n\n      forallb evenb [0;2;4;5] = false\n\n      forallb (beq_nat 5) [] = true\n\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n\n      existsb (beq_nat 5) [0;2;3;6] = false\n\n      existsb (andb true) [true;true;false] = true\n\n      existsb oddb [1;0;0;0;0;3] = true\n\n      existsb evenb [] = false\n\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n\n    Finally, prove a theorem [existsb_existsb'] stating that\n    [existsb'] and [existsb] have the same behavior. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => true\n  | x :: xs => if test x then forallb test xs else false\n  end.\n\nFixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => false\n  | x :: xs => if test x then true else existsb test xs\n  end.\n\nDefinition existsb' {X : Type} (test : X -> bool) (l : list X) : bool :=\n  negb (forallb (fun y => negb (test y)) l).\n\nTheorem existsb_existsb' : forall (X : Type) (test : X -> bool) (l : list X),\n    existsb test l = existsb' test l.\nProof.\n  intros. induction l.\n  - reflexivity.\n  - unfold existsb'. simpl. destruct (test x).\n    + reflexivity.\n    + simpl. rewrite IHl. reflexivity.\nQed.\n\n\n\n\n(** $Date: 2016-07-14 17:02:35 -0400 (Thu, 14 Jul 2016) $ *)\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_03/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.8705972751232809, "lm_q1q2_score": 0.6622203855415923}}
{"text": "Require Import Coq.Reals.Reals.\nRequire Export Coq.Lists.List.\n\nRequire Export Autosubst.Autosubst.\n\nRequire Import utils.\nRequire Export entropy.\n\n\nLocal Open Scope ennr.\n\n(** * Types *)\n\n(** Types for our language are traditional real numbers (positive and negative,\n    no infinity) and arrows. *)\nInductive Ty :=\n| ℝ : Ty\n| Arrow : Ty -> Ty -> Ty\n.\nNotation \"x ~> y\" := (Arrow x y) (at level 69, right associativity).\n\nLemma ty_eq_dec : forall (τ τ' : Ty), {τ = τ'} + {τ <> τ'}.\nProof.\n  decide equality.\nDefined.\n\n(** Environments are De Bruijn indexed lists. While doing lookup in a list is\n    slightly annoying and slightly mismatched with autosubst, the finiteness\n    allows for things to be unique and decidable. *)\nDefinition Env (T : Type) := list T.\nDefinition empty_env {T : Type} : Env T := nil.\nNotation \"·\" := empty_env.\n\nFixpoint lookup {T} (ρ : Env T) x : option T :=\n  match ρ with\n  | nil => None\n  | v :: ρ' =>\n    match x with\n    | O => Some v\n    | S x' => lookup ρ' x'\n    end\n  end.\n\n(** * Expressions\n\n    While Autosubst (https://www.ps.uni-saarland.de/autosubst/) brings light and\n    joy into the miserable world of doing substitutions, it has some issues that\n    affect our representation of terms.\n\n    We define expressions using a GADT so that all terms are well typed.\n    However, autosubst is unable to either derive instances (not that much of a\n    problem) or reason about substitutions (big problem) of these terms.\n\n    We work around this by also defining a mostly type-erased version of the\n    terms for autosubst to work with. The type erasure is done carefully (i.e.\n    we keep the annotations on ambiguous terms (i.e. lambda)) so that the\n    erasure is injective. This means that whenever autosubst can demonstrate an\n    equality between to erased terms we can leverage the injectivity to get an\n    equality between fully typed terms.\n\n    ---- *)\n\n(** First, the well-typed terms: *)\nInductive expr (Γ : Env Ty) : Ty -> Type :=\n| e_real (r : R) : expr Γ ℝ\n| e_var {τ : Ty} (x : var)\n        (H : lookup Γ x = Some τ)\n  : expr Γ τ\n| e_lam {τa τr}\n        (body : expr (τa :: Γ) τr)\n  : expr Γ (τa ~> τr)\n| e_app {τa τr}\n        (ef : expr Γ (τa ~> τr))\n        (ea : expr Γ τa)\n  : expr Γ τr\n| e_factor (e : expr Γ ℝ)\n  : expr Γ ℝ\n| e_sample\n  : expr Γ ℝ\n| e_plus (el : expr Γ ℝ)\n         (er : expr Γ ℝ)\n  : expr Γ ℝ.\n\nArguments e_real {Γ} r.\nArguments e_var {Γ τ} x H.\nArguments e_lam {Γ τa τr} body.\nArguments e_app {Γ τa τr} ef ea.\nArguments e_factor {Γ} e.\nArguments e_sample {Γ}.\nArguments e_plus {Γ} el er.\n\n(** Now, the erased terms: (u stands for untyped) *)\nInductive u_expr :=\n| u_app : u_expr -> u_expr -> u_expr\n| u_factor : u_expr -> u_expr\n| u_sample : u_expr\n| u_plus : u_expr -> u_expr -> u_expr\n| u_real : R -> u_expr\n| u_lam : Ty -> {bind u_expr} -> u_expr\n| u_var : var -> u_expr\n.\n\nInstance Ids_u_expr : Ids u_expr. derive. Defined.\nInstance Rename_u_expr : Rename u_expr. derive. Defined.\nInstance Subst_u_expr : Subst u_expr. derive. Defined.\nInstance SubstLemmas_u_expr : SubstLemmas u_expr. derive. Defined.\n\nFixpoint erase {Γ τ} (e : expr Γ τ) : u_expr :=\n  match e with\n  | e_real r => u_real r\n  | e_var x _ => u_var x\n  | @e_lam _ τa τr body => u_lam τa (erase body)\n  | e_app ef ea => u_app (erase ef) (erase ea)\n  | e_factor e => u_factor (erase e)\n  | e_sample => u_sample\n  | e_plus el er => u_plus (erase el) (erase er)\n  end.\nCoercion erase' {Γ τ} : expr Γ τ -> u_expr := erase.\nArguments erase' / {_ _} _.\n\n(** The first step towards proving injectivity of [erase] is uniqueness of\n    typing for an erased term. *)\nLemma expr_type_unique {Γ τ0 τ1} (e0 : expr Γ τ0) (e1 : expr Γ τ1) :\n  erase e0 = erase e1 ->\n  τ0 = τ1.\nProof.\n  intros Heq.\n  revert τ1 e1 Heq.\n  dependent induction e0; intros;\n    dep_destruct (e1, Heq);\n    auto.\n  {\n    rewrite H0 in H.\n    inject H.\n    reflexivity.\n  } {\n    rewrite (IHe0 _ _ x).\n    reflexivity.\n  } {\n    specialize (IHe0_1 _ _ x).\n    inject IHe0_1.\n    reflexivity.\n  }\nQed.\n\nRequire Import FinFun.\nLemma erase_injective Γ τ : Injective (@erase Γ τ).\nProof.\n  intro x.\n  dependent induction x;\n    intros y Hxy;\n    dep_destruct (y, Hxy);\n    auto.\n  {\n    f_equal.\n    apply UIP_dec.\n    decide equality.\n    apply ty_eq_dec.\n  } {\n    f_equal.\n    apply IHx; auto.\n  } {\n    pose proof expr_type_unique _ _ x.\n    inject H.\n    erewrite IHx1, IHx2; auto.\n  } {\n    erewrite IHx; auto.\n  } {\n    erewrite IHx1, IHx2; auto.\n  }\nQed.\nArguments erase_injective {_ _ _ _} _.\n\n\n(** * Values\n\n    While it would be nice to define values and exprs as mutually inductive\n    types, autosubst can't handle mutual induction at the moment. Instead,\n    values are defined as a subset type of expressions. For convenience, a\n    coercion to expressions is defined. *)\n\nDefinition is_val (e : u_expr) : Prop :=\n  match e with\n  | u_real _ | u_lam _ _ => True\n  | _ => False\n  end.\n\nInductive val τ :=\n  mk_val (e : expr · τ) (H : is_val e).\nArguments mk_val {τ} e H.\nCoercion expr_of_val {τ} : val τ -> expr · τ :=\n  fun v => let (e, _) := v in e.\n\n(** proof irrelevance for [is_val], which also nicely means that coercion from a\n    value to an expression is reversible. *)\nLemma is_val_unique {e : u_expr} (iv0 iv1 : is_val e) :\n  iv0 = iv1.\nProof.\n  destruct e; try contradiction; destruct iv0, iv1; auto.\nQed.\n\nLemma val_eq {τ} {v0 v1 : val τ} :\n  v0 = v1 :> (expr · τ) ->\n  v0 = v1 :> (val τ).\nProof.\n  intros.\n  destruct v0, v1.\n  cbn in *.\n  subst.\n\n  f_equal.\n  apply is_val_unique.\nQed.\n\n(** the constructors for values I wish I had *)\nDefinition v_real r : val ℝ :=\n  mk_val (e_real r) I.\n\nDefinition v_lam {τa τr} body : val (τa ~> τr) :=\n  mk_val (e_lam body) I.\n\n(** If a rewrite or other tactic is expecting a value, but sees an expression it\n    will refuse to work. These two lemmas can be used to help the process along.\n    *)\nDefinition rewrite_v_real r : e_real r = v_real r := eq_refl.\nDefinition rewrite_v_lam {τa τr} body : e_lam body = @v_lam τa τr body := eq_refl.\n\n(** specialize destruction principles for values *)\nDefinition val_arrow_rect {τa τr}\n           (P : val (τa ~> τr) -> Type)\n           (case_lam : forall body, P (v_lam body)) :\n  forall v, P v.\nProof.\n  intros [v Hv].\n  dependent destruction v; try contradiction Hv.\n  destruct Hv.\n  apply case_lam.\nQed.\n\nLemma val_real_rect\n      (P : val ℝ -> Type)\n      (case_real : forall r, P (v_real r)) :\n  forall v, P v.\nProof.\n  intros.\n  destruct v as [v Hv].\n  dependent destruction v; try contradiction Hv.\n  destruct Hv.\n  apply case_real.\nQed.\n\nLemma wt_val_rect {τ}\n      (P : val τ -> Type)\n      (case_real :\n         forall r (τeq : ℝ = τ),\n           P (rew τeq in v_real r))\n      (case_lam :\n         forall τa τr\n                (τeq : (τa ~> τr) = τ)\n                body,\n           P (rew τeq in v_lam body)) :\n  forall v, P v.\nProof.\n  intros.\n  destruct τ. {\n    apply val_real_rect.\n    intros.\n    exact (case_real r eq_refl).\n  } {\n    apply val_arrow_rect.\n    intros.\n    exact (case_lam _ _ eq_refl body).\n  }\nQed.\n\nLtac destruct_val wt_v :=\n  match (type of wt_v) with\n  | val ℝ =>\n    destruct wt_v using val_real_rect\n  | val (?τa ~> ?τr) =>\n    destruct wt_v using val_arrow_rect\n  | val ?τ =>\n    destruct wt_v using wt_val_rect\n  end.\n\n(** Quite often we will with a goal containing a [mk_val e False] hidden\n    somewhere inside it. The tactic [absurd_val] hunts for that [False] in\n    common places and contradicts it. *)\n\nLemma for_absurd_val {τ} {v : val τ} {e : expr · τ} :\n  (expr_of_val v) = e ->\n  is_val e.\nProof.\n  intros.\n  destruct v.\n  subst.\n  auto.\nQed.\n\nLtac absurd_val :=\n  match goal with\n  | [ H : (expr_of_val _) = _ |- _ ] =>\n    contradiction (for_absurd_val H)\n  | [ H : _ = (expr_of_val _) |- _ ] =>\n    contradiction (for_absurd_val (eq_sym H))\n  end.\n\n(** *** Tactics\n\n    Some tactics useful for making use of equalities between erased expressions.\n    *)\n\nLtac inject_erase_directly :=\n  match goal with\n  | [ H : erase ?x = erase ?y |- _ ] =>\n    match type of x with\n    | (expr _ ?τx) =>\n      match type of y with\n      | (expr _ τx) =>\n        apply erase_injective in H;\n          try subst x\n      | (expr _ ?τy) =>\n        let H' := fresh \"H\" in\n        pose proof (expr_type_unique _ _ H) as H';\n          (subst τx || dep_destruct H');\n          apply erase_injective in H;\n          try subst x\n      end\n    end\n  end.\n\nLtac match_erase_eqs :=\n  let H := fresh \"H\" in\n  let H' := fresh \"H\" in\n  match goal with\n  | [H0 : erase ?x = ?s, H1 : erase ?y = ?s |- _ ] =>\n    pose proof (eq_trans H0 (eq_sym H1)) as H;\n    let z := type of y in\n    let kill_τ τ :=\n        pose proof (expr_type_unique _ _ H) as H';\n        (subst τ || dep_destruct H') in\n    match type of x with\n    | z => idtac\n    | val ?τ => kill_τ τ\n    | expr · ?τ => kill_τ τ\n    end;\n    apply erase_injective in H;\n    subst x\n  end;\n  clear_dups.\n\nLtac subst_erase_eq :=\n  match goal with\n  | [ H : erase ?e = _, H' : context [ erase ?e ] |- _ ] =>\n    rewrite H in H';\n      try clear H e\n  end.\n\n(** dep_destruct is often slow, do don't use unless we need *)\n(* TODO: speed up even more for exprs *)\nLtac expr_destruct e :=\n  match type of e with\n  | expr _ (_ ~> _) => dep_destruct e\n  | expr _ ℝ => dep_destruct e\n  | expr _ _ => destruct e\n  end.\n\nLtac inject_erased :=\n  let go e H :=\n      expr_destruct e; inject H\n  in match goal with\n     | [ H : erase ?e = u_app _ _ |- _ ] => go e H\n     | [ H : erase ?e = u_factor _ |- _ ] => go e H\n     | [ H : erase ?e = u_sample |- _ ] => go e H\n     | [ H : erase ?e = u_plus _ _ |- _ ] => go e H\n     | [ H : erase ?e = u_real _ |- _ ] => go e H\n     | [ H : erase ?e = u_lam _ _ |- _ ] => go e H\n     | [ H : erase ?e = u_var _ |- _ ] => go e H\n     | [ H : erase ?e = ids _ |- _ ] => go e H\n     end.\n\n(** [elim_erase_eqs]'s main objective is to eliminate hypothesis of the form\n    [erase e = ...] *)\nLtac elim_erase_eqs :=\n  progress repeat (subst_erase_eq\n                   || inject_erase_directly\n                   || match_erase_eqs\n                   || inject_erased);\n  clear_dups.\n\n\n(** ** Using [sig] to program by tactics *)\n\n(** As types get more dependent and pattern matching in Gallina becomes more\n    challenging, we will make use of an idiom to define functions. If we want to\n    define a function of type [A -> B], instead of defining it directly, we will\n    opaquely define a function of the form [A -> {b : B | P b}] using tactics.\n\n    The idea is to put all the information needed about the internals into [P]\n    so that you can eliminate calls to the function (wich now look like\n    [proj1_sig (f x)]) using [destruct (f x)] and rewriting insead\n    of standard computation.\n\n    The tactic [elim_sig_exprs] attempts to do exactly that destruction on\n    results of type [expr]. *)\n\nLtac elim_sig_exprs :=\n  let doit Γ τ pair stac :=\n      (let e := fresh \"e\" in\n       let He := fresh \"H\" e in\n       destruct pair as [e He];\n       stac;\n       asimpl in He) in\n  progress repeat\n           match goal with\n           | [ H : context [ @proj1_sig (expr ?Γ ?τ) _ ?pair ] |- _ ] =>\n             doit Γ τ pair ltac:(simpl in H)\n           | [ |- context [ @proj1_sig (expr ?Γ ?τ) _ ?pair ] ] =>\n             doit Γ τ pair ltac:(simpl)\n           end.\n\n\n(** * Substitution\n\n    Thanks to autosubst, substitution has been easily defined on erased terms.\n    The goal now is to define substitution on well-typed terms. The process of\n    defining it will be what is often called \"proving a substitution lemma\".\n\n    {TODO: is that the right wording?} *)\n\n(** First, we are going to need environments of well-typed terms. These will\n    essentially be dependent lists. *)\nInductive dep_list {A} (v : A -> Type) : Env A -> Type :=\n| dep_nil : dep_list v ·\n| dep_cons {τ Γ'} : v τ -> dep_list v Γ' -> dep_list v (τ :: Γ')\n.\nArguments dep_nil {_ _}.\nArguments dep_cons {_ _ _ _} _ _.\n\nFixpoint dep_lookup {A} {v : A -> Type} {Γ} (ρ : dep_list v Γ) (x : nat)\n  : option {τ : A & v τ} :=\n  match ρ with\n  | dep_nil => None\n  | dep_cons e ρ' =>\n    match x with\n    | O => Some (existT _ _ e)\n    | S x' => dep_lookup ρ' x'\n    end\n  end.\n\nFixpoint dep_map {A} {v0 v1 : A -> Type} {Γ}\n         (f : forall a, v0 a -> v1 a)\n         (ρ : dep_list v0 Γ)\n  : dep_list v1 Γ :=\n  match ρ with\n  | dep_nil => dep_nil\n  | dep_cons e ρ' => dep_cons (f _ e) (dep_map f ρ')\n  end.\n\nFixpoint dep_env_allT {A} {v : A -> Type} {Γ}\n         (P : forall a, v a -> Type)\n         (ρ : dep_list v Γ) : Type\n  :=\n    match ρ with\n    | dep_nil => True\n    | dep_cons e ρ' => P _ e * dep_env_allT P ρ'\n    end.\n\n(** Although in the end we only care about environments of closed values, for\n    the intermediate stages of substitution we will need to work with\n    environments of open terms as well.\n\n    We will lift the erase function over environments, but we will do it as a\n    separate function for open expressions vs values. The reason for this is to\n    keep the casts between [val] and [expr ·] at cases better suited for\n    computation. *)\nFixpoint erase_wt_expr_env {Γ Δ} (ρ : dep_list (expr Δ) Γ)\n  : nat -> u_expr :=\n  match ρ with\n  | dep_nil => ids\n  | dep_cons e ρ' => erase e .: erase_wt_expr_env ρ'\n  end.\n\nDefinition wt_env := dep_list val.\n\nFixpoint erase_wt_env {Γ} (ρ : wt_env Γ) : nat -> u_expr :=\n  match ρ with\n  | dep_nil => ids\n  | dep_cons e ρ' => erase e .: erase_wt_env ρ'\n  end.\n\nLemma erase_envs_equiv {Γ} (ρ : wt_env Γ) :\n  erase_wt_expr_env (dep_map (@expr_of_val) ρ) =\n  erase_wt_env ρ.\nProof.\n  induction ρ; auto.\n  cbn.\n  f_equal.\n  auto.\nQed.\n\n(** A downside to the list representation of environments is that doing lookup\n    from a dependent list is awkward. *)\nLemma env_search {A Γ} {v : A -> Type} (ρ : dep_list v Γ) {x τ} :\n  lookup Γ x = Some τ ->\n  {e : v τ | dep_lookup ρ x = Some (existT v τ e)}.\nProof.\n  intros.\n  revert Γ ρ H.\n  induction x; intros. {\n    destruct Γ; inject H.\n    dep_destruct ρ.\n    eexists.\n    reflexivity.\n  } {\n    destruct Γ; [discriminate |].\n    dep_destruct ρ.\n    simpl in *.\n    exact (IHx _ _ H).\n  }\nQed.\n\nLemma env_search_subst {Γ} (ρ : wt_env Γ) {x τ} :\n  lookup Γ x = Some τ ->\n  {v : val τ | erase v = erase_wt_env ρ x}.\nProof.\n  intros.\n  revert Γ ρ H.\n  induction x; intros. {\n    destruct Γ; inject H.\n    dep_destruct ρ.\n    eexists.\n    reflexivity.\n  } {\n    destruct Γ; [discriminate |].\n    dep_destruct ρ.\n    simpl in *.\n    exact (IHx _ _ H).\n  }\nQed.\n\nLemma weaken_lookup {A} {Γ : Env A} {x τ Γw} :\n  lookup Γ x = Some τ ->\n  lookup (Γ ++ Γw) x = Some τ.\nProof.\n  intros.\n  revert Γ H.\n  induction x; intros. {\n    destruct Γ; inversion H.\n    auto.\n  } {\n    destruct Γ; try discriminate H.\n    simpl in *.\n    apply IHx.\n    auto.\n  }\nQed.\n\nFixpoint weaken {Γ τ} (e : expr Γ τ) Γw : expr (Γ ++ Γw) τ :=\n  match e with\n  | e_real r => e_real r\n  | e_var x H => e_var x (weaken_lookup H)\n  | e_lam body => e_lam (weaken body Γw)\n  | e_app ef ea => e_app (weaken ef Γw) (weaken ea Γw)\n  | e_factor e => e_factor (weaken e Γw)\n  | e_sample => e_sample\n  | e_plus el er => e_plus (weaken el Γw) (weaken er Γw)\n  end.\n\n(** The definition of typed substitution borrows from\n    https://www.ps.uni-saarland.de/autosubst/doc/Plain.Demo.html *)\n\n(** A combination of weakening and renaming preserves types *)\nLemma expr_ren {Γ τ} ξ (e : expr Γ τ) Δ :\n  lookup Γ = ξ >>> lookup Δ ->\n  {e' : expr Δ τ |\n   erase e' = rename ξ (erase e)}.\nProof.\n  revert ξ Δ.\n  induction e; intros. {\n    exists (e_real r).\n    simpl.\n    auto.\n  } {\n    simple refine (exist _ (e_var (ξ x) _) _); simpl; auto.\n    rewrite <- H.\n    rewrite H0.\n    auto.\n  } {\n    assert (lookup (τa :: Γ) = upren ξ >>> lookup (τa :: Δ)). {\n      extensionality x.\n      destruct x; auto.\n      simpl.\n      rewrite H.\n      auto.\n    }\n    destruct (IHe _ _ H0).\n    exists (e_lam x).\n    simpl.\n    rewrite e0.\n    auto.\n  } {\n    edestruct IHe1, IHe2; eauto.\n    eexists (e_app _ _).\n    simpl.\n    rewrite e, e0.\n    auto.\n  } {\n    edestruct IHe; eauto.\n    eexists (e_factor _).\n    simpl.\n    rewrite e0.\n    auto.\n  } {\n    exists e_sample; auto.\n  } {\n    edestruct IHe1, IHe2; eauto.\n    eexists (e_plus _ _).\n    simpl.\n    rewrite e, e0.\n    auto.\n  }\nQed.\n\n(** lift's autosubst's untyped [up] function to well-typed environments *)\nLemma up_expr_env {Γ Δ : Env Ty}\n      (σ : dep_list (expr Δ) Γ)\n      (τa : Ty)\n  : { σ' : dep_list (expr (τa :: Δ)) (τa :: Γ) |\n      forall x τ,\n        lookup (τa :: Γ) x = Some τ ->\n        erase_wt_expr_env σ' x = up (erase_wt_expr_env σ) x }.\nProof.\n  simple refine (exist _ _ _); auto. {\n    constructor. {\n      apply (e_var O).\n      auto.\n    } {\n      refine (dep_map _ σ).\n      intros a e.\n      apply (expr_ren S e).\n      auto.\n    }\n  } {\n    simpl.\n    intros.\n    revert Γ Δ σ H.\n    destruct x; auto.\n    induction x; intros. {\n      simpl.\n      destruct σ; inversion H; subst.\n      simpl.\n      destruct expr_ren.\n      rewrite e0.\n      auto.\n    } {\n      destruct σ; try discriminate H; simpl in *.\n      rewrite IHx; auto.\n    }\n  }\nQed.\n\n(** Autosubst works with infinite substitution environments, but we never want\n    to (and never have to) deal with the parts of the substitution that lie\n    outside Γ. *)\nLemma subst_only_matters_up_to_env {Γ τ} (e : expr Γ τ) σ0 σ1 :\n  (forall x τ,\n      lookup Γ x = Some τ ->\n      σ0 x = σ1 x) ->\n  (erase e).[σ0] = (erase e).[σ1].\nProof.\n  revert σ0 σ1.\n  induction e; simpl; intros; f_equal; eauto.\n\n  apply IHe.\n  intros.\n  destruct x; auto.\n  simpl in H0.\n  specialize (H _ _ H0).\n  unfold up.\n  simpl.\n  rewrite H.\n  auto.\nQed.\n\n(** Finally we are armed with enough lemmas to define type-preserving\n    substitution. *)\nLemma ty_subst {Γ τ} (e : expr Γ τ) :\n  forall Δ (ρ : dep_list (expr Δ) Γ),\n    {e' : expr Δ τ |\n     erase e' = (erase e).[erase_wt_expr_env ρ]}.\nProof.\n  induction e; intros. {\n    exists (e_real r).\n    reflexivity.\n  } {\n    simpl.\n    destruct (env_search ρ H).\n    exists x0.\n    revert Γ H ρ e.\n    induction x; intros. {\n      destruct ρ; inversion e; subst.\n      auto.\n    } {\n      destruct ρ; inversion e; subst.\n      simpl.\n      apply IHx; auto.\n    }\n  } {\n    destruct (up_expr_env ρ τa).\n    destruct (IHe _ x).\n\n    eexists (e_lam _).\n    simpl.\n    f_equal.\n    rewrite e1.\n\n    apply subst_only_matters_up_to_env.\n    auto.\n  } {\n    edestruct IHe1, IHe2; auto.\n    eexists (e_app _ _).\n    simpl.\n    rewrite e, e0.\n    reflexivity.\n  } {\n    edestruct IHe; auto.\n    exists (e_factor x).\n    simpl.\n    rewrite e0.\n    reflexivity.\n  } {\n    exists e_sample.\n    reflexivity.\n  } {\n    edestruct IHe1, IHe2; auto.\n    exists (e_plus x x0).\n    simpl.\n    rewrite e, e0.\n    reflexivity.\n  }\nQed.\n\nLemma close {Γ} (ρ : wt_env Γ) {τ} (e : expr Γ τ) :\n  {e' : expr · τ |\n   erase e' = (erase e).[erase_wt_env ρ]}.\nProof.\n  rewrite <- erase_envs_equiv.\n  apply ty_subst.\nQed.\n\nLemma close_nil (ρ : wt_env ·) {τ} (e : expr · τ) :\n  proj1_sig (close ρ e) = e.\nProof.\n  dep_destruct ρ.\n  elim_sig_exprs.\n  elim_erase_eqs.\n  reflexivity.\nQed.\n\n(** Since most day-to-day substitution is done by β, it's nice to have a small\n    helper function to substitute exactly one value into a lambda body. *)\nDefinition ty_subst1 {τa τr}\n      (e : expr (τa :: ·) τr)\n      (v : val τa) :\n  { e' : expr · τr |\n    erase e' = (erase e).[erase v /] }\n  := ty_subst e · (dep_cons (v : expr · τa) dep_nil).\n\n(** * Evaluation *)\n\n(** Evaluation is defined as a big-step relation. While it would have been nicer\n    to instead define it as a partial function so that it's determinism is more\n    obvious, the complicated recursion done by application means that\n    determinism is instead done by logical relation in a more difficult manner.\n    (See [eval_dec] in determinism.v) *)\nReserved Notation \"'EVAL' σ ⊢ e ⇓ v , w\" (at level 69, e at level 99, no associativity).\nInductive eval (σ : Entropy) : forall {τ} (e : expr · τ) (v : val τ) (w : R+), Type :=\n| EVAL_val {τ} (v : val τ) :\n    (EVAL σ ⊢ v ⇓ v, 1)\n| EVAL_app {τa τr}\n       {ef : expr · (τa ~> τr)}\n       {ea : expr · τa}\n       {body : expr (τa :: ·) τr}\n       {va : val τa}\n       {vr : val τr}\n       {w0 w1 w2 : R+}\n  : (EVAL (π 0 σ) ⊢ ef ⇓ mk_val (e_lam body) I, w0) ->\n    (EVAL (π 1 σ) ⊢ ea ⇓ va, w1) ->\n    (EVAL (π 2 σ) ⊢ proj1_sig (ty_subst1 body va) ⇓ vr, w2) ->\n    (EVAL σ ⊢ e_app ef ea ⇓ vr, w0 * w1 * w2)\n| EVAL_factor {e : expr · ℝ} {r : R} {w : R+} {is_v} (rpos : (0 <= r)%R)\n  : (EVAL σ ⊢ e ⇓ mk_val (e_real r) is_v, w) ->\n    (EVAL σ ⊢ e_factor e ⇓ v_real r, finite r rpos * w)\n| EVAL_sample\n  : (EVAL σ ⊢ e_sample ⇓ v_real (proj1_sig (σ O)), 1)\n| EVAL_plus {e0 e1 : expr · ℝ} {r0 r1 : R} {is_v0 is_v1} {w0 w1 : R+}\n  : (EVAL (π 0 σ) ⊢ e0 ⇓ mk_val (e_real r0) is_v0, w0) ->\n    (EVAL (π 1 σ) ⊢ e1 ⇓ mk_val (e_real r1) is_v1, w1) ->\n    (EVAL σ ⊢ e_plus e0 e1 ⇓ v_real (r0 + r1), w0 * w1)\nwhere \"'EVAL' σ ⊢ e ⇓ v , w\" := (@eval σ _ e v w)\n.\n\n(** Misc lemmas *)\n\n(** [inversion] has a hard time recognizing that [EVAL_val] is the only\n    constructor that evaluates a value, so we use lemma instead. *)\nLemma invert_eval_val {σ τ} {v v' : val τ} {w} :\n  (EVAL σ ⊢ v ⇓ v', w) ->\n  v = v' /\\ w = 1.\nProof.\n  intros.\n  destruct τ;\n    destruct_val v;\n    destruct_val v';\n    dependent destruction H;\n    auto.\nQed.\n\n(** Equality of expressions is decidable. Currently unused, but a nice tool to\n    have for feeding to UIP_dec. *)\nLemma u_expr_eq_dec (u0 u1 : u_expr) :\n  {u0 = u1} + {u0 <> u1}.\nProof.\n  decide equality. {\n    apply Req_EM_T.\n  } {\n    decide equality.\n  } {\n    decide equality.\n  }\nQed.\n\n(** The GADTs in [expr] are too much for the [decide equality] tactic.\n    Fortunately, the hard work of converting it to a GADT-less version has\n    already been done in erase_injective. *)\nLemma expr_eq_dec {Γ τ} (e0 e1 : expr Γ τ) :\n  {e0 = e1} + {e0 <> e1}.\nProof.\n  destruct (u_expr_eq_dec (erase e0) (erase e1)). {\n    left.\n    exact (erase_injective e).\n  } {\n    right.\n    contradict n.\n    subst.\n    auto.\n  }\nQed.", "meta": {"author": "cobbal", "repo": "ppl-ctx-equiv-coq", "sha": "1b5ae5e58c65ae625068007f89353ad065394e15", "save_path": "github-repos/coq/cobbal-ppl-ctx-equiv-coq", "path": "github-repos/coq/cobbal-ppl-ctx-equiv-coq/ppl-ctx-equiv-coq-1b5ae5e58c65ae625068007f89353ad065394e15/src/syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6622203753261756}}
{"text": "\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nLemma lem2: forall l n, Cons n (rev l) = rev (append l (Cons n Nil)).\nProof.\nintros. induction l.\n  - simpl. rewrite <- IHl. reflexivity.\n  - reflexivity.\nQed.\n\nLemma lem: forall l, rev (rev l) = l.\nProof.\ninduction l.\n  - simpl. rewrite <- lem2. rewrite IHl. reflexivity.\n  - reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : lst) (y : lst), eq (rev (rev (append x y))) (append (rev (rev x)) (rev (rev y))).\nProof.\n  intros. rewrite lem. \n  rewrite lem.\n  rewrite lem. 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/goal17.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.6622203709864276}}
{"text": "From Coq Require Import ZArith Reals Psatz.\nFrom Flocq Require Import Binary.\n\nImport List ListNotations.\n\nSet Bullet Behavior \"Strict Subproofs\". \n\n\nFrom Iterative Require Import   lemmas.\n\n\nFrom mathcomp Require Import matrix bigop all_algebra all_ssreflect.\nFrom mathcomp.analysis Require Import Rstruct.\nFrom Coquelicot Require Import Lub Rbar.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** We will open the real scope and the Ring scope \n  separately **)\n\nOpen Scope ring_scope.\n\n(** We instantiate the ring scope with real scope using\n  Delimit Scope ... **)\nDelimit Scope ring_scope with Ri.\nDelimit Scope R_scope with Re.\n\n(** We next import the ring theory so that we can use\n  it for reals **)\nImport Order.TTheory GRing.Theory Num.Def Num.Theory.\n\n\n(** Infinity norm of a vector is the maximum of \n    absolute values of the entries of a vector \n**)\nDefinition vec_inf_norm {n:nat} (v : 'cV[R]_n) :=\n bigmaxr 0%Re [seq (Rabs (v i 0)) | i <- enum 'I_n].\n\n(** Infinity norm of a matrix is the maximum of the columm sums **)\nDefinition matrix_inf_norm {n:nat} (A: 'M[R]_n) :=\n  bigmaxr 0%Re [seq (row_sum A i) | i <- enum 'I_n].\n\nLemma vec_inf_norm_0_is_0 {n:nat}: \n  @vec_inf_norm n.+1 0 = 0%Re.\nProof.\nrewrite /vec_inf_norm. apply bigmaxrP.\nsplit.\n+ apply /mapP. exists (@ord0 n).\n  - by rewrite mem_enum.\n  - by rewrite mxE Rabs_R0.\n+ intros. rewrite nth_seq_0_is_0. apply /RleP. apply Rle_refl.\n  by rewrite size_map size_enum_ord in H. \nQed.\n\n\n\nLemma triang_ineq {n:nat} : forall a b: 'cV[R]_n.+1,\nvec_inf_norm(a + b) <= vec_inf_norm a + vec_inf_norm b.\nProof.\nintros.\nrewrite /vec_inf_norm. apply /RleP.\napply bigmax_le.\n+ by rewrite size_map size_enum_ord. \n+ intros. rewrite -RplusE. \n  apply Rle_trans with \n    ([seq Rabs (a i0 0) | i0 <- enum 'I_n.+1]`_i + \n     [seq Rabs (b i0 0) | i0 <- enum 'I_n.+1]`_i)%Re.\n  - assert ([seq Rabs ((a + b)%Ri i0 0) | i0 <- enum 'I_n.+1] = \n               mkseq (fun i =>  Rabs ((a + b)%Ri (@inord n i) 0)) n.+1).\n    { unfold mkseq. rewrite -val_enum_ord.\n      rewrite -[in RHS]map_comp.\n      apply eq_map. unfold eqfun. intros.\n      rewrite !mxE //=. rewrite !mxE. by rewrite inord_val.\n    } rewrite H0 nth_mkseq; last by rewrite size_map size_enum_ord in H.  \n    assert ([seq Rabs (a i0 0) | i0 <- enum 'I_n.+1] = \n               mkseq (fun i =>  Rabs (a (@inord n i) 0)) n.+1).\n    { unfold mkseq. rewrite -val_enum_ord.\n      rewrite -[in RHS]map_comp.\n      apply eq_map. unfold eqfun. intros. by rewrite //= inord_val //=.\n    } rewrite H1 nth_mkseq ; last by rewrite size_map size_enum_ord in H.\n    assert ([seq Rabs (b i0 0) | i0 <- enum 'I_n.+1] = \n               mkseq (fun i =>  Rabs (b (@inord n i) 0)) n.+1).\n    { unfold mkseq. rewrite -val_enum_ord.\n      rewrite -[in RHS]map_comp.\n      apply eq_map. unfold eqfun. intros. by rewrite //= inord_val //=.\n    } rewrite H2 nth_mkseq ; last by rewrite size_map size_enum_ord in H.\n    rewrite !mxE //=. rewrite -RplusE. apply Rabs_triang.\n  - apply Rplus_le_compat.\n    * apply /RleP. \n      apply (@bigmaxr_ler _ 0%Re [seq Rabs (a i0 0) | i0 <- enum 'I_n.+1] i).\n      rewrite size_map size_enum_ord.\n      by rewrite size_map size_enum_ord in H.\n    * apply /RleP. \n      apply (@bigmaxr_ler _ 0%Re [seq Rabs (b i0 0) | i0 <- enum 'I_n.+1] i).\n      rewrite size_map size_enum_ord.\n      by rewrite size_map size_enum_ord in H.\nQed.\n\n\n\nLemma submult_prop {n:nat} (A: 'M[R]_n.+1) (v : 'cV[R]_n.+1):\n  vec_inf_norm (A *m v) <=\n  matrix_inf_norm A * vec_inf_norm v.\nProof.\nrewrite /vec_inf_norm /matrix_inf_norm. rewrite mulrC.\nrewrite -bigmaxr_mulr.\n+ apply /RleP. apply bigmax_le.\n  - by rewrite size_map size_enum_ord.\n  - intros.\n    apply Rle_trans with\n    [seq (bigmaxr 0\n           [seq Rabs (v i1 0) | i1 <- enum 'I_n.+1] *\n         row_sum A i0)%Ri\n      | i0 <- enum 'I_n.+1]`_i.\n    * assert ([seq Rabs ((A *m v) i0 0) | i0 <- enum 'I_n.+1] = \n              mkseq (fun i => Rabs ((A *m v) (@inord n i) 0)) n.+1).\n      { unfold mkseq. rewrite -val_enum_ord.\n        rewrite -[in RHS]map_comp.\n        apply eq_map. unfold eqfun. intros.\n        rewrite !mxE //=. rewrite !mxE. by rewrite //= inord_val //=.\n      } rewrite H0 nth_mkseq ; last by rewrite size_map size_enum_ord in H.\n      assert ([seq bigmaxr 0\n                  [seq Rabs (v i1 0) | i1 <- enum 'I_n.+1] *  row_sum A i0\n                    | i0 <- enum 'I_n.+1] = \n               mkseq (fun i =>  bigmaxr 0  \n                        [seq Rabs (v i1 0) | i1 <- enum 'I_n.+1] *  row_sum A (@inord n i)) n.+1).\n      { unfold mkseq. rewrite -val_enum_ord.\n        rewrite -[in RHS]map_comp.\n        apply eq_map. unfold eqfun. intros.\n        by rewrite //= inord_val //=.\n      } rewrite H1 nth_mkseq ; last by rewrite size_map size_enum_ord in H.\n      rewrite -RmultE. rewrite !mxE.\n      apply Rle_trans with \n        (\\sum_j Rabs (A (inord i) j * v j 0)).\n      ++ apply /RleP. apply Rabs_ineq.\n      ++ assert (\\sum_j Rabs (A (inord i) j * v j 0) = \n                  \\sum_j (Rabs (A (inord i) j) * Rabs (v j 0))).\n         { apply eq_big. by []. intros. by rewrite Rabs_mult. }\n         rewrite H2. rewrite Rmult_comm. apply /RleP. rewrite RmultE. rewrite -bigmaxr_mulr.\n         apply /RleP. \n         rewrite bigmaxr_mulr. rewrite -RmultE. rewrite /row_sum.\n         rewrite big_distrl //=.\n         apply /RleP. apply big_sum_ge_ex_abstract. intros.\n         rewrite -!RmultE. apply Rmult_le_compat_l.\n         -- apply Rabs_pos.\n         -- apply Rle_trans with [seq Rabs (v i1 0) | i1 <- enum 'I_n.+1]`_i0.\n            ** assert ([seq Rabs (v i1 0) | i1 <- enum 'I_n.+1] = \n                       mkseq (fun i => Rabs (v (@inord n i) 0)) n.+1).\n               { unfold mkseq. rewrite -val_enum_ord.\n                 rewrite -[in RHS]map_comp.\n                 apply eq_map. unfold eqfun. intros.\n                 by rewrite //= inord_val //=.\n               } rewrite H4 nth_mkseq ; last by rewrite size_map size_enum_ord in H. \n               rewrite //= inord_val. nra.\n            ** apply /RleP. apply (@bigmaxr_ler _ 0%Re [seq Rabs (v i1 0) | i1 <- enum 'I_n.+1] i0).\n                rewrite size_map size_enum_ord.\n                by rewrite size_map size_enum_ord in H.\n         -- unfold row_sum. apply big_ge_0_ex_abstract. intros.\n            apply /RleP. apply Rabs_pos.\n         -- unfold row_sum. apply big_ge_0_ex_abstract. intros.\n            apply /RleP. apply Rabs_pos.\n    * apply /RleP. \n      apply (@bigmaxr_ler _ 0%Re [seq bigmaxr 0\n                [seq Rabs (v i1 0) | i1 <- enum 'I_n.+1] * row_sum A i0\n                  | i0 <- enum 'I_n.+1] i).\n      rewrite size_map size_enum_ord.\n      by rewrite size_map size_enum_ord in H.\n+ apply bigmax_le_0.\n  - by apply /RleP; apply Rle_refl.\n  - intros. \n    assert ([seq Rabs (v i0 0) | i0 <- enum 'I_n.+1]= \n              mkseq (fun i => Rabs (v (@inord n i) 0)) n.+1).\n    { unfold mkseq. rewrite -val_enum_ord.\n      rewrite -[in RHS]map_comp.\n      apply eq_map. unfold eqfun. intros.\n      by rewrite //= inord_val //=.\n    } rewrite H0 nth_mkseq ; last by rewrite size_map size_enum_ord in H.\n    unfold row_sum. apply /RleP. apply Rabs_pos.\nQed.\n\n\n\nLemma matrix_norm_pd {n:nat} (A : 'M[R]_n.+1):\n  0 <= matrix_inf_norm A.\nProof.\nrewrite /matrix_inf_norm.\napply bigmax_le_0.\n+ by apply /RleP; apply Rle_refl.\n+ intros. rewrite seq_equiv.\n  rewrite nth_mkseq; last by rewrite size_map size_enum_ord in H.\n  rewrite /row_sum. apply big_ge_0_ex_abstract.\n  intros. apply /RleP. apply Rabs_pos.\nQed.\n\n\n\n\nLemma vec_norm_pd {n:nat} (v : 'cV[R]_n.+1):\n  0 <= vec_inf_norm v.\nProof.\nrewrite /vec_inf_norm.\napply bigmax_le_0.\n+ by apply /RleP; apply Rle_refl.\n+ intros. rewrite seq_equiv.\n  rewrite nth_mkseq; last by rewrite size_map size_enum_ord in H.\n  apply /RleP. apply Rabs_pos.\nQed.\n\n\nLemma reverse_triang_ineq:\n  forall n a b c, \n  @vec_inf_norm n.+1 (a - b) <= c -> \n  @vec_inf_norm n.+1 (a) - @vec_inf_norm n.+1 (b) <= c.\nProof.\nintros. apply /RleP. rewrite -RminusE.\napply Rle_trans with (vec_inf_norm (a - b)).\n+ assert (forall x y z:R, (x  <= y + z)%Re -> (x  - y <= z)%Re).\n  { intros. nra. } apply H0.\n  apply Rle_trans with (vec_inf_norm (b + (a - b))).\n  - assert (a = b + (a - b)).\n    { apply matrixP. unfold eqrel. intros. rewrite !mxE. \n      rewrite -RplusE -RminusE.\n      assert ((b x y + (a x y - b x y))%Re = a x y).\n      { nra. } by rewrite H1.\n    } rewrite -H1. apply Rle_refl.\n  - apply /RleP. apply triang_ineq. \n+ by apply /RleP.\nQed.\n\n\nLemma vec_inf_norm_opp {n:nat}:\n  forall v: 'cV[R]_n,  \n  vec_inf_norm v = vec_inf_norm (-v).\nProof.\nintros. rewrite /vec_inf_norm. \nassert ([seq Rabs (v i 0) | i <- enum 'I_n] = \n        [seq Rabs ((- v)%Ri i 0) | i <- enum 'I_n]).\n{ apply eq_map. unfold eqfun. intros.\n  rewrite! mxE. rewrite -RoppE. by rewrite  Rabs_Ropp.\n} by rewrite H.\nQed.\n\n\n\n\nLemma cs_ineq_vec_inf_norm :\nforall len, forall a b c d: 'cV[R]_len,\n(0 < len)%N -> \nvec_inf_norm(a - b + c -d) <= vec_inf_norm(a - b) + vec_inf_norm(c -d).\nProof.\nintros.\n  assert ((a - b + c -d) = (a - b) + (c - d)).\n  { apply matrixP. unfold eqrel. intros. rewrite !mxE. \n    rewrite -!RplusE -!RoppE. nra.\n  } rewrite H0.\n  assert (len = len.-1.+1).\n  {  rewrite prednK; auto. }\n  move: a  b c d H0. rewrite H1. intros. by apply triang_ineq.\nQed.\n\n\nLemma matrix_norm_le {n:nat}:\n  forall (A B : 'M[R]_n.+1),\n  matrix_inf_norm (A *m B) <= matrix_inf_norm A * matrix_inf_norm B.\nProof.\nintros. rewrite /matrix_inf_norm.\napply /RleP. apply bigmax_le.\n+ by rewrite size_map size_enum_ord.\n+ intros. rewrite seq_equiv. rewrite nth_mkseq.\n  - rewrite /row_sum. \n    apply Rle_trans with \n    (\\sum_(j < n.+1) (\\sum_(k < n.+1) (Rabs (A (inord i) k) * Rabs (B k j))%Re)).\n    * apply /RleP. apply big_sum_ge_ex_abstract. intros.\n      rewrite !mxE.\n      apply Rle_trans with \n      (\\sum_j (Rabs ((A (inord i) j) * B j i0))).\n      ++ apply /RleP. apply Rabs_ineq.\n      ++ assert (\\sum_j Rabs (A (inord i) j * B j i0) = \n                  \\sum_(k < n.+1) (Rabs (A (inord i) k) * Rabs (B k i0))%Re).\n         { apply eq_big. by []. intros. by rewrite Rabs_mult. }\n         rewrite H1. nra.\n    * assert (\\sum_(j < n.+1)\n                \\sum_(k < n.+1)\n                   (Rabs (A (inord i) k) * Rabs (B k j))%Re = \n               \\sum_(k < n.+1)\n                  \\sum_(j < n.+1)\n                     (Rabs (A (inord i) k) * Rabs (B k j))%Re).\n      { apply exchange_big. } rewrite H0. \n      rewrite mulrC. rewrite -bigmaxr_mulr.\n      apply Rle_trans with \n      (nth 0 [seq (bigmaxr 0 [seq \\sum_(j < n.+1) Rabs (B i1 j)\n                      | i1 <- enum 'I_n.+1] *\n                    (\\sum_(j < n.+1) Rabs (A i0 j)))%Ri | i0 <- enum 'I_n.+1] i).\n      ++ rewrite seq_equiv. rewrite nth_mkseq. \n         -- rewrite big_distrr //=. apply /RleP.\n            apply big_sum_ge_ex_abstract. intros.\n            rewrite -RmultE. rewrite Rmult_comm.\n            rewrite -big_distrr //=. rewrite -RmultE.\n            apply Rmult_le_compat_l.\n            ** apply Rabs_pos.\n            ** apply /RleP. \n               assert (\\sum_(i1 < n.+1) Rabs (B i0 i1) = \n                        nth 0 [seq \\sum_(j < n.+1) Rabs (B i1 j)\n                               | i1 <- enum 'I_n.+1]  i0).\n                { rewrite seq_equiv. rewrite nth_mkseq. by rewrite inord_val. apply ltn_ord. }\n                rewrite H2. \n                apply (@bigmaxr_ler _ 0  [seq \\sum_(j < n.+1) Rabs (B i1 j)\n                                           | i1 <- enum 'I_n.+1] i0).\n                rewrite size_map size_enum_ord. apply ltn_ord.\n         -- by rewrite size_map size_enum_ord in H.\n      ++ apply /RleP. \n         apply (@bigmaxr_ler _ 0%Re [seq bigmaxr 0\n                       [seq \\sum_(j < n.+1) Rabs (B i1 j)\n                          | i1 <- enum 'I_n.+1] *\n                     (\\sum_(j < n.+1) Rabs (A i0 j))\n                   | i0 <- enum 'I_n.+1] i).\n         rewrite size_map size_enum_ord.\n         by rewrite size_map size_enum_ord in H.\n      ++ apply bigmax_le_0.\n         -- apply /RleP. apply Rle_refl.\n         -- intros. rewrite seq_equiv. rewrite nth_mkseq.\n            ** apply big_ge_0_ex_abstract. intros.\n               apply /RleP. apply Rabs_pos.\n            ** by rewrite size_map size_enum_ord in H1.\n  - by rewrite size_map size_enum_ord in H.\nQed.\n\n\nLemma matrix_norm_add {n:nat}:\n  forall (A B : 'M[R]_n.+1),\n  matrix_inf_norm (A + B) <= matrix_inf_norm A + matrix_inf_norm B.\nProof.\nintros. rewrite /matrix_inf_norm.\napply /RleP. apply bigmax_le.\n+ by rewrite size_map size_enum_ord //=.\n+ intros.\n  rewrite seq_equiv. rewrite nth_mkseq.\n  - rewrite /row_sum.\n    apply Rle_trans with \n    (\\sum_(j < n.+1) Rabs (A (inord i) j) + \n     \\sum_(j < n.+1) Rabs (B (inord i) j))%Re.\n    * assert (\\sum_(j < n.+1) Rabs ((A + B)%Ri (inord i) j) = \n              \\sum_(j < n.+1) Rabs (A (inord i) j + B (inord i) j)).\n      { apply eq_big. by []. intros. rewrite !mxE. by rewrite -RplusE. }\n      rewrite H0. apply sum_abs_le .\n    * apply Rplus_le_compat.\n      ++ assert (\\sum_(j < n.+1) Rabs (A (inord i) j) = \n                  nth 0 [seq \\sum_(j < n.+1) Rabs (A i0 j)\n                            | i0 <- enum 'I_n.+1] i).\n         { rewrite seq_equiv. rewrite nth_mkseq.\n           + by [].\n           + by rewrite size_map size_enum_ord in H.\n         } rewrite H0. apply /RleP.\n         apply (@bigmaxr_ler _ 0 [seq \\sum_(j < n.+1) Rabs (A i0 j)\n                                      | i0 <- enum 'I_n.+1] i).\n         rewrite size_map size_enum_ord in H.\n         by rewrite size_map size_enum_ord.\n      ++ assert (\\sum_(j < n.+1) Rabs (B (inord i) j) = \n                  nth 0 [seq \\sum_(j < n.+1) Rabs (B i0 j)\n                            | i0 <- enum 'I_n.+1] i).\n         { rewrite seq_equiv. rewrite nth_mkseq.\n           + by [].\n           + by rewrite size_map size_enum_ord in H.\n         } rewrite H0. apply /RleP.\n         apply (@bigmaxr_ler _ 0 [seq \\sum_(j < n.+1) Rabs (B i0 j)\n                                      | i0 <- enum 'I_n.+1] i).\n         rewrite size_map size_enum_ord in H.\n         by rewrite size_map size_enum_ord.\n  - by rewrite size_map size_enum_ord in H.\nQed.\n\n\nLemma matrix_norm_sum {n:nat} (f : nat -> 'M[R]_n.+1) (k:nat):\n  matrix_inf_norm\n   (\\sum_(j < k.+1) f j) <= \n  \\sum_(j < k.+1) (matrix_inf_norm (f j)).\nProof.\ninduction k.\n+ rewrite !big_ord_recr //= !big_ord0 !add0r. by apply /RleP; nra.\n+ rewrite big_ord_recr //=.\n  assert (\\sum_(j < k.+2) matrix_inf_norm (f j) = \n          \\sum_(j < k.+1) matrix_inf_norm (f j) + matrix_inf_norm (f k.+1)).\n  { by rewrite big_ord_recr //=. } rewrite H.\n  apply /RleP. \n  apply Rle_trans with \n  (matrix_inf_norm (\\sum_(i < k.+1) f i) + matrix_inf_norm (f k.+1))%Re.\n  - apply /RleP. apply matrix_norm_add.\n  - rewrite -RplusE. \n    apply Rplus_le_compat_r.\n    by apply /RleP.\nQed.\n\n\n\nLemma matrix_inf_norm_1 {n:nat}:\n  @matrix_inf_norm n.+1 1 = 1%Re.\nProof.\nrewrite /matrix_inf_norm. rewrite seq_equiv.\nassert (mkseq (fun i : nat => row_sum 1 (@inord n i)) n.+1 = \n          mkseq (fun i : nat => 1%Re) n.+1).\n{ apply eq_map. unfold eqfun. intros.\n  rewrite /row_sum. \n  rewrite (bigD1 (inord x)) //=.\n  assert (\\sum_(i < n.+1 | i != inord x) Rabs ((1%:M : 'M[R]_n.+1) (inord x) i) = 0%Re).\n  { rewrite big_0_ex_abstract.\n    + by [].\n    + intros. rewrite !mxE.\n      assert (inord x == i = false).\n      { rewrite eq_sym. apply /eqP. by apply /eqP. } rewrite H0 //=.\n      by rewrite Rabs_R0. \n      } rewrite H !mxE //=.\n  rewrite addr0. \n  assert (@inord n x == @inord n x = true).\n  { by apply /eqP. } rewrite H0 //=. by rewrite Rabs_R1.\n} rewrite H.\napply bigmaxrP.\nsplit.\n+ assert (1%Re = nth 0 (mkseq (fun=> 1) n.+1) 0).\n  { by rewrite nth_mkseq. } rewrite H0. rewrite inE //=. \n  apply /orP. by left.\n+ intros. rewrite nth_mkseq.\n  - apply /RleP. apply Rle_refl.\n  - assert (mkseq (fun i : nat => 1%Re) n.+1 = \n             [seq 1%Re | i <- enum 'I_n.+1]).\n    { by rewrite seq_equiv. } rewrite H1 in H0.\n    rewrite size_map size_enum_ord //= in H0.\nQed.\n\n\nLemma matrix_inf_norm_pow {n:nat}:\n  forall (A: 'M[R]_n.+1) (i: nat),\n  (matrix_inf_norm (A ^+ i) <= (matrix_inf_norm A)^+i)%Re.\nProof.\nintros.\ninduction i.\n+ rewrite !expr0. rewrite matrix_inf_norm_1 . apply Rle_refl.\n+ rewrite !exprS. \n  apply Rle_trans with \n  (matrix_inf_norm A * matrix_inf_norm (A ^+ i))%Re.\n  - apply /RleP. apply matrix_norm_le .\n  - rewrite -RmultE. apply Rmult_le_compat_l.\n    * apply /RleP. apply matrix_norm_pd.\n    * apply IHi.\nQed.\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "VeriNum", "repo": "iterative_methods", "sha": "7507d713cceaf91d9493dab620d3583438b8bc8a", "save_path": "github-repos/coq/VeriNum-iterative_methods", "path": "github-repos/coq/VeriNum-iterative_methods/iterative_methods-7507d713cceaf91d9493dab620d3583438b8bc8a/inf_norm_properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6622203658787192}}
{"text": "Require Import Arith List.\nRequire Import BellantoniCook.Lib BellantoniCook.Cobham.\n\nDefinition Zero_e (n:nat) : Cobham :=\n  Comp n Zero nil.\n\nLemma arity_Zero n : arity (Zero_e n) = ok_arity n.\nProof.\n  trivial.\nQed.\n\nLemma rec_bounded_Zero n : \n  rec_bounded (Zero_e n).\nProof.\nsimpl; tauto.\nQed.\n\nDefinition One_e (n:nat) : Cobham :=\n  Comp n (Comp 0 (Succ true) [Zero]) nil.\n\nLemma arity_One n : arity (One_e n) = ok_arity n.\nProof.\n  trivial.\nQed.\n\nLemma rec_bounded_One n :\n  rec_bounded (One_e n).\nProof.\nsimpl; tauto.\nQed.\n\n(** Def 12 of (Rose) *)\n\nDefinition App_e : Cobham :=\n  Rec (Proj 1 0)\n  (Comp 3 (Succ false) [Proj 3 1])\n  (Comp 3 (Succ true) [Proj 3 1])\n  (Comp 2 Smash [Comp 2 (Succ true) [Proj 2 0]; Comp 2 (Succ true) [Proj 2 1] ]).\n\nLemma arity_App : arity App_e = ok_arity 2.\nProof.\n  trivial.\nQed.\n\nLemma rec_bounded_App : rec_bounded App_e.\nProof.\nsimpl.\nintuition.\ndestruct l as [ | u [ | v l] ]; simpl.\nomega.\nrewrite length_smash, mult_1_r; simpl.\ninduction u as [ | [ | ] u IH]; simpl; omega.\nrewrite length_smash', length_smash; simpl.\ninduction u as [ | [ | ] u IH]; simpl; omega.\nQed.\n\nLemma App_correct : forall l,\n  Sem App_e l = hd nil l ++ hd nil (tl l).\nProof.\n  intros; simpl.\n  destruct l; simpl; trivial.\n  induction l; simpl.\n  destruct l0; simpl; trivial.\n  rewrite IHl; case a; trivial.\nQed.\n\nOpaque App_e.\n\nDefinition Rev_e : Cobham :=\n  Rec\n    Zero\n    (Comp 2 App_e [Proj 2 1; Comp 2 (Succ false) [Zero_e 2]])\n    (Comp 2 App_e [Proj 2 1; Comp 2 (Succ true) [Zero_e 2]])\n    (Proj 1 0).\n\nLemma arity_Rev : \n  arity Rev_e = ok_arity 1.\nProof.\ntrivial.\nQed.\n\nLemma rec_bounded_Rev :\n  rec_bounded Rev_e.\nProof.\nsimpl.\nintuition.\napply rec_bounded_App.\napply rec_bounded_App.\ndestruct l as [ | v l].\ntrivial.\nsimpl.\ninduction v as [ | [ | ] v IH].\ntrivial.\nsimpl.\nrewrite App_correct.\nsimpl.\nrewrite app_length.\nsimpl; omega.\nsimpl.\nrewrite App_correct.\nsimpl.\nrewrite app_length.\nsimpl; omega.\nQed. \n\nLemma Rev_correct l :\n  Sem Rev_e l = List.rev (hd nil l).\nProof.\ndestruct l as [ | v l].\ntrivial.\nsimpl.\ninduction v as [ | [ | ] v IH].\ntrivial.\nsimpl.\nrewrite App_correct.\nsimpl; congruence.\nsimpl.\nrewrite App_correct.\nsimpl; congruence.\nQed.\n\nDefinition RemoveLSZ_e : Cobham :=\n  Rec\n    Zero\n    (Proj 2 1)\n    (Comp 2 (Succ true) [Proj 2 0])\n    (Proj 1 0).\n\nLemma arity_RemoveLSZ : \n  arity RemoveLSZ_e = ok_arity 1.\nProof.\ntrivial.\nQed.\n\nLemma rec_bounded_RemoveLSZ :\n  rec_bounded RemoveLSZ_e.\nProof.\nsimpl.\nintuition.\ndestruct l as [ | v l].\ntrivial.\nsimpl.\ninduction v as [ | [ | ] v IH].\ntrivial.\ntrivial.\nsimpl; omega.\nQed.\n\nLemma RemoveLSZ_app u v l :\n  Sem RemoveLSZ_e ((u++v)::l) =\n  match Sem RemoveLSZ_e (u::l) with\n  | nil => Sem RemoveLSZ_e (v::l)\n  | u' => u'++v\n  end.\nProof.\nsimpl.\ninduction u as [ | [ | ] u IH]; trivial.\nQed.\n\nDefinition Cond : Cobham :=\n  Rec (Proj 3 0) (Proj 5 4) (Proj 5 3) (\n    Comp 4 Smash [\n      Comp 4 (Succ true) [Proj 4 1];\n      Comp 4 Smash [\n        Comp 4 (Succ true) [Proj 4 2];\n        Comp 4 (Succ true) [Proj 4 3]\n      ]\n    ]\n  ).\n\nLemma arity_Cond : arity Cond = ok_arity 4.\nProof.\ntrivial.\nQed.\n\nLemma rec_bounded_Cond : rec_bounded' Cond.\nProof.\n  simpl; repeat (split; auto);  intros.\n  repeat (rewrite length_smash'; simpl).\n  repeat (rewrite length_smash; simpl).\n  repeat (rewrite length_smash'; simpl).\n  repeat (rewrite length_smash; simpl).\n  \n  destruct (hd nil l); simpl; repeat rewrite nth_S_tl.\n\n  rewrite plus_n_Sm.\n  rewrite plus_comm.\n  apply le_plus_trans.\n  apply le_trans with ( S (S (length (nth 1 l nil)) * 1)).\n  omega.\n  apply le_n_S.\n  apply le_n_S.\n  apply mult_le_compat.\n  trivial.\n  apply le_n_S.\n  auto with arith.\n\n  apply le_trans with ( S (length (if b then nth 2 l nil else nth 3 l nil)) * 1).\n  rewrite mult_1_r; auto with arith.\n\n  apply le_trans with (S (S (length (nth 2 l nil)) * S (length (nth 3 l nil)))).\n  case b.\n  rewrite mult_1_r.\n  apply le_n_S.\n  rewrite <- mult_1_r at 1.\n  apply mult_le_compat; auto with arith.\n  rewrite mult_1_r.\n  apply le_n_S.\n  rewrite <- mult_1_l at 1.\n  apply mult_le_compat; auto with arith.\n  set (R1 := length (nth 1 l nil)).\n  set (R2 := length (nth 2 l nil)).\n  set (R3 := length (nth 3 l nil)).\n  set (R4 := length (nth 4 l nil)).\n  ring_simplify.\n  cutrewrite (R2 * R3 * R1 + R2 * R3 + R2 * R1 + R2 + R3 * R1 + R3 + 2 * R1 + 3 =\n    (R2 * R3 + R2 + R3 + 2) + (R2 * R3 * R1 + R2 * R1 + R3 * R1 + 2 * R1 + 1)).\n  auto with arith.\n  ring.\nQed.\n\nLemma Cond_correct : forall l,\n  Sem Cond l =\n  match hd nil l with\n  | nil => hd nil (tl l)\n  | true::_ => hd nil (tl (tl l))\n  | false::_ => hd nil (tl (tl (tl l)))\n  end.\nProof.\ndestruct l as [ | [ | [ | ] v1] [ | v2 [ | v3 [ | v4 l] ] ] ]; 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/bellantonicook/src/BellantoniCook/CobhamLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.6621862231282014}}
{"text": "Require Coq.Logic.Classical_Prop.\nRequire Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.lemma_equalitysymmetric.\nRequire Import ProofCheckingEuclid.lemma_orderofpoints_ABC_ACD_BCD.\nRequire Import ProofCheckingEuclid.lemma_orderofpoints_ABC_BCD_ACD.\nRequire Import ProofCheckingEuclid.lemma_outerconnectivity.\nRequire Import ProofCheckingEuclid.lemma_s_onray.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\n\nLemma lemma_onray_shared_initial_point :\n\tforall B C D V,\n\tOnRay B C D ->\n\tOnRay B C V ->\n\tOnRay B D V.\nProof.\n\tintros B C D V.\n\tintros OnRay_BC_D.\n\tintros OnRay_BC_V.\n\n\tdestruct OnRay_BC_D as (E & BetS_E_B_D & BetS_E_B_C).\n\tdestruct OnRay_BC_V as (H & BetS_H_B_V & BetS_H_B_C).\n\n\tassert (~ ~ BetS E B V) as BetS_E_B_V.\n\t{\n\t\tintros nBetS_E_B_V.\n\n\t\tassert (~ BetS B E H) as nBetS_B_E_H.\n\t\t{\n\t\t\tintros BetS_B_E_H.\n\n\t\t\tpose proof (axiom_betweennesssymmetry _ _ _ BetS_B_E_H) as BetS_H_E_B.\n\t\t\tpose proof (lemma_orderofpoints_ABC_ACD_BCD _ _ _ _ BetS_H_E_B BetS_H_B_V) as BetS_E_B_V.\n\n\t\t\tcontradict BetS_E_B_V.\n\t\t\texact nBetS_E_B_V.\n\t\t}\n\n\t\tassert (~ BetS B H E) as nBetS_B_H_E.\n\t\t{\n\t\t\tintros BetS_B_H_E.\n\n\t\t\tpose proof (axiom_betweennesssymmetry _ _ _ BetS_B_H_E) as BetS_E_H_B.\n\t\t\tpose proof (lemma_orderofpoints_ABC_BCD_ACD _ _ _ _ BetS_E_H_B BetS_H_B_V) as BetS_E_B_V.\n\n\t\t\tcontradict BetS_E_B_V.\n\t\t\texact nBetS_E_B_V.\n\t\t}\n\n\t\tpose proof (axiom_betweennesssymmetry _ _ _ BetS_E_B_C) as BetS_C_B_E.\n\t\tpose proof (axiom_betweennesssymmetry _ _ _ BetS_H_B_C) as BetS_C_B_H.\n\t\tpose proof (lemma_outerconnectivity _ _ _ _ BetS_C_B_H BetS_C_B_E nBetS_B_H_E nBetS_B_E_H) as eq_H_E.\n\n\t\tpose proof (lemma_equalitysymmetric _ _ eq_H_E) as eq_E_H.\n\t\tassert (BetS E B V) as BetS_E_B_V by (rewrite eq_E_H; exact BetS_H_B_V).\n\n\t\tcontradict BetS_E_B_V.\n\t\texact nBetS_E_B_V.\n\t}\n\tapply Classical_Prop.NNPP in BetS_E_B_V.\n\n\tpose proof (lemma_s_onray _ _ _ _ BetS_E_B_D BetS_E_B_V) as OnRay_BD_V.\n\texact OnRay_BD_V.\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_shared_initial_point.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.6621862170916888}}
{"text": "Require Import decideq.\n\n(**********************************************************************)\n\n(*Definining a dependent destruct from decideq:*)\n\nLtac dep_destruct H := depdestruct H; dep_destruct_cleanup; try discriminate.\n\nLtac dde := dependent decide equality.\nNotation defeq := (ltac:(dde)) (only parsing).\n\nRequire PeanoNat.\nExisting Instance PeanoNat.Nat.eq_dec.\n\n(* Require Eqdep. *)\n(* Ltac UIP_alias ::= Eqdep.EqdepTheory.UIP. *)\n(* Ltac inj_pair2_alias ::= Eqdep.EqdepTheory.inj_pair2. *)\n\nRequire Eqdep_dec.\nLtac UIP_alias ::= Eqdep_dec.UIP_dec.\nLtac inj_pair2_alias ::= Eqdep_dec.inj_pair2_eq_dec.\n\n(* Require Eqdep_em. *)\n(* Ltac UIP_alias ::= Eqdep_em.UIP_em. *)\n(* Ltac inj_pair2_alias ::= Eqdep_em.inj_pair2_eqem. *)\n\n(**********************************************************************)\n\n(* example from James Wilcox - see:\nhttp://homes.cs.washington.edu/~jrw12/dep-destruct.html*)\n\nInductive Fin : nat -> Set :=\n| F1 : forall n : nat, Fin (S n)\n| FS : forall n : nat, Fin n -> Fin (S n).\n\nInstance Fin_eqdec : eqdec Fin := defeq.\nPrint Assumptions Fin_eqdec.\n\nDefinition cardinality (n : nat) (A : Type) : Prop :=\n  exists (f : A -> Fin n) (g : Fin n -> A),\n    (forall x, g (f x) = x) /\\\n    (forall y, f (g y) = y).\n\nDefinition bool_to_Fin_2 (x : bool) : Fin 2 :=\n  if x then FS _ (F1 _) else F1 _.\n\nDefinition Fin_2_to_bool (y : Fin 2) : bool :=\n  match y with\n  | F1 _ => false\n  | FS _ (F1 _) => true\n  | _ => false (* bogus! *)\n  end.\n\nTheorem bool_cardinality_2 : cardinality 2 bool.\nProof.\n  unfold cardinality.\n  exists bool_to_Fin_2.\n  exists Fin_2_to_bool.\n  split; intros.\n  - destruct x; reflexivity.\n  - dep_destruct y; try reflexivity.\n    dep_destruct y; try reflexivity.\n    dep_destruct y.\nQed.\nPrint Assumptions bool_cardinality_2.\n\nLemma fin_case :\n  forall n (P : Fin (S n) -> Type),\n    (P (F1 _)) ->\n    (forall x, P (FS _ x)) ->\n    (forall x, P x).\nProof.\n  intros n P X X0 x. \n  dep_destruct x.\n  all:auto with nocore.\nQed.\nPrint Assumptions fin_case.\n\n(**********************************************************************)\n\nLemma le_minus : forall n:nat, n < 1 -> n = 0.\nProof.\n  intros n H.\n  dep_destruct H. (*not enough generalizing*)\n  Undo.\n  solve [dep_destruct H; inversion H]. (*but backtracking forces it*)\n  Undo.\n  Ltac sigTgen.sigT_generalize_as_needed ::= false.\n  dep_destruct H. (*now have enough without backtracking*)\n  inversion H.\nQed.\nPrint Assumptions le_minus.\n\nLtac sigTgen.sigT_generalize_as_needed ::= true.\n\nInductive vect A : nat -> Type :=\n| vnil : vect A 0\n| vcons : forall (h:A) (n:nat), vect A n -> vect A (S n).\n\nLemma vect_break: forall A n, forall v : vect A (S n), exists v' : vect A n, exists a : A, v = vcons A a _ v'.\nProof.\n  intros A n v.\n  dep_destruct v.\n  do 2 eexists.\n  reflexivity.\nQed.\nPrint Assumptions vect_break.\n\n\n(*from /test-suite/success/dependentind.v:*)\n(** Example by Andrew Kenedy, uses simplification of the first component of dependent pairs. *)\n\nSet Implicit Arguments.\n\nInductive Ty :=\n | Nat : Ty\n | Prod : Ty -> Ty -> Ty.\n\nInstance Ty_eqdec : eqdec Ty := defeq.\nPrint Assumptions Ty_eqdec.\n\nInductive Exp : Ty -> Type :=\n| Const : nat -> Exp Nat\n| Pair : forall t1 t2, Exp t1 -> Exp t2 -> Exp (Prod t1 t2)\n| Fst : forall t1 t2, Exp (Prod t1 t2) -> Exp t1.\n\nInstance Exp_eqdec : eqdec Exp := defeq.\nPrint Assumptions Exp_eqdec.\n\nInductive Ev : forall t, Exp t -> Exp t -> Prop :=\n| EvConst   : forall n, Ev (Const n) (Const n)\n| EvPair    : forall t1 t2 (e1:Exp t1) (e2:Exp t2) e1' e2',\n               Ev e1 e1' -> Ev e2 e2' -> Ev (Pair e1 e2) (Pair e1' e2')\n| EvFst     : forall t1 t2 (e:Exp (Prod t1 t2)) e1 e2,\n               Ev e (Pair e1 e2) ->\n               Ev (Fst e) e1.\n\nLemma EvFst_inversion : forall t1 t2 (e:Exp (Prod t1 t2)) e1, Ev (Fst e) e1 -> exists e2, Ev e (Pair e1 e2).\n  intros t1 t2 e e1 ev.\n  dep_destruct ev.\n  Fail eexists; eassumption.\n  Undo 2.\n  (*backtrack to generalize enough works:*)\n  dep_destruct ev; eexists; eassumption.\n  Undo.\n  (*or, turn off as_needed mode:*)\n  Ltac sigTgen.sigT_generalize_as_needed ::= false.\n  dep_destruct ev.\n  eexists; eassumption.\nQed.\nPrint Assumptions EvFst_inversion. (*closed now, was using eq_rect_eq*)\n\n", "meta": {"author": "jonleivent", "repo": "deptacs", "sha": "09fa319614f6b7ae5c08346da80a5f1204c7a4cd", "save_path": "github-repos/coq/jonleivent-deptacs", "path": "github-repos/coq/jonleivent-deptacs/deptacs-09fa319614f6b7ae5c08346da80a5f1204c7a4cd/examples2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619306896955, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.6621862129973279}}
{"text": "(**********************************************************************\n\n Enriched slice categories\n\n In this file, we define enriched slice categories. The approach that\n we take, is based on the fact that slice categories can be defined\n using dialgebras. As such, we can reuse the fact that we already\n showed that the category of dialgebras has an enrichment, and we can\n specialize that to obtain an enrichment for slice categories.\n\n Let's be more specific. Suppose that we have a category `C` and an\n object `x` in `C`. To construct the slice category `C/x` we take the\n category of dialgebras between the identity and the functor that is\n constantly `x`. As such, the objects of this category are pairs of an\n object `a` in `C` together with a morphism `a --> x`. As such, this\n corresponds to objects in the slice category `C/x`. The same can be\n said for morphisms.\n\n Note that we assume that the monoidal category `V` has equalizers and\n that the unit is terminal. The reason for that, is because of how\n morphisms in the slice category are defined. If we have two objects\n `f : a --> x` and `g : b --> x` in the slice `C/x`, then a morphism\n from `f` to `g` consists of a morphism `h : a --> b` such that we have\n `f = g · h`. Equalizers are used to o encode the commutativity\n requirement. If one were to define it concretely, one would take the\n equalizer of the following diagram\n ```\n               h ↦ h · g\n             ------------>\n    a --> b                a --> x\n             ----> 𝟙 ---->\n                      f\n ```\n Instead of this concrete definition, we reuse that we already defined\n the enriched category of dialgebras.\n\n Contents\n 1. Enrichment for slice categories\n 2. An equivalence between dialgebras and the slice\n\n **********************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.Univalence.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.CategoryTheory.categories.Dialgebras.\nRequire Import UniMath.CategoryTheory.slicecat.\nRequire Import UniMath.CategoryTheory.Adjunctions.Core.\nRequire Import UniMath.CategoryTheory.Equivalences.Core.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Enrichment.\nRequire Import UniMath.CategoryTheory.EnrichedCats.EnrichmentFunctor.\nRequire Import UniMath.CategoryTheory.EnrichedCats.EnrichmentTransformation.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Examples.DialgebraEnriched.\nRequire Import UniMath.CategoryTheory.Monoidal.Categories.\nRequire Import UniMath.CategoryTheory.limits.equalizers.\nRequire Import UniMath.CategoryTheory.limits.terminal.\n\nImport MonoidalNotations.\n\nLocal Open Scope cat.\nLocal Open Scope moncat.\n\nSection EnrichedSlice.\n  Context (V : monoidal_cat)\n          (HV𝟙 : isTerminal V (I_{V}))\n          (HV : Equalizers V)\n          {C : category}\n          (E : enrichment C V)\n          (x : C).\n\n  (**\n   1. Enrichment for slice categories\n   *)\n  Definition slice_cat_enrichment\n    : enrichment\n        (dialgebra (functor_identity C) (constant_functor C C x))\n        V\n    := dialgebra_enrichment\n         V HV\n         (functor_id_enrichment E)\n         (functor_constant_enrichment HV𝟙 x E E).\n\n  (**\n   2. An equivalence between dialgebras and the slice\n   *)\n  Definition dialgebra_to_slice_data\n    : functor_data\n        (dialgebra (functor_identity C) (constant_functor C C x))\n        (slice_cat C x).\n  Proof.\n    use make_functor_data.\n    - exact (λ x, x).\n    - refine (λ x y f, pr1 f ,, _) ; cbn.\n      abstract\n        (exact (!(id_right _) @ pr2 f)).\n  Defined.\n\n  Definition dialgebra_to_slice_is_functor\n    : is_functor dialgebra_to_slice_data.\n  Proof.\n    repeat split.\n    - intro ; intros.\n      use subtypePath ; [ intro ; apply homset_property | ] ; cbn.\n      apply idpath.\n    - intro ; intros.\n      use subtypePath ; [ intro ; apply homset_property | ] ; cbn.\n      apply idpath.\n  Qed.\n\n  Definition dialgebra_to_slice\n    : dialgebra (functor_identity C) (constant_functor C C x) ⟶ slice_cat C x.\n  Proof.\n    use make_functor.\n    - exact dialgebra_to_slice_data.\n    - exact dialgebra_to_slice_is_functor.\n  Defined.\n\n  Definition slice_to_dialgebra_data\n    : functor_data\n        (slice_cat C x)\n        (dialgebra (functor_identity C) (constant_functor C C x)).\n  Proof.\n    use make_functor_data.\n    - exact (λ x, x).\n    - refine (λ x y f, pr1 f ,, _) ; cbn.\n      abstract\n        (exact (id_right _ @ pr2 f)).\n  Defined.\n\n  Definition slice_to_dialgebra_is_functor\n    : is_functor slice_to_dialgebra_data.\n  Proof.\n    repeat split.\n    - intro ; intros.\n      use subtypePath ; [ intro ; apply homset_property | ] ; cbn.\n      apply idpath.\n    - intro ; intros.\n      use subtypePath ; [ intro ; apply homset_property | ] ; cbn.\n      apply idpath.\n  Qed.\n\n  Definition slice_to_dialgebra\n    : slice_cat C x ⟶ dialgebra (functor_identity C) (constant_functor C C x).\n  Proof.\n    use make_functor.\n    - exact slice_to_dialgebra_data.\n    - exact slice_to_dialgebra_is_functor.\n  Defined.\n\n  Definition dialgebra_to_slice_unit\n    : functor_identity _ ⟹ dialgebra_to_slice ∙ slice_to_dialgebra.\n  Proof.\n    use make_nat_trans.\n    - refine (λ f, identity _ ,, _).\n      abstract\n        (cbn ;\n         exact (id_right _ @ !(id_left _))).\n    - abstract\n        (intros f₁ f₂ τ ;\n         use subtypePath ; [ intro ; apply homset_property | ] ; cbn ;\n         exact (id_right _ @ !(id_left _))).\n  Defined.\n\n  Definition dialgebra_to_slice_counit\n    : slice_to_dialgebra ∙ dialgebra_to_slice ⟹ functor_identity _.\n  Proof.\n    use make_nat_trans.\n    - refine (λ f, identity _ ,, _).\n      abstract\n        (cbn ;\n         exact (!(id_left _))).\n    - abstract\n        (intros f₁ f₂ τ ;\n         use subtypePath ; [ intro ; apply homset_property | ] ; cbn ;\n         exact (id_right _ @ !(id_left _))).\n  Defined.\n\n  Definition dialgebra_to_slice_adj_equiv\n    : adj_equivalence_of_cats dialgebra_to_slice.\n  Proof.\n    simple refine ((_ ,, ((_ ,, _) ,, _ ,, _)) ,, _ ,, _).\n    - exact slice_to_dialgebra.\n    - exact dialgebra_to_slice_unit.\n    - exact dialgebra_to_slice_counit.\n    - abstract\n        (intros f ;\n         use subtypePath ; [ intro ; apply homset_property | ] ; cbn ;\n         apply id_left).\n    - abstract\n        (intros f ;\n         use subtypePath ; [ intro ; apply homset_property | ] ; cbn ;\n         apply id_left).\n    - intro f.\n      use is_z_iso_dialgebra.\n      cbn.\n      apply is_z_isomorphism_identity.\n    - intro f.\n      use z_iso_to_slice_precat_z_iso.\n      cbn.\n      apply is_z_isomorphism_identity.\n  Defined.\nEnd EnrichedSlice.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/CategoryTheory/EnrichedCats/Examples/SliceEnriched.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6621175717976747}}
{"text": "Coq < Section Club.\n\nCoq < Require Import Classical.\n\nCoq < Variables A B C D E : Prop.\nA is assumed\nB is assumed\nC is assumed\nD is assumed\nE is assumed\n\nCoq < Hypothesis rule1 : ~A -> B.\nrule1 is assumed\n\nCoq < Hypothesis rule2 : C \\/ ~B.\nrule2 is assumed\n\nCoq < Hypothesis rule3 : D -> ~E.\nrule3 is assumed\n\nCoq < Hypothesis rule4 : E <-> A.\nrule4 is assumed\n\nCoq < Hypothesis rule5 : C -> A /\\ D.\nrule5 is assumed\n\nCoq < Hypothesis rule6 : A -> C.\nrule6 is assumed\n\nCoq < Lemma NoMember : False.\n1 subgoal\n  \n  A : Prop\n  B : Prop\n  C : Prop\n  D : Prop\n  E : Prop\n  rule1 : ~ A -> B\n  rule2 : C \\/ ~ B\n  rule3 : D -> ~ E\n  rule4 : E <-> A\n  rule5 : C -> A /\\ D\n  rule6 : A -> C\n  ============================\n   False\n\nNoMember < tauto.\nNo more subgoals.\n\nNoMember < Qed.\ntauto.\n\nNoMember 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/practice06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.662117564056218}}
{"text": "Require Coq.Bool.Bool.\n\nModule BoolNotation.\n  Infix \"||\" := orb.\n  Infix \"&&\" := andb.\nEnd BoolNotation.\nImport BoolNotation.\n\nDefinition consider_bool (b:bool) : {b=true}+{b=false}.\nProof. destruct (Bool.bool_dec b true) as [H | H] ; eauto.\n  apply Bool.not_true_is_false in H ; eauto.\nQed.\n\nDefinition orf {A} (f:A -> bool) (g:A -> bool) (a:A) : bool := f a || g a.\nDefinition andf {A} (f:A -> bool) (g:A -> bool) (a:A) : bool := f a && g a.\n\nLemma bool_conj_true : forall b1 b2, (b1 && b2) = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros ; constructor ; intros.\n  - destruct b1,b2 ; auto.\n  - destruct b1,b2 ; auto.\n    destruct H as [H1 H2] ; discriminate H2.\n    destruct H as [H1 H2] ; discriminate H1.\n    destruct H as [H1 H2] ; discriminate H1.\nQed.\n", "meta": {"author": "davdar", "repo": "coq-fp", "sha": "d0b752d9ea9592ba0bc7b067b46a63740fcff056", "save_path": "github-repos/coq/davdar-coq-fp", "path": "github-repos/coq/davdar-coq-fp/coq-fp-d0b752d9ea9592ba0bc7b067b46a63740fcff056/src/CoreData/Bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6620874075326192}}
{"text": "(* week_35.v *)\n(* dIFP 2014-2015, Q1 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* **********\n\n   (0) download and install on your computer:\n       - Coq\n       - Emacs with Proof General (tick \"3 Windows mode layout\" in the Coq top menu;\n         use the hybrid mode if your screen is not wide enough)\n\n   (1) edit the present file, and step through it with Coq,\n       proving the lemmas as you go\n\n   ********** *)\n\nCheck O.\n\nCheck 0.\n\nCheck 1.\n\nCheck S O.\n\nCheck S 1.\n\nCheck S (S (S O)).\n\nCheck (fun x => S x).\n\nCheck S.\n\nCheck (fun x => S (S x)).\n\nCheck (fun f => fun x => S (f (S x))).\n\nCheck (fun f x => S (f (S x))).\n\nCheck 1 + 2.\n\nCompute 1 + 2.\n\nCheck\n  (fun (P : Prop) (p : P) => p).\n\nCheck\n  (fun (P Q : Prop) (p : P) (q : Q) => p).\n\nCheck\n  (fun (P Q : Prop) (p : P) (q : Q) => q).\n\n(* ********** *)\n\n(* Propositional logic:\n\n   P ::= X\n       | P -> P\n       | P /\\ P\n       | P \\/ P\n\n   X ::= A | B | C | D | E | ...\n\n   forall A B C ... : Prop, p\n*)\n\n(*\n   intro and apply\n*)\n\nLemma La :\n  forall P : Prop,\n    P -> P.\nProof.\n  intro P.\n  intro H_P.\n  apply H_P.\nQed.\n\n(*\n   intros\n*)\n\nLemma La' :\n  forall P : Prop,\n    P -> P.\nProof.\n  intros P H_P.\n  apply H_P.\nQed.\n\nLemma Lb :\n  forall P Q : Prop,\n    P -> Q -> P.\nProof.\n  intro P.\n  intro Q.\n  intro H_P.\n  intro H_Q.\n  apply H_P.\nQed.\n\nLemma Lb' :\n  forall P Q : Prop,\n    P -> Q -> P.\nProof.\n  intros P Q.\n  intros H_P H_Q.\n  apply H_P.\nQed.\n\nLemma Lb'' :\n  forall P Q : Prop,\n    P -> Q -> P.\nProof.\n  intros P Q H_P H_Q.\n  apply H_P.\nQed.\n\nLemma Lc :\n  forall P Q : Prop,\n    P -> Q -> Q.\nProof.\n  intros P Q H_P H_Q.\n  apply H_Q.\n  Qed.\n\nLemma Ld :\n  forall P1 P2 P3 P4 P5 : Prop,\n    P1 -> P2 -> P3 -> P4 -> P5 -> P3.\nProof.\n  intros P1 P2 P3 P4 P5.\n  intros H_P1 H_P2 H_P3 H_P4 H_P5.\n  apply H_P3.\n  Qed.\n\n(* ********** *)\n\n(* conjunction in an assumption: use destruct *)\n\nLemma Ca :\n  forall P1 P2 : Prop,\n    P1 /\\ P2 -> P2.\nProof.\n  intros P1 P2.\n  intros H_P1_and_P2.\n  destruct H_P1_and_P2 as [H_P1 H_P2].\n  apply H_P2.\nQed.\n\nLemma Ca' :\n  forall P1 P2 : Prop,\n    P1 /\\ P2 -> P2.\nProof.\n  intros P1 P2.\n  intros [H_P1 H_P2].\n  apply H_P2.\nQed.\n\nLemma Ca'' :\n  forall P1 P2 : Prop,\n    P1 /\\ P2 -> P1.\nProof.\n  intros P1 P2 [H_P1 H_P2].\n  apply H_P1.\n  Qed.\n\nLemma Cb :\n  forall P1 P2 P3 : Prop,\n    P1 /\\ (P2 /\\ P3) -> P3.\nProof.\n  intros P1 P2 P3.\n  intros [H_P1 [H_P2 H_P3]].\n  apply H_P3.\nQed.\n\nLemma Cb' :\n  forall P1 P2 P3 : Prop,\n    P1 /\\ P2 /\\ P3 -> P3.\nProof.\n  intros P1 P2 P3.\n  intros [H_P1 [H_P2 H_P3]].\n  apply H_P3.\nQed.\n\nLemma Cc :\n  forall P1 P2 P3 P4 : Prop,\n    (P1 /\\ P2) /\\ (P3 /\\ P4) -> P3.\nProof.\n  intros P1 P2 P3 P4.\n  intros [[H_P1 H_P2] [H_P3 H_P4]].\n  apply H_P3.\n  Qed.\n\n(* ********** *)\n\n(* conjunction in the goal: use split *)\n\nLemma conjunction_is_commutative :\n  forall P Q : Prop,\n    P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q.\n  intros [H_P H_Q].\n  split.\n    apply H_Q.\n    apply H_P.\nQed.\n\nLemma conjunction_is_commutative' :\n  forall P Q : Prop,\n    P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [H_P H_Q].\n  split.\n    apply H_Q.\n    apply H_P.\nQed.\n\n(*\n   Notation: \"X <-> Y\" is the same as \"(X -> Y) /\\ (Y -> X)\"\n*)\n\nLemma conjunction_is_commutative_either_way :\n  forall P Q : Prop,\n    P /\\ Q <-> Q /\\ P.\nProof.\n  intros P Q.\n  split.\n    intros [H_P H_Q].\n    split.\n    apply H_Q.\n    apply H_P.\n\n    intros [H_Q H_P].\n    split.\n    apply H_P.\n    apply H_Q.\nQed.\n\n(* Simpler: apply conjunction_is_commutative instead of repeating its proof *)\n\nLemma conjunction_is_commutative_either_way' :\n  forall P Q : Prop,\n    P /\\ Q <-> Q /\\ P.\nProof.\n  intros P Q.\n  split.\n  apply (conjunction_is_commutative P Q).\n  apply (conjunction_is_commutative Q P).\nQed.\n\nLemma conjunction_is_associative_from_left_to_right :\n  forall P1 P2 P3 : Prop,\n    (P1 /\\ P2) /\\ P3 -> P1 /\\ (P2 /\\ P3).\nProof.\n  intros P1 P2 P3.\n  intros [[H_P1 H_P2] H_P3].\n  split.\n    apply H_P1.\n    split.\n      apply H_P2.\n      apply H_P3.\nQed.\n\nLemma conjunction_is_associative_from_right_to_left :\n  forall P1 P2 P3 : Prop,\n    P1 /\\ (P2 /\\ P3) -> (P1 /\\ P2) /\\ P3.\nProof.\n  intros P1 P2 P3.\n  intros [H_P1 [H_P2 H_P3]].\n  split. split.\n  apply H_P1. apply H_P2. apply H_P3.\n  Qed.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma conjunction_is_associative_either_way :\n  forall P1 P2 P3 : Prop,\n    P1 /\\ (P2 /\\ P3) <-> (P1 /\\ P2) /\\ P3.\nProof.\n  intros P1 P2 P3.\n  split.\n  apply (conjunction_is_associative_from_right_to_left).\n  apply (conjunction_is_associative_from_left_to_right).\n  Qed.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma conjunction_is_associative_4_from_left_to_right :\n  forall P1 P2 P3 P4 : Prop,\n    P1 /\\ (P2 /\\ (P3 /\\ P4)) -> ((P1 /\\ P2) /\\ P3) /\\ P4.\nProof.\n  intros P1 P2 P3 P4.\n  intros [H_P1 [H_P2 [H_P3 H_P4]]].\n  split. split. split.\n  apply H_P1. apply H_P2. apply H_P3. apply H_P4.\n  Qed.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma conjunction_is_associative_4_from_right_to_left :\n  forall P1 P2 P3 P4 : Prop,\n    ((P1 /\\ P2) /\\ P3) /\\ P4 -> P1 /\\ (P2 /\\ (P3 /\\ P4)).\nProof.\n  intros P1 P2 P3 P4.\n  intros [[[H_P1 H_P2] H_P3] H_P4].\n  split. apply H_P1.\n  split. apply H_P2.\n  split. apply H_P3.\n  apply H_P4.\n  Qed.\n  \n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma conjunction_is_associative_4_either_way :\n  forall P1 P2 P3 P4 : Prop,\n    P1 /\\ (P2 /\\ (P3 /\\ P4)) <-> ((P1 /\\ P2) /\\ P3) /\\ P4.\nProof.\n  intros P1 P2 P3 P4.\n  split.\n  apply (conjunction_is_associative_4_from_left_to_right).\n  apply (conjunction_is_associative_4_from_right_to_left).\n  Qed.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\n(* ********** *)\n\n(* disjunction in the goal: use left or right *)\n\nLemma whatever_1 :\n  forall P Q : Prop,\n    P -> Q -> P \\/ Q.\nProof.\n  intros P Q.\n  intros H_P H_Q.\n  left.\n  apply H_P.\nQed.\n\nLemma whatever_1' :\n  forall P Q : Prop,\n    P -> Q -> P \\/ Q.\nProof.\n  intros P Q.\n  intros H_P H_Q.\n  right.\n  apply H_Q.\nQed.\n\n(* ********** *)\n\n(* disjunction in an assumption: use destruct *)\n\nLemma disjunction_is_commutative :\n  forall P Q : Prop,\n    P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q.\n  intro H_P_or_Q.\n  destruct H_P_or_Q as [H_P | H_Q].\n  right.\n  apply H_P.\n  left.\n  apply H_Q.\nQed.\n\nLemma disjunction_is_commutative' :\n  forall P Q : Prop,\n    P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q.\n  intros [H_P| H_Q].\n  right.\n  apply H_P.\n  left.\n  apply H_Q.\nQed.\n\nLemma disjunction_is_commutative'' :\n  forall P Q : Prop,\n    P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q [H_P | H_Q].\n  right.\n  apply H_P.\n  left.\n  apply H_Q.\nQed.\n\nLemma disjunction_is_commutative_either_way :\n  forall P Q : Prop,\n    P \\/ Q <-> Q \\/ P.\nProof.\n  intros P Q.\n  split.\n  apply (disjunction_is_commutative).\n  apply (disjunction_is_commutative).\n  Qed.\n\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma disjunction_is_associative_from_left_to_right :\n  forall P1 P2 P3 : Prop,\n    (P1 \\/ P2) \\/ P3 -> P1 \\/ (P2 \\/ P3).\nProof.\n  intros P1 P2 P3 [[H_P1 | H_P2] | H_P3].\n  left. apply H_P1.\n  right. left. apply H_P2.\n  right. right. apply H_P3.\nQed.\n\nLemma disjunction_is_associative_from_right_to_left :\n  forall P1 P2 P3 : Prop,\n    P1 \\/ (P2 \\/ P3) -> (P1 \\/ P2) \\/ P3.\nProof.\n  intros P1 P2 P3 [H_P1 | [H_P2 | H_P3]].\n  left. left. apply H_P1.\n  left. right. apply H_P2.\n  right. apply H_P3.\n  Qed.\n\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma disjunction_is_associative_either_way :\n  forall P1 P2 P3 : Prop,\n    P1 \\/ (P2 \\/ P3) <-> (P1 \\/ P2) \\/ P3.\nProof.\n  intros P1 P2 P3.\n  split.\n  apply (disjunction_is_associative_from_right_to_left).\n  apply (disjunction_is_associative_from_left_to_right).\n  Qed.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma disjunction_is_associative_4_from_left_to_right :\n  forall P1 P2 P3 P4 : Prop,\n    P1 \\/ (P2 \\/ (P3 \\/ P4)) -> ((P1 \\/ P2) \\/ P3) \\/ P4.\nProof.\n  intros P1 P2 P3 P4.\n  intros H.\n  apply (disjunction_is_associative_from_right_to_left).\n  apply (disjunction_is_associative_from_right_to_left).\n  apply H.\n  Qed.\n\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma disjunction_is_associative_4_from_right_to_left :\n  forall P1 P2 P3 P4 : Prop,\n    ((P1 \\/ P2) \\/ P3) \\/ P4 -> P1 \\/ (P2 \\/ (P3 \\/ P4)).\nProof.\n  intros P1 P2 P3 P4 H.\n  apply (disjunction_is_associative_from_left_to_right).\n  apply (disjunction_is_associative_from_left_to_right).\n  apply H.\n  Qed.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma disjunction_is_associative_4_either_way :\n  forall P1 P2 P3 P4 : Prop,\n    P1 \\/ (P2 \\/ (P3 \\/ P4)) <-> ((P1 \\/ P2) \\/ P3) \\/ P4.\nProof.\n  intros P1 P2 P3 P4.\n  split.\n  apply (disjunction_is_associative_4_from_left_to_right).\n  apply (disjunction_is_associative_4_from_right_to_left).\n  Qed.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\n(* ********** *)\n\nLemma transitivity_of_implication :\n  forall A B C : Prop,\n    (A -> B) -> (B -> C) -> (A -> C).\nProof.\n  intros A B C.\n  intro H_A_implies_B.\n  intro H_B_implies_C.\n  intro H_A.\n  apply H_B_implies_C.\n  apply H_A_implies_B.\n  apply H_A.\nQed.\n\nLemma transitivity_of_implication' :\n  forall A B C : Prop,\n    (B -> C) -> (A -> B) -> (A -> C).\nProof.\n  intros A B C.\n  intro H_B_imp_C.\n  intro H_A_imp_B.\n  intro H_A.\n  apply H_B_imp_C.\n  apply H_A_imp_B.\n  apply H_A.\n  Qed.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma Le :\n  forall A B C: Prop,\n    (A \\/ B -> C) -> (A -> C) \\/ (B -> C).\nProof.\n  intros A B C.\n  intro H_A_or_B_implies_C.\n  left.\n  intro H_A.\n  apply H_A_or_B_implies_C.\n  left.\n  apply H_A.\n\n  Restart.\n\n  intros A B C.\n  intro H_A_or_B_implies_C.\n  right.\n  intro H_B.\n  apply H_A_or_B_implies_C.\n  right.\n  apply H_B.\nQed.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma Le' :\n  forall A B C: Prop,\n    (A -> C) \\/ (B -> C) -> (A \\/ B -> C).\nProof.\n(*  intros A B C.\n  intros [H_A_imp_C | H_B_imp_C].\n  intros H_A_or_B.\n  apply H_A_imp_C.\n  destruct H_A_or_B as [H_A | H_B].\n  apply H_A.\n  Abort. *)\n  Admitted.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma Lf :\n  forall A B C: Prop,\n    (A \\/ B -> C) -> (A -> C) /\\ (B -> C).\nProof.\n  (* intros A B C.\n  intros H_A_or_B_imp_C. *)\n  Admitted.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma Lf' :\n  forall A B C: Prop,\n    (A -> C) /\\ (B -> C) -> (A \\/ B -> C).\nProof.\n  intros A B C.\n  intros [H_A_imp_C H_B_imp_C].\n  intros [H_A | H_B].\n  apply H_A_imp_C. apply H_A.\n  apply H_B_imp_C. apply H_B.\n  Qed.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma Lg :\n  forall A B C: Prop,\n    (A /\\ B -> C) -> (A -> C) \\/ (B -> C).\nProof.\n  (*intros A B C.\n  intros H_A_or_B_imp_C.\n  left.\n  intros H_A.\n  apply H_A_or_B_imp_C.*) Admitted.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma Lg' :\n  forall A B C: Prop,\n    (A -> C) \\/ (B -> C) -> (A /\\ B -> C).\nProof.\n  intros A B C.\n  intros [H_A_imp_C | H_B_imp_C].\n  intros [H_A H_B].\n  apply H_A_imp_C.\n  apply H_A.\n  intros [H_A H_B].\n  apply H_B_imp_C.\n  apply H_B.\n  Qed.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma Lh :\n  forall A B C: Prop,\n    (A /\\ B -> C) -> (A -> C) /\\ (B -> C).\nProof.\n  (* intros A B C.\n  intros H_A_and_B_imp_C.\n  intros *)Admitted.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma Lh' :\n  forall A B C: Prop,\n    (A -> C) /\\ (B -> C) -> (A /\\ B -> C).\nProof.\n  intros A B C.\n  intros [H_A_imp_C H_B_imp_C].\n  intros [H_A H_B].\n  apply H_A_imp_C. apply H_A. Qed.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\n(* ********** *)\n\nLemma distributivity_of_disjunction_over_conjunction:\n  forall A B C : Prop,\n    A \\/ (B /\\ C) <-> (A \\/ B) /\\ (A \\/ C).\nProof.\nAdmitted.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma distributivity_of_conjunction_over_disjunction:\n  forall A B C : Prop,\n    A /\\ (B \\/ C) <-> (A /\\ B) \\/ (A /\\ C).\nProof.\nAdmitted.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\n(* ********** *)\n\nLemma Curry :\n  forall P Q R : Prop,\n    (P /\\ Q -> R) -> (P -> Q -> R).\nProof.\nAdmitted.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma unCurry :\n  forall P Q R : Prop,\n    (P -> Q -> R) -> (P /\\ Q -> R).\nProof.\nAdmitted.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma Curry_and_unCurry :\n  forall P Q R : Prop,\n    (P /\\ Q -> R) <-> P -> Q -> R.\nProof.\nAdmitted.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\n(* ********** *)\n\n(* Here is how to import a Coq library about arithmetic expressions: *)\n\nRequire Import Arith.\n\nCheck plus_comm.\n\n(*\nplus_comm\n     : forall n m : nat, n + m = m + n\n*)\n\nLemma comm_a :\n  forall a b c : nat,\n    (a + b) + c = c + (b + a).\nProof.\nAdmitted.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\nLemma comm_b :\n  forall x y z : nat,\n    (x + y) + z = z + (y + x).\nProof.\nAdmitted.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\n(* symmetry *)\n\nLemma comm_c :\n  forall a b c : nat,\n    c + (b + a) = (a + b) + c.\nProof.\nAdmitted.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\n(* ********** *)\n\nCheck plus_assoc.\n\n(*\nplus_assoc\n     : forall n m p : nat, n + (m + p) = n + m + p\n*)\n\nLemma assoc_a :\n  forall a b c d : nat,\n    ((a + b) + c) + d = a + (b + (c + d)).\nProof.\nAdmitted.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\n(* ********** *)\n\nLemma mixed_a :\nforall a b c d : nat,\n    (c + (a + b)) + d = (b + (d + c)) + a.\nProof.\nAdmitted.\n(* Exercise: replace \"Admitted.\" by a proof, if there is one. *)\n\n(* ********** *)\n\n(* end of week_35.v *)\n", "meta": {"author": "blacksails", "repo": "dIFP", "sha": "9d3e5f2838674f4fae670668c8a249f11eba0fac", "save_path": "github-repos/coq/blacksails-dIFP", "path": "github-repos/coq/blacksails-dIFP/dIFP-9d3e5f2838674f4fae670668c8a249f11eba0fac/w35/week_35.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.6620874004756357}}
{"text": "Require Import\n  Coq.Lists.List\n  MathClasses.interfaces.abstract_algebra\n  MathClasses.theory.rings\n  Ring.\nImport ListNotations.\n\nSection contents.\n  Context R `{Ring R}.\n  Add Ring R: (stdlib_ring_theory R).\n\n  Definition poly := list R.\n\n  Coercion poly_constant (c : R) : poly := [c].\n\n  Global Instance poly_zero: Zero poly := [].\n  Global Instance poly_one: One poly := poly_constant 1.\n\n  Definition all (l: list Prop): Prop := fold_left and l True.\n  Lemma all_cons P Ps: all (P::Ps) ↔ P ∧ all Ps.\n  Proof.\n    unfold all.\n    revert P; generalize True as Q.\n    induction Ps as [|P' Ps IH]; intros.\n    { cbn; tauto. }\n    change (fold_left and (P' :: Ps) (Q ∧ P) ↔ P ∧ fold_left and (P'::Ps) Q).\n    rewrite !IH.\n    transitivity (P' ∧ (P ∧ fold_left and Ps Q)); try tauto.\n    now rewrite <- (IH Q P).\n  Qed.\n  Arguments all: simpl never.\n\n  Definition poly_eq_zero: poly → Prop := all ∘ map ((=) 0).\n  Corollary poly_eq_zero_cons x p: poly_eq_zero (x::p) ↔ x = 0 ∧ poly_eq_zero p.\n  Proof.\n    unfold poly_eq_zero, compose; cbn; rewrite all_cons.\n    intuition now symmetry.\n  Qed.\n\n  Lemma poly_eq_zero_ind (P: poly → Prop) (case_nil: P [])\n        (casecons: ∀ x p, x = 0 → poly_eq_zero p → P p → P (x::p))\n        p: poly_eq_zero p → P p.\n  Proof.\n    induction p as [|x p IH]; auto.\n    intros [??]%poly_eq_zero_cons.\n    eauto.\n  Qed.\n\n  Global Instance poly_eq: Equiv poly :=\n    fix F p q :=\n    match p, q with\n    | [], _ => poly_eq_zero q\n    | _, [] => poly_eq_zero p\n    | h :: t, h' :: t' => h = h' ∧ F t t'\n    end.\n\n  Lemma poly_eq_p_zero p: (p = 0) ↔ poly_eq_zero p.\n  Proof. now destruct p. Qed.\n\n  Instance: Reflexive poly_eq.\n  Proof with intuition. repeat intro. induction x... split... Qed.\n\n  Lemma poly_eq_cons :\n    ∀ (a b : R) (p q : poly), (a = b /\\ poly_eq p q) <-> poly_eq (a :: p) (b :: q).\n  Proof. easy. Qed.\n\n  Lemma poly_eq_ind (P: poly → poly → Prop)\n        (case_0: ∀ p p', poly_eq_zero p → poly_eq_zero p' → P p p')\n        (case_cons: ∀ x x' p p', x = x' → p = p' → P p p' → P (x::p) (x'::p'))\n        p: ∀ p', p = p' → P p p'.\n  Proof.\n    induction p as [|x p IH]; intros [|x' p'] eqxy.\n    1,2,3: now apply case_0.\n    destruct eqxy.\n    apply case_cons; auto.\n  Qed.\n\n  Lemma poly_eq_zero_trans p q: poly_eq_zero p → poly_eq_zero q → p = q.\n  Proof.\n    revert q.\n    induction p as [|x p IH]; intros ? eqp eqq; auto.\n    destruct q as [|y q]; auto.\n    rewrite poly_eq_zero_cons in *.\n    rewrite <- poly_eq_cons.\n    destruct eqp as [-> ?], eqq as [-> ?]; split; eauto.\n    now apply IH.\n  Qed.\n\n  Instance: Symmetric poly_eq.\n  Proof.\n    intros p p' eqp.\n    pattern p, p'; apply poly_eq_ind; auto; clear p p' eqp.\n    - now intros; apply poly_eq_zero_trans.\n    - intros ???? eqx eqp IH.\n      rewrite <- poly_eq_cons; auto.\n  Qed.\n\n  Instance poly_eq_zero_proper: Proper (poly_eq ==> iff) poly_eq_zero.\n  Proof.\n    apply proper_sym_impl_iff.\n    { apply _. }\n    red; refine (poly_eq_ind _ _ _).\n    - intros; hnf; auto.\n    - unfold impl; intros ???? eqx eqp IH.\n      rewrite !poly_eq_zero_cons, eqx; tauto.\n  Qed.\n\n  Instance: Transitive poly_eq.\n  Proof.\n    intros ??? eqxy; revert z.\n    pattern x, y; refine (poly_eq_ind _ _ _ x y eqxy); clear x y eqxy.\n    { intros x y x0 y0 z eqz.\n      apply poly_eq_zero_trans; auto.\n      now rewrite <- eqz. }\n    intros ???? eqx eqp IH z eqz.\n    destruct z as [|x'' p''].\n    { eapply poly_eq_zero_proper; eauto.\n      now split. }\n    destruct eqz as [eqx' eqp']; split; eauto.\n  Qed.\n\n  Global Instance: Setoid poly.\n  Proof. split; try apply _. Qed.\n\n  Global Instance: Plus poly := fix F p q :=\n    match p, q with\n    | [], _ => q\n    | _, [] => p\n    | h :: t, h' :: t' => h + h' :: F t t'\n    end.\n\n  Lemma poly_eq_zero_plus_l p q: poly_eq_zero p → p + q = q.\n  Proof.\n    intro eqp; revert q.\n    induction eqp as [|x p eqx eqp IH] using poly_eq_zero_ind.\n    { easy. }\n    intros [|y q].\n    { cbn -[poly_eq_zero].\n      rewrite poly_eq_zero_cons; auto. }\n    cbn; split; auto.\n    ring [eqx].\n  Qed.\n\n  Instance plus_commutative: Commutative (+).\n  Proof with (try easy); cbn.\n    intro.\n    induction x as [|x p IH]; intros [|y q]...\n    split; auto; ring.\n  Qed.\n\n  Corollary poly_eq_zero_plus_r p q: poly_eq_zero q → p + q = p.\n  Proof.\n    rewrite commutativity.\n    apply poly_eq_zero_plus_l.\n  Qed.\n\n  Corollary poly_eq_zero_plus p q: poly_eq_zero p → poly_eq_zero q → poly_eq_zero (p+q).\n  Proof.\n    intro.\n    rewrite <- !poly_eq_p_zero; intro.\n    now rewrite poly_eq_zero_plus_l.\n  Qed.\n\n  Global Instance poly_plus_proper: Proper (poly_eq ==> poly_eq ==> poly_eq) (+).\n  Proof.\n    unfold Proper, respectful.\n    refine (poly_eq_ind _ _ _).\n    { intros p p' zp zp' q q' eqq.\n      rewrite !poly_eq_zero_plus_l; auto. }\n    intros ???? eqx eqp IH.\n    refine (poly_eq_ind _ _ _).\n    { intros q q' zq zq'.\n      rewrite !poly_eq_zero_plus_r; auto.\n      cbn; auto. }\n    intros y y' q q' eqy eqq _.\n    cbn; split; eauto.\n    ring [eqx eqy].\n  Qed.\n\n  Instance plus_associative: Associative (+).\n  Proof with try easy.\n    do 2 red; induction x as [|x p IH]...\n    intros [|y q]...\n    intros [|z r]...\n    cbn; split; auto.\n    ring.\n  Qed.\n\n  Instance plus_left_id: LeftIdentity (+) 0.\n  Proof. now intro; rewrite poly_eq_zero_plus_l. Qed.\n  Instance plus_right_id: RightIdentity (+) 0.\n  Proof. now intro; rewrite poly_eq_zero_plus_r. Qed.\n\n  Instance poly_plus_monoid: Monoid poly.\n  Proof. repeat (split; try apply _). Qed.\n\n  Global Instance: Negate poly := map (-).\n\n  Lemma poly_negate_zero p: poly_eq_zero p ↔ poly_eq_zero (-p).\n  Proof.\n    induction p as [|x p IH].\n    { easy. }\n    cbn.\n    rewrite !poly_eq_zero_cons, IH.\n    enough (x = 0 ↔ -x = 0) by tauto.\n    split; intro eq0; ring [eq0].\n  Qed.\n\n  Instance poly_negate_proper: Proper (poly_eq ==> poly_eq) (-).\n  Proof.\n    refine (poly_eq_ind _ _ _).\n    { now intros ?? ->%poly_negate_zero%poly_eq_p_zero ->%poly_negate_zero%poly_eq_p_zero. }\n    intros ???? eqx eqp IH.\n    cbn; split; eauto.\n  Qed.\n\n  Instance poly_negate_l: LeftInverse (+) (-) 0.\n  Proof.\n    intro; rewrite poly_eq_p_zero.\n    induction x as [|x p IH]; cbn.\n    { easy. }\n    rewrite poly_eq_zero_cons; split; auto.\n    ring.\n  Qed.\n\n  Instance poly_negate_r: RightInverse (+) (-) 0.\n  Proof. now intro; rewrite commutativity, left_inverse. Qed.\n\n  Instance poly_plus_abgroup: AbGroup poly.\n  Proof. repeat (split; try apply _). Qed.\n\n  Fixpoint poly_mult_cr (q: poly) (c: R): poly :=\n    match q with\n    | [] => 0\n    | d :: q1 => c*d :: poly_mult_cr q1 c\n    end.\n\n  Lemma poly_mult_cr_0_l q c: poly_eq_zero q → poly_eq_zero (poly_mult_cr q c).\n  Proof.\n    induction q as [|x q IH].\n    { easy. }\n    cbn.\n    rewrite !poly_eq_zero_cons.\n    intros [-> ?]; split; auto.\n    ring.\n  Qed.\n\n  Instance poly_mult_cr_proper: Proper ((=) ==> (=) ==> (=)) poly_mult_cr.\n  Proof.\n    intros p p' eqp c c' eqc.\n    revert p p' eqp; refine (poly_eq_ind _ _ _).\n    { now intros; apply poly_eq_zero_trans; apply poly_mult_cr_0_l. }\n    intros ???? eqx eqp IH.\n    split; auto; cbn.\n    ring [eqx eqc].\n  Qed.\n\n  Lemma poly_mult_cr_1_l x: poly_mult_cr 1 x = [x].\n  Proof. cbn; split; [ring|easy]. Qed.\n  Instance poly_mult_cr_1_r: RightIdentity poly_mult_cr 1.\n  Proof.\n    red; induction x as [|x p IH]; [easy|cbn].\n    split; auto; ring.\n  Qed.\n\n  Instance poly_mult_cr_dist_l: LeftHeteroDistribute poly_mult_cr (+) (+).\n  Proof.\n    intros x a b.\n    induction x as [|x p IH]; [easy|cbn].\n    split; auto; ring.\n  Qed.\n  Instance poly_mult_cr_dist_r: RightHeteroDistribute poly_mult_cr (+) (+).\n  Proof.\n    intros p q a.\n    revert q.\n    induction p as [|x p IH]; intros [|y q]; [easy..|cbn].\n    split; auto; ring.\n  Qed.\n  Instance poly_mult_cr_assoc: HeteroAssociative poly_mult_cr (.*.) poly_mult_cr poly_mult_cr.\n  Proof.\n    intros x a b.\n    induction x as [|p x IH]; [easy|cbn].\n    split; auto; ring.\n  Qed.\n\n  Lemma poly_mult_cr_0_r q c: c = 0 → poly_eq_zero (poly_mult_cr q c).\n  Proof.\n    intros ->.\n    induction q as [|x q IH]; [easy|cbn].\n    rewrite poly_eq_zero_cons; split; auto.\n    ring.\n  Qed.\n\n  Global Instance: Mult poly := fix F p q :=\n    match p with\n    | [] => 0\n    | c :: p1 => poly_mult_cr q c + (0 :: F p1 q)\n    end.\n\n  Lemma poly_mult_0_l p q: poly_eq_zero p → poly_eq_zero (p * q).\n  Proof.\n    induction 1 using poly_eq_zero_ind; [easy|cbn].\n    apply poly_eq_zero_plus.\n    - now apply poly_mult_cr_0_r.\n    - rewrite poly_eq_zero_cons; auto.\n  Qed.\n\n  Lemma poly_mult_0_r p q: poly_eq_zero q → poly_eq_zero (p * q).\n  Proof.\n    induction p as [|x p IH]; [easy|cbn].\n    intro eq0.\n    apply poly_eq_zero_plus.\n    - now apply poly_mult_cr_0_l.\n    - rewrite poly_eq_zero_cons; auto.\n  Qed.\n\n  Instance poly_mult_proper: Proper ((=) ==> (=) ==> (=)) (.*.).\n  Proof.\n    refine (poly_eq_ind _ _ _).\n    { intros ?? zp zp' q q' eqq.\n      now apply poly_eq_zero_trans; apply poly_mult_0_l. }\n    intros ???? eqx eqp IH q q' eqq.\n    cbn.\n    apply poly_plus_proper.\n    { now rewrite eqx, eqq. }\n    split; auto.\n    now apply IH.\n  Qed.\n\n  Instance poly_mult_left_distr: LeftDistribute (.*.) (+).\n  Proof.\n    intros p q r.\n    induction p as [|x p IH]; [easy|cbn].\n    rewrite (distribute_r q r x).\n    rewrite <- !associativity; apply poly_plus_proper; [easy|].\n    rewrite associativity, (commutativity (0::p*q)), <- associativity.\n    apply poly_plus_proper; [easy|].\n    cbn; split; [ring|easy].\n  Qed.\n\n  Lemma poly_mult_cons_r p q x: p * (x::q) = poly_mult_cr p x + (0 :: p * q).\n  Proof.\n    induction p as [|y p IH]; cbn; auto.\n    split; auto.\n    rewrite IH, !associativity, (commutativity (poly_mult_cr _ _)).\n    split; try easy.\n    ring.\n  Qed.\n\n  Instance poly_mult_comm: Commutative (.*.).\n  Proof.\n    intros p.\n    induction p as [|x p IH].\n    { cbn; intro.\n      now apply poly_mult_0_r. }\n    intros [|y q]; cbn.\n    { rewrite poly_eq_zero_cons; split; auto.\n      now apply poly_mult_0_r. }\n    split. 1: ring.\n    rewrite !poly_mult_cons_r, !associativity.\n    apply poly_plus_proper.\n    { apply commutativity. }\n    rewrite <- poly_eq_cons; split; auto.\n    apply IH.\n  Qed.\n\n  Instance poly_mult_right_distr: RightDistribute (.*.) (+).\n  Proof.\n    intros p q r.\n    now rewrite commutativity, distribute_l, !(commutativity r).\n  Qed.\n\n  Instance poly_mult_1_l: LeftIdentity (.*.) 1.\n  Proof.\n    intro; cbn.\n    rewrite poly_mult_cr_1_r, poly_eq_zero_plus_r; auto.\n    now split.\n  Qed.\n\n  Instance poly_mult_1_r: RightIdentity (.*.) 1.\n  Proof.\n    intro; rewrite commutativity; apply left_identity.\n  Qed.\n\n  Instance poly_mult_assoc: Associative (.*.).\n  Proof with (try easy); cbn.\n    intros x.\n    induction x as [|x p IH]...\n    intros q r; cbn.\n    rewrite distribute_r.\n    apply poly_plus_proper; cbn -[poly_eq].\n    { clear IH.\n      induction q as [|y q IH]...\n      rewrite distribute_r, <- associativity, (commutativity x y).\n      apply poly_plus_proper...\n      split; auto.\n      ring. }\n    assert (poly_mult_cr r 0 = 0) as ->.\n    { now rewrite poly_eq_p_zero; apply poly_mult_cr_0_r. }\n    cbn; split; eauto.\n    now rewrite IH.\n  Qed.\n\n  Global Instance poly_ring: Ring poly.\n  Proof. repeat (split; try apply _). Qed.\nEnd contents.\n\n(*\n\nSection test.\n\n  Context `{Ring R} (x y: poly (poly (poly (poly R)))).\n\n  Goal x + y == x * y.\n    set (d := Plus_instance_0 ).\n    set (u := Mult_instance_0).\n    set (t := poly (poly R)).\n    unfold poly_zero.\n\n*)\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/polynomials.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6620873971645228}}
{"text": "Fixpoint eqb (n m : nat) : bool :=\n  match n, m with\n  | O, S m' => false\n  | S n', O => false\n  | O, O => true\n  | S n', S m' => eqb n' m'\n  end.\n\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\n\nTheorem zero_nbeq_plus_q : forall n : nat,\n    0 =? (n + 1) = false.\nProof.\n  intros [| n'].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n", "meta": {"author": "zant", "repo": "gallina", "sha": "5259a6caf0c6abfb3be3437a74b42e8dee32d831", "save_path": "github-repos/coq/zant-gallina", "path": "github-repos/coq/zant-gallina/gallina-5259a6caf0c6abfb3be3437a74b42e8dee32d831/zero_nbeq_plus_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6620873964584759}}
{"text": "(******************************************************************************)\n(* Chapter 1.4: Functors                                                      *)\n(******************************************************************************)\n(* @suharahiromichi *)\n\n(*\n(0)\n同じディレクトリにある Categories.v を使う。\n\n(1) ベースライン\nhttp://www.megacz.com/berkeley/coq-categories/\nこれをもとに改変。Instance ... Proper を使うようにした。\n *)\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import Morphisms.\nRequire Import Aw_0_Notations.\nRequire Import Aw_1_3_Categories.\n\nClass Functor `(C1 : Category) `(C2 : Category) (fobj : C1 -> C2) : Type :=\n  {\n    functor_fobj := fobj;\n    fmor                : forall {a b : C1}, a ~> b -> (fobj a) ~> (fobj b);\n    fmor_respects       : forall {a b : C1} {f f' : a ~> b},\n                            f === f' -> fmor f === fmor f';\n    fmor_preserves_id   : forall {a : C1}, @fmor a a iid === iid;\n(* forall a, fmor (id a) === iid (fobj a); *)\n    fmor_preserves_comp : forall {a b c : C1} {f : a ~> b} {g : b ~> c},\n                            (fmor g) \\\\o (fmor f) === fmor (g \\\\o f)\n  }.\nCoercion functor_fobj : Functor >-> Funclass.\n\nCheck functor_fobj : ∀Obj Hom C1 Obj0 Hom0 C2 fobj _ _, C2.\n(* ,の前の最後の「_」は、普通の引数で、C1（の対象） *)\nCheck @fmor        : ∀Obj Hom C1 Obj0 Hom0 C2 fobj _ a b _, fobj a ~> fobj b.\n(* ,の前の最後の「_」は、普通の引数で、a ~> b の型を持つ。 *)\n\n(* fobj と fmor の意味：\nカテゴリ1 C1 = (Obj, Hom)\nカテゴリ2 C2 = (Obj0, Hom0)\n\nfobj : C1 -> C2、カテゴリC1（の対象）からC2（の対象）への写像\nファンクタからのコアーションが効く。\n\nfmor : (a ~> b) -> (fobj a ~> fobj b)\nカテゴリC1（の射）からC2（の射）への写像、\nただし fobj が与えられないと、意味をなさないことに注意！\n *)\n\nCheck @fmor : ∀Obj Hom C1 Obj0 Hom0 C2 fobj _ a b _, fobj a ~> fobj b.\nCheck fmor : _ ~> _ -> _ ~> _.\nAbout fmor.                       (* Set Implicit Arguments の所為で、\n                                     fobj は implicit になっている。 *)\nArguments fmor {Obj Hom Obj0 Hom0 C1 C2} fobj {_ a b} _ : rename.\nCheck fmor.                          (* fobj を指定するようにする。 *)\n\nNotation \"F \\ f\" := (fmor F f) : category_scope.\nOpen Scope category_scope.\n\n(* parametric_morphism_fmor *)\n(* これの証明に、Classの公理に Proper (eqv ==> eqv) fmor が必要なわけではない。 *)\n(* また、(@fmor _ _ .... a b) は fmor と略せない。  *)\nInstance functor_fmor_Proper `(C1 : Category) `(C2 : Category)\n         (Fobj : C1 -> C2) (F : Functor Fobj) (a b : C1) :\n  Proper (@eqv (a ~> b) ==> @eqv (Fobj a ~> Fobj b)) (@fmor _ _ _ _ _ _ _ _ a b).\nProof.\n  move=> x y.                               (* これが肝 *)\n  Check (@fmor_respects _ _ C1 _ _ C2 Fobj F a b x y).\n  by apply (@fmor_respects _ _ C1 _ _ C2 Fobj F a b x y).\nQed.\n\n(* 恒等関手 *)\n(* the identity functor *)\nProgram Instance functor_id `(C : Category) : Functor (fun (x : C) => x) :=\n  {|\n    fmor := fun (a b : C) (f : a ~> b) => f\n  |}.\nObligation 2.                               (* iid === iid *)\nProof.\n  Check (fun (x : C) => C).                 (* カテゴリC(の対象)から、カテゴリC(の対象)の写像 *)\n  Check (fun (a b : C) (f : a ~> b) => f).  (* カテゴリC(の射)から、カテゴリC(の射)の写像 *)\n  reflexivity.                              (* fmor_preserves_id *)\nDefined.\nObligation 3.                               (* g \\\\o f === g \\\\o f *)\nProof.\n  reflexivity.                              (* fmor_preserves_comp *)\nDefined.\n\n(* 定数関手 *)\n(* the constant functor *)\nProgram Instance functor_const `(C : Category) `{D : Category} (d : D) :\n  Functor (fun (x : C) => d) :=\n  {|\n    fmor := fun (a b : C) (f : a ~> b) => iid\n  |}.\nObligation 1.\nProof.\n  Check (fun (x : C) => d). (* カテゴリC(の対象)から、カテゴリD(の対象)の写像 *)\n  Check (fun (a b : C) (f : a ~> b) => iid). (* カテゴリC(の射)から、カテゴリD(の射)の写像 *)\n  reflexivity.\nDefined.\nObligation 2.\nProof.\n  reflexivity.\nDefined.\nObligation 3.\nProof.\n  by apply left_identity.\nDefined.\n\nGeneralizable Variables Fobj Gobj.\n\nLocate \"_ ○ _\".                            (* \"f ○ g\" := fun x => f (g x) *)\nLocate \"_ \\o _\".                            (* SSReflect では、こっちを使う。 *)\nLocate \"_ \\\\o _\".                           (* \"f \\\\o g\" := comp f g *)\n\n(* 関手の合成 *)\n(* functors compose *)\nProgram Instance functor_comp `(C1 : Category) `(C2 : Category) `(C3 : Category)\n        `(F : @Functor _ _ C1 _ _ C2 Fobj) `(G : @Functor _ _ C2 _ _ C3 Gobj) :\n  Functor (Gobj \\o Fobj) :=\n  {|\n    fmor := fun a b m => G \\ (F \\ m)\n  |}.\nObligation 1.\nProof.\n  Check F : C1 -> C2.              (* C1の対象からC2の対象への写像  *)\n  Check Fobj : C1 -> C2.           (* C1の対象からC2の対象への写像  *)\n  Check fmor F.                    (* C1の射からC2の射への写像 *)\n  Check G : C2 -> C3.              (* C2の対象からC3の対象への写像  *)\n  Check Gobj : C2 -> C3.           (* C2の対象からC3の対象への写像  *)\n  Check fmor G.                    (* C2の射からC3の射への写像 *)\n  rewrite H.\n  reflexivity.\nDefined.\nObligation 2.\nProof.\n  repeat setoid_rewrite fmor_preserves_id.\n  reflexivity.\nDefined.\nObligation 3.\nProof.\n  repeat setoid_rewrite fmor_preserves_comp.\n  reflexivity.\nDefined.\n\nNotation \"f >>>> g\" := (@functor_comp _ _ _ _ _ _ _ _ _ _ f _ g)   : category_scope.\nOpen Scope category_scope.\n\nGeneralizable Variables Xobj Yobj Zobj a b.\n\n(*\nLemma functor_comp_assoc `{C : Category} `{D : Category} `{E : Category} `{F : Category}\n      `(F1 : @Functor _ _ C _ _ D Xobj)\n      `(F2 : @Functor _ _ D _ _ E Yobj)\n      `(F3 : @Functor _ _ E _ _ F Zobj) :\n  forall (a b : C) (f : a ~> b),\n    ((F1 >>>> F2) >>>> F3) \\ f === (F1 >>>> (F2 >>>> F3)) \\ f.\n      \nLemma functor_comp_assoc `{C':Category}`{D:Category}`{E:Category}`{F:Category}\n  {F1obj}(F1:Functor C' D F1obj)\n  {F2obj}(F2:Functor D E F2obj)\n  {F3obj}(F3:Functor E F F3obj)\n  `(f:a~>b) :\n  ((F1 >>>> F2) >>>> F3) \\ f ~~ (F1 >>>> (F2 >>>> F3)) \\ f.\n  intros; simpl.\n  reflexivity.\n  Qed.\n*)\n\n(* this is like JMEq, but for the particular case of ~~; note it does not require any axioms! *)\n\nInductive heq_morphisms `{C : Category} {a b : C} (f : a ~> b) :\n  forall {a' b' : C}, a' ~> b' -> Prop :=\n| heq_morphisms_intro {f' : a ~> b} :\n    eqv f f' -> @heq_morphisms _ _ C a b f a b f'.\n\nDefinition heq_morphisms_refl `{C : Category} a b f :\n  @heq_morphisms _ _ C a b f a  b  f.\nProof.\n  apply heq_morphisms_intro.\n  reflexivity.\nQed.\nCheck heq_morphisms_refl.\nCheck @heq_morphisms_refl :\n  forall {Obj Hom C} {a b : Obj} {f : a ~> b},\n    heq_morphisms f f.\n\nDefinition heq_morphisms_symm `{C : Category} a b f a' b' f' :\n  @heq_morphisms _ _ C a b f a' b' f' -> @heq_morphisms _ _ C a' b' f' a b f.\nProof.\n  case=> f'' H.\n  apply: heq_morphisms_intro.\n  rewrite H.\n  reflexivity.\nQed.\nCheck heq_morphisms_symm.\nCheck @heq_morphisms_symm :\n  forall {Obj Hom C}\n         {a b : Obj} {f : a ~> b}\n         {a' b' : Obj} {f' : a' ~> b'},\n    heq_morphisms f f' -> heq_morphisms f' f.\n\nDefinition heq_morphisms_tran `{C : Category} a b f a' b' f' a'' b'' f'' :\n  @heq_morphisms _ _ C a b f a' b' f' ->\n  @heq_morphisms _ _ C a' b' f' a'' b'' f'' ->\n  @heq_morphisms _ _ C a b f a'' b'' f''.\nProof.\n  case=> f''' H.\n  case=> f'''' H'.\n  apply: heq_morphisms_intro.\n  rewrite -H'.\n  by apply: H.\nQed.\nCheck heq_morphisms_tran.\nCheck @heq_morphisms_tran :\n  forall {Obj Hom C}\n         {a b : Obj} {f : a ~> b}\n         {a' b' : Obj} {f' : a' ~> b'}\n         {a'' b'' : Obj} {f'' : a'' ~> b''},\n    heq_morphisms f f' -> heq_morphisms f' f'' -> heq_morphisms f f''.\n\n(*\nAdd Parametric Relation  (Ob:Type)(Hom:Ob->Ob->Type)(C:Category Ob Hom)(a b:Ob) : (hom a b) (eqv a b)\n  reflexivity proved by  heq_morphisms_refl\n  symmetry proved by     heq_morphisms_symm\n  transitivity proved by heq_morphisms_tran\n  as parametric_relation_heq_morphisms.\n  Add Parametric Morphism `(c:Category Ob Hom)(a b c:Ob) : (comp a b c)\n  with signature (eqv _ _ ==> eqv _ _ ==> eqv _ _) as parametric_morphism_comp.\n  auto.\n  Defined.\n*)\n\nImplicit Arguments heq_morphisms [ Obj Hom C a b a' b' ].\nHint Constructors heq_morphisms.\n\nDefinition EqualFunctors `{C1 : Category} `{C2 : Category}\n           {F1obj} (F1 : Functor F1obj)\n           {F2obj} (F2 : Functor F2obj) :=\n  forall a b (f f' : hom a b),\n    f === f' -> heq_morphisms (fmor F1 f) (fmor F2 f').\n(* f f' : a~~{C1}~~>b *)\n\nNotation \"f ~~~~ g\" := (EqualFunctors f g) (at level 45).\n\nClass IsomorphicCategories `(C : Category) `(D : Category) : Type :=\n  {\n    ic_f_obj    : C -> D;\n    ic_g_obj    : D -> C;\n    ic_f        : Functor ic_f_obj;\n    ic_g        : Functor ic_g_obj;\n    \n    ic_forward  : ic_f >>>> ic_g ~~~~ functor_id C;\n    ic_backward : ic_g >>>> ic_f ~~~~ functor_id D\n  }.\n\n(* this causes Coq to die: *)\n(* Definition IsomorphicCategories := Isomorphic (CategoryOfCategories). *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/categories/Aw_1_4_Functors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979306, "lm_q2_score": 0.7718435030872967, "lm_q1q2_score": 0.662062747411249}}
{"text": "Require Import coqutil.Datatypes.Inhabited.\nRequire Coq.Lists.List coqutil.Datatypes.List.\nRequire Import Coq.ZArith.ZArith. Local Open Scope Z_scope.\nRequire Import Coq.micromega.Lia.\n\nModule List.\n  Section WithA.\n    Import List.ListNotations.\n    Local Notation len l := (Z.of_nat (List.length l)) (only parsing).\n\n    Context [A: Type].\n\n    Definition get{inh: inhabited A}(l: list A)(z: Z): A :=\n      if Z.ltb z 0 then default\n      else List.nth (Z.to_nat z) l default.\n\n    Definition from(z: Z): list A -> list A := List.skipn (Z.to_nat z).\n\n    Definition upto(z: Z): list A -> list A := List.firstn (Z.to_nat z).\n\n    (* length-preserving update seems to create too many additional terms,\n       so we prefer non-length-preserving update\n    Definition zupds(l: list A)(i: Z)(xs: list A): list A :=\n      upto i l ++ from (-i) (upto (zlen l - i) xs) ++ from (i + zlen xs) l. *)\n\n    Definition set(l: list A)(i: Z)(x: A): list A :=\n      upto i l ++ [x] ++ from (i + 1) l.\n\n    Definition repeatz(x: A)(n: Z): list A := List.repeat x (Z.to_nat n).\n\n    Lemma len_from: forall (l: list A) i,\n        0 <= i <= len l ->\n        len (from i l) = len l - i.\n    Proof. intros. unfold from. rewrite List.skipn_length. lia. Qed.\n\n    Lemma len_upto: forall (l: list A) i,\n        0 <= i <= len l ->\n        len (upto i l) = i.\n    Proof. intros. unfold upto. rewrite List.firstn_length. lia. Qed.\n\n    Lemma len_set: forall (l: list A) i x,\n        0 <= i < len l ->\n        len (set l i x) = len l.\n    Proof.\n      intros. unfold set, upto, from.\n      rewrite 2List.app_length, List.skipn_length, List.firstn_length. cbn. lia.\n    Qed.\n\n    Lemma len_app: forall (l1 l2: list A), len (l1 ++ l2) = len l1 + len l2.\n    Proof. intros. rewrite List.app_length. lia. Qed.\n\n    Lemma repeatz_0: forall (x: A), repeatz x 0 = nil.\n    Proof. intros. reflexivity. Qed.\n\n    Lemma len_repeatz: forall (x: A) (n: Z), 0 <= n -> len (repeatz x n) = n.\n    Proof. intros. unfold repeatz. rewrite List.repeat_length. lia. Qed.\n\n    Lemma from_beginning: forall (l: list A) i, i <= 0 -> from i l = l.\n    Proof. intros. unfold from. replace (Z.to_nat i) with O by lia. reflexivity. Qed.\n\n    Lemma upto_beginning: forall (l: list A) i, i <= 0 -> upto i l = nil.\n    Proof. intros. unfold upto. replace (Z.to_nat i) with O by lia. reflexivity. Qed.\n\n    Lemma from_pastend: forall (l: list A) i, len l <= i -> from i l = nil.\n    Proof. intros. unfold from. apply List.skipn_all2. lia. Qed.\n\n    Lemma upto_pastend: forall (l: list A) i, len l <= i -> upto i l = l.\n    Proof. intros. unfold upto. apply List.firstn_all2. lia. Qed.\n\n  End WithA.\n\n  Module ZIndexNotations.\n    Declare Scope zlist_scope.\n\n    (* Notation instead of Definition so that lia sees the Z.of_nat and\n       knows it's nonnegative.\n       Separate notations for parsing/printing because we can't put the parsing\n       notation in a scope: https://github.com/coq/coq/issues/16464 *)\n    Notation len l := (Z.of_nat (List.length l)) (only parsing).\n    Notation \"'len' l\" := (Z.of_nat (List.length l))\n      (at level 10, only printing) : zlist_scope.\n\n    Notation \"a [ i ]\" := (List.get a i)\n      (at level 8, i at level 99, left associativity, format \"a [ i ]\") : zlist_scope.\n\n    Notation \"l [ i := x ]\" := (List.set l i x)\n      (at level 8, i at level 99, left associativity,\n       format \"l [ i  :=  x ]\") : zlist_scope.\n\n    Notation \"a [: i ]\" := (List.upto i a)\n      (at level 8, i at level 99, left associativity, format \"a [: i ]\")\n    : zlist_scope.\n\n    Notation \"a [ i :]\" := (List.from i a)\n      (at level 8, i at level 99, left associativity, format \"a [ i :]\")\n    : zlist_scope.\n\n    (* Note: i needs to be at level <= 99 to avoid conflict with type annotation, and all\n       other notations starting with `_ [ _` must therefore also put i at that same level. *)\n    Notation \"a [ i : j ]\" := (List.from i (List.upto j a))\n      (at level 8, i at level 99, left associativity, format \"a [ i  :  j ]\")\n    : zlist_scope.\n\n    (* Now, `f [x]` means \"list f at index x\", so it can't mean \"function f applied to\n       singleton list x\" any more, so we need to use a different notation for list liteals.\n       Note, though, that this breaks parsing of Ltac like `tac1; [tac2|]`, and separating\n       the bracket and bar into two tokens would bring the notation in conflict with\n       index notations again. *)\n    Notation \"[| x |]\" := (cons x nil) (format \"[| x |]\"): zlist_scope.\n    Notation \"[| x ; y ; .. ; z |]\" :=\n      (cons x (cons y .. (cons z nil) .. )) (format \"[| x ;  y ;  .. ;  z |]\") : zlist_scope.\n\n    (* Redefined common list notations that we leave unchanged, but don't want to import\n       from standard library because that one also gives us [ _ ; _ ; .. ; _ ] *)\n    Notation \"h :: t\" := (cons h t) : zlist_scope.\n    Notation \"a ++ b\" := (app a b) : zlist_scope.\n  End ZIndexNotations.\n\n  Section WithAAndZNotations.\n    Import ZIndexNotations. Open Scope zlist_scope.\n\n    Context [A: Type].\n\n    (* Merging adjacent list slices:\n       1) Turn all slices into the canonical format a[i:j]\n       2) Apply merge_adjacent_slices *)\n\n    Lemma from_upto_comm: forall (l: list A) (i j: Z),\n        0 <= i ->\n        0 <= j ->\n        l[i:][:j] = l[i : i+j].\n    Proof.\n      intros. unfold List.from, List.upto.\n      rewrite List.firstn_skipn_comm. f_equal. f_equal. lia.\n    Qed.\n\n    Lemma from_from: forall (l: list A) (i j: Z),\n        0 <= i ->\n        0 <= j ->\n        l[i:][j:] = l[i+j:].\n    Proof.\n      intros. unfold List.from, List.upto.\n      rewrite List.skipn_skipn. f_equal. lia.\n    Qed.\n\n    Lemma from_canon: forall (l: list A) (i: Z),\n        l[i:] = l[i:len(l)].\n    Proof.\n      unfold List.from, List.upto. intros.\n      replace (Z.to_nat (Z.of_nat (List.length l))) with (List.length l) by lia.\n      rewrite List.firstn_all.\n      reflexivity.\n    Qed.\n\n    Lemma upto_canon: forall (l: list A) (i: Z),\n        l[:i] = l[0:i].\n    Proof.\n      unfold List.from, List.upto. intros.\n      replace (Z.to_nat (Z.of_nat (List.length l))) with (List.length l) by lia.\n      reflexivity.\n    Qed.\n\n    Lemma merge_adjacent_slices: forall (l: list A) (i j k: Z),\n        i <= j <= k ->\n        l[i:j] ++ l[j:k] = l[i:k].\n    Proof.\n      intros. unfold List.from, List.upto.\n      rewrite <- (List.firstn_skipn (Z.to_nat j - Z.to_nat i)\n                    (List.skipn (Z.to_nat i) (List.firstn (Z.to_nat k) l))).\n      rewrite List.firstn_skipn_comm.\n      rewrite List.skipn_skipn.\n      rewrite List.firstn_firstn.\n      repeat match goal with\n             | |- @eq (list _) _ _ => f_equal\n             end.\n      all: lia.\n    Qed.\n\n    Lemma upto_app_discard_r: forall (xs ys: list A) i,\n        i <= len xs ->\n        (xs ++ ys)[:i] = xs[:i].\n    Proof.\n      unfold upto. intros. rewrite List.firstn_app.\n      replace (Z.to_nat i - length xs)%nat with O by lia.\n      change (List.firstn 0 ys) with (@nil A).\n      apply List.app_nil_r.\n    Qed.\n\n    Lemma from_app_discard_l: forall (xs ys: list A) i,\n        len xs <= i ->\n        (xs ++ ys)[i:] = ys[i - len xs :].\n    Proof.\n      unfold from. intros. rewrite List.skipn_app.\n      rewrite List.skipn_all2 by lia. simpl.\n      f_equal. lia.\n    Qed.\n\n    Lemma from_upto_get: forall {inh: inhabited A} (xs : list A) i,\n        0 <= i < len xs ->\n        xs[i:i+1] = [| xs[i] |].\n    Proof.\n      unfold get, from, upto.\n      induction xs; intros;\n        [ destruct H; simpl in H0; lia | ].\n      simpl in H.\n      rewrite Zpos_P_of_succ_nat in H.\n      destruct (Z_dec i 0) as [[Hi | Hi] | Hi].\n      - exfalso. lia.\n      - replace (Z.to_nat (i+1)) with (S (Z.to_nat ((i-1)+1))) by lia.\n        rewrite List.firstn_cons.\n        replace (Z.to_nat i) with (S (Z.to_nat (i-1))) by lia.\n        rewrite List.skipn_cons.\n        rewrite IHxs; [ | lia].\n        destruct (i-1 <? 0) eqn:E; [lia | clear E].\n        destruct (i <? 0) eqn:E; [lia | clear E].\n        simpl. reflexivity.\n      - subst. simpl. reflexivity.\n    Qed.\n\n    Lemma split_at_index: forall (xs : list A) i,\n        0 <= i <= len xs ->\n        xs = xs[:i] ++ xs[i:].\n    Proof.\n      intros.\n      rewrite from_canon, upto_canon.\n      rewrite merge_adjacent_slices by auto.\n      rewrite from_beginning by easy.\n      rewrite upto_pastend; easy.\n    Qed.\n\n    Lemma expose_nth: forall {inh: inhabited A} (xs : list A) i,\n        0 <= i < len xs ->\n        xs = xs[:i] ++ [| xs[i] |] ++ xs[i+1:].\n    Proof.\n      intros.\n      rewrite <- from_upto_get by auto.\n      rewrite (from_canon xs (i+1)).\n      rewrite merge_adjacent_slices by lia.\n      rewrite <- from_canon.\n      apply split_at_index.\n      lia.\n    Qed.\n\n    Lemma len_sized_slice: forall (xs : list A) i size,\n        0 <= size /\\ 0 <= i /\\ i + size <= len xs ->\n        len xs[i:][:size] = size.\n    Proof.\n      intros.\n      rewrite len_upto; auto.\n      unfold from. rewrite List.length_skipn. lia.\n    Qed.\n\n    Lemma len_add_sized_slice: forall (xs : list A) i size,\n        0 <= size /\\ 0 <= i /\\ i + size <= len xs ->\n        len xs[i : i+size] = size.\n    Proof.\n      intros. rewrite <- from_upto_comm by lia. apply len_sized_slice; lia.\n    Qed.\n\n    Lemma len_indexed_slice: forall (xs : list A) i j,\n        0 <= i /\\ i <= j /\\ j <= len xs ->\n        len xs[i : j] = j-i.\n    Proof.\n      intros.\n      replace j with (i + (j-i)) by lia.\n      rewrite <- from_upto_comm by lia.\n      rewrite len_sized_slice; lia.\n    Qed.\n\n  End WithAAndZNotations.\nEnd List.\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/Datatypes/ZList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6620627372967347}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\nRequire Import BinPos BinNat BinInt Zbool Zcompare Zorder Zabs Znat Ndiv_def.\nLocal Open Scope Z_scope.\n\n(** * Definitions of divisions for binary integers *)\n\n(** Concerning the many possible variants of integer divisions, see:\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   We provide here two flavours:\n\n    - convention Floor (F) : [Zdiv_eucl], [Zdiv], [Zmod]\n    - convention Trunc (T) : [Zquotrem], [Zquot], [Zrem]\n\n   A third one, the Euclid (E) convention, can be found in file\n   Zeuclid.v\n\n   For non-zero b, they all satisfy [a = b*(a/b) + (a mod b)]\n   and [ |a mod b| < |b| ], but the sign of the modulo will differ\n   when [a<0] and/or [b<0].\n\n*)\n\n(** * Floor *)\n\n(** [Zdiv_eucl] provides a Truncated-Toward-Bottom (a.k.a Floor)\n  Euclidean division. Its projections are named [Zdiv] and [Zmod].\n  These functions correspond to the `div` and `mod` of Haskell.\n  This is the historical convention of Coq.\n\n  The main properties of this convention are :\n    - we have [sgn (a mod b) = sgn (b)]\n    - [div a b] is the greatest integer smaller or equal to the exact\n      fraction [a/b].\n    - there is no easy sign rule.\n\n  In addition, note that we arbitrary take [a/0 = 0] and [a mod 0 = 0].\n*)\n\n(** First, a division for positive numbers. Even if the second\n   argument is a Z, the answer is arbitrary is it isn't a Zpos. *)\n\nFixpoint Zdiv_eucl_POS (a:positive) (b:Z) : Z * Z :=\n  match a with\n    | xH => if Zge_bool b 2 then (0, 1) else (1, 0)\n    | xO a' =>\n      let (q, r) := Zdiv_eucl_POS a' b in\n\tlet r' := 2 * r in\n\t  if Zgt_bool b r' then (2 * q, r') else (2 * q + 1, r' - b)\n    | xI a' =>\n      let (q, r) := Zdiv_eucl_POS a' b in\n\tlet r' := 2 * r + 1 in\n\t  if Zgt_bool b r' then (2 * q, r') else (2 * q + 1, r' - b)\n  end.\n\n(** Then the general euclidean division *)\n\nDefinition Zdiv_eucl (a b:Z) : Z * Z :=\n  match a, b with\n    | 0, _ => (0, 0)\n    | _, 0 => (0, 0)\n    | Zpos a', Zpos _ => Zdiv_eucl_POS a' b\n    | Zneg a', Zpos _ =>\n      let (q, r) := Zdiv_eucl_POS a' b in\n\tmatch r with\n\t  | 0 => (- q, 0)\n\t  | _ => (- (q + 1), b - r)\n\tend\n    | Zneg a', Zneg b' =>\n      let (q, r) := Zdiv_eucl_POS a' (Zpos b') in (q, - r)\n    | Zpos a', Zneg b' =>\n      let (q, r) := Zdiv_eucl_POS a' (Zpos b') in\n\tmatch r with\n\t  | 0 => (- q, 0)\n\t  | _ => (- (q + 1), b + r)\n\tend\n  end.\n\nDefinition Zdiv (a b:Z) : Z := let (q, _) := Zdiv_eucl a b in q.\nDefinition Zmod (a b:Z) : Z := let (_, r) := Zdiv_eucl a b in r.\n\nInfix \"/\" := Zdiv : Z_scope.\nInfix \"mod\" := Zmod (at level 40, no associativity) : Z_scope.\n\n\n(** * Trunc *)\n\n(** [Zquotrem] provides a Truncated-Toward-Zero Euclidean division.\n  Its projections are named [Zquot] and [Zrem]. These functions\n  correspond to the `quot` and `rem` of Haskell, and this division\n  convention is used in most programming languages, e.g. Ocaml.\n\n  With this convention:\n   - we have [sgn(a rem b) = sgn(a)]\n   - sign rule for division: [quot (-a) b = quot a (-b) = -(quot a b)]\n   - and for modulo: [a rem (-b) = a rem b] and [(-a) rem b = -(a rem b)]\n\n Note that we arbitrary take here [quot a 0 = 0] and [a rem 0 = a].\n*)\n\nDefinition Zquotrem (a b:Z) : Z * Z :=\n  match a, b with\n   | 0,  _ => (0, 0)\n   | _, 0  => (0, a)\n   | Zpos a, Zpos b =>\n     let (q, r) := Pdiv_eucl a b in (Z_of_N q, Z_of_N r)\n   | Zneg a, Zpos b =>\n     let (q, r) := Pdiv_eucl a b in (- Z_of_N q, - Z_of_N r)\n   | Zpos a, Zneg b =>\n     let (q, r) := Pdiv_eucl a b in (- Z_of_N q, Z_of_N r)\n   | Zneg a, Zneg b =>\n     let (q, r) := Pdiv_eucl a b in (Z_of_N q, - Z_of_N r)\n  end.\n\nDefinition Zquot a b := fst (Zquotrem a b).\nDefinition Zrem a b := snd (Zquotrem a b).\n\nInfix \"÷\" := Zquot (at level 40, left associativity) : Z_scope.\n(** No infix notation for rem, otherwise it becomes a keyword *)\n\n(** * Correctness proofs *)\n\n(** Correctness proofs for Trunc *)\n\nLemma Zdiv_eucl_POS_eq : forall a b, 0 < b ->\n  let (q, r) := Zdiv_eucl_POS a b in Zpos a = b * q + r.\nProof.\n intros a b Hb.\n induction a; cbv beta iota delta [Zdiv_eucl_POS]; fold Zdiv_eucl_POS.\n (* ~1 *)\n destruct Zdiv_eucl_POS as (q,r); cbv zeta.\n rewrite Zpos_xI, IHa, Zmult_plus_distr_r, Zmult_permute.\n destruct Zgt_bool.\n now rewrite Zplus_assoc.\n now rewrite Zmult_plus_distr_r, Zmult_1_r, <- !Zplus_assoc, Zplus_minus.\n (* ~0 *)\n destruct Zdiv_eucl_POS as (q,r); cbv zeta.\n rewrite (Zpos_xO a), IHa, Zmult_plus_distr_r, Zmult_permute.\n destruct Zgt_bool; trivial.\n now rewrite Zmult_plus_distr_r, Zmult_1_r, <- !Zplus_assoc, Zplus_minus.\n (* ~1 *)\n generalize (Zge_cases b 2); destruct Zge_bool; intros Hb'.\n now rewrite Zmult_0_r.\n replace b with 1. reflexivity.\n apply Zle_antisym. now apply Zlt_le_succ in Hb. now apply Zlt_succ_le.\nQed.\n\nLemma Zdiv_eucl_eq : forall a b, b<>0 ->\n let (q, r) := Zdiv_eucl a b in a = b * q + r.\nProof.\n intros [ |a|a] [ |b|b]; unfold Zdiv_eucl; trivial;\n  (now destruct 1) || intros _;\n  generalize (Zdiv_eucl_POS_eq a (Zpos b) (eq_refl _));\n  destruct Zdiv_eucl_POS as (q,r); try change (Zneg a) with (-Zpos a);\n  intros ->.\n (* Zpos Zpos *)\n reflexivity.\n (* Zpos Zneg *)\n rewrite <- (Zopp_neg b), Zmult_opp_comm.\n destruct r as [ |r|r]; trivial.\n rewrite Zopp_plus_distr, Zmult_plus_distr_r, <- Zplus_assoc. f_equal.\n now rewrite <- Zmult_opp_comm, Zmult_1_r, Zplus_assoc, Zplus_opp_l.\n rewrite Zopp_plus_distr, Zmult_plus_distr_r, <- Zplus_assoc. f_equal.\n now rewrite <- Zmult_opp_comm, Zmult_1_r, Zplus_assoc, Zplus_opp_l.\n (* Zneg Zpos *)\n rewrite (Zopp_plus_distr _ r), Zopp_mult_distr_r.\n destruct r as [ |r|r]; trivial; unfold Zminus.\n rewrite Zopp_plus_distr, Zmult_plus_distr_r, <- Zplus_assoc. f_equal.\n now rewrite <- Zmult_opp_comm, Zmult_1_r, Zplus_assoc, Zplus_opp_l.\n rewrite Zopp_plus_distr, Zmult_plus_distr_r, <- Zplus_assoc. f_equal.\n now rewrite <- Zmult_opp_comm, Zmult_1_r, Zplus_assoc, Zplus_opp_l.\n (* Zneg Zneg *)\n now rewrite (Zopp_plus_distr _ r), Zopp_mult_distr_l.\nQed.\n\nLemma Z_div_mod_eq_full : forall a b, b<>0 -> a = b*(a/b) + (a mod b).\nProof.\n intros a b Hb. generalize (Zdiv_eucl_eq a b Hb).\n unfold Zdiv, Zmod. now destruct Zdiv_eucl.\nQed.\n\nLemma Zmod_POS_bound : forall a b, 0<b -> 0 <= snd (Zdiv_eucl_POS a b) < b.\nProof.\n assert (AUX : forall a p, a < Zpos (p~0) -> a - Zpos p < Zpos p).\n  intros. unfold Zminus. apply Zlt_plus_swap. unfold Zminus.\n  now rewrite Zopp_involutive, Zplus_diag_eq_mult_2, Zmult_comm.\n intros a [|b|b] Hb; discriminate Hb || clear Hb.\n induction a; cbv beta iota delta [Zdiv_eucl_POS]; fold Zdiv_eucl_POS.\n (* ~1 *)\n destruct Zdiv_eucl_POS as (q,r). cbv zeta.\n simpl in IHa; destruct IHa as (Hr,Hr').\n generalize (Zgt_cases (Zpos b) (2*r+1)). destruct Zgt_bool.\n unfold snd in *.\n split. apply Zplus_le_0_compat. now apply Zmult_le_0_compat. easy.\n  now apply Zgt_lt.\n unfold snd in *.\n split. now apply Zle_minus_le_0.\n  apply AUX.\n  destruct r as [|r|r]; try (now destruct Hr); try easy.\n  red. simpl. apply Pcompare_eq_Lt. exact Hr'.\n (* ~0 *)\n destruct Zdiv_eucl_POS as (q,r). cbv zeta.\n simpl in IHa; destruct IHa as (Hr,Hr').\n generalize (Zgt_cases (Zpos b) (2*r)). destruct Zgt_bool.\n unfold snd in *.\n split. now apply Zmult_le_0_compat.\n  now apply Zgt_lt.\n unfold snd in *.\n split. now apply Zle_minus_le_0.\n  apply AUX.\n  destruct r as [|r|r]; try (now destruct Hr); try easy.\n (* 1 *)\n generalize (Zge_cases (Zpos b) 2). destruct Zge_bool; simpl.\n split. easy. now apply Zle_succ_l, Zge_le.\n now split.\nQed.\n\nLemma Zmod_pos_bound : forall a b, 0 < b -> 0 <= a mod b < b.\nProof.\n intros a [|b|b] Hb; discriminate Hb || clear Hb.\n destruct a as [|a|a]; unfold Zmod, Zdiv_eucl.\n now split.\n now apply Zmod_POS_bound.\n generalize (Zmod_POS_bound a (Zpos b) (eq_refl _)).\n destruct Zdiv_eucl_POS as (q,r). unfold snd. intros (Hr,Hr').\n destruct r as [|r|r]; (now destruct Hr) || clear Hr.\n now split.\n split. now apply Zlt_le_weak, Zlt_plus_swap.\n now apply Zlt_minus_simpl_swap.\nQed.\n\nLemma Zmod_neg_bound : forall a b, b < 0 -> b < a mod b <= 0.\nProof.\n intros a [|b|b] Hb; discriminate Hb || clear Hb.\n destruct a as [|a|a]; unfold Zmod, Zdiv_eucl.\n now split.\n generalize (Zmod_POS_bound a (Zpos b) (eq_refl _)).\n destruct Zdiv_eucl_POS as (q,r). unfold snd. intros (Hr,Hr').\n destruct r as [|r|r]; (now destruct Hr) || clear Hr.\n now split.\n split. rewrite Zplus_comm. now apply (Zplus_lt_compat_r 0).\n rewrite Zplus_comm. apply Zle_plus_swap. simpl. now apply Zlt_le_weak.\n generalize (Zmod_POS_bound a (Zpos b) (eq_refl _)).\n destruct Zdiv_eucl_POS as (q,r). unfold snd. intros (Hr,Hr').\n split. red in Hr'. now rewrite Zcompare_opp in Hr'. now destruct r.\nQed.\n\n(** Correctness proofs for Floor *)\n\nTheorem Zquotrem_eq: forall a b,\n  let (q,r) := Zquotrem a b in a = q * b + r.\nProof.\n destruct a, b; simpl; trivial;\n generalize (Pdiv_eucl_correct p p0); case Pdiv_eucl; trivial;\n  intros q r H; try change (Zneg p) with (-Zpos p);\n  rewrite <- (Z_of_N_pos p), H, Z_of_N_plus, Z_of_N_mult; f_equal.\n now rewrite Zmult_opp_comm.\n now rewrite Zopp_plus_distr, Zopp_mult_distr_l.\n now rewrite Zopp_plus_distr, Zopp_mult_distr_r.\nQed.\n\nLemma Z_quot_rem_eq : forall a b, a = b*(a÷b) + Zrem a b.\nProof.\n intros a b. rewrite Zmult_comm. generalize (Zquotrem_eq a b).\n unfold Zquot, Zrem. now destruct Zquotrem.\nQed.\n\nLemma Zrem_bound : forall a b, 0<=a -> 0<b -> 0 <= Zrem a b < b.\nProof.\n intros a [|b|b] Ha Hb; discriminate Hb || clear Hb.\n destruct a as [|a|a]; (now destruct Ha) || clear Ha.\n compute. now split.\n unfold Zrem, Zquotrem.\n generalize (Pdiv_eucl_remainder a b). destruct Pdiv_eucl as (q,r).\n simpl. split. apply Z_of_N_le_0.\n destruct r; red; simpl; trivial.\nQed.\n\nLemma Zrem_opp_l : forall a b, Zrem (-a) b = - (Zrem a b).\nProof.\n intros [|a|a] [|b|b]; trivial; unfold Zrem;\n  simpl; destruct Pdiv_eucl; simpl; try rewrite Zopp_involutive; trivial.\nQed.\n\nLemma Zrem_opp_r : forall a b, Zrem a (-b) = Zrem a b.\nProof.\n intros [|a|a] [|b|b]; trivial; unfold Zrem; simpl;\n  destruct Pdiv_eucl; simpl; try rewrite Zopp_involutive; trivial.\nQed.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/ZArith/Zdiv_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6620627356013556}}
{"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$ i*)\n\n(** This file formalizes Berardi's paradox which says that in\n   the calculus of constructions, excluded middle (EM) and axiom of\n   choice (AC) imply proof irrelevance (PI).\n   Here, the axiom of choice is not necessary because of the use\n   of inductive types.\n<<\n@article{Barbanera-Berardi:JFP96,\n   author    = {F. Barbanera and S. Berardi},\n   title     = {Proof-irrelevance out of Excluded-middle and Choice\n                in the Calculus of Constructions},\n   journal   = {Journal of Functional Programming},\n   year      = {1996},\n   volume    = {6},\n   number    = {3},\n   pages     = {519-525}\n}\n>> *)\n\nSet Implicit Arguments.\n\nSection Berardis_paradox.\n\n(** Excluded middle *)\nHypothesis EM : forall P:Prop, P \\/ ~ P.\n\n(** Conditional on any proposition. *)\nDefinition IFProp (P B:Prop) (e1 e2:P) :=\n  match EM B with\n  | or_introl _ => e1\n  | or_intror _ => e2\n  end.\n\n(** Axiom of choice applied to disjunction.\n    Provable in Coq because of dependent elimination. *)\nLemma AC_IF :\n forall (P B:Prop) (e1 e2:P) (Q:P -> Prop),\n   (B -> Q e1) -> (~ B -> Q e2) -> Q (IFProp B e1 e2).\nProof.\nintros P B e1 e2 Q p1 p2.\nunfold IFProp in |- *.\ncase (EM B); assumption.\nQed.\n\n\n(** We assume a type with two elements. They play the role of booleans.\n    The main theorem under the current assumptions is that [T=F] *)\nVariable Bool : Prop.\nVariable T : Bool.\nVariable F : Bool.\n\n(** The powerset operator *)\nDefinition pow (P:Prop) := P -> Bool.\n\n\n(** A piece of theory about retracts *)\nSection Retracts.\n\nVariables A B : Prop.\n\nRecord retract : Prop :=\n  {i : A -> B; j : B -> A; inv : forall a:A, j (i a) = a}.\n\nRecord retract_cond : Prop :=\n  {i2 : A -> B; j2 : B -> A; inv2 : retract -> forall a:A, j2 (i2 a) = a}.\n\n\n(** The dependent elimination above implies the axiom of choice: *)\nLemma AC : forall r:retract_cond, retract -> forall a:A, j2 r (i2 r a) = a.\nProof.\nintros r.\ncase r; simpl in |- *.\ntrivial.\nQed.\n\nEnd Retracts.\n\n(** This lemma is basically a commutation of implication and existential\n    quantification:  (EX x | A -> P(x))  <=> (A -> EX x | P(x))\n    which is provable in classical logic ( => is already provable in\n    intuitionnistic logic). *)\n\nLemma L1 : forall A B:Prop, retract_cond (pow A) (pow B).\nProof.\nintros A B.\ndestruct (EM (retract (pow A) (pow B))) as [(f0,g0,e) | hf].\n  exists f0 g0; trivial.\n  exists (fun (x:pow A) (y:B) => F) (fun (x:pow B) (y:A) => F); intros;\n    destruct hf; auto.\nQed.\n\n\n(** The paradoxical set *)\nDefinition U := forall P:Prop, pow P.\n\n(** Bijection between [U] and [(pow U)] *)\nDefinition f (u:U) : pow U := u U.\n\nDefinition g (h:pow U) : U :=\n  fun X => let lX := j2 (L1 X U) in let rU := i2 (L1 U U) in lX (rU h).\n\n(** We deduce that the powerset of [U] is a retract of [U].\n    This lemma is stated in Berardi's article, but is not used\n    afterwards. *)\nLemma retract_pow_U_U : retract (pow U) U.\nProof.\nexists g f.\nintro a.\nunfold f, g in |- *; simpl in |- *.\napply AC.\nexists (fun x:pow U => x) (fun x:pow U => x).\ntrivial.\nQed.\n\n(** Encoding of Russel's paradox *)\n\n(** The boolean negation. *)\nDefinition Not_b (b:Bool) := IFProp (b = T) F T.\n\n(** the set of elements not belonging to itself *)\nDefinition R : U := g (fun u:U => Not_b (u U u)).\n\n\nLemma not_has_fixpoint : R R = Not_b (R R).\nProof.\nunfold R at 1 in |- *.\nunfold g in |- *.\nrewrite AC with (r := L1 U U) (a := fun u:U => Not_b (u U u)).\ntrivial.\nexists (fun x:pow U => x) (fun x:pow U => x); trivial.\nQed.\n\n\nTheorem classical_proof_irrelevence : T = F.\nProof.\ngeneralize not_has_fixpoint.\nunfold Not_b in |- *.\napply AC_IF.\nintros is_true is_false.\nelim is_true; elim is_false; trivial.\n\nintros not_true is_true.\nelim not_true; trivial.\nQed.\n\nEnd Berardis_paradox.\n", "meta": {"author": "JasonGross", "repo": "category-coq-experience-tests", "sha": "f9949ede618788fd051fe8327f997ee683388e49", "save_path": "github-repos/coq/JasonGross-category-coq-experience-tests", "path": "github-repos/coq/JasonGross-category-coq-experience-tests/category-coq-experience-tests-f9949ede618788fd051fe8327f997ee683388e49/coq/coq-8.3pl5-foundations/test-suite/misc/berardi_test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818985, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.6619779516271943}}
{"text": "Section on_ex. \n  Variables \n   (A:Type)\n   (P Q:A -> Prop).\n\n Lemma ex_or : (exists x:A, P x \\/ Q x) -> ex P \\/ ex Q.\n Proof.\n  intro H; elim H; intros x [H1|H1].\n  left ; exists x; trivial.\n  right ; exists x; trivial.\n Qed.\n \n Lemma ex_or_R : ex P \\/ ex Q -> (exists x:A, P x \\/ Q x).\n Proof.\n  intros [H | H]; case H; intros x Hx; exists x; auto.\n Qed.\n\n Lemma two_is_three : (exists x:A, forall R : A->Prop, R x) -> 2 = 3.\n Proof.\n  intro H; elim H; intros x Hx.\n  elim (Hx (fun y:A => False)).\n Qed.\n\n Lemma forall_no_ex : (forall x:A, P x) -> ~(exists y:A, ~ P y).\n Proof.\n  intros H H0; elim H0.\n  intros x Hx; apply Hx ; apply H.\n Qed.\n\nEnd on_ex.\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/exo_on_ex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818985, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6619779416106104}}
{"text": "(*********************************************)\n(* This file is part of the 'Higman' contrib *)\n(* file : tree.v                             *)\n(* contains : tree definition and its        *)   \n(*  associated induction principle           *)\n(* author : W.Delobel                        *)\n(*********************************************)\n\nSet Implicit Arguments.\nRequire Export Arith.\nRequire Export List.\n  \nSection Wrap.\n\n    Unset Elimination Schemes.\n\n    Variable A : Set.\n    Variable leA : A -> A -> Prop.\n\n    Inductive tree : Set := \n      | node : A -> list tree -> tree.\n\nSection definitions.\n\n\n    Fixpoint tree_size (t : tree) : nat :=\n      match t with \n\t| node _ l => S ((fix l_size (l : list tree) : nat :=\n\t\t\t    match l with \n\t\t\t      | nil => 0\n\t\t\t      | t' :: l' => (tree_size t') + (l_size l')\n\t\t\t    end) l)\n      end.\n\n   Definition root (t : tree) : A :=\n\tmatch t with \n\t| node a l => a\n\tend.\n\n   Definition subtrees (t : tree) : list tree :=\n\tmatch t with \n\t| node _ l => l\n\tend.\n\n   \nInductive tree_in_forest : tree -> list tree -> Prop :=\n| tif0 : forall t t' l, In t' l -> subtree t t' -> tree_in_forest t l\nwith subtree : tree -> tree -> Prop :=\n| sub0 : forall t, subtree t t\n| sub1 : forall t l ts, tree_in_forest t ts -> subtree t (node l ts). \n\n\nEnd definitions.\n\nSection tree_rect.\n\n    Variables\n      (P : tree -> Type)\n      (Q : list tree -> Type).\n\n    Hypotheses\n      (H1 : forall x, P (node x nil))\n      (H2 : forall f v, Q v -> P (node f v))\n      (H3 : Q nil)\n      (H4 : forall t v, P t -> Q v -> Q (t :: v)).\n\n    Fixpoint tree_rect_aux t : P t :=\n      match t as t return P t with\n\t| node f v => H2 f\n\t  ((fix vt_rect (v : list tree) : Q v :=\n\t    match v as v return Q v with\n\t      | nil => H3\n\t      | cons t' v' => H4 (tree_rect_aux t') (vt_rect v')\n\t    end) v)\n      end.\n\nEnd tree_rect.\n\nSet Elimination Schemes.\n\t\t\t    \nInductive lforall (P : tree -> Type) : list tree -> Type :=\n| lforall_nil : lforall P nil\n| lforall_cons : forall a l, lforall P l -> P a -> lforall P (a::l).\n\n\nLemma tree_rect : forall P : tree -> Type, \n      (forall x, P (node x nil)) -> (forall f v, lforall P v -> P (node f v)) ->\n      forall t, P t.\nProof.\n\tintros P H1 H2. \n\tapply tree_rect_aux with (Q := fun l => lforall P l); trivial.\n\tconstructor.\n\tintros; constructor; trivial.\nQed.\n\nLemma tree_ind : forall P : tree -> Prop, \n\t(forall x, P (node x nil)) -> (forall f v, (forall u, In u v -> P u) -> P (node f v)) ->\n\tforall t, P t.\nProof.\n\tintros P H1 H2.\n\tapply tree_rect; trivial.\n\tintros f v H; apply H2.\n\tinduction H; intros u Hu.\n\tinversion Hu.\n\telim Hu; clear Hu; intro Hu.\n\tsubst; trivial.\n\tapply IHlforall; trivial.\nQed.\n\nFact im_sub_tree_size : forall a l t, In t l -> (tree_size t) < (tree_size (node a l)).\nProof.\n\tintros a l; induction l as [| u l IHl]; intros t Hin.\n\tinversion Hin.\n\telim Hin; clear Hin; intro Hin.\n\tsubst; simpl in |- *.\n\tapply lt_le_trans with (S (tree_size t)); auto with arith.\n\tapply lt_le_trans with (tree_size (node a l)); auto with arith.\n\tsimpl; auto with arith.\nQed.\n\nFact subtree_trans : forall t t' t'', subtree t t' -> subtree t' t'' -> subtree t t''.\nProof.\nassert (H : forall t'' t', subtree t' t'' -> forall t, subtree t t' -> subtree t t'').\nintro t; induction t as [a | a f IHt]; intros t' H1 t'' H2.\ninversion H1; subst; trivial.\ninversion H3; subst; trivial.\ninversion H.\ninversion H1; subst; trivial.\nconstructor 2.\ninversion H3; subst.\nconstructor 1 with t'0; trivial.\napply IHt with t'; trivial.\nintros t t' t'' H1 H2; apply H with t'; trivial.\nQed.\n\nFact eq_tree_dec : (forall (a a' : A), {a = a'} + {a <> a'}) -> \nforall (t t' : tree), {t = t'} + {t <> t'}.\nProof.\nintro eq_A_dec; apply (tree_rect (P:=fun t => forall (t' : tree), {t = t'} + {t <> t'})).\nintros a t'; destruct t' as [a' ts'].\ndestruct ts'; [idtac | right; intro HF; inversion HF].\nelim (eq_A_dec a a'); intro case_a_a'; [left | right; intro HF; apply case_a_a']; subst; trivial.\ninversion HF; trivial.\nintros a ts IHt t'; destruct t' as [a' ts'].\nelim (eq_A_dec a a'); intro case_a_a'; [subst a'|right;intro HF;inversion HF;apply case_a_a'; trivial].\nassert (H : {ts = ts'} + {ts <> ts'}).\ngeneralize ts'; clear ts'; induction IHt; intro ts'.\ndestruct ts' as [| t' ts']; [left | right]; trivial.\nintro HF; inversion HF.\ndestruct ts' as [| t' ts']; [right | idtac]; trivial.\nintro HF; inversion HF.\nelim (IHIHt ts'); intro case_ts'.\nsubst; elim (p t'); intro case_t'; subst; [left | right]; trivial.\nintro HF; inversion HF; apply case_t'; trivial.\nright; intro HF; inversion HF; apply case_ts'; trivial.\nelim H; clear H; intro H; [left; subst | right]; trivial.\nintro HF; inversion HF; apply H; trivial.\nQed.\n\nEnd Wrap.\n", "meta": {"author": "coq-contribs", "repo": "higman-s", "sha": "0cae3b45df7a65f49afdb58f182065b939e5d224", "save_path": "github-repos/coq/coq-contribs-higman-s", "path": "github-repos/coq/coq-contribs-higman-s/higman-s-0cae3b45df7a65f49afdb58f182065b939e5d224/tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6619677302762005}}
{"text": "Require Import Shor.\nRequire Import euler.Primes.\nRequire Import euler.AltPrimes.\nRequire Import SQIR.ExtractionGateSet.\nRequire Import ExtrShor Reduction.\nRequire Import QuantumLib.DiscreteProb.\n\n(* The end-to-end definition of Shor's algorithm, combining the facts from \n   Shor.v and ShorAux.v into a digestable form. *)\n\n(** Coq definitions that will be extracted to OCaml **)\n\n(* given r = ord(a,N), try to find a factor of N (based on Shor.Factor_post) *)\nDefinition factor (a N r : nat) := \n  let cand1 := Nat.gcd (a ^ (r / 2) - 1) N in\n  let cand2 := Nat.gcd (a ^ (r / 2) + 1) N in \n  if (1 <? cand1) && (cand1 <? N) then Some cand1      (* candidate #1 is a factor *)\n  else if (1 <? cand2) && (cand2 <? N) then Some cand2 (* candidate #2 is a factor *)\n  else None.                                           (* failed to find factor *)\n\n(* End-to-end definition of Shor's algorithm.\n\n   Inputs:\n     N = number to factor\n     rnds = stream of random real values\n     i = index into rnds\n     niter = max number of iterations\n   \n   Output:\n     None or Some x where x is a nontrivial factor of N.\n\n   Algorithm: Up to a maximum number of iterations, select \"a\" uniformly from \n   [1,n-1] and\n     1. Run the circuit generated by (shor_circuit a N) on input  ∣0⟩_{n + k}.\n     2. Measure the first n qubits, resulting in the n-bit number x.\n     3. Run continued fraction expansion (= OF_post) to get r, which is a \n        candidate for the order (ord a N).\n     4. Use r to try to factor N.\n\n  The probability of success (returning Some) and the resources (aka qubits and \n  gates) used is a function of N and niter (see proofs below). *)\n\n(* We will customize the extraction of this function to avoid extracting our\n   uc_eval function, which relies on an inefficient representation of matrices. *)\nDefinition run n (c : ucom U) rnd : nat :=\n  sample (apply_u (UnitarySem.uc_eval (to_base_ucom n c))) rnd.\n\n(* N   : number to factor\n   rnd : source of randomness for sampling *)\nDefinition shor_body N rnd :=\n  let n := shor_output_nqs N in\n  let k := modmult_nqs N in\n  (* create a uniform distribution *)\n  let adist := uniform 1 N in\n  (* use rnd to sample from adist *)\n  let a := sample adist rnd in\n  (* do a and N share a factor? *)\n  if Nat.gcd a N =? 1%nat\n  (* if not, use a to construct a quantum circuit*)\n  then let c := shor_circuit a N in\n       (* get the leftover randomness to sample from the circuit's output *)\n       let rnd' := compute_new_rnd rnd adist a in\n       (* run the circuit *)\n       let x := run (shor_nqs N) c rnd' in\n       (* try to factor *)\n       factor a N (OF_post a N (fst k x) n)\n  else Some (Nat.gcd a N).\n  \n\nDefinition end_to_end_shors N rnds :=\n  iterate rnds (shor_body N).\n\n(** Correctness properties for Shor's **)\n\nDefinition coprime (a b : nat) : Prop := Nat.gcd a b = 1%nat.\n\n(* The probability that shor_body returns ord(a,N) is at least κ / (Nat.log2 N)^4 \n   where κ is about 0.055 (see Shor.Shor_correct_full). *)\nLemma shor_body_returns_order : forall (a N : nat),\n  (0 < a < N)%nat ->\n  coprime a N ->\n  let n := shor_output_nqs N in\n  let k := modmult_nqs N in\n  let circ := to_base_ucom (n + k) (shor_circuit a N) in\n  pr_outcome_sum \n      (apply_u (UnitarySem.uc_eval circ))\n      (fun x => OF_post a N (fst k x) n =? ord a N) \n    >= κ / INR (Nat.log2 N)^4.\nProof.\n  intros a N Ha1 Ha2 n k circ.\n  subst circ.\n  remember (fun x => OF_post a N x n =? ord a N) as f'.\n  replace (fun x : nat => OF_post a N (fst k x) n =? ord a N)\n    with (fun x : nat => f' (fst k x)).\n  rewrite rewrite_pr_outcome_sum.\n  specialize (Shor.Shor_correct a N Ha1 Ha2) as H1.\n  specialize (shor_circuit_same' a N) as H2.\n  unfold prob_shor_outputs in H2.\n  erewrite big_sum_eq_bounded.\n  2: { intro i. rewrite H2. reflexivity. lia. }\n  unfold probability_of_success in H1.\n  unfold r_found in H1.\n  subst f'.\n  apply H1.\n  apply WF_uc_eval.\n  subst f'.\n  reflexivity.\nQed.\n\nDefinition leads_to_factor N a := \n  nontrivgcd a N ||\n  (nontrivgcd (a ^ ((ord a N) / 2)%nat - 1) N ||\n   nontrivgcd (a ^ ((ord a N) / 2)%nat + 1) N).\n\n(* Assuming that N is not prime, not even, and not a power of a prime, for a\n   random choice of a, the probability that ord(a,N) can be used to find a\n   factor is at least 1/2. *) \nLemma shor_factoring_succeeds : forall N,\n  ~ (prime N) -> Nat.Odd N -> (forall p k, prime p -> N <> p ^ k)%nat ->\n   pr_outcome_sum\n     (uniform 1 N)\n     (fun x => leads_to_factor N x)\n   >= 1 / 2.\nProof.\n  intros.\n  apply simplify_primality in H; trivial. clear H0 H1.\n  destruct H as [p [k [q [H0 [H1 [H3 [H4 [H5 H6]]]]]]]].\n  assert (H :( N - 1 <= 2 * count1 (leads_to_factor N) (N - 1))%nat).\n  subst N.\n  apply reduction_factor_order_finding; auto.\n  assert (2 < N)%nat.\n  subst N. \n  rewrite <- (Nat.mul_1_l 2).\n  apply Nat.mul_lt_mono_nonneg; try lia.\n  apply Nat.pow_gt_1; lia.\n  rewrite pr_outcome_sum_count by lia.\n  unfold count1 in *. erewrite count_eq.\n  2 : { intros x Hx. replace (2 + x - 1)%nat with (x + 1)%nat by lia. reflexivity. }\n  rewrite count_eq with (g := leads_to_factor N).\n  apply le_INR in H. rewrite mult_INR in H. replace (INR 2) with 2 in H by easy.\n  unfold Rdiv.\n  assert (0 < INR (N - 1)).\n  { apply lt_0_INR. lia. }\n  assert (0 < / INR (N - 1)).\n  { apply Harmonic.INR_inv_pos. lia. }\n  apply Rmult_le_compat_r with (r := (/ INR (N - 1))%R) in H; try lra.\n  rewrite Rinv_r in H by lra.\n  apply Rmult_le_compat_l with (r := 2%R) in H; try lra.\n  intros. f_equal. lia.\nQed.\n\nDefinition is_a_factor x y := exists z, (1 < z < y)%nat /\\ y = (z * x)%nat.\n\nLemma gcd_is_factor : forall x y, (1 < Nat.gcd x y < y)%nat -> is_a_factor (Nat.gcd x y) y.\nProof.\n  intros x y H.\n  unfold is_a_factor.\n  specialize (Nat.gcd_divide_r x y) as G. destruct G.\n  exists x0.\n  split; try lia.\n  split; nia.\nQed.\n\nLemma factor_returns_factor : forall a N r x,\n  factor a N r = Some x -> is_a_factor x N.\nProof.\n  intros a N r x H.\n  unfold factor in H.\n  remember (Nat.gcd (a ^ (r / 2) - 1) N) as k1.\n  remember (Nat.gcd (a ^ (r / 2) + 1) N) as k2.\n  bdestruct (1 <? k1); bdestruct (k1 <? N); \n    bdestruct (1 <? k2); bdestruct (k2 <? N); \n    simpl in H; inversion H; subst;\n    apply gcd_is_factor; auto.\nQed.\n\nLemma end_to_end_shors_correct : forall N rnds x,\n    (1 < N)%nat ->\n    (Forall (fun x => 0 <= x < 1) rnds) ->\n    end_to_end_shors N rnds = Some x ->\n    is_a_factor x N.\nProof.\n  intros N rnds x H Hrnds H0.\n  unfold end_to_end_shors in H0.\n  induction rnds as [ | rnd rnds]; intros.\n  inversion H0.\n  simpl in H0.\n  destruct (shor_body N rnd) eqn:sb; auto.\n  inversion H0; subst.\n  unfold shor_body in sb.\n  remember (sample (uniform 1 N) rnd) as a.\n  bdestruct (Nat.gcd a N =? 1).\n  apply factor_returns_factor in sb. \n  auto.\n  inversion sb.\n  apply gcd_is_factor.\n  assert (1 <= a < N)%nat.\n  { rewrite Heqa.\n    inversion Hrnds.\n    apply sample_uniform; auto.\n  }\n  assert (0 < Nat.gcd a N)%nat.\n  apply Natgcd_pos; lia.\n  assert (Nat.gcd a N <= a)%nat.\n  rewrite Nat.gcd_comm.\n  apply Misc.Nat_gcd_le_r.\n  lia. \n  lia.\n  inversion Hrnds. apply IHrnds; assumption.\nQed.\n\n(* For the rest of the proof, it is convenient to use a version\n   of shor_body that explicitly constructs the joint distribution. *)\nDefinition process N out :=\n  let n := shor_output_nqs N in\n  let k := modmult_nqs N in\n  let a := fst (n + k) out in\n  let x := snd (n + k) out in\n  if Nat.gcd a N =? 1%nat\n  then factor a N (OF_post a N (fst k x) n)\n  else Some (Nat.gcd a N).\n\nDefinition shor_joint_distr N := \n  join (uniform 1 N) \n       (fun a => apply_u (uc_eval (shor_nqs N) (shor_circuit a N))).\n\nDefinition shor_body_alt N rnd :=\n  let out := sample (shor_joint_distr N) rnd in\n  process N out.\n\nLemma shor_body_alt_same : forall N rnd,\n  (1 < N)%nat ->\n  0 <= rnd < 1 ->\n  shor_body N rnd = shor_body_alt N rnd.\nProof.\n  intros.\n  assert (Hun : distribution (uniform 1 N)).\n  apply distribution_uniform. auto.\n  destruct Hun as [Hun1 Hun2].\n  unfold shor_body, shor_body_alt, shor_joint_distr, process.\n  rewrite fst_sample_join, snd_sample_join.\n  reflexivity.\n  rewrite Hun2. auto.\n  apply Hun1.\n  intro k. apply length_apply_u.\n  intros k Hk. \n  apply distribution_apply_u.\n  apply uc_eval_unitary.\n  apply uc_well_typed_shor_circuit.\n  rewrite length_uniform in Hk; lia.\n  lra.\n  apply Hun1.\n  intro k. apply length_apply_u.\n  intros k Hk.\n  apply distribution_apply_u.\n  apply uc_eval_unitary.\n  apply uc_well_typed_shor_circuit.\n  rewrite length_uniform in Hk; lia.\nQed.\n\nLemma shor_body_succeeds_with_high_probability' : forall N,\n    ~ (prime N) -> Nat.Odd N -> (forall p k, prime p -> N <> p ^ k)%nat ->\n    let n := shor_output_nqs N in\n    let k := modmult_nqs N in\n    let distr := shor_joint_distr N in\n    let f1 a := leads_to_factor N a in\n    let f2 a x := (OF_post a N (fst k x) n =? ord a N) ||\n                  negb (Nat.gcd a N =? 1) in\n    pr_outcome_sum distr\n      (fun z => let x := fst (n + k) z in\n             let y := snd (n + k) z in\n             f1 x && f2 x y)\n      >= (1 / 2) * (κ / INR (Nat.log2 N)^4).\nProof.\n  intros.\n  assert (H1N : (1 < N)%nat).\n  { destruct N. inversion H0. lia.\n    destruct N. destruct (infinitely_many_primes 1%nat) as [p [Hp1 Hp2]].\n    specialize (H1 p O Hp2). simpl in H1. lia. lia.\n  }\n  assert (ILog : (1 <= Nat.log2 N)%nat).\n  { specialize (Nat.log2_pos N) as G. lia.\n  }\n  specialize (κn4in01 (Nat.log2 N) ILog) as G.\n  apply pr_outcome_sum_join_geq.\n  apply distribution_uniform.\n  apply H1N.\n  lra.\n  apply shor_factoring_succeeds; auto.\n  intros i Hi.\n  split.\n  apply length_apply_u.\n  subst f2.\n  assert (Hdist : distribution (apply_u (UnitarySem.uc_eval (to_base_ucom (n + k) (shor_circuit i N))))).\n  { apply distribution_apply_u.\n    apply uc_eval_unitary.\n    apply uc_well_typed_shor_circuit.\n    rewrite length_uniform in Hi.\n    lia.\n    lia.\n  }\n  bdestruct (Nat.gcd i N =? 1).\n  eapply Rge_trans.\n  apply Rle_ge.\n  apply pr_outcome_sum_orb.\n  destruct Hdist as [Hdist _]; auto.\n  apply shor_body_returns_order.\n  split.\n  destruct i. simpl in H2. lia. lia.\n  rewrite length_uniform in Hi. lia. lia.\n  unfold coprime.\n  assumption.\n  rewrite pr_outcome_sum_true.\n  destruct Hdist as [_ Hdist].\n  subst n k.\n  unfold uc_eval.\n  unfold shor_nqs.\n  rewrite Hdist.\n  lra.\n  intros j Hj.\n  bdestruct (Nat.gcd i N =? 1).\n  easy.\n  simpl. rewrite orb_true_r. reflexivity.\nQed.\n\nLemma shor_body_succeeds_with_high_probability : forall N,\n    ~ (prime N) -> Nat.Odd N -> (forall p k, prime p -> N <> p ^ k)%nat ->\n    let n := shor_output_nqs N in\n    let k := modmult_nqs N in\n    let distr := shor_joint_distr N in\n    pr_outcome_sum distr (fun x => negb (isNone (process N x)))\n      >= (1 / 2) * (κ / INR (Nat.log2 N)^4).\nProof.\n  intros N HN1 HN2 HN3 n k distr.\n  assert (H1N : (1 < N)%nat).\n  { destruct N. inversion HN2. lia.\n    destruct N. destruct (infinitely_many_primes 1%nat) as [p [Hp1 Hp2]].\n    specialize (HN3 p O Hp2). simpl in HN3. lia. lia.\n  }\n  assert (Hdist: distribution distr).\n  subst distr. \n  apply distribution_join.\n  apply distribution_uniform.\n  lia.\n  intros i Hi.\n  apply distribution_apply_u.\n  apply uc_eval_unitary.\n  apply uc_well_typed_shor_circuit.\n  rewrite length_uniform in Hi.\n  lia.\n  lia.\n  apply Rle_ge.\n  eapply Rle_trans.\n  apply Rge_le.\n  apply shor_body_succeeds_with_high_probability'; auto.\n  apply pr_outcome_sum_implies.\n  destruct Hdist as [Hdist _]; auto.\n  simpl.\n  intros x H.\n  unfold process.\n  subst n k.\n  remember (fst (shor_output_nqs N + modmult_nqs N) x) as a.\n  remember (snd (shor_output_nqs N + modmult_nqs N) x) as y.\n  clear - H.\n  destruct (Nat.gcd a N =? 1) eqn:E; auto.\n  apply beq_nat_true in E.\n  apply andb_prop in H as [H1 H2].\n  simpl in H2. rewrite orb_false_r in H2.\n  apply beq_nat_true in H2. rewrite H2.\n  unfold factor.\n  unfold leads_to_factor in H1.\n  remember (a ^ (ord a N / 2) + 1)%nat as ap1.\n  remember (a ^ (ord a N / 2) - 1)%nat as am1.\n  replace ((1 <? Nat.gcd am1 N) && (Nat.gcd am1 N <? N)) with (nontrivgcd am1 N) by (unfold nontrivgcd; reflexivity).\n  replace ((1 <? Nat.gcd ap1 N) && (Nat.gcd ap1 N <? N)) with (nontrivgcd ap1 N) by (unfold nontrivgcd; reflexivity).\n  destruct (nontrivgcd am1 N). easy.\n  destruct (nontrivgcd ap1 N). easy.\n  simpl in H1. rewrite orb_false_r in H1.\n  unfold nontrivgcd, nontriv in H1. rewrite E in H1. simpl in H1. easy.\nQed.\n\nLemma shor_body_fails_with_low_probability : forall N,\n    ~ (prime N) -> Nat.Odd N -> (forall p k, prime p -> N <> p ^ k)%nat ->\n    let n := shor_output_nqs N in\n    let k := modmult_nqs N in\n    let distr := shor_joint_distr N in\n    pr_outcome_sum distr (fun x => isNone (process N x))\n      <= 1 - (1 / 2) * (κ / INR (Nat.log2 N)^4).\nProof.\n  intros.\n  assert (H1N : (1 < N)%nat).\n  { destruct N. inversion H0. lia.\n    destruct N. destruct (infinitely_many_primes 1%nat) as [p [Hp1 Hp2]].\n    specialize (H1 p O Hp2). simpl in H1. lia. lia.\n  }\n  rewrite pr_outcome_sum_negb.\n  specialize (shor_body_succeeds_with_high_probability N H H0 H1) as G.\n  assert (distribution distr).\n  { apply distribution_join.\n    apply distribution_uniform.\n    lia.\n    intros.\n    apply distribution_apply_u.\n    apply uc_eval_unitary.\n    apply uc_well_typed_shor_circuit.\n    rewrite length_uniform in H2. lia.\n    lia.\n  }\n  destruct H2. rewrite H3.\n  assert (forall r1 r2 r3, r2 >= r3 -> r1 - r2 <= r1 - r3)%R by (intros; lra).\n  apply H4. apply G.\nQed.\n\n(* For n iterations of end_to_end_shors, the probability of success is\n   1 - (1 - ((1 / 2) * (κ / INR (Nat.log2 N)^4))^n). *)\nLocal Opaque pow leads_to_factor.\nLemma end_to_end_shors_fails_with_low_probability : forall N niter r,\n  ~ (prime N) -> Nat.Odd N -> (forall p k, prime p -> N <> p ^ k)%nat ->\n  pr_Ps (fun rnds => isNone (end_to_end_shors N rnds) = true) niter r ->\n  (r <= (1 - (1 / 2) * (κ / INR (Nat.log2 N)^4))^niter)%R.\nProof.\n  intros N niter r HN1 HN2 HN3 H.\n  assert (H1N : (1 < N)%nat).\n  { destruct N. inversion HN2. lia.\n    destruct N. destruct (infinitely_many_primes 1%nat) as [p [Hp1 Hp2]].\n    specialize (HN3 p O Hp2). simpl in HN3. lia. lia.\n  }\n  unfold end_to_end_shors in H.\n  apply pr_Ps_same \n    with (Ps2:=fun rnds => isNone (iterate rnds (shor_body_alt N)) = true) in H.\n  specialize (shor_body_fails_with_low_probability N HN1 HN2 HN3) as Hbody.\n  apply pr_outcome_sum_leq_exists in Hbody.\n  destruct Hbody as [r0 [? ?]].\n  apply pr_iterate_None with (n := niter) in H1.\n  eapply pr_Ps_unique in H. \n  2: apply H1.\n  subst r.\n  remember (1 / 2 * (κ / INR (Nat.log2 N) ^ 4)) as β.\n  clear H1.\n  apply pow_incr.\n  assumption.\n  apply distribution_join.\n  apply distribution_uniform.\n  lia.\n  intros i Hi.\n  apply distribution_apply_u.\n  apply uc_eval_unitary.\n  apply uc_well_typed_shor_circuit.\n  rewrite length_uniform in Hi.\n  auto.\n  lia.\n  intros rnds Hrnds.\n  rewrite iterate_replace_body with (body':=shor_body_alt N); auto.\n  reflexivity.\n  intros.\n  apply shor_body_alt_same; auto.\nQed.\n", "meta": {"author": "inQWIRE", "repo": "SQIR", "sha": "7d2938bf63080e37d47059befa27a57f12cc099c", "save_path": "github-repos/coq/inQWIRE-SQIR", "path": "github-repos/coq/inQWIRE-SQIR/SQIR-7d2938bf63080e37d47059befa27a57f12cc099c/examples/shor/Main.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6619677256101665}}
{"text": "Require Import DecidabilityFacts SemiDecidabilityFacts.\nRequire Cantor.\nRequire Import FinTypesDef.\n\nLocal Notation \"'if!' x 'is' p 'then' a 'else' b\" := (match x with p => a | _ => b end) (at level 0, p pattern).\n\nLemma enumerable_semi_decidable {X} {p : X -> Prop} :\n  discrete X -> enumerable p -> semi_decidable p.\nProof.\n  unfold enumerable, enumerator.\n  intros [d Hd] [f Hf].\n  exists (fun x n => if! f n is Some y then d (x,y) else false).\n  intros x. rewrite Hf. split.\n  - intros [n Hn]. exists n.\n    rewrite Hn. now eapply Hd.\n  - intros [n Hn]. exists n.\n    destruct (f n); inversion Hn.\n    eapply Hd in Hn. now subst.\nQed.\n\nDefinition enumerator__T' X f := forall x : X, exists n : nat, f n = Some x.\nNotation enumerator__T f X := (enumerator__T' X f).\nDefinition enumerable__T X := exists f : nat -> option X, enumerator__T f X.\n\nLemma semi_decider_enumerator {X} {p : X -> Prop} {e f} :\n  enumerator__T e X -> semi_decider f p -> {g | enumerator g p}.\nProof.\n  unfold semi_decider. intros He Hf.\n  exists (fun p => let (n, m) := Cantor.of_nat p in\n           if! e n is Some x then if f x m then Some x else None else None).\n  intros x. rewrite Hf. split.\n  - intros [n Hn]. destruct (He x) as [m Hm].\n    exists (Cantor.to_nat (m,n)). now rewrite Cantor.cancel_of_to, Hm, Hn.\n  - intros [mn Hmn]. destruct (Cantor.of_nat mn) as (m, n).\n    destruct (e m) as [x'|]; try congruence.\n    destruct (f x' n) eqn:E; inversion Hmn. subst.\n    exists n. exact E.\nQed.\n\nLemma semi_decidable_enumerable {X} {p : X -> Prop} :\n  enumerable__T X -> semi_decidable p -> enumerable p.\nProof.\n  intros [e He] [f Hf].\n  destruct (semi_decider_enumerator He Hf) as [g Hg].\n  now exists g.\nQed.\n\nTheorem dec_count_enum {X} {p : X -> Prop} :\n  decidable p -> enumerable__T X -> enumerable p.\nProof.\n  intros ? % decidable_semi_decidable ?.\n  now eapply semi_decidable_enumerable.\nQed.\n\nTheorem dec_count_enum' X (p : X -> Prop) :\n  decidable p -> enumerable__T X -> enumerable (fun x => ~ p x).\nProof.\n  intros ? % dec_compl ?. eapply dec_count_enum; eauto.\nQed.\n\nLemma enumerable_enumerable_T X :\n  enumerable (fun _ : X => True) <-> enumerable__T X.\nProof.\n  split.\n  - intros [e He]. exists e. intros x. now eapply He.\n  - intros [c Hc]. exists c. intros x. split; eauto.\nQed.\n\n(* Type enumerability facts  *)\n\nDefinition nat_enum (n : nat) := Some n.\nLemma enumerator__T_nat :\n  enumerator__T nat_enum nat.\nProof.\n  intros n. cbv. eauto.\nQed.\n\nDefinition unit_enum (n : nat) := Some tt.\nLemma enumerator__T_unit :\n  enumerator__T unit_enum unit.\nProof.\n  intros []. cbv. now exists 0.\nQed. \n\nDefinition bool_enum (n : nat) := Some (if! n is 0 then true else false).\nLemma enumerator__T_bool :\n  enumerator__T bool_enum bool.\nProof.\n  intros []. cbv.\n  - now exists 0.\n  - now exists 1.\nQed.\n\nDefinition prod_enum {X Y} (f1 : nat -> option X) (f2 : nat -> option Y) n : option (X * Y) :=\n  let (n, m) := Cantor.of_nat n in\n  if! (f1 n, f2 m) is (Some x, Some y) then Some (x, y) else None.\nLemma enumerator__T_prod {X Y} f1 f2 :\n  enumerator__T f1 X -> enumerator__T f2 Y ->\n  enumerator__T (prod_enum f1 f2) (X * Y).\nProof.\n  intros H1 H2 (x, y).\n  destruct (H1 x) as [n1 Hn1], (H2 y) as [n2 Hn2].\n  exists (Cantor.to_nat (n1, n2)). unfold prod_enum.\n  now rewrite Cantor.cancel_of_to, Hn1, Hn2.\nQed.\n\nDefinition option_enum {X} (f : nat -> option X) n :=\n  match n with 0 => Some None | S n => Some (f n) end.\nLemma enumerator__T_option {X} f :\n  enumerator__T f X -> enumerator__T (option_enum f) (option X).\nProof.\n  intros H [x | ].\n  - destruct (H x) as [n Hn]. exists (S n). cbn. now rewrite Hn.\n  - exists 0. reflexivity.\nQed.\n\nDefinition sigT_enum {X: Type} {P : X -> Type}\n  (f : nat -> option X) (fP : forall x, nat -> option (P x)) (n : nat) : \n    option {x : X & P x} :=\n  let (nx, nP) := Cantor.of_nat n in\n  match f nx with\n  | Some x =>\n    match fP x nP with\n    | Some y => Some (existT P x y)\n    | _ => None\n    end\n  | None => None\n  end.\nLemma enumerator__T_sigT {X: Type} {P : X -> Type} f fP :\n  enumerator__T f X -> (forall x, enumerator__T (fP x) (P x)) ->\n  enumerator__T (sigT_enum f fP) {x : X & P x}.\nProof.\n  intros Hf HfP [x HPx].\n  destruct (Hf x) as [nx Hnx].\n  destruct (HfP x (HPx)) as [nP HnP].\n  exists (Cantor.to_nat (nx, nP)).\n  unfold sigT_enum.\n  now rewrite !Cantor.cancel_of_to, Hnx, HnP.\nQed.\n\nDefinition sigT2_enum {X: Type} {P : X -> Type} {Q : X -> Type}\n  (f : nat -> option X) (fP : forall x, nat -> option (P x)) (fQ : forall x, nat -> option (Q x)) (n : nat) : \n    option {x : X & P x & Q x} :=\n  let (nx, m) := Cantor.of_nat n in\n  let (nP, nQ) := Cantor.of_nat m in\n  match f nx with\n  | Some x =>\n    match fP x nP, fQ x nQ with\n    | Some y, Some z => Some (existT2 P Q x y z)\n    | _, _ => None\n    end\n  | None => None\n  end.\nLemma enumerator__T_sigT2 {X: Type} {P : X -> Type} {Q : X -> Type} f fP fQ :\n  enumerator__T f X -> (forall x, enumerator__T (fP x) (P x)) -> (forall x, enumerator__T (fQ x) (Q x)) ->\n  enumerator__T (sigT2_enum f fP fQ) {x : X & P x & Q x}.\nProof.\n  intros Hf HfP HfQ [x HPx HQx].\n  destruct (Hf x) as [nx Hnx].\n  destruct (HfP x (HPx)) as [nP HnP].\n  destruct (HfQ x (HQx)) as [nQ HnQ].\n  exists (Cantor.to_nat (nx, Cantor.to_nat (nP, nQ))).\n  unfold sigT2_enum.\n  now rewrite !Cantor.cancel_of_to, Hnx, HnP, HnQ.\nQed.\n\nRequire Import List.\n\nDefinition finType_enum {X: finType} (n : nat) : option X :=\n  nth_error (@enum _ (class X)) n.\nLemma enumerator__T_finType {X: finType} :\n  enumerator__T finType_enum X.\nProof.\n  intros x.\n  assert (H := (@enum_ok _ (class X)) x).\n  unfold finType_enum. induction enum as [|y L IH].\n  - easy.\n  - cbn in H. destruct (Dec (x = y)) as [->|H'].\n    + now exists 0.\n    + destruct (IH H) as [n Hn]. now exists (S n).\nQed.\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\nDefinition Fin_enum {k: nat} (n : nat) : option (Fin.t k) :=\n  nth_error (all_fins k) n.\nLemma enumerator__T_Fin {k: nat} :\n  enumerator__T Fin_enum (Fin.t k).\nProof.\n  intros t. exists (proj1_sig (Fin.to_nat t)).\n  unfold Fin_enum. induction t as [n|n t IH].\n  { reflexivity. }\n  cbn. destruct (Fin.to_nat t) as [t' H']. cbn in *.\n  now rewrite nth_error_map, IH.\nQed.\n\nOpaque Cantor.to_nat Cantor.of_nat.\n\nFixpoint Vector_enum {X: Type} {k: nat} (f : nat -> option X) (n : nat) : option (Vector.t X k) :=\n  match k return option (Vector.t X k) with\n  | 0 => Some (@Vector.nil X)\n  | S k' => \n    let (nx, m) := Cantor.of_nat n in\n    match f nx with\n    | Some x =>\n      match (@Vector_enum X k' f m) with\n      | Some v => Some (@Vector.cons X x k' v)\n      | _ => None\n      end\n    | None => None\n    end\n  end.\nLemma enumerator__T_Vector {X: Type} {k: nat} (f : nat -> option X) :\n  enumerator__T f X -> enumerator__T (Vector_enum f) (Vector.t X k).\nProof.\n  intros Hf. induction k as [|k IH].\n  { intros t. pattern t. apply (Vector.case0). now exists 0. }\n  intros t. rewrite (Vector.eta t).\n  destruct (Hf (VectorDef.hd t)) as [nx Hnx].\n  destruct (IH (VectorDef.tl t)) as [m Hm].\n  exists (Cantor.to_nat (nx, m)).\n  cbn. now rewrite Cantor.cancel_of_to, Hnx, Hm.\nQed.\n\nExisting Class enumerator__T'.\n(* Existing Class enumerable__T. *)\n\nLemma enumerator_enumerable {X} {f} :\n  enumerator__T f X -> enumerable__T X.\nProof.\n  intros H. exists f. eapply H.\nQed.\n#[export] Hint Resolve enumerator_enumerable : core.\n\n#[global] Existing Instance enumerator__T_prod.\n#[global] Existing Instance enumerator__T_option.\n#[global] Existing Instance enumerator__T_bool.\n#[global] Existing Instance enumerator__T_nat.\n#[global] Existing Instance enumerator__T_sigT.\n#[global] Existing Instance enumerator__T_sigT2.\n#[global] Existing Instance enumerator__T_finType.\n#[global] Existing Instance enumerator__T_finType.\n#[global] Existing Instance enumerator__T_Fin.\n#[global] Existing Instance enumerator__T_Vector.\n", "meta": {"author": "ianshil", "repo": "FO_Bi_Int", "sha": "f2be82e6baa29f87066c04f5ae011ab71fd77311", "save_path": "github-repos/coq/ianshil-FO_Bi_Int", "path": "github-repos/coq/ianshil-FO_Bi_Int/FO_Bi_Int-f2be82e6baa29f87066c04f5ae011ab71fd77311/Enumerability/EnumerabilityFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6619415289011381}}
{"text": "(** * Generation of Hoare proof obligations in partial correctness\n\n This file is part of the \"Tutorial on Hoare Logic\".\n For an introduction to this Coq library,\n see README #or <a href=index.html>index.html</a>#.\n\n This file gives a syntactic definition of the weakest liberal precondition [wlp]\n introduced in #<a href=hoarelogicsemantics.html>#[hoarelogicsemantics]#</a>#.\n*)\n\nGlobal Set Asymmetric Patterns.\nSet Implicit Arguments.\nRequire Export hoarelogicsemantics.\n\nModule PartialHoareLogic (HD: HoareLogicDefs).\n\nExport HD.\nModule HLD:=HD.\n\nDefinition sem_wp := wlp.\n\n(** * Syntactic definition of the weakest liberal precondition.\n\n In the following, we show that this definition is logically \n equivalent to [wlp].\n *)\nFixpoint synt_wp (prog: ImpProg) : Pred -> Pred \n := fun post e =>\n  match prog with\n  | Iskip => post e\n  | (Iset A x expr) => post (E.upd x (E.eval expr e) e)\n  | (Iif cond p1 p2) =>\n          ((E.eval cond e)=true -> (synt_wp p1 post e))\n       /\\ ((E.eval cond e)=false -> (synt_wp p2 post e))\n  | (Iseq p1 p2) => synt_wp p1 (synt_wp p2 post) e\n  | (Iwhile cond p) =>  \n        exists inv:Pred, \n             (inv e)\n          /\\ (forall e', (inv e') \n                  -> (E.eval cond e')=false -> (post e'))\n          /\\ (forall e', (inv e') \n                  -> (E.eval cond e')=true -> (synt_wp p inv e'))\n  end.\n\n(** This property is also trivially satisfied by [wlp]. \n    We need it here to prove the soundness.\n*)\nLemma synt_wp_monotonic: \n  forall (p: ImpProg) (post1 post2: Pred),\n   (post1 |= post2) -> (synt_wp p post1) |= (synt_wp p post2).\nProof.\n  induction p; simpl; firstorder eauto with hoare.\nQed.\n\nHint Resolve synt_wp_monotonic: hoare.\n\n(** * Soundness\n  \n    The proof of soundness proceeds by induction over the derivation\n    [exec ... prog ...] in implicit hypothesis induced by [wlp] definition.\n\n    Please, notice that coq performs the [exec_Iwhile] case alone (that's where \n    monotonicity is used). Unfortunately, the case [exec_Iif] which seems\n    trivial to a human is not discharged by Coq.\n*)\nLemma wp_sound: forall prog post, synt_wp prog post |= prog{=post=}.\nProof.\n intros prog post e H0 e' H; generalize post H0; clear H0 post.\n elim H; clear H e' e prog; simpl; try ((firstorder eauto 20 with hoare); fail).\n (** - case [exec_Iif] *)\n intros e cond p1 p2 e'.\n case (E.eval cond e); simpl; firstorder auto.\nQed.\n\n(** * Completeness\n \n    The proof of completeness proceeds by induction over [prog] syntax.\n\n    Please, notice that coq performs this proof almost alone. The only\n    hint given here is the invariant.\n*)\nLemma wp_complete: forall prog post, prog{=post=} |= (synt_wp prog post).\nProof.\n unfold wlp; intros prog; elim prog; clear prog; simpl;\n try ((firstorder auto with hoare); fail).\n (** - case [Iseq] *)\n eauto with hoare.\n (** - case [Iwhile]: I provide the invariant below *)\n  intros.\n  constructor 1 with (x:=wlp (Iwhile cond p) post).\n  unfold wlp; intuition eauto 20 with hoare.\nQed.\n\n(** * Combining the previous results with transitivity of [ |= ] *)\n\nHint Resolve wp_complete wp_sound: hoare.\n\nTheorem soundness: forall pre p post, pre |= (synt_wp p post) -> pre |= p {=post=}.\nProof.\n auto with hoare.\nQed.\n\nTheorem completeness: forall pre p post, pre |= p {=post=} -> pre |= (synt_wp p post).\nProof.\n  intuition auto with hoare.\nQed.\n\n\nEnd PartialHoareLogic.\n\n(** \"Tutorial on Hoare Logic\" Library. Copyright 2007 Sylvain Boulme.\n\nThis file is distributed under the terms of the \n \"GNU LESSER GENERAL PUBLIC LICENSE\" version 3.  \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/hoare-tut/partialhoarelogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6619415264219215}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nFrom LCAC Require Import Relations_ext seq_ext_base ssrnat_ext seq_ext.\nRequire FunInd.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nInductive term : Set := var of nat | app of term & term | abs of term.\n\nCoercion var : nat >-> term.\n\nFixpoint eqterm t1 t2 :=\n  match t1, t2 with\n    | var n, var m => n == m\n    | app t1l t1r, app t2l t2r => eqterm t1l t2l && eqterm t1r t2r\n    | abs t1, abs t2 => eqterm t1 t2\n    | _, _ => false\n  end.\n\nLemma eqtermP : Equality.axiom eqterm.\nProof.\nmove => t1 t2; apply: (iffP idP) => [| <-]; last by elim: t1 => //= t1l ->.\nby elim: t1 t2 => [n | t1l IH t1r IH' | t1 IH]\n  [// m /eqP -> | //= t2l t2r /andP [] /IH -> /IH' -> | // t2 /IH ->].\nDefined.\n\nCanonical term_eqMixin := EqMixin eqtermP.\nCanonical term_eqType := Eval hnf in EqType term term_eqMixin.\n\nFixpoint shift d c t : term :=\n  match t with\n    | var n => var (if c <= n then n + d else n)\n    | app t1 t2 => app (shift d c t1) (shift d c t2)\n    | abs t1 => abs (shift d c.+1 t1)\n  end.\n\nNotation substitutev ts m n :=\n  (shift n 0 (nth (var (m - n - size ts)) ts (m - n))) (only parsing).\n\nFixpoint substitute n ts t : term :=\n  match t with\n    | var m => if n <= m then substitutev ts m n else m\n    | app t1 t2 => app (substitute n ts t1) (substitute n ts t2)\n    | abs t' => abs (substitute n.+1 ts t')\n  end.\n\nReserved Notation \"t ->b1 t'\" (at level 70, no associativity).\n\nInductive betared1 : relation term :=\n  | betared1beta t1 t2     : app (abs t1) t2 ->b1 substitute 0 [:: t2] t1\n  | betared1appl t1 t1' t2 : t1 ->b1 t1' -> app t1 t2 ->b1 app t1' t2\n  | betared1appr t1 t2 t2' : t2 ->b1 t2' -> app t1 t2 ->b1 app t1 t2'\n  | betared1abs t t'       : t ->b1 t' -> abs t ->b1 abs t'\n  where \"t ->b1 t'\" := (betared1 t t').\n\nNotation betared := [* betared1].\nInfix \"->b\" := betared (at level 70, no associativity).\n\nHint Constructors betared1.\n\nLemma shiftzero n t : shift 0 n t = t.\nProof. by elim: t n; congruence' => v n; rewrite addn0 if_same. Qed.\n\nLemma shift_add d d' c c' t :\n  c <= c' <= c + d -> shift d' c' (shift d c t) = shift (d' + d) c t.\nProof. case/andP; do 2 elimleq; elim: t c; congruence' => *; elimif_omega. Qed.\n\nLemma shift_shift_distr d c d' c' t :\n  c' <= c -> shift d' c' (shift d c t) = shift d (d' + c) (shift d' c' t).\nProof. elimleq; elim: t c'; congruence' => *; elimif_omega. Qed.\n\nLemma shift_subst_distr n d c ts t :\n  c <= n -> shift d c (substitute n ts t) = substitute (d + n) ts (shift d c t).\nProof.\nby elimleq; elim: t c; congruence' => v c; elimif;\n  rewrite shift_add //= add0n leq_addr.\nQed.\n\nLemma subst_shift_distr n d c ts t :\n  n <= c ->\n  shift d c (substitute n ts t) =\n  substitute n (map (shift d (c - n)) ts) (shift d (size ts + c) t).\nProof.\nelimleq; elim: t n; congruence' => v n; elimif.\n- rewrite !nth_default ?size_map /=; elimif_omega.\n- rewrite -shift_shift_distr // nth_map' /=;\n    congr shift; apply nth_equal; rewrite size_map; elimif_omega.\nQed.\n\n(*\nLemma subst_shift_distr' n d c ts t :\n  shift d (n + c) (substitute n ts t) =\n  substitute n [seq shift d c i | i <- ts] (shift d (size ts + (n + c)) t).\nProof. by rewrite subst_shift_distr ?addKn // leq_addr. Qed.\n*)\n\nLemma subst_shift_cancel n d c ts t :\n  c <= n -> size ts + n <= d + c ->\n  substitute n ts (shift d c t) = shift (d - size ts) c t.\nProof.\ndo 2 elimleq; elim: t c; congruence' => v c;\n  elimif; rewrite nth_default /=; elimif_omega.\nQed.\n\nLemma subst_subst_distr n m xs ys t :\n  m <= n ->\n  substitute n xs (substitute m ys t) =\n  substitute m (map (substitute (n - m) xs) ys) (substitute (size ys + n) xs t).\nProof.\nelimleq; elim: t m; congruence' => v m; elimif.\n- rewrite nth_default ?(@subst_shift_cancel m) // ?size_map /=; elimif_omega.\n- rewrite -shift_subst_distr // nth_map' /=;\n    congr shift; apply nth_equal; rewrite size_map; elimif_omega.\nQed.\n\nLemma subst_app n xs ys t :\n  substitute n xs (substitute (size xs + n) ys t) = substitute n (xs ++ ys) t.\nProof.\nelim: t n; congruence' => v n; rewrite nth_cat size_cat;\n  elimif_omega; rewrite subst_shift_cancel; elimif_omega.\nQed.\n\nLemma subst_nil n t : substitute n [::] t = t.\nProof. elim: t n; congruence' => m n; rewrite nth_nil /=; elimif_omega. Qed.\n\nLemma subst_betared1 n ts t t' :\n  t ->b1 t' -> substitute n ts t ->b1 substitute n ts t'.\nProof.\nmove => H; elim/betared1_ind: t t' / H n => /=; auto => t t' n.\nby rewrite subst_subst_distr //= add1n subn0.\nQed.\n\n(* small example for PPL2015 paper *)\nLemma shift_betared t t' d c : t ->b1 t' -> shift d c t ->b1 shift d c t'.\nProof.\nmove => H; elim/betared1_ind: t t' / H d c => /=; auto => t1 t2 d c.\nrewrite subst_shift_distr //= add1n subn0; auto.\nQed.\n\nModule confluence_proof.\n\nReserved Notation \"t ->bp t'\" (at level 70, no associativity).\n\nInductive parred : relation term :=\n  | parredvar n : var n ->bp var n\n  | parredapp t1 t1' t2 t2' :\n    t1 ->bp t1' -> t2 ->bp t2' -> app t1 t2 ->bp app t1' t2'\n  | parredabs t t' : t ->bp t' -> abs t ->bp abs t'\n  | parredbeta t1 t1' t2 t2' :\n    t1 ->bp t1' -> t2 ->bp t2' -> app (abs t1) t2 ->bp substitute 0 [:: t2'] t1'\n  where \"t ->bp t'\" := (parred t t').\n\nHint Constructors parred.\n\nFunction reduce_all_redex t : term :=\n  match t with\n    | var _ => t\n    | app (abs t1) t2 =>\n      substitute 0 [:: reduce_all_redex t2] (reduce_all_redex t1)\n    | app t1 t2 => app (reduce_all_redex t1) (reduce_all_redex t2)\n    | abs t' => abs (reduce_all_redex t')\n  end.\n\nLemma parred_refl t : parred t t.\nProof. elim: t; auto. Qed.\n\nLemma betaredappl t1 t1' t2 : t1 ->b t1' -> app t1 t2 ->b app t1' t2.\nProof. apply (rtc_map' (fun x y => @betared1appl x y t2)). Qed.\n\nLemma betaredappr t1 t2 t2' : t2 ->b t2' -> app t1 t2 ->b app t1 t2'.\nProof. apply (rtc_map' (@betared1appr t1)). Qed.\n\nLemma betaredabs t t' : t ->b t' -> abs t ->b abs t'.\nProof. apply (rtc_map' betared1abs). Qed.\n\nHint Resolve parred_refl betaredappl betaredappr betaredabs.\n\nLemma betared1_in_parred : inclusion betared1 parred.\nProof. apply betared1_ind; auto. Qed.\n\nLemma parred_in_betared : inclusion parred betared.\nProof.\napply parred_ind; auto => t1 t1' t2 t2' H H0 H1 H2.\n- apply rtc_trans with (app t1' t2); auto.\n- apply rtc_trans with (app (abs t1') t2); auto.\n  apply rtc_trans with (app (abs t1') t2'); auto.\n  by apply rtc_step.\nQed.\n\nLemma shift_parred t t' d c : t ->bp t' -> shift d c t ->bp shift d c t'.\nProof.\nmove => H; elim/parred_ind: t t' / H d c => //=;\n  auto => t1 t1' t2 t2' H H0 H1 H2 d c.\nrewrite subst_shift_distr //= add1n subn0; auto.\nQed.\n\nLemma subst_parred n ps t t' :\n  Forall (prod_curry parred) ps -> t ->bp t' ->\n  substitute n [seq fst p | p <- ps] t ->bp\n  substitute n [seq snd p | p <- ps] t'.\nProof.\nmove => H H0; elim/parred_ind: t t' / H0 n => /=; auto.\n- move => v n; elimif; rewrite !size_map; apply shift_parred.\n  elim: ps v H => //= [[t t']] ps IH [| v] [] //= H H0.\n  by rewrite subSS; apply IH.\n- move => t1 t1' t2 t2' H0 H1 H2 H3 n.\n  by rewrite subst_subst_distr //= add1n subn0; auto.\nQed.\n\nLemma parred_all_lemma t t' : t ->bp t' -> t' ->bp reduce_all_redex t.\nProof with auto.\nelim/reduce_all_redex_ind: {t}_ t'.\n- by move => t n H t' H0; inversion H0; subst.\n- move => _ t1 t2 _ H H0 t' H1; inversion H1; subst.\n  + inversion H4; subst...\n  + apply (@subst_parred 0 [:: (t2', reduce_all_redex t2)]) => /=...\n- move => _ t1 t2 _ H H0 H1 t' H2; inversion H2; subst => //...\n- move => _ t1 _ H t2 H0; inversion H0; subst...\nQed.\n\nLemma parred_confluent : confluent parred.\nProof.\nby move => t1 t2 t3 H H0; exists (reduce_all_redex t1); apply parred_all_lemma.\nQed.\n\nTheorem betared_confluent : confluent betared.\nProof.\napply (rtc_confluent' betared1_in_parred parred_in_betared parred_confluent).\nQed.\n\nEnd confluence_proof.\n", "meta": {"author": "pi8027", "repo": "lambda-calculus", "sha": "a5c58079b944ec8f98d8a3fabc2c829bb32a1de7", "save_path": "github-repos/coq/pi8027-lambda-calculus", "path": "github-repos/coq/pi8027-lambda-calculus/lambda-calculus-a5c58079b944ec8f98d8a3fabc2c829bb32a1de7/coq/deBruijn/Untyped.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012104, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6619415161663472}}
{"text": "Require Export H1_4.\nRequire Export Reals.\n\nModule Section1_5.\n\nOpen Scope R_scope.\n\n(* 数环 *)\nDefinition Ring (S : Ensemble R) := forall (a b : R),\n  S ≠ Φ R -> a ∈ S -> b ∈ S -> \n  ((a+b) ∈ S /\\ (a-b) ∈ S /\\ (a*b) ∈ S).\n\n(* 数域 *)\nDefinition Field (F : Ensemble R) := Ring F /\\ \n  (exists c, c ≠ 0 /\\ c ∈ F) /\\ \n  (forall a b, a ∈ F -> b ∈ F -> b ≠ 0 -> (a/b) ∈ F).\n\n(* 实数下的有理数域 *)\nDefinition Q2R := \\{ λ u, exists (c1 c2 : Z), \n  (IZR c2) ≠ 0/\\u = (IZR c1)/(IZR c2) \\}.\n\n(* 定理1.5.1 *)\nTheorem Theorem1_5_1 : forall (F : Ensemble R), Field F -> Q2R ⊂ F.\nProof.\n  intros. red in H. destruct H, H0. destruct H0 as [a H0]. destruct H0.\n  generalize (H1 a a); intros. apply H3 in H2; auto.\n  assert (a / a = 1). { field; auto. } rewrite H4 in H2; clear H4.\n  assert (F ≠ Φ R). { intro. rewrite H4 in H2. \n  apply -> AxiomII in H2; simpl in H2. apply H2; auto. } red in H.\n  (* 所有的正整数属于F *)\n  assert (forall x : Z, (0 <= x)%Z -> (IZR x) ∈ F). {\n  apply Z_of_nat_prop. intros. rewrite <- INR_IZR_INZ.\n   induction n.\n  - simpl. generalize (H 1 1); intros. apply H5 in H4; auto. clear H5.\n    destruct H4, H5. assert (1-1 = 0). { field. } rewrite H7 in H5; auto.\n  - rewrite S_INR. generalize (H (INR n) 1); intros. apply H5 in H4; auto.\n    clear H5. destruct H4, H5. auto. }\n  (* 所有的整数属于F *)\n  assert (forall x : Z, (IZR x) ∈ F).\n  { intros. \n    generalize (classic (0 <= x)%Z); intros; destruct H6.\n    - apply H5 in H6; auto.\n    - apply Znot_le_gt in H6. assert (0 <= -x)%Z. {\n      Z.swap_greater. lia. } apply H5 in H7.\n      generalize (H 0 (IZR (- x))); intros. apply H8 in H4; auto.\n      + clear H8. destruct H4, H8. rewrite Z_R_minus in H8. simpl in H8.\n        assert (- - x = x)%Z. { ring. } rewrite H10 in H8; auto. \n      + generalize (H 1 1); intros. apply H9 in H4; clear H9; auto.\n        destruct H4, H9. assert (1-1=0). { field. } rewrite <- H11; auto. }\n  red; intros. apply -> AxiomII in H7; simpl in H7. destruct H7, H7.\n  assert (IZR x ∈ F /\\ IZR x0 ∈ F). { \n  generalize (H6 x); generalize (H6 x0); intros. split; auto. }\n  destruct H7. rewrite H9. eapply H1; eauto.\nQed.\n\nEnd Section1_5.\nExport Section1_5.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "LIUYANG2021", "repo": "higher_algebra", "sha": "9f2086d548c29c5601bf7a0cec75d4cbbfffdb3a", "save_path": "github-repos/coq/LIUYANG2021-higher_algebra", "path": "github-repos/coq/LIUYANG2021-higher_algebra/higher_algebra-9f2086d548c29c5601bf7a0cec75d4cbbfffdb3a/H1_5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6617433977278027}}
{"text": "Require Import Base.\nRequire Import SemanticsBase.\n\nInductive 𝔱sem : 𝔱 -> 𝔱 -> Prop :=\n  | 𝔱sem_prj1 : forall t1 t2, 𝔱sem (𝔱prj 1 (𝔱pair t1 t2)) t1\n  | 𝔱sem_prj2 : forall t1 t2, 𝔱sem (𝔱prj 2 (𝔱pair t1 t2)) t2\n  | 𝔱sem_app : forall x t t', 𝔱sem (𝔱app (𝔱lambda x t) t') (𝔱subst t x t')\n  | 𝔱sem_case1 : forall v x1 x2 t1 t2, 𝔱sem (𝔱case (𝔱inj 1 v) x1 t1 x2 t2) (𝔱subst t1 x1 v)\n  | 𝔱sem_case2 : forall v x1 x2 t1 t2, 𝔱sem (𝔱case (𝔱inj 2 v) x1 t1 x2 t2) (𝔱subst t2 x2 v).\n\nInductive 𝔢sem : 𝔢 -> 𝔢 -> Prop :=\n  | 𝔢sem_let_hole : forall e, 𝔢sem (𝔢holelet (𝔢hole) e) e\n  | 𝔢sem_let : forall x1 x2 e1 e2 e, x1 <> x2 -> 𝔢sem (𝔢let x1 x2 (𝔢pair e1 e2) e) (𝔢subst (𝔢subst e x1 e1) x2 e2)\n  | 𝔢sem_app : forall x e1 e2, 𝔢sem (𝔢app (𝔢lambda x e1) e2) (𝔢subst e1 x e2)\n  | 𝔢sem_bind : forall x e1 e2, 𝔢sem (𝔢bind x (𝔢return e1) e2) (𝔢subst e2 x e1)\n  | 𝔢sem_force_suspend : forall e, 𝔢sem (𝔢force (𝔱suspend e)) e\n  | 𝔢sem_case1 : forall x1 x2 e1 e2 e, 𝔢sem (𝔢case (𝔢inj 1 e) x1 e1 x2 e2) (𝔢subst e1 x1 e)\n  | 𝔢sem_case2 : forall x1 x2 e1 e2 e, 𝔢sem (𝔢case (𝔢inj 2 e) x1 e1 x2 e2) (𝔢subst e2 x2 e).\n\n\n(*  | 𝔢sem_flor_let : forall v x e, 𝔢sem (𝔢florlet x (𝔢flor v) e) (𝔢subst e x v). *)", "meta": {"author": "aerabi", "repo": "lttt", "sha": "05c869f505f1759ffcd0ec9a0bd118f22ccddd84", "save_path": "github-repos/coq/aerabi-lttt", "path": "github-repos/coq/aerabi-lttt/lttt-05c869f505f1759ffcd0ec9a0bd118f22ccddd84/src/OperationalSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909757, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6616742922832328}}
{"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 type of setoids and type of setoid morphisms\n  - identity and composition of setoid morphisms\n\n*)\n\nRequire Import Misc.Unicode.\nRequire Import Morphisms.\nRequire Export SetoidClass.\n\nGeneralizable All Variables.\n(** * Setoid **)\n\n(*------------------------------------------------------------------------------\n  -- ＳＥＴＯＩＤ  ＤＥＦＩＮＩＴＩＯＮ\n  ----------------------------------------------------------------------------*)\n(** ** Setoid definiton **)\n\nModule Setoid.\n\n  Structure Setoid : Type := mkSetoid\n  { Carrier   :>  Type\n  ; Equiv     :   Carrier → Carrier → Prop\n  ; is_Equiv  :   Equivalence Equiv }.\n\n  Existing Instance is_Equiv.\n\n  Arguments Equiv {_} _ _.\n\n  Notation \"'Setoid.make' ⦃ 'Carrier' ≔ c ; 'Equiv' ≔ eq ⦄\" :=\n    (mkSetoid c eq _) (only parsing).\n\n  Program Definition eq_setoid (T : Type) : Setoid := Setoid.make  ⦃ Carrier  ≔ T\n                                                                   ; Equiv    ≔ eq ⦄.\n\n  Notation \"_≈_\"         := Equiv                    (only parsing).\n  Notation \"x ≈ y :> T\"  := (Equiv (s := T) x y)     (at level 70, y at next level, no associativity).\n  Notation \"x ≈ y\"       := (Equiv x y)              (at level 70, no associativity).\n  Notation \"x ≉ y\"       := (complement Equiv x y)   (at level 70, no associativity).\n\nEnd Setoid.\n\n\n(*------------------------------------------------------------------------------\n  -- ＳＥＴＯＩＤ  ＭＯＲＰＨＩＳＭ\n  ----------------------------------------------------------------------------*)\n(** ** Morphism between setoids **)\n\nModule Π.\n\n  Import Setoid.\n\n  Structure Π (From To : Setoid) : Type := mkΠ\n  { map         :>  From → To\n  ; map_proper  :   Proper (_≈_ ==> _≈_) map }.\n\n  Existing Instance map_proper.\n\n  Lemma cong From To (f : Π From To) : ∀ x y, x ≈ y → f x ≈ f y.\n  Proof.\n    intros x y eq_xy; now rewrite eq_xy.\n  Qed.\n\n  Program Definition setoid (From To : Setoid) : Setoid :=\n    Setoid.make  ⦃ Carrier  ≔ Π From To\n                 ; Equiv    ≔ λ f g ∙ ∀ x y, x ≈ y → f x ≈ g y ⦄.\n  Next Obligation.\n    constructor.\n    - (* Reflexivity *)\n      intros f x y eq_xy. now rewrite eq_xy.\n    - (* Symmetry *)\n      intros f g eq_fg x y eq_xy. rewrite eq_xy. symmetry. now apply eq_fg.\n    - (* Transitivity *)\n      intros f g h eq_fg eq_gh x y eq_xy. etransitivity; eauto.\n      now apply eq_gh.\n  Qed.\n\n  Notation \"[ A ⟶ B ]\" := (Π A B).\n\n  Notation make f := (@mkΠ _ _ f _) (only parsing).\n\n  Notation \"'λ' x .. y ↦ F\" := (make (λ x ∙ .. (λ y ∙ F) ..))\n    (at level 200, x binder, y binder, no associativity).\n\n  Program Definition id {A} : [A ⟶ A] := make (λ x ∙ x).\n  Next Obligation.\n    intros f g eq_fg. exact eq_fg.\n  Qed.\n\n  Program Definition compose {A B C} (g : [B ⟶ C]) (f : [A ⟶ B]) : [A ⟶ C] := make (λ x ∙ g (f x)).\n  Next Obligation.\n    intros x y eq_xy. rewrite eq_xy. reflexivity.\n  Qed.\n\nEnd Π.\n\nModule Π₂.\n\n  Import Setoid.\n\n  Structure Π₂ (A B C : Setoid) : Type := mkΠ₂\n  { map          :>  A → B → C\n  ; map_compose  :   Proper (_≈_ ==> _≈_ ==> _≈_) map }.\n\n  Existing Instance map_compose.\n\n  Lemma cong A B C (f : Π₂ A B C) : ∀ x x' y y', x ≈ x' → y ≈ y' → f x y ≈ f x' y'.\n  Proof.\n    intros x x' y y' eq_xx' eq_yy'; now rewrite eq_xx', eq_yy'.\n  Qed.\n\n  Notation \"[ A ⟶ B ⟶ C ]\" := (Π₂ A B C).\n\n  Notation make  f := (@mkΠ₂ _ _ _ f _) (only parsing).\n\n  Notation \"'λ' x .. y ↦₂ F\" := (make (λ x ∙ .. (λ y ∙ F) ..))\n    (at level 200, x binder, y binder, no associativity).\n\nEnd Π₂.\n\n(*----------------------------------------------------------------------------*)\n\nExport Setoid Π Π₂.\n", "meta": {"author": "rs-", "repo": "Triangles", "sha": "57f10cb6c627c331b2c6e7b344a34ae50838cc67", "save_path": "github-repos/coq/rs--Triangles", "path": "github-repos/coq/rs--Triangles/Triangles-57f10cb6c627c331b2c6e7b344a34ae50838cc67/Theory/SetoidType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.661652586009688}}
{"text": "Require Coq.Logic.Classical_Prop.\nRequire Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.euclidean_tactics.\nRequire Import ProofCheckingEuclid.lemma_altitudebisectsbase.\nRequire Import ProofCheckingEuclid.lemma_betweennotequal.\nRequire Import ProofCheckingEuclid.lemma_collinear_ABC_ABD_BCD.\nRequire Import ProofCheckingEuclid.lemma_collinearorder.\nRequire Import ProofCheckingEuclid.lemma_collinearright.\nRequire Import ProofCheckingEuclid.lemma_congruenceflip.\nRequire Import ProofCheckingEuclid.lemma_extension.\nRequire Import ProofCheckingEuclid.lemma_inequalitysymmetric.\nRequire Import ProofCheckingEuclid.lemma_midpointunique.\nRequire Import ProofCheckingEuclid.lemma_orderofpoints_ABC_BCD_ABD.\nRequire Import ProofCheckingEuclid.lemma_orderofpoints_ABC_BCD_ACD.\nRequire Import ProofCheckingEuclid.lemma_rightreverse.\nRequire Import ProofCheckingEuclid.lemma_s_midpoint.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_droppedperpendicularunique :\n\tforall A J M P,\n\tRightTriangle A M P ->\n\tRightTriangle A J P ->\n\tCol A M J ->\n\teq M J.\nProof.\n\tintros A J M P.\n\tintros RightTriangle_AMP.\n\tintros RightTriangle_AJP.\n\tintros Col_A_M_J.\n\n\tpose proof (lemma_collinearorder _ _ _ Col_A_M_J) as (_ & Col_M_J_A & _ & _ & Col_J_M_A).\n\n\tassert (~ neq M J) as eq_M_J.\n\t{\n\t\tintros neq_M_J.\n\n\t\tpose proof (lemma_inequalitysymmetric _ _ neq_M_J) as neq_J_M.\n\n\t\tpose proof (lemma_extension _ _ _ _ neq_M_J neq_M_J) as (E & BetS_M_J_E & _).\n\n\t\tpose proof (lemma_betweennotequal _ _ _ BetS_M_J_E) as (_ & _ & neq_M_E).\n\t\tpose proof (axiom_betweennesssymmetry _ _ _ BetS_M_J_E) as BetS_E_J_M.\n\n\t\tpose proof (lemma_extension _ _ _ _ neq_J_M neq_M_E) as (F & BetS_J_M_F & Cong_MF_ME).\n\n\t\tpose proof (lemma_orderofpoints_ABC_BCD_ABD _ _ _ _ BetS_E_J_M BetS_J_M_F) as BetS_E_J_F.\n\t\tpose proof (lemma_orderofpoints_ABC_BCD_ACD _ _ _ _ BetS_E_J_M BetS_J_M_F) as BetS_E_M_F.\n\t\tpose proof (axiom_betweennesssymmetry _ _ _ BetS_E_J_F) as BetS_F_J_E.\n\t\tpose proof (axiom_betweennesssymmetry _ _ _ BetS_E_M_F) as BetS_F_M_E.\n\t\tpose proof (lemma_betweennotequal _ _ _ BetS_E_J_F) as (neq_J_F & _ & _).\n\t\tpose proof (lemma_betweennotequal _ _ _ BetS_J_M_F) as (neq_M_F & _ & _).\n\t\tpose proof (lemma_inequalitysymmetric _ _ neq_J_F) as neq_F_J.\n\t\tpose proof (lemma_inequalitysymmetric _ _ neq_M_F) as neq_F_M.\n\n\t\tpose proof (lemma_congruenceflip _ _ _ _ Cong_MF_ME) as (_ & Cong_FM_ME & _ ).\n\n\t\tassert (Col J M F) as Col_J_M_F by (unfold Col; one_of_disjunct BetS_J_M_F).\n\t\tpose proof (lemma_collinearorder _ _ _ Col_J_M_F) as (Col_M_J_F & _ & _ & _ & _).\n\n\t\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_M_J_F Col_M_J_A neq_M_J) as Col_J_F_A.\n\t\tpose proof (lemma_collinearorder _ _ _ Col_J_F_A) as (_ & _ & Col_A_J_F & _ & _).\n\n\t\tpose proof (lemma_collinearright _ _ _ _ RightTriangle_AJP Col_A_J_F neq_F_J) as RightTriangle_FJP.\n\n\t\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_J_M_F Col_J_M_A neq_J_M) as Col_M_F_A.\n\t\tpose proof (lemma_collinearorder _ _ _ Col_M_F_A) as (_ & _ & Col_A_M_F & _ & _).\n\n\t\tpose proof (lemma_collinearright _ _ _ _ RightTriangle_AMP Col_A_M_F neq_F_M) as RightTriangle_FMP.\n\t\tpose proof (lemma_rightreverse _ _ _ _ RightTriangle_FMP BetS_F_M_E Cong_FM_ME) as Cong_FP_EP.\n\t\tpose proof (lemma_altitudebisectsbase _ _ _ _ BetS_F_J_E Cong_FP_EP RightTriangle_FJP) as Midpoint_F_J_E.\n\t\tpose proof (lemma_s_midpoint _ _ _ BetS_F_M_E Cong_FM_ME) as Midpoint_F_M_E.\n\t\tpose proof (lemma_midpointunique _ _ _ _ Midpoint_F_J_E Midpoint_F_M_E) as eq_J_M.\n\n\t\tcontradict eq_J_M.\n\t\texact neq_J_M.\n\t}\n\tapply Classical_Prop.NNPP in eq_M_J.\n\n\texact eq_M_J.\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_droppedperpendicularunique.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.6616480031035824}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nFrom adtind Require Import goal33.\n\nSet Printing Depth 1000.\nDefinition lfind_eval  x:=\nmult (qfac x (Succ Zero)) x.\n\nCompute lfind_eval  (Succ (Succ (Succ Zero))).\n\nCompute lfind_eval  (Succ (Succ (Succ Zero))).\n\nCompute lfind_eval  (Succ (Succ (Succ (Succ Zero)))).\n\nCompute lfind_eval  (Succ Zero).\n\nCompute lfind_eval  (Succ (Succ (Succ Zero))).\n\nCompute lfind_eval  (Zero).\n\nCompute lfind_eval  (Succ (Succ (Succ (Succ (Succ Zero))))).\n\nCompute lfind_eval  (Succ Zero).\n\nCompute lfind_eval  (Succ Zero).\n\nCompute lfind_eval  (Succ (Succ Zero)).\n\nCompute lfind_eval  (Zero).\n\nCompute lfind_eval  (Succ (Succ (Succ (Succ Zero)))).\n\nCompute lfind_eval  (Succ (Succ Zero)).\n\nCompute lfind_eval  (Zero).\n\nCompute lfind_eval  (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_qfac_mult_116_mult_assoc/lfind_eval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004187, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.661638187844168}}
{"text": "Section Evolution.\n  Variable St : Type.\n  Variable t : St -> St -> Type.\n  \n  CoInductive evolutionFrom : St -> Type :=\n  | evolve {s s'} : t s s' -> evolutionFrom s' -> evolutionFrom s.\n\n  Definition evolution := sigT evolutionFrom.\n\n  Fixpoint fastForward (e:evolution) (n:nat) {struct n} : evolution.\n    refine (match n with \n    | 0 => e \n    | S n' => let ' existT _ _ (evolve _ e') := e in \n             fastForward (existT _ _ e') n'\n    end).\n  Defined.\n\n  Section Property.\n    Variable P : St -> Prop.\n\n    CoInductive ForallStates : forall {s}, P s -> evolutionFrom s -> Prop :=\n    | evolveHolds s p s' p' t e : @ForallStates s p e -> @ForallStates s' p' (evolve t e).\n\n    Definition always e := exists p, ForallStates p (projT2 e).\n  \n    Definition eventually e := exists n, always (fastForward e n).\n  End Property.\nEnd Evolution.\n", "meta": {"author": "uwplse", "repo": "bagpipe", "sha": "67a38c4c6def7fb270a045b4afa668d22e293be7", "save_path": "github-repos/coq/uwplse-bagpipe", "path": "github-repos/coq/uwplse-bagpipe/bagpipe-67a38c4c6def7fb270a045b4afa668d22e293be7/src/bagpipe/coq/Main/Library/Evolution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896132, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6616381704880376}}
{"text": "(*\nChapter 9\nSimply Typed Lambda-Calculus\n*)\n\nRequire Import TLC.LibLN.\n\nInductive typ : Set :=\n  | t_arrow : typ -> typ -> typ\n  | t_bool  : typ.\n\nInductive exp : Set :=\n  | e_fvar : var -> exp\n  | e_bvar : nat -> exp\n  | e_abs : typ -> exp -> exp\n  | e_app : exp -> exp -> exp\n  | e_tru : exp\n  | e_fls : exp\n  | e_cond : exp -> exp -> exp -> exp.\n\nDefinition env := env typ.\n\nFixpoint subst_ee (x : var) (s t: exp) {struct t} : exp :=\n  match t with\n  | e_fvar y => If (y = x) then s else e_fvar y\n  | e_bvar i => e_bvar i\n  | e_abs T t1 => e_abs T (subst_ee x s t1)\n  | e_app t1 t2 => e_app (subst_ee x s t1) (subst_ee x s t2)\n  | e_tru => e_tru\n  | e_fls => e_fls\n  | e_cond t t1 t2 => e_cond (subst_ee x s t) (subst_ee x s t1) (subst_ee x s t2)\nend.\n\nFixpoint open_ee_rec (j : nat) (s t: exp) {struct t} : exp :=\n  match t with\n  | e_fvar y => e_fvar y\n  | e_bvar i => If (i = j) then s else e_bvar i\n  | e_abs T t1 => e_abs T (open_ee_rec (S j) s t1)\n  | e_app t1 t2 => e_app (open_ee_rec j s t1) (open_ee_rec j s t2)\n  | e_tru => e_tru\n  | e_fls => e_fls\n  | e_cond t t1 t2 => e_cond (open_ee_rec j s t) (open_ee_rec j s t1) (open_ee_rec j s t2)\nend.\n\nDefinition open_ee t u := open_ee_rec 0 u t.\n\n(** Notation for opening up binders with type or term variables *)\n\nNotation \"t 'open_ee_var' x\" := (open_ee t (e_fvar x)) (at level 67).\n\nInductive lc_exp : exp -> Prop :=\n  | lc_fvar : forall x,\n      lc_exp (e_fvar x)\n | lc_abs : forall (L:vars) (e:exp) T,\n      ( forall x , x \\notin L -> lc_exp (open_ee e (e_fvar x)))  ->\n     lc_exp (e_abs T e)\n | lc_app : forall (e1 e2:exp),\n     lc_exp e1 ->\n     lc_exp e2 ->\n     lc_exp (e_app e1 e2)\n | lc_tru : \n      lc_exp e_tru\n | lc_fls : \n      lc_exp e_fls\n | lc_cond : forall e e1 e2,\n      lc_exp e ->\n      lc_exp e1 ->\n      lc_exp e2 ->\n      lc_exp (e_cond e e1 e2).\n\nInductive value : exp -> Prop :=\n  | val_abs : forall T e,\n      value (e_abs T e)\n  | val_tru : value e_tru\n  | val_fls : value e_fls.\n\nInductive typing : env -> exp -> typ -> Prop :=\n  | typ_var : forall x E T,\n     ok E ->\n     binds x T E ->\n     typing E (e_fvar x) T\n  | typ_abs : forall (L:vars) (E:env) (T1 T2:typ) (e:exp),\n     ok E ->\n     (forall x, x \\notin L -> \n        typing (E & x ~ T1) (open_ee e (e_fvar x)) T2) ->\n     typing E (e_abs T1 e) (t_arrow T1 T2)\n  | typ_app : forall (E:env) (e1 e2: exp) (T1 T2:typ),\n      typing E e1 (t_arrow T1 T2) ->\n      typing E e2 T1 ->\n      typing E (e_app e1 e2) T2\n  | typ_tru : forall E,\n      ok E ->\n      typing E e_tru t_bool\n  | typ_fls : forall E,\n      ok E ->\n      typing E e_fls t_bool\n  | typ_cond : forall E e e1 e2 T,\n      typing E e t_bool ->\n      typing E e1 T ->\n      typing E e2 T ->\n      typing E (e_cond e e1 e2) T.\n\nInductive step : exp -> exp -> Prop :=\n  | step_appl : forall e1 e2 e1',\n      lc_exp e2 ->\n      step e1 e1' ->\n      step (e_app e1 e2) (e_app e1' e2)\n  | step_appr : forall e1 e2 e2',\n      value e1 ->\n      step e2 e2' ->\n      step (e_app e1 e2) (e_app e1 e2')\n | step_beta : forall (e:exp) (v:exp) T,\n     lc_exp (e_abs T e) ->\n     value v ->\n     step (e_app (e_abs T e) v) (open_ee e v)\n | step_cond : forall e e1 e2 e',\n     lc_exp e1 ->\n     lc_exp e2 ->\n     step e e' ->\n     step (e_cond e e1 e2) (e_cond e' e1 e2)\n | step_condl : forall e1 e2,\n     lc_exp e1 ->\n     lc_exp e2 ->\n     step (e_cond e_tru e1 e2) e1\n | step_condr : forall e1 e2,\n     lc_exp e1 ->\n     lc_exp e2 ->\n     step (e_cond e_fls e1 e2) e2.\n\nLemma cannonical_form_bool : forall v,\n  value v ->\n  forall E, typing E v t_bool ->\n  v = e_tru \\/ v = e_fls.\nProof.\n  introv Val Typ.\n  inverts Typ; try solve [inverts* Val].\nQed.\n\nLemma canonical_form_abs : forall v,\n  value v ->\n  forall T1 T2 E, typing E v (t_arrow T1 T2) ->\n  exists e, v = e_abs T1 e.\nProof.\n  introv Val Typ. inverts Val; try solve [inverts Typ].\n  inverts Typ. exists* e.\nQed.\n\n#[export]\nHint Constructors value step lc_exp step : core.\n\n(** Gathering free names already used in the proofs **)\n\nFixpoint fv_ee (e:exp) : vars :=\n  match e with\n  | e_fvar y => \\{y}\n  | e_bvar i => \\{}\n  | e_abs T t1 => fv_ee t1\n  | e_app t1 t2 => (fv_ee t1) \\u (fv_ee t2)\n  | e_tru => \\{}\n  | e_fls => \\{}\n  | e_cond t t1 t2 => (fv_ee t) \\u (fv_ee t1) \\u (fv_ee t2)\n  end.\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 : exp => fv_ee x) in\n  let F := gather_vars_with (fun x : env => dom x) in\n  constr:(A \\u B \\u C \\u F).\n\n(** \"pick_fresh x\" tactic create a fresh variable with name x *)\n\nLtac pick_fresh x :=\n  let L := gather_vars in (pick_fresh_gen L x).\n\n(** \"apply_fresh T as x\" is used to apply inductive rule which\n   use an universal quantification over a cofinite set *)\n\nTactic Notation \"apply_fresh\" constr(T) \"as\" ident(x) :=\n  apply_fresh_base T gather_vars x.\n\nTactic Notation \"apply_fresh\" \"*\" constr(T) \"as\" ident(x) :=\n  apply_fresh T as x; autos*.\n\n(** These tactics help applying a lemma which conclusion mentions\n  an environment (E & F) in the particular case when F is empty *)\n\nLtac get_env :=\n  match goal with\n  | |- typing ?E _ _ => E\n  end.\n\nTactic Notation \"apply_empty_bis\" tactic(get_env) constr(lemma) :=\n  let E := get_env in rewrite <- (concat_empty_r E);\n  eapply lemma; try rewrite concat_empty_r.\n\nTactic Notation \"apply_empty\" constr(F) :=\n  apply_empty_bis (get_env) F.\n\nTactic Notation \"apply_empty\" \"*\" constr(F) :=\n  apply_empty F; autos*.\n\nLemma progress : forall e T,\n  lc_exp e ->\n  typing empty e T ->\n  value e \\/ exists e', step e e'.\nProof.\n  introv LC Typ.\n  inductions Typ.\n - apply binds_empty_inv in H0. inverts H0.\n - inverts LC. left*.\n - right. inverts LC. destruct~ IHTyp1.\n   destruct~ IHTyp2.\n   apply canonical_form_abs in Typ1; auto.\n   destruct Typ1 as [e Typ1].\n   subst. exists* (open_ee e e2).\n   destruct H0 as [e' H0]. exists*.\n   destruct H as [e' H]. exists*.\n - left*.\n - left*.\n - right. inverts LC. destruct~ IHTyp1.\n   apply cannonical_form_bool in Typ1; auto.\n   destruct Typ1. \n   subst. exists*. subst. exists*.\n   destruct H as [e' H]. exists*.\nQed.\n\nLemma typing_weakening : forall E F G e T,\n  typing (E & G) e T ->\n  ok (E & F & G) ->\n  typing (E & F & G) e T.\nProof.\n  introv Typ Ok. gen F. inductions Typ; simpl; intros.\n  - apply* typ_var.\n    apply* binds_weaken.\n  - apply_fresh* typ_abs as y.\n    forwards*: H1 y E (G & y ~ T1) F.\n    rewrite~ concat_assoc.\n    rewrite~ concat_assoc.\n    rewrite~ concat_assoc in H2.\n  - apply* typ_app.\n  - apply* typ_tru.\n  - apply* typ_fls.\n  - apply* typ_cond.\nQed.\n\n(* ********************************************************************** *)\n(** ** Properties of term substitution in terms *)\n\nLemma open_ee_rec_term_core : forall e j v u i, i <> j ->\nopen_ee_rec j v e = open_ee_rec i u (open_ee_rec j v e) ->\n  e = open_ee_rec i u e.\nProof.\n  induction e; introv Neq H; simpl in *; inversion H; f_equal*.\n  case_nat*. case_nat*.\nQed.\n\n\nLemma open_ee_rec_term : forall u e,\n  lc_exp e -> forall k, e = open_ee_rec k u e.\nProof.\n  induction 1; intros; simpl; f_equal*.\n  unfolds open_ee_rec. pick_fresh x.\n   apply* (@open_ee_rec_term_core e 0 (e_fvar x)).\nQed.\n\n(** Substitution for a fresh name is identity. *)\n\nLemma subst_ee_fresh : forall x u e,\n  x \\notin fv_ee e -> subst_ee x u e = e.\nProof.\n  induction e; simpl; intros; f_equal*.\n  case_var*.\nQed.\n\n(** Substitution distributes on the open operation. *)\n\nLemma subst_ee_open_ee : forall t1 t2 u x, lc_exp u ->\nsubst_ee x u (open_ee t1 t2) =\nopen_ee (subst_ee x u t1) (subst_ee x u t2).\nProof.\n  intros. unfold open_ee. generalize 0.\n  induction t1; intros; simpls; f_equal*.\n  case_var*. rewrite* <- open_ee_rec_term.\n  case_nat*.\nQed.\n\n(** Substitution and open_var for distinct names commute. *)\n\nLemma subst_ee_open_ee_var : forall x y u e, y <> x -> lc_exp u ->\n  (subst_ee x u e) open_ee_var y = subst_ee x u (e open_ee_var y).\nProof.\n  introv Neq Wu. rewrite* subst_ee_open_ee.\n  simpl. case_var*.\nQed.\n\n(** Opening up a body t with a type u is the same as opening\n  up the abstraction with a fresh name x and then substituting u for x. *)\n\nLemma subst_ee_intro : forall x u e,\n  x \\notin fv_ee e -> lc_exp u ->\n  open_ee e u = subst_ee x u (e open_ee_var x).\nProof.\n  introv Fr Wu. rewrite* subst_ee_open_ee.\n  rewrite* subst_ee_fresh. simpl. case_var*.\nQed.\n\nLemma typing_regular : forall E e T,\n  typing E e T -> ok E /\\ lc_exp e.\nProof.\n  introv Typ. inductions Typ; auto.\n  - split*.\n    apply_fresh lc_abs as y.\n    forwards*: H1 y.\n  - split*.\n  - split*.\nQed.\n\nLemma typing_through_subst_ee : forall E F x S e T s,\n  typing (E & x ~ S & F) e T ->\n  typing (E & F) s S ->\n  typing (E & F) (subst_ee x s e) T.\nProof.\n  introv TypT TypS.\n  inductions TypT; simpl.\n  - case_var.\n    binds_get H0. auto.\n    binds_cases H0; apply* typ_var.\n  - apply_fresh* typ_abs as y.\n    specialize (H1 y).\n    forwards*: H1 E (F & y ~ T1) x S.\n    rewrite~ concat_assoc.\n    rewrite~ concat_assoc.\n    apply_empty* typing_weakening.\n    (* rewrite <- (concat_empty_r (E & F & y ~ T1)).\n    apply* typing_weakening.\n    rewrite~ concat_empty_r.\n    rewrite~ concat_empty_r. *)\n    rewrite~ concat_assoc in H2.\n    rewrite~ subst_ee_open_ee_var.\n    apply typing_regular in TypS.\n    destruct~ TypS.\n  - apply* typ_app.\n  - apply* typ_tru.\n  - apply* typ_fls.\n  - apply* typ_cond.\nQed.\n\nLemma preservation : forall E e T e',\n  typing E e T ->\n  step e e' ->\n  typing E e' T.\nProof.\n  introv Typ red.\n  gen e'. inductions Typ; intros; try solve [inverts red].\n  - inverts red.\n    eapply typ_app; eauto.\n    eapply typ_app; eauto.\n    inverts Typ1.\n    pick_fresh y.\n    forwards*: H7 y.\n    rewrite <- (concat_empty_r E).\n    rewrite <- (concat_empty_r (E & y ~ T1)) in H.\n    rewrite~ (@subst_ee_intro y).\n    forwards*: typing_through_subst_ee H.\n    rewrite~ (concat_empty_r).\n    forwards*: typing_regular Typ2.\n  - inverts* red.\n    apply* typ_cond.\nQed.\n", "meta": {"author": "baberrehman", "repo": "TAPL", "sha": "cc7639a1d699fa8f36f269fddf1b45f70c606f30", "save_path": "github-repos/coq/baberrehman-TAPL", "path": "github-repos/coq/baberrehman-TAPL/TAPL-cc7639a1d699fa8f36f269fddf1b45f70c606f30/ch9/ch9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6616115049102445}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n\nDefinition surjective {A B : Type} (f : A -> B) :=\n  forall (b : B), exists a, f a = b.\n\n\nDefinition injective {A B : Type} (f : A -> B) :=\n  forall (a1 a2 : A), f a1 = f a2 -> a1 = a2.\n\n\nDefinition left_inverse {A B : Type} (f : A -> B) :=\n  exists (g : B -> A), (forall a, g (f a) = a).\n\n\n(* Permutations are bijections on an alphabet *)\nDefinition bijective {A B : Type} (f : A -> B) :=\n  injective f /\\ surjective f.\n\n\nTheorem injective_composition :\n  forall (A B C : Type) (f : A -> B) (g : B -> C),\n    injective f ->\n    injective g ->\n    injective (compose g f).\nProof.\n  intros A B C f g Hf Hg.\n  unfold injective in *. unfold compose in *.\n  intros a1 a2 H.\n  apply Hg in H. apply Hf in H.\n  assumption.\nQed.\n\n\nTheorem composition_injective :\n  forall (A B C : Type) (f : A -> B) (g : B -> C),\n    injective (compose g f) ->\n    surjective f ->\n    injective f /\\ injective g.\nProof.\n  intros A B C f g Hinj Hsurj.\n  unfold injective in *. unfold compose in *.\n  split.\n  - intros a1 a2 Hf.\n    apply Hinj. rewrite Hf.\n    reflexivity.\n  - intros b1 b2 Hg.\n    unfold surjective in Hsurj.\n    destruct (Hsurj b1) as [a1 Hfa1].\n    destruct (Hsurj b2) as [a2 Hfa2].\n    subst.\n    apply Hinj in Hg. subst.\n    reflexivity.\nQed.\n\n\nTheorem composition_surjective :\n  forall (A B C : Type) (f : A -> B) (g : B -> C),\n    surjective (compose g f) ->\n    surjective g.\nProof.\n  intros A B C f g H.\n  unfold surjective in *.\n  intros b. destruct (H b) as [a Hcomp].\n  exists (f a). assumption.\nQed.\n\n\nTheorem injective_id :\n  forall (A : Type), injective (@id A).\nProof.\n  unfold injective. intros A a1 a2 H.\n  compute in H.\n  assumption.\nQed.\n\n\nTheorem surjective_id :\n  forall (A : Type), surjective (@id A).\nProof.\n  unfold surjective. intros A b.\n  exists b.\n  reflexivity.\nQed.\n\n\nTheorem composition_id :\n  forall (A B : Type) (f : A -> B) (g : B -> A),\n  (forall a, g (f a) = a) -> compose g f = id.\nProof.\n  intros A B f g H.\n  apply functional_extensionality.\n  apply H.\nQed.\n\n\nTheorem composition_surjective_f :\n  forall (A B : Type) (f : A -> B) (g : B -> A),\n  surjective (compose g f) -> injective g -> surjective f.\nProof.\n  unfold surjective.\n  intros A B f g H Hinj b.\n  pose proof (H (g b)). destruct H0.\n  exists x. unfold compose in H0.\n  apply Hinj in H0.\n  assumption.\nQed.\n\n\nTheorem to_compose :\n  forall (A B C : Type) (f : A -> B) (g : B -> C) (a : A),\n    g (f a) = (compose g f) a.\nProof.\n  reflexivity.\nQed.\n\n\nTheorem left_inverse_injective :\n  forall {A B : Type} (f : A -> B),\n    left_inverse f ->\n    injective f.\nProof.\n  intros A B f [g H].\n  unfold injective.\n  intros a1 a2 Hfa.\n  apply f_equal with (f:=g) in Hfa.\n  apply composition_id in H.\n  rewrite to_compose with (f:=f) in Hfa.\n  rewrite to_compose with (f:=f) in Hfa.\n  rewrite H in Hfa.\n  compute in Hfa.\n  assumption.\nQed.\n\n\nTheorem left_inverse_not_equal :\n  forall {A B : Type} (f : A -> B) (a b : A),\n    left_inverse f ->\n    a <> b ->\n    f a <> f b.\nProof.\n  intros A B f a b [g Hinv] Hab.\n  unfold not in *.\n  intros Hfab.\n  apply Hab.\n  apply (f_equal g) in Hfab.\n  repeat rewrite Hinv in Hfab.\n  assumption.\nQed.\n\n\nTheorem left_inverse_injective_on_domain :\n  forall {A B : Type} (f : A -> B) (g : B -> A),\n    (forall a, g (f a) = a) ->\n    forall a1 a2, g (f a1) = g (f a2) -> f a1 = f a2.\nProof.\n  intros A B f g H a1 a2 Hgf.\n  repeat rewrite H in Hgf.\n  subst. reflexivity.\nQed.\n", "meta": {"author": "Chobbes", "repo": "coq-enigma", "sha": "3809e43b458c7fb586a5a297ba78e2c31196ad43", "save_path": "github-repos/coq/Chobbes-coq-enigma", "path": "github-repos/coq/Chobbes-coq-enigma/coq-enigma-3809e43b458c7fb586a5a297ba78e2c31196ad43/bijections.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6616115010811741}}
{"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(** * denum: retracting various countable types into positives *)\n\nRequire Import common positives ordinal.\nSet Implicit Arguments.\n\n(** * Sums *)\n\nDefinition mk_sum (x: positive+positive) :=\n  match x with\n    | inl p => xO p\n    | inr p => xI p\n  end.\nDefinition get_sum x := \n  match x with\n    | xO p => inl p\n    | xI p => inr p\n    | _ => assert_false (inl xH)\n  end.\nLemma get_mk_sum x: get_sum (mk_sum x) = x.  \nProof. now destruct x. Qed.\n\n(** * Pairs *)\n\nFixpoint xpair y x :=\n  match x with \n    | xH => xI (xO y)\n    | xO x => xO (xO (xpair y x))\n    | xI x => xI (xI (xpair y x))\n  end.\nDefinition mk_pair (x: positive*positive) := xpair (snd x) (fst x).\nFixpoint get_pair x := \n  match x with \n    | xI (xO p) => (xH,p)\n    | xO (xO x) => let '(x,y) := get_pair x in (xO x,y)\n    | xI (xI x) => let '(x,y) := get_pair x in (xI x,y)\n    | _ => assert_false (xH,xH)\n  end.\nLemma get_mk_pair x: get_pair (mk_pair x) = x.  \nProof. \n  destruct x as [x y]. unfold mk_pair. simpl. \n  induction x; simpl; now rewrite ?IHx. \nQed.\n\n(** * Natural numbers *)\n\n(** we use a much simpler function than the standard bijection, \n   since we only need a retract *)\nDefinition mk_nat := nat_rec (fun _=>positive) xH (fun _ => xO).\nFixpoint get_nat x := \n  match x with \n    | xH => O\n    | xO x => S (get_nat x) \n    | _ => assert_false O \n  end.\nLemma get_mk_nat x: get_nat (mk_nat x) = x.  \nProof. induction x; simpl; now rewrite ?IHx. Qed.\n\n(** * Ordinals *)\n\nDefinition mk_ord n (x: ord n) := mk_nat x.\n(** get_ord returns an option since [n] could be 0, \n   this is not problematic in practice *)\nDefinition get_ord n (x: positive): option (ord n).\n set (y:=get_nat x). case (lt_ge_dec y n).\n intro Hy. exact (Some (Ord y Hy)).\n intros _. exact None.\nDefined.\nLemma get_mk_ord n x: get_ord n (mk_ord x) = Some x.  \nProof. \n  unfold mk_ord, get_ord. destruct x as [i Hi]; simpl. \n  rewrite get_mk_nat. case lt_ge_dec.\n  intro. f_equal. now apply eq_ord. \n  rewrite Hi at 1. discriminate.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "relation-algebra", "sha": "2d9066e917400dc3e2b10ad9c12710620d20644b", "save_path": "github-repos/coq/coq-contribs-relation-algebra", "path": "github-repos/coq/coq-contribs-relation-algebra/relation-algebra-2d9066e917400dc3e2b10ad9c12710620d20644b/denum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6616114976085414}}
{"text": "(*\n   Here we prove that if a series converges absolutely, then every\n   rearrangement of that series (1) converges absolutely, and (2)\n   converges to the same value.  This is needed to show that the\n   definition of expectation is sensible and matches alternate ways of\n   defining it.\n*)\n\nFrom discprob.basic Require Import base order bigop_ext nify sval.\nFrom discprob.prob Require Import countable.\nRequire Import Reals Fourier Omega Psatz ClassicalEpsilon.\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype seq bigop fintype ssrnat choice.\nFrom Coquelicot Require Import Rcomplements Rbar Series Lim_seq Hierarchy Markov.\n\nLemma sum_n_m_filter (a: nat → R) (P: pred nat) n m:\n  sum_n_m (λ n, if P n then (Rabs (a n)) else 0) n m <= sum_n_m (Rabs \\o a) n m.\nProof.\n  apply sum_n_m_le => k. destruct (P k) => //=; try nra.\n  apply Rabs_pos.\nQed.\n\nLemma foldl_max l:\n  ∀ x, foldl max x l ≥ x.\nProof.\n  induction l; rewrite //=; intros; try lia.\n  specialize (IHl (Init.Nat.max x a)).\n  etransitivity; eauto. apply Max.le_max_l.\nQed.\n\nLemma max_fun_range (σ: nat → nat) m:\n  ∃ N, (∀ m', m' ≤ m → σ m' ≤ N) ∧ (∃ m0, m0 ≤ m ∧ σ m0 = N).\nProof.\n  induction m.\n  - exists (σ O). split.\n    * by inversion 1.\n    * exists O. split; auto.\n  - destruct IHm as (N&?&Hachieve).\n    exists (Init.Nat.max N (σ (S m))). split.\n    * intros m'. inversion 1; subst.\n      ** auto with *.\n      ** etransitivity; last apply Max.le_max_l; eauto.\n    * apply (Max.max_case_strong).\n      ** intros. destruct Hachieve as (m0&?&?). exists m0; split; subst; auto.\n      ** intros. exists (S m). split; auto.\nQed.\n\nSection bijective.\n\nLemma bij_nat_cover (σ: nat → nat) (bij: bijective σ):\n  ∀ n, ∃ m, ∀ m', m' ≥ m →\n  ∃ N, (∀ n', n' ≤ n → ∃ m'', m'' ≤ m' ∧ σ m'' = n') ∧ N ≥ n ∧ (∀ m'', m'' ≤ m' → σ m'' ≤ N).\nProof.\n  destruct bij as [σinv Hcan1 Hcan2].\n  induction n.\n  - exists (σinv O) => m' Hgem.\n    edestruct (max_fun_range σ m') as (N&?&?).\n    exists N; split.\n    * intros n'. inversion 1; subst. exists (σinv O); repeat split; auto.\n    * split; auto with *.\n  - destruct IHn as (m&Hm). (* N&(IHm1&?&?)). *)\n    exists (Init.Nat.max m (σinv (S n))) => m' Hgem.\n    edestruct (max_fun_range σ (Init.Nat.max m' (σinv (S n)))) as (N'&Hbound&?).\n    exists N'; repeat split.\n    * intros n'. inversion 1; subst.\n      ** exists (σinv (S n)). split; auto.\n         transitivity (Init.Nat.max m (σinv (S n))); first apply Max.le_max_r; eauto.\n      ** destruct (Hm m') as (N&(IHm1&?&?)).\n         { etransitivity; eauto; first apply Max.le_max_l. }\n         destruct (IHm1 n') as (x&?&?); auto.\n    * specialize (Hbound (σinv (S n))).\n      rewrite Hcan2 in Hbound. apply Hbound. auto with *.\n    * intros m'' Hlem'. eapply Hbound. etransitivity; eauto. apply Max.le_max_l.\nQed.\n\nLemma sum_n_bij_sandwich (a: nat → R) (σ: nat → nat) (bij: bijective σ):\n  ∀ n, ∃ m, ∀ m', m' ≥ m →\n  ∃ n', n' ≥ n ∧ sum_n (Rabs \\o a) n <= sum_n ((Rabs \\o a) \\o σ) m' <= sum_n (Rabs \\o a) n'.\nProof.\n  intros n; edestruct (bij_nat_cover σ bij n) as (m&Hm).\n  exists m => m' Hgem.\n  edestruct Hm as (N&(Hhit&?&Hup)); eauto.\n  exists N. repeat split; auto.\n  - rewrite ?sum_n_bigop //=.\n    rewrite /index_enum.\n    destruct bij as [σinv Hcan1 Hcan2].\n    assert (Hupinv : ∀ n' : nat, n' ≤ n → σinv n' ≤ m').\n    {\n      intros n'. move /Hhit => [m''] [Hle Heq].\n      rewrite -Heq Hcan1. done.\n    }\n    set (σinv' := λ x: 'I_(S n),\n                  match x with\n                    | Ordinal k Hle =>\n                      Ordinal (proj2 (SSR_leq _ _) (le_n_S _ _ (Hupinv _ (proj1 (SSR_leq k n) Hle))))\n                  end).\n    apply (sum_reidx_map_le _ _ _ _ σinv').\n    * intros (x&Hlex) ?. rewrite Hcan2. reflexivity.\n    * intros; split; auto. rewrite -enumT mem_enum //=.\n    * intros. apply Rle_ge, Rabs_pos.\n    * rewrite -enumT. apply enum_uniq.\n    * rewrite -enumT. apply enum_uniq.\n    * intros (x&?) (y&?) => //= _. inversion 1. apply ord_inj => //=.\n      apply (bij_inj (Bijective Hcan2 Hcan1)). done.\n  - rewrite ?sum_n_bigop //=.\n    rewrite /index_enum.\n    set (σ' := λ x: 'I_(S m'),\n                  match x with\n                    | Ordinal k Hle =>\n                      Ordinal (proj2 (SSR_leq _ _) (le_n_S _ _ (Hup _ (proj1 (SSR_leq k m') Hle))))\n                  end).\n    apply (sum_reidx_map_le _ _ _ _ σ').\n    * intros (x&Hlex) ?. reflexivity.\n    * intros; split; auto. rewrite -enumT mem_enum //=.\n    * intros. apply Rle_ge, Rabs_pos.\n    * rewrite -enumT. apply enum_uniq.\n    * rewrite -enumT. apply enum_uniq.\n    * intros (x&?) (y&?) => //= _. inversion 1. apply ord_inj => //=.\n      apply (bij_inj bij). done.\nQed.\n\nLemma sum_n_m_bij_diff_abs (a: nat → R) (σ: nat → nat) (bij: bijective σ):\n  ∀ N, ∃ M, ∀ m, m ≥ M →\n  ∃ n, n ≥ N ∧ Rabs (sum_n (Rabs \\o a \\o σ) m - sum_n (Rabs \\o a) N) <= sum_n_m (Rabs \\o a) (S N) n.\nProof.\n  intros N.\n  destruct (sum_n_bij_sandwich a σ bij N) as (M&HM).\n  exists M => m HgeM.\n  edestruct (HM m HgeM) as (N'&?&(?&?)); eauto.\n  exists N'; split; auto.\n  rewrite (sum_n_m_sum_n); last done.\n  rewrite Rabs_right; last nra.\n  rewrite /minus/plus/opp/=. nra.\nQed.\n\nLemma sum_n_m_bij_diff (a: nat → R) (σ: nat → nat) (bij: bijective σ):\n  ∀ N, ∃ M, ∀ m, m ≥ M →\n  ∃ n, n ≥ N ∧ Rabs (sum_n (a \\o σ) m - sum_n a N) <= sum_n_m (Rabs \\o a) (S N) n.\nProof.\n  intros n; edestruct (bij_nat_cover σ bij n) as (m&Hm).\n  exists m => m' Hgem.\n  edestruct Hm as (N&(Hhit&?&Hup)); eauto.\n  exists N. repeat split; auto.\n  transitivity (Rabs (\\big[Rplus/0]_(S n <= i < S N | exC (λ m0, (leq m0 m') && (σ m0 == i))) (a i)));\n    last first.\n  {\n    rewrite sum_n_m_bigop. etransitivity; first apply Rabs_bigop_triang.\n    rewrite //=. apply Rabs_bigop_filter. auto.\n  }\n  right. f_equal.\n  assert (sum_n (a \\o σ) m' =\n          \\big[Rplus/0]_(i < S N | exC (λ m0, (m0 <= m')%nat && (σ m0 == i))) a i) as ->.\n  {\n    rewrite sum_n_bigop.\n    rewrite /index_enum.\n    set (σ' := λ x: 'I_(S m'),\n                  match x with\n                    | Ordinal k Hle =>\n                      Ordinal (proj2 (SSR_leq _ _) (le_n_S _ _ (Hup _ (proj1 (SSR_leq k m') Hle))))\n                  end).\n    eapply (sum_reidx_map (Finite.enum (ordinal_finType m'.+1))\n                          (Finite.enum (ordinal_finType N.+1))\n                          (λ x, true) _ σ').\n    * intros (x&Hlex) ? => //=.\n    * intros (m0&?); split; auto. apply (introT (exCP _)).\n      exists m0. apply /andP; split => //=.\n    * intros (n'&?) _. move /exCP => [m0]. move /andP => [Hle Heq].\n      intros Hfalse. contradiction Hfalse.\n      assert (m0 < S m')%nat as Hlt.\n      { nify.  omega. }\n      exists (Ordinal Hlt). repeat split; eauto.\n      apply ord_inj => //=. nify. done.\n    * rewrite -enumT. apply enum_uniq.\n    * rewrite -enumT. apply enum_uniq.\n    * intros (x&?) (y&?)  _ => //=. inversion 1. apply ord_inj => //=.\n      eapply bij_inj; eauto.\n  }\n  assert (sum_n a n =\n          \\big[Rplus/0]_(i < S n | exC (λ m0, (m0 <= m')%nat && (σ m0 == i))) a i) as ->.\n  {\n    rewrite sum_n_bigop.\n    apply eq_bigl. intros (i&Hle).\n    symmetry. eapply (introT (exCP _)).\n    edestruct (Hhit i) as (m''&?&?); first by (nify; lia).\n    exists m''. apply /andP; split; nify; auto.\n  }\n  rewrite -(big_mkord (λ i, exC (λ m0, (m0 <= m')%nat && (σ m0 == i)))).\n  assert (S n <= S N)%nat as Hsplit by (nify; lia).\n  rewrite (big_cat_nat _ _ _ _ Hsplit) //=.\n  rewrite big_mkord.\n  assert (∀ a b, a + b - a = b) as -> by (intros; field).\n  done.\nQed.\n\nLemma norm_dist_mid x y z: norm (x - y) <= norm (x - z) + norm (z - y).\nProof.\n  replace (x - y) with ((x - z) + (z - y)) by field.\n  etransitivity; last eapply norm_triangle.\n  apply Rle_refl.\nQed.\nLemma series_rearrange (a: nat → R) (σ: nat → nat) (bij: bijective σ) (v: R):\n  is_series (λ n, Rabs (a n)) v →\n  is_series (λ n, Rabs (a (σ n))) v ∧\n  is_series (λ n, a (σ n)) (Series a).\nProof.\n  intros Habsconv.\n  assert (ex_series a) as (v'&Hconv) by (eapply ex_series_Rabs; eexists; eauto).\n  assert(Hnorm: ∀ eps : posreal, ∃ N M, ∀ m, M ≤ m →\n         norm (sum_n (Rabs \\o a) N - sum_n (Rabs \\o a \\o σ) m) < eps ∧\n         norm (sum_n a N - sum_n (a \\o σ) m) < eps ∧\n         norm (sum_n (Rabs \\o a) N - v) < eps ∧\n         norm (sum_n a N - v') < eps).\n  {\n    intros eps.\n    edestruct (Cauchy_ex_series (Rabs \\o a)) as (N0&IHN).\n    { exists v; eauto. }\n    assert (∃ N, ∀ N', N' ≥ N → norm (sum_n (Rabs \\o a) N' - v) < eps) as (N1&HN1).\n    { rewrite /is_series in Habsconv.\n      edestruct Habsconv as (x&Hball). eapply locally_ball.\n      exists x. eapply Hball.\n    }\n    assert (∃ N, ∀ N', N' ≥ N → norm (sum_n a N' - v') < eps) as (N2&HN2).\n    { rewrite /is_series in Hconv.\n      edestruct Hconv as (x&Hball). eapply locally_ball.\n      exists x. eapply Hball.\n    }\n    set (N := max N0 (max N1 N2)).\n    edestruct (sum_n_m_bij_diff_abs a σ bij N) as (M1&IHM1).\n    edestruct (sum_n_m_bij_diff a σ bij N) as (M2&IHM2).\n    exists N. exists (max M1 M2) => m Hle.\n    apply Nat.max_lub_iff in Hle as (?&?).\n    rewrite /norm//=/abs//=; repeat split; auto.\n    - rewrite Rabs_minus_sym. edestruct (IHM1 m) as (n&?&Hle); auto.\n      eapply Rle_lt_trans; first eapply Hle.\n      rewrite /norm//=/abs//= in IHN.\n      eapply Rle_lt_trans; first apply Rle_abs.\n      assert (N0 <= N)%coq_nat.\n      { rewrite /N. apply Max.le_max_l. }\n      eapply IHN; auto. omega.\n    - rewrite Rabs_minus_sym. edestruct (IHM2 m) as (n&?&Hle); auto.\n      eapply Rle_lt_trans; first eapply Hle.\n      rewrite /norm//=/abs//= in IHN.\n      eapply Rle_lt_trans; first apply Rle_abs.\n      assert (N0 <= N)%coq_nat.\n      { rewrite /N. apply Max.le_max_l. }\n      eapply IHN; auto. omega.\n    - eapply HN1.\n      rewrite /N. etransitivity; first apply Max.le_max_r. apply Max.le_max_l.\n    - eapply HN2.\n      rewrite /N. etransitivity; first apply Max.le_max_r. apply Max.le_max_r.\n  }\n  split.\n  - rewrite /is_series. eapply filterlim_locally => eps.\n    edestruct (Hnorm (pos_div_2 eps)) as (N&M&?HNM).\n    exists M => m Hle.\n    specialize (HNM m Hle) as (?&?&?&?).\n    rewrite /ball//=/AbsRing_ball//=/abs/AbsRing.abs//=/minus//=/plus//=/opp//=.\n    specialize (norm_dist_mid (sum_n (Rabs \\o a \\o σ) m) v (sum_n (Rabs \\o a) N)).\n    rewrite {1}/norm//={1}/Rminus.\n    intros Hle'. eapply Rle_lt_trans; first eapply Hle'.\n    destruct eps as (eps&?).\n    replace (eps) with (eps/2 + eps/2); last by field.\n    apply Rplus_lt_compat; eauto.\n    rewrite /norm//=/abs//= Rabs_minus_sym. done.\n  - assert (Series a = v') as -> by (eapply is_series_unique; eauto).\n    rewrite /is_series. eapply filterlim_locally => eps.\n    edestruct (Hnorm (pos_div_2 eps)) as (N&M&?HNM).\n    exists M => m Hle.\n    specialize (HNM m Hle) as (?&?&?&?).\n    rewrite /ball//=/AbsRing_ball//=/abs/AbsRing.abs//=/minus//=/plus//=/opp//=.\n    specialize (norm_dist_mid (sum_n (a \\o σ) m) v' (sum_n a N)).\n    rewrite {1}/norm//={1}/Rminus.\n    intros Hle'. eapply Rle_lt_trans; first eapply Hle'.\n    destruct eps as (eps&?).\n    replace (eps) with (eps/2 + eps/2); last by field.\n    apply Rplus_lt_compat; eauto.\n    rewrite /norm//=/abs//= Rabs_minus_sym. done.\nQed.\n\nEnd bijective.\n\nSection covering.\n\nVariable (a: nat → R).\nVariable (σ: nat → nat).\nVariable (INJ: ∀ n n', a (σ n) <> 0 → σ n = σ n' → n = n').\nVariable (COV: ∀ n, a n <> 0 → ∃ m, σ m = n).\n\nLemma inj_nat_cover:\n  ∀ n, ∃ m, ∀ m', m' ≥ m →\n  ∃ N, (∀ n', n' ≤ n → (∃ m'', m'' ≤ m' ∧ σ m'' = n') ∨ a n' = 0)\n       ∧ N ≥ n ∧ (∀ m'', m'' ≤ m' → σ m'' ≤ N).\nProof.\n  induction n.\n  - destruct (Req_dec (a O) 0) as [|Hneq].\n    * exists O => m' Hge.\n      edestruct (max_fun_range σ m') as (N&?&?).\n      exists N; split.\n      ** intros n'. inversion 1. subst. auto.\n      ** split; auto with *.\n    * edestruct (COV O Hneq) as (m&?).\n      exists m => m'.\n      edestruct (max_fun_range σ m') as (N&?&?).\n      exists N; split.\n      ** intros n'. inversion 1. subst. left. eauto.\n      ** split; auto with *.\n  - destruct IHn as (m&Hm).\n    destruct (Req_dec (a (S n)) 0) as [|Hneq].\n    * exists m => m' Hge.\n      edestruct Hm as (N&?&?&?); eauto.\n      exists (S N); repeat split; auto; last omega.\n      intros n'. inversion 1; subst; auto.\n    * edestruct (COV (S n) Hneq) as (minv&Heq).\n    exists (Init.Nat.max m minv) => m' Hgem.\n    edestruct (max_fun_range σ (Init.Nat.max m' minv)) as (N'&Hbound&?).\n    exists N'; repeat split.\n    ** intros n'. inversion 1; subst. left.\n      *** exists minv. split; auto.\n         transitivity (Init.Nat.max m minv); first apply Max.le_max_r; eauto.\n      *** destruct (Hm m') as (N&(IHm1&?&?)).\n         { etransitivity; eauto; first apply Max.le_max_l. }\n         eauto.\n    ** specialize (Hbound minv).\n       rewrite -Heq. eapply Hbound. apply Max.le_max_r.\n    ** intros m'' Hlem'. eapply Hbound. etransitivity; eauto. apply Max.le_max_l.\nQed.\n\nLemma sum_n_m_cover_diff:\n  ∀ N, ∃ M, ∀ m, m ≥ M →\n  ∃ n, n ≥ N ∧ Rabs (sum_n (a \\o σ) m - sum_n a N) <= sum_n_m (Rabs \\o a) (S N) n.\nProof.\n  intros n; edestruct (inj_nat_cover n) as (m&Hm).\n  exists m => m' Hgem.\n  edestruct Hm as (N&(Hhit&?&Hup)); eauto.\n  exists N. repeat split; auto.\n  transitivity (Rabs (\\big[Rplus/0]_(S n <= i < S N | exC (λ m0, (leq m0 m') && (σ m0 == i))) (a i)));\n    last first.\n  {\n    rewrite sum_n_m_bigop. etransitivity; first apply Rabs_bigop_triang.\n    rewrite //=. apply Rabs_bigop_filter. auto.\n  }\n  right. f_equal.\n  assert (sum_n (a \\o σ) m' =\n          \\big[Rplus/0]_(i < S N | exC (λ m0, (m0 <= m')%nat && (σ m0 == i))) a i) as ->.\n  {\n    rewrite sum_n_bigop.\n    rewrite bigop_cond_non0 [a in _ = a]bigop_cond_non0.\n    rewrite /index_enum.\n    set (σ' := λ x: 'I_(S m'),\n                  match x with\n                    | Ordinal k Hle =>\n                      Ordinal (proj2 (SSR_leq _ _) (le_n_S _ _ (Hup _ (proj1 (SSR_leq k m') Hle))))\n                  end).\n    eapply (sum_reidx_map (Finite.enum (ordinal_finType m'.+1))\n                          (Finite.enum (ordinal_finType N.+1))\n                          _ _ σ').\n    * intros (x&Hlex) ? => //=.\n    * intros (m0&?); split; auto. apply /andP; split; auto. apply (introT (exCP _)).\n      exists m0. apply /andP; split => //=.\n    * intros (n'&?) _. move /andP => [HexC ?]. move /exCP in HexC.\n      destruct (HexC) as (m0&HexC'). move /andP in HexC'.  destruct (HexC') as (?&Heq).\n      intros Hfalse. contradiction Hfalse.\n      assert (m0 < S m')%nat as Hlt.\n      { nify.  omega. }\n      exists (Ordinal Hlt). repeat split; auto.\n      ** apply /andP; split; auto. rewrite //=. move /eqP in Heq. rewrite Heq. done.\n      ** apply ord_inj => //=. nify. done.\n    * rewrite -enumT. apply enum_uniq.\n    * rewrite -enumT. apply enum_uniq.\n    * intros (x&?) (y&?) Hneq0 => //=. inversion 1. apply ord_inj => //=.\n      eapply INJ; eauto. move /eqP. move /negP in Hneq0. auto.\n  }\n  assert (sum_n a n =\n          \\big[Rplus/0]_(i < S n | exC (λ m0, (m0 <= m')%nat && (σ m0 == i))) a i) as ->.\n  {\n    rewrite sum_n_bigop.\n    rewrite bigop_cond_non0 [a in _ = a]bigop_cond_non0.\n    eapply (sum_reidx_map _ _ _ _ id).\n    * intros (x&Hlex) ? => //=.\n    * intros (n'&Hle) ? Hneq0; split; auto. apply /andP; split; auto. apply (introT (exCP _)).\n      edestruct (Hhit n') as [(m''&?&?)|].\n      { clear -Hle. nify. omega. }\n      ** exists m''. apply /andP; split; nify; try omega => //=. subst. done.\n      ** exfalso. rewrite //= in Hneq0. move /eqP in Hneq0. auto.\n    * intros (n'&Hle) _. move /andP => [HexC ?]. move /exCP in HexC.\n      destruct (HexC) as (m0&HexC'). move /andP in HexC'.  destruct (HexC') as (?&Heq).\n      intros Hfalse. exfalso. eapply Hfalse. exists (Ordinal Hle). repeat split; auto.\n    * rewrite /index_enum. rewrite -enumT. apply enum_uniq.\n    * rewrite /index_enum. rewrite -enumT. apply enum_uniq.\n    * intros (x&?) (y&?) => //=.\n  }\n  rewrite -(big_mkord (λ i, exC (λ m0, (m0 <= m')%nat && (σ m0 == i)))).\n  assert (S n <= S N)%nat as Hsplit by (nify; lia).\n  rewrite (big_cat_nat _ _ _ _ Hsplit) //=.\n  rewrite big_mkord.\n  assert (∀ a b, a + b - a = b) as -> by (intros; field).\n  done.\nQed.\n\nEnd covering.\n\nLemma series_rearrange_covering (a: nat → R) (σ: nat → nat)\n      (INJ: ∀ n n', a (σ n) <> 0 → σ n = σ n' → n = n')\n      (COV: ∀ n, a n <> 0 → ∃ m, σ m = n)\n      (v: R):\n  is_series (λ n, Rabs (a n)) v →\n  is_series (λ n, Rabs (a (σ n))) v ∧\n  is_series (λ n, a (σ n)) (Series a).\nProof.\n  intros Habsconv.\n  assert (ex_series a) as (v'&Hconv) by (eapply ex_series_Rabs; eexists; eauto).\n  assert(Hnorm: ∀ eps : posreal, ∃ N M, ∀ m, M ≤ m →\n         norm (sum_n (Rabs \\o a) N - sum_n (Rabs \\o a \\o σ) m) < eps ∧\n         norm (sum_n a N - sum_n (a \\o σ) m) < eps ∧\n         norm (sum_n (Rabs \\o a) N - v) < eps ∧\n         norm (sum_n a N - v') < eps).\n  {\n    intros eps.\n    edestruct (Cauchy_ex_series (Rabs \\o a)) as (N0&IHN).\n    { exists v; eauto. }\n    assert (∃ N, ∀ N', N' ≥ N → norm (sum_n (Rabs \\o a) N' - v) < eps) as (N1&HN1).\n    { rewrite /is_series in Habsconv.\n      edestruct Habsconv as (x&Hball). eapply locally_ball.\n      exists x. eapply Hball.\n    }\n    assert (∃ N, ∀ N', N' ≥ N → norm (sum_n a N' - v') < eps) as (N2&HN2).\n    { rewrite /is_series in Hconv.\n      edestruct Hconv as (x&Hball). eapply locally_ball.\n      exists x. eapply Hball.\n    }\n    set (N := max N0 (max N1 N2)).\n    edestruct (sum_n_m_cover_diff (Rabs \\o a) σ) as (M1&IHM1).\n    {  rewrite //= => n n'. intros Hneq0. apply INJ; eauto.\n       intros Heq0. rewrite Heq0 Rabs_R0 in Hneq0. auto.\n    }\n    {\n      rewrite //= => n. intros Hneq0. eapply COV.\n       intros Heq0. rewrite Heq0 Rabs_R0 in Hneq0. auto.\n    }\n    edestruct (sum_n_m_cover_diff a σ INJ COV N) as (M2&IHM2).\n    exists N. exists (max M1 M2) => m Hle.\n    apply Nat.max_lub_iff in Hle as (?&?).\n    rewrite /norm//=/abs//=; repeat split; auto.\n    - rewrite Rabs_minus_sym. edestruct (IHM1 m) as (n&?&Hle); auto.\n      eapply Rle_lt_trans; first eapply Hle.\n      rewrite /norm//=/abs//= in IHN.\n      eapply Rle_lt_trans; first apply Rle_abs.\n      assert (N0 <= N)%coq_nat.\n      { rewrite /N. apply Max.le_max_l. }\n      eapply Rle_lt_trans; last apply (IHN (S N) n); auto; try omega.\n      right. f_equal. apply sum_n_m_ext_loc; auto.\n      intros => //=. rewrite //= Rabs_Rabsolu. done.\n    - rewrite Rabs_minus_sym. edestruct (IHM2 m) as (n&?&Hle); auto.\n      eapply Rle_lt_trans; first eapply Hle.\n      rewrite /norm//=/abs//= in IHN.\n      eapply Rle_lt_trans; first apply Rle_abs.\n      assert (N0 <= N)%coq_nat.\n      { rewrite /N. apply Max.le_max_l. }\n      eapply IHN; auto. omega.\n    - eapply HN1.\n      rewrite /N. etransitivity; first apply Max.le_max_r. apply Max.le_max_l.\n    - eapply HN2.\n      rewrite /N. etransitivity; first apply Max.le_max_r. apply Max.le_max_r.\n  }\n  split.\n  - rewrite /is_series. eapply filterlim_locally => eps.\n    edestruct (Hnorm (pos_div_2 eps)) as (N&M&?HNM).\n    exists M => m Hle.\n    specialize (HNM m Hle) as (?&?&?&?).\n    rewrite /ball//=/AbsRing_ball//=/abs/AbsRing.abs//=/minus//=/plus//=/opp//=.\n    specialize (norm_dist_mid (sum_n (Rabs \\o a \\o σ) m) v (sum_n (Rabs \\o a) N)).\n    rewrite {1}/norm//={1}/Rminus.\n    intros Hle'. eapply Rle_lt_trans; first eapply Hle'.\n    destruct eps as (eps&?).\n    replace (eps) with (eps/2 + eps/2); last by field.\n    apply Rplus_lt_compat; eauto.\n    rewrite /norm//=/abs//= Rabs_minus_sym. done.\n  - assert (Series a = v') as -> by (eapply is_series_unique; eauto).\n    rewrite /is_series. eapply filterlim_locally => eps.\n    edestruct (Hnorm (pos_div_2 eps)) as (N&M&?HNM).\n    exists M => m Hle.\n    specialize (HNM m Hle) as (?&?&?&?).\n    rewrite /ball//=/AbsRing_ball//=/abs/AbsRing.abs//=/minus//=/plus//=/opp//=.\n    specialize (norm_dist_mid (sum_n (a \\o σ) m) v' (sum_n a N)).\n    rewrite {1}/norm//={1}/Rminus.\n    intros Hle'. eapply Rle_lt_trans; first eapply Hle'.\n    destruct eps as (eps&?).\n    replace (eps) with (eps/2 + eps/2); last by field.\n    apply Rplus_lt_compat; eauto.\n    rewrite /norm//=/abs//= Rabs_minus_sym. done.\nQed.\n\nLemma series_rearrange_covering_pos (a: nat → R) (σ: nat → nat)\n      (INJ: ∀ n n', a (σ n) <> 0 → σ n = σ n' → n = n')\n      (COV: ∀ n, a n <> 0 → ∃ m, σ m = n)\n      (POS: ∀ n, a n >= 0)\n      (v: R):\n  is_series a v →\n  is_series (λ n, a (σ n)) v.\nProof.\n  intros. eapply (is_series_ext (λ n, Rabs (a (σ n)))).\n  { intros n. rewrite Rabs_right; auto. }\n  edestruct series_rearrange_covering as (His1&?); last eapply His1; eauto.\n  eapply is_series_ext; eauto.\n  { intros n. rewrite Rabs_right; auto. }\nQed.\n\nLemma Series_rearrange_covering (a: nat → R) (σ: nat → nat)\n      (INJ: ∀ n n', a (σ n) <> 0 → σ n = σ n' → n = n')\n      (COV: ∀ n, a n <> 0 → ∃ m, σ m = n):\n  ex_series (λ n, Rabs (a n)) →\n  Series a = Series (a \\o σ).\nProof.\n  intros (v'&?).\n  symmetry. apply is_series_unique. edestruct series_rearrange_covering; eauto.\nQed.\n\nLemma countable_series_rearrange_covering {Y X: countType}\n      (a: X → R) (σ: Y → X)\n      (INJ: ∀ n n', a (σ n) <> 0 → σ n = σ n' → n = n')\n      (COV: ∀ n, a n <> 0 → ∃ m, σ m = n)\n      (v: R):\n  is_series (countable_sum (λ n, Rabs (a n))) v →\n  is_series (countable_sum (λ n, Rabs (a (σ n)))) v ∧\n  is_series (countable_sum (λ n, a (σ n))) (Series (countable_sum a)).\nProof.\n  set (a' := λ n, match n with | O => 0 | S n' => countable_sum a n' end).\n  set (σ' := λ n, match @pickle_inv Y n with\n                  | Some x =>\n                    S (pickle (σ x))\n                  | None => O\n                  end).\n  intros His. edestruct (series_rearrange_covering a' σ') as (Habs&?).\n  { intros n n'. rewrite /σ'/a'/countable_sum/oapp//=.\n    destruct (@pickle_inv Y n) as [s|] eqn:Heqs.\n    * rewrite pickleK_inv.\n      destruct (@pickle_inv Y n') as [s'|] eqn:Heqs'.\n      ** intros ? HeqS. inversion HeqS as [Heq]. apply pickle_inj in Heq.\n         assert (s = s').\n         { eapply INJ; eauto. }\n         subst. eapply pickle_inv_some_inj; eauto; congruence.\n      ** intros Hneq0 Hpickle. inversion Hpickle.\n    * nra.\n  }\n  {\n    intros n. rewrite /a'/countable_sum/σ'//=.\n    destruct n as [|n]; first nra.\n    destruct (@pickle_inv X n) as [s|] eqn:Heqs.\n    * rewrite //= => Hneq0.  edestruct (COV _ Hneq0) as (m&Heqm).\n      exists (pickle m). rewrite pickleK_inv => //=. subst.\n      f_equal.\n      eapply pickle_inv_some_inv; eauto.\n    * rewrite //=; nra.\n  }\n  {\n    rewrite /a'.\n    apply: is_series_decr_1.\n    rewrite Rabs_R0 /opp//= Ropp_0/plus//= Rplus_0_r.\n    eapply is_series_ext; last eassumption.\n    intros n. rewrite /countable_sum//=. destruct pickle_inv => //=.\n    by rewrite Rabs_R0.\n  }\n  split.\n  * eapply is_series_ext; last eapply Habs.\n    intros n. rewrite /a'/countable_sum/σ'//=.\n    destruct (@pickle_inv Y n) as [s|] eqn:Heqs.\n    ** rewrite pickleK_inv //=.\n    ** rewrite //= Rabs_R0 //=.\n  * assert (Series a' = Series (countable_sum a)) as Heq.\n    { rewrite /a'. by eapply Series_incr_1_aux. }\n    rewrite -Heq.\n    eapply is_series_ext; last eassumption.\n    intros n. rewrite /a'/countable_sum/σ'//=.\n    destruct (@pickle_inv Y n) as [s|] eqn:Heqs.\n    ** rewrite pickleK_inv //=.\n    ** rewrite //=.\nQed.\n\nLemma countable_series_oapp {X: countType}\n      (a: X → R) (v: R):\n  is_series (countable_sum (λ n, Rabs (oapp a R0 n))) v →\n  is_series (countable_sum (λ n, Rabs (a n))) v ∧\n  is_series (countable_sum (λ n, a n)) (Series (countable_sum (oapp a R0))).\nProof.\n  intros. edestruct (countable_series_rearrange_covering (oapp a R0) Some) as (Habs&?).\n  { rewrite //=. intros. congruence. }\n  { rewrite //=. intros [|]; rewrite //=; (eauto || nra). }\n  { eauto. }\n  split.\n  * eapply is_series_ext; last eapply Habs.\n    intros n. rewrite //=.\n  * eapply is_series_ext; eauto.\nQed.\n\nLemma countable_series_oapp' {X: countType}\n      (a: X → R) (v: R):\n  is_series (countable_sum (λ n, Rabs (a n))) v →\n  is_series (countable_sum (λ n, Rabs (oapp a R0 n))) v ∧\n  is_series (countable_sum (oapp a R0)) (Series (countable_sum a)).\nProof.\n  intros His.\n  set (a' := λ n, match n with | O => 0 | S n' => countable_sum a n' end).\n  set (σ' := λ n, match @pickle_inv (option_countType X) n with\n                  | Some (Some x) =>\n                    S (pickle x)\n                  | _ => O\n                  end).\n  edestruct (series_rearrange_covering a' σ') as (Habs&?).\n  { intros n n'. rewrite /σ'/a'/countable_sum/oapp//=.\n    destruct (@pickle_inv (option_countType X) n) as [[s|]|] eqn:Heqs.\n    * rewrite pickleK_inv.\n      destruct (@pickle_inv (option_countType X) n') as [[s'|]|] eqn:Heqs'.\n      ** intros ? HeqS. inversion HeqS as [Heq]. apply pickle_inj in Heq.\n         subst. eapply pickle_inv_some_inj; eauto; congruence.\n      ** intros Hneq0 Hpickle. inversion Hpickle.\n      ** intros Hneq0 Hpickle. inversion Hpickle.\n    * nra.\n    * congruence.\n  }\n  {\n    intros n. rewrite /a'/countable_sum/σ'//=.\n    destruct n as [|n]; first nra.\n    destruct (@pickle_inv X n) as [s|] eqn:Heqs => //=.\n    * rewrite //= => Hneq0.\n      exists (pickle (Some s)). rewrite pickleK_inv => //=. f_equal.\n      eapply pickle_inv_some_inv; eauto.\n  }\n  {\n    rewrite /a'.\n    apply: is_series_decr_1.\n    rewrite Rabs_R0 /opp//= Ropp_0/plus//= Rplus_0_r.\n    eapply is_series_ext; last eassumption.\n    intros n. rewrite /countable_sum//=. destruct pickle_inv => //=.\n    by rewrite Rabs_R0.\n  }\n  split.\n  * eapply is_series_ext; last eapply Habs.\n    intros n. rewrite /a'/countable_sum/σ'//=.\n    destruct (@pickle_inv (option_countType X) n) as [[s|]|] eqn:Heqs.\n    ** rewrite pickleK_inv //=.\n    ** rewrite //= Rabs_R0 //=.\n    ** rewrite //= Rabs_R0 //=.\n  * assert (Series a' = Series (countable_sum a)) as Heq.\n    { rewrite /a'. by eapply Series_incr_1_aux. }\n    rewrite -Heq.\n    eapply is_series_ext; last eassumption.\n    intros n. rewrite /a'/countable_sum/σ'//=.\n    destruct (@pickle_inv (option_countType X) n) as [[s|]|] eqn:Heqs.\n    ** rewrite pickleK_inv //=.\n    ** rewrite //=.\n    ** rewrite //=.\nQed.\n\nLemma countable_Series_oapp' {X: countType}\n      (a: X → R):\n  ex_series (countable_sum (λ n, Rabs (a n))) →\n  Series (countable_sum a) = Series (countable_sum (oapp a R0)).\nProof.\n  intros (v&Hex).\n  edestruct (countable_series_oapp' a); eauto.\n  symmetry. apply is_series_unique; eauto.\nQed.\n\nRemark gt_support_conv {X: countType} (b: X → R): ∀ x, b x > 0 → support b.\nProof.\n  intros x Hgt. exists x. destruct (Rgt_dec (b x) 0); auto.\nDefined.\n\nLemma countable_series_rearrange_covering_match {X Y: countType}\n      (a: X → R) (b: Y → R) (σ: support b → support a)\n      (Hapos: ∀ x, a x >= 0)\n      (Hbpos: ∀ x, b x >= 0)\n      (INJ: ∀ n n', σ n = σ n' → n = n')\n      (COV: ∀ n, ∃ m, σ m = n)\n      (EQ: ∀ n, a (sval (σ n)) = b (sval n))\n      (v: R):\n  is_series (countable_sum (λ n, a n)) v →\n  is_series (countable_sum (λ n, b n)) v.\nProof.\n  intros His.\n  set (σ':=\n         λ y, match Rgt_dec (b y) 0 with\n              | left Hpf =>\n                Some (sval (σ (gt_support_conv _ _ Hpf)))\n              | _  => None\n              end).\n    cut (is_series (countable_sum (λ n, Rabs (oapp a R0 (σ' n)))) v).\n    { intros Hext. eapply is_series_ext; last eapply Hext.\n      intros n. rewrite /countable_sum/σ'//=.\n      destruct pickle_inv as [s|] => //=.\n      { destruct Rgt_dec => //=.\n        * rewrite EQ //=; try nra.\n          rewrite Rabs_right; nra.\n        * rewrite Rabs_R0. destruct (Hbpos s); nra.\n      }\n    }\n  edestruct (countable_series_rearrange_covering (oapp a R0) σ').\n  { rewrite /σ'. intros n n'. do 2 destruct Rgt_dec => //=.\n    intros Hneq0 Heq. inversion Heq as [Heq']. apply sval_inj_pi in Heq'. eapply INJ in Heq'.\n    inversion Heq'. done.\n  }\n  { intros [s|] => //=. intros Hneq0.\n    destruct (Hapos s) as [Hgt0|Heq0]; last nra.\n    destruct (COV (gt_support_conv a s Hgt0)) as (y&Heqy).\n    exists (sval y). rewrite /σ'.\n    destruct Rgt_dec as [|Hngt]; last first.\n    { destruct y as (y&Hgt). simpl in Hngt. exfalso. clear -Hngt Hgt. destruct Rgt_dec; auto. }\n    f_equal. transitivity (sval (σ y)).\n    { do 2 f_equal. apply sval_inj_pred => //=. }\n    rewrite Heqy => //=.\n  }\n  { edestruct (countable_series_oapp' a).\n    { eapply is_series_ext; last eassumption.\n      rewrite /countable_sum => n. destruct (@pickle_inv X n) => //=.\n      rewrite Rabs_right; eauto.\n    }\n    eauto.\n  }\n  eauto.\nQed.\n\nLemma countable_series_rearrange_covering_match_fun {X Y: countType}\n      (a: X → R) (b: Y → R) (σ: {x : Y | b x ≠ 0} → { x : X | a x ≠ 0 })\n   (*   (Hapos: ∀ x, a x >= 0)\n      (Hbpos: ∀ x, b x >= 0)  *)\n      (INJ: ∀ n n', σ n = σ n' → n = n')\n      (COV: ∀ n, ∃ m, σ m = n)\n      (EQ: ∀ n, a (sval (σ n)) = b (sval n))\n      (v: R):\n  is_series (countable_sum (λ n, Rabs (a n))) v →\n  is_series (countable_sum (λ n, Rabs (b n))) v ∧\n  is_series (countable_sum b) (Series (countable_sum a)).\nProof.\n  intros His.\n  set (σ':=\n         λ y, match Req_EM_T (b y) 0 with\n              | right Hpf =>\n                Some (sval (σ (exist _ y Hpf)))\n              | _  => None\n              end).\n  assert (Hext0: ∀ n : nat, countable_sum (λ n0 : Y, (oapp a R0 (σ' n0))) n\n                           = countable_sum (λ n0 : Y, (b n0)) n).\n  {\n      intros n. rewrite /countable_sum/σ'//=.\n      destruct pickle_inv as [s|] => //=.\n      { destruct Req_EM_T as [Heq0|Hneq0] => //=.\n        rewrite //=. eapply EQ.\n      }\n  }\n  cut (is_series (countable_sum (λ n, Rabs (oapp a R0 (σ' n)))) v ∧\n       is_series (countable_sum (λ n, oapp a R0 (σ' n))) (Series (countable_sum a))).\n  { intros (Hext_abs&Hext). split.\n    * eapply is_series_ext; last eapply Hext_abs.\n      intros n. rewrite ?countable_sum_Rabs. f_equal; eauto.\n    * eapply is_series_ext; last eapply Hext.\n      intros n. eauto.\n  }\n  edestruct (countable_series_rearrange_covering (oapp a R0) σ').\n  { rewrite /σ'. intros n n'. do 2 destruct Req_EM_T => //=.\n    intros Hneq0 Heq. inversion Heq as [Heq']. apply sval_inj_pi in Heq'. eapply INJ in Heq'.\n    inversion Heq'. done.\n  }\n  { intros [s|] => //=. intros Hneq0.\n    destruct (COV (exist _ s Hneq0)) as (y&Heqy).\n    exists (sval y). rewrite /σ'.\n    destruct Req_EM_T as [Hngt|].\n    { destruct y as (y&Hgt). simpl in Hngt. exfalso. clear -Hngt Hgt. congruence. }\n    f_equal. transitivity (sval (σ y)).\n    { do 2 f_equal. apply sval_inj_pi => //=. }\n    rewrite Heqy => //=.\n  }\n  { edestruct (countable_series_oapp' a).\n    { eapply is_series_ext; last eassumption.\n      rewrite /countable_sum => n. destruct (@pickle_inv X n) => //=.\n    }\n    eauto.\n  }\n  split; eauto.\n  rewrite countable_Series_oapp'; eauto.\n  eexists; eauto.\nQed.\n", "meta": {"author": "jtassarotti", "repo": "coq-proba", "sha": "11d69b2286940ff532421252a7d9b1384c2f674a", "save_path": "github-repos/coq/jtassarotti-coq-proba", "path": "github-repos/coq/jtassarotti-coq-proba/coq-proba-11d69b2286940ff532421252a7d9b1384c2f674a/theories/prob/rearrange.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225577, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6614266370382095}}
{"text": "From CoqMTL Require Export Base.\n\n(** This module aims to check whether [Applicative]'s laws are orthogonal,\n    i.e. independent from each other. We take an axiomatic approach.\n\n    First we postulate the existence of a thing [F] that has some functions\n    named [fmap], [pure] and [ap]. *)\n\nAxiom\n  (F : Type -> Type)\n  (fmap : forall {A B : Type}, (A -> B) -> F A -> F B)\n  (pure : forall {A : Type}, A -> F A)\n  (ap : forall {A B : Type}, F (A -> B) -> F A -> F B).\n\n(** We introduce familiar notations. *)\n\nNotation \"f <*> x\" := (ap f x)\n  (left associativity, at level 40).\n\n(** Then we define various laws that this [F] can possibly satisfy. *)\n\nDefinition fmap_id : Prop :=\n  forall A : Type, fmap (@id A) = id.\n\nDefinition fmap_comp : Prop :=\n  forall (A B C : Type) (f : A -> B) (g : B -> C),\n    fmap (f .> g) = fmap f .> fmap g.\n\nDefinition identity : Prop :=\n  forall (A : Type) (ax : F A), ap (pure id) ax = ax.\n\nDefinition composition : Prop :=\n  forall (A B C : Type) (af : F (A -> B)) (ag : F (B  -> C)) (ax : F A),\n    ap (ap (ap (pure compose) ag) af) ax = ap ag (ap af ax).\n\nDefinition homomorphism : Prop :=\n  forall (A B : Type) (f : A -> B) (x : A),\n    ap (pure f) (pure x) = pure (f x).\n\nDefinition interchange : Prop :=\n  forall (A B : Type) (f : F (A -> B)) (x : A),\n    ap f (pure x) = ap (pure (fun f => f x)) f.\n\nDefinition fmap_pure_ap : Prop :=\n  forall (A B : Type) (f : A -> B) (x : F A),\n    fmap f x = ap (pure f) x.\n\n(** This law is some kind of alternative for [fmap_pure_ap]. *)\nDefinition fmap_pure : Prop :=\n  forall (A B : Type) (f : A -> B) (x : A),\n    fmap f (pure x) = pure (f x).\n\n(** Finally we try to derive some of these laws from others. It turns out\n    that [identity] follows from [fmap_pure_ap] and the functor laws. *)\n\nLemma identity' :\n  fmap_pure_ap -> fmap_id -> identity.\nProof.\n  compute. intros fmap_pure_ap fmap_id A x.\n  rewrite <- fmap_pure_ap, fmap_id. reflexivity.\nQed.\n\nLemma homomorphism' :\n  fmap_pure_ap -> fmap_pure -> homomorphism.\nProof.\n  compute. intros fmap_pure_ap fmap_pure A B f x.\n  rewrite <- fmap_pure_ap, fmap_pure. reflexivity.\nQed.\n\nLemma fmap_id' :\n  fmap_pure_ap -> identity -> fmap_id.\nProof.\n  compute. intros fmap_pure_ap identity A.\n  ext a. rewrite fmap_pure_ap, identity.\n  reflexivity.\nQed.\n\nLemma fmap_pure' :\n  fmap_pure_ap -> homomorphism -> fmap_pure.\nProof.\n  compute. intros fmap_pure_ap homomorphism A B f x.\n  rewrite fmap_pure_ap, homomorphism. reflexivity.\nQed.", "meta": {"author": "wkolowski", "repo": "coq-mtl", "sha": "e3ecb0cf0378e62816d391783e7421d769aec26b", "save_path": "github-repos/coq/wkolowski-coq-mtl", "path": "github-repos/coq/wkolowski-coq-mtl/coq-mtl-e3ecb0cf0378e62816d391783e7421d769aec26b/Theory/Laws/ApplicativeLaws.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6614266370382094}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nFrom adtind Require Import goal20.\n\nSet Printing Depth 1000.\nDefinition lfind_eval  x n:=\nCons n x.\n\nCompute lfind_eval  (Cons (Succ (Succ (Succ Zero))) (Cons Zero Nil)) (Zero).\n\nCompute lfind_eval  (Cons Zero (Cons (Succ (Succ (Succ Zero))) Nil)) (Zero).\n\nCompute lfind_eval  (Nil) (Succ (Succ Zero)).\n\nCompute lfind_eval  (Cons (Succ Zero) (Cons (Succ (Succ (Succ Zero))) Nil)) (Zero).\n\nCompute lfind_eval  (Cons (Succ Zero) Nil) (Succ Zero).\n\nCompute lfind_eval  (Cons (Succ Zero) (Cons (Succ (Succ Zero)) Nil)) (Succ (Succ Zero)).\n\nCompute lfind_eval  (Cons (Succ (Succ (Succ Zero))) (Cons (Succ (Succ Zero)) Nil)) (Succ Zero).\n\nCompute lfind_eval  (Cons Zero (Cons (Succ Zero) (Cons Zero Nil))) (Succ (Succ (Succ Zero))).\n\nCompute lfind_eval  (Cons (Succ Zero) Nil) (Zero).\n\nCompute lfind_eval  (Nil) (Succ Zero).\n\nCompute lfind_eval  (Cons Zero (Cons Zero Nil)) (Zero).\n\nCompute lfind_eval  (Nil) (Succ (Succ (Succ (Succ Zero)))).\n\nCompute lfind_eval  (Cons Zero Nil) (Succ Zero).\n\nCompute lfind_eval  (Cons Zero (Cons (Succ Zero) (Cons Zero Nil))) (Zero).\n\nCompute lfind_eval  (Cons Zero Nil) (Zero).\n\nCompute lfind_eval  (Cons (Succ Zero) (Cons Zero Nil)) (Zero).\n\nCompute lfind_eval  (Cons Zero Nil) (Succ (Succ Zero)).\n\nCompute lfind_eval  (Cons Zero (Cons Zero (Cons Zero (Cons Zero (Cons (Succ Zero) Nil))))) (Zero).\n\nCompute lfind_eval  (Nil) (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_goal20_theorem0_40_lem/lfind_eval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6614266344063408}}
{"text": "Require Import BenB.\n\n(*\n  Eerst leggen we de basisproposities vast.\n*)\n\nVariable G1: Prop. (* Het goud zit in koffer 1. *)\nVariable G2: Prop. (* Het goud zit in koffer 2. *)\nVariable G3: Prop. (* Het goud zit in koffer 3. *)\nVariable G4: Prop. (* Het goud zit in koffer 4. *)\n\n(* \n  Daarna leggen we de daaruit afgeleide uitspraken vast.\n*)\n  \nDefinition K1 := G2     . (* Het goud zit in koffer 2. *)\nDefinition K2 := ~G1 /\\ ~G3 /\\ ~G4      . (* Alle andere koffers zijn leeg. *)\nDefinition K3 := G3     . (* Deze koffer bevat goud. *)\nDefinition K4 := ~G4      . (* Deze koffer is leeg. *)\n\n(* \n  En vervolgens maken we wat hulpdefinities.\n\n  Vul de definities aan waar dat nodig is!\n*)\n\nDefinition erIsMinimaalEenKofferMetGoud :=\nG1 \\/ G2 \\/ G3 \\/ G4.\n\nDefinition erIsMaximaalEenKofferMetGoud :=\n~(G1\\/G2\\/G3) \\/ ~(G1\\/G2\\/G4) \\/ ~(G1\\/G3\\/G4) \\/ ~(G2\\/G3\\/G4).\n\nDefinition erIsPreciesEenKofferMetGoud :=\n  erIsMinimaalEenKofferMetGoud\n/\\\n  erIsMaximaalEenKofferMetGoud\n.\n\nDefinition erIsMinimaalEenKofferMetEenWareUitspraak :=\nK1 \\/ K2 \\/ K3 \\/ K4.\n\nDefinition erIsMaximaalEenKofferMetEenWareUitspraak :=\n~(K1\\/K2\\/K3) \\/ ~(K1\\/K2\\/K4) \\/ ~(K1\\/K3\\/K4) \\/ ~(K2\\/K3\\/K4).\n\nDefinition erIsPreciesEenKofferMetEenWareUitspraak :=\n  erIsMinimaalEenKofferMetEenWareUitspraak\n/\\\n  erIsMaximaalEenKofferMetEenWareUitspraak\n.\n\n\nTheorem deOplossingIs :\n    erIsPreciesEenKofferMetGoud\n/\\\n    erIsPreciesEenKofferMetEenWareUitspraak\n->\n    G1 (* Geef hier aan in welke koffer het goud zit. *)\n    /\\\n    K4  (* Geef hier aan op welke koffer de ware uitspraak staat. *)\n.\nProof.\nunfold erIsPreciesEenKofferMetGoud.\nunfold erIsMinimaalEenKofferMetGoud.\nunfold erIsMaximaalEenKofferMetGoud.\nunfold erIsPreciesEenKofferMetEenWareUitspraak.\nunfold erIsMinimaalEenKofferMetEenWareUitspraak.\nunfold erIsMaximaalEenKofferMetEenWareUitspraak.\nunfold K1.\nunfold K2.\nunfold K3.\nunfold K4.\ntauto.\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/Taak03/Taak03_kofferpuzzel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6614266242035589}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(***********************************************************************\n      UList.v                                                                                       \n                                                                                                         \n      Definition of list with distinct elements                                 \n                                                                                                         \n      Definition: ulist                                                                         \n************************************************************************)\nRequire Import List.\nRequire Import Arith.\nRequire Import Permutation.\nRequire Import ListSet.\n \nSection UniqueList.\nVariable A : Set.\nVariable eqA_dec : forall (a b : A),  ({ a = b }) + ({ a <> b }).\n(* A list is unique if there is not twice the same element in the list *)\n \nInductive ulist : list A ->  Prop :=\n  ulist_nil: ulist nil\n | ulist_cons: forall a l, ~ In a l -> ulist l ->  ulist (a :: l) .\nHint Constructors ulist : core.\n(* Inversion theorem *)\n \nTheorem ulist_inv: forall a l, ulist (a :: l) ->  ulist l.\nintros a l H; inversion H; auto.\nQed.\n(* The append of two unique list is unique if the list are distinct *)\n \nTheorem ulist_app:\n forall l1 l2,\n ulist l1 ->\n ulist l2 -> (forall (a : A), In a l1 -> In a l2 ->  False) ->  ulist (l1 ++ l2).\nintros L1; elim L1; simpl; auto.\nintros a l H l2 H0 H1 H2; apply ulist_cons; simpl; auto.\nred; intros H3; case in_app_or with ( 1 := H3 ); auto; intros H4.\ninversion H0; auto.\napply H2 with a; auto.\napply H; auto.\napply ulist_inv with ( 1 := H0 ); auto.\nintros a0 H3 H4; apply (H2 a0); auto.\nQed.\n(* Iinversion theorem the appended list *)\n \nTheorem ulist_app_inv:\n forall l1 l2 (a : A), ulist (l1 ++ l2) -> In a l1 -> In a l2 ->  False.\nintros l1; elim l1; simpl; auto.\nintros a l H l2 a0 H0 [H1|H1] H2.\ninversion H0 as [|a1 l0 H3 H4 H5]; auto.\ncase H3; rewrite H1; auto with datatypes.\napply (H l2 a0); auto.\napply ulist_inv with ( 1 := H0 ); auto.\nQed.\n(* Iinversion theorem the appended list *)\n \nTheorem ulist_app_inv_l: forall (l1 l2 : list A), ulist (l1 ++ l2) ->  ulist l1.\nintros l1; elim l1; simpl; auto.\nintros a l H l2 H0.\ninversion H0 as [|il1 iH1 iH2 il2 [iH4 iH5]]; apply ulist_cons; auto.\nintros H5; case iH2; auto with datatypes.\napply H with l2; auto.\nQed.\n(* Iinversion theorem the appended list *)\n \nTheorem ulist_app_inv_r: forall (l1 l2 : list A), ulist (l1 ++ l2) ->  ulist l2.\nintros l1; elim l1; simpl; auto.\nintros a l H l2 H0; inversion H0; auto.\nQed.\n(* Uniqueness is decidable *)\n \nDefinition ulist_dec: forall l,  ({ ulist l }) + ({ ~ ulist l }).\nintros l; elim l; auto.\nintros a l1 [H|H]; auto.\ncase (In_dec eqA_dec a l1); intros H2; auto.\nright; red; intros H1; inversion H1; auto.\nright; intros H1; case H; apply ulist_inv with ( 1 := H1 ).\nDefined.\n(* Uniqueness is compatible with permutation *)\n \nTheorem ulist_perm:\n forall (l1 l2 : list A), permutation l1 l2 -> ulist l1 ->  ulist l2.\nintros l1 l2 H; elim H; clear H l1 l2; simpl; auto.\nintros a l1 l2 H0 H1 H2; apply ulist_cons; auto.\ninversion_clear H2 as [|ia il iH1 iH2 [iH3 iH4]]; auto.\nintros H3; case iH1;\n apply permutation_in with ( 1 := permutation_sym _ _ _ H0 ); auto.\ninversion H2; auto.\nintros a b L H0; apply ulist_cons; auto.\ninversion_clear H0 as [|ia il iH1 iH2]; auto.\ninversion_clear iH2 as [|ia il iH3 iH4]; auto.\nintros H; case H; auto.\nintros H1; case iH1; rewrite H1; simpl; auto.\napply ulist_cons; auto.\ninversion_clear H0 as [|ia il iH1 iH2]; auto.\nintros H; case iH1; simpl; auto.\ninversion_clear H0 as [|ia il iH1 iH2]; auto.\ninversion iH2; auto.\nQed.\n \nTheorem ulist_def:\n forall l a,\n In a l -> ulist l ->  ~ (exists l1 , permutation l (a :: (a :: l1)) ).\nintros l a H H0 [l1 H1].\nabsurd (ulist (a :: (a :: l1))); auto.\nintros H2; inversion_clear H2; simpl; auto with datatypes.\napply ulist_perm with ( 1 := H1 ); auto.\nQed.\n \nTheorem ulist_incl_permutation:\n forall (l1 l2 : list A),\n ulist l1 -> incl l1 l2 ->  (exists l3 , permutation l2 (l1 ++ l3) ).\nintros l1; elim l1; simpl; auto.\nintros l2 H H0; exists l2; simpl; auto.\nintros a l H l2 H0 H1; auto.\ncase (in_permutation_ex _ a l2); auto with datatypes.\nintros l3 Hl3.\ncase (H l3); auto.\napply ulist_inv with ( 1 := H0 ); auto.\nintros b Hb.\nassert (H2: In b (a :: l3)).\napply permutation_in with ( 1 := permutation_sym _ _ _ Hl3 );\n auto with datatypes.\nsimpl in H2 |-; case H2; intros H3; simpl; auto.\ninversion_clear H0 as [|c lc Hk1]; auto.\ncase Hk1; subst a; auto.\nintros l4 H4; exists l4.\napply permutation_trans with (a :: l3); auto.\napply permutation_sym; auto.\nQed.\n \nTheorem ulist_eq_permutation:\n forall (l1 l2 : list A),\n ulist l1 -> incl l1 l2 -> length l1 = length l2 ->  permutation l1 l2.\nintros l1 l2 H1 H2 H3.\ncase (ulist_incl_permutation l1 l2); auto.\nintros l3 H4.\nassert (H5: l3 = @nil A).\ngeneralize (permutation_length _ _ _ H4); rewrite length_app; rewrite H3.\nrewrite plus_comm; case l3; simpl; auto.\nintros a l H5; absurd (lt (length l2) (length l2)); auto with arith.\npattern (length l2) at 2; rewrite H5; auto with arith.\nreplace l1 with (app l1 l3); auto.\napply permutation_sym; auto.\nrewrite H5; rewrite app_nil_end; auto.\nQed.\n \n\nTheorem ulist_incl_length:\n forall (l1 l2 : list A), ulist l1 -> incl l1 l2 ->  le (length l1) (length l2).\nintros l1 l2 H1 Hi; case ulist_incl_permutation with ( 2 := Hi ); auto.\nintros l3 Hl3; rewrite permutation_length with ( 1 := Hl3 ); auto.\nrewrite length_app; simpl; auto with arith.\nQed.\n\nTheorem ulist_incl2_permutation:\n forall (l1 l2 : list A),\n ulist l1 -> ulist l2 -> incl l1 l2 -> incl l2 l1  ->  permutation l1 l2.\nintros l1 l2 H1 H2 H3 H4.\napply ulist_eq_permutation; auto.\napply le_antisym; apply ulist_incl_length; auto.\nQed.\n \n \nTheorem ulist_incl_length_strict:\n forall (l1 l2 : list A),\n ulist l1 -> incl l1 l2 -> ~ incl l2 l1 ->  lt (length l1) (length l2).\nintros l1 l2 H1 Hi Hi0; case ulist_incl_permutation with ( 2 := Hi ); auto.\nintros l3 Hl3; rewrite permutation_length with ( 1 := Hl3 ); auto.\nrewrite length_app; simpl; auto with arith.\ngeneralize Hl3; case l3; simpl; auto with arith.\nrewrite <- app_nil_end; auto.\nintros H2; case Hi0; auto.\nintros a HH; apply permutation_in with ( 1 := H2 ); auto.\nintros a l Hl0; (rewrite plus_comm; simpl; rewrite plus_comm; auto with arith).\nQed.\n \nTheorem in_inv_dec:\n forall (a b : A) l, In a (cons b l) ->  a = b \\/ ~ a = b /\\ In a l.\nintros a b l H; case (eqA_dec a b); auto; intros H1.\nright; split; auto; inversion H; auto.\ncase H1; auto.\nQed.\n \nTheorem in_ex_app_first:\n forall (a : A) (l : list A),\n In a l ->\n  (exists l1 : list A , exists l2 : list A , l = l1 ++ (a :: l2) /\\ ~ In a l1  ).\nintros a l; elim l; clear l; auto.\nintros H; case H.\nintros a1 l H H1; auto.\ngeneralize (in_inv_dec _ _ _ H1); intros [H2|[H2 H3]].\nexists (nil (A:=A)); exists l; simpl; split; auto.\nsubst; auto.\ncase H; auto; intros l1 [l2 [Hl2 Hl3]]; exists (a1 :: l1); exists l2; simpl;\n split; auto.\nsubst; auto.\nintros H4; case H4; auto.\nQed.\n \nTheorem ulist_inv_ulist:\n forall (l : list A),\n ~ ulist l ->\n  (exists a ,\n   exists l1 ,\n   exists l2 ,\n   exists l3 , l = l1 ++ ((a :: l2) ++ (a :: l3)) /\\ ulist (l1 ++ (a :: l2))    ).\nintros l; elim l  using list_length_ind; clear l.\nintros l; case l; simpl; auto; clear l.\nintros Rec H0; case H0; auto.\nintros a l H H0.\ncase (In_dec eqA_dec a l); intros H1; auto.\ncase in_ex_app_first with ( 1 := H1 ); intros l1 [l2 [Hl1 Hl2]]; subst l.\ncase (ulist_dec l1); intros H2.\nexists a; exists (@nil A); exists l1; exists l2; split; auto.\nsimpl; apply ulist_cons; auto.\ncase (H l1); auto.\nrewrite length_app; auto with arith.\nintros b [l3 [l4 [l5 [Hl3 Hl4]]]]; subst l1.\nexists b; exists (a :: l3); exists l4; exists (l5 ++ (a :: l2)); split; simpl;\n auto.\n(repeat (rewrite <- ass_app; simpl)); auto.\napply ulist_cons; auto.\ncontradict Hl2; auto.\nreplace (l3 ++ (b :: (l4 ++ (b :: l5)))) with ((l3 ++ (b :: l4)) ++ (b :: l5));\n auto with datatypes.\n(repeat (rewrite <- ass_app; simpl)); auto.\ncase (H l); auto; intros a1 [l1 [l2 [l3 [Hl3 Hl4]]]]; subst l.\nexists a1; exists (a :: l1); exists l2; exists l3; split; auto.\nsimpl; apply ulist_cons; auto.\ncontradict H1.\nreplace (l1 ++ (a1 :: (l2 ++ (a1 :: l3))))\n     with ((l1 ++ (a1 :: l2)) ++ (a1 :: l3)); auto with datatypes.\n(repeat (rewrite <- ass_app; simpl)); auto.\nQed.\n \nTheorem incl_length_repetition:\n forall (l1 l2 : list A),\n incl l1 l2 ->\n lt (length l2) (length l1) ->\n  (exists a ,\n   exists ll1 ,\n   exists ll2 ,\n   exists ll3 ,\n   l1 = ll1 ++ ((a :: ll2) ++ (a :: ll3)) /\\ ulist (ll1 ++ (a :: ll2))    ).\nintros l1 l2 H H0; apply ulist_inv_ulist.\nintros H1; absurd (le (length l1) (length l2)); auto with arith.\napply ulist_incl_length; auto.\nQed.\n \nEnd UniqueList.\nArguments ulist [A].\nGlobal Hint Constructors ulist : core.\n \nTheorem ulist_map:\n forall (A B : Set) (f : A ->  B) l,\n (forall x y, (In x l) -> (In y l) ->  f x = f y ->  x = y) -> ulist l ->  ulist (map f l).\nintros a b f l Hf Hl; generalize Hf; elim Hl; clear Hf;  auto.\nsimpl; auto.\nintros a1 l1 H1 H2 H3 Hf; simpl.\napply ulist_cons; auto with datatypes.\ncontradict H1.\ncase in_map_inv with ( 1 := H1 ); auto with datatypes.\nintros b1 [Hb1 Hb2].\nreplace a1 with b1; auto with datatypes.\nQed.\n \nTheorem ulist_list_prod:\n forall (A : Set) (l1 l2 : list A),\n ulist l1 -> ulist l2 ->  ulist (list_prod l1 l2).\nintros A l1 l2 Hl1 Hl2; elim Hl1; simpl; auto.\nintros a l H1 H2 H3; apply ulist_app; auto.\napply ulist_map; auto.\nintros x y _ _ H; inversion H; auto.\nintros p Hp1 Hp2; case H1.\ncase in_map_inv with ( 1 := Hp1 ); intros a1 [Ha1 Ha2]; auto.\ncase in_list_prod_inv with ( 1 := Hp2 ); intros b1 [c1 [Hb1 [Hb2 Hb3]]]; auto.\nreplace a with b1; auto.\nrewrite Ha2 in Hb1; injection Hb1; auto.\nQed.\n", "meta": {"author": "dderjoel", "repo": "base", "sha": "2aa122fb618100b7fed3119ea3cef73cec5bf4a5", "save_path": "github-repos/coq/dderjoel-base", "path": "github-repos/coq/dderjoel-base/base-2aa122fb618100b7fed3119ea3cef73cec5bf4a5/fiat-crypto/coqprime/src/Coqprime/List/UList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.661426618196391}}
{"text": "Require Import Arith List Recdef.\nImport ListNotations.\nFixpoint ltn_rec (l : list bool) : nat :=\n  match l with \n    nil => 0 \n  | a::tl => (if a then 1 else 0) + 2 * ltn_rec tl\n  end.\n\nDefinition ltn (l : list bool) := ltn_rec (rev l).\n\nDefinition testing_liste := [true;true;true].\nCompute ltn testing_liste.\n\nFunction ntl (n : nat) {wf lt} :=\n  match n with\n    0 => nil\n  | S p =>  negb (Nat.even n) :: ntl (Nat.div2 n)\n  end.\nintros n p nsp; apply Nat.lt_div2.\nauto with arith.\nexact lt_wf.\nQed.\n\nLemma toto : ntl 32 = false::false::false::false::false::true::nil.\nrewrite 7!ntl_equation; simpl; reflexivity.\nQed.\n\nLemma titi n : ltn (ntl n) = n.\nProof.\ninduction n using (well_founded_ind lt_wf).\nrewrite ntl_equation.\ncase_eq n.\n  trivial.\nintros p n_is_Sp.\nchange ((if negb (Nat.even (S p)) then 1 else 0) +\n        2 * ltn (ntl (Nat.div2 (S p))) = S p).\nrewrite H; cycle 1.\n  rewrite n_is_Sp; apply Nat.lt_div2; auto with arith.\n\nLemma toto : ntl 4 = true::false::false::nil.\nrewrite 4!ntl_equation; simpl.\nCheck ntl_terminate.\nSearch Nat.div2.\nSearch (list bool).\nCheck Nat.bitwise.\n\n\nDefinition ntl (n : nat) :=\n  Fix lt_wf (fun _ => list bool)\n  (fun x ntl =>\n     match zerop x with\n       left _ => nil\n     | right h => negb(Nat.even x) :: \n                  ntl (Nat.div2 x) (Nat.lt_div2 _ h)\nend).\n\nCheck Fix.\n\n", "meta": {"author": "romisfrag", "repo": "little_mmx_encode-decode", "sha": "9f5a583fc2376f271bac30ec82c8800614a5fdd6", "save_path": "github-repos/coq/romisfrag-little_mmx_encode-decode", "path": "github-repos/coq/romisfrag-little_mmx_encode-decode/little_mmx_encode-decode-9f5a583fc2376f271bac30ec82c8800614a5fdd6/srcOld2/exercises2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.6614266140007771}}
{"text": "Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice fintype fingraph  finfun  finset.\n\nRequire Import misc.\nRequire Import regexp.\n\nSet Implicit Arguments.\n\n(** Finite automata. ***)\nSection FA.\n\nVariable char: finType.\n\n(** Type of input sequences ***)\nDefinition word := misc.word char.\n\n(** Deterministic finite automata. **)\nSection DFA.\n\n(** The type of deterministic finite automata. ***)\nRecord dfa : Type :=\n  {\n    dfa_state :> finType;\n    dfa_s: dfa_state;\n    dfa_fin: pred dfa_state;\n    dfa_step: dfa_state -> char -> dfa_state\n    }.\n\n\n(** Acceptance on DFAs **)\nSection Acceptance.\n\n(** Assume some automaton **)\nVariable A: dfa.\n\n(** We define a run of w on the automaton A\n   to be the list of states x_1 .. x_|w|\n   traversed when following the edges labeled\n   w_1 .. w_|w| starting in x. **)\nFixpoint dfa_run' (x: A) (w: word) : seq A :=\nmatch w with\n  | [::] => [::]\n  | a::w => (dfa_step A x a) ::dfa_run' (dfa_step A x a) w\nend.\n\n(** A simplifying function for a \"aux2\" run\n   (i.e. starting at s). **)\nDefinition dfa_run := [fun w => dfa_run' (dfa_s A) w].\n\n(** Acceptance of w in x is defined as\n   finality of the last state of a run of w on A\n   starting in x. **)\nFixpoint dfa_accept x w :=\nmatch w with\n  | [::] => dfa_fin A x\n  | a::w => dfa_accept (dfa_step A x a) w\nend.\n\nLemma dfa_accept_cons x a w:\n  a::w \\in dfa_accept x = (w \\in dfa_accept (dfa_step A x a)).\nProof. by rewrite -simpl_predE /=. Qed.\n\n(** We define the language of the deterministic\n   automaton, i.e. acceptance in the starting state. **)\nDefinition dfa_lang := [pred w | dfa_accept (dfa_s A) w].\n\n(** take lemma. **)\nLemma dfa_run'_take x w n: take n (dfa_run' x w) = dfa_run' x (take n w).\nProof. elim: w x n => [|a w IHw] x n //.\ncase: n => [|n] //=. by rewrite IHw.\nQed.\n\n(** rcons and cat lemmas. **)\nLemma dfa_run'_cat x w1 w2 :\n  dfa_run' x (w1 ++ w2) = dfa_run' x w1 ++ dfa_run' (last x (dfa_run' x w1)) w2.\nProof. elim: w1 w2 x => [|a w1 IHw1] w2 x //.\nsimpl. by rewrite IHw1.\nQed.\n\n\n(* slightly altered acceptance statement. *)\nLemma dfa_run_accept x w: last x (dfa_run' x w) \\in dfa_fin A = (w \\in dfa_accept x).\nProof. elim: w x => [|a w IHw] x //. by rewrite /= IHw. Qed.\n\nEnd Acceptance.\n\nEnd DFA.\n\nImplicit Arguments Build_dfa [dfa_state]. \n\n\n(** Non-deterministic automata. **)\nSection NFA.\n\n(** The type of non-deterministic finite automata. ***)\nRecord nfa : Type :=\n  {\n    nfa_state :> finType;\n    nfa_s: nfa_state;\n    nfa_fin: pred nfa_state;\n    nfa_step: nfa_state -> char -> pred nfa_state\n    }.\n\n(** Acceptance on non-deterministic automata. **)\nSection Acceptance.\n\nVariable A: nfa.\n\n(** Non-deterministic acceptance. **)\nFixpoint nfa_accept (x: A) w :=\nmatch w with\n  | [::] => nfa_fin A x\n  | a::w => [ exists y, (nfa_step A x a y) && nfa_accept y w ]\nend.\n\n(** We define the language of the non-deterministic\n   automaton, i.e. acceptance in the starting state. **)\nDefinition nfa_lang := [pred w | nfa_accept (nfa_s A) w].\n\n(** We define labeled paths over the non-deterministic step relation **)\nFixpoint nfa_run x (xs : seq A) (w: word) {struct xs} :=\nmatch xs,w with\n  | y :: xs', a::w' => nfa_step A x a y && nfa_run y xs' w'\n  | [::]    , [::]  => true\n  | _       , _     => false\nend.\n\nLemma nfa_run_accept x w:\n  reflect (exists2 xs, nfa_run x xs w & last x xs \\in nfa_fin A)\n          (nfa_accept x w).\nProof.\n  elim: w x => [|a w IHw] x.\n    case H: (nfa_accept x [::]); constructor.\n      by exists [::].\n    move => [[|y xs]] //.\n    move: H => /= H _.\n    by rewrite -topredE /= H.\n  case H: nfa_accept => /=; constructor.\n    move/existsP: H => [] y /andP [] H1 /IHw [] xs H2 H3.\n    exists (y::xs) => //=.\n    by rewrite H1 H2 /=.\n  move => [[|y xs]] //= /andP [] H1 H2 H3.\n  move/existsP: H => H.\n  apply: H. exists y.\n  rewrite H1 /=.\n  apply/IHw.\n  by exists xs.\nQed.\n \n\n(** Helpful facts **)\nLemma nfa_accept_cat x w1 w2:\n  nfa_accept x (w1 ++ w2) <->\n  exists xs,\n    nfa_run x xs w1\n    && nfa_accept (last x xs) w2.\nProof. split.\n  elim: w1 w2 x => [|a w1 IHw1] w2 x.\n    simpl. exists [::]. simpl. exact: H.\n  move/existsP => [] y /andP [] H0 /IHw1 [] ys /andP [] H1 H2.\n  exists (y::ys) => /=. by rewrite H0 H1 H2.\nelim: w1 w2 x => [|a w1 IHw1] w2 x; move => [] [|y ys] /andP [] H0 H1 //.\nmove: H0 => /= /andP [] H2 H3. \napply/existsP. exists y. rewrite H2 /=.\napply: IHw1.\nexists ys. by rewrite H3 H1.\nQed.\n\nEnd Acceptance.\n\nEnd NFA.\n\nImplicit Arguments Build_nfa [nfa_state]. \n\n(** We define the powerset construction to obtain\n   a deterministic automaton from a non-deterministic one. **) \nSection PowersetConstruction.\n\nVariable A: nfa.\n\nDefinition nfa_to_dfa :=\n  {| dfa_s := set1 (nfa_s A);\n    dfa_fin := [ pred X: {set A} | [ exists x: A, (x \\in X) && nfa_fin A x] ];\n    dfa_step := [ fun X a => \\bigcup_(x | x \\in X) finset (nfa_step A x a) ]\n   |}.\n\n(** We prove that for every state x, the new automaton\n   accepts at least the language of the given automaton\n   when starting in a set containing x. **)\nLemma nfa_to_dfa_aux2 (x: A) w (X: nfa_to_dfa):\n  x \\in X -> nfa_accept A x w -> dfa_accept nfa_to_dfa X w.\nProof. move => H0.\n  elim: w X x H0 => [|a w IHw] X x H0.\n    (* [::] *)\n    move => /= H1. apply/existsP. exists x.\n    by rewrite H0 H1.\n  (* a::w *)\n  move => /= /existsP [] y /andP [] H1.\n  apply (IHw).\n  apply/bigcupP.\n  exists x => //.\n  by rewrite in_set.\nQed.\n\n(** Next we prove that in any set of states X, for every word w,\n   if the powerset automaton accepts w in X, there exists one\n   representative state of that set in which the given automaton\n   accepts w. **)\nLemma nfa_to_dfa_aux1 (X: nfa_to_dfa) w:\n  dfa_accept nfa_to_dfa X w -> [ exists x, (x \\in X) && nfa_accept A x w ].\nProof. elim: w X => [|a w IHw] X => //.\n  move/IHw => /existsP [] y /andP [].\n  rewrite /dfa_step /nfa_to_dfa. \n  move/bigcupP => [] x H0. rewrite in_set => H1 H2 /=.\n  apply/existsP. exists x. rewrite H0 /=.\n  apply/existsP. exists y. \n  by rewrite H1 H2.\nQed.\n\n(** Finally, we prove that the language of the powerset\n   automaton is exactly the language of the given\n   automaton. **)\nLemma nfa_to_dfa_correct : nfa_lang A =i dfa_lang nfa_to_dfa.\nProof. move => w. apply/idP/idP => /=.\n  apply: nfa_to_dfa_aux2. by apply/set1P.\nby move/nfa_to_dfa_aux1 => /existsP [] x /andP [] /set1P ->.\nQed.\n  \n\nEnd PowersetConstruction.\n\n\n(** Embedding deterministic automata in non-deterministic automata. **)\nSection Embed.\n\nVariable A: dfa.\n\nDefinition dfa_to_nfa : nfa :=\n  {|\n    nfa_s := dfa_s A;\n    nfa_fin := dfa_fin A;\n    nfa_step := fun x a y => y == dfa_step A x a \n  |}.\n\n(** We prove that dfa_to_nfa accepts the same language as\n   the given automaton in any state. **)\nLemma dfa_to_nfa_correct' x w : dfa_accept A x w = nfa_accept dfa_to_nfa x w.\nProof. elim: w x => [|b w IHw] x.\n  by [].\nsimpl. rewrite IHw.\napply/idP/existsP.\n  move => H0. exists (dfa_step A x b). by rewrite eq_refl H0.\nby move => [] y /andP [] /eqP ->.\nQed.\n\n(** We prove that dfa_to_nfa accepts the same language\n   as the given automaton in the starting state, i.e. their\n   languages are equal. **)\nLemma dfa_to_nfa_correct : dfa_lang A =i nfa_lang dfa_to_nfa.\nProof.\n  exact: dfa_to_nfa_correct'.\nQed.\n    \nEnd Embed.\n\n(** Primitive automata **)\nSection Primitive.\n  Definition dfa_void :=\n   {| \n      dfa_s := tt;\n      dfa_fin := pred0;\n      dfa_step := [fun x a => tt]\n   |}.\n  \n  Lemma dfa_void_correct x w: ~~ dfa_accept dfa_void x w.\n  Proof. by elim: w x => [|a w IHw] //= x. Qed.\n\n  Definition dfa_eps :=\n    {|\n      dfa_s := true;\n      dfa_fin := pred1 true;\n      dfa_step := [fun x a => false]\n     |}.\n\n  Lemma dfa_eps_correct: dfa_lang dfa_eps =i pred1 [::].\n  Proof.\n    have H: (forall w, ~~ dfa_accept dfa_eps false w).\n      by elim => [|a v IHv] //=.\n    move => w.\n    elim: w => [|a w IHw] //.\n    apply/idP/idP.\n    exact: H. \n  Qed.\n      \n  Definition dfa_char a :=\n    {|\n      dfa_s := None;\n      dfa_fin := pred1 (Some true);\n      dfa_step := [fun x b => if x == None then if b == a then Some true else Some false else Some false ]\n    |}.\n  \n  Lemma dfa_char_correct'' a w: ~~ dfa_accept (dfa_char a) (Some false) w.\n  Proof. by elim: w => [|b v IHv] //=. Qed.\n  Lemma dfa_char_correct' a w: dfa_accept (dfa_char a) (Some true) w = (w == [::]).\n  Proof.\n    elim: w a => [|b w IHw] a //=.\n    apply/idP/idP.\n    exact: dfa_char_correct''.\n  Qed.\n  Lemma dfa_char_correct a w: dfa_lang (dfa_char a) w = (w == [::a]).\n  Proof.\n    elim: w a => [|b w IHw] a //=.\n    case H: (b == a).\n      move/eqP: H => ->.\n      rewrite dfa_char_correct'.\n      by apply/eqP/eqP => [-> | []].\n    apply/idP/eqP.\n      move => H0. move: (dfa_char_correct'' a w). by rewrite H0.\n    move => [] /eqP. by rewrite H.\n  Qed.\n\n  Definition dfa_dot :=\n    {|\n      dfa_s := None;\n      dfa_fin := pred1 (Some true);\n      dfa_step := [fun x b => if x == None then Some true else Some false ]\n    |}.\n            \n  Lemma dfa_dot_correct'' w: ~~ dfa_accept dfa_dot (Some false) w.\n  Proof. by elim: w => [|b v IHv] //=. Qed.\n  Lemma dfa_dot_correct' w: dfa_accept dfa_dot (Some true) w = (w == [::]).\n  Proof.\n    elim: w => [|b w IHw] //=.\n    apply/idP/idP.\n    exact: dfa_dot_correct''.\n  Qed.\n  Lemma dfa_dot_correct w: dfa_lang dfa_dot w = (size w == 1).\n  Proof.\n    elim: w => [|b w IHw] //=.\n    rewrite dfa_dot_correct'.\n    apply/eqP/eqP => [-> | []] //=.\n    exact: size0nil.\n  Qed.\n\n  \nEnd Primitive.\n\n(** Operations on non-deterministic automata. **)\nSection DFAOps.\n\nVariable A1: dfa.\n\n\n(** Complement automaton **)\n  \n(** We construct the resulting automaton. **)\nDefinition dfa_compl :=\n {| \n    dfa_s := dfa_s A1;\n    dfa_fin := [ fun x1 => ~~ dfa_fin A1 x1 ];\n    dfa_step := (dfa_step A1)\n  |}.\n\n(** We prove that the complement automaton accepts exactly\n   the words not accepted by the original automaton. **)\nLemma dfa_compl_correct' x:\n  [ predC dfa_accept A1 x ] =i dfa_accept dfa_compl x.\nProof. move => w. elim: w x => [|a w IHw] x.  \n    by apply/idP/idP.\n  simpl. rewrite -topredE dfa_accept_cons /= -IHw.\n  apply/negP/idP; rewrite dfa_accept_cons; by move/negP.\nQed.\n\n(** Language correctness for dfa_compl **)\nLemma dfa_compl_correct:\n  [ predC dfa_lang A1 ] =i dfa_lang dfa_compl.\nProof. exact: dfa_compl_correct'. Qed.\n\n  \n(** Operations on two automata. **)\nSection BinaryOps.\n  \nVariable A2: dfa.\n\n(** Disjunction automaton **)\n\nDefinition dfa_disj :=\n  {|\n    dfa_s := (dfa_s A1, dfa_s A2);\n    dfa_fin := (fun q => let (x1,x2) := q in dfa_fin A1 x1 || dfa_fin A2 x2);\n    dfa_step := [fun x a => (dfa_step A1 x.1 a, dfa_step A2 x.2 a)]\n   |}.\n\n(** Correctness w.r.t. any state. **)\nLemma dfa_disj_correct' x:\n  [ predU dfa_accept A1 x.1 & dfa_accept A2 x.2 ]\n    =i dfa_accept dfa_disj x.\nProof. move => w. elim: w x => [|a w IHw].\n  by move => [].\nmove => x /=. by rewrite dfa_accept_cons -IHw.\nQed.\n\n(** Language correctness. **)\nLemma dfa_disj_correct:\n  [ predU  dfa_lang A1 & dfa_lang A2 ]\n    =i dfa_lang dfa_disj.\nProof. move => w /=. by rewrite -dfa_disj_correct'. Qed.\n\n(** Conjunction **) \n  \nDefinition dfa_conj :=\n {| \n    dfa_s := (dfa_s A1, dfa_s A2);\n    dfa_fin := (fun x => dfa_fin A1 x.1 && dfa_fin A2 x.2);\n    dfa_step := [fun x a => (dfa_step A1 x.1 a, dfa_step A2 x.2 a)]\n  |}.\n\n(** Correctness w.r.t. any state. **)\nLemma dfa_conj_correct' x1 x2 :\n  [ predI  dfa_accept A1 x1 & dfa_accept A2 x2 ]\n  =i dfa_accept dfa_conj (x1, x2).\nProof. move => w. elim: w x1 x2 => [|a w IHw].\n  by [].\nmove => x1 x2.\nexact: IHw.\nQed.\n\n(** Language correctness. **)\nLemma dfa_conj_correct:\n  [ predI dfa_lang A1 & dfa_lang A2 ]\n  =i dfa_lang dfa_conj.\nProof. move => w. by rewrite -dfa_conj_correct'  /=. Qed.\n\nEnd BinaryOps.\n\n(* Remove unreachable states *)\nSection Reachability.\n  Definition reachable1 := [ fun x y => [ exists a, dfa_step A1 x a == y ] ].\n\n  Definition reachable := enum (connect reachable1 (dfa_s A1)).\n\n  Lemma reachable_step x a: x \\in reachable ->  dfa_step A1 x a \\in reachable.\n  Proof.\n    rewrite 2!mem_enum -2!topredE /= => Hx.\n    eapply connect_trans.\n      eassumption.\n    apply/connectP.\n    exists [::dfa_step A1 x a] => //=.\n    rewrite andbT. apply/existsP. by exists a.\n  Qed.\n\n  Lemma reachable0 : dfa_s A1 \\in reachable. \n  Proof. rewrite mem_enum -topredE /=. by apply connect0. Qed.\n\n  Definition dfa_connected :=\n   {| \n      dfa_s := SeqSub reachable0;\n      dfa_fin := fun x => match x with SeqSub x _ => dfa_fin A1 x end;\n      dfa_step := fun x a => match x with\n        | SeqSub _ Hx => SeqSub (reachable_step _ a Hx)\n        end\n    |}.\n      \n\n  Lemma dfa_connected_correct' x (Hx: x \\in reachable) :\n    dfa_accept dfa_connected (SeqSub Hx) =i dfa_accept A1 x.\n  Proof. move => w. elim: w x Hx => [|a w IHw] x Hx //=.\n    by rewrite 2!dfa_accept_cons IHw.\n  Qed. \n\n  Lemma dfa_connected_correct: dfa_lang dfa_connected =i dfa_lang A1.\n  Proof.\n    move => w. by rewrite /dfa_lang /= dfa_connected_correct'.\n  Qed.\n\n  Definition reachable1_connected := [ fun x y => [ exists a, dfa_step dfa_connected x a == y ] ].\n  Lemma reachable1_connected_aux2 x y (Hx: x \\in reachable) (Hy: y \\in reachable) : connect reachable1 x y -> connect reachable1_connected (SeqSub Hx) (SeqSub Hy).\n  Proof.\n    move/connectP => [p].\n    elim: p x Hx y Hy => [|z p IHp] x Hx y Hy //=.\n      move => _ H.                                \n      move: Hx Hy. rewrite H => Hx Hy.\n      have: (Hx = Hy).\n        by apply: bool_irrelevance.\n      move => ->.\n      apply: connect0.\n    move/andP => [] /existsP [] a /eqP Ha Hpz H.\n    have Hz: (z \\in reachable).\n      rewrite -Ha. by apply reachable_step.\n    pose H0 := (IHp _ Hz _ Hy Hpz H).\n    eapply connect_trans.\n      apply connect1.\n      instantiate (1 := SeqSub Hz).\n      apply/existsP. exists a.\n      simpl. move: Hz H0.\n      rewrite -Ha => Hz H0.\n      have: Hz = reachable_step x a Hx.\n        apply bool_irrelevance.\n      by move => ->.\n    assumption.\n  Qed.\n\n                   \n  Lemma dfa_connected_repr' (x y: dfa_connected):\n    connect reachable1_connected y x ->\n    exists w, last y (dfa_run' dfa_connected y w) = x.\n  Proof.\n    move/connectP => [] p.\n    elim: p x y => [|z p IHp] x y.\n      move => _ -> /=. by exists [::].\n    move => /= /andP [] /existsP [] a /eqP Ha Hp Hx.\n    destruct (IHp x z) as [w Hw] => //.\n    exists (a::w).\n    by rewrite /= Ha.\n  Qed.\n\n  Lemma dfa_connected_repr x :\n    exists w, last (dfa_s dfa_connected) (dfa_run dfa_connected w) = x.\n  Proof.\n    apply dfa_connected_repr'.\n    destruct x as [x Hx].\n    apply (reachable1_connected_aux2 (dfa_s A1) x reachable0).\n    by rewrite mem_enum -topredE /= in Hx.\n  Qed.\n  \n  Lemma dfa_connected_repr_pred x :\n    exists w, last (dfa_s dfa_connected) (dfa_run dfa_connected w) == x.\n  Proof.\n    move: (dfa_connected_repr x) => [w /eqP].\n    by eauto.\n  Defined.\n  \n  Lemma dfa_connected_repr_fun (x: dfa_connected):\n    word.\n  Proof.\n    move: (dfa_connected_repr_pred x).\n    apply (xchoose).\n  Defined.\n\n  Lemma dfa_connected_repr_fun_correct x: last (dfa_s dfa_connected) (dfa_run dfa_connected (dfa_connected_repr_fun x)) = x.\n  Proof.\n    rewrite /dfa_connected_repr_fun. \n    by move: (xchooseP (dfa_connected_repr_pred x)) => /eqP.\n  Qed.\n    \n  Lemma dfa_connected_repr_fun_injective: injective dfa_connected_repr_fun.\n  Proof.\n    move => x y.\n    rewrite /dfa_connected_repr_fun => H.\n    move: (xchooseP (dfa_connected_repr_pred x)) => /eqP.\n    move: (xchooseP (dfa_connected_repr_pred y)) => /eqP.\n    rewrite H. by move => -> ->.\n  Qed.\n\n  Lemma dfa_connected_size: #|A1| >= #|dfa_connected|.\n  Proof.\n    rewrite /dfa_connected /= /reachable card_seq_sub.\n    by rewrite -cardE max_card.\n    exact: enum_uniq.\n  Qed.\n    \nEnd Reachability.\n\nSection Emptiness.\n\n  Definition dfa_lang_empty := #|dfa_fin dfa_connected| == 0.\n\n  Lemma dfa_lang_empty_aux2: dfa_lang dfa_connected =i pred0 -> dfa_lang_empty.\n  Proof.\n    rewrite /dfa_lang_empty.\n    move => H.\n    apply/eqP/eq_card0.\n    move => x.\n    apply/idP/idP.\n    apply/negP.\n    move: (dfa_connected_repr x) => [w Hw].\n    move: (H w).\n    rewrite /dfa_lang /= -dfa_run_accept.\n    rewrite Hw.\n    by move/negP.\n  Qed. \n  \n  Lemma dfa_lang_empty_aux1: dfa_lang_empty -> dfa_lang dfa_connected =i pred0.\n  Proof.\n    rewrite /dfa_lang_empty.\n    move => H w.\n    apply/idP/idP.\n    apply/negP.\n    rewrite /dfa_lang /= -dfa_run_accept.\n    by move/eqP/card0_eq: H => ->.\n  Qed.\n                              \n  Lemma dfa_lang_empty_correct:\n    reflect (dfa_lang A1 =i pred0)\n            dfa_lang_empty.\n  Proof.\n    apply/iffP.\n    eexact (@idP dfa_lang_empty ).\n      move => H w. rewrite -dfa_connected_correct.\n      exact: dfa_lang_empty_aux1.\n    move => H.\n    apply: dfa_lang_empty_aux2.\n    move => w.\n    by rewrite dfa_connected_correct.\n  Qed.\n    \nEnd Emptiness.\n\nEnd DFAOps.\n\nSection Equivalence.\n  Definition dfa_sym_diff A1 A2 :=\n    dfa_disj (dfa_conj A1 (dfa_compl A2)) (dfa_conj A2 (dfa_compl A1)).\n\n  Definition dfa_equiv A1 A2 := dfa_lang_empty (dfa_sym_diff A1 A2).\n\n  Lemma dfa_equiv_correct A1 A2:\n    dfa_equiv A1 A2 <-> dfa_lang A1 =i dfa_lang A2.\n  Proof.\n    split; rewrite /dfa_sym_diff.\n      move/dfa_lang_empty_correct => H w.\n      move: (H w).\n      rewrite -dfa_disj_correct -topredE /= -2!dfa_conj_correct -2!topredE /= -2!dfa_compl_correct.\n      move/norP => [] /nandP [] /negP H1 /nandP [] /negP H2;\n      apply/idP/idP; try by [];\n      move/negP: H1; move/negP: H2;\n      by auto using negbNE.\n    move => H. apply/dfa_lang_empty_correct => w. move: (H w).\n    rewrite -dfa_disj_correct -3!topredE /= -2!dfa_conj_correct -2!topredE /= -2!dfa_compl_correct.\n    rewrite -H -4!topredE /= -2!topredE /= andbN => ->.\n    by rewrite andbN.\nQed.    \n\nEnd Equivalence.\n\n\n(** Operations on non-deterministic automata. **)\nSection NFAOps.\nVariable A1: nfa.\nVariable A2: nfa.\n\n(** Concatenation of two non-deterministic automata. **)\n\nDefinition nfa_conc : nfa :=\n  {|\n    nfa_s := inl _ (nfa_s A1);\n    nfa_fin := [fun x => \n        match x with\n          | inl x => nfa_fin A1 x && nfa_fin A2 (nfa_s A2)\n          | inr x => nfa_fin A2 x\n        end];\n     nfa_step := fun x a y =>\n        match x,y with\n          | inl x, inl y => nfa_step A1 x a y\n          | inl x, inr y => nfa_fin A1 x && nfa_step A2 (nfa_s A2) a y\n          | inr x, inr y => nfa_step A2 x a y\n          | inr x, inl y => false\n        end\n   |}.\n\n(** We prove that every path of A2 can be mapped to a path\n   of nfa_conc. **)\nLemma nfa_conc_cont x xs w:\n  nfa_run A2 x xs w\n  -> nfa_run nfa_conc (inr _ x) (map (@inr A1 A2) xs) w.\nProof. elim: xs x w => [|y xs IHxs] x w; case: w => [|a w] => //.\nsimpl. by move/andP => [] -> /IHxs ->.\nQed.\n\n(** We prove that every word in the language of A2\n   is also accepted by any final state of A1 in\n   nfa_conc. **)\nLemma nfa_conc_fin1 x1 w:\n  nfa_fin A1 x1 ->\n  nfa_lang A2 w ->\n  nfa_accept nfa_conc (inl _ x1) w.\nProof.\nmove => H0 /nfa_run_accept [] ys.\nelim: ys w x1 H0 => [|y ys IHys] [|a w] x1 H0 //=.\n  rewrite -topredE /=.\n  by move: H0 => -> _ ->.\nmove => /andP [] H1 H2 H3.\napply/existsP. exists (inr _ y).\nrewrite H0 H1 /=.\napply/nfa_run_accept.\n  eexists _.\n  apply nfa_conc_cont.\n  by eassumption.\nby rewrite last_map /nfa_fin.\nQed.\n\n(** We prove that for every word w1 accepted by A1 in\n   some state x and for every word w2 in the language of A2\n   w1 ++ w2 will be accepted by the corresponding state in\n   nfa_conc. **)\nLemma nfa_conc_aux2 x w1 w2:\n  nfa_accept A1 x w1 ->\n  nfa_lang A2 w2 ->\n  nfa_accept nfa_conc (inl _ x) (w1 ++ w2).\nProof. elim: w1 w2 x => [|a w1 IHw1] w2 x.\n    move => H0 /nfa_run_accept [] xs [] H1 H2.\n    move: (nfa_conc_cont _ _ _ H1) => H3.\n    apply/nfa_accept_cat.\n    exists [::] => /=.\n    apply: nfa_conc_fin1 => //.\n    apply/nfa_run_accept.\n    by eauto.\n  move => /existsP [] y /andP [] H1 H2 H3 /=.\n  apply/existsP. exists (inl _ y).\n  rewrite H1 /=.\n  apply: IHw1.\n    exact: H2.\n  exact: H3.\nQed.\n\n(** We prove that every word accepted by some state X in nfa_conc is\n   - EITHER a concatenation of two words w1, w2 which are accpeted\n   by A1, A2 (resp.) if X corresponds to one of A1's states\n   - OR accepted by A2 in the state corresponding to X if X\n   corresponds to one of A2's states. **)\nLemma nfa_conc_aux1 X w :\n  nfa_accept nfa_conc X w ->\n  match X with\n  | inl x => exists w1, exists w2, (w == w1 ++ w2) && (nfa_accept A1 x w1) && nfa_lang A2 w2\n  | inr x => nfa_accept A2 x w\nend.\nProof.\n  elim: w X => [|a w IHw] [x|x] //=.\n      move => /andP [] H0 H1. exists [::]. exists [::].\n      by rewrite /= H0 H1.\n    move/existsP => [] [y|y] /andP [] H0 /IHw.\n      (* inl / inl *)\n      move => [] w1 [] w2 /andP [] /andP [] /eqP H1 H2 /= H3.\n      exists (a::w1). exists w2.\n      rewrite H1 eq_refl H3 andTb andbT.\n      apply/existsP. exists y.\n      move: H0 => /= ->. rewrite andTb.\n      exact H2.\n    (* inl / inr *)\n    move: H0 => /= /andP [] H0 H1 /= H2.\n    exists [::]. exists (a::w) => /=.\n    rewrite H0 eq_refl 2!andTb.\n    apply/existsP. exists y.\n    by rewrite H1 H2.\n  (* inr / inl  *)\n  move/existsP => [] [y|y] /andP [] H0 /IHw.\n  by [].\n(* inr / inr *)\nmove: H0 => /= H0 H1.\napply/existsP. exists y.\nby rewrite H0 H1.\nQed.\n\nLemma nfa_conc_correct: nfa_lang nfa_conc =i conc (nfa_lang A1) (nfa_lang A2).\nProof.\n  move => w.\n  apply/idP/concP.\n    move/nfa_conc_aux1.\n    rewrite /nfa_conc /nfa_s.\n    move => [] w1 [] w2 /andP [] /andP [] /eqP H0 H1 H2.\n    by eauto.\n  move => [] w1 H0 [] w2 H2 ->.\n  by apply/nfa_conc_aux2.\n  Qed.  \n\n(** Plus operator for non-deterministic automata. **)\n\n(** The step relation implements the following rule:\n   - every edge to a final state will also be duplicated\n   to point to s0.\n   **)\nDefinition step_plus x a y : bool :=\nnfa_step A1 x a y || (\n                      (y == nfa_s A1)\n                      && [ exists z, (nfa_fin A1 z) && (nfa_step A1 x a z) ]\n                    ).\n\n(** **)\nDefinition nfa_repeat : nfa :=\n  {|\n    nfa_s := nfa_s A1;\n    nfa_fin := nfa_fin A1;\n    nfa_step := fun x a y =>\n        nfa_step A1 x a y || (\n                      (y == nfa_s A1)\n                      && [ exists  z, (nfa_fin A1 z) && (nfa_step A1 x a z) ]\n                    )\n   |}.\n\n\n(** We prove that every path of A1 can be mapped to a path\n   of nfa_repeat. **)\nLemma nfa_repeat_cont x xs w:\n  nfa_run A1 x xs w\n  -> nfa_run nfa_repeat x xs w.\nProof. elim: xs x w => [|y xs IHxs] x w; case: w => [|a w] => //.\nmove/andP => [] H0 /= /IHxs ->.\nby rewrite /step_plus H0 orTb.\nQed.\n\n(** We prove that every accepting path labeled (a::w) in A1\n   exists in nfa_repeat with only the last state changed to\n   A1's starting state. This new path need not be accepting. **)\nLemma nfa_repeat_lpath x y xs a w:\n  nfa_fin nfa_repeat (last x (y::xs)) ->\n  nfa_run nfa_repeat x (y::xs) (a::w) ->\n  nfa_run nfa_repeat x (rcons (belast y xs) (nfa_s A1)) (a::w).\nProof. elim: xs x y a w => [|z xs IHxs] x y a [|b w] //=.\n      rewrite 2!andbT.\n      move => H0 /orP [|/andP [] /eqP].\n        move => H1. rewrite/step_plus.\n        apply/orP. right. rewrite eq_refl.\n        apply/existsP. exists y. by rewrite H0 H1.\n      move => H1 /existsP [] z /andP [] H2 H3. move: H1 H0 => -> H4.\n      apply/orP. right. rewrite eq_refl /=.\n      apply/existsP. exists z. by rewrite H2 H3.\n    by rewrite andbF.\n  by rewrite andbF.\nrewrite -(last_cons y). move => H0 /andP [] H1 /andP [] H3 H4.\nrewrite H1 /=. apply: IHxs.\n  by rewrite H0.\nsimpl. by rewrite H3 H4.\nQed.\n  \n(** We prove that every word accepted by A1 in\n   some state x is also accepted by nfa_repeat in\n   that state. **)\nLemma nfa_repeat_correct0' x w1 :\n  nfa_accept A1 x w1 ->\n  nfa_accept nfa_repeat x w1.\nProof.\n  move/nfa_run_accept => [] xs [].\n  move/nfa_repeat_cont => H0 H1.\n  apply/nfa_run_accept.\n  by exists xs. \nQed.\n\n(** We prove that every word accepted by A1 is also\n   accepted by nfa_repeat. **)\nLemma nfa_repeat_correct0 w :\n  nfa_lang A1 w ->\n  nfa_lang nfa_repeat w.\nProof. exact: nfa_repeat_correct0'. Qed.\n\n(** We prove that every prefix accpeted by A1 followed\n   by a suffix accepted by nfa_repeat is again accepted\n   by nfa_repeat. This is the first part of the proof of\n   language correctness for nfa_repeat. **)\nLemma nfa_repeat_aux2 w1 w2:\n  nfa_lang A1 w1 ->\n  nfa_lang nfa_repeat w2 ->\n  nfa_lang nfa_repeat (w1 ++ w2).\nProof.\nmove => /nfa_run_accept [] [|x xs] []; case: w1 => [|a w1] => //.\nmove => H0 H1 H2.\napply/(nfa_accept_cat).\nexists (rcons (belast x xs) (nfa_s A1)).\napply/andP. split.\n  apply: nfa_repeat_lpath.\n    exact: H1.\n  apply: nfa_repeat_cont.\n  exact: H0.\nrewrite last_rcons.\nexact H2.\nQed.\n\n\n(** We prove that every word accepted by some state x in nfa_repeat\n   is a concatenation of two words w1, w2 which are accpeted by\n   A1 in x and nfa_repeat (resp.). **) \nLemma nfa_repeat_aux1' x w :\n  nfa_accept nfa_repeat x w ->\n  ((exists w1, exists w2, (w == w1 ++ w2) && (w1 != [::]) && (nfa_accept A1 x w1) && nfa_lang nfa_repeat w2\n    ) \\/ nfa_accept A1 x w ).\nProof. elim: w x => [|a w IHw] x.\n  move => H0. right.\n  exact: H0.\ncase/existsP => y /andP [H0 H1].\ncase: (IHw _ H1) => [[w1 [w2 /andP [/andP [/andP [/eqP H2 H9] H3] H4]]]|H2].\n  move: H0 => /orP [H5|].\n    left. exists (a::w1). exists w2.\n    rewrite H2 eq_refl H4 andbT /=.\n    apply/existsP. exists y.\n    by rewrite H5 H3.\n  move/andP => [] H5 /existsP [] z /andP [H6 H7].\n  move: H5 H1 H3 => /eqP -> H1 H3.\n  left. exists ([::a]). exists w.\n  rewrite eq_refl /=. apply/andP. split.\n    apply/existsP. exists z. by rewrite H6 H7.\n  exact: H1.\nmove: H0 => /orP [H5|].\n  right => /=. apply/existsP. exists y.\n  by rewrite H5 H2.\n  move/andP => [/eqP H3 /existsP [z /andP [H4 H5]]].\nmove: H3 H1 H2 => -> H1 H2.\nleft. exists [::a]. exists w.\nrewrite eq_refl /=. apply/andP. split.\n  apply/existsP. exists z. by rewrite H5 H4.\nexact H1.\nQed.\n\n(** We prove the second part of language correctness\n   for nfa_repeat. **)\nLemma nfa_repeat_aux1 w:\n  nfa_lang nfa_repeat w ->\n  ((exists w1, exists w2, (w == w1 ++ w2) && (w1 != [::]) && (nfa_lang A1 w1) && nfa_lang nfa_repeat w2\n    ) \\/ nfa_lang A1 w ).\nProof. exact: nfa_repeat_aux1'. Qed.\n\n\n(* Star operator *)\nDefinition nfa_star := (dfa_disj dfa_eps (nfa_to_dfa nfa_repeat)).\n\nLemma nfa_star_aux1 w: w \\in dfa_lang nfa_star -> w \\in star (nfa_lang A1).\nProof.\n  rewrite /nfa_star -dfa_disj_correct -topredE /=.\n    rewrite dfa_eps_correct => /orP [].\n      move => /eqP ->.\n      apply/starP. by exists [::].\n    rewrite -nfa_to_dfa_correct.\n    move: w.\n    apply: (size_induction size).\n    move => w IHw.\n    move/nfa_repeat_aux1' => [].\n      move => [] w1 [] w2 [/andP [/andP [/andP [/eqP H1 H2] H3] H4]].\n      have H5: (size w2 < size w).\n        rewrite H1 size_cat addnC -{1}(addn0 (size w2)).\n        rewrite ltn_add2l.\n        by destruct w1.\n      move: (IHw w2 H5 H4) => /starP [] vv H6 H7.\n      apply/starP. exists (w1::vv).\n          by rewrite /= H6 -topredE /= /eps /= H2 /nfa_lang /= -topredE /= H3.\n        by rewrite H1 H7.\n      rewrite /nfa_lang /=.\n\n      case: w IHw => [|a w] IHw H.\n        apply/starP. by exists [::].\n      apply/starP.\n        exists [::(a::w)] => //=.\n        by rewrite -topredE andbT.\n      by rewrite cats0.\nQed.  \n      \nLemma nfa_star_aux2 w: w \\in star (nfa_lang A1) -> w \\in dfa_lang nfa_star.\nProof.\n    rewrite /nfa_star -dfa_disj_correct -2!topredE /= -nfa_to_dfa_correct.\n    move/starP => [] vv. elim: vv w => [|v vv IHvv] w.\n      rewrite /= => _ ->. move: (dfa_eps_correct [::]).\n      by rewrite /dfa_lang /=.\n    rewrite [all _ _]/=.\n    move/andP => [] /andP [] H0 H1 H2 H3.\n    rewrite H3 [flatten _]/=.\n    move/orP: (IHvv (flatten vv) H2 (Logic.eq_refl _)) => [].\n      rewrite dfa_eps_correct => /eqP H4.\n      move: H3. rewrite [flatten _]/= H4 cats0.\n      move => H5. subst. apply/orP. right.\n      rewrite H4 in IHvv.\n      by apply nfa_repeat_correct0.\n    move => H4.\n    apply/orP. right.\n    by apply: nfa_repeat_aux2.\nQed.\n\nLemma nfa_star_correct: dfa_lang nfa_star =i star (nfa_lang A1).\nProof.\n  move => w.\n  apply/idP/idP.\n    by move/nfa_star_aux1.\n  by move/nfa_star_aux2.\nQed.\n\nEnd NFAOps.\n\n\nEnd FA.\n\n\n", "meta": {"author": "Janno", "repo": "Bachelor-Thesis", "sha": "3ba23a0803ffa6d2cb69dcd10ec3533e367d9294", "save_path": "github-repos/coq/Janno-Bachelor-Thesis", "path": "github-repos/coq/Janno-Bachelor-Thesis/Bachelor-Thesis-3ba23a0803ffa6d2cb69dcd10ec3533e367d9294/src/automata.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198947, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6614088385125546}}
{"text": "Require Import ZArith.\nRequire Import Psatz.\n\nFrom mathcomp\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq path div choice.\nFrom mathcomp\nRequire Import fintype tuple finfun bigop prime finset binomial.\nFrom mathcomp\nRequire Import ssralg ssrnum ssrint rat.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory.\nImport Num.Theory.\n\nLocal Open Scope ring_scope.\nDelimit Scope Z_scope with coqZ.\n\n(* Translation of type int into type Z *)\nDefinition Z_of_int (n : int) : Z :=\nmatch n with\n  |Posz k => Z_of_nat k\n  |Negz k => Zopp (Z_of_nat k.+1)\nend.\n\n(* Correspondance bewteen comparison relations *)\nLemma Z_of_intP n m : n = m <-> Z_of_int n = Z_of_int m.\nProof.\nsplit; first by move->.\ncase: n=> [[|nn]|nn]; case: m => [[|mm]|mm] //=.\n- by rewrite !Zpos_P_of_succ_nat; move/Zsucc_inj/inj_eq_rev->.\n- case; move/(f_equal Zpos); rewrite !Zpos_P_of_succ_nat.\n  by move/Zsucc_inj/inj_eq_rev->.\nQed.\n\nLemma Z_of_intbP n m : n == m <-> Z_of_int n = Z_of_int m.\nProof. by rewrite <- Z_of_intP; split; move/eqP. Qed.\n\nLemma Z_of_intbPn n m : n != m <-> Z_of_int n <> Z_of_int m.\nProof. by rewrite <- Z_of_intP; split; move/eqP. Qed.\n\nLemma Z_ltP (x y : int) : (x < y) <-> (Zlt (Z_of_int x) (Z_of_int y)).\nProof.\nsplit; case: x=> [[|xx]|xx]; case: y => [[|yy]|y] //.\n- move=> h; rewrite /= !Zpos_P_of_succ_nat; apply: Zsucc_lt_compat; apply: inj_lt.\n  exact: ltP.\n- rewrite /Z_of_int; rewrite !NegzE => h.\n  have {h} : (Z_of_nat y.+1 < Z_of_nat xx.+1)%coqZ by apply/inj_lt/ltP.\n  by lia.\n- by rewrite /= !Zpos_P_of_succ_nat; move/Zsucc_lt_reg/inj_lt_rev/ltP.\n- rewrite /Z_of_int !NegzE => h.\n- have {h} : (Z_of_nat y.+1 < Z_of_nat xx.+1)%coqZ by lia.\n  by move/inj_lt_rev/ltP.\nQed.\n\nLemma Z_leP (x y : int) : (x <= y) <-> Zle (Z_of_int x) (Z_of_int y).\nProof.\nsplit.\n- rewrite ler_eqVlt; case/orP; first by move/eqP->; exact: Zle_refl.\n  move/Z_ltP; exact: Zlt_le_weak.\ncase/Z_le_lt_eq_dec; first by move/Z_ltP/ltrW.\nby move/Z_of_intP->.\nQed.\n\n(*Transformation of a constraint (x # y) where (x y : int) and # is a comparison\nrelation into the corresponding constraint (Z_of_int x #' Z_of_int y) where #' is\nthe analogue of # on Z. The transformation is performed on the first such formula\nfound either in the context or the conclusion of the goal *)\nLtac zify_int_rel :=\n match goal with\n  (* Prop equalities *)\n  | H : (@eq _ _ _) |- _ => move/Z_of_intP: H => H\n  | |- (@eq _ _ _) => rewrite -> Z_of_intP\n  | H : context [ @eq _ ?a ?b ] |- _ => rewrite -> (Z_of_intP a b) in H\n  | |- context [ @eq _ ?a ?b ] => rewrite -> (Z_of_intP a b)\n  (* less than *)\n  | H : is_true (@Num.Def.ltr _ _ _) |- _ => move/Z_ltP: H => H\n  | |- is_true (@Num.Def.ltr _ _ _) => rewrite -> Z_ltP\n  | H : context [  is_true (@Num.Def.ltr _ ?a ?b) ] |- _ => rewrite -> (Z_ltP a b) in H\n  | |- context [ is_true (@Num.Def.ltr _ ?a ?b) ] => rewrite -> (Z_ltP a b)\n  (* less or equal *)\n  | H : is_true (@Num.Def.ler _ _ _) |- _ => move/Z_leP: H => H\n  | |- is_true (@Num.Def.ler _ _ _) => rewrite -> Z_leP\n  | H : context [  is_true (@Num.Def.ler _ ?a ?b) ] |- _ => rewrite -> (Z_leP a b) in H\n  | |- context [  is_true (@Num.Def.ler _ ?a ?b) ] => rewrite -> (Z_leP a b)\n  (* Boolean equality *)\n  |H : is_true (@eq_op _  _ _) |- _ => rewrite -> Z_of_intbP in H\n  | |- is_true (@eq_op _  _ _) => rewrite -> Z_of_intbP\n  |H : context [ is_true (@eq_op _  _ _)] |- _ => rewrite -> Z_of_intbP in H\n  | |- context [ is_true (@eq_op _  _ _)] => rewrite -> Z_of_intbP\n  (* Negated boolean equality *)\n  |H : is_true (negb (@eq_op _  _ _)) |- _ => rewrite -> Z_of_intbPn in H\n  | |- is_true (negb (@eq_op _  _ _)) => rewrite -> Z_of_intbPn\n  |H : context [ is_true (negb (@eq_op _  _ _))] |- _ => rewrite -> Z_of_intbPn in H\n  | |- context [ is_true (negb (@eq_op _  _ _))] => rewrite -> Z_of_intbPn\n end.\n\n(* Distribution of Z_of_int over arithmetic operations *)\nLemma Z_of_intmorphD  : {morph Z_of_int : x y  /  x + y >-> (Zplus x y) }.\nProof.\nhave aux (n m : nat) :\n  Z_of_int (Posz n.+1 + Negz m) = (Z_of_int n.+1 + Z_of_int (Negz m))%coqZ.\n  rewrite {2 3}/Z_of_int NegzE; case: (ltngtP m n)=> hmn.\n  + rewrite subzn; last exact: ltn_trans hmn _.\n    rewrite subSn // /Z_of_int -subSn // inj_minus1 //; apply/leP.\n    exact: ltn_trans hmn _.\n  + rewrite -[_ - _]opprK opprB subzn; last exact: ltn_trans hmn _.\n    rewrite subSn // -NegzE /Z_of_int -subSn // inj_minus1; first by lia.\n    apply/leP; exact: ltn_trans hmn _.\n  + by rewrite hmn subrr Zplus_opp_r.\nmove=> x y /=; case: x=> [[|xx]|xx]; case: y => [[|yy]|y] //.\n- by rewrite /= subn0.\n- by rewrite addr0 Zplus_0_r.\n- by rewrite -PoszD addnS /Z_of_int -inj_plus -addnS.\n- by rewrite addr0 Zplus_0_r.\n- by rewrite addrC aux Zplus_comm.\n- rewrite {2 3}/Z_of_int !NegzE -opprD -PoszD addnS -NegzE /Z_of_int -addnS.\n  by rewrite inj_plus Zopp_plus_distr.\nQed.\n\nLemma Z_of_intmorphM  : {morph Z_of_int : x y  / x * y  >-> (Zmult x y) }.\nhave aux (n m : nat) :\n  Z_of_int (Posz n.+1 * Negz m) = (Z_of_int n.+1 * Z_of_int (Negz m))%coqZ.\n  rewrite {2 3}/Z_of_int NegzE mulrN -PoszM mulnS addSn -NegzE /Z_of_int -addSn.\n  by rewrite -mulnS inj_mult; lia.\nmove=> x y /=; case: x=> [[|xx]|xx]; case: y => [[|yy]|y] //.\n- by rewrite mulr0 Zmult_0_r.\n- by rewrite -PoszM /Z_of_int inj_mult.\n- by rewrite mulrC aux Zmult_comm.\n- rewrite ![in LHS]NegzE mulrN mulNr opprK -PoszM /Z_of_int inj_mult; lia.\nQed.\n\nLemma Z_of_intmorphN  : {morph Z_of_int : x / - x >-> Zopp x}.\nProof. by case=> [] [|xx]. Qed.\n\n\n(*Pushing Z_of_int at the leaves of expressions.The transformation is *)\n(*performed on the first such formula found either in the context or *)\n(*the conclusion of the goal *)\n(* We (boldly?) assume here that all operations are ring ones *)\nLtac zify_int_op :=\n match goal with\n  (* add -> Zplus *)\n  | H : context [ Z_of_int (@GRing.add _ _ _) ] |- _ => rewrite Z_of_intmorphD in H\n  | |- context [ Z_of_int (@GRing.add _ _ _) ] => rewrite Z_of_intmorphD\n  (* opp -> Zopp *)\n  | H : context [ Z_of_int (@GRing.opp _ _) ] |- _ => rewrite Z_of_intmorphN in H\n  | |- context [ Z_of_int (@GRing.opp _  _) ] => rewrite Z_of_intmorphN\n  (* mul -> Zmult *)\n  | H : context [ Z_of_int (@GRing.mul _ _ _) ] |- _ => rewrite Z_of_intmorphM in H\n  | |- context [ Z_of_int (@GRing.mul _ _ _) ] => rewrite Z_of_intmorphM\n  (* (* O -> Z0 *) *)\n  | H : context [ Z_of_int (GRing.zero _) ] |- _ => rewrite [Z_of_int O]/= in H\n  | |- context [ Z_of_int (GRing.zero _) ] => rewrite [Z_of_int O]/=\n  (* (* 1 -> 1 *) *)\n  | H : context [ Z_of_int (GRing.one _) ] |- _ => rewrite [Z_of_int 1]/= in H\n  | |- context [ Z_of_int (GRing.one _) ] => rewrite [Z_of_int 1]/=\n  (* (* n -> n *) *)\n  | H : context [ Z_of_int _ ] |- _ => rewrite [Z_of_int (S _)]/= in H\n  | |- context [ Z_of_int _ ] => rewrite [Z_of_int (S _)]/=\n  | H : context [ Z_of_nat _ ] |- _ => rewrite [Z_of_nat 0]/= [Z_of_nat (S _)]/= in H\n  | |- context [ Z_of_nat _ ] => rewrite [Z_of_nat 0]/= [Z_of_nat (S _)]/=\n end.\n\n(* Preparing a goal to be solved by lia by translating every formula *)\n(* in the context or the conclusion which expresses a constraint on *)\n(* some int into the analogue on Z *)\nLtac zify_int :=\n  repeat progress zify_int_rel;\n  repeat progress zify_int_op.\n\n(* Preprocessing + lia *)\nLtac intlia := zify_int; lia.\n\n\n(*Transformation of a constraint (x # y) where (x y : nat) and # is a comparison\nrelation into the corresponding constraint (x #' y) where #' is\nthe std lib analogue of #. The transformation is performed on the first such formula\nfound either in the context or the conclusion of the goal *)\nLtac ssrnatify_rel :=\n match goal with\n  (* less or equal (also codes for strict comparison in ssrnat) *)\n  | H : is_true (leq _ _) |- _ => move/leP: H => H\n  | H : context [ is_true (leq ?a ?b)] |- _ =>\n     rewrite <- (rwP (@leP a b)) in H\n  | |- is_true (leq _ _) => apply/leP\n  | |- context [ is_true (leq ?a ?b)] => rewrite <- (rwP (@leP a b))\n  (* Boolean equality *)\n  | H : is_true (@eq_op _ _ _) |- _ => move/eqP: H => H\n  | |- is_true (@eq_op _ _ _) => apply/eqP\n  | H : context [ is_true (@eq_op _ _ _)] |- _ =>\n     rewrite <-  (rwP (@eqP _ _ _)) in H\n  | |- context [ is_true (@eq_op _ ?x ?y)] => rewrite <- (rwP (@eqP _ x y))\n  (* Negated boolean equality *)\n  | H : is_true (negb (@eq_op _  _ _)) |- _ => move/eqP: H => H\n  | |- is_true (negb (@eq_op _  _ _)) => apply/eqP\n  | H : context [ is_true (negb (@eq_op _ _ _))] |- _ =>\n     rewrite <-  (rwP (@eqP _ _ _)) in H\n  | |- context [ is_true (negb (@eq_op _ ?x ?y))] =>\n     rewrite <- (rwP (@eqP _ x y))\n end.\n\n(* Converting ssrnat operation to their std lib analogues *)\nLtac ssrnatify_op :=\n match goal with\n  (* subn -> minus *)\n  | H : context [subn _ _] |- _ => rewrite -!minusE in H\n  | |- context [subn _ _] => rewrite -!minusE\n  (* addn -> plus *)\n  | H : context [addn _ _] |- _ => rewrite -!plusE in H\n  | |- context [addn _ _] => rewrite -!plusE\n  (* muln -> mult *)\n  | H : context [muln _ _] |- _ => rewrite -!multE in H\n  | |- context [muln _ _] => rewrite -!multE\n end.\n\n(* Preparing a goal to be solved by lia by translating every formula *)\n(* in the context or the conclusion which expresses a constraint on *)\n(* some nat into the std lib, Prop, analogues *)\nLtac ssrnatify :=\n  repeat progress ssrnatify_rel;\n  repeat progress ssrnatify_op.\n\n(* Preprocessing + lia *)\nLtac ssrnatlia := ssrnatify; lia.\n\n(* Preprocessing + lia *)\nLtac ssrnatomega := ssrnatify; omega.\n\n\n(*** Below starts the code of goal_to_lia, to be cleaned as well ***)\n\n(* goal_to_lia is a pre-prcoessing heuristic to be performed when the goal is\n   more intricate and features more casts and boolean connectives. It is\n   not polished as it does not scale on larger goals. *)\n\n\nLemma eqr_int_prop (x y : int) :\n (x%:~R = y%:~R :> rat) <-> x = y.\nProof.\nsplit; last by move ->.\nby move/eqP; rewrite eqr_int; move/eqP.\nQed.\n\n\nLtac rat_to_ring_lia :=\n  rewrite -?[0%Q]/((Posz 0)%:~R : rat) -?[1%Q]/((Posz 1)%:~R : rat)\n          -?[(_ - _)%Q]/(_ - _ : rat)%R -?[(_ / _)%Q]/(_ / _ : rat)%R\n          -?[(_ + _)%Q]/(_ + _ : rat)%R -?[(_ * _)%Q]/(_ * _ : rat)%R\n          -?[(- _)%Q]/(- _ : rat)%R -?[(_ ^-1)%Q]/(_ ^-1 : rat)%R /=.\n\nLtac rat_to_ring_hyp hyp :=\n  rewrite -?[0%Q]/((Posz 0)%:~R : rat) -?[1%Q]/((Posz 1)%:~R : rat)\n          -?[(_ - _)%Q]/(_ - _ : rat)%R -?[(_ / _)%Q]/(_ / _ : rat)%R\n          -?[(_ + _)%Q]/(_ + _ : rat)%R -?[(_ * _)%Q]/(_ * _ : rat)%R\n          -?[(- _)%Q]/(- _ : rat)%R -?[(_ ^-1)%Q]/(_ ^-1 : rat)%R /= in hyp.\n\nLtac propify_bool_connectives :=\nrewrite ?(negb_and, negb_or);\nrepeat (match goal with\n | H : context [ is_true (andb _ _) ] |- _ => rewrite -(rwP andP) in H\n | |-  context [ is_true (andb _ _) ]      => rewrite -(rwP andP)\n | H : context [ is_true (orb _ _) ] |- _ => rewrite -(rwP orP) in H\n | |-  context [ is_true (orb _ _) ]      => rewrite -(rwP orP) end);\nrewrite ?(=^~ ltrNge, =^~ lerNgt).\n\n\nLtac goal_to_lia :=\npropify_bool_connectives;\nrat_to_ring_lia;\nrewrite ?NegzE;\n(* unpropagate morZ_of_intsms to get, where that is pertinent,*)\n(* propositions of the form _%:~R =/<=/< _%:~R *)\nrewrite -?(rmorphD,rmorphN, rmorphB,rmorphM);\n(* get rid of the cast %:~R around various compare operations *)\nrewrite ?(eqr_int,ler_int, ltr_int, eqr_int_prop); (* TODO: add nats here *)\n(* put Z_of_int around the sides of the operation =,<=,or < (on ints)  *)\ntry (rewrite -> !Z_of_intbPn);\ntry (rewrite -> !Z_of_intbP);\ntry (rewrite -> !Z_ltP);\ntry (rewrite -> !Z_leP);\ntry (rewrite -> !Z_of_intP); (* TODO: add nats here *)\n(* just in case there were some trapped nats inside the goal *)\nrewrite ?(PoszD,PoszM);\n(* distribute Z_of_int to the leaves of the arithmetic expressions *)\nrewrite ?(Z_of_intmorphN, Z_of_intmorphM, Z_of_intmorphD)\n?[Z_of_int 1]/= ?[Z_of_int 0]/= ?[Z_of_int (S _)]/=;\n(* somehow we obtain (is_true true) somewhere and lia dislikes it *)\nrepeat (rewrite [true](erefl : true = (0 < (1 : int))));\nrepeat (rewrite [false](erefl : false = (0 < (0 : int)))).\n", "meta": {"author": "amahboubi", "repo": "lia4mathcomp", "sha": "70182f813ee49f662365a1a3a5222ecec83c507b", "save_path": "github-repos/coq/amahboubi-lia4mathcomp", "path": "github-repos/coq/amahboubi-lia4mathcomp/lia4mathcomp-70182f813ee49f662365a1a3a5222ecec83c507b/lia_tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357569, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6614088281823076}}
{"text": "(*\n\n   Benedikt Ahrens and Régis Spadotti\n\n   Terminal semantics for codata types in intensional Martin-Löf type theory\n\n   http://arxiv.org/abs/1401.1053\n\n*)\n\n(*\n\n  Content of this file:\n\n  definition of the category of sets, proof that it has products\n\n*)\n\nRequire Import Theory.Category.\nRequire Import Theory.Product.\n\n(*------------------------------------------------------------------------------\n  -- ＣＡＴＥＧＯＲＹ  ＯＦ  ＴＹＰＥＳ\n  ----------------------------------------------------------------------------*)\n(** * Category of Types **)\n\n(** ** Type category definition **)\n\nProgram Definition Hom (A B : Type) : Setoid := Setoid.make ⦃ Carrier ≔ A → B\n                                                           ; Equiv   ≔ λ f g ∙ ∀ x, f x = g x ⦄.\n(** equivalence **)\nNext Obligation.\n  constructor; hnf; simpl; [ reflexivity | now symmetry | etransitivity ; eauto ].\nQed.\n\nLocal Infix \"⇒\" := Hom.\n\nDefinition id {A} : A ⇒ A := λ x ∙ x.\n\nProgram Definition compose {A B C} : [ B ⇒ C ⟶ A ⇒ B ⟶ A ⇒ C ] :=\n  Π₂.make (λ g f x ∙ g (f x)).\n(** g-cong₂ **)\nNext Obligation.\n  intros f₁ f₂ eq_f₁f₂ g₁ g₂ eq_g₁g₂ x.\n  now rewrite eq_f₁f₂, eq_g₁g₂.\nQed.\n\nLocal Infix \"∘\" := compose.\n\nLemma left_id A B (f : A ⇒ B) : id ∘ f ≈ f.\nProof.\n  hnf ; intuition.\nQed.\n\nLemma right_id A B (f : A ⇒ B) : f ∘ id ≈ f.\nProof.\n  hnf ; intuition.\nQed.\n\nLemma compose_assoc A B C D (f : A ⇒ B) (g : B ⇒ C) (h : C ⇒ D) : h ∘ g ∘ f ≈ h ∘ (g ∘ f).\nProof.\n  hnf ; intuition.\nQed.\n\nCanonical Structure 𝑻𝒚𝒑𝒆 : Category :=\n  mkCategory left_id right_id compose_assoc.\n\n(*------------------------------------------------------------------------------\n  -- ＴＹＰＥＳ  ＨＡＶＥ  ＢＩＮＡＲＹ  ＰＲＯＤＵＣＴ\n  ----------------------------------------------------------------------------*)\n(** ** Types have binary product **)\n\nProgram Instance 𝑻𝒚𝒑𝒆_BinaryProduct : BinaryProduct 𝑻𝒚𝒑𝒆 :=\n  BinaryProduct.make  ⦃ Category  ≔ 𝑻𝒚𝒑𝒆\n                      ; _×_       ≔ _⟨×⟩_\n                      ; ⟨_,_⟩     ≔ λ C f g (c : C) ∙ (f c , g c)\n                      ; π₁        ≔ fst\n                      ; π₂        ≔ snd ⦄.\n(** Pmor-cong₂ **)\nNext Obligation.\n  intros f₁ f₂ eq_f₁f₂ g₁ g₂ eq_g₁g₂ x. now f_equal.\nQed.\n(** Pmor-universal **)\nNext Obligation.\n  rewrite <- H. rewrite <- H0.\n  remember (i x); destruct (i x); now subst.\nQed.\n", "meta": {"author": "rs-", "repo": "Triangles", "sha": "57f10cb6c627c331b2c6e7b344a34ae50838cc67", "save_path": "github-repos/coq/rs--Triangles", "path": "github-repos/coq/rs--Triangles/Triangles-57f10cb6c627c331b2c6e7b344a34ae50838cc67/Category/Types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516188, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6614088221887344}}
{"text": "Require Import HoTT.\n\n(** a characterization of the relations (dependent types over simple products)\nthat represent Functions.\n*)\n\nLocal Open Scope path_scope.\n\nDefinition sigMap { A B : Type } ( P : A -> B -> Type )\n  : { y : A * B & P (fst y) (snd y) } -> A.\nProof.\n  intros [ [ a _ ] _ ].\n  auto.\nDefined.\n\nDefinition IsFunctional { A B : Type } ( P : A -> B -> Type ) \n  := \n  IsEquiv (sigMap P).\n\nDefinition underlyingFunction { A B : Type } \n ( P : A -> B -> Type )\n : ( IsFunctional P ) -> A -> B.\nProof.\n  intros [ inv retr sect adj ] a.\n  exact (snd (projT1 (inv a))).\nDefined.\n\nDefinition valPath { A B } ( f : A -> B ) :\n A -> B -> Type :=\n  fun a => fun b => ( b = f a ).\n\nDefinition valSectn { A B } ( f : A -> B ) :\n  A -> { ab : A * B & (valPath f) (fst ab) (snd ab) }.\nProof.\n  intro a.\n  exists ( a, f a ).\n  exact idpath.\nDefined.\n\nLemma isfunc_valpath { A B } ( f : A -> B ) :\n  IsFunctional (valPath f).\nProof.\n  apply isequiv_adjointify with (valSectn f).\n  intro.\n    auto.\n    intro.\n    destruct x.\n    destruct x as [ a b ].\n    simpl in *.\n    unfold valPath in v.\n   assert \n    ( @paths { z : B & z = f a } ( f a ; idpath ) ( b ; v ) ).\n      apply path_sigma with (inverse v).\n      simpl. destruct v. auto.\n   refine ( transport (fun bp : { z : B & z = f a } =>\n    valSectn f a = ( ( a , bp .1 ) ; bp .2 ) ) X _ ).\n    exact idpath.\nDefined.\n\nLemma htp_valpath { A B } ( f : A -> B ) :\n  f == (underlyingFunction (valPath f) (isfunc_valpath f)).\nProof.\n  intro. auto.\nDefined.\n\nLemma map_valpath { A B } ( P : A -> B -> Type ) ( H : IsFunctional P ) :\n  forall a b, ( valPath (underlyingFunction P H) a b ) ->  ( P a b ).\nProof.\n  intros.\n  destruct H as [ inv sect retr adj ].\n    simpl in X.\n    assert ( heq := sect a ).\n    cbv in X. cbv.\n    destruct (inv a) as [ [ r s ] t ].\n      simpl in *. cbv.\n      destruct X. destruct heq. auto.\nDefined.\n\nLemma inv_valpath { A B } ( P : A -> B -> Type ) ( H : IsFunctional P ) :\n  forall a b, (P a b) -> ( valPath (underlyingFunction P H) a b ).\nProof.\n  intros.\n  destruct H as [ inv sect retr adj ].\n  simpl in *.\n  lazy.\n   set ( thePoint := @existT (A * B) (fun z => P (fst z)(snd z)) (a,b) X ).\n    assert ( help := retr thePoint ).\n    assert ( helq := ap snd (ap (@projT1 _ _) help ) ).\n      lazy in helq.\n  exact (inverse helq).\nDefined.\n\nLemma hfibr_IsFunc { A B } ( P : A -> B -> Type ) ( H : IsFunctional P ) : \n  forall a, (sigT (P a)) -> hfiber (sigMap P) a.\nProof.\n  intros a [ b x ].\n  exists (@existT _ (fun z => P (fst z) (snd z)) (a,b) x).\n  auto.\nDefined.\n\nLemma fibrMap_IsFunc { A B } ( P : A -> B -> Type ) ( H : IsFunctional P ) : \n  forall a,  hfiber (sigMap P) a -> (sigT (P a)) .\nProof.\n  intros a [ abp eq ].\n  destruct abp as [ [ a' b' ] x ].\n  simpl in eq. destruct eq.\n  exists b'. auto.\nDefined.\n\nLemma equiv_hfibr_IsFunc { A B } ( P : A -> B -> Type ) ( H : IsFunctional P ) : \n  forall a, IsEquiv (hfibr_IsFunc P H a).\nProof.\n  intros.\n  apply isequiv_adjointify with (fibrMap_IsFunc P H a).\n  intro.\n    destruct x as [ [ [ a' b' ] p ] eq ].\n    simpl in *.\n    destruct eq.\n    auto.\n  intro.\n    destruct x as [ b x ].\n    auto.\nDefined.\n\nLemma contr_IsFunc { A B } ( P : A -> B -> Type ) ( H : IsFunctional P ) : \n  forall a, Contr (sigT (P a)).\nProof.\n  assert ( help := fcontr_isequiv _ H ).\n  intro a.\n    set ( theEquiv := BuildEquiv _ _ (hfibr_IsFunc P H a) (equiv_hfibr_IsFunc P H a) ).\n  refine ( contr_equiv (theEquiv ^-1)%equiv).\nDefined.\n\n", "meta": {"author": "jcmckeown", "repo": "hott_ss", "sha": "a565d2f0b0add8a2925be3dbda90669d58e73d07", "save_path": "github-repos/coq/jcmckeown-hott_ss", "path": "github-repos/coq/jcmckeown-hott_ss/hott_ss-a565d2f0b0add8a2925be3dbda90669d58e73d07/FunctionRels.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6613525290469374}}
{"text": "Require Import Coq.Bool.Bool.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\n\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Notations.\nRequire Import Crypto.Util.ZUtil.Land.\nRequire Import Crypto.Util.ZUtil.Testbit.\nRequire Import Crypto.Util.ZUtil.TwosComplement.\n\nRequire Import Crypto.Util.ZUtil.Tactics.SolveRange.\n\nImport Notations.\n\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma sign_bit_0_land_pow2 a m :\n    Z.sign_bit m a = 0 -> a &' 2 ^ (m - 1) = 0.\n  Proof.\n    intros H; apply Z.shiftr_eq_0_iff in H; destruct H as [? |[? ?] ]; subst.\n    - rewrite Z.land_0_l; reflexivity.\n    - rewrite Z.land_pow2_testbit, Z.bits_above_log2; lia. Qed.\n\n  Lemma sign_bit_testbit a m\n        (Hm : 0 < m)\n        (H : 0 <= a < 2 ^ m) :\n    Z.sign_bit m a = Z.b2z (Z.testbit a (m - 1)).\n  Proof.\n    rewrite Z.testbit_spec', Z.mod_small, <- Z.shiftr_div_pow2 by Z.solve_range.\n    reflexivity. Qed.\n\n  Lemma sign_bit_equiv a m\n        (Hm : 0 < m)\n        (Ha : 0 <= a < 2 ^ m) :\n    Z.sign_bit m a = Z.b2z (negb (a <? 2 ^ (m - 1))).\n  Proof. rewrite <- (Z.mod_small _ _ Ha) at 2.\n         rewrite Z.twos_complement_cond_equiv, sign_bit_testbit, negb_involutive; lia. Qed.\n\n  Lemma sign_bit_1_land_pow2 a m\n        (Hm : 0 < m)\n        (Ha : 0 <= a < 2 ^ m) :\n    Z.sign_bit m a <> 0 -> a &' 2 ^ (m - 1) = 2 ^ (m - 1).\n  Proof.\n    intros H. rewrite Z.land_pow2_testbit, Z.testbit_b2z, <- sign_bit_testbit by assumption.\n    apply Z.eqb_neq in H; rewrite H; reflexivity. Qed.\n\n  Lemma sign_bit_0_testbit a m\n        (Hm : 0 < m) :\n    Z.sign_bit m a = 0 -> Z.testbit a (m - 1) = false.\n  Proof.\n    assert (Hnz : 2 ^ (m - 1) <> 0) by (apply Z.pow_nonzero; lia).\n    intro H; apply sign_bit_0_land_pow2 in H. rewrite Z.land_pow2_testbit in H;\n                                                destruct (Z.testbit a (m - 1));\n                                                [contradiction|reflexivity]. Qed.\n\n  Lemma sign_bit_1_testbit a m\n        (Hm : 0 < m)\n        (Ha : 0 <= a < 2 ^ m) :\n    Z.sign_bit m a <> 0 -> Z.testbit a (m - 1) = true.\n  Proof.\n    rewrite Z.testbit_b2z, <- sign_bit_testbit by lia; intro H.\n    apply Z.eqb_neq in H; rewrite H; reflexivity. Qed.\nEnd Z.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Util/ZUtil/SignBit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.6613057056103874}}
{"text": "Require Import Arith List.\nSet Implicit Arguments.\nRequire Export Coq.Init.Datatypes.\nRequire Import Coq.Program.Equality.\n\n(** * Heterogeneous Environment List\n    This doesn't diverge too wildly from standard HList implemenations.\n    A good reference, and the implementation this version is based on is\n    http://adam.chlipala.net/cpdt/html/DataStruct.html\n*)\n\nSection envlist.\n  (*Definition var := nat.\n  Definition var_dec := eq_nat_decide.*)\n  Inductive var : Type :=\n    | VZero : var\n    | VSucc : var -> var.\n  Lemma var_dec : forall (a b:var), {a=b}+{a<>b}.\n    intro a. induction a; intros; dependent inversion b. left; reflexivity. right. discriminate. right. discriminate.\n    induction (IHa v). subst. left; reflexivity. right. intro bad. inversion bad. apply b0. auto.\n  Defined.\n\n  Definition tyenv := list (var * Set).\n  Inductive tymember (x:var) (t:Set) : list (var*Set) -> Type :=\n  | TFirst : forall tl, tymember x t ((x,t)::tl)\n  | TLater : forall y ty tl, tymember x t tl -> tymember x t ((y,ty)::tl).\n  Fixpoint tyrem (x:var) (t:Set) {l:list(var*Set)} (m:tymember x t l) : list(var*Set):=\n    match m with\n    | TFirst tl => tl\n    | TLater y ty tl tm0 => tyrem tm0\n    end.\n  \n  Inductive envlist : list (var*Set) -> Type:=\n  | ENil : envlist nil\n  | ECons : forall (x:var) (t:Set) (ls:list (var*Set)), t -> envlist ls -> envlist ((x,t)::ls).\n  \n  Check ECons.\n  Inductive envmember : forall (x:var) (t:Set) (l:list(var*Set)), envlist l -> Type :=\n  | EFirst : forall x t val l tl, @envmember x t ((x,t)::l) (ECons x val tl)\n  | ELater : forall x t y ty val l tl,\n                    @envmember x t _ tl ->\n                    @envmember x t ((y,ty)::l) (ECons y val tl).\n  Fixpoint envlookup (x:var) (t:Set) {l:list(var*Set)} (e:envlist l) (mem:envmember x t e) : t :=\n    match mem with\n      | EFirst _ _ v _ _ => v\n      | ELater x' t' _ _ _ _ _ next => envlookup (*x' t' _ _*) next\n      end. \n  Print envlookup.\n\n  (* This generates a hideous term, but fortunately we never really need to extract it. *)\n  Fixpoint tymem2envmem (x:var) (t:Set) {l:list(var*Set)} (tm:tymember x t l) (e:envlist l) : envmember x t e.\n  destruct tm. dependent induction e. constructor.\n  dependent induction e. constructor. firstorder. Defined.\n\n  \n  Fixpoint envrem (x:var) (t:Set) {l:list(var*Set)} (e:envlist l) (mem:envmember x t e) (tm:tymember x t l): envlist (tyrem tm).\n  destruct tm. dependent induction e; compute[tyrem]; fold tyrem; auto.\n  unfold tyrem; fold tyrem.\n  assert (etl : envlist tl). dependent induction e. assumption.\n  eapply (envrem x t tl etl). eapply tymem2envmem. assumption.\n  Defined.\n\n  Parameter x : var.\n  Check envlookup.\n  Definition test : nat. refine(@envlookup x nat _ (ECons x 0 ENil) _). constructor. Defined.\n  Lemma findx : test = 0. eauto. Qed.\n\n\nEnd envlist.\n\nNotation \"'ε'\" := (@nil (var*Set)).\nNotation \" x : t , Γ \" := ((x,t)::Γ) (at level 30, right associativity).\nNotation \"∅\" := ENil.\nNotation \" x ↦ v , E \" := (ECons x v E) (at level 30, right associativity).\n\nSection env_notation_tests.\n  Parameter y : var. Parameter z : var.\n  Check (y:nat,z:bool,ε).\n\n  Check (y↦3,z↦true,∅).\n\nEnd env_notation_tests.\n", "meta": {"author": "csgordon", "repo": "rgref", "sha": "9f66be539d584b0a1ca18f67a13c07dc6b4d310a", "save_path": "github-repos/coq/csgordon-rgref", "path": "github-repos/coq/csgordon-rgref/rgref-9f66be539d584b0a1ca18f67a13c07dc6b4d310a/RGref/DSL/LinearEnv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6613057009682023}}
{"text": "(* \n  Autor(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\n(* \n  Problem(s):\n    Simple Semi-unification (SSemiU)\n    Semi-unification (SemiU)\n    Right-uniform Two-Inequality Semi-unification (RU2SemiU)\n    Left-uniform Two-Inequality Semi-unification (LU2SemiU)\n*)\n\n(*\n  Literature:\n  [1] Andrej Dudenhefner. \"Undecidability of Semi-Unification on a Napkin\"\n      5th International Conference on Formal Structures for Computation and Deduction (FSCD 2020): 9:1-9:16\n      https://drops.dagstuhl.de/opus/volltexte/2020/12331\n*)\n\nRequire Import List.\n\n(* terms are built up from atoms and a binary term constructor arr *)\nInductive term : Set :=\n  | atom : nat -> term\n  | arr : term -> term -> term.\n\nDefinition valuation : Set := nat -> term.\n\n(* substitute atoms n of a term t by (f n) *)\nFixpoint substitute (f: valuation) (t: term) : term :=\n  match t with\n  | atom n => f n\n  | arr s t => arr (substitute f s) (substitute f t)\n  end.\n\n(* Simple Semi-unification Definition *)\n\n(* simple semi unification constraint\n  ((a, x), (y, b)) mechanizes the constraint (a|x|ϵ ≐ ϵ|y|b) *)\nDefinition constraint : Set := ((bool * nat) * (nat * bool)).\n\n(* constraint semantics, \n  (φ, ψ0, ψ1) models a|x|ϵ ≐ ϵ|y|b if ψa (φ (x)) = πb (φ (y)) *)\nDefinition models (φ ψ0 ψ1: valuation) : constraint -> Prop :=\n  fun '((a, x), (y, b)) => \n    match φ y with\n    | atom _ => False\n    | arr s t => (if b then t else s) = substitute (if a then ψ1 else ψ0) (φ x)\n    end.\n\n(* Simple Semi-unification *)\n(* are there substitutions (φ, ψ0, ψ1) that model each constraint? *)\nDefinition SSemiU (p : list constraint) := \n  exists (φ ψ0 ψ1: valuation), forall (c : constraint), In c p -> models φ ψ0 ψ1 c.\n\n\n(* Semi-unification Definition *)\n\n(* inequality: s ≤ t *)\nDefinition inequality : Set := (term * term).\n\n(* φ solves s ≤ t, if there is ψ such that ψ (φ (s)) = φ (s) *)\nDefinition solution (φ : valuation) : inequality -> Prop := \n  fun '(s, t) => exists (ψ : valuation), substitute ψ (substitute φ s) = substitute φ t.\n\n(* Semi-unification *)\n(* is there a substitution φ that solves all inequalities? *)\nDefinition SemiU (p: list inequality) := \n  exists (φ: valuation), forall (c: inequality), In c p -> solution φ c.\n\n(* Right-uniform Two-Inequality Semi-unification *)\n(* All right-hand sides of inequalities are identical, there are exactly two inequlities *)\nDefinition RU2SemiU : term * term * term -> Prop := \n  fun '(s0, s1, t) => exists (φ ψ0 ψ1: valuation), \n    substitute ψ0 (substitute φ s0) = substitute φ t /\\ substitute ψ1 (substitute φ s1) = substitute φ t.\n\n(* Left-uniform Two-Inequality Semi-unification *)\n(* All right-hand sides of inequalities are identical, there are exactly two inequlities *)\nDefinition LU2SemiU : term * term * term -> Prop := \n  fun '(s, t0, t1) => exists (φ ψ0 ψ1: valuation), \n    substitute ψ0 (substitute φ s) = substitute φ t0 /\\ substitute ψ1 (substitute φ s) = substitute φ t1.\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/SemiUnification/SemiU.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6612047197297303}}
{"text": "\nRequire Import Coq.Relations.Relation_Definitions.\n\nRequire Import Axioms.\n\nRequire Import Tactics.\nRequire Import Equality.\nRequire Import Sigma.\n\n\nLocal Open Scope type_scope.\n\n\n\n(* Ordered families of equivalences *)\n\nRecord ofe : Type :=\nmk_ofe\n  { car : Type;\n    dist : nat -> (relation car);\n    dist_eqrel : forall n, equiv car (dist n);\n    dist_limeq : forall x y, (forall n, dist n x y) -> x = y;\n    dist_downward : forall n x y, dist (S n) x y -> dist n x y;\n    dist_zero : forall x y, dist 0 x y }.\n\nArguments dist {o} n x y.\n\n\nDefinition dist_refl (A : ofe) n := dist_eqrel A n andel.\nDefinition dist_trans (A : ofe) n := dist_eqrel A n anderl.\nDefinition dist_symm (A : ofe) n := dist_eqrel A n anderr.\n\n\nLemma dist_refl' :\n  forall A n (x y : car A),\n    x = y\n    -> dist n x y.\nProof.\nintros A n x y H.\nsubst y.\napply dist_refl.\nQed.\n\n\nLemma downward_leq :\n  forall (A : Type) (R : nat -> relation A) m n (x y : A),\n    (forall n x y, R (S n) x y -> R n x y)\n    -> m <= n\n    -> R n x y\n    -> R m x y.\nProof.\nintros A R m n x y Hdownward Hleq Hdist.\nrevert Hdist.\ninduct Hleq; auto.\nQed.\n\n\nLemma dist_downward_leq :\n  forall (A : ofe) m n (x y : car A),\n    m <= n\n    -> dist n x y\n    -> dist m x y.\nProof.\nintros A m n x y Hleq Hdist.\neapply downward_leq; eauto; [].\nintros; apply dist_downward; auto.\nQed.\n\n\nLemma dist_downward_pred :\n  forall (A : ofe) n (x y : car A),\n    dist n x y\n    -> dist (pred n) x y.\nProof.\nintros A n x y H.\ndestruct n as [| n'].\n- simpl.\n  apply dist_zero.\n\n- simpl.\n  apply dist_downward; auto.\nQed.\n\n\nLemma dist_if_pos :\n  forall (A : ofe) n (x y : car A),\n    (n > 0 -> dist n x y)\n    -> dist n x y.\nProof.\nintros A n x y Hdist.\ndestruct n as [| n].\n  {\n  apply dist_zero.\n  }\napply Hdist.\nomega.\nQed.\n\n\n(* Nonexpansiveness/Contractiveness *)\n\nDefinition nonexpansive {A B : ofe} (f : car A -> car B) :=\n  forall n x y, dist n x y -> dist n (f x) (f y).\n\nDefinition contractive {A B : ofe} (f : car A -> car B) :=\n  forall n x y, dist n x y -> dist (S n) (f x) (f y).\n\n\nLemma ident_nonexpansive :\n  forall (A : ofe),\n    @nonexpansive A A (fun x => x).\nProof.\nintros A n x y Hxy.\nassumption.\nQed.\n\n\nLemma const_nonexpansive :\n  forall (A B : ofe) (x : car B),\n    @nonexpansive A B (fun _ => x).\nProof.\nintros A B x.\nintros n _ _ _.\napply dist_refl.\nQed.\n\n\nLemma transport_nonexpansive :\n  forall A (B : A -> ofe) i a a' (x y : car (B a)) (h : a = a'),\n    @dist (B a) i x y\n    -> @dist (B a') i (transport h (fun z => car (B z)) x) (transport h (fun z => car (B z)) y).\nProof.\nintros A B i a a' x y h Hdist.\nsubst a'.\ncbn.\nexact Hdist.\nQed.\n\n\n(* not used anywhere *)\nLemma transport_noncontractive :\n  forall A (B : A -> ofe) i a a' (x y : car (B a)) (h : a = a'),\n    dist i (transport h (fun z => car (B z)) x) (transport h (fun z => car (B z)) y)\n    -> dist i x y.\nProof.\nintros A B i a a' x y h H.\nsubst a'.\nauto.\nQed.\n\n\nLemma compose_ne_ne :\n  forall (A B C : ofe) f g,\n    @nonexpansive B C f\n    -> @nonexpansive A B g\n    -> nonexpansive (fun x => f (g x)).\nProof.\nintros A B C f g Hnef Hneg.\nintros n x y Hxy.\nso (Hneg _#3 Hxy) as Hgxy.\nso (Hnef _#3 Hgxy) as Hfgxy.\nexact Hfgxy.\nQed.\n\n\n(* Convergence *)\n\nDefinition convergent {A : Type} (d : nat -> relation A) (f : nat -> A) :=\n  forall n, d n (f n) (f (S n)).\n\nLemma convergent_leq_gen :\n  forall A (R : nat -> relation A) f,\n    (forall n, equiv _ (R n))\n    -> (forall n x y, R (S n) x y -> R n x y)\n    -> convergent R f\n    -> forall m n, m <= n -> R m (f m) (f n).\nProof.\nintros A R f Hequiv Hdownward Hconv m n Hleq.\ninduct Hleq.\n\n(* eq *)\n{\napply (Hequiv _ andel).\n}\n\n(* S *)\n{\nintros n Hleq IH.\napply (Hequiv m anderl _ (f n)); auto; [].\neapply downward_leq; eauto.\n}\nQed.\n\n\nLemma convergent_leq :\n  forall A f,\n    convergent (@dist A) f\n    -> forall m n, m <= n -> dist m (f m) (f n).\nProof.\nintros A f Hconv m n Hleq.\napply convergent_leq_gen; auto.\n- auto using dist_eqrel.\n\n- auto using dist_downward.\nQed.\n\n\nLemma const_convergent :\n  forall A x,\n    convergent (@dist A) (fun _ => x).\nProof.\nintros A x.\nintros n.\napply dist_refl; done.\nQed.\n\n\nLemma map_convergent_prim :\n  forall (A B : Type) (d : nat -> relation A) (d' : nat -> relation B) (ch : nat -> A) (f : A -> B),\n    (forall n x y, d n x y -> d' n (f x) (f y))\n    -> convergent d ch\n    -> convergent d' (fun i => f (ch i)).\nProof.\nintros A B d d' ch f Hne Hconv.\nintro i.\napply Hne; [].\napply Hconv.\nQed.\n\n\nLemma map_convergent :\n  forall (A B : ofe) (ch : nat -> car A) (f : car A -> car B),\n    nonexpansive f\n    -> convergent (@dist A) ch\n    -> convergent (@dist B) (fun i => f (ch i)).\nProof.\nintros A B ch f Hne Hconv.\neapply map_convergent_prim; eauto.\nQed.\n\n\n(* Limits *)\n\n(* It's convenient to require that cofes be nonempty, since they are easier\n   to work with, and all the cofes we consider are nonempty anyway.\n\n   Now that I've embraced the description axiom, I would probably state\n   completeness more conveniently, as an existence statement in Prop.\n   Maybe change it if I ever make serious use of completeness.\n*)\nRecord complete (A : ofe) : Type :=\nmk_complete\n  { limit : forall ch, convergent dist ch -> car A;\n    inhabitant : car A;\n\n    complete_dist : forall ch n (p : convergent dist ch), dist n (limit ch p) (ch n) }.\n\nArguments limit {A} c.\nArguments inhabitant {A} c.\n\n\n(* Give limit a less-awful interface. *)\nDefinition limits {A : ofe} (ch : nat -> car A) (x : car A) :=\n  forall n,\n    dist n (ch n) x.\n\n\nLemma limits_to_limit :\n  forall (A : ofe) (C : complete A) (ch : nat -> car A) (x : car A),\n    limits ch x\n    -> forall p, limit C ch p = x.\nProof.\nintros A C ch x Hlimits Hconv.\napply dist_limeq; [].\nintro n.\neapply dist_trans.\n  - apply complete_dist.\n\n  - apply Hlimits.\nQed.\n\n\nLemma limit_to_limits :\n  forall (A : ofe) (C : complete A) (ch : nat -> car A) (p : convergent (@dist A) ch),\n    limits ch (limit C ch p).\nProof.\nintros A C ch p.\nintro n.\napply dist_symm; [].\napply complete_dist.\nQed.\n\n\nLemma limits_unique :\n  forall (A : ofe) (ch : nat -> car A) (x y : car A),\n    limits ch x\n    -> limits ch y\n    -> x = y.\nProof.\nintros A ch x y Hlimx Hlimy.\napply dist_limeq; [].\nintro n.\neapply dist_trans.\n- apply dist_symm; [].\n  apply Hlimx.\n\n- apply Hlimy.\nQed.\n\n\nLemma limits_const :\n  forall (A : ofe) (x : car A),\n    limits (fun i => x) x.\nProof.\nintros A x.\nintro n.\napply dist_refl.\nQed.\n\n\nLemma limits_truncate :\n  forall (A : ofe) (ch : nat -> car A) (x : car A) n,\n    limits ch x\n    -> limits (fun i => ch (Nat.add n i)) x.\nProof.\nintros A ch x n Hlim.\nintro i.\napply (dist_downward_leq _ i (n+i)).\n- omega.\n\n- apply Hlim.\nQed.\n\n\n(* We could strengthen this lemma (eliminate the convergent requirement)\n   if we weakened the definition of limits to permit slower convergence.\n   But the stronger convergence is awfully convenient, and this isn't unworkable.\n*)\nLemma limits_prepend :\n  forall (A : ofe) (C : complete A) (ch : nat -> car A) (x : car A) n,\n    convergent (@dist A) ch\n    -> limits (fun i => ch (n + i)%nat) x\n    -> limits ch x.\nProof.\nintros A C ch x n Hconv Hlim.\nso (limit_to_limits _ C _ Hconv) as Hlim'.\nso (limits_truncate _#3 n Hlim') as Hlim''.\nso (limits_unique _#4 Hlim Hlim'').\nsubst x.\nexact Hlim'.\nQed.\n\n\nLemma limits_convergent :\n  forall (A : ofe) (ch : nat -> car A) (x : car A),\n    limits ch x\n    -> convergent (@dist A) ch.\nProof.\nintros A ch x Hlim.\nintro i.\napply (dist_trans _ _ _ x).\n- apply Hlim.\n\n- apply dist_symm; [].\n  apply dist_downward; [].\n  apply Hlim.\nQed.\n\n\nLemma ofe_fixpoint :\n  forall (A : ofe) (C : complete A) (f : car A -> car A),\n    contractive f\n    -> existsT! (x : car A), f x = x.\nProof.\nintros A C f Hcontract.\nset (ch := @nat_rect (fun _ => car A) (inhabitant C) (fun _ x => f x)).\nassert (convergent (@dist A) ch) as p.\n  {\n  intros i.\n  induct i.\n  - apply dist_zero.\n\n  - intros i IH.\n    simpl.\n    apply Hcontract; [].\n    exact IH.\n  }\nexists (limit C ch p).\nassert (f (limit C ch p) = limit C ch p) as Hfix.\n  {\n  so (limit_to_limits A C ch p) as Hlimits.\n  apply (limits_unique _ ch); auto; [].\n  apply (limits_prepend _ C _ _ 1); auto; [].\n  simpl.\n  intro i.\n  apply dist_downward; [].\n  apply Hcontract; [].\n  apply Hlimits.\n  }\nsplit; auto; [].\nintros y Hfix'.\napply dist_limeq; [].\nintro i.\ninduct i.\n- apply dist_zero.\n\n- intros i IH.\n  rewrite <- Hfix; [].\n  rewrite <- Hfix'; [].\n  apply Hcontract.\n  assumption.\nQed.\n\n\n(* Nonexpansive function space *)\n\nDefinition nearrow (A B : ofe) : Type := exT (car A -> car B) (@nonexpansive A B).\n\n\nNotation \"A -n> B\" := (nearrow A B)\n  (at level 99, right associativity) : ofe_scope.\n\n\nOpen Scope ofe_scope.\n\n\nDefinition nearrow_const (A : ofe) (B : ofe) (x : car B) : A -n> B :=\n  expair (fun _ => x) (const_nonexpansive A B x).\n\n\nDefinition idne {A : ofe} : A -n> A := expair _ (ident_nonexpansive A).\n\n\nDefinition dist_ne {A B : ofe} n (f g : A -n> B) := forall x, dist n (pi1 f x) (pi1 g x).\n\n\nDefinition limit_ne {A B : ofe} (C : complete B) :\n  forall ch, convergent (@dist_ne A B) ch -> A -n> B.\nProof.\nintros f Hconv.\nexists (fun x : car A => limit C (fun i => pi1 (f i) x) (fun n => Hconv n x)).\nintros n x y Hdist.\napply (dist_trans B n _ (pi1 (f n) x)).\n- so (complete_dist B C _ n (fun n => Hconv n x)) as H.\n  simpl in H.\n  exact H.\n\n- apply (dist_trans B n _ (pi1 (f n) y)).\n  + so (pi2 (f n)) as Hne.\n    exact (Hne n x y Hdist).\n\n  + apply (dist_symm B n); [].\n    so (complete_dist B C _ n (fun n => Hconv n y)) as H.\n    simpl in H.\n    exact H.\nDefined.\n\n\nLemma nearrow_extensionality :\n  forall A B (f g : A -n> B),\n    (forall x, pi1 f x = pi1 g x)\n    -> f = g.\nProof.\nintros A B f g H.\napply exT_extensionality_prop.\nfextensionality 1.\nexact H.\nQed.\n\n\nLemma nearrow_extensionality_dep :\n  forall A (B : A -> ofe) (C : ofe) (a a' : A) (f : B a -n> C) (g : B a' -n> C),\n    eq_dep A (fun a => car (B a) -> car C) a (pi1 f) a' (pi1 g)\n    -> eq_dep A (fun a => B a -n> C) a f a' g.\nProof.\nintros A B C a a' f g Heq.\nso (eq_dep_impl_eq_fst _#6 Heq); subst a'.\nso (eq_dep_impl_eq_snd _#5 Heq) as Heq'.\napply eq_impl_eq_dep_snd.\napply exT_extensionality_prop; auto.\nQed.\n\n\nDefinition nearrow_ofe (A B : ofe) : ofe.\nProof.\napply \n  (mk_ofe \n     (A -n> B)\n     (@dist_ne A B)).\n\n(* eqrel *)\n{\nintro n.\ndo2 2 split.\n+ intros f x.\n  apply (dist_refl B n).\n\n+ intros f g h Hfg Hgh x.\n  eapply (dist_trans B n); eauto.\n\n+ intros f g H x.\n  apply (dist_symm B n); [].\n  apply H.\n}\n\n(* limeq *)\n{\nintros f g Hsim.\ndestruct f as [f Hnef].\ndestruct g as [g Hneg].\ncut (f = g).\n  {\n  intro.\n  subst g.\n  f_equal; [].\n  apply proof_irrelevance.\n  }\napply functional_extensionality; [].\nintro x.\napply (dist_limeq B); [].\nintro n.\nexact (Hsim n x).\n}\n\n(* downward *)\n{\nintros n f g Hdist.\nintro x.\napply (dist_downward B); [].\nexact (Hdist x).\n}\n\n(* zero *)\n{\nintros f g x.\napply dist_zero.\n}\nDefined.\n\n\nDefinition nearrow_complete (A : ofe) (B : ofe) (C : complete B) : complete (nearrow_ofe A B).\nProof.\napply \n  (mk_complete (nearrow_ofe A B)\n     (@limit_ne A B C)\n     (expair (fun _ => inhabitant C) (const_nonexpansive _ _ _))).\nintros f n Hconv.\nintro x.\ncbn.\napply (complete_dist B).\nDefined.\n\n\nDefinition nearrow_id (A : ofe) : A -n> A :=\n  expair _ (ident_nonexpansive A).\n\nDefinition nearrow_compose {A B C : ofe} (f : B -n> C) (g : A -n> B) : A -n> C :=\n  expair _ (compose_ne_ne A B C (pi1 f) (pi1 g) (pi2 f) (pi2 g)).\n\n\nLemma nearrow_compose_id_left :\n  forall A B (f : A -n> B),\n    nearrow_compose (nearrow_id B) f = f.\nProof.\nintros A B f.\ndestruct f as [f Hne].\nunfold nearrow_compose.\nf_equal; [].\napply proof_irrelevance; done.\nQed.\n\n\nLemma nearrow_compose_id_right :\n  forall A B (f : A -n> B),\n    nearrow_compose f (nearrow_id A) = f.\nProof.\nintros A B f.\ndestruct f as [f Hne].\nunfold nearrow_compose.\nf_equal; [].\napply proof_irrelevance; done.\nQed.\n\n\nLemma nearrow_compose_assoc :\n  forall A B C D (f : C -n> D) (g : B -n> C) (h : A -n> B),\n    nearrow_compose (nearrow_compose f g) h = nearrow_compose f (nearrow_compose g h).\nProof.\nintros A B C D f g h.\ndestruct f as [f Hnef].\ndestruct g as [g Hneg].\ndestruct h as [h Hneh].\nunfold nearrow_compose; simpl.\nf_equal; [].\napply proof_irrelevance.\nQed.\n\n\nLemma nearrow_compose_nonexpansive :\n  forall A B C n (f f' : B -n> C) (g g' : A -n> B),\n    dist_ne n f f'\n    -> dist_ne n g g'\n    -> dist_ne n (nearrow_compose f g) (nearrow_compose f' g').\nProof.\nintros A B C n f f' g g' Hdistf Hdistg.\nintro x.\nsimpl.\ndestruct f as [f Hnef].\ndestruct f' as [f' Hnef'].\ndestruct g as [g Hneg].\ndestruct g' as [g' Hneg'].\nsimpl.\napply (dist_trans C n _ (f' (g x))).\n- apply Hdistf; done.\n\n- apply Hnef'; [].\n  apply Hdistg; done.\nQed.\n\n\nDefinition composer (A B C : ofe) (f : B -n> C) : nearrow_ofe A B -n> nearrow_ofe A C.\nProof.\nexists (fun g => nearrow_compose f g).\nintros n g g' Hg.\nrefine (nearrow_compose_nonexpansive _#8 _ Hg).\napply (@dist_refl (nearrow_ofe B C)).\nDefined.\n\n\nLemma eq_nearrow_ne :\n  forall (A B : ofe) (h : A = B),\n    nonexpansive (fun x => transport h car x).\nProof.\nintros A B h.\nsubst B.\napply ident_nonexpansive.\nQed.\n\n\nDefinition eq_nearrow {A B : ofe} (h : A = B) : A -n> B\n  :=\n  expair (fun x => transport h car x) (eq_nearrow_ne A B h).\n\n\nDefinition transport_ne {A} {a a' : A} (h : a = a') (B : A -> ofe)\n  : B a -n> B a'\n  :=\n  @expair\n    _ (@nonexpansive (B a) (B a'))\n    (fun x => transport h (fun z => car (B z)) x)\n    (fun i m n Hdist => transport_nonexpansive A B i a a' m n h Hdist).\n\n\nDefinition dep_transport_ne {A} {a a' : A} (h : a = a')\n  (B : A -> Type)\n  (C : forall a, B a -> ofe)\n  (b : B a)\n  : C a b -n> C a' (transport h B b)\n  :=\n  match h\n    as h\n    in _ = a'\n    return C a b -n> C a' (transport h B b)\n  with\n  | eq_refl _ => idne\n  end.\n\n\nDefinition dep_transport_ne' {A} {a a' : A} (h : a = a')\n  (B : A -> Type)\n  (C : forall a, B a -> ofe)\n  (b : B a)\n  : C a' (transport h B b) -n> C a b\n  :=\n  match h\n    as h\n    in _ = a'\n    return C a' (transport h B b) -n> C a b\n  with\n  | eq_refl _ => idne\n  end.\n\n\n(* We could reuse nearrow_compose, but it seems cleaner to do it directly. *)\nDefinition nearrow_compose2 {A B C D : ofe} (f : A -n> B) (h : C -n> D)\n  (g : B -n> C) : A -n> D.\nProof.\nrefine (expair (fun x => pi1 h (pi1 g (pi1 f x))) _).\nintros n x y Hxy.\napply (pi2 h).\napply (pi2 g).\napply (pi2 f); auto.\nDefined.\n\n\nLemma nearrow_compose2_nonexpansive :\n  forall A B C D (f : A -n> B) (h : C -n> D),\n    @nonexpansive (nearrow_ofe B C) (nearrow_ofe A D) (nearrow_compose2 f h).\nProof.\nintros A B C D f h.\nintros n g g' Hg.\ncbn.\nintros x.\ncbn.\napply (pi2 h).\napply Hg.\nQed.\n\n\nDefinition nearrow_compose2_ne {A B C D : ofe} (f : A -n> B) (h : C -n> D) \n  : nearrow_ofe B C -n> nearrow_ofe A D\n  :=\n  expair (nearrow_compose2 f h) (nearrow_compose2_nonexpansive _#4 f h).\n\n\nLemma nearrow_compose2_compose :\n  forall (A B C D E F : ofe) \n    (f1 : A -n> B) (f2 : B -n> C) (g : C -n> D) (h2 : D -n> E) (h1 : E -n> F),\n      nearrow_compose2 f1 h1 (nearrow_compose2 f2 h2 g)\n      =\n      nearrow_compose2 (nearrow_compose f2 f1) (nearrow_compose h1 h2) g.\nProof.\nintros A B C D E F f1 f2 g h2 h1.\napply nearrow_extensionality.\nintro x.\ncbn.\nreflexivity.\nQed.\n\n\nLemma nearrow_compose2_split :\n  forall A B C D (f : C -n> D) (g : B -n> C) (h : A -n> B),\n    nearrow_compose2 h f g\n    =\n    nearrow_compose f (nearrow_compose g h).\nProof.\nintros A B C D f g h.\napply nearrow_extensionality.\nintro x.\ncbn.\nreflexivity.\nQed.\n\n\n(* Product spaces *)\n\nDefinition dist_prod {A B : ofe} n (p q : car A * car B) :=\n  dist n (fst p) (fst q) /\\ dist n (snd p) (snd q).\n\n\nDefinition prod_ofe (A B : ofe) : ofe.\nProof.\napply (mk_ofe (car A * car B) (@dist_prod A B)).\n\n(* eqrel *)\n{\nintro n.\ndo2 2 split.\n+ intros (x, y).\n  split; apply dist_refl.\n\n+ intros (x1, y1) (x2, y2) (x3, y3) H12 H23.\n  destruct H12 as (H12x, H12y).\n  destruct H23 as (H23x, H23y).\n  split; eapply dist_trans; eauto.\n\n+ intros (x1, y1) (x2, y2) H.\n  destruct H as (Hx, Hy).\n  split; eapply dist_symm; eauto.\n}\n\n(* limeq *)\n{\nintros (x, y) (x', y') Hsim.\nf_equal.\n+ apply dist_limeq; [].\n  intro n.\n  destruct (Hsim n); auto.\n\n+ apply dist_limeq; [].\n  intro n.\n  destruct (Hsim n); auto.\n}\n\n(* downward *)\n{\nintros n (x, y) (x', y') Hdist.\ndestruct Hdist.\nsplit; apply dist_downward; eauto.\n}\n\n(* zero *)\n{\nintros (x, y) (x', y').\nsplit; apply dist_zero.\n}\nDefined.\n\n\nDefinition pair_ne {A B C : ofe} (f : A -n> B) (g : A -n> C)\n  : A -n> prod_ofe B C.\nProof.\nexists (fun x => (pi1 f x, pi1 g x)).\nexact (fun n x y H => conj (pi2 f n x y H) (pi2 g n x y H)).\nDefined.\n\n\nDefinition fst_ne {A B : ofe} : prod_ofe A B -n> A.\nProof.\nexists fst.\nintros n x y Hxy.\nexact (Hxy andel).\nDefined.\n\n\nDefinition snd_ne {A B : ofe} : prod_ofe A B -n> B.\nProof.\nexists snd.\nintros n x y Hxy.\nexact (Hxy ander).\nDefined.\n\n\nDefinition mpair_ne {A B C D : ofe} (f : A -n> C) (g : B -n> D)\n  : prod_ofe A B -n> prod_ofe C D.\nProof.\nexists (fun x => (pi1 f (fst x), pi1 g (snd x))).\nexact (fun n x y H => conj (pi2 f n _ _ (carp H)) (pi2 g n _ _ (cdrp H))).\nDefined.\n\n\nLemma dist_prod_fst :\n  forall A B n (p q : car (prod_ofe A B)),\n    dist n p q\n    -> dist n (fst p) (fst q).\nProof.\nintros A B n p q Hdist.\ndestruct Hdist.\nauto.\nQed.\n\n\nLemma dist_prod_snd :\n  forall A B n (p q : car (prod_ofe A B)),\n    dist n p q\n    -> dist n (snd p) (snd q).\nProof.\nintros A B n p q Hdist.\ndestruct Hdist.\nauto.\nQed.\n\n\nDefinition limit_prod (A B : ofe) (C : complete A) (D : complete B) :\n  forall ch, convergent (@dist_prod A B) ch -> car A * car B.\nProof.\nintros ch Hconv.\nsplit.\n  {\n  refine (limit C (fun i => fst (ch i)) _); [].\n  eapply map_convergent_prim; eauto; [].\n  intros n p q Hdist.\n  destruct Hdist; auto.\n  }\n  \n  {\n  refine (limit D (fun i => snd (ch i)) _); [].\n  eapply map_convergent_prim; eauto; [].\n  intros n p q Hdist.\n  destruct Hdist; auto.\n  }\nDefined.\n\n\nDefinition prod_complete (A B : ofe) (C : complete A) (D : complete B) : complete (prod_ofe A B).\nProof.\napply (mk_complete (prod_ofe A B) (limit_prod A B C D) (inhabitant C, inhabitant D)).\nintros ch n Hconv.\nso (Hconv n) as (H1 & H2).\nsplit.\n+ apply complete_dist.\n\n+ apply complete_dist.\nDefined.\n\n\nDefinition unit_ofe : ofe.\nProof.\napply\n  (mk_ofe\n     unit\n     (fun _ _ _ => True)).\n\n- do2 2 split; intro; auto.\n\n- intros x y _.\n  destruct x; destruct y.\n  reflexivity.\n\n- auto.\n\n- auto.\nDefined.\n\n\nDefinition unit_complete : complete unit_ofe.\nProof.\napply\n  (mk_complete unit_ofe\n     (fun _ _ => tt)\n     tt).\nintros ch n _.\nset (x := ch n).\ndestruct x.\napply dist_refl.\nDefined.\n", "meta": {"author": "kcrary", "repo": "istari", "sha": "42e71bc3bfba08542d005f27d100aa7537b1012b", "save_path": "github-repos/coq/kcrary-istari", "path": "github-repos/coq/kcrary-istari/istari-42e71bc3bfba08542d005f27d100aa7537b1012b/coq/Ofe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6612047134225759}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type :=  Nil : lst | Cons : natural -> lst -> lst .\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint 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. lfind.  reflexivity. \nAdmitted.\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\n", "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_goal80_rev_append_43_append_nil/goal80.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6611504156735993}}
{"text": "\nRequire Export Iron.Language.SystemF2Effect.Type.Operator.LiftTT.\nRequire Export Iron.Language.SystemF2Effect.Type.Relation.SubsT.\n\n\n(* If one type subsumes another, and we substitute some third\n   type into both, then the results are also subsumptive.\n\n   NOTE: The more general form where t1 and t2 are open should also\n         be true, but we don't need it for the main proofs.\n*)\nLemma subsT_closed_liftT_liftT\n :  forall sp t1 t2 k d\n ,  SubsT nil sp t1 t2 k\n -> SubsT nil sp (liftTT 1 d t1) (liftTT 1 d t2) k.\nProof.\n intros.\n have (ClosedT t1).\n have (ClosedT t2).\n rrwrite (liftTT 1 d t1 = t1).\n rrwrite (liftTT 1 d t2 = t2).\n auto.\nQed.\nHint Resolve subsT_closed_liftT_liftT. \n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Language/SystemF2Effect/Type/Operator/LiftTT/SubsT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6611504002387554}}
{"text": "Require Import Rbase MyRIneq.\nRequire Import Rsequence_def Rsequence_facts Rsequence_cv_facts.\n\nRequire Import List.\nRequire Import Option.\nRequire Import Ass_handling.\n\n(* Reifications of sequences, limits and being the limit of a\n   particular sequence. *)\n\nInductive rseq :=\n  | rseq_cst   : forall (r : R), rseq\n  | rseq_var   : forall (n : nat), rseq\n  | rseq_opp   : forall (r : rseq), rseq\n  | rseq_plus  : forall (rl rr : rseq), rseq\n  | rseq_minus : forall (rl rr : rseq), rseq.\n\nInductive rseq_limit :=\n  | minus_inf : rseq_limit\n  | finite : forall (l : R), rseq_limit\n  | plus_inf : rseq_limit.\n\nDefinition is_limit r l := match l with\n  | minus_inf => Rseq_cv_neg_infty r\n  | finite l => Rseq_cv r l\n  | plus_inf => Rseq_cv_pos_infty r\nend.\n\n(* Two extensionally equal sequences have the same limit. *)\n\nLemma is_limit_ext : forall r s k l,\n  is_limit r k ->\n  r == s -> k = l ->\n  is_limit s l.\nProof.\nintros r s k [] Hrk Hrs Hkl ;\n [ eapply Rseq_cv_neg_infty_eq_compat\n | eapply Rseq_cv_eq_compat ; [symmetry |]\n | eapply Rseq_cv_pos_infty_eq_compat ]\n ; subst ; eassumption.\nQed.\n\nDefinition Rseq_with_limit := {r : Rseq & {l : rseq_limit | is_limit r l}}.\n\nDefinition rseq_limit_opp l := match l with\n  | minus_inf => plus_inf\n  | finite u  => finite (- u)\n  | plus_inf  => minus_inf\nend.\n\nLemma rseq_limit_opp_is_limit : forall r l,\n  is_limit r l ->\n  is_limit (- r) (rseq_limit_opp l).\nProof.\nintros r [] Hl ; simpl ;\n [ apply Rseq_cv_neg_infty_opp_compat\n | apply Rseq_cv_opp_compat\n | apply Rseq_cv_pos_infty_opp_compat] ;\n assumption.\nQed.\n\nDefinition rseq_limit_add ll lr := match ll, lr with\n  | minus_inf, plus_inf  => None\n  | plus_inf , minus_inf => None\n  | minus_inf, _         => Some minus_inf\n  | _        , minus_inf => Some minus_inf\n  | plus_inf , _         => Some plus_inf\n  | _        , plus_inf  => Some plus_inf\n  | finite u , finite v  => Some (finite (u + v))\nend.\n\nFixpoint comp_limit (r : rseq) (env : list Rseq_with_limit) : option rseq_limit :=\nmatch r with\n  | rseq_cst r => Return (finite r)\n  | rseq_var n => Bind (nth_error env n) (fun x => Return (proj1_sig (projT2 x)))\n  | rseq_opp r => Bind (comp_limit r env) (fun l => Some (rseq_limit_opp l))\n  | rseq_plus rl rr => Bind (comp_limit rl env) (fun ll =>\n                       Bind (comp_limit rr env) (fun lr => rseq_limit_add ll lr))\n  | rseq_minus rl rr => Bind (comp_limit rl env) (fun ll =>\n                        Bind (comp_limit rr env) (fun lr => rseq_limit_add ll (rseq_limit_opp lr)))\nend.\n\nFixpoint comp_rseq (r : rseq) (env : list Rseq_with_limit) := match r with\n  | rseq_cst r => Return (Rseq_constant r)\n  | rseq_var n => Bind (nth_error env n) (fun un => Some (projT1 un))\n  | rseq_opp r => Bind (comp_rseq r env) (fun un => Some (Rseq_opp un))\n  | rseq_plus rl rr => Bind (comp_rseq rl env) (fun un =>\n                       Bind (comp_rseq rr env) (fun vn => Some (Rseq_plus un vn)))\n  | rseq_minus rl rr => Bind (comp_rseq rl env) (fun un =>\n                       Bind (comp_rseq rr env) (fun vn => Some (Rseq_minus un vn)))\nend.\n\nLtac fold_is_limit := match goal with\n  | |- Rseq_cv ?r ?l => fold (is_limit r (finite l))\n  | |- Rseq_cv_neg_infty ?r => fold (is_limit r minus_inf)\n  | |- Rseq_cv_pos_infty ?r => fold (is_limit r plus_inf)\nend.\n\nLemma comp_rseq_limit_compat : forall r env un l,\n  comp_rseq r env = Some un ->\n  comp_limit r env = Some l ->\n  is_limit un l.\nProof.\nintros r env ; induction r ; intros un l Hun Hl ; simpl in *.\n inversion Hun ; inversion Hl ; apply Rseq_constant_cv.\n destruct (nth_error env n) as [Hget |].\n  inversion Hun ; inversion Hl ; apply (proj2_sig (projT2 Hget)).\n  inversion Hl.\n destruct (comp_rseq r env) as [vn |] ; [| inversion Hun] ;\n  destruct (comp_limit r env) as [lo |] ; [| inversion Hl] ;\n  inversion Hun ; inversion Hl.\n  apply rseq_limit_opp_is_limit, IHr ; reflexivity.\n destruct (comp_rseq r1 env) as [vn |] ; [| inversion Hun] ;\n  destruct (comp_limit r1 env) as [ll |] ; [| inversion Hl] ;\n  destruct (comp_rseq r2 env) as [wn |] ; [| inversion Hun] ;\n  destruct (comp_limit r2 env) as [lr |] ; [| inversion Hl].\n   destruct ll ; destruct lr ; inversion Hun ; inversion Hl ;\n   subst.\n    apply Rseq_cv_neg_infty_plus_compat ; fold_is_limit ;\n     [apply IHr1 | apply IHr2] ; reflexivity.\n    eapply Rseq_cv_finite_plus_neg_infty_l ; fold_is_limit ;\n     [apply IHr1 | apply IHr2] ; reflexivity.\n    eapply Rseq_cv_finite_plus_neg_infty_r ; fold_is_limit ;\n     [apply IHr1 | apply IHr2] ; reflexivity.\n    eapply Rseq_cv_plus_compat ; fold_is_limit ;\n     [apply IHr1 | apply IHr2] ; reflexivity.\n    eapply Rseq_cv_finite_plus_pos_infty_r ; fold_is_limit ;\n     [apply IHr1 | apply IHr2] ; reflexivity.\n    eapply Rseq_cv_finite_plus_pos_infty_l ; fold_is_limit ;\n     [apply IHr1 | apply IHr2] ; reflexivity.\n    apply Rseq_cv_pos_infty_plus_compat ; fold_is_limit ;\n     [apply IHr1 | apply IHr2] ; reflexivity.\n destruct (comp_rseq r1 env) as [vn |] ; [| inversion Hun] ;\n  destruct (comp_limit r1 env) as [ll |] ; [| inversion Hl] ;\n  destruct (comp_rseq r2 env) as [wn |] ; [| inversion Hun] ;\n  destruct (comp_limit r2 env) as [lr |] ; [| inversion Hl].\n   inversion Hun ; eapply (is_limit_ext (Rseq_plus vn (Rseq_opp wn))) ;\n    [| intro n ; unfold Rseq_plus, Rseq_minus, Rseq_opp ; ring | reflexivity].\n   destruct ll ; destruct lr ; inversion Hl ; subst.\n    apply Rseq_cv_finite_plus_neg_infty_l with (- l0)%R ; fold_is_limit ;\n     [apply IHr1 | fold (rseq_limit_opp (finite l0)) ;\n     apply rseq_limit_opp_is_limit, IHr2] ; reflexivity.\n    apply Rseq_cv_neg_infty_plus_compat ; fold_is_limit ;\n     [apply IHr1 | fold (rseq_limit_opp plus_inf) ;\n     apply rseq_limit_opp_is_limit, IHr2] ; reflexivity.\n    apply Rseq_cv_finite_plus_pos_infty_r with l0 ; fold_is_limit ;\n     [apply IHr1 | fold (rseq_limit_opp minus_inf) ;\n     apply rseq_limit_opp_is_limit, IHr2] ; reflexivity.\n    apply Rseq_cv_plus_compat ; fold_is_limit ;\n     [apply IHr1 | fold (rseq_limit_opp (finite l1)) ;\n     apply rseq_limit_opp_is_limit, IHr2] ; reflexivity.\n    eapply Rseq_cv_finite_plus_neg_infty_r ; fold_is_limit ;\n     [apply IHr1 | fold (rseq_limit_opp plus_inf) ;\n     apply rseq_limit_opp_is_limit, IHr2] ; reflexivity.\n    apply Rseq_cv_pos_infty_plus_compat ; fold_is_limit ;\n     [apply IHr1 | fold (rseq_limit_opp minus_inf) ;\n     apply rseq_limit_opp_is_limit, IHr2] ; reflexivity.\n    apply Rseq_cv_finite_plus_pos_infty_l with (- l0)%R ; fold_is_limit ;\n     [apply IHr1 | fold (rseq_limit_opp (finite l0)) ;\n     apply rseq_limit_opp_is_limit, IHr2] ; reflexivity.\nQed.\n\nDefinition rseq_precondition r env un l :=\nmatch comp_rseq r env with\n  | None    => False\n  | Some vn =>\n  match comp_limit r env with\n    | None => False\n    | Some v => (un == vn) /\\ (l = v)\n  end\nend.\n\nLemma tactic_correctness : forall r env un l,\n   rseq_precondition r env un l ->\n   is_limit un l.\nProof.\nunfold rseq_precondition ; intros r env un l ;\n destruct_eq (comp_rseq r env) ;\n destruct_eq (comp_limit r env) ;\n intros [].\n intros ; eapply is_limit_ext ;\n  [ eapply comp_rseq_limit_compat | |] ;\n  symmetry ; eassumption.\nQed.\n\n\n\n(*\n\nSection Test.\n\nLtac add_var v l :=\n  let rec aux v l n := match l with\n    | nil       => constr: (n , v :: nil)\n    | v  :: _   => constr: (n , l)\n    | ?a :: ?tl => match aux v tl (S n) with | (?m , ?tl') => constr: (m , cons a tl') end\n    end in\n  aux v l O.\n\nLtac known_limit An := match goal with\n  | [ H: is_limit An ?a |- _ ] => constr: (Some (An , a , H))\n  | _                          => constr: (None  )\nend.\n\nLtac reify_rseq_aux f l := match f with\n  | Rseq_constant ?v  => constr: (rseq_cst v , l)\n  | Rseq_opp  ?un     =>\n        match reify_rseq_aux un l  with | (?UN , ?l1) => constr: (rseq_opp UN , l1) end\n  | Rseq_plus ?un ?vn =>\n        match reify_rseq_aux un l  with | (?UN , ?l1) =>\n        match reify_rseq_aux vn l1 with | (?VN , ?l2) => constr: (rseq_plus UN VN , l2) end end\n  | Rseq_minus ?un ?vn =>\n        match reify_rseq_aux un l  with | (?UN , ?l1) =>\n        match reify_rseq_aux vn l1 with | (?VN , ?l2) => constr: (rseq_minus UN VN , l2) end end\n  | ?An =>\n        match known_limit An with | None => fail | Some ?a =>\n        match add_var a l with | (?A , ?l1) => constr: (rseq_var A , l1) end end\nend.\n\nCheck tactic_correctness.\n\nLtac reify_rseq := match goal with\n  | |- Rseq_cv ?f ?l =>\n        match reify_rseq_aux f (@nil Rseq_with_limit) with | (?r , ?env) =>\n        change (is_limit f (finite l)) end end.\n\n\nVariable Un Vn : Rseq.\nVariable u  v  : R.\n\nHypothesis Un_cv : Rseq_cv Un u.\nHypothesis Vn_cv : Rseq_cv Vn v.\n\n\nGoal Rseq_cv Un u.\nProof.\nfold (is_limit Un (finite u)) in *.\nfold (is_limit Vn (finite v)) in *.\nreify_rseq.\n  apply (tactic_correctness (rseq_var 0) (Un :: nil) Un (finite u)).\n\n  with (r := r) (env := env) \n eapply tactic_correctness.\n*)\n", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/src/Reals/Rsequence/Rsequence_tactics_reflection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6611447447466843}}
{"text": "\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\n\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.limits.graphs.colimits.\n\nRequire Import UniMath.Combinatorics.StandardFiniteSets.\nRequire Import UniMath.Combinatorics.FiniteSets.\n\nLocal Open Scope cat.\nLocal Open Scope stn.\n\n(** * Standard graphs and diagrams.\n\n    Contents\n    1. Graphs\n    2. Diagram constructors\n    3. Cocone constructors\n\n *)\n\nSection graphs.\n  (**\n   1. Graphs.\n   *)\n\n  Definition empty_graph : graph\n    := make_graph empty (λ _ _, empty).\n\n  Definition unit_graph : graph\n    := make_graph unit (λ _ _, empty).\n\n  (* The graph with two verticies, true and false, no edges. *)\n  Definition bool_graph : graph\n    := make_graph bool (λ _ _, empty).\n\n    (* The interval graph: true ---tt---> false *)\n  Definition interval_graph : graph.\n  Proof.\n    use make_graph.\n    - exact bool.\n    - intros a b.\n      induction a; induction b.\n      + exact empty.\n      + exact unit.             (* true --> false *)\n      + exact empty.\n      + exact empty.\n  Defined.\n\n  (* (● 1) <------ (● 0) ------> (● 2) *)\n  Definition span_graph : graph.\n  Proof.\n    use make_graph.\n    - exact three.\n    - use three_rec.\n      + apply three_rec.\n        * exact empty.\n        * exact unit.\n        * exact unit.\n      + exact(λ _, empty).\n      + exact(λ _, empty).\n  Defined.\n\n  (* X as verticies, no edges. *)\n  Definition discrete_graph (X : UU) : graph\n    := make_graph X (λ _ _, empty).\n\n\n  (* The graph with two verticies: (● 0) and (● 1),\n     and X as edges from (● 0) to (● 1), no other edges.\n\n     Input \\mdlgblkcircle for ●, or use (stnpr 0) and (stnpr 1) *)\n\n  Definition parallell_graph (X : UU) : graph.\n  Proof.\n    use make_graph.\n    - exact two.\n    - use two_rec_dep.\n      + exact(two_rec empty X).\n      + exact(λ _, empty).\n  Defined.\n\n  Definition parallell_start {X : UU}\n    : vertex (parallell_graph X)\n    := (● 0).\n\n  Definition parallell_end {X : UU}\n    : vertex (parallell_graph X)\n    := (● 1).\n\n  Definition parallell_edge {X : UU}\n    (e : X)\n    : @edge (parallell_graph X) parallell_start parallell_end\n    := e.\n\n  (* Two parallell edges, pair_left, pair_right : : pair_src --> pair_end. *)\n\n  Definition pair_graph : graph\n    := parallell_graph (unit ⨿ unit).\n\n  Definition pair_src : vertex pair_graph\n    := (● 0).\n\n  Definition pair_dst : vertex pair_graph\n    := (● 1).\n\n  Definition pair_left : @edge pair_graph pair_src pair_dst\n    := inl tt.\n\n  Definition pair_right : @edge pair_graph pair_src pair_dst\n    := inr tt.\n\n  (* Multi span: One base vertex (inr tt) and X verticies\n     with one unique edge from the base each, no other edges. *)\n  Definition multispan_graph (X : UU) : graph.\n  Proof.\n    use make_graph.\n    - exact(X ⨿ unit).          (* inr tt is the base point. *)\n    - use coprod_rect.\n      + exact(λ _ _, empty).    (* No edges x --> unit *)\n      + apply unit_rect.\n        apply coprod_rect.\n        * exact(λ _, unit).     (* One edge unit --> x *)\n        * exact(λ _, empty).    (* No edge unit --> unit *)\n  Defined.\n\n  Definition multispan_vertex {X : UU}\n    (x : X)\n    : vertex (multispan_graph X)\n    := (inl x).\n\n  Definition multispan_base {X : UU}\n    : vertex (multispan_graph X)\n    := (inr tt).\n\n  Definition multispan_edge {X : UU}\n    (x : X)\n    : edge multispan_base (multispan_vertex x)\n    := tt.\n\nEnd graphs.\n\nSection diagrams.\n  (**\n   2. Diagram constructors.\n   *)\n\n  Definition make_empty_diagram {C : category}\n    : diagram empty_graph C\n    := make_diagram\n         (fromempty : vertex empty_graph -> C)\n         (λ _ _, fromempty).\n\n  Definition make_unit_diagram {C : category}\n    (point : C)\n    : diagram unit_graph C.\n  Proof.\n    use make_diagram.\n    - exact(unit_rect _ point).\n    - exact(λ _ _, empty_rect _).\n  Defined.\n\n  Definition make_bool_diagram {C : category}\n    (a b : C)\n    : diagram bool_graph C.\n  Proof.\n    use make_diagram.\n    - exact(bool_rect _ a b).\n    - intros *; exact fromempty.\n  Defined.\n\n  Definition make_interval_diagram {C : category}\n    (x : C)\n    (y : C)\n    (f : x --> y)\n    : diagram interval_graph C.\n  Proof.\n    use make_diagram.\n    - exact(bool_rect _ x y).\n    - intros a b; destruct a, b; try (exact fromempty).\n      exact(λ _ , f).\n  Defined.\n\n  Definition make_span_diagram {C : category }\n    (a b c : C)\n    (f : C ⟦a, b⟧)\n    (g : C⟦a, c⟧)\n    : diagram span_graph C.\n  Proof.\n    use make_diagram.\n    - exact(three_rec a b c).\n    - use three_rec_dep; use three_rec_dep; try exact(empty_rect _).\n      + exact(unit_rect _ f).\n      + exact(unit_rect _ g).\n  Defined.\n\n  Definition make_discrete_diagram {J : category} {X : UU}\n    (objects : X -> J)\n    : diagram (discrete_graph X) J.\n  Proof.\n    use make_diagram.\n    - exact objects.\n    - exact(λ _ _, empty_rect _).\n  Defined.\n\n  (* Given any diagram we can obtain a new diagram, forgetting the edges in the original graph. *)\n  Definition make_discrete_diagram' {J : category}\n    {g : graph}\n    (d : diagram g J)\n    : diagram (discrete_graph (vertex g)) J.\n  Proof.\n    use make_diagram.\n    - exact(dob d).\n    - exact(λ _ _, empty_rect _).\n  Defined.\n\n  Definition make_parallell_diagram {C : category}\n    (X : UU)\n    (x y : C)\n    (f : ∏ (t : X), x --> y)\n    : diagram (parallell_graph X) C.\n  Proof.\n    use make_diagram.\n    - exact(two_rec x y).\n    - use two_rec_dep.\n      + use(two_rec_dep _ (empty_rect _) f).\n      + exact(λ _, empty_rect _).\n  Defined.\n\n  Definition make_pair_diagram {C : category}\n    (a b : C)\n    (f g : a --> b)\n    : diagram pair_graph C.\n  Proof.\n    apply(make_parallell_diagram (unit ⨿ unit) a b).\n    exact(sumofmaps (λ _, f) (λ _, g)).\n  Defined.\n\n  Definition make_multispan_diagram {J : category}\n    (X : UU)\n    (base : J)\n    (endpoint : ∏ (x : X), J)\n    (morphism : ∏ (x : X), J⟦ base, endpoint x ⟧)\n    : diagram (multispan_graph X) J.\n  Proof.\n    use make_diagram.\n    - exact(sumofmaps endpoint (λ _, base)).\n    - use coprod_rect.\n      + exact(λ _ _, empty_rect _).\n      + apply unit_rect.\n        use coprod_rect.\n        * exact(λ (a : X) (_ : unit), morphism a).\n        * exact(λ _, empty_rect _).\n  Defined.\nEnd diagrams.\n\nSection cocones.\n\n  (**\n   3. Constructors of cocones.\n   *)\n  Definition make_empty_cocone {J : category}\n    (d : diagram empty_graph J)\n    (j : J)\n    : cocone d j.\n  Proof.\n    use make_cocone.\n    - exact(empty_rect _).\n    - exact(λ _ _, empty_rect _).\n  Defined.\n\n  Definition make_discrete_cocone {J : category} {X : UU}\n    (d : diagram (discrete_graph X) J)\n    (z : J)\n    (f : ∏ (x : X), J⟦dob d x, z⟧)\n    : cocone d z.\n  Proof.\n    use make_cocone.\n    - exact f.\n    - exact(λ _ _, empty_rect _).\n  Defined.\n\n  Definition make_parallell_cocone {J : category} {X : UU}\n    (d : diagram (parallell_graph X) J)\n    (z : J)\n    (in₀ : dob d (stnpr 0) --> z)\n    (in₁ : dob d (stnpr 1) --> z)\n    (commutes : ∏ (x : X), dmor d (x : @edge (parallell_graph X) (stnpr 0) (stnpr 1)) · in₁ = in₀)\n    : cocone d z.\n  Proof.\n    use make_cocone.\n    - exact(two_rec_dep _ in₀ in₁).\n    - abstract(use(two_rec_dep _ (two_rec_dep _ (empty_rect _) commutes)); exact(λ _, empty_rect _)).\n  Defined.\n\n  Lemma parallell_cocone_commutes {J : category} {X : UU}\n    {d : diagram (parallell_graph X) J}\n    {j : J}\n    (cc : cocone d j)\n    (x : X)\n    : dmor d (parallell_edge x) · coconeIn cc parallell_end = coconeIn cc parallell_start.\n  Proof.\n    exact(coconeInCommutes cc parallell_start parallell_end (parallell_edge x)).\n  Qed.\n\n  Definition make_pair_cocone {J : category} {X : UU}\n    (d : diagram pair_graph J)\n    (j : J)\n    (src_in : J⟦dob d pair_src, j⟧)\n    (dst_in : J⟦dob d pair_dst, j⟧)\n    (com_left : dmor d pair_left · dst_in = src_in)\n    (com_right : dmor d pair_right · dst_in = src_in)\n    : cocone d j.\n  Proof.\n    use make_parallell_cocone.\n    - exact src_in.\n    - exact dst_in.\n    - abstract(use coprod_rect; apply unit_rect; assumption).\n  Defined.\n\n  Lemma pair_cocone_commutes {J : category}\n    {d : diagram pair_graph J}\n    {j : J}\n    (cc : cocone d j)\n    (e : edge pair_src pair_dst)\n    : dmor d e · coconeIn cc pair_dst = coconeIn cc pair_src.\n  Proof.\n    exact(coconeInCommutes cc pair_src pair_dst e).\n  Qed.\n\n  Definition make_multispan_cocone {J : category} {X : UU}\n    (d : diagram (multispan_graph X) J)\n    (apex : J)\n    (base_inject : J⟦ dob d multispan_base, apex ⟧)\n    (inject : ∏ (x : X), J⟦ dob d (multispan_vertex x), apex ⟧)\n    (commutes : ∏ (x : X), dmor d (multispan_edge x) · inject x = base_inject)\n    : cocone d apex.\n  Proof.\n    use make_cocone.\n    - apply coprod_rect.\n      + exact inject.\n      + apply unit_rect.\n        exact base_inject.\n    - abstract(use coprod_rect; [exact(λ _ _, empty_rect _) | use unit_rect ];\n               use coprod_rect; cbn; [exact(λ a, unit_rect _ (commutes a))\n                                       |exact(λ _, empty_rect _)]).\n  Defined.\n\n  Lemma multispan_cocone_commutes {J : category} {X : UU}\n    {d : diagram (multispan_graph X) J}\n    {apex : J}\n    (cc : cocone d apex)\n    (z : X)\n    : (dmor d (multispan_edge z)) · coconeIn cc (multispan_vertex z) =  coconeIn cc multispan_base.\n  Proof.\n    exact(coconeInCommutes cc multispan_base (multispan_vertex z) tt).\n  Qed.\n\nEnd cocones.\n\nSection finite.\n  Definition is_finite_graph (g : graph) : UU\n    := isfinite (vertex g)\n         × ∏ (a b : vertex g), isfinite (edge a b).\n\n  Definition finite_vertexset {g : graph} (gfinite : is_finite_graph g)\n    : isfinite (vertex g)\n    := pr1 gfinite.\n\n  Definition finite_edgeset {g : graph} (gfinite : is_finite_graph g)\n    : ∏ (a b : vertex g), isfinite (edge a b)\n    := pr2 gfinite.\n\n  (* Proofs that some of the above graphs are finite. *)\n  Lemma is_finite_graph_empty\n    : is_finite_graph empty_graph.\n  Proof.\n    split.\n    - exact isfiniteempty.\n    - exact(λ _ _, isfiniteempty).\n  Qed.\n\n  Lemma is_finite_graph_unit\n    : is_finite_graph unit_graph.\n  Proof.\n    split.\n    - exact isfiniteunit.\n    - exact(λ _ _, isfiniteempty).\n  Qed.\n\n  Lemma is_finite_graph_bool\n    : is_finite_graph bool_graph.\n  Proof.\n    split.\n    - exact isfinitebool.\n    - exact(λ _ _, isfiniteempty).\n  Qed.\n\n  Lemma is_finite_graph_pair\n    : is_finite_graph pair_graph.\n  Proof.\n    split.\n    - exact(isfinitestn 2).\n    - use two_rec_dep; use two_rec_dep; try exact isfiniteempty.\n      apply isfinitecoprod; apply isfiniteunit.\n  Qed.\n\n  Lemma is_finite_graph_interval\n    : is_finite_graph interval_graph.\n  Proof.\n    split.\n    - exact isfinitebool.\n    - use bool_rect; use bool_rect; try exact isfiniteempty.\n      exact isfiniteunit.\n  Qed.\nEnd finite.\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/limits/StandardDiagrams.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6611447252329191}}
{"text": "From Hammer Require Import Hammer.\n\n\n\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 Export Ensembles.\nRequire Export Relations_1.\nRequire Export Partial_Order.\n\nSection Bounds.\nVariable U : Type.\nVariable D : PO U.\n\nLet C := @Carrier_of U D.\n\nLet R := @Rel_of U D.\n\nInductive Upper_Bound (B:Ensemble U) (x:U) : Prop :=\nUpper_Bound_definition :\nIn U C x -> (forall y:U, In U B y -> R y x) -> Upper_Bound B x.\n\nInductive Lower_Bound (B:Ensemble U) (x:U) : Prop :=\nLower_Bound_definition :\nIn U C x -> (forall y:U, In U B y -> R x y) -> Lower_Bound B x.\n\nInductive Lub (B:Ensemble U) (x:U) : Prop :=\nLub_definition :\nUpper_Bound B x -> (forall y:U, Upper_Bound B y -> R x y) -> Lub B x.\n\nInductive Glb (B:Ensemble U) (x:U) : Prop :=\nGlb_definition :\nLower_Bound B x -> (forall y:U, Lower_Bound B y -> R y x) -> Glb B x.\n\nInductive Bottom (bot:U) : Prop :=\nBottom_definition :\nIn U C bot -> (forall y:U, In U C y -> R bot y) -> Bottom bot.\n\nInductive Totally_ordered (B:Ensemble U) : Prop :=\nTotally_ordered_definition :\n(Included U B C ->\nforall x y:U, Included U (Couple U x y) B -> R x y \\/ R y x) ->\nTotally_ordered B.\n\nDefinition Compatible : Relation U :=\nfun x y:U =>\nIn U C x ->\nIn U C y ->  exists z : _, In U C z /\\ Upper_Bound (Couple U x y) z.\n\nInductive Directed (X:Ensemble U) : Prop :=\nDefinition_of_Directed :\nIncluded U X C ->\nInhabited U X ->\n(forall x1 x2:U,\nIncluded U (Couple U x1 x2) X ->\nexists x3 : _, In U X x3 /\\ Upper_Bound (Couple U x1 x2) x3) ->\nDirected X.\n\nInductive Complete : Prop :=\nDefinition_of_Complete :\n(exists bot : _, Bottom bot) ->\n(forall X:Ensemble U, Directed X ->  exists bsup : _, Lub X bsup) ->\nComplete.\n\nInductive Conditionally_complete : Prop :=\nDefinition_of_Conditionally_complete :\n(forall X:Ensemble U,\nIncluded U X C ->\n(exists maj : _, Upper_Bound X maj) ->\nexists bsup : _, Lub X bsup) -> Conditionally_complete.\nEnd Bounds.\n\nHint Resolve Totally_ordered_definition Upper_Bound_definition\nLower_Bound_definition Lub_definition Glb_definition Bottom_definition\nDefinition_of_Complete Definition_of_Complete\nDefinition_of_Conditionally_complete.\n\nSection Specific_orders.\nVariable U : Type.\n\nRecord Cpo : Type := Definition_of_cpo\n{PO_of_cpo : PO U; Cpo_cond : Complete U PO_of_cpo}.\n\nRecord Chain : Type := Definition_of_chain\n{PO_of_chain : PO U;\nChain_cond : Totally_ordered U PO_of_chain (@Carrier_of _ PO_of_chain)}.\n\nEnd Specific_orders.\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/Sets/Cpo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.661129423471202}}
{"text": "Require Export FunctionalExtensionality.\nRequire Export PropExtensionality.\nRequire Export List.\nRequire Export Sorting.\nRequire Export PeanoNat.\nRequire Export ZArith.\n\nProposition In_remove (T: Type)\n    (eq_dec: forall (x y: T), {x = y} + {x <> y})\n    (x y: T) (xs: list T):\n  In x xs -> y <> x -> In x (remove eq_dec y xs).\ninduction xs; intros; inversion H;\nsimpl; destruct (eq_dec y a).\nexfalso. apply H0. rewrite <- H1. auto.\nrewrite H1. left. reflexivity.\napply IHxs; assumption.\nright. apply IHxs; assumption.\nQed.\n\nProposition In_remove_elim (T: Type)\n    (eq_dec: forall (x y: T), {x = y} + {x <> y})\n    (x y: T) (xs: list T):\n  y <> x -> In x (remove eq_dec y xs) -> In x xs.\ninduction xs; intros; simpl in H0.\ninversion H0.\nspecialize (IHxs H).\ndestruct (eq_dec y a).\nspecialize (IHxs H0). right. assumption.\ninversion H0. rewrite H1. left. auto.\nspecialize (IHxs H1). right. assumption.\nQed.\n\n(* ========= *)\n(* VARIABLES *)\n(* ========= *)\n\nDefinition V := nat.\nDefinition dummy: V := 0.\n\n(* ========================================= *)\n(* FRESHNESS OF VARIABLES AND ITS PROPERTIES *)\n(* ========================================= *)\n\nFixpoint maximum (xs: list V): V :=\n  match xs with\n  | nil => dummy\n  | (x::xs) => max x (maximum xs)\n  end.\nProposition maximum_prop (xs: list V):\n  forall x, In x xs -> x <= maximum xs.\nintros. induction xs. inversion H.\nsimpl. destruct H.\nrewrite H.\napply Nat.le_max_l.\ndestruct (le_gt_dec a (maximum xs)).\nrewrite max_r; try assumption.\napply IHxs; assumption.\nunfold gt in g.\napply Nat.lt_le_incl in g.\nrewrite max_l; try assumption.\neapply le_trans.\napply IHxs; assumption.\nassumption.\nQed.\nProposition maximum_In (xs: list V):\n  xs <> nil -> In (maximum xs) xs.\nintro. destruct xs.\nexfalso; apply H; reflexivity.\ninduction xs.\nsimpl. left. unfold dummy.\nrewrite Nat.max_0_r; reflexivity.\nsimpl.\nassert (In (maximum (v :: xs)) (v :: xs)).\n  apply IHxs. intro. inversion H0. clear IHxs.\ninversion H0. simpl in H1.\ndestruct (Nat.max_dec a (maximum xs)).\nrewrite e.\ndestruct (Nat.max_dec v a).\nleft. auto.\nright. left. auto.\nleft. rewrite e. auto.\ndestruct (Nat.max_dec a (maximum xs)).\nrewrite e.\ndestruct (Nat.max_dec v a).\nleft. auto.\nright. left. auto.\nrewrite e.\nright. right. apply H1.\nQed.\n\nProposition maximum_app (xs ys: list V):\n  maximum (xs ++ ys) = max (maximum xs) (maximum ys).\ninduction xs; simpl. reflexivity.\nrewrite IHxs.\napply Nat.max_assoc.\nQed.\n\nProposition maximum_subset (xs zs: list V):\n  (forall x : V, In x xs -> In x zs) -> maximum xs <= maximum zs.\nintro. destruct xs.\nsimpl. unfold dummy.\napply Nat.le_0_l.\npose proof (maximum_prop zs).\npose proof (maximum_In (v :: xs)).\napply H0. apply H. apply H1. intro. inversion H2.\nQed.\n\nDefinition fresh (xs: list V): V := S (maximum xs).\nProposition fresh_prop (xs: list V):\n  forall x, In x xs -> x < fresh xs.\nunfold fresh.\nintros. apply le_lt_n_Sm.\napply maximum_prop; assumption.\nQed.\nProposition fresh_notIn (xs: list V):\n  ~In (fresh xs) xs.\nintro.\npose proof (fresh_prop xs).\nspecialize H0 with (fresh xs).\nspecialize (H0 H).\neapply Nat.lt_irrefl. apply H0.\nQed.\n\nProposition fresh_app (xs ys: list V):\n  fresh (xs ++ ys) = max (fresh xs) (fresh ys).\nunfold fresh.\nrewrite maximum_app.\nsimpl. reflexivity.\nQed.\n\nProposition fresh_notInApp (xs ys: list V):\n  ~In (fresh (xs ++ ys)) xs.\nrewrite fresh_app.\ndestruct (Nat.max_dec (fresh xs) (fresh ys)).\nrewrite e. apply fresh_notIn.\nrewrite e.\npose proof (Max.le_max_l (fresh xs) (fresh ys)).\nrewrite e in H.\ndestruct (Nat.eq_dec (fresh xs) (fresh ys)).\nrewrite <- e0. apply fresh_notIn.\napply Nat.le_lteq in H. destruct H. clear n.\nintro.\napply fresh_prop in H0.\neapply Nat.lt_irrefl.\neapply Nat.lt_trans. apply H. apply H0.\nexfalso. apply n. assumption.\nQed.\n\nProposition fresh_notInGeneral (xs zs: list V):\n  (forall x, In x xs -> In x zs) -> ~In (fresh zs) xs.\nintro.\napply maximum_subset in H.\nunfold fresh.\nintro.\napply maximum_prop in H0.\neapply le_trans in H; [|apply H0].\neapply Nat.nle_succ_diag_l. apply H.\nQed.\n\n(* ========= *)\n(* THE STORE *)\n(* ========= *)\n\nDefinition store := V -> Z.\n\nDefinition store_update (s: store) (x: V) (v: Z): store :=\n  fun y => if Nat.eq_dec x y then v else s y.\n\nProposition store_update_lookup_same (s: store) (x: V) (v: Z):\n  store_update s x v x = v.\nunfold store_update.\ndestruct (Nat.eq_dec x x).\nreflexivity.\nexfalso. apply n. reflexivity.\nQed.\n\nProposition store_update_lookup_diff (s: store) (x x': V) (v: Z):\n  x <> x' -> store_update s x v x' = s x'.\nintros. unfold store_update.\ndestruct (Nat.eq_dec x x').\nexfalso. apply H; assumption.\nreflexivity.\nQed.\n\nProposition store_update_id (s: store) (x: V):\n  store_update s x (s x) = s.\napply functional_extensionality; intro.\nunfold store_update.\ndestruct (Nat.eq_dec x x0).\nrewrite e; reflexivity.\nreflexivity.\nQed.\n\nProposition store_update_collapse (s: store) (x: V) (v w: Z):\n  (store_update (store_update s x v) x w) =\n  (store_update s x w).\napply functional_extensionality; intro z.\nunfold store_update.\ndestruct (Nat.eq_dec x z); reflexivity.\nQed.\n\nProposition store_update_swap (s: store) (e: Z) (x y: V) (v: Z):\n  x <> y ->\n  (store_update (store_update s x e) y v) =\n  (store_update (store_update s y v) x e).\nintros G; apply functional_extensionality; intro z.\nunfold store_update.\ndestruct (Nat.eq_dec y z); destruct (Nat.eq_dec x z); try reflexivity.\nexfalso. apply G. rewrite e0; rewrite e1. reflexivity.\nQed.\n\nDefinition eq_restr (s t: store) (z: list V): Prop :=\n  forall (x: V), In x z -> s x = t x.\n\nProposition eq_restr_split (s t: store) (xs ys: list V):\n  eq_restr s t (xs ++ ys) -> eq_restr s t xs /\\ eq_restr s t ys.\nunfold eq_restr; intro; split; intros;\napply H; apply in_or_app; auto.\nQed.\n\nProposition eq_restr_cons (s t: store) (x: V) (xs: list V):\n  eq_restr s t (x :: xs) -> s x = t x /\\ eq_restr s t xs.\nintros; split.\napply H. left; auto.\nintro; intro.\napply H. right; auto.\nQed.\n\nProposition eq_restr_comm (s t: store) (xs: list V):\n  eq_restr s t xs -> eq_restr t s xs.\nunfold eq_restr; intros; symmetry; apply H; assumption.\nQed.\n\nProposition eq_restr_incl (s t: store) (xs ys: list V):\n  (forall x, In x ys -> In x xs) ->\n  eq_restr s t xs -> eq_restr s t ys.\nintros. intro; intro.\napply H in H1.\napply H0; auto.\nQed.\n\nProposition eq_restr_store_update (s t: store) (x: V) (v: Z) (xs: list V):\n  eq_restr s t xs -> eq_restr (store_update s x v) (store_update t x v) xs.\nintros. intro; intro.\nunfold store_update. destruct (Nat.eq_dec x x0). reflexivity.\napply H. auto.\nQed.\n\n(* ====================== *)\n(* EXPRESSIONS AND GUARDS *)\n(* ====================== *)\n\n(* Expressions and guards are shallow, but finitely based *)\nRecord expr: Set := mkexpr {\n  eval: store -> Z;\n  evar: list V;\n  econd: forall (s t: store), eq_restr s t evar -> eval s = eval t\n}.\nCoercion eval: expr >-> Funclass.\n\nProposition const_expr_cond (v: Z) (s t : store):\n  eq_restr s t nil -> v = v.\nintros. reflexivity.\nQed.\nDefinition const_expr (v: Z): expr :=\n  mkexpr (fun s => v) nil (const_expr_cond v).\nCoercion const_expr: Z >-> expr.\nProposition var_expr_cond (x: V) (s t : store):\n  eq_restr s t (x :: nil) -> s x = t x.\nintro. unfold eq_restr in H.\nspecialize H with x. apply H.\nleft. reflexivity.\nQed.\nDefinition var_expr (x: V): expr :=\n  mkexpr (fun s => s x) (x :: nil) (var_expr_cond x).\nCoercion var_expr: V >-> expr.\n\nProposition esub_cond (e: expr) (x: V) (e': expr) (s t : store):\n  eq_restr s t (remove Nat.eq_dec x (evar e) ++ evar e') ->\n  eval e (store_update s x (eval e' s)) =\n    eval e (store_update t x (eval e' t)).\nintro.\nassert (eval e' s = eval e' t).\napply (econd e').\nintro; intro; apply H.\napply in_or_app; right; assumption.\nrewrite <- H0.\nunfold store_update.\napply (econd e).\nunfold eq_restr.\nintro; intro.\ndestruct (Nat.eq_dec x x0).\nreflexivity.\napply H; apply in_or_app; left.\napply In_remove; assumption.\nQed.\nDefinition esub (e: expr) (x: V) (e': expr): expr :=\n  mkexpr (fun s => eval e (store_update s x (eval e' s)))\n    (remove Nat.eq_dec x (evar e) ++ evar e') (esub_cond e x e').\n\nProposition esub_simpl (e: expr) (x: V) (e': expr):\n  ~In x (evar e) -> forall s, eval (esub e x e') s = eval e s.\nintros. simpl.\napply econd. intro. intro.\nunfold store_update.\ndestruct (Nat.eq_dec x x0).\nexfalso. apply H. rewrite e0. assumption.\nreflexivity.\nQed.\n\nProposition esub_notInVar (e: expr) (x: V) (e': expr):\n  ~In x (evar e') -> ~ In x (evar (esub e x e')).\nintros; simpl; intro.\napply in_app_or in H0; destruct H0.\neapply remove_In; apply H0.\napply H; auto.\nQed.\n\nProposition expr_eq (e1 e2: expr):\n  (eval e1 = eval e2) -> (evar e1 = evar e2) -> e1 = e2.\nintros. destruct e1. destruct e2.\nsimpl in *. revert econd0. rewrite H. rewrite H0.\nintro. pose proof (proof_irrelevance _ econd0 econd1).\nrewrite H1. reflexivity.\nQed.\n\nRecord guard: Set := mkguard {\n  gval: store -> bool;\n  gvar: list V;\n  gcond: forall (s t: store), eq_restr s t gvar -> gval s = gval t\n}.\nCoercion gval: guard >-> Funclass.\n\nProposition const_guard_cond (v: bool) (s t : store):\n  eq_restr s t nil -> v = v.\nintros. reflexivity.\nQed.\nDefinition const_guard (v: bool): guard :=\n  mkguard (fun s => v) nil (const_guard_cond v).\nCoercion const_guard: bool >-> guard.\n\nProposition equals_cond (e1 e2: expr) (s t : store):\n  eq_restr s t (evar e1 ++ evar e2) ->\n  (if Z.eq_dec (eval e1 s) (eval e2 s) then true else false) =\n  (if Z.eq_dec (eval e1 t) (eval e2 t) then true else false).\nintro H.\napply eq_restr_split in H; destruct H.\npose proof (econd e1 s t); rewrite H1.\npose proof (econd e2 s t); rewrite H2.\nall: auto.\nQed.\nDefinition equals (e1 e2: expr): guard :=\n  mkguard (fun s => if Z.eq_dec (eval e1 s) (eval e2 s) then\n    true else false) (evar e1 ++ evar e2) (equals_cond e1 e2).\n\nProposition gsub_cond (g: guard) (x: V) (e: expr) (s t: store):\n  eq_restr s t (remove Nat.eq_dec x (gvar g) ++ evar e) ->\n  gval g (store_update s x (eval e s)) =\n  gval g (store_update t x (eval e t)).\nintro.\nassert (eval e s = eval e t).\napply (econd e).\nintro; intro; apply H.\napply in_or_app; right; assumption.\nrewrite <- H0.\nunfold store_update.\napply (gcond g).\nunfold eq_restr.\nintro; intro.\ndestruct (Nat.eq_dec x x0).\nreflexivity.\napply H; apply in_or_app; left.\napply In_remove; assumption.\nQed.\nDefinition gsub (g: guard) (x: V) (e: expr): guard :=\n  mkguard (fun s => gval g (store_update s x (eval e s)))\n    (remove Nat.eq_dec x (gvar g) ++ evar e) (gsub_cond g x e).\n\nProposition gsub_notInVar (g: guard) (x:V) (e: expr):\n  ~In x (evar e) -> ~In x (gvar (gsub g x e)).\nintros; simpl; intro.\napply in_app_or in H0; destruct H0.\neapply remove_In; apply H0.\napply H. assumption.\nQed.\n\nProposition guard_eq (g1 g2: guard):\n  (gval g1 = gval g2) -> (gvar g1 = gvar g2) -> g1 = g2.\nintros. destruct g1. destruct g2.\nsimpl in *. revert gcond0. rewrite H. rewrite H0.\nintro. pose proof (proof_irrelevance _ gcond0 gcond1).\nrewrite H1. reflexivity.\nQed.\n\n(* ==================== *)\n(* CLASSICAL ASSERTIONS *)\n(* ==================== *)\n\nDefinition heap := Z -> option Z.\n\nDefinition heap_update (h: heap) (k v: Z): heap :=\n  fun n => if Z.eq_dec k n then Some v else h n.\n\nDefinition heap_clear (h: heap) (k: Z): heap :=\n  fun n => if Z.eq_dec k n then None else h n.\n\nDefinition dom (h: heap) (k: Z): Prop := h k <> None.\n\nDefinition Partition (h h1 h2: heap): Prop :=\n  (forall k, (dom h k -> dom h1 k \\/ dom h2 k)) /\\\n  (forall k, ~(dom h1 k /\\ dom h2 k)) /\\\n  (forall k, dom h1 k -> h k = h1 k) /\\\n  (forall k, dom h2 k -> h k = h2 k).\n\n(* Assertions are shallow, but finitely based *)\nRecord cassert: Type := mkcassert {\n  cval: heap * store -> Prop;\n  cvar: list V;\n  ccond: forall (h: heap) (s t: store), eq_restr s t cvar -> cval (h, s) <-> cval (h, t);\n  cstable: forall (h: heap) (s: store), ~~cval (h, s) -> cval (h, s)\n}.\nCoercion cval: cassert >-> Funclass.\n\nProposition ctest_cond (g: guard):\n  forall (h : heap) (s t : store),\n   eq_restr s t (gvar g) -> g s = true <-> g t = true.\nintros.\nrewrite gcond with (t := t).\napply iff_refl.\nassumption.\nQed.\nProposition ctest_stable (g: guard):\n  forall (h : heap) (s : store),\n   ~ ~ g s = true -> g s = true.\nintros. destruct (g s); auto.\nQed.\nDefinition ctest (g: guard): cassert :=\n  mkcassert (fun '(h, s) => gval g s = true) (gvar g) (ctest_cond g) (ctest_stable g).\n\nProposition chasval_cond (e1 e2: expr):\n  forall (h : heap) (s t : store),\n   eq_restr s t (evar e1 ++ evar e2) ->\n   h (e1 s) = Some (e2 s) <->\n   h (e1 t) = Some (e2 t).\nintros.\napply eq_restr_split in H; destruct H.\nsplit; intro.\n- rewrite <- econd with (s := s); auto.\n  rewrite <- (econd e2) with (s := s); auto.\n- rewrite econd with (t := t); auto.\n  rewrite (econd e2) with (t := t); auto.\nQed.\nProposition chasval_stable (e1 e2: expr):\n  forall (h : heap) (s : store),\n   ~ ~ (h (e1 s) = Some (e2 s)) ->\n   h (e1 s) = Some (e2 s).\nintros.\ndestruct (h (e1 s)).\nremember (e2 s).\ndestruct (Z.eq_dec z z0).\nrewrite e; auto.\nexfalso; apply H. intro. inversion H0.\napply n; auto.\nexfalso.\napply H. intro. inversion H0.\nQed.\nDefinition chasval (e1 e2: expr): cassert :=\n  mkcassert (fun '(h, s) => h (e1 s) = Some (e2 s)) (evar e1 ++ evar e2)\n    (chasval_cond e1 e2) (chasval_stable e1 e2).\n\nProposition cland_cond (p q: cassert):\n  forall (h : heap) (s t : store),\n   eq_restr s t (cvar p ++ cvar q) ->\n   p (h, s) /\\ q (h, s) <->\n   p (h, t) /\\ q (h, t).\nintros.\napply eq_restr_split in H; destruct H.\nsplit; intro; destruct H1.\nrewrite ccond with (t := t) in H1; auto.\nrewrite ccond with (t := t) in H2; auto.\nrewrite <- ccond with (s := s) in H1; auto.\nrewrite <- ccond with (s := s) in H2; auto.\nQed.\nProposition cland_stable (p q: cassert):\n  forall (h : heap) (s : store),\n   ~ ~ (p (h, s) /\\ q (h, s)) ->\n   p (h, s) /\\ q (h, s).\nintros; split; apply cstable; intro;\napply H; intro; destruct H1; apply H0; auto.\nQed.\nDefinition cland (p q: cassert): cassert :=\n  mkcassert (fun '(h, s) => p (h, s) /\\ q (h, s)) (cvar p ++ cvar q)\n    (cland_cond p q) (cland_stable p q).\n\nProposition clor_cond (p q: cassert):\n  forall (h : heap) (s t : store),\n   eq_restr s t (cvar p ++ cvar q) ->\n   ~(~p (h, s) /\\ ~q (h, s)) <->\n   ~(~p (h, t) /\\ ~q (h, t)).\nintros.\napply eq_restr_split in H; destruct H.\nsplit; intro; intro; destruct H2;\napply H1; split; intro.\nrewrite ccond with (t := t) in H4; auto.\nrewrite ccond with (t := t) in H4; auto.\nrewrite <- ccond with (s := s) in H4; auto.\nrewrite <- ccond with (s := s) in H4; auto.\nQed.\nProposition clor_stable (p q: cassert):\n  forall (h : heap) (s : store),\n   ~ ~ (~(~p (h, s) /\\ ~q (h, s))) ->\n   ~(~p (h, s) /\\ ~q (h, s)).\nintros; intro; destruct H0.\napply H; intro; apply H2; split; auto.\nQed.\nDefinition clor (p q: cassert): cassert :=\n  mkcassert (fun '(h, s) => ~(~p (h, s) /\\ ~q (h, s))) (cvar p ++ cvar q)\n    (clor_cond p q) (clor_stable p q).\n\nProposition climp_cond (p q: cassert):\n  forall (h : heap) (s t : store),\n   eq_restr s t (cvar p ++ cvar q) ->\n   (p (h, s) -> q (h, s)) <->\n   (p (h, t) -> q (h, t)).\nintros.\napply eq_restr_split in H; destruct H.\nsplit; intros.\napply ccond with (s := s); auto.\napply H1.\napply ccond with (t := t); auto.\napply ccond with (t := t); auto.\napply H1.\napply ccond with (s := s); auto.\nQed.\nProposition climp_stable (p q: cassert):\n  forall (h : heap) (s : store),\n   ~ ~ (p (h, s) -> q (h, s)) ->\n   (p (h, s) -> q (h, s)).\nintros.\napply cstable; intro.\napply H; intro.\napply H1; apply H2; auto.\nQed.\nDefinition climp (p q: cassert): cassert :=\n  mkcassert (fun '(h, s) => p (h, s) -> q (h, s)) (cvar p ++ cvar q)\n    (climp_cond p q) (climp_stable p q).\n\nProposition clexists_cond (x: V) (p: cassert):\n  forall (h : heap) (s t : store),\n   eq_restr s t (remove Nat.eq_dec x (cvar p)) ->\n   ~ (forall v : Z, ~ p (h, store_update s x v)) <->\n   ~ (forall v : Z, ~ p (h, store_update t x v)).\nintros; split; intro; intro; apply H0; intro; intro.\n- apply H1 with (v := v).\n  apply ccond with (s := store_update s x v); auto.\n  intro; intro; unfold store_update.\n  destruct (Nat.eq_dec x x0); auto.\n  apply H.\n  apply In_remove; auto.\n- apply H1 with (v := v).\n  apply ccond with (t := store_update t x v); auto.\n  intro; intro; unfold store_update.\n  destruct (Nat.eq_dec x x0); auto.\n  apply H.\n  apply In_remove; auto.\nQed.\nProposition clexists_stable (x: V) (p: cassert):\n  forall (h : heap) (s : store),\n   ~ ~ ~ (forall v : Z, ~ p (h, store_update s x v)) ->\n   ~ (forall v : Z, ~ p (h, store_update s x v)).\nintros; intro.\napply H; intro; apply H1; intros; intro.\napply H0 with (v := v).\nauto.\nQed.\nDefinition clexists (x: V) (p: cassert): cassert :=\n  mkcassert (fun '(h, s) => ~forall v, ~p (h, store_update s x v)) (remove Nat.eq_dec x (cvar p))\n  (clexists_cond x p) (clexists_stable x p).\n\nProposition clforall_cond (x: V) (p: cassert):\n  forall (h : heap) (s t : store),\n   eq_restr s t (remove Nat.eq_dec x (cvar p)) ->\n   (forall v : Z, p (h, store_update s x v)) <->\n   (forall v : Z, p (h, store_update t x v)).\nintros; split; intro; intro.\n- apply ccond with (s := store_update s x v).\n  intro; intro; unfold store_update.\n  destruct (Nat.eq_dec x x0); auto.\n  apply H.\n  apply In_remove; auto.\n  apply H0.\n- apply ccond with (t := store_update t x v).\n  intro; intro; unfold store_update.\n  destruct (Nat.eq_dec x x0); auto.\n  apply H.\n  apply In_remove; auto.\n  apply H0.\nQed.\nProposition clforall_stable (x: V) (p: cassert):\n  forall (h : heap) (s : store),\n   ~ ~ (forall v : Z, p (h, store_update s x v)) ->\n   (forall v : Z, p (h, store_update s x v)).\nintros. apply cstable; intro. apply H; intro.\napply H0.\napply H1.\nQed.\nDefinition clforall (x: V) (p: cassert): cassert :=\n  mkcassert (fun '(h, s) => forall v, p (h, store_update s x v)) (remove Nat.eq_dec x (cvar p))\n  (clforall_cond x p) (clforall_stable x p).\n\nProposition csand_cond (p q: cassert):\n  forall (h : heap) (s t : store),\n   eq_restr s t (cvar p ++ cvar q) ->\n   ~ (forall h1 h2 : heap, ~ (Partition h h1 h2 /\\ p (h1, s) /\\ q (h2, s))) <->\n   ~ (forall h1 h2 : heap, ~ (Partition h h1 h2 /\\ p (h1, t) /\\ q (h2, t))).\nintros; split; intro; intro; apply H0; intros; intro.\n- destruct H2.\n  eapply H1. split. apply H2.\n  destruct H3.\n  apply eq_restr_split in H; destruct H.\n  split.\n  apply ccond with (s := s); auto.\n  apply ccond with (s := s); auto.\n- destruct H2.\n  eapply H1. split. apply H2.\n  destruct H3.\n  apply eq_restr_split in H; destruct H.\n  split.\n  apply ccond with (t := t); auto.\n  apply ccond with (t := t); auto.\nQed.\nProposition csand_stable (p q: cassert):\n  forall (h : heap) (s : store),\n   ~ ~ ~ (forall h1 h2 : heap, ~ (Partition h h1 h2 /\\ p (h1, s) /\\ q (h2, s))) ->\n   ~ (forall h1 h2 : heap, ~ (Partition h h1 h2 /\\ p (h1, s) /\\ q (h2, s))).\nintros; intro. apply H; intro. auto.\nQed.\nDefinition csand (p q: cassert): cassert :=\n  mkcassert (fun '(h, s) => ~forall h1 h2, ~(Partition h h1 h2 /\\ p (h1, s) /\\ q (h2, s)))\n    (cvar p ++ cvar q) (csand_cond p q) (csand_stable p q).\n\nProposition csimp_cond (p q: cassert):\n  forall (h : heap) (s t : store),\n   eq_restr s t (cvar p ++ cvar q) ->\n   (forall h'' h' : heap, Partition h'' h h' -> p (h', s) -> q (h'', s)) <->\n   forall h'' h' : heap, Partition h'' h h' -> p (h', t) -> q (h'', t).\nintros.\napply eq_restr_split in H; destruct H.\nsplit; intro; intros.\napply ccond with (s := s); auto.\napply H1 with (h' := h'); auto.\napply ccond with (t := t); auto.\napply ccond with (t := t); auto.\napply H1 with (h' := h'); auto.\napply ccond with (s := s); auto.\nQed.\nProposition csimp_stable (p q: cassert):\n  forall (h : heap) (s : store),\n   ~ ~ (forall h'' h' : heap, Partition h'' h h' -> p (h', s) -> q (h'', s)) ->\n   forall h'' h' : heap, Partition h'' h h' -> p (h', s) -> q (h'', s).\nintros. apply cstable; intro. apply H; intro. apply H2.\napply H3 with (h' := h'); auto.\nQed.\nDefinition csimp (p q: cassert): cassert :=\n  mkcassert (fun '(h, s) => forall h'' h', Partition h'' h h' -> p (h', s) -> q (h'', s))\n    (cvar p ++ cvar q) (csimp_cond p q) (csimp_stable p q).\n\n(* Abbreviations *)\n\nDefinition cltrue: cassert := (ctest true).\nDefinition clfalse: cassert := (ctest false).\nDefinition clnot (p: cassert): cassert := (climp p clfalse).\nDefinition clequiv (p q: cassert): cassert := (cland (climp p q) (climp q p)).\nDefinition chasvaldash (e: expr): cassert :=\n  let y := fresh (evar e) in clexists y (chasval e y).\nDefinition cemp: cassert := (clforall dummy (clnot (chasvaldash dummy))).\nDefinition cpointsto (e e': expr): cassert :=\n  let x := fresh (evar e) in cland (chasval e e') (clforall x (climp (chasvaldash x) (ctest (equals x e)))).\nDefinition cpointstodash (e: expr): cassert :=\n  let y := fresh (evar e) in clexists y (cpointsto e y).\nDefinition chasval_alt (e e': expr): cassert :=\n  csand (cpointsto e e') (ctest true).\nDefinition chasvaldash_alt (e: expr): cassert :=\n  csand (cpointstodash e) (ctest true).\n\n(* Operations on assertions *)\n\nProposition csub_cond (p: cassert) (x: V) (e: expr):\n  forall (h : heap) (s t : store),\n   eq_restr s t (remove Nat.eq_dec x (cvar p) ++ evar e) ->\n   p (h, store_update s x (e s)) <->\n   p (h, store_update t x (e t)).\nintros.\napply eq_restr_split in H; destruct H.\nsplit; intro.\n- pose proof (econd e s t H0).\n  rewrite <- H2.\n  apply ccond with (s := store_update s x (e s)); auto.\n  intro; intro; unfold store_update.\n  destruct (Nat.eq_dec x x0); auto.\n  apply H.\n  apply In_remove; auto.\n- pose proof (econd e s t H0).\n  rewrite H2.\n  apply ccond with (t := store_update t x (e t)); auto.\n  intro; intro; unfold store_update.\n  destruct (Nat.eq_dec x x0); auto.\n  apply H.\n  apply In_remove; auto.\nQed.\nProposition csub_stable (p: cassert) (x: V) (e: expr):\n  forall (h : heap) (s : store),\n   ~ ~ p (h, store_update s x (e s)) ->\n   p (h, store_update s x (e s)).\nintros. apply cstable. auto.\nQed.\nDefinition csub (p: cassert) (x: V) (e: expr): cassert :=\n  mkcassert (fun '(h, s) => p (h, store_update s x (eval e s)))\n    (remove Nat.eq_dec x (cvar p) ++ evar e) (csub_cond p x e) (csub_stable p x e).\n\nProposition csub_heap_update_cond (p: cassert) (x: V) (e: expr):\n  forall (h : heap) (s t : store),\n   eq_restr s t (x :: cvar p ++ evar e) ->\n   p (heap_update h (s x) (e s), s) <->\n   p (heap_update h (t x) (e t), t).\nintros.\napply eq_restr_cons in H; destruct H.\napply eq_restr_split in H0; destruct H0.\nrewrite H.\npose proof (econd e s t H1).\nrewrite H2.\napply ccond.\nauto.\nQed.\nProposition csub_heap_update_stable (p: cassert) (x: V) (e: expr):\n  forall (h : heap) (s : store),\n   ~ ~ p (heap_update h (s x) (e s), s) ->\n   p (heap_update h (s x) (e s), s).\nintros. apply cstable. auto.\nQed.\nDefinition csub_heap_update (p: cassert) (x: V) (e: expr): cassert :=\n  mkcassert (fun '(h, s) => p (heap_update h (s x) (e s), s))\n    (x :: cvar p ++ evar e) (csub_heap_update_cond p x e) (csub_heap_update_stable p x e).\n\nProposition csub_heap_clear_cond (p: cassert) (x: V):\n  forall (h : heap) (s t : store),\n   eq_restr s t (x :: cvar p) ->\n   p (heap_clear h (s x), s) <->\n   p (heap_clear h (t x), t).\nintros.\napply eq_restr_cons in H; destruct H.\nrewrite H.\napply ccond.\nauto.\nQed.\nProposition csub_heap_clear_stable (p: cassert) (x: V):\n  forall (h : heap) (s : store),\n   ~ ~ p (heap_clear h (s x), s) ->\n   p (heap_clear h (s x), s).\nintros. apply cstable. assumption.\nQed.\nDefinition csub_heap_clear (p: cassert) (x: V): cassert :=\n  mkcassert (fun '(h, s) => p (heap_clear h (s x), s))\n    (x :: cvar p) (csub_heap_clear_cond p x) (csub_heap_clear_stable p x).\n\n(* Properties of assertions *)\nDefinition valid (p: cassert): Prop :=\n  forall (h: heap) (s: store), p (h, s).\n\n(* ===================================== *)\n(* BASIC INSTRUCTIONS AND WHILE PROGRAMS *)\n(* ===================================== *)\n\nInductive assignment :=\n| basic: V -> expr -> assignment\n| lookup: V -> expr -> assignment\n| mutation: V -> expr -> assignment\n| new: V -> expr -> assignment\n| dispose: V -> assignment.\n\nDefinition avar (a: assignment): list V :=\n  match a with\n  | basic x e => x :: evar e\n  | lookup x e => x :: evar e\n  | mutation x e => x :: evar e\n  | new x e => x :: evar e\n  | dispose x => x :: nil\n  end.\n\nInductive program :=\n| assign: assignment -> program\n| diverge: program\n| skip: program\n| comp: program -> program -> program\n| ite: guard -> program -> program -> program\n| while: guard -> program -> program.\nCoercion assign: assignment >-> program.\n\nFixpoint pvar (p: program): list V :=\n  match p with\n  | assign a => avar a\n  | diverge => nil\n  | skip => nil\n  | comp S1 S2 => pvar S1 ++ pvar S2\n  | ite g S1 S2 => gvar g ++ pvar S1 ++ pvar S2\n  | while g S1 => gvar g ++ pvar S1\n  end.\n\n(* ================================================ *)\n(* SEMANTICS OF PROGRAMS, SEE FIGURE 1 IN THE PAPER *)\n(* ================================================ *)\n\nInductive bigstep: program -> heap * store -> option (heap * store) -> Prop :=\n| step_basic (x: V) (e: expr) (h: heap) (s: store):\n    bigstep (basic x e) (h, s) (Some (h, store_update s x (eval e s)))\n| step_lookup (x: V) (e: expr) (h: heap) (s: store) (v: Z):\n    h (eval e s) = Some v ->\n    bigstep (lookup x e) (h, s) (Some (h, store_update s x v))\n| step_lookup_fail (x: V) (e: expr) (h: heap) (s: store):\n    h (eval e s) = None ->\n    bigstep (lookup x e) (h, s) None\n| step_mutation (x: V) (e: expr) (h: heap) (s: store):\n    dom h (s x) ->\n    bigstep (mutation x e) (h, s) (Some (heap_update h (s x) (eval e s), s))\n| step_mutation_fail (x: V) (e: expr) (h: heap) (s: store):\n    ~dom h (s x) ->\n    bigstep (mutation x e) (h, s) None\n| step_new (x: V) (e: expr) (h: heap) (s: store) (n: Z):\n    ~(dom h n) ->\n    bigstep (new x e) (h, s)\n      (Some (heap_update h n (eval e s), store_update s x n))\n| step_dispose (x: V) (h: heap) (s: store):\n    dom h (s x) ->\n    bigstep (dispose x) (h, s) (Some (heap_clear h (s x), s))\n| step_dispose_fail (x: V) (h: heap) (s: store):\n    ~dom h (s x) ->\n    bigstep (dispose x) (h, s) None\n| step_skip (h: heap) (s: store):\n    bigstep skip (h, s) (Some (h, s))\n| step_comp (S1 S2: program) (h h' h'': heap) (s s' s'': store):\n    bigstep S1 (h, s) (Some (h', s')) ->\n    bigstep S2 (h', s') (Some (h'', s'')) ->\n    bigstep (comp S1 S2) (h, s) (Some (h'', s''))\n| step_comp_fail1 (S1 S2: program) (h: heap) (s: store):\n    bigstep S1 (h, s) None ->\n    bigstep (comp S1 S2) (h, s) None\n| step_comp_fail2 (S1 S2: program) (h h': heap) (s s': store):\n    bigstep S1 (h, s) (Some (h', s')) ->\n    bigstep S2 (h', s') None ->\n    bigstep (comp S1 S2) (h, s) None\n| step_ite_true (g: guard) (S1 S2: program) (h: heap) (s: store) o:\n    g s = true ->\n    bigstep S1 (h, s) o ->\n    bigstep (ite g S1 S2) (h, s) o\n| step_ite_false (g: guard) (S1 S2: program) (h: heap) (s: store) o:\n    g s = false ->\n    bigstep S2 (h, s) o ->\n    bigstep (ite g S1 S2) (h, s) o\n| step_while_true (g: guard) (S1: program) (h h': heap) (s s': store) o:\n    g s = true ->\n    bigstep S1 (h, s) (Some (h', s')) ->\n    bigstep (while g S1) (h', s') o ->\n    bigstep (while g S1) (h, s) o\n| step_while_false (g: guard) (S1: program) (h: heap) (s: store):\n    g s = false ->\n    bigstep (while g S1) (h, s) (Some (h, s))\n| step_while_fail (g: guard) (S1: program) (h: heap) (s: store):\n    g s = true ->\n    bigstep S1 (h, s) None ->\n    bigstep (while g S1) (h, s) None.\n\nProposition diverge_empty (h: heap) (s: store):\n  forall o, ~bigstep diverge (h, s) o.\nintros; intro; inversion H.\nQed.\n\nProposition while_unfold (g: guard) (S1: program):\n  forall h s o,\n    bigstep (while g S1) (h, s) o <->\n    bigstep (ite g (comp S1 (while g S1)) skip) (h, s) o.\nintros. split; intros.\n- inversion H.\n  apply step_ite_true; auto.\n  destruct o. destruct p.\n  eapply step_comp. apply H6. apply H7.\n  eapply step_comp_fail2. apply H6. apply H7.\n  apply step_ite_false; auto.\n  apply step_skip.\n  apply step_ite_true; auto.\n  apply step_comp_fail1; auto.\n- inversion H.\n  inversion H7.\n  eapply step_while_true; auto.\n  apply H13. apply H14.\n  eapply step_while_fail; auto.\n  eapply step_while_true; auto.\n  apply H13. apply H14.\n  inversion H7.\n  apply step_while_false; auto.\nQed.\n\nFixpoint approx (n: nat) (g: guard) (S1: program): program :=\n  match n with\n  | O => diverge\n  | S m => ite g (comp S1 (approx m g S1)) skip\n  end.\n\nProposition while_approx (g: guard) (S1: program):\n  forall h s o,\n    bigstep (while g S1) (h, s) o <->\n    exists n, bigstep (approx n g S1) (h, s) o.\nintros; split; intro.\n- remember (while g S1).\n  induction H; try inversion Heqp.\n  + apply IHbigstep2 in Heqp.\n    destruct Heqp.\n    exists (S x).\n    simpl.\n    apply step_ite_true.\n    rewrite <- H3. apply H.\n    destruct o; [destruct p|].\n    eapply step_comp.\n    rewrite <- H4. apply H0. apply H2.\n    eapply step_comp_fail2.\n    rewrite <- H4. apply H0. apply H2.\n  + exists 1.\n    simpl.\n    apply step_ite_false.\n    rewrite <- H1. apply H.\n    apply step_skip.\n  + exists 1.\n    simpl.\n    apply step_ite_true.\n    rewrite <- H2. apply H.\n    apply step_comp_fail1.\n    rewrite <- H3. apply H0.\n- destruct H.\n  generalize dependent h.\n  generalize dependent s.\n  generalize dependent o.\n  induction x; intros.\n  + simpl in H.\n    exfalso.\n    pose proof (diverge_empty h s).\n    specialize H0 with o.\n    apply H0; auto.\n  + simpl in H.\n    inversion H.\n    inversion H7.\n    apply IHx in H14.\n    eapply step_while_true.\n    apply H6.\n    apply H13.\n    apply H14.\n    apply step_while_fail.\n    apply H6.\n    apply H13.\n    apply IHx in H14.\n    eapply step_while_true.\n    apply H6.\n    apply H13.\n    apply H14.\n    inversion H7.\n    eapply step_while_false.\n    apply H6.\nQed.\n\nDefinition omega: program := while true skip.\n\nProposition omega_diverge_equiv:\n  forall h s o,\n    bigstep omega (h, s) o <->\n    bigstep diverge (h, s) o.\nintros. unfold omega.\nrewrite while_approx.\nsplit; intro.\ndestruct H.\ngeneralize dependent s.\ngeneralize dependent h.\ninduction x; intros; simpl in H.\nauto.\ninversion H.\ninversion H7.\nrewrite H11.\napply IHx.\ninversion H13.\nrewrite <- H11. assumption.\ninversion H13.\nrewrite H11.\napply IHx.\nrewrite <- H11.\ninversion H13. assumption.\ninversion H6.\ninversion H.\nQed.\n\n(* ================ *)\n(* PROGRAM MODALITY *)\n(* ================ *)\n\nProposition bigstep_cond (S1: program) (p: heap * store) (o: option (heap * store)):\n  bigstep S1 p o ->\n  forall xs, (forall x, In x (pvar S1) -> In x xs) ->\n  forall h s, (h, s) = p ->\n  forall t, eq_restr s t xs ->\n  (forall h' s', Some (h', s') = o ->\n    exists t', eq_restr s' t' xs /\\ bigstep S1 (h, t) (Some (h', t'))) /\\\n  (None = o ->\n    bigstep S1 (h, t) None).\nintro.\ninduction H; intros xs G h0 s0 G1 t G3; inversion G1; clear G1;\n(split; [intros h'0 s'0 G2; inversion G2; clear G2 | intro G2; inversion G2; clear G2 ]).\n- rewrite H1 in G3.\n  exists (store_update t x (e t)). split.\n  + intro; intro.\n    unfold store_update.\n    destruct (Nat.eq_dec x x0).\n    apply econd.\n    eapply eq_restr_incl; [|apply G3].\n    intros. apply G. simpl; auto.\n    apply G3; auto.\n  + apply step_basic.\n- exists (store_update t x v). split.\n  + intro; intro.\n    rewrite <- H2.\n    unfold store_update.\n    destruct (Nat.eq_dec x x0); auto.\n  + apply step_lookup.\n    pose proof (econd e s t).\n    rewrite <- H0; auto.\n    rewrite <- H2.\n    eapply eq_restr_incl; [|apply G3].\n    intros. apply G. simpl; auto.\n- apply step_lookup_fail.\n  erewrite <- econd. apply H.\n  rewrite <- H2.\n  eapply eq_restr_incl; [|apply G3].\n  intros. apply G. simpl. auto.\n- exists t. split.\n  + rewrite <- H2. auto.\n  + assert (s x = t x).\n    { rewrite H2 in G3.\n      apply G3. apply G. simpl. auto. }\n    assert (e s = e t).\n    { apply econd.\n      eapply eq_restr_incl; [ | rewrite H2 in G3; apply G3].\n      intros. apply G. simpl. auto. }\n    rewrite H0.\n    rewrite H5.\n    apply step_mutation.\n    rewrite <- H0. assumption.\n- apply step_mutation_fail.\n  assert (s x = t x).\n  rewrite H2 in G3. apply G3.\n  apply G. simpl. auto.\n  rewrite <- H0. auto.\n- exists (store_update t x n).\n  split. rewrite H2 in G3.\n  apply eq_restr_store_update; assumption.\n  assert (e s = e t).\n  { apply econd.\n    eapply eq_restr_incl; [ | rewrite H2 in G3; apply G3].\n    intros. apply G. simpl. auto. }\n  rewrite H0.\n  apply step_new. assumption.\n- exists t. split.\n  rewrite H2 in G3. auto.\n  assert (s x = t x).\n  { rewrite H2 in G3.\n    apply G3. apply G. simpl. auto. }\n  rewrite H0.\n  apply step_dispose.\n  rewrite <- H0. assumption.\n- apply step_dispose_fail.\n  assert (s x = t x).\n  rewrite H2 in G3. apply G3.\n  apply G. simpl. auto.\n  rewrite <- H0. auto.\n- exists t. split.\n  rewrite <- H1. auto.\n  apply step_skip.\n- destruct IHbigstep1 with (xs := xs) (h := h) (s := s) (t := t); auto.\n  intros. apply G. simpl. apply in_or_app; auto. rewrite <- H3. auto.\n  edestruct H1. reflexivity. destruct H7.\n  destruct IHbigstep2 with (xs := xs) (h := h') (s := s') (t := x); auto.\n  intros. apply G. simpl. apply in_or_app; auto.\n  edestruct H9. reflexivity. destruct H11.\n  exists x0. split; auto.\n  eapply step_comp.\n  apply H8.\n  apply H12.\n- apply step_comp_fail1.\n  destruct IHbigstep with (xs := xs) (h := h) (s := s) (t := t); auto.\n  intros. apply G. simpl. apply in_or_app; auto. rewrite <- H2. auto.\n- destruct IHbigstep1 with (xs := xs) (h := h) (s := s) (t := t); auto.\n  intros. apply G. simpl. apply in_or_app; auto. rewrite <- H3. auto.\n  edestruct H1. reflexivity. destruct H5.\n  eapply step_comp_fail2.\n  apply H6.\n  destruct IHbigstep2 with (xs := xs) (h := h') (s := s') (t := x); auto.\n  intros. apply G. simpl. apply in_or_app; auto.\n- destruct o. destruct p.\n  destruct IHbigstep with (xs := xs) (h := h) (s := s) (t := t); auto.\n  intros. apply G. simpl. apply in_or_app. right. apply in_or_app; auto.\n  rewrite <- H3; auto.\n  destruct H4 with (h' := h1) (s' := s1); auto. destruct H6.\n  inversion H1.\n  exists x. split; auto.\n  apply step_ite_true; auto.\n  rewrite H3 in G3.\n  rewrite <- gcond with (s := s); auto.\n  eapply eq_restr_incl; [|apply G3]. intros.\n  apply G. simpl. apply in_or_app; auto.\n  inversion H1.\n- destruct o. inversion H1.\n  destruct IHbigstep with (xs := xs) (h := h) (s := s) (t := t); auto.\n  intros. apply G. simpl. apply in_or_app. right. apply in_or_app; auto.\n  rewrite <- H3; auto.\n  rewrite H3 in G3.\n  apply step_ite_true.\n  rewrite <- gcond with (s := s); auto.\n  eapply eq_restr_incl; [|apply G3]. intros.\n  apply G. simpl. apply in_or_app; auto.\n  apply H5. auto.\n- destruct o. destruct p.\n  destruct IHbigstep with (xs := xs) (h := h) (s := s) (t := t); auto.\n  intros. apply G. simpl. apply in_or_app. right. apply in_or_app; auto.\n  rewrite <- H3; auto.\n  destruct H4 with (h' := h1) (s' := s1); auto. destruct H6.\n  inversion H1.\n  exists x. split; auto.\n  apply step_ite_false; auto.\n  rewrite H3 in G3.\n  rewrite <- gcond with (s := s); auto.\n  eapply eq_restr_incl; [|apply G3]. intros.\n  apply G. simpl. apply in_or_app; auto.\n  inversion H1.\n- destruct o. inversion H1.\n  destruct IHbigstep with (xs := xs) (h := h) (s := s) (t := t); auto.\n  intros. apply G. simpl. apply in_or_app. right. apply in_or_app; auto.\n  rewrite <- H3; auto.\n  rewrite H3 in G3.\n  apply step_ite_false.\n  rewrite <- gcond with (s := s); auto.\n  eapply eq_restr_incl; [|apply G3]. intros.\n  apply G. simpl. apply in_or_app; auto.\n  apply H5. auto.\n- destruct o; inversion H2. destruct p; inversion H6.\n  destruct IHbigstep1 with (xs := xs) (h := h) (s := s) (t := t); auto.\n  intros. apply G. simpl. apply in_or_app; auto. rewrite H4 in G3; auto.\n  destruct H5 with (h' := h') (s' := s'); auto. destruct H10.\n  destruct IHbigstep2 with (xs := xs) (h := h') (s := s') (t := x); auto.\n  destruct H12 with (h' := h1) (s' := s1); auto. destruct H14.\n  exists x0.\n  split; auto.\n  eapply step_while_true.\n  rewrite H4 in G3.\n  rewrite <- gcond with (s := s); auto.\n  intro; intro. apply G3. apply G. simpl. apply in_or_app; auto.\n  apply H11.\n  auto.\n- destruct o; inversion H2.\n  destruct IHbigstep1 with (xs := xs) (h := h) (s := s) (t := t); auto.\n  intros. apply G. simpl. apply in_or_app; auto. rewrite H4 in G3; auto.\n  destruct H5 with (h' := h') (s' := s'); auto. destruct H7.\n  destruct IHbigstep2 with (xs := xs) (h := h') (s := s') (t := x); auto.\n  eapply step_while_true.\n  erewrite <- gcond. apply H.\n  rewrite H4 in G3.\n  eapply eq_restr_incl; [|apply G3].\n  intros. apply G. simpl.\n  apply in_or_app. auto.\n  apply H8.\n  apply H10. auto.\n- exists t. split. rewrite <- H2. assumption.\n  apply step_while_false.\n  erewrite <- gcond. apply H.\n  rewrite H2 in G3.\n  eapply eq_restr_incl; [|apply G3].\n  intros. apply G. simpl.\n  apply in_or_app. auto.\n- destruct IHbigstep with (xs := xs) (h := h) (s := s) (t := t); auto.\n  intros. apply G. simpl. apply in_or_app; auto. rewrite H3 in G3; auto.\n  apply step_while_fail.\n  erewrite <- gcond. apply H.\n  rewrite H3 in G3.\n  eapply eq_restr_incl; [|apply G3].\n  intros. apply G. simpl.\n  apply in_or_app. auto.\n  apply H4. auto.\nQed.\n\nProposition cwlp_cond (S1: program) (q: cassert):\n  forall (h : heap) (s t : store),\n   eq_restr s t (pvar S1 ++ cvar q) ->\n   (~ bigstep S1 (h, s) None /\\ forall (h' : heap) (s' : store),\n      bigstep S1 (h, s) (Some (h', s')) -> q (h', s')) <->\n   (~ bigstep S1 (h, t) None /\\ forall (h' : heap) (s' : store),\n      bigstep S1 (h, t) (Some (h', s')) -> q (h', s')).\nintros; split; intro; destruct H0.\n- split.\n  + intro.\n    pose proof (bigstep_cond S1 (h, t) None H2 (pvar S1 ++ cvar q)).\n    destruct H3 with (h := h) (s := t) (t := s); auto.\n    intros. apply in_or_app; auto.\n    apply eq_restr_comm. apply H.\n  + intros.\n    pose proof (bigstep_cond S1 (h, t) (Some (h', s')) H2 (pvar S1 ++ cvar q)).\n    destruct H3 with (h := h) (s := t) (t := s); auto.\n    intros. apply in_or_app; auto.\n    apply eq_restr_comm. apply H.\n    destruct H4 with (h' := h') (s' := s'); auto. destruct H6.\n    rewrite ccond with (t := x).\n    apply H1. assumption.\n    eapply eq_restr_incl; [|apply H6].\n    intros. apply in_or_app. auto.\n- split.\n  + intro.\n    pose proof (bigstep_cond S1 (h, s) None H2 (pvar S1 ++ cvar q)).\n    destruct H3 with (h := h) (s := s) (t := t); auto.\n    intros. apply in_or_app; auto.\n  + intros.\n    pose proof (bigstep_cond S1 (h, s) (Some (h', s')) H2 (pvar S1 ++ cvar q)).\n    destruct H3 with (h := h) (s := s) (t := t); auto.\n    intros. apply in_or_app; auto.\n    destruct H4 with (h' := h') (s' := s'); auto. destruct H6.\n    rewrite ccond with (t := x).\n    apply H1. assumption.\n    eapply eq_restr_incl; [|apply H6].\n    intros. apply in_or_app. auto.\nQed.\nProposition cwlp_stable (S1: program) (q: cassert):\n  forall (h : heap) (s : store),\n   ~ ~ (~ bigstep S1 (h, s) None /\\ forall (h' : heap) (s' : store),\n      bigstep S1 (h, s) (Some (h', s')) -> q (h', s')) ->\n   (~ bigstep S1 (h, s) None /\\ forall (h' : heap) (s' : store),\n      bigstep S1 (h, s) (Some (h', s')) -> q (h', s')).\nintros. split.\nintro. apply H. intro. destruct H1.\napply H1. assumption.\nintros. apply cstable. intro.\napply H. intro. destruct H2.\napply H3 in H0.\napply H1. assumption.\nQed.\nDefinition cwlp (S1: program) (q: cassert): cassert :=\n  mkcassert (fun '(h, s) => ~bigstep S1 (h, s) None /\\\n      forall h' s', bigstep S1 (h, s) (Some (h', s')) -> q (h', s'))\n    (pvar S1 ++ cvar q) (cwlp_cond S1 q) (cwlp_stable S1 q).\n\n\n", "meta": {"author": "praalhans", "repo": "OSL", "sha": "10a34c4c5c89418c4df4705845380ebab6a17137", "save_path": "github-repos/coq/praalhans-OSL", "path": "github-repos/coq/praalhans-OSL/OSL-10a34c4c5c89418c4df4705845380ebab6a17137/shallow/Language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6611294185850582}}
{"text": "Require Import init.\n\nRequire Import order_minmax.\n\nRequire Export analysis_norm.\n\nDefinition series {V} `{Plus V, Zero V} (a : nat → V) (n : nat) := sum a 0 n.\n\nDefinition cauchy_series {V} `{Plus V, Zero V, AbsoluteValue V} (a : nat → V)\n    := ∀ ε, 0 < ε → ∃ N, ∀ i j, N ≤ i → |sum a i j| < ε.\n(* begin hide *)\n\nSection AnalysisSeries.\n\nContext {V} `{\n    VP : Plus V,\n    VZ : Zero V,\n    VN : Neg V,\n    @PlusComm V VP,\n    @PlusAssoc V VP,\n    @PlusLid V VP VZ,\n    @PlusLinv V VP VZ VN,\n\n    SM : ScalarMult real V,\n    @ScalarId real V real_one SM,\n    @ScalarLdist real V VP SM,\n    @ScalarRdist real V real_plus VP SM,\n\n    VA : AbsoluteValue V,\n    @AbsDefinite V VA VZ,\n    @AbsNeg V VA VN,\n    @AbsTriangle V VA VP,\n    @AbsPositive V VA,\n    @AbsScalar V VA SM\n}.\n\nExisting Instance abs_metric.\n(* end hide *)\n\nDefinition abs_converges (a : nat → V) := seq_converges (series (λ n, |a n|)).\n\nTheorem series_scalar : ∀ af a c, seq_lim (series af) a →\n    seq_lim (series (λ n, c · af n)) (c · a).\nProof.\n    intros af a c a_lim.\n    assert (series (λ n, c · af n) = (λ n, c · sum af 0 n)) as f_eq.\n    {\n        apply functional_ext.\n        intros n.\n        nat_induction n.\n        -   unfold series.\n            unfold zero; cbn.\n            rewrite scalar_ranni.\n            reflexivity.\n        -   cbn.\n            unfold series in IHn.\n            rewrite IHn.\n            rewrite scalar_ldist.\n            reflexivity.\n    }\n    rewrite f_eq.\n    apply seq_lim_scalar.\n    exact a_lim.\nQed.\n\nTheorem series_sum : ∀ af bf a b, seq_lim (series af) a → seq_lim (series bf) b\n    → seq_lim (series (λ n, af n + bf n)) (a + b).\nProof.\n    intros af bf a b a_lim b_lim.\n    assert (series (λ n, af n + bf n) = (λ n, series af n + series bf n))\n        as f_eq.\n    {\n        apply functional_ext.\n        intros n.\n        nat_induction n.\n        -   unfold zero; cbn.\n            rewrite plus_rid.\n            reflexivity.\n        -   cbn.\n            unfold series in IHn.\n            rewrite IHn.\n            do 2 rewrite <- plus_assoc.\n            apply lplus.\n            do 2 rewrite plus_assoc.\n            apply rplus.\n            apply plus_comm.\n    }\n    rewrite f_eq.\n    apply seq_lim_plus; assumption.\nQed.\n\nTheorem series_converges_cauchy :\n    ∀ af, seq_converges (series af) → cauchy_series af.\nProof.\n    intros af af_conv.\n    apply converges_cauchy in af_conv.\n    intros ε ε_pos.\n    specialize (af_conv ε ε_pos) as [N af_conv].\n    exists N.\n    intros i j i_ge.\n    assert (N ≤ i + j) as j_ge.\n    {\n        apply (trans i_ge).\n        rewrite <- (plus_rid i) at 1.\n        apply le_lplus.\n        apply nat_pos.\n    }\n    specialize (af_conv (i + j) i j_ge i_ge).\n    unfold series in af_conv; cbn in af_conv.\n    rewrite sum_minus in af_conv.\n    rewrite plus_lid in af_conv.\n    exact af_conv.\nQed.\n\nTheorem cauchy_series_converges : complete V →\n    ∀ af, cauchy_series af → seq_converges (series af).\nProof.\n    intros V_comp af af_conv.\n    apply V_comp.\n    intros ε ε_pos.\n    specialize (af_conv ε ε_pos) as [N af_conv].\n    exists N.\n    intros i j i_ge j_ge.\n    unfold series; cbn.\n    destruct (connex i j) as [leq|leq].\n    -   apply nat_le_ex in leq as [c eq]; subst.\n        rewrite abs_minus.\n        rewrite sum_minus.\n        rewrite plus_lid.\n        apply af_conv.\n        exact i_ge.\n    -   apply nat_le_ex in leq as [c eq]; subst.\n        rewrite sum_minus.\n        rewrite plus_lid.\n        apply af_conv.\n        exact j_ge.\nQed.\n(* begin hide *)\nEnd AnalysisSeries.\n\nSection AnalysisSeries.\n\nContext {V} `{\n    VP : Plus V,\n    VZ : Zero V,\n    VN : Neg V,\n    @PlusComm V VP,\n    @PlusAssoc V VP,\n    @PlusLid V VP VZ,\n    @PlusLinv V VP VZ VN,\n\n    SM : ScalarMult real V,\n    @ScalarId real V real_one SM,\n    @ScalarLdist real V VP SM,\n    @ScalarRdist real V real_plus VP SM,\n\n    VA : AbsoluteValue V,\n    @AbsDefinite V VA VZ,\n    @AbsNeg V VA VN,\n    @AbsTriangle V VA VP,\n    @AbsPositive V VA,\n    @AbsScalar V VA SM\n}.\n\nExisting Instance abs_metric.\n(* end hide *)\n\nTheorem abs_converge_test : complete V → ∀ af,\n    abs_converges af → seq_converges (series af).\nProof.\n    intros V_comp af af_conv.\n    apply (cauchy_series_converges V_comp).\n    intros ε ε_pos.\n    unfold abs_converges in af_conv.\n    apply series_converges_cauchy in af_conv.\n    specialize (af_conv ε ε_pos) as [N af_conv].\n    exists N.\n    intros i j i_geq.\n    specialize (af_conv i j i_geq) as ltq.\n    apply (le_lt_trans2 ltq).\n    clear ε ε_pos N af_conv i_geq ltq.\n    assert (0 ≤ sum (λ n, |af n|) i j) as sum_pos.\n    {\n        nat_induction j.\n        -   unfold zero at 2; cbn.\n            apply refl.\n        -   cbn.\n            rewrite <- (plus_rid 0).\n            apply le_lrplus; [>exact IHj|].\n            apply abs_pos.\n    }\n    rewrite (abs_pos_eq _ sum_pos).\n    clear sum_pos.\n    nat_induction j.\n    -   unfold zero; cbn.\n        rewrite <- abs_zero.\n        apply refl.\n    -   cbn.\n        apply (trans (abs_tri _ _)).\n        apply le_rplus.\n        exact IHj.\nQed.\n\nTheorem series_skip : ∀ an n,\n    seq_converges (series an) ↔ seq_converges (series (λ m, an (m + n))).\nProof.\n    intros an n.\n    split.\n    -   intros [x anx].\n        exists (x - sum an 0 n).\n        rewrite metric_seq_lim in *.\n        intros ε ε_pos.\n        specialize (anx ε ε_pos) as [N anx].\n        exists N.\n        intros m m_geq.\n        specialize (anx (n + m) (trans m_geq (nat_le_self_lplus m n))).\n        cbn in *.\n        unfold series in *.\n        rewrite sum_argument_plus.\n        rewrite plus_lid.\n        rewrite <- plus_assoc.\n        rewrite <- neg_plus.\n        rewrite <- (plus_lid n) at 2.\n        rewrite sum_plus.\n        exact anx.\n    -   intros [x anx].\n        exists (x + sum an 0 n).\n        rewrite metric_seq_lim in *.\n        intros ε ε_pos.\n        specialize (anx ε ε_pos) as [N anx].\n        exists (N + n).\n        intros m m_geq.\n        apply nat_le_ex in m_geq as [c eq]; subst m.\n        specialize (anx (N + c) (nat_le_self_rplus _ _)).\n        cbn in *.\n        unfold series in *.\n        rewrite sum_argument_plus in anx.\n        rewrite plus_lid in anx.\n        rewrite <- (neg_neg (sum an 0 n)).\n        rewrite <- plus_assoc.\n        rewrite <- neg_plus.\n        rewrite (plus_comm (-sum an 0 n)).\n        rewrite (plus_comm N n).\n        rewrite <- plus_assoc.\n        rewrite sum_minus.\n        rewrite plus_lid.\n        exact anx.\nQed.\n(* begin hide *)\nEnd AnalysisSeries.\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/Analysis/Norm/analysis_series.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.661129408936525}}
{"text": "Require Export DevCoq.Dev.basic_matroid_list.\n\nParameter rk_singleton_ge : forall P, rk (P :: nil)  >= 1.\nParameter rk_couple_ge : forall P Q, ~ P = Q -> rk(P :: Q :: nil) >= 2.\nParameter rk_three_points_on_lines : forall A B, exists C, rk (A :: B :: C :: nil) = 2 /\\ rk (B :: C :: nil) = 2 /\\ rk (A :: C :: nil) = 2.\nParameter rk_inter : forall A B C D, exists J, rk (A :: B :: J :: nil) = 2 /\\ rk (C :: D :: J :: nil) = 2.\nParameter rk_lower_dim : exists P0 P1 P2, rk( P0 :: P1 :: P2 :: nil) >=3.\n\nLemma rk_singleton_1 : forall A, rk(A :: nil) <= 1.\nProof.\nintros.\napply matroid1_b_useful.\nintuition.\nQed.\n\nLemma rk_singleton : forall A, rk(A :: nil) = 1.\nProof.\nintros.\nassert(H := rk_singleton_ge A).\nassert(HH := rk_singleton_1 A).\nomega.\nQed.\n\nLemma matroid1_b_useful2 : forall (l : list Point) (a : Point), length (a :: l) >= 1 -> rk (a :: l) >= 1.\nProof.\nintros.\nassert(HH := rk_singleton a).\nassert(HH0 := matroid2 (a :: nil) (a :: l)).\nassert(HH1 : incl (a :: nil) (a :: l));[my_inO|].\nassert(HH2 := HH0 HH1).\nomega.\nQed.\n\nLemma rk_couple_2 : forall A B, rk(A :: B :: nil) <= 2.\nProof.\nintros.\napply matroid1_b_useful.\nintuition.\nQed.\n\nLemma rk_couple : forall A B : Point,~ A = B -> rk(A :: B :: nil) = 2.\nProof.\nintros.\nassert(HH := rk_couple_2 A B).\nassert(HH0 := rk_couple_ge A B H).\nomega.\nQed.\n\nLemma rk_triple_3 : forall A B C : Point, rk (A :: B :: C :: nil) <= 3.\nProof.\nintros.\napply matroid1_b_useful.\nintuition.\nQed.\n\nLemma couple_rk1 : forall A B, rk(A :: B :: nil) = 2 -> ~ A = B.\nProof.\nintros.\nintro.\nrewrite H0 in H.\nassert(HH : equivlist (B :: B :: nil) (B :: nil));[my_inO|].\nrewrite HH in H.\nassert(HH0 := rk_singleton_1 B).\nomega.\nQed.\n\nLemma couple_rk2 : forall A B, rk(A :: B :: nil) = 1 -> A = B.\nProof.\nintros.\ncase_eq(eq_dec A B).\nintros.\nassumption.\nintros.\nassert(HH := rk_couple A B n).\nomega.\nQed.\n\nLemma rk_quadruple_inter_aux : forall A B C D E,\n~ A = C ->\n~ A = D ->\n~ B = C ->\n~ B = D -> \nrk(A :: B :: E :: nil) = 2 -> \nrk(C :: D :: E :: nil) = 2 ->\nrk(A :: B :: C :: D :: nil) = 2 \\/ rk(A :: B :: C :: D :: nil) = 3.\nProof.\nintros.\n\nassert (HH0 : rk((A :: B :: E :: nil) ++ (C :: D :: E :: nil)) + rk(list_inter (A :: B :: E :: nil) (C :: D :: E :: nil)) <=\n       rk(A :: B :: E :: nil) + rk(C :: D :: E :: nil)).\napply matroid3_useful;my_inO.\nassert(HH1 : equivlist (list_inter (A :: B :: E :: nil) (C :: D :: E :: nil))  (E :: nil)).\nmy_inO.\nassert(HH2 := rk_singleton E).\nrewrite HH1 in HH0.\nrewrite HH2 in HH0.\nrewrite H3 in HH0.\nrewrite H4 in HH0.\n\nassert(HH3 : rk(A :: B :: E :: C :: D :: E :: nil) = 2 \\/ rk(A :: B :: E :: C :: D :: E :: nil) = 3).\napply le_lt_or_eq in HH0;simpl in HH0.\ndestruct HH0.\nassert(HH4 : rk(A :: B :: E :: C :: D :: E :: nil) < 3).\nsolve[intuition].\nassert(HH5 : incl (A :: B :: E :: nil) (A :: B :: E :: C :: D :: E :: nil));[my_inO|].\nassert(HH6 := matroid2 (A :: B :: E :: nil) (A :: B :: E :: C :: D :: E :: nil) HH5).\nomega.\nomega.\n\ndestruct HH3.\n\nassert(HH3 := rk_couple A C H).\nassert(HH4 : incl (A :: C :: nil) (A :: B :: C :: D :: nil));[my_inO|].\nassert(HH5 : incl (A :: B :: C :: D :: nil) (A :: B :: E :: C :: D :: E :: nil));[my_inO|].\nassert(HH6 := matroid2 (A :: C :: nil) (A :: B :: C :: D :: nil) HH4).\nassert(HH7 := matroid2 (A :: B :: C :: D :: nil) (A :: B :: E :: C :: D :: E :: nil) HH5).\nomega.\n\nassert(HH3 : incl (A :: B :: C :: D :: nil) (A :: B :: E :: C :: D :: E :: nil));[my_inO|].\nassert(HH4 := matroid2 (A :: B :: C :: D :: nil) (A :: B :: E :: C :: D :: E :: nil) HH3).\nrewrite H5 in HH4.\napply le_lt_or_eq in HH4.\ndestruct HH4.\nassert(HH5 := rk_couple A C H).\nassert(HH6 : incl (A :: C :: nil) (A :: B :: C :: D :: nil));[my_inO|].\nassert(HH7 := matroid2 (A :: C :: nil) (A :: B :: C :: D :: nil) HH6).\nomega.\nomega.\nQed.\n\nLemma rk_quadruple_inter_aux2 : forall B C D E,\n~ B = C ->\n~ B = D -> \nrk(D :: B :: E :: nil) = 2 -> \nrk(C :: D :: E :: nil) = 2 ->\nrk(D :: B :: C :: D :: nil) = 2 \\/ rk(D :: B :: C :: D :: nil) = 3.\nProof.\nintros.\n\nassert (HH0 : rk((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) + rk(list_inter (D :: B :: E :: nil) (C :: D :: E :: nil)) <=\n       rk(D :: B :: E :: nil) + rk(C :: D :: E :: nil)).\napply matroid3_useful;my_inO.\nassert (HH1 : equivlist (list_inter (D :: B :: E :: nil) (C :: D :: E :: nil)) (D :: E :: nil));[my_inO|].\nrewrite HH1 in HH0.\ncase_eq(eq_dec D E).\nintros;subst.\nrewrite H1 in HH0;rewrite H2 in HH0.\nassert(HH2 : equivlist (E :: E :: nil) (E :: nil));[my_inO|].\nreplace (rk (E :: E :: nil)) with (rk(E :: nil)) in HH0.\n2:rewrite HH2;intuition.\nassert(HH3 := rk_singleton E).\nrewrite HH3 in HH0.\n\nassert(HH4 : rk(E :: B :: E :: C :: E :: E :: nil) = 2 \\/ rk((E :: B :: E :: C :: E :: E :: nil)) = 3).\napply le_lt_or_eq in HH0;simpl in HH0.\ndestruct HH0.\nassert(HH5 : rk((E :: B :: E :: C :: E :: E :: nil)) < 3).\nsolve[intuition].\nassert(HH4 : incl (E :: B :: E :: nil) (E :: B :: E :: C :: E :: E :: nil));[my_inO|].\nassert(HH6 := matroid2 (E :: B :: E :: nil) (E :: B :: E :: C :: E :: E :: nil) HH4).\nomega.\nomega.\n\nassert(HH5 : equivlist (E :: B :: E :: C :: E :: E :: nil) (E :: B :: C :: E :: nil));[my_inO|].\nrewrite HH5 in HH4.\nomega.\n\nintros.\nrewrite H1 in HH0;rewrite H2 in HH0.\nassert(HH2 := rk_couple D E n).\nrewrite HH2 in HH0.\nassert(HH3 : rk((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) = 2).\nassert(HH4 : incl (D :: E :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil)));[my_inO|].\nassert(HH5 := matroid2 (D :: E :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) HH4). \nomega.\nassert(HH4 := rk_couple B C H).\nassert(HH5 : incl (B :: C :: nil) (D :: B :: C :: D :: nil));[my_inO|].\nassert(HH6 := matroid2 (B :: C :: nil) (D :: B :: C :: D :: nil) HH5).\nassert(HH7 : incl (D :: B :: C :: D :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil)));[my_inO|].\nassert(HH8 := matroid2 (D :: B :: C :: D :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) HH7).\nomega.\nQed.\n\nLemma rk_quadruple_inter : forall A B C D E,\nrk(A :: B :: E :: nil) = 2 -> \nrk(C :: D :: E :: nil) = 2 ->\nrk(A :: B :: C :: D :: nil) = 1 \\/ rk(A :: B :: C :: D :: nil) = 2 \\/ rk(A :: B :: C :: D :: nil) = 3.\nProof.\nintros.\ncase_eq(eq_dec A C);\ncase_eq(eq_dec A D);\ncase_eq(eq_dec B C);\ncase_eq(eq_dec B D).\n\nintros.\nrewrite e;rewrite e1.\ncase_eq(eq_dec C D).\nintros;rewrite e3.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n);assert(HH : equivlist (D :: D :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e;rewrite e1.\ncase_eq(eq_dec C D).\nintros;rewrite e2.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n0);assert(HH : equivlist (C :: C :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e;rewrite e1.\ncase_eq(eq_dec C D).\nintros;rewrite e2.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n0);assert(HH : equivlist (C :: D :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e in *.\nassert(HH0 := rk_quadruple_inter_aux2 B C D E n0 n H H0).\nomega.\n\nintros.\nrewrite e0;rewrite e1.\ncase_eq(eq_dec C D).\nintros;rewrite e2.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n0);assert(HH : equivlist (C :: C :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e;rewrite e0.\ncase_eq(eq_dec C D).\nintros;rewrite e1.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n1);assert(HH : equivlist (C :: C :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e;rewrite e0.\ncase_eq(eq_dec C D).\nintros;rewrite e1.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n1);assert(HH : equivlist (C :: D :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e in *.\nassert(HH0 : equivlist (C :: D :: E :: nil) (D :: C :: E :: nil));[my_inO|].\nrewrite HH0 in H0.\nassert(HH1 := rk_quadruple_inter_aux2 B D C E n n0 H H0).\nassert(HH2 : equivlist (C :: B :: C :: D :: nil) (C :: B :: D :: C :: nil));[my_inO|].\nrewrite HH2.\nomega.\n\nintros.\nrewrite e;rewrite e1.\ncase_eq(eq_dec C D).\nintros;rewrite e2.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n0);assert(HH : equivlist (D :: D :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e;rewrite e0.\ncase_eq(eq_dec C D).\nintros;rewrite e1.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n1);assert(HH : equivlist (D :: C :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e;rewrite e0.\ncase_eq(eq_dec C D).\nintros;rewrite e1.\nassert(HH0 : equivlist (D :: D :: D :: D :: nil) (D :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton D);omega.\nintros.\nassert(HH0 := rk_couple C D n1);assert(HH : equivlist (D :: D :: C :: D :: nil) (C :: D :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros.\nrewrite e in *.\nassert(HH0 := rk_quadruple_inter_aux2 B C D E n0 n H H0).\nomega.\n\nintros.\nrewrite e in  *.\nassert(HH0 : equivlist (A :: D :: E :: nil) (D :: A :: E :: nil));[my_inO|].\nrewrite HH0 in H.\nassert(HH1 := rk_quadruple_inter_aux2 A C D E n0 n H H0).\nassert(HH2 : equivlist (D :: A :: C :: D :: nil) (A :: D :: C :: D :: nil));[my_inO|].\nrewrite HH2 in HH1.\nomega.\n\nintros.\nrewrite e in  *.\nassert(HH0 : equivlist (A :: C :: E :: nil) (C :: A :: E :: nil));[my_inO|].\nrewrite HH0 in H.\nassert(HH1 : equivlist (C :: D :: E :: nil) (D :: C :: E :: nil));[my_inO|].\nrewrite HH1 in H0.\nassert(HH2 := rk_quadruple_inter_aux2 A D C E n0 n1 H H0).\nassert(HH3 : equivlist (C :: A :: D :: C :: nil) (A :: C :: C :: D :: nil));[my_inO|].\nrewrite HH3 in HH2.\nomega.\n\nintros.\nrewrite e in *.\nassert(HH0 : equivlist (A :: D :: E :: nil) (D :: A :: E :: nil));[my_inO|].\nrewrite HH0 in H.\nassert(HH1 := rk_quadruple_inter_aux2 A C D E n1 n0 H H0).\nassert(HH2 : equivlist (A :: D :: C :: D :: nil) (D :: A :: C :: D :: nil));[my_inO|].\nrewrite HH2.\nomega.\n\nintros.\nassert(HH0 := rk_quadruple_inter_aux A B C D E n2 n1 n0 n H H0).\nomega.\nQed.\n\nLemma rk_quadruple_max_3 : forall X Y Z W: Point,rk(X :: Y :: Z :: W :: nil) <= 3.\nintros.\nassert(HH0 := rk_inter X Y Z W).\ndestruct HH0.\ndestruct H.\nassert(HH1 := rk_quadruple_inter X Y Z W x H H0).\nomega.\nQed.\n\nLemma rk_quintuple_inter_aux : forall A B C D E,\n~ A = C ->\n~ A = D ->\n~ B = C ->\n~ B = D -> \nrk(A :: B :: E :: nil) = 2 -> \nrk(C :: D :: E :: nil) = 2 ->\nrk(A :: B :: C :: D :: E :: nil) = 2 \\/ rk(A :: B :: C :: D :: E :: nil) = 3.\nProof.\nintros.\n\nassert (HH0 : rk((A :: B :: E :: nil) ++ (C :: D :: E :: nil)) + rk(list_inter (A :: B :: E :: nil) (C :: D :: E :: nil)) <=\n       rk(A :: B :: E :: nil) + rk(C :: D :: E :: nil)).\napply matroid3_useful;my_inO.\nassert(HH1 : equivlist (list_inter (A :: B :: E :: nil) (C :: D :: E :: nil))  (E :: nil)).\nmy_inO.\nassert(HH2 := rk_singleton E).\nrewrite HH1 in HH0.\nrewrite HH2 in HH0.\nrewrite H3 in HH0.\nrewrite H4 in HH0.\n\nassert(HH3 : rk(A :: B :: E :: C :: D :: E :: nil) = 2 \\/ rk(A :: B :: E :: C :: D :: E :: nil) = 3).\napply le_lt_or_eq in HH0;simpl in HH0.\ndestruct HH0.\nassert(HH4 : rk(A :: B :: E :: C :: D :: E :: nil) < 3).\nsolve[intuition].\nassert(HH5 : incl (A :: B :: E :: nil) (A :: B :: E :: C :: D :: E :: nil));[my_inO|].\nassert(HH6 := matroid2 (A :: B :: E :: nil) (A :: B :: E :: C :: D :: E :: nil) HH5).\nomega.\nomega.\n\ndestruct HH3.\n\nassert(HH3 := rk_couple A C H).\nassert(HH4 : incl (A :: C :: nil) (A :: B :: C :: D :: E :: nil));[my_inO|].\nassert(HH5 : incl (A :: B :: C :: D :: E :: nil) (A :: B :: E :: C :: D :: E :: nil));[my_inO|].\nassert(HH6 := matroid2 (A :: C :: nil) (A :: B :: C :: D :: E :: nil) HH4).\nassert(HH7 := matroid2 (A :: B :: C :: D :: E :: nil) (A :: B :: E :: C :: D :: E :: nil) HH5).\nomega.\n\nassert(HH3 : incl (A :: B :: C :: D :: E :: nil) (A :: B :: E :: C :: D :: E :: nil));[my_inO|].\nassert(HH4 := matroid2 (A :: B :: C :: D :: E :: nil) (A :: B :: E :: C :: D :: E :: nil) HH3).\nrewrite H5 in HH4.\napply le_lt_or_eq in HH4.\ndestruct HH4.\nassert(HH5 := rk_couple A C H).\nassert(HH6 : incl (A :: C :: nil) (A :: B :: C :: D :: E :: nil));[my_inO|].\nassert(HH7 := matroid2 (A :: C :: nil) (A :: B :: C :: D :: E :: nil) HH6).\nomega.\nomega.\nQed.\n\nLemma rk_quintuple_inter_aux2 : forall B C D E,\n~ B = C ->\n~ B = D -> \nrk(D :: B :: E :: nil) = 2 -> \nrk(C :: D :: E :: nil) = 2 ->\nrk(D :: B :: C :: D :: E :: nil) = 2 \\/ rk(D :: B :: C :: D :: E :: nil) = 3.\nProof.\nintros.\n\nassert (HH0 : rk((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) + rk(list_inter (D :: B :: E :: nil) (C :: D :: E :: nil)) <=\n       rk(D :: B :: E :: nil) + rk(C :: D :: E :: nil)).\napply matroid3_useful;my_inO.\nassert (HH1 : equivlist (list_inter (D :: B :: E :: nil) (C :: D :: E :: nil)) (D :: E :: nil));[my_inO|].\nrewrite HH1 in HH0.\ncase_eq(eq_dec D E).\nintros;subst.\nrewrite H1 in HH0;rewrite H2 in HH0.\nassert(HH2 : equivlist (E :: E :: nil) (E :: nil));[my_inO|].\nreplace (rk (E :: E :: nil)) with (rk(E :: nil)) in HH0.\n2:rewrite HH2;intuition.\nassert(HH3 := rk_singleton E).\nrewrite HH3 in HH0.\n\nassert(HH4 : rk(E :: B :: E :: C :: E :: E :: nil) = 2 \\/ rk((E :: B :: E :: C :: E :: E :: nil)) = 3).\napply le_lt_or_eq in HH0;simpl in HH0.\ndestruct HH0.\nassert(HH5 : rk((E :: B :: E :: C :: E :: E :: nil)) < 3).\nsolve[intuition].\nassert(HH4 : incl (E :: B :: E :: nil) (E :: B :: E :: C :: E :: E :: nil));[my_inO|].\nassert(HH6 := matroid2 (E :: B :: E :: nil) (E :: B :: E :: C :: E :: E :: nil) HH4).\nomega.\nomega.\n\nassert(HH5 : equivlist (E :: B :: E :: C :: E :: E :: nil) (E :: B :: C :: E :: E :: nil));[my_inO|].\nrewrite HH5 in HH4.\nomega.\n\nintros.\nrewrite H1 in HH0;rewrite H2 in HH0.\nassert(HH2 := rk_couple D E n).\nrewrite HH2 in HH0.\nassert(HH3 : rk((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) = 2).\nassert(HH4 : incl (D :: E :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil)));[my_inO|].\nassert(HH5 := matroid2 (D :: E :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) HH4). \nomega.\nassert(HH4 := rk_couple B C H).\nassert(HH5 : incl (B :: C :: nil) (D :: B :: C :: D :: E :: nil));[my_inO|].\nassert(HH6 := matroid2 (B :: C :: nil) (D :: B :: C :: D :: E :: nil) HH5).\nassert(HH7 : incl (D :: B :: C :: D :: E :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil)));[my_inO|].\nassert(HH8 := matroid2 (D :: B :: C :: D :: E :: nil) ((D :: B :: E :: nil) ++ (C :: D :: E :: nil)) HH7).\nomega.\nQed.\n\nLemma rk_quintuple_inter : forall A B C D E,\nrk(A :: B :: E :: nil) = 2 -> \nrk(C :: D :: E :: nil) = 2 ->\nrk(A :: B :: C :: D :: E :: nil) = 1 \\/ rk(A :: B :: C :: D :: E :: nil) = 2 \\/ rk(A :: B :: C :: D :: E :: nil) = 3.\nProof.\nintros.\ncase_eq(eq_dec A C);\ncase_eq(eq_dec A D);\ncase_eq(eq_dec B C);\ncase_eq(eq_dec B D).\n\nintros;rewrite <-e2;rewrite e;rewrite e1.\ncase_eq(eq_dec D E).\nintros;rewrite e3.\nassert(HH0 : equivlist (E :: E :: E :: E :: E :: nil) (E :: nil));[my_inO|].\nrewrite HH0;assert(HH1 := rk_singleton E);omega.\nintros.\nassert(HH0 := rk_couple D E n);assert(HH : equivlist (D :: D :: D :: D :: E :: nil) (D :: E :: nil));[my_inO|].\nrewrite HH;omega.\n\nintros;apply False_ind;apply n;rewrite e;rewrite <-e0;rewrite e1;reflexivity.\n\nintros;apply False_ind;apply n;rewrite e;rewrite <-e0;rewrite e1;reflexivity.\n\nintros;rewrite e in *.\nassert(HH := rk_quintuple_inter_aux2 B C D E n0 n H H0);intuition.\n\nintros;apply False_ind;apply n;rewrite <-e;rewrite e0;rewrite <-e1;reflexivity.\n\nintros;rewrite e;rewrite e0.\nassert(HH0 : equivlist (C :: C :: C :: D :: E :: nil) (C :: D :: E :: nil));[my_inO|].\nrewrite HH0;right;left;assumption.\n\nintros;rewrite e;rewrite e0.\nassert(HH0 : equivlist (C :: D :: C :: D :: E :: nil) (C :: D :: E :: nil));[my_inO|].\nrewrite HH0;right;left;assumption.\n\nintros;rewrite e in *.\nassert(HH : equivlist (C :: D :: E :: nil) (D :: C :: E :: nil));[my_inO|];rewrite HH in H0.\nassert(HH0 := rk_quintuple_inter_aux2 B D C E n n0 H H0).\nassert(HH1 : equivlist (C :: B :: D :: C :: E :: nil) (C :: B :: C :: D :: E :: nil));[my_inO|].\nrewrite HH1 in HH0;intuition.\n\nintros;apply False_ind;apply n;rewrite <-e0;rewrite e;rewrite e1;reflexivity.\n\nintros;rewrite e;rewrite e0.\nassert(HH0 : equivlist (D :: C :: C :: D :: E :: nil) (C :: D :: E :: nil));[my_inO|].\nrewrite HH0;right;left;assumption.\n\nintros;rewrite e;rewrite e0.\nassert(HH0 : equivlist (D :: D :: C :: D :: E :: nil) (C :: D :: E :: nil));[my_inO|].\nrewrite HH0;right;left;assumption.\n\nintros;rewrite e in *.\nassert(HH0 := rk_quintuple_inter_aux2 B C D E n0 n H H0);intuition.\n\nintros;rewrite e in *.\nassert(HH : equivlist (A :: D :: E :: nil) (D :: A :: E :: nil));[my_inO|];rewrite HH in H.\nassert(HH0 := rk_quintuple_inter_aux2 A C D E n0 n H H0). \nassert(HH1 : equivlist (D :: A :: C :: D :: E :: nil) (A :: D :: C :: D :: E :: nil));[my_inO|].\nrewrite HH1 in HH0;intuition.\n\nintros;rewrite e in *.\nassert(HH : equivlist (A :: C :: E :: nil) (C :: A :: E :: nil));[my_inO|];rewrite HH in H.\nassert(HH0 : equivlist (C :: D :: E :: nil) (D :: C :: E :: nil));[my_inO|];rewrite HH0 in H0.\nassert(HH1 := rk_quintuple_inter_aux2 A D C E n0 n1 H H0). \nassert(HH2 : equivlist (C :: A :: D :: C :: E :: nil) (A :: C :: C :: D :: E :: nil));[my_inO|].\nrewrite HH2 in HH1;intuition.\n\nintros;rewrite e in *.\nassert(HH : equivlist (A :: D :: E :: nil) (D :: A :: E :: nil));[my_inO|];rewrite HH in H.\nassert(HH0 := rk_quintuple_inter_aux2 A C D E n1 n0 H H0).\nassert(HH1 : equivlist (D :: A :: C :: D :: E :: nil) (A :: D :: C :: D :: E :: nil));[my_inO|].\nrewrite HH1 in HH0;intuition.\n\nintros.\nassert(HH := rk_quintuple_inter_aux A B C D E n2 n1 n0 n H H0);intuition.\nQed.\n\nLemma rk_quintuple_max_3 : forall X Y Z W V: Point, rk(X :: Y :: Z :: W :: V :: nil) <= 3.\nProof.\nintros.\n\nassert(HH := rk_lower_dim).\ndestruct HH;destruct H;destruct H.\nassert(HH := rk_triple_3 x x0 x1).\nassert(HH0 : rk (x :: x0 :: x1 :: nil) = 3);[omega|].\nassert(HH1 := rk_quadruple_max_3 x x0 x1 X).\nassert(HH2 := rk_quadruple_max_3 x x0 x1 Y).\nassert(HH3 := rk_quadruple_max_3 x x0 x1 Z).\nassert(HH4 := rk_quadruple_max_3 x x0 x1 W).\nassert(HH5 := rk_quadruple_max_3 x x0 x1 V).\nassert(HH6 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: nil));[my_inO|].\nassert(HH7 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: Y :: nil));[my_inO|].\nassert(HH8 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: Z :: nil));[my_inO|].\nassert(HH9 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: W :: nil));[my_inO|].\nassert(HH10 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: V :: nil));[my_inO|].\nassert(HH11 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: nil) HH6).\nassert(HH12 : rk (x :: x0 :: x1 :: X :: nil) = 3);[omega|].\nassert(HH13 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: Y :: nil) HH7).\nassert(HH14 : rk (x :: x0 :: x1 :: Y :: nil) = 3);[omega|].\nassert(HH15 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: Z :: nil) HH8).\nassert(HH16 : rk (x :: x0 :: x1 :: Z :: nil) = 3);[omega|].\nassert(HH17 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: W :: nil) HH9).\nassert(HH18 : rk (x :: x0 :: x1 :: W :: nil) = 3);[omega|].\nassert(HH19 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: V :: nil) HH10).\nassert(HH20 : rk (x :: x0 :: x1 :: V :: nil) = 3);[omega|].\nclear H HH HH1 HH2 HH3 HH4 HH5 HH6 HH7 HH8 HH9 HH10 HH11 HH13 HH15 HH17 HH19.\n\ncase_eq(eq_dec X Y);intros.\nrewrite e;assert(HH21 : equivlist (Y :: Y :: Z :: W :: V :: nil) (Y :: Z :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 Y Z W V);assumption.\ncase_eq(eq_dec X Z);intros.\nrewrite e;assert(HH21 : equivlist (Z :: Y :: Z :: W :: V :: nil) (Y :: Z :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 Y Z W V);assumption.\ncase_eq(eq_dec X W);intros.\nrewrite e;assert(HH21 : equivlist (W :: Y :: Z :: W :: V :: nil) (Y :: Z :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 Y Z W V);assumption.\ncase_eq(eq_dec X V);intros.\nrewrite e;assert(HH21 : equivlist (V :: Y :: Z :: W :: V :: nil) (Y :: Z :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 Y Z W V);assumption.\ncase_eq(eq_dec Y Z);intros.\nrewrite e;assert(HH21 : equivlist (X :: Z :: Z :: W :: V :: nil) (X :: Z :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 X Z W V);assumption.\ncase_eq(eq_dec Y W);intros.\nrewrite e;assert(HH21 : equivlist (X :: W :: Z :: W :: V :: nil) (X :: Z :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 X Z W V);assumption.\ncase_eq(eq_dec Y V);intros.\nrewrite e;assert(HH21 : equivlist (X :: V :: Z :: W :: V :: nil) (X :: Z :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 X Z W V);assumption.\ncase_eq(eq_dec Z W);intros.\nrewrite e;assert(HH21 : equivlist (X :: Y :: W :: W :: V :: nil) (X :: Y :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 X Y W V);assumption.\ncase_eq(eq_dec Z V);intros.\nrewrite e;assert(HH21 : equivlist (X :: Y :: V :: W :: V :: nil) (X :: Y :: W :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 X Y W V);assumption.\ncase_eq(eq_dec W V);intros.\nrewrite e;assert(HH21 : equivlist (X :: Y :: Z :: V :: V :: nil) (X :: Y :: Z :: V :: nil));[my_inO|];\nrewrite HH21;assert(HH22 := rk_quadruple_max_3 X Y Z V);assumption.\nclear H H0 H1 H2 H3 H4 H5 H6 H7 H8.\n\nassert (HH23 : rk((x :: x0 :: x1 :: X :: nil) ++ (x :: x0 :: x1 :: Y :: nil)) + rk(list_inter (x :: x0 :: x1 :: X :: nil) (x :: x0 :: x1 :: Y :: nil)) <=\n       rk(x :: x0 :: x1 :: X :: nil) + rk(x :: x0 :: x1 :: Y :: nil)).\napply matroid3_useful;my_inO.\nassert(HH24 : equivlist (list_inter (x :: x0 :: x1 :: X :: nil) (x :: x0 :: x1 :: Y :: nil))  (x :: x0 :: x1 :: nil));[my_inO|].\nrewrite HH24 in HH23;clear HH24.\nassert(HH25 : equivlist ((x :: x0 :: x1 :: X :: nil) ++ x :: x0 :: x1 :: Y :: nil) (x :: x0 :: x1 :: X :: Y :: nil));[my_inO|].\nrewrite HH25 in HH23;clear HH25.\nassert(HH26 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y :: nil));[my_inO|].\nassert(HH27 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y :: nil) HH26).\nassert(HH28 : rk(x :: x0 :: x1 :: X :: Y :: nil) = 3);[omega|].\nclear HH12 HH14 HH23 HH26 HH27.\n\nassert (HH29 : rk((x :: x0 :: x1 :: X :: Y :: nil) ++ (x :: x0 :: x1 :: Z :: nil)) + rk(list_inter (x :: x0 :: x1 :: X :: Y :: nil) (x :: x0 :: x1 :: Z :: nil)) <=\n       rk(x :: x0 :: x1 :: X :: Y :: nil) + rk(x :: x0 :: x1 :: Z :: nil)).\napply matroid3_useful;my_inO.\nassert(HH30 : equivlist (list_inter (x :: x0 :: x1 :: X :: Y :: nil) (x :: x0 :: x1 :: Z :: nil))  (x :: x0 :: x1 :: nil));[my_inO|].\nrewrite HH30 in HH29;clear HH30.\nassert(HH31 : equivlist ((x :: x0 :: x1 :: X :: Y :: nil) ++ x :: x0 :: x1 :: Z :: nil) (x :: x0 :: x1 :: X :: Y :: Z :: nil));[my_inO|].\nrewrite HH31 in HH29;clear HH31.\nassert(HH32 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y :: Z :: nil));[my_inO|].\nassert(HH33 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y ::  Z :: nil) HH32).\nassert(HH34 : rk(x :: x0 :: x1 :: X :: Y :: Z :: nil) = 3);[omega|].\nclear HH16 HH28 HH29 HH32 HH33.\n\nassert (HH35 : rk((x :: x0 :: x1 :: X :: Y :: Z :: nil) ++ (x :: x0 :: x1 :: W :: nil)) + rk(list_inter (x :: x0 :: x1 :: X :: Y :: Z :: nil) (x :: x0 :: x1 :: W :: nil)) <=\n       rk(x :: x0 :: x1 :: X :: Y :: Z :: nil) + rk(x :: x0 :: x1 :: W :: nil)).\napply matroid3_useful;my_inO.\nassert(HH36 : equivlist (list_inter (x :: x0 :: x1 :: X :: Y :: Z :: nil) (x :: x0 :: x1 :: W :: nil))  (x :: x0 :: x1 :: nil));[my_inO|].\nrewrite HH36 in HH35;clear HH36.\nassert(HH37 : equivlist ((x :: x0 :: x1 :: X :: Y :: Z :: nil) ++ x :: x0 :: x1 :: W :: nil) (x :: x0 :: x1 :: X :: Y :: Z :: W :: nil));[my_inO;left;my_inO|].\nrewrite HH37 in HH35;clear HH37.\nassert(HH38 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y :: Z :: W :: nil));[my_inO|].\nassert(HH39 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y ::  Z :: W :: nil) HH38).\nassert(HH40 : rk(x :: x0 :: x1 :: X :: Y :: Z :: W ::nil) = 3);[omega|].\nclear HH18 HH34 HH35 HH38 HH39.\n\nassert (HH41 : rk((x :: x0 :: x1 :: X :: Y :: Z :: W :: nil) ++ (x :: x0 :: x1 :: V :: nil)) + rk(list_inter (x :: x0 :: x1 :: X :: Y :: Z :: W ::nil) (x :: x0 :: x1 :: V :: nil)) <=\n       rk(x :: x0 :: x1 :: X :: Y :: Z :: W :: nil) + rk(x :: x0 :: x1 :: V :: nil)).\napply matroid3_useful;my_inO.\nassert(HH42 : equivlist (list_inter (x :: x0 :: x1 :: X :: Y :: Z :: W :: nil) (x :: x0 :: x1 :: V :: nil))  (x :: x0 :: x1 :: nil));[my_inO|].\nrewrite HH42 in HH41;clear HH42.\nassert(HH43 : equivlist ((x :: x0 :: x1 :: X :: Y :: Z :: W :: nil) ++ x :: x0 :: x1 :: V :: nil) (x :: x0 :: x1 :: X :: Y :: Z :: W :: V :: nil));[my_inO;left;my_inO|].\nrewrite HH43 in HH41;clear HH43.\nassert(HH44 : incl (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y :: Z :: W :: V :: nil));[my_inO|].\nassert(HH45 := matroid2 (x :: x0 :: x1 :: nil) (x :: x0 :: x1 :: X :: Y ::  Z :: W :: V :: nil) HH44).\nassert(HH46 : rk(x :: x0 :: x1 :: X :: Y :: Z :: W ::V :: nil) = 3);[omega|].\nclear HH20 HH40 HH41 HH44 HH45.\nassert(HH47 : incl (X :: Y :: Z :: W :: V :: nil)(x :: x0 :: x1 :: X :: Y :: Z :: W :: V :: nil));[my_inO|].\nassert(HH48 := matroid2 (X :: Y :: Z :: W :: V :: nil)(x :: x0 :: x1 :: X :: Y :: Z :: W :: V :: nil) HH47).\nomega.\nQed.\n", "meta": {"author": "pascalschreck", "repo": "MatroidIncidenceProver", "sha": "e492d375a2264e6c908c9c47fe719c39e3f847f8", "save_path": "github-repos/coq/pascalschreck-MatroidIncidenceProver", "path": "github-repos/coq/pascalschreck-MatroidIncidenceProver/MatroidIncidenceProver-e492d375a2264e6c908c9c47fe719c39e3f847f8/matroidbasedIGprover/matroid_C_Coq/DevCoq/Dev/basic_rank_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6611294089365249}}
{"text": "Parameter object : Type.\nParameter arrow : Type.\nParameter source : arrow -> object -> Prop.\nParameter target : arrow -> object -> Prop.\n\nNotation \"f ':' A '~>' B\" := ((source f A) /\\ (target f B)) (at level 40). \n\nAxiom R1a: forall A, exists u, u: A ~> A.\nAxiom R1b: forall A B C f g, f:A ~> B /\\ g: B ~> C -> exists gf, gf: A ~> C.\n\nParameter top : object.\nAxiom R2: forall A, exists bang, bang: A ~> top.\n\nParameter conj : object -> object -> object.\nNotation \"A 'and' B\" := (conj A B) (at level 25).\n\nAxiom R3a: forall A B, exists prA, prA : A and B ~> A.\nAxiom R3b: forall A B, exists prB, prB : A and B ~> B.\nAxiom R3c: forall A B C f g, f: C ~> A /\\ g: C ~> B -> exists h, h: C ~> A and B.\n\nLemma andComm: forall A B, exists swap, swap: A and B ~> B and A.\nProof.\n  intros.\n  pose proof (R3b A B). destruct H.\n  pose proof (R3a A B). destruct H0.\n  eapply R3c. split.\n  - apply H.\n  - apply H0.\nQed.", "meta": {"author": "mirithering", "repo": "coq", "sha": "bff4429c146a998a416f3c177b772b0fefd92d46", "save_path": "github-repos/coq/mirithering-coq", "path": "github-repos/coq/mirithering-coq/coq-bff4429c146a998a416f3c177b772b0fefd92d46/lambekScott.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.6610964900675241}}
{"text": "Set Implicit Arguments.\nRequire Export graft.\n\n\n\nDefinition LTree_decomp (A:Set) (t: LTree A) : LTree A\n  := match t with\n         LLeaf => LLeaf\n       | LBin a t1 t2 => (LBin  a t1 t2)\n       end.\n\nLemma LTree_decompose : \n   forall (A : Set) (t: LTree A), t = LTree_decomp t.\nProof.\n destruct t; trivial.\nQed.\n\nLtac  LTree_unfold term :=\n  apply trans_equal with (1 := LTree_decompose term).\n\n\nLemma graft_unfold1 : forall (A:Set) (t': LTree A),\n    graft LLeaf  t' = t'.\nProof.\n intros A t'; LTree_unfold (graft LLeaf t');\n  case t'; simpl; auto.\nQed.\n\nLemma graft_unfold2: forall (A:Set)(a:A) (t1 t2 t':LTree A),\n                      (graft (LBin a t1 t2) t')=\n                      (LBin a (graft t1 t') (graft t2 t')).\nProof.\n intros A a t1 t2 t'; LTree_unfold (graft (LBin a t1 t2) t');\n  simpl; auto.\nQed.\n\n\nLemma graft_unfold : forall (A:Set) (t t': LTree A),\n                     graft t t' = match t  with\n                                  | LLeaf => t'\n                                  | LBin n t1 t2 =>\n                                             LBin  n (graft t1 t')\n                                                     (graft t2 t')\n                                  end.\nProof.\n intros A t t'; case t.\n apply graft_unfold1. \n intros; apply graft_unfold2.\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/co-inductifs/SRC/graft_unfold.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.661092902171037}}
{"text": "(* 7. Hierarchies *)\n(* 7.5 Linking a custom data type to the library *)\n\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n(* Set Printing Coercions.                     (* *** *) *)\n\nInductive windrose : predArgType := N | S | E | W.\nCheck N \\in windrose.\nFail Check N != S.\nFail Check #| windrose | == 4.\n\nDefinition w2o (w : windrose) : 'I_4 :=\n  match w with\n  | N => inord 0\n  | S => inord 1\n  | E => inord 2\n  | W => inord 3\n  end.\n\nDefinition o2w (o : 'I_4) : windrose :=\n  match val o with\n  | 0 => N\n  | 1 => S\n  | 2 => E\n  | _ => W\n  end.\n\n(* w2o と o2w がキャンセルの関係であることを証明する。 *)\nLemma can_wo4 : cancel w2o o2w.\nProof.\n  case.\n  rewrite /o2w.\n  rewrite /val.\n  rewrite /=.\n  rewrite inordK.\n  - done.\n  - done.\n  Restart.\n    by case; rewrite /o2w /= inordK.\nQed.\nDefinition windrose_eqMixin := CanEqMixin can_wo4.\n\n(* w2o が injective であることを証明する。 *)\n\nLemma inj_w2o : injective w2o.\nProof.\n  Check can_inj : forall (rT aT : Type) (f : aT -> rT) (g : rT -> aT),\n    cancel f g -> injective f.\n  apply can_inj with (g:=o2w).              (* cancel (f:=w2o) (g:=o2w) *)\n  by apply can_wo4.\nQed.\nDefinition windrose_eqMixin' := InjEqMixin inj_w2o.\n\n(* Equality.axiom (∀x y, w2o x == w2o y) が成立することを証明する。 *)\n\nLemma w2o_eqP : Equality.axiom (fun x y => w2o x == w2o y).\nProof.\n  Check inj_eqAxiom : forall (T : Type) (eT : eqType) (f : T -> Equality.sort eT),\n    injective f -> Equality.axiom (T:=T) (fun x y : T => f x == f y).\n  apply: inj_eqAxiom.\n    by apply: inj_w2o.\nQed.\nDefinition windrose_eqMixin'' := EqMixin w2o_eqP.\n\n\n(* Definition windrose_eqMixin := CanEqMixin can_wo4. *)\nCanonical windrose_eqType := EqType windrose windrose_eqMixin.\n\nCheck N \\in windrose.\nCheck N != S.\nFail Check #| windrose | == 4.\n\nDefinition windrose_choiceMixin := CanChoiceMixin can_wo4.\nCanonical windrose_choiceType := ChoiceType windrose windrose_choiceMixin.\n\nDefinition windrose_countMixin := CanCountMixin can_wo4.\nCanonical windrose_countType := CountType windrose windrose_countMixin.\n\nDefinition windrose_finMixin := CanFinMixin can_wo4.\n\n(* pcan_enumP は証明されているが、can_enumP はないので証明する。 *)\nLemma can_enumP : forall (eT : countType) (fT : finType)\n         (f : Countable.sort eT -> Finite.sort fT)\n         (g : Finite.sort fT -> Countable.sort eT),\n    cancel f g -> Finite.axiom (undup (map g (Finite.enum fT))).\nProof.\n  move=> eT fT f g.\n  move=> fK x; rewrite count_uniq_mem ?undup_uniq // mem_undup.\n  by rewrite -[x]fK map_f //.\nQed.\n\nLemma windrose_enumP : Finite.axiom (undup (map o2w (Finite.enum (ordinal_finType 4)))).\nProof.\n  Check can_enumP.\n  apply can_enumP with (f:=w2o).\n  by apply can_wo4.\nQed.\nDefinition windrose_finMixin' := FinMixin windrose_enumP.\n\n(* Definition windrose_finMixin := CanFinMixin can_wo4. *)\nCanonical windrose_finType := FinType windrose windrose_finMixin.\n\nCheck N \\in windrose.\nCheck N != S.\nCheck #| windrose | == 4.\n\n(* END *)\n\nPrint Equality.axiom.\n(* 一般に injective なら Equality.axiom が成り立つという定理： inj_eqAxiom *)\nCheck inj_eqAxiom : forall (T : Type) (eT : eqType) (f : T -> eT),\n    injective f -> Equality.axiom (T:=T) (fun x y : T => f x == f y).\nCheck @inj_eqAxiom\n      windrose                              (* T : Type *)\n      (ordinal_eqType 4)                    (* eT : eqType *)\n      w2o.                                  (* T -> eT *)\n\nPrint Finite.axiom.\n(* 一般に cancel なら Finite.axiom が成り立つという定理 *)\nCheck can_enumP : forall (eT : countType)  (* windrose *)\n                         (fT : finType)    (* 'I_4 *)\n                         (f : eT -> fT)  (* w2o : windrose -> 'I_4. *)\n                         (g : fT -> eT), (* o2w' : 'I_4 -> windrose. *)\n    cancel f g -> Finite.axiom (T:=eT) (undup (map g (Finite.enum fT))).\nCheck @can_enumP\n      windrose_countType\n      (ordinal_finType 4)\n      w2o\n      o2w.\n\n(* その他の補題 *)\nCheck can_pcan : forall (rT aT : Type) (f : aT -> rT) (g : rT -> aT),\n    cancel f g -> pcancel f (fun y : rT => Some (g y)).\n\nDefinition o2n (o : 'I_4) : nat := val o.\n\n(* サブタイプ型の値からオリジナル型の値を取り出す。 *)\nCheck @val : forall (T : Type) (P : pred T) (s : subType P), s -> T.\n(* これは、injective である。 *)\nCheck val_inj.\n\n(* サブタイプ('I_4 から、オリジナルタイプの nat を取り出す。 *)\nGoal injective o2n.\nProof.\n  move=> n x.\n  rewrite /o2n.\n  (* val n = val x -> n = x *)\n  by apply val_inj.\nQed.\n\n(* END *)\n\n(* 主役は w2o か o2w か *)\n\n(*\n(* pcancel w2o o2w であることを証明する。 *)\nDefinition pcan_wo4 := can_pcan can_wo4.\nDefinition o2w' o : option windrose := Some (o2w o).\n *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/math-comp-book/suhara.ch7-windrose-2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085758631159, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.6610929017263586}}
{"text": "Require Import Imp.\nRequire Import Smallstep.\nRequire Import Types.\n\nModule STLC.\n\nInductive ty :=\n  | TBool  : ty\n  | TArrow : ty -> ty -> ty.\n\nInductive tm :=\n  | tvar   : id -> tm\n  | tapp   : tm -> tm -> tm\n  | tabs   : id -> ty -> tm -> tm\n  | ttrue  : tm\n  | tfalse : tm\n  | tif    : tm -> tm -> tm -> tm\n.\n\nDefinition x := (Id 0).\nDefinition y := (Id 1).\nDefinition z := (Id 2).\nHint Unfold x.\nHint Unfold y.\nHint Unfold z.\n\nReserved Notation \"'[' x ':=' s ']' t\" (at level 20).\n\nFixpoint subst (x : id) (s : tm) (t : tm) : tm :=\n  match t with\n    | tvar i   => if eq_id_dec i x then s else tvar i\n    | tapp a b => tapp ([x := s] a) ([x := s] b)\n    | tabs i tp bd => if eq_id_dec i x then tabs i tp bd\n                      else tabs i tp ([x := s] bd)\n    | tif c bt be => tif ([x := s] c) ([x := s] bt) ([x := s] be)\n    | e => e\n  end\n  where \"'[' x ':=' s ']' t\" := (subst x s t).\n\n(* Exercise: 3 stars (substi) *)\n\nInductive substi (s : tm) (x : id) : tm -> tm -> Prop :=\n  | s_var1 :\n      substi s x (tvar x) s\n  | s_var2 : forall i,\n      i <> x ->\n      substi s x (tvar i) (tvar i)\n  | s_app  : forall a a' b b',\n      substi s x a a' ->\n      substi s x b b' ->\n      substi s x (tapp a b) (tapp a' b')\n  | s_abs1 : forall tp bd,\n      substi s x (tabs x tp bd) (tabs x tp bd)\n  | s_abs2 : forall i tp bd bd',\n      i <> x ->\n      substi s x bd bd' ->\n      substi s x (tabs i tp bd) (tabs i tp bd')\n  | s_if   : forall c c' t t' e e',\n      substi s x c c' ->\n      substi s x t t' ->\n      substi s x e e' ->\n      substi s x (tif c t e) (tif c' t' e')\n  | s_true :\n      substi s x ttrue ttrue\n  | s_false :\n      substi s x tfalse tfalse\n.\n\nHint Constructors substi.\n\nTheorem substi_correct : forall s x t t',\n  [x := s] t = t' <-> substi s x t t'.\nProof.\n  split; intro.\n  - generalize dependent t'.\n    induction t; simpl; intros; subst; auto;\n      destruct (eq_id_dec i x0); subst; auto.\n  - induction H; simpl; subst; auto;\n      try rewrite eq_id; try rewrite neq_id; auto.\nQed.\n\n(* END substi. *)\n\nInductive value : tm -> Prop :=\n  | v_abs   : forall x T t, value (tabs x T t)\n  | v_true  : value ttrue\n  | v_false : value tfalse.\n\nHint Constructors value.\n\nReserved Notation \"t1 '==>' t2\" (at level 40).\n\nInductive step : tm -> tm -> Prop :=\n  | ST_AppAbs : forall x T t12 v2,\n      value v2 ->\n      (tapp (tabs x T t12) v2) ==> [x := v2] t12\n  | ST_App1   : forall t1 t1' t2,\n      t1 ==> t1' ->\n      tapp t1 t2 ==> tapp t1' t2\n  | ST_App2   : forall t1 t2 t2',\n      value t1 ->\n      t2 ==> t2' ->\n      tapp t1 t2 ==> tapp t1 t2'\n  | ST_IfTrue  : forall t e,\n      tif ttrue t e ==> t\n  | ST_IfFalse : forall t e,\n      tif tfalse t e ==> e\n  | ST_If : forall c c' t e,\n      c ==> c' ->\n      tif c t e ==> tif c' t e\n  where \"t1 '==>' t2\" := (step t1 t2).\n\nHint Constructors step.\n\nNotation multistep := (multi step).\n\nNotation \"t1 '==>*' t2\" := (multistep t1 t2) (at level 40).\n\nNotation idB    := (tabs x TBool (tvar x)).\nNotation idBB   := (tabs x (TArrow TBool TBool) (tvar x)).\nNotation idBBBB := (tabs x (TArrow (TArrow TBool TBool) (TArrow TBool TBool))\n                           (tvar x)).\n\n(* Exercise: 2 stars (step_example3) *)\n\nLemma step_example5 :\n       (tapp (tapp idBBBB idBB) idB)\n  ==>* idB.\nProof.\n  eapply multi_step.\n    apply ST_App1. apply ST_AppAbs. apply v_abs.\n  eapply multi_step.\n    apply ST_AppAbs. apply v_abs.\n  simpl. apply multi_refl.\nQed.\n\nLemma step_example5_with_normalize :\n       (tapp (tapp idBBBB idBB) idB)\n  ==>* idB.\nProof. normalize. Qed.\n\n(* END step_example3. *)\n\nDefinition context := id -> option ty.\n\nDefinition pupdate { A : Type } (m : id -> option A) (x : id) (v : A) :=\n  update m x (Some v).\n\nHint Unfold pupdate.\n\nReserved Notation \"Gamma '|-' t '\\in' T\" (at level 40).\n\nInductive has_type : context -> tm -> ty -> Prop :=\n  | T_Var : forall G i T,\n      G i = Some T ->\n      G |- tvar i \\in T\n  | T_Abs : forall G i T11 bd T12,\n      pupdate G i T11 |- bd \\in T12 ->\n      G |- tabs i T11 bd \\in TArrow T11 T12\n  | T_App : forall G a1 a2 T11 T12,\n      G |- a1 \\in TArrow T11 T12 ->\n      G |- a2 \\in T11 ->\n      G |- tapp a1 a2 \\in T12\n  | T_True : forall G,\n      G |- ttrue \\in TBool\n  | T_False : forall G,\n      G |- tfalse \\in TBool\n  | T_If : forall G c t e T,\n      G |- c \\in TBool ->\n      G |- t \\in T ->\n      G |- e \\in T ->\n      G |- (tif c t e) \\in T\n  where \"Gamma '|-' t '\\in' T\" := (has_type Gamma t T).\n\nHint Constructors has_type.\n\n(* Exercise: 2 stars, optional (typing_example_2_full) *)\n\nExample typing_example_2_full :\n  (fun _ => None) |-\n    (tabs x TBool\n       (tabs y (TArrow TBool TBool)\n          (tapp (tvar y) (tapp (tvar y) (tvar x))))) \\in\n    (TArrow TBool (TArrow (TArrow TBool TBool) TBool)).\nProof.\n  apply T_Abs. apply T_Abs.\n  unfold pupdate.\n  apply T_App with TBool. apply T_Var. reflexivity.\n  apply T_App with TBool. apply T_Var. reflexivity.\n  apply T_Var. reflexivity.\nQed.\n\n(* END typing_example_2_full. *)\n\n(* Exercise: 2 stars (typing_example_3) *)\n\nExample typing_example_3 :\n  exists T,\n    (fun _ => None) |-\n      (tabs x (TArrow TBool TBool)\n         (tabs y (TArrow TBool TBool)\n            (tabs z TBool\n               (tapp (tvar y) (tapp (tvar x) (tvar z)))))) \\in T.\nProof with auto.\n  exists (TArrow (TArrow TBool TBool)\n    ((TArrow (TArrow TBool TBool) (TArrow TBool TBool)))).\n  repeat econstructor.\nQed.\n\n(* END typing_example_3. *)\n\n(* Exercise: 3 stars, optional (typing_nonexample_3) *)\n\nExample typing_nonexample_3 :\n  ~ (exists S, exists T,\n       (fun _ => None) |-\n          (tabs x S\n             (tapp (tvar x) (tvar x))) \\in\n     T).\nProof.\n  intros [S [T H]].\n  inversion H;  subst; clear H.\n  inversion H5; subst; clear H5.\n  inversion H2; subst; clear H2.\n  inversion H4; subst; clear H4.\n  rewrite H2 in H1.\n  inversion H1.\n  clear H1 H2 S.\n  induction T11; inversion H0.\n  apply IHT11_1. rewrite <- H2. assumption.\nQed.\n\n(* END typing_nonexample_3. *)\n\nEnd STLC.\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/Stlc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6610928961624494}}
{"text": "Set Implicit Arguments.\nRequire Import Arith.\nRequire Import Wf_nat.\nRequire Import List.\nImport ListNotations.\n\nSection var.\n  Variable var : Set.\n\n  Inductive term : Set :=\n  | tvar : var -> term\n  | tapp : term -> term -> term\n  | tabs : (var -> term) -> term.\n\n  (* Inductive value : term -> Prop := *)\n  (* | vabs : forall (x: var -> term), value (tabs x). *)\n\n  (* Inductive eval : term -> term -> Prop := *)\n  (* | E_App1 : forall (t1 t1' t2: term), eval t1 t1' -> eval (tapp t1 t2) (tapp t1' t2) *)\n  (* | E_App2 : forall (v1 t2 t2': term), value v1 -> eval t2 t2' -> eval (tapp v1 t2) (tapp v1 t2'). *)\nEnd var.\n\nDefinition Exp := forall var, term var.\n\nExample identity : Exp := fun _ => tabs (fun x => tvar x).\nExample self_app : Exp := fun _ => tabs (fun x => tapp (tvar x) (tvar x)).\n\nFixpoint size (t: term unit): nat :=\n  match t with\n  | tvar _ => 1\n  | tapp t1 t2 => 1 + (size t1) + (size t2)\n  | tabs t' => 1 + size (t' tt)\n  end.\n\nDefinition Size (t: Exp) := size (t unit).\n\nEval compute in Size identity.\nEval compute in Size self_app.\n\nFixpoint depth (t: term unit): nat :=\n  match t with\n  | tvar _ => 1\n  | tapp t1 t2 => 1 + (list_max [(depth t1); (depth t2)])\n  | tabs t' => 1 + depth (t' tt)\n  end.\n\nDefinition Depth (t: Exp) := depth (t unit).\n\nEval compute in Depth identity.\nEval compute in Depth self_app.\n\nSection flatten.\n  Variable var: Set.\n\n  Fixpoint flatten (t : term (term var)) : term var :=\n    match t with\n    | tvar t' => t'\n    | tapp t1 t2 => tapp (flatten t1) (flatten t2)\n    | tabs t1 => tabs (fun x => flatten (t1 (tvar x)))\n  end.\n\nEnd flatten.\n\nDefinition Exp1 := forall var : Set, var -> term var.\nDefinition Subst (E: Exp1) (E' : Exp): Exp := fun var => flatten (E (term var) (E' var)).\n\nExample ident1 : Exp1 := fun _ X => tvar X.\n\nExample free_var : Exp1 := fun _ x => tabs (fun y => tvar x).\nExample expr : Exp := fun _ => tabs (fun x => tvar x).\n\nEval compute in Subst free_var expr.\n", "meta": {"author": "paulcadman", "repo": "tapl", "sha": "fe6724ef0b2b5b46517a08a42417680497729cee", "save_path": "github-repos/coq/paulcadman-tapl", "path": "github-repos/coq/paulcadman-tapl/tapl-fe6724ef0b2b5b46517a08a42417680497729cee/ch05/utlc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.6610928959383021}}
{"text": "From Coq Require Import ZArith Ascii String Eqdep_dec.\nFrom Vyper Require Import Config.\n\nInductive int_size\n:= I8 | I32 | I64 | I128 | I256.\n\nDefinition int_size_in_bits (i: int_size): Z\n:= match i with\n   | I8 => 8\n   | I32 => 32\n   | I64 => 64\n   | I128 => 128\n   | I256 => 256\n   end.\n\nDefinition int_size_in_bytes (i: int_size): Z\n:= match i with\n   | I8 => 1\n   | I32 => 4\n   | I64 => 8\n   | I128 => 16\n   | I256 => 32\n   end.\n\nLemma int_size_ok (i: int_size):\n  int_size_in_bits i = (8 * int_size_in_bytes i)%Z.\nProof.\n  destruct i; trivial. \nQed.\n\nDefinition string_of_int_size (i: int_size): string\n:= match i with\n   | I8 => \"8\"\n   | I32 => \"32\"\n   | I64 => \"64\"\n   | I128 => \"128\"\n   | I256 => \"256\"\n   end.\n\nDefinition int_size_of_string (s: string): option int_size\n:= match s with\n   | \"8\"%string => Some I8\n   | \"32\"%string => Some I32\n   | \"64\"%string => Some I64\n   | \"128\"%string => Some I128\n   | \"256\"%string => Some I256\n   | _ => None\n   end.\n\nLemma int_size_of_string_of_int_size (i: int_size):\n  int_size_of_string (string_of_int_size i) = Some i.\nProof.\nnow destruct i.\nQed.\n\nDefinition uint_max (i: int_size) := (2 ^ int_size_in_bits i - 1)%Z.\nDefinition sint_max (i: int_size) := (2 ^ (int_size_in_bits i - 1) - 1)%Z.\nDefinition sint_min (i: int_size) := (- 2 ^ (int_size_in_bits i - 1))%Z.\n\nExample uint_max_byte: uint_max I8 = 255%Z.    Proof. trivial. Qed.\nExample sint_min_byte: sint_min I8 = (-128)%Z. Proof. trivial. Qed.\nExample sint_max_byte: sint_max I8 = 127%Z.    Proof. trivial. Qed.\n\nInductive yul_type\n:= BoolType\n | IntType (size: int_size) (signed: bool).\n\nLemma yul_type_eq_dec (a b: yul_type)\n: {a = b} + {a <> b}.\nProof.\nrepeat decide equality.\nDefined.\n\nDefinition U8 := IntType I8 false.\nDefinition S8 := IntType I8 true.\nDefinition U32 := IntType I32 false.\nDefinition S32 := IntType I32 true.\nDefinition U64 := IntType I64 false.\nDefinition S64 := IntType I64 true.\nDefinition U128 := IntType I128 false.\nDefinition S128 := IntType I128 true.\nDefinition U256 := IntType I256 false.\nDefinition S256 := IntType I256 true.\n\nDefinition uint256_to_Z_as_signed {C: VyperConfig} (n: uint256)\n: Z\n:= let z := Z_of_uint256 n in\n   if Z.testbit z 255%Z\n     then z - 2 ^ 256\n     else z.\n\nInductive yul_value {C: VyperConfig} (t: yul_type)\n:= NumberValue (value: uint256)\n               (ok: match t with\n                    | BoolType => false\n                    | IntType size true  => let x := uint256_to_Z_as_signed value in\n                                            andb (sint_min size <=? x)%Z (x <=? sint_max size)%Z\n                    | IntType size false => let x := Z_of_uint256 value in\n                                            andb (0 <=? x)%Z (x <=? uint_max size)%Z\n                    end = true)\n | BoolValue (b: bool)\n             (ok:  match t with\n                   | BoolType => true\n                   | _ => false\n                   end = true).\n\nDefinition yul_true  {C: VyperConfig} := BoolValue BoolType true eq_refl.\nDefinition yul_false {C: VyperConfig} := BoolValue BoolType false eq_refl.\n\nLemma yul_uint256_helper {C: VyperConfig} (value: uint256):\n  ((0 <=? Z_of_uint256 value)%Z && (Z_of_uint256 value <=? uint_max I256)%Z)%bool = true.\nProof.\nassert (R := uint256_range value).\napply andb_true_intro. split.\nnow rewrite Z.leb_le.\nunfold uint_max. unfold int_size_in_bits.\nrewrite Z.leb_le.\napply Zsucc_le_reg.\nreplace (Z.succ (2 ^ 256 - 1))%Z with (2 ^ 256)%Z by trivial.\nnow apply Zlt_le_succ.\nQed.\n\nDefinition yul_uint256 {C: VyperConfig} (value: uint256)\n: yul_value U256\n:= NumberValue U256 value (yul_uint256_helper value).\n\nDefinition dynamic_value {C: VyperConfig} := { t: yul_type & yul_value t }.\n\nDefinition dynamic_value_of_uint256 {C: VyperConfig} (value: uint256)\n:= existT _ U256 (yul_uint256 value).\n\nDefinition uint256_of_yul_value {C: VyperConfig} {t: yul_type} (y: yul_value t)\n: uint256\n:= match y with\n   | NumberValue _ value _ => value\n   | BoolValue _ true  _ => one256\n   | BoolValue _ false _ => zero256\n   end.\n\nLocal Lemma uint256_to_yul_value_helper_bool {C: VyperConfig} {t: yul_type} (T: t = BoolType):\n   match t with\n   | BoolType => true\n   | IntType _ _ => false\n   end = true.\nProof.\nnow subst.\nQed.\n\nLocal Lemma uint256_to_yul_value_helper_sint {C: VyperConfig} {t: yul_type} {u : uint256}\n                                             {size: int_size} (T: t = IntType size true)\n                                             (E: let x := uint256_to_Z_as_signed u in\n                                                  ((sint_min size <=? x)%Z &&\n                                                    (x <=? sint_max size)%Z)%bool = true):\n   match t with\n   | BoolType => false\n   | IntType size true =>\n       let x := uint256_to_Z_as_signed u in ((sint_min size <=? x)%Z && (x <=? sint_max size)%Z)%bool\n   | IntType size false => let x := Z_of_uint256 u in ((0 <=? x)%Z && (x <=? uint_max size)%Z)%bool\n   end = true.\nProof.\nnow subst.\nQed.\n\nLocal Lemma uint256_to_yul_value_helper_uint {C: VyperConfig} {t: yul_type} {u : uint256}\n                                             {size: int_size} (T: t = IntType size false)\n                                             (E: let x := Z_of_uint256 u in\n                                                  ((0 <=? x)%Z && (x <=? uint_max size)%Z)%bool = true):\n   match t with\n   | BoolType => false\n   | IntType size true =>\n       let x := uint256_to_Z_as_signed u in ((sint_min size <=? x)%Z && (x <=? sint_max size)%Z)%bool\n   | IntType size false => let x := Z_of_uint256 u in ((0 <=? x)%Z && (x <=? uint_max size)%Z)%bool\n   end = true.\nProof.\nnow subst.\nQed.\n\nDefinition yul_value_of_uint256 {C: VyperConfig} (u: uint256) (t: yul_type)\n: option (yul_value t)\n:= match t as t' return t = t' -> _ with\n   | BoolType => fun T =>\n                 match Z_of_uint256 u with\n                 | 0%Z => Some (BoolValue t false (uint256_to_yul_value_helper_bool T))\n                 | 1%Z => Some (BoolValue t true (uint256_to_yul_value_helper_bool T))\n                 | _ => None\n                 end\n   | IntType size true => fun T =>\n                          let x := uint256_to_Z_as_signed u in\n                          (if andb (sint_min size <=? x)%Z (x <=? sint_max size)%Z as c\n                           return _ = c -> _\n                             then fun E => Some (NumberValue t u (uint256_to_yul_value_helper_sint T E))\n                             else fun _ => None) eq_refl\n   | IntType size false => fun T =>\n                           let x := Z_of_uint256 u in\n                           (if andb (0 <=? x)%Z (x <=? uint_max size)%Z as c return _ = c -> _\n                              then fun E => Some (NumberValue t u (uint256_to_yul_value_helper_uint T E))\n                              else fun _ => None) eq_refl\n   end eq_refl.\n\nLemma yul_value_of_uint256_u256 {C: VyperConfig} (u: uint256):\n  yul_value_of_uint256 u U256 = Some (yul_uint256 u).\nProof.\nsimpl.\nassert (R := uint256_range u).\nunfold uint_max. unfold int_size_in_bits.\nassert (T: ((0 <=? Z_of_uint256 u)%Z && (Z_of_uint256 u <=? 2 ^ 256 - 1)%Z)%bool = true).\n{\n  apply andb_true_intro.\n  destruct R as (L, U).\n  split. { apply Z.leb_le. exact L. }\n  apply Z.leb_le.\n  rewrite Z.sub_1_r.\n  apply Z.lt_le_pred in U.\n  exact U.\n}\nrewrite Logic2.if_yes with (E := T).\nf_equal.\nunfold yul_uint256.\nf_equal.\napply eq_proofs_unicity. decide equality.\nQed.\n\nLemma yul_value_of_uint256_of_yul_value {C: VyperConfig} (t: yul_type) (v: yul_value t):\n  yul_value_of_uint256 (uint256_of_yul_value v) t = Some v.\nProof.\ndestruct t; cbn; destruct v; try discriminate.\n{\n  destruct b; cbn; [unfold one256 | unfold zero256];\n     rewrite uint256_ok; cbn; repeat f_equal; apply eq_proofs_unicity;\n     decide equality.\n}\ndestruct signed; cbn in *.\n{\n  (* signed *)\n  remember (fun E =>\n             Some (NumberValue (IntType size true) value (uint256_to_yul_value_helper_sint eq_refl E)))\n    as good_branch.\n  enough (Q: forall E, good_branch E = Some (NumberValue (IntType size true) value ok)).\n  {\n    clear Heqgood_branch.\n    revert good_branch Q.\n    assert (ok' := ok).\n    now rewrite ok'.\n  }\n  intros.\n  subst. repeat f_equal.\n  apply eq_proofs_unicity; decide equality.\n}\n(* unsigned *)\nremember (fun E =>\n           Some (NumberValue (IntType size false) value (uint256_to_yul_value_helper_uint eq_refl E)))\n  as good_branch.\nenough (Q: forall E, good_branch E = Some (NumberValue (IntType size false) value ok)).\n{\n  clear Heqgood_branch.\n  revert good_branch Q.\n  assert (ok' := ok).\n  now rewrite ok'.\n}\nintros.\nsubst. repeat f_equal.\napply eq_proofs_unicity; decide equality.\nQed.\n\nDefinition uint256_of_dynamic_value {C: VyperConfig} (d: dynamic_value)\n: uint256\n:= let '(existT _ _ v) := d in\n   uint256_of_yul_value v.\n\nLemma bool_eq_via_uint256 {C: VyperConfig}\n                          (a b: bool)\n                          (E: (if a then one256 else zero256)\n                               =\n                              (if b then one256 else zero256)):\n  a = b.\nProof.\nassert (E': Z_of_uint256 (if a then one256 else zero256) = Z_of_uint256 (if b then one256 else zero256))\n  by now rewrite E.\nunfold one256 in E'. unfold zero256 in E'.\ndestruct a, b; repeat rewrite uint256_ok in E'; now try discriminate.\nQed.\n\nLemma yul_value_eq_via_uint256 {C: VyperConfig}\n                               (t: yul_type)\n                               (a b: yul_value t)\n                               (E: uint256_of_yul_value a = uint256_of_yul_value b):\n  a = b.\nProof.\nunfold uint256_of_yul_value in E.\ndestruct a, b, t; try discriminate; [| apply bool_eq_via_uint256 in E ];\n  subst; f_equal; apply Eqdep_dec.eq_proofs_unicity; decide equality.\nQed.\n\nDefinition string_of_type (t: yul_type)\n:= match t with\n   | BoolType => \"bool\"%string\n   | IntType size signed => String (if signed then \"s\"%char else \"u\"%char) (string_of_int_size size)\n   end.\n\nExample string_of_u256: string_of_type U256 = \"u256\"%string. Proof. trivial. Qed.\n\nDefinition type_of_string (s: string)\n: option yul_type\n:= match s with\n   | String \"s\"%char size =>\n        match int_size_of_string size with\n        | Some s => Some (IntType s true)\n        | None => None\n        end\n   | String \"u\"%char size =>\n        match int_size_of_string size with\n        | Some s => Some (IntType s false)\n        | None => None\n        end\n   | \"bool\"%string => Some BoolType\n   | _ => None\n   end.\n\nLemma type_of_string_of_type (t: yul_type):\n  type_of_string (string_of_type t) = Some t.\nProof.\ndestruct t as [|size]. { trivial. }\nnow destruct size, signed.\nQed.\n\n\nLocal Lemma int_zero_value_helper {C: VyperConfig} (size: int_size) (signed: bool):\n   match IntType size signed with\n   | BoolType => false\n   | IntType size true =>\n       let x := uint256_to_Z_as_signed zero256 in\n       ((sint_min size <=? x)%Z && (x <=? sint_max size)%Z)%bool\n   | IntType size false =>\n       let x := Z_of_uint256 zero256 in ((0 <=? x)%Z && (x <=? uint_max size)%Z)%bool\n   end = true.\nProof.\ncbn. unfold zero256. unfold uint256_to_Z_as_signed.\nrewrite uint256_ok. cbn.\nnow destruct signed, size.\nQed.\n\nDefinition int_zero_value {C: VyperConfig} (size: int_size) (signed: bool)\n: yul_value (IntType size signed)\n:= NumberValue (IntType size signed) zero256 (int_zero_value_helper size signed).\n\n\nDefinition zero_value {C: VyperConfig} (t: yul_type)\n: yul_value t\n:= match t with\n   | BoolType => yul_false\n   | IntType size signed => int_zero_value size signed\n   end.\n\nLemma zero_value_ok {C: VyperConfig} (t: yul_type):\n  Z_of_uint256 (uint256_of_yul_value (zero_value t)) = 0%Z.\nProof.\ndestruct t; cbn; unfold zero256; rewrite uint256_ok; trivial.\nQed.", "meta": {"author": "formalize", "repo": "coq-vyper", "sha": "8996c1534b9d56696f92b60031ff1523b3593690", "save_path": "github-repos/coq/formalize-coq-vyper", "path": "github-repos/coq/formalize-coq-vyper/coq-vyper-8996c1534b9d56696f92b60031ff1523b3593690/L50/Types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6610599474155011}}
{"text": "Require Export Arith.\nRequire Export ArithRing.\nRequire Export Wf_nat.\nAdd LoadPath \"../../progav/SRC/\".\n(* The preliminary theorems are already in the exercise fib_positive. *)\nRequire Export fib_positive.\n \nTheorem div2_rec:\n forall (P : nat ->  Set),\n P 0 -> P 1 -> (forall n, P n ->  P (S (S n))) -> forall (n : nat),  P n.\nProof.\nintros P H0 H1 Hrec n; assert (P n * P (S n))%type.\nelim n; intuition.\nintuition.\nQed.\n \nTheorem div2_spec:\n forall n,  ({x : nat | 2 * x = n}) + ({x : nat | 2 * x + 1 = n}).\nintros n; elim n  using div2_rec.\nleft; exists 0; trivial.\nright; exists 0; trivial.\nintros p [[x Heq]|[x Heq]].\nleft; exists (S x); rewrite <- Heq; ring.\nright; exists (S x); rewrite <- Heq; ring.\nQed.\n \nTheorem half_smaller0: forall n x, 2 * x = S n ->  (x < S n).\nProof.\nintros; omega.\nQed.\n \nTheorem half_smaller1: forall n x, 2 * x + 1 = n ->  (x < n).\nProof.\nintros; omega.\nQed.\n \nDefinition fib_log_F:\n forall (x : nat),\n (forall (y : nat),\n  y < x ->  ({u : nat & {v : nat | u = fib y /\\ v = fib (S y)}})) ->\n  ({u : nat & {v : nat | u = fib x /\\ v = fib (S x)}}).\nintros [|x'].\nintros _.\nexists 1; exists 1; auto.\ndestruct (div2_spec (S x')) as [[half_sx' Heq]|[half_x' Heq]]; intros fib_log.\ndestruct (fib_log half_sx' (half_smaller0 _ _ Heq)) as [u [v [Heq1 Heq2]]].\nrewrite <- Heq.\nexists (u * u + (v - u) * (v - u)).\nexists ((2 * u) * v - u * u).\nrewrite Heq1; rewrite Heq2.\nsplit.\nreplace (S half_sx') with (half_sx' + 1).\nrewrite <- fib_2n.\ntrivial.\nring.\nreplace (S half_sx') with (half_sx' + 1).\nrewrite <- fib_2n_plus_1.\nreplace (2 * half_sx' + 1) with (S (2 * half_sx')).\ntrivial.\nring.\nring.\ndestruct (fib_log half_x' (half_smaller1 _ _ Heq)) as [u [v [Heq1 Heq2]]].\nrewrite <- Heq.\nexists ((2 * u) * v - u * u).\nexists (v * v + u * u).\nrewrite Heq1; rewrite Heq2.\nsplit.\nreplace (S half_x') with (half_x' + 1).\nrewrite <- fib_2n_plus_1.\ntrivial.\nring.\nreplace (S half_x') with (half_x' + 1).\nrewrite <- fib_2n_plus_2.\ntrivial.\nring.\nQed.\n \nDefinition fib_log :\n  forall (x : nat),  ({u : nat & {v : nat | u = fib x /\\ v = fib (S x)}}) :=\n   well_founded_induction\n    lt_wf (fun x => {u : nat & {v : nat | u = fib x /\\ v = fib (S x)}})\n    fib_log_F.\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/fib_log.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6610599449006013}}
{"text": "(* \n  Autor(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) TU Dortmund University, Dortmund, Germany\n*)\n\n(* \n  Problem(s):\n    Two-counter Machine Halting (CM2_HALT)\n    Two-counter Machine Reversibility (CM2_REV)\n    Reversible Two-counter Machine Halting (CM2_REV_HALT)\n    Two-counter Machine Uniform Boundedness (CM2_UBOUNDED)\n    Two-counter Machine Uniform Mortality (CM2_UMORTAL)\n*)\n\nRequire Import List ssrfun.\n\n(* a configuration consists of a state and two counter values *)\nDefinition Config : Set := nat * (nat * nat).\n\n(* accessors for state, value1, value2 of configurations *)\nDefinition state (x: Config) : nat := fst x.\nArguments state !x /.\nDefinition value1 (x: Config) : nat := fst (snd x).\nArguments value1 !x /.\nDefinition value2 (x: Config) : nat := snd (snd x).\nArguments value2 !x /.\n\n(* the instruction inc true maps \n      a configuration (p, (v1, v2)) to (1+p, (v1, 1+v2))\n    the instruction inc false maps \n      a configuration (p, (v1, v2)) (1+p, (1+v1, v2))\n    an instruction dec true q maps\n      a configuration (p, (v1, 0)) to (1+p, (v1, 0)) \n      a configuration (p, (v1, 1+v2)) to (q, (v1, v2)) \n    an instruction dec false q maps\n      a configuration (p, (0, v2)) to (1+p, (0, v2)) \n      a configuration (p, (1+v1, v2)) to (q, (v1, v2)) *)\nInductive Instruction : Set := \n  | inc : bool -> Instruction\n  | dec : bool -> nat -> Instruction.\n\n(* a two-counter machine is a list of instructions *)\nDefinition Cm2 : Set := list Instruction.\n\n(* partial two-counter machine step function *)\nDefinition step (M: Cm2) (x: Config) : option Config :=\n  match nth_error M (state x) with\n  | None => None (* halting configuration *)\n  | Some (inc b) => (* increase counter, goto next state*)\n    Some (1 + (state x), ((if b then 0 else 1) + (value1 x), (if b then 1 else 0) + (value2 x)))\n  | Some (dec b y) => (* decrease counter, if successful goto state y *)\n    Some (\n      if b then \n        match value2 x with\n        | 0 => (1 + (state x), (value1 x, 0))\n        | S n => (y, (value1 x, n))\n        end\n      else\n        match value1 x with\n        | 0 => (1 + (state x), (0, value2 x))\n        | S n => (y, (n, value2 x))\n        end)\n  end.\n\n(* iterated partial two-counter machine step function *)\nDefinition steps (M: Cm2) (k: nat) (x: Config) : option Config :=\n  Nat.iter k (obind (step M)) (Some x).\n\n(* two-counter machine configuration reachability *)\nDefinition reaches (M: Cm2) (x y: Config) :=\n  exists k, steps M k x = Some y.\n\n(* does M eventually terminate starting from the configuration x? *)\nDefinition terminating (M: Cm2) (x: Config) :=\n  exists k, steps M k x = None.\n\n(* injectivity of the step function *)\nDefinition reversible (M : Cm2) : Prop := \n  forall x y z, step M x = Some z -> step M y = Some z -> x = y.\n\n(* k bounds the number of reachable configurations from x *)\nDefinition bounded (M: Cm2) (k: nat) (x: Config) : Prop := \n  exists (L: list Config), (length L <= k) /\\\n    (forall (y: Config), reaches M x y -> In y L).\n\n(* uniform bound for number of reachable configurations *)\nDefinition uniformly_bounded (M: Cm2) : Prop :=\n  exists k, forall x, bounded M k x.\n\n(* k bounds the number of steps in a terminating run from x *)\nDefinition mortal (M: Cm2) (k: nat) (x: Config) : Prop := \n  steps M k x = None.\n\n(* uniform bound for number of steps until termination *)\nDefinition uniformly_mortal (M: Cm2) : Prop :=\n  exists k, forall x, mortal M k x.\n\n(* Two-counter Machine Halting:\n   Given a two-counter machine M,\n   does a run in M starting from configuration (0, (0, 0)) eventually halt? *)\nDefinition CM2_HALT : Cm2 -> Prop :=\n  fun M => terminating M (0, (0, 0)).\n\n(* Two-counter Machine Reversibility:\n   Given a two-counter machine M,\n   is the step function of M injective? *)\nDefinition CM2_REV : Cm2 -> Prop :=\n  fun M => reversible M.\n\n(* Reversible Two-counter Machine Halting:\n   Given a reversible two-counter machine M and a configucation x, \n   does a run in M starting from x eventually halt? *)\nDefinition CM2_REV_HALT : { M: Cm2 | reversible M } * Config -> Prop :=\n  fun '((exist _ M _), x) => terminating M x.\n\n(* Two-counter Machine Uniform Boundedness:\n   Given a two-counter machine M,\n   is there a uniform bound n,\n   such that for any configuration x,\n   the number of reacheable configurations from x is bounded by n? *)\nDefinition CM2_UBOUNDED : Cm2 -> Prop :=\n  fun M => uniformly_bounded M.\n\n(* Two-counter Machine Uniform Mortality:\n   Given a two-counter machine M,\n   is there a uniform bound n,\n   such that for any configuration x,\n   a run in M starting from x halts after at most n steps? *)\nDefinition CM2_UMORTAL : Cm2 -> Prop :=\n  fun M => uniformly_mortal M.\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/CM2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6610599401288789}}
{"text": "Require Export ZArith.\nRequire Export List.\nRequire Export Arith.\nRequire Export Omega.\nRequire Export Zwf.\nRequire Export Relations.\nRequire Export Inverse_Image.\nRequire Export Transitive_Closure.\n\nLtac caseEq f := generalize (refl_equal f); pattern f at -1; case f.\n\n\nFixpoint bdiv_aux (b m n:nat){struct b} : nat*nat :=\n  match b with\n  | O => (0, 0)\n  | S b' =>\n      match le_gt_dec n m with\n      | left H =>\n          match bdiv_aux b' (m-n) n with\n          | pair q r => (S q, r)\n          end\n      | right H => (0, m)\n      end\n  end.\n\nTheorem bdiv_aux_correct1 :\n forall b m n:nat, m <= b -> 0 < n -> \n m = fst (bdiv_aux b m n) * n + snd (bdiv_aux b m n).\nProof.\n intros b; elim b; simpl.\n intros m n Hle; inversion Hle; auto.\n intros b' Hrec m n Hleb Hlt; case (le_gt_dec n m); simpl; auto.\n intros Hle; generalize (Hrec (m-n) n);\n  case (bdiv_aux b' (m-n) n); simpl; intros q r Hrec'.\n rewrite <- plus_assoc; rewrite <- Hrec'; auto with arith.\n omega. \nQed.\n\nHypothesis bdiv_aux_correct2 :\n forall b m n:nat, m <= b -> 0 < n -> snd (bdiv_aux b m n) < n.\n\nDefinition bdiv :\n  forall m n:nat, 0 < n -> {q:nat &{r:nat | m = q*n+r /\\ r < n}}.\n refine\n  (fun (m n:nat)(h:0 < n) =>\n    let p := bdiv_aux m m n in\n    existS (fun q:nat => {r : nat | m = q*n+r /\\ r < n})\n      (fst p)(exist _ (snd p) _)).\n unfold p; split.\n apply bdiv_aux_correct1; auto.\n intros; eapply bdiv_aux_correct2; eauto.\nDefined.\n\nTime Eval lazy beta iota zeta delta in (bdiv_aux 2000 2000 31).\n\nTime Eval lazy beta delta iota zeta in\n  match bdiv 2000 31 (lt_O_Sn 30) with\n    existS q (exist r h) => (q,r)\n  end.\n\nRequire Import Lt.\n\nTheorem lt_Acc : forall n:nat, Acc lt n.\nProof.\n induction n.\n split; intros p H; inversion H.\n split. \n intros y H0.\n case (le_lt_or_eq _ _ H0).\n intro; apply Acc_inv with n; auto with arith.\n intro e; injection e; intro e1; rewrite e1; assumption. \nQed.\n\nTheorem lt_wf : well_founded lt.\nProof.\n exact lt_Acc.\nQed.\n\nInductive Rpos_div2 : positive->positive->Prop :=\n  Rpos1 : forall x:positive, Rpos_div2 x (xO x)\n| Rpos2 : forall x:positive, Rpos_div2 x (xI x).\nTheorem Rpos_div2_wf : well_founded Rpos_div2.\nProof.\n unfold well_founded; intros a; elim a;\n  (intros; apply Acc_intro; intros y Hr; inversion Hr; auto).\nQed.\n\nDefinition div_type (m:nat) :=\n  forall n:nat, 0 < n -> {q:nat &{r:nat | m = q*n+r /\\ r < n}}.\n\nDefinition div_type' (m n q:nat) :=\n  {r:nat | m = q*n+r /\\ r < n}.\n\nDefinition div_type'' (m n q r:nat) := m = q*n+r /\\ r < n.\n\nDefinition div_F :\n  forall x:nat, (forall y:nat, y < x -> div_type y) -> div_type x.\n unfold div_type at 2.\n refine\n  (fun m div_rec n Hlt =>\n     match le_gt_dec n m with\n     | left H_n_le_m =>\n         match div_rec (m-n) _ n _ with\n         | existS q (exist r H_spec) =>\n             existS (div_type' m n)(S q)\n               (exist (div_type'' m n (S q)) r _)\n         end\n     | right H_n_gt_m =>\n         existS (div_type' m n) 0\n            (exist (div_type'' m n 0) m _)\n     end); unfold div_type''; auto with arith.\n  elim H_spec; intros H1 H2; split; auto.\n rewrite (le_plus_minus n m H_n_le_m); rewrite H1; ring.\nQed.\n\nDefinition div :\n  forall m n:nat, 0 < n -> {q:nat &{r:nat | m = q*n+r /\\ r < n}} :=\n  well_founded_induction lt_wf div_type div_F.\n\n\nParameter div2 : nat->nat.\nAxiom div2_le : forall n:nat, div2 n <= n.\nHypothesis double_div2_le : forall x:nat, div2 x + div2 x <= x.\n\nHypothesis f_lemma :\n  forall x v:nat, v <= div2 x -> div2 x + v <= x.\n\nHint Resolve div2_le f_lemma double_div2_le.\n\nDefinition nested_F :\n  forall x:nat, (forall y:nat, y < x->{v:nat|v <= y})->{v:nat | v <= x}.\nrefine\n  (fun x => match x return (forall y:nat, y < x ->{v:nat | v <= y})->\n                          {v:nat | v <= x} with\n              O => fun f => exist _ 0 _\n            | S x' => \n              fun f => match f (div2 x') _ with\n                        exist v H1 =>\n                        match f (div2 x' + v) _ with\n                          exist v1 H2 => exist _ (S v1) _\n                        end\n                      end\n            end); auto with arith.\n  apply le_n_S.\n  eauto with arith.\nDefined.\n\nDefinition nested_f :=\n  well_founded_induction\n    lt_wf (fun x:nat => {v:nat | v <= x}) nested_F.\n    \n\n\nDefinition div_it_F (f:nat->nat->nat*nat)(m n:nat) :=\n  match le_gt_dec n m with\n  | left _ => let (q, r) := f (m-n) n in (S q, r)\n  | right _ => (0, m)\n  end.\n\nFixpoint iter (A:Set)(n:nat)(F:A->A)(g:A){struct n} : A :=\n  match n with O => g | S p => F (iter A p F g) end.\n\nImplicit Arguments iter [A].\n\nDefinition div_it_terminates :\n  forall n m:nat, 0 < m ->\n    {v:nat*nat |\n     exists p:nat,\n      (forall k:nat, p < k -> forall g:nat->nat->nat*nat,\n           iter k div_it_F g n m = v)}.\n intros n; elim n using (well_founded_induction lt_wf).\n intros n' Hrec m Hlt.\n caseEq (le_gt_dec m n'); intros H Heq_test.\n case Hrec with (y := n'-m)(2 := Hlt); auto with arith.\n intros [q r]; intros Hex; exists (S q, r).\n elim Hex; intros p Heq.\n exists (S p).\n intros k.\n case k.\n intros; elim (lt_n_O (S p)); auto.\n intros k' Hplt g; simpl; unfold div_it_F at 1.\n rewrite Heq; auto with arith.\n rewrite Heq_test; auto.\n exists (0, n'); exists 0; intros k; case k.\n intros; elim (lt_irrefl 0); auto.\n intros k' Hltp g; simpl; unfold div_it_F at 1.\n rewrite Heq_test; auto.\nDefined.\n\nDefinition div_it (n m:nat)(H:0 < m) : nat*nat :=\n  let (v, _) := div_it_terminates n m H in v.\n\nDefinition max (m n:nat) : nat :=\n  match le_gt_dec m n with left _ => n | right _ => m end.\n\nTheorem max1_correct : forall n m:nat, n <= max n m.\n intros n m; unfold max; case (le_gt_dec n m); auto with arith.\nQed.\n\nTheorem max2_correct : forall n m:nat, m <= max n m.\n intros n m; unfold max; case (le_gt_dec n m); auto with arith.\nQed.\n\nHint Resolve max1_correct max2_correct : arith.\n\nTheorem div_it_fix_eqn :\n forall (n m:nat)(h:(0 < m)),\n   div_it n m h =\n   match le_gt_dec m n with\n   | left H => let (q,r) := div_it (n-m) m h in (S q, r)\n   | right H => (0, n)\n   end.\nProof.\n intros n m h.\n unfold div_it; case (div_it_terminates n m h).\n intros v Hex1; case (div_it_terminates (n-m) m h).\n intros v' Hex2.\n elim Hex2; elim Hex1; intros p Heq1 p' Heq2.\n rewrite <- Heq1 with\n     (k := S (S (max p p')))(g := fun x y:nat => v).\n rewrite <- Heq2 with (k := S (max p p'))(g := fun x y:nat => v).\n reflexivity.\n eauto with arith.\n eauto with arith.\nQed.\n\nTheorem div_it_correct1 :\n forall (m n:nat)(h:0 < n),\n   m = fst (div_it m n h) * n + snd (div_it m n h).\nProof.\n intros m; elim m using (well_founded_ind lt_wf).\n intros m' Hrec n h; rewrite div_it_fix_eqn.\n case (le_gt_dec n m'); intros H; trivial.\n pattern m' at 1; rewrite (le_plus_minus n m'); auto.\n pattern (m'-n) at 1.\n rewrite Hrec with (m'-n) n h; auto with arith.\n case (div_it (m'-n) n h); simpl; auto with arith.\nQed.\n\nReset div2.\n\nFixpoint div2 (n:nat) : nat :=\n  match n with S (S p) => S (div2 p) | _ => 0 end.\n\nInductive log_domain : nat->Prop :=\n  log_domain_1 : log_domain 1\n| log_domain_2 :\n    forall p:nat, log_domain (S (div2 p))-> log_domain (S (S p)).\n\nTheorem log_domain_non_O : forall x:nat, log_domain x -> x <> 0.\nProof.\n intros x H; case H; intros; discriminate.\nQed.\n\nTheorem log_domain_inv :\n forall x p:nat, log_domain x -> x = S (S p)-> log_domain (S (div2 p)).\nProof.\n intros x p H; case H; try (intros H'; discriminate H').\n intros p' H1 H2; injection H2; intros H3; \n rewrite <- H3; assumption.\nDefined.\n\nFixpoint log (x:nat)(h:log_domain x){struct h} : nat :=\n  match x as y return x = y -> nat with\n  | 0 => fun h' => False_rec nat (log_domain_non_O x h h')\n  | S 0 => fun h' => 0\n  | S (S p) => \n       fun h' => S (log (S (div2 p))(log_domain_inv x p h h'))\n  end (refl_equal x).\n\nInductive log2_domain : nat->Prop :=\n  l21 : log2_domain 1\n| l22 : forall x:nat,\n        x <> 1 -> x <> 0 -> log2_domain (div2 x) -> log2_domain x.\n\nHypothesis log2_domain_non_zero : forall x:nat, log2_domain x -> x <> 0.\n\nTheorem log2_domain_invert :\n forall x:nat, log2_domain x -> x <> 0 -> x <> 1 -> log2_domain (div2 x).\nProof.\n intros x h; case h.\n intros h1 h2; elim h2; reflexivity.\n intros; assumption.\nDefined. \n\nFixpoint log2 (x:nat)(h:log2_domain x){struct h} : nat :=\n  match eq_nat_dec x 0 with\n  | left heq => False_rec nat (log2_domain_non_zero x h heq)\n  | right hneq =>\n      match eq_nat_dec x 1 with\n      | left heq1 => 0\n      | right hneq1 =>\n          S (log2 (div2 x)(log2_domain_invert x h hneq hneq1))\n      end\n  end.\nScheme log_domain_ind2 := Induction for log_domain Sort Prop.\n\nFixpoint two_power (n:nat) : nat :=\n  match n with\n  | O => 1\n  | S p => 2 * two_power p\n  end.\n\nSection proof_on_log.\n\n Hypothesis mult2_div2_le : forall x:nat, 2 * div2 x <= x.\n  \nTheorem pow_log_le :\n forall (x:nat)(h:log_domain x), two_power (log x h) <= x.\nProof.\n intros x h; elim h using log_domain_ind2.\n simpl; auto with arith.\n\n intros p l Hle.\n lazy beta iota zeta delta [two_power log_domain_inv log];\n  fold log two_power.\n apply le_trans with (2 * S (div2 p)); auto with arith.\n exact (mult2_div2_le (S (S p))).\nQed.\n\nEnd proof_on_log.\n\nSection little_semantics.\nVariables Var aExp bExp : Set.\nInductive inst : Set :=\n  | Skip : inst\n  | Assign : Var->aExp->inst\n  | Sequence : inst->inst->inst\n  | WhileDo : bExp->inst->inst.\n\nVariables (state : Set)(evalA : state->aExp->option Z)\n  (evalB : state -> bExp -> option bool)\n  (exec : state->inst->state->Prop).\nOpen Scope Z_scope.\n\nDefinition extract_option (A:Set)(x:option A)(def:A) : A :=\n  match x with\n  | None => def\n  | Some v => v\n  end.\nImplicit Arguments extract_option [A].\nImplicit Arguments Some [A].\n\nInductive forLoops : inst->Prop :=\n  | aForLoop :\n      forall (e:bExp)(i:inst)(variant:aExp),\n        (forall s s':state,\n           evalB s e = Some true -> exec s i s' ->\n           Zwf 0 (extract_option (evalA s' variant) 0)\n             (extract_option (evalA s variant) 0))->\n        forLoops i -> forLoops (WhileDo e i)\n  | assignFor : forall (v:Var)(e:aExp), forLoops (Assign v e)\n  | skipFor : forLoops Skip\n  | sequenceFor :\n      forall i1 i2:inst,\n        forLoops i1 -> forLoops i2 -> forLoops (Sequence i1 i2).\n\n\nEnd little_semantics.\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/chap15.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6610599207839118}}
{"text": "From mathcomp Require Import ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nRequire Import function.\n\nSection FunctionTheories.\n\n  Variable U:Type.\n  Variable F: U -> U.\n  Variables A B: Ensemble U.\n\n  Theorem union_function_domain:\n    forall (f:Ensemble (Ensemble (Ensemble U))) (X Y:Ensemble U),\n      (f ≔ F ⊦ A ⟼ B) -> f '' (X ∪ Y) = (f '' X) ∪ (f '' Y).\n  Proof.\n    move => f X Y [Hf HfS].\n    move: union_of_image_of_correspondence_eq => H.\n    apply (H U (fun x y:U => y = F x) A B X Y f).\n    apply Hf.\n  Qed.\n\n  Theorem union_inversion_mapping_domain:\n    forall (f:Ensemble (Ensemble (Ensemble U))) (X Y:Ensemble U),\n      (f ≔ F ⊦ A ⟼ B) -> f^-1 '' (X ∪ Y) = (f^-1 '' X) ∪ (f^-1 '' Y).\n  Proof.\n    move => f X Y H.\n    inversion H as [Hf HfS].\n    apply /Extensionality_Ensembles.\n    +split => x H0.\n     inversion H0 as [x0 [y0 H1]].\n     rewrite -H2 in H1.\n     inversion H1.\n     inversion H3 as [y0' | y0'].\n     inversion H4 as [x1 y1].\n     ++left.\n       split.\n       exists y0.\n       split.\n       apply H5.\n       rewrite -H2.\n       rewrite -H8.\n       split.\n       apply H7.\n     ++right.\n       split.\n       exists y0.\n       split.\n       apply H5.\n       rewrite -H2.\n       apply H4.\n    +split.\n     ++inversion H0.\n       inversion H1 as [x0'].\n       inversion H3 as [y].\n       inversion H5.\n       inversion H7 as [x1 y1].\n       exists y.\n       split.\n       left.\n       apply H6.\n       apply H7.\n     ++inversion H1 as [x0'].\n       inversion H3 as [y].\n       inversion H5.\n       exists y.\n       split.\n       right.\n       apply H6.\n       apply H7.\n  Qed.\n\n  Theorem intersction_inversion_mapping_domain:\n    forall (f:Ensemble (Ensemble (Ensemble U))) (X Y:Ensemble U),\n      (f ≔ F ⊦ A ⟼ B) -> f^-1 '' (X ∩ Y) = (f^-1 '' X) ∩ (f^-1 '' Y).\n  Proof.\n    move => f X Y H.\n    unfold Mapping in H.\n    inversion H as [Hf HfS].\n    rewrite Hf.\n    apply /Extensionality_Ensembles.\n    split => x H0.\n    +inversion H0 as [x'].\n     inversion H1 as [y].\n     inversion H3.\n     inversion H4 as [y'].\n     split; split; exists y; split.\n     apply H6.\n     apply H5.\n     apply H7.\n     apply H5.\n    +inversion H0 as [x'].\n     inversion H1 as [x0].\n     inversion H4 as [y].\n     inversion H6.\n     inversion H2 as [x0'].\n     inversion H9 as [y'].\n     inversion H11.\n     inversion H8 as [x2 y2].\n     inversion H14.\n     inversion H13 as [x3 y3].\n     inversion H18 as [x3' y3'].\n     inversion H17.\n     inversion H20.\n     apply ordered_pair_iff in H15.\n     inversion H15.\n     apply ordered_pair_iff in H16.\n     inversion H16.\n     apply ordered_pair_iff in H19.\n     inversion H19.\n     apply ordered_pair_iff in H21.\n     inversion H21.\n     rewrite H28 in H22.\n     rewrite H32 in H24.\n     rewrite H27 in H22.\n     rewrite H31 in H24.\n     rewrite -H22 in H24.\n     rewrite H33 in H24.\n     rewrite H30 in H24.\n     rewrite H29 in H24.\n     rewrite H26 in H24.\n     rewrite H24 in H12.\n     split.\n     exists y.\n     split.\n     split.\n     apply H7.\n     apply H12.\n     rewrite H24 in H13.\n     apply H13.\n  Qed.\n\n  Theorem included_image:\n    forall (f:Ensemble (Ensemble (Ensemble U))) (A':Ensemble U),\n      (f ≔ F ⊦ A ⟼ B) /\\ A' ⊂ A -> f '' A' ⊂ f '' A.\n  Proof.\n    move: included_domain_to_included_image => H.\n    move => f A'.\n    case => [[Hf HfS] H0].\n    apply (H U (fun x y:U => y = F x) A B f A' A).\n    apply Hf.\n    split; done.\n  Qed.\n\n  Theorem if_mapping_is_injection_then_inverse_mapping_is_unique:\n    forall (f:Ensemble (Ensemble (Ensemble U))),\n      f ≔ F ⊦ A ⟼ B /\\ Injection f -> forall (y x0 x1:U), (|y, x0|) ∈ f^-1 /\\ (|y, x1|) ∈ f^-1 -> x0 = x1.\n  Proof.\n    move => f.\n    case => [H HIf].\n    move => y x0 x1.\n    case => H0 H1.\n    inversion H0.\n    inversion H1.\n    apply ordered_pair_swap in H2.\n    apply ordered_pair_swap in H4.\n    rewrite H2 in H3.\n    rewrite H4 in H5.\n    apply (HIf x0 x1 y).\n    split.\n    apply H3.\n    apply H5.\n  Qed.\n\n  Theorem if_mapping_is_bijection_then_inverse_mapping_is_bijection:\n    forall (f:Ensemble (Ensemble (Ensemble U))),\n      f ≔ F ⊦ A ⟼ B /\\ Bijection f B -> 𝕯( f^-1 ) = B /\\ 𝕽( f^-1 ) = A /\\ Bijection (f^-1) A.\n  Proof.\n    move => f.\n    case => Hf0 [ HSfI HSfB ].\n    inversion Hf0 as [Hf HfS].\n    +split.\n     apply /Extensionality_Ensembles.\n     ++split => y.\n       move => H.\n       inversion H as [y' ].\n       inversion H0 as [y''].\n       inversion H2 as [x].\n       inversion H4.\n       rewrite Hf in H6.\n       inversion H6.\n       inversion H8.\n       rewrite H7 in H10.\n       apply ordered_pair_swap in H5.\n       rewrite H5 in H10.\n       apply ordered_pair_in_direct_product_iff_and in H10.\n       inversion H10.\n       apply H12.\n     ++move => HB.\n       split.\n       split.\n       +++suff: exists x:U, (|x,y|) ∈ f.\n          move => H0.\n          inversion H0.\n          exists x.\n          split.\n          apply H.\n          apply HSfB.\n     --apply HB.\n    +split.\n     apply /Extensionality_Ensembles.\n     split => x.\n    +move => HyRfi.\n     inversion HyRfi as [x0].\n     inversion H as [y0].\n     inversion H1 as [y0'].\n     inversion H3 as [x1 y1].\n     apply ordered_pair_swap in H5.\n     rewrite H5 in H4.\n     rewrite Hf in H4.\n     inversion H4.\n     inversion H7.\n     rewrite H6 in H9.\n     apply ordered_pair_in_direct_product_iff_and in H9.\n     inversion H9.\n     apply H10.\n    +move => HA.\n     split.\n     split.\n     ++suff: exists y:U, (|x,y|) ∈ f.\n       move => H0.\n       inversion H0 as [y].\n       exists y.\n       split.\n       apply H.\n    -apply HfS.\n     apply HA.\n     split.\n     move => y y' x.\n     case => H0 H1.\n     inversion H0.\n     inversion H1.\n     apply ordered_pair_swap in H.\n     apply ordered_pair_swap in H3.\n     rewrite Hf in H2.\n     rewrite Hf in H4.\n     inversion H2.\n     inversion H6.\n     inversion H4.\n     inversion H10.\n     rewrite H in H5.\n     apply ordered_pair_iff in H.\n     inversion H.\n     apply ordered_pair_iff in H3.\n     inversion H3.\n     apply ordered_pair_iff in H5.\n     inversion H5.\n     apply ordered_pair_iff in H9.\n     inversion H9.\n     rewrite -H18.\n     rewrite H7.\n     rewrite H17.\n     rewrite -H16.\n     rewrite -H20.\n     rewrite H11.\n     rewrite H19.\n     rewrite H15.\n     reflexivity.\n    +move => x HA.\n     ++suff: exists y:U, (|x,y|) ∈ f.\n       move => H0.\n       inversion H0 as [y].\n       exists y.\n       split.\n       apply H.\n    -apply HfS.\n     apply HA.\n  Qed.\n\nEnd FunctionTheories.\n\nRequire Export function.", "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/function_theories.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6610154408323938}}
{"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.\n\nFrom Undecidability.Shared.Libs.DLW \n  Require Import utils_tac utils_nat pos vec.\n\nFrom Undecidability.MuRec \n  Require Import recalg ra_utils recomp ra_recomp.\n\nFrom Undecidability.H10.Dio \n  Require Import dio_single.\n\nSet Implicit Arguments.\n\nSet Default Proof Using \"Type\".\n\nLocal Notation \"'⟦' f '⟧'\" := (@ra_rel _ f) (at level 0).\n\nSection dio_poly.\n\n  Variable (n m : nat).\n\n  Fixpoint ra_dio_poly (p : dio_polynomial (pos n) (pos m)) : recalg (n+m).\n  Proof.\n    destruct p as [ c | i | x | [] p q ].\n    + apply ra_cst_n, c.\n    + apply ra_proj, pos_left, i. \n    + apply ra_proj, pos_right, x.\n    + apply ra_comp with (1 := ra_plus), (ra_dio_poly p##ra_dio_poly q##vec_nil).\n    + apply ra_comp with (1 := ra_mult), (ra_dio_poly p##ra_dio_poly q##vec_nil).\n  Defined.\n\n  Fact ra_dio_poly_prim p : prim_rec (ra_dio_poly p).\n  Proof.\n    induction p as [ | | | [] ]; simpl; repeat (split; auto);\n      intros j; analyse pos j; simpl; auto.\n  Qed.\n\n  Opaque ra_cst_n ra_plus ra_mult ra_inject ra_project ra_eq.\n\n  Section ra_dio_poly_eval.\n\n    Variable (v : vec nat (n+m)).\n\n    Notation φ := (fun i => vec_pos v (pos_left _ i)).\n    Notation ν := (fun i => vec_pos v (pos_right _ i)).\n\n    Fact ra_dio_poly_val p : ⟦ra_dio_poly p⟧ v (dp_eval φ ν p).\n    Proof.\n      induction p as [ c | i | x | [] p Hp q Hq ]; simpl.\n      + apply ra_cst_n_val.\n      + cbv; auto.\n      + cbv; auto.\n      + exists (dp_eval φ ν p ## dp_eval φ ν q ## vec_nil); split.\n        * apply ra_plus_val.\n        * intros j; analyse pos j; simpl; auto.\n      + exists (dp_eval φ ν p ## dp_eval φ ν q ## vec_nil); split.\n        * apply ra_mult_val.\n        * intros j; analyse pos j; simpl; auto.\n    Qed.\n\n    Variable (p q : dio_polynomial (pos n) (pos m)).\n\n    Definition ra_dio_poly_eq : recalg (n+m).\n    Proof using p q.\n      apply ra_comp with (1 := ra_eq).\n      refine (_##_##vec_nil); apply ra_dio_poly.\n      + exact p.\n      + exact q.\n    Defined.\n\n    Hint Resolve ra_dio_poly_prim : core.\n  \n    Fact ra_dio_poly_eq_prim : prim_rec ra_dio_poly_eq.\n    Proof.\n      simpl; split; auto.\n      intros j; analyse pos j; auto.\n    Qed. \n\n    Fact ra_dio_poly_eq_val : { e | ⟦ra_dio_poly_eq⟧ v e /\\ (e = 0 <-> dp_eval φ ν p = dp_eval φ ν q) }.\n    Proof.\n      destruct ra_eq_rel with (v := dp_eval φ ν p ## dp_eval φ ν q ## vec_nil) as (e & H1 & H2); simpl in H2.\n      exists e; split; auto.\n      simpl.\n      exists (dp_eval φ ν p ## dp_eval φ ν q ## vec_nil); split; auto.\n      intros i; analyse pos i; simpl; apply ra_dio_poly_val.\n    Qed.\n\n    Opaque ra_dio_poly_eq.\n\n    Hint Resolve ra_dio_poly_eq_prim : core.\n\n    Definition ra_dio_poly_test : recalg (S m).\n    Proof using p q.\n      apply ra_comp with (1 := ra_dio_poly_eq).\n      apply vec_set_pos; intros i.\n      destruct (pos_both _ _ i) as [ j | j ].\n      + apply ra_comp with (1 := ra_project j), (ra_proj pos0 ## vec_nil).\n      + apply ra_proj, pos_nxt, j.\n    Defined.\n\n    Fact ra_dio_poly_test_prim : prim_rec ra_dio_poly_test.\n    Proof.\n      simpl; split; auto.\n      intros i.\n      rewrite vec_pos_set.\n      destruct (pos_both n m i).\n      + simpl; split; auto.\n        intros j; analyse pos j; simpl; auto.\n      + simpl; auto.\n    Qed.\n\n    Fact ra_dio_poly_test_total : total ⟦ra_dio_poly_test⟧.\n    Proof. apply prim_rec_tot, ra_dio_poly_test_prim. Qed.\n\n  End ra_dio_poly_eval.\n\n  Notation φ := (fun x w i => vec_pos (vec_app (project n x) w) (pos_left _ i)).\n  Notation ν := (fun x w i => vec_pos (vec_app (project n x) w) (pos_right _ i)).\n\n  Variable (p q : dio_polynomial (pos n) (pos m)).\n\n  Fact ra_dio_poly_test_val x w : { e | ⟦ra_dio_poly_test p q⟧ (x##w) e /\\ (e = 0 <-> dp_eval (φ x w) (ν x w) p \n                                                                                    = dp_eval (φ x w) (ν x w) q) }.\n  Proof.\n    destruct (ra_dio_poly_eq_val (vec_app (project n x) w) p q) as (e & H1 & H2).\n    exists e; split; auto.\n    exists (vec_app (project n x) w); split; auto.\n    intros i; repeat rewrite vec_pos_set.\n    generalize (pos_lr_both n m i). \n    destruct (pos_both n m i) as [ j | j ]; intros Hj; subst i; simpl.\n    * unfold vec_app; rewrite vec_pos_set, pos_both_left.\n      exists (x##vec_nil); split.\n      - apply ra_project_val.\n      - intros k; analyse pos k; simpl; cbv; auto.\n    * unfold vec_app; rewrite vec_pos_set, pos_both_right; reflexivity.\n  Qed.\n\n  Fact ra_dio_poly_test_rel v e : ⟦ra_dio_poly_test p q⟧ v e\n                               -> e = 0 <-> dp_eval (φ (vec_head v) (vec_tail v)) \n                                                    (ν (vec_head v) (vec_tail v)) p \n                                          = dp_eval (φ (vec_head v) (vec_tail v)) \n                                                    (ν (vec_head v) (vec_tail v)) q.\n  Proof.\n    vec split v with x; intros H; simpl vec_head; simpl vec_tail.\n    destruct (ra_dio_poly_test_val x v) as (e' & H1 & H2).\n    rewrite <- H2; clear H2.\n    generalize (ra_rel_fun _ _ _ _ H H1); intros []; tauto.\n  Qed.\n\n  Opaque ra_dio_poly_test.\n\n  Definition ra_dio_poly_find : recalg m.\n  Proof using p q. apply ra_min, (ra_dio_poly_test p q). Defined.\n\n  Lemma ra_dio_poly_find_rel w : (exists e, ⟦ra_dio_poly_find⟧ w e) <-> exists x, ⟦ra_dio_poly_test p q⟧ (x##w) 0.\n  Proof.\n    simpl; unfold s_min.\n    apply μ_min_of_total.\n    + intros ? ? ?; apply ra_rel_fun.\n    + intros x; destruct (ra_dio_poly_test_val x w) as (e & ? & _).\n      exists e; auto.\n  Qed.\n\n  (* ra_dio_poly_find terminates on w iff some solution of p(w,x1,...,xn) = q(w,x1,...,xn) exists \n\n      so termination of ra_dio_poly_find terminates on w simulates the existence of a solution\n      to a given diophantine equation *)\n\n  Theorem ra_dio_poly_find_spec w :  ex (⟦ra_dio_poly_find⟧ w) \n                                <-> exists v, dp_eval (vec_pos v) (vec_pos w) p \n                                            = dp_eval (vec_pos v) (vec_pos w) q.\n  Proof.\n    rewrite ra_dio_poly_find_rel; split.\n    + intros (x & Hx).\n      destruct (ra_dio_poly_test_val x w) as (e & H1 & H2).\n      generalize (ra_rel_fun _ _ _ _ H1 Hx); rewrite H2.\n      exists (project n x); auto.\n      eq goal H; f_equal; apply dp_eval_ext; intro; try rewrite vec_pos_app_left; auto;\n        rewrite vec_pos_app_right; auto.\n    + intros (v & Hv).\n      exists (inject v).\n      destruct (ra_dio_poly_test_val (inject v) w) as (e & H1 & H2).\n      rewrite project_inject in H2.\n      assert (e=0); try (subst; auto; fail).\n      apply H2.\n      eq goal Hv; f_equal; apply dp_eval_ext; intro; try rewrite vec_pos_app_left; auto;\n        rewrite vec_pos_app_right; auto.\n  Qed.\n\nEnd dio_poly.\n\nOpaque ra_dio_poly_find.\n\nSection dio_ra_enum.\n\n  (* Given p = q in dio_eq (pos 1) (pos m), given a total\n     µ-rec function of type recalg 1 that enumerates the solutions \n\n     given n compute x#w in vec nat (1+m). Compute \n     p[x][w] = q[x][w]. If equal, return (S x), otherwise return 0 *)\n\n   Variable (m : nat) (p q : dio_polynomial (pos m) (pos 1)).\n\n   Let f := ra_dio_poly_test p q.\n \n   Let Hf x w : {e : nat |\n       ⟦ f ⟧ (x ## w) e /\\\n       (e = 0 <->\n        dp_eval\n          (fun i => vec_pos (vec_app (project m x) w) (pos_left 1 i))\n          (fun i => vec_pos (vec_app (project m x) w) (pos_right m i))\n          p =\n        dp_eval\n          (fun i => vec_pos (vec_app (project m x) w) (pos_left 1 i))\n          (fun i => vec_pos (vec_app (project m x) w) (pos_right m i)) q) }.\n  Proof. apply ra_dio_poly_test_val. Qed.\n\n  Opaque f.\n\n  Let g : recalg 1.\n  Proof.\n    apply ra_comp with (1 := ra_ite).\n    refine (_##_##_##vec_nil).\n    + apply ra_comp with (1 := f), ra_vec_project.\n    + apply ra_comp with (1 := ra_succ).\n      refine (_##vec_nil).\n      apply (@ra_project 2 pos1).\n    + apply ra_cst_n, 0.\n  Defined.\n\n  Opaque ra_decomp_l ra_decomp_r ra_project.\n\n  Let Hg0 : prim_rec g.\n  Proof.\n    simpl; split; auto.\n    intros j; analyse pos j; auto.\n    + simpl; split; auto.\n      * apply ra_dio_poly_test_prim.\n      * intros j; analyse pos j; simpl; auto; split; auto.\n    + simpl; split; auto.\n      intros j; analyse pos j; auto.\n  Qed.\n\n  Let Hg1 x : ex (⟦g⟧ (x##vec_nil)).\n  Proof. apply prim_rec_tot; auto. Qed.\n\n  (* Not a very nice proof ... *)\n\n  Let Hg x : (exists n, ⟦g⟧ (n##vec_nil) (S x)) <-> exists w, dp_eval (vec_pos w) (fun _ => x) p\n                                                            = dp_eval (vec_pos w) (fun _ => x) q.\n  Proof.\n    split.\n    + intros (n & w & H1 & H2).\n      apply ra_ite_rel in H1.\n      generalize (H2 pos0) (H2 pos1) (H2 pos2).\n      clear H2; revert H1.\n      repeat rewrite vec_pos_set.\n      vec split w with a; vec split w with b; vec split w with c; vec nil w; clear w.\n      simpl; intros H1 H2 H3 H4.\n      destruct H3 as (w & H3 & H5).\n      generalize (H5 pos0); revert H3; clear H5.\n      vec split w with d; vec nil w; clear w; simpl; intros H3 H5.\n      apply ra_project_rel in H5; simpl in H5.\n      destruct H4 as (w & H4 & _); red in H4; clear w.\n      destruct H2 as (w & H2 & H6).\n      generalize (H6 pos0) (H6 pos1); clear H6.\n      revert H2; vec split w with u; vec split w with v; vec nil w; clear w; simpl.\n      intros H2 H6 H7.\n      apply ra_project_rel in H6.\n      apply ra_project_rel in H7.\n      simpl in H5, H6, H7.\n      subst c b d u v.\n      apply ra_dio_poly_test_rel in H2; simpl in H2.\n      exists (project m (decomp_l n)).\n      apply proj1 in H2.\n      destruct a; try discriminate.\n      simpl in H1; injection H1; clear H1; intros H1.\n      specialize (H2 eq_refl); subst x.\n      eq goal H2; f_equal; apply dp_eval_ext;\n        try (intros; rewrite vec_pos_app_left; auto);\n        intros j _; analyse pos j; rewrite vec_pos_app_right; simpl; auto.\n    + intros (w & Hw).\n      destruct (Hf (inject w) (x##vec_nil)) as (e & H1 & H2).\n      assert (e = 0) as He.\n      { apply H2.\n        eq goal Hw; f_equal; apply dp_eval_ext;\n          try (intros j _; rewrite vec_pos_app_left; rewrite project_inject; auto);\n          intros j _; analyse pos j; rewrite vec_pos_app_right; simpl; auto. }\n      clear H2; subst e.\n      exists (inject (inject w##x##vec_nil)).\n      unfold g.\n      exists (0##S x##0##vec_nil); split.\n      * apply ra_ite_rel; simpl; auto.\n      * intros j; rewrite vec_pos_set; analyse pos j; simpl.\n        - exists (inject w ## x ## vec_nil); split; auto.\n          intros j; analyse pos j; simpl.\n          { apply ra_project_rel; simpl.\n            rewrite decomp_l_recomp; auto. }\n          { apply ra_project_rel; simpl.\n            rewrite decomp_r_recomp, decomp_l_recomp; auto. }\n        - exists (x##vec_nil); split; try (red; auto; fail).\n          intros j; analyse pos j; simpl.\n          apply ra_project_rel; simpl.\n          rewrite decomp_r_recomp, decomp_l_recomp; auto.\n        - exists vec_nil; split; try (red; auto; fail).\n          intros j; analyse pos j.\n  Qed.\n\n  Theorem dio_poly_eq_2_ra_prim : \n          { g : recalg 1 | prim_rec g \n               /\\ forall x, (exists n, ⟦g⟧ (n##vec_nil) (S x)) \n                         <-> exists w, dp_eval (vec_pos w) (fun _ => x) p\n                                     = dp_eval (vec_pos w) (fun _ => x) q }.\n  Proof. exists g; split; auto. Qed. \n\nEnd dio_ra_enum.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/MuRec/ra_dio_poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6610154358894634}}
{"text": "Require Import init.\n\nRequire Import linear_base.\n\n(* TODO: Deal with multilinear functions in general *)\nDefinition bilinear {U V1 V2 V3} `{\n    Plus V1, Plus V2, Plus V3,\n    ScalarMult U V1,\n    ScalarMult U V2,\n    ScalarMult U V3\n} (f : V1 → V2 → V3) :=\n    (∀ a v1 v2, f (a · v1) v2 = a · (f v1 v2)) ∧\n    (∀ a v1 v2, f v1 (a · v2) = a · (f v1 v2)) ∧\n    (∀ v1 v2 v3, f (v1 + v2) v3 = f v1 v3 + f v2 v3) ∧\n    (∀ v1 v2 v3, f v1 (v2 + v3) = f v1 v2 + f v1 v3).\n\n(* begin hide *)\nSection Bilinear.\n\nContext {U V1 V2 V3} `{\n    UP : Plus U,\n    UZ : Zero U,\n    UN : Neg U,\n    UO : One U,\n    @PlusComm U UP,\n    @PlusLid U UP UZ,\n    @PlusLinv U UP UZ UN,\n\n    V1P : Plus V1,\n    V1Z : Zero V1,\n    V1N : Neg V1,\n    UV1 : ScalarMult U V1,\n    @PlusComm V1 V1P,\n    @PlusAssoc V1 V1P,\n    @PlusLid V1 V1P V1Z,\n    @PlusLinv V1 V1P V1Z V1N,\n    @ScalarId U V1 UO UV1,\n    @ScalarRdist U V1 UP V1P UV1,\n\n    V2P : Plus V2,\n    V2Z : Zero V2,\n    V2N : Neg V2,\n    UV2 : ScalarMult U V2,\n    @PlusComm V2 V2P,\n    @PlusAssoc V2 V2P,\n    @PlusLid V2 V2P V2Z,\n    @PlusLinv V2 V2P V2Z V2N,\n    @ScalarId U V2 UO UV2,\n    @ScalarRdist U V2 UP V2P UV2,\n\n    V3P : Plus V3,\n    V3Z : Zero V3,\n    V3N : Neg V3,\n    UV3 : ScalarMult U V3,\n    @PlusComm V3 V3P,\n    @PlusAssoc V3 V3P,\n    @PlusLid V3 V3P V3Z,\n    @PlusLinv V3 V3P V3Z V3N,\n    @ScalarId U V3 UO UV3,\n    @ScalarRdist U V3 UP V3P UV3\n}.\n(* end hide *)\nVariables (f : V1 → V2 → V3) (f_bil : bilinear f).\n\nTheorem bilinear_lscalar : ∀ a v1 v2, f (a · v1) v2 = a · (f v1 v2).\nProof.\n    apply f_bil.\nQed.\n\nTheorem bilinear_rscalar : ∀ a v1 v2, f v1 (a · v2) = a · (f v1 v2).\nProof.\n    apply f_bil.\nQed.\n\nTheorem bilinear_rdist : ∀ v1 v2 v3, f (v1 + v2) v3 = f v1 v3 + f v2 v3.\nProof.\n    apply f_bil.\nQed.\n\nTheorem bilinear_ldist : ∀ v1 v2 v3, f v1 (v2 + v3) = f v1 v2 + f v1 v3.\nProof.\n    apply f_bil.\nQed.\n\nTheorem bilinear_lanni : ∀ v, f 0 v = 0.\nProof.\n    intros v.\n    rewrite <- (scalar_lanni 0).\n    rewrite bilinear_lscalar.\n    apply scalar_lanni.\nQed.\n\nTheorem bilinear_ranni : ∀ v, f v 0 = 0.\nProof.\n    intros v.\n    rewrite <- (scalar_lanni 0).\n    rewrite bilinear_rscalar.\n    apply scalar_lanni.\nQed.\n\nTheorem bilinear_lneg : ∀ u v, f (-u) v = -(f u v).\nProof.\n    intros u v.\n    rewrite <- scalar_neg_one.\n    rewrite bilinear_lscalar.\n    rewrite scalar_neg_one.\n    reflexivity.\nQed.\n\nTheorem bilinear_rneg : ∀ u v, f u (-v) = -(f u v).\nProof.\n    intros u v.\n    rewrite <- scalar_neg_one.\n    rewrite bilinear_rscalar.\n    rewrite scalar_neg_one.\n    reflexivity.\nQed.\n(* begin hide *)\nEnd Bilinear.\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/Linear/linear_bilinear.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88242786954645, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.661015428630386}}
{"text": "Require Import XR_Rsqr.\nRequire Import XR_Rmult_comm.\nRequire Import XR_Rmult_assoc.\nRequire Import XR_Rmult_eq_compat_l.\nRequire Import XR_Rmult_eq_compat_r.\n\nLocal Open Scope R_scope.\n\nLemma Rsqr_mult : forall x y:R, Rsqr (x * y) = Rsqr x * Rsqr y.\nProof.\n  intros x y.\n  unfold Rsqr.\n  repeat rewrite Rmult_assoc.\n  apply Rmult_eq_compat_l.\n  repeat rewrite <- Rmult_assoc.\n  apply Rmult_eq_compat_r.\n  rewrite Rmult_comm.\n  reflexivity.\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_mult.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6610154266248758}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\nRequire Import List Arith Lia.\n\nFrom Undecidability.Shared.Libs.DLW.Utils\n  Require Import utils_tac utils_list finite.\n\nFrom Undecidability.Shared.Libs.DLW.Vec \n  Require Import pos vec.\n\nFrom Undecidability.TRAKHTENBROT\n  Require Import notations utils fol_ops fo_sig fo_terms fo_logic.\n\nImport fol_notations.\n\nSet Default Proof Using \"Type\".\n\nSet Implicit Arguments.\n\n(* * First order definability and closure properties *)\n\nNotation ø := vec_nil.\n\nOpaque fo_term_subst fo_term_map fo_term_sem.\n\nSection fo_definability.\n\n  Variable (Σ : fo_signature) (ls : list (syms Σ)) (lr : list (rels Σ))\n           (X : Type) (M : fo_model Σ X).\n\n  Definition fot_definable (f : (nat -> X) -> X) := \n       { t | incl (fo_term_syms t) ls /\\ forall φ, fo_term_sem M φ t = f φ }.\n\n  Definition fol_definable (R : (nat -> X) -> Prop) :=\n       { A | incl (fol_syms A) ls \n          /\\ incl (fol_rels A) lr \n          /\\ forall φ, fol_sem M φ A <-> R φ }.\n\n  (* A FOL definable predicate is always extensional *)\n\n  Fact fot_def_ext t : fot_definable t -> forall φ ψ, (forall n, φ n = ψ n) -> t φ = t ψ.\n  Proof.\n    intros (k & _ & Hk) phi psi H.\n    rewrite <- Hk, <- Hk; apply fo_term_sem_ext; auto.\n  Qed.\n\n  Fact fol_def_ext R : fol_definable R -> forall φ ψ, (forall n, φ n = ψ n) -> R φ <-> R ψ.\n  Proof.\n    intros (A & _ & _ & HA) phi psi H.\n    rewrite <- HA, <- HA; apply fol_sem_ext.\n    intros; auto.\n  Qed.\n\n  (* We derive closure properties *)\n\n  Fact fot_def_proj n : fot_definable (fun φ => φ n).\n  Proof. exists (£ n); intros; split; rew fot; auto; intros _ []. Qed.\n\n  Fact fot_def_map (f : nat -> nat) t :\n           fot_definable t -> fot_definable (fun φ => t (fun n => φ (f n))).\n  Proof.\n    intros H; generalize (fot_def_ext H); revert H.\n    intros (k & H1 & H2) H3.\n    exists (fo_term_map f k); split.\n    + rewrite fo_term_syms_map; auto.\n    + intro phi; rewrite <- fo_term_subst_map; rew fot.\n      rewrite H2; apply H3; intro; rew fot; auto.\n  Qed.\n \n  Fact fot_def_comp s v : \n        In s ls\n      -> (forall p, fot_definable (fun φ => vec_pos (v φ) p))\n      -> fot_definable (fun φ => fom_syms M s (v φ)).\n  Proof.\n    intros H0 H; apply vec_reif_t in H.\n    destruct H as (w & Hw).\n    exists (in_fot _ w); split; rew fot.\n    + intros x [ -> | H ]; auto; revert H.\n      rewrite in_flat_map.\n      intros (t & H1 & H2).\n      apply in_vec_list, in_vec_inv in H1.\n      destruct H1 as (p & <- ).\n      revert H2; apply Hw.\n    + intros phi; rew fot; f_equal.\n      apply vec_pos_ext; intros p.\n      rewrite vec_pos_map.\n      apply Hw; auto.\n  Qed.\n\n  Fact fot_def_equiv f g : \n         (forall φ, f φ = g φ) -> fot_definable f -> fot_definable g.\n  Proof.\n    intros E (t & H1 & H2); exists t; split; auto; intro; rewrite H2; auto.\n  Qed.\n\n  Fact fol_def_atom r v :\n         In r lr\n      -> (forall p, fot_definable (fun φ => vec_pos (v φ) p))\n      -> fol_definable (fun φ => fom_rels M r (v φ)).\n  Proof.\n    intros H0 H; apply vec_reif_t in H.\n    destruct H as (w & Hw).\n    exists (@fol_atom _ _ w); msplit 2.\n    + simpl; intro s; rewrite in_flat_map.\n      intros (t & H1 & H2).\n      apply in_vec_list, in_vec_inv in H1.\n      destruct H1 as (p & <- ).\n      revert H2; apply Hw.\n    + simpl; intros ? [ -> | [] ]; auto.\n    + intros phi; simpl.\n      apply fol_equiv_ext; f_equal.\n      apply vec_pos_ext; intros p.\n      rewrite vec_pos_map; apply Hw; auto.\n  Qed.\n\n  Fact fol_def_True : fol_definable (fun _ => True).\n  Proof. exists (⊥⤑⊥); intros; simpl; msplit 2; try red; simpl; tauto. Qed.\n \n  Fact fol_def_False : fol_definable (fun _ => False).\n  Proof. exists ⊥; intros; simpl; msplit 2; try red; simpl; tauto. Qed.\n\n  Fact fol_def_equiv R T : \n          (forall φ, R φ <-> T φ) -> fol_definable R -> fol_definable T.\n  Proof. \n    intros H (A & H1 & H2 & H3); exists A; msplit 2; auto; intro; rewrite <- H; auto. \n  Qed.\n\n  Fact fol_def_conj R T : \n         fol_definable R -> fol_definable T -> fol_definable (fun φ => R φ /\\ T φ).\n  Proof.\n    intros (A & H1 & H2 & H3) (B & HH4 & H5 & H6); exists (fol_bin fol_conj A B); msplit 2.\n    1,2: simpl; intro; rewrite in_app_iff; intros []; auto.\n    intro; simpl; rewrite H3, H6; tauto.\n  Qed.\n\n  Fact fol_def_disj R T : \n         fol_definable R -> fol_definable T -> fol_definable (fun φ => R φ \\/ T φ).\n  Proof.\n    intros (A & H1 & H2 & H3) (B & HH4 & H5 & H6); exists (fol_bin fol_disj A B); msplit 2.\n    1,2: simpl; intro; rewrite in_app_iff; intros []; auto.\n    intro; simpl; rewrite H3, H6; tauto.\n  Qed.\n\n  Fact fol_def_imp R T : \n         fol_definable R -> fol_definable T -> fol_definable (fun φ => R φ -> T φ).\n  Proof.\n    intros (A & H1 & H2 & H3) (B & HH4 & H5 & H6); exists (fol_bin fol_imp A B); msplit 2.\n    1,2: simpl; intro; rewrite in_app_iff; intros []; auto.\n    intro; simpl; rewrite H3, H6; tauto.\n  Qed.\n\n  Fact fol_def_fa (R : X -> (nat -> X) -> Prop) :\n          fol_definable (fun φ => R (φ 0) (fun n => φ (S n)))\n       -> fol_definable (fun φ => forall x, R x φ).\n  Proof.\n    intros (A & H1 & H2 & H3); exists (fol_quant fol_fa A); msplit 2; auto.\n    intro; simpl; apply forall_equiv.\n    intro; rewrite H3; simpl; tauto.\n  Qed.\n\n  Fact fol_def_ex (R : X -> (nat -> X) -> Prop) :\n          fol_definable (fun φ => R (φ 0) (fun n => φ (S n)))\n       -> fol_definable (fun φ => exists x, R x φ).\n  Proof.\n    intros (A & H1 & H2 & H3); exists (fol_quant fol_ex A); msplit 2; auto.\n    intro; simpl; apply exists_equiv.\n    intro; rewrite H3; simpl; tauto.\n  Qed.\n\n  Fact fol_def_list_fa K l (R : K -> (nat -> X) -> Prop) :\n           (forall k, In k l -> fol_definable (R k))\n        -> fol_definable (fun φ => forall k, In k l -> R k φ).\n  Proof.\n    intros H.\n    set (f := fun k Hk => proj1_sig (H k Hk)).\n    exists (fol_lconj (list_in_map l f)); msplit 2. \n    + rewrite fol_syms_bigop.\n      intros s; simpl; rewrite <- app_nil_end.\n      rewrite in_flat_map.\n      intros (A & H1 & H2).\n      apply In_list_in_map_inv in H1.\n      destruct H1 as (k & Hk & ->).\n      revert H2; apply (proj2_sig (H k Hk)); auto.\n    + rewrite fol_rels_bigop.\n      intros s; simpl; rewrite <- app_nil_end.\n      rewrite in_flat_map.\n      intros (A & H1 & H2).\n      apply In_list_in_map_inv in H1.\n      destruct H1 as (k & Hk & ->).\n      revert H2; apply (proj2_sig (H k Hk)); auto.\n    + intros phi.\n      rewrite fol_sem_lconj; split.\n      * intros H1 k Hk; apply (proj2_sig (H k Hk)), H1.\n        change (In (f k Hk) (list_in_map l f)). \n        apply In_list_in_map.\n      * intros H1 A H2.\n        apply In_list_in_map_inv in H2.\n        destruct H2 as (k & Hk & ->).\n        apply (proj2_sig (H k Hk)); auto.\n  Qed.\n\n  Fact fol_def_bounded_fa m (R : nat -> (nat -> X) -> Prop) :\n             (forall n, n < m -> fol_definable (R n))\n          -> fol_definable (fun φ => forall n, n < m -> R n φ).\n  Proof.\n    intros H.\n    apply fol_def_equiv with (R := fun φ => forall n, In n (list_an 0 m) -> R n φ).\n    + intros phi; apply forall_equiv; intro; rewrite list_an_spec; simpl; split; try tauto.\n      intros H1 ?; apply H1; lia.\n    + apply fol_def_list_fa.\n      intros n Hn; apply H; revert Hn; rewrite list_an_spec; lia.\n  Qed.\n\n  Fact fol_def_list_ex K l (R : K -> (nat -> X) -> Prop) :\n           (forall k, In k l -> fol_definable (R k))\n        -> fol_definable (fun φ => exists k, In k l /\\ R k φ).\n  Proof.\n    intros H.\n    set (f := fun k Hk => proj1_sig (H k Hk)).\n    exists (fol_ldisj (list_in_map l f)); msplit 2. \n    + rewrite fol_syms_bigop.\n      intros s; simpl; rewrite <- app_nil_end.\n      rewrite in_flat_map.\n      intros (A & H1 & H2).\n      apply In_list_in_map_inv in H1.\n      destruct H1 as (k & Hk & ->).\n      revert H2; apply (proj2_sig (H k Hk)); auto.\n    + rewrite fol_rels_bigop.\n      intros s; simpl; rewrite <- app_nil_end.\n      rewrite in_flat_map.\n      intros (A & H1 & H2).\n      apply In_list_in_map_inv in H1.\n      destruct H1 as (k & Hk & ->).\n      revert H2; apply (proj2_sig (H k Hk)); auto.\n    + intros phi.\n      rewrite fol_sem_ldisj; split.\n      * intros (A & H1 & HA).\n        apply In_list_in_map_inv in H1.\n        destruct H1 as (k & Hk & ->).\n        exists k; split; auto.\n        apply (proj2_sig (H k Hk)); auto.\n      * intros (k & Hk & H1).\n        exists (f k Hk); split.\n        - apply In_list_in_map.\n        - apply (proj2_sig (H k Hk)); auto.\n  Qed.\n\n  Fact fol_def_subst (R : (nat -> X) -> Prop) (f : nat -> (nat -> X) -> X) :\n          (forall n, fot_definable (f n))\n       -> fol_definable R\n       -> fol_definable (fun φ => R (fun n => f n φ)).\n  Proof.\n    intros H1 H2. \n    generalize (fol_def_ext H2); intros H3.\n    destruct H2 as (A & G1 & G2 & HA).\n    set (rho := fun n => proj1_sig (H1 n)).\n    exists (fol_subst rho A); msplit 2. \n    + red; apply Forall_forall; apply fol_syms_subst.\n      * intros n Hn; rewrite Forall_forall.\n        intro; apply (fun n => proj2_sig (H1 n)).\n      * apply Forall_forall, G1.\n    + rewrite fol_rels_subst; auto.\n    + intros phi.\n      rewrite fol_sem_subst, HA.\n      apply H3; intro; unfold rho; rew fot.\n      apply (fun n => proj2_sig (H1 n)).\n  Qed.\n\nEnd fo_definability.\n\nCreate HintDb fol_def_db.\n\n#[export] Hint Resolve fot_def_proj fot_def_map fot_def_comp fol_def_True fol_def_False : fol_def_db.\n\nTactic Notation \"fol\" \"def\" := \n   repeat ((  apply fol_def_conj \n           || apply fol_def_disj \n           || apply fol_def_imp \n           || apply fol_def_ex\n           || apply fol_def_fa\n           || (apply fol_def_atom; intro)\n           || apply fol_def_subst); auto with fol_def_db); auto with fol_def_db.\n\nSection extra.\n\n  Variable (Σ : fo_signature) (ls : list (syms Σ)) (lr : list (rels Σ))\n           (X : Type) (M : fo_model Σ X).\n\n  (* More closure properties *)\n\n  Fact fol_def_iff R T : \n         fol_definable ls lr M R \n      -> fol_definable ls lr M T \n      -> fol_definable ls lr M (fun φ => R φ <-> T φ).\n  Proof.\n    intros; fol def.\n  Qed.\n\n  Fact fol_def_subst2 R t1 t2 : \n           fol_definable ls lr M (fun φ => R (φ 0) (φ 1))\n        -> fot_definable ls M t1\n        -> fot_definable ls M t2\n        -> fol_definable ls lr M (fun φ => R (t1 φ) (t2 φ)).\n  Proof.\n    intros H1 H2 H3.\n    set (f n := match n with\n        | 0 => t1 \n        | 1 => t2\n        | _ => fun φ => φ 0\n      end).\n    change (fol_definable ls lr M (fun φ => R (f 0 φ) (f 1 φ))). \n    apply fol_def_subst with (2 := H1) (f := f).\n    intros [ | [ | n ] ]; simpl; fol def.\n  Qed.\n\n  Let env_vec (φ : nat -> X) n := vec_set_pos (fun p => φ (@pos2nat n p)).\n  Let env_env (φ : nat -> X) n k := φ (n+k).\n\n  Fact fol_def_vec_fa n (R : vec X n -> (nat -> X) -> Prop) :\n           (fol_definable ls lr M (fun φ => R (env_vec φ n) (env_env φ n)))\n         -> fol_definable ls lr M (fun φ => forall v, R v φ).\n  Proof.\n    revert R; induction n as [ | n IHn ]; intros R HR.\n    + revert HR; apply fol_def_equiv; intros phi; simpl.\n      split; auto; intros ? v; vec nil v; auto.\n    + set (T φ := forall v x, R (x##v) φ).\n      apply fol_def_equiv with (R := T).\n      * intros phi; unfold T; split.\n        - intros H v; vec split v with x; auto.\n        - intros H ? ?; apply (H (_##_)).\n      * unfold T; apply IHn, fol_def_fa, HR.\n  Qed.\n\n  Fact fol_def_vec_ex n (R : vec X n -> (nat -> X) -> Prop) :\n           (fol_definable ls lr M (fun φ => R (env_vec φ n) (env_env φ n)))\n         -> fol_definable ls lr M (fun φ => exists v, R v φ).\n  Proof.\n    revert R; induction n as [ | n IHn ]; intros R HR.\n    + revert HR; apply fol_def_equiv; intros phi; simpl.\n      split.\n      * exists vec_nil; auto.\n      * intros (v & Hv); revert Hv; vec nil v; auto.\n    + set (T φ := exists v x, R (x##v) φ).\n      apply fol_def_equiv with (R := T).\n      * intros phi; unfold T; split.\n        - intros (v & x & Hv); exists (x##v); auto.\n        - intros (v & Hv); revert Hv; vec split v with x; exists v, x; auto.\n      * unfold T; apply IHn, fol_def_ex, HR.\n  Qed.\n\n  Fact fol_def_finite_fa I (R : I -> (nat -> X) -> Prop) :\n            finite_t I\n         -> (forall i, fol_definable ls lr M (R i))\n         -> fol_definable ls lr M (fun φ => forall i : I, R i φ).\n  Proof.\n    intros (l & Hl) H.\n    apply fol_def_equiv with (R := fun φ => forall i, In i l -> R i φ).\n    + intros phi; apply forall_equiv; intro; split; auto.\n    + apply fol_def_list_fa; auto.\n  Qed.\n\n  Fact fol_def_finite_ex I (R : I -> (nat -> X) -> Prop) :\n            finite_t I\n         -> (forall i, fol_definable ls lr M (R i))\n         -> fol_definable ls lr M (fun φ => exists i : I, R i φ).\n  Proof.\n    intros (l & Hl) H.\n    apply fol_def_equiv with (R := fun φ => exists i, In i l /\\ R i φ).\n    + intros phi; apply exists_equiv; intro; split; auto; tauto.\n    + apply fol_def_list_ex; auto.\n  Qed.\n\nEnd extra.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/TRAKHTENBROT/fo_definable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6610154236874556}}
{"text": "(**\nフィボナッチ数の最大公約数 (GCD of Fibonacci Numbers) その2\n============================\n\n@suharahiromichi\n\n2022/01/29\n\n2022/02/27 fibn_ind と gcdn_ind を証明して、functional inducntion を使わずに証明する。\n*)\n\n(**\n# はじめに\n\nフィボナッチ数の最大公約数は、その最大公約数番目のフィボナッチ数に等しい、\n\n```math\n\ngcd(F_m, F_n) = F_{gcd(m, n)}\n```\n\nという定理があります。エドゥアール・リュカ（François Édouard Anatole Lucas) が発見して、\nクヌーツ先生の本 ([1] (式 6.111) など) で有名になったのだそうです。\n\nフィボナッチ数の加法定理をつかうと簡単に証明できるので、トライしてみましょう。\n\n\nこの記事は [2] の続編です。\n\n先の記事では、Coqのfunctional inducntionを使用しましたが、\nこの記事ではそれを使わないで証明してみます。\n具体的には、フィボナッチ数とユーグリッドの互除法についての帰納原理\n（fibn_ind と gcdn_ind）を自分で証明して、使用します。\nこちらのほうが、よりMathComp風の証明だといえるでしょう。\n\nなお、gcdn_ind の証明は、Coq Tokyo [3]でおしえてもらいました。\n\n\nこのソースは、以下にあります。\n\nhttps://github.com/suharahiromichi/coq/blob/master/math/ssr_fib_3_2.v\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 Fib3_2.\n\n(**  \n# フィボナッチ数の定義と定理\n*)\n  Fixpoint fibn (n : nat) : nat :=\n    match n with\n    | 0 => 0\n    | 1 => 1\n    | (m.+1 as pn).+1 => fibn m + fibn pn (* fibn n.-2 + fibn n.-1 *)\n    end.\n\n(**\n## 簡単な補題\n*)\n\n(**\n1個分のフィボナッチ数の計算\n *)\n  Lemma fibn_n n : fibn n.+2 = fibn n + fibn n.+1.\n  Proof.\n    done.\n  Qed.\n\n(**\n隣り合ったフィボナッチ数は互いに素である。\n*)\n  Lemma fibn_coprime (n : nat) : coprime (fibn n) (fibn n.+1).\n  Proof.\n    rewrite /coprime.\n    elim: n => [//= | n IHn].\n    rewrite fibn_n.\n    by rewrite gcdnDr gcdnC.\n  Qed.\n  \n(**\n## フィボナッチ数列の帰納法\n*)\n  Lemma fibn_ind (P : nat -> nat -> Prop) :\n    P 0 0 ->\n    P 1 1 ->\n    (forall m : nat, P m (fibn m) ->\n                     P m.+1 (fibn m.+1) ->\n                     P m.+2 (fibn m + fibn m.+1))\n    ->\n      forall m : nat, P m (fibn m).\n  Proof.\n    move=> H1 H2 IH.\n    (* m について2回場合分して、m.+2 を取り出す。 *)\n    elim/ltn_ind => [[_ | [_ | m]]].\n    - by rewrite /fibn.\n    - by rewrite /fibn.\n    - move: (IH m).\n      rewrite -fibn_n => {IH} IH H.\n      by apply: IH; apply: H.\n  Qed.\n  \n  Definition Pfibn m0 n0 :=\n    forall n, fibn (n + m0.+1) = fibn m0.+1 * fibn n.+1 + n0 * fibn n.\n\n  Check @fibn_ind Pfibn\n    : Pfibn 0 0 ->\n      Pfibn 1 1 ->\n      (forall m : nat, Pfibn m (fibn m) ->\n                       Pfibn m.+1 (fibn m.+1) ->\n                       Pfibn m.+2 (fibn m + fibn m.+1))\n      ->\n        forall m : nat, Pfibn m (fibn m).\n  \n(**\n## フィボナッチ数列の加法定理\n\nfibn_ind を使って、functional induction を使わずに証明します。\n*)\n  Lemma fibn_addition' m n :\n    fibn (m + n.+1) = fibn n.+1 * fibn m.+1 + fibn n * fibn m.\n  Proof.\n    apply: (@fibn_ind Pfibn); rewrite /Pfibn.\n    - clear m n => n.\n      rewrite addn1.\n      rewrite [fibn 1]/= mul1n mul0n addn0.\n      done.\n      \n    - clear m n => n.\n      rewrite addn2.\n      rewrite [fibn 2]/= add0n 2!mul1n.\n      rewrite addnC -fibn_n.\n      done.\n      \n    - clear m n => m IHn0 IHn1 n.\n      rewrite fibn_n 2!mulnDl.\n      \n      (* F(n + m.+1) の項をまとめて置き換える *)\n      rewrite ?addnA [_ + fibn m * fibn n]addnC. (* この項を先頭に。 *)\n      rewrite ?addnA [_ + fibn m.+1 * fibn n.+1]addnC ?addnA. (* この項を先頭に。 *)\n      rewrite -IHn0.\n       \n      (* F(n + m.+2) の項をまとめて置き換える *)\n      rewrite ?addnA [_ + fibn m.+1 * fibn n]addnC. (* この項を先頭に。 *)\n      rewrite ?addnA [_ + fibn m.+2 * fibn n.+1]addnC ?addnA. (* この項を先頭に。 *)\n      rewrite -IHn1.\n\n      rewrite -addn3 addnA addn3.\n      rewrite -[m.+2]addn2 addnA addn2.\n      rewrite -[m.+1]addn1 addnA addn1.\n      rewrite fibn_n addnC.\n      done.\n  Qed.\n  \n  Lemma fibn_addition m n :\n    1 <= n -> fibn (m + n) = fibn n * fibn m.+1 + fibn n.-1 * fibn m.\n  Proof.\n    move=> H.\n    have H' := fibn_addition' m n.-1.\n    by rewrite prednK in H'.\n  Qed.\n\n(**\n# ユーグリッドの互除法の帰納法の証明\n*)\n  Lemma gcdn_ind (P : nat -> nat -> nat -> Prop) :\n    (forall n, P 0 n n) ->\n    (forall m n, P (n %% m) m (gcdn (n %% m) m) ->\n                 P m n (gcdn m n))\n    ->\n      forall m n, P m n (gcdn m n).\n  Proof.\n    move => H0 Hmod.\n    elim/ltn_ind => [[| m]] // H n.\n    - have -> : gcdn 0 n = n by elim: n.\n      done.\n    - apply: Hmod.\n      exact: H (ltn_mod _ _) _.\n  Qed.\n\n  Definition Pgcdn m0 n0 n1 := gcdn (fibn m0) (fibn n0) = fibn n1.\n  \n  Check @gcdn_ind Pgcdn\n    : (forall n : nat, Pgcdn 0 n n) ->\n      (forall m n : nat, Pgcdn (n %% m) m (gcdn (n %% m) m) -> Pgcdn m n (gcdn m n)) ->\n      forall m n : nat, Pgcdn m n (gcdn m n).\n\n(**\n# フィボナッチ数のGCD\n*)\n\n(**\nGKPの解答にある、``m > n`` ならば ``gcd (fibn m) (fibn n) = gcd (fibn (m - n)) (fibn n)``\nと同じものを証明するが、そのために ``m`` を ``0`` と非0で振り分ける。\n *)\n  Lemma fibn_lemma_gkp' m n :\n    1 <= m -> gcdn (fibn (n + m)) (fibn n) = gcdn (fibn m) (fibn n).\n  Proof.\n    move=> H.\n    rewrite fibn_addition //.\n    rewrite gcdnC addnC gcdnMDl.\n    rewrite Gauss_gcdl.\n    - by rewrite gcdnC.\n    - by apply: fibn_coprime.\n  Qed.\n  \n  Lemma fibn_lemma_gkp m n :\n    gcdn (fibn (n + m)) (fibn n) = gcdn (fibn m) (fibn n).\n  Proof.\n    case: m => [| m].\n    - rewrite addn0 /=.\n      by rewrite gcd0n gcdnn.\n    - by rewrite fibn_lemma_gkp'.\n  Qed.\n  \n(**\ngcdnMDl のフィボナッチ数版\n*)\n  Check gcdnMDl : forall k m n : nat, gcdn m (k * m + n) = gcdn m n.\n  Lemma fibn_gcdMDl n q r :\n    gcdn (fibn (q * n + r)) (fibn n) = gcdn (fibn n) (fibn r).\n  Proof.\n    elim: q => [| q IHq].\n    - rewrite mul0n add0n.\n      rewrite gcdnC.\n      done.\n    - Search _ (_.+1 * _).\n      rewrite mulSn -addnA.\n      rewrite [LHS]fibn_lemma_gkp.\n      done.\n  Qed.\n  \n(**\ngcdn_modr のフィボナッチ数版\n*)\n  Check gcdn_modr : forall m n : nat, gcdn m (n %% m) = gcdn m n.\n  Lemma fibn_gcdn_modr m n :\n    gcdn (fibn m) (fibn n) = gcdn (fibn n) (fibn (m %% n)).\n  Proof.\n    move: (fibn_gcdMDl n (m %/ n) (m %% n)).\n    rewrite -divn_eq.\n    done.\n  Qed.\n\n(**\ngcdn_ind を使って、functional induction を使わずに証明します。\n*)\n  Theorem gcdn_fibn__fibn_gcdn (m n : nat) : gcdn (fibn m) (fibn n) = fibn (gcdn m n).\n  Proof.\n    apply: (@gcdn_ind Pgcdn); rewrite /Pgcdn.\n    - move=> n'.\n      by rewrite /= gcd0n.\n    - move=> m' n' /= IHm.\n      rewrite gcdnC -fibn_gcdn_modr gcdn_modl gcdnC in IHm.\n      by rewrite IHm gcdnC.\n  Qed.\n  \nEnd Fib3_2.\n\n(**\n# 文献\n\n[1] Graham, Knuth, Patashnik \"Concrete Mathematics\", Second Edition\n\n\n[2] 「フィボナッチ数の最大公約数」\n[https://qiita.com/suharahiromichi/items/d0861c1ef82d67d823c0]\n\n\n[3] Coq Tokyo [https://readcoqart.connpass.com/]\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/math/ssr_fib_3_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245911726384, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.660914684376788}}
{"text": "Require Import Coq.Unicode.Utf8_core.\n\nTheorem plus_rewrited : ∀ n m: nat,\n  n = m → n + n = m + m.\n(* Assuming n=m then n+n eq m+m *)\n\nProof.\n  intros n m.\n  intros H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\n(* What coq think abuot ht above code?\n\n1 subgoal\n\nn, m : nat\nH : n = m\n——————————————————\nm + m = m + m\n *)", "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/p006_proof_rewriting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6608736440749533}}
{"text": "Add LoadPath \".\" as OmegaCategories.\nRequire Export Unicode.Utf8_core.\nRequire Import BinInt Even List Heap Le Plus Minus.\nRequire Import Omega. \n\n(** * Globular sets, basic definitions  *)\n\n(** First, a notation for [existT], the quantifier over [Type]s *)\n\nSet Implicit Arguments.\n\n(** Inductive type for globular sets *)\n(** This corresponds to Definition 1 of the TLCA paper *)\n\nCoInductive GType : Type := mkGType : ∀ (Obj : Type), (Obj -> Obj -> GType) -> GType. \n\nDefinition objects (G : GType) : Type.\ndestruct G as [Obj G]. exact Obj.\nDefined.\n\nNotation \" | A |\" := (objects A) (at level 80).\n\nDefinition hom (G : GType) : ∀ (a b : |G|), GType.\ndestruct G as [Obj G]. exact G.\nDefined.\n\nReserved Notation \" A ==> B \" (at level 90).\nNotation \" G [ A , B ]\" := (hom G A B) (at level 80).\n\n\n(** Definition of morphism of globular types *)\n\nCoInductive GHom : ∀ (G H : GType), Type := \n  mkGHom : ∀ (G H : GType) (f0 : |G| -> |H|)\n             (f1 : ∀ (x x' : |G|), G [x,x'] ==> H [f0 x, f0 x']),\n             G ==> H\nwhere \" A ==> B \" := (GHom A B).\n\nDefinition app G H (f : G ==> H) : |G| -> |H|.\nintro x. destruct f. exact (f0 x).\nDefined.\n\nNotation \"f @@ x\" := (app f x) (at level 20) : type_scope.\n\nDefinition map G H (f : G ==> H) (x x' : |G|) : G [x,x'] ==> H [f @@ x, f @@ x'].\ndestruct f. exact (f1 x x').\nDefined.\n\nNotation \"f << x , x' >>\" := (map f x x') (at level 80).\n\n(** Definition of product of globular types (Definition 2 in TLCA paper)*)\n\nReserved Notation \"A ** B\" (at level 90).\n\nCoFixpoint product (G H : GType) : GType :=  \n  @mkGType (prod (objects G) (objects H)) \n         (fun xy xy' => G [fst xy, fst xy'] ** H [snd xy, snd xy'])\nwhere \"A ** B\"  := (product A B).\n\n(* composition of morphisms of GTypes *)\n\nCoFixpoint GComp  (X Y Z:GType) : X ==> Y -> Y ==> Z -> X ==> Z :=\n  fun f g => mkGHom _ _ (fun x => g @@ (f @@ x)) \n                    (fun x x' => GComp (f << x , x' >>) (g << f @@ x, f @@ x'>>)).\n\n(* identity on GTypes *)\n\nCoFixpoint GId (G:GType) : G ==> G := mkGHom G G id (fun x y => GId (G [x, y])).\n\n(* Definition of the terminal globular type *)\n\nCoFixpoint Delta (X0 : Type) : GType := @mkGType X0 (fun _ _ => Delta X0).\n\nDefinition terminal : GType := Delta unit.\n", "meta": {"author": "tabareau", "repo": "omega_categories", "sha": "d8b5aa149a7f1b272927466089e59e1bfbc5cc1e", "save_path": "github-repos/coq/tabareau-omega_categories", "path": "github-repos/coq/tabareau-omega_categories/omega_categories-d8b5aa149a7f1b272927466089e59e1bfbc5cc1e/GType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682086, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6608499708280028}}
{"text": "(* Exercise 4 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_004 : (forall x y : D, R x y) -> forall x : D, R x x.\nProof.\nimp_i a1.\nall_i a.\nall_e (forall y:D, R a y) a.\nall_e (forall x:D, forall y:D, R x y) a.\nhyp a1.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred004.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.660849968451017}}
{"text": "Require Export Arith.\n\nFixpoint bdiv_aux (b m n:nat) {struct b} : nat * nat :=\n  match b with\n  | O => (0, 0)\n  | S b' =>\n      match le_gt_dec n m with\n      | left H => match bdiv_aux b' (m - n) n with\n                  | (q, r) => (S q, r)\n                  end\n      | right H => (0, m)\n      end\n  end.\n\n(* Here is the real solution to the exercise.  One of the keys is\n  to detect that we are going to prove properties of inequalities\n  that can be decided using lia. *)\n\nRequire Export Lia.\n\nTheorem bdiv_aux_correct2 :\n forall b m n:nat, m <= b -> 0 < n -> snd (bdiv_aux b m n) < n.\nProof.\n intros b; induction b as [ | b Hrec]; auto with arith.\n { cbn in |- *;   intros m n Hle Hlt; case (le_gt_dec n m).\n   -  generalize (Hrec (m - n) n).\n      case (bdiv_aux b (m - n) n); simpl in |- *; intros; lia.\n   - simpl in |- *; intros; lia.\n  }\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/ch15_general_recursion/SRC/bdiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.6608041833227705}}
{"text": "(** Pierre Castéran, University of Bordeaux and LaBRI *)\n\n\nFrom Coq Require Import Arith Peano_dec Lia Relations Relation_Operators.\nFrom hydras Require Import  Hydra_Lemmas Simple_LexProd ON_Omega2.\nImport ON_Generic.\n\n(** There is no measure into omega^2  for proving termination\nof all hydra battles *)\n\n\n(* begin snippet Impossibility *)\n\nSection Impossibility_Proof.\n(* end snippet Impossibility *)\n\n  (** Let us assume there is a variant from [Hydra] into [omega^2] \n  for proving the termination of all hydra battles *)\n  \n  (* begin snippet Impossibilitya *)\n  \n  Variable m : Hydra -> ON_Omega2.t.\n  Context\n    (Hvar: @Hvariant _ _ (ON_Generic.ON_wf (ON:=Omega2)) free m).\n\n  (* end snippet Impossibilitya *)\n\n  (* begin snippet Impossibilityb *)\n  \n  Let big_h := hyd1 (hyd2 head head).\n\n  (* end snippet Impossibilityb *)\n  \n  (** To every pair $(i,j)$ of natural numbers we associate an hydra \n        with $i$ branches of length 2 and $j$ branches of length 1 *)\n\n  (* begin snippet Impossibilityc *)\n\n  Let iota (p: ON_Omega2.t) := \n    node (hcons_mult (hyd1 head) (fst p)\n                     (hcons_mult head (snd p) hnil)).\n  \n\n  (* end snippet Impossibilityc *)\n\n  (* begin snippet Impossibilityd *)\n  \n  Let small_h := iota (m big_h).\n  (* end snippet Impossibilityd *)\n  \n\n  (** *** Proof of the inequality [m small_h o< m big_h] \n   *)\n\n  #[local] Hint Constructors R1 S1 S2 : hydra.\n\n  Lemma m_big_h_not_null : m big_h <> zero.\n  Proof.\n    intro H; pose (h1 := hyd1 (hyd1 head)).\n    assert (first_round : big_h -+-> h1).\n    {\n      left; exists 0; right; left; constructor 1 with (n:=0).\n      split; left.\n    }\n    specialize (m_strict_mono m Hvar first_round).   \n    rewrite H; inversion_clear 1; lia.\n  Qed. \n  \n  (* begin snippet bigToSmall *)\n  \n  Lemma big_to_small : big_h -+-> small_h. (* .no-out *)\n\n  (* end snippet bigToSmall *)\n  \n  Proof.\n    unfold small_h; case_eq  (m big_h); intros i j Hj;  destruct i.\n    \n    (*  i = 0 *)\n    - unfold big_h; right with (hyd1 (hyd1 head)).\n      exists 0; right; left.\n      left with (n:=0);  split; left.\n      destruct j.\n      + now destruct m_big_h_not_null.\n      + unfold iota;cbn;left.\n        exists j;right; left; constructor 1;  split;  left.\n        \n    (* i > 0 *)\n    - unfold iota; cbn;  destruct j.\n      +   left; unfold iota, big_h; cbn.\n          exists i; right; left; left;   split; left.\n      +  right with (iota (S (S i), 0)). \n         unfold iota;  simpl fst ; simpl snd;   cbn; exists (S i); right.\n         left; left;  split; left.\n         left;  exists j; right; left;   right. \n         rewrite <- hcons_mult_comm;  apply hcons_mult_S1.\n         left; split; left.\n  Qed.\n\n  (* begin snippet mLt *)\n\n  (*|\n.. coq:: no-out\n|*)\n  \n  Corollary m_lt : m small_h o< m big_h.\n  Proof. apply m_strict_mono with (1:=Hvar) (2:=big_to_small). Qed.\n  (*||*)\n\n  (* end snippet mLt *)\n  \n  (** *** Proof of the inequality [m big_h o<= m small_h]  *)\n\n  (** *** Let us decompose any inequality p o< q into elementary steps *)\n\n  (* begin snippet stepDef *)\n\n  Inductive step : t -> t -> Prop :=\n  | succ_step : forall i j,  step (i, S j) (i, j)\n  | limit_step : forall i j, step (S i, 0) (i, j).\n\n  (* end snippet stepDef *)\n  \n  Lemma succ_rounds : forall i j,  iota (i,S j) -+-> iota (i, j).\n  Proof.\n    unfold iota;  left; exists 0;  left;   split; \n      apply hcons_mult_S0;  constructor.\n  Qed.\n\n  Lemma limit_rounds_0 :\n    forall i j, round_n j (iota (S i, 0)) (iota (i, S j)).\n  Proof.\n    intros i j;  destruct i.\n    - unfold iota;   right;  left;\n        change  (hcons head (hcons_mult head j hnil))\n          with (hcons_mult head (S j) hnil).\n      left; split;  left.\n    -   right; left; cbn;  rewrite <- hcons_mult_comm; right.\n        apply hcons_mult_S1; left; split; constructor.\n  Qed.\n  \n  Lemma limit_rounds : forall i j, iota (S i, 0) -+-> iota (i, j).\n  Proof.\n    intros i j;  apply round_plus_trans with (iota (i, S j)).\n    - left; exists j; apply limit_rounds_0.\n    - apply succ_rounds.\n  Qed.\n\n  #[local] Hint Constructors step clos_trans_1n : hydra.\n  #[local] Hint Resolve lex_1 lex_2: hydra.\n  #[local] Hint Unfold lt : hydra.\n\n\n  (* begin snippet stepToBattle *)\n  \n  Lemma step_to_battle : forall p q, step p q -> iota p -+-> iota q. (* .no-out *)\n\n  (* end snippet stepToBattle *)\n  \n  Proof.\n    destruct 1; [ apply succ_rounds |  apply limit_rounds].\n  Qed.\n\n  #[local] Hint Resolve step_to_battle : hydra.\n\n  (* begin snippet mGe *)\n\n\n  \n  Lemma m_ge : m big_h o<= m small_h. (* .no-out *)\n  Proof. (* .no-out *)\n    unfold small_h;\n    pattern (m big_h);\n      apply  well_founded_induction with (R := ON_lt) (1:= ON_wf);\n      intros (i,j) IHij.\n\n    (* end snippet mGe *)\n\n    (* begin snippet mGeb *)\n       (*|\n.. coq:: none\n|*)\n    destruct j as [|k].\n    - destruct i as [| l].\n      +  apply le_0. \n      +  assert (is_true (limitb (S l, 0))) by  reflexivity.\n        specialize (limit_is_lub (S l, 0) H (m (iota (S l, 0)))).\n        intros <- k; eapply Comparable.le_lt_trans.  \n        apply IHij;left; auto.\n        red; apply (m_strict_mono m Hvar); auto with hydra.\n        simpl canon. \n        apply step_to_battle.  apply limit_step. \n    - change (i, S k) with (succ (i,k)) at 1.\n      rewrite <- (lt_succ_le (i,k) (m (iota (i, S k)))).\n      eapply (Comparable.le_lt_trans).\n      instantiate (1:= (m (iota (i, k)))). \n      apply IHij; right; auto.      \n      apply (m_strict_mono m Hvar); auto with hydra.\n      (*||*)\n      (* ... *)\n  Qed.\n\n    (* end snippet mGeb *)\n\n  (* begin snippet Impossible *)\n\n  (*|\n.. coq:: no-out\n|*)\n  \n  Theorem Impossible : False.\n  Proof.\n    destruct (StrictOrder_Irreflexive (R:=ON_lt) (m big_h));\n      eapply le_lt_trans; [apply m_ge | apply m_lt].\n  Qed. \n\nEnd Impossibility_Proof.\n\n(*||*)\n\n\n  (* end snippet Impossible *)\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/Hydra/Omega2_Small.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6608041805756752}}
{"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(* Trying an abstract compiler with labels instead of nats as source code addressing *)\n\nRequire Import List Arith Omega.\n\nRequire Import utils subcode sss bsm_defs compiler.\n\n\n(** ** Semantic Correctness of Compiled Code *)\n\nSet Implicit Arguments.\n\nSection comp.\n\n  (** This is an abstract proof of compiler soundness & completeness \n\n      The principle of this compiler is to map every source individual\n      instruction into a list of target instructions that simulate the\n      source instruction. We describe our assumptions later on ...\n\n    *)\n\n  Variable (X Y : Set)                                  (* X is a small type of source instructions and \n                                                           Y of destination instructions *) \n           (icomp : (nat -> nat) -> nat -> X -> list Y) (* instruction compiler w.r.t. a given linker & a position \n                                                           icomp lnk i x compiles instruction x at position i \n                                                           using linker lnk into a list of target instructions\n                                                         *)\n           (ilen  : X -> nat)                           (* compiled code length does not depend on linker or position,\n                                                           it only depends on the original instruction\n                                                           whether this assumption is strong or not is debatable\n                                                           but we only encountered cases which satisfy this assuption\n                                                         *)\n           (Hilen : forall lnk n x, length (icomp lnk n x) = ilen x)\n           (*Hilen2  : forall x, 1 <= ilen x*).           (* compiled code should not be empty, even if the source\n                                                           instruction is something like NO-OP, to ensure progress\n                                                           in the simulation as source code executes \n                                                           also not a strong requirement\n\n                                                           This can be removed because it can be deduced (where it\n                                                           is used) from Hilen1 & step_X_tot & Hicomp \n                                                         *)\n\n  (* Semantics for X and Y instructions *)\n\n  Variables (state_X state_Y : Type)\n            (step_X : X -> (nat*state_X) -> (nat*state_X) -> Prop)\n            (step_Y : Y -> (nat*state_Y) -> (nat*state_Y) -> Prop).\n\n  Notation \"i '/X/' s -1> t\" := (step_X i s t) (at level 70, no associativity).\n  Notation \"P '/X/' s '-[' k ']->' t\" := (sss_steps step_X P k s t) (at level 70, no associativity).\n  Notation \"P '/X/' s '-+>' t\" := (sss_progress step_X P s t) (at level 70, no associativity).\n  Notation \"P '/X/' s ->> t\" := (sss_compute step_X P s t) (at level 70, no associativity).\n  Notation \"P '/X/' s '~~>' t\" := (sss_output step_X P s t) (at level 70, no associativity).\n  Notation \"P '/X/' s ↓\" := (sss_terminates step_X P s)(at level 70, no associativity).\n\n  Notation \"i '/Y/' s -1> t\" := (step_Y i s t) (at level 70, no associativity).\n  Notation \"P '/Y/' s '-[' k ']->' t\" := (sss_steps step_Y P k s t) (at level 70, no associativity).\n  Notation \"P '/Y/' s '-+>' t\" := (sss_progress step_Y P s t) (at level 70, no associativity).\n  Notation \"P '/Y/' s ->> t\" := (sss_compute step_Y P s t) (at level 70, no associativity).\n  Notation \"P '/Y/' s '~~>' t\" := (sss_output step_Y P s t) (at level 70, no associativity).\n  Notation \"P '/Y/' s ↓\" := (sss_terminates step_Y P s)(at level 70, no associativity).\n\n  (** We assume totality of X semantics, i.e. no instruction can block the computation\n      and functionality of Y semantics \n\n      Totality is not necessary achieved ... think of a HALT instruction \n      what should we do in that case ? It should not be too difficult to\n      embed a partial model of computation into a total one by transforming\n      blocking cases into jumps at a PC value outside of the code.\n    *)\n\n  Hypothesis (step_X_tot : forall I st1, exists st2, I /X/ st1 -1> st2)\n             (step_Y_fun : forall I st st1 st2, I /Y/ st -1> st1 -> I /Y/ st -1> st2 -> st1 = st2).\n\n (** simul is an invariant: simul st_X st_Y means that st_X is simulated by st_Y *)\n\n  Variable (simul : state_X -> state_Y -> Prop).\n\n  Infix \"⋈\" := simul (at level 70, no associativity).\n\n  (** Simulation is preserved by compiled instructions \n      this of course ensures the *semantic correctness of\n      the compilation of individual instructions*\n\n      Notice the important hypothesis of preservation of the +1\n      relative address by the linker otherwise it might not be\n      possible to establish the below predicate.\n\n      If the source language involves other relative addresses like\n      +2 or +d or -d, the present compiler might have to be substantially\n      updated.\n\n      +1 is very likely to be used even implicitly because every instruction\n      that does not branch (like INC or PUSH) implicitly jumps at +1 ...\n    *) \n\n  Definition instruction_compiler_sound := forall lnk I i1 v1 i2 v2 w1, \n                     I /X/ (i1,v1) -1> (i2,v2)\n                  -> lnk (1+i1) = length (icomp lnk i1 I) + lnk i1\n                  -> v1 ⋈ w1\n       -> exists w2, (lnk i1,icomp lnk i1 I) /Y/ (lnk i1,w1) -+> (lnk i2,w2)\n                  /\\ v2 ⋈ w2.\n\n  Hypothesis Hicomp : instruction_compiler_sound.\n\n  Section correctness. \n\n    (** We assume each instruction in P is compiled in Q according to the individual \n        instruction compiler combined with what the linker says for branching. \n        This is a *syntactic correctness criterion* for the whole compiled program Q\n      *)\n\n    Variables (linker : nat -> nat) (P : nat * list X) (Q : nat * list Y)\n              (HPQ : forall i I, (i,I::nil) <sc P -> (linker i, icomp linker i I) <sc Q\n                                                   /\\ linker (1+i) = ilen I + linker i).\n\n    (** From semantic correctness of individually compiled instructions and\n        syntactic correctness of the whole compiled program, we derive\n        soundness and completeness of the compiled program Q wrt the\n        source program P *)\n\n    Theorem compiler_sound i1 v1 i2 v2 w1 :\n                      v1 ⋈ w1 /\\ P /X/ (i1,v1) ->> (i2,v2)\n        -> exists w2, v2 ⋈ w2 /\\ Q /Y/ (linker i1,w1) ->> (linker i2,w2).\n    Proof.\n      change i1 with (fst (i1,v1)) at 2; change v1 with (snd (i1,v1)) at 1.\n      change i2 with (fst (i2,v2)) at 2; change v2 with (snd (i2,v2)) at 2.\n      generalize (i1,v1) (i2,v2); clear i1 v1 i2 v2.\n      intros st1 st2 (H1 & q & H2); revert H2 w1 H1.\n      induction 1 as [ (i1,v1) | q (i1,v1) (i2,v2) st3 H1 H2 IH2]; simpl; intros w1 H0.\n      + exists w1; split; auto; exists 0; constructor.\n      + destruct H1 as (k & l & I & r & v' & G1 & G2 & G3).\n        inversion G2; subst v' i1; clear G2.\n        destruct (Hicomp linker) with (1 := G3) (3 := H0)\n          as (w2 & G4 & G5).\n        * rewrite Hilen; apply HPQ; subst; exists l, r; auto.\n        * destruct (IH2 _ G5) as (w3 & G6 & G7).\n          exists w3; split; auto.\n          apply sss_compute_trans with (2 := G7); simpl.\n          apply sss_progress_compute.\n          revert G4; apply subcode_sss_progress.\n          apply HPQ; subst; exists l, r; auto.\n    Qed.\n\n    (* When still inside of P, the computation in Q simulates\n       a computation in P *)\n\n    Local Lemma compiler_complete_step p st1 w1 w3 :\n           snd st1 ⋈ snd w1\n        -> linker (fst st1) = fst w1\n        -> in_code (fst st1) P\n        -> out_code (fst w3) Q\n        -> Q /Y/ w1 -[p]-> w3\n        -> exists q st2 w2, snd st2 ⋈ snd w2\n                        /\\ linker (fst st2) = fst w2\n                        /\\ P /X/ st1 ->> st2\n                        /\\ Q /Y/ w2 -[q]-> w3\n                        /\\ q < p.\n    Proof.\n      revert st1 w1 w3; intros (i1,v1) (j1,w1) (j3,w3); simpl fst; simpl snd.\n      intros H1 H2 H3 H4 H5.\n      destruct (in_code_subcode H3) as (I & HI).\n      destruct HPQ with (1 := HI) as (H6 & H7).\n      assert (out_code j3 (linker i1, icomp linker i1 I)) as G2.\n      { revert H4; apply subcode_out_code; auto. }\n      assert (H8 : ilen I <> 0).\n      { intros H.\n        destruct (step_X_tot I (i1,v1)) as ((i2,v2) & Hst).\n        apply (Hicomp linker) with (3 := H1) in Hst; auto.\n        2: rewrite Hilen; auto.\n        destruct Hst as (w2 & (q & Hq1 & Hq2) & _).\n        rewrite <- (Hilen linker i1) in H.\n        destruct (icomp linker i1 I); try discriminate.\n        apply sss_steps_stall, proj1 in Hq2; simpl; omega. }\n      assert (in_code (linker i1) (linker i1, icomp linker i1 I)) as G3.\n      { simpl; rewrite (Hilen linker i1 I); omega. }\n      rewrite <- H2 in H5.\n      destruct (step_X_tot I (i1,v1)) as ((i2,v2) & G4).\n      destruct (Hicomp linker) with (1 := G4) (3 := H1) as (w2 & G5 & G6).\n      * rewrite H7, Hilen; auto.\n      * apply subcode_sss_progress_inv with (3 := H6) (4 := G5) in H5; auto.\n        destruct H5 as (q & H5 & G7).\n        exists q, (i2,v2), (linker i2, w2); simpl; repeat (split; auto).\n        apply subcode_sss_compute with (1 := HI).\n        exists 1; apply sss_steps_1.\n        exists i1, nil, I, nil, v1; repeat (split; auto).\n        f_equal; simpl; omega.\n    Qed.\n\n    (* Termination in Q simulates termination in P *)\n\n    Theorem compiler_complete i1 v1 w1 : \n          v1 ⋈ w1 -> Q /Y/ (linker i1,w1) ↓ -> P /X/ (i1,v1) ↓.\n    Proof.\n      intros H1 (st & (q & H2) & H3). \n      revert i1 v1 w1 H1 H2 H3.\n      induction q as [ q IHq ] using (well_founded_induction lt_wf).\n      intros i1 v1 w1 H1 H2 H3.\n      destruct (in_out_code_dec i1 P) as [ H4 | H4 ].\n      + destruct compiler_complete_step with (5 := H2) (st1 := (i1,v1))\n          as (p & (i2,v2) & (j2,w2) & G1 & G2 & G3 & G4 & G5); auto; simpl in *; subst j2.\n        destruct IHq with (1 := G5) (2 := G1) (3 := G4)\n          as ((i3 & v3) & F3 & F4); auto.\n        exists (i3,v3); repeat (split; auto).\n        apply sss_compute_trans with (1 := G3); auto.\n      + exists (i1,v1); repeat (split; auto).\n        exists 0; constructor.\n    Qed.\n\n    Corollary compiler_complete' i1 v1 w1 st : \n                            v1 ⋈ w1 /\\ Q /Y/ (linker i1,w1) ~~> st\n        -> exists i2 v2 w2, v2 ⋈ w2 /\\ P /X/ (i1,v1) ~~> (i2,v2)\n                                    /\\ Q /Y/ (linker i2,w2) ~~> st.\n    Proof.\n      intros (H1 & H2).\n      destruct compiler_complete with (1 := H1) (2 := ex_intro (fun x => Q /Y/ (linker i1, w1) ~~> x) _ H2)\n        as ((i2,v2) & H3 & H4).\n      exists i2, v2.\n      destruct (compiler_sound (conj H1 H3)) as (w2 & H5 & H6).\n      exists w2; do 2 (split; auto).\n      split; auto.\n      destruct H2 as (H2 & H0); split; auto.\n      apply sss_compute_inv with (3 := H6); auto.\n    Qed.\n\n  End correctness.\n\n  (** ** A Syntactically Correct Compiler *)\n\n  (** Now we build a correct linker & compiled program pair *)\n\n  Variable (P : nat * list X) (iQ : nat).\n\n  Let iP := fst P.\n  Let cP := snd P.\n\n  Let err := iQ+length_compiler ilen cP.\n\n  Definition gen_linker := linker ilen (iP,cP) iQ err.\n  Definition gen_compiler := compiler icomp ilen (iP,cP) iQ err.\n\n  Notation cQ := gen_compiler.\n  Notation lnk := gen_linker.\n\n  Let P_eq : P = (iP,cP).\n  Proof. unfold iP, cP; destruct P; auto. Qed.\n\n  Fact gen_linker_out i : out_code i (iP,cP) -> lnk i = iQ+length cQ.\n  Proof.\n    intros H.\n    unfold lnk.\n    rewrite linker_out_err; unfold err; simpl; auto.\n    * unfold cQ; rewrite compiler_length; auto.\n    * omega.\n  Qed.\n\n  Theorem gen_compiler_sound i1 v1 i2 v2 w1 : \n                    v1 ⋈ w1 /\\ (iP,cP) /X/ (i1,v1) ~~> (i2,v2)\n      -> exists w2, v2 ⋈ w2 /\\ (iQ,cQ) /Y/ (lnk i1,w1) ~~> (lnk i2,w2).\n  Proof.\n    intros (H1 & H2 & H3).\n    destruct compiler_sound with (2 := conj H1 H2) (linker := gen_linker) (Q := (iQ,cQ))\n      as (w2 & G1 & G2).\n    + apply compiler_subcode; auto.\n    + simpl fst in H3.\n      exists w2; split; auto.\n      split; auto; simpl.\n      rewrite <- gen_linker_out with i2; auto.\n  Qed.\n\n  Theorem gen_compiler_complete i1 v1 w1 :\n            v1 ⋈ w1 -> (iQ,gen_compiler) /Y/ (gen_linker i1,w1) ↓ -> (iP,cP) /X/ (i1,v1) ↓.\n  Proof.\n    apply compiler_complete, compiler_subcode; auto.\n  Qed.\n\n  Corollary gen_compiler_output v w i' v' : \n        v ⋈ w -> (iP,cP) /X/ (iP,v) ~~> (i',v') -> exists w', (iQ,gen_compiler) /Y/ (iQ,w) ~~> (code_end (iQ,cQ),w') /\\ v' ⋈ w'.\n  Proof.\n    intros H H1.\n    destruct gen_compiler_sound with (1 := conj H H1) as (w1 & H2 & H3).\n    exists w1.\n    simpl; rewrite <- gen_linker_out with i'.\n    + rewrite <- (linker_code_start ilen (iP,cP) iQ err) at 2; auto.\n    + apply H1.\n  Qed.\n\n  Corollary gen_compiler_terminates v w : \n          v ⋈ w -> (iQ,gen_compiler) /Y/ (iQ,w) ↓ -> (iP,cP) /X/ (iP,v) ↓.\n  Proof.\n    intros H (w' & H').\n    apply gen_compiler_complete with (1 := H).\n    unfold gen_linker; rewrite linker_code_start; auto; firstorder.\n  Qed.\n\n  Theorem gen_compiler_correction : \n           { lnk : nat -> nat \n           & { Q | fst Q = iQ \n                /\\ lnk iP = iQ\n                /\\ (forall i, out_code i P -> lnk i = code_end Q)\n                /\\ (forall i1 v1 w1 i2 v2, v1 ⋈ w1 /\\ P /X/ (i1,v1) ~~> (i2,v2)     -> exists w2,    v2 ⋈ w2 /\\ Q /Y/ (lnk i1,w1) ~~> (lnk i2,w2)) \n                /\\ (forall i1 v1 w1 j2 w2, v1 ⋈ w1 /\\ Q /Y/ (lnk i1,w1) ~~> (j2,w2) -> exists i2 v2, v2 ⋈ w2 /\\ P /X/ (i1,v1) ~~> (i2,v2) /\\ j2 = lnk i2) \n           } }.\n  Proof.\n    exists lnk, (iQ,cQ); split; auto; split; [ | split ].\n    + rewrite <- (linker_code_start ilen (iP,cP) iQ err); auto.\n    + rewrite P_eq; apply gen_linker_out.\n    + rewrite P_eq.\n      split.\n      * intros i1 v1 w1 i2 v2 H.\n        destruct gen_compiler_sound with (1 := H) as (w2 & H3 & H4).\n        exists w2; split; auto.\n      * intros i1 v1 w1 j2 w2 (H1 & H2).\n        destruct gen_compiler_complete with (1 := H1) (i1 := i1) \n          as ((i3,v3) & H3).\n        - exists (j2,w2); auto.\n        - destruct gen_compiler_sound with (1 := conj H1 H3) as (w3 & H4 & H5).\n          generalize (sss_output_fun step_Y_fun H2 H5); inversion 1.\n          exists i3, v3; auto.\n  Qed.\n\nEnd comp.\n", "meta": {"author": "uds-psl", "repo": "ill-undecidability", "sha": "0bfda1a33cb3411c8f2c0263e15d5c85c090721d", "save_path": "github-repos/coq/uds-psl-ill-undecidability", "path": "github-repos/coq/uds-psl-ill-undecidability/ill-undecidability-0bfda1a33cb3411c8f2c0263e15d5c85c090721d/coq/Code/compiler_correction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6608041710716309}}
{"text": "Require Import kernel_graph.\nRequire Import graph_examples.\nRequire Import Omega.\n\n(* A walk in G from x to y. *)\nRecord walk (G : Graph) (x y : nat) := {\n  walk_intermediate : nat ; (* stevilo vmesnih vozlisc *)\n  walk_length := S (S walk_intermediate) ; (* stevilo vozlisc *)\n  walk_func :> nat -> nat ;\n  walk_in_graph : forall i, i < walk_length -> walk_func i < V G ;\n  walk_connected : forall i, i < S walk_intermediate -> G (walk_func i) (walk_func (S i)) ;\n  walk_start : walk_func 0 = x ;\n  walk_end : walk_func (S walk_intermediate) = y\n}.\n\nArguments walk_intermediate {_ _ _} _.\nArguments walk_length {_ _ _} _.\n\nDefinition connected (G : Graph) :=\n  forall x y, x < G -> y < G -> x < y -> walk G x y.\n\nLemma prove_for_one (P : nat -> Prop) (i : nat) :\n  i < 1 -> P 0 -> P i.\nProof.\n  intros H G.\n  induction i.\n  - assumption.\n  - omega.\nQed.\n\nLemma prove_for_two (P : nat -> Prop) (i : nat) :\n  i < 2 -> P 0 -> P 1 -> P i.\nProof.\n  intros ilt2 H0 H1.\n  induction i.\n  - auto.\n  - induction i.\n    + auto.\n    + omega.\nQed.\n\nLemma complete_connected (n : nat) : connected (K n).\nProof.\n  intros x y xG yG x_lt_y.\n  simple refine {| walk_intermediate := 0 ;\n                   walk_func := (fun i => match i with\n                                       | 0 => x\n                                       | _ => y\n                                       end) |}.\n  - intros i H.\n    pattern i.\n    now apply prove_for_two.\n  - intros i H.\n    simpl ; pattern i.\n    apply prove_for_one.\n    + assumption.\n    + omega.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nLemma walk_transitive (G : Graph) (x y z : nat) :\n  x < G -> y < G -> z < G ->\n  walk G x y -> walk G y z -> walk G x z.\nProof.\n  intros ? ? ? s t.\n  assert (E : s (S (walk_intermediate s)) = t 0).\n  { rewrite walk_start. apply walk_end. }\n  simple refine {|\n           walk_intermediate := S (walk_intermediate s + walk_intermediate t) ;\n           walk_func := (fun i => if lt_dec i (walk_length s) then s i else t (S (i - walk_length s)))\n         |}.\n  - intros i ?.\n    simpl.\n    destruct (lt_dec i (walk_length s)).\n    + now apply walk_in_graph.\n    + apply walk_in_graph.\n      unfold walk_length.\n      omega.\n  - intros i ? ; simpl.\n    destruct (lt_dec i (walk_length s)) ; destruct (lt_dec (S i) (walk_length s)).\n    + apply walk_connected.\n      unfold walk_length in * ; omega.\n    + replace i with (walk_length s - 1) in *.\n      * { simpl.\n          rewrite Nat.sub_diag.\n          rewrite E.\n          apply walk_connected.\n          omega.\n        }\n      * omega.\n    + omega.\n    + unfold walk_length; simpl.\n      replace (S (i - S (walk_intermediate s))) with (S (S (i - S (S (walk_intermediate s))))).\n      * apply walk_connected.\n        unfold walk_length in *.\n        omega.\n      * unfold walk_length in *.\n        omega.\n  - now apply walk_start.\n  - simpl.\n    unfold walk_length in *.\n    destruct (lt_dec (S (S (walk_intermediate s + walk_intermediate t))) (S (S (walk_intermediate s)))).\n    + omega.\n    + rewrite minus_plus.\n      apply walk_end.\nDefined.\n\nDefinition idecomposable (G : Graph) :=\n  forall col : nat -> bool, all x : G, all y : G,\n  (col x = true -> col y = false ->\n   some a : G, some b : G, (col a = true /\\ col b = false /\\ G a b)).\n\nTheorem connected_then_idecomposable (G : Graph) : connected G -> idecomposable G.\nAdmitted.\n\nTheorem idecomposable_then_connected (G : Graph) : idecomposable G -> connected G.\nAdmitted.\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/connected.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6608041665669978}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nFrom LCAC Require Import seq_ext_base ssrnat_ext.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* insert *)\n\nDefinition insert A xs ys d n : seq A :=\n  take n ys ++ nseq (n - size ys) d ++ xs ++ drop n ys.\n\nSection Insert.\n\nVariable (A B : Type).\n\nLemma size_insert (xs ys : seq A) d n :\n  size (insert xs ys d n) = size xs + maxn n (size ys).\nProof. rewrite /insert !size_cat size_nseq size_take size_drop; ssromega. Qed.\n\nLemma map_insert (f : A -> B) xs ys d n :\n  map f (insert xs ys d n) = insert (map f xs) (map f ys) (f d) n.\nProof. by rewrite /insert !map_cat map_take map_nseq size_map map_drop. Qed.\n\nLemma nth_insert (xs ys : seq A) d d' n m :\n  nth d (insert xs ys d' n) m =\n  if m < n then nth d' ys m else\n  if m < n + size xs then nth d' xs (m - n) else nth d ys (m - size xs).\nProof.\nrewrite /insert !nth_cat size_take size_nseq -subnDA nth_drop nth_take'.\nhave ->: minn n (size ys) + (n - size ys) = n by ssromega.\nelimif_omega; rewrite nth_nseq H0 nth_default //; ssromega.\nQed.\n\nLemma cons_insert n y (xs ys : seq A) d :\n  y :: (insert xs ys d n) = insert xs (y :: ys) d n.+1.\nProof. by rewrite /insert /= subSS. Qed.\n\nLemma take_insert n (xs ys : seq A) d :\n  take n (insert xs ys d n) = take n ys ++ nseq (n - size ys) d.\nProof.\nby rewrite /insert take_cat size_take ltnNge geq_minl /= minnE subKn\n           ?leq_subr // take_cat size_nseq ltnn subnn take0 cats0.\nQed.\n\nLemma drop_insert n (xs ys : seq A) d :\n  drop (n + size xs) (insert xs ys d n) = drop n ys.\nProof.\nrewrite /insert !catA drop_cat !size_cat size_take size_nseq drop_addn.\nelimif_omega.\nQed.\n\nEnd Insert.\n\n(* context *)\n\nDefinition context A := (seq (option A)).\n\nNotation ctxnth := (nth None).\nNotation ctxindex xs n x := (Some x == ctxnth xs n).\nNotation ctxmap f xs := (map (omap f) xs).\nNotation ctxinsert xs ys n := (insert xs ys None n).\n\nSection Context.\n\nVariable (A : eqType).\n\nFixpoint ctxleq_rec (xs ys : context A) : bool :=\n  match xs, ys with\n    | [::], _ => true\n    | (None :: xs), [::] => ctxleq_rec xs [::]\n    | (None :: xs), (_ :: ys) => ctxleq_rec xs ys\n    | (Some _ :: _), [::] => false\n    | (Some x :: xs), (Some y :: ys) => (x == y) && ctxleq_rec xs ys\n    | (Some _ :: _), (None :: _) => false\n  end.\n\nDefinition ctxleq := nosimpl ctxleq_rec.\n\nInfix \"<=c\" := ctxleq (at level 70, no associativity).\n\nLemma ctxleqE xs ys :\n  (xs <=c ys) =\n  ((head None xs == head None ys) || (head None xs == None)) &&\n    (behead xs <=c behead ys).\nProof.\nmove: xs ys => [| [x |] xs] [| [y |] ys] //=.\nby case/boolP: (Some x == None) => // _; rewrite orbF.\nQed.\n\nLemma ctxleqP (xs ys : context A) :\n  reflect (forall n a, ctxindex xs n a -> ctxindex ys n a) (xs <=c ys).\nProof.\napply: (iffP idP); elim: xs ys => [| x xs IH].\n- by move => ys _ n a; rewrite nth_nil.\n- by case => [| y ys]; rewrite ctxleqE /= =>\n    /andP [] /orP [] /eqP -> H [] //= n a /(IH _ H) //; rewrite nth_nil.\n- by move => ys; rewrite ctxleqE eqxx orbT.\n- by case => [| y ys]; rewrite ctxleqE /= => H; apply/andP;\n    (split;\n     [ case: x H; rewrite ?eqxx ?orbT // => x H; rewrite (H 0 x) |\n       apply IH => n a /(H n.+1 a) ]).\nQed.\n\nLemma ctxleqxx (xs : context A) : xs <=c xs.\nProof. by apply/ctxleqP. Qed.\n\nLemma ctxleq_trans (xs ys zs : context A) :\n  xs <=c ys -> ys <=c zs -> xs <=c zs.\nProof. do 2 move/ctxleqP => ?; apply/ctxleqP; auto. Qed.\n\nLemma ctxleq_app (xs xs' ys ys' : context A) :\n  size xs = size xs' ->\n  (xs ++ ys) <=c (xs' ++ ys') = (xs <=c xs') && (ys <=c ys').\nProof.\nelim: xs xs' => [| x xs IH] [] //= x' xs' [].\nby rewrite ctxleqE /=; move/IH => ->; apply esym; rewrite ctxleqE /= andbA.\nQed.\n\nLemma ctxleq_appl (xs ys zs : context A) :\n  (xs ++ ys <=c xs ++ zs) = (ys <=c zs).\nProof. by rewrite ctxleq_app // ctxleqxx. Qed.\n\nLemma ctxleq_appr (xs ys : context A) : xs <=c (xs ++ ys).\nProof. by rewrite -{1}(cats0 xs) ctxleq_appl. Qed.\n\nLemma ctxindex_last ctx (x : A) : ctxindex (ctx ++ [:: Some x]) (size ctx) x.\nProof. by rewrite nth_cat ltnn subnn. Qed.\n\nLemma ctxinsert_leq n (xs ys zs : context A) :\n  ctxinsert xs ys n <=c zs ->\n  exists xs' ys', [&& zs <=c ctxinsert xs' ys' n, ctxinsert xs' ys' n <=c zs,\n                      xs <=c xs' & ys <=c ys'].\nProof.\nAbort.\n\nEnd Context.\n\nInfix \"<=c\" := ctxleq (at level 70, no associativity).\n\nLemma ctxnth_map A B (f : A -> B) xs n :\n  ctxnth (ctxmap f xs) n = omap f (ctxnth xs n).\nProof. by elim: xs n => [| x xs IH] []. Defined.\n\nLemma ctxindex_map (A B : eqType) (f : A -> B) xs n x :\n  ctxindex xs n x -> ctxindex (ctxmap f xs) n (f x).\nProof. by rewrite ctxnth_map => /eqP <-. Qed.\n\nLemma ctxleq_map (A B : eqType) (f : A -> B) xs ys :\n  xs <=c ys -> ctxmap f xs <=c ctxmap f ys.\nProof.\nmove/ctxleqP => H; apply/ctxleqP => n a.\nmove: (H n); rewrite -!(nth_map' (omap f) None).\nby case: (ctxnth xs n) => //= a' /(_ a' (eqxx _)) /eqP => <-.\nQed.\n\nHint Resolve ctxindex_map ctxleqxx ctxleq_trans ctxleq_app\n             ctxleq_appl ctxleq_appr ctxleq_map.\n\n(* Forall *)\n\nFixpoint Forall A (P : A -> Prop) xs :=\n  if xs is x :: xs then P x /\\ Forall P xs else True.\n\nLemma Forall_impl :\n  forall (A : Type) (P Q : A -> Prop) xs,\n  (forall a, P a -> Q a) -> Forall P xs -> Forall Q xs.\nProof. move => A P Q xs H; elim: xs; firstorder. Qed.\n\nLemma Forall_map (A B : Type) (f : A -> B) P xs :\n  Forall P (map f xs) <-> Forall (P \\o f) xs.\nProof. by elim: xs => //= x xs ->. Qed.\n\nLemma Forall_nth (A : Type) (P : A -> Prop) xs :\n  Forall P xs <-> (forall x m, m < size xs -> P (nth x xs m)).\nProof.\nelim: xs => //= x' xs [] IH IH'; split.\n- by case => H H0 x [] //= n; rewrite ltnS; apply IH.\n- move => H; split.\n  + by apply (H x' 0).\n  + by apply IH' => x m; apply (H x m.+1).\nQed.\n\nLemma allP' (A : eqType) (P : pred A) xs :\n  reflect (Forall P xs) (all P xs).\nProof.\napply (iffP idP); elim: xs => //= x xs IH.\n- by case/andP => -> /IH.\n- by case => ->.\nQed.\n\n(* zip *)\n\nFixpoint zipwith (A B C : Type) (f : A -> B -> C) xd yd\n         (xs : seq A) (ys : seq B) : seq C :=\n  match xs, ys with\n    | [::], ys => map (f xd) ys\n    | xs, [::] => map (f^~ yd) xs\n    | x :: xs', y :: ys' => f x y :: zipwith f xd yd xs' ys'\n  end.\n", "meta": {"author": "pi8027", "repo": "lambda-calculus", "sha": "a5c58079b944ec8f98d8a3fabc2c829bb32a1de7", "save_path": "github-repos/coq/pi8027-lambda-calculus", "path": "github-repos/coq/pi8027-lambda-calculus/lambda-calculus-a5c58079b944ec8f98d8a3fabc2c829bb32a1de7/coq/lib/seq_ext.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.6607287457464138}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nRequire Import ClassicalFacts.\n\nHint Unfold not: core.\n\nAxiom classic : forall P:Prop, P \\/ ~ P.\n\nLemma NNPP : forall p:Prop, ~ ~ p -> p.\nProof. hammer_hook \"Classical_Prop\" \"Classical_Prop.NNPP\".  \nunfold not; intros; elim (classic p); auto.\nintro NP; elim (H NP).\nQed.\n\n\n\nLemma Peirce : forall P:Prop, ((P -> False) -> P) -> P.\nProof. hammer_hook \"Classical_Prop\" \"Classical_Prop.Peirce\".  \nintros P H; destruct (classic P); auto.\nQed.\n\nLemma not_imply_elim : forall P Q:Prop, ~ (P -> Q) -> P.\nProof. hammer_hook \"Classical_Prop\" \"Classical_Prop.not_imply_elim\".  \nintros; apply NNPP; red.\nintro; apply H; intro; absurd P; trivial.\nQed.\n\nLemma not_imply_elim2 : forall P Q:Prop, ~ (P -> Q) -> ~ Q.\nProof. hammer_hook \"Classical_Prop\" \"Classical_Prop.not_imply_elim2\".  \ntauto.\nQed.\n\nLemma imply_to_or : forall P Q:Prop, (P -> Q) -> ~ P \\/ Q.\nProof. hammer_hook \"Classical_Prop\" \"Classical_Prop.imply_to_or\".  \nintros; elim (classic P); auto.\nQed.\n\nLemma imply_to_and : forall P Q:Prop, ~ (P -> Q) -> P /\\ ~ Q.\nProof. hammer_hook \"Classical_Prop\" \"Classical_Prop.imply_to_and\".  \nintros; split.\napply not_imply_elim with Q; trivial.\napply not_imply_elim2 with P; trivial.\nQed.\n\nLemma or_to_imply : forall P Q:Prop, ~ P \\/ Q -> P -> Q.\nProof. hammer_hook \"Classical_Prop\" \"Classical_Prop.or_to_imply\".  \ntauto.\nQed.\n\nLemma not_and_or : forall P Q:Prop, ~ (P /\\ Q) -> ~ P \\/ ~ Q.\nProof. hammer_hook \"Classical_Prop\" \"Classical_Prop.not_and_or\".  \nintros; elim (classic P); auto.\nQed.\n\nLemma or_not_and : forall P Q:Prop, ~ P \\/ ~ Q -> ~ (P /\\ Q).\nProof. hammer_hook \"Classical_Prop\" \"Classical_Prop.or_not_and\".  \nsimple induction 1; red; simple induction 2; auto.\nQed.\n\nLemma not_or_and : forall P Q:Prop, ~ (P \\/ Q) -> ~ P /\\ ~ Q.\nProof. hammer_hook \"Classical_Prop\" \"Classical_Prop.not_or_and\".  \ntauto.\nQed.\n\nLemma and_not_or : forall P Q:Prop, ~ P /\\ ~ Q -> ~ (P \\/ Q).\nProof. hammer_hook \"Classical_Prop\" \"Classical_Prop.and_not_or\".  \ntauto.\nQed.\n\nLemma imply_and_or : forall P Q:Prop, (P -> Q) -> P \\/ Q -> Q.\nProof. hammer_hook \"Classical_Prop\" \"Classical_Prop.imply_and_or\".  \ntauto.\nQed.\n\nLemma imply_and_or2 : forall P Q R:Prop, (P -> Q) -> P \\/ R -> Q \\/ R.\nProof. hammer_hook \"Classical_Prop\" \"Classical_Prop.imply_and_or2\".  \ntauto.\nQed.\n\nLemma proof_irrelevance : forall (P:Prop) (p1 p2:P), p1 = p2.\nProof. hammer_hook \"Classical_Prop\" \"Classical_Prop.proof_irrelevance\".  exact (proof_irrelevance_cci classic). Qed.\n\n\n\n\nLtac classical_right := match goal with\n|- ?X \\/ _ => (elim (classic X);intro;[left;trivial|right])\nend.\n\nLtac classical_left := match goal with\n|- _ \\/ ?X => (elim (classic X);intro;[right;trivial|left])\nend.\n\nRequire Export EqdepFacts.\n\nModule Eq_rect_eq.\n\nLemma eq_rect_eq :\nforall (U:Type) (p:U) (Q:U -> Type) (x:Q p) (h:p = p), x = eq_rect p Q x p h.\nProof. hammer_hook \"Classical_Prop\" \"Classical_Prop.Eq_rect_eq.eq_rect_eq\".  \nintros; rewrite proof_irrelevance with (p1:=h) (p2:=eq_refl p); reflexivity.\nQed.\n\nEnd Eq_rect_eq.\n\nModule EqdepTheory := EqdepTheory(Eq_rect_eq).\nExport EqdepTheory.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Logic/Classical_Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.6607287457464138}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** * A typeclass to ease the handling of decidable properties. *)\n\n(** A proposition is decidable whenever it is reflected by a boolean. *)\n\nClass Decidable (P : Prop) := {\n  Decidable_witness : bool;\n  Decidable_spec : Decidable_witness = true <-> P\n}.\n\n(** Alternative ways of specifying the reflection property. *)\n\nLemma Decidable_sound : forall P (H : Decidable P),\n  Decidable_witness = true -> P.\nProof.\nintros P H Hp; apply -> Decidable_spec; assumption.\nQed.\n\nLemma Decidable_complete : forall P (H : Decidable P),\n  P -> Decidable_witness = true.\nProof.\nintros P H Hp; apply <- Decidable_spec; assumption.\nQed.\n\nLemma Decidable_sound_alt : forall P (H : Decidable P),\n   ~ P -> Decidable_witness = false.\nProof.\nintros P [wit spec] Hd; simpl; destruct wit; tauto.\nQed.\n\nLemma Decidable_complete_alt : forall P (H : Decidable P),\n  Decidable_witness = false -> ~ P.\nProof.\nintros P [wit spec] Hd Hc; simpl in *; intuition congruence.\nQed.\n\n(** The generic function that should be used to program, together with some\n  useful tactics. *)\n\nDefinition decide P {H : Decidable P} := Decidable_witness (Decidable:=H).\n\nLtac _decide_ P H :=\n  let b := fresh \"b\" in\n  set (b := decide P) in *;\n  assert (H : decide P = b) by reflexivity;\n  clearbody b;\n  destruct b; [apply Decidable_sound in H|apply Decidable_complete_alt in H].\n\nTactic Notation \"decide\" constr(P) \"as\" ident(H) :=\n  _decide_ P H.\n\nTactic Notation \"decide\" constr(P) :=\n  let H := fresh \"H\" in _decide_ P H.\n\n(** Some usual instances. *)\n\nRequire Import Bool Arith ZArith.\n\nProgram Instance Decidable_eq_bool : forall (x y : bool), Decidable (eq x y) := {\n  Decidable_witness := Bool.eqb x y\n}.\nNext Obligation.\n apply eqb_true_iff.\nQed.\n\nProgram Instance Decidable_eq_nat : forall (x y : nat), Decidable (eq x y) := {\n  Decidable_witness := Nat.eqb x y\n}.\nNext Obligation.\n apply Nat.eqb_eq.\nQed.\n\nProgram Instance Decidable_le_nat : forall (x y : nat), Decidable (x <= y) := {\n  Decidable_witness := Nat.leb x y\n}.\nNext Obligation.\n apply Nat.leb_le.\nQed.\n\nProgram Instance Decidable_eq_Z : forall (x y : Z), Decidable (eq x y) := {\n  Decidable_witness := Z.eqb x y\n}.\nNext Obligation.\n apply Z.eqb_eq.\nQed.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Classes/DecidableClass.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789040926008, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.6607287345506918}}
{"text": "Require Export PropLang.\nRequire Export List.\nRequire Export Subcontext.\nRequire Export RelationClasses.\nRequire Export Morphisms.\nRequire Export NaturalDeduction.\n\nSection Hilbert.\n\nContext {atom : Type}.\n\nInductive hilbert_axiom : prop atom -> Prop :=\n| hilbert_axiom_I {P} : hilbert_axiom (P ⊃ P)\n| hilbert_axiom_K {P Q} : hilbert_axiom (P ⊃ Q ⊃ P)\n| hilbert_axiom_S {P Q R} : hilbert_axiom ((P ⊃ Q ⊃ R) ⊃ (P ⊃ Q) ⊃ P ⊃ R)\n| hilbert_axiom_bot_elim {P} : hilbert_axiom (⊥ ⊃ P)\n| hilbert_axiom_top_intro : hilbert_axiom ⊤\n| hilbert_axiom_and_intro {P Q} : hilbert_axiom (P ⊃ Q ⊃ P ∧ Q)\n| hilbert_axiom_and_elim {P Q R} : hilbert_axiom ((P ⊃ Q ⊃ R) ⊃ P ∧ Q ⊃ R)\n| hilbert_axiom_or_introl {P Q} : hilbert_axiom (P ⊃ P ∨ Q)\n| hilbert_axiom_or_intror {P Q} : hilbert_axiom (Q ⊃ P ∨ Q)\n| hilbert_axiom_or_elim {P Q R} : hilbert_axiom ((P ⊃ R) ⊃ (Q ⊃ R) ⊃ P ∨ Q ⊃ R).\n\nReserved Notation \"Γ ≤h Γ'\" (no associativity, at level 61).\n\n(* Γ ≤h Γ' means that there is a valid sequence of steps starting\n   from Γ with the additional steps along with Γ giving Γ'.\n   Note that for convenience we add each step at the front of the\n   list instead of the back. *)\nInductive hilbert_derivation : list (prop atom) -> list (prop atom) -> Prop :=\n| hilbert_empty {Γ} : Γ ≤h Γ\n| hilbert_axiom_derivation {Γ Γ' P} : Γ ≤h Γ' -> hilbert_axiom P ->\n  Γ ≤h P :: Γ'\n| hilbert_modus_ponens {Γ Γ' P Q} : Γ ≤h Γ' -> In P Γ' -> In (P ⊃ Q) Γ' ->\n  Γ ≤h Q :: Γ'\nwhere \"Γ ≤h Γ'\" := (hilbert_derivation Γ Γ').\n\nGlobal Instance hilbert_derivation_preord : PreOrder hilbert_derivation.\nProof.\nconstructor.\n+ intro Γ; constructor.\n+ intros Γ Γ' Γ'' H H0. induction H0.\n  - assumption.\n  - constructor 2; auto.\n  - constructor 3 with (P := P); eauto.\nQed.\n\nLemma hilbert_derivation_tail : forall Γ Γ', Γ ≤h Γ' ->\n  exists Γ'', Γ' = Γ'' ++ Γ.\nProof.\ninduction 1.\n+ exists nil; reflexivity.\n+ destruct IHhilbert_derivation as [Γ'']. exists (P :: Γ'').\n  rewrite H1. reflexivity.\n+ destruct IHhilbert_derivation as [Γ'']. exists (Q :: Γ'').\n  rewrite H2. reflexivity.\nQed.\n\nLemma hilbert_derivation_context_extension :\n  forall Γ Γ' Γ'', Γ ⊆ Γ' -> Γ ≤h Γ'' ++ Γ ->\n  Γ' ≤h Γ'' ++ Γ'.\nProof.\nintros. remember (Γ'' ++ Γ) as Γ₀. revert Γ'' HeqΓ₀. induction H0.\n+ intros. change (nil ++ Γ = Γ'' ++ Γ) in HeqΓ₀.\n  apply app_inv_tail in HeqΓ₀. subst; simpl. constructor.\n+ intros. destruct (hilbert_derivation_tail _ _ H0) as [Γh]. subst.\n  pose proof (IHhilbert_derivation H Γh eq_refl).\n  change ((P :: Γh) ++ Γ = Γ'' ++ Γ) in HeqΓ₀.\n  apply app_inv_tail in HeqΓ₀. subst. simpl. constructor 2; auto.\n+ intros. destruct (hilbert_derivation_tail _ _ H0) as [Γh]. subst.\n  pose proof (IHhilbert_derivation H Γh eq_refl).\n  change ((Q :: Γh) ++ Γ = Γ'' ++ Γ) in HeqΓ₀.\n  apply app_inv_tail in HeqΓ₀. subst. simpl.\n  constructor 3 with (P := P); auto.\n  - destruct (in_app_or _ _ _ H1).\n    * apply in_or_app; left; assumption.\n    * apply in_or_app; right; auto.\n  - destruct (in_app_or _ _ _ H2).\n    * apply in_or_app; left; assumption.\n    * apply in_or_app; right; auto.\nQed.\n\nInductive hilbert_proves (Γ : list (prop atom)) (P : prop atom) : Prop :=\n| hilbert_derivation_proves : forall Γ', Γ ≤h (P :: Γ') -> hilbert_proves Γ P.\nNotation \"Γ ⊢h P\" := (hilbert_proves Γ P) (no associativity, at level 61).\n\nProposition hilbert_assumption {Γ P} : In P Γ -> Γ ⊢h P.\nProof.\nintros. apply hilbert_derivation_proves with (Γ' := P ⊃ P :: Γ).\napply @hilbert_modus_ponens with (P := P).\n+ apply hilbert_axiom_derivation.\n  - constructor.\n  - constructor.\n+ right; assumption.\n+ left; reflexivity.\nQed.\n\nGlobal Instance hilbert_context_extension :\n  Proper (subcontext ++> eq ==> Basics.impl) hilbert_proves.\nProof.\nintros Γ Γ' ? P Q [] ?. destruct H0. destruct (hilbert_derivation_tail _ _ H0).\ndestruct x.\n+ simpl in H1. subst. apply hilbert_assumption. apply H. prove_In.\n+ injection H1; intros; subst. change (Γ ≤h (p :: x) ++ Γ) in H0.\n  pose proof (hilbert_derivation_context_extension _ _ _ H H0).\n  eauto using hilbert_derivation_proves.\nQed.\n\nProposition hilbert_cut {Γ P Q} :\n  Γ ⊢h P -> P :: Γ ⊢h Q -> Γ ⊢h Q.\nProof.\ndestruct 1. intros.\nsimple refine (let H1 := hilbert_context_extension (P :: Γ) (P :: Γ') _ _ _ eq_refl H0 in _).\n+ rewrite subcontext_cons; split.\n  - prove_In.\n  - destruct (hilbert_derivation_tail _ _ H). red; intros.\n    rewrite H1. apply in_or_app; right; assumption.\n+ destruct H1. rewrite <- H in H1. eauto using hilbert_derivation_proves.\nQed.\n\nInductive hilbert_impl_lift (Γ Γ' : list (prop atom)) (P : prop atom) : Prop :=\n| hilbert_impl_lift_intro : forall Γ'', Γ ≤h Γ'' ->\n  (forall Q, In Q Γ' -> In (P ⊃ Q) Γ'') -> hilbert_impl_lift Γ Γ' P.\n\nLemma hilbert_cond_derivation : forall Γ Γ' P, P :: Γ ≤h Γ' ->\n  hilbert_impl_lift Γ Γ' P.\nProof.\nintros. remember (P :: Γ) as PΓ. revert P Γ HeqPΓ.\ninduction H; intros; subst.\n+ assert (forall Γ, Γ ⊆ Γ0 -> hilbert_impl_lift Γ0 Γ P).\n  - induction Γ.\n    * exists Γ0.\n      { constructor. }\n      { destruct 1. }\n    * rewrite subcontext_cons. destruct 1. destruct (IHΓ H0).\n      assert (Γ0 ≤h a ⊃ P ⊃ a :: Γ'') by\n        eauto using hilbert_derivation, hilbert_axiom_K.\n      assert (Γ0 ≤h P ⊃ a :: a ⊃ P ⊃ a :: Γ'').\n      { apply @hilbert_modus_ponens with (P := a); auto; try prove_In.\n        right. destruct (hilbert_derivation_tail _ _ H1).\n        rewrite H4. apply in_or_app; right; assumption. }\n      { apply hilbert_impl_lift_intro with (1 := H4).\n        destruct 1; subst; (prove_In || (do 2 right; auto)). }\n  - destruct (H Γ0); try reflexivity.\n    assert (Γ0 ≤h P ⊃ P :: Γ'') by\n      eauto using hilbert_derivation, hilbert_axiom_I.\n    apply hilbert_impl_lift_intro with (1 := H2).\n    destruct 1; subst; (prove_In || (right; auto)).\n+ destruct (IHhilbert_derivation _ _ eq_refl).\n  assert (Γ0 ≤h P :: Γ'') by eauto using hilbert_derivation.\n  assert (Γ0 ≤h P ⊃ P0 ⊃ P :: P :: Γ'') by eauto using\n    hilbert_derivation, hilbert_axiom_K.\n  assert (Γ0 ≤h P0 ⊃ P :: P ⊃ P0 ⊃ P :: P :: Γ'') by\n    (apply @hilbert_modus_ponens with (P := P); auto; prove_In).\n  apply hilbert_impl_lift_intro with (1 := H5).\n  destruct 1; subst; (prove_In || (do 3 right; auto)).\n+ destruct (IHhilbert_derivation _ _ eq_refl).\n  pose proof (H3 _ H0); pose proof (H3 _ H1).\n  assert (Γ0 ≤h (P0 ⊃ P ⊃ Q) ⊃ (P0 ⊃ P) ⊃ (P0 ⊃ Q) :: Γ'') by\n    eauto using hilbert_derivation, hilbert_axiom_S.\n  assert (Γ0 ≤h (P0 ⊃ P) ⊃ P0 ⊃ Q ::\n          (P0 ⊃ P ⊃ Q) ⊃ (P0 ⊃ P) ⊃ (P0 ⊃ Q) :: Γ'') by\n    (apply @hilbert_modus_ponens with (P := P0 ⊃ P ⊃ Q); auto;\n     (prove_In || (right; auto))).\n  assert (Γ0 ≤h P0 ⊃ Q :: (P0 ⊃ P) ⊃ P0 ⊃ Q ::\n          (P0 ⊃ P ⊃ Q) ⊃ (P0 ⊃ P) ⊃ (P0 ⊃ Q) :: Γ'') by\n    (apply @hilbert_modus_ponens with (P := P0 ⊃ P); auto;\n     (prove_In || (right; right; auto))).\n  apply hilbert_impl_lift_intro with (1 := H8).\n  destruct 1; subst; (prove_In || (do 3 right; auto)).\nQed.\n\nTheorem hilbert_cond_proof {P Q Γ} :\n  P :: Γ ⊢h Q -> Γ ⊢h P ⊃ Q.\nProof.\nintros. destruct H. destruct (hilbert_cond_derivation _ _ _ H).\nassert (In (P ⊃ Q) Γ'') by (apply H1; prove_In).\ndestruct (hilbert_assumption H2). rewrite <- H0 in H3.\neauto using hilbert_derivation_proves.\nQed.\n\n\nProposition hilbert_axiom_soundness {Γ P} :\n  hilbert_axiom P -> Γ ⊢ P.\nProof.\ndestruct 1.\n+ apply ND_cond_proof. apply ND_assumption. prove_In.\n+ apply ND_cond_proof. apply ND_cond_proof. apply ND_assumption. prove_In.\n+ do 3 apply ND_cond_proof. apply @ND_modus_ponens with (P := Q).\n  - apply @ND_modus_ponens with (P := P); apply ND_assumption; prove_In.\n  - apply @ND_modus_ponens with (P := P); apply ND_assumption; prove_In.\n+ apply ND_cond_proof. apply ND_exfalso_quodlibet.\n  apply ND_assumption; prove_In.\n+ apply ND_True_intro.\n+ do 2 apply ND_cond_proof. apply ND_and_intro; apply ND_assumption; prove_In.\n+ do 2 apply ND_cond_proof. apply @ND_and_elim with (P := P) (Q := Q).\n  - apply ND_assumption; prove_In.\n  - apply @ND_modus_ponens with (P := Q).\n    * apply @ND_modus_ponens with (P := P); apply ND_assumption; prove_In.\n    * apply ND_assumption; prove_In.\n+ apply ND_cond_proof. apply ND_or_introl; apply ND_assumption; prove_In.\n+ apply ND_cond_proof. apply ND_or_intror; apply ND_assumption; prove_In.\n+ do 3 apply ND_cond_proof. apply @ND_proof_by_cases with (P := P) (Q := Q).\n  - apply ND_assumption; prove_In.\n  - apply @ND_modus_ponens with (P := P); apply ND_assumption; prove_In.\n  - apply @ND_modus_ponens with (P := Q); apply ND_assumption; prove_In.\nQed.\n\nProposition hilbert_derivation_soundness {Γ Γ'} :\n  Γ ≤h Γ' -> forall P, In P Γ' -> Γ ⊢ P.\nProof.\ninduction 1.\n+ apply @ND_assumption.\n+ destruct 1; subst; auto using hilbert_axiom_soundness.\n+ destruct 1; subst; auto.\n  apply @ND_modus_ponens with (P := P); auto.\nQed.\n\nTheorem hilbert_soundness {Γ P} : Γ ⊢h P -> Γ ⊢ P.\nProof.\ndestruct 1. refine (hilbert_derivation_soundness H _ _). prove_In.\nQed.\n\nProposition hilbert_proves_axiom {Γ P} : hilbert_axiom P -> Γ ⊢h P.\nProof.\nintros. exists Γ. eauto using hilbert_derivation.\nQed.\n\nTheorem hilbert_completeness {Γ P} : Γ ⊢ P -> Γ ⊢h P.\nProof.\ninduction 1.\n+ destruct IHND_proves. assert (Γ ≤h ⊥ ⊃ P :: ⊥ :: Γ') by\n    eauto using hilbert_derivation, hilbert_axiom_bot_elim.\n  assert (Γ ≤h P :: ⊥ ⊃ P :: ⊥ :: Γ') by\n    (apply @hilbert_modus_ponens with (P := ⊥); auto; prove_In).\n  eauto using hilbert_derivation_proves.\n+ apply hilbert_proves_axiom. constructor.\n+ destruct IHND_proves. assert (Γ ≤h P ⊃ P ∨ Q :: P :: Γ') by\n    eauto using hilbert_derivation, hilbert_axiom_or_introl.\n  assert (Γ ≤h P ∨ Q :: P ⊃ P ∨ Q :: P :: Γ') by\n    (apply @hilbert_modus_ponens with (P := P); auto; prove_In).\n  eauto using hilbert_derivation_proves.\n+ destruct IHND_proves. assert (Γ ≤h Q ⊃ P ∨ Q :: Q :: Γ') by\n    eauto using hilbert_derivation, hilbert_axiom_or_intror.\n  assert (Γ ≤h P ∨ Q :: Q ⊃ P ∨ Q :: Q :: Γ') by\n    (apply @hilbert_modus_ponens with (P := Q); auto; prove_In).\n  eauto using hilbert_derivation_proves.\n+ apply hilbert_cond_proof in IHND_proves2;\n  apply hilbert_cond_proof in IHND_proves3.\n  apply (hilbert_cut IHND_proves1).\n  apply @hilbert_cut with (P := P ⊃ R).\n  - refine (hilbert_context_extension _ _ _ _ _ eq_refl IHND_proves2).\n    prove_subcontext.\n  - apply @hilbert_cut with (P := Q ⊃ R).\n    * refine (hilbert_context_extension _ _ _ _ _ eq_refl IHND_proves3).\n      prove_subcontext.\n    * set (Γ' := Q ⊃ R :: P ⊃ R :: P ∨ Q :: Γ).\n      assert (Γ' ≤h (P ⊃ R) ⊃ (Q ⊃ R) ⊃ P ∨ Q ⊃ R :: Γ') by\n        eauto using hilbert_derivation, hilbert_axiom_or_elim.\n      assert (Γ' ≤h (Q ⊃ R) ⊃ P ∨ Q ⊃ R :: (P ⊃ R) ⊃ (Q ⊃ R) ⊃ P ∨ Q ⊃ R :: Γ') by\n        (apply @hilbert_modus_ponens with (P := P ⊃ R); auto;\n         unfold Γ'; prove_In).\n      assert (Γ' ≤h P ∨ Q ⊃ R :: (Q ⊃ R) ⊃ P ∨ Q ⊃ R ::\n        (P ⊃ R) ⊃ (Q ⊃ R) ⊃ P ∨ Q ⊃ R :: Γ') by\n        (apply @hilbert_modus_ponens with (P := Q ⊃ R); auto;\n        unfold Γ'; prove_In).\n      assert (Γ' ≤h R :: P ∨ Q ⊃ R :: (Q ⊃ R) ⊃ P ∨ Q ⊃ R ::\n        (P ⊃ R) ⊃ (Q ⊃ R) ⊃ P ∨ Q ⊃ R :: Γ') by\n        (apply @hilbert_modus_ponens with (P := P ∨ Q); auto;\n        unfold Γ'; prove_In).\n      eauto using hilbert_derivation_proves.\n+ apply (hilbert_cut IHND_proves1).\n  apply @hilbert_cut with (P := Q).\n  - refine (hilbert_context_extension _ _ _ _ _ eq_refl IHND_proves2).\n    prove_subcontext.\n  - set (Γ' := Q :: P :: Γ).\n    assert (Γ' ≤h P ⊃ Q ⊃ P ∧ Q :: Γ') by\n      eauto using hilbert_derivation, hilbert_axiom_and_intro.\n    assert (Γ' ≤h Q ⊃ P ∧ Q :: P ⊃ Q ⊃ P ∧ Q :: Γ') by\n      (apply @hilbert_modus_ponens with (P := P); auto;\n      unfold Γ'; prove_In).\n    assert (Γ' ≤h P ∧ Q :: Q ⊃ P ∧ Q :: P ⊃ Q ⊃ P ∧ Q :: Γ') by\n      (apply @hilbert_modus_ponens with (P := Q); auto;\n      unfold Γ'; prove_In).\n    eauto using hilbert_derivation_proves.\n+ apply (hilbert_cut IHND_proves1).\n  apply @hilbert_cut with (P := P ⊃ Q ⊃ R).\n  - do 2 apply hilbert_cond_proof.\n    refine (hilbert_context_extension _ _ _ _ _ eq_refl IHND_proves2).\n    prove_subcontext.\n  - set (Γ' := P ⊃ Q ⊃ R :: P ∧ Q :: Γ).\n    assert (Γ' ≤h (P ⊃ Q ⊃ R) ⊃ P ∧ Q ⊃ R :: Γ') by\n      eauto using hilbert_derivation, hilbert_axiom_and_elim.\n    assert (Γ' ≤h P ∧ Q ⊃ R :: (P ⊃ Q ⊃ R) ⊃ P ∧ Q ⊃ R :: Γ') by\n      (apply @hilbert_modus_ponens with (P := P ⊃ Q ⊃ R); auto;\n       unfold Γ'; prove_In).\n    assert (Γ' ≤h R :: P ∧ Q ⊃ R :: (P ⊃ Q ⊃ R) ⊃ P ∧ Q ⊃ R :: Γ') by\n      (apply @hilbert_modus_ponens with (P := P ∧ Q); auto;\n      unfold Γ'; prove_In).\n    eauto using hilbert_derivation_proves.\n+ auto using hilbert_cond_proof.\n+ apply (hilbert_cut IHND_proves1).\n  apply @hilbert_cut with (P := P).\n  - refine (hilbert_context_extension _ _ _ _ _ eq_refl IHND_proves2).\n    prove_subcontext.\n  - set (Γ' := P :: P ⊃ Q :: Γ). exists Γ'.\n    apply @hilbert_modus_ponens with (P := P); (apply hilbert_empty ||\n      (unfold Γ'; prove_In)).\n+ auto using hilbert_assumption.\n+ eauto using hilbert_cut.\nQed.\n\nTheorem ND_hilbert_equiv : forall Γ P, Γ ⊢ P <-> Γ ⊢h P.\nProof.\nsplit; [ apply hilbert_completeness | apply hilbert_soundness ].\nQed.\n\nEnd Hilbert.\n\nNotation \"Γ ≤h Γ'\" := (hilbert_derivation Γ Γ') (no associativity, at level 61).\nNotation \"Γ ⊢h P\" := (hilbert_proves Γ P) (no associativity, at level 61).\n", "meta": {"author": "dschepler", "repo": "coq-sequent-calculus", "sha": "5e87c4f4f61d01ecf990e4e25b9280e6422a73e0", "save_path": "github-repos/coq/dschepler-coq-sequent-calculus", "path": "github-repos/coq/dschepler-coq-sequent-calculus/coq-sequent-calculus-5e87c4f4f61d01ecf990e4e25b9280e6422a73e0/Hilbert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563823, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6606824723639138}}
{"text": "(**\nSystem F\n\nexamples/ssr/POPLmark.v をもとに作成した。\n\n@suharahiromichi 2014_07_23\n *)\n\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import AutosubstSsr Context.\n\n(** **** Syntax *)\n\nInductive type : Type :=\n| TyVar (x : var)\n| Arr (A1 A2 : type)\n| All (A2 : {bind type}).\n\nInductive term :=\n| TeVar (x : var)\n| Abs (A : type) (s : {bind term})\n| App (s t : term)\n| TAbs (s : {bind type in term})\n| TApp (s : term) (A : type).\n\n(** **** Substitutions *)\n\nInstance Ids_type : Ids type. derive. Defined.\nInstance Rename_type : Rename type. derive. Defined.\nInstance Subst_type : Subst type. derive. Defined.\nInstance SubstLemmas_type : SubstLemmas type. derive. Qed.\nInstance HSubst_term : HSubst type term. derive. Defined.\nInstance Ids_term : Ids term. derive. Defined.\nInstance Rename_term : Rename term. derive. Defined.\nInstance Subst_term : Subst term. derive. Defined.\nInstance HSubstLemmas_term : HSubstLemmas type term. derive. Qed.\nInstance SubstHSubstComp_type_term : SubstHSubstComp type term. derive. Qed.\nInstance SubstLemmas_term : SubstLemmas term. derive. Qed.\n\n(** **** Subtyping *)\n\nNotation \"Gamma `_ x\" := (dget Gamma x).    (* not used *)\nNotation \"Gamma ``_ x\" := (get Gamma x) (at level 3, x at level 2,\n  left associativity, format \"Gamma ``_ x\").\n\n(** **** Typing *)\n\nReserved Notation \"'TY' Gamma |- A : B\"\n  (at level 68, A at level 99, no associativity,\n   format \"'TY'  Gamma  |-  A  :  B\").\nInductive ty (Gamma : list type) : term -> type -> Prop :=\n| ty_var x :\n    x < size Gamma ->\n    TY Gamma |- TeVar x : Gamma``_x\n| ty_abs A B s :\n    TY A::Gamma |- s : B ->\n    TY Gamma |- Abs A s : Arr A B\n| ty_app A B s t:\n    TY Gamma |- s : Arr A B ->\n    TY Gamma |- t : A ->\n    TY Gamma |- App s t : B\n| ty_tabs A s :\n    TY Gamma..[ren (+1)] |- s : A ->\n    TY Gamma |- TAbs s : All A\n| ty_tapp A B s :\n    TY Gamma |- s : All A ->\n    TY Gamma |- TApp s B : A.[B/]\nwhere \"'TY' Gamma |- s : A\" := (ty Gamma s A).\n\nDefinition value (s : term) : bool :=\n  match s with Abs _ _ | TAbs _ => true | _ => false end.\n\nReserved Notation \"'EV' s => t\"\n  (at level 68, s at level 80, no associativity, format \"'EV'   s  =>  t\").\nInductive eval : term -> term -> Prop :=\n| E_AppAbs A s t : EV App (Abs A s) t => s.[t/]\n| E_TAppTAbs s B : EV TApp (TAbs s) B => s.|[B/]\n| E_AppFun s s' t :\n     EV s => s' ->\n     EV App s t => App s' t\n| E_AppArg s s' v:\n     EV s => s' -> value v ->\n     EV App v s => App v s'\n| E_TypeFun s s' A :\n     EV s => s' ->\n     EV TApp s A => TApp s' A\nwhere \"'EV' s => t\" := (eval s t).\n\n(** **** Preservation *)\n\nLemma ty_ren Gamma1 Gamma2 s A xi :\n  (forall x, x < size Gamma1 -> xi x < size Gamma2) ->\n  (forall x, x < size Gamma1 -> Gamma2``_(xi x) = Gamma1``_x) ->\n  TY Gamma1 |- s : A ->\n  TY Gamma2 |- s.[ren xi] : A.\nProof with eauto using ty.\n  move=> h1 h2 ty.\n  elim: ty Gamma2 xi h1 h2 => {Gamma1 s A} /=...\n  - move=> Gamma1 x lt Gamma2 xi h1 h2.\n    rewrite -h2 //.\n    apply: ty_var...\n  - move=> Gamma1 A B s _ ih Gamma2 xi h1 h2.\n    asimpl.\n    apply: ty_abs.\n    by apply: ih => [[|x/h1]|[|x/h2]].\n  - move=> Gamma1 A B s ih Gamma2 xi h1 h2.\n    apply: ty_tabs.\n    apply: ih => x.\n    + by rewrite !size_map => /h1.\n    + rewrite !size_map => lt.\n      rewrite !get_map ?h2 //.\n      exact: h1.\nQed.\n\nLemma ty_evar Gamma x A :\n  A = Gamma``_x ->\n  x < size Gamma ->\n  TY Gamma |- TeVar x : A.\nProof.\n  move ->.\n  exact: ty_var.\nQed.\n\nLemma ty_etapp Gamma A C D s :\n  D = A.[C/] ->\n  TY Gamma |- s : All A ->\n  TY Gamma |- TApp s C : D.\nProof.\n  move->.\n  exact: ty_tapp.\nQed.\n\nLemma ty_weak Gamma s A B :\n  TY Gamma |- s : A ->\n  TY B::Gamma |- s.[ren (+1)] : A.\nProof.\n  exact: ty_ren.\nQed.\n\nLemma ty_hsubst Gamma s A sigma :\n  TY Gamma |- s : A ->\n  TY Gamma..[sigma] |- s.|[sigma] : A.[sigma].\nProof with eauto using ty.\n  move=> ty.\n  elim: ty sigma => {Gamma s A} /=...\n  - move=> Gamma x lt sigma.\n    apply: ty_evar.\n    + by rewrite get_map.\n    + by rewrite size_map.\n  - move=> Gamma A s ty ih sigma.\n    apply ty_tabs.\n    specialize (ih (up sigma)).\n    move: ih.\n    asimpl.\n    by apply.\n  - move=> Gamma A B s ty ih sigma.\n    asimpl.\n    Check ty_etapp.\n    eapply (ty_etapp _ (A.[up sigma]) _ _ (s.|[sigma])).\n    + by autosubst.\n    + by eapply ih.\nQed.\n\nLemma ty_tweak Gamma s A :\n  TY Gamma |- s : A ->\n  TY Gamma..[ren (+1)] |- s.|[ren (+1)] : A.[ren (+1)].\nProof.\n  by apply: ty_hsubst.\nQed.\n\nLemma ty_subst Gamma1 Gamma2 s A sigma :\n  (forall x, x < size Gamma1 -> TY Gamma2 |- sigma x : Gamma1``_x) ->\n  TY Gamma1 |- s : A ->\n  TY Gamma2 |- s.[sigma] : A.\nProof with eauto using ty.\n  move=> h ty.\n  elim: ty Gamma2 sigma h => {Gamma1 s A} /=...\n  - move=> Gamma1 A B s _ ih Gamma2 sigma h /=.\n    apply: ty_abs.\n    move: ih.\n    apply; move=> [/= | x /h /ty_weak].\n    + move=> Hsz.\n      by apply: ty_var.\n    + autosubst.\n  - move=> Gamma1 A B s ih Gamma2 sigma h.\n    apply: ty_tabs.\n    apply: ih.\n    move=> x.\n    rewrite size_map => lt.\n    rewrite get_map //=.\n    exact/ty_tweak/h.                       (* by apply ty_tweak; apply h *)\nQed.\n\n(* ***** *)\n\nLemma ty_beta Gamma s t A B :\n  TY Gamma |- t : A ->\n  TY A::Gamma |- s : B ->\n  TY Gamma |- s.[t/] : B.\nProof.\n  move=> ty.\n  apply: ty_subst => -[|n lt] //=.\n  exact: ty_var.\nQed.\n\nLemma ty_betaT' Gamma s B C :\n  TY Gamma..[ren (+1)]..[C/] |- s.|[C/] : B.[C/] ->\n  TY Gamma |- s.|[C/] : B.[C/].\nProof.\n  autosubst.\nQed.\n\nLemma ty_betaT Gamma s A B C :\n  C = A ->\n  TY Gamma..[ren (+1)] |- s : B ->\n  TY Gamma |- s.|[C/] : B.[C/].\nProof.\n  move=> subt ty.\n  apply ty_betaT'.\n  apply: ty_hsubst ty.\nQed.\n\n(* ***** *)\n\nLemma eqn_abs : forall A A' s s', Abs A s = Abs A' s' -> A = A' /\\ s = s'.\nProof.\n  move=> A A' s s' H.\n  inversion H.\n  by [].\nQed.\n\nLemma eqn_arr : forall A A' B B', Arr A B = Arr A' B' -> A = A' /\\ B = B'.\nProof.\n  move=> A A' B B' H.\n  by inv H.\nQed.\n\nLemma eqn_tabs : forall s s', TAbs s = TAbs s' -> s = s'.\nProof.\n  move=> s s' H.\n  inversion H.\n  by [].\nQed.\n\nLemma eqn_all : forall s s', All s = All s' -> s = s'.\nProof.\n  move=> s s' H.\n  inversion H.\n  by [].\nQed.\n\nLemma ty_inv_abs' Gamma A A' B T s :\n  TY Gamma |- Abs A s : T ->\n  T = Arr A' B ->\n  TY A'::Gamma |- s : B.\nProof.\n  move e: (Abs A s) => t ty.\n  elim: ty A A' B s e; move => {Gamma t T} //.\n - move=> Gamma A B s h ih A' A'' B' s' eqn sub2.\n   apply eqn_abs in eqn. destruct eqn as [eqn1 eqn2].\n   apply eqn_arr in sub2. destruct sub2 as [sub21 sub22].\n   subst.\n   by apply h.\nQed.\n\nLemma ty_inv_abs Gamma A A' B s :\n  TY Gamma |- Abs A s : Arr A' B ->\n  TY A'::Gamma |- s : B.\nProof.\n  move=> ty. apply: ty_inv_abs'.\n  - by apply ty.\n  - by [].\nQed.\n\n(* ***** *)\n\nLemma ty_inv_tabs' Gamma B T s :\n  TY Gamma |- TAbs s : T ->\n  T = All B ->\n  TY Gamma..[ren(+1)] |- s : B.\nProof.\n  move e: (TAbs s) => t ty.\n  elim: ty B s e => {Gamma t T} //.\n  move=> Gamma A s ty ih A' s' e1 e2.\n  apply eqn_tabs in e1.\n  apply eqn_all in e2.\n  subst.\n  by apply: ty0.\nQed.\n\nLemma ty_inv_tabs Gamma B s :\n  TY Gamma |- TAbs s : All B ->\n  TY Gamma..[ren(+1)] |- s : B.\nProof.\n  move=> ty.\n  apply: (ty_inv_tabs' _ _ (All B)).\n    - by apply ty.\n    - by [].\nQed.\n\n(* ***** *)\n\nTheorem preservation Gamma s t A :\n  TY Gamma |- s : A -> EV s => t -> TY Gamma |- t : A.\nProof with eauto using ty.\n  move=> ty. elim: ty t => {Gamma s A}...\n  - move=> Gamma x _ t ev. by inv ev.\n  - move=> Gamma A B s _ i t ev. by inv ev.\n  - move=> Gamma A B s t ty1 ih1 ty2 ih2 u ev.\n    inversion ev.               (* inv ev *)\n    subst.\n    Check ty_inv_abs.\n    (* move: ty1. move/ty_inv_abs. exact: ty_beta. *)\n    apply ty_inv_abs in ty1. move: ty1. exact: ty_beta.\n    eauto using ty.\n    eauto using ty.\n  - move=> Gamma A B s _ t ev. by inv ev.\n  - move=> Gamma A B s ty ih t ev. inv ev.\n      Check E_TAppTAbs.\n      Check ty_tapp Gamma A B s0.\n    + apply ty_inv_tabs in ty0. move: ty0.\n    (* move: ty0 => /ty_inv_tabs H. *)\n      apply: (ty_betaT _ s0 _ _)...\n    + apply: ty_tapp...\nQed.\n\n(** **** Progress *)\n\nDefinition is_abs s := if s is Abs _ _ then true else false.\nDefinition is_tabs s := if s is TAbs _ then true else false.\n\nLemma canonical_arr Gamma s A B :\n  TY Gamma |- s : Arr A B -> value s -> is_abs s.\nProof.\n  move=> ty.\n  by inv ty.\nQed.\n\nLemma canonical_all Gamma s A :\n  TY Gamma |- s : All A -> value s -> is_tabs s.\nProof.\n  move=> ty.\n  by inv ty.\nQed.\n\nLemma ev_progress' Gamma s A :\n  TY Gamma |- s : A -> Gamma = [::] -> value s \\/ exists t, EV s => t.\nProof with eauto using eval.\n  elim=> {Gamma s A} /=; try solve [intuition].\n  - move=> Gamma x lt eqn. by subst.\n  - move=> Gamma A B s t ty1 ih1 _ ih2 eqn. right.\n    case: (ih1 eqn) => {ih1} [vs|[s' h1]]...\n    case: (ih2 eqn) => {ih2 eqn} [vt|[t' h2]]...\n    case: s {ty1 vs} (canonical_arr _ _ _ _ ty1 vs) => //...\n  - move=> Gamma A B s ty ih eqn. right.\n    case: (ih eqn) => {ih eqn}[vs|[s' h]]...\n    case: s {ty vs} (canonical_all _ _ _ ty vs) => //.\n    move=> s H.\n    exists s.|[B/].\n    apply E_TAppTAbs.\nQed.\n\nTheorem ev_progress s A:\n  TY nil |- s : A -> value s \\/ exists t,  EV s => t.\nProof.\n  move=> ty.\n  exact: ev_progress' ty _.\nQed.\n\n(* Local Variables: *)\n(* coq-load-path: ((\".\" \"Ssr\")) *)\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/autosubst/ssr_autosubst_ctx_SystemF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579722, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.6606824710252956}}
{"text": "(***************************************************************************\n* Safety for STLC in Wright & Felleisen style - Definitions                *\n* Arthur Charguéraud, July 2007                                            *\n***************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibLN.\n\n(** Grammar of types. *)\n\nInductive typ : Set :=\n  | typ_var   : var -> typ\n  | typ_arrow : typ -> typ -> typ.\n\n(** Grammar of pre-terms. *)\n\nInductive trm : Set :=\n  | trm_bvar : nat -> trm\n  | trm_fvar : var -> trm\n  | trm_abs  : trm -> trm\n  | trm_app  : trm -> trm -> trm.\n\n(** Opening up abstractions *)\n\nFixpoint open_rec (k : nat) (u : trm) (t : trm) {struct t} : trm :=\n  match t with\n  | trm_bvar i    => If k = i then u else (trm_bvar i)\n  | trm_fvar x    => trm_fvar x\n  | trm_abs t1    => trm_abs (open_rec (S k) u t1)\n  | trm_app t1 t2 => trm_app (open_rec k u t1) (open_rec k u t2)\n  end.\n\nDefinition open t u := open_rec 0 u t.\n\nNotation \"{ k ~> u } t\" := (open_rec k u t) (at level 67).\nNotation \"t ^^ u\" := (open t u) (at level 67).\nNotation \"t ^ x\" := (open t (trm_fvar x)).\n\n(** Terms are locally-closed pre-terms *)\n\nInductive term : trm -> Prop :=\n  | term_var : forall x,\n      term (trm_fvar x)\n  | term_abs : forall L t1,\n      (forall x, x \\notin L -> term (t1 ^ x)) ->\n      term (trm_abs t1)\n  | term_app : forall t1 t2,\n      term t1 -> \n      term t2 -> \n      term (trm_app t1 t2).\n\n(** Environment is an associative list mapping variables to types. *)\n\nDefinition env := LibEnv.env typ.\n\n(** Typing relation *)\n\nReserved Notation \"E |= t ~: T\" (at level 69).\n\nInductive typing : env -> trm -> typ -> Prop :=\n  | typing_var : forall E x T,\n      ok E ->\n      binds x T E ->\n      E |= (trm_fvar x) ~: T\n  | typing_abs : forall L E U T t1,\n      (forall x, x \\notin L -> \n        (E & x ~ U) |= t1 ^ x ~: T) ->\n      E |= (trm_abs t1) ~: (typ_arrow U T)\n  | typing_app : forall S T E t1 t2,\n      E |= t1 ~: (typ_arrow S T) -> \n      E |= t2 ~: S ->\n      E |= (trm_app t1 t2) ~: T\n\nwhere \"E |= t ~: T\" := (typing E t T).\n\n(** Definition of values (only abstractions are values) *)\n\nInductive value : trm -> Prop :=\n  | value_abs : forall t1,\n      term (trm_abs t1) -> value (trm_abs t1).\n\n(** Reduction contexts *)\n\nInductive ctx : Set :=\n  | ctx_hole : ctx\n  | ctx_app_1 : forall (C : ctx) t2,\n      term t2 -> ctx\n  | ctx_app_2 : forall t1 (C : ctx),\n      value t1 -> ctx.\n\nFixpoint ctx_of (C : ctx) (t : trm) {struct C} : trm :=\n  match C with\n  | ctx_hole         => t\n  | ctx_app_1 C t2 _ => trm_app (ctx_of C t) t2\n  | ctx_app_2 t1 C _ => trm_app t1 (ctx_of C t)\n  end.\n\n(** Reduction relation - one step in call-by-value *)\n\nInductive red : trm -> trm -> Prop :=\n  | red_beta : forall t1 t2,\n      term (trm_abs t1) -> \n      value t2 ->\n      red (trm_app (trm_abs t1) t2) (t1 ^^ t2)\n  | red_ctx : forall C t t',\n      red t t' ->\n      red (ctx_of C t) (ctx_of C t').\n\nNotation \"t --> t'\" := (red t t') (at level 68).\n\n(** Goal is to prove preservation and progress *)\n\nDefinition preservation := forall E t t' T,\n  E |= t ~: T ->\n  t --> t' ->\n  E |= t' ~: T.\n\nDefinition progress := forall t T, \n  empty |= t ~: T ->\n     value t \n  \\/ exists t', t --> t'.\n\n", "meta": {"author": "samuelgruetter", "repo": "typesafety-proofs-spring14", "sha": "45189a3af1815788eed81a4f4ef60f7c4b8a2c98", "save_path": "github-repos/coq/samuelgruetter-typesafety-proofs-spring14", "path": "github-repos/coq/samuelgruetter-typesafety-proofs-spring14/typesafety-proofs-spring14-45189a3af1815788eed81a4f4ef60f7c4b8a2c98/DotTransitivity/ln/STLC_Core_WF_Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6606824694098652}}
{"text": "(* 1- Naive *)\nRequire Import ZArith.\nRequire Import Toy.Naive.lib.\nRequire Import Coq.Lists.List.\nRequire Import Toy.Naive.usl.implementation.\nImport T.\nOpen Scope Z.\n\nInductive aexp : Type :=\n  | ANum (n : Z)\n  | AId (X : var)\n  | APlus (a1 a2 : aexp)\n  | AMinus (a1 a2 : aexp)\n  | AMult (a1 a2 : aexp)\n  | ADiv (a1 a2 : aexp)\n  | ADeref (a : aexp).\n\nModule Denote_Aexp.\n\nDefinition add_sem (da1 da2 : state -> option Z) : state -> option Z :=\n  fun st =>\n    match da1 st, da2 st with\n      | Some v1, Some v2 => Some (v1 + v2)\n      | _, _ => None\n    end. \n\nDefinition sub_sem (da1 da2 : state -> option Z) : state -> option Z :=\n  fun st =>\n    match da1 st, da2 st with\n      | Some v1, Some v2 => Some (v1 - v2)\n      | _, _ => None\n    end.\n\nDefinition mul_sem (da1 da2 : state -> option Z) : state -> option Z :=\n  fun st =>\n    match da1 st, da2 st with\n      | Some v1, Some v2 => Some (v1 * v2)\n      | _, _ => None\n    end.\n  \nDefinition div_sem (da1 da2 : state -> option Z) : state -> option Z :=\n  fun st =>\n    match da1 st, da2 st with\n      | Some v1, Some v2 =>\n          if Z.eq_dec v2 0 then None else Some (v1 / v2)\n      | _, _ => None\n    end.\n\nDefinition deref_sem (da : state -> option Z) : state -> option Z :=\n  fun st =>\n    match da st with\n      | Some v => match snd st v with\n        | Some v' => Some v'\n        | _ => None\n      end\n      | _ => None\n    end.\n\nFixpoint aeval (a : aexp) : state -> option Z :=\n  match a with\n    | ANum n => fun _ =>  Some n\n    | AId X => fun st => Some (fst st X)\n    | APlus a1 a2 => add_sem (aeval a1) (aeval a2)\n    | AMinus a1 a2 => sub_sem (aeval a1) (aeval a2)\n    | AMult a1 a2 => mul_sem (aeval a1) (aeval a2)\n    | ADiv a1 a2 => div_sem (aeval a1) (aeval a2)\n    | ADeref a => deref_sem (aeval a)\n  end.\n\nEnd Denote_Aexp.\n\nInductive bexp : Type :=\n  | BTrue\n  | BFalse\n  | BEq (a1 a2 : aexp)\n  | BLe (a1 a2 : aexp)\n  | BNot (b : bexp)\n  | BAnd (b1 b2 : bexp).\n\nRecord bexp_denote : Type := {\n  true_set : state -> Prop;\n  false_set : state -> Prop;\n  error_set : state -> Prop; }.\n\nDefinition opt_test (R : Z -> Z -> Prop) (X Y : state -> option Z) : bexp_denote :=\n{|\n  true_set := fun st =>\n    match X st, Y st with\n      | Some n1, Some n2 => R n1 n2\n      | _, _ => False\n    end;\n  false_set := fun st =>\n    match X st, Y st with\n      | Some n1, Some n2 => ~ R n1 n2\n      | _, _ => False\n    end;\n  error_set := fun st =>\n    match X st, Y st with\n      | Some n1, Some n2 => False\n      | _, _ => True \n    end; |}.\n\nModule Denote_Bexp.\nImport Denote_Aexp.\n\nFixpoint beval (b : bexp) : bexp_denote :=\n  match b with\n    | BTrue =>\n        {| true_set := Sets.full;\n           false_set := Sets.empty;\n           error_set := Sets.empty; |}\n    | BFalse =>\n        {| true_set := Sets.empty;\n           false_set := Sets.full;\n           error_set := Sets.empty; |}\n    | BEq a1 a2 =>\n        opt_test Z.eq (aeval a1) (aeval a2)\n    | BLe a1 a2 => \n        opt_test Z.le (aeval a1) (aeval a2)\n    | BNot b =>\n        {| true_set := false_set (beval b);\n           false_set := true_set (beval b);\n           error_set := error_set (beval b); |}\n    | BAnd b1 b2 =>\n        {| true_set := Sets.intersect (true_set (beval b1)) (true_set (beval b2));\n           false_set := Sets.union (false_set (beval b1))\n                                   (Sets.intersect (true_set (beval b1))\n                                                   (false_set (beval b2)));\n           error_set := Sets.union (error_set (beval b1))\n                                   (Sets.intersect (true_set (beval b1))\n                                                   (error_set (beval b2))); |}\n       end.\n\nEnd Denote_Bexp.\n\nInductive com : Type :=\n  | CSkip\n  | CBreak\n  | CCont\n  | CAss_load (X : var) (a : aexp)\n  | CAss_store (a1 : aexp) (a2 : aexp)\n  | CSeq (c1 c2 : com)\n  | CIf (b : bexp) (c1 c2 : com)\n  | CFor (c1 c2 : com).\n\nRecord com_denote : Type := {\n  com_normal : state -> state -> Prop;\n  com_break : state -> state -> Prop;\n  com_cont : state -> state -> Prop;\n  com_error : state -> Prop }.\n\nModule Denote_Com.\nImport Denote_Aexp.\nImport Denote_Bexp.\n\nDefinition skip_sem : com_denote := {|\n  com_normal := BinRel.id;\n  com_break := BinRel.empty;\n  com_cont := BinRel.empty;\n  com_error := Sets.empty |}.\n\nDefinition break_sem : com_denote := {|\n  com_normal := BinRel.empty; \n  com_break := BinRel.id;\n  com_cont := BinRel.empty;\n  com_error := Sets.empty |}.\n\nDefinition cont_sem : com_denote := {|\n  com_normal := BinRel.empty;\n  com_break := BinRel.empty;\n  com_cont := BinRel.id;\n  com_error := Sets.empty |}.\n\nDefinition load_sem (X : var) (DA : state -> option Z) : com_denote := {|\n  com_normal := fun st1 st2 => match DA st1 with\n    | Some n => (fst st2 X = n) /\\ (forall Y, Y <> X -> fst st2 Y = fst st1 Y) /\\ (snd st1 = snd st2)\n    | None => False\n  end;\n  com_break := BinRel.empty;\n  com_cont := BinRel.empty;\n  com_error := fun st => (DA st) = None; |}.\n  \nDefinition store_sem (DAL DAR : state -> option Z) : com_denote := {|\n  com_normal := fun st1 st2 => match DAL st1, DAR st1 with\n    | Some p, Some v => (snd st1 p <> None) /\\ (snd st2 p = Some v) /\\\n        (forall p', p <> p' -> snd st2 p' = snd st1 p') /\\ (fst st1 = fst st2)\n    | _, _ => False \n  end;\n  com_break := BinRel.empty;\n  com_cont := BinRel.empty;\n  com_error := fun st => match DAL st, DAR st with\n    | Some p, Some v => snd st p = None\n    | _, _ => True \n  end; |}.\n\nDefinition seq_sem (DC1 DC2 : com_denote) : com_denote := {|\n  com_normal := BinRel.concat (com_normal DC1) (com_normal DC2);\n    (* exists st3, com_normal DC1 st1 st3 /\\ com_normal DC2 st3 st2; *)\n  com_break := BinRel.union (com_break DC1) (BinRel.concat (com_normal DC1) (com_break DC2));\n    (* (com_break DC1 st1 st2) \\/\n    (exists st3, com_normal DC1 st1 st3 /\\ com_break DC2 st3 st2); *)\n  com_cont := BinRel.union (com_cont DC1) (BinRel.concat (com_normal DC1) (com_cont DC2));\n    (* (com_cont DC1 st1 st2) \\/\n    (exists st3, com_normal DC1 st1 st3 /\\ com_cont DC2 st3 st2); *)\n  com_error := Sets.union (com_error DC1) (BinRel.dia (com_normal DC1) (com_error DC2)) |}.\n    (* (com_error DC1 st) \\/ (exists st', com_normal DC1 st st' /\\ com_error DC2 st'); |}. *)\n  \nDefinition if_sem (DB : bexp_denote) (DC1 DC2 : com_denote) : com_denote := {|\n  com_normal := BinRel.union (BinRel.concat (BinRel.testrel (true_set DB)) (com_normal DC1))\n    (BinRel.concat (BinRel.testrel (false_set DB)) (com_normal DC2));\n  com_break := BinRel.union (BinRel.concat (BinRel.testrel (true_set DB)) (com_break DC1))\n    (BinRel.concat (BinRel.testrel (false_set DB)) (com_break DC2));\n  com_cont := BinRel.union (BinRel.concat (BinRel.testrel (true_set DB)) (com_cont DC1))\n    (BinRel.concat (BinRel.testrel (false_set DB)) (com_cont DC2));\n  com_error := Sets.union (error_set DB) \n    (Sets.union (Sets.intersect (true_set DB) (com_error DC1)) (Sets.intersect (false_set DB) (com_error DC2)))|}.\n\n(* Definition if_sem (DB : bexp_denote) (DC1 DC2 : com_denote) : com_denote := {|\n  com_normal := fun st1 st2 => \n    (true_set DB st1 /\\ com_normal DC1 st1 st2) \\/\n    (false_set DB st1 /\\ com_normal DC2 st1 st2);\n  com_break := fun st1 st2 =>\n    (true_set DB st1 /\\ com_break DC1 st1 st2) \\/\n    (false_set DB st1 /\\ com_break DC2 st1 st2);\n  com_cont := fun st1 st2 =>\n    (true_set DB st1 /\\ com_cont DC1 st1 st2) \\/\n    (false_set DB st1 /\\ com_cont DC2 st1 st2);\n  com_error := fun st =>\n    (error_set DB st) \\/\n    (true_set DB st /\\ com_error DC1 st) \\/\n    (false_set DB st /\\ com_error DC2 st); |}. *)\n\nFixpoint iter_loop_body (DC1 DC2 : com_denote) (n : nat) : com_denote := match n with\n  | O => {|\n      com_normal := BinRel.union (com_break DC1) (BinRel.concat (com_normal DC1) (com_break DC2));\n      com_break := BinRel.empty;\n      com_cont := BinRel.empty;\n      com_error := Sets.union (com_error DC1) (BinRel.dia (com_normal DC1) (com_error DC2)) |}\n  | S n' => {|\n      com_normal := BinRel.concat \n        (BinRel.union (BinRel.concat (com_normal DC1) (com_normal DC2)) \n          (BinRel.concat (com_cont DC1) (com_normal DC2))) \n        (com_normal (iter_loop_body DC1 DC2 n'));\n      com_break := BinRel.empty;\n      com_cont := BinRel.empty;\n      com_error := BinRel.dia \n        (BinRel.union (BinRel.concat (com_normal DC1) (com_normal DC2)) \n          (BinRel.concat (com_cont DC1) (com_normal DC2))) \n        (com_error (iter_loop_body DC1 DC2 n')) |}\nend.\n\nDefinition for_sem (DC1 DC2 : com_denote) : com_denote := {|\n  com_normal := BinRel.omega_union (fun n => com_normal (iter_loop_body DC1 DC2 n));\n  com_break := BinRel.empty;\n  com_cont := BinRel.empty;\n  com_error := Sets.omega_union (fun n => com_error (iter_loop_body DC1 DC2 n)) |}.\n\n\n(* Fixpoint iter_loop_body (DC1 DC2 : com_denote) (n : nat) : com_denote :=\n  match n with\n  | O => {|\n      com_normal := fun st1 st2 =>\n        (com_break DC1 st1 st2) \\/\n        (exists st3, com_normal DC1 st1 st3 /\\ com_break DC2 st3 st2);\n      com_break := fun st1 st2 => False;\n      com_cont := fun st1 st2 => False;\n      com_error := fun st =>\n        (com_error DC1 st) \\/\n        (exists st', com_normal DC1 st st' /\\ com_error DC2 st') |}\n  | S n' => {|\n      com_normal := fun st1 st2 => exists st3,\n        ((exists st4, com_normal DC1 st1 st4 /\\ com_normal DC2 st4 st3) \\/\n        (exists st4, com_cont DC1 st1 st4 /\\ com_normal DC2 st4 st3)) /\\\n        (com_normal (iter_loop_body DC1 DC2 n') st3 st2);\n      com_break := fun st1 st2 => False;\n      com_cont := fun st1 st2 => False;\n      com_error := fun st => exists st',\n        ((exists st2, com_normal DC1 st st2 /\\ com_normal DC2 st2 st') \\/\n        (exists st2, com_cont DC1 st st2 /\\ com_normal DC2 st2 st')) /\\\n        (com_error (iter_loop_body DC1 DC2 n') st') |}\n  end.\n\nDefinition for_sem (DC1 DC2 : com_denote) : com_denote := {|\n  com_normal := fun st1 st2 =>\n    exists n, com_normal (iter_loop_body DC1 DC2 n) st1 st2;\n  com_break := fun st1 st2 => False;\n  com_cont := fun st1 st2 => False;\n  com_error := fun st =>\n    exists n, com_error (iter_loop_body DC1 DC2 n) st |}. *)\n\nFixpoint ceval (c : com) : com_denote :=\n  match c with\n  | CSkip => skip_sem\n  | CBreak => break_sem\n  | CCont => cont_sem\n  | CAss_load X a => load_sem X (aeval a)\n  | CAss_store a1 a2 => store_sem (aeval a1) (aeval a2)\n  | CSeq c1 c2 => seq_sem (ceval c1) (ceval c2)\n  | CIf b c1 c2 => if_sem (beval b) (ceval c1) (ceval c2)\n  | CFor c1 c2 => for_sem (ceval c1) (ceval c2)\n  end.\n\nEnd Denote_Com.\n", "meta": {"author": "TaoYC0904", "repo": "Toy-Language-Address", "sha": "cabf1d8ef0fd11dd5bf4d61b2df2322a296f710c", "save_path": "github-repos/coq/TaoYC0904-Toy-Language-Address", "path": "github-repos/coq/TaoYC0904-Toy-Language-Address/Toy-Language-Address-cabf1d8ef0fd11dd5bf4d61b2df2322a296f710c/1-Naive/Language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571774, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6606824651171989}}
{"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(* F. Besson: to evaluate polynomials, the original code is using a list.\n   For big polynomials, this is inefficient -- linear access.\n   I have modified the code to use binary trees -- logarithmic access.  *)\n\n\nSet Implicit Arguments.\nRequire Import Setoid Morphisms Env BinPos BinNat BinInt.\nRequire Export Ring_theory.\n\nLocal Open Scope positive_scope.\nImport RingSyntax.\n\nSection MakeRingPol.\n\n (* Ring elements *)\n Variable R:Type.\n Variable (rO rI : R) (radd rmul rsub: R->R->R) (ropp : R->R).\n Variable req : R -> R -> Prop.\n\n (* Ring properties *)\n Variable Rsth : Equivalence req.\n Variable Reqe : ring_eq_ext radd rmul ropp req.\n Variable ARth : almost_ring_theory rO rI radd rmul rsub ropp req.\n\n (* Coefficients *)\n Variable C: Type.\n Variable (cO cI: C) (cadd cmul csub : C->C->C) (copp : C->C).\n Variable ceqb : C->C->bool.\n Variable phi : C -> R.\n Variable CRmorph : ring_morph rO rI radd rmul rsub ropp req\n                                cO cI cadd cmul csub copp ceqb phi.\n\n (* Power coefficients *)\n Variable Cpow : Type.\n Variable Cp_phi : N -> Cpow.\n Variable rpow : R -> Cpow -> R.\n Variable pow_th : power_theory rI rmul req Cp_phi rpow.\n\n (* R notations *)\n Notation \"0\" := rO. Notation \"1\" := rI.\n Infix \"+\" := radd. Infix \"*\" := rmul.\n Infix \"-\" := rsub. Notation \"- x\" := (ropp x).\n Infix \"==\" := req.\n Infix \"^\" := (pow_pos rmul).\n\n (* C notations *)\n Infix \"+!\" := cadd. Infix \"*!\" := cmul.\n Infix \"-! \" := csub. Notation \"-! x\" := (copp x).\n Infix \"?=!\" := ceqb. Notation \"[ x ]\" := (phi x).\n\n (* Useful tactics *)\n Add Morphism radd with signature (req ==> req ==> req) as radd_ext.\n Proof. exact (Radd_ext Reqe). Qed.\n\n Add Morphism rmul with signature (req ==> req ==> req) as rmul_ext.\n Proof. exact (Rmul_ext Reqe). Qed.\n\n Add Morphism ropp with signature (req ==> req) as ropp_ext.\n Proof. exact (Ropp_ext Reqe). Qed.\n\n Add Morphism rsub with signature (req ==> req ==> req) as rsub_ext.\n Proof. exact (ARsub_ext Rsth Reqe ARth). Qed.\n\n Ltac rsimpl := gen_srewrite Rsth Reqe ARth.\n\n Ltac add_push := gen_add_push radd Rsth Reqe ARth.\n Ltac mul_push := gen_mul_push rmul Rsth Reqe ARth.\n\n Ltac add_permut_rec t :=\n   match t with\n   | ?x + ?y => add_permut_rec y || add_permut_rec x\n   | _ => add_push t; apply (Radd_ext Reqe); [|reflexivity]\n   end.\n\n Ltac add_permut :=\n  repeat (reflexivity ||\n    match goal with |- ?t == _ => add_permut_rec t end).\n\n Ltac mul_permut_rec t :=\n   match t with\n   | ?x * ?y => mul_permut_rec y || mul_permut_rec x\n   | _ => mul_push t; apply (Rmul_ext Reqe); [|reflexivity]\n   end.\n\n Ltac mul_permut :=\n  repeat (reflexivity ||\n    match goal with |- ?t == _ => mul_permut_rec t end).\n\n\n (* Definition of multivariable polynomials with coefficients in C :\n    Type [Pol] represents [X1 ... Xn].\n    The representation is Horner's where a [n] variable polynomial\n    (C[X1..Xn]) is seen as a polynomial on [X1] which coefficients\n    are polynomials with [n-1] variables (C[X2..Xn]).\n    There are several optimisations to make the repr compacter:\n    - [Pc c] is the constant polynomial of value c\n       == c*X1^0*..*Xn^0\n    - [Pinj j Q] is a polynomial constant w.r.t the [j] first variables.\n        variable indices are shifted of j in Q.\n       == X1^0 *..* Xj^0 * Q{X1 <- Xj+1;..; Xn-j <- Xn}\n    - [PX P i Q] is an optimised Horner form of P*X^i + Q\n        with P not the null polynomial\n       == P * X1^i + Q{X1 <- X2; ..; Xn-1 <- Xn}\n\n    In addition:\n    - polynomials of the form (PX (PX P i (Pc 0)) j Q) are forbidden\n      since they can be represented by the simpler form (PX P (i+j) Q)\n    - (Pinj i (Pinj j P)) is (Pinj (i+j) P)\n    - (Pinj i (Pc c)) is (Pc c)\n *)\n\n Inductive Pol : Type :=\n  | Pc : C -> Pol\n  | Pinj : positive -> Pol -> Pol\n  | PX : Pol -> positive -> Pol -> Pol.\n\n Definition P0 := Pc cO.\n Definition P1 := Pc cI.\n\n Fixpoint Peq (P P' : Pol) {struct P'} : bool :=\n  match P, P' with\n  | Pc c, Pc c' => c ?=! c'\n  | Pinj j Q, Pinj j' Q' =>\n    match j ?= j' with\n    | Eq => Peq Q Q'\n    | _ => false\n    end\n  | PX P i Q, PX P' i' Q' =>\n    match i ?= i' with\n    | Eq => if Peq P P' then Peq Q Q' else false\n    | _ => false\n    end\n  | _, _ => false\n  end.\n\n Infix \"?==\" := Peq.\n\n Definition mkPinj j P :=\n  match P with\n  | Pc _ => P\n  | Pinj j' Q => Pinj (j + j') Q\n  | _ => Pinj j P\n  end.\n\n Definition mkPinj_pred j P:=\n  match j with\n  | xH => P\n  | xO j => Pinj (Pos.pred_double j) P\n  | xI j => Pinj (xO j) P\n  end.\n\n Definition mkPX P i Q :=\n  match P with\n  | Pc c => if c ?=! cO then mkPinj xH Q else PX P i Q\n  | Pinj _ _ => PX P i Q\n  | PX P' i' Q' => if Q' ?== P0 then PX P' (i' + i) Q else PX P i Q\n  end.\n\n Definition mkXi i := PX P1 i P0.\n\n Definition mkX := mkXi 1.\n\n (** Opposite of addition *)\n\n Fixpoint Popp (P:Pol) : Pol :=\n  match P with\n  | Pc c => Pc (-! c)\n  | Pinj j Q => Pinj j (Popp Q)\n  | PX P i Q => PX (Popp P) i (Popp Q)\n  end.\n\n Notation \"-- P\" := (Popp P).\n\n (** Addition et subtraction *)\n\n Fixpoint PaddC (P:Pol) (c:C) : Pol :=\n  match P with\n  | Pc c1 => Pc (c1 +! c)\n  | Pinj j Q => Pinj j (PaddC Q c)\n  | PX P i Q => PX P i (PaddC Q c)\n  end.\n\n Fixpoint PsubC (P:Pol) (c:C) : Pol :=\n  match P with\n  | Pc c1 => Pc (c1 -! c)\n  | Pinj j Q => Pinj j (PsubC Q c)\n  | PX P i Q => PX P i (PsubC Q c)\n  end.\n\n Section PopI.\n\n  Variable Pop : Pol -> Pol -> Pol.\n  Variable Q : Pol.\n\n  Fixpoint PaddI (j:positive) (P:Pol) : Pol :=\n   match P with\n   | Pc c => mkPinj j (PaddC Q c)\n   | Pinj j' Q' =>\n     match Z.pos_sub j' j with\n     | Zpos k =>  mkPinj j (Pop (Pinj k Q') Q)\n     | Z0 => mkPinj j (Pop Q' Q)\n     | Zneg k => mkPinj j' (PaddI k Q')\n     end\n   | PX P i Q' =>\n     match j with\n     | xH => PX P i (Pop Q' Q)\n     | xO j => PX P i (PaddI (Pos.pred_double j) Q')\n     | xI j => PX P i (PaddI (xO j) Q')\n     end\n   end.\n\n  Fixpoint PsubI (j:positive) (P:Pol) : Pol :=\n   match P with\n   | Pc c => mkPinj j (PaddC (--Q) c)\n   | Pinj j' Q' =>\n     match Z.pos_sub j' j with\n     | Zpos k =>  mkPinj j (Pop (Pinj k Q') Q)\n     | Z0 => mkPinj j (Pop Q' Q)\n     | Zneg k => mkPinj j' (PsubI k Q')\n     end\n   | PX P i Q' =>\n     match j with\n     | xH => PX P i (Pop Q' Q)\n     | xO j => PX P i (PsubI (Pos.pred_double j) Q')\n     | xI j => PX P i (PsubI (xO j) Q')\n     end\n   end.\n\n Variable P' : Pol.\n\n Fixpoint PaddX (i':positive) (P:Pol) : Pol :=\n  match P with\n  | Pc c => PX P' i' P\n  | Pinj j Q' =>\n    match j with\n    | xH =>  PX P' i' Q'\n    | xO j => PX P' i' (Pinj (Pos.pred_double j) Q')\n    | xI j => PX P' i' (Pinj (xO j) Q')\n    end\n  | PX P i Q' =>\n    match Z.pos_sub i i' with\n    | Zpos k => mkPX (Pop (PX P k P0) P') i' Q'\n    | Z0 => mkPX (Pop P P') i Q'\n    | Zneg k => mkPX (PaddX k P) i Q'\n    end\n  end.\n\n Fixpoint PsubX (i':positive) (P:Pol) : Pol :=\n  match P with\n  | Pc c => PX (--P') i' P\n  | Pinj j Q' =>\n    match j with\n    | xH =>  PX (--P') i' Q'\n    | xO j => PX (--P') i' (Pinj (Pos.pred_double j) Q')\n    | xI j => PX (--P') i' (Pinj (xO j) Q')\n    end\n  | PX P i Q' =>\n    match Z.pos_sub i i' with\n    | Zpos k => mkPX (Pop (PX P k P0) P') i' Q'\n    | Z0 => mkPX (Pop P P') i Q'\n    | Zneg k => mkPX (PsubX k P) i Q'\n    end\n  end.\n\n\n End PopI.\n\n Fixpoint Padd (P P': Pol) {struct P'} : Pol :=\n  match P' with\n  | Pc c' => PaddC P c'\n  | Pinj j' Q' => PaddI Padd Q' j' P\n  | PX P' i' Q' =>\n    match P with\n    | Pc c => PX P' i' (PaddC Q' c)\n    | Pinj j Q =>\n      match j with\n      | xH => PX P' i' (Padd Q Q')\n      | xO j => PX P' i' (Padd (Pinj (Pos.pred_double j) Q) Q')\n      | xI j => PX P' i' (Padd (Pinj (xO j) Q) Q')\n      end\n    | PX P i Q =>\n      match Z.pos_sub i i' with\n      | Zpos k => mkPX (Padd (PX P k P0) P') i' (Padd Q Q')\n      | Z0 => mkPX (Padd P P') i (Padd Q Q')\n      | Zneg k => mkPX (PaddX Padd P' k P) i (Padd Q Q')\n      end\n    end\n  end.\n Infix \"++\" := Padd.\n\n Fixpoint Psub (P P': Pol) {struct P'} : Pol :=\n  match P' with\n  | Pc c' => PsubC P c'\n  | Pinj j' Q' => PsubI Psub Q' j' P\n  | PX P' i' Q' =>\n    match P with\n    | Pc c => PX (--P') i' (*(--(PsubC Q' c))*) (PaddC (--Q') c)\n    | Pinj j Q =>\n      match j with\n      | xH => PX (--P') i' (Psub Q Q')\n      | xO j => PX (--P') i' (Psub (Pinj (Pos.pred_double j) Q) Q')\n      | xI j => PX (--P') i' (Psub (Pinj (xO j) Q) Q')\n      end\n    | PX P i Q =>\n      match Z.pos_sub i i' with\n      | Zpos k => mkPX (Psub (PX P k P0) P') i' (Psub Q Q')\n      | Z0 => mkPX (Psub P P') i (Psub Q Q')\n      | Zneg k => mkPX (PsubX Psub P' k P) i (Psub Q Q')\n      end\n    end\n  end.\n Infix \"--\" := Psub.\n\n (** Multiplication *)\n\n Fixpoint PmulC_aux (P:Pol) (c:C) : Pol :=\n  match P with\n  | Pc c' => Pc (c' *! c)\n  | Pinj j Q => mkPinj j (PmulC_aux Q c)\n  | PX P i Q => mkPX (PmulC_aux P c) i (PmulC_aux Q c)\n  end.\n\n Definition PmulC P c :=\n  if c ?=! cO then P0 else\n  if c ?=! cI then P else PmulC_aux P c.\n\n Section PmulI.\n  Variable Pmul : Pol -> Pol -> Pol.\n  Variable Q : Pol.\n  Fixpoint PmulI (j:positive) (P:Pol) : Pol :=\n   match P with\n   | Pc c => mkPinj j (PmulC Q c)\n   | Pinj j' Q' =>\n     match Z.pos_sub j' j with\n     | Zpos k => mkPinj j (Pmul (Pinj k Q') Q)\n     | Z0 => mkPinj j (Pmul Q' Q)\n     | Zneg k => mkPinj j' (PmulI k Q')\n     end\n   | PX P' i' Q' =>\n     match j with\n     | xH => mkPX (PmulI xH P') i' (Pmul Q' Q)\n     | xO j' => mkPX (PmulI j P') i' (PmulI (Pos.pred_double j') Q')\n     | xI j' => mkPX (PmulI j P') i' (PmulI (xO j') Q')\n     end\n   end.\n\n End PmulI.\n\n Fixpoint Pmul (P P'' : Pol) {struct P''} : Pol :=\n   match P'' with\n   | Pc c => PmulC P c\n   | Pinj j' Q' => PmulI Pmul Q' j' P\n   | PX P' i' Q' =>\n     match P with\n     | Pc c => PmulC P'' c\n     | Pinj j Q =>\n       let QQ' :=\n         match j with\n         | xH => Pmul Q Q'\n         | xO j => Pmul (Pinj (Pos.pred_double j) Q) Q'\n         | xI j => Pmul (Pinj (xO j) Q) Q'\n         end in\n       mkPX (Pmul P P') i' QQ'\n     | PX P i Q=>\n       let QQ' := Pmul Q Q' in\n       let PQ' := PmulI Pmul Q' xH P in\n       let QP' := Pmul (mkPinj xH Q) P' in\n       let PP' := Pmul P P' in\n       (mkPX (mkPX PP' i P0 ++ QP') i' P0) ++ mkPX PQ' i QQ'\n     end\n  end.\n\n Infix \"**\" := Pmul.\n\n Fixpoint Psquare (P:Pol) : Pol :=\n   match P with\n   | Pc c => Pc (c *! c)\n   | Pinj j Q => Pinj j (Psquare Q)\n   | PX P i Q =>\n     let twoPQ := Pmul P (mkPinj xH (PmulC Q (cI +! cI))) in\n     let Q2 := Psquare Q in\n     let P2 := Psquare P in\n     mkPX (mkPX P2 i P0 ++ twoPQ) i Q2\n   end.\n\n (** Monomial **)\n\n (** A monomial is X1^k1...Xi^ki. Its representation\n     is a simplified version of the polynomial representation:\n\n     - [mon0] correspond to the polynom [P1].\n     - [(zmon j M)] corresponds to [(Pinj j ...)],\n       i.e. skip j variable indices.\n     - [(vmon i M)] is X^i*M with X the current variable,\n       its corresponds to (PX P1 i ...)]\n *)\n\n  Inductive Mon: Set :=\n  | mon0: Mon\n  | zmon: positive -> Mon -> Mon\n  | vmon: positive -> Mon -> Mon.\n\n Definition mkZmon j M :=\n   match M with mon0 => mon0 | _ => zmon j M end.\n\n Definition zmon_pred j M :=\n   match j with xH => M | _ => mkZmon (Pos.pred j) M end.\n\n Definition mkVmon i M :=\n   match M with\n   | mon0 => vmon i mon0\n   | zmon j m => vmon i (zmon_pred j m)\n   | vmon i' m => vmon (i+i') m\n   end.\n\n Fixpoint MFactor (P: Pol) (M: Mon) : Pol * Pol :=\n   match P, M with\n        _, mon0 => (Pc cO, P)\n   | Pc _, _    => (P, Pc cO)\n   | Pinj j1 P1, zmon j2 M1 =>\n      match (j1 ?= j2) with\n        Eq => let (R,S) := MFactor P1 M1 in\n                 (mkPinj j1 R, mkPinj j1 S)\n      | Lt => let (R,S) := MFactor P1 (zmon (j2 - j1) M1) in\n                 (mkPinj j1 R, mkPinj j1 S)\n      | Gt => (P, Pc cO)\n      end\n  | Pinj _ _, vmon _ _ => (P, Pc cO)\n  | PX P1 i Q1, zmon j M1 =>\n             let M2 := zmon_pred j M1 in\n             let (R1, S1) := MFactor P1 M in\n             let (R2, S2) := MFactor Q1 M2 in\n               (mkPX R1 i R2, mkPX S1 i S2)\n  | PX P1 i Q1, vmon j M1 =>\n      match (i ?= j) with\n        Eq => let (R1,S1) := MFactor P1 (mkZmon xH M1) in\n                 (mkPX R1 i Q1, S1)\n      | Lt => let (R1,S1) := MFactor P1 (vmon (j - i) M1) in\n                 (mkPX R1 i Q1, S1)\n      | Gt => let (R1,S1) := MFactor P1 (mkZmon xH M1) in\n                 (mkPX R1 i Q1, mkPX S1 (i-j) (Pc cO))\n      end\n   end.\n\n  Definition POneSubst (P1: Pol) (M1: Mon) (P2: Pol): option Pol :=\n    let (Q1,R1) := MFactor P1 M1 in\n    match R1 with\n     (Pc c) => if c ?=! cO then None\n               else Some (Padd Q1 (Pmul P2 R1))\n    | _ => Some (Padd Q1 (Pmul P2 R1))\n    end.\n\n  Fixpoint PNSubst1 (P1: Pol) (M1: Mon) (P2: Pol) (n: nat) : Pol :=\n    match POneSubst P1 M1 P2 with\n     Some P3 => match n with S n1 => PNSubst1 P3 M1 P2 n1 | _ => P3 end\n    | _ => P1\n    end.\n\n  Definition PNSubst (P1: Pol) (M1: Mon) (P2: Pol) (n: nat): option Pol :=\n    match POneSubst P1 M1 P2 with\n     Some P3 => match n with S n1 => Some (PNSubst1 P3 M1 P2 n1) | _ => None end\n    | _ => None\n    end.\n\n  Fixpoint PSubstL1 (P1: Pol) (LM1: list (Mon * Pol)) (n: nat) : Pol :=\n    match LM1 with\n     cons (M1,P2) LM2 => PSubstL1 (PNSubst1 P1 M1 P2 n) LM2 n\n    | _ => P1\n    end.\n\n  Fixpoint PSubstL (P1: Pol) (LM1: list (Mon * Pol)) (n: nat) : option Pol :=\n    match LM1 with\n     cons (M1,P2) LM2 =>\n      match PNSubst P1 M1 P2 n with\n        Some P3 => Some (PSubstL1 P3 LM2 n)\n     |  None => PSubstL P1 LM2 n\n     end\n    | _ => None\n    end.\n\n  Fixpoint PNSubstL (P1: Pol) (LM1: list (Mon * Pol)) (m n: nat) : Pol :=\n    match PSubstL P1 LM1 n with\n     Some P3 => match m with S m1 => PNSubstL P3 LM1 m1 n | _ => P3 end\n    | _ => P1\n    end.\n\n (** Evaluation of a polynomial towards R *)\n\n Fixpoint Pphi(l:Env R) (P:Pol) : R :=\n  match P with\n  | Pc c => [c]\n  | Pinj j Q => Pphi (jump j l) Q\n  | PX P i Q => Pphi l P * (hd l) ^ i + Pphi (tail l) Q\n  end.\n\n Reserved Notation \"P @ l \" (at level 10, no associativity).\n Notation \"P @ l \" := (Pphi l P).\n\n (** Evaluation of a monomial towards R *)\n\n Fixpoint Mphi(l:Env R) (M: Mon) : R :=\n  match M with\n  | mon0 => rI\n  | zmon j M1 => Mphi (jump j l) M1\n  | vmon i M1 => Mphi (tail l) M1 * (hd l) ^ i\n  end.\n\n Notation \"M @@ l\" := (Mphi l M) (at level 10, no associativity).\n\n (** Proofs *)\n\n Ltac destr_pos_sub :=\n  match goal with |- context [Z.pos_sub ?x ?y] =>\n   generalize (Z.pos_sub_discr x y); destruct (Z.pos_sub x y)\n  end.\n\n Lemma Peq_ok P P' : (P ?== P') = true -> forall l, P@l == P'@ l.\n Proof.\n  revert P';induction P;destruct P';simpl; intros H l; try easy.\n  - now apply (morph_eq CRmorph).\n  - destruct (Pos.compare_spec p p0); [ subst | easy | easy ].\n    now rewrite IHP.\n  - specialize (IHP1 P'1); specialize (IHP2 P'2).\n    destruct (Pos.compare_spec p p0); [ subst | easy | easy ].\n    destruct (P2 ?== P'1); [|easy].\n    rewrite H in *.\n    now rewrite IHP1, IHP2.\n Qed.\n\n Lemma Peq_spec P P' :\n   BoolSpec (forall l, P@l == P'@l) True (P ?== P').\n Proof.\n  generalize (Peq_ok P P'). destruct (P ?== P'); auto.\n Qed.\n\n Lemma Pphi0 l : P0@l == 0.\n Proof.\n  simpl;apply (morph0 CRmorph).\n Qed.\n\n Lemma Pphi1 l : P1@l == 1.\n Proof.\n  simpl;apply (morph1 CRmorph).\n Qed.\n\nLemma env_morph p e1 e2 :\n  (forall x, e1 x = e2 x) -> p @ e1 = p @ e2.\nProof.\n  revert e1 e2. induction p ; simpl.\n  - reflexivity.\n  - intros e1 e2 EQ. apply IHp. intros. apply EQ.\n  - intros e1 e2 EQ. f_equal; [f_equal|].\n    + now apply IHp1.\n    + f_equal. apply EQ.\n    + apply IHp2. intros; apply EQ.\nQed.\n\nLemma Pjump_add P i j l :\n  P @ (jump (i + j) l) = P @ (jump j (jump i l)).\nProof.\n  apply env_morph. intros. rewrite <- jump_add. f_equal.\n  apply Pos.add_comm.\nQed.\n\nLemma Pjump_xO_tail P p l :\n  P @ (jump (xO p) (tail l)) = P @ (jump (xI p) l).\nProof.\n  apply env_morph. intros. now jump_simpl.\nQed.\n\nLemma Pjump_pred_double P p l :\n  P @ (jump (Pos.pred_double p) (tail l)) = P @ (jump (xO p) l).\nProof.\n  apply env_morph. intros.\n  rewrite jump_pred_double. now jump_simpl.\nQed.\n\n Lemma mkPinj_ok j l P : (mkPinj j P)@l == P@(jump j l).\n Proof.\n  destruct P;simpl;rsimpl.\n  now rewrite Pjump_add.\n Qed.\n\n Lemma pow_pos_add x i j : x^(j + i) == x^i * x^j.\n Proof.\n  rewrite Pos.add_comm.\n  apply (pow_pos_add Rsth Reqe.(Rmul_ext) ARth.(ARmul_assoc)).\n Qed.\n\n Lemma ceqb_spec c c' : BoolSpec ([c] == [c']) True (c ?=! c').\n Proof.\n  generalize (morph_eq CRmorph c c').\n  destruct (c ?=! c'); auto.\n Qed.\n\n Lemma mkPX_ok l P i Q :\n  (mkPX P i Q)@l == P@l * (hd l)^i + Q@(tail l).\n Proof.\n  unfold mkPX. destruct P.\n  - case ceqb_spec; intros H; simpl; try reflexivity.\n    rewrite H, (morph0 CRmorph), mkPinj_ok; rsimpl.\n  - reflexivity.\n  - case Peq_spec; intros H; simpl; try reflexivity.\n    rewrite H, Pphi0, Pos.add_comm, pow_pos_add; rsimpl.\n Qed.\n\n Hint Rewrite\n  Pphi0\n  Pphi1\n  mkPinj_ok\n  mkPX_ok\n  (morph0 CRmorph)\n  (morph1 CRmorph)\n  (morph0 CRmorph)\n  (morph_add CRmorph)\n  (morph_mul CRmorph)\n  (morph_sub CRmorph)\n  (morph_opp CRmorph)\n  : Esimpl.\n\n (* Quicker than autorewrite with Esimpl :-) *)\n Ltac Esimpl := try rewrite_db Esimpl; rsimpl; simpl.\n\n Lemma PaddC_ok c P l : (PaddC P c)@l == P@l + [c].\n Proof.\n  revert l;induction P;simpl;intros;Esimpl;trivial.\n  rewrite IHP2;rsimpl.\n Qed.\n\n Lemma PsubC_ok c P l : (PsubC P c)@l == P@l - [c].\n Proof.\n  revert l;induction P;simpl;intros.\n  - Esimpl.\n  - rewrite IHP;rsimpl.\n  - rewrite IHP2;rsimpl.\n Qed.\n\n Lemma PmulC_aux_ok c P l : (PmulC_aux P c)@l == P@l * [c].\n Proof.\n  revert l;induction P;simpl;intros;Esimpl;trivial.\n  rewrite IHP1, IHP2;rsimpl. add_permut. mul_permut.\n Qed.\n\n Lemma PmulC_ok c P l : (PmulC P c)@l == P@l * [c].\n Proof.\n  unfold PmulC.\n  case ceqb_spec; intros H.\n  - rewrite H; Esimpl.\n  - case ceqb_spec; intros H'.\n    + rewrite H'; Esimpl.\n    + apply PmulC_aux_ok.\n Qed.\n\n Lemma Popp_ok P l : (--P)@l == - P@l.\n Proof.\n  revert l;induction P;simpl;intros.\n  - Esimpl.\n  - apply IHP.\n  - rewrite IHP1, IHP2;rsimpl.\n Qed.\n\n Hint Rewrite PaddC_ok PsubC_ok PmulC_ok Popp_ok : Esimpl.\n\n Lemma PaddX_ok P' P k l :\n  (forall P l, (P++P')@l == P@l + P'@l) ->\n  (PaddX Padd P' k P) @ l == P@l + P'@l * (hd l)^k.\n Proof.\n  intros IHP'.\n  revert k l. induction P;simpl;intros.\n  - add_permut.\n  - destruct p; simpl;\n    rewrite ?Pjump_xO_tail, ?Pjump_pred_double; add_permut.\n  - destr_pos_sub; intros ->;Esimpl.\n    + rewrite IHP';rsimpl. add_permut.\n    + rewrite IHP', pow_pos_add;simpl;Esimpl. add_permut.\n    + rewrite IHP1, pow_pos_add;rsimpl. add_permut.\n Qed.\n\n Lemma Padd_ok P' P l : (P ++ P')@l == P@l + P'@l.\n Proof.\n  revert P l; induction P';simpl;intros;Esimpl.\n  - revert p l; induction P;simpl;intros.\n    + Esimpl; add_permut.\n    + destr_pos_sub; intros ->;Esimpl.\n      * now rewrite IHP'.\n      * rewrite IHP';Esimpl. now rewrite Pjump_add.\n      * rewrite IHP. now rewrite Pjump_add.\n    + destruct p0;simpl.\n      * rewrite IHP2;simpl. rsimpl. rewrite Pjump_xO_tail. Esimpl.\n      * rewrite IHP2;simpl. rewrite Pjump_pred_double. rsimpl.\n      * rewrite IHP'. rsimpl.\n  - destruct P;simpl.\n    + Esimpl. add_permut.\n    + destruct p0;simpl;Esimpl; rewrite IHP'2; simpl.\n      * rewrite Pjump_xO_tail. rsimpl. add_permut.\n      * rewrite Pjump_pred_double. rsimpl. add_permut.\n      * rsimpl. unfold tail. add_permut.\n    + destr_pos_sub; intros ->; Esimpl.\n      * rewrite IHP'1, IHP'2;rsimpl. add_permut.\n      * rewrite IHP'1, IHP'2;simpl;Esimpl.\n        rewrite pow_pos_add;rsimpl. add_permut.\n      * rewrite PaddX_ok by trivial; rsimpl.\n        rewrite IHP'2, pow_pos_add; rsimpl. add_permut.\n Qed.\n\n Lemma PsubX_ok P' P k l :\n  (forall P l, (P--P')@l == P@l - P'@l) ->\n  (PsubX Psub P' k P) @ l == P@l - P'@l * (hd l)^k.\n Proof.\n  intros IHP'.\n  revert k l. induction P;simpl;intros.\n  - rewrite Popp_ok;rsimpl; add_permut.\n  - destruct p; simpl;\n    rewrite Popp_ok;rsimpl;\n    rewrite ?Pjump_xO_tail, ?Pjump_pred_double; add_permut.\n  - destr_pos_sub; intros ->; Esimpl.\n    + rewrite IHP';rsimpl. add_permut.\n    + rewrite IHP', pow_pos_add;simpl;Esimpl. add_permut.\n    + rewrite IHP1, pow_pos_add;rsimpl. add_permut.\n Qed.\n\n Lemma Psub_ok P' P l : (P -- P')@l == P@l - P'@l.\n Proof.\n  revert P l; induction P';simpl;intros;Esimpl.\n  - revert p l; induction P;simpl;intros.\n    + Esimpl; add_permut.\n    + destr_pos_sub; intros ->;Esimpl.\n      * rewrite IHP';rsimpl.\n      * rewrite IHP';Esimpl. now rewrite Pjump_add.\n      * rewrite IHP. now rewrite Pjump_add.\n    + destruct p0;simpl.\n      * rewrite IHP2;simpl. rsimpl. rewrite Pjump_xO_tail. Esimpl.\n      * rewrite IHP2;simpl. rewrite Pjump_pred_double. rsimpl.\n      * rewrite IHP'. rsimpl.\n  - destruct P;simpl.\n    + Esimpl; add_permut.\n    + destruct p0;simpl;Esimpl; rewrite IHP'2; simpl.\n      * rewrite Pjump_xO_tail. rsimpl. add_permut.\n      * rewrite Pjump_pred_double. rsimpl. add_permut.\n      * rsimpl. unfold tail. add_permut.\n    + destr_pos_sub; intros ->; Esimpl.\n      * rewrite IHP'1, IHP'2;rsimpl. add_permut.\n      * rewrite IHP'1, IHP'2;simpl;Esimpl.\n        rewrite pow_pos_add;rsimpl. add_permut.\n      * rewrite PsubX_ok by trivial;rsimpl.\n        rewrite IHP'2, pow_pos_add;rsimpl. add_permut.\n Qed.\n\n Lemma PmulI_ok P' :\n   (forall P l, (Pmul P P') @ l == P @ l * P' @ l) ->\n   forall P p l, (PmulI Pmul P' p P) @ l == P @ l * P' @ (jump p l).\n Proof.\n  intros IHP'.\n  induction P;simpl;intros.\n  - Esimpl; mul_permut.\n  - destr_pos_sub; intros ->;Esimpl.\n    + now rewrite IHP'.\n    + now rewrite IHP', Pjump_add.\n    + now rewrite IHP, Pjump_add.\n  - destruct p0;Esimpl; rewrite ?IHP1, ?IHP2; rsimpl.\n    + rewrite Pjump_xO_tail. f_equiv. mul_permut.\n    + rewrite Pjump_pred_double. f_equiv. mul_permut.\n    + rewrite IHP'. f_equiv. mul_permut.\n Qed.\n\n Lemma Pmul_ok P P' l : (P**P')@l == P@l * P'@l.\n Proof.\n  revert P l;induction P';simpl;intros.\n  - apply PmulC_ok.\n  - apply PmulI_ok;trivial.\n  - destruct P.\n    + rewrite (ARmul_comm ARth). Esimpl.\n    + Esimpl. rewrite IHP'1;Esimpl. f_equiv.\n      destruct p0;rewrite IHP'2;Esimpl.\n      * now rewrite Pjump_xO_tail.\n      * rewrite Pjump_pred_double; Esimpl.\n    + rewrite Padd_ok, !mkPX_ok, Padd_ok, !mkPX_ok,\n       !IHP'1, !IHP'2, PmulI_ok; trivial. simpl. Esimpl.\n      unfold tail.\n      add_permut; f_equiv; mul_permut.\n Qed.\n\n Lemma Psquare_ok P l : (Psquare P)@l == P@l * P@l.\n Proof.\n  revert l;induction P;simpl;intros;Esimpl.\n  - apply IHP.\n  - rewrite Padd_ok, Pmul_ok;Esimpl.\n    rewrite IHP1, IHP2.\n    mul_push ((hd l)^p). now mul_push (P2@l).\n Qed.\n\n Lemma Mphi_morph M e1 e2 :\n  (forall x, e1 x = e2 x) -> M @@ e1 = M @@ e2.\n Proof.\n   revert e1 e2; induction M; simpl; intros e1 e2 EQ; trivial.\n   - apply IHM. intros; apply EQ.\n   - f_equal.\n     * apply IHM. intros; apply EQ.\n     * f_equal. apply EQ.\n Qed.\n\nLemma Mjump_xO_tail M p l :\n  M @@ (jump (xO p) (tail l)) = M @@ (jump (xI p) l).\nProof.\n  apply Mphi_morph. intros. now jump_simpl.\nQed.\n\nLemma Mjump_pred_double M p l :\n  M @@ (jump (Pos.pred_double p) (tail l)) = M @@ (jump (xO p) l).\nProof.\n  apply Mphi_morph. intros.\n  rewrite jump_pred_double. now jump_simpl.\nQed.\n\nLemma Mjump_add M i j l :\n  M @@ (jump (i + j) l) = M @@ (jump j (jump i l)).\nProof.\n  apply Mphi_morph. intros. now rewrite <- jump_add, Pos.add_comm.\nQed.\n\n Lemma mkZmon_ok M j l :\n   (mkZmon j M) @@ l == (zmon j M) @@ l.\n Proof.\n destruct M; simpl; rsimpl.\n Qed.\n\n Lemma zmon_pred_ok M j l :\n   (zmon_pred j M) @@ (tail l) == (zmon j M) @@ l.\n Proof.\n   destruct j; simpl; rewrite ?mkZmon_ok; simpl; rsimpl.\n   - now rewrite Mjump_xO_tail.\n   - rewrite Mjump_pred_double; rsimpl.\n Qed.\n\n Lemma mkVmon_ok M i l :\n   (mkVmon i M)@@l == M@@l * (hd l)^i.\n Proof.\n  destruct M;simpl;intros;rsimpl.\n  - rewrite zmon_pred_ok;simpl;rsimpl.\n  - rewrite pow_pos_add;rsimpl.\n Qed.\n\n Ltac destr_mfactor R S := match goal with\n  | H : context [MFactor ?P _] |- context [MFactor ?P ?M] =>\n    specialize (H M); destruct MFactor as (R,S)\n end.\n\n Lemma Mphi_ok P M l :\n   let (Q,R) := MFactor P M in\n     P@l == Q@l + M@@l * R@l.\n Proof.\n revert M l; induction P; destruct M; intros l; simpl; auto; Esimpl.\n - case Pos.compare_spec; intros He; simpl.\n   * destr_mfactor R1 S1. now rewrite IHP, He, !mkPinj_ok.\n   * destr_mfactor R1 S1. rewrite IHP; simpl.\n     now rewrite !mkPinj_ok, <- Mjump_add, Pos.add_comm, Pos.sub_add.\n   * Esimpl.\n - destr_mfactor R1 S1. destr_mfactor R2 S2.\n   rewrite IHP1, IHP2, !mkPX_ok, zmon_pred_ok; simpl; rsimpl.\n   add_permut.\n - case Pos.compare_spec; intros He; simpl; destr_mfactor R1 S1;\n   rewrite ?He, IHP1, mkPX_ok, ?mkZmon_ok; simpl; rsimpl;\n   unfold tail; add_permut; mul_permut.\n   * rewrite <- pow_pos_add, Pos.add_comm, Pos.sub_add by trivial; rsimpl.\n   * rewrite mkPX_ok. simpl. Esimpl. mul_permut.\n     rewrite <- pow_pos_add, Pos.sub_add by trivial; rsimpl.\n Qed.\n\n Lemma POneSubst_ok P1 M1 P2 P3 l :\n   POneSubst P1 M1 P2 = Some P3 -> M1@@l == P2@l ->\n   P1@l == P3@l.\n Proof.\n unfold POneSubst.\n assert (H := Mphi_ok P1). destr_mfactor R1 S1. rewrite H; clear H.\n intros EQ EQ'. replace P3 with (R1 ++ P2 ** S1).\n - rewrite EQ', Padd_ok, Pmul_ok; rsimpl.\n - revert EQ. destruct S1; try now injection 1.\n   case ceqb_spec; now inversion 2.\n Qed.\n\n Lemma PNSubst1_ok n P1 M1 P2 l :\n    M1@@l == P2@l -> P1@l == (PNSubst1 P1 M1 P2 n)@l.\n Proof.\n revert P1. induction n; simpl; intros P1;\n generalize (POneSubst_ok P1 M1 P2); destruct POneSubst;\n   intros; rewrite <- ?IHn; auto; reflexivity.\n Qed.\n\n Lemma PNSubst_ok n P1 M1 P2 l P3 :\n    PNSubst P1 M1 P2 n = Some P3 -> M1@@l == P2@l -> P1@l == P3@l.\n Proof.\n unfold PNSubst.\n assert (H := POneSubst_ok P1 M1 P2); destruct POneSubst; try discriminate.\n destruct n; inversion_clear 1.\n intros. rewrite <- PNSubst1_ok; auto.\n Qed.\n\n Fixpoint MPcond (LM1: list (Mon * Pol)) (l: Env R) : Prop :=\n   match LM1 with\n   | cons (M1,P2) LM2 => (M1@@l == P2@l) /\\ MPcond LM2 l\n   | _ => True\n   end.\n\n Lemma PSubstL1_ok n LM1 P1 l :\n   MPcond LM1 l -> P1@l == (PSubstL1 P1 LM1 n)@l.\n Proof.\n revert P1; induction LM1 as [|(M2,P2) LM2 IH]; simpl; intros.\n - reflexivity.\n - rewrite <- IH by intuition. now apply PNSubst1_ok.\n Qed.\n\n Lemma PSubstL_ok n LM1 P1 P2 l :\n   PSubstL P1 LM1 n = Some P2 -> MPcond LM1 l -> P1@l == P2@l.\n Proof.\n revert P1. induction LM1 as [|(M2,P2') LM2 IH]; simpl; intros.\n - discriminate.\n - assert (H':=PNSubst_ok n P3 M2 P2'). destruct PNSubst.\n   * injection H as <-. rewrite <- PSubstL1_ok; intuition.\n   * now apply IH.\n Qed.\n\n Lemma PNSubstL_ok m n LM1 P1 l :\n    MPcond LM1 l -> P1@l == (PNSubstL P1 LM1 m n)@l.\n Proof.\n revert LM1 P1. induction m; simpl; intros;\n assert (H' := PSubstL_ok n LM1 P2); destruct PSubstL;\n auto; try reflexivity.\n rewrite <- IHm; auto.\n Qed.\n\n (** Definition of polynomial expressions *)\n\n Inductive PExpr : Type :=\n  | PEc : C -> PExpr\n  | PEX : positive -> PExpr\n  | PEadd : PExpr -> PExpr -> PExpr\n  | PEsub : PExpr -> PExpr -> PExpr\n  | PEmul : PExpr -> PExpr -> PExpr\n  | PEopp : PExpr -> PExpr\n  | PEpow : PExpr -> N -> PExpr.\n\n (** evaluation of polynomial expressions towards R *)\n Definition mk_X j := mkPinj_pred j mkX.\n\n (** evaluation of polynomial expressions towards R *)\n\n Fixpoint PEeval (l:Env R) (pe:PExpr) : R :=\n   match pe with\n   | PEc c => phi c\n   | PEX j => nth j l\n   | PEadd pe1 pe2 => (PEeval l pe1) + (PEeval l pe2)\n   | PEsub pe1 pe2 => (PEeval l pe1) - (PEeval l pe2)\n   | PEmul pe1 pe2 => (PEeval l pe1) * (PEeval l pe2)\n   | PEopp pe1 => - (PEeval l pe1)\n   | PEpow pe1 n => rpow (PEeval l pe1) (Cp_phi n)\n   end.\n\n (** Correctness proofs *)\n\n Lemma mkX_ok p l : nth p l == (mk_X p) @ l.\n Proof.\n  destruct p;simpl;intros;Esimpl;trivial.\n  rewrite nth_spec ; auto.\n  unfold hd.\n  now rewrite <- nth_pred_double, nth_jump.\n Qed.\n\n Hint Rewrite Padd_ok Psub_ok : Esimpl.\n\nSection POWER.\n  Variable subst_l : Pol -> Pol.\n  Fixpoint Ppow_pos (res P:Pol) (p:positive) : Pol :=\n   match p with\n   | xH => subst_l (res ** P)\n   | xO p => Ppow_pos (Ppow_pos res P p) P p\n   | xI p => subst_l ((Ppow_pos (Ppow_pos res P p) P p) ** P)\n   end.\n\n  Definition Ppow_N P n :=\n   match n with\n   | N0 => P1\n   | Npos p => Ppow_pos P1 P p\n   end.\n\n  Lemma Ppow_pos_ok l :\n    (forall P, subst_l P@l == P@l) ->\n    forall res P p, (Ppow_pos res P p)@l == res@l * (pow_pos Pmul P p)@l.\n  Proof.\n   intros subst_l_ok res P p. revert res.\n   induction p;simpl;intros; rewrite ?subst_l_ok, ?Pmul_ok, ?IHp;\n    mul_permut.\n  Qed.\n\n  Lemma Ppow_N_ok l :\n    (forall P, subst_l P@l == P@l) ->\n    forall P n, (Ppow_N P n)@l == (pow_N P1 Pmul P n)@l.\n  Proof.\n  destruct n;simpl.\n  - reflexivity.\n  - rewrite Ppow_pos_ok by trivial. Esimpl.\n  Qed.\n\n End POWER.\n\n (** Normalization and rewriting *)\n\n Section NORM_SUBST_REC.\n  Variable n : nat.\n  Variable lmp:list (Mon*Pol).\n  Let subst_l P := PNSubstL P lmp n n.\n  Let Pmul_subst P1 P2 := subst_l (Pmul P1 P2).\n  Let Ppow_subst := Ppow_N subst_l.\n\n  Fixpoint norm_aux (pe:PExpr) : Pol :=\n   match pe with\n   | PEc c => Pc c\n   | PEX j => mk_X j\n   | PEadd (PEopp pe1) pe2 => Psub (norm_aux pe2) (norm_aux pe1)\n   | PEadd pe1 (PEopp pe2) =>\n     Psub (norm_aux pe1) (norm_aux pe2)\n   | PEadd pe1 pe2 => Padd (norm_aux  pe1) (norm_aux pe2)\n   | PEsub pe1 pe2 => Psub (norm_aux pe1) (norm_aux pe2)\n   | PEmul pe1 pe2 => Pmul (norm_aux pe1) (norm_aux pe2)\n   | PEopp pe1 => Popp (norm_aux pe1)\n   | PEpow pe1 n => Ppow_N (fun p => p) (norm_aux pe1) n\n   end.\n\n  Definition norm_subst pe := subst_l (norm_aux pe).\n\n  (** Internally, [norm_aux] is expanded in a large number of cases.\n      To speed-up proofs, we use an alternative definition. *)\n\n  Definition get_PEopp pe :=\n   match pe with\n   | PEopp pe' => Some pe'\n   | _ => None\n   end.\n\n  Lemma norm_aux_PEadd pe1 pe2 :\n    norm_aux (PEadd pe1 pe2) =\n    match get_PEopp pe1, get_PEopp pe2 with\n    | Some pe1', _ => (norm_aux pe2) -- (norm_aux pe1')\n    | None, Some pe2' => (norm_aux pe1) -- (norm_aux pe2')\n    | None, None => (norm_aux pe1) ++ (norm_aux pe2)\n    end.\n  Proof.\n  simpl (norm_aux (PEadd _ _)).\n  destruct pe1; [ | | | | | reflexivity | ];\n   destruct pe2; simpl get_PEopp; reflexivity.\n  Qed.\n\n  Lemma norm_aux_PEopp pe :\n    match get_PEopp pe with\n    | Some pe' => norm_aux pe = -- (norm_aux pe')\n    | None => True\n    end.\n  Proof.\n  now destruct pe.\n  Qed.\n\n  Lemma norm_aux_spec l pe :\n    PEeval l pe == (norm_aux pe)@l.\n  Proof.\n   intros.\n   induction pe.\n   - reflexivity.\n   - apply mkX_ok.\n   - simpl PEeval. rewrite IHpe1, IHpe2.\n     assert (H1 := norm_aux_PEopp pe1).\n     assert (H2 := norm_aux_PEopp pe2).\n     rewrite norm_aux_PEadd.\n     do 2 destruct get_PEopp; rewrite ?H1, ?H2; Esimpl; add_permut.\n   - simpl. rewrite IHpe1, IHpe2. Esimpl.\n   - simpl. rewrite IHpe1, IHpe2. now rewrite Pmul_ok.\n   - simpl. rewrite IHpe. Esimpl.\n   - simpl. rewrite Ppow_N_ok by reflexivity.\n     rewrite pow_th.(rpow_pow_N). destruct n0; simpl; Esimpl.\n     induction p;simpl; now rewrite ?IHp, ?IHpe, ?Pms_ok, ?Pmul_ok.\n  Qed.\n\n End NORM_SUBST_REC.\n\nEnd MakeRingPol.\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/plugins/micromega/EnvRing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.660679019558187}}
{"text": "Inductive Exp :=\n| number : nat -> Exp\n| plus : Exp -> Exp -> Exp.\n\nCompute (number 0).\nCompute (plus (number 0) (number 7)).\n\nCoercion number : nat >-> Exp.\n\nCompute (plus 0 7).\n\nNotation \"A +' B\" := (plus A B) (at level 50).\nCompute (0 +' 7 +' 6).", "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/curs3_exp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6606790041689592}}
{"text": "Require Import Notation.\nRequire Import Axioms.\nRequire Import GeneralTactics.\n\nRequire Import Coq.Logic.FinFun.\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Sets.Ensembles.\nRequire Import Coq.Program.Basics.\n\n(* Require Export Coq.Sets.Ensembles. *)\n\nOpen Scope program_scope.\n\n\n(* This representation of equivalent-class predicates is inspired by \n   the presentation in the HoTT book (section 6.10)\n *)\n\nSection Quotient.\n\nContext {A} (R: relation A) {equivR: Equivalence R}.\n\nNotation \"x ∼ y\" := (R x y) (at level 70, no associativity).\n\nDefinition In {U} A x := In U A x.\n\n\nDefinition equiv_class (e: Ensemble A) :=\n  exists x, forall y, x ∼ y <-> In e y.\n\nTheorem ec_all_in_related : forall e,\n  equiv_class e ->\n  forall x y, In e x -> In e y -> x ∼ y.\nProof using A R equivR.\n  intros * H * Hx Hy.\n  destruct H as [a H].\n  transitivity a.\n  - symmetry.\n    now apply H.\n  - now apply H.\nQed.\n\nTheorem ec_all_related_in : forall e,\n  equiv_class e ->\n  forall x y, x ∼ y -> In e x -> In e y.\nProof using A R equivR.\n  intros * H * Heq Hx.\n  destruct H as [a H].\n  apply H.\n  transitivity x.\n  - now apply H.\n  - assumption.\nQed.\n\nDefinition quotient := {e | equiv_class e}.\n\nDefinition class_to_ensemble (c: quotient) : Ensemble A := proj1_sig c.\nCoercion class_to_ensemble : quotient >-> Ensemble.\n\nDefinition qclass (a: A) : quotient.\n  (* refine (exist _ (λ x, a ∼ x) _). *)\n  refine (exist _ (R a) _).\nProof.\n  now exists a.\nDefined.\n\nTheorem in_qclass : forall a,\n  In (qclass a) a.\nProof using A R equivR.\n  intros *.\n  cbn.\n  reflexivity.\nQed.\n\nTheorem qclass_eq : forall a (c: quotient),\n  In c a -> \n  c = qclass a.\nProof using A R equivR.\n  intros * Hin.\n  destruct c as [e p].\n  simpl in Hin.\n  apply exist_eq.\n  extensionality x.\n  extensionality H.\n  - follows eapply ec_all_in_related.\n  - follows eapply ec_all_related_in.\nQed.\n\nLemma in_some_class : forall a,\n  exists c: quotient, In c a.\nProof using A R equivR.\n  intros *.\n  exists (qclass a).\n  apply in_qclass.\nQed.\n\nTheorem class_nonempty : forall c: quotient,\n  exists x, In c x.\nProof using A R equivR.\n  intros *.\n  destruct c as (? & a & p).\n  exists a.\n  apply p.\n  reflexivity.\nQed.\n\nLemma classes_partition : forall a,\n  exists! c: quotient, In c a.\nProof using A R equivR.\n  intros *.\n  exists (qclass a).\n  split.\n  - apply in_qclass.\n  - intros * Hin.\n    symmetry.\n    now apply qclass_eq.\nQed.\n\nLemma class_unique : forall (c1 c2: quotient) a,\n  In c1 a ->\n  In c2 a ->\n  c1 = c2.\nProof using A R equivR.\n  intros * Hin Hin'.\n  apply qclass_eq in Hin, Hin'.\n  now subst.\nQed.\n\nLemma classes_disjoint : forall (c1 c2: quotient) a,\n  c1 <> c2 ->\n  In c1 a -> ~ In c2 a.\nProof using A R equivR.\n  intros * Hneq Hin Hin'.\n  applyc Hneq.\n  follows eapply class_unique.\nQed.\n\nTheorem qclass_surjective : Surjective qclass.\nProof using A R equivR.\n  intros c.\n  destruct (class_nonempty c) as [a ?].\n  exists a.\n  symmetry.\n  now apply qclass_eq.\nQed.\n\nTheorem qclass_spec : forall x y,\n  (qclass x = qclass y) = (x ∼ y).\nProof using A R equivR.\n  intros *.\n  extensionality H.\n  - apply eq_sig_fst in H.\n    symmetry.\n    pattern x.\n    induction H.\n    reflexivity.\n  - apply exist_eq.\n    extensionality a.\n    extensionality H'.\n    + now transitivity x.\n    + now transitivity y.\nQed.\n\nDefinition quotient_rect :\n  forall (P: quotient -> Type),\n    (forall Q p, P (exist _ Q p)) ->\n    forall c, P c.\nProof using.\n  intros * H *.\n  destruct c.\n  apply H.\nDefined.\n\nDefinition quotient_rec :\n  forall (P: quotient -> Set),\n    (forall Q p, P (exist _ Q p)) ->\n    forall c, P c\n  := quotient_rect.\n\n(* Our inductive principle is more pleasant, because we can reflect arbitrary \n   classes to the canonical qclass representation\n *)\nTheorem quotient_ind :\n  forall (P: quotient -> Prop),\n    (forall a, P (qclass a)) ->\n    forall c, P c.\nProof using A R equivR.\n  intros * H *.\n  destruct c as [Q p].\n  eta.\n  destruct (qclass_surjective (exist _ Q p)) as [? <-].\n  assumption!.\nQed.\n\nDefinition respects_equiv (f: A -> A) :=\n  forall x y, x ∼ y -> (f x) ∼ (f y).\n\nDefinition respects_equiv2 (f: A -> A -> A) :=\n  forall x x' y y', x ∼ x' -> y ∼ y' -> (f x y) ∼ (f x' y').\n\nDefinition liftQ (f: A -> A) (re: respects_equiv f) : quotient -> quotient.\nProof using A R equivR.\n  intros [P p].\n  refine (exist _ (λ a, ∃ x, (f x) ∼ a /\\ P x) _).\n  destruct p as [a p].\n  exists (f a).\n  intros *.\n  split; intro H.\n  - exists a.\n    split.\n    + assumption.\n    + apply p.\n      reflexivity.\n  - destruct H as (? & <- & ?).\n    apply re.\n    now apply p.\nDefined.\n \nTheorem liftQ_qclass : forall (f: A -> A) (re: respects_equiv f) a,\n  liftQ f re (qclass a) = qclass (f a).\nProof using.\n  intros *.\n  apply exist_eq'.\n  simpl.\n  extensionality x.\n  extensionality; split.\n  - intros (? & <- & ?).\n    now apply re.\n  - intros ?.\n    now exists a.\nQed.\n\nDefinition liftQ2 (f: A -> A -> A) (re: respects_equiv2 f) :\n  quotient -> quotient -> quotient.\nProof using A R equivR.\n  intros [P p] [Q q].\n  refine (exist _ (λ a, ∃ x y, (f x y) ∼ a /\\ P x /\\ Q y) _).\n  destruct p as [a p], q as [a' q].\n  exists (f a a').\n  intros *.\n  split; intro H.\n  - exists a a'.\n    max split.\n    + assumption.\n    + now apply p.\n    + now apply q.\n  - destruct H as (? & ? & <- & ? & ?).\n    apply re.\n    + now apply p.\n    + now apply q.\nDefined.\n\nTheorem liftQ2_qclass : forall (f: A -> A -> A) (re: respects_equiv2 f) x y,\n  liftQ2 f re (qclass x) (qclass y) = qclass (f x y).\nProof using.\n  intros *.\n  apply exist_eq'.\n  simpl.\n  extensionality a.\n  extensionality; split.\n  - intros (x' & y' & <- & H & H').\n    now apply re.\n  - intros ?.\n    now exists x y.\nQed.\n\nEnd Quotient.\n\nArguments quotient A R : clear implicits.\nNotation \"A / R\" := (quotient A R) : type_scope.\n\nNotation \"f 'respects' R\"  := (respects_equiv  R f) (at level 50).\nNotation \"f 'respects2' R\" := (respects_equiv2 R f) (at level 50).\n\nClose Scope program_scope.", "meta": {"author": "ku-sldg", "repo": "CTL", "sha": "75bb188ae2689baeb28d34a789fe839871c240fe", "save_path": "github-repos/coq/ku-sldg-CTL", "path": "github-repos/coq/ku-sldg-CTL/CTL-75bb188ae2689baeb28d34a789fe839871c240fe/Glib/Quotient.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6606551269601698}}
{"text": "Require Export GeoCoq.Tarski_dev.Ch04_col.\n\nSection T5.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma l5_1 : forall A B C D,\n  A <> B -> Bet A B C -> Bet A B D -> Bet A C D \\/ Bet A D C.\nProof.\n    intros.\n    prolong A D C' C D.\n    prolong A C D' C D.\n    prolong A C' B' C B.\n    prolong A D' B'' D B.\n    assert (Cong B C' B'' C).\n      apply (l2_11 B D C' B'' D' C).\n        apply between_exchange3 with A; Between.\n        apply between_inner_transitivity with A; Between.\n        Cong.\n      apply cong_transitivity with C D; Cong.\n    assert (Cong B B' B'' B).\n      {\n      apply (l2_11 B C' B' B'' C B); Cong.\n\n        {\n        assert (Bet A B C'); [|eBetween].\n        induction (eq_dec_points B D); [treat_equalities; auto|].\n        apply between_symmetry.\n        apply outer_transitivity_between2 with D; eBetween.\n        }\n\n        {\n        induction (eq_dec_points C D'); [treat_equalities; eBetween|].\n        apply outer_transitivity_between2 with D'; eBetween.\n        }\n      }\n    assert(B'' =  B').\n      apply (construction_uniqueness A B B B''); Cong.\n        apply between_exchange4 with D'; Between;\n        apply between_exchange4 with C; Between.\n      apply between_exchange4 with C'; Between;\n      apply between_exchange4 with D; Between.\n    subst B''.\n    assert (Bet B C D') by (apply between_exchange3 with A; assumption).\n    assert (FSC B C D' C' B' C' D C).\n      repeat split; Cong.\n        left; apply between_exchange3 with A; Between.\n        apply (l2_11 B C D' B' C' D); Cong.\n          apply between_symmetry.\n          apply between_exchange3 with A; assumption.\n        apply cong_transitivity with C D; Cong.\n      apply cong_transitivity with C D; Cong.\n    induction (eq_dec_points B C).\n      subst C; auto.\n    assert (Cong D' C' D C) by (eapply l4_16; try apply H13; assumption).\n    assert (exists E, Bet C E C' /\\ Bet D E D') by (apply inner_pasch with A; Between).\n    ex_and H16 E.\n    assert (IFSC D E D' C D E D' C') by (unfold IFSC; repeat split; Cong; apply cong_transitivity with C D; Cong).\n    assert (IFSC C E C' D C E C' D') by (unfold IFSC; repeat split; Cong; apply cong_transitivity with C D; Cong).\n    assert (Cong E C E C') by (eapply l4_2; try apply H18; auto).\n    assert (Cong E D E D') by (eapply l4_2; try apply H19; auto).\n    induction (eq_dec_points C C').\n      subst C'; right; assumption.\n    show_distinct C D'.\n      auto.\n    prolong C' C P C D'.\n    prolong D' C R C E.\n    prolong P R Q R P.\n    assert (FSC D' C R P P C E D').\n      repeat split; Col; Cong.\n      apply l2_11 with C C; Cong.\n      apply between_inner_transitivity with C'; Between.\n    assert (Cong R P E D') by (eauto using l4_16).\n    assert (Cong R Q E D).\n      eapply cong_transitivity.\n        apply cong_transitivity with R P; Cong.\n      apply cong_transitivity with E D'; Cong.\n    assert (FSC D' E D C P R Q C).\n      repeat split; Col; Cong.\n      eapply (l2_11 D' E D P R Q); Between; Cong.\n    assert (Cong D C Q C).\n      induction (eq_dec_points D' E).\n        unfold IFSC, Cong_3 in *; spliter; treat_equalities; Cong.\n      apply l4_16 with D' E P R; assumption.\n    assert (Cong C P C Q).\n      unfold FSC, Cong_3 in *; spliter.\n      apply cong_transitivity with C D; Cong.\n      apply cong_transitivity with C D'; Cong.\n    show_distinct R C.\n      auto.\n    assert (Cong D' P D' Q) by (apply (l4_17 R C); unfold Col; Between; Cong).\n    assert (Cong B P B Q).\n      apply l4_17 with C D'; Col.\n    assert (Cong B' P B' Q).\n      apply (l4_17 C D'); Cong.\n      left.\n      apply between_exchange3 with A; assumption.\n    assert (Cong C' P C' Q).\n      assert (Bet B C' B').\n        apply between_exchange3 with A; try assumption.\n        apply between_exchange4 with D; try assumption.\n      eapply l4_17 with B B'; Cong; Col.\n      intro; treat_equalities; auto.\n    assert (Cong P P P Q).\n      apply l4_17 with C C'; Col.\n    treat_equalities.\n    left; assumption.\nQed.\n\nLemma l5_2 : forall A B C D,\n  A <> B -> Bet A B C -> Bet A B D -> Bet B C D \\/ Bet B D C.\nProof.\n    intros.\n    assert (Bet A C D \\/ Bet A D C) by (eapply l5_1; eauto).\n    induction H2.\n    left; eBetween.\n    right; eBetween.\nQed.\n\nLemma segment_construction_2 :\n  forall A Q B C, A <> Q -> exists X, (Bet Q A X \\/ Bet Q X A) /\\ Cong Q X B C.\nProof.\n    intros.\n    prolong A Q A' A Q.\n    prolong A' Q X B C.\n    exists X.\n    show_distinct A' Q.\n    solve [intuition].\n    split; try assumption.\n    eapply (l5_2 A' Q); Between.\nQed.\n\nLemma l5_3 : forall A B C D,\n Bet A B D -> Bet A C D -> Bet A B C \\/ Bet A C B.\nProof.\n    intros.\n    assert (exists P, Bet D A P /\\ A<>P) by  (apply point_construction_different).\n    ex_and H1 P.\n    assert (Bet P A B) by eBetween.\n    assert (Bet P A C) by eBetween.\n    apply (l5_2 P);auto.\nQed.\n\nLemma bet3__bet : forall A B C D E, Bet A B E -> Bet A D E -> Bet B C D -> Bet A C E.\nProof.\n    intros.\n    destruct (l5_3 A B D E H H0).\n      apply between_exchange4 with D; trivial.\n      apply between_exchange2 with B; assumption.\n    apply between_exchange4 with B; trivial.\n    apply between_exchange2 with D; Between.\nQed.\n\nLemma le_bet : forall A B C D, Le C D A B -> exists X, Bet A X B /\\ Cong A X C D.\nProof.\n    intros.\n    unfold Le in H.\n    ex_and H Y.\n    exists Y;split;Cong.\nQed.\n\nLemma l5_5_1 : forall A B C D,\n  Le A B C D -> exists x, Bet A B x /\\ Cong A x C D.\nProof.\n    unfold Le.\n    intros.\n    ex_and H P.\n    prolong A B x P D.\n    exists x.\n    split.\n      assumption.\n    eapply l2_11;eauto.\nQed.\n\nLemma l5_5_2 : forall A B C D,\n (exists x, Bet A B x /\\ Cong A x C D) -> Le A B C D.\nProof.\n    intros.\n    ex_and H P.\n    unfold Le.\n    assert (exists B' : Tpoint, Bet C B' D /\\ Cong_3 A B P C B' D) by (eapply l4_5;auto).\n    ex_and H1 y.\n    exists y.\n    unfold Cong_3 in *;intuition.\nQed.\n\nLemma l5_6 : forall A B C D A' B' C' D',\n Le A B C D -> Cong A B A' B' -> Cong C D C' D' -> Le A' B' C' D'.\nProof.\n    unfold Le.\n    intros.\n    spliter.\n    ex_and H y.\n    assert (exists z : Tpoint, Bet C' z D' /\\ Cong_3 C y D C' z D') by (eapply l4_5;auto).\n    ex_and H3 z.\n    exists z.\n    split.\n      assumption.\n    unfold Cong_3 in *; spliter.\n    apply cong_transitivity with A B; Cong.\n    apply cong_transitivity with C y; assumption.\nQed.\n\nLemma le_reflexivity : forall A B, Le A B A B.\nProof.\n    unfold Le.\n    intros.\n    exists B.\n    split; Between; Cong.\nQed.\n\nLemma le_transitivity : forall A B C D E F, Le A B C D -> Le C D E F -> Le A B E F.\nProof.\n    unfold Le.\n    intros.\n    ex_and H y.\n    ex_and H0 z.\n    assert (exists P : Tpoint, Bet E P z /\\ Cong_3 C y D E P z) by (eapply l4_5;assumption).\n    ex_and H3 P.\n    exists P.\n    split.\n      eBetween.\n    unfold Cong_3 in H4; spliter; apply cong_transitivity with C y; Cong.\nQed.\n\nLemma between_cong : forall A B C, Bet A C B -> Cong A C A B -> C = B.\nProof.\n    intros.\n    assert (Bet A B C).\n    eapply l4_6 with A C B; unfold Cong_3; repeat split; Cong.\n    eapply between_equality; eBetween.\nQed.\n\nLemma cong3_symmetry : forall A B C A' B' C' : Tpoint , Cong_3 A B C A' B' C' -> Cong_3 A' B' C' A B C.\nProof.\n    unfold Cong_3.\n    intros.\n    intuition.\nQed.\n\nLemma between_cong_2 : forall A B D E, Bet A D B -> Bet A E B -> Cong A D A E -> D = E.\nProof.\n    intros.\n    apply cong3_bet_eq with A B; unfold Cong_3; repeat split; Cong.\n    eapply (l4_2 B E A B B D A B).\n    unfold IFSC; repeat split; Cong; Between.\nQed.\n\nLemma between_cong_3 :\n  forall A B D E, A <> B -> Bet A B D -> Bet A B E -> Cong B D B E -> D = E.\nProof.\n    intros.\n    assert (T:=l5_2 A B D E H H0 H1).\n    elim T; intro; clear T.\n    apply between_cong with B; Cong.\n    symmetry; apply between_cong with B; Cong.\nQed.\n\nLemma le_anti_symmetry : forall A B C D, Le A B C D -> Le C D A B -> Cong A B C D.\nProof.\n    intros.\n    assert (exists T, Bet C D T /\\ Cong C T A B) by (apply l5_5_1;assumption).\n    unfold Le in H.\n    ex_and H Y.\n    ex_and H1 T.\n    assert (Cong C Y C T) by eCong.\n    assert (Bet C Y T) by eBetween.\n    assert (Y=T) by (eapply between_cong;eauto).\n    subst Y.\n    assert (T=D) by (eapply between_equality;eBetween).\n    subst T.\n    Cong.\nQed.\n\nLemma cong_dec : forall A B C D,\n  Cong A B C D \\/ ~ Cong A B C D.\nProof.\n    intros.\n    elim (eq_dec_points A B); intro; subst; elim (eq_dec_points C D); intro; subst.\n    left; Cong.\n    right; intro; apply H; apply cong_identity with B; Cong.\n    right; intro; apply H; apply cong_identity with D; Cong.\n    elim (segment_construction_2 B A C D).\n    intros D' HD'.\n    spliter.\n    elim (eq_dec_points B D');intro.\n    subst; left; assumption.\n    right; intro.\n    assert (Cong A D' A B) by CongR.\n    elim H1; intro; clear H1.\n    assert (B = D') by (apply (between_cong A D' B); Cong).\n    subst;intuition.\n    assert (D'=B) by (apply (between_cong A B D');assumption).\n    subst;intuition.\n    intuition.\nQed.\n\nLemma bet_dec : forall A B C, Bet A B C  \\/  ~ Bet A B C.\nProof.\n    intros.\n    elim (segment_construction A B B C); intros C' HC'.\n    spliter.\n    elim (eq_dec_points C C'); intro.\n    subst; tauto.\n    elim (eq_dec_points A B);intro.\n    left; subst; Between.\n    right; intro; apply H1; apply between_cong_3 with A B; Cong.\nQed.\n\nLemma col_dec : forall A B C, Col A B C \\/ ~ Col A B C.\nProof.\n    intros.\n    unfold Col.\n    elim (bet_dec A B C); intro; elim (bet_dec B C A); intro; elim (bet_dec C A B); intro; tauto.\nQed.\n\n\nLemma le_trivial : forall A C D, Le A A C D .\nProof.\n    intros.\n    unfold Le.\n    exists C.\n    split; Between; Cong.\nQed.\n\nLemma le_cases : forall A B C D, Le A B C D \\/ Le C D A B.\nProof.\n    intros.\n    induction(eq_dec_points A B).\n      subst B; left; apply le_trivial.\n    assert (exists X : Tpoint, (Bet A B X \\/ Bet A X B) /\\ Cong A X C D) by (eapply (segment_construction_2 B A C D);auto).\n    ex_and H0 X.\n    induction H0.\n      left; apply l5_5_2; exists X; split; assumption.\n    right; unfold Le; exists X; split; Cong.\nQed.\n\nLemma le_zero : forall A B C, Le A B C C -> A=B.\nProof.\n    intros.\n    assert (Le C C A B) by apply le_trivial.\n    assert (Cong A B C C) by (apply le_anti_symmetry;assumption).\n    treat_equalities;auto.\nQed.\n\nLemma le_diff : forall A B C D, A <> B -> Le A B C D -> C <> D.\nProof.\n  intros A B C D HAB HLe Heq.\n  subst D; apply HAB, le_zero with C; assumption.\nQed.\n\nLemma lt_diff : forall A B C D, Lt A B C D -> C <> D.\nProof.\n  intros A B C D HLt Heq.\n  subst D.\n  destruct HLt as [HLe HNCong].\n  assert (A = B) by (apply le_zero with C; assumption).\n  subst B; Cong.\nQed.\n\nLemma bet_cong_eq :\n forall A B C D,\n  Bet A B C ->\n  Bet A C D ->\n  Cong B C A D ->\n  C = D /\\ A = B.\nProof.\n    intros.\n    assert(C = D).\n      assert(Le A C A D) by (eapply l5_5_2; exists D; split; Cong).\n      assert(Le C B C A) by (eapply l5_5_2; exists A; split; Between; Cong).\n      assert(Cong A C A D) by (eapply le_anti_symmetry; try assumption; apply l5_6 with C B C A; Cong).\n      apply between_cong with A; assumption.\n    split; try assumption.\n    subst D; apply sym_equal.\n    eapply (between_cong C); Between; Cong.\nQed.\n\nLemma cong__le : forall A B C D, Cong A B C D -> Le A B C D.\nProof.\n  intros A B C D H.\n  exists D.\n  split.\n  Between.\n  Cong.\nQed.\n\nLemma cong__le3412 : forall A B C D, Cong A B C D -> Le C D A B.\nProof.\n  intros A B C D HCong.\n  apply cong__le.\n  Cong.\nQed.\n\nLemma le1221 : forall A B, Le A B B A.\nProof.\n  intros A B.\n  apply cong__le; Cong.\nQed.\n\nLemma le_left_comm : forall A B C D, Le A B C D -> Le B A C D.\nProof.\n  intros A B C D Hle.\n  apply (le_transitivity _ _ A B); auto.\n  apply le1221; auto.\nQed.\n\nLemma le_right_comm : forall A B C D, Le A B C D -> Le A B D C.\nProof.\n  intros A B C D Hle.\n  apply (le_transitivity _ _ C D); auto.\n  apply le1221; auto.\nQed.\n\nLemma le_comm : forall A B C D, Le A B C D -> Le B A D C.\nProof.\n  intros.\n  apply le_left_comm.\n  apply le_right_comm.\n  assumption.\nQed.\n\nLemma ge_left_comm : forall A B C D, Ge A B C D -> Ge B A C D.\nProof.\n    intros.\n    unfold Ge in *.\n    apply le_right_comm.\n    assumption.\nQed.\n\nLemma ge_right_comm : forall A B C D, Ge A B C D -> Ge A B D C.\nProof.\n    intros.\n    unfold Ge in *.\n    apply le_left_comm.\n    assumption.\nQed.\n\nLemma ge_comm :  forall A B C D, Ge A B C D -> Ge B A D C.\nProof.\n    intros.\n    apply ge_left_comm.\n    apply ge_right_comm.\n    assumption.\nQed.\n\nLemma lt_right_comm : forall A B C D, Lt A B C D -> Lt A B D C.\nProof.\n    intros.\n    unfold Lt in *.\n    spliter.\n    split.\n      apply le_right_comm.\n      assumption.\n    intro.\n    apply H0.\n    apply cong_right_commutativity.\n    assumption.\nQed.\n\nLemma lt_left_comm : forall A B  C D, Lt A B C D -> Lt B A C D.\nProof.\n    intros.\n    unfold Lt in *.\n    spliter.\n    split.\n      unfold Le in *.\n      ex_and H P.\n      exists P.\n      apply cong_left_commutativity in H1.\n      split; assumption.\n    intro.\n    apply H0.\n    apply cong_left_commutativity.\n    assumption.\nQed.\n\nLemma lt_comm : forall A B  C D, Lt A B C D -> Lt B A D C.\nProof.\n    intros.\n    apply lt_left_comm.\n    apply lt_right_comm.\n    assumption.\nQed.\n\nLemma gt_left_comm : forall A B C D, Gt A B C D -> Gt B A C D.\nProof.\n    intros.\n    unfold Gt in *.\n    apply lt_right_comm.\n    assumption.\nQed.\n\nLemma gt_right_comm : forall A B C D, Gt A B C D -> Gt A B D C.\nProof.\n    intros.\n    unfold Gt in *.\n    apply lt_left_comm.\n    assumption.\nQed.\n\nLemma gt_comm : forall A B C D, Gt A B C D -> Gt B A D C.\nProof.\n    intros.\n    apply gt_left_comm.\n    apply gt_right_comm.\n    assumption.\nQed.\n\nLemma cong2_lt__lt : forall A B C D A' B' C' D',\n Lt A B C D -> Cong A B A' B' -> Cong C D C' D' -> Lt A' B' C' D'.\nProof.\n  intros A B C D A' B' C' D' Hlt HCong1 HCong2.\n  destruct Hlt as [Hle HNCong].\n  split.\n  apply (l5_6 A B C D); auto.\n  intro.\n  apply HNCong.\n  apply (cong_transitivity _ _ A' B'); auto.\n  apply (cong_transitivity _ _ C' D'); Cong.\nQed.\n\nLemma fourth_point : forall A B C P, A <> B -> B <> C -> Col A B P -> Bet A B C ->\n  Bet P A B \\/ Bet A P B \\/ Bet B P C \\/ Bet B C P.\nProof.\n    intros.\n    induction H1.\n      assert(HH:= l5_2 A B C P H H2 H1).\n      right; right.\n      induction HH.\n        right; auto.\n      left; auto.\n    induction H1.\n      right; left.\n      Between.\n    left; auto.\nQed.\n\nLemma third_point : forall A B P, Col A B P -> Bet P A B \\/ Bet A P B \\/ Bet A B P.\nProof.\n    intros.\n    induction H.\n      right; right.\n      auto.\n    induction H.\n      right; left.\n      Between.\n    left.\n    auto.\nQed.\n\nLemma l5_12_a : forall A B C, Bet A B C -> Le A B A C /\\ Le B C A C.\nProof.\n    intros.\n    split.\n      unfold Le.\n      exists B; split.\n        assumption.\n      apply cong_reflexivity.\n    apply le_comm.\n    unfold Le.\n    exists B.\n    split.\n      apply between_symmetry.\n      assumption.\n    apply cong_reflexivity.\nQed.\n\nLemma bet__le1213 : forall A B C, Bet A B C -> Le A B A C.\nProof.\n    intros A B C HBet.\n    destruct (l5_12_a A B C HBet); trivial.\nQed.\n\nLemma bet__le2313 : forall A B C, Bet A B C -> Le B C A C.\nProof.\n    intros A B C HBet.\n    destruct (l5_12_a A B C HBet); trivial.\nQed.\n\nLemma bet__lt1213 : forall A B C, B <> C -> Bet A B C -> Lt A B A C.\nProof.\n    intros A B C HBC HBet.\n    split.\n      apply bet__le1213; trivial.\n    intro.\n    apply HBC, between_cong with A; trivial.\nQed.\n\nLemma bet__lt2313 : forall A B C, A <> B -> Bet A B C -> Lt B C A C.\nProof.\n    intros; apply lt_comm, bet__lt1213; Between.\nQed.\n\nLemma l5_12_b : forall A B C, Col A B C -> Le A B A C -> Le B C A C -> Bet A B C.\nProof.\n    intros.\n    unfold Col in H.\n    induction H.\n      assumption.\n    induction H.\n      assert(Le B C B A /\\ Le C A B A).\n        apply l5_12_a.\n          assumption.\n      spliter.\n      assert(Cong A B A C).\n        apply le_anti_symmetry.\n          assumption.\n        apply le_comm.\n        assumption.\n      assert(C = B).\n        eapply between_cong.\n          apply between_symmetry.\n          apply H.\n        apply cong_symmetry.\n        assumption.\n      subst B.\n      apply between_trivial.\n    assert(Le B A B C /\\ Le A C B C).\n      apply l5_12_a.\n        apply between_symmetry.\n        assumption.\n    spliter.\n    assert(Cong B C A C).\n      apply le_anti_symmetry.\n        assumption.\n      assumption.\n    assert(A = B).\n      eapply between_cong.\n        apply H.\n      apply cong_symmetry.\n      apply cong_commutativity.\n      assumption.\n    subst A.\n    apply between_symmetry.\n    apply between_trivial.\nQed.\n\nLemma bet_le_eq : forall A B C, Bet A B C -> Le A C B C -> A = B.\nProof.\n    intros.\n    assert(Le C B C A).\n      eapply l5_5_2.\n      exists A.\n      split.\n        apply between_symmetry.\n        assumption.\n      apply cong_reflexivity.\n    assert(Cong A C B C).\n      apply le_anti_symmetry.\n        assumption.\n      apply le_comm.\n      assumption.\n    apply sym_equal.\n    eapply between_cong.\n      apply between_symmetry.\n      apply H.\n    apply cong_commutativity.\n    apply cong_symmetry.\n    assumption.\nQed.\n\nLemma or_lt_cong_gt : forall A B C D, Lt A B C D \\/ Gt A B C D \\/ Cong A B C D.\nProof.\n    intros.\n    assert(HH:= le_cases A B C D).\n    induction HH.\n      induction(cong_dec A B C D).\n        right; right.\n        assumption.\n      left.\n      unfold Lt.\n      split; assumption.\n    induction(cong_dec A B C D).\n      right; right.\n      assumption.\n    right; left.\n    unfold Gt.\n    unfold Lt.\n    split.\n      assumption.\n    intro.\n    apply H0.\n    apply cong_symmetry.\n    assumption.\nQed.\n\nLemma lt__le : forall A B C D, Lt A B C D -> Le A B C D.\nProof.\n    intros A B C D Hlt.\n    destruct Hlt.\n    assumption.\nQed.\n\nLemma le1234_lt__lt : forall A B C D E F, Le A B C D -> Lt C D E F -> Lt A B E F.\nProof.\n    intros A B C D E F Hle Hlt.\n    destruct Hlt as [Hle' HNCong].\n    split.\n      apply (le_transitivity _ _ C D); auto.\n    intro.\n    apply HNCong.\n    apply le_anti_symmetry; auto.\n    apply (l5_6 A B C D); Cong.\nQed.\n\nLemma le3456_lt__lt : forall A B C D E F, Lt A B C D -> Le C D E F -> Lt A B E F.\nProof.\n    intros A B C D E F Hlt Hle.\n    destruct Hlt as [Hle' HNCong].\n    split.\n      apply (le_transitivity _ _ C D); auto.\n    intro.\n    apply HNCong.\n    apply le_anti_symmetry; auto.\n    apply (l5_6 C D E F); Cong.\nQed.\n\nLemma lt_transitivity : forall A B C D E F, Lt A B C D -> Lt C D E F -> Lt A B E F.\nProof.\n    intros A B C D E F HLt1 HLt2.\n    apply le1234_lt__lt with C D; try (apply lt__le); assumption.\nQed.\n\nLemma not_and_lt : forall A B C D, ~ (Lt A B C D /\\ Lt C D A B).\nProof.\n    intros A B C D.\n    intro HInter.\n    destruct HInter as [[Hle HNCong] []].\n    apply HNCong.\n    apply le_anti_symmetry; assumption.\nQed.\n\nLemma nlt : forall A B, ~ Lt A B A B.\nProof.\n    intros A B Hlt.\n    apply (not_and_lt A B A B).\n    split; assumption.\nQed.\n\nLemma le__nlt : forall A B C D, Le A B C D -> ~ Lt C D A B.\nProof.\n    intros A B C D HLe HLt.\n    apply (not_and_lt A B C D); split; auto.\n    split; auto.\n    unfold Lt in *; spliter; auto with cong.\nQed.\n\nLemma cong__nlt : forall A B C D,\n Cong A B C D -> ~ Lt A B C D.\nProof.\n    intros P Q R S H.\n    apply le__nlt.\n    unfold Le.\n    exists Q; split; Cong; Between.\nQed.\n\nLemma nlt__le : forall A B C D, ~ Lt A B C D -> Le C D A B.\nProof.\n    intros A B C D HNLt.\n    destruct (le_cases A B C D); trivial.\n    destruct (cong_dec C D A B).\n      apply cong__le; assumption.\n    exfalso.\n    apply HNLt.\n    split; Cong.\nQed.\n\nLemma lt__nle : forall A B C D, Lt A B C D -> ~ Le C D A B.\nProof.\n    intros A B C D HLt HLe.\n    revert HLt.\n    apply le__nlt; assumption.\nQed.\n\nLemma nle__lt : forall A B C D, ~ Le A B C D -> Lt C D A B.\nProof.\n    intros A B C D HNLe.\n    destruct (le_cases A B C D).\n      contradiction.\n    split; trivial.\n    intro.\n    apply HNLe.\n    apply cong__le; Cong.\nQed.\n\nLemma lt1123 : forall A B C, B<>C -> Lt A A B C.\nProof.\nintros.\nsplit.\napply le_trivial.\nintro.\ntreat_equalities.\nintuition.\nQed.\n\nLemma bet2_le2__le : forall O o A B a b, Bet a o b -> Bet A O B -> Le o a O A -> Le o b O B -> Le a b A B.\nProof.\nintros.\ninduction(eq_dec_points A O).\ntreat_equalities; auto.\nassert (o=a). \napply le_zero with A;auto.\nsubst;auto.\ninduction(eq_dec_points B O).\ntreat_equalities;auto.\nassert (o=b). \napply le_zero with B;auto.\nsubst;auto using le_left_comm, le_right_comm.\n\n\nassert(HH:= segment_construction A O b o).\nex_and HH b'.\nassert(HH:= segment_construction B O a o).\nex_and HH a'.\n\nunfold Le in H1.\nex_and H1 a''.\n\nassert(a' = a'').\n{\n  apply(construction_uniqueness B O a o a' a'' H4);\n  eBetween.\n  Cong.\n}\ntreat_equalities.\n\nassert(Le B a' B A).\n{\n  unfold Le.\n  exists a'.\n  split; eBetween; Cong.\n}\n\nunfold Le in H2.\nex_and H2 b''.\n\nassert(b' = b'').\n{\n  apply(construction_uniqueness A O b o b' b'' H3);\n  eBetween.\n  Cong.\n}\n\ntreat_equalities.\n\nassert(Le a' b' a' B).\n{\n  unfold Le.\n  exists b'.\n  split; eBetween; Cong.\n}\n\nassert(Le a' b' A B).\n{\n  apply(le_transitivity a' b' a' B A B); auto using le_left_comm, le_right_comm.\n}\n\napply(l5_6 a' b' A B a b A B); Cong.\napply (l2_11 a' O b' a o b);\neBetween; Cong.\nQed.\n\nLemma Le_cases : forall A B C D, Le A B C D \\/ Le B A C D \\/ Le A B D C \\/ Le B A D C -> Le A B C D.\nProof.\n    intros A B C D [|[|[|]]]; [|apply le_left_comm|apply le_right_comm|apply le_comm]; assumption.\nQed.\n\nLemma Lt_cases : forall A B C D, Lt A B C D \\/ Lt B A C D \\/ Lt A B D C \\/ Lt B A D C -> Lt A B C D.\nProof.\n    intros A B C D [|[|[|]]]; [|apply lt_left_comm|apply lt_right_comm|apply lt_comm]; assumption.\nQed.\n\nEnd T5.\n\n#[global]\nHint Resolve le_reflexivity le_anti_symmetry le_trivial le_zero cong__le cong__le3412\n             le1221 le_left_comm le_right_comm le_comm lt__le bet__le1213 bet__le2313\n             lt_left_comm lt_right_comm lt_comm bet__lt1213 bet__lt2313 lt1123 : le.\n\nLtac Le := auto with le.\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Tarski_dev/Ch05_bet_le.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.6606551231811941}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(* G. Huet 1-9-95 *)\n\nRequire Import Permut Setoid.\nRequire Plus. (* comm. and ass. of plus *)\n\nSet Implicit Arguments.\n\nSection multiset_defs.\n\n  Variable A : Type.\n  Variable eqA : A -> A -> Prop.\n  Hypothesis eqA_equiv : Equivalence eqA.\n  Hypothesis Aeq_dec : forall x y:A, {eqA x y} + {~ eqA x y}.\n\n  Inductive multiset : Type :=\n    Bag : (A -> nat) -> multiset.\n\n  Definition EmptyBag := Bag (fun a:A => 0).\n  Definition SingletonBag (a:A) :=\n    Bag (fun a':A => match Aeq_dec a a' with\n                       | left _ => 1\n                       | right _ => 0\n                     end).\n\n  Definition multiplicity (m:multiset) (a:A) : nat := let (f) := m in f a.\n\n  (** multiset equality *)\n  Definition meq (m1 m2:multiset) :=\n    forall a:A, multiplicity m1 a = multiplicity m2 a.\n\n  Lemma meq_refl : forall x:multiset, meq x x.\n  Proof.\n    destruct x; unfold meq; reflexivity.\n  Qed.\n\n  Lemma meq_trans : forall x y z:multiset, meq x y -> meq y z -> meq x z.\n  Proof.\n    unfold meq.\n    destruct x; destruct y; destruct z.\n    intros; rewrite H; auto.\n  Qed.\n\n  Lemma meq_sym : forall x y:multiset, meq x y -> meq y x.\n  Proof.\n    unfold meq.\n    destruct x; destruct y; auto.\n  Qed.\n\n  (** multiset union *)\n  Definition munion (m1 m2:multiset) :=\n    Bag (fun a:A => multiplicity m1 a + multiplicity m2 a).\n\n  Lemma munion_empty_left : forall x:multiset, meq x (munion EmptyBag x).\n  Proof.\n    unfold meq; unfold munion; simpl; auto.\n  Qed.\n\n  Lemma munion_empty_right : forall x:multiset, meq x (munion x EmptyBag).\n  Proof.\n    unfold meq; unfold munion; simpl; auto.\n  Qed.\n\n  Lemma munion_comm : forall x y:multiset, meq (munion x y) (munion y x).\n  Proof.\n    unfold meq; unfold multiplicity; unfold munion.\n    destruct x; destruct y; auto with arith.\n  Qed.\n\n  Lemma munion_ass :\n    forall x y z:multiset, meq (munion (munion x y) z) (munion x (munion y z)).\n  Proof.\n    unfold meq; unfold munion; unfold multiplicity.\n    destruct x; destruct y; destruct z; auto with arith.\n  Qed.\n\n  Lemma meq_left :\n    forall x y z:multiset, meq x y -> meq (munion x z) (munion y z).\n  Proof.\n    unfold meq; unfold munion; unfold multiplicity.\n    destruct x; destruct y; destruct z.\n    intros; elim H; auto with arith.\n  Qed.\n\n  Lemma meq_right :\n    forall x y z:multiset, meq x y -> meq (munion z x) (munion z y).\n  Proof.\n    unfold meq; unfold munion; unfold multiplicity.\n    destruct x; destruct y; destruct z.\n    intros; elim H; auto.\n  Qed.\n\n  (** Here we should make multiset an abstract datatype, by hiding [Bag],\n      [munion], [multiplicity]; all further properties are proved abstractly *)\n\n  Lemma munion_rotate :\n    forall x y z:multiset, meq (munion x (munion y z)) (munion z (munion x y)).\n  Proof.\n    intros; apply (op_rotate multiset munion meq).\n      apply munion_comm.\n      apply munion_ass.\n      exact meq_trans.\n      exact meq_sym.\n      trivial.\n  Qed.\n\n  Lemma meq_congr :\n    forall x y z t:multiset, meq x y -> meq z t -> meq (munion x z) (munion y t).\n  Proof.\n    intros; apply (cong_congr multiset munion meq); auto using meq_left, meq_right.\n      exact meq_trans.\n  Qed.\n\n  Lemma munion_perm_left :\n    forall x y z:multiset, meq (munion x (munion y z)) (munion y (munion x z)).\n  Proof.\n    intros; apply (perm_left multiset munion meq); auto using munion_comm, munion_ass, meq_left, meq_right, meq_sym.\n      exact meq_trans.\n  Qed.\n\n  Lemma multiset_twist1 :\n    forall x y z t:multiset,\n      meq (munion x (munion (munion y z) t)) (munion (munion y (munion x t)) z).\n  Proof.\n    intros; apply (twist multiset munion meq); auto using munion_comm, munion_ass, meq_sym, meq_left, meq_right.\n    exact meq_trans.\n  Qed.\n\n  Lemma multiset_twist2 :\n    forall x y z t:multiset,\n      meq (munion x (munion (munion y z) t)) (munion (munion y (munion x z)) t).\n  Proof.\n    intros; apply meq_trans with (munion (munion x (munion y z)) t).\n    apply meq_sym; apply munion_ass.\n    apply meq_left; apply munion_perm_left.\n  Qed.\n\n  (** specific for treesort *)\n\n  Lemma treesort_twist1 :\n    forall x y z t u:multiset,\n      meq u (munion y z) ->\n      meq (munion x (munion u t)) (munion (munion y (munion x t)) z).\n  Proof.\n    intros; apply meq_trans with (munion x (munion (munion y z) t)).\n    apply meq_right; apply meq_left; trivial.\n    apply multiset_twist1.\n  Qed.\n\n  Lemma treesort_twist2 :\n    forall x y z t u:multiset,\n      meq u (munion y z) ->\n      meq (munion x (munion u t)) (munion (munion y (munion x z)) t).\n  Proof.\n    intros; apply meq_trans with (munion x (munion (munion y z) t)).\n    apply meq_right; apply meq_left; trivial.\n    apply multiset_twist2.\n  Qed.\n\n  (** SingletonBag *)\n\n  Lemma meq_singleton : forall a a',\n    eqA a a' -> meq (SingletonBag a) (SingletonBag a').\n  Proof.\n    intros; red; simpl; intro a0.\n    destruct (Aeq_dec a a0) as [Ha|Ha]; rewrite H in Ha;\n      decide (Aeq_dec a' a0) with Ha; reflexivity.\n  Qed.\n\n(*i theory of minter to do similarly\nRequire Min.\n(* multiset intersection *)\nDefinition minter := [m1,m2:multiset]\n    (Bag [a:A](min (multiplicity m1 a)(multiplicity m2 a))).\ni*)\n\nEnd multiset_defs.\n\nUnset Implicit Arguments.\n\nHint Unfold meq multiplicity: datatypes.\nHint Resolve munion_empty_right munion_comm munion_ass meq_left meq_right\n  munion_empty_left: datatypes.\nHint Immediate meq_sym: datatypes.\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/Sets/Multiset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672043084051, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.6606551230875995}}
{"text": "From Cat Require Import Imports Category.\nRequire Import ProofIrrelevance.\n\n\n(** Preorders *)\n\nClass PreOrder: Type :=\n{\n   pos    : Set;\n   pohrel : pos -> pos -> bool;\n   porefl : forall x: pos, pohrel x x = true;\n   potrans: forall x y z: pos, pohrel x y = true /\\ pohrel y z = true -> pohrel x z = true\n}.\n\nPrint Nat.leb.\n\nLemma natleb_refl: forall a: nat, Nat.leb a a = true.\nProof. intro a.\n       induction a.\n       - simpl. reflexivity.\n       - simpl. exact IHa.\nQed.\n\n\nLemma natleb_trans: forall x y z : nat, Nat.leb x y = true /\\ Nat.leb y z = true ->\n                                        Nat.leb x z = true.\nProof. intro x.\n       induction x.\n       - intros y z (Ha, Hb).\n         simpl. reflexivity.\n       - intros y z (Ha, Hb).\n         simpl.\n         simpl in Ha.\n         case_eq y.\n         + intro Hy.\n           rewrite Hy in Ha.\n           contradict Ha.\n           easy.\n         + intros k Hy.\n           rewrite Hy in Ha.\n           case_eq z.\n           ++ intros Hz.\n              rewrite Hy, Hz in Hb.\n              simpl in Hb.\n              contradict Hb.\n              easy.\n           ++ intros l Hz.\n              rewrite Hy, Hz in Hb.\n              simpl in Hb.\n              specialize (IHx k l (conj Ha Hb)).\n              exact IHx.\nQed.\n\nExample NatPreOrder: PreOrder.\nProof. unshelve econstructor.\n       - exact nat.\n       - exact Nat.leb.\n       - intro x.\n         rewrite natleb_refl.\n         reflexivity.\n       - intros x y z (Ha, Hb).\n         rewrite natleb_trans with (y := y).\n         + reflexivity.\n         + split.\n           ++ exact Ha.\n           ++ exact Hb.\nQed.\n\nClass PreOrderMap (P1 P2: PreOrder): Set :=\n{\n   posmap   : (@pos P1) -> (@pos P2);\n   pohrelmap: forall x x', (@pohrel P1) x x' = true -> (@pohrel P2) (posmap x) (posmap x') = true\n}.\n\nLemma PreOrderMapEq: forall (P1 P2: PreOrder) (F G: PreOrderMap P1 P2),\n  @posmap P1 P2 F = @posmap P1 P2 G -> F = G.\nProof. intros.\n       destruct P1 as (P1, le1, r1, t1).\n       destruct P2 as (P2, le2, r2, t2).\n       destruct F as (f, Hf).\n       destruct G as (g, Hg).\n       simpl in *. subst.\n       f_equal.\n       now destruct (proof_irrelevance _ Hf Hg).\nQed.\n\nDefinition IdPreOrderMap (P: PreOrder): PreOrderMap P P.\nProof. destruct P as (P, le, r, t).\n       unshelve econstructor.\n       - simpl. intro a. exact a.\n       - intros x y H. simpl in *.\n         exact H.\nDefined.\n\nDefinition PreOrderMapComp {P1 P2 P3: PreOrder} (F: PreOrderMap P1 P2) (G: PreOrderMap P2 P3): PreOrderMap P1 P3.\nProof. destruct P1 as (P1, le1, r1, t1).\n       destruct P2 as (P2, le2, r2, t2).\n       destruct P3 as (P3, le3, r3, t3).\n       destruct F as (f, fax).\n       simpl in *.\n       destruct G as (g, gax).\n       simpl in *.\n       unshelve econstructor; simpl.\n       - intro a. exact (g (f a)).\n       - simpl. intros x y H.\n         specialize (gax (f x) (f y)).\n         apply gax.\n         specialize (fax x y).\n         apply fax.\n         exact H.\nDefined.\n\nLemma PreOrderMapCompAssoc: forall (P1 P2 P3 P4: PreOrder) \n                                   (F: PreOrderMap P1 P2) \n                                   (G: PreOrderMap P2 P3) \n                                   (H: PreOrderMap P3 P4),\n                                   PreOrderMapComp (PreOrderMapComp F G) H = \n                                   PreOrderMapComp F (PreOrderMapComp G H).\nProof. intros P1 P2 P3 P4 F G H.\n       destruct P1 as (P1, le1, r1, t1).\n       destruct P2 as (P2, le2, r2, t2).\n       destruct P3 as (P3, le3, r3, t3).\n       destruct P4 as (P4, le4, r4, t4).\n       destruct F as (f, fax).\n       destruct G as (g, gax).\n       destruct H as (h, hax).\n       simpl in *.\n       apply PreOrderMapEq.\n       simpl.\n       reflexivity.\nQed.\n\nLemma PreOrderMapIdL: forall (P1 P2: PreOrder) (F: PreOrderMap P1 P2),\n                              PreOrderMapComp (IdPreOrderMap P1) F = F.\nProof. intros P1 P2 F.\n       destruct P1 as (P1, le1, r1, t1).\n       destruct P2 as (P2, le2, r2, t2).\n       destruct F as (f, fax).\n       simpl in *.\n       apply PreOrderMapEq.\n       simpl.\n       reflexivity.\nQed.\n\nLemma PreOrderMapIdR: forall (P1 P2: PreOrder) (F: PreOrderMap P1 P2),\n                              PreOrderMapComp F (IdPreOrderMap P2) = F.\nProof. intros P1 P2 F.\n       destruct P1 as (P1, le1, r1, t1).\n       destruct P2 as (P2, le2, r2, t2).\n       destruct F as (f, fax).\n       apply PreOrderMapEq.\n       simpl.\n       reflexivity.\nQed.\n\nDefinition PreOrderCat: Category.\nProof. unshelve econstructor.\n       - exact PreOrder.\n       - intros P1 P2. exact (PreOrderMap P2 P1).\n       - intro P. simpl. exact (IdPreOrderMap P).\n       - intros P1 P2 P3 G F. simpl in *.\n         exact (PreOrderMapComp F G).\n       - repeat intro. now subst.\n       - simpl. intros P1 P2 P3 P4 F G H.\n         apply PreOrderMapCompAssoc.\n       - simpl. intros P1 P2 F.\n         rewrite PreOrderMapIdR.\n         reflexivity.\n       - simpl. intros P1 P2 F.\n         rewrite PreOrderMapIdL.\n         reflexivity.\nDefined.\n\n(* Lemma PreOrderHRelEq: forall (P: PreOrder) (a b c d: @pos P),\n (@pohrel P b a = true) /\\ (@pohrel P c b = true) /\\ (@pohrel P d c = true) ->\n (@pohrel P b a && @pohrel P d b) = (@pohrel P c a && @pohrel P d c).\nProof. intros P a b c d (H1, (H2, H3)).\n       destruct P as (P, le, r, t).\n       cbn in *. rewrite H1, H3. simpl.\n       pose proof t as tt.\n       specialize (t c b a). rewrite t.\n       specialize (tt d c b). rewrite tt. easy.\n       easy. easy.\nQed.\n *)\n\nCheck @pohrel.\n\nDefinition PreOrderICMap (P: PreOrder) (x y: @pos P): Type :=\n  if (@pohrel P x y) then unit else Empty_set.\n\n(* Definition PreOrderICMap (P: PreOrder) (x y: @pos P): Type.\nProof. destruct P as (P, le, r, t).\n       simpl in *.\n       clear r t.\n       destruct (le x y).\n       - exact unit.\n       - exact Empty_set.\nDefined. *)\n\nLemma PreOrderICMapEq: forall (P: PreOrder) (x y: @pos P) (f g: PreOrderICMap P x y), f = g.\nProof. intros P x y.\n       destruct P as (P, le, r, t).\n       unfold PreOrderICMap.\n       simpl in *.\n       destruct (le x y).\n       - intros f g.\n         destruct f, g.\n         reflexivity.\n       - intros f g.\n         destruct f, g.\nQed.\n\nDefinition PreOrderICid (P: PreOrder) (x: @pos P): PreOrderICMap P x x.\nProof. destruct P as (P, le, r, t).\n       unfold PreOrderICMap.\n       simpl in *.\n       rewrite r.\n       exact tt.\nDefined.\n\nDefinition PreOrderICcomp (P: PreOrder) (x y z: @pos P) \n  (f: PreOrderICMap P z y) (g: PreOrderICMap P y x): PreOrderICMap P z x.\nProof. destruct P as (A, le, r, t).\n       unfold PreOrderICMap in *.\n       simpl in *.\n       specialize (t z y x).\n       case_eq (le z y).\n       - intro le1.\n         case_eq (le y x).\n         + intro le2.\n           rewrite le1, le2 in t.\n           rewrite t.\n           ++ exact tt.\n           ++ split.\n              * reflexivity.\n              * reflexivity.\n         + intro le2.\n           rewrite le2 in g.\n           destruct g.\n       - intro le1.\n         rewrite le1 in f.\n         destruct f.\nDefined.\n\nDefinition PreOrderDetCat (P: PreOrder): Category.\nProof. unshelve econstructor.\n       - exact (@pos P).\n       - intros x y. exact (PreOrderICMap P y x).\n       - intro x. exact (PreOrderICid P x).\n       - simpl. intros z y x g f. exact (PreOrderICcomp P x y z f g).\n       - repeat intro. now subst.\n       - simpl. intros x y z w f g h. apply PreOrderICMapEq.\n       - simpl. intros x y f. apply PreOrderICMapEq.\n       - simpl. intros x y f. apply PreOrderICMapEq.\nDefined.\n\n\nLemma MonoPDC: forall (P: PreOrder) (C := PreOrderDetCat P) (X Y Z: @obj C) (h: arrow Z Y),\n  forall (f g: arrow Y X), h o f = h o g -> f = g.\nProof. intros (P, leq, ax1, ax2) C X Y Z h f g e.\n       apply PreOrderICMapEq.\nQed.\n\nLemma EpiPDC: forall (P: PreOrder) (C := PreOrderDetCat P) (X Y Z: @obj C) (h: arrow Y X),\n  forall (f g: arrow Z Y), f o h = g o h -> f = g.\nProof. intros (P, leq, ax1, ax2) C X Y Z h f g e.\n       apply PreOrderICMapEq.\nQed.\n\n\n\n\n\n", "meta": {"author": "ekiciburak", "repo": "CatTheo", "sha": "f80ac2700ca09eaff5c1bd6addcbf9ca2fdbb2fd", "save_path": "github-repos/coq/ekiciburak-CatTheo", "path": "github-repos/coq/ekiciburak-CatTheo/CatTheo-f80ac2700ca09eaff5c1bd6addcbf9ca2fdbb2fd/Preorder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.6606551216660843}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Correctness of instruction selection for integer division *)\n\nRequire Import Zquot Coqlib.\nRequire Import AST Integers Floats Values Memory Globalenvs Events.\nRequire Import Cminor Op CminorSel.\nRequire Import SelectOp SelectOpproof SplitLong SplitLongproof SelectLong SelectLongproof SelectDiv.\n\nLocal Open Scope cminorsel_scope.\n\n(** * Main approximation theorems *)\n\nSection Z_DIV_MUL.\n\nVariable N: Z.      (**r number of relevant bits *)\nHypothesis N_pos: N >= 0.\nVariable d: Z.      (**r divisor *)\nHypothesis d_pos: d > 0.\n\n(** This is theorem 4.2 from Granlund and Montgomery, PLDI 1994. *)\n\nLemma Zdiv_mul_pos:\n  forall m l,\n  l >= 0 ->\n  two_p (N+l) <= m * d <= two_p (N+l) + two_p l ->\n  forall n,\n  0 <= n < two_p N ->\n  Z.div n d = Z.div (m * n) (two_p (N + l)).\nProof.\n  intros m l l_pos [LO HI] n RANGE.\n  exploit (Z_div_mod_eq n d). auto.\n  set (q := n / d).\n  set (r := n mod d).\n  intro EUCL.\n  assert (0 <= r <= d - 1).\n    unfold r. generalize (Z_mod_lt n d d_pos). omega.\n  assert (0 <= m).\n    apply Zmult_le_0_reg_r with d. auto.\n    exploit (two_p_gt_ZERO (N + l)). omega. omega.\n  set (k := m * d - two_p (N + l)).\n  assert (0 <= k <= two_p l).\n    unfold k; omega.\n  assert ((m * n - two_p (N + l) * q) * d = k * n + two_p (N + l) * r).\n    unfold k. rewrite EUCL. ring.\n  assert (0 <= k * n).\n    apply Z.mul_nonneg_nonneg; omega.\n  assert (k * n <= two_p (N + l) - two_p l).\n    apply Z.le_trans with (two_p l * n).\n    apply Zmult_le_compat_r. omega. omega.\n    replace (N + l) with (l + N) by omega.\n    rewrite two_p_is_exp.\n    replace (two_p l * two_p N - two_p l)\n       with (two_p l * (two_p N - 1))\n         by ring.\n    apply Zmult_le_compat_l. omega. exploit (two_p_gt_ZERO l). omega. omega.\n    omega. omega.\n  assert (0 <= two_p (N + l) * r).\n    apply Z.mul_nonneg_nonneg.\n    exploit (two_p_gt_ZERO (N + l)). omega. omega.\n    omega.\n  assert (two_p (N + l) * r <= two_p (N + l) * d - two_p (N + l)).\n    replace (two_p (N + l) * d - two_p (N + l))\n       with (two_p (N + l) * (d - 1)) by ring.\n    apply Zmult_le_compat_l.\n    omega.\n    exploit (two_p_gt_ZERO (N + l)). omega. omega.\n  assert (0 <= m * n - two_p (N + l) * q).\n    apply Zmult_le_reg_r with d. auto.\n    replace (0 * d) with 0 by ring.  rewrite H2. omega.\n  assert (m * n - two_p (N + l) * q < two_p (N + l)).\n    apply Zmult_lt_reg_r with d. omega.\n    rewrite H2.\n    apply Z.le_lt_trans with (two_p (N + l) * d - two_p l).\n    omega.\n    exploit (two_p_gt_ZERO l). omega. omega.\n  symmetry. apply Zdiv_unique with (m * n - two_p (N + l) * q).\n  ring. omega.\nQed.\n\nLemma Zdiv_unique_2:\n  forall x y q, y > 0 -> 0 < y * q - x <= y -> Z.div x y = q - 1.\nProof.\n  intros. apply Zdiv_unique with (x - (q - 1) * y). ring.\n  replace ((q - 1) * y) with (y * q - y) by ring. omega.\nQed.\n\nLemma Zdiv_mul_opp:\n  forall m l,\n  l >= 0 ->\n  two_p (N+l) < m * d <= two_p (N+l) + two_p l ->\n  forall n,\n  0 < n <= two_p N ->\n  Z.div n d = - Z.div (m * (-n)) (two_p (N + l)) - 1.\nProof.\n  intros m l l_pos [LO HI] n RANGE.\n  replace (m * (-n)) with (- (m * n)) by ring.\n  exploit (Z_div_mod_eq n d). auto.\n  set (q := n / d).\n  set (r := n mod d).\n  intro EUCL.\n  assert (0 <= r <= d - 1).\n    unfold r. generalize (Z_mod_lt n d d_pos). omega.\n  assert (0 <= m).\n    apply Zmult_le_0_reg_r with d. auto.\n    exploit (two_p_gt_ZERO (N + l)). omega. omega.\n  cut (Z.div (- (m * n)) (two_p (N + l)) = -q - 1).\n    omega.\n  apply Zdiv_unique_2.\n  apply two_p_gt_ZERO. omega.\n  replace (two_p (N + l) * - q - - (m * n))\n     with (m * n - two_p (N + l) * q)\n       by ring.\n  set (k := m * d - two_p (N + l)).\n  assert (0 < k <= two_p l).\n    unfold k; omega.\n  assert ((m * n - two_p (N + l) * q) * d = k * n + two_p (N + l) * r).\n    unfold k. rewrite EUCL. ring.\n  split.\n  apply Zmult_lt_reg_r with d. omega.\n  replace (0 * d) with 0 by omega.\n  rewrite H2.\n  assert (0 < k * n). apply Z.mul_pos_pos; omega.\n  assert (0 <= two_p (N + l) * r).\n    apply Z.mul_nonneg_nonneg. exploit (two_p_gt_ZERO (N + l)); omega. omega.\n  omega.\n  apply Zmult_le_reg_r with d. omega.\n  rewrite H2.\n  assert (k * n <= two_p (N + l)).\n    rewrite Z.add_comm. rewrite two_p_is_exp; try omega.\n    apply Z.le_trans with (two_p l * n). apply Zmult_le_compat_r. omega. omega.\n    apply Zmult_le_compat_l. omega. exploit (two_p_gt_ZERO l). omega. omega.\n  assert (two_p (N + l) * r <= two_p (N + l) * d - two_p (N + l)).\n    replace (two_p (N + l) * d - two_p (N + l))\n       with (two_p (N + l) * (d - 1))\n         by ring.\n    apply Zmult_le_compat_l. omega. exploit (two_p_gt_ZERO (N + l)). omega. omega.\n  omega.\nQed.\n\n(** This is theorem 5.1 from Granlund and Montgomery, PLDI 1994. *)\n\nLemma Zquot_mul:\n  forall m l,\n  l >= 0 ->\n  two_p (N+l) < m * d <= two_p (N+l) + two_p l ->\n  forall n,\n  - two_p N <= n < two_p N ->\n  Z.quot n d = Z.div (m * n) (two_p (N + l)) + (if zlt n 0 then 1 else 0).\nProof.\n  intros. destruct (zlt n 0).\n  exploit (Zdiv_mul_opp m l H H0 (-n)). omega.\n  replace (- - n) with n by ring.\n  replace (Z.quot n d) with (- Z.quot (-n) d).\n  rewrite Zquot_Zdiv_pos by omega. omega.\n  rewrite Z.quot_opp_l by omega. ring.\n  rewrite Z.add_0_r. rewrite Zquot_Zdiv_pos by omega.\n  apply Zdiv_mul_pos; omega.\nQed.\n\nEnd Z_DIV_MUL.\n\n(** * Correctness of the division parameters *)\n\nLemma divs_mul_params_sound:\n  forall d m p,\n  divs_mul_params d = Some(p, m) ->\n  0 <= m < Int.modulus /\\ 0 <= p < 32 /\\\n  forall n,\n  Int.min_signed <= n <= Int.max_signed ->\n  Z.quot n d = Z.div (m * n) (two_p (32 + p)) + (if zlt n 0 then 1 else 0).\nProof with (try discriminate).\n  unfold divs_mul_params; intros d m' p'.\n  destruct (find_div_mul_params Int.wordsize\n               (Int.half_modulus - Int.half_modulus mod d - 1) d 32)\n  as [[p m] | ]...\n  generalize (p - 32). intro p1.\n  destruct (zlt 0 d)...\n  destruct (zlt (two_p (32 + p1)) (m * d))...\n  destruct (zle (m * d) (two_p (32 + p1) + two_p (p1 + 1)))...\n  destruct (zle 0 m)...\n  destruct (zlt m Int.modulus)...\n  destruct (zle 0 p1)...\n  destruct (zlt p1 32)...\n  intros EQ; inv EQ.\n  split. auto. split. auto. intros.\n  replace (32 + p') with (31 + (p' + 1)) by omega.\n  apply Zquot_mul; try omega.\n  replace (31 + (p' + 1)) with (32 + p') by omega. omega.\n  change (Int.min_signed <= n < Int.half_modulus).\n  unfold Int.max_signed in H. omega.\nQed.\n\nLemma divu_mul_params_sound:\n  forall d m p,\n  divu_mul_params d = Some(p, m) ->\n  0 <= m < Int.modulus /\\ 0 <= p < 32 /\\\n  forall n,\n  0 <= n < Int.modulus ->\n  Z.div n d = Z.div (m * n) (two_p (32 + p)).\nProof with (try discriminate).\n  unfold divu_mul_params; intros d m' p'.\n  destruct (find_div_mul_params Int.wordsize\n               (Int.modulus - Int.modulus mod d - 1) d 32)\n  as [[p m] | ]...\n  generalize (p - 32); intro p1.\n  destruct (zlt 0 d)...\n  destruct (zle (two_p (32 + p1)) (m * d))...\n  destruct (zle (m * d) (two_p (32 + p1) + two_p p1))...\n  destruct (zle 0 m)...\n  destruct (zlt m Int.modulus)...\n  destruct (zle 0 p1)...\n  destruct (zlt p1 32)...\n  intros EQ; inv EQ.\n  split. auto. split. auto. intros.\n  apply Zdiv_mul_pos; try omega. assumption.\nQed.\n\nLemma divs_mul_shift_gen:\n  forall x y m p,\n  divs_mul_params (Int.signed y) = Some(p, m) ->\n  0 <= m < Int.modulus /\\ 0 <= p < 32 /\\\n  Int.divs x y = Int.add (Int.shr (Int.repr ((Int.signed x * m) / Int.modulus)) (Int.repr p))\n                         (Int.shru x (Int.repr 31)).\nProof.\n  intros. set (n := Int.signed x). set (d := Int.signed y) in *.\n  exploit divs_mul_params_sound; eauto. intros (A & B & C).\n  split. auto. split. auto.\n  unfold Int.divs. fold n; fold d. rewrite C by (apply Int.signed_range).\n  rewrite two_p_is_exp by omega. rewrite <- Zdiv_Zdiv.\n  rewrite Int.shru_lt_zero. unfold Int.add. apply Int.eqm_samerepr. apply Int.eqm_add.\n  rewrite Int.shr_div_two_p. apply Int.eqm_unsigned_repr_r. apply Int.eqm_refl2.\n  rewrite Int.unsigned_repr. f_equal.\n  rewrite Int.signed_repr. rewrite Int.modulus_power. f_equal. ring.\n  cut (Int.min_signed <= n * m / Int.modulus < Int.half_modulus).\n  unfold Int.max_signed; omega.\n  apply Zdiv_interval_1. generalize Int.min_signed_neg; omega. apply Int.half_modulus_pos.\n  apply Int.modulus_pos.\n  split. apply Z.le_trans with (Int.min_signed * m). apply Zmult_le_compat_l_neg. omega. generalize Int.min_signed_neg; omega.\n  apply Zmult_le_compat_r. unfold n; generalize (Int.signed_range x); tauto. tauto.\n  apply Z.le_lt_trans with (Int.half_modulus * m).\n  apply Zmult_le_compat_r. generalize (Int.signed_range x); unfold n, Int.max_signed; omega. tauto.\n  apply Zmult_lt_compat_l. generalize Int.half_modulus_pos; omega. tauto.\n  assert (32 < Int.max_unsigned) by (compute; auto). omega.\n  unfold Int.lt; fold n. rewrite Int.signed_zero. destruct (zlt n 0); apply Int.eqm_unsigned_repr.\n  apply two_p_gt_ZERO. omega.\n  apply two_p_gt_ZERO. omega.\nQed.\n\nTheorem divs_mul_shift_1:\n  forall x y m p,\n  divs_mul_params (Int.signed y) = Some(p, m) ->\n  m < Int.half_modulus ->\n  0 <= p < 32 /\\\n  Int.divs x y = Int.add (Int.shr (Int.mulhs x (Int.repr m)) (Int.repr p))\n                         (Int.shru x (Int.repr 31)).\nProof.\n  intros. exploit divs_mul_shift_gen; eauto. instantiate (1 := x).\n  intros (A & B & C). split. auto. rewrite C.\n  unfold Int.mulhs. rewrite Int.signed_repr. auto.\n  generalize Int.min_signed_neg; unfold Int.max_signed; omega.\nQed.\n\nTheorem divs_mul_shift_2:\n  forall x y m p,\n  divs_mul_params (Int.signed y) = Some(p, m) ->\n  m >= Int.half_modulus ->\n  0 <= p < 32 /\\\n  Int.divs x y = Int.add (Int.shr (Int.add (Int.mulhs x (Int.repr m)) x) (Int.repr p))\n                         (Int.shru x (Int.repr 31)).\nProof.\n  intros. exploit divs_mul_shift_gen; eauto. instantiate (1 := x).\n  intros (A & B & C). split. auto. rewrite C. f_equal. f_equal.\n  rewrite Int.add_signed. unfold Int.mulhs. set (n := Int.signed x).\n  transitivity (Int.repr (n * (m - Int.modulus) / Int.modulus + n)).\n  f_equal.\n  replace (n * (m - Int.modulus)) with (n * m +  (-n) * Int.modulus) by ring.\n  rewrite Z_div_plus. ring. apply Int.modulus_pos.\n  apply Int.eqm_samerepr. apply Int.eqm_add; auto with ints.\n  apply Int.eqm_sym. eapply Int.eqm_trans. apply Int.eqm_signed_unsigned.\n  apply Int.eqm_unsigned_repr_l. apply Int.eqm_refl2. f_equal. f_equal.\n  rewrite Int.signed_repr_eq. rewrite Zmod_small by assumption.\n  apply zlt_false. omega.\nQed.\n\nTheorem divu_mul_shift:\n  forall x y m p,\n  divu_mul_params (Int.unsigned y) = Some(p, m) ->\n  0 <= p < 32 /\\\n  Int.divu x y = Int.shru (Int.mulhu x (Int.repr m)) (Int.repr p).\nProof.\n  intros. exploit divu_mul_params_sound; eauto. intros (A & B & C).\n  split. auto.\n  rewrite Int.shru_div_two_p. rewrite Int.unsigned_repr.\n  unfold Int.divu, Int.mulhu. f_equal. rewrite C by apply Int.unsigned_range.\n  rewrite two_p_is_exp by omega. rewrite <- Zdiv_Zdiv by (apply two_p_gt_ZERO; omega).\n  f_equal. rewrite (Int.unsigned_repr m).\n  rewrite Int.unsigned_repr. f_equal. ring.\n  cut (0 <= Int.unsigned x * m / Int.modulus < Int.modulus).\n  unfold Int.max_unsigned; omega.\n  apply Zdiv_interval_1. omega. compute; auto. compute; auto.\n  split. simpl. apply Z.mul_nonneg_nonneg. generalize (Int.unsigned_range x); omega. omega.\n  apply Z.le_lt_trans with (Int.modulus * m).\n  apply Zmult_le_compat_r. generalize (Int.unsigned_range x); omega. omega.\n  apply Zmult_lt_compat_l. compute; auto. omega.\n  unfold Int.max_unsigned; omega.\n  assert (32 < Int.max_unsigned) by (compute; auto). omega.\nQed.\n\n(** Same, for 64-bit integers *)\n\nLemma divls_mul_params_sound:\n  forall d m p,\n  divls_mul_params d = Some(p, m) ->\n  0 <= m < Int64.modulus /\\ 0 <= p < 64 /\\\n  forall n,\n  Int64.min_signed <= n <= Int64.max_signed ->\n  Z.quot n d = Z.div (m * n) (two_p (64 + p)) + (if zlt n 0 then 1 else 0).\nProof with (try discriminate).\n  unfold divls_mul_params; intros d m' p'.\n  destruct (find_div_mul_params Int64.wordsize\n               (Int64.half_modulus - Int64.half_modulus mod d - 1) d 64)\n  as [[p m] | ]...\n  generalize (p - 64). intro p1.\n  destruct (zlt 0 d)...\n  destruct (zlt (two_p (64 + p1)) (m * d))...\n  destruct (zle (m * d) (two_p (64 + p1) + two_p (p1 + 1)))...\n  destruct (zle 0 m)...\n  destruct (zlt m Int64.modulus)...\n  destruct (zle 0 p1)...\n  destruct (zlt p1 64)...\n  intros EQ; inv EQ.\n  split. auto. split. auto. intros.\n  replace (64 + p') with (63 + (p' + 1)) by omega.\n  apply Zquot_mul; try omega.\n  replace (63 + (p' + 1)) with (64 + p') by omega. omega.\n  change (Int64.min_signed <= n < Int64.half_modulus).\n  unfold Int64.max_signed in H. omega.\nQed.\n\nLemma divlu_mul_params_sound:\n  forall d m p,\n  divlu_mul_params d = Some(p, m) ->\n  0 <= m < Int64.modulus /\\ 0 <= p < 64 /\\\n  forall n,\n  0 <= n < Int64.modulus ->\n  Z.div n d = Z.div (m * n) (two_p (64 + p)).\nProof with (try discriminate).\n  unfold divlu_mul_params; intros d m' p'.\n  destruct (find_div_mul_params Int64.wordsize\n               (Int64.modulus - Int64.modulus mod d - 1) d 64)\n  as [[p m] | ]...\n  generalize (p - 64); intro p1.\n  destruct (zlt 0 d)...\n  destruct (zle (two_p (64 + p1)) (m * d))...\n  destruct (zle (m * d) (two_p (64 + p1) + two_p p1))...\n  destruct (zle 0 m)...\n  destruct (zlt m Int64.modulus)...\n  destruct (zle 0 p1)...\n  destruct (zlt p1 64)...\n  intros EQ; inv EQ.\n  split. auto. split. auto. intros.\n  apply Zdiv_mul_pos; try omega. assumption.\nQed.\n\nRemark int64_shr'_div_two_p:\n  forall x y, Int64.shr' x y = Int64.repr (Int64.signed x / two_p (Int.unsigned y)).\nProof.\n  intros; unfold Int64.shr'. rewrite Int64.Zshiftr_div_two_p; auto. generalize (Int.unsigned_range y); omega.\nQed.\n\nLemma divls_mul_shift_gen:\n  forall x y m p,\n  divls_mul_params (Int64.signed y) = Some(p, m) ->\n  0 <= m < Int64.modulus /\\ 0 <= p < 64 /\\\n  Int64.divs x y = Int64.add (Int64.shr' (Int64.repr ((Int64.signed x * m) / Int64.modulus)) (Int.repr p))\n                             (Int64.shru x (Int64.repr 63)).\nProof.\n  intros. set (n := Int64.signed x). set (d := Int64.signed y) in *.\n  exploit divls_mul_params_sound; eauto. intros (A & B & C).\n  split. auto. split. auto.\n  unfold Int64.divs. fold n; fold d. rewrite C by (apply Int64.signed_range).\n  rewrite two_p_is_exp by omega. rewrite <- Zdiv_Zdiv.\n  rewrite Int64.shru_lt_zero. unfold Int64.add. apply Int64.eqm_samerepr. apply Int64.eqm_add.\n  rewrite int64_shr'_div_two_p. apply Int64.eqm_unsigned_repr_r. apply Int64.eqm_refl2.\n  rewrite Int.unsigned_repr. f_equal.\n  rewrite Int64.signed_repr. rewrite Int64.modulus_power. f_equal. ring.\n  cut (Int64.min_signed <= n * m / Int64.modulus < Int64.half_modulus).\n  unfold Int64.max_signed; omega.\n  apply Zdiv_interval_1. generalize Int64.min_signed_neg; omega. apply Int64.half_modulus_pos.\n  apply Int64.modulus_pos.\n  split. apply Z.le_trans with (Int64.min_signed * m). apply Zmult_le_compat_l_neg. omega. generalize Int64.min_signed_neg; omega.\n  apply Zmult_le_compat_r. unfold n; generalize (Int64.signed_range x); tauto. tauto.\n  apply Z.le_lt_trans with (Int64.half_modulus * m).\n  apply Zmult_le_compat_r. generalize (Int64.signed_range x); unfold n, Int64.max_signed; omega. tauto.\n  apply Zmult_lt_compat_l. generalize Int64.half_modulus_pos; omega. tauto.\n  assert (64 < Int.max_unsigned) by (compute; auto). omega.\n  unfold Int64.lt; fold n. rewrite Int64.signed_zero. destruct (zlt n 0); apply Int64.eqm_unsigned_repr.\n  apply two_p_gt_ZERO. omega.\n  apply two_p_gt_ZERO. omega.\nQed.\n\nTheorem divls_mul_shift_1:\n  forall x y m p,\n  divls_mul_params (Int64.signed y) = Some(p, m) ->\n  m < Int64.half_modulus ->\n  0 <= p < 64 /\\\n  Int64.divs x y = Int64.add (Int64.shr' (Int64.mulhs x (Int64.repr m)) (Int.repr p))\n                             (Int64.shru' x (Int.repr 63)).\nProof.\n  intros. exploit divls_mul_shift_gen; eauto. instantiate (1 := x).\n  intros (A & B & C). split. auto. rewrite C.\n  unfold Int64.mulhs. rewrite Int64.signed_repr. auto.\n  generalize Int64.min_signed_neg; unfold Int64.max_signed; omega.\nQed.\n\nTheorem divls_mul_shift_2:\n  forall x y m p,\n  divls_mul_params (Int64.signed y) = Some(p, m) ->\n  m >= Int64.half_modulus ->\n  0 <= p < 64 /\\\n  Int64.divs x y = Int64.add (Int64.shr' (Int64.add (Int64.mulhs x (Int64.repr m)) x) (Int.repr p))\n                             (Int64.shru' x (Int.repr 63)).\nProof.\n  intros. exploit divls_mul_shift_gen; eauto. instantiate (1 := x).\n  intros (A & B & C). split. auto. rewrite C. f_equal. f_equal.\n  rewrite Int64.add_signed. unfold Int64.mulhs. set (n := Int64.signed x).\n  transitivity (Int64.repr (n * (m - Int64.modulus) / Int64.modulus + n)).\n  f_equal.\n  replace (n * (m - Int64.modulus)) with (n * m +  (-n) * Int64.modulus) by ring.\n  rewrite Z_div_plus. ring. apply Int64.modulus_pos.\n  apply Int64.eqm_samerepr. apply Int64.eqm_add; auto with ints.\n  apply Int64.eqm_sym. eapply Int64.eqm_trans. apply Int64.eqm_signed_unsigned.\n  apply Int64.eqm_unsigned_repr_l. apply Int64.eqm_refl2. f_equal. f_equal.\n  rewrite Int64.signed_repr_eq. rewrite Zmod_small by assumption.\n  apply zlt_false. omega.\nQed.\n\nRemark int64_shru'_div_two_p:\n  forall x y, Int64.shru' x y = Int64.repr (Int64.unsigned x / two_p (Int.unsigned y)).\nProof.\n  intros; unfold Int64.shru'. rewrite Int64.Zshiftr_div_two_p; auto. generalize (Int.unsigned_range y); omega.\nQed.\n\nTheorem divlu_mul_shift:\n  forall x y m p,\n  divlu_mul_params (Int64.unsigned y) = Some(p, m) ->\n  0 <= p < 64 /\\\n  Int64.divu x y = Int64.shru' (Int64.mulhu x (Int64.repr m)) (Int.repr p).\nProof.\n  intros. exploit divlu_mul_params_sound; eauto. intros (A & B & C).\n  split. auto.\n  rewrite int64_shru'_div_two_p. rewrite Int.unsigned_repr.\n  unfold Int64.divu, Int64.mulhu. f_equal. rewrite C by apply Int64.unsigned_range.\n  rewrite two_p_is_exp by omega. rewrite <- Zdiv_Zdiv by (apply two_p_gt_ZERO; omega).\n  f_equal. rewrite (Int64.unsigned_repr m).\n  rewrite Int64.unsigned_repr. f_equal. ring.\n  cut (0 <= Int64.unsigned x * m / Int64.modulus < Int64.modulus).\n  unfold Int64.max_unsigned; omega.\n  apply Zdiv_interval_1. omega. compute; auto. compute; auto.\n  split. simpl. apply Z.mul_nonneg_nonneg. generalize (Int64.unsigned_range x); omega. omega.\n  apply Z.le_lt_trans with (Int64.modulus * m).\n  apply Zmult_le_compat_r. generalize (Int64.unsigned_range x); omega. omega.\n  apply Zmult_lt_compat_l. compute; auto. omega.\n  unfold Int64.max_unsigned; omega.\n  assert (64 < Int.max_unsigned) by (compute; auto). omega.\nQed.\n\n(** * Correctness of the smart constructors for division and modulus *)\n\nSection CMCONSTRS.\n\nVariable prog: program.\nVariable hf: helper_functions.\nHypothesis HELPERS: helper_functions_declared prog hf.\nLet ge := Genv.globalenv prog.\nVariable sp: val.\nVariable e: env.\nVariable m: mem.\n\nLemma is_intconst_sound:\n  forall v a n le,\n  is_intconst a = Some n -> eval_expr ge sp e m le a v -> v = Vint n.\nProof with (try discriminate).\n  intros. unfold is_intconst in *.\n  destruct a... destruct o... inv H. inv H0. destruct vl; inv H5. auto.\nQed.\n\nLemma eval_divu_mul:\n  forall le x y p M,\n  divu_mul_params (Int.unsigned y) = Some(p, M) ->\n  nth_error le O = Some (Vint x) ->\n  eval_expr ge sp e m le (divu_mul p M) (Vint (Int.divu x y)).\nProof.\n  intros. unfold divu_mul. exploit (divu_mul_shift x); eauto. intros [A B].\n  assert (C: eval_expr ge sp e m le (Eletvar 0) (Vint x)) by (apply eval_Eletvar; eauto).\n  assert (D: eval_expr ge sp e m le (Eop (Ointconst (Int.repr M)) Enil) (Vint (Int.repr M))) by EvalOp.\n  exploit eval_mulhu. eexact C. eexact D. intros (v & E & F). simpl in F. inv F. \n  exploit eval_shruimm. eexact E. instantiate (1 := Int.repr p).\n  intros [v [P Q]]. simpl in Q.\n  replace (Int.ltu (Int.repr p) Int.iwordsize) with true in Q.\n  inv Q. rewrite B. auto.\n  unfold Int.ltu. rewrite Int.unsigned_repr. rewrite zlt_true; auto. tauto.\n  assert (32 < Int.max_unsigned) by (compute; auto). omega.\nQed.\n\nTheorem eval_divuimm:\n  forall le e1 x n2 z,\n  eval_expr ge sp e m le e1 x ->\n  Val.divu x (Vint n2) = Some z ->\n  exists v, eval_expr ge sp e m le (divuimm e1 n2) v /\\ Val.lessdef z v.\nProof.\n  unfold divuimm; intros. generalize H0; intros DIV.\n  destruct x; simpl in DIV; try discriminate.\n  destruct (Int.eq n2 Int.zero) eqn:Z2; inv DIV.\n  destruct (Int.is_power2 n2) as [l | ] eqn:P2.\n- erewrite Int.divu_pow2 by eauto.\n  replace (Vint (Int.shru i l)) with (Val.shru (Vint i) (Vint l)).\n  apply eval_shruimm; auto.\n  simpl. erewrite Int.is_power2_range; eauto.\n- destruct (Compopts.optim_for_size tt).\n  + eapply eval_divu_base; eauto. EvalOp.\n  + destruct (divu_mul_params (Int.unsigned n2)) as [[p M] | ] eqn:PARAMS.\n    * exists (Vint (Int.divu i n2)); split; auto.\n      econstructor; eauto. eapply eval_divu_mul; eauto.\n    * eapply eval_divu_base; eauto. EvalOp.\nQed.\n\nTheorem eval_divu:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.divu x y = Some z ->\n  exists v, eval_expr ge sp e m le (divu a b) v /\\ Val.lessdef z v.\nProof.\n  unfold divu; intros.\n  destruct (is_intconst b) as [n2|] eqn:B.\n- exploit is_intconst_sound; eauto. intros EB; clear B.\n  destruct (is_intconst a) as [n1|] eqn:A.\n+ exploit is_intconst_sound; eauto. intros EA; clear A.\n  destruct (Int.eq n2 Int.zero) eqn:Z. eapply eval_divu_base; eauto. \n  subst. simpl in H1. rewrite Z in H1; inv H1.\n  TrivialExists.\n+ subst. eapply eval_divuimm; eauto.\n- eapply eval_divu_base; eauto.\nQed.\n\nLemma eval_mod_from_div:\n  forall le a n x y,\n  eval_expr ge sp e m le a (Vint y) ->\n  nth_error le O = Some (Vint x) ->\n  eval_expr ge sp e m le (mod_from_div a n) (Vint (Int.sub x (Int.mul y n))).\nProof.\n  unfold mod_from_div; intros.\n  exploit eval_mulimm; eauto. instantiate (1 := n). intros [v [A B]].\n  simpl in B. inv B. EvalOp.\nQed.\n\nTheorem eval_moduimm:\n  forall le e1 x n2 z,\n  eval_expr ge sp e m le e1 x ->\n  Val.modu x (Vint n2) = Some z ->\n  exists v, eval_expr ge sp e m le (moduimm e1 n2) v /\\ Val.lessdef z v.\nProof.\n  unfold moduimm; intros. generalize H0; intros MOD.\n  destruct x; simpl in MOD; try discriminate.\n  destruct (Int.eq n2 Int.zero) eqn:Z2; inv MOD.\n  destruct (Int.is_power2 n2) as [l | ] eqn:P2.\n- erewrite Int.modu_and by eauto.\n  change (Vint (Int.and i (Int.sub n2 Int.one)))\n    with (Val.and (Vint i) (Vint (Int.sub n2 Int.one))).\n  apply eval_andimm. auto.\n- destruct (Compopts.optim_for_size tt).\n  + eapply eval_modu_base; eauto. EvalOp.\n  + destruct (divu_mul_params (Int.unsigned n2)) as [[p M] | ] eqn:PARAMS.\n    * econstructor; split.\n      econstructor; eauto. eapply eval_mod_from_div.\n      eapply eval_divu_mul; eauto. simpl; eauto. simpl; eauto.\n      rewrite Int.modu_divu. auto.\n      red; intros; subst n2; discriminate.\n    * eapply eval_modu_base; eauto. EvalOp.\nQed.\n\nTheorem eval_modu:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.modu x y = Some z ->\n  exists v, eval_expr ge sp e m le (modu a b) v /\\ Val.lessdef z v.\nProof.\n  unfold modu; intros.\n  destruct (is_intconst b) as [n2|] eqn:B.\n- exploit is_intconst_sound; eauto. intros EB; clear B.\n  destruct (is_intconst a) as [n1|] eqn:A.\n+ exploit is_intconst_sound; eauto. intros EA; clear A.\n  destruct (Int.eq n2 Int.zero) eqn:Z. eapply eval_modu_base; eauto. \n  subst. simpl in H1. rewrite Z in H1; inv H1.\n  TrivialExists.\n+ subst. eapply eval_moduimm; eauto.\n- eapply eval_modu_base; eauto.\nQed.\n\nLemma eval_divs_mul:\n  forall le x y p M,\n  divs_mul_params (Int.signed y) = Some(p, M) ->\n  nth_error le O = Some (Vint x) ->\n  eval_expr ge sp e m le (divs_mul p M) (Vint (Int.divs x y)).\nProof.\n  intros. unfold divs_mul.\n  assert (C: eval_expr ge sp e m le (Eletvar 0) (Vint x)) by (apply eval_Eletvar; eauto).\n  assert (D: eval_expr ge sp e m le (Eop (Ointconst (Int.repr M)) Enil) (Vint (Int.repr M))) by EvalOp.\n  exploit eval_mulhs. eexact C. eexact D. intros (v & X & F). simpl in F; inv F.\n  exploit eval_shruimm. eexact C. instantiate (1 := Int.repr (Int.zwordsize - 1)).\n  intros [v1 [Y LD]]. simpl in LD.\n  change (Int.ltu (Int.repr 31) Int.iwordsize) with true in LD.\n  simpl in LD. inv LD.\n  assert (RANGE: 0 <= p < 32 -> Int.ltu (Int.repr p) Int.iwordsize = true).\n  { intros. unfold Int.ltu. rewrite Int.unsigned_repr. rewrite zlt_true by tauto. auto.\n    assert (32 < Int.max_unsigned) by (compute; auto). omega. }\n  destruct (zlt M Int.half_modulus).\n- exploit (divs_mul_shift_1 x); eauto. intros [A B].\n  exploit eval_shrimm. eexact X. instantiate (1 := Int.repr p). intros [v1 [Z LD]].\n  simpl in LD. rewrite RANGE in LD by auto. inv LD.\n  exploit eval_add. eexact Z. eexact Y. intros [v1 [W LD]].\n  simpl in LD. inv LD.\n  rewrite B. exact W.\n- exploit (divs_mul_shift_2 x); eauto. intros [A B].\n  exploit eval_add. eexact X. eexact C. intros [v1 [Z LD]].\n  simpl in LD. inv LD.\n  exploit eval_shrimm. eexact Z. instantiate (1 := Int.repr p). intros [v1 [U LD]].\n  simpl in LD. rewrite RANGE in LD by auto. inv LD.\n  exploit eval_add. eexact U. eexact Y. intros [v1 [W LD]].\n  simpl in LD. inv LD.\n  rewrite B. exact W.\nQed.\n\nTheorem eval_divsimm:\n  forall le e1 x n2 z,\n  eval_expr ge sp e m le e1 x ->\n  Val.divs x (Vint n2) = Some z ->\n  exists v, eval_expr ge sp e m le (divsimm e1 n2) v /\\ Val.lessdef z v.\nProof.\n  unfold divsimm; intros. generalize H0; intros DIV.\n  destruct x; simpl in DIV; try discriminate.\n  destruct (Int.eq n2 Int.zero\n            || Int.eq i (Int.repr Int.min_signed) && Int.eq n2 Int.mone) eqn:Z2; inv DIV.\n  destruct (Int.is_power2 n2) as [l | ] eqn:P2.\n- destruct (Int.ltu l (Int.repr 31)) eqn:LT31.\n  + eapply eval_shrximm; eauto. eapply Val.divs_pow2; eauto.\n  + eapply eval_divs_base; eauto. EvalOp.\n- destruct (Compopts.optim_for_size tt).\n  + eapply eval_divs_base; eauto. EvalOp.\n  + destruct (divs_mul_params (Int.signed n2)) as [[p M] | ] eqn:PARAMS.\n    * exists (Vint (Int.divs i n2)); split; auto.\n      econstructor; eauto. eapply eval_divs_mul; eauto.\n    * eapply eval_divs_base; eauto. EvalOp.\nQed.\n\nTheorem eval_divs:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.divs x y = Some z ->\n  exists v, eval_expr ge sp e m le (divs a b) v /\\ Val.lessdef z v.\nProof.\n  unfold divs; intros.\n  destruct (is_intconst b) as [n2|] eqn:B.\n- exploit is_intconst_sound; eauto. intros EB; clear B.\n  destruct (is_intconst a) as [n1|] eqn:A.\n+ exploit is_intconst_sound; eauto. intros EA; clear A.\n  destruct (Int.eq n2 Int.zero) eqn:Z. eapply eval_divs_base; eauto.\n  subst. simpl in H1. \n  destruct (Int.eq n2 Int.zero || Int.eq n1 (Int.repr Int.min_signed) && Int.eq n2 Int.mone); inv H1.\n  TrivialExists.\n+ subst. eapply eval_divsimm; eauto.\n- eapply eval_divs_base; eauto.\nQed.\n\nTheorem eval_modsimm:\n  forall le e1 x n2 z,\n  eval_expr ge sp e m le e1 x ->\n  Val.mods x (Vint n2) = Some z ->\n  exists v, eval_expr ge sp e m le (modsimm e1 n2) v /\\ Val.lessdef z v.\nProof.\n  unfold modsimm; intros.\n  exploit Val.mods_divs; eauto. intros [y [A B]].\n  generalize A; intros DIV.\n  destruct x; simpl in DIV; try discriminate.\n  destruct (Int.eq n2 Int.zero\n            || Int.eq i (Int.repr Int.min_signed) && Int.eq n2 Int.mone) eqn:Z2; inv DIV.\n  destruct (Int.is_power2 n2) as [l | ] eqn:P2.\n- destruct (Int.ltu l (Int.repr 31)) eqn:LT31.\n  + exploit (eval_shrximm ge sp e m (Vint i :: le) (Eletvar O)).\n    constructor. simpl; eauto. eapply Val.divs_pow2; eauto.\n    intros [v1 [X LD]]. inv LD.\n    econstructor; split. econstructor. eauto.\n    apply eval_mod_from_div. eexact X. simpl; eauto.\n    simpl. auto.\n  + eapply eval_mods_base; eauto. EvalOp.\n- destruct (Compopts.optim_for_size tt).\n  + eapply eval_mods_base; eauto. EvalOp.\n  + destruct (divs_mul_params (Int.signed n2)) as [[p M] | ] eqn:PARAMS.\n    * econstructor; split.\n      econstructor. eauto. apply eval_mod_from_div with (x := i); auto.\n      eapply eval_divs_mul with (x := i); eauto.\n      simpl. auto.\n    * eapply eval_mods_base; eauto. EvalOp.\nQed.\n\nTheorem eval_mods:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.mods x y = Some z ->\n  exists v, eval_expr ge sp e m le (mods a b) v /\\ Val.lessdef z v.\nProof.\n  unfold mods; intros.\n  destruct (is_intconst b) as [n2|] eqn:B.\n- exploit is_intconst_sound; eauto. intros EB; clear B.\n  destruct (is_intconst a) as [n1|] eqn:A.\n+ exploit is_intconst_sound; eauto. intros EA; clear A.\n  destruct (Int.eq n2 Int.zero) eqn:Z. eapply eval_mods_base; eauto.\n  subst. simpl in H1. \n  destruct (Int.eq n2 Int.zero || Int.eq n1 (Int.repr Int.min_signed) && Int.eq n2 Int.mone); inv H1.\n  TrivialExists.\n+ subst. eapply eval_modsimm; eauto.\n- eapply eval_mods_base; eauto.\nQed.\n\nLemma eval_modl_from_divl:\n  forall le a n x y,\n  eval_expr ge sp e m le a (Vlong y) ->\n  nth_error le O = Some (Vlong x) ->\n  eval_expr ge sp e m le (modl_from_divl a n) (Vlong (Int64.sub x (Int64.mul y n))).\nProof.\n  unfold modl_from_divl; intros.\n  exploit eval_mullimm; eauto. instantiate (1 := n). intros (v1 & A1 & B1).\n  assert (A0: eval_expr ge sp e m le (Eletvar O) (Vlong x)) by (constructor; auto).\n  exploit eval_subl ; auto ; try apply HELPERS. exact A0. exact A1.\n  intros (v2 & A2 & B2).\n  simpl in B1; inv B1. simpl in B2; inv B2. exact A2.\nQed.\n\nLemma eval_divlu_mull:\n  forall le x y p M,\n  divlu_mul_params (Int64.unsigned y) = Some(p, M) ->\n  nth_error le O = Some (Vlong x) ->\n  eval_expr ge sp e m le (divlu_mull p M) (Vlong (Int64.divu x y)).\nProof.\n  intros. unfold divlu_mull. exploit (divlu_mul_shift x); eauto. intros [A B].\n  assert (A0: eval_expr ge sp e m le (Eletvar O) (Vlong x)) by (constructor; auto).\n  exploit eval_mullhu. eauto. eexact A0. instantiate (1 := Int64.repr M). intros (v1 & A1 & B1).\n  exploit eval_shrluimm. eauto. eexact A1. instantiate (1 := Int.repr p). intros (v2 & A2 & B2).\n  simpl in B1; inv B1. simpl in B2. replace (Int.ltu (Int.repr p) Int64.iwordsize') with true in B2. inv B2.\n  rewrite B. assumption.\n  unfold Int.ltu. rewrite Int.unsigned_repr. rewrite zlt_true; auto. tauto.\n  assert (64 < Int.max_unsigned) by (compute; auto). omega.\nQed.\n\nTheorem eval_divlu:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.divlu x y = Some z ->\n  exists v, eval_expr ge sp e m le (divlu a b) v /\\ Val.lessdef z v.\nProof.\n  unfold divlu; intros.\n  destruct (is_longconst b) as [n2|] eqn:N2.\n- assert (y = Vlong n2) by (eapply is_longconst_sound; eauto). subst y.\n  destruct (is_longconst a) as [n1|] eqn:N1.\n+ assert (x = Vlong n1) by (eapply is_longconst_sound; eauto). subst x.\n  simpl in H1. destruct (Int64.eq n2 Int64.zero); inv H1.\n  econstructor; split. apply eval_longconst. constructor.\n+ destruct (Int64.is_power2' n2) as [l|] eqn:POW.\n* exploit Val.divlu_pow2; eauto. intros EQ; subst z. apply eval_shrluimm; auto.\n* destruct (Compopts.optim_for_size tt). eapply eval_divlu_base; eauto.\n  destruct (divlu_mul_params (Int64.unsigned n2)) as [[p M]|] eqn:PARAMS.\n** destruct x; simpl in H1; try discriminate.\n   destruct (Int64.eq n2 Int64.zero); inv H1.\n   econstructor; split; eauto. econstructor. eauto. eapply eval_divlu_mull; eauto.\n** eapply eval_divlu_base; eauto.\n- eapply eval_divlu_base; eauto.\nQed.\n\nTheorem eval_modlu:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.modlu x y = Some z ->\n  exists v, eval_expr ge sp e m le (modlu a b) v /\\ Val.lessdef z v.\nProof.\n  unfold modlu; intros.\n  destruct (is_longconst b) as [n2|] eqn:N2.\n- assert (y = Vlong n2) by (eapply is_longconst_sound; eauto). subst y.\n  destruct (is_longconst a) as [n1|] eqn:N1.\n+ assert (x = Vlong n1) by (eapply is_longconst_sound; eauto). subst x.\n  simpl in H1. destruct (Int64.eq n2 Int64.zero); inv H1.\n  econstructor; split. apply eval_longconst. constructor.\n+ destruct (Int64.is_power2 n2) as [l|] eqn:POW.\n* exploit Val.modlu_pow2; eauto. intros EQ; subst z. eapply eval_andl; eauto. apply eval_longconst.\n* destruct (Compopts.optim_for_size tt). eapply eval_modlu_base; eauto.\n  destruct (divlu_mul_params (Int64.unsigned n2)) as [[p M]|] eqn:PARAMS.\n** destruct x; simpl in H1; try discriminate.\n   destruct (Int64.eq n2 Int64.zero) eqn:Z; inv H1.\n   rewrite Int64.modu_divu.\n    econstructor; split; eauto. econstructor. eauto.\n    eapply eval_modl_from_divl; eauto.\n    eapply eval_divlu_mull; eauto.\n    red; intros; subst n2; discriminate Z.\n** eapply eval_modlu_base; eauto.\n- eapply eval_modlu_base; eauto.\nQed.\n\nLemma eval_divls_mull:\n  forall le x y p M,\n  divls_mul_params (Int64.signed y) = Some(p, M) ->\n  nth_error le O = Some (Vlong x) ->\n  eval_expr ge sp e m le (divls_mull p M) (Vlong (Int64.divs x y)).\nProof.\n  intros. unfold divls_mull.\n  assert (A0: eval_expr ge sp e m le (Eletvar O) (Vlong x)).\n  { constructor; auto. }\n  exploit eval_mullhs. eauto. eexact A0. instantiate (1 := Int64.repr M).  intros (v1 & A1 & B1).\n  exploit eval_addl; auto; try apply HELPERS. eexact A1. eexact A0. intros (v2 & A2 & B2).\n  exploit eval_shrluimm. eauto. eexact A0. instantiate (1 := Int.repr 63). intros (v3 & A3 & B3).\n  set (a4 := if zlt M Int64.half_modulus\n             then mullhs (Eletvar 0) (Int64.repr M)\n             else addl (mullhs (Eletvar 0) (Int64.repr M)) (Eletvar 0)).\n  set (v4 := if zlt M Int64.half_modulus then v1 else v2).\n  assert (A4: eval_expr ge sp e m le a4 v4).\n  { unfold a4, v4; destruct (zlt M Int64.half_modulus); auto. }\n  exploit eval_shrlimm. eauto. eexact A4. instantiate (1 := Int.repr p). intros (v5 & A5 & B5).\n  exploit eval_addl; auto; try apply HELPERS. eexact A5. eexact A3. intros (v6 & A6 & B6).\n  assert (RANGE: forall x, 0 <= x < 64 -> Int.ltu (Int.repr x) Int64.iwordsize' = true).\n  { intros. unfold Int.ltu. rewrite Int.unsigned_repr. rewrite zlt_true by tauto. auto.\n    assert (64 < Int.max_unsigned) by (compute; auto). omega. }\n  simpl in B1; inv B1.\n  simpl in B2; inv B2.\n  simpl in B3; rewrite RANGE in B3 by omega; inv B3.\n  destruct (zlt M Int64.half_modulus).\n- exploit (divls_mul_shift_1 x); eauto. intros [A B].\n  simpl in B5; rewrite RANGE in B5 by auto; inv B5.\n  simpl in B6; inv B6.\n  rewrite B; exact A6.\n- exploit (divls_mul_shift_2 x); eauto. intros [A B].\n  simpl in B5; rewrite RANGE in B5 by auto; inv B5.\n  simpl in B6; inv B6.\n  rewrite B; exact A6.\nQed.\n\nTheorem eval_divls:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.divls x y = Some z ->\n  exists v, eval_expr ge sp e m le (divls a b) v /\\ Val.lessdef z v.\nProof.\n  unfold divls; intros.\n  destruct (is_longconst b) as [n2|] eqn:N2.\n- assert (y = Vlong n2) by (eapply is_longconst_sound; eauto). subst y.\n  destruct (is_longconst a) as [n1|] eqn:N1.\n+ assert (x = Vlong n1) by (eapply is_longconst_sound; eauto). subst x.\n  simpl in H1.\n  destruct (Int64.eq n2 Int64.zero\n         || Int64.eq n1 (Int64.repr Int64.min_signed) && Int64.eq n2 Int64.mone); inv H1.\n  econstructor; split. apply eval_longconst. constructor.\n+ destruct (Int64.is_power2' n2) as [l|] eqn:POW.\n* destruct (Int.ltu l (Int.repr 63)) eqn:LT.\n** exploit Val.divls_pow2; eauto. intros EQ. eapply eval_shrxlimm; eauto.\n** eapply eval_divls_base; eauto.\n* destruct (Compopts.optim_for_size tt). eapply eval_divls_base; eauto.\n  destruct (divls_mul_params (Int64.signed n2)) as [[p M]|] eqn:PARAMS.\n** destruct x; simpl in H1; try discriminate.\n   destruct (Int64.eq n2 Int64.zero\n             || Int64.eq i (Int64.repr Int64.min_signed) && Int64.eq n2 Int64.mone); inv H1.\n   econstructor; split; eauto. econstructor. eauto.\n   eapply eval_divls_mull; eauto.\n** eapply eval_divls_base; eauto.\n- eapply eval_divls_base; eauto.\nQed.\n\nTheorem eval_modls:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.modls x y = Some z ->\n  exists v, eval_expr ge sp e m le (modls a b) v /\\ Val.lessdef z v.\nProof.\n  unfold modls; intros.\n  destruct (is_longconst b) as [n2|] eqn:N2.\n- assert (y = Vlong n2) by (eapply is_longconst_sound; eauto). subst y.\n  destruct (is_longconst a) as [n1|] eqn:N1.\n+ assert (x = Vlong n1) by (eapply is_longconst_sound; eauto). subst x.\n  simpl in H1.\n  destruct (Int64.eq n2 Int64.zero\n         || Int64.eq n1 (Int64.repr Int64.min_signed) && Int64.eq n2 Int64.mone); inv H1.\n  econstructor; split. apply eval_longconst. constructor.\n+ destruct (Int64.is_power2' n2) as [l|] eqn:POW.\n* destruct (Int.ltu l (Int.repr 63)) eqn:LT.\n**destruct x; simpl in H1; try discriminate.\n  destruct (Int64.eq n2 Int64.zero\n         || Int64.eq i (Int64.repr Int64.min_signed) && Int64.eq n2 Int64.mone) eqn:D; inv H1.\n  assert (Val.divls (Vlong i) (Vlong n2) = Some (Vlong (Int64.divs i n2))).\n  { simpl; rewrite D; auto. }\n  exploit Val.divls_pow2; eauto. intros EQ.\n  set (le' := Vlong i :: le).\n  assert (A: eval_expr ge sp e m le' (Eletvar O) (Vlong i)) by (constructor; auto).\n  exploit eval_shrxlimm; eauto. intros (v1 & A1 & B1). inv B1.\n  econstructor; split.\n  econstructor. eauto. eapply eval_modl_from_divl. eexact A1. reflexivity.\n  rewrite Int64.mods_divs. auto.\n**eapply eval_modls_base; eauto.\n* destruct (Compopts.optim_for_size tt). eapply eval_modls_base; eauto.\n  destruct (divls_mul_params (Int64.signed n2)) as [[p M]|] eqn:PARAMS.\n** destruct x; simpl in H1; try discriminate.\n   destruct (Int64.eq n2 Int64.zero\n             || Int64.eq i (Int64.repr Int64.min_signed) && Int64.eq n2 Int64.mone); inv H1.\n   econstructor; split; eauto. econstructor. eauto.\n   rewrite Int64.mods_divs.\n   eapply eval_modl_from_divl; auto.\n   eapply eval_divls_mull; eauto.\n** eapply eval_modls_base; eauto.\n- eapply eval_modls_base; eauto.\nQed.\n\n(** * Floating-point division *)\n\nTheorem eval_divf:\n  forall le a b x y,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  exists v, eval_expr ge sp e m le (divf a b) v /\\ Val.lessdef (Val.divf x y) v.\nProof.\n  intros until y. unfold divf. destruct (divf_match b); intros.\n- unfold divfimm. destruct (Float.exact_inverse n2) as [n2' | ] eqn:EINV.\n  + inv H0. inv H4. simpl in H6. inv H6. econstructor; split.\n    EvalOp. constructor. eauto. constructor. EvalOp. simpl; eauto. constructor.\n    simpl; eauto.\n    destruct x; simpl; auto. erewrite Float.div_mul_inverse; eauto.\n  + TrivialExists.\n- TrivialExists.\nQed.\n\nTheorem eval_divfs:\n  forall le a b x y,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  exists v, eval_expr ge sp e m le (divfs a b) v /\\ Val.lessdef (Val.divfs x y) v.\nProof.\n  intros until y. unfold divfs. destruct (divfs_match b); intros.\n- unfold divfsimm. destruct (Float32.exact_inverse n2) as [n2' | ] eqn:EINV.\n  + inv H0. inv H4. simpl in H6. inv H6. econstructor; split.\n    EvalOp. constructor. eauto. constructor. EvalOp. simpl; eauto. constructor.\n    simpl; eauto.\n    destruct x; simpl; auto. erewrite Float32.div_mul_inverse; eauto.\n  + TrivialExists.\n- TrivialExists.\nQed.\n\nEnd CMCONSTRS.\n", "meta": {"author": "frevson", "repo": "CompCert", "sha": "459f6414ee9ba5a0a8e138ab589eb3e1b88b5daa", "save_path": "github-repos/coq/frevson-CompCert", "path": "github-repos/coq/frevson-CompCert/CompCert-459f6414ee9ba5a0a8e138ab589eb3e1b88b5daa/backend/SelectDivproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6605845494970392}}
{"text": "Require Import Psatz.\nRequire Import Reals.\n\nRequire Export reMatrix.\n\n(* TODO: Add S and T gates, split this into multiple files including one for gates. *)\n\n(* Using our (complex, unbounded) matrices, their complex numbers *)\n\n(*******************************************)\n(** * Quantum basis states *)\n(*******************************************)\n\n(* Maybe change to IF statements? *)\nDefinition qubit0 : Vector 2 := \n  fun x y => match x, y with \n          | 0, 0 => C1\n          | 1, 0 => C0\n          | _, _ => C0\n          end.\nDefinition qubit1 : Vector 2 := \n  fun x y => match x, y with \n          | 0, 0 => C0\n          | 1, 0 => C1\n          | _, _ => C0\n          end.\n\n(* Ket notation: \\mid 0 \\rangle *)\nNotation \"∣0⟩\" := qubit0.\nNotation \"∣1⟩\" := qubit1.\nNotation \"⟨0∣\" := qubit0†.\nNotation \"⟨1∣\" := qubit1†.\nNotation \"∣0⟩⟨0∣\" := (∣0⟩×⟨0∣).\nNotation \"∣1⟩⟨1∣\" := (∣1⟩×⟨1∣).\nNotation \"∣1⟩⟨0∣\" := (∣1⟩×⟨0∣).\nNotation \"∣0⟩⟨1∣\" := (∣0⟩×⟨1∣).\n\nDefinition bra (x : nat) : Matrix 1 2 := if x =? 0 then ⟨0∣ else ⟨1∣.\nDefinition ket (x : nat) : Matrix 2 1 := if x =? 0 then ∣0⟩ else ∣1⟩.\n\n(* Note the 'mid' symbol for these *)\nNotation \"'∣' x '⟩'\" := (ket x).\nNotation \"'⟨' x '∣'\" := (bra x). (* This gives the Coq parser headaches *)\n\nNotation \"∣ x , y , .. , z ⟩\" := (kron .. (kron ∣x⟩ ∣y⟩) .. ∣z⟩) (at level 0).\n(* Alternative: |0⟩|1⟩. *)\n                                                                       \nTransparent bra.\nTransparent ket.\nTransparent qubit0.\nTransparent qubit1.\n\nDefinition bool_to_ket (b : bool) : Matrix 2 1 := if b then ∣1⟩ else ∣0⟩.\n                                                                     \nDefinition bool_to_matrix (b : bool) : Matrix 2 2 := if b then ∣1⟩⟨1∣ else ∣0⟩⟨0∣.\n\nDefinition bool_to_matrix' (b : bool) : Matrix 2 2 := fun x y =>\n  match x, y with\n  | 0, 0 => if b then 0 else 1\n  | 1, 1 => if b then 1 else 0\n  | _, _ => 0\n  end.  \n  \nLemma bool_to_matrix_eq : forall b, bool_to_matrix b = bool_to_matrix' b.\nProof. intros. destruct b; simpl; solve_matrix. Qed.\n\nLemma bool_to_ket_matrix_eq : forall b,\n    outer_product (bool_to_ket b) (bool_to_ket b) = bool_to_matrix b.\nProof. unfold outer_product. destruct b; simpl; reflexivity. Qed.\n\nDefinition bools_to_matrix (l : list bool) : Square (2^(length l)) := \n  big_kron (map bool_to_matrix l).\n\nLemma ket_decomposition : forall (ψ : Vector 2), \n  WF_Matrix ψ ->\n  ψ = (ψ 0%nat 0%nat) .* ∣ 0 ⟩ .+ (ψ 1%nat 0%nat) .* ∣ 1 ⟩.\nProof.\n  intros.\n  prep_matrix_equality.\n  unfold scale, Mplus.\n  destruct y as [|y']. \n  2:{ rewrite H; try lia. \n      unfold ket, qubit0, qubit1. simpl. \n      repeat (destruct x; try lca). }\n  destruct x as [| [| n]]; unfold ket, qubit0, qubit1; simpl; try lca.  \n  rewrite H; try lia.\n  lca.\nQed. \n\n(****************)\n(** * Unitaries *)\n(****************)\n\nDefinition hadamard : Matrix 2 2 := \n  (fun x y => match x, y with\n          | 0, 0 => (1 / √2)\n          | 0, 1 => (1 / √2)\n          | 1, 0 => (1 / √2)\n          | 1, 1 => -(1 / √2)\n          | _, _ => 0\n          end).\n\nFixpoint hadamard_k (k : nat) : Matrix (2^k) (2^k):= \n  match k with\n  | 0 => I 1\n  | S k' => hadamard ⊗ hadamard_k k'\n  end. \n\nLemma hadamard_1 : hadamard_k 1 = hadamard.\nProof. apply kron_1_r. Qed.\n\n(* Alternative definitions:\nDefinition pauli_x : Matrix 2 2 := fun x y => if x + y =? 1 then 1 else 0.\nDefinition pauli_y : Matrix 2 2 := fun x y => if x + y =? 1 then (-1) ^ x * Ci else 0.\nDefinition pauli_z : Matrix 2 2 := fun x y => if (x =? y) && (x <? 2) \n                                           then (-1) ^ x * Ci else 0.\n*)\n\nDefinition σx : Matrix 2 2 := \n  fun x y => match x, y with\n          | 0, 1 => C1\n          | 1, 0 => C1\n          | _, _ => C0\n          end.\n\nDefinition σy : Matrix 2 2 := \n  fun x y => match x, y with\n          | 0, 1 => -Ci\n          | 1, 0 => Ci\n          | _, _ => C0\n          end.\n\nDefinition σz : Matrix 2 2 := \n  fun x y => match x, y with\n          | 0, 0 => C1\n          | 1, 1 => -C1\n          | _, _ => C0\n          end.\n\nDefinition sqrtx : Matrix 2 2 :=\n  fun x y => match x, y with\n          | 0, 0 => (1 + Ci)/2\n          | 0, 1 => (1 - Ci)/2\n          | 1, 0 => (1 - Ci)/2\n          | 1, 1 => (1 + Ci)/2\n          | _, _ => C0\n          end.\n\nLemma sqrtx_sqrtx : sqrtx × sqrtx = σx.\nProof.\n  unfold sqrtx, σx, Mmult.\n  prep_matrix_equality.\n  destruct_m_eq; \n  autorewrite with trig_db C_db; try lca.\nQed.\n\nDefinition control {n : nat} (A : Matrix n n) : Matrix (2*n) (2*n) :=\n  fun x y => if (x <? n) && (y =? x) then 1 else \n          if (n <=? x) && (n <=? y) then A (x-n)%nat (y-n)%nat else 0.\n\n(* Definition cnot := control pauli_x. *)\n(* Direct definition makes our lives easier *)\n(* Dimensions are given their current form for convenient\n   kron_mixed_product applications *)\nDefinition cnot : Matrix (2*2) (2*2) :=\n  fun x y => match x, y with \n          | 0, 0 => C1\n          | 1, 1 => C1\n          | 2, 3 => C1\n          | 3, 2 => C1\n          | _, _ => C0\n          end.          \n\nLemma cnot_eq : cnot = control σx.\nProof.\n  unfold cnot, control, σx.\n  solve_matrix.\nQed.\n\nDefinition notc : Matrix (2*2) (2*2) :=\n  fun x y => match x, y with \n          | 1, 3 => 1%C\n          | 3, 1 => 1%C\n          | 0, 0 => 1%C\n          | 2, 2 => 1%C\n          | _, _ => 0%C\n          end.          \n\n(* Swap Matrices *)\n\nDefinition swap : Matrix (2*2) (2*2) :=\n  fun x y => match x, y with\n          | 0, 0 => C1\n          | 1, 2 => C1\n          | 2, 1 => C1\n          | 3, 3 => C1\n          | _, _ => C0\n          end.\n\nHint Unfold qubit0 qubit1 hadamard σx σy σz control cnot swap bra ket : U_db.\n\n(** ** Rotation Matrices *)\n                              \n(* Standard(?) definition, but it makes equivalence-checking a little annoying \n   because of a global phase.\n\nDefinition rotation (θ ϕ λ : R) : Matrix 2 2 :=\n  fun x y => match x, y with\n             | 0, 0 => (Cexp (-(ϕ + λ)/2)) * (cos (θ/2))\n             | 0, 1 => - (Cexp (-(ϕ - λ)/2)) * (sin (θ/2))\n             | 1, 0 => (Cexp ((ϕ - λ)/2)) * (sin (θ/2))\n             | 1, 1 => (Cexp ((ϕ + λ)/2)) * (cos (θ/2))\n             | _, _ => C0\n             end.\n*)\nDefinition rotation (θ ϕ λ : R) : Matrix 2 2 :=\n  fun x y => match x, y with\n             | 0, 0 => (cos (θ/2))\n             | 0, 1 => - (Cexp λ) * (sin (θ/2))\n             | 1, 0 => (Cexp ϕ) * (sin (θ/2))\n             | 1, 1 => (Cexp (ϕ + λ)) * (cos (θ/2))\n             | _, _ => C0\n             end.\n\n(* z_rotation lemmas are further down *)\nDefinition phase_shift (ϕ : R) : Matrix 2 2 :=\n  fun x y => match x, y with\n          | 0, 0 => C1\n          | 1, 1 => Cexp ϕ\n          | _, _ => C0\n          end.\n\n(* Notation z_rotation := phase_shift. *)\n\nDefinition x_rotation  (θ : R) : Matrix 2 2 :=\n  fun x y => match x, y with\n          | 0, 0 => cos (θ / 2)\n          | 0, 1 => -Ci * sin (θ / 2)\n          | 1, 0 => -Ci * sin (θ / 2)\n          | 1, 1 => cos (θ / 2)\n          | _, _ => 0\n          end.\n\nDefinition y_rotation  (θ : R) : Matrix 2 2 :=\n  fun x y => match x, y with\n          | 0, 0 => cos (θ / 2)\n          | 0, 1 => - sin (θ / 2)\n          | 1, 0 => sin (θ / 2)\n          | 1, 1 => cos (θ / 2)\n          | _, _ => 0\n          end.\n\n(* Shifted by i so x/y_rotation PI = σx/y :\nDefinition x_rotation  (θ : R) : Matrix 2 2 :=\n  fun x y => match x, y with\n          | 0, 0 => Ci * cos (θ / 2)\n          | 0, 1 => sin (θ / 2)\n          | 1, 0 => sin (θ / 2)\n          | 1, 1 => Ci * cos (θ / 2)\n          | _, _ => 0\n          end.\n\nDefinition y_rotation  (θ : R) : Matrix 2 2 :=\n  fun x y => match x, y with\n          | 0, 0 => Ci * cos (θ / 2)\n          | 0, 1 => -Ci * sin (θ / 2)\n          | 1, 0 => Ci * sin (θ / 2)\n          | 1, 1 => Ci * cos (θ / 2)\n          | _, _ => 0\n          end.\n *)\n\nLemma x_rotation_pi : x_rotation PI = -Ci .* σx.\nProof.\n  unfold σx, x_rotation, scale.\n  prep_matrix_equality.\n  destruct_m_eq; \n  autorewrite with trig_db C_db;\n  reflexivity. \nQed.\n\nLemma y_rotation_pi : y_rotation PI = -Ci .* σy.\nProof.\n  unfold σy, y_rotation, scale. \n  prep_matrix_equality.\n  destruct_m_eq; \n  autorewrite with trig_db C_db;\n  try reflexivity. \nQed.\n\nLemma hadamard_rotation : rotation (PI/2) 0 PI = hadamard.\nProof.\n  unfold hadamard, rotation. \n  prep_matrix_equality.\n  destruct_m_eq; try reflexivity; \n  unfold Cexp; apply injective_projections; simpl;\n  autorewrite with R_db;\n  autorewrite with trig_db;\n  autorewrite with R_db;\n  try reflexivity.\n  all: rewrite Rmult_assoc;\n       replace (/2 * /2)%R with (/4)%R by lra;\n       repeat rewrite <- Rdiv_unfold;\n       autorewrite with trig_db;\n       rewrite sqrt2_div2;\n       lra.\nQed.\n\nLemma pauli_x_rotation : rotation PI 0 PI = σx.\nProof.\n  unfold σx, rotation. \n  prep_matrix_equality.\n  destruct_m_eq; try reflexivity;\n  unfold Cexp; apply injective_projections; simpl;\n  autorewrite with trig_db;\n  lra.\nQed.\n\nLemma pauli_y_rotation : rotation PI (PI/2) (PI/2) = σy.\nProof. \n  unfold σy, rotation. \n  prep_matrix_equality.\n  destruct_m_eq; try reflexivity;\n  unfold Cexp; apply injective_projections; simpl;\n  autorewrite with trig_db;\n  lra.\nQed.\n\nLemma pauli_z_rotation : rotation 0 0 PI = σz.\nProof. \n  unfold σz, rotation. \n  prep_matrix_equality.\n  destruct_m_eq; try reflexivity;\n  unfold Cexp; apply injective_projections; simpl;\n  autorewrite with R_db;\n  autorewrite with trig_db;\n  lra.\nQed.\n\n(* sqrtx as a (x-)rotation? *)\n\nLemma Rx_rotation : forall θ, rotation θ (3*PI/2) (PI/2) = x_rotation θ.\nProof.\n  intros.\n  unfold rotation, x_rotation. \n  prep_matrix_equality.\n  destruct_m_eq;\n  autorewrite with C_db Cexp_db; reflexivity.\nQed.\n\nLemma Ry_rotation : forall θ, rotation θ 0 0 = y_rotation θ.\nProof. \n  intros.\n  unfold rotation, y_rotation. \n  prep_matrix_equality.\n  destruct_m_eq;\n  autorewrite with C_db Cexp_db; try reflexivity.\nQed.\n\n\nLemma phase_shift_rotation : forall θ, rotation 0 0 θ = phase_shift θ.\nProof. \n  intros.\n  unfold phase_shift, rotation. \n  prep_matrix_equality.\n  destruct_m_eq; try reflexivity;\n  unfold Cexp; apply injective_projections; simpl;\n  autorewrite with R_db;\n  autorewrite with trig_db;\n  lra.\nQed.\n\nLemma I_rotation : rotation 0 0 0 = I 2.\nProof.\n  unfold I, rotation. \n  prep_matrix_equality.\n  destruct_m_eq; try reflexivity;\n  unfold Cexp; apply injective_projections; simpl;\n  autorewrite with R_db;\n  autorewrite with trig_db;\n  autorewrite with R_db;\n  try reflexivity.\n  bdestruct (x =? y); bdestruct (S (S x) <? 2); simpl; try reflexivity; lia.\n  destruct (x =? y); destruct (S (S x) <? 2); reflexivity.\nQed.\n\n\n(* Lemmas *)\n\nLemma sqrtx_decompose: sqrtx = hadamard × phase_shift (PI/2) × hadamard.\nProof.\n  solve_matrix.\n  all: rewrite Cexp_PI2; group_radicals; lca.\nQed.\n\n(* Additional tactics for ∣0⟩, ∣1⟩, cnot and σx. *)\n\nLemma Mmult00 : ⟨0∣ × ∣0⟩ = I 1. Proof. solve_matrix. Qed.\nLemma Mmult01 : ⟨0∣ × ∣1⟩ = Zero. Proof. solve_matrix. Qed.\nLemma Mmult10 : ⟨1∣ × ∣0⟩ = Zero. Proof. solve_matrix. Qed.\nLemma Mmult11 : ⟨1∣ × ∣1⟩ = I 1. Proof. solve_matrix. Qed.\n\nLemma MmultX1 : σx × ∣1⟩ = ∣0⟩. Proof. solve_matrix. Qed.\nLemma Mmult1X : ⟨1∣ × σx = ⟨0∣. Proof. solve_matrix. Qed.\nLemma MmultX0 : σx × ∣0⟩ = ∣1⟩. Proof. solve_matrix. Qed.\nLemma Mmult0X : ⟨0∣ × σx = ⟨1∣. Proof. solve_matrix. Qed.\n\nLemma MmultXX : σx × σx = I 2. Proof. solve_matrix. Qed.\nLemma MmultYY : σy × σy = I 2. Proof. solve_matrix. Qed.\nLemma MmultZZ : σz × σz = I 2. Proof. solve_matrix. Qed.\nLemma MmultHH : hadamard × hadamard = I 2. Proof. solve_matrix. Qed.\nLemma Mplus01 : ∣0⟩⟨0∣ .+ ∣1⟩⟨1∣ = I 2. Proof. solve_matrix. Qed.\nLemma Mplus10 : ∣1⟩⟨1∣ .+ ∣0⟩⟨0∣ = I 2. Proof. solve_matrix. Qed.\n                            \nLemma σx_on_right0 : forall (q : Vector 2), (q × ⟨0∣) × σx = q × ⟨1∣.\nProof. intros. rewrite Mmult_assoc, Mmult0X. reflexivity. Qed.\n\nLemma σx_on_right1 : forall (q : Vector 2), (q × ⟨1∣) × σx = q × ⟨0∣.\nProof. intros. rewrite Mmult_assoc, Mmult1X. reflexivity. Qed.\n\nLemma σx_on_left0 : forall (q : Matrix 1 2), σx × (∣0⟩ × q) = ∣1⟩ × q.\nProof. intros. rewrite <- Mmult_assoc, MmultX0. reflexivity. Qed.\n\nLemma σx_on_left1 : forall (q : Matrix 1 2), σx × (∣1⟩ × q) = ∣0⟩ × q.\nProof. intros. rewrite <- Mmult_assoc, MmultX1. reflexivity. Qed.\n\nLemma cancel00 : forall (q1 : Matrix 2 1) (q2 : Matrix 1 2), \n  WF_Matrix q2 ->\n  (q1 × ⟨0∣) × (∣0⟩ × q2) = q1 × q2.\nProof. \n  intros. \n  rewrite Mmult_assoc. \n  rewrite <- (Mmult_assoc ⟨0∣).\n  rewrite Mmult00.             \n  Msimpl; reflexivity.\nQed.\n\nLemma cancel01 : forall (q1 : Matrix 2 1) (q2 : Matrix 1 2), \n  (q1 × ⟨0∣) × (∣1⟩ × q2) = Zero.\nProof. \n  intros. \n  rewrite Mmult_assoc. \n  rewrite <- (Mmult_assoc ⟨0∣).\n  rewrite Mmult01.             \n  Msimpl_light; reflexivity.\nQed.\n\nLemma cancel10 : forall (q1 : Matrix 2 1) (q2 : Matrix 1 2), \n  (q1 × ⟨1∣) × (∣0⟩ × q2) = Zero.\nProof. \n  intros. \n  rewrite Mmult_assoc. \n  rewrite <- (Mmult_assoc ⟨1∣).\n  rewrite Mmult10.             \n  Msimpl_light; reflexivity.\nQed.\n\nLemma cancel11 : forall (q1 : Matrix 2 1) (q2 : Matrix 1 2), \n  WF_Matrix q2 ->\n  (q1 × ⟨1∣) × (∣1⟩ × q2) = q1 × q2.\nProof. \n  intros. \n  rewrite Mmult_assoc. \n  rewrite <- (Mmult_assoc ⟨1∣).\n  rewrite Mmult11.             \n  Msimpl; reflexivity.\nQed.\n\nHint Rewrite Mmult00 Mmult01 Mmult10 Mmult11 Mmult0X MmultX0 Mmult1X MmultX1 : Q_db.\nHint Rewrite MmultXX MmultYY MmultZZ MmultHH Mplus01 Mplus10 : Q_db.\nHint Rewrite σx_on_right0 σx_on_right1 σx_on_left0 σx_on_left1 : Q_db.\nHint Rewrite cancel00 cancel01 cancel10 cancel11 using (auto with wf_db) : Q_db.\n\nLemma swap_swap : swap × swap = I (2*2). Proof. solve_matrix. Qed.\n\nLemma swap_swap_r : forall (A : Matrix (2*2) (2*2)), \n  WF_Matrix A ->\n  A × swap × swap = A.\nProof.\n  intros.\n  rewrite Mmult_assoc.\n  rewrite swap_swap.\n  Msimpl.\n  reflexivity.\nQed.\n\nHint Rewrite swap_swap swap_swap_r using (auto 100 with wf_db): Q_db.\n\n\n\n(* The input k is really k+1, to appease to Coq termination gods *)\n(* NOTE: Check that the offsets are right *)\n(* Requires: i + 1 < n *)\nFixpoint swap_to_0_aux (n i : nat) {struct i} : Matrix (2^n) (2^n) := \n  match i with\n  | O => swap ⊗ I (2^(n-2))\n  | S i' =>  (I (2^i) ⊗ swap ⊗ I (2^(n-i-2))) × (* swap i-1 with i *)\n            swap_to_0_aux n i' × \n            (I (2^i) ⊗ swap ⊗ I (2^(n-i-2))) (* swap i-1 with 0 *)\n  end.\n\n(* Requires: i < n *)\nDefinition swap_to_0 (n i : nat) : Matrix (2^n) (2^n) := \n  match i with \n  | O => I (2^n) \n  | S i' => swap_to_0_aux n i'\n  end.\n  \n(* Swapping qubits i and j in an n-qubit system, where i < j *) \n(* Requires i < j, j < n *)\nFixpoint swap_two_aux (n i j : nat) : Matrix (2^n) (2^n) := \n  match i with \n  | O => swap_to_0 n j \n  | S i' => I 2 ⊗ swap_two_aux (n-1) (i') (j-1)\n  end.\n\n(* Swapping qubits i and j in an n-qubit system *)\n(* Requires i < n, j < n *)\nDefinition swap_two (n i j : nat) : Matrix (2^n) (2^n) :=\n  if i =? j then I (2^n) \n  else if i <? j then swap_two_aux n i j\n  else swap_two_aux n j i.\n\n(* Simpler version of swap_to_0 that shifts other elements *)\n(* Requires: i+1 < n *)\nFixpoint move_to_0_aux (n i : nat) {struct i}: Matrix (2^n) (2^n) := \n  match i with\n  | O => swap ⊗ I (2^(n-2))\n  | S i' => (move_to_0_aux n i') × (I (2^i) ⊗ swap ⊗ I (2^(n-i-2))) \n                  \n  end.\n             \n(* Requires: i < n *)\nDefinition move_to_0 (n i : nat) : Matrix (2^n) (2^n) := \n  match i with \n  | O => I (2^n) \n  | S i' => move_to_0_aux n i'\n  end.\n \n(* Always moves up in the matrix from i to k *)\n(* Requires: k < i < n *)\nFixpoint move_to (n i k : nat) : Matrix (2^n) (2^n) := \n  match k with \n  | O => move_to_0 n i \n  | S k' => I 2 ⊗ move_to (n-1) (i-1) (k')\n  end.\n\n(*\nEval compute in ((swap_two 1 0 1) 0 0)%nat.\nEval compute in (print_matrix (swap_two 1 0 2)).\n*)\n\n(** Well Formedness of Quantum States and Unitaries **)\n\nLemma WF_bra0 : WF_Matrix ⟨0∣. Proof. show_wf. Qed. \nLemma WF_bra1 : WF_Matrix ⟨1∣. Proof. show_wf. Qed.\nLemma WF_qubit0 : WF_Matrix ∣0⟩. Proof. show_wf. Qed.\nLemma WF_qubit1 : WF_Matrix ∣1⟩. Proof. show_wf. Qed.\nLemma WF_braqubit0 : WF_Matrix ∣0⟩⟨0∣. Proof. show_wf. Qed.\nLemma WF_braqubit1 : WF_Matrix ∣1⟩⟨1∣. Proof. show_wf. Qed.\nLemma WF_bool_to_ket : forall b, WF_Matrix (bool_to_ket b). \nProof. destruct b; show_wf. Qed.\nLemma WF_bool_to_matrix : forall b, WF_Matrix (bool_to_matrix b).\nProof. destruct b; show_wf. Qed.\nLemma WF_bool_to_matrix' : forall b, WF_Matrix (bool_to_matrix' b).\nProof. destruct b; show_wf. Qed.\n\nLemma WF_ket : forall n, WF_Matrix (ket n).\nProof. destruct n; simpl; show_wf. Qed.\nLemma WF_bra : forall n, WF_Matrix (bra n).\nProof. destruct n; simpl; show_wf. Qed.\n\nLemma WF_bools_to_matrix : forall l, \n  @WF_Matrix (2^(length l)) (2^(length l))  (bools_to_matrix l).\nProof. \n  induction l; auto with wf_db.\n  unfold bools_to_matrix in *; simpl.\n  apply WF_kron; try rewrite map_length; try lia.\n  apply WF_bool_to_matrix.\n  apply IHl.\nQed.\n\nHint Resolve WF_bra0 WF_bra1 WF_qubit0 WF_qubit1 WF_braqubit0 WF_braqubit1 : wf_db.\nHint Resolve WF_bool_to_ket WF_bool_to_matrix WF_bool_to_matrix' : wf_db.\nHint Resolve WF_ket WF_bra WF_bools_to_matrix : wf_db.\n\nLemma WF_hadamard : WF_Matrix hadamard. Proof. show_wf. Qed.\nLemma WF_σx : WF_Matrix σx. Proof. show_wf. Qed.\nLemma WF_σy : WF_Matrix σy. Proof. show_wf. Qed.\nLemma WF_σz : WF_Matrix σz. Proof. show_wf. Qed.\nLemma WF_cnot : WF_Matrix cnot. Proof. show_wf. Qed.\nLemma WF_swap : WF_Matrix swap. Proof. show_wf. Qed.\n\nLemma WF_rotation : forall θ ϕ λ, WF_Matrix (rotation θ ϕ λ). Proof. intros. show_wf. Qed.\nLemma WF_phase : forall ϕ, WF_Matrix (phase_shift ϕ). Proof. intros. show_wf. Qed.\n\n\nLemma WF_control : forall (n : nat) (U : Matrix n n), \n      WF_Matrix U -> WF_Matrix (control U).\nProof.\n  intros n U WFU.\n  unfold control, WF_Matrix in *.\n  intros x y [Hx | Hy];\n  bdestruct (x <? n); bdestruct (y =? x); bdestruct (n <=? x); bdestruct (n <=? y);\n    simpl; try reflexivity; try lia. \n  all: rewrite WFU; [reflexivity|lia].\nQed.\n\nHint Resolve WF_hadamard WF_σx WF_σy WF_σz WF_cnot WF_swap WF_phase : wf_db.\nHint Resolve WF_rotation : wf_db.\n\nHint Extern 2 (WF_Matrix (phase_shift _)) => apply WF_phase : wf_db.\nHint Extern 2 (WF_Matrix (control _)) => apply WF_control : wf_db.\n\n(***************************)\n(** Unitaries are unitary **)\n(***************************)\n\n(* For this section, we could just convert all single-qubit unitaries into their \n   rotation form and use rotation_unitary. *)\n\nDefinition WF_Unitary {n: nat} (U : Matrix n n): Prop :=\n  WF_Matrix U /\\ U † × U = I n.\n\nHint Unfold WF_Unitary : U_db.\n\n(* More precise *)\n(* Definition unitary_matrix' {n: nat} (A : Matrix n n): Prop := Minv A A†. *)\n\nLemma H_unitary : WF_Unitary hadamard.\nProof.\n  split.\n  show_wf.\n  unfold Mmult, I.\n  prep_matrix_equality.\n  autounfold with U_db.\n  destruct x as [| [|x]]; destruct y as [|[|y]]; simpl; autorewrite with C_db; \n    try reflexivity.\n  replace ((S (S x) <? 2)) with false by reflexivity.\n  rewrite andb_false_r.\n  reflexivity.\nQed.\n\nLemma σx_unitary : WF_Unitary σx.\nProof. \n  split.\n  show_wf.\n  unfold Mmult, I.\n  prep_matrix_equality.\n  destruct x as [| [|x]]; destruct y as [|[|y]]; try lca.\n  simpl.\n  replace ((S (S x) <? 2)) with false by reflexivity.\n  rewrite andb_false_r.\n  lca.\nQed.\n\nLemma σy_unitary : WF_Unitary σy.\nProof.\n  split.\n  show_wf.\n  unfold Mmult, I.\n  prep_matrix_equality.\n  destruct x as [| [|x]]; destruct y as [|[|y]]; try lca.\n  simpl.\n  replace ((S (S x) <? 2)) with false by reflexivity.\n  rewrite andb_false_r.\n  lca.\nQed.\n\nLemma σz_unitary : WF_Unitary σz.\nProof.\n  split.\n  show_wf.\n  unfold Mmult, I.\n  prep_matrix_equality.\n  destruct x as [| [|x]]; destruct y as [|[|y]]; try lca.\n  simpl.\n  replace ((S (S x) <? 2)) with false by reflexivity.\n  rewrite andb_false_r.\n  lca.\nQed.\n\nLemma phase_unitary : forall ϕ, @WF_Unitary 2 (phase_shift ϕ).\nProof.\n  intros ϕ.\n  split; [show_wf|].\n  unfold Mmult, I, phase_shift, adjoint, Cexp.\n  prep_matrix_equality.\n  destruct x as [| [|x]]; destruct y as [|[|y]]; try lca.\n  - simpl.\n    Csimpl.\n    unfold Cconj, Cmult.\n    simpl.\n    unfold Rminus.\n    rewrite Ropp_mult_distr_l.\n    rewrite Ropp_involutive.\n    replace (cos ϕ * cos ϕ)%R with ((cos ϕ)²) by easy.\n    replace (sin ϕ * sin ϕ)%R with ((sin ϕ)²) by easy. \n    rewrite Rplus_comm.\n    rewrite sin2_cos2.\n    lca.\n  - simpl. Csimpl.\n    replace ((S (S x) <? 2)) with false by reflexivity.\n    rewrite andb_false_r.\n    lca.\nQed.\n\nLemma rotation_unitary : forall θ ϕ λ, @WF_Unitary 2 (rotation θ ϕ λ).\nProof.\n  intros.\n  split; [show_wf|].\n  unfold Mmult, I, rotation, adjoint, Cexp.\n  prep_matrix_equality.\n  destruct_m_eq; try lca;\n  unfold Cexp, Cconj;\n  apply injective_projections; simpl;\n  autorewrite with R_db;\n  try lra.\n  (* some general rewriting *)\n  all: (repeat rewrite <- Rmult_assoc;\n        repeat rewrite Ropp_mult_distr_l;\n        repeat rewrite <- Rmult_plus_distr_r;\n        repeat rewrite Rmult_assoc;\n        repeat rewrite (Rmult_comm (cos (θ * / 2)));\n        repeat rewrite (Rmult_comm (sin (θ * / 2)));\n        repeat rewrite <- Rmult_assoc;\n        repeat rewrite <- Rmult_plus_distr_r).\n  (* all the cases are about the same; just setting up applications of\n     cos_minus/sin_minus and simplifying *)\n  all: repeat rewrite <- cos_minus.\n  3: (rewrite (Rmult_comm (cos ϕ));\n      rewrite <- (Ropp_mult_distr_l (sin ϕ));\n      rewrite (Rmult_comm (sin ϕ));\n      rewrite <- Rminus_unfold).\n  5: (rewrite (Rmult_comm _ (cos ϕ));\n      rewrite (Rmult_comm _ (sin ϕ));\n      rewrite <- Ropp_mult_distr_r;\n      rewrite <- Rminus_unfold).\n  all: try rewrite <- sin_minus.\n  all: autorewrite with R_db.\n  all: repeat rewrite Rplus_opp_r.\n  all: try (rewrite Ropp_plus_distr;\n            repeat rewrite <- Rplus_assoc;\n            rewrite Rplus_opp_r).\n  all: try (rewrite (Rplus_comm ϕ λ);\n            rewrite Rplus_assoc;\n            rewrite Rplus_opp_r).\n  all: (autorewrite with R_db;\n        autorewrite with trig_db;\n        autorewrite with R_db).\n  all: try lra.\n  all: try (replace (cos (θ * / 2) * cos (θ * / 2))%R with ((cos (θ * / 2))²) by easy;\n            replace (sin (θ * / 2) * sin (θ * / 2))%R with ((sin (θ * / 2))²) by easy).\n  1: rewrite Rplus_comm.\n  all: try (rewrite sin2_cos2; reflexivity).\n  (* two weird left-over cases *)\n  all: (destruct ((x =? y) && (S (S x) <? 2)) eqn:E;\n        try reflexivity).\n  apply andb_prop in E as [_ E].\n  apply Nat.ltb_lt in E; lia.\nQed.\n\nLemma x_rotation_unitary : forall θ, @WF_Unitary 2 (x_rotation θ).\nProof. intros. rewrite <- Rx_rotation. apply rotation_unitary. Qed.\n\nLemma y_rotation_unitary : forall θ, @WF_Unitary 2 (y_rotation θ).\nProof. intros. rewrite <- Ry_rotation. apply rotation_unitary. Qed.\n\nLemma control_unitary : forall n (A : Matrix n n), \n                          WF_Unitary A -> WF_Unitary (control A). \nProof.\n  intros n A H.\n  destruct H as [WF U].\n  split; auto with wf_db.\n  unfold control, adjoint, Mmult, I.\n  prep_matrix_equality.\n  simpl.\n  bdestructΩ (x =? y).\n  - subst; simpl.\n    rewrite Csum_sum.\n    bdestructΩ (y <? n + (n + 0)).\n    + bdestructΩ (n <=? y).\n      * rewrite Csum_0_bounded. Csimpl.\n        rewrite (Csum_eq _ (fun x => A x (y - n)%nat ^* * A x (y - n)%nat)).\n        ++ unfold control, adjoint, Mmult, I in U.\n           rewrite Nat.add_0_r.\n           eapply (equal_f) in U. \n           eapply (equal_f) in U. \n           rewrite U.\n           rewrite Nat.eqb_refl. simpl.\n           bdestructΩ (y - n <? n).\n           easy.\n        ++ apply functional_extensionality. intros x.\n           bdestructΩ (n + x <? n).\n           bdestructΩ (n <=? n + x).\n           rewrite minus_plus.\n           easy.\n        ++ intros x L.\n           bdestructΩ (y =? x).\n           rewrite andb_false_r.\n           bdestructΩ (n <=? x).\n           simpl. lca.\n      * rewrite (Csum_unique 1). \n        rewrite Csum_0_bounded.\n        ++ lca.\n        ++ intros.\n           rewrite andb_false_r.\n           bdestructΩ (n + x <? n).\n           simpl.\n           lca.\n        ++ exists y.\n           repeat rewrite andb_false_r.\n           split. easy.\n           split. \n           rewrite Nat.eqb_refl.\n           bdestructΩ (y <? n).\n           simpl. lca.\n           intros x Ne.\n           bdestructΩ (y =? x ).\n           repeat rewrite andb_false_r.\n           lca.\n    + rewrite 2 Csum_0_bounded; [lca| |].\n      * intros x L.\n        rewrite WF by (right; lia).\n        bdestructΩ (n + x <? n).\n        bdestructΩ (n <=? n + x).\n        bdestructΩ (n <=? y).\n        lca.\n      * intros x L.\n        bdestructΩ (y =? x).\n        rewrite andb_false_r.\n        bdestructΩ (n <=? x).\n        simpl. lca.\n  - simpl.\n    rewrite Csum_sum.\n    bdestructΩ (y <? n + (n + 0)).\n    + bdestructΩ (n <=? y).\n      * rewrite Csum_0_bounded. Csimpl.\n        bdestructΩ (n <=? x).\n        rewrite (Csum_eq _ (fun z => A z (x - n)%nat ^* * A z (y - n)%nat)).\n        ++ unfold control, adjoint, Mmult, I in U.\n           rewrite Nat.add_0_r.\n           eapply (equal_f) in U. \n           eapply (equal_f) in U. \n           rewrite U.\n           bdestructΩ (x - n =? y - n).\n           simpl.\n           easy.\n        ++ apply functional_extensionality. intros z.\n           bdestructΩ (n + z <? n).\n           bdestructΩ (n <=? n + z).\n           rewrite minus_plus.\n           easy.\n        ++ rewrite Csum_0. easy.\n           intros z.\n           bdestructΩ (n + z <? n).\n           rewrite andb_false_r.\n           Csimpl. easy. \n        ++ intros z L.\n           bdestructΩ (z <? n).\n           bdestructΩ (n <=? z).\n           bdestructΩ (x =? z); bdestructΩ (y =? z); try lca. \n      * bdestructΩ (n <=? x).        \n        ++ rewrite Csum_0_bounded.\n           rewrite Csum_0_bounded. lca.\n           ** intros z L.\n              bdestructΩ (n + z <? n).\n              rewrite andb_false_r.\n              lca.\n           ** intros z L.\n              bdestructΩ (z <? n).\n              rewrite andb_false_r.\n              bdestructΩ (x =? z); bdestructΩ (y =? z); try lca.\n              bdestructΩ (n <=? z).\n              lca.\n        ++ rewrite 2 Csum_0_bounded; [lca| |].\n           ** intros z L.\n              rewrite andb_false_r.\n              bdestructΩ (x =? n + z); bdestructΩ (y =? n + z); rewrite andb_false_r; lca.\n           ** intros z L.\n              rewrite andb_false_r.\n              bdestructΩ (x =? z); bdestructΩ (y =? z); rewrite andb_false_r; lca.\n    + rewrite 2 Csum_0_bounded; [lca| |].\n      * intros z L.\n        bdestructΩ (n + z <? n). \n        bdestructΩ (n <=? n + z). \n        bdestructΩ (n <=? y).\n        rewrite (WF _ (y-n)%nat) by (right; lia).\n        lca.\n      * intros z L.\n        bdestructΩ (y =? z).\n        rewrite andb_false_r.\n        rewrite (WF _ (y-n)%nat) by (right; lia).\n        destruct ((n <=? z) && (n <=? y)); lca.\nQed.\n\nLemma transpose_unitary : forall n (A : Matrix n n), WF_Unitary A -> WF_Unitary (A†).\nProof.\n  intros. \n  simpl.\n  split.\n  + destruct H; auto with wf_db.\n  + unfold WF_Unitary in *.\n    rewrite adjoint_involutive.\n    destruct H as [_ H].\n    apply Minv_left in H as [_ S]. (* NB: admitted lemma *)\n    assumption.\nQed.\n\nLemma cnot_unitary : WF_Unitary cnot.\nProof.\n  split. \n  apply WF_cnot.\n  unfold Mmult, I.\n  prep_matrix_equality.\n  do 4 (try destruct x; try destruct y; try lca).\n  replace ((S (S (S (S x))) <? 4)) with (false) by reflexivity.\n  rewrite andb_false_r.\n  lca.\nQed.\n\nLemma id_unitary : forall n, WF_Unitary (I n). \nProof.\n  split.\n  apply WF_I.\n  unfold WF_Unitary.\n  rewrite id_adjoint_eq.\n  apply Mmult_1_l.\n  apply WF_I.\nQed.\n\nLemma swap_unitary : WF_Unitary swap.\nProof. \n  split.\n  apply WF_swap.\n  unfold WF_Unitary, Mmult, I.\n  prep_matrix_equality.\n  do 4 (try destruct x; try destruct y; try lca).\n  replace ((S (S (S (S x))) <? 4)) with (false) by reflexivity.\n  rewrite andb_false_r.\n  lca.\nQed.\n\nLemma zero_not_unitary : forall n, ~ (WF_Unitary (@Zero (2^n) (2^n))).\nProof.\n  intros n.\n  intros F.\n  destruct F as [_ U].\n  apply (f_equal2_inv 0 0)%nat in U.\n  revert U.\n  rewrite Mmult_0_r.\n  unfold I, Zero.\n  simpl.\n  bdestruct (0 <? 2 ^ n).\n  intros F. inversion F. lra.\n  specialize (pow_positive 2 n) as P.\n  lia.\nQed.\n\nLemma kron_unitary : forall {m n} (A : Matrix m m) (B : Matrix n n),\n  WF_Unitary A -> WF_Unitary B -> WF_Unitary (A ⊗ B).\nProof.\n  intros m n A B [WFA UA] [WFB UB].\n  unfold WF_Unitary in *.\n  split.\n  auto with wf_db.\n  rewrite kron_adjoint.\n  rewrite kron_mixed_product.\n  rewrite UA, UB.\n  rewrite id_kron. \n  easy.\nQed.\n\nLemma Mmult_unitary : forall (n : nat) (A : Square n) (B : Square n),\n  WF_Unitary A ->\n  WF_Unitary B ->\n  WF_Unitary (A × B).  \nProof.\n  intros n A B [WFA UA] [WFB UB].\n  split.\n  auto with wf_db.\n  Msimpl.\n  rewrite Mmult_assoc.\n  rewrite <- (Mmult_assoc A†).\n  rewrite UA.\n  Msimpl.\n  apply UB.\nQed.\n\n(********************)\n(* Self-adjointness *)\n(********************)\n\n(* Maybe change to \"Hermitian?\" *)\n\nDefinition id_sa := id_adjoint_eq.\n\nLemma hadamard_sa : hadamard† = hadamard.\nProof.\n  prep_matrix_equality.\n  repeat (try destruct x; try destruct y; try lca; trivial).\nQed.\n\nLemma σx_sa : σx† = σx.\nProof. \n  prep_matrix_equality. \n  repeat (try destruct x; try destruct y; try lca; trivial).\nQed.\n\nLemma σy_sa : σy† = σy.\nProof.\n  prep_matrix_equality. \n  repeat (try destruct x; try destruct y; try lca; trivial).\nQed.\n\nLemma σz_sa : σz† = σz.\nProof.\n  prep_matrix_equality. \n  repeat (try destruct x; try destruct y; try lca; trivial).\nQed.\n\nLemma cnot_sa : cnot† = cnot.\nProof.\n  prep_matrix_equality. \n  repeat (try destruct x; try destruct y; try lca; trivial).\nQed.\n\nLemma swap_sa : swap† = swap.\nProof.\n  prep_matrix_equality. \n  repeat (try destruct x; try destruct y; try lca; trivial).\nQed.\n\nLemma control_adjoint : forall n (U : Square n), (control U)† = control (U†).\nProof.\n  intros n U.\n  unfold control, adjoint.\n  prep_matrix_equality.\n  rewrite Nat.eqb_sym.\n  bdestruct (y =? x). \n  - subst.\n    bdestruct (x <? n); bdestruct (n <=? x); try lia; simpl; lca.\n  - rewrite 2 andb_false_r.\n    rewrite andb_comm.\n    rewrite (if_dist _ _ _ Cconj).\n    rewrite Cconj_0.\n    reflexivity.\nQed.\n\nLemma control_sa : forall (n : nat) (A : Square n), \n    A† = A -> (control A)† = (control A).\nProof.\n  intros n A H.\n  rewrite control_adjoint.\n  rewrite H.\n  easy.\nQed.  \n\nLemma phase_adjoint : forall ϕ, (phase_shift ϕ)† = phase_shift (-ϕ). \nProof.\n  intros ϕ.\n  unfold phase_shift, adjoint.\n  prep_matrix_equality.\n  destruct_m_eq; try lca.\n  unfold Cexp, Cconj. \n  rewrite cos_neg, sin_neg.\n  easy.\nQed.\n\n(* x and y rotation adjoints aren't x and rotations? *)\n\nLemma rotation_adjoint : forall θ ϕ λ, (rotation θ ϕ λ)† = rotation (-θ) (-λ) (-ϕ).\nProof.\n  intros.\n  unfold rotation, adjoint.\n  prep_matrix_equality.\n  destruct_m_eq; try lca;\n  unfold Cexp, Cconj;\n  apply injective_projections; simpl;\n  try rewrite <- Ropp_plus_distr;\n  autorewrite with R_db;\n  autorewrite with trig_db;\n  try rewrite (Rplus_comm λ ϕ);\n  autorewrite with R_db;\n  reflexivity.\nQed.\n\nLemma braqubit0_sa : ∣0⟩⟨0∣† = ∣0⟩⟨0∣. Proof. lma. Qed.\nLemma braqubit1_sa : ∣1⟩⟨1∣† = ∣1⟩⟨1∣. Proof. lma. Qed.\n\nHint Rewrite hadamard_sa σx_sa σy_sa σz_sa cnot_sa swap_sa braqubit1_sa braqubit0_sa control_adjoint phase_adjoint rotation_adjoint : Q_db.\n\n(* Rather use control_adjoint :\nHint Rewrite control_sa using (autorewrite with M_db; reflexivity) : M_db. *)\n\nLemma cnot_decomposition : ∣1⟩⟨1∣ ⊗ σx .+ ∣0⟩⟨0∣ ⊗ I 2 = cnot.\nProof. solve_matrix. Qed.                                               \n\nLemma notc_decomposition : σx ⊗ ∣1⟩⟨1∣ .+ I 2 ⊗ ∣0⟩⟨0∣ = notc.\nProof. solve_matrix. Qed.                                               \n\n(*********************)\n(** ** Phase Lemmas **)\n(*********************)\n\nLemma phase_0 : phase_shift 0 = I 2.\nProof. \n  unfold phase_shift, I. \n  rewrite Cexp_0.\n  solve_matrix.\nQed.\n\nLemma phase_2pi : phase_shift (2 * PI) = I 2.\n  unfold phase_shift, I. \n  rewrite Cexp_2PI.\n  solve_matrix.\nQed.\n\nLemma phase_pi : phase_shift PI = σz.\nProof.\n  unfold phase_shift, σz.\n  rewrite Cexp_PI.\n  replace (RtoC (-1)) with (Copp (RtoC 1)) by lca.\n  reflexivity.\nQed.\n\nLemma phase_neg_pi : phase_shift (-PI) = σz.\nProof.\n  unfold phase_shift, σz.\n  rewrite Cexp_neg.\n  rewrite Cexp_PI.\n  replace (/ -1) with (Copp (RtoC 1)) by lca.\n  reflexivity.\nQed.\n\nLemma phase_mul : forall θ θ', phase_shift θ × phase_shift θ' = phase_shift (θ + θ').\nProof.\n  intros. solve_matrix. rewrite Cexp_add. reflexivity.\nQed.  \n\n(* Old, can probably remove *)\nLemma phase_PI4_m8 : forall k,\n  phase_shift (IZR k * PI / 4) = phase_shift (IZR (k - 8) * PI / 4).\nProof.\n  intros. unfold phase_shift. rewrite Cexp_PI4_m8. reflexivity.\nQed.\n\nLemma phase_mod_2PI : forall k, phase_shift (IZR k * PI) = phase_shift (IZR (k mod 2) * PI).\nProof.\n  intros. unfold phase_shift. rewrite Cexp_mod_2PI. reflexivity.\nQed.\n\nLemma phase_mod_2PI_scaled : forall (k sc : Z), \n  sc <> 0%Z ->\n  phase_shift (IZR k * PI / IZR sc) = phase_shift (IZR (k mod (2 * sc)) * PI / IZR sc).\nProof.\n  intros. unfold phase_shift. rewrite Cexp_mod_2PI_scaled; easy. \nQed.\n\n\nHint Rewrite phase_0 phase_2pi phase_pi phase_neg_pi : Q_db.\n\n\n(*****************************)\n(* Positive Semidefiniteness *)\n(*****************************)\n\nDefinition positive_semidefinite {n} (A : Square n) : Prop :=\n  forall (z : Vector n), WF_Matrix z -> fst ((z† × A × z) O O) >= 0.  \n\nLemma pure_psd : forall (n : nat) (ϕ : Vector n), (WF_Matrix ϕ) -> positive_semidefinite (ϕ × ϕ†). \nProof.\n  intros n ϕ WFϕ z WFZ.\n  repeat rewrite Mmult_assoc.\n  remember (ϕ† × z) as ψ.\n  repeat rewrite <- Mmult_assoc.\n  rewrite <- (adjoint_involutive _ _ ϕ).\n  rewrite <- Mmult_adjoint.\n  rewrite <- Heqψ.\n  unfold Mmult. simpl.\n  rewrite <- Ropp_mult_distr_l.\n  rewrite Rplus_0_l.\n  unfold Rminus.\n  rewrite Ropp_involutive.\n  replace (fst (z 1%nat 0%nat) * fst (z 1%nat 0%nat))%R with ((fst (z 1%nat 0%nat))²) by easy. \n  replace (snd (z 1%nat 0%nat) * snd (z 1%nat 0%nat))%R with ((snd (z 1%nat 0%nat))²) by easy. \n  apply Rle_ge.\n  apply Rplus_le_le_0_compat; apply Rle_0_sqr.\nQed.\n\nLemma braket0_psd : positive_semidefinite ∣0⟩⟨0∣.\nProof. apply pure_psd. auto with wf_db. Qed.\n\nLemma braket1_psd : positive_semidefinite ∣1⟩⟨1∣.\nProof. apply pure_psd. auto with wf_db. Qed.\n\nLemma H0_psd : positive_semidefinite (hadamard × ∣0⟩⟨0∣ × hadamard).\nProof.\n  repeat rewrite Mmult_assoc.\n  rewrite <- hadamard_sa at 2.\n  rewrite <- Mmult_adjoint.\n  repeat rewrite <- Mmult_assoc.\n  apply pure_psd.\n  auto with wf_db.\nQed.\n\n\n(*************************)\n(* Pure and Mixed States *)\n(*************************)\n\nNotation Density n := (Matrix n n) (only parsing). \n\nDefinition Classical {n} (ρ : Density n) := forall i j, i <> j -> ρ i j = 0.\n\nDefinition Pure_State_Vector {n} (φ : Vector n): Prop := \n  WF_Matrix φ /\\ φ† × φ = I  1.\n\nDefinition Pure_State {n} (ρ : Density n) : Prop := \n  exists φ, Pure_State_Vector φ /\\ ρ = φ × φ†.\n\nInductive Mixed_State {n} : Matrix n n -> Prop :=\n| Pure_S : forall ρ, Pure_State ρ -> Mixed_State ρ\n| Mix_S : forall (p : R) ρ1 ρ2, 0 < p < 1 -> Mixed_State ρ1 -> Mixed_State ρ2 ->\n                                       Mixed_State (p .* ρ1 .+ (1-p)%R .* ρ2).  \n\nLemma WF_Pure : forall {n} (ρ : Density n), Pure_State ρ -> WF_Matrix ρ.\nProof. intros. destruct H as [φ [[WFφ IP1] Eρ]]. rewrite Eρ. auto with wf_db. Qed.\nHint Resolve WF_Pure : wf_db.\n\nLemma WF_Mixed : forall {n} (ρ : Density n), Mixed_State ρ -> WF_Matrix ρ.\nProof. induction 1; auto with wf_db. Qed.\nHint Resolve WF_Mixed : wf_db.\n\nLemma pure0 : Pure_State ∣0⟩⟨0∣. \nProof. exists ∣0⟩. intuition. split. auto with wf_db. solve_matrix. Qed.\n\nLemma pure1 : Pure_State ∣1⟩⟨1∣. \nProof. exists ∣1⟩. intuition. split. auto with wf_db. solve_matrix. Qed.\n\nLemma pure_id1 : Pure_State (I  1).\nProof. exists (I  1). split. split. auto with wf_db. solve_matrix. solve_matrix. Qed.\n\nLemma pure_dim1 : forall (ρ : Square 1), Pure_State ρ -> ρ = I  1.\nProof.\n  intros ρ [φ [[WFφ IP1] Eρ]]. \n  apply Minv_flip in IP1.\n  rewrite Eρ; easy.\nQed.    \n                              \nLemma pure_state_kron : forall m n (ρ : Square m) (φ : Square n),\n  Pure_State ρ -> Pure_State φ -> Pure_State (ρ ⊗ φ).\nProof.\n  intros m n ρ φ [u [[WFu Pu] Eρ]] [v [[WFv Pv] Eφ]].\n  exists (u ⊗ v).\n  split; [split |]. \n  - replace (S O) with (S O * S O)%nat by reflexivity.\n    apply WF_kron; auto.\n  - Msimpl. rewrite Pv, Pu. Msimpl. easy.\n  - Msimpl. subst. easy.\nQed.\n\nLemma mixed_state_kron : forall m n (ρ : Square m) (φ : Square n),\n  Mixed_State ρ -> Mixed_State φ -> Mixed_State (ρ ⊗ φ).\nProof.\n  intros m n ρ φ Mρ Mφ.\n  induction Mρ.\n  induction Mφ.\n  - apply Pure_S. apply pure_state_kron; easy.\n  - rewrite kron_plus_distr_l.\n    rewrite 2 Mscale_kron_dist_r.\n    apply Mix_S; easy.\n  - rewrite kron_plus_distr_r.\n    rewrite 2 Mscale_kron_dist_l.\n    apply Mix_S; easy.\nQed.\n\nLemma pure_state_trace_1 : forall {n} (ρ : Density n), Pure_State ρ -> trace ρ = 1.\nProof.\n  intros n ρ [u [[WFu Uu] E]]. \n  subst.\n  clear -Uu.\n  unfold trace.\n  unfold Mmult, adjoint in *.\n  simpl in *.\n  match goal with\n    [H : ?f = ?g |- _] => assert (f O O = g O O) by (rewrite <- H; easy)\n  end. \n  unfold I in H; simpl in H.\n  rewrite <- H.\n  apply Csum_eq.\n  apply functional_extensionality.\n  intros x.\n  rewrite Cplus_0_l, Cmult_comm.\n  easy.\nQed.\n\nLemma mixed_state_trace_1 : forall {n} (ρ : Density n), Mixed_State ρ -> trace ρ = 1.\nProof.\n  intros n ρ H. \n  induction H. \n  - apply pure_state_trace_1. easy.\n  - rewrite trace_plus_dist.\n    rewrite 2 trace_mult_dist.\n    rewrite IHMixed_State1, IHMixed_State2.\n    lca.\nQed.\n\n(* The following two lemmas say that for any mixed states, the elements along the \n   diagonal are real numbers in the [0,1] interval. *)\n\nLemma mixed_state_diag_in01 : forall {n} (ρ : Density n) i , Mixed_State ρ -> \n                                                        0 <= fst (ρ i i) <= 1.\nProof.\n  intros.\n  induction H.\n  - destruct H as [φ [[WFφ IP1] Eρ]].\n    destruct (lt_dec i n). \n    2: rewrite Eρ; unfold Mmult, adjoint; simpl; rewrite WFφ; simpl; [lra|lia].\n    rewrite Eρ.\n    unfold Mmult, adjoint in *.\n    simpl in *.\n    rewrite Rplus_0_l.\n    match goal with\n    [H : ?f = ?g |- _] => assert (f O O = g O O) by (rewrite <- H; easy)\n    end. \n    unfold I in H. simpl in H. clear IP1.\n    match goal with\n    [ H : ?x = ?y |- _] => assert (H': fst x = fst y) by (rewrite H; easy); clear H\n    end.\n    simpl in H'.\n    rewrite <- H'.    \n    split.\n    + unfold Rminus. rewrite <- Ropp_mult_distr_r. rewrite Ropp_involutive.\n      rewrite <- Rplus_0_r at 1.\n      apply Rplus_le_compat; apply Rle_0_sqr.    \n    + match goal with \n      [ |- ?x <= fst (Csum ?f ?m)] => specialize (Csum_member_le f n) as res\n      end.\n      simpl in *.\n      unfold Rminus in *.\n      Search (_ * - _)%R.\n      rewrite <- Ropp_mult_distr_r.\n      rewrite Ropp_mult_distr_l.\n      apply res with (x := i); trivial. \n      intros x.\n      unfold Rminus. rewrite <- Ropp_mult_distr_l. rewrite Ropp_involutive.\n      rewrite <- Rplus_0_r at 1.\n      apply Rplus_le_compat; apply Rle_0_sqr.    \n  - simpl.\n    repeat rewrite Rmult_0_l.\n    repeat rewrite Rminus_0_r.\n    split.\n    assert (0 <= p * fst (ρ1 i i)).\n      apply Rmult_le_pos; lra.\n    assert (0 <= (1 - p) * fst (ρ2 i i)).\n      apply Rmult_le_pos; lra.\n    lra.\n    assert (p * fst (ρ1 i i) <= p)%R. \n      rewrite <- Rmult_1_r.\n      apply Rmult_le_compat_l; lra.\n    assert ((1 - p) * fst (ρ2 i i) <= (1-p))%R. \n      rewrite <- Rmult_1_r.\n      apply Rmult_le_compat_l; lra.\n    lra.\nQed.\n\nLemma mixed_state_diag_real : forall {n} (ρ : Density n) i , Mixed_State ρ -> \n                                                        snd (ρ i i) = 0.\nProof.\n  intros.\n  induction H.\n  + unfold Pure_State in H. \n  - destruct H as [φ [[WFφ IP1] Eρ]].\n    rewrite Eρ.\n    simpl. \n    lra.\n  + simpl.\n    rewrite IHMixed_State1, IHMixed_State2.\n    repeat rewrite Rmult_0_r, Rmult_0_l.\n    lra.\nQed.\n\nLemma mixed_dim1 : forall (ρ : Square 1), Mixed_State ρ -> ρ = I  1.\nProof.\n  intros.  \n  induction H.\n  + apply pure_dim1; trivial.\n  + rewrite IHMixed_State1, IHMixed_State2.\n    prep_matrix_equality.\n    lca.\nQed.  \n\n(* Useful to be able to normalize vectors *)\n\nDefinition norm {n} (ψ : Vector n) : R :=\n  sqrt (fst ((ψ† × ψ) O O)).\n\nDefinition normalize {n} (ψ : Vector n) :=\n  / (norm ψ) .* ψ.\n\nLemma inner_product_ge_0 : forall {d} (ψ : Vector d),\n  0 <= fst ((ψ† × ψ) O O).\nProof.\n  intros.\n  unfold Mmult, adjoint.\n  apply Csum_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\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.\n  rewrite Mscale_adj.\n  distribute_scale.\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.\n\n(** Density matrices and superoperators **)\n\nDefinition Superoperator m n := Density m -> Density n.\n\nDefinition WF_Superoperator {m n} (f : Superoperator m n) := \n  (forall ρ, Mixed_State ρ -> Mixed_State (f ρ)).   \n\nDefinition super {m n} (M : Matrix m n) : Superoperator n m := fun ρ => \n  M × ρ × M†.\n\nLemma super_I : forall n ρ,\n      WF_Matrix ρ ->\n      super (I n) ρ = ρ.\nProof.\n  intros.\n  unfold super.\n  Msimpl.\n  reflexivity.\nQed.\n\nLemma WF_super : forall  m n (U : Matrix m n) (ρ : Square n), \n  WF_Matrix U -> WF_Matrix ρ -> WF_Matrix (super U ρ).\nProof.\n  unfold super.\n  auto with wf_db.\nQed.\n\nHint Resolve WF_super : wf_db.\n\nLemma super_outer_product : forall m (φ : Matrix m 1) (U : Matrix m m), \n    super U (outer_product φ φ) = outer_product (U × φ) (U × φ).\nProof.\n  intros. unfold super, outer_product.\n  autorewrite with M_db Q_db.\n  repeat rewrite Mmult_assoc. reflexivity.\nQed.\n\nDefinition compose_super {m n p} (g : Superoperator n p) (f : Superoperator m n)\n                      : Superoperator m p := fun ρ => g (f ρ).\n\nLemma WF_compose_super : forall m n p (g : Superoperator n p) (f : Superoperator m n) \n  (ρ : Square m), \n  WF_Matrix ρ ->\n  (forall A, WF_Matrix A -> WF_Matrix (f A)) ->\n  (forall A, WF_Matrix A -> WF_Matrix (g A)) ->\n  WF_Matrix (compose_super g f ρ).\nProof.\n  unfold compose_super.\n  auto.\nQed.\n\nHint Resolve WF_compose_super : wf_db.\n\n\nLemma compose_super_correct : forall {m n p} \n                              (g : Superoperator n p) (f : Superoperator m n),\n      WF_Superoperator g -> \n      WF_Superoperator f ->\n      WF_Superoperator (compose_super g f).\nProof.\n  intros m n p g f pf_g pf_f.\n  unfold WF_Superoperator.\n  intros ρ mixed.\n  unfold compose_super.\n  apply pf_g. apply pf_f. auto.\nQed.\n\nDefinition sum_super {m n} (f g : Superoperator m n) : Superoperator m n :=\n  fun ρ => (1/2)%R .* f ρ .+ (1 - 1/2)%R .* g ρ.\n\nLemma sum_super_correct : forall m n (f g : Superoperator m n),\n      WF_Superoperator f -> WF_Superoperator g -> WF_Superoperator (sum_super f g).\nProof.\n  intros m n f g wf_f wf_g ρ pf_ρ.\n  unfold sum_super. \n  set (wf_f' := wf_f _ pf_ρ).\n  set (wf_g' := wf_g _ pf_ρ).\n  apply (Mix_S (1/2) (f ρ) (g ρ)); auto. \n  lra.\nQed.\n\n(* Maybe we shouldn't call these superoperators? Neither is trace-preserving *)\nDefinition SZero {m n} : Superoperator m n := fun ρ => Zero.\nDefinition Splus {m n} (S T : Superoperator m n) : Superoperator m n :=\n  fun ρ => S ρ .+ T ρ.\n\n(* These are *)\nDefinition new0_op : Superoperator 1 2 := super ∣0⟩.\nDefinition new1_op : Superoperator 1 2 := super ∣1⟩.\nDefinition meas_op : Superoperator 2 2 := Splus (super ∣0⟩⟨0∣) (super ∣1⟩⟨1∣).\nDefinition discard_op : Superoperator 2 1 := Splus (super ⟨0∣) (super ⟨1∣).\n\nLemma pure_unitary : forall {n} (U ρ : Matrix n n), \n  WF_Unitary U -> Pure_State ρ -> Pure_State (super U ρ).\nProof.\n  intros n U ρ [WFU H] [φ [[WFφ IP1] Eρ]].\n  rewrite Eρ.\n  exists (U × φ).\n  split.\n  - split; auto with wf_db.\n    rewrite (Mmult_adjoint U φ).\n    rewrite Mmult_assoc.\n    rewrite <- (Mmult_assoc (U†)).\n    rewrite H, Mmult_1_l, IP1; easy.\n  - unfold super.\n    rewrite (Mmult_adjoint U φ).\n    repeat rewrite Mmult_assoc.\n    reflexivity.\nQed.    \n\nLemma mixed_unitary : forall {n} (U ρ : Matrix n n), \n  WF_Unitary U -> Mixed_State ρ -> Mixed_State (super U ρ).\nProof.\n  intros n U ρ H M.\n  induction M.\n  + apply Pure_S.\n    apply pure_unitary; trivial.\n  + unfold WF_Unitary, super in *.\n    rewrite Mmult_plus_distr_l.\n    rewrite Mmult_plus_distr_r.\n    rewrite 2 Mscale_mult_dist_r.\n    rewrite 2 Mscale_mult_dist_l.\n    apply Mix_S; trivial.\nQed.\n\nLemma super_unitary_correct : forall {n} (U : Matrix n n), \n  WF_Unitary U -> WF_Superoperator (super U).\nProof.\n  intros n U H ρ Mρ.\n  apply mixed_unitary; easy.\nQed.\n\nLemma compose_super_assoc : forall {m n p q}\n      (f : Superoperator m n) (g : Superoperator n p) (h : Superoperator p q), \n      compose_super (compose_super f g) h\n    = compose_super f (compose_super g h).\nProof. easy. Qed.\n\nLemma compose_super_eq : forall {m n p} (A : Matrix m n) (B : Matrix n p), \n      compose_super (super A) (super B) = super (A × B).\nProof.\n  intros.\n  unfold compose_super, super.\n  apply functional_extensionality. intros ρ.\n  rewrite Mmult_adjoint.\n  repeat rewrite Mmult_assoc.\n  reflexivity.\nQed.\n\n\n(* This is compose_super_correct \nLemma WF_Superoperator_compose : forall m n p (s : Superoperator n p) (s' : Superoperator m n),\n    WF_Superoperator s ->\n    WF_Superoperator s' ->\n    WF_Superoperator (compose_super s s').\nProof.\n  unfold WF_Superoperator.\n  intros m n p s s' H H0 ρ H1.\n  unfold compose_super.\n  apply H.\n  apply H0.\n  easy.\nQed.\n*)\n\n(**************)\n(* Automation *)\n(**************)\n\nLtac Qsimpl := try restore_dims; autorewrite with M_db_light M_db Q_db.\n\n\n(****************************************)\n(* Tests and Lemmas about swap matrices *)\n(****************************************)\n\nLemma swap_spec : forall (q q' : Vector 2), WF_Matrix q -> \n                                       WF_Matrix q' ->\n                                       swap × (q ⊗ q') = q' ⊗ q.\nProof.\n  intros q q' WF WF'.\n  solve_matrix.\n  - destruct y. lca. \n    rewrite WF by lia. \n    rewrite (WF' O (S y)) by lia.\n    lca.\n  - destruct y. lca. \n    rewrite WF by lia. \n    rewrite (WF' O (S y)) by lia.\n    lca.\n  - destruct y. lca. \n    rewrite WF by lia. \n    rewrite (WF' 1%nat (S y)) by lia.\n    lca.\n  - destruct y. lca. \n    rewrite WF by lia. \n    rewrite (WF' 1%nat (S y)) by lia.\n    lca.\nQed.  \n\nHint Rewrite swap_spec using (auto 100 with wf_db) : Q_db.\n\nExample swap_to_0_test_24 : forall (q0 q1 q2 q3 : Vector 2), \n  WF_Matrix q0 -> WF_Matrix q1 -> WF_Matrix q2 -> WF_Matrix q3 ->\n  swap_to_0 4 2 × (q0 ⊗ q1 ⊗ q2 ⊗ q3) = (q2 ⊗ q1 ⊗ q0 ⊗ q3). \nProof.\n  intros q0 q1 q2 q3 WF0 WF1 WF2 WF3.\n  unfold swap_to_0, swap_to_0_aux.\n  simpl.\n  rewrite Mmult_assoc.\n  repeat rewrite Mmult_assoc.\n  rewrite (kron_assoc q0 q1) by auto with wf_db. Qsimpl.\n  replace 4%nat with (2*2)%nat by reflexivity.\n  repeat rewrite kron_assoc by auto with wf_db.\n  restore_dims.\n  rewrite <- (kron_assoc q0 q2) by auto with wf_db. Qsimpl.\n  rewrite (kron_assoc q2) by auto with wf_db. Qsimpl.\n  rewrite <- kron_assoc by auto with wf_db. Qsimpl.\n  repeat rewrite <- kron_assoc by auto with wf_db.\n  reflexivity.\nQed.\n\nLemma swap_two_base : swap_two 2 1 0 = swap.\nProof. unfold swap_two. simpl. apply kron_1_r. Qed.\n\nLemma swap_second_two : swap_two 3 1 2 = I 2 ⊗ swap.\nProof.\n  unfold swap_two.\n  simpl.\n  rewrite kron_1_r.\n  reflexivity.\nQed.\n\nLemma swap_0_2 : swap_two 3 0 2 = (I 2 ⊗ swap) × (swap ⊗ I 2) × (I 2 ⊗ swap).\nProof.\n  unfold swap_two.\n  simpl.\n  Qsimpl.\n  reflexivity.\nQed.\n\n(*\nProposition swap_to_0_spec : forall (q q0 : Matrix 2 1) (n k : nat) (l1 l2 : list (Matrix 2 1)), \n   length l1 = (k - 1)%nat ->\n   length l2 = (n - k - 2)%nat ->   \n   @Mmult (2^n) (2^n) 1 (swap_to_0 n k) (⨂ ([q0] ++ l1 ++ [q] ++ l2)) = \n     ⨂ ([q] ++ l1 ++ [q0] ++ l2).\n\nProposition swap_two_spec : forall (q q0 : Matrix 2 1) (n0 n1 n2 n k : nat) (l0 l1 l2 : list (Matrix 2 1)), \n   length l0 = n0 ->\n   length l1 = n1 ->\n   length l2 = n2 ->   \n   n = (n0 + n1 + n2 + 2)%nat ->\n   @Mmult (2^n) (2^n) 1 \n     (swap_two n n0 (n0+n1+1)) (⨂ (l0 ++ [q0] ++ l1 ++ [q] ++ l2)) = \n     ⨂ (l0 ++ [q] ++ l1 ++ [q0] ++ l2).\n*)\n\nExample move_to_0_test_24 : forall (q0 q1 q2 q3 : Vector 2), \n  WF_Matrix q0 -> WF_Matrix q1 -> WF_Matrix q2 -> WF_Matrix q3 ->\n  move_to_0 4 2 × (q0 ⊗ q1 ⊗ q2 ⊗ q3) = (q2 ⊗ q0 ⊗ q1 ⊗ q3). \nProof.\n  intros q0 q1 q2 q3 WF0 WF1 WF2 WF3.\n  unfold move_to_0, move_to_0_aux.\n  repeat rewrite Mmult_assoc.\n  rewrite (kron_assoc q0 q1) by auto with wf_db.\n  simpl.\n  restore_dims.\n  replace 4%nat with (2*2)%nat by reflexivity.\n  Qsimpl.\n  rewrite <- kron_assoc by auto with wf_db.\n  restore_dims.\n  repeat rewrite (kron_assoc _ q1) by auto with wf_db. \n  Qsimpl.\n  reflexivity.\nQed.\n\n(* *)\n\n\n", "meta": {"author": "Vickyswj", "repo": "DiracRepr", "sha": "5f4f0759f64b938fd7eb71e1968ea378e56e6646", "save_path": "github-repos/coq/Vickyswj-DiracRepr", "path": "github-repos/coq/Vickyswj-DiracRepr/DiracRepr-5f4f0759f64b938fd7eb71e1968ea378e56e6646/Dirac/src/com/Quantum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6605845488466693}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_ray2.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_lessthancongruence.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_3_7b.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_ray : \n   forall A B P, \n   Out A B P -> neq P B -> ~ BetS A P B ->\n   BetS A B P.\nProof.\nintros.\nassert (neq A B) by (conclude lemma_ray2).\nlet Tf:=fresh in\nassert (Tf:exists E, (BetS E A P /\\ BetS E A B)) by (conclude_def Out );destruct Tf as [E];spliter.\nassert (neq A P) by (forward_using lemma_betweennotequal).\nlet Tf:=fresh in\nassert (Tf:exists D, (BetS A B D /\\ Cong B D A P)) by (conclude lemma_extension);destruct Tf as [D];spliter.\nassert (Cong D B B D) by (conclude cn_equalityreverse).\nassert (Cong D B A P) by (conclude lemma_congruencetransitive).\nassert (BetS D B A) by (conclude axiom_betweennesssymmetry).\nassert (Lt A P D A) by (conclude_def Lt ).\nassert (Cong D A A D) by (conclude cn_equalityreverse).\nassert (Lt A P A D) by (conclude lemma_lessthancongruence).\nlet Tf:=fresh in\nassert (Tf:exists F, (BetS A F D /\\ Cong A F A P)) by (conclude_def Lt );destruct Tf as [F];spliter.\nassert (BetS E A D) by (conclude lemma_3_7b).\nassert (BetS E A F) by (conclude axiom_innertransitivity).\nassert (Cong A P A F) by (conclude lemma_congruencesymmetric).\nassert (eq P F) by (conclude lemma_extensionunique).\nassert (BetS A P D) by (conclude cn_equalitysub).\nassert (~ ~ BetS A B P).\n {\n intro.\n assert (eq B P) by (conclude axiom_connectivity).\n assert (neq B P) by (conclude lemma_inequalitysymmetric).\n contradict.\n }\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_ray.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6605845335770762}}
{"text": "Require Import ZFnats.\nRequire Import ZFpairs.\nRequire Import ZFstable.\n\nDefinition inl x := couple zero x.\nDefinition inr y := couple (succ zero) y.\nDefinition dest_sum p := snd p.\n\nInstance inl_morph : morph1 inl.\nunfold inl; do 2 red; intros.\nrewrite H; reflexivity.\nQed.\nInstance inr_morph : morph1 inr.\nunfold inr; do 2 red; intros.\nrewrite H; reflexivity.\nQed.\nInstance dest_sum_morph : morph1 dest_sum.\nProof snd_morph.\n\nLemma discr_sum : forall x y, ~ inl x == inr y.\nunfold inl, inr; red; intros.\napply (discr zero).\nrewrite <- (fst_def (succ zero) y).\nrewrite <- H.\nrewrite fst_def; reflexivity.\nQed.\n\nLemma dest_sum_inl : forall x, dest_sum (inl x) == x.\nunfold dest_sum, inl; intros.\napply snd_def.\nQed.\n\nLemma dest_sum_inr : forall y, dest_sum (inr y) == y.\nunfold dest_sum, inr; intros.\napply snd_def.\nQed.\n\nLemma inl_inj : forall x y, inl x == inl y -> x == y.\nintros.\nrewrite <- (dest_sum_inl x).\nrewrite <- (dest_sum_inl y).\nrewrite H; reflexivity.\nQed.\n\nLemma inr_inj : forall x y, inr x == inr y -> x == y.\nintros.\nrewrite <- (dest_sum_inr x).\nrewrite <- (dest_sum_inr y).\nrewrite H; reflexivity.\nQed.\n\nDefinition sum X Y :=\n  prodcart (singl zero) X ∪ prodcart (singl (succ zero)) Y.\n\nInstance sum_morph : morph2 sum.\ndo 3 red; unfold sum; intros.\nrewrite H; rewrite H0; reflexivity.\nQed.\n\nLemma sum_ind : forall X Y a (P:Prop),\n  (forall x, x ∈ X -> a == inl x -> P) ->\n  (forall y, y ∈ Y -> a == inr y -> P) ->\n  a ∈ sum X Y -> P.\nunfold sum, inl, inr; intros.\napply union2_elim in H1; destruct H1.\n apply H with (snd a).\n  apply snd_typ in H1; trivial.\n\n  setoid_replace zero with (fst a).\n   apply surj_pair with (1:=H1).\n\n   apply fst_typ in H1; apply singl_elim in H1; auto with *.\n\n apply H0 with (snd a).\n  apply snd_typ in H1; trivial.\n\n  setoid_replace (succ zero) with (fst a).\n   apply surj_pair with (1:=H1).\n\n   apply fst_typ in H1; apply singl_elim in H1; auto with *.\nQed.\n\nLemma inl_typ : forall X Y x, x ∈ X -> inl x ∈ sum X Y.\nunfold inl, sum; intros.\napply union2_intro1.\napply couple_intro; trivial.\napply singl_intro.\nQed.\n\nLemma inr_typ : forall X Y y, y ∈ Y -> inr y ∈ sum X Y.\nunfold inr, sum; intros.\napply union2_intro2.\napply couple_intro; trivial.\napply singl_intro.\nQed.\n\nLemma sum_mono : forall X X' Y Y',\n  X ⊆ X' -> Y ⊆ Y' -> sum X Y ⊆ sum X' Y'.\nred; intros.\nelim H1 using sum_ind; intros.\n rewrite H3.\n apply inl_typ; auto.\n\n rewrite H3.\n apply inr_typ; auto.\nQed.\n\nLemma sum_inv_l X Y x :\n  inl x ∈ sum X Y -> x ∈ X.\nintros.\napply sum_ind with (3:=H); intros.\n apply couple_injection in H1; destruct H1.\n rewrite H2; trivial.\n\n apply discr_sum in H1; contradiction.\nQed.\nLemma sum_inv_r X Y y :\n  inr y ∈ sum X Y -> y ∈ Y.\nintros.\napply sum_ind with (3:=H); intros.\n symmetry in H1; apply discr_sum in H1; contradiction.\n\n apply couple_injection in H1; destruct H1.\n rewrite H2; trivial.\nQed.\n\n  Definition sum_case f g x :=\n    cond_set (fst x == zero) (f (dest_sum x)) ∪\n    cond_set (fst x == succ zero) (g (dest_sum x)).\n\nLemma sum_case_inl0 : forall f g x,\n  (exists a, x == inl a) ->\n  sum_case f g x == f (dest_sum x).\nintros.\ndestruct H as (a,H).\nassert (fst x == zero).\n rewrite H; unfold inl; rewrite fst_def; reflexivity.\nunfold sum_case.\napply eq_intro; intros.\n apply union2_elim in H1; destruct H1; rewrite cond_set_ax in H1; destruct H1; trivial.\n rewrite H2 in H0; apply discr in H0; contradiction.\n\n apply union2_intro1.\n rewrite cond_set_ax; split; trivial.\nQed.\n\nLemma sum_case_inr0 : forall f g x,\n  (exists b, x == inr b) ->\n  sum_case f g x == g (dest_sum x).\nintros.\ndestruct H as (b,H).\nassert (fst x == succ zero).\n rewrite H; unfold inr; rewrite fst_def; reflexivity.\nunfold sum_case.\napply eq_intro; intros.\n apply union2_elim in H1; destruct H1; rewrite cond_set_ax in H1; destruct H1; trivial.\n rewrite H0 in H2; apply discr in H2; contradiction.\n\n apply union2_intro2.\n rewrite cond_set_ax; split; trivial.\nQed.\n\nLemma sum_case_ext : forall A1 A2 B1 B2 B1' B2',\n  eq_fun A1 B1 B1' ->\n  eq_fun A2 B2 B2' ->\n  eq_fun (sum A1 A2) (sum_case B1 B2) (sum_case B1' B2').\nred; intros.\napply sum_ind with (3:=H1); intros.\n rewrite sum_case_inl0.\n 2:exists x0; trivial.\n rewrite sum_case_inl0.\n 2:exists x0; rewrite <- H2; trivial.\n apply H.\n 2:rewrite H2; reflexivity.\n rewrite H4; rewrite dest_sum_inl; trivial.\n\n rewrite sum_case_inr0.\n 2:exists y; trivial.\n rewrite sum_case_inr0.\n 2:exists y; rewrite <- H2; trivial.\n apply H0.\n 2:rewrite H2; reflexivity.\n rewrite H4; rewrite dest_sum_inr; trivial.\nQed.\n\nInstance sum_case_morph : Proper\n  ((eq_set ==> eq_set) ==> (eq_set ==> eq_set) ==> eq_set ==> eq_set)\n  sum_case.\ndo 4 red; intros.\nunfold sum_case.\napply union2_morph; (apply cond_set_morph2; [rewrite H1; reflexivity|intros]).\n apply H; apply snd_morph; trivial.\n apply H0; apply snd_morph; trivial.\nQed.\n\nLemma sum_case_ind0 :\n  forall A B f g x (P:set->Prop),\n  Proper (eq_set ==> iff) P ->\n  x ∈ sum A B ->\n  (forall a, a ∈ A -> x == inl a -> P (f (dest_sum x))) ->\n  (forall b, b ∈ B -> x == inr b -> P (g (dest_sum x))) ->\n  P (sum_case f g x).\nintros.\napply sum_ind with (3:=H0); intros.\n rewrite sum_case_inl0; eauto.\n rewrite sum_case_inr0; eauto.\nQed.\n\n\nLemma sum_case_inl : forall f g a, morph1 f ->\n  sum_case f g (inl a) == f a.\nintros.\nrewrite sum_case_inl0.\n rewrite dest_sum_inl; reflexivity.\n\n exists a; reflexivity.\nQed.\n\nLemma sum_case_inr : forall f g b, morph1 g ->\n  sum_case f g (inr b) == g b.\nintros.\nrewrite sum_case_inr0.\n rewrite dest_sum_inr; reflexivity.\n\n exists b; reflexivity.\nQed.\n\nLemma sum_case_ind :\n  forall A B f g (P:set->Prop),\n  Proper (eq_set ==> iff) P ->\n  morph1 f ->\n  morph1 g ->\n  (forall a, a ∈ A -> P (f a)) ->\n  (forall b, b ∈ B -> P (g b)) ->\n  forall x,\n  x ∈ sum A B ->\n  P (sum_case f g x).\nintros.\napply sum_ind with (3:=H4); intros.\n rewrite H6.\n rewrite sum_case_inl; auto.\n\n rewrite H6.\n rewrite sum_case_inr; auto.\nQed.\n\n\nLemma sum_is_ext : forall o F G,\n  ext_fun o F ->\n  ext_fun o G ->\n  ext_fun o (fun y => sum (F y) (G y)).\ndo 2 red; intros.\nrewrite (H x x'); trivial.\nrewrite (H0 x x'); trivial.\nreflexivity.\nQed.\nHint Resolve sum_is_ext.\n\nLemma sum_stable_class K F G :\n  morph1 F ->\n  morph1 G ->\n  stable_class K F ->\n  stable_class K G ->\n  stable_class K (fun y => sum (F y) (G y)).\nintros Fm Gm Fs Gs.\nred; red ;intros.\ndestruct inter_wit with (2:=H0) as (w,winX).\n do 2 red; intros.\n rewrite H1; reflexivity.\nassert (forall x, x ∈ X -> z ∈ sum (F x) (G x)).\n intros.\n apply inter_elim with (1:=H0).\n rewrite replf_ax.\n  exists x; auto with *.\n\n  red; red; intros.\n  rewrite H3; reflexivity.\nclear H0.\nassert (z ∈ sum (F w) (G w)) by auto.\napply sum_ind with (3:=H0); intros.\n rewrite H3; apply inl_typ.\n apply Fs; eauto.\n apply inter_intro.\n  intros.\n  rewrite replf_ax in H4.\n  2:red;red;intros;apply Fm; trivial.\n  destruct H4.\n  rewrite H5; clear H5 y.\n  assert (z ∈ sum (F x0) (G x0)) by auto.\n  apply sum_ind with (3:=H5); intros.\n   rewrite H7 in H3; apply inl_inj in H3; rewrite <-H3; trivial.\n\n   rewrite H3 in H7; apply discr_sum in H7; contradiction.\n\n  exists (F w).\n  rewrite replf_ax.\n  2:red;red;intros;apply Fm;trivial.\n  exists w; auto with *.\n\n rewrite H3; apply inr_typ.\n apply Gs; eauto.\n apply inter_intro.\n  intros.\n  rewrite replf_ax in H4.\n  2:red;red;intros;apply Gm; trivial.\n  destruct H4.\n  rewrite H5; clear H5 y0.\n  assert (z ∈ sum (F x) (G x)) by auto.\n  apply sum_ind with (3:=H5); intros.\n   rewrite H7 in H3; apply discr_sum in H3; contradiction.\n\n   rewrite H7 in H3; apply inr_inj in H3; rewrite <-H3; trivial.\n\n  exists (G w).\n  rewrite replf_ax.\n  2:red;red;intros;apply Gm;trivial.\n  exists w; auto with *.\nQed.\n", "meta": {"author": "barras", "repo": "cic-model", "sha": "dcc38f3104048aa50d230f819085131b16702d3d", "save_path": "github-repos/coq/barras-cic-model", "path": "github-repos/coq/barras-cic-model/cic-model-dcc38f3104048aa50d230f819085131b16702d3d/ZFsum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6605845262674649}}
{"text": "(* Euler Product Formula *)\n(* https://en.wikipedia.org/wiki/Proof_of_the_Euler_product_formula_for_the_Riemann_zeta_function *)\n\nSet Nested Proofs Allowed.\nRequire Import Utf8 Arith Psatz Setoid Morphisms.\nRequire Import Sorting.Permutation SetoidList.\nImport List List.ListNotations.\nRequire Import Misc Primes.\n\n(* ζ(s) = Σ (n ∈ ℕ* ) 1/n^s = Π (p ∈ Primes) 1/(1-1/p^s) *)\n\n(* Here ζ is not applied to ℂ as usual, but to any field, whose\n   type is defined below; most of the theorems has a field f\n   as implicit first parameter.\n     And we have never to evaluate a value ζ(s) for a given s,\n   so the ζ function is just defined by the coefficients of\n   its terms. See type ln_series below. *)\n\nClass field :=\n  { f_type : Set;\n    f_zero : f_type;\n    f_one : f_type;\n    f_add : f_type → f_type → f_type;\n    f_mul : f_type → f_type → f_type;\n    f_opp : f_type → f_type;\n    f_inv : f_type → f_type;\n    f_add_comm : ∀ x y, f_add x y = f_add y x;\n    f_add_assoc : ∀ x y z, f_add x (f_add y z) = f_add (f_add x y) z;\n    f_add_0_l : ∀ x, f_add f_zero x = x;\n    f_add_opp_diag_l : ∀ x, f_add (f_opp x) x = f_zero;\n    f_mul_comm : ∀ x y, f_mul x y = f_mul y x;\n    f_mul_assoc : ∀ x y z, f_mul x (f_mul y z) = f_mul (f_mul x y) z;\n    f_mul_1_l : ∀ x, f_mul f_one x = x;\n    f_mul_inv_diag_l : ∀ x, x ≠ f_zero → f_mul (f_inv x) x = f_one;\n    f_mul_add_distr_l : ∀ x y z,\n      f_mul x (f_add y z) = f_add (f_mul x y) (f_mul x z) }.\n\nDeclare Scope field_scope.\nDelimit Scope field_scope with F.\n\nDefinition f_sub {F : field} x y := f_add x (f_opp y).\n\nNotation \"- x\" := (f_opp x) : field_scope.\nNotation \"x + y\" := (f_add x y) : field_scope.\nNotation \"x - y\" := (f_sub x y) : field_scope.\nNotation \"x * y\" := (f_mul x y) : field_scope.\nNotation \"0\" := (f_zero) : field_scope.\nNotation \"1\" := (f_one) : field_scope.\n\nTheorem f_add_0_r {F : field} : ∀ x, (x + 0)%F = x.\nProof.\nintros.\nrewrite f_add_comm.\napply f_add_0_l.\nQed.\n\nTheorem f_opp_0 {F : field} : (- 0)%F = 0%F.\nProof.\nrewrite <- (f_add_0_r (- 0)%F).\napply f_add_opp_diag_l.\nQed.\n\nTheorem f_add_opp_diag_r {F : field} : ∀ x, (x + - x = 0)%F.\nProof.\nintros.\nrewrite f_add_comm.\napply f_add_opp_diag_l.\nQed.\n\nTheorem f_add_sub {F : field} : ∀ x y, (x + y - y)%F = x.\nProof.\nintros.\nunfold f_sub.\nrewrite <- f_add_assoc.\nrewrite f_add_opp_diag_r.\nnow rewrite f_add_0_r.\nQed.\n\nTheorem f_add_move_r {F : field} : ∀ x y z, (x + y)%F = z ↔ x = (z - y)%F.\nProof.\nintros.\nsplit.\n-intros H.\n rewrite <- H.\n now rewrite f_add_sub.\n-intros H.\n rewrite H.\n unfold f_sub.\n rewrite <- f_add_assoc.\n rewrite f_add_opp_diag_l.\n now rewrite f_add_0_r.\nQed.\n\nTheorem f_add_move_0_r {F : field} : ∀ x y, (x + y = 0)%F ↔ x = (- y)%F.\nProof.\nintros.\nsplit.\n-intros H.\n apply f_add_move_r in H.\n unfold f_sub in H.\n now rewrite f_add_0_l in H.\n-intros H.\n apply f_add_move_r.\n unfold f_sub.\n now rewrite f_add_0_l.\nQed.\n\nTheorem f_add_add_swap {F : field} : ∀ x y z, (x + y + z = x + z + y)%F.\nProof.\nintros.\ndo 2 rewrite <- f_add_assoc.\napply f_equal, f_add_comm.\nQed.\n\nTheorem f_mul_mul_swap {F : field} : ∀ x y z, (x * y * z = x * z * y)%F.\nProof.\nintros.\ndo 2 rewrite <- f_mul_assoc.\napply f_equal, f_mul_comm.\nQed.\n\nTheorem f_opp_involutive {F : field} : ∀ x, (- - x)%F = x.\nProof.\nintros.\nsymmetry.\napply f_add_move_0_r.\napply f_add_opp_diag_r.\nQed.\n\nTheorem f_mul_add_distr_r {F : field} : ∀ x y z,\n  ((x + y) * z)%F = (x * z + y * z)%F.\nProof.\nintros.\nrewrite f_mul_comm, f_mul_add_distr_l.\nnow do 2 rewrite (f_mul_comm z).\nQed.\n\nTheorem f_mul_0_l {F : field} : ∀ x, (0 * x = 0)%F.\nProof.\nintros.\nassert (H : (0 * x + x = x)%F). {\n  transitivity ((0 * x + 1 * x)%F).\n  -now rewrite f_mul_1_l.\n  -rewrite <- f_mul_add_distr_r.\n   now rewrite f_add_0_l, f_mul_1_l.\n}\napply f_add_move_r in H.\nunfold f_sub in H.\nnow rewrite f_add_opp_diag_r in H.\nQed.\n\nTheorem f_mul_0_r {F : field} : ∀ x, (x * 0 = 0)%F.\nProof.\nintros.\nrewrite f_mul_comm.\napply f_mul_0_l.\nQed.\n\nTheorem f_eq_mul_0_l {F : field} : ∀ x y,\n  (x * y = 0)%F → y ≠ 0%F → x = 0%F.\nProof.\nintros * Hxy Hy.\nrewrite f_mul_comm in Hxy.\napply (f_equal (f_mul (f_inv y))) in Hxy.\nrewrite f_mul_0_r, f_mul_assoc in Hxy.\nrewrite f_mul_inv_diag_l in Hxy; [ | easy ].\nnow rewrite f_mul_1_l in Hxy.\nQed.\n\nTheorem f_mul_opp_l {F : field} : ∀ x y, (- x * y = - (x * y))%F.\nProof.\nintros.\napply f_add_move_0_r.\nrewrite <- f_mul_add_distr_r.\nrewrite f_add_opp_diag_l.\napply f_mul_0_l.\nQed.\n\nTheorem f_mul_opp_r {F : field} : ∀ x y, (x * - y = - (x * y))%F.\nProof.\nintros.\nnow rewrite f_mul_comm, f_mul_opp_l, f_mul_comm.\nQed.\n\nTheorem f_mul_1_r {F : field} : ∀ x, (x * 1)%F = x.\nProof.\nintros.\nrewrite f_mul_comm.\napply f_mul_1_l.\nQed.\n\n(* Euler product formula *)\n\n(*\nRiemann zeta function is\n   ζ(s) = 1 + 1/2^s + 1/3^s + 1/4^s + 1/5^s + ...\n\nEuler product formula is the fact that\n                    1\n   ζ(s) = -----------------------------------------------\n          (1-1/2^s) (1-1/3^s) (1-1/5^s) ... (1-1/p^s) ...\n\nwhere the product in the denominator applies on all prime numbers\nand only them.\n\nThe proof is the following.\n\nWe first prove that\n   ζ(s) (1-1/2^s) = 1 + 1/3^s + 1/5^s + 1/7^s + ...\n\ni.e. all terms but the multiples of 2\ni.e. all odd numbers\n\n(this is easy to verify on a paper)\n\nThen we continue by proving\n   ζ(s) (1-1/2^s) (1-1/3^s) =\n       1 + 1/5^s + 1/7^s + 1/11^s + ... + 1/23^s + 1/25^s + ...\n\ni.e. all terms but the multiples of 2 and 3\n\nThen we do it for the number 5 in the second term (1/5^s) of the series.\n\nThis number in the second term is always the next prime number, like in the\nSieve of Eratosthenes.\n\nUp to prime number p, we have, using commutativity\n  ζ(s) (1-1/2^s) (1-1/3^s) ... (1-1/p^s) = 1 + 1/q^s + ...\n\nwhere q is the prime number after p and the rest holds terms whose\nnumber is greater than q and not divisible by the primes between\n2 and p.\n\nWhen p tends towards infinity, the term to the right is just 1\nand we get Euler's formula.\n\n    ---\n\nImplementation.\n\nζ(s) and all the expressions above are actually of the form\n    a₁ + a₂/2^s + a₃/3^s + a₄/4^s + ...\n\nWe can represent them by the sequence\n    (a_n) = (a₁, a₂, a₃, ...)\n\nFor example, ζ is (1, 1, 1, 1, ...)\nand (1-1/3^s) is (1, 0, -1, 0, 0, 0, ...)\n\nWe call them \"series with logarithm powers\" because they can be\nwritten\n    a₁ + a₂ x^ln(2) + a₃ x^ln(3) + a₄ x^ln(4) + a₅ x^ln(5) + ...\n\nwith x = e^(-s). Easy to verify.\n\nNote that we do not consider the parameters s or x. The fact that\nthey are supposed to be complex number is irrelevant in this proof.\nWe just consider they belong to a field (type \"field\" defined\nabove).\n*)\n\n(* Definition of the type of such a series; a value s of this\n   type is a function ls : nat → field representing the series\n       ls(1) + ls(2)/2^s + ls(3)/3^s + ls(4)/4^s + ...\n   or the equivalent form with x at a logarithm power\n       ls(1) + ls(2).x^ln(2) + ls(3).x^ln(3) + ls(4).x^ln(4)+...\n   where x = e^(-s)\n *)\n\nClass ln_series {F : field} :=\n  { ls : nat → f_type }.\n\n(* Definition of the type of a polynomial: this is just\n   a finite series; it can be represented by a list *)\n\nClass ln_polyn {F : field} :=\n  { lp : list f_type }.\n\n(* Syntactic scopes, allowing to use operations on series and\n   polynomials with usual mathematical forms. For example we can\n   write e.g.\n        (s1 * s2 + s3)%LS\n   instead of the less readable\n        ls_add (ls_mul s1 s2) s3\n*)\n\nDeclare Scope ls_scope.\nDelimit Scope ls_scope with LS.\n\nDeclare Scope lp_scope.\nDelimit Scope lp_scope with LP.\n\nArguments ls {_} _%LS _%nat.\nArguments lp {_}.\n\n(* Equality between series; since these series start with 1, the\n   comparison is only on natural indices different from 0 *)\n\nDefinition ls_eq {F : field} s1 s2 := ∀ n, n ≠ 0 → ls s1 n = ls s2 n.\nArguments ls_eq _ s1%LS s2%LS.\n\n(* which is an equivalence relation *)\n\nTheorem ls_eq_refl {F : field} : reflexive _ ls_eq.\nProof. easy. Qed.\n\nTheorem ls_eq_sym {F : field} : symmetric _ ls_eq.\nProof.\nintros x y Hxy i Hi.\nnow symmetry; apply Hxy.\nQed.\n\nTheorem ls_eq_trans {F : field} : transitive _ ls_eq.\nProof.\nintros x y z Hxy Hyz i Hi.\nnow eapply eq_trans; [ apply Hxy | apply Hyz ].\nQed.\n\nAdd Parametric Relation {F : field} : (ln_series) ls_eq\n reflexivity proved by ls_eq_refl\n symmetry proved by ls_eq_sym\n transitivity proved by ls_eq_trans\n as ls_eq_rel.\n\n(* The unit series: 1 + 0/2^s + 0/3^s + 0/4^s + ... *)\n\nDefinition ls_one {F : field} :=\n  {| ls n := match n with 1 => 1%F | _ => 0%F end |}.\n\n(* Notation for accessing a series coefficient at index i *)\n\nNotation \"r ~{ i }\" := (ls r i) (at level 1, format \"r ~{ i }\").\n\n(* adding, opposing, subtracting polynomials *)\n\nDefinition lp_add {F : field} p q :=\n  {| lp :=\n       List.map (prod_curry f_add) (List_combine_all (lp p) (lp q) 0%F) |}.\nDefinition lp_opp {F : field} p := {| lp := List.map f_opp (lp p) |}.\nDefinition lp_sub {F : field} p q := lp_add p (lp_opp q).\n\nNotation \"x - y\" := (lp_sub x y) : lp_scope.\nNotation \"1\" := (ls_one) : ls_scope.\n\n(* At last, the famous ζ function: all its coefficients are 1 *)\n\nDefinition ζ {F : field} := {| ls _ := 1%F |}.\n\n(* Series where the indices, which are multiple of some n, are 0\n      1 + ls(2)/2^s + ls(3)/3^s + ... + ls(n-1)/(n-1)^s + 0/n^s +\n      ... + ls(ni-1)/(ni-1)^s + 0/ni^s + ls(ni+1)/(ni+1)^s + ...\n   This special series allows to cumulate the multiplications of\n   terms of the form (1-1/p^s); when doing (1-1/p^s).ζ, the result\n   is ζ without all terms multiple of p *)\n\nDefinition series_but_mul_of {F : field} n s :=\n  {| ls i :=\n       match i mod n with\n       | 0 => 0%F\n       | _ => ls s i\n       end |}.\n\n(* product of series is like the convolution product but\n   limited to divisors; indeed the coefficient of the term\n   in x^ln(n), resulting of the multiplication of two series\n   u and v, is the sum:\n      u_1.v_n + ... u_d.v_{n/d} + ... u_n.v_1\n   where d covers all the divisors of n *)\n\nDefinition log_prod_term {F : field} u v n i :=\n  (u i * v (n / i))%F.\n\nDefinition log_prod_list {F : field} u v n :=\n  List.map (log_prod_term u v n) (divisors n).\n\nDefinition log_prod {F : field} u v n :=\n  List.fold_left f_add (log_prod_list u v n) 0%F.\n\n(* Σ (i = 1, ∞) s1_i x^ln(i) * Σ (i = 1, ∞) s2_i x^ln(i) *)\nDefinition ls_mul {F : field} s1 s2 :=\n  {| ls := log_prod (ls s1) (ls s2) |}.\n\n(* polynomial seen as a series *)\n\nDefinition ls_of_pol {F : field} p :=\n  {| ls n :=\n       match n with\n       | 0 => 0%F\n       | S n' => List.nth n' (lp p) 0%F end |}.\n\nDefinition ls_pol_mul_r {F : field} s p :=\n  ls_mul s (ls_of_pol p).\n\nArguments ls_of_pol _ p%LP.\nArguments ls_pol_mul_r _ s%LS p%LP.\n\nNotation \"x = y\" := (ls_eq x y) : ls_scope.\nNotation \"x * y\" := (ls_mul x y) : ls_scope.\nNotation \"s *' p\" := (ls_pol_mul_r s p) (at level 41, left associativity) :\n   ls_scope.\n\nTheorem in_divisors : ∀ n,\n  n ≠ 0 → ∀ d, d ∈ divisors n → n mod d = 0 ∧ d ≠ 0.\nProof.\nintros * Hn *.\nunfold divisors.\nintros Hd.\napply filter_In in Hd.\ndestruct Hd as (Hd, Hnd).\nsplit; [ now apply Nat.eqb_eq | ].\napply in_seq in Hd; flia Hd.\nQed.\n\nTheorem in_divisors_iff : ∀ n,\n  n ≠ 0 → ∀ d, d ∈ divisors n ↔ n mod d = 0 ∧ d ≠ 0.\nProof.\nintros * Hn *.\nunfold divisors.\nsplit; [ now apply in_divisors | ].\nintros (Hnd, Hd).\napply filter_In.\nsplit; [ | now apply Nat.eqb_eq ].\napply in_seq.\nsplit; [ flia Hd | ].\napply Nat.mod_divides in Hnd; [ | easy ].\ndestruct Hnd as (c, Hc).\nrewrite Nat.mul_comm in Hc; rewrite Hc.\ndestruct c; [ easy | ].\ncbn; flia.\nQed.\n\nTheorem divisor_inv : ∀ n d, d ∈ divisors n → n / d ∈ divisors n.\nProof.\nintros * Hd.\napply List.filter_In in Hd.\napply List.filter_In.\ndestruct Hd as (Hd, Hm).\napply List.in_seq in Hd.\napply Nat.eqb_eq in Hm.\nrewrite Nat_mod_0_mod_div; [ | flia Hd | easy ].\nsplit; [ | easy ].\napply Nat.mod_divides in Hm; [ | flia Hd ].\ndestruct Hm as (m, Hm).\nrewrite Hm at 1.\napply List.in_seq.\nrewrite Nat.mul_comm, Nat.div_mul; [ | flia Hd ].\nsplit.\n+apply (Nat.mul_lt_mono_pos_l d); [ flia Hd | ].\n flia Hm Hd.\n+rewrite Hm.\n destruct d; [ flia Hd | cbn; flia ].\nQed.\n\n(* allows to rewrite H1, H2 with\n      H1 : s1 = s3\n      H2 : s2 = s4\n   in expression\n      (s1 * s2)%LS\n   changing it into\n      (s3 * s4)%LS *)\nLocal Instance ls_mul_morph {F : field} :\n  Proper (ls_eq ==> ls_eq ==> ls_eq) ls_mul.\nProof.\nintros s1 s2 Hs12 s'1 s'2 Hs'12 n Hn.\ncbn - [ log_prod ].\nunfold log_prod, log_prod_list; f_equal.\nspecialize (in_divisors n Hn) as Hd.\nremember (divisors n) as l eqn:Hl; clear Hl.\ninduction l as [| a l]; [ easy | cbn ].\nrewrite IHl; [ | now intros d Hdl; apply Hd; right ].\nf_equal.\nunfold log_prod_term.\nspecialize (Hd a (or_introl eq_refl)) as Ha.\ndestruct Ha as (Hna, Ha).\nrewrite Hs12; [ | easy ].\nrewrite Hs'12; [ easy | ].\napply Nat.mod_divides in Hna; [ | easy ].\ndestruct Hna as (c, Hc).\nrewrite Hc, Nat.mul_comm, Nat.div_mul; [ | easy ].\nnow intros H; rewrite Hc, H, Nat.mul_0_r in Hn.\nQed.\n\nTheorem divisors_are_sorted : ∀ n, Sorted.Sorted lt (divisors n).\nProof.\nintros.\nunfold divisors.\nspecialize (SetoidList.filter_sort eq_equivalence Nat.lt_strorder) as H2.\nspecialize (H2 Nat.lt_wd).\nspecialize (H2 (λ a, n mod a =? 0) (seq 1 n)).\nnow specialize (H2 (Sorted_Sorted_seq _ _)).\nQed.\n\nTheorem sorted_gt_lt_rev : ∀ l, Sorted.Sorted gt l → Sorted.Sorted lt (rev l).\nProof.\nintros l Hl.\ninduction l as [| a l]; [ constructor | cbn ].\napply (SetoidList.SortA_app eq_equivalence).\n-now apply IHl; inversion Hl.\n-now constructor.\n-intros x y Hx Hy.\n apply SetoidList.InA_alt in Hy.\n destruct Hy as (z & Haz & Hza); subst z.\n destruct Hza; [ subst a | easy ].\n apply SetoidList.InA_rev in Hx.\n rewrite List.rev_involutive in Hx.\n apply SetoidList.InA_alt in Hx.\n destruct Hx as (z & Haz & Hza); subst z.\n apply Sorted.Sorted_inv in Hl.\n destruct Hl as (Hl, Hyl).\n clear IHl.\n induction Hyl; [ easy | ].\n destruct Hza as [Hx| Hx]; [ now subst x | ].\n transitivity b; [ clear H | easy ].\n assert (Hgtt : Relations_1.Transitive gt). {\n   unfold gt.\n   clear; intros x y z Hxy Hyz.\n   now transitivity y.\n }\n apply Sorted.Sorted_StronglySorted in Hl; [ | easy ].\n inversion Hl; subst.\n specialize (proj1 (Forall_forall (gt b) l) H2) as H3.\n now apply H3.\nQed.\n\nTheorem sorted_equiv_nat_lists : ∀ l l',\n  Sorted.Sorted lt l\n  → Sorted.Sorted lt l'\n  → (∀ a, a ∈ l ↔ a ∈ l')\n  → l = l'.\nProof.\nintros * Hl Hl' Hll.\nrevert l' Hl' Hll.\ninduction l as [| a l]; intros. {\n  destruct l' as [| a' l']; [ easy | ].\n  now specialize (proj2 (Hll a') (or_introl eq_refl)) as H1.\n}\ndestruct l' as [| a' l']. {\n  now specialize (proj1 (Hll a) (or_introl eq_refl)) as H1.\n}\nassert (Hltt : Relations_1.Transitive lt). {\n  intros x y z Hxy Hyz.\n  now transitivity y.\n}\nassert (Haa : a = a'). {\n  specialize (proj1 (Hll a) (or_introl eq_refl)) as H1.\n  destruct H1 as [H1| H1]; [ easy | ].\n  specialize (proj2 (Hll a') (or_introl eq_refl)) as H2.\n  destruct H2 as [H2| H2]; [ easy | ].\n  apply Sorted.Sorted_StronglySorted in Hl; [ | easy ].\n  apply Sorted.Sorted_StronglySorted in Hl'; [ | easy ].\n  inversion Hl; subst.\n  inversion Hl'; subst.\n  specialize (proj1 (Forall_forall (lt a) l) H4) as H7.\n  specialize (proj1 (Forall_forall (lt a') l') H6) as H8.\n  specialize (H7 _ H2).\n  specialize (H8 _ H1).\n  flia H7 H8.\n}\nsubst a; f_equal.\napply IHl.\n-now apply Sorted.Sorted_inv in Hl.\n-now apply Sorted.Sorted_inv in Hl'.\n-intros a; split; intros Ha.\n +specialize (proj1 (Hll _) (or_intror Ha)) as H1.\n  destruct H1 as [H1| H1]; [ | easy ].\n  subst a'.\n  apply Sorted.Sorted_StronglySorted in Hl; [ | easy ].\n  inversion Hl; subst.\n  specialize (proj1 (Forall_forall (lt a) l) H2) as H3.\n  specialize (H3 _ Ha); flia H3.\n +specialize (proj2 (Hll _) (or_intror Ha)) as H1.\n  destruct H1 as [H1| H1]; [ | easy ].\n  subst a'.\n  apply Sorted.Sorted_StronglySorted in Hl'; [ | easy ].\n  inversion Hl'; subst.\n  specialize (proj1 (Forall_forall (lt a) l') H2) as H3.\n  specialize (H3 _ Ha); flia H3.\nQed.\n\nTheorem map_inv_divisors : ∀ n,\n  divisors n = List.rev (List.map (λ i, n / i) (divisors n)).\nProof.\nintros.\nspecialize (divisors_are_sorted n) as H1.\nassert (H2 : Sorted.Sorted lt (rev (map (λ i : nat, n / i) (divisors n)))). {\n  apply sorted_gt_lt_rev.\n  destruct n; [ constructor | ].\n  specialize (in_divisors (S n) (Nat.neq_succ_0 _)) as H2.\n  remember (divisors (S n)) as l eqn:Hl; symmetry in Hl.\n  clear Hl.\n  induction l as [| a l]; [ constructor | ].\n  cbn; constructor.\n  -apply IHl; [ now inversion H1 | ].\n   now intros d; intros Hd; apply H2; right.\n  -clear IHl.\n   revert a H1 H2.\n   induction l as [| b l]; intros; [ constructor | ].\n   cbn; constructor; unfold gt.\n   apply Sorted.Sorted_inv in H1.\n   destruct H1 as (_, H1).\n   apply Sorted.HdRel_inv in H1.\n   assert (Ha : a ≠ 0). {\n     intros H; subst a.\n     now specialize (H2 0 (or_introl eq_refl)) as H3.\n   }\n   assert (Hb : b ≠ 0). {\n     intros H; subst b.\n     now specialize (H2 0 (or_intror (or_introl eq_refl))) as H3.\n   }\n   specialize (Nat.div_mod (S n) a Ha) as H3.\n   specialize (Nat.div_mod (S n) b Hb) as H4.\n   specialize (H2 a (or_introl eq_refl)) as H.\n   rewrite (proj1 H), Nat.add_0_r in H3; clear H.\n   specialize (H2 b (or_intror (or_introl eq_refl))) as H.\n   rewrite (proj1 H), Nat.add_0_r in H4; clear H.\n   apply (Nat.mul_lt_mono_pos_l b); [ flia Hb | ].\n   rewrite <- H4.\n   apply (Nat.mul_lt_mono_pos_l a); [ flia Ha | ].\n   rewrite (Nat.mul_comm _ (_ * _)), Nat.mul_shuffle0.\n   rewrite <- Nat.mul_assoc, <- H3.\n   apply Nat.mul_lt_mono_pos_r; [ flia | easy ].\n}\napply sorted_equiv_nat_lists; [ easy | easy | ].\nintros a.\nsplit; intros Ha.\n-apply List.in_rev; rewrite List.rev_involutive.\n destruct (zerop n) as [Hn| Hn]; [ now subst n | ].\n apply Nat.neq_0_lt_0 in Hn.\n specialize (in_divisors n Hn a Ha) as (Hna, Haz).\n apply List.in_map_iff.\n exists (n / a).\n split; [ | now apply divisor_inv ].\n apply Nat_mod_0_div_div; [ | easy ].\n split; [ flia Haz | ].\n apply Nat.mod_divides in Hna; [ | easy ].\n destruct Hna as (c, Hc); subst n.\n destruct c; [ now rewrite Nat.mul_comm in Hn | ].\n rewrite Nat.mul_comm; cbn; flia.\n-apply List.in_rev in Ha.\n destruct (zerop n) as [Hn| Hn]; [ now subst n | ].\n apply Nat.neq_0_lt_0 in Hn.\n apply in_divisors_iff; [ easy | ].\n apply List.in_map_iff in Ha.\n destruct Ha as (b & Hnb & Hb).\n subst a.\n apply in_divisors; [ easy | ].\n now apply divisor_inv.\nQed.\n\n(* Commutativity of product of series *)\n\nTheorem fold_f_add_assoc {F : field} : ∀ a b l,\n  fold_left f_add l (a + b)%F = (fold_left f_add l a + b)%F.\nProof.\nintros.\nrevert a.\ninduction l as [| c l]; intros; [ easy | cbn ].\nrewrite <- IHl; f_equal.\napply f_add_add_swap.\nQed.\n\nTheorem fold_f_mul_assoc {F : field} : ∀ a b l,\n  fold_left f_mul l (a * b)%F = (fold_left f_mul l a * b)%F.\nProof.\nintros.\nrevert a.\ninduction l as [| c l]; intros; [ easy | cbn ].\nrewrite <- IHl; f_equal.\napply f_mul_mul_swap.\nQed.\n\nTheorem fold_log_prod_add_on_rev {F : field} : ∀ u v n l,\n  n ≠ 0\n  → (∀ d, d ∈ l → n mod d = 0 ∧ d ≠ 0)\n  → fold_left f_add (map (log_prod_term u v n) l) f_zero =\n     fold_left f_add (map (log_prod_term v u n) (rev (map (λ i, n / i) l)))\n       f_zero.\nProof.\nintros * Hn Hd.\ninduction l as [| a l]; intros; [ easy | cbn ].\nrewrite f_add_0_l.\nrewrite List.map_app.\nrewrite List.fold_left_app; cbn.\nspecialize (Hd a (or_introl eq_refl)) as H1.\ndestruct H1 as (H1, H2).\nrewrite <- IHl.\n-unfold log_prod_term at 2 4.\n rewrite Nat_mod_0_div_div; [ | | easy ]; cycle 1. {\n   split; [ flia H2 | ].\n   apply Nat.mod_divides in H1; [ | easy ].\n   destruct H1 as (c, Hc).\n   destruct c; [ now rewrite Nat.mul_comm in Hc | ].\n   rewrite Hc, Nat.mul_comm; cbn; flia.\n }\n rewrite (f_mul_comm (v (n / a))).\n now rewrite <- fold_f_add_assoc, f_add_0_l.\n-intros d Hdl.\n now apply Hd; right.\nQed.\n\nTheorem fold_log_prod_comm {F : field} : ∀ u v i,\n  fold_left f_add (log_prod_list u v i) f_zero =\n  fold_left f_add (log_prod_list v u i) f_zero.\nProof.\nintros u v n.\nunfold log_prod_list.\nrewrite map_inv_divisors at 2.\nremember (divisors n) as l eqn:Hl; symmetry in Hl.\ndestruct (zerop n) as [Hn| Hn]; [ now subst n; cbn in Hl; subst l | ].\napply Nat.neq_0_lt_0 in Hn.\nspecialize (in_divisors n Hn) as Hd; rewrite Hl in Hd.\nnow apply fold_log_prod_add_on_rev.\nQed.\n\nTheorem ls_mul_comm {F : field} : ∀ x y,\n  (x * y = y * x)%LS.\nProof.\nintros * i Hi.\ncbn - [ log_prod ].\napply fold_log_prod_comm.\nQed.\n\n(* *)\n\nTheorem f_mul_fold_add_distr_l {F : field} : ∀ a b l,\n  (a * fold_left f_add l b)%F =\n  (fold_left f_add (map (f_mul a) l) (a * b)%F).\nProof.\nintros.\nrevert a b.\ninduction l as [| c l]; intros; [ easy | cbn ].\nrewrite <- f_mul_add_distr_l.\napply IHl.\nQed.\n\nTheorem f_mul_fold_add_distr_r {F : field} : ∀ a b l,\n  (fold_left f_add l a * b)%F =\n  (fold_left f_add (map (f_mul b) l) (a * b)%F).\nProof.\nintros.\nrevert a b.\ninduction l as [| c l]; intros; [ easy | cbn ].\nrewrite (f_mul_comm b).\nrewrite <- f_mul_add_distr_r.\napply IHl.\nQed.\n\nTheorem map_f_mul_fold_add_distr_l {F : field} : ∀ (a : nat → f_type) b f l,\n  map (λ i, (a i * fold_left f_add (f i) b)%F) l =\n  map (λ i, fold_left f_add (map (f_mul (a i)) (f i)) (a i * b)%F) l.\nProof.\nintros a b.\ninduction l as [| c l]; [ easy | cbn ].\nrewrite f_mul_fold_add_distr_l; f_equal.\napply IHl.\nQed.\n\nTheorem map_f_mul_fold_add_distr_r {F : field} : ∀ a (b : nat → f_type) f l,\n  map (λ i, (fold_left f_add (f i) a * b i)%F) l =\n  map (λ i, fold_left f_add (map (f_mul (b i)) (f i)) (a * b i)%F) l.\nProof.\nintros a b.\ninduction l as [| c l]; [ easy | cbn ].\nrewrite f_mul_fold_add_distr_r; f_equal.\napply IHl.\nQed.\n\n(* The product of series is associative; first, lemmas *)\n\nDefinition compare_trip '(i1, j1, k1) '(i2, j2, k2) :=\n  match Nat.compare i1 i2 with\n  | Eq =>\n      match Nat.compare j1 j2 with\n      | Eq => Nat.compare k1 k2\n      | c => c\n      end\n  | c => c\n  end.\nDefinition lt_triplet t1 t2 := compare_trip t1 t2 = Lt.\n\nDefinition xyz_zxy '((x, y, z) : (nat * nat * nat)) := (z, x, y).\n\nTheorem map_mul_triplet {F : field} : ∀ u v w (f g h : nat → nat → nat) k l a,\n  fold_left f_add\n    (flat_map\n       (λ d, map (λ d', (u (f d d') * v (g d d') * w (h d d')))%F (k d)) l)\n    a =\n  fold_left f_add\n    (map (λ t, let '(i, j, k) := t in (u i * v j * w k)%F)\n      (flat_map\n         (λ d, map (λ d', (f d d', g d d', h d d')) (k d)) l))\n    a.\nProof.\nintros.\nrevert a.\ninduction l as [| b l]; intros; [ easy | cbn ].\nrewrite map_app.\ndo 2 rewrite fold_left_app.\nrewrite IHl; f_equal; clear.\nremember (k b) as l eqn:Hl; clear Hl.\nrevert a b.\ninduction l as [| c l]; intros; [ easy | cbn ].\napply IHl.\nQed.\n\nTheorem StrictOrder_lt_triplet : StrictOrder lt_triplet.\nProof.\nconstructor.\n-intros ((i, j), k) H.\n unfold lt_triplet, compare_trip in H.\n now do 3 rewrite Nat.compare_refl in H.\n-unfold lt_triplet, compare_trip.\n intros ((a1, a2), a3) ((b1, b2), b3) ((c1, c2), c3) Hab Hbc.\n remember (a1 ?= b1) as ab1 eqn:Hab1; symmetry in Hab1.\n remember (a1 ?= c1) as ac1 eqn:Hac1; symmetry in Hac1.\n remember (b1 ?= c1) as bc1 eqn:Hbc1; symmetry in Hbc1.\n remember (a2 ?= b2) as ab2 eqn:Hab2; symmetry in Hab2.\n remember (b2 ?= c2) as bc2 eqn:Hbc2; symmetry in Hbc2.\n remember (a2 ?= c2) as ac2 eqn:Hac2; symmetry in Hac2.\n move ac2 before ab1; move bc2 before ab1; move ab2 before ab1.\n move bc1 before ab1; move ac1 before ab1.\n destruct ab1; [ | | easy ].\n +apply Nat.compare_eq_iff in Hab1; subst b1.\n  destruct ab2; [ | | easy ].\n  *apply Nat.compare_eq_iff in Hab2; subst b2.\n   apply Nat.compare_lt_iff in Hab.\n   destruct bc1; [ | | easy ].\n  --apply Nat.compare_eq_iff in Hbc1; subst c1.\n    rewrite <- Hac1, Nat.compare_refl.\n    destruct bc2; [ | | easy ].\n   ++apply Nat.compare_eq_iff in Hbc2; subst c2.\n     apply Nat.compare_lt_iff in Hbc.\n     rewrite <- Hac2, Nat.compare_refl.\n     apply Nat.compare_lt_iff.\n     now transitivity b3.\n   ++apply Nat.compare_lt_iff in Hbc2.\n     destruct ac2; [ | easy | ].\n    **apply Nat.compare_eq_iff in Hac2; subst c2.\n      flia Hbc2.\n    **apply Nat.compare_gt_iff in Hac2.\n      flia Hbc2 Hac2.\n  --apply Nat.compare_lt_iff in Hbc1.\n    destruct ac1; [ | easy | ].\n   **apply Nat.compare_eq_iff in Hac1; flia Hbc1 Hac1.\n   **apply Nat.compare_gt_iff in Hac1; flia Hbc1 Hac1.\n  *destruct bc1; [ | | easy ].\n  --apply Nat.compare_eq_iff in Hbc1; subst c1.\n    destruct bc2; [ | | easy ].\n   ++apply Nat.compare_eq_iff in Hbc2; subst c2.\n     rewrite <- Hac2, Hab2.\n     destruct ac1; [ easy | easy | ].\n     now rewrite Nat.compare_refl in Hac1.\n   ++apply Nat.compare_lt_iff in Hab2.\n     apply Nat.compare_lt_iff in Hbc2.\n     destruct ac1; [ | easy | ].\n    **destruct ac2; [ | easy | ].\n    ---apply Nat.compare_eq_iff in Hac2; subst c2.\n       flia Hab2 Hbc2.\n    ---apply Nat.compare_gt_iff in Hac2.\n       flia Hab2 Hbc2 Hac2.\n    **now rewrite Nat.compare_refl in Hac1.\n  --now rewrite <- Hac1, Hbc1.\n +destruct ac1; [ | easy | ].\n  *apply Nat.compare_eq_iff in Hac1; subst c1.\n   destruct ac2; [ | easy | ].\n  --apply Nat.compare_eq_iff in Hac2; subst c2.\n    destruct bc1; [ | | easy ].\n   ++apply Nat.compare_eq_iff in Hbc1; subst b1.\n     now rewrite Nat.compare_refl in Hab1.\n   ++apply Nat.compare_lt_iff in Hab1.\n     apply Nat.compare_lt_iff in Hbc1.\n     flia Hab1 Hbc1.\n  --destruct bc1; [ | | easy ].\n   ++apply Nat.compare_eq_iff in Hbc1; subst b1.\n     now rewrite Nat.compare_refl in Hab1.\n   ++apply Nat.compare_lt_iff in Hab1.\n     apply Nat.compare_lt_iff in Hbc1.\n     flia Hab1 Hbc1.\n  *destruct bc1; [ | | easy ].\n  --apply Nat.compare_eq_iff in Hbc1; subst c1.\n    now rewrite Hac1 in Hab1.\n  --apply Nat.compare_lt_iff in Hab1.\n    apply Nat.compare_lt_iff in Hbc1.\n    apply Nat.compare_gt_iff in Hac1.\n    flia Hab1 Hbc1 Hac1.\nQed.\n\nTheorem mul_assoc_indices_eq : ∀ n,\n  flat_map (λ d, map (λ d', (d, d', n / d / d')) (divisors (n / d))) (divisors n) =\n  map xyz_zxy (flat_map (λ d, map (λ d', (d', d / d', n / d)) (divisors d)) (rev (divisors n))).\nProof.\nintros.\ndestruct (zerop n) as [Hn| Hn]; [ now rewrite Hn | ].\napply Nat.neq_0_lt_0 in Hn.\ndo 2 rewrite flat_map_concat_map.\nrewrite map_rev.\nrewrite (map_inv_divisors n) at 2.\nrewrite <- map_rev.\nrewrite rev_involutive.\nrewrite map_map.\nrewrite concat_map.\nrewrite map_map.\nf_equal.\nspecialize (in_divisors n Hn) as Hin.\nremember (divisors n) as l eqn:Hl; clear Hl.\ninduction l as [| a l]; [ easy | ].\ncbn - [ divisors ].\nrewrite IHl. 2: {\n  intros * Hd.\n  now apply Hin; right.\n}\nf_equal.\nrewrite Nat_mod_0_div_div; cycle 1. {\n  specialize (Hin a (or_introl eq_refl)) as (H1, H2).\n  split; [ flia H2 | ].\n  apply Nat.mod_divides in H1; [ | easy ].\n  destruct H1 as (c, Hc); rewrite Hc.\n  destruct c; [ now rewrite Hc, Nat.mul_comm in Hn | ].\n  rewrite Nat.mul_comm; cbn; flia.\n} {\n  apply (Hin a (or_introl eq_refl)).\n}\nnow rewrite map_map.\nQed.\n\nTheorem Permutation_f_sum_add {F : field} {A} : ∀ (l1 l2 : list A) f a,\n  Permutation l1 l2\n  → fold_left f_add (map f l1) a =\n     fold_left f_add (map f l2) a.\nProof.\nintros * Hperm.\ninduction Hperm using Permutation_ind; [ easy | | | ]. {\n  cbn; do 2 rewrite fold_f_add_assoc.\n  now rewrite IHHperm.\n} {\n  now cbn; rewrite f_add_add_swap.\n}\netransitivity; [ apply IHHperm1 | apply IHHperm2 ].\nQed.\n\nTheorem fold_add_flat_prod_assoc {F : field} : ∀ n u v w,\n  n ≠ 0\n  → fold_left f_add\n       (flat_map (λ d, map (f_mul (u d)) (log_prod_list v w (n / d)))\n          (divisors n))\n       0%F =\n     fold_left f_add\n       (flat_map (λ d, map (f_mul (w (n / d))) (log_prod_list u v d))\n          (divisors n))\n       0%F.\nProof.\nintros * Hn.\ndo 2 rewrite flat_map_concat_map.\nunfold log_prod_list.\ndo 2 rewrite List_map_map_map.\nunfold log_prod_term.\nassert (H : ∀ f l,\n  map (λ d, map (λ d', (u d * (v d' * w (n / d / d')))%F) (f d)) l =\n  map (λ d, map (λ d', (u d * v d' * w (n / d / d'))%F) (f d)) l). {\n  intros.\n  induction l as [| a l]; [ easy | cbn ].\n  rewrite IHl; f_equal; clear.\n  induction (f a) as [| b l]; [ easy | cbn ].\n  rewrite IHl; f_equal.\n  apply f_mul_assoc.\n}\nrewrite H; clear H.\nassert (H : ∀ f l,\n  map (λ d, map (λ d', (w (n / d) * (u d' * v (d / d')))%F) (f d)) l =\n  map (λ d, map (λ d', (u d' * v (d / d') * w (n / d))%F) (f d)) l). {\n  intros.\n  induction l as [| a l]; [ easy | cbn ].\n  rewrite IHl; f_equal; clear.\n  induction (f a) as [| b l]; [ easy | cbn ].\n  rewrite IHl; f_equal.\n  apply f_mul_comm.\n}\nrewrite H; clear H.\ndo 2 rewrite <- flat_map_concat_map.\ndo 2 rewrite map_mul_triplet.\nremember (\n  flat_map (λ d, map (λ d', (d, d', n / d / d')) (divisors (n / d)))\n    (divisors n))\n  as l1 eqn:Hl1.\nremember (\n  flat_map (λ d, map (λ d', (d', d / d', n / d)) (divisors d))\n    (divisors n))\n  as l2 eqn:Hl2.\nmove l2 before l1.\nassert (H1 : ∀ d1 d2 d3, d1 * d2 * d3 = n ↔ (d1, d2, d3) ∈ l1). {\n  split; intros Huvw.\n  -intros.\n   assert (Hd1 : d1 ≠ 0) by now intros H; rewrite <- Huvw, H in Hn.\n   assert (Hd2 : d2 ≠ 0). {\n     now intros H; rewrite <- Huvw, H, Nat.mul_0_r in Hn.\n   }\n   assert (Hd3 : d3 ≠ 0). {\n     now intros H; rewrite <- Huvw, H, Nat.mul_comm in Hn.\n   }\n   subst l1.\n   apply in_flat_map.\n   exists d1.\n   split. {\n     apply in_divisors_iff; [ easy | ].\n     split; [ | easy ].\n     rewrite <- Huvw.\n     apply Nat.mod_divides; [ easy | ].\n     exists (d2 * d3).\n     symmetry; apply Nat.mul_assoc.\n   }\n   apply List.in_map_iff.\n   exists d2.\n   rewrite <- Huvw.\n   rewrite <- Nat.mul_assoc, Nat.mul_comm.\n   rewrite Nat.div_mul; [ | easy ].\n   rewrite Nat.mul_comm.\n   rewrite Nat.div_mul; [ | easy ].\n   split; [ easy | ].\n   apply in_divisors_iff; [ now apply Nat.neq_mul_0 | ].\n   split; [ | easy ].\n   apply Nat.mod_divides; [ easy | ].\n   exists d3; apply Nat.mul_comm.\n  -subst l1.\n   apply List.in_flat_map in Huvw.\n   destruct Huvw as (d & Hd & Hdi).\n   apply List.in_map_iff in Hdi.\n   destruct Hdi as (d' & Hd' & Hdd).\n   apply in_divisors in Hd; [ | easy ].\n   destruct Hd as (Hnd, Hd).\n   injection Hd'; clear Hd'; intros Hw Hv Hu.\n   subst d1 d2 d3.\n   apply Nat.mod_divides in Hnd; [ | easy ].\n   destruct Hnd as (d1, Hd1).\n   rewrite Hd1, Nat.mul_comm, Nat.div_mul in Hdd; [ | easy ].\n   rewrite Hd1, (Nat.mul_comm _ d1), Nat.div_mul; [ | easy ].\n   assert (Hd1z : d1 ≠ 0) by now intros H; rewrite H in Hdd.\n   apply in_divisors in Hdd; [ | easy ].\n   destruct Hdd as (Hdd, Hd'z).\n   apply Nat.mod_divides in Hdd; [ | easy ].\n   destruct Hdd as (d'', Hdd).\n   rewrite <- Nat.mul_assoc, Nat.mul_comm; f_equal.\n   rewrite Hdd at 1.\n   now rewrite (Nat.mul_comm _ d''), Nat.div_mul.\n}\nassert (H2 : ∀ d1 d2 d3, d1 * d2 * d3 = n ↔ (d1, d2, d3) ∈ l2). {\n  intros.\n  split; intros Hddd.\n  -assert (Hd1 : d1 ≠ 0) by now intros H; rewrite <- Hddd, H in Hn.\n   assert (Hd2 : d2 ≠ 0). {\n     now intros H; rewrite <- Hddd, H, Nat.mul_0_r in Hn.\n   }\n   assert (Hd3 : d3 ≠ 0). {\n     now intros H; rewrite <- Hddd, H, Nat.mul_comm in Hn.\n   }\n   subst l2.\n   apply in_flat_map.\n   exists (d1 * d2).\n   split. {\n     apply in_divisors_iff; [ easy | ].\n     split; [ | now apply Nat.neq_mul_0 ].\n     rewrite <- Hddd.\n     apply Nat.mod_divides; [ now apply Nat.neq_mul_0 | ].\n     now exists d3.\n   }\n   apply List.in_map_iff.\n   exists d1.\n   rewrite <- Hddd.\n   rewrite Nat.mul_comm, Nat.div_mul; [ | easy ].\n   rewrite Nat.mul_comm, Nat.div_mul; [ | now apply Nat.neq_mul_0 ].\n   split; [ easy | ].\n   apply in_divisors_iff; [ now apply Nat.neq_mul_0 | ].\n   split; [ | easy ].\n   apply Nat.mod_divides; [ easy | ].\n   exists d2; apply Nat.mul_comm.\n  -subst l2.\n   apply List.in_flat_map in Hddd.\n   destruct Hddd as (d & Hd & Hdi).\n   apply List.in_map_iff in Hdi.\n   destruct Hdi as (d' & Hd' & Hdd).\n   apply in_divisors in Hd; [ | easy ].\n   destruct Hd as (Hnd, Hd).\n   injection Hd'; clear Hd'; intros Hd3 Hd2 Hd1.\n   subst d1 d2 d3.\n   apply Nat.mod_divides in Hnd; [ | easy ].\n   destruct Hnd as (d1, Hd1).\n   rewrite Hd1, (Nat.mul_comm d), Nat.div_mul; [ | easy ].\n   rewrite Nat.mul_comm; f_equal.\n   apply in_divisors in Hdd; [ | easy ].\n   destruct Hdd as (Hdd, Hd').\n   apply Nat.mod_divides in Hdd; [ | easy ].\n   destruct Hdd as (d'', Hdd).\n   rewrite Hdd at 1.\n   now rewrite (Nat.mul_comm _ d''), Nat.div_mul.\n}\nassert (Hl1s : Sorted.Sorted lt_triplet l1). {\n  clear - Hn Hl1.\n  specialize (in_divisors n Hn) as Hin.\n  specialize (divisors_are_sorted n) as Hs.\n  remember (divisors n) as l eqn:Hl; clear Hl.\n  subst l1.\n  induction l as [| a l]; [ now cbn | ].\n  cbn - [ divisors ].\n  apply (SetoidList.SortA_app eq_equivalence).\n  -specialize (Hin a (or_introl eq_refl)); clear IHl.\n   destruct Hin as (Hna, Ha).\n   apply Nat.mod_divides in Hna; [ | easy ].\n   destruct Hna as (b, Hb).\n   rewrite Hb, Nat.mul_comm, Nat.div_mul; [ | easy ].\n   subst n.\n   assert (Hb : b ≠ 0) by now intros H; rewrite H, Nat.mul_comm in Hn.\n   clear Hn l Hs; rename b into n; rename Hb into Hn.\n   specialize (in_divisors n Hn) as Hin.\n   specialize (divisors_are_sorted n) as Hs.\n   remember (divisors n) as l eqn:Hl; clear Hl.\n   induction l as [| b l]; cbn; [ easy | ].\n   constructor.\n   +apply IHl; [ now intros d Hd; apply Hin; right | now inversion Hs ].\n   +clear IHl.\n    destruct l as [| c l]; cbn; [ easy | ].\n    constructor.\n    unfold lt_triplet, compare_trip.\n    rewrite Nat.compare_refl.\n    remember (b ?= c) as bb eqn:Hbb; symmetry in Hbb.\n    destruct bb; [ | easy | ].\n    *apply Nat.compare_eq in Hbb; subst b.\n     inversion Hs; subst.\n     inversion H2; flia H0.\n    *apply Nat.compare_gt_iff in Hbb.\n     inversion Hs; subst.\n     inversion H2; flia H0 Hbb.\n  -apply IHl; [ now intros d Hd; apply Hin; right | now inversion Hs ].\n  -intros t1 t2 Hsl Hitt.\n   assert (Hjk1 : ∃ j1 k1, t1 = (a, j1, k1)). {\n     clear - Hsl.\n     remember (divisors (n / a)) as l eqn:Hl; symmetry in Hl; clear Hl.\n     induction l as [| b l]; [ now apply SetoidList.InA_nil in Hsl | ].\n     cbn in Hsl.\n     apply SetoidList.InA_cons in Hsl.\n     destruct Hsl as [Hsl| Hsl]. {\n       now rewrite Hsl; exists b, (n / a / b).\n     }\n     now apply IHl.\n   }\n   destruct Hjk1 as (j1 & k1 & Ht1); rewrite Ht1.\n   assert (Hjk2 : ∃ i2 j2 k2, a < i2 ∧ t2 = (i2, j2, k2)). {\n     clear - Hs Hitt.\n     revert a Hs.\n     induction l as [| b l]; intros. {\n       now apply SetoidList.InA_nil in Hitt.\n     }\n     cbn - [ divisors ] in Hitt.\n     apply SetoidList.InA_app in Hitt.\n     destruct Hitt as [Hitt| Hitt]. {\n       clear - Hitt Hs.\n       assert (H2 : ∃ j2 k2, t2 = (b, j2, k2)). {\n         clear - Hitt.\n         induction (divisors (n / b)) as [| a l]. {\n           now apply SetoidList.InA_nil in Hitt.\n         }\n         cbn in Hitt.\n         apply SetoidList.InA_cons in Hitt.\n         destruct Hitt as [Hitt| Hitt]. {\n           now rewrite Hitt; exists a, (n / b / a).\n         }\n         now apply IHl.\n       }\n       destruct H2 as (j2 & k2 & H2).\n       rewrite H2.\n       exists b, j2, k2.\n       split; [ | easy ].\n       apply Sorted.Sorted_inv in Hs.\n       destruct Hs as (Hs, Hr2).\n       now apply Sorted.HdRel_inv in Hr2.\n     }\n     apply IHl; [ easy | ].\n     apply Sorted.Sorted_inv in Hs.\n     destruct Hs as (Hs, Hr).\n     apply Sorted.Sorted_inv in Hs.\n     destruct Hs as (Hs, Hr2).\n     constructor; [ easy | ].\n     apply Sorted.HdRel_inv in Hr.\n     eapply (SetoidList.InfA_ltA Nat.lt_strorder); [ apply Hr | easy ].\n   }\n   destruct Hjk2 as (i2 & j2 & k2 & Hai2 & Ht2).\n   rewrite Ht2.\n   unfold lt_triplet; cbn.\n   remember (a ?= i2) as ai eqn:Hai; symmetry in Hai.\n   destruct ai; [ | easy | ].\n   +apply Nat.compare_eq_iff in Hai; flia Hai Hai2.\n   +apply Nat.compare_gt_iff in Hai; flia Hai Hai2.\n}\nassert (Hll : length l1 = length l2). {\n  rewrite mul_assoc_indices_eq in Hl1.\n  subst l1 l2.\n  rewrite map_length.\n  do 2 rewrite List_flat_map_length.\n  do 2 rewrite map_rev.\n  rewrite map_map.\n  remember (map _ (divisors n)) as l eqn:Hl; clear.\n  remember 0 as a; clear Heqa.\n  revert a.\n  induction l as [| b l]; intros; [ easy | cbn ].\n  rewrite fold_right_app; cbn.\n  rewrite IHl; clear.\n  revert a b.\n  induction l as [| c l]; intros; [ easy | cbn ].\n  rewrite IHl; ring.\n}\nassert (H3 : ∀ t, t ∈ l1 ↔ t ∈ l2). {\n  intros ((d1, d2), d3); split; intros Ht.\n  -now apply H2, H1.\n  -now apply H1, H2.\n}\nassert (Hnd1 : NoDup l1). {\n  clear - Hl1s.\n  induction l1 as [| a1 l1]; [ constructor | ].\n  apply Sorted.Sorted_inv in Hl1s.\n  destruct Hl1s as (Hs, Hr).\n  constructor; [ | now apply IHl1 ].\n  intros Ha.\n  clear IHl1.\n  revert a1 Hr Ha.\n  induction l1 as [| a2 l1]; intros; [ easy | ].\n  apply Sorted.HdRel_inv in Hr.\n  destruct Ha as [Ha| Ha]. {\n    subst a1; revert Hr.\n    apply StrictOrder_lt_triplet.\n  }\n  apply Sorted.Sorted_inv in Hs.\n  eapply IHl1; [ easy | | apply Ha ].\n  eapply SetoidList.InfA_ltA; [ | apply Hr | easy ].\n  apply StrictOrder_lt_triplet.\n}\nassert (Hnd2 : NoDup l2). {\n  rewrite mul_assoc_indices_eq in Hl1.\n  remember (λ d : nat, map (λ d' : nat, (d', d / d', n / d)) (divisors d))\n    as f eqn:Hf.\n  rewrite Hl1 in Hnd1.\n  rewrite Hl2.\n  apply NoDup_map_inv in Hnd1.\n  rewrite flat_map_concat_map in Hnd1.\n  rewrite map_rev in Hnd1.\n  rewrite flat_map_concat_map.\n  remember (map f (divisors n)) as l eqn:Hl.\n  now apply NoDup_concat_rev.\n}\nassert (HP : Permutation l1 l2). {\n  now apply NoDup_Permutation.\n}\nnow apply Permutation_f_sum_add.\nQed.\n\nTheorem fold_add_add {F : field} : ∀ a a' l l',\n  (fold_left f_add l a + fold_left f_add l' a')%F =\n  fold_left f_add (l ++ l') (a + a')%F.\nProof.\nintros.\nrevert a.\ninduction l as [| b l]; intros; cbn. {\n  rewrite f_add_comm, (f_add_comm _ a').\n  symmetry; apply fold_f_add_assoc.\n}\nrewrite IHl.\nnow rewrite f_add_add_swap.\nQed.\n\nTheorem fold_add_map_fold_add {F : field} : ∀ (f : nat → _) a b l,\n  List.fold_left f_add (List.map (λ i, List.fold_left f_add (f i) (a i)) l)\n    b =\n  List.fold_left f_add (List.flat_map (λ i, a i :: f i) l)\n    b.\nProof.\nintros.\ninduction l as [| c l]; [ easy | cbn ].\nrewrite fold_f_add_assoc.\nrewrite fold_f_add_assoc.\nrewrite IHl, f_add_comm.\nrewrite fold_add_add.\nrewrite (f_add_comm _ b).\nnow rewrite fold_f_add_assoc.\nQed.\n\nTheorem log_prod_assoc {F : field} : ∀ u v w i,\n  i ≠ 0\n  → log_prod u (log_prod v w) i = log_prod (log_prod u v) w i.\nProof.\nintros * Hi.\nunfold log_prod at 1 3.\nunfold log_prod_list, log_prod_term.\nunfold log_prod.\nrewrite map_f_mul_fold_add_distr_l.\nrewrite fold_add_map_fold_add.\nrewrite map_f_mul_fold_add_distr_r.\nrewrite fold_add_map_fold_add.\nassert\n  (H : ∀ (u : nat → _) f l,\n   flat_map (λ i, (u i * 0)%F :: f i) l =\n   flat_map (λ i, 0%F :: f i) l). {\n  clear; intros.\n  induction l as [| a l]; [ easy | cbn ].\n  now rewrite f_mul_0_r, IHl.\n}\nrewrite H; clear H.\nassert\n  (H : ∀ (u : nat → _) f l,\n   flat_map (λ i, (0 * u i)%F :: f i) l =\n   flat_map (λ i, 0%F :: f i) l). {\n  clear; intros.\n  induction l as [| a l]; [ easy | cbn ].\n  now rewrite f_mul_0_l, IHl.\n}\nrewrite H; clear H.\nassert\n  (H : ∀ (f : nat → _) l l',\n   fold_left f_add (flat_map (λ i, 0%F :: f i) l) l' =\n   fold_left f_add (flat_map f l) l'). {\n  clear; intros.\n  revert l'.\n  induction l as [| a l]; intros; [ easy | cbn ].\n  rewrite f_add_0_r.\n  do 2 rewrite fold_left_app.\n  apply IHl.\n}\ndo 2 rewrite H.\nclear H.\nnow apply fold_add_flat_prod_assoc.\nQed.\n\n(* Associativity of product of series *)\n\nTheorem ls_mul_assoc {F : field} : ∀ x y z,\n  (x * (y * z) = (x * y) * z)%LS.\nProof.\nintros * i Hi.\nnow apply log_prod_assoc.\nQed.\n\nTheorem ls_mul_mul_swap {F : field} : ∀ x y z,\n  (x * y * z = x * z * y)%LS.\nProof.\nintros.\nrewrite ls_mul_comm.\nrewrite (ls_mul_comm _ y).\nrewrite ls_mul_assoc.\nrewrite (ls_mul_comm _ x).\napply ls_mul_assoc.\nQed.\n\n(* *)\n\nTheorem fold_left_map_log_prod_term {F : field} : ∀ u i x l,\n  (∀ j, j ∈ l → 2 ≤ j)\n  → fold_left f_add (map (log_prod_term (ls ls_one) u (S i)) l) x = x.\nProof.\nintros * Hin.\nrevert i.\ninduction l as [| a l]; intros; [ easy | ].\ncbn - [ ls_one ].\nunfold log_prod_term at 2.\nreplace ls_one~{a} with 0%F. 2: {\n  cbn.\n  destruct a; [ easy | ].\n  destruct a; [ exfalso | now destruct a ].\n  specialize (Hin 1 (or_introl eq_refl)); flia Hin.\n}\nrewrite f_mul_0_l, f_add_0_r.\napply IHl.\nintros j Hj.\nnow apply Hin; right.\nQed.\n\nTheorem ls_mul_1_l {F : field} : ∀ r, (ls_one * r = r)%LS.\nProof.\nintros * i Hi.\ndestruct i; [ easy | clear Hi ].\ncbn - [ ls_one ].\nunfold log_prod_term at 2.\nreplace ls_one~{1} with 1%F by easy.\nrewrite f_add_0_l, f_mul_1_l, Nat.div_1_r.\ncbn - [ ls_one ].\napply fold_left_map_log_prod_term.\nintros j Hj.\nassert (H : ∀ s i f, 2 ≤ s → j ∈ filter f (seq s i) → 2 ≤ j). {\n  clear; intros * Hs Hj.\n  revert s j Hs Hj.\n  induction i; intros; [ easy | ].\n  cbn - [ \"mod\" ] in Hj.\n  remember (f s) as m eqn:Hm; symmetry in Hm.\n  destruct m. {\n    cbn in Hj.\n    destruct Hj as [Hj| Hj]; [ now subst s | ].\n    apply (IHi (S s)); [ flia Hs | easy ].\n  }\n  apply (IHi (S s)); [ flia Hs | easy ].\n}\neapply (H 2 i); [ easy | ].\napply Hj.\nQed.\n\nTheorem ls_mul_1_r {F : field} : ∀ r, (r * 1 = r)%LS.\nProof.\nintros.\nnow rewrite ls_mul_comm, ls_mul_1_l.\nQed.\n\nTheorem eq_first_divisor_1 : ∀ n, n ≠ 0 → List.hd 0 (divisors n) = 1.\nProof.\nintros.\nnow destruct n.\nQed.\n\nTheorem eq_last_divisor : ∀ n, n ≠ 0 → List.last (divisors n) 0 = n.\nProof.\nintros n Hn.\nremember (divisors n) as l eqn:Hl.\nsymmetry in Hl.\nunfold divisors in Hl.\nspecialize (List_last_seq 1 n Hn) as H1.\nreplace (1 + n - 1) with n in H1 by flia.\nspecialize (proj2 (filter_In (λ a, n mod a =? 0) n (seq 1 n))) as H2.\nrewrite Hl in H2.\nrewrite Nat.mod_same in H2; [ | easy ].\ncbn in H2.\nassert (H3 : n ∈ seq 1 n). {\n  rewrite <- H1 at 1.\n  apply List_last_In.\n  now destruct n.\n}\nassert (H : n ∈ seq 1 n ∧ true = true) by easy.\nspecialize (H2 H); clear H.\nassert (H : seq 1 n ≠ []); [ now intros H; rewrite H in H3 | ].\nspecialize (app_removelast_last 0 H) as H4; clear H.\nrewrite H1 in H4.\nassert (H : seq 1 n ≠ []); [ now intros H; rewrite H in H3 | ].\nrewrite H4, filter_app in Hl; cbn in Hl.\nrewrite Nat.mod_same in Hl; [ | easy ].\ncbn in Hl; rewrite <- Hl.\napply List_last_app.\nQed.\n\nTheorem NoDup_divisors : ∀ n, NoDup (divisors n).\nProof.\nintros.\nspecialize (divisors_are_sorted n) as Hs.\napply Sorted.Sorted_StronglySorted in Hs; [ | apply Nat.lt_strorder ].\nremember (divisors n) as l eqn:Hl; clear Hl.\ninduction Hs; [ constructor | ].\nconstructor; [ | easy ].\nintros Ha.\nclear - H Ha.\nspecialize (proj1 (Forall_forall (lt a) l) H a Ha) as H1.\nflia H1.\nQed.\n\n(* Polynomial 1-1/n^s ≍ 1-x^ln(n) *)\n\nDefinition pol_pow {F : field} n :=\n  {| lp := List.repeat 0%F (n - 1) ++ [1%F] |}.\n\n(* *)\n\nNotation \"1\" := (pol_pow 1) : lp_scope.\n\nTheorem fold_ls_mul_assoc {F : field} {A} : ∀ l b c (f : A → _),\n  (fold_left (λ c a, c * f a) l (b * c) =\n   fold_left (λ c a, c * f a) l b * c)%LS.\nProof.\nintros.\nrevert b c.\ninduction l as [| d l]; intros; [ easy | cbn ].\ndo 3 rewrite IHl.\napply ls_mul_mul_swap.\nQed.\n\nTheorem eq_pol_1_sub_pow_0 {F : field} : ∀ m n d,\n  d ∈ divisors n\n  → d ≠ 1\n  → d ≠ m\n  → (ls_of_pol (pol_pow 1 - pol_pow m))~{d} = 0%F.\nProof.\nintros * Hd Hd1 Hdm.\ndestruct (Nat.eq_dec n 0) as [Hn| Hn]; [ now subst n | ].\napply in_divisors in Hd; [ | easy ].\ndestruct Hd as (Hnd, Hd).\ncbn.\ndestruct d; [ easy | ].\ndestruct m. {\n  cbn; rewrite f_add_opp_diag_r.\n  destruct d; [ easy | now destruct d ].\n}\nrewrite Nat_sub_succ_1.\napply -> Nat.succ_inj_wd_neg in Hdm.\ndestruct m. {\n  destruct d; [ easy | now destruct d ].\n}\ndestruct d; [ easy | cbn ].\ndestruct m. {\n  destruct d; [ easy | now destruct d ].\n}\ncbn; rewrite f_opp_0, f_add_0_l.\ndestruct d; [ easy | ].\nclear - Hdm.\ndo 2 apply -> Nat.succ_inj_wd_neg in Hdm.\nrevert d Hdm.\ninduction m; intros. {\n  destruct d; [ easy | now destruct d ].\n}\ncbn; rewrite f_opp_0, f_add_0_l.\ndestruct d; [ easy | ].\napply -> Nat.succ_inj_wd_neg in Hdm.\nnow apply IHm.\nQed.\n\n(*\nHere, we prove that\n   ζ(s) (1 - 1/2^s)\nis equal to\n   ζ(s) without terms whose rank is divisible by 2\n   (only odd ones are remaining)\n\nBut actually, our theorem is more general.\nWe prove, for any m and r, that\n   r(s) (1 - 1/m^s)\n\nwhere r is a series having the following property\n   ∀ i, r(s)_{i} = r(s)_{n*i}\n(the i-th coefficient of the series is equal to its (n*i)-th coefficient,\nwhich is true for ζ since all its coefficients are 1)\n\nis equal to a series r with all coefficients, whose rank is\na multiple of m, are removed.\n\nThe resulting series ζ(s) (1-1/m^s) has this property for all n\nsuch as gcd(m,n)=1, allowing us at the next theorems to restart\nwith that series and another prime number. We can then iterate\nfor all prime numbers.\n\nNote that we can then apply that whatever order of prime numbers\nand even not prime numbers if we want, providing their gcd two by\ntwo is 1.\n*)\n\nTheorem series_times_pol_1_sub_pow {F : field} : ∀ s m,\n  2 ≤ m\n  → (∀ i, i ≠ 0 → ls s i = ls s (m * i))\n  → (s *' (pol_pow 1 - pol_pow m) = series_but_mul_of m s)%LS.\nProof.\nintros * Hm Hs n Hn.\ncbn - [ ls_of_pol log_prod ].\nremember (n mod m) as p eqn:Hp; symmetry in Hp.\nunfold log_prod, log_prod_list.\nremember (log_prod_term (ls s) (ls (ls_of_pol (pol_pow 1 - pol_pow m))) n)\n  as t eqn:Ht.\nassert (Htn : t n = s~{n}). {\n  rewrite Ht; unfold log_prod_term.\n  rewrite Nat.div_same; [ | easy ].\n  replace ((ls_of_pol _)~{1}) with 1%F. 2: {\n    symmetry; cbn.\n    destruct m; [ flia Hm | cbn ].\n    rewrite Nat.sub_0_r.\n    destruct m; [ flia Hm | clear; cbn ].\n    now destruct m; cbn; rewrite f_opp_0, f_add_0_r.\n  }\n  apply f_mul_1_r.\n}\ndestruct p. {\n  apply Nat.mod_divides in Hp; [ | flia Hm ].\n  destruct Hp as (p, Hp).\n  assert (Hpz : p ≠ 0). {\n    now intros H; rewrite H, Nat.mul_0_r in Hp.\n  }\n  move p before n; move Hpz before Hn.\n  assert (Htm : t p = (- s~{n})%F). {\n    assert (H : t p = (- s~{p})%F). {\n      rewrite Ht; unfold log_prod_term.\n      rewrite Hp, Nat.div_mul; [ | easy ].\n      replace ((ls_of_pol _)~{m}) with (- 1%F)%F. 2: {\n        symmetry; cbn.\n        destruct m; [ flia Hm | cbn ].\n        rewrite Nat.sub_0_r.\n        destruct m; [ flia Hm | clear; cbn ].\n        induction m; [ cbn; apply f_add_0_l | cbn ].\n        destruct m; cbn in IHm; cbn; [ easy | apply IHm ].\n      }\n      now rewrite f_mul_opp_r, f_mul_1_r.\n    }\n    rewrite Hs in H; [ | easy ].\n    now rewrite <- Hp in H.\n  }\n  assert (Hto : ∀ d, d ∈ divisors n → d ≠ n → d ≠ p → t d = 0%F). {\n    intros d Hdn Hd1 Hdm.\n    rewrite Ht; unfold log_prod_term.\n    remember (n / d) as nd eqn:Hnd; symmetry in Hnd.\n    assert (Hd : d ≠ 0). {\n      intros H; rewrite H in Hdn.\n      now apply in_divisors in Hdn.\n    }\n    move d before p; move Hd before Hn.\n    assert (Hdnd : n = d * nd). {\n      rewrite <- Hnd.\n      apply Nat.div_exact; [ easy | ].\n      now apply in_divisors in Hdn.\n    }\n    clear Hnd.\n    assert (Hd1n : nd ≠ 1). {\n      now intros H; rewrite H, Nat.mul_1_r in Hdnd; symmetry in Hdnd.\n    }\n    replace ((ls_of_pol (pol_pow 1 - pol_pow m))~{nd}) with 0%F. 2: {\n      symmetry.\n      assert (Hndm : nd ≠ m). {\n        intros H; rewrite Hdnd, H, Nat.mul_comm in Hp.\n        apply Nat.mul_cancel_l in Hp; [ easy | ].\n        now intros H1; rewrite H, H1, Nat.mul_0_r in Hdnd.\n      }\n      assert (Hndd : nd ∈ divisors n). {\n        specialize (divisor_inv n _ Hdn) as H1.\n        rewrite Hdnd in H1 at 1.\n        rewrite Nat.mul_comm, Nat.div_mul in H1; [ easy | ].\n        now intros H; rewrite H in Hdnd.\n      }\n      now apply (eq_pol_1_sub_pow_0 _ n).\n    }\n    apply f_mul_0_r.\n  }\n  assert (Hpd : p ∈ divisors n). {\n    apply in_divisors_iff; [ easy | ].\n    now rewrite Hp, Nat.mod_mul.\n  }\n  specialize (In_nth _ _ 0 Hpd) as (k & Hkd & Hkn).\n  specialize (nth_split _ 0 Hkd) as (l1 & l2 & Hll & Hl1).\n  rewrite Hkn in Hll.\n  assert (Hdn : divisors n ≠ []). {\n    intros H; rewrite H in Hll; now destruct l1.\n  }\n  specialize (app_removelast_last 0 Hdn) as H1.\n  rewrite eq_last_divisor in H1; [ | easy ].\n  rewrite Hll in H1 at 2.\n  rewrite H1, map_app, fold_left_app; cbn.\n  rewrite removelast_app; [ | easy ].\n  rewrite map_app.\n  rewrite fold_left_app.\n  assert (H2 : ∀ a, fold_left f_add (map t l1) a = a). {\n    assert (H2 : ∀ d, d ∈ l1 → t d = 0%F). {\n      intros d Hd.\n      assert (H2 : d ≠ n). {\n        intros H2; move H2 at top; subst d.\n        specialize (divisors_are_sorted n) as H2.\n        rewrite H1 in H2.\n        apply Sorted.Sorted_StronglySorted in H2. 2: {\n          apply Nat.lt_strorder.\n        }\n        clear - Hd H2.\n        induction l1 as [| a l1]; [ easy | ].\n        destruct Hd as [Hd| Hd]. {\n          subst a.\n          cbn in H2.\n          remember (l1 ++ p :: l2) as l eqn:Hl; symmetry in Hl.\n          destruct l as [| a l]; [ now destruct l1 | ].\n          remember (removelast (a :: l)) as l3 eqn:Hl3.\n          clear - H2.\n          cbn in H2.\n          apply StronglySorted_inv in H2.\n          destruct H2 as (_, H1).\n          induction l3 as [| a l]. {\n            cbn in H1.\n            apply Forall_inv in H1; flia H1.\n          }\n          cbn in H1.\n          apply Forall_inv_tail in H1.\n          now apply IHl.\n        }\n        cbn in H2.\n        remember (l1 ++ p :: l2) as l eqn:Hl; symmetry in Hl.\n        destruct l as [| a1 l]; [ now destruct l1 | ].\n        remember (removelast (a1 :: l)) as l3 eqn:Hl3.\n        cbn in H2.\n        apply StronglySorted_inv in H2.\n        now apply IHl1.\n      }\n      apply Hto; [ | easy | ]. 2: {\n        intros H; move H at top; subst d.\n        specialize (divisors_are_sorted n) as H3.\n        rewrite Hll in H3.\n        clear - Hd H3.\n        apply Sorted.Sorted_StronglySorted in H3. 2: {\n          apply Nat.lt_strorder.\n        }\n        induction l1 as [| a l]; [ easy | ].\n        cbn in H3.\n        destruct Hd as [Hp| Hp]. {\n          subst a.\n          apply StronglySorted_inv in H3.\n          destruct H3 as (_, H3).\n          clear - H3.\n          induction l as [| a l]. {\n            cbn in H3; apply Forall_inv in H3; flia H3.\n          }\n          cbn in H3.\n          apply Forall_inv_tail in H3.\n          now apply IHl.\n        }\n        apply StronglySorted_inv in H3.\n        now apply IHl.\n      }\n      rewrite Hll.\n      now apply in_or_app; left.\n    }\n    intros a.\n    clear - H2.\n    induction l1 as [| b l]; [ easy | ].\n    cbn; rewrite fold_f_add_assoc.\n    rewrite H2; [ | now left ].\n    rewrite f_add_0_r.\n    apply IHl.\n    intros d Hd.\n    now apply H2; right.\n  }\n  rewrite <- fold_f_add_assoc.\n  rewrite (f_add_comm _ (t n)), H2.\n  rewrite f_add_0_r.\n  destruct l2 as [| a l2]. {\n    rewrite Hll in H1; cbn in H1.\n    rewrite removelast_app in H1; [ | easy ].\n    cbn in H1; cbn.\n    rewrite app_nil_r in H1.\n    apply app_inj_tail in H1.\n    destruct H1 as (_, H1); move H1 at top; subst p.\n    destruct m; [ flia Hm | ].\n    destruct m; [ flia Hm | ].\n    cbn in Hp; flia Hn Hp.\n  }\n  remember (a :: l2) as l; cbn; subst l.\n  rewrite map_cons.\n  cbn - [ removelast ].\n  rewrite Htn, Htm.\n  rewrite f_add_opp_diag_r.\n  assert (H3 : ∀ d, d ∈ removelast (a :: l2) → t d = 0%F). {\n    intros d Hd.\n    apply Hto.\n    -rewrite Hll.\n     apply in_or_app; right; right.\n     remember (a :: l2) as l.\n     clear - Hd.\n     (* lemma to do *)\n     destruct l as [| a l]; [ easy | ].\n     revert a Hd.\n     induction l as [| b l]; intros; [ easy | ].\n     destruct Hd as [Hd| Hd]; [ now subst d; left | ].\n     now right; apply IHl.\n    -intros H; move H at top; subst d.\n     assert (Hnr : n ∈ removelast (l1 ++ p :: a :: l2)). {\n       rewrite removelast_app; [ | easy ].\n       apply in_or_app; right.\n       remember (a :: l2) as l; cbn; subst l.\n       now right.\n     }\n     remember (removelast (l1 ++ p :: a :: l2)) as l eqn:Hl.\n     clear - H1 Hnr.\n     specialize (NoDup_divisors n) as H2.\n     rewrite H1 in H2; clear H1.\n     induction l as [| a l]; [ easy | ].\n     destruct Hnr as [Hnr| Hrn]. {\n       subst a; cbn in H2.\n       apply NoDup_cons_iff in H2.\n       destruct H2 as (H, _); apply H.\n       now apply in_or_app; right; left.\n     }\n     cbn in H2.\n     apply NoDup_cons_iff in H2.\n     now apply IHl.\n    -intros H; move H at top; subst d.\n     move Hpd at bottom.\n     specialize (NoDup_divisors n) as Hnd.\n     rewrite Hll in Hpd, Hnd.\n     remember (a :: l2) as l3 eqn:Hl3.\n     clear - Hpd Hd Hnd.\n     assert (Hp : p ∈ l3). {\n       clear - Hd.\n       destruct l3 as [| a l]; [ easy | ].\n       revert a Hd.\n       induction l as [| b l]; intros; [ easy | ].\n       remember (b :: l) as l1; cbn in Hd; subst l1.\n       destruct Hd as [Hd| Hd]; [ now subst a; left | ].\n       now right; apply IHl.\n     }\n     clear Hd.\n     apply NoDup_remove_2 in Hnd; apply Hnd; clear Hnd.\n     now apply in_or_app; right.\n  }\n  remember (removelast (a :: l2)) as l eqn:Hl.\n  clear - H3.\n  assert (Ha : ∀ a, fold_left f_add (map t l) a = a). {\n    induction l as [| b l]; intros; [ easy | cbn ].\n    rewrite fold_f_add_assoc.\n    rewrite H3; [ | now left ].\n    rewrite f_add_0_r; apply IHl.\n    now intros d Hd; apply H3; right.\n  }\n  apply Ha.\n}\nassert (Hto : ∀ d, d ∈ divisors n → d ≠ n → t d = 0%F). {\n  intros d Hd Hd1.\n  rewrite Ht; unfold log_prod_term.\n  replace ((ls_of_pol (pol_pow 1 - pol_pow m))~{n / d}) with 0%F. 2: {\n    symmetry.\n    assert (Hn1 : n / d ≠ 1). {\n      intros H.\n      apply in_divisors in Hd; [ | easy ].\n      destruct Hd as (Hnd, Hd).\n      apply Nat.mod_divides in Hnd; [ | easy ].\n      destruct Hnd as (c, Hc).\n      rewrite Hc, Nat.mul_comm, Nat.div_mul in H; [ | easy ].\n      rewrite H, Nat.mul_1_r in Hc.\n      now symmetry in Hc.\n    }\n    assert (Hdm : n / d ≠ m). {\n      intros H; subst m.\n      specialize (divisor_inv n d Hd) as Hnd.\n      apply in_divisors in Hnd; [ | easy ].\n      now rewrite Hp in Hnd.\n    }\n    apply divisor_inv in Hd.\n    now apply (eq_pol_1_sub_pow_0 _ n).\n  }\n  apply f_mul_0_r.\n}\nassert (Hnd : n ∈ divisors n). {\n  apply in_divisors_iff; [ easy | ].\n  now rewrite Nat.mod_same.\n}\nspecialize (NoDup_divisors n) as Hndd.\nremember (divisors n) as l eqn:Hl; symmetry in Hl.\nclear - Hnd Hto Htn Hndd.\ninduction l as [| a l]; [ easy | cbn ].\nrewrite fold_f_add_assoc.\ndestruct Hnd as [Hnd| Hnd]. {\n  subst a.\n  replace (fold_left _ _ _) with 0%F. 2: {\n    symmetry.\n    clear - Hto Hndd.\n    induction l as [| a l]; [ easy | cbn ].\n    rewrite fold_f_add_assoc.\n    apply NoDup_cons_iff in Hndd.\n    rewrite Hto; [ | now right; left | ]. 2: {\n      intros H; apply (proj1 Hndd); rewrite H.\n      now left.\n    }\n    rewrite f_add_0_r.\n    apply IHl. {\n      intros d Hd Hdn.\n      apply Hto; [ | easy ].\n      destruct Hd as [Hd| Hd]; [ now left | now right; right ].\n    }\n    destruct Hndd as (Hna, Hndd).\n    apply NoDup_cons_iff in Hndd.\n    apply NoDup_cons_iff.\n    split; [ | easy ].\n    intros H; apply Hna.\n    now right.\n  }\n  now rewrite Htn, f_add_0_l.\n}\napply NoDup_cons_iff in Hndd.\nrewrite Hto; [ | now left | now intros H; subst a ].\nrewrite f_add_0_r.\napply IHl; [ | easy | easy ].\nintros d Hd Hdn.\napply Hto; [ now right | easy ].\nQed.\n\n(*\nHere, we try to prove that\n   ζ(s) (1 - 1/2^s) (1 - 1/3^s) (1 - 1/5^s) ... (1 - 1/p^s)\nis equal to\n   ζ(s) without terms whose rank is divisible by 2, 3, 5, ... or p\ni.e.\n   1 + 1/q^s + ... where q is the next prime after p\n\nBut actually, our theorem is a little more general:\n\n1/ we do not do it for 2, 3, 5 ... p but for any list of natural numbers\n   (n1, n2, n3, ... nm) such that gcd(ni,nj) = 1 for i≠j, what is true\n   in particular for a list of prime numbers.\n\n2/ It is not the ζ function but any series r with logarithm powers such that\n       ∀ i, r_{i} = r_{n*i}\n   for any n in (n1, n2, n3 ... nm)\n   what is true for ζ function since ∀ i ζ_{i}=1.\n*)\n\nNotation \"'Π' ( a ∈ l ) , p\" :=\n  (List.fold_left (λ c a, (c * ls_of_pol p%LP)%LS) l ls_one)\n  (at level 36, a at level 0, l at level 60, p at level 36) : ls_scope.\n\nTheorem list_of_pow_1_sub_pol_times_series {F : field} : ∀ l r,\n  (∀ a, List.In a l → 2 ≤ a)\n  → (∀ a, a ∈ l → ∀ i, i ≠ 0 → r~{i} = r~{a*i})\n  → (∀ na nb, na ≠ nb → Nat.gcd (List.nth na l 1) (List.nth nb l 1) = 1)\n  → (r * Π (a ∈ l), (pol_pow 1 - pol_pow a) =\n     fold_right series_but_mul_of r l)%LS.\nProof.\nintros * Hge2 Hai Hgcd.\ninduction l as [| a1 l]. {\n  intros i Hi.\n  cbn - [ ls_mul ].\n  now rewrite ls_mul_1_r.\n}\ncbn.\nrewrite fold_ls_mul_assoc.\nrewrite ls_mul_assoc.\nrewrite IHl; cycle 1. {\n  now intros a Ha; apply Hge2; right.\n} {\n  intros a Ha i Hi; apply Hai; [ now right | easy ].\n} {\n  intros na nb Hnn.\n  apply (Hgcd (S na) (S nb)).\n  now intros H; apply Hnn; apply Nat.succ_inj in H.\n}\napply series_times_pol_1_sub_pow; [ now apply Hge2; left | ].\nintros i Hi.\nspecialize (Hai a1 (or_introl eq_refl)) as Ha1i.\nclear - Hi Ha1i Hgcd.\ninduction l as [| a l]; [ now apply Ha1i | cbn ].\nremember (i mod a) as m eqn:Hm; symmetry in Hm.\ndestruct m. {\n  destruct a; [ easy | ].\n  apply Nat.mod_divides in Hm; [ | easy ].\n  destruct Hm as (m, Hm).\n  rewrite Hm, Nat.mul_comm, <- Nat.mul_assoc, Nat.mul_comm.\n  now rewrite Nat.mod_mul.\n}\nremember ((a1 * i) mod a) as n eqn:Hn; symmetry in Hn.\ndestruct n. {\n  destruct a. {\n    cbn in Hm, Hn; subst i.\n    apply Nat.mul_eq_0_l in Hn; [ subst a1 | easy ].\n    now specialize (Hgcd 0 1 (Nat.neq_0_succ _)) as H1.\n  }\n  apply Nat.mod_divide in Hn; [ | easy ].\n  specialize (Nat.gauss (S a) a1 i Hn) as H1.\n  enough (H : Nat.gcd (S a) a1 = 1). {\n    specialize (H1 H); clear H.\n    apply Nat.mod_divide in H1; [ | easy ].\n    now rewrite Hm in H1.\n  }\n  specialize (Hgcd 0 1 (Nat.neq_0_succ _)) as H2.\n  now cbn in H2; rewrite Nat.gcd_comm in H2.\n}\napply IHl; intros na nb Hnab; cbn.\ndestruct na. {\n  destruct nb; [ easy | ].\n  now apply (Hgcd 0 (S (S nb))).\n}\ndestruct nb; [ now apply (Hgcd (S (S na)) 0) | ].\napply (Hgcd (S (S na)) (S (S nb))).\nnow apply Nat.succ_inj_wd_neg.\nQed.\n\nCorollary list_of_1_sub_pow_primes_times_ζ {F : field} : ∀ l,\n  (∀ p, p ∈ l → prime p)\n  → NoDup l\n  → (ζ * Π (p ∈ l), (pol_pow 1 - pol_pow p) =\n     fold_right series_but_mul_of ζ l)%LS.\nProof.\nintros * Hp Hnd.\napply list_of_pow_1_sub_pol_times_series; [ | easy | ]. {\n  intros p Hpl.\n  specialize (Hp _ Hpl) as H1.\n  destruct p; [ easy | ].\n  destruct p; [ easy | ].\n  do 2 apply -> Nat.succ_le_mono.\n  apply Nat.le_0_l.\n} {\n  intros * Hnab.\n  destruct (lt_dec na (length l)) as [Hna| Hna]. {\n    specialize (Hp _ (nth_In l 1 Hna)) as H1.\n    destruct (lt_dec nb (length l)) as [Hnb| Hnb]. {\n      specialize (Hp _ (nth_In l 1 Hnb)) as H2.\n      move H1 before H2.\n      assert (Hne : nth na l 1 ≠ nth nb l 1). {\n        intros He.\n        apply Hnab.\n        apply (proj1 (NoDup_nth l 1) Hnd na nb Hna Hnb He).\n      }\n      now apply eq_primes_gcd_1.\n    }\n    apply Nat.nlt_ge in Hnb.\n    rewrite (nth_overflow _ _ Hnb).\n    apply Nat.gcd_1_r.\n  }\n  apply Nat.nlt_ge in Hna.\n  rewrite (nth_overflow _ _ Hna).\n  apply Nat.gcd_1_r.\n}\nQed.\n\n(* *)\n\nDefinition primes_upto n := filter is_prime (seq 1 n).\n\n(*\nCompute (primes_upto 17).\n*)\n\nTheorem primes_upto_are_primes : ∀ k p,\n  p ∈ primes_upto k\n  → prime p.\nProof.\nintros * Hp.\nnow apply filter_In in Hp.\nQed.\n\nTheorem NoDup_primes_upto : ∀ k, NoDup (primes_upto k).\nProof.\nintros.\nunfold primes_upto.\napply NoDup_filter.\napply seq_NoDup.\nQed.\n\nTheorem gcd_primes_upto : ∀ k na nb,\n  na ≠ nb\n  → Nat.gcd (nth na (primes_upto k) 1) (nth nb (primes_upto k) 1) = 1.\nProof.\nintros * Hnab.\nremember (nth na (primes_upto k) 1) as pa eqn:Hpa.\nremember (nth nb (primes_upto k) 1) as pb eqn:Hpb.\nmove pb before pa.\ndestruct (le_dec (length (primes_upto k)) na) as [Hka| Hka]. {\n  rewrite Hpa, nth_overflow; [ | easy ].\n  apply Nat.gcd_1_l.\n}\ndestruct (le_dec (length (primes_upto k)) nb) as [Hkb| Hkb]. {\n  rewrite Hpb, nth_overflow; [ | easy ].\n  apply Nat.gcd_1_r.\n}\napply Nat.nle_gt in Hka.\napply Nat.nle_gt in Hkb.\napply eq_primes_gcd_1. {\n  apply (primes_upto_are_primes k).\n  now rewrite Hpa; apply nth_In.\n} {\n  apply (primes_upto_are_primes k).\n  now rewrite Hpb; apply nth_In.\n}\nintros H; apply Hnab; clear Hnab.\nsubst pa pb.\napply (proj1 (NoDup_nth (primes_upto k) 1)); [ | easy | easy | easy ].\napply NoDup_primes_upto.\nQed.\n\n(* formula for all primes up to a given value *)\n\nTheorem list_of_1_sub_pow_primes_upto_times {F : field} : ∀ r k,\n  (∀ a, a ∈ primes_upto k → ∀ i, i ≠ 0 → r~{i} = r~{a*i})\n  → (r * Π (p ∈ primes_upto k), (1 - pol_pow p) =\n     fold_right series_but_mul_of r (primes_upto k))%LS.\nProof.\nintros * Hri.\napply list_of_pow_1_sub_pol_times_series; [ | easy | ]. {\n  intros p Hpl.\n  apply primes_upto_are_primes in Hpl.\n  destruct p; [ easy | ].\n  destruct p; [ easy | flia ].\n} {\n  intros * Hnab.\n  now apply gcd_primes_upto.\n}\nQed.\n\nTheorem series_but_mul_primes_upto {F : field} : ∀ n i r, 1 < i < n →\n  (fold_right series_but_mul_of r (primes_upto n))~{i} = 0%F.\nProof.\nintros * (H1i, Hin).\nspecialize (exist_prime_divisor i H1i) as H1.\ndestruct H1 as (d & Hd & Hdi).\nassert (Hdn : d ∈ primes_upto n). {\n  apply filter_In.\n  split; [ | easy ].\n  apply in_seq.\n  assert (Hdz : d ≠ 0); [ now intros H; rewrite H in Hd | ].\n  apply Nat.mod_divide in Hdi; [ | easy ].\n  apply Nat.mod_divides in Hdi; [ | easy ].\n  destruct Hdi as (c, Hc).\n  split. {\n    destruct d; [ rewrite Hc in H1i; cbn in H1i; flia H1i | flia ].\n  }\n  apply (le_lt_trans _ i); [ | flia Hin ].\n  rewrite Hc.\n  destruct c; [ rewrite Hc, Nat.mul_0_r in H1i; flia H1i | ].\n  rewrite Nat.mul_succ_r; flia.\n}\nassert (Hdz : d ≠ 0); [ now intros H; rewrite H in Hd | ].\napply Nat.mod_divide in Hdi; [ | easy ].\napply Nat.mod_divides in Hdi; [ | easy ].\ndestruct Hdi as (c, Hc).\nsubst i.\nremember (primes_upto n) as l.\nclear n Hin Heql.\ninduction l as [| a l]; [ easy | ].\ndestruct Hdn as [Hdn| Hdn]. {\n  subst a; cbn.\n  now rewrite Nat.mul_comm, Nat.mod_mul.\n}\ncbn.\ndestruct ((d * c) mod a); [ easy | ].\nnow apply IHl.\nQed.\n\nTheorem times_product_on_primes_close_to {F : field} : ∀ r s n,\n  (∀ a, a ∈ primes_upto n → ∀ i, i ≠ 0 → r~{i} = r~{a*i})\n  → s = (r * Π (p ∈ primes_upto n), (1 - pol_pow p))%LS\n  → s~{1} = r~{1} ∧ ∀ i, 1 < i < n → s~{i} = 0%F.\nProof.\nintros * Hrp Hs; subst s.\nsplit. 2: {\n  intros * (H1i, Hin).\n  rewrite list_of_1_sub_pow_primes_upto_times; [ | easy | flia H1i ].\n  now apply series_but_mul_primes_upto.\n}\ncbn.\nrewrite f_add_0_l.\nunfold log_prod_term.\nrewrite Nat.div_1_r.\nspecialize (gcd_primes_upto n) as Hgcd.\nassert (Hil : ∀ a, a ∈ primes_upto n → 2 ≤ a). {\n  intros * Ha.\n  apply filter_In in Ha.\n  destruct a; [ easy | ].\n  destruct a; [ easy | flia ].\n}\nremember (primes_upto n) as l eqn:Hl; symmetry in Hl.\nreplace ((Π (p ∈ l), (1 - pol_pow p))~{1})%F with 1%F. 2: {\n  symmetry.\n  clear Hl.\n  induction l as [| p l]; [ easy | cbn ].\n  rewrite fold_ls_mul_assoc; [ | easy ].\n  cbn - [ ls_of_pol ].\n  rewrite f_add_0_l.\n  unfold log_prod_term.\n  rewrite Nat.div_1_r.\n  rewrite IHl; cycle 1. {\n    intros a Ha i Hi.\n    apply Hrp; [ now right | easy ].\n  } {\n    intros * Hnab.\n    apply (Hgcd (S na) (S nb) (proj2 (Nat.succ_inj_wd_neg na nb) Hnab)).\n  } {\n    intros a Ha.\n    now apply Hil; right.\n  }\n  rewrite f_mul_1_l.\n  destruct p; cbn. {\n    specialize (Hil 0 (or_introl eq_refl)).\n    flia Hil.\n  }\n  rewrite Nat.sub_0_r.\n  destruct p. {\n    specialize (Hil 1 (or_introl eq_refl)).\n    flia Hil.\n  }\n  cbn; clear.\n  now destruct p; cbn; rewrite f_opp_0, f_add_0_r.\n}\napply f_mul_1_r.\nQed.\n\nCorollary ζ_times_product_on_primes_close_to_1 {F : field} : ∀ s n,\n  s = (ζ * Π (p ∈ primes_upto n), (1 - pol_pow p))%LS\n  → s~{1} = 1%F ∧ (∀ i, 1 < i < n → s~{i} = 0%F).\nProof.\nintros * Hs.\nreplace 1%F with ζ~{1} by easy.\nnow apply times_product_on_primes_close_to.\nQed.\n\n(*\nDefinition lim_tow_inf_eq {F : field} (f : nat → ln_series) (s : ln_series) :=\n  ∀ i, i ≠ 0 → ∃ n, ∀ m, m > n → (f m)~{i} = s~{i}.\n\nNotation \"'lim' ( n '→' '∞' ) x = y\" := (lim_tow_inf_eq (λ n, x%LS) y%LS)\n  (at level 70, n at level 1, x at level 50).\n\nTheorem lim_ζ_times_product_on_primes {F : field} :\n  lim (n → ∞) ζ * Π (p ∈ primes_upto n), (1 - pol_pow p) = 1.\nProof.\nintros i Hi.\nexists i.\nintros m Hmi.\nspecialize (ζ_times_product_on_primes_close_to_1 _ m (eq_refl _)) as H1.\ndestruct H1 as (H1, H2).\ndestruct (Nat.eq_dec i 1) as [H1i| H1i]; [ now subst i | ].\nreplace (1~{i}) with 0%F by now destruct i; [ | destruct i ].\napply H2.\nsplit; [ | easy ].\ndestruct i; [ easy | ].\ndestruct i; [ easy | ].\napply -> Nat.succ_lt_mono.\napply Nat.lt_0_succ.\nQed.\n*)\n\nDefinition limit_sequence_equal {A} (f : nat → nat → A) (v : nat → A) :=\n  ∀ i, { n & ∀ m, n ≤ m → f m i = v i }.\n\nNotation \"'gen_lim' ( n → ∞ ) x = y\" := (limit_sequence_equal (λ n, x) y)\n  (at level 70, n at level 1, x at level 50).\n\nDefinition ls1 {F : field} s i := s~{i+1}.\n\nNotation \"'lim' ( n → ∞ ) x = y\" :=\n  (gen_lim (n → ∞) ls1 x%LS = ls1 y%LS)\n  (at level 70, n at level 1, x at level 50).\n\nTheorem lim_ζ_times_product_on_primes {F : field} :\n  lim (n → ∞) ζ * Π (p ∈ primes_upto n), (1 - pol_pow p) = 1.\nProof.\nintros i.\nexists (i + 2).\nintros m Hmi.\nspecialize (ζ_times_product_on_primes_close_to_1 _ m (eq_refl _)) as H1.\ndestruct H1 as (H1, H2).\nunfold ls1.\ndestruct (Nat.eq_dec i 0) as [Hzi| Hzi]; [ now subst i | ].\nreplace (1~{i+1}) with 0%F by now destruct i; [ | destruct i ].\napply H2.\nsplit; [ | flia Hmi ].\ndestruct i; [ easy | ].\nrewrite Nat.add_1_r.\napply -> Nat.succ_lt_mono.\napply Nat.lt_0_succ.\nQed.\n\nCheck @lim_ζ_times_product_on_primes.\n\n(*\nTheorem ζ_Euler_product_eq : ...\n*)\n", "meta": {"author": "roglo", "repo": "coq_euler_prod_form", "sha": "30dae9698b21909f0d2cf84ca20995fcd491b50b", "save_path": "github-repos/coq/roglo-coq_euler_prod_form", "path": "github-repos/coq/roglo-coq_euler_prod_form/coq_euler_prod_form-30dae9698b21909f0d2cf84ca20995fcd491b50b/Formula.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973932, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6605831469266334}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Lists.List.\nImport ListNotations. \nRequire Import maps.\nRequire Import smallstep2.\nRequire Import typerevise. \nRequire Import stlc.\n\nModule STLCProp.\nImport STLC.\n\nLemma canonical_forms_bool : forall t,\n  empty |- t in TBool ->\n  value t ->\n  (t = ttrue) \\/ (t = tfalse).\nProof.\nintros. inversion H0.\n- subst. inversion H.\n- left. reflexivity.\n- right. reflexivity.\nQed.\n\nLemma canonical_forms_fun : forall t T1 T2,\n  empty |- t in (TArrow T1 T2) ->\n  value t ->\n  exists x u, t = tabs x T1 u.\nProof.\nintros. inversion H0.\n- subst. inversion H.\nexists x0. exists t0.\nreflexivity.\n- subst. inversion H.\n- subst. inversion H.\nQed.\n\nTheorem progress : forall t T,\n  empty |- t in T ->\n  value t \\/ exists t', t --> t'.\nProof.\nintros.\nremember (@empty ty) as Gamma. \ninduction H; subst ...\n- inversion H.\n- left. apply v_abs.\n- right. destruct IHhas_type1. reflexivity.\n  + destruct IHhas_type2. reflexivity.\nassert (exists x0 t, t1 = tabs x0 T11 t). \neapply canonical_forms_fun. eapply H.\napply H1. destruct H3 as [x00 [t0 Heq]].\n  exists (subst x00 t2 t0). rewrite  Heq. \n  apply ST_AppAbs.\n  apply H2. inversion H2.\n  exists (tapp t1 x0). apply ST_App2.\n  apply H1. apply H3. \n + inversion H1. exists (tapp x0 t2).\n   apply ST_App1. apply H2.\n- left. apply v_true.\n- left. apply v_false.\n- destruct IHhas_type1 as [v |I].\n + reflexivity.\n + destruct (canonical_forms_bool t1).\n   apply H. apply v. right. subst. \n   exists t2.\n   apply ST_IfTrue.\n   subst. right. exists t3. apply ST_IfFalse.\n + right. inversion I. exists (tif x0 t2 t3).\n   apply ST_If. apply H2.\nQed.\n\nTheorem progress' : forall t T,\n     empty |- t in T ->\n     value t \\/ exists t', t --> t'.\nProof.\n  intros t. induction t; intros T Ht; auto.\n  + left. inversion Ht. subst. inversion H1.\n  + right. inversion Ht. subst.\n    assert (H22: empty |- t1 in TArrow T11 T).\n    apply H2.  \n    apply IHt1 in H2. destruct H2 as [A|B].\n    apply IHt2 in H4. destruct H4 as [C|D].\n    assert (exists x t, t1 = tabs x T11 t). \neapply canonical_forms_fun. eapply H22.\napply A. destruct H as [x [t Heq]].\nsubst. exists (subst x t2 t).\n    apply ST_AppAbs. apply C.\ninversion D. exists (tapp t1 x0).\napply ST_App2. apply A. apply H. \ninversion B. exists (tapp x0 t2).\napply ST_App1. apply H.\n + right. inversion Ht. subst. \n   assert (H33: empty |- t1 in TBool).\n   apply H3. \n   apply IHt1 in H3. \n   destruct H3 as [A|B].\n   destruct (canonical_forms_bool t1).\n   apply H33. apply A. subst.\n   exists t2. apply ST_IfTrue.\n   subst. exists t3. apply ST_IfFalse.\n   inversion B. exists (tif x0 t2 t3).\n   apply ST_If. apply H.\nQed.\n\nInductive appears_free_in : \nstring -> tm -> Prop :=\n  | afi_var : forall x,\n      appears_free_in x (tvar x)\n  | afi_app1 : forall x t1 t2,\n      appears_free_in x t1 ->\n      appears_free_in x (tapp t1 t2)\n  | afi_app2 : forall x t1 t2,\n      appears_free_in x t2 ->\n      appears_free_in x (tapp t1 t2)\n  | afi_abs : forall x y T11 t12,\n      y <> x ->\n      appears_free_in x t12 ->\n      appears_free_in x (tabs y T11 t12)\n  | afi_if1 : forall x t1 t2 t3,\n      appears_free_in x t1 ->\n      appears_free_in x (tif t1 t2 t3)\n  | afi_if2 : forall x t1 t2 t3,\n      appears_free_in x t2 ->\n      appears_free_in x (tif t1 t2 t3)\n  | afi_if3 : forall x t1 t2 t3,\n      appears_free_in x t3 ->\n      appears_free_in x (tif t1 t2 t3).\nHint Constructors appears_free_in.\n\nDefinition closed (t:tm) :=\n  forall x, ~ appears_free_in x t.\n\nLemma free_in_context : forall x t T Gamma,\n   appears_free_in x t ->\n   Gamma |- t in T ->\n   exists T', Gamma x = Some T'.\nProof.\nintros. generalize dependent Gamma. \ngeneralize dependent T.\ninduction H;intros.\n- inversion H0. subst. exists T. apply H2.\n- inversion H0. subst. \n  apply IHappears_free_in in H4. \n  apply H4.\n- inversion H0. subst. \n  apply IHappears_free_in in H6. \n  apply H6.\n- inversion H1. subst. \n  apply IHappears_free_in in H7. \n    rewrite update_neq in H7.\n  apply H7. apply H.\n- inversion H0. subst. \n  apply IHappears_free_in in H5.\n  apply H5.\n- inversion H0. subst. \n  apply IHappears_free_in in H7.\n  apply H7.\n- inversion H0. subst. \n  apply IHappears_free_in in H8.\n  apply H8.\nQed.\n\n(* Corollary typable_empty__closed : forall t T,\n    empty |- t in T ->\n    closed t.\nProof.\nintros. unfold closed; intros.  \ninversion H. \n- inversion H0.\n- subst.  inversion H0.\n  +  \n   rewrite update_neq in H4.  *)\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/stlcproprevise.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6605831452727818}}
{"text": "(* Following http://adam.chlipala.net/theses/andreser.pdf chapter 3 *)\nRequire Import Coq.ZArith.ZArith Coq.micromega.Lia.\nRequire Import Coq.Structures.Orders.\nRequire Import Coq.Lists.List.\nRequire Import Crypto.Algebra.Nsatz.\nRequire Import Crypto.Arithmetic.ModularArithmeticTheorems.\nRequire Import Crypto.Util.Decidable.\nRequire Import Crypto.Util.LetIn.\nRequire Import Crypto.Util.ListUtil.\nImport Crypto.Util.ListUtil.Reifiable.\nRequire Import Crypto.Util.NatUtil.\nRequire Import Crypto.Util.Prod.\nRequire Import Crypto.Util.Decidable.Bool2Prop.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\nRequire Import Crypto.Util.Tactics.UniquePose.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.EquivModulo.\nRequire Import Crypto.Util.ZUtil.Modulo Crypto.Util.ZUtil.Div.\nRequire Import Crypto.Util.ZUtil.Zselect.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Modulo.PullPush.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.\nRequire Import Crypto.Util.ZUtil.Tactics.RewriteModSmall.\nRequire Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo.\nRequire Import Crypto.Util.Notations.\nImport ListNotations. Local Open Scope Z_scope.\n\nModule Associational.\n  Definition eval (p:list (Z*Z)) : Z :=\n    fold_right (fun x y => x + y) 0%Z (map (fun t => fst t * snd t) p).\n\n  Lemma eval_nil : eval nil = 0.\n  Proof. trivial.                                             Qed.\n  Lemma eval_cons p q : eval (p::q) = fst p * snd p + eval q.\n  Proof. trivial.                                             Qed.\n  Lemma eval_app p q: eval (p++q) = eval p + eval q.\n  Proof. induction p; rewrite <-?List.app_comm_cons;\n           rewrite ?eval_nil, ?eval_cons; nsatz.              Qed.\n\n#[global]\n  Hint Rewrite eval_nil eval_cons eval_app : push_eval.\n  Local Ltac push := autorewrite with\n      push_eval push_map push_partition push_flat_map\n      push_fold_right push_nth_default cancel_pair.\n\n  Lemma eval_map_mul (a x:Z) (p:list (Z*Z))\n  : eval (List.map (fun t => (a*fst t, x*snd t)) p) = a*x*eval p.\n  Proof. induction p; push; nsatz.                            Qed.\n#[global]\n  Hint Rewrite eval_map_mul : push_eval.\n\n  Definition mul (p q:list (Z*Z)) : list (Z*Z) :=\n    flat_map (fun t =>\n      map (fun t' =>\n        (fst t * fst t', snd t * snd t'))\n    q) p.\n  Lemma eval_mul p q : eval (mul p q) = eval p * eval q.\n  Proof. induction p; cbv [mul]; push; nsatz.                 Qed.\n#[global]\n  Hint Rewrite eval_mul : push_eval.\n\n  Definition square (p:list (Z*Z)) : list (Z*Z) :=\n    list_rect\n      _\n      nil\n      (fun t ts acc\n       => (dlet two_t2 := 2 * snd t in\n               (fst t * fst t, snd t * snd t)\n                 :: (map (fun t'\n                          => (fst t * fst t', two_t2 * snd t'))\n                         ts))\n            ++ acc)\n      p.\n  Lemma eval_square p : eval (square p) = eval p * eval p.\n  Proof. induction p; cbv [square list_rect Let_In]; push; nsatz. Qed.\n#[global]\n  Hint Rewrite eval_square : push_eval.\n\n  Definition negate_snd (p:list (Z*Z)) : list (Z*Z) :=\n    map (fun cx => (fst cx, -snd cx)) p.\n  Lemma eval_negate_snd p : eval (negate_snd p) = - eval p.\n  Proof. induction p; cbv [negate_snd]; push; nsatz.          Qed.\n#[global]\n  Hint Rewrite eval_negate_snd : push_eval.\n\n  Example base10_2digit_mul (a0:Z) (a1:Z) (b0:Z) (b1:Z) :\n    {ab| eval ab = eval [(10,a1);(1,a0)] * eval [(10,b1);(1,b0)]}.\n    eexists ?[ab].\n    (* Goal: eval ?ab = eval [(10,a1);(1,a0)] * eval [(10,b1);(1,b0)] *)\n    rewrite <-eval_mul.\n    (* Goal: eval ?ab = eval (mul [(10,a1);(1,a0)] [(10,b1);(1,b0)]) *)\n    cbv -[Z.mul eval]; cbn -[eval].\n    (* Goal: eval ?ab = eval [(100,(a1*b1));(10,a1*b0);(10,a0*b1);(1,a0*b0)]%RT *)\n    trivial.                                              Defined.\n\n  Lemma eval_partition f (p:list (Z*Z)) :\n    eval (snd (partition f p)) + eval (fst (partition f p)) = eval p.\n  Proof. induction p; cbn [partition]; eta_expand; break_match; cbn [fst snd]; push; nsatz. Qed.\n#[global]\n  Hint Rewrite eval_partition : push_eval.\n\n  Lemma eval_partition' f (p:list (Z*Z)) :\n    eval (fst (partition f p)) + eval (snd (partition f p)) = eval p.\n  Proof. rewrite Z.add_comm, eval_partition; reflexivity. Qed.\n#[global]\n  Hint Rewrite eval_partition' : push_eval.\n\n  Lemma eval_fst_partition f p : eval (fst (partition f p)) = eval p - eval (snd (partition f p)).\n  Proof. rewrite <- (eval_partition f p); nsatz. Qed.\n  Lemma eval_snd_partition f p : eval (snd (partition f p)) = eval p - eval (fst (partition f p)).\n  Proof. rewrite <- (eval_partition f p); nsatz. Qed.\n\n  Definition split (s:Z) (p:list (Z*Z)) : list (Z*Z) * list (Z*Z)\n    := let hi_lo := partition (fun t => fst t mod s =? 0) p in\n       (snd hi_lo, map (fun t => (fst t / s, snd t)) (fst hi_lo)).\n  Lemma eval_snd_split s p (s_nz:s<>0) :\n    s * eval (snd (split s p)) = eval (fst (partition (fun t => fst t mod s =? 0) p)).\n  Proof using Type. cbv [split Let_In]; induction p;\n    repeat match goal with\n    | |- context[?a/?b] =>\n      unique pose proof (Z_div_exact_full_2 a b ltac:(trivial) ltac:(trivial))\n    | _ => progress push\n    | _ => progress break_match\n    | _ => progress nsatz                                end. Qed.\n  Lemma eval_split s p (s_nz:s<>0) :\n    eval (fst (split s p)) + s * eval (snd (split s p)) = eval p.\n  Proof using Type. rewrite eval_snd_split, eval_fst_partition by assumption; cbv [split Let_In]; cbn [fst snd]; lia. Qed.\n\n  Lemma reduction_rule' b s c (modulus_nz:s-c<>0) :\n    (s * b) mod (s - c) = (c * b) mod (s - c).\n  Proof using Type. replace (s * b) with ((c*b) + b*(s-c)) by nsatz.\n    rewrite Z.add_mod,Z_mod_mult,Z.add_0_r,Z.mod_mod;trivial. Qed.\n\n  Lemma reduction_rule a b s c (modulus_nz:s-c<>0) :\n    (a + s * b) mod (s - c) = (a + c * b) mod (s - c).\n  Proof using Type. apply Z.add_mod_Proper; [ reflexivity | apply reduction_rule', modulus_nz ]. Qed.\n\n  Definition reduce (s:Z) (c:list _) (p:list _) : list (Z*Z) :=\n    let lo_hi := split s p in fst lo_hi ++ mul c (snd lo_hi).\n\n  Lemma eval_reduce s c p (s_nz:s<>0) (modulus_nz:s-eval c<>0) :\n    eval (reduce s c p) mod (s - eval c) = eval p mod (s - eval c).\n  Proof using Type. cbv [reduce]; push.\n         rewrite <-reduction_rule, eval_split; trivial.      Qed.\n#[global]\n  Hint Rewrite eval_reduce : push_eval.\n\n  Lemma eval_reduce_adjusted s c p w c' (s_nz:s<>0) (modulus_nz:s-eval c<>0)\n        (w_mod:w mod s = 0) (w_nz:w <> 0) (Hc' : eval c' = (w / s) * eval c) :\n    eval (reduce w c' p) mod (s - eval c) = eval p mod (s - eval c).\n  Proof using Type.\n    cbv [reduce]; push.\n    rewrite Hc', <- (Z.mul_comm (eval c)), <- !Z.mul_assoc, <-reduction_rule by auto.\n    autorewrite with zsimplify_const; rewrite !Z.mul_assoc, Z.mul_div_eq_full, w_mod by auto.\n    autorewrite with zsimplify_const; rewrite eval_split; trivial.\n  Qed.\n\n  (* reduce at most [n] times, stopping early if the high list is nil at any point *)\n  Definition repeat_reduce (n : nat) (s:Z) (c:list _) (p:list _) : list (Z * Z)\n    := nat_rect\n         _\n         (fun p => p)\n         (fun n' repeat_reduce_n' p\n          => let lo_hi := split s p in\n             if (length (snd lo_hi) =? 0)%nat\n             then p\n             else let p := fst lo_hi ++ mul c (snd lo_hi) in\n                  repeat_reduce_n' p)\n         n\n         p.\n\n  Lemma repeat_reduce_S_step n s c p\n    : repeat_reduce (S n) s c p\n      = if (length (snd (split s p)) =? 0)%nat\n        then p\n        else repeat_reduce n s c (reduce s c p).\n  Proof using Type. cbv [repeat_reduce]; cbn [nat_rect]; break_innermost_match; auto. Qed.\n\n  Lemma eval_repeat_reduce n s c p (s_nz:s<>0) (modulus_nz:s-eval c<>0) :\n    eval (repeat_reduce n s c p) mod (s - eval c) = eval p mod (s - eval c).\n  Proof using Type.\n    revert p; induction n as [|n IHn]; intro p; [ reflexivity | ];\n      rewrite repeat_reduce_S_step; break_innermost_match;\n        [ reflexivity | rewrite IHn ].\n    now rewrite eval_reduce.\n  Qed.\n#[global]\n  Hint Rewrite eval_repeat_reduce : push_eval.\n\n  Lemma eval_repeat_reduce_adjusted n s c p w c' (s_nz:s<>0) (modulus_nz:s-eval c<>0)\n        (w_mod:w mod s = 0) (w_nz:w <> 0) (Hc' : eval c' = (w / s) * eval c) :\n    eval (repeat_reduce n w c' p) mod (s - eval c) = eval p mod (s - eval c).\n  Proof using Type.\n    revert p; induction n as [|n IHn]; intro p; [ reflexivity | ];\n      rewrite repeat_reduce_S_step; break_innermost_match;\n        [ reflexivity | rewrite IHn ].\n    now rewrite eval_reduce_adjusted.\n  Qed.\n\n  Definition split_one (s:Z) (w fw : Z) (p:list (Z*Z)) :=\n    let hi_lo := partition (fun t => (fst t =? w)) p in\n      (snd hi_lo, map (fun t => (fst t / fw, snd t)) (fst hi_lo)).\n\n  Lemma eval_split_one s w fw p (s_nz:s<>0) (fw_nz:fw<>0) (w_fw : w mod fw = 0) (fw_s : fw mod s = 0):\n    Associational.eval (fst (split_one s w fw p)) + fw * Associational.eval (snd (split_one s w fw p)) = Associational.eval p.\n  Proof.\n    remember (Z_div_exact_full_2 _ _ fw_nz w_fw) as H2.\n    clear HeqH2 fw_nz w_fw.\n    induction p as [|t p' IHp'].\n    - simpl. cbv [Associational.eval]. simpl. lia.\n    - cbv [split_one]. simpl. destruct (fst t =? w) eqn:E.\n      + simpl in IHp'. remember (partition (fun t0 : Z * Z => fst t0 =? w) p') as thing.\n        destruct thing as [thing1 thing2]. simpl. simpl in IHp'. repeat rewrite Associational.eval_cons.\n        ring_simplify. simpl.\n        apply Z.eqb_eq in E. rewrite E. rewrite <- H2. rewrite <- IHp'. ring.\n      + simpl in IHp'. remember (partition (fun t0 : Z * Z => fst t0 =? w) p') as thing.\n        destruct thing as [thing1 thing2]. simpl. simpl in IHp'. repeat rewrite Associational.eval_cons.\n        rewrite <- IHp'. ring.\n  Qed.\n\n  Definition reduce_one (s:Z) (w fw : Z) (c: Z) (p:list _) : list (Z*Z) :=\n    let lo_hi := split_one s w fw p in\n    fst lo_hi ++ map (fun thing => (fst thing, snd thing * (c * (fw / s)))) (snd lo_hi).\n\n  Lemma eval_map_mul_snd (x:Z) (p:list (Z*Z))\n    : Associational.eval (List.map (fun t => (fst t, snd t * x)) p) = x * Associational.eval p.\n  Proof. induction p; push; nsatz. Qed.\n\n  Lemma eval_reduce_one s w fw c p (s_nz:s<>0) (fw_nz:fw<>0) (w_fw : w mod fw = 0) (fw_s : fw mod s = 0)\n                               (modulus_nz: s - c<>0) :\n              Associational.eval (reduce_one s w fw c p) mod (s - c) =\n              Associational.eval p mod (s - c).\n  Proof using Type.\n    cbv [reduce_one]; push.\n    rewrite eval_map_mul_snd. rewrite <- Z.mul_assoc.\n    rewrite <- (reduction_rule _ _ _ _ modulus_nz).\n    rewrite Z.mul_assoc. rewrite <- (Z_div_exact_full_2 fw s s_nz fw_s). rewrite eval_split_one; trivial.\n  Qed.\n\n  (*\n  Definition splitQ (s:Q) (p:list (Z*Z)) : list (Z*Z) * list (Z*Z)\n    := let hi_lo := partition (fun t => (fst t * Zpos (Qden s)) mod (Qnum s) =? 0) p in\n       (snd hi_lo, map (fun t => ((fst t * Zpos (Qden s)) / Qnum s, snd t)) (fst hi_lo)).\n  Lemma eval_snd_splitQ s p (s_nz:Qnum s<>0) :\n   Qnum s * eval (snd (splitQ s p)) = eval (fst (partition (fun t => (fst t * Zpos (Qden s)) mod (Qnum s) =? 0) p)) * Zpos (Qden s).\n  Proof using Type.\n    (* Work around https://github.com/mit-plv/fiat-crypto/issues/381 ([nsatz] can't handle [Zpos]) *)\n    cbv [splitQ Let_In]; cbn [fst snd]; zify; generalize dependent (Zpos (Qden s)); generalize dependent (Qnum s); clear s; intros.\n    induction p;\n    repeat match goal with\n    | |- context[?a/?b] =>\n      unique pose proof (Z_div_exact_full_2 a b ltac:(trivial) ltac:(trivial))\n    | _ => progress push\n    | _ => progress break_match\n    | _ => progress nsatz                                end. Qed.\n  Lemma eval_splitQ s p (s_nz:Qnum s<>0) :\n    eval (fst (splitQ s p)) + (Qnum s * eval (snd (splitQ s p))) / Zpos (Qden s) = eval p.\n  Proof using Type. rewrite eval_snd_splitQ, eval_fst_partition by assumption; cbv [splitQ Let_In]; cbn [fst snd]; Z.div_mod_to_quot_rem_in_goal; nia. Qed.\n  Lemma eval_splitQ_mul s p (s_nz:Qnum s<>0) :\n    eval (fst (splitQ s p)) * Zpos (Qden s) + (Qnum s * eval (snd (splitQ s p))) = eval p * Zpos (Qden s).\n  Proof using Type. rewrite eval_snd_splitQ, eval_fst_partition by assumption; cbv [splitQ Let_In]; cbn [fst snd]; nia. Qed.\n   *)\n  Lemma eval_rev p : eval (rev p) = eval p.\n  Proof using Type. induction p; cbn [rev]; push; lia. Qed.\n#[global]\n  Hint Rewrite eval_rev : push_eval.\n  (*\n  Lemma eval_permutation (p q : list (Z * Z)) : Permutation p q -> eval p = eval q.\n  Proof using Type. induction 1; push; nsatz.                          Qed.\n\n  Module RevWeightOrder <: TotalLeBool.\n    Definition t := (Z * Z)%type.\n    Definition leb (x y : t) := Z.leb (fst y) (fst x).\n    Infix \"<=?\" := leb.\n    Local Coercion is_true : bool >-> Sortclass.\n    Theorem leb_total : forall a1 a2, a1 <=? a2 \\/ a2 <=? a1.\n    Proof using Type.\n      cbv [is_true leb]; intros x y; rewrite !Z.leb_le; pose proof (Z.le_ge_cases (fst x) (fst y)).\n      lia.\n    Qed.\n    Global Instance leb_Transitive : Transitive leb.\n    Proof using Type. repeat intro; unfold is_true, leb in *; Z.ltb_to_lt; lia. Qed.\n  End RevWeightOrder.\n\n  Module RevWeightSort := Mergesort.Sort RevWeightOrder.\n\n  Lemma eval_sort p : eval (RevWeightSort.sort p) = eval p.\n  Proof using Type. symmetry; apply eval_permutation, RevWeightSort.Permuted_sort. Qed.\n  Hint Rewrite eval_sort : push_eval.\n  *)\n  (* rough template (we actually have to do things a bit differently to account for duplicate weights):\n[ dlet fi_c := c * fi in\n   let (fj_high, fj_low) := split fj at s/fi.weight in\n   dlet fi_2 := 2 * fi in\n    dlet fi_2_c := 2 * fi_c in\n    (if fi.weight^2 >= s then fi_c * fi else fi * fi)\n       ++ fi_2_c * fj_high\n       ++ fi_2 * fj_low\n | fi <- f , fj := (f weight less than i) ]\n   *)\n  (** N.B. We take advantage of dead code elimination to allow us to\n      let-bind partial products that we don't end up using *)\n  (** [v] -> [(v, v*c, v*c*2, v*2)] *)\n  Definition let_bind_for_reduce_square (c:list (Z*Z)) (p:list (Z*Z)) : list ((Z*Z) * list(Z*Z) * list(Z*Z) * list(Z*Z)) :=\n    let two := [(1,2)] (* (weight, value) *) in\n    map (fun t => dlet c_t := mul [t] c in dlet two_c_t := mul c_t two in dlet two_t := mul [t] two in (t, c_t, two_c_t, two_t)) p.\n  Definition reduce_square (s:Z) (c:list (Z*Z)) (p:list (Z*Z)) : list (Z*Z) :=\n    let p := let_bind_for_reduce_square c p in\n    let div_s := map (fun t => (fst t / s, snd t)) in\n    list_rect\n      _\n      nil\n      (fun t ts acc\n       => (let '(t, c_t, two_c_t, two_t) := t in\n           (if ((fst t * fst t) mod s =? 0)\n            then div_s (mul [t] c_t)\n            else mul [t] [t])\n             ++ (flat_map\n                   (fun '(t', c_t', two_c_t', two_t')\n                    => if ((fst t * fst t') mod s =? 0)\n                       then div_s\n                              (if fst t' <=? fst t\n                               then mul [t'] two_c_t\n                               else mul [t] two_c_t')\n                       else (if fst t' <=? fst t\n                             then mul [t'] two_t\n                             else mul [t] two_t'))\n                   ts))\n            ++ acc)\n      p.\n  Lemma eval_map_div s p (s_nz:s <> 0) (Hmod : forall v, In v p -> fst v mod s = 0)\n    : eval (map (fun x => (fst x / s, snd x)) p) = eval p / s.\n  Proof using Type.\n    assert (Hmod' : forall v, In v p -> (fst v * snd v) mod s = 0).\n    { intros; push_Zmod; rewrite Hmod by assumption; autorewrite with zsimplify_const; reflexivity. }\n    induction p as [|p ps IHps]; push.\n    { autorewrite with zsimplify_const; reflexivity. }\n    { cbn [In] in *; rewrite Z.div_add_exact by eauto.\n      rewrite !Z.Z_divide_div_mul_exact', IHps by auto using Znumtheory.Zmod_divide.\n      nsatz. }\n  Qed.\n  Lemma eval_map_mul_div s a b c (s_nz:s <> 0) (a_mod : (a*a) mod s = 0)\n    : eval (map (fun x => ((a * (a * fst x)) / s, b * (b * snd x))) c) = ((a * a) / s) * (b * b) * eval c.\n  Proof using Type.\n    rewrite <- eval_map_mul; apply f_equal, map_ext; intro.\n    rewrite !Z.mul_assoc.\n    rewrite !Z.Z_divide_div_mul_exact' by auto using Znumtheory.Zmod_divide.\n    f_equal; nia.\n  Qed.\n#[global]\n  Hint Rewrite eval_map_mul_div using solve [ auto ] : push_eval.\n\n  Lemma eval_map_mul_div' s a b c (s_nz:s <> 0) (a_mod : (a*a) mod s = 0)\n    : eval (map (fun x => (((a * a) * fst x) / s, (b * b) * snd x)) c) = ((a * a) / s) * (b * b) * eval c.\n  Proof using Type. rewrite <- eval_map_mul_div by assumption; f_equal; apply map_ext; intro; Z.div_mod_to_quot_rem_in_goal; f_equal; nia. Qed.\n#[global]\n  Hint Rewrite eval_map_mul_div' using solve [ auto ] : push_eval.\n\n  Lemma eval_flat_map_if A (f : A -> bool) g h p\n    : eval (flat_map (fun x => if f x then g x else h x) p)\n      = eval (flat_map g (fst (partition f p))) + eval (flat_map h (snd (partition f p))).\n  Proof using Type.\n    induction p; cbn [flat_map partition fst snd]; eta_expand; break_match; cbn [fst snd]; push;\n      nsatz.\n  Qed.\n  (*Local Hint Rewrite eval_flat_map_if : push_eval.*) (* this should be [Local], but that doesn't work *)\n\n  Lemma eval_if (b : bool) p q : eval (if b then p else q) = if b then eval p else eval q.\n  Proof using Type. case b; reflexivity. Qed.\n#[global]\n  Hint Rewrite eval_if : push_eval.\n\n  Lemma split_app s p q :\n    split s (p ++ q) = (fst (split s p) ++ fst (split s q), snd (split s p) ++ snd (split s q)).\n  Proof using Type.\n    cbv [split]; rewrite !partition_app; cbn [fst snd].\n    rewrite !map_app; reflexivity.\n  Qed.\n  Lemma fst_split_app s p q :\n    fst (split s (p ++ q)) = fst (split s p) ++ fst (split s q).\n  Proof using Type. rewrite split_app; reflexivity. Qed.\n  Lemma snd_split_app s p q :\n    snd (split s (p ++ q)) = snd (split s p) ++ snd (split s q).\n  Proof using Type. rewrite split_app; reflexivity. Qed.\n#[global]\n  Hint Rewrite fst_split_app snd_split_app : push_eval.\n\n  Lemma eval_reduce_list_rect_app A s c N C p :\n    eval (reduce s c (@list_rect A _ N (fun x xs acc => C x xs ++ acc) p))\n    = eval (@list_rect A _ (reduce s c N) (fun x xs acc => reduce s c (C x xs) ++ acc) p).\n  Proof using Type.\n    cbv [reduce]; induction p as [|p ps IHps]; cbn [list_rect]; push; [ nsatz | rewrite <- IHps; clear IHps ].\n    push; nsatz.\n  Qed.\n#[global]\n  Hint Rewrite eval_reduce_list_rect_app : push_eval.\n\n  Lemma eval_list_rect_app A N C p :\n    eval (@list_rect A _ N (fun x xs acc => C x xs ++ acc) p)\n    = @list_rect A _ (eval N) (fun x xs acc => eval (C x xs) + acc) p.\n  Proof using Type. induction p; cbn [list_rect]; push; nsatz. Qed.\n#[global]\n  Hint Rewrite eval_list_rect_app : push_eval.\n\n  Local Existing Instances list_rect_Proper pointwise_map flat_map_Proper.\n  Local Hint Extern 0 (Proper _ _) => solve_Proper_eq : typeclass_instances.\n\n  Lemma reduce_nil s c : reduce s c nil = nil.\n  Proof using Type. cbv [reduce]; induction c; cbn; intuition auto. Qed.\n#[global]\n  Hint Rewrite reduce_nil : push_eval.\n\n  Lemma eval_reduce_app s c p q : eval (reduce s c (p ++ q)) = eval (reduce s c p) + eval (reduce s c q).\n  Proof using Type. cbv [reduce]; push; nsatz. Qed.\n#[global]\n  Hint Rewrite eval_reduce_app : push_eval.\n\n  Lemma eval_reduce_cons s c p q :\n    eval (reduce s c (p :: q))\n    = (if fst p mod s =? 0 then eval c * ((fst p / s) * snd p) else fst p * snd p)\n      + eval (reduce s c q).\n  Proof using Type.\n    cbv [reduce split]; cbn [partition fst snd]; eta_expand; push.\n    break_innermost_match; cbn [fst snd map]; push; nsatz.\n  Qed.\n#[global]\n  Hint Rewrite eval_reduce_cons : push_eval.\n\n  Lemma mul_cons_l t ts p :\n    mul (t::ts) p = map (fun t' => (fst t * fst t', snd t * snd t')) p ++ mul ts p.\n  Proof using Type. reflexivity. Qed.\n  Lemma mul_nil_l p : mul nil p = nil.\n  Proof using Type. reflexivity. Qed.\n  Lemma mul_nil_r p : mul p nil = nil.\n  Proof using Type. cbv [mul]; induction p; cbn; intuition auto. Qed.\n#[global]\n  Hint Rewrite mul_nil_l mul_nil_r : push_eval.\n  Lemma mul_app_l p p' q :\n    mul (p ++ p') q = mul p q ++ mul p' q.\n  Proof using Type. cbv [mul]; rewrite flat_map_app; reflexivity. Qed.\n  Lemma mul_singleton_l_app_r p q q' :\n    mul [p] (q ++ q') = mul [p] q ++ mul [p] q'.\n  Proof using Type. cbv [mul flat_map]; rewrite !map_app, !app_nil_r; reflexivity. Qed.\n#[global]\n  Hint Rewrite mul_singleton_l_app_r : push_eval.\n  Lemma mul_singleton_singleton p q :\n    mul [p] [q] = [(fst p * fst q, snd p * snd q)].\n  Proof using Type. reflexivity. Qed.\n\n  Lemma eval_reduce_square_step_helper s c t' t v (s_nz:s <> 0) :\n    (fst t * fst t') mod s = 0 \\/ (fst t' * fst t) mod s = 0 -> In v (mul [t'] (mul (mul [t] c) [(1, 2)])) -> fst v mod s = 0.\n  Proof using Type.\n    cbv [mul]; cbn [map flat_map fst snd].\n    rewrite !app_nil_r, flat_map_singleton, !map_map; cbn [fst snd]; rewrite in_map_iff; intros [H|H] [? [? ?] ]; subst; revert H.\n    all:cbn [fst snd]; autorewrite with zsimplify_const; intro H; rewrite Z.mul_assoc, Z.mul_mod_l.\n    all:rewrite H || rewrite (Z.mul_comm (fst t')), H; autorewrite with zsimplify_const; reflexivity.\n  Qed.\n\n  Lemma eval_reduce_square_step s c t ts (s_nz : s <> 0) :\n    eval (flat_map\n            (fun t' => if (fst t * fst t') mod s =? 0\n                    then map (fun t => (fst t / s, snd t))\n                             (if fst t' <=? fst t\n                              then mul [t'] (mul (mul [t] c) [(1, 2)])\n                              else mul [t] (mul (mul [t'] c) [(1, 2)]))\n                    else (if fst t' <=? fst t\n                          then mul [t'] (mul [t] [(1, 2)])\n                          else mul [t] (mul [t'] [(1, 2)])))\n            ts)\n    = eval (reduce s c (mul [(1, 2)] (mul [t] ts))).\n  Proof using Type.\n    induction ts as [|t' ts IHts]; cbn [flat_map]; [ push; nsatz | rewrite eval_app, IHts; clear IHts ].\n    change (t'::ts) with ([t'] ++ ts); rewrite !mul_singleton_l_app_r, !mul_singleton_singleton; autorewrite with zsimplify_const; push.\n    break_match; Z.ltb_to_lt; push; try nsatz.\n    all:rewrite eval_map_div by eauto using eval_reduce_square_step_helper; push; autorewrite with zsimplify_const.\n    all:rewrite ?Z.mul_assoc, <- !(Z.mul_comm (fst t')), ?Z.mul_assoc.\n    all:rewrite ?Z.mul_assoc, <- !(Z.mul_comm (fst t)), ?Z.mul_assoc.\n    all:rewrite <- !Z.mul_assoc, Z.mul_assoc.\n    all:rewrite !Z.Z_divide_div_mul_exact' by auto using Znumtheory.Zmod_divide.\n    all:nsatz.\n  Qed.\n\n  Lemma eval_reduce_square_helper s c x y v (s_nz:s <> 0) :\n    (fst x * fst y) mod s = 0 \\/ (fst y * fst x) mod s = 0 -> In v (mul [x] (mul [y] c)) -> fst v mod s = 0.\n  Proof using Type.\n    cbv [mul]; cbn [map flat_map fst snd].\n    rewrite !app_nil_r, ?flat_map_singleton, !map_map; cbn [fst snd]; rewrite in_map_iff; intros [H|H] [? [? ?] ]; subst; revert H.\n    all:cbn [fst snd]; autorewrite with zsimplify_const; intro H; rewrite Z.mul_assoc, Z.mul_mod_l.\n    all:rewrite H || rewrite (Z.mul_comm (fst x)), H; autorewrite with zsimplify_const; reflexivity.\n  Qed.\n\n  Lemma eval_reduce_square_exact s c p (s_nz:s<>0) (modulus_nz:s-eval c<>0)\n    : eval (reduce_square s c p) = eval (reduce s c (square p)).\n  Proof using Type.\n    cbv [let_bind_for_reduce_square reduce_square square Let_In]; rewrite list_rect_map; push.\n    apply list_rect_Proper; [ | repeat intro; subst | reflexivity ]; cbv [split]; push; [ nsatz | ].\n    rewrite flat_map_map, eval_reduce_square_step by auto.\n    break_match; Z.ltb_to_lt; push.\n    1:rewrite eval_map_div by eauto using eval_reduce_square_helper; push.\n    all:cbv [mul]; cbn [map flat_map fst snd]; rewrite !app_nil_r, !map_map; cbn [fst snd].\n    all:autorewrite with zsimplify_const.\n    all:rewrite <- ?Z.mul_assoc, !(Z.mul_comm (fst a)), <- ?Z.mul_assoc.\n    all:rewrite ?Z.mul_assoc, <- (Z.mul_assoc _ (fst a) (fst a)), <- !(Z.mul_comm (fst a * fst a)).\n    1:rewrite !Z.Z_divide_div_mul_exact' by auto using Znumtheory.Zmod_divide.\n    all:idtac;\n      let LHS := match goal with |- ?LHS = ?RHS => LHS end in\n      let RHS := match goal with |- ?LHS = ?RHS => RHS end in\n      let f := match LHS with context[eval (reduce _ _ (map ?f _))] => f end in\n      let g := match RHS with context[eval (reduce _ _ (map ?f _))] => f end in\n      rewrite (map_ext f g) by (intros; f_equal; nsatz).\n    all:nsatz.\n  Qed.\n  Lemma eval_reduce_square s c p (s_nz:s<>0) (modulus_nz:s-eval c<>0)\n    : eval (reduce_square s c p) mod (s - eval c)\n      = (eval p * eval p) mod (s - eval c).\n  Proof using Type. rewrite eval_reduce_square_exact by assumption; push; auto. Qed.\n#[global]\n  Hint Rewrite eval_reduce_square : push_eval.\n\n  Definition bind_snd (p : list (Z*Z)) :=\n    map (fun t => dlet_nd t2 := snd t in (fst t, t2)) p.\n\n  Lemma bind_snd_correct p : bind_snd p = p.\n  Proof using Type.\n    cbv [bind_snd]; induction p as [| [? ?] ];\n      push; [|rewrite IHp]; reflexivity.\n  Qed.\n\n  Definition value_at_weight (a : list (Z * Z)) (d : Z) :=\n    fold_right Z.add 0 (map snd (filter (fun p => fst p =? d) a)).\n\n  Lemma value_at_weight_works a d : d * (value_at_weight a d) = Associational.eval (filter (fun p => fst p =? d) a).\n  Proof.\n    induction a as [| a0 a' IHa'].\n    - cbv [Associational.eval value_at_weight]. simpl. lia.\n    - cbv [value_at_weight]. simpl. destruct (fst a0 =? d) eqn:E.\n      + rewrite Associational.eval_cons. simpl. rewrite <- IHa'. cbv [value_at_weight]. lia.\n      + apply IHa'.\n  Qed.\n\n  Lemma not_in_value_0 a d : ~ In d (map fst a) -> value_at_weight a d = 0.\n  Proof.\n    intros H. induction a as [| x a' IHa'].\n    - reflexivity.\n    - cbv [value_at_weight]. simpl. destruct (fst x =? d) eqn:E.\n      + exfalso. apply H. simpl. lia.\n      + apply IHa'. intros H'. apply H. simpl. right. apply H'.\n  Qed.\n\n  Definition dedup_weights a :=\n    map (fun d => (d, value_at_weight a d)) (nodupb Z.eqb (map fst a)).\n\n  Lemma funs_same (l : list Z) (a0 : Z*Z) (a' : list (Z*Z)) :\n  ~ In (fst a0) l ->\n  forall d, In d l ->\n  (fun d : Z => (d, value_at_weight (a0 :: a') d)) d = (fun d => (d, value_at_weight a' d)) d.\n  Proof.\n    intros H d H'. simpl. f_equal. cbv [value_at_weight]. simpl. destruct (fst a0 =? d) eqn:E.\n    - exfalso. rewrite Z.eqb_eq in E. subst. apply (H H').\n    - reflexivity.\n  Qed.\n\n  Lemma eval_dedup_weights a : Associational.eval (dedup_weights a) = Associational.eval a.\n  Proof.\n    induction a as [| a0 a' IHa'].\n    - reflexivity.\n    - cbv [dedup_weights]. simpl. destruct (existsb (Z.eqb (fst a0)) (nodupb Z.eqb (map fst a'))) eqn:E.\n      + apply (existsb_eqb_true_iff Z.eqb Z.eqb_eq) in E. rewrite <- (nodupb_in_iff Z.eqb Z.eqb_eq) in E.\n        apply (nodupb_split Z.eqb Z.eqb_eq) in E. destruct E as [l1 [l2 [H1 [H2 H3] ] ] ]. rewrite H1.\n        repeat rewrite map_app. rewrite (map_ext_in _ _ l1 (funs_same l1 a0 a' H2)).\n        rewrite (map_ext_in _ _ l2 (funs_same l2 a0 a' H3)). repeat rewrite Associational.eval_app. simpl.\n        repeat rewrite Associational.eval_cons. simpl. rewrite <- IHa'. simpl. rewrite Associational.eval_nil. \n        cbv [dedup_weights]. rewrite H1. repeat rewrite map_app. repeat rewrite Associational.eval_app.\n        cbv [value_at_weight]. simpl. rewrite Z.eqb_refl. simpl. cbv [Associational.eval]. simpl. lia.\n      + simpl. apply (existsb_eqb_false_iff Z.eqb Z.eqb_eq) in E. rewrite (map_ext_in _ _ _ (funs_same _ _ _ E)).\n        repeat rewrite Associational.eval_cons. simpl. rewrite <- IHa'. cbv [dedup_weights]. f_equal. f_equal.\n        rewrite <- (nodupb_in_iff Z.eqb Z.eqb_eq) in E. cbv [value_at_weight]. simpl. rewrite Z.eqb_refl.\n        apply not_in_value_0 in E. cbv [value_at_weight] in E. simpl. rewrite E. lia.\n  Qed.\n\n  Section Carries.\n    Definition carryterm (w fw:Z) (t:Z * Z) :=\n      if (Z.eqb (fst t) w)\n      then dlet_nd t2 := snd t in\n           dlet_nd d2 := t2 / fw in\n           dlet_nd m2 := t2 mod fw in\n           [(w * fw, d2);(w,m2)]\n      else [t].\n\n    Lemma eval_carryterm w fw (t:Z * Z) (fw_nonzero:fw<>0):\n      eval (carryterm w fw t) = eval [t].\n    Proof using Type*.\n      cbv [carryterm Let_In]; break_match; push; [|trivial].\n      pose proof (Z.div_mod (snd t) fw fw_nonzero).\n      rewrite Z.eqb_eq in *.\n      nsatz.\n    Qed. Hint Rewrite eval_carryterm using auto : push_eval.\n\n    Definition carry (w fw:Z) (p:list (Z * Z)):=\n      flat_map (carryterm w fw) p.\n\n    Lemma eval_carry w fw p (fw_nonzero:fw<>0):\n      eval (carry w fw p) = eval p.\n    Proof using Type*. cbv [carry]; induction p; push; nsatz. Qed.\n    Hint Rewrite eval_carry using auto : push_eval.\n\n  Definition borrowterm (w fw:Z) (t:Z * Z) :=\n      let quot := w / fw in\n      if (Z.eqb (fst t) w)\n        then [(quot, snd t * fw)]\n        else [t].\n\n  Lemma eval_borrowterm w fw (t:Z * Z) (fw_nz:fw<>0) (w_fw:w mod fw = 0) :\n        Associational.eval (borrowterm w fw t) = Associational.eval [t].\n  Proof using Type*.\n    cbv [borrowterm Let_In]; break_match; push; [|trivial].\n    pose proof (Z.div_mod (snd t) fw fw_nz).\n    rewrite Z.eqb_eq in *.\n    ring_simplify. rewrite Z.mul_comm. rewrite Z.mul_assoc. rewrite <- Z_div_exact_full_2; lia.\n  Qed.\n\n  Definition borrow (w fw:Z) (p:list (Z*Z)) :=\n    flat_map (borrowterm w fw) p.\n\n  Lemma eval_borrow w fw p (fw_nz:fw<>0) (w_fw:w mod fw = 0):\n        Associational.eval (borrow w fw p) = Associational.eval p.\n  Proof using Type*.\n    cbv [borrow borrowterm]. induction p as [| a p' IHp'].\n    - trivial.\n    - push. destruct (fst a =? w) eqn:E.\n      + rewrite Z.mul_comm. rewrite <- Z.mul_assoc. rewrite <- Z_div_exact_full_2; lia.\n      + rewrite IHp'. lia.\n  Qed.\n\n  End Carries.\nEnd Associational.\n\nModule Weight.\n  Section Weight.\n    Context weight\n            (weight_0 : weight 0%nat = 1)\n            (weight_positive : forall i, 0 < weight i)\n            (weight_multiples : forall i, weight (S i) mod weight i = 0)\n            (weight_divides : forall i : nat, 0 < weight (S i) / weight i).\n\n    Lemma weight_multiples_full' j : forall i, weight (i+j) mod weight i = 0.\n    Proof using weight_positive weight_multiples.\n      induction j; intros;\n        repeat match goal with\n               | _ => rewrite Nat.add_succ_r\n               | _ => rewrite IHj\n               | |- context [weight (S ?x) mod weight _] =>\n                 rewrite (Z.div_mod (weight (S x)) (weight x)), weight_multiples by auto with zarith\n               | _ => progress autorewrite with push_Zmod natsimplify zsimplify_fast\n               | _ => reflexivity\n               end.\n    Qed.\n\n    Lemma weight_multiples_full j i : (i <= j)%nat -> weight j mod weight i = 0.\n    Proof using weight_positive weight_multiples.\n      intros; replace j with (i + (j - i))%nat by lia.\n      apply weight_multiples_full'.\n    Qed.\n\n    Lemma weight_divides_full j i : (i <= j)%nat -> 0 < weight j / weight i.\n    Proof using weight_positive weight_multiples. auto using Z.gt_lt, Z.div_positive_gt_0, weight_multiples_full with zarith. Qed.\n\n    Lemma weight_div_mod j i : (i <= j)%nat -> weight j = weight i * (weight j / weight i).\n    Proof using weight_positive weight_multiples. intros. apply Z.div_exact; auto using weight_multiples_full with zarith. Qed.\n\n    Lemma weight_mod_pull_div n x :\n      x mod weight (S n) / weight n =\n      (x / weight n) mod (weight (S n) / weight n).\n    Proof using weight_positive weight_multiples weight_divides.\n      replace (weight (S n)) with (weight n * (weight (S n) / weight n));\n      repeat match goal with\n             | _ => progress autorewrite with zsimplify_fast\n             | _ => rewrite Z.mul_div_eq_full by auto with zarith\n             | _ => rewrite Z.mul_div_eq' by auto with zarith\n             | _ => rewrite Z.mod_pull_div\n             | _ => rewrite weight_multiples by auto with zarith\n             | _ => solve [auto with zarith]\n             end.\n    Qed.\n\n    Lemma weight_div_pull_div n x :\n      x / weight (S n) =\n      (x / weight n) / (weight (S n) / weight n).\n    Proof using weight_positive weight_multiples weight_divides.\n      replace (weight (S n)) with (weight n * (weight (S n) / weight n));\n      repeat match goal with\n             | _ => progress autorewrite with zdiv_to_mod zsimplify_fast\n             | _ => rewrite Z.mul_div_eq_full by auto with zarith\n             | _ => rewrite Z.mul_div_eq' by auto with zarith\n             | _ => rewrite Z.div_div by auto with zarith\n             | _ => rewrite weight_multiples by assumption\n             | _ => solve [auto with zarith]\n             end.\n    Qed.\n  End Weight.\nEnd Weight.\n\nModule Positional.\n  Import Weight.\n  Section Positional.\n  Context (weight : nat -> Z)\n          (weight_0 : weight 0%nat = 1)\n          (weight_nz : forall i, weight i <> 0).\n\n  Definition to_associational (n:nat) (xs:list Z) : list (Z*Z)\n    := combine (map weight (List.seq 0 n)) xs.\n  Definition eval n x := Associational.eval (@to_associational n x).\n  Lemma eval_to_associational n x :\n    Associational.eval (@to_associational n x) = eval n x.\n  Proof using Type. trivial.                                             Qed.\n  Hint Rewrite @eval_to_associational : push_eval.\n  Lemma eval_nil n : eval n [] = 0.\n  Proof using Type. cbv [eval to_associational]. rewrite combine_nil_r. reflexivity. Qed.\n  Hint Rewrite eval_nil : push_eval.\n  Lemma eval0 p : eval 0 p = 0.\n  Proof using Type. cbv [eval to_associational]. reflexivity. Qed.\n  Hint Rewrite eval0 : push_eval.\n\n  Lemma eval_snoc n m x y : n = length x -> m = S n -> eval m (x ++ [y]) = eval n x + weight n * y.\n  Proof using Type.\n    cbv [eval to_associational]; intros; subst n m.\n    rewrite seq_snoc, map_app.\n    rewrite combine_app_samelength by distr_length.\n    autorewrite with push_eval. simpl.\n    autorewrite with push_eval cancel_pair; ring.\n  Qed.\n\n  Lemma eval_snoc_S n x y : n = length x -> eval (S n) (x ++ [y]) = eval n x + weight n * y.\n  Proof using Type. intros; erewrite eval_snoc; eauto. Qed.\n  Hint Rewrite eval_snoc_S using (solve [distr_length]) : push_eval.\n\n  (* SKIP over this: zeros, add_to_nth *)\n  Local Ltac push := autorewrite with push_eval push_map distr_length\n    push_flat_map push_fold_right push_nth_default cancel_pair natsimplify.\n  Definition zeros n : list Z := repeat 0 n.\n  Lemma length_zeros n : length (zeros n) = n. Proof using Type. clear; cbv [zeros]; distr_length. Qed.\n  Hint Rewrite length_zeros : distr_length.\n  Lemma eval_combine_zeros ls n : Associational.eval (List.combine ls (zeros n)) = 0.\n  Proof using Type.\n    clear; cbv [Associational.eval zeros].\n    revert n; induction ls, n; simpl; rewrite ?IHls; nsatz.   Qed.\n  Lemma eval_zeros n : eval n (zeros n) = 0.\n  Proof using Type. apply eval_combine_zeros.                            Qed.\n  Definition add_to_nth i x (ls : list Z) : list Z\n    := ListUtil.update_nth i (fun y => x + y) ls.\n  Lemma length_add_to_nth i x ls : length (add_to_nth i x ls) = length ls.\n  Proof using Type. clear; cbv [add_to_nth]; distr_length. Qed.\n  Hint Rewrite length_add_to_nth : distr_length.\n  Lemma eval_add_to_nth (n:nat) (i:nat) (x:Z) (xs:list Z) (H:(i<length xs)%nat)\n        (Hn : length xs = n) (* N.B. We really only need [i < Nat.min n (length xs)] *) :\n    eval n (add_to_nth i x xs) = weight i * x + eval n xs.\n  Proof using Type.\n    subst n.\n    cbv [eval to_associational add_to_nth].\n    rewrite ListUtil.combine_update_nth_r at 1.\n    rewrite <-(update_nth_id i (List.combine _ _)) at 2.\n    rewrite <-!(ListUtil.splice_nth_equiv_update_nth_update _ _\n      (weight 0, 0)) by (push; lia); cbv [ListUtil.splice_nth id].\n    repeat match goal with\n           | _ => progress push\n           | _ => progress break_match\n           | _ => progress (apply Zminus_eq; ring_simplify)\n           | _ => rewrite <-ListUtil.map_nth_default_always\n           end; lia.                                          Qed.\n  Hint Rewrite @eval_add_to_nth eval_zeros eval_combine_zeros : push_eval.\n  Lemma add_to_nth_zero i l : add_to_nth i 0 l = l.\n  Proof. cbv [add_to_nth]. apply update_nth_id_eq. reflexivity. Qed.\n\n  Lemma zeros_ext_map {A} n (p : list A) : length p = n -> zeros n = map (fun _ => 0) p.\n  Proof using Type. cbv [zeros]; intro; subst; induction p; cbn; congruence. Qed.\n\n  Lemma eval_mul_each (n:nat) (a:Z) (p:list Z)\n        (Hn : length p = n)\n    : eval n (List.map (fun x => a*x) p) = a*eval n p.\n  Proof using Type.\n    clear -Hn.\n    transitivity (Associational.eval (map (fun t => (1 * fst t, a * snd t)) (to_associational n p))).\n    { cbv [eval to_associational]; rewrite !combine_map_r.\n      f_equal; apply map_ext; intros; f_equal; nsatz. }\n    { rewrite Associational.eval_map_mul, eval_to_associational; nsatz. }\n  Qed.\n  Hint Rewrite eval_mul_each : push_eval.\n\n  Definition place (t:Z*Z) (i:nat) : nat * Z :=\n    nat_rect\n      (fun _ => unit -> (nat * Z)%type)\n      (fun _ => (O, fst t * snd t))\n      (fun i' place_i' _\n       => let i := S i' in\n          if (fst t mod weight i =? 0)\n          then (i, let c := fst t / weight i in c * snd t)\n          else place_i' tt)\n      i\n      tt.\n\n  Lemma place_in_range (t:Z*Z) (n:nat) : (fst (place t n) < S n)%nat.\n  Proof using Type. induction n; cbv [place nat_rect] in *; break_match; autorewrite with cancel_pair; try lia. Qed.\n  Lemma weight_place t i : weight (fst (place t i)) * snd (place t i) = fst t * snd t.\n  Proof using weight_nz weight_0. induction i; cbv [place nat_rect] in *; break_match; push;\n    repeat match goal with |- context[?a/?b] =>\n      unique pose proof (Z_div_exact_full_2 a b ltac:(auto) ltac:(auto))\n           end; nsatz.                                        Qed.\n  Hint Rewrite weight_place : push_eval.\n  Lemma weight_add_mod (weight_mul : forall i, weight (S i) mod weight i = 0) i j\n    : weight (i + j) mod weight i = 0.\n  Proof using weight_nz.\n    rewrite Nat.add_comm.\n    induction j as [|[|j] IHj]; cbn [Nat.add] in *;\n      eauto using Z_mod_same_full, Z.mod_mod_trans.\n  Qed.\n  Lemma weight_mul_iff (weight_pos : forall i, 0 < weight i) (weight_mul : forall i, weight (S i) mod weight i = 0) i j\n    : weight i mod weight j = 0 <-> ((j < i)%nat \\/ forall k, (i <= k <= j)%nat -> weight k = weight j).\n  Proof using weight_nz.\n    split.\n    { destruct (dec (j < i)%nat); [ left; lia | intro H; right; revert H ].\n      assert (j = (j - i) + i)%nat by lia.\n      generalize dependent (j - i)%nat; intro jmi; intros ? H0.\n      subst j.\n      destruct jmi as [|j]; [ intros k ?; assert (k = i) by lia; subst; f_equal; lia | ].\n      induction j as [|j IH]; cbn [Nat.add] in *.\n      { intros k ?; assert (k = i \\/ k = S i) by lia; destruct_head'_or; subst;\n          eauto using Z.mod_mod_0_0_eq_pos. }\n      { specialize_by lia.\n        { pose proof (weight_mul (S (j + i))) as H.\n          specialize_by eauto using Z.mod_mod_trans with lia.\n          intros k H'; destruct (dec (k = S (S (j + i)))); subst;\n            try rewrite IH by eauto using Z.mod_mod_trans with lia;\n            eauto using Z.mod_mod_trans, Z.mod_mod_0_0_eq_pos with lia.\n          rewrite (IH i) in * by lia.\n          eauto using Z.mod_mod_trans, Z.mod_mod_0_0_eq_pos with lia. } } }\n    { destruct (dec (j < i)%nat) as [H|H]; [ intros _ | intros [H'|H']; try lia ].\n      { assert (i = j + (i - j))%nat by lia.\n        generalize dependent (i - j)%nat; intro imj; intros.\n        subst i.\n        apply weight_add_mod; auto. }\n      { erewrite H', Z_mod_same_full by lia; lia. } }\n  Qed.\n  Lemma weight_div_from_pos_mul (weight_pos : forall i, 0 < weight i) (weight_mul : forall i, weight (S i) mod weight i = 0)\n    : forall i, 0 < weight (S i) / weight i.\n  Proof using weight_nz.\n    intro i; generalize (weight_mul i) (weight_mul (S i)).\n    Z.div_mod_to_quot_rem; nia.\n  Qed.\n  Lemma place_weight n (weight_pos : forall i, 0 < weight i) (weight_mul : forall i, weight (S i) mod weight i = 0)\n        (weight_unique : forall i j, (i <= n)%nat -> (j <= n)%nat -> weight i = weight j -> i = j)\n        i x\n    : (place (weight i, x) n) = (Nat.min i n, (weight i / weight (Nat.min i n)) * x).\n  Proof using weight_0 weight_nz.\n    cbv [place].\n    induction n as [|n IHn]; cbn; [ destruct i; cbn; rewrite ?weight_0; autorewrite with zsimplify_const; reflexivity | ].\n    destruct (dec (i < S n)%nat);\n      break_innermost_match; cbn [fst snd] in *; Z.ltb_to_lt; [ | rewrite IHn | | rewrite IHn ];\n        break_innermost_match;\n        rewrite ?Min.min_l in * by lia;\n        rewrite ?Min.min_r in * by lia;\n        eauto with lia.\n    { rewrite weight_mul_iff in * by auto.\n      destruct_head'_or; try lia.\n      assert (S n = i).\n      { apply weight_unique; try lia.\n        symmetry; eauto with lia. }\n      subst; reflexivity. }\n    { rewrite weight_mul_iff in * by auto.\n      exfalso; intuition eauto with lia. }\n  Qed.\n\n  Definition from_associational n (p:list (Z*Z)) :=\n    List.fold_right (fun t ls =>\n      dlet_nd p := place t (pred n) in\n      add_to_nth (fst p) (snd p) ls ) (zeros n) p.\n  Lemma eval_from_associational n p (n_nz:n<>O \\/ p = nil) :\n    eval n (from_associational n p) = Associational.eval p.\n  Proof using weight_0 weight_nz. destruct n_nz; [ induction p | subst p ];\n  cbv [from_associational Let_In] in *; push; try\n  pose proof place_in_range a (pred n); try lia; try nsatz;\n  apply fold_right_invariant; cbv [zeros add_to_nth];\n  intros; rewrite ?map_length, ?List.repeat_length, ?seq_length, ?length_update_nth;\n  destruct n; cbn [pred] in *; try lia.                     Qed.\n  Hint Rewrite @eval_from_associational : push_eval.\n  Lemma length_from_associational n p : length (from_associational n p) = n.\n  Proof using Type. cbv [from_associational Let_In]. apply fold_right_invariant; intros; distr_length. Qed.\n  Hint Rewrite length_from_associational : distr_length.\n\n  Definition extend_to_length (n_in n_out : nat) (p:list Z) : list Z :=\n    p ++ zeros (n_out - n_in).\n  Lemma eval_extend_to_length n_in n_out p :\n    length p = n_in -> (n_in <= n_out)%nat ->\n    eval n_out (extend_to_length n_in n_out p) = eval n_in p.\n  Proof using Type.\n    cbv [eval extend_to_length to_associational]; intros.\n    replace (seq 0 n_out) with (seq 0 (n_in + (n_out - n_in))) by (f_equal; lia).\n    rewrite seq_add, map_app, combine_app_samelength, Associational.eval_app;\n      push; lia.\n  Qed.\n  Hint Rewrite eval_extend_to_length : push_eval.\n  Lemma length_extend_to_length n_in n_out p :\n    length p = n_in -> (n_in <= n_out)%nat ->\n    length (extend_to_length n_in n_out p) = n_out.\n  Proof using Type. clear; cbv [extend_to_length]; intros; distr_length.        Qed.\n  Hint Rewrite length_extend_to_length : distr_length.\n\n  Definition drop_high_to_length (n : nat) (p:list Z) : list Z :=\n    firstn n p.\n  Lemma length_drop_high_to_length n p :\n    length (drop_high_to_length n p) = Nat.min n (length p).\n  Proof using Type. clear; cbv [drop_high_to_length]; intros; distr_length.        Qed.\n  Hint Rewrite length_drop_high_to_length : distr_length.\n\n  Section mulmod.\n    Context (s:Z) (s_nz:s <> 0)\n            (c:list (Z*Z))\n            (m_nz:s - Associational.eval c <> 0).\n    Definition mulmod (n:nat) (a b:list Z) : list Z\n      := let a_a := to_associational n a in\n         let b_a := to_associational n b in\n         let ab_a := Associational.mul a_a b_a in\n         let abm_a := Associational.repeat_reduce n s c ab_a in\n         from_associational n abm_a.\n    Lemma eval_mulmod n (f g:list Z)\n          (Hf : length f = n) (Hg : length g = n) :\n      eval n (mulmod n f g) mod (s - Associational.eval c)\n      = (eval n f * eval n g) mod (s - Associational.eval c).\n    Proof using m_nz s_nz weight_0 weight_nz. cbv [mulmod]; push; trivial.\n    destruct f, g; simpl in *; [ right; subst n | left; try lia.. ].\n    clear; cbv -[Associational.repeat_reduce].\n    induction c as [|?? IHc]; simpl; trivial.                 Qed.\n\n    Definition squaremod (n:nat) (a:list Z) : list Z\n      := let a_a := to_associational n a in\n         let aa_a := Associational.reduce_square s c a_a in\n         let aam_a := Associational.repeat_reduce (pred n) s c aa_a in\n         from_associational n aam_a.\n    Lemma eval_squaremod n (f:list Z)\n          (Hf : length f = n) :\n      eval n (squaremod n f) mod (s - Associational.eval c)\n      = (eval n f * eval n f) mod (s - Associational.eval c).\n    Proof using m_nz s_nz weight_0 weight_nz. cbv [squaremod]; push; trivial.\n    destruct f; simpl in *; [ right; subst n; reflexivity | left; try lia.. ]. Qed.\n  End mulmod.\n  Hint Rewrite @eval_mulmod @eval_squaremod : push_eval.\n\n  Definition add (n:nat) (a b:list Z) : list Z\n    := let a_a := to_associational n a in\n       let b_a := to_associational n b in\n       from_associational n (a_a ++ b_a).\n  Lemma eval_add n (f g:list Z)\n        (Hf : length f = n) (Hg : length g = n) :\n    eval n (add n f g) = (eval n f + eval n g).\n  Proof using weight_0 weight_nz. cbv [add]; push; trivial. destruct n; auto.          Qed.\n  Hint Rewrite @eval_add : push_eval.\n  Lemma length_add n f g\n        (Hf : length f = n) (Hg : length g = n) :\n    length (add n f g) = n.\n  Proof using Type. clear -Hf Hf; cbv [add]; distr_length.               Qed.\n  Hint Rewrite @length_add : distr_length.\n\n  Section Carries.\n    Definition carry n m (index:nat) (p:list Z) : list Z :=\n      from_associational\n        m (@Associational.carry (weight index)\n                                (weight (S index) / weight index)\n                                (to_associational n p)).\n\n    Lemma length_carry n m index p : length (carry n m index p) = m.\n    Proof using Type. cbv [carry]; distr_length. Qed.\n    Hint Rewrite length_carry : distr_length.\n    Lemma eval_carry n m i p: (n <> 0%nat) -> (m <> 0%nat) ->\n                              weight (S i) / weight i <> 0 ->\n      eval m (carry n m i p) = eval n p.\n    Proof using weight_0 weight_nz.\n      cbv [carry]; intros; push; [|tauto].\n      rewrite @Associational.eval_carry by eauto.\n      apply eval_to_associational.\n    Qed. Hint Rewrite @eval_carry : push_eval.\n\n    Definition carry_reduce n (s:Z) (c:list (Z * Z))\n               (index:nat) (p : list Z) :=\n      from_associational\n        n (Associational.reduce\n             s c (to_associational (S n) (@carry n (S n) index p))).\n\n    Lemma eval_carry_reduce n s c index p :\n      (s <> 0) -> (s - Associational.eval c <> 0) -> (n <> 0%nat) ->\n      (weight (S index) / weight index <> 0) ->\n      eval n (carry_reduce n s c index p) mod (s - Associational.eval c)\n      = eval n p mod (s - Associational.eval c).\n    Proof using weight_0 weight_nz. cbv [carry_reduce]; intros; push; auto.            Qed.\n    Hint Rewrite @eval_carry_reduce : push_eval.\n    Lemma length_carry_reduce n s c index p\n      : length p = n -> length (carry_reduce n s c index p) = n.\n    Proof using Type. cbv [carry_reduce]; distr_length.                  Qed.\n    Hint Rewrite @length_carry_reduce : distr_length.\n\n    (* N.B. It is important to reverse [idxs] here, because fold_right is\n      written such that the first terms in the list are actually used\n      last in the computation. For example, running:\n\n      `Eval cbv - [Z.add] in (fun a b c d => fold_right Z.add d [a;b;c]).`\n\n      will produce [fun a b c d => (a + (b + (c + d)))].*)\n    Definition chained_carries n s c p (idxs : list nat) :=\n      fold_right (fun a b => carry_reduce n s c a b) p (rev idxs).\n\n    Lemma eval_chained_carries n s c p idxs :\n      (s <> 0) -> (s - Associational.eval c <> 0) -> (n <> 0%nat) ->\n      (forall i, In i idxs -> weight (S i) / weight i <> 0) ->\n      eval n (chained_carries n s c p idxs) mod (s - Associational.eval c)\n      = eval n p mod (s - Associational.eval c).\n    Proof using Type*.\n      cbv [chained_carries]; intros; push.\n      apply fold_right_invariant; [|intro; rewrite <-in_rev];\n        destruct n; intros; push; auto.\n    Qed. Hint Rewrite @eval_chained_carries : push_eval.\n    Lemma length_chained_carries n s c p idxs\n      : length p = n -> length (@chained_carries n s c p idxs) = n.\n    Proof using Type.\n      intros; cbv [chained_carries]; induction (rev idxs) as [|x xs IHxs];\n        cbn [fold_right]; distr_length.\n    Qed. Hint Rewrite @length_chained_carries : distr_length.\n\n    (* Reverse of [eval]; translate from Z to basesystem by putting\n    everything in first digit and then carrying. *)\n    Definition encode n s c (x : Z) : list Z :=\n      chained_carries n s c (from_associational n [(1,x)]) (seq 0 n).\n    Lemma eval_encode n s c x :\n      (s <> 0) -> (s - Associational.eval c <> 0) -> (n <> 0%nat) ->\n      (forall i, In i (seq 0 n) -> weight (S i) / weight i <> 0) ->\n      eval n (encode n s c x) mod (s - Associational.eval c)\n      = x mod (s - Associational.eval c).\n    Proof using Type*. cbv [encode]; intros; push; auto; f_equal; lia. Qed.\n    Lemma length_encode n s c x\n      : length (encode n s c x) = n.\n    Proof using Type. cbv [encode]; repeat distr_length.                 Qed.\n  End Carries.\n  Hint Rewrite @eval_encode @eval_carry @eval_carry_reduce @eval_chained_carries : push_eval.\n  Hint Rewrite @length_encode @length_carry @length_carry_reduce @length_chained_carries : distr_length.\n\n  Section sub.\n    Context (n:nat)\n            (s:Z) (s_nz:s <> 0)\n            (c:list (Z * Z))\n            (m_nz:s - Associational.eval c <> 0)\n            (balance:list Z)\n            (length_balance:length balance = n)\n            (eval_balance:eval n balance mod (s - Associational.eval c) = 0).\n\n    Definition negate_snd (a:list Z) : list Z\n      := let A := to_associational n a in\n         let negA := Associational.negate_snd A in\n         from_associational n negA.\n\n    Definition scmul (x:Z) (a:list Z) : list Z\n      := let A := to_associational n a in\n         let R := Associational.mul A [(1, x)] in\n         from_associational n R.\n\n    Definition sub (a b:list Z) : list Z\n      := let ca := add n balance a in\n         let _b := negate_snd b in\n         add n ca _b.\n\n    Lemma length_scmul x a : length (scmul x a) = n.\n    Proof using Type. cbv [scmul]; now push. Qed.\n    Hint Rewrite length_scmul : distr_length.\n\n    Lemma eval_scmul x a : eval n (scmul x a) = x * eval n a.\n    Proof using weight_0 weight_nz.\n      clear -weight_0 weight_nz.\n      destruct (zerop n) as [->|]; [ cbn; lia | ].\n      cbv [scmul]; push; try lia.\n    Qed.\n    Hint Rewrite eval_scmul : push_eval.\n\n    Hint Rewrite eval_balance : push_eval.\n    Lemma eval_sub a b\n      : (forall i, In i (seq 0 n) -> weight (S i) / weight i <> 0) ->\n        (List.length a = n) -> (List.length b = n) ->\n        eval n (sub a b) mod (s - Associational.eval c)\n        = (eval n a - eval n b) mod (s - Associational.eval c).\n    Proof using s_nz m_nz weight_0 weight_nz eval_balance length_balance.\n      destruct (zerop n) as [->|]; try reflexivity.\n      intros; cbv [sub negate_snd]; push; repeat distr_length;\n        eauto with lia.\n      push_Zmod; push; pull_Zmod; push_Zmod; pull_Zmod; distr_length; eauto.\n    Qed.\n    Hint Rewrite eval_sub : push_eval.\n    Lemma length_sub a b\n      : length a = n -> length b = n ->\n        length (sub a b) = n.\n    Proof using length_balance. intros; cbv [sub scmul negate_snd]; repeat distr_length. Qed.\n    Hint Rewrite length_sub : distr_length.\n    Definition opp (a:list Z) : list Z\n      := sub (zeros n) a.\n    Lemma eval_opp\n          (a:list Z)\n      : (length a = n) ->\n        (forall i, In i (seq 0 n) -> weight (S i) / weight i <> 0) ->\n        eval n (opp a) mod (s - Associational.eval c)\n        = (- eval n a) mod (s - Associational.eval c).\n    Proof using m_nz s_nz weight_0 weight_nz eval_balance length_balance. intros; cbv [opp]; push; distr_length; auto.       Qed.\n    Lemma length_opp a\n      : length a = n -> length (opp a) = n.\n    Proof using length_balance. cbv [opp]; intros; repeat distr_length.            Qed.\n  End sub.\n  Hint Rewrite @eval_scmul @eval_opp @eval_sub : push_eval.\n  Hint Rewrite @length_scmul @length_sub @length_opp : distr_length.\n\n  Section select.\n    Definition zselect (mask cond:Z) (p:list Z) :=\n      dlet t := Z.zselect cond 0 mask in List.map (Z.land t) p.\n\n    Definition select (cond:Z) (if_zero if_nonzero:list Z) :=\n      List.map (fun '(p, q) => Z.zselect cond p q) (List.combine if_zero if_nonzero).\n\n    Lemma map_and_0 n (p:list Z) : length p = n -> map (Z.land 0) p = zeros n.\n    Proof using Type.\n      intro; subst; induction p as [|x xs IHxs]; [reflexivity | ].\n      cbn; f_equal; auto.\n    Qed.\n    Lemma eval_zselect n mask cond p (H:List.map (Z.land mask) p = p) :\n      length p = n\n      -> eval n (zselect mask cond p) =\n         if dec (cond = 0) then 0 else eval n p.\n    Proof using Type.\n      cbv [zselect Let_In].\n      rewrite Z.zselect_correct; break_match.\n      { intros; erewrite map_and_0 by eassumption. apply eval_zeros. }\n      { rewrite H; reflexivity. }\n    Qed.\n    Lemma length_zselect mask cond p :\n      length (zselect mask cond p) = length p.\n    Proof using Type. clear dependent weight. cbv [zselect Let_In]; break_match; intros; distr_length. Qed.\n\n    (** We need an explicit equality proof here, because sometimes it\n        matters that we retain the same bounds when selecting.  The\n        alternative (weaker) lemma is [eval_select], where we only\n        talk about equality under [eval]. *)\n    Lemma select_eq cond n : forall p q,\n        length p = n -> length q = n ->\n        select cond p q = if dec (cond = 0) then p else q.\n    Proof using weight.\n      cbv [select]; induction n; intros;\n        destruct p; distr_length;\n          destruct q; distr_length;\n        repeat match goal with\n               | _ => progress autorewrite with push_combine push_map\n               | _ => rewrite IHn by distr_length\n               | _ => rewrite Z.zselect_correct\n               | _ => break_match; reflexivity\n               end.\n    Qed.\n    Lemma eval_select n cond p q :\n      length p = n -> length q = n\n      -> eval n (select cond p q) =\n         if dec (cond = 0) then eval n p else eval n q.\n    Proof using weight.\n      intros; erewrite select_eq by eauto.\n      break_match; reflexivity.\n    Qed.\n    Lemma length_select_min cond p q :\n      length (select cond p q) = Nat.min (length p) (length q).\n    Proof using Type. clear dependent weight. cbv [select Let_In]; distr_length. Qed.\n    Hint Rewrite length_select_min : distr_length.\n    Lemma length_select n cond p q :\n      length p = n -> length q = n ->\n      length (select cond p q) = n.\n    Proof using Type. clear dependent weight. distr_length; lia **. Qed.\n\n    Lemma select_push cond a b f (H : length a = length b) :\n      f (select cond a b) = Z.zselect cond (f a) (f b).\n    Proof using Type. unfold select, Z.zselect.\n                      destruct (Z.eqb_spec cond 0); subst; simpl.\n                      - rewrite (map_ext _ fst), ListUtil.map_fst_combine, <- H, firstn_all; reflexivity.\n                      - rewrite (map_ext _ snd), ListUtil.map_snd_combine, H, firstn_all; reflexivity. Qed.\n  End select.\nEnd Positional.\n(* Hint Rewrite disappears after the end of a section *)\n#[global]\nHint Rewrite length_zeros length_add_to_nth length_from_associational @length_add @length_carry_reduce @length_carry @length_chained_carries @length_encode @length_scmul @length_sub @length_opp @length_select @length_zselect @length_select_min @length_extend_to_length @length_drop_high_to_length : distr_length.\n#[global]\nHint Rewrite @eval_zeros @eval_nil @eval_snoc_S @eval_select @eval_zselect @eval_extend_to_length using solve [auto; distr_length]: push_eval.\nSection Positional_nonuniform.\n  Context (weight weight' : nat -> Z).\n\n  Lemma eval_hd_tl n (xs:list Z) :\n    length xs = n ->\n    eval weight n xs = weight 0%nat * hd 0 xs + eval (fun i => weight (S i)) (pred n) (tl xs).\n  Proof using Type.\n    intro; subst; destruct xs as [|x xs]; [ cbn; lia | ].\n    cbv [eval to_associational Associational.eval] in *; cbn.\n    rewrite <- map_S_seq; reflexivity.\n  Qed.\n\n  Lemma eval_cons n (x:Z) (xs:list Z) :\n    length xs = n ->\n    eval weight (S n) (x::xs) = weight 0%nat * x + eval (fun i => weight (S i)) n xs.\n  Proof using Type. intro; subst; apply eval_hd_tl; reflexivity. Qed.\n\n  Lemma eval_weight_mul n p k :\n    (forall i, In i (seq 0 n) -> weight i = k * weight' i) ->\n    eval weight n p = k * eval weight' n p.\n  Proof using Type.\n    setoid_rewrite List.in_seq.\n    revert n weight weight'; induction p as [|x xs IHxs], n as [|n]; intros weight weight' Hwt;\n      cbv [eval to_associational Associational.eval] in *; cbn in *; try lia.\n    rewrite Hwt, Z.mul_add_distr_l, Z.mul_assoc by lia.\n    erewrite <- !map_S_seq, IHxs; [ reflexivity | ]; cbn; eauto with lia.\n  Qed.\nEnd Positional_nonuniform.\n#[global]\nHint Rewrite @eval_cons using solve [auto; distr_length]: push_eval.\nEnd Positional.\n\nRecord weight_properties {weight : nat -> Z} :=\n  {\n    weight_0 : weight 0%nat = 1;\n    weight_positive : forall i, 0 < weight i;\n    weight_multiples : forall i, weight (S i) mod weight i = 0;\n    weight_divides : forall i : nat, 0 < weight (S i) / weight i;\n  }.\nGlobal Hint Resolve weight_0 weight_positive weight_multiples weight_divides : core.\n#[global]\nHint Rewrite @weight_0 @weight_multiples using solve [auto]: push_eval.\nLemma weight_nz {weight : nat -> Z} {wprops : @weight_properties weight}\n  : forall i, weight i <> 0.\nProof. intro i; pose proof (@weight_positive _ wprops i); lia. Qed.\nGlobal Hint Resolve weight_nz : core.\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/Core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933403143929, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.6605324684017418}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Sorting.Permutation.\nRequire Import Coq.Relations.Relations.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.Setoids.Setoid.\n\nLemma eq_then_Permutation: forall{A:Type} (l1 l2:list A), l1 = l2 -> Permutation l1 l2.\nProof.\nintros A l1 l2 H.\nrewrite H; reflexivity.\nQed.\n\n\nLemma app_compat_perm_latter(A:Type) : forall l a1 a2:list A, Permutation a1 a2 -> Permutation (l++a1) (l++a2).\nProof.\nintros l a1 a2 Ha.\ninduction l.\n- exact Ha.\n- apply perm_skip,IHl.\nQed.\n\nInstance app_compat_perm(A:Type) : Proper (@Permutation A ==> @Permutation A ==> @Permutation A) (@app A).\nProof.\nunfold Proper,respectful.\nintros a1 a2 Ha b1 b2 Hb.\ninduction Ha.\n- exact Hb.\n- apply perm_skip.\n  exact IHHa.\n- apply perm_trans with ((x::y::l)++b1).\n  + apply perm_swap.\n  + apply perm_skip,perm_skip,app_compat_perm_latter,Hb.\n- apply perm_trans with (l'++b2); [exact IHHa1|].\n  apply perm_trans with (l'++b1); [|exact IHHa2].\n  apply app_compat_perm_latter,Permutation_sym,Hb.\nQed.\n\nLemma Permutation_In_In: forall{A:Type} (x:A) (l1 l2:list A), Permutation l1 l2 -> In x l1 -> In x l2.\nProof.\nintros A x l1 l2 HP H.\ninduction HP.\n- exact H.\n- destruct H as [H|H].\n  + left.\n    exact H.\n  + right.\n    apply IHHP,H.\n- destruct H as [H|[H|H]].\n  + right.\n    left.\n    exact H.\n  + left.\n    exact H.\n  + right.\n    right.\n    exact H.\n- apply IHHP2,IHHP1,H.\nQed.\n\nInstance In_compat_perm(A:Type):\n    Proper (eq ==> @Permutation A ==> iff) (@In A).\nProof.\nunfold Proper,respectful.\nintros x1 x2 Hx l1 l2 Hl.\nrewrite Hx; clear x1 Hx.\nsplit.\n- apply Permutation_In_In,Hl.\n- apply Permutation_In_In.\n  symmetry.\n  exact Hl.\nQed.\n\nInstance length_compat_perm(A:Type):\n    Proper (@Permutation A ==> eq) (@length A).\nProof.\nunfold Proper, respectful.\nintros LA LB HL.\napply Permutation_length,HL.\nQed.\n\nLemma app_normalize_1:\n  forall(A:Type) (l1 l2 l3:list A),\n    (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\nintros A l1 l2 l3.\nrewrite app_assoc.\nreflexivity.\nQed.\n\nLemma app_normalize_2:\n  forall(A:Type) (a1:A) (l2 l3:list A),\n    (a1 :: l2) ++ l3 = a1 :: (l2 ++ l3).\nProof.\nintros; reflexivity.\nQed.\n\nLemma app_normalize_3:\n  forall(A:Type) (l1:list A), (nil++l1) = l1.\nProof.\nintros; reflexivity.\nQed.\n\nLtac app_normalize := repeat (\n  rewrite app_normalize_1 || \n  rewrite app_normalize_2 ||\n  rewrite app_normalize_3).\n\nLemma perm_takeit_1:\n  forall(A:Type) (target:list A) (l1 l2:list A),\n    Permutation (l1 ++ (target ++ l2)) (target ++ (l1 ++ l2)).\nProof.\nintros A target l1 l2.\nrewrite (app_assoc l1 target l2),\n  (Permutation_app_comm l1 target),\n  <-(app_assoc target l1 l2).\nreflexivity.\nQed.\n\nLemma perm_takeit_2:\n  forall(A:Type) (target:list A) (a1:A) (l2:list A),\n    Permutation (a1 :: (target ++ l2)) (target ++ (a1 :: l2)).\nProof.\nintros A target a1 l2.\napply (perm_takeit_1 _ _ (a1::nil)).\nQed.\n\nLemma perm_takeit_3:\n  forall(A:Type) (target:list A) (l1:list A),\n    Permutation (l1 ++ target) (target ++ l1).\nProof.\nintros A target l1.\napply Permutation_app_comm.\nQed.\n\nLemma perm_takeit_4:\n  forall(A:Type) (target:list A) (a1:A),\n    Permutation (a1 :: target) (target ++ (a1::nil)).\nProof.\nintros A target a1.\napply (perm_takeit_3 _ _ (a1::nil)).\nQed.\n\nLemma perm_takeit_5:\n  forall(A:Type) (target:A) (l1 l2:list A),\n    Permutation (l1 ++ (target :: l2)) (target :: (l1 ++ l2)).\nProof.\nintros A target l1 l2.\napply (perm_takeit_1 _ (target::nil)).\nQed.\n\nLemma perm_takeit_6:\n  forall(A:Type) (target:A) (a1:A) (l2:list A),\n    Permutation (a1 :: (target :: l2)) (target :: (a1 :: l2)).\nProof.\nintros A target a1 l2.\napply (perm_takeit_2 _ (target::nil)).\nQed.\n\nLemma perm_takeit_7:\n  forall(A:Type) (target:A) (l1:list A),\n    Permutation (l1 ++ (target::nil)) (target :: l1).\nProof.\nintros A target l1.\napply (perm_takeit_3 _ (target::nil)).\nQed.\n\nLemma perm_takeit_8:\n  forall(A:Type) (target:A) (a1:A),\n    Permutation (a1 :: (target::nil)) (target :: (a1::nil)).\nProof.\nintros A target a1.\napply (perm_takeit_4 _ (target::nil)).\nQed.\n\nLtac perm_simplify := app_normalize; repeat (\n  rewrite app_nil_r ||\n  match goal with\n  | [ |- Permutation ?L1 ?L1 ] => reflexivity\n  | [ |- Permutation (?A1++_) (?A1++_) ] => apply Permutation_app_head\n  | [ |- Permutation (?A1::_) (?A1::_) ] => apply perm_skip\n  | [ |- Permutation _ (?L1++_) ] => (\n      rewrite (perm_takeit_1 _ L1) at 1 ||\n      rewrite (perm_takeit_2 _ L1) at 1 ||\n      rewrite (perm_takeit_3 _ L1) at 1 ||\n      rewrite (perm_takeit_4 _ L1) at 1 )\n  | [ |- Permutation _ (?A1::_) ] => (\n      rewrite (perm_takeit_5 _ A1) at 1 ||\n      rewrite (perm_takeit_6 _ A1) at 1 ||\n      rewrite (perm_takeit_7 _ A1) at 1 ||\n      rewrite (perm_takeit_8 _ A1) at 1 )\n  | [ |- Permutation _ _ ] => fail\n  end).\n\nLtac perm :=\n  match goal with\n  | [ |- Permutation _ _ ] => perm_simplify; fail \"perm failed\"\n  | [ |- _ ] => fail \"perm can't solve this system.\"\n  end.\n\nLemma PProp_perm_select:\n  forall(A:Type) (P1 P2:A) (L1 L2:list A),\n    Permutation (P1::L1) (P2::L2) ->\n      (\n        P1 = P2 /\\ Permutation L1 L2\n      ) \\/ (\n        exists L2',\n          Permutation L2 (P1::L2') /\\\n          Permutation L1 (P2::L2')\n      ).\nProof.\nintros A P1 P2 L1 L2 HP.\nassert (HI:=in_eq P1 L1).\nrewrite HP in HI.\ndestruct HI as [HI|HI].\n- left.\n  split.\n  + symmetry.\n    exact HI.\n  + rewrite HI in HP.\n    apply Permutation_cons_inv in HP.\n    exact HP.\n- right.\n  destruct (in_split _ _ HI) as (L2A,(L2B,HL2)).\n  exists (L2A++L2B).\n  split.\n  + rewrite HL2.\n    perm.\n  + apply Permutation_cons_inv with (a:=P1).\n    rewrite HP.\n    rewrite HL2.\n    perm.\nQed.\n", "meta": {"author": "qnighy", "repo": "IPC-Coq", "sha": "5a41b4150b94c5a1947ddde1aa4c130564c9398c", "save_path": "github-repos/coq/qnighy-IPC-Coq", "path": "github-repos/coq/qnighy-IPC-Coq/IPC-Coq-5a41b4150b94c5a1947ddde1aa4c130564c9398c/IPC/MyPermutations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.6605324570634847}}
{"text": "Require Import Coinduc.\n\nRequire Import Classical.\n\nLemma Not_Infinite_Finite :\n  forall (A:Set) (l:LList A),\n   ~ Infinite l -> Finite l.\nProof.\n  intros A l H.\n  case (classic (Finite l)).\n  trivial.\n  intro; elim H ; apply Not_Finite_Infinite ; trivial.\nQed.\n\nLemma Finite_or_Infinite :\n  forall (A:Set)(l:LList A), Finite l \\/ Infinite l. \nProof.\n  intros A l; case (classic (Finite l)).\n  auto.\n  right; apply Not_Finite_Infinite ; trivial.\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/co-inductifs/SRC/finite_or_infinite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.6605324501129092}}
{"text": "Require Import HoTT HitTactics.\nRequire Import Circ.\n(* This is a non-truncated definition of a free monoid *)\n(* In this file we will prove that this construction does not give rise to a h-set. *)\nSection monoid.\nVariable A : Type.\n\nPrivate Inductive M : Type :=\n| el : A -> M\n| e  : M\n| op : M -> M -> M.\n\nInfix \"+\" := op. (* left assoc *)\nNotation \"0\" := e.\nCoercion el : A >-> M.\n\nAxiom assoc : forall (a b c : M), \n (a + b) + c = a + (b + c).\nAxiom ident_l : forall (a : M),\n  0 + a = a.\nAxiom ident_r : forall (a : M),\n  a + 0 = a.\n\nFixpoint M_ind\n  (Y : M -> Type)\n  (AY : forall a : A, Y (el a))\n  (eY : Y 0)\n  (opY : forall x y : M, Y x -> Y y -> Y (x + y))\n  (opY_assoc : forall x y z : M, forall (xY : Y x) (yY : Y y) (zY : Y z),\n      assoc x y z # opY _ _ (opY _ _ xY yY) zY = opY _ _ xY (opY _ _ yY zY))\n  (opY_ident_l : forall (x : M) (xY : Y x), \n      ident_l x # opY _ _ eY xY = xY)\n  (opY_ident_r : forall (x : M) (xY : Y x), \n      ident_r x # opY _ _ xY eY = xY)\n  (x : M)\n  {struct x}\n  : Y x :=\n  (match x return _ -> _ -> _ -> Y x with\n    | el a => fun _ _ _ => AY a\n    | e    => fun _ _ _ => eY\n    | e1 + e2 => fun _ _ _ => \n       opY e1 e2 (M_ind Y AY eY opY opY_assoc opY_ident_l opY_ident_r e1) \n                 (M_ind Y AY eY opY opY_assoc opY_ident_l opY_ident_r e2)\n  end) opY_assoc opY_ident_l opY_ident_r.\n\nAxiom M_ind_beta_assoc : forall\n  (Y : M -> Type)\n  (AY : forall a : A, Y (el a))\n  (eY : Y 0)\n  (opY : forall x y : M, Y x -> Y y -> Y (x + y))\n  (opY_assoc : forall x y z : M, forall (xY : Y x) (yY : Y y) (zY : Y z),\n      assoc x y z # opY _ _ (opY _ _ xY yY) zY = opY _ _ xY (opY _ _ yY zY))\n  (opY_ident_l : forall (x : M) (xY : Y x), \n      ident_l x # opY _ _ eY xY = xY)\n  (opY_ident_r : forall (x : M) (xY : Y x), \n      ident_r x # opY _ _ xY eY = xY)\n  (x y z : M),\n  apD (M_ind Y AY eY opY opY_assoc opY_ident_l opY_ident_r) (assoc x y z)\n  = opY_assoc x y z (M_ind Y AY eY opY opY_assoc opY_ident_l opY_ident_r x)\n                    (M_ind Y AY eY opY opY_assoc opY_ident_l opY_ident_r y)\n                    (M_ind Y AY eY opY opY_assoc opY_ident_l opY_ident_r z).\n\nAxiom M_ind_beta_ident_l : forall\n  (Y : M -> Type)\n  (AY : forall a : A, Y (el a))\n  (eY : Y 0)\n  (opY : forall x y : M, Y x -> Y y -> Y (x + y))\n  (opY_assoc : forall x y z : M, forall (xY : Y x) (yY : Y y) (zY : Y z),\n      assoc x y z # opY _ _ (opY _ _ xY yY) zY = opY _ _ xY (opY _ _ yY zY))\n  (opY_ident_l : forall (x : M) (xY : Y x), \n      ident_l x # opY _ _ eY xY = xY)\n  (opY_ident_r : forall (x : M) (xY : Y x), \n      ident_r x # opY _ _ xY eY = xY)\n  (x : M),\n  apD (M_ind Y AY eY opY opY_assoc opY_ident_l opY_ident_r) (ident_l x)\n  = opY_ident_l x (M_ind Y AY eY opY opY_assoc opY_ident_l opY_ident_r x).\n\nAxiom M_ind_beta_ident_r : forall\n  (Y : M -> Type)\n  (AY : forall a : A, Y (el a))\n  (eY : Y 0)\n  (opY : forall x y : M, Y x -> Y y -> Y (x + y))\n  (opY_assoc : forall x y z : M, forall (xY : Y x) (yY : Y y) (zY : Y z),\n      assoc x y z # opY _ _ (opY _ _ xY yY) zY = opY _ _ xY (opY _ _ yY zY))\n  (opY_ident_l : forall (x : M) (xY : Y x), \n      ident_l x # opY _ _ eY xY = xY)\n  (opY_ident_r : forall (x : M) (xY : Y x), \n      ident_r x # opY _ _ xY eY = xY)\n  (x : M),\n  apD (M_ind Y AY eY opY opY_assoc opY_ident_l opY_ident_r) (ident_r x)\n  = opY_ident_r x (M_ind Y AY eY opY opY_assoc opY_ident_l opY_ident_r x).\n\nDefinition M_rec\n  (Y : Type)\n  (AY : A -> Y)\n  (eY : Y)\n  (opY : Y -> Y -> Y)\n  (opY_assoc : forall x y z : Y, \n      opY (opY x y) z = opY x (opY y z))\n  (opY_ident_l : forall (x : Y), \n      opY eY x = x)\n  (opY_ident_r : forall (x : Y), \n      opY x eY = x)\n  (x : M) : Y.\nProof.\nsimple refine (M_ind (fun _ => Y) \n                AY\n                eY\n                (fun _ _ => opY) _ _ _ x); simpl.\n- intros ??? a b c.\n  etransitivity. apply transport_const. apply opY_assoc.\n- intros ? a.\n  etransitivity. apply transport_const. apply opY_ident_l.\n- intros ? a.\n  etransitivity. apply transport_const. apply opY_ident_r.\nDefined.\n\n\nDefinition M_rec_beta_assoc : forall\n  (Y : Type)\n  (AY : A -> Y)\n  (eY : Y)\n  (opY : Y -> Y -> Y)\n  (opY_assoc : forall x y z : Y, \n      opY (opY x y) z = opY x (opY y z))\n  (opY_ident_l : forall (x : Y), \n      opY eY x = x)\n  (opY_ident_r : forall (x : Y), \n      opY x eY = x)\n  (x y z : M),\n  ap (M_rec Y AY eY opY opY_assoc opY_ident_l opY_ident_r) (assoc x y z)\n  = opY_assoc (M_rec Y AY eY opY opY_assoc opY_ident_l opY_ident_r x)\n              (M_rec Y AY eY opY opY_assoc opY_ident_l opY_ident_r y)\n              (M_rec Y AY eY opY opY_assoc opY_ident_l opY_ident_r z).\nProof.\n  intros.\n  eapply (cancelL (transport_const _ _)).\n  etransitivity. symmetry.\n   apply apD_const.\n  unfold M_rec. simpl. \n  change (fun x0 : M =>\n   M_ind (fun _ : M => Y) AY eY (fun _ _ : M => opY)\n     (fun (x1 y0 z0 : M) (a b c : Y) =>\n      transport_const (assoc x1 y0 z0) (opY (opY a b) c) @ opY_assoc a b c)\n     (fun (x1 : M) (a : Y) =>\n      transport_const (ident_l x1) (opY eY a) @ opY_ident_l a)\n     (fun (x1 : M) (a : Y) =>\n      transport_const (ident_r x1) (opY a eY) @ opY_ident_r a) x0)\n  with (M_ind (fun _ : M => Y) AY eY (fun _ _ : M => opY)\n     (fun (x1 y0 z0 : M) (a b c : Y) =>\n      transport_const (assoc x1 y0 z0) (opY (opY a b) c) @ opY_assoc a b c)\n     (fun (x1 : M) (a : Y) =>\n      transport_const (ident_l x1) (opY eY a) @ opY_ident_l a)\n     (fun (x1 : M) (a : Y) =>\n      transport_const (ident_r x1) (opY a eY) @ opY_ident_r a)).\n  rewrite M_ind_beta_assoc. reflexivity.\nQed.\n\nDefinition M_rec_beta_ident_l : forall\n  (Y : Type)\n  (AY : A -> Y)\n  (eY : Y)\n  (opY : Y -> Y -> Y)\n  (opY_assoc : forall x y z : Y, \n      opY (opY x y) z = opY x (opY y z))\n  (opY_ident_l : forall (x : Y), \n      opY eY x = x)\n  (opY_ident_r : forall (x : Y), \n      opY x eY = x)\n  (x : M),\n  ap (M_rec Y AY eY opY opY_assoc opY_ident_l opY_ident_r) (ident_l x)\n  = opY_ident_l (M_rec Y AY eY opY opY_assoc opY_ident_l opY_ident_r x).\nProof.\n  intros.\n  eapply (cancelL (transport_const _ _)).\n  etransitivity. symmetry.\n   apply apD_const.\n  unfold M_rec. simpl. \n  rewrite M_ind_beta_ident_l. reflexivity.\nQed.\n\nDefinition M_rec_beta_ident_r : forall\n  (Y : Type)\n  (AY : A -> Y)\n  (eY : Y)\n  (opY : Y -> Y -> Y)\n  (opY_assoc : forall x y z : Y, \n      opY (opY x y) z = opY x (opY y z))\n  (opY_ident_l : forall (x : Y), \n      opY eY x = x)\n  (opY_ident_r : forall (x : Y), \n      opY x eY = x)\n  (x : M),\n  ap (M_rec Y AY eY opY opY_assoc opY_ident_l opY_ident_r) (ident_r x)\n  = opY_ident_r (M_rec Y AY eY opY opY_assoc opY_ident_l opY_ident_r x).\nProof.\n  intros.\n  eapply (cancelL (transport_const _ _)).\n  etransitivity. symmetry.\n   apply apD_const.\n  unfold M_rec. simpl. \n  rewrite M_ind_beta_ident_r. reflexivity.\nQed.\n\nEnd monoid.\n\nArguments op {_} x y.\nArguments el {_} a.\nArguments e {_}.\nInfix \"⊡\" := op (at level 80).\n\nInstance M_recursion A : HitRecursion (M A) := {\n  indTy := _; recTy := _; \n  H_inductor := (M_ind A); H_recursor := (M_rec A) }.\n\n(* (M A) is not an h-set by recursion into S1 *)\nSection monoid_sphere.\nContext `{UAxiom : Univalence}.\nVariable A : Type.\n\nDefinition f (x : S1) : x = x.\nProof.\nhinduction x.\n- exact loop.\n- etransitivity. \n  eapply (@transport_paths_FlFr S1 S1 idmap idmap).\n  hott_simpl.\nDefined.\n\nDefinition S1op (x y : S1) : S1.\nProof.\nhrecursion y.\n- exact x. (* x + base = x *)\n- apply f. \nDefined.\n\nLemma S1op_nr (x : S1) : S1op x base = x.\nProof. reflexivity. Defined.\n\nLemma S1op_nl (x : S1) : S1op base x = x.\nProof.\nhrecursion x.\n- exact loop.\n- etransitivity.\n  apply (@transport_paths_FlFr _ _ (fun x => S1op base x) idmap _ _ loop loop).\n  hott_simpl.\n  apply moveR_pM. apply moveR_pM. hott_simpl.\n  etransitivity. apply (ap_V (S1op base) loop).\n  f_ap. apply S1_rec_beta_loop.\nDefined.\n\nLemma S1op_assoc (x y z : S1) : S1op x (S1op y z) = S1op (S1op x y) z.\nProof.\nhrecursion z.\n- reflexivity.\n- etransitivity.\n  apply (@transport_paths_FlFr _ _ (fun z => S1op x (S1op y z)) (S1op (S1op x y)) _ _ loop idpath). \n  hott_simpl.\n  apply moveR_Mp. hott_simpl.\n  rewrite S1_rec_beta_loop.\n  rewrite ap_compose.\n  rewrite S1_rec_beta_loop.\n  hrecursion y.\n  + symmetry. apply S1_rec_beta_loop.\n  + apply is1type_S1.\nDefined.\n\nDefinition M_to_S : M A -> S1.\nProof.\nhrecursion.\n- intro a. apply base.\n- exact base.\n- exact S1op.\n- intros. symmetry. apply S1op_assoc.\n- apply S1op_nl.\n- apply S1op_nr.\nDefined.\n\nLemma M_S_ap : (ident_l A e) = (ident_r A e) -> idpath = loop.\nProof.\nintros H.\nenough (ap M_to_S (ident_l A e) = ap M_to_S (ident_r A e)) as H'.\n- rewrite M_rec_beta_ident_l in H'. \n  simpl in H'.\n  rewrite M_rec_beta_ident_r in H'.\n  unfold S1op_nr in H'. \n  exact H'^.\n- f_ap.\nDefined.\n\nLemma M_not_hset : IsHSet (M A) -> False.\nProof.\nintros H.\nenough (idpath = loop). \n- assert (S1_encode _ idpath = S1_encode _ (loopexp loop (pos Int.one))) as H' by f_ap.\n  rewrite S1_encode_loopexp in H'. simpl in H'. symmetry in H'.\n  apply (pos_neq_zero H').\n- apply M_S_ap.\n  apply set_path2.\nDefined.\n\nEnd monoid_sphere.\n", "meta": {"author": "co-dan", "repo": "hott-snippets", "sha": "0257a0e921c3d920a1dc58769afb2d9407123855", "save_path": "github-repos/coq/co-dan-hott-snippets", "path": "github-repos/coq/co-dan-hott-snippets/hott-snippets-0257a0e921c3d920a1dc58769afb2d9407123855/monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530937, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6604971011830587}}
{"text": "From Coq Require Import ZArith Reals Psatz.\nFrom mathcomp Require Import all_ssreflect ssralg \n              ssrnat all_algebra seq matrix.\nFrom mathcomp.analysis Require Import Rstruct.\nImport List ListNotations.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nRequire Import lemmas.\n\nOpen Scope ring_scope.\n\nDelimit Scope ring_scope with Ri.\nDelimit Scope R_scope with Re.\n\nImport Order.TTheory GRing.Theory Num.Def Num.Theory.\n\nFixpoint vec_to_list_real {n:nat} (m:nat) (v :'cV[R]_n.+1)\n   : list R := \n   match m with \n   | O => []\n   | S p => [v (@inord n p) ord0] ++ vec_to_list_real p v\n   end.\n\n\nDefinition A1_diag {n: nat} (A: 'M[R]_n.+1) : 'cV[R]_n.+1:=\n  \\col_i (1 / (A i i))%Re.\n\n\nDefinition diag_matrix_vec_mult_R {n:nat} (v1 v2 : 'cV[R]_n.+1)\n  : 'cV[R]_n.+1 :=\n  \\col_i ((nth (n.+1.-1 -i) (vec_to_list_real n.+1 v1) 0%Re) * \n          (nth (n.+1.-1 -i) (vec_to_list_real n.+1 v2) 0%Re)).\n\nLemma nth_vec_to_list_real_sub {n:nat} i m (v1 v2 :'cV[R]_n.+1) d:\n  (i < m)%nat ->\n  nth (m.-1 -i) (@vec_to_list_real n m (v1 - v2)) d = \n  nth (m.-1 -i) (@vec_to_list_real n m v1) d - \n  nth (m.-1 -i) (@vec_to_list_real n m v2) d.\nProof.\nintros.\ninduction m.\n+ by rewrite ltn0 in H.\n+ simpl. rewrite -subn_gt0 in IHm. rewrite -predn_sub in IHm.\n  destruct (m-i)%nat.\n  - by rewrite !mxE /=.\n  - simpl in IHm. by apply IHm.\nQed.\n\nLemma diag_matrix_vec_mult_diff {n:nat} (v1 v2 v3 : 'cV[R]_n.+1):\n  diag_matrix_vec_mult_R v1 v2 - diag_matrix_vec_mult_R v1 v3 = \n  diag_matrix_vec_mult_R v1 (v2 - v3).\nProof.\napply /matrixP. unfold eqrel. intros. rewrite !mxE.\nrewrite nth_vec_to_list_real_sub.\n+ rewrite -!RmultE -!RminusE. field_simplify. auto.\n+ apply ltn_ord.\nQed.\n\n\n\nLemma diag_matrix_vec_mult_diff_r {n:nat} (v1 v2 v3 : 'cV[R]_n.+1):\n  diag_matrix_vec_mult_R v1 v3 - diag_matrix_vec_mult_R v2 v3 = \n  diag_matrix_vec_mult_R (v1 - v2) v3.\nProof.\napply /matrixP. unfold eqrel. intros. rewrite !mxE.\nrewrite nth_vec_to_list_real_sub.\n+ rewrite -!RmultE -!RminusE. field_simplify. auto.\n+ apply ltn_ord.\nQed.\n\n\n\nLemma nth_vec_to_list_real {n:nat} i m (v :'cV[R]_n.+1) d:\n  (i < m)%nat ->\n  nth (m.-1 -i) (@vec_to_list_real n m v) d = v (@inord n i) ord0.\nProof.\nintros.\nelim: m i H => [ | m IHm] i H.\n+ by [].\n+ simpl.\n  rewrite leq_eqVlt in H.\n  assert ((i == m) \\/ (i < m)%nat).\n  { by apply /orP. } destruct H0.\n  - assert (i = m). { by apply /eqP. }\n    rewrite H1. simpl.\n    assert ((m - m)%nat = 0%N). \n    { apply /eqP. rewrite subn_eq0. by []. } by rewrite H2 /=.\n  - assert (nth (m.-1 - i) (vec_to_list_real m v)\n                d = v (inord i) ord0).\n    { by apply IHm. } \n    rewrite -H1. rewrite -[in RHS]predn_sub.\n    rewrite -subn_gt0 in H0. rewrite -predn_sub in H1.\n    by destruct (m - i)%nat.\nQed.\n\n\nDefinition A2_J_real {n:nat} (A: 'M[R]_n.+1): \n  'M[R]_n.+1 :=\n  \\matrix_(i,j) \n    if (i==j :> nat) then 0%Re else A i j. \n\n\n(** Define real real functional model **)\n\nDefinition x_fix {n:nat} x b (A: 'M[R]_n.+1) : \n  'cV[R]_n.+1 :=\n  let r := b - ((A2_J_real A) *m x) in\n  diag_matrix_vec_mult_R (A1_diag A) r.\n\n\n\n", "meta": {"author": "VeriNum", "repo": "iterative_methods", "sha": "7507d713cceaf91d9493dab620d3583438b8bc8a", "save_path": "github-repos/coq/VeriNum-iterative_methods", "path": "github-repos/coq/VeriNum-iterative_methods/iterative_methods-7507d713cceaf91d9493dab620d3583438b8bc8a/fma_real_func_model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.660487098874322}}
{"text": "Require Import init.\n\nRequire Import nat.\nRequire Import rat.\nRequire Import set.\nRequire Import nat_abstract.\nRequire Import int_abstract.\nRequire Import rat_abstract.\n\nRecord ArchOrderedField := make_arch_ordered {\n    aof_set : (nat → Prop) → Prop;\n    aof_plus : Plus (set_type aof_set);\n    aof_zero : Zero (set_type aof_set);\n    aof_neg : Neg (set_type aof_set);\n    aof_plus_comm : @PlusComm (set_type aof_set) aof_plus;\n    aof_plus_assoc : @PlusAssoc (set_type aof_set) aof_plus;\n    aof_plus_lid : @PlusLid (set_type aof_set) aof_plus aof_zero;\n    aof_plus_linv : @PlusLinv (set_type aof_set) aof_plus aof_zero aof_neg;\n\n    aof_mult : Mult (set_type aof_set);\n    aof_one : One (set_type aof_set);\n    aof_div : Div (set_type aof_set);\n    aof_mult_comm : @MultComm (set_type aof_set) aof_mult;\n    aof_mult_assoc : @MultAssoc (set_type aof_set) aof_mult;\n    aof_ldist : @Ldist (set_type aof_set) aof_plus aof_mult;\n    aof_mult_lid : @MultLid (set_type aof_set) aof_mult aof_one;\n    aof_mult_linv : @MultLinv (set_type aof_set) aof_zero aof_mult aof_one aof_div;\n\n    aof_le : Order (set_type aof_set);\n    aof_le_antisym : @Antisymmetric (set_type aof_set) le;\n    aof_le_trans : @Transitive (set_type aof_set) le;\n    aof_le_connex : @Connex (set_type aof_set) le;\n    aof_le_lplus : @OrderLplus (set_type aof_set) aof_plus aof_le;\n    aof_le_mult : @OrderMult (set_type aof_set) aof_zero aof_mult aof_le;\n\n    aof_not_trivial : @NotTrivial (set_type aof_set);\n    aof_arch : @Archimedean (set_type aof_set) aof_plus aof_zero aof_le;\n}.\n\nSection ArchOrderedField.\n\nVariables (A B : ArchOrderedField).\n\nLet U1 := aof_set A.\nLet A_plus := aof_plus A.\nLet A_zero := aof_zero A.\nLet A_neg := aof_neg A.\nLet A_plus_comm := aof_plus_comm A.\nLet A_plus_assoc := aof_plus_assoc A.\nLet A_plus_lid := aof_plus_lid A.\nLet A_plus_linv := aof_plus_linv A.\nLet A_mult := aof_mult A.\nLet A_one := aof_one A.\nLet A_div := aof_div A.\nLet A_mult_comm := aof_mult_comm A.\nLet A_mult_assoc := aof_mult_assoc A.\nLet A_ldist := aof_ldist A.\nLet A_mult_lid := aof_mult_lid A.\nLet A_mult_linv := aof_mult_linv A.\nLet A_le := aof_le A.\nLet A_le_antisym := aof_le_antisym A.\nLet A_le_trans := aof_le_trans A.\nLet A_le_connex := aof_le_connex A.\nLet A_le_lplus := aof_le_lplus A.\nLet A_le_mult := aof_le_mult A.\nLet A_not_trivial := aof_not_trivial A.\nLet A_arch := aof_arch A.\nLet U2 := aof_set B.\nLet B_plus := aof_plus B.\nLet B_zero := aof_zero B.\nLet B_neg := aof_neg B.\nLet B_plus_comm := aof_plus_comm B.\nLet B_plus_assoc := aof_plus_assoc B.\nLet B_plus_lid := aof_plus_lid B.\nLet B_plus_linv := aof_plus_linv B.\nLet B_mult := aof_mult B.\nLet B_one := aof_one B.\nLet B_div := aof_div B.\nLet B_mult_comm := aof_mult_comm B.\nLet B_mult_assoc := aof_mult_assoc B.\nLet B_ldist := aof_ldist B.\nLet B_mult_lid := aof_mult_lid B.\nLet B_mult_linv := aof_mult_linv B.\nLet B_le := aof_le B.\nLet B_le_antisym := aof_le_antisym B.\nLet B_le_trans := aof_le_trans B.\nLet B_le_connex := aof_le_connex B.\nLet B_le_lplus := aof_le_lplus B.\nLet B_le_mult := aof_le_mult B.\nLet B_not_trivial := aof_not_trivial B.\nLet B_arch := aof_arch B.\nLocal Existing Instances A_plus A_zero A_neg A_plus_comm A_plus_assoc A_plus_lid\n    A_plus_linv A_mult A_one A_div A_mult_comm A_mult_assoc A_ldist A_mult_lid\n    A_mult_linv A_le A_le_antisym A_le_trans A_le_connex A_le_lplus A_le_mult\n    A_not_trivial A_arch B_plus B_zero B_neg B_plus_comm B_plus_assoc B_plus_lid\n    B_plus_linv B_mult B_one B_div B_mult_comm B_mult_assoc B_ldist B_mult_lid\n    B_mult_linv B_le B_le_antisym B_le_trans B_le_connex B_le_lplus B_le_mult\n    B_not_trivial B_arch.\n\nDefinition arch_ordered_homo (f : set_type (aof_set A) → set_type (aof_set B))\n    :=\n        f 0 = 0 ∧\n        f 1 = 1 ∧\n        (∀ a b, f (a + b) = f a + f b) ∧\n        (∀ a b, f (a * b) = f a * f b) ∧\n        (∀ a b, a ≤ b → f a ≤ f b).\n\nTheorem arch_ordered_homo_neg : ∀ f, arch_ordered_homo f → ∀ x, f (-x) = -f x.\nProof.\n    intros f f_homo x.\n    pose proof f_homo as [f_zero [f_one [f_plus [f_mult f_le]]]].\n    apply plus_lcancel with (f x).\n    rewrite <- f_plus.\n    do 2 rewrite plus_rinv.\n    exact f_zero.\nQed.\n\nTheorem arch_ordered_homo_inj : ∀ f, arch_ordered_homo f → Injective f.\nProof.\n    intros f f_homo.\n    split.\n    intros a b eq.\n    rewrite <- plus_0_anb_b_a.\n    rewrite <- plus_0_anb_b_a in eq.\n    rewrite <- (arch_ordered_homo_neg _ f_homo) in eq.\n    pose proof f_homo as [f_zero [f_one [f_plus [f_mult f_le]]]].\n    rewrite <- f_plus in eq.\n    remember (b - a) as c.\n    clear a b Heqc.\n    classic_contradiction contr.\n    apply lmult with (f (/c)) in eq.\n    rewrite mult_ranni in eq.\n    rewrite <- f_mult in eq.\n    rewrite mult_linv in eq by exact contr.\n    rewrite f_one in eq.\n    apply not_trivial_one in eq.\n    exact eq.\nQed.\n\n\nTheorem arch_ordered_homo_le : ∀ f, arch_ordered_homo f →\n    ∀ x y, x ≤ y ↔ f x ≤ f y.\nProof.\n    intros f f_homo x y.\n    split; [>apply f_homo|].\n    intros leq.\n    classic_contradiction contr.\n    rewrite nle_lt in contr.\n    destruct contr as [yx neq].\n    apply f_homo in yx.\n    pose proof (antisym leq yx) as eq.\n    apply (arch_ordered_homo_inj _ f_homo) in eq.\n    symmetry in eq.\n    contradiction.\nQed.\n\nTheorem arch_ordered_homo_lt : ∀ f, arch_ordered_homo f →\n    ∀ x y, x < y ↔ f x < f y.\nProof.\n    intros f f_homo x y.\n    unfold strict.\n    rewrite <- (arch_ordered_homo_le _ f_homo).\n    split.\n    -   intros [leq neq].\n        split; [>exact leq|].\n        intros eq.\n        apply arch_ordered_homo_inj in eq; [>|exact f_homo].\n        contradiction.\n    -   intros [leq neq].\n        split; [>exact leq|].\n        intros eq.\n        subst y.\n        contradiction.\nQed.\n\nTheorem arch_ordered_homo_div : ∀ f, arch_ordered_homo f →\n    ∀ x, 0 ≠ x → f (/x) = /f x.\nProof.\n    intros f f_homo x x_nz.\n    pose proof f_homo as [f_zero [f_one [f_plus [f_mult f_le]]]].\n    assert (0 ≠ f x) as fx_nz.\n    {\n        intros contr.\n        rewrite <- f_zero in contr.\n        apply arch_ordered_homo_inj in contr; [>|exact f_homo].\n        contradiction.\n    }\n    apply mult_lcancel with (f x); [>exact fx_nz|].\n    rewrite <- f_mult.\n    rewrite mult_rinv by exact x_nz.\n    rewrite mult_rinv by exact fx_nz.\n    exact f_one.\nQed.\n\nTheorem arch_ordered_homo_nat : ∀ f, arch_ordered_homo f →\n    ∀ n, f (from_nat n) = from_nat n.\nProof.\n    intros f f_homo n.\n    pose proof f_homo as [f_zero [f_one [f_plus [f_mult f_le]]]].\n    nat_induction n.\n    -   setoid_rewrite homo_zero.\n        exact f_zero.\n    -   cbn.\n        rewrite f_plus.\n        rewrite f_one, IHn.\n        reflexivity.\nQed.\n\nTheorem arch_ordered_homo_int : ∀ f, arch_ordered_homo f →\n    ∀ n, f (int_to_abstract n) = int_to_abstract n.\nProof.\n    intros f f_homo n.\n    pose proof f_homo as [f_zero [f_one [f_plus [f_mult f_le]]]].\n    equiv_get_value n.\n    destruct n as [m n].\n    unfold int_to_abstract; equiv_simpl.\n    unfold int_to_abstract_base; cbn.\n    rewrite f_plus.\n    rewrite arch_ordered_homo_neg by exact f_homo.\n    do 2 rewrite arch_ordered_homo_nat by exact f_homo.\n    reflexivity.\nQed.\n\nTheorem arch_ordered_homo_rat : ∀ f, arch_ordered_homo f →\n    ∀ q, f (rat_to_abstract q) = rat_to_abstract q.\nProof.\n    intros f f_homo q.\n    pose proof f_homo as [f_zero [f_one [f_plus [f_mult f_le]]]].\n    equiv_get_value q.\n    unfold rat_to_abstract; equiv_simpl.\n    unfold rat_to_abstract_base; cbn.\n    rewrite f_mult.\n    rewrite arch_ordered_homo_div.\n    2: exact f_homo.\n    2: apply int_to_abstract_nz.\n    do 2 rewrite arch_ordered_homo_int by exact f_homo.\n    reflexivity.\nQed.\n\nTheorem arch_ordered_homo_uni_wlog : ∀ f g,\n    arch_ordered_homo f → arch_ordered_homo g →\n    ∀ x, f x ≤ g x.\nProof.\n    intros f g f_homo g_homo x.\n    classic_contradiction ltq.\n    rewrite nle_lt in ltq.\n    pose proof (rat_dense_in_arch (g x) (f x) ltq) as [r [r_gt r_lt]].\n    rewrite <- (arch_ordered_homo_rat g g_homo) in r_gt.\n    rewrite <- (arch_ordered_homo_rat f f_homo) in r_lt.\n    rewrite <- arch_ordered_homo_lt in r_gt by exact g_homo.\n    rewrite <- arch_ordered_homo_lt in r_lt by exact f_homo.\n    destruct (trans r_gt r_lt); contradiction.\nQed.\nTheorem arch_ordered_homo_uni : ∀ f g,\n    arch_ordered_homo f → arch_ordered_homo g → f = g.\nProof.\n    intros f g f_homo g_homo.\n    apply functional_ext.\n    intros x.\n    apply antisym; apply arch_ordered_homo_uni_wlog; assumption.\nQed.\n\nTheorem arch_ordered_homo_eq : ∀ f g x,\n    arch_ordered_homo f → arch_ordered_homo g → f x = g x.\nProof.\n    intros f g x f_homo g_homo.\n    rewrite (arch_ordered_homo_uni f g f_homo g_homo).\n    reflexivity.\nQed.\n\nEnd ArchOrderedField.\n\nArguments arch_ordered_homo_eq {A B}.\n\nTheorem identity_arch_ordered_homo : ∀ A, arch_ordered_homo A A identity.\nProof.\n    intros A.\n    repeat split; intro; try assumption.\n    intros b ab; exact ab.\nQed.\n\nTheorem arch_ordered_homo_identity :\n    ∀ A f, arch_ordered_homo A A f → f = identity.\nProof.\n    intros A f f_homo.\n    apply arch_ordered_homo_uni.\n    -   exact f_homo.\n    -   apply identity_arch_ordered_homo.\nQed.\n\nTheorem arch_ordered_homo_compose :\n    ∀ A B C f g, arch_ordered_homo A B f → arch_ordered_homo B C g →\n    arch_ordered_homo A C (λ x, g (f x)).\nProof.\n    intros A B C f g f_homo g_homo.\n    destruct f_homo as [f_zero [f_one [f_plus [f_mult f_le]]]].\n    destruct g_homo as [g_zero [g_one [g_plus [g_mult g_le]]]].\n    split; [>|split; [>|split; [>|split]]].\n    -   rewrite f_zero.\n        exact g_zero.\n    -   rewrite f_one.\n        exact g_one.\n    -   intros a b.\n        rewrite f_plus.\n        apply g_plus.\n    -   intros a b.\n        rewrite f_mult.\n        apply g_mult.\n    -   intros a b ab.\n        apply g_le.\n        apply f_le.\n        exact ab.\nQed.\n\nGlobal Instance arch_ordered_le : Order ArchOrderedField := {\n    le A B := ∃ f, arch_ordered_homo A B f\n}.\nGlobal Program Instance arch_ordered_le_refl : Reflexive le.\nNext Obligation.\n    unfold le; cbn.\n    exists identity.\n    apply identity_arch_ordered_homo.\nQed.\nGlobal Program Instance arch_ordered_le_trans : Transitive le.\nNext Obligation.\n    rename x into A, y into B, z into C, H into AB, H0 into BC.\n    unfold le in *; cbn in *.\n    destruct AB as [f f_homo].\n    destruct BC as [g g_homo].\n    exists (λ x, g (f x)).\n    apply arch_ordered_homo_compose; assumption.\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/Zorn/zorn_real_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6604870791306351}}
{"text": "Require Import List Omega SetoidClass Recdef.\nImport ListNotations.\n\nRequire Import Class.\n\nFixpoint even n :=\n  match n with\n  | 0 => true\n  | S m => negb (even m)\n  end.\n\nLemma even_odd_half : forall n, (even n = true -> exists k, 2 * k = n) /\\\n  (even n = false -> exists k, S (2 * k) = n).\nProof.\n  induction n; split; intros.\n  - exists 0; auto.\n  - discriminate.\n  - simpl in H.\n    destruct IHn.\n    destruct H1 as [k Hk].\n    + destruct (even n); [discriminate | auto].\n    + exists (S k).\n      omega.\n  - destruct IHn.\n    destruct H0 as [k Hk].\n    + simpl in H.\n      destruct (even n); [auto | discriminate].\n    + exists k; omega.\nQed.\n\nLemma even_half : forall n, even n = true -> exists k, 2 * k = n.\nProof.\n  intros; apply even_odd_half; auto.\nQed.\n\nLemma odd_half : forall n, even n = false -> exists k, S (2 * k) = n.\nProof.\n  intros; apply even_odd_half; auto.\nQed.\n\nLemma even_2k : forall k, even (2 * k) = true.\nProof.\n  induction k.\n  - auto.\n  - simpl; rewrite <- plus_n_Sm; simpl.\n    simpl in IHk; rewrite IHk; auto.\nQed.\n\nLemma odd_2k1 : forall k, even (S (2 * k)) = false.\nProof.\n  induction k.\n  - auto.\n  - simpl; rewrite <- plus_n_Sm.\n    simpl; simpl in IHk.\n    rewrite IHk; auto.\nQed.\n\nLemma half_2k : forall k, (2*k)/2 = k.\nProof.\n  intro.\n  rewrite Nat.mul_comm.\n  rewrite Nat.div_mul; omega.\nQed.\n\nLemma half_2k1 : forall k, (S (2 * k))/2 = k.\nProof.\n  intro.\n  pose (Nat.add_b2n_double_div2 true).\n  simpl Nat.b2n in e.\n  apply e.\nQed.\n\nSection Fin.\n\nFixpoint Fin(n : nat) : Type :=\n  match n with\n  | 0 => Empty_set\n  | S m => unit + Fin m\n  end.\n\nFixpoint Fin_le{n} : Fin n -> Fin n -> Prop :=\n  match n with\n  | 0 => fun i _ => match i with end\n  | S m => fun i j => match i,j with\n                      | inl _, inl _ => False\n                      | inl _, inr _ => True\n                      | inr _, inl _ => False\n                      | inr i', inr j' => Fin_le i' j'\n                      end\n  end.\n\nLemma Fin_le_irref : forall (n : nat)(i : Fin n), ~ Fin_le i i.\nProof.\n  induction n.\n  - intros [].\n  - destruct i as [[]|j].\n    + tauto.\n    + apply IHn.\nQed.\n\nLemma Fin_le_trans : forall (n : nat)(i j k : Fin n), Fin_le i j -> Fin_le j k -> Fin_le i k.\nProof.\n  induction n; intros.\n  - destruct i.\n  - destruct i as [|i']; destruct k as [|k'].\n    + destruct j; auto.\n    + exact I.\n    + destruct j; auto.\n    + destruct j as [|j'].\n      * destruct H.\n      * apply (IHn _ j' _); auto.\nQed.\n\nLemma Fin_trich : forall (n : nat)(i j : Fin n), {i = j} + {Fin_le i j} + {Fin_le j i}.\nProof.\n  induction n.\n  - intros [].\n  - intros [[]|i'] [[]|j'].\n    + left; left; auto.\n    + left; right; exact I.\n    + right; exact I.\n    + destruct (IHn i' j') as [[Heq|Hle]|Hge].\n      * left; left; congruence.\n      * left; right; exact Hle.\n      * right; exact Hge.\nQed.\n\nFixpoint list_index{X}(xs : list X){struct xs} : Fin (length xs) -> X :=\n  match xs return Fin (length xs) -> X with\n  | [] => fun i => match i with end\n  | y::ys => fun i => match i with\n                      | inl _ => y\n                      | inr j => list_index ys j\n                      end\n  end.\n\nLemma in_index : forall {X}`{Eq X}(xs : list X)(x : X), setoidIn x xs -> exists (i : Fin (length xs)),\n  list_index xs i == x.\nProof.\n  induction xs; intros.\n  - destruct H1.\n  - destruct H1.\n    + exists (inl tt); simpl; symmetry; auto.\n    + destruct (IHxs x H1) as [i Hi].\n      exists (inr i); auto.\nQed.\n\nEnd Fin.", "meta": {"author": "emarzion", "repo": "cantor", "sha": "24f1508d67c47317693cc771fc51e7dcdd87ce8c", "save_path": "github-repos/coq/emarzion-cantor", "path": "github-repos/coq/emarzion-cantor/cantor-24f1508d67c47317693cc771fc51e7dcdd87ce8c/Util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6604850445704867}}
{"text": "Require Import Coq.Lists.List.\nImport ListNotations.\n\nTheorem silly1_using_apply : forall (n m o p : nat), n=m -> [n;o] = [n;p] -> [n;o] = [m;p].\nProof.\n    intros.\n    rewrite <- H.\n    apply H0.\nQed.\n\nTheorem silly1_using_rewrite : forall (n m o p : nat), n=m -> [n;o] = [n;p] -> [n;o] = [m;p].\nProof.\n    intros.\n    rewrite <- H.\n    rewrite H0. reflexivity.\nQed.\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter7_Library_MoreCoq/silly1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.6604850298688147}}
{"text": "Welcome to Coq ciosx:/builds/workspace/coq-8.5pl3-macos,(detached from 2290dbb) (2290dbb9c95b63e693ced647731623e64297f5c8)\n\nCoq < Theorem plus_O_n' : forall n : nat, 0 + n = n.\n1 subgoal\n  \n  ============================\n  forall n : nat, 0 + n = n\n\nplus_O_n' < Proof.\n1 subgoal\n  \n  ============================\n  forall n : nat, 0 + n = n\n\nplus_O_n' < intros n.\n1 subgoal\n  \n  n : nat\n  ============================\n  0 + n = n\n\nplus_O_n' < reflexivity.\nNo more subgoals.\n\nplus_O_n' < Qed.\nProof.\nintros n.\nreflexivity.\n\nQed.\nplus_O_n' 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/basic010.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6604850249285826}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2011     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\n(* $Id: Zwf.v 14641 2011-11-06 11:59:10Z herbelin $ *)\n\nRequire Import ZArith_base.\nRequire Export Wf_nat.\nRequire Import Omega.\nOpen Local Scope Z_scope.\n\n(** Well-founded relations on Z. *)\n\n(** We define the following family of relations on [Z x Z]:\n\n    [x (Zwf c) y]   iff   [x < y & c <= y]\n *)\n\nDefinition Zwf (c x y:Z) := c <= y /\\ x < y.\n\n(** and we prove that [(Zwf c)] is well founded *)\n\nSection wf_proof.\n\n  Variable c : Z.\n\n  (** The proof of well-foundness is classic: we do the proof by induction\n      on a measure in nat, which is here [|x-c|] *)\n\n  Let f (z:Z) := Zabs_nat (z - c).\n\n  Lemma Zwf_well_founded : well_founded (Zwf c).\n    red in |- *; intros.\n    assert (forall (n:nat) (a:Z), (f a < n)%nat \\/ a < c -> Acc (Zwf c) a).\n    clear a; simple induction n; intros.\n  (** n= 0 *)\n    case H; intros.\n    case (lt_n_O (f a)); auto.\n    apply Acc_intro; unfold Zwf in |- *; intros.\n    assert False; omega || contradiction.\n  (** inductive case *)\n    case H0; clear H0; intro; auto.\n    apply Acc_intro; intros.\n    apply H.\n    unfold Zwf in H1.\n    case (Zle_or_lt c y); intro; auto with zarith.\n    left.\n    red in H0.\n    apply lt_le_trans with (f a); auto with arith.\n    unfold f in |- *.\n    apply Zabs.Zabs_nat_lt; omega.\n    apply (H (S (f a))); auto.\n  Qed.\n\nEnd wf_proof.\n\nHint Resolve Zwf_well_founded: datatypes v62.\n\n\n(** We also define the other family of relations:\n\n    [x (Zwf_up c) y]   iff   [y < x <= c]\n *)\n\nDefinition Zwf_up (c x y:Z) := y < x <= c.\n\n(** and we prove that [(Zwf_up c)] is well founded *)\n\nSection wf_proof_up.\n\n  Variable c : Z.\n\n  (** The proof of well-foundness is classic: we do the proof by induction\n      on a measure in nat, which is here [|c-x|] *)\n\n  Let f (z:Z) := Zabs_nat (c - z).\n\n  Lemma Zwf_up_well_founded : well_founded (Zwf_up c).\n  Proof.\n    apply well_founded_lt_compat with (f := f).\n    unfold Zwf_up, f in |- *.\n    intros.\n    apply Zabs.Zabs_nat_lt.\n    unfold Zminus in |- *. split.\n    apply Zle_left; intuition.\n    apply Zplus_lt_compat_l; unfold Zlt in |- *; rewrite <- Zcompare_opp;\n      intuition.\n  Qed.\n\nEnd wf_proof_up.\n\nHint Resolve Zwf_up_well_founded: datatypes 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/ZArith/Zwf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6604850225179787}}
{"text": "From Coq Require Import List.\nImport ListNotations.\n\n\nDefinition iffT (X Y : Type) : Type := (X -> Y) * (Y -> X).\nNotation \"X <=> Y\" := (iffT X Y) (at level 95, no associativity).\n\n(* Minimal Logic *)\nSection Minimal.\n\n  Inductive prop : Type :=\n  | P : nat -> prop\n  | Impl : prop -> prop -> prop\n  | Conj : prop -> prop -> prop\n  | Disj : prop -> prop -> prop.\n\n  Notation \"A ∧ B\" := (Conj A B) (at level 41).\n  Notation \"A ∨ B\" := (Disj A B) (at level 42).\n  Notation \"A '-->' B\" := (Impl A B) (at level 43, right associativity).\n  Notation \"x 'el' A\" := (In x A) (at level 70).\n  Notation \"A <<= B\" := (incl A B) (at level 70).\n\n  (* Inductive type formalizing deduction in minimal logic *)\n  Reserved Notation \"A ⊢ s\" (at level 70).\n  Inductive prv : list prop -> prop -> Type :=\n  | II A phi psi : phi::A ⊢ psi -> A ⊢ phi --> psi\n  | IE A phi psi : A ⊢ phi --> psi -> A ⊢ phi -> A ⊢ psi\n  | Ctx A phi : phi el A -> A ⊢ phi\n  | CI A phi psi : A ⊢ phi -> A ⊢ psi -> A ⊢ phi ∧ psi\n  | CE1 A phi psi : A ⊢ phi ∧ psi -> A ⊢ phi\n  | CE2 A phi psi : A ⊢ phi ∧ psi -> A ⊢ psi\n  | DI1 A phi psi : A ⊢ phi -> A ⊢ phi ∨ psi\n  | DI2 A phi psi : A ⊢ psi -> A ⊢ phi ∨ psi\n  | DE  A phi psi theta : A ⊢ phi ∨ psi -> phi::A ⊢ theta -> psi::A ⊢ theta -> A ⊢ theta\n  where \"A ⊢ phi\" := (prv A phi).\n\n  Ltac Select n :=\n    match n with \n    | 0 => left\n    | S ?x => right; Select x\n    end.\n  Ltac Exact n := apply Ctx; now Select n.\n  Ltac Intro := apply II.\n  Ltac Intros := repeat Intro.\n  Ltac Apply n := eapply IE; [Exact n|idtac].\n  Ltac Left := apply DI1.\n  Ltac Right := apply DI2.\n  Ltac Destruct n := eapply DE; [Exact n|idtac|idtac].\n  Ltac Split := apply CI.\n\n\n  Lemma Weak A B phi :\n    A ⊢ phi -> A <<= B -> B ⊢ phi.\n  Proof.\n    induction 1 in B |-*; try unshelve (solve [econstructor; intuition]); try now econstructor.\n  Qed.\n\n  Fact Imp A s t :\n    A ⊢ s --> t <=> s::A ⊢ t.\n  Proof.\n    split.\n    - intros H. eapply IE. \n      2: apply Ctx. eapply Weak. exact H.\n      all: firstorder.\n    - now Intro.\n  Qed.\n\n\n\n  (* Fix some propositional variable F *)\n  Variable F : prop.\n\n  Definition Contradiction := forall A B, nil ⊢ A --> (A --> F) --> B.\n  Definition Explosion := forall A, nil ⊢ F --> A.\n  Definition LEM := forall A, nil ⊢ A ∨ (A --> F).\n  Definition DN := forall A, nil ⊢ ((A --> F) --> F) --> A.\n  Definition CP := forall A B, nil ⊢ ((B --> F) --> (A --> F)) --> A --> B.\n\n  Definition Peirce := forall A B, nil ⊢ ((A --> B) --> A) --> A.\n\n\n  Lemma CP' {X Y Gamma} : CP -> Gamma ⊢ (Y --> F) --> (X --> F) -> Gamma ⊢ X --> Y.\n  Proof.\n    intros cp. apply IE. eapply Weak.\n    apply (cp X Y). firstorder.\n  Qed.\n\n  Goal DN <=> CP.\n  Proof.\n    split.\n    - intros dn A B.\n      generalize (dn B).\n      eapply IE. Intros.\n      Apply 2. Intros.\n      eapply IE. instantiate (1 := A).\n      + Apply 2. Exact 0.\n      + Exact 1.\n    - intros cp A. apply (CP' cp).\n      Intros. Apply 0. Intros.\n      Apply 2. Exact 0.\n  Qed.\n\n  Goal DN -> Explosion.\n  Proof.\n    intros dn A.\n    generalize (dn A).\n    eapply IE. Intros.\n    Apply 1. Intros. Exact 1.\n  Qed.\n\n  Goal CP -> Peirce.\n  Proof.\n    intros cp A B. apply (CP' cp).\n    Intros. Apply 1. Apply 0.\n    apply (CP' cp). Intro. Exact 2.\n  Qed.\n\n  Goal Peirce -> LEM.\n  Proof.\n    intros peirce X.\n    eapply IE. apply (peirce (X ∨ (X --> F)) F).\n    Intros. Right. Intros.\n    Apply 1. Left. Exact 0.\n  Qed.\n  \n  Goal LEM * Explosion -> DN.\n  Proof.\n    intros [lem expl] X.\n    generalize (lem X); apply IE.\n    generalize (expl X); apply IE.\n    Intros. Destruct 1.\n    - Exact 0.\n    - Apply 3. Apply 1. Exact 0.\n  Qed.\n\n\n  Section NonDeduc.\n\n    (*  Meta Argument: Assume it is possible to show \n        Peirce -> Explosion = forall X, |- F -> X. \n        Since F was an arbitrary choice, this would mean we would really have a way of showing : \n     *)\n    Hypothesis H : forall Y, Peirce -> forall X, nil ⊢ Y --> X.\n\n    (* However it then turns out that *)\n    Goal Peirce -> forall P, nil ⊢ P.\n    Proof.\n      intros peirce P.\n      enough (nil ⊢ (P --> P) --> P) as C.\n      revert C. eapply IE. \n      - Intros. Apply 0. Intros. Exact 0.\n      - now apply H.\n    Qed.\n       \n  End NonDeduc.\n\n\nEnd Minimal.\n\n\n", "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/MinimalLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924953, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.6604750847907931}}
{"text": "Require Coq.Strings.Ascii.\nRequire Coq.Lists.List.\nRequire Coq.Setoids.Setoid.\nRequire Coq.Relations.Relations.\nRequire Coq.Classes.Morphisms.\nRequire Turing.Util.\nRequire Import Coq.Lists.List. \nImport Coq.Lists.List.ListNotations.\n\nOpen Scope char_scope. (* Ensure by default we are representing characters. *)\n\nSection Defs.\n  Import List.\n  Import ListNotations.\n  Import Ascii.\n\n  Definition word := list ascii.\n\n  (** A language is a predicate on words. We say that [w] is in language [L] if,\n      and only if, [L w]. *)\n\n  Definition language := word -> Prop.\n\n  (** A word is in a language is defined as function application *)\n  Definition In w (L:language) := L w. \n\n  Lemma in_def:\n    forall (L:language) w,\n    L w = In w L.\n  Proof.\n    intros.\n    unfold In.\n    reflexivity.\n  Qed.\n\n  (** The language that accepts all strings. *)\n\n  Definition All : language := fun w => True.\n\n  (** Every word is in [All]. *)\n\n  Lemma all_in:\n    forall w,\n    In w All.\n  Proof.\n    intros.\n    unfold All.\n    apply I.\n  Qed.\n\n  (** The language that rejects all strings. *)\n\n  Definition Void : language := fun w => False.\n\n  (** Conversely, no word is in [Void]. *)\n\n  Lemma void_not_in:\n    forall w,\n    ~ In w Void.\n  Proof.\n    intros.\n    unfold Void; intros N.\n    contradiction.\n  Qed.\n\n  (** [Nil] only accepts empty strings. *)\n\n  Definition Nil : language := fun w => w = [].\n\n  Lemma nil_in:\n    In [] Nil.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma nil_in_inv:\n    forall w,\n    In w Nil ->\n    w = [].\n  Proof.\n    unfold Nil. intros.\n    assumption.\n  Qed.\n\n  (** [Char] accepts a single character. *)\n\n  Definition Char c : language :=\n    fun w => w = [c].\n\n  Lemma char_in:\n    forall (c:ascii),\n    In [c] (Char c).\n  Proof.\n    unfold Char.\n    intros.\n    reflexivity.\n  Qed.\n\n  Lemma char_in_inv:\n    forall c w,\n    In w (Char c) ->\n    w = [c].\n  Proof.\n    unfold Char.\n    intros.\n    assumption.\n  Qed.\n\n  (** [Any] accepts any single character. *)\n\n  Definition Any: language := fun w => exists c, w = [c].\n\n  Lemma any_in:\n    forall c,\n    In [c] Any.\n  Proof.\n    unfold Any.\n    intros.\n    exists c.\n    reflexivity.\n  Qed.\n\n  Lemma any_in_inv:\n    forall w,\n    In w Any -> exists c, w = [c].\n  Proof.\n    unfold Any; auto.\n  Qed.\n\n  (** Concatenation of strings *)\n\n  Definition App (L1 L2:language) : language :=\n    fun w => exists w1 w2, w = w1 ++ w2 /\\ L1 w1 /\\ L2 w2. \n\n  (** Show that if [w1] is in [L1] and [w2] is in [L2], then [w1 ++ w2] is in\n      [App L1 L2]. *)\n\n  Lemma app_in_eq:\n    forall (L1 L2:language) w1 w2,\n    In w1 L1 ->\n    In w2 L2 ->\n    In (w1 ++ w2) (App L1 L2).\n  Proof.\n    unfold In, App; intros.\n    eauto.\n  Qed.\n\n  (** Auxiliary lemma that lets us use app when the string is not directly in\n      the form of [w1 ++ w2]. *)\n  Lemma app_in:\n    forall (L1 L2:language) w1 w2 w3,\n    In w1 L1 ->\n    In w2 L2 ->\n    w3 = w1 ++ w2 ->\n    In w3 (App L1 L2).\n  Proof.\n    unfold In; intros.\n    subst.\n    apply app_in_eq; auto.\n  Qed.\n\n  Lemma app_in_inv:\n    forall (L1 L2:language) w,\n    In w (App L1 L2) ->\n    exists w1 w2, w = w1 ++ w2 /\\ In w1 L1 /\\ In w2 L2.\n  Proof.\n    unfold App; intros.\n    assumption.\n  Qed.\n\n  Lemma app_l_char_in:\n    forall c (L:language) w,\n    In w L ->\n    In (c :: w) (App (Char c) L).\n  Proof.\n    intros.\n    apply app_in with (w1:=[c]) (w2:=w).\n    + apply char_in.\n    + assumption.\n    + reflexivity.\n  Qed.\n\n  Lemma app_l_all_in:\n    forall (L:language) w1 w2,\n    In w2 L ->\n    In (w1 ++ w2) (App All L).\n  Proof.\n    intros.\n    apply app_in with (w1:=w1) (w2:=w2).\n    + apply all_in.\n    + assumption.\n    + reflexivity.\n  Qed.\n\n  Lemma app_l_all_in_skip:\n    forall (L:language) w,\n    In w L ->\n    In w (App All L).\n  Proof.\n    intros.\n    apply app_in with (w1:=[]) (w2:=w).\n    + apply all_in.\n    + assumption.\n    + reflexivity.\n  Qed.\n\n  Lemma app_r_all_in_skip:\n    forall (L:language) w,\n    In w L ->\n    In w (App L All).\n  Proof.\n    intros.\n    apply app_in with (w1:=w) (w2:=[]).\n    + assumption.\n    + apply all_in.\n    + rewrite app_nil_r.\n      reflexivity.\n  Qed.\n\n  Lemma app_r_all_in:\n    forall (L:language) w1 w2,\n    In w1 L ->\n    In (w1 ++ w2) (App L All).\n  Proof.\n    intros.\n    apply app_in with (w1:=w1) (w2:=w2).\n    + assumption.\n    + apply all_in.\n    + reflexivity.\n  Qed.\n\n  Lemma app_l_any_in:\n    forall c w L,\n    In w L ->\n    In (c::w) (App Any L).\n  Proof.\n    intros.\n    apply app_in with (w1:=[c]) (w2:=w); auto using any_in.\n  Qed.\n\n  Lemma app_l_char_in_inv:\n    forall c L w,\n    In w (App (Char c) L) ->\n    exists w', w = c:: w' /\\ In w' L.\n  Proof.\n    intros.\n    apply app_in_inv in H.\n    destruct H as (w1, (w2, (?, (Ha, Hb)))).\n    apply char_in_inv in Ha.\n    subst.\n    exists w2.\n    auto.\n  Qed.\n\n  Lemma app_r_char_in_inv:\n    forall c L w,\n    In w (App L (Char c)) ->\n    exists w', w = w' ++ [c] /\\ In w' L.\n  Proof.\n    intros.\n    apply app_in_inv in H.\n    destruct H as (w1, (w2, (?, (Ha, Hb)))).\n    apply char_in_inv in Hb.\n    subst.\n    exists w1.\n    auto.\n  Qed.\n\n\n  Lemma app_l_any_in_inv:\n    forall w L,\n    In w (App Any L) ->\n    exists w' c, w = c :: w' /\\ In w' L.\n  Proof.\n    intros.\n    apply app_in_inv in H.\n    destruct H as (w1, (w2, (?, (Ha, Hb)))).\n    subst.\n    apply any_in_inv in Ha.\n    destruct Ha as (c, ?).\n    subst.\n    exists w2.\n    exists c.\n    auto.\n  Qed.\n\n\n  (** Union on languages *)\n\n  Definition Union (L1 L2:language) : language :=\n    fun w => L1 w \\/ L2 w.\n\n  Lemma union_in_l:\n    forall (L1 L2:language) w,\n    In w L1 ->\n    In w (Union L1 L2).\n  Proof.\n    unfold In, Union.\n    eauto.\n  Qed.\n\n  Lemma union_in_r:\n    forall (L1 L2:language) w,\n    In w L2 ->\n    In w (Union L1 L2).\n  Proof.\n    unfold In, Union; eauto.\n  Qed.\n\n  Lemma union_in_inv:\n    forall (L1 L2:language) w,\n    In w (Union L1 L2) ->\n    In w L1 \\/ In w L2.\n  Proof.\n    unfold Union; auto.\n  Qed.\n\n  (** Pow definition based on: https://en.wikipedia.org/wiki/Kleene_star *)\n\n  Inductive Pow (L:language) : nat -> word -> Prop :=\n  | pow_nil:\n    Pow L 0 nil\n  | pow_cons:\n    forall n w1 w2 w3,\n    Pow L n w2 ->\n    L w1 ->\n    w3 = w1 ++ w2 ->\n    Pow L (S n) w3.\n\n  Lemma pow_in_eq:\n    forall (L:language) w,\n    In w L ->\n    In w (Pow L 1).\n  Proof.\n    intros.\n    apply pow_cons with (w1:=w) (w2:=nil).\n    + apply pow_nil.\n    + assumption.\n    + rewrite app_nil_r.\n      reflexivity.\n  Qed.\n\n  (** Star definition based on https://en.wikipedia.org/wiki/Kleene_star *)\n\n  Definition Star L : language := fun w => exists n, Pow L n w.\n\n  Lemma star_in_nil:\n    forall L,\n    In [] (Star L).\n  Proof.\n    intros.\n    exists 0.\n    apply pow_nil.\n  Qed.\n\n  Lemma star_in_eq:\n    forall (L:language) w,\n    In w L ->\n    In w (Star L).\n  Proof.\n    intros.\n    exists 1.\n    apply pow_in_eq; auto.\n  Qed.\n\n  Lemma pow_to_star:\n    forall (L:language) n w,\n    In w (Pow L n) ->\n    In w (Star L).\n  Proof.\n    intros.\n    exists n.\n    assumption.\n  Qed.\n\n  Lemma star_to_pow:\n    forall (L:language) w,\n    In w (Star L) ->\n    exists n, In w (Pow L n).\n  Proof.\n    unfold Star, In; intros.\n    assumption.\n  Qed.\n\n  (** Equivalence of languages *)\n\n  Definition Equiv (L1 L2:language) : Prop := forall w, In w L1 <-> In w L2. \n\n  (** Equivalence is symmetric. *)\n\n  Lemma equiv_sym:\n    forall L1 L2,\n    Equiv L1 L2 ->\n    Equiv L2 L1.\n  Proof.\n    unfold Equiv; split; intros; apply H; assumption.\n  Qed.\n\n  (** Equivalence is transitive. *)\n\n  Lemma equiv_trans:\n    forall L1 L2 L3,\n    Equiv L1 L2 ->\n    Equiv L2 L3 ->\n    Equiv L1 L3.\n  Proof.\n    unfold Equiv; intros.\n    rewrite H.\n    rewrite H0.\n    intuition.\n  Qed.\n\n  Lemma equiv_refl:\n    forall L,\n    Equiv L L.\n  Proof.\n    split; intros; tauto.\n  Qed.\n\n  (** Register [Equiv] in Coq's tactics. *)\n  Global Add Parametric Relation : language Equiv\n    reflexivity proved by equiv_refl\n    symmetry proved by equiv_sym\n    transitivity proved by equiv_trans\n    as l_equiv_setoid.\n\n  Goal forall (L1 L2:language), Equiv L1 L2 -> Equiv L2 L1.\n  Proof.\n    intros.\n    symmetry. (** We can apply symmetry in the goal. *)\n    rewrite H. (** We can rewrite H in the goal. *)\n    reflexivity. (** We can use reflexivity to conclude Equiv goals. *)\n  Qed.\n\n  Lemma pow_equiv_in:\n    forall L1 L2 n w,\n    Equiv L1 L2 ->\n    In w (Pow L1 n) ->\n    In w (Pow L2 n).\n  Proof.\n    intros.\n    induction H0; intros.\n    - apply pow_nil.\n    - subst.\n      apply pow_cons with (w1:=w1) (w2:=w2); auto.\n      apply H.\n      assumption.\n  Qed.\n\n  Lemma pow_equiv:\n    forall (L1 L2:language),\n    Equiv L1 L2 ->\n    forall n,\n    Equiv (Pow L1 n) (Pow L2 n).\n  Proof.\n    split; intros.\n    + eauto using pow_equiv_in.\n    + apply equiv_sym in H.\n      eauto using pow_equiv_in.\n  Qed.\n\n  Lemma star_equiv:\n    forall (L1 L2:language),\n    Equiv L1 L2 ->\n    Equiv (Star L1) (Star L2).\n  Proof.\n    split; intros.\n    + apply star_to_pow in H0.\n      destruct H0 as (n, Hi).\n      apply pow_to_star with (n:=n).\n      eauto using pow_equiv_in.\n    + apply star_to_pow in H0.\n      destruct H0 as (n, Hi).\n      apply pow_to_star with (n:=n).\n      apply equiv_sym in H.\n      eauto using pow_equiv_in.\n  Qed.\n\n  Lemma star_equiv_in:\n    forall L1 L2 w,\n    Equiv L1 L2 ->\n    In w (Star L1) ->\n    In w (Star L2).\n  Proof.\n    intros.\n    apply star_equiv in H.\n    apply H.\n    assumption.\n  Qed.\n\n  Lemma app_in_equiv:\n    forall L1 L2 L3 L4 w,\n    Equiv L1 L3 ->\n    Equiv L2 L4 ->\n    In w (App L1 L2) ->\n    In w (App L3 L4).\n  Proof.\n    intros.\n    apply app_in_inv in H1.\n    destruct H1 as (w1, (w2, (?, (Ha, Hb)))).\n    subst.\n    apply app_in_eq.\n    + apply H; assumption.\n    + apply H0. assumption.\n  Qed.\n\n  Lemma equiv_app:\n    forall L1 L2 L3 L4,\n    Equiv L1 L3 ->\n    Equiv L2 L4 ->\n    Equiv (App L1 L2) (App L3 L4).\n  Proof.\n    split; intros.\n    - eapply app_in_equiv; eauto.\n    - eapply app_in_equiv; eauto.\n      + apply equiv_sym. assumption.\n      + apply equiv_sym. assumption.\n  Qed.\n\n  Lemma union_in_equiv:\n    forall L1 L2 L3 L4 w,\n    Equiv L1 L3 ->\n    Equiv L2 L4 ->\n    In w (Union L1 L2) ->\n    In w (Union L3 L4).\n  Proof.\n    intros.\n    destruct H1.\n    - apply H in H1.\n      apply union_in_l.\n      assumption.\n    - apply H0 in H1.\n      apply union_in_r.\n      assumption.\n  Qed.\n\n  Lemma equiv_union:\n    forall L1 L2 L3 L4,\n    Equiv L1 L3 ->\n    Equiv L2 L4 ->\n    Equiv (Union L1 L2) (Union L3 L4).\n  Proof.\n    split; intros.\n    - eapply union_in_equiv; eauto.\n    - eapply union_in_equiv; eauto.\n      + apply equiv_sym. assumption.\n      + apply equiv_sym. assumption.\n  Qed.\n\n  Section equiv_proper.\n  Import Morphisms.\n\n  Global Instance in_equiv_proper: Proper (eq ==> Equiv ==> iff) In.\n  Proof.\n    unfold Proper, respectful, Equiv.\n    intros.\n    subst.\n    split; intros; apply H0 in H; auto.\n  Qed.\n\n  (* Allow rewriting under App *)\n  Global Instance app_equiv_proper: Proper (Equiv ==> Equiv ==> Equiv) App.\n  Proof.\n    unfold Proper.\n    unfold respectful.\n    intros.\n    apply equiv_app; auto.\n  Qed.\n  (* Allow rewriting under Union *)\n  Global Instance union_equiv_proper: Proper (Equiv ==> Equiv ==> Equiv) Union.\n  Proof.\n    unfold Proper.\n    unfold respectful.\n    intros.\n    apply equiv_union; auto.\n  Qed.\n\n  Global Instance star_equiv_proper: Proper (Equiv ==> Equiv) Star.\n  Proof.\n    unfold Proper.\n    unfold respectful.\n    apply star_equiv.\n  Qed.\n\n  Global Instance pow_equiv_proper (n:nat): Proper (Equiv ==> Equiv) (fun x => Pow x n).\n  Proof.\n    unfold Proper.\n    unfold respectful.\n    intros.\n    apply pow_equiv.\n    assumption.\n  Qed.\n\n  End equiv_proper.\n  (** Relate [All] with [Star Any]. *)\n\n  Lemma app_assoc_in_1:\n    forall L1 L2 L3 w,\n    In w (App L1 (App L2 L3)) ->\n    In w (App (App L1 L2) L3).\n  Proof.\n    intros.\n    apply app_in_inv in H.\n    destruct H as (w1, (w2, (?, (Ha, Hb)))).\n    subst.\n    apply app_in_inv in Hb.\n    destruct Hb as (w3, (w4, (?, (Hc, Hd)))).\n    subst.\n    rewrite app_assoc.\n    auto using app_in_eq.\n  Qed.\n\n  Lemma app_assoc_in_2:\n    forall L1 L2 L3 w,\n    In w (App (App L1 L2) L3) ->\n    In w (App L1 (App L2 L3)).\n  Proof.\n    intros.\n    apply app_in_inv in H.\n    destruct H as (w1, (w2, (?, (Ha, Hb)))).\n    subst.\n    apply app_in_inv in Ha.\n    destruct Ha as (w3, (w4, (?, (Ha, Hc)))).\n    subst.\n    rewrite <- app_assoc.\n    auto using app_in_eq.\n  Qed.\n\n  Lemma app_assoc_rw:\n    forall L1 L2 L3,\n    Equiv (App L1 (App L2 L3)) (App (App L1 L2) L3).\n  Proof.\n    intros.\n    split; intros.\n    - apply app_assoc_in_1.\n      assumption.\n    - apply app_assoc_in_2.\n      assumption.\n  Qed.\n\n  Lemma union_assoc_in_1:\n    forall w L1 L2 L3,\n    In w (Union L1 (Union L2 L3)) ->\n    In w (Union (Union L1 L2) L3).\n  Proof.\n    intros.\n    destruct H as [H1|[H2|H3]].\n    - left.\n      left.\n      assumption.\n    - left.\n      right.\n      assumption.\n    - right.\n      assumption.\n  Qed.\n\n  Lemma union_assoc_in_2:\n    forall L1 L2 L3 w,\n    In w (Union (Union L1 L2) L3) ->\n    In w (Union L1 (Union L2 L3)).\n  Proof.\n    intros.\n    destruct H as [[H|H]|H].\n    - left; assumption.\n    - right. left. assumption.\n    - right.\n      right.\n      assumption.\n  Qed.\n\n  Lemma pow_char_in_inv:\n    forall c n w,\n    In w (Pow (Char c) n) ->\n    w = Util.pow1 c n.\n  Proof.\n    induction n; intros.\n    - inversion H; subst; clear H.\n      reflexivity.\n    - inversion H; subst; clear H.\n      inversion H2; subst; clear H2.\n      apply IHn in H1.\n      subst.\n      reflexivity.\n  Qed.\n\n  Lemma pow_char_cons:\n    forall c n w,\n    In w (Pow (Char c) n) ->\n    In (c::w) (Pow (Char c) (S n)).\n  Proof.\n    intros.\n    apply pow_cons with (w1:=[c]) (w2:=w).\n    - assumption.\n    - apply char_in.\n    - reflexivity.\n  Qed.\n\n  Lemma pow_char_in:\n    forall c n,\n    In (Util.pow1 c n) (Pow (Char c) n).\n  Proof.\n    induction n; intros.\n    - apply pow_nil.\n    - simpl.\n      apply pow_cons with (w1:=[c]) (w2:=Util.pow1 c n).\n      + assumption.\n      + apply char_in.\n      + reflexivity.\n  Qed.\n\n  Lemma pow_char_cons_inv:\n    forall c n w,\n    In w (Pow (Char c) (S n)) ->\n    exists w', w = c::w' /\\ In w' (Pow (Char c) n).\n  Proof.\n    intros.\n    inversion H; subst; clear H.\n    inversion H2; subst; clear H2.\n    exists w2.\n    auto.\n  Qed.\n\n  Lemma pow_pow_in_inv:\n    forall c1 c2 n1 n2 w,\n    In w (App (Pow (Char c1) n1) (Pow (Char c2) n2)) ->\n    w = Util.pow1 c1 n1 ++ Util.pow1 c2 n2.\n  Proof.\n    intros.\n    apply app_in_inv in H.\n    destruct H as (w1, (w2, (?, (Ha, Hb)))).\n    subst.\n    apply pow_char_in_inv in Ha.\n    apply pow_char_in_inv in Hb.\n    subst.\n    reflexivity.\n  Qed.\n\n  Lemma pow_pow_in_inv_eq:\n    forall c1 c2 n1 n2 m1 m2,\n    c1 <> c2 ->\n    App (Pow (Char c1) n1) (Pow (Char c2) n2) (Util.pow1 c1 m1 ++ Util.pow1 c2 m2) ->\n    n1 = m1 /\\ n2 = m2.\n  Proof.\n    intros.\n    apply pow_pow_in_inv in H0.\n    assert (n1 = m1) by eauto using Util.pow1_app_inv_eq_1.\n    subst.\n    assert (n2 = m2) by eauto using Util.pow1_app_inv_eq_2.\n    subst.\n    intuition.\n  Qed.\n\n  Lemma pow_add:\n    forall L n1 n2 (w1 w2:word),\n    In w1 (Pow L n1) ->\n    In w2 (Pow L n2) ->\n    In (w1 ++ w2) (Pow L (n1 + n2)).\n  Proof.\n    induction n1; intros.\n    - inversion H; subst; clear H; simpl.\n      assumption.\n    - inversion H; subst; clear H.\n      simpl.\n      assert (Hx := IHn1 _ _ _ H2 H0).\n      rewrite <- app_assoc.\n      eapply pow_cons; eauto.\n  Qed.\n\n  Lemma pow_add_inv:\n    forall L n1 n2 (w:word),\n    In w (Pow L (n1 + n2)) ->\n    exists w1 w2, w = w1 ++ w2 /\\ In w1 (Pow L n1) /\\ In w2 (Pow L n2).\n  Proof.\n    induction n1; simpl; intros. {\n      exists nil, w.\n      intuition.\n      apply pow_nil.\n    }\n    inversion H; subst; clear H.\n    assert (Hx := H1).\n    apply IHn1 in H1.\n    destruct H1 as (w3, (w4, (?, (Ha, Hb)))).\n    subst.\n    exists (w1 ++ w3) % list, w4.\n    rewrite app_assoc.\n    intuition.\n    unfold In.\n    eauto using pow_cons.\n  Qed.\n\n  Lemma nil_pow_in_inv:\n    forall n w,\n    In w (Pow Nil n) ->\n    w = [].\n  Proof.\n    induction n; intros.\n    - inversion H; subst; clear H.\n      reflexivity.\n    - inversion H; subst; clear H.\n      apply nil_in_inv in H2.\n      subst.\n      apply IHn in H1.\n      subst.\n      reflexivity.\n  Qed.\n\n  Lemma void_pow_in_inv:\n    forall n w,\n    In w (Pow Void n) ->\n    w = [].\n  Proof.\n    intros.\n    induction H.\n    - reflexivity.\n    - subst.\n      apply void_not_in in H0.\n      contradiction.\n  Qed.\n\n  Lemma pow_cons_eq:\n    forall (L:language) w1 w2 n,\n    In w1 L ->\n    In w2 (Pow L n) ->\n    In (w1 ++ w2) (Pow L (S n)).\n  Proof.\n    intros.\n    apply pow_cons with (w1:=w1) (w2:=w2); auto.\n  Qed.\n\n  Lemma star_cons:\n    forall (L:language) w1 w2 w3,\n    In w1 L ->\n    In w2 (Star L) ->\n    w3 = w1 ++ w2 ->\n    In w3 (Star L).\n  Proof.\n    intros.\n    destruct H0 as (n, Hp).\n    exists (S n).\n    subst.\n    apply pow_cons_eq; auto.\n  Qed.\n\n  Lemma star_cons_eq:\n    forall (L:language) w1 w2,\n    In w1 L ->\n    In w2 (Star L) ->\n    In (w1 ++ w2) (Star L).\n  Proof.\n    intros.\n    apply star_cons with (w1:=w1) (w2:=w2); auto.\n  Qed.\n\n\nEnd Defs.\n\n\nDeclare Scope lang_scope.\n\nModule LangNotations.\n  Import Ascii.\n  Notation \"{}\" := Void : lang_scope.\n  Infix \">>\" := App (at level 40, left associativity) : lang_scope.\n  Notation \"a 'U' b\" := (Union a b) (at level 50, left associativity)  : lang_scope.\n  Notation \"x '*'\" := (Star x) (at level 20) : lang_scope.\n  Infix \"^^\" := Pow (right associativity, at level 35) : lang_scope.\n  Infix \"==\" := Equiv (at level 95, no associativity) : lang_scope.\n  Coercion Char: ascii >-> language.\nEnd LangNotations.\n\n\n\nSection Rewrites.\n  Import LangNotations.\n  Import List.\n  Import ListNotations.\n  Open Scope lang_scope.\n\n  Lemma union_assoc_rw:\n    forall L1 L2 L3,\n    L1 U (L2 U L3) == (L1 U L2) U L3.\n  Proof.\n    intros.\n    split; intros.\n    - apply union_assoc_in_1.\n      assumption.\n    - apply union_assoc_in_2.\n      assumption.\n  Qed.\n\n  Lemma union_sym_rw:\n    forall L1 L2,\n    L1 U L2 == L2 U L1.\n  Proof.\n    split; intros; destruct H; try (left; assumption); try (right; assumption).\n  Qed.\n\n  Lemma union_dup_rw:\n    forall L,\n    L U L == L.\n  Proof.\n    intros; split; intros.\n    - destruct H; assumption.\n    - left. assumption.\n  Qed.\n\n  Lemma star_any_rw:\n    Any * == All.\n  Proof.\n    split; intros.\n    - apply all_in.\n    - unfold Star.\n      generalize dependent H.\n      induction w; intros. {\n        exists 0.\n        apply pow_nil.\n      }\n      assert (All w) by auto using all_in.\n      destruct IHw as (n, Hp); auto.\n      exists (S n).\n      rewrite in_def in *.\n      apply pow_cons with (w1:=[a]) (w2:=w); auto.\n      rewrite in_def.\n      auto using any_in.\n  Qed.\n\n  Lemma app_r_void_rw:\n    forall (L:language),\n    L >> {} == {}.\n  Proof.\n    split; intros.\n    - apply app_in_inv in H.\n      destruct H as (w1, (w2, (?, (Ha, Hb)))).\n      apply void_not_in in Hb.\n      contradiction.\n    - apply void_not_in in H.\n      contradiction.\n  Qed.\n\n  Lemma app_l_void_rw:\n    forall (L:language),\n    {} >> L == {}.\n  Proof.\n    split; intros.\n    - apply app_in_inv in H.\n      destruct H as (w1, (w2, (?, (Ha,Hb)))).\n      apply void_not_in in Ha.\n      contradiction.\n    - apply void_not_in in H.\n      contradiction.\n  Qed.\n\n  Lemma app_l_nil_rw:\n    forall (L:language),\n    Nil >> L == L.\n  Proof.\n    intros.\n    split; intros.\n    - apply app_in_inv in H.\n      destruct H as (w1, (w2, (?, (Ha, Hb)))).\n      subst.\n      apply nil_in_inv in Ha.\n      subst.\n      assumption.\n    - apply app_in_eq with (w1:=[]) (w2:=w).\n      + apply nil_in.\n      + assumption.\n  Qed.\n\n  Lemma app_r_nil_rw:\n    forall (L:language),\n    L >> Nil == L.\n  Proof.\n    split; intros.\n    - apply app_in_inv in H.\n      destruct H as (w1, (w2, (?, (Ha, Hb)))).\n      subst.\n      apply nil_in_inv in Hb.\n      subst.\n      rewrite app_nil_r.\n      assumption.\n    - apply app_in with (w1:=w) (w2:=[]).\n      + assumption.\n      + apply nil_in.\n      + rewrite app_nil_r.\n        reflexivity.\n  Qed.\n\n  Lemma union_r_void_rw:\n    forall (L:language),\n    L U {} == L.\n  Proof.\n    split; intros.\n    + apply union_in_inv in H.\n      destruct H; auto.\n      apply void_not_in in H.\n      contradiction.\n    + left.\n      assumption. \n  Qed.\n\n  Lemma union_l_void_rw:\n    forall (L:language),\n    {} U L == L.\n  Proof.\n    split; intros.\n    - destruct H. {\n        apply void_not_in in H.\n        contradiction.\n      }\n      assumption.\n    - right.\n      assumption.\n  Qed.\n\n  Lemma union_r_all_rw:\n    forall (L:language),\n    L U All == All.\n  Proof.\n    split; intros.\n    + apply all_in.\n    + right.\n      assumption. \n  Qed.\n\n  Lemma union_l_all_rw:\n    forall (L:language),\n    All U L == All.\n  Proof.\n    split; intros.\n    - apply all_in.\n    - left.\n      assumption.\n  Qed.\n\n  Lemma app_star_rw:\n    forall (L:language),\n    L * >> L * == L  * .\n  Proof.\n    split; intros.\n    - apply app_in_inv in H.\n      destruct H as (w1, (w2, (?, (Ha, Hb)))).\n      subst.\n      destruct Ha as (n1, Ha).\n      destruct Hb as (n2, Hb).\n      exists (n1 + n2).\n      apply pow_add; auto.\n    - apply app_in_eq with (w1:=[]) (w2:=w).\n      + apply star_in_nil.\n      + assumption.\n  Qed.\n\n  Lemma star_star_rw:\n    forall (L:language),\n    L * * == L *.\n  Proof.\n    intros.\n    split; intros.\n    - apply star_to_pow in H.\n      destruct H as (n, Hn).\n      generalize dependent w.\n      induction n; intros. {\n        inversion Hn; subst; clear Hn.\n        apply star_in_nil.\n      }\n      inversion Hn; subst; clear Hn.\n      apply IHn in H0.\n      apply app_star_rw.\n      auto using app_in_eq.\n    - destruct H as (n, H).\n      exists 1.\n      apply pow_cons with (w1:=w) (w2:=nil).\n      + apply pow_nil.\n      + exists n.\n        assumption.\n      + auto with *.\n  Qed.\n\n  Lemma star_nil_rw:\n    Nil * == Nil.\n  Proof.\n    split; intros.\n    - apply star_to_pow in H.\n      destruct H as (n, H).\n      apply nil_pow_in_inv in H.\n      subst.\n      apply nil_in.\n    - apply nil_in_inv in H.\n      subst.\n      apply star_in_nil.\n  Qed.\n\n  Lemma star_void_rw:\n    {} * == Nil.\n  Proof.\n    split; intros.\n    - destruct H as (n, H).\n      apply void_pow_in_inv in H.\n      subst.\n      apply nil_in.\n    - apply nil_in_inv in H.\n      subst.\n      exists 0.\n      apply pow_nil.\n  Qed.\n\n  Lemma app_union_distr_l:\n    forall L1 L2 L3,\n    L1 >> L3 U L2 >> L3 == (L1 U L2) >> L3.\n  Proof.\n    split; intros.\n    - destruct H as [H|H]; apply app_in_inv in H; destruct H as (w1, (w2, (?, (Ha, Hb)))); subst;\n      apply app_in_eq; auto.\n      + left.\n        assumption.\n      + right.\n        assumption.\n    - apply app_in_inv in H.\n      destruct H as (w1, (w2, (?, (Ha, Hb)))); subst.\n      apply union_in_inv in Ha.\n      destruct Ha.\n      + apply union_in_l.\n        auto using app_in_eq.\n      + apply union_in_r.\n        auto using app_in_eq.\n  Qed.\n\n  Lemma pow_zero_rw:\n    forall L,\n    L ^^ 0 == Nil.\n  Proof.\n    split; intros.\n    - inversion H; subst; clear H.\n      apply nil_in.\n    - apply nil_in_inv in H.\n      subst.\n      apply pow_nil.\n  Qed.\n\n  Lemma pow_succ_equiv:\n    forall n L1 L2, \n    L1 == L2 ->\n    L1 ^^ n == L2 ^^ n ->\n    L1 ^^ S n == L2 ^^ S n.\n  Proof.\n    split; intros.\n    - inversion H1; subst; clear H1.\n      apply H0 in H3.\n      apply pow_cons with (w1:=w1) (w2:=w2); auto.\n      apply H in H4.\n      assumption.\n    - inversion H1; subst; clear H1.\n      apply H0 in H3.\n      apply pow_cons with (w1:=w1) (w2:=w2); auto.\n      apply H in H4.\n      assumption.\n  Qed.\n\n  (** A nil inside a star can be elided. *)\n\n  Lemma star_union_nil_rw:\n    forall L1,\n    (Nil U L1) * == L1 *.\n  Proof.\n    intros.\n    split; intros.\n    - destruct H as (n, H).\n      induction H.\n      + apply star_in_nil.\n      + subst.\n        destruct H0.\n        * inversion H0; subst; clear H0.\n          simpl.\n          assumption.\n        * apply star_cons_eq; auto.\n    - destruct H as (n, H).\n      induction H.\n      + apply star_in_nil.\n      + subst.\n        apply star_cons_eq; auto.\n        right.\n        assumption.\n  Qed.\n\nEnd Rewrites.\n\n\nModule Examples.\n  Import Ascii.\n  Import Util.\n  Import LangNotations.\n  Open Scope lang_scope.\n  Open Scope char_scope. (* Ensure by default we are representing characters. *)\n\n  (** Any string that ends with \"a\" *)\n  Definition L1 : language := All >> \"a\".\n\n  (** Show that the notation above is equivalent to writing a more direct, yet\n     more verbose notation: *)\n  Lemma l1_spec:\n    L1 == fun w => exists w', w = w' ++ [\"a\"].\n  Proof.\n    unfold L1.\n    (* When to unfold Equiv?\n       - If the language only uses operators, then use rewrite rules.\n       - If the language has a general specification (ie, without language\n         operators, then you must unfold Equiv.\n    *)\n    unfold Equiv.\n    (* A proof of equivalence consists of using destructor-lemmas on the\n       assumption and constructor-lemmas to conclude.\n       *)\n    split; intros.\n    - Search (In _ (_ >> _)).\n      (* \n       To note:\n        - Lemmas that end with _inv destruct the assumption\n        - Lemmas that end with _in_inv destruct assumptions In _ _\n\n       Thus, app_in_inv destructructs an assumption that holds an App\n      \n       Not to be confused with lemmas that start with app_in_,\n       they are *constructors*, which is necessary in the next goal.\n      *)\n      apply app_in_inv in H.\n      destruct H as (wa, (wb, (?, (Ha, Hb)))).\n      subst.\n      unfold In.\n      Search (In _ (Char _ )).\n      apply char_in_inv in Hb.\n      subst.\n      exists wa.\n      reflexivity.\n    - (* This is an arbitrary In relation, so we must open it. *)\n      unfold In in H.\n      (* Destruct its contents as much as possible. *)\n      destruct H as (wa, H).\n      (* Take care of equations *)\n      subst.\n      (* Search for constructors of App: *)\n      Search (In (_ ++ _) ( _ >> _)).\n      apply app_in_eq.\n      + Search (In _ All).\n        apply all_in.\n      + Search (In _ (Char _)).\n        apply char_in.\n  Qed.\n\n  (** Show that string \"a\" is in L1. *)\n  Lemma a_in_l1: In [\"a\"] L1.\n  Proof.\n    unfold L1.\n    (*\n      When using LangNotations, [] now becomes language Nil. If you use []\n      to represent the empty list, you will get the following error:\n      \n         The term \"[]\" has type \"word -> Prop\" while it is expected to have type \"list ascii\".\n     \n      To work around the issue use nil to represent the empty string.\n     *)\n    apply app_in with (w1:=[]) (w2:=[\"a\"]). (* When using lists use nil to represent  *)\n    + apply all_in.\n    + apply char_in.\n    + auto.\n    (* Alternative proof:\n    apply app_l_all_in_skip.\n    apply char_in.\n    *)\n  Qed.\n\n  (** Show that we can rewrite under In *)\n  Lemma a_in_l1_void: In [\"a\"] (L1 U {}).\n  Proof.\n    (* We recall that we can simplify the language by descarding {} *)\n    Search (_ U {}).\n    (* union_r_void_rw: forall L : language, L U {} == L *)\n    rewrite union_r_void_rw.\n    apply a_in_l1.\n  Qed.\n\n  (** Show that the empty string is not in L1. *)\n  Lemma nil_not_in_l1: ~ In [] L1.\n  Proof.\n    unfold L1; intros N.\n    Search (In _ (_ >> _)).\n    apply app_in_inv in N.\n    destruct N as (w1, (w2, (H1, (H2, H3)))).\n    (* We gather that (H1) w1 ++ w2 is the empty string *) \n    (* However, from (H3) we get that w2 is [\"a\"] *)\n    apply char_in_inv in H3.\n    subst.\n    (* We are not done, because we do not know what w1 is. Let us do a case\n       analysis on w1. *)\n    destruct w1.\n    + inversion H1. (* use the explosion principle, from w2 *)\n    + inversion H1. (* use the explosion principle, from w1 *)\n  Qed.\n\n  (** Show that string \"bbba\" is L1 *)\n\n  Lemma bbba_in_l1: In [\"b\"; \"b\"; \"b\"; \"a\"] L1.\n  Proof.\n    unfold L1.\n    apply app_in with (w1:=[\"b\"; \"b\"; \"b\"]) (w2:=[\"a\"]).\n    - apply all_in.\n    - apply char_in.\n    - reflexivity.\n  Qed.\n\n  (* An example that uses rewrites. *)\n  Goal\n    ((\"a\" >> {}) * U \"a\") * == \"a\" *.\n  Proof.\n    (* Nil and Void are always great candidates to start your search. *)\n    Search (_ >> {}).\n    (* We can simplify the App: *)\n    rewrite app_r_void_rw.\n    (* We note that we have another candidate, so we search *)\n    Search ({} *).\n    (* We simplify the void star. *)\n    rewrite star_void_rw.\n    (* Another candidate: *)\n    Search (Nil U _).\n    rewrite star_union_nil_rw.\n    (* Done. *)\n    reflexivity.\n  Qed.\n\n  Definition L2 : language := fun w => length w = 2.\n\n  (** Show that L2 can be described as concatenating two Any-characters. *)\n  Lemma l2_spec:\n    L2 == Any >> Any.\n  Proof.\n    unfold Examples.L2; split; intros.\n    - unfold In in H.\n      (* We know that w has length 2, but we must do a case analysis to look\n         at its structure. *)\n      destruct w. {\n        (* Impossible because w = [] *)\n        inversion H.\n      }\n      (* w <> [] *)\n      (* Let us try to get the remaining character. *)\n      destruct w. {\n        (* Impossible because w = [a] *)\n        inversion H.\n      }\n      destruct w. {\n        (* The only possible case where the list has exactly 2 elements. *)\n        Search (App Any _).\n        apply app_l_any_in.\n        apply any_in.\n      }\n      (* This case is impossible because the list has at least 3 elements. *)\n      inversion H.\n    - Search (Any >> _).\n      apply app_l_any_in_inv in H.\n      destruct H as (w', (c1, (?, Hi))).\n      subst.\n      apply any_in_inv in Hi.\n      destruct Hi as (c2, ?).\n      subst.\n      reflexivity.\n  Qed.\n\n  (** Show that string \"01\" is in L2. *)\n  Lemma _01_in_l2: In [\"0\"; \"1\"] L2.\n  Proof.\n    unfold L2.\n    reflexivity.\n  Qed.\n\n  Definition L3 : language := \"a\" >> All >> \"b\".\n\n  Lemma l3_spec:\n    L3 == fun w => exists w', [\"a\"] ++ w' ++ [\"b\"] = w.\n  Proof.\n    unfold L3; split; intros.\n    - apply app_r_char_in_inv in H.\n      destruct H as (w1, (?, Hw)).\n      apply app_l_char_in_inv in Hw.\n      destruct Hw as (w2, (?, _)).\n      subst.\n      simpl.\n      exists w2.\n      reflexivity.\n    - unfold In in H.\n      destruct H as (w', ?).\n      subst.\n      simpl.\n      apply app_assoc_in_1.\n      apply app_l_char_in.\n      apply app_l_all_in.\n      apply char_in.\n  Qed.\n\n  (** We define the language in terms of the Pow and App combinators. *)\n\n  Definition L4 := fun w => exists n, In w (\"a\" ^^ n >> \"b\" ^^ n).\n\n  (** We then show that this correspond to our expectation of when not using\n      combinators: *)\n  Lemma l4_spec:\n    L4 == fun x => exists n, pow1 \"a\" n ++ pow1 \"b\" n = x.\n  Proof.\n    unfold L4; split; intros.\n    - destruct H as (n, Hw).\n      exists n.\n      apply app_in_inv in Hw.\n      destruct Hw as (w1, (w2, (?, (Ha, Hb)))).\n      subst.\n      apply pow_char_in_inv in Ha.\n      apply pow_char_in_inv in Hb.\n      subst.\n      reflexivity.\n    - destruct H as (n, H).\n      subst.\n      exists n.\n      apply app_in_eq.\n      + apply pow_char_in.\n      + apply pow_char_in.\n  Qed.\n\n  (** L4 accepts the empty string. *)\n  Lemma nil_in_l4: In [] L4.\n  Proof.\n    unfold L4.\n    exists 0.\n    apply app_in with (w1:=[]) (w2:=[]).\n    + apply pow_nil.\n    + apply pow_nil.\n    + reflexivity.\n  Qed.\n\n  (** L4 accepts a single a and a single b. *)\n  Lemma aabb_in_l4: In [\"a\"; \"a\"; \"b\"; \"b\"] L4.\n  Proof.\n    exists 2.\n    apply app_in with (w1:=[\"a\"; \"a\"]) (w2:=[\"b\"; \"b\"]).\n    + apply pow_char_cons, pow_char_cons.\n      apply pow_nil.\n    + apply pow_char_cons, pow_char_cons.\n      apply pow_nil.\n    + reflexivity.\n  Qed.\n\n  Lemma abb_not_in_l4: ~ In [\"a\"; \"b\"; \"b\"] L4.\n  Proof.\n    unfold L4;\n    intros N.\n    destruct N as (n, N).\n    (* Let us rearrange the string to be in terms of Util.pow1. *)\n    assert (R: [\"a\"; \"b\"; \"b\"] = (pow1 \"a\" 1 ++ pow1 \"b\" 2) % list) by reflexivity.\n    rewrite R in *; clear R.\n    (* Our language is: a^n b^n = a^1 b^2, thus n = 1 and n = 2\n       and we reach a contradiction. *) \n    apply pow_pow_in_inv_eq in N.\n    - (* n = 1 and n = 2, contradiction *)\n      destruct N.\n      subst.\n      inversion H0.\n    - (* show that a = b *)\n      intros M.\n      inversion M.\n  Qed.\n\n  (** Show that this random string is not in L4 *)\n\n  Lemma car_not_in_l4: ~ In [\"c\"; \"a\"; \"r\"] L4.\n  Proof.\n    unfold L4.\n    intros N.\n    destruct N as (n, H).\n    (* Since the left-hand side has a power, we can enforce that the first\n       character has to be a 'a' if n > 0. Let us do a case analysis on n. *)\n    destruct n. {\n      apply app_in_inv in H.\n      destruct H as (w1, (w2, (Hs, (Ha, Hb)))).\n      (* Any power of 0 yields an empty string, so w1 = [] and w2 = [] *) \n      inversion Ha; subst.\n      inversion Hb; subst.\n      (* Thus \"car\" = \"\" which is a contradiction. *)\n      inversion Hs.\n    }\n    apply app_in_inv in H.\n    destruct H as (w1, (w2, (Hs, (Ha, Hb)))).\n    (* Ha is: a ^ (S n) = w, so we know that w = a :: w' *)\n    apply pow_char_cons_inv in Ha.\n    destruct Ha as (w', (?, ?)).\n    subst.\n    (* Hs now says that on the lhs starts with c and rhs starts with a,\n       contradiction. *)\n    inversion Hs.\n  Qed.\n\nEnd Examples.\n", "meta": {"author": "yforster", "repo": "cs420-library", "sha": "6e7725535c50efd4da4c253de5933cc6e8974390", "save_path": "github-repos/coq/yforster-cs420-library", "path": "github-repos/coq/yforster-cs420-library/cs420-library-6e7725535c50efd4da4c253de5933cc6e8974390/src/Lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.660475066829647}}
{"text": "Require Import Setoid.\nRequire Import Morphisms.\nRequire Import Coq.Program.Basics.\nRequire Import Program.Wf.\n\nUnset Printing Records.\n\nFrom Ordinal Require Import Defs.\nFrom Ordinal Require Import Operators.\nFrom Ordinal Require Import Arith.\nFrom Ordinal Require Import Fixpoints.\nFrom Ordinal Require Import VeblenDefs.\n\nRequire Import List.\nImport ListNotations.\nOpen Scope list.\n\nSection VeblenSymbol.\n  Variable Idx : Type.\n  Variable idx_lt : Idx -> Idx -> Prop.\n  Variable idx_zero : Idx.\n  Variable idx_succ : Idx -> Idx.\n\n  Hypothesis idx_lt_trans: forall x y z, idx_lt x y -> idx_lt y z -> idx_lt x z.\n  Hypothesis idx_lt_wf : well_founded idx_lt.\n  Hypothesis idx_succ_lt : forall x, idx_lt x (idx_succ x).\n\n  Definition idx_le i j := forall x, idx_lt x i -> idx_lt x j.\n\n  Fixpoint well_formed_tail i (ls:list (Idx * Ord)) : Prop :=\n    match ls with\n    | [] => True\n    | ((j,x) :: ls') => idx_lt i j /\\ well_formed_tail j ls'\n    end.\n\n  Definition well_formed_symbol (ls:list (Idx * Ord)) : Prop :=\n    match ls with\n    | [] => True\n    | ((i,x) :: ls') => well_formed_tail i ls'\n    end.\n\n  Lemma well_formed_tail_symbol i ls : well_formed_tail i ls -> well_formed_symbol ls.\n  Proof.\n    destruct ls; simpl in *; intuition.\n    destruct p. intuition.\n  Qed.\n\n  Fixpoint indices_bounded (ls:list (Idx * Ord)) (i:Idx) : Prop :=\n    match ls with\n    | [] => True\n    | ((j,x) :: ls') => idx_lt j i /\\ indices_bounded ls' i\n    end.\n\n  Lemma well_formed_symbols_bounded : forall ls, well_formed_symbol ls -> exists i, indices_bounded ls i.\n  Proof.\n    intros ls. destruct ls.\n    - exists idx_zero. simpl. auto.\n    - destruct p as [j x].\n      simpl.\n      clear x.\n      revert j.\n      induction ls.\n      + simpl; intros.\n        exists (idx_succ j). split; auto.\n      + intros.\n        destruct a as [k y].\n        simpl in *.\n        destruct H as [Hk H].\n        destruct (IHls k H) as [i [??]].\n        exists i; intuition.\n        apply idx_lt_trans with k; auto.\n  Qed.\n\n  Lemma is_well_formed_tail a xs : well_formed_symbol (a::xs) -> well_formed_symbol xs.\n  Proof.\n    destruct a. simpl. destruct xs; intuition.\n    apply well_formed_tail_symbol with i; auto.\n  Qed.\n\n  Lemma is_well_formed_cons j y i x x' ls :\n    idx_lt j i ->\n    well_formed_symbol ((i,x)::ls) ->\n    well_formed_symbol ((j,y)::(i,x')::ls).\n  Proof.\n    simpl; intros. split; auto.\n  Qed.\n\n  Lemma is_well_formed_prefix : forall xs ys, well_formed_symbol (xs ++ ys) -> well_formed_symbol xs.\n  Proof.\n    destruct xs; simpl; auto.\n    destruct p as [i _].\n    revert i; induction xs; simpl; intuition; eauto.\n  Qed.\n\n  Lemma well_formed_tail_bounded : forall xs i j o ys,\n      well_formed_tail i (xs ++ (j,o) :: ys) -> idx_lt i j /\\ indices_bounded xs j.\n  Proof.\n    induction xs; simpl.\n    - intuition.\n    - destruct a as [k _]. simpl; intros i j o ys [H1 H2].\n      apply IHxs in H2.\n      intuition.\n      apply idx_lt_trans with k; auto.\n  Qed.\n\n  Lemma well_formed_bounded : forall xs j o ys,\n      well_formed_symbol (xs ++ (j,o) :: ys) -> indices_bounded xs j.\n  Proof.\n    destruct xs; simpl.\n    - intuition.\n    - destruct p as [k _].\n      apply well_formed_tail_bounded.\n  Qed.\n\n  Definition VeblenSymbol := { ls:list (Idx*Ord) | well_formed_symbol ls }.\n\n  Inductive symbol_lt : list (Idx*Ord) -> list (Idx*Ord) -> Prop :=\n  | symbol_lt_drop : forall i x ls, symbol_lt ls ((i,x)::ls)\n  | symbol_lt_ord  : forall i x x' ls ys,\n      x' < x ->\n      indices_bounded ys i ->\n      symbol_lt (ys ++ ((i,x')::ls)) ((i,x)::ls).\n\n  Definition VeblenSymbol_lt (xs ys : VeblenSymbol) : Prop :=\n    symbol_lt (proj1_sig xs) (proj1_sig ys).\n\n  Lemma symbol_lt_append_Acc : forall a,\n    Acc symbol_lt a ->\n    forall b, Acc symbol_lt b ->\n    Acc symbol_lt (a ++ b).\n  Proof.\n    intros a Ha. induction Ha.\n    intros b Hb.\n    destruct x as [|[j o] x].\n    - simpl; auto.\n    - simpl.\n      constructor. simpl; intros.\n      inversion H1; subst.\n      + apply H0; auto.\n        apply symbol_lt_drop.\n      + cut (Acc symbol_lt ((ys ++ ((j,x') :: x)) ++ b)).\n        { rewrite <- app_assoc. auto. }\n        apply H0; auto.\n        apply symbol_lt_ord; auto.\n  Qed.\n\n  Theorem symbol_lt_bounded_Acc : forall i xs, indices_bounded xs i -> Acc symbol_lt xs.\n  Proof.\n    induction i as [i Hind_i] using (well_founded_induction idx_lt_wf).\n    induction xs; intros.\n    - constructor. intros ys Hys.\n      inversion Hys.\n    - destruct a as [j x]. simpl in *. destruct H.\n      induction x as [x Hind_x] using ordinal_induction.\n      constructor. intros ys. intro Hys.\n      inversion Hys; subst.\n      + apply IHxs; auto.\n      + apply symbol_lt_append_Acc.\n        * apply (Hind_i j); auto.\n        * apply Hind_x; auto.\n  Qed.\n\n  Theorem symbol_lt_well_formed_Acc : forall xs, well_formed_symbol xs -> Acc symbol_lt xs.\n  Proof.\n    intros.\n    destruct (well_formed_symbols_bounded xs H) as [i Hi].\n    apply (symbol_lt_bounded_Acc i xs Hi).\n  Qed.\n\n  Section MultiVeblen.\n    Variable f : Ord -> Ord.\n\n    Lemma step_down i (j:{ j:Idx | idx_lt j i}) A g ai y ls :\n      symbol_lt ((proj1_sig j,y)::(i,g ai)::ls) ((i,ord A g)::ls).\n    Proof.\n      apply (symbol_lt_ord i (ord A g) (g ai) ls [(proj1_sig j,y)]).\n      - apply (index_lt (ord A g) ai).\n      - simpl; split; auto. apply (proj2_sig j).\n    Qed.\n\n    Fixpoint MultiVeblen (xs : list (Idx*Ord)) (HAcc : Acc symbol_lt xs) {struct HAcc} : Ord -> Ord :=\n      fix inner (x:Ord) : Ord :=\n        match xs as xs' return Acc symbol_lt xs' -> Ord with\n        | [] => fun _ => f x\n        | ((i,ord A g)::ls) => fun HAcc' =>\n            match HAcc' with\n            | Acc_intro _ Hsub =>\n              MultiVeblen ls (Hsub ls (symbol_lt_drop i (ord A g) ls)) x ⊔\n              match x with\n              | ord X h =>\n                @supOrd A (fun ai =>\n                   fixOrd (MultiVeblen ((i,g ai)::ls) (Hsub _ (symbol_lt_ord i (ord A g) (g ai) ls nil (index_lt (ord A g) ai) I)))\n                              (ord X (fun xi => inner (h xi)))\n                   ⊔\n                @supOrd { j:Idx | idx_lt j i} (fun j =>\n                   fixOrd (fun y => MultiVeblen ((proj1_sig j,y)::(i,g ai)::ls) (Hsub _ (step_down i j A g ai y ls)) zeroOrd)\n                       (ord X (fun xi => inner (h xi)))\n                   ))\n              end\n        end\n      end HAcc.\n\n   End MultiVeblen.\nEnd VeblenSymbol.\n\nDefinition nat_symbol := list (nat*Ord).\n\nRequire Import Lia.\n\nLemma nat_symbol_bounded : forall (x:nat_symbol), exists i, indices_bounded nat lt x i.\nProof.\n  induction x; simpl.\n  - exists O. auto.\n  - destruct IHx as [i Hi].\n    destruct a as [j _]; simpl.\n    exists (Peano.max i (S j)).\n    split; [ lia | ].\n    induction x; simpl.\n    + auto.\n    + destruct a as [k y]; simpl in *.\n      split; [ lia | intuition ].\nQed.\n\nRequire Import Wf_nat.\n\nLemma nat_symbol_lt_wf : well_founded (symbol_lt nat lt).\nProof.\n  intro x.\n  destruct (nat_symbol_bounded x) as [i Hi].\n  apply symbol_lt_bounded_Acc with i; auto.\n  apply lt_wf.\nQed.\n\nDefinition nth_veblen (n:nat) : Ord -> Ord :=\n  MultiVeblen nat lt powOmega [(n,1)] (nat_symbol_lt_wf [(n,1)]).\n\nDefinition SmallVeblenOrdinal : Ord := ord nat (fun n => nth_veblen n 0).\n", "meta": {"author": "robdockins", "repo": "ordinals", "sha": "063164521baddfc99ab8c2d222cb01637e8833e1", "save_path": "github-repos/coq/robdockins-ordinals", "path": "github-repos/coq/robdockins-ordinals/ordinals-063164521baddfc99ab8c2d222cb01637e8833e1/Ordinal/VeblenSymbol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6603609716416117}}
{"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(** ** Luca's theorem *)\n\nRequire Import Arith Nat Omega Lia List.\nRequire Import utils_tac gcd prime binomial sums Zp rel_iter.\n\nSet Implicit Arguments.\n\nLocal Notation power := (mscal mult 1).\nLocal Notation expo := (mscal mult 1).\n\nSection fact.\n\n  Let factorial_cancel n a b : fact n * a = fact n * b -> a = b.\n  Proof.\n    apply Nat.mul_cancel_l.\n    generalize (fact_gt_0 n); intro; lia.\n  Qed.\n  \n  Notation Π := (msum mult 1).\n\n  Notation mprod_an := (fun a n => Π n (fun i => i+a)).\n\n  Fact mprod_factorial n : fact n = mprod_an 1 n.\n  Proof.\n    induction n as [ | n IHn ].\n    + rewrite msum_0; auto.\n    + rewrite msum_plus1; auto.\n      rewrite mult_comm, <- IHn, fact_S.\n      f_equal; lia.\n  Qed.\n\n  Variable (p : nat) (Hp : p <> 0).\n\n  Notation \"〚 x 〛\" := (nat2Zp Hp x).\n\n  Let expo_p_cancel n a b : expo n p * a = expo n p * b -> a = b.\n  Proof.\n    apply Nat.mul_cancel_l.\n    generalize (power_ge_1 n Hp); intros; lia.\n  Qed.\n\n  Fact mprod_factorial_Zp i n :〚mprod_an (i*p+1) n〛=〚fact n〛.\n  Proof.\n    rewrite mprod_factorial.\n    induction n as [ | n IHn ].\n    + do 2 rewrite msum_0; auto.\n    + do 2 (rewrite msum_plus1; auto).\n      do 2 rewrite nat2Zp_mult; f_equal; auto.\n      apply nat2Zp_inj.\n      rewrite (plus_comm n), <- plus_assoc, plus_comm.\n      rewrite <- rem_plus_div; auto.\n      * f_equal; lia.\n      * apply divides_mult, divides_refl.\n  Qed.\n\n  Notation φ := (fun n r => mprod_an (n*p+1) r).\n  Notation Ψ := (fun n => Π n (fun i => mprod_an (i*p+1) (p-1))).\n\n  Let phi_Zp_eq n r :〚φ n r〛=〚fact r〛.\n  Proof. apply mprod_factorial_Zp. Qed.\n\n  Fact mprod_factorial_mult n : fact (n*p) = expo n p * fact n * Ψ n.\n  Proof.\n    induction n as [ | n IHn ].\n    + rewrite Nat.mul_0_l, msum_0, mscal_0, fact_0; auto.\n    + replace (S n*p) with (n*p+p) by ring.\n      rewrite mprod_factorial, msum_plus, <- mprod_factorial; auto.\n      replace p with (S (p-1)) at 2 by omega.\n      rewrite msum_plus1; auto.\n      rewrite <- plus_assoc.\n      replace (p-1+1) with p by omega.\n      replace (n*p+p) with ((S n)*p) by ring.\n      rewrite mscal_S, fact_S, msum_S.\n      rewrite IHn.\n      repeat rewrite mult_assoc.\n      rewrite (mult_comm _ p).\n      repeat rewrite <- mult_assoc.\n      do 2 f_equal.\n      rewrite (mult_comm (S n)).\n      repeat rewrite <- mult_assoc; f_equal.\n      repeat rewrite mult_assoc; f_equal.\n      rewrite msum_ext with (f := fun i => n*p+i+1)\n                            (g := fun i => i+(n*p+1)).\n      2: intros; ring. \n      rewrite <- msum_plus1; auto.\n  Qed.\n \n  Lemma mprod_factorial_euclid n r : fact (n*p+r) = expo n p * fact n * φ n r * Ψ n.\n  Proof.\n    rewrite mprod_factorial, msum_plus; auto.\n    rewrite <- mprod_factorial.\n    rewrite msum_ext with (f := fun i => n*p+i+1)\n                          (g := fun i => i+(n*p+1)).\n    2: intros; ring. \n    rewrite mprod_factorial_mult; auto; ring.\n  Qed.\n\n  Notation Zp := (Zp_zero Hp).\n  Notation Op := (Zp_one Hp).\n  Notation \"∸\" := (Zp_opp Hp).\n  Infix \"⊗\" := (Zp_mult Hp) (at level 40, left associativity).\n  Notation expoZp := (mscal (Zp_mult Hp) (Zp_one Hp)).\n\n  Hint Resolve Nat_mult_monoid.\n\n  Let Psi_Zp_eq n :〚Ψ n〛= expoZp n〚fact (p-1)〛.\n  Proof.\n    induction n as [ | n IHn ].\n    + rewrite msum_0, mscal_0; auto.\n    + rewrite msum_plus1, nat2Zp_mult.\n      rewrite mscal_plus1; auto.\n      2: apply Zp_mult_monoid.\n      2: apply Nat_mult_monoid.\n      f_equal; auto.\n  Qed.\n\n  Hypothesis (Hprime : prime p).\n\n  Let phi_Zp_invertible n r : r < p -> Zp_invertible Hp 〚φ n r〛.\n  Proof.\n    intros H; simpl; rewrite phi_Zp_eq.\n    apply Zp_invertible_factorial; auto.\n  Qed.\n\n  Let Psi_Zp_invertible n : Zp_invertible Hp 〚Ψ n〛.\n  Proof.\n    simpl; rewrite (Psi_Zp_eq n).\n    apply Zp_expo_invertible, Zp_invertible_factorial; auto; omega.\n  Qed.\n\n  (** rewrite the binomial theorem\n\n               fact k * fact (n-k) * binomial n k = fact n   \n\n      when      \n\n         k = K*p + k0\n         n = N*p + n0\n\n      with\n       \n      1)  K <= N & k0 <= n0\n   \n      we get n-k = (N-K)*p + (n0-k0) and\n\n        expo K     p * fact K     * φ K      k0     * Ψ K\n      .* expo (N-K) p * fact (N-K) * φ (N-K) (n0-k0) * Ψ (N-K)\n      .* binomial n k \n      = expo N p     * fact N     * φ N      n0     * Ψ N.\n\n      hence, simplifying by expo N p  we get\n\n        fact K * fact (N-K) * φ K k0 * Ψ K * φ (N-K) (n0-k0) * Ψ (N-K) * binomial n k = fact N * φ N n0 * Ψ N. \n\n      then in Z/Zp we derive (modulo Wilson's theorem, unnecessary here〚fact (p-1)〛=〚-1〛) \n\n       〚fact K〛⊗〚fact (N-K)〛⊗〚fact k0〛⊗〚-1〛^K⊗〚fact (n0-k0)〛⊗〚-1〛^(N-K)⊗〚binomial n k〛\n      =〚fact N〛⊗〚fact n0〛⊗〚-1〛^N\n\n        that we combine with 〚fact K〛⊗〚fact (N-K)〛⊗〚binomial N K〛=〚fact N〛\n                        and  〚fact k0〛⊗〚fact (n0-k0)〛⊗〚binomial n0 k0〛=〚fact n0〛\n\n        to derive the result:〚binomial n k 〛=〚binomial N K〛⊗〚binomial n0 k0〛\n\n      with \n \n      2) K < N & n0 < k0\n\n      we have n-k = (N-(K+1))*p + (p-(k0-n0)) and\n\n        expo K         p * fact K         * φ K          k0         * Ψ K\n      .* expo (N-(K+1)) p * fact (N-(K+1)) * φ (N-(K+1)) (p-(k0-n0)) * Ψ (N-(K+1))\n      .* binomial n k \n      = expo N p     * fact N     * φ N      n0     * Ψ N.\n\n      hence\n \n         fact K * φ K k0 * Ψ K * fact (N-(K+1)) * φ (N-(K+1)) (p-(k0-n0)) * Ψ (N-(K+1)) * binomial n k \n       = p * ....\n\n      then in Z/Zp all the left factor are invertible except binomial n k which must thus be〚0〛 *)\n\n  Section binomial_without_p_not_zero.\n\n    Variable (n N n0 k K k0 : nat) (Hn : n = N*p+n0) (Hk : k = K*p+k0) (H1 : K <= N) (H2 : k0 <= n0).\n\n    Let Hkn : k <= n.\n    Proof.\n      rewrite Hn, Hk.\n      replace N with (K+(N-K)) by omega.\n      rewrite Nat.mul_add_distr_r.\n      generalize ((N-K)*p); intros; omega.\n    Qed.\n   \n    Let Hnk : n - k = (N-K)*p+(n0-k0).\n    Proof.\n      rewrite Hn, Hk, Nat.mul_sub_distr_r.\n      cut (K*p <= N*p).\n      + generalize (K*p) (N*p); intros; omega.\n      + apply mult_le_compat; auto.\n    Qed.\n  \n    Fact binomial_wo_p : φ K k0 * Ψ K * φ (N-K) (n0-k0) * Ψ (N-K) * binomial n k \n                       = binomial N K * φ N n0 * Ψ N.\n    Proof.\n      apply (factorial_cancel (N-K)); repeat rewrite mult_assoc.\n      rewrite (mult_comm (fact _) (binomial _ _)).\n      apply (factorial_cancel K); repeat rewrite mult_assoc.\n      rewrite (mult_comm (fact _) (binomial _ _)).\n      rewrite <- binomial_thm; auto.\n      apply expo_p_cancel with N.\n      repeat rewrite mult_assoc.\n      rewrite <- mprod_factorial_euclid, <- Hn.\n      rewrite binomial_thm with (1 := Hkn).\n      rewrite Hnk. \n      rewrite Hk at 3.\n      replace N with (K+(N-K)) at 1 by omega.\n      rewrite power_plus.\n      do 2 rewrite mprod_factorial_euclid.\n      ring.\n    Qed.\n\n    Hypothesis (Hn0 : n0 < p).\n\n    Hint Resolve Zp_mult_monoid.\n\n    Fact binomial_Zp_prod :〚binomial n k〛=〚binomial N K〛⊗〚binomial n0 k0〛.\n    Proof.\n      generalize binomial_wo_p; intros G.\n      apply f_equal with (f := nat2Zp Hp) in G.\n      repeat rewrite nat2Zp_mult in G.\n      repeat rewrite Psi_Zp_eq in G.\n      repeat rewrite phi_Zp_eq in G.\n      rewrite binomial_thm with (1 := H2) in G.\n      repeat rewrite nat2Zp_mult in G.\n      rewrite (Zp_mult_comm _ _〚 fact k0 〛) in G.\n      repeat rewrite Zp_mult_assoc in G.\n      rewrite (Zp_mult_comm _ _〚 fact k0 〛) in G.\n      repeat rewrite <- Zp_mult_assoc in G.\n      apply Zp_invertible_cancel_l in G.\n      2: apply Zp_invertible_factorial; auto; omega.\n      repeat rewrite Zp_mult_assoc in G.\n      do 2 rewrite (Zp_mult_comm _ _〚 fact _ 〛) in G.\n      repeat rewrite <- Zp_mult_assoc in G.\n      apply Zp_invertible_cancel_l in G.\n      2: apply Zp_invertible_factorial; auto; omega.\n      repeat rewrite Zp_mult_assoc in G.\n      rewrite <- mscal_plus in G; auto.\n      replace (K+(N-K)) with N in G by omega.\n      rewrite (Zp_mult_comm _ _ (expoZp _ _)) in G.\n      apply Zp_invertible_cancel_l in G; trivial.\n      apply Zp_expo_invertible, Zp_invertible_factorial; auto; omega.\n    Qed.\n\n  End binomial_without_p_not_zero.\n\n  Section binomial_without_p_zero.\n\n    Variable (n N n0 k K k0 : nat) (Hn : n = N*p+n0) (Hk : k = K*p+k0) \n             (H1 : K < N) (H2 : n0 < k0) (Hk0 : k0 < p).\n\n    Let H3 : p - (k0-n0) < p.    Proof. omega. Qed.\n    Let H4 : S (N-1) = N.        Proof. omega. Qed.\n    Let H5 : N-1 = K+(N-(K+1)).  Proof. omega. Qed.\n    Let H6 : N = K+1+(N-(K+1)).  Proof. omega. Qed.\n    Let HNK : N-K = S (N-(K+1)). Proof. omega. Qed.\n\n    Let Hkn : k <= n.\n    Proof.\n      rewrite Hn, Hk, H6.\n      do 2 rewrite Nat.mul_add_distr_r.\n      generalize ((N-(K+1))*p); clear H3 H4 H5 H6 HNK; intros; omega.\n    Qed.\n   \n    Let Hnk : n - k = (N-(K+1))*p+(p-(k0-n0)).\n    Proof.\n      rewrite Hn, Hk, Nat.mul_sub_distr_r.\n      cut ((K+1)*p <= N*p).\n      + rewrite Nat.mul_add_distr_r.\n        generalize (K*p) (N*p); clear H3 H4 H5 H6 HNK Hkn; intros; omega.\n      + apply mult_le_compat; auto; clear H3 H4 H5 H6 HNK Hkn; omega.\n    Qed.\n\n    Fact binomial_with_p : fact K * fact (N-(K+1)) * φ K k0 * Ψ K * φ (N-(K+1)) (p-(k0-n0)) * Ψ (N-(K+1)) * binomial n k \n                         = p * fact N * φ N n0 * Ψ N.\n    Proof.\n      apply expo_p_cancel with (N-1).\n      repeat rewrite mult_assoc.\n      rewrite (mult_comm (expo _ _) p).\n      rewrite <- mscal_S.\n      rewrite H4, <- mprod_factorial_euclid, <- Hn.\n      rewrite binomial_thm with (1 := Hkn).\n      rewrite Hnk.\n      rewrite Hk at 3.\n      do 2 rewrite mprod_factorial_euclid.\n      rewrite H5 at 1.\n      rewrite power_plus.\n      ring.\n    Qed.\n\n    Fact binomial_with_p' : φ K k0 * Ψ K * φ (N-(K+1)) (p-(k0-n0)) * Ψ (N-(K+1)) * binomial n k \n                          = p * binomial N K * (N-K) * φ N n0 * Ψ N.\n    Proof.\n      apply (factorial_cancel (N-(K+1))); repeat rewrite mult_assoc.\n      apply (factorial_cancel K); repeat rewrite mult_assoc.\n      rewrite binomial_with_p.\n      rewrite binomial_thm with (n := N) (p := K).\n      2: { apply lt_le_weak; auto. }\n      rewrite HNK at 1.\n      rewrite fact_S.\n      rewrite <- HNK.\n      ring.\n    Qed.\n \n    Fact binomial_Zp_zero :〚binomial n k〛= Zp.\n    Proof.\n      generalize binomial_with_p'; intros G.\n      apply f_equal with (f := nat2Zp Hp) in G.\n      repeat rewrite nat2Zp_mult in G.\n      rewrite nat2Zp_p in G.\n      repeat rewrite Zp_mult_zero in G.\n      apply Zp_invertible_eq_zero in G; auto.\n      repeat (apply Zp_mult_invertible; auto).\n    Qed.\n\n  End binomial_without_p_zero.\n\nEnd fact.\n\nSection lucas_lemma.\n\n  (* https://math.stackexchange.com/questions/1463758/proof-of-lucas-theorem-without-the-polynomial-hint *)\n\n  Variables (p : nat) (Hprime : prime p).\n\n  Let Hp : p <> 0.\n  Proof.\n    generalize (prime_ge_2 Hprime); intro; omega.\n  Qed.\n\n  Variables (n N n0 k K k0 : nat)\n            (G1 : n = N*p+n0)  (G2 : n0 < p)\n            (G3 : k = K*p+k0)  (G4 : k0 < p).\n\n  Let choice : (K <= N  /\\ k0 <= n0)\n            \\/ (n0 < k0 /\\ K < N)\n            \\/ ((n0 < k0 \\/ N < K) /\\ n < k).\n  Proof.\n    destruct (le_lt_dec k n) as [ H0 | H0 ];\n    destruct (le_lt_dec k0 n0) as [ H1 | H1 ];\n    destruct (le_lt_dec K N) as [ H2 | H2 ]; try omega.\n    + do 2 right; split; auto.\n      rewrite G1, G3.\n      replace K with (N+1+(K-N-1)) by omega.\n      do 2 rewrite Nat.mul_add_distr_r.\n      generalize ((K-N-1)*p); intros; omega.\n    + destruct (eq_nat_dec N K); try omega.\n      do 2 right; split; auto.\n      rewrite G1, G3; subst N; omega.\n    + do 2 right; split; auto.\n      rewrite G1, G3.\n      replace K with (N+1+(K-N-1)) by omega.\n      do 2 rewrite Nat.mul_add_distr_r.\n      generalize ((K-N-1)*p); intros; omega.\n  Qed.\n\n  Theorem lucas_lemma : rem (binomial n k) p = rem (binomial N K * binomial n0 k0) p.\n  Proof.\n    destruct choice as [ (H1 & H2) \n                     | [ (H1 & H2)\n                       | (H1 & H2) ] ]; clear choice.\n    3: { rewrite binomial_gt with (1 := H2).\n         f_equal.\n         destruct H1 as [ H1 | H1 ]; \n           rewrite binomial_gt with (1 := H1); ring. }\n    + apply nat2Zp_inj with (Hp := Hp).\n      rewrite nat2Zp_mult.\n      apply binomial_Zp_prod; auto.\n    + rewrite binomial_gt with (1 := H1).\n      rewrite Nat.mul_0_r.\n      apply nat2Zp_inj with (Hp := Hp).\n      rewrite nat2Zp_zero.\n      apply binomial_Zp_zero with (2 := G1) (3 := G3); auto.\n  Qed.\n\nEnd lucas_lemma.\n\nCheck lucas_lemma.\nPrint Assumptions lucas_lemma.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/coq-library-undecidability/H10/ArithLibs/luca.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6603609606391715}}
{"text": "Require Import Coq.Lists.List.\nImport ListNotations.\n\nSet Implicit Arguments.\n\nSection Prefix.\n\n  Variable A : Type.\n\n  Inductive prefix : list A -> list A -> Prop :=\n  | prefix_empty : forall l, prefix [] l\n  | prefix_cons : forall x l l', prefix l l' -> prefix (x::l) (x::l').\n\n  Lemma prefix_refl :\n    forall l, prefix l l.\n  Proof.\n    induction l; constructor; assumption.\n  Qed.\n\n  Lemma prefix_app :\n    forall l1 l2 l3, prefix l1 l2 -> prefix l1 (l2 ++ l3).\n  Proof.\n    intros l1 l2 l3 Hpre.\n    induction Hpre; simpl; constructor; assumption.\n  Qed.\n\n  Lemma prefix_app_exists :\n    forall l1 l3, prefix l1 l3 -> exists l2, l3 = l1 ++ l2.\n  Proof.\n    intros l1 l2 Hpre.\n    induction Hpre.\n    exists l; reflexivity.\n    inversion IHHpre as [l2 Hl2].\n    rewrite Hl2.\n    exists l2.\n    reflexivity.\n  Qed.\n\nEnd Prefix.\n\n\nSection Postfix.\n\n  Variable A : Type.\n\n  Inductive postfix (l : list A) : list A -> Prop :=\n  | postfix_refl : postfix l l\n  | postfix_cons : forall x l', postfix l l' -> postfix l (x::l').\n\n  Lemma postfix_empty :\n    forall l, postfix [] l.\n  Proof.\n    induction l; constructor; assumption.\n  Qed.\n\n  Lemma postfix_app :\n    forall l1 l2 l3, postfix l1 l2 -> postfix (l1 ++ l3) (l2 ++ l3).\n  Proof.\n    intros l1 l2 l3 Hpost.\n    induction Hpost; simpl; constructor; assumption.\n  Qed.\n\n  Lemma postfix_app_exists :\n    forall l1 l3, postfix l1 l3 -> exists l2, l3 = l2 ++ l1.\n  Proof.\n    intros l1 l3 Hpost.\n    induction Hpost.\n    exists []; reflexivity.\n    rename l' into l3.\n    inversion IHHpost as [l2 Hl2].\n    exists (x::l2); simpl.\n    rewrite Hl2; reflexivity.\n  Qed.\n\n  Theorem prefix_postfix_rev :\n    forall l1 l2, prefix l1 l2 -> postfix (rev l1) (rev l2).\n  Proof.\n    intros l1 l2 Hpre.\n    induction Hpre.\n    apply postfix_empty.\n    apply postfix_app.\n    assumption.\n  Qed.\n\n  Theorem postfix_prefix_rev :\n    forall l1 l2, postfix l1 l2 -> prefix (rev l1) (rev l2).\n  Proof.\n    intros l1 l2 Hpost.\n    induction Hpost.\n    apply prefix_refl.\n    apply prefix_app.\n    assumption.\n  Qed.\n\nEnd Postfix.\n\nSection Assoc.\n\n  Variable A : Type.\n  Hypothesis eq_dec : forall x y : A, {x = y} + {x <> y}.\n  Variable B : Type.\n\n  Fixpoint assoc (l : list (A*B)) (x : A) : option B :=\n    match l with\n    | [] => None\n    | ab::l' => let '(a,b) := ab in if eq_dec x a then Some b else assoc l' x\n    end.\n\nEnd Assoc.\n\nSection FunctionDef.\n\n  Variable A B : Type.\n  Variable R : A -> B -> Prop.\n\n  Definition function := forall a, exists! b, R a b.\n\n  Theorem function_eq :\n    function ->\n    forall a b b', R a b -> R a b' -> b' = b.\n  Proof.\n    unfold function.\n    intros H a b b' Hb Hb'.\n    specialize (H a).\n    inversion H as [b'' Huniq].\n    replace b with b'' by (apply Huniq; assumption).\n    replace b' with b'' by (apply Huniq; assumption).\n    reflexivity.\n  Qed.\n\nEnd FunctionDef.\n\nSection ListRel.\n\n  Variable A B : Type.\n  Variable R : A -> B -> Prop.\n\n  Inductive list_rel : list A -> list B -> Prop :=\n  | list_rel_nil : list_rel [] []\n  | list_rel_cons : forall x xs y ys,\n      list_rel xs ys -> R x y -> list_rel (x::xs) (y::ys).\n\n  Theorem function_rel__function_list_rel :\n    function R -> function list_rel.\n  Proof.\n    unfold function.\n    intros Hf xs.\n    induction xs as [|x xs].\n\n    (* Nil *)\n    exists [].\n    split.\n    constructor.\n    intros ys Hlr.\n    inversion Hlr.\n    reflexivity.\n\n    (* Cons *)\n    inversion IHxs as [ys Hys]; subst; clear IHxs.\n    specialize (Hf x).\n    inversion Hf as [y Hy]; subst; clear Hf.\n    exists (y::ys).\n    destruct Hys as [Hlrs Hys_uniq].\n    destruct Hy as [HRxy Hy_uniq].\n    split.\n    constructor; assumption.\n    intros ys'.\n    destruct ys' as [|y' ys']; intros H; inversion H; subst; clear H.\n    replace y' with y by (apply Hy_uniq; assumption).\n    replace ys' with ys by (apply Hys_uniq; assumption).\n    reflexivity.\n  Qed.\n\n  Theorem function_list_rel__function_rel :\n    function list_rel -> function R.\n  Proof.\n    unfold function.\n    intros H a.\n    specialize (H [a]).\n    inversion H as [bs (Hb,Huniq)].\n    destruct bs; inversion Hb; subst; clear Hb.\n    exists b.\n    split.\n    assumption.\n    intros b' Hb'.\n    inversion H3; subst; clear H3.\n    assert (list_rel [a] [b']) as Hlb'.\n    constructor.\n    constructor.\n    assumption.\n    specialize (Huniq [b'] Hlb').\n    inversion Huniq.\n    reflexivity.\n  Qed.\n\nEnd ListRel.\n\n\nSection ListRelEq.\n\n  Variable A : Type.\n\n  Theorem list_rel_eq__list_eq :\n    forall (l1 l2 : list A), list_rel eq l1 l2 -> l1 = l2.\n  Proof.\n    induction l1; intros l2 Hlr;\n      inversion Hlr as [ | x xs y ys]; subst.\n    reflexivity.\n    replace ys with l1 by (apply IHl1; assumption); reflexivity.\n  Qed.\n\nEnd ListRelEq.\n\n\nSection FunctionComposition.\n\n  Variable A B C : Type.\n\n  Definition comp (R1 : A -> B -> Prop) (R2 : B -> C -> Prop) : A -> C -> Prop :=\n    fun a c => forall b, R1 a b -> R2 b c.\n\n  Theorem comp_function :\n    forall R1 R2,\n      function R1 -> function R2 -> function (comp R1 R2).\n  Proof.\n    unfold function, comp.\n    intros R1 R2 HR1 HR2 a.\n    specialize (HR1 a).\n    inversion HR1 as [b (Hb,Hb1)]; clear HR1.\n    specialize (HR2 b).\n    inversion HR2 as [c (Hc,Hc1)]; clear HR2.\n    exists c.\n    split.\n    intros b' Hb'.\n    replace b'  with b by (apply Hb1; assumption).\n    assumption.\n    intros c' Hc'.\n    apply Hc1.\n    apply Hc'.\n    assumption.\n  Qed.\n\n  Theorem comp_correct :\n    forall (f : B -> C) (g : A -> B) x y,\n      f (g x) = y <-> comp (fun a b => g a = b) (fun b c => f b = c) x y.\n  Proof.\n    unfold comp.\n    intros f g x y.\n    split; intros H.\n    intros b Hg; subst; reflexivity.\n    apply H.\n    reflexivity.\n  Qed.\n\nEnd FunctionComposition.\n\n\nSection Relations.\n\n  Section Converse.\n    Variable A B : Type.\n    Variable R : A -> B -> Prop.\n\n    Definition transp (b : B) (a : A) : Prop := R a b.\n  End Converse.\n\nEnd Relations.\n", "meta": {"author": "sampollard", "repo": "q-supplement", "sha": "2b5290074d3055509b77508e5a8e411f23f68640", "save_path": "github-repos/coq/sampollard-q-supplement", "path": "github-repos/coq/sampollard-q-supplement/q-supplement-2b5290074d3055509b77508e5a8e411f23f68640/semantics/coq/src/Util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.6603607780938253}}
{"text": "Require Import Setoid Morphisms.\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLemma iter_id (T : Type) n : @iter T n id =1 id.\nProof. by elim: n. Qed.\n\nLemma iterK n (T : Type) (f g : T -> T) : \n  cancel f g -> cancel (iter n f) (iter n g).\nProof.\nby move => can_fg; elim: n => // n IHn x; rewrite iterS iterSr IHn can_fg.\nQed.\n\nLemma leq_subl n m o : n <= m -> n - o <= m.\nProof. move => A. rewrite -[m]subn0. exact: leq_sub. Qed.\n\n(** *** Lemmas on [index] and [subseq] *)\n(** could go to seq.v *)\n\nLemma mem2_index (T : eqType) (x y : T) (s : seq T) : \n  uniq s -> y \\in s -> mem2 s x y = (index x s <= index y s).\nProof.\nhave [|xNs _ y_s] := boolP (x \\in s); last first.\n  by rewrite mem2lf // (memNindex xNs) leqNgt index_mem y_s.\nelim: s => //= z s IHs x_s /andP[zNs uniq_s] y_s; rewrite mem2_cons.\nrewrite y_s; have [-> //|zDx] := eqVneq z x.\nhave [<-|zDy] := eqVneq z y;first by rewrite mem2rf. \nrewrite !inE ?[_ == z]eq_sym ?(negbTE zDy) ?(negbTE zDx) /= in x_s y_s.\nexact: IHs.\nQed.\n\nLemma index_subseq (T : eqType) x y (s1 s2 : seq T) :\n  y \\in s1 -> subseq s1 s2 -> uniq s2 -> \n  index x s1 <= index y s1 -> index x s2 <= index y s2.\nProof.\nmove=> y_s1 sub_s1_s2 uniq_s2; have uniq_s1 := subseq_uniq sub_s1_s2 uniq_s2.\nrewrite -!mem2_index ?mem2E // => [?|]; last exact: (mem_subseq sub_s1_s2).\nexact: subseq_trans sub_s1_s2.\nQed.\n\nSection Path.\n\nLemma eq_traject (T : Type) (f g : T -> T) : f =1 g -> traject f =2 traject g.\nProof. move=> fg x n; elim: n x => //= n IHn x. by rewrite IHn fg. Qed.\n\nVariable (T : eqType). \nImplicit Types (s p : seq T) (x y : T).\n\nLemma head_rot s x0 n : n < size s -> head x0 (rot n s) = nth x0 s n.\nProof.\nmove=> n_lt_s; rewrite /rot -nth0 nth_cat size_drop subn_gt0 n_lt_s.\nby rewrite -{2}[s](cat_take_drop n) nth_cat size_take n_lt_s ltnn subnn.\nQed.\n\nLemma next_cons x0 x s : next (x::s) x = head x0 (rcons s x).\nProof. by case: s => [|y s] /=; rewrite eqxx. Qed.\n\nLemma next_neq x p : x \\in p -> uniq p -> 1 < size p -> x != next p x.\nProof. \nmove => x_p; have [i p' rot_p uniq_p] := rot_to x_p.\nmove: (uniq_p); rewrite -(next_rot i) // -(size_rot i) -(rot_uniq i) {}rot_p.\ncase: p' => //= y p'. rewrite inE eqxx. by case: (x == y).\nQed.\n\nLemma prev_neq x p : x \\in p -> uniq p -> 1 < size p -> x != prev p x.\nProof.\nmove => x_p uniq_p lt1p. have := @next_neq (prev p x) _ _ uniq_p lt1p.\nby rewrite mem_prev next_prev // eq_sym; apply.\nQed.\n\nLemma iter_next_rot x0 s n :\n  n < size s -> uniq s -> iter n (next s) (head x0 s) = head x0 (rot n s).\nProof.\nelim: n s => [|n IHn] s; first by move => *; rewrite rot0.\ncase: s => [_ /= |x s]; first by rewrite (@eq_iter _ _ id) ?iter_id.\nmove => n_lt_s uniq_s. rewrite iterSr rotS 1?ltnW // rot_rot rot1_cons.\nrewrite (next_cons x0).\nunder eq_iter => z do rewrite -(next_rot 1) ?rot1_cons //.\nby rewrite IHn // ?size_rcons ?rcons_uniq // ltnW.\nQed.\n\nLemma iter_next_nth x0 s n : \n  uniq s -> n < size s -> iter n (next s) (head x0 s) = nth x0 s n.\nProof. by move => *; rewrite iter_next_rot // head_rot. Qed.\n\nLemma traject_next x0 s : \n  uniq s -> traject (next s) (head x0 s) (size s) = s.\nProof. \nmove=> uniq_s; apply: (@eq_from_nth _ x0); rewrite size_traject // => i i_lt_s.\nrewrite (set_nth_default (head x0 s)) ?size_traject //.\nby rewrite nth_traject // iter_next_nth.\nQed.\n\nLemma mem_arc (p : seq T) (x y : T) : {subset arc p x y <= p}.\nProof. by move => z /mem_take; rewrite mem_rot. Qed.\n\nEnd Path.\n\nLemma map_arc (aT rT : eqType) (f : aT -> rT) (s : seq aT) (x y : aT) : \n  injective f -> [seq f z | z <- arc s x y] = arc (map f s) (f x) (f y).\nProof. \nby move=> inj_f; rewrite /arc -map_rot !index_map // map_take.\nQed.\n\nLemma next_map (aT rT : eqType) (f : aT -> rT) (s : seq aT) (x : aT) : \n  injective f -> next (map f s) (f x) = f (next s x).\nProof.\nmove=> inj_f; case: s => //= a s.\nby elim: s a {2 4}a => /= [|y s IHs] a b; rewrite inj_eq // ?IHs -fun_if.\nQed.\n\n(** *** Lemmas on [index] *)\n(** could go to [fingraph.v] *)\n\nLemma eq_findex (T : finType) (f g : T -> T) : \n  f =1 g -> findex f =2 findex g.\nProof. \nmove=> fg x y; rewrite /findex /index /orbit /order (eq_traject fg). \ncongr (_ _ (traject _ _ _)); exact/eq_card/eq_fconnect.\nQed.\n\nLemma findex_head (T : finType) (x y : T) (s : seq T) (uniq_xs : uniq (x::s)) :\n  findex (next (x :: s)) x y = index y (x :: s).\nProof.\nrewrite /findex (_ : orbit (next (x::s)) x = x::s) // /orbit.\nrewrite (@order_cycle _ _ (x::s)) ?mem_head ?cycle_next //.\nexact: (@traject_next _ x).\nQed.\n\n\nFrom GraphTheory Require Import preliminaries.\nLocal Notation splitPr := path.splitPr.\n\n(* Only the lemmas below are actually used: \n(* already on mathcomp master *)\nAxiom card_gt1P : \n   forall {T : finType} {A : pred T}, reflect (exists x y : T, [/\\ x \\in A, y \\in A & x != y]) (1 < #|A|).\nAxiom disjointFr :  \n  forall (T : finType) (A B : pred T), reflect (forall x : T, x \\in A -> x \\in B -> False) [disjoint A & B].\n*)\n\nLemma head_arc (T: eqType) (s : seq T) (x y : T) (xDy : x != y) : \n  uniq s -> x \\in s -> y \\in s -> x \\in arc s x y.\nProof.\nmove=>  uniq_s x_s y_s. case: (rot_to_arc uniq_s x_s y_s xDy) => i s1 s2 <- _ _. \nexact: mem_head.\nQed.\n\nLemma next_mem_arc (T : eqType) (s : seq T) (x y : T) : \n  uniq s -> x \\in s -> y \\in s -> x != y -> next s x \\in rcons (arc s x y) y.\nProof.\nmove=> uniq_s x_s y_s xDy.\nhave [i s1 s2 arc1 arc2 rot_r] := rot_to_arc uniq_s x_s y_s xDy.\nrewrite -arc1 -(next_rot i) // rot_r (next_cons x).\nby case: s1 {arc1 rot_r} => [|z s1']; rewrite /= !inE eqxx orbT.\nQed.\n\n(* Not used *)\nLemma arc_next (T : eqType) (s : seq T) (x : T) : \n  1 < size s -> uniq s -> x \\in s -> arc s x (next s x) = [:: x].\nProof. \nmove=> le2s uniq_s x_s. \nhave xDnx : x != next s x by apply: next_neq.\nhave nx_s : next s x \\in s by rewrite mem_next.\nhave [i s1 s2 A1 A2 rot_i] := rot_to_arc uniq_s x_s nx_s xDnx.\nsuff s1nil : s1 = [::] by rewrite -A1 s1nil.\nmove: (uniq_s); rewrite -(rot_uniq i) rot_i -(next_rot i) // rot_i (next_cons x).\nby case: s1 {A1 A2 rot_i} => //= y s1'; rewrite !(inE,mem_cat) eqxx orbT andbF.\nQed.\n\n\nDefinition path0 (T : Type) (e : rel T) (s : seq T) :=\n  if s is x::s then path e x s else true.\n\nLemma path_path0 (T : Type) (e : rel T) x (s : seq T) : \n  path e x s -> path0 e s.\nProof. by case: s => //= y s /andP [_]. Qed.\n\n\nSection UcycleArc.\nVariables (T : finType) (e : rel T) (s : seq T).\n\nLemma arc_path x y (xDy : x != y) :\n  ucycle e s -> x \\in s -> y \\in s -> path0 e (arc s x y).\nProof.\nmove=> /andP[cycle_s uniq_s] x_s y_s. \nhave [i s1 s2 <- _ E /=] := rot_to_arc uniq_s x_s y_s xDy.\nmove: cycle_s. rewrite -(rot_cycle i) E /= rcons_path cat_path.\nby case: (path e x s1).\nQed.\n\nLemma arc_edge x y : \n  ucycle e s -> x \\in s -> y \\in s -> x != y -> e (last x (arc s x y)) y.\nProof.\nmove => /andP [cycle_s uniq_s] x_s y_s xDy.\nhave [n s1 s2 <- _ rot_s] := rot_to_arc uniq_s x_s y_s xDy.\nmove: cycle_s; rewrite -(rot_cycle n) {}rot_s /=.\nby rewrite rcons_path cat_path /=; case: (e (last _ _) _); rewrite // andbF.\nQed.\n\nLemma arc_findex x y z (xDy : x != y) : \n  uniq s -> x \\in s -> y \\in s -> \n  (z \\in arc s x y) = (findex (next s) x z < findex (next s) x y).\nProof.\nmove=> uniq_s x_s y_s; have [i s1 s2 A1 A2 R] := rot_to_arc uniq_s x_s y_s xDy.\nunder eq_findex => u do rewrite -(next_rot i) //.\nunder (@eq_findex _ (next s)) => u do rewrite -(next_rot i) //.\nhave uniq_xy : uniq (x :: s1 ++ y :: s2) by rewrite -R rot_uniq.\nrewrite R !findex_head // -cat_cons !index_cat index_head.\nrewrite -A1 [X in _ < X]ifN. \n  by case: ifP => [Hz|_]; rewrite ?ltn_add2l // addn0 index_mem Hz.\nby apply: contraTN uniq_xy => C; rewrite -cat_cons cat_uniq /= C /= andbF.\nQed.\n\nLemma arc_disjoint2 x y : \n  uniq s -> x \\in s -> y \\in s -> x != y -> [disjoint arc s x y & arc s y x].\nProof.\nmove => uniq_s x_s y_s xDy.\nhave [n s1 s2 <- <- rot_s] := rot_to_arc uniq_s x_s y_s xDy.\nmove: uniq_s; rewrite -(rot_uniq n) rot_s -cat_cons cat_uniq. \nby rewrite disjoint_sym disjoint_has => /and3P [_ -> _].\nQed.\n\nLemma arc_disjoint x1 x2 y1 y2 : \n  uniq s -> x1 \\in s -> x2 \\in s -> y1 \\in s -> y2 \\in s -> x1 != x2 -> y1 != y2 ->\n  findex (next s) x1 x2 <= findex (next s) x1 y1 ->\n  findex (next s) y1 y2 <= findex (next s) y1 x1 ->\n  [disjoint arc s x1 x2 & arc s y1 y2].\nProof.\nmove=> uniq_s x1_s x2_s y1_s y2_s x1Dx2 y1Dy2 index_x index_y.\nhave x1Dy1 : x1 != y1. \n{ apply: contraNneq x1Dx2 => ?; subst y1. \n  by move: index_x; rewrite findex0 leqn0 findex_eq0. }\napply/pred0Pn => -[x] /=; rewrite !arc_findex // => /andP [A1 A2].\nhave {A1 index_x} := leq_trans A1 index_x.\nhave {A2 index_y} := leq_trans A2 index_y.\nrewrite -!arc_findex //= 1?eq_sym // => x_arc.\nby apply/negP; rewrite (disjointFl (@arc_disjoint2 x1 y1  _ _ _ _)).\nQed.\n\nVariable p : seq T.\nHypothesis uniq_s : uniq s.\nHypothesis p_sub_s : subseq p s.\nLet p_in_s := mem_subseq p_sub_s.\nLet uniq_p := subseq_uniq p_sub_s uniq_s.\n\nLemma findex_next_other (x y : T) :\n  x \\in p -> y \\in p -> x != y -> findex (next s) x (next p x) <= findex (next s) x y.\nProof.\nmove=> x_p y_p xDy; have x_s : x \\in s by apply: p_in_s.\nhave [n s' rot_n] := rot_to x_s.\nunder eq_findex => z do rewrite -(next_rot n) //.\nunder [X in _ <= X]eq_findex => z do rewrite -(next_rot n) //.\nhave uniq_xs : uniq (x :: s') by rewrite -rot_n rot_uniq.\nhave [m _ sub] := subseq_rot n p_sub_s.\nrewrite rot_n !findex_head // -(next_rot m) //; rewrite rot_n in sub. \nhave [p' P] : exists p', rot m p = x :: p'. \n{ rewrite -(mem_rot m) in x_p; rewrite -(rot_uniq m) in (uniq_p).\n  case: (splitPr x_p) sub => p1 p2. rewrite -[x::s']cat0s.\n  rewrite uniq_subseq_pivot // => /andP.\n  by rewrite subseq0 => -[/eqP -> _]; exists p2. }\nrewrite P next_nth mem_head index_head.\ncase: p' P => [|y' p' P]; first by rewrite /= eqxx leq0n.\nrewrite [nth _ _ _]/= P in sub *; apply: index_subseq sub _ _ => //.\n  by rewrite -P mem_rot.\nby rewrite /= eqxx (negbTE xDy); case: (x == y').\nQed.\n\nLemma arc_next_disjoint x y : \n  x \\in p -> y \\in p -> x != y ->\n  [disjoint arc s x (next p x) & arc s y (next p y)].\nProof.\nmove=> x_p y_p xDy. \nhave x_s : x \\in s by apply p_in_s.\nhave ? : 1 < size p.\n{ apply: leq_trans (card_size _). by apply/card_gt1P; exists x,y. }\napply: arc_disjoint; try apply: p_in_s; rewrite ?mem_next //.\n1-2: exact: next_neq.\nall: by apply: findex_next_other; rewrite // eq_sym.\nQed.\n\nLemma arc_cover x y : x \\in s -> y \\in s -> x != y -> s =i [predU arc s x y & arc s y x].\nProof.\nmove=> x_s y_s xDy z; have [i s1 s2 A1 A2 def_s] := rot_to_arc uniq_s x_s y_s xDy.\nby rewrite -(mem_rot i) def_s -cat_cons A1 A2 mem_cat.\nQed.\n\nLemma mem_arc_other x y z : x \\in s -> y \\in s -> z \\in s -> x != y -> \n  (z \\in arc s x y) = (z \\notin arc s y x).\nProof.\nmove=> x_s y_s z_s xDy; have/esym := arc_cover x_s y_s xDy z; rewrite z_s inE /=.\nhave D := arc_disjoint2 uniq_s x_s y_s xDy.\nby case/orP => z_arc; rewrite z_arc ?(disjointFr D) // ?(disjointFl D).\nQed.\n\nLemma arc_remainder x : 1 < size p -> x \\in p -> {subset p <= rcons (arc s (next p x) x) x}.\nProof.\nmove=> gt1p x_p y y_p; rewrite mem_rcons inE; have [//|xDy/=] := eqVneq x y.\nrewrite mem_arc_other ?p_in_s ?mem_next // 1?eq_sym ?next_neq //.\nhave D := arc_next_disjoint x_p y_p xDy. \nby rewrite (disjointFl D) // head_arc ?p_in_s ?next_neq ?mem_next.\nQed.\n\nEnd UcycleArc.\n\nSection SubCycle.\nVariables (T : eqType).\nImplicit Types (p s : seq T).\n\nDefinition subcycle p s := [exists n : 'I_(size p).+1, subseq (rot n p) s].\n\nLemma subcycleP p s : reflect (exists n, subseq (rot n p) s) (subcycle p s).\nProof.\napply: (iffP existsP) => [[n On]|[n rot_n]]; first by exists n.\nhave [lt_p|ge_p] := ltnP n (size p).+1; first by exists (Ordinal lt_p).\nby exists (Ordinal (ltn0Sn _)); rewrite /= rot0 -[p](@rot_oversize _ n) // ltnW.\nQed.\n\nLemma subcycle_rot_l n p s : subcycle (rot n p) s = subcycle p s.\nProof. \napply/subcycleP/subcycleP => [[m]|[m sub]].\n  rewrite rot_rot_add => sub; eexists; exact: sub.\nexists (rot_add (rot n p) ((size (rot n p)) - n) m). \nby rewrite -rot_rot_add -/(rotr _ _) rotK.\nQed.\n\nLemma subcycle_rot_r n p s : subcycle p (rot n s) = subcycle p s.\nProof.\napply/subcycleP/subcycleP => -[m sub].\n  have [k _ sub'] := subseq_rot (size (rot n s) - n) sub.\n  rewrite -/(rotr _ _) rotK rot_rot_add in sub'; eexists; exact sub'.\nhave [k _ sub'] := subseq_rot n sub. \nby exists (rot_add p m k); rewrite -rot_rot_add.\nQed.\n\nLemma subcycle_rot n m s p : subcycle (rot n p) (rot m s) = subcycle p s.\nProof. by rewrite subcycle_rot_l subcycle_rot_r. Qed.\n\nLemma subseq_subcyle p s : subseq p s -> subcycle p s.\nProof. by move => sub; apply/subcycleP; exists 0; rewrite rot0. Qed.\n\nLemma subcycle_trans : transitive subcycle.\nProof.\nmove=> r p q sub_p_r /subcycleP [m sub_r_q].\nmove: sub_p_r; rewrite -(subcycle_rot_r m) => /subcycleP [n] sub_p_r.\nby apply/subcycleP; exists n; apply: subseq_trans sub_r_q.\nQed.\n\nLemma subcycle_uniq p s : subcycle p s -> uniq s -> uniq p.\nProof. \nmove=> /subcycleP [n sub_p_s]; rewrite -(rot_uniq n p).\nexact: subseq_uniq.\nQed.\n\nLemma mem_subcycle p s : subcycle p s -> {subset p <= s}.\nProof. \nmove=> /subcycleP[n /mem_subseq sub_p_s] z z_p.\nby apply: sub_p_s; rewrite mem_rot.\nQed.\n\nLemma subcycle_get_arc x p s :\n  x \\in s -> uniq s -> subcycle p s -> 1 < size p ->\n  exists2 z, z \\in p & x \\in arc s z (next p z).\nProof.\nwlog [s' -> _ {s}] : s / exists s', s = x::s'.\n{ move=> W x_s uniq_s sub_p_s size_p; have [i s' rot_i] := rot_to x_s. \n  case: (W (rot i s)); rewrite ?mem_rot ?rot_uniq ?subcycle_rot_r //; first by exists s'.\n  move=> z z_p; rewrite arc_rot ?(mem_subcycle sub_p_s) //; by exists z. }\nmove=> uniq_s sub_p_s size_p. \nhave uniq_p : uniq p by apply: subcycle_uniq uniq_s.\nhave [x_p|xNp] := boolP (x \\in p).\n- exists x; rewrite ?head_arc ?mem_head //; first exact: next_neq. \n  apply: mem_subcycle sub_p_s _ _. by rewrite mem_next.\n- have has_p : has (mem p) s'. \n  {  case: p => [//|z p] in size_p sub_p_s uniq_p xNp *.\n     apply/hasP; exists z; rewrite /= ?mem_head //. \n     move:(mem_subcycle sub_p_s) => /(_ z (mem_head _ _)) /predU1P [zx|//].\n     by rewrite zx inE eqxx in xNp. }\n  case def_s : _ _ _ _ / (split_find_nth x has_p) => [/= nz s1 s2 nz_p Ns2].\n  pose z := path.prev p nz. \n  have z_s2 : z \\in s2. \n  { have z_p : z \\in p by rewrite path.mem_prev. \n    move:(mem_subcycle sub_p_s z_p); rewrite inE => /predU1P[zx|].\n      by subst; contrab.\n    rewrite def_s. rewrite mem_cat mem_rcons inE eq_sym (negbTE (prev_neq _ _ _)) //=.\n    by case/orP => [z_s1|//]; apply: contraNT Ns2 => _; apply/hasP; exists z. }\n  exists z; rewrite ?path.mem_prev // next_prev // -cats1 -catA /=.\n  case def_s2 : _ / (path.splitPr z_s2) => [p1 p2]. \n  have U1 : uniq (x :: s1 ++ nz :: p1 ++ z :: p2).\n  { by rewrite -def_s2 -[nz :: _]cat1s catA cats1 -def_s. }\n  move: (U1). rewrite -cat_cons -(rot_uniq (size (x :: s1))) rot_size_cat => U2.\n  rewrite -cat_cons -(arc_rot (size (x :: s1))) // ?rot_size_cat ?(inE,mem_cat,eqxx,orbT)//.\n  have E : ((nz :: p1) ++ z :: p2) ++ x :: s1 = nz :: p1 ++ z :: (p2 ++ x :: s1).\n  { by rewrite /= -!cat_cons -!catA. }\n  by rewrite E right_arc -?E// !(inE,mem_cat) eqxx /= !orbT.\nQed.\n\n\n\nEnd SubCycle.\n\n\nLemma arc_iterP (T : eqType) (x y z : T) (s : seq T) (xDy : x != y) : \n  uniq s -> x \\in s -> y \\in s -> \n  reflect (exists2 n, iter n (next s) x = z \n                    & forall m, m <= n -> iter m (next s) x != y) \n          (z \\in arc s x y).\nProof.\nmove=> uniq_s x_s y_s. \nhave [i s1 s2 arc1 arc2 rot_i] := rot_to_arc uniq_s x_s y_s xDy.\nhave I k (lt_k_s : k < size (rot i s)) : iter k (next s) x = nth x (rot i s) k.\n{ have -> : x = head z (rot i s) by rewrite rot_i.\n  under eq_iter => u do rewrite -(next_rot i) //.\n  by rewrite iter_next_nth // ?rot_uniq // (set_nth_default z). }\nhave yNarc1 : y \\notin arc s x y. \n{ apply: contraTN uniq_s; rewrite -(rot_uniq i) rot_i -cat_cons arc1 cat_uniq.\n  move=> y_arc1; rewrite [has _ _](_ : _ = true) ?andbF //.\n  by apply/hasP; exists y => //=; apply: mem_head. }\napply: (iffP idP) => [z_arc1|[n iter_n min_n]].\n- have z_s := mem_arc z_arc1; exists (index z (rot i s)) => [|m lt_m_z].\n    rewrite I ?nth_index // ?mem_rot // index_mem. \n    by rewrite rot_i -cat_cons arc1 mem_cat z_arc1.\n   have lt_m_a1 : m < size (arc s x y). \n   { apply: leq_ltn_trans lt_m_z _.\n     by rewrite rot_i -cat_cons arc1 index_cat z_arc1 index_mem. }\n   have m_lt_s : m < size (rot i s). \n     by apply: leq_trans lt_m_a1 _; rewrite rot_i -cat_cons arc1 size_cat leq_addr.\n   apply: contraNneq yNarc1; rewrite I // => {1}<-.\n   by rewrite rot_i -cat_cons arc1 nth_cat lt_m_a1 mem_nth.\n- pose k := index y (rot i s); have lt_k_s : k < size (rot i s).\n    by rewrite index_mem rot_i !(inE,mem_cat) eqxx !orbT.\n  have lt_n_k : n < k. \n    rewrite ltnNge; apply/negP=> /min_n.\n    by rewrite I // nth_index ?eqxx // rot_i !(inE,mem_cat) eqxx !orbT.\n  rewrite -iter_n I ?(ltn_trans lt_n_k lt_k_s) // rot_i -cat_cons arc1 nth_cat.\n  suff eq_k : k = size (arc s x y) by   rewrite -eq_k lt_n_k mem_nth // -eq_k.\n  by rewrite /k rot_i -cat_cons arc1 index_cat (negbTE yNarc1) /= ?eqxx ?addn0.\nQed.\n\nLemma next_iter (T : eqType) (x y : T) (s : seq T) :\n  uniq s -> x \\in s -> y \\in s -> exists n, iter n (next s) x == y.\nProof. \nmove=> uniq_s x_s y_s; have [i s' rot_i] := rot_to x_s.\nexists (index y (rot i s)); under eq_iter => z do rewrite -(next_rot i) //.\nhave -> : x = head y (rot i s) by rewrite rot_i. \nby rewrite iter_next_nth ?nth_index ?index_mem ?mem_rot ?rot_uniq.\nQed.\n\nLemma prev_iter (T : eqType) (x y : T) (s : seq T) :\n  uniq s -> x \\in s -> y \\in s -> exists n, iter n (prev s) x == y.\nProof.\nmove=> uniq_s x_s y_s; have [n /eqP eq_x] := next_iter uniq_s y_s x_s.\nby exists n; rewrite -eq_x iterK //; apply: prev_next.\nQed.\n\nLemma subcycle_get_arc' (T : eqType) x (p s : seq T) : \n  x \\in s -> uniq s -> subcycle p s -> 1 < size p ->\n  exists2 z, z \\in p & x \\in arc s z (next p z).\nProof.\nmove=> x_s uniq_s sub_p_s le2p. \nhave mem_s := mem_subcycle sub_p_s.\nhave uniq_p : uniq p by apply: subcycle_uniq uniq_s.\nhave /ex_minnP [n iter_n min_n] : exists n, iter n (prev s) x \\in p.\n  move/leqW : le2p; rewrite ltnS -has_predT => /hasP [z z_p _].\n  have [n /eqP it_n] := next_iter uniq_s (mem_s _ z_p) x_s.\n  by exists n; rewrite -it_n iterK //; exact: prev_next.\nset z := iter n _ _ in iter_n *; exists z => //. \nhave [z_s nz_s] : z \\in s /\\ next p z \\in s by rewrite ?mem_s // ?mem_next.\napply/arc_iterP; rewrite ?next_neq //.\nhave /ex_minnP [m /eqP iter_m min_m] := next_iter uniq_s z_s nz_s.\nexists n => [|n'] ; first exact/iterK/next_prev.\napply: contraTN => /min_m => le_m_n'. rewrite -ltnNge.\napply: leq_trans le_m_n' => {n'}. apply: wlog_neg; rewrite -ltnNge => gt_m_n.\nhave gt0m : 0 < m. \n{ by rewrite lt0n; apply: contra_eq_neq iter_m => -> /=; apply: next_neq. }\nhave gt0n : 0 < n by apply: leq_trans gt0m _.\nhave/min_n : iter (n - m) (prev s) x \\in p. \n{ have En : n = m + (n - m) by rewrite subnKC.\n  move: iter_n. rewrite -mem_next -iter_m /z {1}En iterD iterK //.\n  exact: next_prev. }\nby rewrite leqNgt ltn_subrL gt0m gt0n.\nQed.\n\nLemma arc_subcycle_disjoint (T : finType) (p s : seq T) (x y : T) : \n  uniq s -> subcycle p s -> x \\in p -> y \\in p -> x != y -> \n  [disjoint arc s x (next p x) & arc s y (next p y)].\nProof.\nmove=> uniq_s /subcycleP [m sub_p_s].\nwlog: p {sub_p_s} / subseq p s => [W|?]; last exact: arc_next_disjoint.\nmove: (W _ sub_p_s); rewrite !mem_rot !next_rot // -(rot_uniq m).\nall: exact: subseq_uniq uniq_s.\nQed.\n\nLemma arc_subcycle_disjoints (T : finType) (p s : seq T) (x y nx ny : T) : \n  uniq s -> subcycle p s -> x \\in p -> y \\in p -> x != y -> nx = next p x -> ny = next p y ->\n  [disjoint [set z in arc s x nx] & [set z in arc s y ny]].\nProof.\nmove=> uniq_s subcycle_p x_p y_p xDy next_x next_y.\nunder eq_disjoint => z do by rewrite !inE.\nunder eq_disjoint_r => z do by rewrite !inE.\nby rewrite next_x next_y; apply: (arc_subcycle_disjoint uniq_s).\nQed.\n", "meta": {"author": "coq-community", "repo": "graph-theory", "sha": "18bdabc919f6b20946f40cd5d4fbb5143c46a2bf", "save_path": "github-repos/coq/coq-community-graph-theory", "path": "github-repos/coq/coq-community-graph-theory/graph-theory-18bdabc919f6b20946f40cd5d4fbb5143c46a2bf/theories/core/arc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.6603607695325174}}
{"text": "From LF Require Export Basics.\nFrom LF Require Export Logic.\nRequire Import PeanoNat.\n\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\nNotation \"~ x\" := (not x) : type_scope.\n\nLemma lma (P:Prop) : ~(P /\\ ~P).\nProof.\n  unfold not.\n  intros H.\n  destruct H as [p].\n  apply H.\n  apply p.\nQed.\n\nLemma lma' (P Q:Prop) : ~(P \\/ Q) -> ~P /\\ ~Q.\nProof.\n  unfold not.\n  intros H.\n  constructor.\n  - intro p.\n    apply H.\n    left.\n    apply p.\n  - intro q.\n    apply H.\n    right.\n    apply q.\nQed.\n\n(*1 - 1 балл*)\nTheorem excluded_middle_irrefutableKR: forall (P : Prop), ~~(P \\/ ~ P).\nProof.\nintros P H.\n  apply lma' in H.\n  apply lma in H.\n  apply H.\nQed.\n\n(*2 - 0.5 баллов*)\nTheorem all_imp_ist A (P Q: A -> Prop): \n  (forall x: A, P x -> Q x) -> (forall y, P y) -> forall z, Q z. \nProof.\nAdmitted.\n\n(*3 - 1 балл*)\nTheorem or_distributes_over_and_2 P Q R :\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n    intros. inversion H as [[HP|HQ] [HP2|HR]].\n    apply or_introl. apply HP.\n    apply or_introl. apply HP.\n    apply or_introl. apply HP2.\n    apply or_intror. split. apply HQ. apply HR.\nQed.\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(*4 - 0.5 баллов*)\n(*В примерах (Example) заменить \"A\" на функцию, которая позволит из данного (короткого)\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.\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_map':\n  flat_map (fun n => [n;n;n;n]) [1;5;4]\n  = [1; 1; 1; 1; 5; 5; 5; 5; 4; 4; 4; 4].\nProof. reflexivity. Qed.\n\nExample test_flat_map'':\n  flat_map (fun n => [n;n]) [8;10;15;2]\n  = [8; 8; 10; 10; 15; 15; 2; 2].\nProof. reflexivity. Qed.\n\nRequire Import Classical_Prop.\n\nDefinition peirce_law := forall P Q: Prop, ((P -> Q) -> P) -> P.\nDefinition classic := forall P:Prop,   ~~P  ->  P.\nDefinition peirce := peirce_law.\nDefinition double_neg := 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(*5 - 2 балла*)\n(*Используя приведенные выше определения доказать теорему*)\nTheorem classic_implies_demorgan : classic -> de_morgan_not_and_not.\nProof.\nunfold classic, de_morgan_not_and_not.\nintro Classic. intros P Q. unfold not.\nintro nan. apply Classic. unfold not.\nintro double_neg. apply nan. \nsplit.\n intro. apply double_neg. left. assumption.\n intro. apply double_neg. right. assumption.\nQed.\n\n(*6 - 2 балла*)\n(*Используя приведенные выше определения доказать теорему*)\nTheorem demorgan_implies_exclude : de_morgan_not_and_not -> excluded_middle.\nProof.\nunfold de_morgan_not_and_not, excluded_middle.\nintros Demogran P. apply Demogran. unfold not. intro.\ninversion H. contradiction.\nQed.\n\n\n\n\n\n\n", "meta": {"author": "MihaxXx", "repo": "PLTLabs", "sha": "7923d04d0a4fec4be6424ccba71890e8e1812de6", "save_path": "github-repos/coq/MihaxXx-PLTLabs", "path": "github-repos/coq/MihaxXx-PLTLabs/PLTLabs-7923d04d0a4fec4be6424ccba71890e8e1812de6/KR2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.660360766033149}}
{"text": "Require Export P06.\n\n\n\n(** **** Exercise: 3 stars, optional (add_slowly_decoration)  *)\n(** The following program adds the variable X into the variable Z\n    by repeatedly decrementing X and incrementing Z.\n  WHILE X <> 0 DO\n     Z ::= Z + 1;;\n     X ::= X - 1\n  END\n\n    Following the pattern of the [subtract_slowly] example above, pick\n    a precondition and postcondition that give an appropriate\n    specification of [add_slowly]; then (informally) decorate the\n    program accordingly. *)\n\nTheorem slow_addition_dec_correct : forall n m,\n  {{fun st => st X = n /\\ st Y = m }}\n  WHILE BNot (BEq (AId X) (ANum 0)) DO\n     Y ::= APlus (AId Y) (ANum 1);;\n     X ::= AMinus (AId X) (ANum 1)\n  END\n  {{fun st => st Y = n + m}}.\nProof. intros n m.\n  apply hoare_consequence_pre with (P':= (fun st => st X + st Y = n + m )).\n  Case \"{{P'}} while {{Q}}\".\n    eapply hoare_consequence_post.\n    SCase \"{{P'} while {{P'/\\~b}}\".\n      apply hoare_while.  (* now P'/\\b c1;;c2 P' *)\n      eapply hoare_seq.\n      SSCase \"{{P''}} c2 {{P'}}\". apply hoare_asgn.\n      SSCase \"{{P'/\\b}} c1 {{P''}}\".\n        eapply hoare_consequence_pre. apply hoare_asgn.\n        unfold assert_implies, assn_sub. intros.\n        unfold update; simpl. destruct H. simpl in H0.\n        apply negb_true_iff in H0. apply beq_nat_false_iff in H0.\n        omega.\n    SCase \"P'/\\~b ->> Q\".\n      unfold assert_implies. intros.\n      destruct H. simpl in H0. apply negb_false_iff in H0. apply beq_nat_true_iff in H0. omega.\n  Case \"P' ->> P\".\n    unfold assert_implies. intros. 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/P07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.660360765284695}}
{"text": "Require Import Omega.\nRequire Import List.\nRequire Import Permutation.\nRequire Import NPeano.\nImport ListNotations.\n\nDefinition injective {A B : Type} (L : list A) (f : A -> B) : Prop :=\n  forall x1 x2, In x1 L -> In x2 L -> f x1 = f x2 -> x1 = x2.\n\nDefinition pairwise_disjoint {A B : Type} (L : list A) (f : A -> list B) : Prop :=\n  forall x1 x2 y, In x1 L -> In x2 L -> In y (f x1) -> In y (f x2) -> x1 = x2.\n\nFixpoint nub'\n  {A : Type} (eq_dec : forall x y : A, {x = y} + {x <> y}) (L : list A) : list A :=\n    match L with\n    | [] => []\n    | x :: M => (if in_dec eq_dec x M then [] else [x]) ++ nub' eq_dec M\n    end.\n\nDefinition select {A : Type} (L : list bool) (M : list A) : list A :=\n  map (@snd bool A) (filter (@fst bool A) (combine L M)).\n\nLemma empty_length :\n  forall (A : Type) (L : list A), L = [] <-> length L = 0.\nProof.\n  intros A [|x L].\n  - tauto.\n  - simpl.\n    split; intro H; contradict H; auto with *.\nQed.\n\nLemma nonempty_length :\n  forall (A : Type) (L : list A), L <> [] <-> length L > 0.\nProof.\n  intros A [|x L].\n  - simpl.\n    intuition.\n  - simpl.\n    auto with *.\nQed.\n\nLemma removelast_correct :\n  forall (A : Type) (x : A) (L : list A), removelast (L ++ [x]) = L.\nProof.\n  intros A x L.\n  rewrite removelast_app; simpl; auto with *.\nQed.\n\nLemma removelast_length :\n  forall (A : Type) (L : list A), length (removelast L) = length L - 1.\nProof.\n  intros A L.\n  induction L as [|x [|y L] IH]; trivial.\n  change (S (length (removelast (y :: L))) = S (length (y :: L)) - 1).\n  rewrite IH.\n  simpl.\n  omega.\nQed.\n\nLemma tail_length :\n  forall (A : Type) (L : list A), length (tail L) = length L - 1.\nProof.\n  intros A L.\n  induction L as [|x L IH]; trivial.\n  simpl.\n  omega.\nQed.\n\nLemma firstn_correct :\n  forall (A : Type) (L M : list A), firstn (length L) (L ++ M) = L.\nProof.\n  intros A L M.\n  induction L as [|x L IH]; trivial.\n  simpl.\n  rewrite IH.\n  trivial.\nQed.\n\nLemma firstn_map :\n  forall (A B : Type) (k : nat) (f : A -> B) (L : list A),\n    firstn k (map f L) = map f (firstn k L).\nProof.\n  intros A B k f.\n  induction k as [|k IH]; intros [|x L]; trivial.\n  simpl.\n  rewrite IH.\n  trivial.\nQed.\n\nLemma firstn_incl :\n  forall (A : Type) (k : nat) (L : list A),\n    forall (x : A), In x (firstn k L) -> In x L.\nProof.\n  intros A k.\n  induction k as [|k IH]; intros [|x L] y H; trivial.\n  - simpl in *.\n    tauto.\n  - simpl in *.\n    destruct H as [H|H]; [tauto|].\n    right.\n    apply IH.\n    trivial.\nQed.\n\nLemma skipn_correct :\n  forall (A : Type) (L M : list A), skipn (length L) (L ++ M) = M.\nProof.\n  intros A L M.\n  induction L as [|x L IH]; trivial.\nQed.\n\nLemma skipn_length :\n  forall (A : Type) (k : nat) (L : list A), length (skipn k L) = length L - k.\nProof.\n  intros A k L.\n  apply (plus_reg_l _ _ (min k (length L))).\n  rewrite <- firstn_length at 1.\n  rewrite <- app_length, firstn_skipn.\n  destruct (le_dec k (length L)) as [H|H]; [rewrite min_l|rewrite min_r]; omega.\nQed.\n\nLemma skipn_map :\n  forall (A B : Type) (k : nat) (f : A -> B) (L : list A),\n    skipn k (map f L) = map f (skipn k L).\nProof.\n  intros A B k f.\n  induction k as [|k IH]; intros [|x L]; simpl; trivial.\nQed.\n\nLemma skipn_incl :\n  forall (A : Type) (k : nat) (L : list A),\n    forall (x : A), In x (skipn k L) -> In x L.\nProof.\n  intros A k.\n  induction k as [|k IH]; intros [|x L] y H; auto with *.\nQed.\n\nLemma nth_skipn :\n  forall (A : Type) (n : nat) (L : list A) (d : A),\n    nth n L d = hd d (skipn n L).\nProof.\n  intros A n L d.\n  revert L.\n  induction n as [|n IH]; intros [|x L]; simpl; trivial.\nQed.\n\nLemma combine_nth2 :\n  forall (A B : Type) (L : list A) (M : list B) (n : nat) (x : A) (y : B),\n    n < length L -> n < length M -> nth n (combine L M) (x, y) = (nth n L x, nth n M y).\nProof.\n  intros A B L M n x y.\n  revert L M.\n  induction n as [|n IH]; intros L M HL LM;\n    (destruct L as [|v L]; [simpl in *; omega|]);\n    (destruct M as [|w M]; [simpl in *; omega|]);\n    trivial.\n  apply IH; auto with *.\nQed.\n\nLemma in_seq :\n  forall m n x, In x (seq m n) <-> m <= x < m + n.\nProof.\n  intros m n x.\n  revert m.\n  induction n as [|n IH]; intro m.\n  - simpl in *.\n    omega.\n  - simpl.\n    specialize (IH (S m)).\n    assert (m = x \\/ m <> x) by omega.\n    intuition.\nQed.\n\nLemma flat_map_length :\n  forall (A B : Type) (f : A -> list B) (L : list A) (n : nat),\n    (forall x, In x L -> length (f x) = n) ->\n      length (flat_map f L) = n * length L.\nProof.\n  intros A B f L n.\n  rewrite mult_comm.\n  induction L as [|x L IH]; trivial.\n  intro Hf.\n  simpl.\n  rewrite app_length.\n  rewrite Hf by auto with *.\n  rewrite IH by auto with *.\n  trivial.\nQed.\n\nLemma flat_map_app :\n  forall (A B : Type) (f : A -> list B) (L M : list A),\n    flat_map f (L ++ M) = flat_map f L ++ flat_map f M.\nProof.\n  intros A B f L M.\n  induction L as [|x L IH]; trivial.\n  simpl.\n  rewrite IH.\n  auto with *.\nQed.\n\nLemma filter_length :\n  forall (A : Type) (f : A -> bool) (L : list A),\n    length (filter f L) <= length L.\nProof.\n  intros A f L.\n  induction L as [|x L IH]; trivial.\n  simpl.\n  destruct (f x); simpl.\n  - omega.\n  - auto.\nQed.\n\nLemma NoDup_singleton :\n  forall (A : Type) (x : A), NoDup [x].\nProof.\n  intros A x.\n  apply NoDup_cons; [tauto|].\n  apply NoDup_nil.\nQed.\n\nLemma NoDup_app :\n  forall (A : Type) (L M : list A),\n    NoDup L -> NoDup M -> (forall x, ~ (In x L /\\ In x M)) -> NoDup (L ++ M).\nProof.\n  intros A L M HL HM.\n  induction HL as [|x L Hx HL IH]; trivial.\n  intro HD.\n  simpl.\n  apply NoDup_cons.\n  - rewrite in_app_iff.\n    specialize (HD x).\n    intuition.\n  - apply IH.\n    intro y.\n    specialize (HD y).\n    intuition.\nQed.\n\nLemma NoDup_map :\n  forall (A B : Type) (f : A -> B) (L : list A),\n    injective L f -> NoDup L -> NoDup (map f L).\nProof.\n  intros A B f L Hf HL.\n  induction HL as [|x L Hx HL IH]; [apply NoDup_nil|].\n  simpl.\n  apply NoDup_cons.\n  - rewrite in_map_iff.\n    intros [x2 [Ef Hx2]].\n    specialize (Hf x2 x).\n    rewrite <- Hf in Hx; auto with *.\n  - compute in *.\n    auto.\nQed.\n\nLemma NoDup_flat_map :\n  forall (A B : Type) (f : A -> list B) (L : list A),\n    (forall x, In x L -> NoDup (f x)) ->\n    pairwise_disjoint L f ->\n    NoDup L ->\n      NoDup (flat_map f L).\nProof.\n  intros A B f L Hf1 Hf2 HL.\n  induction HL as [|x L Hx HL IH]; [apply NoDup_nil|].\n  simpl.\n  apply NoDup_app.\n  - apply Hf1.\n    auto with *.\n  - apply IH.\n    + auto with *.\n    + intros x1 x2 y.\n      specialize (Hf2 x1 x2 y).\n      auto with *.\n  - intros y [H1 H2].\n    rewrite in_flat_map in H2.\n    destruct H2 as [x2 [H2 H3]].\n    specialize (Hf2 x x2 y).\n    rewrite Hf2 in Hx; auto with *.\nQed.\n\nLemma NoDup_seq :\n  forall m n, NoDup (seq m n).\nProof.\n  intros m n.\n  revert m.\n  induction n as [|n IH]; intro m.\n  - apply NoDup_nil.\n  - specialize (IH (S m)).\n    simpl.\n    apply NoDup_cons.\n    + rewrite in_seq.\n      omega.\n    + trivial.\nQed.\n\nLemma Permutation_NoDup :\n  forall (A : Type) (L M : list A), Permutation L M -> NoDup L -> NoDup M.\nProof.\n  intros A L M HP.\n  induction HP as [ |x L M HP IH| | ].\n  - trivial.\n  - intro H.\n    apply NoDup_cons.\n    + intro H2.\n      symmetry in HP.\n      apply (Permutation_in x) in HP; trivial.\n      contradict HP.\n      revert H.\n      apply (NoDup_remove_2 nil).\n    + apply IH.\n      revert H.\n      apply (NoDup_remove_1 nil).\n  - intro H.\n    pose (NoDup_remove_1 nil _ _ H) as H2.\n    pose (NoDup_remove_2 nil _ _ H) as H3.\n    pose (NoDup_remove_1 nil _ _ H2) as H4.\n    pose (NoDup_remove_2 nil _ _ H2) as H5.\n    repeat apply NoDup_cons; firstorder.\n  - tauto.\nQed.\n\nLemma NoDup_incl_Permutation :\n  forall (A : Type) (L M : list A),\n    NoDup L -> incl L M -> length L = length M -> Permutation L M.\nProof.\n  intros A L M HN.\n  revert M.\n  induction L as [|x L IH]; intros M HI HL.\n  - symmetry in HL.\n    apply empty_length in HL.\n    subst M.\n    trivial.\n  - assert (In x M) as H by auto with *.\n    destruct (in_split x M H) as [M1 [M2 E]].\n    subst M.\n    rewrite <- Permutation_middle.\n    apply perm_skip.\n    apply IH.\n    + inversion HN.\n      trivial.\n    + intros y K.\n      assert (In y (x :: L)) as K2 by auto with *.\n      specialize (HI y K2).\n      rewrite in_app_iff in *.\n      simpl in HI.\n      destruct HI as [H1|[H2|H3]]; try tauto.\n      subst y.\n      inversion HN.\n      tauto.\n    + revert HL.\n      repeat rewrite app_length.\n      simpl.\n      auto with *.\nQed.\n\nLemma Permutation_incl_left :\n  forall (A : Type) (L M N : list A),\n    Permutation L M -> (incl L N <-> incl M N).\nProof.\n  intros A L M N HP.\n  split; intros H x Hx; apply H; revert Hx; apply Permutation_in; auto with *.\nQed.\n\nLemma Permutation_incl_right :\n  forall (A : Type) (L M N : list A),\n    Permutation L M -> (incl N L <-> incl N M).\nProof.\n  intros A L M N HP.\n  split; intros H x Hx; [|symmetry in HP]; apply (Permutation_in _ HP); auto.\nQed.\n\nLemma incl_drop :\n  forall (A : Type) (L M : list A) (x : A), incl L (x :: M) -> ~ In x L -> incl L M.\nProof.\n  intros A L M x H1 H2 y Hy.\n  specialize (H1 y Hy).\n  destruct H1 as [H1|H1].\n  - subst y.\n    tauto.\n  - trivial.\nQed.\n\nLemma incl_cons_iff :\n  forall (A : Type) (x : A) (L M : list A),\n    incl (x :: L) M <-> In x M /\\ incl L M.\nProof.\n  unfold incl.\n  simpl.\n  intuition.\n  subst.\n  trivial.\nQed.\n\nLemma NoDup_incl_lel :\n  forall (A : Type) (L M : list A), NoDup L -> incl L M -> length L <= length M.\nProof.\n  intros A L M HI.\n  revert M.\n  induction L as [|x L IH]; [auto with *|].\n  intros M HM.\n  rewrite incl_cons_iff in HM.\n  destruct HM as [Hx HL].\n  apply in_split in Hx.\n  destruct Hx as [P [Q HM]].\n  subst M.\n  rewrite app_length.\n  simpl.\n  rewrite <- plus_n_Sm, <- app_length.\n  apply le_n_S.\n  apply IH.\n  - inversion HI.\n    trivial.\n  - intros y Hy.\n    specialize (HL y Hy).\n    revert HL.\n    repeat rewrite in_app_iff.\n    intros [H|[H|H]]; try tauto.\n    subst y.\n    inversion HI.\n    tauto.\nQed.\n\nLemma seq_app :\n  forall k m n : nat, seq k m ++ seq (k + m) n = seq k (m + n).\nProof.\n  intros k m n.\n  revert k.\n  induction m as [|m IH]; intro k.\n  - replace (k + 0) with k; trivial.\n  - simpl.\n    replace (k + S m) with (S k + m) by omega.\n    rewrite IH.\n    trivial.\nQed.\n\nLemma in_nub' :\n  forall (A : Type) eq_dec (L : list A) (x : A), In x (nub' eq_dec L) <-> In x L.\nProof.\n  intros A eq_dec L x.\n  induction L as [|y L IH]; [tauto|].\n  simpl.\n  rewrite <- IH.\n  destruct (in_dec eq_dec y L) as [H|H].\n  - intuition.\n    subst.\n    tauto.\n  - auto with *.\nQed.\n\nLemma NoDup_nub' :\n  forall (A : Type) eq_dec (L : list A), NoDup (nub' eq_dec L).\nProof.\n  intros A eq_dec L.\n  induction L as [|x L IH]; [apply NoDup_nil|].\n  unfold nub'.\n  destruct (in_dec eq_dec x L) as [H|H]; fold (@nub' A).\n  - trivial.\n  - apply NoDup_cons; trivial.\n    rewrite in_nub'.\n    trivial.\nQed.\n\nLemma NoDup_nub'_eq :\n  forall (A : Type) eq_dec (L : list A), NoDup L -> L = nub' eq_dec L.\nProof.\n  intros A eq_dec L H.\n  induction L as [|x L IH]; trivial.\n  simpl.\n  inversion H as [|y M H1 H2 [E1 E2]].\n  subst y M.\n  destruct (in_dec eq_dec x L) as [N|]; [tauto|].\n  rewrite <- IH; trivial.\nQed.\n\nLemma nub'_length :\n  forall (A : Type) eq_dec (L : list A), length (nub' eq_dec L) <= length L.\nProof.\n  intros A eq_dec L.\n  induction L as [|x L IH]; trivial.\n  simpl.\n  destruct (in_dec eq_dec x L) as [H|H].\n  - auto.\n  - simpl.\n    omega.\nQed.\n\nLemma nub'_filter :\n  forall (A : Type) eq_dec (f : A -> bool) (L : list A),\n    nub' eq_dec (filter f L) = filter f (nub' eq_dec L).\nProof.\n  intros A eq_dec f L.\n  induction L as [|x L IH]; trivial.\n  simpl.\n  destruct (f x) eqn:E;\n    simpl;\n    rewrite IH;\n    destruct (in_dec eq_dec x L) as [H1|H1];\n    destruct (in_dec eq_dec x (filter f L)) as [H2|H2];\n    rewrite filter_In in H2;\n    try tauto;\n    simpl;\n    destruct (f x);\n    trivial;\n    discriminate.\nQed.\n\nLemma select_length :\n  forall (A : Type) (L : list bool) (M : list A),\n    length (select L M) <= length M.\nProof.\n  intros A L M.\n  unfold select.\n  rewrite map_length, filter_length, combine_length.\n  auto with *.\nQed.\n\nLemma select_cons :\n  forall (A : Type) (x : bool) (L : list bool) (y : A) (M : list A),\n    select (x :: L) (y :: M) = (if x then [y] else []) ++ select L M.\nProof.\n  intros A x L y M.\n  destruct x; trivial.\nQed.\n\nLemma select_length_equal :\n  forall (A : Type) (L : list bool) (M N : list A),\n    length M = length N -> length (select L M) = length (select L N).\nProof.\n  intros A L M; revert L.\n  induction M as [|x M IH]; intros [|v L] [|y N]; trivial; simpl; try omega.\n  repeat rewrite select_cons, app_length.\n  intro H.\n  rewrite (IH L N) by auto.\n  destruct v; trivial.\nQed.\n\nLemma select_incl :\n  forall (A : Type) (L : list bool) (M : list A),\n    incl (select L M) M.\nProof.\n  intros A L M x.\n  unfold select.\n  rewrite in_map_iff.\n  intros [[y z] [E H]].\n  rewrite filter_In in H.\n  simpl in E.\n  subst z.\n  destruct H as [H _].\n  revert H.\n  apply in_combine_r.\nQed.\n\nLemma in_select :\n  forall (A : Type) (x d : A) (L : list bool) (M : list A),\n    In x (select L M) <-> (exists n : nat, nth n L false = true /\\ nth n M d = x /\\ n < length M).\nProof.\n  intros A x d L M.\n  unfold select.\n  rewrite in_map_iff.\n  split.\n  - intros [[b y] [E H]].\n    simpl in E.\n    subst y.\n    apply filter_In in H.\n    destruct H as [H E].\n    simpl in E.\n    subst b.\n    apply in_split in H.\n    destruct H as [N [P E]].\n    pose (f_equal (fun Q => nth (length N) Q (false, d)) E) as H.\n    simpl in H.\n    pose (f_equal (@length (bool * A)) E) as HL.\n    rewrite combine_length, app_length in HL.\n    simpl in HL.\n    assert (min (length L) (length M) <= length L) as HM1 by auto with *.\n    assert (min (length L) (length M) <= length M) as HM2 by auto with *.\n    rewrite combine_nth2 in H by omega.\n    rewrite app_nth2 in H by auto.\n    replace (length N - length N) with 0 in H by omega.\n    injection H as E1 E2.\n    exists (length N).\n    auto with *.\n  - intros [n [E1 [E2 H2]]].\n    exists (true, x).\n    split; trivial.\n    apply filter_In.\n    split; trivial.\n    rewrite <- E1, <- E2.\n    destruct (le_lt_dec (length L) n) as [H1|H1].\n    + apply (nth_overflow _ false) in H1.\n      rewrite H1 in E1.\n      discriminate.\n    + rewrite <- combine_nth2; trivial.\n      apply nth_In.\n      rewrite combine_length.\n      apply NPeano.Nat.min_glb_lt; trivial.\nQed.\n\nDefinition search_first\n  {A : Type}\n  (eq_dec : forall x y : A, {x = y} + {x <> y})\n  (x : A) (L : list A) :\n    {M : list A & {N | L = M ++ x :: N /\\ ~ In x M}} + {~ In x L}.\nProof.\n  induction L as [|y L IH].\n  - right.\n    tauto.\n  - destruct (eq_dec x y) as [E|NE].\n    + left.\n      exists nil, L.\n      subst y.\n      tauto.\n    + destruct IH as [[M [N [H1 H2]]]|NI].\n      * left.\n        exists (y :: M), N.\n        subst L.\n        simpl.\n        intuition.\n      * right.\n        firstorder.\nDefined.\n\nDefinition search_last\n  {A : Type}\n  (eq_dec : forall x y : A, {x = y} + {x <> y})\n  (x : A) (L : list A) :\n    {M : list A & {N | L = M ++ x :: N /\\ ~ In x N}} + {~ In x L}.\nProof.\n  destruct (search_first eq_dec x (rev L)) as [[M [N [H1 H2]]]|H].\n  - left.\n    exists (rev N), (rev M).\n    rewrite <- (rev_involutive L), <- rev_unit, <- rev_app_distr, <- app_assoc, H1, <- in_rev.\n    tauto.\n  - right.\n    rewrite <- in_rev in H.\n    trivial.\nDefined.\n\nDefinition remove1 {A : Type} eq_dec (x : A) (L : list A) : list A :=\n  match search_first eq_dec x L with\n  | inleft (existT _ M (exist _ N _)) => M ++ N\n  | inright _ => L\n  end.\n\nFixpoint list_diff {A : Type} eq_dec (L M : list A) : list A :=\n  match M with\n  | [] => L\n  | x :: N => remove1 eq_dec x (list_diff eq_dec L N)\n  end.\n\nLemma Permutation_remove1 :\n  forall (A : Type) eq_dec (x : A) (L M : list A),\n    Permutation (x :: L) M -> Permutation L (remove1 eq_dec x M).\nProof.\n  intros A eq_dec x L M H.\n  unfold remove1.\n  destruct (search_first eq_dec x M) as [[M1 [M2 [HM _]]]|NI].\n  - subst M.\n    apply Permutation_cons_app_inv in H.\n    trivial.\n  - apply (Permutation_in x) in H.\n    + tauto.\n    + auto with *.\nQed.\n\nLemma Permutation_list_diff :\n  forall (A : Type) eq_dec (L M N : list A),\n    Permutation (L ++ M) N -> Permutation M (list_diff eq_dec N L).\nProof.\n  intros A eq_dec L M N.\n  revert M.\n  induction L as [|x L IH]; trivial.\n  intros M H.\n  simpl.\n  apply Permutation_remove1, IH.\n  rewrite <- Permutation_middle.\n  trivial.\nQed.\n\nLemma list_diff_undisturbed :\n  forall (A : Type) eq_dec (x : A) (L M : list A),\n    In x L -> ~ In x M -> In x (list_diff eq_dec L M).\nProof.\n  intros A eq_dec x L M HL HM.\n  induction M as [|y M IH]; trivial.\n  simpl.\n  unfold remove1.\n  destruct (search_first eq_dec y (list_diff eq_dec L M)) as [[N1 [N2 [E H]]]|H].\n  - assert (~ In x M) as HM2 by auto with *.\n    specialize (IH HM2).\n    rewrite E, in_app_iff in IH.\n    destruct IH as [IH|[IH|IH]]; auto with *.\n    subst y.\n    contradict HM.\n    auto with *.\n  - auto with *.\nQed.\n\nLemma list_diff_NoDup_length :\n  forall (A : Type) eq_dec (L M : list A),\n    NoDup M -> incl M L -> length (list_diff eq_dec L M) = length L - length M.\nProof.\n  intros A eq_dec L M HN HI.\n  induction M as [|x M IH]; auto with *.\n  simpl.\n  unfold remove1.\n  destruct (search_first eq_dec x (list_diff eq_dec L M)) as [[N1 [N2 [E H]]]|H].\n  - assert (NoDup M) as HN2 by (inversion HN; trivial).\n    assert (incl M L) as HI2 by (unfold incl; auto with *).\n    specialize (IH HN2 HI2).\n    rewrite E, app_length in IH.\n    simpl in IH.\n    rewrite app_length.\n    omega.\n  - contradict H.\n    apply list_diff_undisturbed; auto with *.\n    inversion HN.\n    trivial.\nQed.\n\nDefinition empty_dec {A : Type} (L : list A) :\n  {L = []} + {L <> []}.\nProof.\n  destruct L.\n  - tauto.\n  - auto with *.\nDefined.\n\nDefinition NoDup_dec\n  {A : Type}\n  (eq_dec : forall x y : A, {x = y} + {x <> y})\n  (L : list A) :\n    {NoDup L} + {~ NoDup L}.\nProof.\n  destruct (list_eq_dec eq_dec L (nub' eq_dec L)) as [Y|N].\n  - left.\n    rewrite Y.\n    apply NoDup_nub'.\n  - right.\n    contradict N.\n    apply NoDup_nub'_eq, N.\nDefined.\n\nDefinition Permutation_dec\n  {A : Type}\n  (eq_dec : forall x y : A, {x = y} + {x <> y})\n  (L M : list A) :\n    {Permutation L M} + {~ Permutation L M}.\nProof.\n  revert M.\n  induction L as [|x L IH]; intro M.\n  - destruct M as [|x M].\n    + left.\n      apply perm_nil.\n    + right.\n      intro H.\n      apply Permutation_nil in H.\n      discriminate.\n  - destruct (search_first eq_dec x M) as [[M1 [M2 [HM _]]]|NI].\n    subst M.\n    + specialize (IH (M1 ++ M2)).\n      destruct IH as [YP|NP].\n      * left.\n        apply Permutation_cons_app.\n        trivial.\n      * right.\n        contradict NP.\n        exact (Permutation_cons_app_inv M1 M2 NP).\n    + right.\n      contradict NI.\n      apply (Permutation_in x NI).\n      auto with *.\nDefined.\n\nDefinition incl_dec\n  {A : Type}\n  (eq_dec : forall x y : A, {x = y} + {x <> y})\n  (L M : list A) :\n    {incl L M} + {~ incl L M}.\nProof.\n  induction L as [|x L IH].\n  - left.\n    intros x H.\n    contradict H.\n  - destruct (in_dec eq_dec x M) as [Y|N].\n    + destruct IH as [Y2|N2].\n      * left.\n        auto with *.\n      * right.\n        contradict N2.\n        intro y.\n        auto with *.\n    + right.\n      auto with *.\nDefined.\n", "meta": {"author": "ccd0", "repo": "superpermutations", "sha": "f32ee7adbb1468d0ca95ca98960dfe3bdca72cb2", "save_path": "github-repos/coq/ccd0-superpermutations", "path": "github-repos/coq/ccd0-superpermutations/superpermutations-f32ee7adbb1468d0ca95ca98960dfe3bdca72cb2/ListTheorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.8615382165412808, "lm_q1q2_score": 0.6601912678076522}}
{"text": "(******************************************************************************)\n(** * Minimal elements of relations *)\n(******************************************************************************)\n\nRequire Import HahnBase HahnList HahnSets HahnRelationsBasic.\nRequire Import HahnEquational HahnRewrite HahnMaxElt.\nRequire Import Arith Setoid.\n\nSet Implicit Arguments.\n\n\nDefinition min_elt A (r: relation A) (a : A) :=\n  forall b (REL: r b a), False.\n\nDefinition wmin_elt A (r: relation A) (a : A) :=\n  forall b (REL: r b a), a = b.\n\n\nSection BasicProperties.\n\nVariable A : Type.\nVariables r r' r'' : relation A.\nVariable a : A.\n\nLemma min_transp : min_elt r⁻¹ ≡₁ max_elt r.\nProof.\n  split; unfold min_elt, max_elt, transp, set_subset; ins; desf.  \nQed.\n\nLemma max_transp : max_elt r⁻¹ ≡₁ min_elt r.\nProof.\n  split; unfold min_elt, max_elt, transp, set_subset; ins; desf.  \nQed.\n\nLemma set_subset_min_elt (S: r' ⊆ r) : min_elt r ⊆₁ min_elt r'.\nProof. unfold min_elt, inclusion, set_subset in *; intuition; eauto. Qed.\n\nLemma set_subset_wmin_elt (S: r' ⊆ r) : wmin_elt r ⊆₁ wmin_elt r'.\nProof. unfold wmin_elt, inclusion, set_subset in *; intuition; eauto. Qed.\n\nLemma set_equiv_min_elt (S: r ≡ r') : min_elt r ≡₁ min_elt r'.\nProof. unfold min_elt, same_relation, set_equiv, set_subset in *; intuition; eauto. Qed.\n\nLemma set_equiv_wmin_elt (S: r ≡ r') : wmin_elt r ≡₁ wmin_elt r'.\nProof. unfold wmin_elt, same_relation, set_equiv in *; intuition; eauto. Qed.\n\nLemma min_elt_weaken : min_elt r a -> wmin_elt r a.\nProof.\n  red; ins; exfalso; eauto.\nQed.\n\nLemma min_elt_union : min_elt r a -> min_elt r' a -> min_elt (r +++ r') a.\nProof.\n  unfold union; red; ins; desf; eauto.\nQed.\n\nLemma wmin_elt_union : wmin_elt r a -> wmin_elt r' a -> wmin_elt (r +++ r') a.\nProof.\n  unfold union; red; ins; desf; eauto.\nQed.\n\nLemma min_elt_t : min_elt r a -> min_elt (r⁺) a.\nProof.\n  red; ins; apply clos_trans_t1n in REL; induction REL; eauto.\nQed.\n\nLemma wmin_elt_rt : wmin_elt r a -> wmin_elt (r＊) a.\nProof.\n  red; ins; apply clos_rt_rt1n in REL; induction REL; intuition; desf; eauto.\nQed.\n\nLemma wmin_elt_t : wmin_elt r a -> wmin_elt (r⁺) a.\nProof.\n  by red; ins; eapply wmin_elt_rt, inclusion_t_rt.\nQed.\n\nLemma wmin_elt_eqv (f: A -> Prop) : wmin_elt (eqv_rel f) a.\nProof.\n  unfold eqv_rel; red; ins; desf.\nQed.\n\nLemma wmin_elt_restr_eq B (f: A -> B) :\n  wmin_elt r a -> wmin_elt (restr_eq_rel f r) a.\nProof.\n  unfold restr_eq_rel in *; red; ins; desf; eauto.\nQed.\n\nLemma min_elt_restr_eq B (f: A -> B) :\n  min_elt r a -> min_elt (restr_eq_rel f r) a.\nProof.\n  unfold restr_eq_rel in *; red; ins; desf; eauto.\nQed.\n\nLemma wmin_elt_r :\n  wmin_elt r a -> wmin_elt (r^?) a.\nProof.\n  unfold clos_refl; red; ins; desf; eauto.\nQed.\n\nLemma min_elt_seq1 : min_elt r' a -> min_elt (r ⨾ r') a.\nProof.\n  unfold seq; red; ins; desf; apply H in REL0; desf; eauto.\nQed.\n\nLemma wmin_elt_seq2 : wmin_elt r a -> wmin_elt r' a -> wmin_elt (r ⨾ r') a.\nProof.\n  unfold seq; red; ins; desf; apply H0 in REL0; desf; eauto.\nQed.\n\nLemma wmin_elt_seq1 : min_elt r' a -> wmin_elt (r ⨾ r') a.\nProof.\n  unfold seq; red; ins; desf; apply H in REL0; desf; eauto.\nQed.\n\nLemma min_elt_seq2 : min_elt r a -> wmin_elt r' a -> min_elt (r ⨾ r') a.\nProof.\n  unfold seq; red; ins; desf; apply H0 in REL0; desf; eauto.\nQed.\n\nEnd BasicProperties.\n\nGlobal Hint Immediate min_elt_weaken : hahn.\nGlobal Hint Resolve wmin_elt_union min_elt_union : hahn.\nGlobal Hint Resolve wmin_elt_t wmin_elt_r wmin_elt_rt min_elt_t : hahn.\nGlobal Hint Resolve min_elt_restr_eq wmin_elt_restr_eq : hahn.\nGlobal Hint Resolve min_elt_seq1 min_elt_seq2 wmin_elt_seq1 wmin_elt_seq2 : hahn.\n\nSection MoreProperties.\n\nVariable A : Type.\nImplicit Type r : relation A.\n\nLemma seq_min r r' b\n      (MAX: min_elt r b) (DOM: forall x y, r' x y -> x = b) :\n  r ⨾ r' ≡ ∅₂.\nProof.\n  unfold seq; split; red; ins; desf.\n  apply DOM in H0; desf; eauto.\nQed.\n\nLemma seq_min_t r r' b\n      (MAX: min_elt r b) (DOM: forall x y, r' x y -> x = b) :\n  r ⁺ ⨾ r'  ≡ ∅₂.\nProof.\n  eauto using seq_min with hahn.\nQed.\n\nLemma seq_min_rt r r' b\n      (MAX: min_elt r b) (COD: forall x y, r' x y -> x = b) :\n  r ＊ ⨾ r' ≡ r'.\nProof.\n  rewrite rtE; relsf; rewrite seq_min_t; relsf.\nQed.\n\nLemma seq_min_r r r' b\n      (MAX: min_elt r b) (COD: forall x y, r' x y -> x = b) :\n  r ^? ⨾ r' ≡ r'.\nProof.\n  rewrite crE; relsf; rewrite seq_min; relsf.\nQed.\n\nLemma seq_min_eq r b (MAX: min_elt r b) :\n  r ⨾⦗eq b⦘ ≡ ∅₂.\nProof.\n  eapply seq_min; unfold eqv_rel; ins; desf; eauto.\nQed.\n\nLemma seq_min_t_eq r b (MAX: min_elt r b) :\n  r⁺ ⨾⦗eq b⦘ ≡ ∅₂.\nProof.\n  eauto using seq_min_eq with hahn.\nQed.\n\nLemma seq_min_rt_eq r b (MAX: min_elt r b) :\n  r＊ ⨾⦗eq b⦘ ≡ ⦗eq b⦘.\nProof.\n  rewrite rtE; relsf; rewrite seq_min_t_eq; relsf.\nQed.\n\nLemma seq_min_r_eq r b (MAX: min_elt r b) :\n  r^? ⨾⦗eq b⦘ ≡ ⦗eq b⦘.\nProof.\n  rewrite crE; relsf; rewrite seq_min_eq; relsf.\nQed.\n\nLemma seq_min_singl r a b (MAX: min_elt r a) :\n  r ⨾ singl_rel a b ≡ ∅₂.\nProof.\n  unfold singl_rel, seq; split; red; ins; desf; eauto.\nQed.\n\nLemma seq_min_t_singl r a b (MAX: min_elt r a) :\n  r⁺ ⨾ singl_rel a b ≡ ∅₂.\nProof.\n  eauto using seq_min_singl with hahn.\nQed.\n\nLemma seq_min_rt_singl r a b (MAX: min_elt r a) :\n  r＊ ⨾ singl_rel a b ≡ singl_rel a b.\nProof.\n  rewrite rtE; relsf; rewrite seq_min_t_singl; relsf.\nQed.\n\nLemma seq_min_r_singl r a b (MAX: min_elt r a) :\n  r^? ⨾ singl_rel a b ≡ singl_rel a b.\nProof.\n  rewrite crE; relsf; rewrite seq_min_singl; relsf.\nQed.\n\nLemma seq_eqv_min r : \n  r ⨾ ⦗min_elt r⦘ ≡ ∅₂.\nProof.\n  basic_solver.\nQed.\n\nLemma seq_t_eqv_min r :\n  r⁺ ⨾ ⦗min_elt r⦘ ≡ ∅₂.\nProof.\n  rewrite ct_end, seqA; seq_rewrite seq_eqv_min; basic_solver.\nQed.\n\nLemma seq_rt_eqv_min r :\n  r＊ ⨾ ⦗min_elt r⦘ ≡ ⦗min_elt r⦘.\nProof.\n  rewrite rtE; relsf; rewrite seq_t_eqv_min; relsf.\nQed.\n\nLemma seq_r_eqv_min r :\n  r^? ⨾ ⦗min_elt r⦘ ≡ ⦗min_elt r⦘.\nProof.\n  rewrite crE; relsf; rewrite seq_eqv_min; relsf.\nQed.\n\nLemma seq_eqv_min_transp r : \n  ⦗min_elt r⦘ ⨾ r⁻¹  ≡ ∅₂.\nProof.\n  basic_solver.\nQed.\n\nLemma seq_eqv_min_transp_t r :\n  ⦗min_elt r⦘ ⨾ (r⁻¹)⁺ ≡ ∅₂.\nProof.\n  rewrite ct_begin; seq_rewrite seq_eqv_min_transp; basic_solver.\nQed.\n\nLemma seq_eqv_min_transp_rt r :\n  ⦗min_elt r⦘ ⨾ (r⁻¹)＊  ≡ ⦗min_elt r⦘.\nProof.\n  rewrite rtE; relsf; rewrite seq_eqv_min_transp_t; relsf.\nQed.\n\nLemma seq_eqv_min_transp_r r :\n  ⦗min_elt r⦘ ⨾ (r⁻¹)^?  ≡ ⦗min_elt r⦘.\nProof.\n  rewrite crE; relsf; rewrite seq_eqv_min_transp; relsf.\nQed.\n\nLemma seq_wmin r r' b\n      (MAX: wmin_elt r b) (D: forall x y, r' x y -> x = b) :\n    r⨾ r' ⊆ r'.\nProof.\n  unfold seq; red; ins; desf; eauto.\n  specialize (D _ _ H0); desf; apply MAX in H; desf.\nQed.\n\nLemma seq_wmin_t r r' b\n      (MAX: wmin_elt r b) (D: forall x y, r' x y -> x = b) :\n  r ⁺⨾ r' ⊆ r'.\nProof.\n  eauto using seq_wmin with hahn.\nQed.\n\nLemma seq_wmin_rt r r' b\n      (MAX: wmin_elt r b) (COD: forall x y, r' x y -> x = b) :\n  r ＊⨾ r' ≡ r'.\nProof.\n  rewrite rtE; split; relsf; rewrite seq_wmin_t; relsf.\nQed.\n\nLemma seq_wmin_r r r' b\n      (MAX: wmin_elt r b) (COD: forall x y, r' x y -> x = b) :\n  r ^?⨾ r' ≡ r'.\nProof.\n  rewrite crE; split; relsf; rewrite seq_wmin; relsf.\nQed.\n\nLemma seq_wmin_eq r b (MAX: wmin_elt r b) :\n  r ⨾ ⦗eq b⦘ ⊆ ⦗eq b⦘.\nProof.\n  eapply seq_wmin; unfold eqv_rel; ins; desf.\nQed.\n\nLemma seq_wmin_t_eq r b (MAX: wmin_elt r b) :\n  r ⁺ ⨾ ⦗eq b⦘ ⊆ ⦗eq b⦘.\nProof.\n  eauto using seq_wmin_eq with hahn.\nQed.\n\nLemma seq_wmin_rt_eq r b (MAX: wmin_elt r b) :\n  r ＊ ⨾ ⦗eq b⦘ ≡ ⦗eq b⦘.\nProof.\n  rewrite rtE; split; relsf; rewrite seq_wmin_t_eq; relsf.\nQed.\n\nLemma seq_wmin_r_eq r b (MAX: wmin_elt r b) :\n  r ^? ⨾ ⦗eq b⦘ ≡ ⦗eq b⦘.\nProof.\n  rewrite crE; split; relsf; rewrite seq_wmin_eq; relsf.\nQed.\n\nLemma seq_wmin_singl r a b (MAX: wmin_elt r a) :\n  r ⨾ singl_rel a b ⊆ singl_rel a b.\nProof.\n  unfold singl_rel, seq; red; ins; desf; eauto.\n  apply MAX in H; desf.\nQed.\n\nLemma seq_wmin_t_singl r a b (MAX: wmin_elt r a) :\n  r ⁺ ⨾ singl_rel a b ⊆ singl_rel a b.\nProof.\n  eauto using seq_wmin_singl with hahn.\nQed.\n\nLemma seq_wmin_rt_singl r a b (MAX: wmin_elt r a) :\n  r ＊ ⨾ singl_rel a b ≡ singl_rel a b.\nProof.\n  rewrite rtE; split; relsf; rewrite seq_wmin_t_singl; relsf.\nQed.\n\nLemma seq_wmin_r_singl r a b (MAX: wmin_elt r a) :\n  r ^? ⨾ singl_rel a b ≡ singl_rel a b.\nProof.\n  rewrite crE; split; relsf; rewrite seq_wmin_singl; relsf.\nQed.\n\nEnd MoreProperties.\n\nGlobal Hint Unfold min_elt wmin_elt : unfolderDb.\n\nRequire Import Morphisms.\n\nInstance min_elt_Proper A : Proper (inclusion --> set_subset) _ := set_subset_min_elt (A:=A).\nInstance wmin_elt_Proper A : Proper (inclusion --> set_subset) _ := set_subset_wmin_elt (A:=A).\nInstance min_elt_Propere A : Proper (same_relation ==> set_equiv) _ := set_equiv_min_elt (A:=A).\nInstance wmin_elt_Propere A : Proper (same_relation ==> set_equiv) _ := set_equiv_wmin_elt (A:=A).\n\nAdd Parametric Morphism A : (@min_elt A) with signature\n  inclusion --> eq ==> Basics.impl as min_elt_mori.\nProof.\n  unfold inclusion, min_elt, Basics.impl; eauto.\nQed.\n\nAdd Parametric Morphism A : (@wmin_elt A) with signature\n  inclusion --> eq ==> Basics.impl as wmin_elt_mori.\nProof.\n  unfold inclusion, wmin_elt, Basics.impl; eauto.\nQed.\n\nAdd Parametric Morphism A : (@min_elt A) with signature\n  same_relation --> eq ==> iff as min_elt_more.\nProof.\n  unfold same_relation, inclusion, min_elt; firstorder.\nQed.\n\nAdd Parametric Morphism A : (@wmin_elt A) with signature\n  same_relation --> eq ==> iff as wmin_elt_more.\nProof.\n  unfold same_relation, inclusion, wmin_elt; firstorder.\nQed.\n\n", "meta": {"author": "vafeiadis", "repo": "hahn", "sha": "d486f449a51c14b8e1093f14d096cc99833974d7", "save_path": "github-repos/coq/vafeiadis-hahn", "path": "github-repos/coq/vafeiadis-hahn/hahn-d486f449a51c14b8e1093f14d096cc99833974d7/HahnMinElt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759128, "lm_q2_score": 0.7662936430859598, "lm_q1q2_score": 0.6601912504383949}}
{"text": "Lemma L2 : forall (A:Type) (P : A->Prop) (Q : Prop),\n  (forall x:A, P x -> Q) <-> ((exists y:A, P y) -> Q).\n  Proof.\n  intros A P Q.\n(* \n1 subgoal\nA : Type\nP : A -> Prop\nQ : Prop\n______________________________________(1/1)\n(forall x : A, P x -> Q) <-> (exists y : A, P y) -> Q \n*)\n\n  split.\n\n(* \n2 subgoals\nA : Type\nP : A -> Prop\nQ : Prop\n______________________________________(1/2)\n(forall x : A, P x -> Q) -> (exists y : A, P y) -> Q\n\n\n______________________________________(2/2)\n((exists y : A, P y) -> Q) -> forall x : A, P x -> Q \n*)\n\n  intro H.\n(*\n2 subgoals\nA : Type\nP : A -> Prop\nQ : Prop\nH : forall x : A, P x -> Q\n______________________________________(1/2)\n(exists y : A, P y) -> Q\n*)\n  intros [y Hy].\n\n(*\n2 subgoals\nA : Type\nP : A -> Prop\nQ : Prop\nH : forall x : A, P x -> Q\ny : A\nHy : P y\n______________________________________(1/2)\nQ\n*)\n  apply (H y).\n\n(*\n2 subgoals\nA : Type\nP : A -> Prop\nQ : Prop\nH : forall x : A, P x -> Q\ny : A\nHy : P y\n______________________________________(1/2)\nP y\n\n*)\n assumption.\n\n\n(*\n1 subgoal\nA : Type\nP : A -> Prop\nQ : Prop\n______________________________________(1/1)\n((exists y : A, P y) -> Q) -> forall x : A, P x -> Q\n*)\n\n  intro H.\n\n(*\n1 subgoal\nA : Type\nP : A -> Prop\nQ : Prop\nH : (exists y : A, P y) -> Q\n______________________________________(1/1)\nforall x : A, P x -> Q\n*)\n  \n  intros x Hx.\n  \n(*\n1 subgoal\nA : Type\nP : A -> Prop\nQ : Prop\nH : (exists y : A, P y) -> Q\nx : A\nHx : P x\n______________________________________(1/1)\nQ\n*)\n  apply H.\n(*\n1 subgoal\nA : Type\nP : A -> Prop\nQ : Prop\nH : (exists y : A, P y) -> Q\nx : A\nHx : P x\n______________________________________(1/1)\nexists y : A, P y\n*)\n  exists x.\n\n(*\n1 subgoal\nA : Type\nP : A -> Prop\nQ : Prop\nH : (exists y : A, P y) -> Q\nx : A\nHx : P x\n______________________________________(1/1)\nP x\n*)\n assumption.\n\nQed.", "meta": {"author": "magret2canard", "repo": "master1", "sha": "a993e9cbd38ee045af2900f9486ee9438d5e3274", "save_path": "github-repos/coq/magret2canard-master1", "path": "github-repos/coq/magret2canard-master1/master1-a993e9cbd38ee045af2900f9486ee9438d5e3274/LOGIQUE/Exam/memo_exam.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.6601400803751545}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nTheorem append_nil: forall (l: lst), append l Nil = l.\nProof.\n   induction l.\n   { simpl. f_equal. assumption. }\n   { simpl. reflexivity. }\nQed.\n\nTheorem append_assoc:\n   forall (l1 l2 l3: lst), append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\n   induction l1; induction l2; induction l3; try (simpl; reflexivity).\n   { simpl. rewrite <- IHl1. f_equal. }\n   { simpl. rewrite 2 append_nil. reflexivity. }\n   { simpl. rewrite append_nil.  reflexivity. }\n   { simpl. rewrite 2 append_nil. reflexivity. }\nQed.\n\nTheorem append_rev_cons:\n   forall (l1 l2: lst) (x: natural),\n   rev (append l1 (Cons x l2)) = append (rev l2) (Cons x (rev l1)).\nProof.\n   induction l1; induction l2; try (simpl; reflexivity).\n   { intro. simpl. rewrite IHl1. simpl. rewrite <- append_assoc.\n   f_equal. }\n   { intro. simpl. rewrite IHl1. simpl. reflexivity. }\nQed.\n\nTheorem rev_append: forall (l1 l2: lst), rev (append l1 l2) = append (rev l2) (rev l1).\nProof.\n   induction l1.\n   { induction l2.\n   { simpl. rewrite append_rev_cons.\n      rewrite <- 2 append_assoc.\n      f_equal. }\n   { simpl. rewrite append_nil. reflexivity. }\n   }\n   { intro. simpl. rewrite append_nil. reflexivity. }\nQed.\n\nTheorem rev_involutive : forall (x : lst), eq (rev (rev x)) x.\nProof.\n   induction x.\n   { simpl. rewrite rev_append. simpl. f_equal.\n   assumption. }\n   { simpl. reflexivity. }\nQed.\n\nTheorem theorem0 : forall (x : lst), eq (rev (append (rev x) Nil)) x.\nProof.\n   intro.\nlfind. \nAdmitted.\n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal30_theorem0_73_append_nil/goal30.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.6601400646006529}}
{"text": "Require Import Arith.\n\n\n\n\n\n(******************************************************************************)\n(* FONCTIONS RECURSIVES ET INDUCTION SUR LES LISTES                           *)\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(* 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 := \n  match l1 with\n  | []     => l2\n  | x :: l => x::(concat l l2)\n  end.\n\n(* On note ++ en notation infix pour la concatenation *)\nInfix \"++\" := concat.\n\n\n(* On reprend la fonction appartient du TP de LIFLF *)\n\nFixpoint appartient (x : nat) (l : nlist) : bool :=\n  match l with\n  | [] => false\n  | h::rl => (Nat.eqb x h) || (appartient x rl)\n  end.\n(* END CUT *)\n\n(* Exprimer (cf. TD de LIFLC) et montrer que cette fonction retourne\ntrue sur la donnée de paramètres x de type nat et l de type nlist\nseulement si on peut écrire l comme une nlist l1 concaténée à une\nnlist l2 commençant par x *)\n\n(* on aura besoin du théorème \n   - Bool.orb_prop \n*)\nCheck Bool.orb_prop.\n\n(* on aura besoin du théorème \n   - beq_nat_true (déjà vu)\n*)\n\nCheck beq_nat_true.\n\n(* En hypothèse l'existentiel est éliminé avec destruct de l'hypothèse *)\n(* Rappel : la règle d'introduction de l'existentiel dans le but est exists objet_specialisé *)\n\n\n\nTheorem appartient_seulement : forall(x:nat), forall(l:nlist), appartient x l = true -> exists(l1:nlist), exists(l2:nlist), l = concat l1 (x::l2).\nProof.\nintro x.\nintro l.\ninduction l.\n-\nintro h0.\nexists [].\nexists [].\ndiscriminate.\n-intro h1.\nexists [].\nexists l.\nsimpl.\ndestruct IHl.\n+rewrite <- h1.\nsimpl.\nrewrite <- h1.\nQed.\n\n    \n(**********************************************************************)\n(* Exprimer et montrer que la fonction plus est commutative                       *)\n(* On commencera par montrer un petit lemme technique                 *)\n(**********************************************************************)\n\nLemma plus_Succ_r : forall a b, S (plus a b) = plus a (S b). \nProof.\nAdmitted. (* remplacer ici *)\n\nLemma plus_commute : \nProof.\nAdmitted. (* remplacer ici *)\n\n\n(******************************************************************************)\n(* Les arbres binaires de nat *)\n(******************************************************************************)\n\n(* le type inductif *)\nInductive BinTree : Set :=\n  | leaf : BinTree \n  | node : BinTree -> nat -> BinTree -> BinTree.\n\n(**********************************************************************)\n(* Montrer par induction sur Bin E qu'un arbre binaire comportant\n   n occurrences de l’arbre vide contient n - 1 éléments              *)\n(**********************************************************************)\n(* on aura sans doute besoin du théorème plus_n_Sm *)\nCheck plus_n_Sm.\n\n(* les deux fonctions qui comptent *)\nFixpoint count_leaves (t:BinTree) : nat :=\nend.\n\nFixpoint count_nodes (t:BinTree) : nat :=\nend.\n\n(* la propriété *)\nLemma count_leaves_nodes : forall (t:BinTree), 1 + (count_nodes t) =  (count_leaves  t).\nProof.\nAdmitted. (* remplacer ici *)\n\n\n(**********************************************************************)\n(* ÉTUDE DE CAS.\n\nOn se propose de regarder le cas de l'automate qui reconnaît les mots finissant par \"aab\".\nOn commence par définir cet automate en utilisant le TP de LIFLF.\n *)\n(**********************************************************************)\n\n(* inclure ici le TP de LF *)\n\n\n(* Automate qui reconnaît les mots qui finissent par \"aab\" *)\nDefinition gaab := [ ]. (* remplacer ici *)\n\nDefinition Aaab := false. (* remplacer ici *)\n\n\n(* Écrire en commentaire la grammaire régulière produisant le langage de l'automate *)\n(* Source : X1\n *)\n\n(* On peut définir le prédicat \"être généré par cette grammaire\" *)\n\n(* En effet : une règle \"N -> c M\" signifie qu'un mot généré depuis N\n   peut être constitué d'un c suivi par un mot généré depuis M donc\n   pour tout mot w, le mot cw est généré par N si w est généré par M.\n   Dit autrement : \"pour tout mot w, si w est généré depuis M alors cw\n   est généré depuis N\".  C'est exactement ce qu'on se propose\n   d'écrire. *)\n\n(* On va donc définir un prédicat *inductif*, paramétré par un mot et\nun état (vu comme un non terminal de la grammaire ), dont chaque\nrègle de construction caractérise chaque règle de grammaire *)\n\n(* Définir ce prédicat inductif Paab, de type liste Alphabet -> nat -> Prop *)\nInductive Paab : list Alphabet -> nat -> Prop := False (* remplacer ici *)\n.\n\n\n(* Pour montrer qu'un mot est bien généré depuis un état, il suffit\nd'appliquer (apply) les règles de construction jusqu'à tomber sur un\ncas de base. *)\n(* Montrer que le mot abaaab est bien généré depuis le non terminal 1 *)\n\nLemma exemple :  Paab [a;b;a;a;a;b] 1.\nProof.\nAdmitted. (* remplacer ici *)\n\n(* CE PRÉDICAT (DÉRIVÉ DE LA GRAMMAIRE) CARACTÉRISE-T-IL BIEN LES MOTS\nRECONNUS PAR L'AUTOMATE ? *)\n\n(* Pour le montrer on va poser un lemme intermédiaire *)\n\n(* Ce lemme, appelons-le PmimeA, énonce que pour tout mot généré à\npartir d'un état/non terminal, disons q, de la grammaire, la lecture\nde ce mot depuis q dans l'automate aboutit à un état, disons e, et cet\nétat e est acceptant. *)\n\n(* Définir le lemme PmimeA *)\nLemma PmimeA : False. (* remplacer ici *)\nProof.\nAdmitted. (* remplacer ici *)\n\n(* Pour le montrer une nouvelle tactique va être bien utile :\ninversion.\n  - La tactique \"inversion\" appliquée à un nom d'inductif énumère les\n  cas *possibles* de règles qui ont pu le produire.\n  - Les cas absurdes sont éliminés, en particulier si une hypothèse n'a\n  pu apparaître qu'à l'aide de cas absurdes, le but est prouvé.\n  - On va se servir de cette tactique pour se placer dans les différents\n  cas du prédicat. *)\n\n\n\n(* Énoncer et montrer le théorème principal : tout mot généré depuis le non terminal 1 est reconnu par l'automate. *)\nTheorem PA : False. (* remplacer ici *)\nProof.\nAdmitted. (* remplacer ici *)\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_tp3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634457, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.6601400631077319}}
{"text": "(*|\n####################################################\nProblems with dependent types in Coq proof assistant\n####################################################\n\n:Link: https://stackoverflow.com/q/43453365\n|*)\n\n(*|\nQuestion\n********\n\nConsider the following simple expression language:\n|*)\n\nRequire Import Arith_base List. (* .none *)\nInductive Exp : Set :=\n| EConst : nat -> Exp\n| EVar   : nat -> Exp\n| EFun   : nat -> list Exp -> Exp.\n\n(*| and its wellformedness predicate: |*)\n\nDefinition Env := list nat.\n\nInductive WF (env : Env) : Exp -> Prop :=\n| WFConst : forall n, WF env (EConst n)\n| WFVar   : forall n, In n env -> WF env (EVar n)\n| WFFun   : forall n es, In n env ->\n                         Forall (WF env) es ->\n                         WF env (EFun n es).\n\n(*|\nwhich basically states that every variable and function symbols must\nbe defined in the environment. Now, I want to define a function that\nstates the decidability of ``WF`` predicate:\n|*)\n\nDefinition WFDec (env : Env) : forall e, {WF env e} + {~ WF env e}.\n  refine (fix wfdec e : {WF env e} + {~ WF env e} :=\n            match e as e' return e = e' -> {WF env e'} + {~ WF env e'} with\n            | EConst n => fun _ => left _ _\n            | EVar n => fun _ =>\n                          match in_dec eq_nat_dec n env with\n                          | left _ _ => left _ _\n                          | right _ _ => right _ _\n                          end\n            | EFun n es => fun _ =>\n                             match in_dec eq_nat_dec n env with\n                             | left _ _ => _\n                             | right _ _ => right _ _\n                             end\n            end (eq_refl e)); clear wfdec; subst; eauto.\nAbort. (* .none *)\n\n(*|\nThe trouble is how to state that ``WF`` predicate holds or not for a\nlist of expressions in the ``EFun`` case. My obvious guess was:\n\n.. code-block:: coq\n\n    ...\n    match Forall_dec (WF env) wfdec es with\n    ...\n\nBut Coq refuses it, arguing that the recursive call ``wfdec`` is\nill-formed. My question is: Is it possible to define decidability of\nsuch wellformedness predicate without changing the expression\nrepresentation?\n\nThe complete working code is at the following `gist\n<https://gist.github.com/rodrigogribeiro/132e4feca910f40198242d3da3eca040>`__.\n|*)\n\n(*|\nAnswer (ejgallego)\n******************\n\nAs a temporal workaround you can define ``wf`` as:\n|*)\nFrom mathcomp Require Import all_ssreflect. (* .none *)\nDefinition wf (env : Env) := fix wf (e : Exp) : bool :=\n    match e with\n    | EConst _ => true\n    | EVar v   => v \\in env\n    | EFun v l => [&& v \\in env & all wf l]\n    end.\n\n(*|\nwhich is usually way more convenient to use. However, this definition\nwill be pretty useless due to Coq generating the wrong induction\nprinciple for ``exp``, as it doesn't detect the list. What I usually\ndo is to fix the induction principle manually, but this is costly.\nExample:\n|*)\n\nReset Initial. (* .none *)\nFrom Coq Require Import List.\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Printing Implicit Defensive.\nImport Prenex Implicits.\n\nSection ReflectMorph.\n\n  Lemma and_MR P Q b c : reflect P b -> reflect Q c -> reflect (P /\\ Q) (b && c).\n  Proof. by move=> h1 h2; apply: (iffP andP) => -[/h1 ? /h2 ?]. Qed.\n\n  Lemma or_MR P Q b c : reflect P b -> reflect Q c -> reflect (P \\/ Q) (b || c).\n  Proof. by move=> h1 h2; apply: (iffP orP) => -[/h1 | /h2]; auto. Qed.\n\nEnd ReflectMorph.\n\nSection IN.\n  Variables (X : eqType).\n\n  Lemma InP (x : X) l : reflect (In x l) (x \\in l).\n  Proof.\n    elim: l => [|y l ihl]; first by constructor 2.\n    by apply: or_MR; rewrite // eq_sym; exact: eqP.\n  Qed.\n\nEnd IN.\n\nSection FORALL.\n\n  Variables (X : Type) (P : X -> Prop).\n  Variables (p : X -> bool).\n\n  Lemma Forall_inv x l : Forall P (x :: l) -> P x /\\ Forall P l.\n  Proof. by move=> U; inversion U. Qed.\n\n  Lemma ForallP l : (forall x, In x l -> reflect (P x) (p x)) ->\n                    reflect (Forall P l) (all p l).\n  Proof.\n    elim: l => [|x l hp ihl /=]; first by constructor.\n    have/hp {hp}hp : forall x : X, In x l -> reflect (P x) (p x).\n    by move=> y y_in; apply: ihl; right.\n    have {ihl} ihl := ihl _ (or_introl erefl).\n    by apply: (iffP andP) => [|/Forall_inv] [] /ihl hx /hp hall; constructor.\n  Qed.\n\nEnd FORALL.\n\nInductive Exp : Type :=\n| EConst : nat -> Exp\n| EVar   : nat -> Exp\n| EFun   : nat -> list Exp -> Exp.\n\nLemma Exp_rect_list (P : Exp -> Type) :\n  (forall n : nat, P (EConst n)) ->\n  (forall n : nat, P (EVar n)) ->\n  (forall (n : nat) (l : seq Exp),\n      (forall x, In x l -> P x) -> P (EFun n l)) -> forall e : Exp, P e.\nAdmitted.\n\nDefinition Env := list nat.\n\nDefinition wf (env : Env) := fix wf (e : Exp) : bool :=\n    match e with\n    | EConst _ => true\n    | EVar v   => v \\in env\n    | EFun v l => [&& v \\in env & all wf l]\n    end.\n\nInductive WF (env : Env) : Exp -> Prop :=\n| WFConst : forall n, WF env (EConst n)\n| WFVar   : forall n, In n env -> WF env (EVar n)\n| WFFun   : forall n es, In n env ->\n                         Forall (WF env) es ->\n                         WF env (EFun n es).\n\nLemma WF_inv env e (wf : WF env e) :\n  match e with\n  | EConst n  => True\n  | EVar n    => In n env\n  | EFun n es => In n env /\\ Forall (WF env) es\n  end.\nProof. by case: e wf => // [n | n l] H; inversion H. Qed.\n\nLemma wfP env e : reflect (WF env e) (wf env e).\nProof.\n  elim/Exp_rect_list: e => [n | n | n l ihe] /=; try repeat constructor.\n  by apply: (iffP idP) => [/InP | /WF_inv/InP //]; constructor.\n  apply: (iffP andP) => [[/InP ? /ForallP H] | /WF_inv[/InP ? /ForallP]].\n  by constructor => //; exact: H.\n  by auto.\nQed.\n\n(*|\nAnswer (Arthur Azevedo De Amorim)\n*********************************\n\nThe problem is that ``Forall_dec`` is defined as opaque in the\nstandard library (that is, with ``Qed`` instead of ``Defined``).\nBecause of that, Coq does not know that the use of ``wfdec`` is valid.\n\nThe immediate solution to your problem is to redefine ``Forall_dec``\nso that it is transparent. You can do this by printing the proof term\nthat Coq generates and pasting it in your source file. I've added a\n`gist\n<https://gist.github.com/anonymous/5b3fdc11871e42b3e9cfe006f6d8cc76>`__\nhere with a complete solution.\n\nNeedless to say, this approach lends itself to bloated, hard to read,\nand hard to maintain code. As ejgallego was pointing out in his\nanswer, your best bet in this case is probably to define a Boolean\nfunction that decides ``WF``, and use that instead of ``WFDec``. The\nonly problem with his approach, as he said, is that you will need to\nwrite your own induction principle to ``Exp`` in order to prove that\nthe Boolean version indeed decides the inductive definition. Adam\nChlipala's CPDT has a `chapter\n<http://adam.chlipala.net/cpdt/html/InductiveTypes.html>`__ on\ninductive types that gives an example of such an induction principle;\njust look for \"nested inductive types\".\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/problems-with-dependent-types-in-coq-proof-assistant.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.6601400626400892}}
{"text": "Require Export euclidean__axioms.\nRequire Export euclidean__defs.\nRequire Export lemma__parallelflip.\nRequire Export lemma__parallelsymmetric.\nRequire Export logic.\nDefinition lemma__PGsymmetric : forall A B C D, (euclidean__defs.PG A B C D) -> (euclidean__defs.PG C D A B).\nProof.\nintro A.\nintro B.\nintro C.\nintro D.\nintro H.\nassert (* Cut *) ((euclidean__defs.Par A B C D) /\\ (euclidean__defs.Par A D B C)) as H0.\n- assert ((euclidean__defs.Par A B C D) /\\ (euclidean__defs.Par A D B C)) as H0 by exact H.\nassert ((euclidean__defs.Par A B C D) /\\ (euclidean__defs.Par A D B C)) as __TmpHyp by exact H0.\ndestruct __TmpHyp as [H1 H2].\nsplit.\n-- exact H1.\n-- exact H2.\n- assert (* Cut *) (euclidean__defs.Par C D A B) as H1.\n-- destruct H0 as [H1 H2].\napply (@lemma__parallelsymmetric.lemma__parallelsymmetric A B C D H1).\n-- assert (* Cut *) (euclidean__defs.Par B C A D) as H2.\n--- destruct H0 as [H2 H3].\napply (@lemma__parallelsymmetric.lemma__parallelsymmetric A D B C H3).\n--- assert (* Cut *) (euclidean__defs.Par C B D A) as H3.\n---- destruct H0 as [H3 H4].\nassert (* Cut *) ((euclidean__defs.Par C B A D) /\\ ((euclidean__defs.Par B C D A) /\\ (euclidean__defs.Par C B D A))) as H5.\n----- apply (@lemma__parallelflip.lemma__parallelflip B C A D H2).\n----- destruct H5 as [H6 H7].\ndestruct H7 as [H8 H9].\nexact H9.\n---- assert (* Cut *) (euclidean__defs.PG C D A B) as H4.\n----- split.\n------ exact H1.\n------ exact H3.\n----- exact H4.\nQed.\n", "meta": {"author": "Karnaj", "repo": "dktactgeo", "sha": "f98a62e5ffa2030dc89962e1349e0c273cc911b9", "save_path": "github-repos/coq/Karnaj-dktactgeo", "path": "github-repos/coq/Karnaj-dktactgeo/dktactgeo-f98a62e5ffa2030dc89962e1349e0c273cc911b9/lemma__PGsymmetric.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6600625548770115}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nSection Nagoya2013.\n\n  Definition Sk k n := \\sum_(1 <= i < n.+1) i ^ k.\n  Variable m : nat.\n  Hypothesis Hm : m > 1.\n  Definition Tm n := \\sum_(1 <= k < m) 'C(m, k) * Sk k n. (* binomial.v 参照*)\n\n  Check big_nat1\n        : forall (R : Type) (idx : R) (op : Monoid.law idx) (n : nat) (F : nat -> R),\n            \\big[op/idx]_(n <= i < n.+1) F i = F n.\n\n  Lemma Sk1 k :\n    Sk k 1 = 1.\n  Proof.\n    by rewrite /Sk big_nat1 exp1n.\n    (*\n      Sk k 1 = 1.\n      ↓\n      ↓rewrite /Sk.\n      ↓\n      \\sum_(1 <= i < 2) i ^ k = 1\n      ↓\n      ↓rewrite big_nat1.\n      ↓\n      1 ^ k = 1\n      ↓\n      ↓rewrite exp1n.\n      ↓\n      1 = 1\n    *)\n  Qed.\n\n  Lemma Tm1 :\n    Tm 1 = 2 ^ m - 2.\n  Proof.\n    rewrite /Tm.\n    rewrite [in 2 ^ m](_ : 2 = 1 + 1) //.\n    rewrite Pascal. (* 二項公式*)\n    transitivity ((\\sum_(0 <= k < m.+1) 'C(m, k)) - 2).\n      symmetry.\n      rewrite (@big_cat_nat _ _ _ m) //=.\n      rewrite (@big_cat_nat _ _ _ 1) //=; last by apply ltnW.\n      rewrite addnAC !big_nat1 bin0 binn addKn.\n      apply eq_bigr => i H.\n      by rewrite Sk1 muln1.\n    rewrite big_mkord.\n    congr (_ - _).\n    apply eq_bigr => i _.\n    by rewrite !exp1n !muln1.\n  Qed.\n\n  Search (_ ^ _) \"exp\". (* 自然数の指数関数expn に関する様々な補題*)\n\n  Lemma Tm2 :\n    Tm 2 = 3 ^ m - 3.\n  Proof.\n    rewrite /Tm.\n    have ->: 3 ^ m - 3 = 2 ^ m - 2 + (3 ^ m - 1 - 2 ^ m).\n      (* 追加ここから *)\n      rewrite addnC addnBA.\n      - rewrite subnK.\n        + by rewrite -subnDA.\n        + (*\n            2 ^ m <= 3 ^ m - 1\n            2 ^ m <= (2 + 1) ^ m - 1\n            2 ^ m <= \\sum_(i < m.+1) 'C(m, i) * (2 ^ (m - i) * 1 ^ i) - 1\n            2 ^ m <= 'C(m, 0) * (2 ^ (m - 0) * 1 ^ 0) +\n                     \\sum_(1 <= i < m.+1) 'C(m, i) * (2 ^ (m - i) * 1 ^ i) - 1\n            2 ^ m <= 1 * (2 ^ m * 1) +\n                     \\sum_(1 <= i < m.+1) 'C(m, i) * (2 ^ (m - i) * 1 ^ i) - 1\n            2 ^ m <= 2 ^ m +\n                     \\sum_(1 <= i < m.+1) 'C(m, i) * (2 ^ (m - i) * 1 ^ i) - 1\n                0 <= \\sum_(1 <= i < m.+1) 'C(m, i) * (2 ^ (m - i) * 1 ^ i) - 1\n                0 <= \\sum_(1 <= i < m) 'C(m, i) * (2 ^ (m - i) * 1 ^ i) +\n                    'C(m, m) * (2 ^ (m - m) * 1 ^ m) - 1\n                0 <= \\sum_(1 <= i < m) 'C(m, i) * (2 ^ (m - i) * 1 ^ i) +\n                     1 * (2 ^ 0 * 1) - 1\n                0 <= \\sum_(1 <= i < m) 'C(m, i) * (2 ^ (m - i) * 1 ^ i) + 1 - 1\n                0 <= \\sum_(1 <= i < m) 'C(m, i) * (2 ^ (m - i) * 1 ^ i)\n          *)\n          rewrite [in 3 ^ m](_ : 3 = 2 + 1); last done.\n          rewrite Pascal.\n          rewrite -(@big_mkord _ 0 addn m.+1 (fun n => true) (fun i => 'C(m, i) * (2 ^ (m - i) * 1 ^ i))).\n          rewrite big_nat_recl.\n          rewrite bin0 subn0 expn0 mul1n muln1.\n          rewrite -{1}[2 ^ m]addn0.\n          rewrite -{3}[m]prednK; last by apply: (@ltn_trans 1 0 m).\n          rewrite big_nat_recr /=.\n          + rewrite prednK; last by apply: (@ltn_trans 1 0 m).\n            rewrite binn exp1n subnn expn0 !mul1n addnA addn1 subn1 PeanoNat.Nat.pred_succ.\n            by rewrite leq_add2l.\n          + rewrite leq_eqVlt; apply/orP; right.\n            by rewrite -(@ltn_add2r 1) add0n addn1 prednK; last by apply: (@ltn_trans 1 0 m).\n          rewrite leq_eqVlt; apply/orP; right.\n          by apply: (@ltn_trans 1 0 m).\n      - rewrite -{1}(exp1n m) ltn_exp2r; first done.\n        by apply: (@ltn_trans 1 0 m).\n      (* 追加ここまで *)\n    rewrite -Tm1.\n    rewrite [in 3 ^ m](_ : 3 = 1 + 2) //.\n    rewrite Pascal.\n    transitivity (Tm 1 + (\\sum_(1 <= k < m) 'C(m, k) * 2 ^ k)).\n      rewrite -big_split /=.\n      apply eq_bigr => i _.\n      rewrite /Sk !big_cons !big_nil.\n      by rewrite !addn0 -mulnDr.\n    congr (_ + _).\n    transitivity ((\\sum_(0 <= k < m.+1) 'C(m, k) * 2 ^ k) - 1 - 2 ^ m).\n    (* 追加ここから *)\n      rewrite [in RHS]big_nat_recr /=. \n      - rewrite binn mul1n.\n        rewrite [in RHS]big_ltn; last by apply: (@ltn_trans 1 0 m).\n        rewrite bin0 expn0 muln1.\n        rewrite -addnA addnC -subnDA [1 + 2 ^ m]addnC -addnA -addnBA; last done.\n        by rewrite subnn addn0.\n      - apply: ltnW.\n        by apply: (@ltn_trans 1 0 m).\n    rewrite big_mkord.\n    have -> : \\sum_(i < m.+1) 'C(m, i) * 2 ^ i =\n              \\sum_(i < m.+1) 'C(m, i) * (1 ^ (m - i) * 2 ^ i).\n      rewrite -(@big_mkord _ 0 addn m.+1 (fun n => true) (fun i => 'C(m, i) * 2 ^ i)).\n      rewrite -(@big_mkord _ 0 addn m.+1 (fun n => true) (fun i => 'C(m, i) * (1 ^ (m - i) * 2 ^ i))).\n      apply: (@eq_big_nat _ 0 addn 0 m.+1 (fun i => 'C(m, i) * 2 ^ i) (fun i => 'C(m, i) * (1 ^ (m - i) * 2 ^ i))) => i.\n      by rewrite exp1n mul1n.\n    by [].\n    (* 追加ここまで *)\n  Qed.\n\n  Theorem Tmn n :\n    Tm n.+1 = n.+2 ^ m - n.+2.\n  Proof.\n    elim: n => [|n IHn] /=.\n      by apply Tm1.\n    have Hm': m > 0 by apply ltnW.\n    have ->: n.+3 ^ m - n.+3 = n.+2 ^ m - n.+2 + (n.+3 ^ m - 1 - n.+2 ^ m).\n    (* 追加ここから *)\n      rewrite addnC addnBA.\n      - rewrite subnK.\n        + by rewrite -subnDA addnC addn1.\n        + rewrite -[n.+3]addn1 Pascal.\n          rewrite -(@big_mkord _ 0 addn m.+1 (fun n => true) (fun i => 'C(m, i) * (n.+2 ^ (m - i) * 1 ^ i))).\n          rewrite big_nat_recl; last by apply: ltnW.\n          rewrite bin0 subn0 expn0 mul1n muln1 -{1}[n.+2 ^ m]addn0.\n          rewrite -{3}[m]prednK; last by apply: (@ltn_trans 1 0 m).\n          rewrite big_nat_recr /=.\n          * rewrite prednK; last by apply: (@ltn_trans 1 0 m).\n            rewrite binn exp1n subnn expn0 !mul1n addnA addn1 subn1 PeanoNat.Nat.pred_succ.\n            by rewrite leq_add2l.\n          * rewrite leq_eqVlt; apply/orP; right.\n            by rewrite -(@ltn_add2r 1) add0n addn1 prednK; last by apply: (@ltn_trans 1 0 m).\n      - rewrite -[n.+2]addn1 Pascal.\n        rewrite -(@big_mkord _ 0 addn m.+1 (fun n => true) (fun i => 'C(m, i) * (n.+1 ^ (m - i) * 1 ^ i))).\n        rewrite big_nat_recr /=.\n        + rewrite binn exp1n subnn expn0 !mul1n.\n          rewrite -{1}[m]prednK; last by apply: (@ltn_trans 1 0 m).\n          rewrite big_nat_recr /=.\n          * rewrite -{4}[m]prednK; last done.\n            rewrite binSn prednK; last done.\n            rewrite -subn1 subKn; last done.\n            rewrite expn1 exp1n muln1.\n            rewrite -{4}[m]prednK; last done.\n            rewrite -[m.-1.+1]addn1 mulnDl mul1n -addnA -[_ + n.+1 + 1]addnA addnA.\n            rewrite -{1}[n.+1 + 1]add0n (@leq_add2r (n.+1 + 1)).\n            by [].\n          * rewrite leq_eqVlt; apply/orP; right.\n            by rewrite -(@ltn_add2r 1) add0n addn1 prednK; last by apply: (@ltn_trans 1 0 m).\n        + by apply: ltnW.\n    (*\n      この時点でゴールは次の形になっている。\n      m : nat\n      Hm : 1 < m\n      n : nat\n      IHn : Tm n.+1 = n.+2 ^ m - n.+2\n      Hm' : 0 < m\n      ______________________________________(1/1)\n      Tm n.+2 = n.+2 ^ m - n.+2 + (n.+3 ^ m - 1 - n.+2 ^ m)\n    *)\n    rewrite -IHn /Tm /Sk.\n    (*\n        \\sum_(1 <= k < m) 'C(m, k) * (\\sum_(1 <= i < n.+3) i ^ k)\n      = \\sum_(1 <= k < m) 'C(m, k) * (\\sum_(1 <= i < n.+2) i ^ k + n.+2 ^ k)\n      = \\sum_(1 <= k < m) 'C(m, k) * \\sum_(1 <= i < n.+2) i ^ k +\n        \\sum_(1 <= k < m) 'C(m, k) * n.+2 ^ k\n\n        \\sum_(1 <= k < m) 'C(m, k) * n.+2 ^ k\n      = 'C(m, 1)    * n.+2 ^ 1 +\n        ... +\n        'C(m, m.-1) * n.+2 ^ m.-1\n\n        n.+3 ^ m - 1 - n.+2 ^ m\n      = n.+3 ^ m - 1 - n.+2 ^ m\n      = (n.+2 + 1) ^ m - 1 - n.+2 ^ m\n    *)\n    have -> : n.+3 ^ m - 1 - n.+2 ^ m = \\sum_(1 <= k < m) 'C(m, k) * n.+2 ^ k.\n      rewrite -[n.+3]addn1 addnC.\n      rewrite Pascal.\n      rewrite -(@big_mkord _ 0 addn m.+1 (fun n => true) (fun i => 'C(m, i) * (1 ^ (m - i) * n.+2 ^ i))).\n      rewrite big_nat_recr /=; last done.\n      rewrite binn exp1n !mul1n.\n      rewrite big_ltn; last done.\n      rewrite bin0 exp1n !mul1n expn0 [1 + _]addnC -addnA -subnDA -subnBA; last done.\n      rewrite subnn subn0.\n      apply: eq_big_nat => i H.\n      by rewrite exp1n mul1n.\n    rewrite -big_split /=.\n    apply: congr_big; first done; first done.\n    by move=> i _; rewrite -mulnDr -big_nat_recr.\n    (* 追加ここまで *)\n  Qed.\n\n  Lemma lm_bin p k :\n    2 < p ->\n    1 <= k < p.-1 ->\n    prime p ->\n    ~~(p %| 'C(p.-1, k)).\n    (*\n      pが3以上の素数であり、\n      kが1以上p-1未満であるなら、\n      'C(p-1, k)はpで割り切れない。\n    *)\n  Proof.\n    move=> Hpgt2 /andP [Hkgt0 Hkltpredp] Hprmp.\n    rewrite bin_factd.\n    - rewrite -prime_coprime; last done.\n      apply/coprimeP; first by apply: (@ltn_trans 2).\n      exists (((p.-1)`!.+1) %/ p, k`! * (p.-1 - k)`!) => /=.\n      rewrite divnK.\n      + rewrite mulnC divnK.\n        * rewrite -addn1 addnC -addnBA; last done.\n          by rewrite subnn.\n        * rewrite -(@bin_fact p.-1 k).\n          -- by apply: dvdn_mull.\n          -- by rewrite leq_eqVlt; apply/orP; right.\n      + by move: (Hprmp); rewrite Wilson; last by apply: (@ltn_trans 2).\n    - by apply: (@ltn_trans k).\n  Qed.\n\n  Lemma lm_evn_p p :\n    p > 2 ->\n    prime p ->\n    odd p.-1 = false.\n    (*\n      pが3以上の素数なら、\n      p-1は奇数ではない。\n    *)\n  Proof.\n    move=> Hpgt2 => /even_prime [Hpeq2 | Hoddp].\n    - by rewrite Hpeq2 in Hpgt2.\n    - apply: negbTE.\n      rewrite -oddS.\n      rewrite prednK; first done.\n      by apply: (@ltn_trans 2 0 p).\n  Qed.\n\n  Lemma lm_div_p_tmpp_pp p :\n    p > 2 ->\n    \\sum_(1 <= k < p.-1) 'C(p.-1, k) * Sk k p.-1 = p ^ p.-1 - p ->\n    p %| \\sum_(1 <= k < p.-1) 'C(p.-1, k) * Sk k p.-1.\n    (*\n      pが3以上で、\n      \\sum_(1 <= k < p.-1) 'C(p.-1, k) * Sk k p.-1 = p ^ p.-1 - pなら、\n      \\sum_(1 <= k < p.-1) 'C(p.-1, k) * Sk k p.-1はpで割り切れる。(当たり前)\n    *)\n  Proof.\n    move=> Hpgt2 ->.\n    apply: dvdn_sub; last done.\n    apply: dvdn_exp; last done.\n    rewrite ltn_predRL.\n    by apply: (@ltn_trans 2 1 p).\n  Qed.\n\n  Lemma lm_div_3_tm2_2 :\n    3 %| \\sum_(1 <= k < 2) 'C(2, k) * Sk k 2.\n    (*\n      \\sum_(1 <= k < 2) 'C(2, k) * Sk k 2は3で割り切れる。\n    *)\n  Proof.\n    rewrite big_nat1 bin1 /Sk.\n    have -> : (2 * \\sum_(1 <= i < 3) i ^ 1) = 2 * 3.\n      rewrite big_ltn; last done.\n      rewrite big_ltn; last done.\n      by rewrite big_nil !expn1 addn0.\n    by apply: dvdn_mull.\n  Qed.\n\n  Lemma lm_div_3_tm2_2' :\n    3 %| Sk 1 2.\n    (*\n      Sk 1 2は3で割り切れる。(定理Skpでp=3の場合)\n    *)\n  Proof.\n    move: lm_div_3_tm2_2.\n    rewrite big_ltn; last done.\n    rewrite big_nil addn0.\n    have H : ~~ (3 %| 'C(2, 1)) by apply: (lm_bin 3 1).\n    rewrite Euclid_dvdM; last done.\n    by move/orP; case.\n  Qed.\n\n  Lemma lm_sum_0_to_n n :\n    2 * (\\sum_(0 <= i < n.+1) i ^ 1) = n * n.+1.\n    (*\n      1からnまでの和は、n*(n+1)/2に等しい。\n    *)\n  Proof.\n    elim: n => [| n IHn].\n    - rewrite big_ltn; last done.\n      rewrite expn1 add0n.\n      by rewrite big_geq; last done.\n    - rewrite big_nat_recr /=; last done.\n      by rewrite mulnDr expn1 IHn -mulnDl addn2 mulnC.\n  Qed.\n\n  Lemma lm_div_p_tmpp_pp' p :\n    p > 2 ->\n    prime p ->\n    p %| \\sum_(1 <= k < p.-1) 'C(p.-1, k) * Sk k p.-1 ->\n    (p %| \\sum_(1 <= k < 2) 'C(p.-1, k) * Sk k p.-1)\n    /\\ (p %| \\sum_(2 <= k < p.-1) 'C(p.-1, k) * Sk k p.-1).\n    (*\n      pが3以上の素数で、\n      \\sum_(1 <= k < p.-1) 'C(p.-1, k) * Sk k p.-1がpで割り切れるなら、\n      \\sum_(1 <= k < 2) 'C(p.-1, k) * Sk k p.-1と\n      \\sum_(2 <= k < p.-1) 'C(p.-1, k) * Sk k p.-1は\n      ともにpで割り切れる。\n    *)\n  Proof.\n    move=> Hpgt2 Hprmp.\n    rewrite big_ltn; last by rewrite ltn_predRL.\n    rewrite bin1.\n    rewrite -{1}(@odd_double_half p.-1) lm_evn_p; last done; last done.\n    rewrite -muln2 -mulnA /Sk prednK; last  by apply: (@ltn_trans 2 0 p).\n    have H : 2 * (\\sum_(1 <= i < p) i ^ 1) = p.-1 * p.\n      move: (lm_sum_0_to_n p.-1).\n      rewrite prednK; last by apply: (@ltn_trans 2 0 p).\n      rewrite big_ltn; last by apply: (@ltn_trans 2 0 p).\n      by rewrite expn1 add0n.\n    rewrite H mulnA.\n    move/dvdn_add_eq.\n    rewrite dvdn_mull; last done.\n    move=> <-.\n    rewrite big_ltn; last done.\n    rewrite bin1 -{1}(@odd_double_half p.-1) lm_evn_p; last done; last done.\n    by rewrite -muln2 -mulnA /Sk H mulnA big_nil addn0 dvdn_mull.\n  Qed.\n\n  Lemma lm_div_p_tmpp_pp'' p :\n    p > 2 ->\n    prime p ->\n    m = p.-1 ->\n    p %| \\sum_(1 <= k < m) 'C(m, k) * Sk k p.-1.\n    (*\n      pが3以上の素数であり、\n      m=p-1なら、\n      \\sum_(1 <= k < m) 'C(m, k) * Sk k p.-1はpで割り切れる。\n    *)\n  Proof.\n    move=> Hpgt2 Hprmp Hmeqprdp.\n    move: (Tmn p.-2).\n    rewrite prednK /Tm.\n    - move=> ->.\n      rewrite prednK; last by apply: (@ltn_trans 2 0 p).\n      apply: dvdn_sub; last done.\n      rewrite dvdn_exp; first done; last done.\n      by apply: (@ltn_trans 1 0 m).\n    - rewrite -Hmeqprdp.\n      by apply: (@ltn_trans 1 0 m).\n  Qed.\n\n  Theorem Skp p k :\n    p > 2 ->\n    prime p ->\n    1 <= k < p.-1 ->\n    p %| Sk k p.-1.\n    (*\n      pが3以上の素数のとき、\n      Sk(p-1) (1 <= k <= p-2)はpの倍数である。\n    *)\n  Proof.\n    (* 追加ここから *)\n    (* 追加ここまで *)\n  Admitted.\n\nEnd Nagoya2013.\n", "meta": {"author": "wakaba2017", "repo": "ProofCafe", "sha": "f2dd32225e2a9ed38577621e228d0adc1e1cd0b5", "save_path": "github-repos/coq/wakaba2017-ProofCafe", "path": "github-repos/coq/wakaba2017-ProofCafe/ProofCafe-f2dd32225e2a9ed38577621e228d0adc1e1cd0b5/ssrcoq9-self_learning.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6600625521695578}}
{"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 Coq_Cats.Type_Cat.Type_Cat.\n\n(** A cardinality restriction for types is a property that holds for a type\n    if and only if it holds for all types isomorphic to it. *)\nRecord Card_Restriction : Type :=\n{\n  Card_Rest : Type → Prop;\n\n  Card_Rest_Respect : ∀ (A B : Type),\n      (A ≃≃ B ::> Type_Cat)%isomorphism → Card_Rest A → Card_Rest B\n}.\n\nCoercion Card_Rest : Card_Restriction >-> Funclass.\n\n(** A type is finite if it is isomorphic to a subset of natural numbers\n    less than n for soem natural number n. *)\nProgram Definition Finite : Card_Restriction :=\n  {|\n    Card_Rest :=\n      fun A => inhabited {n : nat & (A ≃≃ {x : nat | x < n} ::> Type_Cat)%isomorphism}\n  |}.\n\nNext Obligation.\nProof.\n  destruct H as [[n I]].\n  eexists.\n  refine (existT _ n (I ∘ (X⁻¹)%isomorphism)%isomorphism).\nQed.\n", "meta": {"author": "amintimany", "repo": "Categories", "sha": "1839108875df0107fa4f6061c654003decda2d49", "save_path": "github-repos/coq/amintimany-Categories", "path": "github-repos/coq/amintimany-Categories/Categories-1839108875df0107fa4f6061c654003decda2d49/Coq_Cats/Type_Cat/Card_Restriction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.6600147569754278}}
{"text": "Require Export ImpList_J.\n\nDefinition Assertion := state -> Prop.\n\n\nDefinition hoare_triple (P: Assertion) (c: com) (Q: Assertion): Prop :=\n  forall st st',\n    c / st || st' ->\n    P st ->\n    Q st'.\n\nNotation \"{{ P }} c\" := (hoare_triple P c (fun st => True)) (at level 90): hoare_spec_scope.\nNotation \"{{ P }} c {{ Q }}\" := (hoare_triple P c Q) (at level 90, c at next level): hoare_spec_scope.\n\nOpen Scope hoare_spec_scope.\n\nTheorem hoare_post_true: forall (P Q: Assertion) c,\n                           (forall st, Q st) ->\n                           {{P}} c {{Q}}.\nProof.\n  intros P Q c H. unfold hoare_triple.\n  intros st st' Heval Hp.\n  apply H.\nQed.\n\nTheorem hoare_pre_false: forall (P Q: Assertion) c,\n                           (forall st, ~(P st)) ->\n                           {{P}} c {{Q}}.\nProof.\n  intros P Q c H.\n  unfold hoare_triple.\n  intros st st' Heval Hpre.\n  apply H in Hpre.\n  inversion Hpre.\nQed.\n\nDefinition assn_sub V a Q: Assertion :=\n  fun (st: state) =>\n    Q (update st V (aeval st a)).\n\nTheorem hoare_asgn: forall Q V a,\n                      {{assn_sub V a Q}} (V ::= a) {{Q}}.\nProof.\n  unfold hoare_triple.\n  intros Q V a st st' HE HQ.\n  unfold assn_sub in HQ.\n  inversion HE.\n  subst.\n  assumption.\nQed.\n\nExample assn_sub_example :\n  {{fun st => 3 = 3}}\n    (X ::= (ANum 3))\n    {{fun st => asnat (st X) = 3}}.\nProof.\n  assert ((fun st => 3 = 3) = (assn_sub X (ANum 3) (fun st => asnat (st X) = 3))).\n  unfold assn_sub. reflexivity.\n  rewrite -> H.\n  apply hoare_asgn.\nQed.\n\nTheorem hoare_asgn_eq: forall Q Q' V a,\n                         Q' = assn_sub V a Q ->\n                         {{Q'}} (V ::= a) {{Q}}.\nProof.\n  intros Q Q' V a H.\n  rewrite H. apply hoare_asgn.\nQed.\n\nExample assn_sub_example':\n  {{fun st => 3 = 3}}\n    (X ::= (ANum 3))\n    {{fun st => asnat (st X) = 3}}.\nProof.\n  apply hoare_asgn_eq. reflexivity.\nQed.\n\nTheorem hoare_asgn_weakest: forall P V a Q,\n                              {{P}} (V ::= a) {{Q}} ->\n                              forall st, P st -> assn_sub V a Q st.\nProof.\n  intros P V a Q Has st HE.\n  unfold hoare_triple in Has.\n  unfold assn_sub.\n  apply Has with (st := st).\n  apply E_Asgn.\n  reflexivity.\n  assumption.\nQed.\n\n\nTheorem hoare_consequence: forall (P P' Q Q': Assertion) c,\n                             {{P'}} c {{Q'}} ->\n                             (forall st, P st -> P' st) ->\n                             (forall st, Q' st -> Q st) ->\n                             {{P}} c {{Q}}.\nProof.\n  intros P P' Q Q' c H HPP' HQ'Q.\n  intros st st' Hc HP.\n  apply HQ'Q. apply (H st st'). assumption.\n  apply HPP'. assumption.\nQed.\n\nTheorem hoare_consequence_pre: forall (P P' Q: Assertion) c,\n                                 {{P'}} c {{Q}} ->\n                                 (forall st, P st -> P' st) ->\n                                 {{P}} c {{Q}}.\nProof.\n  intros P P' Q c H HPP'.\n  apply hoare_consequence with (P' := P') (Q' := Q); try assumption.\n  intros st H'. apply H'.\nQed.\n\nTheorem hoare_consequence_post: forall (P Q' Q: Assertion) c,\n                                  {{P}} c {{Q'}} ->\n                                  (forall st, Q' st -> Q st) ->\n                                  {{P}} c {{Q}}.\nProof.\n  intros P Q' Q c H HQQ'.\n  apply hoare_consequence with (P' := P) (Q' := Q'); try assumption.\n  + intros st H'. apply H'.\nQed.\n\nExample hoare_asgn_example1:\n  {{fun st => True}} (X ::= (ANum 1)) {{fun st => asnat (st X) = 1}}.\nProof.\n  apply hoare_consequence_pre with (P' := (fun st => 1 = 1)).\n  apply hoare_asgn_eq. reflexivity.\n  intros st H. reflexivity.\nQed.\n\nExample hoare_asgn_example1' :\n  {{fun st => True}}\n    (X ::= (ANum 1))\n    {{fun st => asnat (st X) = 1}}.\nProof.\n  eapply hoare_consequence_pre.\n  apply hoare_asgn_eq. reflexivity.\n  intros st H. reflexivity.\nQed.\n\nTheorem hoare_skip: forall P,\n                      {{P}} SKIP {{P}}.\nProof.\n  intros P st st' H HP.\n  inversion H.\n  subst. assumption.\nQed.\n\nTheorem hoare_seq: forall P Q R c1 c2,\n                     {{Q}} c2 {{R}} ->\n                     {{P}} c1 {{Q}} ->\n                     {{P}} c1;c2 {{R}}.\nProof.\n  intros P Q R c1 c2 HQR HPQ.\n  intros st st' H Hp.\n  inversion H. subst. clear H.\n  apply (HQR st'0 st'); try assumption.\n  apply (HPQ st st'0); try assumption.\nQed.\n\nExample hoare_asgn_example3: forall a n,\n                               {{fun st => aeval st a = n}}\n                                 (X ::= a; SKIP)\n                                 {{fun st => st X = n}}.\nProof.\n  intros a n. eapply hoare_seq.\n  + apply hoare_skip.\n  + eapply hoare_consequence_pre. apply hoare_asgn.\n    intros st H. subst. reflexivity.\nQed.\n\nExample hoare_asgn_example4:\n  {{fun st => True}} (X ::= (ANum 1); Y ::= (ANum 2))\n               {{fun st => asnat (st X) = 1 /\\ asnat (st Y) = 2}}.\nProof.\n  eapply hoare_seq.\n  apply hoare_asgn.\n  unfold assn_sub.\n  unfold update.\n  simpl.\n  intros st st' H H'.\n  inversion H. subst. simpl.\n  omega.\nQed.\n\nDefinition bassn b: Assertion :=\n  fun st => (beval st b = true).\n\nLemma bexp_eval_true: forall b st,\n                        beval st b = true -> (bassn b) st.\nProof.\n  intros b st H.\n  unfold bassn. assumption.\nQed.\n\nLemma bexp_eval_false: forall b st,\n                         beval st b = false -> ~ ((bassn b) st).\nProof.\n  intros b st H contra.\n  unfold bassn in contra.\n  rewrite contra in H. inversion H.\nQed.\n\nTheorem hoare_if: forall P Q b c1 c2,\n                    {{fun st => P st /\\ bassn b st}} c1 {{Q}}  ->\n                    {{fun st => P st /\\ ~(bassn b st)}} c2 {{Q}} ->\n                    {{P}} (IFB b THEN c1 ELSE c2 FI) {{Q}}.\nProof.\n  intros P Q b c1 c2 HTrue HFalse st st' HE HP.\n  inversion HE; subst.\n  + apply (HTrue st st'). assumption.\n    split. assumption. apply bexp_eval_true. assumption.\n  + apply (HFalse st st'). assumption.\n    split. assumption. apply bexp_eval_false. assumption.\nQed.\n\nExample if_example:\n  {{fun st => True}}\n    IFB (BEq (AId X) (ANum 0))\n    THEN (Y ::= (ANum 2))\n    ELSE (Y ::= (APlus (AId X) (ANum 1)))\n    FI\n    {{fun st => asnat (st X) <= asnat (st Y)}}.\nProof.\n  apply hoare_if.\n  + eapply hoare_consequence_pre. apply hoare_asgn.\n    unfold bassn, assn_sub, update.  simpl. intros.\n    inversion H. symmetry in H1; apply beq_nat_eq in H1.\n    rewrite H1. omega.\n  +\n    eapply hoare_consequence_pre. apply hoare_asgn.\n    unfold assn_sub, update; simpl; intros. omega.\nQed.\n\nLemma hoare_while: forall P b c,\n                     {{fun st => P st /\\ bassn b st}} c {{P}} ->\n                     {{P}} WHILE b DO c END {{fun st => P st /\\ ~ (bassn b st)}}.\nProof.\n  intros P b c Hhoare st st' He HP.\n  remember (WHILE b DO c END) as wocm.\n  ceval_cases (induction He) Case; try (inversion Heqwocm); subst.\n  Case \"E_WhileEnd\".\n  split. assumption. apply bexp_eval_false. assumption.\n  Case \"E_WhileLoop\".\n  apply IHHe2. reflexivity.\n  apply (Hhoare st st'); try assumption.\n  split. assumption. apply bexp_eval_true. assumption.\nQed.\n\nExample while_example:\n  {{fun st => asnat (st X) <= 3}}\n    WHILE (BLe (AId X) (ANum 2))\n    DO X ::= APlus (AId X) (ANum 1) END\n    {{fun st => asnat (st X) = 3}}.\nProof.\n  eapply hoare_consequence_post.\n  apply hoare_while.\n  eapply hoare_consequence_pre.\n  apply hoare_asgn.\n  unfold bassn, assn_sub. intros. rewrite update_eq. simpl.\n  inversion H as [_ H0].simpl in H0. apply ble_nat_true in H0.\n  omega.\n  unfold bassn. intros. inversion H as [Hle Hb]. simpl in Hb.\n  remember (ble_nat (asnat (st X)) 2) as le. destruct le.\n  apply ex_falso_quodlibet. apply Hb. reflexivity.\n  symmetry in Heqle. apply ble_nat_false in Heqle. omega.\nQed.\n\nTheorem always_loop_hoare: forall P Q,\n                             {{P}} WHILE BTrue DO SKIP END {{Q}}.\nProof.\n  intros P Q.\n  apply hoare_consequence_pre with (P' := fun st : state => True).\n  eapply hoare_consequence_post.\n  apply hoare_while.\n  Case \"Loop body preserves invariant\".\n  apply hoare_post_true. intros st. apply I.\n  Case \"Loop invariant and negated guard imply postcondition\".\n  simpl. intros st [Hinv Hguard].\n  apply ex_falso_quodlibet. apply Hguard. reflexivity.\n  Case \"Precondition implies invariant\".\n  intros st H. constructor.\nQed.\n\nTheorem always_loop_hoare': forall P Q,\n                              {{P}} WHILE BTrue DO SKIP END {{Q}}.\nProof.\n  unfold hoare_triple. intros P Q st st' contra.\n  apply loop_never_stops in contra. inversion contra.\nQed.", "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/hore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.6599869027551647}}
{"text": "From Coq Require Import ssreflect ssrbool ssrfun.\nFrom mathcomp Require Import eqtype seq.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection SnocList.\nContext (A : Type).\n\nInductive sseq : Type :=\n\tsnil : sseq | snoc : sseq -> A -> sseq.\n\nFixpoint scat s1 s2 := if s2 is snoc s2' x then snoc (scat s1 s2') x else s1.\n\nEnd SnocList.\n\nSection Fun.\n\nFixpoint smap {A B} (f : A -> B) (s : sseq A) : sseq B :=\n  if s is snoc xs x then snoc (smap f xs) (f x) else @snil B.\n\nFixpoint to_seq {A} (s : sseq A) : seq A :=\n  if s is snoc xs x then rcons (to_seq xs) x else [::].\n\nFixpoint from_seq {A} (s : seq A) : sseq A :=\n  if s is x::xs then scat (snoc (@snil A) x) (from_seq xs) else @snil A.\n\nEnd Fun.\n\nSection Eqtype.\nContext {T : eqType}.\n\nFixpoint eq_sseq (t1 t2 : sseq T) :=\n  match t1, t2 with\n  | snil, snil => true\n  | snoc s x, snoc t y => eq_sseq s t && (x == y)\n  | _, _ => false\n  end.\n\nLemma eq_sseqP : Equality.axiom eq_sseq.\nProof.\nmove; elim=> [|s IH x][|t y] /=; try by constructor.\nhave [<-/=|neqx] := x =P y; last by rewrite andbF; apply: ReflectF; case.\nrewrite andbT; apply: (iffP idP).\n- by move/IH=>->.\nby case=><-; apply/IH.\nQed.\n\nCanonical sseq_eqMixin := EqMixin eq_sseqP.\nCanonical sseq_eqType := Eval hnf in EqType (sseq T) sseq_eqMixin.\n\nEnd Eqtype.\n\nSection SnocPred.\nContext (A : Type).\nVariable a : pred A.\n\nFixpoint sall s := if s is snoc s' x then a x && sall s' else true.\n\nFixpoint shas s := if s is snoc s' x then a x || shas s' else false.\n\nEnd SnocPred.\n", "meta": {"author": "clayrat", "repo": "coq-foata", "sha": "258b72f74505e9c2441b4c4b2b6a3dbbf9fb9479", "save_path": "github-repos/coq/clayrat-coq-foata", "path": "github-repos/coq/clayrat-coq-foata/coq-foata-258b72f74505e9c2441b4c4b2b6a3dbbf9fb9479/theories/sseq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.6599868917075334}}
{"text": "Theorem lt_le: forall n p: nat, n < p -> n <= p.\nProof.\nintros n p H.\n\n\nShow.\n(*\n  intros  n p H. unfold lt in H. apply le_S_n. apply le_S. 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/le.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.659986888513657}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*             Ralph Matthes [+]                              *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*                             [+] Affiliation IRIT -- CNRS   *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Omega.\nRequire Import list_utils wf_utils bt bft_forest bft_std bft_inj.\n\nSet Implicit Arguments.\n\nSection bfn_NC. (* necessary conditions *)\n\n  (** We derive equations from the functional spec of BFN:\n\n      the expected output of (bfn_f i l) is \n      a list ln such that l ~lt ln \n                      and is_bfn_from i ln *)\n\n  Variable (X : Type) (bfn_f : nat -> list (bt X) -> list (bt nat))\n           (H0 : forall i l, l ~lt rev (bfn_f i l))\n           (H1 : forall i l, is_bfn_from i (rev (bfn_f i l))).\n\n  Let H0' i l : rev l ~lt bfn_f i l.\n  Proof.\n    apply Forall2_rev_eq.\n    rewrite rev_involutive.\n    apply H0.\n  Qed.\n\n  Fact rev_inj K (l m : list K) : rev l = rev m -> l = m.\n  Proof.\n    intro. \n    rewrite <- (rev_involutive l), <- (rev_involutive m).\n    f_equal; trivial.\n  Qed.\n\n  Theorem bfn_f_eq_0 i : bfn_f i nil = nil.\n  Proof.\n    apply rev_inj.\n    symmetry; apply lbt_is_bfn_from_eq with i; simpl; auto.\n    + apply lbt_eq_trans with (2 := H0 _ _); constructor.\n    + red; rewrite bft_f_fix_0; simpl; constructor.\n  Qed.\n\n  Theorem bfn_f_eq_1 i x l : bfn_f i (leaf x::l) = bfn_f (S i) l ++ leaf i :: nil.\n  Proof.\n    apply rev_inj.\n    rewrite rev_app_distr; simpl.\n    apply lbt_is_bfn_from_eq with i; auto.\n    + apply lbt_eq_sym, lbt_eq_trans with (2 := H0 _ _); repeat constructor.\n      apply lbt_eq_sym, H0.\n    + red; rewrite bft_f_fix_oka_1; simpl.\n      split; auto; apply H1.\n  Qed.\n\n  Theorem bfn_f_eq_2 i a x b l : exists an bn ln,\n               bfn_f (S i) (l++a::b::nil) = bn::an::ln\n            /\\ bfn_f i (node a x b::l) = ln ++ node an i bn :: nil.\n  Proof.\n    generalize (H0 (S i) (l++a::b::nil)); intros H.\n    apply Forall2_rev in H.\n    rewrite rev_involutive, rev_app_distr in H.\n    simpl in H; revert H.\n    case_eq (bfn_f (S i) (l ++ a :: b :: nil)).\n    { inversion 2. }\n    intros bn ln E H.\n    apply Forall2_cons_inv in H.\n    destruct H as (H2 & H).\n    destruct ln as [ | an ln ].\n    { inversion H. }\n    apply Forall2_cons_inv in H.\n    destruct H as (H3 & H4).\n    exists an, bn, ln; split; auto.\n    apply rev_inj.\n    apply lbt_is_bfn_from_eq with i; auto.\n    + apply lbt_eq_sym, lbt_eq_trans with (2 := H0 _ _), lbt_eq_sym.\n      rewrite rev_app_distr.\n      simpl; repeat constructor; auto.\n      apply Forall2_rev_eq.\n      rewrite rev_involutive; auto.\n    + red; rewrite rev_app_distr; simpl. \n      rewrite bft_f_fix_oka_2; simpl.\n      split; auto.\n      generalize (H1 (S i) (l++a::b::nil)).\n      rewrite E; simpl.\n      rewrite app_ass; simpl; auto.\n  Qed.\n\nEnd bfn_NC.\n\nSection bfn_SC. (* sufficient conditions, synthesis *)\n\n  (* Assuming [bfn_f] satisfies the previous equations, \n     then [bfn_f] satisfies the functional spec of BFN *)\n     \n  Variable (X : Type) (bfn_f : nat -> list (bt X) -> list (bt nat))\n           (H0 : forall i, bfn_f i nil = nil)\n           (H1 : forall i x l, bfn_f i (leaf x::l) = bfn_f (S i) l ++ leaf i :: nil)\n           (H2 : forall i a x b l, exists an bn ln,\n                bfn_f (S i) (l++a::b::nil) = bn::an::ln\n             /\\ bfn_f i (node a x b::l) = ln ++ node an i bn :: nil).\n\n  Theorem bfn_f_lt i l : l ~lt rev (bfn_f i l).\n  Proof.\n    induction on i l as IH with measure (lsum l).\n    destruct l as [ | [ x | a x b ] l ].\n    + rewrite H0; constructor.\n    + rewrite H1, rev_app_distr; simpl. \n      repeat constructor.\n      apply IH; simpl; omega.\n    + destruct (H2 i a x b l) as (an & bn & ln & H3 & H4).\n      rewrite H4, rev_app_distr; simpl.\n      assert (lsum (l++a::b::nil) < lsum (node a x b :: l)) as D.\n      { rewrite lsum_app; simpl; omega. }\n      generalize (IH (S i) _ D); rewrite H3.\n      simpl; rewrite app_ass; simpl; intros H5.\n      apply Forall2_2snoc_inv in H5; destruct H5 as (? & ? & ?).\n      repeat constructor; assumption.\n  Qed.\n\n  Theorem bfn_f_bfn i l : is_bfn_from i (rev (bfn_f i l)).\n  Proof.\n    induction on i l as IH with measure (lsum l).\n    destruct l as [ | [ x | a x b ] l ].\n    + rewrite H0; red; rewrite bft_f_fix_0; simpl; constructor.\n    + rewrite H1, rev_app_distr; simpl; red.\n      rewrite bft_f_fix_oka_1; split; auto.\n      apply IH; simpl; omega.\n    + destruct (H2 i a x b l) as (an & bn & ln & H3 & H4).\n      rewrite H4, rev_app_distr; simpl; red.\n      rewrite bft_f_fix_oka_2; split; auto.\n      replace (rev ln++an::bn::nil) with (rev (bn::an::ln)).\n      * rewrite <- H3; apply IH.\n        rewrite lsum_app; simpl; omega.\n      * simpl; rewrite app_ass; auto.\n  Qed.\n\nEnd bfn_SC.\n\n", "meta": {"author": "DmxLarchey", "repo": "BFE", "sha": "0bf8376a80ca4378be1630689f6561744d43474e", "save_path": "github-repos/coq/DmxLarchey-BFE", "path": "github-repos/coq/DmxLarchey-BFE/BFE-0bf8376a80ca4378be1630689f6561744d43474e/coq/bfn_spec_rev.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528132451416, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6599085020986981}}
{"text": "Require Export XR_Rplus_0_r.\nRequire Export XR_Rle_lt_trans.\nRequire Export XR_Rplus_le_compat_l.\n\nLocal Open Scope R_scope.\n\nLemma Rplus_lt_reg_pos_r : forall r1 r2 r3,\n  R0 <= r2 ->\n  r1 + r2 < r3 ->\n  r1 < r3.\nProof.\n  intros x y z.\n  intros hy h.\n  apply Rle_lt_trans with (x+y).\n  {\n    pattern x at 1;rewrite <- Rplus_0_r.\n    apply Rplus_le_compat_l.\n    exact hy.\n  }\n  { exact h. }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rplus_lt_reg_pos_r.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6599084903206335}}
{"text": "From mathcomp Require Import ssreflect.\nRequire Import NPeano ZArith.\nFrom Coquelicot Require Import Coquelicot.\nRequire Import Reals Field Psatz Plouffe.\nRequire Export String.\n\n(******************************************************************************)\n(*                                                                            *)\n(*     COMPUTING HEXADECIMAL DIGITS OF PI WITH THE PLOUFFE FORMULA            *)\n(*                                                                            *)\n(******************************************************************************)\n\nLtac tlra := try lra.\nLtac tlia := try lia.\n\nNotation \"a %:R \" := (INR a) (at level 10).\n\nOpen Scope nat_scope.\n\n(******************************************************************************)\n(* Some theorems for nat                                                      *)\n\nLemma le_minus_0 a b : a <= b -> a - b = 0.\nProof.  by elim: a b => //= n IH [|b] //; tlia. Qed.\n\nLemma Ndiv_minus a b c : 0 < c -> (a - b * c) / c = a / c - b.\nProof.\nmove=> Pc.\ncase: (le_lt_dec (b * c) a) => Labc; last first.\n  rewrite !le_minus_0; tlia.\n    by rewrite Nat.div_0_l; lia.\n  by apply: Nat.div_le_upper_bound; lia.\nby rewrite -{2}(Nat.sub_add (b * c) a) // Nat.div_add; lia.\nQed.\n\nLemma mod_minus_mult a b c : 0 < c -> b * c <= a -> (a - b * c) mod c = a mod c.\nProof.\nmove=> Pp Lbca.\nby rewrite -{2}(Nat.sub_add (b * c) a) // Nat.mod_add; lia.\nQed.\n\nLemma pow_mod a b n :\n  (0 < n -> (a ^ b) mod n = (a mod n) ^ b mod n)%nat.\nProof.\nmove=> Pn; elim: b => //= b IH.\nrewrite Nat.mul_mod ?IH; tlia.\nby rewrite Nat.mul_mod_idemp_r; lia.\nQed.\n\nLemma mod_between (a b c1 c2 m n : nat) :\n (0 <= c1 <= c2  -> m < n -> c2 < b ^ m -> 1 < b ->\n  ((a + c2) mod (b ^n) / (b ^ m) = a mod (b ^n) / (b ^ m)) ->\n  ((a + c1) mod (b ^n) / (b ^ m) = a mod (b ^n) / (b ^ m))).\nProof.\nmove=> Lc1c2 Lmn Ldbm Pb Eac2ab.\nhave F0 : b ^ m < b ^ n by apply: Nat.pow_lt_mono_r .\nhave F1 : 2 * b ^ m <= b ^ n.\n  apply: le_trans (_ : b ^ (1 + m) <= b ^ n).\n    rewrite Nat.pow_add_r Nat.pow_1_r.\n    by apply: mult_le_compat_r; lia.\n  by apply: Nat.pow_le_mono_r; lia.\npose x := a mod (b ^ n).\nhave F2 : x < b ^ n by apply: Nat.mod_upper_bound; lia.\ncase: (le_lt_dec (b ^ n) (x + c2)) => Lbnxc2.\n  have F3 : (a + c2) mod b ^ n = x + c2 - b ^ n.\n    rewrite Nat.add_mod -/x; tlia.\n    rewrite [c2 mod _]Nat.mod_small; tlia.\n    rewrite -(Nat.sub_add (b ^ n) (x + c2)) //.\n    rewrite Nat.add_mod ?Nat.mod_same; tlia.\n    rewrite plus_0_r Nat.mod_mod; tlia.\n    rewrite Nat.mod_small; lia.\n  have F4 : a mod b ^ n / b ^ m = 0.\n    by rewrite -Eac2ab F3 Nat.div_small //; lia.\n  have: b ^ m / b ^ m <= x / b ^ m.\n    apply: Nat.div_le_mono; lia.\n  by rewrite F4 Nat.div_same; lia.\nhave ->: (a + c1) mod b ^ n  = x + c1.\n  rewrite Nat.add_mod -/x; tlia.\n  rewrite [c1 mod _]Nat.mod_small; tlia.\n  by rewrite Nat.mod_small; lia.\nrewrite -/x; apply: le_antisym.\n  rewrite -Eac2ab.\n  have ->: (a + c2) mod b ^ n  = x + c2.\n    rewrite Nat.add_mod -/x; tlia.\n    rewrite [c2 mod _]Nat.mod_small; tlia.\n    by rewrite Nat.mod_small; lia.\n  by apply: Nat.div_le_mono; lia.\nby apply: Nat.div_le_mono; lia.\nQed.\n\n(******************************************************************************)\n\nOpen Scope Z_scope.\n\n(* Some theorems from Z *)\n\nRequire Import ZArith.\n\nLemma pow_Zpower a b : \n   Z.of_nat (a ^ b) =  (Z.of_nat a ^ Z.of_nat b)%Z.\nProof.\nrewrite -Zpower_nat_Z.\nelim: b => //= n IH.\nby rewrite -IH Nat2Z.inj_mul.\nQed.\n\n\n(******************************************************************************)\n\nOpen Scope R_scope.\n\n(* Some theorems from R *)\n\nLemma Rinv_le_0_compat x : 0 < x -> 0 <= / x.\nProof.\nmove=> Px.\nhave->: / x = 1 / x by rewrite /Rdiv Rmult_1_l.\napply: Rdiv_le_0_compat; lra.\nQed.\n\nLemma sum_f_R0_plus_r (f : nat -> R) m n :\n  sum_f_R0 f (S (m +  n)) = \n      sum_f_R0 f m + sum_f_R0 (fun n => f (S m + n)%nat) n. \nProof.\nelim: n m f => [m f | n IH m f]; first by rewrite /= plus_0_r.\nrewrite Nat.add_succ_r decomp_sum; tlia.\nrewrite [pred _]/= IH -Rplus_assoc -(decomp_sum _ (S m)); tlia.\nrewrite [sum_f_R0 _ (S n)]decomp_sum; tlia.\nrewrite /= plus_0_r -!Rplus_assoc.\ncongr (_ + _ + _).\nby apply: sum_eq => i _;rewrite Nat.add_succ_r.\nQed.\n\nLemma approx_divR a b : (0 < b)%nat -> 0 <= a%:R / b%:R - (a / b)%:R < 1.\nProof.\nmove=> bP.\nhave bPR : 0 < b%:R by apply: lt_0_INR.\nhave ->: 1 = (/ b%:R) * b%:R by field; lra.\nhave ->: a%:R / (b) %:R - (a / b) %:R = (/ b%:R) * (a%:R - (a / b * b)%:R).\n  rewrite mult_INR; field; lra.\nhave ibPR : 0 < /b%:R by apply: Rinv_0_lt_compat.\nsplit.\n  apply: Rmult_le_pos; tlra.\n  suff: (a / b * b) %:R <= a%:R by lra.\n  apply: le_INR.\n  rewrite mult_comm {2}(Nat.div_mod a b); lia.\napply: Rmult_lt_compat_l; tlra.\nsuff: a%:R < (a / b * b + b) %:R by rewrite plus_INR; lra.\napply: lt_INR.\nrewrite {1}(Nat.div_mod a b); tlia.\nrewrite mult_comm.\nsuff :  (a mod b < b)%nat by lia.\napply: Nat.mod_upper_bound; lia.\nQed.\n\nLemma pow_INR a n : (a ^ n)%:R = a%:R ^ n.\nProof. by elim: n => //= n; rewrite mult_INR => ->. Qed.\n\nLemma Int_part_IZR z : Int_part (IZR z) = z.\nProof.\nsuff : (z + 1 = up (IZR z))%Z by rewrite /Int_part; lia.\nby apply: tech_up; rewrite plus_IZR /=; lra.\nQed.\n\nLemma frac_part_IZR z : frac_part (IZR z) = 0.\nProof. by rewrite /frac_part Int_part_IZR; lra. Qed.\n\nLemma le_Int_part a b : a <= b -> (Int_part a <= Int_part b)%Z.\nProof.\nmove=> aLb.\nhave Fa := base_Int_part a.\nhave Fb := base_Int_part b.\nhave : IZR(Int_part a) < IZR(Int_part b) + 1; tlra.\nby rewrite -(plus_IZR _ 1) => /lt_IZR; lia.\nQed.\n\nLemma le_Int_part_pos a : 0 <= a -> (0 <= Int_part a)%Z.\nProof.\nmove=> aLb; rewrite -(Int_part_IZR 0).\nby apply: le_Int_part.\nQed.\n\nLemma Int_part_INR b c : (0 < c)%nat ->\n  (Int_part (b * c%:R) / (Z.of_nat c) = Int_part b)%Z.\nProof.\nmove=> Pc.\nhave ZPc : (0 < Z.of_nat c)%Z by apply: (inj_lt 0).\nrewrite {1}[b](_ : b = IZR (Int_part b) + frac_part b); last first.\n  by rewrite /frac_part; lra.\nrewrite Rmult_plus_distr_r {1}INR_IZR_INZ -mult_IZR  plus_Int_part2; last first.\n  by rewrite frac_part_IZR; have := base_fp (frac_part b * c %:R); lra.\nrewrite Int_part_IZR Z.div_add_l; tlia.\nrewrite Z.div_small; tlia; split.\n  change 0%Z with (Z.of_nat 0).\n  rewrite -Int_part_INR; apply: le_Int_part.\n  apply: Rmult_le_pos; first by have := base_fp b; lra.\n  by apply: (le_INR 0); lia.\napply: lt_IZR; rewrite -INR_IZR_INZ.\nhave [Fa _] := base_Int_part (frac_part b * c %:R).\napply: Rle_lt_trans Fa _.\nrewrite -{2}[_%:R]Rmult_1_l.\napply: Rmult_lt_compat_r; first by apply: (lt_INR 0).\nby have [] := base_fp b.\nQed.\n\n\nDefinition Rdigit (b : nat) (d : nat) (r : R) :=\n   (Z.to_nat (Int_part ((Rabs r) * (b%:R ^ d))) mod b)%nat.\n\nLemma RdigitS b d r : Rdigit b d (r * b%:R) = Rdigit b (S d) r.\nProof.\nrewrite /Rdigit Rabs_mult (Rabs_pos_eq _ (pos_INR _)) /=.\nby rewrite Rmult_assoc.\nQed.\n\nLemma Rdigit_shift b d r n :\n  Rdigit b d (r * (b%:R ^ n)) = Rdigit b (n + d) r.\nProof.\nelim: n r => [r | n IH r] /=; first by rewrite Rmult_1_r.\nby rewrite -Rmult_assoc IH RdigitS.\nQed.\n\nLemma Rdigit_mod_div b r k n : (0 < b)%nat ->\n   Rdigit (b ^ n) 1 r  = \n   ((Z.to_nat (Int_part ((Rabs r) * b%:R ^ (k + n)))) \n         mod (b ^ (k + n)) / (b ^ k))%nat.\nProof.\nmove=> Pb.\nhave F0 m : (0 < b ^ m)%nat.\n  suff : (1 ^ m <= b ^ m)%nat by rewrite Nat.pow_1_l; lia.\n  apply: Nat.pow_le_mono_l; lia.\nhave F1 m : (0 <= Int_part (Rabs r * b %:R ^ m))%Z.\n  apply: le_Int_part_pos.\n  by repeat (apply: Rmult_le_pos || apply: Rabs_pos || apply: pow_le\n             || apply: pos_INR).\nhave F2 := inj_lt  _ _ (F0 (k + n)%nat).\nrewrite -[(_ mod _)%nat]Nat2Z.id Zdiv.mod_Zmod; last first.\n  have := F0 (k + n)%nat; lia.\nrewrite Z2Nat.id //.\nrewrite Zdiv.Zmod_eq; tlia.\nrewrite Z2Nat.inj_sub; last first.\n  apply: Zmult_gt_0_le_0_compat; tlia.\n  by apply: Z_div_pos; tlia.\nrewrite Z2Nat.inj_mul; tlia; last first.\n  by apply: Z_div_pos; tlia.\nrewrite Nat2Z.id -pow_INR Int_part_INR; tlia.\nrewrite (_ : (b ^ (k + n) = b ^ n * b ^ k)%nat) //; last first.\n  by rewrite Nat.pow_add_r mult_comm.\nrewrite Nat.mul_assoc Ndiv_minus //.\nrewrite mult_INR -Rmult_assoc.\nrewrite -(Int_part_INR (Rabs r) (b ^ n)) //.\nrewrite -[X in (_ = X - _)%nat]Nat2Z.id.\nrewrite Zdiv.div_Zdiv; last by have := F0 k; lia.\nrewrite Z2Nat.id; last first.\n  by rewrite Rmult_assoc -mult_INR mult_comm -Nat.pow_add_r pow_INR.\nrewrite Int_part_INR //.\nrewrite -{2}[Int_part _]Z2Nat.id //; last by rewrite pow_INR.\nrewrite -Zdiv.div_Zdiv ?Nat2Z.id; last by have := F0 n; lia.\nrewrite mult_comm -Nat.mod_eq //; last by have := F0 n; lia.\nby rewrite /Rdigit /= Rmult_1_r.\nQed.\n\nLemma Rdigit_mod_div16 r d p : (3 < p)%nat ->\n   Rdigit 16 d r  = \n   ((Z.to_nat (Int_part ((Rabs r) * 16 ^ d / 16 * 2 ^ p )))\n        mod (2 ^ p) / (2 ^ p / 16))%nat.\nProof.\nmove=> Pp.\nhave ->: (p = (p - 4) + 4)%nat by lia.\nhave ->: (2 ^ (p - 4 + 4) / 16 = 2 ^ (p - 4))%nat.\n  by rewrite Nat.pow_add_r Nat.div_mul.\nhave F : Rabs r * 16 ^ d / 16 = Rabs (r * 16 ^ d / 16).\n  rewrite !Rabs_mult [Rabs (16 ^ _)]Rabs_pos_eq; last first.\n    by apply: pow_le; lra.\n  by rewrite [Rabs (/_)]Rabs_pos_eq; lra.\nrewrite F -Rdigit_mod_div; tlia.\nrewrite -RdigitS.\nhave ->: (2 ^ 4) %:R = 16 by rewrite /=; lra.\nhave ->: r * 16 ^ d / 16 * 16 = r * 16%:R ^ d.\n  have ->: 16 %:R = 16 by rewrite /=; lra.\n  by field.\nby rewrite Rdigit_shift plus_0_r.\nQed.\n\n(******************************************************************************)\n(*                                                                            *)\n(*                              COMPUTATION in NAT                            *)\n(*                                                                            *)\n(******************************************************************************)\n\nOpen Scope nat_scope.\n\nSection NComputePi.\n\n(* Precision *)\nVariable p : nat.\nLet pS := 2 ^ p.\n\nLet PpS : 0 < 2 ^ p.\nProof.\nsuff : 2 ^ 0 <= 2 ^ p by rewrite /=; lia.\nby apply: Nat.pow_le_mono_r; lia.\nQed.\n\n(* Digit position *)\nVariable d : nat.\n\nSection power.\n\nVariable m : nat.\n\n(* a ^ b mod m *)\nDefinition NpowerMod a b m := (a ^ b) mod m.\nLemma NpowerModE a b : 0 < m -> \n exists u, a ^ b = u * m + NpowerMod a b m.\nProof.\nby exists (a ^ b / m); rewrite Mult.mult_comm; apply: Nat.div_mod; lia.\nQed.\n\nEnd power.\n\nLet f k i := (((16 ^ d / 16) * 2 ^ p) / (16 ^ i * (8 * i + k)%:R))%R.\nLet g k i := (/ (16 ^ i * (8 * i + k)%:R))%R.\n\nLemma fgE k : (Series (f k) = (16 ^ d / 16) * 2 ^ p * Series (g k))%R.\nProof. by exact: Series_scal_l. Qed.\n\nLemma PigE : ((16 ^ d / 16) * 2 ^ p * PI = \n               4 * (Series (f 1)) - 2 * (Series (f 4)) \n                       - (Series (f 5)) - (Series (f 6)))%R.\nProof. by rewrite Plouffe_PI /Sk /a !fgE /g; lra. Qed.\n\n(* Iterative state : counter kN = k and result *) \nInductive NstateF := NStateF (i : nat) (res : nat).\n\n(* Un pas : i = i + 1\n            res = ress + (16^(d - 1 - k)) * 2^p / (8 * k + j) *)\nDefinition NiterF (k : nat) (st : NstateF) :=\n  let (i, res) := st in\n  let r := 8 * i + k in\n  let res := res + (pS * (NpowerMod 16 (d - 1 - i) r)) / r in\n  let res := if res <? pS then res else res - pS in\n  NStateF (S i) res.\n\nLemma NiterF_mod k i res : 0 < k ->\n  let (_, res1) := NiterF k (NStateF i res) in res < pS -> res1 < pS.\nProof.\nrewrite /NiterF => Pj sLpS.\nset x := _ / _.\nhave : x < pS.\n  apply: Nat.div_lt_upper_bound; tlia.\n  rewrite mult_comm.\n  apply: mult_lt_compat_r; tlia .\n  by apply: Nat.mod_upper_bound; tlia.\ncase E : (_ <? _); tlia.\nby move: E; rewrite Nat.ltb_lt; lia.\nQed.\n\nLemma base_sum_approxL k i (v := 8 * i + k) (po := NpowerMod 16 (d - 1 - i) v) :\n 0 < k -> i < d -> \n   exists u, (0 <= f k i - (pS * po / v)%:R - u%:R * 2 ^ p < 1)%R.\nProof.\nmove=> Pj iLd.\nhave Pv : 0 < v by rewrite /v; lia.\nhave [u1 Hu1] := NpowerModE _ 16 (d - 1 - i) Pv.\nhave F1 := approx_divR (pS * po) v Pv.\nhave F2 : (0 < v%:R)%R by apply: (lt_INR 0).\nhave F3 : (0 < 16 ^ i)%R by apply: pow_lt; lra.\nhave ->: f k i = ((2 ^ p * 16 ^ (d - 1 - i))%:R / v%:R)%R.\n  rewrite /f -/v mult_INR !pow_INR.\n  have->: (2%:R = 2)%R by rewrite /=; lra.\n  have->: (16%:R = 16)%R by rewrite /=; lra.\n  have {1}->: d = (d - 1 - i) + i + 1 by lia.\n  rewrite !pow_add; field; lra.\nexists u1.\nrewrite Hu1 mult_plus_distr_l plus_INR.\nrewrite ![(2 ^ p * _)%:R]mult_INR [(u1 * _)%:R]mult_INR.\nrewrite [(_ / _)%R]Rmult_plus_distr_r.\nrewrite !Rmult_assoc Rinv_r ?Rmult_1_r; tlra.\nrewrite pow_INR.\nhave->: (2%:R = 2)%R by rewrite /=; lra.\nhave ->: forall a b c d,  a = c -> (a + b - d - c = b - d)%R; last by lra.\n  by move=> a1 b1 c1 d1 ->; ring.\nhave ->: (2 ^ p = pS %:R)%R.\n  by rewrite /pS; rewrite pow_INR.\nby rewrite -Rmult_assoc -mult_INR -/po; lra.\nQed.\n\nNotation nat_iter n A f x := (nat_rect (fun _ => A) x (fun _ => f) n).\n\n(* Compute \\sum_{i = 0 to d - 1} (16^(d - 1 - i)) * 2^p / (8 * i + k) *)\nDefinition NiterL k :=\n   nat_iter d _ (NiterF k) (NStateF 0 0).\n\nLemma NiterL_mod j : 0 < j ->\n  let (_, s1) := NiterL j in s1 < pS.\nProof.\nrewrite /NiterL => Pj.\nhave F : 0 < pS.\n  suff: 1 <= pS by lia.\n  by apply: (Nat.pow_le_mono_r 2 0 p); lia.\nelim: d => //= n.\ncase: (nat_iter _ _  _ _) => k s sLp.\nby apply: NiterF_mod.\nQed.\n\nLemma sumLE k : 0 < k -> 0 < d ->\n  let (_, res) := NiterL k in \n  exists u, \n  (0 <= sum_f_R0 (f k) (d - 1) - res%:R - u%:R * 2 ^ p < d%:R)%R.\nProof.\nmove=> Pk; rewrite /NiterL.\nhave F n m s :\n     exists s1, nat_iter n _ (NiterF k) (NStateF m s) = (NStateF (m + n) s1).\n  elim: n  => //= [|n [s1->]]; first by exists s; congr NStateF; lia.\n  by rewrite Nat.add_succ_r; eexists; refine (refl_equal _).\nrewrite /NiterL.\nelim: {-2}d (Nat.le_refl d) => // [dP dV| [|n] IH nLd _].\n- by contradict dV; lia.\n- rewrite /=.\n  suff ->: pS * NpowerMod 16 (d - 1 - 0) k / k <? pS = true.\n    rewrite {-1 4}(_ : k = 8 * 0 + k); tlia.\n    by apply:  base_sum_approxL; lia.\n  rewrite Nat.ltb_lt; apply: Nat.div_lt_upper_bound; tlia.\n  rewrite mult_comm; apply: mult_lt_compat_r.\n    by apply: Nat.mod_upper_bound; lia.\n  suff : 1 ^ 0 <= pS by rewrite Nat.pow_0_r; lia.\n  by apply: Nat.pow_le_mono; lia.\nhave F1 : S n <= d by lia.\nhave F2 : 0 < S n by lia.\nrewrite (nat_rect_plus 1 (S n)).\nhave {IH} := IH F1 F2.\nhave {F}[s->]:= F (S n) 0 0 => [[u]].\nrewrite nat_rect_succ_r /nat_rect.\nchange (0 + S n) with (S n).\nreplace  (S n - 1) with n by lia.\nreplace  (S (S n - 1)) with (S n) by lia.\nreplace  (S (S n) - 1) with (S n) by lia.\nrewrite /NiterF.\nset sum := sum_f_R0 _ _.\nset v := 8 * S n + k.\nset po := NpowerMod _ _ _.\nhave [u1 Hu1] := base_sum_approxL k (S n) Pk nLd.\nrewrite -/po -/v in Hu1 => Hu.\nhave F3 :\n   (0 <=\n          sum + f k (S n) - (s + pS * po / v) %:R - \n                      (u %:R * 2 ^ p + u1 %:R * 2 ^ p) < (S (S n)) %:R)%R.\n  have ->: forall a b c d e f, (((a + b - (c + d)%:R) - (e + f)) = \n                             (a - c%:R - e + (b - f - d%:R)))%R.\n    by move=> *; rewrite plus_INR; ring.\n  by rewrite S_INR; lra.\ncase E : (_ <? _).\n  exists (u + u1).\n  rewrite [(u + _)%:R]plus_INR Rmult_plus_distr_r sum_N_predN; tlia.\n  by rewrite [pred _]/= -/sum.\nexists (u + S u1).\nrewrite minus_INR; last first.\n  by rewrite -Nat.nlt_ge -Nat.ltb_lt E.\nrewrite [(u + _)%:R]plus_INR Rmult_plus_distr_r; tlia.\nrewrite sum_N_predN -/sum; tlia.\nrewrite S_INR Rmult_plus_distr_r Rmult_1_l.\nhave ->: (pS%:R = 2 ^ p)%R by rewrite pow_INR /=.\nby lra.\nQed.\n\n(* Iterative state : counter kN = index shift and result *) \nInductive NstateG := NStateG (i : nat) (s : nat) (res : nat).\n\n(* Un pas : i = i + 1, s = s / 16,\n            res = res + (d / (8 * i + k)) *)\nDefinition NiterG (k : nat) (st : NstateG) :=\n  let (i, s, res) := st in\n  let r := 8 * i + k in\n  let res := res + (s / r) in\n  NStateG (S i) (s / 16) res.\n\n(* Compute \\sum_{i = d to infinity} (16^(d - 1 - i)) / (8 * i + j) *)\nDefinition NiterR k :=\n  nat_iter (p / 4) _ (NiterG k) (NStateG d (pS / 16) 0).\n\nLemma sumRE k : 0 < k -> 0 < p / 4 ->\n  let (_,_, s1) := NiterR k in \n  (0 <= sum_f_R0 (fun i => (f k (d + i))) (p / 4 - 1) - s1%:R < (p / 4)%:R)%R.\nProof.\nmove=> Pk.\nhave F n m i s :\n     exists s1, nat_iter n _ (NiterG k) (NStateG m (pS / (16 ^ i)) s)\n                              = (NStateG (m + n)(pS / (16 ^ (i + n))) s1).\n  elim: n  => //= [|n [s1->]].\n    by exists s; congr NStateG; rewrite ?plus_0_r; tlia.\n  rewrite !Nat.add_succ_r.\n  rewrite Nat.pow_succ_r; tlia.\n  have F : 16 ^ 0 <= 16 ^(i + n) by apply: Nat.pow_le_mono_r; lia.\n  rewrite Nat.pow_0_r in F; tlia. \n  rewrite mult_comm -Nat.div_div; tlia.\n  by eexists; refine (refl_equal _).\nhave G j : \n    (0 <= f k (d + j) - (pS / 16 ^ (1 + j) / (8 * (d + j) + k)) %:R < 1 %:R)%R.\n  have F2 j1 : 0 < 16 ^ j1.\n    have : 16 ^ 0 <= 16 ^ j1 by apply: Nat.pow_le_mono_r; lia.\n    by rewrite Nat.pow_0_r; lia.\n  have F3 j1 : (0 < 16 ^ j1)%R.\n    have<-: (16%:R = 16)%R by rewrite /=; lra.\n    rewrite -(pow_INR 16).\n    by apply: (lt_INR 0).\n  have F4 : 0 < (16 ^ (1 + j) * (8 * (d + j) + k)).\n    by apply: Nat.mul_pos_pos; try apply: F2; tlia.\n  have := approx_divR pS _ F4.\n  rewrite  /f /pS !(mult_INR, pow_INR) !Nat.div_div; try lia.\n  have->: (1%:R = 1)%R by rewrite /=; lra.\n  have->: (2%:R = 2)%R by rewrite /=; lra.\n  have->: (16%:R = 16)%R by rewrite /=; lra.\n  set u := (_ / _)%R.\n  set v := (_ / _)%R.\n  replace u with v; first by [].\n  rewrite /v /u !pow_add pow_1; field; tlra.\n  have : (0 < (8 * (d + j) + k) %:R)%R.\n    apply: (lt_INR 0); lia.\n  by have := F3 j; have := F3 d; lra. \nrewrite /NiterR.\nelim: (p/4) => [H|[|n] IH _].\n- contradict H; lia.\n- rewrite nat_rect_succ_r /nat_rec /NiterG.\n  change (1 - 1) with 0.\n  rewrite /sum_f_R0 plus_0_l.\n  change 16 with (16 ^(1 + 0)).\n  by rewrite (_ : 8 * d = 8 * (d + 0)); tlia.\nrewrite (nat_rect_plus 1 (S n)).\nhave F1 : 0 < S n by lia.\nhave {IH} := IH F1.\nhave := F (S n) d 1 0.\nrewrite Nat.pow_1_r => [[s ->]]. \nrewrite nat_rect_succ_r /nat_rect.\nreplace  (S n - 1) with n by lia.\nreplace  (S (S n) - 1) with (S n) by lia.\nrewrite /NiterG.\nset sum := sum_f_R0 _ _.\nset v := 8 * (d + S n) + k.\nrewrite /sum_f_R0 -/sum_f_R0 -/sum.\nhave := G (S n).\nrewrite -/v.\nrewrite [((S (S _))%:R)%R]S_INR plus_INR.\nchange (1%:R)%R with 1%R.\nlra.\nQed.\n\nLemma NiterR_mod k : 0 < k ->\n  let (_, _, res) := NiterR k in 15 * res < pS.\nProof.\nmove=> Pk.\ncase: (lt_dec 0 (p / 4))=> Pp; last first.\n  rewrite /NiterR /nat_rect; replace (p / 4) with 0; tlia. \nhave F0 : (0 < 16 ^ d)%R by apply: pow_lt; lra. \nhave F1 j N :\n       j <> 1%R ->\n       sum_f_R0 (fun i : nat => (j ^ i)%R) N = ((1 - j ^ S N) / (1 - j))%R.\n  by move=> kD; elim: N => /= [|n ->]; field; lra. \nhave F2 N : (sum_f_R0 (fun i => (f k (d + i))) N <= \n    (16 ^ d / 16 * 2 ^ p) * (1/16)^d *\n         (sum_f_R0 (fun i : nat => ((1/16)^ i)%R) N))%R.\n  have F j : (f k (d + j) <= 16 ^ d / 16 * 2 ^ p * (1 / 16) ^ (d + j))%R.\n    have FF1 : (0 < 16 ^ (d + j))%R by apply: pow_lt; lra.  \n    have FF2 : (1 <= (8 * (d + j) + k)%:R)%R by apply: (le_INR 1); lia.\n    rewrite /f  [((_ / _)^ _)%R]Rpow_mult_distr -Rinv_pow; tlra.\n    rewrite -{2}[(16 ^ (d + j))%R]Rmult_1_r.\n    rewrite pow1 Rmult_1_l /Rdiv !Rmult_assoc.\n    rewrite ![(/(_ ^ _ * _))%R]Rinv_mult_distr; tlra.\n    repeat apply: Rmult_le_compat_l; try by apply: pow_le; lra.\n    - by apply: Rinv_le_0_compat; lra.\n    - by apply: Rinv_le_0_compat; lra.\n    by apply: Rle_Rinv; lra.\n  elim: N => /= [|n IH]; first by  have := F 0; rewrite plus_0_r; lra.\n  by have := F (S n); rewrite Nat.add_succ_r /= pow_add; lra.\nhave F3 N : (sum_f_R0 (fun i => (f k (d + i))) N < 2 ^ p / 15)%R.\n  apply: Rle_lt_trans (F2 _) _.\n  rewrite F1; tlra.\n  have-> : (16 ^ d / 16 * 2 ^ p * (1 / 16) ^ d = 2 ^ p / 16)%R.\n    rewrite [((_ / _)^ _)%R]Rpow_mult_distr -Rinv_pow; tlra.\n    by rewrite pow1; field; lra.\n  rewrite !Rmult_assoc; apply: Rmult_lt_compat_l; tlra.\n    by apply: pow_lt; lra. \n  have ->: (/15 = /16 * (1 / (1 - 1/16)))%R by lra.\n  apply: Rmult_lt_compat_l; tlra.\n  apply: Rmult_lt_compat_r; tlra.\n  suff : (0 < (1/16) ^S N )%R by lra.\n  apply: pow_lt; lra.\nhave :=  sumRE _ Pk Pp; case: NiterR => _ _ s Hs.\napply: INR_lt.\nrewrite pow_INR mult_INR.\nhave->: (15 %:R = 15)%R by rewrite /=; lra.\nhave->: (2 %:R = 2)%R by rewrite /=; lra.\nby have := F3 (p / 4 - 1); lra.\nQed.\n\nLemma ex_series_f k : 0 < k -> @ex_series R_AbsRing R_NormedModule (f k).\nProof.\nmove=> Pj; rewrite /f.\nassert (F : ex_series (fun i => (16 ^ d / 16 * 2 ^ p) * (1 / 16) ^ i)%R).\n  apply: ex_series_scal_l.\n  apply: ex_series_geom.\n  by split_Rabs; lra.\napply: ex_series_le F => n.\nhave F1 : (0 < 16 ^ n)%R by apply: pow_lt; lra.\nhave F2 : (0 < (8 * n + k) %:R)%R   by apply: (lt_INR 0); lia.\nhave H1: (0 <= 16 ^ d / 16 * 2 ^ p)%R.\n  repeat (apply: Rcomplements.Rdiv_le_0_compat || apply: Rmult_le_pos);\n    (try by apply: pow_le; lra); lra.\napply:(Rle_trans _ (16 ^ d / 16 * 2 ^ p / (16 ^ n * (8 * n + k) %:R))); last first.\n  apply: Rmult_le_compat_l.\n    by apply H1.\nrewrite Rinv_mult_distr; tlra.\nhave ->: ((1 / 16) ^ n = / (16 ^ n) * 1)%R.\n  rewrite /Rdiv Rmult_1_l Rinv_pow; lra.\napply: Rmult_le_compat_l.\n  by apply: Rinv_le_0_compat.\nhave ->: (1 = 1 / 1)%R by field.\nrewrite /Rdiv Rmult_1_l.\napply: Rle_Rinv; tlra.\nby apply: (le_INR 1); lia.\nset gg := (16 ^ d / 16 * 2 ^ p / (16 ^ n * (8 * n + k) %:R))%R.\n  rewrite  /Hierarchy.norm /= /abs /= Rabs_right.\n    by apply: Req_le. \napply: Rle_ge; apply: Rdiv_le_0_compat=>//.\nby apply:Rmult_lt_0_compat.\nQed.\n\nLemma series_bound k : 0 < k -> \n  (0 <= Series (fun i : nat => f k (d + (p / 4 + i))) < 1)%R.\nProof.\nmove => Pj; split.\n  suff <-: Series (fun i => (0 * 0)%R) = 0%R.\n    apply: Series_le => [n|]; last first.\n      apply: (ex_series_ext (fun i : nat => f k ((d + p / 4) + i))).\n        by move=> n; rewrite Plus.plus_assoc.\n      by rewrite -ex_series_incr_n; apply: ex_series_f.\n    split; tlra.\n    rewrite Rmult_0_l.\n    repeat (apply: Rcomplements.Rdiv_le_0_compat || apply: Rmult_le_pos);\n    (try by apply: pow_le; lra); tlra.\n    apply: Rmult_lt_0_compat; first by apply: pow_lt; lra.\n    by apply: (lt_INR 0); lia.\n  by rewrite Series_scal_l; lra.\npose f1 k := ((16 ^ d / 16 * 2 ^ p) / (16 ^ (d + (p / 4))) * (/16) ^ k)%R.\nrewrite /f.\napply: Rle_lt_trans (Series_le _ f1 _ _) _.\n- move=> n; rewrite /f1; split.\n    repeat (apply: Rcomplements.Rdiv_le_0_compat || apply: Rmult_le_pos);\n    (try by apply: pow_le; lra); tlra.\n    apply: Rmult_lt_0_compat; first by apply: pow_lt; lra.\n    by apply: (lt_INR 0); lia.\n  set x := (16 ^ d / 16 * 2 ^ p)%R.\n  set y := (_ * _)%R.\n  rewrite -Rinv_pow; tlra.\n  rewrite Rmult_assoc.\n  apply: Rmult_le_compat_l.\n    by repeat (apply: Rcomplements.Rdiv_le_0_compat || apply: Rmult_le_pos);\n      (try by apply: pow_le; lra); lra.\n  rewrite -Rinv_mult_distr.\n  - rewrite -Rdef_pow_add.\n    apply: Rle_Rinv; first by apply: pow_lt; lra.\n      apply: Rmult_lt_0_compat; first by apply: pow_lt; lra.\n      by apply: (lt_INR 0); lia.\n    rewrite -Plus.plus_assoc -[X in (X <= _)%R]Rmult_1_r.\n    apply: Rmult_le_compat_l; first by apply: pow_le; lra.\n    by apply: (le_INR 1); lia.\n  - suff: (0 < 16 ^ (d + p / 4))%R by lra.\n    by apply: pow_lt; lra.\n  suff: (0 < 16 ^ n)%R by lra.\n  by apply: pow_lt; lra.\n- apply: ex_series_scal_l.\n  apply: ex_series_geom.\n  by split_Rabs; lra.\nrewrite Series_scal_l.\nrewrite Series_geom; last by split_Rabs; lra.\nset x := (_ * _)%R.\nhave ->: x = ((16 ^ d * 2 ^ p * 16) / (15 * 16 ^ (d + p / 4 + 1)))%R.\n  rewrite /x !Rdef_pow_add pow_1.\n  field.\n  have : (0 < 16 ^ (p / 4))%R by apply: pow_lt; lra.\n  have : (0 < 16 ^ d)%R by apply: pow_lt; lra.\n  by lra.\nrewrite Rcomplements.Rlt_div_l; last first.\n  apply: Rmult_lt_0_compat; tlra.\n  by apply: pow_lt; lra.\nhave ->: (1 * (15 * 16 ^ (d + p / 4 + 1)) = \n             16  ^ d * (2 ^ (4 * (p / 4 + 1)) * 15))%R.\n  rewrite pow_mult (_ : (2 ^ 4 = 16)%R); last by ring.\n  by rewrite !pow_add; ring.\nrewrite !Rmult_assoc.\napply: Rmult_lt_compat_l.\n  by apply: pow_lt; lra.\napply: Rlt_le_trans (_ : (2 ^ (p + 1) *  15 <= _)%R).\n  rewrite pow_add Rmult_assoc.\n  apply: Rmult_lt_compat_l; last by lra.\n  by apply: pow_lt; lra.\napply: Rmult_le_compat_r; tlra.\napply: Rle_pow; tlra.\nrewrite {1}(NPeano.Nat.div_mod p 4); tlia.\nhave := NPeano.Nat.mod_bound_pos p 4.\nby lia.\nQed.\n\nLemma bound k : 0 < k ->  \n  exists u, \n  let (_, res1) := NiterL k in\n  let (_, _, res2) := NiterR k in\n  (0 <= Series (f k) - res1%:R - res2%:R - u %:R * 2 ^ p  < (d + p / 4 + 1)%:R)%R.\nProof.\nmove=> Pk.\nhave F := ex_series_f _ Pk.\ncase: (lt_dec 0 d) => Pd.\n  rewrite (Series_incr_n _ d) //.\n  replace (pred d) with (d - 1); tlia.\n  have := sumLE _ Pk Pd.\n  case: NiterL => _ s1 [u Hs1]; exists u.\n  case: (lt_dec 0 (p / 4)) => Pp.\n    rewrite (Series_incr_n _ (p/4)) //; last first.\n      by rewrite -ex_series_incr_n.\n    replace (pred (p / 4)) with (p / 4 - 1); tlia.\n    have := sumRE _ Pk Pp.\n    case: NiterR => _ _ s2.\n    move: Hs1.\n    have := series_bound _ Pk.\n    rewrite !plus_INR.\n    change (1%:R)%R with 1%R.\n    by lra.\n  have := series_bound _ Pk.\n  rewrite /NiterR; replace (p / 4) with 0 by lia.\n  rewrite /nat_rect /=.\n  rewrite !plus_INR.\n  change (1%:R)%R with 1%R.\n  change (0%:R)%R with 0%R.\n  by lra.\nexists 0.\ncase: (lt_dec 0 (p / 4)) => Pp.\n  rewrite (Series_incr_n _ (p/4)) //.\n  replace (pred (p / 4)) with (p / 4 - 1); tlia.\n  have := sumRE _ Pk Pp.\n  rewrite /NiterL.\n  have := series_bound _ Pk.\n  replace d with 0 by lia.\n  rewrite /nat_rect /=.\n  case: NiterR => _ _ s2.\n  rewrite !plus_INR.\n  change (1%:R)%R with 1%R.\n  change (0%:R)%R with 0%R.\n  set xxx := Series _.\n  set yyy := sum_f_R0 _ _.\n  by lra.\nhave := series_bound _ Pk.\nrewrite /NiterL /NiterR.\nreplace d with 0 by lia.\nreplace (p / 4) with 0 by lia.\nrewrite /nat_rect /=.\nset xxx := Series _.\nlra.\nQed.\n\n(* Compute \\sum_{i = 0 to infinity} (16^(d - 1 - i)) / (8 * i + j) *)\nDefinition NsumV k :=\n  let: NStateF _ res1 := NiterL k in\n  let: NStateG _ _ res2 := NiterR k in res1 + res2.\n\nLemma NsumV_mod k :  0 < k -> NsumV k < 2 * pS.\nProof.\nmove=> Pk.\nrewrite /NsumV.\nhave := NiterL_mod _ Pk.\nhave := NiterR_mod _ Pk.\ncase: NiterL; case: NiterR => _ _ t _ s; lia.\nQed.\n  \nLemma bound_NsumV k : 0 < k ->  \n  exists u, \n  (0 <= Series (f k) - (NsumV k)%:R - u %:R * 2 ^ p  < (d + p / 4 + 1)%:R)%R.\nProof.\nmove=> Pj.\nhave [u] := bound _ Pj.\nrewrite /NsumV; case: NiterL; case: NiterR => _ _ t _ s Hu.\nexists u; move : Hu.\nrewrite !plus_INR; lra.\nQed.\n\nLemma main_thm (delta := d + p / 4 + 1)\n          (X :=  (4 * Series (f 1) - 2 * Series (f 4) \n                       - Series (f 5) - Series (f 6))%R)\n          (Y := (4 * (NsumV 1) + \n             (9 * pS - (2 * NsumV 4 + NsumV 5 + NsumV 6 + 4 * delta)))%nat)\n   : 3 < p -> 8 * delta < 2 ^ (p - 4) -> \n      (Y + 8 * delta) mod 2 ^ p / 2 ^ (p - 4) = Y mod 2 ^ p / 2 ^ (p - 4)\n  -> Rdigit 16 d PI = Y mod 2 ^ p / 2 ^ (p - 4).\nProof.\nmove=> Pp Hdelta HmodEq.\nhave PX : (0 <= X)%R.\n  rewrite /X -PigE.\n  have PIp:= PI2_1.\n  by repeat ((apply: Rmult_le_pos || apply: Rabs_pos || apply: pow_le\n             || apply: pos_INR); tlra).\nhave FE : (4%:R = 4)%R by rewrite /=; lra.\nhave TE : (2%:R = 2)%R by rewrite /=; lra.\nhave NE : (9%:R = 9)%R by rewrite /=; lra.\nhave PSE : (pS%:R = 2 ^ p)%R.\n  by rewrite pow_INR TE /=; lra.\npose NNE := (FE, TE, NE, PSE).\nhave F1 : (0 < 1)%nat by lia.\nhave pS1 := NsumV_mod _ F1.\nhave {F1}[u1 Hu1] := bound_NsumV _ F1.\nhave F4 : (0 < 4)%nat by lia.\nhave pS4 := NsumV_mod _ F4.\nhave {F4}[u4 Hu4] := bound_NsumV _ F4.\nhave F5 : (0 < 5)%nat by lia.\nhave pS5 := NsumV_mod _ F5.\nhave {F5}[u5 Hu5] := bound_NsumV _ F5.\nhave F6 : (0 < 6)%nat by lia.\nhave pS6 := NsumV_mod _ F6.\nhave {F6}[u6 Hu6] := bound_NsumV _ F6.\nrewrite -/delta in Hu1 Hu4 Hu5 Hu6.\nhave Pd : 4 * delta < pS.\n  rewrite /pS.\n  have ->: p = 4 + (p - 4) by lia.\n  by rewrite /=; lia.\nhave {u1 Hu1}[v1 Hv1] : exists u,\n   (0 <= 4 * Series (f 1) - 4 * (NsumV 1) %:R \n           - u %:R * 2 ^ p < 4 * delta %:R)%R.\n  exists (4 * u1); rewrite mult_INR.\n  have ->: (4%:R = 4)%R by rewrite /=; lra.\n  by lra.\nhave {u4 u5 u6 Hu4 Hu5 Hu6}[v2 Hv2] : exists u,\n   (0 <= 2 * Series (f 4) + Series (f 5) + Series (f 6)  - \n        (2 * NsumV 4 + NsumV 5 +  NsumV 6) %:R \n         - u %:R * 2 ^ p < 4 * delta %:R)%R.\n  exists (2 * u4 + u5 + u6); rewrite 4!plus_INR !mult_INR.\n  have ->: (2%:R = 2)%R by rewrite /=; lra.\n  by lra.\nhave  YE: Y%:R =  (4 * (NsumV 1)%:R + \n             (9 * 2 ^ p - (2 * NsumV 4 + NsumV 5 + NsumV 6)%:R \n                        - 4 * delta%:R))%R.\n  rewrite /Y /delta !(mult_INR, plus_INR).\n  rewrite minus_INR; last by rewrite -/delta; lia.\n  by rewrite !(mult_INR, plus_INR) !NNE; lra.\nhave P1 :\n  (Y%:R + v1%:R * 2 ^ p < X + v2%:R * 2 ^ p + 9 * 2 ^ p <\n   Y%:R + v1%:R * 2 ^ p + 8 * delta %:R)%R.\n  by rewrite YE /X; lra.\nset xx := (X + v2 %:R * 2 ^ p + 9 * 2 ^ p)%R.\nset yy := (Y %:R + v1 %:R * 2 ^ p)%R.\nset zz := (xx - yy)%R.\nhave Fc1 : (0 < zz < 8 * delta %:R)%R.\n  by rewrite /zz /xx /yy; lra.\nhave GG : (0 <= xx - (v1 %:R * 2 ^ p))%R.\n  rewrite /zz /yy in Fc1.\n  suff: (0 <= Y%:R)%R by lra.\n  by apply: pos_INR.\npose c1 := Z.to_nat (Int_part zz).\nhave F2 : 0 <= c1 <= 8 * delta.\n  have F2 : (0 <= zz)%R by lra.\n  have F3 : (0 <= Int_part zz)%Z.\n    rewrite -[0%Z](R_Ifp.Int_part_INR 0).\n    by apply: le_Int_part.\n  have := F3.\n  rewrite Z2Nat.inj_le ?Nat2Z.id -/c1 ; tlia.\n  have F4 : (zz <= (8 * delta)%:R)%R.\n    rewrite mult_INR; have ->: (8%:R = 8)%R by rewrite /=; lra.\n    by lra.\n  have := le_Int_part _ _ F4.\n  rewrite R_Ifp.Int_part_INR.\n  by rewrite Z2Nat.inj_le ?Nat2Z.id -/c1 ; lia.\nhave F3 : p - 4 < p by lia.\nhave F5 : 1 < 2 by lia.\nhave := mod_between Y 2 c1 (8 * delta) (p - 4) p F2 F3 Hdelta F5 HmodEq.\nrewrite /c1 /zz /yy.\nrewrite -{1}[Y]Nat2Z.id.\nrewrite -Z2Nat.inj_add; tlia; last first.\n  apply: le_Int_part_pos. \n  have := pos_INR Y.\n  by rewrite /zz /yy in Fc1; lra.\nrewrite -R_Ifp.Int_part_INR.\nrewrite -plus_Int_part2; last first.\n  set V := (_ - _)%R.\n  have := base_fp V.\n  by rewrite INR_IZR_INZ frac_part_IZR; lra.\nset U := (_ + _)%R.\nhave ->: U = (X + ((v2 + 9) * 2  ^p ) %:R - (v1 * 2 ^ p)%:R)%R.\n  by rewrite !mult_INR !plus_INR pow_INR !NNE /U /xx; lra.\nrewrite Rminus_Int_part1; last first.\n  set V := (_ + _)%R.\n  have := base_fp V.\n  by rewrite INR_IZR_INZ frac_part_IZR; lra.\nrewrite plus_Int_part2; last first.\n  have := base_fp X.\n  by rewrite INR_IZR_INZ frac_part_IZR; lra.\nrewrite !R_Ifp.Int_part_INR.\nrewrite Z2Nat.inj_sub; tlia.\nrewrite Z2Nat.inj_add; tlia; last first.\n  by apply: le_Int_part_pos; lra.\nrewrite !Nat2Z.id mod_minus_mult; tlia; last first.\n  have FF x : x * 2 ^ p = Z.to_nat (Int_part (x%:R * 2 ^ p)).\n    by rewrite -PSE -mult_INR R_Ifp.Int_part_INR Nat2Z.id.\n  rewrite !{}FF -Z2Nat.inj_add; try apply: le_Int_part_pos; tlra; last first.\n    by rewrite -PSE -mult_INR; apply: pos_INR.\n  rewrite -Z2Nat.inj_le.\n  - rewrite -plus_Int_part2; last first.\n      rewrite -PSE -mult_INR.\n      have := base_fp X.\n      by rewrite INR_IZR_INZ frac_part_IZR; lra.\n    apply: le_Int_part.\n    rewrite /xx in GG.\n    by rewrite plus_INR NE; lra.\n  - apply: le_Int_part_pos.\n    rewrite -PSE -mult_INR.\n    by apply: pos_INR.\n  rewrite -PSE -mult_INR.\n  rewrite R_Ifp.Int_part_INR .\n  suff : (0 <= Int_part X)%Z by lia.\n  by apply: le_Int_part_pos.\nrewrite Nat.mod_add; tlia.\nrewrite /X -PigE.\nhave ->: (16 ^ d / 16 * 2 ^ p * PI = Rabs PI * 16 ^ d / 16 * 2 ^ p)%R.\n  rewrite Rabs_pos_eq; tlra.\n  by have := PI2_1; lra.\nhave {1}->: 2 ^ (p - 4) = 2 ^ p / 16.\n  have {2}->: p = 4 + (p - 4) by lia.\n  by rewrite Nat.pow_add_r mult_comm Nat.div_mul.\nrewrite -Rdigit_mod_div16 //; lia.\nQed.\n\n(* Extra the first digit from Plouffe formula *)\nDefinition NpiDigit :=\n  let delta := d + p / 4 + 1 in\n  if (3 <? p) then\n    if (8 * delta <? 2 ^ (p - 4)) then\n      let Y := (4 * (NsumV 1) + \n             (9 * pS - (2 * NsumV 4 + NsumV 5 + NsumV 6 + 4 * delta))) in\n      let v1 := (Y + 8 * delta) mod 2 ^ p / 2 ^ (p - 4) in\n      let v2 := Y mod 2 ^ p / 2 ^ (p - 4) in\n      if beq_nat v1 v2 then Some v2 else\n      None\n    else None\n  else None.\n\nLemma NpiDigit_correct k : \n  NpiDigit = Some k -> Rdigit 16 d PI = k.\nProof.\nrewrite /NpiDigit.\ncase E1 : Nat.ltb => //.\nmove: E1; rewrite Nat.ltb_lt => E1.\ncase E2 : Nat.ltb => //.\nmove: E2; rewrite Nat.ltb_lt => E2.\ncase: Nat.eqb_spec => // E3 [<-].\nby apply: main_thm.\nQed.\n\nEnd NComputePi.\n\n(* Hexa conversion *)\nDefinition nToS n :=\n  let v := n in  \n  match v with\n  | 0%nat => \"0\"%string \n  | 1%nat => \"1\"%string\n  | 2%nat => \"2\"%string\n  | 3%nat => \"3\"%string\n  | 4%nat => \"4\"%string\n  | 5%nat => \"5\"%string\n  | 6%nat => \"6\"%string\n  | 7%nat => \"7\"%string\n  | 8%nat => \"8\"%string\n  | 9%nat => \"9\"%string\n  | 10%nat => \"A\"%string\n  | 11%nat => \"B\"%string\n  | 12%nat => \"C\"%string\n  | 13%nat => \"D\"%string\n  | 14%nat => \"E\"%string\n  | 15%nat => \"F\"%string\n  | _ => \"?\"%string\nend. \n \n(* How many bits of the fixed-point like computation *)\nDefinition Nprecision := 14.\n\nDefinition NpiDigitF k :=\n  match NpiDigit Nprecision k with Some v => v | _ => 16 end.\n\nFixpoint rNpi k n :=\n  match n with \n  | S n1 => String.append (nToS (NpiDigitF k)) (rNpi (S k) n1)\n  | _ =>  (nToS (NpiDigitF k))\nend.\n\n(* Compute string of the hexa representation of pi *)\nDefinition Npi := rNpi 0.\n\n(* Pi in hexa \n\n3243F6A8885A308D313198A2E03707344A4093822299F31D00\n82EFA98EC4E6C89452821E638D01377BE5466CF34E90C6CC0A\nC29B7C97C50DD3F84D5B5B54709179216D5D98979FB1BD1310\nBA698DFB5AC2FFD72DBD01ADFB7B8E1AFED6A267E96BA7C904\n5F12C7F9924A19947B3916CF70801F2E2858EFC16636920D87\n1574E69A458FEA3F4933D7E0D95748F728EB658718BCD58821\n54AEE7B54A41DC25A59B59C30D5392AF26013C5D1B02328608\n5F0CA417918B8DB38EF8E79DCB0603A180E6C9E0E8BB01E8A3\nED71577C1BD314B2778AF2FDA55605C60E65525F3AA55AB945\n748986263E8144055CA396A2AAB10B6B4CC5C341141E8CEA15\n*)\n\n(* First 5 digits of Pi *)\nTime Compute Npi 5.\n\nDefinition Ndigit n := nToS (NpiDigitF n).\n\n(* 6^th decimal of Pi *)\nTime Compute Ndigit 5.\n\n(******************************************************************************)\n(*                               Turning from N to BigN                       *)\n(******************************************************************************)\n\nFrom Bignums Require Import BigN.\n\nOpen Scope bigN_scope.\n\nNotation \" [[ n ]] \" := (Z.to_nat [n]).\n\nLemma specN_add m n : [[m + n]] = ([[m]] + [[n]])%nat.\nProof.\nby rewrite BigN.spec_add Z2Nat.inj_add //; apply: BigN.spec_pos.\nQed.\n\nLemma specN_sub m n : [[m - n]] = ([[m]] - [[n]])%nat.\nProof.\nrewrite BigN.spec_sub.\ncase: (Zmax_spec 0 ([m] - [n])) => [] [H1 ->] /=.\n  rewrite le_minus_0 // -Z2Nat.inj_le; tlia.\n    by apply: BigN.spec_pos.\n  by apply: BigN.spec_pos.\nrewrite Z2Nat.inj_sub //.\nby apply: BigN.spec_pos.\nQed.\n\nLemma specN_mul m n : [[m * n]] = ([[m]] * [[n]])%nat.\nProof.\nby rewrite BigN.spec_mul Z2Nat.inj_mul //; apply: BigN.spec_pos.\nQed.\n\nLemma specN_pow m n : ([[m ^ n]] = [[m]] ^ [[n]])%nat.\nProof.\nrewrite BigN.spec_pow -[X in _ = X]Nat2Z.id pow_Zpower.\nby rewrite !Z2Nat.id //; apply: BigN.spec_pos.\nQed.\n\nLemma specN_mod m n : \n  (0 < [[n]])%nat -> [[m mod n]] = ([[m]] mod [[n]])%nat.\nProof.\nmove=> Pn.\nrewrite BigN.spec_modulo -[X in _ = X]Nat2Z.id.\nby rewrite mod_Zmod  ?Z2Nat.id //; tlia; try by apply: BigN.spec_pos.\nQed.\n\nLemma specN_cmp m n : m <? n = ([[m]] <? [[n]])%nat.\nProof.\nrewrite BigN.spec_ltb.\ncase E : (_ <? _)%nat.\n  move: E; rewrite Nat.ltb_lt -Z2Nat.inj_lt; try by apply: BigN.spec_pos.\n  by rewrite -Zlt_is_lt_bool.\nhave : ~ ([m] < [n])%Z.\n  rewrite Z2Nat.inj_lt; try by apply: BigN.spec_pos.\n  by rewrite -Nat.ltb_lt E.\nby rewrite Zlt_is_lt_bool; case: (_ <? _)%Z.\nQed.\n\nLemma specN_if_cmp m n p q : \n  [[if m <? n then p else q]] = \n  (if [[m]] <? [[n]] then [[p]] else [[q]])%nat.\nProof. by rewrite specN_cmp; case: (_ <? _)%nat. Qed.\n\nLemma specN_eqb m n : m =? n = (beq_nat [[m]] [[n]])%nat.\nProof.\nrewrite BigN.spec_eqb.\ncase: Nat.eqb_spec.\n  rewrite Z.eqb_eq.\n  by apply: Z2Nat.inj; apply: BigN.spec_pos.\ncase E: (_ =? _)%Z => // [] [].\nby move: E; rewrite Z.eqb_eq => ->.\nQed.\n\nLemma specN_if_eqp m n p q : \n  [[if m =? n then p else q]] = \n  (if beq_nat [[m]] [[n]] then [[p]] else [[q]])%nat.\nProof. by rewrite specN_eqb; case: beq_nat. Qed.\n\nLemma specN_shiftl m n : \n  ([[BigN.shiftl m n]] = (2 ^ [[n]]) * [[m]])%nat.\nProof.\nrewrite BigN.spec_shiftl Z.shiftl_mul_pow2; last first.\n  by apply: BigN.spec_pos.\nrewrite Z2Nat.inj_mul; last 2 first.\n- by apply: BigN.spec_pos.\n- by apply: Z.pow_nonneg.\nrewrite -[(_ ^ _)%nat]Nat2Z.id pow_Zpower !Z2Nat.id.\n  by rewrite mult_comm.\nby apply: BigN.spec_pos.\nQed.\n\nLemma specN_shiftr m n : \n  [[BigN.shiftr m n]] = ([[m]] / (2 ^ [[n]]))%nat.\nProof.\nrewrite BigN.spec_shiftr.\n  rewrite Z.shiftr_div_pow2; last first.\n  by apply: BigN.spec_pos.\nrewrite -[(_ / _)%nat]Nat2Z.id.\nrewrite div_Zdiv ?pow_Zpower ?Z2Nat.id //.\n- by apply: BigN.spec_pos.\n- by apply: BigN.spec_pos.\nsuff : (2 ^ 0 <= 2 ^ [[n]])%nat by rewrite /=; lia.\nby apply: Nat.pow_le_mono_r; lia.\nQed.\n\nLemma specN_div m n : \n  (0 < [[n]] -> [[m / n]] = [[m]] / [[n]])%nat.\nProof.\nmove=> Pn.\nrewrite BigN.spec_div.\nrewrite -[(_ / _)%nat]Nat2Z.id div_Zdiv ?Z2Nat.id; tlia.\nby apply: BigN.spec_pos.\nQed.\n\n(******************************************************************************)\n\nSection ComputePi.\n\n(* Precision *)\nVariable p : N.\nDefinition pN := BigN.of_N p.\nDefinition pS := BigN.shiftl 1 pN.\n\n(* Digit position *)\nVariable d : N.\nDefinition dN := BigN.of_N d.\n\nSection power.\n\nVariable m : bigN.\n\nFixpoint powerModc a (b : positive) (c : bigN) :=\nmatch b with \n  xH => (a * c) mod m\n| xO b1 => powerModc ((a * a) mod m) b1 c\n| xI b1 => powerModc ((a * a) mod m) b1 ((a * c) mod m)\nend.\n\nLemma specN_powerModc a b c : (0 < [[m]])%nat ->\n  [[powerModc a b c]] = (([[a]] ^ (Pos.to_nat b) * [[c]]) mod [[m]])%nat.\nProof.\nmove=> mP; elim: b a c => // [b1 IH a c|b1 IH a c|a c]; last first.\n- by rewrite /= specN_mod // specN_mul mult_1_r.\n- rewrite IH Pos2Nat.inj_xO.\n  rewrite Nat.pow_mul_r.\n  rewrite specN_mod //.\n  rewrite -[X in X = _]Nat.mul_mod_idemp_l; tlia.\n  rewrite -[X in _ = X]Nat.mul_mod_idemp_l; tlia.\n  congr (_ * _ mod _)%nat.\n  rewrite -pow_mod; tlia.\n  congr (_ ^ _ mod _)%nat.\n  by rewrite specN_mul /=; lia.\nrewrite IH Pos2Nat.inj_xI.\nrewrite Nat.pow_succ_r; tlia.\nrewrite Nat.pow_mul_r.\nrewrite !specN_mod //.\nrewrite Nat.mul_mod_idemp_r; tlia.\nrewrite !specN_mul // Mult.mult_assoc.\nrewrite -[X in X = _]Nat.mul_mod_idemp_l; tlia.\nrewrite -[X in _ = X]Nat.mul_mod_idemp_l; tlia.\ncongr (_ * _ mod _)%nat.\nrewrite [X in (_ = X mod _)%nat]mult_comm.\nrewrite -[X in _ = X]Nat.mul_mod_idemp_l; tlia.\nrewrite pow_mod; tlia.\nrewrite [X in _ = X]Nat.mul_mod_idemp_l /= ; tlia.\nby congr ((_ mod _) ^ _ * _ mod _)%nat; lia.\nQed.\n\nEnd power.\n\n(* a ^ b mod m *)\nDefinition powerMod a (b : N) m := \n  match b with Npos b1 => powerModc m a b1 1 | _ => \n                  if m <? 2 then 0 else 1 end.\n\nLemma specN_powerMod a b m:  (0 < [[m]])%nat ->\n  [[powerMod a b m]] = (([[a]] ^ (N.to_nat b)) mod [[m]])%nat.\nProof.\nmove=> Pm.\ncase: b => [|b ] /=.\n  rewrite specN_cmp.\n  case E : (_ <? _)%nat.\n    move: E; rewrite Nat.ltb_lt.\n    rewrite -[ [[2]] ]/2%nat.\n    by move=> u; replace [[m]] with 1%nat; try lia.\n  rewrite Nat.mod_small //.\n  move: E; rewrite Nat.ltb_nlt.\n  by rewrite -[ [[2]] ]/2%nat; lia.\nrewrite specN_powerModc; tlia.\nby rewrite mult_1_r.\nQed.\n\nCompute powerMod 2 123939 1239393331.\nCompute powerMod 17 262626 1239393331.\n\n(* Iterative state : counter iN = i and result *) \nInductive stateF := StateF (iN : bigN) (i : N) (s : bigN).\n\n(* Un pas : i = i + 1, iN = iN + 1,\n            ress = res + (16^(d - 1 - k)) * 2^p / (8 * i + k) *)\nDefinition iterF (k : bigN) (st : stateF) :=\n  let: StateF iN i res := st in\n  let r := 8 * iN + k in\n  let res := res + (BigN.shiftl (powerMod 16 (d - 1 - i)%N r) pN) / r in\n  let res := if res <? pS then res else res - pS in\n  StateF (iN + 1) (i + 1)%N res.\n\nDefinition eq_StateF (s1 : stateF) (s2 : NstateF) :=\n  let: StateF i1 i1N res1 := s1 in\n  let: NStateF i2 res2 := s2 in\n  [[i1]] = i2 /\\ N.to_nat i1N = i2 /\\ [[res1]] = res2.\n\nLemma specN_iterF s1 s2 k : (0 < [[k]])%nat ->\n  eq_StateF s1 s2 ->\n  eq_StateF (iterF k s1) (NiterF (N.to_nat p) (N.to_nat d) [[k]] s2).\nProof.\nmove=> Pk.\ncase: s1; case: s2.\nrewrite /NiterF /iterF. \nmove=> k2 s2 k1 l1 s1 [<- [k1E <-] ].\nhave F : (0 < [[8]] * [[k1]] + [[k]])%nat.\n  set x := (_ * _)%nat; lia.\nrepeat split.\n- by rewrite specN_add /= Plus.plus_comm.\n- by rewrite -k1E Nnat.N2Nat.inj_add Plus.plus_comm.\nrewrite !(specN_if_cmp, specN_add, specN_sub, specN_mul, \n          specN_div, specN_shiftl, specN_powerMod) //.\nhave ->: [[16]] = 16%nat by [].\nhave ->: [[8]] = 8%nat by [].\nrewrite /pS /NpowerMod !Nnat.N2Nat.inj_sub k1E.\nhave ->: N.to_nat 1 = 1%nat by [].\nhave ->: N.to_nat p = [[pN]].\n  by rewrite BigN.spec_of_N -Z_N_nat N2Z.id.\nby rewrite mult_1_r.\nQed.\n\n(* Compute \\sum_{i = 0 to d - 1} (16^(d - 1 - i)) * 2^p / (8 * i + k) *)\nDefinition iterL k :=\n   N.iter d (iterF k) (StateF 0 0%N 0).\n\nLemma specN_iterL k : (0 < [[k]])%nat ->\n  eq_StateF (iterL k) (NiterL (N.to_nat p) (N.to_nat d) [[k]]).\nProof.\nmove=> Pk.\nrewrite /iterL /NiterL.\nrewrite -{1}[d]Nnat.N2Nat.id -Nnat.Nat2N.inj_iter.\nelim: {1 3}N.to_nat => //= n IH.\nby apply: specN_iterF.\nQed.\n\n(* Iterative state : counter iN = i shift s and result *) \nInductive stateG := StateG (iN : bigN) (i : N) (s : bigN) (res : bigN).\n\nDefinition eq_StateG (st1 : stateG) (st2 : NstateG) :=\n  let: StateG i1N i1 s1 res1 := st1 in\n  let: NStateG i2 s2 res2 := st2 in\n  [[i1N]] = i2 /\\ N.to_nat i1 = i2 /\\ [[s1]] = s2 /\\ [[res1]] = res2.\n\n(* Un pas : iN = iN + 1, i = i + 1, s = s / 16,\n            res = res + (s / (8 * i + k)) *)\nDefinition iterG (k : bigN) (st : stateG) :=\n  let: StateG iN i s res := st in\n  let r := 8 * iN + k in\n  let res := res + (s / r) in\n  StateG (iN + 1) (i + 1)%N (BigN.shiftr s 4) res.\n\nLemma specN_iterG st1 st2 k : (0 < [[k]])%nat ->\n  eq_StateG st1 st2 ->\n  eq_StateG (iterG k st1) (NiterG [[k]] st2).\nProof.\nmove=> Pj.\ncase: st1; case: st2.\nrewrite /NiterG /iterG. \nmove=> k2 d2 n2 k1 l1 d1 n1 [<- [k1E [<- <-] ] ].\nrepeat split.\n- by rewrite specN_add /= Plus.plus_comm.\n- by rewrite -k1E Nnat.N2Nat.inj_add Plus.plus_comm.\n- by rewrite specN_shiftr.\nrewrite !(specN_if_cmp, specN_add, specN_sub, specN_mul, \n          specN_div, specN_shiftl, specN_powerMod) //.\nset x := (_ * _)%nat; lia.\nQed.\n\n(* Compute \\sum_{i = d to infinity} (16^(d - 1 - i)) / (8 * i + k) *)\nDefinition iterR k :=\n  N.iter (p / 4) (iterG k) (StateG dN d (BigN.shiftr pS 4) 0).\n\nLemma specN_iterR k : (0 < [[k]])%nat ->\n  eq_StateG (iterR k) (NiterR (N.to_nat p) (N.to_nat d) [[k]]).\nProof.\nmove=> Pk.\nrewrite /iterR /NiterR.\nhave -> : (p / 4)%N = (N.of_nat (N.to_nat p / 4)).\n  apply: N2Z.inj.\n  by rewrite N2Z.inj_div nat_N_Z div_Zdiv ?N_nat_Z; lia.\nrewrite -Nnat.Nat2N.inj_iter.\nelim: (_ / _)%nat => [|n IH].\n  repeat split.\n    by rewrite -Z_N_nat BigN.spec_of_N N2Z.id.\n  rewrite /pS specN_shiftr /pS specN_shiftl.\n  rewrite Nat.mul_1_r.\n  by rewrite -Z_N_nat BigN.spec_of_N N2Z.id.\nby apply: specN_iterG.\nQed.\n\n(* Compute \\sum_{i = 0 to infinity} (16^(d - 1 - i)) / (8 * i + k) *)\nDefinition sumV k :=\n  let: StateF _ _ res1 := iterL k in\n  let: StateG _ _ _ res2 := iterR k in res1 + res2.\n\nLemma specN_sumV k : (0 < [[k]])%nat ->\n  [[sumV k]] = NsumV (N.to_nat p) (N.to_nat d) [[k]].\nProof.\nmove=> Pk.\nrewrite /sumV /NsumV.\nhave := specN_iterL _ Pk.\nhave := specN_iterR _ Pk.\ncase: iterL => /= k1 l1 s1.\ncase: NiterL => /= k2 l2.\ncase: iterR => /= k3 l3 d3 s3.\ncase: NiterR => /= k4 l4 s4.\nmove=> [_ [_ [_] <-] ] [_ [_] <-].\nby rewrite specN_add.\nQed.\n\n(* Extra the first digit from Plouffe formula *)\nDefinition piDigit :=\n  let delta := dN + pN / 4 + 1 in\n  if (3 <? pN) then\n    if (8 * delta <? 2 ^ (pN - 4)) then\n      let Y := (4 * (sumV 1) + \n             (9 * pS - (2 * sumV 4 + sumV 5 + sumV 6 + 4 * delta))) in\n      let v1 := (Y + 8 * delta) mod 2 ^ pN / 2 ^ (pN - 4) in\n      let v2 := Y mod 2 ^ pN / 2 ^ (pN - 4) in\n      if v1 =? v2 then Some v2 else\n      None\n    else None\n  else None.\n\nLemma specN_piDigit :\n  match piDigit with \n  | Some x =>  NpiDigit (N.to_nat p) (N.to_nat d) = Some [[x]]\n  | None => NpiDigit (N.to_nat p) (N.to_nat d) = None\n  end.\nProof.\nhave F1 : (0 < [[2]] ^ [[pN]])%nat.\n  set x := (_ ^ _)%nat.\n  suff : (2 ^ 0 <= x)%nat by rewrite /=; lia.\n  by apply: Nat.pow_le_mono_r; lia.\nhave F2 : (0 < [[2]] ^ ([[pN]] - [[4]]))%nat.\n  set x := (_ ^ _)%nat.\n  suff : (2 ^ 0 <= x)%nat by rewrite /=; lia.\n  by apply: Nat.pow_le_mono_r; lia.\nhave F3 : (0 < [[4]])%nat.\n  by have ->: [[4]] = 4%nat by []; lia.\nhave F5 : (0 < [[5]])%nat.\n  by have ->: [[5]] = 5%nat by []; lia.\nhave F6 : (0 < [[6]])%nat.\n  by have ->: [[6]] = 6%nat by []; lia.\nrewrite /piDigit /NpiDigit.\nrewrite !(specN_cmp, specN_eqb, specN_add, specN_sub, specN_mul, \n          specN_div, specN_shiftl, specN_pow, specN_mod, specN_sumV) //.\nhave-> : [[pN]] = N.to_nat p.\n  by rewrite -Z_N_nat BigN.spec_of_N N2Z.id.\ncase: (_ <? _)%nat => //.\nhave-> : [[dN]] = N.to_nat d.\n  by rewrite -Z_N_nat BigN.spec_of_N N2Z.id.\ncase: (_ <? _)%nat => //.\nrewrite Nat.mul_1_r.\ncase: beq_nat => //.\nrewrite !(specN_cmp, specN_eqb, specN_add, specN_sub, specN_mul, \n          specN_div, specN_shiftl, specN_pow, specN_mod, specN_sumV) //.\nhave-> : [[pN]] = N.to_nat p.\n  by rewrite -Z_N_nat BigN.spec_of_N N2Z.id.\nhave-> : [[dN]] = N.to_nat d.\n  by rewrite -Z_N_nat BigN.spec_of_N N2Z.id.\nby rewrite Nat.mul_1_r.\nQed.\n\nLemma piDigit_correct k : \n  piDigit = Some k -> Rdigit 16 (N.to_nat d) PI = [[k]].\nProof.\nhave := specN_piDigit.\ncase: piDigit => // n H [<-].\nby apply: NpiDigit_correct H.\nQed.\n\nEnd ComputePi.\n\n \n(* How many bits of the fixed-point like computation *)\nDefinition precision := 36%N.\n\nDefinition piDigitF d :=\n  match piDigit precision d with Some k => k | _ => 16 end.\n\nDefinition NToS n := nToS (Z.to_nat (BigN.to_Z n)).\n\n\nFixpoint rpi k n :=\n  let v := NToS (piDigitF (N.of_nat k)) in\n  match n with \n  | S n1 => String.append v (rpi (S k) n1)\n  | _ =>  v\nend.\n\n(* Compute string of the hexa representation of pi *)\nDefinition pi := rpi 0.\n\nDefinition digit n := NToS (piDigitF n).\n\n(* 1 000 000^th decimal of Pi *)\nTime Compute digit 1000000000.\n\n\n(* Pi in hexa \n\n3243F6A8885A308D313198A2E03707344A4093822299F31D00\n82EFA98EC4E6C89452821E638D01377BE5466CF34E90C6CC0A\nC29B7C97C50DD3F84D5B5B54709179216D5D98979FB1BD1310\nBA698DFB5AC2FFD72DBD01ADFB7B8E1AFED6A267E96BA7C904\n5F12C7F9924A19947B3916CF70801F2E2858EFC16636920D87\n1574E69A458FEA3F4933D7E0D95748F728EB658718BCD58821\n54AEE7B54A41DC25A59B59C30D5392AF26013C5D1B02328608\n5F0CA417918B8DB38EF8E79DCB0603A180E6C9E0E8BB01E8A3\nED71577C1BD314B2778AF2FDA55605C60E65525F3AA55AB945\n748986263E8144055CA396A2AAB10B6B4CC5C341141E8CEA15\n*)\n\n(* First 500 digits of Pi by blocks of 50 *)\nTime Compute rpi 0 49.\nTime Compute rpi 50 49.\nTime Compute rpi 100 49.\nTime Compute rpi 150 49.\nTime Compute rpi 200 49.\nTime Compute rpi 250 49.\nTime Compute rpi 300 49.\nTime Compute rpi 350 49.\nTime Compute rpi 400 49.\nTime Compute rpi 450 49.\n\n\n", "meta": {"author": "thery", "repo": "Plouffe", "sha": "c87255de87fe5a845fbed4b19932bf41f1ea5507", "save_path": "github-repos/coq/thery-Plouffe", "path": "github-repos/coq/thery-Plouffe/Plouffe-c87255de87fe5a845fbed4b19932bf41f1ea5507/CPlouffe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6598735870645854}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n(*                      Evgeny Makarov, INRIA, 2007                     *)\n(************************************************************************)\n\nRequire Import NBase.\n\nModule Homomorphism (N1 N2 : NAxiomsRecSig).\n\nLocal Notation \"n == m\" := (N2.eq n m) (at level 70, no associativity).\n\nDefinition homomorphism (f : N1.t -> N2.t) : Prop :=\n  f N1.zero == N2.zero /\\ forall n, f (N1.succ n) == N2.succ (f n).\n\nDefinition natural_isomorphism : N1.t -> N2.t :=\n  N1.recursion N2.zero (fun (n : N1.t) (p : N2.t) => N2.succ p).\n\nInstance natural_isomorphism_wd : Proper (N1.eq ==> N2.eq) natural_isomorphism.\nProof.\nunfold natural_isomorphism.\nrepeat red; intros. f_equiv; trivial.\nrepeat red; intros. now f_equiv.\nQed.\n\nTheorem natural_isomorphism_0 : natural_isomorphism N1.zero == N2.zero.\nProof.\nunfold natural_isomorphism; now rewrite N1.recursion_0.\nQed.\n\nTheorem natural_isomorphism_succ :\n  forall n : N1.t, natural_isomorphism (N1.succ n) == N2.succ (natural_isomorphism n).\nProof.\nunfold natural_isomorphism.\nintro n. rewrite N1.recursion_succ; auto with *.\nrepeat red; intros. now f_equiv.\nQed.\n\nTheorem hom_nat_iso : homomorphism natural_isomorphism.\nProof.\nunfold homomorphism, natural_isomorphism; split;\n[exact natural_isomorphism_0 | exact natural_isomorphism_succ].\nQed.\n\nEnd Homomorphism.\n\nModule Inverse (N1 N2 : NAxiomsRecSig).\n\nModule Import NBasePropMod1 := NBaseProp N1.\n(* This makes the tactic induct available. Since it is taken from\n(NBasePropFunct NAxiomsMod1), it refers to induction on N1. *)\n\nModule Hom12 := Homomorphism N1 N2.\nModule Hom21 := Homomorphism N2 N1.\n\nLocal Notation h12 := Hom12.natural_isomorphism.\nLocal Notation h21 := Hom21.natural_isomorphism.\nLocal Notation \"n == m\" := (N1.eq n m) (at level 70, no associativity).\n\nLemma inverse_nat_iso : forall n : N1.t, h21 (h12 n) == n.\nProof.\ninduct n.\nnow rewrite Hom12.natural_isomorphism_0, Hom21.natural_isomorphism_0.\nintros n IH.\nnow rewrite Hom12.natural_isomorphism_succ, Hom21.natural_isomorphism_succ, IH.\nQed.\n\nEnd Inverse.\n\nModule Isomorphism (N1 N2 : NAxiomsRecSig).\n\nModule Hom12 := Homomorphism N1 N2.\nModule Hom21 := Homomorphism N2 N1.\nModule Inverse12 := Inverse N1 N2.\nModule Inverse21 := Inverse N2 N1.\n\nLocal Notation h12 := Hom12.natural_isomorphism.\nLocal Notation h21 := Hom21.natural_isomorphism.\n\nDefinition isomorphism (f1 : N1.t -> N2.t) (f2 : N2.t -> N1.t) : Prop :=\n  Hom12.homomorphism f1 /\\ Hom21.homomorphism f2 /\\\n  forall n, N1.eq (f2 (f1 n)) n /\\\n  forall n, N2.eq (f1 (f2 n)) n.\n\nTheorem iso_nat_iso : isomorphism h12 h21.\nProof.\nunfold isomorphism.\nsplit. apply Hom12.hom_nat_iso.\nsplit. apply Hom21.hom_nat_iso.\nsplit. apply Inverse12.inverse_nat_iso.\napply Inverse21.inverse_nat_iso.\nQed.\n\nEnd Isomorphism.\n\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/Numbers/Natural/Abstract/NIso.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6598735822455601}}
{"text": "Require Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Classes.Morphisms.\n\nRequire Export NaturalTransformation.\n\nSection functor_category.\n  Polymorphic Variables(A: CatSig)(B: Cat).\n\n  Polymorphic Definition natTransId(F: FunSig A B): NatTrans F F.\n    refine {| natTrans X := id (F X) |}.\n    intros X Y f.\n    transitivity (fmap F f).\n    apply (ident_r B).\n    symmetry.\n    apply (ident_l B).\n  Defined.\n\n  Polymorphic Definition natTransComp{F G H: FunSig A B}:\n      NatTrans G H-> NatTrans F G -> NatTrans F H.\n    intros eta1 eta2.\n    refine {| natTrans X := comp (eta1 X) (eta2 X) |}.\n    intros X Y f.\n    transitivity (comp (comp (fmap H f) (eta1 X)) (eta2 X)).\n    apply (assoc B).\n    transitivity (comp (comp (eta1 Y) (fmap G f)) (eta2 X)).\n    f_equiv.\n    apply natTrans_natural.\n    transitivity (comp (eta1 Y) (comp (eta2 Y) (fmap F f))).\n    transitivity (comp (eta1 Y) (comp (fmap G f) (eta2 X))).\n    symmetry.\n    apply (assoc B).\n    f_equiv.\n    apply natTrans_natural.\n    apply (assoc B).\n  Defined.\n\n\n  Polymorphic Definition FUNSig: CatSig := {|\n    Ob                 := Fun A B;\n    Hom                := NatTrans;\n    id                 := natTransId;\n    comp F G H         := natTransComp;\n    eq_h F G eta1 eta2 := forall X, eq_h (eta1 X) (eta2 X)\n  |}.\n\n  Polymorphic Lemma FUNAx: CatAx FUNSig.\n  Proof.\n    split.\n    intros F G.\n    split.\n    intros f X.\n    reflexivity.\n    intros f g H X.\n    symmetry.\n    apply H.\n    intros f g h H1 H2 X.\n    transitivity (g X).\n    apply H1.\n    apply H2.\n    intros F G H f f' H1 g g' H2 X.\n    apply (comp_eq B).\n    apply H1.\n    apply H2.\n    intros F G f X.\n    apply (ident_r B).\n    intros F G f X.\n    apply (ident_l B).\n    intros F G H I h g f X.\n    apply (assoc B).\n  Qed.\n\n  Polymorphic Definition FUN: Cat := {|\n    catAx  := FUNAx\n  |}.\n\n  Polymorphic Definition fun_iso(F G: FUNSig)\n      (iso: forall X, Iso (F X) (G X))\n      (Hnat: natural iso):\n      Iso F G.\n    refine {|\n      iso_hom := {|\n        natTrans X := iso_hom (iso X);\n        natTrans_natural := Hnat\n      |}: @Hom FUN _ _;\n      iso_inv := {|\n        natTrans X := iso_inv (iso X);\n        natTrans_natural := iso_natural _ Hnat\n      |}\n    |}.\n    simpl.\n    split; intro X; apply (iso_prop _).\n  Defined.\nEnd functor_category.\n\nArguments natTransId   {_ _}.\nArguments natTransComp {_ _ _ _ _}.\nArguments fun_iso      {_ _}.\n", "meta": {"author": "sielenk", "repo": "coq-playground", "sha": "a1ac659ce5724fc2ae0953653570d6113d41f7f2", "save_path": "github-repos/coq/sielenk-coq-playground", "path": "github-repos/coq/sielenk-coq-playground/coq-playground-a1ac659ce5724fc2ae0953653570d6113d41f7f2/FunctorCategory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6598735748435105}}
{"text": "(**\nフィボナッチ数列についての定理の証明\n\nF(k * n) は F(k) の倍数である、など。\n\n参考：  http://parametron.blogspot.com/2017/03/blog-post.html\n*)\n\nFrom mathcomp Require Import all_ssreflect.\nFrom common Require Import ssromega.\nRequire Import Recdef.                      (* Function *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(**\nffibonacci\n *)\n\nSection Fibonacci.\n\n(**\n# 参考\n\nSFの古い版にあった even の証明に使う帰納法の例。\n*)\n  Definition nat_ind2 :\n    forall (P : nat -> Prop),\n    P 0 ->\n    P 1 ->\n    (forall n : nat, P n -> P n.+2) ->\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                           | n'.+2 => PSS n' (f n')\n                           end.\n  \n  Check nat_ind2\n    : forall P : nat -> Prop,\n      P 0 ->\n      P 1 ->\n      (forall n : nat, P n -> P n.+2) ->\n      forall n : nat, P n.\n\n(**\n# fib の証明に使う帰納法\n*)\n\n(**\n# fibonacci 関数の定義\n*)\n  (* Require Import Recdef. *)\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  (* functional induction (fib m) で使われる。 *)\n  Check fib_ind\n     : forall P : nat -> nat -> Prop,\n       (forall n : nat, n = 0 -> P 0 0) ->\n       (forall n : nat, n = 1 -> P 1 1) ->\n       (forall n m : nat,\n        n = m.+2 -> P m (fib m) -> P m.+1 (fib m.+1) -> P m.+2 (fib m + fib m.+1)) ->\n       forall n : nat, P n (fib n).\n  \n  Lemma fib_0 n : fib 0 * fib n = 0.\n  Proof.\n      by rewrite mul0n.\n  Qed.\n  \n  Lemma fib_1 n : fib 1 * fib n = fib n.\n  Proof.\n      by rewrite mul1n.\n  Qed.\n        \n  Lemma fib_2 n : fib 2 * fib n = fib n.\n  Proof.\n      by rewrite mul1n.\n  Qed.\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参考文献では、\n\n```F(m + n) = F(m) * F(n+1) + F(m-1) * F(n)```\n\n一旦、mをm+1に変更し（右辺を昇順にして）証明した。\nさらに、m ≧ 1 の条件を追加して証明した。\n*)  \n  Lemma fib_addition' m n :\n    fib (m + n + 1) = fib m * fib n + fib m.+1 * fib n.+1.\n  Proof.\n    functional induction (fib m).           (* fib_ind *)\n    - rewrite add0n addn1.\n      rewrite fib_0 fib_1 add0n.\n      done.\n      \n    - rewrite add1n addn1.\n      rewrite fib_2 fib_1.      \n      rewrite -fib_n.\n      done.\n      \n    - rewrite 2!fib_n 2!mulnDl.      \n      \n      (* F(m + n + 1) の項をまとめて置き換える *)\n      rewrite ?addnA [_ + fib m.+1 * fib n.+1]addnC ?addnA.\n      rewrite [fib m.+1 * fib n.+1 + fib m * fib n]addnC.\n      rewrite -IHn0.\n      \n      (* F(m.+1 + n + 1) の項をまとめて置き換える *)\n      rewrite -?[fib (m + n + 1) + fib m.+1 * fib n + fib m.+2 * fib n.+1]addnA.\n      rewrite -IHn1.\n      \n      have -> : m.+2 + n + 1 = (m + n + 1).+2 by ssromega.\n      have -> : m.+1 + n + 1 = (m + n + 1).+1 by ssromega.\n      rewrite -fib_n.\n      done.\n  Qed.\n  \n  Lemma fib_addition m n :\n    1 <= m -> fib (m + n) = fib m * fib n.+1 + fib m.-1 * fib n.\n  Proof.\n    move=> H.\n    have H' := fib_addition' m.-1 n.\n    rewrite -?addnA addnCA addn1 prednK in H'.\n    - rewrite addnC.\n      rewrite [fib m * fib n.+1 + fib m.-1 * fib n]addnC.\n      done.\n    - done.\n  Qed.\n  \n(**\nF(n * k) は F(k) の倍数である。\n\nn についての帰納法で解く。\n\n一旦、Coqの帰納法にあわせて、n と k ともに n+1 と k+1 として証明したのち、\nk ≧ 1 と n ≧ 1 の条件をつけて証明する。\n*)\n  Lemma dvdn_1 k m n : k %| m -> k %| m * n.\n  Proof.\n      by apply: dvdn_mulr.\n  Qed.\n  \n  Lemma dvdn_2 k m : k %| m * k.\n  Proof.\n      by apply: dvdn_mull.\n  Qed.\n  \n  Lemma fibkn_divs_fibk' k n : fib k.+1 %| fib (n.+1 * k.+1).\n  Proof.\n    elim: n.\n    - rewrite mul1n.\n      done.\n    - move=> n IHn.\n      have -> : n.+2 * k.+1 = n.+1 * k.+1 + k + 1\n        by rewrite -addn1  mulnDl mul1n -?addnA addn1.\n      rewrite fib_addition'.\n      apply: dvdn_add.\n      + by apply: dvdn_1.                   (* IHn 使う *)\n      + by apply: dvdn_2.\n    Qed.\n  \n  Lemma fibkn_divs_fibk k n : 1 <= k -> 1 <= n -> fib k %| fib (n * k).\n  Proof.\n    move=> Hk Hm.\n    have H' := fibkn_divs_fibk' k.-1 n.-1.\n    rewrite prednK in H'; last done.\n    rewrite prednK in H'; last done.\n    done.\n  Qed.\n  \n\n(**\n参考文献では、\n\n```F(n.+1) * F(n.-1) - F(n)^2 = (-1)^n```\n\nすなわち、nが偶数なら1、奇数なら-1。\n参考文献ならば、n についての単純な帰納法で証明できる。ただしP(1)を底にする。\n\nここでは、Coqの帰納法にあわせて n, n.+1, n.+2 とする（偶数なら-1、奇数なら1）とともに、\n(-1)が使えないので、偶数と奇数で、引き算の方向を逆にして、つねに1と比較する。\n\nnat_ind2 を使って証明する。\n*)  \n\n  Lemma oddn2 n : odd n.+2 = odd n.\n  Proof.\n    rewrite /=.\n    by rewrite negbK.\n  Qed.\n\n  Lemma oddn1 n : odd n.+1 = ~~ odd n.\n  Proof.\n    done.\n  Qed.\n  \n  Lemma odd_pred n : 1 <= n -> odd n.-1 = ~~ odd n.\n  Proof.\n    elim: n => [// | n IHn H].\n      by rewrite succnK oddn1 negbK.\n  Qed.\n  \n  Lemma fibfib_fib2 n : fib n.+3 * fib n.+1 - fib n.+2 * fib n.+2 =\n                        fib n.+1 * fib n.+1 - fib n.+2 * fib n.\n  Proof.\n    rewrite [fib n.+3]fib_n.\n    rewrite {2}[fib n.+2]fib_n.\n    rewrite 2!mulnDl.\n    rewrite [fib n.+2 * fib n.+1]mulnC.\n    rewrite subnDr.\n    rewrite [fib n.+2 * fib n]mulnC.\n    done.\n  Qed.\n  \n  Lemma fib2_fibfib n : fib n.+2 * fib n.+2 - fib n.+3 * fib n.+1 =\n                        fib n.+2 * fib n - fib n.+1 * fib n.+1.\n  Proof.\n    rewrite [fib n.+3]fib_n.\n    rewrite {1}[fib n.+2]fib_n.\n    rewrite 2!mulnDl.\n    rewrite [fib n.+2 * fib n.+1]mulnC.\n    rewrite subnDr.\n    rewrite [fib n.+2 * fib n]mulnC.\n    done.\n  Qed.\n  \n  Lemma fib_o n :\n    fib n.+4 * fib n.+2 - fib n.+3 * fib n.+3 =\n    fib n.+2 * fib n - fib n.+1 * fib n.+1.\n  Proof.\n    rewrite fibfib_fib2.\n    rewrite fib2_fibfib.\n    done.\n  Qed.\n\n  Lemma fib_e n :\n    fib n.+3 * fib n.+3 - fib n.+4 * fib n.+2 =\n    fib n.+1 * fib n.+1 - fib n.+2 * fib n.\n  Proof.\n    rewrite fib2_fibfib.\n    rewrite fibfib_fib2.\n    done.\n  Qed.\n  \n  Lemma fib_e_o' n :\n    if odd n then\n      fib n.+2 * fib n - (fib n.+1)^2 = 1\n    else\n      (fib n.+1)^2 - fib n.+2 * fib n = 1.\n  Proof.\n    rewrite -mulnn.\n    elim/nat_ind2 : n => [/= | /= | n IHn].\n    - by ssromega.\n    - by ssromega.\n    - by rewrite oddn2 fib_o fib_e.\n  Qed.\n\n  Lemma fib_e_o n :\n    1 <= n ->\n    if odd n then\n      (fib n)^2 - fib n.+1 * fib n.-1 = 1\n    else\n      fib n.+1 * fib n.-1 - (fib n)^2 = 1.\n  Proof.\n    move=> Hn.\n    have H' := fib_e_o' n.-1.\n    rewrite prednK in H'; last done.\n    rewrite odd_pred in H' ; last done.\n      by rewrite if_neg in H'.\n  Qed.\n  \nEnd Fibonacci.\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.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.6598704377818545}}
{"text": "Require Export Reals.\n\nRequire Import Psatz.\n\n(******************************************)\n(** Relevant lemmas from Rcomplements.v. **)\n(******************************************)\n\n\nOpen Scope R_scope.\n\nLemma Rle_minus_l : forall a b c,(a - c <= b <-> a <= b + c). Proof. intros. lra. Qed.\nLemma Rlt_minus_r : forall a b c,(a < b - c <-> a + c < b). Proof. intros. lra. Qed.\nLemma Rlt_minus_l : forall a b c,(a - c < b <-> a < b + c). Proof. intros. lra. Qed.\nLemma Rle_minus_r : forall a b c,(a <= b - c <-> a + c <= b). Proof. intros. lra. Qed.\nLemma Rminus_le_0 : forall a b, a <= b <-> 0 <= b - a. Proof. intros. lra. Qed.\nLemma Rminus_lt_0 : forall a b, a < b <-> 0 < b - a. Proof. intros. lra. Qed.\n\n(* Automation *)\n\nLemma Rminus_unfold : forall r1 r2, (r1 - r2 = r1 + -r2). Proof. reflexivity. Qed.\nLemma Rdiv_unfold : forall r1 r2, (r1 / r2 = r1 */ r2). Proof. reflexivity. Qed.\n\nHint Rewrite Rminus_unfold Rdiv_unfold Ropp_0 Ropp_involutive Rplus_0_l Rplus_0_r \n             Rmult_0_l Rmult_0_r Rmult_1_l Rmult_1_r : R_db.\nHint Rewrite <- Ropp_mult_distr_l Ropp_mult_distr_r : R_db.\nHint Rewrite Rinv_l Rinv_r sqrt_sqrt using lra : R_db.\n\nNotation \"√ n\" := (sqrt n) (at level 20) : R_scope.\n\n(* Useful Lemmas *)\n\nLemma Rmult_div_assoc : forall (x y z : R), x * (y / z) = x * y / z.\nProof. intros. unfold Rdiv. rewrite Rmult_assoc. reflexivity. Qed.\n\nLemma Rmult_div : forall r1 r2 r3 r4 : R, r2 <> 0 -> r4 <> 0 -> \n  r1 / r2 * (r3 / r4) = r1 * r3 / (r2 * r4). \nProof. intros. unfold Rdiv. rewrite Rinv_mult_distr; trivial. lra. Qed.\n\nLemma Rdiv_cancel :  forall r r1 r2 : R, r1 = r2 -> r / r1 = r / r2.\nProof. intros. rewrite H. reflexivity. Qed.\n\nLemma Rsum_nonzero : forall r1 r2 : R, r1 <> 0 \\/ r2 <> 0 -> r1 * r1 + r2 * r2 <> 0. \nProof.\n  intros.\n  replace (r1 * r1)%R with (r1 ^ 2)%R by lra.\n  replace (r2 * r2)%R with (r2 ^ 2)%R by lra.\n  specialize (pow2_ge_0 (r1)). intros GZ1.\n  specialize (pow2_ge_0 (r2)). intros GZ2.\n  destruct H.\n  - specialize (pow_nonzero r1 2 H). intros NZ. lra.\n  - specialize (pow_nonzero r2 2 H). intros NZ. lra.\nQed.\n\n\nLemma Rpow_le1: forall (x : R) (n : nat), 0 <= x <= 1 -> x ^ n <= 1.\nProof.\n  intros; induction n.\n  - simpl; lra.\n  - simpl.\n    rewrite <- Rmult_1_r.\n    apply Rmult_le_compat; try lra.\n    apply pow_le; lra.\nQed.\n    \n(* The other side of Rle_pow, needed below *)\nLemma Rle_pow_le1: forall (x : R) (m n : nat), 0 <= x <= 1 -> (m <= n)%nat -> x ^ n <= x ^ m.\nProof.\n  intros x m n [G0 L1] L.\n  remember (n - m)%nat as p.\n  replace n with (m+p)%nat in * by lia.\n  clear -G0 L1.\n  rewrite pow_add.\n  rewrite <- Rmult_1_r.\n  apply Rmult_le_compat; try lra.\n  apply pow_le; trivial.\n  apply pow_le; trivial.\n  apply Rpow_le1; lra.\nQed.\n\n(****************)\n(* Square Roots *)\n(****************)\n\nLemma pow2_sqrt : forall x:R, 0 <= x -> (√ x) ^ 2 = x.\nProof. intros; simpl; rewrite Rmult_1_r, sqrt_def; auto. Qed.\n\nLemma sqrt_pow : forall (r : R) (n : nat), (0 <= r)%R -> (√ (r ^ n) = √ r ^ n)%R.\nProof.\n  intros r n Hr.\n  induction n.\n  simpl. apply sqrt_1.\n  rewrite <- 2 tech_pow_Rmult.\n  rewrite sqrt_mult_alt by assumption.\n  rewrite IHn. reflexivity.\nQed.\n\nLemma pow2_sqrt2 : (√ 2) ^ 2 = 2.\nProof. apply pow2_sqrt; lra. Qed.\n\nLemma pown_sqrt : forall (x : R) (n : nat), \n  0 <= x -> √ x ^ (S (S n)) = x * √ x ^ n.\nProof.\n  intros. simpl. rewrite <- Rmult_assoc. rewrite sqrt_sqrt; auto.\nQed.  \n\nLemma sqrt_neq_0_compat : forall r : R, 0 < r -> √ r <> 0.\nProof. intros. specialize (sqrt_lt_R0 r). lra. Qed.\n\nLemma sqrt_inv : forall (r : R), 0 < r -> √ (/ r) = (/ √ r)%R.\nProof.\n  intros.\n  replace (/r)%R with (1/r)%R by lra.\n  rewrite sqrt_div_alt, sqrt_1 by lra.\n  lra.\nQed.  \n\nLemma sqrt2_div2 : (√ 2 / 2)%R = (1 / √ 2)%R.\nProof.\n   field_simplify_eq; try (apply sqrt_neq_0_compat; lra).\n   rewrite pow2_sqrt2; easy.\nQed.\n\nLemma sqrt2_inv : √ (/ 2) = (/ √ 2)%R.\nProof. apply sqrt_inv; lra. Qed.  \n\nLemma sqrt_sqrt_inv : forall (r : R), 0 < r -> (√ r * √ / r)%R = 1.\nProof. \n  intros. \n  rewrite sqrt_inv; trivial. \n  rewrite Rinv_r; trivial. \n  apply sqrt_neq_0_compat; easy.\nQed.\n\nLemma sqrt2_sqrt2_inv : (√ 2 * √ / 2)%R = 1.\nProof. apply sqrt_sqrt_inv. lra. Qed.\n\nLemma sqrt2_inv_sqrt2 : ((√ / 2) * √ 2)%R = 1.\nProof. rewrite Rmult_comm. apply sqrt2_sqrt2_inv. Qed.\n\nLemma sqrt2_inv_sqrt2_inv : ((√ / 2) * (√ / 2) = /2)%R.\nProof. \n  rewrite sqrt2_inv. field_simplify. \n  rewrite pow2_sqrt2. easy. \n  apply sqrt_neq_0_compat; lra. \nQed.\n\n(* Automation *)\nLtac R_field_simplify := repeat field_simplify_eq [pow2_sqrt2 sqrt2_inv].\nLtac R_field := R_field_simplify; easy.\n\n(* Trigonometry *)\n\nLemma sin_upper_bound_aux : forall x : R, 0 < x < 1 -> sin x <= x.\nProof.\n  intros x H.\n  specialize (SIN_bound x) as B.\n    destruct (SIN x) as [_ B2]; try lra.\n    specialize PI2_1 as PI1. lra.\n    unfold sin_ub, sin_approx in *.\n    simpl in B2.\n    unfold sin_term at 1 in B2.\n    simpl in B2.\n    unfold Rdiv in B2.\n    rewrite Rinv_1, Rmult_1_l, !Rmult_1_r in B2.\n    (* Now just need to show that the other terms are negative... *)\n    assert (sin_term x 1 + sin_term x 2 + sin_term x 3 + sin_term x 4 <= 0); try lra.\n    unfold sin_term.\n    remember (INR (fact (2 * 1 + 1))) as d1.\n    remember (INR (fact (2 * 2 + 1))) as d2.\n    remember (INR (fact (2 * 3 + 1))) as d3.\n    remember (INR (fact (2 * 4 + 1))) as d4.\n    assert (0 < d1) as L0.\n    { subst. apply lt_0_INR. apply lt_O_fact. }\n    assert (d1 <= d2) as L1.\n    { subst. apply le_INR. apply fact_le. simpl; lia. }\n    assert (d2 <= d3) as L2.\n    { subst. apply le_INR. apply fact_le. simpl; lia. }\n    assert (d3 <= d4) as L3.\n    { subst. apply le_INR. apply fact_le. simpl; lia. }\n    simpl.    \n    ring_simplify.\n    assert ( - (x * (x * (x * 1)) / d1) + x * (x * (x * (x * (x * 1)))) / d2 <= 0).\n    rewrite Rplus_comm.\n    apply Rle_minus.\n    field_simplify; try lra.\n    assert (x ^ 5 <= x ^ 3).\n    { apply Rle_pow_le1; try lra; try lia. }\n    apply Rmult_le_compat; try lra.\n    apply pow_le; lra.\n    left. apply Rinv_0_lt_compat. lra.\n    apply Rinv_le_contravar; lra.\n    unfold Rminus.\n    assert (- (x * (x * (x * (x * (x * (x * (x * 1)))))) / d3) +\n            x * (x * (x * (x * (x * (x * (x * (x * (x * 1)))))))) / d4 <= 0).\n    rewrite Rplus_comm.\n    apply Rle_minus.\n    field_simplify; try lra.\n    assert (x ^ 9 <= x ^ 7).\n    { apply Rle_pow_le1; try lra; try lia. }\n    apply Rmult_le_compat; try lra.\n    apply pow_le; lra.\n    left. apply Rinv_0_lt_compat. lra.\n    apply Rinv_le_contravar; lra.\n    lra.\nQed.\n\nLemma sin_upper_bound : forall x : R, Rabs (sin x) <= Rabs x.\nProof.\n  intros x.  \n  specialize (SIN_bound x) as B.\n  destruct (Rlt_or_le (Rabs x) 1).\n  (* abs(x) > 1 *)\n  2:{ apply Rabs_le in B. lra. }\n  destruct (Rtotal_order x 0) as [G | [E| L]].\n  - (* x < 0 *)\n    rewrite (Rabs_left x) in * by lra.\n    rewrite (Rabs_left (sin x)).\n    2:{ apply sin_lt_0_var; try lra.\n        specialize PI2_1 as PI1.\n        lra. }\n    rewrite <- sin_neg.\n    apply sin_upper_bound_aux.\n    lra.\n  - (* x = 0 *)\n    subst. rewrite sin_0. lra.\n  - rewrite (Rabs_right x) in * by lra.\n    rewrite (Rabs_right (sin x)).\n    2:{ apply Rle_ge.\n        apply sin_ge_0; try lra.\n        specialize PI2_1 as PI1. lra. }\n    apply sin_upper_bound_aux; lra.\nQed.    \n\n\nHint Rewrite sin_0 sin_PI4 sin_PI2 sin_PI cos_0 cos_PI4 cos_PI2 cos_PI sin_neg cos_neg : trig_db.\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/RealAux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867729389246, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.6598704139480762}}
{"text": "From Cat Require Import Imports Category Preorder Monoid Poset Isomorphism.\nRequire Import FunctionalExtensionality.\nRequire Import ProofIrrelevance.\nSet Universe Polymorphism.\n(** Category theoretic properties *)\n\n(** Terminal Object *)\n\nClass Terminal (C: Category) (tobj: @obj C): Type :=\n{\n  tmorph : forall X, @arrow C tobj X; \n  tmorphu: forall X (f g: @arrow C tobj X), f = g\n}.\n\n(* Terminal Object Exercise*)\n\nClass Triple: Type :=\n{\n  us: Set;\n  xo: us;\n  xs: us -> us\n}.\n\nClass TripleMap (T1 T2: Triple): Type :=\n{\n  um   : @us T1 -> @us T2;\n  umax1: um (@xo T1) = @xo T2;\n  umax2: forall x, um (@xs T1 x) = (@xs T2) (um x)\n}. \n\nLemma TripleMapEq: forall {T1 T2: Triple} (F G: TripleMap T1 T2), \n  @um T1 T2 F = @um T1 T2 G -> F = G.\nProof. intros (T1, xo1, xs1) (T2, xo2, xs2) (f, fax1, fax2) (g, gax1, gax2) H.\n       simpl in *.\n       subst.\n       destruct (proof_irrelevance _ fax2 gax2).\n       f_equal.\n       apply (@UIP _ _ _ eq_refl gax1).\nQed.\n\nDefinition TripleCategory: Category.\nProof. unshelve econstructor.\n       - exact Triple.\n       - intros T1 T2. exact (TripleMap T2 T1).\n       - simpl. intro T.\n         unshelve econstructor.\n         + intro a. exact a.\n         + simpl. reflexivity.\n         + simpl. intro a. reflexivity.\n       - intros (X, x0, xS) (Y, y0, yS) (Z, z0, ZS) (g, gax1, gax2) (f, fax1, fax2).\n         unshelve econstructor.\n         + simpl in *. intro a. exact (g (f a)).\n         + simpl in *. rewrite fax1, gax1.\n           reflexivity.\n         + simpl in *. intro x.\n           rewrite fax2, gax2.\n           reflexivity.\n       - repeat intro. now subst.\n       - simpl. intros.\n         apply TripleMapEq.\n         destruct a as (X, x0, xS).\n         destruct b as (Y, y0, yS).\n         destruct c as (Z, z0, zS).\n         destruct d as (W, w0, wS).\n         destruct f as (f, fax1, fax2).\n         destruct g as (g, gax1, gax2).\n         destruct h as (h, hax1, hax2).\n         simpl in *. \n         reflexivity.\n       - simpl. intros.\n         apply TripleMapEq.\n         destruct a as (X, x0, xS).\n         destruct b as (Y, y0, yS).\n         destruct f as (f, fax1, fax2).\n         simpl in *.\n         reflexivity.\n       - simpl. intros.\n         apply TripleMapEq.\n         destruct a as (X, x0, xS).\n         destruct b as (Y, y0, yS).\n         destruct f as (f, fax1, fax2).\n         simpl in *.\n         reflexivity.\nDefined.\n\nClass hasTerminal (C: Category): Type :=\n{\n  tobj: @obj C;\n  hast: Terminal C tobj \n}.\n\nLemma hasTerminalTripleCategory: hasTerminal TripleCategory.\nProof. unshelve econstructor.\n       - unshelve econstructor.\n         + exact unit.\n         + exact tt.\n         + exact (id).\n       - unshelve econstructor.\n         + simpl. intros (X, x0, xS).\n           unshelve econstructor.\n           ++ simpl. intro x. exact tt.\n           ++ simpl. reflexivity.\n           ++ simpl. intro x. reflexivity.\n         + simpl. intros (X, x0, xS).\n           intros (f, fax1, fax2) (g, gax1, gax2).\n           simpl in *.\n           apply TripleMapEq.\n           simpl.\n           apply functional_extensionality.\n           intro x.\n           destruct (f x).\n           destruct (g x).\n           reflexivity.\nQed.\n\nDefinition tunit: Terminal SetCat unit.\nProof. unshelve econstructor.\n       - simpl. intros X x. exact tt.\n       - simpl. intros X f g.\n         apply functional_extensionality.\n         intro x.\n         destruct (f x).\n         destruct (g x).\n         reflexivity.\nDefined.\n\nLemma hasTerminalSetCat: hasTerminal SetCat.\nProof. unshelve econstructor.\n       - exact unit.\n       - apply tunit.\nDefined.\n\nDefinition unit_eqb (a b: unit) := true.\n(*   match a, b with\n    | tt, tt => true\n  end. *)\n\nDefinition UPreOrder: PreOrder.\nProof. unshelve econstructor.\n       - exact unit.\n       - intros a b. exact (unit_eqb a b).\n       - simpl. intro x. unfold unit_eqb. reflexivity.\n       - simpl. intros. unfold unit_eqb. reflexivity.\nDefined.\n\nLemma umapeq: forall A (f g: A -> unit), f = g.\nProof. intros.\n       apply functional_extensionality.\n       intro a.\n       destruct (f a).\n       destruct (g a).\n       reflexivity.\nDefined.\n\n\nDefinition tunitPre: Terminal PreOrderCat UPreOrder.\nProof. unshelve econstructor.\n       - simpl.\n         intros (A, le, r, t).\n         unshelve econstructor.\n         + simpl. intro a.\n           exact tt.\n         + simpl. intros. reflexivity.\n       - simpl. intros A F G.\n         apply PreOrderMapEq.\n         destruct F as (f, fax).\n         destruct G as (g, gax).\n         simpl in *.\n         apply umapeq.\nDefined.\n\nDefinition hasTerminalPreOrderCat: hasTerminal PreOrderCat.\nProof. unshelve econstructor.\n       - exact UPreOrder.\n       - exact tunitPre.\nDefined.\n\nDefinition UPoset: PoSet.\nProof. unshelve econstructor.\n       - exact UPreOrder.\n       - simpl. intros.\n         destruct x, y. \n         reflexivity.\nDefined.\n\nDefinition tunitPoset: Terminal Poset UPoset.\nProof. unshelve econstructor.\n       - simpl.\n         intros ((A, le, r, t), ant).\n         unshelve econstructor.\n         + simpl.\n           unshelve econstructor.\n           ++ simpl. intro a.\n              exact tt.\n           ++ simpl. intros. reflexivity.\n       - simpl. intros A f g.\n         destruct A as ((A, le, r, t), a).\n         destruct f, g.\n         simpl in *.\n         destruct posetmap, posetmap0.\n         simpl in *.\n         specialize (umapeq A posmap posmap0); intro.\n         subst.\n         f_equal. f_equal.\n         destruct (proof_irrelevance _ pohrelmap pohrelmap0).\n         reflexivity.\nDefined.\n\nDefinition UMonoid: Monoid.\nProof. unshelve econstructor.\n       - exact unit.\n       - exact tt.\n       - intros a b. exact tt.\n       - simpl. intros x y z. reflexivity.\n       - simpl. intros.\n         destruct x.\n         simpl. reflexivity.\n       - simpl. intros.\n         destruct x. reflexivity.\nDefined.\n\n\nDefinition tunitMon: Terminal Mon UMonoid.\nProof. unshelve econstructor.\n       - simpl. intro M1.\n         destruct M1 as (M1, e1, M1f, M1ob1, M1ob2, M1ob3).\n         unshelve econstructor.\n         + simpl. intro a.\n           exact tt.\n         + simpl. reflexivity.\n         + intros x y. simpl. reflexivity.\n       - simpl. intros A F G.\n         apply MonoidMapEq.\n         destruct A as (M1, e1, M1f, M1ob1, M1ob2, M1ob3).\n         destruct F as (f, fax1, fax2).\n         destruct G as (g, gax1, gax2).\n         simpl in *.\n         apply functional_extensionality.\n         intro x.\n         destruct (f x).\n         destruct (g x).\n         reflexivity.\nDefined.\n\nClass top (P: PreOrder): Type :=\n{\n   ptop : @pos P; \n   potob: forall (x: @pos P), (@pohrel P x ptop) = true\n}.\n\nLemma tPreOrderDetCat: forall (P: PreOrder) (t: top P), \n  Terminal (PreOrderDetCat P) (@ptop P t).\nProof. intros (P, le, r, t) (u, ax1).\n       unshelve econstructor.\n       - intro y. simpl in *.\n         unfold PreOrderICMap.\n         simpl.\n         rewrite ax1. exact tt.\n       - simpl in *.\n         intros.\n         unfold PreOrderICMap in *.\n         simpl in *.\n         destruct (le X u).\n         destruct f, g. easy.\n         destruct f, g.\nDefined.\n\nLemma hasTerminalPreOrderDetCat (P: PreOrder) (t: top P): hasTerminal (PreOrderDetCat P).\nProof. unshelve econstructor.\n       - exact (@ptop P t).\n       - apply tPreOrderDetCat.\nDefined.\n\nClass MonoidSingl: Type :=\n{\n   msingl  : Monoid;\n   msinglob: @mons msingl = unit\n}.\n\nLemma SingletonMonoid: Monoid.\nProof. unshelve econstructor.\n       - exact unit.\n       - exact tt.\n       - intros a b. exact tt.\n       - simpl. intros a b c. reflexivity.\n       - simpl. intro x. destruct x. reflexivity.\n       - simpl. intro x. destruct x. reflexivity.\nDefined.\n\nClass SingletonList (A: Type) (a: A): Type :=\n{\n  sl  : list A;\n  obsl: (cons a nil) = sl\n}.\n\nLemma SingletonListMonoid: Monoid.\nProof. unshelve econstructor.\n       - exact (SingletonList unit tt).\n       - unshelve econstructor.\n         + exact (cons tt nil).\n         + intros. easy.\n       - intros (l1, a) (l2, b).\n         unshelve econstructor.\n         + exact (cons tt nil).\n         + easy.\n       - simpl. intros (l1, a) (l2, b) (l3, c).  reflexivity.\n       - simpl. intros (l, x). subst. reflexivity.\n       - simpl. intros (l, x). subst. reflexivity.\nDefined.\n\nLemma MonoidDetCat_SingletonMonoid_Terminal: Terminal (MonoidDetCat SingletonMonoid) tt.\nProof. unshelve econstructor.\n       - simpl in *. intro t. exact tt.\n       - simpl in *. intros t f g. destruct f, g. easy.\nDefined. \n\nLemma tMonoidDetCat: forall (M: MonoidSingl), Terminal (MonoidDetCat (@msingl M)) tt.\nProof. intros ((M, e, ob, a, ax1, ax2), ax3).\n       unshelve econstructor.\n       - simpl in *. intro t. subst. exact tt.\n       - simpl in *. intros t f g. subst. destruct f, g. easy.\nDefined.\n\n\nLemma TerminalIso0: forall (C: Category) (T T': @obj C) (t: Terminal C T), @Isomorphic C T T' -> Terminal C T'.\nProof. intros C T T' (Tax1, Tax2) (f, (finv, fax1, fax2)).\n       simpl in *.\n       unshelve econstructor.\n       - simpl. intro a.\n         exact (f o Tax1 a).\n       - simpl. intros a g h.\n         specialize (Tax2 a (finv o g) (finv o h)).\n         assert (f o finv o g = f o finv o h).\n         { rewrite <- assoc. rewrite Tax2. rewrite assoc. easy. }\n         rewrite fax1, !identity_f in H. easy.\nQed.\n\nLemma TerminalIso: forall (C: Category) (T T': @obj C) (t: Terminal C T) (t': Terminal C T'), @Isomorphic C T T'.\nProof. intros C T T' (tax1, tax2) (rax1, rax2).\n       simpl in *.\n       unshelve econstructor.\n       - exact (rax1 T).\n       - unshelve econstructor.\n         + exact (tax1 T').\n         + apply rax2.\n         + apply tax2.\nQed.\n\nLemma TerminalIsoUnique: forall (C: Category) (T T': @obj C) (t: Terminal C T) (t': Terminal C T'),\n  { f: @arrow C T T' & \n    Isomorphism C f -> (forall g: @arrow C T T', Isomorphism C g -> f = g) }.\nProof. intros C T T' (tax1, tax2) (rax1, rax2).\n       simpl in *.\n       exists (tax1 T').\n       intros (finv, fax1, fax2) g (ginv, gax1, gax2).\n       apply tax2.\nQed.\n\nLemma TerminalIsoUniqueA: forall (C: Category) (T T': @obj C) (t: Terminal C T) (t': Terminal C T') \n  (f g: @arrow C T T'), Isomorphism C f -> Isomorphism C g -> f = g.\nProof. intros C T T' (tax1, tax2) (rax1, rax2) f g\n       (finv, fax1, fax2) (ginv, gax1, gax2).\n       simpl in *.\n       apply tax2.\nQed.\n\nLemma TerminalIsoUniqueAlt: forall (C: Category) (T T': @obj C) (t: Terminal C T) (t': Terminal C T') \n  (f g: @arrow C T T') (i j:Isomorphism C f), i = j.\nProof. intros C T T' (tax1, tax2) (rax1, rax2) f g\n       (finv, fax1, fax2) (ginv, gax1, gax2).\n       simpl in *.\n       apply IsomorphismEq.\n       simpl.\n       apply rax2.\nQed.\n\n", "meta": {"author": "ekiciburak", "repo": "CatTheo", "sha": "f80ac2700ca09eaff5c1bd6addcbf9ca2fdbb2fd", "save_path": "github-repos/coq/ekiciburak-CatTheo", "path": "github-repos/coq/ekiciburak-CatTheo/CatTheo-f80ac2700ca09eaff5c1bd6addcbf9ca2fdbb2fd/Terminal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.659870409397296}}
{"text": "(* This file is generated by Why3's Coq driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import ZArith.\nRequire Import Rbase.\nAxiom Max_is_ge : forall (x:Z) (y:Z), (x <= (Zmax x y))%Z /\\\n  (y <= (Zmax x y))%Z.\n\nAxiom Max_is_some : forall (x:Z) (y:Z), ((Zmax x y) = x) \\/ ((Zmax x y) = y).\n\nAxiom Min_is_le : forall (x:Z) (y:Z), ((Zmin x y) <= x)%Z /\\\n  ((Zmin x y) <= y)%Z.\n\nAxiom Min_is_some : forall (x:Z) (y:Z), ((Zmin x y) = x) \\/ ((Zmin x y) = y).\n\nAxiom Max_x : forall (x:Z) (y:Z), (y <= x)%Z -> ((Zmax x y) = x).\n\nAxiom Max_y : forall (x:Z) (y:Z), (x <= y)%Z -> ((Zmax x y) = y).\n\nAxiom Min_x : forall (x:Z) (y:Z), (x <= y)%Z -> ((Zmin x y) = x).\n\nAxiom Min_y : forall (x:Z) (y:Z), (y <= x)%Z -> ((Zmin x y) = y).\n\nAxiom Max_sym : forall (x:Z) (y:Z), (y <= x)%Z -> ((Zmax x y) = (Zmax y x)).\n\nAxiom Min_sym : forall (x:Z) (y:Z), (y <= x)%Z -> ((Zmin x y) = (Zmin y x)).\n\nInductive list (a:Type) :=\n  | Nil : list a\n  | Cons : a -> (list a) -> list a.\nSet Contextual Implicit.\nImplicit Arguments Nil.\nUnset Contextual Implicit.\nImplicit Arguments Cons.\n\nParameter length: forall (a:Type), (list a)  -> Z.\n\nImplicit Arguments length.\n\nAxiom length_def : forall (a:Type), forall (l:(list a)),\n  match l with\n  | Nil  => ((length l) = 0%Z)\n  | Cons _ r => ((length l) = (1%Z + (length r))%Z)\n  end.\n\nAxiom Length_nonnegative : forall (a:Type), forall (l:(list a)),\n  (0%Z <= (length l))%Z.\n\nAxiom Length_nil : forall (a:Type), forall (l:(list a)),\n  ((length l) = 0%Z) <-> (l = (Nil:(list a))).\n\nParameter char : Type.\n\nDefinition word  := (list char).\n\nInductive dist : (list char) -> (list char) -> Z -> Prop :=\n  | dist_eps : (dist (Nil:(list char)) (Nil:(list char)) 0%Z)\n  | dist_add_left : forall (w1:(list char)) (w2:(list char)) (n:Z), (dist w1\n      w2 n) -> forall (a:char), (dist (Cons a w1) w2 (n + 1%Z)%Z)\n  | dist_add_right : forall (w1:(list char)) (w2:(list char)) (n:Z), (dist w1\n      w2 n) -> forall (a:char), (dist w1 (Cons a w2) (n + 1%Z)%Z)\n  | dist_context : forall (w1:(list char)) (w2:(list char)) (n:Z), (dist w1\n      w2 n) -> forall (a:char), (dist (Cons a w1) (Cons a w2) n).\n\nDefinition min_dist(w1:(list char)) (w2:(list char)) (n:Z): Prop := (dist w1\n  w2 n) /\\ forall (m:Z), (dist w1 w2 m) -> (n <= m)%Z.\n\nAxiom min_dist_equal : forall (w1:(list char)) (w2:(list char)) (a:char)\n  (n:Z), (min_dist w1 w2 n) -> (min_dist (Cons a w1) (Cons a w2) n).\n\nAxiom min_dist_diff : forall (w1:(list char)) (w2:(list char)) (a:char)\n  (b:char) (m:Z) (p:Z), (~ (a = b)) -> ((min_dist (Cons a w1) w2 p) ->\n  ((min_dist w1 (Cons b w2) m) -> (min_dist (Cons a w1) (Cons b w2)\n  ((Zmin m p) + 1%Z)%Z))).\n\nTheorem min_dist_eps : forall (w:(list char)) (a:char) (n:Z), (min_dist w\n  (Nil:(list char)) n) -> (min_dist (Cons a w) (Nil:(list char))\n  (n + 1%Z)%Z).\n(* YOU MAY EDIT THE PROOF BELOW *)\nunfold min_dist.\nintros w a n [H1 H2].\n split.\napply dist_add_left.\nassumption.\nintros m Hm; inversion Hm.\ngeneralize (H2 n0 H5).\nintros; omega.\nQed.\n(* DO NOT EDIT BELOW *)\n\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/examples/edit_distance/edit_distance_Word_min_dist_eps_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846387, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6598540116687674}}
{"text": "Require Export OrderSig.\nRequire Export PQSig.\n\nInductive preT' A :=\n  Node : A -> nat -> list (preT' A) -> preT' A.\n\nDefinition preQ' A := list (preT' A).\n\nModule SkewBinaryHeap (OO:Order) <: PQSig.\n\n\n\nSet Implicit Arguments.\n\nModule O := OO.\nExport O.\nRequire Export Arith.\nRequire Export List.\nRequire Export Program.\nRequire Export Omega.\nRequire Export Recdef.\nRequire Export Coq.Program.Wf.\nRequire Export caseTactic.\n\n(* TODO: stability *)\n\nDefinition preT := preT' A.\nDefinition preQ := list preT.\n\nDefinition root (x:preT) :=\n  match x with\n    | Node v _ _ => v\n  end.\n\nDefinition rank (x:preT) :=\n  match x with\n    | Node _ r _ => r\n  end.\n\nDefinition link (x y:preT) :=\n  match x, y with\n    | Node v n p, Node w m q =>\n      if LEQ v w \n        then Node _ v (S n) (y::p)\n        else Node _ w (S m) (x::q)\n  end.\n\nDefinition skewLink (x y z:preT) :=\n  match x, y, z with\n    | Node a i p, \n      Node b j q,\n      Node c k r =>\n      if LEQ a b\n        then if LEQ a c\n          then Node _ a (S j) [y;z]\n          else Node _ c (S k) (x::y::r)\n        else if LEQ b c\n          then Node _ b (S j) (x::z::q)\n          else Node _ c (S k) (x::y::r)\n  end.\n\nFixpoint ins t xs :=\n  match xs with\n    | [] => [t]\n    | y::ys =>\n      match nat_compare (rank t) (rank y) with\n        | Lt => t::xs\n        | _ => ins (link t y) ys\n      end\n  end.\n\nDefinition uniqify xs :=\n  match xs with\n    | [] => []\n    | y::ys => ins y ys\n  end.\n\nDefinition combLen (xy:preQ * preQ) := \n  let (x,y) := xy in\n    List.length x + List.length y.\n\nFunction meldUniq (xy:preQ * preQ) {measure combLen xy} : preQ :=\n  match xy with\n    | ([],y) => y\n    | (x,[]) => x\n    | (p::ps,q::qs) => \n      match nat_compare (rank p) (rank q) with\n        | Lt => p :: meldUniq (ps, q::qs)\n        | Gt => q :: meldUniq (p::ps, qs)\n        | Eq => ins (link p q) (meldUniq (ps,qs))\n      end\n  end.\nProof.\n  intros; subst.\n  unfold combLen.\n  simpl; omega.\n\n  intros; subst.\n  unfold combLen.\n  simpl; omega.\n\n  intros; subst.\n  unfold combLen.\n  simpl; omega.\nQed.\n\nDefinition preEmpty : preQ := [].\n\nDefinition preInsert x ys :=\n  match ys with\n    | z1::z2::zr =>\n      if beq_nat (rank z1) (rank z2)\n        then skewLink (Node _ x 0 []) z1 z2 :: zr\n        else Node _ x 0 [] :: ys\n    | _ => Node _ x 0 [] :: ys\n  end.\n\nDefinition preMeld x y :=\n  meldUniq (uniqify x, uniqify y).\n\nFixpoint preFindMinHelp x xs :=\n  match xs with \n    | [] => root x\n    | y::ys => \n      let z := preFindMinHelp y ys in\n        let w := root x in\n          if LEQ w z\n            then w\n            else z\n  end.\n\nDefinition preFindMin x :=\n  match x with\n    | [] => None\n    | y::ys => Some (preFindMinHelp y ys)\n  end.\n\nFixpoint getMin x xs :=\n  match xs with\n    | [] => (x,[])\n    | y::ys =>\n      let (t,ts) := getMin y ys in\n        if LEQ (root x) (root t)\n          then (x,xs)\n          else (t,x::ts)\n  end.\n\nFixpoint split t x c :=\n  match c with\n    | [] => (t,x)\n    | d::ds => \n      match rank d with\n        | 0 => split t ((root d)::x) ds\n        | _ => split (d::t) x ds\n      end\n  end.\n\nDefinition preDeleteMin x :=\n  match x with\n    | [] => []\n    | y::ys =>\n      match getMin y ys with\n        | (Node _ _ c,t) =>\n          let (p,q) := split [] [] c in\n            fold_right preInsert (preMeld t p) q\n      end\n  end.\n\nDefinition preExtractMin x :=\n  match x with\n    | [] => None\n    | y::ys => Some\n      match getMin y ys with\n        | (Node v _ c,t) => (v,\n          let (p,q) := split [] [] c in\n            fold_right preInsert (preMeld t p) q)\n      end\n  end.\n\n\n(*\nExtraction preDeleteMin.\nExtraction Language Haskell.\nExtraction Inline and_rect sig_rect meldUniq_terminate.\nExtract Inductive list => \"[]\" [\"[]\" \"(:)\"].\nExtract Inductive bool => \"Bool\" [\"True\" \"False\"].\nRecursive Extraction preDeleteMin.\nExtraction \"ExtractedSkew.hs\" preDeleteMin preFindMin preInsert preMeld.\n*)\n\nInductive rankN : preT -> nat -> Prop :=\n  singleton : forall x, rankN (Node _ x 0 []) 0\n| simple : forall n v p y,\n             rankN (Node _ v n p) n ->\n             rankN y n ->\n             rankN (Node _ v (S n) (y::p)) (S n)\n| skewA : forall n x y z,\n          rankN x n ->\n          rankN z n ->\n          rankN (Node _ y (S n) [x;z]) (S n)\n| skewB : forall n x v p y,\n          rankN (Node _ v n p) n ->\n          rankN y n ->\n          rankN (Node _ v (S n) ((Node _ x 0 [])::y::p)) (S n).\nHint Constructors rankN.\n\nDefinition rankP x := rankN x (rank x).\n\nInductive posBinaryRank : preQ -> nat -> Prop :=\n  last : forall x n,\n         rankN x n ->\n         posBinaryRank [x] n\n| next : forall x n m xs,\n         rankN x n ->\n         n < m ->\n         posBinaryRank xs m ->\n         posBinaryRank (x::xs) n.\nHint Constructors posBinaryRank.\n\nInductive binaryRank : preQ -> Prop :=\n  zeroBin : binaryRank []\n| posBin : forall n xs,\n           posBinaryRank xs n ->\n           binaryRank xs.\nHint Constructors binaryRank.\n\nInductive posSkewBinaryRank : preQ -> nat -> Prop :=\n  vanilla : forall xs n, \n            posBinaryRank xs n ->\n            posSkewBinaryRank xs n\n| skew : forall x n xs,\n         rankN x n ->\n         posBinaryRank xs n ->\n         posSkewBinaryRank (x::xs) n.\nHint Constructors posSkewBinaryRank.\n\nInductive skewBinaryRank : preQ -> Prop :=\n  zeroSkew : skewBinaryRank []\n| posSkew : forall n xs,\n           posSkewBinaryRank xs n ->\n           skewBinaryRank xs.\nHint Constructors skewBinaryRank.\n\nLemma rankDestruct :\n  forall v n c m,\n    rankN (Node _ v n c) m ->\n    n = m.\nProof.\n  intros v n c m r.\n  inversion r; subst; auto.\nQed.\nHint Resolve rankDestruct.\n\nLemma rankRank :\n  forall x n,\n    rankN x n ->\n    rank x = n.\nProof.\n  intros x n r.\n  inversion r; subst; auto.\nQed.\nHint Resolve rankRank.\n\nLemma rankFunction :\n  forall x n m,\n    rankN x n ->\n    rankN x m -> \n    n = m.\nProof.\n  intros x n m XN XM;\n    destruct x as [v i p].\n  assert (i = n). eapply rankDestruct; eauto. subst.\n  eapply rankDestruct; eauto.\nQed.\n\nLemma linkRank :\n  forall n x y, \n    rankN x n -> \n    rankN y n -> \n    rankN (link x y) (S n).\nProof.\n  intros n x y X Y.\n  unfold link.\n  destruct x as [v xn p]; destruct y as [w yn q].\n  assert (xn = n); try (eapply rankDestruct; eauto); subst.\n  assert (yn = n); try (eapply rankDestruct; eauto); subst.\n  remember (LEQ v w) as vw; destruct vw; apply simple; auto.\nQed.\nHint Resolve linkRank.\n\nLemma skewLinkRank :\n  forall n x y z,\n    rankN x 0 ->\n    rankN y n ->\n    rankN z n ->\n    rankN (skewLink x y z) (S n).\nProof.\n  intros n x y z X Y Z.\n  unfold skewLink.\n  destruct x as [a i p]; destruct y as [b j q]; destruct z as [c k r].\n  assert (i = 0); try (eapply rankDestruct; eauto); subst.\n  assert (j = n); try (eapply rankDestruct; eauto); subst.\n  assert (k = n); try (eapply rankDestruct; eauto); subst.\n  assert (p = []); try (inversion X; auto); subst.\n  remember (LEQ a b) as ab; remember (LEQ a c) as ac;\n    remember (LEQ b c) as bc;\n      destruct ab; destruct ac; \n        destruct bc;  simpl; \n          try (apply skewB; assumption);\n            try (apply skewA; assumption).\nQed.\nHint Resolve skewLinkRank.\n\nLemma insNoDupeHelp : \n  forall n m x xs, \n    rankN x n ->\n    posBinaryRank xs m ->\n    n <= m ->\n    exists k, k >= n /\\ posBinaryRank (ins x xs) k.\nProof.\n  intros n m x xs xn xsm nm.\n  generalize dependent x;\n    generalize dependent n.\n  induction xsm.\n  Case \"last\".\n    intros j jn y yj.\n    destruct x as [v xx p]. \n    assert (xx = n). eapply rankDestruct; eauto. subst.\n    destruct y as [w yy q]. \n    assert (yy = j). eapply rankDestruct; eauto. subst.\n    unfold ins.\n    unfold rank.\n    remember (nat_compare j n) as ncjn; destruct ncjn.\n    SCase \"j = n\".\n      assert (j = n). apply nat_compare_eq; auto. subst.\n      exists (S n). split.\n      auto.  constructor. apply linkRank; auto.\n    SCase \"j < n\".\n      assert (j < n) as jn2. apply nat_compare_lt; auto.\n      exists j. \n      split. auto.\n      eapply next; eauto.\n    SCase \"j > n\".\n      assert (j > n) as jn2. apply nat_compare_gt; auto.\n      assert False as f. omega. inversion f.\n  Case \"next\".\n    intros j jn y yj.\n    destruct x as [v xx p]. \n    assert (xx = n). eapply rankDestruct; eauto. subst.\n    destruct y as [w yy q]. \n    assert (yy = j). eapply rankDestruct; eauto. subst.\n    unfold ins.\n    unfold rank at 1. unfold rank at 1.\n    remember (nat_compare j n) as ncjn; destruct ncjn.\n    SCase \"j = n\".\n      assert (j = n). apply nat_compare_eq; auto. subst.\n      fold ins.\n      assert (exists k, k >= S n \n        /\\ posBinaryRank (ins (link (Node _ w n q) (Node _ v n p)) xs) k).\n      eapply IHxsm.\n      auto. auto.\n      destruct H1.\n      destruct H1.\n      exists x.\n      split. auto with arith.\n      auto.\n    SCase \"j < n\".\n      assert (j < n) as jn2. apply nat_compare_lt; auto.\n      exists j. \n      split; auto.\n      eapply next; eauto.\n    SCase \"j > n\".\n      assert (j > n) as jn2. apply nat_compare_gt; auto.\n      assert False as f. omega. inversion f.\nQed.\n\nLemma insNoDupe : \n  forall n x xs, \n    posSkewBinaryRank (x::xs) n ->\n    exists k, k >= n /\\ posBinaryRank (ins x xs) k.\nProof.\n  intros n x xs xxsn.\n  inversion xxsn; subst.\n  Case \"vanilla\".\n    destruct xs.\n    SCase \"xs = nil\".\n      eauto.\n    SCase \"xs = p :: _\".\n      simpl.\n      assert (nat_compare (rank x) (rank p) = Lt).\n      destruct x; destruct p; simpl.\n      inversion H; subst.\n      inversion H5; subst.\n      assert (n0 = n). eapply rankDestruct; eauto.\n      subst.\n      assert (n1 = m). eapply rankDestruct; eauto.\n      subst.\n      apply nat_compare_lt; auto.\n      assert (n0 = n). eapply rankDestruct; eauto.\n      subst.\n      assert (n1 = m). eapply rankDestruct; eauto.\n      subst.\n      apply nat_compare_lt; auto.\n      rewrite H0.\n      eauto.\n  rename H1 into xn.\n  rename H3 into xsn.\n  eapply insNoDupeHelp; eauto.\nQed.\n\nLemma preInsertRank :\n  forall x ys,\n    skewBinaryRank ys ->\n    skewBinaryRank (preInsert x ys).\nProof with auto.\n  intros x ys P.\n  destruct ys.\n  Case \"ys = []\".\n    simpl.\n    SCase \"skewBinaryRank [Node x 0 []]\".\n      eapply posSkew.\n      eapply vanilla.\n      eapply last.\n      apply singleton.\n  Case \"ys = p :: _\".\n    unfold preInsert.\n    destruct ys.\n    SCase \"ys = nil\".\n      rename P into R.\n      SSCase \"skewBinaryRank [Node x 0 []; p]\".\n        eapply posSkew.\n        inversion R as [|n xs P]; subst.\n        inversion P; subst.\n        SSSCase \"\".\n          destruct n.\n          eapply skew; eauto. constructor.\n          eapply next. constructor.\n          Focus 2. eauto.\n          auto with arith.\n        SSSCase \"impossible\".\n          inversion H3.\n    SCase \"ys = p0 :: _\".\n      rename p0 into q.\n      rename P into R.\n      remember (beq_nat (rank p) (rank q)) as pq; destruct pq.\n      SSCase \"rank p = rank q\".\n        assert (rank p = rank q) as pq. apply beq_nat_true; auto.\n        SSSCase \"skewBinaryRank (skewLink (Node x 0 []) p q :: ys\".\n          eapply posSkew.\n          inversion R; subst.\n          inversion H; subst.\n          assert (rank p = n).\n          inversion H0; auto; eapply rankRank; auto.\n          subst.\n          assert (rank p < rank q).\n          inversion H0; subst.\n          assert (rank q = m).\n          inversion H6; auto; eapply rankRank; auto.\n          subst. auto.\n          assert False as f. omega. inversion f.\n\n          instantiate (1 := S (rank p)).\n          assert (rank p = n).\n          eapply rankRank; auto.\n          subst.\n          inversion H4; subst.\n          eapply vanilla; auto.\n\n          inversion H5.\n          eapply skew; auto. \n          subst; auto.\n          \n          eapply vanilla; auto.\n          apply next with (m := m).\n          eapply skewLinkRank; auto.\n          omega. auto.\n      SSCase \"rank p <> rank q\".\n        assert (rank p <> rank q) as pq. apply beq_nat_false; auto.\n        \n        apply posSkew with (n := 0).\n        inversion R; subst.\n        destruct n.\n        SSSCase \"skew\".\n          apply skew.\n          constructor.\n          inversion H; subst.\n          auto.\n          assert (rank p = 0). apply rankRank; auto.\n          assert (rank q = 0).\n          inversion H4; subst; apply rankRank; auto.\n          assert False as f. omega. inversion f.\n\n       SSSCase \"vanilla\".\n         apply vanilla.\n         apply next with (m := S n).\n         constructor. omega.\n         inversion H; subst.\n         auto.\n         assert (rank p = S n). apply rankRank; auto.\n         assert (rank q = S n).\n         inversion H4; subst;\n         apply rankRank; auto.\n         assert False as f. omega. inversion f.\nQed. \n\nDefinition min x y :=\n  match nat_compare x y with\n    | Lt => x\n    | _ => y\n  end.\n\nLemma meldUniqRank :\n  forall x n y m,\n    posBinaryRank x n ->\n    posBinaryRank y m ->\n    exists k, k >= min n m\n      /\\ posBinaryRank (meldUniq (x,y)) k.\nProof with auto.\n  assert \n    (let P := \n      fun (xy:(preQ*preQ)) r =>\n        let (x,y) := xy in\n          forall n m,\n            posBinaryRank x n ->\n            posBinaryRank y m ->\n            exists k, k >= min n m\n              /\\ posBinaryRank r k\n            in forall xy, P xy (meldUniq xy)).\n  eapply meldUniq_ind; intros; auto.\n\n  inversion H.\n  inversion H0.\n  assert (rank p = n). inversion H0; apply rankRank; auto.\n  assert (rank q = m). inversion H1; apply rankRank; auto.\n  subst.\n  assert (rank p < rank q). apply nat_compare_lt; auto.\n  inversion H0; subst.\n  unfold min. rewrite e0.\n  exists (rank p); split; auto.\n  rewrite meldUniq_equation. \n  eapply next.\n  Focus 3.\n  eauto. auto. auto.\n  unfold min. rewrite e0. \n  exists (rank p); split; auto.\n  assert (exists k, k >= min m (rank q)\n    /\\ posBinaryRank (meldUniq (ps, q::qs)) k).\n  apply H; auto.\n  destruct H3.\n  destruct H3.\n  eapply next.\n  Focus 3.\n  eauto. eauto.\n  unfold min in H3.\n  remember (nat_compare m (rank q)) as mq; destruct mq; omega.\n  \n  assert (rank p = n). inversion H0; apply rankRank; auto.\n  assert (rank q = m). inversion H1; apply rankRank; auto.\n  subst.\n  assert (rank q < rank p). apply nat_compare_gt; auto.\n  inversion H1; subst.\n  unfold min. rewrite e0.\n  exists (rank q); split; auto.\n  rewrite meldUniq_equation. \n  eapply next.\n  Focus 3.\n  eauto. auto. auto.\n  unfold min. rewrite e0. \n  exists (rank q); split; auto.\n  assert (exists k, k >= min (rank p) m\n    /\\ posBinaryRank (meldUniq (p::ps, qs)) k).\n  apply H; auto.\n  destruct H3.\n  destruct H3.\n  eapply next.\n  Focus 3.\n  eauto. eauto.\n  unfold min in H3.\n  remember (nat_compare (rank p) m) as mq; destruct mq; omega.\n\n  assert (rank p = rank q). apply nat_compare_eq; auto.\n  assert (exists k : nat,\n    k >= S (min n m)\n    /\\ posBinaryRank (ins (link p q) (meldUniq (ps, qs))) k).\n  apply insNoDupe.\n    inversion H0; inversion H1; subst.\n  rewrite meldUniq_equation.\n  eapply vanilla. eapply last. eapply linkRank.\n  assert (rank p = n). apply rankRank; auto; subst.\n  assert (rank q = m). apply rankRank; auto; subst.\n  rewrite H3 in *. rewrite H4 in *. subst.\n  unfold min.\n  remember (nat_compare (rank p) (rank p)) as pp.\n  destruct pp; auto.\n  assert (rank p = n). apply rankRank; auto; subst.\n  assert (rank q = m). apply rankRank; auto; subst.\n  rewrite H3 in *. rewrite H4 in *. subst.\n  unfold min.\n  remember (nat_compare (rank p) (rank p)) as pp.\n  destruct pp; auto.\n  \n  rewrite meldUniq_equation.\n  assert (rank p = n). apply rankRank; auto; subst.\n  assert (rank q = m). apply rankRank; auto; subst.\n  rewrite H3 in *; rewrite H4 in *; subst.\n  assert (min (rank p) (rank p) = rank p) as rp.\n  unfold min.\n  remember (nat_compare (rank p) (rank p)) as pp.\n  destruct pp; auto.\n  rewrite rp in *.\n  inversion H10. subst.\n  eapply skew; auto. \n  subst.\n  eapply vanilla; auto.\n  eapply next. Focus 3. eauto.\n  auto. omega.\n  \n  rewrite meldUniq_equation.\n  assert (rank p = n). apply rankRank; auto; subst.\n  assert (rank q = m). apply rankRank; auto; subst.\n  rewrite H3 in *; rewrite H4 in *; subst.\n  assert (min (rank p) (rank p) = rank p) as rp.\n  unfold min.\n  remember (nat_compare (rank p) (rank p)) as pp.\n  destruct pp; auto.\n  rewrite rp in *.\n  inversion H6. subst.\n  eapply skew; destruct ps; auto.\n  subst.\n  eapply vanilla; destruct ps; auto.\n  eapply next. Focus 3. eauto.\n  auto. omega.\n\n  assert (rank p = n). apply rankRank; auto; subst.\n  assert (rank q = m). apply rankRank; auto; subst.\n  rewrite H3 in *; rewrite H4 in *; subst.\n  assert (min (rank p) (rank p) = rank p) as rp.\n  unfold min.\n  remember (nat_compare (rank p) (rank p)) as pp.\n  destruct pp; auto.\n  rewrite rp in *.\n  \n  assert (exists k, k >= min m0 m1\n    /\\ posBinaryRank (meldUniq (ps,qs)) k).\n  apply H; auto.\n  destruct H2.\n  destruct H2.\n  remember (nat_compare (S (rank p)) x) as spx.\n  destruct spx.\n  assert (S (rank p) = x). apply nat_compare_eq. auto.\n  subst.\n  apply skew; auto.\n  assert (S (rank p) < x). apply nat_compare_lt. auto.\n  apply vanilla.\n  eapply next.\n  Focus 3.\n  eauto.\n  auto.\n  auto.\n  assert (S (rank p) > x). apply nat_compare_gt. auto.\n  assert (S (rank p) < x).\n  assert (S (rank p) <= min m0 m1).\n  assert (S (rank p) <= m0); auto with arith.\n  assert (S (rank p) <= m1); auto with arith.\n  unfold min.\n  remember (nat_compare m0 m1) as mm; destruct mm; auto.\n  omega. assert False as f. omega. inversion f.\n\n  destruct H3.\n  destruct H3.\n  exists x. split.\n  auto with arith.\n  auto.\n\n  simpl in H.\n  intros.\n  pose (H (x,y)) as I.\n  simpl in I.\n  pose (I n m H0 H1) as J.\n  destruct J.\n  exists x0.\n  split.\n  destruct H2.\n  auto.\n  destruct H2. auto.\nQed.\n  \n  \nLemma preMeldRank :\n  forall x y,\n    skewBinaryRank x ->\n    skewBinaryRank y ->\n    skewBinaryRank (preMeld x y).\nProof with auto.\n  intros x y xR yR.\n  unfold preMeld.\n  destruct x; destruct y.\n  simpl. rewrite meldUniq_equation. auto.\n  simpl. rewrite meldUniq_equation.\n  inversion yR; subst.\n  edestruct insNoDupe with (n := n) (x := p); eauto.\n  eapply posSkew. eapply vanilla.\n  destruct H0. eapply H1.\n  simpl. rewrite meldUniq_equation.\n  inversion xR; subst.\n  edestruct insNoDupe with (n := n) (x := p); eauto.\n  eapply posSkew. eapply vanilla.\n  destruct H0.\n  destruct (ins p x); eauto.\n\n  rename p0 into q.\n  inversion xR; inversion yR; subst.\n  rename n0 into m.\n  inversion H; inversion H1;\n    inversion H0; inversion H4; subst;\n  simpl; edestruct insNoDupe as [R S]; \n    edestruct insNoDupe as [T U];\n      edestruct meldUniqRank as [P Q];\n        try (eapply posSkew; \n          apply vanilla; \n            destruct Q; eauto; eauto; eauto);\n        try (destruct U; eauto);\n          try (destruct S; eauto); eauto.\nQed.\n\nLemma splitPosRank :\n  forall v n c,\n    rankP (Node _ v n c) ->\n    forall r m, posBinaryRank r m ->\n      n <= m ->\n      forall h t z, (h,t) = split r z c ->\n        exists k, posSkewBinaryRank h k.\nProof.\n  intros v n c H.\n  unfold rankP in H.\n  simpl in H.\n  dependent induction H; intros.\n  simpl in H1. inversion H1. subst.\n  eauto.\n  simpl in H3.\n  destruct y as [w j q].\n  simpl in *. assert (j = n). eauto. subst.\n  destruct n.\n  eapply IHrankN1. Focus 3.\n  eauto. eauto. auto with arith.\n  eapply IHrankN1. Focus 3.\n  eauto. eapply next. eauto.\n  Focus 2. eauto.\n  auto with arith. auto.\n  destruct x as [a b c]; destruct z as [d e f].\n  assert (b = n). eauto; subst.\n  assert (e = n). eauto; subst.\n  subst.\n  simpl in H3.\n  destruct n.\n  inversion H3; subst. eauto.\n  inversion H3; subst.\n  exists (S n).\n  eapply skew; eauto.\n\n  destruct y as [a b c].\n  assert (b = n). eauto.\n  subst.\n  simpl in H3.\n  destruct n.\n  eapply IHrankN1. Focus 3. eauto.\n  eauto. auto with arith.\n  \n  eapply IHrankN1.\n  Focus 3.\n  eapply H3.\n  eapply next. eauto.\n  Focus 2. eauto.\n  auto. auto.\nQed.\n\nLemma splitRank :\n  forall v n c,\n    rankP (Node _ v n c) ->\n    forall h t z, (h,t) = split [] z c ->\n      skewBinaryRank h.\nProof.\n  intros v n c H.\n  unfold rankP in H.\n  simpl in H.\n  dependent induction H; intros.\n  simpl in H. inversion H; subst. eauto.\n  \n  destruct y as [a b c].\n  assert (b = n); eauto; subst.\n  simpl in H1; destruct n.\n  eapply IHrankN1. eauto.\n  assert (exists k, posSkewBinaryRank h k).\n  eapply splitPosRank.\n  Focus 4. eauto.\n  Focus 2. eapply last. eauto.\n  eauto. auto.\n  destruct H2. eauto.\n  \n  destruct x as [a b c]; destruct z as [d e f].\n  assert (b = n); eauto; subst.\n  assert (e = n); eauto; subst.\n  simpl in H1; destruct n.\n  inversion H1; eauto.\n  inversion H1; subst; eauto.\n  \n  simpl in H1.\n  destruct y as [a b c].\n  assert (b = n); eauto; subst.\n  destruct n; simpl in H1.\n  eapply IHrankN1; eauto.\n  assert (exists k, posSkewBinaryRank h k).\n  eapply splitPosRank.\n  Focus 4. eauto.\n  Focus 2. eapply last. eauto.\n  eauto. auto.\n  destruct H2. eauto.\nQed.\n\nLemma getMinBinRank:\n  forall x n,\n    rankN x n ->\n    forall xs m, posBinaryRank xs m ->\n      n < m ->\n      forall y z,\n        (y,z) = getMin x xs ->\n        (exists k, k >= n /\\\n          posBinaryRank z k)\n        /\\ (exists j, j >= n /\\\n          rankN y j).\nProof.\n  intros x n xn xs. \n  generalize dependent x;\n    generalize dependent n.\n  induction xs; intros.\n  inversion H.\n  simpl in H1.\n  remember (getMin a xs) as axs.\n  destruct axs as [t ts].\n  remember (LEQ (root x) (root t)) as rxt.\n  destruct rxt.\n  inversion_clear H1; subst.\n  split. exists m; eauto 10 with arith.\n  eauto.\n  inversion_clear H1; subst.\n  inversion H; subst.\n  simpl in Heqaxs; eauto.\n  inversion_clear Heqaxs; subst; eauto.\n  split. eauto 10.\n  eauto 10 with arith.\n  assert ((exists k, k >= m /\\ posBinaryRank ts k) /\\\n    (exists j, j >= m /\\ rankN t j)).\n  eapply IHxs.\n  Focus 2. eauto. Focus 3. eauto.\n  eauto. eauto.\n  destruct H1.\n  destruct H1.\n  destruct H1.\n  destruct H2.\n  destruct H2.\n  split.\n  exists n. split; auto. eapply next. auto. Focus 2. eauto.\n  omega.\n  exists x1. split. omega. auto.\nQed.\n\nLemma getMinQRank:\n  forall x xs,\n    skewBinaryRank (x::xs) ->\n    forall y z,\n      (y,z) = getMin x xs ->\n      skewBinaryRank z.\nProof.\n  intros x xs xxs.\n  inversion xxs; subst.\n  inversion H; subst.\n  inversion H0; subst.\n  simpl; intros. inversion H1; subst; eauto.\n  intros.\n  assert ((exists k, k >= n /\\\n    posBinaryRank z k)\n  /\\ (exists j, j >= n /\\\n    rankN y j)). eapply getMinBinRank.\n  Focus 4. eauto. auto. eauto. auto.\n  inversion H2. destruct H5. destruct H5.\n  eapply posSkew. eapply vanilla. eauto.\n  inversion H4; subst.\n  simpl. remember (LEQ (root x) (root x0)) as xx0; destruct xx0; intros.\n  inversion_clear H1; subst; eauto.\n  inversion_clear H1; subst; eauto.\n  simpl.\n  intros.\n  remember (getMin x0 xs0) as x00; destruct x00.\n  remember (LEQ (root x) (root p)) as xp; destruct xp;\n    inversion_clear H5; subst.\n  eauto.\n  assert ((exists k, k >= n /\\\n    posBinaryRank l k)\n  /\\ (exists j, j >= n /\\\n    rankN p j)). eapply getMinBinRank.\n  Focus 4. eauto.\n  auto. eauto. auto.\n  inversion H5.\n  destruct H6.\n  destruct H6.\n  apply posSkew with (n := n).\n  destruct H6. eapply skew. eauto. eauto.\n  eapply vanilla.\n  eapply next. eauto. Focus 2. eauto. omega.\nQed.\n\nLemma getMinTRank:\n  forall x xs,\n    skewBinaryRank (x::xs) ->\n    forall y z,\n      (y,z) = getMin x xs ->\n      rankP y.\nProof.\n  intros x xs; generalize dependent x; induction xs; \n    intros x; destruct x; unfold rankP; intros.\n  inversion_clear H0; simpl.\n  inversion H; subst.\n  inversion H0; subst.\n  inversion H1; subst.\n  pose H3 as NN.\n  apply rankDestruct in NN; subst. auto.\n  inversion H7.\n  inversion H5.\n\n  simpl in H0.\n  remember (getMin a xs) as axs; destruct axs.\n  remember (LEQ a0 (root p)) as ap; destruct ap;\n    inversion_clear H0; subst.\n  inversion H; subst.\n  inversion H0; subst.\n  inversion H1; subst.\n  pose H4 as NN.\n  apply rankDestruct in NN; subst; auto.\n  pose H3 as NN.\n  apply rankDestruct in NN; subst; auto.\n  eapply IHxs.\n  Focus 2. eauto.\n  inversion H; subst.\n  inversion H0; subst.\n  inversion H1; subst.\n  eauto.\n  eauto.\nQed.\n\nLemma deleteMinRank :\n  forall x,\n    skewBinaryRank x ->\n    skewBinaryRank (preDeleteMin x).\nProof.\n  intros x S.\n  unfold preDeleteMin.\n  destruct x; eauto.\n  remember (getMin p x) as yz. destruct yz as [y z].\n  destruct y as [a b c].\n  remember (split [] [] c) as rs.\n  destruct rs as [r s].\n  assert (skewBinaryRank r) as ss.\n  eapply splitRank. Focus 2. eauto.\n  eapply getMinTRank. Focus 2. eauto. auto.\n  assert (skewBinaryRank z) as zz.\n  eapply getMinQRank. Focus 2. eauto. auto.\n  assert (skewBinaryRank (preMeld z r)).\n  eapply preMeldRank; auto.\n  clear Heqrs.\n  induction s.\n  simpl; auto.\n  simpl.\n  apply preInsertRank; auto.\nQed.\n\n\nLemma extractMinRank :\n  forall x,\n    skewBinaryRank x ->\n    forall t u,\n      Some (t,u) = preExtractMin x ->\n      skewBinaryRank u.\nProof.\n  intros x S t u T.\n  unfold preExtractMin in *.\n  destruct x; eauto. inversion T.\n  remember (getMin p x) as yz. destruct yz as [y z].\n  destruct y as [a b c].\n  remember (split [] [] c) as rs.\n  destruct rs as [r s].\n  assert (skewBinaryRank r) as ss.\n  eapply splitRank. Focus 2. eauto.\n  eapply getMinTRank. Focus 2. eauto. auto.\n  assert (skewBinaryRank z) as zz.\n  eapply getMinQRank. Focus 2. eauto. auto.\n  assert (skewBinaryRank (preMeld z r)).\n  eapply preMeldRank; auto.\n  inversion_clear T; subst.\n  clear Heqrs.\n  induction s.\n  simpl; auto.\n  simpl.\n  apply preInsertRank; auto.\nQed.\n\nInductive minHeap : preT -> Prop :=\n  lone : forall v n, minHeap (Node _ v n [])\n| top : forall v n n' w m m' p ys,\n        minHeap (Node _ v n ys) ->\n        true = LEQ v w ->\n        minHeap (Node _ w m' p) ->\n        minHeap (Node _ v n' ((Node _ w m p) :: ys)).\nHint Constructors minHeap.\n\nInductive All t (p:t -> Prop) : list t -> Prop :=\n  Nil : All p []\n| Cons : forall x xs,\n         p x ->\n         All p xs ->\n         All p (x::xs).\nHint Constructors All.\n\nLemma linkHeap :\n  forall x y, minHeap x -> minHeap y -> minHeap (link x y).\nProof.\n  intros x y X Y.\n  unfold link.\n  destruct x as [v n p]; destruct y as [w m q].\n  remember (LEQ v w) as vw; destruct vw; eapply top; eauto.\n  apply leqSymm; auto.\nQed.\nHint Resolve linkHeap.\n\nLemma skewLinkHeap :\n  forall x y z, minHeap y -> minHeap z -> \n    minHeap (skewLink (Node _ x 0 []) y z).\nProof.\n  intros x y z Y Z.\n  unfold skewLink.\n  rename x into a.\n  destruct y as [b j q]; destruct z as [c k r].\n  unfold rank in *; subst.\n  remember (LEQ a b) as ab; destruct ab; simpl.\n  Case \"a <= b\".\n    remember (LEQ a c) as ac; destruct ac; simpl.\n    SCase \"a <= c\".\n      eapply top with (n:=0); auto. eapply top.\n      apply lone with (n := 0). auto.\n      eauto. eauto.\n    SCase \"a > c\".\n      assert (true = LEQ c a). apply leqSymm; auto.\n      eapply top with (n:=0).  Focus 3. apply lone with (n := 0).\n      eapply top. eauto.\n      eapply leqTransTrue; eauto. eauto. auto.\n  Case \"b > a\".\n    assert (true = LEQ b a). apply leqSymm; auto.\n    remember (LEQ b c) as bc; destruct bc; simpl.\n    SCase \"b <= c\".\n      eapply top with (n:=0). Focus 3.\n      eapply lone with (n:= 0). \n      eapply top; auto. eauto. eauto. auto.\n    SCase \"b > c\".\n      assert (true = LEQ c b). apply leqSymm; auto.\n      eapply top with (n:=0). Focus 3. eapply lone with (n:=0).\n      eapply top; auto. eauto. eauto.\n      eapply leqTransTrue; eauto.\nQed.\nHint Resolve skewLinkHeap.\n\nLemma insHeap : \n  forall x xs,\n    minHeap x ->\n    All minHeap xs ->\n    All minHeap (ins x xs).\nProof.\n  intros x xs.\n  generalize dependent x.\n  induction xs; intros; auto.\n    simpl; auto.\n    inversion H0; subst.\n    simpl.\n    remember (nat_compare (rank x) (rank a)) as xa; destruct xa; auto.\nQed.\n\nLemma preInsertHeap :\n  forall x ys,\n    All minHeap ys ->\n    All minHeap (preInsert x ys).\nProof with auto.\n  intros x ys P.\n  destruct ys.\n  Case \"ys = []\".\n    simpl. \n    SCase \"All minHeap [Node x 0 []]\".\n      eapply Cons.\n      SSCase \"minHeap (Node x 0 [])\".\n        apply lone.\n      SSCase \"All minHeap []\".\n        apply Nil.\n  Case \"ys = p :: _\".\n    unfold preInsert.\n    destruct ys.\n    SCase \"ys = nil\".\n      rename P into M.\n      SSCase \"All minHeap [Node x 0 []; p]\".\n        inversion M; subst.\n        eapply Cons; eauto. \n    SCase \"ys = p0 :: _\".\n      rename p0 into q.\n      rename P into M.\n      remember (beq_nat (rank p) (rank q)) as pq; destruct pq.\n      SSCase \"All minHeap (skewLink (Node x 0 []) p q :: ys)\".\n        apply Cons.\n        apply skewLinkHeap; auto.\n        inversion M; auto.\n        inversion M. inversion H2; auto.\n        inversion M. inversion H2; auto.\n      SSCase \"All minHeap (Node x 0 [] :: p :: q :: ys\".\n         apply Cons; auto.\nQed.\n\nLemma meldUniqHeap :\n  forall x y,\n    All minHeap x ->\n    All minHeap y ->\n    All minHeap (meldUniq (x,y)).\nProof.\n  assert \n    (let P := \n      fun (xy:(preQ*preQ)) r =>\n        let (x,y) := xy in\n              All minHeap x ->\n              All minHeap y ->\n              All minHeap r\n              in forall xy, P xy (meldUniq xy)).\n  eapply meldUniq_ind; intros; auto.\n  inversion H0; subst.\n  apply Cons; auto.\n  inversion H1; subst.\n  apply Cons; auto.\n  inversion H1; inversion H0; subst.\n  apply insHeap; auto.\n  intros.\n  simpl in H.\n  pose (H (x, y)) as I.\n  eapply I; auto.\nQed.\n\nLemma preMeldHeap :\n  forall x y,\n    All minHeap x ->\n    All minHeap y ->\n    All minHeap (preMeld x y).\nProof with auto.\n  intros x y xH yH.\n\n  apply meldUniqHeap.\n  destruct x; inversion xH; subst; auto.\n  apply insHeap; auto. \n  destruct y; inversion yH; subst; auto.\n  apply insHeap; auto.\nQed.\n\nLemma getMinTHeap :\n  forall x xs,\n    minHeap x ->\n    All minHeap xs ->\n    forall y z, (y,z) = getMin x xs ->\n      minHeap y.\nProof.\n  intros x xs;\n    generalize dependent x;\n      induction xs;\n        simpl; intros.\n  inversion_clear H1; subst; auto.\n  remember (getMin a xs) as tts; destruct tts; subst.\n  remember (LEQ (root x) (root p)) as xp; destruct xp.\n  inversion_clear H1; subst. auto.\n  inversion_clear H1; subst.\n  inversion_clear H0; subst.\n  eapply IHxs; eauto. \nQed.\n\nLemma getMinQHeap :\n  forall x xs,\n    minHeap x ->\n    All minHeap xs ->\n    forall y z, (y,z) = getMin x xs ->\n      All minHeap z.\nProof.\n  intros x xs;\n    generalize dependent x;\n      induction xs; simpl; intros.\n  inversion_clear H1; subst; eauto.\n  remember (getMin a xs) as tts; destruct tts.\n  remember (LEQ (root x) (root p)) as xp; destruct xp;\n    inversion_clear H1; subst; eauto.\n  inversion_clear H0; subst.\n  apply Cons; eauto.\nQed.\n\nLemma splitHeap :\n  forall a, All minHeap a ->\n    forall b c, All minHeap c ->\n      forall y z, (y,z) = split a b c ->\n        All minHeap y.\nProof.\n  intros a AA b c.\n  generalize dependent a;\n    generalize dependent b.\n  induction c; simpl; intros.\n  inversion_clear H0; subst; auto.\n  destruct a as [i j k]; destruct j; simpl in *.\n  eapply IHc. Focus 3. eauto.\n  auto. inversion_clear H; subst; auto.\n  inversion_clear H; subst.\n  eapply IHc. Focus 3. eauto.\n  auto. auto.\nQed.\n\n\nLemma childrenHeap :\n  forall v i c,\n    minHeap (Node _ v i c) ->\n    All minHeap c.\nProof.\n  intros v i c;\n    generalize dependent v; \n      generalize dependent i; \n        induction c;\n          simpl; intros.\n  auto.\n  inversion_clear H; subst.\n  apply Cons.\n  inversion_clear H2; subst; auto.\n  eapply top. eauto. auto. eauto.\n  eapply IHc. eauto.\nQed.\n\nLemma preDeleteMinHeap :\n  forall x,\n    All minHeap x ->\n    All minHeap (preDeleteMin x).\nProof.\n  intros x.\n  induction x; simpl; intros.\n  eauto.\n  inversion_clear H; subst.\n  remember (getMin a x) as pt; destruct pt as [p t].\n  destruct p as [zz zzz c].\n  remember (split [] [] c) as pq; destruct pq as [p q].\n  assert (All minHeap p). eapply splitHeap.\n  Focus 3. eauto. auto.\n  assert (minHeap (Node _ zz zzz c)). eapply getMinTHeap.\n  Focus 3. eauto. auto. auto.\n  eapply childrenHeap. eauto.\n  assert (All minHeap t). eapply getMinQHeap. Focus 3. eauto.\n  auto. auto.\n\n  clear Heqpq.\n  \n  induction q. simpl.\n  apply preMeldHeap; auto.\n  simpl.\n  apply preInsertHeap; auto.\nQed.\n\nLemma preExtractMinHeap :\n  forall x,\n    All minHeap x ->\n    forall y z,\n      Some (y,z) = preExtractMin x ->\n      All minHeap z.\nProof.\n  intros x.\n  induction x; simpl; intros.\n  inversion H0.\n  inversion_clear H; subst.\n  remember (getMin a x) as pt; destruct pt as [p t].\n  destruct p as [zz zzz c].\n  remember (split [] [] c) as pq; destruct pq as [p q].\n  assert (All minHeap p). eapply splitHeap.\n  Focus 3. eauto. auto.\n  assert (minHeap (Node _ zz zzz c)). eapply getMinTHeap.\n  Focus 3. eauto. auto. auto.\n  eapply childrenHeap. eauto.\n  inversion_clear H0; subst.\n  assert (All minHeap t). eapply getMinQHeap. Focus 3. eauto.\n  auto. auto.\n\n  clear Heqpq.\n  \n  induction q. simpl.\n  apply preMeldHeap; auto.\n  simpl.\n  apply preInsertHeap; auto.\nQed.\n\nDefinition PQP x := skewBinaryRank x /\\ All minHeap x.\n\nDefinition PQ := { x:preQ | PQP x}.\n\nProgram Definition empty : PQ := [].\nNext Obligation.\n  split; constructor.\nQed.\n\nProgram Definition insert : A -> PQ -> PQ := preInsert.\nNext Obligation.\n  destruct x0.\n  destruct p.\n  split.\n  simpl.\n  apply preInsertRank. assumption.\n  simpl. apply preInsertHeap. assumption.\nQed.\n\nProgram Definition findMin : PQ -> option A := preFindMin.\n\nProgram Definition meld : PQ -> PQ -> PQ := preMeld.\nNext Obligation.\n  destruct x; destruct x0.\n  destruct p; destruct p0; split; simpl.\n  apply preMeldRank; auto.\n  apply preMeldHeap; auto.\nQed.\n\nProgram Definition deleteMin : PQ -> PQ := preDeleteMin.\nNext Obligation.\n  destruct x. destruct p; split; simpl.\n  apply deleteMinRank; auto.\n  apply preDeleteMinHeap; auto.\nQed.\n\n(*\nProgram Definition extractMin (x:PQ) : option (A*PQ) :=\n  match preExtractMin x with\n    | None => None\n    | Some (y,z) => Some (y,z)\n  end.\nNext Obligation.\n  destruct x. destruct p; split; simpl.\n  eapply extractMinRank; eauto.\n  eapply preExtractMinHeap; eauto.\nQed.\n*)\n\n(*\nPrint extractMin.\n\nLocate \"_ = _\".\nPrint eq.\n*)\n\n\nDefinition extractMin (x:PQ) : option (A*PQ).\nrefine (fun x =>\n  match x with\n    | exist x' xp =>\n      match preExtractMin x' as j return ((j=preExtractMin x') -> option (A*PQ)) with\n        | None => fun _ => None\n        | Some (y,z) => fun s => Some (y,(@exist _ _ z _))\n      end eq_refl\n  end).\n  destruct xp as [R M].\n  split.\n  eapply extractMinRank; eauto.\n  eapply preExtractMinHeap; eauto.\nDefined.\n\nLemma extractMin_equality :\n  forall x px y z pz,\n    Some (y,exist _ z pz) = extractMin (exist _ x px) ->\n    Some (y,z) = preExtractMin x.\nProof.\n  intros.\n  generalize dependent H. \n  remember (preExtractMin x) as pemx.\n  unfold extractMin.  \n(*  generalize dependent Heqpemx.*)\n  assert (forall (zz:option(A*preQ)) (pp:zz= preExtractMin x),\n    Some (y, exist (fun x0 : preQ => PQP x0) z pz) =\n    match\n      zz as j return (j = preExtractMin x -> option (A * PQ))\n      with\n      | Some p =>\n        let (y0, z0) as p0\n          return (Some p0 = preExtractMin x -> option (A * PQ)) := p in\n          fun s : Some (y0, z0) = preExtractMin x =>\n            Some\n            (y0,\n              exist (fun x0 : preQ => PQP x0) z0\n              match px with\n                | conj R M => conj (extractMinRank R s) (preExtractMinHeap M s)\n              end)\n      | None => fun _ : None = preExtractMin x => None\n   end pp -> Some (y, z) = pemx) as P.\n  intros.\n  destruct zz.\n  destruct p.\n  inversion_clear H; subst. auto.\n  inversion H.\n  pose (P (preExtractMin x) eq_refl) as Q.\n  apply Q.\nQed.\n\nLemma extractMin_none :\n  forall x px,\n    None = extractMin (exist _ x px) ->\n    None = preExtractMin x.\nProof.\n  intros.\n  generalize dependent H. \n  remember (preExtractMin x) as pemx.\n  unfold extractMin.  \n(*  generalize dependent Heqpemx.*)\n  assert (forall (zz:option(A*preQ)) (pp:zz= preExtractMin x),\n    None =\n    match\n      zz as j return (j = preExtractMin x -> option (A * PQ))\n      with\n      | Some p =>\n        let (y0, z0) as p0\n          return (Some p0 = preExtractMin x -> option (A * PQ)) := p in\n          fun s : Some (y0, z0) = preExtractMin x =>\n            Some\n            (y0,\n              exist (fun x0 : preQ => PQP x0) z0\n              match px with\n                | conj R M => conj (extractMinRank R s) (preExtractMinHeap M s)\n              end)\n      | None => fun _ : None = preExtractMin x => None\n   end pp -> None = pemx) as P. Focus 2.\n  eapply P.\n  intros.\n  destruct zz.\n  destruct p.\n  inversion_clear H; subst.\n  rewrite Heqpemx. auto.\nQed.\n  \n\nEnd SkewBinaryHeap.", "meta": {"author": "jbapple", "repo": "priority-queues", "sha": "559defbdace49e17d65893eb03577afa8403d767", "save_path": "github-repos/coq/jbapple-priority-queues", "path": "github-repos/coq/jbapple-priority-queues/priority-queues-559defbdace49e17d65893eb03577afa8403d767/brodal-okasaki/skewBinaryHeap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6598539970768965}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra all_field.\nRequire Import s2int.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport Order.TTheory GRing.Theory Num.Theory zmodp.\nOpen Scope ring_scope.\nOpen Scope S2I_scope.\n\nSection Quantum.\n\nLemma conjC_sqrt2 : (sqrtC 2%:R)^* = (sqrtC 2%:R) :> algC.\nProof. by rewrite conj_Creal // Creal_s2Int // sQ2_proof. Qed.\n\nLemma sqrt2_neq0 : sqrtC 2%:R != 0 :> algC.\nProof. by rewrite sqrtC_eq0 (eqC_nat 2 0). Qed.\n\nLemma sqrt2X_neq0 k : sqrtC 2%:R ^+ k != 0 :> algC.\nProof.  by rewrite expf_neq0 // sqrt2_neq0. Qed.\n\nLemma conj_s2Int x : x \\is a s2Int -> x^* = x.\nProof. by move=> H; rewrite conj_Creal // Creal_s2Int. Qed.\n\n\nDefinition o2 : 'I_3 := Ordinal (isT: 2 < 3)%N.\nDefinition o3E (i : 'I_3) : [||i == 0, i ==1 | i == o2].\nProof. by case: i => [] [|[|[|]]]. Qed.\n\nLemma sum3E (R :ringType) (F : 'I_3 -> R) : \n  \\sum_(i < 3)  F i = F 0 + F 1 + F o2.\nProof.\nrewrite !big_ord_recl /= big_ord0 addr0 !addrA.\nby congr (F _ + F _ + F _); apply/val_eqP.\nQed.\n\n(* conjugate transpose *)\nDefinition trCmx m n (M : 'M_(m,n)) := map_mx (conjC : algC -> _) (trmx M).\n\nNotation \"M ^T*\" := (trCmx M) (at level 10).\n\nLemma trCmx_const n a : (a%:M)^T* = a^*%:M :> 'M_n.\nProof.\nrewrite /trCmx tr_scalar_mx.\nby apply/matrixP=> i j; rewrite !mxE; case: eqP; rewrite ?rmorph0.\nQed.\n\nLemma trCmx0 n : 0^T* = 0 :> 'M[algC]_n.\nProof.\nhave <-: 0%:M = 0 :>  'M[algC]_n by apply/matrixP=> i j; rewrite !mxE mul0rn.\nby rewrite trCmx_const conjC0.\nQed.\n\nLemma trCmx1 n : (1%:M)^T* = 1%:M :> 'M[algC]_n.\nProof. by rewrite trCmx_const conjC1. Qed.\n\nLemma trCmxN n (M : 'M[algC]_n) : (-M)^T* = - (M^T* ).\nProof. by rewrite -[RHS]map_mxN -raddfN. Qed.\n\nLemma trCmx_mul m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n   (A *m B)^T* = B^T* *m A^T*.\nProof. by rewrite /trCmx -!map_trmx map_mxM trmx_mul. Qed.\n\nLemma trmx_eq0 m n (R: ringType) (M : 'M[R]_(m, n)) : (M  ^T == 0) = (M == 0).\nProof.\napply/eqP/eqP => [H|->]; last by rewrite trmx0.\nby rewrite -[M]trmxK H trmx0.\nQed.\n\nLemma trCmx_eq0 m n (M : 'M_(m, n)) : (M  ^T* == 0) = (M == 0).\nProof. by rewrite map_mx_eq0 trmx_eq0. Qed.\n\nLemma trCmxK n : cancel (@trCmx n n) (@trCmx n n).\nProof.\nmove=> u.\nrewrite /trCmx map_trmx trmxK .\nby apply/matrixP=> i j; rewrite !mxE conjCK.\nQed.\n\nLemma trCmxZ m n (M : 'M_(m,n)) c :\n  (c *: M)^T* = c^* *: M^T*.\nProof. by apply/matrixP=> i j; rewrite !mxE rmorphM. Qed.\n\nLemma mulmxkC n (R : idomainType) (A B : 'M[R]_n) c : \n   c != 0 -> A *m B = c%:M -> B *m A = c%:M.\nProof.\nmove=> nZc AB1; pose A' := \\det B *: \\adj A.\nhave kA: A' *m A = (c ^+ n)%:M.\n  by rewrite -scalemxAl mul_adj_mx scale_scalar_mx mulrC -det_mulmx AB1 det_scalar.\nhave nZcn : c ^+ n != 0 by apply: expf_neq0.\napply: (scalemx_inj nZcn).\nrewrite -mul_scalar_mx -kA !mulmxA -(mulmxA A') AB1.\nby rewrite scalar_mxC -mulmxA kA -mul_scalar_mx -!scalar_mxM mulrC.\nQed.\n\nLemma trCmx_tr m n (M : 'M_(m, n)) :\n  (forall i j, M i j \\is Creal) -> trCmx M = M^T.\nProof. by move=> H; apply/matrixP => i j; rewrite !mxE (CrealP (H _ _ )). Qed.\n\n(* Unitary *)\nDefinition mxunitary {n} :=\n [qualify M |  M *m (M : 'M_n) ^T* == 1%:M].\n\nLemma mxunitaryP n (M : 'M_n) :\n  reflect \n   (forall i  j : 'I_n, \n     \\sum_(k < n) (M i k * (M j k)^*) = (i == j)%:R)\n   (M \\is mxunitary).\nProof.\napply: (iffP eqP) => [/matrixP H i j| H].\n  have := H i j.\n  by rewrite !mxE => <-; apply: eq_bigr => k; rewrite !mxE.\napply/matrixP=> i j.\nby rewrite !mxE -H; apply: eq_bigr => k; rewrite !mxE.\nQed.\n\nLemma mxunitary1 n : (1%:M : 'M_n) \\is mxunitary.\nProof. by rewrite qualifE /mxunitary mul1mx trCmx_const conjC1. Qed. \n\nLemma mxunitaryN (n : nat) : \n  {in mxunitary, forall M : 'M_n, - M \\in mxunitary}.\nProof.\ncase: n => [|n] M H.\n  by rewrite (_ : -M = M) //; apply/matrixP=> [] [].\napply/eqP.\nrewrite -{2}scaleN1r trCmxZ rmorphN rmorph1 scaleN1r.\nrewrite mulmxN mulNmx opprK.\nby apply/eqP.\nQed.\n\nLemma mxunitaryM n  : \n   {in mxunitary &, forall M1 M2 : 'M_n, M1 *m M2 \\in mxunitary}.\nProof.\nmove=> M1 M2 /eqP H1 /eqP H2; apply/eqP.\nrewrite trCmx_mul mulmxA -[_ *m M2 ^T*]mulmxA H2.\nby rewrite scalar_mxC -mulmxA H1 mul1mx.\nQed.\n\nLemma mxunitaryT n (M : 'M_n) : M ^T* \\is mxunitary = (M \\is mxunitary).\nProof.\nrewrite qualifE /mxunitary trCmxK.\nby apply/eqP/eqP=> H; rewrite (mulmxkC (@oner_neq0 _)).\nQed.\n\n(* All the scaled elements are in s2Int *)\n\nDefinition mxs2int {n} m := \n [qualify M | \n   [forall i : 'I_n, forall j : 'I_n, (sqrtC 2%:R ^+ m) * (M : 'M_n) i j \\is a s2Int]].\n\nNotation \" m .-s2int\" := (mxs2int m) (format \"m .-s2int\", at level 10).\n\nLemma mxs2intP n m  (M : 'M_n) : \n  reflect (forall i j,  (sqrtC 2%:R) ^+ m * M i j \\is a s2Int) \n          (M \\is m.-s2int).\nProof.\napply: (iffP forallP) => [H i j|H i]; first by have /forallP/(_ j) := H i.\nby apply/forallP=> j; apply: H.\nQed.\n\nLemma mxs2int1 n : (1%:M : 'M_n) \\is 0.-s2int.\nProof.\napply/forallP=> i; apply/forallP=> j; rewrite mul1r mxE.\nby case: eqP; rewrite (rpred0, rpred1).\nQed.\n\nLemma mxs2intW n m1 m2  (M : 'M_n) : \n  (m1 <= m2)%N -> M \\is m1.-s2int -> M \\is m2.-s2int.\nProof.\nmove=> /subnK<- /mxs2intP Hm; apply/mxs2intP=> i j.\nby rewrite exprD -mulrA rpredM // rpredX // sQ2_proof.\nQed.\n\nLemma mxs2intM n m1 m2 (M1 M2 : 'M_n) : \n  M1 \\is m1.-s2int -> M2 \\is m2.-s2int -> M1 *m M2 \\is (m1 + m2).-s2int.\nProof.\nmove=> /mxs2intP HS1 /mxs2intP HS2; apply/mxs2intP=> i j.\nrewrite !mxE !mulr_sumr rpred_sum // => k _.\nby rewrite exprD -mulrA [_ * (M1 _ _ * _)]mulrCA !mulrA -mulrA rpredM.\nQed.\n\nLemma mxs2intT n m (M : 'M_n) : (M ^T* \\is m.-s2int) = (M \\is m.-s2int).\nProof.\napply/mxs2intP/mxs2intP => H i j; have := H j i; rewrite !mxE => H1.\n  by rewrite  -[_ * _]conjCK s2Int_conj // rmorphM rmorphX conjC_sqrt2.\nby rewrite -conjC_sqrt2 -rmorphX -rmorphM s2Int_conj.\nQed.\n\nLemma mxs2int_tr n m (M : 'M_n) : M \\is m.-s2int -> M^T* = M^T.\nProof.\nmove=> /mxs2intP H; apply/matrixP=> i j; rewrite !mxE.\nrewrite conj_Creal //.\nrewrite -[M j i](mulfK (sqrt2X_neq0 m)) rpredM //.\n  by rewrite mulrC Creal_s2Int.\nby rewrite rpredXN // Creal_s2Int // sQ2_proof.\nQed.\n\n(* An element of M scaled by s2 ^ m is odd *) \nDefinition mxodd {n} m :=\n [qualify M |\n  [exists i, exists j, odds2i ((sqrtC 2%:R) ^+ m * (M : 'M_n) i j)]].\n\nNotation \" m .-odd\" := (mxodd m) (format \"m .-odd\", at level 10).\n\nLemma mxodd1 n : (1 : 'M_n.+1) \\is 0.-odd.\nProof.\napply/existsP; exists 0; apply/existsP; exists 0.\nby rewrite mxE mulr1 (odds2i_nat 1).\nQed.\n\nLemma mxoddP n m (M : 'M_n) : \n  reflect (exists i, exists j, \n                   odds2i ((sqrtC 2%:R) ^+ m * M i j))\n          (M \\is m.-odd).\nProof.\napply: (iffP existsP) => [[i /existsP[j H]]|[i [j H]]].\n  by exists i; exists j.\nby exists i; apply/existsP; exists j.\nQed.\n\nLemma mxoddPn n m (M : 'M_n) : \n  reflect (forall i j, ~~ odds2i ((sqrtC 2%:R) ^+ m * M i j)) \n          (~~ (M \\is m.-odd)).\nProof.\nrewrite negb_exists.\napply: (iffP forallP) => [H i j|H i].\n  by have := H i; rewrite negb_exists => /forallP/(_ j).\nby rewrite negb_exists; apply/forallP.\nQed.\n\nLemma mxs2int_odd n m (M : 'M_n) :\n  M \\is m.+1.-s2int -> M \\is m.-s2int =(M \\isn't m.+1.-odd).\nProof.\nmove=> /mxs2intP H.\nhave [/mxoddP[i [j H1]]|/mxoddPn H1]/= := boolP (_ \\is _.-odd).\n  apply/negP=> /mxs2intP/(_ i j) H2.\n  have := H1.\n  by rewrite exprS -mulrA odds2iM  ?(negPf odds2i_sQ2) // sQ2_proof.\napply/mxs2intP=> i j.\nhave := H1 i j.\nrewrite (odds2i_dvd (S2Iof (H i j))) => /dvdS2IP[r /val_eqP/eqP/=].\nrewrite [RHS]mulrC exprS -!mulrA => /(mulfI sqrt2_neq0)->.\nby apply: algS2IP.\nQed.\n\n(* M is unitary and all the scaled elements are in s2Int *)\nDefinition mxsunitary {n} m :=\n [qualify M |  (M \\is mxunitary) &&  ((M : 'M_n) \\is m.-s2int)].\n\nNotation \" m .-sunitary\" := (mxsunitary m) (format \"m .-sunitary\", at level 10).\n\nLemma mxsunitary_unitary n m (M : 'M_n) : M \\is m.-sunitary -> M \\is mxunitary.\nProof. by case/andP. Qed.\n\nLemma mxsunitary_s2int n m (M : 'M_n) i j : \n  M \\is m.-sunitary -> (sqrtC 2%:R ^+ m) * M i j \\is a s2Int.\nProof. by case/andP=> _ /mxs2intP. Qed.\n\nLemma mxsunitaryN n c (M : 'M_n) : M \\is c.-sunitary -> -M \\is c.-sunitary.\nProof.\nmove=> H.\nhave /andP[H1 /forallP H2] := H.\nrewrite qualifE /mxsunitary ?mxunitaryN //.\napply/forallP=> i; apply/forallP=> j.\nrewrite !mxE mulrN rpredN.\nby have /forallP := H2 i.\nQed.\n\nLemma mxsunitaryM n m1 m2 (M1 M2 : 'M_n) : \n  M1 \\is m1.-sunitary -> M2 \\is m2.-sunitary -> \n  M1 *m M2 \\is (m1 + m2).-sunitary.\nProof.\nmove=> /andP[H1o H1s] /andP[H2o H2s].\nby rewrite qualifE /mxsunitary mxunitaryM // mxs2intM.\nQed.\n\nLemma mxsunitaryT n m (M : 'M_n) : (M ^T* \\is m.-sunitary) = (M \\is m.-sunitary).\nProof. by rewrite qualifE/mxsunitary mxs2intT mxunitaryT. Qed.\n\nLemma mxsunitary_inj k n (M M1 M2 : 'M_n) :\n M \\is k.-sunitary ->  M *m M1 = M *m M2 -> M1 = M2.\nProof.\nmove=> Hs H.\nhave F : trCmx M *m M = 1%:M.\n  have := Hs.\n  rewrite -mxsunitaryT => /andP[].\n  by rewrite qualifE /mxunitary trCmxK => /eqP.\nby rewrite -[LHS]mul1mx -F -mulmxA H mulmxA F mul1mx.\nQed.\n \nLemma mxsunitary_tr n m (M : 'M_n) : M \\is m.-sunitary -> M^T* = M^T.\nProof.\nmove=> sO.\napply/matrixP=> i j.\nrewrite !mxE -{1}[M _ _](mulfK (sqrt2X_neq0 m)).\nrewrite rmorphM !conj_Creal ?(mulfK (sqrt2X_neq0 m)) //.\n  by rewrite rpredXN // Creal_s2Int // sQ2_proof.\nby rewrite mulrC Creal_s2Int // (mxsunitary_s2int j i sO).\nQed.\n\nLemma mxsunitaryW n m1 m2  (M : 'M_n) : \n  (m1 <= m2)%N -> M \\is m1.-sunitary -> M \\is m2.-sunitary.\nProof.\nby move=> H; rewrite !qualifE /mxsunitary => /andP[-> /(mxs2intW H)].\nQed.\n\nLemma mxsunitary0_odd n (M : 'M_n.+1) : M \\is 0.-sunitary -> M \\is 0.-odd.\nProof.\nmove=> Hn.\nrewrite -[_ \\is _]negbK negb_exists.\napply/negP=> /forallP /(_ 0).\nrewrite negb_exists => /forallP H1.\nhave F i1 j1 : M i1 j1 \\is a s2Int.\n  by have /andP[_ /forallP/(_ i1)/forallP/(_ j1)] := Hn; rewrite mul1r.\nhave F1 : \\sum_(k < n.+1) (M ord0 k) ^+ 2 = 1.\n  have /mxunitaryP/(_ 0 0) := mxsunitary_unitary Hn.\n  rewrite eqxx mulr1n => <-.\n  apply: eq_bigr => k _.\n  by rewrite expr2 conj_Creal // Creal_s2Int.\nhave : odds2i 1 by rewrite /odds2i (s2intA_nat 1).\nrewrite -F1 odds2i_sum => [|i _ _]; last by rewrite rpredX.\nrewrite big1 // => i _.\nby have := negPf (H1 i); rewrite mul1r odds2iM // => ->.\nQed.\n\nLemma mxsunitary_odd n m (M : 'M_n) :\n  M \\is m.+1.-sunitary -> (M \\is m.-sunitary) = (M \\isn't m.+1.-odd).\nProof.\nmove=> /andP[Ho Hs].\nby rewrite qualifE /mxsunitary Ho mxs2int_odd.\nQed.\n\nLemma mxoddN n c (M : 'M_n) : \n  M \\is c.-sunitary -> (-M \\is c.-odd) = (M \\is c.-odd).\nProof.\nmove=> H.\napply/mxoddP/mxoddP; move=> [i [j Hij]]; exists i; exists j.\n  rewrite !mxE mulrN in Hij.\n  rewrite -odds2iN //.\n  by apply: mxsunitary_s2int H.\nby rewrite !mxE mulrN // odds2iN // (mxsunitary_s2int _ _ H).\nQed.\n\n(* M is unitary and m is the smallest value such that all the scaled \n   elements are in s2Int *)\nDefinition mxounitary {n} m := \n [qualify M |\n  [&& (M : 'M_n) \\is mxunitary, M \\is m.-s2int & M \\is m.-odd]].\n\nNotation \" m .-unitary\" := (mxounitary m) (format \"m .-unitary\", at level 10).\n\nLemma mxounitaryE n m  (M : 'M_n) :\n   (M \\is m.-unitary) = ((M \\is m.-sunitary) && (M \\is m.-odd)).\nProof. by rewrite -andbA. Qed.\n\nLemma mxounitary_unitary n m (M : 'M_n) : M \\is m.-unitary -> M \\is mxunitary.\nProof. by case/and3P. Qed.\n\nLemma mxounitary_s2int n m (M : 'M_n) i j :\n  M \\is m.-unitary -> (sqrtC 2%:R ^+ m) * M i j \\is a s2Int.\nProof. by case/and3P=> _ /mxs2intP. Qed.\n\nLemma mxounitary_sunitary n m (M : 'M_n) :\n  M \\is m.-unitary -> M \\is m.-sunitary.\nProof. by rewrite mxounitaryE; case/andP. Qed.\n\nLemma mxounitary_odd n m (M : 'M_n) :\n  M \\is m.-unitary -> exists i, exists j, odds2i ((sqrtC 2%:R ^+ m) * M i j).\nProof. by case/and3P=> _ _ /mxoddP. Qed.\n\nLemma mxounitary1 n : (1 : 'M_n.+1) \\is 0.-unitary.\nProof. by rewrite qualifE /mxounitary mxunitary1 mxs2int1 mxodd1. Qed.\n\nLemma mxounitaryN (n : nat) c (M : 'M_n) :\n   M \\is c.-unitary -> -M \\is c.-unitary.\nProof.\nmove=> H; move: (H).\nrewrite !mxounitaryE=> /andP[H1 H2].\nby rewrite (mxoddN H1) mxsunitaryN.\nQed.\n\nLemma mxounitaryT n m (M : 'M_n) : (M ^T* \\is m.-unitary) = (M \\is m.-unitary).\nProof.\nrewrite !mxounitaryE mxsunitaryT.\napply/andb_id2l=> /mxsunitary_s2int Hs.\napply/mxoddP/mxoddP => [] [i [j H1]]; exists j; exists i;\n     have := H1; rewrite !mxE => H2.\n  rewrite  -[_ * _]conjCK odds2i_conj ?s2Int_conj //.\n  by rewrite rmorphM rmorphX conjC_sqrt2.\nby rewrite -conjC_sqrt2 -rmorphX -rmorphM odds2i_conj.\nQed.\n\nLemma mxounitary_tr n m (M : 'M_n) : M \\is m.-unitary -> M^T* = M^T.\nProof.\nmove=> sO.\nhave sn : M \\is m.-sunitary by move: sO; rewrite mxounitaryE => /andP[]. \nby apply: mxsunitary_tr sn.\nQed.\n\nLemma odds2ij_row3 m (M : 'M_3) i (k := sqrtC (2%:R) ^+ m.+1) : \n  M \\is m.+1.-sunitary -> \n   ~~ ((odds2i (k * M i 0) && odds2j (k * M i 0)) (+) \n       (odds2i (k * M i 1) && odds2j (k * M i 1)) (+) \n       (odds2i (k * M i o2) && odds2j (k * M i o2))).\nProof.\nmove=> /andP[/mxunitaryP/(_ i i)].\nrewrite sum3E eqxx /= => H /mxs2intP F0.\nhave F1 j1 : 2%:R ^+ m.+1 *  (M i j1 * (M i j1)^*) =  (k * M i j1) ^+ 2.\n  rewrite [RHS]expr2 -{2}(_ : k * (M i j1) ^* = k * M i j1).\n    rewrite -[RHS]mulrA  [_ * (k * _)]mulrCA !mulrA -expr2.\n    by rewrite -exprM mulnC exprM sqrtCK.\n  rewrite {1}/k -conjC_sqrt2 -rmorphX -rmorphM.\n  by rewrite conj_Creal // Creal_s2Int // s2Int_conj.\nhave : s2intB (2%:R ^+ m.+1 * 1%:R) == 0.\n  by rewrite mulr1 -natrX /odds2j s2intB_nat.\nrewrite -H !mulrDr !F1 !s2intB_add ?[s2intB (_ ^+ _)]s2intB_mul \n        ?(rpredX, rpredD) //.\nhave F2 x : x + x = 2%:R * x by rewrite mulrDl mul1r.\nrewrite ![s2intB _ * _]mulrC !F2 -!mulrDr mulf_eq0 /=.\nby rewrite /odds2i /odds2j /odds2j -!oddzM -!oddzD => /eqP->.\nQed.\n\nLemma odds2ij_col3 m (M : 'M_3) i (k := sqrtC (2%:R) ^+ m.+1)  : \n  M \\is m.+1.-sunitary -> \n  ~~ ((odds2i (k * M 0 i) && odds2j (k * M 0 i)) (+) \n      (odds2i (k * M 1 i) && odds2j (k * M 1 i)) (+) \n      (odds2i (k * M o2 i) && odds2j (k * M o2 i))).\nProof.\nmove=> H.\nmove: (H); rewrite -mxsunitaryT  (mxsunitary_tr H) => H1.\nhave := odds2ij_row3 i H1.\nby rewrite !mxE.\nQed.\n\nLemma odds2i_2row3 m (M : 'M_3) i j (k := sqrtC (2%:R) ^+ m.+1) : \n  M \\is m.+1.-sunitary -> \n   ~~ ((odds2i (k * M i 0) && odds2i (k * M j 0)) (+) \n       (odds2i (k * M i 1) && odds2i (k * M j 1)) (+) \n       (odds2i (k * M i o2) && odds2i (k * M j o2))).\nProof.\nmove=> Hn.\nhave /mxsunitary_s2int Hs := Hn.\nhave /mxsunitary_unitary/mxunitaryP/(_ i j) := Hn.\nrewrite sum3E => Ho.\nhave F1 j1 : 2%:R ^+ m.+1 *  (M i j1 * (M j j1)^*) = \n             (k * M i j1) * (k * M j j1).\n  rewrite  -(_ : k * (M j j1) ^* = k * M j j1).\n    rewrite -[RHS]mulrA  [_ * (k * _)]mulrCA !mulrA -expr2.\n    by rewrite -exprM mulnC exprM sqrtCK.\n  rewrite {1}/k -conjC_sqrt2 -rmorphX -rmorphM.\n  by rewrite conj_Creal // Creal_s2Int // s2Int_conj.\nhave : ~~ odds2i (2%:R ^+ m.+1 * (i == j)%:R).\n  case: eqP => _.\n    rewrite mulr1.\n    have ->: 2%:R ^+ m.+1 = (2%:R ^+ m.+1 : S2I) :> algC by rewrite rmorphX.\n    rewrite odds2i_dvd; apply/dvdS2IP; exists (sQ2 * 2%:R ^+ m); rewrite exprSr.\n    by rewrite mulrAC -expr2 sQ2K mulrC.\n  by rewrite mulr0 /odds2i (s2intA_nat 0).\nby rewrite -Ho !mulrDr !F1 !odds2iD ?rpredD 1?rpredM //\n           ![odds2i (_ * _ * _)]odds2iM.\nQed.\n\nLemma odds2i_row3 m (M : 'M_3) i (k := sqrtC (2%:R) ^+ m.+1) : \n  M \\is m.+1.-sunitary -> \n  ~~ (odds2i (k * M i 0) (+) odds2i (k * M i 1) (+) odds2i (k * M i o2)).\nProof.\nmove=> Hn.\nhave := odds2i_2row3 i i Hn.\nby rewrite !andbb.\nQed.\n\nLemma odds2i_row3_gen m (M : 'M_3) i i1 j1 k1 (k := sqrtC (2%:R) ^+ m.+1)  : \n  M \\is m.+1.-sunitary -> i1 != j1 -> i1 != k1 -> j1 != k1 ->\n  ~~ (odds2i (k * M i i1) (+) odds2i (k * M i j1) (+) odds2i (k * M i k1)).\nProof.\nmove=> Hn i1Dj1 i1Dk1 j1Dk1.\nrewrite (_ : _ (+) _ = \\big[addb/false]_j (odds2i (k * M i j))); last first.\n  rewrite (bigD1 i1) // (bigD1 j1) 1?eq_sym // \n          (bigD1 k1) ?[k1 == _]eq_sym ?i1Dk1 //=.\n  rewrite big1 ?addbF ?addbA //.\n  move=> k2 /andP[/andP[k2Di1 k2Dj1 k2Dk1]].\n  have := card_ord 3.\n  rewrite (cardD1 i1) (cardD1 j1) (cardD1 k1) (cardD1 k2).\n  by rewrite !inE ![k1 == _]eq_sym i1Dk1 j1Dk1 k2Dk1 k2Dj1 k2Di1 eq_sym i1Dj1.\nrewrite (bigD1 0) // (bigD1 1) // (bigD1 o2) //= big1 ?addbF ?addbA.\n  by apply: odds2i_row3 Hn.\nby case => [] [|[|[|]]].\nQed.\n\nLemma odds2i_2col3 m (M : 'M_3) i j (k := sqrtC (2%:R) ^+ m.+1) : \n  M \\is m.+1.-sunitary -> \n   ~~ ((odds2i (k * M 0 i) && odds2i (k * M 0 j)) (+) \n       (odds2i (k * M 1 i) && odds2i (k * M 1 j)) (+) \n       (odds2i (k * M o2 i) && odds2i (k * M o2 j))).\nProof.\nmove=> H.\nmove: (H); rewrite -mxsunitaryT  (mxsunitary_tr H) => H1.\nhave := odds2i_2row3 i j H1.\nby rewrite !mxE.\nQed.\n\nLemma odds2i_col3 m (M : 'M_3) i (k := sqrtC (2%:R) ^+ m.+1) : \n  M \\is m.+1.-sunitary -> \n  ~~ (odds2i (k * M 0 i) (+) odds2i (k * M 1 i) (+) odds2i (k * M o2 i)).\nProof.\nmove=> Hn.\nhave := odds2i_2col3 i i Hn.\nby rewrite !andbb.\nQed.\n\nLemma odds2i_col3_gen m (M : 'M_3) i i1 j1 k1 (k := sqrtC (2%:R) ^+ m.+1) : \n  M \\is m.+1.-sunitary -> i1 != j1 -> i1 != k1 -> j1 != k1 ->\n  ~~ (odds2i (k * M i1 i) (+) odds2i (k * M j1 i) (+) odds2i (k * M k1 i)).\nProof.\nmove=> Hn i1Dj1 i1Dk1 j1Dk1.\nmove: (Hn); rewrite -mxsunitaryT  (mxsunitary_tr Hn) => Hn1.\nhave := odds2i_row3_gen i Hn1 i1Dj1 i1Dk1 j1Dk1.\nby rewrite !mxE.\nQed.\n\nLemma mxsunitary_eq0 (M : 'M_3) i j : \n  M \\is 0.-sunitary -> [|| M i j == 0, M i j == -1 | M i j == 1].\nProof.\nmove=> Hn.\nhave F i1 j1 : M i1 j1 \\is a s2Int.\n  by have := mxsunitary_s2int i1 j1 Hn; rewrite mul1r.\nhave F1 : \\sum_(k < 3) (M i k) ^+ 2 = 1.\n  have /mxunitaryP/(_ i i) := mxsunitary_unitary Hn.\n  rewrite eqxx mulr1n /= => <-.\n  apply: eq_bigr => k _.\n  by rewrite expr2 conj_Creal // Creal_s2Int.\nhave [/eqP->//|nZM]:= boolP (M i  j == 0).\nhave := congr1 s2intA F1.\nrewrite (s2intA_nat 1) /= s2intA_sum /= => [|k _ _]; last first.\n  by rewrite expr2 rpredM.\nrewrite (bigD1 j) //= => H1.\nsuff /s2intA_sqrt_eq1-> : s2intA (M i j ^+ 2) = 1 by [].\napply: le_anti.\nrewrite -{1}[1]H1 ler_addl s2intA_sqrt_gt1 ?andbT //.\nelim/big_rec: _ => // k y _ yP.\napply: addr_ge0 => //.\nhave [/eqP->|nZxs] := boolP (M i k == 0).\n  by rewrite expr0n (s2intA_nat 0).\nby apply: le_trans (s2intA_sqrt_gt1  _ _).\nQed.\n\nDefinition even_row n m (M : 'M_n) i :=\n   [forall j,  ~~ odds2i (((sqrtC 2%:R) ^+ m) * M i j)].\n\nLemma even_row3E i m (M : 'M_3) (k := (sqrtC 2%:R) ^+ m) : \n  even_row m M i = \n  [&& ~~ odds2i (k * M i 0), ~~ odds2i (k * M i 1)  &  ~~ odds2i (k * M i o2)].\nProof.\napply/forallP/and3P=> [H|[H1 H2 H3 j]] //.\nby case/or3P: (o3E j) => /eqP->.\nQed. \n\nLemma even_row3_inj i j m (M : 'M_3) :\n  M \\is m.+1.-unitary -> even_row m.+1 M i -> even_row m.+1 M j -> i = j.\nProof.\nmove=> Hs; move: (Hs).\nrewrite mxounitaryE => /andP[Hn /mxoddP[i1 [j1 Ho1]]].\nmove=> /forallP/(_ j1) Ei /forallP/(_ j1) Ej.\ncase: (i =P j) => // /eqP iDj.\nhave i1Di : i1 != i by apply: contra Ei => /eqP<-.\nhave i1Dj : i1 != j by apply: contra Ej => /eqP<-.\nhave /negP[] := odds2i_col3_gen j1 Hn i1Di i1Dj iDj.\nby rewrite Ho1 (negPf Ei) (negPf Ej).\nQed.\n\nDefinition even_col n m (M : 'M_n) j := \n   [forall i,  ~~ odds2i (((sqrtC 2%:R) ^+ m) * M i j)].\n\nLemma even_col_def n m (M : 'M_n) j : even_col m M j =  even_row m (M^T) j.\nProof.\nby apply/forallP/forallP=> H i; have := H i; rewrite mxE.\nQed.\n\nLemma even_col_row n m (M : 'M_n) i : \n  M \\is m.-s2int -> even_col m M i = even_row m (M^T*) i.\nProof. by move=> Hs; rewrite even_col_def (mxs2int_tr Hs). Qed.\n\nLemma even_row_col n m (M : 'M_n) i : even_row m M i = even_col m M^T i.\nProof. by rewrite even_col_def trmxK. Qed.\n\nLemma even_col3E i m M (k := (sqrtC 2%:R) ^+ m) : \n  even_col m M i = \n  [&& ~~ odds2i (k * M 0 i), ~~ odds2i (k * M 1 i) &  ~~ odds2i (k * M o2 i)].\nProof. by rewrite even_col_def even_row3E !mxE. Qed.\n\nLemma even_col3_inj i j m (M : 'M_3) :\n  M \\is m.+1.-unitary -> even_col m.+1 M i -> even_col m.+1 M j -> i = j.\nProof.\nmove=> Ho; rewrite !even_col_def; apply: even_row3_inj.\nby rewrite -(mxounitary_tr Ho) mxounitaryT.\nQed.\n\nDefinition erow n m (M : 'M_n.+1) := odflt 0 [pick i | even_row m M i].\nDefinition ecol n m (M : 'M_n.+1) := odflt 0 [pick i | even_col m M i].\n\nLemma even_erow3 m (M : 'M_3) :\n M \\is m.+1.-sunitary -> even_row m.+1 M (erow m.+1 M).\nProof.\nmove=> Hn; rewrite /erow; case: pickP => // H.\nhave := odds2i_row3 0 Hn.\nhave := odds2i_row3 1 Hn.\nhave := odds2i_row3 o2 Hn.\nhave :=  odds2i_2col3 0 1 Hn.\nhave :=  odds2i_2col3 0 o2 Hn.\nhave :=  odds2i_2col3 1 o2 Hn.\nhave /idP/negP := H 0.\nhave /idP/negP := H 1.\nhave /idP/negP := H o2.\nrewrite !even_row3E.\nby do 9 (case: odds2i; rewrite ?(addbT, addbF) //=).\nQed.\n\nLemma even_ecol3 m (M : 'M_3) :\n  M \\is m.+1.-sunitary -> even_col m.+1 M (ecol m.+1 M).\nProof.\nmove=> Hn; rewrite /ecol; case: pickP => // H.\nhave := odds2i_col3 0 Hn.\nhave := odds2i_col3 1 Hn.\nhave := odds2i_col3 o2 Hn.\nhave :=  odds2i_2row3 0 1 Hn.\nhave :=  odds2i_2row3 0 o2 Hn.\nhave :=  odds2i_2row3 1 o2 Hn.\nhave /idP/negP := H 0.\nhave /idP/negP := H 1.\nhave /idP/negP := H o2.\nrewrite !even_col3E.\nby do 9 (case: odds2i; rewrite ?(addbT, addbF) //=).\nQed.\n\nLemma mxounitary_odds2i m (M : 'M_3) i j (k := sqrtC (2%:R) ^+ m.+1)  :\n  M \\is m.+1.-unitary -> \n  odds2i (k * M i j) = (i != erow m.+1 M) && (j != ecol m.+1 M).\nProof.\nmove=> Hn.\nmove: Hn; rewrite mxounitaryE => /andP[Hn  /mxoddP[i1 [j1 Ho1]]].\ncase: eqP=> [->|/eqP Hr]/=.\n  by have /forallP/(_ j)/negPf := even_erow3 Hn.\ncase: eqP=> [->|/eqP Hc]/=.\n  by have /forallP/(_ i)/negPf := even_ecol3 Hn.\nhave iDe : i1 != erow m.+1 M.\n  have /forallP/(_ j1) Hs1 := even_erow3 Hn.\n  by apply: contra Hs1 => /eqP<-.\nhave jDe : j1 != ecol m.+1 M.\n  have /forallP/(_ i1) Hs1 := even_ecol3 Hn.\n  by apply: contra Hs1 => /eqP<-.\nhave [/eqP iEi1|iDi1] := boolP (i1 == i).\n  have [/eqP jEj1|jDj1] := boolP (j1 == j).\n    by rewrite -iEi1 -jEj1.\n  have := odds2i_row3_gen i Hn jDj1 jDe Hc.\n  rewrite (negPf (forallP (even_ecol3 Hn) i)) addbF.\n  by rewrite -iEi1 Ho1 negbK.\nhave := odds2i_col3_gen j1 Hn iDi1 iDe Hr.\nrewrite (negPf (forallP (even_erow3 Hn) j1)).\nrewrite Ho1 addbF negbK => sO1.\nhave [/eqP <-//|jDj1] := boolP (j1 == j).\nhave := odds2i_row3_gen i Hn jDj1 jDe Hc.\nby rewrite (negPf (forallP (even_ecol3 Hn) i)) sO1 addbF negbK.\nQed.\n\nLemma mxsunitary_oddij m k (M : 'M[algC]_3) :\n   M \\is m.+2.-sunitary ->  M \\isn't m.+2.-odd ->\n   (forall i j, j != k -> ~~ odds2j ((sqrtC 2%:R) ^+ m.+2 * M i j)) ->\n   M \\is m.-sunitary.\nProof.\nmove=> Hn Ho Hj.\nhave F1 : M \\is m.+1.-sunitary by rewrite mxsunitary_odd.\nhave F2 (k1 : 'I_3)  : k1 != k -> even_col m.+1 M k1.\n  move=> k1Dk; apply/forallP => i1.\n  have F3 : ((sqrtC 2%:R)^m.+1 *: M) i1 k1 \\is a s2Int.\n    by have := mxsunitary_s2int i1 k1 F1; rewrite mxE.\n  pose x := S2Iof F3.\n  have F4 : ((sqrtC 2%:R)^m.+2 *: M) i1 k1 \\is a s2Int\n    by have := mxsunitary_s2int i1 k1 Hn; rewrite mxE.\n  pose y := S2Iof F4.\n  have yE : y = x * sQ2.\n    apply/val_eqP => /=.\n    by rewrite !mxE [_ * sqrtC _]mulrC mulrA.\n  have := (odds2i_dvd x); rewrite /= mxE => ->.\n  have oy : ~~ odds2i y.\n    by have /mxoddPn /(_ i1 k1) := Ho; rewrite /= mxE.\n  suff: 2%:R %| y.\n    move=> /dvdS2IP[z]; rewrite yE -sQ2K expr2 mulrA.\n    rewrite ![_ * sQ2]mulrC => HH.\n    apply/dvdS2IP; exists z.\n    have /mulfI : sQ2 != 0 by apply/val_eqP/eqP/sqrt2_neq0.\n    apply.\n    by rewrite HH [_ * z]mulrC.\n  by rewrite -odds2ij_dvd negb_or oy /= !mxE Hj.\nhave /F2 H1 : k + 1 != k by rewrite addrC -subr_eq0 addrK.\nhave /F2 H2 : k + 2%:R != k by rewrite addrC -subr_eq0 addrK.\nrewrite mxsunitary_odd //; apply/negP => Ho1.\nsuff /even_col3_inj/(_ H1 H2)/eqP : M \\is m.+1.-unitary.\n  by rewrite addrC -subr_eq0 opprD addrA addrK.\nby rewrite mxounitaryE F1.\nQed.\n  \nDefinition seq2matrix (R: ringType) m n (l: seq (seq R)) :=\n  \\matrix_(i<m,j<n) nth 1 (nth [::] l i) j.\n\nLocal Notation \"''M{' l } \" := (seq2matrix _ _ l).\n\nDefinition Tx :'M[algC]_3 := \n            (sqrtC 2%:R)^-1 *:  'M{[::[::sqrtC 2%:R; 0 ;  0]; \n                                   [::   0      ; 1 ; -1]; \n                                   [::   0      ; 1 ;  1]]}.\n\nLemma mxounitary_Tx : Tx \\is 1.-unitary.\nProof.\nhave F := algS2IP sQ2.\nhave F1 : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave F2 : (sqrtC 2%:R)^-1 \\is Creal by rewrite rpredV Creal_s2Int.\napply/and3P; split.\n- by apply/mxunitaryP => i j;\n     case/or3P: (o3E i) => /eqP->; case/or3P: (o3E j) => /eqP->;\n     rewrite sum3E !mxE\n            ?(mulVf, conjC0, conjC1, mul0r, mulr0, addr0, add0r, mulr1, \n             mulrN1, mulNr, mulrN, opprK, rmorphN, subrr) //=;\n    rewrite !conj_Creal // -invfM // -expr2 sqrtCK\n             -[_^-1]mul1r -mulrDl mulfV // (eqC_nat 2 0).\n- by apply/mxs2intP=> i j; \n     case/or3P : (o3E i) => /eqP->; case/or3P : (o3E j) => /eqP->;\n     rewrite !mxE /= ?(mulr0, mulr1, mulrN, mulVf, mulfV)\n                   ?(rpred0, rpredN, rpred1).\napply/mxoddP; exists 1; exists 1.\nby rewrite !mxE /= mulr1 expr1 mulfV // (odds2i_nat 1).\nQed.\n\nDefinition Ty :'M[algC]_3 := \n             (sqrtC 2%:R)^-1 *: 'M{[::[:: 1 ;          0;  1]; \n                                   [:: 0 ; sqrtC 2%:R;  0]; \n                                   [::-1 ;          0;  1]]}.\n\nLemma mxounitary_Ty : Ty \\is 1.-unitary.\nProof.\nhave F := algS2IP sQ2.\nhave F1 : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave F2 : (sqrtC 2%:R)^-1 \\is Creal by rewrite rpredV Creal_s2Int.\napply/andP; split.\n  by apply/mxunitaryP => i j;\n     case/or3P: (o3E i) => /eqP->; case/or3P: (o3E j) => /eqP->;\n     rewrite sum3E !mxE\n            ?(mulVf, conjC0, conjC1, mul0r, mulr0, addr0, add0r, mulr1, \n             mulrN1, mulNr, mulrN, opprK, rmorphN, oppr0) 1?addrC ?subrr //;\n     rewrite !conj_Creal // -invfM // -expr2 sqrtCK\n             -[_^-1]mul1r -mulrDl mulfV // (eqC_nat 2 0).\napply/andP; split.\n  by apply/forallP=> i; apply/forallP=> j; \n     case/or3P : (o3E i) => /eqP->; case/or3P : (o3E j) => /eqP->;\n     rewrite !mxE /= ?(mulr0, mulr1, mulrN, mulVf, mulfV)\n                   ?(rpred0, rpredN, rpred1).\napply/existsP; exists 0; apply/existsP; exists 0.\nby rewrite !mxE /= mulr1 expr1 mulfV // (odds2i_nat 1).\nQed.\n\nDefinition Tz :'M[algC]_3 := \n             (sqrtC 2%:R)^-1 *: 'M{[::[::1; -1;          0]; \n                                   [::1;  1;          0];\n                                   [::0;  0; sqrtC 2%:R]]}.\n\nLemma mxounitary_Tz : Tz \\is 1.-unitary.\nProof.\nhave F := algS2IP sQ2.\nhave F1 : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave F2 : (sqrtC 2%:R)^-1 \\is Creal by rewrite rpredV Creal_s2Int.\napply/andP; split.\n  by apply/mxunitaryP => i j;\n     case/or3P: (o3E i) => /eqP->; case/or3P: (o3E j) => /eqP->;\n     rewrite sum3E !mxE\n            ?(mulVf, conjC0, conjC1, mul0r, mulr0, addr0, add0r, mulr1, \n             mulrN1, mulNr, mulrN, opprK, rmorphN, oppr0) ?subrr //;\n     rewrite !conj_Creal // -invfM // -expr2 sqrtCK\n             -[_^-1]mul1r -mulrDl mulfV // (eqC_nat 2 0).\napply/andP; split.\n  by apply/forallP=> i; apply/forallP=> j; \n     case/or3P : (o3E i) => /eqP->; case/or3P : (o3E j) => /eqP->;\n     rewrite !mxE /= ?(mulr0, mulr1, mulrN, mulVf, mulfV)\n                   ?(rpred0, rpredN, rpred1).\napply/existsP; exists 0; apply/existsP; exists 0.\nby rewrite !mxE /= mulr1 expr1 mulfV // (odds2i_nat 1).\nQed.\n\nLemma TxT_mul (M : 'M[algC]_3) :\n   Tx^T* * M =\n (sqrtC 2%:R)^-1 *:\n 'M{[::[::sqrtC 2%:R * M 0 0; sqrtC 2%:R * M 0 1 ;  sqrtC 2%:R * M 0 o2]; \n       [::   M 1 0 + M o2 0;     M 1 1 + M o2 1;     M 1 o2 + M o2 o2];\n       [:: - M 1 0 + M o2 0;   - M 1 1 + M o2 1;   - M 1 o2 + M o2 o2]]}.\nProof.\napply/matrixP=> i j.\nhave F := algS2IP sQ2.\nhave F1 : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave F2 : (sqrtC 2%:R)^-1 \\is Creal by rewrite rpredV Creal_s2Int.\nrewrite !mxE sum3E !mxE /=.\nby case/or3P: (o3E i) => /eqP->; case/or3P: (o3E j) => /eqP-> /=;\n   rewrite ?(mulrA, mulVf, mul0r, mulr0, mul1r, mulr1, rmorph1, rmorph0, \n            add0r, addr0) //;\n   rewrite ?(mulrN1, rmorphN, mulNr, (I, mulrN));\n   rewrite  conj_Creal // ?Creal_s2Int // -mulrDr.\nQed.\n\nLemma TxT_mul_row  (M : 'M[algC]_3) i j :\n   (Tx^T* * M) i j = if i == 0 then M 0 j\n                   else if i == 1 then  (sqrtC 2%:R)^-1 * (M 1 j + M o2 j) else \n                   (sqrtC 2%:R)^-1 * (- M 1 j + M o2 j).\nProof.\nhave F1 : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nrewrite TxT_mul !mxE.\nby case/or3P : (o3E i) => /eqP->; case/or3P : (o3E j) => /eqP->;\n   rewrite //= mulrA mulVf ?mul1r.\nQed.\n\nLemma TyT_mul (M : 'M[algC]_3) :\n   Ty^T* * M =\n (sqrtC 2%:R)^-1 *:\n 'M{[::[::   M 0 0 - M o2 0;     M 0 1 - M o2 1;     M 0 o2 - M o2 o2];\n       [::sqrtC 2%:R * M 1 0; sqrtC 2%:R * M 1 1 ;  sqrtC 2%:R * M 1 o2]; \n       [::   M 0 0 + M o2 0;     M 0 1 + M o2 1;     M 0 o2 + M o2 o2]]}.\nProof.\napply/matrixP=> i j.\nhave F := algS2IP sQ2.\nhave F1 : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave F2 : (sqrtC 2%:R)^-1 \\is Creal by rewrite rpredV Creal_s2Int.\nrewrite !mxE sum3E !mxE /=.\nby case/or3P: (o3E i) => /eqP->; case/or3P: (o3E j) => /eqP-> /=;\n   rewrite ?(mulrA, mulVf, mul0r, mulr0, mul1r, mulr1, rmorph1, rmorph0, \n            add0r, addr0) //;\n   rewrite ?(mulrN1, rmorphN, mulNr, (I, mulrN));\n   rewrite  conj_Creal // ?Creal_s2Int // -mulrDr.\nQed.\n\nLemma TyT_mul_row  (M : 'M[algC]_3) i j :\n   (Ty^T* * M) i j = if i == 1 then M 1 j\n                   else if i == o2 then (sqrtC 2%:R)^-1 * (M 0 j + M o2 j) else \n                    (sqrtC 2%:R)^-1 * (M 0 j - M o2 j).\nProof.\nhave F1 : sqrtC 2%:R != 0 :> algC  by rewrite sqrtC_eq0 (eqC_nat _ 0).\nrewrite TyT_mul !mxE.\nby case/or3P : (o3E i) => /eqP->; case/or3P : (o3E j) => /eqP->;\n   rewrite //= mulrA mulVf ?mul1r.\nQed.\n\nLemma TzT_mul (M : 'M[algC]_3) :\n   Tz^T* * M =\n (sqrtC 2%:R)^-1 *:\n 'M{[::[::   M 0 0 + M 1 0;     M 0 1 + M 1 1;     M 0 o2 + M 1 o2];\n       [:: - M 0 0 + M 1 0;   - M 0 1 + M 1 1;   - M 0 o2 + M 1 o2];\n       [::sqrtC 2%:R * M o2 0; sqrtC 2%:R * M o2 1 ;  sqrtC 2%:R * M o2 o2]]}.\nProof.\napply/matrixP=> i j.\nhave F := algS2IP sQ2.\nhave F1 : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave F2 : (sqrtC 2%:R)^-1 \\is Creal by rewrite rpredV Creal_s2Int.\nrewrite !mxE sum3E !mxE /=.\nby case/or3P: (o3E i) => /eqP->; case/or3P: (o3E j) => /eqP-> /=;\n   rewrite ?(mulrA, mulVf, mul0r, mulr0, mul1r, mulr1, rmorph1, rmorph0, \n            add0r, addr0) //;\n   rewrite ?(mulrN1, rmorphN, mulNr, (I, mulrN));\n   rewrite  conj_Creal // ?Creal_s2Int // -mulrDr.\nQed.\n\nLemma TzT_mul_row  (M : 'M[algC]_3) i j :\n   (Tz^T* * M) i j = if i == o2 then M o2 j\n                   else if i == 0 then (sqrtC 2%:R)^-1 * (M 0 j + M 1 j) else \n                   (sqrtC 2%:R)^-1 * (- M 0 j + M 1 j).\nProof.\nhave F1 : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nrewrite TzT_mul !mxE.\nby case/or3P : (o3E i) => /eqP->; case/or3P : (o3E j) => /eqP->;\n   rewrite //= mulrA mulVf ?mul1r.\nQed.\n\nLemma mxsunitary_TxT m (M : 'M_3) : \n  M \\is m.+1.-unitary -> (Tx^T* * M \\is m.-sunitary) = (erow m.+1 M == 0).\nProof.\nmove=> Hos.\nhave Hn := mxounitary_sunitary Hos.\npose k : algC := (sqrtC 2%:R) ^+ m.+1.\npose l : algC := (sqrtC 2%:R) ^+ m.+2.\nhave F := algS2IP sQ2.\nhave F1 : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave S1 := mxounitary_s2int _ _ Hos.\ncase: eqP => [E1|/eqP D1].\n  have F2 (k1 : 'I_3)  : \n    k1 != ecol m.+1 M -> even_col m.+2 (Tx ^T* * M) k1.\n    move=> k1Dk; apply/forallP => i1.\n    rewrite TxT_mul_row.\n    case: eqP => H1.\n      rewrite exprS -mulrA odds2iM ?(algS2IP sQ2) // negb_and odds2i_sQ2.\n      by rewrite (mxounitary_odds2i _ _ Hos).\n    case: eqP => H2.\n      rewrite exprSr !mulrA mulfK // mulrDr.\n      rewrite odds2iD // negb_add.\n      by rewrite !mxounitary_odds2i // E1.\n    rewrite exprSr !mulrA mulfK // mulrDr mulrN.\n    rewrite odds2iD ?rpredN // odds2iN // negb_add.\n    by rewrite !mxounitary_odds2i // E1.\n  have /F2 H1 : ecol m.+1 M + 1 != ecol m.+1 M.\n    by rewrite addrC -subr_eq0 addrK.\n  have /F2 H2 : ecol m.+1 M + 2%:R != ecol m.+1 M.\n    by rewrite addrC -subr_eq0 addrK.\n  have H3 : Tx ^T* * M \\is m.+2.-sunitary.\n    by rewrite -[m.+2]add1n mxsunitaryM //\n               mxsunitaryT ?mxounitary_sunitary ?mxounitary_Tx.\n  have F3 : Tx ^T* * M \\isn't m.+2.-odd.\n    apply/negP=> F3.\n    have Hos2 : Tx ^T* * M \\is m.+2.-unitary by rewrite mxounitaryE H3.\n    have /eqP := even_col3_inj Hos2 H1 H2.\n    by rewrite addrC -subr_eq0 opprD addrA addrK.\n  suff F4 i1 j1 : j1 !=\n     ecol m.+1 M -> ~~ odds2j (l * (Tx ^T* * M) i1 j1).\n    by apply: mxsunitary_oddij F4.\n  move=> j1De.\n  rewrite TxT_mul_row.\n  case: eqP => H1'.\n    rewrite [l]exprS -mulrA odds2jM ?(algS2IP sQ2) //.\n    rewrite  (negPf odds2i_sQ2) odds2j_sQ2 /=.\n    by rewrite (mxounitary_odds2i _ _ Hos) // negb_and !negbK E1.\n  case: eqP => H2'.\n    rewrite [l]exprSr !mulrA mulfK // mulrDr odds2jD // .\n    have := odds2ij_col3 j1 Hn.\n    by rewrite !(mxounitary_odds2i _ _ Hos) E1 j1De.\n  rewrite [l]exprSr !mulrA mulfK // mulrDr mulrN.\n  rewrite odds2jD ?rpredN // odds2jN //.\n  have := odds2ij_col3 j1 Hn.\n  by rewrite !(mxounitary_odds2i _ _ Hos) // E1 j1De.\napply/idP => /andP[_ /forallP/(_ 0)/forallP/(_ (ecol m.+1 M + 1))].\nrewrite  TxT_mul_row /= => /s2intP [a [b Hab]].\nhave : odds2i (k * M 0 (ecol m.+1 M + 1)).\n  by rewrite (mxounitary_odds2i _ _ Hos) eq_sym D1 addrC -subr_eq0 addrK.\nrewrite {1}[k]exprS -mulrA Hab odds2iM ?sqrt2_S2I //.\n  by rewrite (negPf odds2i_sQ2).\nby apply/s2intP; exists a; exists b.\nQed.\n\nLemma mxounitaryS_TxT m (M : 'M_3) :\n   M \\is m.+2.-unitary -> Tx^T* * M \\isn't m.-sunitary.\nProof.\nmove=> Hos; apply/negP=> Hn1.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave := mxsunitary_TxT  Hos.\ncase: eqP => [He /idP Hn| He /idP[]]; last first.\n  by apply: mxsunitaryW Hn1.\npose k : algC := sqrtC 2%:R ^+ m.+2.\npose l : algC := sqrtC 2%:R ^+ m.+1.\npose l1 : algC := sqrtC 2%:R ^+ m.\npose x := l * ((Tx ^T* * M) 1 (ecol m.+2 M + 1)).\nhave Px : x \\is a s2Int by apply: mxsunitary_s2int Hn.\nhave [Ox|Ex] := boolP (odds2i x).\n  suff : sQ2 %| (S2Iof Px) by rewrite -odds2i_dvd Ox.\n  pose x1 := l1 * ((Tx ^T* * M)  1 (ecol m.+2 M + 1)).\n  have Px1 : x1 \\is a s2Int by apply: mxsunitary_s2int Hn1.\n  apply/dvdS2IP; exists (S2Iof Px1).\n  apply/val_eqP => /=.\n  by rewrite /x /x1 !mxE [_ * sqrtC _]mulrC mulrA [l]exprS.\npose y := l * ((Tx ^T* * M)) o2 (ecol m.+2 M + 1).\nhave Py : y \\is a s2Int by apply: mxsunitary_s2int Hn.\nhave : odds2i (x + y).\n  rewrite /x /y TxT_mul_row /= TxT_mul_row /=. \n  rewrite !mulrDr !mulrN [_ * _ + _]addrC addrA addrK -mulrDr.\n  rewrite (_ : ?[x] + ?x = 2%:R * ?x); last by rewrite mulrDl mul1r.\n  rewrite -{1}[2%:R]sqrtCK !mulrA -exprSr mulfK //.\n  by rewrite (mxounitary_odds2i _  _ Hos) He /=  addrC -subr_eq0 addrK.\nrewrite odds2iD // (negPf Ex) /= => Oy.\nsuff : sQ2 %| (S2Iof Py) by rewrite -odds2i_dvd Oy.\npose y1 := l1 * ((Tx ^T* * M)  o2 (ecol m.+2 M + 1)).\nhave Py1 : y1 \\is a s2Int by apply: mxsunitary_s2int Hn1.\napply/dvdS2IP; exists (S2Iof Py1). \napply/val_eqP => /=.\nby rewrite /y /y1 [_ * sqrtC _]mulrC mulrA -exprS.\nQed.\n\nLemma mxsunitary_TyT m (M : 'M_3) : \n  M \\is m.+1.-unitary -> (Ty^T* * M \\is m.-sunitary) = (erow m.+1 M == 1).\nProof.\nmove=> Hos.\nhave Hn := mxounitary_sunitary Hos.\npose k : algC := (sqrtC 2%:R) ^+ m.+1.\npose l : algC := (sqrtC 2%:R) ^+ m.+2.\nhave F := algS2IP sQ2.\nhave F1 : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave S1 := mxounitary_s2int _ _ Hos.\ncase: eqP => [E1|/eqP D1].\n  have F2 (k1 : 'I_3)  : \n    k1 != ecol m.+1 M -> even_col m.+2 (Ty ^T* * M) k1.\n    move=> k1Dk; apply/forallP => i1.\n    rewrite TyT_mul_row.\n    case: eqP => H1.\n      rewrite exprS -mulrA odds2iM ?(algS2IP sQ2) // negb_and odds2i_sQ2.\n      by rewrite (mxounitary_odds2i _ _ Hos).\n    case: eqP => H2.\n      rewrite exprSr !mulrA mulfK // mulrDr.\n      rewrite odds2iD // negb_add.\n      by rewrite !mxounitary_odds2i // E1.\n    rewrite exprSr !mulrA mulfK // mulrDr mulrN.\n    rewrite odds2iD ?rpredN // odds2iN // negb_add.\n    by rewrite !mxounitary_odds2i // E1.\n  have /F2 H1 : ecol m.+1 M + 1 != ecol m.+1 M.\n    by rewrite addrC -subr_eq0 addrK.\n  have /F2 H2 : ecol m.+1 M + 2%:R != ecol m.+1 M.\n    by rewrite addrC -subr_eq0 addrK.\n  have H3 : Ty ^T* * M \\is m.+2.-sunitary.\n    by rewrite -[m.+2]add1n mxsunitaryM //\n               mxsunitaryT ?mxounitary_sunitary  ?mxounitary_Ty.\n  have F3 : Ty ^T* * M \\isn't m.+2.-odd.\n    apply/negP=> F3.\n    have Hos2 : Ty ^T* * M \\is m.+2.-unitary by rewrite mxounitaryE H3.\n    have /eqP := even_col3_inj Hos2 H1 H2.\n    by rewrite addrC -subr_eq0 opprD addrA addrK.\n  suff F4 i1 j1 : j1 !=\n     ecol m.+1 M -> ~~ odds2j (l * (Ty ^T* * M) i1 j1).\n    by apply: mxsunitary_oddij F4.\n  move=> j1De.\n  rewrite TyT_mul_row.\n  case: eqP => H1'.\n    rewrite [l]exprS -mulrA odds2jM ?(algS2IP sQ2) //.\n    rewrite  (negPf odds2i_sQ2) odds2j_sQ2 /=.\n    by rewrite (mxounitary_odds2i _ _ Hos) // negb_and !negbK E1.\n  case: eqP => H2'.\n    rewrite [l]exprSr !mulrA mulfK // mulrDr -/k odds2jD // .\n    have := odds2ij_col3 j1 Hn.\n    by rewrite !(mxounitary_odds2i _ _ Hos) // E1 j1De addbF.\n  rewrite [l]exprSr !mulrA mulfK // mulrDr -/k mulrN.\n  rewrite odds2jD ?rpredN // odds2jN //.\n  have := odds2ij_col3 j1 Hn.\n  by rewrite !(mxounitary_odds2i _ _ Hos) // E1 j1De addbF.\napply/idP => /andP[_ /forallP/(_ 1)/forallP/(_ (ecol m.+1 M + 1))].\nrewrite  TyT_mul_row /= => /s2intP [a [b Hab]].\nhave : odds2i (k * M 1 (ecol m.+1 M + 1)).\n  by rewrite (mxounitary_odds2i _ _ Hos) eq_sym D1 addrC -subr_eq0 addrK.\nrewrite {1}[k]exprS -mulrA Hab odds2iM ?sqrt2_S2I //.\n  by rewrite (negPf odds2i_sQ2).\nby apply/s2intP; exists a; exists b.\nQed.\n\n\nLemma mxounitaryS_TyT m (M : 'M_3) :\n   M \\is m.+2.-unitary ->  Ty^T* * M \\isn't m.-sunitary.\nProof.\nmove=> Hos; apply/negP=> Hn1.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave := mxsunitary_TyT  Hos.\ncase: eqP => [He /idP Hn| He /idP[]]; last first.\n  by apply: mxsunitaryW Hn1.\npose k : algC := sqrtC 2%:R ^+ m.+2.\npose l : algC := sqrtC 2%:R ^+ m.+1.\npose l1 : algC := sqrtC 2%:R ^+ m.\npose x := l * ((Ty ^T* * M) 0 (ecol m.+2 M + 1)).\nhave Px : x \\is a s2Int by apply: mxsunitary_s2int Hn.\nhave [Ox|Ex] := boolP (odds2i x).\n  suff : sQ2 %| (S2Iof Px) by rewrite -odds2i_dvd Ox.\n  pose x1 := l1 * ((Ty ^T* * M) 0 (ecol m.+2 M + 1)).\n  have Px1 : x1 \\is a s2Int by apply: mxsunitary_s2int Hn1.\n  apply/dvdS2IP; exists (S2Iof Px1).\n  apply/val_eqP => /=.\n  by rewrite /x /x1 !mxE [_ * sqrtC _]mulrC mulrA [l]exprS.\npose y := l * ((Ty ^T* * M)) o2 (ecol m.+2 M + 1).\nhave Py : y \\is a s2Int by apply: mxsunitary_s2int Hn.\nhave : odds2i (x + y).\n  rewrite /x /y TyT_mul_row /= TyT_mul_row /=. \n  rewrite mulrBr !mulrDr mulrN -/k [X in odds2i(_ + _ + X)]addrC.\n  rewrite addrA subrK -mulrDr.\n  rewrite (_ : ?[x] + ?x = 2%:R * ?x); last by rewrite mulrDl mul1r.\n  rewrite -{1}[2%:R]sqrtCK !mulrA -exprSr mulfK //.\n  by rewrite (mxounitary_odds2i _  _ Hos) He /=  addrC -subr_eq0 addrK.\nrewrite odds2iD // (negPf Ex) /= => Oy.\nsuff : sQ2 %| (S2Iof Py) by rewrite -odds2i_dvd Oy.\npose y1 := l1 * ((Ty ^T* * M)  o2 (ecol m.+2 M + 1)).\nhave Py1 : y1 \\is a s2Int by apply: mxsunitary_s2int Hn1.\napply/dvdS2IP; exists (S2Iof Py1). \napply/val_eqP => /=.\nby rewrite /y /y1 [_ * sqrtC _]mulrC mulrA -exprS.\nQed.\n\nLemma mxsunitary_TzT m (M : 'M_3) : \n  M \\is m.+1.-unitary -> (Tz^T* * M \\is m.-sunitary) = (erow m.+1 M == o2).\nProof.\nmove=> Hos.\nhave Hn := mxounitary_sunitary Hos.\npose k : algC := (sqrtC 2%:R) ^+ m.+1.\npose l : algC := (sqrtC 2%:R) ^+ m.+2.\nhave F := algS2IP sQ2.\nhave F1 : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave S1 := mxounitary_s2int _ _ Hos.\ncase: eqP => [E1|/eqP D1].\n  have F2 (k1 : 'I_3)  : \n    k1 != ecol m.+1 M -> even_col m.+2 (Tz ^T* * M) k1.\n    move=> k1Dk; apply/forallP => i1.\n    rewrite TzT_mul_row.\n    case: eqP => H1.\n      rewrite exprS -mulrA odds2iM ?(algS2IP sQ2) // negb_and odds2i_sQ2.\n      by rewrite (mxounitary_odds2i _ _ Hos).\n    case: eqP => H2.\n      rewrite exprSr !mulrA mulfK // mulrDr -/k.\n      rewrite odds2iD // negb_add.\n      by rewrite !mxounitary_odds2i // E1.\n    rewrite exprSr !mulrA mulfK // mulrDr -/k mulrN.\n    rewrite odds2iD ?rpredN // odds2iN // negb_add.\n    by rewrite !mxounitary_odds2i // E1.\n  have /F2 H1 : ecol m.+1 M + 1 != ecol m.+1 M.\n    by rewrite addrC -subr_eq0 addrK.\n  have /F2 H2 : ecol m.+1 M + 2%:R != ecol m.+1 M.\n    by rewrite addrC -subr_eq0 addrK.\n  have H3 : Tz ^T* * M \\is m.+2.-sunitary.\n    by rewrite -[m.+2]add1n mxsunitaryM // \n               mxsunitaryT ?mxounitary_sunitary ?mxounitary_Tz.\n  have F3 : Tz ^T* * M \\isn't m.+2.-odd.\n    apply/negP=> F3.\n    have Hos2 : Tz ^T* * M \\is m.+2.-unitary by rewrite mxounitaryE H3.\n    have /eqP := even_col3_inj Hos2 H1 H2.\n    by rewrite addrC -subr_eq0 opprD addrA addrK.\n  suff F4 i1 j1 : j1 !=\n     ecol m.+1 M -> ~~ odds2j (l * (Tz ^T* * M) i1 j1).\n    by apply: mxsunitary_oddij F4.\n  move=> j1De.\n  rewrite TzT_mul_row.\n  case: eqP => H1'.\n    rewrite [l]exprS -mulrA odds2jM ?(algS2IP sQ2) //.\n    rewrite  (negPf odds2i_sQ2) odds2j_sQ2 /=.\n    by rewrite (mxounitary_odds2i _ _ Hos) // negb_and !negbK E1.\n  case: eqP => H2'.\n    rewrite [l]exprSr !mulrA mulfK // mulrDr -/k odds2jD // .\n    have := odds2ij_col3 j1 Hn.\n    by rewrite !(mxounitary_odds2i _ _ Hos) // E1 j1De addbF.\n  rewrite [l]exprSr !mulrA mulfK // mulrDr -/k mulrN.\n  rewrite odds2jD ?rpredN // odds2jN //.\n  have := odds2ij_col3 j1 Hn.\n  by rewrite !(mxounitary_odds2i _ _ Hos) // E1 j1De addbF.\napply/idP => /andP[_ /forallP/(_ o2)/forallP/(_ (ecol m.+1 M + 1))].\nrewrite  TzT_mul_row /= => /s2intP [a [b Hab]].\nhave : odds2i (k * M o2 (ecol m.+1 M + 1)).\n  by rewrite (mxounitary_odds2i _ _ Hos) eq_sym D1 addrC -subr_eq0 addrK.\nrewrite {1}[k]exprS -mulrA Hab odds2iM ?sqrt2_S2I //.\n  by rewrite (negPf odds2i_sQ2).\nby apply/s2intP; exists a; exists b.\nQed.\n\nLemma mxounitaryS_TzT m (M : 'M_3) :\n   M  \\is m.+2.-unitary -> Tz^T* * M \\isn't m.-sunitary.\nProof.\nmove=> Hos; apply/negP=> Hn1.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave := mxsunitary_TzT  Hos.\ncase: eqP => [He /idP Hn| He /idP[]]; last first.\n  by apply: mxsunitaryW Hn1.\npose k : algC := sqrtC 2%:R ^+ m.+2.\npose l : algC := sqrtC 2%:R ^+ m.+1.\npose l1 : algC := sqrtC 2%:R ^+ m.\npose x := l * ((Tz ^T* * M) 0 (ecol m.+2 M + 1)).\nhave Px : x \\is a s2Int by apply: mxsunitary_s2int Hn.\nhave [Ox|Ex] := boolP (odds2i x).\n  suff : sQ2 %| (S2Iof Px) by rewrite -odds2i_dvd Ox.\n  pose x1 := l1 * ((Tz ^T* * M) 0 (ecol m.+2 M + 1)).\n  have Px1 : x1 \\is a s2Int by apply: mxsunitary_s2int Hn1.\n  apply/dvdS2IP; exists (S2Iof Px1).\n  apply/val_eqP => /=.\n  by rewrite /x /x1 !mxE [_ * sqrtC _]mulrC mulrA [l]exprS.\npose y := l * ((Tz ^T* * M)) 1 (ecol m.+2 M + 1).\nhave Py : y \\is a s2Int by apply: mxsunitary_s2int Hn.\nhave : odds2i (x + y).\n  rewrite /x /y TzT_mul_row /= TzT_mul_row /=.\n  rewrite !mulrDr !mulrN -/k [X in odds2i(X + _)]addrC.\n  rewrite addrA addrK -mulrDr.\n  rewrite (_ : ?[x] + ?x = 2%:R * ?x); last by rewrite mulrDl mul1r.\n  rewrite -{1}[2%:R]sqrtCK !mulrA -exprSr mulfK //.\n  by rewrite (mxounitary_odds2i _  _ Hos) He /=  addrC -subr_eq0 addrK.\nrewrite odds2iD // (negPf Ex) /= => Oy.\nsuff : sQ2 %| (S2Iof Py) by rewrite -odds2i_dvd Oy.\npose y1 := l1 * ((Tz ^T* * M) 1 (ecol m.+2 M + 1)).\nhave Py1 : y1 \\is a s2Int by apply: mxsunitary_s2int Hn1.\napply/dvdS2IP; exists (S2Iof Py1). \napply/val_eqP => /=.\nby rewrite /y /y1 [_ * sqrtC _]mulrC mulrA -exprS.\nQed.\n\nLemma Tx_mul (M : 'M[algC]_3) :\n   Tx * M =\n (sqrtC 2%:R)^-1 *:\n 'M{[::[::sqrtC 2%:R * M 0 0; sqrtC 2%:R * M 0 1 ;  sqrtC 2%:R * M 0 o2]; \n       [::   M 1 0 - M o2 0;     M 1 1 - M o2 1;     M 1 o2 - M o2 o2];\n       [::   M 1 0 + M o2 0;     M 1 1 + M o2 1;     M 1 o2 + M o2 o2]]}.\nProof.\napply/matrixP=> i j.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nrewrite !mxE sum3E !mxE.\nby case/or3P : (o3E i) => /eqP->; case/or3P : (o3E j) => /eqP-> /=;\n   rewrite /= ?(mul0r, mulr0, mulr1, add0r, addr0, mulNr, mulrN, mul1r)\n           ?mulrA ?mulVf // ?mulrBr ?mulrDr.\nQed.\n\nLemma Tx_mul_row  (M : 'M[algC]_3) i j :\n   (Tx * M) i j = if i == 0 then M 0 j\n                   else if i == 1 then  (sqrtC 2%:R)^-1 * (M 1 j - M o2 j) else \n                   (sqrtC 2%:R)^-1 * (M 1 j + M o2 j).\nProof.\nrewrite Tx_mul !mxE.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nby case/or3P : (o3E i) => /eqP->; case/or3P : (o3E j) => /eqP->//=;\n   rewrite mulrA mulVf // mul1r.\nQed.\n\nLemma mxsunitary0_neq0_row (M : 'M_3) i j k :\n  M \\is 0.-sunitary ->  M i j != 0 -> M i k = (k == j)%:R * M i k.\nProof.\nhave [|kDj Hs /negP Mij] := boolP (k == _); first by rewrite mul1r.\nhave /andP[/mxunitaryP /(_ i i)/eqP] := Hs.\nrewrite sum3E -!addrA -!normCK eqxx mul0r.\nhave : `|M i j| = 1.\n  by have /or3P[/eqP->//|/eqP->|/eqP->] := mxsunitary_eq0 i j Hs;\n     rewrite ?normrN1 ?normr1 ?expr1n.\nmove: kDj.\ncase/or3P : (o3E j) => /eqP-> kDj ->; rewrite expr1n.\n- rewrite -[1%:R]addr0.\n  move/eqP/addrI/eqP.\n  rewrite addr_ss_eq0 ?sqr_ge0 ?normr_ge0 //; last by rewrite !exprn_ge0.\n  rewrite !sqrf_eq0 !normr_eq0 => /andP[/eqP H2 /eqP H3] _.\n  move: kDj.\n  by case/or3P : (o3E k) => /eqP->; rewrite ?eqxx.\n- rewrite addrCA -[1%:R]addr0.\n  move/eqP/addrI/eqP.\n  rewrite addr_ss_eq0 ?sqr_ge0 ?normr_ge0 //; last by rewrite !exprn_ge0.\n  rewrite !sqrf_eq0 !normr_eq0 => /andP[/eqP H2 /eqP H3] _.\n  move: kDj.\n  by case/or3P : (o3E k) => /eqP->; rewrite ?eqxx.\nrewrite !addrA -[1%:R]add0r.\nmove/eqP/addIr/eqP.\nrewrite addr_ss_eq0 ?sqr_ge0 ?normr_ge0 //; last by rewrite !exprn_ge0.\nrewrite !sqrf_eq0 !normr_eq0 => /andP[/eqP H2 /eqP H3] _.\nmove: kDj.\nby case/or3P : (o3E k) => /eqP->; rewrite ?eqxx.\nQed.\n\nLemma mxsunitary0_neq0_col (M : 'M_3) i j k : \n  M \\is 0.-sunitary -> M i j != 0 -> M k j = (k == i)%:R * M k j.\nProof.\nmove=> Hn Mij; apply/eqP.\nhave [|kDj] := boolP (k == _); first by rewrite mul1r.\nrewrite mul0r.\nrewrite -mxsunitaryT in Hn.\nhave /(_ j i) := mxsunitary0_neq0_row k Hn.\nrewrite !mxE (negPf kDj) mul0r conjC_eq0 => /(_ Mij)/eqP.\nby rewrite conjC_eq0.\nQed.\n\nLemma mxsunitary0_neq0_odd (M : 'M_3) i j : \n  M \\is 0.-sunitary -> M i j != 0 -> odds2i (M i j).\nProof.\nmove=> Hn /negP.\nby have /or3P[//|/eqP->|/eqP->] := mxsunitary_eq0 i j Hn;\n  rewrite ?odds2iN ?rpred1 // (odds2i_nat 1).\nQed. \n\nLemma mxsunitary0_ex_neq0 (M : 'M_3) i :\n  M \\is 0.-sunitary -> exists j, M i j != 0.\nProof.\nmove=> Hn; apply/existsP.\nhave [//|] := boolP [exists x, M i x != 0].\nrewrite negb_exists => /forallP H.\nhave H1 x : M i x = 0.\n  by apply/eqP; rewrite -[_ == 0]negbK (negPf (H _)).  \nhave /andP[/mxunitaryP /(_ i i)/eqP] := Hn.\nby rewrite sum3E !H1 !mul0r !add0r eqxx eq_sym oner_eq0.\nQed.\n\nLemma mxsunitary0_Tx_odd (M : 'M_3) : M \\is 0.-sunitary -> Tx * M \\is 1.-odd.\nProof.\nmove=> Hn; apply/mxoddP.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave [i M1i] := mxsunitary0_ex_neq0 1 Hn.\nexists 1; exists i.\nrewrite Tx_mul_row /= mulrA mulfV // mul1r.\nrewrite (mxsunitary0_neq0_col o2 Hn M1i) /=.\nby rewrite mul0r subr0 mxsunitary0_neq0_odd.\nQed.\n\nLemma mxounitary_Tx_odd m (M : 'M_3) : \n  M \\is m.+1.-unitary -> (Tx * M \\is m.+2.-odd) = (erow m.+1 M != 0).\nProof.\nmove=> Hos.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave Hs2i := mxounitary_s2int _ _ Hos.\nhave [eO1|dO1] /= := boolP (_ == _); apply/idP.\n  apply/negP/mxoddPn => i j.\n  rewrite Tx_mul_row /=.\n  have := mxounitary_odds2i 1 j Hos.\n  have := mxounitary_odds2i o2 j Hos.\n  rewrite (eqP eO1) (negPf (_ : o2 != 0)) //= => H1 H2.\n  have [/eqP iE|] := boolP (i == 0); last first.\n    rewrite 2!fun_if !mulrA exprSr mulfK // !mulrDr mulrN.\n    by rewrite !odds2iD ?odds2iN ?rpredN ?H1 ?H2 ?addbb ?if_same.\n  by rewrite exprS -mulrA odds2iM ?(negPf odds2i_sQ2) ?sqrt2_S2I.\npose j := ecol m.+1 M + 1.\napply/mxoddP; exists o2; exists j.\nrewrite Tx_mul_row /= exprSr !mulrA mulfK // mulrDr.\nrewrite odds2iD // (mxounitary_odds2i 1 j Hos) \n                   (mxounitary_odds2i o2 j Hos) /j.\nhave := dO1.\nby case/or3P : (o3E (erow m.+1 M)) => /eqP-> //;\n   case/or3P : (o3E (ecol m.+1 M)) => /eqP->.\nQed.\n\n\nLemma mxounitary_Tx_sunitary m (M : 'M_3) :\n  M \\is m.+1.-unitary -> (Tx * M \\is m.-sunitary) = (erow m.+1 M == 0).\nProof.\nmove=> Hos.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nset k : algC := (sqrtC 2%:R) ^+ m.+1.\nset l : algC := (sqrtC 2%:R) ^+ m.+2.\nhave S1 := mxounitary_s2int _ _ Hos.\ncase: eqP => [E1|/eqP D1].\n  have F1 (k1 : 'I_3)  : k1 != ecol m.+1 M -> even_col m.+2 (Tx * M) k1.\n    move=> k1Dk; apply/forallP => i1.\n    rewrite Tx_mul_row.\n    case: eqP => H1.\n      rewrite exprS -mulrA.\n      rewrite odds2iM ?(algS2IP sQ2) // negb_and odds2i_sQ2.\n      by rewrite (mxounitary_odds2i _ _ Hos).\n    case: eqP => H2.\n      rewrite exprSr mulrA mulfK // mulrBr.\n      rewrite odds2iD ?rpredN // odds2iN // negb_add.\n      by rewrite !(mxounitary_odds2i _ _ Hos) E1.\n    rewrite exprSr mulrA mulfK // mulrDr.\n    rewrite odds2iD // negb_add.\n    by rewrite !(mxounitary_odds2i _ _ Hos) E1.\n  have /F1 H1 : ecol m.+1 M + 1 != ecol m.+1 M.\n    by rewrite addrC -subr_eq0 addrK.\n  have /F1 H2 : ecol m.+1 M + 2%:R != ecol m.+1 M.\n    by rewrite addrC -subr_eq0 addrK.\n  have H3 : Tx * M \\is m.+2.-sunitary.\n    by rewrite -[m.+2]add1n mxsunitaryM // \n                mxounitary_sunitary // mxounitary_Tx.\n  have F2 : Tx * M \\isn't m.+2.-odd.\n    apply/negP=> H.\n    have /even_col3_inj/(_ H1 H2) /eqP : Tx * M \\is m.+2.-unitary.\n      by rewrite mxounitaryE H3.\n    by rewrite addrC -subr_eq0 opprD addrA addrK.\n  suff F3 i1 j1 : j1 != ecol m.+1 M -> ~~ odds2j (l * (Tx * M) i1 j1).\n    by apply: mxsunitary_oddij F3.\n  move=> j1De.\n  rewrite Tx_mul_row.\n  case: eqP => H1'.\n    rewrite [l]exprS -mulrA.\n    rewrite odds2jM ?(algS2IP sQ2) // (negPf odds2i_sQ2) odds2j_sQ2 /=.\n    by rewrite (mxounitary_odds2i _ _ Hos) // negb_and !negbK E1.\n  case: eqP => H2'.\n    rewrite [l]exprSr mulrA mulfK // mulrBr.\n    rewrite odds2jD ?odds2jN ?rpredN //.\n    have := odds2ij_col3 j1 (mxounitary_sunitary Hos).\n    by rewrite !(mxounitary_odds2i _ _ Hos) // E1 j1De.\n  rewrite [l]exprSr mulrA mulfK // mulrDr.\n  rewrite odds2jD //.\n  have := odds2ij_col3 j1 (mxounitary_sunitary Hos).\n  by rewrite !(mxounitary_odds2i _ _ Hos) // E1 j1De.\napply/idP => /andP[_ /forallP/(_ 0)/forallP/(_ (ecol m.+1 M + 1))].\nrewrite  Tx_mul_row eqxx => /s2intP [a [b Hab]].\nhave : odds2i (k * M 0 (ecol m.+1 M + 1)).\n  by rewrite (mxounitary_odds2i _ _ Hos) eq_sym D1 addrC -subr_eq0 addrK.\nrewrite {1}[k]exprS -mulrA Hab odds2iM ?sqrt2_S2I //.\n  by rewrite (negPf odds2i_sQ2).\nby apply/s2intP; exists a; exists b.\nQed.\n\nLemma Ty_mul (M : 'M[algC]_3) :\n   Ty * M =\n (sqrtC 2%:R)^-1 *:\n 'M{[::[::   M 0 0 + M o2 0;     M 0 1 + M o2 1;     M 0 o2 + M o2 o2];\n       [::sqrtC 2%:R * M 1 0; sqrtC 2%:R * M 1 1 ;  sqrtC 2%:R * M 1 o2]; \n       [::  - M 0 0 + M o2 0;   -M 0 1 + M o2 1;    -M 0 o2 + M o2 o2]]}.\nProof.\napply/matrixP=> i j.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nrewrite !mxE sum3E !mxE.\nby case/or3P : (o3E i) => /eqP->; case/or3P : (o3E j) => /eqP-> /=;\n   rewrite /= ?(mul0r, mulr0, mulr1, add0r, addr0, mulNr, mulrN, mul1r)\n           ?mulrA ?mulVf // ?mulrBr ?mulrDr // mulrN.\nQed.\n\nLemma Ty_mul_row  (M : 'M[algC]_3) i j :\n   (Ty * M) i j = if i == 1 then M 1 j\n                  else if i == o2 then (sqrtC 2%:R)^-1 * (- M 0 j + M o2 j) else \n                   (sqrtC 2%:R)^-1  * (M 0 j + M o2 j).\nProof.\nrewrite Ty_mul !mxE.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nby case/or3P : (o3E i) => /eqP->; case/or3P : (o3E j) => /eqP->//=;\n   rewrite mulrA mulVf // mul1r.\nQed.\n\nLemma mxsunitary0_Ty_odd (M : 'M_3) : M \\is 0.-sunitary -> Ty * M \\is 1.-odd.\nProof.\nmove=> Hn; apply/mxoddP.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave [i M1i] := mxsunitary0_ex_neq0 0 Hn.\nexists 0; exists i.\nrewrite Ty_mul_row /= mulrA mulfV // mul1r.\nrewrite (mxsunitary0_neq0_col o2 Hn M1i) /=.\nby rewrite mul0r addr0 mxsunitary0_neq0_odd.\nQed.\n\nLemma mxounitary_Ty_odd m (M : 'M_3) : \n  M \\is m.+1.-unitary -> (Ty * M \\is m.+2.-odd) = (erow m.+1 M != 1).\nProof.\nmove=> Hos.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave Hs2i := mxounitary_s2int _ _ Hos.\nhave [eO1|dO1] /= := boolP (_ == _); apply/idP.\n  apply/negP/mxoddPn => i j.\n  rewrite Ty_mul_row /=.\n  have := mxounitary_odds2i 0 j Hos.\n  have := mxounitary_odds2i o2 j Hos.\n  rewrite (eqP eO1) //= => H1 H2.\n  have [/eqP iE|] := boolP (i == 1); last first.\n    rewrite 2!fun_if !mulrA exprSr mulfK // !mulrDr mulrN.\n    by rewrite !odds2iD ?odds2iN ?rpredN ?H1 ?H2 ?addbb ?if_same.\n  by rewrite exprS -mulrA odds2iM ?(negPf odds2i_sQ2) ?sqrt2_S2I.\npose j := ecol m.+1 M + 1.\napply/mxoddP; exists o2; exists j.\nrewrite Ty_mul_row /=.\nrewrite exprSr !mulrA mulfK // mulrDr mulrN.\nrewrite odds2iD ?rpredN // ?odds2iN // (mxounitary_odds2i 0 j Hos) \n                   (mxounitary_odds2i o2 j Hos) /j.\nhave := dO1.\nby case/or3P : (o3E (erow m.+1 M)) => /eqP-> //;\n   case/or3P : (o3E (ecol m.+1 M)) => /eqP->.\nQed.\n\nLemma mxounitary_Ty_sunitary m (M : 'M_3) :\n  M \\is m.+1.-unitary -> (Ty * M \\is m.-sunitary) = (erow m.+1 M == 1).\nProof.\nmove=> Hos.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nset k : algC := (sqrtC 2%:R) ^+ m.+1.\nset l : algC := (sqrtC 2%:R) ^+ m.+2.\nhave S1 := mxounitary_s2int _ _ Hos.\ncase: eqP => [E1|/eqP D1].\n  have F1 (k1 : 'I_3)  : k1 != ecol m.+1 M -> even_col m.+2 (Ty * M) k1.\n    move=> k1Dk; apply/forallP => i1.\n    rewrite Ty_mul_row.\n    case: eqP => H1.\n      rewrite exprS -mulrA.\n      rewrite odds2iM ?(algS2IP sQ2) // negb_and odds2i_sQ2.\n      by rewrite (mxounitary_odds2i _ _ Hos).\n    case: eqP => H2.\n      rewrite exprSr mulrA mulfK // mulrDr mulrN.\n      rewrite odds2iD ?rpredN // odds2iN // negb_add.\n      by rewrite !(mxounitary_odds2i _ _ Hos) E1.\n    rewrite exprSr mulrA mulfK // mulrDr.\n    rewrite odds2iD // negb_add.\n    by rewrite !(mxounitary_odds2i _ _ Hos) E1.\n  have /F1 H1 : ecol m.+1 M + 1 != ecol m.+1 M.\n    by rewrite addrC -subr_eq0 addrK.\n  have /F1 H2 : ecol m.+1 M + 2%:R != ecol m.+1 M.\n    by rewrite addrC -subr_eq0 addrK.\n  have H3 : Ty * M \\is m.+2.-sunitary.\n    by rewrite -[m.+2]add1n mxsunitaryM //\n               mxounitary_sunitary // mxounitary_Ty.\n  have F2 : Ty * M \\isn't m.+2.-odd.\n    apply/negP=> H.\n    have /even_col3_inj/(_ H1 H2) /eqP : Ty * M \\is m.+2.-unitary.\n      by rewrite mxounitaryE H3.\n    by rewrite addrC -subr_eq0 opprD addrA addrK.\n  suff F3 i1 j1 : j1 != ecol m.+1 M -> ~~ odds2j (l * (Ty * M) i1 j1).\n    by apply: mxsunitary_oddij F3.\n  move=> j1De.\n  rewrite Ty_mul_row.\n  case: eqP => H1'.\n    rewrite [l]exprS -mulrA.\n    rewrite odds2jM ?(algS2IP sQ2) // (negPf odds2i_sQ2) odds2j_sQ2 /=.\n    by rewrite (mxounitary_odds2i _ _ Hos) // negb_and !negbK E1.\n  case: eqP => H2'.\n    rewrite [l]exprSr mulrA mulfK // mulrDr mulrN.\n    rewrite odds2jD ?odds2jN ?rpredN //.\n    have := odds2ij_col3 j1 (mxounitary_sunitary Hos).\n    by rewrite !(mxounitary_odds2i _ _ Hos) // E1 j1De addbF.\n  rewrite [l]exprSr mulrA mulfK // mulrDr.\n  rewrite odds2jD //.\n  have := odds2ij_col3 j1 (mxounitary_sunitary Hos).\n  by rewrite !(mxounitary_odds2i _ _ Hos) // E1 j1De addbF.\napply/idP => /andP[_ /forallP/(_ 1)/forallP/(_ (ecol m.+1 M + 1))].\nrewrite  Ty_mul_row eqxx => /s2intP [a [b Hab]].\nhave : odds2i (k * M 1 (ecol m.+1 M + 1)).\n  by rewrite (mxounitary_odds2i _ _ Hos) eq_sym D1 addrC -subr_eq0 addrK.\nrewrite {1}[k]exprS -mulrA Hab odds2iM ?sqrt2_S2I //.\n  by rewrite (negPf odds2i_sQ2).\nby apply/s2intP; exists a; exists b.\nQed.\n\nLemma Tz_mul (M : 'M[algC]_3) :\n   Tz * M =\n (sqrtC 2%:R)^-1 *:\n 'M{[::[::   M 0 0 - M 1 0;     M 0 1 - M 1 1;     M 0 o2 - M 1 o2];\n       [::   M 0 0 + M 1 0;     M 0 1 + M 1 1;     M 0 o2 + M 1 o2];\n       [::sqrtC 2%:R * M o2 0; sqrtC 2%:R * M o2 1 ;  sqrtC 2%:R * M o2 o2]]}.\nProof.\napply/matrixP=> i j.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nrewrite !mxE sum3E !mxE.\nby case/or3P : (o3E i) => /eqP->; case/or3P : (o3E j) => /eqP-> /=;\n   rewrite /= ?(mul0r, mulr0, mulr1, add0r, addr0, mulNr, mulrN, mul1r)\n           ?mulrA ?mulVf // ?mulrBr ?mulrDr // mulrN.\nQed.\n\nLemma Tz_mul_row  (M : 'M[algC]_3) i j :\n   (Tz * M) i j = if i == o2 then M o2 j\n                  else if i == 0 then (sqrtC 2%:R)^-1 * (M 0 j - M 1 j) else \n                  (sqrtC 2%:R)^-1 * (M 0 j + M 1 j).\nProof.\nrewrite Tz_mul !mxE.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nby case/or3P : (o3E i) => /eqP->; case/or3P : (o3E j) => /eqP->//=;\n   rewrite mulrA mulVf // mul1r.\nQed.\n\nLemma mxsunitary0_Tz_odd  (M : 'M_3) : M \\is 0.-sunitary -> Tz * M \\is 1.-odd.\nProof.\nmove=> Hn; apply/mxoddP.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave [i M1i] := mxsunitary0_ex_neq0 0 Hn.\nexists 1; exists i.\nrewrite Tz_mul_row /= mulrA mulfV // mul1r.\nrewrite (mxsunitary0_neq0_col 1 Hn M1i) /=.\nby rewrite mul0r addr0 mxsunitary0_neq0_odd.\nQed.\n\nLemma mxounitary_Tz_odd m (M : 'M_3) :\n  M \\is m.+1.-unitary -> (Tz * M \\is m.+2.-odd) = (erow m.+1 M != o2).\nProof.\nmove=> Hos.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nhave Hs2i := mxounitary_s2int _ _ Hos.\nhave [eO1|dO1] /= := boolP (_ == _); apply/idP.\n  apply/negP/mxoddPn => i j.\n  rewrite Tz_mul_row /=.\n  have := mxounitary_odds2i 0 j Hos.\n  have := mxounitary_odds2i 1 j Hos.\n  rewrite (eqP eO1) //= => H1 H2.\n  have [/eqP iE|] := boolP (i == o2); last first.\n    rewrite 2!fun_if !mulrA exprSr mulfK // !mulrDr mulrN.\n    by rewrite !odds2iD ?odds2iN ?rpredN ?H1 ?H2 ?addbb ?if_same.\n  by rewrite exprS -mulrA odds2iM ?(negPf odds2i_sQ2) ?sqrt2_S2I.\npose j := ecol m.+1 M + 1.\napply/mxoddP; exists 0; exists j.\nrewrite Tz_mul_row /=.\nrewrite exprSr !mulrA mulfK // mulrDr mulrN.\nrewrite odds2iD ?rpredN // ?odds2iN // (mxounitary_odds2i 0 j Hos) \n                   (mxounitary_odds2i 1 j Hos) /j.\nhave := dO1.\nby case/or3P : (o3E (erow m.+1 M)) => /eqP-> //;\n   case/or3P : (o3E (ecol m.+1 M)) => /eqP->.\nQed.\n\nLemma mxounitary_Tz_sunitary m (M : 'M_3) :\n  M \\is m.+1.-unitary -> (Tz * M \\is m.-sunitary) = (erow m.+1 M == o2).\nProof.\nmove=> Hos.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\nset k : algC := (sqrtC 2%:R) ^+ m.+1.\nset l : algC := (sqrtC 2%:R) ^+ m.+2.\nhave S1 := mxounitary_s2int _ _ Hos.\ncase: eqP => [E1|/eqP D1].\n  have F1 (k1 : 'I_3)  : k1 != ecol m.+1 M -> even_col m.+2 (Tz * M) k1.\n    move=> k1Dk; apply/forallP => i1.\n    rewrite Tz_mul_row.\n    case: eqP => H1.\n      rewrite exprS -mulrA.\n      rewrite odds2iM ?(algS2IP sQ2) // negb_and odds2i_sQ2.\n      by rewrite (mxounitary_odds2i _ _ Hos).\n    case: eqP => H2.\n      rewrite exprSr mulrA mulfK // mulrDr mulrN.\n      rewrite odds2iD ?rpredN // odds2iN // negb_add.\n      by rewrite !(mxounitary_odds2i _ _ Hos) E1.\n    rewrite exprSr mulrA mulfK // mulrDr.\n    rewrite odds2iD // negb_add.\n    by rewrite !(mxounitary_odds2i _ _ Hos) E1.\n  have /F1 H1 : ecol m.+1 M + 1 != ecol m.+1 M.\n    by rewrite addrC -subr_eq0 addrK.\n  have /F1 H2 : ecol m.+1 M + 2%:R != ecol m.+1 M.\n    by rewrite addrC -subr_eq0 addrK.\n  have H3 : Tz * M \\is m.+2.-sunitary.\n    by rewrite -[m.+2]add1n mxsunitaryM //\n               mxounitary_sunitary // mxounitary_Tz.\n  have F2 : Tz * M \\isn't m.+2.-odd.\n    apply/negP=> H.\n    have /even_col3_inj/(_ H1 H2) /eqP : Tz * M \\is m.+2.-unitary.\n      by rewrite mxounitaryE H3.\n    by rewrite addrC -subr_eq0 opprD addrA addrK.\n  suff F3 i1 j1 : j1 != ecol m.+1 M -> ~~ odds2j (l * (Tz * M) i1 j1).\n    by apply: mxsunitary_oddij F3.\n  move=> j1De.\n  rewrite Tz_mul_row.\n  case: eqP => H1'.\n    rewrite [l]exprS -mulrA.\n    rewrite odds2jM ?(algS2IP sQ2) // (negPf odds2i_sQ2) odds2j_sQ2 /=.\n    by rewrite (mxounitary_odds2i _ _ Hos) // negb_and !negbK E1.\n  case: eqP => H2'.\n    rewrite [l]exprSr mulrA mulfK // mulrDr mulrN.\n    rewrite odds2jD ?odds2jN ?rpredN //.\n    have := odds2ij_col3 j1 (mxounitary_sunitary Hos).\n    by rewrite !(mxounitary_odds2i _ _ Hos) // E1 j1De addbF.\n  rewrite [l]exprSr mulrA mulfK // mulrDr.\n  rewrite odds2jD //.\n  have := odds2ij_col3 j1 (mxounitary_sunitary Hos).\n  by rewrite !(mxounitary_odds2i _ _ Hos) // E1 j1De addbF.\napply/idP => /andP[_ /forallP/(_ o2)/forallP/(_ (ecol m.+1 M + 1))].\nrewrite  Tz_mul_row eqxx => /s2intP [a [b Hab]].\nhave : odds2i (k * M o2 (ecol m.+1 M + 1)).\n  by rewrite (mxounitary_odds2i _ _ Hos) eq_sym D1 addrC -subr_eq0 addrK.\nrewrite {1}[k]exprS -mulrA Hab odds2iM ?sqrt2_S2I //.\n  by rewrite (negPf odds2i_sQ2).\nby apply/s2intP; exists a; exists b.\nQed.\n\nLemma Tx_mul_Ty_neq m (M : 'M[algC]_3) : M \\is m.-sunitary -> Tx * M != Ty * M.\nProof.\nmove=> /andP[/eqP H _]; apply: contra (_: Tx != Ty) => [/eqP H1|].\n  by rewrite -[Tx]mulmx1 -H mulmxA [_ *m M]H1 -mulmxA H mulmx1.\napply/eqP=> /matrixP/(_ 0 o2)/eqP.\nby rewrite !mxE mulr0 mulr1 eq_sym invr_eq0 sqrtC_eq0 (eqC_nat _ 0).\nQed.\n\nLemma Tx_mul_Tz_neq m (M : 'M[algC]_3) : M \\is m.-sunitary -> Tx * M != Tz * M.\nProof.\nmove=> /andP[/eqP H _]; apply: contra (_: Tx != Tz) => [/eqP H1|].\n  by rewrite -[Tx]mulmx1 -H mulmxA [_ *m M]H1 -mulmxA H mulmx1.\napply/eqP=> /matrixP/(_ 1 0)/eqP.\nby rewrite !mxE  mulr0 mulr1 eq_sym invr_eq0 sqrtC_eq0 (eqC_nat _ 0).\nQed.\n\nLemma Ty_mul_Tz_neq m (M : 'M[algC]_3) : M \\is m.-sunitary -> Ty * M != Tz * M.\nProof.\nmove=> /andP[/eqP H _]; apply: contra (_: Ty != Tz) => [/eqP H1|].\n  by rewrite -[Ty]mulmx1 -H mulmxA [_ *m M]H1 -mulmxA H mulmx1.\napply/eqP=> /matrixP/(_ 1 0)/eqP.\nby rewrite !mxE  mulr0 mulr1 eq_sym invr_eq0 sqrtC_eq0 (eqC_nat _ 0).\nQed.\n\nLemma even_row3_Tx_mul k (M : 'M[algC]_3) :\n  M \\is k.-sunitary -> even_row k.+1  (Tx * M) 0.\nProof.\nmove=> Hs.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\napply/forallP=> /= i; rewrite Tx_mul !mxE /=.\nby case/or3P: (o3E i) => /eqP->//=;\n   rewrite !mulrA divfK // exprS -mulrA;\n   rewrite odds2iM ?negb_and ?odds2i_sQ2 //\n          ?(mxsunitary_s2int _ _ Hs) // sQ2_proof.\nQed.\n\nLemma even_row3_Ty_mul k (M : 'M[algC]_3) :\n M \\is k.-sunitary -> even_row k.+1  (Ty * M) 1.\nProof.\nmove=> Hs.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\napply/forallP=> /= i; rewrite Ty_mul !mxE /=.\nby case/or3P: (o3E i) => /eqP->//=;\n   rewrite !mulrA divfK // exprS -mulrA;\n   rewrite odds2iM ?negb_and ?odds2i_sQ2 //\n          ?(mxsunitary_s2int _ _ Hs) // sQ2_proof.\nQed.\n\nLemma even_row3_Tz_mul k (M : 'M[algC]_3) :\n  M \\is k.-sunitary -> even_row k.+1  (Tz * M) o2.\nProof.\nmove=> Hs.\nhave F : sqrtC 2%:R != 0 :> algC by rewrite sqrtC_eq0 (eqC_nat _ 0).\napply/forallP=> /= i; rewrite Tz_mul !mxE /=.\nby case/or3P: (o3E i) => /eqP->//=;\n   rewrite !mulrA divfK // exprS -mulrA;\n   rewrite odds2iM ?negb_and ?odds2i_sQ2 //\n          ?(mxsunitary_s2int _ _ Hs) // sQ2_proof.\nQed.\n\nLemma even_row3_erow (k : nat) i (M : 'M_3) :\n   M \\is k.+1.-unitary -> even_row k.+1 M i -> erow k.+1 M = i.\nProof.\nmove=> Hos HE.\napply: even_row3_inj HE => //.\nby apply/even_erow3/mxounitary_sunitary.\nQed.\n\nDefinition getM m (M : 'M[algC]_3) :=\n  tnth [tuple of [::Tx; Ty; Tz]] (erow m M).\n\nLemma getME m M : [|| getM m M == Tx, getM m M == Ty | getM m M == Tz].\nProof.\nrewrite /getM; set j := erow m M.\nby case/or3P : (o3E j) => /eqP->; rewrite  !(tnth_nth Tx) /= ?eqxx ?orbT.\nQed.\n \nDefinition reduceT m (M : 'M[algC]_3) := getM m M ^T* * M.\n\nFixpoint reduceTs n m M := \n  if n is n1.+1 then reduceTs n1 m.-1 (reduceT m M) else M.\n\nLemma reduceTsS n m M : reduceTs n.+1 m M = reduceTs n m.-1 (reduceT m M).\nProof. by []. Qed.\n\nLemma mxsunitary_reduceT m (M : 'M_3) : \n  M \\is m.+1.-unitary -> reduceT m.+1 M \\is m.-sunitary .\nProof.\nmove=>  Hos.\nrewrite /reduceT /getM.\ncase/or3P : (o3E (erow m.+1 M))=> H; rewrite (eqP H) /=.\n- by rewrite mxsunitary_TxT.\n- by rewrite mxsunitary_TyT.\nby rewrite mxsunitary_TzT.\nQed.\n\nLemma mxounitary_reduceT m (M : 'M_3) : \n  M \\is m.+1.-unitary -> reduceT m.+1 M \\is m.-unitary.\nProof.\nmove=> Hos.\nhave Hn := mxsunitary_reduceT Hos.\nrewrite mxounitaryE Hn /=.\ncase: m Hn Hos => [Hn Hos|m Hn Hos].\n  by rewrite mxsunitary0_odd.\nrewrite -[_ \\is _]negbK -(mxsunitary_odd Hn).\nrewrite /reduceT /getM; set k := erow m.+2 M.\ncase/or3P : (o3E k) => H; rewrite (eqP H) !(tnth_nth Tx) /=.\n- by rewrite mxounitaryS_TxT.\n- by rewrite mxounitaryS_TyT.\nby rewrite mxounitaryS_TzT.\nQed.\n\nLemma mxounitary_reduceTs_rec m n (M : 'M_3) : \n  M \\is (m + n).-unitary -> reduceTs n (m + n) M \\is m.-unitary.\nProof.\nelim: n m M => [m M |n IH m M HO]; first by rewrite addn0.\nby rewrite addnS /= IH // mxounitary_reduceT // -addnS.\nQed.\n\nLemma mxounitary_reduceTs m (M : 'M_3) : \n  M \\is m.-unitary -> reduceTs m m M \\is 0.-unitary.\nProof. by rewrite {1 3} [m]/(0 + m)%N => /mxounitary_reduceTs_rec. Qed.\n\nLemma mxounitary0_Tx (M : 'M_3) : M \\is 0.-unitary -> Tx * M \\is 1.-unitary.\nProof.\nmove=> Hos; have Hn := mxounitary_sunitary Hos.\nrewrite mxounitaryE mxsunitary0_Tx_odd ?andbT //.\nby rewrite  (@mxsunitaryM _ 1 0) // mxounitary_sunitary // mxounitary_Tx.\nQed.\n\nLemma mxounitary_Tx_mul m (M : 'M_3) :\n  M \\is m.+1.-unitary -> Tx * M \\is m.+2.-unitary = (erow m.+1  M != 0).\nProof.\nmove=> Hos; have Hn := mxounitary_sunitary Hos.\nrewrite mxounitaryE mxounitary_Tx_odd // (@mxsunitaryM _ 1 m.+1) //.\nby rewrite mxounitary_sunitary // mxounitary_Tx.\nQed.\n\nLemma mxounitary0_Ty (M : 'M_3) : M \\is 0.-unitary -> Ty * M \\is 1.-unitary.\nProof.\nmove=> Hos; have Hn := mxounitary_sunitary Hos.\nrewrite mxounitaryE mxsunitary0_Ty_odd ?andbT //.\nby rewrite  (@mxsunitaryM _ 1 0) // mxounitary_sunitary // mxounitary_Ty.\nQed.\n\nLemma mxounitary_Ty_mul m (M : 'M_3) : \n  M \\is m.+1.-unitary -> Ty * M \\is m.+2.-unitary = (erow m.+1  M != 1).\nProof.\nmove=> Hos; have Hn := mxounitary_sunitary Hos.\nrewrite mxounitaryE mxounitary_Ty_odd // (@mxsunitaryM _ 1 m.+1) //.\nby rewrite mxounitary_sunitary // mxounitary_Ty.\nQed.\n\nLemma mxounitary0_Tz (M : 'M_3) : M \\is 0.-unitary -> Tz * M \\is 1.-unitary.\nProof.\nmove=> Hos; have Hn := mxounitary_sunitary Hos.\nrewrite mxounitaryE mxsunitary0_Tz_odd ?andbT //.\nby rewrite  (@mxsunitaryM _ 1 0) // mxounitary_sunitary // mxounitary_Tz.\nQed.\n\nLemma mxounitary_Tz_mul m (M : 'M_3) : \n  M \\is m.+1.-unitary -> Tz * M \\is m.+2.-unitary = (erow m.+1  M != o2).\nProof.\nmove=> Hos; have Hn := mxounitary_sunitary Hos.\nrewrite mxounitaryE mxounitary_Tz_odd // (@mxsunitaryM _ 1 m.+1) //.\nby rewrite mxounitary_sunitary // mxounitary_Tz.\nQed.\n\nLemma erow_Tx0 M : M \\is 0.-unitary -> erow 1 (Tx * M) = 0.\nProof.\nmove=> HM.\nhave F := mxounitary0_Tx HM.\nmove: (F); rewrite mxounitaryE => /andP[/even_erow3 F1 _].\napply: even_row3_erow F _.\napply/forallP => x.\nrewrite expr1 Tx_mul_row eqxx //.\nhave F2 i1 j1 : M i1 j1 \\is a s2Int.\n  by have := (mxounitary_s2int i1 j1 HM); rewrite mul1r.\nrewrite odds2iM  ? sQ2_proof ?(mxsunitary_s2int _ _ HM) //.\nby rewrite ?negb_and ?odds2i_sQ2.\nQed.\n\nLemma erow_Tx k M : \n  M \\is k.+1.-unitary -> erow k.+1 M != 0 -> erow k.+2 (Tx * M) = 0.\nProof.\nmove=> HM H.\nhave F : Tx * M \\is k.+2.-unitary by rewrite mxounitary_Tx_mul.\nmove: (F); rewrite mxounitaryE => /andP[/even_erow3 F1 _].\napply: even_row3_erow F _.\napply/forallP => x.\nrewrite Tx_mul_row eqxx exprS -mulrA.\nrewrite odds2iM  ?sQ2_proof //.\n  by rewrite ?negb_and ?odds2i_sQ2.\nby exact: (mxounitary_s2int _ _ HM).\nQed.\n\nLemma erow_Ty0 M : M \\is 0.-unitary -> erow 1 (Ty * M) = 1.\nProof.\nmove=> HM.\nhave F := mxounitary0_Ty HM.\nmove: (F); rewrite mxounitaryE => /andP[/even_erow3 F1 _].\napply: even_row3_erow F _.\napply/forallP => x.\nrewrite expr1 Ty_mul_row eqxx //.\nhave F2 i1 j1 : M i1 j1 \\is a s2Int.\n  by have := (mxounitary_s2int i1 j1 HM); rewrite mul1r.\nrewrite odds2iM  ? sQ2_proof ?(mxsunitary_s2int _ _ HM) //.\nby rewrite ?negb_and ?odds2i_sQ2.\nQed.\n\nLemma erow_Ty k M : \n  M \\is k.+1.-unitary -> erow k.+1 M != 1 -> erow k.+2 (Ty * M) = 1.\nProof.\nmove=> HM H.\nhave F : Ty * M \\is k.+2.-unitary by rewrite mxounitary_Ty_mul.\nmove: (F); rewrite mxounitaryE => /andP[/even_erow3 F1 _].\napply: even_row3_erow F _.\napply/forallP => x.\nrewrite Ty_mul_row eqxx exprS -mulrA.\nrewrite odds2iM  ?sQ2_proof //.\n  by rewrite ?negb_and ?odds2i_sQ2.\nby exact: (mxounitary_s2int _ _ HM).\nQed.\n\nLemma erow_Tz0 M : M \\is 0.-unitary -> erow 1 (Tz * M) = o2.\nProof.\nmove=> HM.\nhave F := mxounitary0_Tz HM.\nmove: (F); rewrite mxounitaryE => /andP[/even_erow3 F1 _].\napply: even_row3_erow F _.\napply/forallP => x.\nrewrite expr1 Tz_mul_row eqxx //.\nhave F2 i1 j1 : M i1 j1 \\is a s2Int.\n  by have := (mxounitary_s2int i1 j1 HM); rewrite mul1r.\nrewrite odds2iM  ? sQ2_proof ?(mxsunitary_s2int _ _ HM) //.\nby rewrite ?negb_and ?odds2i_sQ2.\nQed.\n\nLemma erow_Tz k M : \n  M \\is k.+1.-unitary -> erow k.+1 M != o2 -> erow k.+2 (Tz * M) = o2.\nProof.\nmove=> HM H.\nhave F : Tz * M \\is k.+2.-unitary by rewrite mxounitary_Tz_mul.\nmove: (F); rewrite mxounitaryE => /andP[/even_erow3 F1 _].\napply: even_row3_erow F _.\napply/forallP => x.\nrewrite Tz_mul_row eqxx exprS -mulrA.\nrewrite odds2iM  ?sQ2_proof //.\n  by rewrite ?negb_and ?odds2i_sQ2.\nby exact: (mxounitary_s2int _ _ HM).\nQed.\n\nFixpoint Tn n : 'M_3 := \n  if n is n1.+1 then (if erow n1  (Tn n1) == 0 then Ty else Tx) * Tn n1\n  else 1.\n\nLemma mxounitary_Tn k : Tn k \\is k.-unitary.\nProof.\nelim: k => [|k IH] /=; first by apply: mxounitary1.\ncase: k IH => [_ /=|k IH].\n  rewrite mulr1; case (_ == _).\n    by rewrite -[Ty]mulr1 mxounitary0_Ty // mxounitary1.\n  by rewrite -[Tx]mulr1 mxounitary0_Tx // mxounitary1.\nhave [/eqP HE|HD] := boolP (_ == _).\n  by rewrite mxounitary_Ty_mul // HE.\nby rewrite mxounitary_Tx_mul // HE.\nQed.\n\nEnd Quantum.\n\nNotation \"M ^T*\" := (trCmx M) (at level 10).\n\nNotation \" m .-s2int\" := (mxs2int m) (format \"m .-s2int\", at level 10).\n\nNotation \" m .-odd\" := (mxodd m) (format \"m .-odd\", at level 10).\n\nNotation \" m .-sunitary\" := (mxsunitary m) (format \"m .-sunitary\", at level 10).\n\nNotation \" m .-unitary\" := (mxounitary m) (format \"m .-unitary\", at level 10).\n\nNotation \"''M{' l } \" := (seq2matrix _ _ l).\n\n\n\n", "meta": {"author": "thery", "repo": "Selinger", "sha": "2ace9aac2ff0f15c76a72c2691c890f58e36f02a", "save_path": "github-repos/coq/thery-Selinger", "path": "github-repos/coq/thery-Selinger/Selinger-2ace9aac2ff0f15c76a72c2691c890f58e36f02a/quantum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6598539948664961}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\nRequire Import Relations Setoid SetoidList List Multiset PermutSetoid Permutation Omega.\n\nSet Implicit Arguments.\n\n\n\nSection Perm.\n\nVariable A : Type.\nHypothesis eq_dec : forall x y:A, {x=y} + {~ x=y}.\n\nNotation permutation := (permutation _ eq_dec).\nNotation list_contents := (list_contents _ eq_dec).\n\n\n\nLemma multiplicity_In :\nforall l a, In a l <-> 0 < multiplicity (list_contents l) a.\nProof. hammer_hook \"PermutEq\" \"PermutEq.multiplicity_In\".  \nintros; split; intro H.\neapply In_InA, multiplicity_InA in H; eauto with typeclass_instances.\neapply multiplicity_InA, InA_alt in H as (y & -> & H); eauto with typeclass_instances.\nQed.\n\nLemma multiplicity_In_O :\nforall l a, ~ In a l -> multiplicity (list_contents l) a = 0.\nProof. hammer_hook \"PermutEq\" \"PermutEq.multiplicity_In_O\".  \nintros l a; rewrite multiplicity_In;\ndestruct (multiplicity (list_contents l) a); auto.\ndestruct 1; auto with arith.\nQed.\n\nLemma multiplicity_In_S :\nforall l a, In a l -> multiplicity (list_contents l) a >= 1.\nProof. hammer_hook \"PermutEq\" \"PermutEq.multiplicity_In_S\".  \nintros l a; rewrite multiplicity_In; auto.\nQed.\n\nLemma multiplicity_NoDup :\nforall l, NoDup l <-> (forall a, multiplicity (list_contents l) a <= 1).\nProof. hammer_hook \"PermutEq\" \"PermutEq.multiplicity_NoDup\".  \ninduction l.\nsimpl.\nsplit; auto with arith.\nintros; apply NoDup_nil.\nsplit; simpl.\ninversion_clear 1.\nrewrite IHl in H1.\nintros; destruct (eq_dec a a0) as [H2|H2]; simpl; auto.\nsubst a0.\nrewrite multiplicity_In_O; auto.\nintros; constructor.\nrewrite multiplicity_In.\ngeneralize (H a).\ndestruct (eq_dec a a) as [H0|H0].\ndestruct (multiplicity (list_contents l) a); auto with arith.\nsimpl; inversion 1.\ninversion H3.\ndestruct H0; auto.\nrewrite IHl; intros.\ngeneralize (H a0); auto with arith.\ndestruct (eq_dec a a0); simpl; auto with arith.\nQed.\n\nLemma NoDup_permut :\nforall l l', NoDup l -> NoDup l' ->\n(forall x, In x l <-> In x l') -> permutation l l'.\nProof. hammer_hook \"PermutEq\" \"PermutEq.NoDup_permut\".  \nintros.\nred; unfold meq; intros.\nrewrite multiplicity_NoDup in H, H0.\ngeneralize (H a) (H0 a) (H1 a); clear H H0 H1.\ndo 2 rewrite multiplicity_In.\ndestruct 3; omega.\nQed.\n\n\nLemma permut_In_In :\nforall l1 l2 e, permutation l1 l2 -> In e l1 -> In e l2.\nProof. hammer_hook \"PermutEq\" \"PermutEq.permut_In_In\".  \nunfold PermutSetoid.permutation, meq; intros l1 l2 e P IN.\ngeneralize (P e); clear P.\ndestruct (In_dec eq_dec e l2) as [H|H]; auto.\nrewrite (multiplicity_In_O _ _ H).\nintros.\ngeneralize (multiplicity_In_S _ _ IN).\nrewrite H0.\ninversion 1.\nQed.\n\nLemma permut_cons_In :\nforall l1 l2 e, permutation (e :: l1) l2 -> In e l2.\nProof. hammer_hook \"PermutEq\" \"PermutEq.permut_cons_In\".  \nintros; eapply permut_In_In; eauto.\nred; auto.\nQed.\n\n\nLemma permut_nil :\nforall l, permutation l nil -> l = nil.\nProof. hammer_hook \"PermutEq\" \"PermutEq.permut_nil\".  \nintro l; destruct l as [ | e l ]; trivial.\nassert (In e (e::l)) by (red; auto).\nintro Abs; generalize (permut_In_In _ Abs H).\ninversion 1.\nQed.\n\n\n\nLemma permutation_Permutation :\nforall l l', Permutation l l' <-> permutation l l'.\nProof. hammer_hook \"PermutEq\" \"PermutEq.permutation_Permutation\".  \nsplit.\ninduction 1.\napply permut_refl.\napply permut_cons; auto.\nchange (permutation (y::x::l) ((x::nil)++y::l)).\napply permut_add_cons_inside; simpl; apply permut_refl.\napply permut_trans with l'; auto.\nrevert l'.\ninduction l.\nintros.\nrewrite (permut_nil (permut_sym H)).\napply Permutation_refl.\nintros.\ndestruct (In_split _ _ (permut_cons_In H)) as (h2,(t2,H1)).\nsubst l'.\napply Permutation_cons_app.\napply IHl.\napply permut_remove_hd with a; auto with typeclass_instances.\nQed.\n\n\n\nLemma permut_length_1:\nforall a b, permutation (a :: nil) (b :: nil)  -> a=b.\nProof. hammer_hook \"PermutEq\" \"PermutEq.permut_length_1\".  \nintros a b; unfold PermutSetoid.permutation, meq; intro P;\ngeneralize (P b); clear P; simpl.\ndestruct (eq_dec b b) as [H|H]; [ | destruct H; auto].\ndestruct (eq_dec a b); simpl; auto; intros; discriminate.\nQed.\n\nLemma permut_length_2 :\nforall a1 b1 a2 b2, permutation (a1 :: b1 :: nil) (a2 :: b2 :: nil) ->\n(a1=a2) /\\ (b1=b2) \\/ (a1=b2) /\\ (a2=b1).\nProof. hammer_hook \"PermutEq\" \"PermutEq.permut_length_2\".  \nintros a1 b1 a2 b2 P.\nassert (H:=permut_cons_In P).\ninversion_clear H.\nleft; split; auto.\napply permut_length_1.\nred; red; intros.\ngeneralize (P a); clear P; simpl.\ndestruct (eq_dec a1 a) as [H2|H2];\ndestruct (eq_dec a2 a) as [H3|H3]; auto.\ndestruct H3; transitivity a1; auto.\ndestruct H2; transitivity a2; auto.\nright.\ninversion_clear H0; [|inversion H].\nsplit; auto.\napply permut_length_1.\nred; red; intros.\ngeneralize (P a); clear P; simpl.\ndestruct (eq_dec a1 a) as [H2|H2];\ndestruct (eq_dec b2 a) as [H3|H3]; auto.\nsimpl; rewrite <- plus_n_Sm; inversion 1; auto.\ndestruct H3; transitivity a1; auto.\ndestruct H2; transitivity b2; auto.\nQed.\n\n\nLemma permut_length :\nforall l1 l2, permutation l1 l2 -> length l1 = length l2.\nProof. hammer_hook \"PermutEq\" \"PermutEq.permut_length\".  \ninduction l1; intros l2 H.\nrewrite (permut_nil (permut_sym H)); auto.\ndestruct (In_split _ _ (permut_cons_In H)) as (h2,(t2,H1)).\nsubst l2.\nrewrite app_length.\nsimpl; rewrite <- plus_n_Sm; f_equal.\nrewrite <- app_length.\napply IHl1.\napply permut_remove_hd with a; auto with typeclass_instances.\nQed.\n\nVariable B : Type.\nVariable eqB_dec : forall x y:B, { x=y }+{ ~x=y }.\n\n\n\nLemma permutation_map :\nforall f l1 l2, permutation l1 l2 ->\nPermutSetoid.permutation _ eqB_dec (map f l1) (map f l2).\nProof. hammer_hook \"PermutEq\" \"PermutEq.permutation_map\".  \nintros f; induction l1.\nintros l2 P; rewrite (permut_nil (permut_sym P)); apply permut_refl.\nintros l2 P.\nsimpl.\ndestruct (In_split _ _ (permut_cons_In P)) as (h2,(t2,H1)).\nsubst l2.\nrewrite map_app.\nsimpl.\napply permut_add_cons_inside.\nrewrite <- map_app.\napply IHl1; auto.\napply permut_remove_hd with a; auto with typeclass_instances.\nQed.\n\nEnd Perm.\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/quick/PermutEq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6598291085389791}}
{"text": "Require Import\n  Coq.Relations.Relation_Definitions\n  Coq.Relations.Relation_Operators\n  Coq.Relations.Operators_Properties.\n\nRequire Import\n  Coq.Program.Basics\n  Coq.Classes.RelationClasses\n  Coq.Classes.Morphisms.\n\nRequire Import\n  Setoid.\n\n#[local]\nAdd Parametric Relation : Prop impl\n  reflexivity proved by impl_Reflexive\n  transitivity proved by impl_Transitive\n  as PreOrder_impl.\n\nSection Classes.\n  Context\n    {A : Type}\n    (R : relation A).\n\n  Class Connex :\n    Prop :=\n    connexity :\n    forall\n    x y : A,\n    R x y \\/\n    R y x.\n\n  Class Functional :\n    Prop :=\n    functionality :\n    forall\n    x y y' : A,\n    R x y ->\n    R x y' ->\n    y = y'.\n\n  #[local]\n  Instance Asymmetric_Irreflexive\n    (Asymmetric_R : Asymmetric R) :\n    Irreflexive R.\n  Proof.\n    intros x R_x_x.\n    now apply asymmetry with x x.\n  Qed.\nEnd Classes.\n\nModule Restriction.\n  Section Restriction.\n    Context\n      {A : Type}\n      (P : A -> Prop)\n      (R : relation A).\n\n    Definition Restriction :\n      relation (sig P) :=\n      fun x y => R (proj1_sig x) (proj1_sig y).\n\n    Let R' :\n      relation (sig P) :=\n      Restriction.\n\n    #[local]\n    Instance reflexive\n      {Reflexive_R : Reflexive R} :\n      Reflexive R'.\n    Proof.\n      intros (x & P_x).\n      apply Reflexive_R.\n    Qed.\n\n    #[local]\n    Instance irreflexive\n      {Irreflexive_R : Irreflexive R} :\n      Irreflexive R'.\n    Proof.\n      intros (x & P_x).\n      apply Irreflexive_R.\n    Qed.\n\n    #[local]\n    Instance symmetric\n      {Symmetric_R : Symmetric R} :\n      Symmetric R'.\n    Proof.\n      intros (x & P_x) (y & P_y).\n      apply Symmetric_R.\n    Qed.\n\n    #[local]\n    Instance asymmetric\n      {Asymmetric_R : Asymmetric R} :\n      Asymmetric R'.\n    Proof.\n      intros (x & P_x) (y & P_y).\n      apply Asymmetric_R.\n    Qed.\n\n    #[local]\n    Instance transitive\n      {Transitive_R : Transitive R} :\n      Transitive R'.\n    Proof.\n      intros (x & P_x) (y & P_y) (z & P_z).\n      apply Transitive_R.\n    Qed.\n\n    #[local]\n    Instance preorder\n      {PreOrder_R : PreOrder R} :\n      PreOrder R'.\n    Proof.\n      constructor; eauto with typeclass_instances.\n    Qed.\n\n    #[local]\n    Instance equivalence\n      {Equivalence_R : Equivalence R} :\n      Equivalence R'.\n    Proof.\n      constructor; eauto with typeclass_instances.\n    Qed.\n  End Restriction.\n\n  Section PartialOrder.\n    Context\n      {A : Type}\n      (P : A -> Prop)\n      (R Eq : relation A).\n\n    Let R' :\n      relation (sig P) :=\n      Restriction.Restriction P R.\n\n    Let Eq' :\n      relation (sig P) :=\n      Restriction.Restriction P Eq.\n\n    #[local]\n    Existing Instance Restriction.equivalence.\n    #[local]\n    Instance antisymmetric\n      `{Antisymmetric_R : Antisymmetric A R Eq} :\n      Antisymmetric (sig P) R' Eq'.\n    Proof.\n      intros (x & P_x) (y & P_y).\n      apply Antisymmetric_R.\n    Qed.\n\n    #[local]\n    Existing Instance Restriction.preorder.\n    #[local]\n    Instance partial_order\n      `{PartialOrder_R : PartialOrder A R Eq} :\n      PartialOrder R' Eq'.\n    Proof.\n      intros (x & P_x) (y & P_y).\n      apply PartialOrder_R.\n    Qed.\n  End PartialOrder.\nEnd Restriction.\nImport Restriction(Restriction).\n\nModule ReflexiveTransitive.\n  Section ReflexiveTransitive.\n    Context\n      {A : Type}\n      (R : relation A).\n\n    Definition Closure :\n      relation A :=\n      clos_refl_trans_1n _ R.\n\n    #[local]\n    Instance subrelation :\n      subrelation R Closure.\n    Proof.\n      intros x y R_x_y.\n      now apply clos_rt1n_step.\n    Qed.\n\n    #[local]\n    Instance reflexive :\n      Reflexive Closure.\n    Proof.\n      intros x.\n      apply rt1n_refl.\n    Qed.\n\n    #[local]\n    Instance transitive :\n      Transitive Closure.\n    Proof.\n      intros x y z; unfold Closure.\n      rewrite <- 3!clos_rt_rt1n_iff.\n      now constructor 3 with y.\n    Qed.\n\n    #[local]\n    Add Parametric Relation : A Closure\n      reflexivity proved by reflexive\n      transitivity proved by transitive\n      as preorder.\n\n    Add Parametric Morphism\n      {B : Type}\n      (S : relation B)\n      (f : A -> B)\n      `{PreOrder_R : PreOrder B S}\n      `{Proper_f : Proper (A -> B) (R ++> S)%signature f} : f with signature\n      Closure ++> S as morphism.\n    Proof.\n      intros x y Closure_x_y.\n      induction Closure_x_y as\n        [x|\n      x x' y R_x_x' Closure_x'_y IHx'_y].\n        reflexivity.\n      now transitivity (f x'); [rewrite R_x_x'|].\n    Qed.\n  End ReflexiveTransitive.\n\n  Section Restriction.\n    Variables\n      (A : Type)\n      (P : A -> Prop)\n      (R : relation A)\n      (Proper_P : Proper (R ++> impl) P)\n      (x y : A)\n      (P_x : P x).\n\n    #[local]\n    Existing Instance ReflexiveTransitive.reflexive.\n    Lemma Restriction :\n      Closure R x y ->\n      exists\n      P_y : P y,\n      Closure\n        (Restriction P R)\n        (exist P x P_x)\n        (exist P y P_y).\n    Proof.\n      induction 1 as\n        [x|\n      x x' y R_x_x' Closure_x'_y IHx'_y].\n        now exists P_x.\n      assert (P_x' : P x') by now rewrite <- R_x_x'.\n      specialize IHx'_y with P_x' as (P_y & H).\n      now exists P_y; constructor 2 with (exist P x' P_x').\n    Qed.\n  End Restriction.\nEnd ReflexiveTransitive.\n", "meta": {"author": "BasaltEXE", "repo": "shuffle", "sha": "bd095e45de6cc8e940736860db990c73ff0d4929", "save_path": "github-repos/coq/BasaltEXE-shuffle", "path": "github-repos/coq/BasaltEXE-shuffle/shuffle-bd095e45de6cc8e940736860db990c73ff0d4929/Relations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7799929053683037, "lm_q1q2_score": 0.6598291055095236}}
{"text": "(* The needed primitives                                                        *)\nVariable Exists   : forall (a:Type), (a -> Prop) -> Prop. \nVariable mkExists : forall (a:Type) (p:a -> Prop) (x:a), p x -> Exists a p.\nVariable ExistsInd : forall (a:Type) (p:a -> Prop) (c:Exists a p -> Prop), (forall (x:a)(q:p x), c (mkExists a p x q)) -> forall (e:Exists a p), c e.\nDefinition ExistsE : forall (a:Type) (p:a -> Prop) (A:Prop), (forall (x:a), p x -> A) -> Exists a p -> A := \n    fun a p A H e => ExistsInd a p (fun _ => A) H e.\n\n(* THese primitives exist                                                       *)\nInductive Exists2 (a:Type) (p:a -> Prop) : Prop :=\n| mkExists2 : forall (x:a), p x -> Exists2 a p\n.\n\nDefinition ExistsInd2 : forall (a:Type) (p:a -> Prop) (c:Exists2 a p -> Prop), \n    (forall (x:a)(q:p x), c (mkExists2 a p x q)) -> \n        forall (x:Exists2 a p), c x :=\n    fun (a:Type) (p:a -> Prop) (c:Exists2 a p -> Prop) (f:forall (x:a) (q:p x), c (mkExists2 a p x q)) (e:Exists2 a p) =>\n        match e with\n        | mkExists2 _ _ x q => f x q\n        end. \n\nDefinition ExistsE2 : forall (a:Type) (p:a -> Prop) (A:Prop), \n    (forall (x:a), p x -> A) -> Exists2 a p -> A := \n    fun a p A H e => ExistsInd2 a p (fun _ => A) H e.\n\n(*\nCheck Exists2.\nCheck mkExists2.\nCheck ExistsInd2.\nCheck ExistsE2.\n*)\n\n\nArguments Exists {a}.\nArguments mkExists {a} {p}.\n\n\nDefinition L1 : forall (a:Type) (p:a -> Prop), ~(Exists p) <-> forall (x:a), ~ p x.\nProof.\n    intros a p. split.\n    - intros f x H. apply f. apply mkExists with x. assumption.\n    - intros f H. apply (ExistsE a p). \n        + intros x H'. apply (f x). assumption.\n        + assumption.\nQed.\n\nDefinition L2 : forall (a:Type) (p:a -> Prop), ~(Exists p) <-> forall (x:a), ~ p x.\nProof.\nrefine (\n    fun (a:Type) (p:a -> Prop) => conj\n        (fun (f:~Exists p) (x:a) (H:p x) => f (mkExists x H))\n        (fun (f:forall (x:a), ~ p x) (H:Exists p) =>\n            ExistsE a p False \n                (fun (x:a) (H':p x) => f x H') \n                H\n)).\nDefined.\n\nDefinition L3 : forall (a b:Type) (p:a -> b -> Prop),\n    Exists (fun (x:a) => Exists (fun (y:b) => p x y)) -> \n    Exists (fun (y:b) => Exists (fun (x:a) => p x y)).\nProof.\n    intros a b p H1. \n    apply (ExistsE a (fun (x:a) => Exists (fun (y:b) => p x y))).\n    - intros x H2. apply (ExistsE b (fun (y:b) => p x y)).\n        + intros y H3. apply (mkExists y). apply (mkExists x). exact H3.\n        + exact H2.\n    - exact H1.\nQed.\n\n\nDefinition L4 : forall (a b:Type) (p:a -> b -> Prop),\n    Exists (fun (x:a) => Exists (fun (y:b) => p x y)) -> \n    Exists (fun (y:b) => Exists (fun (x:a) => p x y)).\nProof.\nrefine (\n    fun (a b:Type) (p:a -> b -> Prop) =>\n        fun (H1:Exists (fun (x:a) => Exists (fun (y:b) => p x y))) =>\n            ExistsE a (fun (x:a) => Exists (fun (y:b) => p x y)) _\n                (fun (x:a) (H2: Exists (fun (y:b) => p x y)) => \n                    ExistsE b (fun (y:b) => p x y) _\n                        (fun (y:b) (H3:p x y) =>\n                            mkExists y (mkExists x H3))\n                        H2)\n                H1\n).\nDefined.\n\nDefinition L5 : forall (a:Type) (p q : a -> Prop),\n    Exists (fun x => p x \\/ q x) <-> Exists p \\/ Exists q.\nProof.\n    intros a p q. split.\n    - intros H. apply (ExistsE a (fun x => p x \\/ q x)).\n        + intros x [H'|H'].\n            { left.  apply (mkExists x). exact H'. }\n            { right. apply (mkExists x). exact H'. }\n        + exact H.\n    - intros [H|H].\n        + apply (ExistsE a p).\n            { intros x H'. apply (mkExists x). left. exact H'. }\n            { assumption. }\n        + apply (ExistsE a q).\n            { intros x H'. apply (mkExists x). right. exact H'. }\n            { assumption. }\nQed.\n\nDefinition L6 : forall (a:Type) (p q : a -> Prop),\n    Exists (fun x => p x \\/ q x) <-> Exists p \\/ Exists q.\nProof.\nrefine (\n    fun (a:Type) (p q:a -> Prop) => conj\n        (fun (H:Exists (fun x => p x \\/ q x)) => \n            ExistsE a (fun x => p x \\/ q x) (Exists p \\/ Exists q)\n                (fun (x:a) (H':p x \\/ q x) =>\n                    match H' with\n                    | or_introl H'  => or_introl (mkExists x H')\n                    | or_intror H'  => or_intror (mkExists x H')\n                    end) H)\n        (fun (H:Exists p \\/ Exists q) => \n            match H with\n            | or_introl H   => ExistsE a p (Exists (fun x => p x \\/ q x)) \n                (fun (x:a) (H':p x) => mkExists x (or_introl H')) H\n            | or_intror H   => ExistsE a q (Exists (fun x => p x \\/ q x))\n                (fun (x:a) (H':q x) => mkExists x (or_intror H')) H\n            end)).\nDefined.\n\nDefinition L7 : forall (a:Type) (p:a -> Prop),\n    Exists p -> ~ forall (x:a), ~ p x.\nProof.\n    intros a p H1 H2. apply (ExistsE a p).\n    - intros x H3. apply (H2 x). exact H3.\n    - exact H1.\nQed.\n\nDefinition L8 : forall (a:Type) (p:a -> Prop), Exists p -> ~ forall (x:a), ~ p x \n:=  fun (a:Type) (p:a -> Prop) =>\n        fun (H1:Exists p) (H2:forall (x:a), ~ p x) =>\n            ExistsE a p False H2 H1.\n\nDefinition L9 : forall (a:Type) (p:a -> Prop)(A:Prop),\n    (Exists p -> A) <-> forall (x:a), p x -> A.\nProof.\n    intros a p A. split; intros H.\n    - intros x Hx. apply H. apply mkExists with x. exact Hx.\n    - intros H'. apply (ExistsE a p).\n        + exact H.\n        + exact H'.\nQed.\n\nDefinition L10 : forall (a:Type) (p:a -> Prop)(A:Prop),\n    (Exists p -> A) <-> forall (x:a), p x -> A.\nProof.\nrefine (\n    fun (a:Type) (p:a -> Prop) (A:Prop) => conj\n        (fun (H:Exists p -> A) (x:a) (Hx:p x)  => \n            H (mkExists x Hx)) \n        (fun (H:forall (x:a), p x -> A) (H':Exists p) =>\n            ExistsE a p A H H'\n)). \nQed.\n\nDefinition L11 : forall (a:Type) (p:a -> Prop),\n    ~~(Exists p) <-> ~ forall (x:a), ~ p x.\nProof.\n    intros a p. split; intros H1 H2.\n    - apply H1. intros H3. apply (ExistsE a p False).\n        + intros x Hx. apply (H2 x). exact Hx.\n        + exact H3.\n    - apply H1. intros x Hx. apply H2. apply mkExists with x. exact Hx.\nQed.\n\nDefinition L12 : forall (a:Type) (p:a -> Prop),\n    ~~(Exists p) <-> ~ forall (x:a), ~ p x.\nProof.\nrefine (\n    fun (a:Type) (p:a -> Prop) => conj\n        (fun (H1:~~Exists p) (H2: forall (x:a), ~ p x) => \n            H1 (fun (H3:Exists p) => \n                ExistsE a p False \n                    (fun (x:a) (Hx:p x) => H2 x Hx) \n                    H3))\n        (fun (H1:~ forall (x:a), ~ p x) (H2:~Exists p) =>\n            H1 (fun (x:a) (Hx:p x) => H2 (mkExists x Hx)))).\nQed.\n\nDefinition L13 : forall (a:Type) (p:a -> Prop),\n    Exists (fun x => ~~p x) -> ~~Exists p.\nProof.\n    intros a p H1 H2. apply (ExistsE a (fun x => ~~p x) False).\n    - intros x Hx. apply Hx. intros Hx'. apply H2. \n      apply mkExists with x. exact Hx'.\n    - exact H1.\nQed.\n\nDefinition L14 : forall (a:Type) (p:a -> Prop),\n    Exists (fun x => ~~p x) -> ~~Exists p.\nProof.\nrefine (\n    fun (a:Type) (p:a -> Prop) (H1:Exists (fun x => ~~p x)) (H2:~Exists p) =>\n    ExistsE a (fun x => ~~p x) False\n        (fun (x:a) (Hx:~~p x) => Hx (fun (Hx':p x) => H2 (mkExists x Hx')))\n        H1\n).\nQed.\n\nDefinition L15 : forall (A:Prop), A <-> exists (q:A), True. \nProof.\n    intros A. split; intros H.\n    - exists H. apply I.\n    - destruct H as [q H]. exact q.\nQed.\n\n\n\nDefinition L16 : forall (A:Prop), A <-> exists (q:A), True.\nProof.\nrefine (\n    fun (A:Prop) => conj\n        (fun (H:A) => ex_intro (fun (_:A) => True) H I)\n        (fun (H:exists (q:A), True) =>\n            match H with\n            | ex_intro _ q _  => q\n            end\n)).\nQed.\n\nDefinition L17 : forall (a:Type) (x y:a), \n    x <> y <-> exists (p:a -> Prop), p x /\\ ~p y.\nProof.\n    intros a x y. split; intros H.\n    - exists (fun (z:a) => x = z). split.\n        + reflexivity.\n        + exact H.\n    - destruct H as [p [H1 H2]]. intros H. apply H2. \n      rewrite <- H. exact H1.\nQed.\n\nDefinition L18 : forall (a:Type) (x y:a), \n    x <> y <-> exists (p:a -> Prop), p x /\\ ~p y.\nProof.\nrefine (\n    fun (a:Type) (x y:a) => conj\n        (fun (H:x <> y) => ex_intro _ (fun (z:a) => x = z) (conj (eq_refl x) H))\n        (fun (H:exists (p:a -> Prop), p x /\\ ~p y) =>\n            match H with\n            | ex_intro _ p H =>\n                match H with\n                | conj H1 H2 => \n                    fun (H:x = y) => H2 (eq_ind x p H1 y H)\n                end\n            end\n        \n)).\nQed.\n\nDefinition L19 : forall (a:Type) (p:a -> Prop),\n    (exists (x:a), p x) <-> forall (A:Prop), (forall (x:a), p x -> A) -> A.\nProof.\n    intros a p. split.\n    - intros [x H1] A H2. apply H2 with x. exact H1.\n    - intros H1. apply H1. intros x H2. exists x. exact H2.\nQed.\n\n\nDefinition L20 : forall (a:Type) (p:a -> Prop),\n    (exists (x:a), p x) <-> forall (A:Prop), (forall (x:a), p x -> A) -> A.\nProof.\nrefine (\n    fun (a:Type) (p:a -> Prop) => conj\n        (fun (H:exists (x:a), p x) =>\n            match H with\n            | ex_intro _ x H1  =>\n                fun (A:Prop) (H2:forall (x:a), p x -> A) => H2 x H1\n            end)\n        (fun (H1:forall (A:Prop), (forall (x:a), p x -> A) -> A) => \n            H1 (exists (x:a), p x) (fun (x:a) (H2:p x) => ex_intro p x H2))).\nDefined.\n\nDefinition L21 : forall (a:Type) (p q:a -> Prop),\n    (forall (x:a), p x <-> q x) -> \n    (forall (x:a), p x) <-> (forall (x:a), q x).\nProof.\n    intros a p q H1. split; intros H2 x; destruct (H1 x) as [H3 H4].\n    - apply H3. apply H2.\n    - apply H4. apply H2.\nQed.\n\nDefinition L22 : forall (a:Type) (p q:a -> Prop),\n    (forall (x:a), p x <-> q x) -> \n    (forall (x:a), p x) <-> (forall (x:a), q x).\nProof.\nrefine (\n    fun (a:Type) (p q:a -> Prop) (H1:forall (x:a), p x <-> q x) => conj\n        (fun (H2:forall (x:a), p x) (x:a) =>\n            match (H1 x) with\n            | conj H3 H4    => H3 (H2 x)\n            end)\n        (fun (H2:forall (x:a), q x) (x:a) =>\n            match (H1 x) with \n            | conj H3 H4    => H4 (H2 x)\n            end\n)).\nDefined.\n\nDefinition L23 : forall (a:Type) (p q:a -> Prop),\n    (forall (x:a), p x <-> q x) -> \n    (exists (x:a), p x) <-> (exists (x:a), q x).\nProof.\n    intros a p q H1; split; intros [x H2]; \n    destruct (H1 x) as [H3 H4]; exists x.\n    - apply H3. exact H2.\n    - apply H4. exact H2.\nQed.\n\nDefinition L24 : forall (a:Type) (p q:a -> Prop),\n    (forall (x:a), p x <-> q x) -> \n    (exists (x:a), p x) <-> (exists (x:a), q x).\nProof.\nrefine (\n    fun (a:Type) (p q:a -> Prop) (H1:forall (x:a), p x <-> q x) => conj\n        (fun (H2:exists (x:a), p x) =>\n            match H2 with\n            | ex_intro _ x H2   =>\n                match (H1 x) with\n                | conj H3 H4    => ex_intro q x (H3 H2)\n                end\n            end)\n        (fun (H2:exists (x:a), q x) =>\n            match H2 with\n            | ex_intro _ x H2   =>\n                match (H1 x) with\n                | conj H3 H4    => ex_intro p x (H4 H2)\n                end\n            end)\n).\nDefined.\n\nDefinition L25 : forall (a:Type) (p:a -> Prop) (A:Prop),\n    (exists (x:a), p x) /\\ A <-> exists (x:a), p x /\\ A.\nProof.\n    intros a p A. split.\n    - intros [[x H1] H2]. exists x. split.\n        + exact H1.\n        + exact H2.\n    - intros [x [H1 H2]]. split.\n        + exists x. exact H1.\n        + exact H2.\nQed.\n\nDefinition L26 : forall (a:Type) (p:a -> Prop) (A:Prop),\n    (exists (x:a), p x) /\\ A <-> exists (x:a), p x /\\ A.\nProof.\nrefine (\n    fun (a:Type) (p:a -> Prop) (A:Prop) => conj\n        (fun (H1: (exists (x:a), p x) /\\ A) =>\n            match H1 with\n            | conj (ex_intro _ x H1) H2 => ex_intro (fun (x:a) => p x /\\ A) x (conj H1 H2)\n            end)\n        (fun (H1: exists (x:a), p x /\\ A) =>\n            match H1 with\n            | ex_intro _ x (conj H1 H2) => conj (ex_intro p x H1) H2\n            end\n)).\nDefined.\n\nTheorem Barber : forall (a:Type) (p:a -> a -> Prop),\n    ~exists (x:a), forall (y:a), p x y <-> ~ p y y.\nProof.\n    intros a p [x H]. destruct (H x) as [H1 H2];\n    apply H1; apply H2; intros H3; apply H1; assumption.\nQed.\n\nDefinition L27 : forall (a:Type) (p:a -> a -> Prop),\n    ~exists (x:a), forall (y:a), p x y <-> ~ p y y.\nProof.\nrefine (\n    fun (a:Type) (p:a -> a -> Prop) =>\n        fun (H: exists (x:a), forall (y:a), p x y <-> ~p y y ) =>\n            match H with\n            | ex_intro _ x H    =>\n                match (H x) with\n                | conj H1 H2 => \n                    let px := \n                        H2 (fun (qx:p x x) => H1 qx qx)\n                    in H1 px px\n                end\n            end\n).\nDefined.\n\n\nDefinition LawRussell : forall (A:Prop), ~(A <-> ~A).\nProof.\n    intros A [H1 H2]. apply H1; apply H2; intros H3; apply H1; assumption.\nQed.\n\nDefinition L28 : forall (A:Prop), ~(A <-> ~A).\nProof.\nrefine (\n    fun (A:Prop) (H:A <-> ~A) => \n        match H with\n        | conj H1 H2 => \n            let p :=\n                H2 (fun (x:A) => H1 x x)\n            in H1 p p\n        end\n).\nDefined.\n\nDefinition L29 : forall (a:Type) (p:a -> a -> Prop),\n    ~exists (x:a), forall (y:a), p x y <-> ~ p y y.\nProof.\nrefine (\n    fun (a:Type) (p:a -> a -> Prop) =>\n        fun (H:exists (x:a), forall (y:a), p x y <-> ~ p y y ) =>\n            match H with\n            | ex_intro _ x H => LawRussell (p x x) (H x)\n            end\n).\nDefined.\n\nDefinition FixedPoint (a:Type) (f:a -> a) (x:a) : Prop := f x = x.\n\nArguments FixedPoint {a}.\n\nDefinition HasFixedPoint (a:Type) (f:a -> a) : Prop :=\n    exists (x:a), FixedPoint f x.\n\nArguments HasFixedPoint {a}.\n\nDefinition L30 : ~ HasFixedPoint negb.\nProof.\n    unfold HasFixedPoint. unfold FixedPoint. intros [b H]. \n    destruct b; inversion H.\nQed.\n\nDefinition L31 : ~ HasFixedPoint (fun (A:Prop) => ~A).\nProof.\n    unfold HasFixedPoint. unfold FixedPoint. intros [A H1].\n    apply (LawRussell A). split; intros H2.\n    - rewrite <- H1 in H2. assumption.\n    - rewrite H1 in H2. assumption.\nQed.\n\nDefinition Surjective (a b:Type) (f:a -> b) : Prop :=\n    forall (y:b), exists (x:a), f x = y.\n\nArguments Surjective {a} {b}.\n\nTheorem Lawvere : forall (X Y:Type), \n    (exists (F:X -> (X -> Y)), Surjective F) -> \n    forall (f:Y -> Y), HasFixedPoint f.\nProof.\n    intros X Y [F H] f. unfold Surjective in H. \n    unfold HasFixedPoint. unfold FixedPoint.\n    destruct (H (fun u => f (F u u))) as [x H'].\n    exists (F x x). change ((fun u => f (F u u)) x = F x x). \n    rewrite <- H'. reflexivity.\nQed.\n\nDefinition Rewrite : forall (a:Type) (x y:a) (p:a -> Prop),\n    x = y -> p x -> p y.\nProof.\n    intros a x y p E H. rewrite <- E. assumption.\nQed.\n\nDefinition L32 : forall (a:Type) (x y:a) (p:a -> Prop), \n    x = y -> p x -> p y.\nProof.\nrefine (\n    fun (a:Type) (x y:a) (p:a -> Prop) (E:x = y) (H:p x) =>\n        match E with\n        | eq_refl _ => H\n        end\n).\nQed.\n\nDefinition CongFun : forall (a b:Type) (f g:a -> b) (x:a), f = g -> f x = g x.\nProof.\nrefine (\n    fun (a b:Type) (f g:a -> b) (x:a) (E:f = g) =>\n        match E with\n        | eq_refl _ => eq_refl (f x)\n        end\n).\nQed.\n\nArguments CongFun {a} {b} {f} {g}.\n\nDefinition L33 : forall (X Y:Type), \n    (exists (F:X -> (X -> Y)), Surjective F) -> \n    forall (f:Y -> Y), HasFixedPoint f.\nProof.\nrefine (\n    fun (X Y:Type) (H:exists (F:X -> (X -> Y)), Surjective F) =>\n        fun (f:Y -> Y) => \n            match H with\n            | ex_intro _ F H =>\n                match H (fun u => f (F u u)) with\n                | ex_intro _ x H'   => \n                    ex_intro _ (F x x) \n                        (@CongFun X Y (fun u => f (F u u)) (F x) x (eq_sym H'))\n                end\n            end\n).\nQed.\n\nDefinition Cantor : forall (X:Type), ~ exists (f:X -> (X -> bool)), Surjective f.\nProof.\n    intros X H. assert (forall (f:bool -> bool), HasFixedPoint f) as H'.\n        { apply Lawvere with X. assumption. }\n    apply L30. apply H'.\nQed.\n\nDefinition Cantor' : forall (X:Type), ~ exists (f:X -> (X -> Prop)), Surjective f.\nProof.\n    intros X H. assert (forall (f:Prop -> Prop), HasFixedPoint f) as H'.\n        { apply Lawvere with X. assumption. }\n    apply L31. apply H'.\nQed.\n\nInductive Void : Type :=.\n\nDefinition absurd (x:Void) : Void :=\n    match x with end.\n\nLemma L34 : ~ HasFixedPoint absurd.\nProof.\n    unfold HasFixedPoint. intros [x H]. inversion x.\nQed.\n\nLemma L35 : ~HasFixedPoint absurd.\nProof.\nrefine (\n    fun (p:HasFixedPoint absurd) =>\n        match p with\n        | ex_intro _ x H    => \n            match x with end\n        end\n).\nQed.\n\nDefinition L36 (x : bool * bool) : bool * bool :=\n    match x with\n    | (b1,b2)   => (negb b1, b2)\n    end.\n\nDefinition L37: ~HasFixedPoint L36.\nProof.\n    unfold HasFixedPoint, FixedPoint, L36. intros [x H].\n    destruct x as [b1 b2]. destruct b1; inversion H.\nQed.\n\nDefinition L38: ~HasFixedPoint S.\nProof.\n    unfold HasFixedPoint, FixedPoint. intros [n H].\n    revert H. revert n. induction n as [|n IH]; intros H.\n    - inversion H.\n    - inversion H. apply IH. assumption.\nQed.\n\nDefinition L39 (a:Type) : Type := a -> bool.\n\nDefinition cast (a b:Type) (p:a = b) (x:a) : b :=\n    match p with\n    | eq_refl _  => x\n    end.\n\nLemma cast_cast_is_id : forall (a b:Type) (x:a) (p:a = b),\n    cast b a (eq_sym p) (cast a b p x) = x.\nProof.\n   intros a b x p. unfold cast. destruct p. simpl. reflexivity.\nQed.\n\n\nDefinition L41: ~HasFixedPoint L39.\nProof.\n    unfold HasFixedPoint, FixedPoint, L39. intros [a H].\n    apply Cantor with a.\n    remember (fun (x:a) => cast a (a -> bool) (eq_sym H) x) as f eqn:E. \n    exists f. unfold Surjective. intros y.\n    remember (cast (a -> bool) a H y) as x eqn:H1.\n    exists x. rewrite E. rewrite H1. simpl.\n    apply cast_cast_is_id.\nQed.\n\nDefinition L42 : forall (f:True -> True), HasFixedPoint f.\nProof.\n    intros f. unfold HasFixedPoint, FixedPoint.\n    exists I. destruct (f I). reflexivity.\nQed.\n\nDefinition L43 : forall (f:True -> True), HasFixedPoint f.\nProof.\nrefine (\n    fun (f:True -> True) =>\n        ex_intro _ I\n            match (f I) as x return x = I with\n            | I => eq_refl I\n            end\n).\nQed.\n\nDefinition L44 : ~ HasFixedPoint (fun (A:Prop) => ~A).\nProof.\n    intros [X H1]. unfold FixedPoint in H1.\n    assert (HasFixedPoint (fun (x:False) => x)) as H2.\n        { apply Lawvere with X. unfold not in H1. rewrite H1.\n          exists (fun x => x). unfold Surjective. intros y.\n          exists y. reflexivity. }\n    unfold HasFixedPoint in H2. destruct H2 as [x H2].\n    contradiction.\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/cttwc/existential.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6598291029158018}}
{"text": "Require Import Ascii String Nat List.\nOpen Scope nat_scope.\nOpen Scope string_scope.\nImport ListNotations.\nInductive t: Set:=\n  |ess : t\n  |fdsfsd (a:t).\n\nInductive dict : Set := \n  | empty_dict : dict\n  | add_dict (s:string) (n:nat) (d : dict): dict.\nCheck dict.\nCheck empty_dict.\n\nOpen Scope string_scope.\nFixpoint assoc1 (key: string) (mydict: dict) : option nat:= \n  match mydict with\n  |empty_dict => None\n  |add_dict s v d => match s =? key with\n                     |true => Some v\n                     |false => assoc1 key d\n                    end\n  end.\n\nOpen Scope nat_scope.\nFixpoint assoc2 (key: nat) (mydict: dict) : option string := \n  match mydict with\n  |empty_dict => None%string\n  |add_dict s v d => match key =? v with\n                     |true => Some s\n                     |false => assoc2 key d\n                    end\n  end.\n(* Les dictionnaires seront bijectifs, c’est-`a-dire qu’une chaˆıne ou un nombre n’y apparaˆıt qu’au plus une fois.*)\nFixpoint is_bijectif (mydict : dict) : bool :=\n  match mydict with\n  |empty_dict => true\n  |add_dict s v mydict' => match (assoc1 s mydict', assoc2 v mydict') with\n                           | (None, None) => is_bijectif mydict'\n                           | _ => false\n                           end\n  end.\n\nOpen Scope char_scope.\nFixpoint cons_init_dict (m : nat) := \n  match m with\n  |0 => add_dict (String (ascii_of_nat m) EmptyString) m empty_dict\n  |S m => add_dict (String (ascii_of_nat m) EmptyString) m (cons_init_dict m)\n  end.\n\n\nDefinition init_dict := cons_init_dict 256.\nCheck init_dict.\n\n(* Les dictionnaires contiendront des associations pour au moins toutes les chaˆınes de taille 1 (c.`a.d les\ncaract`eres) *)\nFixpoint contain_str_len_1_aux (m:nat) (mydict : dict) := \n  match m with\n  |0 => match assoc1 (String (ascii_of_nat m) EmptyString) mydict with\n        |Some _ => true\n        |None   => false\n        end\n  |S m => match assoc1 (String (ascii_of_nat m) EmptyString) mydict with\n          |Some _ => contain_str_len_1_aux m mydict\n          |None   => false\n          end\n  end.\nDefinition contain_str_len_1 (mydict : dict) : bool := \n  contain_str_len_1_aux 256 mydict.\n\n(* les nombres pr ́esents rempliront exactement tout un intervalle entre 0 inclus et un certain\nnombre max exclus. *)\n\nFixpoint list_nb_contained (mydict : dict) : list nat :=\n  match mydict with\n  | empty_dict => nil\n  | add_dict _ v mydict => cons v (list_nb_contained mydict)\n  end.\nFixpoint max_list_nat (l : list nat) : nat :=\n  match l with\n  |nil => 0\n  |cons n l => max n (max_list_nat l)\n  end.\n\nOpen Scope nat.\nDefinition contain_an_interval (mydict : dict) : bool :=\n  let l := list_nb_contained mydict \n  in max_list_nat l =? (List.length l)-2.\n\nCompute list_nb_contained init_dict.\nCompute List.length (list_nb_contained init_dict).\nCompute contain_an_interval init_dict.", "meta": {"author": "Qdake", "repo": "Programmation-fonctionnelle-et-preuves-formelles-en-Coq", "sha": "d8c9d67fdb37502d9e3e08df11ef446fceb967b7", "save_path": "github-repos/coq/Qdake-Programmation-fonctionnelle-et-preuves-formelles-en-Coq", "path": "github-repos/coq/Qdake-Programmation-fonctionnelle-et-preuves-formelles-en-Coq/Programmation-fonctionnelle-et-preuves-formelles-en-Coq-d8c9d67fdb37502d9e3e08df11ef446fceb967b7/projet_2018.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603725, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6598290998863463}}
{"text": "Add LoadPath \"~/LocalSoftware/CoqAST/plugin/src/\".\nRequire Import PrintAST.ASTPlugin.\n\nVariables P Q : nat -> Prop.\n\nTheorem t1 : (forall (x : nat), (P x) -> (Q x)) -> (forall (x : nat), P x) -> forall (x : nat), Q x.\nProof.\n  intros hxpx hxp n.\n  pose (hpn := hxp n).\n  pose (hpnqn := hxpx n).\n  apply (hpnqn hpn).\nQed.\n\nPrint ex.\n\n\nTheorem t2 : (exists (x : nat), P x) -> exists (x : nat), P x \\/ Q x.\nProof.\n  intros hpx.\n  destruct hpx as [x hpx].\n\n  pose (hpqx := or_introl hpx : P x \\/ Q x).\n", "meta": {"author": "scottviteri", "repo": "ManipulateProofTrees", "sha": "7aeaf156031d80726c7a8cf9b6fce0b4eefd3fe7", "save_path": "github-repos/coq/scottviteri-ManipulateProofTrees", "path": "github-repos/coq/scottviteri-ManipulateProofTrees/ManipulateProofTrees-7aeaf156031d80726c7a8cf9b6fce0b4eefd3fe7/ProofSourceFiles/PredLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6598290985894852}}
{"text": "Require Export D.\n\n(* Subtask 1 *)\n\nTheorem double_negation_excluded_middle : 이중부정 -> 배중률.\nProof.\n  (* FILL IN HERE *)\n  intros NNPP P. apply NNPP. intros Hc.\n  eassert (P -> False) by (intros HP; destruct (Hc (@or_introl P (~P) HP))).\n  destruct (Hc (@or_intror P (~P) H)).\nQed.\n\n(* Subtask 2 *)\n\nFixpoint is_square' (fuel : nat) (n : nat) (m : nat) (k : nat) : bool :=\n  match fuel with\n  | 0 => false\n  | S fuel' =>\n    if Nat.ltb m n then\n      is_square' fuel' n (S (2 * k + m)) (S k)\n    else Nat.eqb n m\n  end\n.\nDefinition is_square (n : nat) : bool := is_square' (S n) n 0 0.\n\nLemma is_square'_trefl : forall fuel n m k,\n  m = k * k -> is_square' fuel n m k = true -> n 이 제곱수이다.\nProof.\n  intro fuel; induction fuel; intros.\n  + inv H0.\n  + unfold is_square' in H0. fold is_square' in H0.\n    destruct (Nat.ltb m n) eqn: Hmn; reflection.\n    - apply (IHfuel _ (S (2 * k + m)) (S k)); try assumption. simpl_arith.\n    - subst m. exists k. congruence.\nQed.\n\nLemma is_square_trefl : forall n, is_square n = true -> n 이 제곱수이다.\nProof.\n  intros. unfold is_square in H.\n  apply is_square'_trefl in H; eauto.\nQed.\n\nLemma sq_inc' : forall n, n * n <= S n * S n.\nProof.\n  intros. replace (S n * S n) with (S (n + n) + n * n) by simpl_arith.\n  remember (n * n) as x. remember (S (n + n)) as y. clear.\n  induction y; simpl; eauto.\nQed.\n\nLemma sq_inc : forall x y, x <= y -> x * x <= y * y.\nProof.\n  intros x y; revert x. induction y; intros; inv H; eauto.\n  apply (le_trans _ (y * y)).\n  + apply IHy. assumption.\n  + apply sq_inc'.\nQed.\n\nLemma is_square'_frefl : forall fuel n m k,\n  fuel > n - m -> m = k * k\n  -> is_square' fuel n m k = false -> forall x, x >= k -> x * x <> n.\nProof.\n  intro fuel; induction fuel; intros.\n  + inv H.\n  + unfold is_square' in H1. fold is_square' in H1.\n    destruct (Nat.ltb m n) eqn: Hmn; reflection.\n    - inv H2; try (intro Hc; subst; le_contra).\n      apply le_prog in H3. remember (S m0) as x; clear m0 Heqx.\n      apply (IHfuel _ (S (2 * k + k * k)) (S k)); try assumption; try (\n        simpl_arith; fail\n      ). apply le_rev in H. apply (le_trans _ (n - k * k)); try assumption.\n      remember (k * k) as y. remember (2 * k) as z. revert Hmn; clear; intros.\n      destruct n; try (inv Hmn; fail).\n      assert (minus_eq : forall x y, x <= y -> S y - x = S (y - x)). {\n        clear; induction x; intros; try (induction y; simpl; eauto; fail).\n        simpl. destruct y; try (inv H; eauto). apply IHx.\n        apply le_S in H1. apply le_rev. assumption.\n      } rewrite (minus_eq _ _ (le_rev _ _ Hmn)). apply le_prog. simpl.\n      revert n y Hmn; induction z; intros; eauto. destruct n; eauto.\n      inv Hmn.\n      * replace (S n - S n) with 0 by (clear; induction n; eauto).\n        replace (S n - (S z + S n)) with 0 by (\n          clear; induction n; simpl_arith; eauto\n        ). eauto.\n      * replace (S n - (S z + y)) with (n - (z + y)) by eauto.\n        rewrite (minus_eq _ _ (le_rev _ _ H0)).\n        apply (le_trans _ (n - y)); try assumption; eauto.\n    - intros Hc. apply sq_inc in H2. rewrite <- H0 in H2.\n      rewrite Hc in H2. clear H0 Hc x k H. inv Hmn.\n      * destruct (H1 eq_refl).\n      * apply le_prog in H. remember (S m0) as m; clear Heqm m0. le_contra.\nQed.\n\nLemma is_sqaure_frefl : forall n, is_square n = false -> ~n 이 제곱수이다.\nProof.\n  intros. unfold is_square in H.\n  assert (n_Sn : S n > n - 0). {\n    replace (n - 0) with n by (clear; induction n; eauto). eauto.\n  } assert (FACT := is_square'_frefl (S n) n 0 0 n_Sn eq_refl H).\n  intro Hc. destruct Hc as [x Heqx].\n  eassert (x >= 0) by (clear; induction x; eauto). destruct (FACT x H0 Heqx).\nQed.\n\nTheorem excluded_middle_square : 제곱수 는 극단적이야! .\nProof.\n  (* FILL IN HERE *)\n  intros x. destruct (is_square x) eqn: Heqx.\n  + left. apply is_square_trefl; assumption.\n  + right. apply is_sqaure_frefl; assumption.\nQed.\n\n(* Subtask 3 *)\n\nFixpoint divides' (fuel : nat) (n : nat) (m : nat) : bool :=\n  match fuel with\n  | 0 => false\n  | S fuel' =>\n    if Nat.ltb n m then match n with 0 => true | _ => false end\n    else divides' fuel' (n - m) m\n  end\n.\n\nDefinition divides (n : nat) (m : nat) := divides' (S n) n m.\n\nLemma divides'_trefl : forall fuel n m,\n  divides' fuel n m = true -> m 이 n 을 나눈다.\nProof.\n  intro fuel; induction fuel; intros.\n  + inv H.\n  + simpl in H. destruct (Nat.ltb n m) eqn: Hnm; reflection.\n    - destruct n; try (inv H; fail). exists 0; eauto.\n    - apply IHfuel in H. destruct H as [x Heqx].\n      assert (n = m * (S x)). {\n        revert Hnm Heqx; clear; intros.\n        assert (n - m + m = n). {\n          clear x Heqx; revert m Hnm. induction n; intros.\n          * inv Hnm. eauto.\n          * destruct m; eauto. simpl. rewrite <- plus_n_Sm.\n            apply le_rev in Hnm. rewrite (IHn _ Hnm). refl.\n        } rewrite <- H. rewrite Heqx. rewrite add_comm. simpl_arith.\n      } exists (S x); assumption.\nQed.\n\nLemma divides_trefl : forall n m, divides n m = true -> m 이 n 을 나눈다.\nProof.\n  intros. eapply divides'_trefl; eassumption.\nQed.\n\nLemma divides'_frefl : forall fuel n m, m > 0 -> fuel > n ->\n  divides' fuel n m = false -> ~m 이 n 을 나눈다.\nProof.\n  intro fuel; induction fuel; intros.\n  + inv H0.\n  + simpl in H1. destruct (Nat.ltb n m) eqn: Hnm; reflection.\n    - destruct n; inv H1. intro Hc.\n      destruct Hc as [x Heqx]. destruct x; simpl_arith; try (inv Heqx; fail).\n      rewrite Heqx in Hnm. unfold lt in Hnm.\n      replace (S (m + m * x)) with (m + S (m * x)) in Hnm by simpl_arith.\n      rewrite add_comm in Hnm; le_contra.\n    - intro Hc. destruct Hc as [x Heqx]. destruct x.\n      * simpl_arith. subst n. inv Hnm. inv H.\n      * assert (m 이 n - m 을 나눈다). {\n          exists x. subst. simpl_arith. rewrite add_comm.\n          remember (m * x) as y; clear. revert y. induction m; intros;\n          simpl_arith; induction y; eauto.\n        } apply IHfuel in H2; try assumption; try (destruct (Heqx H2); fail).\n        destruct m; try (inv H; fail). revert H0 Hnm; clear; intros.\n        destruct n; try (inv Hnm; fail). simpl. apply le_rev in H0.\n        clear Hnm. apply (le_trans _ (S n)); try assumption. apply le_prog.\n        clear. revert n; induction m; intros; induction n; eauto.\nQed.\n\nLemma divides_frefl : forall n m, m > 0 ->\n  divides n m = false -> ~m 이 n 을 나눈다.\nProof.\n  intros. eapply divides'_frefl; try eassumption; eauto.\nQed.\n\nFixpoint is_prime' (n : nat) (m : nat) :=\n  match m with\n  | 0 => false\n  | S m' => match m' with\n    | 0 => true\n    | S _ => if divides n m then false else is_prime' n m'\n    end\n  end\n.\n\nDefinition is_prime (n : nat) :=\n  match n with\n  | 0 => false\n  | S n' => is_prime' n n'\n  end\n.\n\nLemma is_prime'_trefl : forall n m,\n  is_prime' n m = true -> forall x, 1 < x <= m -> ~x 가 n 을 나눈다.\nProof.\n  intros n m; revert n. induction m; intros.\n  + destruct H0; le_contra.\n  + simpl in H. destruct m.\n    - destruct H0; le_contra.\n    - destruct (divides n (S (S m))) eqn: HnSSm; try (inv H; fail).\n      destruct H0. inv H1.\n      * apply divides_frefl; try assumption. clear; induction m; eauto.\n      * apply IHm; try assumption. split; assumption.\nQed.\n\nLemma is_prime_trefl : forall n, is_prime n = true -> n 이 소수이다.\nProof.\n  intros. unfold is_prime in H.\n  destruct n; try destruct n.\n  + inv H.\n  + inv H.\n  + split.\n    - clear; induction n; eauto.\n    - intros. apply (is_prime'_trefl _ (S n)); try assumption.\n      destruct H0. split; try assumption. apply le_rev; assumption.\nQed.\n\nLemma is_prime'_frefl : forall n m,\n  1 < m < n -> is_prime' n m = false -> ~n 이 소수이다.\nProof.\n  intros n m; revert n. induction m; intros; destruct H; try le_contra.\n  simpl in H0. destruct m; try le_contra.\n  destruct (divides n (S (S m))) eqn: HnSSm.\n  + apply divides_trefl in HnSSm. destruct HnSSm. intro Hc.\n    unfold 소수 in Hc. destruct Hc as [_ Hc].\n    specialize (Hc (S (S m)) (conj H H1)). apply Hc. eexists; eauto.\n  + destruct m; try (inv H0; fail). apply IHm; try split.\n    - clear. induction m; eauto.\n    - eapply le_trans; try eassumption; eauto.\n    - assumption.\nQed.\n\nLemma is_prime_frefl : forall n, is_prime n = false -> ~n 이 소수이다.\nProof.\n  intros. unfold is_prime in H.\n  destruct n; try destruct n.\n  + clear. intro Hc. destruct Hc as [Hc _]. le_contra.\n  + clear. intro Hc. destruct Hc as [Hc _]. le_contra.\n  + eapply is_prime'_frefl; try eassumption; split; eauto.\n    destruct n.\n    - inv H.\n    - clear; induction n; eauto.\nQed.\n\nTheorem excluded_middle_prime : 소수 는 극단적이야! .\nProof.\n  (* FILL IN HERE *)\n  intros n. destruct (is_prime n) eqn: EQ.\n  + left. apply is_prime_trefl; assumption.\n  + right. apply is_prime_frefl; assumption.\nQed.\n", "meta": {"author": "ghudegy", "repo": "2020", "sha": "07637dd4640fec626a0c14e929cf147d30b05af4", "save_path": "github-repos/coq/ghudegy-2020", "path": "github-repos/coq/ghudegy-2020/2020-07637dd4640fec626a0c14e929cf147d30b05af4/files/excluded_middle/Method2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6598290977180172}}
{"text": "From mathcomp.ssreflect Require Import all_ssreflect.\n\n\nStructure sset (T:eqType) := SSet {\n                                    seqOf :> seq T;\n                                    uniqueness    : uniq seqOf }.\n\nCanonical  sset_subType T := Eval hnf in [subType for seqOf T ].\nCanonical  sset_eqMixin T:= Eval hnf in [eqMixin of sset T by <:].\nCanonical  sset_eqType T := Eval hnf in  EqType (sset T) (sset_eqMixin T).\n\nLemma undup_preserves_in {T:eqType} (a:T) (l:seq T) : (a \\in l) == (a \\in undup l).\n  move: l.\n  elim =>//=.\n  move=> a0 l IH.\n  rewrite in_cons.\n  case_eq (a == a0).\n  move /eqP =><-.\n\n  simpl.\n  case_eq (a \\in l).\n    by move=><-.\n      by rewrite in_cons eq_refl.\n  move=> Ha.\n  simpl.\n  case_eq (a0 \\in l) =>//=.\n  by rewrite in_cons Ha.\nQed.\n\n\n  \n  Definition union {T:eqType} (x y:sset T) : sset T.\n  refine (SSet _ (undup (x++y)) _).\n  \n  destruct x,y.\n  simpl.\n  move: (undup_uniq seqOf0) => H0.\n  move: (undup_uniq seqOf1) => H1.\n\n  \n\n  elim seqOf0. by exact H1.\n\n  move=> a l IH.\n  apply undup_uniq.\n  Defined.\n\n  Definition intersect {T:eqType} (x y: sset T) : sset T.\n    refine (SSet _ ( filter (fun e => e \\in seqOf _ y) x ) _ ). \n    apply filter_uniq.\n    exact: uniqueness x.\n  Defined.\n\n  Definition EmptySet t: sset t.\n    refine (SSet _ [::] _).\n    done.\n  Defined.\n\n  Definition mk_set {T:eqType} (x:T) : sset T. by refine ( SSet _ [:: x ] _ ).\n  Defined.\n\n  ", "meta": {"author": "sayon", "repo": "mini-c", "sha": "802cd66231053b9835ad83794ebd364224839432", "save_path": "github-repos/coq/sayon-mini-c", "path": "github-repos/coq/sayon-mini-c/mini-c-802cd66231053b9835ad83794ebd364224839432/coqnd/SSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940925, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6597938329039845}}
{"text": "(* Deletion *)\n(*\n * This deletion function was written in the beginning with the start pointer\n * data structure. It was tested to work but nothing was ever proved about it\n * due to time constraints.\n *)\n(*\nFixpoint delete_from_list {X: Type} (sk: nat) (lst: list (nat * X))\n                          : list (nat * X) :=\n  match lst with\n  | nil => nil\n  | (k, v) :: xs => if beq_nat k sk \n                    then xs \n                    else (k,v) :: delete_from_list sk xs\n                         \n  end.\n\nDefinition node_length {X: Type} {b: nat} (tree: bplustree b X): nat :=\n  match tree with\n  | bptLeaf kvl => length kvl\n  | bptNode sp nodes => length nodes\n  end.\n  \nEval simpl in node_length root.\n\nDefinition merge_trees {X: Type} {b:nat} (t1 t2: bplustree b X)\n                       : bplustree b X :=\n  match (t1, t2) with\n  | (bptNode sp1 lst1, bptNode sp2 lst2) => \n      bptNode b X sp1 (app lst1 ((peek_key_deep sp2, sp2) :: lst2))\n  | (bptLeaf lst1, bptLeaf lst2) => bptLeaf b X (app lst1 lst2)\n  | _ => t1\n  end. \n\nDefinition distr_betweentwo {X: Type} {b: nat} (t1 t2: bplustree b X)\n                             : (bplustree b X * bplustree b X) :=\n  match (t1, t2) with\n  | (bptNode sp1 lst1, bptNode sp2 lst2) => \n    if blt_nat (length lst1) b (*the list of t1 is too small*)\n    then \n      (* Here I plus by 1 as the sp2 is being added to lst1 no matter what *)\n      let index_to_split_list2 := minus b (S (length lst1)) in \n      let (part1, part2) := split_at_index lst2 index_to_split_list2 in\n      \n      let ret_tree1 := bptNode b X sp1 ((snoc lst1 (peek_key_deep sp2, sp2)) ++ part1) in\n      \n      let new_list2_sp := match head part2 with\n                          | None => sp2\n                          | Some p => snd p\n                          end in\n      let new_list2 := match tail part2 with\n                       | None => nil\n                       | Some xs => xs\n                       end in\n                       \n      let ret_tree2 := bptNode b X new_list2_sp new_list2 in\n      (ret_tree1, ret_tree2)\n       \n    else (* the list of t2 is too small*)\n      let index_to_split_list1 := minus (length lst1) (minus b (length lst2)) in\n      let (part1, part2) := split_at_index lst1 index_to_split_list1 in\n      \n      let ret_tree1 := bptNode b X sp1 part1 in\n      \n      let new_list2_sp := match head part2 with\n                          | None => sp2\n                          | Some p => snd p\n                          end in\n      let tail_of_part2 := match tail part2 with\n                       | None => nil\n                       | Some xs => xs\n                       end in\n                       \n      let ret_tree2 := bptNode b X new_list2_sp (app (tail_of_part2) ((peek_key_deep sp2, sp2) :: lst2)) in\n      \n      (ret_tree1, ret_tree2)\n  | (bptLeaf kvl1, bptLeaf kvl2) => \n    let (first_half, second_half) := split_in_half (app kvl1 kvl2) in\n    (bptLeaf b X first_half, bptLeaf b X second_half) \n  | _ => (t1, t2) \n  end.\n  \nDefinition leaf := bptLeaf 1 nat [(1, 1)].\nDefinition emptyNode := bptNode 1 nat left [].\nDefinition twoEntriesNode := bptNode 1 nat leaf [(peek_key centre, centre), (peek_key right, right)].\n\nEval compute in twoEntriesNode.\nEval compute in emptyNode.\nEval compute in distr_betweentwo twoEntriesNode emptyNode.\n\n\nFixpoint redistribute_list {X: Type} {b: nat} (nodes: list (nat * bplustree b X))\n                     : (list (nat * bplustree b X) * bool) :=\n  match nodes with\n  | nil => (nil, false)\n  | x1 :: xs1 => \n         match xs1 with\n\t     | nil => ([x1], false)\n\t     | x2 :: nil => if blt_nat (node_length (snd x1)) b\n\t                    then\n\t             \t\t  if beq_nat (node_length (snd x2)) b\n\t             \t\t  then \n\t               \t\t\tlet merge_res := merge_trees (snd x1) (snd x2) in\n\t               \t\t\t([(peek_key_deep merge_res, merge_res)], true)\n\t             \t\t  else \n\t               \t\t\tlet (a, b) := distr_betweentwo (snd x1) (snd x2) in\n\t               \t\t\t((peek_key_deep a, a) :: (peek_key_deep b, b) :: nil, false)\n\t           \t\t\telse if blt_nat (node_length (snd x2)) b\n\t                \tthen\n\t                  \t  if beq_nat (node_length (snd x1)) b\n\t                  \t  then \n\t                    \tlet merge_res := merge_trees (snd x1) (snd x2) in\n\t                    \t([(peek_key_deep merge_res, merge_res)], true)\n\t                  \t  else \n\t                    \tlet (a, b) := distr_betweentwo (snd x1) (snd x2) in\n\t                    \t((peek_key_deep a, a) :: (peek_key_deep b, b) :: nil, false)\n\t                \telse\n\t                  \t  (x1 :: x2 :: nil, false)\n\t     | x2 :: xs2 => if blt_nat (node_length (snd x1)) b\n\t                    then \n\t                      if beq_nat (node_length (snd x2)) b\n\t                      then \n\t                        let merge_res := merge_trees (snd x1) (snd x2) in\n\t                        ((peek_key_deep merge_res, merge_res) :: xs2, true)\n\t                      else \n\t                        let (a, b) := distr_betweentwo (snd x1) (snd x2) in\n\t                        ((peek_key_deep a, a) :: (peek_key_deep b, b) :: xs2, false)\n\t                    else\n\t                      let (res, should_balance) := redistribute_list xs1 in\n\t                      (x1 :: res, should_balance)\n\t     end\n  end.\n\nDefinition redistribute {X: Type} {b: nat} (tree: bplustree b X)\n                            : (bplustree b X * bool) :=\n  match tree with\n  | bptLeaf kvl => (tree, false)\n  | bptNode sp nil => (tree, true)\n  | bptNode sp lst => \n    let (res, should_balance) := redistribute_list ((peek_key_deep sp, sp) :: lst) in\n    match res with\n    | nil => (bptNode b X sp res, should_balance) (*Should never be a possibility*)\n    | (k, v) :: xs => (bptNode b X v xs, should_balance) \n    end\n  end.\n\nDefinition balance {X: Type} {b: nat} (tree_ind: bplustree b X * bool)\n                            : bplustree b X * bool :=\n  match snd tree_ind with\n  | false => (fst tree_ind, false)\n  | true  => redistribute (fst tree_ind)\n  end.\n  \n  \n(* Returns a tree that it has deleted an entry from, a bool indicating if balancing should\n   be performed *)\nFixpoint delete' {X: Type} {b: nat} (sk: nat) (tree: (bplustree b X))\n                : (bplustree b X * bool) :=\n  \n  let fix traverse_node (nptrs: list (nat * (bplustree b X)))\n                   : (list (nat * (bplustree b X)) * bool) :=\n    match nptrs with\n    | nil => (nil, false)\n    | (k1,t1) :: xs => match xs with\n                       | nil => let (new_tree, should_balance) := delete' sk t1 in\n                                  (((peek_key_deep new_tree, new_tree) :: xs), should_balance) \n                       \n                       | (k2, t2) :: xs' => if blt_nat sk k2 \n                                            then \n                                              let (new_tree, should_balance) := delete' sk t1 in\n                                \t\t\t    (((peek_key_deep new_tree, new_tree) :: xs), should_balance)\n                                \t\t\t  \n                                            else \n                                              let (traversed, should_balance) := traverse_node xs in\n                       \t\t\t\t\t\t  ((k1,t1) :: traversed, should_balance)\t\t\t  \n                       end\n    end\n  \n  in\n  \n  match tree with\n  | bptLeaf kvl => let deletion_lst := delete_from_list sk kvl in \n                     if blt_nat (length deletion_lst) b \n                     then (bptLeaf b X deletion_lst, true)\n                     else (bptLeaf b X deletion_lst, false)\n  | bptNode sp nil => \n                let (new_sp, should_balance) := delete' sk sp in\n  \t\t\t      let new_node := (bptNode b X new_sp nil) in\n  \t\t\t        balance (new_node, should_balance)\n  \t\t\t    \n  | bptNode sp ((k, child) :: xs) => \n                if blt_nat sk k \n  \t\t\t    then \n  \t\t\t      let (new_sp, should_balance) := delete' sk sp in\n  \t\t\t      let new_node := (bptNode b X new_sp ((k, child) :: xs)) in\n  \t\t\t        balance (new_node, should_balance)\n  \t\t\t    \n  \t\t\t    else \n  \t\t\t      let (new_node_list, should_balance) := traverse_node ((k, child) :: xs) in\n  \t\t\t      let new_node := (bptNode b X sp (new_node_list)) in\n  \t\t\t        balance (new_node, should_balance)\n  end.\n\nDefinition delete {X: Type} {b: nat} (sk: nat) (tree: (bplustree b X))\n                : bplustree b X :=\n  match fst (delete' sk tree) with\n  | bptNode sp nil => sp\n  | t => t \n  end.\n  \nDefinition empty2Tree := bptLeaf 1 nat [].\nDefinition atree:= insert 17 117 (insert 6 106 (insert 31 131 (insert 4 104 (insert 20 120 (insert 15 115 \n                   (insert 1 101 (insert 7 107 (insert 3 103 empty2Tree)))))))).\nEval compute in atree.\n\n(*Definition missing_some := delete 31 (delete 20 (delete 6 (delete 3 (delete 4 atree)))).\nEval compute in missing_some.\nDefinition missing_17 := delete 17 missing_some.\nEval compute in delete 15 (delete 7 (delete 1 missing_17)).*)\n\n  \n  \n  *)\n  \n  \n  \n  \n  \n  \n  \n  \n  \n", "meta": {"author": "nicolaidahl", "repo": "BPlusTrees", "sha": "f017e4d3a334f72e1fd1cfb777e5bdd78cd9ca49", "save_path": "github-repos/coq/nicolaidahl-BPlusTrees", "path": "github-repos/coq/nicolaidahl-BPlusTrees/BPlusTrees-f017e4d3a334f72e1fd1cfb777e5bdd78cd9ca49/code/DiscardedDeletionFunction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6597337140827032}}
{"text": "Require Import CoqCompile.Cps.\n(* must import ZArith first, otherwise coq wont recognize Z type *)\nRequire Import ZArith List String Bool.\nRequire Import ExtLib.Sets.ListSet.\nRequire Import ExtLib.Decidables.Decidable.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n(* implements Abstracting Abstract Machines from class 2012-10-22 *)\n\nModule AAMach.\n  Import CPS.\n\n  (********** type definitions **********)\n\n  (* abstract values *)\n  Inductive hval : Type := \n  | Con_h : constructor -> hval\n  | Z_h : Z -> hval\n  | Tup_h : list var -> hval\n  (* | Clo_h : env_t (lset (@eq hval)) -> list var -> exp -> hval. *)\n  (* dont need closures? *)\n  | Lam_h : list var -> exp -> hval.\n\n  Definition is_Z_h (v:hval) :bool:=\n    match v with\n      | Z_h _ => true\n      | _ => false\n    end.\n  Definition is_Tup_h (v:hval): bool:=\n    match v with \n      | Tup_h _ => true\n      | _ => false\n    end.\n  Definition is_Lam_h (v:hval):bool:=\n    match v with\n      | Lam_h _ _ => true\n      | _ => false\n    end.\n  Definition is_Con_h (v:hval):bool:=\n    match v with\n      | Con_h _ => true\n      | _ => false\n    end.\n\n\n  (* sets of abstract values *)\n  Definition hset := lset (@eq hval).\n\n  (* abstract environment mapping variables to sets of abstract values *)  \n  Definition henv := env_t hset.\n\n\n(********** equality functions **********)\n\n  Definition exp_eq_dec : forall (x y:exp), {x=y}+{x<>y}.\n    fix exp_eq_dec 1\n      with (decl_eq_dec (x y:decl) {struct x}: {x=y}+{x<>y}).\n    repeat decide equality.\n    repeat decide equality.\n  Defined.\n\n  Definition exp_eq_bool (e1 e2: exp) : bool :=\n    if exp_eq_dec e1 e2 then true else false.\n\n  Definition string_dec_bool (s1 s2: string) : bool :=\n    if string_dec s1 s2 then true else false.\n\nSection eq_list.\n  Context {A:Type}.\n  Variable (eqA:A->A->bool).\n  Fixpoint eq_list (l1 l2: list (A)): bool:=\n    match l1,l2 with\n      | nil,nil => true\n      | (a1)::q1,(a2)::q2=> eqA a1 a2 && eq_list q1 q2\n      | _,_ => false\n    end.\nEnd eq_list.\n\n(* Section eq_pair. *)\n(*   Context {A B :Type}. *)\n(*   Variable (eqA:A->A->bool). *)\n(*   Variable (eqB:B->B->bool). *)\n(*   Fixpoint eq_pair (p1 p2: A*B): bool := *)\n(*     match p1,p2 with *)\n(*       | (p1a,p1b),(p2a,p2b) => eqA p1a p2a && eqB p1b p2b *)\n(*     end. *)\n(* End eq_pair. *)\n\n(* Section eq_env. *)\n(*   Context {A:Type}. *)\n(*   Variable (eqA:A->A->bool). *)\n(*   Definition eq_env (env1 env2: env_t A):bool:= *)\n(*     eq_list (eq_pair string_dec_bool eqA) env1 env2. *)\n(* End eq_env. *)\n\n(* Section eq_set. *)\n(*   Context{A:Type}. *)\n(*   Variable(eqA:A->A->bool). *)\n(*   Definition eq_set (set1 set2: lset (@eq A)):bool:= *)\n(*     eq_list eqA set1 set2. *)\n(* End eq_set. *)\n\n  Fixpoint hval_eq (h1 h2: hval) : bool :=\n    match h1, h2 with\n      | Con_h c1, Con_h c2 => string_dec_bool c1 c2\n      | Z_h z1, Z_h z2 => Zeq_bool z1 z2\n      | Tup_h xs1, Tup_h xs2 => eq_list string_dec_bool xs1 xs2\n      (* | Clo_h env1 xs1 e1, Clo_h env2 xs2 e2 =>  *)\n      (*   eq_env (eq_set hval_eq) env1 env2 && *)\n      (*   eq_list string_dec_bool xs1 xs2 && *)\n      (*   exp_eq_bool e1 e2 *)\n      | Lam_h xs1 e1, Lam_h xs2 e2 =>\n        eq_list string_dec_bool xs1 xs2 && exp_eq_bool e1 e2\n      | _,_  => false\n    end.\n  Definition hval_eq_prop (h1 h2:hval):Prop:=\n    if hval_eq h1 h2 then True else False.\n \n\n\n\n(********** set functions **********)\n\n(* returns union of vs1 and vs2 *)\nFixpoint hset_union (vs1:hset) (vs2:hset):hset:=\n  match vs1 with\n    | nil => vs2\n    | v::vs => hset_union vs (lset_add hval_eq v vs2)\n  end.\n\n(* filters out elements x of vs where f(x) = false *)\nFixpoint hset_filter (f:hval->bool) (vs:hset) : hset :=\n  match vs with\n    | nil => nil\n    | v::rest => if f v then v::hset_filter f rest else hset_filter f rest\n  end. \n\n\n\n(********** env functions **********)\n\n(* extend env(x) with v, ie env(x) = env(x) \\cup {v} *)\nFixpoint extend_env (env:henv) (x:var) (v:hval): henv:=\n  match env with\n    | nil => (x,(lset_add hval_eq v (lset_empty hval_eq_prop)))::nil\n    | (y,vs)::rest => \n      if string_dec x y \n        then (x,(lset_add hval_eq v vs))::rest\n        else (y,vs)::extend_env rest x v\n  end.\n\n(* extend env(x) with vs, ie env(x) = env(x) \\cup vs *)\nFixpoint extend_envs (env:henv) (x:var) (vs:hset):henv:=\n  match env with\n    | nil => (x,vs)::nil\n    | (y,vs2)::rest =>\n      if string_dec x y\n        then (x,hset_union vs vs2)::rest\n        else (y,vs2)::extend_envs rest x vs\n  end.\n\nLocal Open Scope string_scope.\n\nDefinition h1 := Con_h \"A\".\nDefinition h2 := Con_h \"B\".\nDefinition h3 := Tup_h (\"x\"::\"y\"::\"z\"::nil).\nDefinition h4 := Tup_h (\"a\"::\"b\"::nil).\nDefinition h5 := Z_h 2.\n\nDefinition env1 := extend_env nil \"x\" h1.\nDefinition env2 := extend_env env1 \"x\" h2.\nDefinition env3 := extend_env env2 \"x\" h1.\n(* h1 (\"A\") should only appear once *)\nEval compute in env3.\nDefinition env4 := extend_env env3 \"y\" h1.\nDefinition env5 := extend_env env4 \"y\" h3.\nEval compute in env5.\n\n(* extracts var from Op *)\nDefinition o2x (o:op):var :=\n  match o with\n    | Var_o x => x\n    | _ => \"x\" (* shouldnt get here bc we are assuming only vars *)\n  end.\n\nLocal Close Scope string_scope.\n\n(* non-option version of env lookup, return emptyset if x\\notin dom(env)*)\nFixpoint env_lookup (env:henv) (x:var):hset:=\n  match env with\n    | nil => (lset_empty hval_eq_prop)\n    | (y,vs)::rest => if string_dec x y then vs else env_lookup rest x\n  end.\n\n(* env(x) = env(x) \\cup env(\\pi i tup) *)\nFixpoint extend_env_proj_tup (env:henv) (x:var) (i:Z) (tup:list var): henv:=\n  extend_envs env x (env_lookup env (nth (Z.abs_nat i) tup x)).\n\n(* extend env(x) with ith element of every tuple in tups *)\nFixpoint extend_env_proj (env:henv) (x:var) (i:Z) (tups:hset):henv:=\n  match tups with \n    | nil => env\n    | (Tup_h xs)::rest => \n      extend_env_proj (extend_env_proj_tup env x i xs) x i rest\n    | _ => env (* can get here bc tups is all Tup_h *)\n  end.\n\n(* for x in xs, extend env(x) with env(arg), for corresponding arg in args *)\nFixpoint extend_env_xs (env:henv) (xs:list var) (args:list var):henv:=\n  match xs,args with\n    | nil,nil => env\n    | x::rest,y::restargs => \n      extend_env_xs (extend_envs env x (env_lookup env y)) rest restargs\n    | _,_ => env\n  end.\n      \n(* merge two environments, extending when appropriate, and adding otherwise *)\nFixpoint merge_envs (env1:henv) (env2:henv):henv:=\n  match env1,env2 with \n    | nil,nil => nil\n    | nil,_ => env2\n    | _,nil => env1\n    | (x,vs)::rest,_ => merge_envs rest (extend_envs env2 x vs)\n  end.\n\n\n\nLocal Open Scope string_scope.\n\n(********** Abstracting Abstract Machines **********)\n\n(* extend env with decl d *)\nFixpoint extend (env:henv) (d:decl) : henv :=\n  match d with\n    | Op_d x (Con_o c) => extend_env env x (Con_h c)\n    | Op_d x (Int_o z) => extend_env env x (Z_h z)\n    | Prim_d x Plus_p xs => extend_env env x (Con_h \"Int\")\n    | Prim_d x MkTuple_p os => extend_env env x (Tup_h (map o2x os))\n    | Prim_d x Proj_p ((Int_o i)::tup::nil) => \n      extend_env_proj env x i (hset_filter is_Tup_h (env_lookup env (o2x tup)))\n    | Fn_d f xs e => extend_env env f (Lam_h xs e)\n    | Rec_d ds =>\n      (fix map_extend (ds:list decl) (env:henv): henv :=\n        match ds with\n          | nil => env\n          | d::rest => map_extend rest (extend env d)\n        end) ds env\n    | _ => env\n  end.\n\nLocal Close Scope string_scope.\n\n(* given machine state of e and env, compute list of envs, \n   one for each possible final state *)\nFixpoint aeval (fuel:nat) (e:exp) (env:henv) : list henv:=\n  match fuel with\n    | 0 => nil\n    | S n => \n      match e with\n        | App_e o os => \n          let lams := hset_filter is_Lam_h (env_lookup env (o2x o)) in\n          let args := map o2x os in\n            flat_map\n            (fun v => \n              match v with\n                | Lam_h xs e => aeval n e (extend_env_xs env xs args)\n                | _ => nil\n              end)\n            lams\n        | Let_e d e => aeval n e (extend env d)\n        | Switch_e o arms def => \n          (flat_map\n            (fun arm => \n              match arm with \n                | (_,e) => aeval n e env\n              end)\n            arms) ++\n          (match def with\n             | None => nil\n             | Some e => aeval n e env\n           end)\n        | Halt_e o => env::nil\n      end\n  end.\n\n(* computes abstract env for given program e \n   by merging all envs from possible states *)\nDefinition inj (e:exp) : henv := fold_left merge_envs (aeval 100 e nil) nil.\n\n\n\nLocal Open Scope string_scope.\n\nDefinition e1 := Halt_e (Var_o \"x\").\nEval compute in inj e1.\n\nDefinition e2 := Let_e (Op_d \"x\" (Var_o \"y\")) e1.\nEval compute in inj e2.\n\n(* test projection *)\nDefinition e3 := Let_e (Op_d \"x\" (Con_o \"A\"))\n                  (Let_e (Op_d \"y\" (Con_o \"B\"))\n                   (Let_e (Prim_d \"z\" MkTuple_p (Var_o \"x\"::Var_o \"y\"::nil))\n                     (Let_e (Op_d \"w\" (Con_o \"C\"))\n                       (Let_e (Prim_d \"w\" Proj_p (Int_o 0::Var_o \"z\"::nil))\n                         (Halt_e (Var_o \"w\")))))).\n(* env(w) should be \"C\" and either \"A\" or \"B\", \n   depending on whether e3 gets the 1st or 2nd element from tuple \"z\" *)\nEval compute in inj e3.\n\nDefinition e4 :=\n  Let_e (Op_d \"1\" (Int_o 1))\n   (Let_e (Op_d \"2\" (Int_o 2))\n     (Let_e (Op_d \"3\" (Int_o 3))\n       (Let_e (Op_d \"4\" (Int_o 4))\n         (Let_e (Fn_d \"f\" (\"x\"::\"y\"::nil)\n                  (Let_e (Prim_d \"z\" Plus_p (Var_o \"x\"::Var_o \"y\"::nil))\n                    (Halt_e (Var_o \"z\"))))\n           (App_e (Var_o \"f\") (Var_o \"1\"::Var_o \"2\"::nil)))))).\n(* result \"z\" should have abstract value \"Int\" *)\nEval compute in inj e4.\n\n(* test combining of fn parameters of the same name*)\nDefinition e5 :=\n  Let_e (Op_d \"1\" (Int_o 1))\n   (Let_e (Op_d \"2\" (Int_o 2))\n     (Let_e (Op_d \"3\" (Int_o 3))\n       (Let_e (Op_d \"4\" (Int_o 4))\n         (Let_e (Fn_d \"g\" (\"x\"::\"y\"::nil)\n                  (Let_e (Prim_d \"z\" Plus_p (Var_o \"x\"::Var_o \"y\"::nil))\n                    (Halt_e (Var_o \"z\"))))\n           (Let_e (Fn_d \"f\" (\"x\"::\"y\"::nil)\n                    (App_e (Var_o \"g\") (Var_o \"3\"::Var_o \"4\"::nil)))\n             (App_e (Var_o \"f\") (Var_o \"1\"::Var_o \"2\"::nil))))))).\n(* env(x) and env(y) should have multiple values: 1 and 3, and 2 and 4 *)\nEval compute in inj e5.\n\n(* test multiple possible tuples in a projection *)\nDefinition e6 :=\n  Let_e (Op_d \"1\" (Int_o 1))\n   (Let_e (Op_d \"2\" (Int_o 2))\n     (Let_e (Op_d \"3\" (Int_o 3))\n       (Let_e (Op_d \"4\" (Int_o 4))\n         (Let_e (Prim_d \"tup1\" MkTuple_p (Var_o \"1\"::Var_o \"2\"::nil))\n           (Let_e (Prim_d \"tup2\" MkTuple_p (Var_o \"3\"::Var_o \"4\"::nil))\n             (Let_e (Fn_d \"g\" (\"x\"::nil)\n                      (Let_e (Prim_d \"z\" Proj_p (Int_o 1::Var_o \"x\"::nil))\n                        (Halt_e (Var_o \"z\"))))\n               (Let_e (Fn_d \"f\" (\"x\"::nil)\n                        (App_e (Var_o \"g\") (Var_o \"tup2\"::nil)))\n                 (App_e (Var_o \"f\") (Var_o \"tup1\"::nil))))))))).\n(* env(x) should have both tuples,\n    and \"z\" should have two values, one from each tuple *)\nEval compute in inj e6.\n\n(* test multiple possible lambdas in app *)\nDefinition e7 :=\n  Let_e (Op_d \"1\" (Int_o 1))\n   (Let_e (Op_d \"2\" (Int_o 2))\n     (Let_e (Op_d \"3\" (Int_o 3))\n       (Let_e (Op_d \"4\" (Int_o 4))\n         (Let_e (Fn_d \"g1\" (\"x1\"::\"y1\"::nil)\n                  (Let_e (Prim_d \"z1\" Plus_p (Var_o \"x1\"::Var_o \"y1\"::nil))\n                    (Halt_e (Var_o \"z1\"))))\n           (Let_e (Fn_d \"g2\" (\"x2\"::\"y2\"::nil)\n                    (Let_e (Prim_d \"z2\" Plus_p (Var_o \"x2\"::Var_o \"y2\"::nil))\n                      (Halt_e (Var_o \"z2\"))))\n             (Let_e (Fn_d \"g3\" (\"x3\"::\"y3\"::nil)\n                      (Let_e (Prim_d \"z3\" Plus_p (Var_o \"x3\"::Var_o \"y3\"::nil))\n                        (Halt_e (Var_o \"z3\"))))\n               (Let_e (Fn_d \"f\" (\"g\"::\"x\"::\"y\"::nil)\n                        (App_e (Var_o \"g\") (Var_o \"x\"::Var_o \"y\"::nil)))\n                 (Switch_e (Var_o \"1\")\n                   ((Int_p 1,(App_e (Var_o \"f\") (Var_o \"g1\"::Var_o \"1\"::Var_o \"2\"::nil)))::\n                    (Int_p 2,(App_e (Var_o \"f\") (Var_o \"g2\"::Var_o \"3\"::Var_o \"4\"::nil)))::nil)\n                   (Some (App_e (Var_o \"f\") (Var_o \"g3\"::Var_o \"2\"::Var_o \"3\"::nil))))))))))).\n(* g should be bound to three lambdas, \n   all of x1-3, y1-3, z1-3 should be bound,\n   and x and y should be bound to three values each *)\nEval compute in inj e7.\n\n\n\n\nClose Scope string_scope.\n\nEnd AAMach.", "meta": {"author": "coq-ext-lib", "repo": "coq-compile", "sha": "8edfe71f4f91d5abf479bee50a3f1529b99acd4f", "save_path": "github-repos/coq/coq-ext-lib-coq-compile", "path": "github-repos/coq/coq-ext-lib-coq-compile/coq-compile-8edfe71f4f91d5abf479bee50a3f1529b99acd4f/src/coq/Analyze/AAMach.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6597337045584046}}
{"text": "From Coq Require Import\n  PArith.PArith Program.Wf.\nFrom DEZ Require Export\n  Init.\n\nFrom Coq Require Import Lia List Recdef.\nImport ListNotations Pos.\n\nLocal Open Scope positive_scope.\n\nDefinition seq (n p : positive) : list positive :=\n  map of_nat (seq (to_nat n) (to_nat p)).\n\n(** A deep dive into \"efficient pairing functions\".\n    Positive domain constraints make them even more horrifying. *)\n\n(** * Cantor (triangle shell) *)\n\nDefinition tri (n : positive) : positive :=\n  div2 (n * (1 + n)).\n\nDefinition tri_inverse_lb (n : positive) : positive :=\n  sqrt (2 * n) - 1.\n\nDefinition tri_inverse_ub (n : positive) : positive :=\n  sqrt (2 * n).\n\nDefinition tri_search (n p q : positive) : positive :=\n  if q <? tri p then n else p.\n\nDefinition tri_inverse (n : positive) : positive :=\n  tri_search (tri_inverse_lb n) (tri_inverse_ub n) n.\n\nDefinition c_unpair (n p : positive) : positive :=\n  div2 (3 + (n + p - 1) ^ 2 - n - p) + p - 1.\n  (* div2 (4 + (n + p) ^ 2 - 3 * (n + p)) + p - 1. *)\n\nDefinition c_pair (n : positive) : positive * positive :=\n  match peanoView n with\n  | PeanoOne => (1, 1)\n  | PeanoSucc p _ =>\n  let q := tri_inverse p in\n  let r := n - tri q in\n  (2 + q - r, r)\n  end.\n\n(* Compute map (prod_uncurry c_unpair o c_pair) (map of_nat (seq 1%nat 64%nat)). *)\n\n(** * Szudzik (square shell) *)\n\n\nDefinition s_unpair (n p : positive) : positive :=\n  if p <? n then\n  1 + n * n + p - 2 * n else\n  p * p + n + p - 2 * p.\n\nDefinition s_pair (n : positive) : positive * positive :=\n  match peanoView n with\n  | PeanoOne => (1, 1)\n  | PeanoSucc p _ =>\n    let q := sqrt p in\n    let r := q * q in\n    let s := 1 + q in\n    if n <? s + r then\n    (s, n - r) else\n    (n - r - q, s)\n  end.\n\n(** * Rosenberg--Strong (square shell) *)\n\nDefinition rs_unpair (n p : positive) : positive :=\n  let q := max n p in\n  (** We now know [n <= q] and [p <= q], so [n < 1 + q].\n      Therefore [1 + n < 1 + 1 + q], leading to\n      [1 < 1 + 1 + q - n] and thus [1 <= 1 + q - n].\n      Similarly [1 <= 1 + q - p].\n      This is probably useless information. *)\n  let r := q * q in\n  (** We now know [q <= r], so [q < 1 + r].\n      Therefore [1 + q < 1 + 1 + r], leading to\n      [1 < 1 + 1 + r - q] and thus [1 <= 1 + r - q].\n      This is the tightest we can cut it. *)\n  1 + r - q + p - n.\n\nDefinition rs_pair (n : positive) : positive * positive :=\n  match peanoView n with\n  | PeanoOne => (1, 1)\n  | PeanoSucc p _ =>\n    let q := sqrt p in\n    let r := q * q in\n    let s := 1 + q in\n    if n <? s + r then\n    (s, n - r) else\n    (2 * s + r - n, s)\n  end.\n\n(* Compute map (prod_uncurry rs_unpair o rs_pair)\n  (map of_nat (seq (S O) 64%nat)). *)\n", "meta": {"author": "Tuplanolla", "repo": "dez", "sha": "c2eadc2e032094c3504ec3803c000dba4feb547e", "save_path": "github-repos/coq/Tuplanolla-dez", "path": "github-repos/coq/Tuplanolla-dez/dez-c2eadc2e032094c3504ec3803c000dba4feb547e/fowl/Justifies/PositivePairingFunctions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.6597126948917341}}
{"text": "Require Import A1_Plan A2_Orientation A3_Metrique .\nRequire Import B5_BetweenProp B7_Tactics .\nRequire Import C1_Distance C3_SumDistance.\n\nSection DISTANCE_LE.\n\nDefinition DistanceLe := fun M N : Point => Segment Oo N M.\n\nLemma DistanceLeRefl : forall A : Point, DistanceLe A A.\nProof.\n\tunfold DistanceLe in |- *; intros.\n\timmediate1.\nQed.\n\nLemma DistanceLeOo : forall A : Point, DistanceLe Oo A.\nProof.\n\tunfold DistanceLe in |- *; intros.\n\timmediate1.\nQed.\n\nLemma SegmentDistanceLe : forall A B C : Point,\n\tSegment A B C ->\n\tDistanceLe (Distance A C) (Distance A B).\nProof.\n\tintros; unfold DistanceLe in |- *.\n\tapply (EquiDistantSegment A B C Oo (Distance A B) (Distance A C) Uu).\n\t trivial.\n\t apply EquiDistantSym; apply EquiDistantDistance.\n\t apply EquiDistantSym; apply EquiDistantDistance.\n\t immediate1.\n\t apply IsDistanceDistance.\n\t apply IsDistanceDistance.\nQed.\n\nLemma DistanceLeSegment : forall A B C D : Point,\n\tDistanceLe (Distance A C) (Distance A B) ->\n\tA <> D ->\n\tClosedRay A D B ->\n\tClosedRay A D C ->\n\tSegment A B C.\nProof.\n\tunfold DistanceLe in |- *; intros.\n\tapply (EquiDistantSegment Oo (Distance A B) (Distance A C) A B C D).\n\t trivial.\n\t apply EquiDistantDistance.\n\t apply EquiDistantDistance.\n\t trivial.\n\t trivial.\n\t trivial.\nQed.\n\nLemma DistanceLeTrans : forall A B C : Point,\n\tDistanceLe A B ->\n\tDistanceLe B C ->\n\tDistanceLe A C.\nProof.\n\tunfold DistanceLe in |- *; intros.\n\tapply (SegmentTransADB Oo A B C); trivial.\nQed.\n\nLemma DistanceLeDistancePlus : forall A B : Point,\n\tIsDistance A ->\n\tDistanceLe A (DistancePlus A B).\nProof.\n\tintros; unfold DistanceLe in |- *.\n\tpattern A at 2 in |- *; rewrite <- (IsDistanceEqDistance A H).\n\trewrite DistancePlusOoM; apply IsDistanceSegmentDistancePlus.\n\tapply IsDistanceDistance.\nQed.\n\nLemma DistanceLeDistancePlusDistance : forall A B C: Point,\n\tDistanceLe (Distance A B) (DistancePlus (Distance A B) C).\nProof.\n\tintros; apply DistanceLeDistancePlus.\n\tapply IsDistanceDistance.\nQed.\n\nLemma DistanceLeDistancePlusDistancePlus : forall A B C: Point,\n\tDistanceLe (DistancePlus A B) (DistancePlus (DistancePlus A B) C).\nProof.\n\tintros; apply DistanceLeDistancePlus.\n\tapply IsDistanceDistancePlus.\nQed.\n\nLemma LeftRegularDistanceLe : forall A B C : Point,\n\tDistanceLe A B ->\n\tDistanceLe (DistancePlus C A) (DistancePlus C B).\nProof.\n\tintros.\n\trewrite (DistancePlusOoN C B).\n\trewrite <- (Chasles Oo A B).\n\t rewrite DistancePlusAssoc.\n\t   rewrite <- (DistancePlusOoN C A).\n\t   apply DistanceLeDistancePlusDistancePlus.\n\t exact H.\nQed.\n\nEnd DISTANCE_LE.\n", "meta": {"author": "coq-contribs", "repo": "euclidean-geometry", "sha": "06838851a5924918d98e5a9c07ffa84021e13af7", "save_path": "github-repos/coq/coq-contribs-euclidean-geometry", "path": "github-repos/coq/coq-contribs-euclidean-geometry/euclidean-geometry-06838851a5924918d98e5a9c07ffa84021e13af7/C4_DistanceLe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6596925076701288}}
{"text": "Require Import Sorting.Permutation.\nRequire Import Lia.\nRequire Import List.\nExport ListNotations.\nRequire Import Arith Arith.EqNat.\nRequire Extraction.\n\nFixpoint is_sorted' (l : list nat) : bool :=\n  match l with\n  | []      => true\n  | a :: l' => \n      match l' with\n      | []       => true\n      | b :: l'' => leb a b && is_sorted' l'\n      end\n  end.\n\nInductive is_smallest : nat -> list nat -> Prop :=\n| smallest_unit : forall a, is_smallest a [a]\n| smallest_head : forall a b tl\n                         (LE  : a <= b)\n                         (SST : is_smallest b tl),\n    is_smallest a (a :: tl)\n| smallest_tail : forall a b tl\n                         (LT : a < b)\n                         (SST : is_smallest a tl),\n    is_smallest a (b :: tl)\n.\n\nInductive is_sorted : list nat -> Prop :=\n| sorted_nil   : is_sorted []\n| sorted_one a : is_sorted [a]\n| sorted_cons a tl\n              (SORTED : is_sorted tl)\n              (SST : is_smallest\n                       a (a :: tl))\n  :\n    is_sorted (a :: tl)\n.\n\nTheorem sort l :\n  { l' | Permutation l l' & is_sorted l' }.\nProof.\n  induction l.\n  { exists [].\n    { apply perm_nil. }\n    apply sorted_nil. }\n  inversion IHl.\n  rename x into l'.\n  rename H into PERM.\n  rename H0 into SORT.\nAbort.\n\nInductive is_inserted : nat -> list nat -> list nat -> Prop\n  :=\n| ins_head : forall n tl, is_inserted n tl (n :: tl)\n| ins_tail : forall n m tl tl'\n                    (INS : is_inserted n tl tl'),\n    is_inserted n (m :: tl) (m :: tl')\n.\n\nLemma is_inserted_perm a tl tl' \n  (INS : is_inserted a tl tl') :\n  Permutation (a :: tl) tl'.\nProof.\n  generalize dependent a.\n  generalize dependent tl'.\n  induction tl.\n  { intros.\n    inversion INS.  \n    apply Permutation_refl. }\n    (* Search Permutation. *)\n    (* apply perm_skip. *)\n    (* apply perm_nil. *)\n  intros.\n  inversion INS.\n  { apply Permutation_refl. }\n  apply IHtl in INS0.\n  (* apply perm_trans with (l' := (a :: a0 :: tl)). *)\n  eapply perm_trans.\n  { apply perm_swap. }\n  apply perm_skip. apply INS0.\nQed.\n\nLemma insert_sorted a l (SORT : is_sorted l) :\n  { l' | is_inserted a l l' & is_sorted l'}.\nProof.\n  induction l.\n  { exists [a]; constructor. }\n  edestruct IHl as [l'].\n  { clear -SORT. inversion SORT; subst.\n    { constructor. }\n    assumption. }\n  destruct (le_gt_dec a a0).\n  { exists (a::a0::l).\n    { constructor. }\n    apply sorted_cons; auto.\n    eapply smallest_head; eauto.\n    inversion SORT; subst.\n    { constructor. }\n    assumption. }\n\n  exists (a0::l').\n  { constructor. assumption. }\n  \n  clear -SORT i i0 g.\n  induction i. \n  { constructor; auto.\n    eapply smallest_head with (b:=n).\n    { lia. }\n    inversion i0; subst.\n    { constructor. }\n    assumption. }\n\n  constructor; auto.\n  apply smallest_head with (b:=m).\n  2: { inversion i0; subst.\n       { constructor. }\n       assumption. }\n  \n  clear -SORT.\n  inversion SORT; subst.\n  inversion SST; subst.\n  2: lia.\n  inversion SST0; subst.\n  { assumption. }\n  { assumption. }\n  lia.\nDefined.\n\nTheorem sort l :\n  { l' | Permutation l l' & is_sorted l' }.\nProof.\n  induction l.\n  { exists [].\n    { apply perm_nil. }\n    apply sorted_nil. }\n  inversion IHl.\n  rename x into l'.\n  rename H into PERM.\n  rename H0 into SORT.\n  apply (insert_sorted a l') in SORT.\n  destruct SORT as [l'' AA BB].\n  exists l''.\n  2: { apply BB. }\n  apply is_inserted_perm in AA.\n  eapply perm_trans.\n  2: apply AA.\n  apply perm_skip.\n  apply PERM.\nDefined.\n\nPrint sort.\n\nExtraction Language OCaml.\n\n\n\n\n\n", "meta": {"author": "semantics-classroom", "repo": "coq-intro-problems-dj-kostya", "sha": "f821eaf8b3b510ff7ab8ca78e1c7d430fbf6032f", "save_path": "github-repos/coq/semantics-classroom-coq-intro-problems-dj-kostya", "path": "github-repos/coq/semantics-classroom-coq-intro-problems-dj-kostya/coq-intro-problems-dj-kostya-f821eaf8b3b510ff7ab8ca78e1c7d430fbf6032f/src/sorts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6596924985901932}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\n\nFixpoint leb (n m : nat) : bool :=\n  match n with\n  | 0 => true\n  | S n' =>\n    match m with \n    | 0 => false\n    | S m' => leb n' m'\n    end\n  end.\n\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\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\n\nInductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\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\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\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n\nFixpoint app {X : Type} (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nInductive list' {X:Type} : Type :=\n  | nil'\n  | cons' (x : X) (l : list').\n\nDefinition mynil : list nat := nil.\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\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros X l. \n  induction l as [|n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros A l m n.\n  induction l as [|h t IHt].\n  - reflexivity.\n  - simpl. rewrite-> IHt. reflexivity.\nQed.\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros X l1 l2. \n  induction l1 as [|h1 t1 IHt1'].\n  - reflexivity.\n  - simpl. rewrite -> IHt1'. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros X l1 l2. \n  induction l1 as [|h1 t1 IHt1'].\n  - simpl. rewrite -> app_nil_r.  reflexivity.\n  - simpl. rewrite -> IHt1'. \n    rewrite <- app_assoc. reflexivity.\nQed. \n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros X l.\n  induction l as [|h t IHt].\n  - reflexivity.\n  - simpl. rewrite -> rev_app_distr.\n    rewrite -> IHt. reflexivity.\nQed.\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\n\nArguments pair {X} {Y} _ _.\n\nNotation \"( x , y )\" := (pair x y).\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\n Fixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\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    | (f, s) => (x :: f, y :: s)\n    end\n  end.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. reflexivity. Qed.\n\nModule OptionPlayground.\n\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\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 :: l' => if n =? O then Some a else nth_error l' (pred n)\n  end.\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n  | [] => None\n  | h :: t => Some h\n  end.\n\nCheck @hd_error.\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\nEnd OptionPlayground.\n  \n\nDefinition doit3times {X:Type} (f:X -> X) (n:X) : X :=\n  f (f (f n)).\n\nFixpoint filter {X:Type} (test: X -> bool) (l:list X)\n                : (list X) :=\n  match l with\n  | [] => []\n  | h :: t => if test h then h :: (filter test t)\n                        else filter test t\n  end.\n\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\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity. Qed.\n\nExample test_filter2':\n    filter (fun l => (length l) =? 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n => if evenb n then 7 <=? n else false) l.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity. Qed.\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\n\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\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\nTheorem map_app : forall (X Y : Type) (f : X -> Y) (l1 l2 : list X),\n  map f (l1 ++ l2) = (map f l1) ++ (map f l2).\nProof.\n  intros X Y f l1 l2.\n  induction l1 as [|h t IHl1].\n  - reflexivity.\n  - simpl. rewrite -> IHl1. reflexivity.\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros X Y f l.\n  induction l as [|h t IHt].\n  - reflexivity.\n  - simpl. rewrite <- IHt. \n    rewrite -> map_app.\n    reflexivity. \nQed.\n\nFixpoint flat_map {X Y: Type} (f: X -> list Y) (l: list X)\n                   : (list Y) :=\n  match l with\n  | nil => []\n  | h :: t => (f h) ++ (flat_map f t)\n  end. \n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\nProof. reflexivity. Qed.\n\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)\n                         : 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.\nDefinition ftrue := constfun true.\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros X l.\n  induction l as [|h t IHl].\n  - reflexivity.\n  - simpl. rewrite <- IHl. reflexivity.\nQed. \n\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y :=\n  fold (fun x l => (f x) :: l) l [].\n\nExample test_fold_map1:\n  fold_map (fun n => S n) [1;5;4]\n  = [2; 6; 5].\nProof. reflexivity. Qed.\n\nTheorem fold_map_correct : forall (X Y : Type)\n  (f: X -> Y) (l : list X), \n  fold_map f l = map f l.\nProof.\n  intros X Y f l.\n  induction l as [|h t IHl].\n  - reflexivity.\n  - simpl. rewrite <- IHl. reflexivity.\nQed.\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z :=\n  match p with\n  | (x, y) => f x y\n  end.\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  intros.\n  reflexivity.\nQed.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros.\n  destruct p as (x, y).\n  simpl. reflexivity.\nQed.\n  \nModule Church.\nDefinition cnat := forall X : Type, \n  (X -> X) -> X -> X.\n\nDefinition one : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\nDefinition two : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\nDefinition zero : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\nDefinition three : cnat := @doit3times.\n\nDefinition succ (n : cnat) : cnat := \n  fun (X : Type) (f : X -> X) (x : X) =>\n    f (n X f x).\n\nExample succ_1 : succ zero = one.\nProof. reflexivity. Qed.\nExample succ_2 : succ one = two.\nProof. reflexivity. Qed.\nExample succ_3 : succ two = three.\nProof. reflexivity. Qed.\n\nDefinition plus (n m : cnat) : cnat := \n  fun (X : Type) (f : X -> X) (x : X) =>\n    n X f (m X f x).\n\nExample plus_1 : plus zero one = one.\nProof. reflexivity. Qed.\nExample plus_2 : plus two three = plus three two.\nProof. reflexivity. Qed.\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. reflexivity. Qed.\n\nDefinition mult (n m : cnat) : cnat := \n  fun (X : Type) (f : X -> X) (x : X) =>\n    m X (n X f) x.\nExample mult_1 : mult one one = one.\nProof. reflexivity. Qed.\nExample mult_2 : mult zero (plus three three) = zero.\nProof. reflexivity. Qed.\nExample mult_3 : mult two three = plus three three.\nProof. reflexivity. Qed.\n\nDefinition exp (n m : cnat) : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) =>\n    (n ((X -> X)-> X -> X)\n      (fun y => \n        fun (f : X -> X) (x : X) => \n          m X (y f) x) (one X)) f x.\n\n(*\nExample exp_1 : exp two two = plus two two.\nProof. reflexivity. Qed.\nExample exp_2 : exp three zero = one.\nProof. reflexivity. Qed.\nExample exp_3 : exp three two = plus (mult two (mult two two)) one.\nProof. reflexivity. Qed.\n*)\n\nEnd Church.\n\nInductive id : Type :=\n  | Id (n : nat).\n\n(** Internally, an [id] is just a number.  Introducing a separate type\n    by wrapping each nat with the tag [Id] makes definitions more\n    readable and gives us the flexibility to change representations\n    later if we wish. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition eqb_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => n1 =? n2\n  end.\n\n\n", "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/Induction_structure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.6596924884575628}}
{"text": "Set Implicit Arguments.\n\n(* Import the core FCF definitions and theory. *)\nRequire Import otp.FCF.\n\n(* Matches our OTP definition in OTP_verif.v *)\nDefinition OTP_encrypt_FCF {SP : nat} (key msg : Bvector SP) : Bvector SP :=\n  BVxor SP key msg.  \n\n(* Indistinguishability security property *)\nDefinition rand_indist {SP : nat} (x : Comp (Bvector SP)) :=\n  forall (n : Bvector SP),\n    evalDist x n == evalDist ({0,1}^SP) n. \n\nLemma allow_assumption :\n  forall SP input (f : Bvector SP -> Bvector SP) n,\n    rand_indist (ret input) ->\n    evalDist (ret (f input)) n == evalDist (x <-$ {0,1}^SP; ret (f x)) n.\nProof.\n  intros.\n  unfold rand_indist in *.\n  rewrite <- evalDist_left_ident_eq with (c2 := fun x => ret f x).\n  eapply evalDist_seq_eq. intros. apply H.\n  intros. reflexivity.\nQed.\n\nLemma OTP_encrypt_indist :\n  forall SP (msg key : Bvector SP),\n    rand_indist (ret key) ->\n    rand_indist (ret (OTP_encrypt_FCF key msg)). \nProof. \n  intros.\n  unfold rand_indist.\n  intros.\n  unfold OTP_encrypt_FCF.\n  unfold rand_indist in *.\n  symmetry.\n  rewrite <- evalDist_right_ident.\n  symmetry.\n  erewrite allow_assumption with (f := fun x => BVxor SP x msg).\n\n  eapply evalDist_iso. \n  - intuition. \n  - instantiate (1:= BVxor SP msg). \n    instantiate (1:= BVxor SP msg). \n    intros. \n    rewrite <- BVxor_assoc. \n    rewrite BVxor_same_id. \n    rewrite BVxor_id_l. \n    reflexivity. \n  - intros. \n    rewrite <- BVxor_assoc. \n    rewrite BVxor_same_id. \n    rewrite BVxor_id_l. \n    reflexivity. \n  - intros. \n    simpl. \n    apply in_getAllBvectors. \n  - intros. \n    simpl. reflexivity. \n  - intros. \n    rewrite BVxor_comm.\n    rewrite <- BVxor_assoc.\n    rewrite BVxor_same_id. \n    rewrite BVxor_id_l. \n    reflexivity.\n  - exact H.\nQed.  \n\n\nDefinition OTP {SP : nat} (msg : Bvector SP) : Comp (Bvector SP) :=\n  key <-$ {0,1}^SP;\n  ret (OTP_encrypt_FCF key msg). \n\n(* Assuming the key is drawn uniformly at random (assumption added by OTP), \n OTP_encrypt is indistinguishable from random bits *)\nTheorem OTP_indist : forall SP (msg : Bvector SP),\n    rand_indist (OTP msg). \nProof. \n  intros. \n  unfold rand_indist.\n  intros.\n  unfold OTP.\n  unfold OTP_encrypt_FCF.\n\n  symmetry.    \n  rewrite <- evalDist_right_ident. \n  eapply evalDist_iso. \n  - intuition. \n  - instantiate (1:= BVxor SP msg). \n    instantiate (1:= BVxor SP msg). \n    intros. \n    rewrite <- BVxor_assoc. \n    rewrite BVxor_same_id. \n    rewrite BVxor_id_l. \n    reflexivity. \n  - intros. \n    rewrite <- BVxor_assoc. \n    rewrite BVxor_same_id. \n    rewrite BVxor_id_l. \n    reflexivity. \n  - intros. \n    simpl. \n    apply in_getAllBvectors. \n  - intros. \n    simpl. reflexivity. \n  - intros. \n    rewrite BVxor_comm. \n    reflexivity. \nQed. \n\n", "meta": {"author": "GaloisInc", "repo": "cryptol-semantics", "sha": "b4d8b55ec9b3b796427eb9e270e73e1857c597bf", "save_path": "github-repos/coq/GaloisInc-cryptol-semantics", "path": "github-repos/coq/GaloisInc-cryptol-semantics/cryptol-semantics-b4d8b55ec9b3b796427eb9e270e73e1857c597bf/otp/OTP_FCF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6596161940215941}}
{"text": "(*\n   Anarchy Proof\n   \n   Peirce\n   http://as305.dyndns.org/aps/problem/view/3\n\n\n   Converse Peirce\n   http://as305.dyndns.org/aps/problem/view/4\n\n\n   call/cc\n   http://as305.dyndns.org/aps/problem/view/5\n*)\n\n\nRequire Import Classical.                   (* 古典論理パッケージ *)\n\n\n(****************)\n(* Prove 'Peirce's law'. *)\n(* 「パースの論理式」を証明する。*)\n(* 古典論理では証明できるが、直観論理では証明できない。*)\n(* 「パースの論理式」を排中律で証明する。*)\n(****************)\n\n\nTheorem Peirce : forall (P Q: Prop), ((P -> Q) -> P) -> P.\nProof.\n  intros p q H.\n  Check classic.                            (* 排中律の公理 *)\n  (* Logic/Classical_Prop.v で定義されている。*)\n  elim (classic p).\n  intros P.\n  assumption.\n\n\n  intros H0.\n  apply H0 in H.\n  elim H.\n  intros H1.\n  (* H0 : ~P と H1 : P から Falseを求める *)\n  apply H0 in H1.\n  case H1.                                  (* 前提がFalseで証明は終了。 *)\nQed.\n\n\n(* 「パースの論理式」を二重否定除去で証明する。*)\n\n\nTheorem Peirce' : forall (P Q: Prop), ((P -> Q) -> P) -> P.\nProof.\n  intros p q H.\n  Check NNPP.                               (* 二重否定の除去 *)\n  apply NNPP.\n  intros nHp.\n  apply nHp in H.\n  apply H.\n  intros Hp.\n  case (nHp Hp).\nQed.\n\n\n(* Verifier *)\nDefinition check_Peirce: forall (P Q: Prop), ((P -> Q) -> P) -> P := Peirce.\n  \n(* Classical パッケージを使用しない。*)\n\n\n(****************)\n(* パースの論理式を使って、排中律を証明する。*)\n(****************)\n\n\n(* 古典論理で(Classicalパッケージを使う)、パースの論理式の証明は、\n   coq_classical.v を参照せよ。*)\n(* Axiom Peirce : forall (P Q: Prop), ((P -> Q) -> P) -> P. *)\n\n\nTheorem Excluded_Middle : forall (P: Prop), P \\/ ~P.\nProof.\n  intros p.\n  Check (Peirce p False).\n  apply (Peirce _ False).                   (* apply Peirce with False. *)\n  intros H.\n  right.\n  intros Hp.                                (* ~ p に対して、さらにintrosする！ *)\n  apply H.\n  left.\n  apply Hp.\nQed.\n\n\n(* Verifier *)\nDefinition check_Excluded_Middle : forall (P: Prop), P \\/ ~P := Excluded_Middle.\n\n\n(****************)\n(* Prove 'call/cc implies excluded middle'. *)\n(* call/cc を使って、排中律 (law of the excluded middle) を証明する。*)\n(****************)\n\n\nAxiom callcc: forall (P: Prop), ((P -> False) -> P) -> P.\n\n\nTheorem Excluded_Middle' : forall (P: Prop), P \\/ ~P.\nProof.\n  intros p.\n  apply callcc.                             (* パースの論理式の特別な形。 *)\n  (* パースの論理式による証明と同じだが、\n     auto で済ますこともできる。*)\n  auto.\nQed.\n\n\n(* Verifier *)\nDefinition check_Excluded_Middle' : forall (P: Prop), P \\/ ~P := Excluded_Middle'.\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_classical.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6596161917420273}}
{"text": "(****** Pointwise consistency for the central difference approximation of the 2nd derivative ********)\n\n\nRequire Import Reals Psatz.\nRequire Import Coquelicot.Hierarchy.\nRequire Import Coquelicot.Rbar.\nRequire Import Coquelicot.Coquelicot.\nRequire Import Omega Init.Nat Arith.EqNat.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Interval.Interval_missing.\nRequire Import Interval.coqapprox.taylor_thm.\n\n\n(*Defining a real valued function u(x)*)\nParameter u: R->R.\n\n(*Defining an operator for derivatives. The operator D takes a natural number for the order of derivative and a real , x (point at which the derivative\nis to be computed. The return type is real. *)\nVariable D:nat->R->R. \n\n(* Checking for continuity and differentiability of u at x*)\n\nDefinition continuity u := forall x:R, continuity_pt u x.\nDefinition derivable u := forall x:R, derivable_pt u x.\n\n\n(* [a b] is the interval in which the Taylor Lagrange is studied*)\nVariables l r :R.\n\n(* n is the order of derivative when the differentiability property is to verified and n is the order of continuity of u when its continuity property \nis considered *)\n\n\nVariable n:nat.\n\n(* Cab x means x lies in the closed interval [a b] *)\nNotation Cab x:= (l<=x<=r).\n(* Oab x means x lies in the open interval (a b) *)\nNotation Oab x:=(l<x<r).\n\n\n\n(* Define a hypothesis that \\frac {d^k (u}{d x^k} at x is \\frac{d^(k+1) (f)}{d x^(k+1)} in (a b)*)\nHypothesis derivable_pt_lim_Dp :\n  forall k x n, (k <= n)%nat -> Oab x ->\n  derivable_pt_lim (D k) x (D (S k) x).\n\n\n(*Define a hypothesis that f is C^(k) continuous in [a b]*)\nHypothesis continuity_pt_Dp :\n  forall k x n, (k <= n)%nat -> Cab x ->\n  continuity_pt (D k) x.\n\n\n(* Tcoeff is defined as \\frac {d^(n) (u)}{d x^n} *)\nNotation Tcoeff n x :=(D n x/(INR (fact n)) )(only parsing).\n\n(* Tterm is defined as Tcoeff * (x-x0)^n *)\nNotation Tterm n x0 x := (Tcoeff n x0 * ((x-x0)^n))(only parsing).\n\n(* Tsum is the truncated Taylor polynomial of degree n*)\nNotation Tsum n x0 x := (sum_f_R0 (fun i => Tterm i x0  x) n)(only parsing).\n\n\n(* instantiate Taylor_Lagrange for u(x+dx) with n=2*)\n(* Lemma statement: for x lies in (a b) , dx>0, (x+dx) in (a b), there exists a real c, such that u(x+dx)-u(x)-(du/dx)*(dx)- (1/2!)*(d^2 u / dx^2)*(dx^2)= (1/3!)*(d^3 u(c)/dx^3)*(dx^3)\n                    where c in (x x+dx) *)\n\n(* D 0 (x+dx) means u(x+dx)\n  S 2 means (2+1) or 3 , S is a successor operator in Peano arithemtic for natural numbers *)\n\n\nLemma Inst_nat_upper (x dx:R):\nOab x-> dx>0-> Oab (x+dx) -> exists c:R, D 0 (x+dx) - Tsum 3 x (x+dx) = Tcoeff (S 3) c * (x+dx-x)^(S 3) /\\ (x <> x+dx -> x < c < x+dx \\/ x+dx < c < x).\nProof.\nintros.\n(* Cor_Taylor_Lagrange is the Taylor Lagrange remainder theorem:\n\n  Cab x0 -> Cab x ->\n  exists c,\n  D 0 x - Tsum n x0 x =\n  Tcoeff (S n) c * (x - x0)^(S n)\n  /\\ (x0 <> x -> x0 < c < x \\/ x < c < x0).\n\nTheorem statement: \nfor x0 in [a b], x in [a b], there exists c in R, such that u(x)- u(x0)-(du(x0)/dx)*(dx)- .... - (1/n!)*(d^n u(x0)/ dx^n)*(dx^n)= (1/(n+1)!)*(d^(n+1) u(c)/dx^(n+1)\nwhere c in (x0 x) or (x x0).\n\nHere x0 is the point of expansion.\n\nThe theorem takes as argument, x (x+dx) and the order of expansion which in this case is 2. \n*)\napply (Cor_Taylor_Lagrange x (x+dx) 3).\nintros.\napply (derivable_pt_lim_Dp k x0 3). apply H2.  \nnra. nra. nra.\nQed.\n\n\n(* instantiate Taylor_Lagrange for u(x-dx) with n=3*)\nLemma Inst_nat_lower(x dx: R):\nOab x->dx>0-> Oab (x-dx) -> exists c:R, D 0 (x-dx) - Tsum 3 x (x-dx) = Tcoeff (S 3) c * (x-dx-x)^(S 3)/\\ (x <> x-dx -> x < c < x-dx \\/ x-dx < c < x). \nProof.\nintros.\napply (Cor_Taylor_Lagrange (x-dx) x 3).\nintros.\napply (derivable_pt_lim_Dp k x0 3). apply H2.  \nnra. nra. nra.\nQed.\n\n(* Proof of Taylor Lagrange for u(x+dx)*)\n(* Lemma statement:\n\nfor x in (a b),\nthere exists eta >0 in R, M>0 in R , such that forall dx in R, dx>0,\n(x+dx) in (a b) and dx < eta, \n\n| u(x+dx) - u(x)- (du/dx)*(dx)- (1/2!)*(d^2 u/ dx^2)*(dx^2)- (1/3!) * (d^3 u/dx^3)* (dx ^3)| <= M* (dx^4).\ni.e. The truncation error is big O (dx^4)\n\n*) \nLemma taylor_uupper (x:R):\nOab x-> exists eta: R, eta>0 /\\ exists M :R, M>0  /\\forall dx:R, dx>0 ->Oab (x+dx)->  (dx<eta ->  Rabs(D 0 (x+dx) - Tsum 3 x (x+dx)) <=M*(dx^4)).\nProof.\nintros.\n\n(* here we provide an evidence for eta, i.e. existential quantification for eta.\n\nHere i have chosen eta to be (b-x) . Reason for chosing so will be explained later *)\nexists (r-x).\n\n(* whenever there is an \"and\" operator in the goal, the \"split\" tactic splits the goal into two subgoals *)\nsplit.\n- nra. (* since x in (a b), b-x >0, nra does this mathematical reasoning to prove the subgoal *)\n- \n  (* We have to provide an evidence for M to continue the proof. We chose M to be max (d^4 u /dx) in the interval [x b] since\n    we are studying for u(x+dx) in (x b). \n    Thus, we use a lemma in COQ, which establishes the existence of a maximum in a compact interval for a continuous function. \n    Lemma statement: there exists a point F in R, F in [p1 p2] such that for all y in R , y in [p1 p2], f y <= f F.\n                     where f is a real valued function. The maximum is f F. \n    Thus, we use this lemma for d^4 u/dx^4 to get an evidence for M.\n  *)\n  cut( exists F:R , (forall y:R, x<=y<=x+(r-x) ->(D 4 y) <= (D 4 F)) /\\ x<=F<=x+(r-x)).\n  { intros.  destruct H0 as [F H0]. (* In a hypothesis, destruct breaks it into two sub hypothesis. Since this is an \n                                        existential hypotheis, an evidence F is provided. This introduces F in the environment\n                                        which will later be used. *)\n    (* here, we used a lemma in COQ, which establishes the existence of a minimum in a compact interval for a continuous function.\n      Lemma statement: there exists a point G in R, G in [p1 p2] such that for all y in R, y in [p1 p2], f G <= f y,\n                       where f is a real valued function. The minimum is f G.\n      Thus, we have introduced two lemmas so far to establish the existence of a maximum and a minimum in the interval [x b].\n      These bounds will later be used to prove that the lagrange remainder d^4 u(c)/dx^4 <= M.\n     *)\n    cut( exists G:R , (forall y:R, x<=y<=x+(r-x) ->(D 4 G) <= (D 4 y)) /\\ x<=G<=x+(r-x)).\n    - intros. destruct H1 as [G H1]. (* G (the point at which d^4 u/dx^4 attains a minimum value) is introduced into the environment*)  \n      \n      (* We instantiate M with maximum of |d^4 u(G)/dx^4| and |d^4 u(F)/dx^4| *)\n      exists (Rmax 1 (Rmax (Rabs( D 4 G/ INR (fact 4))) (Rabs(D 4 F/ INR (fact 4))))).\n      split. \n       + (* Rlt_le_trans: fforall r1 r2 r3, r1 < r2 -> r2 <= r3 -> r1 < r3. \n            This lemma is used to establish that M instantiated as before is greater than 0 *)\n\n        apply (Rlt_le_trans 0 1 (Rmax 1 (Rmax (Rabs( D 4 G/ INR (fact 4))) (Rabs(D 4 F/ INR (fact 4)))))).\n          * lra. (*apply Rlt_0_1.*)\n          * (*Rmax_l:  forall x y:R, x <= Rmax x y.*)\n            apply Rmax_l.\n       + intros. (*introduces dx and its properties into the environment*) \n      cut(Oab x-> dx>0-> Oab (x+dx) -> exists c:R, D 0 (x+dx) - Tsum 3 x (x+dx) = Tcoeff (S 3) c * (x+dx-x)^(S 3)/\\ (x <> x+dx -> x < c < x+dx \\/ x+dx < c < x)).\n      (* We introduce the lemma defined earlier, Inst_nat_upper into the proof context. The idea is to get information on \"c\" which\n         to be used in taylor lagrange for u(x+dx) and instantiate the order of truncation as well *)\n      { intros.\n        specialize (H5 H H2 H3).\n        destruct H5 as [c H5]. (* destruct introduces c in the environment *)\n        destruct H5 as [H5 H6]. (* destruct breaks the hypothesis H5 into two separate hypothesis which were connected by the \"and\" operator*)\n        destruct H0 as [H0 H7]. specialize (H0 c). (* instantiate y with c *)\n        assert (H8: x<=c<=x+(r-x)). {  nra. }  (* assert: This tactic introduces new hypothesis in the context. \n        Purpose of doing so is to break the hypotheis H0, which is done using \"specialize\" tactic in the next step.\n        Since this hypotheis is a reasoning on interval, \"nra\" is used to prove it *)\n        specialize (H0 H8). \n        destruct H1 as [H1 H9]. specialize (H1 c). specialize (H1 H8). (* Similarly, we break the hypothesis H1*)\n        (* Now we have the information that (d^4 u(c)/dx^4) is bounded below by (d^4 u(G)/dx^4) and bounded above by \n           (d^4 u(F)/dx^4). This information will be used later to prove that |d^4 u(c)/dx^4| <= M *)\n        \n        (* Now we are in a position to prove the lemma for taylor_lagrange of u(x+dx) *)\n        (* Here, we write the truncated taylor series in terms of lagrange remainder. \n          This will lead us to prove that |(d^4 u(c)/dx^4)* (dx^4)| <= M * (dx^4) i.e. the lagrange remainder is big O (dx^4) *)        \n        cut ( D 0 (x+dx) - Tsum 3 x (x+dx) =  Tcoeff (S 3) c * ((x+dx) -x)^(S 3)).\n        * intros. rewrite H10. \n          cut( (x+dx)-x = dx). intros. rewrite H11. \n          cut (Rabs (D 4 c / INR (fact 4) * dx ^ 4) = Rabs (D 4 c / INR (fact 4)) * dx ^ 4).\n          - intros. rewrite H12.\n            (*Lemma Rmult_le_compat_r :forall r r1 r2, 0 <= r -> r1 <= r2 -> r1 * r <= r2 * r.\n              Purpose of introducing this lemma is to get rid of dx^4 on both sides. This is equivalent to dividing dx^4 on both sides\n              since dx >0 (hypothesis H2)*)\n            apply Rmult_le_compat_r. (* Applying this tactic introduces the premise that dx^3>=0 *)\n            apply Rlt_le. (*Lemma Rlt_le : forall r1 r2, r1 < r2 -> r1 <= r2. \n            Purpose of doing this is to reduce the goal to dx^3>0 which can be proved by applying the hypotheis H2: dx>0*)\n             apply pow_lt. apply H2.\n          \n          -  (* Start of proof that |d^u(c)/dx^3| <= M *)\n             apply Rle_trans with  (Rmax (Rabs (D 4 G / INR (fact 4))) (Rabs (D 4 F / INR (fact 4)))). \n             apply RmaxAbs.\n             (*Lemma RmaxAbs :\n                forall (p q:R) r, p <= q -> q <= r -> Rabs q <= Rmax (Rabs p) (Rabs r).\n                \n              Purpose of using this lemma is to reduce the goal into following 2 subgoals:\n              D 4 G / INR (fact 4) <= D 4 c / INR (fact 4)\n              ______________________________________(2/6)\n              D 4 c / INR (fact 4) <= D 4 F / INR (fact 4)\n\n              This reduction will further help in application of the hypothesis H0 and H1 (these hypothesis gives information on the\n              bounds for the lagrange remainder *)\n\n             cut(D 4 G / INR (fact 4)= (D 4 G)*(/ INR (fact 4))).\n             (* Here, we follow the process for reduction of \n                D 4 G / INR (fact 4) <= D 4 c / INR (fact 4) to D 4 G <= D 4 c.\n                In the following steps,we perform a relatively long process for a basic operation of eliminating 1/4! on boh sides *)\n             { intros.  rewrite H13. \n               cut(D 4 c / INR (fact 4)= (D 4 c)*(/ INR (fact 4))).\n               + intros. rewrite H14. apply Rmult_le_compat_r. apply Rlt_le. \n                 apply Rinv_0_lt_compat. (*Lemma Rinv_0_lt_compat : forall r, 0 < r -> 0 < / r. *)\n                 apply lt_0_INR. (*Lemma lt_0_INR : forall n:nat, (0 < n)%nat -> 0 < INR n.*)\n                 simpl. (*simpl: This tactic performs mathematical simplification, i.e. it simplifies 4! to 24. *)\n                 omega. (*The tactic omega, due to Pierre Crégut, is an automatic decision procedure for Presburger arithmetic.\n                 It solves quantifier-free formulas built with ~, /, /`, `-> on top of equalities, inequalities and disequalities \n                 on both the type nat of natural numbers and Z of binary integers. *)\n                 apply H1.\n               + trivial.\n              }\n              { trivial. }\n             (* Similarly, we carry the same process for reducing  D 4 c / INR (fact 4) <= D 4 F / INR (fact 4) to D 4 c <= D 4 F and proving it*)\n             cut(D 4 c / INR (fact 4) = (D 4 c)*(/ INR(fact 4))).\n             { intros. rewrite H13.\n               cut(D 4 F / INR(fact 4)= (D 4 F)*(/INR (fact 4))).\n               + intros. rewrite H14. apply Rmult_le_compat_r. apply Rlt_le. apply Rinv_0_lt_compat. apply lt_0_INR.  simpl. omega. apply H0.\n               + trivial.\n            } \n            { trivial. }\n            apply Rmax_r. (*Lemma Rmax_r : forall x y:R, y <= Rmax x y.*)\n             \n        * rewrite Rabs_mult. (*Lemma Rabs_mult : forall x y:R, Rabs (x * y) = Rabs x * Rabs y.*)\n          cut (dx^4 = (Rabs (dx^4))).  \n          { intros. rewrite <- H12. reflexivity. (* reflexivity is used to prove goals of type A=B *) }\n          { cut (Rabs(dx ^ 4) = dx ^ 4).\n            - intros. rewrite H12. reflexivity. \n            - apply Rabs_right. (*Lemma Rabs_right : forall r, r >= 0 -> Rabs r = r. This is applicable since dx>0*)\n              apply Rgt_ge. (*Lemma Rgt_ge : forall r1 r2, r1 > r2 -> r1 >= r2.\n              Purpose is to reduce the goal, dx^4>=0 to dx^4>0 so that we can apply H2.*)\n              apply pow_lt. apply H2. \n         } \n      + lra. apply H5.\n    }\n    { apply (Inst_nat_upper x dx). } (* Here we apply the lemma Inst_nat_upper since the goal statement matche with the lemma statement*)\n  - (* Here we apply the lemma on the lower bound for the 3rd derivative in the interval [x b], and prove the non-dependent premises*)\n    apply (continuity_ab_min (D 4) x (x+(r-x))). nra. intros. apply (continuity_pt_Dp 4 c 4). omega. nra.\n  }\n  {\n   (* Here we apply the lemma on the upper bound for the 4th derivative in the interval [x b], and prove the non-dependent premises*)\n  apply (continuity_ab_maj (D 4) x (x+(r-x))). nra. intros. apply (continuity_pt_Dp 4 c 4). omega. nra.\n  } \nQed. (* The lemma on the taylor lagrange for u(x+dx) is proved and defined*)\n   \n\n(*Proof of Taylor Lagrange for u(x-dx)*)\nLemma taylor_ulower (x:R):\nOab x -> exists delta: R, delta>0 /\\ exists K :R, K>0 /\\ forall dx:R, dx>0 ->Oab (x-dx)-> (dx<delta -> Rabs(D 0 (x-dx) - Tsum 3 x (x-dx)) <=K*(dx^4)).\nProof.\n(* instantiate eta with (x-a)*)\nexists (x-l).\nsplit.\n- nra.\n- (* Introduce lemma to establish maximum of (d^4 u(y)/dx^4) in the interval [a x].*)\n  cut( exists F:R , (forall y:R, x-(x-l)<=y<=x ->(D 4 y) <= (D 4 F)) /\\ x-(x-l)<=F<=x).\n  { intros. destruct H0 as [F H0]. (* destruct introduces F in the environment *)\n    (* Introduce lemma to establish minimum of (d^4 u(y)/dx^4) in the inteval [a x]*)\n    cut( exists G:R , (forall y:R, x-(x-l)<=y<=x ->(D 4 G) <= (D 4 y)) /\\ x-(x-l)<=G<=x).\n    - intros. destruct H1 as [G H1]. (*destruct introduces G in the environment *)\n\n      (*instantiate K*) \n      exists (Rmax 1 (Rmax (Rabs( D 4 G/ INR (fact 4))) (Rabs(D 4 F/ INR (fact 4))))).\n      split.\n      + apply (Rlt_le_trans 0 1 (Rmax 1 (Rmax (Rabs( D 4 G/ INR (fact 4))) (Rabs(D 4 F/ INR (fact 4)))))).\n          * lra. (*apply Rlt_0_1.*)\n          *  apply Rmax_l.\n      + intros.\n        (* Introduce the lemma Inst_nat_lower to extract information about \"c\" and also to instantiate the order of approximation \n        in taylor lagrange for u(x-dx) to 2*)\n        cut(Oab x-> dx>0-> Oab (x-dx) -> exists c:R, D 0 (x-dx) - Tsum 3 x (x-dx) = Tcoeff (S 3) c * (x-dx-x)^(S 3)/\\ (x <> x-dx -> x < c < x-dx \\/ x-dx < c < x)).\n        { intros. specialize (H5 H H2 H3). (*break the hypothesis by using the information about dx already present in the environment\n                                            in form of hypothesis *)\n          destruct H5 as [c H5]. (* introduce \"c\" in the environment*)\n          destruct H5 as [H5 H6]. (* Break the hypothesis into separate hypothesis connected by the \"and\" operator *)\n          destruct H0 as [H0 H7]. specialize (H0 c). \n          assert (H8: x-(x-l)<=c<=x). {  nra. } (* Introduce a new hypothesis establishing that c lies in [a x]*)\n          specialize (H0 H8). (* reduce hypothesis H0 into inequality D 4 c <= D 4 F *)\n          destruct H1 as [H1 H9]. specialize (H1 c). specialize (H1 H8). (* reduce hypothesis H1 into inequality D 4 G<= D 4 c*)\n        (* Now we have the information that (d^4 u(c)/dx^4) is bounded below by (d^4 u(G)/dx^4) and bounded above by \n           (d^4 u(F)/dx^4). This information will be used later to prove that |d^4 u(c)/dx^4| <= M *)\n        \n        (* Now we are in a position to prove the lemma for taylor_lagrange of u(x-dx) *)\n        (* Here, we write the truncated taylor series in terms of lagrange remainder. \n          This will lead us to prove that |(d^4 u(c)/dx^4)* (dx^3)| <= K * (dx^4) i.e. the lagrange remainder is big O (dx^4) *) \n          cut ( D 0 (x-dx) - Tsum 3 x (x-dx) =  Tcoeff (S 3) c * ((x-dx) - x)^(S 3)).\n          { intros. rewrite H10. \n            cut((x-dx)-x = -dx). \n            + intros. rewrite H11. \n              cut (Rabs (D 4 c / INR (fact 4) * (- dx) ^ 4)= (Rabs ( D 4 c / INR (fact 4))) * dx ^ 4).\n              - intros. rewrite  H12.\n                apply  Rmult_le_compat_r. \n                apply Rlt_le. apply pow_lt. apply H2. \n                   \n             (* Start of proof that |d^4u(c)/dx^4| <= K *)\n                   apply Rle_trans with  (Rmax (Rabs (D 4 G / INR (fact 4))) (Rabs (D 4 F / INR (fact 4)))).\n                   apply RmaxAbs.\n                  (*Lemma RmaxAbs :\n                    forall (p q:R) r, p <= q -> q <= r -> Rabs q <= Rmax (Rabs p) (Rabs r).\n                    \n                  Purpose of using this lemma is to reduce the goal into following 2 subgoals:\n                  D 4 G / INR (fact 4) <= D 4 c / INR (fact 4)\n                  ______________________________________(2/6)\n                  D 4 c / INR (fact 4) <= D 4 F / INR (fact 4)\n\n                  This reduction will further help in application of the hypothesis H0 and H1 (these hypothesis gives information \n                  on the bounds for the lagrange remainder *)\n\n                   cut(D 4 G / INR (fact 4)= (D 4 G)*(/ INR (fact 4))).\n                (* Here, we follow the process for reduction of \n                D 4 G / INR (fact 4) <= D 4 c / INR (fact 4) to D 4 G <= D 4 c.\n                In the following steps,we perform a relatively long process for a basic operation of eliminating 1/4! on boh sides *)\n                    { intros.  rewrite H13. \n                     cut(D 4 c / INR (fact 4)= (D 4 c)*(/ INR (fact 4))).\n                     + intros. rewrite H14. apply Rmult_le_compat_r. apply Rlt_le. apply Rinv_0_lt_compat. apply lt_0_INR. simpl. omega. apply H1.\n                     + trivial.\n                    }\n                    { trivial. }\n                    (* Similarly, we carry the same process for reducing  D 4 c / INR (fact 4) <= D 4 F / INR (fact 4) to D 4 c <= D 4 F and proving it*)\n                   cut(D 4 c / INR (fact 4) = (D 4 c)*(/ INR(fact 4))).\n                   { intros. rewrite H13.\n                     cut(D 4 F / INR(fact 4)= (D 4 F)*(/INR (fact 4))).\n                     + intros. rewrite H14. apply Rmult_le_compat_r. apply Rlt_le. apply Rinv_0_lt_compat. apply lt_0_INR.  simpl. omega. apply H0.\n                     + trivial.\n                   } \n                   { trivial. }\n                  apply Rmax_r.\n                 - assert ( (-dx)^4= dx ^4).\n                   assert ( -dx = -1 * dx). { nra. }\n                   rewrite H12. assert (dx ^4= (-1)^4 * (dx^4)). { nra. } rewrite H13. apply Rpow_mult_distr.\n                   rewrite H12.  assert (Rabs (D 4 c / INR (fact 4) * dx ^ 4)= Rabs (D 4 c / INR (fact 4))* Rabs(dx^4)). { apply Rabs_mult. }\n                   rewrite H13. apply Rmult_eq_compat_l. apply Rabs_right. nra. \n                + nra.\n              }\n            apply H5.\n         }\n         { apply (Inst_nat_lower x dx). } (* Here we apply the lemma Inst_nat_lower since the goal statement matches with the lemma statement *)\n      - (* Here we apply the lemma on the lower bound for the 4th derivative in the interval [a x], and prove the non-dependent premises*)\n        apply (continuity_ab_min (D 4) (x-(x-l)) x). nra. intros. apply (continuity_pt_Dp 4 c 4). omega. nra.\n    }\n    { (* Here we apply the lemma on the upper bound for the 4th derivative in the interval [a x], and prove the non-dependent premises*) \n      apply (continuity_ab_maj (D 4) (x-(x-l)) x). nra. intros. apply (continuity_pt_Dp 4 c 4). omega. nra. }         \n   \nQed. (* Lemma on taylor_lagrange for u(x-dx) is proved and defined*)\n\n(*Proof for 2nd order FD scheme, | (u(x+dx) -2* u(x) +u(x-dx))/(dx^2) - (d^2u/dx^2)| <= G*(dx^2)\n  The strategy here is to rewrite the scheme into taylor lagrange for u(x+dx) and u(x-dx) and use the already\n  proven lemmas to complete the proof *)\n\n\n(* Theorem statement:\n    for x in (a b), there exists gamma>0 in R and G >0 in R, such that forall dx >0 in R and dx<gamma, \n   | (u(x+dx) -2* u(x) +u(x-dx))/(dx^2) - (d^2u/dx^2)| <= G*(dx^2), i.e. the scheme is 2nd order accurate *)\n\nTheorem taylor_FD (x:R):\nOab x -> exists gamma:R, gamma >0 /\\ exists G:R, G>0/\\ forall dx:R, dx>0 -> Oab (x+dx) -> Oab (x-dx)->(dx< gamma -> Rabs( (D 0 (x+dx) - 2* (D 0 x) +D 0 (x-dx)) * / (dx * dx) - D 2 x)<= G*(dx^2)).\nProof.\nintros.\n\n(* We would like to instantiate gamma with min (eta, delta) and G with (M+K), but so far,we have no information \non M and K in the environment, thus we introduce the lemmas  on taylor lagrange for u(x+dx) and u(x-dx) and \nextract the informations on eta, delta, M and K *)\n\n(* Lemma on taylor lagrange for u(x+dx)*)\ncut(Oab x->  exists eta: R, eta>0 /\\ exists M :R, M>0 /\\forall dx:R, dx>0 ->Oab (x+dx)->(dx<eta -> Rabs(D 0 (x+dx) - Tsum 3 x (x+dx)) <=M*(dx^4))).\n- intros. destruct H0 as [eta H1]. (*destruct introduces eta in the environment *)\n  apply H. (* proves x in (a b)*) \n  destruct H1 as [H2 H3]. (* Breaks the hypothesis H3 into separate hypothesis connected by the \"and\" operator*)\n  (* Lemma on taylor lagrange for u(x-dx)*)  \n  cut(Oab x ->  exists delta: R, delta>0 /\\exists K :R, K>0 /\\ forall dx:R, dx>0 ->Oab (x-dx)-> (dx<delta -> Rabs(D 0 (x-dx) - Tsum 3 x (x-dx)) <=K*(dx^4))).\n  + intros. destruct H0 as [delta H4]. (* destruct introduces delta in the environment *)\n    apply H. destruct H4 as [H5 H6].\n    exists (Rmin eta delta).\n    split.\n    { (* Proof for min(eta, delta) >0 *) \n     apply Rmin_pos. (*Lemma Rmin_pos : forall x y:R, 0 < x -> 0 < y -> 0 < Rmin x y.\n     Applying this lemma, produces two subgoals, eta>0, delta>0, since we already have these information in the\n     environment in form of hypothesis H2 and H5 , we just apply them in the following steps. *)\n     apply H2. apply H5. }\n    \n     (* we now have to instantiate G , hence we revisit the lemmas on taylor lagrange for u(x+dx) and u(x-dx) \n    which are already present in the environment as hypothesis H3 and H4 respectively *)\n    { destruct H3 as [M H4]. (* introduces M in the environment *)\n      destruct H4 as [H7 H8]. destruct H6 as [K H6]. (* destruct introduces K in the environment*)\n      destruct H6 as [H9 H10].\n      exists (M+K). (* Since we now have information about M and K , we can instantiate G with (M+K) *)\n      split.\n      * nra. (* in the environment, we already have M>0, K>0 , hence nra uses these facts to prove (M+K)>0 *)\n      * intros. (* introduces information on \"dx\" in the environment*)\n        (* We introduce additional hypothesis dx<eta and dx< delta, these will be used to break the lemmas on \n          u(x+dx) and u(x-dx) further . We will prove these hypothesis later *)\n       cut(dx<eta). \n       + cut(dx< delta).\n         - intros. specialize(H8 dx H0 H1 H11). (* Use the information on dx to further break the hypothesis \n          and get the desired form of taylor lagrange for (u(x+dx)) after getting rid of the quantifiers *)\n          specialize( H10 dx H0 H3 H6). \n          (* Use the information on dx to further break the hypothesis \n          and get the desired form of taylor lagrange for (u(x-dx)) after getting rid of the quantifiers *)\n\n          (* Next , we will decompose the scheme into the lemmas on taylor lagrange for u(x+dx) and u(x-dx) and apply those lemmas separately\n            to complete the proof *)\n          apply Rmult_le_reg_r with (dx^2).\n          * nra.\n          * assert((M + K) * dx ^ 2 * dx ^ 2= (M+K) * (dx ^4)). { nra. }\n            rewrite H12. \n            cut( Rabs(dx^2)= dx^2).\n            { intros. rewrite <- H13.\n              assert (Rabs (((D 0 (x + dx) - 2 * D 0 x + D 0 (x - dx)) * / (dx * dx) - D 2 x) * (dx ^2))=\n                         Rabs ((D 0 (x + dx) - 2 * D 0 x + D 0 (x - dx)) * / (dx * dx) - D 2 x) * Rabs (dx ^ 2)).\n              { apply Rabs_mult. }\n              rewrite <- H14.\n              assert(((D 0 (x + dx) - 2 * D 0 x + D 0 (x - dx)) * / (dx * dx) - D 2 x) * dx ^ 2=\n                      ((D 0 (x + dx) - 2 * D 0 x + D 0 (x - dx)) - (D 2 x) * (dx^2))).\n              { assert ( dx*dx = dx^2). { nra. } rewrite H15. \n                assert (((D 0 (x + dx) - 2 * D 0 x + D 0 (x - dx)) * / dx ^ 2 - D 2 x) * dx ^ 2=\n                        ((D 0 (x + dx) - 2 * D 0 x + D 0 (x - dx)) * / dx ^ 2) * (dx ^2) -D 2 x * dx ^ 2). { nra. }\n                rewrite H16. \n                assert ((D 0 (x + dx) - 2 * D 0 x + D 0 (x - dx)) * / dx ^ 2 * dx ^ 2= (D 0 (x + dx) - 2 * D 0 x + D 0 (x - dx))).\n                { assert(((D 0 (x + dx) - 2 * D 0 x + D 0 (x - dx)) * / dx ^ 2 )* dx ^ 2 = (D 0 (x + dx) - 2 * D 0 x + D 0 (x - dx)) * (dx^2) */ (dx^2)). { nra. }\n                  rewrite H17. apply Rinv_r_simpl_l. nra.\n                }\n                rewrite H17. reflexivity.\n              }\n              rewrite H15.\n              assert (( D 2 x) * (dx^2)= ((D 2 x)/(INR (fact 2)))*(dx ^2) +  ((D 2 x)/(INR (fact 2)))*(dx ^2)). \n              { assert (INR (fact 2) = 2). { assert ( fact 2= 2%nat). { unfold fact. omega. } rewrite H16. trivial. }\n                rewrite H16. nra.\n              }\n              rewrite H16. \n              assert ( (D 0 (x + dx) - 2 * D 0 x + D 0 (x - dx) - (D 2 x / INR (fact 2) * dx ^ 2 + D 2 x / INR (fact 2) * dx ^ 2))=\n                        (D 0 (x+dx) - (D 0 x + D 1 x * dx + D 2 x / INR (fact 2) * dx ^ 2 + (D 3 x / INR (fact 3)) * dx ^3)) + ( D 0 (x-dx) - (D 0 x - D 1 x * dx + D 2 x / INR (fact 2) * dx ^ 2- (D 3 x/ INR (fact 3))* (dx ^3)))). { nra. }\n              rewrite H17. \n              cut( (D 0 x + D 1 x * dx + D 2 x / INR (fact 2) * dx ^ 2 + (D 3 x/ INR (fact 3))* (dx ^3))= Tsum 3 x (x+dx)).\n              + intros. rewrite H18. \n                cut((D 0 x - D 1 x * dx + D 2 x / INR (fact 2) * dx ^ 2 - D 3 x / INR (fact 3) * dx ^ 3)= Tsum 3 x (x-dx)).\n                - intros. rewrite H19.\n                  apply Rle_trans with (Rabs(D 0 (x + dx) - sum_f_R0 (fun i : nat => D i x / INR (fact i) * (x + dx - x) ^ i) 3)+\n                                        Rabs ((D 0 (x - dx) - sum_f_R0 (fun i : nat => D i x / INR (fact i) * (x - dx - x) ^ i) 3))).\n                  * apply Rabs_triang.\n                  * assert ((M + K) * dx ^ 4= M * (dx ^4) + K * (dx ^4)). { nra. }\n                    rewrite H20. apply Rplus_le_compat. \n                    apply H8. \n                    apply H10.\n                - unfold sum_f_R0. assert (x-dx-x= -dx). { nra. } rewrite H19.\n                  assert (fact 0 =1%nat). { simpl. reflexivity. } rewrite H20.\n                  assert (fact 1= 1%nat). { simpl. reflexivity. } rewrite H21. \n                  assert (INR 1= 1). { reflexivity. } rewrite H22. \n                  assert (D 0 x / 1 * (- dx) ^ 0= D 0 x). { nra. } rewrite H23.\n                  assert ( D 1 x / 1 * (- dx) ^ 1 = - D 1 x * dx). { nra. } rewrite H24.\n                  assert (D 3 x / INR (fact 3) * (- dx) ^ 3= - D 3 x / INR (fact 3) * dx ^ 3).  { nra. } rewrite H25.\n                  assert ( (-dx)^2 = dx ^2). { nra. } rewrite H26. nra. \n              + unfold sum_f_R0. assert (x+dx -x = dx). { nra. } rewrite H18. \n                assert (fact 0 =1%nat). { simpl. reflexivity. } rewrite H19.\n                assert (fact 1= 1%nat). { simpl. reflexivity. } rewrite H20. \n                assert (D 0 x / INR 1 * dx ^ 0 = D 0 x). { assert (dx^0=1). { nra. } rewrite H21. assert (INR 1=1). { reflexivity. } rewrite H22. nra. }\n                rewrite H21.\n                assert (D 1 x / INR 1 * dx ^ 1 = D 1 x * dx). { assert (INR 1 =1). { reflexivity. } rewrite H22. nra. }\n                rewrite H22. reflexivity.\n              }\n              { apply Rabs_right. nra. }\n           -  (* Proof for dx< delta*)\n               apply (Rmin_Rgt eta) in H4. destruct H4 as [H11 H12]. (*We have dx < Rmin eta delta as our hypothesis H4. \n                Rmin_Rgt tactic breaks H4 into dx < eta and dx < delta. we will use the later in this proof*)\n               apply H12.\n        + (*Proof for dx < eta*)\n           apply (Rmin_Rgt eta) in H4. (*Lemma Rmin_Rgt : forall r1 r2 r, Rmin r1 r2 > r <-> r1 > r /\\ r2 > r.\n           We have dx < Rmin eta delta as our hypothesis H4. Rmin_Rgt tactic breaks H4 into dx < eta and dx < delta. we will use the former in this proof*)\n           destruct H4 as [H11 H12]. (* breaks the modified hypothesis H4 into two separate hypotheis dx<eta and dx<delta so that these can be ready to \n           be applied *) \n           apply H11.\n      }\n   + apply (taylor_ulower x). \n- apply (taylor_uupper x).\nQed.\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/pointwise_consistency.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6596161790503233}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_collinear5.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_NChelper : \n   forall A B C P Q, \n   nCol A B C -> Col A B P -> Col A B Q -> neq P Q ->\n   nCol P Q C.\nProof.\nintros.\nassert (~ eq A B).\n {\n intro.\n assert (Col A B C) by (conclude_def Col ).\n contradict.\n }\nassert (Col B P Q) by (conclude lemma_collinear4).\nassert (neq B A) by (conclude lemma_inequalitysymmetric).\nassert (Col B A P) by (forward_using lemma_collinearorder).\nassert (Col B A Q) by (forward_using lemma_collinearorder).\nassert (Col A P Q) by (conclude lemma_collinear4).\nassert (Col P Q A) by (forward_using lemma_collinearorder).\nassert (Col P Q B) by (forward_using lemma_collinearorder).\nassert (~ Col P Q C).\n {\n intro.\n assert (Col A B C) by (conclude lemma_collinear5).\n contradict.\n }\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_NChelper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6596161744911901}}
{"text": "Require Import Ascii String Zdiv.\n\nOpen Scope string.\n\nInductive format :=\n| fmt_int : format -> format\n| fmt_string : format -> format\n| fmt_other : ascii -> format -> format\n| fmt_end : format.\n\nFixpoint format_str s :=\n  match s with\n  | String \"%\" (String \"d\" s') => fmt_int (format_str s')\n  | String \"%\" (String \"s\" s') => fmt_string (format_str s')\n  | String c s' => fmt_other c (format_str s')\n  | EmptyString => fmt_end\n  end.\n\nFixpoint gen_format_type f :=\n  match f with\n  | fmt_int f' => Z -> gen_format_type f'\n  | fmt_string f' => string -> gen_format_type f'\n  | fmt_other _ f' => gen_format_type f'\n  | fmt_end => string\n  end.\n\n(* I can't find a nicer way to convert Z -> string :( *)\nDefinition digit_to_string n : string :=\n  match n with\n  | 0%Z => \"0\"\n  | 1%Z => \"1\"\n  | 2%Z => \"2\"\n  | 3%Z => \"3\"\n  | 4%Z => \"4\"\n  | 5%Z => \"5\"\n  | 6%Z => \"6\"\n  | 7%Z => \"7\"\n  | 8%Z => \"8\"\n  | 9%Z => \"9\"\n  | _ => \"\"\n  end.\n\nFixpoint z_to_string' n z acc : string :=\n  match n with\n  | 0 => acc\n  | S n' =>\n    let acc' := digit_to_string (Zmod z 10) ++ acc\n    in match (Zdiv z 10) with\n       | Z0 => acc'\n       | z' => z_to_string' n' z' acc'\n       end\n  end.\n\nDefinition z_to_string z :=\n  if Z.geb z 0\n  then z_to_string' (Z.to_nat z) z \"\"\n  else let z' := Zabs z\n       in \"-\" ++ z_to_string' (Z.to_nat z') z' \"\".\n(* end of laborious Z -> string stuff *)\n\nFixpoint to_fn f s : gen_format_type f :=\n  match f with\n  | fmt_int f' => fun i => to_fn f' (s ++ z_to_string i)\n  | fmt_string f' => fun i => to_fn f' (s ++ i)\n  | fmt_other a f' => to_fn f' (s ++ String a EmptyString)\n  | fmt_end => s\n  end.\n\nDefinition printf s := to_fn (format_str s) \"\".\n\nEval compute in printf \"%s %s %d\" \"hi\" \"there\" 123%Z.", "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/printf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6596161695007665}}
{"text": "Require Import List.\nRequire Import EqNat.\n\nDefinition alist := list (nat * bool).\n\nFixpoint in_assignment n (a : alist) : Prop :=\n  match a with\n    | nil => False\n    | (h,_)::t => if beq_nat n h\n                  then True\n                  else in_assignment n t\n  end.\n\nLemma in_empty : forall a, in_assignment a nil -> False.\n  intros; compute in H; apply H.\nQed.\n\nFixpoint find_assignment n (a : alist) : in_assignment n a -> bool :=\n  match a with\n    | nil => fun pf => match (in_empty n) pf with end\n    | (h, tv)::t => if beq_nat h n\n                    then fun _ => tv\n                    else find_assignment n t\n  end.\n", "meta": {"author": "etosch", "repo": "logic", "sha": "40e1f1c26bd89fed3a814d90166995cc44568ef5", "save_path": "github-repos/coq/etosch-logic", "path": "github-repos/coq/etosch-logic/logic-40e1f1c26bd89fed3a814d90166995cc44568ef5/src/snippit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789452074398, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6596013587643962}}
{"text": "Require Import XR_Rmin.\nRequire Import XR_Rmax.\nRequire Import XR_Rle_dec.\nRequire Import XR_Rnot_le_lt.\n\nLocal Open Scope R_scope.\n\nLemma Rminmax : forall a b, Rmin a b <= Rmax a b.\nProof.\n  intros x y.\n  unfold Rmin, Rmax.\n  destruct (Rle_dec x y) as [ h | h ].\n  { exact h. }\n  {\n    left.\n    apply Rnot_le_lt.\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_Rminmax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6596013525670742}}
{"text": "Require Import HoTT.\nFrom HoTT.Categories Require Import\n     Functor NaturalTransformation FunctorCategory.\nFrom HoTT.Categories Require Import\n     GroupoidCategory.\nFrom GR.bicategories Require Import general_category.\n\nRecord BiCategory_d :=\n  Build_BiCategory_d {\n      Obj_d :> Type ;\n      Hom_d : Obj_d -> Obj_d -> PreCategory ;\n      id₁_d : forall (X : Obj_d), Hom_d X X ;\n      hcomp_obj : forall {X Y Z : Obj_d},\n          Hom_d Y Z * Hom_d X Y -> Hom_d X Z ;\n      hcomp_hom : forall {X Y Z : Obj_d}\n                        {f g : Hom_d Y Z * Hom_d X Y}\n                        (η : morphism (Hom_d Y Z) (fst f) (fst g) *\n                             morphism (Hom_d X Y) (snd f) (snd g)),\n          morphism (Hom_d X Z) (hcomp_obj f) (hcomp_obj g) ;\n      left_unit_d : forall {X Y : Obj_d}\n                         (f : Hom_d X Y),\n          morphism (Hom_d X Y) (hcomp_obj (id₁_d Y, f)) f ;\n      left_unit_inv_d : forall {X Y : Obj_d}\n                         (f : Hom_d X Y),\n          morphism (Hom_d X Y) f (hcomp_obj (id₁_d Y, f)) ;\n      right_unit_d : forall {X Y : Obj_d}\n                         (f : Hom_d X Y),\n          morphism (Hom_d X Y) (hcomp_obj (f, id₁_d X)) f ;\n      right_unit_inv_d : forall {X Y : Obj_d}\n                          (f : Hom_d X Y),\n          morphism (Hom_d X Y) f (hcomp_obj (f, id₁_d X)) ;\n      assoc_d : forall {W X Y Z : Obj_d}\n                         (h : Hom_d Y Z)\n                         (g : Hom_d X Y)\n                         (f : Hom_d W X),\n          morphism (Hom_d W Z)\n                   (hcomp_obj (hcomp_obj (h, g), f))\n                   (hcomp_obj (h, hcomp_obj (g, f))) ;\n      assoc_inv_d : forall {W X Y Z : Obj_d}\n                             (h : Hom_d Y Z)\n                             (g : Hom_d X Y)\n                             (f : Hom_d W X),\n          morphism (Hom_d W Z)\n                   (hcomp_obj (h, hcomp_obj (g, f)))\n                   (hcomp_obj (hcomp_obj (h, g), f))\n    }.\n\nLtac make_bicategory := simple refine (Build_BiCategory_d _ _ _ _ _ _ _ _ _ _ _).\n\nRecord is_bicategory (C : BiCategory_d)\n  := Build_is_bicategory {\n         hcomp_id_p :\n           forall {X Y Z : C}\n                  (f : Hom_d C Y Z * Hom_d C X Y),\n           (hcomp_hom C (1 : morphism (Hom_d C Y Z * Hom_d C X Y) f f) = 1)%morphism ;\n         hcomp_comp_p :\n           forall {X Y Z : C}\n                  {f g h : Hom_d C Y Z * Hom_d C X Y}\n                  (η₂ : morphism (Hom_d C Y Z * Hom_d C X Y) g h)\n                  (η₁ : morphism (Hom_d C Y Z * Hom_d C X Y) f g),\n             (hcomp_hom C (η₂ o η₁) = hcomp_hom C η₂ o hcomp_hom C η₁)%morphism ;\n         left_unit_natural_p :\n           forall {X Y : C}\n                  {f g : Hom_d C X Y}\n                  (η : morphism (Hom_d C X Y) f g),\n             ((left_unit_d C g)\n                o @hcomp_hom C X Y Y (id₁_d C Y, f) (id₁_d C Y, g) (1,η)\n              = η o left_unit_d C f)%morphism ;\n         left_unit_inv_natural_p :\n           forall {X Y : C}\n                  {f g : Hom_d C X Y}\n                  (η : morphism (Hom_d C X Y) f g),\n             (left_unit_inv_d C g o η\n              =\n              (@hcomp_hom C X Y Y (id₁_d C Y, f) (id₁_d C Y, g) (1,η))\n                o left_unit_inv_d C f)%morphism ;\n         right_unit_natural_p :\n           forall {X Y : C}\n                  {f g : Hom_d C X Y}\n                  (η : morphism (Hom_d C X Y) f g),\n             ((right_unit_d C g)\n                o @hcomp_hom C X X Y (f,id₁_d C X) (g,id₁_d C X) (η,1)\n              = η o right_unit_d C f)%morphism ;\n         right_unit_inv_natural_p :\n           forall {X Y : C}\n                  {f g : Hom_d C X Y}\n                  (η : morphism (Hom_d C X Y) f g),\n             (right_unit_inv_d C g o η\n              =\n              (@hcomp_hom C X X Y (f,id₁_d C X) (g,id₁_d C X) (η,1))\n                o right_unit_inv_d C f)%morphism ;\n         left_unit_left_p : forall {X Y : C}\n                                 (f : Hom_d C X Y),\n             (left_unit_d C f o left_unit_inv_d C f = 1)%morphism ;\n         left_unit_right_p : forall {X Y : C}\n                                 (f : Hom_d C X Y),\n             (left_unit_inv_d C f o left_unit_d C f = 1)%morphism ;\n         right_unit_left_p : forall {X Y : C}\n                                 (f : Hom_d C X Y),\n             (right_unit_d C f o right_unit_inv_d C f = 1)%morphism ;\n         right_unit_right_p : forall {X Y : C}\n                                 (f : Hom_d C X Y),\n             (right_unit_inv_d C f o right_unit_d C f = 1)%morphism ;\n         assoc_natural_p :\n           forall {W X Y Z : C}\n                  {h₁ h₂ : Hom_d C Y Z}\n                  {g₁ g₂ : Hom_d C X Y}\n                  {f₁ f₂ : Hom_d C W X}\n                  (ηh : morphism (Hom_d C Y Z) h₁ h₂)\n                  (ηg : morphism (Hom_d C X Y) g₁ g₂)\n                  (ηf : morphism (Hom_d C W X) f₁ f₂),\n             ((assoc_d C h₂ g₂ f₂)\n                o (@hcomp_hom\n                     C W X Z (_,f₁) (_,f₂)\n                     (@hcomp_hom\n                        C X Y Z (h₁,g₁) (h₂,g₂) \n                        (ηh, ηg), ηf)) =\n              (@hcomp_hom\n                 C W Y Z (h₁,_) (h₂,_)\n                 (ηh, @hcomp_hom\n                        C W X Y (g₁,f₁) (g₂,f₂)\n                        (ηg, ηf)))\n                o assoc_d C h₁ g₁ f₁)%morphism ;\n         assoc_inv_natural_p :\n           forall {W X Y Z : C}\n                  {h₁ h₂ : Hom_d C Y Z}\n                  {g₁ g₂ : Hom_d C X Y}\n                  {f₁ f₂ : Hom_d C W X}\n                  (ηh : morphism (Hom_d C Y Z) h₁ h₂)\n                  (ηg : morphism (Hom_d C X Y) g₁ g₂)\n                  (ηf : morphism (Hom_d C W X) f₁ f₂),\n             ((assoc_inv_d C h₂ g₂ f₂)\n                o (@hcomp_hom\n                     C W Y Z (h₁,_) (h₂,_) \n                     (ηh, @hcomp_hom\n                            C W X Y (g₁,f₁) (g₂,f₂)\n                            (ηg, ηf))) =\n              (@hcomp_hom\n                 C W X Z (_,f₁) (_,f₂)\n                 (@hcomp_hom\n                    C X Y Z (h₁,g₁) (h₂,g₂)\n                    (ηh, ηg), ηf))\n                o assoc_inv_d C h₁ g₁ f₁)%morphism ;\n         assoc_left_p :\n           forall {W X Y Z : C}\n                  (f : Hom_d C Y Z)\n                  (g : Hom_d C X Y)\n                  (h : Hom_d C W X),\n             (assoc_d C f g h o assoc_inv_d C f g h = 1)%morphism ;\n         assoc_right_p :\n           forall {W X Y Z : C}\n                  (f : Hom_d C Y Z)\n                  (g : Hom_d C X Y)\n                  (h : Hom_d C W X),\n             (assoc_inv_d C f g h o assoc_d C f g h = 1)%morphism ;\n         triangle_r_p :\n           forall {X Y Z : C}\n                  (g : Hom_d C Y Z)\n                  (f : Hom_d C X Y),\n             (@hcomp_hom\n                C X Y Z (_,f) (g,f)\n                (right_unit_d C g, 1) =\n              (@hcomp_hom\n                 C X Y Z (g,hcomp_obj C _) (g,f)\n                (1, left_unit_d C f))\n                o assoc_d C g (id₁_d C Y) f)%morphism ;\n         pentagon_p :\n           forall {V W X Y Z : C}\n                  (k : Hom_d C Y Z) (h : Hom_d C X Y)\n                  (g : Hom_d C W X) (f : Hom_d C V W),\n             ((assoc_d C k h (hcomp_obj C (g, f)))\n                o assoc_d C (hcomp_obj C (k, h)) g f\n              =\n              (@hcomp_hom\n                 C V Y Z\n                 (k,hcomp_obj C (hcomp_obj C (h, g), f))\n                 (k,hcomp_obj C (h, hcomp_obj C (g, f)))\n                 (1, assoc_d C h g f))\n                o assoc_d C k (hcomp_obj C (h, g)) f\n                o (@hcomp_hom\n                     C _ _ _\n                     (_,_) (_,_)\n                     (assoc_d C k h g, 1)))%morphism\n       }.\n\nLtac make_is_bicategory := simple refine (Build_is_bicategory _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _).\n\nArguments hcomp_id_p {C} _ {X Y Z} f.\nArguments hcomp_comp_p {C} _ {X Y Z f g h} _ _.\nArguments left_unit_natural_p {C} _ {X Y f g} η.\nArguments left_unit_inv_natural_p {C} _ {X Y f g} η.\nArguments left_unit_left_p {C} _ {X Y} f.\nArguments left_unit_right_p {C} _ {X Y} f.\nArguments right_unit_natural_p {C} _ {X Y f g} η.\nArguments right_unit_inv_natural_p {C} _ {X Y f g} η.\nArguments right_unit_left_p {C} _ {X Y} f.\nArguments right_unit_right_p {C} _ {X Y} f.\nArguments assoc_natural_p {C} _ {W X Y Z h₁ h₂ g₁ g₂ f₁ f₂} ηh ηg ηf.\nArguments assoc_inv_natural_p {C} _ {W X Y Z h₁ h₂ g₁ g₂ f₁ f₂} ηh ηg ηf.\nArguments assoc_left_p {C} _ {W X Y Z} f g h.\nArguments assoc_right_p {C} _ {W X Y Z} f g h.\nArguments triangle_r_p {C} _ {X Y Z} g f.\nArguments pentagon_p {C} _ {V W X Y Z} k h g f.\n\nDefinition BiCategory\n  := {C : BiCategory_d & is_bicategory C}.\n\nDelimit Scope bicategory_scope with bicategory.\nBind Scope bicategory_scope with BiCategory.\nOpen Scope bicategory_scope.\n\nDefinition Build_BiCategory\n           (C : BiCategory_d)\n           (HC : is_bicategory C)\n  : BiCategory\n  := (C;HC).\n\nDefinition Obj : BiCategory -> Type\n  := fun C => Obj_d C.1.\n\nCoercion Obj : BiCategory >-> Sortclass.\n\nDefinition Hom (C : BiCategory)\n  : Obj C -> Obj C -> PreCategory\n  := Hom_d C.1.\n\nNotation \"C ⟦ X , Y ⟧ \" := (Hom C X Y) (at level 60) : bicategory_scope.\nNotation \"f ==> g\" := (morphism (Hom _ _ _) f g) (at level 60) : bicategory_scope.\n\nDefinition vcomp\n           {C : BiCategory}\n           {X Y : C}\n           {f g h : C⟦X,Y⟧}\n           (η₂ : g ==> h)\n           (η₁ : f ==> g)\n  : f ==> h\n  := (η₂ o η₁)%morphism.\n\nArguments vcomp {C X Y f g h} η₂%bicategory η₁%bicategory.\nNotation \"η₂ '∘' η₁\" := (vcomp η₂ η₁) (at level 41, left associativity) : bicategory_scope.\n\nDefinition vcomp_assoc\n           {C : BiCategory}\n           {X Y : C}\n           {f g h k : C⟦X,Y⟧}\n           (η₃ : h ==> k)\n           (η₂ : g ==> h)\n           (η₁ : f ==> g)\n  : (η₃ ∘ η₂) ∘ η₁ = η₃ ∘ (η₂ ∘ η₁).\nProof.\n  apply associativity.\nDefined.\n\nDefinition id₂\n           {C : BiCategory}\n           {X Y : C}\n           (f : C⟦X,Y⟧)\n  : f ==> f\n  := 1%morphism.\n\nDefinition vcomp_left_identity\n           {C : BiCategory}\n           {X Y : C}\n           {f g : C⟦X,Y⟧}\n           (η : f ==> g)\n  : id₂ g ∘ η = η\n  := left_identity _ _ _ _.\n\nDefinition vcomp_right_identity\n           {C : BiCategory}\n           {X Y : C}\n           {f g : C⟦X,Y⟧}\n           (η : f ==> g)\n  : η ∘ id₂ f = η\n  := right_identity _ _ _ _.\n\nDefinition id₁ {C : BiCategory}\n  : forall (X : C), C⟦X,X⟧\n  := id₁_d C.1.\n\nDefinition hcomp1 {C : BiCategory} {X Y Z : C}\n  : C⟦Y,Z⟧ -> C⟦X,Y⟧ -> C⟦X,Z⟧\n  := fun g f => hcomp_obj C.1 (g,f).\n\nArguments hcomp1 {C X Y Z} g%bicategory f%bicategory.\nNotation \"f '·' g\" := (hcomp1 f g) (at level 41, left associativity) : bicategory_scope.\n\nDefinition hcomp2\n           {C : BiCategory}\n           {X Y Z : C}\n           {f₁ g₁ : C⟦X,Y⟧}\n           {f₂ g₂ : C⟦Y,Z⟧}\n           (η₂ : f₂ ==> g₂)\n           (η₁ : f₁ ==> g₁)\n  : f₂ · f₁ ==> g₂ · g₁.\nProof.\n  apply (hcomp_hom C.1) ; simpl.\n  exact (η₂,η₁).\nDefined.\n\nArguments hcomp2 {C X Y Z f₁ g₁ f₂ g₂} η₂%bicategory η₁%bicategory.\nNotation \"η₁ '*' η₂\" := (hcomp2 η₁ η₂) (at level 40, left associativity) : bicategory_scope.\n\nDefinition interchange\n           {C : BiCategory}\n           {X Y Z : C}\n           {f₁ g₁ h₁ : C⟦Y,Z⟧}\n           {f₂ g₂ h₂ : C⟦X,Y⟧}\n           (η₁ : f₁ ==> g₁) (η₂ : f₂ ==> g₂)\n           (ε₁ : g₁ ==> h₁) (ε₂ : g₂ ==> h₂)\n  : (ε₁ ∘ η₁) * (ε₂ ∘ η₂) = (ε₁ * ε₂) ∘ (η₁ * η₂)\n  := @hcomp_comp_p _ C.2 X Y Z (f₁,f₂) (g₁,g₂) (h₁,h₂) (ε₁,ε₂) (η₁,η₂).\n\nDefinition hcomp_id₂\n           {C : BiCategory}\n           {X Y Z : C}\n           (f₂ : C⟦Y, Z⟧) (f₁ : C⟦X,Y⟧)\n  : id₂ f₂ * id₂ f₁ = id₂ (f₂ · f₁).\nProof.\n  apply (hcomp_id_p C.2).\nDefined.\n\nDefinition hcomp {C : BiCategory} (X Y Z : C)\n  : Functor (Category.prod (C⟦Y,Z⟧) (C⟦X,Y⟧)) (C⟦X,Z⟧).\nProof.\n  simple refine (Build_Functor _ _ _ _ _ _).\n  - intros [g f].\n    exact (g · f).\n  - intros [f₁ f₂] [g₁ g₂] [η₁ η₂].\n    exact (η₁ * η₂).\n  - intros [f₁ f₂] [g₁ g₂] [h₁ h₂] [η₁ η₂] [ε₁ ε₂].\n    cbn in *.\n    apply interchange.\n  - intros [f₁ f₂].\n    cbn in *.\n    apply hcomp_id₂.\nDefined.\n\nDefinition left_unit\n           {C : BiCategory}\n           {X Y : C}\n           (f : C⟦X, Y⟧)\n  : id₁ Y · f ==> f\n  := left_unit_d C.1 f.\n\nDefinition left_unit_natural\n           {C : BiCategory}\n           {X Y : C}\n           {f g : C⟦X, Y⟧}\n           (η : f ==> g)\n  : left_unit g ∘ (id₂ (id₁ Y) * η) = η ∘ left_unit f\n  := left_unit_natural_p C.2 η.\n\nDefinition left_unitor {C : BiCategory} (X Y : C)\n  : NaturalTransformation\n      (hcomp X Y Y o (const_functor (id₁ Y) * 1))\n      1.\nProof.\n  simple refine (Build_NaturalTransformation _ _ _ _).\n  - exact left_unit.\n  - intros ; apply left_unit_natural.\nDefined.\n\nDefinition left_unit_inv\n           {C : BiCategory}\n           {X Y : C}\n           (f : C⟦X, Y⟧)\n  : f ==> id₁ Y · f\n  := left_unit_inv_d C.1 f.\n\nDefinition left_unit_inv_natural\n           {C : BiCategory}\n           {X Y : C}\n           {f g : C⟦X, Y⟧}\n           (η : f ==> g)\n  : left_unit_inv g ∘ η = (id₂ (id₁ Y) * η) ∘ left_unit_inv f\n  := left_unit_inv_natural_p C.2 η.\n\nDefinition left_unitor_inv {C : BiCategory} (X Y : C)\n  : NaturalTransformation\n      1\n      (hcomp X Y Y o (const_functor (id₁ Y) * 1)).\nProof.\n  simple refine (Build_NaturalTransformation _ _ _ _).\n  - exact left_unit_inv.\n  - intros ; apply left_unit_inv_natural.\nDefined.\n\nDefinition left_unit_left\n           {C : BiCategory}\n           {X Y : C}\n           (f : C⟦X, Y⟧)\n  : left_unit f ∘ left_unit_inv f = id₂ f\n  := left_unit_left_p C.2 f.\n\nDefinition left_unitor_left `{Univalence} {C : BiCategory} (X Y : C)\n  : (left_unitor X Y o left_unitor_inv X Y = 1)%natural_transformation.\nProof.\n  apply path_natural_transformation.\n  intros f ; cbn in *.\n  exact (left_unit_left f).\nDefined.\n\nDefinition left_unit_right\n           {C : BiCategory}\n           {X Y : C}\n           (f : C⟦X, Y⟧)\n  : left_unit_inv f ∘ left_unit f = id₂ (id₁ Y · f)\n  := left_unit_right_p C.2 f.\n\nDefinition left_unitor_right `{Univalence} {C : BiCategory} (X Y : C)\n  : (left_unitor_inv X Y o left_unitor X Y = 1)%natural_transformation.\nProof.\n  apply path_natural_transformation.\n  intros f ; cbn in *.\n  exact (left_unit_right f).\nDefined.\n\nDefinition right_unit\n           {C : BiCategory}\n           {X Y : C}\n           (f : C⟦X, Y⟧)\n  : f · id₁ X ==> f\n  := right_unit_d C.1 f.\n\nDefinition right_unit_natural\n           {C : BiCategory}\n           {X Y : C}\n           {f g : C⟦X, Y⟧}\n           (η : f ==> g)\n  : right_unit g ∘ (η * id₂ (id₁ X)) = η ∘ right_unit f\n  := right_unit_natural_p C.2 η.\n\nDefinition right_unitor {C : BiCategory} (X Y : C)\n  : NaturalTransformation\n      (hcomp X X Y o (1 * const_functor (id₁ X)))\n      1.\nProof.\n  simple refine (Build_NaturalTransformation _ _ _ _).\n  - exact right_unit.\n  - intros ; apply right_unit_natural.\nDefined.\n\nDefinition right_unit_inv\n           {C : BiCategory}\n           {X Y : C}\n           (f : C⟦X, Y⟧)\n  : f ==> f · id₁ X\n  := right_unit_inv_d C.1 f.\n\nDefinition right_unit_inv_natural\n           {C : BiCategory}\n           {X Y : C}\n           {f g : C⟦X, Y⟧}\n           (η : f ==> g)\n  : right_unit_inv g ∘ η = (η * id₂ (id₁ X)) ∘ right_unit_inv f\n  := right_unit_inv_natural_p C.2 η.\n\nDefinition right_unitor_inv {C : BiCategory} (X Y : C)\n  : NaturalTransformation\n      1\n      (hcomp X X Y o (1 * const_functor (id₁ X))).\nProof.\n  simple refine (Build_NaturalTransformation _ _ _ _).\n  - exact right_unit_inv.\n  - intros ; apply right_unit_inv_natural.\nDefined.\n\nDefinition right_unit_left\n           {C : BiCategory}\n           {X Y : C}\n           (f : C⟦X, Y⟧)\n  : right_unit f ∘ right_unit_inv f = id₂ f\n  := right_unit_left_p C.2 f.\n\nDefinition right_unitor_left `{Univalence} {C : BiCategory} (X Y : C)\n  : (right_unitor X Y o right_unitor_inv X Y = 1)%natural_transformation.\nProof.\n  apply path_natural_transformation.\n  intros f ; cbn in *.\n  apply right_unit_left.\nQed.\n\nDefinition right_unit_right\n           {C : BiCategory}\n           {X Y : C}\n           (f : C⟦X, Y⟧)\n  : right_unit_inv f ∘ right_unit f = id₂ (f · id₁ X)\n  := right_unit_right_p C.2 f.\n\nDefinition right_unitor_right `{Univalence} {C : BiCategory} (X Y : C)\n  : (right_unitor_inv X Y o right_unitor X Y = 1)%natural_transformation.\nProof.\n  apply path_natural_transformation.\n  intros f ; cbn in *.\n  apply right_unit_right.\nQed.\n\nDefinition assoc\n           {C : BiCategory}\n           {W X Y Z : C}\n           (h : C⟦Y,Z⟧) (g : C⟦X,Y⟧) (f : C⟦W,X⟧)\n  : (h · g) · f ==> h · (g · f)\n  := assoc_d C.1 h g f.\n\nDefinition assoc_natural\n           {C : BiCategory}\n           {W X Y Z : C}\n           {h₁ h₂ : C⟦Y,Z⟧} {g₁ g₂ : C⟦X,Y⟧} {f₁ f₂ : C⟦W,X⟧}\n           (ηh : h₁ ==> h₂)\n           (ηg : g₁ ==> g₂)\n           (ηf : f₁ ==> f₂)\n  : assoc h₂ g₂ f₂ ∘ ((ηh * ηg) * ηf) = (ηh * (ηg * ηf)) ∘ assoc h₁ g₁ f₁\n  := assoc_natural_p C.2 ηh ηg ηf.\n\nDefinition associator {C : BiCategory} (W X Y Z : C)\n  : NaturalTransformation\n      (hcomp W X Z o (hcomp X Y Z,1))\n      ((hcomp W Y Z)\n         o (1,hcomp W X Y)\n         o assoc_prod (Hom C Y Z) (Hom C X Y) (Hom C W X)).\nProof.\n  simple refine (Build_NaturalTransformation _ _ _ _).\n  - intros [[h g] f] ; simpl in *.\n    apply assoc.\n  - intros [[h₁ g₁] f₁] [[h₂ g₂] f₂] [[ηh ηg] ηf] ; simpl in *.\n    apply assoc_natural.\nDefined.\n\nDefinition assoc_inv\n           {C : BiCategory}\n           {W X Y Z : C}\n           (h : C⟦Y,Z⟧) (g : C⟦X,Y⟧) (f : C⟦W,X⟧)\n  : h · (g · f) ==> (h · g) · f\n  := assoc_inv_d C.1 h g f.\n\nDefinition assoc_inv_natural\n           {C : BiCategory}\n           {W X Y Z : C}\n           {h₁ h₂ : C⟦Y,Z⟧} {g₁ g₂ : C⟦X,Y⟧} {f₁ f₂ : C⟦W,X⟧}\n           (ηh : h₁ ==> h₂)\n           (ηg : g₁ ==> g₂)\n           (ηf : f₁ ==> f₂)\n  : assoc_inv h₂ g₂ f₂ ∘ (ηh * (ηg * ηf)) = ((ηh * ηg) * ηf) ∘ assoc_inv h₁ g₁ f₁\n  := assoc_inv_natural_p C.2 ηh ηg ηf.\n\nDefinition associator_inv {C : BiCategory} (W X Y Z : Obj C)\n  : NaturalTransformation\n      ((hcomp W Y Z)\n         o (1,hcomp W X Y)\n         o assoc_prod (Hom C Y Z) (Hom C X Y) (Hom C W X))\n      (hcomp W X Z o (hcomp X Y Z,1)).\nProof.\n  simple refine (Build_NaturalTransformation _ _ _ _).\n  - intros [[h g] f] ; simpl in *.\n    apply assoc_inv.\n  - intros [[h₁ g₁] f₁] [[h₂ g₂] f₂] [[ηh ηg] ηf] ; simpl in *.\n    apply assoc_inv_natural.\nDefined.\n\nDefinition assoc_left\n           {C : BiCategory}\n           {W X Y Z : C}\n           (h : C⟦Y,Z⟧) (g : C⟦X,Y⟧) (f : C⟦W,X⟧)\n  : assoc h g f ∘ assoc_inv h g f = id₂ (h · (g · f))\n  := assoc_left_p C.2 h g f.\n\nDefinition associator_left `{Univalence} {C : BiCategory} (W X Y Z : C)\n  : (associator W X Y Z o associator_inv W X Y Z = 1)%natural_transformation.\nProof.\n  apply path_natural_transformation.\n  intros f.\n  apply assoc_left.\nQed.\n\nDefinition assoc_right\n           {C : BiCategory}\n           {W X Y Z : C}\n           (h : C⟦Y,Z⟧) (g : C⟦X,Y⟧) (f : C⟦W,X⟧)\n  : assoc_inv h g f ∘ assoc h g f = id₂ ((h · g) · f)\n  := assoc_right_p C.2 h g f.\n\nDefinition associator_right `{Univalence} {C : BiCategory} (W X Y Z : C)\n  : (associator_inv W X Y Z o associator W X Y Z = 1)%natural_transformation.\nProof.\n  apply path_natural_transformation.\n  intros f.\n  apply assoc_right.\nQed.\n\nDefinition Build_IsIsomorphism_2cell\n           {C : BiCategory}\n           {X Y : C}\n           {f g : C⟦X,Y⟧}\n           {α : f ==> g}\n           (α_inv : g ==> f)\n           (sect : α_inv ∘ α = id₂ f)\n           (retr : α ∘ α_inv = id₂ g)\n  : IsIsomorphism α.\nProof.\n  simple refine (Build_IsIsomorphism _ _ _ _ _ _ _).\n  - exact α_inv.\n  - exact sect.\n  - exact retr.\nDefined.\n\n(** * Two-cells that are isomorphisms *)\n(** Inverse of a two-cell *)\nDefinition twoinverse\n           {C : BiCategory}\n           {X Y : C}\n           {f g : C⟦X,Y⟧}\n           (η : f ==> g)\n           `{IsIsomorphism _ _ _ η}\n  : g ==> f\n  := morphism_inverse η.\n(** We add this notion insted of using the notation for\n    `morphism_inverse` because `morphism_inverse` is a projection out\n    of the IsIsomorphism typeclass, which is often implicit, leading\n    to goals containing term \"_ ^-1\". E.g. `Check left_inverse.` *)\nNotation \"η ^-1\" := (twoinverse η) : bicategory_scope.\n\nDefinition vcomp_left_inverse\n           {C : BiCategory}\n           {X Y : C}\n           {f g : C⟦X,Y⟧}\n           (η : f ==> g)\n           `{IsIsomorphism _ _ _ η}\n  : η^-1 ∘ η = id₂ f.\nProof.\n  apply left_inverse.\nDefined.\n\nDefinition vcomp_right_inverse\n           {C : BiCategory}\n           {X Y : C}\n           {f g : C⟦X,Y⟧}\n           (η : f ==> g)\n           `{IsIsomorphism _ _ _ η}\n  : η ∘ η^-1 = id₂ g.\nProof.\n  apply right_inverse.\nDefined.\n\nInstance iso_id₂\n         {C : BiCategory}\n         {X Y : C}\n         (f : C⟦X,Y⟧)\n  : IsIsomorphism (id₂ f)\n  := _.\n\nInstance iso_inverse\n         {C : BiCategory}\n         {X Y : C}\n         {f g : C⟦X,Y⟧}\n         (α : f ==> g)\n         `{IsIsomorphism _ _ _ α}\n  : IsIsomorphism α^-1\n  := _.\n\nInstance iso_vcomp\n         {C : BiCategory}\n         {X Y : C}\n         {f g h : C⟦X,Y⟧}\n         (α : f ==> g)\n         (β : g ==> h)\n         `{IsIsomorphism _ _ _ α}\n         `{IsIsomorphism _ _ _ β}\n  : IsIsomorphism (β ∘ α)\n  := _.\n \nInstance left_unit_iso\n         {C : BiCategory}\n         {X Y : C}\n         (f : C⟦X,Y⟧)\n  : IsIsomorphism (left_unit f).\nProof.\n  simple refine (Build_IsIsomorphism_2cell _ _ _).\n  - exact (left_unit_inv f).\n  - apply left_unit_right.\n  - apply left_unit_left.\nDefined.\n\nInstance left_unit_inv_iso\n         {C : BiCategory}\n         {X Y : C}\n         (f : C⟦X,Y⟧)\n  : IsIsomorphism (left_unit_inv f).\nProof.\n  simple refine (Build_IsIsomorphism_2cell _ _ _).\n  - exact (left_unit f).\n  - apply left_unit_left.\n  - apply left_unit_right.\nDefined.\n\nInstance left_unitor_iso `{Univalence} {C : BiCategory} (X Y : C)\n  : @IsIsomorphism (_ -> _) _ _ (left_unitor X Y).\nProof.\n  simple refine (Build_IsIsomorphism _ _ _ _ _ _ _).\n  - exact (left_unitor_inv X Y).\n  - apply left_unitor_right.\n  - apply left_unitor_left.\nDefined.\n\nDefinition inverse_of_left_unitor\n           `{Univalence}\n           {C : BiCategory}\n           (X Y : C)\n  : @morphism_inverse (_ -> _) _ _ (left_unitor X Y) _ = left_unitor_inv X Y\n  := idpath.\n\nInstance right_unit_iso\n         {C : BiCategory}\n         {X Y : C}\n         (f : C⟦X,Y⟧)\n  : IsIsomorphism (right_unit f).\nProof.\n  simple refine (Build_IsIsomorphism_2cell _ _ _).\n  - exact (right_unit_inv f).\n  - apply right_unit_right.\n  - apply right_unit_left.\nDefined.\n\nInstance right_unit_inv_iso\n         {C : BiCategory}\n         {X Y : C}\n         (f : C⟦X,Y⟧)\n  : IsIsomorphism (right_unit_inv f).\nProof.\n  simple refine (Build_IsIsomorphism_2cell _ _ _).\n  - exact (right_unit f).\n  - apply right_unit_left.\n  - apply right_unit_right.\nDefined.\n\nInstance right_unitor_iso `{Univalence} {C : BiCategory} (X Y : C)\n  : @IsIsomorphism (_ -> _) _ _ (right_unitor X Y).\nProof.\n  simple refine (Build_IsIsomorphism _ _ _ _ _ _ _).\n  - exact (right_unitor_inv X Y).\n  - apply right_unitor_right.\n  - apply right_unitor_left.\nDefined.\n\nDefinition inverse_of_right_unitor\n           `{Univalence}\n           {C : BiCategory}\n           (X Y : C)\n  : @morphism_inverse (_ -> _) _ _ (right_unitor X Y) _ = right_unitor_inv X Y\n  := idpath.\n\nInstance assoc_iso\n         {C : BiCategory}\n         {W X Y Z : C}\n         (h : C⟦Y,Z⟧) (g : C⟦X,Y⟧) (f : C⟦W,X⟧)\n  : IsIsomorphism (assoc h g f).\nProof.\n  simple refine (Build_IsIsomorphism_2cell _ _ _).\n  - exact (assoc_inv h g f).\n  - apply assoc_right.\n  - apply assoc_left.\nDefined.\n\nInstance assoc_inv_iso\n         {C : BiCategory}\n         {W X Y Z : C}\n         (h : C⟦Y,Z⟧) (g : C⟦X,Y⟧) (f : C⟦W,X⟧)\n  : IsIsomorphism (assoc_inv h g f).\nProof.\n  simple refine (Build_IsIsomorphism_2cell _ _ _).\n  - exact (assoc h g f).\n  - apply assoc_left.\n  - apply assoc_right.\nDefined.\n\nInstance associator_iso\n         `{Univalence}\n         {C : BiCategory}\n         (W X Y Z : C)\n  : @IsIsomorphism (_ -> _) _ _ (associator W X Y Z).\nProof.\n  simple refine (Build_IsIsomorphism _ _ _ _ _ _ _).\n  - exact (associator_inv W X Y Z).\n  - apply associator_right.\n  - apply associator_left.\nDefined.\n\nDefinition inverse_of_associator\n           `{Univalence}\n           {C : BiCategory}\n           (W X Y Z : C)\n  : @morphism_inverse (_ -> _) _ _ (associator W X Y Z) _ = associator_inv W X Y Z\n  := idpath.\n\nDefinition triangle_r\n           {C : BiCategory}\n           {X Y Z : C}\n           (g : C⟦Y,Z⟧)\n           (f : C⟦X,Y⟧)\n  : right_unit g * id₂ f = (id₂ g * left_unit f) ∘ assoc g (id₁ Y) f\n  := triangle_r_p C.2 g f.\n\nDefinition pentagon\n           {C : BiCategory}\n           {V W X Y Z : C}\n           (k : C⟦Y,Z⟧) (h : C⟦X,Y⟧) (g : C⟦W,X⟧) (f : C⟦V,W⟧)\n  : (assoc k h (g · f) ∘ assoc (k · h) g f)\n    =\n    (id₂ k * assoc h g f) ∘ assoc k (h · g) f ∘ (assoc k h g * id₂ f)\n  := pentagon_p C.2 k h g f.\n\nGlobal Instance hcomp_iso\n       {C : BiCategory}\n       {X Y Z : C}\n       {f₁ g₁ : C⟦Y,Z⟧} {f₂ g₂ : C⟦X,Y⟧}\n       (η₁ : f₁ ==> g₁) (η₂ : f₂ ==> g₂)\n       `{IsIsomorphism _ _ _ η₁}\n       `{IsIsomorphism _ _ _ η₂}\n  : IsIsomorphism (η₁ * η₂).\nProof.\n  simple refine (Build_IsIsomorphism_2cell _ _ _).\n  - exact (η₁^-1 * η₂^-1).\n  - rewrite <- interchange.\n    rewrite !vcomp_left_inverse.\n    apply hcomp_id₂.\n  - rewrite <- interchange.\n    rewrite !vcomp_right_inverse.\n    apply hcomp_id₂.\nDefined.\n\nDefinition bc_whisker_l\n           {C : BiCategory}\n           {X Y Z : C}\n           {f₁ : C⟦X,Y⟧} {f₂ : C⟦X,Y⟧}\n           (g : C⟦Y,Z⟧)\n           (α : f₁ ==> f₂)\n  : (g · f₁) ==> (g · f₂)\n  := id₂ g * α.\n\nNotation \"g '◅' α\" := (bc_whisker_l g α) (at level 40) : bicategory_scope.\n\nDefinition bc_whisker_l_id₂\n           {C : BiCategory}\n           {X Y Z : C}\n           (f : C⟦X,Y⟧)\n           (g : C⟦Y,Z⟧)\n  : g ◅ (id₂ f) = id₂ (g · f)\n  := hcomp_id₂ g f.\n\nDefinition bc_whisker_r\n           {C : BiCategory}\n           {X Y Z : C}\n           {g₁ : C⟦Y,Z⟧} {g₂ : C⟦Y,Z⟧}\n           (β : g₁ ==> g₂)\n           (f : C⟦X,Y⟧)\n  : (g₁ · f) ==> (g₂ · f)\n  := β * id₂ f.\n\nNotation \"β '▻' f\" := (bc_whisker_r β f) (at level 40) : bicategory_scope.\n\nDefinition bc_whisker_r_id₂\n           {C : BiCategory}\n           {X Y Z : C}\n           (f : C⟦X,Y⟧)\n           (g : C⟦Y,Z⟧)\n  : (id₂ g) ▻ f = id₂ (g · f)\n  := hcomp_id₂ g f.\n\nDefinition inverse_of_assoc\n           {C : BiCategory}\n           {W X Y Z : C}\n           (h : C⟦Y,Z⟧) (g : C⟦X,Y⟧) (f : C⟦W,X⟧)\n  : (assoc h g f)^-1 = assoc_inv h g f\n  := idpath.\n\nDefinition inverse_of_left_unit\n           {C : BiCategory}\n           {X Y : C}\n           (f : C⟦X,Y⟧)\n  : (left_unit f)^-1 = left_unit_inv f\n  := idpath.\n\nDefinition inverse_of_right_unit\n           {C : BiCategory}\n           {X Y : C}\n           (f : C⟦X,Y⟧)\n  : (right_unit f)^-1 = right_unit_inv f\n  := idpath.\n\n(** Properties of isomorphisms *)\nDefinition id₂_inverse\n           {C : BiCategory}\n           {X Y : C}\n           (f : C⟦X,Y⟧)\n  : (id₂ f)^-1 = id₂ f\n  := idpath.\n\nDefinition vcomp_inverse\n           {C : BiCategory}\n           {X Y : C}\n           {f g h : C⟦X,Y⟧}\n           (η₁ : f ==> g) (η₂ : g ==> h)\n           `{IsIsomorphism _ _ _ η₁}\n           `{IsIsomorphism _ _ _ η₂}\n  : (η₂ ∘ η₁)^-1 = η₁^-1 ∘ η₂^-1\n  := idpath.\n\nDefinition hcomp_inverse\n           {C : BiCategory}\n           {X Y Z : C}\n           {f₁ g₁ : C⟦Y,Z⟧} {f₂ g₂ : C⟦X,Y⟧}\n           (η₁ : f₁ ==> g₁) (η₂ : f₂ ==> g₂)\n           `{IsIsomorphism _ _ _ η₁}\n           `{IsIsomorphism _ _ _ η₂}\n  : (η₁ * η₂)^-1 = η₁^-1 * η₂^-1\n  := idpath.\n\nDefinition vcomp_cancel_left\n           {C : BiCategory}\n           {X Y : C}\n           {f g h : C⟦X,Y⟧}\n           (ε : g ==> h)\n           (η₁ η₂ : f ==> g)\n           `{IsIsomorphism _ _ _ ε}\n  : ε ∘ η₁ = ε ∘ η₂ -> η₁ = η₂.\nProof.\n  intros Hhf.  \n  refine ((vcomp_left_identity _)^ @ _ @ vcomp_left_identity _).\n  rewrite <- (vcomp_left_inverse ε).\n  rewrite !vcomp_assoc.\n  rewrite Hhf.\n  reflexivity.\nDefined.\n\nDefinition vcomp_cancel_right\n           {C : BiCategory}\n           {X Y : C}\n           {f g h : C⟦X,Y⟧}\n           (ε : f ==> g) (η₁ η₂ : g ==> h)\n           `{IsIsomorphism _ _ _ ε}\n  : η₁ ∘ ε = η₂ ∘ ε -> η₁ = η₂.\nProof.\n  intros Hhf.  \n  refine ((vcomp_right_identity _)^ @ _ @ vcomp_right_identity _).\n  rewrite <- (vcomp_right_inverse ε).\n  rewrite <- !vcomp_assoc.\n  rewrite Hhf.\n  reflexivity.\nDefined.\n\nDefinition vcomp_move_L_Vp\n           {C : BiCategory}\n           {X Y : C}\n           {f g h : C⟦X,Y⟧}\n           (η₁ : f ==> g) (η₂ : f ==> h) (ε : g ==> h) \n           `{IsIsomorphism _ _ _ ε}\n  : ε ∘ η₁ = η₂ -> η₁ = ε^-1 ∘ η₂.\nProof.\n  intros ?.\n  rewrite <- (vcomp_left_identity η₁).\n  rewrite <- (vcomp_left_inverse ε).\n  rewrite vcomp_assoc.\n  apply ap.\n  assumption.\nQed.\n\nDefinition vcomp_move_L_pV\n           {C : BiCategory}\n           {X Y : C}\n           {f g h : C⟦X,Y⟧}\n           (η₁ : g ==> h) (η₂ : f ==> h) (ε : f ==> g) \n           `{IsIsomorphism _ _ _ ε}\n  : η₁ ∘ ε = η₂ -> η₁ = η₂ ∘ ε^-1.\nProof.\n  intros Hη.\n  rewrite <- (vcomp_right_identity η₁).\n  rewrite <- (vcomp_right_inverse ε).\n  rewrite <- vcomp_assoc.\n  rewrite Hη.\n  reflexivity.\nQed.\n\nDefinition vcomp_move_R_Mp\n           {C : BiCategory}\n           {X Y : C}\n           {f g h : C⟦X,Y⟧}\n           (η₁ : f ==> g) (η₂ : f ==> h) (ε : g ==> h) \n           `{IsIsomorphism _ _ _ ε}\n  : η₁ = ε^-1 ∘ η₂ -> ε ∘ η₁ = η₂.\nProof.\n  intros ?.\n  rewrite <- (vcomp_left_identity η₂).\n  rewrite <- (vcomp_right_inverse ε).\n  rewrite vcomp_assoc.\n  apply ap.\n  assumption.\nQed.\n\nDefinition vcomp_move_R_pM\n           {C : BiCategory}\n           {X Y : C}\n           {f g h : C⟦X,Y⟧}\n           (η₁ : g ==> h) (η₂ : f ==> h) (ε : f ==> g) \n           `{IsIsomorphism _ _ _ ε}\n  : η₁ = η₂ ∘ ε^-1 -> η₁ ∘ ε = η₂.\nProof.\n  intros Hη.\n  rewrite <- (vcomp_right_identity η₂).\n  rewrite <- (vcomp_left_inverse ε).\n  rewrite <- vcomp_assoc.\n  rewrite Hη.\n  reflexivity.\nQed.\n\nDefinition vcomp_move_L_Mp\n           {C : BiCategory}\n           {X Y : C}\n           {f g h : C⟦X,Y⟧}\n           (η₁ : f ==> h) (η₂ : f ==> g) (ε : g ==> h) \n           `{IsIsomorphism _ _ _ ε}\n  : ε^-1 ∘ η₁ = η₂ -> η₁ = ε ∘ η₂.\nProof.\n  intros ?.\n  rewrite <- (vcomp_left_identity η₁).\n  rewrite <- (vcomp_right_inverse ε).\n  rewrite vcomp_assoc.\n  apply ap.\n  assumption.\nQed.\n\nDefinition vcomp_move_L_pM\n           {C : BiCategory}\n           {X Y : C}\n           {f g h : C⟦X,Y⟧}\n           (η₁ : f ==> h) (η₂ : g ==> h) (ε : f ==> g) \n           `{IsIsomorphism _ _ _ ε}\n  : η₁ ∘ ε^-1 = η₂ -> η₁ = η₂ ∘ ε.\nProof.\n  intros Hη.\n  rewrite <- (vcomp_right_identity η₁).\n  rewrite <- (vcomp_left_inverse ε).\n  rewrite <- vcomp_assoc.\n  rewrite Hη.\n  reflexivity.\nQed.\n\nDefinition path_inverse_2cell\n           {C : BiCategory}\n           {X Y : C}\n           {f g : C⟦X,Y⟧}\n           (η₁ η₂ : f ==> g)\n           {Hη₁ : IsIsomorphism η₁}\n           {Hη₂ : IsIsomorphism η₂}\n  : η₁ = η₂ -> η₁^-1 = η₂^-1.\nProof.\n  intros p.\n  rewrite <- (vcomp_right_identity (η₁^-1)%bicategory).\n  rewrite <- (vcomp_left_identity (η₂^-1)%bicategory).\n  rewrite <- (vcomp_right_inverse η₂).\n  rewrite <- vcomp_assoc.\n  f_ap.\n  rewrite <- p.\n  apply vcomp_left_inverse.\nDefined.\n\nDefinition is_21 `{Funext} (C : BiCategory)\n  : hProp\n  := BuildhProp (forall (X Y : C), IsGroupoid (C⟦X,Y⟧)).\n", "meta": {"author": "nmvdw", "repo": "groupoids", "sha": "dd54321b2589c7cf31f379bd63b4a86cf9052792", "save_path": "github-repos/coq/nmvdw-groupoids", "path": "github-repos/coq/nmvdw-groupoids/groupoids-dd54321b2589c7cf31f379bd63b4a86cf9052792/bicategories/bicategory/bicategory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6595649982877839}}
{"text": "\nTheorem Ex036 (A B : Prop): (A -> B) -> A -> B.\nProof.\n  intros.\n  apply H.\n  exact H0.\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/Ex036.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.659564535487658}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrnat ssrfun.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** \nExercise 7.2 Partially-ordered sets\n\nMathcomp ライブラリに命名規則をあわせた。\nModuleとSectionの階層を削除して、シンプルな構成にする。\n (* see. ssr_pnp_deprecords_3.v *)\n*)\n\nModule Poset.\n  \n(**\nMixinの定義\n*)\n  Record posetMixin (T : Type) :=\n    PosetMixin {\n        valid : T -> bool;\n        rel : T -> T -> bool;\n        refl (x : T) : rel x x;\n        asym (x y : T) : rel x y -> rel y x -> x = y;\n        trans (y x z : T) : rel x y -> rel y z -> rel x z\n      }.\n  (**\nPackの定義\n*)\n  Structure posetType : Type :=\n    PosetType {\n        sort :> Type;\n        m : posetMixin sort\n      }.\n  Print Graph.   (* [sort] : posetType >-> Sortclass *)\n(*  Local Coercion sort : posetType >-> Sortclass. *)\n\n(*\n  Variable cT: posetType.\n  \n  Print posetType.\n  Definition poset_struct : posetMixin cT := (* Coercion cT *)\n    let: PosetType _ c := cT return posetMixin cT in c.\n  Definition valid_op := valid poset_struct.\n  Definition rel_op := rel poset_struct.\n*)  \n  Definition valid_op {cT : posetType} := @valid cT (m cT).\n  Definition rel_op {cT : posetType} := @rel cT (m cT).\n  \n  Notation \"x <== y\" := (rel_op x y) (at level 70, no associativity).\n  (* rel ではない！ *)\n  Notation Rel := @rel_op.\n  Notation Valid := @valid_op.\n  \n  Section POSETLemmas.\n    Variable T : posetType.\n    \n    Lemma poset_refl (x : T) : x <== x.\n    Proof.\n      case: T x => tp [rel Hv Href Hasym Htrans x].\n        by apply: Href.\n    Qed.\n    \n    Lemma poset_asym (x y : T) : x <== y -> y <== x -> x = y.\n    Proof.\n      case: T x y => tp [rel Hv Href Hasym Htrans x y].\n        by apply Hasym.\n    Qed.\n    \n    Lemma poset_trans (y x z : T) : x <== y -> y <== z -> x <== z.\n    Proof.\n      case: T x y z => tp [rel Hv Href Hasym Htrans x y z].\n        by apply Htrans.\n    Qed.\n  End POSETLemmas.\n  \n(**\n自然数のPOSETを定義する。\n *)\n  Check leqnn : forall n : nat, n <= n.\n  \n  Lemma eqn_leq' : forall m n : nat, m <= n -> n <= m -> m = n.\n  Proof.\n    move=> m n.\n    elim: m n => [|m IHm] [|n] //.\n    move=> H1 H2; congr (_ .+1); move: H1 H2.\n      by apply (IHm n).\n  Qed.\n  \n  Check leq_trans : forall n m p : nat, m <= n -> n <= p -> m <= p.\n  \n  Definition nat_posetMixin :=\n    PosetMixin\n      (fun _ => id true)                    (* valid *)\n      leqnn                                 (* ref *)\n      eqn_leq'                              (* asym *)\n      leq_trans.                            (* trans *)\n  \n  Canonical nat_posetType := @PosetType nat nat_posetMixin.\n  Print Canonical Projections. (* nat <- POSETDef.sort ( nat_posetType ) *)\n  \n  Compute 1 <== 1.                          (* true *)\n  Compute 1 <== 2.                          (* true *)\n  Compute 2 <== 1.                          (* false *)\n  \n  Section PosetExamples.\n    Variables x y z : nat.\n    \n    Check Rel : forall cT : posetType, cT -> cT -> bool.\n    About \"_ <== _\".                          (* Rel := POSET.rel_op *)\n    \n    Goal x <== x.\n    Proof.\n        by apply: poset_refl.\n    Qed.\n    \n    Goal x <== y -> y <== x -> x = y.\n    Proof.\n        by apply: poset_asym.\n    Qed.\n    \n    Goal x <== y -> y <== z -> x <== z.\n    Proof.\n        by apply: poset_trans.\n    Qed.\n  End PosetExamples.\nEnd Poset.\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/pnp/ssr_pnp_poset_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.6595518840224509}}
{"text": "From Coq Require Import\n  PeanoNat.\nFrom DEZ Require Export\n  Init.\nFrom DEZ.Is Require Import\n  TotalOrder Semiring MonoidHomomorphism.\n\nModule Equivalence.\n\nInstance nat_has_eqv : HasEqv nat := Nat.eq.\n\nInstance nat_is_reflexive : IsReflexive Nat.eq := {}.\nProof. intros x. reflexivity. Qed.\n\nInstance nat_is_symmetric : IsSymmetric Nat.eq := {}.\nProof. intros x y p. symmetry; auto. Qed.\n\nInstance nat_is_transitive : IsTransitive Nat.eq := {}.\nProof. intros x y z p q. transitivity y; auto. Qed.\n\nInstance nat_is_setoid : IsSetoid Nat.eq := {}.\n\nEnd Equivalence.\n\nModule Order.\n\nInstance nat_has_ord : HasOrd nat := Nat.le.\n\nInstance nat_is_antisymmetric : IsAntisymmetric Nat.le := {}.\nProof. intros x y p q. apply Nat.le_antisymm; auto. Qed.\n\nInstance nat_is_transitive : IsTransitive Nat.le := {}.\nProof. intros x y z p q. transitivity y; auto. Qed.\n\nInstance nat_is_connex : IsConnex Nat.le := {}.\nProof. intros x y. apply Nat.le_ge_cases. Qed.\n\nInstance nat_is_total_order : IsTotalOrder Nat.le := {}.\nProof. cbv -[Nat.le]. apply Nat.le_wd. Qed.\n\nEnd Order.\n\nModule Additive.\n\nInstance nat_has_opr : HasOpr nat := Nat.add.\n\nInstance nat_is_associative : IsAssociative Nat.add := {}.\nProof. intros x y z. apply Nat.add_assoc. Qed.\n\nInstance nat_is_semigroup : IsSemigroup Nat.add := {}.\nProof. cbv -[Nat.add]. apply Nat.add_wd. Qed.\n\nInstance nat_has_idn : HasIdn nat := Nat.zero.\n\nInstance nat_is_left_identifiable : IsLeftIdentifiable Nat.add Nat.zero := {}.\nProof. intros x. apply Nat.add_0_l. Qed.\n\nInstance nat_is_right_identifiable :\n  IsRightIdentifiable Nat.add Nat.zero := {}.\nProof. intros x. apply Nat.add_0_r. Qed.\n\nInstance nat_is_identifiable : IsBiidentifiable Nat.add Nat.zero := {}.\n\nInstance nat_is_monoid : IsMonoid Nat.add Nat.zero := {}.\n\nInstance nat_is_commutative : IsCommutative Nat.add := {}.\nProof. intros x y. apply Nat.add_comm. Qed.\n\nInstance nat_is_commutative_monoid :\n  IsCommutativeMonoid Nat.add Nat.zero := {}.\n\nEnd Additive.\n\nModule Multiplicative.\n\nInstance nat_has_opr : HasOpr nat := Nat.mul.\n\nInstance nat_is_associative : IsAssociative Nat.mul := {}.\nProof. intros x y z. apply Nat.mul_assoc. Qed.\n\nInstance nat_is_semigroup : IsSemigroup Nat.mul := {}.\nProof. cbv -[Nat.mul]. apply Nat.mul_wd. Qed.\n\nInstance nat_has_idn : HasIdn nat := Nat.one.\n\nInstance nat_is_left_identifiable : IsLeftIdentifiable Nat.mul Nat.one := {}.\nProof. intros x. apply Nat.mul_1_l. Qed.\n\nInstance nat_is_right_identifiable : IsRightIdentifiable Nat.mul Nat.one := {}.\nProof. intros x. apply Nat.mul_1_r. Qed.\n\nInstance nat_is_identifiable : IsBiidentifiable Nat.mul Nat.one := {}.\n\nInstance nat_is_monoid : IsMonoid Nat.mul Nat.one := {}.\n\nInstance nat_is_commutative : IsCommutative Nat.mul := {}.\nProof. intros x y. apply Nat.mul_comm. Qed.\n\nInstance nat_is_commutative_monoid : IsCommutativeMonoid Nat.mul Nat.one := {}.\n\nEnd Multiplicative.\n\nInstance nat_has_add : HasAdd nat := Nat.add.\nInstance nat_has_mul : HasMul nat := Nat.mul.\n\nInstance nat_has_zero : HasZero nat := Nat.zero.\nInstance nat_has_one : HasOne nat := Nat.one.\n\nInstance nat_is_left_distributive : IsLeftDistributive Nat.add Nat.mul := {}.\nProof. intros x y z. apply Nat.mul_add_distr_l. Qed.\n\nInstance nat_is_right_distributive : IsRightDistributive Nat.add Nat.mul := {}.\nProof. intros x y z. apply Nat.mul_add_distr_r. Qed.\n\nInstance nat_is_distributive : IsBidistributive Nat.add Nat.mul := {}.\n\nInstance nat_is_semiring : IsSemiring Nat.add Nat.zero Nat.mul Nat.one := {}.\n\nDefinition natexp (x : nat) : nat := 2 ^ x.\n\nInstance nat_has_hom : HasHom nat nat := natexp.\n\nInstance nat_is_setoid_homomorphism : IsSetoidHomomorphism natexp := {}.\nProof. cbv -[Nat.pow]. apply Nat.pow_wd. reflexivity. Qed.\n\nInstance nat_is_semigroup_homomorphism :\n  IsSemigroupHomomorphism Nat.add Nat.mul natexp := {}.\nProof. intros x y. apply Nat.pow_add_r. Qed.\n\nInstance nat_is_monoid_homomorphism :\n  IsMonoidHomomorphism Nat.add Nat.zero Nat.mul Nat.one natexp := {}.\nProof. reflexivity. Qed.\n", "meta": {"author": "Tuplanolla", "repo": "dez", "sha": "c2eadc2e032094c3504ec3803c000dba4feb547e", "save_path": "github-repos/coq/Tuplanolla-dez", "path": "github-repos/coq/Tuplanolla-dez/dez-c2eadc2e032094c3504ec3803c000dba4feb547e/garbage/prototype/Provides/NatTheorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6595383535892428}}
{"text": "Require Import Tapl.DSub.Base.\n\n\nInductive type : Set :=\n  | ty_top  : type (* ⊤ *)\n  | ty_bot  : type (* ⊥ *)\n  | ty_decl : type → type → type (* {A : S .. T *)\n  | ty_proj : nat → type (* x.A *)\n  | ty_dep_fun : type → type → type. (* ∀(x:S) T *)\n\nInductive term : Set :=\n  | tm_var : nat → term\n  | tm_tag : type → term\n  | tm_abs : type → term → term\n  | tm_app : term → term → term\n  | tm_let : term → type → term → term.\n\nDefinition context := list type.\nInductive wfT : context → type → Prop := \n  | wfT_top : ∀ Γ, wfT Γ ty_top\n  | wfT_bot : ∀ Γ, wfT Γ ty_bot\n  | wfT_decl : ∀ Γ S T,\n      wfT Γ S → wfT Γ T →\n      wfT Γ (ty_decl S T)\n  | wfT_proj : ∀ Γ i,\n      (∃ T, get i Γ = Some T) →\n      wfT Γ (ty_proj i)\n  | wfT_dep_fun : ∀ Γ S T,\n      wfT Γ S →\n      wfT (S :: Γ) T →\n      wfT Γ (ty_dep_fun S T)\n.\n\nInductive wfX : context → term → Prop :=\n  | wfX_var : ∀ Γ i,\n      (∃ T, get i Γ = Some T) →\n      wfX Γ (tm_var i)\n  | wfX_tag : ∀ Γ T,\n      wfT Γ T →\n      wfX Γ (tm_tag T)\n  | wfX_abs : ∀ Γ T t,\n      wfT Γ T →\n      wfX (T :: Γ) t →\n      wfX Γ (tm_abs T t)\n  | wfX_app : ∀ Γ t1 t2,\n      wfX Γ t1 →\n      wfX Γ t2 →\n      wfX Γ (tm_app t1 t2)\n  | wfX_let : ∀ Γ t1 T t2,\n      wfX Γ t1 →\n      wfX (T :: Γ) t2 →\n      wfX Γ (tm_let t1 T t2).\n\nDefinition closed := wfX nil.\n", "meta": {"author": "tmoux", "repo": "coq-pl", "sha": "fe79928ab82daebe5012cd3204a0eeff83ee8ade", "save_path": "github-repos/coq/tmoux-coq-pl", "path": "github-repos/coq/tmoux-coq-pl/coq-pl-fe79928ab82daebe5012cd3204a0eeff83ee8ade/tapl/DSub/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6595383533925677}}
{"text": "Module Evote.\n\n  Require Import Notations.\n  Require Import Coq.Lists.List.\n  Require Import Coq.Arith.Le.\n  Require Import Coq.Numbers.Natural.Peano.NPeano.\n  Require Import Coq.Arith.Compare_dec.\n  Require Import Coq.omega.Omega.\n  Require Import Bool.Sumbool.\n  Require Import Bool.Bool.\n  Import ListNotations.\n\n  (* type level existential quantifier *)\n  Notation \"'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 ']'\")\n    : type_scope.\n\n  (* candidates are a finite type with decidable equality *)\n  Parameter cand : Type.\n  Parameter cand_all : list cand.\n  Hypothesis cand_fin : forall c: cand, In c cand_all.\n  Hypothesis dec_cand : forall n m : cand, {n = m} + {n <> m}.\n\n  (* edge is the margin in Schulze counting, i.e. edge c d is the number of\n     voters that perfer c over d *)\n  (* TODO: possibly rename? *)\n  Parameter edge: cand -> cand -> nat.\n\n  (* prop-level path *)\n  Inductive Path (k: nat) : cand -> cand -> Prop :=\n  | unit c d : edge c d >= k -> Path k c d\n  | cons  c d e : edge c d >= k -> Path k d e -> Path k c e.\n\n  (* type-level path *)\n  Inductive PathT (k: nat) : cand -> cand -> Type :=\n  | unitT : forall c d, edge c d >= k -> PathT k c d\n  | consT : forall c d e, edge c d >= k -> PathT k d e -> PathT k c e.\n\n  (* winning condition in Schulze counting *)\n  Definition wins (c: cand) :=\n    forall d : cand, exists k : nat,\n        ((Path k c d) /\\ (forall l, Path l d c -> l <= k)).\n\n  (* auxilary functions: all pairs that can be formed from a list *)\n  Fixpoint all_pairs {A: Type} (l: list A): list (A * A) :=\n    match l with\n    |   [] => []\n    |    c::cs => (c, c)::(all_pairs cs) ++ (map (fun x => (c, x)) cs)\n                       ++ (map (fun x => (x, c)) cs)\n    end.\n\n  (* boolean equality on candidates derived from decidable equality *)\n  Definition cand_eqb (c d: cand) := proj1_sig (bool_of_sumbool (dec_cand c d)).\n\n  Lemma cand_eqb_prop (c d: cand) : cand_eqb c d = true -> c = d.\n  Proof.\n    intro H. unfold cand_eqb in H. destruct (dec_cand c d). assumption. simpl in H. inversion H.\n  Qed.\n\n  (* boolean membership in lists of pairs *)\n  Definition bool_in (p: (cand * cand)%type) (l: list (cand * cand)%type) :=\n    existsb (fun q => (andb (cand_eqb (fst q) (fst p))) ((cand_eqb (snd q) (snd p)))) l.\n\n  (* towards the definition of co-closed sets *)\n  (* el is a boolean function that returns true if the edge between two cands is <= k *)\n  Definition el (k: nat) (p: (cand * cand)%type) := Compare_dec.leb (edge (fst p) (snd p)) k.\n\n  (* mp k (a, c) l (for midpoint) returns true if there's a midpoint b st. either the edge between\n     a and b is <= k or else the pair (b, c) is in l *)\n  Definition mp (k: nat) (p: (cand * cand)%type) (l: list (cand *cand)%type) :=\n    let a := fst p in\n    let c := snd p in\n    fold_left (fun x => fun b => andb x (orb (bool_in (b, c) l) (el k (a,b)))) cand_all true.\n\n  (* W k is the dual of the operator the least fixpoint of which inductively defines paths *)\n  (* W_k (l) = {(a, c) : edge a c <= k /\\ forall b: (b, c) \\in l \\/edge a c <= k } *)\n  (* Wf is the boolean predicate that expresses the operator *)\n  Definition Wf k l :=  (fun p => andb (el k p)  (mp k p l) ).\n  Definition W (k: nat) : list (cand * cand)%type -> list (cand *cand)%type :=\n    fun l => filter (Wf k l) (all_pairs cand_all).\n\n  (* a k-coclosed set is a set that is co-closed under W_k *)\n  (* idea: the greatest co-closed (and indeed any co-closed set) only *)\n  (* contains pairs (x, y) s.t. there's no path of strength >= k between x and y *)\n  Definition coclosed (k: nat) (l: list (cand * cand)%type) :=\n    forall x, In x l -> In x (W k l).\n\n  (* evidence for winning a Schulze election. *)\n  Definition ev (c: cand) := forall d : cand, existsT (k: nat),\n    (PathT k c d) * (existsT (l: list (cand * cand)%type), In (d, c)l /\\ coclosed k l).\n\n  (* type-level paths allow to construct evidence for the existence of paths *)\n  (* TODO: change name of lemma? *)\n  Lemma equivalent : forall c d k , PathT k c d -> Path k c d.\n  Proof.\n    intros. induction X. apply unit. assumption.\n    apply cons with (d := d). assumption.\n    assumption.\n  Qed.\n\n  (* logical interpretation of the midpoint function *)\n  (* TODO: change name of lemma? *)\n  Lemma edge_prop : forall a b k, el k (a, b) = true -> edge a b <= k.\n  Proof.\n    intros a b k H; unfold el in H; simpl in H;\n      apply leb_complete in H; assumption.\n  Qed.\n\n  Lemma boolin_prop :  forall a b l, bool_in (a, b) l = true -> In (a, b) l.\n  Proof.\n    intros a b l H. unfold bool_in in H; simpl in H.\n    rewrite existsb_exists in H. destruct H. destruct x. simpl in H.\n    destruct H. apply andb_true_iff in H0.\n    destruct H0. apply cand_eqb_prop in H0.\n    apply cand_eqb_prop in H1. rewrite H0 in H. rewrite H1 in H.\n    assumption.\n  Qed.\n\n  Lemma fold_left_uni :\n    forall (A : Type) (f : A -> bool) l a,\n      fold_left (fun x y => andb x (f y)) l a = true -> a = true /\\ List.Forall (fun a => f a = true) l.\n  Proof.\n    induction l; simpl; intros.\n    - auto.\n    - apply IHl in H. destruct H.\n      apply andb_true_iff in H.\n      intuition.\n  Qed.\n\n  Lemma fold_left_andb :\n    forall (A : Type) (f : A -> bool) l a,\n      fold_left (fun x y => andb x (f y)) l a = true -> List.Forall (fun a => f a = true) l.\n  Proof. apply fold_left_uni. Qed.\n\n  Lemma fold_left_true :\n    forall (p : cand * cand) (l : list (cand * cand)) (k : nat),\n      fold_left (fun (x : bool) (b : cand) =>\n                   andb x (orb (bool_in (b, snd p) l)\n                               (el k (fst p, b)))) cand_all true = true ->\n      forall c, (bool_in (c, snd p) l) = true \\/ (el k (fst p, c)) = true.\n  Proof.\n    intros. apply fold_left_andb in H.\n    rewrite Forall_forall in H.\n    rewrite <- orb_true_iff.\n    apply H. apply cand_fin.\n  Qed.\n\n\n  Lemma forthemoment : forall k p l, mp k p l = true ->\n                                forall b, In (b, snd p) l \\/ edge (fst p) b <= k.\n  Proof.\n    intros k (u, v) l H b. unfold mp in H.\n    apply fold_left_true with (c := b) in H.\n    simpl in H; simpl. destruct H as [H | H].\n    apply boolin_prop in H. left; assumption.\n    apply edge_prop in H. right; assumption.\n  Qed.\n\n  (* generic property of coclosed sets as commented above *)\n  Lemma coclosednow : forall k l, coclosed k l -> forall s x y,\n        Path s x y -> In (x, y) l -> s <= k.\n  Proof.\n    intros k l Hcc.\n    intros s x y.\n    intro p.\n    induction p.\n    (* path of length one *)\n    intro Hin.\n    unfold coclosed in Hcc.\n    specialize (Hcc (c, d)).\n    specialize (Hcc Hin).\n    unfold W in Hcc.\n    Check filter_In.\n    assert (HW: In (c, d) (all_pairs cand_all) /\\  (Wf k l)  (c, d) = true).\n    apply filter_In.\n    assumption.\n    destruct HW as [HW1 HW2].\n    unfold Wf in HW2.\n\n    assert ( el k (c, d) = true /\\ mp k (c, d) l = true).\n    apply andb_true_iff. assumption.\n    destruct H0 as [He Hc].\n    unfold el in He.\n    simpl in He.\n    assert (Hle: edge c d <= k). apply leb_complete. assumption.\n    omega.\n    (* non-unit path *)\n    intro Hin.\n    unfold coclosed in Hcc.\n    specialize (Hcc (c, e)).   specialize (Hcc Hin).\n    unfold W in Hcc.\n    assert (HW: In (c, e) (all_pairs cand_all) /\\  (Wf k l)  (c, e) = true).\n    apply filter_In. assumption.\n    destruct HW as [HW1 HW2].\n    unfold Wf in HW2.\n    assert ( el k (c, e) = true /\\ mp k (c, e) l = true).\n    apply andb_true_iff. assumption.\n    destruct H0 as [He Hc].\n    unfold el in He.\n    simpl in He.\n    assert (Hle: edge c e <= k). apply leb_complete. assumption.\n    (*  forall b, In (b, snd p) l \\/ edge (fst p) b <= k. *)\n    assert (Hmp: forall m, In (m, (snd (c, e))) l \\/ edge (fst (c, e)) m <= k).\n    apply  forthemoment. assumption.\n    simpl in Hmp.\n    specialize (Hmp d).\n    destruct Hmp as [Hm1 | Hm2].\n    (* case 2nd part of path in coclosed list *)\n    specialize (IHp Hm1).\n    assumption.\n    (* case first edge of small weight *)\n    omega.\n  Qed.\n\n  Theorem th1: forall c, ev c -> wins c.\n  Proof.\n    intros c H.\n    unfold wins. unfold ev in H.\n    intro d.\n    specialize (H d).\n    destruct H as [k H].\n    destruct H as [Hp Hc].\n    exists k.\n    split.\n    apply equivalent. assumption.\n    intros s p.\n    destruct Hc as [l Hc].\n    destruct Hc as [Hin Hcc].\n    apply coclosednow with (x := d) (y := c) (l := l).\n    assumption.\n    assumption.\n    assumption.\n  Qed.\n\n  (* reverse process. Create evidence from winner *)\n\n  Definition geb (a b : nat) :=\n    match ge_dec a b with\n    | left _ => true\n    | right _ => false\n    end.\n\n  Theorem geb_true : forall a b,\n      geb a b = true <-> a >= b.\n  Proof.\n    split; intros. unfold geb in H. destruct ge_dec in H. assumption. inversion H.\n    unfold geb. destruct ge_dec. reflexivity. congruence.\n  Qed.\n  \n  (* elg is boolean function returns true if the edge between two candidates\n     of >= k. *)\n  Definition elg (k : nat) (p : (cand * cand)) : bool :=\n    geb (edge (fst p) (snd p)) k.\n\n  (* mp k (a, c) l (for midpoint) returns true if there's a midpoint b st.\n     the edge between a and b is >= k /\\ the pair (b, c) is in l *)\n  Definition mpg (k : nat) (p : (cand * cand)) (l : list (cand * cand)) :=\n    let a := fst p in\n    let c := snd p in\n    fold_left (fun x => fun b => andb x (andb (elg k (a, b)) (bool_in (b, c) l))) cand_all true.\n\n  Definition Of k l  := (fun p => orb (elg k p) (mpg k p l)).\n  Definition O k : list (cand * cand) -> list (cand * cand) :=\n    fun l => filter (Of k l) (all_pairs cand_all).\n\n  Lemma mpg_true : forall k p l,\n      mpg k p l = true <-> exists b, elg k (fst p, b) = true /\\ In (b, snd p) l. \n  Proof. Admitted.\n\n  Lemma in_list : forall c d, In c cand_all ->  In d cand_all -> In (c, d) (all_pairs cand_all).\n  Proof. Admitted.\n\n  Lemma gebedge_true : forall c d k, edge c d >= k <->  geb (edge c d) k = true.\n  Proof.\n    split; intros. apply geb_true. assumption.\n    apply geb_true. assumption.\n  Qed.\n\n  Fixpoint iterfun {A : Type} (f : A -> A) (n : nat) (a : A) : A :=\n    match n with\n    | 0 => a\n    | S n' => f (iterfun f n' a)\n    end.\n  \n    \n  Theorem wins_evi_1: forall k c d, Path k c d -> exists (n : nat), In (c, d) (iterfun (O k) n []).\n  Proof.\n    induction 1.\n    exists 1. simpl. unfold O, Of.\n    apply filter_In. split. apply in_list; repeat (apply cand_fin).\n    apply orb_true_iff. left. apply gebedge_true. simpl.\n    assumption.\n\n    destruct IHPath.\n    exists (S x). simpl. apply filter_In. split. apply in_list; repeat (apply cand_fin).\n    unfold Of. rewrite orb_true_iff. right. apply mpg_true.\n    simpl. exists d. split. unfold elg. simpl. apply gebedge_true. assumption.\n    assumption.\n  Qed.\n\n  Theorem wins_evi_2 : forall k n c d, In (c, d) (iterfun (O k) n []) -> Path k c d.\n  Proof.\n    intros k n. induction n. simpl. intros c d H; inversion H.\n    intros c d H. simpl in H. unfold O in H. apply filter_In in H.\n    destruct H as [H1 H2]. unfold Of in H2. apply orb_true_iff in H2.\n    destruct H2 as [H2 | H2]. unfold elg in H2; simpl in H2. apply gebedge_true in H2.\n    constructor 1. assumption.\n    apply mpg_true in H2. simpl in H2. destruct H2 as [m H2]. destruct H2 as [H3 H4].\n    apply cons with (d := m). unfold elg in H3; simpl in H3. apply gebedge_true in H3.\n    assumption.  apply (IHn m d). fold (O k) in H4. assumption.\n  Qed.\nEnd Evote.\n", "meta": {"author": "mukeshtiwari", "repo": "formalized-voting", "sha": "44c001288087c96c0fe8569dcc6c9704e68fb9aa", "save_path": "github-repos/coq/mukeshtiwari-formalized-voting", "path": "github-repos/coq/mukeshtiwari-formalized-voting/formalized-voting-44c001288087c96c0fe8569dcc6c9704e68fb9aa/Schulze.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6595383371553326}}
{"text": "Require Coq.Init.Datatypes.\nImport Coq.Init.Notations.\nNotation \"A -> B\" := (forall (_ : A), B) : type_scope.\nRequire Import Coq.Program.Tactics.\nRequire Import inductionAndFunctionsSolutions.\n\nSection lemmasExamples.\n\n  Definition twicePlusOneIsPlusTwo:\n    forall x:ThreeElementSet,\n      plusOneModThree (plusOneModThree x) = plusTwoModThree x.\n  Proof.\n  intros. induction x.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  Defined.\n\n  Definition thirdLostAfterRounding:\n    forall x y z:ThreeElementSet,\n      roundToPair (triple x y z) = pair x y.\n  Proof.\n  intros. simpl. reflexivity.\n  Defined.\n\n  Definition testAppend {x y z:ThreeElementSet} {l:Lst}:\n    append (cons x nil) (cons y (cons z l)) =\n    cons x (cons y (cons z l)).\n  Proof.\n  simpl. reflexivity. \n  Defined.\n\n  Definition appendAssoc (l m n:Lst):\n    append (append l m) n = append l (append m n).\n  Proof.\n    induction l.\n    - simpl. reflexivity.\n    - simpl. rewrite IHl. reflexivity.\n  Defined.\n\nEnd lemmasExamples.\n\nSection lemmasExercises.\n\n  Definition constantModThree:\n    forall x:FourElementSet,\n      fourModThree (constantAtZero4 x) =\n      constantAtZero (fourModThree x).\n  Proof.\n  intros. simpl. reflexivity.\n  Defined.\n\n  Definition doubleModThreeIdempotent:\n    forall x:ThreeElementSet,\n      doubleModThree (doubleModThree x) = x.\n  Proof.\n  intros. induction x.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  Defined.\n\n  Definition lengthDoubleCons:\n    forall x y:ThreeElementSet,\n    forall l:Lst,\n      length (cons y (cons x l)) = succ (succ (length l)).\n  Proof.\n  intros. induction l.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  Defined.\n  \n  Definition appendHigherAssoc (l1 l2 l3 l4:Lst):\n  append l1 (append l2 (append l3 l4)) = \n  append (append(append l1 l2) l3) l4.\n  Proof.\n  rewrite appendAssoc. rewrite appendAssoc. reflexivity.\n  Defined.\n  \n  Definition lengthLemma (l1 l2:Lst) (x:ThreeElementSet):\n  length (append l1 (append (cons x nil) l2)) =\n  succ ( length (append l1 l2)).\n  Proof.\n  simpl. induction l1.\n  - simpl. reflexivity.\n  - simpl. rewrite IHl1. reflexivity.\n  Defined.\n\nEnd lemmasExercises.", "meta": {"author": "mwpb", "repo": "introduction-univalence-coq", "sha": "106643b5aea0937740e5ea51993a21da117dca2a", "save_path": "github-repos/coq/mwpb-introduction-univalence-coq", "path": "github-repos/coq/mwpb-introduction-univalence-coq/introduction-univalence-coq-106643b5aea0937740e5ea51993a21da117dca2a/solutions/lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6595113218148856}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq fintype.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** * Exercise: Define equality type for the following datatype *)\nInductive tri :=\n| Yes | No | Maybe.\n\nPrint eq_op.\nAbout eq_op.\n(* rel T := T -> T -> bool *)\nPrint Equality.type.\n(*\nDefinition tri_eq : tri -> tri -> bool :=\n    fun a b =>\n        match a, b with\n        | Yes, Yes | No, No | Maybe, Maybe => true\n        | _, _ => false\n        end.\nLemma tri_eq_proof : Equality.axiom tri_eq.\nProof.\nby case; case; constructor.\nQed.\n\nCanonical tri_eqType :=\n    EqType tri (EqMixin tri_eq_proof).\n\nCheck (1, Yes) == (1, Maybe).\nCheck erefl : (1, Yes) == (1, Maybe) = false.\n*)\n\nCheck 'I_3. (* [0..n) *)\nPrint ordinal.\n\nDefinition tri_to_ord (t : tri) : 'I_3 :=\n    match t with\n    | Yes => inord 0\n    | No => inord 1\n    | Maybe => inord 2\n    end.\nPrint inord.\n\nDefinition ord_tri (o : 'I_3) : tri :=\n    match (o : nat) with\n    | 0 => Yes\n    | 1 => No\n    | _ => Maybe\n    end.\n\nLemma ord_triK : cancel tri_to_ord ord_tri.\nProof.\nby case ; rewrite /ord_tri /tri_to_ord inordK.\nQed.\n\nDefinition tri_eqMixin := CanEqMixin ord_triK.\nCanonical tri_eqType := EqType tri tri_eqMixin.\n\nCheck (1, Yes) == (1, Maybe).\n(* Check erefl : (1, Yes) == (1, Maybe) = false. *)\n\nRecord record : predArgType := Mk_record {\n    A : nat;\n    B : bool;\n    C : nat * nat;\n}.\n\nDefinition record_to_triple (r : record) : (nat * bool * (nat * nat)).\nProof. move: r ; by case. Defined.\nDefinition triple_to_record (t : (nat * bool * (nat * nat))) : record :=\n    match t with\n    | (a, b, c) => Mk_record a b c\n    end.\nLemma record_tripleK : cancel record_to_triple triple_to_record.\nProof.\nby case.\nQed.\n\nDefinition record_eqMixin := CanEqMixin record_tripleK.\nCanonical record_eqType := EqType record record_eqMixin.\n\nVariable test : record.\nCheck (test == test).\nCompute (Mk_record 1 true (2, 3)) == (Mk_record 2 true (2, 3)).\n\n(* Odd and even numbers *)\n\nStructure odd_nat := Odd {\n    oval :> nat;\n    oprop : odd oval\n}.\nCheck @Odd 3 erefl.\nCompute odd 3.\n\nLemma oddP (n : odd_nat) : odd n.\nProof.\nby case: n.\nQed.\n\nStructure even_nat := Even {\n    eval :> nat;\n    eprop : ~~ (odd eval)\n}.\nDefinition e2 := Even (erefl (~~ (odd 2))).\nCompute e2 + 3.\nLemma evenP (n : even_nat) : ~~ (odd n).\nProof. by case: n. Qed.\n\n(** Part 1: Arithmetics **)\n\nExample test_odd (n : odd_nat) :\n    ~~ (odd 6) && odd (n * 3).\nProof. Fail by rewrite oddP evenP. Abort.\n\nCanonical even_0 : even_nat := @Even 0 isT.\n\nLemma oddS n : ~~ (odd n) -> odd n.+1.\nProof. done. Qed.\n\nLemma evenS n : (odd n) -> ~~ (odd n.+1).\nProof.\ncase: n => // n /= ; by rewrite negbK.\nQed.\n\nCanonical odd_even (m : even_nat) : odd_nat :=\n    @Odd m.+1 (oddS (eprop m)). \nCanonical even_odd (m : odd_nat) : even_nat :=\n    @Even m.+1 (evenS (oprop m)).\n\nLemma foo (m : even_nat) : odd m.+1.\nProof.\n(* будет строить инстанс odd_nat, чтобы прийти к цели *)\n(* который построится благодаря канонам *)\n(* oddP : forall n : odd_nat, odd (oval n) *)\n(*                            odd S m *)\n(* oval ?n === S m  => triggers odd_even *)\n(* ?n = odd_even ?m *)\nby rewrite oddP.\nQed.\n\nLemma foo' (m : even_nat) : odd m.+3.\nProof.\nby rewrite oddP.\nQed.\n\n\nLemma odd_mulP (n m : odd_nat) : odd (n * m).\nProof.\ncase: n => /= n n0 ; case: m => /= m m0.\nby rewrite oddM ; apply/andP.\nQed.\n\n\n\n\nExample test_odd (n : odd_nat) :\n  ~~ (odd 6) && odd (n * 3).\nProof.\napply/andP ; split => //.\nby rewrite odd_mulP.\nQed.\n\n\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/seminar07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830606, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6594502978450278}}
{"text": "(* infotheo (c) AIST. R. Affeldt, M. Hagiwara, J. Senizergues. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat div seq choice fintype.\nFrom mathcomp Require Import tuple finfun bigop finset.\nRequire Import Reals Fourier.\nRequire Import Reals_ext Ranalysis_ext ssr_ext Rssr log2 ln_facts Rbigop proba.\nRequire Import divergence variation_dist pinsker_function partition_inequality.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope divergence_scope.\nLocal Open Scope variation_distance_scope.\nLocal Open Scope reals_ext_scope.\n\nSection Pinsker_2_bdist.\n\nVariables p q : R.\nHypothesis p01 : 0 <= p <= 1.\nHypothesis q01 : 0 <= q <= 1.\nVariable A : finType.\nHypothesis card_A : #|A| = 2%nat.\n\nLet P := bdist card_A p01.\nLet Q := bdist card_A q01.\n\nHypothesis P_dom_by_Q : P << Q.\n\nLemma pinsker_fun_p_eq c : pinsker_fun p c q = D(P || Q) - c * d(P , Q) ^ 2.\nProof.\npose A_0 := Two_set.val0 card_A.\npose A_1 := Two_set.val1 card_A.\nset pi := P A_0.\nset pj := P A_1.\nset qi := Q A_0.\nset qj := Q A_1.\nhave Hpi : pi = 1 - p.\n  rewrite /pi /= ffunE.\n  case: ifP => //; by rewrite eqxx.\nhave Hqi : qi = 1 - q.\n  rewrite /qi /= ffunE.\n  case: ifP => //; by rewrite eqxx.\nhave Hpj : pj = p.\n  rewrite /pj /= ffunE /Two_set.val1.\n  case: ifP => //; by move/eqP/enum_val_inj.\nhave Hqj : qj = q.\n  rewrite /qj /= ffunE /Two_set.val1.\n  case: ifP => //; by move/eqP/enum_val_inj.\ntransitivity (D(P || Q) - c * (Rabs (p - q) + Rabs ((1 - p) - (1 - q))) ^ 2).\n  rewrite /pinsker_fun /div /index_enum -enumT Two_set.enum big_cons big_cons big_nil addR0.\n  rewrite -/pi -/pj -/qi -/qj Hpi Hpj Hqi Hqj.\n  have -> : Two_set.val0 card_A \\in A by apply enum_valP.\n  have -> : Two_set.val1 card_A \\in A by apply enum_valP.\n  set tmp := (Rabs (_) + _) ^ 2.\n  have -> : tmp = 4 * (p - q) ^ 2.\n    rewrite /tmp (_ : 1 - p - (1 - q) = q - p); last by field.\n    rewrite id_rem_plus.\n    have -> : Rabs (q - p) = Rabs (p - q).\n      rewrite -Rabs_Ropp.\n      f_equal; by field.\n    rewrite -mulRA (_ : Rabs _ * Rabs _ = (Rabs (p - q))^2); last by rewrite /= mulR1.\n    rewrite Rabs_sq; by field.\n  rewrite [X in _ = _ + _ - X]mulRA.\n  rewrite [in X in _ = _ + _ - X](mulRC c).\n  f_equal.\n  case: p01 => Hp1 Hp2.\n  case: q01 => Hq1 Hq2.\n  case/Rle_lt_or_eq_dec : Hp1 => Hp1; last first.\n    rewrite -Hp1 !mul0R Rminus_0_r addR0 add0R !mul1R log_1 /Rdiv.\n    case/Rle_lt_or_eq_dec : Hq2 => Hq2; last first.\n      move: (@P_dom_by_Q (Two_set.val0 card_A)).\n      rewrite -/pi -/qi => abs.\n      rewrite Hqi Hq2 Rminus_diag_eq // in abs.\n      move: {abs}(abs Logic.eq_refl).\n      rewrite Hpi -Hp1 Rminus_0_r.\n      move=> abs. suff : False by done. fourier.\n    rewrite log_mult; last 2 first.\n      fourier.\n      apply Rinv_0_lt_compat; fourier.\n      rewrite log_Rinv; last by fourier.\n      rewrite log_1; by field.\n  case/Rle_lt_or_eq_dec : Hq1 => Hq1; last first.\n    move: (@P_dom_by_Q (Two_set.val1 card_A)).\n    rewrite -/pj -/qj Hqj -Hq1.\n    move/(_ Logic.eq_refl).\n    rewrite Hpj => abs.\n    rewrite abs in Hp1.\n    by apply Rlt_irrefl in Hp1.\n  rewrite /div_fct /comp /= (_ : id q = q) //.\n  case/Rle_lt_or_eq_dec : Hp2 => Hp2; last first.\n    rewrite Hp2 Rminus_diag_eq // !mul0R /Rdiv log_mult; last 2 first.\n      fourier.\n      apply Rinv_0_lt_compat; fourier.\n    rewrite log_1 Rmult_1_l log_Rinv //; by field.\n  rewrite log_mult //; last by apply Rinv_0_lt_compat.\n  rewrite log_Rinv //.\n  case/Rle_lt_or_eq_dec : Hq2 => Hq2; last first.\n    move: (@P_dom_by_Q (Two_set.val0 card_A)).\n    rewrite -/pi -/qi Hqi -Hq2 Rminus_diag_eq //.\n    move/(_ Logic.eq_refl).\n    rewrite Hpi => abs.\n    suff : False by done. fourier.\n  rewrite /Rdiv log_mult; last 2 first.\n    fourier.\n    apply Rinv_0_lt_compat; fourier.\n  rewrite log_Rinv; last by fourier.\n  by field.\ndo 2 f_equal.\nrewrite /var_dist /index_enum -enumT Two_set.enum big_cons big_cons big_nil addR0.\nby rewrite -/pi -/pj -/qi -/qj Hpi Hpj Hqi Hqj addRC.\nQed.\n\nLemma Pinsker_2_inequality_bdist : / (2 * ln 2) * d(P , Q) ^ 2 <= D(P || Q).\nProof.\nset lhs := _ * _.\nset rhs := D(_ || _).\nsuff : 0 <= rhs - lhs by move=> ?; fourier.\nrewrite -pinsker_fun_p_eq.\napply pinsker_fun_pos with p01 q01 A card_A => //.\nsplit.\n  apply Rlt_le, Rinv_0_lt_compat, Rmult_lt_0_compat.\n  fourier.\n  by apply ln_2_pos.\nby apply Rle_refl.\nQed.\n\nEnd Pinsker_2_bdist.\n\nSection Pinsker_2.\n\nVariable A : finType.\nVariables P Q : dist A.\nHypothesis card_A : #|A| = 2%nat.\nHypothesis P_dom_by_Q : P << Q.\n\nLemma Pinsker_2_inequality : / (2 * ln 2) * d(P , Q) ^ 2 <= D(P || Q).\nProof.\nmove: (charac_bdist P card_A) => [r1 [Hr1 Hp]].\nmove: (charac_bdist Q card_A) => [r2 [Hr2 Hq]].\nrewrite Hp Hq.\napply Pinsker_2_inequality_bdist.\nby rewrite /dom_by -Hp -Hq.\nQed.\n\nEnd Pinsker_2.\n\nSection Pinsker.\n\nVariable A : finType.\nVariables P Q : dist A.\nHypothesis P_dom_by_Q : P << Q.\n\nLocal Open Scope Rb_scope.\n\nLocal Notation \"0\" := (false).\nLocal Notation \"1\" := (true).\n\n(** * Pinsker's Inequality *)\n\nLemma Pinsker_inequality : / (2 * ln 2) * d(P , Q) ^ 2 <= D(P || Q).\nProof.\npose A0 := [set a | Q a <b= P a].\npose A1 := [set a | P a <b Q a].\npose A_ := fun b => match b with 0 => A0 | 1 => A1 end.\nhave cov : A_ 0 :|: A_ 1 = setT.\n  rewrite /= /A0 /A1.\n  have -> : [set x | P x <b Q x] = ~: [set x | Q x <b= P x].\n    apply/setP => a; by rewrite in_set in_setC in_set RltNge.\n  by rewrite setUCr.\nhave dis : A_ 0 :&: A_ 1 = set0.\n  rewrite /A_ /A0 /A1.\n  have -> : [set x | P x <b Q x] = ~: [set x | Q x <b= P x].\n    apply/setP => a; by rewrite in_set in_setC in_set RltNge.\n  by rewrite setICr.\npose P_A := bipart dis cov P.\npose Q_A := bipart dis cov Q.\nhave step1 : D(P_A || Q_A) <= D(P || Q) by apply partition_inequality; exact P_dom_by_Q.\nsuff : / (2 * ln 2) * d(P , Q) ^2 <= D(P_A || Q_A).\n  move=> ?; apply Rle_trans with (D(P_A || Q_A)) => //; by apply Rge_le.\nhave step2 : d( P , Q ) = d( P_A , Q_A ).\n  rewrite /var_dist.\n  transitivity (\\rsum_(a | a \\in A0) Rabs (P a - Q a) + \\rsum_(a | a \\in A1) Rabs (P a - Q a)).\n    rewrite -(@rsum_union _ _ _ (A0 :|: A1)) //; last by rewrite -setI_eq0 -dis /A_ setIC.\n    apply eq_bigl => a; by rewrite cov in_set.\n  transitivity (Rabs (P_A 0 - Q_A 0) + Rabs (P_A 1 - Q_A 1)).\n    f_equal.\n    - rewrite /P_A /Q_A /bipart /= /bipart_pmf /=.\n      transitivity (\\rsum_(a | a \\in A0) (P a - Q a)).\n        apply eq_bigr => a; rewrite /A0 in_set => Ha.\n        rewrite Rabs_pos_eq //.\n        move/RleP in Ha; by fourier.\n      rewrite big_split /= Rabs_pos_eq; last first.\n        suff : \\rsum_(a | a \\in A0)Q a <= \\rsum_(a | a \\in A0) P a.\n          move=> ?; by fourier.\n        apply: Rle_big_P_f_g => a.\n        rewrite inE; by move/RleP.\n      rewrite -(big_morph _ morph_Ropp Ropp_0) //; by field.\n    - rewrite /P_A /Q_A /bipart /= /bipart_pmf /=.\n      have [A1_card | A1_card] : #|A1| = O \\/ (0 < #|A1|)%nat.\n        destruct (#|A1|); [tauto | by right].\n      + move/eqP : A1_card; rewrite cards_eq0; move/eqP => A1_card.\n        rewrite A1_card !big_set0 Rabs_pos_eq //; [by field | fourier].\n      + transitivity (\\rsum_(a | a \\in A1) - (P a - Q a)).\n          apply eq_bigr => a; rewrite /A1 in_set => Ha.\n          rewrite Rabs_left //.\n          move/RltP in Ha; by fourier.\n        rewrite -(big_morph _  morph_Ropp Ropp_0) // big_split /= Rabs_left; last first.\n          suff : \\rsum_(a | a \\in A1) P a < \\rsum_(a | a \\in A1) Q a by move=> ?; fourier.\n          apply: Rlt_big_f_g_X => // a.\n          rewrite /A1 in_set; by move/RltP.\n        by rewrite -(big_morph _ morph_Ropp Ropp_0).\n  rewrite /index_enum -enumT Two_set.enum /=.\n    symmetry; by rewrite card_bool.\n  move=> HX.\n  rewrite /bipart_pmf big_cons /= big_cons /= big_nil /= addR0.\n  set i0 := Two_set.val0 HX.\n  set i1 := Two_set.val1 HX.\n  have : i0 <> i1.\n    apply/eqP.\n    by apply Two_set.val0_neq_val1.\n  wlog : i0 i1 / (i0 == false) && (i1 == true).\n    move=> Hwlog i0i1.\n    have : ((i0, i1) == (true, false)) || ((i0, i1) == (false, true)).\n      move: i0 i1 i0i1; by case; case.\n    case/orP; case/eqP => -> ->.\n    - by rewrite (Hwlog false true) // addRC.\n    - by apply Hwlog.\n  case/andP => /eqP ? /eqP ?; by subst i0 i1.\nrewrite step2.\napply (Pinsker_2_inequality card_bool) => /= b.\nrewrite /bipart_pmf => H.\nhave {H}H : 0%R = bipart_pmf A_ Q b. done.\nmove: (@Req_0_rmul_inv A (fun x => x \\in A_ b) (pmf Q) (Rle0f Q) H) => {H}H.\ntransitivity (\\rsum_(a | a \\in A_ b) 0%R).\n  apply eq_bigr => // a Ha.\n  apply P_dom_by_Q; by rewrite -H.\nby rewrite big_const iter_Rplus mulR0.\nQed.\n\nLemma Pinsker_inequality_weak : d(P , Q) <= sqrt (2 * D(P || Q)).\nProof.\nrewrite -(sqrt_Rsqr (d(P , Q))); last by apply pos_var_dist.\napply sqrt_le_1_alt.\napply (Rmult_le_reg_l (/ 2)); first by apply Rinv_0_lt_compat; fourier.\napply Rle_trans with (D(P || Q)); last first.\n  rewrite mulRA Rinv_l; last by move=> ?; fourier.\n  rewrite mul1R; by apply Rle_refl.\neapply Rle_trans; last by apply Pinsker_inequality.\nrewrite (_ : forall x, Rsqr x = x ^ 2); last by move=> ?; rewrite /Rsqr /pow; field.\napply Rmult_le_compat_r; first by apply le_sq.\napply Rle_Rinv; [ | fourier| ].\n- apply Rmult_lt_0_compat; [fourier | exact ln_2_pos].\n- rewrite -[X in _ <= X]mulR1.\n  apply Rmult_le_compat_l; first by fourier.\n  rewrite [X in _ <= X](_ : 1%R = ln (exp 1)); last by rewrite ln_exp.\n  apply ln_increasing_le; [fourier | exact two_e].\nQed.\n\nEnd Pinsker.\n", "meta": {"author": "johnbender", "repo": "shannon", "sha": "552c66f7c76ad687430f4fb8122a2a2b94b741ee", "save_path": "github-repos/coq/johnbender-shannon", "path": "github-repos/coq/johnbender-shannon/shannon-552c66f7c76ad687430f4fb8122a2a2b94b741ee/pinsker.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.6594502757377423}}
{"text": "Require Import Reals Interval.Tactic.\n\nGoal forall x, (-1 / 3 <= x - x <= 1 / 7)%R.\nProof.\nintros x.\ninterval with (i_autodiff x).\nQed.\n", "meta": {"author": "validsdp", "repo": "coq-interval", "sha": "4035680e718ae256601e00454279f1770e5c15e8", "save_path": "github-repos/coq/validsdp-coq-interval", "path": "github-repos/coq/validsdp-coq-interval/coq-interval-4035680e718ae256601e00454279f1770e5c15e8/testsuite/bug-20150925.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.7217432122827967, "lm_q1q2_score": 0.6594398357820082}}
{"text": "Require Import Cring.\nFrom mathcomp Require Import all_ssreflect all_algebra.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope ring_scope.\nImport GRing.Theory.\n\nSection Terre.\n\n(* Un corps quelconque                                                        *)\nVariable R : fieldType.\n\n(* Le nombre Pi                                                               *)\n\nVariable Pi : R.\n\nHypothesis NZPi : Pi != 0.\nHypothesis NZP2 : 2%:R != 0 :> R.\n\nDefinition length (r : R) := 2%:R * Pi * r.\n\nDefinition delta := 1 / (2%:R * Pi).\n\nLemma delta_length r1 r2 k  : length r1 - length r2 = k -> r1 = r2 + k * delta.\nProof.\nrewrite /length /delta => Hd.\nhave P2D0 : 2%:R * Pi != 0 by rewrite mulf_eq0 negb_or NZP2.\napply: (mulfI P2D0); rewrite mulrDr [k * _]mulrA mulr1.\nby rewrite [X in _ = _ + X]mulrC divfK // addrC -Hd subrK.\nQed.\n\nFact result r1 r2 :  length r1 - length r2 = 6%:R -> r1 = r2 + 3%:R / Pi.\nProof.\nhave->: 6%:R = (3%:R * 2%:R) :> R by rewrite -natrM.\nby move/delta_length->; rewrite !mulrA mulr1 invfM mulrA mulfK.\nQed.\n\nEnd Terre.", "meta": {"author": "thery", "repo": "lemonde", "sha": "a91665306424cfea8c4b9bdb0a1826666029b1a1", "save_path": "github-repos/coq/thery-lemonde", "path": "github-repos/coq/thery-lemonde/lemonde-a91665306424cfea8c4b9bdb0a1826666029b1a1/terre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.6593568372511034}}
{"text": "Require Import ct24.\n\nSection PermSplitPivot.\n\nVariable A : Type.\nVariable le: A -> A -> Prop.\nVariable le_dec: forall (x y: A), {le x y} + {~le x y}.\nImplicit Type l : list A.\n\nLemma Permutation_split_pivot: forall (a : A) l,\n  Permutation (fst (split_pivot A le le_dec a l) \n    ++ snd (split_pivot A le le_dec a l)) l.\nProof.\ninduction l; simpl; auto.\ndestruct (split_pivot A le le_dec a l); simpl in *.\ndestruct (le_dec a0 a); simpl; auto;\nrewrite <- Permutation_middle; constructor; auto.\nDefined.\n\nEnd PermSplitPivot.\n\nLemma permutation_split_pivot : forall (a : nat) (l : list nat),\n  Permutation (fst (split_pivot nat le le_dec a l) \n    ++ snd (split_pivot nat le le_dec a l)) l.\nProof.\napply Permutation_split_pivot.\nDefined.", "meta": {"author": "jinxinglim", "repo": "coq-chain", "sha": "e237c6b5f797f2af43237b68ff599d6cc0a8d60e", "save_path": "github-repos/coq/jinxinglim-coq-chain", "path": "github-repos/coq/jinxinglim-coq-chain/coq-chain-e237c6b5f797f2af43237b68ff599d6cc0a8d60e/contributions/ct25.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6593420673256314}}
{"text": "(* -*- mode: coq; mode: visual-line -*-  *)\nRequire Import Basics Types.\nRequire Import HoTT.Truncations.\nRequire Import Spaces.BAut Spaces.BAut.Rigid.\nRequire Import ExcludedMiddle.\n\nLocal Open Scope trunc_scope.\nLocal Open Scope path_scope.\n\n(** * The universe *)\n\n(** ** Automorphisms of the universe *)\n\n(** See \"Parametricity, automorphisms of the universe, and excluded middle\" by Booij, Escardo, Lumsdaine, Shulman. *)\n\n(** If two inequivalent types have equivalent automorphism oo-groups, then assuming LEM we can swap them and leave the rest of the universe untouched. *)\nSection SwapTypes.\n  (** Amusingly, this does not actually require univalence!  But of course, to verify [BAut A <~> BAut B] in any particular example does require univalence. *)\n  Context `{Funext} `{ExcludedMiddle}.\n  Context (A B : Type) (ne : ~(A <~> B)) (e : BAut A <~> BAut B).\n\n  Definition equiv_swap_types : Type <~> Type.\n  Proof.\n    refine (((equiv_decidable_sum (fun X:Type => merely (X=A)))^-1)\n              oE _ oE\n              (equiv_decidable_sum (fun X:Type => merely (X=A)))).\n    refine ((equiv_functor_sum_l\n               (equiv_decidable_sum (fun X => merely (X.1=B)))^-1)\n              oE _ oE\n              (equiv_functor_sum_l\n                 (equiv_decidable_sum (fun X => merely (X.1=B))))).\n    refine ((equiv_sum_assoc _ _ _)\n              oE _ oE\n              (equiv_sum_assoc _ _ _)^-1).\n    apply equiv_functor_sum_r.\n    assert (q : BAut B <~> {x : {x : Type & ~ merely (x = A)} &\n                                merely (x.1 = B)}).\n    { refine (equiv_sigma_assoc _ _ oE _).\n      apply equiv_functor_sigma_id; intros X.\n      apply equiv_iff_hprop.\n      - intros p.\n        refine (fun q => _ ; p).\n        strip_truncations.\n        destruct q.\n        exact (ne (equiv_path X B p)).\n      - exact pr2. }\n    refine (_ oE equiv_sum_symm _ _).\n    apply equiv_functor_sum'.\n    - exact (e^-1 oE q^-1).\n    - exact (q oE e).\n  Defined.\n\n  Definition equiv_swap_types_swaps : merely (equiv_swap_types A = B).\n  Proof.\n    assert (ea := (e (point _)).2). cbn in ea.\n    strip_truncations; apply tr.\n    unfold equiv_swap_types.\n    apply moveR_equiv_V.\n    rewrite (equiv_decidable_sum_l\n               (fun X => merely (X=A)) A (tr 1)).\n    assert (ne' : ~ merely (B=A))\n      by (intros p; strip_truncations; exact (ne (equiv_path A B p^))).\n    rewrite (equiv_decidable_sum_r\n               (fun X => merely (X=A)) B ne').\n    cbn.\n    apply ap, path_sigma_hprop; cbn.\n    exact ea.\n  Defined.\n\n  Definition equiv_swap_types_not_id\n    : equiv_swap_types <> equiv_idmap.\n  Proof.\n    intros p.\n    assert (q := equiv_swap_types_swaps).\n    strip_truncations.\n    apply ne.\n    apply equiv_path.\n    rewrite p in q; exact q.\n  Qed.\n\nEnd SwapTypes.\n\n(** In particular, we can swap any two distinct rigid types. *)\n\nDefinition equiv_swap_rigid `{Univalence} `{ExcludedMiddle}\n           (A B : Type) `{IsRigid A} `{IsRigid B} (ne : ~(A <~> B))\n  : Type <~> Type.\nProof.\n  refine (equiv_swap_types A B ne _).\n  apply equiv_contr_contr.\nDefined.\n\n(** Such as [Empty] and [Unit]. *)\n\nDefinition equiv_swap_empty_unit `{Univalence} `{ExcludedMiddle}\n  : Type <~> Type\n  := equiv_swap_rigid Empty Unit (fun e => e^-1 tt).\n\n(** In this case we get an untruncated witness of the swapping. *)\n\nDefinition equiv_swap_rigid_swaps `{Univalence} `{ExcludedMiddle}\n           (A B : Type) `{IsRigid A} `{IsRigid B} (ne : ~(A <~> B))\n  : equiv_swap_rigid A B ne A = B.\nProof.\n  unfold equiv_swap_rigid, equiv_swap_types.\n  apply moveR_equiv_V.\n  rewrite (equiv_decidable_sum_l\n             (fun X => merely (X=A)) A (tr 1)).\n  assert (ne' : ~ merely (B=A))\n    by (intros p; strip_truncations; exact (ne (equiv_path A B p^))).\n  rewrite (equiv_decidable_sum_r\n             (fun X => merely (X=A)) B ne').\n  cbn.\n  apply ap, path_sigma_hprop; cbn.\n  exact ((path_contr (center (BAut B)) (point (BAut B)))..1).\nDefined.\n\n(** We can also swap the products of two rigid types with another type [X], under a connectedness/truncatedness assumption. *)\n\nDefinition equiv_swap_prod_rigid  `{Univalence} `{ExcludedMiddle}\n           (X A B : Type) (n : trunc_index) (ne : ~(X*A <~> X*B))\n           `{IsRigid A} `{IsConnected n.+1 A}\n           `{IsRigid B} `{IsConnected n.+1 B}\n           `{IsTrunc n.+1 X}\n  : Type <~> Type.\nProof.\n  refine (equiv_swap_types (X*A) (X*B) ne _).\n  transitivity (BAut X).\n  - symmetry; exact (baut_prod_rigid_equiv X A n).\n  - exact (baut_prod_rigid_equiv X B n).\nDefined.\n\n(** Conversely, from some nontrivial automorphisms of the universe we can deduce nonconstructive consequences. *)\n\nDefinition lem_from_aut_type_unit_empty `{Univalence}\n           (f : Type <~> Type) (eu : f Unit = Empty)\n  : ExcludedMiddle_type.\nProof.\n  apply DNE_to_LEM, DNE_from_allneg; intros P ?.\n  exists (f P); split.\n  - intros p.\n    assert (Contr P) by (apply contr_inhabited_hprop; assumption).\n    assert (q : Unit = P)\n      by (apply path_universe_uncurried, equiv_contr_contr).\n    destruct q.\n    rewrite eu.\n    auto.\n  - intros nfp.\n    assert (q : f P = Empty)\n      by (apply path_universe_uncurried, equiv_to_empty, nfp).\n    rewrite <- eu in q.\n    apply ((ap f)^-1) in q.\n    rewrite q; exact tt.\nDefined.\n\nLemma equiv_hprop_idprod `{Univalence}\n      (A : Type) (P : Type) (a : merely A) `{IsHProp P}\n  : P <-> (P * A = A).\nProof.\n  split.\n  - intros p; apply path_universe with snd.\n    apply isequiv_adjointify with (fun a => (p,a)).\n    + intros x; reflexivity.\n    + intros [p' x].\n      apply path_prod; [ apply path_ishprop | reflexivity ].\n  - intros q.\n    strip_truncations.\n    apply equiv_path in q.\n    exact (fst (q^-1 a)).\nDefined.\n\nDefinition lem_from_aut_type_inhabited_empty `{Univalence}\n           (f : Type <~> Type)\n           (A : Type) (a : merely A) (eu : f A = Empty)\n  : ExcludedMiddle_type.\nProof.\n  apply DNE_to_LEM, DNE_from_allneg; intros P ?.\n  exists (f (P * A)); split.\n  - intros p.\n    assert (q := fst (equiv_hprop_idprod A P a) p).\n    apply (ap f) in q.\n    rewrite eu in q.\n    rewrite q; auto.\n  - intros q.\n    apply equiv_to_empty in q.\n    apply path_universe_uncurried in q.\n    rewrite <- eu in q.\n    apply ((ap f)^-1) in q.\n    exact (snd (equiv_hprop_idprod A P a) q).\nDefined.\n\n(** If you can derive a constructive taboo from an automorphism of the universe such that [g X <> X], then you get [X]-many beers; see <https://groups.google.com/d/msg/homotopytypetheory/8CV0S2DuOI8/blCo7x-B7aoJ>. *)\n\nDefinition zero_beers `{Univalence}\n           (g : Type <~> Type) (ge : g Empty <> Empty)\n  : ~~ExcludedMiddle_type.\nProof.\n  pose (f := equiv_inverse g).\n  intros nlem.\n  apply ge.\n  apply path_universe_uncurried, equiv_to_empty; intros gz.\n  apply nlem.\n  apply (lem_from_aut_type_inhabited_empty f (g Empty) (tr gz)).\n  unfold f; apply eissect.\nDefined.\n\nDefinition lem_beers `{Univalence}\n           (g : Type <~> Type) (ge : g ExcludedMiddle_type <> ExcludedMiddle_type)\n  : ~~ExcludedMiddle_type.\nProof.\n  intros nlem.\n  pose (nlem' := equiv_to_empty nlem).\n  apply path_universe_uncurried in nlem'.\n  rewrite nlem' in ge.\n  apply (zero_beers g) in ge.\n  exact (ge nlem).\nDefined.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Spaces/Universe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6593420594485943}}
{"text": "(*\nhttp://ccvanishing.hateblo.jp/entry/2013/01/06/212707\nhttps://gist.github.com/y-taka-23/4466805A\n *)\nRequire Import subset.\n\nClass TopSpace (X : Set) (Open : Subset X -> Prop) :=\n  {\n    TS_whole : Open (whole X);\n    TS_empty : Open (empty X);\n    TS_intsec : forall U1 U2 : Subset X,\n        Open U1 -> Open U2 -> Open (intsec U1 U2);\n    TS_union : forall (I : Set) (index : I -> Subset X),\n        (forall i : I, Open (index i)) -> Open (bigcup I index)\n  }.\nClass Continuous (X : Set) (XOpen : Subset X -> Prop)\n      (Y : Set) (YOpen : Subset Y -> Prop)\n      (f : X -> Y) :=\n  {\n    Conti_TopSpace_l :>\n                     TopSpace X XOpen;\n    Conti_TopSpace_r :>\n                     TopSpace Y YOpen;\n    Conti_preim :\n      forall V : Subset Y, YOpen V -> XOpen (preimage f V)\n  }.\nClass Connected (X : Set) (Open : Subset X -> Prop) (S : Subset X) :=\n  {\n    Conn_TopSpace :> TopSpace X Open;\n    Conn_insep :\n      forall U1 U2 : Subset X,\n        Open U1 -> Open U2 -> incl S (union U1 U2) ->\n        (exists x1 : X, (intsec S U1) x1) ->\n        (exists x2 : X, (intsec S U2) x2) ->\n        exists x : X, intsec S (intsec U1 U2) x\n  }.\nDefinition identity (X : Set) : X -> X := fun (x : X) => x.\n                                                   \nClass Homeomorphism (X Y : Set) (XOpen : Subset X -> Prop) (YOpen : Subset Y -> Prop) (f : X -> Y) :=\n  {\n    Homeo_conti :> Continuous X XOpen Y YOpen f;\n    Homeo_bijec :\n      exists g : Y -> X,\n        composite g f = identity X ->\n        composite f g = identity Y ->\n        Continuous Y YOpen X XOpen g\n  }.\n(*\nClass Locally_homeo (X Y : Set) (XOpen : Subset X -> Prop) (YOpen : Subset Y -> Prop) (f : X -> Y) :=\n  {\n    LH_conti :> Continuous X XOpen Y YOpen f;\n    LH_locinv :\n      forall x : X, exists U : Subset X, U x -> XOpen U -> Homeomophism U (image (restr f U)) \n*)\nSection Connectedness.\n\nVariables X Y : Set.\nVariable XOpen : Subset X -> Prop.\nVariable YOpen : Subset Y -> Prop.\nHypothesis X_TopSpace : TopSpace X XOpen.\nHypothesis Y_TopSpace : TopSpace Y YOpen.\nVariable f : X -> Y.\nHypothesis f_Continuous : Continuous X XOpen Y YOpen f.\nVariable U : Subset X.\nHypothesis U_Connected : Connected X XOpen U.\n\nInstance image_Connected : Connected Y YOpen (image f U).\nProof.\n  apply Build_Connected.\n  apply Y_TopSpace.\n  intros.\n  destruct H2.\n  destruct H3.\n  assert (exists x : X, (intsec U (intsec (preimage f U1) (preimage f U2)) x)).\n  apply Conn_insep.\n  apply f_Continuous.\n  apply H.\n  apply f_Continuous.\n  apply H0.\n  assert (incl U (preimage f (image f U))).\n  apply im_preim.\n  assert (incl (preimage f (image f U)) (preimage f (union U1 U2))).\n  apply preim_incl.\n  apply H1.\n  assert (preimage f (union U1 U2) = union (preimage f U1) (preimage f U2)).\n  apply preim_union.\n  rewrite <- H6.\n  apply (incl_trans U (preimage f (image f U)) (preimage f (union U1 U2))).\n  apply H4.\n  apply H5.\n  apply intsec_and in H2.\n  unfold image in H2.\n  destruct H2.\n  destruct H2.\n  exists x1.\n  apply intsec_and.\n  intuition.\n  unfold preimage.\n  subst.\n  apply H4.\n  apply intsec_and in H3.\n  unfold image in H3.\n  destruct H3.\n  destruct H3.\n  exists x1.\n  apply intsec_and.\n  intuition.\n  unfold preimage.\n  subst.\n  apply H4.\n  destruct H4.\n  exists (f x1).\n  apply intsec_and.\n  apply intsec_and in H4.\n  destruct H4.\n  apply intsec_and in H5.\n  unfold preimage in H5.\n  split.\n  unfold image.\n  exists x1.\n  intuition.\n  apply intsec_and.\n  apply H5.\nQed.\n\nEnd Connectedness.\n", "meta": {"author": "unaoya", "repo": "sou-ken-topos", "sha": "b4d0cc1e3949fd27623eaba036041093044b53dc", "save_path": "github-repos/coq/unaoya-sou-ken-topos", "path": "github-repos/coq/unaoya-sou-ken-topos/sou-ken-topos-b4d0cc1e3949fd27623eaba036041093044b53dc/top_space.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7431679972357831, "lm_q1q2_score": 0.6593420566182863}}
{"text": "(** * StlcProp: Properties of STLC *)\n\nRequire Import Maps.\nRequire Import Types.\nRequire Import Stlc.\nRequire Import Smallstep.\nModule STLCProp.\nImport STLC.\n\n(** In this chapter, we develop the fundamental theory of the Simply\n    Typed Lambda Calculus -- in particular, the type safety\n    theorem. *)\n\n(* ################################################################# *)\n(** * Canonical Forms *)\n\n(** As we saw for the simple calculus in the [Types] chapter, the\n    first step in establishing basic properties of reduction and types\n    is to identify the possible _canonical forms_ (i.e., well-typed\n    closed values) belonging to each type.  For [Bool], these are the boolean\n    values [ttrue] and [tfalse].  For arrow types, the canonical forms\n    are lambda-abstractions.  *)\n\nLemma canonical_forms_bool : forall t,\n  empty |- t \\in TBool ->\n  value t ->\n  (t = ttrue) \\/ (t = tfalse).\nProof.\n  intros t HT HVal.\n  inversion HVal; intros; subst; try inversion HT; auto.\nQed.\n\nLemma canonical_forms_fun : forall t T1 T2,\n  empty |- t \\in (TArrow T1 T2) ->\n  value t ->\n  exists x u, t = tabs x T1 u.\nProof.\n  intros t T1 T2 HT HVal.\n  inversion HVal; intros; subst; try inversion HT; subst; auto.\n  exists x0. exists t0.  auto.\nQed.\n\n(* ################################################################# *)\n(** * Progress *)\n\n(** The _progress_ theorem tells us that closed, well-typed\n    terms are not stuck: either a well-typed term is a value, or it\n    can take a reduction step.  The proof is a relatively\n    straightforward extension of the progress proof we saw in the\n    [Types] chapter.  We'll give the proof in English first, then\n    the formal version. *)\n\nTheorem progress : forall t T,\n     empty |- t \\in T ->\n     value t \\/ exists t', t ==> t'.\n\n(** _Proof_: By induction on the derivation of [|- t \\in T].\n\n    - The last rule of the derivation cannot be [T_Var], since a\n      variable is never well typed in an empty context.\n\n    - The [T_True], [T_False], and [T_Abs] cases are trivial, since in\n      each of these cases we can see by inspecting the rule that [t]\n      is a value.\n\n    - If the last rule of the derivation is [T_App], then [t] has the\n      form [t1 t2] for some [t1] and [t2], where [|- t1 \\in T2 -> T]\n      and [|- t2 \\in T2] for some type [T2].  By the induction\n      hypothesis, either [t1] is a value or it can take a reduction\n      step.\n\n        - If [t1] is a value, then consider [t2], which by the other\n          induction hypothesis must also either be a value or take a\n          step.\n\n            - Suppose [t2] is a value.  Since [t1] is a value with an\n              arrow type, it must be a lambda abstraction; hence [t1\n              t2] can take a step by [ST_AppAbs].\n\n            - Otherwise, [t2] can take a step, and hence so can [t1\n              t2] by [ST_App2].\n\n        - If [t1] can take a step, then so can [t1 t2] by [ST_App1].\n\n    - If the last rule of the derivation is [T_If], then [t = if t1\n      then t2 else t3], where [t1] has type [Bool].  By the IH, [t1]\n      either is a value or takes a step.\n\n        - If [t1] is a value, then since it has type [Bool] it must be\n          either [true] or [false].  If it is [true], then [t] steps\n          to [t2]; otherwise it steps to [t3].\n\n        - Otherwise, [t1] takes a step, and therefore so does [t] (by\n          [ST_If]). *)\nProof with eauto.\n  intros t T Ht.\n  remember (@empty ty) as Gamma.\n  induction Ht; subst Gamma...\n  - (* T_Var *)\n    (* contradictory: variables cannot be typed in an\n       empty context *)\n    inversion H.\n\n  - (* T_App *)\n    (* [t] = [t1 t2].  Proceed by cases on whether [t1] is a\n       value or steps... *)\n    right. destruct IHHt1...\n    + (* t1 is a value *)\n      destruct IHHt2...\n      * (* t2 is also a value *)\n        assert (exists x0 t0, t1 = tabs x0 T11 t0).\n        eapply canonical_forms_fun; eauto.\n        destruct H1 as [x0 [t0 Heq]]. subst.\n        exists ([x0:=t2]t0)...\n\n      * (* t2 steps *)\n        inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...\n\n    + (* t1 steps *)\n      inversion H as [t1' Hstp]. exists (tapp t1' t2)...\n\n  - (* T_If *)\n    right. destruct IHHt1...\n\n    + (* t1 is a value *)\n      destruct (canonical_forms_bool t1); subst; eauto.\n\n    + (* t1 also steps *)\n      inversion H as [t1' Hstp]. exists (tif t1' t2 t3)...\nQed.\n\n(** **** Exercise: 3 stars, advanced (progress_from_term_ind)  *)\n(** Show that progress can also be proved by induction on terms\n    instead of induction on typing derivations. *)\n\nTheorem progress' : forall t T,\n     empty |- t \\in T ->\n     value t \\/ exists t', t ==> t'.\nProof.\n  intros t.\n  induction t; intros T Ht; auto.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Preservation *)\n\n(** The other half of the type soundness property is the\n    preservation of types during reduction.  For this part, we'll need\n    to develop some technical machinery for reasoning about variables\n    and substitution.  Working from top to bottom (from the high-level\n    property we are actually interested in to the lowest-level\n    technical lemmas that are needed by various cases of the more\n    interesting proofs), the story goes like this:\n\n      - The _preservation theorem_ is proved by induction on a typing\n        derivation, pretty much as we did in the [Types] chapter.\n        The one case that is significantly different is the one for\n        the [ST_AppAbs] rule, whose definition uses the substitution\n        operation.  To see that this step preserves typing, we need to\n        know that the substitution itself does.  So we prove a...\n\n      - _substitution lemma_, stating that substituting a (closed)\n        term [s] for a variable [x] in a term [t] preserves the type\n        of [t].  The proof goes by induction on the form of [t] and\n        requires looking at all the different cases in the definition\n        of substitition.  This time, the tricky cases are the ones for\n        variables and for function abstractions.  In both, we discover\n        that we need to take a term [s] that has been shown to be\n        well-typed in some context [Gamma] and consider the same term\n        [s] in a slightly different context [Gamma'].  For this we\n        prove a...\n\n      - _context invariance_ lemma, showing that typing is preserved\n        under \"inessential changes\" to the context [Gamma] -- in\n        particular, changes that do not affect any of the free\n        variables of the term.  And finally, for this, we need a\n        careful definition of...\n\n      - the _free variables_ of a term -- i.e., those variables\n        mentioned in a term and not in the scope of an enclosing\n        function abstraction binding a variable of the same name.\n\n   To make Coq happy, we need to formalize the story in the opposite\n   order... *)\n\n(* ================================================================= *)\n(** ** Free Occurrences *)\n\n(** A variable [x] _appears free in_ a term _t_ if [t] contains some\n    occurrence of [x] that is not under an abstraction labeled [x].\n    For example:\n      - [y] appears free, but [x] does not, in [\\x:T->U. x y]\n      - both [x] and [y] appear free in [(\\x:T->U. x y) x]\n      - no variables appear free in [\\x:T->U. \\y:T. x y]\n\n    Formally: *)\n\nInductive appears_free_in : id -> tm -> Prop :=\n  | afi_var : forall x,\n      appears_free_in x (tvar x)\n  | afi_app1 : forall x t1 t2,\n      appears_free_in x t1 -> appears_free_in x (tapp t1 t2)\n  | afi_app2 : forall x t1 t2,\n      appears_free_in x t2 -> appears_free_in x (tapp t1 t2)\n  | afi_abs : forall x y T11 t12,\n      y <> x  ->\n      appears_free_in x t12 ->\n      appears_free_in x (tabs y T11 t12)\n  | afi_if1 : forall x t1 t2 t3,\n      appears_free_in x t1 ->\n      appears_free_in x (tif t1 t2 t3)\n  | afi_if2 : forall x t1 t2 t3,\n      appears_free_in x t2 ->\n      appears_free_in x (tif t1 t2 t3)\n  | afi_if3 : forall x t1 t2 t3,\n      appears_free_in x t3 ->\n      appears_free_in x (tif t1 t2 t3).\n\nHint Constructors appears_free_in.\n\n(** The _free variables_ of a term are just the variables that appear\n    free in it.  A term with no free variables is said to be\n    _closed_. *)\n\nDefinition closed (t:tm) :=\n  forall x, ~ appears_free_in x t.\n\n(** An _open_ term is one that is not closed (or not known to be\n    closed). *)\n\n(** **** Exercise: 1 starM (afi)  *)\n(** In the space below, write out the rules of the [appears_free_in]\n    relation in informal inference-rule notation.  (Use whatever\n    notational conventions you like -- the point of the exercise is\n    just for you to think a bit about the meaning of each rule.)\n    Although this is a rather low-level, technical definition,\n    understanding it is crucial to understanding substitution and its\n    properties, which are really the crux of the lambda-calculus. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ================================================================= *)\n(** ** Substitution *)\n\n(** To prove that substitution preserves typing, we first need a\n    technical lemma connecting free variables and typing contexts: If\n    a variable [x] appears free in a term [t], and if we know [t] is\n    well typed in context [Gamma], then it must be the case that\n    [Gamma] assigns a type to [x]. *)\n\nLemma free_in_context : forall x t T Gamma,\n   appears_free_in x t ->\n   Gamma |- t \\in T ->\n   exists T', Gamma x = Some T'.\n\n(** _Proof_: We show, by induction on the proof that [x] appears free\n      in [t], that, for all contexts [Gamma], if [t] is well typed\n      under [Gamma], then [Gamma] assigns some type to [x].\n\n      - If the last rule used is [afi_var], then [t = x], and from the\n        assumption that [t] is well typed under [Gamma] we have\n        immediately that [Gamma] assigns a type to [x].\n\n      - If the last rule used is [afi_app1], then [t = t1 t2] and [x]\n        appears free in [t1].  Since [t] is well typed under [Gamma],\n        we can see from the typing rules that [t1] must also be, and\n        the IH then tells us that [Gamma] assigns [x] a type.\n\n      - Almost all the other cases are similar: [x] appears free in a\n        subterm of [t], and since [t] is well typed under [Gamma], we\n        know the subterm of [t] in which [x] appears is well typed\n        under [Gamma] as well, and the IH gives us exactly the\n        conclusion we want.\n\n      - The only remaining case is [afi_abs].  In this case [t =\n        \\y:T11.t12] and [x] appears free in [t12], and we also know\n        that [x] is different from [y].  The difference from the\n        previous cases is that, whereas [t] is well typed under\n        [Gamma], its body [t12] is well typed under [(Gamma, y:T11)],\n        so the IH allows us to conclude that [x] is assigned some type\n        by the extended context [(Gamma, y:T11)].  To conclude that\n        [Gamma] assigns a type to [x], we appeal to lemma\n        [update_neq], noting that [x] and [y] are different\n        variables. *)\n\nProof.\n  intros x t T Gamma H H0. generalize dependent Gamma.\n  generalize dependent T.\n  induction H;\n         intros; try solve [inversion H0; eauto].\n  - (* afi_abs *)\n    inversion H1; subst.\n    apply IHappears_free_in in H7.\n    rewrite update_neq in H7; assumption.\nQed.\n\n(** Next, we'll need the fact that any term [t] that is well typed in\n    the empty context is closed (it has no free variables). *)\n\n(** **** Exercise: 2 stars, optional (typable_empty__closed)  *)\nCorollary typable_empty__closed : forall t T,\n    empty |- t \\in T  ->\n    closed t.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Sometimes, when we have a proof [Gamma |- t : T], we will need to\n    replace [Gamma] by a different context [Gamma'].  When is it safe\n    to do this?  Intuitively, it must at least be the case that\n    [Gamma'] assigns the same types as [Gamma] to all the variables\n    that appear free in [t]. In fact, this is the only condition that\n    is needed. *)\n\nLemma context_invariance : forall Gamma Gamma' t T,\n     Gamma |- t \\in T  ->\n     (forall x, appears_free_in x t -> Gamma x = Gamma' x) ->\n     Gamma' |- t \\in T.\n\n(** _Proof_: By induction on the derivation of \n    [Gamma |- t \\in T].\n\n      - If the last rule in the derivation was [T_Var], then [t = x]\n        and [Gamma x = T].  By assumption, [Gamma' x = T] as well, and\n        hence [Gamma' |- t \\in T] by [T_Var].\n\n      - If the last rule was [T_Abs], then [t = \\y:T11. t12], with [T\n        = T11 -> T12] and [Gamma, y:T11 |- t12 \\in T12].  The\n        induction hypothesis is that, for any context [Gamma''], if\n        [Gamma, y:T11] and [Gamma''] assign the same types to all the\n        free variables in [t12], then [t12] has type [T12] under\n        [Gamma''].  Let [Gamma'] be a context which agrees with\n        [Gamma] on the free variables in [t]; we must show [Gamma' |-\n        \\y:T11. t12 \\in T11 -> T12].\n\n        By [T_Abs], it suffices to show that [Gamma', y:T11 |- t12 \\in\n        T12].  By the IH (setting [Gamma'' = Gamma', y:T11]), it\n        suffices to show that [Gamma, y:T11] and [Gamma', y:T11] agree\n        on all the variables that appear free in [t12].\n\n        Any variable occurring free in [t12] must be either [y] or\n        some other variable.  [Gamma, y:T11] and [Gamma', y:T11]\n        clearly agree on [y].  Otherwise, note that any variable other\n        than [y] that occurs free in [t12] also occurs free in [t =\n        \\y:T11. t12], and by assumption [Gamma] and [Gamma'] agree on\n        all such variables; hence so do [Gamma, y:T11] and [Gamma',\n        y:T11].\n\n      - If the last rule was [T_App], then [t = t1 t2], with [Gamma |-\n        t1 \\in T2 -> T] and [Gamma |- t2 \\in T2].  One induction\n        hypothesis states that for all contexts [Gamma'], if [Gamma']\n        agrees with [Gamma] on the free variables in [t1], then [t1]\n        has type [T2 -> T] under [Gamma']; there is a similar IH for\n        [t2].  We must show that [t1 t2] also has type [T] under\n        [Gamma'], given the assumption that [Gamma'] agrees with\n        [Gamma] on all the free variables in [t1 t2].  By [T_App], it\n        suffices to show that [t1] and [t2] each have the same type\n        under [Gamma'] as under [Gamma].  But all free variables in\n        [t1] are also free in [t1 t2], and similarly for [t2]; hence\n        the desired result follows from the induction hypotheses. *)\n\nProof with eauto.\n  intros.\n  generalize dependent Gamma'.\n  induction H; intros; auto.\n  - (* T_Var *)\n    apply T_Var. rewrite <- H0...\n  - (* T_Abs *)\n    apply T_Abs.\n    apply IHhas_type. intros x1 Hafi.\n    (* the only tricky step... the [Gamma'] we use to\n       instantiate is [update Gamma x T11] *)\n    unfold update. unfold t_update. destruct (beq_id x0 x1) eqn: Hx0x1...\n    rewrite beq_id_false_iff in Hx0x1. auto.\n  - (* T_App *)\n    apply T_App with T11...\nQed.\n\n(** Now we come to the conceptual heart of the proof that reduction\n    preserves types -- namely, the observation that _substitution_\n    preserves types. *)\n\n(** Formally, the so-called _substitution lemma_ says this:\n    Suppose we have a term [t] with a free variable [x], and suppose\n    we've assigned a type [T] to [t] under the assumption that [x] has\n    some type [U].  Also, suppose that we have some other term [v] and\n    that we've shown that [v] has type [U].  Then, since [v] satisfies\n    the assumption we made about [x] when typing [t], we can\n    substitute [v] for each of the occurrences of [x] in [t] and\n    obtain a new term that still has type [T]. *)\n\n(** _Lemma_: If [Gamma,x:U |- t \\in T] and [|- v \\in U], then [Gamma |-\n    [x:=v]t \\in T]. *)\n\nLemma substitution_preserves_typing : forall Gamma x U t v T,\n     update Gamma x U |- t \\in T ->\n     empty |- v \\in U   ->\n     Gamma |- [x:=v]t \\in T.\n\n(** One technical subtlety in the statement of the lemma is that\n    we assign [v] the type [U] in the _empty_ context -- in other\n    words, we assume [v] is closed.  This assumption considerably\n    simplifies the [T_Abs] case of the proof (compared to assuming\n    [Gamma |- v \\in U], which would be the other reasonable assumption\n    at this point) because the context invariance lemma then tells us\n    that [v] has type [U] in any context at all -- we don't have to\n    worry about free variables in [v] clashing with the variable being\n    introduced into the context by [T_Abs].\n\n    The substitution lemma can be viewed as a kind of commutation\n    property.  Intuitively, it says that substitution and typing can\n    be done in either order: we can either assign types to the terms\n    [t] and [v] separately (under suitable contexts) and then combine\n    them using substitution, or we can substitute first and then\n    assign a type to [ [x:=v] t ] -- the result is the same either\n    way.\n\n    _Proof_: We show, by induction on [t], that for all [T] and\n    [Gamma], if [Gamma,x:U |- t \\in T] and [|- v \\in U], then [Gamma\n    |- [x:=v]t \\in T].\n\n      - If [t] is a variable there are two cases to consider,\n        depending on whether [t] is [x] or some other variable.\n\n          - If [t = x], then from the fact that [Gamma, x:U |- x \\in\n            T] we conclude that [U = T].  We must show that [[x:=v]x =\n            v] has type [T] under [Gamma], given the assumption that\n            [v] has type [U = T] under the empty context.  This\n            follows from context invariance: if a closed term has type\n            [T] in the empty context, it has that type in any context.\n\n          - If [t] is some variable [y] that is not equal to [x], then\n            we need only note that [y] has the same type under [Gamma,\n            x:U] as under [Gamma].\n\n      - If [t] is an abstraction [\\y:T11. t12], then the IH tells us,\n        for all [Gamma'] and [T'], that if [Gamma',x:U |- t12 \\in T']\n        and [|- v \\in U], then [Gamma' |- [x:=v]t12 \\in T'].\n\n        The substitution in the conclusion behaves differently\n        depending on whether [x] and [y] are the same variable.\n\n        First, suppose [x = y].  Then, by the definition of\n        substitution, [[x:=v]t = t], so we just need to show [Gamma |-\n        t \\in T].  But we know [Gamma,x:U |- t : T], and, since [y]\n        does not appear free in [\\y:T11. t12], the context invariance\n        lemma yields [Gamma |- t \\in T].\n\n        Second, suppose [x <> y].  We know [Gamma,x:U,y:T11 |- t12 \\in\n        T12] by inversion of the typing relation, from which\n        [Gamma,y:T11,x:U |- t12 \\in T12] follows by the context\n        invariance lemma, so the IH applies, giving us [Gamma,y:T11 |-\n        [x:=v]t12 \\in T12].  By [T_Abs], [Gamma |- \\y:T11. [x:=v]t12\n        \\in T11->T12], and by the definition of substitution (noting\n        that [x <> y]), [Gamma |- \\y:T11. [x:=v]t12 \\in T11->T12] as\n        required.\n\n      - If [t] is an application [t1 t2], the result follows\n        straightforwardly from the definition of substitution and the\n        induction hypotheses.\n\n      - The remaining cases are similar to the application case.\n\n    _Technical note_: This proof is a rare case where an\n    induction on terms, rather than typing derivations, yields a\n    simpler argument.  The reason for this is that the assumption\n    [update Gamma x U |- t \\in T] is not completely generic, in the\n    sense that one of the \"slots\" in the typing relation -- namely the\n    context -- is not just a variable, and this means that Coq's\n    native induction tactic does not give us the induction hypothesis\n    that we want.  It is possible to work around this, but the needed\n    generalization is a little tricky.  The term [t], on the other\n    hand, is completely generic. \n*)\n\nProof with eauto.\n  intros Gamma x U t v T Ht Ht'.\n  generalize dependent Gamma. generalize dependent T.\n  induction t; intros T Gamma H;\n    (* in each case, we'll want to get at the derivation of H *)\n    inversion H; subst; simpl...\n  - (* tvar *)\n    rename i into y. destruct (beq_idP x y) as [Hxy|Hxy].\n    + (* x=y *)\n      subst.\n      rewrite update_eq in H2.\n      inversion H2; subst. \n      eapply context_invariance. eassumption.\n      apply typable_empty__closed in Ht'. unfold closed in Ht'.\n      intros.  apply (Ht' x0) in H0. inversion H0.\n    + (* x<>y *)\n      apply T_Var. rewrite update_neq in H2...\n  - (* tabs *)\n    rename i into y. rename t into T. apply T_Abs.\n    destruct (beq_idP x y) as [Hxy | Hxy].\n    + (* x=y *)\n      subst. rewrite update_shadow in H5. apply H5.\n    + (* x<>y *)\n      apply IHt. eapply context_invariance...\n      intros z Hafi. unfold update, t_update.\n      destruct (beq_idP y z) as [Hyz | Hyz]; subst; trivial.\n      rewrite <- beq_id_false_iff in Hxy.\n      rewrite Hxy...\nQed.\n\n(* ================================================================= *)\n(** ** Main Theorem *)\n\n(** We now have the tools we need to prove preservation: if a closed\n    term [t] has type [T] and takes a step to [t'], then [t']\n    is also a closed term with type [T].  In other words, the small-step\n    reduction relation preserves types. *)\n\nTheorem preservation : forall t t' T,\n     empty |- t \\in T  ->\n     t ==> t'  ->\n     empty |- t' \\in T.\n\n(** _Proof_: By induction on the derivation of [|- t \\in T].\n\n    - We can immediately rule out [T_Var], [T_Abs], [T_True], and\n      [T_False] as the final rules in the derivation, since in each of\n      these cases [t] cannot take a step.\n\n    - If the last rule in the derivation is [T_App], then [t = t1\n      t2].  There are three cases to consider, one for each rule that\n      could be used to show that [t1 t2] takes a step to [t'].\n\n        - If [t1 t2] takes a step by [ST_App1], with [t1] stepping to\n          [t1'], then by the IH [t1'] has the same type as [t1], and\n          hence [t1' t2] has the same type as [t1 t2].\n\n        - The [ST_App2] case is similar.\n\n        - If [t1 t2] takes a step by [ST_AppAbs], then [t1 =\n          \\x:T11.t12] and [t1 t2] steps to [[x:=t2]t12]; the\n          desired result now follows from the fact that substitution\n          preserves types.\n\n    - If the last rule in the derivation is [T_If], then [t = if t1\n      then t2 else t3], and there are again three cases depending on\n      how [t] steps.\n\n        - If [t] steps to [t2] or [t3], the result is immediate, since\n          [t2] and [t3] have the same type as [t].\n\n        - Otherwise, [t] steps by [ST_If], and the desired conclusion\n          follows directly from the induction hypothesis. *)\n\nProof with eauto.\n  remember (@empty ty) as Gamma.\n  intros t t' T HT. generalize dependent t'.\n  induction HT;\n       intros t' HE; subst Gamma; subst;\n       try solve [inversion HE; subst; auto].\n  - (* T_App *)\n    inversion HE; subst...\n    (* Most of the cases are immediate by induction,\n       and [eauto] takes care of them *)\n    + (* ST_AppAbs *)\n      apply substitution_preserves_typing with T11...\n      inversion HT1...\nQed.\n\n(** **** Exercise: 2 stars, recommendedM (subject_expansion_stlc)  *)\n(** An exercise in the [Types] chapter asked about the _subject\n    expansion_ property for the simple language of arithmetic and\n    boolean expressions.  Does this property hold for STLC?  That is,\n    is it always the case that, if [t ==> t'] and [has_type t' T],\n    then [empty |- t \\in T]?  If so, prove it.  If not, give a\n    counter-example not involving conditionals.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(* ################################################################# *)\n(** * Type Soundness *)\n\n(** **** Exercise: 2 stars, optional (type_soundness)  *)\n(** Put progress and preservation together and show that a well-typed\n    term can _never_ reach a stuck state.  *)\n\nDefinition stuck (t:tm) : Prop :=\n  (normal_form step) t /\\ ~ value t.\n\nCorollary soundness : forall t t' T,\n  empty |- t \\in T ->\n  t ==>* t' ->\n  ~(stuck t').\nProof.\n  intros t t' T Hhas_type Hmulti. unfold stuck.\n  intros [Hnf Hnot_val]. unfold normal_form in Hnf.\n  induction Hmulti.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Uniqueness of Types *)\n\n(** **** Exercise: 3 starsM (types_unique)  *)\n(** Another nice property of the STLC is that types are unique: a\n    given term (in a given context) has at most one type. *)\n(** Formalize this statement and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 1 starM (progress_preservation_statement)  *)\n(** Without peeking at their statements above, write down the progress\n    and preservation theorems for the simply typed lambda-calculus (as \n    Coq theorems). *) \n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 starsM (stlc_variation1)  *)\n(** Suppose we add a new term [zap] with the following reduction rule\n\n                         ---------                  (ST_Zap)\n                         t ==> zap\n\nand the following typing rule:\n\n                      ----------------               (T_Zap)\n                      Gamma |- zap : T\n\n    Which of the following properties of the STLC remain true in\n    the presence of these rules?  For each property, write either\n    \"remains true\" or \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n(* FILL IN HERE *)\n      - Progress\n(* FILL IN HERE *)\n      - Preservation\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 2 starsM (stlc_variation2)  *)\n(** Suppose instead that we add a new term [foo] with the following \n    reduction rules:\n\n                       -----------------                (ST_Foo1)\n                       (\\x:A. x) ==> foo\n\n                         ------------                   (ST_Foo2)\n                         foo ==> true\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n(* FILL IN HERE *)\n      - Progress\n(* FILL IN HERE *)\n      - Preservation\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 2 starsM (stlc_variation3)  *)\n(** Suppose instead that we remove the rule [ST_App1] from the [step]\n    relation. Which of the following properties of the STLC remain\n    true in the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n(* FILL IN HERE *)\n      - Progress\n(* FILL IN HERE *)\n      - Preservation\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation4)  *)\n(** Suppose instead that we add the following new rule to the \n    reduction relation:\n\n            ----------------------------------        (ST_FunnyIfTrue)\n            (if true then t1 else t2) ==> true\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n(* FILL IN HERE *)\n      - Progress\n(* FILL IN HERE *)\n      - Preservation\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation5)  *)\n(** Suppose instead that we add the following new rule to the typing \n    relation:\n\n                 Gamma |- t1 \\in Bool->Bool->Bool\n                     Gamma |- t2 \\in Bool\n                 ------------------------------          (T_FunnyApp)\n                    Gamma |- t1 t2 \\in Bool\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n(* FILL IN HERE *)\n      - Progress\n(* FILL IN HERE *)\n      - Preservation\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation6)  *)\n(** Suppose instead that we add the following new rule to the typing \n    relation:\n\n                     Gamma |- t1 \\in Bool\n                     Gamma |- t2 \\in Bool\n                    ---------------------               (T_FunnyApp')\n                    Gamma |- t1 t2 \\in Bool\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n(* FILL IN HERE *)\n      - Progress\n(* FILL IN HERE *)\n      - Preservation\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation7)  *)\n(** Suppose we add the following new rule to the typing relation \n    of the STLC:\n\n                         ------------------- (T_FunnyAbs)\n                         |- \\x:Bool.t \\in Bool\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n(* FILL IN HERE *)\n      - Progress\n(* FILL IN HERE *)\n      - Preservation\n(* FILL IN HERE *)\n[]\n*)\n\nEnd STLCProp.\n\n(* ================================================================= *)\n(** ** Exercise: STLC with Arithmetic *)\n\n(** To see how the STLC might function as the core of a real\n    programming language, let's extend it with a concrete base\n    type of numbers and some constants and primitive\n    operators. *)\n\nModule STLCArith.\nImport STLC.\n\n(** To types, we add a base type of natural numbers (and remove\n    booleans, for brevity). *)\n\nInductive ty : Type :=\n  | TArrow : ty -> ty -> ty\n  | TNat   : ty.\n\n(** To terms, we add natural number constants, along with\n    successor, predecessor, multiplication, and zero-testing. *)\n\nInductive tm : Type :=\n  | tvar : id -> tm\n  | tapp : tm -> tm -> tm\n  | tabs : id -> ty -> tm -> tm\n  | tnat  : nat -> tm\n  | tsucc : tm -> tm\n  | tpred : tm -> tm\n  | tmult : tm -> tm -> tm\n  | tif0  : tm -> tm -> tm -> tm.\n\n(** **** Exercise: 4 starsM (stlc_arith)  *)\n(** Finish formalizing the definition and properties of the STLC\n    extended with arithmetic.  Specifically:\n\n    - Copy the core definitions and theorems for STLC that we went\n      through above (from the definition of values through the\n      Preservation theorem, inclusive), and paste it into the file at\n      this point.  Do not copy examples, exercises, etc.  (In\n      particular, make sure you don't copy any of the [] comments at\n      the end of exercises, to avoid confusing the autograder.)\n\n    - Extend the definitions of the [subst] operation and the [step]\n      relation to include appropriate clauses for the arithmetic\n      operators.\n\n    - Extend the proofs of all the properties (up to [preservation])\n      of the original STLC to deal with the new syntactic forms.  Make\n      sure Coq accepts the whole file. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd STLCArith.\n\n(** $Date: 2016-12-20 12:03:19 -0500 (Tue, 20 Dec 2016) $ *)\n\n", "meta": {"author": "lmatz", "repo": "sf", "sha": "1ef36ed6ca3fb693d6d0b795b7f76081972799e7", "save_path": "github-repos/coq/lmatz-sf", "path": "github-repos/coq/lmatz-sf/sf-1ef36ed6ca3fb693d6d0b795b7f76081972799e7/StlcProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6591854850968266}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Basic_Cons.CCC Basic_Cons.PullBack.\nRequire Import Coq_Cats.Type_Cat.Type_Cat.\n\n(** Type_Cat has pullbacks. The pullback of two functions f : a → b and \n    g : c → b is {(x, y) | f x = g y} *)\nSection PullBack.\n  Context {A B C : Type} (f : A → C) (g : B → C).\n\n  Local Hint Extern 1 =>\n  match goal with\n    [x : sig _ |- _ ] =>\n    let H := fresh \"H\" in\n    destruct x as [x H]\n  end.\n  \n  Program Definition Type_Cat_PullBack : @PullBack Type_Cat _ _ _ f g :=\n    {|\n      pullback := {x : A * B| f (fst x) = g (snd x)};\n      pullback_morph_1 := fun z => (fst (proj1_sig z));\n      pullback_morph_2 := fun z => (snd (proj1_sig z));\n      pullback_morph_ex := fun x p1 p2 H x' => (exist _ (p1 x', p2 x') _)\n    |}.\n\n  Next Obligation.\n  Proof.\n    match goal with\n      [|- ?A1 (?A2 ?x) = ?B1 (?B2 ?x)] =>\n      match goal with\n        [H : (fun w => A1 (A2 w)) = (fun w' => B1 (B2 w'))  |- _] =>\n        apply (equal_f H)\n      end\n    end.\n  Qed.    \n\n  Local Obligation Tactic := idtac.\n\n  Next Obligation.\n  Proof.  \n    intros X p1 p2 H u u' H1 H2 H3 H4.\n    destruct H3; destruct H4.\n    extensionality x.\n    set (H1x := equal_f H1 x); clearbody H1x; clear H1.\n    set (H2x := equal_f H2 x); clearbody H2x; clear H2.\n    cbn in *.\n    match goal with\n      [|- ?A = ?B] => destruct A as [[a1 a2] Ha]; destruct B as [[b1 b2] Hb]\n    end.\n    cbn in *.\n    apply sig_proof_irrelevance; cbn.\n    rewrite H1x; rewrite H2x; trivial.\n  Qed.\n\nEnd PullBack.\n\nInstance Type_Cat_Has_PullBacks : Has_PullBacks Type_Cat :=\n  fun a b c f g => Type_Cat_PullBack f g.", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/Categories/Coq_Cats/Type_Cat/PullBack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6591854784876888}}
{"text": "(* infotheo (c) AIST. R. Affeldt, M. Hagiwara, J. Senizergues. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq div.\nFrom mathcomp Require Import choice fintype finfun bigop prime binomial ssralg.\nFrom mathcomp Require Import finset fingroup finalg matrix.\nRequire Import Reals Fourier.\nRequire Import ssrR Reals_ext logb Rbigop.\nRequire Import proba entropy aep.\n\n(** * Typical Sequences *)\n\nReserved Notation \"'`TS'\".\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope entropy_scope.\nLocal Open Scope proba_scope.\n\nSection typical_sequence_definition.\n\nVariable A : finType.\nVariable P : dist A.\nVariable n : nat.\nVariable epsilon : R.\n\n(** Definition a typical sequence: *)\n\nDefinition typ_seq (t : 'rV[A]_n) :=\n  exp2 (- INR n * (`H P + epsilon)) <b= P `^ n t <b= exp2 (- INR n * (`H P - epsilon)).\n\nDefinition set_typ_seq := [set ta | typ_seq ta].\n\nEnd typical_sequence_definition.\n\nNotation \"'`TS'\" := (set_typ_seq) : typ_seq_scope.\n\nLocal Open Scope typ_seq_scope.\n\nLemma set_typ_seq_incl A (P : dist A) n epsilon : 0 <= epsilon -> forall r, 1 <= r ->\n  `TS P n (epsilon / 3) \\subset `TS P n epsilon.\nProof.\nmove=> He r Hr.\napply/subsetP => x.\nrewrite /typ_seq !inE /typ_seq.\ncase/andP. move/leRP => H2. move/leRP => H3.\napply/andP; split; apply/leRP.\n- apply/(leR_trans _ H2)/Exp_le_increasing => //.\n  rewrite !mulNR.\n  rewrite leR_oppr oppRK; apply leR_wpmul2l; first exact/leR0n.\n  apply leR_add2l, Rdiv_le => //; fourier.\n- eapply Rle_trans; first by apply H3.\n  apply Exp_le_increasing => //.\n  rewrite !mulNR.\n  rewrite leR_oppr oppRK; apply leR_wpmul2l; first exact/leR0n.\n  apply leR_add2l; rewrite leR_oppr oppRK; apply Rdiv_le => //; fourier.\nQed.\n\nSection typ_seq_prop.\n\nVariable A : finType.\nVariable P : dist A.\nVariable epsilon : R.\nVariable n : nat.\n\n(** The total number of typical sequences is upper-bounded by 2^(k*(H P + e)): *)\n\nLemma TS_sup : INR #| `TS P n epsilon | <= exp2 (INR n * (`H P + epsilon)).\nProof.\nsuff Htmp : INR #| `TS P n epsilon | * exp2 (- INR n * (`H P + epsilon)) <b= 1.\n  apply/leRP; rewrite -(mulR1 (exp2 _)) mulRC -leR_pdivr_mulr //.\n  by rewrite /Rdiv -exp2_Ropp -mulNR.\nrewrite -(pmf1 (P `^ n)).\nrewrite (_ : _ * _ = \\rsum_(x in `TS P n epsilon) (exp2 (- INR n * (`H P + epsilon)))); last first.\n  by rewrite big_const iter_addR.\napply/leRP/ler_rsum_l => //=.\n- move=> i; rewrite inE; by case/andP => /leRP.\n- move=> a _; exact/dist_ge0.\nQed.\n\nLemma typ_seq_definition_equiv x : x \\in `TS P n epsilon ->\n  exp2 (- INR n * (`H P + epsilon)) <= P `^ n x <= exp2 (- INR n * (`H P - epsilon)).\nProof.\nrewrite inE /typ_seq.\ncase/andP => H1 H2; split; by apply/leRP.\nQed.\n\nLemma typ_seq_definition_equiv2 x : x \\in `TS P n.+1 epsilon ->\n  `H P - epsilon <= - (1 / INR n.+1) * log (P `^ n.+1 x) <= `H P + epsilon.\nProof.\nrewrite inE /typ_seq.\ncase/andP => H1 H2; split;\n  apply/leRP; rewrite -(leR_pmul2l' (INR n.+1)) ?ltR0n' //;\n  rewrite div1R mulRA mulRN mulRV ?INR_eq0' // mulN1R; apply/leRP.\n- rewrite leR_oppr.\n  apply/(@Exp_le_inv 2) => //.\n  rewrite LogK //; last by apply/(ltR_leR_trans (exp2_gt0 _)); apply/leRP: H1.\n  apply/leRP; by rewrite -mulNR.\n- rewrite leR_oppl.\n  apply/(@Exp_le_inv 2) => //.\n  rewrite LogK //; last by apply/(ltR_leR_trans (exp2_gt0 _)); apply/leRP: H1.\n  apply/leRP; by rewrite -mulNR.\nQed.\n\nEnd typ_seq_prop.\n\nSection typ_seq_more_prop.\n\nVariable A : finType.\nVariable P : dist A.\nVariable epsilon : R.\nVariable n : nat.\n\nHypothesis He : 0 < epsilon.\n\nLemma Pr_TS_1 : aep_bound P epsilon <= INR n.+1 -> 1 - epsilon <= Pr (P `^ n.+1) (`TS P n.+1 epsilon).\nProof.\nmove=> k0_k.\nhave -> : Pr P `^ n.+1 (`TS P n.+1 epsilon) =\n  Pr P `^ n.+1 [set i | (i \\in `TS P n.+1 epsilon) &&\n  (0 <b P `^ n.+1 i) ].\n  apply Pr_ext.\n  apply/setP => t.\n  rewrite !inE.\n  move LHS : (typ_seq _ _ _) => [|] //=.\n  rewrite /typ_seq in LHS.\n  case/andP : LHS => /leRP LHS _.\n  exact/esym/ltRP/(ltR_leR_trans (exp2_gt0 _) LHS).\nset p := [set _ | _].\nmove: (Pr_cplt (P `^ n.+1) p) => Htmp.\nrewrite Pr_to_cplt.\nsuff ? : Pr (P `^ n.+1) (~: p) <= epsilon by apply leR_add2l; rewrite leR_oppl oppRK.\nhave -> : Pr P `^ n.+1 (~: p) =\n  Pr P `^ n.+1 [set x | P `^ n.+1 x == 0]\n  +\n  Pr P `^ n.+1 [set x | (0 <b P `^ n.+1 x) && (`| - (1 / INR n.+1) * log (P `^ n.+1 x) - `H P | >b epsilon) ].\n  have H1 : ~: p =\n    [set x | P `^ n.+1 x == 0 ] :|:\n    [set x | (0 <b P `^ n.+1 x) &&\n               (`| - (1 / INR n.+1) * log (P `^ n.+1 x) - `H P | >b epsilon)].\n    apply/setP => i.\n    rewrite !inE.\n    rewrite negb_and.\n    rewrite orbC.\n    move LHS : (_ || _) => [|].\n    + case/orP : LHS => LHS.\n      * apply/esym/orP; left.\n        rewrite -leRNgt' in LHS; move/leRP in LHS.\n        apply/eqP; rewrite eqR_le; split => //; exact: dist_ge0.\n      * rewrite /typ_seq negb_and in LHS.\n        case/orP : LHS => LHS.\n        - apply/esym.\n          case/boolP : (P `^ n.+1 i == 0) => /= H1; first by [].\n          rewrite lt0R H1 /=; apply/andP; split; first exact/leRP/dist_ge0.\n          rewrite -ltRNge' in LHS; move/ltRP in LHS.\n          apply (@Log_increasing 2) in LHS => //; last first.\n            apply/ltRP; rewrite lt0R H1 /=; exact/leRP/dist_ge0.\n          move/ltRP : LHS.\n          rewrite /exp2 ExpK // mulRC mulRN -mulNR -ltR_pdivr_mulr; last exact/ltR0n.\n          rewrite /Rdiv mulRC => /ltRP; rewrite ltR_oppr => /ltRP.\n          rewrite mulNR -ltR_subRL' => LHS.\n          rewrite mul1R geR0_norm //.\n          by move/ltRP : LHS; move/(ltR_trans He)/ltRW.\n        - rewrite leRNgt' negbK in LHS.\n          apply/esym/orP; right.\n          move/ltRP in LHS.\n          apply/andP; split; first exact/ltRP/(ltR_trans (exp2_gt0 _) LHS).\n          apply (@Log_increasing 2) in LHS => //.\n          move: LHS; rewrite /exp2 ExpK // => /ltRP.\n          rewrite mulRC mulRN -mulNR -ltR_pdivl_mulr; last exact/ltR0n.\n          rewrite oppRD oppRK => LHS.\n          have H2 : forall a b c, - a + b < c -> - c - a < - b by move=> *; fourier.\n          move/ltRP/H2 in LHS.\n          rewrite div1R mulRC mulRN -/(Rdiv _ _) leR0_norm.\n          + apply/ltRP; by rewrite ltR_oppr.\n          + apply: (leR_trans (ltRW LHS)); by fourier.\n      * move/negbT : LHS.\n        rewrite negb_or 2!negbK /typ_seq => /andP[H1 /andP[/leRP H2 /leRP H3]].\n        apply/esym/negbTE.\n        rewrite negb_or; apply/andP; split; first exact/eqP/gtR_eqF/ltRP.\n        rewrite negb_and H1 /= -leRNgt'.\n        apply (@Log_increasing_le 2) in H2 => //.\n        rewrite /exp2 ExpK // in H2.\n        move/leRP : H2.\n        rewrite mulRC mulRN -mulNR -leR_pdivl_mulr ?oppRD; last exact/ltR0n.\n        move/leRP => H2.\n        have /(_ _ _ _ H2) {H2}H2 : forall a b c, - a + - b <= c -> - c - a <= b.\n          by move=> *; fourier.\n        apply (@Log_increasing_le 2) in H3 => //; last exact/ltRP.\n        rewrite /exp2 ExpK // in H3.\n        move/leRP : H3.\n        rewrite mulRC mulRN -mulNR -leR_pdivr_mulr; last exact/ltR0n.\n        rewrite oppRD oppRK div1R mulRC mulRN => /leRP H3.\n        have /(_ _ _ _ H3) {H3}H3 : forall a b c, a <= - c + b -> - b <= - a - c.\n          by move=> *; fourier.\n        rewrite leR_Rabsl; apply/andP; split; exact/leRP.\n  rewrite H1 Pr_union_disj; last first.\n    apply disjoint_setI0.\n    rewrite disjoints_subset.\n    apply/subsetP => i.\n    rewrite !inE /= => Hi.\n    rewrite negb_and.\n    by rewrite (eqP Hi) ltRR'.\n  congr (_ + _); apply Pr_ext => i /=; by rewrite !inE.\nhave -> : Pr P `^ n.+1 [set x | P `^ n.+1 x == 0] = 0.\n  rewrite /Pr.\n  transitivity (\\rsum_(a in 'rV[A]_n.+1 | P `^ n.+1 a == 0) 0).\n    apply eq_big => // i.\n      by rewrite !inE.\n    by rewrite inE => /eqP.\n  by rewrite big_const /= iter_addR mulR0.\nrewrite add0R.\napply/(leR_trans _ (@aep _ P n _ He k0_k))/Pr_incl/subsetP => /= t.\nrewrite inE /=.\ncase/andP => H2 H3.\nrewrite inE H2 /=.\napply/ltRW'; by rewrite mulRN -mulNR.\nQed.\n\nVariable He1 : epsilon < 1.\n\n(** In particular, for k big enough, the set of typical sequences is not empty: *)\n\nLemma set_typ_seq_not0 : aep_bound P epsilon <= INR n.+1 ->\n  #| `TS P n.+1 epsilon | <> O.\nProof.\nmove/Pr_TS_1 => H.\ncase/boolP : (#| `TS P n.+1 epsilon |== O) => Heq; last by apply/eqP.\nsuff : False by done.\nrewrite cards_eq0 in Heq.\nmove/eqP in Heq.\nrewrite Heq (_ : Pr _ _ = 0) in H; last by rewrite /Pr big_set0.\nfourier.\nQed.\n\n(** the typical sequence of index 0 *)\n\nDefinition TS_0 (H : aep_bound P epsilon <= INR n.+1) : [finType of 'rV[A]_n.+1].\napply (@enum_val _ (pred_of_set (`TS P n.+1 epsilon))).\nhave -> : #| `TS P n.+1 epsilon| = #| `TS P n.+1 epsilon|.-1.+1.\n  rewrite prednK //.\n  move/set_typ_seq_not0 in H.\n  rewrite lt0n; by apply/eqP.\nexact ord0.\nDefined.\n\nLemma TS_0_is_typ_seq (k_k0 : aep_bound P epsilon <= INR n.+1) :\n  TS_0 k_k0 \\in `TS P n.+1 epsilon.\nProof. rewrite /TS_0. apply/enum_valP. Qed.\n\n(** The total number of typical sequences is lower-bounded by (1 - e)*2^(k*(H P - e))\n    for k big enough: *)\n\nLemma TS_inf : aep_bound P epsilon <= INR n.+1 ->\n  (1 - epsilon) * exp2 (INR n.+1 * (`H P - epsilon)) <= INR #| `TS P n.+1 epsilon |.\nProof.\nmove=> k0_k.\nhave H1 : 1 - epsilon <= Pr (P `^ n.+1) (`TS P n.+1 epsilon) <= 1.\n  split; by [apply Pr_TS_1 | apply Pr_1].\nhave H2 : (forall x, x \\in `TS P n.+1 epsilon ->\n  exp2 (- INR n.+1 * (`H P + epsilon)) <= P `^ n.+1 x <= exp2 (- INR n.+1 * (`H P - epsilon))).\n  by move=> x; rewrite inE /typ_seq => /andP[/leRP ? /leRP].\nmove: (wolfowitz (exp2_gt0 _) (exp2_gt0 _) H1 H2).\nrewrite mulNR exp2_Ropp {1}/Rdiv invRK; last exact/nesym/ltR_eqF.\nby case.\nQed.\n\nEnd typ_seq_more_prop.\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/typ_seq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6591854770457051}}
{"text": "(** * Natural numbers and their properties. Vladimir Voevodsky . Apr. - Sep. 2011  \n\nThis file contains the formulations and proofs of general properties of natural numbers from the univalent perspecive. *)\n\n\n\n\n\n\n(** ** Preambule *)\n\n(** Settings *)\n\nUnset Automatic Introduction. (* This line has to be removed for the file to compile with Coq8.2 *)\n\n\n\n(** Imports. *)\n\nAdd LoadPath \"../hlevel1\" .\nAdd LoadPath \"../Generalities\".\n\nRequire Export algebra1d . \n\n(** To up-stream files  *)\n\n\n\n(** ** Equality on [ nat ] *)\n\n\n(** *** Basic properties of [ paths ] on [ nat ] and the proofs of [ isdeceq ] and [ isaset ] for [ nat ] .  *) \n   \n\nLemma negpaths0sx ( x : nat ) : neg ( paths O (S x) ) .\nProof. intro. set (f:= fun n : nat => match n with O => true | S m => false end ) . apply ( negf ( @maponpaths _ _ f 0 ( S x ) ) nopathstruetofalse ) . Defined. \n\nLemma negpathssx0 ( x : nat ) : neg ( paths (S x) O ) .\nProof. intros x X. apply (negpaths0sx x (pathsinv0  X)). Defined. \n\nLemma invmaponpathsS ( n m : nat ) : paths ( S n ) ( S m ) -> paths n m .\nProof. intros n m e . set ( f := fun n : nat => match n with O => O | S m => m end ) .   apply ( @maponpaths _ _ f ( S n ) ( S m ) e ) .  Defined.  \n\nLemma noeqinjS ( x x' : nat ) : neg ( paths x x' ) -> neg ( paths (S x) (S x') ) .\nProof. intros x x'. apply ( negf ( invmaponpathsS x x' ) ) .  Defined. \n \nDefinition isdeceqnat: isdeceq nat.\nProof. unfold isdeceq.  intro x . induction x as [ | x IHx ] . intro x' .  destruct x'. apply ( ii1  ( idpath O ) ) . apply ( ii2  ( negpaths0sx x' ) ) . intro x' .  destruct x'.  apply ( ii2  (negpathssx0 x ) ) . destruct ( IHx x' ) as [ p | e ].   apply ( ii1 ( maponpaths S  p ) ) .  apply ( ii2 ( noeqinjS  _ _ e ) ) . Defined . \n\nDefinition isisolatedn ( n : nat ) : isisolated _ n .\nProof. intro. unfold isisolated . intro x' . apply isdeceqnat . Defined. \n\nTheorem isasetnat: isaset nat.\nProof.  apply (isasetifdeceq _ isdeceqnat). Defined. \n\nDefinition natset : hSet := hSetpair _ isasetnat . \n(* Canonical Structure natset . *) \n\nDefinition nateq ( x y : nat ) : hProp := hProppair ( paths x y ) ( isasetnat _ _  )  .\nDefinition isdecrelnateq : isdecrel nateq  := fun a b => isdeceqnat a b .\nDefinition natdeceq : decrel nat := decrelpair isdecrelnateq . \n(* Canonical Structure natdeceq. *)\n\nDefinition natbooleq := decreltobrel natdeceq .  \n\nDefinition natneq ( x y : nat ) : hProp := hProppair ( neg ( paths x y ) ) ( isapropneg _  )  .\nDefinition isdecrelnatneq : isdecrel natneq  := isdecnegrel _ isdecrelnateq . \nDefinition natdecneq : decrel nat := decrelpair isdecrelnatneq . \n\n(* Canonical Structure natdecneq. *) \n\nDefinition natboolneq := decreltobrel natdecneq .  \n\n(** *** [ S : nat -> nat ] is a decidable inclusion . *)\n\nTheorem isinclS : isincl S .\nProof. apply ( isinclbetweensets S isasetnat isasetnat invmaponpathsS ) .  Defined .\n\nTheorem isdecinclS : isdecincl S .\nProof. intro n . apply isdecpropif . apply ( isinclS n ) .  destruct n as [ | n ] .  assert ( nh : neg ( hfiber S 0 ) ) .  intro hf .  destruct hf as [ m e ] .  apply ( negpathssx0 _ e ) .  apply ( ii2 nh ) .  apply ( ii1 ( hfiberpair _ n ( idpath _ ) ) ) .  Defined . \n\n\n(** ** Inequalities on [ nat ] . *)\n\n\n(** *** Boolean \"less or equal\" and \"greater or equal\" on [ nat ] . *)\n\nFixpoint natgtb (n m : nat) : bool :=\nmatch n , m with\n | S n , S m => natgtb n m\n | O, _ => false\n | _, _ => true\nend.\n\n\n\n(** *** Semi-boolean \"greater\" on [ nat ] or [ natgth ]  \n\n1. Note that due to its definition [ natgth ] automatically has the property that [ natgth n m <-> natgth ( S n ) ( S m ) ] and the same applies to all other inequalities defined in this section.\n2. We choose \"greater\" as the root relation from which we define all other relations on [ nat ] because it is more natural to extend \"greater\" to integers and then to rationals than it is to extend \"less\".   *) \n\n\nDefinition natgth ( n m : nat ) := hProppair ( paths ( natgtb n m ) true ) ( isasetbool _ _ ) . \n\nLemma negnatgth0n ( n : nat ) : neg ( natgth 0 n ) .\nProof. intro n . simpl . intro np . apply ( nopathsfalsetotrue np ) .  Defined . \n\nLemma natgthsnn ( n : nat ) : natgth ( S n ) n .\nProof . intro . induction n as [ | n IHn ] . simpl . apply idpath .   apply IHn . Defined .\n\nLemma natgthsn0 ( n : nat ) : natgth ( S n ) 0 .\nProof . intro . simpl . apply idpath .  Defined . \n\nLemma negnatgth0tois0 ( n : nat ) ( ng : neg ( natgth n 0 ) ) : paths n 0 .\nProof . intro. destruct n as [ | n ] . intro.   apply idpath.  intro ng .  destruct ( ng ( natgthsn0 _ ) ) . Defined . \n\nLemma natneq0togth0 ( n : nat ) ( ne : neg ( paths n 0 ) ) : natgth n 0 .\nProof . intros . destruct n as [ | n ] . destruct ( ne ( idpath _ ) ) .  apply natgthsn0 .  Defined . \n\nLemma nat1gthtois0 ( n : nat ) ( g : natgth 1 n ) : paths n 0 .\nProof . intro . destruct n as [ | n ] . intro . apply idpath . intro x .  destruct ( negnatgth0n n x ) .  Defined .\n\nLemma istransnatgth ( n m k : nat ) : natgth n m -> natgth m k -> natgth n k .\nProof. intro. induction n as [ | n IHn ] . intros m k g . destruct ( negnatgth0n _ g ) .  intro m . destruct m as [ | m ] . intros k g g' . destruct ( negnatgth0n _ g' ) . intro k . destruct k as [ | k ] . intros . apply natgthsn0 . apply ( IHn m k ) .  Defined. \n\nLemma isirreflnatgth ( n : nat ) : neg ( natgth n n ) .\nProof. intro . induction n as [ | n IHn ] . apply ( negnatgth0n 0 ) .  apply IHn .  Defined . \n\nNotation negnatlthnn := isirreflnatgth . \n\nLemma natgthtoneq ( n m : nat ) ( g : natgth n m ) : neg ( paths n m ) .\nProof . intros . intro e . rewrite e in g . apply ( isirreflnatgth _ g ) . Defined .  \n\nLemma isasymmnatgth ( n m : nat ) : natgth n m -> natgth m n -> empty .\nProof. intros n m is is' . apply ( isirreflnatgth n ( istransnatgth _ _ _ is is' ) ) . Defined .  \n\nLemma isantisymmnegnatgth ( n m : nat ) : neg ( natgth n m ) -> neg ( natgth m n ) -> paths n m .\nProof . intro n . induction n as [ | n IHn ] . intros m ng0m ngm0  .  apply ( pathsinv0 ( negnatgth0tois0 _ ngm0 ) ) . intro m . destruct m as [ | m ] . intros ngsn0 ng0sn . destruct ( ngsn0 ( natgthsn0 _ ) ) .  intros ng1 ng2 .   apply ( maponpaths S ( IHn m ng1 ng2 ) ) .  Defined .     \n\nLemma isdecrelnatgth : isdecrel natgth .\nProof. intros n m . apply ( isdeceqbool ( natgtb n m ) true ) .  Defined .\n\nDefinition natgthdec := decrelpair isdecrelnatgth .\n\n(* Canonical Structure natgthdec . *)\n\nLemma isnegrelnatgth : isnegrel natgth .\nProof . apply isdecreltoisnegrel . apply isdecrelnatgth . Defined . \n\nLemma iscoantisymmnatgth ( n m : nat ) : neg ( natgth n m ) -> coprod ( natgth m n ) ( paths n m ) .\nProof . apply isantisymmnegtoiscoantisymm . apply isdecrelnatgth .  intros n m . apply isantisymmnegnatgth . Defined .  \n\nLemma iscotransnatgth ( n m k : nat ) : natgth n k -> hdisj ( natgth n m ) ( natgth m k ) .\nProof . intros x y z gxz .  destruct ( isdecrelnatgth x y ) as [ gxy | ngxy ] . apply ( hinhpr _ ( ii1 gxy ) ) . apply hinhpr .   apply ii2 .  destruct ( isdecrelnatgth y x ) as [ gyx | ngyx ] . apply ( istransnatgth _ _ _ gyx gxz ) .  set ( e := isantisymmnegnatgth _ _ ngxy ngyx ) . rewrite e in gxz .  apply gxz .  Defined .   \n\n\n\n\n(** *** Semi-boolean \"less\" on [ nat ] or [ natlth ] *)\n\nDefinition natlth ( n m : nat ) := natgth m n .\n\nDefinition negnatlthn0 ( n : nat ) : neg ( natlth n 0 ) := negnatgth0n n .\n\nDefinition natlthnsn ( n : nat ) : natlth n ( S n ) := natgthsnn n . \n\nDefinition negnat0lthtois0 ( n : nat ) ( nl : neg ( natlth 0 n ) ) : paths n 0 := negnatgth0tois0 n nl .\n\nDefinition natneq0to0lth ( n : nat ) ( ne : neg ( paths n 0 ) ) : natlth 0 n := natneq0togth0 n ne .\n\nDefinition natlth1tois0 ( n : nat ) ( l : natlth n 1 ) : paths n 0 := nat1gthtois0 _ l . \n\nDefinition istransnatlth ( n m k  : nat ) : natlth n m -> natlth m k -> natlth n k := fun lnm lmk => istransnatgth _ _ _ lmk lnm . \n\nDefinition isirreflnatlth ( n : nat ) : neg ( natlth n n ) := isirreflnatgth n . \n\nNotation negnatgthnn := isirreflnatlth . \n\nLemma natlthtoneq ( n m : nat ) ( g : natlth n m ) : neg ( paths n m ) .\nProof . intros . intro e . rewrite e in g . apply ( isirreflnatlth _ g ) . Defined .   \n\nDefinition isasymmnatlth ( n m : nat ) : natlth n m -> natlth m n -> empty := fun lnm lmn => isasymmnatgth _ _ lmn lnm .\n\nDefinition isantisymmnegnattth  ( n m : nat ) : neg ( natlth n m ) -> neg ( natlth m n ) -> paths n m := fun nlnm nlmn => isantisymmnegnatgth _ _ nlmn nlnm .\n\nDefinition isdecrelnatlth  : isdecrel natlth  := fun n m => isdecrelnatgth m n . \n\nDefinition natlthdec := decrelpair isdecrelnatlth .\n\n(* Canonical Structure natlthdec . *)\n\nDefinition isnegrelnatlth : isnegrel natlth := fun n m => isnegrelnatgth m n .\n\nDefinition iscoantisymmnatlth ( n m : nat ) : neg ( natlth n m ) -> coprod ( natlth m n ) ( paths n m ) .\nProof . intros n m nlnm . destruct ( iscoantisymmnatgth m n nlnm ) as [ l | e ] . apply ( ii1 l ) . apply ( ii2 ( pathsinv0 e ) ) . Defined . \n\nDefinition iscotransnatlth ( n m k : nat ) : natlth n k -> hdisj ( natlth n m ) ( natlth m k ) . \nProof . intros n m k lnk . apply ( ( pr1 islogeqcommhdisj ) ( iscotransnatgth _ _ _ lnk ) )  .  Defined .      \n\n\n\n(** *** Semi-boolean \"less or equal \" on [ nat ] or [ natleh ] *)\n\nDefinition natleh ( n m : nat ) := hProppair ( neg ( natgth n m ) ) ( isapropneg _ )  .\n\nDefinition natleh0tois0 ( n : nat ) ( l : natleh n 0 ) : paths n 0 := negnatgth0tois0 _ l .\n\nDefinition natleh0n ( n : nat ) : natleh 0 n := negnatgth0n _ .\n\nDefinition negnatlehsn0 ( n : nat ) : neg ( natleh ( S n ) 0 ) := todneg _ ( natgthsn0 n ) . \n\nDefinition negnatlehsnn ( n : nat ) : neg ( natleh ( S n ) n ) := todneg _ ( natgthsnn _ ) . \n\nDefinition  istransnatleh ( n m k : nat ) : natleh n m -> natleh m k -> natleh n k .\nProof. apply istransnegrel . unfold iscotrans. apply iscotransnatgth .  Defined.   \n\nDefinition isreflnatleh ( n : nat ) : natleh n n := isirreflnatgth n .  \n\nDefinition isantisymmnatleh ( n m : nat ) : natleh n m -> natleh m n -> paths n m := isantisymmnegnatgth n m .   \n\nDefinition isdecrelnatleh : isdecrel natleh := isdecnegrel _ isdecrelnatgth . \n\nDefinition natlehdec := decrelpair isdecrelnatleh .\n\n(* Canonical Structure natlehdec . *)\n\nDefinition isnegrelnatleh : isnegrel natleh .\nProof . apply isdecreltoisnegrel . apply isdecrelnatleh . Defined . \n\nDefinition iscoasymmnatleh ( n m : nat ) ( nl : neg ( natleh n m ) ) : natleh m n := negf ( isasymmnatgth _ _ ) nl . \n\nDefinition istotalnatleh : istotal natleh . \nProof . intros x y . destruct ( isdecrelnatleh x y ) as [ lxy | lyx ] . apply ( hinhpr _ ( ii1 lxy ) ) . apply hinhpr .   apply ii2 . apply ( iscoasymmnatleh _ _ lyx ) .   Defined . \n\n\n\n(** *** Semi-boolean \"greater or equal\" on [ nat ] or [ natgeh ] . *)\n\n\nDefinition natgeh ( n m : nat ) : hProp := hProppair ( neg ( natgth m n ) ) ( isapropneg _ ) .  \n\nDefinition nat0gehtois0 ( n : nat ) ( g : natgeh 0 n ) : paths n 0 := natleh0tois0 _ g . \n\nDefinition natgehn0 ( n : nat ) : natgeh n 0 := natleh0n n .  \n\nDefinition negnatgeh0sn ( n : nat ) : neg ( natgeh 0 ( S n ) ) := negnatlehsn0 n . \n\nDefinition negnatgehnsn ( n : nat ) : neg ( natgeh n ( S n ) ) := negnatlehsnn n . \n\nDefinition istransnatgeh ( n m k : nat ) : natgeh n m -> natgeh m k -> natgeh n k := fun gnm gmk => istransnatleh _ _ _ gmk gnm . \n\nDefinition isreflnatgeh ( n : nat ) : natgeh n n := isreflnatleh _ . \n\nDefinition isantisymmnatgeh ( n m : nat ) : natgeh n m -> natgeh m n -> paths n m := fun gnm gmn => isantisymmnatleh _ _ gmn gnm . \n\nDefinition isdecrelnatgeh : isdecrel natgeh := fun n m => isdecrelnatleh m n .\n\nDefinition natgehdec := decrelpair isdecrelnatgeh .\n\n(* Canonical Structure natgehdec . *)\n\nDefinition isnegrelnatgeh : isnegrel natgeh := fun n m => isnegrelnatleh m n . \n\nDefinition iscoasymmnatgeh ( n m : nat ) ( nl : neg ( natgeh n m ) ) : natgeh m n := iscoasymmnatleh _ _ nl . \n\nDefinition istotalnatgeh : istotal natgeh := fun n m => istotalnatleh m n .\n\n\n\n\n(** *** Simple implications between comparisons *)\n\nDefinition natgthtogeh ( n m : nat ) : natgth n m -> natgeh n m .\nProof. intros n m g . apply iscoasymmnatgeh . apply ( todneg _ g ) . Defined .\n\nDefinition natlthtoleh ( n m : nat ) : natlth n m -> natleh n m := natgthtogeh _ _ . \n\nDefinition natlehtonegnatgth ( n m : nat ) : natleh n m -> neg ( natgth n m )  .\nProof. intros n m is is' . apply ( is is' ) .  Defined . \n\nDefinition  natgthtonegnatleh ( n m : nat ) : natgth n m -> neg ( natleh n m ) := fun g l  => natlehtonegnatgth _ _ l g .   \n\nDefinition natgehtonegnatlth ( n m : nat ) : natgeh n m -> neg ( natlth n m ) := fun gnm lnm => natlehtonegnatgth _ _ gnm lnm . \n\nDefinition natlthtonegnatgeh ( n m : nat ) : natlth n m -> neg ( natgeh n m ) := fun gnm lnm => natlehtonegnatgth _ _ lnm gnm .  \n\nDefinition negnatlehtogth ( n m : nat ) : neg ( natleh n m ) -> natgth n m := isnegrelnatgth n m .   \n\nDefinition negnatgehtolth ( n m : nat ) : neg ( natgeh n m ) -> natlth n m := isnegrelnatlth n m .\n\nDefinition negnatgthtoleh ( n m : nat ) : neg ( natgth n m ) -> natleh n m .\nProof . intros n m ng . destruct ( isdecrelnatleh n m ) as [ l | nl ] . apply l . destruct ( nl ng ) .  Defined . \n\nDefinition negnatlthtogeh ( n m : nat ) : neg ( natlth n m ) -> natgeh n m := fun nl => negnatgthtoleh _ _ nl . \n\n\n(* *** Simple corollaries of implications *** *)\n\nDefinition natlehnsn ( n : nat ) : natleh n ( S n ) := natlthtoleh _ _ ( natgthsnn n ) .  \n\nDefinition natgehsnn ( n : nat ) : natgeh ( S n ) n := natlehnsn n  .\n\n\n(** *** Comparison alternatives *)\n\n\nDefinition natgthorleh ( n m : nat ) : coprod ( natgth n m ) ( natleh n m ) .\nProof . intros . apply ( isdecrelnatgth n m ) .  Defined . \n\nDefinition natlthorgeh ( n m : nat ) : coprod ( natlth n m ) ( natgeh n m ) := natgthorleh _ _ .\n\nDefinition natneqchoice ( n m : nat ) ( ne : neg ( paths n m ) ) : coprod ( natgth n m ) ( natlth n m ) .\nProof . intros . destruct ( natgthorleh n m ) as [ l | g ]  .   apply ( ii1 l ) .  destruct ( natlthorgeh n m ) as [ l' | g' ] . apply ( ii2 l' ) .  destruct ( ne ( isantisymmnatleh _ _ g g' ) ) . Defined . \n\nDefinition natlehchoice ( n m : nat ) ( l : natleh n m ) : coprod ( natlth n m ) ( paths n m ) .\nProof .  intros . destruct ( natlthorgeh n m ) as [ l' | g ] .  apply ( ii1 l' ) . apply ( ii2 ( isantisymmnatleh _ _ l g ) ) . Defined . \n\nDefinition natgehchoice ( n m : nat ) ( g : natgeh n m ) : coprod ( natgth n m ) ( paths n m ) .\nProof .  intros . destruct ( natgthorleh n m ) as [ g' | l ] .  apply ( ii1 g' ) . apply ( ii2 ( isantisymmnatleh _ _ l g ) ) .  Defined . \n\n\n\n\n(** *** Mixed transitivities *)\n\n\n\nLemma natgthgehtrans ( n m k : nat ) : natgth n m -> natgeh m k -> natgth n k .\nProof. intros n m k gnm gmk . destruct ( natgehchoice m k gmk ) as [ g' | e ] . apply ( istransnatgth _ _ _ gnm g' ) .  rewrite e in gnm  .  apply gnm . Defined. \n\nLemma natgehgthtrans ( n m k : nat ) : natgeh n m -> natgth m k -> natgth n k .\nProof. intros n m k gnm gmk . destruct ( natgehchoice n m gnm ) as [ g' | e ] . apply ( istransnatgth _ _ _ g' gmk ) .  rewrite e .  apply gmk . Defined. \n\nLemma natlthlehtrans ( n m k : nat ) : natlth n m -> natleh m k -> natlth n k .\nProof . intros n m k l1 l2 . apply ( natgehgthtrans k m n l2 l1 ) . Defined . \n\nLemma natlehlthtrans ( n m k : nat ) : natleh n m -> natlth m k -> natlth n k .\nProof . intros n m k l1 l2 . apply ( natgthgehtrans k m n l2 l1 ) . Defined . \n\n\n\n(** *** Two comparisons and [ S ] *)\n\nLemma natgthtogehsn ( n m : nat ) : natgth n m -> natgeh n ( S m ) .\nProof. intro n . induction n as [ | n IHn ] .  intros m X .  destruct ( negnatgth0n _ X ) . intros m X . destruct m as [ | m ] .  apply ( natgehn0 n ) .  apply ( IHn m X ) .  Defined . \n\nLemma natgthsntogeh ( n m : nat ) : natgth ( S n ) m -> natgeh n m .\nProof. intros n m a . apply ( natgthtogehsn ( S n ) m a ) . Defined. (* PeWa *) \n\nLemma natgehtogthsn ( n m : nat ) : natgeh n m -> natgth ( S n ) m .\nProof . intros n m X . apply ( natgthgehtrans _ n _ ) .  apply natgthsnn . apply X . Defined.  (* New *)\n\nLemma natgehsntogth ( n m : nat ) : natgeh n ( S m ) -> natgth n m .\nProof. intros n m X . apply ( natgehgthtrans _ ( S m ) _ X ) .  apply natgthsnn . Defined .  (* New *)\n\nLemma natlthtolehsn ( n m : nat ) : natlth n m -> natleh ( S n ) m .\nProof. intros n m X . apply ( natgthtogehsn m n X ) . Defined .\n\nLemma natlehsntolth ( n m : nat ) : natleh ( S n ) m -> natlth n m .\nProof.  intros n m X . apply ( natgehsntogth m n X ) .   Defined . \n\nLemma natlehtolthsn ( n m : nat ) : natleh n m -> natlth n ( S m ) . \nProof. intros n m X . apply ( natgehtogthsn m n X ) .  Defined.\n\nLemma natlthsntoleh ( n m : nat ) : natlth n ( S m ) -> natleh n m .\nProof. intros n m a . apply ( natlthtolehsn n ( S m ) a ) . Defined. (* PeWa *) \n\n\n\n(** *** Comparsion alternatives and [ S ] *)\n\n\nLemma natlehchoice2 ( n m : nat ) : natleh n m -> coprod ( natleh ( S n ) m ) ( paths n m ) .\nProof . intros n m l . destruct ( natlehchoice n m l ) as [ l' | e ] .   apply ( ii1 ( natlthtolehsn _ _ l' ) ) . apply ( ii2 e ) .  Defined . \n\n\nLemma natgehchoice2 ( n m : nat ) : natgeh n m -> coprod ( natgeh n ( S m ) ) ( paths n m ) .\nProof . intros n m g . destruct ( natgehchoice n m g ) as [ g' | e ] .   apply ( ii1 ( natgthtogehsn _ _ g' ) ) . apply ( ii2 e ) . Defined . \n\n\nLemma natgthchoice2 ( n m : nat ) : natgth n m -> coprod ( natgth n ( S m ) ) ( paths n ( S m ) ) .\nProof.  intros n m g . destruct ( natgehchoice _ _ ( natgthtogehsn _ _ g ) ) as [ g' | e ] . apply ( ii1 g' ) .  apply ( ii2 e ) .  Defined . \n\n\nLemma natlthchoice2 ( n m : nat ) : natlth n m -> coprod ( natlth ( S n ) m ) ( paths ( S n ) m ) .\nProof.  intros n m l . destruct ( natlehchoice _ _ ( natlthtolehsn _ _ l ) ) as [ l' | e ] . apply ( ii1 l' ) .  apply ( ii2 e ) .   Defined . \n   \n\n\n\n\n\n(** ** Some properties of [ plus ] on [ nat ] *)\n\n(* Addition is defined in Init/Peano.v by the following code \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*)\n\n\n(** *** The structure of the additive ablelian monoid on [ nat ] *) \n\n\nLemma natplusl0 ( n : nat ) : paths ( 0 + n ) n .\nProof . intros . apply idpath . Defined .  \n\nLemma natplusr0 ( n : nat ) : paths ( n + 0 ) n .\nProof . intro . induction n as [ | n IH n ] . apply idpath .  simpl . apply ( maponpaths S IH ) . Defined .\nHint Resolve natplusr0: natarith .\n\nLemma natplusnsm ( n m : nat ) : paths ( n + S m ) ( S n + m ) .\nProof. intro . simpl . induction n as [ | n IHn ] .  auto with natarith . simpl . intro . apply ( maponpaths S ( IHn m ) ) .  Defined . \nHint Resolve natplusnsm : natarith .\n\nLemma natpluscomm ( n m : nat ) : paths ( n + m ) ( m + n ) .\nProof. intro. induction n as [ | n IHn ] . intro . auto with natarith .  intro .  set ( int := IHn ( S m ) ) . set ( int2 := pathsinv0 ( natplusnsm n m ) ) . set ( int3 := pathsinv0 ( natplusnsm m n ) ) .  set ( int4 := pathscomp0 int2 int  ) .  apply ( pathscomp0 int4 int3 ) . Defined . \nHint Resolve natpluscomm : natarith . \n\nLemma natplusassoc ( n m k : nat ) : paths ( ( n + m ) + k ) ( n + ( m + k ) ) .\nProof . intro . induction n as [ | n IHn ] . auto with natarith . intros . simpl .  apply ( maponpaths S ( IHn m k ) ) . Defined. \nHint Resolve natplusassoc : natarith .\n\nDefinition nataddabmonoid : abmonoid := abmonoidpair ( setwithbinoppair natset ( fun n m : nat => n + m ) ) ( dirprodpair ( dirprodpair natplusassoc ( @isunitalpair natset _ 0 ( dirprodpair natplusl0 natplusr0 ) ) ) natpluscomm ) .    \n\n\n\n\n(** *** Addition and comparisons  *)\n\n\n\n(** [ natgth ] *)\n\n\n\nDefinition natgthtogths ( n m : nat ) : natgth n m -> natgth ( S n ) m  .\nProof. intros n m is . apply ( istransnatgth _ _ _ ( natgthsnn n ) is ) . Defined .\n\nDefinition negnatgthmplusnm ( n m : nat ) : neg ( natgth m ( n + m ) ) .\nProof. intros . induction n as [ | n IHn ] .  apply isirreflnatgth . apply ( istransnatleh _ _ _ IHn ( ( natlthtoleh _ _ ( natlthnsn _ ) ) ) ) .  Defined . \n\nDefinition negnatgthnplusnm ( n m : nat ) : neg ( natgth n ( n + m ) ) .\nProof. intros . rewrite ( natpluscomm n m ) .  apply ( negnatgthmplusnm m n ) .  Defined . \n\nDefinition natgthandplusl ( n m k : nat ) : natgth n m -> natgth ( k + n ) ( k + m ) .\nProof. intros n m k l . induction k as [ | k IHk ] . assumption .  assumption .  Defined . \n\nDefinition natgthandplusr ( n m k : nat ) : natgth n m -> natgth ( n + k ) ( m + k ) .\nProof. intros . rewrite ( natpluscomm n k ) . rewrite ( natpluscomm m k ) . apply natgthandplusl . assumption . Defined . \n\nDefinition natgthandpluslinv  ( n m k : nat ) : natgth ( k + n ) ( k + m ) -> natgth n m  .\nProof. intros n m k l . induction k as [ | k IHk ] . assumption .  apply ( IHk l ) . Defined .\n\nDefinition natgthandplusrinv ( n m k : nat ) :  natgth ( n + k ) ( m + k ) -> natgth n m  . \nProof. intros n m k l . rewrite ( natpluscomm n k ) in l . rewrite ( natpluscomm m k ) in l . apply ( natgthandpluslinv _ _ _ l )  . Defined . \n \n\n(** [ natlth ] *)\n\n\nDefinition natlthtolths ( n m : nat ) : natlth n m -> natlth n ( S m ) := natgthtogths _ _ . \n\nDefinition negnatlthplusnmm ( n m : nat ) : neg ( natlth ( n + m ) m )  := negnatgthmplusnm _ _ .\n\nDefinition negnatlthplusnmn ( n m : nat ) : neg ( natlth ( n + m ) n )  := negnatgthnplusnm _ _ .\n\nDefinition natlthandplusl ( n m k : nat ) : natlth n m -> natlth ( k + n ) ( k + m )  := natgthandplusl _ _ _ . \n\nDefinition natlthandplusr ( n m k : nat ) : natlth n m -> natlth ( n + k ) ( m + k ) := natgthandplusr _ _ _ .\n\nDefinition natlthandpluslinv  ( n m k : nat ) : natlth ( k + n ) ( k + m ) -> natlth n m := natgthandpluslinv _ _ _ .\n\nDefinition natlthandplusrinv ( n m k : nat ) :  natlth ( n + k ) ( m + k ) -> natlth n m := natgthandplusrinv _ _ _ . \n\n\n\n(** [ natleh ] *)\n\n\nDefinition natlehtolehs ( n m : nat ) : natleh n m -> natleh n ( S m ) .  \nProof . intros n m is . apply ( istransnatleh _ _ _ is ( natlthtoleh _ _ ( natlthnsn _ ) ) ) . Defined .\n\nDefinition natlehmplusnm ( n m : nat ) : natleh m ( n + m )  := negnatlthplusnmm _ _  .\n\nDefinition natlehnplusnm ( n m : nat ) : natleh n ( n + m ) := negnatlthplusnmn _ _  .\n\nDefinition natlehandplusl ( n m k : nat ) : natleh n m -> natleh ( k + n ) ( k + m ) := negf ( natgthandpluslinv n m k )  . \n\nDefinition natlehandplusr ( n m k : nat ) : natleh n m -> natleh ( n + k ) ( m + k ) := negf ( natgthandplusrinv n m k )  . \n\nDefinition natlehandpluslinv  ( n m k : nat ) : natleh ( k + n ) ( k + m ) -> natleh n m := negf ( natgthandplusl n m k )  .  \n\nDefinition natlehandplusrinv ( n m k : nat ) :  natleh ( n + k ) ( m + k ) -> natleh n m :=  negf ( natgthandplusr n m k ) . \n\n\n\n\n(** [ natgeh ] *)\n\n\nDefinition natgehtogehs ( n m : nat ) : natgeh n m -> natgeh ( S n ) m := natlehtolehs _ _  .\n \nDefinition natgehplusnmm ( n m : nat ) : natgeh ( n + m ) m := negnatgthmplusnm _ _ .\n\nDefinition natgehplusnmn ( n m : nat ) : natgeh ( n + m ) n := negnatgthnplusnm _ _  . \n\nDefinition natgehandplusl ( n m k : nat ) : natgeh n m -> natgeh ( k + n ) ( k + m ) := negf ( natgthandpluslinv m n k ) .  \n\nDefinition natgehandplusr ( n m k : nat ) : natgeh n m -> natgeh ( n + k ) ( m + k ) := negf ( natgthandplusrinv m n k )  . \n\nDefinition natgehandpluslinv  ( n m k : nat ) : natgeh ( k + n ) ( k + m ) -> natgeh n m := negf ( natgthandplusl m n k )  . \n\nDefinition natgehandplusrinv ( n m k : nat ) :  natgeh ( n + k ) ( m + k ) -> natgeh n m :=  negf ( natgthandplusr m n k ) . \n\n\n\n(* The following are included mainly for direct compatibility with the library hz.v *)\n\n\n\n(** *** Comparisons and [ n -> n + 1 ] *)\n\nDefinition natgthtogthp1 ( n m : nat ) : natgth n m -> natgth ( n + 1 ) m  .\nProof. intros n m is . destruct (natpluscomm 1 n) . apply (natgthtogths n m is). Defined. \n \nDefinition natlthtolthp1 ( n m : nat ) : natlth n m -> natlth n ( m + 1 ) := natgthtogthp1 _ _ . \n\nDefinition natlehtolehp1 ( n m : nat ) : natleh n m -> natleh n ( m + 1 ) .  \nProof . intros n m is . destruct (natpluscomm 1 m) . apply (natlehtolehs n m is). Defined. \n\nDefinition natgehtogehp1 ( n m : nat ) : natgeh n m -> natgeh ( n + 1 ) m := natlehtolehp1 _ _  .\n \n\n\n(** *** Two comparisons and [ n -> n + 1 ] *)\n\nLemma natgthtogehp1 ( n m : nat ) : natgth n m -> natgeh n ( m + 1 ) .\nProof. intros n m is . destruct (natpluscomm 1 m) . apply (natgthtogehsn n m is). Defined . \n\n\nLemma natgthp1togeh ( n m : nat ) : natgth ( n + 1 ) m -> natgeh n m .\nProof.   intros n m is . destruct (natpluscomm 1 n) . apply ( natgthsntogeh n m is). Defined. (* PeWa *) \n\nLemma natlehp1tolth ( n m : nat ) : natleh ( n + 1 )  m -> natlth n m .\nProof.  intros n m is . destruct (natpluscomm 1 n) . apply (natlehsntolth n m is).  Defined . \n\nLemma natlthtolehp1 ( n m : nat ) : natlth n m -> natleh ( n + 1 )  m .\nProof. intros n m is . destruct (natpluscomm 1 n) . apply (natlthtolehsn n m is). Defined .\n\nLemma natlthp1toleh ( n m : nat ) : natlth n ( m + 1 ) -> natleh n m .\nProof. intros n m is . destruct (natpluscomm 1 m) . apply (natlthsntoleh n m is). Defined. (* PeWa *) \n\nLemma natgehp1togth ( n m : nat ) : natgeh n ( m + 1 ) -> natgth n m .\nProof. intros n m is . destruct (natpluscomm 1 m) . apply (natgehsntogth n m is). Defined .  \n\n\n(** *** Comparsion alternatives and [ n -> n + 1 ] *)\n\n\nLemma natlehchoice3 ( n m : nat ) : natleh n m -> coprod ( natleh ( n + 1 )  m ) ( paths n m ) .\nProof . intros n m l . destruct ( natlehchoice n m l ) as [ l' | e ] .   apply ( ii1 ( natlthtolehp1 _ _ l' ) ) . apply ( ii2 e ) .  Defined . \n\n\nLemma natgehchoice3 ( n m : nat ) : natgeh n m -> coprod ( natgeh n ( m + 1 ) ) ( paths n m ) .\nProof . intros n m g . destruct ( natgehchoice n m g ) as [ g' | e ] .   apply ( ii1 ( natgthtogehp1 _ _ g' ) ) . apply ( ii2 e ) . Defined . \n\n\nLemma natgthchoice3 ( n m : nat ) : natgth n m -> coprod ( natgth n ( m + 1 ) ) ( paths n ( m + 1 ) ) .\nProof.  intros n m g . destruct ( natgehchoice _ _ ( natgthtogehp1 _ _ g ) ) as [ g' | e ] . apply ( ii1 g' ) .  apply ( ii2 e ) .  Defined . \n\n\nLemma natlthchoice3 ( n m : nat ) : natlth n m -> coprod ( natlth ( n + 1 )  m ) ( paths ( n + 1 )  m ) .\nProof.  intros n m l . destruct ( natlehchoice _ _ ( natlthtolehp1 _ _ l ) ) as [ l' | e ] . apply ( ii1 l' ) .  apply ( ii2 e ) .   Defined . \n   \n\n\n\n\n\n\n\n(** *** Cancellation properties of [ plus ] on [ nat ] *)\n\nLemma pathsitertoplus ( n m : nat ) : paths ( iteration S n m ) ( n + m ) .\nProof. intros .  induction n as [ | n IHn ] . apply idpath . simpl .  apply ( maponpaths S IHn ) .  Defined .\n\nLemma isinclnatplusr ( n : nat ) : isincl ( fun m : nat => m + n ) .\nProof. intro . induction n as [ | n IHn ] . apply ( isofhlevelfhomot 1 _ _ ( fun m : nat => pathsinv0 ( natplusr0 m ) ) ) . apply ( isofhlevelfweq 1 ( idweq nat ) ) .  apply ( isofhlevelfhomot 1 _ _ ( fun m : nat => pathsinv0 ( natplusnsm m n ) ) ) . simpl .   apply ( isofhlevelfgf 1 _ _ isinclS IHn ) .  Defined. \n\nLemma isinclnatplusl ( n : nat ) : isincl ( fun m : nat => n + m ) .\nProof. intro .  apply ( isofhlevelfhomot 1 _ _ ( fun m : nat => natpluscomm m n ) ( isinclnatplusr n ) ) . Defined . \n\nLemma natplusrcan ( a b c : nat ) ( is : paths ( a + c ) ( b + c ) ) : paths a b .\nProof . intros . apply ( invmaponpathsincl _ ( isinclnatplusr c ) a b ) . apply is . Defined .  \n\nLemma natpluslcan ( a b c : nat ) ( is : paths ( c + a ) ( c + b ) ) : paths a b .\nProof . intros . rewrite ( natpluscomm _ _ ) in is . rewrite ( natpluscomm c b ) in is . apply ( natplusrcan a b c  is ) .  Defined .   \n\n\nLemma iscontrhfibernatplusr ( n m : nat ) ( is : natgeh m n ) : iscontr ( hfiber ( fun i : nat => i + n ) m ) .\nProof. intros . apply iscontraprop1 .    apply isinclnatplusr . induction m as [ | m IHm ] . set ( e := natleh0tois0 _ is ) .   split with 0 . apply e .  destruct ( natlehchoice2 _ _ is ) as [ l | e ] .  set ( j := IHm l ) .  destruct j as [ j e' ] . split with ( S j ) .  simpl . apply ( maponpaths S e' ) .  split with 0 . simpl .  assumption .  Defined . \n\nLemma neghfibernatplusr ( n m : nat ) ( is : natlth m n ) : neg ( hfiber  ( fun i : nat => i + n ) m ) .\nProof. intros. intro h . destruct h as [ i e ] . rewrite ( pathsinv0 e )  in is . destruct ( natlehtonegnatgth _ _ ( natlehmplusnm i n ) is ) .  Defined .    \n\nLemma isdecinclnatplusr ( n : nat ) : isdecincl ( fun i : nat => i + n ) .\nProof. intros . intro m . apply isdecpropif . apply ( isinclnatplusr _ m ) . destruct ( natlthorgeh m n ) as [ ni | i ] .  apply ( ii2 ( neghfibernatplusr n m ni ) ) . apply ( ii1 ( pr1 ( iscontrhfibernatplusr n m i ) ) ) . Defined .  \n\n\n\n\n(** *** Some properties of [ minus ] on [ nat ] \n\nNote : minus is defined in Init/Peano.v by the following code:\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*)\n\n\nDefinition minuseq0 ( n m : nat ) ( is : natleh n m ) : paths ( n - m )%nat  0 .\nProof. intros n m . generalize n . clear n . induction m .  intros n is . rewrite ( natleh0tois0 n is ) . simpl . apply idpath. intro n . destruct n . intro . apply idpath .  apply (IHm n ) . Defined. \n\nDefinition minusgeh0 ( n m : nat ) ( is : natgeh n m ) : natgeh ( n - m ) 0%nat.\nProof. intro . induction n as [ | n IHn ] . intros.  apply isreflnatgeh. intros .  apply natgehn0 . Defined. \n\nDefinition minusgth0 ( n m : nat ) ( is : natgth n m ) : natgth ( n - m ) 0%nat .\nProof . intro n . induction n as [ | n IHn ] .  intros .  destruct (negnatgth0n _ is ) . intro m . destruct m as [ | m ] . intro . apply natgthsn0 .  intro is .  apply ( IHn m is ) .  Defined. \n\nDefinition minusgth0inv ( n m : nat ) ( is : natgth ( n - m ) 0%nat ) : natgth n m .\nProof . intro . induction n as [ | n IHn ] . intros .  destruct ( negnatgth0n _ is ) . intro . destruct m as [ | m ]. intros . apply natgthsn0.  intro . apply ( IHn m is ) . Defined. \n\n\n\nDefinition natminuseqn ( n : nat ) : paths ( n - 0 )%nat n .\nProof . intro. destruct n . apply idpath . apply idpath. Defined. \n\nDefinition natminuslehn ( n m : nat ) : natleh ( n - m ) n .\nProof . intro n. induction n as [ | n IHn ] . intro. apply isreflnatleh .  intro . destruct m as [ | m ]. apply isreflnatleh . simpl .  apply ( istransnatleh _ _ _ (IHn m) ( natlehnsn n ) ) .  Defined. \n\nDefinition natminuslthn ( n m : nat ) ( is : natgth n 0 ) ( is' : natgth m 0 ) : natlth ( n - m ) n .\nProof . intro . induction n as [ | n IHn ] . intros . destruct ( negnatgth0n _ is ) . intro m . induction m . intros . destruct ( negnatgth0n _ is' ) . intros . apply ( natlehlthtrans _ n _ ) .  apply ( natminuslehn n m )  .  apply natlthnsn . Defined. \n\nDefinition natminuslthninv (n m : nat ) ( is : natlth ( n - m ) n ) : natgth m 0 .\nProof. intro .   induction n as [ | n IHn ] . intros .  destruct ( negnatlthn0 _ is ) . intro m . destruct m as [ | m ] . intro . destruct ( negnatlthnn _ is ) .  intro .  apply ( natgthsn0 m ) . Defined. \n\n\n\nDefinition minusplusnmm ( n m : nat ) ( is : natgeh n m ) : paths ( ( n - m ) + m ) n .\nProof . intro n . induction n as [ | n IHn] . intro m . intro is . simpl . apply ( natleh0tois0 _ is ) . intro m . destruct m as [ | m ] . intro .   simpl . rewrite ( natplusr0 n ) .  apply idpath .  simpl . intro is .  rewrite ( natplusnsm ( n - m ) m ) . apply ( maponpaths S ( IHn m is ) ) .  Defined . \n\nDefinition minusplusnmmineq ( n m : nat ) : natgeh ( ( n - m ) + m ) n .\nProof. intros. destruct ( natlthorgeh n m ) as [ lt | ge ] .  rewrite ( minuseq0 _ _ ( natlthtoleh _ _ lt ) ). apply ( natgthtogeh _ _ lt ) . rewrite ( minusplusnmm _ _ ge ) . apply isreflnatgeh . Defined. \n\nDefinition plusminusnmm ( n m : nat ) : paths ( ( n + m ) - m )%nat n .\nProof. intros . set ( int1 := natgehplusnmm n m ) . apply ( natplusrcan _ _ m ) .  rewrite ( minusplusnmm _ _ int1 ) .  apply idpath. Defined. \n\n\n(* *** Two-sided minus and comparisons *)\n\nDefinition natgehandminusr ( n m k : nat ) ( is : natgeh  n m ) : natgeh ( n - k ) ( m - k ) .\nProof. intro n. induction n as [ | n IHn ] . intros .  rewrite ( nat0gehtois0 _ is ) . apply isreflnatleh .  intro m . induction m . intros . destruct k .  apply natgehn0.  apply natgehn0 .  intro k . induction k . intro is .  apply is .  intro is .  apply ( IHn m k is ) . Defined. \n\nDefinition natgehandminusl ( n m k : nat ) ( is : natgeh n m ) : natgeh ( n - k ) ( m - k ) .\nProof .  intro n. induction n as [ | n IHn ] . intros . rewrite ( nat0gehtois0 _ is ) . apply isreflnatleh .  intro m . induction m . intros . destruct k .  apply natgehn0 . apply natgehn0 .  intro k . induction k . intro is .  apply is . intro is .  apply ( IHn m k is ) .  Defined. \n\nDefinition natgehandminusrinv ( n m k : nat ) ( is' : natgeh n k ) ( is : natgeh  ( n - k ) ( m - k ) ) : natgeh n m  .\nProof. intro n. induction n as [ | n IHn ] . intros . rewrite ( nat0gehtois0 _ is' ) in is . rewrite ( natminuseqn m )  in is . rewrite ( nat0gehtois0 _ is ) . apply isreflnatleh .  intro m . induction m . intros . apply natgehn0 . intros . destruct k .  rewrite natminuseqn in is . rewrite natminuseqn in is .  apply is . apply ( IHn m k is' is ) .  Defined. \n\n(*\n\nDefinition natgehandminuslinv ( n m k : nat ) ( is' : natgeh k n ) ( is : natleh  ( k - n ) ( k - m ) ) : natgeh n m  .\nProof. intros. set ( int := natgehgthtrans _ ( k - n ) _ is ( minusgeh0 _ _ is' ) ) . set ( int' := minusgeh0inv _ _ int ) . set ( int'' := natlehandplusr _ _ n is ) . rewrite ( minusplusnmm _ _ ( natgthtogeh _ _ is' ) ) in int''.  set ( int''' := natlehandplusr _ _ m int'' ) .  rewrite ( natplusassoc _ n _ ) in int'''.   rewrite ( natpluscomm n m ) in int''' . destruct ( natplusassoc ( k - m ) m n ) in int'''. rewrite ( minusplusnmm _ _ ( natgthtogeh _ _ int' ) ) in int'''.  apply ( natgehandpluslinv _ _ k ) . apply int'''.  Defined. \n\n\n\n\n\ninduction n as [ | n IHn ] . intros . rewrite ( nat0gehtois0 _ is' ) in is . rewrite ( natminuseqn m )  in is . rewrite ( nat0gehtois0 _ is ) . apply isreflnatleh .  intro m . induction m . intros . apply natgehn0 . intros . destruct k .  rewrite natminuseqn in is . rewrite natminuseqn in is .  apply is . apply ( IHn m k is is' ) .  Defined. \n\n\n\nDefinition natgthandminusinvr ( n m k : nat ) ( is : natgth n m ) ( is' : natgth n k ) : natgth ( n - k ) ( m - k ) .\nProof . intro n. induction n as [ | n IHn ] . intros . destruct ( negnatgth0n _ is ) .  intro m . induction m . intros . destruct k .  apply natgthsn0.  apply ( IHapply natgehn0 .  intro k . induction k . intro is .  apply is .  intro is .  apply ( IHn m k is ) . Defined. \n\n\n\nDefinition natlehandminusl ( n m k : nat ) ( is : natgeh n m ) : natleh ( k - n ) ( k - m ) .\nProof. intro n. induction n as [ | n IHn ] . intros .  rewrite ( nat0gehtois0 _ is ) . apply isreflnatleh .  intro m . induction m . intros . destruct k .  apply natminuslehn . apply natminuslehn .  intro k . induction k . intro is .  apply isreflnatleh . intro is .  apply ( IHn m k ) . apply is .  Defined. \n\nDefinition natlehandminusr \n\nDefinition natlthandminusl ( n m k : nat ) ( is : natgth n m ) ( is' : natgeh k n ) : natlth ( k - n ) ( k - m ) .\nProof. intro n. induction n as [ | n IHn ] . intros .  destruct ( negnatgth0n _ is ) . intro m . induction m . intros . destruct k .  destruct ( negnatgeh0sn _ is' ) . apply ( natlehlthtrans _ k _ )  .  apply ( natminuslehn k n ) . apply natlthnsn .  intro k . induction k . intros is is'.  destruct ( negnatgeh0sn _ is' ) . intros is is' .  apply ( IHn m k is is' ) .  Defined. \n\nDefinition natlehandminusl ( n m k : nat ) ( is : natgeh n m ) : natleh ( k - n ) ( k - m ) .\nProof. intro n. induction n as [ | n IHn ] . intros .  rewrite ( nat0gehtois0 _ is ) . apply isreflnatleh .  intro m . induction m . intros . destruct k .  apply natminuslehn . apply natminuslehn .  intro k . induction k . intro is .  apply isreflnatleh . intro is .  apply ( IHn m k ) . apply is .  Defined. \n\n\nDefinition natlehandminusl ( n m k : nat ) : ( natleh n m ) -> natgeh ( k - n ) ( k - m ) := natlehandminusl m n k . \n\nDefinition natlehandminusr ( n m k : nat ) : ( natleh n m ) -> natleh ( n - k ) ( m - k ) := natgehandminusr m n k .\n\n\n \n\n(* *** One sided minus and comparisons *)\n\n\n(* *** Greater or equal and minus *)\n\n\nDefinition natgehrightminus ( n m k : nat ) ( is : natgeh ( n + m ) k ) : natgeh n ( k - m ) .\nProof. intros . \n\nDefinition natgehrightplus ( n m k : nat ) ( is : natgeh ( n - m ) k ) : natgeh n ( k + m ) .\n\nDefinition natgehleftminus ( n m k : nat ) ( is : natgeh n ( m + k ) ) : natgeh ( n - k ) m .\n\nDefinition natgehleftplus ( n m k : nat ) ( is : natgeh n ( m - k ) ) : natgeh ( n + k ) m .\n\n\n(* **** Greater and minus *)\n\n\nDefinition natgthrightminus ( n m k : nat ) ( is : natgth ( n + m ) k ) : natgth n ( k - m ) .\nProof . intros. \n\nDefinition natgthrightplus ( n m k : nat ) ( is : natgth ( n - m ) k ) : natgth n ( k + m ) .\n\nDefinition natgthleftminus ( n m k : nat ) ( is : natgth n ( m + k ) ) : natgth ( n - k ) m .\n\nDefinition natgthleftplus ( n m k : nat ) ( is : natgth n ( m - k ) ) : natgth ( n + k ) m .\\\n\n\n(* **** Less and minus *)\n\n\nDefinition natlthrightminus ( n m k : nat ) ( is : natlth ( n + m ) k ) : natlth n ( k - m ) .\n\nDefinition natlthrightplus ( n m k : nat ) ( is : natlth ( n - m ) k ) : natlth n ( k + m ) .\n\nDefinition natlthleftminus ( n m k : nat ) ( is : natlth n ( m + k ) ) : natlth ( n - k ) m .\n\nDefinition natlthleftplus ( n m k : nat ) ( is : natlth n ( m - k ) ) : natlth ( n + k ) m .\n\n\n(* **** Less or equal and minus *)\n\n\nDefinition natlehrightminus ( n m k : nat ) ( is : natleh ( n + m ) k ) : natleh n ( k - m ) .\n\nDefinition natlehrightplus ( n m k : nat ) ( is : natleh ( n - m ) k ) : natleh n ( k + m ) .\n\nDefinition natlehleftminus ( n m k : nat ) ( is : natleh n ( m + k ) ) : natleh ( n - k ) m .\n\nDefinition natlehleftplus ( n m k : nat ) ( is : natleh n ( m - k ) ) : natleh ( n + k ) m .\n\n\n\n\n\n\n\n\n\n\n(* *** Mixed plus/minus associativities. \n\nThere are four possible plus/minus associativities which are labelled by pp, pm, mp and mm depending on where in the side with the left parenthesis one has minuses and where one has pluses. Two of those - pp and mm, are unconditional. Two others require a condition to hold as equality and also provide an unconditional inequality. Alltogether we have six statements including a repeat of the usual pp associativity which we give here another name in accrdance with the general naming scheme for these statements. *)\n\nNotation natassocppeq := natplusassoc .\n\nDefinition natassocpmeq ( n m k : nat ) ( is : natgeh m k ) : paths (( n + m ) - k )%nat (n + ( m - k )).\nProof. intros.  apply ( natplusrcan _ _ k ) . rewrite ( natplusassoc n _ k ) .  rewrite ( minusplusnmm _ k is ) .  set ( is' := istransnatgeh _ _ _ ( natgehplusnmm n m ) is ) . rewrite ( minusplusnmm _ k is' ) . apply idpath. Defined. \n\nDefinition natassocpmineq ( n m k : nat ) : natleh (( n + m ) - k ) ( n + ( m - k )) .\nProof. intros n m k . destruct (natgthorleh k m) as [g | le]. \n\nset ( e := minuseq0 m k ( natgthtogeh _ _ g ) ) .   rewrite e . rewrite (natplusr0 n ).  destruct (boolchoice ( natgtb k (n+m) ) ) as [ g' | le']. set ( e' := minuseq0 (n+m) k ( natgthtogeh _ _ g' ) ) .  rewrite e' . apply natleh0n . apply ( natlehandplusrinv _ _ k ) . rewrite ( minusplusnmm _ k ) . apply natlehandplusl . apply ( natlthtoleh _ _ g ) . set ( int := falsetonegtrue _ le' ) . assumption .\n\nrewrite ( natassocpmeq _ _ _ le ) .  apply isreflnatleh . Defined.\n\n\nDefinition natassocmpeq ( n m k : nat ) ( isnm : natgeh n m ) ( ismk : natgeh m k ) : paths (( n - m ) + k )%nat (n - ( m - k ))%nat.\nProof. intros.  apply ( natplusrcan _ _ ( m - k ) ) . \n\nassert ( is' : natleh ( m - k ) n ) . apply ( istransnatleh _ _ _ (natminuslehn _ _ ) isnm ) . rewrite ( minusplusnmm _ _ is' ) . rewrite (natplusassoc _ k _ ) .  rewrite ( natpluscomm k _ ) . rewrite ( minusplusnmm _ _ ismk ) . rewrite ( minusplusnmm _ _ isnm ) . apply idpath. Defined. \n\n\nDefinition natassocmpineq ( n m k : nat ) : natgeh (( n - m ) + k ) ( n - ( m - k )) .\nProof. intros n m k . destruct (natgthorleh k m) as [g | le]. \n\nset ( e := minuseq0 m k ( natgthtogeh _ _ g ) ) .   rewrite e . rewrite ( natminuseqn n ) . apply ( natgehandplusrinv _ _ m ) . rewrite ( natplusassoc _ _ m ) .  rewrite ( natpluscomm _ m ) . destruct ( natplusassoc ( n - m ) m k ) . assert ( int1 : natgeh (n - m + m + k ) ( n + k ) ) .  apply ( natgehandplusr _ _ k ) .  apply minusplusnmmineq . assert ( int2 : natgeh (n + k ) (n + m ) ) . apply ( natgehandplusl _ _ n ) . apply ( natgthtogeh _ _ g ) .  apply ( istransnatgeh _ _ _ int1 int2 ) .  \n\ndestruct ( natgthorleh m n ) as [g' | le']. rewrite ( minuseq0 _ _ ( natgthtogeh _ _ g' ) ) . change ( 0 + k ) with k .   apply ( natgehandplusrinv _ _ (m - k ) ) .  rewrite ( natpluscomm k _ ) . rewrite ( minusplusnmm _ _ le ) .  \n\ndestruct ( natgthorleh ( m - k ) n ) as [ g'' | le'' ] . rewrite ( minuseq0 n ( m - k ) ( natgthtogeh _ _ g'' ) ) .   apply ( natminuslehn  m k ) . rewrite ( minusplusnmm _ _ le'' ) .  apply ( natgthtogeh _ _ g' ) .  \n\nrewrite ( natassocmpeq _ _ _ le' le ) . apply isreflnatgeh .  Defined. \n\n\nDefinition natassocmmeq ( n m k : nat ) : paths (( n  - m ) - k )%nat (n - ( m + k ))%nat.\nProof. intros.  destruct ( natgthorleh ( m + k ) n ) as [ g | le ] . \n\nrewrite ( minuseq0 _ _ ( natgthtogeh _ _ g ) ) .  assert ( int1 : natleh ( n - m ) k ) . rewrite natpluscomm in g . set ( int2 := natgehandminusr _ _ m ( natgthtogeh _ _ g ) ) .  rewrite plusminusnmm in int2 .  apply int2 .  apply ( minuseq0 _ _ int1 ) . apply ( natplusrcan _ _ ( m + k ) ) .   rewrite ( minusplusnmm _ ( m + k )%nat ) . rewrite ( natpluscomm m k ) . destruct ( natplusassoc ( n - m - k ) k m ) .   rewrite \n\n\n\n\n\n\n\n\napply ( natplusrcan _ _ k ) . rewrite ( natplusassoc n _ k ) .  rewrite ( minusplusnmm _ k is ) .  set ( is' := istransnatgeh _ _ _ ( natgehplusnmm n m ) is ) . rewrite ( minusplusnmm _ k is' ) .apply idpath. Defined. \n\nDefinition natassocpmineq ( n m k : nat ) : natleh (( n + m ) - k ) ( n + ( m - k )) .\nProof. intros n m k . destruct (natgthorleh k m) as [g | le]. \n\nset ( e := minuseq0 m k ( natgthtogeh _ _ g ) ) .   rewrite e . rewrite (natplusr0 n ).  destruct (boolchoice ( natgtb k (n+m) ) ) as [ g' | le']. set ( e' := minuseq0 (n+m) k ( natgthtogeh _ _ g' ) ) .  rewrite e' . apply natleh0n . apply ( natlehandplusrinv _ _ k ) . rewrite ( minusplusnmm _ k ) . apply natlehandplusl . apply ( natlthtoleh _ _ g ) . set ( int := falsetonegtrue _ le' ) . assumption .\n\nrewrite ( natassocpmeq _ _ _ le ) .  apply isreflnatleh . Defined.\n\n \n\n\n\n*)\n\n\n\n\n\n\n(** ** Some properties of [ mult ] on [ nat ] \n\nNote : multiplication is defined in Init/Peano.v by the following code:\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\n*)\n\n(** *** Basic algebraic properties of [ mult ] on [ nat ] *)\n\nLemma natmult0n ( n : nat ) : paths ( 0 * n ) 0 .\nProof. intro n . apply idpath . Defined . \nHint Resolve natmult0n : natarith .\n\nLemma natmultn0 ( n : nat ) : paths ( n * 0 ) 0 .\nProof. intro n . induction n as [ | n IHn ] . apply idpath . simpl .   assumption .  Defined . \nHint Resolve natmultn0 : natarith .\n\nLemma multsnm ( n m : nat ) : paths ( ( S n ) * m ) ( m + n * m ) .\nProof. intros . apply idpath . Defined .\nHint Resolve multsnm : natarith .\n\nLemma multnsm ( n m : nat ) : paths ( n * ( S m ) ) ( n + n * m ) .\nProof. intro n . induction n as [ | n IHn ] . intro .  simpl .  apply idpath .  intro m .  simpl . apply ( maponpaths S ) .  rewrite ( pathsinv0 ( natplusassoc n m ( n * m ) ) ) .  rewrite ( natpluscomm n m ) .  rewrite ( natplusassoc m n ( n * m ) ) .  apply ( maponpaths ( fun x : nat => m + x ) ( IHn m ) ) .  Defined . \nHint Resolve multnsm : natarith .\n\nLemma natmultcomm ( n m : nat ) : paths ( n * m ) ( m * n ) .\nProof. intro . induction n as [ | n IHn ] . intro .  auto with natarith . intro m .  rewrite ( multsnm n m ) .  rewrite ( multnsm m n ) .  apply ( maponpaths ( fun x : _ => m + x ) ( IHn m ) ) .   Defined .\n\nLemma natrdistr ( n m k : nat ) : paths ( ( n + m ) * k ) ( n * k + m * k ) .\nProof . intros . induction n as [ | n IHn ] . auto with natarith .   simpl . rewrite ( natplusassoc k ( n * k ) ( m * k ) ) .   apply ( maponpaths ( fun x : _ => k + x ) ( IHn ) ) .  Defined . \n  \nLemma natldistr ( m k n : nat ) : paths ( n * ( m + k ) ) ( n * m + n * k ) .\nProof . intros m k n . induction m as [ | m IHm ] . simpl . rewrite ( natmultn0 n ) . auto with natarith .  simpl . rewrite ( multnsm n ( m + k ) ) . rewrite ( multnsm n m ) .  rewrite ( natplusassoc _ _ _ ) .  apply ( maponpaths ( fun x : _ => n + x ) ( IHm ) ) . Defined .\n\nLemma natmultassoc ( n m k : nat ) : paths ( ( n * m ) * k ) ( n * ( m * k ) ) .\nProof. intro . induction n as [ | n IHn ] . auto with natarith . intros . simpl . rewrite ( natrdistr m ( n * m ) k ) .  apply ( maponpaths ( fun x : _ => m * k + x ) ( IHn m k ) ) .   Defined . \n\nLemma natmultl1 ( n : nat ) : paths ( 1 * n ) n .\nProof. simpl .  auto with natarith . Defined . \nHint Resolve natmultl1 : natarith .\n\nLemma natmultr1 ( n : nat ) : paths ( n * 1 ) n .\nProof. intro n . rewrite ( natmultcomm n 1 ) . auto with natarith . Defined . \nHint Resolve natmultr1 : natarith .\n\nDefinition natmultabmonoid : abmonoid :=  abmonoidpair ( setwithbinoppair natset ( fun n m : nat => n * m ) ) ( dirprodpair ( dirprodpair natmultassoc ( @isunitalpair natset _ 1 ( dirprodpair natmultl1 natmultr1 ) ) ) natmultcomm ) . \n\n    \n\n\n(** *** [ nat ] as a commutative rig *)\n\nDefinition natcommrig : commrig .\nProof . split with ( setwith2binoppair natset ( dirprodpair  ( fun n m : nat => n + m ) ( fun n m : nat => n * m ) ) ) .  split . split . split with ( dirprodpair ( dirprodpair ( dirprodpair natplusassoc ( @isunitalpair natset _ 0 ( dirprodpair natplusl0 natplusr0 ) ) ) natpluscomm ) ( dirprodpair natmultassoc ( @isunitalpair natset _ 1 ( dirprodpair natmultl1 natmultr1 ) ) ) ) . apply ( dirprodpair natmult0n natmultn0 ) . apply ( dirprodpair natldistr natrdistr ) . unfold iscomm . apply natmultcomm . Defined .\n\n\n(** *** Cancellation properties of [ mult ] on [ nat ] *)\n\nDefinition natneq0andmult ( n m : nat ) ( isn : natneq n 0 ) ( ism : natneq m 0 ) : natneq ( n * m ) 0 .\nProof . intros . destruct n as [ | n ] . destruct ( isn ( idpath _ ) ) .  destruct m as [ | m ] .  destruct ( ism ( idpath _ ) ) . simpl . apply ( negpathssx0 ) .  Defined . \n\nDefinition natneq0andmultlinv ( n m : nat ) ( isnm : natneq ( n * m ) 0 ) : natneq n 0 := rigneq0andmultlinv natcommrig n m isnm . \n\nDefinition natneq0andmultrinv ( n m : nat ) ( isnm : natneq ( n * m ) 0 ) : natneq m 0 := rigneq0andmultrinv natcommrig n m isnm .\n\n\n\n(** *** Multiplication and comparisons  *)\n\n\n(** [ natgth ] *)\n\n\nDefinition natgthandmultl ( n m k : nat ) ( is : natneq k 0 ) : natgth n m -> natgth ( k * n ) ( k * m ) .\nProof. intro n . induction n as [ | n IHn ] .  intros m k g g' . destruct ( negnatgth0n _ g' ) .  intro m . destruct m as [ | m ] . intros k g g' . rewrite ( natmultn0 k ) .  rewrite ( multnsm k n ) .  apply ( natgehgthtrans _ _ _ ( natgehplusnmn k ( k* n ) ) ( natneq0togth0 _ g ) ) .  intros k g g' . rewrite ( multnsm k n ) . rewrite ( multnsm k m ) . apply ( natgthandplusl _ _ _ ) . apply ( IHn m k g g' ) . Defined .  \n\nDefinition natgthandmultr ( n m k : nat ) ( is : natneq k 0 ) : natgth n m -> natgth ( n * k ) ( m * k )  .\nProof . intros n m k l . rewrite ( natmultcomm n k ) . rewrite ( natmultcomm m k ) . apply ( natgthandmultl n m k l ) . Defined .\n\nDefinition natgthandmultlinv ( n m k : nat ) : natgth ( k * n ) ( k * m ) -> natgth n m .\nProof . intro n . induction n as [ | n IHn ] . intros m k g . rewrite ( natmultn0 k ) in g . destruct ( negnatgth0n _ g ) .  intro m . destruct m as [ | m ] .  intros . apply ( natgthsn0 _ ) . intros k g . rewrite ( multnsm k n ) in g .  rewrite ( multnsm k m ) in g . apply ( IHn m k ( natgthandpluslinv _ _ k g ) ) .  Defined . \n\nDefinition natgthandmultrinv ( n m k : nat ) : natgth ( n * k ) ( m * k ) -> natgth n m .\nProof.  intros n m k g . rewrite ( natmultcomm n k ) in g . rewrite ( natmultcomm m k ) in g . apply ( natgthandmultlinv n m k g ) . Defined .\n\n\n\n(** [ natlth ] *)\n\n\nDefinition natlthandmultl ( n m k : nat ) ( is : natneq k 0 ) : natlth n m -> natlth ( k * n ) ( k * m )  := natgthandmultl _ _ _ is .\n\nDefinition natlthandmultr ( n m k : nat ) ( is : natneq k 0 ) : natlth n m -> natlth ( n * k ) ( m * k ) := natgthandmultr _ _ _ is .\n\nDefinition natlthandmultlinv ( n m k : nat ) : natlth ( k * n ) ( k * m ) -> natlth n m := natgthandmultlinv _ _ _  .\n\nDefinition natlthandmultrinv ( n m k : nat ) : natlth ( n * k ) ( m * k ) -> natlth n m := natgthandmultrinv _ _ _ .\n\n\n(** [ natleh ] *)\n\n\nDefinition natlehandmultl ( n m k : nat ) : natleh n m -> natleh ( k * n ) ( k * m ) := negf ( natgthandmultlinv _ _ _ ) .\n\nDefinition natlehandmultr ( n m k : nat ) : natleh n m -> natleh ( n * k ) ( m * k ) := negf ( natgthandmultrinv _ _ _ ) .\n\nDefinition natlehandmultlinv ( n m k : nat ) ( is : natneq k 0 ) : natleh ( k * n ) ( k * m ) -> natleh n m := negf ( natgthandmultl _ _ _ is )  .\n\nDefinition natlehandmultrinv ( n m k : nat ) ( is : natneq k 0 ) : natleh ( n * k ) ( m * k ) -> natleh n m := negf ( natgthandmultr _ _ _ is ) .\n\n\n(** [ natgeh ] *)\n\n\nDefinition natgehandmultl ( n m k : nat ) : natgeh n m -> natgeh ( k * n ) ( k * m ) := negf ( natgthandmultlinv _ _ _ ) .\n\nDefinition natgehandmultr ( n m k : nat ) : natgeh n m -> natgeh ( n * k ) ( m * k )  := negf ( natgthandmultrinv _ _ _ ) .\n\nDefinition natgehandmultlinv ( n m k : nat ) ( is : natneq k 0 ) : natgeh ( k * n ) ( k * m ) -> natgeh n m := negf ( natgthandmultl _ _ _ is )   .\n\nDefinition natgehandmultrinv ( n m k : nat ) ( is : natneq k 0 ) : natgeh ( n * k ) ( m * k ) -> natgeh n m := negf ( natgthandmultr _ _ _ is )  .\n\n\n\n\n\n\n(** *** Properties of comparisons in the terminology of  algebra1.v *)\n\nOpen Scope rig_scope.\n\n(** [ natgth ] *)\n\nLemma isplushrelnatgth : @isbinophrel nataddabmonoid natgth . \nProof . split . apply  natgthandplusl .  apply natgthandplusr .  Defined . \n\nLemma isinvplushrelnatgth : @isinvbinophrel nataddabmonoid natgth . \nProof . split . apply  natgthandpluslinv .  apply natgthandplusrinv .  Defined . \n\nLemma isinvmulthrelnatgth : @isinvbinophrel natmultabmonoid natgth . \nProof . split .  intros a b c r . apply ( natlthandmultlinv _ _ _ r ) .   intros a b c r .  apply ( natlthandmultrinv _ _ _ r ) .  Defined . \n\nLemma isrigmultgtnatgth : isrigmultgt natcommrig natgth .\nProof . change ( forall a b c d : nat , natgth a b -> natgth c d -> natgth ( a * c + b * d ) ( a * d + b * c ) ) .  intro a . induction a as [ | a IHa ] . intros b c d rab rcd . destruct ( negnatgth0n _ rab ) . \n\nintro b . induction b as [ | b IHb ] . intros c d rab rcd . rewrite ( natmult0n d ) .  rewrite ( natplusr0 _ ) .  rewrite ( natmult0n _ ) .        rewrite ( natplusr0 _ ) . apply ( natlthandmultl _ _ _ ( natgthtoneq _ _ rab ) rcd ) . intros c d rab rcd . simpl . set ( rer := ( abmonoidrer nataddabmonoid ) ) . simpl in rer .  rewrite ( rer _ _ d _ ) . rewrite ( rer _ _ c _ ) .  rewrite ( natpluscomm c d ) .  apply ( natlthandplusl (a * d + b * c)  (a * c + b * d) ( d + c ) ) . apply ( IHa _ _ _ rab rcd ) .  Defined . \n\nLemma isinvrigmultgtnatgth : isinvrigmultgt natcommrig natgth .\nProof . set ( rer := abmonoidrer nataddabmonoid  ) .  simpl in rer .  apply isinvrigmultgtif . intros a b c d . generalize a b c . clear a b c .  induction d as [ | d IHd ] .  \n\nintros a b c g gab . change ( pr1 ( natgth ( a * c + b * 0 ) ( a * 0 + b * c ) ) ) in g .   destruct c as [ | c ] .  rewrite ( natmultn0 _ ) in g .  destruct ( isirreflnatgth _ g ) .  apply natgthsn0 .   \n\nintros a b c g gab .  destruct c as [ | c ] . change ( pr1 ( natgth ( a * 0 + b * S d ) ( a * S d + b * 0 ) ) ) in g . rewrite ( natmultn0 _ ) in g .  rewrite ( natmultn0 _ ) in g .  rewrite ( natplusl0 _ ) in g . rewrite ( natplusr0 _ ) in g .  set ( g' := natgthandmultrinv _ _ _ g ) .  destruct ( isasymmnatgth _ _ gab g' ) .  change ( pr1 ( natgth ( a * S c + b * S d ) ( a * S d + b * S c ) ) ) in g .  rewrite ( multnsm _ _ ) in g .   rewrite ( multnsm _ _ ) in g .  rewrite ( multnsm _ _ ) in g .  rewrite ( multnsm _ _ ) in g . rewrite ( rer _ ( a * c ) _ _ ) in g . rewrite ( rer _ ( a * d ) _ _ ) in g . set ( g' := natgthandpluslinv _ _ ( a + b ) g ) .  apply ( IHd a b c g' gab ) . Defined .  \n\n\n\n\n\n(** [ natlth ] *)\n\nLemma isplushrelnatlth : @isbinophrel nataddabmonoid natlth . \nProof . split . intros a b c . apply  ( natgthandplusl b a c ) . intros a b c . apply ( natgthandplusr b a c )  .  Defined . \n\nLemma isinvplushrelnatlth : @isinvbinophrel nataddabmonoid natlth . \nProof . split . intros a b c . apply  ( natgthandpluslinv b a c ) .  intros a b c . apply ( natgthandplusrinv b a c ) .  Defined . \n\nLemma isinvmulthrelnatlth : @isinvbinophrel natmultabmonoid natlth . \nProof . split . intros a b c r .  apply ( natlthandmultlinv  _ _ _ r ) .   intros a b c r .  apply ( natlthandmultrinv _ _ _ r ) .  Defined . \n\n(** [ natleh ] *)\n\nLemma isplushrelnatleh : @isbinophrel nataddabmonoid natleh . \nProof . split . apply natlehandplusl .  apply natlehandplusr . Defined . \n\nLemma isinvplushrelnatleh : @isinvbinophrel nataddabmonoid natleh . \nProof . split . apply natlehandpluslinv .  apply natlehandplusrinv . Defined . \n\nLemma ispartinvmulthrelnatleh : @ispartinvbinophrel natmultabmonoid ( fun x => natneq x 0 ) natleh . \nProof . split . intros a b c s r . apply ( natlehandmultlinv _ _ _ s r ) .   intros a b c s r .  apply ( natlehandmultrinv _ _ _ s r ) .  Defined . \n\n\n(** [ natgeh ] *)\n\nLemma isplushrelnatgeh : @isbinophrel nataddabmonoid natgeh . \nProof . split . intros a b c . apply ( natlehandplusl b a c ) .   intros a b c . apply ( natlehandplusr b a c ) . Defined . \n\nLemma isinvplushrelnatgeh : @isinvbinophrel nataddabmonoid natgeh . \nProof . split . intros a b c . apply ( natlehandpluslinv b a c ) .   intros a b c . apply ( natlehandplusrinv b a c ) . Defined . \n\nLemma ispartinvmulthrelnatgeh : @ispartinvbinophrel natmultabmonoid ( fun x => natneq x 0 ) natgeh . \nProof . split .  intros a b c s r . apply ( natlehandmultlinv _ _ _ s r ) .   intros a b c s r .  apply ( natlehandmultrinv _ _ _ s r ) .  Defined . \n\n\nClose Scope rig_scope . \n\n\n\n(** *** Submonoid of non-zero elements in [ nat ] *)\n\nDefinition natnonzero : @subabmonoids natmultabmonoid . \nProof . split with ( fun a => natneq a 0 ) .  unfold issubmonoid .  split .  unfold issubsetwithbinop . intros a a' .  apply ( natneq0andmult _ _ ( pr2 a ) ( pr2 a' ) ) . apply ( ct ( natneq , isdecrelnatneq, 1 , 0 ) ) . Defined . \n\nLemma natnonzerocomm ( a b : natnonzero ) : paths ( @op natnonzero a b ) ( @op natnonzero b a ) . \nProof . intros . apply ( invmaponpathsincl _ ( isinclpr1carrier _ ) ( @op natnonzero a b ) ( @op natnonzero b a ) ) .  simpl . apply natmultcomm . Defined . \n\n\n\n(** *** Division with a remainder on [ nat ] \n\nFor technical reasons it is more convenient to introduce divison with remainder for all pairs (n,m) including pairs of the form (n,0). *)\n\n\nDefinition natdivrem ( n m : nat ) : dirprod nat nat .\nProof. intros . induction n as [ | n IHn ] . intros . apply ( dirprodpair 0 0 ) . destruct ( natlthorgeh ( S ( pr2 IHn ) ) m )  . apply ( dirprodpair ( pr1 IHn ) ( S ( pr2 IHn ) ) ) .  apply ( dirprodpair ( S ( pr1 IHn ) ) 0 ) .   Defined . \n\nDefinition natdiv ( n m : nat )  := pr1 ( natdivrem n m ) .\nDefinition natrem ( n m : nat )  := pr2 ( natdivrem n m ) .\n\nLemma lthnatrem ( n m : nat ) ( is : natneq m 0 ) : natlth ( natrem n m ) m .\nProof. intro . destruct n as [ | n ] . unfold natrem . simpl . intros.  apply ( natneq0togth0 _ is ) .  unfold natrem . intros m is . simpl .   destruct ( natlthorgeh (S (pr2 (natdivrem n m))) m )  as [ nt | t ] . simpl . apply nt . simpl .  apply ( natneq0togth0 _ is ) .   Defined . \n\n\nTheorem natdivremrule ( n m : nat ) ( is : natneq m 0 ) : paths n ( ( natrem n m ) + ( natdiv n m ) * m ) .\nProof. intro . induction n as [ | n IHn ] . simpl .  intros . apply idpath . intros m is .  unfold natrem . unfold natdiv . simpl .  destruct ( natlthorgeh ( S ( pr2 ( natdivrem n m  ) ) ) m )  as [ nt | t ] . \n\nsimpl .  apply ( maponpaths S ( IHn m is ) ) .\n\nsimpl . set ( is' := lthnatrem n m is ) .  destruct ( natgthchoice2 _ _ is' ) as [ h | e ] .    destruct ( natlehtonegnatgth _ _ t h ) .  fold ( natdiv n m ) . set ( e'' := maponpaths S ( IHn m is ) ) .  change (S (natrem n m + natdiv n m * m) ) with (  S ( natrem n m ) + natdiv n m * m ) in  e'' . rewrite ( pathsinv0 e ) in e'' . apply e'' . \nDefined . \n\nOpaque natdivremrule . \n\n\nLemma natlehmultnatdiv ( n m : nat ) ( is : natneq m 0 ) :  natleh ( mult ( natdiv n m ) m ) n .\nProof . intros . set ( e := natdivremrule n m ) . set ( int := ( natdiv n m ) * m ) . rewrite e . unfold int  .   apply ( natlehmplusnm _ _ ) .  apply is . Defined . \n\n\nTheorem natdivremunique ( m i j i' j' : nat ) ( lj : natlth j m ) ( lj' : natlth j' m ) ( e : paths ( j + i * m ) ( j' + i' * m ) ) : dirprod ( paths i i' ) ( paths j j' ) .\nProof. intros m i . induction i as [ | i IHi ] .\n\nintros j i' j' lj lj' .  intro e .  simpl in e . rewrite ( natplusr0 j ) in e .  rewrite e in lj .  destruct i' . simpl in e .  rewrite ( natplusr0 j' ) in e .  apply ( dirprodpair ( idpath _ ) e ) .  simpl in lj . rewrite ( natpluscomm m ( i' * m ) ) in lj . rewrite ( pathsinv0 ( natplusassoc _ _ _ ) ) in lj .  destruct ( negnatgthmplusnm _ _ lj ) .\n\nintros j i' j' lj lj' e . destruct i' as [ | i' ] .  simpl in e .  rewrite ( natplusr0 j' ) in e . rewrite ( pathsinv0 e ) in lj' .   rewrite ( natpluscomm m ( i * m ) ) in lj' .  rewrite ( pathsinv0 ( natplusassoc _ _ _ ) ) in lj' .  destruct ( negnatgthmplusnm _ _ lj' ) .  \n\nsimpl in e .  rewrite ( natpluscomm m ( i * m ) ) in e .  rewrite ( natpluscomm m ( i' * m ) ) in e .  rewrite ( pathsinv0 ( natplusassoc j _ _ ) ) in e .  rewrite ( pathsinv0 ( natplusassoc j' _ _ ) ) in e . set ( e' := invmaponpathsincl _ ( isinclnatplusr m ) _ _ e ) .  set ( ee := IHi j i' j' lj lj' e' ) .  apply ( dirprodpair ( maponpaths S ( pr1 ee ) ) ( pr2 ee )  ) .  Defined . \n\nOpaque natdivremunique .\n\nLemma natdivremandmultl ( n m k : nat ) ( ism : natneq m 0 ) ( iskm : natneq ( k * m ) 0 ) : dirprod ( paths ( natdiv ( k * n ) ( k * m ) ) ( natdiv n m ) ) ( paths ( natrem ( k * n ) ( k * m ) ) ( k * ( natrem n m ) ) ) . \nProof . intros . set ( ak := natdiv ( k * n ) ( k * m ) ) . set ( bk := natrem ( k * n ) ( k * m ) ) . set ( a :=  natdiv n m ) . set ( b :=  natrem n m ) . assert ( e1 : paths ( bk + ak * ( k * m )  ) ( ( b * k ) + a * ( k * m ) ) ) . unfold ak. unfold bk .   rewrite ( pathsinv0 ( natdivremrule  ( k * n ) ( k * m ) iskm ) ) . rewrite ( natmultcomm k m ) .   rewrite ( pathsinv0 ( natmultassoc _ _ _ ) ) . rewrite ( pathsinv0 ( natrdistr _ _ _ ) ) .  unfold a . unfold b .  rewrite ( pathsinv0 ( natdivremrule  n m ism ) ) . apply ( natmultcomm k n ) . assert ( l1 := lthnatrem  n m ism ) . assert ( l1' := ( natlthandmultr _ _ _ ( natneq0andmultlinv _ _ iskm ) l1 ) )  .   rewrite ( natmultcomm m k ) in l1' . set ( int := natdivremunique _ _ _ _ _ ( lthnatrem ( k * n ) ( k * m ) iskm ) l1' e1 ) . \n\nsplit with ( pr1 int ) . \n\nrewrite ( natmultcomm k b ) . apply ( pr2 int ) .  Defined . \n\nOpaque natdivremandmultl .\n\n\nDefinition natdivandmultl ( n m k : nat ) ( ism : natneq m 0 ) ( iskm : natneq ( k * m ) 0 ) : paths ( natdiv ( k * n ) ( k * m ) ) ( natdiv n m ) := pr1 ( natdivremandmultl _ _ _ ism iskm ) .\n\n  \nDefinition natremandmultl ( n m k : nat ) ( ism : natneq m 0 ) ( iskm : natneq ( k * m ) 0 ) : paths ( natrem ( k * n ) ( k * m ) ) ( k * ( natrem n m ) ) := pr2 ( natdivremandmultl _ _ _ ism iskm ) .\n\n\nLemma natdivremandmultr ( n m k : nat ) ( ism : natneq m 0 ) ( ismk : natneq ( m * k ) 0 ) : dirprod ( paths ( natdiv ( n * k ) ( m * k ) ) ( natdiv n m ) ) ( paths ( natrem ( n * k ) ( m * k) ) ( ( natrem n m ) * k  ) ) . \nProof . intros . rewrite ( natmultcomm m k ) .   rewrite ( natmultcomm m k ) in ismk .  rewrite ( natmultcomm n k ) . rewrite ( natmultcomm ( natrem _ _ ) k ) .  apply ( natdivremandmultl _ _ _ ism ismk ) . Defined . \n\n\nOpaque natdivremandmultr .\n\n\nDefinition natdivandmultr ( n m k : nat ) ( ism : natneq m 0 ) ( ismk : natneq ( m * k ) 0 ) : paths ( natdiv ( n * k ) ( m * k ) ) ( natdiv n m ) := pr1 ( natdivremandmultr _ _ _ ism ismk ) .\n \n\nDefinition natremandmultr ( n m k : nat ) ( ism : natneq m 0 ) ( ismk : natneq ( m * k ) 0 ) : paths ( natrem ( n * k ) ( m * k ) ) ( ( natrem n m ) * k ) := pr2 ( natdivremandmultr _ _ _ ism ismk ) .\n\n\n\n\n\n(** *** Exponentiation [ natpower n m ] ( \" n to the power m \" ) on [ nat ] *)\n\nFixpoint natpower ( n m : nat ) := match m with\nO => 1 |\nS m' => n * ( natpower n m' ) end .\n\n\n(** *** Factorial on [ nat ] *)\n\nFixpoint factorial ( n : nat ) := match n with\n0 => 1 |\nS n' => ( S n' ) * ( factorial n' ) end .  \n\n\n\n\n\n(** ** The order-preserving functions [ di i : nat -> nat ] whose image is the complement to one element [ i ] . *)\n\n\n\n\nDefinition di ( i : nat ) ( x : nat ) : nat :=\nmatch natlthorgeh x i with \nii1 _ => x |\nii2 _ => S x \nend .\n\n\nLemma natlehdinsn ( i n : nat ) : natleh ( di i n ) ( S n ) .\nProof . intros . unfold di . destruct ( natlthorgeh n i ) . apply natlthtoleh . apply natlthnsn . apply isreflnatleh .  Defined . \n\nLemma natgehdinn ( i n : nat ) : natgeh ( di i n ) n .\nProof. intros . unfold di . destruct ( natlthorgeh n i ) .  apply isreflnatleh .  apply natlthtoleh . apply natlthnsn .   Defined . \n\n\nLemma isincldi ( i : nat ) : isincl ( di i ) .\nProof. intro .   apply ( isinclbetweensets ( di i ) isasetnat isasetnat ) . intros x x' . unfold di . intro e. destruct  ( natlthorgeh x i )  as [ l | nel ] .  destruct  ( natlthorgeh x' i )   as [ l' | nel' ] . apply e .  rewrite e in l .  set ( e' := natgthtogths _ _  l ) . destruct ( nel' e' ) .   destruct  ( natlthorgeh x' i )  as [ l' | nel' ] .  destruct e.  set ( e' := natgthtogths _ _ l' ) . destruct ( nel e' ) .  apply ( invmaponpathsS _ _ e ) . Defined . \n\n\nLemma neghfiberdi ( i : nat ) : neg ( hfiber ( di i ) i ) .\nProof. intros i hf . unfold di in hf . destruct hf as [ j e ] .  destruct ( natlthorgeh j i ) as [ l | g ] . destruct e . apply ( isirreflnatlth _ l) .  destruct e in g .  apply ( negnatgehnsn _ g ) .   Defined. \n\nLemma iscontrhfiberdi ( i j : nat ) ( ne : neg ( paths i j ) ) : iscontr ( hfiber ( di i ) j ) .\nProof. intros . apply iscontraprop1 .   apply ( isincldi i j ) . destruct ( natlthorgeh j i ) as [ l | nel ]  .  split with j .  unfold di .   destruct ( natlthorgeh j i ) as [ l' | nel' ]  .  apply idpath .  destruct ( nel' l ) .   destruct ( natgehchoice2 _ _ nel ) as [ g | e ] . destruct j as [ | j ] . destruct ( negnatgeh0sn _ g ) .   split with j . unfold di .  destruct ( natlthorgeh j i ) as [ l' | g' ] .  destruct ( g l' ) .  apply idpath .  destruct ( ne ( pathsinv0 e ) ) . Defined . \n \n\nLemma isdecincldi ( i : nat ) : isdecincl ( di i ) .\nProof. intro i . intro j . apply isdecpropif .   apply ( isincldi i j ) .  destruct ( isdeceqnat i j )  as [ eq | neq ] .    destruct eq .  apply ( ii2 ( neghfiberdi i ) ) . apply ( ii1 ( pr1 ( iscontrhfiberdi i j neq ) ) ) .   Defined .\n\n\n\n\n\n\n(** ** Inductive types [ le ] with values in [ Type ] . \n\nThis part is included for illustration purposes only . In practice it is easier to work with [ natleh ] than with [ le ] . \n\n*)\n\n(** *** A generalization of [ le ] and its properties . *)\n\nInductive leF { T : Type } ( F : T -> T ) ( t : T ) : T -> Type := leF_O : leF F t t | leF_S : forall t' : T , leF F t t' -> leF F t ( F t' ) .\n\nLemma leFiter { T : UU } ( F : T -> T ) ( t : T ) ( n : nat ) : leF F t ( iteration F n t ) .\nProof. intros .   induction n as [ | n IHn ] . apply leF_O . simpl . unfold funcomp . apply leF_S .  assumption .  Defined . \n\nLemma leFtototal2withnat { T : UU } ( F : T -> T ) ( t t' : T ) ( a : leF F t t' ) : total2 ( fun n : nat => paths ( iteration F n t ) t' ) .\nProof. intros. induction a as [ | b H0 IH0 ] . split with O . apply idpath .  split with  ( S ( pr1 IH0 ) ) . simpl . apply ( @maponpaths _ _ F ( iteration F ( pr1 IH0 ) t ) b ) . apply ( pr2 IH0 ) .  Defined. \nLemma total2withnattoleF { T : UU } ( F : T -> T ) ( t t' : T ) ( a : total2 ( fun n : nat => paths ( iteration F n t ) t' ) ) : leF F t t' .\nProof. intros .  destruct a as [ n e ] .  destruct e .  apply leFiter.  Defined . \n\n\nLemma leFtototal2withnat_l0 { T : UU } ( F : T -> T ) ( t : T ) ( n : nat ) : paths ( leFtototal2withnat F t _ (leFiter F t n)) ( tpair _  n ( idpath (iteration F n t) ) ) . \nProof . intros . induction n as [ | n IHn ] .   apply idpath . simpl .  \nset ( h := fun ne :  total2 ( fun n0 : nat => paths ( iteration F n0 t ) ( iteration F n t ) ) => tpair  ( fun n0 : nat => paths ( iteration F n0 t ) ( iteration F ( S n ) t ) ) ( S ( pr1 ne ) ) ( maponpaths F ( pr2 ne ) ) ) . apply ( @maponpaths _ _ h  _ _ IHn ) . Defined. \n\n\nLemma isweqleFtototal2withnat { T : UU } ( F : T -> T ) ( t t' : T ) : isweq ( leFtototal2withnat F t t' ) .\nProof . intros .  set ( f := leFtototal2withnat F t t' ) . set ( g :=  total2withnattoleF  F t t' ) . \nassert ( egf : forall x : _ , paths ( g ( f x ) ) x ) . intro x .  induction x as [ | y H0 IHH0 ] . apply idpath . simpl . simpl in IHH0 .  destruct (leFtototal2withnat F t y H0 ) as [ m e ] .   destruct e .  simpl .   simpl in IHH0.  apply (  @maponpaths _ _ ( leF_S F t (iteration F m t) ) _ _ IHH0 ) .\nassert ( efg : forall x : _ , paths ( f ( g x ) ) x ) . intro x .  destruct x as [ n e ] .  destruct e . simpl .  apply  leFtototal2withnat_l0 . \napply ( gradth _ _ egf efg ) . Defined.\n\nDefinition weqleFtototalwithnat { T : UU } ( F : T -> T ) ( t t' : T ) : weq ( leF F t t' ) (  total2 ( fun n : nat => paths ( iteration F n t ) t' ) ) := weqpair _ ( isweqleFtototal2withnat F t t' ) .\n\n\n(** *** Inductive types [ le ] with values in [ Type ] are in [ hProp ] *)\n\nDefinition le ( n : nat ) : nat -> Type := leF S n .\nDefinition le_n := leF_O S .\nDefinition le_S := leF_S S . \n\n\n\nTheorem isaprople ( n m : nat ) : isaprop ( le n m ) .\nProof. intros .  apply ( isofhlevelweqb 1 ( weqleFtototalwithnat S n m ) ) . apply invproofirrelevance .  intros x x' .  set ( i := @pr1 _ (fun n0 : nat => paths (iteration S n0 n) m) ) . assert ( is : isincl i ) . apply ( isinclpr1 _ ( fun n0 : nat => isasetnat (iteration S n0 n) m ) ) . apply ( invmaponpathsincl _  is ) .  destruct x as [ n1 e1 ] . destruct x' as [ n2 e2 ] . simpl .   set ( int1 := pathsinv0 ( pathsitertoplus n1 n ) ) . set ( int2 := pathsinv0 (pathsitertoplus n2 n ) ) . set ( ee1 := pathscomp0 int1 e1 ) . set ( ee2 := pathscomp0 int2 e2 ) . set ( e := pathscomp0 ee1 ( pathsinv0 ee2 ) ) .   apply ( invmaponpathsincl _ ( isinclnatplusr n ) n1 n2 e ) .    Defined . \n\n(** *** Comparison between [ le ] with values in [ Type ] and [ natleh ] . *)\n\n\nLemma letoleh ( n m : nat ) : le n m -> natleh n m .\nProof .  intros n m H . induction H as [ | m H0 IHH0 ] . apply isreflnatleh .  apply natlehtolehs .  assumption .  Defined . \n\nLemma natlehtole ( n m : nat ) : natleh n m ->  le n m .\nProof. intros n m H .  induction m .  assert ( int := natleh0tois0 n H ) .   clear H . destruct int . apply le_n . \n set ( int2 := natlehchoice2 n ( S m ) H ) .  destruct int2 as [ isnatleh | iseq ] . apply ( le_S n m ( IHm isnatleh ) ) . destruct iseq .   apply le_n . Defined .\n\nLemma isweqletoleh ( n m : nat ) : isweq ( letoleh n m ) .\nProof. intros . set ( is1 := isaprople n m ) . set ( is2 := pr2 ( natleh n m )  ) . apply ( isweqimplimpl ( letoleh n m ) ( natlehtole n m ) is1 is2 ) .  Defined . \n\nDefinition weqletoleh ( n m : nat ) := weqpair _ ( isweqletoleh n m ) .\n\n\n\n\n(* End of the file hnat.v *)\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/arxiv/Foundations/hlevel2/hnat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6591854743619977}}
{"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.", "meta": {"author": "oiwn", "repo": "coq_experiments", "sha": "1dfaa31c647cf3027100112e998fefc4b462bcf7", "save_path": "github-repos/coq/oiwn-coq_experiments", "path": "github-repos/coq/oiwn-coq_experiments/coq_experiments-1dfaa31c647cf3027100112e998fefc4b462bcf7/weekdays.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6591854704365675}}
{"text": "(*|\n================================\nExample: ABC transition system\n================================\n\nWe define a simple state machine with a field `x` that goes from `A` to `B` to `C`, and separately a field `happy` that remains constant.\n\nThe state machine has a safety property that says `happy` is true, and a liveness property that says `◇ ⌜λ s, s.(x) = C⌝`.\n\n|*)\n\nFrom TLA Require Import logic.\n\n(*|\nThis module contains the trusted (assume correct) definitions for the state machine itself, as well as the desired safety and liveness properties.\n|*)\nModule spec.\n\n  Inductive abc := A | B | C.\n  Record state :=\n    { x: abc; happy: bool; }.\n\n  Definition ab : action state :=\n    λ s s', (s.(x) = A ∧ s'.(x) = B ∧ s'.(happy) = s.(happy)).\n\n  Definition bc : action state :=\n    λ s s', (s.(x) = B ∧ s'.(x) = C ∧ s'.(happy) = s.(happy)).\n\n  Definition init (s: state) :=\n      s.(x) = A ∧ s.(happy) = true.\n\n  (*|\nIt is important to allow stuttering (`s = s'`) in this predicate! Otherwise there would be no infinite sequences satisfying `□ ⟨next⟩`, since after two transitions no steps would be possible.\n  |*)\n  Definition next s s' :=\n    ab s s' ∨ bc s s' ∨ s = s'.\n\n  (*|\nThe safety property for this example is that happy always remains true.\n  |*)\n  Definition safe : state → Prop :=\n    λ s, s.(happy).\n\n  (*|\nThe statement that the state machine satisfies safety follows the very standard TLA formula here, `⌜init⌝ ∧ □ ⟨next⟩ → □ ⌜safe⌝`. This says that if `init` holds in the first state of an execution and every subsequent transition satisfies `next`, then `safe` holds of every state.\n  |*)\n  Definition safety : predicate state :=\n    ⌜init⌝ ∧ □ ⟨next⟩ → □ ⌜safe⌝.\n\n  (*|\nIntuitively the liveness property for this example is that eventually the field `x` will be `C`. Stating this formally is a bit more sophisticated than for safety. We still have ⌜init⌝ ∧ □⟨next⟩ as an assumption (we only consider executions that follow the state machine semantics), but in order for this theorem to hold we need the `ab` and `bc` actions to run \"often enough\", expressed via weak fairness assumptions. Without these, the theorem would be false, because it would be valid for an execution to consist of infinitely many stuttering steps, starting from a state satisfying `init`.\n|*)\n  Definition liveness : predicate state :=\n    ⌜init⌝ ∧ □ ⟨next⟩ ∧ weak_fairness ab ∧ weak_fairness bc →\n    ◇ ⌜λ s, s.(x) = C⌝.\n\nEnd spec.\n\n(*|\n\nThe remainder of the code is untrusted proof (except for the fact that ⊢ safety\nand ⊢ liveness are stated and proven as theorems).\n\n|*)\n\nImport spec.\n\nSection example.\n\nImplicit Types (s: state).\n\n(*|\nA little automation will prove all the state-machine specific reasoning required for this example, essentially by brute force.\n|*)\nHint Unfold init happy next ab bc : stm.\nHint Unfold safe : stm.\n\nHint Unfold enabled : stm.\n\nLtac stm :=\n  autounfold with stm in *;\n  intros;\n  repeat match goal with\n        | s: state |- _ =>\n          let x := fresh \"x\" in\n          let happy := fresh \"happy\" in\n          destruct s as [x happy]\n        | H: (@eq state _ _) |- _ => invc H\n        end;\n  intuition idtac;\n  try solve [\n      try match goal with\n      | |- ∃ (s: state), _ => eexists {| x := _; happy := _; |}\n      end;\n    intuition (subst; eauto; try congruence) ].\n\n(*|\n--------\nSafety\n--------\n\nThe safety property is pretty easy, using `init_invariant`. In fact it's so simple it's already inductive and we don't need to go through a separate invariant.\n|*)\n\nTheorem always_happy : ⊢ safety.\nProof.\n  tla_intro.\n  apply init_invariant. (* .unfold *)\n  - stm.\n  - stm.\nQed.\n\n(*|\n-----------\nLiveness\n-----------\n\nLiveness is more interesting. The high-level strategy is to use the rule `wf1` to prove `A ~~> B` and that `B ~~> C`; then we can chain them together and finally apply them by showing that `init` implies `A`.\n|*)\n\n(*|\nNotice that the state-machine reasoning all happens here, and in the analogous `b_leads_to_c` proof below. We only need to prove one- and two-state properties and the wf1 rules lifts them to a temporal property that uses the weak fairness assumption.\n|*)\nLemma a_leads_to_b :\n  □ ⟨ next ⟩ ∧ weak_fairness ab ⊢\n  ⌜λ s, s.(x) = A⌝ ~~> ⌜λ s, s.(x) = B⌝.\nProof.\n  apply wf1. (* .unfold *)\n  - stm.\n  - stm.\n  - stm.\nQed.\n\nLemma init_a :\n  ⌜init⌝ ⊢ ⌜λ s, s.(x) = A⌝.\nProof.\n  apply state_pred_impl => s.  stm.\nQed.\n\n(*|\nThis theorem isn't directly needed; we carry out the same reasoning to derive ◇ C from the leads_to proofs.\n|*)\nTheorem eventually_b :\n  ⌜init⌝ ∧ □ ⟨next⟩ ∧ weak_fairness ab ⊢\n  ◇ ⌜λ s, s.(x) = B⌝.\nProof.\n  apply (leads_to_apply ⌜ λ s, s.(x) = A ⌝).\n  { rewrite init_a; tla_prop. }\n  tla_apply a_leads_to_b.\nQed.\n\nLemma b_leads_to_c :\n  □ ⟨ next ⟩ ∧ weak_fairness bc ⊢\n   ⌜λ s, s.(x) = B⌝ ~~> ⌜λ s, s.(x) = C⌝.\nProof.\n  apply wf1.\n  - stm.\n  - stm.\n  - stm.\nQed.\n\nLemma a_leads_to_c :\n  □ ⟨ next ⟩ ∧ weak_fairness ab ∧ weak_fairness bc ⊢\n  ⌜ λ s, s.(x) = A ⌝ ~~> ⌜ λ s, s.(x) = C ⌝.\nProof.\n  leads_to_trans (⌜λ s, s.(x) = B⌝).\n  { tla_apply a_leads_to_b. }\n  tla_apply b_leads_to_c.\nQed.\n\nTheorem eventually_c : ⊢ liveness.\nProof.\n  tla_intro.\n(*|\n`leads_to_apply p` will switch from proving `◇ q` to `p` and `p ~~> q`.\n|*)\n  apply (leads_to_apply ⌜λ s, s.(x) = A⌝).\n  { rewrite init_a; tla_prop. }\n  tla_apply a_leads_to_c.\nQed.\n\nEnd example.\n", "meta": {"author": "tchajed", "repo": "coq-tla", "sha": "b2973089a67646614720c27031f9dde8ff2f82f6", "save_path": "github-repos/coq/tchajed-coq-tla", "path": "github-repos/coq/tchajed-coq-tla/coq-tla-b2973089a67646614720c27031f9dde8ff2f82f6/src/examples/hello_liveness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6591854677528602}}
{"text": "From QuickChick Require Import QuickChick.\n\nRequire Import List. Import ListNotations.\nRequire Import String. Open Scope string.\n\n#[local]\nInstance DecOpt_and \n    {P1} `{DO1 : DecOpt P1}\n    {P2} `{DO2 : DecOpt P2} : \n    DecOpt (P1 /\\ P2) := {\n  decOpt := \n    fun n => \n    match @decOpt P1 DO1 n with\n    | Some true => @decOpt P2 DO2 n\n    | _ => Some false\n    end\n}.\n\nInductive Tree :=\n| Leaf : Tree\n| Node : nat -> Tree -> Tree -> Tree.\n\nDerive (Arbitrary, Sized, Show) for Tree. \n\nInductive bst : nat -> nat -> Tree -> Prop :=\n| bst_Leaf : forall lo hi, bst lo hi Leaf\n| bst_Node : forall lo hi x l r,\n    le (S lo) x ->  le (S x) hi ->\n    bst lo x l -> bst x hi r ->\n    bst lo hi (Node x l r).\n\nDerive ArbitrarySizedSuchThat for (fun x => le y x).\nDerive ArbitrarySizedSuchThat for (fun x => le x y).\nDerive ArbitrarySizedSuchThat for (fun t => bst lo hi t).\n\nDerive DecOpt for (bst lo hi t).\n\nDefinition genBetween lo hi: G (option nat) :=\n  if (lo <= hi)?\n    then\n      bindGenOpt (genST (fun x => le x (hi - lo))) (fun x => \n      ret (Some (x + lo)))\n    else ret None.\n\nFixpoint is_bst (lo hi : nat) (t : Tree) :=\n  match t with\n  | Leaf => true\n  | Node x l r =>\n    andb ((lo <= x /\\ x <= hi) ?)\n         (andb (is_bst lo x l)\n               (is_bst x hi r))\n  end.\n\n(* Instance Decbst : forall lo hi t, Dec (bst lo hi t). *)\n\nFixpoint maxNode x t: nat :=\n  match t with \n  | Leaf => x\n  | Node y l r => maxNode y r\n  end.\n\nFixpoint minNode x t: nat :=\n  match t with \n  | Leaf => x\n  | Node y l r => minNode y l\n  end.\n\n(* How much to weight branches, as a function of their size *)\nDefinition mut_bst_branch_weighting (n: nat): nat := 2 * n.\n\n(* Keeps generating values that satisfy the first property until one also \n   satisfies the second property. *)\nDefinition genSTF {A : Type} \n    (P1 : A -> Prop) `{GenSuchThat A P1}\n    (P2 : A -> bool) :\n    G (option A) :=\n  backtrack [\n    ( 1\n    , bindGenOpt (@arbitraryST A P1 _) (fun a =>\n      if P2 a then\n        ret (Some a)\n      else \n        ret None)\n    )\n  ].\n\n(* Keeps generating values that satisfy the first property until one also \n   satisfies the second property. *)\nDefinition genSTF'\n    {A : Type}\n    (P : A -> Prop * bool) `{GenSuchThat A (fun a => fst (P a))} :\n    G (option A) :=\n  backtrack [\n    ( 1\n    , bindGenOpt (@arbitraryST A (fun a => fst (P a)) _) (fun a =>\n      if snd (P a)\n        then ret (Some a)\n        else ret None\n      )\n    )\n  ].\n\nDefinition allb (l : list bool) : bool := forallb id l.\n\nFixpoint mut_bst (lo hi: nat) (t: Tree) : G (option Tree) :=\n  let n := size t in \n  (* preserves size *)\n  let regenerate : G (option Tree) :=\n        @arbitrarySizeST _ (fun t => bst lo hi t) _ n in\n  match t return G (option Tree) with \n  | Leaf => \n    backtrack [ \n      (* regenerate *)\n      \n      ( 1\n      , regenerate )\n\n      (* -------------------------------------------------------------------- *)\n      (* recombine *)\n      \n      (* recombine: Leaf [EMPTY] *)\n      (*    nothing to recombine with *)\n      (*    nothing to recombine into *)\n      (*    so, result will be same  *)\n      \n      (* -------------------------------------------------------------------- *)\n      (* recombine: Node x Leaf r via bst_Node *)\n      (*    generate: x, l *)\n    ; ( 1\n      (* , bindGenOpt (genSTF (fun x => lo <= x) (fun x => allb [(x <= hi)? ; is_bst lo x Leaf])) (fun x =>\n        bindGenOpt (genSTF (fun r => bst x hi r) (fun r => allb [])) (fun r => *)\n      , bindGenOpt (genSTF' (fun x => (lo <= x, allb [(x <= hi)? ; is_bst lo x Leaf] ))) (fun x =>\n        bindGenOpt (genSTF' (fun r => bst x hi r, allb [])) (fun r =>\n        ret (Some (Node x Leaf r))))\n      )\n      \n      (* recombine: Node x l Leaf via bst_Node *)\n      (*    generate: x, l *)\n    ; ( 1\n      , bindGenOpt (genSTF (fun x => x <= hi) (fun x => allb [(lo <= x)? ; is_bst x hi Leaf])) (fun x =>\n        bindGenOpt (genSTF (fun l => bst lo x l) (fun l => allb [])) (fun l =>\n        ret (Some (Node x l Leaf))))\n      )\n      \n      (* -------------------------------------------------------------------- *)\n      (* mutate child *)\n      (* no children to mutate *)  \n    ]\n  | Node x l r =>\n    backtrack [\n      (* -------------------------------------------------------------------- *)\n      (* regenerate *)\n        \n      ( 1\n      , regenerate )\n\n      (* -------------------------------------------------------------------- *)\n      (* recombine *)\n\n      (* recombine: Leaf [EMPTY] *)\n      (*    nothing to recombine into *)\n      \n      (* recombine: Node x' l' r  via bst_Node *)\n      (*    regenerate x', l' *)\n      ; ( 1\n        , bindGenOpt (genSTF (fun x' => x' <= lo) (fun x' => allb [(x' <= hi)? ; is_bst x' hi r])) (fun x' =>\n          bindGenOpt (genSTF (fun l' => bst lo x' l') (fun l' => allb [])) (fun l' =>\n          ret (Some (Node x' l' r))))\n        )    \n      \n      (* recombine: Node x' l  r' via bst_Node *)\n      (*    regenerate x', r' *)\n      ; ( 1\n        , bindGenOpt (genSTF (fun x' => x' <= lo) (fun x' => allb [(x' <= hi)? ; is_bst lo x' l])) (fun x' =>\n          bindGenOpt (genSTF (fun r' => bst lo x' r') (fun r' => allb [])) (fun r' =>\n          ret (Some (Node x' l r'))))\n        )\n      \n      (* recombine: Node x  l' r' via bst_Node *)\n      (*    regenerate l', r' *)\n      ; ( 1\n        , bindGenOpt (genSTF (fun l' => bst lo x l') (fun l' => allb [])) (fun l' =>\n          bindGenOpt (genSTF (fun r' => bst x hi r') (fun r' => allb [])) (fun r' =>\n          ret (Some (Node x l' r'))))\n        )\n      \n      (* recombine: Node x' l  r  via bst_Node *)\n      (*    regenerate x' *)\n      ; ( 1\n        , bindGenOpt (genSTF (fun x' => x' <= lo) (fun x' => allb [(x' <= hi)? ; is_bst lo x' l ; is_bst x' hi r])) (fun x' =>\n          ret (Some (Node x' l r)))\n        )\n      \n      (* recombine: Node x  l' r  via bst_Node *)\n      (*    regenerate l' *)\n      ; ( 1\n        , bindGenOpt (genSTF (fun l' => bst lo x l') (fun l' => allb [])) (fun l' =>\n          ret (Some (Node x l' r))) \n        )\n      \n      (* recombine: Node x  l  r' via bst_Node *)\n      (*    regenerate r' *)\n      ; ( 1\n        , bindGenOpt (genSTF (fun r' => bst x hi r') (fun r' => allb [])) (fun r' =>\n          ret (Some (Node x l r')))\n        )\n\n      (* -------------------------------------------------------------------- *)\n      (* mutate child *)\n\n      (* mutate child: l *)\n      ; ( size l\n        , mut_bst lo x l\n        )\n\n      (* mutate child: r *)\n      ; ( size r\n        , mut_bst x hi r\n        )\n    ]\n  end.\n  \n  match t return G (option Tree) with\n  | Leaf => mut_here \n  | Node x l r =>\n    backtrack\n      [ (* here *)\n        ( 1 , mut_here )\n      ; (* x *)\n        ( 1\n        (* specialized *)\n        (* , bindGenOpt (genBetween (maxNode lo l) (minNode hi r)) (fun x' => *)\n        (* generalized *)\n        , bindGenOpt\n            (backtrack [\n              ( 1\n              , bindGenOpt (genST (fun x => lo <= x)) (fun x' =>\n                  if\n                    (andb ((x' <= hi)?)\n                    (andb (is_bst lo x' l)\n                          (is_bst x' hi r)))\n                  then ret (Some x)\n                  else ret None)\n              )\n            ])\n            (fun x' => ret (Some (Node x' l r)))\n        )\n      ; (* l *)\n        ( mut_bst_branch_weighting (size l)\n        , bindGenOpt (mut_bst lo x l) (fun l' => \n          ret (Some (Node x l' r)))\n        )\n      ; (* r *)\n        ( mut_bst_branch_weighting (size r)\n        , bindGenOpt (mut_bst x hi r) (fun r' => \n          ret (Some (Node x l r')))\n        )\n      ]\n  end.    \n\nDefinition mut_preserves_bst :=\n  forAll (arbitrary: G nat) (fun hi =>\n  forAllMaybe (genST (fun lo => lo <= hi)) (fun lo =>\n  forAllMaybe (@arbitraryST _ (fun t => bst lo hi t) _) (fun t =>\n  forAllMaybe (mut_bst lo hi t) (fun t' =>\n  ret (is_bst lo hi t')\n  )))).\n\nQuickChick mut_preserves_bst.\n\nSample (mut_bst 0 100 (Node 50 (Node 25 Leaf Leaf) (Node 75 Leaf Leaf))).", "meta": {"author": "Bazinga9000", "repo": "QuickTarget", "sha": "d7bae541f210af1183a040172216568ab4074e8b", "save_path": "github-repos/coq/Bazinga9000-QuickTarget", "path": "github-repos/coq/Bazinga9000-QuickTarget/QuickTarget-d7bae541f210af1183a040172216568ab4074e8b/examples/smart-mutators/bst_generic_v2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.659185465790145}}
{"text": "(* This file is generated by Why3's Coq driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import ZArith.\nRequire Import Rbase.\nRequire int.Int.\n\n(* Why3 assumption *)\nInductive list (a:Type) :=\n  | Nil : list a\n  | Cons : a -> (list a) -> list a.\nSet Contextual Implicit.\nImplicit Arguments Nil.\nUnset Contextual Implicit.\nImplicit Arguments Cons.\n\n(* Why3 assumption *)\nSet Implicit Arguments.\nFixpoint mem (a:Type)(x:a) (l:(list a)) {struct l}: Prop :=\n  match l with\n  | Nil => False\n  | (Cons y r) => (x = y) \\/ (mem x r)\n  end.\nUnset Implicit Arguments.\n\n(* Why3 assumption *)\nSet Implicit Arguments.\nFixpoint infix_plpl (a:Type)(l1:(list a)) (l2:(list a)) {struct l1}: (list\n  a) :=\n  match l1 with\n  | Nil => l2\n  | (Cons x1 r1) => (Cons x1 (infix_plpl r1 l2))\n  end.\nUnset Implicit Arguments.\n\nAxiom Append_assoc : forall (a:Type), forall (l1:(list a)) (l2:(list a))\n  (l3:(list a)), ((infix_plpl l1 (infix_plpl l2\n  l3)) = (infix_plpl (infix_plpl l1 l2) l3)).\n\nAxiom Append_l_nil : forall (a:Type), forall (l:(list a)), ((infix_plpl l\n  (Nil :(list a))) = l).\n\n(* Why3 assumption *)\nSet Implicit Arguments.\nFixpoint length (a:Type)(l:(list a)) {struct l}: Z :=\n  match l with\n  | Nil => 0%Z\n  | (Cons _ r) => (1%Z + (length r))%Z\n  end.\nUnset Implicit Arguments.\n\nAxiom Length_nonnegative : forall (a:Type), forall (l:(list a)),\n  (0%Z <= (length l))%Z.\n\nAxiom Length_nil : forall (a:Type), forall (l:(list a)),\n  ((length l) = 0%Z) <-> (l = (Nil :(list a))).\n\nAxiom Append_length : forall (a:Type), forall (l1:(list a)) (l2:(list a)),\n  ((length (infix_plpl l1 l2)) = ((length l1) + (length l2))%Z).\n\nAxiom mem_append : forall (a:Type), forall (x:a) (l1:(list a)) (l2:(list a)),\n  (mem x (infix_plpl l1 l2)) <-> ((mem x l1) \\/ (mem x l2)).\n\nAxiom mem_decomp : forall (a:Type), forall (x:a) (l:(list a)), (mem x l) ->\n  exists l1:(list a), exists l2:(list a), (l = (infix_plpl l1 (Cons x l2))).\n\n(* Why3 assumption *)\nSet Implicit Arguments.\nFixpoint no_repet (a:Type)(l:(list a)) {struct l}: Prop :=\n  match l with\n  | Nil => True\n  | (Cons x r) => (~ (mem x r)) /\\ (no_repet r)\n  end.\nUnset Implicit Arguments.\n\nParameter vertex : Type.\n\nParameter edge: vertex -> vertex -> Prop.\n\n(* Why3 assumption *)\nInductive path : vertex -> vertex -> (list vertex) -> Prop :=\n  | path_empty : forall (v:vertex), (path v v (Nil :(list vertex)))\n  | path_cons : forall (v:vertex) (v1:vertex) (v2:vertex) (l:(list vertex)),\n      ((edge v v1) /\\ (path v1 v2 l)) -> (path v v2 (Cons v l)).\n\nAxiom First_path_elt1 : forall (v:vertex) (v1:vertex) (v2:vertex) (l:(list\n  vertex)), (path v1 v2 (Cons v l)) -> (v = v1).\n\nAxiom First_path_elt2 : forall (v1:vertex) (v2:vertex) (l:(list vertex)),\n  ((~ (v1 = v2)) /\\ (path v1 v2 l)) -> exists lqt:(list vertex),\n  (l = (Cons v1 lqt)).\n\nAxiom MergePath : forall (v:vertex) (v1:vertex) (v2:vertex) (l1:(list\n  vertex)) (l2:(list vertex)), ((path v1 v l1) /\\ (path v v2 l2)) -> (path v1\n  v2 (infix_plpl l1 l2)).\n\n(* Why3 goal *)\nTheorem SplitPath : forall (l1:(list vertex)) (l2:(list vertex)) (v:vertex)\n  (v1:vertex) (v2:vertex), (path v1 v2 (infix_plpl l1 (Cons v l2))) ->\n  ((path v1 v l1) /\\ (path v v2 (Cons v l2))).\ninduction l1.\nsimpl; intros.\nassert (h := First_path_elt1 _ _ _ _ H).\nsubst; split; auto.\nconstructor.\nsimpl.\nintros l2 v v1 v2 H1.\ninversion H1.\nsubst; clear H1.\ndestruct H3 as (h1,h2).\ndestruct (IHl1 l2 v v3 v2 h2) as (h3,h4).\nsplit; auto.\neconstructor; eauto.\nQed.\n\n\n", "meta": {"author": "yutopio", "repo": "bellmanford", "sha": "50b47566eaee0077b5d7ed51d551721525313b6b", "save_path": "github-repos/coq/yutopio-bellmanford", "path": "github-repos/coq/yutopio-bellmanford/bellmanford-50b47566eaee0077b5d7ed51d551721525313b6b/path/path_Path_SplitPath_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.659185465069153}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith List Omega.\n\nRequire Import tacs.\n\nRequire Import rel_utils.\nRequire Import list_utils.\nRequire Import sublist.\n\nSet Implicit Arguments.\n\nSection Ge_Good.\n\n  Variables (A : Type) (R : A -> A -> Prop).\n\n  Infix \"<<\" := R (at level 70).\n\n  Definition Ge_ex a w := exists x, In x w /\\ x << a.\n  Definition Ge_fa a w := forall x, In x w -> x << a.\n  Definition Ge_ex_fa a lw := exists w, In w lw /\\ Ge_fa a w.\n  Definition Ge_fa_fa a lw := forall w, In w lw -> Ge_fa a w.\n\n  Fixpoint Incr w :=\n    match w with\n      | nil   => True\n      | a::w  => Ge_fa a w /\\ Incr w\n    end.\n\n  Fact Incr_spec w : Incr w <-> forall l a r, w = l++a::r -> Ge_fa a r.\n  Proof.\n    split.\n\n    induction w as [ | b w IH ]; intros H [ | x l ] a r E; try discriminate E; simpl in E;\n    injection E; clear E; intros; subst; simpl in H; auto.\n    apply H.\n    destruct H as [ _ H ]; apply (IH H) with (1 := eq_refl).\n    \n    intros H.\n    induction w as [ | x w IH ]; simpl in H |- *; auto; split.\n    apply H with (l := nil); auto.\n    apply IH.\n    intros l a r ?; apply (H (x::l)); simpl; f_equal; auto.\n  Qed.  \n\n  Fact Ge_ex_sg a b : Ge_ex a (b::nil) <-> b << a.\n  Proof.\n    split.\n    intros (? & [ | [] ] & ?); subst; auto.\n    exists b; split; auto; left; auto.\n  Qed.\n\n  Fact Ge_fa_sg a b : Ge_fa a (b::nil) <-> b << a.\n  Proof.\n    split.\n    intros H; apply H; left; auto.\n    intros ? ? [ ? | [] ]; subst; auto.\n  Qed.\n\n  Fact Ge_ex_fa_sg a w : Ge_ex_fa a (w::nil) <-> Ge_fa a w.\n  Proof.\n    split.\n    intros (? & [ | [] ] & ?); subst; auto.\n    exists w; split; auto; left; auto.\n  Qed.\n\n  Fact Ge_ex_fa_app a ll mm : Ge_ex_fa a (ll++mm) <-> (Ge_ex_fa a ll \\/ Ge_ex_fa a mm).\n  Proof.\n    split.\n    intros (x & H1 & H2).\n    apply in_app_or in H1.\n    destruct H1; [ left | right ]; exists x; auto.\n    intros [ (x & ? & ?) | (x & ? & ?) ]; exists x; split; auto; \n      apply in_or_app; [ left | right ]; auto.\n  Qed.\n\n  Inductive good : list A -> Prop := \n    | in_good_0 : forall ll a b, In b ll -> b << a -> good (a::ll)\n    | in_good_1 : forall ll a, good ll -> good (a::ll).\n\n  Inductive bad : list A -> Prop :=\n    | in_bad_0 : bad nil\n    | in_bad_1 : forall ll a, (forall b, In b ll -> ~ b << a) -> bad ll -> bad (a::ll).\n    \n  Fact good_mono a ll : good ll -> good (a::ll).\n  Proof.\n    constructor 2; auto.\n  Qed.\n\n  Fact good_nil_inv : ~ good nil.\n  Proof. intros H; inversion H. Qed.\n\n  Fact good_cons_inv a ll : good (a::ll) -> Ge_ex a ll \\/ good ll.\n  Proof. \n    intros H; inversion_clear H.\n    left; exists b; auto.\n    right; auto.\n  Qed.\n\n  Fact good_sg_inv a : ~ good (a::nil).\n  Proof.\n    intros H; apply good_cons_inv in H.\n    destruct H as [ (? & [] & _ ) | H ].\n    revert H; apply good_nil_inv.\n  Qed.\n\n  Fact good_cons_not_inv a ll : good (a::ll) -> ~ good ll -> Ge_ex a ll.\n  Proof.\n    intros H ?; apply good_cons_inv in H; tauto.\n  Qed.\n\n  Fact good_two_inv a b : good (a::b::nil) -> b << a.\n  Proof.\n    intros H.\n    apply good_cons_inv in H.\n    destruct H as [ H | H ].\n    apply Ge_ex_sg in H; auto.\n    apply good_sg_inv in H; destruct H.\n  Qed.\n\n  Fact good_bad_False ll : good ll -> bad ll -> False.\n  Proof.\n    induction 1 as [ ll a b H1 H2 | ll a Hll IH ].\n    inversion_clear 1.\n    apply H0 with (1 := H1); auto.\n    inversion_clear 1; auto.\n  Qed.\n\n  Fact not_good_eq_bad ll : ~ good ll <-> bad ll.\n  Proof.\n    split.\n\n    induction ll; intros H.\n    constructor.\n    constructor.\n    intros; contradict H.\n    constructor 1 with (1 := H0); auto.\n    apply IHll; contradict H.\n    constructor 2; auto.\n    \n    intros ? ?; apply good_bad_False with ll; auto.\n  Qed.\n\n  Fact good_or_bad_implies_dec : (forall ll, { good ll } + { bad ll }) -> (forall x y, { x << y } + { ~ x << y }).\n  Proof.\n    intros H x y.\n    destruct (H (y::x::nil)).\n    left.\n    inversion_clear g.\n    destruct H0 as [ | [] ]; subst; tauto.\n    inversion_clear H0.\n    destruct H1.\n    inversion_clear H1.\n    right.\n    inversion_clear b.\n    apply H0; left; auto.\n  Qed.\n \n  Fact good_sublist ll mm : ll <sl mm -> good ll -> good mm.\n  Proof.\n    induction 1 as [ mm | a ll mm H IH | a ll mm H IH ].\n    intros H; inversion H.\n    intros H'; apply good_cons_inv in H'.\n    destruct H' as [ (b & H1 & H2) | H' ].\n    constructor 1 with b; auto.\n    apply sl_In with (1 := H); auto.\n    constructor 2; auto.\n    constructor 2; auto.\n  Qed.\n\n  Fact good_app_left ll mm : good mm -> good (ll++mm).\n  Proof.\n    apply good_sublist, sl_app_left.\n  Qed.\n\n  Fact good_app_right ll mm : good ll -> good (ll++mm).\n  Proof.\n    apply good_sublist, sl_app_right.\n  Qed.\n\n  Fact good_pfx_rev f a b : a <= b -> good (pfx_rev f a) -> good (pfx_rev f b).\n  Proof.\n    intros H.\n    rewrite (le_plus_minus _ _ H), plus_comm, pfx_rev_plus.\n    apply good_app_left.\n  Qed.\n \n  Fact good_inv ll : good ll <-> exists l a m b r, ll = l++a::m++b::r /\\ b << a.\n  Proof.\n    split.\n\n    induction 1 as [ ll a b Hll H1 | ll x Hll IH ].\n    apply in_split in Hll; destruct Hll as ( m & r & H2 ).\n    exists nil, a, m, b, r; subst; auto.\n    destruct IH as (l & a & m & b & r & H1 & H2).\n    exists (x::l), a, m, b, r; subst; auto.\n    \n    intros (l & a & m & b & r & H1 & H2); subst.\n    apply good_app_left.\n    constructor 1 with b; auto.\n    apply in_or_app; right; left; auto.\n  Qed.\n\n  Fact good_pfx_rev_eq n f : good (pfx_rev f n) <-> exists i j, i < j < n /\\ R (f i) (f j).\n  Proof.\n    rewrite good_inv; split.\n    \n    intros (l & a & m & b & r & H1 & H2).\n    exists (length r), (length (m++b::r)); split.\n    apply f_equal with (f := @length _) in H1.\n    rewrite pfx_rev_length in H1.\n    rewrite H1.\n    do 3 (rewrite app_length; simpl); split; omega.\n    rewrite pfx_rev_eq with (1 := H1).\n    cutrewrite (l++a::m++b::r = (l++a::m)++b::r) in H1.\n    rewrite pfx_rev_eq with (1 := H1); auto.\n    rewrite app_ass; simpl; auto.\n    \n    intros (i & j & (H1 & H2) & H3).\n    exists (pfx_rev (fun x => f (S j + x)) (n - S j)), \n           (f j), \n           (pfx_rev (fun x => f (S i + x)) (j - S i)),\n           (f i),\n           (pfx_rev f i).\n    split; auto.\n    assert (n = (n - S i) + S i) as H; try omega.\n    rewrite H at 1.\n    rewrite pfx_rev_plus; simpl.\n    assert (n - S i = (n - S j) + S (j - S i)) as H'; try omega.\n    rewrite H' at 1.\n    rewrite pfx_rev_plus; simpl.\n    rewrite app_ass; simpl.\n    f_equal.\n    apply pfx_rev_ext; intros; f_equal; omega.\n    f_equal.\n    f_equal; omega.\n  Qed.\n  \n  Fact good_pfx_eq n f : good (pfx f n) <-> exists i j, i < j < n /\\ R (f j) (f i).\n  Proof.    \n    rewrite <- (rev_involutive (pfx f n)).\n    rewrite <- pfx_pfx_rev_eq.\n    rewrite pfx_rev_minus.\n    rewrite <- pfx_pfx_rev_eq.\n    rewrite good_pfx_rev_eq.\n    split; intros (i & j & H1 & H2).\n    exists (n - S j), (n - S i); split; auto; omega.\n    exists (n - S j), (n - S i); split.\n    omega.\n    replace_with H2; f_equal; omega.\n  Qed.\n    \n  Fact exists_good_app ll mm : (exists a b, In a ll /\\ In b mm /\\ R b a) -> good (ll++mm).\n  Proof.\n    intros (a & b & H1 & H2 & H3).\n    revert a H1 b H2 H3.\n    induction ll as [ | x ll IHll ].\n    intros ? [].\n    intros a [ ? | Ha ] b Hb ?; subst; simpl.\n    constructor 1 with b; auto; apply in_or_app; tauto.\n    constructor 2; apply IHll with (1 := Ha) (2 := Hb); auto.\n  Qed.\n\n  Fact good_app_inv ll mm : good (ll++mm) -> good ll\n                                          \\/ good mm\n                                          \\/ exists a b, In a ll /\\ In b mm /\\ b << a.\n  Proof.\n    induction ll as [ | x ll IH ]; simpl.\n    tauto.\n    intros H.\n    apply good_cons_inv in H.\n    destruct H as [ (a & H1 & H2) | H ].\n    apply in_app_or in H1; destruct H1 as [ H1 | H1 ].\n    left; constructor 1 with a; auto.\n    right; right; exists x, a; tauto.\n    apply IH in H.\n    destruct H as [ H | [ H | (a & b & H1 & H2 & H3) ] ].\n    left; constructor 2; auto.\n    tauto.\n    right; right; exists a, b; tauto.\n  Qed.   \n\n  Fact good_eq_exists ll : good ll <-> exists l a m b r, ll = l++a::m++b::r /\\ b << a.\n  Proof.\n    apply good_inv.\n  Qed.\n\n  Fact sublist_good_eq ll : good ll <-> exists a b, R b a /\\ a::b::nil <sl ll.\n  Proof.\n    split.\n\n    induction 1 as [ l a b H1 H2 | l b H (u & v & H1 & H2)].\n    exists a, b; split; auto; constructor 2; apply In_sl; auto.\n    exists u, v; split; auto; constructor 3; auto.\n   \n    intros (a & b & H1 & H2).\n    apply good_sublist with (1 := H2).\n    constructor 1 with b; auto; left; auto.\n  Qed.\n\n  Section decision_procedures.\n\n    Variable Rdec : forall x y, { x << y } + { ~ x << y }.\n    \n    Definition Ge_ex_dec a w : { Ge_ex a w } + { ~ Ge_ex a w }.\n    Proof.\n      destruct list_dec_rec with (P := fun x => x << a) (ll := w) \n        as [ (x & H1 & H2) | H ]; simpl; auto.\n      left; exists x; auto.\n      right; intros (x & H1 & H2); apply H with (1 := H1); auto.\n    Qed.\n\n    Definition Ge_fa_dec a w : { Ge_fa a w } + { ~ Ge_fa a w }.\n    Proof.\n      destruct list_dec_rec with (P := fun x => ~ x << a) (ll := w) \n        as [ (x & H1 & H2) | H ]; simpl; auto.\n      intros x; destruct (Rdec x a); tauto.\n      left; intros z Hz.\n      destruct (Rdec z a) as [ | C ]; try tauto.\n      apply H in C; tauto.\n    Qed.\n\n    Definition Ge_ex_fa_dec a lw : { Ge_ex_fa a lw } + { ~ Ge_ex_fa a lw }.\n    Proof.\n      destruct list_dec_rec with (P := fun w => Ge_fa a w) (ll := lw) \n        as [ (w & H1 & H2) | H ]; auto.\n      intros; apply Ge_fa_dec.\n      left; exists w; auto.\n      right; intros (x & H1 & H2).\n      revert H2; apply H; auto.\n    Qed.\n\n    Fact Ge_ex_fa_app_dec a ll mm : Ge_ex_fa a (ll++mm) -> { Ge_ex_fa a ll } + { Ge_ex_fa a mm }.\n    Proof.\n      intros H.\n      rewrite Ge_ex_fa_app in H.\n      destruct (Ge_ex_fa_dec a ll); \n      destruct (Ge_ex_fa_dec a mm); tauto.\n    Qed.\n\n    Definition good_bad_dec ll : { good ll } + { bad ll }.\n    Proof.\n      induction ll as [ | x ll [ IH | IH ] ].\n      right; constructor 1.\n      left; constructor 2; auto.\n      destruct (list_dec_rec (fun y => y << x) ll) as [ (y & H1 & H2) | H ].\n      intros; apply Rdec.\n      left; constructor 1 with (1 := H1); auto.\n      right; constructor; auto.\n    Qed.\n\n    Definition good_dec ll : { good ll } + { ~ good ll }.\n    Proof. \n      destruct (good_bad_dec ll); [ left | right ]; auto.\n      rewrite not_good_eq_bad; auto.\n    Qed.\n\n  End decision_procedures.\n\n  Fact sublist_good ll mm : ll <sl mm -> good ll -> good mm.\n  Proof.\n    induction 1 as [ mm | x ll mm H IH | x ll mm H IH ]; intros H1.\n    apply good_nil_inv in H1; tauto.\n    apply good_cons_inv in H1; destruct H1 as [ (y & H1 & H2) | H1 ].\n    constructor 1 with y; auto.\n    apply sl_In with (1 := H); auto.\n    constructor 2; auto.\n    constructor 2; auto.\n  Qed.\n\n  (* From Fridlender Thesis *)\n\n  Definition ctxt ll a1 a2 := good ll \\/ Ge_ex a1 ll \\/ a1 << a2.\n\n  Fact ctxt_nil a1 a2 : ctxt nil a1 a2 <-> a1 << a2.\n  Proof.\n    split.\n    intros [ H | [ H | H ] ]; auto.\n    apply good_nil_inv in H; tauto.\n    destruct H as (? & [] & _).\n    right; right; auto.\n  Qed.\n  \n  Fact ctxt_cons a ll a1 a2 : ctxt (a::ll) a1 a2 <-> ctxt ll a1 a2 \\/ ctxt ll a a1.\n  Proof.\n    split.\n\n    intros [ H | [ H | H ] ]; auto.\n    apply good_cons_inv in H.\n    destruct H as [ H | H ].\n    right; right; left; auto.\n    right; left; auto.\n    destruct H as (x & [ H | H ] & H1); subst.\n    right; right; right; auto.\n    left; right; left; exists x; auto.\n    left; right; right; auto.\n    \n    intros [ H | H ]; revert H; intros  [ H | [ H | H ] ].\n\n    left; constructor 2; auto.\n    destruct H as ( x & H1 & H2 ).\n    right; left; exists x; split; auto; right; auto.\n    right; right; auto.    \n    \n    left; constructor 2; auto.\n    destruct H as ( x & H1 & H2 ).\n    left; constructor 1 with x; auto.\n    right; left; exists a; split; auto; left; auto.   \n\n  Qed.\n\n  (* this looks very much like Coquand lift_rel *)\n\n  Fact lift_rel_list_ctxt ll : R lrlift ll ~eq2 ctxt ll.\n  Proof.\n    induction ll as [ | a ll IH ]; simpl; split; intros u v;\n    (rewrite ctxt_nil || rewrite ctxt_cons); auto; unfold lift_rel;\n    intros [ | ]; [ left | right | left | right ]; apply IH; auto.\n  Qed.\n  \nEnd Ge_Good.\n\nFact good_inc X (R S : X -> X -> Prop) : R inc2 S -> good R inc1 good S.\nProof.\n  intros H ll.\n  induction 1 as [ ll a b Hll Hab | ].\n  constructor 1 with (1 := Hll); auto.\n  constructor 2; auto.\nQed.\n\nSection good_map.\n  \n  Variable (X Y : Type) (f : X -> Y) (R : X -> X -> Prop) (S : Y -> Y -> Prop) \n           (HRS2 : forall x y, S (f x) (f y) -> R x y)\n           (HRS1 : forall x y, R x y -> S (f x) (f y)).\n\n  Fact good_map_inv ll : good S (map f ll) -> good R ll.\n  Proof.\n    set (ll' := map f ll).\n    generalize (eq_refl ll').\n    unfold ll' at 2.\n    intros H1 H2.\n    generalize ll' H2 ll H1.\n    clear ll ll' H1 H2.\n    induction 1 as [ ll' a b Hll Hab | ll' a H1 IH ]; intros [ | x ll ] Hll'; try discriminate Hll'; \n      simpl in Hll'; injection Hll'; clear Hll'; intros; subst.\n    apply in_map_iff in Hll.\n    destruct Hll as (y & H1 & H2); subst.\n    constructor 1 with y; auto.\n    specialize (IH _ eq_refl).\n    constructor 2; auto.\n  Qed.\n  \n  Fact good_map ll : good R ll -> good S (map f ll).\n  Proof.\n    induction 1 as [ ll a b Hll Hab | ll a H1 IH ]; simpl.\n    constructor 1 with (f b); auto.\n    apply in_map_iff; exists b; auto.\n    constructor 2; auto.\n  Qed.    \n   \nEnd good_map.\n\nFact good_lift_rel X R ll a : good (R rlift a) ll -> @good X R (ll++a::nil).\nProof.\n  induction 1 as [ ll u v H1 [ H2 | H2 ] | ll u H IH ]; simpl.\n  apply in_good_0 with v; auto.\n  apply in_or_app; left; auto.\n  apply in_good_1.\n  induction ll as [ | x ll IH]; simpl; destruct H1; subst.\n  simpl; apply in_good_0 with a; auto.\n  apply in_or_app; right; left; auto.\n  apply in_good_1; auto.\n  apply in_good_1; auto.\nQed.\n\nFact good_lift_rel_list X R mm ll : good (R lrlift mm) ll -> @good X R (ll++mm).\nProof.\n  revert ll.\n  induction mm as [ | a mm IH ]; simpl; intros ll.\n  rewrite <- app_nil_end; auto.\n  intros H.\n  apply good_lift_rel, IH in H.\n  revert H.\n  rewrite app_ass; simpl; auto.\nQed.\n\nFact good_snoc X R ll a : @good X R (ll++a::nil) -> good (R rlift a) ll \\/ exists x, R a x /\\ In x ll.\nProof.\n  intros H2.\n  apply good_app_inv in H2.\n  destruct H2 as [ H2 | [ H2 | H2 ] ].\n  left; revert H2; apply good_inc; red; auto.\n  apply good_sg_inv in H2; destruct H2.\n  destruct H2 as (x & b & H2 & [ | [] ] & H3); subst b.\n  right; exists x; auto.\nQed. \n\nFact Forall_map_proj1_sig X (P : X -> Prop) (ll : list (sig P)) : Forall P (map (@proj1_sig _ _) ll).\nProof.\n  induction ll as [ | (x & Hx) ll IH ]; simpl; constructor; auto.\nQed.\n\nFact good_Restr X (R : X -> X -> Prop) P ll : good (R <# P #>) ll <-> good R (map (@proj1_sig _ _) ll) /\\ Forall P (map (@proj1_sig _ _) ll).\nProof.\n  split.\n\n  induction 1 as [ ll (a & Ha) (b & Hb) H1 H2 | ll (a & Ha) H1 (H2 & H3) ]; split.\n\n  simpl.\n  constructor 1 with b.\n  rewrite in_map_iff.\n  exists (exist _ b Hb); auto.\n  simpl in H2; auto.\n  simpl; constructor; auto.\n  apply Forall_map_proj1_sig.\n  \n  simpl; constructor 2; auto.\n  simpl; constructor; auto.\n  \n  intros (H1 & H2).\n  induction ll as [ | (a & Ha) ll IH ].\n  apply good_nil_inv in H1; destruct H1.\n  simpl in H1; apply good_cons_inv in H1.\n  simpl in H2; apply Forall_cons_inv in H2.\n  destruct H2 as [ H2 H3 ].\n  destruct H1 as [ (b & Hb & H1) | H1 ].\n  2: constructor 2; auto.\n  rewrite in_map_iff in Hb.\n  destruct Hb as ((b' & Hb) & H4 & H5); simpl in H4; subst b'.\n  constructor 1 with (exist _ b Hb); auto.\nQed.\n\nSection interleave.\n\n  Variable X : Type.\n\n  Inductive interleave : list X -> list X -> list X -> Prop :=\n    | in_intl_0 : forall m, interleave nil m m\n    | in_intl_1 : forall l, interleave l nil l\n    | in_intl_2 : forall a l m k, interleave l m k -> interleave (a::l) m (a::k)\n    | in_intl_3 : forall l b m k, interleave l m k -> interleave l (b::m) (b::k).\n\n  Variable (R : X -> X -> Prop).\n\n  Fact In_inlt_left x l m k : interleave l m k -> In x l -> In x k.\n  Proof.\n     induction 1 as [ m | l | a l m k H IH | l b m k H IH ]; auto.\n     intros [].\n     intros [ [] | ]; [ left | right ]; auto.\n     right; auto.\n  Qed.\n\n  Fact In_inlt_right x l m k : interleave l m k -> In x m -> In x k.\n  Proof.\n     induction 1 as [ m | l | a l m k H IH | l b m k H IH ]; auto.\n     intros [].\n     right; auto.\n     intros [ [] | ]; [ left | right ]; auto.\n  Qed.\n\n  Fact good_intl_left l m k : interleave l m k -> good R l -> good R k.\n  Proof.\n    induction 1 as [ m | l | a l m k H IH | l b m k H IH ]; auto.\n    intros H; apply good_nil_inv in H; destruct H.\n    intros H1; apply good_cons_inv in H1.\n    destruct H1 as [ (x & H1 & H2) | H1 ].\n    constructor 1 with x; auto.\n    revert H1; apply In_inlt_left with (1 := H).\n    constructor 2; auto.\n    constructor 2; auto.\n  Qed.\n\n  Fact good_intl_right l m k : interleave l m k -> good R m -> good R k.\n  Proof.\n    induction 1 as [ m | l | a l m k H IH | l b m k H IH ]; auto.\n    intros H; apply good_nil_inv in H; destruct H.\n    constructor 2; auto.\n    intros H1; apply good_cons_inv in H1.\n    destruct H1 as [ (x & H1 & H2) | H1 ].\n    constructor 1 with x; auto.\n    revert H1; apply In_inlt_right with (1 := H).\n    constructor 2; auto.\n  Qed.\n\nEnd interleave.\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/good_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633915959134569, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6591854604227305}}
{"text": "(* 1 *)\n\nInductive month : Set :=\n    January   | Febuary | March    | April\n  | May       | June    | July     | August\n  | September | October | November | December.\n\nInductive season : Set :=\n    Winter\n  | Spring\n  | Summer\n  | Autumn.\n\nDefinition which_season : month -> season :=\n  month_rec (fun month => season)\n            Winter Winter Spring\n            Spring Spring Summer\n            Summer Summer Autumn\n            Autumn Autumn Winter.\n\n(* 3 *)\n\nTheorem bool_equal :\n  forall b : bool, b = true \\/ b = false.\nProof.\n  intro b;\n    elim b;\n    [apply or_introl | apply or_intror];\n    apply refl_equal.\nQed.\n\nReset bool_equal.\n\nTheorem bool_equal :\n  forall b : bool, b = true \\/ b = false.\nProof.\n  intro b; pattern b; apply bool_ind; [left | right]; reflexivity.\nQed.\n\n(* 4 *)\n\nReset which_season.\n\nDefinition which_season (m : month) : season :=\n  match m with\n     December | January | Febuary => Winter\n   | March    | April   | May     => Spring\n   | June     | July    | August  => Summer\n   | _ => Autumn\n  end.\n\n(* 5 *)\n\nDefinition even_days (leap : bool) (m : month) : bool :=\n  match m with\n    April | June | September | November => true\n  | Febuary => if leap then false else true\n  | _ => false\n  end.\n\n(* 6 *)\n\nDefinition bool_eq (a b : bool) : bool :=\n  match a,b with\n    true,true | false,false => true\n  | _,_ => false\n  end.\n\nDefinition bool_not (a : bool) : bool := if a then false else true.\n\nDefinition bool_xor (a b : bool) : bool := bool_not (bool_eq a b).\n\nDefinition bool_and (a b : bool) : bool :=\n  match a,b with\n    true,true => true\n  | _,_ => false\n  end.\n\nDefinition bool_or (a b : bool) : bool :=\n  match a,b with\n    true,_ | _,true => true\n  | _,_ => false\n  end.\n\nTheorem xor_not_eq : forall b1 b2 : bool,\n    bool_xor b1 b2 = bool_not (bool_eq b1 b2).\nProof. trivial. Qed.\n\nTheorem not_and_or_not_not : forall b1 b2 : bool,\n    bool_not (bool_and b1 b2) =\n    bool_or (bool_not b1) (bool_not b2).\nProof.\n  intros b1 b2;\n    induction b1; induction b2;\n                  simpl; trivial.\nQed.\n\nTheorem not_not_eq_b : forall b : bool,\n    bool_not (bool_not b) = b.\nProof.\n  intros b; unfold bool_not; induction b; trivial.\nQed.\n\n\nTheorem bool_tex : forall b : bool,\n                   (bool_or b (bool_not b)) = true.\nProof.\n  intros b; induction b; simpl; trivial.\nQed.\n\nTheorem bool_eq_reflect : forall b1 b2 : bool,\n    (bool_eq b1 b2) = true -> b1 = b2.\nProof.\n  intros b1 b2; induction b1; induction b2; simpl; trivial.\n  intros H; rewrite H; elim H; trivial.\nQed.\n\nTheorem bool_eq_reflect2 : forall b1 b2 : bool,\n                           b1 = b2 -> (bool_eq b1 b2) = true.\nProof.\n  intros b1 b2. induction b1; induction b2; simpl; trivial.\n  intros H; rewrite H; elim H; trivial.\nQed.\n\nTheorem bool_not_or : forall b1 b2 : bool,\n    (bool_not (bool_or b1 b2)) =\n    (bool_and (bool_not b1) (bool_not b2)).\nProof.\n  intros b1 b2; induction b1; induction b2; simpl; trivial.\nQed.\n\nTheorem bool_or_and_distr: forall b1 b2 b3 : bool,\n        (bool_or (bool_and b1 b3) (bool_and b2 b3))\n        = (bool_and (bool_or b1 b2) b3).\nProof.\n  intros b1 b2 b3. induction b1; induction b2; induction b3; simpl; trivial.\nQed.\n\n(* 8 *)\n\nRequire Import ZArith.\n\nOpen Scope Z_scope.\n\nRecord plane : Set := point {abscissa : Z; ordinate : Z}.\n\nDefinition manhattan (a b : plane) : Z :=\n  (Z.abs (abscissa a - abscissa b)) + (Z.abs (ordinate a - ordinate b)).\n\n(* 9 *)\n\nInductive vehicle : Set :=\n  bicycle : nat -> vehicle | motorized : nat -> nat -> vehicle.\n\nDefinition nb_seats : vehicle -> nat :=\n  vehicle_rec (fun _ => nat)\n              (fun n => n)\n              (fun n _ => n).\n\n(* 10 *)\n\nDefinition next_month : month -> month :=\n  month_rec (fun m => month)\n            Febuary March April May\n            June July August September\n            October November December January.\n\nDefinition is_jan : month -> Prop :=\n  month_rect (fun month => Prop)\n             True False False False\n             False False False False\n             False False False False.\n\n(* 11 *)\n\nDefinition bool_to_prop (b : bool) : Prop :=\n  match b with\n    true => True | _ => False\n  end.\n\nTheorem true_not_false : true <> false.\nProof.\n  unfold not; intros H.\n  change (bool_to_prop false).\n  rewrite <- H.\n  simpl.\n  trivial.\nQed.\n\n(* 12 *)\n  \nDefinition vehicle_to_prop (v : vehicle) : Prop :=\n  match v with\n    bicycle _ => True\n  |  _ => False\n  end.\n\nTheorem bi_not_motor : forall n m l: nat,\n    bicycle n <> motorized m l.\nProof.\n  intros n m l H.\n  change (vehicle_to_prop (motorized m l)).\n  rewrite <- H.\n  simpl.\n  trivial.\nQed.\n\n(* 13 *)\n\nRequire Import Arith.\n\nOpen Scope nat_scope.\n\nRecord RatPlus : Set :=\n  mkRat {top : nat; bottom:nat; bottom_condition: bottom <> 0}.\n\nAxiom eq_ratplus :\n  forall r r',\n    top r * bottom r' = top r' * bottom r ->\n    r = r'.\n\nDefinition r : RatPlus.\n  apply (mkRat 2 4); auto with arith.\nDefined.\n\nDefinition r' : RatPlus.\n  apply (mkRat 3 6); auto with arith.\nDefined.\n\nTheorem r_r'_eq : r = r'.\nProof.\n  apply eq_ratplus; auto.\nQed.\n\nTheorem r_not_r' : r <> r'.\n  unfold not. intros H. discriminate H.\nQed.\n\nTheorem rat_contradiction : False.\n  absurd (r = r').\n  apply r_not_r'.\n  apply r_r'_eq.\nQed.\n\nReset eq_RatPlus.\n\n(* 15 *)\n\nDefinition true_under_three (n : nat) : bool :=\n  match n with\n    0 => true\n  | 1 => true\n  | 2 => true\n  | _ => false\n  end.\n\nEval compute in true_under_three 2.\n\n(* 16 *)\n\nFixpoint rev_plus (n m : nat) {struct m} : nat :=\n  match m with 0 => n | S p => S (rev_plus n p) end.\n\nEval compute in rev_plus 3 5.\n\n(* 17 *)\n\nFixpoint sum_f (n : nat) (f : nat -> Z) : Z :=\n  match n with\n    0 => 0\n  | S k => f k + sum_f k f\n  end.\n\n(* 18 *)\n\nFixpoint two_power (n : nat) : nat :=\n  match n with\n    0 => 1\n  | S k => 2 * two_power k\n  end.\n\n\n(* 20 *)\n\nDefinition pos_even_bool (p : positive) : bool :=\n  match p with xO _ => true | _ => false end.\n\n(* 21 *)\n\nDefinition pos_div4 (p : positive) : Z :=\n  match p with\n    xO (xO n) | xO (xI n) => Zpos n\n  | xI (xI n) | xI (xO n) => Zpos n\n  | _ => 0\n  end.\n\n(* 22 *)\n\nVariable pos_mult : positive -> positive -> positive.\n\nDefinition mul (n m : Z) : Z :=\n  match n,m with\n    Zpos x, Zpos y | Zneg x, Zneg y => Zpos (pos_mult x y)\n  | Zpos x, Zneg y | Zneg x, Zpos y => Zneg (pos_mult x y)\n  | _,_ => Z0\n  end.\n\n(* 23 *)\n\nInductive l : Set :=\n    l_and : l -> l -> l\n  | l_or : l -> l -> l\n  | not_l : l -> l\n  | l_imp : l -> l -> l\n  | l_t : l\n  | l_f : l.\n\nFixpoint l_eval (form : l) : l :=\n  match form with\n  | l_and la lb => match (l_eval la),(l_eval lb) with\n                     l_t, l_t => l_t\n                   | _,_ => l_f\n                   end\n  | l_or la lb => match (l_eval la),(l_eval lb) with\n                    l_t,_ | _,l_t => l_t\n                  | _,_ => l_f\n                  end\n  | not_l la => match l_eval la with\n                  l_t => l_f\n                | _ => l_t\n                end\n  | l_imp la lb => match (l_eval la),(l_eval lb) with\n                     _,l_t | l_f, l_f => l_t\n                   | _,_ => l_f\n                   end\n  | l_t => l_t\n  | l_f => l_f\n  end.\n\n(* 24 *)\n\nInductive rat : Set :=\n  one : rat | N : rat -> rat | D : rat -> rat.\n\n(* 25 *)\n\nInductive Z_btree : Set :=\n  Z_leaf : Z_btree | Z_node : Z -> Z_btree -> Z_btree -> Z_btree.\n\nFixpoint value_present (z : Z) (t : Z_btree) : bool :=\n  match t with\n    Z_leaf => false\n  | Z_node x l r =>\n    if Zeq_bool z x then true\n    else match value_present z l with\n           true => true\n         | _ => value_present z r\n         end\n  end.\n\n(* 26 *)\n\nFixpoint power (z : Z) (n : nat) : Z :=\n  match n with\n    0%nat => 1 | S p => z * (power z p)\n  end.\n\nFixpoint discrete_log (p : positive) : nat :=\n  match p with\n    xH => 0%nat\n  | xO n | xI n => S (discrete_log n)\n  end.\n\n(* 27 *)\n\n\nInductive Z_fbtree : Set :=\n  Z_fleaf : Z_fbtree\n| Z_fnode : Z -> (bool -> Z_fbtree) -> Z_fbtree.\n\nFixpoint fzero_present (t : Z_fbtree) : bool :=\n  match t with\n    Z_fleaf => false\n  | Z_fnode z f =>\n    if Zeq_bool z 0%Z then true\n    else match fzero_present (f true) with\n           true => true\n         | _ => fzero_present (f false)\n         end\n  end.\n\n(* 28 *)\n\nInductive Z_inf_tree : Set :=\n  Z_inf_leaf : Z_inf_tree\n| Z_inf_branch : Z -> (nat -> Z_inf_tree) -> Z_inf_tree.\n\nFixpoint sum_or (n : nat) (f : nat -> bool) : bool :=\n  match n with\n    0 => false\n  | S k => if f (S k) then true else sum_or k f\n  end.\n\nFixpoint zero_in_inf (n : nat) (t : Z_inf_tree) : bool :=\n  match n,t with\n  | S k, Z_inf_branch z f => if Zeq_bool z 0 then true else sum_or k (fun x : nat => zero_in_inf k (f x))\n  | Z, Z_inf_branch z _ => Zeq_bool z 0\n  | _, Z_inf_leaf => false\n  end.\n\n(* 29 *)\n\nLtac refl := reflexivity.\n\nTheorem plus_n_0 : forall n : nat, n = n + 0.\nProof.\n  intro n. elim n. refl.\n  intros n' H. simpl. elim H. refl.\nQed.\n\n(* 30 *)\n\nFixpoint zb_to_zfb  (t : Z_btree) : Z_fbtree :=\n  match t with\n    Z_leaf => Z_fleaf\n  | Z_node x l r =>\n      Z_fnode x (fun b : bool => if b\n                                 then zb_to_zfb l\n                                 else zb_to_zfb r)\n  end.\n\nFixpoint zfb_to_zb  (t : Z_fbtree) : Z_btree :=\n  match t with\n    Z_fleaf => Z_leaf\n  | Z_fnode x f => Z_node x\n                          (zfb_to_zb (f true))\n                          (zfb_to_zb (f false))\n  end.\n\nTheorem zb_to_zfb_and_back :\n  forall t : Z_btree, zfb_to_zb (zb_to_zfb t) = t.\nProof.\n  induction t.\n  simpl; refl.\n  simpl; rewrite IHt1; rewrite IHt2; refl.\nQed.\n\n(*\nTheorem zfb_to_zb_and_back :\n  forall t : Z_fbtree, zb_to_zfb (zfb_to_zb t) = t.\n*)\n\n(* 31 *)\n\nFixpoint mult2 (n : nat) : nat :=\n  match n with\n    0 => 0\n  | S k => S (S (mult2 k))\n  end.\n\nTheorem plus_n_eq_x_2 :\n  forall n : nat, mult2 n = n + n.\nProof.\n  induction n.\n  trivial.\n  simpl.\n  rewrite IHn.\n  rewrite plus_n_Sm.\n  trivial.\nQed.\n  \n\n(* 32 *)\n\nFixpoint sum_n (n : nat) : nat :=\n  match n with\n    0 => 0\n  | S p => S p + sum_n p\n  end.\n\n(* misprint?  *)\n  \n(* 33 *)\n\nRequire Import Arith.\n\nTheorem n_lt_sum_n :\n  forall n : nat, n <= sum_n n.\nProof.\n  induction n.\n  refl.\n  simpl.\n  rewrite le_n_S.\n  2: apply IHn.\n  rewrite plus_n_Sm.\n  apply le_plus_r.\nQed.\n\n(* 34 *)\n\nRequire Import List.\n\nDefinition fst_2 (A : Set) (l : list A) : list A :=\n  match l with\n    x :: y :: _ => x :: y :: nil\n  | _ => nil\n  end.\n\n(* 35 *)\n  \nFixpoint fst_n (A : Set) (n : nat) (l : list A) {struct n} : list A :=\n  match n,l with\n    S k, x :: xs => x :: fst_n _ k xs\n  | _,_ => nil\n  end.\n\n(* 36 *)\n\nFixpoint sum_list (l : list Z) : Z :=\n  match l with\n    x :: xs => x + sum_list xs\n  | _ => 0\n  end.\n\n(* 37 *)\n\nFixpoint n_ones (n : nat) : list Z :=\n  match n with  \n    S k => 1%Z :: n_ones k\n  | O => nil\n  end.\n\n(* 38 *)\n\nFixpoint one_to_n (n : nat) : list Z :=\n  match n with\n    O => nil\n  | S k => one_to_n k ++ Z.of_nat (S k) :: nil\n  end.\n\n(* 39 *)\n\nFixpoint nth_option (A:Set)(n:nat)(l:list A) {struct l}\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  | n, nil => None\n  end.\n\nFixpoint nth_option' (A : Set) (n : nat) (l : list A) {struct n}\n  : option A :=\n  match n,l with\n    O, a :: t => Some a\n  | S k, a :: t => nth_option _ k t\n  | n, nil => None\n  end.\n\nTheorem nth_eq_prime :\n  forall (A : Set) (n : nat) (l : list A),\n    nth_option A n l = nth_option' A n l.\nProof.\n  intros A n l. induction n; induction l; simpl; trivial.\nQed.\n\n(* 40 *)\n\nTheorem none_means_shorter :\n  forall (A : Set) (n : nat) (l : list A),\n    nth_option A n l = None -> length l <= n.\nProof.\n  simple induction n.\n  destruct l0. simpl. trivial.\n  simpl. intros H. absurd (Some a = None). discriminate H.\n  assumption.\n  intros n0 H l H'.\n  destruct l. simpl. auto with arith.\n  simpl. auto with arith.\nQed.\n\n(* 41 *)\n\nFixpoint la_to_fa (A : Set) (f : A -> bool) (l : list A) {struct l} : option A :=\n  match l with\n    x :: xs => if f x then Some x else la_to_fa _ f xs\n  | _ => None\n  end.\n\n(* 42 *)\n\nFixpoint split_pairs (A B : Set) (l : list (A*B)) {struct l} : (list A) * (list B) :=\n  match l with\n    (a,b) :: ps => ((a :: fst (split_pairs _ _ ps)) , (b :: snd (split_pairs _ _ ps)))\n  | _ => (nil,nil)\n  end.\n\nFixpoint combine (A B : Set) (la : list A) (lb : list B) {struct la} : list (A*B) :=\n  match la,lb with\n    x::xs,y::ys => (x,y) :: combine _ _ xs ys\n  | _,_ => nil\n  end.\n\nTheorem cmb_split_eq_og :\n  forall (A B : Set) (l : list (A*B)), combine A B (fst (split_pairs A B l)) (snd (split_pairs A B l)) = l.\nProof.\n  induction l0. simpl. trivial.\n  case a. intros a0 b. simpl. rewrite IHl0. trivial.\nQed.\n\n(* 43 *)\n\nInductive btree (A : Set) : Set :=\n  leaf : btree A\n| node : A -> btree A -> btree A -> btree A.\n\nFixpoint Z_to_btree (t : Z_btree) : btree Z :=\n  match t with\n    Z_leaf => leaf _\n  | Z_node x l r => node _ x (Z_to_btree l) (Z_to_btree r)\n  end.\n\nFixpoint btree_to_ztree (t : btree Z) : Z_btree :=\n  match t with\n    leaf _ => Z_leaf\n  | node _ x l r => Z_node x (btree_to_ztree l) (btree_to_ztree r)\n  end.\n\nTheorem iso_btree_z_zbtree :\n  forall t : Z_btree, btree_to_ztree (Z_to_btree t) = t.\nProof.\n  intros t. induction t.\n  simpl; trivial.\n\n  simpl; rewrite IHt1; rewrite IHt2; trivial.\nQed.\n\n(* 44 *)\n\n(*\nInductive rat : Set :=\n  one : rat | N : rat -> rat | D : rat -> rat.\n *)\n\nFixpoint frac (r : rat) : nat * nat :=\n  match r with\n    one => (1,1)\n  | N r => let (n,d) := frac r in (n + d, d)\n  | D r => let (n,d) := frac r in (d, n + d)\n  end.\n\n\n(* 45 / 46 skipping till later *)\n\nInductive htree (A : Set) : nat -> Set :=\n  hleaf : A -> htree A 0\n| hnode : forall n : nat, A -> htree A n -> htree A n -> htree A (S n).\n\n(* 47 *)\n\nFixpoint n_to_tree (n : nat) : htree Z n :=\n  match n with\n    S k => hnode _ _ (Z.of_nat (S k)) (n_to_tree k) (n_to_tree k)\n  | O => hleaf Z 0%Z\n  end.\n\n(* 48 *)\n\nInductive binary_word : nat -> Set :=\n  empty_bin : binary_word 0\n| cons_bin : forall m : nat, bool -> binary_word m -> binary_word (S m).\n\nFixpoint binary_word_concat (n m : nat) (w : binary_word n) (w' : binary_word m) {struct w}\n  : binary_word (n + m) :=\n  match w in binary_word p return binary_word (p + m) with\n    empty_bin => w'\n  | cons_bin q b w'' => cons_bin (q + m) b (binary_word_concat q m w'' w')\n  end.\n\n(* 49  and 50 skipping for now*)\n\n(* 51 *)\n\nLemma l1 : forall x y : Empty_set, x = y.\nProof.\n  intros x y.\n  induction x.\nQed.\n\nLemma l2 : forall x y : Empty_set, ~ x=y.\nProof.\n  intros x y.\n  induction x.\nQed.\n", "meta": {"author": "Ablach", "repo": "CoqArt_exercises", "sha": "a2c38b095b6972e57a3c152ec22f3100475b6186", "save_path": "github-repos/coq/Ablach-CoqArt_exercises", "path": "github-repos/coq/Ablach-CoqArt_exercises/CoqArt_exercises-a2c38b095b6972e57a3c152ec22f3100475b6186/ch6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6591845036384536}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\nSet Implicit Arguments.\n\n(** Streams *)\n\nSection Streams.\n\nVariable A : Type.\n\nCoInductive Stream : Type :=\n    Cons : A -> Stream -> Stream.\n\n\nDefinition hd (x:Stream) := match x with\n                            | Cons a _ => a\n                            end.\n\nDefinition tl (x:Stream) := match x with\n                            | Cons _ s => s\n                            end.\n\n\nFixpoint Str_nth_tl (n:nat) (s:Stream) : Stream :=\n  match n with\n  | O => s\n  | S m => Str_nth_tl m (tl s)\n  end.\n\nDefinition Str_nth (n:nat) (s:Stream) : A := hd (Str_nth_tl n s).\n\n\nLemma unfold_Stream :\n forall x:Stream, x = match x with\n                      | Cons a s => Cons a s\n                      end.\nProof.\n  intro x.\n  case x.\n  trivial.\nQed.\n\nLemma tl_nth_tl :\n forall (n:nat) (s:Stream), tl (Str_nth_tl n s) = Str_nth_tl n (tl s).\nProof.\n  simple induction n; simpl; auto.\nQed.\nHint Resolve tl_nth_tl: datatypes.\n\nLemma Str_nth_tl_plus :\n forall (n m:nat) (s:Stream),\n   Str_nth_tl n (Str_nth_tl m s) = Str_nth_tl (n + m) s.\nsimple induction n; simpl; intros; auto with datatypes.\nrewrite <- H.\nrewrite tl_nth_tl; trivial with datatypes.\nQed.\n\nLemma Str_nth_plus :\n forall (n m:nat) (s:Stream), Str_nth n (Str_nth_tl m s) = Str_nth (n + m) s.\nintros; unfold Str_nth; rewrite Str_nth_tl_plus;\n trivial with datatypes.\nQed.\n\n(** Extensional Equality between two streams  *)\n\nCoInductive EqSt (s1 s2: Stream) : Prop :=\n    eqst :\n        hd s1 = hd s2 -> EqSt (tl s1) (tl s2) -> EqSt s1 s2.\n\n(** A coinduction principle *)\n\nLtac coinduction proof :=\n  cofix proof; intros; constructor;\n   [ clear proof | try (apply proof; clear proof) ].\n\n\n(** Extensional equality is an equivalence relation *)\n\nTheorem EqSt_reflex : forall s:Stream, EqSt s s.\ncoinduction EqSt_reflex.\nreflexivity.\nQed.\n\nTheorem sym_EqSt : forall s1 s2:Stream, EqSt s1 s2 -> EqSt s2 s1.\ncoinduction Eq_sym.\ncase H; intros; symmetry ; assumption.\ncase H; intros; assumption.\nQed.\n\n\nTheorem trans_EqSt :\n forall s1 s2 s3:Stream, EqSt s1 s2 -> EqSt s2 s3 -> EqSt s1 s3.\ncoinduction Eq_trans.\ntransitivity (hd s2).\ncase H; intros; assumption.\ncase H0; intros; assumption.\napply (Eq_trans (tl s1) (tl s2) (tl s3)).\ncase H; trivial with datatypes.\ncase H0; trivial with datatypes.\nQed.\n\n(** The definition given is equivalent to require the elements at each\n    position to be equal *)\n\nTheorem eqst_ntheq :\n forall (n:nat) (s1 s2:Stream), EqSt s1 s2 -> Str_nth n s1 = Str_nth n s2.\nunfold Str_nth; simple induction n.\nintros s1 s2 H; case H; trivial with datatypes.\nintros m hypind.\nsimpl.\nintros s1 s2 H.\napply hypind.\ncase H; trivial with datatypes.\nQed.\n\nTheorem ntheq_eqst :\n forall s1 s2:Stream,\n   (forall n:nat, Str_nth n s1 = Str_nth n s2) -> EqSt s1 s2.\ncoinduction Equiv2.\napply (H 0).\nintros n; apply (H (S n)).\nQed.\n\nSection Stream_Properties.\n\nVariable P : Stream -> Prop.\n\n(*i\nInductive Exists : Stream -> Prop :=\n  | Here    : forall x:Stream, P x -> Exists x\n  | Further : forall x:Stream, ~ P x -> Exists (tl x) -> Exists x.\ni*)\n\nInductive Exists ( x: Stream ) : Prop :=\n  | Here : P x -> Exists x\n  | Further : Exists (tl x) -> Exists x.\n\nCoInductive ForAll (x: Stream) : Prop :=\n    HereAndFurther : P x -> ForAll (tl x) -> ForAll x.\n\nLemma ForAll_Str_nth_tl : forall m x, ForAll x -> ForAll (Str_nth_tl m x).\nProof.\ninduction m.\n tauto.\nintros x [_ H].\nsimpl.\napply IHm.\nassumption.\nQed.\n\nSection Co_Induction_ForAll.\nVariable Inv : Stream -> Prop.\nHypothesis InvThenP : forall x:Stream, Inv x -> P x.\nHypothesis InvIsStable : forall x:Stream, Inv x -> Inv (tl x).\n\nTheorem ForAll_coind : forall x:Stream, Inv x -> ForAll x.\ncoinduction ForAll_coind; auto.\nQed.\nEnd Co_Induction_ForAll.\n\nEnd Stream_Properties.\n\nEnd Streams.\n\nSection Map.\nVariables A B : Type.\nVariable f : A -> B.\nCoFixpoint map (s:Stream A) : Stream B := Cons (f (hd s)) (map (tl s)).\n\nLemma Str_nth_tl_map : forall n s, Str_nth_tl n (map s)= map (Str_nth_tl n s).\nProof.\ninduction n.\nreflexivity.\nsimpl.\nintros s.\napply IHn.\nQed.\n\nLemma Str_nth_map : forall n s, Str_nth n (map s)= f (Str_nth n s).\nProof.\nintros n s.\nunfold Str_nth.\nrewrite Str_nth_tl_map.\nreflexivity.\nQed.\n\nLemma ForAll_map : forall (P:Stream B -> Prop) (S:Stream A), ForAll (fun s => P\n(map s)) S <-> ForAll P (map S).\nProof.\nintros P S.\nsplit; generalize S; clear S; cofix ForAll_map; intros S; constructor;\ndestruct H as [H0 H]; firstorder.\nQed.\n\nLemma Exists_map : forall (P:Stream B -> Prop) (S:Stream A), Exists (fun s => P\n(map s)) S -> Exists P (map S).\nProof.\nintros P S H.\n(induction H;[left|right]); firstorder.\nDefined.\n\nEnd Map.\n\nSection Constant_Stream.\nVariable A : Type.\nVariable a : A.\nCoFixpoint const  : Stream A := Cons a const.\nEnd Constant_Stream.\n\nSection Zip.\n\nVariable A B C : Type.\nVariable f: A -> B -> C.\n\nCoFixpoint zipWith (a:Stream A) (b:Stream B) : Stream C :=\nCons (f (hd a) (hd b)) (zipWith (tl a) (tl b)).\n\nLemma Str_nth_tl_zipWith : forall n (a:Stream A) (b:Stream B),\n Str_nth_tl n (zipWith a b)= zipWith (Str_nth_tl n a) (Str_nth_tl n b).\nProof.\ninduction n.\nreflexivity.\nintros [x xs] [y ys].\nunfold Str_nth in *.\nsimpl in *.\napply IHn.\nQed.\n\nLemma Str_nth_zipWith : forall n (a:Stream A) (b:Stream B), Str_nth n (zipWith a\n b)= f (Str_nth n a) (Str_nth n b).\nProof.\nintros.\nunfold Str_nth.\nrewrite Str_nth_tl_zipWith.\nreflexivity.\nQed.\n\nEnd Zip.\n\nUnset Implicit Arguments.\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/Lists/Streams.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757313, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.6591845023534605}}
{"text": "Definition negb (b: bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | false => true\n  | true => (negb b2)\nend.\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", "meta": {"author": "zant", "repo": "gallina", "sha": "5259a6caf0c6abfb3be3437a74b42e8dee32d831", "save_path": "github-repos/coq/zant-gallina", "path": "github-repos/coq/zant-gallina/gallina-5259a6caf0c6abfb3be3437a74b42e8dee32d831/nandb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.659184491071387}}
{"text": "(* begin hide *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.PropExtensionality.\nRequire Import Coq.Logic.Description.\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Unicode.Utf8.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n(* end hide *)\n(** Quotients are crucial in mathematical practice, and it is a shame that they\nare not available in Coq's standard library.  There was a recent discussion on\nthe #<a href=https://github.com/coq/coq/issues/10871>Coq GitHub page</a># on\nthis issue and the consequences of implementing quotients like #<a\nhref=https://leanprover.github.io/>Lean</a># does, where the eliminator for\nfunction types has a reduction rule that breaks pleasant metatheoretic\nproperties such as subject reduction.\n\nIn this post, we are going to define quotients in Coq with three standard\naxioms:\n\n- Functional extensionality\n\n- Propositional extensionality\n\n- Constructive definite description (also known as the axiom of unique choice) *)\n\nCheck @functional_extensionality_dep :\n  ∀ A B (f g : ∀ x : A, B x),\n    (∀ x : A, f x = g x) → f = g.\n\nCheck @propositional_extensionality :\n  ∀ P Q, (P ↔ Q) → P = Q.\n\nCheck @constructive_definite_description :\n  ∀ A P, (exists! x : A, P x) → {x : A | P x}.\n\n(** As far as axioms go, these three are relatively harmless.  In particular,\nthey are valid in any #<a\nhref=https://en.wikipedia.org/wiki/Topos##Elementary_topoi_(topoi_in_logic)>elementary\ntopos</a>#, which are generally regarded as a good universe for doing\nconstructive, higher-order reasoning.  (Naturally, adding axioms in type theory\ndoes not come for free: since they have no useful reduction behavior, our\nquotients won't compute.) *)\n\nSection Quotient.\n\n(** We define the quotient of [T] by an equivalence relation [R] as usual: it is\nthe type of equivalence classes of [R]. *)\n\nContext (T : Type) (R : relation T) (RP : Equivalence R).\n\n(* begin hide *)\nUnset Elimination Schemes.\n(* end hide *)\nRecord quot := Quot_ {\n  quot_class  : T → Prop;\n  quot_classP : ∃ x, quot_class = R x;\n}.\n(* begin hide *)\nSet Elimination Schemes.\n(* end hide *)\n\n(** The projection into the quotient is given by the [Quot] constructor below,\nwhich maps [x] to its equivalence class [R x].  This definition satisfies the\nusual properties: [Quot x = Quot y] if and only if [R x y].  The \"if\" direction\nrequires the principle of proof irrelevance, which is a consequence of\npropositional extensionality. *)\n\nDefinition Quot (x : T) : quot :=\n  @Quot_ (R x) (ex_intro _ x erefl).\n\nLemma Quot_inj x y : Quot x = Quot y → R x y.\nProof.\nmove=> e; rewrite -[R x y]/(quot_class (Quot x) y) e //=; reflexivity.\nQed.\n\nLemma eq_Quot x y : R x y → Quot x = Quot y.\nProof.\nmove=> e; rewrite /Quot; move: (ex_intro _ y _).\nsuff ->: R y = R x.\n  move=> ?; congr Quot_; exact: proof_irrelevance.\napply: functional_extensionality=> z.\napply: propositional_extensionality.\nby rewrite /= e.\nQed.\n\n(** We can also show that [Quot] is surjective by extracting the witness in the\nexistential. *)\nLemma Quot_inv q : ∃ x, q = Quot x.\nProof.\ncase: q=> [P [x xP]]; exists x; move: (ex_intro _ _ _).\nrewrite xP=> e; congr Quot_; exact: proof_irrelevance.\nQed.\n\n(** Unique choice comes into play when defining the elimination principles for\nthe quotient.  In its usual non-dependent form, the principle says that we can\nlift a function [f : T → S] to another function [quot → S] provided that [f] is\nconstant on equivalence classes.  We define a more general dependently typed\nversion, which allows in particular to prove a property [S q] by proving that [S\n(Quot x)] holds for any [x].  The statement of the compatibility condition for\n[f] is a bit complicated because it needs to equate terms of different types [S\n(Quot x)] and [S (Quot y)], which requires us to transport the left-hand side\nalong the equivalence [R x y]. *)\n\nSection Elim.\n\nDefinition cast A B (e : A = B) : A → B :=\n  match e with erefl => id end.\n\nContext (S : quot → Type) (f : ∀ x, S (Quot x)).\nContext (fP : ∀ x y (exy : R x y), cast (congr1 S (eq_Quot exy)) (f x) = f y).\n\n(** We begin with an auxiliary result that uniquely characterizes the result of\napplying the eliminator to an element [q : quot].  Thanks to unique choice, this\nallows us to define the eliminator as a function [quot_rect]. *)\n\nLemma quot_rect_subproof (q : quot) :\n  exists! a : S q, ∃ x (exq : Quot x = q), a = cast (congr1 S exq) (f x).\nProof.\ncase: (Quot_inv q)=> x -> {q}.\nexists (f x); split=> [|a]; first by exists x, erefl.\ncase=> y [eyx -> {a}].\nby rewrite (proof_irrelevance _ eyx (eq_Quot (Quot_inj eyx))) fP.\nQed.\n\nDefinition quot_rect q : S q :=\n  sval (constructive_definite_description _ (quot_rect_subproof q)).\n\nLemma quot_rectE x : quot_rect (Quot x) = f x.\nProof.\nrewrite /quot_rect.\ncase: constructive_definite_description=> _ [y [eyx /= ->]].\nby rewrite (proof_irrelevance _ eyx (eq_Quot (Quot_inj eyx))) fP.\nQed.\n\nEnd Elim.\n\n(** In the non-dependent case, the compatibility condition acquires its usual\nform. *)\n\nSection Rec.\n\nContext S (f : T → S) (fP : ∀ x y, R x y → f x = f y).\n\nDefinition congr1CE (A B : Type) (b : B) x y (e : x = y) :\n  congr1 (λ _ : A, b) e = erefl :=\n  match e with erefl => erefl end.\n\nDefinition quot_rec : quot -> S :=\n  @quot_rect (λ _, S) f\n    (λ x y exy, etrans\n      (congr1 (λ p, cast p (f x)) (congr1CE S (eq_Quot exy)))\n      (fP exy)).\n\nLemma quot_recE x : quot_rec (Quot x) = f x.\nProof. by rewrite /quot_rec quot_rectE. Qed.\n\nEnd Rec.\n\nEnd Quotient.\n", "meta": {"author": "arthuraa", "repo": "poleiro", "sha": "c2f2159470872ac83d305b4a50fda8fccc89ae53", "save_path": "github-repos/coq/arthuraa-poleiro", "path": "github-repos/coq/arthuraa-poleiro/poleiro-c2f2159470872ac83d305b4a50fda8fccc89ae53/theories/Quotients.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6591252371880577}}
{"text": "(* \n  Smolka-Brown Chapter 9\n  \nSpyridon Antonatos\n*)\n\nRequire Import List.\nRequire Import Basics.\n\nDefinition var := nat.\n\nInductive ter : Type :=\n  | V : var -> ter\n  | T : ter -> ter -> ter.\n\n(* An equation is a tuple of two terms (term, term) *)\nDefinition eqn := prod ter ter.\n\n(* Implicit types for ease of use*)\nImplicit Types x y z : var.\nImplicit Types s t u v : ter.\nImplicit Type e : eqn.\nImplicit Types A B C : list eqn.\nImplicit Types sigma tau : ter -> ter.\nImplicit Types m n k : nat.\n\n(* Substitution method *)\nDefinition subst sigma : Prop :=\n  forall s t, sigma (T s t) = T (sigma s) (sigma t).\n\nDefinition unif sigma A : Prop :=\n  subst sigma /\\ forall s t, In (s,t) A -> sigma s = sigma t.\n\nDefinition unifiable A : Prop :=\n  exists sigma, unif sigma A.\n\n\nDefinition principal_unifier sigma A : Prop :=\n  unif sigma A /\\ forall tau, unif tau A -> forall s, tau (sigma s) = tau s.\n\n(* Exercise 9.1.1 *)\nLemma subst_term_var_agreement :\n  forall sigma tau, (subst sigma) -> (subst tau) ->\n    (forall x, sigma (V x) = tau (V x)) ->\n        forall s, (sigma s) = (tau s).\nProof.\n  intros sigma tau sub1 sub2 var_agree s. induction s.\n  - apply var_agree.\n  - unfold subst in sub1. unfold subst in sub2. rewrite sub1. \n  rewrite sub2. rewrite IHs1. rewrite IHs2. reflexivity.\nQed.\n\n(* Exercise 9.1.2 *)\nLemma principle_unif_idempotent :\nforall sigma A, principal_unifier sigma A -> (forall t, (sigma (sigma t)) = (sigma t)).\nProof.\nintros. unfold principal_unifier in H. destruct H. apply H0. apply H.\nQed.\n\n(* Exercise 9.1.3 *)\nLemma unif_fact_a :\nforall A t s sigma, unif sigma ((s, t) :: A) <-> (sigma s) = (sigma t) /\\ unif sigma A.\nProof.\nintros. split.\n- intros. split.\n{ unfold unif in H. destruct H. apply H0. simpl. left. reflexivity. }\n{ unfold unif in *. destruct H. split. \n { apply H. }\n { intros. apply H0. simpl. right. apply H1. }\n}\n- intros. destruct H. unfold unif in *. destruct H0. split.\n{ apply H0. }\n{ intros. unfold In in H2. destruct H2.\n  { inversion H2. rewrite H4 in H. rewrite H5 in H. apply H. }\n  { apply H1 in H2. apply H2. }}\nQed.  \n\n\nLemma unif_fact_b :\nforall A B sigma, unif sigma (A ++ B) <-> (unif sigma A) /\\ (unif sigma B).\nProof.\nintros. split. \n- intros. split.\n+ induction B.\n* rewrite app_nil_r in H. apply H.\n* apply IHB. unfold unif in H. destruct H. unfold unif. split. apply H. intros. apply H0. apply in_app_or in H1. apply in_app_iff with (l':= a :: B).\ndestruct H1.\n{ left. apply H1. }\n{ right. apply in_cons. apply H1. }\n+ induction A.\n* simpl in H. apply H.\n* apply IHA. unfold unif in H. destruct H. unfold unif. split. apply H. intros. apply H0. apply in_app_or in H1. apply in_app_iff with (l := a :: A). \ndestruct H1.\n{ left. apply in_cons. apply H1. }\n{ right. apply H1. }\n\n- intros. unfold unif in *. destruct H. destruct H. destruct H0. split. apply H. intros. \napply in_app_or in H3. destruct H3.\n{ apply H1. apply H3. }\n{ apply H2. apply H3. }\nQed.\n\nLemma sub_list_unif :\nforall A B C, unifiable (A ++ B ++ C) -> unifiable B.\nAdmitted.\n\n(* Proof.\nintros.\ninversion H.\ninversion H0.\nunfold In in H2.\ninversion H2.\nAbort. *)\n\nLemma sub_list_not_unif_sublist :\nforall A B,\n(incl A B) ->  unifiable B ->  unifiable A.\nProof.\nintros.\nunfold incl in H.\nunfold unifiable in *.\nunfold unif in *.\ndestruct H0.\ndestruct H0.\nexists x.\nsplit.\n- apply H0.\n- intros. apply H in H2. apply H1 in H2. apply H2.\nQed.\n\n\n(* 9.1.2 *)\nFixpoint V_t (x : ter) : list ter :=\n   match x with\n   | V v1 => (cons x nil)\n   | T t1 t2 => (V_t t1) ++ (V_t t2)\n  end.\n\nFixpoint V_l (l : list eqn) : list ter :=\n   match l with\n   | nil => nil\n   | ((s , t) :: l') => (V_t s) ++ (V_t t) ++ (V_l l')\n  end.\n\nFixpoint Domain (A : list eqn) : list ter :=\n  match A with\n  | nil => nil\n  | ((t1 , t2) :: A') =>\n    match t1 with\n    | V v1 => t1 :: (Domain A')\n    | T ta tb => nil\n    end\n  end. \n\nInductive disjoint {T} : list T -> list T -> Prop :=\n  | disjoint_nil : disjoint nil nil\n  | disjoint_cons_l : forall l1 l2 q, ~ In q l2 ->\n                        disjoint l1 l2 -> disjoint (q :: l1) l2\n  | disjoint_cons_r : forall l1 l2 q, ~ In q l1 ->\n                        disjoint l1 l2 -> disjoint l1 (q :: l2).\n\nInductive solved : list eqn -> Prop :=\n  | solved_n : solved nil\n  | solved_f : forall x s A, ((~ (In (V x)(V_t s))) /\\ (~ (In (V x) (Domain A))) \n                                              /\\ (disjoint (V_t s) (Domain A))\n                                              /\\ (solved A) )-> solved ((V x , s) :: A).\n\n(* Definition disjoint {X} (A B : list X) : Prop :=\n  ~ (exists x:X, In x A /\\ In x B ).\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\n\nDefinition eq_var (x1 : var) (x2 : var) : bool :=\n  beq_nat x1 x2.\n\nFixpoint var_repl_t (s : ter) (x : var) (t : ter) : ter :=\n  match s with\n  | V v1 =>\n    if eq_var v1 x then t else s\n  | T ta tb => T (var_repl_t ta x t) (var_repl_t tb x t)\n  end.\n\nFixpoint var_repl_l (A : list eqn) (x : var) (t : ter) : list eqn :=\n  match A with\n  | nil => nil\n  | ((t1 , t2) :: A') => ( var_repl_t t1 x t, var_repl_t t2 x t) :: (var_repl_l A' x t)\n  end.\n\nFixpoint fi (A : list eqn) (s : ter) : ter :=\n  match A with\n  | nil => s\n  | ((t1 , t2) :: A') =>\n    match t1 with\n    | V v1 => (var_repl_t (fi A' s) v1 t2)\n    | T _ _ => s\n    end\n  end.\n\n(* Lemma A_solv_pric_unif :\nforall A s, solved A -> principle_unifier (fi A s) A \n*)\n\nFixpoint beq_terms (t1 : ter) (t2 : ter) : bool :=\n  match t1 with\n  | V v1 =>\n    match t2 with\n    | V v2 => eq_var v1 v2\n    | T _ _ => false\n    end\n  | T t1a t2a =>\n    match t2 with\n    | V v2 => false\n    | T t1b t2b => (beq_terms t1a t1b) &&\n                   (beq_terms t2a t2b)\n    end\n  end.    \n\nDefinition bad_eqn e : Prop :=\n  match e with\n  | (t1 , t2)=>\n    match t1 with\n    | V v1 => (beq_terms t1 t2) = false /\\ (In t1 (V_t t2))\n    | T _ _ => False\n    end\n  end.  \n\n\nLemma De_morgan_1 : forall p1 p2 : Prop,\n    ~ (p1 \\/ p2 ) -> ~p1 /\\ ~p2.\nProof.\nunfold not.\nintros p1 p2 H.\nsplit.\n- intros p1a. apply H. left. apply p1a.\n- intros p2a. apply H. right. apply p2a.\nQed.\n\n\nLemma exercise_923_a :\nforall x s t, ~ (In (V x) (V_t s)) -> var_repl_t s x t = s.\nProof.\n\nintros.\ninduction s.\n- simpl in H. apply De_morgan_1 in H. simpl in H. inversion H.\nunfold var_repl_t. destruct H0. inversion H.  destruct (eq_var v x) .\nAbort.\n\nLemma exercise_923_b :\nforall x A t, ~ (In (V x) (V_l A)) -> var_repl_l A x t = A.\nProof.\nAbort.\n\nLemma exercise_923_c :\nforall x A t, ~ (In (V x) (Domain A)) -> Domain (var_repl_l A x t) = Domain A.\nProof.\nAbort.\n\n\n\n\n\n\n\n\n\n\n\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/Unification.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6591252148948187}}
{"text": "From mathcomp Require Import ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nRequire Import logic_theories.\nRequire Import logic_pred_theories.\nRequire Import class_set.\nRequire Import class_set_theories.\n\nSection Direct_Product_Theories.\n\n  Variable U:Type.\n\n  Theorem ordered_pair_in_direct_product_iff_and:\n    forall (A B:Ensemble U) (a b:U), (|a,b|) ∈ A × B <-> a ∈ A /\\ b ∈ B.\n  Proof.\n    move => A B a b.\n    rewrite /iff.\n    split.\n    move => H.\n    inversion H.\n    inversion H0.\n    inversion H2 as [y].\n    inversion H3.\n    inversion H5.\n    fold (OrderedPair x y) in H7.\n    move: H7.\n    rewrite (ordered_pair_iff a b x y).\n    case => H7 H8.\n    rewrite H7.\n    rewrite H8.\n    split.\n    apply H4.\n    apply H6.\n    case => [H0 H1].\n    split.\n    exists a.\n    exists b.\n    split.\n    apply H0.\n    split.\n    apply H1.\n    fold (OrderedPair a b).\n    reflexivity.\n  Qed.\n\n  Theorem direct_product_empty_r: forall (X:Ensemble U), X × {||} = {||}.\n  Proof.\n    move => X.\n    apply /Extensionality_Ensembles.\n    split => Y.\n    -case.\n     move => Z.\n     case => [x [y [H1 [H2 H3]]]].\n     rewrite H3.\n     apply NNPP.\n     rewrite /not => H4.\n     move: H2.\n     apply Noone_in_empty.\n    -move => H0.\n     apply NNPP.\n     rewrite /not => H1.\n     move: H0.\n     apply Noone_in_empty.\n  Qed.\n\n  Theorem direct_product_empty_l: forall (X:Ensemble U), {||} × X = {||}.\n  Proof.\n    move => X.\n    apply /Extensionality_Ensembles.\n    split => Y.\n    move => H0.\n    apply NNPP.\n    rewrite /not => H1.\n    move: H0.\n    case => Z.\n    case => [x [y]].\n    case => [H2 [H3 H4]].\n    move : H2.\n    apply Noone_in_empty.\n    move => H0.\n    apply NNPP.\n    rewrite /not => H1.\n    move: H0.\n    apply Noone_in_empty.\n  Qed.\n\n  Theorem direct_product_empty_comm: forall (X:Ensemble U), {||} × X =  X × {||}.\n  Proof.\n    move => X.\n    rewrite direct_product_empty_r.\n    rewrite direct_product_empty_l.\n    reflexivity.\n  Qed.\n\n  Theorem direct_product_empty_iff:\n    forall (X Y:Ensemble U), X × Y = {||} <-> X = {||} \\/ Y = {||}.\n  Proof.\n    move => X Y.\n    rewrite /iff.\n    split.\n    +apply contrapositive.\n     apply classic.\n     move => H.\n     ++suff: ~(forall (x y:U), ~((|x,y|) ∈ X × Y)).\n       move => H0 H1.\n       apply H0.\n       rewrite H1.\n       move => x y.\n       apply Noone_in_empty.\n     ++suff: exists x y:U, (|x,y|) ∈ X × Y.\n       case => [x [y]].\n       move => H0.\n       unfold not.\n       move => H1.\n       move: H0.\n       apply H1.\n     ++suff: exists x y:U, x ∈ X /\\ y ∈ Y.\n       case => [x [y [HX HY]]].\n       exists x.\n       exists y.\n       rewrite ordered_pair_in_direct_product_iff_and.\n       split.\n       apply HX.\n       apply HY.\n     ++suff: (exists x:U, x ∈ X) /\\ (exists y:U, y ∈ Y).\n       case.\n       case => [x HX [y HY]].\n       exists x.\n       exists y.\n       split.\n       apply HX.\n       apply HY.\n     ++split; apply not_all_not_ex; unfold not; rewrite -Axiom_of_EmptySet; move => H1; apply H.\n       left.\n       apply H1.\n       right.\n       apply H1.\n    +case => H; rewrite H.\n     rewrite direct_product_empty_l.\n     reflexivity.\n     rewrite direct_product_empty_r.\n     reflexivity.\n  Qed.\n\n  Theorem direct_product_included_iff:\n    forall (X Y W Z:Ensemble U), W × Z ⊂ X × Y <-> W × Z = {||} \\/ (W ⊂ X /\\ Z ⊂ Y).\n  Proof.\n    +move => X Y W Z.\n     rewrite /iff.\n     split.\n     move => H.\n     (* W × Z ⊂ X × Y -> forall (t s:U), (|t,s|) ∈ W × Z -> (|t,s|) ∈ X × Y *)\n     ++have L0: forall (t s:U), (|t,s|) ∈ W × Z -> (|t,s|) ∈ X × Y.\n       move => t s.\n       unfold Included in H.\n       apply H.\n     (* (forall (t s:U), (|t,s|) ∈ W × Z -> (|t,s|) ∈ X × Y) -> (forall (t s:U), ((t ∈ W /\\ s ∈ Z) -> (t ∈ X /\\ s ∈ Y))) *)\n     ++have L1: forall (t s:U), ((t ∈ W /\\ s ∈ Z) -> (t ∈ X /\\ s ∈ Y)).\n       move => t s.\n       rewrite -!ordered_pair_in_direct_product_iff_and.\n       apply L0.\n     (* (forall (t s:U), ((t ∈ W /\\ s ∈ Z) -> (t ∈ X /\\ s ∈ Y))) -> (forall (t s:U), ((t ∈ W /\\ s ∈ Z) -> t ∈ X) /\\ ((t ∈ W /\\ s ∈ Z) -> s ∈ Y)) *)\n     ++have L2: forall (t s:U), ((t ∈ W /\\ s ∈ Z) -> t ∈ X) /\\ ((t ∈ W /\\ s ∈ Z) -> s ∈ Y).\n       move => t s.\n       split; apply L1.\n     (*  forall (t s:U), ((t ∈ W /\\ s ∈ Z) -> t ∈ X) /\\ ((t ∈ W /\\ s ∈ Z) -> s ∈ Y) -> forall (t s:U), ((t ∈ W -> False) \\/ (s ∈ Z -> False) \\/ t ∈ X) /\\ ((t ∈ W -> False) \\/ (s ∈ Z -> False) \\/ s ∈ Y) *)\n     ++have L3: forall (t s:U), ((t ∈ W -> False) \\/ (s ∈ Z -> False) \\/ t ∈ X) /\\ ((t ∈ W -> False) \\/ (s ∈ Z -> False) \\/ s ∈ Y).\n       move => t0 s0.\n       +++have L31: ((t0 ∈ W /\\ s0 ∈ Z) -> False) <-> (t0 ∈ W -> False) \\/ (s0 ∈ Z -> False).\n          rewrite /iff.\n          split; move => HF.\n          apply not_and_or.\n          unfold not.\n          apply HF.\n          apply or_not_and.\n          unfold not.\n          apply HF.\n       +++have L32: forall (P:Prop), (((t0 ∈ W -> False) \\/ (s0 ∈ Z -> False)) \\/ P) <-> ((t0 ∈ W -> False) \\/ (s0 ∈ Z -> False) \\/ P).\n          move => P.\n          rewrite /iff.\n          split.\n          case.\n          move => HL1.\n          inversion HL1.\n          left.\n          apply H0.\n          right.\n          left.\n          apply H0.\n          move => HL1.\n          right.\n          right.\n          apply HL1.\n          move => HL1.\n          inversion HL1.\n          left.\n          left.\n          apply H0.\n          inversion H0.\n          left.\n          right.\n          apply H1.\n          right.\n          apply H1.\n     ++rewrite -!L32.\n       rewrite -L31.\n       rewrite !or_not_l_iff_2.\n       apply L2.\n       apply classic.\n       apply classic.\n     (* forall (t s:U), ((t ∈ W -> False) \\/ (s ∈ Z -> False) \\/ t ∈ X) /\\ ((t ∈ W -> False) \\/ (s ∈ Z -> False) \\/ s ∈ Y) ->\n        forall (t s:U), ((t ∈ W -> t ∈ X) \\/ (s ∈ Z -> False)) /\\ ((s ∈ Z -> s ∈ Y) \\/ (t ∈ W -> False)) *)\n     ++have L4: forall (t s:U), ((t ∈ W -> t ∈ X) \\/ (s ∈ Z -> False)) /\\ ((s ∈ Z -> s ∈ Y) \\/ (t ∈ W -> False)).\n       move => t s.\n       rewrite -(or_not_l_iff_1 (t ∈ W) (t ∈ X)).\n       rewrite or_assoc.\n       rewrite (or_comm (t ∈ X) (s ∈ Z -> False)).\n       rewrite -(or_not_l_iff_1 (s ∈ Z) (s ∈ Y)).\n       rewrite or_assoc.\n       rewrite (or_comm (s ∈ Y) (t ∈ W -> False)).\n       rewrite -(or_assoc (s ∈ Z -> False) (t ∈ W -> False) (s ∈ Y)).\n       rewrite (or_comm (s ∈ Z -> False) (t ∈ W -> False)).\n       rewrite or_assoc.\n       apply L3.\n       apply classic.\n       apply classic.\n    (* (forall (t s:U), ((t ∈ W -> t ∈ X) \\/ (s ∈ Z -> False)) /\\ ((s ∈ Z -> s ∈ Y) \\/ (t ∈ W -> False))) ->\n       forall (t s:U), ((t ∈ W -> t ∈ X) \\/ (s ∈ Z -> False))) /\\ (forall (t s:U),((s ∈ Z -> s ∈ Y) \\/ (t ∈ W -> False)) *)\n    +have L5: (forall (t s:U), ((t ∈ W -> t ∈ X) \\/ (s ∈ Z -> False))) /\\ (forall (t s:U),((s ∈ Z -> s ∈ Y) \\/ (t ∈ W -> False))).\n     split; apply L4.\n    (*\n       (forall (t s:U), ((t ∈ W -> t ∈ X) \\/ (s ∈ Z -> False))) /\\ (forall (t s:U),((s ∈ Z -> s ∈ Y) \\/ (t ∈ W -> False))))\n       ->\n       ((forall (t:U), (t ∈ W -> t ∈ X)) \\/ forall (s:U), (s ∈ Z -> False)) /\\ ((forall (s:U), (s ∈ Z -> s ∈ Y)) \\/ (forall (t:U), (t ∈ W -> False)))\n     *)\n    +have L6: ((forall (t:U), (t ∈ W -> t ∈ X)) \\/ (forall (s:U), (s ∈ Z -> False))) /\\\n              ((forall (s:U), (s ∈ Z -> s ∈ Y)) \\/ (forall (t:U), (t ∈ W -> False))).\n     move: L5.\n     case.\n     move => L61 L62.\n     split; apply forall_bound_or_dist_2.\n     apply L61.\n     move => t s.\n     apply L62.\n    +fold (Included U W X) in L6.\n     fold (Included U Z Y) in L6.\n     move : L6.\n     rewrite -(Axiom_of_EmptySet Z).\n     rewrite -(Axiom_of_EmptySet W).\n     move => L6.\n     rewrite direct_product_empty_iff.\n     apply or_dist_and.\n     ++suff: (Z={||} \\/ W ⊂ X) /\\ (W={||} \\/ Z ⊂ Y).\n       case.\n       move => H0 H1.\n       split.\n       inversion H0.\n       left.\n       right.\n       apply H2.\n       right.\n       apply H2.\n       inversion H1.\n       left.\n       left.\n       apply H2.\n       right.\n       apply H2.\n     rewrite (or_comm (Z={||}) (W ⊂ X)).\n     rewrite (or_comm (W={||}) (Z ⊂ Y)).\n     apply L6.\n    +case.\n     move => H.\n     rewrite H.\n     apply Included_Empty.\n     case => H0 H1.\n     unfold Included.\n     move => S.\n     case => [T [x [y [HxW [HyZ HT]]]]].\n     rewrite HT.\n     apply ordered_pair_in_direct_product_iff_and.\n     split.\n     move: HxW.\n     apply H0.\n     move: HyZ.\n     apply H1.\n  Qed.\n\n  Theorem direct_product_eq_to_or:\n    forall (A B C D:Ensemble U), A × B = C × D -> A × B = {||} \\/ C × D = {||} \\/ (A = C /\\ B = D).\n  Proof.\n    +move => A B C D H.\n     ++have L0: (A × B ⊂ C × D) /\\ (C × D ⊂ A × B).\n       apply Extension.\n       apply H.\n    +inversion L0 as [LH0 LH1].\n     apply imp_not_l.\n     apply classic.\n     move => H0.\n     apply imp_not_l.\n     apply classic.\n     move => H1.\n     ++suff: (A ⊂ C /\\ B ⊂ D) /\\ (C ⊂ A /\\ D ⊂ B).\n       case => [[H2 H3] [H4 H5]].\n       split.\n       apply /Extensionality_Ensembles.\n       unfold Same_set.\n       split.\n       apply H2.\n       apply H4.\n       apply /Extensionality_Ensembles.\n       unfold Same_set.\n       split.\n       apply H3.\n       apply H5.\n    +split.\n     move: H0.\n     apply imp_not_l.\n     apply classic.\n     apply direct_product_included_iff.\n     apply LH0.\n     move: H1.\n     apply imp_not_l.\n     apply classic.\n     apply direct_product_included_iff.\n     apply LH1.\n  Qed.\n\n  Theorem direct_product_or_eq:\n    forall (A B C D:Ensemble U), (A × B = {||} /\\ C × D = {||}) \\/ (A = C /\\ B = D) -> A × B = C × D.\n  Proof.\n    move => A B C D.\n    case => H; inversion H; rewrite H0; rewrite H1; reflexivity.\n  Qed.\n\n  Theorem direct_product_included_right:\n    forall (X Y Z:Ensemble U), ~(X={||}) /\\ X × Z ⊂ X × Y -> Z ⊂ Y.\n  Proof.\n    move => X Y Z.\n    case => HFX.\n    rewrite direct_product_included_iff.\n    rewrite direct_product_empty_iff.\n    case.\n    case.\n    apply contrapositive.\n    apply classic.\n    move => H.\n    apply HFX.\n    move => H.\n    rewrite H.\n    apply Included_Empty.\n    case => H.\n    apply.\n  Qed.\n\n  Theorem direct_product_included_partial:\n    forall (X Y Z:Ensemble U), Z ⊂ Y -> X × Z ⊂ X × Y.\n  Proof.\n    move => X Y Z H.\n    apply direct_product_included_iff.\n    right.\n    split => x.\n    apply.\n    apply H.\n  Qed.\n\n  Theorem direct_product_union_dist_r:\n    forall (X Y Z:Ensemble U), X × (Y ∪ Z) = X × Y ∪ X × Z.\n  Proof.\n    move => X Y Z.\n    apply /Extensionality_Ensembles.\n    +split => S.\n     case => T.\n     case => [x [y [H1 [H2 H3]]]].\n     inversion H2.\n     ++left.\n       rewrite H3.\n       apply ordered_pair_in_direct_product_iff_and.\n       split.\n       apply H1.\n       apply H.\n     ++right.\n       rewrite H3.\n       apply ordered_pair_in_direct_product_iff_and.\n       split.\n       apply H1.\n       apply H.\n    +case; move => T; case => V; case => [x [y [H1 [H2 H3]]]]; rewrite H3; apply ordered_pair_in_direct_product_iff_and; split.\n     apply H1.\n     left.\n     apply H2.\n    +apply H1.\n     right.\n     apply H2.\n  Qed.\n\n  Theorem direct_product_intersection_dist_r:\n    forall (X Y Z:Ensemble U), X × (Y ∩ Z) = X × Y ∩ X × Z.\n  Proof.\n    move => X Y Z.\n    apply /Extensionality_Ensembles.\n    split => S.\n    +case => T.\n     case => [x [y [H1 [H2 H3]]]].\n     inversion H2 as [y0 H4 H5 H6].\n     split; split; exists x; exists y.\n     split.\n     apply H1.\n     split.\n     apply H4.\n     apply H3.\n     split.\n     apply H1.\n     split.\n     apply H5.\n     apply H3.\n    +case => T.\n     case => V.\n     case => [x [y [H1 [H2 H3]]]].\n     rewrite H3.\n     rewrite ordered_pair_in_direct_product_iff_and.\n     case => [H4 H5].\n     rewrite ordered_pair_in_direct_product_iff_and.\n     split.\n     apply H1.\n     split.\n     apply H2.\n     apply H5.\n  Qed.\n\n  Goal forall (y:U) (X Y:Ensemble U), y ∈ Y -> Pr1 (X × Y) = X.\n  Proof.\n    move => y X Y HY.\n    apply /Extensionality_Ensembles.\n    split => x H.\n    inversion H.\n    inversion H0 as [y0].\n    apply ordered_pair_in_direct_product_iff_and in H2.\n    inversion H2.\n    apply H3.\n    split.\n    exists y.\n    apply ordered_pair_in_direct_product_iff_and.\n    split.\n    apply H.\n    apply HY.\n  Qed.\n\n  Goal forall (x:U) (X Y:Ensemble U), x ∈ X -> Pr2 (X × Y) = Y.\n  Proof.\n    move => x X Y HX.\n    apply /Extensionality_Ensembles.\n    split => y H.\n    inversion H.\n    inversion H0 as [x0].\n    apply ordered_pair_in_direct_product_iff_and in H2.\n    inversion H2.\n    apply H4.\n    split.\n    exists x.\n    apply ordered_pair_in_direct_product_iff_and.\n    split.\n    apply HX.\n    apply H.\n  Qed.\n\n  Lemma ordered_pair_swap:\n    forall (x y z w:U), (|x,y|) = (|z,w|) <-> (|y,x|) = (|w,z|).\n  Proof.\n    move => x y z w.\n    rewrite /iff.\n    split => H; apply ordered_pair_iff in H; inversion H; rewrite H0;  rewrite H1; reflexivity.\n  Qed.\n  \nEnd Direct_Product_Theories.\n\nExport class_set_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/direct_product_theories.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516188, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6591252119083789}}
{"text": "Add LoadPath \".\" as OPAT.\nRequire Export OPAT.aula3 OPAT.aula4 OPAT.aula5 OPAT.aula6.\n\nInductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(** Actually, [app] will be used a lot in some parts of what\n    follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity.  Qed.\nExample test_app2:             nil ++ [4;5] = [4;5].\nProof. reflexivity.  Qed.\nExample test_app3:             [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity.  Qed.\n\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1:             hd 0 [1;2;3] = 1.\nProof. reflexivity.  Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity.  Qed.\nExample test_tl:              tl [1;2;3] = [2;3].\nProof. reflexivity.  Qed.\n", "meta": {"author": "bugarela", "repo": "Coq", "sha": "9f4973fec5b34ed836aa2239a009385e0549c024", "save_path": "github-repos/coq/bugarela-Coq", "path": "github-repos/coq/bugarela-Coq/Coq-9f4973fec5b34ed836aa2239a009385e0549c024/OPAT exercises/aula7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.8539127585282745, "lm_q1q2_score": 0.6590870103918766}}
{"text": "Require Import prosa.classic.util.all.\nRequire Import prosa.classic.model.arrival.basic.job\n               prosa.classic.model.arrival.basic.task_arrival\n               prosa.classic.model.priority.\nRequire Import prosa.classic.model.schedule.uni.service\n               prosa.classic.model.schedule.uni.schedule.\nRequire Import prosa.classic.model.schedule.uni.limited.platform.definitions\n               prosa.classic.model.schedule.uni.limited.busy_interval.\n\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq path fintype bigop.\n\n(** * Priority inversion is bounded *)\n(** In this module we prove that any priority inversion that occurs in the model with bounded \n    nonpreemptive segments defined in module prosa.classic.model.schedule.uni.limited.platform.definitions \n    is bounded. *)\nModule PriorityInversionIsBounded.\n\n  Import Job Priority UniprocessorSchedule LimitedPreemptionPlatform BusyIntervalJLFP. \n\n  Section PriorityInversionIsBounded.\n\n    Context {Task: eqType}.\n    Variable task_max_nps task_cost: Task -> time.    \n    \n    Context {Job: eqType}.\n    Variable job_arrival: Job -> time.\n    Variable job_max_nps job_cost: Job -> time.\n    Variable job_task: Job -> Task.\n    \n    (* Consider any arrival sequence. *)\n    Variable arr_seq: arrival_sequence Job.\n    Hypothesis H_arrival_times_are_consistent: arrival_times_are_consistent job_arrival arr_seq.\n    \n    (* Next, consider any uniprocessor schedule of this arrival sequence...*)\n    Variable sched: schedule Job.\n    Hypothesis H_jobs_come_from_arrival_sequence: jobs_come_from_arrival_sequence sched arr_seq.\n\n    (* ... where jobs do not execute before their arrival nor after completion. *)\n    Hypothesis H_jobs_must_arrive_to_execute: jobs_must_arrive_to_execute job_arrival sched.\n    Hypothesis H_completed_jobs_dont_execute: completed_jobs_dont_execute job_cost sched. \n    \n    (* Consider a JLFP policy that indicates a higher-or-equal priority relation,\n       and assume that the relation is reflexive and transitive. *)\n    Variable higher_eq_priority: JLFP_policy Job.\n    Hypothesis H_priority_is_reflexive: JLFP_is_reflexive higher_eq_priority.\n    Hypothesis H_priority_is_transitive: JLFP_is_transitive higher_eq_priority.\n\n    (* We consider an arbitrary function can_be_preempted which defines \n       a preemption model with bounded nonpreemptive segments. *)\n    Variable can_be_preempted: Job -> time -> bool.\n    Let preemption_time := preemption_time sched can_be_preempted.\n    Hypothesis H_correct_preemption_model:\n      correct_preemption_model arr_seq sched can_be_preempted.\n    Hypothesis H_model_with_bounded_nonpreemptive_segments:\n      model_with_bounded_nonpreemptive_segments\n        job_cost job_task arr_seq can_be_preempted job_max_nps task_max_nps. \n\n    (* Next, we assume that the schedule is a work-conserving schedule... *)\n    Hypothesis H_work_conserving: work_conserving job_arrival job_cost arr_seq sched.\n\n    (* ... and the schedule respects the policy defined by the \n       can_be_preempted function (i.e., bounded nonpreemptive segments). *)\n    Hypothesis H_respects_policy:\n      respects_JLFP_policy_at_preemption_point\n        job_arrival job_cost arr_seq sched can_be_preempted higher_eq_priority.\n\n    (* Let's define some local names for clarity. *)\n    Let job_scheduled_at := scheduled_at sched.\n    Let job_completed_by := completed_by job_cost sched.\n\n    (* Finally, we introduce the notion of the maximal length of (potential) priority \n       inversion at a time instant t, which is defined as the maximum length of \n       nonpreemptive segments among all jobs that arrived so far. Note that \n       the value [job_max_nps j_lp] is at least ε for any job j_lp, so the maximal\n       length of priority inversion cannot be negative. *)\n    Definition max_length_of_priority_inversion (j: Job) (t: time) :=\n      \\max_(j_lp <- jobs_arrived_before arr_seq t | ~~ higher_eq_priority j_lp j)\n       (job_max_nps j_lp - ε).\n\n    (** Next we prove that a priority inversion of a job is bounded by \n        function max_length_of_priority_inversion. *)\n\n    (** Note that any bound on function max_length_of_priority_inversion will also be \n        a bound on the maximal priority inversion. This bound may be different \n        for different scheduler and/or task models. Thus, we don't define such a bound \n        in this module. *)\n\n    (* Consider any job j of tsk with positive job cost. *)\n    Variable j: Job.\n    Hypothesis H_j_arrives: arrives_in arr_seq j.\n    Hypothesis H_job_cost_positive: job_cost_positive job_cost j.\n    \n    (* Consider any busy interval prefix [t1, t2) of job j. *)\n    Variable t1 t2: time.\n    Hypothesis H_busy_interval_prefix:\n      busy_interval_prefix job_arrival job_cost arr_seq sched higher_eq_priority j t1 t2.\n    \n    (* In this section, we prove that at any time instant after any preemption point\n       (inside the busy interval), the processor is always busy scheduling a \n       job with higher or equal priority. *)\n    Section PreemptionTimeAndPriorityInversion. \n      \n      (* First, we show that the processor at any preemptive point is always \n         busy scheduling a job with higher or equal priority. *)\n      Lemma not_quiet_implies_exists_scheduled_hp_job_at_preemption_point:\n        forall t, \n          t1 <= t < t2 ->\n          preemption_time t ->\n          exists j_hp,\n            arrived_between job_arrival j_hp t1 t2 /\\\n            higher_eq_priority j_hp j /\\\n            job_scheduled_at j_hp t.\n      Proof.\n        move: (H_busy_interval_prefix) => [SL [QUIET [NOTQUIET INBI]]].\n        rename H_work_conserving into WORK, H_respects_policy into PRIO,\n        H_jobs_come_from_arrival_sequence into CONS.\n        move => t /andP [GEt LEt] PREEMPTP.            \n        have NOTIDLE := not_quiet_implies_not_idle\n                          job_arrival job_cost arr_seq _\n                          sched higher_eq_priority j _ _ _ _ _ t1 t2 _ t.\n        feed_n 8 NOTIDLE; eauto 2.\n        unfold is_idle, FP_is_transitive, transitive in *.\n        destruct (sched t) as [j_hp|] eqn:SCHED; [clear NOTIDLE | by exfalso; apply NOTIDLE].\n        move: SCHED => /eqP SCHED.\n        exists j_hp.\n        have HP: higher_eq_priority j_hp j.\n        { apply contraT; move => /negP NOTHP; exfalso.\n          have TEMP: t <= t2.-1; first by rewrite -subn1 subh3 // addn1.\n          rewrite leq_eqVlt in TEMP; move: TEMP => /orP [/eqP EQUALt2m1 | LTt2m1];\n                                                    first rewrite leq_eqVlt in GEt; first move: GEt => /orP [/eqP EQUALt1 | LARGERt1].\n          { subst t; clear LEt.\n            rewrite -EQUALt1 in SCHED; move: EQUALt1 => /eqP EQUALt1.\n            destruct (job_scheduled_at j t1) eqn:SCHEDj.\n            { simpl. have EQ:= only_one_job_scheduled sched j j_hp t1 SCHEDj SCHED.\n                by subst j; apply NOTHP. \n            }\n            { apply NOTHP.\n              apply PRIO with t1; try done.\n              - by move: EQUALt1 => /eqP EQUALt1; rewrite EQUALt1.\n              - apply/andP; split; last first.\n                + by move: SCHEDj; rewrite /job_scheduled_at; move => /negP /negP SCHEDj.\n                + have EQ: t1 = job_arrival j.\n                  { rewrite -eqSS in EQUALt1.\n                    have EQ: t2 = t1.+1.\n                    { rewrite prednK in EQUALt1; first by apply/eqP; rewrite eq_sym.\n                      apply negbNE; rewrite -eqn0Ngt; apply/neqP; intros EQ0.\n                      move: INBI; rewrite EQ0; move => /andP [_ CONTR].\n                        by rewrite ltn0 in CONTR.\n                    } clear EQUALt1.\n                      by move: INBI; rewrite EQ ltnS -eqn_leq; move => /eqP INBI.\n                  }\n                    by rewrite EQ; eapply job_pending_at_arrival; eauto 2.\n            } \n          }\n          { feed (NOTQUIET t); first by apply/andP; split.\n            apply NOTQUIET; intros j_hp' IN HP ARR.\n            apply contraT; move => /negP NOTCOMP'; exfalso.\n            have BACK: backlogged job_arrival job_cost sched j_hp' t.\n            { apply/andP; split.\n              - apply/andP; split. unfold arrived_before, has_arrived in *. by rewrite ltnW. \n                apply/negP; intro COMP; apply NOTCOMP'.\n                  by apply completion_monotonic with (t0 := t).\n              - apply/negP; intro SCHED'.\n                apply only_one_job_scheduled with (j1 := j_hp) in SCHED'; last by done.\n                  by apply NOTHP; subst. \n            }\n            feed (PRIO j_hp' j_hp t PREEMPTP IN BACK); first by done.\n              by apply NOTHP; apply H_priority_is_transitive with j_hp'. \n          }\n          {\n            unfold quiet_time in *.\n            feed (NOTQUIET t.+1). apply/andP; split.\n            - by apply leq_ltn_trans with t1.\n            - rewrite -subn1 ltn_subRL addnC in LTt2m1.\n                by rewrite -[t.+1]addn1.\n                apply NOTQUIET.\n                unfold quiet_time in *; intros j_hp' IN HP ARR.\n                apply contraT; move => /negP NOTCOMP'; exfalso.\n                have BACK: backlogged job_arrival job_cost sched j_hp' t.\n                { apply/andP; split; last first.\n                  { apply/negP; intro SCHED'.\n                    apply only_one_job_scheduled with (j1 := j_hp) in SCHED'; last by done.\n                    apply NOTHP.\n                      by subst. \n                  }\n                  apply/andP; split. unfold arrived_before, has_arrived in *. by done. \n                  apply/negP; intro COMP; apply NOTCOMP'.\n                    by apply completion_monotonic with (t0 := t).\n                }\n                feed (PRIO j_hp' j_hp t PREEMPTP IN BACK); first by done.\n                  by apply NOTHP; apply H_priority_is_transitive with j_hp'. \n          }\n        }\n        repeat split; [| by done | by done].\n        move: (SCHED) => PENDING.\n        eapply scheduled_implies_pending with (job_cost0 := job_cost) in PENDING; [| by eauto | by done].\n        apply/andP; split; last by apply leq_ltn_trans with (n := t); first by move: PENDING => /andP [ARR _]. \n        apply contraT; rewrite -ltnNge; intro LT; exfalso.\n        feed (QUIET j_hp); first by eapply CONS, SCHED.\n        specialize (QUIET HP LT).\n        have COMP: job_completed_by j_hp t by apply completion_monotonic with (t0 := t1).\n        apply completed_implies_not_scheduled in COMP; last by done.\n          by move: COMP => /negP COMP; apply COMP.\n      Qed.\n\n      (* In addition, we prove that every nonpreemptive segment \n         always begins with a preemption time. *)\n      Lemma scheduling_of_any_segment_starts_with_preemption_time: \n        forall j t,\n          job_scheduled_at j t ->\n          exists pt,\n            job_arrival j <= pt <= t /\\\n            preemption_time pt /\\\n            (forall t', pt <= t' <= t -> job_scheduled_at j t').\n      Proof. \n        intros s t SCHEDst.\n        have EX: exists t',\n            (t' <= t)\n              && (job_scheduled_at s t')\n              && (all (fun t'' => job_scheduled_at s t'') (iota t' (t - t').+1 )).\n        { exists t.\n          apply/andP; split; [ by apply/andP; split | ].\n          apply/allP; intros t'.\n          rewrite mem_iota.\n          rewrite subnn addn1 ltnS -eqn_leq.\n            by move => /eqP EQ; subst t'. } \n        have MIN := ex_minnP EX. \n        move: MIN => [mpt /andP [/andP [LT1 SCHEDsmpt] /allP ALL] MIN]; clear EX.\n        destruct mpt.\n        { exists 0; repeat split.\n          - apply/andP; split; last by done.\n              by apply H_jobs_must_arrive_to_execute in SCHEDsmpt.\n          - by eapply zero_is_pt; eauto 2.\n          - by intros; apply ALL; rewrite mem_iota subn0 add0n ltnS. }\n        { have NSCHED: ~~ job_scheduled_at s mpt.\n          { apply/negP; intros SCHED. \n            feed (MIN mpt).\n            apply/andP; split; [by apply/andP; split; [ apply ltnW | ] | ].\n            apply/allP; intros t'.\n            rewrite mem_iota addnS ltnS. \n            move => /andP [GE LE].\n            move: GE; rewrite leq_eqVlt; move => /orP [/eqP EQ| LT].\n            subst t'. by done.\n            apply ALL.\n            rewrite mem_iota addnS ltnS.\n            apply/andP; split; first by done.\n            apply leq_trans with (mpt + (t - mpt)); first by done.\n            rewrite !subnKC; last rewrite ltnW; by done.\n              by rewrite ltnn in MIN. }\n          have PP: preemption_time mpt.+1.\n          { apply first_moment_is_pt with (arr_seq0 := arr_seq) (j0 := s); eauto 2. }\n          exists mpt.+1; repeat split; try done.\n          - apply/andP; split; last by done.\n              by apply H_jobs_must_arrive_to_execute in SCHEDsmpt.\n          - move => t' /andP [GE LE].\n            apply ALL; rewrite mem_iota.\n            rewrite addnS ltnS subnKC; last by done.\n              by apply/andP; split.\n        }\n      Qed. \n      \n      (* Next we prove that at any time instant after a preemption point the\n         processor is always busy with a job with higher or equal priority. *) \n      Lemma not_quiet_implies_exists_scheduled_hp_job_after_preemption_point:\n        forall tp t,\n          preemption_time tp ->\n          t1 <= tp < t2 ->\n          tp <= t < t2 ->\n          exists j_hp,\n            arrived_between job_arrival j_hp t1 t.+1 /\\ \n            higher_eq_priority j_hp j /\\\n            job_scheduled_at j_hp t.\n      Proof.\n        move: (H_jobs_come_from_arrival_sequence) (H_work_conserving) => CONS WORK.\n        move: (H_respects_policy) => PRIO.              \n        move => tp t PRPOINT /andP [GEtp LTtp] /andP [LEtp LTt].\n        have NOTIDLE := not_quiet_implies_not_idle\n                          job_arrival job_cost arr_seq _ sched higher_eq_priority\n                          j _ _ _ _ _ t1 t2 _ t.\n        feed_n 8 NOTIDLE; eauto 2.\n        apply/andP; split; [by apply leq_trans with tp | by done].\n        destruct (sched t) as [j_hp|] eqn:SCHED;\n          last by exfalso; apply NOTIDLE; rewrite /is_idle SCHED.\n        move: SCHED => /eqP SCHED.\n        exists j_hp.\n        have HP: higher_eq_priority j_hp j.\n        { intros.\n          have SOAS := scheduling_of_any_segment_starts_with_preemption_time _ _ SCHED.\n          move: SOAS => [prt [/andP [_ LE] [PR SCH]]].\n          case E:(t1 <= prt).\n          - move: E => /eqP /eqP E; rewrite subn_eq0 in E.\n            have EXISTS := not_quiet_implies_exists_scheduled_hp_job_at_preemption_point prt.\n            feed_n 2 EXISTS; try done.\n            { by apply /andP; split; last by apply leq_ltn_trans with t. }\n            move: EXISTS => [j_lp [_ [HEP SCHEDjhp]]].\n            have EQ: j_hp = j_lp.\n            { by apply (only_one_job_scheduled sched _ _ prt); first (apply SCH; apply/andP; split). }\n              by subst j_hp. \n          - move: E => /eqP /neqP E; rewrite -lt0n subn_gt0 in E.\n            apply negbNE; apply/negP; intros LP.\n            rename j_hp into j_lp.\n            have EXISTS := not_quiet_implies_exists_scheduled_hp_job_at_preemption_point tp.\n            feed_n 2 EXISTS; try done.\n            { by apply /andP; split. }\n            move: EXISTS => [j_hp [_ [HEP SCHEDjhp]]].\n            have EQ: j_hp = j_lp.\n            { apply (only_one_job_scheduled sched _ _ tp). \n                by done.\n                apply SCH; apply/andP; split.\n                apply leq_trans with t1. rewrite ltnW //. by done.\n                  by done.\n            }\n              by subst j_hp; move: LP => /negP LP; apply: LP.\n        } \n        repeat split; [| by done | by done].\n        move: (H_busy_interval_prefix) => [SL [QUIET [NOTQUIET EXj]]]. \n        move: (SCHED) => PENDING.\n        eapply scheduled_implies_pending with (job_cost0 := job_cost) in PENDING;\n          [| by eauto | by done].\n        apply/andP; split; \n          last by apply leq_ltn_trans with (n := t); first by move: PENDING => /andP [ARR _].\n        apply contraT; rewrite -ltnNge; intro LT; exfalso.\n        feed (QUIET j_hp); first by eapply CONS, SCHED.\n        specialize (QUIET HP LT).\n        have COMP: job_completed_by j_hp t.\n        { by apply completion_monotonic with (t0 := t1); [ apply leq_trans with tp | ]. }\n        apply completed_implies_not_scheduled in COMP; last by done.\n          by move: COMP => /negP COMP; apply COMP.\n      Qed.\n\n      (* Now, suppose there exists some constant K that bounds the distance to \n         a preemption time from the beginning of the busy interval. *)\n      Variable K: time.\n      Hypothesis H_preemption_time_exists:\n        exists pr_t, preemption_time pr_t /\\ t1 <= pr_t <= t1 + K.\n\n      (* Then we prove that the processor is always busy with a job with \n         higher-or-equal priority after time instant [t1 + K]. *)\n      Lemma not_quiet_implies_exists_scheduled_hp_job:\n        forall t,\n          t1 + K <= t < t2 ->\n          exists j_hp,\n            arrived_between job_arrival j_hp t1 t.+1 /\\ \n            higher_eq_priority j_hp j /\\\n            job_scheduled_at j_hp t.\n      Proof. \n        move => t /andP [GE LT].\n        move: H_preemption_time_exists => [prt [PR /andP [GEprt LEprt]]].\n        apply not_quiet_implies_exists_scheduled_hp_job_after_preemption_point with (tp := prt); eauto 2. \n        -  apply/andP; split; first by done.\n           apply leq_ltn_trans with (t1 + K); first by done.\n             by apply leq_ltn_trans with t.\n        - apply/andP; split; last by done.\n            by apply leq_trans with (t1 + K).\n      Qed.\n      \n    End PreemptionTimeAndPriorityInversion.\n\n    (* In this section we prove that the function max_length_of_priority_inversion \n       indeed upper bounds the priority inversion length. *)\n    Section PreemprionTimeExists.\n\n      (* First we prove that if a job with higher-or-equal priority is scheduled at \n         a quiet time t+1 then this is the first time when this job is scheduled. *)\n      Lemma hp_job_not_scheduled_before_quiet_time:\n        forall jhp t,\n          quiet_time job_arrival job_cost arr_seq sched higher_eq_priority j t.+1 ->\n          job_scheduled_at jhp t.+1 ->\n          higher_eq_priority jhp j ->\n          ~~ job_scheduled_at jhp t.\n      Proof.\n        intros jhp t QT SCHED1 HP.            \n        apply/negP; intros SCHED2.\n        specialize (QT jhp).\n        feed_n 3 QT; try done.\n        eapply H_jobs_come_from_arrival_sequence; eauto 1.\n        rewrite /arrived_before ltnS.\n        apply H_jobs_must_arrive_to_execute. by done.\n        apply completed_implies_not_scheduled in QT; last by done.\n          by move: QT => /negP NSCHED; apply: NSCHED.\n      Qed.\n      \n      (* Also, we show that lower-priority jobs that are scheduled inside the\n         busy-interval prefix [t1,t2) must have arrived before that interval. *)\n      Lemma low_priority_job_arrives_before_busy_interval_prefix:\n        forall jlp t,\n          t1 <= t < t2 ->\n          job_scheduled_at jlp t ->\n          ~~ higher_eq_priority jlp j ->\n          job_arrival jlp < t1.\n      Proof.\n        move => jlp t /andP [GE LT] SCHED LP.\n        move: (H_busy_interval_prefix) => [NEM [QT [NQT HPJ]]].\n        apply negbNE; apply/negP; intros ARR; rewrite -leqNgt in ARR.\n        have SCH:= scheduling_of_any_segment_starts_with_preemption_time _ _ SCHED.\n        move: SCH => [pt [/andP [NEQ1 NEQ2] [PT FA]]].\n        have NEQ: t1 <= pt < t2.\n        { apply/andP; split.\n          apply leq_trans with (job_arrival jlp); by done.\n          apply leq_ltn_trans with t; by done. }\n        have LL:= not_quiet_implies_exists_scheduled_hp_job_at_preemption_point pt.\n        feed_n 2 LL; try done.\n        move: LL => [jhp [ARRjhp [HP SCHEDhp]]].\n        feed (FA pt). apply/andP; split; by done.\n        have OOJ:= only_one_job_scheduled _ _ _ _ FA SCHEDhp; subst jhp.\n          by move: LP => /negP LP; apply: LP.\n      Qed.\n\n      (* Moreover, we show that lower-priority jobs that are scheduled inside the\n         busy-interval prefix [t1,t2) must be scheduled before that interval. *)\n      Lemma low_priority_job_scheduled_before_busy_interval_prefix:\n        forall jlp t,\n          t1 <= t < t2 ->\n          job_scheduled_at jlp t ->\n          ~~ higher_eq_priority jlp j ->\n          exists t', t' < t1 /\\ job_scheduled_at jlp t'.\n      Proof.\n        move => jlp t NEQ SCHED LP.\n        have ARR := low_priority_job_arrives_before_busy_interval_prefix _ _ NEQ SCHED LP. \n        move: NEQ => /andP [GE LT].\n        exists t1.-1.\n        split.\n        { rewrite prednK; first by done.\n            by apply leq_ltn_trans with (job_arrival jlp).\n        }\n        { move: (H_busy_interval_prefix) => [NEM [QT [NQT HPJ]]].\n          have SCHEDST := scheduling_of_any_segment_starts_with_preemption_time _ _ SCHED.\n          move: SCHEDST => [pt [NEQpt [PT SCHEDc]]].\n          have NEQ: pt < t1.\n          { rewrite ltnNge; apply/negP; intros CONTR.\n            have NQSCHED := not_quiet_implies_exists_scheduled_hp_job_at_preemption_point pt.\n            feed_n 2 NQSCHED; try done.\n            { apply/andP; split; first by done.\n                by apply leq_ltn_trans with t; move: NEQpt => /andP [_ T].\n            }\n            move: NQSCHED => [jhp [ARRhp [HPhp SCHEDhp]]].\n            specialize (SCHEDc pt).\n            feed SCHEDc.\n            { by apply/andP; split; last move: NEQpt => /andP [_ T]. }\n            have EQ:= only_one_job_scheduled sched jhp jlp pt.\n            feed_n 2 EQ; try done.\n            subst jhp.\n              by move: LP => /negP LP; apply: LP.\n          }\n          apply SCHEDc; apply/andP; split.\n          - rewrite -addn1 in NEQ.\n            apply subh3 in NEQ.\n              by rewrite subn1 in NEQ.\n          - apply leq_trans with t1. by apply leq_pred. by done.\n        }\n        Qed.\n      \n      (* Thus, there must be a preemption time in the interval [t1, t1 + max_priority_inversion t1]. \n         That is, if a job with higher-or-equal priority is scheduled at time instant t1, then t1 is \n         a preemprion time. Otherwise, if a job with lower priority is scheduled at time t1, \n         then this jobs also should be scheduled before the beginning of the busy interval. So, the \n         next preemption time will be no more than [max_priority_inversion t1] time units later. *)\n      Lemma preemption_time_exists: \n        exists pr_t,\n          preemption_time pr_t /\\\n          t1 <= pr_t <= t1 + max_length_of_priority_inversion j t1.\n      Proof.\n        set (service := service sched).\n        move: (H_correct_preemption_model) => CORR.\n        move: (H_busy_interval_prefix) => [NEM [QT1 [NQT HPJ]]].\n        case SCHED: (sched t1) => [s | ]; move: SCHED => /eqP SCHED; last first. \n        { exists t1; split; last first.\n          apply/andP; split; [by done | by rewrite leq_addr].\n          move: SCHED => /eqP SCHED.\n          rewrite /preemption_time /LimitedPreemptionPlatform.preemption_time.\n            by rewrite SCHED.\n        }\n        { case PRIO: (higher_eq_priority s j).\n          { exists t1; split; last first.\n            apply/andP; split; [by done | by rewrite leq_addr].\n            destruct t1.\n            { eapply zero_is_pt; [eauto 2 | apply H_jobs_come_from_arrival_sequence]. }\n            eapply hp_job_not_scheduled_before_quiet_time in QT1; eauto 2.\n            eapply first_moment_is_pt with (j0 := s); eauto 2.\n          } \n          { move: (SCHED) => ARRs; apply H_jobs_come_from_arrival_sequence in ARRs.\n            move: (H_model_with_bounded_nonpreemptive_segments s ARRs) => [_ [_ [_ EXPP]]].\n            move: (EXPP (service s t1)) => PP; clear EXPP.\n            feed PP. by apply/andP; split; [done | apply H_completed_jobs_dont_execute].                \n            have EX: exists pt,\n                ((service s t1) <= pt <= (service s t1) + (job_max_nps s - 1))\n                  && can_be_preempted s pt.\n            { move: PP => [pt [NEQ PP]].\n              exists pt; apply/andP; split; by done.\n            } clear PP. \n            have MIN := ex_minnP EX.\n            move: MIN => [sm_pt /andP [NEQ PP] MIN]; clear EX.\n            have Fact: exists Δ, sm_pt = service s t1 + Δ.\n            { exists (sm_pt - service s t1).\n              apply/eqP; rewrite eq_sym; apply/eqP; rewrite subnKC //.\n                by move: NEQ => /andP [T _]. }\n            move: Fact => [Δ EQ]; subst sm_pt; rename Δ into sm_pt.\n            exists (t1 + sm_pt); split.\n            { have Fact1: \n                forall prog, service s t1 <= prog < service s t1 + sm_pt ->\n                        ~~ can_be_preempted s prog. \n              { move => prog /andP [GE LT].\n                apply/negP; intros PPJ.\n                feed (MIN prog); first (apply/andP; split); try done.\n                - apply/andP; split; first by done.\n                  apply leq_trans with (service s t1 + sm_pt).\n                  + by apply ltnW. \n                  + by move: NEQ => /andP [_ K].\n                - by move: MIN; rewrite leqNgt; move => /negP NLT; apply: NLT.\n              } \n              have Fact2: forall t', t1 <= t' < t1 + sm_pt -> job_scheduled_at s t'.\n              { \n                move => t' /andP [GE LT]. \n                have Fact: exists Δ, t' = t1 + Δ.\n                { by exists (t' - t1); apply/eqP; rewrite eq_sym; apply/eqP; rewrite subnKC.  }\n                move: Fact => [Δ EQ]; subst t'.\n                move: (Fact1 (service s (t1 + Δ)))(CORR s) => NPPJ T.\n                feed T; first by done. move: T => [T _ ].\n                apply: T; apply: NPPJ.\n                apply/andP; split.\n                { by apply Service.service_monotonic; rewrite leq_addr. }\n                rewrite /service /UniprocessorSchedule.service (@Service.service_during_cat _ _ _ t1).\n                { rewrite ltn_add2l; rewrite ltn_add2l in LT.\n                  apply leq_ltn_trans with Δ; last by done.\n                  rewrite -{2}(sum_of_ones t1 Δ).\n                  rewrite leq_sum //; clear; intros t _.\n                    by rewrite /service_at; destruct (scheduled_at sched s t). }\n                { by apply/andP; split; [done | rewrite leq_addr]. } \n              }\n              rewrite /preemption_time /LimitedPreemptionPlatform.preemption_time.\n              case SCHEDspt: (sched (t1 + sm_pt)) => [s0 | ]; last by done.\n              move: SCHEDspt => /eqP SCHEDspt.\n              destruct (s == s0) eqn: EQ.\n              { move: EQ => /eqP EQ; subst s0.\n                rewrite /UniprocessorSchedule.service.\n                rewrite (@Service.service_during_cat _ _ _ t1); last first.\n                { by apply/andP; split; [ done | rewrite leq_addr]. }\n                have ALSCHED: service_during sched s t1 (t1 + sm_pt) = sm_pt.\n                { rewrite -{2}(sum_of_ones t1 sm_pt) /service_during.\n                  apply/eqP; rewrite eqn_leq //; apply/andP; split.\n                  { rewrite leq_sum //; clear; intros t _.\n                      by unfold service_at; destruct (scheduled_at sched s t). }\n                  { rewrite big_nat_cond [in X in _ <= X]big_nat_cond.\n                    rewrite leq_sum //.\n                    move => x /andP [HYP _].\n                    rewrite lt0b. \n                      by apply Fact2.\n                  } \n                } \n                  by rewrite ALSCHED.\n              } \n              destruct sm_pt.\n              { exfalso; move: EQ => /negP EQ; apply: EQ.\n                move: SCHED SCHEDspt => /eqP SCHED /eqP SCHEDspt.\n                rewrite addn0 in SCHEDspt; rewrite SCHEDspt in SCHED.\n                  by inversion SCHED. }\n              { rewrite addnS.\n                move: (H_correct_preemption_model s0) => T.\n                feed T; first by eauto 2. move: T => [_ T]; apply: T.\n                apply /negP; intros CONTR.\n                move: EQ => /negP EQ; apply: EQ.\n                move: (Fact2 (t1 + sm_pt)) => SCHEDs0.\n                feed SCHEDs0; first by apply/andP; split; [rewrite leq_addr | rewrite addnS].\n                apply/eqP; eapply only_one_job_scheduled; eauto 2.\n                  by rewrite -addnS.\n              } \n            } \n            move: NEQ => /andP [GE LE].\n            apply/andP; split; first by rewrite leq_addr.\n            rewrite leq_add2l.\n            unfold max_length_of_priority_inversion.\n            rewrite (big_rem s) //=.\n            { rewrite PRIO; simpl.\n              apply leq_trans with (job_max_nps s - ε); last by rewrite leq_maxl.\n                by rewrite leq_add2l in LE. }\n            eapply arrived_between_implies_in_arrivals; eauto 2.\n            apply/andP; split; first by done.\n            eapply low_priority_job_arrives_before_busy_interval_prefix with t1; eauto 2.\n              by rewrite PRIO.\n          }\n        }\n      Qed.\n\n    End PreemprionTimeExists.\n\n  End PriorityInversionIsBounded. \n  \nEnd PriorityInversionIsBounded.", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/classic/model/schedule/uni/limited/platform/priority_inversion_is_bounded.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339907, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6590870076996678}}
{"text": "Require Export trigo.\nSet  Implicit Arguments.\nUnset Strict Implicit.\n(* Formules de trigonometrie necessaires.*)\n \nLemma prod_sin:\n forall (a b : R),  2 * (sin (a + b) * sin (a - b)) = cos (2 * b) - cos (2 * a).\nintros.\nassert\n (cos ((a + b) + (a - b)) =\n  cos (a + b) * cos (a - b) - sin (a + b) * sin (a - b)).\nrewrite cos_som; auto.\nassert\n (cos ((a + b) - (a - b)) =\n  cos (a + b) * cos (a - b) + sin (a + b) * sin (a - b)).\nrewrite <- cos_diff; auto.\nassert\n (2 * (sin (a + b) * sin (a - b)) =\n  cos ((a + b) - (a - b)) - cos ((a + b) + (a - b))).\nrewrite H0; rewrite H.\nring.\nrewrite H1.\nRReplace ((a + b) - (a - b)) (2 * b).\nRReplace ((a + b) + (a - b)) (2 * a); auto.\nQed.\n \nLemma sin_3_a: forall (a : R),  sin (3 * a) = sin a * (2 * cos (2 * a) + 1).\nintros.\nRReplace (3 * a) (a + 2 * a).\nrewrite sin_som.\nrewrite duplication_sin.\nRReplace (sin a * cos (2 * a) + (2 * (sin a * cos a)) * cos a)\n         (sin a * (cos (2 * a) + 2 * (cos a * cos a))).\nassert (2 * Rsqr (cos a) = cos (2 * a) + 1).\nrewrite duplication_cos.\nring.\nRReplace (cos a * cos a) (Rsqr (cos a)).\nrewrite H.\nring.\nQed.\n \nLemma Al_Kashi_sin_cos:\n forall (a b c : R),\n (a + b) + c = pi ->\n  Rsqr (sin c) = (Rsqr (sin a) + Rsqr (sin b)) - ((2 * sin a) * sin b) * cos c.\nintros.\nRReplace ((Rsqr (sin a) + Rsqr (sin b)) - ((2 * sin a) * sin b) * cos c)\n         (((Rsqr (sin a) * Rsqr (cos c) + Rsqr (sin b)) -\n           ((2 * sin a) * sin b) * cos c) - Rsqr (sin a) * (Rsqr (cos c) - 1)).\nreplace\n ((Rsqr (sin a) * Rsqr (cos c) + Rsqr (sin b)) - ((2 * sin a) * sin b) * cos c)\n     with (Rsqr (sin a * cos c - sin b)).\n2:unfold Rsqr; ring.\nrewrite <- (trigo_Pythagore c).\nRReplace (Rsqr (cos c) - (Rsqr (cos c) + Rsqr (sin c))) (- Rsqr (sin c)).\nelim pi_moins_x with ( x := a + c ); [intros H0 H1].\nreplace b with (pi + - (a + c)).\nrewrite H1.\nrewrite sin_som.\nRReplace (sin a * cos c - (sin a * cos c + sin c * cos a)) (- (sin c * cos a)).\nreplace (Rsqr (- (sin c * cos a))) with (Rsqr (sin c) * Rsqr (cos a)).\n2:unfold Rsqr; ring.\nRReplace (Rsqr (sin c) * Rsqr (cos a) - Rsqr (sin a) * - Rsqr (sin c))\n         (Rsqr (sin c) * (Rsqr (cos a) + Rsqr (sin a))).\nrewrite trigo_Pythagore.\nring.\nrewrite <- H; ring.\nQed.\n(* Definition de pisurtrois et formules de trigonometrie.*)\nParameter pisurtrois : R.\n \nAxiom pisurtrois_def : 3 * pisurtrois = pi.\n \nAxiom sin_pisurtrois_non_zero : sin pisurtrois <> 0.\n \nLemma cos_2_pisurtrois: 2 * cos (2 * pisurtrois) + 1 = 0.\nRReplace (2 * cos (2 * pisurtrois) + 1) (sin pi * / sin pisurtrois).\nrewrite sin_pi; ring.\nrewrite <- pisurtrois_def.\nrewrite sin_3_a.\nfield.\napply sin_pisurtrois_non_zero.\nQed.\n \nLemma sin_3_a_pisurtrois:\n forall (a : R),\n  sin (3 * a) = 4 * (sin a * (sin (pisurtrois + a) * sin (pisurtrois - a))).\nintros.\nrewrite sin_3_a.\nRReplace (4 * (sin a * (sin (pisurtrois + a) * sin (pisurtrois - a))))\n         ((2 * sin a) * (2 * (sin (pisurtrois + a) * sin (pisurtrois - a)))).\nrewrite prod_sin.\nRReplace ((2 * sin a) * (cos (2 * a) - cos (2 * pisurtrois)))\n         (sin a * (2 * cos (2 * a) - 2 * cos (2 * pisurtrois))).\nassert (2 * cos (2 * pisurtrois) = - 1).\nRReplace (- 1) (- 1 + 0).\nrewrite <- cos_2_pisurtrois.\nring.\nrewrite H.\nring.\nQed.\n \nLemma Al_Kashi_pisurtrois:\n forall a b c,\n (a + b) + c = pisurtrois ->\n  Rsqr (sin b) =\n  (Rsqr (sin (pisurtrois + a)) + Rsqr (sin (pisurtrois + c))) -\n  ((2 * sin (pisurtrois + a)) * sin (pisurtrois + c)) * cos b.\nintros.\napply Al_Kashi_sin_cos.\nrewrite <- pisurtrois_def.\nRReplace (((pisurtrois + a) + (pisurtrois + c)) + b)\n         (((a + b) + c) + (pisurtrois + pisurtrois)).\nrewrite H; ring.\nQed.\nRequire Export cocyclicite.\n(* lemme a mettre dans distance_euclidienne apres colinearite_distance*)\n \nLemma distance_double_milieu:\n forall (B C A' : PO), A' = milieu B C ->  distance B C = 2 * distance A' C.\nintros.\nrewrite <- (milieu_distance H); auto.\nassert (vec B C = mult_PP 2 (vec B A')).\napply milieu_vecteur_double; auto.\nrewrite (distance_sym A' B).\nRReplace 2 (Rabs 2).\napply colinearite_distance; auto.\nrewrite Rabs_right; auto.\nlra.\nQed.\n(* corollaire du theoreme de l'angle inscrit et de l'angle au centre\n   on utilise le triangle rectangle forme par un cote et sa mediatrice*)\n \nLemma demi_angle_centre:\n forall (A B C A' O : PO),\n triangle A B C ->\n O <> A' ->\n A' = milieu B C ->\n circonscrit O A B C ->\n  double_AV (cons_AV (vec A B) (vec A C)) =\n  double_AV (cons_AV (vec O A') (vec O C)).\nintros.\nderoule_triangle A B C.\nderoule_circonscrit A B C O.\nassert (double_AV (cons_AV (vec A B) (vec A C)) = cons_AV (vec O B) (vec O C)).\napply angle_inscrit; auto.\nrewrite H10.\nassert (double_AV (cons_AV (vec O A') (vec O C)) = cons_AV (vec O B) (vec O C)).\nunfold double_AV.\nreplace (cons_AV (vec O B) (vec O C))\n     with (plus (cons_AV (vec O B) (vec O A')) (cons_AV (vec O A') (vec O C))).\nassert (cons_AV (vec O B) (vec O A') = cons_AV (vec O A') (vec O C)).\napply isocele_mediane_bissectrice; auto.\napply (circonscrit_isocele H2).\nrewrite H11; auto.\napply Chasles; auto.\nrewrite H11; auto.\nQed.\n(*deux angles ayant des mesures differant d'un multiple de pi ont des sinus egaux ou opposes*)\n \nAxiom\n   egalite_double_abs_Sin :\n   forall A B C E F G,\n   double_AV (cons_AV (vec A B) (vec A C)) =\n   double_AV (cons_AV (vec E F) (vec E G)) ->\n    Rabs (Sin (cons_AV (vec A B) (vec A C))) =\n    Rabs (Sin (cons_AV (vec E F) (vec E G))).\n\nRequire Export complements_cercle.\n(* theoreme : dans un triangle avec les notations habituelles  a = 2 R sin A\n   cas particulier : le cote est un diametre du cercle circonscrit*)\n \nLemma diametre_Sinus:\n forall (A B C O : PO),\n triangle A B C ->\n O = milieu B C ->\n circonscrit O A B C ->\n  distance B C = 2 * (distance O C * Rabs (Sin (cons_AV (vec A B) (vec A C)))).\nintros.\nassert (orthogonal (vec A B) (vec A C)).\napply triangle_diametre with O; auto.\nderoule_triangle A B C.\nelim droit_direct_ou_indirect with ( A := A ) ( B := B ) ( C := C );\n (intros; auto).\nrewrite <- (egalite_sin_Sin (A:=A) (B:=B) (C:=C) (x:=pisurdeux)); auto.\nrewrite sin_pisurdeux.\nrewrite Rabs_right; auto.\nrewrite (distance_double_milieu H0); ring.\nlra.\nrewrite <- (egalite_sin_Sin (A:=A) (B:=B) (C:=C) (x:=- pisurdeux)); auto.\nrewrite sin_impaire.\nrewrite sin_pisurdeux.\nrewrite Rabs_left; auto.\nrewrite (distance_double_milieu H0); ring.\nlra.\nQed.\n(* cas general*)\n \nLemma rayon_Sinus_general:\n forall (A B C A' O : PO),\n triangle A B C ->\n O <> A' ->\n A' = milieu B C ->\n circonscrit O A B C ->\n  distance B C = 2 * (distance O C * Rabs (Sin (cons_AV (vec A B) (vec A C)))).\nintros.\nderoule_triangle A B C.\nderoule_circonscrit A B C O.\nassert (orthogonal (vec O A') (vec B C)).\napply milieu_centrecirconscrit_orthogonal_segment with A; auto.\nrewrite (distance_double_milieu H1).\nreplace (distance O C * Rabs (Sin (cons_AV (vec A B) (vec A C))))\n     with (distance C O * Rabs (Sin (cons_AV (vec O A') (vec O C)))).\nrewrite <- triangle_rectangle_absolu_Sin; auto.\nrewrite (distance_sym A' C); auto.\nrewrite H1.\ngeneralize (milieu_distinct2 H5); auto.\napply ortho_sym.\nrewrite <- (milieu_vecteur H1); auto.\nrewrite (milieu_vecteur2 H1); auto.\nSimplortho.\nrewrite distance_sym.\nassert\n (double_AV (cons_AV (vec A B) (vec A C)) =\n  double_AV (cons_AV (vec O A') (vec O C))).\napply demi_angle_centre; auto.\nrewrite (egalite_double_abs_Sin H11); auto.\nQed.\n(* Ce theoreme montre que dans un triangle  a = 2R sin A  avec les notations habituelles.*)\n \nTheorem rayon_Sinus:\n forall A B C O,\n triangle A B C ->\n circonscrit O A B C ->\n  distance B C = 2 * (distance O C * Rabs (Sin (cons_AV (vec A B) (vec A C)))).\nintros.\nderoule_triangle A B C.\nsoit_milieu B C A'.\nelim (classic (A' = O)); intros.\napply diametre_Sinus; auto.\nrewrite <- H8; auto.\napply rayon_Sinus_general with A'; auto.\nQed.\n \nLemma existence_rayon_circonscrit:\n forall A B C,\n triangle A B C ->\n  (exists O : PO , circonscrit O A B C /\\ (exists r : R , r = distance O C ) ).\nintros.\nelim existence_cercle_circonscrit with ( A := A ) ( B := B ) ( C := C );\n [intros O H0; (try clear existence_cercle_circonscrit); (try exact H0) | auto].\nexists O.\nsplit; [try assumption | idtac].\nexists (distance O C); auto.\nQed.\n \nLtac\nsoit_rayon_circonscrit A B C O r :=\nelim (existence_rayon_circonscrit (A:=A) (B:=B) (C:=C)); [intros O | auto];\n intros toto; elim toto; clear toto; intro; intros toto; elim toto; clear toto;\n intros r; intro.\n(* on doit pouvoir le demontrer*)\n \nAxiom\n   triangle_Sin_not_0 :\n   forall A B C, triangle A B C ->  (Sin (cons_AV (vec A B) (vec A C)) <> 0).\n#[export] Hint Resolve triangle_Sin_not_0 :geo.\n \nLemma triangle_abs_Sin_not_0:\n forall A B C,\n triangle A B C ->  (Rabs (Sin (cons_AV (vec A B) (vec A C))) <> 0).\nintros.\napply Rabs_no_R0.\nauto with geo.\nQed.\n#[export] Hint Resolve triangle_abs_Sin_not_0 :geo.\n(* Theoreme connu sous le nom de loi des Sinus.*)\n \nTheorem loi_Sinus:\n forall A B C,\n triangle A B C ->\n  and\n   (distance B C / Rabs (Sin (cons_AV (vec A B) (vec A C))) =\n    distance A B / Rabs (Sin (cons_AV (vec C A) (vec C B))))\n   (distance B C / Rabs (Sin (cons_AV (vec A B) (vec A C))) =\n    distance C A / Rabs (Sin (cons_AV (vec B C) (vec B A)))).\nintros.\nderoule_triangle A B C.\nsoit_rayon_circonscrit A B C D a.\nrewrite (rayon_Sinus (A:=A) (B:=B) (C:=C) (O:=D)); auto.\nrewrite <- H5; auto.\ngeneralize H4; unfold circonscrit, isocele; intros.\nelim H6; [intros H7 H8; (try clear H6); (try exact H8)].\nsplit; [try assumption | idtac].\nrewrite (rayon_Sinus (A:=C) (B:=A) (C:=B) (O:=D)); auto with geo.\nrewrite <- H7; rewrite H8; rewrite H5.\nfield.\nsplit; auto with geo.\napply circonscrit_permute; auto.\nrewrite (rayon_Sinus (A:=B) (B:=C) (C:=A) (O:=D)); auto with geo.\nrewrite H8; rewrite H5.\nfield.\nsplit; auto with geo.\nunfold circonscrit, isocele.\nsplit; auto.\nrewrite <- H7; rewrite H8; auto.\nQed.\n \nDefinition rayon_circonscrit (A B C : PO) (r : R) : Prop :=\n   exists O : PO , circonscrit O A B C /\\ r = distance O C .\n \nLemma triangle_sin_not_0:\n forall A B C x,\n triangle A B C -> image_angle x = cons_AV (vec A B) (vec A C) ->  (sin x <> 0).\nintros.\nderoule_triangle A B C.\nrewrite (egalite_sin_Sin (A:=A) (B:=B) (C:=C) (x:=x)); auto.\nauto with geo.\nQed.\n(* consequence de l'enroulement de la droite des reels sur le cercle trigonometrique dans le sens positif*)\n \nAxiom sin_pos : forall (x : R), ( 0 <= x <= pi ) ->  (sin x >= 0).\n \nAxiom\n   non_multiple_pi_triangle :\n   forall a A B C,\n   ( 0 < a < pi ) ->\n   A <> B ->\n   A <> C -> image_angle a = cons_AV (vec A B) (vec A C) ->  triangle A B C.\n(* debut de la demonstration du theoreme de Morley*)\n \nLemma pisurtrois_utile:\n forall a b c,\n 0 < a -> 0 < b -> 0 < c -> (a + b) + c = pisurtrois ->  ( 0 <= 3 * a <= pi ).\nintros.\nrewrite <- pisurtrois_def.\nsplit.\nlra.\nlra.\nQed.\n \nLemma pisurtrois_utile1:\n forall a b c,\n 0 < a -> 0 < b -> 0 < c -> (a + b) + c = pisurtrois ->  ( 0 <= b + c <= pi ).\nintros.\nrewrite <- pisurtrois_def.\nsplit.\nlra.\nlra.\nQed.\n \nLemma pisurtrois_utile2:\n forall a b c,\n 0 < a -> 0 < b -> 0 < c -> (a + b) + c = pisurtrois ->  ( 0 <= c <= pi ).\nintros.\nrewrite <- pisurtrois_def.\nsplit.\nlra.\nlra.\nQed.\n#[export] Hint Resolve pisurtrois_utile sin_pos pisurtrois_utile1 pisurtrois_utile2 :geo.\n \nLemma pisurtrois_triangle_utile:\n forall a b c A B C,\n 0 < a ->\n 0 < b ->\n 0 < c ->\n (a + b) + c = pisurtrois ->\n A <> B ->\n A <> C -> image_angle (3 * a) = cons_AV (vec A B) (vec A C) ->  triangle A B C.\nintros.\napply non_multiple_pi_triangle with (3 * a); auto.\nrewrite <- pisurtrois_def.\nsplit.\nlra.\nlra.\nQed.\n \nLemma pisurtrois_triangle_utile2:\n forall a b c B C P,\n 0 < a ->\n 0 < b ->\n 0 < c ->\n (a + b) + c = pisurtrois ->\n B <> C ->\n B <> P -> image_angle b = cons_AV (vec B C) (vec B P) ->  triangle B C P.\nintros.\napply non_multiple_pi_triangle with b; auto.\nsplit.\nlra.\nrewrite <- pisurtrois_def.\nlra.\nQed.\n \nLemma Rabs_neg: forall (r : R), r <= 0 ->  Rabs r = - r.\nintros.\nelim H; intros.\nrewrite Rabs_left; auto.\nrewrite H0.\nrewrite Rabs_R0; ring.\nQed.\n(* Application des theoremes rayon_Sinus et loi_Sinus dans un triangle forme par un cote et deux trissectrices.\n   Calcul de la longueur du cote BP dans le triangle BPC.*)\n \nLemma Morley_1:\n forall (a b c r : R) (A B C P : PO),\n 0 < a ->\n 0 < b ->\n 0 < c ->\n (a + b) + c = pisurtrois ->\n A <> B ->\n A <> C ->\n B <> C ->\n B <> P ->\n rayon_circonscrit A B C r ->\n image_angle b = cons_AV (vec B C) (vec B P) ->\n image_angle c = cons_AV (vec C P) (vec C B) ->\n image_angle (3 * a) = cons_AV (vec A B) (vec A C) ->\n  distance B P = (2 * (r * sin (3 * a))) * (sin c / sin (pisurtrois - a)).\nunfold rayon_circonscrit; intros.\nelim H7; [intros O [H13 H12]].\nassert (triangle A B C).\napply (pisurtrois_triangle_utile (a:=a) (b:=b) (c:=c) (A:=A) (B:=B) (C:=C));\n auto.\nassert (triangle B C P).\napply (pisurtrois_triangle_utile2 (a:=a) (b:=b) (c:=c) (B:=B) (C:=C) (P:=P));\n auto.\nderoule_triangle B C P.\nclear H18 H16 H15.\nassert (distance B C = 2 * (r * sin (3 * a))).\nrewrite (rayon_Sinus (A:=A) (B:=B) (C:=C) (O:=O)); auto.\nrewrite H12.\nrewrite <- (egalite_sin_Sin (A:=A) (B:=B) (C:=C) (x:=3 * a)); auto.\nrewrite Rabs_right; eauto with geo.\nrewrite <- H15.\nrewrite <- H2.\nRReplace (((a + b) + c) - a) (b + c).\nelim pi_moins_x with ( x := b + c ); [intros].\nrewrite <- H18.\nelim (loi_Sinus (A:=C) (B:=B) (C:=P)); intros; auto with geo.\nassert\n (distance B P =\n  (distance C B / Rabs (Sin (cons_AV (vec P C) (vec P B)))) *\n  Rabs (Sin (cons_AV (vec C B) (vec C P)))).\nrewrite <- H19.\nfield.\nauto with geo.\nrewrite H21.\nrewrite distance_sym.\nassert (image_angle (- c) = cons_AV (vec C B) (vec C P)).\napply mes_oppx; auto.\nrewrite <- (egalite_sin_Sin (A:=C) (B:=B) (C:=P) (x:=- c)); auto.\nrewrite sin_impaire.\nrewrite (Rabs_neg (r:=- sin c)).\nassert (image_angle (- b) = cons_AV (vec B P) (vec B C)).\napply mes_oppx; auto.\nassert (image_angle (pi + (b + c)) = cons_AV (vec P C) (vec P B)).\nrewrite <- (angle_triangle (A:=C) (B:=B) (C:=P)); auto.\nrewrite <- H23.\nrewrite <- H22.\nrewrite <- add_mes_compatible.\nrewrite <- mes_opp.\nrewrite <- add_mes_compatible.\nRReplace (- (- c + - b)) (b + c); auto.\nrewrite <- (egalite_sin_Sin (A:=P) (B:=C) (C:=B) (x:=pi + (b + c))); auto.\nrewrite H18.\nelim pi_plus_x with ( x := b + c ); intros.\nrewrite H26.\nrewrite Rabs_neg.\nfield.\nassert (- sin (b + c) <> 0).\nrewrite <- H26.\napply (triangle_sin_not_0 (A:=P) (B:=C) (C:=B) (x:=pi + (b + c))); auto with geo.\nauto with real.\nassert (sin (b + c) >= 0); eauto with geo.\nlra.\nassert (sin c >= 0); eauto with geo.\nlra.\nQed.\n(* application de la formule sin 3 a  qui utilise pisurtrois dons le calcul de BP*)\n \nLemma Morley_2:\n forall (a b c r : R) (A B C P : PO),\n 0 < a ->\n 0 < b ->\n 0 < c ->\n (a + b) + c = pisurtrois ->\n A <> B ->\n A <> C ->\n B <> C ->\n B <> P ->\n rayon_circonscrit A B C r ->\n image_angle b = cons_AV (vec B C) (vec B P) ->\n image_angle c = cons_AV (vec C P) (vec C B) ->\n image_angle (3 * a) = cons_AV (vec A B) (vec A C) ->\n  distance B P = (8 * (r * sin a)) * (sin c * sin (pisurtrois + a)).\nintros.\nassert (triangle B C P).\napply (pisurtrois_triangle_utile2 (a:=a) (b:=b) (c:=c) (B:=B) (C:=C) (P:=P));\n auto.\nderoule_triangle B C P.\nclear H13 H12 H15.\nrewrite (Morley_1 (a:=a) (b:=b) (c:=c) (r:=r) (A:=A) (B:=B) (C:=C) (P:=P)); auto.\nrewrite sin_3_a_pisurtrois; auto.\nfield.\nrewrite <- H2.\nRReplace (((a + b) + c) + - a) (b + c); auto.\nassert (image_angle (- c) = cons_AV (vec C B) (vec C P)).\napply mes_oppx; auto.\nassert (image_angle (- b) = cons_AV (vec B P) (vec B C)).\napply mes_oppx; auto.\nassert (image_angle (pi + (b + c)) = cons_AV (vec P C) (vec P B)).\nrewrite <- (angle_triangle (A:=C) (B:=B) (C:=P)); auto.\nrewrite <- H13.\nrewrite <- H12.\nrewrite <- add_mes_compatible.\nrewrite <- mes_opp.\nrewrite <- add_mes_compatible.\nRReplace (- (- c + - b)) (b + c); auto.\nelim pi_plus_x with ( x := b + c ); intros.\nassert (- sin (b + c) <> 0).\nrewrite <- H17.\napply (triangle_sin_not_0 (A:=P) (B:=C) (C:=B) (x:=pi + (b + c))); auto with geo.\nreplace (a + b + c - a) with (b + c) by ring.\nauto with real.\nQed.\n(* calcul de la longueur du cote  CP dans le triangle BPC*)\n \nLemma Morley_3:\n forall (a b c r : R) (A B C P : PO),\n 0 < a ->\n 0 < b ->\n 0 < c ->\n (a + b) + c = pisurtrois ->\n A <> B ->\n A <> C ->\n B <> C ->\n B <> P ->\n rayon_circonscrit A B C r ->\n image_angle b = cons_AV (vec B C) (vec B P) ->\n image_angle c = cons_AV (vec C P) (vec C B) ->\n image_angle (3 * a) = cons_AV (vec A B) (vec A C) ->\n  distance C P = (8 * (r * sin a)) * (sin b * sin (pisurtrois + a)).\nunfold rayon_circonscrit; intros.\nelim H7; clear H7; [intros O [H13 H12]].\nassert (triangle A B C).\napply (pisurtrois_triangle_utile (a:=a) (b:=b) (c:=c) (A:=A) (B:=B) (C:=C));\n auto.\nassert (triangle B C P).\napply (pisurtrois_triangle_utile2 (a:=a) (b:=b) (c:=c) (B:=B) (C:=C) (P:=P));\n auto.\nderoule_triangle B C P.\nclear H17 H14 H15.\nassert (distance C P = (2 * (r * sin (3 * a))) * (sin b / sin (pisurtrois - a))).\nassert (distance B C = 2 * (r * sin (3 * a))).\nrewrite (rayon_Sinus (A:=A) (B:=B) (C:=C) (O:=O)); auto.\nrewrite H12.\nrewrite <- (egalite_sin_Sin (A:=A) (B:=B) (C:=C) (x:=3 * a)); auto.\nrewrite Rabs_right; eauto with geo.\nrewrite <- H14.\nrewrite <- H2.\nRReplace (((a + b) + c) - a) (b + c).\nelim pi_moins_x with ( x := b + c ); [intros].\nrewrite <- H17.\nelim (loi_Sinus (A:=C) (B:=B) (C:=P)); intros; auto with geo.\nassert\n (distance C B / Rabs (Sin (cons_AV (vec P C) (vec P B))) =\n  distance P C / Rabs (Sin (cons_AV (vec B P) (vec B C)))).\nrewrite <- H19; auto.\nassert\n (distance P C =\n  (distance C B / Rabs (Sin (cons_AV (vec P C) (vec P B)))) *\n  Rabs (Sin (cons_AV (vec B P) (vec B C)))).\nrewrite H20.\nfield.\nauto with geo.\nrewrite distance_sym.\nrewrite H21.\nrewrite distance_sym.\nassert (image_angle (- b) = cons_AV (vec B P) (vec B C)).\napply mes_oppx; auto.\nassert (image_angle (- c) = cons_AV (vec C B) (vec C P)).\napply mes_oppx; auto.\nrewrite <- (egalite_sin_Sin (A:=B) (B:=P) (C:=C) (x:=- b)); auto.\nrewrite sin_impaire.\nrewrite (Rabs_neg (r:=- sin b)).\nassert (image_angle (pi + (b + c)) = cons_AV (vec P C) (vec P B)).\nrewrite <- (angle_triangle (A:=C) (B:=B) (C:=P)); auto.\nrewrite <- H23.\nrewrite <- H22.\nrewrite <- add_mes_compatible.\nrewrite <- mes_opp.\nrewrite <- add_mes_compatible.\nRReplace (- (- c + - b)) (b + c); auto.\nrewrite <- (egalite_sin_Sin (A:=P) (B:=C) (C:=B) (x:=pi + (b + c))); auto.\nrewrite H17.\nelim pi_plus_x with ( x := b + c ); intros.\nrewrite H26.\nrewrite Rabs_neg.\nfield.\nassert (- sin (b + c) <> 0).\nrewrite <- H26.\napply (triangle_sin_not_0 (A:=P) (B:=C) (C:=B) (x:=pi + (b + c))); auto with geo.\nauto with real.\nassert (sin (b + c) >= 0); eauto with geo.\nlra.\nassert (sin b >= 0).\napply sin_pos.\napply (pisurtrois_utile2 H H1 H0); auto with real.\nrewrite <- H2; ring.\nlra.\nrewrite H14.\nrewrite sin_3_a_pisurtrois; auto.\nfield.\nrewrite <- H2.\nRReplace (((a + b) + c) + - a) (b + c); auto.\nassert (image_angle (- c) = cons_AV (vec C B) (vec C P)).\napply mes_oppx; auto.\nassert (image_angle (- b) = cons_AV (vec B P) (vec B C)).\napply mes_oppx; auto.\nassert (image_angle (pi + (b + c)) = cons_AV (vec P C) (vec P B)).\nrewrite <- (angle_triangle (A:=C) (B:=B) (C:=P)); auto.\nrewrite <- H15.\nrewrite <- H17.\nrewrite <- add_mes_compatible.\nrewrite <- mes_opp.\nrewrite <- add_mes_compatible.\nRReplace (- (- c + - b)) (b + c); auto.\nelim pi_plus_x with ( x := b + c ); intros.\nassert (- sin (b + c) <> 0).\nrewrite <- H20.\napply (triangle_sin_not_0 (A:=P) (B:=C) (C:=B) (x:=pi + (b + c))); auto with geo.\nreplace (a + b + c - a) with (b + c) by ring.\nauto with real.\nQed.\n(* on applique le lemme precedent dans un autre triangle ABQ forme par un cote et deux trissectrices*)\n \nLemma Morley_4:\n forall (a b c r : R) (A B C Q : PO),\n 0 < a ->\n 0 < b ->\n 0 < c ->\n (a + b) + c = pisurtrois ->\n A <> B ->\n A <> C ->\n B <> C ->\n A <> Q ->\n rayon_circonscrit A B C r ->\n image_angle b = cons_AV (vec B Q) (vec B A) ->\n image_angle a = cons_AV (vec A B) (vec A Q) ->\n image_angle (3 * c) = cons_AV (vec C A) (vec C B) ->\n  distance B Q = (8 * (r * sin c)) * (sin a * sin (pisurtrois + c)).\nintros.\nrewrite <- (Morley_3 (a:=c) (b:=a) (c:=b) (r:=r) (A:=C) (B:=A) (C:=B) (P:=Q));\n auto with geo.\nrewrite <- H2; ring.\ngeneralize H7; unfold rayon_circonscrit, circonscrit, isocele; intros.\nelim H11; [intros O [H13 H14]].\nelim H13; [intros H12 H15].\nexists O.\nsplit; auto.\nsplit; auto.\nrewrite <- H12; auto.\nrewrite H14; rewrite <- H15; auto.\nQed.\n(*dans le triangle BPQ on peut caculer le 3eme cote en utilisant Al_Kashi*)\n \nLemma Morley_5:\n forall (a b c r : R) (A B C P Q : PO),\n 0 < a ->\n 0 < b ->\n 0 < c ->\n (a + b) + c = pisurtrois ->\n A <> B ->\n A <> C ->\n B <> C ->\n B <> P ->\n B <> Q ->\n A <> Q ->\n rayon_circonscrit A B C r ->\n image_angle b = cons_AV (vec B Q) (vec B A) ->\n image_angle b = cons_AV (vec B C) (vec B P) ->\n image_angle b = cons_AV (vec B P) (vec B Q) ->\n image_angle c = cons_AV (vec C P) (vec C B) ->\n image_angle a = cons_AV (vec A B) (vec A Q) ->\n image_angle (3 * a) = cons_AV (vec A B) (vec A C) ->\n image_angle (3 * c) = cons_AV (vec C A) (vec C B) ->\n  Rsqr (distance P Q) =\n  (Rsqr 8 * (Rsqr r * (Rsqr (sin a) * Rsqr (sin c)))) *\n  ((Rsqr (sin (pisurtrois + a)) + Rsqr (sin (pisurtrois + c))) -\n   2 * (sin (pisurtrois + a) * (sin (pisurtrois + c) * cos b))).\nintros.\nrewrite (Al_Kashi (A:=B) (B:=P) (C:=Q) (a:=b)); auto.\nrewrite (Morley_2 (a:=a) (b:=b) (c:=c) (r:=r) (A:=A) (B:=B) (C:=C) (P:=P)); auto.\nrewrite (Morley_4 (a:=a) (b:=b) (c:=c) (r:=r) (A:=A) (B:=B) (C:=C) (Q:=Q)); auto.\nreplace (Rsqr ((8 * (r * sin a)) * (sin c * sin (pisurtrois + a))))\n     with\n      ((Rsqr 8 * (Rsqr r * (Rsqr (sin a) * Rsqr (sin c)))) *\n       Rsqr (sin (pisurtrois + a))).\n2:unfold Rsqr; ring.\nreplace (Rsqr ((8 * (r * sin c)) * (sin a * sin (pisurtrois + c))))\n     with\n      ((Rsqr 8 * (Rsqr r * (Rsqr (sin a) * Rsqr (sin c)))) *\n       Rsqr (sin (pisurtrois + c))).\n2:unfold Rsqr; ring.\nreplace\n (((8 * (r * sin a)) * (sin c * sin (pisurtrois + a))) *\n  (((8 * (r * sin c)) * (sin a * sin (pisurtrois + c))) * cos b))\n     with\n      ((Rsqr 8 * (Rsqr r * (Rsqr (sin a) * Rsqr (sin c)))) *\n       (sin (pisurtrois + a) * (sin (pisurtrois + c) * cos b))).\n2:unfold Rsqr; ring.\nring.\nQed.\n(* utilisation de la formule de trigonometrie Al_Kashi_pisurtrois pour simplifier le calcul.*)\n \nLemma Morley_6:\n forall (a b c r : R) (A B C P Q : PO),\n 0 < a ->\n 0 < b ->\n 0 < c ->\n (a + b) + c = pisurtrois ->\n A <> B ->\n A <> C ->\n B <> C ->\n B <> P ->\n B <> Q ->\n A <> Q ->\n rayon_circonscrit A B C r ->\n image_angle b = cons_AV (vec B Q) (vec B A) ->\n image_angle b = cons_AV (vec B C) (vec B P) ->\n image_angle b = cons_AV (vec B P) (vec B Q) ->\n image_angle c = cons_AV (vec C P) (vec C B) ->\n image_angle a = cons_AV (vec A B) (vec A Q) ->\n image_angle (3 * a) = cons_AV (vec A B) (vec A C) ->\n image_angle (3 * c) = cons_AV (vec C A) (vec C B) ->\n  Rsqr (distance P Q) =\n  (Rsqr 8 * (Rsqr r * (Rsqr (sin a) * Rsqr (sin b)))) * Rsqr (sin c).\nintros.\nrewrite (Morley_5 (a:=a) (b:=b) (c:=c) (r:=r) (A:=A) (B:=B) (C:=C) (P:=P) (Q:=Q));\n auto.\nrewrite (Al_Kashi_pisurtrois (a:=a) (b:=b) (c:=c)); auto.\nring.\nQed.\n \nDefinition equilateral (A B C : PO) := and (isocele A B C) (isocele B C A).\n(*Theoreme de Morley : utilisation de la symetrie de la formule pour conclure.*)\n \nTheorem Morley:\n forall (a b c : R) (A B C P Q T : PO),\n 0 < a ->\n 0 < b ->\n 0 < c ->\n (a + b) + c = pisurtrois ->\n A <> B ->\n A <> C ->\n B <> C ->\n B <> P ->\n B <> Q ->\n A <> T ->\n C <> T ->\n image_angle b = cons_AV (vec B C) (vec B P) ->\n image_angle b = cons_AV (vec B P) (vec B Q) ->\n image_angle b = cons_AV (vec B Q) (vec B A) ->\n image_angle c = cons_AV (vec C P) (vec C B) ->\n image_angle c = cons_AV (vec C T) (vec C P) ->\n image_angle a = cons_AV (vec A B) (vec A Q) ->\n image_angle a = cons_AV (vec A Q) (vec A T) ->\n image_angle a = cons_AV (vec A T) (vec A C) ->  equilateral P Q T.\nintros.\nassert (triangle B C P).\n  apply (pisurtrois_triangle_utile2 (a:=a) (b:=b) (c:=c) (B:=B) (C:=C) (P:=P));\n  auto.\nderoule_triangle B C P.\nassert (triangle B Q A).\n  apply (pisurtrois_triangle_utile2 (a:=a) (b:=b) (c:=c) (B:=B) (C:=Q) (P:=A));\n  auto.\nderoule_triangle B Q A.\nassert (image_angle (3 * a) = cons_AV (vec A B) (vec A C)).\n  RReplace (3 * a) (a + (a + a)).\n  replace (cons_AV (vec A B) (vec A C))\n     with (plus (cons_AV (vec A B) (vec A Q)) (cons_AV (vec A Q) (vec A C))).\n  replace (cons_AV (vec A Q) (vec A C))\n     with (plus (cons_AV (vec A Q) (vec A T)) (cons_AV (vec A T) (vec A C))).\n  rewrite <- H15; rewrite <- H16; rewrite <- H17.\n  rewrite <- add_mes_compatible.\n  rewrite <- add_mes_compatible; auto.\n  apply Chasles; auto.\n  apply Chasles; auto.\nassert (triangle A B C).\n  apply (pisurtrois_triangle_utile (a:=a) (b:=b) (c:=c) (A:=A) (B:=B) (C:=C));\n  auto.\nassert (image_angle (3 * b) = cons_AV (vec B C) (vec B A)).\n  RReplace (3 * b) (b + (b + b)).\n  replace (cons_AV (vec B C) (vec B A))\n     with (plus (cons_AV (vec B C) (vec B P)) (cons_AV (vec B P) (vec B A))).\n  replace (cons_AV (vec B P) (vec B A))\n     with (plus (cons_AV (vec B P) (vec B Q)) (cons_AV (vec B Q) (vec B A))).\n  rewrite <- H12; rewrite <- H11; rewrite <- H10.\n  rewrite <- add_mes_compatible.\n  rewrite <- add_mes_compatible; auto.\n  apply Chasles; auto.\n  apply Chasles; auto.\nassert (image_angle (3 * c) = cons_AV (vec C A) (vec C B)).\n  rewrite <- (angle_triangle (A:=A) (B:=B) (C:=C)); auto.\n  rewrite <- H28.\n  rewrite <- H30.\n  rewrite <- add_mes_compatible.\n  rewrite <- mes_opp.\n  rewrite <- add_mes_compatible.\n  rewrite <- pisurtrois_def.\n  rewrite <- H2.\n  RReplace (3 * ((a + b) + c) + - (3 * a + 3 * b)) (3 * c); auto.\nassert (image_angle c = cons_AV (vec C A) (vec C T)).\n  RReplace c ((3 * c + - c) + - c).\n  rewrite add_mes_compatible.\n  rewrite add_mes_compatible.\n  rewrite H31.\n  assert (image_angle (- c) = cons_AV (vec C B) (vec C P)).\n    apply mes_oppx; auto.\n  pattern (image_angle (- c)) at 1.\n  rewrite H32.\n  replace (plus (cons_AV (vec C A) (vec C B)) (cons_AV (vec C B) (vec C P)))\n     with (cons_AV (vec C A) (vec C P)).\n  assert (image_angle (- c) = cons_AV (vec C P) (vec C T)).\n    apply mes_oppx; auto.\n  rewrite H33.\n  apply Chasles; auto.\n  symmetry; apply Chasles; auto.\nelim existence_rayon_circonscrit with ( A := A ) ( B := B ) ( C := C );\n [intros O [H33 [r H34]] | auto].\nassert (rayon_circonscrit A B C r).\n  unfold rayon_circonscrit.\n  exists O; (split; auto).\nassert\n (and\n   (Rsqr (distance P Q) = Rsqr (distance T P))\n   (Rsqr (distance P Q) = Rsqr (distance Q T))).\n  rewrite (Morley_6 (a:=a) (b:=b) (c:=c) (r:=r) (A:=A) (B:=B) (C:=C) (P:=P) (Q:=Q));\n  auto.\n  rewrite (Morley_6 (a:=b) (b:=c) (c:=a) (r:=r) (A:=B) (B:=C) (C:=A) (P:=T) (Q:=P));\n  auto.\n  rewrite (Morley_6 (a:=c) (b:=a) (c:=b) (r:=r) (A:=C) (B:=A) (C:=B) (P:=Q) (Q:=T));\n  auto.\n  split; ring.\n  rewrite <- H2; ring.\n  exists O.\n  rewrite H34.\n  generalize H33; unfold circonscrit, isocele; intros.\n  elim H36; [intros; (split; auto)].\n  rewrite <- H38; auto.\n  rewrite <- H37; auto.\n  rewrite <- H2; ring.\n  exists O.\n  rewrite H34.\n  generalize H33; unfold circonscrit, isocele; intros.\n  elim H36; [intros; (split; auto)].\n  rewrite <- H38; auto.\nunfold equilateral, isocele.\nelim H36; [intros].\nsplit.\n  rewrite (distance_sym P T); auto with geo.\nrewrite (distance_sym Q P); auto with geo.\nQed.\n\n\n", "meta": {"author": "coq-community", "repo": "HighSchoolGeometry", "sha": "bbf0083ff9b228e873a7de972ee3190dbd229ead", "save_path": "github-repos/coq/coq-community-HighSchoolGeometry", "path": "github-repos/coq/coq-community-HighSchoolGeometry/HighSchoolGeometry-bbf0083ff9b228e873a7de972ee3190dbd229ead/theories/exercice_morley.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6590870048301748}}
{"text": "Require Coq.Arith.Compare_dec.\nRequire Coq.FSets.FMapFacts.\n\nRequire Import Coq.Structures.OrderedType.\nRequire Import Coq.Structures.OrderedTypeEx.\nRequire Import Coq.FSets.FMapAVL.\nRequire Import Coq.FSets.FSetAVL.\nRequire Import Coq.Arith.Peano_dec.\nRequire Import Aniceto.Map.\n\nRequire Import HJ.Mid.\nRequire Import HJ.Tid.\n\nNotation dep := (mid + tid)%type.\n\nNotation d_mid := (@inl mid tid).\n\nNotation d_tid := (@inr mid tid).\n\nModule SumOrderedType (O1 O2:OrderedType) <: OrderedType.\n  Definition t := sum O1.t O2.t.\n  Definition eq o1 o2 :=\n    match o1 with\n    | inl l =>\n      match o2 with\n      | inl r => O1.eq l r\n      | inr r => False\n      end\n    | inr l =>\n      match o2 with\n      | inl r => False\n      | inr r => O2.eq l r\n      end\n    end.\n    \n  Definition lt o1 o2 :=\n    match o1 with\n    | inl l =>\n      match o2 with\n      | inl r => O1.lt l r\n      | inr r => True\n      end\n    | inr l =>\n      match o2 with\n      | inl r => False\n      | inr r => O2.lt l r\n      end\n    end.\n\n  Lemma eq_refl:\n    forall x,\n    eq x x.\n  Proof.\n    intros.\n    destruct x; simpl; eauto using O1.eq_refl, O2.eq_refl.\n  Qed.\n\n  Lemma eq_sym:\n    forall x y,\n    eq x y ->\n    eq y x.\n  Proof.\n    intros.\n    destruct x, y; simpl in *; eauto using O1.eq_sym, O2.eq_sym.\n  Qed.\n\n  Lemma eq_trans :\n    forall x y z,\n    eq x y ->\n    eq y z ->\n    eq x z.\n  Proof.\n    intros.\n    destruct x, y, z; simpl in *.\n    - eauto using O1.eq_trans.\n    - inversion H0.\n    - inversion H0.\n    - inversion H.\n    - inversion H.\n    - inversion H.\n    - inversion H0.\n    - eauto using O2.eq_trans.\n  Qed.\n\n  Lemma lt_trans:\n    forall x y z : t, lt x y -> lt y z -> lt x z.\n  Proof.\n    intros.\n    unfold lt in *.\n    destruct x, y, z; auto.\n    - eauto using O1.lt_trans.\n    - inversion H0.\n    - inversion H.\n    - eauto using O2.lt_trans.\n  Qed.\n\n  Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y.\n  Proof.\n    intros.\n    destruct x, y; simpl in *.\n    - eauto using O1.lt_not_eq.\n    - intuition; inversion H0.\n    - inversion H.\n    - eauto using O2.lt_not_eq.\n  Qed.\n\n  Import Coq.Arith.Compare_dec.\n  Lemma compare:\n    forall x y, Compare lt eq x y.\n  Proof.\n    intros.\n    destruct x, y.\n    - assert (C: Compare O1.lt O1.eq t0 t1) by eauto using O1.compare.\n      destruct C; eauto using LT, EQ, GT.\n    - apply LT.\n      simpl.\n      trivial.\n    - apply GT.\n      simpl.\n      trivial.\n    - assert (C: Compare O2.lt O2.eq t0 t1) by eauto using O2.compare.\n      destruct C; eauto using LT, EQ, GT.\n  Qed.\n\n  Lemma eq_dec : forall x y : t, {eq x y} + {~ eq x y}.\n  Proof.\n    intros.\n    destruct x, y; simpl; eauto using O1.eq_dec, O2.eq_dec.\n  Qed.\n\n  Lemma eq_rw\n    (o1_eq_rw: forall x y, O1.eq x y <-> x = y)\n    (o2_eq_rw: forall x y, O2.eq x y <-> x = y):\n    forall x y, eq x y <-> x = y.\n  Proof.\n    intros.\n    destruct x, y; simpl in *.\n    - split.\n      + intros.\n        apply o1_eq_rw in H; subst.\n        trivial.\n      + intros.\n        inversion H; subst.\n        rewrite o1_eq_rw.\n        trivial.\n    - split; intros; inversion H.\n    - split; intros; inversion H.\n    - split.\n      + intros.\n        apply o2_eq_rw in H; subst.\n        trivial.\n      + intros.\n        inversion H; subst.\n        rewrite o2_eq_rw.\n        trivial.\n  Qed.\n\nEnd SumOrderedType.\n\nModule DEP := SumOrderedType MID TID.\n\nLemma dep_eq_rw:\n  forall x y, DEP.eq x y <-> x = y.\nProof.\n  intros.\n  split;\n  intros;\n  apply DEP.eq_rw in H; auto using mid_eq_rw, tid_eq_rw.\nQed.\n\nLemma dep_eq_dec:\n  forall (x y:dep),\n  { x = y } + { x <> y }.\nProof.\n  intros.\n  destruct (DEP.eq_dec x y); rewrite dep_eq_rw in *; auto.\nQed.\n\nModule SD := FSetAVL.Make DEP.\nModule SD_Facts := FSetFacts.Facts SD.\nDefinition set_dep := SD.t.\n\n", "meta": {"author": "cogumbreiro", "repo": "gorn-coq", "sha": "ee4384d7ae8513c314ffb25027c4249903c6275b", "save_path": "github-repos/coq/cogumbreiro-gorn-coq", "path": "github-repos/coq/cogumbreiro-gorn-coq/gorn-coq-ee4384d7ae8513c314ffb25027c4249903c6275b/src/Dep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694177, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6590870044756061}}
{"text": "Require Export ProjectiveGeometry.Dev.matroid_properties.\nRequire Export ProjectiveGeometry.Dev.projective_space_rank_axioms.\n\n(*****************************************************************************)\n(** Rank space or higher properties **)\n\n\nSection s_rankProperties_1.\n\nContext `{M : RankProjectiveSpace}.\nContext `{EP : EqDecidability Point}.\n\n\nLemma rk_singleton : forall p : Point, rk (singleton p) = 1.\nProof.\nintros.\nassert (rk (singleton p)<= 1).\napply (rk_singleton_le);auto.\nassert (rk (singleton p)>= 1).\napply (rk_singleton_ge);auto.\nomega.\nQed.\n\nLemma rk_couple1 : forall p q : Point,~ p [==] q -> rk(couple p q)=2.\nProof.\nintros.\nassert (rk(couple p q)<=2).\napply (rk_couple_2).\nassert (rk(couple p q)>=2).\napply (rk_couple_ge);auto.\nomega.\nQed.\n\nLemma couple_rk1 : forall p q : Point, rk(couple p q) = 2 -> ~ p [==] q.\nProof.\nintros.\nunfold not;intro.\nassert (rk (couple p q) = 1).\nsetoid_replace (couple p q) with (singleton p).\napply rk_singleton.\nrewrite H1.\nclear H0 H1.\nfsetdecide.\nrewrite H0 in H2.\ninversion H2.\nQed.\n\nLemma couple_rk2 : forall p q : Point, rk (couple p q) = 1 -> p [==] q.\nProof.\nintros.\ncase_eq(eq_dec p q).\nintros.\nassumption.\nintro.\nassert (rk(couple p q)=2).\napply rk_couple1;assumption.\nrewrite H0 in H1.\nassert False.\nintuition.\nintuition.\nQed.\n\nLemma rk_couple2 : forall p q : Point, p [==] q -> rk(couple p q) = 1.\nProof.\nintros.\nsetoid_replace (couple p q) with (singleton p).\napply (rk_singleton).\nrewrite H0.\nfsetdecide.\nQed.\n\nLemma rk_couple_1 : forall p q, 1 <= rk (couple p q).\nProof.\nintros.\ncase_eq(eq_dec p q).\nintro.\nrewrite rk_couple2.\nomega.\nassumption.\nintro.\nrewrite rk_couple1.\nomega.\nassumption.\nQed.\n\nLemma couple_rk_degen : forall p, rk (couple p p) = 2 -> False.\nProof.\nintros.\nassert (rk (couple p p) = 1).\nsetoid_replace (couple p p) with (singleton p).\napply rk_singleton.\nfsetdecide.\nintuition.\nQed.\n\nHint Resolve rk_singleton rk_couple1 rk_couple2 couple_rk1 couple_rk2 couple_rk_degen : rk.\n\nLemma base_points_distinct_1 : ~ P0 [==] P1.\nProof.\nassert (T:= rk_lower_dim).\nunfold not;intro.\nrewrite H0 in T.\nsetoid_replace (quadruple P1 P1 P2 P3) with (triple P1 P2 P3) in T by fsetdecide.\nassert (rk (triple P1 P2 P3) <= 3).\napply rk_triple_le.\nomega.\nQed.\n\nLemma base_points_distinct_2 : ~ P2 [==] P3.\nProof.\nassert (T:= rk_lower_dim).\nunfold not;intro.\nrewrite H0 in T.\nsetoid_replace (quadruple P0 P1 P3 P3) with (triple P0 P1 P3) in T by fsetdecide.\nassert (rk (triple P0 P1 P3) <= 3).\napply rk_triple_le.\nomega.\nQed.\n\nLemma rk_lemma_1 : forall A B P Q,\nrk (couple A B) = 2 ->\nrk (triple A B P) = 2 ->\nrk (triple A B Q) = 2 ->\nrk (quadruple A B P Q) = 2.\nProof.\nintros.\nassert (rk (union (triple A B P) (triple A B Q)) + rk (couple A B) <=\n           rk (triple A B P) + rk (triple A B Q)).\napply (matroid3_useful (triple A B P) (triple A B Q) (couple A B)).\nclear_all;fsetdecide.\n\nassert (rk (union (triple A B P) (triple A B Q)) <= 2).\nomega.\nsetoid_replace (union (triple A B P) (triple A B Q)) with (quadruple A B P Q) in H4.\napply le_antisym.\nauto.\ncut (rk (couple A B) <= rk (quadruple A B P Q)).\nomega.\napply matroid2.\nclear_all;fsetdecide.\nclear_all;fsetdecide.\nQed.\n\nLemma rk_quadruple_max_4_wc : forall A B C D : Point, \n~ A[==]B -> ~ C[==]D -> rk(quadruple A B C D) <= 4.\nProof.\nintros.\napply rk_quadruple_le.\nQed.\n\nLemma rk_quadruple_3_or_higher : forall A B C D,\n~ A[==]B ->\n~ C[==]D ->\nrk(quadruple A B C D) <> 2 ->\nrk(quadruple A B C D) > 2.\nProof.\nintros.\nassert(HH := rk_quadruple_max_4_wc A B C D H0 H1).\nassert(HH0 : rk(quadruple A B C D) <> 1).\nintro.\nassert(HH1 := rk_couple1 A B H0).\nassert(HH2 : (couple A B [<=] quadruple A B C D)%set).\nfsetdecide.\nassert(HH3 := matroid2 (couple A B) (quadruple A B C D) HH2).\nomega.\nassert(HH1 := rk_couple1 A B H0).\nassert(HH2 : rk (couple A B) >= 2).\nintuition.\nassert(HH3 : (couple A B [<=] quadruple A B C D)%set).\nfsetdecide.\nassert(HH4 := matroid2 (couple A B) (quadruple A B C D) HH3).\nassert(HH5 : rk(quadruple A B C D) >= 2).\nomega.\nomega.\nQed.\n\nLemma rk_line_unification : forall A B C,\nrk(couple A B) = 2 -> rk(couple A C) = 2 -> \nrk(couple B C) = 2 -> rk(triple A B C) <= 2 -> rk(triple A B C) = 2.\nProof.\nintros.\nassert(HH : (couple A B [<=] triple A B C)%set).\nfsetdecide.\nassert(HH1 := matroid2 (couple A B) (triple A B C) HH).\nomega.\nQed.\n\nEnd s_rankProperties_1.\n\n\nSection s_rankProperties_2.\n\nContext `{M : RankProjectiveSpace}.\nContext `{EP : EqDecidability Point}.\n\nLemma intersecting_lines_rank_3 : forall A B C D I,\nrk (triple A B I) <= 2 ->\nrk (triple C D I) <= 2 ->\nrk (union (singleton I) (quadruple A B C D)) <= 3.\nProof.\nintros.\nassert (rk (union (triple A B I) (triple C D I)) +\n       rk (singleton I) <=\n       rk (triple A B I) + rk (triple C D I)).\napply (matroid3_useful (triple A B I) (triple C D I) (singleton I)).\nfsetdecide.\nrewrite rk_singleton in H2.\nsetoid_replace (union (triple A B I) (triple C D I)) \nwith (union (singleton I) (quadruple A B C D)) in H2.\nomega.\nunfold Equal; split;clear_all;fsetdecide.\nQed.\n\nEnd s_rankProperties_2.\n\nHint Resolve rk_singleton rk_couple1 rk_couple2 couple_rk1 couple_rk2 couple_rk_degen : rk_base.", "meta": {"author": "ProjectiveGeometry", "repo": "ProjectiveGeometry", "sha": "4f7f4e6c14580833c91fdef38d048259fb454b88", "save_path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry", "path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry/ProjectiveGeometry-4f7f4e6c14580833c91fdef38d048259fb454b88/Dev/rank_space_properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6590869958671273}}
{"text": "Require Import Logic_utils.\nRequire Import Relation.\nRequire Import Ordering.\nRequire Import NatProps.\n\nInductive Z : Type :=\n  | z ( n m : nat).\n\nAxiom z_eq : forall (n0 n1 m0 m1 : nat),\nn0 + m1 = n1 + m0 <-> z n0 m0 = z n1 m1.\n\nDefinition z_plus (z1 : Z)(z2 : Z) : Z :=\n  match z1 with \n  | z a b => match z2 with\n    | z c d => z (a+c) (b+d)\n    end\n  end.\n\nDefinition z_neg (z1 : Z) : Z :=\n  match z1 with\n  | z a b => z b a\n  end.\n\nDefinition z_minus (z1 : Z)(z2 : Z) :=\n  z_plus z1 (z_neg z2).\n\nDefinition z_mul (z1 : Z)(z2 : Z) :=\n  match z1 with\n  | z a b => match z2 with\n    | z c d => z (a*c + b*d) (a*d + b*c)\n    end\n  end.\n\nDefinition z_0 := z 0 0.\nDefinition z_1 := z 1 0.\nNotation \"a +z b\" := (z_plus a b) (at level 50, left associativity).\nNotation \"a -z b\" := (z_minus a b) (at level 50, left associativity).\nNotation \"a *z b\" := (z_mul a b) (at level 40, left associativity).\nNotation \"-z a\" := (z_neg a) (at level 35, right associativity).\n\nTheorem z_eq_neg : forall (a b : Z),\n  -za = -zb -> a = b.\nProof.\ndestruct a, b. simpl. intros. apply z_eq in H. apply z_eq. \nrewrite n_plus_comm. rewrite n_plus_comm with (m:=m). rewrite H. reflexivity.\nQed.\n\nTheorem z_plus_identity : forall (a : Z),\n  a +z z_0 = a.\nProof.\nintros. destruct a. simpl. rewrite n_plus_identity. rewrite n_plus_identity with (n:=m). reflexivity.\nQed.\n\nTheorem z_plus_inverse : forall (a : Z),\n  a +z -za = z_0.\nProof.\ndestruct a. simpl. apply z_eq. \nrewrite n_plus_identity. simpl. apply n_plus_comm.\nQed.\n\nTheorem z_plus_comm : forall (a b : Z),\n  a +z b = b +z a.\nProof.\ndestruct a, b. simpl. rewrite n_plus_comm. rewrite n_plus_comm with (n:=m0). reflexivity. \nQed.\n\nTheorem z_plus_assoc : forall (a b c : Z),\n  (a +z b) +z c = a +z (b +z c).\nProof.\ndestruct a, b, c. simpl. rewrite n_plus_assoc. rewrite n_plus_assoc with (n:=m). reflexivity.\nQed.\n\nTheorem z_plus_cancel : forall (a b c : Z),\n  a +z c = b +z c -> a = b.\nProof.\nintros. destruct a, b, c. simpl in H. apply z_eq in H. apply z_eq.\nrewrite n_plus_assoc in H. rewrite n_plus_assoc in H.\napply n_plus_cancel in H.\nrewrite <- n_plus_assoc in H. rewrite <- n_plus_assoc in H.\nrewrite n_plus_comm with (n:=n1) in H. rewrite n_plus_comm with (n:=n1) in H.\nrewrite n_plus_assoc in H. rewrite n_plus_assoc in H.\napply n_plus_cancel in H. apply H.\nQed.\n\nTheorem z_mul_identity : forall (a : Z),\n  a *z z_1 = a.\nProof.\ndestruct a. simpl. \nrewrite n_mul_identity. rewrite n_mul_identity with (n:=m).\nrewrite n_mul_zero. rewrite n_mul_zero. simpl.\nrewrite n_plus_identity. reflexivity.\nQed.\n\nTheorem z_mul_zero : forall (a : Z),\n  a *z z_0 = z_0.\nProof.\ndestruct a. simpl. \nrewrite n_mul_zero. rewrite n_mul_zero.\nrewrite n_plus_identity. reflexivity.\nQed.\n\nTheorem z_mul_neg : forall (a b : Z),\n  a *z (-zb) = -z(a *z b).\nProof.\ndestruct a, b. simpl. apply z_eq. reflexivity.\nQed.\n\nTheorem z_mul_comm : forall (a b : Z),\n  a *z b = b *z a.\nProof.\nintros. destruct a, b. simpl.\nrewrite n_mul_comm. rewrite n_mul_comm with(n:=m).\nrewrite n_mul_comm with (m:=m0). rewrite n_mul_comm with (m:=n0). \nrewrite n_plus_comm with (n:=m0*n). reflexivity.\nQed.\n\nTheorem z_distributive : forall (a b c : Z),\n  a *z (b +z c) = a *z b +z a *z c.\nProof.\nintros. destruct a, b, c. simpl.\nassert (H: forall (k k0 k1 l l0 l1: nat),\n  k * (k0 + k1) + l * (l0 + l1) = k * k0 + l * l0 + (k * k1 + l * l1)).\n{ intros.\nrewrite n_distributive with (n:=k). rewrite n_distributive with (n:=l).\nset (a:=k*k0). set (b:=k*k1). set (c:=l*l0). set (d:=l*l1).\nrewrite n_plus_assoc. rewrite <- n_plus_assoc with (k:=c). rewrite n_plus_comm with (n:=b).\nrewrite n_plus_assoc. rewrite <- n_plus_assoc with (k:=d). reflexivity. }\nrewrite H. rewrite H with (k:=n)(l:=m). reflexivity.\nQed.\n\nTheorem z_mul_assoc : forall (a b c : Z),\n  a *z (b *z c) = (a *z b) *z c.\nProof.\nintros. destruct a, b, c. simpl.\nassert (H : forall (k k0 k1 l l0 l1: nat), \n  k * (k0 * k1 + l0 * l1) + l * (k0 * l1 + l0 * k1) = (k * k0 + l * l0) * k1 + (k * l0 + l * k0) * l1).\nintros.\n{ rewrite n_distributive with (n:=k). rewrite n_distributive with (n:=l).\nrewrite n_right_distributive with (k:=k1). rewrite n_right_distributive with (k:=l1).\nrewrite n_mul_assoc. set (a:=k*k0*k1).\nrewrite n_mul_assoc. set (b:=k*l0*l1).\nrewrite n_mul_assoc. set (c:=l*k0*l1).\nrewrite n_mul_assoc. set (d:=l*l0*k1).\nrewrite <- n_plus_assoc with (k:=b+c). rewrite n_plus_comm with (n:=d).\nrewrite <- n_plus_assoc with (n:=a). rewrite n_plus_assoc with (n:=b).\nreflexivity. }\nrewrite H. rewrite H with (k:=n)(l:=m). reflexivity.\nQed.\n\n(* inequality *)\n\nDefinition z_le : Relation Z Z :=\nfun p => match p with\n| (a, b) => ( match a with\n  | z n0 m0 => match b with\n    | z n1 m1 => n0 + m1 <= n1 + m0\n    end\n  end)\nend.\n\nDefinition z_lt : Relation Z Z :=\nfun p => match p with\n| (a, b) => ( match a with\n  | z n0 m0 => match b with\n    | z n1 m1 => n0 + m1 < n1 + m0\n    end\n  end)\nend.\n\nDefinition z_ge : Relation Z Z :=\nfun p => match p with\n| (a, b) => z_le (b, a)\nend.\n\nDefinition z_gt : Relation Z Z :=\nfun p => match p with\n| (a, b) => z_lt (b, a)\nend.\n\nNotation \"a <=z b\" := (z_le (a, b)) (at level 70, no associativity).\nNotation \"a <z b\"  := (z_lt (a, b)) (at level 70, no associativity).\nNotation \"a >=z b\" := (z_ge (a, b)) (at level 70, no associativity).\nNotation \"a >z b\"  := (z_gt (a, b)) (at level 70, no associativity).\n\nTheorem z_le_reflexive : forall (a : Z),\n  a <=z a.\nProof.\ndestruct a. simpl. apply le_n.\nQed.\n\nTheorem z_le_transitive : forall (a b c : Z),\n  a <=z b -> b <=z c -> a <=z c.\nProof.\ndestruct a, b, c. simpl. intros ab bc.\npose (H:=n_le_sum (n+m0) (n0+m) (n0+m1) (n1+m0) ab bc).\nrewrite n_plus_comm in H. rewrite n_plus_assoc in H. rewrite n_plus_assoc in H.\napply n_le_plus in H.\nrewrite <- n_plus_assoc in H. rewrite <- n_plus_assoc in H.\nrewrite n_plus_comm in H. rewrite n_plus_comm with (n:=n0) in H.\napply n_le_plus in H.\nrewrite n_plus_comm. rewrite n_plus_comm with (n:=n1). apply H.\nQed.\n\nTheorem z_le_antisymmetric : forall (a b : Z),\n  a <=z b -> b <=z a -> a = b.\nProof.\ndestruct a, b. simpl. intros ab ba.\napply n_le_antisymmetric in ba. apply z_eq. apply ba. apply ab.\nQed.\n\nTheorem z_le_total_ordering : forall (a b : Z),\n  a <=z b \\/ b <=z a.\nProof.\nintros. destruct a, b. simpl. apply n_le_total_partial_ordering.\nQed.\n\nTheorem z_le_total_partial_ordering : total_partial_ordering z_le.\nProof.\nunfold total_partial_ordering. apply conj.\n- unfold partial_ordering. apply conj.\n  + unfold reflexive. apply z_le_reflexive.\n  + apply conj.\n    * unfold antisymmetric. apply z_le_antisymmetric.\n    * unfold transitive. apply z_le_transitive.\n- apply z_le_total_ordering.\nQed.\n\nTheorem z_lt_is_strict_z_le : z_lt = partial_to_strict z_le.\nProof.\nassert (nl : forall (n m: nat), n_lt (n, m) <-> partial_to_strict n_le (n, m)).\n{ apply Relation_eq. apply n_lt_is_strict_n_le. }\n\napply Relation_eq. intros. unfold partial_to_strict.\ndestruct a, b.\nassert (zneq : z n m <> z n0 m0 <-> n + m0 <> n0 + m).\n{ apply not_iff_compat. apply iff_sym. apply z_eq. }\napply and_iff_compat_l with (A:=n+m0<=n0+m) in zneq.\napply iff_iff_compat_l with (A:=n+m0<n0+m) in zneq.\napply zneq. apply nl.\nQed.\n\nTheorem z_le_is_partial_z_lt : z_le = strict_to_partial z_lt.\nProof.\nrewrite z_lt_is_strict_z_le. apply eq_sym.\napply partial_to_strict_to_partial_identity.\napply z_le_total_partial_ordering.\nQed.\n\nTheorem z_lt_total_strict_ordering : total_strict_ordering z_lt.\nProof.\nrewrite z_lt_is_strict_z_le.\napply partial_to_strict_preserves_totality.\napply z_le_total_partial_ordering.\nQed.\n\nTheorem z_le_neg : forall (a b : Z),\n  a <=z b -> -zb <=z -za.\nProof.\n  destruct a, b. simpl. intros.\n  rewrite n_plus_comm. rewrite n_plus_comm with (n:=m). apply H.\nQed.\n\nTheorem z_lt_neg : forall (a b : Z),\n  a <z b -> -zb <z -za.\nProof.\n  destruct a, b. simpl. intros.\n  rewrite n_plus_comm. rewrite n_plus_comm with (n:=m). apply H.\nQed.\n\nTheorem z_le_plus : forall (a b c : Z),\n  a <=z b <-> a +z c <=z b +z c.\nProof.\ndestruct a, b, c. simpl. unfold iff. apply conj.\n- intros. rewrite n_plus_assoc. rewrite n_plus_assoc.\n  apply n_le_plus.\n  rewrite <- n_plus_assoc. rewrite <- n_plus_assoc.\n  rewrite n_plus_comm with (n:=n1). rewrite n_plus_comm with (n:=n1).\n  rewrite n_plus_assoc. rewrite n_plus_assoc.\n  apply n_le_plus. apply H.\n- intros. rewrite n_plus_assoc in H. rewrite n_plus_assoc in H.\n  apply n_le_plus in H.\n  rewrite <- n_plus_assoc in H. rewrite <- n_plus_assoc in H.\n  rewrite n_plus_comm with (n:=n1) in H. rewrite n_plus_comm with (n:=n1) in H.\n  rewrite n_plus_assoc in H. rewrite n_plus_assoc in H.\n  apply n_le_plus in H. apply H.\nQed.\n\nTheorem z_le_sum : forall (a b c d : Z),\n  a <=z b -> c <=z d -> a +z c <=z b +z d.\nProof.\ndestruct a, b, c, d. simpl. intros ab cd.\npose (H:=n_le_sum (n+m0) (n0+m) (n1+m2) (n2+m1) ab cd).\nrewrite <- n_plus_assoc. rewrite <- n_plus_assoc.\nrewrite n_plus_assoc with (n:=n1). rewrite n_plus_assoc with (n:=n2).\nrewrite n_plus_comm with (n:=n1). rewrite n_plus_comm with (n:=n2).\nrewrite <- n_plus_assoc. rewrite <- n_plus_assoc.\nrewrite n_plus_assoc. rewrite n_plus_assoc with (n:=n0). apply H.\nQed.\n\nTheorem z_lt_plus : forall (a b c : Z),\n  a <z b <-> a +z c <z b +z c.\nProof.\nintros. apply conj.\n- rewrite z_lt_is_strict_z_le. intros ab. apply conj.\n  + apply z_le_plus. apply ab.\n  + intros eqacbc. apply z_plus_cancel in eqacbc. apply ab in eqacbc. contradiction.\n- rewrite z_lt_is_strict_z_le. intros acbc. apply conj.\n  + apply proj1 in acbc. apply z_le_plus in acbc. apply acbc.\n  + intros eqab. rewrite eqab in acbc. apply acbc. reflexivity.\nQed.\n\nTheorem z_le_lt_sum : forall (a b c d : Z),\n  a <z b -> c <=z d -> a +z c <z b +z d.\nProof.\nintros a b c d ab cd.\nrewrite z_lt_is_strict_z_le in ab. rewrite z_lt_is_strict_z_le. apply conj.\n- apply z_le_sum. apply ab. apply cd.\n- intros ac_eq_bd. apply z_le_plus with (c:=a) in cd. rewrite z_plus_comm in cd. rewrite z_plus_comm with (a:=d) in cd.\n  rewrite ac_eq_bd in cd. apply z_le_plus in cd. \n  pose (leH := z_le_total_partial_ordering). destruct leH as [partial total].\n  destruct partial as [refl anti]. apply proj1 in anti.\n  destruct ab as [ab a_neq_b]. apply a_neq_b in anti. contradiction.\n  apply ab. apply cd.\nQed.\n\nTheorem z_lt_sum : forall (a b c d : Z),\n  a <z b -> c <z d -> a +z c <z b +z d.\nProof.\nintros a b c d ab cd.\nrewrite z_lt_is_strict_z_le in cd. apply z_le_lt_sum. apply ab. apply cd.\nQed.\n\nTheorem z_lt_mul : forall (a b c : Z),\n  a <z b -> z_0 <z c -> a *z c <z b *z c.\nProof.\ndestruct a, b, c. simpl. intros ab cpos. rewrite n_plus_identity in cpos.\nrewrite <- n_plus_assoc. rewrite n_plus_assoc with (n:=m*m1). \nrewrite <- n_right_distributive. rewrite n_plus_comm with (m:=m0*n1).\nrewrite n_plus_assoc. rewrite <- n_right_distributive. rewrite n_plus_comm with (n:=m).\n\nrewrite <- n_plus_assoc. rewrite n_plus_assoc with (n:=m0*m1).\nrewrite <- n_right_distributive. rewrite n_plus_comm with (m:=m*n1).\nrewrite n_plus_assoc. rewrite <- n_right_distributive. rewrite n_plus_comm with (m:=n).\nrewrite n_plus_comm with (n:=(n0+m)*n1).\n\napply n_lt_lemma1. apply ab. apply cpos.\nQed.\n\nTheorem z_lt_mul2 : forall (a b c : Z),\n  a *z c <z b *z c -> z_0 <z c -> a <z b.\nProof.\nintros a b c acbc cpos.\ndestruct z_lt_total_strict_ordering as [strict total].\ndestruct (total a b) as [ab|ba].\n- apply ab.\n- destruct ba as [ba|eq].\n  + pose (bcac := z_lt_mul b a c ba cpos). apply strict in bcac. contradiction.\n  + rewrite eq in acbc. apply strict in acbc as bcac. contradiction.\nQed. \n\nTheorem z_le_mul : forall (a b c : Z),\n  a <=z b -> z_0 <=z c -> a *z c <=z b *z c.\nProof.\nintros a b c ab cpos.\nrewrite z_le_is_partial_z_lt in ab. destruct ab as [ab|eqab].\n- rewrite z_le_is_partial_z_lt in cpos. destruct cpos as [cpos|c0].\n  + rewrite z_le_is_partial_z_lt. left. apply z_lt_mul. apply ab. apply cpos.\n  + rewrite <- c0. rewrite z_mul_zero. rewrite z_mul_zero. simpl. apply le_n.\n- rewrite eqab. apply z_le_total_partial_ordering.\nQed.\n\nTheorem z_le_mul2 : forall (a b c : Z),\n  a *z c <=z b *z c -> z_0 <z c -> a <=z b.\nProof.\nintros a b c acbc cpos.\ndestruct z_lt_total_strict_ordering as [strict total].\ndestruct (total a b) as [ab|ba].\n- rewrite z_lt_is_strict_z_le in ab. apply ab.\n- destruct ba as [ba|eq].\n  + pose (bcac := z_lt_mul b a c ba cpos).\n    rewrite z_lt_is_strict_z_le in bcac. destruct bcac.\n    apply z_le_total_partial_ordering in acbc. apply acbc in H. apply eq_sym in H. contradiction.\n  + rewrite eq. apply z_le_total_partial_ordering.\nQed.\n\nTheorem z_pos_nonzero : forall (a : Z),\n  z_0 <z a -> a <> z_0.\nProof.\nintros. intro. rewrite H0 in H. inversion H.\nQed.\n\nTheorem z_mul_cancel : forall (a b c : Z),\n  a *z c = b *z c /\\ ~ c = z_0 -> a = b.\nProof.\nintros a b c. \npose z_lt_total_strict_ordering as H. destruct H as [strict total].\nintros eqacbc. destruct (total z_0 c) as [c_pos|c_neg].\n- apply proj1 in eqacbc. destruct (total a b) as [ab|ba].\n  + pose (acbc:= z_lt_mul a b c ab c_pos). rewrite eqacbc in acbc.\n    apply z_lt_total_strict_ordering in acbc as bcac. contradiction.\n  + destruct ba as [ba|eqab]. \n    * pose (bcac:= z_lt_mul b a c ba c_pos). rewrite eqacbc in bcac.\n      apply z_lt_total_strict_ordering in bcac as acbc. contradiction.\n    * apply eqab. \n- destruct c_neg as [c_neg|c0].\n  + apply proj1 in eqacbc. set (nc := z_neg c). apply z_lt_neg in c_neg. simpl z_neg in c_neg.\n    replace c with (z_neg (z_neg c)) in eqacbc.\n    rewrite z_mul_neg in eqacbc. rewrite z_mul_neg with (a:=b) in eqacbc.\n    apply z_eq_neg in eqacbc.\n    destruct (total a b) as [ab|ba].\n    * pose (acbc:= z_lt_mul a b (-z c) ab c_neg). rewrite eqacbc in acbc.\n      apply z_lt_total_strict_ordering in acbc as bcac. contradiction.\n    * destruct ba as [ba|eqab]. \n      --  pose (bcac:= z_lt_mul b a (-z c) ba c_neg). rewrite eqacbc in bcac.\n          apply z_lt_total_strict_ordering in bcac as acbc. contradiction.\n      -- apply eqab.\n    * destruct c. reflexivity.\n  + apply proj2 in eqacbc. apply eq_sym in c0. contradiction.\nQed.\n\nTheorem z_mul_a_b_zero : forall (a b : Z),\n  a *z b = z_0 <-> a = z_0 \\/ b = z_0.\nProof.\nintros. unfold iff. apply conj. \n- destruct (law_of_excluded_middle (b=z_0)).\n  + right. apply H.\n  + left. apply z_mul_cancel with (c:=b). apply conj.\n    * rewrite H0. rewrite z_mul_comm. rewrite z_mul_zero. reflexivity.\n    * apply H.\n- intros. destruct H as [a0|b0].\n  + rewrite a0. destruct b. apply z_eq. reflexivity.\n  + rewrite b0. destruct a. apply z_eq. rewrite n_mul_zero. rewrite n_mul_zero. reflexivity.\nQed.\n\nTheorem z_mul_a_b_nonzero : forall (a b : Z),\n  a <> z_0 -> b <> z_0 -> a *z b <> z_0.\nProof.\nintros a b an0 bn0. intros ab0. apply z_mul_a_b_zero in ab0. destruct ab0 as [a0|b0].\napply an0 in a0. contradiction. apply bn0 in b0. contradiction.\nQed.\n\nTheorem z_mul_a_b_nonzero2 : forall (a b : Z),\n  a *z b <> z_0 -> a <> z_0 /\\ b <> z_0.\nProof.\nintros. apply conj.\n- intro. rewrite H0 in H. destruct b. simpl in H. contradiction.\n- intro. rewrite H0 in H. destruct a. rewrite z_mul_comm in H. simpl in H. contradiction.\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/Integer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6590869913856033}}
{"text": "Load Coq_book_ontology.\n(** Dealing with multidimensional adjectives. Health as an inductive type\n where  the dimensions are enumerated. This is just an enumerated type*)\nDefinition   Degree:= Set. \nInductive Health: Degree:= Heart|Blood|Cholesterol.\nParameter Healthy: Health->Human->Prop.\nDefinition sick:=fun y : Human => ~ (forall x : Health, Healthy x y).\nDefinition healthy:= fun y : Human => forall x : Health, Healthy x y.\n\nTheorem HEALTHY:\n    healthy John -> Healthy Heart John /\\ Healthy Blood John\n    /\\ Healthy Cholesterol John.\n    cbv. intros. split. apply H.\n    split. apply H. apply H. Qed.\n\nTheorem HEALTHY2:\n    healthy John -> not (sick John).\n    cbv. firstorder. Qed.\n\nTheorem HEALTHY3:\n    (exists x: Health, Healthy x John) -> healthy John.\n    cbv. firstorder. Abort.\n\nTheorem HEALTHY4:\n    (exists x: Health, not (Healthy x John)) -> healthy John.\n    cbv. firstorder. Abort.\n\nTheorem HEALTHY5:  \n    (exists x: Health, not (Healthy x John))  -> sick John.\n  cbv. firstorder.  Qed.\n\nInductive art: Degree:= a1|a2|a3|a4.\nParameter F: art -> nat. \nDefinition DIM_CN := fun  h: Human => fun a: art => F a.\nParameter STND_art: nat. \nRecord Artist: Set:= mkartist{h:> Human; EI :  forall a: art, gt (DIM_CN h a) STND_art }.", "meta": {"author": "StergiosCha", "repo": "MTT-semantics_book", "sha": "126a573fdb1a2b687b1f64bf029b7fa2493bd32b", "save_path": "github-repos/coq/StergiosCha-MTT-semantics_book", "path": "github-repos/coq/StergiosCha-MTT-semantics_book/MTT-semantics_book-126a573fdb1a2b687b1f64bf029b7fa2493bd32b/Book_Multi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464115, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6590603163780508}}
{"text": "From Coqprime Require Import PocklingtonRefl.\n\nLocal Open Scope positive_scope.\n\nLemma primo42 : prime 6701029.\nProof.\n apply (Pocklington_refl\n         (Pock_certif 6701029 2 ((127, 1)::(2,2)::nil) 998)\n        ((Proof_certif 127 prime127) ::\n         (Proof_certif 2 prime2) ::\n          nil)).\n native_cast_no_check (refl_equal true).\nQed.\n\n", "meta": {"author": "mukeshtiwari", "repo": "Formally_Verified_Verifiable_Group_Generator", "sha": "e80e8d43e81b5201d6ab82a8ebc07a5cef03476b", "save_path": "github-repos/coq/mukeshtiwari-Formally_Verified_Verifiable_Group_Generator", "path": "github-repos/coq/mukeshtiwari-Formally_Verified_Verifiable_Group_Generator/Formally_Verified_Verifiable_Group_Generator-e80e8d43e81b5201d6ab82a8ebc07a5cef03476b/primality/p1_42.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.6589785476114715}}
{"text": "Lemma L1 : forall (X Y:Prop), ~~(X -> Y) <-> (~~X -> ~~Y).\nProof.\n    intros X Y. split; intros H1 H2.\n    - intros H3. apply H1. intros H4. apply H2. intros H5.\n      apply H3, H4. assumption.\n    - assert (~Y) as H3.\n        { intros H3. apply H2. intros H4. assumption. }\n      apply H2. intros H4. exfalso. apply H1.\n            + intro H5. apply H5. assumption.\n            + assumption.\nQed. \n\n\nLemma L2 : forall (X Y:Prop), ~~(X /\\ Y) <-> ~~X /\\ ~~Y.\nProof.\n    intros  X Y. split.\n    - intros H1. split; intros H2; \n      apply H1; intros [H3 H4]; apply H2; assumption.\n    - intros [H1 H2] H3. apply H1. intros H4. apply H2. intros H5.\n      apply H3. split; assumption.\nQed.\n\nLemma L3 : ~~True <-> True.\nProof.\n    split; intros H1.\n    - trivial.\n    - intros H2. apply H2. trivial.\nQed.\n\n\nLemma L4 : ~~False <-> False.\nProof.\n    split; intros H1.\n    - apply H1. intros H2. contradiction.\n    - contradiction.\nQed.\n\nLemma L5 : forall (X Y:Prop), ~(X /\\ Y) <-> ~~(~X \\/ ~Y).\nProof.\n    intros X Y. split; intros H1.\n    - intros H2. \n      assert (~~X) as H3. { intros H3. apply H2. left. assumption. }\n      assert (~~Y) as H4. { intros H4. apply H2. right. assumption. }\n      apply H3. intros H5. apply H4. intros H6. apply H1. split; assumption.\n    - intros [H2 H3]. apply H1. intros [H4|H4]; apply H4; assumption.\nQed.\n\nLemma L6 : forall (X Y:Prop), (~X -> ~Y) <-> ~~(Y -> X).\nProof.\n    intros X Y. split; intros H1 H2.\n    - assert (~X) as H3. { intros H3. apply H2. intros H4. assumption. }\n      assert (~~Y) as H4. \n        { intros H4. apply H2. intros H5. exfalso. apply H4. assumption. }\n      apply H4, H1, H3.\n    - intros H3. apply H1. intros H4. apply H2, H4, H3.\nQed.\n\n\nLemma L7 : forall (X Y:Prop), (~X -> ~Y) <-> (Y -> ~~X).\nProof.\n    intros X Y. split; intros H1 H2 H3; apply H1; assumption.\nQed.\n\nLemma L8 : forall (X Y:Prop), (X -> Y) -> ~~(~X \\/ Y).\nProof.\n    intros X Y H1 H2. \n    assert (~Y) as H3. { intros H3. apply H2. right. assumption. }\n    assert (~~X) as H4. {intros H4. apply H2. left. assumption. }\n    assert (~X) as H5. { intros H5. apply H3, H1. assumption. }\n    apply H4. assumption.\nQed.\n\n\nLemma L9 : forall (a:Type) (p:a -> Prop), \n    ~(forall (x:a), ~p x) <-> ~~ exists (x:a), p x.\nProof.\n    intros a p. split; intros H1 H2; apply H1.\n    - intros x H3. apply H2. exists x. assumption.\n    - intros [x H3]. apply (H2 x). assumption.\nQed.\n\nLemma L10 : forall (X Y:Prop), ~~X \\/ ~~Y -> ~~(X \\/ Y).\nProof.\n    intros X Y [H1|H1] H2; apply H1; intros H3; apply H2.\n    - left. assumption.\n    - right. assumption.\nQed.\n\nLemma L11 : forall (a:Type) (p:a -> Prop), \n    (exists (x:a), ~~ p x) -> ~~ exists (x:a), p x.\nProof.\n    intros a p [x H1] H2. apply H1. intros H3. apply H2. exists x. assumption.\nQed.\n\nLemma L12 : forall (a:Type) (p:a -> Prop), \n    ~~(forall (x:a), p x) -> forall (x:a), ~~ p x.\nProof.\n    intros a p H1 x H2. apply H1. intros H3. apply H2, H3.\nQed.\n\n(* Coq meta-property not provable in Coq: The double negation of a quantifier   *)\n(* free proposition which is provable using LEM, is provable.                   *)\n\n(* X \\/ ~X is provable using LEM, hence ...                                     *)\nLemma L13 : forall (X:Prop), ~~(X \\/ ~X).\nProof.\n    intros X H1.\n    assert (~X) as H2.  { intros H2. apply H1. left.  assumption. }\n    assert (~~X) as H3. { intros H3. apply H1. right. assumption. }\n    apply H3. assumption.\nQed.\n\n(* ~~X -> X is provable using LEM, hence...                                     *)\nLemma L14 : forall (X:Prop), ~~(~~X -> X).\nProof.\n    intros X H1. apply H1. intros H2. exfalso. apply H2. intros H3. apply H1.\n    intros H4. assumption.\nQed.\n\nLemma L15 : forall (X Y:Prop), ~~(~(X /\\ Y) -> ~X \\/ ~Y).\nProof.\n    intros X Y H1. apply H1. intros H2. \n    assert (~~X) as H3. { intros H3. apply H1. intros H4. left.  assumption. }\n    assert (~~Y) as H4. { intros H4. apply H1. intros H5. right. assumption. }\n    exfalso. apply H3. intros H5. apply H4. intro H6. apply H2. \n    split; assumption.\nQed.\n\n\nLemma L16 : forall (X Y:Prop), ~~((~X -> ~Y) -> Y -> X).\nProof.\n    intros X Y H1. apply H1. intros H2 H3. exfalso. apply H2. \n    - intros H4. apply H1. intros H5 H6. assumption.\n    - assumption.\nQed.\n\nLemma L17 : forall (X Y:Prop), ~~(((X -> Y) -> X) -> X).\nProof.\n    intros X Y H1. apply H1. intros H2.\n    assert (~X) as H3. { intros H3. apply H1. intros H4. assumption. }\n    apply H2. intros H4. exfalso. apply H3. assumption.\nQed.\n\n\nLemma L18 : forall (X Y:Prop), ~~((X -> Y) -> ~X \\/ Y).\nProof.\n    intros X Y H1. apply H1. intros H2.\n    assert (~(~X \\/ Y)) as H3. { intros H3. apply H1. intros H4. assumption. }\n    assert (~Y) as H4. {intros H4. apply H3. right. assumption. }\n    assert (~~X) as H5. { intros H5. apply H3. left. assumption. }\n    exfalso. apply H5. intros H6. apply H4, H2. assumption.\nQed.\n\nLemma L19 : forall (X Y:Prop), ~~((X -> Y) \\/ (Y -> X)).\nProof.\n    intros X Y H1. apply H1.\n    assert (~(X -> Y)) as H2. { intros H2. apply H1. left. assumption. }\n    assert (~(Y -> X)) as H3. { intros H3. apply H1. right. assumption. }\n    assert (~X) as H4. { intros H4. apply H3. intros H5. assumption. }\n    exfalso. apply H2. intros H5. exfalso. apply H4. 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/cttwc/doubleNeg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256591565729, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6588653572416739}}
{"text": "(** **** Exercise: (some_term_is_stuck)  *)\nExample some_term_is_stuck :\n  exists t, stuck t.\nProof.\n  exists (tsucc ttrue). unfold stuck. split.\n  - unfold step_normal_form, not. intros. inversion H.\n    inversion H0. inversion H2.\n  - unfold not, value. intros [A | B].\n    inversion A. inversion B. inversion H0.\nQed.\n\n(** **** Exercise: (value_is_nf)  *)\nLemma value_is_nf : forall t,\n  value t -> step_normal_form t.\nProof.\n  unfold normal_form. unfold not. intros. destruct H0.\n  generalize dependent x.\n  induction t; intros; try solve_by_invert;\n  try (solve_by_invert 2);\n  try (inversion H; try solve_by_invert; inversion H1; subst;\n  inversion H0; subst; eauto).\nQed.\n\n(** **** Exercise: (succ_hastype_nat__hastype_nat)  *)\nExample succ_hastype_nat__hastype_nat : forall t,\n  |- tsucc t \\in TNat ->\n  |- t \\in TNat.\nProof.\n  intros. inversion H. assumption.\nQed.\n\n\n(** **** Exercise: (finish_progress)  *)\n(** Complete the formal proof of the [progress] property.  (Make sure\n    you understand the informal proof fragment in the following\n    exercise before starting -- this will save you a lot of time.) *)\n\nTheorem progress : forall t T,\n  |- t \\in T ->\n  value t \\/ exists t', t ==> t'.\nProof with auto.\n  intros t T HT.\n  induction HT; auto.\n  (* The cases that were obviously values, like T_True and\n     T_False, were eliminated immediately by auto *)\n  - (* T_If *)\n    right. inversion IHHT1; clear IHHT1.\n    + (* t1 is a value *)\n    apply (bool_canonical t1 HT1) in H.\n    inversion H; subst; clear H.\n      exists t2. apply ST_IfTrue.\n      exists t3. apply ST_IfFalse.\n    + (* t1 can take a step *)\n      inversion H as [t1' H1].\n      exists (tif t1' t2 t3). apply ST_If with (t2:=t2) (t3 := t3) in H1 . \n      assumption.\n  - (* T_Succ *) destruct IHHT.\n    left. right. constructor.\n     + apply (nat_canonical t1 HT) in H. auto.\n     + right. inversion H. exists (tsucc x). apply ST_Succ in H0.\n        assumption.\n  - (* T_Pred *)\n    destruct IHHT.\n    + right.\n    apply (nat_canonical t1 HT) in H. \n    inversion H. exists tzero. apply ST_PredZero. \n    exists t. apply ST_PredSucc. assumption.\n    + right. inversion H. exists (tpred x). apply ST_Pred in H0. assumption.\n  - (* T_Zero *)\n    destruct IHHT.\n    + right. apply (nat_canonical t1 HT) in H. inversion H.\n    exists ttrue. apply ST_IszeroZero. \n    exists tfalse. apply ST_IszeroSucc. assumption.\n    + right.\n    destruct H. exists (tiszero x). apply ST_Iszero. assumption.\nQed.\n\nTheorem preservation : forall t t' T,\n  |- t \\in T ->\n  t ==> t' ->\n  |- t' \\in T.\n\n(** **** Exercise: (finish_preservation)  *)\n(** Complete the formal proof of the [preservation] property.  (Again,\n    make sure you understand the informal proof fragment in the\n    following exercise first.) *)\n\nProof with auto.\n  intros t t' T HT HE.\n  generalize dependent t'.\n  induction HT;\n         (* every case needs to introduce a couple of things *)\n         intros t' HE;\n         (* and we can deal with several impossible\n            cases all at once *)\n         try solve_by_invert.\n    - (* T_If *) inversion HE; subst; clear HE.\n      + (* ST_IFTrue *) assumption.\n      + (* ST_IfFalse *) assumption.\n      + (* ST_If *) apply T_If; try assumption.\n        apply IHHT1; assumption.\n    - (* T_Succ *) inversion HE; subst; clear HE. \n      apply T_Succ. apply IHHT. assumption.\n    - (* T_Pred *) inversion HE; subst; clear HE.\n      + assumption.\n      + apply succ_hastype_nat__hastype_nat in HT. assumption.\n      + apply IHHT in H0. apply T_Pred in H0. assumption.\n    - (* T_Bool *) inversion HE; subst; clear HE; constructor.\n      apply IHHT in H0. assumption.\nQed.\n\n(** **** Exercise: (normalize_ex)  *)\nTheorem normalize_ex : exists e',\n  (AMult (ANum 3) (AMult (ANum 2) (ANum 1))) / empty_state\n  ==>a* e'.\nProof.\n  eapply ex_intro. normalize. Qed.\n  \n(** **** Exercise: (normalize_ex')  *)\n(** For comparison, prove it using [apply] instead of [eapply]. *)\n\nTheorem normalize_ex' : exists e',\n  (AMult (ANum 3) (AMult (ANum 2) (ANum 1))) / empty_state\n  ==>a* e'.\nProof.\n  eapply ex_intro. normalize. \nQed.\n\n", "meta": {"author": "mm04", "repo": "Ejercicios-Coq-tfg", "sha": "0ee5b9195b749fe458653d67549df399afc9c87d", "save_path": "github-repos/coq/mm04-Ejercicios-Coq-tfg", "path": "github-repos/coq/mm04-Ejercicios-Coq-tfg/Ejercicios-Coq-tfg-0ee5b9195b749fe458653d67549df399afc9c87d/types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.658865349868229}}
{"text": "Require Import XR_R.\nRequire Import XR_Rsqr.\nRequire Import XR_Rsqr_neg.\nRequire Import XR_Rabs.\nRequire Import XR_Rcase_abs.\n\nLocal Open Scope R_scope.\n\nLemma Rsqr_abs : forall x:R, Rsqr x = Rsqr (Rabs x).\nProof.\n  intro x.\n  unfold Rabs.\n  destruct (Rcase_abs x) as [ h | h ].\n  {\n  rewrite <- Rsqr_neg.\n  reflexivity.\n  }\n  { reflexivity. }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rsqr_abs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6588653393889171}}
{"text": "(*=========================================================================\n  Setup & Sorting\n*)\n\n\nRequire Import Coq.Structures.Orders.\nRequire Import Coq.Sorting.Sorting.\nRequire Import Orders.\nRequire Import Sorting.\nRequire Import Sorted.\nRequire Import Sorting.Mergesort.\nRequire Import Coq.Init.Nat.\nRequire Import Arith.\nRequire Import Omega.\nRequire Export List.\n\n(* From Coq.Structures.Orders. *)\nLocal Coercion is_true : bool >-> Sortclass.\nHint Unfold is_true.\n\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y) \n                     (at level 60, right associativity).\n\n\n(* From Coq.Sorting.Mergesort NatOrder example. Highest priority is 0. *)\nModule PriorityOrder <: TotalLeBool.\n  Definition t := nat.\n  Fixpoint leb x y :=\n    match x, y with\n    | 0, _ => true\n    | _, 0 => false\n    | S x', S y' => leb x' y'\n    end.\n  (*Infix \"<=?\" := leb (at level 35).*)\n  Theorem leb_total : forall a1 a2, a1 <=? a2 \\/ a2 <=? a1.\n  Proof. induction a1; destruct a2; simpl; auto. Qed.\nEnd PriorityOrder.\nModule Import PrioritySort := Sort PriorityOrder. \n\n(*Compute (Sorted leb [ 1 :: 2 :: 3 ]).\nCompute (Sorted PointOrderByX_le [p1;p2;p3;p4;p5]).*)\n\n\n(*Example test_not_Sorted : Sorted leb [2; 1; 3] -> False.\nProof.\n  (* Name the hypothesis on the left side of \"->\" and break Sorted down by cases. *)\n  intros contra. inversion contra.\n\n  (* Look for an obviously false hypothesis, break it down, and repeat. *)\n  repeat match goal with\n    | [ H : HdRel _ 2 [1; 3] |- False ] => inversion_clear H\n    | [ H : is_true (2 <=? 1) |- False ] => inversion_clear H\n  end.\nQed.*)\n\n\n(*=========================================================================\n  Theorems about inequality\n\n  Much of this machinery exists to translate between boolean expressions\n  like `leb a b` and logical propositions like `a <= b`.\n*)\n\n(* Deal with implications of the form `ObviouslyFalse -> P` by introducting\n  `ObviouslyFalse` as a hypotheses and inverting it. There's probably a\n  built-in which does this, but I can't find it. *)\nLtac antecedent_is_false :=\n  (* Use solve to make sure we either prove our goal completely, or fail\n     atomically and leave the hypotheses unchanged. *)\n  solve [ intros contra; inversion contra ].\n\nTheorem leb_true : forall n m,\n  n <=? m = true -> n <= m.\nProof.\n  (* Dispose of most cases mechanically using built-in hypotheses. *)\n  induction n; destruct m; simpl; auto using le_0_n, le_n_S.\n  (* The remaining case is an obvious contradiction. *)\n  antecedent_is_false.\nQed.\n\nTheorem le_implies_leb_true : forall n m, n <= m -> n <=? m.\nProof.\n  induction n; destruct m; simpl; auto using le_S_n.\n  antecedent_is_false.\nQed.\n\n(* Alternate: https://github.com/timjb/software-foundations/blob/master/Logic.v\n   This gave me the hint to induct on m. *)\nTheorem leb_false : forall n m,\n  n <=? m = false -> ~(n <= m).\nProof.\n  intros n m. generalize dependent n.\n  (* Give the pattern of our proof, and simplify. *)\n  induction m; destruct n; simpl;\n    (* Eliminate cases with obvious contractions. *)\n    try antecedent_is_false.\n auto using le_Sn_0.\n     (* Use our induction hypothesis to rewrite the left-hand side,\n        then use omega for logic crunching. *)\n    intros H_not_leq_n_m. apply IHm in H_not_leq_n_m. omega.\nQed.\n\n(* As a general rule, we can solve any trivial theorem about inequalities using\n   the omega tactic. *)\nLemma flip_not_le : forall (a b : nat), not (a <= b) -> b <= a.\nProof. intros. omega. Qed.\n\n(* This is somewhat specific (and deliberately weak) lemma that turns\n   up a lot in our main proof. *)\nLemma flip_not_leb : forall (a b : nat), (a <=? b) = false -> b <=? a.\nProof.\n  intros. apply leb_false in H. apply flip_not_le in H.\n  apply le_implies_leb_true. assumption.\nQed.\n\n\n(*=========================================================================\n  Insertion\n*)\n\nFixpoint insert_sorted (n : nat) (l : list nat) : list nat :=\n  match l with\n    | [] => [n]\n    | n' :: l' =>\n      if n <=? n'\n      then n :: l\n      else n' :: insert_sorted n l'\n  end.\n\n(* It's worth writing unit tests before trying to prove something really\n   complicated, because doing so will make basic failures obvious, and\n   you won't watch a proof fall apart mysteriously on some subclause. *)\n(*Example test_insert_3_1_2 :\n  insert_sorted 2 (insert_sorted 1 (insert_sorted 3 [])) = [1:: 2:: 3].\nProof. reflexivity. Qed.\n\nExample test_insert_2_1_3 :\n  insert_sorted 3 (insert_sorted 1 (insert_sorted 2 [])) = [1; 2; 3].\nProof. reflexivity. Qed.\n\nExample test_insert_2_1_1 :\n  insert_sorted 1 (insert_sorted 1 (insert_sorted 2 [])) = [1; 1; 2].\nProof. reflexivity. Qed. *)\n\n\n(*=========================================================================\n  Proof: Insertion preserves sorting\n*)\n\nHint Resolve flip_not_leb.\nHint Constructors Sorted.\nHint Constructors HdRel.\n\nTheorem insert_sorted_stays_sorted : forall n l,\n  Sorted leb l -> Sorted leb (insert_sorted n l).\nProof.\n  intros n l H_sorted_l.\n  induction l as [|n' l']; simpl; auto.\n (*  Case \"l = n' :: l'\". *)\n    destruct (n <=? n') eqn:H_n_le_n'; auto.\n    (* SCase \"n <=? n' = false\". *)\n      apply Sorted_inv in H_sorted_l.\n      inversion H_sorted_l as [H_sorted_l' HdRel_n'_l'].\n\n      apply Sorted_cons.\n     (*  SSCase \"Sorted (insert_sorted n l')\".  *)apply IHl'. auto.\n      (* SSCase \"HdRel n' (insert_sorted n l')\". *)\n        apply IHl' in H_sorted_l'.\n        destruct l'; simpl; auto.\n        destruct (n <=? n0); auto.\n        inversion HdRel_n'_l'. auto.\nQed.\n\n\n(*=========================================================================\n  Generating Haskell code\n*)\n\nExtraction Language Haskell.\nExtract Inductive list => \"([])\" [ \"[]\" \"(:)\" ].\nExtract Inductive bool => \"Bool\" [ \"True\" \"False\" ].\nExtract Inductive nat => \"Int\" [\"0\" \"(1+)\"].\nExtraction insert_sorted.\n\n(*\n\nHaskell supporting bits.\n\nleb :: Int -> Int -> Bool\nleb = (<=)\n\nmain :: IO () \nmain = do\n  print $ insert_sorted 5 (insert_sorted 3 [])\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/SortedList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6588653312330274}}
{"text": "From mathcomp Require Import ssreflect ssrnat ssrbool.\nSet Bullet Behavior \"Strict Subproofs\".\n\nFrom MonadicEffect Require Import Trees.\n\n(** * Extrinsic and Intrinsic Proofs\n\n    There are two types of proofs: _extrinsic_ ones and _intrisic_\n    ones. An extrinsic proof is what most people familiar with in Coq:\n    you write down a function, and then prove some properties about\n    it. In a intrinsic proof, however, you write the properties in the\n    type of the function.\n\n    Let's just jump into an example to show what they look like. We\n    start with the more familiar extrinsic approach. *)\n\nSection ExtrinsicProof.\n\n  Variable A : Set.\n\n  (** We import state monads from coq-ext-lib. *)\n  From ExtLib Require Import Structures.Monads Data.Monads.StateMonad.\n  Import MonadNotation.\n  Local Open Scope monad_scope.\n\n  (** Consider the following [relabel] function. It labels all leaves\n      in a tree in with [nat]s in an increasing order. It maintains a\n      counter using the state monad. *)\n  Fixpoint relabel (t : Tree A) : state nat (Tree nat) :=\n    match t with\n    | Leaf x =>\n      n <- get ;;\n      put (n + 1) ;;\n      ret (Leaf n)\n    | Node l r =>\n      l' <- relabel l ;;\n      r' <- relabel r ;;\n      ret (Node l' r')\n    end.\n\n  (** Now we can write down a specification of this function and prove\n      it. *)\n  Theorem relabel_spec : forall t s,\n      let: (t', s') := runState (relabel t) s in\n      s' = s + size t' /\\ flatten t' = seq s (size t').\n  Proof.\n    (** The proof starts by doing induction on the tree. The [Leaf]\n        case is trivial, and can be dischagred automatically. *)\n    elim => // => l IHt1 r IHt2 s.\n    (** In the [Node] case, we do some rewriting to expose the\n        computation on left and right children, so we can use our\n        induction hypotheses. *)\n    rewrite /relabel /= -/relabel.\n    (** Now we need a bit boilerplates to destruct the [let]s\n        generated from [bind]s, and pass the states through. *)\n    specialize (IHt1 s). \n    destruct (runState (relabel l) s) as [t' s'].\n    specialize (IHt2 s').\n    destruct (runState (relabel r) s') as [t'' s''].\n    split => /=; intuition; subst.\n    - by rewrite addnA.\n    - by rewrite H0 H2 seq_split.\n  Qed.\nEnd ExtrinsicProof.\n  (** The proof is quite standard. There are a bit boilerplates with\n      [bind]s. Can we make use of the monadic structure to propagate\n      the proof?\n\n      The intrinsic approach offers one solution to that. Let's see\n      how we prove the same thing in that style. *)\n\n(* begin hide *)\nReset ExtrinsicProof.\n(* end hide *)\nSection IntrinsicProof.\n\n  Variable A : Set.\n\n  (** Here we use something called [Dijkstra] monads we have already\n      defined. We will show to define it later. *)\n  From MonadicEffect Require Import Dijkstra.\n\n  (** This time, we enhance the type of the [relabel] function, by\n      putting a pre- and post-condition in its type. By using the\n      [Program] feature provided by Coq, we can define this function\n      with the function body exactly the same as before. One\n      difference is that now Coq will ask us to prove that the result\n      of this function indeed satisfies the post-condition. *)\n  Program Fixpoint relabel {A : Set} (t : Tree A) :\n    ST nat return (Tree nat)\n         requires [fun _ => True]\n         ensures  [fun s t s' => s' = s + size t /\\ flatten t = seq s (size t)] :=\n  match t with\n  | Leaf x =>\n    n <- get ;;\n    put (n + 1) ;;\n    ret (Leaf n)\n  | Node l r =>\n    l' <- relabel l ;;\n    r' <- relabel r ;;\n    ret (Node l' r')\n  end.\n  (** Coq will try to automatically prove some simple proof\n      obligations for us. For this function, the case when [t] is a\n      [Leaf] is trivial, so Coq has already proved it for us.\n      \n      We only need to consider the case when [t] is a [Node]. The\n      proof is quite similar to the last part of the extrinsic\n      proof. *)\n  Next Obligation.\n    repeat split => //.\n    intros; destruct H0; destruct H; subst.\n    apply x1. split => /=. \n    - by rewrite addnA.\n    - by rewrite H2 H1 seq_split.\n  Defined.\nEnd IntrinsicProof.\n\n(* begin hide *)\nReset IntrinsicProof.\n(* end hide *)\n(** * Intrinsic Proofs in Coq\n\n    Before we jump into the details how the above example is\n    implemented in Coq, let's check a little bit technical details in\n    Coq. *)\nSection IntrinsicProof.\n\n  Fail Definition sqr (x : nat) : { s : nat | s = x * x } :=\n    x * x.\n\n  Print sig.\n\n(** The signature of subset types:\n<<\nInductive sig (A : Type) (P : A -> Prop) : Type :=\n    exist : forall x : A, P x -> {x : A | P x}\n\nFor sig: Argument A is implicit\nFor exist: Argument A is implicit\nFor sig: Argument scopes are [type_scope type_scope]\nFor exist: Argument scopes are [type_scope function_scope _ _] \n>> *)\n\n  Definition sqr (x : nat) : { s : nat | s = x * x } :=\n    exist (fun s => s = x * x) (x * x) eq_refl.\n\n  Reset sqr.\n\n  Definition sqr (x : nat) : { s : nat | s = x * x }.\n    refine (exist _ (x * x) _).\n    reflexivity.\n  Defined.\n\n  Reset sqr.\n\n  (** Coq's [Program] feature allows us to program with subset types\n      without worrying about passing the proof objects. *)\n  Program Definition sqr (x : nat) : { s : nat | s = x * x } := x * x.\n\nEnd IntrinsicProof.\n\n(* begin hide *)\nReset IntrinsicProof.\n(* end hide *)\nRequire Import Program.\n\n(** * The Hoare State Monad\n\n    Most of this section is based on [Swierstra, W. (2009). A Hoare\n    Logic for the State Monad]. *)\n\nSection HoareStateMonads.\n\n  Variable S : Set.\n  \n  Definition Pre : Type := S -> Prop.\n  Definition Post (A : Set) : Type := S -> A -> S -> Prop.\n  \n  Program Definition HoareState (pre : Pre) (A : Set) (post : Post A) : Set :=\n    forall s: { s : S | pre s }, { (a, s') : A * S | post s a s' }.\n\n  Definition top : Pre := fun _ => True.\n\n  (** Recall the type of [ret] for an ordinary state monad is\n\n      <<\n      A -> state S A\n      >> *)\n  Program Definition ret (A : Set) :\n    forall a, HoareState top A (fun s a' s' => s = s' /\\ a = a') :=\n    fun a s => (a, s).\n\n  (** Recall the type of [bind] for an ordinary state monad is\n\n      << state S A -> (A -> state S B) -> state S B >>\n      \n      Note the use of dependent type in our second parameter\n      below. The reason is that we would like to refer to [a] in the\n      pre- and post-conditions of the second parametr!  *)\n  Program Definition bind : forall A B P1 P2 Q1 Q2,\n      HoareState P1 A Q1 ->\n      (forall (a : A), HoareState (P2 a) B (Q2 a)) ->\n      HoareState (fun s1 => P1 s1 /\\ forall a s2, Q1 s1 a s2 -> P2 a s2)\n                  B\n                  (fun s1 b s3 => exists a, exists s2, Q1 s1 a s2 /\\ Q2 a s2 b s3) :=\n    fun A B P1 P2 Q1 Q2 m1 m2 s1 =>\n      let: (a, s2) := m1 s1 in m2 a s2.\n  Next Obligation.\n    (** The first obligation is proving that [a] and [s2] satisfies\n        the precontion of [m2]. *)\n    elim: m1 Heq_anonymous => t /= H0 Heq_anonymous.\n    subst. by apply p0.\n  Defined.\n  Next Obligation.\n    (** The second obligation is proving that [m2 a s2] satisfies the\n        post condition of [bind]. *)\n    elim (m2 a) => /=. elim => a' s3 H.\n    exists a. exists s2. split; auto.\n    elim: m1 Heq_anonymous => t /= H0 Heq_anonymous.\n    subst. by apply H0.\n  Defined.\n\n  (** [get] and [put] are straightforward. *)\n  Program Definition get : HoareState top S (fun s a s' => s = s' /\\ a = s) :=\n    fun s => (s, s).\n  Program Definition put (x : S) : HoareState top unit (fun _ _ s' => x = s') :=\n    fun _ => (tt, x).\nEnd HoareStateMonads.\n\n(* begin hide *)\nArguments ret {S} {A}.\nArguments bind {S} {A} {B} {P1} {P2} {Q1} {Q2}.\nArguments get {S}.\nArguments put {S}.\n(* end hide *)\n(** We define some notations to use this monad more easily. *)\nNotation \"c >>= f\" := (bind c f) (at level 50, left associativity).\nNotation \"f =<< c\" := (bind c f) (at level 51, right associativity).\nNotation \"x <- c1 ;; c2\" := (bind c1 (fun x => c2)) (at level 100, c1 at next level, right associativity).\nNotation \"e1 ;; e2\" := (_ <- e1 ;; e2) (at level 100, right associativity).\n\n(** Now we can do an intrinsic proof to show that our [relabel]\n    function is correct with respect to its specification again. *)\nProgram Fixpoint relabel {A : Set} (t : Tree A) :\n  HoareState nat\n             (@top nat)\n             (Tree nat) \n             (fun i t f => f = i + size t /\\ flatten t = seq i (size t)) :=\n  match t with\n  | Leaf x =>\n    n <- get ;;\n    put (n + 1) ;;\n    ret (Leaf n)\n  | Node l r =>\n    l' <- relabel l ;;\n    r' <- relabel r ;;\n    ret (Node l' r')\n  end.\nNext Obligation.\n  case (relabel A l >>= _) => /=.\n  case=> a s' [a1] [s1] [[H0 H1] H2].\n  case: H2 => a2 [s2] [[H3 H4] [H5 H6]].  \n  subst. split => /=.\n  - by rewrite addnA.\n  - by rewrite H1 H4 seq_split.\nDefined.\n\n(** * Dijkstra Monads\n\n    The Hoare state monad we have implemented have a few\n    disadvantages, according to [Swamy, N., Weinberger, J.,\n    Schlesinger, C., Chen, J., & Livshits, B. (2013). Verifying\n    higher-order programs with the dijkstra monad]:\n\n    - There are some existential quantifiers in it. Reasoning with\n      these quantifiers, particularly using automated SMT solvers, can\n      be problematic.\n\n    - It requires the post-condition to be a two-state relation,\n      though sometimes it is not necessary to compare the two states\n      in the specification.\n\n    Therefore, they propose another monad called \"Dijkstra monad\" to\n    resolve the above issues (name after Edsger W. Dijkstra, for his\n    discoveries in his paper [Dijkstra, E. W. (1975). Guarded\n    Commands, Nondeterminacy and Formal Derivation of Programs].\n\n    A Dijkstra monad is parameterized over a weakest precondition\n    transformer. It can be seen as a Hoare state monad: *)\n\nDefinition DST S A wp :=\n  forall p, HoareState S (fun h => wp p h) A (fun h x h' => p x h').\n\n(** But let's define it properly. *)\nReset HoareStateMonads.\n\nSection DijkstraMonads.\n\n  Variables S : Set.\n\n  (** The weakest precondition transformer. As its name suggested, it\n      takes a post-condition and transform it into the weakest\n      precondition. *)\n  Definition WP {A} : Type := (A -> S -> Prop) -> S -> Prop.\n\n  Program Definition DST A (wp : WP) :=\n    forall p, { s : S | wp p s } -> { (a, s') : A * S | p a s' }.\n\n  Program Definition ret { A } (a : A) :\n    DST A (fun p => p a) :=\n    fun _ s => (a, s).\n\n  Program Definition bind : forall A wp1 B wp2,\n      DST A wp1 -> (forall a : A, DST B (wp2 a)) ->\n      DST B (fun p => wp1 (fun a => wp2 a p)) :=\n    fun A wp1 B wp2 c1 c2 p s1 =>\n      (** The function body should be\n\n          <<\n          let: (a, s2) := c1 (fun a => wp2 a p) s1 in c2 a p s2.\n          >>\n          But we can also just write this: *)\n  let: (a, s2) := c1 _ s1 in c2 a _ s2.\n  Next Obligation.\n    elim: c1 Heq_anonymous => a' H' /= Heq_anonymous.\n    subst; done.\n  Defined.\n\n  Program Definition get : DST S (fun p s => p s s) :=\n    fun _ s => (s, s).\n\n  Program Definition put : forall s, DST unit (fun p _ => p tt s) :=\n    fun s _ _ => (tt, s).\n  \nEnd DijkstraMonads.\n\nArguments ret {S} {A}.\nArguments bind {S} {A} {wp1} {B} {wp2}.\nArguments get {S}.\nArguments put {S}.\n\nNotation \"c >>= f\" := (bind c f) (at level 50, left associativity).\nNotation \"f =<< c\" := (bind c f) (at level 51, right associativity).\nNotation \"x <- c1 ;; c2\" := (bind c1 (fun x => c2)) (at level 100, c1 at next level, right associativity).\nNotation \"e1 ;; e2\" := (_ <- e1 ;; e2) (at level 100, right associativity).\n\n(** Let's see how it works with our [relabel] function: *)\nProgram Fixpoint relabel {A : Set} (t : Tree A) :\n  DST nat (Tree nat) (fun post s =>\n                    forall t s', s' = s + size t /\\ flatten t = seq s (size t) ->\n                    post t s' ) :=\n  match t with\n  | Leaf x =>\n    n <- get ;;\n    put (n + 1) ;;\n    ret (Leaf n)\n  | Node l r =>\n    l' <- relabel l ;;\n    r' <- relabel r ;;\n    ret (Node l' r')\n  end.\nNext Obligation.\n  (** We show the function satisfies the post-condition. To do that,\n      we show that it satisfies the weakest precondition. *)\n  apply H3. split => /=.\n  - by rewrite addnA.\n  - by rewrite H2 H1 seq_split.\nDefined.\n\n(** Writing with weakest precondition transformer can sometimes be\n    hard. We can define some notations to make it more intuitive. *)\nReset relabel.\n\nNotation \"'ST' s 'return' a 'requires' [ P ] 'ensures' [ Q ]\" :=\n  (DST s a (fun p s1 => P s1 /\\ (forall c s2, Q s1 c s2 -> p c s2)))\n    (at level 99, P at next level, Q at next level).\n\nNotation \"'ST' s 'return' a 'ensures' [ Q ]\" :=\n  (DST s a (fun p s1 => forall c s2, Q s1 c s2 -> p c s2))\n    (at level 99, Q at next level).\n\nCheck (ST nat return (Tree nat) requires [fun _ => True] ensures [fun _ _ _ => True]).\n\n(** Now the specification for [relabel] looks quite similar to that in\n    the form of a Hoare state monad, but notice that the proof is\n    simpler than that for a Hoare state monad. *)\nProgram Fixpoint relabel {A : Set} (t : Tree A) :\n  ST nat return (Tree nat)\n       ensures  [fun i t f => f = i + size t /\\ flatten t = seq i (size t)] :=\nmatch t with\n| Leaf x =>\n  n <- get ;;\n  put (n + 1) ;;\n  ret (Leaf n)\n| Node l r =>\n  l' <- relabel l ;;\n  r' <- relabel r ;;\n  ret (Node l' r')\nend.\nNext Obligation.\n  apply H3. split => /=. \n  - by rewrite addnA.\n  - by rewrite H2 H1 seq_split.\nDefined.\n", "meta": {"author": "lastland", "repo": "MonadicReflection", "sha": "0b20a78601e23d2bf40631746a3742897bfb43ab", "save_path": "github-repos/coq/lastland-MonadicReflection", "path": "github-repos/coq/lastland-MonadicReflection/MonadicReflection-0b20a78601e23d2bf40631746a3742897bfb43ab/IntrinsicProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.6588118295847607}}
{"text": "Require Import SetoidClass.\nRequire Import Raxiom.\n\nModule Rconvenient (Import T : CReals).\n\nOpen Scope R_scope.\n\nSection Req.\n\n(** * Useful and basics results on <, ==, # *)\n\nLemma Req_sym : forall x y, Req x y -> Req y x.\nProof.\ncompute; intuition.\nQed.\n\nLemma Req_refl : forall r, Req r r.\nProof.\nintros r [H|H]; apply (Rlt_asym r r); apply H.\nQed.\n\nLemma Rlt_irrefl : forall r, r < r -> False.\nProof.\npose Rlt_asym; eauto.\nQed.\n\nLemma Rdiscr_irrefl : forall r, r ## r -> False.\nProof.\nintros ? [|]; eapply Rlt_irrefl; eauto.\nQed.\n\nLemma Req_trans : forall r1 r2 r3 : R, Req r1 r2 -> Req r2 r3 -> Req r1 r3.\nProof.\nintros r1 r2 r3 Hl Hr [H|H].\n eapply Req_lt_compat_l in H; [|eexact Hl].\n eapply Req_lt_compat_l in H; [|eexact Hr].\n apply (Rlt_irrefl _ H).\n\n eapply Req_lt_compat_l in H; [|apply Req_sym; eexact Hr].\n eapply Req_lt_compat_l in H; [|apply Req_sym; eexact Hl].\n apply (Rlt_irrefl _ H).\nQed.\n\nLemma Rlt_le_trans : forall x y z, Rlt x y -> Rle y z -> Rlt x z.\nProof.\nintros ? ? ? ? [|?].\n eapply Rlt_trans; eauto.\n eapply Req_lt_compat_r; eauto.\nQed.\n\nLemma Rle_lt_trans : forall x y z, Rle x y -> Rlt y z -> Rlt x z.\nProof.\nintros ? ? ? [?|].\n apply Rlt_trans; auto.\n intros; eapply Req_lt_compat_l.\n  apply Req_sym; eauto.\n  auto.\nQed.\n\nLemma Rle_trans : forall x y z, Rle x y -> Rle y z -> Rle x z.\nProof.\nintros x y z [xy|xy] [yz|yz].\n left; eapply Rlt_trans; eauto.\n left; eapply Req_lt_compat_r; eauto.\n left; eapply Req_lt_compat_l; eauto; apply Req_sym, xy.\n right; eapply Req_trans; eauto.\nQed.\n\n(** * Setoid **)\n\nGlobal Instance Equivalence_Req : Equivalence Req.\nProof.\nsplit; red.\n  apply Req_refl.\n  apply Req_sym.\n  apply Req_trans.\nQed.\n\nGlobal Instance Setoid_R : Setoid R := { equiv := Req }.\n\nEnd Req.\n\nLemma Radd_eq_compat_r : forall (x1 x2 y : R), Req x1 x2 -> Req (x1 + y) (x2 + y).\nProof.\nintros x1 x2 y Hx.\neapply Req_trans; [ apply Radd_comm | ].\neapply Req_trans; [ | apply Radd_comm ].\napply Radd_eq_compat_l; assumption.\nQed.\n\nLemma Rmul_eq_compat_r : forall x1 x2 y, Req x1 x2 -> Req (x1 * y) (x2 * y).\nProof.\nintros x1 x2 y Hx.\neapply Req_trans; [ apply Rmul_comm | ].\neapply Req_trans; [ | apply Rmul_comm ].\napply Rmul_eq_compat_l; assumption.\nQed.\n\nLemma Rmul_add_distr_r : forall x y z : R, Req ((x + y) * z) (x * z + y * z).\nProof.\nintros x y z.\netransitivity; [apply Rmul_comm|].\netransitivity; [|apply Radd_eq_compat_l; apply Rmul_comm].\netransitivity; [|apply Radd_eq_compat_r; apply Rmul_comm].\napply Rmul_add_distr_l.\nQed.\n\nInstance Proper_Req_add : Proper (Req ==> Req ==> Req) Radd.\nProof.\nintros x x' Hx y y' Hy.\neapply Req_trans.\n eapply Radd_eq_compat_l; eassumption.\n eapply Radd_eq_compat_r; eassumption.\nQed.\n\nInstance Proper_Req_mul : Proper (Req ==> Req ==> Req) Rmul.\nProof.\nintros x x' Hx y y' Hy.\neapply Req_trans.\n  eapply Rmul_eq_compat_l; eassumption.\n  eapply Rmul_eq_compat_r; eassumption.\nQed.\n\nLemma Radd_0_r : forall x, x + R0 == x.\nProof.\nintro.\nrewrite Radd_comm.\napply Radd_0_l.\nQed.\n\nLemma Radd_lt_compat_r : forall x y1 y2 : R, y1 < y2 -> y1 + x < y2 + x.\nProof.\nintros x a b ab.\neapply Req_lt_compat_l; try apply Radd_comm.\neapply Req_lt_compat_r; try apply Radd_comm.\napply Radd_lt_compat_l; auto.\nQed.\n\n\nLemma Radd_lt_compat : forall x1 x2 y1 y2 : R, x1 < x2 -> y1 < y2 -> x1 + y1 < x2 + y2.\nProof.\nintros.\neapply Rlt_trans.\n eapply Radd_lt_compat_l; eauto.\n eapply Radd_lt_compat_r; eauto.\nQed.\n\nLemma Radd_le_compat_l : forall x y1 y2 : R, y1 <= y2 -> x + y1 <= x + y2.\nProof.\n  intros x y1 y2 H. destruct H.\n   left. apply Radd_lt_compat_l. now assumption.\n   \n   right. apply Radd_eq_compat_l. assumption.\nQed.\n\nLemma Radd_le_compat_r : forall x y1 y2 : R, y1 <= y2 -> y1 + x <= y2 + x.\nProof.\n  intros x y1 y2 H. destruct H.\n   left. apply Radd_lt_compat_r. now assumption.\n   \n   right. apply Radd_eq_compat_r. assumption.\nQed.\n\nLemma Radd_lt_le_compat : forall x1 x2 y1 y2 : R, x1 < x2 -> y1 <= y2 -> x1 + y1 < x2 + y2.\nProof.\n  intros x1 x2 y1 y2 H1 H2. apply Rlt_le_trans with (x2 + y1).\n   apply Radd_lt_compat_r. now apply H1.\n   \n   apply Radd_le_compat_l. apply H2.\nQed.\n\nLemma Radd_le_lt_compat : forall x1 x2 y1 y2 : R, x1 <= x2 -> y1 < y2 -> x1 + y1 < x2 + y2.\nProof.\n  intros x1 x2 y1 y2 H1 H2. apply Rle_lt_trans with (x2 + y1).\n   apply Radd_le_compat_r. now apply H1.\n   \n   apply Radd_lt_compat_l. apply H2.\nQed.\n\nLemma Radd_le_compat : forall x1 x2 y1 y2 : R, x1 <= x2 -> y1 <= y2 -> x1 + y1 <= x2 + y2.\nProof.\n  intros x1 x2 y1 y2 H1 H2. apply Rle_trans with (x1 + y2).\n   apply Radd_le_compat_l. now apply H2.\n   \n   apply Radd_le_compat_r. apply H1.\nQed.\n\nLemma Rlt_0_2 : R0 < R1 + R1.\nProof.\napply Req_lt_compat_l with (R0 + R0); try apply Radd_0_l.\napply Rlt_trans with (R0 + R1).\n eapply Radd_lt_compat_l; apply Rlt_0_1.\n eapply Radd_lt_compat_r; apply Rlt_0_1.\nQed.\n\nLemma Radd_eq_cancel_r : forall x x' y, x + y == x' + y -> x == x'.\nProof.\nintros x x' y Hxy.\nrewrite <- (Radd_0_r x), <- (Radd_0_r x').\nrewrite <- (Radd_opp_r y).\nrepeat rewrite <- Radd_assoc.\nrewrite <- Hxy.\napply Radd_eq_compat_l.\nreflexivity.\nQed.\n\nInstance Proper_Req_opp : Proper (Req ==> Req) Ropp.\nProof.\nintros x x' Hx.\napply (Radd_eq_cancel_r _ _ x).\nrewrite Hx at 3.\ndo 2 rewrite Radd_comm, Radd_opp_r; reflexivity.\nQed.\n\nLemma Rmul_1_r : forall x, x * R1 == x.\nProof.\nintros; rewrite Rmul_comm; apply Rmul_1_l.\nQed.\n\nLemma Rinv_r : forall x (pr : x ## R0), x * Rinv x pr == R1.\nProof.\nintros x pr; rewrite Rmul_comm; apply Rinv_l.\nQed.\n\nLemma Rmul_eq_cancel_r : forall x x' y, y ## R0 -> x * y == x' * y -> x == x'.\nProof.\nintros x x' y Hy Hxy.\nrewrite <- (Rmul_1_r x), <- (Rmul_1_r x'), <- (Rinv_r y Hy).\nrepeat rewrite <- Rmul_assoc; rewrite <- Hxy.\napply Rmul_eq_compat_l; reflexivity.\nQed.\n\nInstance Proper_Req_inv : Proper\n  (fun f g : forall x, x ## R0 -> R => forall x x' H H', x == x' -> f x H == f x' H') Rinv.\nProof.\nintros x x' Hx Hx' Heq.\napply (Rmul_eq_cancel_r _ _ x Hx).\nrewrite Heq at 3.\ndo 2 rewrite Rmul_comm, Rinv_r; reflexivity.\nQed.\n\nDefinition R_ring : ring_theory R0 R1 Radd Rmul Rsub Ropp Req.\nProof.\nsplit.\n  apply Radd_0_l.\n  apply Radd_comm.\n  intros; apply Req_sym, Radd_assoc.\n  apply Rmul_1_l.\n  apply Rmul_comm.\n  intros; apply Req_sym, Rmul_assoc.\n  apply Rmul_add_distr_r.\n  reflexivity.\n  apply Radd_opp_r.\nQed.\n\nAdd Ring R_ring : R_ring.\n\nLemma Req_lt_compat : forall x y x' y', x == x' -> y == y' -> x < y -> x' < y'.\nProof.\nintros.\neapply Req_lt_compat_l; eauto.\neapply Req_lt_compat_r; eauto.\nQed.\n\nLemma Req_le_compat : forall x y x' y', x == x' -> y == y' -> x <= y -> x' <= y'.\nProof.\n  intros x y x' y' H1 H2 H3. destruct H3.\n   left. now apply Req_lt_compat with x y; assumption.\n   \n   right. apply Req_trans with x.\n    symmetry. now apply H1.\n    \n    apply Req_trans with y.\n     now assumption.\n     \n     assumption.\nQed.\n\nLemma Radd_lt_cancel_l : forall x1 x2 y : R, y + x1 < y + x2 -> x1 < x2.\nProof.\nintros x1 x2 y Hx.\ncut (- y + (y + x1) < - y + (y + x2)).\n  apply Req_lt_compat; try (ring_simplify; reflexivity).\n  apply Radd_lt_compat_l, Hx.\nQed.\n \nLemma Radd_le_cancel_l : forall x1 x2 y : R, y + x1 <= y + x2 -> x1 <= x2.\nProof.\n  intros x1 x2 y Hx. destruct Hx.\n   left. apply Radd_lt_cancel_l with y. now assumption.\n   \n   right. assert (- y + ( y + x1) == - y + (y + x2)).\n    apply Radd_eq_compat_l. now assumption.\n    \n    do 2 rewrite <- Radd_assoc in H. ring_simplify in H. apply H.\nQed.\n\nLemma Rlt_opp_1_0 : - R1 < R0.\nProof.\neapply Req_lt_compat_l; [ apply Radd_0_l | ].\neapply Req_lt_compat_r; [ apply Radd_opp_r | ].\napply Radd_lt_compat_r.\napply Rlt_0_1.\nQed.\n\nLemma Radd_lt_cancel_r : forall x1 x2 y : R, x1 + y < x2 + y -> x1 < x2.\nProof.\nintros x1 x2 y H.\napply (Radd_lt_compat_l (- y)) in H.\neapply (Req_lt_compat_l _ x1) in H; [ | ring ].\neapply (Req_lt_compat_r _ x2) in H; [ auto | ring ].\nQed.\n\nLemma Radd_eq_cancel_l : forall x y1 y2, (x + y1 == x + y2) -> (y1 == y2).\nProof.\n  intros x y1 y2 H1. apply (Radd_eq_compat_l (-x)) in H1. ring_simplify in H1. apply H1.\nQed.\n\nLemma Radd_le_cancel_r : forall x1 x2 y : R, x1 + y <= x2 + y -> x1 <= x2.\nProof.\n  intros x1 x2 y H. destruct H.\n   left. apply Radd_lt_cancel_r with y. now assumption.\n   \n   right. apply (Radd_eq_compat_r _ _ (-y)) in r. ring_simplify in r. apply r.\nQed.\n\nLemma Rmul_0_l : forall r:R, Req (R0 * r) R0.\nProof.\nintros; ring.\nQed.\n\nLemma Rmul_0_r : forall r:R, Req (r * R0) R0.\nProof.\nintros; ring.\nQed.\n\nDefinition Ppow2 := fix f n := match n with O => xH | S n' => xO (f n') end.\nDefinition Rpow2 n := IPR (Ppow2 n).\n\nLemma Rpos_pow2 : forall n, Rlt R0 (Rpow2 n).\nProof.\n intros n; induction n.\n apply Rlt_0_1.\n apply (Req_lt_compat_l _ _ _ (Radd_0_l R0)).\n apply Rlt_trans with (R0 + Rpow2 n).\n  apply Radd_lt_compat_l; auto.\n  \n  simpl.\n  unfold Rpow2; simpl.\n  eapply Req_lt_compat_r; [ rewrite Rmul_add_distr_r; reflexivity | ].\n  eapply Req_lt_compat_r; [ repeat rewrite Rmul_1_l; reflexivity | ].\n  apply Radd_lt_compat_r; auto.\nQed.\n\nLemma Rnn_pow2 : forall n, Rpow2 n ## R0.\nProof.\n intros n; right; apply Rpos_pow2.\nQed.\n\nLemma Ropp_0 : - R0 == R0.\nProof.\n  rewrite <- Radd_0_l.\n  apply Radd_opp_r.\nQed.\n\nLemma Rmul_lt_cancel_l : forall x y1 y2 : R, R0 < x -> x * y1 < x * y2 -> y1 < y2.\nProof.\n intros r a b rpos Hab.\n assert (Hir := Rinv_0_lt_compat r rpos (inr rpos)).\n remember (Rinv r (inr rpos)) as ir.\n eapply Req_lt_compat_l; [ rewrite <- Rmul_1_l, <- (Rinv_l r (inr rpos)), Rmul_assoc; reflexivity | ].\n eapply Req_lt_compat_r; [ rewrite <- Rmul_1_l, <- (Rinv_l r (inr rpos)), Rmul_assoc; reflexivity | ].\n apply Rmul_lt_compat_l; subst; auto.\nQed.\n\nLemma Rmul_le_cancel_l : forall x y1 y2 : R, R0 < x -> x * y1 <= x * y2 -> y1 <= y2.\nProof.\n  intros x y1 y2 H1 H2. destruct H2.\n   left. now apply Rmul_lt_cancel_l with x; assumption.\n   \n   right. assert (H0: x ## R0).\n    right. now assumption.\n    \n    apply (Rmul_eq_compat_l (Rinv x H0)) in r. do 2 rewrite <- Rmul_assoc in r. rewrite Rinv_l in r.\n    ring_simplify in r. apply r.\nQed.\n\nLemma Rmul_lt_cancel_r : forall x1 x2 y : R, R0 < y -> x1 * y < x2 * y -> x1 < x2.\nProof.\nintros x1 x2 y Hpos H.\neapply Req_lt_compat_l in H; [|apply Rmul_comm].\neapply Req_lt_compat_r in H; [|apply Rmul_comm].\napply Rmul_lt_cancel_l in H; auto.\nQed.\n\nLemma Rmul_le_cancel_r : forall x1 x2 y : R, R0 < y -> x1 * y <= x2 * y -> x1 <= x2.\nProof.\n  intros x1 x2 y H1 H2. destruct H2.\n   left. now apply Rmul_lt_cancel_r with y; assumption.\n   \n   right. assert (H0: y ## R0).\n    right. now assumption.\n    \n    apply (Rmul_eq_compat_r _ _ (Rinv y H0)) in r. do 2 rewrite Rmul_assoc in r. rewrite Rinv_r in r.\n    ring_simplify in r. apply r.\nQed.\n\nLemma Rmul_lt_compat_r : forall x y1 y2 : R, R0 < x -> y1 < y2 -> y1 * x < y2 * x.\nProof.\n intros x; intros.\n apply (Req_lt_compat_l _ _ _ (Rmul_comm x _)).\n apply (Req_lt_compat_r _ _ _ (Rmul_comm x _)).\n apply Rmul_lt_compat_l; auto.\nQed.\n\nLemma Rmul_le_compat_r : forall x y1 y2 : R, R0 <= x -> y1 <= y2 -> y1 * x <= y2 * x.\nProof.\n  intros x y1 y2 H1 H2. destruct H1.\n   destruct H2.\n    left. now apply Rmul_lt_compat_r; assumption.\n    \n    right. rewrite r0. now ring.\n  \n  right. rewrite <- r. ring.\nQed.\n\nLemma Ropp_involutive : forall x, - - x == x.\nProof.\n  intros x. eapply Radd_eq_cancel_r with (- x). rewrite Radd_opp_r. rewrite Radd_comm, Radd_opp_r.\n  reflexivity.\nQed.\n\nLemma Ropp_lt_contravar : forall x y, x < y -> - y < - x.\nProof.\n intros x y Lxy.\n apply (Radd_lt_cancel_r _ _ (x + y)).\n eapply Req_lt_compat_l; [ | eapply Req_lt_compat_r; [ | apply Lxy ] ].\n   (* ; ring : Error: Tactic failure: anomaly: Find_at (level 97). *)\n   ring.\n   ring.\nQed.\n\nLemma Ropp_le_contravar : forall x y, x <= y -> - y <= - x.\nProof.\n  intros x y H1. destruct H1.\n   left. apply Ropp_lt_contravar. now apply r.\n   \n   right. rewrite r. ring.\nQed.\n\nLemma Ropp_lt_contravar_reciprocal : forall x y, - y < - x -> x < y.\nProof.\n intros x y Lxy.\n apply (Req_lt_compat (- - x) (- - y)); try (ring_simplify; reflexivity).\n    (* Again, we could use ring but we get a strange error *)\n apply Ropp_lt_contravar; auto.\nQed.\n\nLemma Ropp_le_contravar_reciprocal : forall x y, - y <= - x -> x <= y.\nProof.\n  intros x y H. destruct H.\n   left. apply Ropp_lt_contravar_reciprocal. now assumption.\n   \n   right. rewrite <- Ropp_involutive. rewrite <- (Ropp_involutive y). rewrite r. reflexivity.\nQed.\n\nLemma Rlt_opp_0 : forall x, R0 < x -> - x < R0.\nProof.\n intros x xpos.\n eapply Req_lt_compat_r; [ apply Ropp_0 | ].\n apply Ropp_lt_contravar; auto.\nQed.\n\nLemma Rle_opp_0 : forall x, R0 <= x -> - x <= R0.\nProof.\n  intros x H. destruct H.\n   left. apply Rlt_opp_0. now assumption.\n   \n   right. rewrite <- r. ring.\nQed.\n\nLemma Rlt_0_opp : forall x, x < R0 -> R0 < - x.\nProof.\n intros x xpos.\n eapply Req_lt_compat_l; [ apply Ropp_0 | ].\n apply Ropp_lt_contravar; auto.  \nQed.\n\nLemma Rle_0_opp : forall x, x <= R0 -> R0 <= - x.\nProof.\n  intros x H. destruct H.\n   left. apply Rlt_0_opp. now assumption.\n   \n   right. rewrite r. ring.\nQed.\n\nLemma Rmul_lt_compat_neg_l : forall x y1 y2 : R, x < R0 -> y1 < y2 -> x * y2 < x * y1.\nProof.\n intros x; intros.\n apply Ropp_lt_contravar_reciprocal.\n apply (Req_lt_compat (- x * y1) (- x * y2)); try (ring_simplify; reflexivity).\n apply Rmul_lt_compat_l; try apply Rlt_0_opp; auto.\nQed.\n\nLemma Rmul_le_compat_neg_l : forall x y1 y2 : R, x <= R0 -> y1 <= y2 -> x * y2 <= x * y1.\nProof.\n  intros x y1 y2 H1 H2. destruct H1.\n   destruct H2.\n    left. now apply Rmul_lt_compat_neg_l; assumption.\n    \n    right. rewrite r0. now reflexivity.\n  \n  right. rewrite r. ring.\nQed.\n\nLemma Rmul_lt_compat_neg_r : forall x y1 y2 : R, x < R0 -> y1 < y2 -> y2 * x < y1 * x.\nProof.\n intros x; intros.\n apply (Req_lt_compat_l _ _ _ (Rmul_comm x _)).\n apply (Req_lt_compat_r _ _ _ (Rmul_comm x _)).\n apply Rmul_lt_compat_neg_l; auto.\nQed.\n\nLemma Rmul_le_compat_neg_r : forall x y1 y2 : R, x <= R0 -> y1 <= y2 -> y2 * x <= y1 * x.\nProof.\n  intros x y1 y2 H1 H2. destruct H1.\n   destruct H2.\n    left. now apply Rmul_lt_compat_neg_r; assumption.\n    \n    right. rewrite r0. now reflexivity.\n  \n  right. rewrite r. ring.\nQed.\n\nLemma Ropp_add : forall a b, - (a + b) == - a - b.\nProof.\nintros a b.\napply Radd_eq_cancel_r with (a + b).\nrewrite Radd_comm, Radd_opp_r.\nunfold Rsub.\nrewrite <- Radd_assoc, Radd_comm, (Radd_comm (- a)).\nrewrite Radd_assoc, (Radd_comm  _ a), Radd_opp_r.\nrewrite Radd_0_r, Radd_opp_r.\nreflexivity.\nQed.\n\nLemma Ropp_sub : forall a b, - (a - b) == b - a.\nProof.\nintros a b.\nunfold Rsub.\nrewrite Ropp_add.\nunfold Rsub.\nrewrite Ropp_involutive.\napply Radd_comm.\nQed.\n\nLemma Rdiv_mul_r : forall a b (bpos : b ## R0), Rdiv a b bpos * b == a.\nProof.\nintros a b bpos.\nunfold Rdiv.\nrewrite Rmul_assoc, Rinv_l, Rmul_1_r; reflexivity.\nQed.\n\nLemma Rdiv_mul_l : forall a b (bpos : b ## R0), b * Rdiv a b bpos == a.\nProof.\nintros; rewrite Rmul_comm; apply Rdiv_mul_r.\nQed.\n\nLemma Rinv_pos_compat : forall x (p : R0 < x) (p' : x ## R0), R0 < Rinv x p'.\nProof.\nintros x xp xd.\napply Rmul_lt_cancel_l with x.\n auto.\n apply (Req_lt_compat R0 R1).\n  ring_simplify; reflexivity.\n  rewrite Rinv_r; reflexivity.\n  apply Rlt_0_1.\nQed.\n\nLemma Req_le_compat_l : forall x1 x2 y : R, x1 == x2 -> x1 <= y -> x2 <= y.\nProof.\n  intros x1 x2 y H1 H2. destruct H2.\n   left. apply Rle_lt_trans with x1.\n    right. symmetry. now apply H1.\n    \n    now assumption.\n  \n  right. rewrite <- H1. assumption.\nQed.\n\nLemma Req_le_compat_r : forall x1 x2 y : R, x1 == x2 -> y <= x1 -> y <= x2.\nProof.\n  intros x1 x2 y H1 H2. destruct H2.\n   left. apply Rlt_le_trans with x1.\n    now assumption.\n    \n    right. now apply H1.\n  \n  right. rewrite <- H1. assumption.\nQed.\n\nLemma Rmul_le_compat_l : forall x y1 y2 : R, R0 <= x -> y1 <= y2 -> x * y1 <= x * y2.\nProof.\n  intros x y1 y2 H1 H2. destruct H1.\n   destruct H2.\n    left. now apply Rmul_lt_compat_l; assumption.\n    \n    right. rewrite r0. now reflexivity.\n  \n  right. rewrite <- r. ring.\nQed.\n\nLemma Radd_pos_compat : forall x y, R0 < x -> R0 < y -> R0 < x + y.\nProof.\n  intros. apply Rle_lt_trans with (R0 + R0).\n   right. now ring.\n   \n   apply Rlt_trans with (x + R0).\n    apply Radd_lt_compat_r. now assumption.\n    \n    apply Radd_lt_compat_l. assumption.\nQed.\n\nLemma Rpos_lt : forall x y, R0 < y - x -> x < y.\nProof.\n  intros x y pxy.\n  apply Radd_lt_cancel_r with (- x).\n  eapply Req_lt_compat_l; [ | eauto ]; symmetry; apply Radd_opp_r.\nQed.\n\nLemma Rlt_pos : forall x y, x < y -> R0 < y - x.\nProof.\n  intros x y pxy.\n  apply Radd_lt_cancel_r with x.\n  eapply Req_lt_compat with x y; auto; symmetry.\n    apply Radd_0_l.\n    ring_simplify; reflexivity.\nQed.\n\nEnd Rconvenient.\n", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/src/Fresh/Reals/Rconvenient.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.6588118185622029}}
{"text": "\n(* Lists of booleans and related theory. *)\n\nSet Implicit Arguments.\n\nRequire Import StdNat.\nRequire Export List.\nRequire Export Bvector.\nRequire Import Omega.\nRequire Import EqDec.\nRequire Import Fold.\nRequire Import Coq.NArith.Ndigits.\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  omega.\n  trivial.\n  destruct n.\n  omega.\n  rewrite IHls.\n  trivial.\n  omega.\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  omega.\n  subst.\n  exists ([], nil).\n  trivial.\n  \n  destruct n.\n  exists ([], a :: ls).\n  trivial.\n  assert (length ls >= n).\n  omega.\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.\nAdmitted.\n\nTheorem shiftOut_1_None : forall (n1 n2 : nat)(s : Blist),\n  shiftOut s n1 = None ->\n  n2 >= n1 ->\n  shiftOut s n2 = None.\nAdmitted.\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\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  Lemma 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.\n  Qed.\n\n  Lemma 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.  \n    \n  Qed.\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  Lemma 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.\n  Qed.\n\n  Lemma 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 omega.\n\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      omega.\n\n      destruct n.\n      destruct ls; simpl in *; try omega.\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.\n    Qed.\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\n  Qed.\n\n  eapply getAllBlists_app_length_In.\n  rewrite rev_length.\n  eapply getAllBlists_app_In_length.\n  eauto.\n\n  Lemma 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.\n  Qed.\n\n  Lemma 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 omega.\n\n    apply in_or_app.\n\n    destruct b; [left | right];\n    eapply in_map_iff; eauto.\n  Qed.\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\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  Fixpoint 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  \n  assert (tailOpt (Vector.cons A a1 n v1) = tailOpt (Vector.cons A a2 n v2)).\n  \n  Lemma 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.\n  Qed.\n  eapply tailOpt_eq.\n  trivial.\n  \n  simpl in *.\n  inversion H0; clear H0; subst.\n  trivial.          \n  \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 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  Lemma 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    omega.\n    destruct ls3; simpl in *; try omega; trivial.\n    subst.\n    rewrite app_nil_r.\n    intuition.\n  Qed.\n  \n  apply app_first_eq in H.\n  intuition; subst.\n  \n  Lemma 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.\n    \n  Qed.\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.size_nat (N.of_nat n).\n\nDefinition bvToNat(k : nat)(v : Bvector k) :=\n  N.to_nat (Bv2N k v).\n\nLemma Bv2N_zero : forall (n : nat),\n  Bv2N n (Bvect_false n) = N0.\n  \n  induction n; intuition; simpl in *.\n  unfold N.double in *.\n  unfold Bvect_false in *.\n  rewrite IHn.\n  trivial.\nQed.\n\nLemma bvNat_zero : forall n, \n  bvToNat (Bvect_false n) = O.\n\n  intuition.\n  unfold bvToNat.\n  assert (N.to_nat N0 = O).\n  simpl.\n  trivial.\n  rewrite <- H.\n  f_equal.\n  eapply Bv2N_zero.\n  \nQed.\n\nDefinition natToBv(k : nat)(v : nat) : Bvector k :=\n  N2Bv_gen k (N.of_nat v).\n\n\nLemma Bv2N_app_false : forall n1 n2 (v1 : Bvector n1),\n  Bv2N (n1 + n2) (Vector.append v1 (Bvect_false n2)) = Bv2N n1 v1.\n  \n  induction n1; intuition.\n  rewrite (vector_0 v1).\n  simpl.\n  apply Bv2N_zero.\n  \n  destruct (vector_S v1).\n  destruct H.\n  rewrite H.\n  simpl.\n  destruct x.\n  rewrite IHn1.\n  trivial.\n  rewrite IHn1.\n  trivial.\n  \nQed.\n\nLemma Bv2N_N2Bv_gen : forall n0 k,\n  n0 >= N.size_nat k ->\n  Bv2N n0 (N2Bv_gen n0 k) = k.\n  \n  intuition.\n  assert (exists x, n0 = N.size_nat k + x)%nat.\n  exists (minus n0 (N.size_nat k)).\n  omega.\n  destruct H0.\n  rewrite H0.\n  rewrite N2Bv_N2Bv_gen_above.\n  rewrite Bv2N_app_false.\n  apply Bv2N_N2Bv.\nQed.\n  \nLemma bvToNat_natToBv_inverse : forall n k,\n  n >= lognat k ->\n  bvToNat (natToBv n k) = k.\n  \n  intuition.\n  unfold bvToNat, natToBv.\n  rewrite Bv2N_N2Bv_gen.\n  apply Nnat.Nat2N.id.\n  trivial.\nQed.\n\nLemma Nat_size_nat_monotonic : forall n1 n2,\n  (n1 < n2)%N ->\n  (N.size_nat n1 <= N.size_nat n2)%nat.\n  \n  intuition.\n  destruct n1; simpl.\n  omega.\n  destruct n2; simpl.\n  inversion H.\n  eapply Pos.size_nat_monotone.\n  intuition.\nQed.\n  \nLemma lognat_monotonic : forall n1 n2,\n  (n1 < n2 ->\n    lognat n1 <= lognat n2)%nat.\n  \n  intuition.\n  unfold lognat.\n  eapply Nat_size_nat_monotonic.\n  specialize (Nnat.Nat2N.inj_compare n1 n2); intuition.\n  apply nat_compare_lt in H.\n  rewrite H in H0.\n  case_eq (N.of_nat n1 ?= N.of_nat n2)%N; intuition;\n    congruence.\nQed.\n\nLemma natToBv_bvToNat_inverse : forall n k,\n  (natToBv n (bvToNat k)) = k.\n\n  intuition.\n  unfold natToBv, bvToNat.\n  rewrite Nnat.N2Nat.id.\n  apply N2Bv_Bv2N.\nQed.\n\nLemma bvToNat_natToBv_eq : forall n (v : Bvector n) k,\n  bvToNat v = k ->\n  v = natToBv n k.\n\n  intuition.\n  rewrite <- H.\n  symmetry.\n  apply natToBv_bvToNat_inverse.\nQed.", "meta": {"author": "FreeAndFair", "repo": "RLA", "sha": "4295e4bb700ebbfe69affeb35dda7ed42273c3a1", "save_path": "github-repos/coq/FreeAndFair-RLA", "path": "github-repos/coq/FreeAndFair-RLA/RLA-4295e4bb700ebbfe69affeb35dda7ed42273c3a1/src/fcf/Blist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673223709251, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.6588118128867938}}
{"text": "Require Import ZArith.\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 => 0%Z\n         end.\n\nEval compute in (pos_div4 56%positive).\nEval compute in (pos_div4 55%positive).\nEval compute in (pos_div4 49%positive).\nEval compute in (pos_div4 3%positive).\nEval compute in (pos_div4 4%positive).\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/pos_div4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6588014909463784}}
{"text": "Set Implicit Arguments.\n\nRequire Import List.\nRequire Import Arith.\nRequire Import Max. \nRequire Import LibTactics. \n\n(** nat *) \nNotation \"k == i\" := (eq_nat_dec k i) (at level 70).\n\nLtac case_nat :=\n  let ldestr X Y := destruct (X == Y); [try subst X | idtac] in\n  match goal with\n  | |- context [?X == ?Y]      => ldestr X Y\n  | H: context [?X == ?Y] |- _ => ldestr X Y\n  end.\n\nNotation emptyset := nil.\n\n(** generating fresh nats *)\nSection Exist_fresh.\n\n  Fixpoint MAX (L : list nat) : nat :=\n    match L with\n    | nil        => O\n    | cons hd tl => max hd (MAX tl)\n    end.\n  \n  Lemma ex_fresh_var_1 : forall x L,\n    In x L -> (x <= MAX L).\n  Proof.\n  induction L; intros.\n    inversion H; simpl.\n    destruct (max_dec a (MAX L)); destruct H; simpl.\n        subst; rewrite e; apply le_refl.\n        eapply le_trans; [ apply IHL; trivial | apply le_max_r].\n        subst; apply le_max_l.\n        eapply le_trans; [apply IHL; trivial | apply le_max_r].\n  Qed.\n      \n  Lemma ex_fresh_var_2 : forall x L,\n    MAX L < x -> ~ In x L.\n  Proof.\n  induction L; intuition; simpl.\n    inversion H0; simpl; subst.\n      eelim (le_not_lt). eapply ex_fresh_var_1. apply H0. trivial.\n    apply IHL. apply le_lt_trans with (m := (MAX (a :: L))). simpl; apply le_max_r. assumption.\n    inversion H0; subst.\n      eelim le_not_lt. eapply ex_fresh_var_1. apply H0. trivial.\n      trivial.\n  Qed.\n\n  Lemma pick_fresh : forall (L : list nat),\n    exists n, ~ In n L.\n  Proof.\n  induction L; intros.\n    exists O; auto.\n    exists (S (MAX (a :: L))); intuition.\n    elim ex_fresh_var_2 with (x := (S (MAX (a :: L)))) (L := (a :: L)).\n      apply lt_n_Sn.\n      trivial.\n  Qed.\n\nEnd Exist_fresh.\n\n(** list nat *)\nLemma list_remove_in : forall n n0 S,\n  In n S -> n <> n0 -> In n (remove eq_nat_dec n0 S).\nProof.\n  induction S; intros; auto.\n  simpl; case_nat.\n    apply IHS; [destruct (in_inv H); congruence; auto | auto].\n    destruct (n == a).\n      subst; eauto with v62.\n      simpl; right; apply IHS; [destruct (in_inv H); [congruence | auto] | auto].\nQed.\n\nLemma list_remove_in_inv: forall S n0 n, \n  In n (remove eq_nat_dec n0 S) -> In n S.\nProof.\n  intros; induction S; auto.\n  destruct (n == a).\n    subst; auto using in_eq.\n    simpl in *. \n    case_nat.\n      right; auto.\n      right; elim (in_inv H); intuition congruence.\nQed.\n\nLemma list_remove_in_inv_2: forall l n0 n, \n  In n (remove eq_nat_dec n0 l) ->\n  n <> n0.\nProof.\n  red; intros; subst; firstorder.\n  contradict H.\n  induction l; simpl; intros; auto; destruct (n0 == a); simpl; firstorder.\nQed.\n\nLemma in_sub_remove : forall (x y:nat) l m,\n  (In x l -> In x m) ->\n  In x (remove eq_nat_dec y l) ->\n  In x (remove eq_nat_dec y m).\nProof.\n  induction l; simpl; intros; intuition.\n  destruct (y==a); simpl in *; auto.\n  elim H0; intros; auto.\n  subst.\n  auto using list_remove_in.\nQed.\n\nLemma list_remove_app : forall x l l',\n  remove eq_nat_dec x (l ++ l') = remove eq_nat_dec x l ++ remove eq_nat_dec x l'.\nProof.\n  induction l.\n  simpl; auto.\n  intro; simpl.\n  case_nat; auto.\n  rewrite IHl; eauto using app_comm_cons.\nQed.\n\nLemma list_remove_repeat : forall x l,\n  remove eq_nat_dec x (remove eq_nat_dec x l) = remove eq_nat_dec x l.\nProof.\n  induction l.\n  simpl; auto.\n  simpl; case_nat; auto.\n    simpl; case_nat; try congruence; auto.\nQed.\n\nLemma list_remove_twice : forall x y l,\n  remove eq_nat_dec x (remove eq_nat_dec y l) = remove eq_nat_dec y (remove eq_nat_dec x l).\nProof.\n  induction l.\n  simpl; auto.\n  simpl; case_nat.\n    repeat case_nat; auto.\n      simpl; repeat case_nat; try congruence; auto.\n    repeat case_nat; simpl; repeat case_nat; try congruence; auto.\nQed.\n\nLemma emptyset_plus : emptyset ++ emptyset = (emptyset:list nat).\nProof.\n  simpl; auto.\nQed.\n\n(** swap_nat *)\nDefinition swap_nat (n m k : nat) : nat :=\n  if n == k then m else if m == k then n else k.\n\nLemma swap_in_eq : forall n0 m k n,\n  k <> n -> swap_nat n0 m k <> swap_nat n0 m n.\nProof.\n  unfold swap_nat; intros.\n  repeat case_nat; congruence.\nQed.\n\nLemma swap_map_remove : forall l m n,\n  m <> n -> ~ In n l -> remove eq_nat_dec n (map (swap_nat n m) l) = remove eq_nat_dec m l.\nProof.\n  induction l.\n  intros; simpl; trivial.\n  intros.\n  assert (n <> a) by firstorder using remove_In.\n  assert (~ In n l) by firstorder.\n  destruct (m == a).\n\n    simpl map at 1.\n    replace (swap_nat n m a) with n.\n    simpl remove at 1; case_nat; try congruence.\n    simpl remove at 2; case_nat; try congruence.\n    auto.\n    unfold swap_nat. \n    case_nat; try congruence.\n    case_nat; try congruence.\n    \n    simpl map at 1.\n    assert (swap_nat n m a = a).\n      unfold swap_nat; case_nat; try congruence; case_nat; congruence.\n    rewrite H3.\n    simpl remove; case_nat; try congruence; case_nat; try congruence.\n    f_equal; auto.\nQed.\n\nLemma swap_not_in : forall m n k l,\n  ~ In k l -> ~ In (swap_nat m n k) (map (swap_nat m n) l).\nProof.\n  intros; induction l.\n  simpl; auto.\n  simpl; unfold swap_nat at 1.\n  assert (k <> a) by firstorder.\n  assert (~ In k l) by firstorder.\n  case_nat.\n\n    assert (n <> swap_nat a n k).\n    unfold swap_nat; repeat case_nat; congruence.\n    firstorder.\n    \n    assert ((if n == a then m else a) <> swap_nat m n k).\n    unfold swap_nat; repeat case_nat; congruence.\n    firstorder.\nQed.\n\nLemma swap_map_idem : forall l n m,\n  map (swap_nat m n) (map (swap_nat m n) l) = l.\nProof.\n  induction l; simpl; intros; f_equal; auto.\n  intros; unfold swap_nat; repeat case_nat; congruence.\nQed.\n\nLemma swap_eq_remove_map : forall l m n,\n  ~ In m l -> remove eq_nat_dec n l = remove eq_nat_dec m (map (swap_nat n m) l).\nProof.\n  induction l; intros; simpl; auto.\n  unfold swap_nat at 1.\n  case_nat; case_nat; try case_nat; try congruence.\n  simpl in H; intuition.\n  simpl in H; intuition.\n  unfold swap_nat at 1; case_nat; try congruence; case_nat; try congruence.\n  erewrite IHl; firstorder.\nQed.\n\nLemma swap_app_remove_map : forall n m k l,\n  map (swap_nat n m) (remove eq_nat_dec k l) \n    = remove eq_nat_dec (swap_nat n m k) (map (swap_nat n m) l).\nProof.\n  induction l; simpl; auto.\n  case_nat.\n    case_nat; try congruence.\n    case_nat.\n      forwards H : (swap_in_eq n m n0); congruence.\n      simpl; rewrite IHl; auto.\nQed.\n\n(** remove O and then map-decrement *)\nNotation map_pred_remove_zero l := (map pred (remove eq_nat_dec O l)).\n\nLemma swap_remove_map_pred_remove_zero : forall n L,\n  remove eq_nat_dec n (map_pred_remove_zero L) = map_pred_remove_zero (remove eq_nat_dec (S n) L).\nProof.\ninduction L; auto.\ndestruct a; simpl; auto.\n  destruct (n == a); simpl; auto.\n    rewrite IHL; auto.\nQed.    \n\nLemma notIn_n_pred_notIn_S_n : forall n L,\n  ~ In n (map pred L) -> ~ In (S n) L.\nProof.\ninduction L; simpl; intuition.\n  destruct a; simpl; intuition.\n    inversion H1.\nQed.   \n\nLemma notIn_remove_notIn : forall n m L,\n  n <> m -> ~ In n (remove eq_nat_dec m L) -> ~ In n L.\nProof.\ninduction L; simpl.\n  intuition.\n  destruct (m == a); simpl; subst; intuition.\nQed.\n\nLemma notIn_remove_notIn_remain : forall n m L,\n  ~ In n L -> ~ In n (remove eq_nat_dec m L).\nProof.\ninduction L; simpl.\n  intuition.\n  destruct (m == a); simpl; subst; intuition.\nQed.    \n\nLemma notIn_remove_self : forall n L,\n  ~ In n (remove eq_nat_dec n L).\nProof.\n  induction L; simpl; intros; auto; destruct (n == a); simpl; firstorder.\nQed.    \n\nLemma notIn_dist : forall A, forall (x :A) L L',\n  ~ In x (L ++ L') -> ~ In x L /\\ ~ In x L'.\nProof.\ninduction L; simpl; intuition.\nQed.\n\nLemma map_eq_nil : forall A, forall f (L : list A), (map f L = (nil : list A)) -> (L = nil).\nProof.\ninduction L; simpl; intuition.\n  inversion H.\nQed.\n\n(** list *)\nLemma list_permuting_in_app_cons_cons : forall T (x:T) l a b l',\n  In x (l ++ a :: b :: l') -> \n  In x (l ++ b :: a :: l').\nProof.\n  induction l; simpl; intros.\n  firstorder.\n  firstorder.\nQed.\n\nLemma list_cons_move_app : forall T (x:T) l l',\n  l ++ x :: l' = (l ++ x :: nil) ++ l'.\nProof.\n  induction l; intros; simpl; auto.\n  f_equal; auto.\nQed.\n\nLemma list_cons_cons_move_app : forall T (y:T) l l',\n  y :: l ++ l' = (y :: l) ++ l'.\nProof.\n  simpl; auto.\nQed.\n\n(** In *)\nLtac destructIn tac := \n  match goal with \n    | H: In ?X emptyset |- _ => inversion H\n    | H: In ?X (?L1 ++ ?L2) |- _ =>\n      apply in_app_or in H; destruct H; destructIn tac\n    | H: In ?X (?X :: ?L) |- _ =>\n      clear H; destructIn tac\n    | H: In ?X (?Y :: ?L) |- _ =>\n      apply in_inv in H; destruct H; destructIn tac\n    | |- In ?X (?Y :: ?L) =>\n      try solve [ apply in_eq; destructIn tac | apply in_cons; destructIn tac ]\n    | |- In ?X (?L1 ++ ?L2) =>\n      apply in_or_app; try solve [ left; destructIn tac | right; destructIn tac ]\n    | _ => tac     \n  end.\n\nTactic Notation \"Destruct\" \"In\" \"by\" tactic(tac) := destructIn tac.\n\n(** notIn  *)\nLemma not_in_not_eq : forall A (X : A) (Y : A) L,\n  X <> Y -> ~ In X L -> ~ In X (Y :: L).\nProof.\n  firstorder.\nQed.\n\nLemma not_in_and_app : forall A L L' (X : A),\n  ~ In X L -> ~ In X L' -> ~ In X (L ++ L').\nProof.\n  induction L; firstorder.\nQed.\n\nLemma not_in_inv : forall A (X : A) (Y : A) L,\n  ~ In X (Y :: L) -> X <> Y /\\ ~ In X L.\nProof.\n  firstorder.\nQed.\n\nLemma not_in_app_and : forall A, forall (x :A) L L',\n  ~ In x (L ++ L') -> ~ In x L /\\ ~ In x L'.\nProof.\n  firstorder.\nQed.\n\nLtac destructNotIn tac := \n  let goal_destr_cons := (apply not_in_not_eq) in\n  let goal_destr_concat := (apply not_in_and_app) in\n  let hypo_destr_cons H := destruct (not_in_inv H); clear H in\n  let hypo_destr_concat H := destruct (not_in_app_and _ _ _ H); clear H in\n  match goal with\n    | H: ?X <> ?X |- _ => congruence\n    | H: ~ In ?X (?Y :: ?L) |- _ => hypo_destr_cons H; (destructNotIn tac)\n    | H: ~ In ?X (?L1 ++ ?L2) |- _ => hypo_destr_concat H; (destructNotIn tac)\n    | |- ~ In ?X (?Y :: ?L) => goal_destr_cons; [ tac | destructNotIn tac ]\n    | |- ~ In ?X (?L1 ++ ?L2) => goal_destr_concat; (destructNotIn tac)\n    | _ => tac\n  end.\n\nTactic Notation \"Destruct\" \"notIn\" \"by\" tactic(tac) := destructNotIn tac.\n\nLemma list_always_incl_emptyset : forall A (l : list A), incl emptyset l.\nProof.\n  induction l; eauto with v62.\nQed.\n", "meta": {"author": "cmcl", "repo": "msci", "sha": "06b1607ee1f4dde3c7c984ce6e1bbc86a8fd36f9", "save_path": "github-repos/coq/cmcl-msci", "path": "github-repos/coq/cmcl-msci/msci-06b1607ee1f4dde3c7c984ce6e1bbc86a8fd36f9/Coq Developments/jar12/lib/LibNat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245994514084, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.6587683693845648}}
{"text": "Module Basics.\n\n(* Для начала, как обычно, заново определим ложь, конъюнкцию и дизъюнкцию *)\n(* Наши определения будут немного отличаться от предыдущих *)\n\nDefinition False : Prop := forall P:Prop, P.\n\nDefinition not : Prop -> Prop := fun A:Prop => A -> False.\n\nNotation \"~' x\" := (not x) (at level 75, right associativity).\n\n(* Конъюнкция *)\nDefinition and : Prop->Prop->Prop := fun A B:Prop => forall P:Prop, (A -> B -> P) -> P.\n\nNotation \"A /_\\ B\" := (and A B) (at level 80).\n\n(* Аксиома A → B → A /\\ B *)\nTheorem andI : forall (A B : Prop), A -> B -> A /_\\ B.\nProof.\n    exact (fun A B a b P H => H a b).\n    (* Также можно доказать так:\n    intros A B a b.\n    unfold and.\n    intros P H.\n    exact (H a b).\n    *)\nQed.\n\n(* Дизъюнция *)\nDefinition or : Prop->Prop->Prop := fun (A B : Prop) => forall P:Prop, (A -> P) -> (B -> P) -> P.\n\nNotation \"A \\_/ B\" := (or A B) (at level 85).\n\n(* Аксиома A → A \\/ B *)\nTheorem orIL : forall (A B : Prop), A -> A \\_/ B.\nProof.\n    exact (fun A B a P H1 H2 => H1 a).\nQed.\n\n(* Аксиома B → A \\/ B *)\nTheorem orIR : forall (A B : Prop), B -> A \\_/ B.\nProof.\n    exact (fun A B b P H1 H2 => H2 b).\nQed.\n\n(* Эквивалентность через конъюнкцию *)\nDefinition iff : Prop->Prop->Prop := fun (A B:Prop) => (A -> B) /_\\ (B -> A).\n\nNotation \"A <=> B\" := (iff A B) (at level 95).\n\n\n(* Теперь начнем развлекаться со множествами *)\n\n(* Для начала определим множество *)\nParameter set : Type.\n\n(* Равенство двух множеств *)\n(* Любое суждение, верное для одного множества, верно и для другого *)\nDefinition eq : set->set->Prop := fun (x y : set) => forall Q:set -> Prop, Q x -> Q y.\n\nNotation \"x == y\" := (eq x y) (at level 70).\nNotation \"x /= y\" := (~' x == y) (at level 70).\n\n(* Докажем рефлексивность такого равенства *)\nTheorem eqI : forall x:set, x == x.\nProof.\n    exact (fun x q H => H).\nQed.\n\n(* И симметричность *)\nTheorem eq_sym : forall x y:set, x == y -> y == x.\nProof.\n    (* CW *)\n    exact (fun x y H => H (fun y => eq y x) (eqI x)).\nQed.\n\n(* Определим квантор существования для set *)\nDefinition ex : (set->Prop)->Prop := fun P:set->Prop => forall Q:Prop, (forall x, P x -> Q) -> Q.\n\nNotation \"'exists' x , p\" := (ex (fun x => p))\n  (at level 200, x ident).\n\n(* P x -> \\exists x P x *)\nTheorem exI : forall P:set->Prop, forall x:set, P x -> exists x, P x.\nProof.\n    exact (fun P x H1 Q H2 => H2 x H1).\nQed.\n\n(* Такой же квантор существования, только для функций вида set -> set *)\nDefinition ex_f : ((set->set)->Prop)->Prop := fun P:(set->set)->Prop => forall Q:Prop, (forall x, P x -> Q) -> Q.\n\nNotation \"'existsf' x , p\" := (ex_f (fun x => p))\n  (at level 200, x ident).\n\nTheorem exI_f : forall P:(set->set)->Prop, forall F:set->set, P F -> existsf F, P F.\nProof.\n    (* CW *)\n    exact (fun P F H1 Q H2 => H2 F H1).\nQed.\n\n(* Квантор единственного существования *)\nDefinition exu : (set->Prop)->Prop := fun P:set->Prop => (exists x, P x) /_\\ (forall x y:set, P x -> P y -> x == y).\n\nNotation \"'exists!' x , p\" := (exu (fun x => p))\n  (at level 200, x ident).\n\nTheorem exuI : forall P:set->Prop, (exists x, P x) -> (forall x y:set, P x -> P y -> x == y) -> exists! x, P x.\nProof.\n    (* CW *)\n    intros P.\n    exact (andI (ex P) (forall x y:set, P x -> P y -> x == y)).\nQed.\n\n(* Оператор описания множества *)\n(* Пригодится позже в доказательствах, пока можно пропустить *)\nParameter Descr : ((set->Prop)->set).\n\nAxiom DescrR : forall P:set->Prop, (exists! x, P x) -> P (Descr P).\n\n\n(* Определим базовые отношения, свойства и операции над множествами *)\n\n(* In - отношение \"x принадлежит множеству y\" *)\n\nParameter In : set->set->Prop.\n\nNotation \"x ':e' y\" := (In x y) (at level 70).\nNotation \"x '/:e' y\" := (~' (In x y)) (at level 70).\n\n(* Subq - отношение \"A вложено в B\" *)\n\nDefinition Subq : set->set->Prop :=\nfun X Y => forall x:set, x :e X -> x :e Y.\n\nNotation \"X 'c=' Y\" := (Subq X Y) (at level 70).\nNotation \"X '/c=' Y\" := (~' (Subq X Y)) (at level 70).\n\nLemma Subq_ref : forall X:set, X c= X.\n    intros X x H1. exact H1.\nQed.\n\nLemma Subq_tra : forall X Y Z:set, X c= Y -> Y c= Z -> X c= Z.\n    (* CW *)\n    intros X Y Z H1 H2 x H3. apply H2. apply H1. exact H3.\nQed.\n\n(* Равенство множеств - это вложенность множеств друг в друга *)\n\nAxiom set_ext : forall X Y:set, X c= Y -> Y c= X -> X == Y.\n\n(* Равенство в другую сторону *)\n\nTheorem set_ext_inv : forall X Y:set, X == Y -> (X c= Y /_\\ Y c= X).\nProof.\n    (* HW *)\n    admit.\nQed.\n\n(* Индукция по множеству *)\n\nAxiom In_ind : forall P:set->Prop, (forall X:set, (forall x, x :e X -> P x) -> P X) -> forall X:set, P X.\n\nParameter Empty : set.\n\nAxiom EmptyAx : ~' exists x, x :e Empty.\n\nLemma EmptyE : forall x:set, x /:e Empty.\n    (* CW *)\n    exact (fun x H => EmptyAx (exI (fun x => x :e Empty) x H)).\nQed.\n\n(* Union(X) - операция объединения всех подмножеств X *)\n(* То есть Union(X) = {x | \\exists Y: x \\in Y, Y \\in X} *)\n\nParameter Union : set->set.\n\nAxiom UnionEq : forall X:set, forall x:set, x :e Union X <=> exists Y, x :e Y /_\\ Y :e X.\n\nLemma A_and_B_A : forall A B:Prop, A /_\\ B -> A.\nProof.\n    unfold and.\n    intros.\n    pose (t := H A).\n    intuition.\nQed.\n\nLemma A_and_B_B : forall A B:Prop, A /_\\ B -> B.\nProof.\n    unfold and.\n    intros.\n    pose (t := H B).\n    intuition.\nQed.\n\nLemma UnionE :\nforall X x:set, x :e (Union X) -> exists Y, x :e Y /_\\ Y :e X.\nProof.\n    (* CW *)\n    exact (fun X x : set =>\n    UnionEq X x (x :e Union X -> exists Y, x :e Y /_\\ Y :e X)\n      (fun (H1 : x :e Union X -> exists Y, x :e Y /_\\ Y :e X)\n         (_ : (exists Y, x :e Y /_\\ Y :e X) -> x :e Union X) => H1)).\nQed.\n\nLemma UnionI :\nforall X x Y:set, x :e Y -> Y :e X -> x :e (Union X).\nProof.\n    (* CW *)\n    exact (fun (X x Y : set) (H1 : x :e Y) (H2 : Y :e X) =>\n    UnionEq X x (x :e Union X)\n      (fun (_ : x :e Union X -> exists Y, x :e Y /_\\ Y :e X)\n         (H4 : (exists Y, x :e Y /_\\ Y :e X) -> x :e Union X) =>\n       H4\n         (exI (fun Y0 : set => x :e Y0 /_\\ Y0 :e X) Y\n            (andI (x :e Y) (Y :e X) H1 H2)))).\nQed.\n\n(* Power(X) - множество всех подмножеств X *)\n\nParameter Power : set->set.\n\nAxiom PowerEq : forall X Y:set, Y :e Power X <=> Y c= X.\n\nLemma PowerE : forall X Y:set, Y :e Power X -> Y c= X.\nProof.\n    intros.\n    pose (t := PowerEq X Y).\n    unfold iff in t.\n    pose (tt := A_and_B_A _ _ t).\n    exact (tt H).\nQed.\n\nLemma PowerI : forall X Y:set, Y c= X -> Y :e (Power X).\n    intros.\n    pose (t := PowerEq X Y).\n    unfold iff in t.\n    pose (tt := A_and_B_B _ _ t).\n    exact (tt H).\nQed.\n\nLemma In_Power : forall X:set, X :e Power X.\nProof.\n    (* CW *)\n    intros X. apply PowerI. apply Subq_ref.\nQed.\n\n(* Sep(X, P) = {x | x :e X, P x} *)\n\nParameter Sep : set -> (set -> Prop) -> set.\n\nNotation \"{ x :i X | P }\" := (Sep X (fun x:set => P)).\n\nAxiom SepEq : forall X:set, forall P:set -> Prop, forall x, x :e {z :i X | P z} <=> x :e X /_\\ P x.\n\nLemma SepI : forall X:set, forall P:set -> Prop, forall x:set,\n x :e X -> P x -> x :e {z :i X|P z}.\nProof.\n    (* CW *)\n    exact (fun (X : set) (P : set -> Prop) (x : set) (H1 : x :e X) (H2 : P x) =>\n    SepEq X P x (x :e Sep X P)\n      (fun (_ : x :e Sep X P -> x :e X /_\\ P x)\n         (H3 : x :e X /_\\ P x -> x :e Sep X P) => H3 (andI (x :e X) (P x) H1 H2))).\nQed.\n\nLemma SepE : forall X:set, forall P:set -> Prop, forall x:set,\n x :e {z :i X|P z} -> x :e X /_\\ P x.\nProof.\n    (* CW *)\n    intros X P x H1. apply (SepEq X P x). exact (fun H2 _ => H2 H1).\nQed.\n\nLemma SepE1 : forall X:set, forall P:set -> Prop, forall x:set,\n x :e {z :i X|P z} -> x :e X.\nProof.\n    (* CW *)\n    exact (fun (X : set) (P : set -> Prop) (x : set) (H1 : x :e Sep X P) =>\n    SepEq X P x (x :e X)\n      (fun (H2 : x :e Sep X P -> x :e X /_\\ P x)\n         (_ : x :e X /_\\ P x -> x :e Sep X P) =>\n       H2 H1 (x :e X) (fun (H3 : x :e X) (_ : P x) => H3))).\nQed.\n\nLemma SepE2 : forall X:set, forall P:set -> Prop, forall x:set,\n x :e {z :i X|P z} -> P x.\nProof.\n    (* CW *)\n    exact (fun (X : set) (P : set -> Prop) (x : set) (H1 : x :e Sep X P) =>\n    SepEq X P x (P x)\n      (fun (H2 : x :e Sep X P -> x :e X /_\\ P x)\n         (_ : x :e X /_\\ P x -> x :e Sep X P) =>\n       H2 H1 (P x) (fun (_ : x :e X) (H3 : P x) => H3))).\nQed.\n\n(* Repl(X, F) = {F x | x :e X} *)\n\nParameter Repl : set->(set->set)->set.\n\nNotation \"{ F | x :i X }\" := (Repl X (fun x:set => F)).\n\nAxiom ReplEq :\nforall X:set, forall F:set->set, forall y:set, y :e {F z|z :i X} <=> exists x, x :e X /_\\ y == F x.\n\nLemma ReplE :\nforall X:set, forall F:set->set, forall y:set, y :e {F z|z :i X} -> exists x, x :e X /_\\ y == F x.\nProof.\n    (* HW *)\n    exact (fun (X : set) (F : set -> set) (y : set) =>\n    ReplEq X F y\n      (y :e Repl X (fun x : set => F x) -> exists x, x :e X /_\\ y == F x)\n      (fun\n         (H1 : y :e Repl X (fun x : set => F x) ->\n               exists x, x :e X /_\\ y == F x)\n         (_ : (exists x, x :e X /_\\ y == F x) ->\n              y :e Repl X (fun x : set => F x)) => H1)).\nQed.\n\nLemma ReplI :\nforall X:set, forall F:set->set, forall x:set, x :e X -> F x :e {F x|x :i X}.\nProof.\n    (* HW *)\n    exact (fun (X : set) (F : set -> set) (x : set) (H1 : x :e X) =>\n    ReplEq X F (F x) (F x :e Repl X (fun x0 : set => F x0))\n      (fun\n         (_ : F x :e Repl X (fun x0 : set => F x0) ->\n              exists x0, x0 :e X /_\\ F x == F x0)\n         (H4 : (exists x0, x0 :e X /_\\ F x == F x0) ->\n               F x :e Repl X (fun x0 : set => F x0)) =>\n       H4\n         (exI (fun x0 : set => x0 :e X /_\\ F x == F x0) x\n            (andI (x :e X) (F x == F x) H1 (eqI (F x)))))).\nQed.\n\n(* Прикольные леммки для разных операций над пустыми множествами *)\n(* Пригодятся позже, когда определим ординалы *)\n\nLemma Subq_Empty : forall X:set, Empty c= X.\nProof.\n    (* CW *)\n    exact (fun (X x : set) (H : x :e Empty) => EmptyE x H (x :e X)).\nQed.\n\nLemma Empty_Power : forall X:set, Empty :e Power X.\nProof.\n    (* CW *)\n    intros X. apply PowerI. apply Subq_Empty.\nQed.\n\nLemma Repl_Empty : forall F:set -> set, {F x|x :i Empty} == Empty.\nProof.\n    (* HW *)\n    exact (fun F : set -> set =>\n    set_ext (Repl Empty F) Empty\n      (fun (x : set) (H1 : x :e Repl Empty F) =>\n       ReplE Empty F x H1 (x :e Empty)\n         (fun (y : set) (H1' : y :e Empty /_\\ x == F y) =>\n          H1' (x :e Empty)\n            (fun (H2 : y :e Empty) (_ : x == F y) => EmptyE y H2 (x :e Empty))))\n      (fun (x : set) (H1 : x :e Empty) => EmptyE x H1 (x :e Repl Empty F))).\nQed.\n\n(* Неупорядоченная пара *)\n\nDefinition TSet : set := {X :i Power (Power Empty) | Empty :e X \\_/ Empty /:e X}.\nDefinition UPair : set->set->set :=\n fun y z:set =>\n {Descr (fun w:set => forall p:set->Prop, (Empty /:e X -> p y) -> (Empty :e X  -> p z) -> p w)|X :i TSet}.\n\nNotation \"{ x , y }\" := (UPair x y).\n\nLemma UPairE :\nforall x y z:set, x :e {y,z} -> x == y \\_/ x == z.\nProof.\n    (* HW *)\n    intros x y z H1. apply ReplE in H1. apply H1.\n    intros u H2. apply H2. intros H3 H4.\n    apply (SepE _ _ _ H3). intros H5 H6. apply (eq_sym _ _ H4).\n    apply (DescrR (fun v:set => forall p:set->Prop, (Empty /:e u -> p y) -> (Empty :e u  -> p z) -> p v)).\n    - apply exuI.\n      + apply H6.\n        * intros H7. apply (exI _ z). intros p _ H8. exact (H8 H7).\n        * intros H7. apply (exI _ y). intros p H8 _. exact (H8 H7).\n      + intros v w H7 H8. apply H7.\n        * { intros H9 p H10. apply H8.\n            - intros _. exact H10.\n            - intros H11. apply (H9 H11).\n          }\n        * { intros H9 p H10. apply H8.\n            - intros H11. apply (H11 H9).\n            - intros _. exact H10.\n          }\n    - intros _. apply orIL. apply eqI.\n    - intros _. apply orIR. apply eqI.\nQed.\n\nLemma UPairI1 :\nforall y z:set, y :e {y,z}.\nProof.\n    (* HW *)\n    intros y z.\n    assert (H1:Descr (fun v => forall p:set->Prop, (Empty /:e Empty -> p y) -> (Empty :e Empty  -> p z) -> p v) == y).\n    {\n      apply (DescrR (fun v => forall p:set->Prop, (Empty /:e Empty -> p y) -> (Empty :e Empty  -> p z) -> p v)).\n      - apply exuI.\n        + apply (exI _ y). intros p H2 _. apply H2. apply EmptyE.\n        + intros v w H2 H3. apply H2.\n          * { intros H4 p H5. apply H3.\n              - intros _. exact H5.\n              - intros H6. apply (EmptyE _ H6).\n            }\n          * intros H4. apply (EmptyE _ H4).\n      - intros _. apply eqI.\n      - intros H2. apply (EmptyE _ H2).\n    }\n    apply (H1 (fun w => w :e UPair y z)).\n    change ((fun u => Descr (fun v => forall p:set->Prop, (Empty /:e u -> p y) -> (Empty :e u  -> p z) -> p v)) Empty :e UPair y z).\n    apply ReplI. apply SepI.\n    - apply Empty_Power.\n    - apply orIR. apply EmptyE.\nQed.\n\nLemma UPairI2 :\nforall y z:set, z :e {y,z}.\nProof.\n    (* HW *)\n    intros y z.\n    assert (H1:Descr (fun v => forall p:set->Prop, (Empty /:e Power Empty -> p y) -> (Empty :e Power Empty  -> p z) -> p v) == z).\n    {\n      apply (DescrR (fun v => forall p:set->Prop, (Empty /:e Power Empty -> p y) -> (Empty :e Power Empty  -> p z) -> p v)).\n      - apply exuI.\n        + apply (exI _ z). intros p _ H2. apply H2. apply Empty_Power.\n        + intros v w H2 H3. apply H2.\n          * intros H4. apply H4. apply Empty_Power.\n          * { intros H4 p H5. apply H3.\n              - intros H6. apply H6. apply Empty_Power.\n              - intros _. exact H5.\n            }\n      - intros H2. apply H2. apply Empty_Power.\n      - intros _. apply eqI.\n    }\n    apply (H1 (fun w => w :e UPair y z)).\n    change ((fun u => Descr (fun v => forall p:set->Prop, (Empty /:e u -> p y) -> (Empty :e u  -> p z) -> p v)) (Power Empty) :e UPair y z).\n    apply ReplI. apply SepI.\n    - apply In_Power.\n    - apply orIL. apply Empty_Power.\nQed.\n\nLemma UPairEq :\nforall x y z, x :e {y,z} <=> x == y \\_/ x == z.\nProof.\n    (* CW *)\n    intros x y z. apply andI. apply UPairE. intros H1. apply H1.\n    intros H2. apply H2. apply UPairI1.\n    intros H2. apply H2. apply UPairI2.\nQed.\n\n(* sing(Y) = {Y, Y} *)\n\nDefinition Sing : set->set := fun y:set => {y,y}.\n\nNotation \"{| y |}\" := (Sing y).\n\nLemma SingI : forall y, y :e {| y |}.\nProof.\n  intros y. unfold Sing. apply UPairI1.\nQed.\n\nLemma SingE : forall x y, x :e {| y |} -> x == y.\nProof.\n  intros x y H1. apply (UPairE _ _ _ H1). exact (fun H => H). exact (fun H => H).\nQed.\n\nLemma SingEq : forall x y, x :e {| y |} <=> x == y.\nProof.\n    (* CW *)\n    intros x y. apply andI. apply SingE. intros H. apply H. apply SingI.\nQed.\n\n(* binunion(X, Y) = Union({X, Y}) *)\n\nDefinition binunion : set -> set -> set := fun X Y => Union {X,Y}.\n\nNotation \"X :u: Y\" := (binunion X Y) (at level 40).\n\nLemma binunionI1 : forall X Y z, z :e X -> z :e X :u: Y.\n    (* CW *)\n    exact (fun (X Y z : set) (H1 : z :e X) => UnionI (UPair X Y) z X H1 (UPairI1 X Y)).\nQed.\n\nLemma binunionI2 : forall X Y z, z :e Y -> z :e X :u: Y.\n    (* CW *)\n    exact (fun (X Y z : set) (H1 : z :e Y) => UnionI (UPair X Y) z Y H1 (UPairI2 X Y)).\nQed.\n\nLemma binunionE : forall X Y z, z :e X :u: Y -> z :e X \\_/ z :e Y.\n    (* HW *)\n    exact (fun (X Y z : set) (H1 : z :e binunion X Y) =>\n    UnionE (UPair X Y) z H1 (z :e X \\_/ z :e Y)\n      (fun (w : set) (H1' : z :e w /_\\ w :e UPair X Y) =>\n       H1' (z :e X \\_/ z :e Y)\n         (fun (H2 : z :e w) (H3 : w :e UPair X Y) =>\n          UPairE w X Y H3 (z :e X \\_/ z :e Y)\n            (fun H4 : w == X =>\n             orIL (z :e X) (z :e Y) (H4 (fun X0 : set => z :e X0) H2))\n            (fun H4 : w == Y =>\n             orIR (z :e X) (z :e Y) (H4 (fun Y0 : set => z :e Y0) H2))))).\nQed.\n\nLemma binunionEq : forall X Y z, z :e X :u: Y <=> z :e X \\_/ z :e Y.\n    (* CW *)\n    intros X Y z. apply andI. apply binunionE. intros H1. apply H1. apply binunionI1. apply binunionI2.\nQed.\n\n(* TODO : setminus, famunion, ordinals, more and more fun to follow *)\n\nEnd Basics.\n\nExport Basics.\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-set-theory/set-theory-basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.6587683640560145}}
{"text": "Require Export Singletons.\nRequire Export Separation.\n\n(* This file contains exercises from Paul Halmos book, Naive Set Theory, and\n   from a few other places. *)\n\nTheorem union_empty : Union ∅ = ∅.\nProof.\n  extension.\n  - apply Union_E in H. destruct H. inv H.\n    contradiction (Empty_E x0).\n  - apply Union_I with (Y := ∅). auto.\n    contradiction (Empty_E x).\nQed.\n\nHint Resolve union_empty.\n\nTheorem union_sing : forall A, Union (Sing A) = A.\nProof. intros. compute. extension; obvious_BUR. Qed.\n\nHint Resolve union_sing.\n\nTheorem union_one : Union One = ∅.\nProof. compute. apply union_sing. Qed.\n\nTheorem union_X_two : forall X, X ∈ Two → Union X = ∅.\nProof.\n  intros. unfold Two in H.\n  apply UPair_E in H.\n  inversion H.\n  rewrite <- union_empty.\n  f_equal. assumption. rewrite H0.\n  compute. apply union_sing.\nQed.\n\nTheorem union_two : Union Two = One.\nProof.\n  compute. extension.\n  apply Union_E in H. destruct H. inv H.\n    apply UPair_E in H1. inv H1.\n      contradiction (Empty_E x).\n      assumption.\n  apply Union_I with (Y := {∅, ∅}).\n    assumption.\n    apply UPair_I2.\nQed.\n\nTheorem union_comm : forall A B, A ∪ B = B ∪ A.\nProof. obvious_BUR. Qed.\n\nTheorem union_assoc : forall A B C, A ∪ (B ∪ C) = (A ∪ B) ∪ C.\nProof. obvious_BUR. Qed.\n\nTheorem union_idem : forall A, A ∪ A = A.\nProof. obvious_BUR. Qed.\n\nTheorem union_incl : forall A B, A ⊆ B ↔ A ∪ B = B.\nProof.\n  intros. split; intros. obvious_BUR.\n  compute. intros. rewrite <- H. union_1.\nQed.\n\nDefinition Inter (M : set) : set :=\n  Sep (Union M) (fun x : set => ∀ A : set, A ∈ M → x ∈ A).\n\nLemma Inter_I : ∀ x M, inh_set M → (∀ A, A ∈ M → x ∈ A) → x ∈ Inter M.\nProof.\n  intros. unfold Inter.\n  apply Sep_I. inv H. specialize (H0 x0).\n    apply Union_I with (Y := x0); auto.\n    auto.\nQed.\n\nHint Resolve Inter_I.\n\nLemma Inter_E : ∀ x M, x ∈ Inter M → inh_set M ∧ ∀ A, A ∈ M → x ∈ A.\nProof.\n  intros. unfold Inter in H.\n  apply Sep_E in H. inv H.\n  apply Union_E in H0. destruct H0. inv H.\n  split.\n    specialize (H1 x0).\n    unfold inh_set. exists x0. auto.\n  auto.\nQed.\n\nHint Resolve Inter_E.\n\nDefinition BinInter (A B : set) : set := Inter (UPair A B).\n\nLemma BinInter_I : ∀ A B a: set, a ∈ A ∧ a ∈ B → a ∈ BinInter A B.\nProof.\n  intros. unfold BinInter. inv H.\n  apply Inter_I.\n    unfold inh_set. exists A. pair_1.\n    intros. pair_e H.\nQed.\n\nHint Resolve BinInter_I.\n\nLemma BinInter_E : ∀ A B x, x ∈ BinInter A B → x ∈ A ∧ x ∈ B.\nProof.\n  intros. unfold BinInter in H.\n  apply Inter_E in H. inv H.\n  unfold inh_set in H0. destruct H0.\n  split; obvious_BUR.\nQed.\n\nHint Resolve BinInter_E.\n\nNotation \"X ∩ Y\" := (BinInter X Y) (at level 69).\n\nLtac inter := apply BinInter_I ; split ; try auto.\nLtac inter_e H :=\n  apply BinInter_E in H ; try (first [ inv H | destruct H ]) ; try auto.\n\nLtac obvious :=\n  repeat (try obvious_BUR; match goal with\n  | [ H : ?X ∈ (?A ∩ ?B) |- _ ] => inter_e H\n  | [ |- ?X ∈ (?A ∩ ?B) ] => inter\n  end; auto).\n\nTheorem inter_zero : forall A, A ∩ ∅ = ∅.\nProof.\n  intros. extension.\n  inter_e H. inter.\n  contradiction (Empty_E x).\nQed.\n\nTheorem inter_comm : forall A B, A ∩ B = B ∩ A.\nProof. intros. extension; obvious. Qed.\n\nTheorem inter_assoc : forall A B C, A ∩ (B ∩ C) = (A ∩ B) ∩ C.\nProof. intros. extension; obvious. Qed.\n\nTheorem inter_idem : forall A, A ∩ A = A.\nProof. intros. extension; obvious. Qed.\n\nTheorem inter_incl : forall A B, A ⊆ B ↔ A ∩ B = A.\nProof.\n  intros. split; intros. extension; obvious.\n  unfold Subq. intros. rewrite <- H in H0. inter_e H0.\nQed.\n\nTheorem union_distr : forall A B C, A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C).\nProof. intros. extension; obvious. Qed.\n\nTheorem inter_distr : forall A B C, A ∪ (B ∩ C) = (A ∪ B) ∩ (A ∪ C).\nProof. intros. extension; obvious. Qed.\n\n(* Exercise.  A necessary and sufficient condition that (A ∩ B) ∪ C = A ∩ (B ∪\n   C) is that C ⊆ A.  Observe that the condition has nothing to do with the\n   set B.\n*)\nTheorem union_assoc_ns : forall A B C, (A ∩ B) ∪ C = A ∩ (B ∪ C) ↔ C ⊆ A.\nProof.\n  intros. split; intros.\n  - apply inter_incl.\n    extension.\n    + obvious.\n    + apply BinInter_I. split.\n        assumption.\n        apply extensionality_E in H. inv H.\n          unfold Subq in *.\n          specialize (H1 x).\n          specialize (H2 x).\n          apply BinInter_E in H1.\n            inv H1. auto.\n            apply Union_I with (Y := C).\n              assumption.\n              apply UPair_I2.\n  - rewrite union_distr.\n    extension.\n    + rewrite inter_comm with (B := C).\n      pose (inter_incl C A). inv i.\n      rewrite H1; assumption.\n    + rewrite inter_comm with (B := C) in H0.\n      pose (inter_incl C A). inv i.\n      rewrite H1 in H0; assumption.\nQed.\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/Unions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245994514082, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.6587683591033597}}
{"text": "(*|\n#################################################\nIn Coq, How to construct an element of 'sig' type\n#################################################\n\n:Link: https://stackoverflow.com/q/44967359\n|*)\n\n(*|\nQuestion\n********\n\nWith a simple inductive definition of a type ``A``:\n|*)\n\nRequire Import EqNat. (* .none *)\nInductive A : Set := mkA : nat -> A.\n\n(* get ID of A *)\nDefinition getId (a : A) : nat := match a with mkA n => n end.\n\n(*| And a subtype definition: |*)\n\n(* filter that test ID of *A* is 0 *)\nDefinition filter (a : A) : bool :=\n  if beq_nat (getId a) 0 then true else false.\n\n(* cast bool to Prop *)\nDefinition IstrueB (b : bool) : Prop := if b then True else False.\n\n(* subtype of *A* that only interests those who pass the filter *)\nDefinition subsetA : Set := { a : A | IstrueB (filter a) }.\n\n(*|\nI try this code to cast element of ``A`` to ``subsetA`` when\n``filter`` passes, but failed to convenience Coq that it is a valid\nconstruction for an element of 'sig' type:\n|*)\n\nFail Definition cast (a : A) : option subsetA :=\n  match filter a with\n  | true => Some (exist _ a (IstrueB (filter a)))\n  | false => None\n  end. (* .unfold *)\n\n(*|\nSo, Coq expects an actual proof of type ``IstrueB (filter a)``, but\nwhat I provide there is type ``Prop``.\n\nCould you shed some lights on how to provide such type? thank you.\n|*)\n\n(*|\nAnswer\n******\n\nFirst of all, there is the standard `is_true\n<https://coq.inria.fr/library/Coq.Init.Datatypes.html#is_true>`__\nwrapper. You can use it explicitly like so:\n|*)\n\nReset subsetA. (* .none *)\nDefinition subsetA : Set := { a : A | is_true (filter a) }.\n\n(*| or implicitly using the coercion mechanism: |*)\n\nReset subsetA. (* .none *)\nCoercion is_true : bool >-> Sortclass.\nDefinition subsetA : Set := { a : A | filter a }.\n\n(*|\nNext, non-dependent pattern-mathching on ``filter a`` doesn't\npropagate ``filter a = true`` into the ``true`` branch. You have at\nleast three options:\n\n1. Use tactics to build your ``cast`` function:\n\n  .. coq::\n|*)\n\nDefinition cast (a : A) : option subsetA.\n  destruct (filter a) eqn:prf.\n  - exact (Some (exist _ a prf)).\n  - exact None.\nDefined.\n\n(*|\n2. Use dependent pattern-matching explicitly (search for \"convoy\n   pattern\" on Stackoverflow or in `CDPT\n   <http://adam.chlipala.net/cpdt/>`__):\n\n   .. coq::\n|*)\n\nDefinition cast' (a : A) : option subsetA :=\n  match filter a as fa\n        return (filter a = fa -> option subsetA)\n  with\n  | true => fun prf => Some (exist _ a prf)\n  | false => fun _ => None\n  end eq_refl.\n\n(*|\n3. Use the Program facilities:\n\n   .. coq::\n|*)\n\nRequire Import Coq.Program.Program.\n\nProgram Definition cast'' (a : A) : option subsetA :=\n  match filter a with\n  | true => Some (exist _ a _)\n  | false => None\n  end.\n\n(*|\n----\n\n**A:** There is also ``Is_true`` in ``Bool``.\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/in-coq-how-to-construct-an-element-of-sig-type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.6587683578872916}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Import NAxioms NSub NZSqrt.\n\nModule NSqrtProp (Import A : NAxiomsSig')(Import B : NSubProp A).\n\nModule Import Private_NZSqrt := Nop <+ NZSqrtProp A A B.\n\nLtac auto' := trivial; try rewrite <- neq_0_lt_0; auto using le_0_l.\nLtac wrap l := intros; apply l; auto'.\n\n\n\nLemma sqrt_spec' : forall a, √a*√a <= a < S (√a) * S (√a).\nProof. hammer_hook \"NSqrt\" \"NSqrt.NSqrtProp.sqrt_spec'\".   wrap sqrt_spec. Qed.\n\nDefinition sqrt_unique : forall a b, b*b<=a<(S b)*(S b) -> √a == b\n:= sqrt_unique.\n\nLemma sqrt_square : forall a, √(a*a) == a.\nProof. hammer_hook \"NSqrt\" \"NSqrt.NSqrtProp.sqrt_square\".   wrap sqrt_square. Qed.\n\nDefinition sqrt_le_mono : forall a b, a<=b -> √a <= √b\n:= sqrt_le_mono.\n\nDefinition sqrt_lt_cancel : forall a b, √a < √b -> a < b\n:= sqrt_lt_cancel.\n\nLemma sqrt_le_square : forall a b, b*b<=a <-> b <= √a.\nProof. hammer_hook \"NSqrt\" \"NSqrt.NSqrtProp.sqrt_le_square\".   wrap sqrt_le_square. Qed.\n\nLemma sqrt_lt_square : forall a b, a<b*b <-> √a < b.\nProof. hammer_hook \"NSqrt\" \"NSqrt.NSqrtProp.sqrt_lt_square\".   wrap sqrt_lt_square. Qed.\n\nDefinition sqrt_0 := sqrt_0.\nDefinition sqrt_1 := sqrt_1.\nDefinition sqrt_2 := sqrt_2.\n\nDefinition sqrt_lt_lin : forall a, 1<a -> √a<a\n:= sqrt_lt_lin.\n\nLemma sqrt_le_lin : forall a, √a<=a.\nProof. hammer_hook \"NSqrt\" \"NSqrt.NSqrtProp.sqrt_le_lin\".   wrap sqrt_le_lin. Qed.\n\nDefinition sqrt_mul_below : forall a b, √a * √b <= √(a*b)\n:= sqrt_mul_below.\n\nLemma sqrt_mul_above : forall a b, √(a*b) < S (√a) * S (√b).\nProof. hammer_hook \"NSqrt\" \"NSqrt.NSqrtProp.sqrt_mul_above\".   wrap sqrt_mul_above. Qed.\n\nLemma sqrt_succ_le : forall a, √(S a) <= S (√a).\nProof. hammer_hook \"NSqrt\" \"NSqrt.NSqrtProp.sqrt_succ_le\".   wrap sqrt_succ_le. Qed.\n\nLemma sqrt_succ_or : forall a, √(S a) == S (√a) \\/ √(S a) == √a.\nProof. hammer_hook \"NSqrt\" \"NSqrt.NSqrtProp.sqrt_succ_or\".   wrap sqrt_succ_or. Qed.\n\nDefinition sqrt_add_le : forall a b, √(a+b) <= √a + √b\n:= sqrt_add_le.\n\nLemma add_sqrt_le : forall a b, √a + √b <= √(2*(a+b)).\nProof. hammer_hook \"NSqrt\" \"NSqrt.NSqrtProp.add_sqrt_le\".   wrap add_sqrt_le. Qed.\n\n\n\nInclude NZSqrtUpProp A A B Private_NZSqrt.\n\nEnd NSqrtProp.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Numbers/Natural/Abstract/NSqrt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324587033253, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6587683554551546}}
{"text": "(* \n * Code for The Hoare State Monad (Proof Pearl), Wouter Swierstra\n * Reference: \n *   https://webspace.science.uu.nl/~swier004//publications/2009-tphols.v \n *)\n\nRequire Import Program.\nRequire Import Arith.\nRequire Import List.\nRequire Import Psatz.\n\nInductive Tree (a : Set) : Set :=\n| Leaf : a -> Tree a\n| Node : Tree a -> Tree a -> Tree a.\n\nArguments Leaf [a] _.\nArguments Node [a] _ _.\n\nCompute Node (Leaf 2) (Leaf 1).\n\nModule Sec2_TheStateMonad.\n\n  Fixpoint relabel {a : Set} (t : Tree a) (s : nat) : Tree nat * nat :=\n    match t with\n    | Leaf _ => (Leaf s, 1 + s)\n    | Node l r =>\n        let (l', s') := relabel l s in\n        let (r', s'') := relabel r s' in\n        (Node l' r', s'')\n    end.\n\n  Compute relabel (Node (Leaf 100) (Leaf 34)) 0.\n  Compute relabel (Node (Leaf 123) (Leaf 567)) 0.\n  \n  Definition State (s a : Set) : Type := s -> a * s.\n  Definition ret (s a : Set) : a -> State s a :=\n    fun x => fun s => (x, s).\n  Definition bind (s a b : Set) : State s a -> (a -> State s b) -> State s b :=\n    fun c1 c2 => fun s1 => let (x, s2) := c1 s1 in c2 x s2.\n\n  Arguments ret [s a] _ _.\n  Arguments bind [s a b] _ _ _.\n\n  Notation \"e1 '>>=' e2\" := (bind e1 e2) (at level 80, right associativity).\n  Notation \"e1 '>>' e2\" := (bind e1 (fun _ => e2)) (at level 80, right associativity).\n\n  Definition get (s : Set) : State s s := fun s => (s, s).\n  Definition put (s : Set) : s -> State s unit := fun s => fun _ => (tt, s).\n\n  Arguments get {s}.\n  Arguments put {s}.\n\n  Fixpoint relabelM {a : Set} (t : Tree a) : State nat (Tree nat) :=\n    match t with\n    | Leaf _ => get >>= fun n =>\n               put (S n) >>\n               ret (Leaf n)\n    | Node l r => relabelM l >>= fun l' =>\n                 relabelM r >>= fun r' =>\n                 ret (Node l' r')\n    end.\n\n  Compute relabelM (Node (Leaf 456) (Leaf 123)) 0.\n\nEnd Sec2_TheStateMonad.\n\nModule Sec3_TheChallenge.\n  Import Sec2_TheStateMonad.\n  (* \n   * How can we prove relabelM is correct? \n   * What's the specification of relabelM?\n   *)\n\n  Fixpoint flatten {a : Set} (t : Tree a) : list a :=\n    match t with\n    | Leaf x => x :: nil\n    | Node l r => flatten l ++ flatten r\n    end.\n  \n  Lemma relabelM_correct : forall {a : Set} (t : Tree a) (n : nat),\n      NoDup (flatten (fst (relabelM t n))).\n  Proof. Admitted.\n\n  (* The flatten result tree corresponds to some list *)\n  (* No duplication in this flatten tree *)\n  (* The invariance of tree shape *)\n \nEnd Sec3_TheChallenge.\n\nModule Sec456.\n\n  (* Strong specification: the type of the relabelM function\n   * should capture its behavior.\n   *)\n\n  Definition Pre (s : Set) : Type := s -> Prop.\n  Definition Post (s a : Set) : Type := s -> a -> s -> Prop.\n\n  (* Requires an initial state that satisfies a given precondition.\n   * Guarantees that the resulting pair satisfies a postcondition\n   * relating the initial state (i), resulting value (x), and final state (f).\n   *)\n  Program Definition HoareState (s : Set) (pre : Pre s) (a : Set) (post : Post s a) : Set :=\n    forall i : { t : s | pre t }, { (x, f) : a * s | post i x f }.\n  \n  (* Now defining `ret` and `bind` of HoareState *)\n\n  Definition top {s : Set} : @Pre s := fun s => True.\n\n  Program Definition ret (s : Set) (a : Set) :\n    forall x, HoareState s top a (fun i y f => i = f /\\ y = x) :=\n    fun x => fun s => (x, s).\n\n  (* First try of `bind`:\n   * HoareState1 P1 a Q1 -> (a -> HoareState P2 b Q2) -> HoareStae ... b ...\n   * P2 and Q2 cannot use the result of the first computation, so let's generalize it:\n   * HoareState1 P1 a Q1 -> \n     (forall (x : a), (a -> HoareState (P2 x) b (Q2 x)) -> \n     HoareStae ... b ...\n   *)\n\n  (* What should be the precondition and postcondition of the _composite_ computation (... b ...)?\n     - its precondition should contain the precondition of the _first_ computation:\n         P1 s1\n\n     - it should also contain that the postcondition of the _first_ computation implies\n       the precondition of the _second_ computation:\n         forall x s2, Q1 s1 x s2 -> P2 x s2\n     \n     - Thus combining them obtains the precondition:\n         (fun s1 => P1 s1 /\\ forall x s2, Q1 s1 x s2 -> P2 x s2)\n\n     - its postcondition existentially quantifies the state and value after _first_ computation,\n       so that they satisfies Q1:\n         exists x, exists s2, Q1 s1 x s2\n       \n     - its postcondition should also satisfy the postcondition of the _second_ computation,\n         (fun s1 y s3 => exists x, exists s2, Q1 s1 x s2 /\\ Q2 x s2 y s3)\n   *)\n\n  Program Definition bind : forall s a b P1 P2 Q1 Q2,\n      (HoareState s P1 a Q1) ->\n      (forall (x : a), HoareState s (P2 x) b (Q2 x)) ->\n      HoareState s\n                 (fun s1 => P1 s1 /\\ forall x s2, Q1 s1 x s2 -> P2 x s2)\n                 b\n                 (fun s1 y s3 => exists x, exists s2, Q1 s1 x s2 /\\ Q2 x s2 y s3)\n    := fun s a b P1 P2 Q1 Q2 =>\n       fun c1 c2 s1 => match c1 s1 with (x, s2) => c2 x s2 end.\n  \n  Next Obligation.\n  Proof.\n    apply p0. destruct c1 as [H1 H2]. simpl in *. subst. apply H2.\n  Defined.\n  Next Obligation.\n  Proof with simpl in *.\n    destruct c1 as [H1 H2]... destruct c2 as [[b0 s0] P2rh]...\n    subst. exists x, s2. intuition.\n  Defined.\n  \n  Arguments ret [s a] _ _.\n  Arguments bind [s a b] {P1 P2 Q1 Q2} _ _ _ .\n\n  Notation \"e1 '>>=' e2\" := (bind e1 e2) (at level 80, right associativity).\n  Notation \"e1 '>>' e2\" := (bind e1 (fun _ => e2)) (at level 80, right associativity).\n\n  Program Definition get (s : Set) :\n    HoareState s top s (fun i x f => i = f /\\ x = i)\n    := fun s => (s, s).\n\n  Program Definition put (s : Set) (x : s) :\n    HoareState s top unit (fun _ _ f => f = x)\n    := fun _ => (tt, x).\n\n  Arguments get {s} _.\n  Arguments put {s} _ _.\n\n  (* That's it! *)\n\n  (* Revisiting relabelM *)\n\n  Fixpoint size {a : Set} (t : Tree a) : nat :=\n    match t with\n    | Leaf x => 1\n    | Node l r => size l + size r\n    end.\n  \n  Fixpoint flatten {a : Set} (t : Tree a) : list a :=\n    match t with\n    | Leaf x => x :: nil\n    | Node l r => flatten l ++ flatten r\n    end.\n\n  Fixpoint seq (x n : nat) : list nat :=\n    match n with\n    | 0 => nil\n    | S k => x :: seq (S x) k\n    end.\n\n  Compute seq 5 10.\n  Compute seq 0 8.\n\n  Lemma SeqSplit : forall y x z, seq x (y + z) = seq x y ++ seq (x + y) z.\n  Proof with simpl; auto.\n    induction y... intros x z... rewrite IHy, plus_Snm_nSm...\n  Qed.\n\n  Program Fixpoint relabelM {a : Set} (t : Tree a) :\n    HoareState nat top (Tree nat)\n               (fun i t f => f = i + size t /\\ flatten t = seq i (size t))\n    := match t with\n       | Leaf _ => get >>= fun n =>\n                  put (S n) >>\n                  ret (Leaf n)\n       | Node l r => relabelM l >>= fun l' =>\n                    relabelM r >>= fun r' =>\n                    ret (Node l' r')\n       end.\n  Next Obligation.\n  Proof. intuition. Defined.\n  Next Obligation.\n  Proof with simpl in *; auto.\n    destruct_call (bind (s := nat))...\n    clear relabelM l r H.\n    destruct_conjs...\n    (* now we must prove that the postcondition holds for the tree \n     * Node l r under the assumption that it holds for recursive \n     * calls to l and r *)   \n    rename y into l, H1 into r, H into lState, H3 into rState.\n    rename H0 into sizeL, H4 into sizeR, H2 into flattenL, H7 into flattenR.\n    rename H5 into finalState, H6 into finalRes.\n    rewrite finalRes.\n    split...\n    - lia.\n    - rewrite flattenL, flattenR, sizeL, SeqSplit...\n  Defined.\n\n  (* Section 6 *)\n  \n  (* How can we prove the result t satisfies Nodup (flatten t)? *)\n  (* We need to weaken the postcondition and \n     strengthen the precondition explicitly, by using `do` *)\n  \n  Program Definition do (s a : Set) (P1 P2 : Pre s) (Q1 Q2 : Post s a) :\n    (forall i, P2 i -> P1 i) -> (forall i x f, Q1 i x f -> Q2 i x f) ->\n    HoareState s P1 a Q1 -> HoareState s P2 a Q2\n    := fun str wkn c => c.\n  Next Obligation.\n  Proof with simpl; auto.\n    destruct_call c... destruct x0 as [x1 f]...\n  Defined.\n\n  (* See complete proof in\n     https://webspace.science.uu.nl/~swier004//publications/2009-tphols.v \n   *)\n  \nEnd Sec456.\n\n(* Some following related work:\n   - F*\n   - Dijkstra Monads for Free (POPL 17)\n   - Dijkstra Monads for All (ICFP 19)\n   - A Predicate Transformer Semantics for Effects (ICFP 19)\n   ...\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/HoareState.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749422, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.6587626552777194}}
{"text": "Require Import List.\nRequire Import String.\nOpen Scope string_scope.\n\nRequire Import StructTactics.\n\nInductive expr : Set :=\n| Var : string -> expr\n| App : expr -> expr -> expr\n| Lam : string -> expr -> expr.\n\nCoercion Var : string >-> expr.\n\nNotation \"X @ Y\" := (App X Y) (at level 49).\nNotation \"\\ X , Y\" := (Lam X Y) (at level 50).\n\nCheck (\\\"x\", \\\"y\", \"x\").\nCheck (\\\"x\", \\\"y\", \"y\").\nCheck ((\\\"x\", \"x\" @ \"x\") @ (\\\"x\", \"x\" @ \"x\")).\n\n(** e1[e2/x] *)\nFixpoint subst (e : expr) (from : string) (to : expr)  : expr :=\n  match e with\n  | Var x => if string_dec from x then to else e\n  | App e1 e2 => App (subst e1 from to) (subst e2 from to)\n  | Lam x e => if string_dec from x then e else Lam x (subst e from to)\n  end.\n\n(**\nCall By Name\n<<\n       e1 --> e1'\n  ---------------------\n    e1 e2 --> e1' e2\n\n  -----------------------------\n    (\\x. e1) e2 --> e1[e2/x]\n>>\n*)\n\nInductive step_cbn : expr -> expr -> Prop :=\n| CBN_crunch:\n    forall e1 e1' e2,\n      step_cbn e1 e1' ->\n      step_cbn (App e1 e2) (App e1' e2)\n| CBN_subst:\n    forall x e1 e2,\n      step_cbn (App (Lam x e1) e2) (subst e1 x e2).\n\nNotation \"e1 ==> e2\" := (step_cbn e1 e2) (at level 51).\n\nLemma step_cbn_det:\n  forall e e1,\n  e ==> e1 ->\n  forall e2,\n  e ==> e2 ->\n  e1 = e2.\nProof.\n  induction 1; intros.\n  - invc H0.\n    + f_equal. apply IHstep_cbn; auto.\n    + invc H.\n  - invc H.\n    + invc H3.\n    + reflexivity.\nQed.\n\n(**\nCall By Value\n<<\n\nv ::= \\ x . e\n\n       e1 --> e1'\n  ---------------------\n    e1 e2 --> e1' e2\n\n       e2 --> e2'\n  ---------------------\n    v e2 --> v e2'\n\n  -----------------------------\n    (\\x. e1) v --> e1[v/x]\n>>\n*)\n\nInductive value : expr -> Prop :=\n| VLam :\n    forall x e,\n      value (Lam x e).\n\nInductive step_cbv : expr -> expr -> Prop :=\n| CBV_crunch_l:\n    forall e1 e1' e2,\n      step_cbv e1 e1' ->\n      step_cbv (App e1 e2) (App e1' e2)\n| CBV_crunch_r:\n    forall v e2 e2',\n      value v ->\n      step_cbv e2 e2' ->\n      step_cbv (App v e2) (App v e2')\n| CBV_subst:\n    forall x e1 v,\n      value v ->\n      step_cbv (App (Lam x e1) v) (subst e1 x v).\n\nNotation \"e1 --> e2\" := (step_cbv e1 e2) (at level 51).\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/LC/drafts/L01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.6587626536046542}}
{"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(* ** Luca's theorem *)\n\nRequire Import Arith Nat Lia List.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac gcd prime binomial sums rel_iter.\n\nFrom Undecidability.H10.ArithLibs \n  Require Import Zp.\n\nSet Implicit Arguments.\n\nLocal Notation power := (mscal mult 1).\nLocal Notation expo := (mscal mult 1).\n\nSection fact.\n\n  Let factorial_cancel n a b : fact n * a = fact n * b -> a = b.\n  Proof.\n    apply Nat.mul_cancel_l.\n    generalize (fact_gt_0 n); intro; lia.\n  Qed.\n  \n  Notation Π := (msum mult 1).\n\n  Notation mprod_an := (fun a n => Π n (fun i => i+a)).\n\n  Fact mprod_factorial n : fact n = mprod_an 1 n.\n  Proof.\n    induction n as [ | n IHn ].\n    + rewrite msum_0; auto.\n    + rewrite msum_plus1; auto.\n      rewrite Nat.mul_comm, <- IHn, fact_S.\n      f_equal; lia.\n  Qed.\n\n  Variable (p : nat) (Hp : p <> 0).\n\n  Notation \"〚 x 〛\" := (nat2Zp Hp x).\n\n  Let expo_p_cancel n a b : expo n p * a = expo n p * b -> a = b.\n  Proof.\n    apply Nat.mul_cancel_l.\n    generalize (power_ge_1 n Hp); intros; lia.\n  Qed.\n\n  Fact mprod_factorial_Zp i n :〚mprod_an (i*p+1) n〛=〚fact n〛.\n  Proof.\n    rewrite mprod_factorial.\n    induction n as [ | n IHn ].\n    + do 2 rewrite msum_0; auto.\n    + do 2 (rewrite msum_plus1; auto).\n      do 2 rewrite nat2Zp_mult; f_equal; auto.\n      apply nat2Zp_inj.\n      rewrite (Nat.add_comm n), <- Nat.add_assoc, Nat.add_comm.\n      rewrite <- rem_plus_div; auto.\n      * f_equal; lia.\n      * apply divides_mult, divides_refl.\n  Qed.\n\n  Notation φ := (fun n r => mprod_an (n*p+1) r).\n  Notation Ψ := (fun n => Π n (fun i => mprod_an (i*p+1) (p-1))).\n\n  Let phi_Zp_eq n r :〚φ n r〛=〚fact r〛.\n  Proof. apply mprod_factorial_Zp. Qed.\n\n  Fact mprod_factorial_mult n : fact (n*p) = expo n p * fact n * Ψ n.\n  Proof using Hp.\n    induction n as [ | n IHn ].\n    + rewrite Nat.mul_0_l, msum_0, mscal_0, fact_0; auto.\n    + replace (S n*p) with (n*p+p) by ring.\n      rewrite mprod_factorial, msum_plus, <- mprod_factorial; auto.\n      replace p with (S (p-1)) at 2 by lia.\n      rewrite msum_plus1; auto.\n      rewrite <- Nat.add_assoc.\n      replace (p-1+1) with p by lia.\n      replace (n*p+p) with ((S n)*p) by ring.\n      rewrite mscal_S, fact_S, msum_S.\n      rewrite IHn.\n      repeat rewrite Nat.mul_assoc.\n      rewrite (Nat.mul_comm _ p).\n      repeat rewrite <- Nat.mul_assoc.\n      do 2 f_equal.\n      rewrite (Nat.mul_comm (S n)).\n      repeat rewrite <- Nat.mul_assoc; f_equal.\n      repeat rewrite Nat.mul_assoc; f_equal.\n      rewrite msum_ext with (f := fun i => n*p+i+1)\n                            (g := fun i => i+(n*p+1)).\n      2: intros; ring. \n      rewrite <- msum_plus1; auto.\n  Qed.\n \n  Lemma mprod_factorial_euclid n r : fact (n*p+r) = expo n p * fact n * φ n r * Ψ n.\n  Proof using Hp.\n    rewrite mprod_factorial, msum_plus; auto.\n    rewrite <- mprod_factorial.\n    rewrite msum_ext with (f := fun i => n*p+i+1)\n                          (g := fun i => i+(n*p+1)).\n    2: intros; ring. \n    rewrite mprod_factorial_mult; auto; ring.\n  Qed.\n\n  Notation Zp := (Zp_zero Hp).\n  Notation Op := (Zp_one Hp).\n  Notation \"∸\" := (Zp_opp Hp).\n  Infix \"⊗\" := (Zp_mult Hp) (at level 40, left associativity).\n  Notation expoZp := (mscal (Zp_mult Hp) (Zp_one Hp)).\n\n  Hint Resolve Nat_mult_monoid : core.\n\n  Let Psi_Zp_eq n :〚Ψ n〛= expoZp n〚fact (p-1)〛.\n  Proof.\n    induction n as [ | n IHn ].\n    + rewrite msum_0, mscal_0; auto.\n    + rewrite msum_plus1, nat2Zp_mult.\n      rewrite mscal_plus1; auto.\n      2: apply Zp_mult_monoid.\n      2: apply Nat_mult_monoid.\n      f_equal; auto.\n  Qed.\n\n  Hypothesis (Hprime : prime p).\n\n  Let phi_Zp_invertible n r : r < p -> Zp_invertible Hp 〚φ n r〛.\n  Proof.\n    intros H; simpl; rewrite phi_Zp_eq.\n    apply Zp_invertible_factorial; auto.\n  Qed.\n\n  Let Psi_Zp_invertible n : Zp_invertible Hp 〚Ψ n〛.\n  Proof.\n    simpl; rewrite (Psi_Zp_eq n).\n    apply Zp_expo_invertible, Zp_invertible_factorial; auto; lia.\n  Qed.\n\n  (* rewrite the binomial theorem\n\n               fact k * fact (n-k) * binomial n k = fact n   \n\n      when      \n\n         k = K*p + k0\n         n = N*p + n0\n\n      with\n       \n      1)  K <= N & k0 <= n0\n   \n      we get n-k = (N-K)*p + (n0-k0) and\n\n        expo K     p * fact K     * φ K      k0     * Ψ K\n      .* expo (N-K) p * fact (N-K) * φ (N-K) (n0-k0) * Ψ (N-K)\n      .* binomial n k \n      = expo N p     * fact N     * φ N      n0     * Ψ N.\n\n      hence, simplifying by expo N p  we get\n\n        fact K * fact (N-K) * φ K k0 * Ψ K * φ (N-K) (n0-k0) * Ψ (N-K) * binomial n k = fact N * φ N n0 * Ψ N. \n\n      then in Z/Zp we derive (modulo Wilson's theorem, unnecessary here〚fact (p-1)〛=〚-1〛) \n\n       〚fact K〛⊗〚fact (N-K)〛⊗〚fact k0〛⊗〚-1〛^K⊗〚fact (n0-k0)〛⊗〚-1〛^(N-K)⊗〚binomial n k〛\n      =〚fact N〛⊗〚fact n0〛⊗〚-1〛^N\n\n        that we combine with 〚fact K〛⊗〚fact (N-K)〛⊗〚binomial N K〛=〚fact N〛\n                        and  〚fact k0〛⊗〚fact (n0-k0)〛⊗〚binomial n0 k0〛=〚fact n0〛\n\n        to derive the result:〚binomial n k 〛=〚binomial N K〛⊗〚binomial n0 k0〛\n\n      with \n \n      2) K < N & n0 < k0\n\n      we have n-k = (N-(K+1))*p + (p-(k0-n0)) and\n\n        expo K         p * fact K         * φ K          k0         * Ψ K\n      .* expo (N-(K+1)) p * fact (N-(K+1)) * φ (N-(K+1)) (p-(k0-n0)) * Ψ (N-(K+1))\n      .* binomial n k \n      = expo N p     * fact N     * φ N      n0     * Ψ N.\n\n      hence\n \n         fact K * φ K k0 * Ψ K * fact (N-(K+1)) * φ (N-(K+1)) (p-(k0-n0)) * Ψ (N-(K+1)) * binomial n k \n       = p * ....\n\n      then in Z/Zp all the left factor are invertible except binomial n k which must thus be〚0〛 *)\n\n  Section binomial_without_p_not_zero.\n\n    Variable (n N n0 k K k0 : nat) (Hn : n = N*p+n0) (Hk : k = K*p+k0) (H1 : K <= N) (H2 : k0 <= n0).\n\n    Let Hkn : k <= n.\n    Proof.\n      rewrite Hn, Hk.\n      replace N with (K+(N-K)) by lia.\n      rewrite Nat.mul_add_distr_r.\n      generalize ((N-K)*p); intros; lia.\n    Qed.\n   \n    Let Hnk : n - k = (N-K)*p+(n0-k0).\n    Proof.\n      rewrite Hn, Hk, Nat.mul_sub_distr_r.\n      cut (K*p <= N*p).\n      + generalize (K*p) (N*p); intros; lia.\n      + apply Nat.mul_le_mono; auto.\n    Qed.\n  \n    Fact binomial_wo_p : φ K k0 * Ψ K * φ (N-K) (n0-k0) * Ψ (N-K) * binomial n k \n                       = binomial N K * φ N n0 * Ψ N.\n    Proof using Hkn.\n      apply (factorial_cancel (N-K)); repeat rewrite Nat.mul_assoc.\n      rewrite (Nat.mul_comm (fact _) (binomial _ _)).\n      apply (factorial_cancel K); repeat rewrite Nat.mul_assoc.\n      rewrite (Nat.mul_comm (fact _) (binomial _ _)).\n      rewrite <- binomial_thm; auto.\n      apply expo_p_cancel with N.\n      repeat rewrite Nat.mul_assoc.\n      rewrite <- mprod_factorial_euclid, <- Hn.\n      rewrite binomial_thm with (1 := Hkn).\n      rewrite Hnk. \n      rewrite Hk at 3.\n      replace N with (K+(N-K)) at 1 by lia.\n      rewrite power_plus.\n      do 2 rewrite mprod_factorial_euclid.\n      ring.\n    Qed.\n\n    Hypothesis (Hn0 : n0 < p).\n\n    Hint Resolve Zp_mult_monoid : core.\n\n    Fact binomial_Zp_prod :〚binomial n k〛=〚binomial N K〛⊗〚binomial n0 k0〛.\n    Proof using Hkn Hn0 Hprime.\n      generalize binomial_wo_p; intros G.\n      apply f_equal with (f := nat2Zp Hp) in G.\n      repeat rewrite nat2Zp_mult in G.\n      repeat rewrite Psi_Zp_eq in G.\n      repeat rewrite phi_Zp_eq in G.\n      rewrite binomial_thm with (1 := H2) in G.\n      repeat rewrite nat2Zp_mult in G.\n      rewrite (Zp_mul_comm _ _〚 fact k0 〛) in G.\n      repeat rewrite Zp_mul_assoc in G.\n      rewrite (Zp_mul_comm _ _〚 fact k0 〛) in G.\n      repeat rewrite <- Zp_mul_assoc in G.\n      apply Zp_invertible_cancel_l in G.\n      2: apply Zp_invertible_factorial; auto; lia.\n      repeat rewrite Zp_mul_assoc in G.\n      do 2 rewrite (Zp_mul_comm _ _〚 fact _ 〛) in G.\n      repeat rewrite <- Zp_mul_assoc in G.\n      apply Zp_invertible_cancel_l in G.\n      2: apply Zp_invertible_factorial; auto; lia.\n      repeat rewrite Zp_mul_assoc in G.\n      rewrite <- mscal_plus in G; auto.\n      replace (K+(N-K)) with N in G by lia.\n      rewrite (Zp_mul_comm _ _ (expoZp _ _)) in G.\n      apply Zp_invertible_cancel_l in G; trivial.\n      apply Zp_expo_invertible, Zp_invertible_factorial; auto; lia.\n    Qed.\n\n  End binomial_without_p_not_zero.\n\n  Section binomial_without_p_zero.\n\n    Variable (n N n0 k K k0 : nat) (Hn : n = N*p+n0) (Hk : k = K*p+k0) \n             (H1 : K < N) (H2 : n0 < k0) (Hk0 : k0 < p).\n\n    Let H3 : p - (k0-n0) < p.    Proof. lia. Qed.\n    Let H4 : S (N-1) = N.        Proof. lia. Qed.\n    Let H5 : N-1 = K+(N-(K+1)).  Proof. lia. Qed.\n    Let H6 : N = K+1+(N-(K+1)).  Proof. lia. Qed.\n    Let HNK : N-K = S (N-(K+1)). Proof. lia. Qed.\n\n    Let Hkn : k <= n.\n    Proof.\n      rewrite Hn, Hk, H6.\n      do 2 rewrite Nat.mul_add_distr_r.\n      generalize ((N-(K+1))*p); clear H3 H4 H5 H6 HNK; intros; lia.\n    Qed.\n   \n    Let Hnk : n - k = (N-(K+1))*p+(p-(k0-n0)).\n    Proof.\n      rewrite Hn, Hk, Nat.mul_sub_distr_r.\n      cut ((K+1)*p <= N*p).\n      + rewrite Nat.mul_add_distr_r.\n        generalize (K*p) (N*p); clear H3 H4 H5 H6 HNK Hkn; intros; lia.\n      + apply Nat.mul_le_mono; auto; clear H3 H4 H5 H6 HNK Hkn; lia.\n    Qed.\n\n    Fact binomial_with_p : fact K * fact (N-(K+1)) * φ K k0 * Ψ K * φ (N-(K+1)) (p-(k0-n0)) * Ψ (N-(K+1)) * binomial n k \n                         = p * fact N * φ N n0 * Ψ N.\n    Proof using Hkn.\n      apply expo_p_cancel with (N-1).\n      repeat rewrite Nat.mul_assoc.\n      rewrite (Nat.mul_comm (expo _ _) p).\n      rewrite <- mscal_S.\n      rewrite H4, <- mprod_factorial_euclid, <- Hn.\n      rewrite binomial_thm with (1 := Hkn).\n      rewrite Hnk.\n      rewrite Hk at 3.\n      do 2 rewrite mprod_factorial_euclid.\n      rewrite H5 at 1.\n      rewrite power_plus.\n      ring.\n    Qed.\n\n    Fact binomial_with_p' : φ K k0 * Ψ K * φ (N-(K+1)) (p-(k0-n0)) * Ψ (N-(K+1)) * binomial n k \n                          = p * binomial N K * (N-K) * φ N n0 * Ψ N.\n    Proof using Hkn.\n      apply (factorial_cancel (N-(K+1))); repeat rewrite Nat.mul_assoc.\n      apply (factorial_cancel K); repeat rewrite Nat.mul_assoc.\n      rewrite binomial_with_p.\n      rewrite binomial_thm with (n := N) (p := K).\n      2: { apply Nat.lt_le_incl; auto. }\n      rewrite HNK at 1.\n      rewrite fact_S.\n      rewrite <- HNK.\n      ring.\n    Qed.\n \n    Fact binomial_Zp_zero :〚binomial n k〛= Zp.\n    Proof using Hkn Hprime.\n      generalize binomial_with_p'; intros G.\n      apply f_equal with (f := nat2Zp Hp) in G.\n      repeat rewrite nat2Zp_mult in G.\n      rewrite nat2Zp_p in G.\n      repeat rewrite Zp_mult_zero in G.\n      apply Zp_invertible_eq_zero in G; auto.\n      repeat (apply Zp_mult_invertible; auto).\n    Qed.\n\n  End binomial_without_p_zero.\n\nEnd fact.\n\nSection lucas_lemma.\n\n  (* https://math.stackexchange.com/questions/1463758/proof-of-lucas-theorem-without-the-polynomial-hint *)\n\n  Variables (p : nat) (Hprime : prime p).\n\n  Let Hp : p <> 0.\n  Proof.\n    generalize (prime_ge_2 Hprime); intro; lia.\n  Qed.\n\n  Variables (n N n0 k K k0 : nat)\n            (G1 : n = N*p+n0)  (G2 : n0 < p)\n            (G3 : k = K*p+k0)  (G4 : k0 < p).\n\n  Let choice : (K <= N  /\\ k0 <= n0)\n            \\/ (n0 < k0 /\\ K < N)\n            \\/ ((n0 < k0 \\/ N < K) /\\ n < k).\n  Proof.\n    destruct (le_lt_dec k n) as [ H0 | H0 ];\n    destruct (le_lt_dec k0 n0) as [ H1 | H1 ];\n    destruct (le_lt_dec K N) as [ H2 | H2 ]; try lia.\n    + do 2 right; split; auto.\n      rewrite G1, G3.\n      replace K with (N+1+(K-N-1)) by lia.\n      do 2 rewrite Nat.mul_add_distr_r.\n      generalize ((K-N-1)*p); intros; lia.\n    + destruct (eq_nat_dec N K); try lia.\n    + do 2 right; split; auto.\n      rewrite G1, G3.\n      replace K with (N+1+(K-N-1)) by lia.\n      do 2 rewrite Nat.mul_add_distr_r.\n      generalize ((K-N-1)*p); intros; lia.\n  Qed.\n\n  Theorem lucas_lemma : rem (binomial n k) p = rem (binomial N K * binomial n0 k0) p.\n  Proof using choice.\n    destruct choice as [ (H1 & H2) \n                     | [ (H1 & H2)\n                       | (H1 & H2) ] ]; clear choice.\n    3: { rewrite binomial_gt with (1 := H2).\n         f_equal.\n         destruct H1 as [ H1 | H1 ]; \n           rewrite binomial_gt with (1 := H1); ring. }\n    + apply nat2Zp_inj with (Hp := Hp).\n      rewrite nat2Zp_mult.\n      apply binomial_Zp_prod; auto.\n    + rewrite binomial_gt with (1 := H1).\n      rewrite Nat.mul_0_r.\n      apply nat2Zp_inj with (Hp := Hp).\n      rewrite nat2Zp_zero.\n      apply binomial_Zp_zero with (2 := G1) (3 := G3); auto.\n  Qed.\n\nEnd lucas_lemma.\n\n(* Eval compute in binomial 3 0. *)\n\nSection lucas_theorem.\n\n  Variable (p : nat) (Hp : prime p).\n\n  Implicit Types (l m : list nat).\n\n  (* base_p [x0;x1;x2;...] =  x0 + x1*p + x2*p² ...*)\n\n  Notation base_p := (expand p).\n\n  Fixpoint binomial_p l :=\n    match l with\n      | nil  => fix loop m := match m with\n        | nil  => 1\n        | y::m => binomial 0 y * loop m\n      end\n      | x::l => fun m => match m with\n        | nil   => binomial x 0 * binomial_p l nil \n        | y::m  => binomial x y * binomial_p l m\n      end\n    end.\n\n  Fact binomial_p_fix00 : binomial_p nil nil = 1.\n  Proof. auto. Qed.\n\n  Fact binomial_p_fix01 y m : binomial_p nil (y::m) = binomial 0 y * binomial_p nil m.\n  Proof. auto. Qed.\n\n  Fact binomial_p_fix10 x l : binomial_p (x::l) nil = binomial x 0 * binomial_p l nil.\n  Proof. auto. Qed.\n\n  Fact binomial_p_fix11 x l y m : binomial_p (x::l) (y::m) = binomial x y * binomial_p l m.\n  Proof. auto. Qed.\n\n  (* This is Luca's thm as described eg on Wikipedia\n\n      if p is prime\n      and x = x0 + x1*p + x2*p² ...\n      and y = y0 + y1*p + y2*p² ...\n\n      then the identity \n \n         binomial x y = binomial x0 y0 * binomial x1 y1 * binomial x2 y2 * ...\n\n      holds modulo p\n\n   *)\n\n  Theorem lucas_theorem (l m : list nat) : \n         Forall (fun i => i < p) l               (* digits must be less than p*)\n      -> Forall (fun i => i < p) m               (* digits must be less than p*)\n      -> rem (binomial (base_p l) (base_p m)) p \n       = rem (binomial_p l m) p.\n  Proof using Hp.\n    intros H; revert H m.\n    induction 1 as [ | x l H1 H2 IH2 ];\n    induction 1 as [ | y m H3 H4 IH4 ].\n    + simpl; auto.\n    + rewrite binomial_p_fix01; simpl base_p.\n      rewrite <- rem_mult_rem, <- IH4, rem_mult_rem, \n              (Nat.mul_comm p), Nat.add_comm, (Nat.mul_comm (binomial _ _)).\n      apply lucas_lemma; auto; simpl; lia.\n    + rewrite binomial_p_fix10; simpl base_p.\n      rewrite <- rem_mult_rem, <- IH2, rem_mult_rem; auto.\n      rewrite (Nat.mul_comm p), Nat.add_comm, (Nat.mul_comm (binomial _ _)).\n      apply lucas_lemma; auto; simpl; lia.\n    + rewrite binomial_p_fix11; simpl base_p.\n      rewrite <- rem_mult_rem, <- IH2, rem_mult_rem; auto.\n      rewrite !(Nat.mul_comm p), !(Nat.add_comm _ (_ * _)), (Nat.mul_comm (binomial _ _)).\n      apply lucas_lemma; auto; simpl; lia.\n  Qed.\n\nEnd lucas_theorem.\n\n(* Check lucas_theorem. *)\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/H10/ArithLibs/luca.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6587550220600815}}
{"text": "Require Import Utf8.\nRequire Import Reals.\nRequire Import Lebesgue.\nRequire Import FunctionalExtensionality.\n\nSet Implicit Arguments.\n\n(** Entropy is the source of all randomness in an evaluation. The particular\nrepresentation we choose is the Hilbert cube #(ℕ → [0, 1])#. In particular,\nthe properties we use on it are that an entropy source can be split into two\nentropy sources through the operations [πL] and [πR], which are defined here\nand axiomatized to be IID in [integration_πL_πR]. When it actually comes to\nusing an entropy [t], it is also convenient to split it into arbitrarily many\nindepent parts, as (π 0 t), (π 1 t), ... *)\n\nDefinition entropy := nat → { r : R | (0 ≤ r ≤ 1)%R }.\n\n(** The projection functions don't muck with any real numbers, just shuffle\nindices around. [πL_n] and the like are the exact index shuffling needed for\n[πL] and the like. *)\nDefinition πL (t : entropy) : entropy := λ n, t (n + n)%nat.\nDefinition πR (t : entropy) : entropy := λ n, t (S (n + n))%nat.\nNotation πU t := (proj1_sig (πL t 0%nat)).\n\n(** [join] is the inverse of projections, that is [t = join (πL t) (πR t)].\nThis is later proved as [join_πL_πR]. This is finally automated in the tactic\n[π_join]. *)\nDefinition join (tL tR : entropy) : entropy :=\nfun n =>\n  if Nat.even n\n  then tL (Nat.div2 n)\n  else tR (Nat.div2 n).\n\nLemma πL_join tL tR : πL (join tL tR) = tL.\nProof.\nextensionality n.\nunfold πL, join.\nassert (Nat.even (n + n) = true). {\n  induction n; simpl; auto.\n  replace (n + S n)%nat with (S (n + n)); auto.\n}\nrewrite H.\nf_equal.\nfold (Nat.double n).\nrewrite Nat.double_twice.\napply Nat.div2_double.\nQed.\n\nLemma πR_join tL tR : πR (join tL tR) = tR.\nProof.\nextensionality n.\nunfold πR, join.\nassert (Nat.even (S (n + n)) = false). {\n  induction n; simpl; auto.\n  replace (n + S n)%nat with (S (n + n)); auto.\n}\nrewrite H.\nf_equal.\nfold (Nat.double n).\nrewrite Nat.double_twice.\napply Nat.div2_succ_double.\nQed.\n\nLemma join_πL_πR t : join (πL t) (πR t) = t.\nProof.\nextensionality n.\nunfold join, πL, πR.\ndestruct (Nat.Even_or_Odd n). {\n  rewrite (proj2 (Nat.even_spec n)); auto.\n\n  f_equal.\n  fold (Nat.double (Nat.div2 n)).\n  rewrite <- Div2.even_double; auto.\n  apply Even.even_equiv; auto.\n} {\n  pose proof (proj2 (Nat.odd_spec n) H).\n  rewrite <- Nat.negb_even in H0.\n  apply Bool.negb_true_iff in H0.\n  rewrite H0.\n\n  f_equal.\n  change (S (Nat.double (Nat.div2 n)) = n).\n  rewrite <- Div2.odd_double; auto.\n  apply Even.odd_equiv; auto.\n}\nQed.\n\nFixpoint π (n : nat) (t : entropy) : entropy :=\nmatch n with\n| O => πL t\n| S n' => π n' (πR t)\nend.\nArguments π _ _ _ : simpl never.\n\nFixpoint π_leftover (n : nat) (t : entropy) : entropy :=\nmatch n with\n| O => t\n| S n' => π_leftover n' (πR t)\nend.\nArguments π_leftover _ _ _ : simpl never.\n\nLemma π_O_join (tl tr : entropy) : π 0 (join tl tr) = tl.\nProof.\napply πL_join.\nQed.\n\nLemma π_S_join (n : nat) (tl tr : entropy) : π (S n) (join tl tr) = π n tr.\nProof.\nunfold π.\nfold π.\nrewrite πR_join.\nauto.\nQed.\n\nLtac π_join := repeat rewrite ?π_O_join, ?π_S_join in *.\n\n(** Axiomatize the stock measure on traces. *)\n\n(** Assume that [entropy] has a probability measure on it *)\nAxiom μentropy : Meas entropy.\nAxiom μentropy_is_a_probability_measure : μentropy full_event = 1.\nAxiom μentropy_is_σ_finite : σ_finite μentropy.\n\n(** This axiom states that entropy can be split into 2 IID entropies. *)\nAxiom integration_πL_πR : ∀ (g : entropy → entropy → R⁺),\n∫ (fun t => g (πL t) (πR t)) μentropy =\n∫ (fun tL => ∫ (fun tR => g tL tR) μentropy) μentropy.\n\nAxiom integration_πU_lebesgue : ∀ (f : R → R⁺),\n∫ (λ (t : entropy), f (proj1_sig (t 0%nat))) μentropy =\n∫ (λ r, f r * (if Rinterval_dec 0 1 r then 1 else 0)) lebesgue_measure.\n\n(** Use the fact that [μentropy] is a probability measure to lift constant\nfunctions out of integrals. *)\nLemma integration_const_entropy :\n∀ (v : R⁺) (f : entropy → R⁺),\n(∀ x, f x = v) → ∫ f μentropy = v.\nProof.\nintros.\nreplace f with (fun x => f x * 1) by (extensionality x; ring).\nsetoid_rewrite H.\nrewrite integration_of_const with (r := v).\n1: {\n  rewrite μentropy_is_a_probability_measure.\n  ring.\n}\nintro; ring.\nQed.\n\n(** A particular entropy value that is an infinite sequence of 0's. *)\nDefinition entropy0 : entropy.\nProof.\nintro n.\nrefine (exist _ 0%R _).\nsplit.\n+ right; ring. \n+ left; prove_sup.\nDefined.", "meta": {"author": "yizhouzhang", "repo": "rrr-popl2022-coq", "sha": "cef22234d660de992f89e151a394e556ddd84831", "save_path": "github-repos/coq/yizhouzhang-rrr-popl2022-coq", "path": "github-repos/coq/yizhouzhang-rrr-popl2022-coq/rrr-popl2022-coq-cef22234d660de992f89e151a394e556ddd84831/coq-src/RRR/Lang/Entropy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6587548708733466}}
{"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(* ** Matric computation *)\n\nRequire Import Arith ZArith.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac gcd prime binomial sums.\n\nSet Implicit Arguments.\n\nSection rings.\n\n  Variable (R : Type) (Rzero Rone : R) (Rplus Rmult Rminus : R -> R -> R) (Ropp : R -> R)\n           (R_is_ring : ring_theory Rzero Rone Rplus Rmult Rminus Ropp eq). \n\n  Infix \"⊕\" := Rplus (at level 50, left associativity).\n  Infix \"⊗\" := Rmult (at level 40, left associativity).\n\n  Notation z := Rzero.\n  Notation o := Rone.\n  Notation \"∸\" := Ropp.\n\n  (* ⊕  ⊗  ∸ *)\n\n  (* We use the magical parameterized ring tactic *)\n\n  Add Ring Rring : R_is_ring.\n\n  (* ⊕  ⊗  ∸ *)\n\n  (*   ( a b )   <-> (a,b,c,d) \n       ( c d )                    *)\n\n  Definition M22 := (R * R * R * R)%type.\n  Definition ID_22 : M22 := (o,z,z,o).\n  Definition ZE_22 : M22 := (z,z,z,z).\n\n  Definition PL22 : M22 -> M22 -> M22.\n  Proof using Rplus.\n    intros (((a,b),c),d) (((a',b'),c'),d').\n    exact (a⊕a',b⊕b',\n           c⊕c',d⊕d').\n  Defined.\n\n  Local Infix \"⊞\" := PL22 (at level 50, left associativity).\n \n  Definition MI22 : M22 -> M22.\n  Proof using Ropp.\n    intros (((a,b),c),d).\n    exact (∸a,∸b,\n           ∸c,∸d).\n  Defined.\n\n  Local Notation \"⊟\" := MI22.\n\n  Fact M22_equal (a b c d a' b' c' d' : R) : a = a' -> b = b' -> c = c' -> d = d' -> (a,b,c,d) = (a',b',c',d').\n  Proof. intros; subst; trivial. Qed.\n\n  Fact M22plus_zero : forall m, ZE_22 ⊞ m = m.\n  Proof using R_is_ring. \n    intros (((a,b),c),d); apply M22_equal; ring.\n  Qed.\n\n  Fact M22add_comm  : forall x y, x ⊞ y = y ⊞ x.\n  Proof using R_is_ring.\n    intros (((a,b),c),d) (((a',b'),c'),d'); apply M22_equal; ring.\n  Qed.\n\n  Fact M22add_assoc  : forall x y u, x ⊞ (y ⊞ u) = x ⊞ y ⊞ u.\n  Proof using R_is_ring.\n    intros (((a,b),c),d) (((a',b'),c'),d') (((a'',b''),c''),d''); simpl; apply M22_equal; ring. \n  Qed.\n\n  Fact M22minus : forall x, x ⊞ ⊟ x = ZE_22.\n  Proof using R_is_ring.\n    intros (((a,b),c),d); apply M22_equal; ring.\n  Qed.\n\n  Fact M22plus_cancel : forall x a b, x ⊞ a = x ⊞ b -> a = b.\n  Proof using R_is_ring.\n    intros x a b H.\n    rewrite <- (M22plus_zero a), <- (M22minus x), (M22add_comm x), \n            <- M22add_assoc, H, M22add_assoc,\n            (M22add_comm _ x), M22minus, M22plus_zero.\n    trivial.\n  Qed.\n\n  Theorem M22plus_monoid : monoid_theory PL22 ZE_22.\n  Proof using R_is_ring.\n    exists.\n    + apply M22plus_zero.\n    + intro; rewrite M22add_comm; apply M22plus_zero.\n    + intros; apply M22add_assoc.\n  Qed.\n\n  Definition MU22 : M22 -> M22 -> M22.\n  Proof using Rplus Rmult.\n    intros (((a,b),c),d) (((a',b'),c'),d').\n    exact (a⊗a' ⊕ b⊗c' , a⊗b' ⊕ b⊗d',\n           c⊗a' ⊕ d⊗c' , c⊗b' ⊕ d⊗d' ).\n  Defined.\n\n  Local Infix \"⊠\" := MU22 (at level 40, left associativity).\n\n  Tactic Notation \"myauto\" integer(n) := do n intros (((?&?)&?)&?); apply M22_equal; ring.\n\n  Fact M22mult_one_l : forall x, ID_22 ⊠ x = x.\n  Proof using R_is_ring. myauto 1. Qed.\n\n  Fact M22mult_one_r : forall x, x ⊠ ID_22 = x.\n  Proof using R_is_ring. myauto 1. Qed.\n\n  Fact M22mul_assoc : forall x y u, x ⊠ (y ⊠ u) = x ⊠ y ⊠ u.\n  Proof using R_is_ring. myauto 3. Qed.\n\n  Fact M22_mult_distr_l : forall x y u, x ⊠ (y⊞u) = x⊠y ⊞ x⊠u.\n  Proof using R_is_ring. myauto 3. Qed.\n \n  Fact M22_mult_distr_r : forall x y u, (y⊞u) ⊠ x = y⊠x ⊞ u⊠x.\n  Proof using R_is_ring. myauto 3. Qed.\n\n  Theorem M22mult_monoid : monoid_theory MU22 ID_22.\n  Proof using R_is_ring.\n    exists.\n    + apply M22mult_one_l.\n    + apply M22mult_one_r.\n    + apply M22mul_assoc.\n  Qed.\n\n  Fact M22_opp_mult_l : forall x y, (⊟ x) ⊠ y = ⊟ (x ⊠ y).\n  Proof using R_is_ring. myauto 2. Qed.\n\n  Fact M22_opp_mult_r : forall x y, x ⊠ (⊟y) = ⊟ (x ⊠ y).\n  Proof using R_is_ring. myauto 2. Qed.\n\n  Definition M22scal (k : R) : M22 -> M22.\n  Proof using Rmult.\n    intros (((u,v),w),z).\n    exact (k⊗u,k⊗v,k⊗w,k⊗z).\n  Defined.\n\n  Fact M22scal_mult k1 k2 : forall x, M22scal k1 (M22scal k2 x) = M22scal (k1⊗k2) x.\n  Proof using R_is_ring. myauto 1. Qed.\n\n  Fact M22scal_PL22 k : forall x y, M22scal k (x ⊞ y) = M22scal k x ⊞ M22scal k y.\n  Proof using R_is_ring. myauto 2. Qed.\n\n  Fact M22scal_MI22 : forall x, M22scal (∸o) x = ⊟x.\n  Proof using R_is_ring. myauto 1. Qed.\n\n  Fact M22scal_zero : forall x, M22scal z x = ZE_22.\n  Proof using R_is_ring. myauto 1. Qed.\n\n  Fact M22scal_MU22_l k : forall x y, M22scal k (x ⊠ y) = M22scal k x ⊠ y.\n  Proof using R_is_ring. myauto 2. Qed.\n\n  Fact M22scal_MU22_r k : forall x y, M22scal k (x ⊠ y) = x ⊠ M22scal k y.\n  Proof using R_is_ring. myauto 2. Qed.\n\n  Fact mscal_M22scal n x : mscal PL22 ZE_22 n x = M22scal (mscal Rplus Rzero n Rone) x.\n  Proof using R_is_ring.\n    induction n as [ | n IHn ].\n    + do 2 rewrite mscal_0; revert x; myauto 1.\n    + do 2 rewrite mscal_S.\n      rewrite IHn; clear IHn.\n      revert x; myauto 1.\n  Qed.\n\n  (* M22 is NOT a ring because mult is not commutative *)\n\n  (* ⊕  ⊗  ∸    ⊞ ⊠ ⊟ *)\n\n  Definition Det22 : M22 -> R.\n  Proof using Rplus Rmult Ropp.\n    intros (((a,b),c),d).\n    exact (a⊗d ⊕ ∸(b⊗c)).\n  Defined.\n\n  Fact Det22_scal k : forall x, Det22 (M22scal k x) = (k ⊗ k) ⊗ Det22 x.\n  Proof using R_is_ring. intros (((?,?),?),?); simpl; ring. Qed.\n\n  Fact Det22_mult : forall x y, Det22 (x⊠y) = Det22 x ⊗ Det22 y.\n  Proof using R_is_ring. intros (((?,?),?),?) (((?,?),?),?); simpl; ring. Qed.\n\n  Notation expo22 := (mscal MU22 ID_22).\n  Notation expoR := (mscal Rmult o).\n\n  Fact expo22_scal k n U : expo22 n (M22scal k U) = M22scal (expoR n k) (expo22 n U).\n  Proof using R_is_ring.\n    induction n as [ | n IHn ].\n    + do 3 rewrite mscal_0; apply M22_equal; ring.\n    + do 3 rewrite mscal_S.\n      rewrite IHn.\n      rewrite <- M22scal_MU22_l, <- M22scal_MU22_r.\n      rewrite M22scal_mult; auto.\n  Qed.\n\n  Fact Det22_expo n x : Det22 (expo22 n x) = expoR n (Det22 x).\n  Proof using R_is_ring.\n    induction n as [ | n IHn ].\n    + do 2 rewrite mscal_0; simpl; ring.\n    + do 2 rewrite mscal_S.\n      rewrite Det22_mult, IHn; ring.\n  Qed.\n\n  Fact Diag22_expo n x y : expo22 n (x,z,z,y) = (expoR n x,Rzero,Rzero,expoR n y).\n  Proof using R_is_ring.\n    induction n as [ | n IHn ]; try (simpl; auto; fail).\n    do 3 rewrite mscal_S; rewrite IHn.\n    apply M22_equal; ring.\n  Qed.\n\n  Fact MU22_Diag22 a b c d x y : (a,b,c,d) ⊠ (x,z,z,y) = (a⊗x,b⊗y,c⊗x,d⊗y).\n  Proof using R_is_ring. apply M22_equal; ring. Qed.\n \n  (* We also the to lift the Z -> Zp morphism to M22 matrices *)\n\n  Fact M22_proj12 a1 b1 c1 d1 a2 b2 c2 d2 : (a1,b1,c1,d1) = (a2,b2,c2,d2) :> M22 -> c1 = c2.\n  Proof. inversion 1; auto. Qed.\n\nEnd rings.\n\nSection ring_morphism.\n\n  Variable (X : Type) (zX oX : X) (pX mX : X -> X -> X) (oppX : X -> X)\n           (Y : Type) (zY oY : Y) (pY mY : Y -> Y -> Y) (oppY : Y -> Y).\n\n  Variable phi : X -> Y.\n\n  Local Notation \"〚 x 〛\" := (phi x).\n\n  Record ring_morphism : Prop := mk_ring_morph {\n    morph_z : 〚 zX 〛= zY;\n    morph_o : 〚 oX 〛= oY;\n    morph_plus : forall x y, 〚 pX x y 〛= pY 〚 x 〛〚 y 〛;\n    morph_mult : forall x y, 〚 mX x y 〛= mY 〚 x 〛〚 y 〛;\n    morph_opp : forall x, 〚 oppX x 〛= oppY 〚 x 〛;\n  }.\n\n  Hypothesis Hphi : ring_morphism.\n\n  Definition morph22 : M22 X -> M22 Y.\n  Proof using phi.\n    intros (((a,b),c),d).\n    exact (〚 a 〛, 〚 b 〛,\n           〚 c 〛, 〚 d 〛).\n  Defined.\n\n  Tactic Notation \"myauto\" integer(n) := do n intros (((?&?)&?)&?); apply M22_equal; ring.\n\n  Fact PL22_morph : forall x y, morph22 (PL22 pX x y) = PL22 pY (morph22 x) (morph22 y).\n  Proof using Hphi. \n    destruct Hphi.\n    do 2 intros (((?&?)&?)&?); apply M22_equal; auto.\n  Qed.\n\n  Fact MU22_morph : forall x y, morph22 (MU22 pX mX x y) = MU22 pY mY (morph22 x) (morph22 y).\n  Proof using Hphi. \n    destruct Hphi as [ G1 G2 G3 G4 G6 ].\n    do 2 intros (((?&?)&?)&?); apply M22_equal; \n      repeat rewrite G3; repeat rewrite G4; auto.\n  Qed.\n\n  Fact MI22_morph : forall x, morph22 (MI22 oppX x) = MI22 oppY (morph22 x).\n  Proof using Hphi. \n    destruct Hphi as [ G1 G2 G3 G4 G6 ].\n    do 1 intros (((?&?)&?)&?); apply M22_equal; \n      repeat rewrite G3; repeat rewrite G4; auto.\n  Qed.\n\n  Fact M22scal_morph : forall k x, morph22 (M22scal mX k x) = M22scal mY 〚 k 〛 (morph22 x).\n  Proof using Hphi.\n    destruct Hphi as [ G1 G2 G3 G4 G6 ].\n    intros k (((?&?)&?)&?); apply M22_equal; auto.\n  Qed.\n\n  Fact Det22_morph : forall x, 〚 Det22 pX mX oppX x 〛= Det22 pY mY oppY (morph22 x).\n  Proof using Hphi.\n    destruct Hphi as [ G1 G2 G3 G4 G6 ].\n    intros (((?&?)&?)&?); simpl.\n    rewrite G3, G6, G4, G4; auto.\n  Qed.\n\n  Fact expo22_morph n x : morph22 (mscal (MU22 pX mX) (ID_22 zX oX) n x)\n                        = mscal (MU22 pY mY) (ID_22 zY oY) n (morph22 x).\n  Proof using Hphi.\n    destruct Hphi as [ G1 G2 G3 G4 G6 ].\n    induction n as [ | n IHn ].\n    + do 2 rewrite mscal_0; apply M22_equal; auto.\n    + do 2 rewrite mscal_S.\n      rewrite MU22_morph, IHn; auto.\n  Qed.\n\nEnd ring_morphism.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/H10/ArithLibs/matrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.658754865374102}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp\nRequire Import ssrfun ssrbool eqtype ssrnat seq path fintype.\nFrom mathcomp\nRequire Import div bigop.\n\n(******************************************************************************)\n(* This file contains the definitions of:                                     *)\n(*        prime p <=> p is a prime.                                           *)\n(*       primes m == the sorted list of prime divisors of m > 1, else [::].   *)\n(*        pfactor == the type of prime factors, syntax (p ^ e)%pfactor.       *)\n(* prime_decomp m == the list of prime factors of m > 1, sorted by primes.    *)\n(*       logn p m == the e such that (p ^ e) \\in prime_decomp n, else 0.      *)\n(*  trunc_log p m == the largest e such that p ^ e <= m, or 0 if p or m is 0. *)\n(*         pdiv n == the smallest prime divisor of n > 1, else 1.             *)\n(*     max_pdiv n == the largest prime divisor of n > 1, else 1.              *)\n(*     divisors m == the sorted list of divisors of m > 0, else [::].         *)\n(*      totient n == the Euler totient (#|{i < n | i and n coprime}|).        *)\n(*       nat_pred == the type of explicit collective nat predicates.          *)\n(*                := simpl_pred nat.                                          *)\n(*    -> We allow the coercion nat >-> nat_pred, interpreting p as pred1 p.   *)\n(*    -> We define a predType for nat_pred, enabling the notation p \\in pi.   *)\n(*    -> We don't have nat_pred >-> pred, which would imply nat >-> Funclass. *)\n(*           pi^' == the complement of pi : nat_pred, i.e., the nat_pred such *)\n(*                   that (p \\in pi^') = (p \\notin pi).                       *)\n(*         \\pi(n) == the set of prime divisors of n, i.e., the nat_pred such  *)\n(*                   that (p \\in \\pi(n)) = (p \\in primes n).                  *)\n(*         \\pi(A) == the set of primes of #|A|, with A a collective predicate *)\n(*                   over a finite Type.                                      *)\n(*     -> The notation \\pi(A) is implemented with a collapsible Coercion, so  *)\n(*        the type of A must coerce to finpred_class (e.g., by coercing to    *)\n(*        {set T}), not merely implement the predType interface (as seq T     *)\n(*        does).                                                              *)\n(*     -> The expression #|A| will only appear in \\pi(A) after simplification *)\n(*        collapses the coercion stack, so it is advisable to do so early on. *)\n(*     pi.-nat n <=> n > 0 and all prime divisors of n are in pi.             *)\n(*          n`_pi == the pi-part of n -- the largest pi.-nat divisor of n.    *)\n(*               := \\prod_(0 <= p < n.+1 | p \\in pi) p ^ logn p n.            *)\n(*     -> The nat >-> nat_pred coercion lets us write p.-nat n and n`_p.      *)\n(* In addition to the lemmas relevant to these definitions, this file also    *)\n(* contains the dvdn_sum lemma, so that bigop.v doesn't depend on div.v.      *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* The complexity of any arithmetic operation with the Peano representation *)\n(* is pretty dreadful, so using algorithms for \"harder\" problems such as    *)\n(* factoring, that are geared for efficient artihmetic leads to dismal      *)\n(* performance -- it takes a significant time, for instance, to compute the *)\n(* divisors of just a two-digit number. On the other hand, for Peano        *)\n(* integers, prime factoring (and testing) is linear-time with a small      *)\n(* constant factor -- indeed, the same as converting in and out of a binary *)\n(* representation. This is implemented by the code below, which is then     *)\n(* used to give the \"standard\" definitions of prime, primes, and divisors,  *)\n(* which can then be used casually in proofs with moderately-sized numeric  *)\n(* values (indeed, the code here performs well for up to 6-digit numbers).  *)\n\n(* We start with faster mod-2 functions. *)\n\nFixpoint edivn2 q r := if r is r'.+2 then edivn2 q.+1 r' else (q, r).\n\nLemma edivn2P n : edivn_spec n 2 (edivn2 0 n).\nProof.\nrewrite -[n]odd_double_half addnC -{1}[n./2]addn0 -{1}mul2n mulnC.\nelim: n./2 {1 4}0 => [|r IHr] q; first by case (odd n) => /=.\nby rewrite addSnnS; apply: IHr.\nQed.\n\nFixpoint elogn2 e q r {struct q} :=\n  match q, r with\n  | 0, _ | _, 0 => (e, q)\n  | q'.+1, 1 => elogn2 e.+1 q' q'\n  | q'.+1, r'.+2 => elogn2 e q' r'\n  end.\n\nVariant elogn2_spec n : nat * nat -> Type :=\n  Elogn2Spec e m of n = 2 ^ e * m.*2.+1 : elogn2_spec n (e, m).\n\nLemma elogn2P n : elogn2_spec n.+1 (elogn2 0 n n).\nProof.\nrewrite -{1}[n.+1]mul1n -[1]/(2 ^ 0) -{1}(addKn n n) addnn.\nelim: n {1 4 6}n {2 3}0 (leqnn n) => [|q IHq] [|[|r]] e //=; last first.\n  by move/ltnW; apply: IHq.\nclear 1; rewrite subn1 -[_.-1.+1]doubleS -mul2n mulnA -expnSr.\nby rewrite -{1}(addKn q q) addnn; apply: IHq.\nQed.\n\nDefinition ifnz T n (x y : T) := if n is 0 then y else x.\n\nVariant ifnz_spec T n (x y : T) : T -> Type :=\n  | IfnzPos of n > 0 : ifnz_spec n x y x\n  | IfnzZero of n = 0 : ifnz_spec n x y y.\n\nLemma ifnzP T n (x y : T) : ifnz_spec n x y (ifnz n x y).\nProof. by case: n => [|n]; [right | left]. Qed.\n\n(* For pretty-printing. *)\nDefinition NumFactor (f : nat * nat) := ([Num of f.1], f.2).\n\nDefinition pfactor p e := p ^ e.\n\nDefinition cons_pfactor (p e : nat) pd := ifnz e ((p, e) :: pd) pd.\n\nLocal Notation \"p ^? e :: pd\" := (cons_pfactor p e pd)\n  (at level 30, e at level 30, pd at level 60) : nat_scope.\n\nSection prime_decomp.\n\nImport NatTrec.\n\nFixpoint prime_decomp_rec m k a b c e :=\n  let p := k.*2.+1 in\n  if a is a'.+1 then\n    if b - (ifnz e 1 k - c) is b'.+1 then\n      [rec m, k, a', b', ifnz c c.-1 (ifnz e p.-2 1), e] else\n    if (b == 0) && (c == 0) then\n      let b' := k + a' in [rec b'.*2.+3, k, a', b', k.-1, e.+1] else\n    let bc' := ifnz e (ifnz b (k, 0) (edivn2 0 c)) (b, c) in\n    p ^? e :: ifnz a' [rec m, k.+1, a'.-1, bc'.1 + a', bc'.2, 0] [:: (m, 1)]\n  else if (b == 0) && (c == 0) then [:: (p, e.+2)] else p ^? e :: [:: (m, 1)]\nwhere \"[ 'rec' m , k , a , b , c , e ]\" := (prime_decomp_rec m k a b c e).\n\nDefinition prime_decomp n :=\n  let: (e2, m2) := elogn2 0 n.-1 n.-1 in\n  if m2 < 2 then 2 ^? e2 :: 3 ^? m2 :: [::] else\n  let: (a, bc) := edivn m2.-2 3 in\n  let: (b, c) := edivn (2 - bc) 2 in\n  2 ^? e2 :: [rec m2.*2.+1, 1, a, b, c, 0].\n\n(* The list of divisors and the Euler function are computed directly from *)\n(* the decomposition, using a merge_sort variant sort the divisor list.   *)\n\nDefinition add_divisors f divs :=\n  let: (p, e) := f in\n  let add1 divs' := merge leq (map (NatTrec.mul p) divs') divs in\n  iter e add1 divs.\n\nDefinition add_totient_factor f m := let: (p, e) := f in p.-1 * p ^ e.-1 * m.\n\nEnd prime_decomp.\n\nDefinition primes n := unzip1 (prime_decomp n).\n\nDefinition prime p := if prime_decomp p is [:: (_ , 1)] then true else false.\n\nDefinition nat_pred := simpl_pred nat.\n\nDefinition pi_unwrapped_arg := nat.\nDefinition pi_wrapped_arg := wrapped nat.\nCoercion unwrap_pi_arg (wa : pi_wrapped_arg) : pi_unwrapped_arg := unwrap wa.\nCoercion pi_arg_of_nat (n : nat) := Wrap n : pi_wrapped_arg.\nCoercion pi_arg_of_fin_pred T pT (A : @fin_pred_sort T pT) : pi_wrapped_arg :=\n  Wrap #|A|.\n\nDefinition pi_of (n : pi_unwrapped_arg) : nat_pred := [pred p in primes n].\n\nNotation \"\\pi ( n )\" := (pi_of n)\n  (at level 2, format \"\\pi ( n )\") : nat_scope.\nNotation \"\\p 'i' ( A )\" := \\pi(#|A|)\n  (at level 2, format \"\\p 'i' ( A )\") : nat_scope.\n\nDefinition pdiv n := head 1 (primes n).\n\nDefinition max_pdiv n := last 1 (primes n).\n\nDefinition divisors n := foldr add_divisors [:: 1] (prime_decomp n).\n\nDefinition totient n := foldr add_totient_factor (n > 0) (prime_decomp n).\n\n(* Correctness of the decomposition algorithm. *)\n\nLemma prime_decomp_correct :\n  let pd_val pd := \\prod_(f <- pd) pfactor f.1 f.2 in\n  let lb_dvd q m := ~~ has [pred d | d %| m] (index_iota 2 q) in\n  let pf_ok f := lb_dvd f.1 f.1 && (0 < f.2) in\n  let pd_ord q pd := path ltn q (unzip1 pd) in\n  let pd_ok q n pd := [/\\ n = pd_val pd, all pf_ok pd & pd_ord q pd] in\n  forall n, n > 0 -> pd_ok 1 n (prime_decomp n).\nProof.\nrewrite unlock => pd_val lb_dvd pf_ok pd_ord pd_ok.\nhave leq_pd_ok m p q pd: q <= p -> pd_ok p m pd -> pd_ok q m pd.\n  rewrite /pd_ok /pd_ord; case: pd => [|[r _] pd] //= leqp [<- ->].\n  by case/andP=> /(leq_trans _)->.\nhave apd_ok m e q p pd: lb_dvd p p || (e == 0) -> q < p ->\n     pd_ok p m pd -> pd_ok q (p ^ e * m) (p ^? e :: pd).\n- case: e => [|e]; rewrite orbC /= => pr_p ltqp.\n    by rewrite mul1n; apply: leq_pd_ok; apply: ltnW.\n  by rewrite /pd_ok /pd_ord /pf_ok /= pr_p ltqp => [[<- -> ->]].\ncase=> // n _; rewrite /prime_decomp.\ncase: elogn2P => e2 m2 -> {n}; case: m2 => [|[|abc]]; try exact: apd_ok.\nrewrite [_.-2]/= !ltnS ltn0 natTrecE; case: edivnP => a bc ->{abc}.\ncase: edivnP => b c def_bc /= ltc2 ltbc3; apply: (apd_ok) => //.\nmove def_m: _.*2.+1 => m; set k := {2}1; rewrite -[2]/k.*2; set e := 0.\npose p := k.*2.+1; rewrite -{1}[m]mul1n -[1]/(p ^ e)%N.\nhave{def_m bc def_bc ltc2 ltbc3}:\n   let kb := (ifnz e k 1).*2 in\n   [&& k > 0, p < m, lb_dvd p m, c < kb & lb_dvd p p || (e == 0)]\n    /\\ m + (b * kb + c).*2 = p ^ 2 + (a * p).*2.\n- rewrite -{-2}def_m; split=> //=; last first.\n    by rewrite -def_bc addSn -doubleD 2!addSn -addnA subnKC // addnC.\n  rewrite ltc2 /lb_dvd /index_iota /= dvdn2 -def_m.\n  by rewrite [_.+2]lock /= odd_double.\nmove: {2}a.+1 (ltnSn a) => n; clearbody k e.\nelim: n => // n IHn in a k p m b c e *; rewrite ltnS => le_a_n [].\nset kb := _.*2; set d := _ + c => /and5P[lt0k ltpm leppm ltc pr_p def_m].\nhave def_k1: k.-1.+1 = k := ltn_predK lt0k.\nhave def_kb1: kb.-1.+1 = kb by rewrite /kb -def_k1; case e.\nhave eq_bc_0: (b == 0) && (c == 0) = (d == 0).\n  by rewrite addn_eq0 muln_eq0 orbC -def_kb1.\nhave lt1p: 1 < p by rewrite ltnS double_gt0.\nhave co_p_2: coprime p 2 by rewrite /coprime gcdnC gcdnE modn2 /= odd_double.\nhave if_d0: d = 0 -> [/\\ m = (p + a.*2) * p, lb_dvd p p & lb_dvd p (p + a.*2)].\n  move=> d0; have{d0 def_m} def_m: m = (p + a.*2) * p.\n    by rewrite d0 addn0 -mulnn -!mul2n mulnA -mulnDl in def_m *.\n  split=> //; apply/hasPn=> r /(hasPn leppm); apply: contra => /= dv_r.\n    by rewrite def_m dvdn_mull.\n  by rewrite def_m dvdn_mulr.\ncase def_a: a => [|a'] /= in le_a_n *; rewrite !natTrecE -/p {}eq_bc_0.\n  case: d if_d0 def_m => [[//| def_m {pr_p}pr_p pr_m'] _ | d _ def_m] /=.\n    rewrite def_m def_a addn0 mulnA -2!expnSr.\n    by split; rewrite /pd_ord /pf_ok /= ?muln1 ?pr_p ?leqnn.\n  apply: apd_ok; rewrite // /pd_ok /= /pfactor expn1 muln1 /pd_ord /= ltpm.\n  rewrite /pf_ok !andbT /=; split=> //; apply: contra leppm.\n  case/hasP=> r /=; rewrite mem_index_iota => /andP[lt1r ltrm] dvrm; apply/hasP.\n  have [ltrp | lepr] := ltnP r p.\n    by exists r; rewrite // mem_index_iota lt1r.\n  case/dvdnP: dvrm => q def_q; exists q; last by rewrite def_q /= dvdn_mulr.\n  rewrite mem_index_iota -(ltn_pmul2r (ltnW lt1r)) -def_q mul1n ltrm.\n  move: def_m; rewrite def_a addn0 -(@ltn_pmul2r p) // mulnn => <-.\n  apply: (@leq_ltn_trans m); first by rewrite def_q leq_mul.\n  by rewrite -addn1 leq_add2l.\nhave def_k2: k.*2 = ifnz e 1 k * kb.\n  by rewrite /kb; case: (e) => [|e']; rewrite (mul1n, muln2).\ncase def_b': (b - _) => [|b']; last first.\n  have ->: ifnz e k.*2.-1 1 = kb.-1 by rewrite /kb; case e.\n  apply: IHn => {n le_a_n}//; rewrite -/p -/kb; split=> //.\n    rewrite lt0k ltpm leppm pr_p andbT /=.\n    by case: ifnzP; [move/ltn_predK->; apply: ltnW | rewrite def_kb1].\n  apply: (@addIn p.*2).\n  rewrite -2!addnA -!doubleD -addnA -mulSnr -def_a -def_m /d.\n  have ->: b * kb = b' * kb + (k.*2 - c * kb + kb).\n    rewrite addnCA addnC -mulSnr -def_b' def_k2 -mulnBl -mulnDl subnK //.\n    by rewrite ltnW // -subn_gt0 def_b'.\n  rewrite -addnA; congr (_ + (_ + _).*2).\n  case: (c) ltc; first by rewrite -addSnnS def_kb1 subn0 addn0 addnC.\n  rewrite /kb; case e => [[] // _ | e' c' _] /=; last first.\n    by rewrite subnDA subnn addnC addSnnS.\n  by rewrite mul1n -doubleB -doubleD subn1 !addn1 def_k1.\nhave ltdp: d < p.\n  move/eqP: def_b'; rewrite subn_eq0 -(@leq_pmul2r kb); last first.\n    by rewrite -def_kb1.\n  rewrite mulnBl -def_k2 ltnS -(leq_add2r c); move/leq_trans; apply.\n  have{ltc} ltc: c < k.*2.\n    by apply: (leq_trans ltc); rewrite leq_double /kb; case e.\n  rewrite -{2}(subnK (ltnW ltc)) leq_add2r leq_sub2l //.\n  by rewrite -def_kb1 mulnS leq_addr.\ncase def_d: d if_d0 => [|d'] => [[//|{def_m ltdp pr_p} def_m pr_p pr_m'] | _].\n  rewrite eqxx -doubleS -addnS -def_a doubleD -addSn -/p def_m.\n  rewrite mulnCA mulnC -expnSr.\n  apply: IHn => {n le_a_n}//; rewrite -/p -/kb; split.\n    rewrite lt0k -addn1 leq_add2l {1}def_a pr_m' pr_p /= def_k1 -addnn.\n    by rewrite leq_addr.\n  rewrite -addnA -doubleD addnCA def_a addSnnS def_k1 -(addnC k) -mulnSr.\n  rewrite -[_.*2.+1]/p mulnDl doubleD addnA -mul2n mulnA mul2n -mulSn.\n  by rewrite -/p mulnn.\nhave next_pm: lb_dvd p.+2 m.\n  rewrite /lb_dvd /index_iota 2!subSS subn0 -(subnK lt1p) iota_add.\n  rewrite has_cat; apply/norP; split=> //=; rewrite orbF subnKC // orbC.\n  apply/norP; split; apply/dvdnP=> [[q def_q]].\n     case/hasP: leppm; exists 2; first by rewrite /p -(subnKC lt0k).\n    by rewrite /= def_q dvdn_mull // dvdn2 /= odd_double.\n  move/(congr1 (dvdn p)): def_m; rewrite -mulnn -!mul2n mulnA -mulnDl.\n  rewrite dvdn_mull // dvdn_addr; last by rewrite def_q dvdn_mull.\n  case/dvdnP=> r; rewrite mul2n => def_r; move: ltdp (congr1 odd def_r).\n  rewrite odd_double -ltn_double {1}def_r -mul2n ltn_pmul2r //.\n  by case: r def_r => [|[|[]]] //; rewrite def_d // mul1n /= odd_double.\napply: apd_ok => //; case: a' def_a le_a_n => [|a'] def_a => [_ | lta] /=.\n  rewrite /pd_ok /= /pfactor expn1 muln1 /pd_ord /= ltpm /pf_ok !andbT /=.\n  split=> //; apply: contra next_pm.\n  case/hasP=> q; rewrite mem_index_iota => /andP[lt1q ltqm] dvqm; apply/hasP.\n  have [ltqp | lepq] := ltnP q p.+2.\n    by exists q; rewrite // mem_index_iota lt1q.\n  case/dvdnP: dvqm => r def_r; exists r; last by rewrite def_r /= dvdn_mulr.\n  rewrite mem_index_iota -(ltn_pmul2r (ltnW lt1q)) -def_r mul1n ltqm /=.\n  rewrite -(@ltn_pmul2l p.+2) //; apply: (@leq_ltn_trans m).\n    by rewrite def_r mulnC leq_mul.\n  rewrite -addn2 mulnn sqrnD mul2n muln2 -addnn addnCA -addnA addnCA addnA.\n  by rewrite def_a mul1n in def_m; rewrite -def_m addnS -addnA ltnS leq_addr.\nset bc := ifnz _ _ _; apply: leq_pd_ok (leqnSn _) _.\nrewrite -doubleS -{1}[m]mul1n -[1]/(k.+1.*2.+1 ^ 0)%N.\napply: IHn; first exact: ltnW.\nrewrite doubleS -/p [ifnz 0 _ _]/=; do 2?split => //.\n  rewrite orbT next_pm /= -(leq_add2r d.*2) def_m 2!addSnnS -doubleS leq_add.\n  - move: ltc; rewrite /kb {}/bc andbT; case e => //= e' _; case: ifnzP => //.\n    by case: edivn2P.\n  - by rewrite -{1}[p]muln1 -mulnn ltn_pmul2l.\n  by rewrite leq_double def_a mulSn (leq_trans ltdp) ?leq_addr.\nrewrite mulnDl !muln2 -addnA addnCA doubleD addnCA.\nrewrite (_ : _ + bc.2 = d); last first.\n  rewrite /d {}/bc /kb -muln2.\n  case: (e) (b) def_b' => //= _ []; first by case: edivn2P.\n  by case c; do 2?case; rewrite // mul1n /= muln2.\nrewrite def_m 3!doubleS addnC -(addn2 p) sqrnD mul2n muln2 -3!addnA.\ncongr (_ + _); rewrite 4!addnS -!doubleD; congr _.*2.+2.+2.\nby rewrite def_a -add2n mulnDl -addnA -muln2 -mulnDr mul2n.\nQed.\n\nLemma primePn n :\n  reflect (n < 2 \\/ exists2 d, 1 < d < n & d %| n) (~~ prime n).\nProof.\nrewrite /prime; case: n => [|[|p2]]; try by do 2!left.\ncase: (@prime_decomp_correct p2.+2) => //; rewrite unlock.\ncase: prime_decomp => [|[q [|[|e]]] pd] //=; last first; last by rewrite andbF.\n  rewrite {1}/pfactor 2!expnS -!mulnA /=.\n  case: (_ ^ _ * _) => [|u -> _ /andP[lt1q _]]; first by rewrite !muln0.\n  left; right; exists q; last by rewrite dvdn_mulr.\n  have lt0q := ltnW lt1q; rewrite lt1q -{1}[q]muln1 ltn_pmul2l //.\n  by rewrite -[2]muln1 leq_mul.\nrewrite {1}/pfactor expn1; case: pd => [|[r e] pd] /=; last first.\n  case: e => [|e] /=; first by rewrite !andbF.\n  rewrite {1}/pfactor expnS -mulnA.\n  case: (_ ^ _ * _) => [|u -> _ /and3P[lt1q ltqr _]]; first by rewrite !muln0.\n  left; right; exists q; last by rewrite dvdn_mulr.\n  by rewrite lt1q -{1}[q]mul1n ltn_mul // -[q.+1]muln1 leq_mul.\nrewrite muln1 !andbT => def_q pr_q lt1q; right=> [[]] // [d].\nby rewrite def_q -mem_index_iota => in_d_2q dv_d_q; case/hasP: pr_q; exists d.\nQed.\n\nLemma primeP p :\n  reflect (p > 1 /\\ forall d, d %| p -> xpred2 1 p d) (prime p).\nProof.\nrewrite -[prime p]negbK; have [npr_p | pr_p] := primePn p.\n  right=> [[lt1p pr_p]]; case: npr_p => [|[d n1pd]].\n    by rewrite ltnNge lt1p.\n  by move/pr_p=> /orP[] /eqP def_d; rewrite def_d ltnn ?andbF in n1pd.\nhave [lep1 | lt1p] := leqP; first by case: pr_p; left.\nleft; split=> // d dv_d_p; apply/norP=> [[nd1 ndp]]; case: pr_p; right.\nexists d; rewrite // andbC 2!ltn_neqAle ndp eq_sym nd1.\nby have lt0p := ltnW lt1p; rewrite dvdn_leq // (dvdn_gt0 lt0p).\nQed.\n\nLemma prime_nt_dvdP d p : prime p -> d != 1 -> reflect (d = p) (d %| p).\nProof.\ncase/primeP=> _ min_p d_neq1; apply: (iffP idP) => [/min_p|-> //].\nby rewrite (negPf d_neq1) /= => /eqP.\nQed.\n\nArguments primeP {p}.\nArguments primePn {n}.\n\nLemma prime_gt1 p : prime p -> 1 < p.\nProof. by case/primeP. Qed.\n\nLemma prime_gt0 p : prime p -> 0 < p.\nProof. by move/prime_gt1; apply: ltnW. Qed.\n\nHint Resolve prime_gt1 prime_gt0 : core.\n\nLemma prod_prime_decomp n :\n  n > 0 -> n = \\prod_(f <- prime_decomp n) f.1 ^ f.2.\nProof. by case/prime_decomp_correct. Qed.\n\nLemma even_prime p : prime p -> p = 2 \\/ odd p.\nProof.\nmove=> pr_p; case odd_p: (odd p); [by right | left].\nhave: 2 %| p by rewrite dvdn2 odd_p.\nby case/primeP: pr_p => _ dv_p /dv_p/(2 =P p).\nQed.\n\nLemma prime_oddPn p : prime p -> reflect (p = 2) (~~ odd p).\nProof.\nby move=> p_pr; apply: (iffP idP) => [|-> //]; case/even_prime: p_pr => ->.\nQed.\n\nLemma odd_prime_gt2 p : odd p -> prime p -> p > 2.\nProof. by move=> odd_p /prime_gt1; apply: odd_gt2. Qed.\n\nLemma mem_prime_decomp n p e :\n  (p, e) \\in prime_decomp n -> [/\\ prime p, e > 0 & p ^ e %| n].\nProof.\ncase: (posnP n) => [-> //| /prime_decomp_correct[def_n mem_pd ord_pd pd_pe]].\nhave /andP[pr_p ->] := allP mem_pd _ pd_pe; split=> //; last first.\n  case/splitPr: pd_pe def_n => pd1 pd2 ->.\n  by rewrite big_cat big_cons /= mulnCA dvdn_mulr.\nhave lt1p: 1 < p.\n  apply: (allP (order_path_min ltn_trans ord_pd)).\n  by apply/mapP; exists (p, e).\napply/primeP; split=> // d dv_d_p; apply/norP=> [[nd1 ndp]].\ncase/hasP: pr_p; exists d => //.\nrewrite mem_index_iota andbC 2!ltn_neqAle ndp eq_sym nd1.\nby have lt0p := ltnW lt1p; rewrite dvdn_leq // (dvdn_gt0 lt0p).\nQed.\n\nLemma prime_coprime p m : prime p -> coprime p m = ~~ (p %| m).\nProof.\ncase/primeP=> p_gt1 p_pr; apply/eqP/negP=> [d1 | ndv_pm].\n  case/dvdnP=> k def_m; rewrite -(addn0 m) def_m gcdnMDl gcdn0 in d1.\n  by rewrite d1 in p_gt1.\nby apply: gcdn_def => // d /p_pr /orP[] /eqP->.\nQed.\n\nLemma dvdn_prime2 p q : prime p -> prime q -> (p %| q) = (p == q).\nProof.\nmove=> pr_p pr_q; apply: negb_inj.\nby rewrite eqn_dvd negb_and -!prime_coprime // coprime_sym orbb.\nQed.\n\nLemma Euclid_dvdM m n p : prime p -> (p %| m * n) = (p %| m) || (p %| n).\nProof.\nmove=> pr_p; case dv_pm: (p %| m); first exact: dvdn_mulr.\nby rewrite Gauss_dvdr // prime_coprime // dv_pm.\nQed.\n\nLemma Euclid_dvd1 p : prime p -> (p %| 1) = false.\nProof. by rewrite dvdn1; case: eqP => // ->. Qed.\n\nLemma Euclid_dvdX m n p : prime p -> (p %| m ^ n) = (p %| m) && (n > 0).\nProof.\ncase: n => [|n] pr_p; first by rewrite andbF Euclid_dvd1.\nby apply: (inv_inj negbK); rewrite !andbT -!prime_coprime // coprime_pexpr.\nQed.\n\nLemma mem_primes p n : (p \\in primes n) = [&& prime p, n > 0 & p %| n].\nProof.\nrewrite andbCA; case: posnP => [-> // | /= n_gt0].\napply/mapP/andP=> [[[q e]]|[pr_p]] /=.\n  case/mem_prime_decomp=> pr_q e_gt0; case/dvdnP=> u -> -> {p}.\n  by rewrite -(prednK e_gt0) expnS mulnCA dvdn_mulr.\nrewrite {1}(prod_prime_decomp n_gt0) big_seq.\napply big_ind => [| u v IHu IHv | [q e] /= mem_qe dv_p_qe].\n- by rewrite Euclid_dvd1.\n- by rewrite Euclid_dvdM // => /orP[].\nexists (q, e) => //=; case/mem_prime_decomp: mem_qe => pr_q _ _.\nby rewrite Euclid_dvdX // dvdn_prime2 // in dv_p_qe; case: eqP dv_p_qe.\nQed.\n\nLemma sorted_primes n : sorted ltn (primes n).\nProof.\nby case: (posnP n) => [-> // | /prime_decomp_correct[_ _]]; apply: path_sorted.\nQed.\n\nLemma eq_primes m n : (primes m =i primes n) <-> (primes m = primes n).\nProof.\nsplit=> [eqpr| -> //].\nby apply: (eq_sorted_irr ltn_trans ltnn); rewrite ?sorted_primes.\nQed.\n\nLemma primes_uniq n : uniq (primes n).\nProof. exact: (sorted_uniq ltn_trans ltnn (sorted_primes n)). Qed.\n\n(* The smallest prime divisor *)\n\nLemma pi_pdiv n : (pdiv n \\in \\pi(n)) = (n > 1).\nProof.\ncase: n => [|[|n]] //; rewrite /pdiv !inE /primes.\nhave:= prod_prime_decomp (ltn0Sn n.+1); rewrite unlock.\nby case: prime_decomp => //= pf pd _; rewrite mem_head.\nQed.\n\nLemma pdiv_prime n : 1 < n -> prime (pdiv n).\nProof. by rewrite -pi_pdiv mem_primes; case/and3P. Qed.\n\nLemma pdiv_dvd n : pdiv n %| n.\nProof.\nby case: n (pi_pdiv n) => [|[|n]] //; rewrite mem_primes=> /and3P[].\nQed.\n\nLemma pi_max_pdiv n : (max_pdiv n \\in \\pi(n)) = (n > 1).\nProof.\nrewrite !inE -pi_pdiv /max_pdiv /pdiv !inE.\nby case: (primes n) => //= p ps; rewrite mem_head mem_last.\nQed.\n\nLemma max_pdiv_prime n : n > 1 -> prime (max_pdiv n).\nProof. by rewrite -pi_max_pdiv mem_primes => /andP[]. Qed.\n\nLemma max_pdiv_dvd n : max_pdiv n %| n.\nProof.\nby case: n (pi_max_pdiv n) => [|[|n]] //; rewrite mem_primes => /andP[].\nQed.\n\nLemma pdiv_leq n : 0 < n -> pdiv n <= n.\nProof. by move=> n_gt0; rewrite dvdn_leq // pdiv_dvd. Qed.\n\nLemma max_pdiv_leq n : 0 < n -> max_pdiv n <= n.\nProof. by move=> n_gt0; rewrite dvdn_leq // max_pdiv_dvd. Qed.\n\nLemma pdiv_gt0 n : 0 < pdiv n.\nProof. by case: n => [|[|n]] //; rewrite prime_gt0 ?pdiv_prime. Qed.\n\nLemma max_pdiv_gt0 n : 0 < max_pdiv n.\nProof. by case: n => [|[|n]] //; rewrite prime_gt0 ?max_pdiv_prime. Qed.\nHint Resolve pdiv_gt0 max_pdiv_gt0 : core.\n\nLemma pdiv_min_dvd m d : 1 < d -> d %| m -> pdiv m <= d.\nProof.\nmove=> lt1d dv_d_m; case: (posnP m) => [->|mpos]; first exact: ltnW.\nrewrite /pdiv; apply: leq_trans (pdiv_leq (ltnW lt1d)).\nhave: pdiv d \\in primes m.\n  by rewrite mem_primes mpos pdiv_prime // (dvdn_trans (pdiv_dvd d)).\ncase: (primes m) (sorted_primes m) => //= p pm ord_pm.\nrewrite inE => /predU1P[-> //|].\nby move/(allP (order_path_min ltn_trans ord_pm)); apply: ltnW.\nQed.\n\nLemma max_pdiv_max n p : p \\in \\pi(n) -> p <= max_pdiv n.\nProof.\nrewrite /max_pdiv !inE => n_p.\ncase/splitPr: n_p (sorted_primes n) => p1 p2; rewrite last_cat -cat_rcons /=.\nrewrite headI /= cat_path -(last_cons 0) -headI last_rcons; case/andP=> _.\nmove/(order_path_min ltn_trans); case/lastP: p2 => //= p2 q.\nby rewrite all_rcons last_rcons ltn_neqAle -andbA => /and3P[].\nQed.\n\nLemma ltn_pdiv2_prime n : 0 < n -> n < pdiv n ^ 2 -> prime n.\nProof.\ncase def_n: n => [|[|n']] // _; rewrite -def_n => lt_n_p2.\nsuffices ->: n = pdiv n by rewrite pdiv_prime ?def_n.\napply/eqP; rewrite eqn_leq leqNgt andbC pdiv_leq; last by rewrite def_n.\nmove: lt_n_p2; rewrite ltnNge; apply: contra => lt_pm_m.\ncase/dvdnP: (pdiv_dvd n) => q def_q.\nrewrite {2}def_q -mulnn leq_pmul2r // pdiv_min_dvd //.\n  by rewrite -[pdiv n]mul1n {2}def_q ltn_pmul2r in lt_pm_m.\nby rewrite def_q dvdn_mulr.\nQed.\n\nLemma primePns n :\n  reflect (n < 2 \\/ exists p, [/\\ prime p, p ^ 2 <= n & p %| n]) (~~ prime n).\nProof.\napply: (iffP idP) => [npr_p|]; last first.\n  case=> [|[p [pr_p le_p2_n dv_p_n]]]; first by case: n => [|[]].\n  apply/negP=> pr_n; move: dv_p_n le_p2_n; rewrite dvdn_prime2 //; move/eqP->.\n  by rewrite leqNgt -{1}[n]muln1 -mulnn ltn_pmul2l ?prime_gt1 ?prime_gt0.\ncase: leqP => [lt1p|]; [right | by left].\nexists (pdiv n); rewrite pdiv_dvd pdiv_prime //; split=> //.\nby case: leqP npr_p => //; move/ltn_pdiv2_prime->; auto.\nQed.\n\nArguments primePns {n}.\n\nLemma pdivP n : n > 1 -> {p | prime p & p %| n}.\nProof. by move=> lt1n; exists (pdiv n); rewrite ?pdiv_dvd ?pdiv_prime. Qed.\n\nLemma primes_mul m n p : m > 0 -> n > 0 ->\n  (p \\in primes (m * n)) = (p \\in primes m) || (p \\in primes n).\nProof.\nmove=> m_gt0 n_gt0; rewrite !mem_primes muln_gt0 m_gt0 n_gt0.\nby case pr_p: (prime p); rewrite // Euclid_dvdM.\nQed.\n\nLemma primes_exp m n : n > 0 -> primes (m ^ n) = primes m.\nProof.\ncase: n => // n _; rewrite expnS; case: (posnP m) => [-> //| m_gt0].\napply/eq_primes => /= p; elim: n => [|n IHn]; first by rewrite muln1.\nby rewrite primes_mul ?(expn_gt0, expnS, IHn, orbb, m_gt0).\nQed.\n\nLemma primes_prime p : prime p -> primes p = [::p].\nProof.\nmove=> pr_p; apply: (eq_sorted_irr ltn_trans ltnn) => // [|q].\n  exact: sorted_primes.\nrewrite mem_seq1 mem_primes prime_gt0 //=.\nby apply/andP/idP=> [[pr_q q_p] | /eqP-> //]; rewrite -dvdn_prime2.\nQed.\n\nLemma coprime_has_primes m n : m > 0 -> n > 0 ->\n  coprime m n = ~~ has (mem (primes m)) (primes n).\nProof.\nmove=> m_gt0 n_gt0; apply/eqnP/hasPn=> [mn1 p | no_p_mn].\n  rewrite /= !mem_primes m_gt0 n_gt0 /= => /andP[pr_p p_n].\n  have:= prime_gt1 pr_p; rewrite pr_p ltnNge -mn1 /=; apply: contra => p_m.\n  by rewrite dvdn_leq ?gcdn_gt0 ?m_gt0 // dvdn_gcd ?p_m.\ncase: (ltngtP (gcdn m n) 1) => //; first by rewrite ltnNge gcdn_gt0 ?m_gt0.\nmove/pdiv_prime; set p := pdiv _ => pr_p.\nmove/implyP: (no_p_mn p); rewrite /= !mem_primes m_gt0 n_gt0 pr_p /=.\nby rewrite !(dvdn_trans (pdiv_dvd _)) // (dvdn_gcdl, dvdn_gcdr).\nQed.\n\nLemma pdiv_id p : prime p -> pdiv p = p.\nProof. by move=> p_pr; rewrite /pdiv primes_prime. Qed.\n\nLemma pdiv_pfactor p k : prime p -> pdiv (p ^ k.+1) = p.\nProof. by move=> p_pr; rewrite /pdiv primes_exp ?primes_prime. Qed.\n\n(* Primes are unbounded. *)\n\nLemma prime_above m : {p | m < p & prime p}.\nProof.\nhave /pdivP[p pr_p p_dv_m1]: 1 < m`! + 1 by rewrite addn1 ltnS fact_gt0.\nexists p => //; rewrite ltnNge; apply: contraL p_dv_m1 => p_le_m.\nby rewrite dvdn_addr ?dvdn_fact ?prime_gt0 // gtnNdvd ?prime_gt1.\nQed.\n\n(* \"prime\" logarithms and p-parts. *)\n\nFixpoint logn_rec d m r :=\n  match r, edivn m d with\n  | r'.+1, (_.+1 as m', 0) => (logn_rec d m' r').+1\n  | _, _ => 0\n  end.\n\nDefinition logn p m := if prime p then logn_rec p m m else 0.\n\nLemma lognE p m :\n  logn p m = if [&& prime p, 0 < m & p %| m] then (logn p (m %/ p)).+1 else 0.\nProof.\nrewrite /logn /dvdn; case p_pr: (prime p) => //.\nrewrite /divn modn_def; case def_m: {2 3}m => [|m'] //=.\ncase: edivnP def_m => [[|q] [|r] -> _] // def_m; congr _.+1; rewrite [_.1]/=.\nhave{m def_m}: q < m'.\n  by rewrite -ltnS -def_m addn0 mulnC -{1}[q.+1]mul1n ltn_pmul2r // prime_gt1.\nelim: {m' q}_.+1 {-2}m' q.+1 (ltnSn m') (ltn0Sn q) => // s IHs.\ncase=> [[]|r] //= m; rewrite ltnS => lt_rs m_gt0 le_mr.\nrewrite -{3}[m]prednK //=; case: edivnP => [[|q] [|_] def_q _] //.\nhave{def_q} lt_qm': q < m.-1.\n  by rewrite -[q.+1]muln1 -ltnS prednK // def_q addn0 ltn_pmul2l // prime_gt1.\nhave{le_mr} le_m'r: m.-1 <= r by rewrite -ltnS prednK.\nby rewrite (IHs r) ?(IHs m.-1) // ?(leq_trans lt_qm', leq_trans _ lt_rs).\nQed.\n\nLemma logn_gt0 p n : (0 < logn p n) = (p \\in primes n).\nProof. by rewrite lognE -mem_primes; case: {+}(p \\in _). Qed.\n\nLemma ltn_log0 p n : n < p -> logn p n = 0.\nProof. by case: n => [|n] ltnp; rewrite lognE ?andbF // gtnNdvd ?andbF. Qed.\n\nLemma logn0 p : logn p 0 = 0.\nProof. by rewrite /logn if_same. Qed.\n\nLemma logn1 p : logn p 1 = 0.\nProof. by rewrite lognE dvdn1 /= andbC; case: eqP => // ->. Qed.\n\nLemma pfactor_gt0 p n : 0 < p ^ logn p n.\nProof. by rewrite expn_gt0 lognE; case: (posnP p) => // ->. Qed.\nHint Resolve pfactor_gt0 : core.\n\nLemma pfactor_dvdn p n m : prime p -> m > 0 -> (p ^ n %| m) = (n <= logn p m).\nProof.\nmove=> p_pr; elim: n m => [|n IHn] m m_gt0; first exact: dvd1n.\nrewrite lognE p_pr m_gt0 /=; case dv_pm: (p %| m); last first.\n  apply/dvdnP=> [] [/= q def_m].\n  by rewrite def_m expnS mulnCA dvdn_mulr in dv_pm.\ncase/dvdnP: dv_pm m_gt0 => q ->{m}; rewrite muln_gt0 => /andP[p_gt0 q_gt0].\nby rewrite expnSr dvdn_pmul2r // mulnK // IHn.\nQed.\n\nLemma pfactor_dvdnn p n : p ^ logn p n %| n.\nProof.\ncase: n => // n; case pr_p: (prime p); first by rewrite pfactor_dvdn.\nby rewrite lognE pr_p dvd1n.\nQed.\n\nLemma logn_prime p q : prime q -> logn p q = (p == q).\nProof.\nmove=> pr_q; have q_gt0 := prime_gt0 pr_q; rewrite lognE q_gt0 /=.\ncase pr_p: (prime p); last by case: eqP pr_p pr_q => // -> ->.\nby rewrite dvdn_prime2 //; case: eqP => // ->; rewrite divnn q_gt0 logn1.\nQed.\n\nLemma pfactor_coprime p n :\n  prime p -> n > 0 -> {m | coprime p m & n = m * p ^ logn p n}.\nProof.\nmove=> p_pr n_gt0; set k := logn p n.\nhave dv_pk_n: p ^ k %| n by rewrite pfactor_dvdn.\nexists (n %/ p ^ k); last by rewrite divnK.\nrewrite prime_coprime // -(@dvdn_pmul2r (p ^ k)) ?expn_gt0 ?prime_gt0 //.\nby rewrite -expnS divnK // pfactor_dvdn // ltnn.\nQed.\n\nLemma pfactorK p n : prime p -> logn p (p ^ n) = n.\nProof.\nmove=> p_pr; have pn_gt0: p ^ n > 0 by rewrite expn_gt0 prime_gt0.\napply/eqP; rewrite eqn_leq -pfactor_dvdn // dvdnn andbT.\nby rewrite -(leq_exp2l _ _ (prime_gt1 p_pr)) dvdn_leq // pfactor_dvdn.\nQed.\n\nLemma pfactorKpdiv p n : prime p -> logn (pdiv (p ^ n)) (p ^ n) = n.\nProof. by case: n => // n p_pr; rewrite pdiv_pfactor ?pfactorK. Qed.\n\nLemma dvdn_leq_log p m n : 0 < n -> m %| n -> logn p m <= logn p n.\nProof.\nmove=> n_gt0 dv_m_n; have m_gt0 := dvdn_gt0 n_gt0 dv_m_n.\ncase p_pr: (prime p); last by do 2!rewrite lognE p_pr /=.\nby rewrite -pfactor_dvdn //; apply: dvdn_trans dv_m_n; rewrite pfactor_dvdn.\nQed.\n\nLemma ltn_logl p n : 0 < n -> logn p n < n.\nProof.\nmove=> n_gt0; have [p_gt1 | p_le1] := boolP (1 < p).\n  by rewrite (leq_trans (ltn_expl _ p_gt1)) // dvdn_leq ?pfactor_dvdnn.\nby rewrite lognE (contraNF (@prime_gt1 _)).\nQed.\n\nLemma logn_Gauss p m n : coprime p m -> logn p (m * n) = logn p n.\nProof.\nmove=> co_pm; case p_pr: (prime p); last by rewrite /logn p_pr.\nhave [-> | n_gt0] := posnP n; first by rewrite muln0.\nhave [m0 | m_gt0] := posnP m; first by rewrite m0 prime_coprime ?dvdn0 in co_pm.\nhave mn_gt0: m * n > 0 by rewrite muln_gt0 m_gt0.\napply/eqP; rewrite eqn_leq andbC dvdn_leq_log ?dvdn_mull //.\nset k := logn p _; have: p ^ k %| m * n by rewrite pfactor_dvdn.\nby rewrite Gauss_dvdr ?coprime_expl // -pfactor_dvdn.\nQed.\n\nLemma lognM p m n : 0 < m -> 0 < n -> logn p (m * n) = logn p m + logn p n.\nProof.\ncase p_pr: (prime p); last by rewrite /logn p_pr.\nhave xlp := pfactor_coprime p_pr.\ncase/xlp=> m' co_m' def_m /xlp[n' co_n' def_n] {xlp}.\nby rewrite {1}def_m {1}def_n mulnCA -mulnA -expnD !logn_Gauss // pfactorK.\nQed.\n\nLemma lognX p m n : logn p (m ^ n) = n * logn p m.\nProof.\ncase p_pr: (prime p); last by rewrite /logn p_pr muln0.\nelim: n => [|n IHn]; first by rewrite logn1.\nhave [->|m_gt0] := posnP m; first by rewrite exp0n // lognE andbF muln0.\nby rewrite expnS lognM ?IHn // expn_gt0 m_gt0.\nQed.\n\nLemma logn_div p m n : m %| n -> logn p (n %/ m) = logn p n - logn p m.\nProof.\nrewrite dvdn_eq => /eqP def_n.\ncase: (posnP n) => [-> |]; first by rewrite div0n logn0.\nby rewrite -{1 3}def_n muln_gt0 => /andP[q_gt0 m_gt0]; rewrite lognM ?addnK.\nQed.\n\nLemma dvdn_pfactor p d n : prime p ->\n  reflect (exists2 m, m <= n & d = p ^ m) (d %| p ^ n).\nProof.\nmove=> p_pr; have pn_gt0: p ^ n > 0 by rewrite expn_gt0 prime_gt0.\napply: (iffP idP) => [dv_d_pn|[m le_m_n ->]]; last first.\n  by rewrite -(subnK le_m_n) expnD dvdn_mull.\nexists (logn p d); first by rewrite -(pfactorK n p_pr) dvdn_leq_log.\nhave d_gt0: d > 0 by apply: dvdn_gt0 dv_d_pn.\ncase: (pfactor_coprime p_pr d_gt0) => q co_p_q def_d.\nrewrite {1}def_d ((q =P 1) _) ?mul1n // -dvdn1.\nsuff: q %| p ^ n * 1 by rewrite Gauss_dvdr // coprime_sym coprime_expl.\nby rewrite muln1 (dvdn_trans _ dv_d_pn) // def_d dvdn_mulr.\nQed.\n\nLemma prime_decompE n : prime_decomp n = [seq (p, logn p n) | p <- primes n].\nProof.\ncase: n => // n; pose f0 := (0, 0); rewrite -map_comp.\napply: (@eq_from_nth _ f0) => [|i lt_i_n]; first by rewrite size_map.\nrewrite (nth_map f0) //; case def_f: (nth _ _ i) => [p e] /=.\ncongr (_, _); rewrite [n.+1]prod_prime_decomp //.\nhave: (p, e) \\in prime_decomp n.+1 by rewrite -def_f mem_nth.\ncase/mem_prime_decomp=> pr_p _ _.\nrewrite (big_nth f0) big_mkord (bigD1 (Ordinal lt_i_n)) //=.\nrewrite def_f mulnC logn_Gauss ?pfactorK //.\napply big_ind => [|m1 m2 com1 com2| [j ltj] /=]; first exact: coprimen1.\n  by rewrite coprime_mulr com1.\nrewrite -val_eqE /= => nji; case def_j: (nth _ _ j) => [q e1] /=.\nhave: (q, e1) \\in prime_decomp n.+1 by rewrite -def_j mem_nth.\ncase/mem_prime_decomp=> pr_q e1_gt0 _; rewrite coprime_pexpr //.\nrewrite prime_coprime // dvdn_prime2 //; apply: contra nji => eq_pq.\nrewrite -(nth_uniq 0 _ _ (primes_uniq n.+1)) ?size_map //=.\nby rewrite !(nth_map f0) //  def_f def_j /= eq_sym.\nQed.\n\n(* Some combinatorial formulae. *)\n\nLemma divn_count_dvd d n : n %/ d = \\sum_(1 <= i < n.+1) (d %| i).\nProof.\nhave [-> | d_gt0] := posnP d; first by rewrite big_add1 divn0 big1.\napply: (@addnI (d %| 0)); rewrite -(@big_ltn _ 0 _ 0 _ (dvdn d)) // big_mkord.\nrewrite (partition_big (fun i : 'I_n.+1 => inord (i %/ d)) 'I_(n %/ d).+1) //=.\nrewrite dvdn0 add1n -{1}[_.+1]card_ord -sum1_card; apply: eq_bigr => [[q ?] _].\nrewrite (bigD1 (inord (q * d))) /eq_op /= !inordK ?ltnS -?leq_divRL ?mulnK //.\nrewrite dvdn_mull ?big1 // => [[i /= ?] /andP[/eqP <- /negPf]].\nby rewrite eq_sym dvdn_eq inordK ?ltnS ?leq_div2r // => ->.\nQed.\n\nLemma logn_count_dvd p n : prime p -> logn p n = \\sum_(1 <= k < n) (p ^ k %| n).\nProof.\nrewrite big_add1 => p_prime; case: n => [|n]; first by rewrite logn0 big_geq.\nrewrite big_mkord -big_mkcond (eq_bigl _ _ (fun _ => pfactor_dvdn _ _ _)) //=.\nby rewrite big_ord_narrow ?sum1_card ?card_ord // -ltnS ltn_logl.\nQed.\n\n(* Truncated real log. *)\n\nDefinition trunc_log p n :=\n  let fix loop n k :=\n    if k is k'.+1 then if p <= n then (loop (n %/ p) k').+1 else 0 else 0\n  in loop n n.\n\nLemma trunc_log_bounds p n :\n  1 < p -> 0 < n -> let k := trunc_log p n in p ^ k <= n < p ^ k.+1.\nProof.\nrewrite {+}/trunc_log => p_gt1; have p_gt0 := ltnW p_gt1.\nelim: n {-2 5}n (leqnn n) => [|m IHm] [|n] //=; rewrite ltnS => le_n_m _.\nhave [le_p_n | // ] := leqP p _; rewrite 2!expnSr -leq_divRL -?ltn_divLR //.\nby apply: IHm; rewrite ?divn_gt0 // -ltnS (leq_trans (ltn_Pdiv _ _)).\nQed.\n\nLemma trunc_log_ltn p n : 1 < p -> n < p ^ (trunc_log p n).+1.\nProof.\nhave [-> | n_gt0] := posnP n; first by move=> /ltnW; rewrite expn_gt0.\nby case/trunc_log_bounds/(_ n_gt0)/andP.\nQed.\n\nLemma trunc_logP p n : 1 < p -> 0 < n -> p ^ trunc_log p n <= n.\nProof. by move=> p_gt1 /(trunc_log_bounds p_gt1)/andP[]. Qed.\n\nLemma trunc_log_max p k j : 1 < p -> p ^ j <= k -> j <= trunc_log p k.\nProof.\nmove=> p_gt1 le_pj_k; rewrite -ltnS -(@ltn_exp2l p) //.\nexact: leq_ltn_trans (trunc_log_ltn _ _).\nQed.\n\n(* pi- parts *)\n\n(* Testing for membership in set of prime factors. *)\n\nCanonical nat_pred_pred := Eval hnf in [predType of nat_pred].\n\nCoercion nat_pred_of_nat (p : nat) : nat_pred := pred1 p.\n\nSection NatPreds.\n\nVariables (n : nat) (pi : nat_pred).\n\nDefinition negn : nat_pred := [predC pi].\n\nDefinition pnat : pred nat := fun m => (m > 0) && all (mem pi) (primes m).\n\nDefinition partn := \\prod_(0 <= p < n.+1 | p \\in pi) p ^ logn p n.\n\nEnd NatPreds.\n\nNotation \"pi ^'\" := (negn pi) (at level 2, format \"pi ^'\") : nat_scope.\n\nNotation \"pi .-nat\" := (pnat pi) (at level 2, format \"pi .-nat\") : nat_scope.\n\nNotation \"n `_ pi\" := (partn n pi) : nat_scope.\n\nSection PnatTheory.\n\nImplicit Types (n p : nat) (pi rho : nat_pred).\n\nLemma negnK pi : pi^'^' =i pi.\nProof. by move=> p; apply: negbK. Qed.\n\nLemma eq_negn pi1 pi2 : pi1 =i pi2 -> pi1^' =i pi2^'.\nProof. by move=> eq_pi n; rewrite 3!inE /= eq_pi. Qed.\n\nLemma eq_piP m n : \\pi(m) =i \\pi(n) <-> \\pi(m) = \\pi(n).\nProof.\nrewrite /pi_of; have eqs := eq_sorted_irr ltn_trans ltnn.\nby split=> [|-> //]; move/(eqs _ _ (sorted_primes m) (sorted_primes n)) ->.\nQed.\n\nLemma part_gt0 pi n : 0 < n`_pi.\nProof. exact: prodn_gt0. Qed.\nHint Resolve part_gt0 : core.\n\nLemma sub_in_partn pi1 pi2 n :\n  {in \\pi(n), {subset pi1 <= pi2}} -> n`_pi1 %| n`_pi2.\nProof.\nmove=> pi12; rewrite ![n`__]big_mkcond /=.\napply (big_ind2 (fun m1 m2 => m1 %| m2)) => // [*|p _]; first exact: dvdn_mul.\nrewrite lognE -mem_primes; case: ifP => pi1p; last exact: dvd1n.\nby case: ifP => pr_p; [rewrite pi12 | rewrite if_same].\nQed.\n\nLemma eq_in_partn pi1 pi2 n : {in \\pi(n), pi1 =i pi2} -> n`_pi1 = n`_pi2.\nProof.\nby move=> pi12; apply/eqP; rewrite eqn_dvd ?sub_in_partn // => p /pi12->.\nQed.\n\nLemma eq_partn pi1 pi2 n : pi1 =i pi2 -> n`_pi1 = n`_pi2.\nProof. by move=> pi12; apply: eq_in_partn => p _. Qed.\n\nLemma partnNK pi n : n`_pi^'^' = n`_pi.\nProof. by apply: eq_partn; apply: negnK. Qed.\n\nLemma widen_partn m pi n :\n  n <= m -> n`_pi = \\prod_(0 <= p < m.+1 | p \\in pi) p ^ logn p n.\nProof.\nmove=> le_n_m; rewrite big_mkcond /=.\nrewrite [n`_pi](big_nat_widen _ _ m.+1) // big_mkcond /=.\napply: eq_bigr => p _; rewrite ltnS lognE.\nby case: and3P => [[_ n_gt0 p_dv_n]|]; rewrite ?if_same // andbC dvdn_leq.\nQed.\n\nLemma partn0 pi : 0`_pi = 1.\nProof. by apply: big1_seq => [] [|n]; rewrite andbC. Qed.\n\nLemma partn1 pi : 1`_pi = 1.\nProof. by apply: big1_seq => [] [|[|n]]; rewrite andbC. Qed.\n\nLemma partnM pi m n : m > 0 -> n > 0 -> (m * n)`_pi = m`_pi * n`_pi.\nProof.\nhave le_pmul m' n': m' > 0 -> n' <= m' * n' by move/prednK <-; apply: leq_addr.\nmove=> mpos npos; rewrite !(@widen_partn (n * m)) 3?(le_pmul, mulnC) //.\nrewrite !big_mkord -big_split; apply: eq_bigr => p _ /=.\nby rewrite lognM // expnD.\nQed.\n\nLemma partnX pi m n : (m ^ n)`_pi = m`_pi ^ n.\nProof.\nelim: n => [|n IHn]; first exact: partn1.\nrewrite expnS; case: (posnP m) => [->|m_gt0]; first by rewrite partn0 exp1n.\nby rewrite expnS partnM ?IHn // expn_gt0 m_gt0.\nQed.\n\nLemma partn_dvd pi m n : n > 0 -> m %| n -> m`_pi %| n`_pi.\nProof.\nmove=> n_gt0 dvmn; case/dvdnP: dvmn n_gt0 => q ->{n}.\nby rewrite muln_gt0 => /andP[q_gt0 m_gt0]; rewrite partnM ?dvdn_mull.\nQed.\n\nLemma p_part p n : n`_p = p ^ logn p n.\nProof.\ncase (posnP (logn p n)) => [log0 |].\n  by rewrite log0 [n`_p]big1_seq // => q; case/andP; move/eqnP->; rewrite log0.\nrewrite logn_gt0 mem_primes; case/and3P=> _ n_gt0 dv_p_n.\nhave le_p_n: p < n.+1 by rewrite ltnS dvdn_leq.\nby rewrite [n`_p]big_mkord (big_pred1 (Ordinal le_p_n)).\nQed.\n\nLemma p_part_eq1 p n : (n`_p == 1) = (p \\notin \\pi(n)).\nProof.\nrewrite mem_primes p_part lognE; case: and3P => // [[p_pr _ _]].\nby rewrite -dvdn1 pfactor_dvdn // logn1.\nQed.\n\nLemma p_part_gt1 p n : (n`_p > 1) = (p \\in \\pi(n)).\nProof. by rewrite ltn_neqAle part_gt0 andbT eq_sym p_part_eq1 negbK. Qed.\n\nLemma primes_part pi n : primes n`_pi = filter (mem pi) (primes n).\nProof.\nhave ltnT := ltn_trans.\ncase: (posnP n) => [-> | n_gt0]; first by rewrite partn0.\napply: (eq_sorted_irr ltnT ltnn); rewrite ?(sorted_primes, sorted_filter) //.\nmove=> p; rewrite mem_filter /= !mem_primes n_gt0 part_gt0 /=.\napply/andP/and3P=> [[p_pr] | [pi_p p_pr dv_p_n]].\n  rewrite /partn; apply big_ind => [|n1 n2 IHn1 IHn2|q pi_q].\n  - by rewrite dvdn1; case: eqP p_pr => // ->.\n  - by rewrite Euclid_dvdM //; case/orP.\n  rewrite -{1}(expn1 p) pfactor_dvdn // lognX muln_gt0.\n  rewrite logn_gt0 mem_primes n_gt0 - andbA /=; case/and3P=> pr_q dv_q_n.\n  by rewrite logn_prime //; case: eqP => // ->.\nhave le_p_n: p < n.+1 by rewrite ltnS dvdn_leq.\nrewrite [n`_pi]big_mkord (bigD1 (Ordinal le_p_n)) //= dvdn_mulr //.\nby rewrite lognE p_pr n_gt0 dv_p_n expnS dvdn_mulr.\nQed.\n\nLemma filter_pi_of n m : n < m -> filter \\pi(n) (index_iota 0 m) = primes n.\nProof.\nmove=> lt_n_m; have ltnT := ltn_trans; apply: (eq_sorted_irr ltnT ltnn).\n- by rewrite sorted_filter // iota_ltn_sorted.\n- exact: sorted_primes.\nmove=> p; rewrite mem_filter mem_index_iota /= mem_primes; case: and3P => //.\nby case=> _ n_gt0 dv_p_n; apply: leq_ltn_trans lt_n_m; apply: dvdn_leq.\nQed.\n\nLemma partn_pi n : n > 0 -> n`_\\pi(n) = n.\nProof.\nmove=> n_gt0; rewrite {3}(prod_prime_decomp n_gt0) prime_decompE big_map.\nby rewrite -[n`__]big_filter filter_pi_of.\nQed.\n\nLemma partnT n : n > 0 -> n`_predT = n.\nProof.\nmove=> n_gt0; rewrite -{2}(partn_pi n_gt0) {2}/partn big_mkcond /=.\nby apply: eq_bigr => p _; rewrite -logn_gt0; case: (logn p _).\nQed.\n\nLemma partnC pi n : n > 0 -> n`_pi * n`_pi^' = n.\nProof.\nmove=> n_gt0; rewrite -{3}(partnT n_gt0) /partn.\ndo 2!rewrite mulnC big_mkcond /=; rewrite -big_split; apply: eq_bigr => p _ /=.\nby rewrite mulnC inE /=; case: (p \\in pi); rewrite /= (muln1, mul1n).\nQed.\n\nLemma dvdn_part pi n : n`_pi %| n.\nProof. by case: n => // n; rewrite -{2}[n.+1](@partnC pi) // dvdn_mulr. Qed.\n\nLemma logn_part p m : logn p m`_p = logn p m.\nProof.\ncase p_pr: (prime p); first by rewrite p_part pfactorK.\nby rewrite lognE (lognE p m) p_pr.\nQed.\n    \nLemma partn_lcm pi m n : m > 0 -> n > 0 -> (lcmn m n)`_pi = lcmn m`_pi n`_pi.\nProof.\nmove=> m_gt0 n_gt0; have p_gt0: lcmn m n > 0 by rewrite lcmn_gt0 m_gt0.\napply/eqP; rewrite eqn_dvd dvdn_lcm !partn_dvd ?dvdn_lcml ?dvdn_lcmr //.\nrewrite -(dvdn_pmul2r (part_gt0 pi^' (lcmn m n))) partnC // dvdn_lcm !andbT.\nrewrite -{1}(partnC pi m_gt0) andbC -{1}(partnC pi n_gt0).\nby rewrite !dvdn_mul ?partn_dvd ?dvdn_lcml ?dvdn_lcmr.\nQed.\n\nLemma partn_gcd pi m n : m > 0 -> n > 0 -> (gcdn m n)`_pi = gcdn m`_pi n`_pi.\nProof.\nmove=> m_gt0 n_gt0; have p_gt0: gcdn m n > 0 by rewrite gcdn_gt0 m_gt0.\napply/eqP; rewrite eqn_dvd dvdn_gcd !partn_dvd ?dvdn_gcdl ?dvdn_gcdr //=.\nrewrite -(dvdn_pmul2r (part_gt0 pi^' (gcdn m n))) partnC // dvdn_gcd.\nrewrite -{3}(partnC pi m_gt0) andbC -{3}(partnC pi n_gt0).\nby rewrite !dvdn_mul ?partn_dvd ?dvdn_gcdl ?dvdn_gcdr.\nQed.\n\nLemma partn_biglcm (I : finType) (P : pred I) F pi :\n    (forall i, P i -> F i > 0) ->\n  (\\big[lcmn/1%N]_(i | P i) F i)`_pi = \\big[lcmn/1%N]_(i | P i) (F i)`_pi.\nProof.\nmove=> F_gt0; set m := \\big[lcmn/1%N]_(i | P i) F i.\nhave m_gt0: 0 < m by elim/big_ind: m => // p q p_gt0; rewrite lcmn_gt0 p_gt0.\napply/eqP; rewrite eqn_dvd andbC; apply/andP; split.\n  by apply/dvdn_biglcmP=> i Pi; rewrite partn_dvd // (@biglcmn_sup _ i).\nrewrite -(dvdn_pmul2r (part_gt0 pi^' m)) partnC //.\napply/dvdn_biglcmP=> i Pi; rewrite -(partnC pi (F_gt0 i Pi)) dvdn_mul //.\n  by rewrite (@biglcmn_sup _ i).\nby rewrite partn_dvd // (@biglcmn_sup _ i).\nQed.\n\nLemma partn_biggcd (I : finType) (P : pred I) F pi :\n    #|SimplPred P| > 0 -> (forall i, P i -> F i > 0) ->\n  (\\big[gcdn/0]_(i | P i) F i)`_pi = \\big[gcdn/0]_(i | P i) (F i)`_pi.\nProof.\nmove=> ntP F_gt0; set d := \\big[gcdn/0]_(i | P i) F i.\nhave d_gt0: 0 < d.\n  case/card_gt0P: ntP => i /= Pi; have:= F_gt0 i Pi.\n  rewrite !lt0n -!dvd0n; apply: contra => dv0d.\n  by rewrite (dvdn_trans dv0d) // (@biggcdn_inf _ i).\napply/eqP; rewrite eqn_dvd; apply/andP; split.\n  by apply/dvdn_biggcdP=> i Pi; rewrite partn_dvd ?F_gt0 // (@biggcdn_inf _ i).\nrewrite -(dvdn_pmul2r (part_gt0 pi^' d)) partnC //.\napply/dvdn_biggcdP=> i Pi; rewrite -(partnC pi (F_gt0 i Pi)) dvdn_mul //.\n  by rewrite (@biggcdn_inf _ i).\nby rewrite partn_dvd ?F_gt0 // (@biggcdn_inf _ i).\nQed.\n\nLemma sub_in_pnat pi rho n :\n  {in \\pi(n), {subset pi <= rho}} -> pi.-nat n -> rho.-nat n.\nProof.\nrewrite /pnat => subpi /andP[-> pi_n].\nby apply/allP=> p pr_p; apply: subpi => //; apply: (allP pi_n).\nQed.\n\nLemma eq_in_pnat pi rho n : {in \\pi(n), pi =i rho} -> pi.-nat n = rho.-nat n.\nProof. by move=> eqpi; apply/idP/idP; apply: sub_in_pnat => p /eqpi->. Qed.\n\nLemma eq_pnat pi rho n : pi =i rho -> pi.-nat n = rho.-nat n.\nProof. by move=> eqpi; apply: eq_in_pnat => p _. Qed.\n\nLemma pnatNK pi n : pi^'^'.-nat n = pi.-nat n.\nProof. exact: eq_pnat (negnK pi). Qed.\n\nLemma pnatI pi rho n : [predI pi & rho].-nat n = pi.-nat n && rho.-nat n.\nProof. by rewrite /pnat andbCA all_predI !andbA andbb. Qed.\n\nLemma pnat_mul pi m n : pi.-nat (m * n) = pi.-nat m && pi.-nat n.\nProof.\nrewrite /pnat muln_gt0 andbCA -andbA andbCA.\ncase: posnP => // n_gt0; case: posnP => //= m_gt0.\napply/allP/andP=> [pi_mn | [pi_m pi_n] p].\n  by split; apply/allP=> p m_p; apply: pi_mn; rewrite primes_mul // m_p ?orbT.\nby rewrite primes_mul // => /orP[]; [apply: (allP pi_m) | apply: (allP pi_n)].\nQed.\n\nLemma pnat_exp pi m n : pi.-nat (m ^ n) = pi.-nat m || (n == 0).\nProof. by case: n => [|n]; rewrite orbC // /pnat expn_gt0 orbC primes_exp. Qed.\n\nLemma part_pnat pi n : pi.-nat n`_pi.\nProof.\nrewrite /pnat primes_part part_gt0.\nby apply/allP=> p; rewrite mem_filter => /andP[].\nQed.\n\nLemma pnatE pi p : prime p -> pi.-nat p = (p \\in pi).\nProof. by move=> pr_p; rewrite /pnat prime_gt0 ?primes_prime //= andbT. Qed.\n\nLemma pnat_id p : prime p -> p.-nat p.\nProof. by move=> pr_p; rewrite pnatE ?inE /=. Qed.\n\nLemma coprime_pi' m n : m > 0 -> n > 0 -> coprime m n = \\pi(m)^'.-nat n.\nProof.\nby move=> m_gt0 n_gt0; rewrite /pnat n_gt0 all_predC coprime_has_primes.\nQed.\n\nLemma pnat_pi n : n > 0 -> \\pi(n).-nat n.\nProof. by rewrite /pnat => ->; apply/allP. Qed.\n\nLemma pi_of_dvd m n : m %| n -> n > 0 -> {subset \\pi(m) <= \\pi(n)}.\nProof.\nmove=> m_dv_n n_gt0 p; rewrite !mem_primes n_gt0 => /and3P[-> _ p_dv_m].\nexact: dvdn_trans p_dv_m m_dv_n.\nQed.\n\nLemma pi_ofM m n : m > 0 -> n > 0 -> \\pi(m * n) =i [predU \\pi(m) & \\pi(n)].\nProof. by move=> m_gt0 n_gt0 p; apply: primes_mul. Qed.\n\nLemma pi_of_part pi n : n > 0 -> \\pi(n`_pi) =i [predI \\pi(n) & pi].\nProof. by move=> n_gt0 p; rewrite /pi_of primes_part mem_filter andbC. Qed.\n\nLemma pi_of_exp p n : n > 0 -> \\pi(p ^ n) = \\pi(p).\nProof. by move=> n_gt0; rewrite /pi_of primes_exp. Qed.\n\nLemma pi_of_prime p : prime p -> \\pi(p) =i (p : nat_pred).\nProof. by move=> pr_p q; rewrite /pi_of primes_prime // mem_seq1. Qed.\n\nLemma p'natEpi p n : n > 0 -> p^'.-nat n = (p \\notin \\pi(n)).\nProof. by case: n => // n _; rewrite /pnat all_predC has_pred1. Qed.\n\nLemma p'natE p n : prime p -> p^'.-nat n = ~~ (p %| n).\nProof.\ncase: n => [|n] p_pr; first by case: p p_pr.\nby rewrite p'natEpi // mem_primes p_pr.\nQed.\n\nLemma pnatPpi pi n p : pi.-nat n -> p \\in \\pi(n) -> p \\in pi.\nProof. by case/andP=> _ /allP; apply. Qed.\n\nLemma pnat_dvd m n pi : m %| n -> pi.-nat n -> pi.-nat m.\nProof. by case/dvdnP=> q ->; rewrite pnat_mul; case/andP. Qed.\n\nLemma pnat_div m n pi : m %| n -> pi.-nat n -> pi.-nat (n %/ m).\nProof.\ncase/dvdnP=> q ->; rewrite pnat_mul andbC => /andP[].\nby case: m => // m _; rewrite mulnK.\nQed.\n\nLemma pnat_coprime pi m n : pi.-nat m -> pi^'.-nat n -> coprime m n.\nProof.\ncase/andP=> m_gt0 pi_m /andP[n_gt0 pi'_n]; rewrite coprime_has_primes //.\nby apply/hasPn=> p /(allP pi'_n); apply/contra/allP.\nQed.\n\nLemma p'nat_coprime pi m n : pi^'.-nat m -> pi.-nat n -> coprime m n.\nProof. by move=> pi'm pi_n; rewrite (pnat_coprime pi'm) ?pnatNK. Qed.\n\nLemma sub_pnat_coprime pi rho m n :\n  {subset rho <= pi^'} -> pi.-nat m -> rho.-nat n -> coprime m n.\nProof.\nby move=> pi'rho pi_m; move/(sub_in_pnat (in1W pi'rho)); apply: pnat_coprime.\nQed.\n\nLemma coprime_partC pi m n : coprime m`_pi n`_pi^'.\nProof. by apply: (@pnat_coprime pi); apply: part_pnat. Qed.\n\nLemma pnat_1 pi n : pi.-nat n -> pi^'.-nat n -> n = 1.\nProof.\nby move=> pi_n pi'_n; rewrite -(eqnP (pnat_coprime pi_n pi'_n)) gcdnn.\nQed.\n\nLemma part_pnat_id pi n : pi.-nat n -> n`_pi = n.\nProof.\ncase/andP=> n_gt0 pi_n.\nrewrite -{2}(partnT n_gt0) /partn big_mkcond; apply: eq_bigr=> p _.\ncase: (posnP (logn p n)) => [-> |]; first by rewrite if_same.\nby rewrite logn_gt0 => /(allP pi_n)/= ->.\nQed.\n\nLemma part_p'nat pi n : pi^'.-nat n -> n`_pi = 1.\nProof.\ncase/andP=> n_gt0 pi'_n; apply: big1_seq => p /andP[pi_p _].\ncase: (posnP (logn p n)) => [-> //|].\nby rewrite logn_gt0; move/(allP pi'_n); case/negP.\nQed.\n\nLemma partn_eq1 pi n : n > 0 -> (n`_pi == 1) = pi^'.-nat n.\nProof.\nmove=> n_gt0; apply/eqP/idP=> [pi_n_1|]; last exact: part_p'nat.\nby rewrite -(partnC pi n_gt0) pi_n_1 mul1n part_pnat.\nQed.\n\nLemma pnatP pi n :\n  n > 0 -> reflect (forall p, prime p -> p %| n -> p \\in pi) (pi.-nat n).\nProof.\nmove=> n_gt0; rewrite /pnat n_gt0.\napply: (iffP allP) => /= pi_n p => [pr_p p_n|].\n  by rewrite pi_n // mem_primes pr_p n_gt0.\nby rewrite mem_primes n_gt0 /=; case/andP; move: p.\nQed.\n\nLemma pi_pnat pi p n : p.-nat n -> p \\in pi -> pi.-nat n.\nProof.\nmove=> p_n pi_p; have [n_gt0 _] := andP p_n.\nby apply/pnatP=> // q q_pr /(pnatP _ n_gt0 p_n _ q_pr)/eqnP->.\nQed.\n\nLemma p_natP p n : p.-nat n -> {k | n = p ^ k}.\nProof. by move=> p_n; exists (logn p n); rewrite -p_part part_pnat_id. Qed.\n\nLemma pi'_p'nat pi p n : pi^'.-nat n -> p \\in pi -> p^'.-nat n.\nProof.\nmove=> pi'n pi_p; apply: sub_in_pnat pi'n => q _.\nby apply: contraNneq => ->.\nQed.\n \nLemma pi_p'nat p pi n : pi.-nat n -> p \\in pi^' -> p^'.-nat n.\nProof. by move=> pi_n; apply: pi'_p'nat; rewrite pnatNK. Qed.\n \nLemma partn_part pi rho n : {subset pi <= rho} -> n`_rho`_pi = n`_pi.\nProof.\nmove=> pi_sub_rho; have [->|n_gt0] := posnP n; first by rewrite !partn0 partn1.\nrewrite -{2}(partnC rho n_gt0) partnM //.\nsuffices: pi^'.-nat n`_rho^' by move/part_p'nat->; rewrite muln1.\nby apply: sub_in_pnat (part_pnat _ _) => q _; apply/contra/pi_sub_rho.\nQed.\n\nLemma partnI pi rho n : n`_[predI pi & rho] = n`_pi`_rho.\nProof.\nrewrite -(@partnC [predI pi & rho] _`_rho) //.\nsymmetry; rewrite 2?partn_part; try by move=> p /andP [].\nrewrite mulnC part_p'nat ?mul1n // pnatNK pnatI part_pnat andbT.\nexact: pnat_dvd (dvdn_part _ _) (part_pnat _ _).\nQed.\n\nLemma odd_2'nat n : odd n = 2^'.-nat n.\nProof. by case: n => // n; rewrite p'natE // dvdn2 negbK. Qed.\n\nEnd PnatTheory.\nHint Resolve part_gt0 : core.\n\n(************************************)\n(* Properties of the divisors list. *)\n(************************************)\n\nLemma divisors_correct n : n > 0 ->\n  [/\\ uniq (divisors n), sorted leq (divisors n)\n    & forall d, (d \\in divisors n) = (d %| n)].\nProof.\nmove/prod_prime_decomp=> def_n; rewrite {4}def_n {def_n}.\nhave: all prime (primes n) by apply/allP=> p; rewrite mem_primes; case/andP.\nhave:= primes_uniq n; rewrite /primes /divisors; move/prime_decomp: n.\nelim=> [|[p e] pd] /=; first by split=> // d; rewrite big_nil dvdn1 mem_seq1.\nrewrite big_cons /=; move: (foldr _ _ pd) => divs.\nmove=> IHpd /andP[npd_p Upd] /andP[pr_p pr_pd].\nhave lt0p: 0 < p by apply: prime_gt0.\nhave {IHpd Upd}[Udivs Odivs mem_divs] := IHpd Upd pr_pd.\nhave ndivs_p m: p * m \\notin divs.\n  suffices: p \\notin divs; rewrite !mem_divs.\n    by apply: contra => /dvdnP[n ->]; rewrite mulnCA dvdn_mulr.\n  have ndv_p_1: ~~(p %| 1) by rewrite dvdn1 neq_ltn orbC prime_gt1.\n  rewrite big_seq; elim/big_ind: _ => [//|u v npu npv|[q f] /= pd_qf].\n    by rewrite Euclid_dvdM //; apply/norP.\n  elim: (f) => // f'; rewrite expnS Euclid_dvdM // orbC negb_or => -> {f'}/=.\n  have pd_q: q \\in unzip1 pd by apply/mapP; exists (q, f).\n  by apply: contra npd_p; rewrite dvdn_prime2 // ?(allP pr_pd) // => /eqP->.\nelim: e => [|e] /=; first by split=> // d; rewrite mul1n.\nhave Tmulp_inj: injective (NatTrec.mul p).\n  by move=> u v /eqP; rewrite !natTrecE eqn_pmul2l // => /eqP.\nmove: (iter e _ _) => divs' [Udivs' Odivs' mem_divs']; split=> [||d].\n- rewrite merge_uniq cat_uniq map_inj_uniq // Udivs Udivs' andbT /=.\n  apply/hasP=> [[d dv_d /mapP[d' _ def_d]]].\n  by case/idPn: dv_d; rewrite def_d natTrecE.\n- rewrite (merge_sorted leq_total) //; case: (divs') Odivs' => //= d ds.\n  rewrite (@map_path _ _ _ _ leq xpred0) ?has_pred0 // => u v _.\n  by rewrite !natTrecE leq_pmul2l.\nrewrite mem_merge mem_cat; case dv_d_p: (p %| d).\n  case/dvdnP: dv_d_p => d' ->{d}; rewrite mulnC (negbTE (ndivs_p d')) orbF.\n  rewrite expnS -mulnA dvdn_pmul2l // -mem_divs'.\n  by rewrite -(mem_map Tmulp_inj divs') natTrecE.\ncase pdiv_d: (_ \\in _).\n  by case/mapP: pdiv_d dv_d_p => d' _ ->; rewrite natTrecE dvdn_mulr.\nrewrite mem_divs Gauss_dvdr // coprime_sym.\nby rewrite coprime_expl ?prime_coprime ?dv_d_p.\nQed.\n\nLemma sorted_divisors n : sorted leq (divisors n).\nProof. by case: (posnP n) => [-> | /divisors_correct[]]. Qed.\n\nLemma divisors_uniq n : uniq (divisors n).\nProof. by case: (posnP n) => [-> | /divisors_correct[]]. Qed.\n\nLemma sorted_divisors_ltn n : sorted ltn (divisors n).\nProof. by rewrite ltn_sorted_uniq_leq divisors_uniq sorted_divisors. Qed.\n\nLemma dvdn_divisors d m : 0 < m -> (d %| m) = (d \\in divisors m).\nProof. by case/divisors_correct. Qed.\n\nLemma divisor1 n : 1 \\in divisors n.\nProof. by case: n => // n; rewrite -dvdn_divisors // dvd1n. Qed.\n\nLemma divisors_id n : 0 < n -> n \\in divisors n.\nProof. by move/dvdn_divisors <-. Qed.\n\n(* Big sum / product lemmas*)\n\nLemma dvdn_sum d I r (K : pred I) F :\n  (forall i, K i -> d %| F i) -> d %| \\sum_(i <- r | K i) F i.\nProof. by move=> dF; elim/big_ind: _ => //; apply: dvdn_add. Qed.\n\nLemma dvdn_partP n m : 0 < n ->\n  reflect (forall p, p \\in \\pi(n) -> n`_p %| m) (n %| m).\nProof.\nmove=> n_gt0; apply: (iffP idP) => n_dvd_m => [p _|].\n  by apply: dvdn_trans n_dvd_m; apply: dvdn_part.\nhave [-> // | m_gt0] := posnP m.\nrewrite -(partnT n_gt0) -(partnT m_gt0).\nrewrite !(@widen_partn (m + n)) ?leq_addl ?leq_addr // /in_mem /=.\nelim/big_ind2: _ => // [* | q _]; first exact: dvdn_mul.\nhave [-> // | ] := posnP (logn q n); rewrite logn_gt0 => q_n.\nhave pr_q: prime q by move: q_n; rewrite mem_primes; case/andP.\nby have:= n_dvd_m q q_n; rewrite p_part !pfactor_dvdn // pfactorK.\nQed.\n\nLemma modn_partP n a b : 0 < n ->\n  reflect (forall p : nat, p \\in \\pi(n) -> a = b %[mod n`_p]) (a == b %[mod n]).\nProof.\nmove=> n_gt0; wlog le_b_a: a b / b <= a.\n  move=> IH; case: (leqP b a) => [|/ltnW] /IH {IH}// IH.\n  by rewrite eq_sym; apply: (iffP IH) => eqab p; move/eqab.\nrewrite eqn_mod_dvd //; apply: (iffP (dvdn_partP _ n_gt0)) => eqab p /eqab;\n  by rewrite -eqn_mod_dvd // => /eqP.\nQed.\n\n(* The Euler totient function *)\n\nLemma totientE n :\n  n > 0 -> totient n = \\prod_(p <- primes n) (p.-1 * p ^ (logn p n).-1).\nProof.\nmove=> n_gt0; rewrite /totient n_gt0 prime_decompE unlock.\nby elim: (primes n) => //= [p pr ->]; rewrite !natTrecE.\nQed.\n\nLemma totient_gt0 n : (0 < totient n) = (0 < n).\nProof.\ncase: n => // n; rewrite totientE // big_seq_cond prodn_cond_gt0 // => p.\nby rewrite mem_primes muln_gt0 expn_gt0; case: p => [|[|]].\nQed.\n\nLemma totient_pfactor p e :\n  prime p -> e > 0 -> totient (p ^ e) = p.-1 * p ^ e.-1.\nProof.\nmove=> p_pr e_gt0; rewrite totientE ?expn_gt0 ?prime_gt0 //.\nby rewrite primes_exp // primes_prime // unlock /= muln1 pfactorK.\nQed.\n\nLemma totient_coprime m n :\n  coprime m n -> totient (m * n) = totient m * totient n.\nProof.\nmove=> co_mn; have [-> //| m_gt0] := posnP m.\nhave [->|n_gt0] := posnP n; first by rewrite !muln0.\nrewrite !totientE ?muln_gt0 ?m_gt0 //.\nhave /(eq_big_perm _)->: perm_eq (primes (m * n)) (primes m ++ primes n).\n  apply: uniq_perm_eq => [||p]; first exact: primes_uniq.\n    by rewrite cat_uniq !primes_uniq -coprime_has_primes // co_mn.\n  by rewrite mem_cat primes_mul.\nrewrite big_cat /= !big_seq.\ncongr (_ * _); apply: eq_bigr => p; rewrite mem_primes => /and3P[_ _ dvp].\n  rewrite (mulnC m) logn_Gauss //; move: co_mn.\n  by rewrite -(divnK dvp) coprime_mull => /andP[].\nrewrite logn_Gauss //; move: co_mn.\nby rewrite coprime_sym -(divnK dvp) coprime_mull => /andP[].\nQed.\n\nLemma totient_count_coprime n : totient n = \\sum_(0 <= d < n) coprime n d.\nProof.\nelim: {n}_.+1 {-2}n (ltnSn n) => // m IHm n; rewrite ltnS => le_n_m.\ncase: (leqP n 1) => [|lt1n]; first by rewrite unlock; case: (n) => [|[]].\npose p := pdiv n; have p_pr: prime p by apply: pdiv_prime.\nhave p1 := prime_gt1 p_pr; have p0 := ltnW p1.\npose np := n`_p; pose np' := n`_p^'.\nhave co_npp': coprime np np' by rewrite coprime_partC.\nhave [n0 np0 np'0]: [/\\ n > 0, np > 0 & np' > 0] by rewrite ltnW ?part_gt0.\nhave def_n: n = np * np' by rewrite partnC.\nhave lnp0: 0 < logn p n by rewrite lognE p_pr n0 pdiv_dvd.\npose in_mod k (k0 : k > 0) d := Ordinal (ltn_pmod d k0).\nrewrite {1}def_n totient_coprime // {IHm}(IHm np') ?big_mkord; last first.\n  apply: leq_trans le_n_m; rewrite def_n ltn_Pmull //.\n  by rewrite /np p_part -(expn0 p) ltn_exp2l.\nhave ->: totient np = #|[pred d : 'I_np | coprime np d]|.\n  rewrite {1}[np]p_part totient_pfactor //=; set q := p ^ _.\n  apply: (@addnI (1 * q)); rewrite -mulnDl [1 + _]prednK // mul1n.\n  have def_np: np = p * q by rewrite -expnS prednK // -p_part.\n  pose mulp := [fun d : 'I_q => in_mod _ np0 (p * d)].\n  rewrite -def_np -{1}[np]card_ord -(cardC (mem (codom mulp))).\n  rewrite card_in_image => [|[d1 ltd1] [d2 ltd2] /= _ _ []]; last first.\n    move/eqP; rewrite def_np -!muln_modr ?modn_small //.\n    by rewrite eqn_pmul2l // => eq_op12; apply/eqP.\n  rewrite card_ord; congr (q + _); apply: eq_card => d /=.\n  rewrite !inE [np in coprime np _]p_part coprime_pexpl ?prime_coprime //.\n  congr (~~ _); apply/codomP/idP=> [[d' -> /=] | /dvdnP[r def_d]].\n    by rewrite def_np -muln_modr // dvdn_mulr.\n  do [rewrite mulnC; case: d => d ltd /=] in def_d *.\n  have ltr: r < q by rewrite -(ltn_pmul2l p0) -def_np -def_d.\n  by exists (Ordinal ltr); apply: val_inj; rewrite /= -def_d modn_small.\npose h (d : 'I_n) := (in_mod _ np0 d, in_mod _ np'0 d).\npose h' (d : 'I_np * 'I_np') := in_mod _ n0 (chinese np np' d.1 d.2).\nrewrite -!big_mkcond -sum_nat_const pair_big (reindex_onto h h') => [|[d d'] _].\n  apply: eq_bigl => [[d ltd] /=]; rewrite !inE /= -val_eqE /= andbC.\n  rewrite !coprime_modr def_n -chinese_mod // -coprime_mull -def_n.\n  by rewrite modn_small ?eqxx.\napply/eqP; rewrite /eq_op /= /eq_op /= !modn_dvdm ?dvdn_part //.\nby rewrite chinese_modl // chinese_modr // !modn_small ?eqxx ?ltn_ord.\nQed.\n\n\n\n", "meta": {"author": "palmskog", "repo": "mathcomp-experiment", "sha": "67a6e83c025784b1e6f646a30dde38e0f33060eb", "save_path": "github-repos/coq/palmskog-mathcomp-experiment", "path": "github-repos/coq/palmskog-mathcomp-experiment/mathcomp-experiment-67a6e83c025784b1e6f646a30dde38e0f33060eb/ssreflect/prime.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145053, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6587548644520427}}
{"text": "Require Import CoqStock.Invs.\nRequire Import CoqStock.List.\n\nRequire Import Brzozowski.Alphabet.\nRequire Import Brzozowski.Derive.\nRequire Import Brzozowski.Language.\n\nCoInductive bisimilar : lang -> lang -> Prop :=\n  | bisim : forall (P Q: lang),\n      ([] \\in P <-> [] \\in Q)\n    /\\\n      (forall (a: alphabet),\n        bisimilar (derive_lang a P) (derive_lang a Q)\n      )\n    -> bisimilar P Q.\n\nNotation \"P <<->> Q\" := (bisimilar P Q) (at level 80).\n\nLemma equivalence_impl_derive_lang_is_equivalent:\n    forall (P Q: lang) (a: alphabet),\n    P {<->} Q ->\n    derive_lang a P {<->} derive_lang a Q.\nProof.\nunfold lang_iff.\nintros.\nunfold derive_lang.\nunfold elem.\nspecialize H with (s := (a :: s)).\nassumption.\nQed.\n\nLemma equivalence_impl_bisimilar:\n  forall (P Q: lang),\n  P {<->} Q -> P <<->> Q.\nProof.\ncofix G.\nintros.\nconstructor.\nunfold lang_iff in H.\nsplit.\n- apply H.\n- intros.\n  apply G.\n  apply equivalence_impl_derive_lang_is_equivalent.\n  assumption.\nQed.\n\nLemma fold_derive_lang:\n  forall (R: lang) (a: alphabet) (s: str),\n  (a :: s) \\in R <-> s \\in (derive_lang a R).\nProof.\nintros.\nunfold derive_lang.\nunfold elem.\nreflexivity.\nQed.\n\nLemma bisimilar_impl_equivalence:\n  forall (P Q: lang),\n  P <<->> Q -> P {<->} Q.\nProof.\nunfold lang_iff.\nintros.\ngeneralize dependent P.\ngeneralize dependent Q.\ninduction s.\n- intros.\n  inversion H.\n  destruct H0.\n  assumption.\n- intros.\n  inversion H.\n  destruct H0.\n  specialize H3 with (a := a).\n  subst.\n  rewrite (fold_derive_lang P a s).\n  rewrite (fold_derive_lang Q a s).\n  apply IHs.\n  assumption.\nQed.\n\nTheorem bisimilar_is_equivalence:\n  forall (P Q: lang),\n  P <<->> Q <-> P {<->} Q.\nProof.\nsplit.\n- apply bisimilar_impl_equivalence.\n- apply equivalence_impl_bisimilar.\nQed.", "meta": {"author": "awalterschulze", "repo": "regex-reexamined-coq", "sha": "71e4a82790f269814fc3eb33e9e9cd1b49b559c5", "save_path": "github-repos/coq/awalterschulze-regex-reexamined-coq", "path": "github-repos/coq/awalterschulze-regex-reexamined-coq/regex-reexamined-coq-71e4a82790f269814fc3eb33e9e9cd1b49b559c5/src/Coinduction/Bisimilar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6587548580307385}}
{"text": "\nRequire Export A004list.\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.\nExample test_length2 :\n    length bool (cons bool true (nil bool)) = 1.\nProof. reflexivity. Qed.\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\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\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\nd (b a 5)           ==> invalid. lack of type\nd mumble (b a 5)    ==> valid. X = mumble\nd bool (b a 5)         ==> valid. X = bool\ne bool true            ==> valid. X = bool.\ne mumble (b c 0)    ==> valid. X = mumble.\ne bool (b c 0)        ==> invalid. mumble <> bool\nc                  ==> valid. mumble.\n*)\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\nEnd MumbleBaz.\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\nFixpoint repeat {X : Type} (n : X) (count : nat) : list X :=\n  match count with\n    | 0 => []\n    | S count' => n :: repeat n count'\n  end.\n\nExample test_repeat1:\n  repeat true 2 = cons true (cons true nil).\nProof. reflexivity. Qed.\n\nTheorem nil_app : forall X:Type, forall l:list X,\n  app [] l = l.\nProof. reflexivity. Qed.\n\n\nTheorem rev_snoc : forall X : Type,\n                     forall v : X,\n                     forall s : list X,\n  rev (snoc s v) = v :: (rev s).\nProof.\n  intros.\n  induction s.\n  reflexivity.\n  simpl.\n  rewrite IHs.\n  reflexivity.\nQed.\n\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  simpl.\n  rewrite rev_snoc.\n  rewrite IHl.\n  reflexivity.\nQed.\n\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.\n  induction l1.\n  reflexivity.\n  simpl.\n  rewrite IHl1.\n  reflexivity.\nQed.\n\n\nInductive prod (X Y : Type) : Type :=\n  pair : X -> Y -> prod X Y.\n\nArguments pair {X} {Y} _ _.\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\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X * Y) :=\n  match (lx,ly) with\n  | ([],_) => []\n  | (_,[]) => []\n  | (x::tx, y::ty) => (x,y) :: (combine tx ty)\n  end.\n\n(* combine : forall X Y: Type -> list X -> list Y -> list (prod X Y) *)\n(*\nEval compute in (combine [1;2] [false;false;true;true]).\n  ==> [(1,false);(2,false)]\n*)\n\nFixpoint split\n         {X Y : Type} (l : list (X * Y))\n           : (list X) * (list Y) :=\n  match l with\n    | [] => ([], [])\n    | (x,y)::t => let (xs',ys') := split t in\n                 (x :: xs', y :: ys')\n  end.\n\n\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 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\n\nDefinition hd_opt {X : Type} (l : list X) : option X :=\n  match l with\n    | [] => None\n    | h :: _ => Some h\n  end.\n\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\nDefinition minustwo(n:nat):nat :=\n  match n with\n    | 0 => 0\n    | S 0 => 0\n    | S (S n) => n\n  end.\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity. Qed.\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 : plus3 4 = 7.\nProof. reflexivity. Qed.\nExample test_plus3' : doit3times plus3 0 = 9.\nProof. reflexivity. Qed.\nExample test_plus3'' : doit3times (plus 3) 0 = 9.\nProof. reflexivity. Qed.\n\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\n\nTheorem uncurry_curry : forall (X Y Z : Type) (f : X -> Y -> Z) x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  intros.\n  unfold prod_curry.\n  unfold prod_uncurry.\n  simpl.\n  reflexivity.\nQed.\n\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                               (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros.\n  unfold prod_curry.\n  unfold prod_uncurry.\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\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\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun x => (andb (evenb x) (bgt_nat x 7))) l.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity. Qed.\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\n\n\nDefinition partition {X : Type} (test : X -> bool) (l : list X)\n                     : list X * list X :=\n  (filter test l,\n   filter (fun x => (negb (test x))) 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\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.\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 snoc_append : forall (X : Type) (l: list X) (x: X),\n  snoc l x = l ++ [x].\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem map_append : forall (X Y: Type) (l1: list X) (l2: list X) (f: X -> Y),\n                       map f (l1 ++ l2) = map f l1 ++ map f l2.\nProof.\n  intros.\n  induction l1.\n  reflexivity.\n  simpl. rewrite IHl1. reflexivity.\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros.\n  induction l.\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = x :: l\".\n    simpl.\n    rewrite <- IHl.\n    rewrite snoc_append.\n    rewrite snoc_append.\n    rewrite map_append.\n    reflexivity.\nQed.\n\nFixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X)\n                   : (list Y) :=\n  match l with\n    | [] => []\n    | h :: l' => f h ++ flat_map f l'\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\n\nFixpoint fold {X Y:Type} (f: X -> Y -> Y) (l:list X) (b:Y) : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\nExample fold_example1 : fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\nExample fold_example2 : fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\nExample fold_example3 : fold app [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n\nExample fold_type_diff_example :\n  fold (fun x y => (andb y (beq_nat 0 x))) [0;0;0;0;1] true = false.\nProof. reflexivity. Qed.\nExample fold_type_diff_example' :\n  fold (fun x y => (andb y (beq_nat 0 x))) [0;0;0;0;0] true = true.\nProof. reflexivity. Qed.\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.\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\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\n\nTheorem override_example : forall (b:bool),\n  (override (constfun b) 3 true) 2 = b.\nProof.\n  intro.\n  destruct b.\n  reflexivity.\n  reflexivity.\nQed.\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\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\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  simpl.\n  rewrite <- IHl.\n  unfold fold_length.\n  reflexivity.\nQed.\n\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\nTheorem foldmap_correct : forall X Y (f : X -> Y) (l : list X),\n                            fold_map f l = map f l.\nProof.\n  intros.\n  induction l as [| x l'].\n  reflexivity.\n  simpl.\n  rewrite <- IHl'.\n  unfold fold_map.\n  reflexivity.\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/software-foundations/A005poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.6586643096568555}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import ssrbool eqtype ssrnat seq fintype ssrfun tuple finset.\nFrom Bits\n     Require Import bits.\nRequire Import spec.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nDefinition remove n (bs : BITS n) k : BITS n := andB bs (invB (shlBn #1 k)).\n\nLemma remove_repr n (bs : BITS n) (k: 'I_n) E : repr bs E ->\n    repr (remove bs k) (E :\\ k).\nProof.\nmove->; apply/setP=> i.\nby rewrite !inE getBit_set_false // fun_if !val_eqE; case: eqP.\nQed.\n", "meta": {"author": "artart78", "repo": "coq-bitset", "sha": "806821b4ccf259885dfb5645e0e6957fb1149c52", "save_path": "github-repos/coq/artart78-coq-bitset", "path": "github-repos/coq/artart78-coq-bitset/coq-bitset-806821b4ccf259885dfb5645e0e6957fb1149c52/src/ops/remove.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6586301166897864}}
{"text": "\n\n\n\n\n(* ---------------------------------------------------------------------------------------\n\n   This file contains results of bounds on Matchings. \n -------------------------------------------------------------------------------------- *)\n\n\n\n\n\nRequire Import ssreflect ssrbool. \nRequire Export Lists.List.\n\nRequire Export GenReflect SetSpecs.\n\nRequire Export DecSort MinMax.\nRequire Export BidAsk.\nRequire Export DecList.\nRequire Export Matching.\nRequire Export AuctionInvar.\nRequire Export Fair.\nRequire Export MM.\nRequire Export UM.\n\nSection bounds.\n\n\nFixpoint bids_above (p:nat)(M:list fill_type) :=\nmatch M with \n|nil => nil\n|m::M' => match (Nat.leb p (bid_of m)) with\n  |true => (bid_of m)::(bids_above p M')\n  |false => (bids_above p M')\n  end\nend.\n\nFixpoint asks_below (p:nat)(M:list fill_type) :=\nmatch M with \n|nil => nil\n|m::M' => match (Nat.leb (ask_of m) p) with\n  |true => (ask_of m)::(asks_below p M')\n  |false => (asks_below p M')\n  end\nend.\n\nLemma matchable_buy_above_sell_below (b:Bid) (a: Ask) (B: list Bid) (A: list Ask) (p:nat): In b (buyers_above p B) -> In a (sellers_below p A)\n-> a<=b.\nProof. intros. apply  buyers_above_elim in H. apply sellers_below_elim in H0. omega. Qed. \n\nLemma buy_below_above_total (M: list fill_type) (B:list Bid) (A:list Ask) (p:nat):\n(matching_in B A M) -> (|(buyers_above p (bids_of M))|) + (|(buyers_below p (bids_of M))|) >= |M|.\nProof. { intros H. destruct H as [H H0]. destruct H0 as [H0 H1]. \n          destruct H as [H H2]. destruct H2 as [H2 H3].\n          induction M. { simpl. auto. }\n           { simpl.  \n            destruct (p <=? bid_of a) eqn: Hpb.\n            { destruct (bid_of a <=? p) eqn: Hpa.\n            { simpl. cut ((| buyers_above p (bids_of M) |) + (| buyers_below p (bids_of M) |) >= |M|). \n            omega. apply IHM. all:eauto. }\n            { simpl. cut ((| buyers_above p (bids_of M) |) + (| buyers_below p (bids_of M) |) >= |M|). \n            omega. apply IHM. all:eauto. } }\n            { destruct (bid_of a <=? p) eqn: Hpa.\n            { simpl. cut ((| buyers_above p (bids_of M) |) + (| buyers_below p (bids_of M) |) >= |M|). omega. apply IHM. all:eauto. }\n            { move /leP in Hpb. move /leP in Hpa. omega. } }}} Qed.\n            \nLemma sell_below_above_total (M: list fill_type) (B:list Bid) (A:list Ask) (p:nat):\n(matching_in B A M) -> (|(sellers_above p (asks_of M))|) + (|(sellers_below p (asks_of M))|) >= |M|.\nProof. { intros H. destruct H as [H H0]. destruct H0 as [H0 H1]. \n          destruct H as [H H2]. destruct H2 as [H2 H3].\n          induction M. { simpl. auto. }\n           { simpl.  \n            destruct (p <=? ask_of a) eqn: Hpb.\n            { destruct (ask_of a <=? p) eqn: Hpa.\n            { simpl. cut ((|(sellers_above p (asks_of M))|) + (|(sellers_below p (asks_of M))|) >= |M|). \n            omega. apply IHM. all:eauto. }\n            { simpl. cut ((|(sellers_above p (asks_of M))|) + (|(sellers_below p (asks_of M))|) >= |M|). \n            omega. apply IHM. all:eauto. } }\n            { destruct (ask_of a <=? p) eqn: Hpa.\n            { simpl. cut ((|(sellers_above p (asks_of M))|) + (|(sellers_below p (asks_of M))|) >= |M|). omega. apply IHM. all:eauto. }\n            { move /leP in Hpb. move /leP in Hpa. omega. } }}} Qed.\n\n\nLemma maching_buyer_right_plus_seller_left \n(M: list fill_type) (B:list Bid) (A:list Ask) (p:nat):\n(matching_in B A M) -> (|(buyers_above p (bids_of M))|) + (|(sellers_below p (asks_of M))|) >= |M|.\nProof.  intros H. apply sellers_below_ge_buyers with (p:=p) in H  as H1.\n                  eapply buyers_above_ge_sellers with (p:=p) in H as H2.\n                  eapply buy_below_above_total with (p:=p) in H as H3.\n                  eapply sell_below_above_total with (p:=p) in H as H4.\n                  omega. Qed.\n\nLemma buyers_above_delete_S (A : list Bid) (b:Bid) (p:nat):\nIn b A -> p<= b-> (| buyers_above p A |)=S((| buyers_above p (delete b A) |)).\nProof. { intros. induction A. destruct H. simpl. destruct (p <=? a) eqn: Hpa.\n{ destruct (b_eqb b a) eqn:Hba. simpl. auto. simpl. destruct (p <=? a).\nsimpl. move /eqP in Hba. simpl in H. destruct H. subst a. destruct Hba.\nauto. apply IHA in H. omega. inversion Hpa. }\n{ destruct (b_eqb b a) eqn: Hba. move /eqP in Hba. subst. move /leP in H0.\n  assert (p <=? a = true). eauto. rewrite H1 in Hpa. inversion Hpa.\n  simpl. destruct (p <=? a) eqn: Hpa2. inversion Hpa. apply IHA. \n  move /eqP in Hba. simpl in H. destruct H. subst a. destruct Hba. auto. exact. }} Qed.\n\nLemma buyers_above_delete (A : list Bid) (b:Bid) (p:nat):\nIn b A -> (p <=? b) = false -> (| buyers_above p A |)=(| buyers_above p (delete b A) |).\nProof. { intros. induction A. destruct H. simpl. destruct (p <=? a) eqn: Hpa.\n{ destruct (b_eqb b a) eqn:Hba. simpl. move /eqP in Hba. subst a.\nrewrite H0 in Hpa. inversion Hpa. simpl. destruct (p <=? a).\nsimpl. move /eqP in Hba. simpl in H. destruct H. subst a. destruct Hba.\nauto. apply IHA in H. omega. inversion Hpa. }\n{ destruct (b_eqb b a) eqn: Hba. auto. simpl.\n  destruct (p <=? a) eqn: Hpa2. inversion Hpa. apply IHA. \n  move /eqP in Hba. simpl in H. destruct H. subst a. destruct Hba. auto. exact. }} Qed.\n  \nLemma sellers_below_delete_S (A : list Ask) (b:Ask) (p:nat):\nIn b A -> b<= p-> (| sellers_below p A |)=S((| sellers_below p (delete b A) |)).\nProof. { intros. induction A. destruct H. simpl. destruct (a <=? p) eqn: Hpa.\n{ destruct (a_eqb b a) eqn:Hba. simpl. auto. simpl. destruct (a <=? p).\nsimpl. move /eqP in Hba. simpl in H. destruct H. subst a. destruct Hba.\nauto. apply IHA in H. omega. inversion Hpa. }\n{ destruct (a_eqb b a) eqn: Hba. move /eqP in Hba. subst. move /leP in H0.\n  assert (a <=? p = true). eauto. rewrite H1 in Hpa. inversion Hpa.\n  simpl. destruct (a <=? p) eqn: Hpa2. inversion Hpa. apply IHA. \n  move /eqP in Hba. simpl in H. destruct H. subst a. destruct Hba. auto. exact. }} Qed.\n\nLemma sellers_below_delete (A : list Ask) (b:Ask) (p:nat):\nIn b A -> (b <=? p) = false -> \n(| sellers_below p A |)=(| sellers_below p (delete b A) |).\nProof. { intros. induction A. destruct H. simpl. destruct (a <=? p) eqn: Hpa.\n{ destruct (a_eqb b a) eqn:Hba. simpl. move /eqP in Hba. subst a.\nrewrite H0 in Hpa. inversion Hpa. simpl. destruct (a <=? p).\nsimpl. move /eqP in Hba. simpl in H. destruct H. subst a. destruct Hba.\nauto. apply IHA in H. omega. inversion Hpa. }\n{ destruct (a_eqb b a) eqn: Hba. auto. simpl.\n  destruct (a <=? p) eqn: Hpa2. inversion Hpa. apply IHA. \n  move /eqP in Hba. simpl in H. destruct H. subst a. destruct Hba. auto. exact. }} Qed.\n  \n\nLemma buyers_above_bid_size (A B:list Bid) (p:nat):\nA [<=] B -> NoDup A -> (|buyers_above p B|) >= (|buyers_above p A|).\nProof. { revert A. induction B as [| b]. intros. assert (A=nil). eauto. subst A.\nsimpl. omega. intros. assert (In b A \\/ ~In b A). eauto. destruct H1.\n{\nsimpl. destruct (p <=? b) eqn: Hpa. simpl.\nassert ((| buyers_above p A |)=S((| buyers_above p (delete b A) |))).\n{ eapply buyers_above_delete_S. exact. move /leP in Hpa. exact. } rewrite H2. cut (| buyers_above p B | >= | buyers_above p (delete b A) |).\nomega. assert (delete b A [<=] delete b (b::B)). eapply delete_subset2. exact. exact.\nsimpl in H3. destruct (b_eqb b b) eqn:Hbb. apply IHB in H3. exact. eauto.\n move /eqP in Hbb. destruct Hbb. auto.\n assert ((| buyers_above p A |)=(| buyers_above p (delete b A) |)).\n{ apply buyers_above_delete. exact. exact.  } rewrite H2.  assert (delete b A [<=] delete b (b::B)). eapply delete_subset2. exact. exact.\nsimpl in H3. destruct (b_eqb b b) eqn:Hbb. apply IHB in H3. exact. eauto.\n move /eqP in Hbb. destruct Hbb. auto. }\n{ assert (A[<=]B). { assert (delete b A [<=] delete b (b::B)). eapply delete_subset2.\nexact. exact. simpl in H2.  destruct (b_eqb b b) eqn: Hbb. assert (A=delete b A).\neapply delete_intro1. exact. rewrite <- H3 in H2. exact. move /eqP in Hbb. destruct Hbb. auto. } simpl. destruct (p <=? b) eqn: Hpa. simpl.\ncut ((| buyers_above p B |) >= (| buyers_above p A |)). omega. apply IHB. eauto. eauto.\napply IHB. eauto. eauto. } } Qed.\n\nLemma sellers_below_ask_size \n(M: list fill_type) (A B:list Ask) (p:nat):\nA [<=] B -> NoDup A -> (|sellers_below p B|) >= (|sellers_below p A|).\nProof. { revert A. induction B as [| b]. intros. assert (A=nil). eauto. subst A.\nsimpl. omega. intros. assert (In b A \\/ ~In b A). eauto. destruct H1.\n{\nsimpl. destruct (b <=? p) eqn: Hpa. simpl.\nassert ((| sellers_below p A |)=S((| sellers_below p (delete b A) |))).\n{ eapply sellers_below_delete_S. exact. move /leP in Hpa. exact. } rewrite H2. cut (| sellers_below p B | >= | sellers_below p (delete b A) |).\nomega. assert (delete b A [<=] delete b (b::B)). eapply delete_subset2. exact. exact.\nsimpl in H3. destruct (a_eqb b b) eqn:Hbb. apply IHB in H3. exact. eauto.\n move /eqP in Hbb. destruct Hbb. auto.\n assert ((| sellers_below p A |)=(| sellers_below p (delete b A) |)).\n{ apply sellers_below_delete. exact. exact.  } rewrite H2.  assert (delete b A [<=] delete b (b::B)). eapply delete_subset2. exact. exact.\nsimpl in H3. destruct (a_eqb b b) eqn:Hbb. apply IHB in H3. exact. eauto.\n move /eqP in Hbb. destruct Hbb. auto. }\n{ assert (A[<=]B). { assert (delete b A [<=] delete b (b::B)). eapply delete_subset2.\nexact. exact. simpl in H2.  destruct (a_eqb b b) eqn: Hbb. assert (A=delete b A).\neapply delete_intro1. exact. rewrite <- H3 in H2. exact. move /eqP in Hbb. destruct Hbb. auto. } simpl. destruct (b <=? p) eqn: Hpa. simpl.\ncut ((| sellers_below p B |) >= (| sellers_below p A |)). omega. apply IHB. eauto. eauto.\napply IHB. eauto. eauto. } } Qed.\n\n\n\n\n\nLemma buyers_above_size \n(M: list fill_type) (B:list Bid) (A:list Ask) (p:nat):\n(matching_in B A M) -> (|buyers_above p B|) >= (|buyers_above p (bids_of M)|).\nProof. intros H. destruct H as [H H0]. destruct H0 as [H0 H1]. \n          destruct H as [H H2]. destruct H2 as [H2 H3].\n          apply buyers_above_bid_size. auto. auto.  Qed.\n          \n\nLemma sellers_below_size \n(M: list fill_type) (B:list Bid) (A:list Ask) (p:nat):\n(matching_in B A M) -> (|sellers_below p A|) >= (|sellers_below p (asks_of M)|).\nProof. intros H. destruct H as [H H0]. destruct H0 as [H0 H1]. \n          destruct H as [H H2]. destruct H2 as [H2 H3].\n          apply sellers_below_ask_size. auto. auto. auto. Qed.\n\nTheorem bound_on_M\n(M: list fill_type) (B:list Bid) (A:list Ask) (p:nat):\n(matching_in B A M) -> \n(|(buyers_above p B)|) + (|(sellers_below p A)|) >= |M|.\nProof. { intros H. apply sellers_below_ge_buyers with (p:=p) in H  as H1b.\n                  eapply buyers_above_ge_sellers with (p:=p) in H as H2a.\n                  eapply buy_below_above_total with (p:=p) in H as H3a.\n                  eapply sell_below_above_total with (p:=p) in H as H3b.\n                  eapply buyers_above_size with (p:=p) in H as H4a.\n                  eapply sellers_below_size with (p:=p) in H as H4b.\n                  omega. } Qed.\n                  \n\n\nLemma buyers_above_nodup (B:list Bid) (Ndb: NoDup B) (p:nat):\nNoDup (buyers_above p B).\nProof. induction B. simpl. constructor. simpl. \ndestruct (p <=? a) eqn: Hpa. assert (H0:~In a B).\neauto. assert (H1:~In a (buyers_above p B)). eauto. \nassert (H2: NoDup B). eauto. eapply IHB in H2. eauto.\nassert (H2: NoDup B). eauto. eapply IHB in H2. eauto. Qed.\n\n\n\nLemma sellers_below_nodup (A:list Ask) (Nda: NoDup A) (p:nat):\nNoDup (sellers_below p A).\nProof. induction A. simpl. constructor. simpl. \ndestruct (a <=? p) eqn: Hap. assert (H0:~In a A).\neauto. assert (H1:~In a (sellers_below p A)). eauto. \nassert (H2: NoDup A). eauto. eapply IHA in H2. eauto.\nassert (H2: NoDup A). eauto. eapply IHA in H2. eauto. Qed.\n\n\nLemma uniform_halfBA (M: list fill_type) (B:list Bid) (A:list Ask)(no_dup_B: NoDup B)(no_dup_A: NoDup A)(n:nat) :\nSorted by_dbp B ->  Sorted by_sp A -> matching_in B A M -> |M|>=2*n ->\n(|pair_uniform B A|)>=n.\nProof. revert A B no_dup_B no_dup_A M. induction n. intros. simpl. omega.\nintros. case A as [| a1 A']. { case B as [| b1 B']. \n(* base case: when A is nil *)\n         \n          { apply matching_on_nilA in H1 as HA. rewrite HA in H2. subst M. simpl in H2.\n          omega. }\n          { apply matching_on_nilA in H1 as HA. rewrite HA in H2. subst M. simpl in H2.\n          omega. } } \n          { case B as [| b1 B']. \n          { apply matching_on_nilB in H1 as HB. rewrite HB in H2. subst M. simpl in H2.\n          omega. }          \n         { (*----- induction step : b::B'   and a:: A' ---------*)\n           assert (Case: b1 < a1 \\/ b1 >= a1 ). omega.\n           destruct Case as [C1 | C2].\n                      { (*------C1:  when b and a are not matchable then produce_MM (b::B') A' *)\n             simpl. replace (a1 <=? b1) with false.\n             2:{ symmetry. apply /leP. omega. } \n             assert (HM:M=nil). eapply unmatchableAB_nil.\n             eauto. eauto. eauto. exact. subst M. simpl in H2. omega. }\n             { (*-- C2: when b and a are matchable then Output is (b,a):: produce_MM B' A'----*)\n             assert (HBdel:B'=(delete b1 B')). { \n             eapply delete_intro1. assert (B'=(delete b1 (b1::B'))).\n             simpl. destruct (b_eqb b1 b1) eqn:heq. auto. move /eqP in heq.\n             destruct heq. auto. rewrite H3. eapply delete_intro2. exact. } \n             assert (HAdel:A'=(delete a1 A')). { \n             eapply delete_intro1. assert (A'=(delete a1 (a1::A'))).\n             simpl. destruct (a_eqb a1 a1) eqn:heq. auto. move /eqP in heq.\n             destruct heq. auto. rewrite H3. eapply delete_intro2. exact. }\n               simpl.\n              replace (a1 <=? b1) with true.\n             \n             2:{ symmetry. apply /leP. auto. } simpl.\n             cut ( (| pair_uniform B' A' |) >= n). omega.\n             assert (Hb: In b1 (bids_of M) \\/ ~ In b1 (bids_of M)). eauto.\n             assert (Ha: In a1 (asks_of M) \\/ ~ In a1 (asks_of M)). eauto.\n             destruct Hb as [Hb1 | Hb2]; destruct Ha as [Ha1 | Ha2].\n\n              { (* Case_ab1: In b (bids_of M) and In a (asks_of M)------*)\n               assert (h3: exists m1, In m1 M /\\ a1 = ask_of m1). eauto.\n               assert (h4: exists m2, In m2 M /\\ b1 = bid_of m2). eauto.\n               destruct h3 as [m1 h3]. destruct h3 as [h3a h3].\n               destruct h4 as [m2 h4]. destruct h4 as [h4a h4].\n               set (M'' := delete m1 (delete m2 M)).\n               assert (HM_size: |M''|>=2*n).\n{ assert (Hdeletem2: |delete m2 M|>=|M| - 1). eauto.\n  assert (Hdeletem1: |delete m1 (delete m2 M)|>=|(delete m2 M)| - 1). eauto. subst M''.\n  omega. }\nassert (HM'B'A': matching_in (delete b1 B') (delete a1 A') M'').\n{ destruct H1 as [ Hmatch1 Hmatch2]. destruct Hmatch1 as [Hmatch1 Hmatch3].\n  destruct Hmatch3 as [Hmatch3 Hmatch4]. destruct Hmatch2 as [Hmatch2 Hmatch5].\n  (*************************************************)\n     assert (Hdbid: (bids_of (delete m1 (delete m2 M))) = \n     (delete (bid_of m1) (delete (bid_of m2) (bids_of M)))).  \n     apply bids_of_delete_delete. exact. exact. exact.\n     assert (Hdask: (asks_of (delete m1 (delete m2 M))) = \n     (delete (ask_of m1) (delete (ask_of m2) (asks_of M)))).  \n     apply asks_of_delete_delete. exact. exact. exact.\n   (**********************************************)\n   unfold matching_in. split. \n   { unfold matching. split. \n   {\n   { eauto. } } split. \n   { subst M''. rewrite Hdbid. eauto. }\n   { subst M''. rewrite Hdask. eauto. }\n   } split. \n{ subst M''. rewrite Hdbid. assert ((delete (bid_of m1) (bids_of M))\n[<=] b1::B'). eauto. assert (delete (bid_of m2) (delete (bid_of m1) (bids_of M)) [<=] delete (bid_of m2) (b1 :: B')).  eapply delete_subset2. eapply delete_subset.  exact. eauto. rewrite<- h4 in H3. assert (delete (bid_of m1) (delete (bid_of m2) (bids_of M)) = delete (bid_of m2) (delete (bid_of m1) (bids_of M))). eapply delete_exchange.\nrewrite H4.  rewrite <- h4. simpl in H3.\n    destruct (b_eqb b1 b1) eqn: Hbb. assert ((delete b1 B')=B'). eauto. rewrite H5.\n    exact. move /eqP in Hbb. destruct Hbb. auto. }    \n     { subst M''. rewrite Hdask. assert ((delete (ask_of m2) (asks_of M))\n[<=] a1::A'). eauto. \n    assert (delete (ask_of m1) (delete (ask_of m2) (asks_of M)) [<=] delete (ask_of m1) (a1 :: A')). eapply delete_subset2. exact. eauto. rewrite<- h3 in H3. simpl in H3.\n    destruct (a_eqb a1 a1) eqn: Haa. assert ((delete a1 A')=A'). eauto. rewrite H4.\n    rewrite<- h3. exact. move /eqP in Haa. destruct Haa. auto. } }\napply IHn in HM'B'A'. rewrite HBdel. rewrite HAdel. exact. {\nassert ((delete b1 B')=B'). eauto. rewrite H3. eauto. }\n{ assert ((delete a1 A')=A'). eauto. rewrite H3. eauto.  } rewrite <- HBdel. eauto.\nrewrite <- HAdel. eauto. exact. }\n\n{(* Case_ab2: In b (bids_of M) and ~ In a (asks_of M)----*)\n               assert (h3: exists m, In m M /\\ b1 = bid_of m). eauto.\n               destruct h3 as [m h3]. destruct h3 as [h3a h3].\n               set (M' := delete m M).\n               assert (h4: matching_in B' A' M').\n                 { unfold matching_in. split.\n                 { (*------ matching M' -----------*)\n                   unfold M'. eauto. } split.\n                 { (*------bids_of M' [<=] B'------*)\n                   intros x h4.\n                   assert (h5: In x (bids_of M)).\n                   { unfold M' in h4. eauto. }\n                   assert (h5a: In x (b1::B')).\n                   { destruct H1. destruct H3. apply H3. auto. }\n                   assert (h6: x <> b1).\n                   { intro h6. unfold M' in h4.\n                     subst x;subst b1.\n                     absurd (In (bid_of m) (bids_of (delete m M))).\n                     { apply matching_elim10. eapply matching_in_elim0.\n                      exact H1. exact h3a. } auto. }\n                   eapply in_inv2. all: eauto. }\n                 { (*------ asks_of M' [<=] A'-------*)\n                   intros x h4.\n                   assert (h5: In x (asks_of M)).\n                   { unfold M' in h4. eauto. }\n                   assert (h6: x <> a1).\n                   { intro h6. subst x. contradiction. }\n                   assert (h7: In x (a1::A')).\n                   { apply H1. auto. }\n                   eapply in_inv2. all: eauto.  } }\n                   apply IHn in h4. exact. eauto. eauto. eauto. eauto. \n                   subst M'. assert ((| delete m M |)=|M| - 1).\n                   eapply delete_size1. exact. rewrite H3. omega. }\n                   \n                   \n{(* Case: ~In b (bids_of M) and In a (asks_of M)----*)\n               assert (h3: exists m, In m M /\\ a1 = ask_of m). eauto.\n               destruct h3 as [m h3]. destruct h3 as [h3a h3].\n               set (M' := delete m M).\n               assert (h4: matching_in B' A' M').\n                 { unfold matching_in. split.\n                 { (*------ matching M' -----------*)\n                   unfold M'. eauto. } split.\n                 { (*------bids_of M' [<=] B'------*)\n                   intros x h4.\n                   assert (h5: In x (bids_of M)).\n                   { unfold M' in h4. eauto. }\n                   assert (h5a: In x (b1::B')).\n                   { apply H1. auto. }\n                   assert (h6: x <> b1).\n                   { intro h6. unfold M' in h4.\n                     subst x;subst a1.\n                     absurd (In (bid_of m) (bids_of (delete m M))).\n                     { apply matching_elim10. eapply matching_in_elim0.\n                      exact H1. exact h3a. } auto. }\n                   eapply in_inv2. all: eauto. }\n                 { (*------ asks_of M' [<=] A'-------*)\n                   intros x h4.\n                   assert (h5: In x (asks_of M)).\n                   { unfold M' in h4. eauto. }\n                   assert (h6: x <> a1).\n                   { intro h6. subst x. \n                   subst M'. assert (~In (ask_of m) (asks_of (delete m M))).\n                   eapply matching_elim11. eapply matching_in_elim0.\n                   exact H1. exact h3a. subst a1. contradiction. }\n                   assert (h7: In x (a1::A')).\n                   { apply H1. auto. }\n                   eapply in_inv2. all: eauto.  } }\n                   apply IHn in h4. exact. eauto. eauto. eauto. eauto.\n                   subst M'. assert ((| delete m M |)=|M| - 1).\n                   eapply delete_size1. exact. rewrite H3. omega. }\n                   assert (h3: matching_in B' A' M). eauto using matching_in_elim8.\n                   apply IHn in h3. exact. eauto. eauto. eauto. eauto. omega. } } } Qed. \n\n\n\n\nEnd bounds.\n\n\n(*\n\nDefinition B2:= ({|b_id:= 1 ; bp:= 125 |}) ::({|b_id:= 2 ; bp:= 120 |}) ::({|b_id:= 3 ; bp:= 112 |}) ::({|b_id:= 4 ; bp:= 91 |}) ::({|b_id:= 5 ; bp:= 82 |}) ::({|b_id:= 6 ; bp:= 82 |}) ::({|b_id:= 7 ; bp:= 69 |}) ::({|b_id:= 8 ; bp:= 37 |}) :: nil.\n\nDefinition A2:= ({|s_id:= 1 ; sp:= 121 |}) ::({|s_id:= 3 ; sp:= 113 |}) ::({|s_id:= 5 ; sp:= 98 |}) ::({|s_id:= 9 ; sp:= 94 |}) ::({|s_id:= 90 ; sp:= 90 |}) ::({|s_id:= 78 ; sp:= 85 |}) ::({|s_id:= 67 ; sp:= 79 |}) ::({|s_id:= 45 ; sp:= 53 |}) ::nil.\n\n *)\n\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/Bounds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6586028320839534}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nInductive tuple A i := { l : list A; p : (length l == i) = true }.\n", "meta": {"author": "eponier", "repo": "compare-eq", "sha": "cc2da184e747d0ad6ada8597e1ebf03377e413e2", "save_path": "github-repos/coq/eponier-compare-eq", "path": "github-repos/coq/eponier-compare-eq/compare-eq-cc2da184e747d0ad6ada8597e1ebf03377e413e2/features/tuple/type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6585633831358976}}
{"text": "(** * Types With Equalities *)\n\nClass Eq (A : Type) := EQ {\n  eq_op : A -> A -> Prop;\n}.\n\nInfix \"≡\" := eq_op (at level 80).\n\nDefinition bijection (A B : Type) `{Eq A} `{Eq B} (f : A -> B) (g : B -> A) :=\n  (forall a, g (f a) ≡ a) /\\ (forall b, f (g b) ≡ b).\n\nDefinition isomorph (A B : Type) `{Eq A} `{Eq B} :=\n  exists f g, bijection A B f g.\n\nInfix \"≃\" := isomorph (at level 80).", "meta": {"author": "acorrenson", "repo": "WiSE", "sha": "7faabb31b45a9a98ac618ab3728ff7b178bda596", "save_path": "github-repos/coq/acorrenson-WiSE", "path": "github-repos/coq/acorrenson-WiSE/WiSE-7faabb31b45a9a98ac618ab3728ff7b178bda596/src/equalities.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6585633793931034}}
{"text": "Require Import Arith.\nRequire Import Cpdt.CpdtTactics.\nPrint pred.\n\nExtraction pred.\n\nSet Implicit Arguments.\n\nLemma zgtz : 0>0-> False.\n  crush. Qed.\n\nDefinition pred_strong1 (n:nat):n>0-> nat :=\nmatch n with\n| O => fun pf:0>0 => match zgtz pf with end\n| S n' => fun _ => n'\nend.\n\nPrint pred_strong1.\n\nTheorem two_gt0 : 2>0.\n  crush. Qed.\n\nEval compute in pred_strong1 two_gt0.\n\nDefinition pred_strong1' (n:nat):n>0 -> nat:=\n  match n return n>0-> nat with\n  | O => fun pf:0>0 => match zgtz pf with end\n  | S n' => fun _ => n'\n  end.\n\nExtraction pred_strong1.\nPrint sig.\n\n", "meta": {"author": "shij-hsu", "repo": "coq", "sha": "335711e36628d93d5723d8617b250e90be578d83", "save_path": "github-repos/coq/shij-hsu-coq", "path": "github-repos/coq/shij-hsu-coq/coq-335711e36628d93d5723d8617b250e90be578d83/cpdt/SubsetTypesAndVars.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6585576021732227}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\n(*********************************************************************)\n(* The basic theory of paths over an eqType; this is essentially a   *)\n(* complement to seq.v.                                              *)\n(* Paths are non-empty sequences that obey a progression relation.   *)\n(* They are passed around in three parts : the head and tail of the  *)\n(* sequence, and a (boolean) predicate asserting the progression.    *)\n(* This is rarely embarrassing, as the first two are usually         *)\n(* implicit parameters inferred from the predicate, and it saves the *)\n(* hassle of constantly constructing and destructing a dependent     *)\n(* record.                                                           *)\n(*    We define similarly cycles, but in this case we allow the      *)\n(* empty sequence (which is a non-rooted empty cycle; by contrast,   *)\n(* the empty path from x is the one-item sequence containing only x) *)\n(* We allow duplicates; uniqueness, if desired (as is the            *)\n(* case for several geometric constructions), must be asserted       *)\n(* separately. We do provide shorthand, but for cycles only, because *)\n(* the equational properties of \"path\" and \"uniq\" are unfortunately  *)\n(* incompatible (esp. wrt \"cat\").                                    *)\n(*    We define notations for the common cases of function paths,    *)\n(* where the progress relation is actually a function. We also       *)\n(* define additional traversal/surgery operations, many of which     *)\n(* could have been in seq.v, but are here because they only really   *)\n(* are useful for sequences considered as paths :                    *)\n(*  - directed surgery : splitPl, splitP, splitPr are dependent      *)\n(*    predicates whose elimination splits a path x0:p at one of its  *)\n(*    elements (say x). The three variants differ as follows:        *)\n(*      - splitPl applies when x is in x0::p, generates two paths p1 *)\n(*        and p2, along with the equation x = (last x0 p), and       *)\n(*        replaces p with (p1 ++ p2) in the goal (the patterned      *)\n(*        Elim can be used to select occurrences and generate an     *)\n(*        equation p = (p1 ++ p2).                                   *)\n(*      - splitP applies when x is in p, and replaces p with         *)\n(*        (rcons p1 x ++ p2), where x appears explicitly at the end  *)\n(*        of the left part.                                          *)\n(*      - splitPr similarly replaces p with (p1 ++ x :: p2), where x *)\n(*        appears explicitly at the right of the split, when x       *)\n(*        actually occurs in p.                                      *)\n(*    The parts p1 and p2 are computed using index/take/drop. The    *)\n(*    splitP variant (but not the others) attempts to replace the    *)\n(*    explicit expressions for p1 and p2 by p1 and p2, respectively. *)\n(*    This is moderately useful, but allows for defining other       *)\n(*    splitting lemmas with conclusions of the form (split x p p1 p2)*)\n(*    with other expressions for p1 and p2 that might be known to    *)\n(*    occur.                                                         *)\n(*  - function trajectories: traject, and  looping predicates.       *)\n(*  - cycle surgery : arc extracts the sub-arc between two points    *)\n(*    (including the first, excluding the second). (arc p x y) is    *)\n(*    thus only meaningful if x and y are different points in p.     *)\n(*  - cycle traversal : next, prev                                   *)\n(*  - path order: mem2 checks whether two points belong to a path    *)\n(*    and appear in order (i.e., (mem2 p x y) checks that y appears  *)\n(*    after an occurrence of x in p). This predicate is a crucial    *)\n(*    part of the definition of the abstract Jordan property.        *)\n(*  - sorting: sorted checks whether a sequence is sorted wrt a      *)\n(*    transitive relation; sorted e (x :: p) expands to path e x p,  *)\n(*    and sort sorts a sequence recursively, using a \"merge\" function*)\n(*    to interleave sorted sublists.                                 *)\n(*  - loop removal : shorten returns a shorter, duplicate-free path  *)\n(*    with the same endpoints as its argument. The related shortenP  *)\n(*    dependent predicate simultaneously substitutes a new path p',  *)\n(*    for (shorten e x p), (last x p') for (last x p), and generates *)\n(*    predicates asserting that p' is a duplicate-free subpath of p. *)\n(* Although these functions operate on the underlying sequences, we  *)\n(* provide a series of lemmas that define their interaction with the *)\n(* path and cycle predicates, e.g., the path_cat equation can be     *)\n(* used to split the path predicate after splitting the underlying   *)\n(* sequence.                                                         *)\n(*********************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nSection Paths.\n\nVariables (n0 : nat) (T : Type).\n\nSection Path.\n\nVariables (x0_cycle : T) (e : rel T).\n\nFixpoint path x (p : seq T) {struct p} :=\n  if p is y :: p' then e x y && path y p' else true.\n\nLemma path_cat : forall x p1 p2,\n  path x (p1 ++ p2) = path x p1 && path (last x p1) p2.\nProof.\nby move=> x p1 p2; elim: p1 x => [|y p1 Hrec] x //=; rewrite Hrec -!andbA.\nQed.\n\nLemma pathP : forall x p x0,\n  reflect (forall i, i < size p -> e (nth x0 (x :: p) i) (nth x0 p i))\n          (path x p).\nProof.\nmove=> x p x0; elim: p x => [|y p Hrec] x /=; first by left.\napply: (iffP andP) => [[Hxy Hp]|Hp].\n  move=> [|i] Hi //; exact: Hrec _ Hp i Hi.\nsplit; first exact: Hp 0 (leq0n (size p)).\napply/(Hrec y) => i; exact: Hp i.+1.\nQed.\n\nDefinition cycle p := if p is x :: p' then path x (rcons p' x) else true.\n\nLemma cycle_path : forall p, cycle p = path (last x0_cycle p) p.\nProof. by move=> [|x p] //=; rewrite -cats1 path_cat /= andbT andbC. Qed.\n\nLemma cycle_rot : forall p, cycle (rot n0 p) = cycle p.\nProof.\ncase: (n0) => [|n] [|y0 p] //=; first by rewrite /rot /= cats0.\nrewrite /rot /= -{3}(cat_take_drop n p) -cats1 -catA path_cat.\ncase: (drop n p) => [|z0 q]; rewrite /= -cats1 !path_cat /= !andbT andbC //.\nby rewrite last_cat; repeat bool_congr.\nQed.\n\nLemma cycle_rotr : forall p, cycle (rotr n0 p) = cycle p.\nProof. by move=> p; rewrite -cycle_rot rotrK. Qed.\n\nEnd Path.\n\nLemma eq_path : forall e e', e =2 e' -> path e =2 path e'.\nProof.\nby move=> e e' Ee x p; elim: p x => [|y p Hrec] x //=; rewrite Ee Hrec.\nQed.\n\nLemma sub_path : forall e e', subrel e e' ->\n  forall x p, path e x p -> path e' x p.\nProof.\nmove=> e e' He x p; elim: p x => [|y p Hrec] x //=.\nby move/andP=> [Hx Hp]; rewrite (He _ _ Hx) (Hrec _ Hp).\nQed.\n\nEnd Paths.\n\nImplicit Arguments pathP [T e x p].\nPrenex Implicits pathP.\n\nSection EqPath.\n\nVariables (n0 : nat) (T : eqType) (x0_cycle : T) (e : rel T).\n\nCoInductive split x : seq T -> seq T -> seq T -> Type :=\n  Split p1 p2 : split x (rcons p1 x ++ p2) p1 p2.\n\nLemma splitP : forall (p : seq T) x, x \\in p ->\n   let i := index x p in split x p (take i p) (drop i.+1 p).\nProof.\nmove=> p x Hx i; have := esym (cat_take_drop i p).\nhave Hi := Hx; rewrite -index_mem -/i in Hi; rewrite (drop_nth x Hi).\nby rewrite -cat_rcons {2}/i (nth_index x Hx) => Dp; rewrite {1}Dp.\nQed.\n\nCoInductive splitl (x1 x : T) : seq T -> Type :=\n  Splitl p1 p2 of last x1 p1 = x : splitl x1 x (p1 ++ p2).\n\nLemma splitPl : forall x1 p x, x \\in x1 :: p -> splitl x1 x p.\nProof.\nmove=> x1 p x; rewrite in_cons.\ncase: eqP => [->| _]; first by rewrite -(cat0s p).\ncase/splitP; split; exact: last_rcons.\nQed.\n\nCoInductive splitr x : seq T -> Type :=\n  Splitr p1 p2 : splitr x (p1 ++ x :: p2).\n\nLemma splitPr : forall (p : seq T) x, x \\in p -> splitr x p.\nProof. by move=> p x; case/splitP=> p1 p2; rewrite cat_rcons. Qed.\n\nFixpoint next_at (x y0 y : T) (p : seq T) {struct p} :=\n  match p with\n  | [::] => if x == y then y0 else x\n  | y' :: p' => if x == y then y' else next_at x y0 y' p'\n  end.\n\nDefinition next p x := if p is y :: p' then next_at x y y p' else x.\n\nFixpoint prev_at (x y0 y : T) (p : seq T) {struct p} :=\n  match p with\n  | [::]     => if x == y0 then y else x\n  | y' :: p' => if x == y' then y else prev_at x y0 y' p'\n  end.\n\nDefinition prev p x := if p is y :: p' then prev_at x y y p' else x.\n\nLemma next_nth : forall p x,\n  next p x = if x \\in p then\n               if p is y :: p' then nth y p' (index x p) else x\n             else x.\nProof.\nmove=> [|y0 p] x //=; elim: p {2 3 5}y0 => [|y' p Hrec] y /=;\n  by rewrite (eq_sym y) in_cons; case (x == y); try exact: Hrec.\nQed.\n\nLemma prev_nth : forall p x,\n  prev p x = if x \\in p then\n               if p is y :: p' then nth y p (index x p') else x\n             else x.\nProof.\nmove=> [|y0 p] x //=; rewrite in_cons orbC.\nelim: p {2 5}y0 => [|y' p Hrec] y; rewrite /= ?in_cons // (eq_sym y').\nby case (x == y') => /=; auto.\nQed.\n\nLemma mem_next : forall (p : seq T) x, (next p x \\in p) = (x \\in p).\nProof.\nmove=> p x; rewrite next_nth; case Hpx: (x \\in p) => //.\ncase: p (index x p) Hpx => [|y0 p'] //= i _; rewrite in_cons.\ncase: (ltnP i (size p')) => Hi; first by rewrite /= (mem_nth y0 Hi) orbT.\nby rewrite (nth_default y0 Hi) eqxx.\nQed.\n\nLemma mem_prev : forall (p : seq T) x, (prev p x \\in p) = (x \\in p).\nProof.\nmove=> p x; rewrite prev_nth; case Hpx: (x \\in p) => //.\ncase: p Hpx => [|y0 p'] Hpx //.\nby apply mem_nth; rewrite /= ltnS index_size.\nQed.\n\n(* ucycleb is the boolean predicate, but ucycle is defined as a Prop *)\n(* so that it can be used as a coercion target. *)\nDefinition ucycleb p := cycle e p && uniq p.\nDefinition ucycle p : Prop := cycle e p && uniq p.\n\n(* Projections, used for creating local lemmas. *)\nLemma ucycle_cycle : forall p, ucycle p -> cycle e p.\nProof. by move=> p; case/andP. Qed.\n\nLemma ucycle_uniq : forall p, ucycle p -> uniq p.\nProof. by move=> p; case/andP. Qed.\n\nLemma next_cycle : forall p x, cycle e p -> x \\in p -> e x (next p x).\nProof.\nmove=> [|y0 p] //= x.\nelim: p {1 3 5}y0 => [|y' p Hrec] y /=; rewrite in_cons.\n  by rewrite andbT orbF => Hy Dy; rewrite Dy (eqP Dy).\nmove/andP=> [Hy Hp]; case: (x =P y) => [->|_] //; exact: Hrec.\nQed.\n\nLemma prev_cycle : forall p x, cycle e p -> x \\in p -> e (prev p x) x.\nProof.\nmove=> [|y0 p] //= x; rewrite in_cons orbC.\nelim: p {1 5}y0 => [|y' p Hrec] y /=; rewrite ?in_cons.\n  by rewrite andbT=> Hy Dy; rewrite Dy (eqP Dy).\nmove/andP=> [Hy Hp]; case: (x =P y') => [->|_] //; exact: Hrec.\nQed.\n\nLemma ucycle_rot : forall p, ucycle (rot n0 p) = ucycle p.\nProof. by move=> *; rewrite /ucycle rot_uniq cycle_rot. Qed.\n\nLemma ucycle_rotr : forall p, ucycle (rotr n0 p) = ucycle p.\nProof. by move=> *; rewrite /ucycle rotr_uniq cycle_rotr. Qed.\n\n(* The \"appears no later\" partial preorder defined by a path. *)\n\nDefinition mem2 (p : seq T) x y := y \\in drop (index x p) p.\n\nLemma mem2l : forall p x y, mem2 p x y -> x \\in p.\nProof.\nmove=> p x y; rewrite /mem2 -!index_mem size_drop; move=> Hxy.\nby rewrite -subn_gt0 -(ltn_predK Hxy) ltnS leq0n.\nQed.\n\nLemma mem2lf : forall (p : seq T) x,\n  (x \\in p) = false -> forall y, mem2 p x y = false.\nProof. move=> p x Hx y; apply/idP => Hp; case/idP: Hx; apply: mem2l Hp. Qed.\n\nLemma mem2r : forall p x y, mem2 p x y -> y \\in p.\nProof.\nrewrite /mem2; move=> p x y Hxy.\nby rewrite -(cat_take_drop (index x p) p) mem_cat Hxy orbT.\nQed.\n\nLemma mem2rf : forall (p : seq T) y,\n  (y \\in p) = false -> forall x, mem2 p x y = false.\nProof. move=> p y Hy x; apply/idP => [Hp]; case/idP: Hy; apply: mem2r Hp. Qed.\n\nLemma mem2_cat : forall p1 p2 x y,\n  mem2 (p1 ++ p2) x y = mem2 p1 x y || mem2 p2 x y || (x \\in p1) && (y \\in p2).\nProof.\nmove=> p1 p2 x y; rewrite {1}/mem2 index_cat drop_cat; case Hp1x: (x \\in p1).\n  rewrite index_mem Hp1x mem_cat /= -orbA.\n  by case Hp2: (y \\in p2); [ rewrite !orbT // | rewrite (mem2rf Hp2) ].\nby rewrite ltnNge leq_addr /= orbF addKn (mem2lf Hp1x).\nQed.\n\nLemma mem2_splice : forall p1 p3 x y p2,\n  mem2 (p1 ++ p3) x y -> mem2 (p1 ++ p2 ++ p3) x y.\nProof.\nmove=> p1 p3 x y p2 Hxy; move: Hxy; rewrite !mem2_cat mem_cat.\ncase: (mem2 p1 x y) (mem2 p3 x y) => [|] // [|] /=; first by rewrite orbT.\nby case: (x \\in p1) => [|] //= Hy; rewrite Hy !orbT.\nQed.\n\nLemma mem2_splice1 : forall p1 p3 x y z,\n  mem2 (p1 ++ p3) x y -> mem2 (p1 ++ z :: p3) x y.\nProof. move=> p1 p3 x y z; exact: (mem2_splice [::z]). Qed.\n\nLemma mem2_cons : forall x p y,\n  mem2 (x :: p) y =1 if x == y then predU1 x (mem p) : pred T else mem2 p y.\nProof. by move=> x p y z; rewrite {1}/mem2 /=; case (x == y). Qed.\n\nLemma mem2_last : forall y0 p x,\n  mem2 (y0 :: p) x (last y0 p) = (x \\in y0 :: p).\nProof.\nmove=> y0 p x; apply/idP/idP; first by apply mem2l.\nrewrite -index_mem /mem2; move: (index x _) => i Hi.\nby rewrite lastI drop_rcons ?size_belast // mem_rcons mem_head.\nQed.\n\nLemma mem2l_cat : forall (p1 : seq T) x, (x \\in p1) = false ->\n  forall p2, mem2 (p1 ++ p2) x =1 mem2 p2 x.\nProof. by move=> p1 x Hx p2 y; rewrite mem2_cat (Hx) (mem2lf Hx) /= orbF. Qed.\n\nLemma mem2r_cat : forall (p2 : seq T) y, (y \\in p2) = false ->\n   forall p1 x, mem2 (p1 ++ p2) x y = mem2 p1 x y.\nProof.\nby move=> p2 y Hy p1 x; rewrite mem2_cat (Hy) (mem2rf Hy) andbF !orbF.\nQed.\n\nLemma mem2lr_splice : forall (p2 : seq T) x y,\n    (x \\in p2) = false -> (y \\in p2) = false ->\n  forall p1 p3, mem2 (p1 ++ p2 ++ p3) x y = mem2 (p1 ++ p3) x y.\nProof.\nmove=> p2 x y Hx Hy p1 p3.\nby rewrite catA !mem2_cat !mem_cat Hx Hy (mem2lf Hx) !andbF !orbF.\nQed.\n\nCoInductive split2r (x y : T) : seq T -> Type :=\n  Split2r p1 p2 of y \\in x :: p2 : split2r x y (p1 ++ x :: p2).\n\nLemma splitP2r : forall p x y, mem2 p x y -> split2r x y p.\nProof.\nmove=> p x y Hxy; have Hx := mem2l Hxy.\nhave Hi := Hx; rewrite -index_mem in Hi.\nmove: Hxy; rewrite /mem2 (drop_nth x Hi) (nth_index x Hx).\nby case (splitP Hx); move=> p1 p2; rewrite cat_rcons; split.\nQed.\n\nFixpoint shorten x (p : seq T) {struct p} :=\n  if p is y :: p' then\n    if x \\in p then shorten x p' else y :: shorten y p'\n  else [::].\n\nCoInductive shorten_spec (x : T) (p : seq T) : T -> seq T -> Type :=\n   ShortenSpec p' of path e x p' & uniq (x :: p') & subpred (mem p') (mem p) :\n     shorten_spec x p (last x p') p'.\n\nLemma shortenP : forall x p, path e x p ->\n   shorten_spec x p (last x p) (shorten x p).\nProof.\nmove=> x p Hp; have: x \\in x :: p by exact: mem_head.\nelim: p x {1 3 5}x Hp => [|y2 p Hrec] x y1.\n  by rewrite mem_seq1 => _; move/eqP->; split.\nrewrite in_cons orbC /=; case/andP=> Hy12 Hp.\ncase: ifP => y2p_x.\n  case: (Hrec _ _ Hp y2p_x) => p' Hp' Up' Hp'p _.\n  by split=> // y; move/Hp'p; exact: predU1r.\ncase: (Hrec y2 _ Hp) => /= [|p' Hp' Up' Hp'p]; first by rewrite mem_head.\nhave{Hp'p} Hp'p: subpred (mem (y2 :: p')) (mem (y2 :: p)).\n  by move=> z; rewrite /= !in_cons; case: (z == y2); last exact: Hp'p.\nrewrite y2p_x -(last_cons x); move/eqP=> xy1.\nsplit=> //=; first by rewrite xy1 Hy12.\nby rewrite {}Up' andbT; apply/negP; move/Hp'p; case/negPf.\nQed.\n\nEnd EqPath.\n\n(* Ordered paths and sorting. *)\n\nSection SortSeq.\n\nVariable T : eqType.\nVariable leT : rel T.\n\nDefinition sorted s := if s is x :: s' then path leT x s' else true.\n\nLemma path_sorted : forall x s, path leT x s -> sorted s.\nProof. by move=> x [|y s] //=; case/andP. Qed.\n\nSection Transitive.\n\nHypothesis leT_tr : transitive leT.\n\nLemma order_path_min : forall x s, path leT x s -> all (leT x) s.\nProof.\nmove=> x [|y s] //=; case/andP=> le_xy; rewrite le_xy /=.\nelim: s => //= z s IHs in y le_xy *; case/andP.\nmove/(leT_tr le_xy)=> le_xz; rewrite le_xz; exact: IHs.\nQed.\n\nLemma sorted_filter : forall a s, sorted s -> sorted (filter a s).\nProof.\nmove=> a s; elim: s => //= x s IHs ord_s.\nmove/(_ (path_sorted ord_s)): IHs; case: (a x) => //=.\ncase def_s': (filter a s) => //= [y s'] ->.\nrewrite (allP (order_path_min ord_s)) //.\nhave: y \\in filter a s by rewrite def_s' mem_head.\nby rewrite mem_filter; case/andP.\nQed.\n\nLemma sorted_uniq : irreflexive leT -> forall s, sorted s -> uniq s.\nProof.\nmove=> leT_irr; elim=> //= x s IHs s_ord.\nrewrite (IHs (path_sorted s_ord)) andbT; apply/negP=> s_x.\nby case/allPn: (order_path_min s_ord); exists x; rewrite // leT_irr.\nQed.\n\nLemma eq_sorted : antisymmetric leT -> forall s1 s2,\n   sorted s1 -> sorted s2 -> perm_eq s1 s2 -> s1 = s2.\nProof.\nmove=> leT_asym; elim=> [|x1 s1 IHs1] s2 //= ord_s1 ord_s2 eq_s12.\n  by case: {+}s2 (perm_eq_size eq_s12).\nhave s2_x1: x1 \\in s2 by rewrite -(perm_eq_mem eq_s12) mem_head.\ncase: s2 s2_x1 eq_s12 ord_s2 => //= x2 s2; rewrite in_cons.\ncase: eqP => [<- _| ne_x12 /= s2_x1] eq_s12 ord_s2.\n  by rewrite {IHs1}(IHs1 s2) ?(@path_sorted x1) // -(perm_cons x1).\ncase: (ne_x12); apply: leT_asym; rewrite (allP (order_path_min ord_s2)) //.\nhave: x2 \\in x1 :: s1 by rewrite (perm_eq_mem eq_s12) mem_head.\ncase/predU1P=> [eq_x12 | s1_x2]; first by case ne_x12.\nby rewrite (allP (order_path_min ord_s1)).\nQed.\n\nLemma eq_sorted_irr : irreflexive leT -> forall s1 s2,\n  sorted s1 -> sorted s2 -> s1 =i s2 -> s1 = s2.\nProof.\nmove=> leT_irr s1 s2 s1_sort s2_sort eq_s12.\nhave: antisymmetric leT.\n  move=> m n; case/andP=> ? ltnm; case/idP: (leT_irr m); exact: leT_tr ltnm.\nmove/eq_sorted; apply=> //; apply: uniq_perm_eq => //; exact: sorted_uniq.\nQed.\n\nEnd Transitive.\n\nHypothesis leT_total : total leT.\n\nFixpoint merge s1 :=\n  if s1 is x1 :: s1' then\n    let fix merge_s1 (s2 : seq T) :=\n      if s2 is x2 :: s2' then\n        if leT x2 x1 then x2 :: merge_s1 s2' else x1 :: merge s1' s2\n      else s1 in\n    merge_s1\n  else id.\n\nLemma path_merge : forall x s1 s2,\n  path leT x s1 -> path leT x s2 -> path leT x (merge s1 s2).\nProof.\nmove=> x s1 s2; elim: s1 s2 x => //= x1 s1 IHs1; elim=> //= x2 s2 IHs2 x.\ncase/andP=> le_x_x1 ord_s1; case/andP=> le_x_x2 ord_s2.\ncase: ifP => le_x21 /=; first by rewrite le_x_x2 {}IHs2 // le_x21.\nby rewrite le_x_x1 IHs1 //=; have:= leT_total x2 x1; rewrite le_x21 /= => ->.\nQed.\n\nLemma sorted_merge : forall s1 s2,\n  sorted s1 -> sorted s2 -> sorted (merge s1 s2).\nProof.\nmove=> [|x1 s1] [|x2 s2] //= ord_s1 ord_s2.\ncase: ifP => le_x21 /=.\n  by apply: (@path_merge x2 (x1 :: s1)) => //=; rewrite le_x21.\nby apply: path_merge => //=; have:= leT_total x2 x1; rewrite le_x21 /= => ->.\nQed.\n\nLemma perm_merge : forall s1 s2, perm_eql (merge s1 s2) (s1 ++ s2).\nProof.\nmove=> s1 s2; apply/perm_eqlP; rewrite perm_eq_sym.\nelim: s1 s2 => //= x1 s1 IHs1.\nelim=> [|x2 s2 IHs2]; rewrite /= ?cats0 //.\ncase: ifP => _ /=; last by rewrite perm_cons.\nby rewrite (perm_catCA (_ :: _) [::x2]) perm_cons.\nQed.\n\nLemma mem_merge : forall s1 s2, merge s1 s2 =i s1 ++ s2.\nProof. by move=> s1 s2; apply: perm_eq_mem; rewrite perm_merge. Qed.\n\nLemma size_merge : forall s1 s2, size (merge s1 s2) = size (s1 ++ s2).\nProof. by move=> s1 s2; apply: perm_eq_size; rewrite perm_merge. Qed.\n\nLemma merge_uniq : forall s1 s2, uniq (merge s1 s2) = uniq (s1 ++ s2).\nProof. by move=> s1 s2; apply: perm_eq_uniq; rewrite perm_merge. Qed.\n\nFixpoint merge_sort_push (s1 : seq T) (ss : seq (seq T)) {struct ss} :=\n  match ss with\n  | [::] :: ss' | [::] as ss' => s1 :: ss'\n  | s2 :: ss' => [::] :: merge_sort_push (merge s1 s2) ss'\n  end.\n\nFixpoint merge_sort_pop (s1 : seq T) (ss : seq (seq T)) {struct ss} :=\n  if ss is s2 :: ss' then merge_sort_pop (merge s1 s2) ss' else s1.\n\nFixpoint merge_sort_rec (ss : seq (seq T)) (s : seq T) {struct s} :=\n  if s is [:: x1, x2 & s'] then\n    let s1 := if leT x1 x2 then [:: x1; x2] else [:: x2; x1] in\n    merge_sort_rec (merge_sort_push s1 ss) s'\n  else merge_sort_pop s ss.\n\nDefinition sort := merge_sort_rec [::].\n\nLemma sorted_sort : forall s, sorted (sort s).\nProof.\nrewrite /sort => s; have allss: all sorted [::] by [].\nelim: {s}_.+1 {-2}s [::] allss (ltnSn (size s)) => // n IHn s ss allss.\nhave: sorted s -> sorted (merge_sort_pop s ss).\n  elim: ss allss s => //= s2 ss IHss.\n  by case/andP=> *; exact: IHss (sorted_merge _ _).\ncase: s => [|x1 [|x2 s _]]; try by auto.\nmove/ltnW; move/IHn; apply; rewrite {n IHn s} ifE; set s1 := if_expr _ _ _.\nhave: sorted s1 by exact: (@sorted_merge [::x2] [::x1]).\nelim: ss {x1 x2}s1 allss => /= [|s2 ss IHss] s1; first by rewrite andbT.\ncase/andP=> ord_s2 ord_ss ord_s1.\nby case: {1}s2=> /= [|_ _]; [rewrite ord_s1 | exact: IHss (sorted_merge _ _)].\nQed.\n\nLemma perm_sort : forall s, perm_eql (sort s) s.\nProof.\nrewrite /sort => s; apply/perm_eqlP; pose catss := foldr (@cat T) [::].\nrewrite perm_eq_sym -{1}[s]/(catss [::] ++ s).\nelim: {s}_.+1 {-2}s [::] (ltnSn (size s)) => // n IHn s ss.\nhave: perm_eq (catss ss ++ s) (merge_sort_pop s ss).\n  elim: ss s => //= s2 ss IHss s1; rewrite -{IHss}(perm_eqrP (IHss _)).\n  by rewrite perm_catC catA perm_catC perm_cat2l -perm_merge.\ncase: s => // x1 [//|x2 s _]; move/ltnW; move/IHn=> {n IHn}IHs.\nrewrite -{IHs}(perm_eqrP (IHs _)) ifE; set s1 := if_expr _ _ _.\nrewrite (catA _ [::_;_] s) {s}perm_cat2r.\napply: (@perm_eq_trans _ (catss ss ++ s1)).\n  by rewrite perm_cat2l /s1 -ifE; case ifP; rewrite // (perm_catC [::_]).\nelim: ss {x1 x2}s1 => /= [|s2 ss IHss] s1; first by rewrite cats0.\nrewrite perm_catC; case def_s2: {2}s2=> /= [|y s2']; first by rewrite def_s2.\nby rewrite catA -{IHss}(perm_eqrP (IHss _)) perm_catC perm_cat2l -perm_merge.\nQed.\n\nLemma mem_sort : forall s, sort s =i s.\nProof. by move=> s; apply: perm_eq_mem; rewrite perm_sort. Qed.\n\nLemma size_sort : forall s, size (sort s) = size s.\nProof. by move=> s; apply: perm_eq_size; rewrite perm_sort. Qed.\n\nLemma sort_uniq : forall s, uniq (sort s) = uniq s.\nProof. by move=> s; apply: perm_eq_uniq; rewrite perm_sort. Qed.\n\nLemma perm_sortP : transitive leT -> antisymmetric leT ->\n  forall s1 s2, reflect (sort s1 = sort s2) (perm_eq s1 s2).\nProof.\nmove=> leT_tr leT_asym s1 s2; apply: (iffP idP) => eq12; last first.\n  by rewrite -perm_sort eq12 perm_sort.\napply: eq_sorted; rewrite ?sorted_sort //.\nby rewrite perm_sort (perm_eqlP eq12) -perm_sort.\nQed.\n\nEnd SortSeq.\n\nLemma sorted_ltn_uniq_leq : forall s, sorted ltn s = uniq s && sorted leq s.\nProof.\ncase=> //= n s; elim: s n => //= m s IHs n.\nrewrite inE ltn_neqAle negb_or IHs -!andbA.\ncase sn: (n \\in s); last do !bool_congr.\nrewrite andbF; apply/and5P=> [[ne_nm lenm _ _ le_ms]]; case/negP: ne_nm.\nrewrite eqn_leq lenm; exact: (allP (order_path_min leq_trans le_ms)).\nQed.\n\nLemma sorted_iota : forall i n, sorted leq (iota i n).\nProof. by move=> i n; elim: n i => // [[|n] //= IHn] i; rewrite IHn leqW. Qed.\n\nLemma sorted_ltn_iota : forall i n, sorted ltn (iota i n).\nProof. by move=> i n; rewrite sorted_ltn_uniq_leq sorted_iota iota_uniq. Qed.\n\n(* Function trajectories. *)\n\nNotation \"'fpath' f\" := (path (frel f))\n  (at level 10, f at level 8) : seq_scope.\n\nNotation \"'fcycle' f\" := (cycle (frel f))\n  (at level 10, f at level 8) : seq_scope.\n\nNotation \"'ufcycle' f\" := (ucycle (frel f))\n  (at level 10, f at level 8) : seq_scope.\n\nPrenex Implicits path next prev cycle ucycle mem2.\n\nSection Trajectory.\n\nVariables (T : Type) (f : T -> T).\n\nFixpoint traject x (n : nat) {struct n} :=\n  if n is n'.+1 then x :: traject (f x) n' else [::].\n\nLemma size_traject : forall x n, size (traject x n) = n.\nProof. by move=> x n; elim: n x => [|n Hrec] x //=; nat_congr. Qed.\n\nLemma last_traject : forall x n, last x (traject (f x) n) = iter n f x.\nProof. by move=> x n; elim: n x => [|n Hrec] x //; rewrite iterSr -Hrec. Qed.\n\nLemma nth_traject : forall i n, i < n ->\n  forall x, nth x (traject x n) i = iter i f x.\nProof.\nmove=> i n Hi x; elim: n {2 3}x i Hi => [|n Hrec] y [|i] Hi //=.\nby rewrite Hrec -?iterSr.\nQed.\n\nEnd Trajectory.\n\nSection EqTrajectory.\n\nVariables (T : eqType) (f : T -> T).\n\nLemma fpathP : forall x p,\n  reflect (exists n, p = traject f (f x) n) (fpath f x p).\nProof.\nmove=> x p; elim: p x => [|y p Hrec] x; first by left; exists 0.\nrewrite /= andbC; case: {Hrec}(Hrec y) => Hrec.\n  apply: (iffP eqP); first by case: Hrec => [n ->] <-; exists n.+1.\n  by case=> [] [|n] // [Dp].\nby right; move=> [[|n] // [Dy Dp]]; case: Hrec; exists n; rewrite Dy -Dp.\nQed.\n\nLemma fpath_traject : forall x n, fpath f x (traject f (f x) n).\nProof. by move=> x n; apply/(fpathP x); exists n. Qed.\n\nDefinition looping x n := iter n f x \\in traject f x n.\n\nLemma loopingP : forall x n,\n  reflect (forall m, iter m f x \\in traject f x n) (looping x n).\nProof.\nmove=> x n; apply introP; last by move=> Hn Hn'; rewrite /looping Hn' in Hn.\ncase: n => [|n] Hn //; elim=> [|m Hrec]; first by exact: predU1l.\nmove: (fpath_traject x n) Hn; rewrite /looping !iterS -last_traject /=.\nrewrite /= in Hrec; case/splitPl: Hrec; move: (iter m f x) => y p1 p2 Ep1.\nrewrite path_cat last_cat Ep1; case: p2 => [|z p2] //; case/and3P=> [_ Dy _] _.\nby rewrite !(in_cons, mem_cat) (eqP Dy) eqxx !orbT.\nQed.\n\nLemma trajectP : forall x n y,\n  reflect (exists2 i, i < n & y = iter i f x) (y \\in traject f x n).\nProof.\nmove=> x n y; elim: n x => [|n Hrec] x; first by right; case.\n  rewrite /= in_cons orbC; case: {Hrec}(Hrec (f x)) => Hrec.\n  by left; case: Hrec => [i Hi ->]; exists i.+1; last by rewrite -iterSr.\napply: (iffP eqP); first by exists 0; first by rewrite ltnNge.\nby move=> [[|i] Hi Dy] //; case Hrec; exists i; last by rewrite -iterSr.\nQed.\n\nLemma looping_uniq : forall x n, uniq (traject f x n.+1) = ~~ looping x n.\nProof.\nmove=> x n; rewrite /looping; elim: n x => [|n Hrec] x //.\nrewrite iterSr {2}[succn]lock /= -lock {}Hrec -negb_or in_cons; bool_congr.\nset y := iter n f (f x); case (trajectP (f x) n y); first by rewrite !orbT.\nrewrite !orbF => Hy; apply/idP/eqP => [Hx|Dy]; last first.\n  by rewrite -{1}Dy /y -last_traject mem_last.\ncase: {Hx}(trajectP _ n.+1 _ Hx) => [m Hm Dx].\nhave Hx': looping x m.+1 by rewrite /looping iterSr -Dx mem_head.\ncase/trajectP: (loopingP _ _ Hx' n.+1); rewrite iterSr -/y.\nmove=> [|i] Hi //; rewrite iterSr => Dy.\nby case: Hy; exists i; first exact (leq_trans Hi Hm).\nQed.\n\nEnd EqTrajectory.\n\nImplicit Arguments fpathP [T f x p].\nImplicit Arguments loopingP [T f x n].\nImplicit Arguments trajectP [T f x n y].\nPrenex Implicits traject fpathP loopingP trajectP.\n\nSection UniqCycle.\n\nVariables (n0 : nat) (T : eqType) (e : rel T) (p : seq T).\n\nHypothesis Up : uniq p.\n\nLemma prev_next : cancel (next p) (prev p).\nProof.\nmove=> x; rewrite prev_nth mem_next next_nth.\ncase Hpx: (x \\in p) => [|] //; case Dp: p Up Hpx => [|y p'] //.\nrewrite -(Dp) {1}Dp /=; move/andP=> [Hpy Hp'] Hx.\nset i := index x p; rewrite -(nth_index y Hx) -/i; congr (nth y).\nrewrite -index_mem -/i Dp /= ltnS leq_eqVlt in Hx.\ncase/predU1P: Hx => [Di|Hi]; last by apply: index_uniq.\nrewrite Di (nth_default y (leqnn _)).\nrewrite -index_mem -leqNgt in Hpy.\nby apply: eqP; rewrite eqn_leq Hpy /index find_size.\nQed.\n\nLemma next_prev : cancel (prev p) (next p).\nProof.\nmove=> x; rewrite next_nth mem_prev prev_nth.\ncase Hpx: (x \\in p) => [|] //; case Dp: p Up Hpx => [|y p'] //.\nrewrite -Dp => Hp Hpx; set i := index x p'.\nhave Hi: i < size p by rewrite Dp /= ltnS /i /index find_size.\nrewrite (index_uniq y Hi Hp); case Hx: (x \\in p'); first by apply: nth_index.\nrewrite Dp in_cons Hx orbF in Hpx; rewrite (eqP Hpx).\nby apply: nth_default; rewrite leqNgt /i index_mem Hx.\nQed.\n\nLemma cycle_next : fcycle (next p) p.\nProof.\ncase Dp: {-2}p Up => [|x p'] Up' //; apply/(pathP x)=> i; rewrite size_rcons => Hi.\nrewrite -cats1 -cat_cons nth_cat Hi /= next_nth {}Dp mem_nth //.\nrewrite index_uniq // nth_cat /=; rewrite ltnS leq_eqVlt in Hi.\ncase/predU1P: Hi => [Di|Hi]; last by rewrite Hi eqxx.\nby rewrite Di ltnn subnn nth_default ?leqnn /= ?eqxx.\nQed.\n\nLemma cycle_prev : cycle (fun x y => x == prev p y) p.\nProof.\napply: etrans cycle_next; symmetry; case Dp: p => [|x p'] //.\napply: eq_path; rewrite -Dp; exact (can2_eq prev_next next_prev).\nQed.\n\nLemma cycle_from_next : (forall x, x \\in p -> e x (next p x)) -> cycle e p.\nProof.\nmove=> He; case Dp: p cycle_next => [|x p'] //; rewrite -Dp !(cycle_path x).\nhave Hx: last x p \\in p by rewrite Dp /= mem_last.\nmove: (next p) He {Hx}(He _ Hx) => np.\nelim: (p) {x p' Dp}(last x p) => [|y p' Hrec] x He Hx //=.\ncase/andP=> [Dy Hp']; rewrite -{1}(eqP Dy) Hx /=.\napply: Hrec Hp' => [z Hz|]; apply: He; [exact: predU1r | exact: predU1l].\nQed.\n\nLemma cycle_from_prev : (forall x, x \\in p -> e (prev p x) x) -> cycle e p.\nProof.\nmove=> He; apply: cycle_from_next => [x Hx].\nby rewrite -{1}[x]prev_next He ?mem_next.\nQed.\n\nLemma next_rot : next (rot n0 p) =1 next p.\nProof.\nmove=> x; have Hp := cycle_next; rewrite -(cycle_rot n0) in Hp.\ncase Hx: (x \\in p); last by rewrite !next_nth mem_rot Hx.\nrewrite -(mem_rot n0) in Hx; exact (esym (eqP (next_cycle Hp Hx))).\nQed.\n\nLemma prev_rot : prev (rot n0 p) =1 prev p.\nProof.\nmove=> x; have Hp := cycle_prev; rewrite -(cycle_rot n0) in Hp.\ncase Hx: (x \\in p); last by rewrite !prev_nth mem_rot Hx.\nrewrite -(mem_rot n0) in Hx; exact (eqP (prev_cycle Hp Hx)).\nQed.\n\nEnd UniqCycle.\n\nSection UniqRotrCycle.\n\nVariables (n0 : nat) (T : eqType) (p : seq T).\n\nHypothesis Up : uniq p.\n\nLemma next_rotr : next (rotr n0 p) =1 next p. Proof. exact: next_rot. Qed.\n\nLemma prev_rotr : prev (rotr n0 p) =1 prev p. Proof. exact: prev_rot. Qed.\n\nEnd UniqRotrCycle.\n\nSection UniqCycleRev.\n\nVariable T : eqType.\n\nLemma prev_rev : forall p : seq T, uniq p -> prev (rev p) =1 next p.\nProof.\nmove=> p Up x; case Hx: (x \\in p); last first.\n  by rewrite next_nth prev_nth mem_rev Hx.\ncase/rot_to: Hx (Up) => [i p' Dp] Urp; rewrite -rev_uniq in Urp.\nrewrite -(prev_rotr i Urp); do 2 rewrite -(prev_rotr 1) ?rotr_uniq //.\nrewrite -rev_rot -(next_rot i Up) {i p Up Urp}Dp.\ncase: p' => [|y p'] //; rewrite !rev_cons rotr1_rcons /= eqxx.\nby rewrite -rcons_cons rotr1_rcons /= eqxx.\nQed.\n\nLemma next_rev : forall p : seq T, uniq p -> next (rev p) =1 prev p.\nProof. by move=> p Up x; rewrite -{2}[p]revK prev_rev // rev_uniq. Qed.\n\nEnd UniqCycleRev.\n\nSection MapPath.\n\nVariables (T T' : Type) (h : T' -> T) (e : rel T) (e' : rel T').\n\nDefinition rel_base (b : pred T) :=\n  forall x' y', ~~ b (h x') -> e (h x') (h y') = e' x' y'.\n\nLemma path_map : forall b x' p', rel_base b ->\n    ~~ has (preim h b) (belast x' p') ->\n  path e (h x') (map h p') = path e' x' p'.\nProof.\nmove=> b x' p' Hb; elim: p' x' => [|y' p' Hrec] x' //=; move/norP=> [Hbx Hbp].\ncongr andb; auto.\nQed.\n\nEnd MapPath.\n\nSection MapEqPath.\n\nVariables (T T' : eqType) (h : T' -> T) (e : rel T) (e' : rel T').\n\nHypothesis Hh : injective h.\n\nLemma mem2_map : forall x' y' p',\n  mem2 (map h p') (h x') (h y') = mem2 p' x' y'.\nProof. by move=> *; rewrite {1}/mem2 (index_map Hh) -map_drop mem_map. Qed.\n\nLemma next_map : forall p, uniq p ->\n  forall x, next (map h p) (h x) = h (next p x).\nProof.\nmove=> p Up x; case Hx: (x \\in p); last by rewrite !next_nth (mem_map Hh) Hx.\ncase/rot_to: Hx => [i p' Dp].\nrewrite -(next_rot i Up); rewrite -(map_inj_uniq Hh) in Up.\nrewrite -(next_rot i Up) -map_rot {i p Up}Dp /=.\nby case: p' => [|y p] //=; rewrite !eqxx.\nQed.\n\nLemma prev_map : forall p, uniq p ->\n  forall x, prev (map h p) (h x) = h (prev p x).\nProof.\nby move=> p Up x; rewrite -{1}[x](next_prev Up) -(next_map Up) prev_next ?map_inj_uniq.\nQed.\n\nEnd MapEqPath.\n\nDefinition fun_base (T T' : eqType) (h : T' -> T) f f' :=\n  rel_base h (frel f) (frel f').\n\nSection CycleArc.\n\nVariable T : eqType.\n\nDefinition arc (p : seq T) x y :=\n  let px := rot (index x p) p in take (index y px) px.\n\nLemma arc_rot : forall i p, uniq p -> {in p, arc (rot i p) =2 arc p}.\nProof.\nmove=> i p Up x Hx y; congr (fun q => take (index y q) q); move: Up Hx {y}.\nrewrite -{1 2 5 6}(cat_take_drop i p) /rot cat_uniq; move/and3P=> [_ Hp _].\nrewrite !drop_cat !take_cat !index_cat mem_cat orbC.\ncase Hx: (x \\in drop i p) => /= => [_|Hx'].\n  rewrite [x \\in _](negbTE (hasPn Hp _ Hx)).\n  by rewrite index_mem Hx ltnNge leq_addr /= addKn catA.\nby rewrite Hx' index_mem Hx' ltnNge leq_addr /= addKn catA.\nQed.\n\nLemma left_arc : forall x y p1 p2,\n  let p := x :: p1 ++ y :: p2 in uniq p -> arc p x y = x :: p1.\nProof.\nmove=> x y p1 p2 p Up; rewrite /arc {1}/p /= eqxx rot0.\nmove: Up; rewrite /p -cat_cons cat_uniq index_cat; move: (x :: p1) => xp1.\nrewrite /= negb_or -!andbA; move/and3P=> [_ Hy _].\nby rewrite (negbTE Hy) eqxx addn0 take_size_cat.\nQed.\n\nLemma right_arc : forall x y p1 p2,\n  let p := x :: p1 ++ y :: p2 in uniq p -> arc p y x = y :: p2.\nProof.\nmove=> x y p1 p2 p Up; set n := size (x :: p1); rewrite -(arc_rot n Up).\n  move: Up; rewrite -(rot_uniq n) /p -cat_cons /n rot_size_cat.\n  by move=> *; rewrite /= left_arc.\nby rewrite /p -cat_cons mem_cat /= mem_head orbT.\nQed.\n\nCoInductive rot_to_arc_spec (p : seq T) (x y : T) : Type :=\n    RotToArcSpec i p1 p2 of x :: p1 = arc p x y\n                          & y :: p2 = arc p y x\n                          & rot i p = x :: p1 ++ y :: p2 :\n    rot_to_arc_spec p x y.\n\nLemma rot_to_arc : forall p x y,\n  uniq p -> x \\in p -> y \\in p -> x != y -> rot_to_arc_spec p x y.\nProof.\nmove=> p x y Up Hx Hy Hxy; case: (rot_to Hx) (Hy) (Up) => [i p' Dp] Hy'.\nrewrite -(mem_rot i) Dp in_cons eq_sym (negPf Hxy) in Hy'.\nrewrite -(rot_uniq i) Dp.\ncase/splitPr: p' / Hy' Dp => [p1 p2] Dp Up'; exists i p1 p2; auto.\n  by rewrite -(arc_rot i Up Hx) Dp (left_arc Up').\nby rewrite -(arc_rot i Up Hy) Dp (right_arc Up').\nQed.\n\nEnd CycleArc.\n\nPrenex Implicits arc.\n\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/ssreflect/attic/ssreflect12/theories/paths.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220787, "lm_q2_score": 0.7549149923816046, "lm_q1q2_score": 0.6585481041932809}}
{"text": "Require Import ZArith.\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype seq.\n\nRequire Import Utils.\n\nClass JoinSemiLattice (Lab : Type) :=\n{ bot : Lab\n; join : Lab -> Lab -> Lab\n; flows : Lab -> Lab -> bool\n; meet : Lab -> Lab -> Lab\n; bot_flows : forall l, flows bot l = true\n; flows_refl : forall l, flows l l = true\n; flows_trans : forall l1 l2 l3, flows l1 l2 = true ->\n                                 flows l2 l3 = true ->\n                                 flows l1 l3 = true\n; flows_antisymm : forall l1 l2, flows l1 l2 = true ->\n                                 flows l2 l1 = true -> l1 = l2\n; flows_join_right : forall l1 l2, flows l1 (join l1 l2) = true\n; flows_join_left : forall l1 l2, flows l2 (join l1 l2) = true\n; join_minimal : forall l1 l2 l, flows l1 l = true ->\n                                 flows l2 l = true ->\n                                 flows (join l1 l2) l = true\n}.\n\nNotation \"l1 \\_/ l2\" := (join l1 l2) (at level 40) : type_scope.\nNotation \"l1 <: l2\" := (flows l1 l2 = true)\n  (at level 50, no associativity) : type_scope.\nNotation \"⊥\" := bot.\n\nHint Resolve\n  @flows_refl\n  @flows_trans\n  @flows_join_left\n  @flows_join_right\n  @flows_antisymm\n  @join_minimal : lat.\n\nDefinition flows_to {Lab : Type} `{JoinSemiLattice Lab} (l1 l2 : Lab) : Z :=\n  if flows l1 l2 then 1%Z else 0%Z.\n\n(** Immediate properties from the semi-lattice structure. *)\nSection JoinSemiLattice_properties.\n\nContext {T: Type}.\n\nLemma flows_join {L : JoinSemiLattice T} : forall l1 l2,\n  l1 <: l2 <-> l1 \\_/ l2 = l2.\nProof.\n  intros.\n  split.\n  - intros H.\n    apply flows_antisymm.\n    + apply join_minimal; auto with lat.\n    + apply flows_join_left.\n  - intros H.\n    rewrite <- H.\n    auto with lat.\nQed.\n\nLemma join_1_rev {L : JoinSemiLattice T} : forall l1 l2 l,\n  l1 \\_/ l2 <: l -> l1 <: l.\nProof. eauto with lat. Qed.\n\nLemma join_2_rev {L : JoinSemiLattice T} : forall l1 l2 l,\n  l1 \\_/ l2 <: l -> l2 <: l.\nProof. eauto with lat. Qed.\n\nLemma join_1 {L : JoinSemiLattice T} : forall l l1 l2,\n  l <: l1 -> l <: l1 \\_/ l2.\nProof. eauto with lat. Qed.\n\nLemma join_2 {L : JoinSemiLattice T} : forall l l1 l2,\n  l <: l2 -> l <: l1 \\_/ l2.\nProof. eauto with lat. Qed.\n\nLemma join_bot_right {L : JoinSemiLattice T} : forall l,\n  l \\_/ bot = l.\nProof.\n  eauto using bot_flows with lat.\nQed.\n\nLemma join_bot_left {L:  JoinSemiLattice T} : forall l,\n  bot \\_/ l = l.\nProof. eauto using bot_flows with lat.\nQed.\n\nLemma not_flows_not_join_flows_left {L : JoinSemiLattice T} : forall l l1 l2,\n  flows l1 l = false ->\n  flows (l1 \\_/ l2) l = false.\nProof.\n  intros.\n  destruct (flows (l1 \\_/ l2) l) eqn:E.\n  exploit join_1_rev; eauto.\n  auto.\nQed.\n\nLemma not_flows_not_join_flows_right {L : JoinSemiLattice T} : forall l l1 l2,\n  flows l2 l = false ->\n  flows (l1 \\_/ l2) l = false.\nProof.\n  intros.\n  destruct (flows (l1 \\_/ l2) l) eqn:E.\n  exploit join_2_rev; eauto.\n  auto.\nQed.\n\nDefinition label_eqb {L : JoinSemiLattice T} l1 l2 :=\n  flows l1 l2 && flows l2 l1.\n\nLemma label_eqP (L : JoinSemiLattice T) : Equality.axiom label_eqb.\nProof.\nmove => l1 l2.\nrewrite /label_eqb.\napply/(iffP idP).\n- move/andP => [H1 H2].\n  by apply flows_antisymm.\n- move => -> .\n  by rewrite !flows_refl.\nQed.\n\nDefinition label_eqMixin (L : JoinSemiLattice T) := EqMixin (@label_eqP L).\n\nEnd JoinSemiLattice_properties.\n\nHint Resolve\n  @join_1\n  @join_2\n  @bot_flows\n  @not_flows_not_join_flows_right\n  @not_flows_not_join_flows_left : lat.\n\nDefinition label_dec {T : Type} {Lat : JoinSemiLattice T}\n  : forall l1 l2 : T, {l1 = l2} + {l1 <> l2}.\nProof.\n  intros x y.\n  destruct (flows x y) eqn:xy;\n  destruct (flows y x) eqn:yx; try (right; congruence).\n  - left. eauto with lat.\n  - generalize (flows_refl x). intros.\n    right. congruence.\nDefined.\n\nClass Lattice (Lab: Type) :=\n{ jslat :> JoinSemiLattice Lab\n; top : Lab\n; flows_top : forall l, l <: top\n}.\n\nModule Import LabelEqType.\n\nCanonical label_eqType T {L : JoinSemiLattice T} := Eval hnf in EqType _ (label_eqMixin L).\n\nEnd LabelEqType.\n\nClass FiniteLattice (Lab : Type) :=\n{\n  lat :> Lattice Lab\n; elems : list Lab\n; all_elems : forall l : Lab, l \\in elems\n}.\n\nDefinition allThingsBelow {L : Type} `{FiniteLattice L} (l : L) : list L :=\n  filter (fun l' => flows l' l) elems.\n", "meta": {"author": "QuickChick", "repo": "IFC", "sha": "5af8d50df56e0b169cc47d1d1dbead199f7e08c2", "save_path": "github-repos/coq/QuickChick-IFC", "path": "github-repos/coq/QuickChick-IFC/IFC-5af8d50df56e0b169cc47d1d1dbead199f7e08c2/Labels.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6585480970784193}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n\nFixpoint even (even_arg0 : natural) : bool\n           := match even_arg0 with\n              | Zero => true\n              | Succ n => negb (even n)\n              end.\n\n\nLemma lem: forall m n, even (plus m n) = negb (even (plus m (Succ n))).\nProof.\ninduction m.\n  - intros. simpl. rewrite <- IHm. reflexivity.\n  - intros. simpl. unfold negb. destruct (even n). reflexivity. reflexivity.\nQed.\n\nLemma lem2: forall n, plus n Zero = n.\nProof.\ninduction n.\n  - simpl. rewrite IHn. reflexivity.\n  - reflexivity.\nQed.\n\n\n(* An alternaturale proof strategy is to prove that plus is commutative as a helper lemma,\nand then this theorem can be proven without induction. *)\n\nTheorem theorem0 : forall (x : natural) (y : natural), eq (even (plus x y)) (even (plus y x)).\nProof.\ninduction x.\n- intros. simpl. rewrite IHx. rewrite lem. unfold negb.\n  destruct (even (plus y (Succ x))). reflexivity. reflexivity.\n- intros. simpl. lfind. Admitted.\n\n", "meta": {"author": "ana-brendel", "repo": "coq-benchmarks", "sha": "78b9ca2993b0fb579d814ed17e63c6859e79681c", "save_path": "github-repos/coq/ana-brendel-coq-benchmarks", "path": "github-repos/coq/ana-brendel-coq-benchmarks/coq-benchmarks-78b9ca2993b0fb579d814ed17e63c6859e79681c/testing_results_initial/old_script_testing/HasSummary/clam/goal24/goal24_lfind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.7217432122827967, "lm_q1q2_score": 0.6585445985914414}}
{"text": "(** **** KE DING 8318 *)\n\nRequire Export Poly. (* Just for definitions, not homework *)\n(** **** Quiz #3 \n   Define a Coq polymorphic list function called \n   \"shuffle\" which alternates the elements\n   of two lists in the resulting output list\n   e.g., \n   (shuffle [true] [false,false]) ==> [true,false,false]\n   (shuffle [false,false] [true]) ==> [false,true,false]\n   (shuffle [1,2,3] [10,11,12,13,14]) ==> [1,10,2,11,3,12,13,14]\n   (shuffle [10,11,12,13,14] [1,2,3]) ==> [10,1,11,2,12,3,13,14]\n   (shuffle [] [1,2]) ==> [1,2]\n   (shuffle [1,2] []) ==> [1,2]\n\n    Also devise a test or two for your function\n*)\n\n(* definition here *)\nFixpoint shuffle {X : Type} (l1 : list X) (l2 : list X) : list X :=\n  match l1, l2 with\n    | nil, _ => l2\n    | _, nil => l1\n    | x1::t1, x2::t2 => x1::x2::(shuffle t1 t2)\n  end.\n\nExample test1 : shuffle [true] [false,false] = [true,false,false].\nProof. reflexivity. Qed.\nExample test2 : shuffle [false,false] [true] = [false,true,false].\nProof. reflexivity. Qed.\nExample test3 : shuffle [1,2,3] [10,11,12,13,14] = [1,10,2,11,3,12,13,14].\nProof. reflexivity. Qed.\nExample test4 : shuffle [10,11,12,13,14] [1,2,3] = [10,1,11,2,12,3,13,14].\nProof. reflexivity. Qed.\nExample test5 : shuffle [] [1,2] = [1,2].\nProof. reflexivity. Qed.\nExample test6 : shuffle [1,2] [] = [1,2].\nProof. reflexivity. Qed.\n\n(* tests here *)\nExample devise_test1 : shuffle [\"c\", \"l\", \"o\", \"y\", \"pomona\"] [\"a\", \"p\",\"l\"]\n                     = [\"c\", \"a\", \"l\", \"p\", \"o\", \"l\", \"y\", \"pomona\"].\nProof. reflexivity. Qed.\nExample devise_test2 : shuffle [monday,wednesday,friday,sunday] [tuesday,thursday,saturday] \n                     = [monday,tuesday,wednesday,thursday,friday,saturday,sunday].\nProof. reflexivity. Qed.\nExample devise_test3 : shuffle [add o, add o, add o, add (dub o), dub (add o)] [dub o, dub o]\n                     = [add o, dub o, add o, dub o, add o, add (dub o), dub (add o)].\nProof. reflexivity. Qed.\nExample devise_test4 : @shuffle nat [] [] = [].\nProof. reflexivity. Qed.\n\n(* email answers .v file to jrfisher@csupomona.edu, using quiz3 in subject line *)\n\n(** **** KE DING 8318 *)", "meta": {"author": "gf4t47", "repo": "coq", "sha": "420c6322eb340e0a0299f5ac07a2a6f495ffc72d", "save_path": "github-repos/coq/gf4t47-coq", "path": "github-repos/coq/gf4t47-coq/coq-420c6322eb340e0a0299f5ac07a2a6f495ffc72d/quiz3_KeDing_8318.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271998, "lm_q2_score": 0.912436153333645, "lm_q1q2_score": 0.6585445839266476}}
{"text": "(**\nThis file is part of the CoqApprox formalization of rigorous\npolynomial approximation in Coq:\nhttp://tamadi.gforge.inria.fr/CoqApprox/\n\nCopyright (c) 2010-2013, ENS de Lyon and Inria.\n\nThis library is governed by the CeCILL-C license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the library under the terms of the CeCILL-C\nlicense as circulated by CEA, CNRS and Inria at the following URL:\nhttp://www.cecill.info/\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided\nonly with a limited warranty and the library's author, the holder of\nthe economic rights, and the successive licensors have only limited\nliability. See the COPYING file for more details.\n*)\n\nRequire Import Rdefinitions Raxioms RIneq Rbasic_fun Zwf.\nRequire Import Epsilon FunctionalExtensionality Ranalysis1 Rsqrt_def.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool.\nFrom mathcomp Require Import eqtype ssrnat seq choice bigop.\nFrom mathcomp Require Import ssrnum ssralg fintype poly mxpoly.\nFrom mathcomp Require Import div order.\n\nRequire Import Rtrigo1 Reals Lra.\nRequire Import Reals Coquelicot.Coquelicot Psatz.\n\nDelimit Scope ring_scope with RR.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nImport Order.TTheory GRing.Theory Num.Def Num.Theory.\n\n\nLocal Open Scope R_scope.\n\nLemma Req_EM_T (r1 r2 : R) : {r1 = r2} + {r1 <> r2}.\nProof.\ncase: (total_order_T r1 r2) => [[r1Lr2 | <-] | r1Gr2].\n- by right=> r1Er2; case: (Rlt_irrefl r1); rewrite {2}r1Er2.\n- by left.\nby right=> r1Er2; case: (Rlt_irrefl r1); rewrite {1}r1Er2.\nQed.\n\nDefinition eqr (r1 r2 : R) : bool :=\n  if Req_EM_T r1 r2 is left _ then true else false.\n\nLemma eqrP : Equality.axiom eqr.\nProof.\nby move=> r1 r2; rewrite /eqr; case: Req_EM_T=> H; apply: (iffP idP).\nQed.\n\nCanonical Structure R_eqMixin := EqMixin eqrP.\nCanonical Structure R_eqType := Eval hnf in EqType R R_eqMixin.\n\nFact inhR : inhabited R.\nProof. exact: (inhabits 0). Qed.\n\nDefinition pickR (P : pred R) (n : nat) :=\n  let x := epsilon inhR P in if P x then Some x else None.\n\nFact pickR_some P n x : pickR P n = Some x -> P x.\nProof. by rewrite /pickR; case: (boolP (P _)) => // Px [<-]. Qed.\n\nFact pickR_ex (P : pred R) :\n  (exists x : R, P x) -> exists n, pickR P n.\nProof. by rewrite /pickR; move=> /(epsilon_spec inhR)->; exists 0%N. Qed.\n\nFact pickR_ext (P Q : pred R) : P =1 Q -> pickR P =1 pickR Q.\nProof.\nmove=> PEQ n; rewrite /pickR; set u := epsilon _ _; set v := epsilon _ _.\nsuff->: u = v by rewrite PEQ.\nby congr epsilon; apply: functional_extensionality=> x; rewrite PEQ.\nQed.\n\nDefinition R_choiceMixin : choiceMixin R :=\n  Choice.Mixin pickR_some pickR_ex pickR_ext.\n\nCanonical R_choiceType := Eval hnf in ChoiceType R R_choiceMixin.\n\nFact RplusA : associative (Rplus).\nProof. by move=> *; rewrite Rplus_assoc. Qed.\n\nDefinition R_zmodMixin := ZmodMixin RplusA Rplus_comm Rplus_0_l Rplus_opp_l.\n\nCanonical Structure R_zmodType := Eval hnf in ZmodType R R_zmodMixin.\n\nFact RmultA : associative (Rmult).\nProof. by move=> *; rewrite Rmult_assoc. Qed.\n\nFact R1_neq_0 : R1 != R0.\nProof. by apply/eqP/R1_neq_R0. Qed.\n\nDefinition R_ringMixin := RingMixin RmultA Rmult_1_l Rmult_1_r\n  Rmult_plus_distr_r Rmult_plus_distr_l R1_neq_0.\n\nCanonical Structure R_ringType := Eval hnf in RingType R R_ringMixin.\nCanonical Structure R_comRingType := Eval hnf in ComRingType R Rmult_comm.\n\nImport Monoid.\n\nCanonical Radd_monoid := Law RplusA Rplus_0_l Rplus_0_r.\nCanonical Radd_comoid := ComLaw Rplus_comm.\n\nCanonical Rmul_monoid := Law RmultA Rmult_1_l Rmult_1_r.\nCanonical Rmul_comoid := ComLaw Rmult_comm.\n\nCanonical Rmul_mul_law := MulLaw Rmult_0_l Rmult_0_r.\nCanonical Radd_add_law := AddLaw Rmult_plus_distr_r Rmult_plus_distr_l.\n\nDefinition Rinvx r := if (r != 0) then / r else r.\n\nDefinition unit_R r := r != 0.\n\nLemma RmultRinvx : {in unit_R, left_inverse 1 Rinvx Rmult}.\nProof.\nmove=> r; rewrite -topredE /unit_R /Rinvx => /= rNZ /=.\nby rewrite rNZ Rinv_l //; apply/eqP.\nQed.\n\nLemma RinvxRmult : {in unit_R, right_inverse 1 Rinvx Rmult}.\nProof.\nmove=> r; rewrite -topredE /unit_R /Rinvx => /= rNZ /=.\nby rewrite rNZ Rinv_r //; apply/eqP.\nQed.\n\nLemma intro_unit_R x y : y * x = R1 /\\ x * y = R1 -> unit_R x.\nProof.\nmove=> [yxE1 xyE1]; apply/eqP=> xZ.\nby case/eqP: R1_neq_0; rewrite -yxE1 xZ Rmult_0_r.\nQed.\n\nLemma Rinvx_out : {in predC unit_R, Rinvx =1 id}.\nProof. by move=> x; rewrite inE /= /Rinvx -if_neg => ->. Qed.\n\nDefinition R_unitRingMixin :=\n  UnitRingMixin RmultRinvx RinvxRmult intro_unit_R Rinvx_out.\n\nCanonical Structure R_unitRing :=\n  Eval hnf in UnitRingType R R_unitRingMixin.\n\nCanonical Structure R_comUnitRingType :=\n  Eval hnf in [comUnitRingType of R].\n\nLemma R_idomainMixin x y : x * y = 0 -> (x == 0) || (y == 0).\nProof.\n(do 2 case: (boolP (_ == _))=> // /eqP)=> yNZ xNZ xyZ.\nby case: (Rmult_integral_contrapositive_currified _ _ xNZ yNZ).\nQed.\n\nCanonical Structure R_idomainType :=\n   Eval hnf in IdomainType R R_idomainMixin.\n\nLemma R_fieldMixin : GRing.Field.mixin_of [unitRingType of R].\nProof. by done. Qed.\n\nDefinition R_fieldIdomainMixin := FieldIdomainMixin R_fieldMixin.\n\nCanonical Structure R_fieldType := FieldType R R_fieldMixin.\n\n(** Reflect the order on the reals to bool *)\n\nDefinition Rleb r1 r2 := if Rle_dec r1 r2 is left _ then true else false.\nDefinition Rltb r1 r2 := Rleb r1 r2 && (r1 != r2).\nDefinition Rgeb r1 r2 := Rleb r2 r1.\nDefinition Rgtb r1 r2 := Rltb r2 r1.\n\nLemma RlebP r1 r2 : reflect (r1 <= r2) (Rleb r1 r2).\nProof. by rewrite /Rleb; apply: (iffP idP); case: Rle_dec. Qed.\n\nLemma RltbP r1 r2 : reflect (r1 < r2) (Rltb r1 r2).\nProof.\nrewrite /Rltb /Rleb; apply: (iffP idP); case: Rle_dec=> //=.\n- by case=> // r1Er2 /eqP[].\n- by move=> _ r1Lr2; apply/eqP/Rlt_not_eq.\nby move=> Nr1Lr2 r1Lr2; case: Nr1Lr2; left.\nQed.\n\nLemma RgebP r1 r2 : reflect (r1 >= r2) (Rgeb r1 r2).\nProof.\nrewrite /Rgeb /Rleb; apply: (iffP idP); case: Rle_dec=> //=.\n  by move=> r2Lr1 _; apply: Rle_ge.\nby move=> Nr2Lr1 r1Gr2; case: Nr2Lr1; apply: Rge_le.\nQed.\n\nLemma RgtbP r1 r2 : reflect (r1 > r2) (Rgtb r1 r2).\nProof.\nrewrite /Rleb; apply: (iffP idP) => r1Hr2; first by apply: Rlt_gt; apply/RltbP.\nby apply/RltbP; apply: Rgt_lt.\nQed.\n\n(*\nLtac toR := rewrite /GRing.add /GRing.opp /GRing.zero /GRing.mul /GRing.inv\n  /GRing.one //=.\n*)\n\nSection ssreal_struct.\n \nImport GRing.Theory.\nImport Num.Theory.\nImport Num.Def.\n \nLocal Open Scope R_scope.\n \nLemma Rleb_norm_add x y : Rleb (Rabs (x + y)) (Rabs x + Rabs y).\nProof. by apply/RlebP/Rabs_triang. Qed.\n \nLemma addr_Rgtb0 x y : Rltb 0 x -> Rltb 0 y -> Rltb 0 (x + y).\nProof. by move/RltbP=> Hx /RltbP Hy; apply/RltbP/Rplus_lt_0_compat. Qed.\n \nLemma Rnorm0_eq0 x : Rabs x = 0 -> x = 0.\nProof. by move=> H; case: (x == 0) /eqP=> // /Rabs_no_R0. Qed.\n \nLemma Rleb_leVge x y : Rleb 0 x -> Rleb 0 y -> (Rleb x y) || (Rleb y x).\nProof.\nmove/RlebP=> Hx /RlebP Hy; case: (Rlt_le_dec x y).\nby move/Rlt_le/RlebP=> ->.\nby move/RlebP=> ->; rewrite orbT.\nQed.\n \nLemma RnormM : {morph Rabs : x y / x * y}.\nexact: Rabs_mult. Qed.\n \nLemma Rleb_def x y : (Rleb x y) = (Rabs (y - x) == y - x).\napply/(sameP (RlebP x y))/(iffP idP)=> [/eqP H| /Rle_minus H].\n  apply: Rminus_le; rewrite -Ropp_minus_distr.\n  apply/Rge_le/Ropp_0_le_ge_contravar.\n  by rewrite -H; apply: Rabs_pos.\napply/eqP/Rabs_pos_eq.\nrewrite -Ropp_minus_distr.\nby apply/Ropp_0_ge_le_contravar/Rle_ge.\nQed.\n \nLemma Rltb_def x y : (Rltb x y) = (y != x) && (Rleb x y).\napply/(sameP (RltbP x y))/(iffP idP).\n  case/andP=> /eqP H /RlebP/Rle_not_gt H2.\n  by case: (Rtotal_order x y)=> // [][] // /esym.\nmove=> H; apply/andP; split; [apply/eqP|apply/RlebP].\n  exact: Rgt_not_eq.\nexact: Rlt_le.\nQed.\n \nDefinition R_numMixin := NumMixin Rleb_norm_add addr_Rgtb0 Rnorm0_eq0.\n\nFact Rle_0D x y : Rleb 0 x -> Rleb 0 y -> Rleb 0 (x + y).\nProof. by move=> /RlebP Hx /RlebP Hy; apply/RlebP; lra. Qed.\n\nFact Rle_0M x y : Rleb 0 x -> Rleb 0 y -> Rleb 0 (x * y).\nProof. by move=> /RlebP Hx /RlebP Hy; apply/RlebP; nra. Qed.\n\nFact Rle_0A x : Rleb 0 x -> Rleb x 0 -> x = 0.\nProof. by move=> /RlebP Hx /RlebP Hy; nra. Qed.\n\nFact Rle_0B x y : Rleb 0 (y - x) = Rleb x y.\nProof. by apply/RlebP/RlebP; lra. Qed.\n\nFact Rle_0X x : Rleb 0 x || Rleb x 0.\nProof.\ncase: (Rle_dec 0 x) => [/RlebP->//|H]; rewrite orbC.\nby have /RlebP-> : x <= 0 by lra.\nQed.\n\nFact Rle0_Rabs x : Rleb 0 x -> Rabs x = x.\nProof. by move=> /RlebP/Rabs_pos_eq. Qed.\n\nFact Rlt_def x y : (Rltb x y) = (y != x) && (Rleb x y).\nProof.\napply/RltbP/andP => [xLy|[/eqP yDx /RlebP xLy]]; last by lra.\n  split; first by apply/eqP; lra.\nby apply/RlebP; lra.\nQed.\n\nDefinition RLeMixin : realLeMixin R_idomainType := \n  RealLeMixin Rle_0D Rle_0M Rle_0A Rle_0B Rle_0X\n              Rabs_Ropp Rle0_Rabs Rlt_def.\nLemma Rleb_total : total Rleb.\nProof.\nmove=> a b; have [/RlebP->//|/RlebP->//] : a <= b \\/ b <= a by lra.\nby rewrite orbT.\nQed.\n\nCanonical RporderType := POrderType ring_display R RLeMixin.\nCanonical RlatticeType := LatticeType R RLeMixin.\nCanonical RdistrLatticeType := DistrLatticeType R RLeMixin.\nCanonical RorderType := OrderType R Rleb_total.\nCanonical RnumDomainType := NumDomainType R RLeMixin.\nCanonical RnormedZmodType := NormedZmodType R R RLeMixin.\nCanonical RnumFieldType := [numFieldType of R].\nCanonical RrealDomainType := [realDomainType of R].\nCanonical RrealFieldType := [realFieldType of R].\n\nLemma Rarchimedean_axiom : Num.archimedean_axiom RrealFieldType.\nProof.\nmove=> x; exists (Z.abs_nat (up x) + 2)%nat.\nhave [Hx1 Hx2]:= (archimed x).\nhave Hz (z : Z): z = (z - 1 + 1)%Z by rewrite Zplus_comm Zplus_minus.\nhave Zabs_nat_Zopp z : Z.abs_nat (- z)%Z = Z.abs_nat z by case: z.\napply/RltbP/Rabs_def1.\n  apply: (Rlt_trans _ ((Z.abs_nat (up x))%:R)%RR); last first.\n    rewrite -[((Z.abs_nat _)%:R)%RR]Rplus_0_r mulrnDr.\n    by apply/Rplus_lt_compat_l/Rlt_0_2.\n  apply: (Rlt_le_trans _ (IZR (up x)))=> //.\n  elim/(well_founded_ind (Zwf_well_founded 0)): (up x) => z IHz.\n  case: (Z_lt_le_dec 0 z) => [zp | zn].\n    rewrite [z]Hz plus_IZR Zabs_nat_Zplus //; last exact: Zlt_0_le_0_pred.\n    rewrite plusE mulrnDr.\n    apply/Rplus_le_compat_r/IHz; split; first exact: Zlt_le_weak.\n    exact: Zlt_pred.\n  apply: (Rle_trans _ (IZR 0)); first exact: IZR_le.\n  by apply/RlebP/(ler0n RnumDomainType (Z.abs_nat z)).\napply: (Rlt_le_trans _ (IZR (up x) - 1)).\n  apply: Ropp_lt_cancel; rewrite Ropp_involutive.\n  rewrite Ropp_minus_distr /Rminus -opp_IZR -{2}(Z.opp_involutive (up x)).\n  elim/(well_founded_ind (Zwf_well_founded 0)): (- up x)%Z => z IHz .\n  case: (Z_lt_le_dec 0 z) => [zp | zn].\n  rewrite [z]Hz Zabs_nat_Zopp plus_IZR.\n  rewrite Zabs_nat_Zplus //; last exact: Zlt_0_le_0_pred.\n    rewrite plusE -Rplus_assoc -addnA [(_ + 2)%nat]addnC addnA mulrnDr.\n    apply: Rplus_lt_compat_r; rewrite -Zabs_nat_Zopp.\n    apply: IHz; split; first exact: Zlt_le_weak.\n    exact: Zlt_pred.\n  apply: (Rle_lt_trans _ 1).\n    rewrite -{2}[1]Rplus_0_r; apply: Rplus_le_compat_l.\n    by rewrite -/(IZR 0); apply: IZR_le.\n  rewrite mulrnDr; apply: (Rlt_le_trans _ 2).\n    by rewrite -{1}[1]Rplus_0_r; apply/Rplus_lt_compat_l/Rlt_0_1.\n  rewrite -[2]Rplus_0_l; apply: Rplus_le_compat_r.\n  by apply/RlebP/(ler0n RnumDomainType (Z.abs_nat _)).\napply: Rminus_le.\nrewrite /Rminus Rplus_assoc [- _ + _]Rplus_comm -Rplus_assoc -!/(Rminus _ _).\nexact: Rle_minus.\nQed.\n \nCanonical Structure R_archiFieldType := ArchiFieldType R Rarchimedean_axiom.\n \n(** Here are the lemmas that we will use to prove that R has\nthe rcfType structure. *)\n \nLemma continuity_eq f g : f =1 g -> continuity f -> continuity g.\nProof.\nmove=> Hfg Hf x eps Heps.\nhave [y [Hy1 Hy2]]:= Hf x eps Heps.\nby exists y; split=> // z; rewrite -!Hfg; exact: Hy2.\nQed.\n \nLemma continuity_sum (I : finType) F (P : pred I):\n(forall i, P i -> continuity (F i)) ->\ncontinuity (fun x => (\\sum_(i | P i) ((F i) x)))%RR.\nProof.\nmove=> H; elim: (index_enum I)=> [|a l IHl].\n  set f:= fun _ => _.\n  have Hf: (fun x=> 0) =1 f by move=> x; rewrite /f big_nil.\n  by apply: (continuity_eq Hf); exact: continuity_const.\nset f := fun _ => _.\ncase Hpa: (P a).\n  have Hf: (fun x => F a x + \\sum_(i <- l | P i) F i x)%RR =1 f.\n    by move=> x; rewrite /f big_cons Hpa.\n  apply: (continuity_eq Hf); apply: continuity_plus=> //.\n  exact: H.\nhave Hf: (fun x => \\sum_(i <- l | P i) F i x)%RR =1 f.\n  by move=> x; rewrite /f big_cons Hpa.\nexact: (continuity_eq Hf).\nQed.\n \nLemma continuity_exp f n: continuity f -> continuity (fun x => (f x)^+ n)%RR.\nProof.\nmove=> Hf; elim: n=> [|n IHn]; first exact: continuity_const.\nset g:= fun _ => _.\nhave Hg: (fun x=> f x * f x ^+ n)%RR =1 g.\n  by move=> x; rewrite /g exprS.\nby apply: (continuity_eq Hg); exact: continuity_mult.\nQed.\n \nLemma Rreal_closed_axiom : Num.real_closed_axiom R_archiFieldType.\nProof.\nmove=> p a b; rewrite !le_eqVlt.\ncase Hpa: (p.[a] == 0)%RR.\n  by move=> ? _ ; exists a=> //; rewrite lexx le_eqVlt.\ncase Hpb: (p.[b] == 0)%RR.\n  by move=> ? _; exists b=> //; rewrite lexx le_eqVlt andbT.\ncase Hab: (a == b).\n  by move=> _; rewrite (eqP Hab) eq_sym Hpb (ltNge 0) /=; case/andP=> /ltW ->.\nrewrite eq_sym Hpb /=; clear=> /RltbP Hab /andP [] /RltbP Hpa /RltbP Hpb.\nsuff Hcp: continuity (fun x => (p.[x])%RR).\n  have [z [[Hza Hzb] /eqP Hz2]]:= IVT _ a b Hcp Hab Hpa Hpb.\n  by exists z=> //; apply/andP; split; apply/RlebP.\nrewrite -[p]coefK poly_def.\nset f := fun _ => _.\nhave Hf: (fun (x : R) => \\sum_(i < size p) (p`_i * x^+i))%RR =1 f.\n  move=> x; rewrite /f horner_sum.\n  by apply: eq_bigr=> i _; rewrite hornerZ hornerXn.\napply: (continuity_eq Hf); apply: continuity_sum=> i _.\napply:continuity_scal; apply: continuity_exp=> x esp Hesp.\nby exists esp; split=> // y [].\nQed.\n \nCanonical Structure R_rcfType := RcfType R Rreal_closed_axiom.\n\n(* proprietes utiles de l'exp *)\n\nOpen Scope ring_scope.\n\nLemma expR0 :\n    exp(GRing.zero R_zmodType) = 1.\nProof. by rewrite exp_0. Qed.\n\nLemma expRD x y :\n    exp(x) * exp(y) = exp(GRing.add x y).\nProof. by rewrite exp_plus. Qed.\n\nLemma expRX x :\n  forall n : nat,\n    exp(x) ^+ n = exp(x *+ n).\nProof.\nelim => [|n Ihn].\n  by rewrite expr0 mulr0n exp_0.\nby rewrite exprS Ihn mulrS expRD.\nQed.\n\n Lemma Rplus_add x y :\n  Rplus x y = GRing.add x y.\nProof. by done. Qed.\n\nLemma Rmult_mul x y :\n  Rmult x y = GRing.mul x y.\nProof. by done. Qed.\n\nLemma Ropp_opp x :\n  Ropp x = GRing.opp x.\nProof. by done. Qed.\n\nLemma Rdiv_div x y :\n  y != 0 -> Rdiv x y = x / y.\nProof.\nmove=> Hneq0.\napply: (@mulIr _ y).\n  by rewrite unitfE.\nrewrite -!mulrA.\nrewrite mulVr;\n  last by rewrite unitfE.\nrewrite -[X in _*X]Rmult_mul.\nrewrite Rinv_l //.\nby apply: (elimN eqP Hneq0).\nQed.\n\nLemma sin_add x y : \n   sin (GRing.add x y) = sin x * cos y + cos x * sin y.\nProof. by rewrite sin_plus. Qed. \n\nLemma cos_add x y : \n   cos (GRing.add x y) = (cos x * cos y - sin x * sin y).\nProof. by rewrite cos_plus. Qed. \n\nLemma natr_INR n : n%:R = INR n.\nProof.\nelim: n => // n IH.\nrewrite  S_INR [_.+1%:R](natrD _ 1) IH -[1%:R]/1.\nby rewrite addrC.\nQed.\n\nLemma natrS (R :ringType) n : n.+1%:R = 1 + n%:R :> R.\nProof. by rewrite -(natrD _ 1 n). Qed.\n\nLemma Z_of_nat_gt0 n: (0 < n)%nat -> (0 < Z.of_nat n)%Z.\nProof. by case: n. Qed.\n\nLemma IZR_Zof_nat n : IZR (Z.of_nat n) = n%:R.\nProof. by rewrite -INR_IZR_INZ natr_INR. Qed.\n\nLemma expr_Rexp a1 b1 : (a1 ^+ b1)%RR = (a1 ^ b1)%R.\nProof.  by elim: b1 => //= n <-; rewrite exprS. Qed.\n\nEnd ssreal_struct.\n\n(* More theorems to make Reals and ssreflect work together *)\n\nLtac toR := rewrite /GRing.add /GRing.opp /GRing.zero /GRing.mul /GRing.inv\n  /GRing.one ?natr_INR //=.\n\nLemma pow_expn x n : Nat.pow x n = expn x n.\nProof. by elim: n => //= n ->; rewrite expnS. Qed.\n\nLemma Rabs_expr x n : Rabs (x ^+ n)%RR = (Rabs x ^+ n)%RR.\nProof.\nelim: n => [|n IH]; first by rewrite !expr0 Rabs_R1.\nby rewrite !exprS Rabs_mult IH.\nQed.\n\nLemma Rabs_exprN1 n : Rabs ((-1) ^+ n)%RR = 1.\nProof. by rewrite Rabs_expr Rabs_Ropp Rabs_R1 expr1n. Qed.\n\nLemma continuous_continuity_pt f t : \n  continuous f t -> continuity_pt f t.\nProof.\nmove=> Hc.\napply: limit1_imp; last first.\n  apply: is_lim_Reals_0.\n  apply: is_lim_comp_continuous => //.\n  apply: is_lim_id.\nby move=> x [_]; lra.\nQed.\n\nImport path.\n\nLemma eqR_leb a b : (a == b) = (Rleb a b && Rleb b a).\nProof.\napply/eqP/andP=> [->|[/RlebP H /RlebP]]; try lra.\nby split; apply/RlebP; lra.\nQed.\n\nLemma Rleb_trans : transitive Rleb.\nProof. by move=> a b c /RlebP H /RlebP H1;apply/RlebP; lra. Qed.\n\nLemma Rltb_trans : transitive Rltb.\nProof. by move=> a b c /RltbP H /RltbP H1;apply/RltbP; lra. Qed.\n\nLemma Rltb_sorted_uniq_leb s : sorted Rltb s = uniq s && sorted Rleb s.\nProof.\ncase: s => //= n s; elim: s n => //= m s IHs n.\nrewrite inE Rltb_def negb_or IHs -!andbA eq_sym.\ncase sn: (n \\in s); last do !bool_congr.\nrewrite andbF; apply/and5P=> [[ne_nm lenm _ _ le_ms]]; case/negP: ne_nm.\nby rewrite eqR_leb lenm; apply: (allP (order_path_min Rleb_trans le_ms)).\nQed.\n\nLemma ex_derive_n_minus_inter f g n a b (h := fun z => f z - g z) :\n      (forall x k,\n        (k <= n)%nat -> a < x < b -> ex_derive_n f k x) ->\n      (forall x k,\n        (k <= n)%nat -> a < x < b -> ex_derive_n g k x) ->\n      (forall x k,\n        (k <= n)%nat -> a < x < b -> ex_derive_n h k x).\nProof.\nmove=> Hf Hg x k kLn aLxLb.\npose d := (Rmin (x - a) (b - x)) / 2.\nhave Pd : 0 < d.\n  by rewrite /d /Rmin; case: Rle_dec; lra.\nhave Hd : a < x - d < x /\\ x < x + d < b.\n  by rewrite /d /Rmin; case: Rle_dec; lra.\napply: ex_derive_n_minus.\n  exists (mkposreal _ Pd) => /= y Hy k1 Hk1.\n  apply: Hf; first apply: leq_trans kLn.\n    by apply/ssrnat.leP.\n  rewrite /ball /= /AbsRing_ball /= /abs /= /minus /plus /opp /= in Hy.\n  split_Rabs; lra.\nexists (mkposreal _ Pd) => /= y Hy k1 Hk1.\napply: Hg; first apply: leq_trans kLn.\n  by apply/ssrnat.leP.\nrewrite /ball /= /AbsRing_ball /= /abs /= /minus /plus /opp /= in Hy.\nsplit_Rabs; lra.\nQed.\n\nLemma Z_of_nat_S n : Z.of_nat n.+1 = (Z.of_nat n + 1)%Z.\nProof. rewrite /=; lia. Qed.\n\nLemma Z_of_nat_double n : Z.of_nat n.*2 = (Z.of_nat n * 2)%Z.\nProof.\nby elim: n => [//=|n IH]; rewrite doubleS !Z_of_nat_S IH; lia.\nQed.\n\nLemma RInt_deriv_lin (f : R -> R) (x y : R) t1 t2  b1 b2 c1 c2 :\n   y != 0 -> t1 <= t2 -> c1 < b1 -> b2 < c2 ->\n  b1 <= x + t1 * y <= b2 -> \n  b1 <= x + t2 * y <= b2 -> \n  (forall x, c1 < x < c2 -> ex_derive f x) ->\n  (forall x, b1 <= x <= b2 -> continuous (Derive f) x) ->\n   RInt (fun z : R => Derive f  (y * z + x)) t1 t2 = \n    (/y) * (f (y * t2 + x) - f (y * t1 + x)).\nProof.\npose g t := y * t + x.\nhave ef u : ex_derive g u.\n  by repeat (apply: ex_derive_mult || apply: ex_derive_plus ||\n             apply : ex_derive_const || apply: ex_derive_id).\nhave Dg u : Derive g u = y.\n    rewrite !(Derive_plus, Derive_const, Derive_mult, Derive_id) ; try\n      by repeat (apply: ex_derive_mult || apply: ex_derive_plus ||\n                apply : ex_derive_const || apply: ex_derive_id).\n    by ring.\nhave Cg u : continuous g u.\n  by do 5\n   (apply: continuous_plus || apply: continuous_mult || apply: continuous_id || \n    apply: continuous_const).\npose RC := R_CompleteNormedModule.\nmove=> /eqP xDy t1Lt2 c1Lb1 b2Lc2 xt1B xt2B Df Cf.\nhave RyP : 0 < Rabs y by split_Rabs; lra.\nhave CDfg t : t1 <= t <= t2 ->continuous (Derive (f \\o g)) t.\n  move=> tB.\n  have : continuous (fun x => Derive g x * Derive f (g x)) t.\n    apply: continuous_mult.\n      apply: (continuous_ext (fun _ => y)) => [v//|].\n      by apply: continuous_const.\n    apply: continuous_comp => //.\n    apply: Cf.\n    by rewrite /g; nra.\n  apply: continuous_ext_loc.\n  have K2 a b c : 0 < a -> b < c / a -> a * b < c.\n    move=> aP abLc.\n    rewrite (_ : c =  a * (c / a)).\n      by apply: Rmult_lt_compat_l.\n    by field; lra.\n  have gtB : b1 <= g t <= b2 by rewrite /g; nra.\n  pose eps := Rmin (Rabs ((c1 - g t)/ y))\n                   (Rabs ((c2 - g t)/ y)).\n  have epsP : 0 < eps by\n  apply: Rmin_glb_lt; rewrite Rabs_div //;\n  apply: Rdiv_lt_0_compat; split_Rabs; lra.\n  exists (mkposreal _ epsP) => u /= Hu.\n  have uB : c1 < g u < c2.\n    have F u1 u2 u3 : u1 < Rmin u2 u3 -> (u1 < u2 /\\ u1 < u3).\n      by rewrite /Rmin; case: Rle_dec; lra.\n    have /F[F1 F2] : Rabs (u - t) < eps by apply: Hu.\n    split.\n      suff : Rabs (g t - g u) < Rabs (c1 - g t) by split_Rabs; lra.\n      have -> : g t - g u = y * (t - u)  by rewrite /g; lra.\n      rewrite Rabs_mult.\n      apply: K2 => //.\n      by rewrite -Rabs_div // Rabs_minus_sym.\n    suff : Rabs (g t - g u) < Rabs (c2 - g t) by split_Rabs; lra.\n    have -> : g t - g u = y * (t - u)  by rewrite /g; lra.\n    rewrite Rabs_mult.\n    apply: K2 => //.\n    by rewrite -Rabs_div // Rabs_minus_sym.\n  rewrite [RHS]Derive_comp //.\n  by apply: Df; lra.\nrewrite (_ : _ - _ = (f \\o g) t2 - (f \\o g) t1); last first.\n  by rewrite /g; congr (_ - f _); ring.\nrewrite -RInt_Derive; last 2 first.\n  move=> t; rewrite Rmin_left // Rmax_right // => tB.\n  apply: ex_derive_comp => //.\n    by apply: Df; rewrite /g; nra.\n  move=> t; rewrite Rmin_left // Rmax_right // => tB //.\n  by exact: CDfg.\nrewrite -[RHS](@RInt_scal RC); last first.\n  apply: ex_RInt_continuous => t; rewrite Rmin_left // Rmax_right //.\n  by exact: CDfg.\napply: RInt_ext; rewrite Rmin_left // Rmax_right // => u Hu.\nrewrite [in RHS]Derive_comp => //; last first.\n  by apply: Df; rewrite /g; nra.\nrewrite Dg /g /scal /= /mult /=; field; lra.\nQed.\n\n\nSection Sum.\n\nImport GRing.Theory.\nOpen Scope ring_scope.\n\n\nLemma ex_RInt_sum (T : eqType) (P : pred T) (f : T -> R -> R) a b l :\n  (forall i, i \\in l -> P i -> ex_RInt (f i) a b) -> \n  ex_RInt (fun x : R => \\sum_(j <- l | P j) f j x)  a b.\nProof.\nelim: l => /= [_|c l IH He].\n  apply: ex_RInt_ext => [x Hx|].\n    by rewrite big_nil.\n  by apply: ex_RInt_const.\napply: ex_RInt_ext => [x Hx|].\n  by rewrite big_cons.\nhave [Pc | NPc] := boolP (P c); last first.\n  apply: IH => i iIl.\n  by apply: He; rewrite inE iIl orbT.\napply: ex_RInt_plus.\n  by apply: He => //; rewrite inE eqxx.\napply: IH => i iIl.\nby apply: He; rewrite inE iIl orbT.\nQed.\n\nLemma RInt_sum (T : eqType) (P : pred T) (f : T -> R -> R) a b l :\n  (forall i, i \\in l -> P i -> ex_RInt (f i) a b) ->\n  RInt\n    (fun x : R => \\sum_(i <- l| P i) (f i x)) a b =\n  \\sum_(i <- l | P i)\n    RInt\n      (fun x : R => (f i x)) a b.\nProof.\nelim: l => /= [HR|c l IH HR].\n  apply: etrans.\n    apply: RInt_ext => i Hi.\n    by rewrite big_nil.\n  by rewrite RInt_const [LHS](@mulr0 [ringType of R]) big_nil.\nrewrite big_cons.\napply: etrans.\n  apply: RInt_ext => x Hx.\n  by rewrite big_cons.\ncase: (boolP (P c)) => [HP|HNP]; last first.\n  apply: IH => i iIl Pi.\n  by apply: HR; rewrite ?inE ?iIl ?orbT.\nrewrite RInt_plus ?IH => // [i iIl Pi||].\n- by apply: HR; rewrite ?inE ?iIl ?orbT.\n- by apply: HR; rewrite ?inE ?eqxx.\napply: ex_RInt_sum=> i iIl Pi.\nby apply: HR; rewrite ?inE ?iIl ?orbT.\nQed.\n\nEnd Sum.\n\nLemma ex_RInt_comp_lin1 f (u v a b : R) :\n       ex_RInt f (u * a + v) (u * b + v) ->\n       @ex_RInt R_CompleteNormedModule (fun y : R => f (u * y + v)) a b.\nProof.\nmove=> H.\ncase: (Req_dec u 0) => [->|/eqP uNz].\n  apply: ex_RInt_ext => [x Hx|].\n    rewrite [_ * _](@mul0r [ringType of R]) \n            [_ + _](@add0r [ringType of R]).\n     by [].\n  by apply: ex_RInt_const.\napply: ex_RInt_ext => [x Hx|].\n  rewrite -[RHS](@mulfK _ u); last by [].\n  by rewrite mulrC [(_ * u)%RR]mulrC.\napply: ex_RInt_scal.\nby apply: ex_RInt_comp_lin.\nQed.\n\nLemma MVT_le (f : R -> R) (a b : R) (df : R -> R): \n   (forall x : R,\n     a <= x <= b -> is_derive f x (df x)) ->\n   (forall x : R,\n     a <= x <= b -> 0 <= df x) ->\n   (forall x : R,\n      a <= x <= b -> continuity_pt f x) ->\n     a <= b -> f a <= f b.\nProof.\nmove=> H1 H2 H3 aLb.\ncase: (MVT_gen f a b df) => x;\n    rewrite Rmin_left // Rmax_right // => Hx.\n- by apply: H1; lra.\n- by apply: H3.\nrewrite (_ : f b = f b - f a + f a); try lra.\nhave [Hx1 ->] := Hx.\nhave := H2 _ Hx1.\nnra.\nQed.\n\nLemma natDivP x y : (0 < y)%nat -> (x %/ y)%nat = (x / y)%nat.\nProof.\nmove=> yP.\napply: (Nat.div_unique _ _ _ (x %% y)).\n by apply/ssrnat.ltP; rewrite ltn_mod.\nby rewrite [(_ * _)%coq_nat]mulnC -[RHS]divn_eq.\nQed.\n\nLemma Rchar : [char R]%RR =i pred0.\nProof.\ncase => //= i; rewrite !inE.\nby rewrite (@eqr_nat [numDomainType of R] i.+1 0%nat) andbF.\nQed.\n", "meta": {"author": "FlorianSteinberg", "repo": "Cheby", "sha": "2b082ee667336fa6872d00085270c7656becf2bd", "save_path": "github-repos/coq/FlorianSteinberg-Cheby", "path": "github-repos/coq/FlorianSteinberg-Cheby/Cheby-2b082ee667336fa6872d00085270c7656becf2bd/Rstruct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6585168412820093}}
{"text": "Require Import Omega.\n\n(* combinadores de táticas *)\n\nTheorem seq_comb\n  : forall (A B : Prop), (((A -> B) -> B) -> B) -> A -> B.\nProof.\n  intros A B HImp Ha ; apply HImp ; intros Hab ; apply Hab ; assumption.\nQed.\n\nTheorem chain\n  : forall (A B C : Prop), (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\n  intros A B C Habc Hab Ha ; apply Habc ; [ assumption | apply Hab ; assumption ].\nQed.\n\nTheorem orElse_example\n  : forall (A B C D : Prop), (A -> B) -> C -> ((A -> B) -> C -> (D -> B) -> D) -> A -> D.\nProof.\n  intros A B C D Hab Hc H Ha ;\n    apply H ; (assumption || intro H1) ;\n      apply Hab ; assumption.\nQed.\n\n\nLemma try_test\n  : forall (A B C D : Prop), (A -> B -> C -> D) -> (A -> B) -> (A -> C -> D).\nProof.\n  intros A B C D H H1 HA HC.\n  apply H  ; try (assumption || (apply H1 ; assumption)).\nQed.\n\nInductive even : nat -> Prop :=\n| ev_zero : even 0\n| ev_ss   : forall n, even n -> even (S (S n)).\n\n\nLemma even_100 : even 100.\nProof.\n  repeat ((apply ev_ss) || (apply ev_zero)).\nQed.\n\n(** táticas adicionais *)\n\nLemma one_not_zero : 0 <> 1.\nProof.\n  intro ; congruence.\nQed.\n\nTheorem orElse_example1\n  : forall (A B C D : Prop), (A -> B) -> C -> ((A -> B) -> C -> (D -> B) -> D) -> A -> D.\nProof.\n  intuition.\nQed.\n\nLemma le_S_cong_omega : forall n m, S n <= S m -> n <= m.\nProof.\n  intros n m ; omega.\nQed.\n\n(** tática auto *)\n\nTheorem auto_example1\n  : forall (A B C D : Prop), (A -> B) -> C -> ((A -> B) -> C -> (D -> B) -> D) -> A -> D.\nProof.\n  auto.\nQed.\n\nInductive Plus : nat -> nat -> nat -> Prop :=\n| PlusZero\n  : forall m, Plus 0 m m\n| PlusSucc\n  : forall n m r,\n    Plus n m r ->\n    Plus (S n) m (S r).\n\nExample plus_4_3 : Plus 4 3 7.\nProof.\n  repeat constructor.\nQed.\n\nHint Constructors Plus.\n\nExample plus_4_3_auto : Plus 4 3 7.\nProof.\n  auto.\nQed.\n\nLemma plus_complete : forall n m r, Plus n m r -> n + m = r.\nProof.\n  induction n ; intros m r H ; inversion H ;\n    subst ; clear H ; simpl ; f_equal ; auto. \nQed.\n\n(** programando táticas com Ltac *)\n\nLtac break_if :=\n  match goal with\n  | [ |- if ?X then _ else _ ] => destruct X\n  end.\n\nTheorem hmm : forall (a b c : bool),\n    if a\n    then if b\n         then True\n         else True\n    else if c\n         then True\n         else True.\nProof.\n  intros; repeat break_if; constructor.\nQed.\n\nLtac break_if_inside :=\n  match goal with\n  | [ |- context[if ?X then _ else _] ] => destruct X\n  end.\n\nTheorem hmm2 : forall (a b : bool),\n    (if a then 42 else 42) = (if b then 42 else 42).\nProof.\n  intros; repeat break_if_inside; reflexivity.\nQed.\n\nLtac simple_tauto :=\n  repeat match goal with\n         | [ H : ?P |- ?P ] => exact H\n         | [ |- True ] => constructor\n         | [ |- _ /\\ _ ] => constructor\n         | [ |- _ -> _ ] => intro\n         | [ H : False |- _ ] => destruct H\n         | [ H : _ /\\ _ |- _ ] => destruct H\n         | [ H : _ \\/ _ |- _ ] => destruct H\n         | [ H1 : ?P -> ?Q, H2 : ?P |- _ ] => apply H1 in H2\n         end.\n\nLemma simple_example : forall A B C, (A -> B) -> (B -> C) -> A -> C.\nProof.\n  simple_tauto.\nQed.\n", "meta": {"author": "rodrigogribeiro", "repo": "coqcourse", "sha": "1e39614285522cba5045b0a190e3bd19c560a2f7", "save_path": "github-repos/coq/rodrigogribeiro-coqcourse", "path": "github-repos/coq/rodrigogribeiro-coqcourse/coqcourse-1e39614285522cba5045b0a190e3bd19c560a2f7/code/tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.6585168407898192}}
{"text": "Require Import Frap Pset9Sig.\n(** * 6.822 Formal Reasoning About Programs, Spring 2020 - Pset 9 *)\n\n(* Authors: Adam Chlipala (adamc@csail.mit.edu),\n * Peng Wang (wangpeng@csail.mit.edu) *)\n\n(* The Forgetful Loop Rule\n *\n * In this pset, we explore a different proof rule for loops, which combines\n * some of the nifty small-footprint reasoning of the frame rule.  Specifically,\n * we consider loops where we traverse linked data structures, *forgetting*\n * about nodes as we pass through them, narrowing our focus to just the subsets\n * of nodes that future loop iterations might touch.  Recall how, to prove\n * linked-list length, we needed to do some grunt work with a predicate for\n * linked-list segments, even though the function will never again access the\n * segments described in the loop invariant.  The forgetful loop rule will allow\n * us to skip the segments and write a loop invariant the matches the overall\n * function specification. *)\n\n(* From the Sig file:\nInductive hoare_triple : forall {result}, assertion -> cmd result -> (result -> assertion) -> Prop :=\n(* First, some basic rules that look exactly the same as before *)\n| HtReturn : forall P {result : Set} (v : result),\n    hoare_triple P (Return v) (fun r => P * [| r = v |])%sep\n| HtBind : forall P {result' result} (c1 : cmd result') (c2 : result' -> cmd result) Q R,\n    hoare_triple P c1 Q\n    -> (forall r, hoare_triple (Q r) (c2 r) R)\n    -> hoare_triple P (Bind c1 c2) R\n\n(* THIS RULE IS DIFFERENT. *)\n| HtLoop : forall {acc res : Set} (init : acc) (body : acc -> cmd (loop_outcome acc res)) P Q,\n    (* As before, the premise forces us to consider any accumulator at the start\n     * of a loop iteration, proving a Hoare triple for each case. *)\n    (forall acc,\n        (* Important difference: now the rule is parameterized over both a\n         * precondition [P] and a postcondition [Q], each of which takes, as an\n         * extra argument, the latest accumulator value. *)\n        hoare_triple (P acc) (body acc)\n                     (fun r =>\n                        match r with\n                        | Done res =>\n                          Q acc res\n                          (* The loop is done?  Then the postcondition had\n                           * better be satisfied directly.  Note that it takes\n                           * the \"before\" and \"after\" accumulators as arguments.\n                           * We'll see shortly why that pays off.... *)\n                        | Again acc' =>\n                          (* It's time for more iterations?  Then we'd better\n                           * satisfy [P] w.r.t. the \"after\" accumulator, but\n                           * with a twist.  We are allowed to *forget* some\n                           * state, captured by the arbitrary frame predicate\n                           * [R].  The idea is that the state we shunt into [R]\n                           * will not be touched again until the loop finishes\n                           * running. *)\n                          exists R, P acc' * R\n                                    (* There is another important requirement on\n                                     * [R]: Assume that the loop finishes, so\n                                     * that the postcondition [Q] is satisfied\n                                     * w.r.t. the new accumulator [acc'].  If we\n                                     * *put back* [R], we should then arrive at\n                                     * a state where the postcondition is\n                                     * satisfied w.r.t. the \"before\" accumulator\n                                     * [acc]! *)\n                                    * [| forall r, Q acc' r * R ===> Q acc r |]\n                        end%sep))\n    -> hoare_triple (P init) (Loop init body) (Q init)\n(* All that may be a bit abstract, but we will show an example\n * verification below, to illustrate. *)\n\n| HtFail : forall {result},\n    hoare_triple (fun _ => False) (Fail (result := result)) (fun _ _ => False)\n\n| HtRead : forall a R,\n    hoare_triple (exists v, a |-> v * R v)%sep (Read a) (fun r => a |-> r * R r)%sep\n| HtWrite : forall a v v',\n    hoare_triple (a |-> v)%sep (Write a v') (fun _ => a |-> v')%sep\n| HtAlloc : forall numWords,\n    hoare_triple emp%sep (Alloc numWords) (fun r => [| r <> 0 |] * r |--> zeroes numWords)%sep\n(* ----------------------------------------------------^^^^^^\n * DIFFERENCE FROM CLASS: Now we record that a freshly allocated object has\n * a nonnull address, so that we are free to use null (0) for a special purpose\n * in linked data structures. *)\n\n| HtFree : forall a numWords,\n    hoare_triple (a |->? numWords)%sep (Free a numWords) (fun _ => emp)%sep\n\n| HtConsequence : forall {result} (c : cmd result) P Q (P' : assertion) (Q' : _ -> assertion),\n    hoare_triple P c Q\n    -> P' ===> P\n    -> (forall r, Q r ===> Q' r)\n    -> hoare_triple P' c Q'\n| HtFrame : forall {result} (c : cmd result) P Q R,\n    hoare_triple P c Q\n    -> hoare_triple (P * R)%sep c (fun r => Q r * R)%sep.\n\nNotation \"{{ P }} c {{ r ~> Q }}\" :=\n  (hoare_triple P%sep c (fun r => Q%sep)) (at level 90, c at next level).\n*)\n\n\n(** * EXAMPLE VERIFICATION: linked-list length revisited *)\n\n(* First, here's essentially the same list-predicate definition from class. *)\n\nFixpoint llist' (ls : list nat) (p : nat) : hprop :=\n  match ls with\n  | nil => [| p = 0 |]\n  | x :: ls' => [| p <> 0 |] * exists p', p |--> [x; p'] * llist' ls' p'\n  end%sep.\n\n(* Let's define a less precise version, which forgets exactly which data a list\n * stores, only remembering that there is indeed a list rooted at [p]. *)\nDefinition llist (p : nat) :=\n  (exists ls, llist' ls p)%sep.\n(* In general with this pset, we'll work with less precise predicates like this\n * [llist], to give you a bit of a break! *)\n\n(* We can prove some logical equivalences on our predicates. *)\n\nLemma llist'_null : forall {ls p}, p = 0\n  -> llist' ls p === [| ls = nil |].\nProof.\n  heq; cases ls; cancel.\nQed.\n\nTheorem llist_null : forall p, p = 0\n  -> llist p === emp.\nProof.\n  unfold llist; simplify.\n  setoid_rewrite (llist'_null H).\n  (* setoid_rewrite does not support \"with\", just positional arguments *)\n  heq; cancel.\nQed.\n\nLemma llist'_nonnull : forall {ls p}, p <> 0\n  -> llist' ls p === exists ls' x p', [| ls = x :: ls' |] * p |--> [x; p'] * llist' ls' p'.\nProof.\n  heq; cases ls; cancel.\n  equality.\n  invert H0; cancel.\nQed.\n\nTheorem llist_nonnull : forall {p}, p <> 0\n  -> llist p === exists x p', p |--> [x; p'] * llist p'.\nProof.\n  unfold llist; simplify.\n  setoid_rewrite (llist'_nonnull H).\n  heq; cancel.\nQed.\n\nOpaque llist.\n(* It's important that we mark [llist] as opaque after we've finished proving\n * the lemmas, so that its definition is never again unfolded.  Rather, we\n * reason about it only with the two lemmas we proved for it. *)\n\n(* Now here's linked-list length again. *)\nDefinition llength (p : nat) :=\n  for a := (p, 0) loop\n    if fst a ==n 0 then\n      Return (Done (snd a))\n    else\n      y <- Read (fst a + 1);\n      Return (Again (y, snd a + 1))\n  done.\n\n(* And here's the simpler proof. However, this time around, we\n * don't prove any functional correctness. We only confirm\n * the absence of memory errors and that if a [llength] call finishes,\n * [p] still points to some linked list.\n *)\nTheorem llength_ok : forall p,\n  {{llist p}}\n    llength p\n  {{_ ~> llist p}}.\nProof.\n  unfold llength.\n  simp.\n  (* We have reached the loop, and it's time to pick an invariant.  The\n   * forgetful loop rule asks for both a precondition and a postcondition, so\n   * the [loop_inv] tactic takes both as separate arguments. *)\n  loop_inv (fun a : nat * nat => llist (fst a))\n           (fun (a : nat * nat) (_ : nat) => llist (fst a)).\n    (* We can use the most natural invariant: there is a list rooted at the first\n     * component of the accumulator [a]. *)\n  -\n    cases (a ==n 0).\n    + step.\n      cancel.\n    + rewrite llist_nonnull by assumption.\n      step.\n      step.\n      simp.\n      step.\n      (* Here's where we encounter the extra quantified [R] from the forgetful loop\n       * rule.  The automation isn't quite smart enough to pick a good [R] for us,\n       * and anyway we might prefer to be in control of what we forget!  We use the\n       * lemma [exis_right] to manually instantiate an existential quantifier\n       * immediately to the right of [===>]. *)\n      apply exis_right with (x := ((a+1) |-> r * exists n0, a |-> n0)%sep).\n      (* The right choice in this case: forget the list cell that [a] points to.  We\n       * are done with this cell and can continue the loop using only the cells that\n       * follow it. *)\n      cancel.\n      rewrite (llist_nonnull n).\n      (* We specify the hypothesis [n] of [llist_nonnull] so that Coq chooses to\n       * rewrite the correct occurrence of [llist] in the goal.  Try without that\n       * detail and watch Coq make the wrong choice! *)\n      cancel.\n  - cancel.\n  - cancel.\nQed.\n\n\n(** * Binary trees *)\n\n(* Now we define binary trees and ask you to verify two of their classic\n * operations. This verification task only concerns memory safety, not\n   functional correctness -- which you already tackled in pset 4! *)\n\n(*\nInductive tree :=\n| Leaf\n| Node (l : tree) (x : nat) (r : tree).\n*)\n\n(* [m] for memory! *)\nFixpoint mtree' (t : tree) (p : nat) : hprop :=\n  match t with\n  | Leaf => [| p = 0 |]\n  | Node l x r => [| p <> 0 |]\n                  * exists p1 p2, p |--> [p1; x; p2]\n                                  * mtree' l p1\n                                  * mtree' r p2\n  end%sep.\n\n(* Here's the version that forgets exactly which tree it is. *)\nDefinition mtree (p : nat) : hprop :=\n  (exists t, mtree' t p)%sep.\n\n(* And here's an extra layer of indirection: a mutable pointer to a tree, which\n * comes in handy for operations that modify the tree. *)\nDefinition mtreep (p : nat) : hprop :=\n  (exists p', [| p <> 0 |] * p |-> p' * mtree p')%sep.\n\n(* Your task: verify the lookup and insertion methods below.\n *\n * Before diving into the proof hacking, it might be a good idea to review the\n * relevant material from the lecture. To help you do that, we suggest that you\n * briefly answer each of the questions below. This exercise is not graded, but\n * we hope it will help you understand the material better.\n * We will also reference this list in office hours to see where you\n * might be stuck.\n *\n * - What does A * B mean?\n *\n * - What does h === g mean?\n *\n * - What does [| P |] do? (When is it necessary?)\n *\n * - What does p |--> [x;y] mean?\n *\n * - What does emp mean?\n *\n * - What memory does an empty llist use?\n *\n * - How can code detect that an llist is empty?\n *\n * - What memory does an llist cons cell use?\n *\n * - How can code detect that an llist starts with a cons cell?\n *\n * - If an llist starts with a cons cell, which lemma/theorem can we use to learn something about its tail, and what does it tell us?\n *\n * - What is the difference between llist' and llist?\n *\n * - How do proofs of lemmas about llist use lemmas about llist'?\n *\n * (extra pedantry:)\n *\n * - Have you read the proof of llength_ok?\n *\n * - Have you stepped through the proof of llength_ok?\n *\n * - Have you read the goal before and after every commented tactic invocation in llength_ok?\n *\n * Now proving correctness of binary-tree manipulation shouldn't be too bad. Cheers!\n*)\n\n\n(* IMPORTANT NOTE:\n * The difficulty of this problem set is scoped assuming you will use the\n * tactics included in the Sig file, which are very similar to the ones from\n * lecture!  Trying to attack these proofs from first principles will likely\n * lead to proof size spiraling out of control. The main ingredients you should\n * expect to reuse are:\n *  - [step]: A tactic to choose the right Hoare-logic rule to apply next, when\n *    your goal is a Hoare triple\n *  - [cancel]: A tactic to prove an implication between two separation-logic\n *    assertions, or reduce it to a simpler implication by *cancel*ing matching\n *    subformulas; before calling [cancel], be sure you have marked [Opaque]\n *    all of the predicates standing for data structures!  There is an [Opaque\n *    mtree] command right below for precisely this reason; please put any lemmas\n *    about [mtree] before it and all program logic proofs after.\n *  - [heq]: A tactic to reduce a separation-logic assertion implication (using\n *    [===]) to two implications (using [===>])\n *  - [loop_inv P0 Q0]: A tactic to apply the loop rule, given an invariant\n *    split in a peculiar way; see above for an example\n *  - [setoid_rewrite H]: A tactic to rewrite within a separation-logic\n *    implication, using an equivalence that applies to one of its subterms\n *\n * Our solution also has a few direct uses of rules [HtConsequence] and\n * [HtFrame], sometimes using the [with] syntax of [apply] to specify values\n * for some variables that appear in these rules' statements. In particular,\n * you can use [HtConsequence] before [HtFrame] to ensure that the predicate\n * that you want to frame out is in the desired syntactic position so that\n * [HtFrame] will apply. The [exis_right] lemma will also be handy, as used\n * in the example above. *)\n\n(* Space is provided here for additional lemmas about [mtree] and [mtree']. *)\n\n\n\n\nOpaque mtree.\n(* ^-- Keep predicates opaque after you've finished proving all the key\n* algebraic properties about them, in order for them to work well with\n* the [cancel] tactic. *)\n\n(* Here's the usual lookup operation. *)\nDefinition lookup (x p : nat) :=\n  t <- Read p; (* First peel away the initial layer of indirection.\n                * You will want to use the regular old frame rule to forget\n                * about some of the state that you won't need after this\n                * point! *)\n  for a := t loop\n    (* The accumulator tells us: the node of the tree we have reached\n     * (for [Again]) or whether the key [x] has been found (for [Done]). *)\n    if a ==n 0 then\n      (* Oh, the pointer is null.  Sorry, didn't find [x]. *)\n      Return (Done false)\n    else\n      (* Read the data value of the current node (which must be nonnull). *)\n      y <- Read (a + 1);\n      if x ==n y then\n        (* Found it! *)\n        Return (Done true)\n      else if x <=? y then\n        (* The key must be earlier in the tree.  Read the left-child pointer and\n         * continue looping with it. *)\n        l <- Read a;\n        Return (Again l)\n      else\n        (* The key must be later in the tree.  Read the right-child pointer and\n         * continue looping with it. *)\n        r <- Read (a + 1 + 1);\n        (* Why [+ 1 + 1] instead of [+ 2]?  It happens to work better with the\n         * automation we're using. ;) *)\n        Return (Again r)\n  done.\n\nTheorem lookup_ok : forall x p,\n  {{mtreep p}}\n    lookup x p\n  {{_ ~> mtreep p}}.\nProof.\nAdmitted.\n\n\n(* And here's the operation to add a new key to a tree. *)\nDefinition insert (x p : nat) :=\n  for a := p loop\n    (* Note that now the accumulator is not the latest tree root, but instead\n     * *a pointer to it*, so that we may overwrite that pointer if necessary.\n     * We start by reading the actual root out of the pointer [p]. *)\n    q <- Read a;\n    if q ==n 0 then\n      (* It's a null pointer?  Perfect.  This is the spot to insert a new\n       * node. *)\n      node <- Alloc 3;\n      (* Initialize its data field with [x]. *)\n      _ <- Write (node + 1) x;\n      (* Redirect the pointer [p] to the new node. *)\n      _ <- Write a node;\n      Return (Done tt)\n    else\n      (* Nonnull?  Read the data field into [y]. *)\n      y <- Read (q + 1);\n      if x <=? y then\n        (* The right spot to insert must be to the left.  Recurse thataway. *)\n        Return (Again q)\n      else\n        (* The right spot to insert must be to the right.  Recurse thataway. *)\n        Return (Again (q + 1 + 1))\n  done.\n\n(* Something very subtle happened in that loop: we iterated using a pointer into\n * *the interior of a struct*, in each branch of the last [if]!  This is a fun\n * example of the kinds of tricks that can be played in a low-level language,\n * and the verification techniques are up to the challenge. *)\n\nTheorem insert_ok : forall x p,\n  {{mtreep p}}\n    insert x p\n  {{_ ~> mtreep p}}.\nProof.\nAdmitted.\n\n(* Our solution also includes a proof that the Hoare triples in this pset\n * correspond to the usual operational semantics... which you do not need\n * to prove. *)\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/pset09_SeparationLogic/Pset9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173791645582, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.658516837583293}}
{"text": "\nRequire Export Iron.Language.SystemF2Cap.Type.Exp.\nRequire Export Iron.Language.SystemF2Cap.Type.Operator.LiftTT.\nRequire Export Iron.Language.SystemF2Cap.Type.Operator.LowerTT.\nRequire Export Iron.Language.SystemF2Cap.Type.Relation.WfT.\n\n\n(********************************************************************)\n(* Substitution of Types in Types. *)\nFixpoint substTT (d: nat) (u: ty) (tt: ty) : ty \n := match tt with\n    | TVar ix\n    => match nat_compare ix d with\n       | Eq          => u\n       | Gt          => TVar (ix - 1)\n       | _           => TVar  ix\n       end\n\n    |  TForall k t   => TForall k (substTT (S d) (liftTT 1 0 u) t)\n    |  TApp t1 t2    => TApp      (substTT d u t1) (substTT d u t2)\n    |  TSum t1 t2    => TSum      (substTT d u t1) (substTT d u t2)\n    |  TBot k        => TBot k\n\n    | TCon0 tc       => TCon0 tc\n    | TCon1 tc t1    => TCon1 tc  (substTT d u t1)\n    | TCon2 tc t1 t2 => TCon2 tc  (substTT d u t1) (substTT d u t2)\n    | TCap _         => tt\n  end.\n\n\n(********************************************************************)\n(* What might happen when we substitute for a variable.\n   This can be easier use than the raw substTT definition. *)\nLemma substTT_TVar_cases\n :  forall n1 n2 t1\n ,  (substTT n1 t1 (TVar n2) = t1            /\\ n1 = n2)\n \\/ (substTT n1 t1 (TVar n2) = TVar (n2 - 1) /\\ n1 < n2)\n \\/ (substTT n1 t1 (TVar n2) = TVar n2       /\\ n1 > n2).\nProof.\n intros.\n unfold substTT.\n  lift_cases; burn.\nQed. \n\n\nLemma substTT_wfT_above\n :  forall d ix t t2\n ,  WfT d t\n -> substTT (d + ix) t2 t = t.\nProof.\n intros. gen d ix t2.\n induction t; rip; inverts H; simpl; f_equal; burn.\n\n Case \"TVar\".\n  norm; omega.\n  lets D: IHt H1. burn.\nQed.\nHint Resolve substTT_wfT_above.\n\n\nLemma substTT_wfT\n :  forall d ix t1 t2\n ,  ix <= d\n -> WfT (S d) t1\n -> WfT d     t2\n -> WfT d (substTT ix t2 t1).\nProof.\n intros. gen d ix t2.\n induction t1; rip; inverts H0; simpl; snorm.\nQed.\nHint Resolve substTT_wfT.\n\n\n(* Closing substitution of types in types *)\nLemma substTT_closing\n :  forall t1 t2\n ,  WfT 1 t1\n -> ClosedT t2\n -> ClosedT (substTT 0 t2 t1).\nProof. eauto. Qed.\nHint Resolve substTT_closing.\n\n\nLemma substTT_closedT_id\n :  forall d t t2\n ,  ClosedT t\n -> substTT d t2 t = t.\nProof.\n intros. rrwrite (d = d + 0). eauto.\nQed.\nHint Resolve substTT_closedT_id.\n\n\nLemma substTT_liftTT_wfT1\n :  forall t1 t2\n ,  WfT 1 t1\n -> ClosedT t2\n -> substTT 0 t2 t1 = liftTT 1 0 (substTT 0 t2 t1).\nProof.\n intros.\n have    (ClosedT (substTT 0 t2 t1)).\n rrwrite (liftTT 1 0 (substTT 0 t2 t1) = substTT 0 t2 t1).\n trivial.\nQed.\nHint Resolve substTT_liftTT_wfT1.\n\n\n(* Substituting into TBot is still TBot. *)\nLemma substTT_TBot\n : forall d t2 k\n , substTT d t2 (TBot k) = TBot k.\nProof. burn. Qed.\nHint Resolve substTT_TBot.\nHint Rewrite substTT_TBot : global.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/devel/Iron/Language/SystemF2Cap/Type/Operator/SubstTT/Base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126791, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6585168358159665}}
{"text": "Require Import Setoid.\n\nParameter A : Set.\n\nAxiom eq_dec : forall a b : A, {a = b} + {a <> b}.\n\nInductive set : Set :=\n  | Empty : set\n  | Add : A -> set -> set.\n\nFixpoint In (a : A) (s : set) {struct s} : Prop :=\n  match s with\n  | Empty => False\n  | Add b s' => a = b \\/ In a s'\n  end.\n\nDefinition same (s t : set) : Prop := forall a : A, In a s <-> In a t.\n\nLemma setoid_set : Setoid_Theory set same.\n\nunfold same in |- *; split ; red.\nred in |- *; auto.\n\nred in |- *.\nintros.\nelim (H a); auto.\n\nintros.\nelim (H a); elim (H0 a).\nsplit; auto.\nQed.\n\nAdd Setoid set same setoid_set as setsetoid.\n\nAdd Morphism In : In_ext.\nunfold same in |- *; intros a s t H; elim (H a); auto.\nQed.\n\nLemma add_aux :\n forall s t : set,\n same s t -> forall a b : A, In a (Add b s) -> In a (Add b t).\nunfold same in |- *; simple induction 2; intros.\nrewrite H1.\nsimpl in |- *; left; reflexivity.\n\nelim (H a).\nintros.\nsimpl in |- *; right.\napply (H2 H1).\nQed.\n\nAdd Morphism Add : Add_ext.\nsplit; apply add_aux.\nassumption.\n\nrewrite H.\nreflexivity.\nQed.\n\nFixpoint remove (a : A) (s : set) {struct s} : set :=\n  match s with\n  | Empty => Empty\n  | Add b t =>\n      match eq_dec a b with\n      | left _ => remove a t\n      | right _ => Add b (remove a t)\n      end\n  end.\n\nLemma in_rem_not : forall (a : A) (s : set), ~ In a (remove a (Add a Empty)).\n\nintros.\nsetoid_replace (remove a (Add a Empty)) with Empty.\n\nauto.\n\nunfold same in |- *.\nsplit.\nsimpl in |- *.\ncase (eq_dec a a).\nintros e ff; elim ff.\n\nintros; absurd (a = a); trivial.\n\nsimpl in |- *.\nintro H; elim H.\nQed.\n\nParameter P : set -> Prop.\nParameter P_ext : forall s t : set, same s t -> P s -> P t.\n\nAdd Morphism P : P_extt.\nintros; split; apply P_ext; (assumption || apply (Seq_sym _ _ setoid_set); assumption).\nQed.\n\nLemma test_rewrite :\n forall (a : A) (s t : set), same s t -> P (Add a s) -> P (Add a t).\nintros.\nrewrite <- H.\nrewrite H.\nsetoid_rewrite <- H.\nsetoid_rewrite H.\nsetoid_rewrite <- H.\ntrivial.\nQed.\n\n(* Unifying the domain up to delta-conversion (example from emakarov) *)\n\nDefinition id: Set -> Set := fun A => A.\nDefinition rel : forall A : Set, relation (id A) := @eq.\nDefinition f: forall A : Set, A -> A := fun A x => x.\n\nAdd Relation (id A) (rel A) as eq_rel.\n\nAdd Morphism (@f A) : f_morph.\nProof.\nunfold rel, f. trivial.\nQed.\n\n(* Submitted by Nicolas Tabareau *)\n(* Needs unification.ml to support environments with de Bruijn *)\n\nGoal forall\n  (f : Prop -> Prop)\n  (Q : (nat -> Prop) -> Prop)\n  (H : forall (h : nat -> Prop), Q (fun x : nat => f (h x)) <-> True)\n  (h:nat -> Prop),\n  Q (fun x : nat => f (Q (fun b : nat => f (h x)))) <-> True.\nintros f0 Q H.\nsetoid_rewrite H.\ntauto.\nQed.\n\n(** Check proper refreshing of the lemma application for multiple \n   different instances in a single setoid rewrite. *)\n\nSection mult.\n  Context (fold : forall {A} {B}, (A -> B) -> A -> B).\n  Context (add : forall A, A -> A).\n  Context (fold_lemma : forall {A B f} {eqA : relation B} x, eqA (fold A B f (add A x)) (fold _ _ f x)).\n  Context (ab : forall B, A -> B).\n  Context (anat : forall A, nat -> A).\n\nGoal forall x, (fold _ _ (fun x => ab A x) (add A x) = anat _ (fold _ _ (ab nat) (add _ x))). \nProof. intros.\n  setoid_rewrite fold_lemma. \n  change (fold A A (fun x0 : A => ab A x0) x = anat A (fold A nat (ab nat) x)).\nAbort.\n\nEnd mult.\n\n(** Current semantics for rewriting with typeclass constraints in the lemma \n   does not fix the instance at the first unification, use [at], or simply rewrite for \n   this semantics. *)\n\nRequire Import Arith.\n\nClass Foo (A : Type) := {foo_neg : A -> A ; foo_prf : forall x : A, x = foo_neg x}.\nInstance: Foo nat. admit. Defined.\nInstance: Foo bool. admit. Defined.\n\nGoal forall (x : nat) (y : bool), beq_nat (foo_neg x) 0 = foo_neg y.\nProof. intros. setoid_rewrite <- foo_prf. change (beq_nat x 0 = y). Abort.\n\nGoal forall (x : nat) (y : bool), beq_nat (foo_neg x) 0 = foo_neg y.\nProof. intros. setoid_rewrite <- @foo_prf at 1. change (beq_nat x 0 = foo_neg y). Abort.\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/setoid_test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.658516828418534}}
{"text": "Lemma impl_and_iff {A B C} : (A -> (B /\\ C)) <-> ((A -> B) /\\ (A -> C)).\nProof. tauto. Qed.\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/Logic/ImplAnd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6585103328363756}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra.\nRequire Import codegen.codegen primitivity nat_word BinNat.\nRequire mt cycle.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection gluing.\nLocal Open Scope N_scope.\n\nNotation len := 624. (* 'n' in tgfsr3.pdf, p.4 is 623*)\nNotation m := 397. (* 'm' in  tgfsr3.pdf, p.4 *)\nNotation w := 32.\nNotation r := 31.\nNotation u := 11.\nNotation s := 7.\nNotation t := 15.\nNotation l := 18.\nNotation a := 2567483615.\nNotation b := 2636928640.\nNotation c := 4022730752.\n\nDefinition upper_mask := Eval compute in @mt.upper_mask r w erefl.\nDefinition lower_mask := Eval compute in @mt.lower_mask r w erefl.\nDefinition whole_mask :=\nEval compute in N_of_word (Tuple (@introTF _ _ true eqP (size_rep (1%R: 'F_2) w))).\nDefinition set_nth d xs n := Eval compute in @set_nth N d xs n.\nDefinition nth d xs n := Eval compute in @nth N d xs n.\nDefinition next_random_state (rand : mt.random_state) :=\nlet state_vec := mt.state_vector rand in\nlet ind := mt.index rand in\nlet current := nth 0 state_vec ind in\nlet next_ind := N.succ ind mod len in\nlet next := nth 0 state_vec next_ind in\nlet far_ind := (ind + m) mod len in\nlet far := nth 0 state_vec far_ind in\nlet z := N.lor (N.land current upper_mask) (N.land next lower_mask) in\nlet xi := N.lxor (N.lxor far (N.shiftr z 1)) (if N.testbit z 0 then a else 0) in\nlet next_rand :=\n  {| mt.index := next_ind; mt.state_vector := set_nth 0 state_vec ind xi |} in\n(xi, next_rand).\n\nLemma next_random_stateE2 :\n  next_random_state =1 @mt.next_random_state len m r a w erefl.\nProof. by []. Qed.\n\nDefinition tempering xi :=\n  let y1 := N.lxor xi (N.shiftr xi u) in\n  let y2 := N.lxor y1 (N.land (N.shiftl y1 s) b) in\n  let y3 := N.lxor y2 (N.land (N.shiftl y2 t) c) in\n  let y4 := N.lxor y3 (N.shiftr y3 l) in\n  y4.\nLemma temperingE : tempering =1 mt.tempering u s t l b c.\nProof. by []. Qed.\n\nDefinition cycle_next_random_state :=\n  @cycle.cycle_next_random_state w len (len - m) r (word_of_N w a) pm\n                                 erefl erefl erefl erefl erefl.\nEnd gluing.\n\nCodeGen Snippet \"#include <stdbool.h> /* for bool, true and false */\".\n\nCodeGen Inductive Type bool => \"bool\".\nCodeGen Inductive Match bool => \"\"\n| true => \"default\"\n| false => \"case 0\".\nCodeGen Constant true => \"true\".\nCodeGen Constant false => \"false\".\n\nCodeGen Snippet \"#include <stdint.h>\".\nCodeGen Snippet \"#include <stdio.h>\".\nCodeGen Snippet \"typedef uint64_t nat;\".\nCodeGen Snippet \"typedef uint32_t positive;\".\nCodeGen Snippet \"typedef uint32_t N;\".\nCodeGen Snippet \"#define succ(n) ((n)+1)\".\nCodeGen Snippet \"#define succn(n) ((n)+1)\".\nCodeGen Snippet \"#define predn(n) ((n)-1)\".\nCodeGen Snippet \"#define xH() (1)\".\nCodeGen Snippet \"#define xO(n) (2*(n))\".\nCodeGen Snippet \"#define xI(n) (2*(n)+1)\".\nCodeGen Snippet \"#define add(n, m) ((n) + (m))\".\nCodeGen Snippet \"#define subn(n, m) ((n) - (m))\".\nCodeGen Snippet \"#define modulo(n, m) ((n) % (m))\".\nCodeGen Snippet \"#define lxor(n, m) ((n) ^ (m))\".\nCodeGen Snippet \"#define lor(n, m) ((n) | (m))\".\nCodeGen Snippet \"#define land(n, m) ((n) & (m))\".\nCodeGen Snippet \"#define testbit(n1,n2) ((n1)&(1<<(n2)))\".\nCodeGen Snippet \"#define nat_of_bin(n) ((nat)(n))\".\nCodeGen Snippet \"#define N0() (0)\".\nCodeGen Snippet \"#define Npos(n) ((nat)(n))\".\nCodeGen Snippet \"#define shiftl(n1,n2) ((n1)<<(n2))\".\nCodeGen Snippet \"#define shiftr(n1,n2) ((n1)>>(n2))\".\n\nCodeGen Inductive Type nat => \"nat\".\nCodeGen Inductive Match nat => \"\"\n| O => \"case 0\"\n| S => \"default\" \"predn\".\nCodeGen Primitive S => \"succn\".\n\nCodeGen Snippet \"#define LARGE_NUM 1000\".\nCodeGen Snippet \"\ntypedef struct {\n  N list[LARGE_NUM];\n  int index;\n} list_N;\n\".\n\nCodeGen Snippet \"\ntypedef struct {\n  N index;\n  list_N state_vector;\n} rand_state;\n\".\n\nCodeGen Snippet \"\nrand_state Build_random_state(N index, list_N list) {\n  rand_state r = {index,list};\n  return r;\n}\n\".\n\nCodeGen Snippet \"#define INDEX(x)        ((x).index)\".\nCodeGen Snippet \"#define STATE_VECTOR(x) ((x).state_vector)\".\n\nCodeGen Inductive Type mt.random_state => \"rand_state\".\nCodeGen Primitive mt.index => \"INDEX\".\nCodeGen Primitive mt.state_vector => \"STATE_VECTOR\".\n\nCodeGen Snippet \"\ntypedef struct {\n  nat fst;\n  rand_state snd;\n} prodNrnd;\n\".\nCodeGen Snippet \"#define make_prodNrnd(x, y) ((prodNrnd){ (x), (y) })\".\n\nCodeGen Inductive Type N * mt.random_state => \"prodNrnd\".\nCodeGen Primitive pair N mt.random_state => \"make_prodNrnd\".\n\nCodeGen Snippet \"\nN nth(N default_value, list_N l, N index) {\n  return l.list[index];\n}\n\".\n\nCodeGen Snippet \"\nlist_N set_nth(N default_value, list_N l, N index, N value) {\n  l.list[index] = value;\n  return l;\n}\n\".\n\nCodeGen Function lower_mask.\nCodeGen Function upper_mask.\nCodeGen Function next_random_state.\nCodeGen Function tempering.\n\nCodeGen Snippet \"\nrand_state initialize_random_state(int s)\n{\n    static list_N mt;\n    int mti;\n    mt.list[0]= s & 0xffffffffUL;\n    for (mti=1; mti<LARGE_NUM; mti++) {\n        mt.list[mti] =\n\t    (1812433253UL * (mt.list[mti-1] ^ (mt.list[mti-1] >> 30)) + mti);\n        mt.list[mti] &= 0xffffffffUL;\n    }\n    return Build_random_state(0, mt);\n}\n\".\n\nCodeGen Snippet \"\nint main(void) {\n  int seed = 20190820;\n  rand_state r = initialize_random_state(seed);\n  int i;\n  for (i = 0; i < 2048; ++i) {\n    prodNrnd p = next_random_state(r);\n    printf(\"\"%d:%u\\n\"\", i, tempering(p.fst));\n    r = p.snd;\n  }\n  return 0;\n}\n\".\n\nCodeGen GenerateFile \"./mt19937_generated.c\".\n", "meta": {"author": "tzskp1", "repo": "codegen-examples", "sha": "5e0eee1a3ee5f27a7f868075cec3def8a2defe04", "save_path": "github-repos/coq/tzskp1-codegen-examples", "path": "github-repos/coq/tzskp1-codegen-examples/codegen-examples-5e0eee1a3ee5f27a7f868075cec3def8a2defe04/mersenne-twister/mt19937.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.658510315267637}}
{"text": "Require Import FMapPositive.\nRequire Import NArith. \nRequire Import ZArith. \n\nRequire Word. \n\n(** Vectors (that is, arrays)  *)\nSection t. \n  Variable length : nat.\n  Variable X  : Type. \n  Definition T := Word.T length ->  X. \n\n  Definition set  (v : T) (j: Word.T length) (x: X) : T :=\n    fun i => if Word.eqb i j then x else v i. \n\n  Definition get (v: T) (i : Word.T length) : X :=\n    v i.\n\n  Lemma gso (v : T)  i j x:\n    Word.eqb i j = false -> \n    get (set v i x) j = get v j.\n  Proof. \n    intros; unfold get, set. simpl. \n    replace (Word.eqb j i) with (Word.eqb i j). rewrite H. auto.\n    rewrite (Bool.eq_iff_eq_true). rewrite ? Word.eqb_correct. intuition.\n  Qed. \n\n  Lemma gss v i j x: \n    Word.eqb i j = true -> \n    get (set v i x) j = x. \n  Proof. \n    unfold get, set. intros. \n    replace (Word.eqb j i) with (Word.eqb i j). rewrite H. auto.\n    rewrite (Bool.eq_iff_eq_true). rewrite ? Word.eqb_correct. intuition.\n  Qed.\nEnd t.\n\nArguments get {length X} _ _. \nArguments set {length X} _ _ _ _. \n             \n    \n\n", "meta": {"author": "braibant", "repo": "Synthesis", "sha": "922982aaddb8a7a16101ff304c45d24a6265dc2e", "save_path": "github-repos/coq/braibant-Synthesis", "path": "github-repos/coq/braibant-Synthesis/Synthesis-922982aaddb8a7a16101ff304c45d24a6265dc2e/src/Vector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6585103141444915}}
{"text": "(* Collect lemmas that are missing from the Coq stdlib and describe the\n   Ensemble-operations as boolean algebra.\n   Associativity, idempotence, commutativity, complements, distributivity, …\n*)\n\nFrom Coq.Sets Require Export Powerset_facts.\nRequire Export EnsemblesImplicit EnsemblesTactics.\n\nLemma Intersection_Full_set\n  {X : Type}\n  {U : Ensemble X} :\n  Intersection Full_set U = U.\nProof.\nnow extensionality_ensembles.\nQed.\n\nLemma Intersection_associative\n  {X : Type}\n  (U V W: Ensemble X) :\n  Intersection (Intersection U V) W = Intersection U (Intersection V W).\nProof.\nnow extensionality_ensembles.\nQed.\n", "meta": {"author": "coq-community", "repo": "zorns-lemma", "sha": "aaf46b0c5f7857ce9211cbaaf36f184ca810e0e8", "save_path": "github-repos/coq/coq-community-zorns-lemma", "path": "github-repos/coq/coq-community-zorns-lemma/zorns-lemma-aaf46b0c5f7857ce9211cbaaf36f184ca810e0e8/Powerset_facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6584138542753445}}
{"text": "Coq < Section Easy007.\n\nCoq < Require Import Classical.\n\nCoq < Variables C D E: Prop.\nC is assumed\nD is assumed\nE is assumed\n\nCoq < Load CpdtTactics.\n\nCoq < Goal ((C -> D) -> (D -> E)) /\\ D -> (C -> E).\n1 subgoal\n  \n  C : Prop\n  D : Prop\n  E : Prop\n  ============================\n   ((C -> D) -> D -> E) /\\ D -> C -> E\n\nUnnamed_thm < crush.\nNo more subgoals.\n\nUnnamed_thm < Qed.\ncrush.\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/cptd/chapt01/007.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6583920410411829}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Max Lia Wellfounded Bool.\n\nFrom Undecidability.Shared.Libs.DLW \n  Require Import Utils.utils.\n\nSet Implicit Arguments.\n\nNotation Zero := false.\nNotation One  := true.\n\nFact list_bool_dec (l m : list bool) : { l = m } + { l <> m }.\nProof. apply list_eq_dec, bool_dec. Qed.\n\n(* {0,1}* = 0*1{0,1}* + 0* *)\n\nFact list_bool_choose lb : { k : _ & { tl | lb = list_repeat Zero k ++ One :: tl } }\n                         + { k            | lb = list_repeat Zero k }.\nProof.\n  induction lb as [ | [] lb IHlb ].\n  * right; exists 0; auto.\n  * left; exists 0, lb; auto.\n  * destruct IHlb as [ (k & lc & H) | (k & H) ].\n    - left; exists (S k), lc; subst; auto.\n    - right; exists (S k); subst; auto.\nQed.\n\n(* {0,1}* = 1*0{0,1}* + 1* *)\n\nFact list_bool_choose_sym lb : { k : _ & { tl | lb = list_repeat One k ++ Zero :: tl } }\n                             + { k            | lb = list_repeat One k }.\nProof.\n  induction lb as [ | [] lb IHlb ].\n  * right; exists 0; auto.\n  * destruct IHlb as [ (k & lc & H) | (k & H) ].\n    - left; exists (S k), lc; subst; auto.\n    - right; exists (S k); subst; auto.\n  * left; exists 0, lb; auto.\nQed.\n\n(* [n1,...,nk] ---> 0...{n1}...01 0{n2}1 ... 0{nk}1 *) \n\nFixpoint list_nat_bool ln :=\n  match ln with\n    | nil   => nil\n    | x::ll => list_repeat Zero x ++ One :: list_nat_bool ll\n  end.\n\nLemma list_bool_decomp k lb : { ln : _ & { lc | lb = list_nat_bool ln ++ lc \n                                             /\\ Exists (fun x => k <= x) ln } }\n                            + { ln : _ & { r  | lb = list_nat_bool ln ++ list_repeat Zero r \n                                             /\\ Forall (fun x => x < k) ln } }.\nProof.\n  induction lb as [ lb IH ] using (measure_rect (@length _)).\n  destruct (list_bool_choose lb) as [ (x & lr & Hlb) | (x & Hlb) ].\n  * destruct (le_lt_dec k x) as [ Hk | Hk ].\n    + left; exists (x::nil), lr; split; simpl.\n      - subst; solve list eq.\n      - constructor 1; auto.\n    + destruct (IH lr) as [ (ln & ld & H2 & H3) | (ln & r & H2 & H3) ].\n      - subst; rew length; lia.\n      - left; exists (x::ln), ld; split.\n        ** subst; solve list eq.\n        ** constructor 2; auto.\n      - right; exists (x::ln), r; split.\n        ** subst; solve list eq.\n        ** constructor; auto.\n  * right; exists nil, x; split.\n     - subst; solve list eq.\n     - constructor.\nQed.\n\nDefinition list_bool_valid   k lb ln := lb = list_nat_bool ln /\\ Forall (fun x => x < k) ln.\nDefinition list_bool_invalid k lb ln := exists lc, lb = list_nat_bool ln ++ lc\n                                            /\\ (   Exists (fun x => k <= x) ln\n                                               \\/  Forall (fun x => x < k) ln \n                                                /\\ exists p, lc = list_repeat Zero (S p)).\n\nFact list_bool_valid_dec k lb : { ln | list_bool_valid k lb ln } + { ln | list_bool_invalid k lb ln }.\nProof.\n  destruct (list_bool_decomp k lb) as [ (ln & lc & H1 & H2) | (ln & [|p] & H1 & H2) ].\n  * right; exists ln, lc; tauto.\n  * left; exists ln; split; auto; subst; solve list eq.\n  * right; exists ln, (list_repeat Zero (S p)); split; auto.\n    right; split; auto; exists p; auto.\nQed.\n\nFixpoint list_bool_nat l :=\n  match l with \n    | nil     => 1\n    | Zero::l => 0 + 2*list_bool_nat l\n    | One::l  => 1 + 2*list_bool_nat l\n  end.\n\nFact list_bool_nat_ge_1 l : 1 <= list_bool_nat l.\nProof. induction l as [ | [] ]; simpl in *; lia. Qed.\n\nUnset Elimination Schemes.\n\nInductive list_bool_succ : list bool -> list bool -> Prop :=\n  | in_lbs_0 : forall k l, list_bool_succ (list_repeat One k ++ Zero :: l) (list_repeat Zero k ++ One :: l)\n  | in_lbs_1 : forall k,   list_bool_succ (list_repeat One k)              (list_repeat Zero (S k)).\n\nSet Elimination Schemes.\n\nSection list_bool_succ_props.\n\n  Fact list_One_Zero_inj a b l m : list_repeat One a ++ Zero :: l = list_repeat One b ++ Zero :: m -> a = b /\\ l = m.\n  Proof.\n    revert b l m; induction a as [ | a IHa ]; intros [ | b ] l m; simpl; try discriminate.\n    inversion 1; auto.\n    intros H.\n    inversion H as [ H1 ].\n    apply IHa in H1.\n    destruct H1; subst; auto.\n  Qed.\n\n  Fact list_One_Zero_not a b l : list_repeat One a ++ Zero :: l <> list_repeat One b.\n  Proof.\n    revert b l; induction a as [ | a IHa ]; intros [ | b ] l; simpl; try discriminate.\n    intros H.\n    inversion H as [ H1 ].\n    apply IHa in H1; auto.\n  Qed.\n\n  Fact list_One_inj a b : list_repeat One a = list_repeat One b -> a = b.\n  Proof.\n    intros H; apply f_equal with (f := @length _) in H; revert H.\n    do 2 rewrite list_repeat_length; auto.\n  Qed.\n\n  Fact list_bool_succ_fun l m1 m2 : list_bool_succ l m1 -> list_bool_succ l m2 -> m1 = m2.\n  Proof.\n    intros H; revert l m1 H m2.\n    intros ? ? [ k l | k ]; inversion 1.\n    apply list_One_Zero_inj in H1; destruct H1; subst k0 l1; auto.\n    symmetry in H1; apply list_One_Zero_not in H1; tauto.\n    apply list_One_Zero_not in H1; tauto.\n    apply list_One_inj in H1; subst; auto.\n  Qed.\n\n  Fact list_bool_succ_nil l : list_bool_succ nil l -> l = Zero::nil.\n  Proof.\n    intros H; symmetry; revert H; apply list_bool_succ_fun.\n    constructor 2 with (k := 0).\n  Qed.\n\n  Fact list_bool_succ_neq : forall l m, list_bool_succ l m -> l <> m.\n  Proof.\n    intros ? ? [ [|k] l | [|k] ]; discriminate.\n  Qed.\n\n  Fact list_bool_succ_neq_nil l : ~ list_bool_succ l nil.\n  Proof.\n    inversion 1.\n    destruct k; discriminate.\n  Qed.\n\nEnd list_bool_succ_props.\n\nSection list_bool_next.\n\n  Let list_bool_next_def l : { m | list_bool_succ l m }.\n  Proof.\n    destruct (list_bool_choose_sym l) as [ (k & tl & H) | (k & H) ]; subst l.\n    * exists (list_repeat Zero k ++ One :: tl); constructor.\n    * exists (list_repeat Zero (S k)); constructor.\n  Qed.\n\n  Definition list_bool_next l := proj1_sig (list_bool_next_def l).\n  Definition list_bool_next_spec l : list_bool_succ l (list_bool_next l). \n  Proof. apply (@proj2_sig _ _). Qed.\n\n  Fact list_bool_next_neq_nil l : list_bool_next l <> nil.\n  Proof.\n    intros H.\n    generalize (list_bool_next_spec l).\n    rewrite H.\n    apply list_bool_succ_neq_nil.\n  Qed.\n\n  Fact iter_list_bool_next_nil l n : iter list_bool_next l n = nil -> n = 0 /\\ l = nil.\n  Proof.\n    destruct n as [ | n ].\n    simpl; auto.\n    replace (S n) with (n+1) by lia.\n    rewrite iter_plus; simpl.\n    intros H.\n    apply list_bool_next_neq_nil in H.\n    destruct H.\n  Qed.\n\nEnd list_bool_next.\n\nFact list_bool_succ_nat l m : list_bool_succ l m -> 1 + list_bool_nat l = list_bool_nat m.\nProof.\n  revert l m; intros ? ? [ k l | k ]; induction k; simpl in *; lia.\nQed.\n \nSection list_bool_succ_rect.\n\n  Variable (P : list bool -> Type)\n           (HP0 : P nil)\n           (HPS : forall l m, list_bool_succ l m -> P l -> P m).\n\n  Let list_bool_succ_rec n : forall l, list_bool_nat l = n -> P l.\n  Proof.\n    induction n as [ | n IHn ]; intros l Hl.\n    * generalize (list_bool_nat_ge_1 l); lia.\n    * destruct (list_bool_choose l) as [ (k & tl & H) | ([ | k] & H) ]; subst l;\n      [ generalize (in_lbs_0 k tl) | apply HP0 | generalize (in_lbs_1 k) ];\n        intros E; apply HPS with (1 := E), IHn;\n        apply list_bool_succ_nat in E; lia.\n  Qed.\n\n  Theorem list_bool_succ_rect : forall l, P l.\n  Proof using HP0 HPS. intro; apply list_bool_succ_rec with (1 := eq_refl). Qed.\n\nEnd list_bool_succ_rect.\n\n\n(* The iteration of list_bool_next from Zero::nil visits every non-empty list of booleans *)\n\nTheorem list_bool_next_total l : l <> nil -> { n | l = iter list_bool_next (Zero::nil) n }.\nProof.\n  induction l as [ | l m Hlm IH ] using list_bool_succ_rect.\n  intros []; auto.\n  intros Hm.\n  destruct (list_bool_choose_sym l) as [ (k & tl & H) | ([|k] & H) ].\n  * destruct IH as (n & Hn).\n    { subst; destruct k; discriminate. }\n    exists (n+1); rewrite iter_plus; simpl.\n    rewrite <- Hn.\n    generalize (list_bool_next_spec l).\n    apply list_bool_succ_fun; auto.\n  * exists 0; simpl.\n    apply list_bool_succ_fun with (1 := Hlm).\n    subst; simpl; constructor 2 with (k := 0).\n  * destruct IH as (n & Hn).\n    { subst; simpl; discriminate. }\n    exists (n+1); rewrite iter_plus; simpl.\n    rewrite <- Hn.\n    generalize (list_bool_next_spec l).\n    apply list_bool_succ_fun; auto.\nQed.\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/list_bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6583920255982022}}
{"text": "Require Import Coq.Logic.ProofIrrelevance.\n\nLemma sig_equivalence :\n  forall (A : Type) (P : A -> Prop) (n m : A) (n_pf : P n) (m_pf : P m),\n    n = m -> exist P n n_pf = exist P m m_pf.\nProof.\n  intros A P n m n_pf m_pf nm_pf.\n  subst.\n  pose proof (proof_irrelevance _ n_pf m_pf).\n  subst. reflexivity.\nQed.", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/BinEncoders/NoEnv/Libraries/Sig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6583735614583812}}
{"text": "(** * Synthesis.Core : Defining the memory model underlying the compiler*)\nRequire Import Common. \nRequire Import DList. \nRequire Word Vector. \n\n\nUnset Elimination Schemes. \n\n(** Definition of types *)\n\nInductive type : Type :=\n| Tunit : type \n| Tbool: type \n| Tint: forall (n : nat), type\n| Ttuple : forall l : list type,  type. \n\n(** Notations used in the paper  *)\nNotation Unit := Tunit.         \nNotation B  := Tbool. \nNotation Int n := (Tint n).\nNotation Tuple l := (Ttuple l). \n\nSection type_ind. \n  Variable P : type -> Prop. \n  Variable Hunit : P Tunit. \n  Variable Hbool : P Tbool. \n  Variable Hint  : forall n, P (Tint n).\n  Variable Hnil  : P (Ttuple []). \n  Variable Hcons  : forall t q, P t -> P (Ttuple q) -> P (Ttuple (t :: q)). \n\n  Definition type_ind (t : type) : P t. \n  refine (let ind := fix ind t : P t :=\n              match t with\n                | Tunit => Hunit\n                | Tbool => Hbool\n                | Tint n => Hint n\n                | Ttuple l => \n                    let fix fold l : P (Ttuple l) :=\n                        match l with \n                          | nil => Hnil\n                          | cons t q => Hcons t q (ind t) (fold q)\n                        end in \n                      fold l\n              end \n          in ind t). \n  Defined. \nEnd type_ind. \nSet Elimination Schemes. \n\nFixpoint eval_type st : Type := \n  match st with \n    | Tunit => unit\n    | Tbool => bool\n    | Tint n => Word.T n\n    | Ttuple l => Tuple.of_list eval_type l\n  end.    \n\nDefinition eval_type_list l : Type := Tuple.of_list eval_type l. \n\nRequire Import NPeano. \n\nDefinition type_eqb : forall a b : type, bool.  \nrefine (let fix fold a b {struct a}: bool :=\n            let fix pointwise   (i j : list type) : bool :=\n                match i, j with \n                  | [] , [] => true\n                  | t::q , t' :: q' => (fold t t' && pointwise q q')%bool\n                  | _, _ => false\n                end%list in \n              match a,b with\n                | Tunit, Tunit => true\n                | Tbool, Tbool => true\n                | Tint n,  Tint m => Nat.eqb n m \n                | Ttuple x, Ttuple y => pointwise x y\n                | _ , _ => false\n              end in fold      \n       ). \nDefined. \n\n\nFixpoint type_list_eqb (la lb : list type) : bool :=\n  match la,lb with \n    | [], [] => true\n    | t :: q , t' :: q' => (type_eqb t t' && type_list_eqb q q' )%bool\n    | _ , _ => false\n  end%list. \n\n\nLemma nat_eqb_eq : forall x y, Nat.eqb x y = true -> x = y. \nProof. \n  induction x; destruct y; try reflexivity || simpl; try congruence.\n  auto. \nDefined. \n\nLemma type_eqb_correct a b : type_eqb a b = true -> a = b. \nProof. \n  revert b. \n  induction a; induction b; try simpl; try (reflexivity || congruence). \n  intros. apply nat_eqb_eq in H. subst. reflexivity. \n  case_eq (type_eqb a b); simpl; intros. \n  apply IHa in H. subst. repeat f_equal. specialize (IHa0 (Ttuple q0) H0). congruence. \n  discriminate. \nDefined. \n\nLemma type_list_eqb_correct la lb : type_list_eqb la lb = true -> la = lb. \nProof. \n    revert lb; induction la; destruct lb; simpl; try discriminate; intuition.\n     rewrite Bool.andb_true_iff in H. destruct H. rewrite (IHla lb); auto. \n     rewrite (type_eqb_correct a t H). reflexivity. \nQed. \n\nLemma type_eqb_refl : forall t, type_eqb t t = true.\nProof.  \n  induction t using type_ind; simpl;  firstorder. \n  apply NPeano.Nat.eqb_eq. reflexivity. \nQed. \n \n(** Operations on types *)\nSection type_ops. \n  \n  Definition eqb_bool (b1 b2: bool)  :=\n    match b1,b2 with \n      | true, true => true\n      | false, false => true\n      | _,_ => false\n    end. \n  \n  Fixpoint type_eq (t : type) : eval_type t -> eval_type t -> bool :=\n    match t with \n      | Tunit => fun _ _  => true\n      | Tint n => @Word.eqb n\n      | Tbool  => eqb_bool \n      | Ttuple l => fun _ _ => false\n    end. \n  \n  Lemma type_eq_correct t x y : type_eq t x y = true -> x = y.\n  Proof. destruct t; simpl in *.\n    destruct x; destruct y; auto. \n    destruct x; destruct y; auto. \n    intros. apply Word.eqb_correct; auto.  \n    discriminate. \n  Qed. \nEnd type_ops. \n\n\nModule Generics.  \n  Record signature T (E : T -> Type) := mk_signature\n                                         {\n                                           args : list T;\n                                           res : T; \n                                           value :> Tuple.of_list E args -> E res\n  }. \n  \n  Arguments mk_signature {T E} args res value. \n  Arguments args {T E} s. \n  Arguments res {T E} s. \n  Arguments value {T E} s _. \n  \n  (* could it be a primitive with an empty set of arguments ? *)\n  Definition constant T (E : T -> Type) (ty : T) := E ty. \n  Arguments constant {T E} ty. \nEnd Generics. \n\nNotation signature := (Generics.signature type eval_type). \nNotation constant := (@Generics.constant type eval_type). \n\nDefinition Cbool b : constant Tbool := b. \nDefinition Cword {n} x : constant (Tint n) := (Word.repr _ x). \n\n(** The definition of state elements. *)\nInductive mem : Type :=\n  | Tinput: forall (t: type), mem\n  | Treg : forall (t : type), mem\n  | Tregfile : forall (n : nat) (t : type), mem. \n\nNotation Input := Tinput.\nNotation Reg   := Treg.\nNotation Regfile   := Tregfile.\n\n\nDefinition state := list mem. \n\nDefinition eval_mem (s : mem) := \n  match s with\n    | Tinput t => eval_type t\n    | Treg t => eval_type t \n    | Tregfile n t => Regfile.T n (eval_type t) \n  end. \n\nNotation eval_state := (DList.T eval_mem). \n", "meta": {"author": "braibant", "repo": "Synthesis", "sha": "922982aaddb8a7a16101ff304c45d24a6265dc2e", "save_path": "github-repos/coq/braibant-Synthesis", "path": "github-repos/coq/braibant-Synthesis/Synthesis-922982aaddb8a7a16101ff304c45d24a6265dc2e/src/Core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6583735540917434}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_collinear4.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_collinearparallel : \n   forall A B C c d, \n   Par A B c d -> Col c d C -> neq C d ->\n   Par A B C d.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists R a b p q, (neq A B /\\ neq c d /\\ Col A B a /\\ Col A B b /\\ neq a b /\\ Col c d p /\\ Col c d q /\\ neq p q /\\ ~ Meet A B c d /\\ BetS a R q /\\ BetS p R b)) by (conclude_def Par );destruct Tf as [R[a[b[p[q]]]]];spliter.\nassert (neq d C) by (conclude lemma_inequalitysymmetric).\nassert (Col d C p) by (conclude lemma_collinear4).\nassert (Col C d p) by (forward_using lemma_collinearorder).\nassert (Col d C q) by (conclude lemma_collinear4).\nassert (Col C d q) by (forward_using lemma_collinearorder).\nassert (~ Meet A B C d).\n {\n intro.\n let Tf:=fresh in\n assert (Tf:exists E, (neq A B /\\ neq C d /\\ Col A B E /\\ Col C d E)) by (conclude_def Meet );destruct Tf as [E];spliter.\n assert (Col C d c) by (forward_using lemma_collinearorder).\n assert (Col d E c) by (conclude lemma_collinear4).\n assert (Col c d E) by (forward_using lemma_collinearorder).\n assert (Meet A B c d) by (conclude_def Meet ).\n contradict.\n }\nassert (Par A B C d) by (conclude_def Par ).\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_collinearparallel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6583735423314967}}
{"text": "Require Import Setoid.\nRequire Import Coq.Lists.List.\nRequire Import Bool.\nRequire Import Coq.Program.Equality.\nImport ListNotations.\nImport PeanoNat.Nat.\n\nPrint In.\nPrint reflect.\n\nInductive Deduplicated {A: Type} : list A -> Prop :=\n| DedupNil  : Deduplicated []\n| DedupCons : forall (x: A) (l: list A), ~ In x l -> Deduplicated l -> Deduplicated (x::l).\n\nFixpoint any {A: Type} (p : A -> bool) (l: list A) : bool :=\n  match l with\n  | [] => false\n  | (x::l') => if p x then true else any p l'\n  end.\n\nDefinition Elem_eq {A: Type} (l l' : list A) : Prop := \n  forall p : A -> bool, any p l = any p l'.\n\nDefinition Same_elements {A: Type} (l l' : list A) : Prop := \n  forall x : A, In x l <-> In x l'.\n\nClass EqDec (A : Type) := { \n  eqf : A -> A -> bool ;\n  eqf_leibniz : forall x y: A, reflect (x = y) (eqf x y)\n}.\n\nPrint Bool.\n\nLemma eqf_refl : forall {A: Type} `{EqDec A}, forall x: A, eqf x x = true.\nProof.\n  intros A eq_dec x. destruct (eqf_leibniz x x).\n  - reflexivity.\n  - exfalso. apply n. reflexivity.\nQed.\n\nLemma eqf_iff : forall {A: Type} `{EqDec A}, forall x y: A, x = y <-> eqf x y = true.\nProof.\n  intros A eq_dec x y. apply reflect_iff. apply eqf_leibniz.\nQed.\n\nLemma not_eqf_iff : forall {A: Type} `{EqDec A}, forall x y: A, x <> y <-> eqf x y = false.\nProof.\n  intros A eq_dec x y. case_eq (eqf x y).\n  - intro e. destruct (eqf_leibniz x y).\n    + split; intro H; try inversion H; try contradiction.\n    + inversion e.\n  - intro e. destruct (eqf_leibniz x y).\n    + inversion e.\n    + split; intro H; assumption. \nQed.\n\nTheorem any_in_eq_dec : forall (A: Type) `{EqDec A}, forall l: list A, forall x: A,\n  reflect (In x l) (any (eqf x) l).\nProof.\n  intros A eq_dec l x. case_eq (any (eqf x) l).\n  - intro H. constructor. induction l.\n    + cbn in *. inversion H.\n    + destruct (eqf_leibniz x a).\n      * cbn. left. symmetry. assumption.\n      * cbn in *. right. apply IHl. rewrite (not_eqf_iff x a) in n.\n        rewrite n in H. assumption.\n  - intro H. constructor. induction l.\n    + cbn. auto.\n    + intro H0. cbn in *. destruct H0.\n      * destruct H0. rewrite (eqf_refl a) in H. inversion H.\n      * case_eq (eqf x a); intro H1.\n        -- rewrite H1 in H. inversion H.\n        -- rewrite H1 in H. apply IHl; assumption.\nQed.\n\nTheorem any_in_eq_dec_iff : forall (A: Type) `{EqDec A}, forall (l: list A) (x: A),\n  (In x l <-> any (eqf x) l = true).\nProof.\n  intros A eq_dec l x. apply reflect_iff. apply any_in_eq_dec.\nQed.\n\nLemma in_any_true : forall (A: Type) (l: list A) (x: A) (p : A -> bool), \n  p x = true -> In x l -> any p l = true.\nProof.\n  intros A l x p H I. induction l.\n  - cbn in I. auto.\n  - cbn in *. destruct I. \n    + subst. rewrite H. reflexivity.\n    + destruct (p a) eqn:H1.\n      * reflexivity.\n      * apply IHl. assumption.\nQed.\n\nLemma exist_in_any : forall (A: Type) (l: list A) (p : A -> bool), \n  any p l = true -> exists x: A, p x = true /\\ In x l.\nProof.\n  intros A l p H. induction l.\n  - cbn in H. inversion H.\n  - cbn in *. destruct (p a) eqn:H0.\n    + exists a. split; try assumption. left. reflexivity.\n    + assert (exists x : A, p x = true /\\ In x l) by (apply IHl; apply H).\n      destruct H1. exists x. destruct H1. split; try assumption. right. assumption.\nQed. \n\nLemma forall_in_any : forall (A: Type) (l: list A) (p : A -> bool), \n  any p l = false -> forall x: A, In x l -> p x = false.\nProof.\n  intros A l. induction l.\n  - cbn in *. intros _ _ x [].\n  - intros p H x I. cbn in *. destruct (p a) eqn:H0.\n    + inversion H.\n    + destruct I.\n      * subst. assumption.\n      * apply IHl; assumption.\nQed. \n\nTheorem elem_eq_for_eq_dec : forall (A: Type), EqDec A -> forall x y: list A, \n  (Elem_eq x y <-> Same_elements x y).\nProof.\n  unfold Elem_eq, Same_elements. intros A eq_dec l l'. split.\n  - intros H x. specialize (H (eqf x)). rewrite any_in_eq_dec_iff, any_in_eq_dec_iff, H. \n    split; intro H0; apply H0.\n  - intros H p. destruct (any p l) eqn:e1; destruct (any p l') eqn:e2; trivial.\n    + assert (exists x: A, p x = true /\\ In x l) by (apply exist_in_any; assumption).\n      assert (forall x: A, In x l' -> p x = false) by (apply forall_in_any; assumption).\n      destruct H0. rewrite H in H0. destruct H0. rewrite <- H0. apply H1. assumption. \n    + assert (exists x: A, p x = true /\\ In x l') by (apply exist_in_any; assumption).\n      assert (forall x: A, In x l -> p x = false) by (apply forall_in_any; assumption).\n      destruct H0. rewrite <- H in H0. destruct H0. rewrite <- H0. symmetry. apply H1. assumption.\nQed. \n\nInductive tree (A: Type) : Type :=\n| leaf : tree A\n| node : A -> tree A -> tree A -> tree A.\n\nArguments leaf {A}.\nArguments node {A} _ _ _.\n\nClass LinearOrder {A: Type} := {\n  ord      : A -> A -> bool;\n  refl     : forall x: A, ord x x = true;\n  anti_sym : forall x y: A, ord x y = true -> ord y x = true -> x = y;\n  trans    : forall x y z: A, ord x y = true -> ord y z = true -> ord x z = true;\n  full     : forall x y, ord x y = true \\/ ord y x = true;\n}.\n\nDefinition comp {A: Type} `{LinearOrder A} (x y: A) := \n  if ord x y then (if ord y x then Eq else Gt) else Lt.\n\nDefinition treeComp {A: Type} `{LinearOrder A} (x: A) (t: tree A) :=\nmatch t with\n| leaf => None\n| node y _ _ =>  Some (comp x y)\nend.\n\nFixpoint add_tree {A: Type} `{LinearOrder A} (x: A) (t : tree A) : tree A :=\nmatch t with\n| leaf => node x leaf leaf\n| node v l r => match comp x v with\n                | Lt => node v (add_tree x l) r\n                | Eq => node v l r\n                | Gt => node v l (add_tree x r)\n                end\nend.\n\nFixpoint to_tree {A: Type} `{LinearOrder A} (l : list A) : tree A := \n  match l with\n  | []      => leaf\n  | (x::l') => add_tree x (to_tree l')\n  end.\n\nFixpoint to_list {A: Type} (l : tree A) : list A := \n  match l with\n  | leaf       => []\n  | node x l r => to_list l ++ [x] ++ to_list r\n  end.\n\nFixpoint TCount {A: Type}(p: A -> bool)(t: tree A) : nat :=\n  match t with\n  | leaf => 0\n  | node x l r => if (p x) then S (TCount p l + TCount p r) else TCount p l + TCount p r\n  end.\n\nFixpoint TAny {A: Type}(p: A -> bool)(t: tree A) : bool :=\n  match t with\n  | leaf => false\n  | node x l r => p x || TAny p l || TAny p r\n  end.\n\nFixpoint count {A: Type} (p: A -> bool) (l: list A): nat :=\n  match l with\n  | nil => O\n  | cons h t => if p h then S (count p t) else count p t\n  end.\n\nDefinition permutation {A: Type} (a b : list A) :=\n  forall p : A -> bool, count p a = count p b.\n\nDefinition TListPermutation{A: Type}(t: tree A)(l: list A) : Prop :=\n  forall p: A->bool, TCount p t = count p l.\n\nDefinition TPermutation{A: Type}(t1 t2: tree A) : Prop :=\n  forall p: A->bool, TCount p t1 = TCount p t2.\n\nDefinition TElem_eq (A: Type) (l l' : tree A) : Prop := \n  forall p : A -> bool, TAny p l = TAny p l'.\n\nDefinition TListElem_eq {A: Type} (t: tree A) (l: list A) : Prop :=\n  forall p : A -> bool, TAny p t = any p l.\n\nDefinition DSort {A: Type} `{LinearOrder A} (l : list A) : list A := to_list (to_tree l).\n\nLemma count_list_concat {A: Type} (l l': list A): \n  forall p: A-> bool, count p (l ++ l') = count p l + count p l'.\nProof.\n  intros p. revert l'. induction l; intros l'.\n  - cbn. reflexivity.\n  - cbn. destruct (p a).\n    + rewrite IHl. cbn. reflexivity.\n    + apply IHl.\nQed.\n \nLemma to_list_perm {A: Type} (t: tree A) : TListPermutation t (to_list t).\nProof.\n  intros p. induction t.\n  - cbn. reflexivity.\n  - cbn. rewrite count_list_concat. cbn. destruct (p a).\n    + rewrite plus_n_Sm, IHt1, IHt2. reflexivity.\n    + rewrite IHt1, IHt2. reflexivity.\nQed.\n\nLemma count_TCount {A: Type} (t: tree A) : forall p: A-> bool,\n  TCount p t = count p (to_list t).\nProof.\n  apply to_list_perm.\nQed.\n\nFixpoint TIn {A: Type} (x: A) (t: tree A) : Prop :=\nmatch t with \n| leaf => False\n| node v l r => v = x \\/ TIn x l \\/ TIn x r\nend.\n\nInductive normal_tree {A: Type} `{LinearOrder A} : tree A -> Prop :=\n| NormLeaf : normal_tree leaf\n| NormNode : forall (x: A) (l r: tree A), normal_tree l -> normal_tree r ->\n  (forall y: A, TIn y l -> comp y x = Lt) -> (forall y: A, TIn y r -> comp y x = Gt) ->\n  normal_tree (node x l r).\n\nDefinition TDeduplicated {A: Type} `{EqDec A} (t: tree A) : Prop := \n  forall x : A, TIn x t -> TCount (eqf x) t = 1.\n\nDefinition LDeduplicated {A: Type} `{EqDec A} (t: list A) : Prop := \n  forall x : A, In x t -> count (eqf x) t = 1.\n\nGlobal Instance lo_eq_dec {A: Type} `{LinearOrder A} : EqDec A.\nProof.\n  exists (fun x y => if ord x y then (if ord y x then true else false) else false).\n  intros x y. destruct (ord x y) eqn:e1; destruct (ord y x) eqn:e2.\n  - constructor. apply  anti_sym; assumption.\n  - constructor. intro H0. subst. rewrite e2 in e1. inversion e1. \n  - constructor. intro H0. subst. rewrite e1 in e2. inversion e2.\n  - constructor. intro H0. subst. assert (ord y y = true) by apply refl. rewrite e1 in H0. inversion H0.\nQed.\n\nLemma in_to_list {A: Type} (x: A) (t: tree A) : In x (to_list t) <-> TIn x t.\nProof.\n  split.\n  - induction t.\n    + cbn. auto.\n    + cbn. intro H. rewrite in_app_iff in H. cbn in *. destruct H; try destruct H.\n      * right. left. apply IHt1. assumption.\n      * left. assumption.\n      * right. right. apply IHt2. assumption.\n  - induction t.\n    + cbn. auto.\n    + cbn. intro H. rewrite in_app_iff. cbn. destruct H; cycle 1. destruct H.\n      * left. apply IHt1. assumption.\n      * right. right. apply IHt2. assumption.\n      * right. left. assumption.\nQed.\n\nLemma not_full {A: Type} `{LinearOrder A} (x y: A) : ~ (ord x y = false /\\ ord y x = false).\nProof.\n  intros (a & b). destruct (full x y).\n  - rewrite H0 in a. discriminate.\n  - rewrite H0 in b. discriminate.\nQed.\n\nLemma comp_eq {A: Type} `{LinearOrder A} (x y: A) : comp x y = Eq <-> x = y.\nProof.\n  split.\n  - unfold comp. intro C. destruct (ord x y) eqn:e1; destruct (ord y x) eqn:e2; try inversion C.\n  apply anti_sym; assumption.\n  - intros []. unfold comp. rewrite refl. auto.\nQed.\n\nLemma comp_lt {A: Type} `{LinearOrder A} (x y: A) : \n  comp x y = Lt <-> ord x y = false /\\ ord y x = true.\nProof.\n  unfold comp. split.\n  - intro C. destruct (ord x y) eqn:e1; destruct (ord y x) eqn:e2; try inversion C; auto.\n    exfalso. apply (not_full x y); split; assumption.\n  - intros (e1 & e2). rewrite e1. auto.\nQed.\n\nLemma comp_gt {A: Type} `{LinearOrder A} (x y: A) : \n  comp x y = Gt <-> ord x y = true /\\ ord y x = false.\nProof.\n  unfold comp. split.\n  - intro C. destruct (ord x y) eqn:e1; destruct (ord y x) eqn:e2; try inversion C; auto.\n  - intros (e1 & e2). rewrite e1. rewrite e2. auto.\nQed.\n\nLemma ord_false_true {A: Type} `{LinearOrder A} (x y z: A) : \n  ord x y = false -> ord y x = true.\nProof.\n  intros. destruct (full x y).\n  - rewrite H0 in H1. discriminate.\n  - assumption.\nQed.\n\nLemma lo_false_trans {A: Type} `{LinearOrder A} (x y z: A) : \n  ord y x = false -> ord z y = false -> ord z x = false.\nProof. \n  intros H1 H2.\n  destruct (ord x z) eqn:H3.\n  - assert (x <> z).\n    + intro. subst. exfalso. apply (not_full y z); split; assumption.\n    + destruct (ord z x) eqn:H4.\n      * destruct (anti_sym x z H3 H4). exfalso. apply H0. auto.\n      * reflexivity.\n  - assert (ord x z = true).\n    + apply (trans x y z); apply ord_false_true; assumption.\n    + rewrite H0 in H3. discriminate.\nQed.\n\nLemma comp_trans {A: Type} `{LinearOrder A} (x y z: A) (c: comparison) :\n  comp x y = c -> comp y z = c -> comp x z = c.\nProof.\n  destruct c.\n  - rewrite (comp_eq x y), (comp_eq y z), (comp_eq x z). intros. subst. auto.\n  - rewrite (comp_lt x y), (comp_lt y z), (comp_lt x z). \n    intros (f1 & t1) (f2 & t2). split.\n    + apply (lo_false_trans z y x); assumption.\n    + apply (trans z y x); assumption.\n  - rewrite (comp_gt x y), (comp_gt y z), (comp_gt x z).\n    intros (t1 & f1) (t2 & f2). split.\n    + apply (trans x y z); assumption.\n    + apply (lo_false_trans x y z); assumption.\nQed.\n\nDefinition comp_inv (c: comparison) :=\nmatch c with \n| Lt => Gt\n| Eq => Eq\n| Gt => Lt\nend.\n\nLemma comp_inv_def {A: Type} `{LinearOrder A} (x y: A):\n  comp y x = comp_inv (comp x y).\nProof.\n  unfold comp. destruct (ord x y) eqn:e1; destruct (ord y x) eqn:e2; cbn; auto.\n  exfalso. apply (not_full x y); split; assumption.\nQed.\n\nLemma comp_inv_iff {A: Type} `{LinearOrder A} (x y: A) (c: comparison):\n  comp y x = c <-> comp x y = comp_inv c.\nProof.\n  rewrite comp_inv_def. split; intro O; destruct c; destruct (comp x y); cbn in *; auto; inversion O.\nQed.\n\nLemma add_dont_remove {A: Type} `{LinearOrder A} (t : tree A) : \n  forall v: A, TIn v t -> forall n: A, TIn v (add_tree n t).\nProof.\n  intros v I n. induction t.\n  - cbn in *. destruct I.\n  - cbn in *. destruct (comp n a) eqn:c.\n    + apply I.\n    + cbn. destruct I as [e|[l | r]]; subst; auto.\n    + cbn. destruct I as [e|[l | r]]; subst; auto.\nQed.\n\nLemma TIn_add {A: Type} `{LinearOrder A} (n: A) (t : tree A) : \n  forall v: A, TIn v (add_tree n t) <-> n = v \\/ TIn v t.\nProof.\n  intros v. split.\n  - intros I. induction t.\n    + left. cbn in *. destruct I; auto; try destruct H0; try destruct H0.\n    + cbn in *. destruct (comp n a) eqn:c.\n      * rewrite comp_eq in c. subst. cbn in *. destruct I as [e|[l|r]]; subst; auto.\n      * cbn in *. destruct I as [e|[l|r]]; subst; auto. specialize (IHt1 l). destruct IHt1; auto.\n      * cbn in *. destruct I as [e|[l|r]]; subst; auto. specialize (IHt2 r). destruct IHt2; auto.\n  - intros [e | I].\n    + induction t.\n      * cbn. auto.\n      * cbn. destruct (comp n a) eqn:c; cbn; auto. rewrite comp_eq in c. subst. auto.\n    + apply add_dont_remove. assumption.\nQed.\n\nTheorem add_preserves_normal {A: Type} `{LinearOrder A} (n: A) (t : tree A) : \n  normal_tree t -> normal_tree (add_tree n t).\nProof.\n  intro N. induction N.\n  - cbn. constructor; try constructor; intros y I; cbn in *; try inversion I.\n  - cbn in *. destruct (comp n x) eqn:c.\n    + constructor; assumption.\n    + constructor; auto. intros y I. rewrite TIn_add in I. destruct I; subst; auto.\n    + constructor; auto. intros y I. rewrite TIn_add in I. destruct I; subst; auto.\nQed.\n\nLemma TCount_for_not_satisfied_pred {A: Type} (t : tree A) (p: A -> bool): \n  (forall x:A, TIn x t -> p x = false) -> TCount p t = 0.\nProof.\n  intros N. induction t.\n  - auto.\n  - cbn in *. rewrite (N a); auto. rewrite IHt1, IHt2; auto.\nQed.\n\nLemma eqf_comp_not_eq {A: Type} `{LinearOrder A} (x y: A) : comp x y <> Eq <-> eqf x y = false.\nProof.\n  rewrite comp_eq. rewrite not_eqf_iff. split; auto.\nQed. \n\nLemma eqf_lt{A: Type} `{LinearOrder A} (x y: A) : comp x y = Lt -> eqf x y = false.\nProof.\n  intro C. rewrite <-eqf_comp_not_eq. intros C'. rewrite C in C'. inversion C'.\nQed.\n\nLemma eqf_gt{A: Type} `{LinearOrder A} (x y: A) : comp x y = Gt -> eqf x y = false.\nProof.\n  intro C. rewrite <-eqf_comp_not_eq. intros C'. rewrite C in C'. inversion C'.\nQed.\n\nTheorem normal_is_depup {A: Type} `{LinearOrder A} (t: tree A) : \n  normal_tree t -> TDeduplicated t.\nProof.\n  intro N. induction N.\n  - intros x I. cbn in I. destruct I.\n  - intros y I. cbn in I. destruct I as [e|[I|I]].\n    + subst. cbn in *. rewrite eqf_refl. rewrite TCount_for_not_satisfied_pred, TCount_for_not_satisfied_pred; auto.\n      * intros x I. rewrite <-eqf_comp_not_eq. specialize (H1 x I). rewrite comp_inv_iff. cbn. rewrite H1. intros [=].\n      * intros x I. rewrite <-eqf_comp_not_eq. specialize (H0 x I). rewrite comp_inv_iff. cbn. rewrite H0. intros [=].\n    + destruct (comp y x) eqn:c.\n      * specialize (H0 y I). rewrite H0 in c. inversion c.\n      * cbn. rewrite eqf_lt; auto. rewrite IHN1; auto. rewrite TCount_for_not_satisfied_pred; auto.\n        intros z I'. rewrite <-eqf_comp_not_eq. rewrite comp_eq. specialize (H1 z I'). intros c'.\n        subst. rewrite c in H1. discriminate.\n      * cbn. rewrite eqf_lt; auto. rewrite IHN1; auto. rewrite TCount_for_not_satisfied_pred; auto.\n        intros z I'. rewrite <-eqf_comp_not_eq. rewrite comp_eq. specialize (H1 z I'). specialize (H0 y I).\n        intros e. subst. rewrite H1 in H0. discriminate.\n    + destruct (comp y x) eqn:c.\n      * specialize (H1 y I). rewrite H1 in c. inversion c.\n      * cbn. rewrite eqf_lt; auto. rewrite IHN2; auto. rewrite TCount_for_not_satisfied_pred; auto.\n        intros z I'. rewrite <-eqf_comp_not_eq. rewrite comp_eq. intro e; subst. specialize (H0 z I').\n        specialize (H1 z I). rewrite H0 in H1. discriminate.\n      * cbn. rewrite eqf_gt; auto. rewrite IHN2; auto. rewrite TCount_for_not_satisfied_pred; auto.\n        intros z I'. rewrite <-eqf_comp_not_eq. rewrite comp_eq. intro e; subst. specialize (H0 z I'). \n        rewrite c in H0. discriminate.\nQed.\n\nTheorem to_tree_normal {A: Type} `{LinearOrder A} (l: list A) : normal_tree (to_tree l).\nProof.\n  induction l.\n  - cbn in *. constructor.\n  - cbn in *. apply add_preserves_normal. assumption.\nQed.\n\nTheorem to_tree_dedup {A: Type} `{LinearOrder A} (l: list A) : TDeduplicated (to_tree l).\nProof.\n  apply normal_is_depup. apply to_tree_normal.\nQed.\n\nTheorem dedup_DSort {A: Type} `{LinearOrder A} (l : list A) : LDeduplicated (DSort l).\nProof.\n  intros x I. unfold DSort in *. rewrite <- count_TCount. rewrite in_to_list in I.\n  apply to_tree_dedup. assumption.\nQed.\n\n\n\n\n\n\n(* Sorted *)\n\nInductive Sorted {A: Type} `{LinearOrder A} : list A -> Prop :=\n  | SortedNil : Sorted []\n  | SortedSing : forall h: A, Sorted [h]\n  | SortedCons : forall h h' : A, forall t: list A,\n      Sorted (h' :: t) -> ord h' h = true -> Sorted (h :: h' :: t).\n\nLemma sorted_without_head {A: Type} `{LinearOrder A} (a: A) (l: list A) :\n  Sorted (a::l) -> Sorted l.\nProof.\n  induction l; intro h.\n  - constructor.\n  - dependent destruction h. assumption.\nQed. \n\nLemma concat_sorted {A: Type} `{LinearOrder A} (h: A) (l l': list A) : Sorted l -> Sorted (h::l') -> \n  (forall x: A, In x l -> ord h x = true) -> Sorted (l ++ (h::l')).\nProof.\n  intros s1 s2 N. induction l.\n  - cbn. assumption.\n  - destruct l.\n    + cbn. constructor; auto. apply (N a). cbn. auto.\n    + cbn in *. constructor.\n      * apply IHl.\n        -- apply (sorted_without_head a). assumption.\n        -- intros x I. apply N. auto.\n      * dependent destruction s1. assumption.\nQed. \n\nLemma head_sorted {A: Type} `{LinearOrder A} (h: A) (l: list A) : Sorted l -> \n  (forall x: A, In x l -> ord x h = true) -> Sorted (h::l).\nProof.\n  intros s N. induction l.\n  - constructor.\n  - constructor; auto. apply N. cbn. auto.\nQed. \n\nLemma ord_comp_lt {A: Type} `{LinearOrder A} (h: A) (l: list A) : \n  (forall x: A, In x l -> comp x h = Lt) -> (forall x: A, In x l -> ord h x = true).\nProof.\n  unfold comp. intros R x I. specialize (R x I). destruct (ord h x) eqn:e1; destruct (ord x h) eqn:e2; auto.\n  - inversion R.\n  - destruct (full h x).\n    + rewrite H0 in e1. discriminate.\n    + rewrite H0 in e2. discriminate.\nQed.\n\nLemma ord_comp_gt {A: Type} `{LinearOrder A} (h: A) (l: list A) : \n  (forall x: A, In x l -> comp x h = Gt) -> (forall x: A, In x l -> ord x h = true).\nProof.\n  unfold comp. intros R x I. specialize (R x I). destruct (ord h x) eqn:e1; destruct (ord x h) eqn:e2; auto.\n  - inversion R.\n  - destruct (full h x).\n    + rewrite H0 in e1. discriminate.\n    + rewrite H0 in e2. discriminate.\nQed.\n\nTheorem normal_to_list_sorted {A: Type} `{LinearOrder A} (t: tree A) : normal_tree t -> Sorted (to_list t).\nProof.\n  intros N. induction N.\n  - cbn. constructor.\n  - cbn. apply concat_sorted; auto.\n    + apply head_sorted; auto. apply ord_comp_gt. intros z I. rewrite in_to_list in I. apply (H1 z I).\n    + apply ord_comp_lt. intros z I. rewrite in_to_list in I. apply (H0 z I).\nQed.\n\nTheorem sorted_DSort {A: Type} `{LinearOrder A} (l : list A) : Sorted (DSort l).\nProof.\n  apply normal_to_list_sorted. apply to_tree_normal.\nQed.\n\n\n\n\n\n\n\n\n\n\n(* Preserves elems *)\n\nLemma any_concat {A: Type} (l l': list A) (p: A -> bool): any p (l ++ l') = any p l || any p l'.\nProof.\n  induction l; auto. cbn. destruct (p a); auto.\nQed.\n\nLemma to_list_any {A: Type} (t: tree A) : TListElem_eq t (to_list t).\nProof.\n  intros p. induction t.\n  - cbn. reflexivity.\n  - cbn. rewrite any_concat. cbn. destruct (p a); cbn; auto.\n    + rewrite orb_comm. auto.\n    + rewrite IHt1, IHt2. reflexivity.\nQed.\n\nLemma add_tree_any {A: Type} `{LinearOrder A} (x: A) (t: tree A) (p: A->bool):\n  TAny p (add_tree x t) = (if p x then true else TAny p t).\nProof.\n  induction t.\n  - cbn. destruct (p x); auto.\n  - cbn. destruct (comp x a) eqn:e; cbn.\n    + rewrite comp_eq in e. subst. destruct (p a) eqn:p_a; auto.\n    + rewrite IHt1. destruct (p a); destruct (p x); auto.\n    + rewrite IHt2. destruct (p a); destruct (p x); auto. rewrite orb_false_l, orb_comm. auto.\nQed.\n\nLemma to_tree_any {A: Type} `{LinearOrder A} (l: list A) : TListElem_eq (to_tree l) l.\nProof.\n  intros p. induction l.\n  - cbn. reflexivity.\n  - cbn. rewrite add_tree_any, IHl. auto.\nQed.\n\nTheorem same_elements_DSort {A: Type} `{LinearOrder A} (l : list A) : Elem_eq l (DSort l).\nProof.\n  unfold DSort. intros p. rewrite <-to_list_any. symmetry. apply to_tree_any.\nQed.\n\n\n\n\n(* Uniquness *) \n\nLemma count_for_not_satisfied_pred {A: Type} (l: list A) (p: A->bool) :\n  (forall x : A, In x l -> p x = false) -> count p l = 0.\nProof.\n  intros N. induction l; auto. cbn. rewrite IHl.\n  - rewrite (N a); auto. cbn. left. auto.\n  - intros x I. apply (N x). cbn. right. assumption.\nQed.\n\nLemma count_existing {A: Type} (l: list A) (p: A->bool) (x: A) :\n  p x = true -> In x l -> count p l <> O.\nProof.\n  intros pred I. induction l.\n  - cbn in *. inversion I.\n  - cbn in *. destruct I.\n    + subst. rewrite pred. apply neq_succ_0.\n    + destruct (p a); auto.\nQed.\n\nTheorem dup_def_eq {A: Type} `{LinearOrder A} (l : list A) : \n  Deduplicated l <-> LDeduplicated l.\nProof.\n  unfold LDeduplicated. split.\n  - intros D x I. induction D.\n    + cbn in *. inversion I.\n    + cbn in *. destruct I.\n      * subst. rewrite eqf_refl. rewrite count_for_not_satisfied_pred; auto. intros y I.\n        rewrite <- not_eqf_iff. intros e. subst. apply H0. assumption.\n      * rewrite (IHD H1). assert (x <> x0) by (intro e; subst; auto). rewrite not_eqf_iff in H2.\n        rewrite H2. auto.\n  - intro D. induction l; constructor.\n    + intro I. specialize (D a (or_intror I)). cbn in D. rewrite eqf_refl in D. assert (count (eqf a) l <> O).\n      * apply count_existing with (x := a); auto. apply eqf_refl.\n      * rewrite neq_0_r in H0. destruct H0 as (m & S). rewrite S in D. inversion D.\n    + apply IHl. intros x I. cbn in *. specialize (D x (or_intror I)). destruct (eqf x a) eqn:e.\n      * rewrite <- eqf_iff in e. subst. assert (count (eqf a) l <> O).\n        -- apply count_existing with (x := a); auto. apply eqf_refl.\n        -- rewrite neq_0_r in H0. destruct H0 as (m & S). rewrite S in D. inversion D. \n      * assumption.\nQed.\n\nTheorem unique_sorted {A: Type} `{LinearOrder A} (l l': list A) : \n  permutation l l' -> Sorted l -> Sorted l' -> l = l'.\nProof.\nAdmitted.\n\nFixpoint remove {A: Type} `{EqDec A} (x: A) (l: list A) :=\nmatch l with \n| []     => []\n| (h::t) => if eqf x h then t else h :: remove x t\nend.\n\nLemma remove_count_true {A: Type} `{EqDec A} (h: A) (l: list A) (p: A -> bool) :\n  In h l -> p h = true -> count p l = S (count p (remove h l)).\nProof.\n  induction l; intros I t.\n  - cbn in *. destruct I. \n  - cbn in *. destruct I.\n    + subst. rewrite t. rewrite eqf_refl. auto.\n    + destruct (p a) eqn:e; destruct (eqf h a) eqn:e1; auto.\n      * cbn in *. rewrite e. rewrite IHl; auto.\n      * rewrite <- eqf_iff in e1. subst. rewrite t in e. discriminate.\n      * cbn in *. rewrite e. apply IHl; auto.\nQed.\n\nLemma remove_count_false {A: Type} `{EqDec A} (h: A) (l: list A) (p: A -> bool) :\n  p h = false -> count p l = count p (remove h l).\nProof.\n  induction l; intros f; auto. cbn in *. \n  destruct (p a) eqn:e; destruct (eqf h a) eqn:e1; auto.\n  - rewrite <- eqf_iff in e1. subst. rewrite f in e. discriminate.\n  - cbn. rewrite e. f_equal. apply IHl; auto.\n  - cbn. rewrite e. apply IHl; auto.\nQed.\n\nLemma in_count_not_O {A: Type} `{EqDec A} (l: list A) (x: A) :\n  In x l <-> count (eqf x) l <> O.\nProof.\n  split.\n  - intros I. induction l.\n    + cbn in I. destruct I.\n    + cbn in *. destruct I as [e|I].\n      * subst. rewrite eqf_refl. auto.\n      * destruct (eqf x a) eqn: e; auto.\n  - intros C. induction l.\n    + cbn in C. contradiction.\n    + cbn in *. destruct (eqf x a) eqn: e; auto. rewrite <- eqf_iff in e.\n      subst. left. auto.\nQed. \n\nLemma perm_in {A: Type} `{EqDec A} (l l': list A) (x: A) :\n  permutation l l' -> In x l -> In x l'.\nProof.\n  intros perm I. rewrite in_count_not_O. rewrite in_count_not_O in I.\n  specialize (perm (eqf x)). rewrite <-perm. assumption.\nQed.\n\nLemma remove_perm {A: Type} `{EqDec A} (h: A) (l l': list A) :\n  permutation (h :: l) l' -> permutation l (remove h l').\nProof.\n  unfold permutation. revert l'. induction l; intros l' perm p.\n  - assert (In h l'). \n    + apply (perm_in [h]); auto. cbn. auto. \n    + cbn. apply eq_add_S. specialize (perm p). cbn in *. destruct (p h) eqn:e.\n      * rewrite <-remove_count_true; auto.\n      * rewrite <-remove_count_false; auto.\n  - assert (In h l') by (apply (perm_in (h::a::l)); cbn; auto).\n    assert (In a l') by (apply (perm_in (h::a::l)); cbn; auto).\n    cbn. apply eq_add_S. apply eq_add_S. specialize (perm p). cbn in *.\n    destruct (p h) eqn:e.\n    + rewrite <-remove_count_true; auto.\n    + rewrite <-remove_count_false; auto.\nQed.\n\nLemma remove_perm' {A: Type} `{EqDec A} (h: A) (l l': list A) :\n  In h l' -> permutation l (remove h l') -> permutation (h :: l) l' .\nProof.\n  unfold permutation. revert l'. induction l; intros l' I perm p.\n  - cbn in *. specialize (perm p). destruct (p h) eqn: e.\n    + rewrite (remove_count_true h); auto.\n    + rewrite (remove_count_false h); auto.\n  - cbn in *. specialize (perm p). destruct (p h) eqn: e.\n    + rewrite (remove_count_true h l'); auto.\n    + rewrite (remove_count_false h l'); auto.\nQed.\n\nDefinition perm_eqf {A: Type} `{EqDec A} (l l': list A) := \n  forall x: A, count (eqf x) l = count (eqf x) l'.\n\nLemma perm_eqf_iff {A: Type} `{EqDec A} (l l': list A) : \n  permutation l l' <-> perm_eqf l l'.\nProof.\n  split.\n  - intros P x. apply (P (eqf x)).\n  - revert l'. induction l; intros l' E p.\n    + destruct l'; auto. specialize (E a). cbn in E. rewrite eqf_refl in E. inversion E.\n    + rewrite (remove_perm' a l l'); auto.\n      * rewrite in_count_not_O. specialize (E a). rewrite <- E. cbn. rewrite eqf_refl. auto.\n      * intros p'. apply IHl. intros x. specialize (E x). cbn in *. destruct (eqf x a) eqn:e.\n        -- apply eq_add_S. rewrite E. rewrite (remove_count_true a); auto.\n           rewrite <- eqf_iff in e. subst. rewrite in_count_not_O. rewrite <-E. auto.\n        -- rewrite E. rewrite (remove_count_false a); auto.\nQed.\n\nLemma any_count_true {A: Type} (l: list A) (p: A -> bool) :\n  (count p l <> 0) <-> (any p l = true).\nProof.\n  split; intro H.\n  - induction l.\n    + cbn in *. contradiction.\n    + cbn in *. destruct (p a) eqn: e; auto.\n  - intro C. induction l.\n    + cbn in *. discriminate.\n    + cbn in *. destruct (p a) eqn: e; try discriminate. apply IHl; auto.\nQed.\n\nLemma any_count_false {A: Type} (l: list A) (p: A -> bool) :\n  (count p l = 0) <-> (any p l = false).\nProof.\n  split; intro H.\n  - induction l; auto. cbn in *. destruct (p a) eqn: e; auto; try discriminate.\n  - induction l; auto. cbn in *. destruct (p a) eqn: e; auto; try discriminate.\nQed.\n\nTheorem unique_dedup_perm {A: Type} `{LinearOrder A} (l l': list A) : \n  Elem_eq l l' -> Deduplicated l -> Deduplicated l' -> permutation l l'.\nProof.\n  rewrite dup_def_eq, dup_def_eq. rewrite perm_eqf_iff.\n  unfold Elem_eq, LDeduplicated. intros eq d1 d2 x.\n  specialize (eq (eqf x)). destruct (any (eqf x) l) eqn:I1; destruct (any (eqf x) l') eqn:I2; try discriminate.\n  - rewrite <- any_count_true in I1. rewrite <- any_count_true in I2.\n    rewrite <- in_count_not_O in I1. rewrite <- in_count_not_O in I2. rewrite d1, d2; auto. \n  - rewrite <- any_count_false in I1. rewrite <- any_count_false in I2. rewrite I1, I2. auto.\nQed.\n\nTheorem deduo_sort_uniquenss {A: Type} `{LinearOrder A} (l l': list A) : Elem_eq l l' -> \n  Sorted l -> Sorted l' -> Deduplicated l -> Deduplicated l' -> l = l'.\nProof.\n  intros e_eq s1 s2 d1 d2. apply unique_sorted; auto. apply unique_dedup_perm; auto.\nQed.\n\n\n\n(* normal function *)\n\nDefinition normalzation {A: Type} (f: A -> A) :=\n  forall x: A, f x = f (f x).\n\nTheorem DSort_normal {A: Type} `{LinearOrder A} : normalzation DSort.\nProof.\n  red. intros l. apply deduo_sort_uniquenss.\n  - apply same_elements_DSort.\n  - apply sorted_DSort.\n  - apply sorted_DSort.\n  - rewrite dup_def_eq. apply dedup_DSort. \n  - rewrite dup_def_eq. apply dedup_DSort. \nQed.\n\nClass equivalance_relation {A: Type} (R: A -> A -> Prop) := equiv_proof {\n  equiv_refl  : forall x: A, R x x;\n  equiv_sym   : forall x y: A, R x y -> R y x;\n  equiv_trans : forall x y z: A, R x y -> R y z -> R x z;\n}.\n\nTheorem eq_elem_equiv {A: Type} : equivalance_relation (Elem_eq (A := A)).\nProof.\n  apply equiv_proof.\n  - intros x p. reflexivity.\n  - intros x y eq p. rewrite eq. reflexivity.\n  - intros x y z eq1 eq2 p. rewrite eq1, eq2. reflexivity.\nQed.\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/Deduplicated.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891348788759, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6583202684180256}}
{"text": "Require Export Base.Categories.\n\nSection monoepi.\nContext {C: Category}.\n\nDefinition monic {a b: C} (f: a ~> b) :=\n  forall c (g1 g2: c ~> a), f ∘ g1 = f ∘ g2 -> g1 = g2.\n\nDefinition epic {a b: C} (f: a ~> b) :=\n  forall c (g1 g2: b ~> c), g1 ∘ f = g2 ∘ f -> g1 = g2.\n\nDefinition splitmonic {a b: C} (f: a ~> b) :=\n  exists f': b ~> a, f' ∘ f = id a.\n\nDefinition splitepic {a b: C} (f: a ~> b) :=\n  exists f': b ~> a, f ∘ f' = id b.\n\nLemma splitmonic_is_monic {a b: C} (f: a ~> b): splitmonic f -> monic f.\nProof.\n  intros [f' Hf] c g1 g2 H.\n  setoid_rewrite <- comp_id_l.\n  rewrite <- Hf.\n  rewrite <- !comp_assoc.\n  now f_equal.\nQed.\n\nLemma splitepic_is_epic {a b: C} (f: a ~> b): splitepic f -> epic f.\nProof.\n  intros [f' Hf] c g1 g2 H.\n  setoid_rewrite <- comp_id_r.\n  rewrite <- Hf.\n  rewrite !comp_assoc.\n  now f_equal.\nQed.\n\nLemma monic_id (a: C): monic (id a).\nProof.\n  intros x f g H.\n  now setoid_rewrite <- comp_id_l.\nQed.\n\nLemma epic_id (a: C): epic (id a).\nProof.\n  intros x f g H.\n  now setoid_rewrite <- comp_id_r.\nQed.\n\nLemma splitmonic_id (a: C): splitmonic (id a).\nProof.\n  exists (id a).\n  apply comp_id_l.\nQed.\n\nLemma splitepic_id (a: C): splitepic (id a).\nProof.\n  exists (id a).\n  apply comp_id_l.\nQed.\n\nLemma monic_comp {a b c: C} (f: b ~> c) (g: a ~> b): monic f -> monic g -> monic (f ∘ g).\nProof.\n  intros Hf Hg x h1 h2 H.\n  apply Hg, Hf.\n  now rewrite !comp_assoc.\nQed.\n\nLemma epic_comp {a b c: C} (f: b ~> c) (g: a ~> b): epic f -> epic g -> epic (f ∘ g).\nProof.\n  intros Hf Hg x h1 h2 H.\n  apply Hf, Hg.\n  now rewrite <- !comp_assoc.\nQed.\n\nLemma splitmonic_comp {a b c: C} (f: b ~> c) (g: a ~> b): splitmonic f -> splitmonic g -> splitmonic (f ∘ g).\nProof.\n  intros [f' Hf] [g' Hg].\n  exists (g' ∘ f').\n  rewrite comp_assoc, <- (comp_assoc g').\n  rewrite Hf, comp_id_r.\n  apply Hg.\nQed.\n\nLemma splitepic_comp {a b c: C} (f: b ~> c) (g: a ~> b): splitepic f -> splitepic g -> splitepic (f ∘ g).\nProof.\n  intros [f' Hf] [g' Hg].\n  exists (g' ∘ f').\n  rewrite comp_assoc, <- (comp_assoc f).\n  rewrite Hg, comp_id_r.\n  apply Hf.\nQed.\n\nLemma monic_comp_r {a b c: C} (f: b ~> c) (g: a ~> b): monic (f ∘ g) -> monic g.\nProof.\n  intros Hc x h1 h2 H.\n  apply Hc.\n  rewrite <- !comp_assoc.\n  now f_equal.\nQed.\n\nLemma epic_comp_l {a b c: C} (f: b ~> c) (g: a ~> b): epic (f ∘ g) -> epic f.\nProof.\n  intros Hc x h1 h2 H.\n  apply Hc.\n  rewrite !comp_assoc.\n  now f_equal.\nQed.\n\nLemma splitmonic_comp_r {a b c: C} (f: b ~> c) (g: a ~> b): splitmonic (f ∘ g) -> splitmonic g.\nProof.\n  intros [h H].\n  exists (h ∘ f).\n  now rewrite <- comp_assoc.\nQed.\n\nLemma splitepic_comp_l {a b c: C} (f: b ~> c) (g: a ~> b): splitepic (f ∘ g) -> splitepic f.\nProof.\n  intros [h H].\n  exists (g ∘ h).\n  now rewrite comp_assoc.\nQed.\n\nEnd monoepi.\n\nModule Isomorphism.\n\nStructure mixin_of {C: Category} {x y: C} (f: x ~> y) := Mixin {\n  inv: y ~> x;\n  inv_l: inv ∘ f = id x;\n  inv_r: f ∘ inv = id y;\n}.\n\nNotation class_of := mixin_of (only parsing).\n\nSection ClassDef.\nContext {C: Category} {x y: C}.\n\nStructure type := Pack { morphism: x ~> y; _: class_of morphism }.\nLocal Coercion morphism: type >-> hom.\n\nVariable (i: type).\nDefinition class := match i return class_of i with Pack _ c => c end.\n\nEnd ClassDef.\n\nModule Exports.\n\nArguments type {_} _ _.\nCoercion morphism: type >-> hom.\nNotation to := morphism.\nNotation iso := type.\n\nEnd Exports.\n\nEnd Isomorphism.\n\nExport Isomorphism.Exports.\n\nSection iso.\nContext {C: Category} {x y: C} (i: iso x y).\n\nDefinition from: y ~> x := Isomorphism.inv i (Isomorphism.class i).\n\nLemma from_to: from ∘ i = id x.\nProof. apply Isomorphism.inv_l. Qed.\nLemma to_from: i ∘ from = id y.\nProof. apply Isomorphism.inv_r. Qed.\n\nDefinition inv_mixin: Isomorphism.mixin_of from :=\n  Isomorphism.Mixin _ _ _ from i to_from from_to.\n\nGlobal Canonical inv: iso y x :=\n  Isomorphism.Pack from inv_mixin.\n\nLemma inv_l: inv ∘ i = id x.\nProof. apply Isomorphism.inv_l. Qed.\n\nLemma inv_r: i ∘ inv = id y.\nProof. apply Isomorphism.inv_r. Qed.\n\nEnd iso.\n\nInfix \"<~>\" := iso (at level 70, no associativity).\nNotation \"i '⁻¹'\" := (inv i) (at level 9).\n\nDefinition id_iso_mixin {C: Category} (x: C): Isomorphism.mixin_of (id x) :=\n  Isomorphism.Mixin C x x (id x) (id x) (comp_id_l (id x)) (comp_id_l (id x)).\n\nCanonical id_iso {C: Category} (x: C): x <~> x :=\n  Isomorphism.Pack (id x) (id_iso_mixin x).\n\nSection Comp_iso.\nContext {C: Category} {x y z: C} (i: y <~> z) (j: x <~> y).\n\nLemma comp_inv_l: j⁻¹ ∘ i⁻¹ ∘ (i ∘ j) = id x.\nProof.\n  rewrite comp_assoc.\n  rewrite <- (comp_assoc (j⁻¹)).\n  rewrite inv_l, comp_id_r.\n  apply inv_l.\nQed.\n\nLemma comp_inv_r: i ∘ j ∘ (j⁻¹ ∘ i⁻¹) = id z.\nProof.\n  rewrite comp_assoc.\n  rewrite <- (comp_assoc i).\n  rewrite inv_r, comp_id_r.\n  apply inv_r.\nQed.\n\nDefinition iso_comp_mixin: Isomorphism.mixin_of (i ∘ j) :=\n  Isomorphism.Mixin _ _ _ (i ∘ j) (j⁻¹ ∘ i⁻¹) comp_inv_l comp_inv_r.\n\nGlobal Canonical iso_comp: iso x z :=\n  Isomorphism.Pack (i ∘ j) iso_comp_mixin.\n\nEnd Comp_iso.\n\nInfix \"·\" := iso_comp (at level 40, left associativity).\n\nLemma iso_eq {C: Category} {x y: C} (i j: x <~> y): i = j <-> to i = to j.\nProof.\n  split; intro H.\n  now subst j.\n  destruct i as [f [f' Hf1 Hf2]], j as [g [g' Hg1 Hg2]].\n  simpl in H.\n  subst g.\n  f_equal.\n  enough (f' = g').\n  subst g'.\n  f_equal.\n  1, 2: apply proof_irrelevance.\n  rewrite <- (comp_id_r f').\n  rewrite <- Hg2.\n  rewrite comp_assoc.\n  rewrite Hf1.\n  apply comp_id_l.\nQed.\n\nLemma icomp_assoc {C: Category} {a b c d: C} (f: c <~> d) (g: b <~> c) (h: a <~> b): f · (g · h) = (f · g) · h.\nProof.\n  apply iso_eq; simpl.\n  apply comp_assoc.\nQed.\n\nLemma icomp_id_l {C: Category} {x y: C} (i: x <~> y): id_iso y · i = i.\nProof.\n  apply iso_eq; simpl.\n  apply comp_id_l.\nQed.\n\nLemma icomp_id_r {C: Category} {x y: C} (i: x <~> y): i · id_iso x = i.\nProof.\n  apply iso_eq; simpl.\n  apply comp_id_r.\nQed.\n\nLemma icomp_inv_l {C: Category} {x y: C} (i: x <~> y): i⁻¹ · i = id_iso x.\nProof.\n  apply iso_eq; simpl.\n  apply from_to.\nQed.\n\nLemma icomp_inv_r {C: Category} {x y: C} (i: x <~> y): i · i⁻¹ = id_iso y.\nProof.\n  apply iso_eq; simpl.\n  apply to_from.\nQed.\n\nDefinition isomorphic (C: Category) (X Y: C) := inhabited (X <~> Y).\n\nInfix \"≃\" := (isomorphic _) (at level 70).\n\nInstance isomorphic_equiv C: Equivalence (isomorphic C).\nProof.\n  constructor.\n  + intros x.\n    constructor.\n    exact (id_iso x).\n  + intros x y H.\n    destruct H as [i].\n    constructor.\n    exact (i⁻¹).\n  + intros x y z H H0.\n    destruct H as [i], H0 as [j].\n    constructor.\n    eapply iso_comp; eassumption.\nQed.\n\nDefinition eq_iso {C: Category} {X Y: C} (e: X = Y): X <~> Y :=\n  match e in (_ = y) return (X <~> y) with\n  | eq_refl => id_iso X\n  end.\n\nTheorem eq_iso_refl {C: Category} {X: C} (e: X = X): eq_iso e = id_iso X.\nProof.\n  unfold eq_iso.\n  assert (e = eq_refl).\n  apply proof_irrelevance.\n  subst e.\n  reflexivity.\nQed.\n\nDefinition is_iso {C: Category} {X Y: C} (f: X ~> Y) :=\n  exists g: Y ~> X, g ∘ f = id X /\\ f ∘ g = id Y.\n\nLemma is_iso_ex {C: Category} {X Y: C} (f: X ~> Y): is_iso f -> exists i: X <~> Y, to i = f.\nProof.\n  intros [g [Hl Hr]].\n  exists (Isomorphism.Pack f (Isomorphism.Mixin _ _ _ f g Hl Hr)).\n  reflexivity.\nQed.\n\nLemma is_isomorphic {C: Category} {X Y: C} (f: X ~> Y): is_iso f -> X ≃ Y.\nProof.\n  intros H.\n  apply is_iso_ex in H.\n  destruct H as [i H].\n  constructor.\n  exact i.\nQed.\n\nLemma is_iso_id {C: Category} {x: C}: is_iso (id x).\nProof.\n  exists (id x).\n  split.\n  all: apply comp_id_l.\nQed.\n\nLemma is_iso_comp {C: Category} {X Y Z: C} (g: Y ~> Z) (f: X ~> Y): is_iso g -> is_iso f -> is_iso (g ∘ f).\nProof.\n  intros [g' [Hgl Hgr]] [f' [Hfl Hfr]].\n  exists (f' ∘ g'); split.\n  all: rewrite comp_assoc.\n  rewrite <- (comp_assoc f').\n  rewrite Hgl, comp_id_r.\n  apply Hfl.\n  rewrite <- (comp_assoc g).\n  rewrite Hfr, comp_id_r.\n  apply Hgr.\nQed.\n\nDefinition is_eq {C: Category} {X Y: C} (f: X ~> Y) :=\n  exists e: X = Y, f = eq_iso e.\n\nLemma iso_is_iso {C: Category} {X Y: C} (f: X <~> Y): is_iso f.\nProof.\n  exists (f⁻¹).\n  split.\n  apply inv_l.\n  apply inv_r.\nQed.\n\nLemma is_eq_is_iso {C: Category} {X Y: C} (f: X ~> Y): is_eq f -> is_iso f.\nProof.\n  intros [e H].\n  subst f.\n  apply iso_is_iso.\nQed.\n\nLemma eq_iso_is_eq {C: Category} {X Y: C} (e: X = Y): is_eq (eq_iso e).\nProof. now exists e. Qed.\n\nLemma is_eq_refl {C: Category} {X: C} (η: X ~> X): is_eq η -> η = id X.\nProof.\n  intros [e1 H1].\n  subst η.\n  now rewrite eq_iso_refl.\nQed.\n\nLemma is_eq_unique {C: Category} {X Y: C} (η ϵ: X ~> Y): is_eq η -> is_eq ϵ -> η = ϵ.\nProof.\n  intros [e1 H1] [e2 H2].\n  subst η ϵ.\n  do 2 f_equal.\n  apply proof_irrelevance.\nQed.\n\nLemma is_eq_unique_iso {C: Category} {X Y: C} (η ϵ: X <~> Y): is_eq η -> is_eq ϵ -> η = ϵ.\nProof.\n  intros Hη Hϵ.\n  now apply iso_eq, is_eq_unique.\nQed.\n\nLemma is_eq_id {C: Category} {X: C}: is_eq (id X).\nProof. now exists eq_refl. Qed.\n\nLemma is_eq_comp {C: Category} {X Y Z: C} (ϵ: Y ~> Z) (η: X ~> Y): is_eq η -> is_eq ϵ -> is_eq (ϵ ∘ η).\nProof.\n  intros [e1 H1] [e2 H2].\n  subst η ϵ Y Z.\n  simpl.\n  rewrite comp_id_l.\n  apply is_eq_id.\nQed.\n\nLemma is_eq_inv {C: Category} {X Y: C} (η: X <~> Y): is_eq η -> is_eq η⁻¹.\nProof.\n  intros [e H].\n  apply iso_eq in H.\n  subst η Y.\n  apply is_eq_id.\nQed.\n\nTheorem iso_is_splitmonic {C: Category} {x y: C} (i: x <~> y): splitmonic i.\nProof.\n  exists (i⁻¹).\n  apply inv_l.\nQed.\n\nTheorem iso_is_splitepic {C: Category} {x y: C} (i: x <~> y): splitepic i.\nProof.\n  exists (i⁻¹).\n  apply inv_r.\nQed.\n\nTheorem iso_monic {C: Category} {x y: C} (i: x <~> y): monic i.\nProof.\n  apply splitmonic_is_monic.\n  apply iso_is_splitmonic.\nQed.\n\nTheorem iso_epic {C: Category} {x y: C} (i: x <~> y): epic i.\nProof.\n  apply splitepic_is_epic.\n  apply iso_is_splitepic.\nQed.\n\nTheorem is_iso_is_splitmonic {C: Category} {x y: C} (f: x ~> y): is_iso f -> splitmonic f.\nProof.\n  intros [f' [H _]].\n  now exists (f').\nQed.\n\nTheorem is_iso_is_splitepic {C: Category} {x y: C} (f: x ~> y): is_iso f -> splitepic f.\nProof.\n  intros [f' [_ H]].\n  now exists (f').\nQed.\n\nTheorem is_iso_monic {C: Category} {x y: C} (f: x ~> y): is_iso f -> monic f.\nProof.\n  intros H.\n  apply splitmonic_is_monic, is_iso_is_splitmonic, H.\nQed.\n\nTheorem is_iso_epic {C: Category} {x y: C} (f: x ~> y): is_iso f -> epic f.\nProof.\n  intros H.\n  apply splitepic_is_epic, is_iso_is_splitepic, H.\nQed.\n\nTheorem splitmonic_epic {C: Category} {x y: C} (f: x ~> y): splitmonic f -> epic f -> is_iso f.\nProof.\n  intros [g inv_l] H.\n  exists g; split.\n  exact inv_l.\n  apply H.\n  rewrite <- comp_assoc, comp_id_l.\n  rewrite inv_l.\n  apply comp_id_r.\nQed.\n\nTheorem splitepic_monic {C: Category} {x y: C} (f: x ~> y): splitepic f -> monic f -> is_iso f.\nProof.\n  intros [g inv_r] H.\n  exists g; split.\n  apply H.\n  rewrite comp_assoc, comp_id_r.\n  rewrite inv_r.\n  apply comp_id_l.\n  exact inv_r.\nQed.\n\nTheorem is_iso_comp_l {C: Category} {x y z: C} (f: y ~> z) (g: x ~> y): is_iso (f ∘ g) -> is_iso g -> is_iso f.\nProof.\n  intros [c Hc] [g' Hg].\n  exists (g ∘ c); split.\n  rewrite <- (comp_id_r _).\n  rewrite <- (proj2 Hg).\n  rewrite <- !(comp_assoc g).\n  f_equal.\n  rewrite comp_assoc, <- (comp_assoc c).\n  rewrite (proj1 Hc).\n  apply comp_id_l.\n  now rewrite comp_assoc.\nQed.\n\nTheorem is_iso_comp_r {C: Category} {x y z: C} (f: y ~> z) (g: x ~> y): is_iso (f ∘ g) -> is_iso f -> is_iso g.\nProof.\n  intros [c Hc] [f' Hf].\n  exists (c ∘ f); split.\n  now rewrite <- comp_assoc.\n  rewrite <- (comp_id_l _).\n  rewrite <- (proj1 Hf).\n  rewrite <- comp_assoc.\n  f_equal.\n  rewrite !comp_assoc.\n  rewrite (proj2 Hc).\n  apply comp_id_l.\nQed.\n\nDefinition co_iso_mixin {C: Category} {x y: C} (i: x <~> y): Isomorphism.mixin_of (from i: @hom (co C) x y) :=\n  Isomorphism.Mixin (co C) x y (from i) (to i) (from_to i) (to_from i).\n\nDefinition co_iso {C: Category} {x y: C} (i: x <~> y): (x: co C) <~> y :=\n  Isomorphism.Pack _ (co_iso_mixin i).\n\nDefinition co_iso_mixin' {C: Category} {x y: C} (i: (x: co C) <~> y): Isomorphism.mixin_of (from i: x ~> y) :=\n  Isomorphism.Mixin C x y (from i) (to i) (from_to i) (to_from i).\n\nDefinition co_iso' {C: Category} {x y: C} (i: (x: co C) <~> y): x <~> y :=\n  Isomorphism.Pack _ (co_iso_mixin' i).\n\nTheorem iso_co {C: Category} (x y: C): (x: co C) ≃ y <-> x ≃ y.\n  split.\n  + intros [i].\n    constructor.\n    apply co_iso', i.\n  + intros [i].\n    constructor.\n    apply co_iso, i.\nQed.\n\nLemma is_iso_co {C: Category} {x y: C} (f: x ~> y): is_iso (f: (y: co C) ~> x) <-> is_iso f.\nProof.\n  split.\n  all: intros [g [Hl Hr]].\n  all: exists g; split.\n  1, 3: exact Hr.\n  all: exact Hl.\nQed.\n\nLemma is_iso_co' {C: Category} {x y: C} (f: (x: co C) ~> y): is_iso (f: y ~> x) <-> is_iso f.\nProof.\n  split.\n  all: intros [g [Hl Hr]].\n  all: exists g; split.\n  1, 3: exact Hr.\n  all: exact Hl.\nQed.\n\nLemma monic_co {C: Category} {x y: C} (f: x ~> y): monic f <-> epic (f: (y: co C) ~> x).\nProof. reflexivity. Qed.\n\nLemma epic_co {C: Category} {x y: C} (f: x ~> y): epic f <-> monic (f: (y: co C) ~> x).\nProof. reflexivity. Qed.\n\nLemma monic_co' {C: Category} {x y: C} (f: (x: co C) ~> y): monic (f: y ~> x) <-> epic f.\nProof. reflexivity. Qed.\n\nLemma epic_co' {C: Category} {x y: C} (f: (x: co C) ~> y): epic (f: y ~> x) <-> monic f.\nProof. reflexivity. Qed.\n\nLemma splitmonic_co {C: Category} {x y: C} (f: x ~> y): splitmonic f <-> splitepic (f: (y: co C) ~> x).\nProof. reflexivity. Qed.\n\nLemma splitepic_co {C: Category} {x y: C} (f: x ~> y): splitepic f <-> splitmonic (f: (y: co C) ~> x).\nProof. reflexivity. Qed.\n\nLemma splitmonic_co' {C: Category} {x y: C} (f: (x: co C) ~> y): splitmonic (f: y ~> x) <-> splitepic f.\nProof. reflexivity. Qed.\n\nLemma splitepic_co' {C: Category} {x y: C} (f: (x: co C) ~> y): splitepic (f: y ~> x) <-> splitmonic f.\nProof. reflexivity. Qed.\n\nLemma is_eq_co {C: Category} {x y: C} (f: x ~> y): is_eq f <-> is_eq (f: (y: co C) ~> x).\nProof.\n  split.\n  all: intros [e H].\n  all: subst f y.\n  all: exact is_eq_id.\nQed.\n\nLemma co_eq_iso {C: Category} {x y: C} (e: x = y): to (@eq_iso (co C) x y e) = to (eq_iso e)⁻¹.\nProof. now destruct e. Qed.\n\nDefinition eunique {C: Category} (P: C -> Prop) (x: C) :=\n  Proper (isomorphic C ==> iff) P /\\\n  P x /\\ forall x', P x' -> x ≃ x'.\n\nDefinition euniqueness {C: Category} (P: C -> Prop) :=\n  forall x y, P x -> P y -> x ≃ y.\n\nNotation \"'exists' !! x .. y , p\" :=\n  (ex (eunique (fun x => .. (ex (eunique (fun y => p))) ..)))\n  (at level 200, x binder, right associativity,\n    format \"'[' 'exists' !! '/ ' x .. y , '/ ' p ']'\"): type_scope.\n\nInstance euniqueness_impl (C: Category): Proper (flip (pointwise_relation C impl) ==> impl) euniqueness.\nProof.\n  intros P Q PQ H x y Hx Hy.\n  apply H.\n  all: now apply PQ.\nQed.\n\nInstance euniqueness_iff (C: Category): Proper (pointwise_relation C iff ==> iff) euniqueness.\nProof.\n  intros P Q H.\n  split.\n  all: change (?P -> ?Q) with (impl P Q).\n  all: f_equiv.\n  all: intros x.\n  exact (proj2 (H x)).\n  exact (proj1 (H x)).\nQed.\n\nInstance eunique_iff (C: Category): Proper (pointwise_relation C iff ==> isomorphic C ==> iff) eunique.\nProof.\n  enough (Proper (pointwise_relation C iff ==> isomorphic C ==> impl) eunique).\n  now split; apply H.\n  intros P Q PQ x y xy [PP [H u]].\n  split; [| split].\n  intros a b H1.\n  rewrite <- PQ.\n  now apply PP.\n  apply PQ.\n  now rewrite <- xy.\n  intros y' H'.\n  rewrite <- xy.\n  apply u, PQ, H'.\nQed.\n\nLemma eunique_existence {C: Category} (P: C -> Prop): (Proper (isomorphic C ==> iff) P /\\ (exists x, P x) /\\ euniqueness P) <-> exists!! x, P x.\nProof.\n  split.\n  + intros [PP [[x H] u]].\n    exists x; split.\n    2: split.\n    1, 2: assumption.\n    intros y Hy.\n    now apply u.\n  + intros [x [PP [H u]]].\n    split.\n    2: split.\n    exact PP.\n    now exists x.\n    intros y z Hy Hz.\n    transitivity x.\n    symmetry.\n    all: now apply u.\nQed.\n\nLemma forall_exists_eunique_domain_coincide {C: Category} (P:C->Prop): (exists!! x, P x) -> forall Q: C -> Prop,\n  Proper (isomorphic C ==> iff) Q ->\n  (forall x, P x -> Q x) <-> (exists x, P x /\\ Q x).\nProof.\n  intros [x [PP [Hx u]]] Q PQ.\n  split.\n  + intros H.\n    exists x; split.\n    exact Hx.\n    apply H, Hx.\n  + intros [y [Hy]] z Hz.\n    rewrite <- (u z Hz).\n    rewrite (u y Hy).\n    exact H.\nQed.\n\nLemma forall_exists_coincide_unique_domain {C: Category} (P: C -> Prop): Proper (isomorphic C ==> iff) P ->\n  (forall Q: C -> Prop, Proper (isomorphic C ==> iff) Q -> (forall x, P x -> Q x) <-> (exists x, P x /\\ Q x))\n  -> (exists!! x, P x).\nProof.\n  intros PP H.\n  destruct (proj1 (H P PP)) as [x [Hx _]].\n  easy.\n  exists x; split; [| split].\n  1, 2: assumption.\n  apply H.\n  intros y z yz.\n  now f_equiv.\n  now exists x.\nQed.\n", "meta": {"author": "adamAndMath", "repo": "Category", "sha": "1d230ee099a3ec7bd21306a404f38b2b3f3c3865", "save_path": "github-repos/coq/adamAndMath-Category", "path": "github-repos/coq/adamAndMath-Category/Category-1d230ee099a3ec7bd21306a404f38b2b3f3c3865/Base/Isomorphism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6583202660411044}}
{"text": "Require Import LogicalRelations.\nRequire Import Coq.Lists.List.\nLocal Open Scope rel_scope.\n\n(** * Tests *)\n\n(** ** Reflexivity *)\n\nGoal\n  forall A (a: A), a = a.\nProof.\n  intros.\n  rauto.\nQed.\n\nGoal\n  forall A (a: A), exists b, b = a.\nProof.\n  intros; eexists.\n  monotonicity.\nQed.\n\n(** ** Setoid rewriting *)\n\nGoal\n  forall A (a b: A) `(HR: Equivalence A) (H: R a b),\n    sum_rel R R (inl a) (inl b).\nProof.\n  intros.\n  rewrite H.\n  rewrite <- H.\n  reflexivity.\nQed.\n\n(** There is an issue with the following. *)\n\nGoal\n  forall A (a b: A) (R: rel A A) (f: A -> A) (p: A -> Prop),\n    Monotonic f (R ++> R) ->\n    Monotonic p (R --> impl) ->\n    R a b ->\n    p (f b) ->\n    p (f a).\nProof.\n  intros A a b R f p Hf Hp Hab H.\n  Fail rewrite <- Hab in H.\nAbort.\n\n(** ** Monotonicity tactics *)\n\n(** Basic sanity check. This has actually failed in the past due to\n  [context_candidate] being too liberal and selecting the [RB]\n  property instead of [RA], then going nowhere with that with no\n  backtracking implemented yet. *)\n\nGoal\n  forall A B (RA: rel A A) (x y: A) (RB: rel B B) (z t: B),\n    RA x y ->\n    RB z t ->\n    RA x y.\nProof.\n  intros.\n  rauto.\nQed.\n\nGoal\n  forall A (a b: A) (R: rel A A) (H: R a b),\n    let f (x y: A * A) := (@pair (A+A) (A+A) (inr (fst x)) (inl (snd y))) in\n    Monotonic f (R * ⊤ ++> ⊤ * R ++> (⊥ + R) * (R + ⊥))%rel.\nProof.\n  intros; unfold f.\n  rauto.\nQed.\n\nGoal\n  forall {A1 A2 B1 B2} (R1 R1': rel A1 A2) (R2 R2': rel B1 B2),\n    subrel R1' R1 ->\n    subrel R2 R2' ->\n    subrel (R1 ++> R2) (R1' ++> R2').\nProof.\n  do 10 intro.\n  rauto.\nQed.\n\n(** Check that we can use relational hypotheses from the context as\n  well as [Monotonic]/[Related] instances. *)\n\nGoal\n  forall\n    {A B} (R: rel A A)\n    (op: A -> B) (Hop: (R ++> eq) op op)\n    (x y: A) (Hxy: R x y),\n    op x = op y.\nProof.\n  intros.\n  rauto.\nQed.\n\n(** Bug with relational parametricity: you can't [RElim] a relation\n  you don't know yet. *)\n\nGoal\n  forall {A B} (RA: rel A A) (RB: rel B B) (m n: (A -> B) * B) (x y: A),\n    ((- ==> RB) * RB)%rel m n ->\n    RB (fst m x) (fst n x).\nProof.\n  intros A B RA RB m n x y Hmn.\n  try monotonicity.\n  try rauto.\nAbort.\n\n(** Pattern matching *)\n\nGoal\n  forall {A B} (RA: rel A A) (RB: rel B B) (x y: A) (f: A -> A + B),\n    RA x y ->\n    (RA ++> RA + RB) f f ->\n    RA (match f x with inl a => a | inr b => x end)\n       (match f y with inl a => a | inr b => y end).\nProof.\n  intros.\n  rauto.\nQed.\n\nGoal\n  forall {A B} (RA: rel A A) (RB: rel B B) (x y: A * B) (z: A),\n    RA z z ->\n    prod_rel RA RB x y ->\n    RA (let (a, b) := x in z)\n       (let (a, b) := y in z).\nProof.\n  intros.\n  rauto.\nQed.\n\nGoal\n  forall {A} (R: rel A A),\n    Monotonic\n      (fun (b: bool) x y => if b then x else y)\n      (- ==> R ++> R ++> R).\nProof.\n  intros.\n  rauto.\nQed.\n\nGoal\n  forall {A} (R : rel A A) (b : bool) (x y : A),\n    b = b ->\n    R x x ->\n    R y y ->\n    R (if b then x else y)\n      (if b then x else y).\nProof.\n  intros.\n  rauto.\nQed.\n\n(** [rel_curry] *)\n\nGoal\n  forall {A B C} R R' S (f: A -> B -> B -> C) (x1 y1: A) (x2 y2: B),\n    Monotonic f (rel_curry (R ++> R' ++> S)) ->\n    S (f x1 x2 x2) (f y1 y2 y2).\nProof.\n  intros A B C R R' S f x1 y1 x2 y2 Hf.\n  monotonicity.\nAbort.\n\n(** *** Hypotheses from the context *)\n\n(* This used to fail because [Hyy] would\n  shadow [Hxy] (the hypothesis we want). *)\n\nGoal\n  forall {A} (R: rel A A) (x y: A),\n    R x y -> eq y y -> R x y.\nProof.\n  intros A R x y Hxy Hyy.\n  monotonicity.\nQed.\n\n(* This still fail with Coq 8.5, but Coq 8.6 is able to backtrack and\n  try hypothesis from the context beyond the first one it finds. *)\n\nGoal\n  forall {A} (R: rel A A) (x y: A),\n    R x y -> eq x y -> R x y.\nProof.\n  intros A R x y Hxy Hyy.\n  try monotonicity.\nAbort.\n\n(** This used to fail because the flipped hypothesis would not be\n  identified as a candidate. This is important because the constraints\n  generated by the setoid rewriting system often have this form. *)\n\nGoal\n  forall {A} (R: rel A A) (f : A -> A),\n    Monotonic f (R ++> R) ->\n    (flip R ++> flip R) f f.\nProof.\n  intros A R f Hf.\n  rauto.\nQed.\n\n(** *** [impl] vs. [subrel] *)\n\n(** This checks that a relational property written in terms of\n  [subrel] can be used to solve a goal stated in terms of [impl].\n  This is made possible by [subrel_impl_relim]. *)\n\nGoal\n  forall A B C (R: rel A A) (f: A -> rel B C) a1 a2 b c,\n    Monotonic f (R ++> subrel) ->\n    R a1 a2 ->\n    impl (f a1 b c) (f a2 b c).\nProof.\n  intros A B C R f a1 a2 b c Hf Ha.\n  monotonicity; rauto.\nQed.\n\nGoal\n  forall A1 A2 B1 B2 (R1 R2: rel A1 A2) (R: rel B1 B2),\n    subrel R1 R2 ->\n    forall x y,\n      (R2 ++> R) x y ->\n      (R1 ++> R) x y.\nProof.\n  intros A1 A2 B1 B2 R1 R2 R HR12 x y.\n  rauto.\nQed.\n\n(** *** Generic rules *)\n\n(** The [coreflexivity] of [rel_prod] and [eq] makes it possible for\n  [pair_rel] to behave in the same way as [f_equal] below, since they\n  allow us to deduce that [eq * eq] is a [subrel] of [eq]. *)\n\nGoal\n  forall A B (x1 x2 : A) (y1 y2 : B),\n    x1 = x2 -> y1 = y2 -> (x1, y1) = (x2, y2).\nProof.\n  intros.\n  rauto.\nQed.\n\n(** ** Using [foo_subrel] instances *)\n\n(** Still broken because of the interaction between [subrel] and\n  [- ==> - ==> impl] (or lack thereof) *)\n\nGoal\n  forall A1 A2 B1 B2 C1 C2 (R1 R2: rel A1 A2) (R1': rel B1 B2) (R: rel C1 C2),\n    subrel R1 R2 ->\n    forall x y,\n      (R2 ++> R) x y ->\n      (R1 ++> R) x y.\nProof.\n  intros A1 A2 B1 B2 C1 C2 R1 R2 R1' R HR12 x y H.\n  rewrite HR12.\n  assumption.\nQed.\n\nGoal\n  forall A B (xa1 xa2 ya1 ya2 : A) (xb1 xb2 yb1 yb2 : B)\n         (opA: A -> A -> A) (opB: B -> B -> B)\n         (RA: rel A A) (RB: rel B B)\n         (HopA: Monotonic opA (RA ++> RA ++> RA))\n         (HopB: Monotonic opB (RB ++> RB ++> RB))\n         (Hxa: RA xa1 xa2)\n         (Hxb: RB xb1 xb2)\n         (Hya: RA ya1 ya2)\n         (Hyb: RB yb1 yb2),\n    (RA * RB)%rel\n      (opA xa1 ya1, opB xb1 yb1)\n      (opA xa2 ya2, opB xb2 yb2).\nProof.\n  intros.\n  rauto.\nQed.\n\nGoal\n  forall A1 A2 B1 B2 C1 C2 (R1 R2: rel A1 A2) (R1': rel B1 B2) (R: rel C1 C2),\n    subrel R1 R2 ->\n    forall x y,\n      (R2 * R1' ++> R) x y ->\n      (R1 * R1' ++> R) x y.\nProof.\n  intros A1 A2 B1 B2 C1 C2 R1 R2 R1' R HR12 x y H.\n  rewrite HR12.\n  assumption.\nQed.\n\n(** ** The [rgraph] tactic *)\n\nGoal\n  forall {A} (R S T: rel A A),\n    subrel R S ->\n    subrel S R ->\n    subrel S T ->\n    subrel R T.\nProof.\n  intros.\n  rstep.\nQed.\n\nGoal\n  forall `(PER) (x y z t : A),\n    R x y ->\n    R z y ->\n    R z t ->\n    R t x.\nProof.\n  intros.\n  rstep.\nQed.\n\n(** ** The [transport] tactic *)\n\nGoal\n  forall W acc A B C (R1: W -> rel A A) (R2: W -> rel B B) (R3: W -> rel C C) f g a b x w,\n    Monotonic f (rforall w, R1 w ++> R2 w) ->\n    Monotonic g (rforall w, R2 w ++> option_rel (rel_incr acc R3 w)) ->\n    R1 w a b ->\n    g (f a) = Some x ->\n    exists y, rel_incr acc R3 w x y.\nProof.\n  intros.\n  transport H2.\n  eexists.\n  rauto.\nQed.\n\n(** ** Tests for specific relators *)\n\n(** *** [list_rel] *)\n\n(** [list_subrel] use to not work because of a missing [Params] declaration. *)\n\nGoal\n  forall A B (R R': rel A B) l1 l2 x y,\n    subrel R R' ->\n    list_rel R l1 l2 ->\n    R' x y ->\n    list_rel R' (x :: l1) (y :: l2).\nProof.\n  intros.\n  rauto.\nQed.\n\n(** *** [rel_pull] *)\n\n(** The [RIntro] instance for [rel_pull] used to be less general. *)\n\nGoal\n  forall A B (f: A -> B) (R: rel B B) x y,\n    R (f x) (f y) ->\n    (R @@ f) x y.\nProof.\n  intros.\n  rauto.\nQed.\n\n(** We don't want the introduction rule for [rel_pull] to shadow\n  relational properties. *)\n\nLemma rel_pull_2:\n  forall A B (f: A -> B) (R: rel B B) (g: A -> A) x y,\n    Monotonic g (⊤ ==> R @@ f) ->\n    (R @@ f) (g x) (g y).\nProof.\n  intros.\n  rauto.\nQed.\n\n(** *** [rel_all] *)\n\nLemma rel_all_1:\n  forall {A} (x: A),\n    (rforall a, req a) x x -> forall a, req a x x.\nProof.\n  intros.\n  rauto.\nQed.\n\n(** *** [rel_ex] *)\n\nLemma rel_ex_1:\n  forall {A} (x: A),\n    (rexists a, req a) x x.\nProof.\n  intros.\n  rauto.\nQed.\n\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/CAL/coqrel/LogicalRelationsTests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891348788759, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6583202625525488}}
{"text": "Set Universe Polymorphism.\n\nSection Graph.\n\nClass Graph := {\n  Vertex : Type;\n  Edge : Vertex -> Vertex -> Type\n}.\n\nContext `{Graph}.\n\nInductive Path : Vertex -> Vertex -> Type :=\n| refl {a} : Path a a\n| step  {a b c} : Edge a b -> Path b c -> Path a c.\n\nEnd Graph.\n", "meta": {"author": "konne88", "repo": "category-theory", "sha": "883c4edd35ad47c82300315d1cd5c7f9238bede6", "save_path": "github-repos/coq/konne88-category-theory", "path": "github-repos/coq/konne88-category-theory/category-theory-883c4edd35ad47c82300315d1cd5c7f9238bede6/Diagram/Graph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.6583112401182901}}
{"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: Datatypes.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\nSet Implicit Arguments.\n\nRequire Import Notations.\nRequire Import Logic.\nDeclare ML Module \"nat_syntax_plugin\".\n\n\n(** [unit] is a singleton datatype with sole inhabitant [tt] *)\n\nInductive unit : Set :=\n    tt : unit.\n\n(** [bool] is the datatype of the boolean values [true] and [false] *)\n\nInductive bool : Set :=\n  | true : bool\n  | false : bool.\n\nAdd Printing If bool.\n\nDelimit Scope bool_scope with bool.\n\nBind Scope bool_scope with bool.\n\n(** Basic boolean operators *)\n\nDefinition andb (b1 b2:bool) : bool := if b1 then b2 else false.\n\nDefinition orb (b1 b2:bool) : bool := if b1 then true else b2.\n\nDefinition implb (b1 b2:bool) : bool := if b1 then b2 else true.\n\nDefinition xorb (b1 b2:bool) : bool :=\n  match b1, b2 with\n    | true, true => false\n    | true, false => true\n    | false, true => true\n    | false, false => false\n  end.\n\nDefinition negb (b:bool) := if b then false else true.\n\nInfix \"||\" := orb : bool_scope.\nInfix \"&&\" := andb : bool_scope.\n\n(*******************************)\n(** * Properties of [andb]     *)\n(*******************************)\n\nLemma andb_prop : forall a b:bool, andb a b = true -> a = true /\\ b = true.\nProof.\n  destruct a; destruct b; intros; split; try (reflexivity || discriminate).\nQed.\nHint Resolve andb_prop: bool.\n\nLemma andb_true_intro :\n  forall b1 b2:bool, b1 = true /\\ b2 = true -> andb b1 b2 = true.\nProof.\n  destruct b1; destruct b2; simpl in |- *; tauto || auto with bool.\nQed.\nHint Resolve andb_true_intro: bool.\n\n(** Interpretation of booleans as propositions *)\n\nInductive eq_true : bool -> Prop := is_eq_true : eq_true true.\n\nHint Constructors eq_true : eq_true.\n\n(** Another way of interpreting booleans as propositions *)\n\nDefinition is_true b := b = true.\n\n(** [is_true] can be activated as a coercion by\n   (Local) Coercion is_true : bool >-> Prop.\n*)\n\n(** Additional rewriting lemmas about [eq_true] *)\n\nLemma eq_true_ind_r :\n  forall (P : bool -> Prop) (b : bool), P b -> eq_true b -> P true.\nProof.\n  intros P b H H0; destruct H0 in H; assumption.\nDefined.\n\nLemma eq_true_rec_r :\n  forall (P : bool -> Set) (b : bool), P b -> eq_true b -> P true.\nProof.\n  intros P b H H0; destruct H0 in H; assumption.\nDefined.\n\nLemma eq_true_rect_r :\n  forall (P : bool -> Type) (b : bool), P b -> eq_true b -> P true.\nProof.\n  intros P b H H0; destruct H0 in H; assumption.\nDefined.\n\n(** [nat] is the datatype of natural numbers built from [O] and successor [S];\n    note that the constructor name is the letter O.\n    Numbers in [nat] can be denoted using a decimal notation;\n    e.g. [3%nat] abbreviates [S (S (S O))] *)\n\nInductive nat : Set :=\n  | O : nat\n  | S : nat -> nat.\n\nDelimit Scope nat_scope with nat.\nBind Scope nat_scope with nat.\nArguments Scope S [nat_scope].\n\n(** [Empty_set] has no inhabitant *)\n\nInductive Empty_set : Set :=.\n\n(** [identity A a] is the family of datatypes on [A] whose sole non-empty\n    member is the singleton datatype [identity A a a] whose\n    sole inhabitant is denoted [refl_identity A a] *)\n\nInductive identity (A:Type) (a:A) : A -> Type :=\n  identity_refl : identity a a.\nHint Resolve identity_refl: core.\n\nImplicit Arguments identity_ind [A].\nImplicit Arguments identity_rec [A].\nImplicit Arguments identity_rect [A].\n\n(** [option A] is the extension of [A] with an extra element [None] *)\n\nInductive option (A:Type) : Type :=\n  | Some : A -> option A\n  | None : option A.\n\nImplicit Arguments None [A].\n\nDefinition option_map (A B:Type) (f:A->B) o :=\n  match o with\n    | Some a => Some (f a)\n    | None => None\n  end.\n\n(** [sum A B], written [A + B], is the disjoint sum of [A] and [B] *)\n\nInductive sum (A B:Type) : Type :=\n  | inl : A -> sum A B\n  | inr : B -> sum A B.\n\nNotation \"x + y\" := (sum x y) : type_scope.\n\n(** [prod A B], written [A * B], is the product of [A] and [B];\n    the pair [pair A B a b] of [a] and [b] is abbreviated [(a,b)] *)\n\nInductive prod (A B:Type) : Type :=\n  pair : A -> B -> prod A B.\n\nAdd Printing Let prod.\n\nNotation \"x * y\" := (prod x y) : type_scope.\nNotation \"( x , y , .. , z )\" := (pair .. (pair x y) .. z) : core_scope.\n\nSection projections.\n  Variables A B : Type.\n  Definition fst (p:A * B) := match p with\n\t\t\t\t| (x, y) => x\n                              end.\n  Definition snd (p:A * B) := match p with\n\t\t\t\t| (x, y) => y\n                              end.\nEnd projections.\n\nHint Resolve pair inl inr: core.\n\nLemma surjective_pairing :\n  forall (A B:Type) (p:A * B), p = pair (fst p) (snd p).\nProof.\n  destruct p; reflexivity.\nQed.\n\nLemma injective_projections :\n  forall (A B:Type) (p1 p2:A * B),\n    fst p1 = fst p2 -> snd p1 = snd p2 -> p1 = p2.\nProof.\n  destruct p1; destruct p2; simpl in |- *; intros Hfst Hsnd.\n  rewrite Hfst; rewrite Hsnd; reflexivity.\nQed.\n\nDefinition prod_uncurry (A B C:Type) (f:prod A B -> C)\n  (x:A) (y:B) : C := f (pair x y).\n\nDefinition prod_curry (A B C:Type) (f:A -> B -> C)\n  (p:prod A B) : C := match p with\n                       | pair x y => f x y\n                       end.\n\n(** Comparison *)\n\nInductive comparison : Set :=\n  | Eq : comparison\n  | Lt : comparison\n  | Gt : comparison.\n\nDefinition CompOpp (r:comparison) :=\n  match r with\n    | Eq => Eq\n    | Lt => Gt\n    | Gt => Lt\n  end.\n\nLemma CompOpp_involutive : forall c, CompOpp (CompOpp c) = c.\nProof.\n  destruct c; reflexivity.\nQed.\n\nLemma CompOpp_inj : forall c c', CompOpp c = CompOpp c' -> c = c'.\nProof.\n  destruct c; destruct c'; auto; discriminate.\nQed.\n\nLemma CompOpp_iff : forall c c', CompOpp c = c' <-> c = CompOpp c'.\nProof.\n  split; intros; apply CompOpp_inj; rewrite CompOpp_involutive; auto.\nQed.\n\n(** The [CompSpec] inductive will be used to relate a [compare] function\n    (returning a comparison answer) and some equality and order predicates.\n    Interest: [CompSpec] behave nicely with [case] and [destruct]. *)\n\nInductive CompSpec {A} (eq lt : A->A->Prop)(x y:A) : comparison -> Prop :=\n | CompEq : eq x y -> CompSpec eq lt x y Eq\n | CompLt : lt x y -> CompSpec eq lt x y Lt\n | CompGt : lt y x -> CompSpec eq lt x y Gt.\nHint Constructors CompSpec.\n\n(** For having clean interfaces after extraction, [CompSpec] is declared\n    in Prop. For some situations, it is nonetheless useful to have a\n    version in Type. Interestingly, these two versions are equivalent.\n*)\n\nInductive CompSpecT {A} (eq lt : A->A->Prop)(x y:A) : comparison -> Type :=\n | CompEqT : eq x y -> CompSpecT eq lt x y Eq\n | CompLtT : lt x y -> CompSpecT eq lt x y Lt\n | CompGtT : lt y x -> CompSpecT eq lt x y Gt.\nHint Constructors CompSpecT.\n\nLemma CompSpec2Type : forall A (eq lt:A->A->Prop) x y c,\n CompSpec eq lt x y c -> CompSpecT eq lt x y c.\nProof.\n destruct c; intros H; constructor; inversion_clear H; auto.\nDefined.\n\n(** Identity *)\n\nDefinition ID := forall A:Type, A -> A.\nDefinition id : ID := fun A x => x.\n\n(** Polymorphic lists and some operations *)\n\nInductive list (A : Type) : Type :=\n | nil : list A\n | cons : A -> list A -> list A.\n\nImplicit Arguments nil [A].\nInfix \"::\" := cons (at level 60, right associativity) : list_scope.\nDelimit Scope list_scope with list.\nBind Scope list_scope with list.\n\nLocal Open Scope list_scope.\n\nDefinition length (A : Type) : list A -> nat :=\n  fix length l :=\n  match l with\n   | nil => O\n   | _ :: l' => S (length l')\n  end.\n\n(** Concatenation of two lists *)\n\nDefinition app (A : Type) : list A -> list A -> list A :=\n  fix app l m :=\n  match l with\n   | nil => m\n   | a :: l1 => a :: app l1 m\n  end.\n\nInfix \"++\" := app (right associativity, at level 60) : list_scope.\n\n(* begin hide *)\n\n(* Compatibility *)\n\nNotation prodT := prod (only parsing).\nNotation pairT := pair (only parsing).\nNotation prodT_rect := prod_rect (only parsing).\nNotation prodT_rec := prod_rec (only parsing).\nNotation prodT_ind := prod_ind (only parsing).\nNotation fstT := fst (only parsing).\nNotation sndT := snd (only parsing).\nNotation prodT_uncurry := prod_uncurry (only parsing).\nNotation prodT_curry := prod_curry (only parsing).\n\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/Init/Datatypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143776, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.6583035305666464}}
{"text": "(*|\n\n=================================================\nLiterate programming with Alectryon (Coq input)\n=================================================\n\nAlectryon supports literate programs and documents (combinations of\ncode and prose) written in Coq and reStructuredText.  Here is an\nexample, written in Coq.\n\n.. image:: coq.png\n    :width: 200px\n    :align: center\n    :height: 100px\n    :alt: alternate text\n\n.. math::\n   A^\\alpha = \\left({\\phi\\over c}, {\\bf A}\\right)\n\n.. coq:: none\n|*)\n\nRequire Import Arith.\n\n(*|\nHere's an *inductive specification* of evenness:\n\n.. index::\n   single: even\n\n.. coq::\n\n|*)\n\nInductive Even : nat -> Prop :=\n| EvenO : Even O\n| EvenS : forall n, Even n -> Even (S (S n)).\n\n(*|\n… and a corresponding decision procedure:\n|*)\n\nFixpoint even (n: nat): bool :=\n  match n with\n  | 0 => true\n  | 1 => false\n  | S (S n) => even n\n  end.\n\n(* Ensure that we never unfold [even (S n)] *)\nArguments even : simpl nomatch.\n\n(* no-hyps no-goals unfold *)\n\n(*|\nStrengthening the spec\n======================\nThe usual approach is to strengthen the spec to work around the weakness of the inductive principle.\nno-hyps no-goals unfold\n\n.. coq::\n|*)\n\nLemma even_Even :\n  forall n, (even n = true <-> Even n) /\\\n       (even (S n) = true <-> Even (S n)). (* .fold *)\nProof. (* .fold *)\n  induction n; cbn.\n  - (* n ← 0 *)\n    repeat split; cbn.\n    all: try constructor.\n    all: inversion 1.\n  - (* n ← S _ *)\n    destruct IHn as ((Hne & HnE) & (HSne & HSnE)).\n    repeat split; cbn.\n    all: eauto using EvenS.\n    inversion 1; eauto.\nQed.\n\n(*|\n.. coq::\n   :class: coq-math-2\n|*)\n\n   Notation \"\\mathbb{B}\" := bool.\n   Print bool. (* .unfold *)\n", "meta": {"author": "jjhugues", "repo": "coq-alectryon-template", "sha": "b48bbcbbfb289ad66510cd772b67f18821d75806", "save_path": "github-repos/coq/jjhugues-coq-alectryon-template", "path": "github-repos/coq/jjhugues-coq-alectryon-template/coq-alectryon-template-b48bbcbbfb289ad66510cd772b67f18821d75806/theories/hello.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6582321959298865}}
{"text": "Require Import Basics.\nRequire Import Spaces.Pos.\nRequire Import Spaces.Int.Core.\nRequire Import Spaces.Int.Spec.\n\n(** ** Iteration of equivalences *)\n\n(** *** Iteration by arbitrary integers *)\n\nDefinition int_iter {A} (f : A -> A) `{!IsEquiv f} (n : Int) : A -> A\n  := match n with\n      | neg n => fun x => pos_iter f^-1 n x\n      | zero => idmap\n      | pos n => fun x => pos_iter f n x\n     end.\n\n(** Iteration by arbitrary integers requires the endofunction to be an equivalence, so that we can define a negative iteration by using its inverse. *)\n\n\nDefinition int_iter_succ_l {A} (f : A -> A) `{IsEquiv _ _ f}\n  (n : Int) (a : A)\n  : int_iter f (int_succ n) a = f (int_iter f n a).\nProof.\n  destruct n as [n| |n]; trivial.\n  + revert n f H a.\n    srapply pos_peano_ind.\n    { intros f H a.\n      symmetry.\n      apply eisretr. }\n    hnf; intros n p f H a.\n    refine (ap (fun x => _ x _) _ @ _).\n    1: rewrite int_neg_pos_succ.\n    1: exact (eisretr int_succ (neg n)).\n    apply moveL_equiv_M.\n    cbn; symmetry.\n    srapply pos_iter_succ_l.\n  + cbn.\n    rewrite pos_add_1_r.\n    srapply pos_iter_succ_l.\nQed.\n\nDefinition int_iter_succ_r {A} (f : A -> A) `{IsEquiv _ _ f}\n  (n : Int) (a : A) : int_iter f (int_succ n) a = int_iter f n (f a).\nProof.\n   destruct n as [n| |n]; trivial.\n+ revert n f H a.\n  srapply pos_peano_ind.\n  { intros f H a.\n    symmetry.\n    apply eissect. }\n  hnf; intros n p f H a.\n  rewrite int_neg_pos_succ.\n  refine (ap (fun x => _ x _) _ @ _).\n  1: exact (eisretr int_succ (neg n)).\n  cbn; rewrite pos_add_1_r.\n  rewrite pos_iter_succ_r.\n  rewrite eissect.\n  reflexivity.\n+ cbn.\n  rewrite pos_add_1_r.\n  srapply pos_iter_succ_r.\nQed.\n\nDefinition iter_int_pred_l {A} (f : A -> A) `{IsEquiv _ _ f}\n  (n : Int) (a : A)\n: int_iter f (int_pred n) a = f^-1 (int_iter f n a).\nProof.\n  destruct n as [n| |n]; trivial.\n  + cbn; rewrite pos_add_1_r.\n    by rewrite pos_iter_succ_l.\n  + revert n.\n    srapply pos_peano_ind.\n    - cbn; symmetry; apply eissect.\n    - hnf; intros p q.\n      rewrite <- pos_add_1_r.\n      change (int_pred (pos (p + 1)%pos))\n        with (int_pred (int_succ (pos p))).\n      rewrite int_pred_succ.\n      change (pos (p + 1)%pos)\n        with (int_succ (pos p)).\n      rewrite int_iter_succ_l.\n      symmetry.\n      apply eissect.\nQed.\n\nDefinition iter_int_pred_r {A} (f : A -> A) `{IsEquiv _ _ f}\n  (n : Int) (a : A)\n: int_iter f (int_pred n) a = int_iter f n (f^-1 a).\nProof.\n  revert f H n a.\n  destruct n as [n| |n]; trivial;\n  induction n as [|n nH] using pos_peano_ind; trivial.\n  2: hnf; intros; apply symmetry, eisretr.\n  all: rewrite <- pos_add_1_r.\n  all: intro a.\n  1: change (neg (n + 1)%pos) with (int_pred (neg n)).\n  2: change (pos (n + 1)%pos) with (int_succ (pos n)).\n  1: rewrite <- 2 int_neg_pos_succ.\n  1: cbn; apply pos_iter_succ_r.\n  rewrite int_pred_succ.\n  rewrite int_iter_succ_r.\n  rewrite eisretr.\n  reflexivity.\nQed.\n\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Spaces/Int/Equiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6582321898053143}}
{"text": "(* Lambda calculus workout *)\n\nRequire Import List.\nImport ListNotations.\nRequire Import Arith.\nRequire Import Id.\n\nFrom hahn Require Import HahnBase.\n\nRequire Import Coq.Relations.Relation_Operators.\n\nSection Lambda.\n\n(* Lambda term in regular named representation *)\nInductive term : Type := \n  Var  : id -> term\n| Abs  : id -> term -> term \n| App  : term -> term -> term.\n\n(* Notations and some examples *)\nNotation \"\\ x , .. , z --> t\" := (Abs x .. (Abs z t) .. ) (at level 38, no associativity).\nNotation \"m @ n\"              := (App m n) (at level 39, left associativity).\n\nDefinition f := 0.\nDefinition g := 1.\nDefinition h := 2.\n\nDefinition x := 3.\nDefinition y := 4.\n\nDefinition m := 5.\nDefinition n := 6.\n\nDefinition v i := Var i.\n           \nDefinition i     := \\ x --> v x.\nDefinition apply := \\ f, x --> (v f @ v x).\nDefinition z     := \\ f, x --> v x.\nDefinition s     := \\ n, f, x --> (v f @ (v n @ v f @ v x)).\nDefinition add   := \\ n, m, f, x --> (v m @ v f @ (v n @ v f @ v x)).\nDefinition mul   := \\ n, m, f, x --> (v m @ (v n @ v f) @ v x).\n\n(* Free variables*) \nInductive fv : id -> term -> Prop :=\n  fv_Var : forall x,  fv x (v x)\n| fv_Abs : forall x y t,  fv y t -> x <> y -> fv y (\\ x --> t)\n| fv_App : forall x a b,  (fv x a) \\/ (fv x b) -> fv x (a @ b).\n\nLemma fv_var: forall x y, fv x (v y) -> x = y.\nProof. admit. Admitted.\n\n(* Capture-avoiding substitution *)\nReserved Notation \"m [[ x <~ y ]] n\" (at level 40, left associativity).\n\nInductive cas : term -> id -> id -> term -> Prop :=\n  cas_Var : forall x y, (v x) [[x <~ y]] (v y)\n\n| cas_Var_neq : forall x y z (NEQ : x <> z), (v z) [[x <~ y]] (v z)\n\n| cas_App : forall m n m' n' x y \n                   (CASM : m [[ x <~ y ]] m')\n                   (CASN : n [[ x <~ y ]] n'),\n            (m @ n) [[ x<~ y ]] (m' @ n')\n\n| cas_Lam : forall m x y, (\\x --> m) [[ x <~ y ]] (\\x --> m)\n\n| cas_Lam_neq : forall m m' x y z\n                       (NEQX : z <> x) (NEQY : z <> y)\n                       (CASM : m [[ x<~ y ]] m'),\n                (\\ z --> m) [[ x <~ y ]] (\\z --> m')\n                \n| cas_Lam_ren : forall m m' m'' x y z\n                       (NFV : ~ fv z m)\n                       (CASM  : m [[ y <~ z ]] m')\n                       (CASM' : m' [[ x <~ y ]] m''),\n                (\\y --> m) [[ x <~ y ]] (\\z --> m'')\nwhere \"m [[ x <~ y ]] n\" := (cas m x y n).\n\n#[local]\nHint Constructors cas : ll.\n\n(* Some lemmas about CAS *)\nLemma cas_reflexive s x : s [[ x <~ x ]] s.\nProof. admit. Admitted.\n\nLemma cas_preserves x y z s s' (NEQX : z <> x) (NEQY : z <> y)\n      (CAS : s [[x <~ y ]] s') (FV : fv z s'):\n  fv z s.\nProof. admit. Admitted.\n\nLemma cas_renames_free s s' x y (NEQ : x <> y)\n      (CAS : s [[ x <~ y ]] s') :\n  ~ fv x s'.\nProof. admit. Admitted.\n\n(* Renaming of variables *)\nReserved Notation \"m [[ x <~ y ]]\" (at level 37, left associativity).\n\nFixpoint rename t x y :=\n  match t with\n  | Var z     => if id_eq_dec z x then v y else t\n  | \\ z --> m => if id_eq_dec z x then t else \\ z --> m [[x <~ y]]\n  | m @ n     => m [[x <~ y]] @ n [[x <~ y]]\n  end\nwhere \"m [[ x <~ y ]]\" := (rename m x y).\n\n(* Safety condition for renaming *)\nInductive safe : term -> id -> id -> Prop :=\n  safe_Var   : forall x y z (NEQ : x <> z),\n    safe (Var x) y z\n\n| safe_App   : forall m n x y (SAFEM : safe m x y) (SAFEN : safe n x y),\n    safe (m @ n) x y\n\n| safe_Lam_1 : forall m z y (NFV : ~ fv y m), safe (\\ z --> m) z y\n| safe_Lam_2 : forall m x y z (NEQY : y <> z) (NEQX : x <> z)\n                      (SAFEM : safe m x y),\n    safe (\\ z --> m) x y\n\n| safe_Lam_3 : forall m x z (NEQX : x <> z) (NFV : ~ fv x m),\n    safe (\\ z --> m) x z.\n\n(* Some lemmas about safety and renaming *)\nLemma safe_nfv m x y (SAFEM : safe m x y) : ~ fv y m.\nProof. admit. Admitted.\n\nLemma safe_fv_neq m x y z (SAFEM : safe m x y) (FV : fv z m) : y <> z.\nProof. admit. Admitted.\n\nLemma rename_not_fv m x z (NEQ : x <> z) : ~ fv x (m [[x <~ z]]).\nProof. admit. Admitted.\n\nLemma safe_reverse m x y (SAFEM : safe m x y) :\n  safe (m [[x <~ y]]) y x.\nProof. admit. Admitted.\n\n#[local]\nHint Resolve safe_reverse : ll.\n\nLemma rename_eq_eq m x : m [[ x <~ x]] = m.\nProof. admit. Admitted.\n  \nLemma rename_not_free_is_id m x y (FH : ~ fv x m) : m [[ x <~ y ]] = m.\nProof. admit. Admitted.\n\nLemma rename_reverse m x y (SH : safe m x y) : (m [[x <~ y]]) [[y <~ x]] = m.\nProof. admit. Admitted.\n\nLemma rename_preserves m x z y (FH : fv x m) (NEH : z <> x) : fv x (m [[ z <~ y ]]).\nProof. admit. Admitted.\n\nLemma rename_free_reverse x y z m (HXZ: x <> z) (HYZ: x <> y) (HFV: fv x (m [[ z <~ y]])) : fv x m.\nProof. admit. Admitted.\n\nLemma rename_if_free m x y z (HFV : fv x (m [[ y <~ z ]])) (HXZ : x <> z) : y <> x.\nProof. admit. Admitted.\n\n#[local]\nHint Resolve rename_reverse : ll.\n\n(* Contexts *)\nInductive Context : Set :=\n  CHole : Context\n| CAbs  : id -> Context -> Context\n| CAppL : Context -> term -> Context\n| CAppR : term -> Context -> Context.\n\n(* Substitution in a context *)\nFixpoint term_in_context (C : Context) (t : term) : term :=\n  match C with\n  | CHole     => t\n  | CAbs x c  => Abs x (term_in_context c t)\n  | CAppL c p => App (term_in_context c t) p\n  | CAppR p c => App p (term_in_context c t)\n  end.\n\n(* Some lemmas about contexts *)\nLemma fv_in_term_in_context\n      (C : Context) (m : term) (x : id) :\n      fv x (term_in_context C m) -> fv x (term_in_context C (\\ x --> v x)) \\/ fv x m.\nProof. admit. Admitted.\n\nLemma fv_in_context\n      (C : Context) (m : term) (x : id) :\n      fv x (term_in_context C (\\ x --> v x)) -> fv x (term_in_context C m).\nProof. admit. Admitted.\n\nLemma fv_in_another_term_in_context\n      (C : Context) (m n : term) (x : id) (FVM : fv x m) (FVC : fv x (term_in_context C m)) :\n      fv x n -> fv x (term_in_context C n).\nProof. admit. Admitted.\n\nLemma empty_context m n (H : term_in_context CHole m = n) : m = n.\nProof. admit. Admitted.\n\nLemma term_in_context_is_var m x C (H : term_in_context C m = v x) : C = CHole.\nProof. admit. Admitted.\n\n(* Alpha conversion *)\nReserved Notation \"m <~~> n\" (at level 38, no associativity).\n\n(* Alpha equivalence *)\nInductive alpha_equivalent : term -> term -> Prop :=\n| ae_Refl    : forall m, m <~~> m\n| ae_Rename  : forall m x y, safe m x y -> (\\ x --> m) <~~> (\\ y --> m [[ x <~ y ]])\n| ae_Subterm : forall C a b, a <~~> b -> term_in_context C a <~~> term_in_context C b \n| ae_Trans   : forall m n p, m <~~> n -> n <~~> p -> m <~~> p\nwhere \"m <~~> n\" := (alpha_equivalent m n).\n\n#[local]\nHint Constructors alpha_equivalent : ll.\n\nLemma alpha_equivalent_symm (m n : term) (HA : m <~~> n) : n <~~> m.\nProof. Admitted.\n\nEnd Lambda.\n", "meta": {"author": "semantics-classroom", "repo": "semantics-problems-dj-kostya", "sha": "d82830853a84c68320c851e9e67d9d9aecdc6f2f", "save_path": "github-repos/coq/semantics-classroom-semantics-problems-dj-kostya", "path": "github-repos/coq/semantics-classroom-semantics-problems-dj-kostya/semantics-problems-dj-kostya-d82830853a84c68320c851e9e67d9d9aecdc6f2f/src/Lambda.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.6582321885517547}}
{"text": "From Coq Require Import omega.Omega.\nFrom Coq Require Import Arith.Arith.\nFrom LF Require Import Imp Maps.\n\n(** Here was our first try at an evaluation function for commands,\n    omitting [WHILE]. *)\n\nOpen Scope imp_scope.\nFixpoint ceval_step1 (st : state) (c : com) : state :=\n  match c with\n    | SKIP =>\n        st\n    | l ::= a1 =>\n        (l !-> aeval st a1 ; st)\n    | c1 ;; c2 =>\n        let st' := ceval_step1 st c1 in\n        ceval_step1 st' c2\n    | TEST 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  (* bogus *)\n  end.\nClose Scope imp_scope.\n(*然而这样的定义不会被Coq接受，因为任何有可能不会停机的函数都会被Coq拒绝*)\n(*一个改进技巧是将一个附加参数传入求值函数中来告诉它要运行多久*)\nOpen Scope imp_scope.\nFixpoint ceval_step2 (st : state) (c : com) (i : nat) : state :=\n  match i with\n  | O => empty_st\n  | S i' =>\n    match c with\n      | SKIP =>\n          st\n      | l ::= a1 =>\n          (l !-> aeval st a1 ; st)\n      | c1 ;; c2 =>\n          let st' := ceval_step2 st c1 i' in\n          ceval_step2 st' c2 i'\n      | TEST 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.\nClose Scope imp_scope.\n\n(*为了区分正常停机和异常停机,将返回参数由state替换为option state*)\nOpen Scope imp_scope.\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 (l !-> aeval st a1 ; st)\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      | TEST 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.\nClose Scope imp_scope.\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\nOpen Scope imp_scope.\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 (l !-> aeval st a1 ; st)\n      | c1 ;; c2 =>\n          LETOPT st' <== ceval_step st c1 i' IN\n          ceval_step st' c2 i'\n      | TEST 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.\nClose Scope imp_scope.\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\nCompute\n     (test_ceval empty_st\n         (X ::= 2;;\n          TEST (X <= 1)\n            THEN Y ::= 3\n            ELSE Z ::= 4\n          FI)).\n(*   ====>\n      Some (2, 0, 4)   *)\n\n(** **** Exercise: 2 stars, standard, recommended (pup_to_n)  \n\n    Write an Imp program that sums the numbers from [1] to\n   [X] (inclusive: [1 + 2 + ... + X]) in the variable [Y].  Make sure\n   your solution satisfies the test that follows. *)\n\nDefinition pup_to_n : com :=\n   (X ::= X;;\n    WHILE ~(X = 0)\n    DO Y ::=Y+X;;\n       X ::= X-1\n    END).\n    \nExample pup_to_n_1 :\n  test_ceval (X !-> 5) pup_to_n\n  = Some (0, 15, 0).\nProof. reflexivity. Qed.\n\n\n(** **** Exercise: 2 stars, standard, optional (peven)  *)\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 evenb_or_not : com :=\n   (X ::= X;;\n   WHILE ~(X <= 2)\n    DO X ::= X-2\n    END;;\n    TEST (X=0)\n        THEN Z ::= 0\n        ELSE Z ::= 1\n    FI).\n\nExample pup_to_n_2 :\n  test_ceval (X !-> 5) evenb_or_not\n  = Some (1, 0, 1).\nProof. reflexivity. Qed.\n\n\n(* ################################################################# *)\n(** * Relational vs. Step-Indexed Evaluation *)\n\nTheorem ceval_step__ceval: forall c st st',\n      (exists i, ceval_step st c i = Some st') ->\n      st =[ c ]=> 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  - (* i = 0 -- contradictory *)\n    intros c st st' H. discriminate H.\n\n  - (* i = S i' *)\n    intros c st st' H.\n    destruct c;\n           simpl in H; inversion H; subst; clear H.\n      + (* SKIP *) apply E_Skip.\n      + (* ::= *) apply E_Ass. reflexivity.\n\n      + (* ;; *)\n        destruct (ceval_step st c1 i') eqn:Heqr1.\n        * (* 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        * (* Otherwise -- contradiction *)\n          discriminate H1.\n\n      + (* TEST *)\n        destruct (beval st b) eqn:Heqr.\n        * (* r = true *)\n          apply E_IfTrue. rewrite Heqr. reflexivity.\n          apply IHi'. assumption.\n        * (* r = false *)\n          apply E_IfFalse. rewrite Heqr. reflexivity.\n          apply IHi'. assumption.\n\n      + (* WHILE *) destruct (beval st b) eqn :Heqr.\n        * (* r = true *)\n         destruct (ceval_step st c i') eqn:Heqr1.\n         { (* r1 = Some s *)\n           apply E_WhileTrue with s. rewrite Heqr.\n           reflexivity.\n           apply IHi'. rewrite Heqr1. reflexivity.\n           apply IHi'. simpl in H1. assumption. }\n         { (* r1 = None *) discriminate H1. }\n        * (* r = false *)\n          injection H1. intros H2. rewrite <- H2.\n          apply E_WhileFalse. apply Heqr. Qed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_ceval_step__ceval_inf : option (nat*string) := None.\n(** [] *)\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.\ninduction i1 as [|i1']; intros i2 st st' c Hle Hceval.\n  - (* i1 = 0 *)\n    simpl in Hceval. discriminate Hceval.\n  - (* i1 = S i1' *)\n    destruct i2 as [|i2']. inversion Hle.\n    assert (Hle': i1' <= i2') by omega.\n    destruct c.\n    + (* SKIP *)\n      simpl in Hceval. inversion Hceval.\n      reflexivity.\n    + (* ::= *)\n      simpl in Hceval. inversion Hceval.\n      reflexivity.\n    + (* ;; *)\n      simpl in Hceval. simpl.\n      destruct (ceval_step st c1 i1') eqn:Heqst1'o.\n      * (* st1'o = Some *)\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      * (* st1'o = None *)\n        discriminate Hceval.\n\n    + (* TEST *)\n      simpl in Hceval. simpl.\n      destruct (beval st b); apply (IHi1' i2') in Hceval;\n        assumption.\n\n    + (* WHILE *)\n      simpl in Hceval. simpl.\n      destruct (beval st b); try assumption.\n      destruct (ceval_step st c i1') eqn: Heqst1'o.\n      * (* st1'o = Some *)\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      * (* i1'o = None *)\n        simpl in Hceval. discriminate Hceval.  Qed.\n\n(** **** Exercise: 3 stars, standard, recommended (ceval__ceval_step) *)\n\nLemma i1_leq_i1i2 :forall i1 i2,\n  i1<=i1+i2.\nProof.\n  induction i2.\n  -rewrite<-plus_n_O. reflexivity.\n  -rewrite plus_comm. simpl. apply le_S. rewrite plus_comm. apply IHi2.\nQed.\nTheorem ceval__ceval_step: forall c st st',\n      st =[ c ]=> st' ->\n      exists i, ceval_step st c i = Some st'.\nProof.\n  intros c st st' Hce.\n  induction Hce.\n  -exists 1. reflexivity.\n  -exists 1. simpl;rewrite H; reflexivity.\n  -destruct IHHce1 as [i1 H1]. destruct IHHce2 as [i2 H2].\n   exists (1+i1+i2). simpl.  \n   destruct (ceval_step st c1 (i1 + i2)) eqn: Heqst1.\n   +assert (H1': ceval_step st c1 (i1+i2) =Some st'). {\n    apply ceval_step_more with (i1:=i1) (i2:= i1+i2).\n    *apply i1_leq_i1i2.\n    *apply H1. }\n    assert (H': s=st'). { rewrite Heqst1 in H1'. \n     inversion H1'. reflexivity. }\n     subst.\n    apply(ceval_step_more i2 (i1+i2)).\n     *rewrite plus_comm. apply i1_leq_i1i2.\n     *apply H2.\n   +assert (H1': ceval_step st c1 (i1+i2) =Some st'). {\n    apply ceval_step_more with (i1:=i1) (i2:= i1+i2).\n    *apply i1_leq_i1i2.\n    *apply H1. }\n    rewrite H1' in Heqst1. inversion Heqst1.\n  -destruct IHHce as [i H1]. exists (1+i). simpl.\n   rewrite H. apply H1.\n  -destruct IHHce as [i H1]. exists (1+i). simpl.\n   rewrite H. apply H1.\n  -exists 1. simpl. rewrite H. reflexivity.\n  -destruct IHHce1 as [i1 H1]. destruct IHHce2 as [i2 H2].\n   exists (1+i1+i2). simpl.\n   rewrite H.\n   assert (H1': ceval_step st c (i1+i2) =Some st'). {\n    apply ceval_step_more with (i1:=i1) (i2:= i1+i2).\n    *apply i1_leq_i1i2.\n    *apply H1. }\n   rewrite H1'.\n   rewrite plus_comm.\n   apply (ceval_step_more i2 (i2+i1)) . \n    *apply i1_leq_i1i2.\n    *apply H2.\nQed. \nTheorem ceval_and_ceval_step_coincide: forall c st st',\n      st =[ c ]=> 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\n(* ################################################################# *)\n(** * Determinism of Evaluation Again *)\n\nTheorem ceval_deterministic' : forall c st st1 st2,\n     st =[ c ]=> st1 ->\n     st =[ c ]=> st2 ->\n     st1 = st2.\nProof.\n  intros c st st1 st2 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.  Qed.\n\n(* Wed Jan 9 12:02:46 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/ImpCEvalFun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928951399098, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.6582321872981947}}
{"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(** Properties of the power function *)\n\nRequire Import Bool NAxioms NSub NParity NZPow.\n\n(** Derived properties of power, specialized on natural numbers *)\n\nModule Type NPowProp\n (Import A : NAxiomsSig')\n (Import B : NSubProp A)\n (Import C : NParityProp A B).\n\n Module Import NZPowP := Nop <+ NZPowProp A A B.\n\nLtac auto' := trivial; try rewrite <- neq_0_lt_0; auto using le_0_l.\nLtac wrap l := intros; apply l; auto'.\n\nLemma pow_succ_r' : forall a b, a^(S b) == a * a^b.\nProof. wrap pow_succ_r. Qed.\n\n(** Power and basic constants *)\n\nLemma pow_0_l : forall a, a~=0 -> 0^a == 0.\nProof. wrap pow_0_l. Qed.\n\nDefinition pow_1_r : forall a, a^1 == a\n := pow_1_r.\n\nLemma pow_1_l : forall a, 1^a == 1.\nProof. wrap pow_1_l. Qed.\n\nDefinition pow_2_r : forall a, a^2 == a*a\n := pow_2_r.\n\n(** Power and addition, multiplication *)\n\nLemma pow_add_r : forall a b c, a^(b+c) == a^b * a^c.\nProof. wrap pow_add_r. Qed.\n\nLemma pow_mul_l : forall a b c, (a*b)^c == a^c * b^c.\nProof. wrap pow_mul_l. Qed.\n\nLemma pow_mul_r : forall a b c, a^(b*c) == (a^b)^c.\nProof. wrap pow_mul_r. Qed.\n\n(** Power and nullity *)\n\nLemma pow_eq_0 : forall a b, b~=0 -> a^b == 0 -> a == 0.\nProof. intros. apply (pow_eq_0 a b); trivial. auto'. Qed.\n\nLemma pow_nonzero : forall a b, a~=0 -> a^b ~= 0.\nProof. wrap pow_nonzero. Qed.\n\nLemma pow_eq_0_iff : forall a b, a^b == 0 <-> b~=0 /\\ a==0.\nProof.\n intros a b. split.\n rewrite pow_eq_0_iff. intros [H |[H H']].\n  generalize (le_0_l b); order. split; order.\n intros (Hb,Ha). rewrite Ha. now apply pow_0_l'.\nQed.\n\n(** Monotonicity *)\n\nLemma pow_lt_mono_l : forall a b c, c~=0 -> a<b -> a^c < b^c.\nProof. wrap pow_lt_mono_l. Qed.\n\nLemma pow_le_mono_l : forall a b c, a<=b -> a^c <= b^c.\nProof. wrap pow_le_mono_l. Qed.\n\nLemma pow_gt_1 : forall a b, 1<a -> b~=0 -> 1<a^b.\nProof. wrap pow_gt_1. Qed.\n\nLemma pow_lt_mono_r : forall a b c, 1<a -> b<c -> a^b < a^c.\nProof. wrap pow_lt_mono_r. Qed.\n\n(** NB: since 0^0 > 0^1, the following result isn't valid with a=0 *)\n\nLemma pow_le_mono_r : forall a b c, a~=0 -> b<=c -> a^b <= a^c.\nProof. wrap pow_le_mono_r. Qed.\n\nLemma pow_le_mono : forall a b c d, a~=0 -> a<=c -> b<=d ->\n a^b <= c^d.\nProof. wrap pow_le_mono. Qed.\n\nDefinition pow_lt_mono : forall a b c d, 0<a<c -> 0<b<d ->\n a^b < c^d\n := pow_lt_mono.\n\n(** Injectivity *)\n\nLemma pow_inj_l : forall a b c, c~=0 -> a^c == b^c -> a == b.\nProof. intros; eapply pow_inj_l; eauto; auto'. Qed.\n\nLemma pow_inj_r : forall a b c, 1<a -> a^b == a^c -> b == c.\nProof. intros; eapply pow_inj_r; eauto; auto'. Qed.\n\n(** Monotonicity results, both ways *)\n\nLemma pow_lt_mono_l_iff : forall a b c, c~=0 ->\n  (a<b <-> a^c < b^c).\nProof. wrap pow_lt_mono_l_iff. Qed.\n\nLemma pow_le_mono_l_iff : forall a b c, c~=0 ->\n  (a<=b <-> a^c <= b^c).\nProof. wrap pow_le_mono_l_iff. Qed.\n\nLemma pow_lt_mono_r_iff : forall a b c, 1<a ->\n  (b<c <-> a^b < a^c).\nProof. wrap pow_lt_mono_r_iff. Qed.\n\nLemma pow_le_mono_r_iff : forall a b c, 1<a ->\n  (b<=c <-> a^b <= a^c).\nProof. wrap pow_le_mono_r_iff. Qed.\n\n(** For any a>1, the a^x function is above the identity function *)\n\nLemma pow_gt_lin_r : forall a b, 1<a -> b < a^b.\nProof. wrap pow_gt_lin_r. Qed.\n\n(** Someday, we should say something about the full Newton formula.\n    In the meantime, we can at least provide some inequalities about\n    (a+b)^c.\n*)\n\nLemma pow_add_lower : forall a b c, c~=0 ->\n  a^c + b^c <= (a+b)^c.\nProof. wrap pow_add_lower. Qed.\n\n(** This upper bound can also be seen as a convexity proof for x^c :\n    image of (a+b)/2 is below the middle of the images of a and b\n*)\n\nLemma pow_add_upper : forall a b c, c~=0 ->\n  (a+b)^c <= 2^(pred c) * (a^c + b^c).\nProof. wrap pow_add_upper. Qed.\n\n(** Power and parity *)\n\nLemma even_pow : forall a b, b~=0 -> even (a^b) = even a.\nProof.\n intros a b Hb. rewrite neq_0_lt_0 in Hb.\n apply lt_ind with (4:=Hb). solve_proper.\n now nzsimpl.\n clear b Hb. intros b Hb IH.\n rewrite pow_succ_r', even_mul, IH. now destruct (even a).\nQed.\n\nLemma odd_pow : forall a b, b~=0 -> odd (a^b) = odd a.\nProof.\n intros. now rewrite <- !negb_even, even_pow.\nQed.\n\nEnd NPowProp.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/Numbers/Natural/Abstract/NPow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.6582321737954908}}
{"text": "Require Import List.\nExport ListNotations.\nRequire Import PeanoNat.\nRequire Import Ensembles.\n\nDelimit Scope My_scope with M.\nOpen Scope My_scope.\nSet Implicit Arguments.\n\nGlobal Parameter V : Set.\n\nParameter eq_dec_propvar : forall p q : V, {p = q}+{p <> q}.\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(* Definitions Language *)\n\n(* First, let us define the propositional formulas we use here. *)\n\nInductive MPropF : Type :=\n | Var : V -> MPropF\n | Bot : MPropF\n | Imp : MPropF -> MPropF -> MPropF\n | Box : MPropF -> MPropF\n.\n\nNotation \"# p\" := (Var p) (at level 1).\nNotation \"A --> B\" := (Imp A B) (at level 16, right associativity).\n\nFixpoint subform (φ : MPropF) : Ensemble MPropF :=\nmatch φ with\n| Var p => Singleton _ (Var p)\n| Bot => Singleton _ Bot\n| Imp ψ χ => Union _ (Singleton _ (Imp ψ χ))\n(Union _ (subform ψ) (subform χ))| Box ψ => Union _ (Singleton _ (Box ψ)) (subform ψ)\nend.\n\nFixpoint subformlist (φ : MPropF) : list MPropF :=\nmatch φ with\n| Var p => (Var p) :: nil\n| Bot => Bot :: nil\n| Imp ψ χ => (Imp ψ χ) :: (subformlist ψ) ++ (subformlist χ)\n| Box ψ => (Box ψ) :: (subformlist ψ)\nend.\n\nDefinition Neg (A : MPropF) := Imp A (Bot).\n\nFixpoint Box_power (n : nat) (A : MPropF) : MPropF :=\nmatch n with\n | 0 => A\n | S m => Box (Box_power m A)\nend.\n\nFixpoint Imp_Box_power (n : nat) (A B : MPropF) : MPropF :=\nmatch n with\n | 0 => A --> B\n | S m => A --> (Imp_Box_power m (Box A) B)\nend.\n\nInductive Box_clos_set (Γ : @Ensemble MPropF): @Ensemble MPropF :=\n  | InitClo : forall A, In _ Γ A -> Box_clos_set Γ A\n  | IndClo : forall A,  Box_clos_set Γ A -> Box_clos_set Γ (Box A).\n\nLemma eq_dec_form : forall x y : MPropF, {x = y}+{x <> y}.\nProof.\ninduction x.\n- intros. destruct y.\n  * pose (eq_dec_propvar v v0). destruct s. left. subst. reflexivity.\n    right. intro. inversion H. apply n. auto.\n  * right. intro. inversion H.\n  * right. intro. inversion H.\n  * right. intro. inversion H.\n- intros. destruct y.\n  * right. intro. inversion H.\n  * auto.\n  * right. intro. inversion H.\n  * right. intro. inversion H.\n- intros. destruct y.\n  * right. intro. inversion H.\n  * right. intro. inversion H.\n  * pose (IHx1 y1). pose (IHx2 y2). destruct s. destruct s0. subst. left. reflexivity.\n    right. intro. inversion H. apply n. assumption. right. intro. inversion H. apply n. auto.\n  * right. intro. inversion H.\n- intros. destruct y.\n  * right. intro. inversion H.\n  * right. intro. inversion H.\n  * right. intro. inversion H.\n  * pose (IHx y). destruct s. subst. left. reflexivity.\n    right. intro. inversion H. apply n. assumption.\nQed.\n\n\n\nFixpoint size (φ : MPropF) : nat :=\nmatch φ with\n| Var p => 1| Bot => 1\n| Imp ψ χ => 1 + (size ψ) + (size χ) | Box ψ => 1 + (size ψ)\nend.\n\nFixpoint subst (σ : V -> MPropF) (φ : MPropF) : MPropF :=\nmatch φ with\n| Var p => (σ p)\n| Bot => Bot\n| Imp ψ χ => Imp (subst σ ψ) (subst σ χ)| Box ψ => Box (subst σ ψ)\nend.\n\nDefinition is_atomicT (A : MPropF) : Type :=\n                  (exists (p : V), A = # p) + (A = Bot).\n\nDefinition is_Atomic (Γ : @Ensemble MPropF) : Type :=\n    forall (A : MPropF), (Γ A) -> ((exists (p : V), A = # p) + (A = Bot)).\n\nFixpoint list_Imp (A : MPropF) (l : list MPropF) : MPropF :=\nmatch l with\n | nil => A\n | h :: t => h --> (list_Imp A t)\nend.\n\nFixpoint Box_list (l : list MPropF) : list MPropF :=\nmatch l with\n | nil => nil\n | h :: t => (Box h) :: (Box_list t)\nend.\n\n\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/Syntax/K_Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6582182086622065}}
{"text": "(** Taken from https://gist.github.com/poizan42/c7017e66f921783c0e52\n    with minor modifications. *)\n\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.ZArith.Znumtheory.\nRequire Import Coq.Sets.Ensembles.\nRequire Import Coq.Sets.Finite_sets.\nRequire Import Coq.PArith.BinPos.\nFrom Coq Require Import Lia.\n\nDefinition Z_ens := Ensemble Z.\n(* Print Finite. *)\n(* Print Empty_set. *)\nDefinition is_empty_set U A := forall x, ~(In U A x).\nInductive Finite' (U : Type) : Ensemble U -> Prop :=\n    Empty_is_finite' : forall A : Ensemble U, \n                      is_empty_set U A -> Finite' U A\n  | Union_is_finite' : forall A : Ensemble U,\n                      Finite' U A ->\n                      forall x : U, ~ In U A x -> Finite' U (Add U A x).\n\nLemma finite_to_finite' : forall (U: Type) (A: Ensemble U),\n  Finite U A -> Finite' U A.\nProof.\n  intros.\n  induction H.\n  apply Empty_is_finite'.\n  unfold is_empty_set.\n  intros.\n  firstorder.\n  apply Union_is_finite'.\n  firstorder.\n  exact H0.\nQed.\n\nLemma finite'_empty_cases : forall (U: Type) (A: Ensemble U),\n  Finite' U A -> is_empty_set U A \\/ ~(is_empty_set U A).\nProof.\n  intros.\n  induction H.\n  left.\n  exact H.\n  right.\n  unfold not; intros.\n  absurd (In U (Add U A x) x).\n  firstorder.\n  intuition.\nQed.\n\nLemma finite'_ne_inhabited : forall (U: Type) (A: Ensemble U),\n  Finite' U A -> ~(is_empty_set U A) -> exists x, In U A x.\nProof.\n  intros U A A_finite A_nonempty.\n  induction A_finite.\n  firstorder.\n  exists x.\n  intuition.\nQed.\n\nLemma Zdivide_Zabs_r a b : (a | b) -> (a | Z.abs b).\nProof.\n  intros.\n  elim Z.abs_eq_or_opp with (n := b).\n  intros.\n  rewrite H0.\n  exact H.\n  intros.\n  rewrite H0.\n  apply Zdivide_opp_r.\n  exact H.\nQed.\n\nLemma Zdivide_Zabs_inv_r a b : (a | Z.abs b) -> (a | b).\nProof.\n  intros.\n  elim Z.abs_eq_or_opp with (n := b).\n  intros.\n  rewrite <- H0.\n  exact H.\n  intros.\n  apply Zdivide_opp_r_rev.\n  rewrite <- H0.\n  exact H.\nQed.\n\nLemma mul_fin_set_divides : forall A:Z_ens,\n  Finite' Z A -> (forall m:Z, In Z A m -> m <> 0) ->\n    exists n:Z, n > 0 /\\ forall m:Z, (In Z A m -> (m | n)).\nProof.\n  intros A A_finite.\n  apply Finite'_ind with (P := fun U =>\n    (forall m:Z, In Z U m -> m <> 0) ->\n    exists n:Z, n > 0 /\\ forall m : Z, In Z U m -> (m | n)).\n  (* Induction start *)\n  intros A0 A0_empty _.\n  exists 1.\n  split.\n  firstorder.\n  intros m H.\n  absurd (In Z A0 m).\n  apply A0_empty.\n  exact H.\n  (* Induction step *)\n  intros A0 A0_finite IH n_add n0_nin_A0 A0_nonzero.\n  elim IH.\n  intros n_mul IHdivides.\n  clear IH.\n  exists (n_mul * Z.abs n_add).\n  split.\n  apply Z.lt_gt.\n  apply Z.mul_pos_pos.\n  intuition.\n  apply Z.abs_pos.\n  { apply A0_nonzero; right; constructor. }\n  intros.\n  compare m n_add.\n    (* m = n_add *)\n    intros m_eq_n_mul.\n    rewrite m_eq_n_mul.\n    apply Z.divide_mul_r.\n    apply Zdivide_Zabs_r.\n    intuition.\n    (* m <> n_add *)\n    intros.\n    apply Z.divide_mul_l.\n    inversion H.\n    apply IHdivides.\n    exact H0.\n    inversion H0.\n    { apply IHdivides.\n      inversion H; subst; auto.\n      intuition. }\n    apply Pos.eq_dec.\n    apply Pos.eq_dec.\n  intros m m_in_A0.\n  apply A0_nonzero.\n  intuition.\n  exact A_finite.\nQed.\n\nLemma ex_rel_prime : forall P:Z_ens,\n  (Finite' Z P /\\ forall p:Z, In Z P p -> prime p) ->\n  exists n:Z, n > 1 /\\ (forall p:Z, In Z P p -> rel_prime p n).\nProof.\n  intros P H.\n  inversion H as [P_finite P_primes].\n  clear H.\n  elim finite'_empty_cases with (A := P).\n  intros P_empty.\n  exists 2.\n  { split; try lia.\n    intros p Hp.\n    apply rel_prime_le_prime.\n    { apply prime_2. }\n    firstorder. }\n  intros P_inhabited.\n  apply finite'_ne_inhabited in P_inhabited.\n  elim mul_fin_set_divides with (A := P).\n  intros n all_divides'.\n  inversion all_divides' as [n_pos all_divides]; clear all_divides'.\n  exists (n+1).\n  split.\n  intuition.\n  \n  intros p p_in_P.\n  pose proof p_in_P as prime_p.\n  apply P_primes in prime_p.\n  (* Show that p is positive *)\n  pose proof prime_p as prime_p'.\n  apply prime_alt in prime_p'.\n  unfold prime' in prime_p'.\n  inversion prime_p' as [p_geq_1 _].\n  clear prime_p'.\n\n  assert (n mod p = 0) as n_mod_p_eq_0.\n    apply Zdivide_mod; apply all_divides; apply p_in_P.\n  assert ((n+1) mod p = 1) as np1_mod_p_eq_1.\n    assert (1 mod p = 1) as one_mod_p_eq_1.\n    apply Zmod_1_l; exact p_geq_1.\n    rewrite <- one_mod_p_eq_1 at 2; clear one_mod_p_eq_1.\n    rewrite Zplus_mod.\n    rewrite n_mod_p_eq_0.\n    rewrite Z.add_0_l.\n    rewrite Zmod_mod.\n    apply eq_refl.\n  apply rel_prime_sym.\n  apply rel_prime_mod_rev.\n  { lia. }\n  rewrite np1_mod_p_eq_1.\n  apply rel_prime_1.\n  exact P_finite.\n  intros p p_in_P.\n  { intuition; subst.\n    apply P_primes in p_in_P.\n    apply not_prime_0; auto. }\n  exact P_finite.\n  exact P_finite.\nQed.\n\nLemma ex_maximal_element : forall (A : Ensemble Z), Finite' Z A ->\n  (exists m, In Z A m) ->\n  exists N, In Z A N /\\ (forall n, In Z A n -> n <= N).\n\nProof.\n  intros A A_is_finite.\n  (* Check Finite'_ind. *)\n  apply Finite'_ind with (P :=\n    fun A => (exists m, In Z A m) ->\n      exists N : Z, In Z A N /\\ (forall n : Z, In Z A n -> n <= N)).\n  (* Induction start, A0: empty set *)\n  clear A A_is_finite; intros.\n  firstorder.\n  (* Induction step *)\n  clear A A_is_finite;\n    intros A0 A0_finite A0_ME_exists' n_add n_add_new add_non_empty.\n  clear add_non_empty.\n  \n  (* - A0 is either empty or non-empty - *)\n  inversion A0_finite as [A0_empty | A1 A1_finite n' n'_nin_A1 A1_A0_rel].\n  (* A0 is empty, the new element must be the maximal element, as it's\n   * the only element. *)\n  exists n_add.\n  split.\n  apply Union_intror.\n  firstorder.\n  intros n0 n0_in_Znew.\n  inversion n0_in_Znew.\n  unfold is_empty_set in H.\n  firstorder.\n  inversion H1.\n  intuition.\n  (* A0 is non-empty, it contains n' *)\n  assert (exists m : Z, In Z A0 m) as A0_non_empty.\n  exists n'.\n  inversion A1_A0_rel.\n  apply Union_intror.\n  apply In_singleton.\n  (* Get rid of the knowledge of the extra element *)\n  rewrite A1_A0_rel.\n  clear A1 n' A1_finite n'_nin_A1 A1_A0_rel.\n\n  (* Use our knowledge to get a useful induction hypothesis. *)\n  apply A0_ME_exists' in A0_non_empty.\n  rename A0_non_empty into A0_ME_exists.\n  clear A0_ME_exists'.\n  elim A0_ME_exists.\n  clear A0_ME_exists.\n  intros n0 n0_is_ME.\n\n  inversion n0_is_ME as [n0_in_A0 n0_is_UB]; clear n0_is_ME.\n  (* The actual element we claim is the maximal element is max(n_add, n0)*)\n  exists (Z.max n_add n0).\n  split.\n\n  (** Show that the element is in A **)\n  elim Z.lt_total with (n := n_add) (m := n0).\n  (* n_add < n0 *)\n  intros.\n  rewrite Z.max_r.\n  apply Union_introl.\n  exact n0_in_A0.\n  intuition.\n  (* n_add = n0 \\/ n0 < n_add *)\n  intros.\n  elim H; clear H.\n  (* n_add = n0 *)\n  intros.\n  rewrite <- H in n0_in_A0.\n  contradiction.\n  (* n0 < n_add *)\n  intros.\n  rewrite Z.max_l.\n  apply Union_intror.\n  firstorder.\n  intuition.\n  \n  (** Show that the element is an upper bound **)\n  intros n n_in_Anew.\n  elim Z.lt_total with (n := n_add) (m := n0).\n  (* n_add < n0 *)\n  intros.\n  compare n n_add.\n  (* n = n_add *)\n  intros n_eq_n_add.\n  rewrite Z.max_r.\n  intuition.\n  intuition.\n  (* n <> n_add *)\n  intros n_neq_n_add.\n  rewrite Z.max_r.\n  apply n0_is_UB.\n  inversion n_in_Anew.\n  trivial.\n  inversion H0.\n  exfalso.\n  firstorder.\n  intuition.\n  apply Pos.eq_dec.\n  apply Pos.eq_dec.\n  (* n_add = n0 \\/ n0 < n_add  *)\n  intros.\n  elim H.\n  (* n_add = n0 *)\n  clear H.\n  intros.\n  rewrite <- H in n0_in_A0.\n  contradiction.\n  (* n0 < n_add *)\n  clear H.\n  intros.\n  rewrite Z.max_l.\n  inversion n_in_Anew; clear x H1.\n  { apply n0_is_UB in H0; lia. }\n  inversion H0.\n  intuition.\n  intuition.\n  (* Finally A is finite *)\n  exact A_is_finite.\nQed.\n\nDefinition all_primes_leq (ub: Z) : Ensemble Z :=\n  fun p: Z => p <= ub /\\ prime p.\n\nLemma all_primes_leq_finite : forall ub, Finite' Z (all_primes_leq ub).\n\nProof.\n  assert (forall p:Z, p <= 1 -> Finite' Z (all_primes_leq p)) as\n    no_primes_finite.\n  intros.\n  apply Empty_is_finite'.\n  unfold is_empty_set; intros n.\n  unfold not; intros n_in_apleq_p.\n  inversion n_in_apleq_p as [n_leq_p n_prime].\n  inversion n_prime as [n_geq_1 _].\n  intuition.\n\n  intros.\n  induction ub.\n  (* n = 0 *)\n  apply no_primes_finite.\n  intuition.\n  (* n > 0 *)\n  apply Pos.peano_ind with (P :=\n    fun n => Finite' Z (all_primes_leq (Z.pos n))).\n  (* n = 1 *)\n  apply no_primes_finite.\n  intuition.\n  (* n > 1, induction step *)\n  intros n0 IH.\n  set (n := Z.pos (Pos.succ n0)).\n  assert (n = Z.succ (Z.pos n0)) as n_eq_succ_n0.\n    rewrite <- Pos2Z.inj_succ.\n    trivial.\n  assert (n > Z.pos n0) as n_geq_n0.\n    rewrite n_eq_succ_n0.\n    apply Z.lt_gt.\n    apply Z.lt_succ_diag_r.\n\n  elim prime_dec with (p := n).\n  (* n is prime *)\n  intros n_prime.\n  replace (all_primes_leq n) with (Add Z (all_primes_leq (Z.pos n0)) n).\n  apply Union_is_finite'.\n  assumption.\n  unfold not, In; intros H.\n  inversion H as [n_leq_n0 _].\n  firstorder.\n  apply Extensionality_Ensembles.\n  split.\n  split.\n  (* inclusion new set -> all_primes_leq *)\n  (* Proof that x <= n *)\n    inversion H as [_1 x_in_apl _2 | _1 x_is_n _2].\n    clear _1 _2 H.\n    (* Case In Z (all_primes_leq (Z.pos n0)) x *)\n    inversion x_in_apl as [x_leq_n0 _].\n    apply Zgt_asym.\n    apply Zgt_le_trans with (m := Z.pos n0).\n    exact n_geq_n0.\n    exact x_leq_n0.\n    clear _1 _2 H.\n    (* Case In Z (Singleton Z n) x *)\n    inversion x_is_n as [n_eq_x].\n    apply Z.le_refl.\n  (* Proof that x is prime *)\n    inversion H as [_1 x_in_apl _2 | _1 x_is_n _2].\n    clear _1 _2 H.\n    inversion x_in_apl as [_ x_is_prime].\n    exact x_is_prime.\n    clear _1 _2 H.\n    inversion x_is_n.\n    exact n_prime.\n  (* inclusion all_primes_leq -> new set *)\n  unfold Included.\n  intros x x_in_apl.\n  inversion x_in_apl as [x_leq_n x_prime].\n  clear x_in_apl.\n  compare x n.\n    (* x = n *)\n    intros x_eq_n.\n    apply Union_intror.\n    rewrite x_eq_n.\n    apply In_singleton.\n    (* x <> n *)\n    intros x_neq_n.\n    apply Union_introl.\n    split.\n    (* Show x <= Z.pos n0 *)\n    apply Zgt_succ_le.\n    rewrite <- n_eq_succ_n0.\n    apply Z.lt_gt.\n    elim not_Zeq with (n := x) (m := n).\n    trivial.\n    intros n_lt_x.\n    apply Z.lt_gt in n_lt_x.\n    contradiction.\n    exact x_neq_n.\n    (* show x is prime *)\n    exact x_prime.\n    apply Pos.eq_dec.\n    apply Pos.eq_dec.\n\n  (* n is not prime *)\n  intros n_neq_prime.\n  replace (all_primes_leq n) with (all_primes_leq (Z.pos n0)).\n  exact IH.\n  apply Extensionality_Ensembles. \n  split.\n  (* In Z (all_primes_leq (Z.pos n0)) x -> In Z (all_primes_leq n) *)\n  split.\n  inversion H as [x_leq_n0 _].\n  apply Zgt_asym.\n  apply Zgt_le_trans with (m := Z.pos n0).\n  exact n_geq_n0.\n  exact x_leq_n0.\n  inversion H as [_ x_prime].\n  exact x_prime.\n  (* In Z (all_primes_leq n) -> In Z (all_primes_leq (Z.pos n0)) x *)\n  split.\n  inversion H as [x_leq_n x_prime].\n  compare x (Z.pos n0).\n  intros x_eq_n0.\n  apply Z.eq_le_incl.\n  exact x_eq_n0.\n  intros x_neq_n0.\n  apply Zgt_succ_le.\n  rewrite <- n_eq_succ_n0.\n  elim Zle_lt_or_eq with (n := x) (m := n).\n  apply Z.lt_gt.\n  intros x_eq_n.\n  rewrite x_eq_n in x_prime.\n  contradiction.\n  exact x_leq_n.\n  apply Pos.eq_dec.\n  apply Pos.eq_dec.\n  apply H.\n\n  (* At last show that the set of negative primes is finite\n    (because it's empty...)*)\n  apply no_primes_finite.\n  apply Z.lt_le_incl.\n  apply Z.lt_trans with (m := 0).\n  apply Zlt_neg_0.\n  apply Z.lt_0_1.\nQed.\n\nLemma ex_prime_divisor : forall n, n > 1 -> exists p, prime p /\\ (p | n).\n\nProof.\n  intros n n_pos.\n  induction n.\n  absurd (0 > 1).\n  intuition.\n  assumption.\n  (* Z.pos p > 0 *)\n  (* A suffienctly strong IH (total induction) *)\n  cut (forall n1, 1 < n1 <= Z.pos p -> exists p, prime p /\\ (p | n1)).\n  intros.\n  apply H.\n  split.\n  apply Z.gt_lt.\n  exact n_pos.\n  apply Z.le_refl.\n  apply Pos.peano_ind with (P := fun np =>\n    forall n1, 1 < n1 <= Z.pos np -> exists p, prime p /\\ (p | n1)).\n  intros.\n  exfalso.\n  intuition.\n\n  (* Induction \"step\" *)\n  intros p0 IH n1 n1_n2_rel.\n  set (n0 := Z.pos p0).\n  set (n2 := Z.pos (Pos.succ p0)).\n  fold n0 in IH.\n  fold n2 in n1_n2_rel.\n  elim prime_dec with (p := n1).\n  (* n1 is prime *)\n  intros n1_prime.\n  exists n1.\n  split.\n  exact n1_prime.\n  apply Z.divide_refl.\n  (* n1 is not prime *)\n  intros n1_nprime.\n  cut (exists n, 1 < n < n1 /\\ (n | n1)).\n  intros.\n  elim H; clear H.\n  intros n n_div_of_n1.\n  cut (exists p1, prime p1 /\\ (p1 | n)).\n  intros H.\n  elim H; clear H.\n  intros p2 p2_pf_of_n.\n  exists p2.\n  split.\n  apply p2_pf_of_n.\n  apply Z.divide_trans with (m := n).\n  apply p2_pf_of_n.\n  apply n_div_of_n1.\n  apply IH.\n  split.\n  firstorder.\n  assert (n2 = Z.succ n0) as n2_eq_n0p1.\n  unfold n2, n0.\n  rewrite Pos2Z.inj_succ. \n  apply eq_refl.\n  rewrite n2_eq_n0p1 in n1_n2_rel; clear n2_eq_n0p1 n2.\n  elim Z.le_succ_r with (n := n1) (m := n0).\n  intros H _.\n  inversion n1_n2_rel as [_ H0].\n  apply H in H0; clear H.\n  elim H0; clear H0.\n  (* case n1 <= n0 *)\n  intros n1_leq_n0.\n  apply Z.lt_le_incl.\n  apply Z.lt_le_trans with (m := n1).\n  apply n_div_of_n1.\n  exact n1_leq_n0.\n  (* case n1 = n0 + 1 *)\n  intros n1_eq_n0p1.\n  rewrite n1_eq_n0p1 in n_div_of_n1; clear n1_eq_n0p1.\n  apply Z.lt_succ_r.\n  apply n_div_of_n1.\n\n  apply not_prime_divide.\n  apply n1_n2_rel.\n  exact n1_nprime.\n\n  (* Negative numbers (contradiction) *)\n  absurd (Z.neg p > 0).\n  apply Pos2Z.neg_is_nonpos.\n  firstorder.\nQed.\n\n(*** There is an infinite number of primes ***)\n(* Formulation 1: Given the set of all prime number <= an integer,\n *   then we can find a prime not in the set. *)\nTheorem ex_prime_gt_ens : forall n, exists p,\n  prime p /\\ ~(In Z (all_primes_leq n) p).\n\nProof.\n  intros n.\n  elim ex_rel_prime with (P := all_primes_leq n).\n  intros n2 H.\n  inversion H as [n2_gt_1 n2_rel_prime]; clear H.\n  elim ex_prime_divisor with (n := n2).\n  intros p p_pf.\n  exists p.\n  split.\n  apply p_pf.\n  unfold not; intros p_in_apl.\n  absurd (rel_prime p p).\n  unfold rel_prime, not.\n  intros p_rel_prime_self.\n  elim Z.eq_dec with (x := p) (y := 1).\n  intros p_eq_1.\n  { subst. destruct p_pf as [HC ?].\n    apply not_prime_1; auto. }\n  intros p_neq_1.\n  elim Zis_gcd_unique with (a := p) (b := p) (c := p) (d := 1).\n  trivial.\n  { intro; subst.\n    destruct p_pf as [[] ?]; lia. }\n  apply Zis_gcd_refl.\n  exact p_rel_prime_self.\n  cut (rel_prime p n2).\n  intros p_n2_rp.\n  apply rel_prime_sym in p_n2_rp.\n  apply rel_prime_div with (p := n2).\n  exact p_n2_rp.\n  apply p_pf.\n  apply n2_rel_prime.\n  exact p_in_apl.\n  apply n2_gt_1.\n\n  split.\n  apply all_primes_leq_finite.\n  firstorder.\nQed.\n\n(* Formulation 2: For every integer n there exists a prime larger than n.*)\nTheorem ex_prime_gt : forall n,\n  exists p, p > n /\\ prime p.\n\nProof.\n  intros n.\n  (*cut (forall p, ~(In Z (all_primes_leq n) p) -> p > n).*)\n  elim ex_prime_gt_ens with (n := n).\n  intros.\n  inversion H as [x_prime x_nin_apl]; clear H.\n  exists x.\n  split.\n  unfold In, all_primes_leq in x_nin_apl.\n  elim Z.lt_ge_cases with (n := n) (m := x).\n  intros.\n  apply Z.lt_gt.\n  exact H.\n  intros.\n  absurd (x <= n /\\ prime x).\n  exact x_nin_apl.\n  firstorder.\n  exact x_prime.\nQed.\n\n(* Formulation 3: For every set of prime numbers there exists a prime\n     not in the set. *)\nTheorem ex_other_prime : forall P:Z_ens,\n  (Finite' Z P /\\ forall p:Z, In Z P p -> prime p) ->\n  exists q:Z, prime q /\\ ~(In Z P q).\n\nProof.\n  intros.\n  inversion H as [P_finite P_primes]; clear H.\n  (* - P is either empty or non-empty - *)\n  inversion P_finite as [P_empty | P1 P1_finite p' p'_nin_P1 P1_P_rel].\n  (* P is empty, 2 is prime.. *)\n  exists 2.\n  split.\n  exact prime_2.\n  firstorder.\n  (* P is nonempty. *)\n  assert (exists m : Z, In Z P m) as P_nonempty.\n  exists p'.\n  inversion P1_P_rel.\n  intuition.\n  (* Get a maximal element *)\n  assert (exists N, In Z P N /\\ (forall n, In Z P n -> n <= N))\n    as ex_maximal_element'.\n  apply ex_maximal_element.\n  exact P_finite.\n  exact P_nonempty.\n\n  elim ex_maximal_element'.\n  rewrite P1_P_rel.\n  clear p' p'_nin_P1 P1_P_rel P1 P1_finite ex_maximal_element'.\n\n  (* Introduce the maximal element *)\n  intros p_max H.\n  inversion H as [p_max_in_P p_max_ME]; clear H.\n  elim ex_prime_gt with (n := p_max).\n  intros q q_max_prime.\n  exists q.\n  split.\n  apply q_max_prime.\n  unfold not; intros q_in_P.\n  absurd (q <= p_max).\n  firstorder.\n  firstorder.\nQed.\n", "meta": {"author": "bagnalla", "repo": "algco", "sha": "433836e4a0743c0443d530913769a00549b6993a", "save_path": "github-repos/coq/bagnalla-algco", "path": "github-repos/coq/bagnalla-algco/algco-433836e4a0743c0443d530913769a00549b6993a/inf_primes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6582181990535976}}
{"text": "\n\n(* \nTheorem ex_ip_ex : forall (A:Type)(a b:A), a=b -> b=a.\nProof.\n  intros. rewrite H. auto.\nDefined.\nPrint ex_ip_ex. \n*)  \n\nPrint eq_ind.\n\nTheorem ex_ip_ex : forall (A:Type)(a b:A), a=b -> b=a.\nProof.\n  refine \n    (fun (A:Type) (a b:A) (H:a=b) => \n      eq_ind_r (fun a':A => b = a') (refl_equal b) H).\nDefined.\n\nRequire Import ZArith.\n \nTheorem plus_permute2 : forall (n m p:nat), n+m+p = n+p+m.\nProof.\n  intros. \n  pattern ((n+m)+p). rewrite <- plus_assoc. \n  pattern (m+p). rewrite plus_comm.\n  pattern (n+(p+m)). rewrite plus_assoc.\n  reflexivity.\nDefined.\n", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/Equality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6582181973514623}}
{"text": "Require Import Coq.Arith.EqNat.\nRequire Import Coq.Relations.Relations.\nRequire Import Coq.Sorting.Permutation.\n\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Integers.\n\nRequire Import VST.msl.Coqlib2.\nRequire Export VST.msl.eq_dec.\n\nLemma max_two_power_nat: forall n1 n2, Z.max (two_power_nat n1) (two_power_nat n2) = two_power_nat (Nat.max n1 n2).\nProof.\n  intros.\n  rewrite !two_power_nat_two_p.\n  pose proof Zle_0_nat n1; pose proof Zle_0_nat n2.\n  rewrite Nat2Z.inj_max.\n  forget (Z.of_nat n1) as m1; forget (Z.of_nat n2) as m2.\n  destruct (Z_le_dec m1 m2).\n  + rewrite (Z.max_r m1 m2) by omega.\n    apply Z.max_r.\n    apply two_p_monotone; omega.\n  + rewrite (Z.max_l m1 m2) by omega.\n    apply Z.max_l.\n    apply two_p_monotone; omega.\nQed.\n\nLemma Z_max_two_p: forall m1 m2, (exists n, m1 = two_power_nat n) -> (exists n, m2 = two_power_nat n) -> (exists n, Z.max m1 m2 = two_power_nat n).\nProof.\n  intros ? ? [? ?] [? ?].\n  subst.\n  rewrite max_two_power_nat.\n  eexists; reflexivity.\nQed.\n\nLemma power_nat_divide: forall n m, two_power_nat n <= two_power_nat m -> Z.divide (two_power_nat n) (two_power_nat m).\nProof.\n  intros.\n  repeat rewrite two_power_nat_two_p in *.\n  unfold Zdivide.\n  exists (two_p (Z.of_nat m - Z.of_nat n)).\n  assert ((Z.of_nat m) = (Z.of_nat m - Z.of_nat n) + Z.of_nat n) by omega.\n  rewrite H0 at 1.\n  assert (Z.of_nat m >= 0) by omega.\n  assert (Z.of_nat n >= 0) by omega.\n  assert (Z.of_nat n <= Z.of_nat m).\n    destruct (Z_le_gt_dec (Z.of_nat n) (Z.of_nat m)).\n    exact l.\n    assert (Z.of_nat m < Z.of_nat n) by omega.\n    assert (two_p (Z.of_nat m) < two_p (Z.of_nat n)) by (apply two_p_monotone_strict; omega).\n    omega.\n  apply (two_p_is_exp (Z.of_nat m - Z.of_nat n) (Z.of_nat n)); omega.\nQed.\n\nLemma power_nat_divide_ge: forall n m: Z,\n  (exists N, n = two_power_nat N) ->\n  (exists M, m = two_power_nat M) ->\n  (n >= m <-> (m | n)).\nProof.\n  intros.\n  destruct H, H0.\n  split; intros.\n  + subst.\n    apply power_nat_divide.\n    omega.\n  + destruct H1 as [k ?].\n    rewrite H1.\n    pose proof two_power_nat_pos x0.\n    pose proof two_power_nat_pos x.\n    assert (k > 0).\n    Focus 1. {\n      eapply Zmult_gt_0_reg_l.\n      + exact H2.\n      + rewrite <- H0, Z.mul_comm; omega.\n    } Unfocus.\n    rewrite <- (Z.mul_1_l m) at 2.\n    apply Zmult_ge_compat_r; omega.\nQed.\n\nLemma power_nat_divide_le: forall n m: Z,\n  (exists N, n = two_power_nat N) ->\n  (exists M, m = two_power_nat M) ->\n  (m <= n <-> (m | n)).\nProof.\n  intros.\n  rewrite <- power_nat_divide_ge; auto.\n  omega.\nQed.\n\nLemma two_p_max_divide: forall m1 m2 m, (exists n, m1 = two_power_nat n) -> (exists n, m2 = two_power_nat n) -> ((Z.max m1 m2 | m) <-> (m1 | m) /\\ (m2 | m)).\nProof.\n  intros.\n  destruct (Z_le_dec m1 m2).\n  + rewrite Z.max_r by omega.\n    rewrite power_nat_divide_le in l by auto.\n    pose proof Zdivides_trans m1 m2 m.\n    tauto.\n  + rewrite Z.max_l by omega.\n    assert (m2 <= m1) by omega.\n    rewrite power_nat_divide_le in H1 by auto.\n    pose proof Zdivides_trans m2 m1 m.\n    tauto.\nQed.\n\nLemma two_p_max_1: forall m1 m2, (exists n, m1 = two_power_nat n) -> (exists n, m2 = two_power_nat n) -> (Z.max m1 m2 = 1 <-> m1 = 1 /\\ m2 = 1).\nProof.\n  assert (forall x, (exists n : nat, x = two_power_nat n) -> (x = 1 <-> (x | 1))).\n  + intros.\n    split; intros.\n    - subst.\n      exists 1; auto.\n    - rewrite <- power_nat_divide_le in H0 by (auto; exists 0%nat; auto).\n      destruct H as [n ?]; subst x.\n      pose proof two_power_nat_pos n.\n      omega.\n  + intros m1 m2 Hm1 Hm2.\n    pose proof Z_max_two_p _ _ Hm1 Hm2 as Hmax.\n    rewrite (H _ Hm1), (H _ Hm2), (H _ Hmax).\n    apply two_p_max_divide; auto.\nQed.\n\nLemma two_power_nat_0: forall x, (exists n, x = two_power_nat n) -> x <> 0.\nProof.\n  intros.\n  destruct H.\n  pose proof two_power_nat_pos x0.\n  omega.\nQed.\n\nHint Rewrite andb_true_iff: align.\nHint Rewrite <- Zle_is_le_bool: align.\nHint Rewrite Z.eqb_eq: align.\nHint Rewrite power_nat_divide_le using (auto with align): align.\nHint Rewrite Z.mod_divide using (apply two_power_nat_0; auto with align): align.\nHint Rewrite two_p_max_divide using (auto with align): align.\nHint Rewrite two_p_max_1 using (auto with align): align.\nHint Resolve Z_max_two_p: align.\n\nLemma Z_of_nat_ge_O: forall n, Z.of_nat n >= 0.\nProof. intros.\nchange 0 with (Z.of_nat O).\napply inj_ge. clear; omega.\nQed.\n\nLemma nth_error_nth:\n  forall A (al: list A) (z: A) i, (i < length al)%nat -> nth_error al i = Some (nth i al z).\nProof.\nintros. revert al H; induction i; destruct al; simpl; intros; auto; try omega.\napply IHi. omega.\nQed.\n\nLemma nat_of_Z_eq: forall i, nat_of_Z (Z_of_nat i) = i.\nProof.\nintros.\napply inj_eq_rev.\nrewrite nat_of_Z_eq; auto.\nomega.\nQed.\n\nLemma nth_error_length:\n  forall {A} i (l: list A), nth_error l i = None <-> (i >= length l)%nat.\nProof.\ninduction i; destruct l; simpl; intuition.\ninv H.\ninv H.\nrewrite IHi in H. omega.\nrewrite IHi. omega.\nQed.\n\nLemma prop_unext: forall P Q: Prop, P=Q -> (P<->Q).\nProof. intros. subst; split; auto. Qed.\n\nLemma list_norepet_In_In: forall {K X} a x y (l:list (K*X)),\n  list_norepet (map (@fst K X) l) -> In (a, x) l -> In (a, y) l -> x = y.\nProof.\n  induction l; intros N Ix Iy.\n   - inv Ix.\n   - simpl in N; inv N.\n     destruct Ix.\n     + subst.\n       simpl in Iy; destruct Iy as [|Iy]; [congruence|].\n       exfalso; apply (in_map (@fst K X)) in Iy; tauto.\n     + simpl in Iy; destruct Iy as [|Iy].\n       subst. exfalso; apply (in_map (@fst K X)) in H; tauto.\n       apply IHl; auto.\nQed.\n\nInductive sublist {A} : list A -> list A -> Prop :=\n| sublist_nil : sublist nil nil\n| sublist_cons a l1 l2 : sublist l1 l2 -> sublist (a :: l1) (a :: l2)\n| sublist_drop a l1 l2 : sublist l1 l2 -> sublist l1 (a :: l2).\n\nLemma sublist_In {A} (a : A) l1 l2 : sublist l1 l2 -> In a l1 -> In a l2.\nProof.\n  intros S; induction S; intros I.\n  - inversion I.\n  - simpl in I; destruct I.\n    subst; left; auto.\n    right; auto.\n  - right; auto.\nQed.\n\nLemma sublist_norepet {A} (l1 l2 : list A) : sublist l1 l2 -> list_norepet l2 -> list_norepet l1.\nProof.\n  intros S; induction S; intros N; auto.\n  - inversion N; subst; constructor; auto.\n    pose proof sublist_In a l1 l2; auto.\n  - inversion N; auto.\nQed.\n\nRequire Import Coq.Sets.Ensembles.\n\nDefinition Ensemble_join {A} (X Y Z: Ensemble A): Prop :=\n  (forall a, Z a <-> X a \\/ Y a) /\\ (forall a, X a -> Y a -> False).\n\nRequire Coq.Logic.ConstructiveEpsilon.\n\nLemma decidable_countable_ex_sig {A} (f : nat -> A)\n      (Hf : forall a, exists n, a = f n)\n      (P : A -> Prop)\n      (Pdec : forall x, {P x} + {~ P x}) :\n  (exists x : A, P x) -> {x : A | P x}.\nProof.\n  intros E.\n  cut ({n | P (f n)}). intros [n Hn]; eauto.\n  apply ConstructiveEpsilon.constructive_indefinite_ground_description_nat.\n  intro; apply Pdec.\n  destruct E as [x Hx].\n  destruct (Hf x) as [n ->].\n  eauto.\nQed.\n\n(** Additions to [if_tac]: when mature, move these upstream *)\n\nTactic Notation \"if_tac\" \"eq:\" simple_intropattern(E) :=\n  match goal with\n    |- context [if ?a then _ else _] =>\n    destruct a as [?H | ?H] eqn:E\n  end.\n\nTactic Notation \"if_tac\" simple_intropattern(H) \"eq:\" simple_intropattern(E):=\n  match goal with\n    |- context [if ?a then _ else _] =>\n    destruct a as H eqn:E\n  end.\n\nTactic Notation \"if_tac\" \"in\" hyp(H0) \"eq:\" simple_intropattern(E) :=\n  match type of H0 with\n    context [if ?a then _ else _] =>\n    destruct a as [?H  | ?H] eqn:E\n  end.\n\nTactic Notation \"if_tac\" simple_intropattern(H) \"in\" hyp(H1) \"eq:\" simple_intropattern(E) :=\n  match type of H1 with\n    context [if ?a then _ else _] =>\n    destruct a as H eqn:E\n  end.\n\n(** Specializing a hypothesis with a newly created goal *)\n\nTactic Notation \"assert_specialize\" hyp(H) :=\n  match type of H with\n    forall x : ?P, _ =>\n    let Htemp := fresh \"Htemp\" in\n    assert P as Htemp; [ | specialize (H Htemp); try clear Htemp ]\n  end.\n\nTactic Notation \"assert_specialize\" hyp(H) \"by\" tactic(tac) :=\n  match type of H with\n    forall x : ?P, _ =>\n    let Htemp := fresh \"Htemp\" in\n    assert P as Htemp by tac; specialize (H Htemp); try clear Htemp\n  end.\n\nTactic Notation \"assert_specialize\" hyp(H) \"as\" simple_intropattern(Hnew) :=\n  match type of H with\n    forall x : ?P, _ =>\n    assert P as Hnew; [ | specialize (H Hnew) ]\n  end.\n\nTactic Notation \"assert_specialize\" hyp(H) \"as\" simple_intropattern(Hnew) \"by\" tactic(tac) :=\n  match type of H with\n    forall x : ?P, _ =>\n    assert P as Hnew by tac;\n    specialize (H Hnew)\n  end.\n\n(** Auto-specializing a hypothesis *)\n\nLtac autospec H := specialize (H ltac:(solve [eauto])).\n\n(** When a hypothesis/term is provably equal, but not convertible, to\n    your goal *)\n\nLtac exact_eq H :=\n  revert H;\n  match goal with\n    |- ?p -> ?q => cut (p = q); [intros ->; auto | ]\n  end.\n\n(** Auto rewriting of a term *)\n\nTactic Notation \"rewr\" :=\n  match goal with\n  | H : ?f = _ |- context [?f] => rewrite H\n  | H : ?f _ = ?f _ |- _ => try (injection H; repeat intros ->)\n  end.\n\nTactic Notation \"rewr\" constr(e) :=\n  match goal with\n    E : e = _ |- _ => rewrite E\n  | E : _ = e |- _ => rewrite <-E\n  end.\n\nTactic Notation \"rewr\" constr(e) \"in\" \"*\" :=\n  match goal with\n    E : e = _ |- _ => rewrite E in *\n  | E : _ = e |- _ => rewrite <-E in *\n  end.\n\nTactic Notation \"rewr\" constr(e) \"in\" hyp(H) :=\n  match goal with\n    E : e = _ |- _ => rewrite E in H\n  | E : _ = e |- _ => rewrite <-E in H\n  end.\n\nLemma perm_search:\n  forall {A} (a b: A) r s t,\n     Permutation (a::t) s ->\n     Permutation (b::t) r ->\n     Permutation (a::r) (b::s).\nProof.\nintros.\neapply perm_trans.\napply perm_skip.\napply Permutation_sym.\napply H0.\neapply perm_trans.\napply perm_swap.\napply perm_skip.\napply H.\nQed.\n\nLemma Permutation_concat: forall {A} (P Q: list (list A)),\n  Permutation P Q ->\n  Permutation (concat P) (concat Q).\nProof.\n  intros.\n  induction H.\n  + apply Permutation_refl.\n  + simpl.\n    apply Permutation_app_head; auto.\n  + simpl.\n    rewrite !app_assoc.\n    apply Permutation_app_tail.\n    apply Permutation_app_comm.\n  + eapply Permutation_trans; eauto.\nQed.    \n\nLemma Permutation_app_comm_trans:\n forall (A: Type) (a b c : list A),\n   Permutation (b++a) c ->\n   Permutation (a++b) c.\nProof.\nintros.\neapply Permutation_trans.\napply Permutation_app_comm.\nauto.\nQed.\n\nLtac solve_perm :=\n    (* solves goals of the form (R ++ ?i = S)\n          where R and S are lists, and ?i is a unification variable *)\n  try match goal with\n       | |-  Permutation (?A ++ ?B) _ =>\n            is_evar A; first [is_evar B; fail 1| idtac];\n            apply Permutation_app_comm_trans\n       end;\n  repeat first [ apply Permutation_refl\n       | apply perm_skip\n       | eapply perm_search\n       ].\n\nGoal exists e, Permutation ((1::2::nil)++e) (3::2::1::5::nil).\neexists.\nsolve_perm.\nQed.\n\nLemma range_pred_dec: forall (P: nat -> Prop),\n  (forall n, {P n} + {~ P n}) ->\n  forall m,\n    {forall n, (n < m)%nat -> P n} + {~ forall n, (n < m)%nat -> P n}.\nProof.\n  intros.\n  induction m.\n  + left.\n    intros; omega.\n  + destruct (H m); [destruct IHm |].\n    - left.\n      intros.\n      destruct (eq_dec n m).\n      * subst; auto.\n      * apply p0; omega.\n    - right.\n      intro.\n      apply n; clear n.\n      intros; apply H0; omega.\n    - right.\n      intro.\n      apply n; clear n.\n      apply H0.\n      omega.\nQed.\n\nLemma Z2Nat_neg: forall i, i < 0 -> Z.to_nat i = 0%nat.\nProof.\n  intros.\n  destruct i; try reflexivity.\n  pose proof Zgt_pos_0 p; omega.\nQed.\n\nLemma Zrange_pred_dec: forall (P: Z -> Prop),\n  (forall z, {P z} + {~ P z}) ->\n  forall l r,  \n    {forall z, l <= z < r -> P z} + {~ forall z, l <= z < r -> P z}.\nProof.\n  intros.\n  assert ((forall n: nat, (n < Z.to_nat (r - l))%nat -> P (l + Z.of_nat n)) <-> (forall z : Z, l <= z < r -> P z)).\n  Focus 1. {\n    split; intros.\n    + specialize (H0 (Z.to_nat (z - l))).\n      rewrite <- Z2Nat.inj_lt in H0 by omega.\n      spec H0; [omega |].\n      rewrite Z2Nat.id in H0 by omega.\n      replace (l + (z - l)) with z in H0 by omega.\n      auto.\n    + apply H0.\n      rewrite Nat2Z.inj_lt in H1.\n      destruct (zlt (r - l) 0).\n      - rewrite Z2Nat_neg in H1 by omega.\n        simpl in H1.\n        omega.\n      - rewrite Z2Nat.id in H1 by omega.\n        omega.\n  } Unfocus.\n  eapply sumbool_dec_iff; [clear H0 | eassumption].\n  apply range_pred_dec.\n  intros.\n  apply H.\nQed.\n\nDefinition eqb_list {A: Type} (eqb_A: A -> A -> bool): list A -> list A -> bool :=\n  fix eqb_list (l1 l2: list A): bool :=\n    match l1, l2 with\n    | nil, nil => true\n    | a1 :: l1, a2 :: l2 => eqb_A a1 a2 && eqb_list l1 l2\n    | _, _ => false\n    end.\n\nLemma eqb_list_spec: forall {A: Type} (eqb_A: A -> A -> bool),\n  (forall a1 a2, eqb_A a1 a2 = true <-> a1 = a2) ->\n  (forall l1 l2, eqb_list eqb_A l1 l2 = true <-> l1 = l2).\nProof.\n  intros.\n  revert l2; induction l1 as [| a1 l1]; intros; destruct l2 as [| a2 l2].\n  + simpl.\n    tauto.\n  + simpl.\n    split; intros; congruence.\n  + simpl.\n    split; intros; congruence.\n  + simpl.\n    rewrite andb_true_iff.\n    rewrite  H.\n    rewrite IHl1.\n    split; intros.\n    - destruct H0; subst; auto.\n    - inv H0; auto.\nQed.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/veric/coqlib4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6581729810053473}}
{"text": "Require Export Quantum.\n\nDefinition ketp : Vector 2 := \n  fun x y => match x, y with \n          | 0, 0 => /√2\n          | 1, 0 => /√2\n          | _, _ => C0\n          end.\nDefinition ketn : Vector 2 := \n  fun x y => match x, y with \n          | 0, 0 => /√2\n          | 1, 0 => -/√2\n          | _, _ => C0\n          end.\n\nNotation \"∣+⟩\" := ketp.\nNotation \"∣-⟩\" := ketn.\nNotation \"⟨+∣\" := ketp†.\nNotation \"⟨-∣\" := ketn†.\n\n\n(* Deutsch *)\n\n(* One-time *)\n\n(* f(0) =  f(1) = 0 *)\n\n\nLemma deutsch0 : (hadamard ⊗ I 2) × (I 2 ⊗ I 2) × (hadamard ⊗ hadamard) × (∣0⟩ ⊗ ∣1⟩) = ∣0⟩ ⊗ ∣-⟩ .\nProof. solve_matrix. Qed.\n\nLemma Ddeutsch0 : super ((hadamard ⊗ I 2) × (I 2 ⊗ I 2) × (hadamard ⊗ hadamard)) ((∣0⟩ ⊗ ∣1⟩) × (∣0⟩ ⊗ ∣1⟩)†)= (∣0⟩ ⊗ ∣-⟩) × (∣0⟩ ⊗ ∣-⟩)†.\nProof.\nunfold super.\nTime solve_matrix.\nQed.\n\n(* Lemma Ddeutsch0' : super (hadamard ⊗ I 2) (super (I 2 ⊗ I 2) (super (hadamard ⊗ hadamard) ((∣0⟩ ⊗ ∣1⟩) × (∣0⟩ ⊗ ∣1⟩)†))) = (∣0⟩ ⊗ ∣-⟩) × (∣0⟩ ⊗ ∣-⟩)†.\nProof.\nunfold super.\nsolve_matrix.\nQed. *)\n\n\n(* f(0) =  f(1) = 1 *)\nLemma deutsch1 : (hadamard ⊗ I 2) × (I 2 ⊗ σx) × (hadamard ⊗ hadamard) × (∣0⟩ ⊗ ∣1⟩) = -1 .* ∣0⟩ ⊗ ∣-⟩ .\nProof. solve_matrix. Qed.\n\nLemma Ddeutsch1 : super ((hadamard ⊗ I 2) × (I 2 ⊗ σx) × (hadamard ⊗ hadamard)) ((∣0⟩ ⊗ ∣1⟩) × (∣0⟩ ⊗ ∣1⟩)†)= (-1 .* ∣0⟩ ⊗ ∣-⟩) × (-1 .* ∣0⟩ ⊗ ∣-⟩ )†.\nProof.\nunfold super.\nTime solve_matrix.\nQed.\n\n(* Lemma Ddeutsch1' : super (hadamard ⊗ I 2) (super (I 2 ⊗ σx) (super (hadamard ⊗ hadamard) ((∣0⟩ ⊗ ∣1⟩) × (∣0⟩ ⊗ ∣1⟩)†)))= (-1 .* ∣0⟩ ⊗ ∣-⟩) × (-1 .* ∣0⟩ ⊗ ∣-⟩ )†.\nProof.\nunfold super.\nsolve_matrix.\nQed. *)\n\n\n(* f(0) = 0, f(1) = 1 *)\nLemma deutsch2 : (hadamard ⊗ I 2) × cnot × (hadamard ⊗ hadamard) × (∣0⟩ ⊗ ∣1⟩) = ∣1⟩ ⊗ ∣-⟩ .\nProof. solve_matrix. Qed.\n\nLemma Ddeutsch2 : super ((hadamard ⊗ I 2) × cnot × (hadamard ⊗ hadamard)) ((∣0⟩ ⊗ ∣1⟩) × (∣0⟩ ⊗ ∣1⟩)†) = (∣1⟩ ⊗ ∣-⟩) × (∣1⟩ ⊗ ∣-⟩ )†.\nProof.\nunfold super.\nTime solve_matrix.\nQed.\n\n(* Lemma Ddeutsch2' : super (hadamard ⊗ I 2) (super cnot (super (hadamard ⊗ hadamard) ((∣0⟩ ⊗ ∣1⟩) × (∣0⟩ ⊗ ∣1⟩)†))) = (∣1⟩ ⊗ ∣-⟩) × (∣1⟩ ⊗ ∣-⟩ )†.\nProof.\nunfold super.\nsolve_matrix.\nQed. *)\n\n\n(* f(0) = 1, f(1) = 0 *)\nDefinition notc : Matrix (2*2) (2*2) :=\n  fun x y => match x, y with \n          | 0, 1 => 1%C\n          | 1, 0 => 1%C\n          | 2, 2 => 1%C\n          | 3, 3 => 1%C\n          | _, _ => 0%C\n          end.\n\nLemma deutsch3 : (hadamard ⊗ I 2) × notc × (hadamard ⊗ hadamard) × (∣0⟩ ⊗ ∣1⟩) = -1 .* ∣1⟩ ⊗ ∣-⟩ .\nProof. solve_matrix. Qed.\n\nLemma Ddeutsch3 : super ((hadamard ⊗ I 2) × notc × (hadamard ⊗ hadamard)) ((∣0⟩ ⊗ ∣1⟩) × (∣0⟩ ⊗ ∣1⟩)†) = (-1 .* ∣1⟩ ⊗ ∣-⟩) × (-1 .* ∣1⟩ ⊗ ∣-⟩)†.\nProof.\nunfold super.\nTime solve_matrix.\nQed.\n\n(* Lemma Ddeutsch3' : super (hadamard ⊗ I 2) (super notc (super (hadamard ⊗ hadamard) ((∣0⟩ ⊗ ∣1⟩) × (∣0⟩ ⊗ ∣1⟩)†))) = (-1 .* ∣1⟩ ⊗ ∣-⟩) × (-1 .* ∣1⟩ ⊗ ∣-⟩)†.\nProof.\nunfold super.\nsolve_matrix.\nQed. *)\n\n(* \nFinished transaction in 18.982 secs (17.437u,0.046s) (successful)\nFinished transaction in 18.77 secs (17.078u,0.031s) (successful)\nFinished transaction in 18.451 secs (17.187u,0.031s) (successful)\nFinished transaction in 19.488 secs (17.578u,0.062s) (successful) *)", "meta": {"author": "Vickyswj", "repo": "DiracRepr", "sha": "5f4f0759f64b938fd7eb71e1968ea378e56e6646", "save_path": "github-repos/coq/Vickyswj-DiracRepr", "path": "github-repos/coq/Vickyswj-DiracRepr/DiracRepr-5f4f0759f64b938fd7eb71e1968ea378e56e6646/Dirac/example/com_exa/D_solve.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6581729782109144}}
{"text": "From CoqAlgs Require Import Base.\n\nSet Implicit Arguments.\n\n(* Formulas. [not f] will be represented as [fImpl f fFalse] and\n   [f1 <-> f2] as [fAnd (fImpl f1 f2) (fImpl f2 f1)]. *)\nInductive formula : Type :=\n    | fFalse : formula\n    | fTrue : formula\n    | fVar : nat -> formula\n    | fAnd : formula -> formula -> formula\n    | fOr : formula -> formula -> formula\n    | fImpl : formula -> formula -> formula.\n\nFixpoint formulaDenote (env : Env Prop) (f : formula) : Prop :=\nmatch f with\n    | fFalse => False\n    | fTrue => True\n    | fVar i => holds i env\n    | fAnd f1 f2 => formulaDenote env f1 /\\ formulaDenote env f2\n    | fOr f1 f2 => formulaDenote env f1 \\/ formulaDenote env f2\n    | fImpl f1 f2 => formulaDenote env f1 -> formulaDenote env f2\nend.\n\nFunction simplifyFormula (f : formula) : formula :=\nmatch f with\n    | fFalse => fFalse\n    | fTrue => fTrue\n    | fVar P => fVar P\n    | fAnd f1 f2 =>\n        match simplifyFormula f1, simplifyFormula f2 with\n            | fOr f11 f12, f2' => fOr (fAnd f11 f2') (fAnd f12 f2')\n            | f1', fOr f21 f22 => fOr (fAnd f1' f21) (fAnd f1' f22)\n            | fFalse, _ => fFalse\n            | _, fFalse => fFalse\n            | fTrue, f2' => f2'\n            | f1', fTrue => f1'\n            | f1', f2' => fAnd f1' f2'\n        end\n    | fOr f1 f2 =>\n        match simplifyFormula f1, simplifyFormula f2 with\n            | fAnd f11 f12, f2' => fAnd (fOr f11 f2') (fOr f12 f2')\n            | f1', fAnd f21 f22 => fAnd (fOr f1' f21) (fOr f1' f22)\n            | fFalse, f2' => f2'\n            | f1', fFalse => f1'\n            | fTrue, _ => fTrue\n            | _, fTrue => fTrue\n            | f1', f2' => fOr f1' f2'\n        end\n    | fImpl f1 f2 =>\n        match simplifyFormula f1 with\n            | fFalse => fTrue\n            | fTrue => f2\n            | fAnd f11 f12 => fImpl f11 (fImpl f12 f2)\n            | fOr f11 f12 => fAnd (fImpl f11 f2) (fImpl f12 f2)\n            | f1' => fImpl f1' f2\n        end\nend.\n\nTheorem simplifyFormula_correct :\n  forall (f : formula) (env : Env Prop),\n    formulaDenote env (simplifyFormula f) <-> formulaDenote env f.\nProof.\n  intros. functional induction simplifyFormula f; cbn.\n  all:\n  repeat match goal with\n      | e : simplifyFormula ?f = _,\n        IH : formulaDenote _ (simplifyFormula ?f) <-> _ |- _ =>\n        rewrite <- IH, e; cbn\n  end; try (tauto; fail).\nQed.\n\nDefinition solveHypothesis (env : Env Prop) :\n  forall (proofs : Proofs) (H : allTrue env proofs) (hyp f : formula)\n    (cont : Proofs -> bool), bool.\nProof.\n  refine (\n  fix solve\n    (proofs : Proofs) (H : allTrue env proofs) (hyp f : formula)\n      (cont : Proofs -> bool) : bool :=\n  match hyp with\n      | fFalse => false\n      | fTrue => cont proofs\n      | fVar i => cont (i :: proofs)\n      | fAnd f1 f2 =>\n          solve proofs H f1 (fImpl f2 f)\n                        (fun proofs' => cont proofs')\n      | fOr f1 f2 =>\n          andb (solve proofs H f1 f cont)\n               (solve proofs H f2 f cont)\n      | _ => false\n  end).\nDefined.\n\nDefinition solveGoal (env : Env Prop)\n  : forall (proofs : Proofs) (H : allTrue env proofs) (f : formula), bool.\nProof.\n  refine (\n  fix solve\n    (proofs : Proofs) (H : allTrue env proofs) (f : formula) : bool :=\n  match f with\n      | fFalse => false\n      | fTrue => true\n      | fVar i =>\n          match in_dec Nat.eq_dec i proofs with\n              | left _ => true\n              | right _ => false\n          end \n      | fAnd f1 f2 => andb (solve proofs H f1) (solve proofs H f2)\n      | fOr f1 f2 => orb (solve proofs H f1) (solve proofs H f2)\n (*     | fImpl f1 f2 =>\n          solveHypothesis env proofs H f1 f2\n            (fun proofs' => solve proofs' _ f2)*)\n      | _ => false\n  end).\nDefined.\n\nDefinition solveFormula (env : Env Prop) (f : formula) : bool.\nProof.\n  refine (solveGoal env [] _ f). cbn. trivial.\nDefined.\n\nTheorem solveGoal_correct :\n  forall (env : Env Prop) (proofs : Proofs) (H : allTrue env proofs)\n  (f : formula),\n    solveGoal env proofs H f = true -> formulaDenote env f.\nProof.\n  induction f; cbn; intros; try congruence.\n    trivial.\n    destruct (in_dec Nat.eq_dec n proofs).\n      apply find_spec with proofs; auto.\n      congruence.\n    rewrite andb_true_iff in H0. tauto.\n    rewrite orb_true_iff in H0. tauto.\nQed.\n\nTheorem solveFormula_correct :\n  forall (env : Env Prop) (f : formula),\n    solveFormula env f = true -> formulaDenote env f.\nProof.\n  intros. destruct f; cbn in *; try congruence.\n    trivial.\n    rewrite andb_true_iff in H. destruct H.\n      split; eapply solveGoal_correct; eauto.\n    rewrite orb_true_iff in H. destruct H.\n      left. eapply solveGoal_correct; eauto.\n      right. eapply solveGoal_correct; eauto.\nQed.\n\nLtac allVarsFormula xs P :=\nmatch P with\n    | ~ ?P' => allVarsFormula xs P'\n    | ?P1 /\\ ?P2 =>\n        let xs' := allVarsFormula xs P2 in allVarsFormula xs' P1\n    | ?P1 \\/ ?P2 =>\n        let xs' := allVarsFormula xs P2 in allVarsFormula xs' P1\n    | ?P1 -> ?P2 =>\n        let xs' := allVarsFormula xs P2 in allVarsFormula xs' P1\n    | ?P1 <-> ?P2 =>\n        let xs' := allVarsFormula xs P2 in allVarsFormula xs' P1\n    | _ => addToList P xs\nend.\n\nLtac reifyFormula xs P :=\nmatch P with\n    | False => constr:(fFalse)\n    | True => constr:(fTrue)\n    | ~ ?P' =>\n        let e := reifyFormula xs P' in constr:(fImpl e fFalse)\n    | ?P1 /\\ ?P2 =>\n        let e1 := reifyFormula xs P1 in\n        let e2 := reifyFormula xs P2 in constr:(fAnd e1 e2)\n    | ?P1 \\/ ?P2 =>\n        let e1 := reifyFormula xs P1 in\n        let e2 := reifyFormula xs P2 in constr:(fOr e1 e2)\n    | ?P1 -> ?P2 =>\n        let e1 := reifyFormula xs P1 in\n        let e2 := reifyFormula xs P2 in constr:(fImpl e1 e2)\n    | ?P1 <-> ?P2 =>\n        let e1 := reifyFormula xs P1 in\n        let e2 := reifyFormula xs P2 in\n          constr:(fAnd (fImpl e1 e2) (fImpl e2 e1))\n    | _ =>\n        let i := lookup P xs in constr:(fVar i)\nend.\n\nLtac reflectFormula :=\nmatch goal with\n    |- ?P =>\n        let xs := allVarsFormula constr:(@nil Prop) P in\n        let f := reifyFormula xs P in\n          change (formulaDenote xs f);\n          rewrite <- simplifyFormula_correct; cbn\nend.\n\nLtac solveGoal :=\nmatch goal with\n    |- ?P =>\n        let xs := allVarsFormula constr:(@nil Prop) P in\n        let f := reifyFormula xs P in change (formulaDenote xs f);\n          rewrite <- simplifyFormula_correct;\n          apply solveFormula_correct; cbn; reflexivity\nend.", "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/Reflection/Formula2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6581729720319545}}
{"text": "Section PropositionLanguage.\n\nContext { atom : Type }.\n\nInductive prop : Type :=\n| atom_prop : atom -> prop\n| bot_prop : prop\n| top_prop : prop\n| and_prop : prop -> prop -> prop\n| or_prop : prop -> prop -> prop\n| impl_prop : prop -> prop -> prop.\n\nDefinition not_prop (P : prop) :=\n  impl_prop P bot_prop.\n\nEnd PropositionLanguage.\n\nArguments prop atom : clear implicits.\n\nNotation \"⊥\" := bot_prop.\nNotation \"⊤\" := top_prop.\nNotation \"¬ P\" := (not_prop P) (at level 51).\nInfix \"∧\" := and_prop (left associativity, at level 52).\nInfix \"∨\" := or_prop (left associativity, at level 53).\nInfix \"⊃\" := impl_prop (right associativity, at level 54).\n", "meta": {"author": "dschepler", "repo": "coq-sequent-calculus", "sha": "5e87c4f4f61d01ecf990e4e25b9280e6422a73e0", "save_path": "github-repos/coq/dschepler-coq-sequent-calculus", "path": "github-repos/coq/dschepler-coq-sequent-calculus/coq-sequent-calculus-5e87c4f4f61d01ecf990e4e25b9280e6422a73e0/PropLang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6581729641997408}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import ssrbool eqtype ssrnat seq fintype ssrfun tuple finset.\nFrom Bits\n     Require Import bits.\nRequire Import spec.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** * Set complement  *)\nDefinition compl n (bs: BITS n): BITS n := invB bs.\n\nLemma compl_repr n (bs: BITS n) E :\n  repr bs E -> repr (compl bs) (~: E).\nProof. by move->; apply/setP=> i; rewrite !inE getBit_liftUnOp. Qed.\n", "meta": {"author": "artart78", "repo": "coq-bitset", "sha": "806821b4ccf259885dfb5645e0e6957fb1149c52", "save_path": "github-repos/coq/artart78-coq-bitset", "path": "github-repos/coq/artart78-coq-bitset/coq-bitset-806821b4ccf259885dfb5645e0e6957fb1149c52/src/ops/compl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6581332731058726}}
{"text": "(** Zhaoguo Wang **)\n\n(** * Poly: Polymorphism and Higher-Order Functions *)\n\n(** In this chapter we continue our development of basic \n    concepts of functional programming.  The critical new ideas are\n    _polymorphism_ (abstracting functions over the types of the data\n    they manipulate) and _higher-order functions_ (treating functions\n    as data).\n*)\n\nRequire Export Lists.   \n\n(* ###################################################### *)\n(** * Polymorphism *)\n(* ###################################################### *)\n(** ** Polymorphic Lists *)\n\n(** For the last couple of chapters, we've been working just\n    with lists of numbers.  Obviously, interesting programs also need\n    to be able to manipulate lists with elements from other types --\n    lists of strings, lists of booleans, lists of lists, etc.  We\n    _could_ just define a new inductive datatype for each of these,\n    for example... *)\n\nInductive boollist : Type :=\n  | bool_nil : boollist\n  | bool_cons : bool -> boollist -> boollist.\n\n(** ... but this would quickly become tedious, partly because we\n    have to make up different constructor names for each datatype, but\n    mostly because we would also need to define new versions of all\n    our list manipulating functions ([length], [rev], etc.)  for each\n    new datatype definition. *)\n\n(** To avoid all this repetition, Coq supports _polymorphic_\n    inductive type definitions.  For example, here is a _polymorphic\n    list_ datatype. *)\n\nInductive list (X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\n(** This is exactly like the definition of [natlist] from the\n    previous chapter, except that the [nat] argument to the [cons]\n    constructor has been replaced by an arbitrary type [X], a binding\n    for [X] has been added to the header, and the occurrences of\n    [natlist] in the types of the constructors have been replaced by\n    [list X].  (We can re-use the constructor names [nil] and [cons]\n    because the earlier definition of [natlist] was inside of a\n    [Module] definition that is now out of scope.) *)\n\n(** What sort of thing is [list] itself?  One good way to think\n    about it is that [list] is a _function_ from [Type]s to\n    [Inductive] definitions; or, to put it another way, [list] is a\n    function from [Type]s to [Type]s.  For any particular type [X],\n    the type [list X] is an [Inductive]ly defined set of lists whose\n    elements are things of type [X]. *)\n\n(** With this definition, when we use the constructors [nil] and\n    [cons] to build lists, we need to tell Coq the type of the\n    elements in the lists we are building -- that is, [nil] and [cons]\n    are now _polymorphic constructors_.  Observe the types of these\n    constructors: *)\n\nCheck nil.\n(* ===> nil : forall X : Type, list X *)\nCheck cons.\n(* ===> cons : forall X : Type, X -> list X -> list X *)\n\n(** (Side note on notation: In .v files, the \"forall\" quantifier is\n    spelled out in letters.  In the generated HTML files, [forall] is\n    usually typeset as the usual mathematical \"upside down A,\" but\n    you'll see the spelled-out \"forall\" in a few places.  This is just\n    a quirk of typesetting: there is no difference in meaning. *)\n\n(** The \"[forall X]\" in these types can be read as an additional\n    argument to the constructors that determines the expected types of\n    the arguments that follow.  When [nil] and [cons] are used, these\n    arguments are supplied in the same way as the others.  For\n    example, the list containing [2] and [1] is written like this: *)\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\n(** (We've gone back to writing [nil] and [cons] explicitly here\n    because we haven't yet defined the [ [] ] and [::] notations for\n    the new version of lists.  We'll do that in a bit.) *)\n\n(** We can now go back and make polymorphic (or \"generic\")\n    versions of all the list-processing functions that we wrote\n    before.  Here is [length], for example: *)\n\nFixpoint length (X:Type) (l:list X) : nat :=\n  match l with\n  | nil      => 0\n  | cons h t => S (length X t)\n  end.\n\n(** Note that the uses of [nil] and [cons] in [match] patterns\n    do not require any type annotations: we already know that the list\n    [l] contains elements of type [X], so there's no reason to include\n    [X] in the pattern.  (More precisely, the type [X] is a parameter\n    of the whole definition of [list], not of the individual\n    constructors.  We'll come back to this point later.)\n\n    As with [nil] and [cons], we can use [length] by applying it first\n    to a type and then to its list argument: *)\n\nExample test_length1 :\n    length nat (cons nat 1 (cons nat 2 (nil nat))) = 2.\nProof. reflexivity.  Qed.\n\n(** To use our length with other kinds of lists, we simply\n    instantiate it with an appropriate type parameter: *)\n\nExample test_length2 :\n    length bool (cons bool true (nil bool)) = 1.\nProof. reflexivity.  Qed.\n\n(** Let's close this subsection by re-implementing a few other\n    standard list functions on our new polymorphic lists: *)\n\nFixpoint app (X : Type) (l1 l2 : list X)\n                : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons X h (app X t l2)\n  end.\n\nFixpoint snoc (X:Type) (l:list X) (v:X) : (list X) :=\n  match l with\n  | nil      => cons X v (nil X)\n  | cons h t => cons X h (snoc X t v)\n  end.\n\nFixpoint rev (X:Type) (l:list X) : list X :=\n  match l with\n  | nil      => nil X\n  | cons h t => snoc X (rev X t) h\n  end.\n\n\n\nExample test_rev1 :\n    rev nat (cons nat 1 (cons nat 2 (nil nat)))\n  = (cons nat 2 (cons nat 1 (nil nat))).\nProof. reflexivity.  Qed.\n\nExample test_rev2:\n  rev bool (nil bool) = nil bool.\nProof. reflexivity.  Qed.\n\nModule MumbleBaz.\n(** **** Exercise: 2 stars (mumble_grumble) *)\n(** Consider the following two inductively defined types. *)\n\nInductive mumble : Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\nInductive grumble (X:Type) : Type :=\n  | d : mumble -> grumble X\n  | e : X -> grumble X.\n\n(** Which of the following are well-typed elements of [grumble X] for\n    some type [X]?\n      - [d (b a 5)]\n      - [d mumble (b a 5)]\n      - [d bool (b a 5)]\n      - [e bool true]\n      - [e mumble (b c 0)]\n      - [e bool (b c 0)]\n      - [c] \n(* \n[d mumble (b a 5)]\n[d bool (b a 5)]\n[e bool true]\n[e mumble (b c 0)]\n[c]\n*)\n**)\n\n(** **** Exercise: 2 stars (baz_num_elts) *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n   | x : baz -> baz\n   | y : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have? *)\n(** 0. none of them is base type.**)\n\n\nEnd MumbleBaz.\n\n(* ###################################################### *)\n(** *** Type Annotation Inference *)\n\n(** Let's write the definition of [app] again, but this time we won't\n    specify the types of any of the arguments. Will Coq still accept\n    it? *)\n\nFixpoint app' X l1 l2 : list X :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons X h (app' X t l2)\n  end.\n\n(** Indeed it will.  Let's see what type Coq has assigned to [app']: *)\n\nCheck app'.\n(* ===> forall X : Type, list X -> list X -> list X *)\nCheck app.\n(* ===> forall X : Type, list X -> list X -> list X *)\n\n(** It has exactly the same type type as [app].  Coq was able to\n    use a process called _type inference_ to deduce what the types of\n    [X], [l1], and [l2] must be, based on how they are used.  For\n    example, since [X] is used as an argument to [cons], it must be a\n    [Type], since [cons] expects a [Type] as its first argument;\n    matching [l1] with [nil] and [cons] means it must be a [list]; and\n    so on.\n\n    This powerful facility means we don't always have to write\n    explicit type annotations everywhere, although explicit type\n    annotations are still quite useful as documentation and sanity\n    checks.  You should try to find a balance in your own code between\n    too many type annotations (so many that they clutter and distract)\n    and too few (which forces readers to perform type inference in\n    their heads in order to understand your code). *)\n\n(* ###################################################### *)\n(** *** Type Argument Synthesis *)\n\n(** Whenever we use a polymorphic function, we need to pass it\n    one or more types in addition to its other arguments.  For\n    example, the recursive call in the body of the [length] function\n    above must pass along the type [X].  But just like providing\n    explicit type annotations everywhere, this is heavy and verbose.\n    Since the second argument to [length] is a list of [X]s, it seems\n    entirely obvious that the first argument can only be [X] -- why\n    should we have to write it explicitly?\n\n    Fortunately, Coq permits us to avoid this kind of redundancy.  In\n    place of any type argument we can write the \"implicit argument\"\n    [_], which can be read as \"Please figure out for yourself what\n    type belongs here.\"  More precisely, when Coq encounters a [_], it\n    will attempt to _unify_ all locally available information -- the\n    type of the function being applied, the types of the other\n    arguments, and the type expected by the context in which the\n    application appears -- to determine what concrete type should\n    replace the [_].\n\n    This may sound similar to type annotation inference -- and,\n    indeed, the two procedures rely on the same underlying mechanisms.\n    Instead of simply omitting the types of some arguments to a\n    function, like\n      app' X l1 l2 : list X :=\n    we can also replace the types with [_], like\n      app' (X : _) (l1 l2 : _) : list X :=\n    which tells Coq to attempt to infer the missing information, just\n    as with argument synthesis.\n\n    Using implicit arguments, the [length] function can be written\n    like this: *)\n\nFixpoint length' (X:Type) (l:list X) : nat :=\n  match l with\n  | nil      => 0\n  | cons h t => S (length' _ t)\n  end.\n\n(** In this instance, we don't save much by writing [_] instead of\n    [X].  But in many cases the difference can be significant.  For\n    example, suppose we want to write down a list containing the\n    numbers [1], [2], and [3].  Instead of writing this... *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...we can use argument synthesis to write this: *)\n\nDefinition list123' := cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ###################################################### *)\n(** *** Implicit Arguments *)\n\n(** If fact, we can go further.  To avoid having to sprinkle [_]'s\n    throughout our programs, we can tell Coq _always_ to infer the\n    type argument(s) of a given function. *)\n\nImplicit Arguments nil [[X]].\nImplicit Arguments cons [[X]].\nImplicit Arguments length [[X]].\nImplicit Arguments app [[X]].\nImplicit Arguments rev [[X]].\nImplicit Arguments snoc [[X]].\n\n(* note: no _ arguments required... *)\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\nCheck (length list123'').\n\n(** Alternatively, we can declare an argument to be implicit while\n    defining the function itself, by surrounding the argument in curly\n    braces.  For example: *)\n\nFixpoint length'' {X:Type} (l:list X) : nat :=\n  match l with\n  | nil      => 0\n  | cons h t => S (length'' t)\n  end.\n\n(** (Note that we didn't even have to provide a type argument to\n    the recursive call to [length''].)  We will use this style\n    whenever possible, although we will continue to use use explicit\n    [Implicit Argument] declarations for [Inductive] constructors. *)\n\n(** One small problem with declaring arguments [Implicit] is\n    that, occasionally, Coq does not have enough local information to\n    determine a type argument; in such cases, we need to tell Coq that\n    we want to give the argument explicitly this time, even though\n    we've globally declared it to be [Implicit].  For example, suppose we\n    write this: *)\n\n(* Definition mynil := nil. *)\n\n(** If we uncomment this definition, Coq will give us an error,\n    because it doesn't know what type argument to supply to [nil].  We\n    can help it by providing an explicit type declaration (so that Coq\n    has more information available when it gets to the \"application\"\n    of [nil]): *)\n\nDefinition mynil : list nat := nil.\n\n(** Alternatively, we can force the implicit arguments to be explicit by\n   prefixing the function name with [@]. *)\n\nCheck @nil.\n\nDefinition mynil' := @nil nat.\n\n(** Using argument synthesis and implicit arguments, we can\n    define convenient notation for lists, as before.  Since we have\n    made the constructor type arguments implicit, Coq will know to\n    automatically infer these when we use the notations. *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** Now lists can be written just the way we'd hope: *)\n\nDefinition list123''' := [1, 2, 3].\n\n\n\n\n\n(* ###################################################### *)\n(** *** Exercises: Polymorphic Lists *)\n\n(** **** Exercise: 2 stars, optional (poly_exercises) *)\n(** Here are a few simple exercises, just like ones in the [Lists]\n    chapter, for practice with polymorphism.  Fill in the definitions\n    and complete the proofs below. *)\n\nFixpoint repeat (X : Type) (n : X) (count : nat) : list X :=\n  match count with\n    | O => nil\n    | S count' => n :: (repeat _ n count')\n  end.\n\nExample test_repeat1:\n  repeat bool true 2 = cons true (cons true nil).\n Proof. reflexivity. Qed.\n\nTheorem nil_app : forall X:Type, forall l:list X,\n  app [] l = l.\nProof.\n  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.\n  rewrite -> IHs.\n  reflexivity.\n  Qed.\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  Case \"l = nil\".\n  reflexivity.\n  Case \"l = cons\".\n  simpl.\n  rewrite -> rev_snoc.\n  rewrite -> IHl.\n  reflexivity.\n  Qed.\n\nTheorem snoc_with_append : forall X : Type,\n                         forall l1 l2 : list X,\n                         forall v : X,\n  snoc (l1 ++ l2) v = l1 ++ (snoc l2 v).\nProof.\n  induction l1.\n  reflexivity.\n  intros.\n  simpl.\n  rewrite IHl1.\n  reflexivity.\n  Qed.\n\n(* ###################################################### *)\n(** ** Polymorphic Pairs *)\n\n(** Following the same pattern, the type definition we gave in\n    the last chapter for pairs of numbers can be generalized to\n    _polymorphic pairs_ (or _products_): *)\n\nInductive prod (X Y : Type) : Type :=\n  pair : X -> Y -> prod X Y.\n\nImplicit Arguments pair [[X] [Y]].\n\n(** As with lists, we make the type arguments implicit and define the\n    familiar concrete notation. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** We can also use the [Notation] mechanism to define the standard\n    notation for pair _types_: *)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** (The annotation [: type_scope] tells Coq that this abbreviation\n    should be used when parsing types.  This avoids a clash with the\n    multiplication symbol.) *)\n\n(** A note of caution: it is easy at first to get [(x,y)] and\n    [X*Y] confused.  Remember that [(x,y)] is a _value_ built from two\n    other values; [X*Y] is a _type_ built from two other types.  If\n    [x] has type [X] and [y] has type [Y], then [(x,y)] has type\n    [X*Y]. *)\n\n(** The first and second projection functions now look pretty\n    much as they would in any functional programming language. *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with (x,y) => x end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with (x,y) => y end.\n\n(** The following function takes two lists and combines them\n    into a list of pairs.  In many functional programming languages,\n    it is called [zip].  We call it [combine] for consistency with\n    Coq's standard library. *)\n(** Note that the pair notation can be used both in expressions and in\n    patterns... *)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match (lx,ly) with\n  | ([],_) => []\n  | (_,[]) => []\n  | (x::tx, y::ty) => (x,y) :: (combine tx ty)\n  end.\n\n(** **** 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\nCheck @combine.\n(*Warning: query commands should not be inserted in scripts\ncombine\n     : forall X Y : Type, list X -> list Y -> list (X * Y)*)\n\nEval simpl in (combine [1,2] [false,false,true,true]).\n(*Warning: query commands should not be inserted in scripts\n     = [(1, false), (2, false)]\n     : list (nat * bool)*)\n\n(** **** Exercise: 2 stars (split) *)\n(** The function [split] is the right inverse of combine: it takes a\n    list of pairs and returns a pair of lists.  In many functional\n    programing languages, this function is called [unzip].\n\n    Uncomment the material below and fill in the definition of\n    [split].  Make sure it passes the given unit tests. *)\n\n\nFixpoint split {X Y : Type} (l : list (X*Y)) : (list X)*(list Y) :=\nmatch l with \n | [] => ([], [])\n | (x, y) :: tl => match split tl with (lx, ly) => (x :: lx, y :: ly) \nend\nend.\n\nExample test_split:\n  split [(1,false),(2,false)] = ([1,2],[false,false]).\nProof. reflexivity.  Qed.\n\n(** (If you're reading the HTML version of this file, note that\n    there's an unresolved typesetting problem in the example: several\n    square brackets are missing.  Refer to the .v file for the correct\n    version. *)\n(** [] *)\n\n(* ###################################################### *)\n(** ** Polymorphic Options *)\n\n(** One last polymorphic type for now: _polymorphic options_.\n    The type declaration generalizes the one for [natoption] in the\n    previous chapter: *)\n\nInductive option (X:Type) : Type :=\n  | Some : X -> option X\n  | None : option X.\n\nImplicit Arguments Some [[X]].\nImplicit Arguments None [[X]].\n\n(** We can now rewrite the [index] function so that it works\n    with any type of lists. *)\n\nFixpoint index {X : Type} (n : nat)\n               (l : list X) : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if beq_nat n O then Some a else index (pred n) l'\n  end.\n\nExample test_index1 :    index 0 [4,5,6,7]  = Some 4.\nProof. reflexivity.  Qed.\nExample test_index2 :    index  1 [[1],[2]]  = Some [2].\nProof. reflexivity.  Qed.\nExample test_index3 :    index  2 [true]  = None.\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 1 star, optional (hd_opt_poly) *)\n(** Complete the definition of a polymorphic version of the\n    [hd_opt] function from the last chapter. Be sure that it\n    passes the unit tests below. *)\n\nDefinition hd_opt {X : Type} (l : list X)  : option X :=\n  (* FILL IN HERE *) admit.\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.\n (* FILL IN HERE *) Admitted.\nExample test_hd_opt2 :   hd_opt  [[1],[2]]  = Some [1].\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Functions as Data *)\n(* ###################################################### *)\n(** ** Higher-Order Functions *)\n\n(** Like many other modern programming languages -- including\n    all _functional languages_ (ML, Haskell, Scheme, etc.) -- Coq\n    treats functions as first-class citizens, allowing functions to be\n    passed as arguments to other functions, returned as results,\n    stored in data structures, etc.\n\n    Functions that manipulate other functions are often called\n    _higher-order_ functions.  Here's a simple one: *)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\n(** The argument [f] here is itself a function (from [X] to\n    [X]); the body of [doit3times] applies [f] three times to some\n    value [n]. *)\n\nCheck @doit3times.\n(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity.  Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity.  Qed.\n\n(* ###################################################### *)\n(** ** Partial Application *)\n\n(** In fact, the multiple-argument functions we have already\n    seen are also examples of passing functions as data.  To see why,\n    recall the type of [plus]. *)\n\nCheck plus.\n(* ==> nat -> nat -> nat *)\n\n(** Each [->] in this expression is actually a _binary_ operator\n    on types.  (This is the same as saying that Coq primitively\n    supports only one-argument functions -- do you see why?)  This\n    operator is _right-associative_, so the type of [plus] is really a\n    shorthand for [nat -> (nat -> nat)] -- i.e., it can be read as\n    saying that \"[plus] is a one-argument function that takes a [nat]\n    and returns a one-argument function that takes another [nat] and\n    returns a [nat].\"  In the examples above, we have always applied\n    [plus] to both of its arguments at once, but if we like we can\n    supply just the first.  This is called _partial application_. *)\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity.  Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity.  Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity.  Qed.\n\n(* ###################################################### *)\n(** ** Digression: Currying *)\n\n(** **** Exercise: 2 stars, advanced (currying) *)\n(** In Coq, a function [f : A -> B -> C] really has the type [A\n    -> (B -> C)].  That is, if you give [f] a value of type [A], it\n    will give you function [f' : B -> C].  If you then give [f'] a\n    value of type [B], it will return a value of type [C].  This\n    allows for partial application, as in [plus3].  Processing a list\n    of arguments with functions that return functions is called\n    _currying_, in honor of the logician Haskell Curry.\n\n    Conversely, we can reinterpret the type [A -> B -> C] as [(A *\n    B) -> C].  This is called _uncurrying_.  With an uncurried binary\n    function, both arguments must be given at once as a pair; there is\n    no partial application. *)\n\n(** We can define currying as follows: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** As an exercise, define its inverse, [prod_uncurry].  Then prove\n    the theorems below to show that the two are inverses. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z :=\n  (* FILL IN HERE *) admit.\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  (* FILL IN HERE *) Admitted.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                               (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Filter *)\n\n(** Here is a useful higher-order function, which takes a list\n    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])\n    and \"filters\" the list, returning a new list containing just those\n    elements for which the predicate returns [true]. *)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | []     => []\n  | h :: t => if test h then h :: (filter test t)\n                        else       filter test t\n  end.\n\n(** For example, if we apply [filter] to the predicate [evenb]\n    and a list of numbers [l], it returns a list containing just the\n    even members of [l]. *)\n\nExample test_filter1: filter evenb [1,2,3,4] = [2,4].\nProof. reflexivity.  Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  beq_nat (length l) 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1, 2], [3], [4], [5,6,7], [], [8] ]\n  = [ [3], [4], [8] ].\nProof. reflexivity.  Qed.\n\n(** We can use [filter] to give a concise version of the\n    [countoddmembers] function from the [Lists] chapter. *)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_countoddmembers'1:   countoddmembers' [1,0,3,1,4,5] = 4.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'2:   countoddmembers' [0,2,4] = 0.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity.  Qed.\n\n(* ###################################################### *)\n(** ** Anonymous Functions *)\n\n(** It is a little annoying to be forced to define the function\n    [length_is_1] and give it a name just to be able to pass it as an\n    argument to [filter], since we will probably never use it again.\n    Moreover, this is not an isolated example.  When using\n    higher-order functions, we often want to pass as arguments\n    \"one-off\" functions that we will never use again; having to give\n    each of these functions a name would be tedious.\n\n    Fortunately, there is a better way. It is also possible to\n    construct a function \"on the fly\" without declaring it at the top\n    level or giving it a name; this is analogous to the notation we've\n    been using for writing down constant lists, natural numbers, and\n    so on. *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity.  Qed.\n\n(** Here is the motivating example from before, rewritten to use\n    an anonymous function. *)\n\nExample test_filter2':\n    filter (fun l => beq_nat (length l) 1)\n           [ [1, 2], [3], [4], [5,6,7], [], [8] ]\n  = [ [3], [4], [8] ].\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 2 stars (filter_even_gt7) *)\n\n(** Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  (* FILL IN HERE *) admit.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1,2,6,9,10,3,12,8] = [10,12,8].\n (* FILL IN HERE *) Admitted.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5,2,6,19,129] = [].\n (* FILL IN HERE *) Admitted.\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(* FILL IN HERE *) admit.\n\nExample test_partition1: partition oddb [1,2,3,4,5] = ([1,3,5], [2,4]).\n(* FILL IN HERE *) Admitted.\nExample test_partition2: partition (fun x => false) [5,9,0] = ([], [5,9,0]).\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Map *)\n\n(** Another handy higher-order function is called [map]. *)\n\nFixpoint map {X Y:Type} (f:X->Y) (l:list X)\n             : (list Y) :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]\n    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has\n    been applied to each element of [l] in turn.  For example: *)\n\nExample test_map1: map (plus 3) [2,0,2] = [5,3,5].\nProof. reflexivity.  Qed.\n\n(** The element types of the input and output lists need not be\n    the same ([map] takes _two_ type arguments, [X] and [Y]).  This\n    version of [map] can thus be applied to a list of numbers and a\n    function from numbers to booleans to yield a list of booleans: *)\n\nExample test_map2: map oddb [2,1,2,5] = [false,true,false,true].\nProof. reflexivity.  Qed.\n\n(** It can even be applied to a list of numbers and\n    a function from numbers to _lists_ of booleans to\n    yield a list of lists of booleans: *)\n\nExample test_map3:\n    map (fun n => [evenb n,oddb n]) [2,1,2,5]\n  = [[true,false],[false,true],[true,false],[false,true]].\nProof. reflexivity.  Qed.\n\n\n\n(** **** Exercise: 3 stars (map_rev) *)\n(** Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (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  (* FILL IN HERE *) admit.\n\nExample test_flat_map1:\n  flat_map (fun n => [n,n,n]) [1,5,4]\n  = [1, 1, 1, 5, 5, 5, 4, 4, 4].\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Lists are not the only inductive type that we can write a\n    [map] function for.  Here is the definition of [map] for the\n    [option] type: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\n(** **** Exercise: 2 stars, optional (implicit_args) *)\n(** The definitions and uses of [filter] and [map] use implicit\n    arguments in many places.  Replace the curly braces around the\n    implicit arguments with parentheses, and then fill in explicit\n    type parameters where necessary and use Coq to check that you've\n    done so correctly.  (This exercise is not to be turned in; it is\n    probably easiest to do it on a _copy_ of this file that you can\n    throw away afterwards.)  [] *)\n\n(* ###################################################### *)\n(** ** Fold *)\n\n(** An even more powerful higher-order function is called\n    [fold].  This function is the inspiration for the \"[reduce]\"\n    operation that lies at the heart of Google's map/reduce\n    distributed programming framework. *)\n\nFixpoint fold {X Y:Type} (f: X->Y->Y) (l:list X) (b:Y) : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(* /TERSE *)\n\n(** Intuitively, the behavior of the [fold] operation is to\n    insert a given binary operator [f] between every pair of elements\n    in a given list.  For example, [ fold plus [1,2,3,4] ] intuitively\n    means [1+2+3+4].  To make this precise, we also need a \"starting\n    element\" that serves as the initial second input to [f].  So, for\n    example,\n   fold plus [1,2,3,4] 0\n    yields\n   1 + (2 + (3 + (4 + 0))).\n    Here are some more examples:\n*)\n\nCheck (fold andb).\n(* ===> fold andb : list bool -> bool -> bool *)\n\nExample fold_example1 : fold mult [1,2,3,4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 : fold andb [true,true,false,true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 : fold app  [[1],[],[2,3],[4]] [] = [1,2,3,4].\nProof. reflexivity. Qed.\n\n\n(** **** Exercise: 1 star, advanced (fold_types_different) *)\n(** Observe that the type of [fold] is parameterized by _two_ type\n    variables, [X] and [Y], and the parameter [f] is a binary operator\n    that takes an [X] and a [Y] and returns a [Y].  Can you think of a\n    situation where it would be useful for [X] and [Y] to be\n    different? *)\n\n(* ###################################################### *)\n(** ** Functions For Constructing Functions *)\n\n(** Most of the higher-order functions we have talked about so\n    far take functions as _arguments_.  Now let's look at some\n    examples involving _returning_ functions as the results of other\n    functions.\n\n    To begin, here is a function that takes a value [x] (drawn from\n    some type [X]) and returns a function from [nat] to [X] that\n    yields [x] whenever it is called, ignoring its [nat] argument. *)\n\nDefinition constfun {X: Type} (x: X) : nat->X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** Similarly, but a bit more interestingly, here is a function\n    that takes a function [f] from numbers to some type [X], a number\n    [k], and a value [x], and constructs a function that behaves\n    exactly like [f] except that, when called with the argument [k],\n    it returns [x]. *)\n\nDefinition override {X: Type} (f: nat->X) (k:nat) (x:X) : nat->X:=\n  fun (k':nat) => if beq_nat k k' then x else f k'.\n\n(** For example, we can apply [override] twice to obtain a\n    function from numbers to booleans that returns [false] on [1] and\n    [3] and returns [true] on all other arguments. *)\n\nDefinition fmostlytrue := override (override ftrue 1 false) 3 false.\n\nExample override_example1 : fmostlytrue 0 = true.\nProof. reflexivity. Qed.\n\nExample override_example2 : fmostlytrue 1 = false.\nProof. reflexivity. Qed.\n\nExample override_example3 : fmostlytrue 2 = true.\nProof. reflexivity. Qed.\n\nExample override_example4 : fmostlytrue 3 = false.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star (override_example) *)\n(** Before starting to work on the following proof, make sure you\n    understand exactly what the theorem is saying and can paraphrase\n    it in your own words.  The proof itself is straightforward. *)\n\nTheorem override_example : forall (b:bool),\n  (override (constfun b) 3 true) 2 = b.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** We'll use function overriding heavily in parts of the rest of the\n    course, and we will end up needing to know quite a bit about its\n    properties.  To prove these properties, though, we need to know\n    about a few more of Coq's tactics; developing these is the main\n    topic of the next chapter.  For now, though, let's introduce just\n    one very useful tactic that will also help us with proving\n    properties of some of the other functions we have introduced in\n    this chapter. *)\n\n(* ###################################################### *)\n(** * The [unfold] Tactic *)\n\n(** Sometimes, a proof will get stuck because Coq doesn't\n    automatically expand a function call into its definition.  (This\n    is a feature, not a bug: if Coq automatically expanded everything\n    possible, our proof goals would quickly become enormous -- hard to\n    read and slow for Coq to manipulate!) *)\n\nTheorem unfold_example_bad : forall m n,\n  3 + n = m ->\n  plus3 n + 1 = m + 1.\nProof.\n  intros m n H.\n  (* At this point, we'd like to do [rewrite -> H], since \n     [plus3 n] is definitionally equal to [3 + n].  However, \n     Coq doesn't automatically expand [plus3 n] to its \n     definition. *)\n  Admitted.\n\n(** The [unfold] tactic can be used to explicitly replace a\n    defined name by the right-hand side of its definition.  *)\n\nTheorem unfold_example : forall m n,\n  3 + n = m ->\n  plus3 n + 1 = m + 1.\nProof.\n  intros m n H.\n  unfold plus3.\n  rewrite -> H.\n  reflexivity.  Qed.\n\n(** Now we can prove a first property of [override]: If we\n    override a function at some argument [k] and then look up [k], we\n    get back the overridden value. *)\n\nTheorem override_eq : forall {X:Type} x k (f:nat->X),\n  (override f k x) k = x.\nProof.\n  intros X x k f.\n  unfold override.\n  rewrite <- beq_nat_refl.\n  reflexivity.  Qed.\n\n(** This proof was straightforward, but note that it requires\n    [unfold] to expand the definition of [override]. *)\n\n(** **** Exercise: 2 stars (override_neq) *)\nTheorem override_neq : forall {X:Type} x1 x2 k1 k2 (f : nat->X),\n  f k1 = x1 ->\n  beq_nat k2 k1 = false ->\n  (override f k2 x2) k1 = x1.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** As the inverse of [unfold], Coq also provides a tactic\n    [fold], which can be used to \"unexpand\" a definition.  It is used\n    much less often. *)\n\n(* ##################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 2 stars (fold_length) *)\n(** Many common functions on lists can be implemented in terms of\n   [fold].  For example, here is an alternate definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4,7,0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length]. *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\n(* FILL IN HERE *) Admitted. \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(* FILL IN HERE *) admit.\n\n(** Write down a theorem in Coq stating that [fold_map] is correct,\n    and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (index_informal) *)\n(** Recall the definition of the [index] function:\n   Fixpoint index {X : Type} (n : nat) (l : list X) : option X :=\n     match l with\n     | [] => None \n     | a :: l' => if beq_nat n O then Some a else index (pred n) l'\n     end.\n   Write an informal proof of the following theorem:\n   forall X n l, length l = n -> @index X (S n) l = None.\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (church_numerals) *)\n\nModule Church.\n\n(** In this exercise, we will explore an alternative way of defining\n    natural numbers, using the so-called _Church numerals_, named\n    after mathematician Alonzo Church. We can represent a natural\n    number [n] as a function that takes a function [f] as a parameter\n    and returns [f] iterated [n] times. More formally, *)\n\nDefinition nat := forall X : Type, (X -> X) -> X -> X.\n\n(** Let's see how to write some numbers with this notation. Any\n    function [f] iterated once shouldn't change. Thus, *)\n\nDefinition one : nat := \n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** [two] should apply [f] twice to its argument: *)\n\nDefinition two : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** [zero] is somewhat trickier: how can we apply a function zero\n    times? The answer is simple: just leave the argument untouched. *)\n\nDefinition zero : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(** More generally, a number [n] will be written as [fun X f x => f (f\n    ... (f x) ...)], with [n] occurrences of [f]. Notice in particular\n    how the [doit3times] function we've defined previously is actually\n    just the representation of [3]. *)\n\nDefinition three : nat := @doit3times.\n\n(** Complete the definitions of the following functions. Make sure\n    that the corresponding unit tests pass by proving them with\n    [reflexivity]. *)    \n\n(** Successor of a natural number *)\n\nDefinition succ (n : nat) : nat :=\n  (* FILL IN HERE *) admit.\n\nExample succ_1 : succ zero = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample succ_2 : succ one = two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample succ_3 : succ two = three.\nProof. (* FILL IN HERE *) Admitted.\n\n(** Addition of two natural numbers *)\n\nDefinition plus (n m : nat) : nat :=\n  (* FILL IN HERE *) admit.\n\nExample plus_1 : plus zero one = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample plus_2 : plus two three = plus three two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. (* FILL IN HERE *) Admitted.\n\n(** Multiplication *)\n\nDefinition mult (n m : nat) : nat := \n  (* FILL IN HERE *) admit.\n\nExample mult_1 : mult one one = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample mult_2 : mult zero (plus three three) = zero.\nProof. (* FILL IN HERE *) Admitted.\n\nExample mult_3 : mult two three = plus three three.\nProof. (* FILL IN HERE *) Admitted.\n\n(** Exponentiation *)\n\n(** Hint: Polymorphism plays a crucial role here. However, 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  (* FILL IN HERE *) admit.\n\nExample exp_1 : exp two two = plus two two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample exp_2 : exp three two = plus (mult two (mult two two)) one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample exp_3 : exp three zero = one.\nProof. (* FILL IN HERE *) Admitted.\n\nEnd Church.\n\n(** [] *)\n\n(* $Date: 2013-02-06 20:14:06 -0500 (Wed, 06 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/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506581031359, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.6581332731058726}}
{"text": "Require Import bool.\nRequire Import nat.\nRequire Import syntax.\nRequire Import eval.\nRequire Import state.\nRequire Import dictionary.\nRequire Import Imp_code.\n\nExample test_aeval0 : forall (env:State), aeval env (ANum 17) = 17.\nProof. reflexivity. Qed.\n\n\nExample test_aeval1 : forall (env:State), aeval env (APlus (ANum 2) (ANum 5)) = 7.\nProof. reflexivity. Qed.\n\n\nExample test_aeval2 : forall (env:State), aeval env (AMinus (ANum 12) (ANum 5)) = 7.\nProof. reflexivity. Qed.\n\n\nExample test_aeval3 : forall (env:State), aeval env (AMult (ANum 4) (ANum 5)) = 20.\nProof. reflexivity. Qed.\n\nExample test_ceval1 : ceval (\n    x ::= ANum 2;;\n    IFB BLe (AKey x) (ANum 1)\n        THEN y ::= ANum 3\n        ELSE z ::= ANum 4\n    FI) \n    emptyState\n    (t_update (t_update emptyState x 2) z 4).\nProof.\n    apply E_Seq with (e' := t_update emptyState x 2).\n    - apply E_Ass. reflexivity.\n    - apply E_IfFalse.\n        + reflexivity.\n        + apply E_Ass. reflexivity.\nQed.\n\nTheorem test_ceval2 : ceval pup_to_n \n    (t_update emptyState x 3)\n    (t_update\n        (t_update\n            (t_update \n                (t_update\n                    (t_update \n                        (t_update \n                            (t_update \n                                (t_update \n                                    emptyState \n                                    x 3)  y 0) y 3) x 2) y 5) x 1) y 6) x 0).\nProof.\n    remember (t_update emptyState x 3) as e0 eqn:E0.\n    remember (t_update e0 y 0) as e1 eqn:E1.\n    remember (t_update e1 y 3) as e2 eqn:E2.\n    remember (t_update e2 x 2) as e3 eqn:E3.\n    remember (t_update e3 y 5) as e4 eqn:E4.\n    remember (t_update e4 x 1) as e5 eqn:E5.\n    remember (t_update e5 y 6) as e6 eqn:E6.\n    remember (t_update e6 x 0) as e7 eqn:E7. \n    apply E_Seq with (e':=e1).\n        - rewrite E1. apply E_Ass. reflexivity.\n        - apply E_WhileLoop with (e':=e3).\n            + rewrite E1, E0. reflexivity.  \n            + apply E_Seq with (e':=e2). \n                { rewrite E2. apply E_Ass. \n                    rewrite E1, E0. reflexivity. }\n                { rewrite E3. apply E_Ass. \n                    rewrite E2, E1, E0. reflexivity. }  \n            + apply E_WhileLoop with (e':=e5).\n                { rewrite E3, E2, E1, E0. reflexivity. }\n                { rewrite E5. apply E_Seq with (e':=e4).\n                    { rewrite E4. apply E_Ass. \n                        rewrite E3, E2, E1, E0. reflexivity. }\n                    { apply E_Ass. \n                        rewrite E4, E3, E2, E1, E0. reflexivity. } }\n                { apply E_WhileLoop with (e':=e7).\n                    { rewrite E5, E4, E3, E2, E1, E0. reflexivity. }\n                    { apply E_Seq with (e':=e6).\n                        { rewrite E6. apply E_Ass. \n                            rewrite E5, E4, E3, E2, E1, E0. reflexivity. }\n                        { rewrite E7. apply E_Ass.\n                            rewrite E6, E5, E4, E3, E2, E1, E0. reflexivity. } }\n                    { apply E_WhileEnd.\n                        rewrite E7, E6, E5, E4, E3, E2, E1, E0. reflexivity. }}\nQed. \n\n\nTheorem test_ceval3 : forall (e e':State) (n:nat),\n    e x = n -> ceval Add2_x e e' -> e' x = n + 2.\nProof.\n    intros e e' n H0 H1. unfold Add2_x in H1. inversion H1. subst. simpl.\n    unfold t_update. reflexivity.\nQed.\n\n\nTheorem test_ceval4 : forall (e e':State) (n m:nat),\n    e x = n -> e y = m -> ceval Mult_x_y_z e e' -> e' z = n*m.\nProof.\n    intros e e' n m Hx Hy H. unfold Mult_x_y_z in H. inversion H. subst.\n    simpl. unfold t_update. reflexivity.\nQed.\n\n(* infinite loop never stop *)\nTheorem test_ceval5 : forall (e e':State), ~ceval loop e e'.\nProof.\n    intros e e' H. unfold loop in H.\n    remember (WHILE BTrue DO SKIP END) as c eqn:Hc. revert Hc. \n    induction H as\n        [e\n        |e a n x H0\n        |e e' e'' c1 c2 H1 IH1 H2 IH2\n        |e e' b c1 c2 H0 H1 IH1\n        |e e' b c1 c2 H0 H1 IH1\n        |e b c H0\n        |e e' e'' b c H0 H1 IH1 H2 IH2\n        ].\n    - intros H'. inversion H'.\n    - intros H'. inversion H'.\n    - intros H'. inversion H'.\n    - intros H'. inversion H'.\n    - intros H'. inversion H'.\n    - intros H'. inversion H'. subst. assert (true = false) as E.\n        { assumption. } inversion E.\n    - intros H'. apply IH2. 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/test_eval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6581332478558362}}
{"text": "(* efficiency problem related to termination checker in 8.2,\nsolved in 8.3 *)\n\nRequire Import Bool.\n\n(* \nLa plus grande partie de ce qui suit revient a genere de gros calculs\ntout d'abord sur le type Z, puis sur le type word\n*)\n\n(* BEGIN calculasse Z, pris essentiellement chez Xavier *)\n\nDefinition Nbit := 31%nat.\nDefinition Zbit := 30%nat.\nDefinition Cbit := 29%nat.\nDefinition Vbit := 28%nat.\n\nRequire Import ZArith.\nOpen Scope Z_scope.\n\n\nDefinition wordsize : nat := 32%nat.\nDefinition modulus : Z := two_power_nat wordsize.\nRecord int: Type := mkint { intval: Z; intrange: 0 <= intval < modulus }.\n\nLemma two_power_nat_O : two_power_nat O = 1.\nProof. reflexivity. Qed.\n\nLemma two_power_nat_pos : forall n : nat, two_power_nat n > 0.\nProof.\n  induction n. rewrite two_power_nat_O. omega.\n  rewrite two_power_nat_S. omega.\nQed.\n\nLemma mod_in_range:\n  forall x, 0 <= Zmod x modulus < modulus.\nProof.\n  intro.\n  exact (Z_mod_lt x modulus (two_power_nat_pos wordsize)).\nQed.\nDefinition repr (x: Z) : int := \n  mkint (Zmod x modulus) (mod_in_range x).\n\nDefinition unsigned (n: int) : Z := intval n.\nDefinition Z_bin_decomp (x: Z) : bool * Z :=\n  match x with\n  | Z0 => (false, 0)\n  | Zpos p =>\n      match p with\n      | xI q => (true, Zpos q)\n      | xO q => (false, Zpos q)\n      | xH => (true, 0)\n      end\n  | Zneg p =>\n      match p with\n      | xI q => (true, Zneg q - 1)\n      | xO q => (false, Zneg q)\n      | xH => (true, -1)\n      end\n  end.\nDefinition zeq: forall (x y: Z), {x = y} + {x <> y} := Z_eq_dec.\n\nFixpoint bits_of_Z (n: nat) (x: Z) {struct n}: Z -> bool :=\n  match n with\n  | O =>\n      (fun i: Z => false)\n  | S m =>\n      let (b, y) := Z_bin_decomp x in\n      let f := bits_of_Z m y in\n      (fun i: Z => if zeq i 0 then b else f (i - 1))\n  end.\n\nDefinition Z_shift_add (b: bool) (x: Z) :=\n  if b then 2 * x + 1 else 2 * x.\n\nFixpoint Z_of_bits (n: nat) (f: Z -> bool) {struct n}: Z :=\n  match n with\n  | O => 0\n  | S m => Z_shift_add (f 0) (Z_of_bits m (fun i => f (i + 1)))\n  end.\n\n\nDefinition bitwise_binop (f: bool -> bool -> bool) (x y: int) :=\n  let fx := bits_of_Z wordsize (unsigned x) in\n  let fy := bits_of_Z wordsize (unsigned y) in\n  repr (Z_of_bits wordsize (fun i => f (fx i) (fy i))).\n\nDefinition and (x y: int): int := bitwise_binop andb x y.\n\n(* END calculasse Z *)\n\n\n(* BEGIN calculasse word *)\n\nNotation word := int.\nCoercion intval : word >-> Z.\n\nFixpoint masks_aux (n k : nat) : Z :=\n  match k with\n    | O => two_power_nat n\n    | S k' => two_power_nat n + masks_aux (S n) k'\n  end.\nDefinition masks (n p : nat) : word := repr (masks_aux n (p-n)).\n\nDefinition bits (k l : nat) (w : word) : word := and (masks k l) w.\nDefinition bits_val (k l : nat) (w : word) : Z :=\n  bits k l w / two_power_nat k.\n\nDefinition mask (n : nat) : word := repr (two_power_nat n).\nDefinition bit (k : nat) (w : word) : word := and (mask k) w.\nDefinition zne (x y : Z) : bool := if Z_eq_dec x y then false else true.\nDefinition is_set (k : nat) (w : word) : bool := zne (bit k w) 0.\n\n(* *)\n\nDefinition FConditionPassed (w : word) : bool :=\n  match bits_val 28 31 w with\n    | (*0000*) 0 => (* Z set *) is_set Zbit w\n    | (*0001*) 1 => (* Z clear *) negb (is_set Zbit w)\n    | (*0010*) 2 => (* C set *) is_set Cbit w\n    | (*0011*) 3 => (* C clear *) negb (is_set Cbit w)\n    | (*0100*) 4 => (* N set *) is_set Cbit w\n    | (*0101*) 5 => (* N clear *) negb (is_set Cbit w)\n    | (*0110*) 6 => (* V set *) is_set Vbit w\n    | (*0111*) 7 => (* V clear *) negb (is_set Vbit w)\n    | (*1000*) 8 => (* C set and Z clear *)\n      andb (is_set Cbit w) (negb (is_set Zbit w))\n    | (*1001*) 9 => (* C clear or Z set *)\n      orb (negb (is_set Cbit w)) (is_set Zbit w)\n    | (*1010*) 10 => (* N set and V set, or N clear and V clear (N==V) *)\n      eqb (is_set Nbit w) (is_set Vbit w)\n    | (*1011*) 11 => (* N set and V clear, or N clear and V set (N!=V) *)\n      negb (eqb (is_set Nbit w) (is_set Vbit w))\n    | (*1100*) 12 => (* Z clear, and either N set and V set,\n         or N clear and V clear (Z==0,N==V) *)\n      andb (negb (is_set Zbit w)) (eqb (is_set Nbit w) (is_set Vbit w))\n    | (*1101*) 13 => (* Z set, or N set and V clear, or N clear and V set\n         (Z==1 or N!=V) *)\n      orb (is_set Zbit w) (negb (eqb (is_set Nbit w) (is_set Vbit w)))\n    | _ => true\n  end.\n\n(* END calculasse word *)\n\n\n(* \nPoint fixe dont le type checking pedale dans le yaourt. \nSi on enleve des cas dans [FConditionPassed] ci-dessus,\nca pedale d'autant moins.\nOn ne voit pas pourquoi [FConditionPassed w] est examine\ndans la def de pt fixe.\n*)\nInductive inst : Type :=\n| Unpredictable\n| IfThen (i : inst)\n.\n\nFixpoint interp (w : word) (i : inst) : option bool :=\n  match i with\n    | Unpredictable => None\n    | IfThen i =>\n      if FConditionPassed w then interp w i else None\n  end.\n\n", "meta": {"author": "git-inria", "repo": "simsoc-cert", "sha": "2a2d45c3d94745fb33d91ed75ca91de083b4cebd", "save_path": "github-repos/coq/git-inria-simsoc-cert", "path": "github-repos/coq/git-inria-simsoc-cert/simsoc-cert-2a2d45c3d94745fb33d91ed75ca91de083b4cebd/coq/coq-bugs/Bug1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6578364613432793}}
{"text": "Require Import FunctionalExtensionality.\n\nSet Asymmetric Patterns.\n\n\n(** Isomorphisms between types. *)\nRecord T { A B : Type } : Type :=\n  { to      : A -> B\n  ; from    : B -> A\n  ; from_to : forall (a : A), from (to a) = a\n  ; to_from : forall (b : B), to (from b) = b\n  }.\n\nArguments T : clear implicits.\n\n(** Isomorphisms form an equivalence relation: they are reflexivity,\n    symmetric, and transitive. *)\nTheorem Refl (A : Type) : T A A.\nProof.\nrefine (\n  {| to   := fun x => x\n   ; from := fun x => x |});\nreflexivity.\nDefined.\n\nDefinition Sym {A B : Type} (iso : T A B) : T B A :=\n  {| to := from iso\n   ; from := to iso\n   ; from_to := to_from iso\n   ; to_from := from_to iso\n  |}.\n\nTheorem Trans { A B C : Type } :\n  T A B -> T B C -> T A C.\nProof.\nintros AB BC.\nrefine (\n{| to   := fun x => to   BC (to   AB x)\n ; from := fun y => from AB (from BC y)\n|}); intros.\n- rewrite (from_to BC).\n  rewrite (from_to AB).\n  reflexivity.\n- rewrite (to_from AB).\n  rewrite (to_from BC).\n  reflexivity.\nDefined.\n\n(** * Sigma type isomorphisms *)\n(** Isomorphisms between Sigma types with different indexing types. *)\n\nDefinition FSig {B : False -> Type} : T (sigT B) False.\nProof. refine (\n{| to := @projT1 _ B\n ; from := False_rect (sigT B) |}).\nintros. destruct a. contradiction. \nintros. contradiction.\nDefined.\n\nDefinition TSig {B : True -> Type} : T (sigT B) (B I).\nProof. refine (\n{| to := fun x => match x with existT I p => p end\n ; from := existT _ I\n|}).\nProof. \nintros x. destruct x. destruct x. reflexivity.\nintros b. reflexivity.\nDefined.\n\nDefinition PlusSig {A1 A2 : Type}\n  {B : (A1 + A2)%type -> Type}\n  {B1 B2 : Type }\n  (iso1 : T (sigT (fun x => B (inl x))) B1)\n  (iso2 : T (sigT (fun x => B (inr x))) B2)\n  :       T (sigT B)                 (B1 + B2)%type.\nProof.\nrefine (\n{| to := fun x : sigT B => match x with\n   | existT (inl a1) pa1 => inl (to iso1 (existT (fun x => B (inl x)) a1 pa1))\n   | existT (inr a2) pa2 => inr (to iso2 (existT (fun x => B (inr x)) a2 pa2))\n   end\n; from := fun x => match x with\n   | inl b1 => match from iso1 b1 with\n     | existT a1 pa1 => existT B (inl a1) pa1\n     end\n   | inr b2 => match from iso2 b2 with\n     | existT a2 pa2 => existT B (inr a2) pa2\n     end\n   end\n|}).\nintros a; destruct a; simpl; destruct x; simpl; rewrite from_to; reflexivity.\nintros b. destruct b; simpl.\ndestruct (from iso1 b) eqn:beqn.\nrewrite <- beqn. rewrite to_from; reflexivity.\ndestruct (from iso2 b) eqn:beqn.\nrewrite <- beqn. rewrite to_from; reflexivity.\nDefined.\n\nLemma sigTimes {A B : Type} : T (A * B) (sigT (fun _ : A => B)).\nProof.\nrefine (\n{| to  := fun p => match p with (x, y) => existT (fun _ : A => B) x y end\n; from := fun p => match p with existT x y => (x, y) end\n|} ).\nProof.\nintros. destruct a. reflexivity.\nintros. destruct b. reflexivity.\nDefined. \n\n(** * Function type isomorphisms *)\n(** Isomorphisms between function types with different argument types. *)\n\nLemma FFunc {B : Type} : T (False -> B) True.\nProof.\nrefine (\n{| to   := fun _ => I\n ; from := fun _ => False_rect B |}); intros.\napply functional_extensionality. intros. inversion x.\ndestruct b. reflexivity.\nDefined.\n\nLemma TFunc {B : Type} : T (True -> B) B.\nProof.\nrefine (\n{| to   := fun f => f I\n ; from := fun b _ => b |}); intros.\napply functional_extensionality. intros. destruct x. reflexivity.\nreflexivity.\nDefined.\n\nLemma PlusFunc {A1 A2 B T1 T2 : Type} : \n   T (A1 -> B) T1\n -> T (A2 -> B) T2\n -> T ((A1 + A2)%type -> B) (T1 * T2).\nProof.\nintros I1 I2.\nrefine (\n{| to := fun f => ( to I1 (fun a1 => f (inl a1))\n                 , to I2 (fun a2 => f (inr a2)) )\n ; from := fun p => match p with\n   | (x, y) => fun v => match v with\n     | inl a1 => from I1 x a1\n     | inr a2 => from I2 y a2\n     end\n   end |}); intros.\n+ apply functional_extensionality; intros. \n  destruct x.\n   - rewrite (from_to I1). reflexivity.\n   - rewrite (from_to I2). reflexivity.\n+ destruct b. f_equal. \n  - rewrite (@to_from _ _ I1). reflexivity.\n  - rewrite (@to_from _ _ I2). reflexivity.\nDefined.\n\nLemma TimesFunc { A1 A2 B X Y : Type } : \n    T (A2 -> B) X\n  -> T (A1 -> X) Y\n  -> T ((A1 * A2)%type -> B) Y.\nProof.\nintros IX IY.\nrefine (\n{| to := fun f => to IY (fun a1 =>\n                 to IX (fun a2 => f (a1, a2)))\n ; from := fun u p => match p with\n   | (a1, a2) => let t := (from IY u) a1\n                in       (from IX t) a2\n   end\n|}); intros.\napply functional_extensionality; intros.\ndestruct x.\nsimpl. rewrite (from_to IY). rewrite (from_to IX). reflexivity.\nsimpl.\nassert (\n(fun a1 : A1 => to IX (fun a2 : A2 => from IX (from IY b a1) a2))\n = \n(fun a1 : A1 => to IX             (from IX (from IY b a1)))\n).\nreflexivity.\nrewrite H. \nassert (\n(fun a1 : A1 => to IX (from IX (from IY b a1)))\n=\n(fun a1 : A1 =>                (from IY b a1))\n).\napply functional_extensionality; intros.\nrewrite (to_from IX). reflexivity.\nrewrite H0.\nrewrite (to_from IY).\nreflexivity.\nDefined.\n\n(** * Congruences *)\n(** Isomorphism is a congruence over the type forming operations\n    for sums, products, and functions. *)\n\nTheorem PlusCong {A B A' B' : Type}\n (IA : T A A')\n (IB : T B B')\n : T (A + B)%type (A' + B')%type.\nProof.\nrefine (\n{| to := fun x => match x with\n   | inl a => inl (to IA a)\n   | inr b => inr (to IB b)\n   end\n ; from := fun x => match x with\n   | inl a' => inl (from IA a')\n   | inr b' => inr (from IB b')\n   end\n|}).\nintros x; destruct x.\nrewrite (from_to IA). reflexivity.\nrewrite (from_to IB). reflexivity.\nintros x; destruct x.\nrewrite (to_from IA). reflexivity.\nrewrite (to_from IB). reflexivity.\nDefined.\n\nTheorem TimesCong {A B A' B' : Type}\n (IA : T A A')\n (IB : T B B')\n : T (A * B)%type (A' * B') %type.\nProof.\nrefine (\n{| to := fun p => match p with | (x, y) => (to IA x, to IB y) end\n ; from := fun p => match p with | (x, y) => (from IA x, from IB y) end\n|}); intros p; destruct p; f_equal.\napply (from_to IA).\napply (from_to IB).\napply (to_from IA).\napply (to_from IB).\nDefined.\n\nTheorem FuncCong { A A' B B' : Type } :\n  T A A' -> T B B' -> T (A -> B) (A' -> B').\nProof.\nintros IA IB.\nrefine (\n  {| to   := fun f a' => to   IB (f (from IA a'))\n   ; from := fun f a  => from IB (f (to   IA a )) |});\nintros; apply functional_extensionality; intro x; simpl;\n  repeat rewrite (from_to IA);\n  repeat rewrite (to_from IA);\n  repeat rewrite (from_to IB);\n  repeat rewrite (to_from IB);\n  reflexivity.\nDefined.\n\nDefinition PlusComm {A B} : T (A + B) (B + A).\nProof. refine (\n  {| to := fun x => match x with\n  | inl a => inr a\n  | inr b => inl b\n  end\n  ; from := fun y => match y with\n  | inl b => inr b\n  | inr a => inl a\n  end\n  |}); intros.\n- destruct a; reflexivity.\n- destruct b; reflexivity.\nDefined.\n\nTheorem eq_dec {A B : Type} : (forall x y : A, {x = y} + {x <> y})\n  -> T A B -> forall x y : B, {x = y} + {x <> y}.\nProof.\nintros dec t x y.\ndestruct (dec (from t x) (from t y)).\n  + left. \n    replace x with (to t (from t x)) by apply to_from.\n    replace y with (to t (from t y)) by apply to_from.\n    f_equal. assumption.\n  + right. congruence.\nQed.\n\n(** * Infinite *)\n(** Cantor's diagonal arguments, which says that there is no bijection\n    between natural numbers and sequences of natural numbers. *)\nTheorem Cantor : T nat (nat -> nat) -> False.\nProof.\nintros iso.\ndestruct iso.\npose (f := fun n => S (to0 n n)).\nassert (forall (n : nat), f <> to0 n).\n- intros n. assert (to0 n n <> f n).\n  unfold f. simpl. apply n_Sn.\n  intros contra. apply H. rewrite contra. reflexivity.\n- pose proof (to_from0 f).\n  rewrite <- H0 in H.\n  apply (H (from0 f)). reflexivity.\nQed.\n\n(** * Subsets *)\n\nLemma sig_eq (A : Type) (P : A -> Prop) (Pirrel : forall a (p q : P a), p = q)\n  : forall (x y : sig P), projT1 x = projT1 y -> x = y.\nProof.\nintros. destruct x, y. simpl in *.\ninduction H. rewrite (Pirrel x p p0).\nreflexivity.\nQed.\n\nTheorem subset {A B : Type} (P : A -> Prop) (Q : B -> Prop)\n  (i : T A B)\n  : (forall a, P a -> Q (to i a))\n  -> (forall b, Q b -> P (from i b))\n  -> (forall a (p q : P a), p = q)\n  -> (forall b (p q : Q b), p = q)\n  -> T (sig P) (sig Q).\nProof.\nintros PimpQ QimpP Pirrel Qirrel.\nrefine (\n  {| to := fun sa => match sa with\n    | exist a pa => exist Q (to i a) (PimpQ a pa)\n    end\n  ;  from := fun sb => match sb with\n    | exist b pb => exist P (from i b) (QimpP b pb)\n    end\n  |}\n); intros inp; destruct inp; simpl;\n  apply sig_eq; try assumption; simpl.\n  apply from_to. apply to_from.\nDefined.\n\nTheorem subsetSelf {A : Type} (P Q : A -> Prop)\n  : (forall a, P a <-> Q a)\n  -> (forall a (p q : P a), p = q)\n  -> (forall b (p q : Q b), p = q)\n  -> T (sig P) (sig Q).\nProof.\nintros. apply (subset _ _ (Refl A)); try assumption; \n intros; simpl; firstorder.\nDefined.\n\n\nTheorem iso_true_subset {A} : T A (sig (fun _ : A => True)).\nProof. refine (\n  {| to := fun a => exist _ a I\n   ; from := fun ea => let (a, _) := ea in a |}\n); intros.\nreflexivity. destruct b. destruct t. reflexivity.\nDefined.\n\nTheorem iso_false_subset {A} : T False (sig (fun _ : A => False)).\nProof. refine (\n  {| to := False_rect _\n  ; from := fun p : sig (fun _ => False) => let (x, px) := p in False_rect _ px\n  |}); intros.\n- contradiction.\n- destruct b. contradiction.\nDefined.\n\nDefinition subset_sum_distr {A B} {P : A + B -> Prop} :\n  T (sig P) (sig (fun a => P (inl a)) + sig (fun b => P (inr b))).\nProof.\nrefine (\n  {| to := fun (p : sig P) => let (x, px) := p in match x as x'\n  return P x' -> sig (fun a => P (inl a)) + sig (fun b => P (inr b)) with\n  | inl a => fun px' => inl (exist (fun a' => P (inl a')) a px')\n  | inr b => fun px' => inr (exist (fun b' => P (inr b')) b px')\n  end px\n  ; from := fun p => match p with\n  | inl (exist a pa) => exist _ (inl a) pa\n  | inr (exist b pb) => exist _ (inr b) pb\n  end\n  |}\n); intros.\n- destruct a as (x & px). destruct x; reflexivity.\n- destruct b as [s | s]; destruct s; reflexivity.\nDefined.\n\n(** Proof irrelevant-things *)\n\nInductive inhabited {A : Type} : Prop :=\n  | elem (a : A) : inhabited.\n\nArguments inhabited : clear implicits.\n\nRequire Import ProofIrrelevance.\n\nTheorem inhabited_idempotent {A : Type} :\n  T A (inhabited A * A).\nProof.\nrefine (\n  {| to := fun a => (elem a, a)\n   ; from := fun p => snd p\n  |}\n).\n- intros. reflexivity.\n- intros. destruct b. simpl.\n  replace (elem a) with i by apply proof_irrelevance.\n  reflexivity.\nDefined.\n\n\nRequire Import Types.Equiv.\n\nImport EqualNotations.\n\nLocal Open Scope equal. \n\nDefinition toEquiv' {A B : Type} (x : T A B) :\n(forall a : A, to x # from_to x a = to_from x (to x a)) -> Equiv.T A B :=\n  Equiv.Build_T A B (to x) (from x) (from_to x) (to_from x).\n\nRequire Import Setoid.\nLemma toEquiv {A B} (x : T A B) : Equiv.T A B.\nProof.\ndestruct x as [f g eta eps].\nrefine (\n  {| Equiv.to := f\n   ; Equiv.from := g\n   ; Equiv.from_to := eta\n   ; Equiv.to_from := fun b =>\n      eq_sym (eps (f (g b)))\n    @ f # eta (g b)\n    @ eps b\n  |}).\nintros.\npose proof (Equiv.f_equal_homotopy_commutes eta a).\nsimpl in H.\npose proof (Equiv.f_equal_natural (f := fun x => f (g x)) (g := fun x => x) eps\n  (f # eta a)).\nrewrite <- (Equiv.f_equal_compose _ _ _ f g) in H0.\nrewrite (Equiv.f_equal_compose _ _ _ g f) in H0.\nrewrite <- H in H0.\nrewrite !Equiv.f_equal_id in H0.\nrewrite <- Equiv.eq_trans_assoc.\nrewrite <- H0. \nrewrite Equiv.eq_trans_assoc.\nrewrite Equiv.eq_sym_l.\nrewrite Equiv.eq_trans_id_l. reflexivity.\nDefined.\n\nDefinition fromEquiv {A B} (x : Equiv.T A B) : T A B :=\n  {| to := Equiv.to x\n   ; from := Equiv.from x\n   ; to_from := Equiv.to_from x\n   ; from_to := Equiv.from_to x\n  |}.\n\n\nLemma sigmaProj1_eq : forall {A A' B} {to : A -> A'} {from : A' -> A}\n  {a : A}\n  (from_to : from (to a) = a),\n  forall b,\n         existT B (from (to a)) (Equiv.transport B (eq_sym from_to) b) =\n         existT B a b.\nProof.\nintros. rewrite from_to0.  simpl. reflexivity.\nDefined.\n\n\nLemma sigmaProj1_eq2 : forall {A A' B} (i : Equiv.T A A')\n  (a' : A') b,\n       existT (fun a'0 : A' => B (Equiv.from i a'0)) (Equiv.to i (Equiv.from i a'))\n         (Equiv.transport B (eq_sym (Equiv.from_to i (Equiv.from i a'))) b) =\n       existT (fun a'0 : A' => B (Equiv.from i a'0)) a' b. \nProof.\nintros. apply EqdepFacts.eq_sigT_iff_eq_dep.\npose proof (Equiv.lemma422 i) as eps.\nsimpl in eps.\nrewrite <- eps. \nremember (Equiv.to_from i a') as x.\ninduction Heqx. rewrite x. reflexivity.\nQed.\n\n(* This is in fact \"true\" but, without Axiom K, the construction is a little\n   bit convoluted. It is proved in the HoTT library by transferring\n   isomorphisms to equivalences. *)\nLemma sigmaPropEquiv {A A' : Type} {B : A -> Type}\n  (iso : Equiv.T A A') \n  : T (sigT B) (sigT (fun a' => B (Equiv.from iso a'))).\nProof.\npose iso as iso'.\ndestruct iso.\nrefine (\n  {| to := fun p : sigT B => let (a, b) := p in \n      existT (fun a' => B (from0 a')) (to0 a) (Equiv.transport B (eq_sym (from_to0 a)) b)\n  ; from := fun p : sigT (fun a' => B (from0 a')) => let (a', b) := p in\n      existT B (from0 a') b\n  ; from_to := fun p : sigT B => match p with\n     existT a b => sigmaProj1_eq (from_to0 a) b\n     end\n  ; to_from := fun p : sigT (fun a' => B (from0 a')) => match p with\n     existT a' b => sigmaProj1_eq2 iso' a' b\n     end\n  |}\n).\nDefined.\n\nDefinition sigmaProp {A A' : Type} {B : A -> Type}\n  (iso : T A A')\n  : T (sigT B) (sigT (fun a' => B (from iso a'))).\nProof.\npose (@sigmaPropEquiv A A' B (toEquiv iso)).\nsimpl in t.\ndestruct iso. apply t.\nDefined.", "meta": {"author": "bmsherman", "repo": "finite", "sha": "63706fa4898aa05296c4290be1dba646b2c512d1", "save_path": "github-repos/coq/bmsherman-finite", "path": "github-repos/coq/bmsherman-finite/finite-63706fa4898aa05296c4290be1dba646b2c512d1/Iso.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6577901405197806}}
{"text": "(* ea *)\n\nStructure Group : Type := const_kozos\n{\n  A :> Set;\n\n  op : A -> A -> A ;\n  inv : A -> A ;\n  z : A ;\n\n  op_assoc : forall a b c, op a (op b c) = op (op a b) c;\n  op_z : forall a, op a z = a /\\ op z a = a ;\n  op_inverse : forall a, op a (inv a) = z /\\ op (inv a) a = z\n}.\n\n\n(* hf *)\n\nFixpoint iter {A:Set} (k:nat) (f:A->A) (x:A) :=\n  match k with\n    | 0 => x\n    | S p => iter p f (f x)\n  end.\n\nEval compute in Nat.add 0 1.\n\nEval compute in iter 0 (Nat.add 1) 0.\nEval compute in iter 1 (Nat.add 1) 0.\nEval compute in iter 2 (Nat.add 1) 0.\n\nStructure CyclicGroup : Type := const_cyclic (* motto *)\n{\n  G :> Group;\n\n  generator : A G ;\n  n : nat ;\n\n  op_cyclic : forall a, exists k, k < n /\\ a = iter k ((op G) generator) (z G)\n}.\n\nInductive GeneratedElement : Set :=\n  | g : nat -> GeneratedElement.\n\nCheck g 0.\nCheck g 1.\n\nDefinition order (e:GeneratedElement) : nat := match e with | g k => k end.\n\nEval compute in order (g 0).\nEval compute in order (g 1).\n\n\nDefinition Z_n (n:nat) := {e:GeneratedElement | order e < n}.\n\nLemma g_0_order_lt_2 : order (g 0) < 2.\nProof.\n  unfold order.\n  auto.\nQed.\n\nDefinition z_2_0 := exist (fun e:GeneratedElement => order e < 2) (g 0) g_0_order_lt_2.\n\nEval compute in proj1_sig z_2_0.\nEval compute in proj2_sig z_2_0.\n\nSearch proj1_sig.\nSearch proj2_sig.\nCheck eq_sig.\n\n\nDefinition Z_n_order (n:nat) (z:Z_n n) : nat := order (proj1_sig z).\n\nEval compute in Z_n_order 2 z_2_0. \n\n\nLemma g_k_order_lt_n (n:nat) (k:nat) : k < n -> order (g k) < n. Proof. unfold order. auto. Qed.\n\nDefinition Z_n_const (n:nat) (k:nat) (p:k < n): Z_n n :=\n  exist (fun e:GeneratedElement => order e < n) (g k) (g_k_order_lt_n n k p).\n\nLemma proof_0_lt_1 : 0 < 1. Proof. auto. Qed. (* FIXME: create by function; possible? *)\nLemma proof_0_lt_2 : 0 < 2. Proof. auto. Qed.\nLemma proof_1_lt_2 : 1 < 2. Proof. auto. Qed.\nLemma proof_0_lt_3 : 0 < 3. Proof. auto. Qed.\nLemma proof_1_lt_3 : 1 < 3. Proof. auto. Qed.\nLemma proof_2_lt_3 : 2 < 3. Proof. auto. Qed.\n\nDefinition z_3_0 := Z_n_const 3 0 proof_0_lt_3.\nDefinition z_3_1 := Z_n_const 3 1 proof_1_lt_3.\nDefinition z_3_2 := Z_n_const 3 2 proof_2_lt_3.\n\nEval compute in Z_n_order 3 z_3_0.\nEval compute in Z_n_order 3 z_3_1.\nEval compute in Z_n_order 3 z_3_2. \n\nLemma Z_n_order_lt_n (n:nat) : forall x:Z_n n, Z_n_order n x < n.\nProof.\n  intro x.\n  unfold Z_n_order.\n  apply (proj2_sig x).\nQed.\n\n\nSearchPattern (nat -> nat -> nat).\nPrint Nat.modulo.\n\nNotation \"n % m\" := (Nat.modulo n m) (at level 20) : type_scope.\n\nEval compute in 0 % 0.\nEval compute in 1 % 2.\nEval compute in 2 % 2. \n\nRequire PeanoNat.\n\nLemma Z_n_op_proof (n:nat) : forall x y:Z_n n, ((Z_n_order n x) + (Z_n_order n y)) % (n) < (n).\nProof.\n  induction x, y.\n  unfold Z_n_order.\n  apply PeanoNat.Nat.mod_upper_bound.\n  cut (n > 0).\n  apply PeanoNat.Nat.neq_0_lt_0.\n  apply PeanoNat.Nat.lt_lt_0 in p.\n  assumption.\nQed.\n\nDefinition Z_n_op (n:nat) (x:Z_n n) (y:Z_n n) : Z_n n :=\n  Z_n_const n (((Z_n_order n x) + (Z_n_order n y)) % (n)) (Z_n_op_proof n x y).\n\nEval compute in Z_n_order 3 (Z_n_op 3 z_3_0 z_3_0).\nEval compute in Z_n_order 3 (Z_n_op 3 z_3_0 z_3_1).\nEval compute in Z_n_order 3 (Z_n_op 3 z_3_1 z_3_2).\n\n\nLemma Z_n_inv_proof (n:nat) : forall x:Z_n n, (n - (Z_n_order n x)) % (n) < (n).\nProof.\n  induction x.\n  unfold Z_n_order.\n  apply PeanoNat.Nat.mod_upper_bound.\n  cut (n > 0).\n  apply PeanoNat.Nat.neq_0_lt_0.\n  apply PeanoNat.Nat.lt_lt_0 in p.\n  assumption.\nQed.\n\nDefinition Z_n_inv (n:nat) (x:Z_n n) : Z_n n :=\n  Z_n_const n ((n - (Z_n_order n x)) % (n)) (Z_n_inv_proof n x).\n\nEval compute in Z_n_order 3 (Z_n_inv 3 z_3_0).\nEval compute in Z_n_order 3 (Z_n_inv 3 z_3_1).\nEval compute in Z_n_order 3 (Z_n_inv 3 z_3_2). \n\nAxiom proof_irrelevance : (* https://github.com/coq/coq/wiki/CoqAndAxioms *)\n  forall (P : Prop) (p q : P), p = q.\n\nLemma warmup (n:nat) (x y:{k:nat | k < n}) : proj1_sig x = proj1_sig y -> x = y.\nProof.\n  destruct x as [x Hx], y as [y Hy].\n  simpl.\n  intro H.\n  subst y.\n  f_equal.\n  apply proof_irrelevance.\nQed.\n\nLemma Z_n_eq_if_order_eq (n:nat) : forall x y:Z_n n, Z_n_order n x = Z_n_order n y -> x = y.\nProof.\n  intros x y.\n  destruct x as [x Hx], y as [y Hy].\n  unfold Z_n_order.\n  simpl.\n  intro H.\n  assert (order x = order y -> x = y) as H2.\n  { case x, y. unfold order. intro H2. rewrite H2. reflexivity. }\n  assert (x = y).\n  apply H2.\n  assumption.\n  subst y.\n  cut (Hx = Hy).\n  intro H3.\n  rewrite H3.\n  reflexivity.\n  apply proof_irrelevance.\nQed.\n\nLemma Z_n_eq_iff_order_eq (n:nat) : forall x y:Z_n n, x = y <-> Z_n_order n x = Z_n_order n y.\nProof.\n  split.\n  intro H.\n  rewrite H.\n  reflexivity.\n  apply Z_n_eq_if_order_eq.\nQed.\n\n\nLemma nat_add_mod_assoc : forall a b c n:nat, n <> 0 -> \n  (a + ((b + c) % (n))) % (n) = (((a + b) % (n)) + c) % (n).\nProof.\n  Print PeanoNat.Nat.add_mod.\n  Print PeanoNat.Nat.add_mod_idemp_l.\n  Print PeanoNat.Nat.add_mod_idemp_r.\n  intros a b c n H.\n  rewrite PeanoNat.Nat.add_mod_idemp_r.\n  rewrite PeanoNat.Nat.add_mod_idemp_l.\n  rewrite PeanoNat.Nat.add_assoc.\n  reflexivity.\n  assumption.\n  assumption.\nQed.\n\nLemma Z_n_op_eq_order (n:nat) :\n  forall x y:Z_n n, Z_n_order n (Z_n_op n x y) = (((Z_n_order n x) + (Z_n_order n y)) % (n)).\nProof.\n  intros x y.\n  unfold Z_n_op.\n  unfold Z_n_order.\n  simpl.\n  reflexivity.\nQed.\n\nLemma Z_n_inv_eq_order (n:nat) :\n  forall x:Z_n n, Z_n_order n (Z_n_inv n x) = ((n) - Z_n_order n x) % (n).\nProof.\n  intro x.\n  unfold Z_n_inv.\n  unfold Z_n_order.\n  simpl.\n  reflexivity.\nQed.\n\n\nTheorem Z_n_group (n:nat) : n <> 0 -> Group.\nProof.\n  intro H.\n  assert (0 < n) as H'.\n  apply PeanoNat.Nat.neq_0_lt_0.\n  assumption.\n  apply (const_kozos (Z_n n) (Z_n_op n) (Z_n_inv n) (Z_n_const n 0 H')).\n\n  intros a b c.\n  rewrite Z_n_eq_iff_order_eq.\n  repeat rewrite Z_n_op_eq_order.\n  apply nat_add_mod_assoc.\n  assumption.\n\n  intro a.\n  repeat rewrite Z_n_eq_iff_order_eq.\n  repeat rewrite Z_n_op_eq_order.\n  assert (Z_n_order n (Z_n_const n 0 H') = 0) as H2.\n  unfold Z_n_order.\n  simpl.\n  reflexivity.\n  rewrite H2.\n  rewrite PeanoNat.Nat.add_0_r.\n  rewrite PeanoNat.Nat.add_0_l.\n  split.\n  apply PeanoNat.Nat.mod_small.\n  apply Z_n_order_lt_n.\n  apply PeanoNat.Nat.mod_small.\n  apply Z_n_order_lt_n.\n\n  intro a.\n  repeat rewrite Z_n_eq_iff_order_eq.\n  repeat rewrite Z_n_op_eq_order.\n  assert (Z_n_order n (Z_n_const n 0 H') = 0) as H2.\n  unfold Z_n_order.\n  simpl.\n  reflexivity.\n  rewrite H2.\n\n  rewrite Z_n_inv_eq_order.\n  split.\n\n  rewrite PeanoNat.Nat.add_mod_idemp_r.\n  rewrite PeanoNat.Nat.add_sub_assoc.\n  rewrite PeanoNat.Nat.add_sub_swap.\n  rewrite PeanoNat.Nat.add_comm.\n  rewrite PeanoNat.Nat.add_sub_assoc.\n  rewrite PeanoNat.Nat.add_sub.\n  apply PeanoNat.Nat.mod_same.\n  assumption.\n  apply le_n.\n  apply le_n.\n  assert (Z_n_order n a < n).\n  apply Z_n_order_lt_n.\n  apply PeanoNat.Nat.lt_le_incl.\n  assumption.\n  assumption.\n\n  rewrite PeanoNat.Nat.add_mod_idemp_l.\n  rewrite PeanoNat.Nat.sub_add.\n  apply PeanoNat.Nat.mod_same.\n  assumption.\n  assert (Z_n_order n a < n).\n  apply Z_n_order_lt_n.\n  apply PeanoNat.Nat.lt_le_incl.\n  assumption.\n  assumption.\nQed.\n\nLemma test (n:nat) (H:n <> 0) : forall a:A (Z_n_group n H), a = a.\nProof.\n  intro a.\n  (* case a. *)\n  reflexivity.\nQed.\n\n(* Lemma test (n:nat) (H:n <> 0) : forall a:A (Z_n_group n H), Z_n_order n a < n. *)\n\nTheorem Z_n_cyclic_group (n:nat) : n > 1 -> CyclicGroup.\nProof.\n  intro H.\n  assert (n <> 0) as H2.\n  assert (n > 0) as H2'.\n  apply PeanoNat.Nat.lt_trans with (p:=n) (m:=1) (n:=0).\n  apply PeanoNat.Nat.lt_succ_diag_r.\n  assumption.\n  apply PeanoNat.Nat.neq_0_lt_0.\n  assumption.\n  Check (Z_n_const n 1 H).\n  Check (z (Z_n_group n H2)).\n  apply (const_cyclic (Z_n_group n H2) (Z_n_const n 1 H) n).\n???\n", "meta": {"author": "mozow01", "repo": "bizcoq2021", "sha": "f98f22ba3ce80899bc88605ce3193d8972102c92", "save_path": "github-repos/coq/mozow01-bizcoq2021", "path": "github-repos/coq/mozow01-bizcoq2021/bizcoq2021-f98f22ba3ce80899bc88605ce3193d8972102c92/hallgatoi/gabormarton/bizcoq_2_hf_2_v2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.6577799441670339}}
{"text": "\nRequire Export ZArith.\nRequire Export List.\nRequire Export Arith Lia.\n\nSection bad_proof_example_for_Induction1.\n\n  Theorem le_plus_minus' : forall n m:nat, m <= n -> n = m+(n-m).\n  Proof.\n    intros n m H;  induction n. \n    -   rewrite <- le_n_O_eq with (1 := H); simpl; trivial. \n    - (* dead end *) \n  Abort.\n\nEnd bad_proof_example_for_Induction1.\n\n\nTheorem lazy_example : forall n:nat, (S n) + 0 = S n.\nProof.\n  intros n; lazy beta iota zeta delta. \n  fold plus.\n  rewrite plus_0_r; reflexivity.\nQed.\n\n#[export] Hint  Extern  4 (_ <> _) => discriminate : core.\n\n#[export] Hint Resolve le_S_n : le_base.\n\nTheorem auto_le_example :\n  forall n m:nat, S (S (S n)) <= S (S (S m)) ->  n <= m.\nProof.\n  intros n m H.\n  auto with le_base.\nQed.\n\nLemma unprovable_le : forall n m:nat, n <= m.\nProof.\n  Time auto with arith.\n  Time auto with le_base arith.\nAbort.\n\nSection bad_proof_for_auto.\n\n  Section Trying_auto.\n    Variable l1 : forall n m:nat, S n <= S m -> n <= m.\n\n    Theorem unprovable_le2 : forall n m:nat, n <= m.\n    Proof.\n      Time auto with arith.\n      Time try (clear l1; auto with arith; fail).\n    Abort.\n\n  End Trying_auto.\n\nEnd bad_proof_for_auto.\n\nSection combinatory_logic.\n\n  Variables (CL:Set)(App:CL->CL->CL)(S:CL)(K:CL).\n  Hypotheses\n    (S_rule :\n       forall A B C:CL, App (App (App S A) B) C = App (App A C)(App B C))\n    (K_rule :\n       forall A B:CL, App (App K A) B = A).\n\n  Hint Rewrite  S_rule K_rule : CL_rules.\n\n  Theorem obtain_I : forall A:CL, App (App (App S K) K) A = A.\n  Proof.\n    intros; autorewrite with CL_rules.\n    reflexivity.\n  Qed.\n\nEnd combinatory_logic.\n\nTheorem example_for_subst :\n  forall (a b c d:nat), a = b+c -> c = 1 -> a+b = d -> 2*a = d+c.\nProof.\n  intros a b c d H H1 H2.\n  subst a.\n  subst.\n  lazy delta [mult] iota zeta beta; \n    rewrite  plus_0_r; \n    repeat rewrite plus_assoc_reverse;\n    trivial.\nQed.\n\nOpen Scope Z_scope.\n\nTheorem ring_example1 : forall x y:Z, (x+y) * (x+y)=x*x + 2*x*y + y*y.\nProof.\n  intros x y; ring.\nQed.\n\nDefinition square (z:Z) := z*z.\n\nTheorem ring_example2 :\n  forall x y:Z, square (x+y) = square x + 2*x*y + square y.\nProof.\n  intros x y; unfold square; ring.\nQed.\n\nTheorem ring_example3 : \n  (forall x y:nat, (x+y)*(x+y) = x*x + 2*x*y + y*y)%nat.\nProof.\n  intros x y; ring.\nQed.\n\nTheorem ring_example4 :\n  (forall x:nat, (S x)*(x+1) = x*x + (x+x+1))%nat.\nProof.\n  intro x; ring_simplify.\n  trivial.\nQed.\n\nRequire Omega.\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.\nQed.\n\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 H0; 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 H0; omega.\nQed.\n\nCheck (fun (X y:Z) => 0 <= X -> 3*X <= 2*y  ->  X < y).\n\nRequire Export Reals.\n\nOpen Scope R_scope.\n\nTheorem example_for_field : forall x y:R, y <> 0 ->(x+y) / y = 1  +(x/y).\nProof.\n  intros x y H; field.\n  assumption.\nQed.\n\nRequire Import Lra.\n\nTheorem example_for_Lra : forall x y:R, x-y >1 -> x - 2*y < 0 -> x > 1.\nProof.\n  intros x y H H0.\n  lra.\nQed.\n\nTheorem ex_tauto1 : forall A B:Prop, A/\\B->A.\nProof.\n  tauto.\nQed.\n\nTheorem ex_tauto2 : forall A B:Prop, A/\\~A -> B.\nProof.\n  tauto.\nQed.\n\nOpen Scope Z_scope.\n\nTheorem ex_tauto3 : forall x y:Z, x<=y -> ~(x<=y) -> x=3.\nProof.\n  tauto.\nQed.\n\nTheorem ex_tauto4 : forall A B:Prop, A\\/B -> B\\/A.\nProof.\n  tauto. \nQed.\n\nTheorem ex_tauto5 : \n  forall A B C D:Prop, (A->B)\\/(A->C)->A->(B->D)->(C->D)->D.\nProof.\n  tauto.\nQed.\n\nOpen Scope nat_scope.\n\nTheorem example_intuition :\n  (forall n p q:nat,  n <= p \\/ n <= q -> n <= p \\/ n <= S q).\nProof.\n  intros n p q; intuition auto with arith.\nQed.\n\nLtac autoClear h := try (clear h; auto with arith; fail).\n\nLtac autoAfter tac := try (tac; auto with arith; fail).\n\nOpen Scope nat_scope.\n\nTheorem example_for_autoAfter : forall  n p:nat,\n    n < p -> n <= p -> 0 < p -> S n < S p.\nProof.\n  intros n p H H0 H1.\n  autoAfter ltac:(clear H0 H1).\nQed.\n\nOpen Scope nat_scope.\n\nLtac le_S_star := apply le_n || (apply le_S; le_S_star).\n\nTheorem le_5_25 : 5 <= 25.\nProof.\n  le_S_star.\nQed.\n\nLtac contrapose H :=\n  match goal with\n  | id:(~_) |- (~_) => intro H; apply id\n  end.\n\nTheorem example_contrapose : \n  forall x y:nat, x <> y -> x <= y -> ~y <= x.\nProof.\n  intros x y H H0.\n  contrapose H'.\n  auto with arith.\nQed.\n\n\n\nSection primes.\n\n  Definition divides (n m:nat) := exists p:nat, p*n = m.\n\n  Lemma divides_O : forall n:nat, divides n 0.\n  Proof.\n    exists 0; reflexivity.\n  Qed.\n\n\n  Lemma divides_plus : forall n m:nat, divides n m -> divides n (n+m).\n  Proof. intros n m [q Hq]; exists (S q). subst; ring. Qed.\n\n  Lemma not_divides_plus : forall n m:nat, ~divides n m -> ~divides n (n+m).\n    intros n m H [q Hq]; apply H; red.\n    destruct q.\n    - exists 0. simpl in *. lia.\n    -   exists q; lia.\n  Qed.\n\n\n  Lemma not_divides_lt : forall n m:nat, 0<m -> m<n -> ~divides n m.\n  Proof.\n    intros n m H H0 [q Hq].\n    subst.\n    destruct q.\n    lia.\n    cbn in H0.\n    lia.\n  Qed.\n\n  Lemma not_lt_2_divides : forall n m:nat, n<>1 -> n<2 -> 0 < m -> ~ divides n m.\n  Proof. \n    intros n m H H0 H1 [q Hq].\n    subst.\n    assert (n = 0) by lia.\n    subst.\n    lia.\n  Qed. \n\n\n  Lemma le_plus_minus : forall n m:nat, le n m -> m = n+(m-n).\n  Proof. intros; lia. Qed.\n\n\n  Lemma lt_lt_or_eq : forall n m:nat, n < S m ->  n<m \\/ n=m.\n  Proof. inversion 1; auto.\n  Qed.\n\n\n  Ltac check_not_divides :=\n    match goal with\n    | |- (~divides ?X1 ?X2) =>\n      cut (X1<=X2);[ idtac | le_S_star ]; intros Hle;\n      rewrite (le_plus_minus _ _ Hle); apply not_divides_plus; \n      simpl; clear Hle; check_not_divides\n    | |- _ => apply not_divides_lt; unfold lt; le_S_star\n\n    end.\n  Open Scope nat_scope.\n\n  #[local] Hint Resolve lt_O_Sn : core.\n\n  Ltac check_lt_not_divides :=\n    match goal with\n    | Hlt:(lt ?X1 2%nat) |- (~divides ?X1 ?X2) =>\n      apply not_lt_2_divides; auto\n    | Hlt:(lt ?X1 ?X2) |- (~divides ?X1 ?X3) =>\n      elim (lt_lt_or_eq _ _ Hlt);\n      [clear Hlt; intros Hlt; check_lt_not_divides\n      | intros Heq; rewrite Heq; check_not_divides]\n    end.\n\n  Definition is_prime (p:nat) : Prop := \n    forall n:nat, n <> 1 -> lt n p -> ~divides n p.\n\n  Theorem prime37 : is_prime 37.\n  Proof.\n    unfold is_prime; intros.\n    check_lt_not_divides.\n    Time Qed.\n\nEnd primes.\n\n\nLtac clear_all :=\n  match goal with\n  | id:_ |- _ => clear id; clear_all\n  | |- _ => idtac\n  end.\n\n\nTheorem clear_example_thm :\n  forall (x y z:nat), x<z->z=2*x->0<x->x=2*y->y<z->x>y.\nProof.\n  intros x y z H H1 H2 H3.\n  generalize H1 H2 H3; clear_all; intros; omega.\nQed.\n\nTheorem S_to_plus_one : forall n:nat, S n = n+1.\nProof.\n  intros; rewrite plus_comm; reflexivity.\nQed.\n\n\nLtac S_to_plus_simpl :=\n  match goal with\n  | |-  context [(S ?X1)] =>\n    match X1 with\n    | 0%nat => fail 1\n    | ?X2 => rewrite (S_to_plus_one X2); S_to_plus_simpl\n    end\n  | |- _ => idtac\n  end.\n\nLtac a_function X1 :=\n  match X1 with\n  | 0%nat => fail 1\n  | ?X2 => rewrite (S_to_plus_one X2); S_to_plus_simpl\n  end.\n\n\nLtac simpl_on e :=\n  let v := eval simpl in e in\n      match goal with\n      | |- context [e] => replace e with v; [idtac | auto]\n      end.\n\nTheorem simpl_on_example :\n  forall n:nat, exists m : nat, (1+n) + 4*(1+n) = 5*(S m).\nProof.\n  intros n; simpl_on (1+n). \n  exists n; auto with arith.\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/ch7_tactics_automation/SRC/chap7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.795658104908603, "lm_q1q2_score": 0.657779942772896}}
{"text": "Require Export P07.\n\n\n\n(** **** Exercise: 3 stars (CIf_congruence)  *)\nTheorem CIf_congruence : forall b b' c1 c1' c2 c2',\n  bequiv b b' -> cequiv c1 c1' -> cequiv c2 c2' ->\n  cequiv (IFB b THEN c1 ELSE c2 FI)\n         (IFB b' THEN c1' ELSE c2' FI).\nProof.\n  unfold cequiv. intros. split; intros.\n  - inversion H2; subst.\n    + rewrite H in H8. rewrite H0 in H9. eapply E_IfTrue. assumption. assumption.\n    + rewrite H in H8. rewrite H1 in H9. eapply E_IfFalse. assumption. assumption.\n  - inversion H2; subst.\n    + rewrite <- H in H8. rewrite <- H0 in H9. eapply E_IfTrue. assumption. assumption.\n    + rewrite <- H in H8. rewrite <- H1 in H9. eapply E_IfFalse. assumption. assumption.\nQed.\n\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/07/P08.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6577799345846924}}
{"text": "(** * Decide: Programming with Decision Procedures *)\n\nSet Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom VFA Require Import Perm.\n\n(* ################################################################# *)\n(** * Using [reflect] to characterize decision procedures *)\n\n(** Thus far in _Verified Functional Algorithms_ we have been using\n   - propositions ([Prop]) such as [a<b] (which is Notation for [lt a b])\n   - booleans ([bool]) such as [a<?b] (which is Notation for [ltb a b]). *)\n\nCheck Nat.lt.  (* : nat -> nat -> Prop *)\nCheck Nat.ltb.  (* : nat -> nat -> bool *)\n\n(** The [Perm] chapter defined a tactic called [bdestruct] that\n    does case analysis on (x <? y) while giving you hypotheses (above\n    the line) of the form (x<y).   This tactic is built using the [reflect]\n    type and the [ltb_reflect] theorem. *)\n\nPrint reflect.\n(* Inductive reflect (P : Prop) : bool -> Set :=\n    | ReflectT : P -> reflect P true\n    | ReflectF : ~ P -> reflect P false  *)\n\nCheck ltb_reflect.  (* : forall x y, reflect (x<y) (x <? y) *)\n\n(** The name [reflect] for this type is a reference to _computational\n   reflection_,  a technique in logic.  One takes a logical formula, or\n   proposition, or predicate,  and designs a syntactic embedding of\n   this formula as an \"object value\" in the logic.  That is, _reflect_ the\n   formula back into the logic. Then one can design computations\n   expressible inside the logic that manipulate these syntactic object\n   values.  Finally, one proves that the computations make transformations\n   that are equivalent to derivations (or equivalences) in the logic.\n\n   The first use of computational reflection was by Goedel, in 1931:\n   his syntactic embedding encoded formulas as natural numbers, a\n   \"Goedel numbering.\"  The second and third uses of reflection were\n   by Church and Turing, in 1936: they encoded (respectively)\n   lambda-expressions and Turing machines.\n\n   In Coq it is easy to do reflection, because the Calculus of Inductive\n   Constructions (CiC) has Inductive data types that can easily encode\n   syntax trees.  We could, for example, take some of our propositional\n   operators such as [and], [or], and make an [Inductive] type that is an\n   encoding of these, and build a computational reasoning system for\n   boolean satisfiability.\n\n   But in this chapter I will show something much simpler.  When\n   reasoning about less-than comparisons on natural numbers, we have\n   the advantage that [nat] is already an inductive type; it is \"pre-reflected,\"\n   in some sense.  (The same for [Z], [list], [bool], etc.)  *)\n\n(** Now, let's examine how [reflect] expresses the coherence between\n  [lt] and [ltb]. Suppose we have a value [v] whose type is\n  [reflect (3<7) (3<?7)].  What is [v]?  Either it is\n  - ReflectT [P] (3<?7), where [P] is a proof of [3<7],  and [3<?7] is [true], or\n  - ReflectF [Q] (3<?7), where [Q] is a proof of [~(3<7)], and [3<?7] is [false].\n  In the case of [3,7], we are well advised to use [ReflectT], because\n   (3<?7) cannot match the [false] required by [ReflectF]. *)\n\nGoal (3<?7 = true). Proof. reflexivity. Qed.\n\n(** So [v] cannot be [ReflectF Q (3<?7)] for any [Q], because that would\n   not type-check.  Now, the next question:  must there exist a value\n   of type [reflect (3<7) (3<?7)]  ?  The answer is yes; that is the\n   [ltb_reflect] theorem.  The result of [Check ltb_reflect], above, says that\n   for any [x,y], there does exist a value (ltb_reflect x y) whose type\n   is exactly [reflect (x<y)(x<?y)].     So let's look at that value!  That is,\n   examine what [H], and [P], and [Q] are equal to at \"Case 1\" and \"Case 2\": *)\n\nTheorem three_less_seven_1: 3<7.\nProof.\nassert (H := ltb_reflect 3 7).\nremember (3<?7) as b.\ndestruct H as [P|Q] eqn:?.\n* (* Case 1: H = ReflectT (3<7) P *)\napply P.\n* (* Case 2: H = ReflectF (3<7) Q *)\ncompute in Heqb.\ninversion Heqb.\nQed.\n\n(** Here is another proof that uses [inversion] instead of [destruct].\n   The [ReflectF] case is eliminated automatically by [inversion]\n   because [3<?7] does not match [false]. *)\n\nTheorem three_less_seven_2: 3<7.\nProof.\nassert (H := ltb_reflect 3 7).\ninversion H as [P|Q].\napply P.\nQed.\n\n(** The [reflect] inductive data type is a way of relating a _decision\n   procedure_ (a function from X to [bool]) with a predicate (a function\n   from X to [Prop]).   The convenience of [reflect], in the verification\n   of functional programs, is that we can do [destruct (ltb_reflect a b)],\n   which relates [a<?b] (in the program) to the [a<b] (in the proof).\n   That's just how the [bdestruct] tactic works; you can go back\n   to [Perm.v] and examine how it is implemented in the [Ltac]\n   tactic-definition language. *)\n\n(* ################################################################# *)\n(** * Using [sumbool] to Characterize Decision Procedures *)\n\nModule ScratchPad.\n\n(** An alternate way to characterize decision procedures,\n   widely used in Coq, is via the inductive type [sumbool].\n\n   Suppose [Q]  is a proposition, that is, [Q: Prop].  We say [Q] is\n   _decidable_ if there is an algorithm for computing a proof of\n   [Q] or [~Q].  More generally, when [P] is a predicate (a function\n   from some type [T] to [Prop]), we say [P] is decidable when\n   [forall x:T, decidable(P)].\n\n   We represent this concept in Coq by an inductive datatype: *)\n\nInductive sumbool (A B : Prop) : Set :=\n | left : A -> sumbool A B\n | right : B -> sumbool A B.\n\n(** Let's consider [sumbool] applied to two propositions: *)\n\nDefinition t1 := sumbool (3<7) (3>2).\nLemma less37: 3<7. Proof. lia. Qed.\nLemma greater23: 3>2. Proof. lia. Qed.\n\nDefinition v1a: t1 := left (3<7) (3>2) less37.\nDefinition v1b: t1 := right (3<7) (3>2) greater23.\n\n(** A value of type [sumbool (3<7) (3>2)] is either one of:\n  - [left] applied to a proof of (3<7), or\n  - [right] applied to a proof of (3>2).   *)\n\n(** Now let's consider: *)\n\nDefinition t2 := sumbool (3<7) (2>3).\nDefinition v2a: t2 := left (3<7) (2>3) less37.\n\n(** A value of type [sumbool (3<7) (2>3)] is either one of:\n  - [left] applied to a proof of (3<7), or\n  - [right] applied to a proof of (2>3).\n  But since there are no proofs of 2>3, only [left] values (such as [v2a])\n  exist.  That's OK. *)\n\n(** [sumbool] is in the Coq standard library, where there is [Notation]\n   for it:  the expression [ {A}+{B} ] means [sumbool A B]. *)\n\nNotation \"{ A } + { B }\" := (sumbool A B) : type_scope.\n\n(** A very common use of [sumbool] is on a proposition and its negation.\n   For example, *)\n\nDefinition t4 := forall a b, {a<b}+{~(a<b)}.\n\n(** That expression, [forall a b, {a<b}+{~(a<b)}], says that for any\n natural numbers [a] and [b], either [a<b] or [a>=b].  But it is _more_\n than that!  Because [sumbool] is an Inductive type with two constructors\n [left] and [right], then given the [{3<7}+{~(3<7)}] you can pattern-match\n on it and learn _constructively_ which thing is true.  *)\n\nDefinition v3: {3<7}+{~(3<7)} := left _ _ less37.\n\nDefinition is_3_less_7:  bool :=\n match v3 with\n | left _ _ _ => true\n | right _ _ _ => false\n end.\n\nEval compute in is_3_less_7. (* = true : bool *)\n\nPrint t4.  (* = forall a b : nat, {a < b} + {~ a < b} *)\n\n(** Suppose there existed a value [lt_dec] of type [t4].  That would be a\n  _decision procedure_ for the less-than function on natural numbers.\n  For any nats [a] and [b], you could calculate [lt_dec a b], which would\n  be either [left ...] (if [a<b] was provable) or [right ...] (if [~(a<b)] was\n  provable).\n\n  Let's go ahead and implement [lt_dec].  We can base it on the function\n  [ltb: nat -> nat -> bool] which calculates whether [a] is less than [b],\n  as a boolean.  We already have a theorem that this function on booleans\n  is related to the proposition [a<b]; that theorem is called [ltb_reflect]. *)\n\nCheck ltb_reflect.  (* : forall x y, reflect (x<y) (x<?y) *)\n\n(** It's not too hard to use [ltb_reflect] to define [lt_dec] *)\n\nDefinition lt_dec (a: nat) (b: nat) : {a<b}+{~(a<b)} :=\nmatch ltb_reflect a b with\n| ReflectT _ P => left (a < b) (~ a < b) P\n| ReflectF _ Q => right (a < b) (~ a < b) Q\nend.\n\n(** Another, equivalent way to define [lt_dec] is to use\n     definition-by-tactic: *)\n\nDefinition lt_dec' (a: nat) (b: nat) : {a<b}+{~(a<b)}.\n  destruct (ltb_reflect a b) as [P|Q]. left. apply P.  right. apply Q.\nDefined.\n\nPrint lt_dec.\nPrint lt_dec'.\n\nTheorem lt_dec_equivalent: forall a b, lt_dec a b = lt_dec' a b.\nProof.\nintros.\nunfold lt_dec, lt_dec'.\nreflexivity.\nQed.\n\n(** Warning: these definitions of [lt_dec] are not as nice as the\n  definition in the Coq standard library, because these are not\n  fully computable.  See the discussion below. *)\n\nEnd ScratchPad.\n\n(* ================================================================= *)\n(** ** [sumbool] in the Coq Standard Library *)\n\nModule ScratchPad2.\nLocate sumbool. (* Coq.Init.Specif.sumbool *)\nPrint sumbool.\n\n(** The output of [Print sumbool] explains that the first two arguments\n   of [left] and [right] are implicit.  We use them as follows (notice that\n   [left] has only one explicit argument [P]:  *)\n\nDefinition lt_dec (a: nat) (b: nat) : {a<b}+{~(a<b)} :=\nmatch ltb_reflect a b with\n| ReflectT _ P => left P\n| ReflectF _ Q => right Q\nend.\n\nDefinition le_dec (a: nat) (b: nat) : {a<=b}+{~(a<=b)} :=\nmatch leb_reflect a b with\n| ReflectT _ P => left P\n| ReflectF _ Q => right Q\nend.\n\n(** Now, let's use [le_dec] directly in the implementation of insertion\n   sort, without mentioning [ltb] at all. *)\n\nFixpoint insert (x:nat) (l: list nat) :=\n  match l with\n  | nil => x::nil\n  | h::t => if le_dec x h then x::h::t else h :: insert x t\n end.\n\nFixpoint sort (l: list nat) : list nat :=\n  match l with\n  | nil => nil\n  | h::t => insert h (sort t)\nend.\n\nInductive sorted: list nat -> Prop :=\n| sorted_nil:\n    sorted nil\n| sorted_1: forall x,\n    sorted (x::nil)\n| sorted_cons: forall x y l,\n   x <= y -> sorted (y::l) -> sorted (x::y::l).\n\n(** **** Exercise: 2 stars, standard (insert_sorted_le_dec) *)\nLemma insert_sorted:\n  forall a l, sorted l -> sorted (insert a l).\nProof.\n  intros a l H.\n  induction H.\n  - constructor.\n  - unfold insert.\n    destruct (le_dec a x) as [ Hle | Hgt].\n\n   (** Look at the proof state now.  In the first subgoal, we have\n      above the line, [Hle: a <= x].  In the second subgoal, we have\n      [Hgt: ~ (a < x)].  These are put there automatically by the\n      [destruct (le_dec a x)].  Now, the rest of the proof can proceed\n      as it did in [Sort.v], but using [destruct (le_dec _ _)] instead of\n      [bdestruct (_ <=? _)]. *)\n\n(* TODO: FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Decidability and Computability *)\n\n(** Before studying the rest of this chapter, it is helpful to study the\n   [ProofObjects] chapter of _Software Foundations volume 1_ if you\n   have not done so already.\n\n   A predicate [P: T->Prop] is _decidable_ if there is a computable\n   function [f: T->bool] such that, forall [x:T], [f x = true <-> P x].\n   The second and most famous example of an _undecidable_ predicate\n   is the Halting Problem (Turing, 1936): [T] is the type of Turing-machine\n   descriptions, and [P(x)] is, Turing machine [x] halts.  The first, and not\n   as famous, example is due to Church, 1936 (six months earlier): test\n   whether a lambda-expression has a normal form.  In 1936-37, as a\n   first-year PhD student before beginning his PhD thesis work, Turing\n   proved these two problems are equivalent.\n\n   Classical logic contains the axiom [forall P, P \\/ ~P].  This is not provable\n   in core Coq, that is, in the bare Calculus of Inductive Constructions.  But\n   its negation is not provable either.   You could add this axiom to Coq\n   and the system would still be consistent (i.e., no way to prove [False]).\n\n   But [P \\/ ~P] is a weaker statement than [ {P}+{~P} ], that is,\n   [sumbool P (~P)].  From [ {P}+{~P} ] you can actually _calculate_ or\n   [compute] either [left (x:P)] or [right(y: ~P)].     From [P \\/ ~P] you cannot\n   [compute] whether [P] is true.  Yes, you can [destruct] it in a proof,\n   but not in a calculation.\n\n   For most purposes its unnecessary to add the axiom [P \\/ ~P] to Coq,\n   because for specific predicates there's a specific way to prove [P \\/ ~P]\n   as a theorem.  For example,  less-than on natural numbers is decidable,\n   and the existence of [ltb_reflect] or [lt_dec] (as a theorem, not as an axiom)\n   is a demonstration of that.\n\n   Furthermore, in this \"book\" we are interested in _algorithms_.  An axiom\n   [P \\/ ~P] does not give us an algorithm to compute whether P is true.  As\n   you saw in the definition of [insert] above, we can use [lt_dec] not only as\n   a theorem that either [3<7] or [~(3<7)], we can use it as a function to\n   compute whether [3<7].  In Coq, you can't compute with axioms!\n   Let's try it: *)\n\nAxiom lt_dec_axiom_1:  forall i j: nat, i<j \\/ ~(i<j).\n\n(** Now, can we use this axiom to compute with?  *)\n\n(* Uncomment and try this:\nDefinition max (i j: nat) : nat :=\n   if lt_dec_axiom_1 i j then j else i.\n*)\n\n(** That doesn't work, because an [if] statement requires an [Inductive]\n  data type with exactly two constructors; but [lt_dec_axiom_1 i j] has\n  type [i<j \\/ ~(i<j)],  which is not Inductive.  But let's try a different axiom: *)\n\nAxiom lt_dec_axiom_2:  forall i j: nat, {i<j} + {~(i<j)}.\n\nDefinition max_with_axiom (i j: nat) : nat :=\n   if lt_dec_axiom_2 i j then j else i.\n\n(** This typechecks, because [lt_dec_axiom_2 i j]  belongs to type\n     [sumbool (i<j) (~(i<j))]   (also written [ {i<j} + {~(i<j)} ]), which does have\n     two constructors.\n\n     Now, let's use this function: *)\n\nEval compute in max_with_axiom 3 7.\n  (*  = if lt_dec_axiom_2 3 7 then 7 else 3\n     : nat *)\n\n(** This [compute] didn't compute very much!  Let's try to evaluate it\n    using [unfold]: *)\n\nLemma prove_with_max_axiom:   max_with_axiom 3 7 = 7.\nProof.\nunfold max_with_axiom.\ntry reflexivity.  (* does not do anything, reflexivity fails *)\n(* uncomment this line and try it:\n   unfold lt_dec_axiom_2.\n*)\ndestruct (lt_dec_axiom_2 3 7).\nreflexivity.\ncontradiction n. lia.\nQed.\n\n(** It is dangerous to add Axioms to Coq: if you add one that's inconsistent,\n   then it leads to the ability to prove [False].  While that's a convenient way\n   to get a lot of things proved, it's unsound; the proofs are useless.\n\n   The Axioms above, [lt_dec_axiom_1] and [lt_dec_axiom_2], are safe enough:\n   they are consistent.  But they don't help in computation.  Axioms are not\n   useful here. *)\n\nEnd ScratchPad2.\n\n(* ################################################################# *)\n(** * Opacity of [Qed] *)\n\n(** This lemma [prove_with_max_axiom] turned out to be _provable_, but the proof\n    could not go by _computation_.  In contrast, let's use [lt_dec], which was built\n    without any axioms: *)\n\nLemma compute_with_lt_dec:  (if ScratchPad2.lt_dec 3 7 then 7 else 3) = 7.\nProof.\ncompute.\n(* uncomment this line and try it:\n   unfold ltb_reflect.\n*)\nAbort.\n\n(** Unfortunately, even though [ltb_reflect] was proved without any axioms, it\n    is an _opaque theorem_  (proved with [Qed] instead of with [Defined]), and\n    one cannot compute with opaque theorems.  Not only that, but it is proved with\n    other opaque theorems such as [iff_sym] and [Nat.ltb_lt].  If we want to\n    compute with an implementation of [lt_dec] built from [ltb_reflect], then\n    we will have to rebuild [ltb_reflect] without using [Qed] anywhere, only [Defined].\n\n    Instead, let's use the version of [lt_dec] from the Coq standard library,\n    which _is_ carefully built without any opaque ([Qed]) theorems.\n*)\n\nLemma compute_with_StdLib_lt_dec:  (if lt_dec 3 7 then 7 else 3) = 7.\nProof.\ncompute.\nreflexivity.\nQed.\n\n(** The Coq standard library has many decidability theorems.  You can\n   examine them by doing the following [Search] command. The results\n   shown here are only for the subset of the library that's currently\n   imported (by the [Import] commands above); there's even more out there. *)\n\nSearch ({_}+{~_}).\n(*\nreflect_dec: forall (P : Prop) (b : bool), reflect P b -> {P} + {~ P}\nlt_dec: forall n m : nat, {n < m} + {~ n < m}\nlist_eq_dec:\n  forall A : Type,\n  (forall x y : A, {x = y} + {x <> y}) ->\n  forall l l' : list A, {l = l'} + {l <> l'}\nle_dec: forall n m : nat, {n <= m} + {~ n <= m}\nin_dec:\n  forall A : Type,\n  (forall x y : A, {x = y} + {x <> y}) ->\n  forall (a : A) (l : list A), {In a l} + {~ In a l}\ngt_dec: forall n m : nat, {n > m} + {~ n > m}\nge_dec: forall n m : nat, {n >= m} + {~ n >= m}\neq_nat_decide: forall n m : nat, {eq_nat n m} + {~ eq_nat n m}\neq_nat_dec: forall n m : nat, {n = m} + {n <> m}\nbool_dec: forall b1 b2 : bool, {b1 = b2} + {b1 <> b2}\nZodd_dec: forall n : Z, {Zodd n} + {~ Zodd n}\nZeven_dec: forall n : Z, {Zeven n} + {~ Zeven n}\nZ_zerop: forall x : Z, {x = 0%Z} + {x <> 0%Z}\nZ_lt_dec: forall x y : Z, {(x < y)%Z} + {~ (x < y)%Z}\nZ_le_dec: forall x y : Z, {(x <= y)%Z} + {~ (x <= y)%Z}\nZ_gt_dec: forall x y : Z, {(x > y)%Z} + {~ (x > y)%Z}\nZ_ge_dec: forall x y : Z, {(x >= y)%Z} + {~ (x >= y)%Z}\n*)\n\n(** The type of [list_eq_dec] is worth looking at.  It says that if you\n     have  a decidable equality for an element type [A], then\n    [list_eq_dec] calculates for you a decidable equality for type [list A].\n    Try it out: *)\n\nDefinition list_nat_eq_dec:\n    (forall al bl : list nat, {al=bl}+{al<>bl}) :=\n  list_eq_dec eq_nat_dec.\n\nEval compute in if list_nat_eq_dec [1;3;4] [1;4;3] then true else false.\n (* = false : bool *)\n\nEval compute in if list_nat_eq_dec [1;3;4] [1;3;4] then true else false.\n (* = true : bool *)\n\n(** **** Exercise: 2 stars, standard (list_nat_in)\n\n    Use [in_dec] to build this function. *)\n\nDefinition list_nat_in: forall (i: nat) (al: list nat), {In i al}+{~ In i al}\n (* TODO: REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample in_4_pi:  (if list_nat_in 4  [3;1;4;1;5;9;2;6] then true else false) = true.\nProof.\nsimpl.\n(* reflexivity. *)\n(* TODO: FILL IN HERE *) Admitted.\n(** [] *)\n\n(** In general, beyond [list_eq_dec] and [in_dec], one can construct a\n     whole programmable calculus of decidability, using the\n     programs-as-proof  language of Coq.  But is it a good idea?  Read on! *)\n\n(* ################################################################# *)\n(** * Advantages and Disadvantages of [reflect] Versus [sumbool] *)\n\n(** I have shown two ways to program decision procedures in Coq,\n    one using [reflect] and the other using [{_}+{~_}], i.e., [sumbool].\n\n   - With [sumbool], you define _two_ things: the operator in [Prop]\n      such as [lt: nat -> nat -> Prop] and the decidability \"theorem\"\n      in [sumbool], such as [lt_dec: forall i j, {lt i j}+{~ lt i j}].  I say\n      \"theorem\" in quotes because it's not _just_ a theorem, it's also\n      a (nonopaque) computable function.\n\n   - With [reflect], you define _three_ things:  the operator in [Prop],\n      the operator in [bool] (such as [ltb: nat -> nat -> bool], and the\n      theorem that relates them (such as [ltb_reflect]).\n\n   Defining three things seems like more work than defining two.\n   But it may be easier and more efficient.  Programming in [bool],\n   you may have more control over how your functions are implemented,\n   you will have fewer difficult uses of dependent types, and you\n   will run into fewer difficulties with opaque theorems.\n\n   However, among Coq programmers, [sumbool] seems to be more\n   widely used, and it seems to have better support in the Coq standard\n   library.  So you may encounter it, and it is worth understanding what\n   it does.   Either of these two methods is a reasonable way of programming\n   with proof.  *)\n\n(* 2022-08-08 17:36 *)\n", "meta": {"author": "p51lee", "repo": "software-foundations", "sha": "14fb45bfebb27ccda716f67159e358d4dbbd2685", "save_path": "github-repos/coq/p51lee-software-foundations", "path": "github-repos/coq/p51lee-software-foundations/software-foundations-14fb45bfebb27ccda716f67159e358d4dbbd2685/03_verified_functional_algorithms/Decide.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012104, "lm_q2_score": 0.7956581024858785, "lm_q1q2_score": 0.6577799339759356}}
{"text": "Require Import Coq.Setoids.Setoid.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\nRequire Import KA.Finite.\nRequire Import KA.Booleans.\nRequire Import KA.Terms.\nRequire Import KA.Scope.\nLocal Open Scope ka_scope.\n\nSection Vectors.\n  Variable (A: Type).\n  Notation term := (term A).\n\n  Definition vector (Q: Type) := Q -> term.\n\n  Definition matrix (Q: Type) := Q -> Q -> term.\nEnd Vectors.\n\nSection VectorOperations.\n  Context {A: Type}.\n  Notation term := (term A).\n  Notation vector := (vector A).\n  Notation matrix := (matrix A).\n\n  Definition vector_sum\n    {Q: Type}\n    (v1 v2: vector Q)\n    (q: Q)\n    : term\n  :=\n    (v1 q + v2 q)%ka\n  .\n\n  Definition vector_chomp\n    {n: nat}\n    (v: vector (position (S n)))\n    (p: position n)\n    : term\n  :=\n    v (PThere p)\n  .\n\n  Equations inner_product {n: nat} (v1 v2: vector (position n)): term := {\n    @inner_product 0 _ _ :=\n      zero;\n    @inner_product (S _) v1 v2 :=\n      v1 PHere ;; v2 PHere + inner_product (vector_chomp v1) (vector_chomp v2);\n  }.\n\n  Definition matrix_vector_product\n    {n: nat}\n    (m: matrix (position n))\n    (v: vector (position n))\n    (p: position n)\n  :=\n    inner_product (m p) v\n  .\n\n  Definition vector_scale_left\n    {Q: Type}\n    (t: term)\n    (v: vector Q)\n    (q: Q)\n  :=\n    t ;; v q\n  .\n\n  Definition vector_scale_right\n    {Q: Type}\n    (v: vector Q)\n    (t: term)\n    (q: Q)\n  :=\n    v q ;; t\n  .\n\n  Definition vector_index\n    {X: Type}\n    `{Finite X}\n    (v: vector X)\n    (p: position (length finite_enum))\n  :\n    term\n  :=\n    v (list_lookup p)\n  .\n\n  Definition vector_lookup\n    {X: Type}\n    `{Finite X}\n    (v: vector (position (length finite_enum)))\n    (x: X)\n  :\n    term\n  :=\n    v (list_index x)\n  .\n\n  Definition matrix_index\n    {X: Type}\n    `{Finite X}\n    (m: matrix X)\n    (p p': position (length finite_enum))\n  :\n    term\n  :=\n    m (list_lookup p) (list_lookup p')\n  .\n\n  Definition matrix_lookup\n    {X: Type}\n    `{Finite X}\n    (m: matrix (position (length finite_enum)))\n    (x x': X)\n  :\n    term\n  :=\n    m (list_index x) (list_index x')\n  .\nEnd VectorOperations.\n\nNotation \"v1 <+> v2\" := (vector_sum v1 v2) (at level 40) : ka_scope.\nNotation \"# v\" := (vector_chomp v) (at level 30) : ka_scope.\nNotation \"v1 ** v2\" := (inner_product v1 v2) (at level 40) : ka_scope.\nNotation \"m <*> v\" := (matrix_vector_product m v) (at level 40) : ka_scope.\nNotation \"t & v\" := (vector_scale_left t v) (at level 30) : ka_scope.\nNotation \"v ;;; t\" := (vector_scale_right v t) (at level 35) : ka_scope.\n\nSection VectorEquiv.\n  Context {A: Type}.\n  Notation term := (term A).\n  Notation vector := (vector A).\n\n  Definition equiv_vec {Q: Type} (v1 v2: vector Q): Prop :=\n    forall (q: Q), v1 q == v2 q\n  .\n\n  Notation \"v1 === v2\" := (equiv_vec v1 v2) (at level 70).\n\n  Lemma equiv_vec_refl {Q: Type} (v: vector Q):\n    v === v\n  .\n  Proof.\n    now intro.\n  Qed.\n\n  Lemma equiv_vec_sym {Q: Type} (v1 v2: vector Q):\n    v1 === v2 -> v2 === v1\n  .\n  Proof.\n    intro; now intro.\n  Qed.\n\n  Lemma equiv_vec_trans {Q: Type} (v1 v2 v3: vector Q):\n    v1 === v2 -> v2 === v3 -> v1 === v3\n  .\n  Proof.\n    intros; intro.\n    now transitivity (v2 q).\n  Qed.\n\n  Global Add Parametric Relation (Q: Type): (vector Q) equiv_vec\n    reflexivity proved by equiv_vec_refl\n    symmetry proved by equiv_vec_sym\n    transitivity proved by equiv_vec_trans\n    as equiv_equiv_vec\n  .\n\n  Global Add Parametric Morphism (Q: Type): vector_sum\n    with signature (@equiv_vec Q) ==> equiv_vec ==> equiv_vec\n    as vector_sum_mor\n  .\n  Proof.\n    intros; intro.\n    unfold vector_sum.\n    now rewrite (H q), (H0 q).\n  Qed.\n\n  Global Add Parametric Morphism (n: nat): vector_chomp\n    with signature (@equiv_vec (position (S n))) ==> equiv_vec\n    as vector_comp_mor.\n  Proof.\n    intros.\n    intro.\n    unfold vector_chomp.\n    now rewrite (H (PThere q)).\n  Qed.\n\n  Global Add Parametric Morphism (n: nat): inner_product\n    with signature (@equiv_vec (position n)) ==> equiv_vec ==> term_equiv\n    as inner_product_mor\n  .\n  Proof.\n    intros.\n    dependent induction n.\n    - autorewrite with inner_product.\n      reflexivity.\n    - autorewrite with inner_product.\n      rewrite (H PHere), (H0 PHere).\n      apply ECongPlus; try reflexivity.\n      apply IHn.\n      + now rewrite H.\n      + now rewrite H0.\n  Qed.\n\n  Definition lequiv_vec {Q: Type} (v1 v2: vector Q): Prop :=\n    forall (q: Q), v1 q <= v2 q\n  .\nEnd VectorEquiv.\n\nNotation \"v1 === v2\" := (equiv_vec v1 v2) (at level 70) : ka_scope.\nNotation \"v1 <== v2\" := (lequiv_vec v1 v2) (at level 70) : ka_scope.\n\nSection VectorProperties.\n  Context {A: Type}.\n  Notation term := (term A).\n  Notation vector := (vector A).\n\n  Lemma vector_scale_left_chomp\n    {n: nat}\n    (t: term)\n    (v: vector (position (S n)))\n  :\n    t & (# v) === # (t & v)\n  .\n  Proof.\n    now intro.\n  Qed.\n\n  Lemma vector_inner_product_scale_left\n    {n: nat}\n    (t: term)\n    (v1 v2: vector (position n))\n  :\n    t ;; (v1 ** v2) == (t & v1) ** v2\n  .\n  Proof.\n    dependent induction n.\n    - autorewrite with inner_product.\n      now rewrite ETimesZeroLeft.\n    - autorewrite with inner_product.\n      rewrite EDistributeLeft.\n      rewrite IHn.\n      unfold vector_scale_left at 2; simpl.\n      rewrite vector_scale_left_chomp.\n      rewrite ETimesAssoc.\n      reflexivity.\n  Qed.\n\n  Lemma vector_chomp_sum\n    {n: nat}\n    (v1 v2: vector (position (S n)))\n  :\n    # (v1 <+> v2) === # v1 <+> # v2\n  .\n  Proof.\n    now intro.\n  Qed.\n\n  Lemma vector_inner_product_distribute_left\n    {n: nat}\n    (v1 v2 v3: vector (position n))\n  :\n    v1 ** v3 + v2 ** v3 == (v1 <+> v2) ** v3\n  .\n  Proof.\n    dependent induction n.\n    - autorewrite with inner_product.\n      now rewrite EPlusIdemp.\n    - autorewrite with inner_product.\n      rewrite EPlusAssoc.\n      rewrite <- EPlusAssoc with (t3 := v2 PHere ;; v3 PHere).\n      rewrite EPlusComm with (t1 := # v1 ** # v3).\n      rewrite EPlusAssoc.\n      rewrite <- EDistributeRight.\n      rewrite <- EPlusAssoc.\n      rewrite IHn.\n      unfold vector_sum at 2.\n      rewrite vector_chomp_sum.\n      reflexivity.\n  Qed.\n\n  Lemma vector_inner_product_contained\n    {n: nat}\n    (v1 v2: vector (position n))\n    (p: position n)\n  :\n    v1 p ;; v2 p <= v1 ** v2\n  .\n  Proof.\n    dependent induction p.\n    - autorewrite with inner_product.\n      apply term_lequiv_split_left.\n      apply term_lequiv_refl.\n    - autorewrite with inner_product.\n      apply term_lequiv_split_right.\n      fold ((# v1) p).\n      fold ((# v2) p).\n      apply IHp.\n  Qed.\n\n  Global Add Parametric Morphism (n: nat): inner_product\n    with signature eq ==> (@lequiv_vec A (position n)) ==> term_lequiv\n    as inner_product_mor_mono\n  .\n  Proof.\n    unfold term_lequiv; intros.\n    dependent induction n.\n    - autorewrite with inner_product.\n      apply term_lequiv_refl.\n    - autorewrite with inner_product.\n      apply term_lequiv_split.\n      + rewrite <- (H PHere).\n        rewrite EDistributeLeft.\n        repeat apply term_lequiv_split_left.\n        apply term_lequiv_refl.\n      + apply term_lequiv_split_right.\n        apply IHn.\n        intro p.\n        apply H.\n  Qed.\n\n  Lemma vector_inner_product_contained_split\n    {n: nat}\n    (v1 v2: vector (position n))\n    (t: term)\n  :\n    (forall p, v1 p ;; v2 p <= t) ->\n    v1 ** v2 <= t\n  .\n  Proof.\n    intros.\n    dependent induction n.\n    - autorewrite with inner_product.\n      rewrite EPlusComm.\n      now rewrite EPlusUnit.\n    - autorewrite with inner_product.\n      apply term_lequiv_split.\n      + apply H.\n      + apply IHn; intros.\n        unfold vector_chomp.\n        apply H.\n  Qed.\n\n  Lemma vector_scale_right_unit\n    {Q: Type}\n    (v: vector Q)\n  :\n    v ;;; 1 === v\n  .\n  Proof.\n    intro q.\n    unfold vector_scale_right.\n    now rewrite ETimesUnitRight.\n  Qed.\n\n  Lemma vector_scale_right_chomp\n    {n: nat}\n    (v: vector (position (S n)))\n    (t: term)\n  :\n    (# v) ;;; t === # (v ;;; t)\n  .\n  Proof.\n    now intro.\n  Qed.\n\n  Lemma vector_inner_product_scale_right\n    {n: nat}\n    (v1 v2: vector (position n))\n    (t: term)\n  :\n    (v1 ** v2) ;; t == v1 ** (v2 ;;; t)\n  .\n  Proof.\n    dependent induction n.\n    - autorewrite with inner_product.\n      now rewrite ETimesZeroRight.\n    - autorewrite with inner_product.\n      rewrite EDistributeRight.\n      rewrite IHn.\n      unfold vector_scale_right at 2; simpl.\n      rewrite vector_scale_right_chomp.\n      rewrite ETimesAssoc.\n      reflexivity.\n  Qed.\n\n  Lemma vector_lequiv_adjunction\n    {X: Type}\n    `{Finite X}\n    (v1: vector (position (length finite_enum)))\n    (v2: vector X)\n  :\n    v1 <== vector_index v2 <-> vector_lookup v1 <== v2\n  .\n  Proof.\n    split; intros.\n    - intro x.\n      unfold vector_lookup.\n      rewrite <- list_lookup_index at 2.\n      rewrite <- list_lookup_index at 3.\n      apply H0.\n    - intro p.\n      unfold vector_index.\n      rewrite <- list_index_lookup at 1.\n      apply H0.\n  Qed.\n\n  Lemma vector_lequiv_squeeze\n    {X: Type}\n    (v1 v2: vector X)\n  :\n    v1 <== v2 ->\n    v2 <== v1 ->\n    v1 === v2\n  .\n  Proof.\n    intros; intro x.\n    apply term_lequiv_squeeze.\n    - apply H.\n    - apply H0.\n  Qed.\nEnd VectorProperties.\n\nSection VectorBool.\n  Context {A: Type}.\n  Notation vector := (vector A).\n  Notation term := (term A).\n\n  Global Program Instance matrix_finite\n    (X Y: Type)\n    `{Finite X}\n    `{Finite Y}\n  :\n    Finite (X -> Y -> bool)\n  := {|\n    finite_enum := map curry finite_enum\n  |}.\n  Next Obligation.\n    destruct (finite_dec (uncurry x1) (uncurry x2)).\n    - left.\n      extensionality x;\n      extensionality y.\n      replace x1 with (curry (uncurry x1)) by reflexivity.\n      replace x2 with (curry (uncurry x2)) by reflexivity.\n      now rewrite e.\n    - right.\n      contradict n.\n      extensionality xy.\n      destruct xy; simpl.\n      now rewrite n.\n  Defined.\n  Next Obligation.\n    replace x with (curry (uncurry x)) by reflexivity.\n    apply in_map_iff.\n    exists (uncurry x).\n    intuition.\n    replace finite_subsets\n      with (@finite_enum (prod X Y -> bool) _)\n      by reflexivity.\n    apply finite_cover.\n  Qed.\n  Next Obligation.\n    apply NoDup_map.\n    - intros.\n      extensionality xy.\n      destruct xy.\n      replace x with (uncurry (curry x)).\n      replace y with (uncurry (curry y)).\n      + simpl.\n        now rewrite H1.\n      + extensionality xy.\n        now destruct xy.\n      + extensionality xy.\n        now destruct xy.\n    - replace finite_subsets\n        with (@finite_enum (prod X Y -> bool) _)\n        by reflexivity.\n      apply finite_nodup.\n  Qed.\n\n  Definition vector_inner_product_bool\n    {X: Type}\n    `{Finite X}\n    (v1 v2: X -> bool)\n  :\n    bool\n  :=\n    disj (map (fun x => andb (v1 x) (v2 x)) finite_enum)\n  .\n\n  Definition matrix_product_bool\n    {X: Type}\n    `{Finite X}\n    (m1 m2: X -> X -> bool)\n    (x1 x2: X)\n  :\n    bool\n  :=\n    vector_inner_product_bool (m1 x1) (fun x => m2 x x2)\n  .\n\n  Lemma matrix_product_characterise\n    {Q: Type}\n    `{Finite Q}\n    (m1 m2: Q -> Q -> bool)\n    (q1 q2: Q)\n  :\n    matrix_product_bool m1 m2 q1 q2 = true <->\n    exists (q3: Q), m1 q1 q3 = true /\\ m2 q3 q2 = true\n  .\n  Proof.\n    unfold matrix_product_bool.\n    unfold vector_inner_product_bool.\n    rewrite disj_true.\n    rewrite in_map_iff.\n    setoid_rewrite Bool.andb_true_iff.\n    split; intros.\n    - destruct H0 as [q3 [? ?]].\n      now exists q3.\n    - destruct H0 as [q3 [? ?]].\n      exists q3; intuition.\n  Qed.\n\n  Lemma matrix_product_bool_unit_left\n    {Q: Type}\n    `{Finite Q}\n    (m: Q -> Q -> bool)\n  :\n    matrix_product_bool finite_eqb m = m\n  .\n  Proof.\n    extensionality q1;\n    extensionality q2.\n    destruct (m _ _) eqn:?.\n    - apply matrix_product_characterise.\n      exists q1; intuition.\n      unfold finite_eqb.\n      now destruct (finite_dec _ _).\n    - apply Bool.not_true_iff_false.\n      apply Bool.not_true_iff_false in Heqb.\n      contradict Heqb.\n      apply matrix_product_characterise in Heqb.\n      destruct Heqb as [q3 [? ?]].\n      unfold finite_eqb in H0.\n      destruct (finite_dec _ _).\n      + now subst.\n      + discriminate.\n  Qed.\n\n  Lemma matrix_product_bool_unit_right\n    {Q: Type}\n    `{Finite Q}\n    (m: Q -> Q -> bool)\n  :\n    matrix_product_bool m finite_eqb = m\n  .\n  Proof.\n    extensionality q1;\n    extensionality q2.\n    destruct (m _ _) eqn:?.\n    - apply matrix_product_characterise.\n      exists q2; intuition.\n      unfold finite_eqb.\n      now destruct (finite_dec _ _).\n    - apply Bool.not_true_iff_false.\n      apply Bool.not_true_iff_false in Heqb.\n      contradict Heqb.\n      apply matrix_product_characterise in Heqb.\n      destruct Heqb as [q3 [? ?]].\n      unfold finite_eqb in H1.\n      destruct (finite_dec _ _).\n      + now subst.\n      + discriminate.\n  Qed.\n\n  Lemma matrix_product_bool_associative\n    {Q: Type}\n    `{Finite Q}\n    (m1 m2 m3: Q -> Q -> bool)\n  :\n    matrix_product_bool (matrix_product_bool m1 m2) m3 =\n    matrix_product_bool m1 (matrix_product_bool m2 m3)\n  .\n  Proof.\n    extensionality q1;\n    extensionality q2.\n    destruct (matrix_product_bool _ _ _) eqn:?; symmetry.\n    - apply matrix_product_characterise in Heqb.\n      destruct Heqb as [q3 [? ?]].\n      apply matrix_product_characterise in H0.\n      destruct H0 as [q4 [? ?]].\n      apply matrix_product_characterise.\n      exists q4; intuition.\n      apply matrix_product_characterise.\n      exists q3; intuition.\n    - apply Bool.not_true_iff_false.\n      apply Bool.not_true_iff_false in Heqb.\n      contradict Heqb.\n      apply matrix_product_characterise in Heqb.\n      destruct Heqb as [q3 [? ?]].\n      apply matrix_product_characterise in H1.\n      destruct H1 as [q4 [? ?]].\n      apply matrix_product_characterise.\n      exists q4; intuition.\n      apply matrix_product_characterise.\n      exists q3; intuition.\n  Qed.\n\n  Definition vector_shift_both\n    {Q: Type}\n    `{Finite Q}\n    (v: vector (prod (Q -> Q -> bool) (Q -> Q -> bool)))\n    (h: Q -> Q -> bool)\n    (fg: prod (Q -> Q -> bool) (Q -> Q -> bool))\n  :\n    term\n  :=\n    v (matrix_product_bool h (fst fg), matrix_product_bool h (snd fg))\n  .\n\n  Definition vector_shift_single\n    {Q: Type}\n    `{Finite Q}\n    (v: vector (prod (Q -> Q -> bool) (Q -> Q -> bool)))\n    (h: Q -> Q -> bool)\n    (fg: prod (Q -> Q -> bool) (Q -> Q -> bool))\n  :\n    term\n  :=\n    v (fst fg, matrix_product_bool (snd fg) h)\n  .\nEnd VectorBool.\n", "meta": {"author": "TobiasKappe", "repo": "ka-fmp-proofs", "sha": "6222b866153c4271a6b2127514c28981c7b83e65", "save_path": "github-repos/coq/TobiasKappe-ka-fmp-proofs", "path": "github-repos/coq/TobiasKappe-ka-fmp-proofs/ka-fmp-proofs-6222b866153c4271a6b2127514c28981c7b83e65/Vectors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6577704454393467}}
{"text": "(** Binary trees the nodes of which are labelled with type A *)\n\nRequire Import Omega\n        Inverse_Image Wellfounded.Inclusion Wf_nat.\n\nSection Some_type_A.\nVariable A: Type.\n\nInductive tree  : Type :=\n  | leaf  \n  | node (label: A)(left_son right_son : tree).\n\n\nInductive subtree  (t:tree) : tree -> Prop :=\n  | subtree1 : forall t'  (x:A), subtree  t (node  x t t')\n  | subtree2 : forall (t':tree) (x:A), subtree  t (node  x t' t).\n\nTheorem well_founded_subtree :  well_founded subtree.\nProof.\n intros t; induction  t as [ | x t1 IHt1 t2 IHt2].\n - split; inversion 1. \n - split; intros y Hsub; inversion_clear Hsub; assumption.\nQed.\n\n(** Alternate arithmetic proof \n\n   Using several lemmas in library Wellfounded, we use tree size\n  as a measure for proving well_foundedness \n\n*)\n\n\n\nFixpoint size (t:tree) : nat :=\nmatch t with leaf => 1\n           | node _ t1 t2 => 1 + size t1 + size t2\nend.\n\n\n\nLemma subtree_smaller : forall (t t': tree), subtree t t' -> size t < size t'.\nProof. \n inversion 1;simpl;omega.\nQed.\n\nLemma well_founded_subtree' : well_founded subtree.\nProof.\n apply wf_incl with (fun t t' => size t < size t').\n intros x y Hxy; now  apply subtree_smaller.\n apply wf_inverse_image; apply lt_wf.\nQed.\n\nEnd Some_type_A.", "meta": {"author": "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/btreewf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6577704446472382}}
{"text": "(** * An intrinsic encoding of Goedel's System T (STLC with natural numbers) *)\n\n(** STLC part is basically a replay of test-suites and examples from the Equations plugin (some of them, in turn, based on Chlipala's CPDT) *)\n(** We add a recursion over natural numbers and notations based on [Custom Entries] *)\nFrom Equations Require Import Equations.\nRequire Import PeanoNat List HList.\n\nImport ListNotations.\n\nImport Nat.\n\nSet Equations Transparent.\n\n(** ** Basic definitions *)\n\nInductive Ty : Set :=\n| tU : Ty\n| tNat : Ty\n| tArr : Ty -> Ty -> Ty.\n\nNotation \"A :-> B\" := (tArr A B) (at level 70).\n\nDefinition Ctx := list Ty.\n\nDefinition is_zero (n : nat) : bool :=\n  match n with\n  | O => true\n  | _ => false\n  end.\n\n(** The intrincic syntax for STLC *)\nInductive Exp : Ctx -> Ty -> Type :=\n| Star : forall {Γ}, Exp Γ tU\n| Var : forall {Γ τ},\n    τ ∈ Γ ->\n    Exp Γ τ\n| Lam : forall {Γ} (τ σ : Ty),\n    Exp (τ :: Γ) σ ->\n    Exp Γ (τ :-> σ)\n| App : forall {Γ} (τ σ : Ty),\n    Exp Γ (τ :-> σ) -> Exp Γ τ ->\n    Exp Γ σ\n| Zero : forall {Γ}, Exp Γ tNat\n| Suc : forall {Γ}, Exp Γ (tNat :-> tNat)\n| Nat_elim : forall {Γ τ}, Exp Γ τ -> Exp Γ (tNat :-> (τ :-> τ)) -> Exp Γ (tNat :-> τ).\n\n(** Let's create custom notations for our lambda terms *)\n\nDeclare Custom Entry ty.\nDeclare Custom Entry lambda.\n\nNotation \"[\\ e \\]\" := e (e custom ty at level 2).\nNotation \"'*'\" := tU (in custom ty).\nNotation \"'ℕ'\" := tNat (in custom ty at level 1).\nNotation \"'SUC'\" := Suc (in custom lambda at level 1).\nNotation \" A -> B\" := (tArr A B) (in custom ty at level 4, right associativity,\n                                    A custom ty,\n                                    B custom ty at level 4).\nNotation \"( x )\" := x (in custom ty, x at level 2).\n\nNotation \"[! e !]\" := e (e custom lambda at level 2).\nNotation \"()\" := (Star) (in custom lambda).\nNotation \"'v0'\" := (Var (here _)) (in custom lambda).\nNotation \"'v1'\" := (Var (there _ (here _))) (in custom lambda).\nNotation \"'v2'\" := (Var (there _ (there _ (here _)))) (in custom lambda).\nNotation \" 'λ' e : τ -> σ\" := (Lam τ σ e) (in custom lambda at level 1,\n                                              e custom lambda at level 2,\n                                              τ custom ty at level 2,\n                                              σ custom ty at level 2).\nNotation \" 'λ' e \" := (Lam _ _ e) (in custom lambda at level 1,\n                                             e custom lambda at level 2).\n\nNotation \" 'ℕ_elim' ( e0 , es ) \" := (Nat_elim e0 es)\n                                       (in custom lambda at level 1,\n                                           e0 custom lambda,\n                                           es custom lambda).\n\nNotation \"e1  e2\" := (App _ _ e1 e2) (in custom lambda at level 1,\n                                                e1 custom lambda,\n                                                e2 custom lambda at level 2\n                                                (* , *)\n                                                (* τ custom ty at level 2, *)\n                                                (* σ custom ty at level 2 *)\n                                            ).\nNotation \"( x )\" := x (in custom lambda, x at level 2).\nNotation \"{ x }\" := x (in custom lambda, x constr).\n\nDefinition unit_arrow2 := [\\ * -> * -> * \\].\n\nDefinition id_unit : Exp [] (tU :-> tU) :=\n  [! λ v0 : * -> * !].\n\nDefinition id_unit_unit : Exp [] (tU :-> (tU :-> tU)) :=\n  [! λ λ v0 !].\n\nDefinition id_fun_unit : Exp [] ((tU :-> tU) :-> (tU :-> tU)) :=\n  [! λ v0 !].\n\nDefinition id_unit_app : Exp [] (tU :-> tU) :=\n  [! {id_fun_unit} (λ v0) !].\n\n\nReserved Notation \"⟦ τ ⟧\" (at level 50).\n\nDefinition nat_elim : forall A : Type, A -> (nat -> A -> A) -> nat -> A :=\n  fun A => nat_rect (fun _ => A).\n\nEquations denoteTy (τ : Ty) : Set :=\n  { ⟦ tU ⟧ := unit;\n    ⟦ tNat ⟧ := nat;\n    ⟦ tArr τ1 τ2 ⟧ := ⟦ τ1 ⟧ -> ⟦ τ2 ⟧ }\n\nwhere \"⟦ τ ⟧\" := (denoteTy τ).\n\nNotation \"ρ ,, x\" := (HCons x ρ) (at level 50).\n\nReserved Notation \"⟦ e ⟧ ρ\" (at level 50).\n\nDefinition Env Γ := hlist Ty denoteTy Γ.\n\nEquations denoteExp {Γ τ} (ρ : Env Γ) (e : Exp Γ τ) : ⟦τ⟧ :=\n  { ⟦ Star ⟧ρ := tt;\n    ⟦ Var i ⟧ρ  := hget ρ i;\n    ⟦ Lam τ σ e ⟧ρ := fun (x : ⟦τ⟧) => denoteExp (ρ ,, x) e;\n    ⟦ App τ σ e1 e2 ⟧ρ := (⟦e1⟧ρ) (⟦e2⟧ρ);\n    ⟦ Zero ⟧ρ := O;\n    ⟦ Suc ⟧ρ := S;\n    ⟦ Nat_elim e0 f⟧ρ := fun n => nat_elim _ (⟦e0⟧ρ) (⟦f⟧ρ) n }\n\nwhere \"⟦ e ⟧ ρ\" := (denoteExp ρ e).\n\nDefinition idf := ⟦ id_unit ⟧HNil.\n\nDefinition my_add_syn : Exp [] (tNat :-> (tNat :-> tNat)) :=\n  [! λ λ (ℕ_elim(v0, (λ λ (SUC v0))) v1) !].\n\nDefinition my_add := Eval compute in ⟦my_add_syn⟧HNil.\n\nCompute my_add 1 2.\n\nLemma my_add_add n m :\n  my_add n m = n + m.\nProof.\n  induction n;simpl;auto.\nQed.\n", "meta": {"author": "annenkov", "repo": "stlcnorm", "sha": "c25865338e92c9b9b13f5f23edcad143a1885c28", "save_path": "github-repos/coq/annenkov-stlcnorm", "path": "github-repos/coq/annenkov-stlcnorm/stlcnorm-c25865338e92c9b9b13f5f23edcad143a1885c28/Stlc/Goedel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.657770429945785}}
{"text": "(** ****************************************************************\n\nBenedikt Ahrens\nstarted March 2015\n\nExtended by: Anders Mörtberg. October 2015\n\nRewritten using displayed categories by: Kobe Wullaert. October 2022\n\n*******************************************************************)\n\n(** ***************************************************************\n\nContents :\n\n- Category of algebras of an endofunctor\n\n- This category is saturated if base precategory is\n\n- Lambek's lemma: if (A,a) is an inital F-algebra then a is an iso\n\n- The natural numbers are initial for X ↦ 1 + X\n\n******************************************************************)\n\nRequire Import UniMath.Foundations.PartD.\nRequire Import UniMath.Foundations.Propositions.\nRequire Import UniMath.Foundations.Sets.\nRequire Import UniMath.MoreFoundations.Tactics.\n\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.Univalence.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.whiskering.\nRequire Import UniMath.CategoryTheory.limits.initial.\n\nRequire Import UniMath.CategoryTheory.DisplayedCats.Core.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Total.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Constructions.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Isos.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Univalence.\n\n(* The following are used for examples *)\nRequire Import UniMath.CategoryTheory.limits.terminal.\nRequire Import UniMath.CategoryTheory.limits.bincoproducts.\nRequire Import UniMath.CategoryTheory.NNO.\n\nLocal Open Scope cat.\n\n(** ** Category of algebras of an endofunctor *)\n\nSection Algebra_Definition.\n\n  Context {C : category} (F : functor C C).\n\n  Definition algebra_disp_cat_ob_mor : disp_cat_ob_mor C.\n  Proof.\n    use tpair.\n    - exact (λ x, F x --> x).\n    - exact (λ x y hx hy f, hx · f = #F f · hy).\n  Defined.\n\n  Definition algebra_disp_cat_id_comp\n    : disp_cat_id_comp C algebra_disp_cat_ob_mor.\n  Proof.\n    split.\n    - intros x hx ; cbn.\n      rewrite !functor_id.\n      rewrite id_left, id_right.\n      apply idpath.\n    - intros x y z f g hx hy hz hf hg ; cbn in *.\n      rewrite !functor_comp.\n      rewrite !assoc.\n      rewrite hf.\n      rewrite !assoc'.\n      rewrite hg.\n      apply idpath.\n  Qed.\n\n  Definition algebra_disp_cat_data : disp_cat_data C\n    := algebra_disp_cat_ob_mor ,, algebra_disp_cat_id_comp.\n\n  Definition algebra_disp_cat_axioms\n    : disp_cat_axioms C algebra_disp_cat_data.\n  Proof.\n    repeat split ; intros ; try (apply homset_property).\n    apply isasetaprop.\n    apply homset_property.\n  Qed.\n\n  Definition algebra_disp_cat : disp_cat C\n    := algebra_disp_cat_data ,, algebra_disp_cat_axioms.\n\n  Definition category_FunctorAlg : category\n    := total_category algebra_disp_cat.\n\n  Definition FunctorAlg := category_FunctorAlg.\n\n  Definition algebra_ob : UU := ob FunctorAlg.\n\n  (* this coercion causes confusion, and it is not inserted when parsing most of the time\n   thus removing coercion globally\n   *)\n  Definition alg_carrier (X : algebra_ob) : C := pr1 X.\n  Local Coercion alg_carrier : algebra_ob >-> ob.\n\n  Definition alg_map (X : algebra_ob) : F X --> X := pr2 X.\n\n(** A morphism of F-algebras (F X, g : F X --> X) and (F Y, h : F Y --> Y)\n    is a morphism f : X --> Y such that the following diagram commutes:\n<<\n>>>>>>> master\n         F f\n    F x ----> F y\n    |         |\n    | g       | h\n    V         V\n    x ------> y\n         f\n>>\n *)\nDefinition is_algebra_mor (X Y : algebra_ob) (f : alg_carrier X --> alg_carrier Y) : UU\n  := alg_map X · f = #F f · alg_map Y.\n\n  Definition algebra_mor (X Y : algebra_ob) : UU := FunctorAlg⟦X,Y⟧.\n  Coercion mor_from_algebra_mor {X Y : algebra_ob} (f : algebra_mor X Y) : C⟦X, Y⟧ := pr1 f.\n\n  Lemma algebra_mor_commutes (X Y : algebra_ob) (f : algebra_mor X Y)\n    : alg_map X · f = #F f · alg_map Y.\n  Proof.\n    exact (pr2 f).\n  Qed.\n\n(*Definition algebra_mor_id (X : algebra_ob) : algebra_mor X X.\nProof.\n  exists (identity _ ).\n  abstract (unfold is_algebra_mor;\n            rewrite id_right ;\n            rewrite functor_id;\n            rewrite id_left;\n            apply idpath).\nDefined.\n\nDefinition algebra_mor_comp (X Y Z : algebra_ob) (f : algebra_mor X Y) (g : algebra_mor Y Z)\n  : algebra_mor X Z.\nProof.\n  exists (f · g).\n  abstract (unfold is_algebra_mor;\n            rewrite assoc;\n            rewrite algebra_mor_commutes;\n            rewrite <- assoc;\n            rewrite algebra_mor_commutes;\n            rewrite functor_comp, assoc;\n            apply idpath).\nDefined.\n\nDefinition precategory_alg_ob_mor : precategory_ob_mor.\nProof.\n  exists algebra_ob.\n  exact algebra_mor.\nDefined.\n\nDefinition precategory_alg_data : precategory_data.\nProof.\n  exists precategory_alg_ob_mor.\n  exists algebra_mor_id.\n  exact algebra_mor_comp.\nDefined.*)\n\n\nEnd Algebra_Definition.\n\n(* Definition isaset_algebra_mor {C : category} (F : functor C C) (X Y : algebra_ob F) : isaset (algebra_mor F X Y).\nProof.\n  apply (isofhleveltotal2 2).\n  - apply C.\n  - intro f.\n    apply isasetaprop.\n    apply C.\nQed.*)\n\nDefinition algebra_mor_eq' {C : category} {F : functor C C} {X Y : algebra_ob F} (f g : algebra_mor F X Y)\n  : (f : alg_carrier F X --> alg_carrier F Y) = g ≃ f = g.\nProof.\n  apply invweq.\n  apply subtypeInjectivity.\n  intro a. apply C.\nDefined.\n\nDefinition algebra_mor_eq {C : category} {F : functor C C} {X Y : FunctorAlg F} (f g : (FunctorAlg F)⟦X,Y⟧)\n  : ((pr1 f : alg_carrier F X --> alg_carrier F Y) = (pr1 g)) -> f = g.\nProof.\n  exact (algebra_mor_eq' f g).\nDefined.\n\n(* Lemma is_precategory_precategory_alg_data {C : category} (F : functor C C)\n  : is_precategory (precategory_alg_data F).\nProof.\n  repeat split; intros; simpl.\n  - apply algebra_mor_eq.\n    apply id_left.\n  - apply algebra_mor_eq.\n    apply id_right.\n  - apply algebra_mor_eq.\n    apply assoc.\n  - apply algebra_mor_eq.\n    apply assoc'.\nQed.\n\nDefinition precategory_FunctorAlg {C : category} (F : functor C C)\n  : precategory := tpair _ _ (is_precategory_precategory_alg_data F).\n\nLemma has_homsets_FunctorAlg {C : category} (F : functor C C)\n  : has_homsets (precategory_FunctorAlg F).\nProof.\n  intros f g.\n  apply isaset_algebra_mor.\nQed.\n\nDefinition category_FunctorAlg {C : category} (F : functor C C) : category\n  := make_category  (precategory_FunctorAlg F) (has_homsets_FunctorAlg F).\n\nNotation FunctorAlg := category_FunctorAlg.*)\n\n\nSection fixacategory.\n\n  Context {C : category}\n          (F : functor C C).\n\n\n(** forgetful functor from FunctorAlg to its underlying category *)\n\n(* first step of definition *)\n(* Definition forget_algebras_data : functor_data (FunctorAlg F) C.\nProof.\n  set (onobs := fun alg : FunctorAlg F => dialgebra_carrier alg).\n  apply (make_functor_data onobs).\n  intros alg1 alg2 m.\n  exact (mor_from_dialgebra_mor m).\nDefined. *)\n\n(* the forgetful functor *)\nDefinition forget_algebras : functor (category_FunctorAlg F) C := pr1_category (algebra_disp_cat F).\n(*Proof.\n  Check dialgebra_pr1.\n\n  apply (make_functor forget_algebras_data).\n  abstract ( split; [intro alg; apply idpath | intros alg1 alg2 alg3 m n; apply idpath] ).\nDefined.*)\n\nEnd fixacategory.\n\n\n(** ** This category is saturated if the base category is  *)\n\nSection FunctorAlg_saturated.\n\n  Context {C : category}\n          (H : is_univalent C)\n          (F : functor C C).\n\n  Definition algebra_eq_type (X Y : FunctorAlg F) : UU\n    := ∑ p : z_iso (pr1 X) (pr1 Y), is_algebra_mor F X Y p.\n\nDefinition algebra_ob_eq (X Y : FunctorAlg F) :\n  (X = Y) ≃ algebra_eq_type X Y.\nProof.\n  eapply weqcomp.\n  - apply total2_paths_equiv.\n  - set (H1 := make_weq _ (H (pr1 X) (pr1 Y))).\n    apply (weqbandf H1).\n    simpl.\n    intro p.\n    destruct X as [X α].\n    destruct Y as [Y β]; simpl in *.\n    destruct p.\n    rewrite idpath_transportf.\n    unfold is_algebra_mor; simpl.\n    rewrite functor_id.\n    rewrite id_left, id_right.\n    apply idweq.\nDefined.\n\nDefinition is_z_iso_from_is_algebra_iso (X Y : FunctorAlg F) (f : X --> Y)\n  : is_z_isomorphism f → is_z_isomorphism (pr1 f).\nProof.\n  intro p.\n  set (H' := z_iso_inv_after_z_iso (make_z_iso' f p)).\n  set (H'':= z_iso_after_z_iso_inv (make_z_iso' f p)).\n  exists (pr1 (inv_from_z_iso (make_z_iso' f p))).\n  split; simpl.\n  - apply (maponpaths pr1 H').\n  - apply (maponpaths pr1 H'').\nDefined.\n\nDefinition inv_algebra_mor_from_is_z_iso {X Y : FunctorAlg F} (f : X --> Y)\n  : is_z_isomorphism (pr1 f) → (Y --> X).\nProof.\n  intro T.\n  set (fiso:=make_z_iso' (pr1 f) T).\n  set (finv:=inv_from_z_iso fiso).\n  exists finv.\n  unfold finv.\n  apply pathsinv0.\n  apply z_iso_inv_on_left.\n  simpl.\n  rewrite functor_on_inv_from_z_iso.\n  rewrite <- assoc.\n  apply pathsinv0.\n  apply z_iso_inv_on_right.\n  simpl.\n  apply (pr2 f).\nDefined.\n\nDefinition is_algebra_iso_from_is_z_iso {X Y : FunctorAlg F} (f : X --> Y)\n  : is_z_isomorphism (pr1 f) → is_z_isomorphism f.\nProof.\n  intro T.\n  exists (inv_algebra_mor_from_is_z_iso f T).\n  split; simpl.\n  - apply algebra_mor_eq.\n    apply (z_iso_inv_after_z_iso (make_z_iso' (pr1 f) T)).\n  - apply algebra_mor_eq.\n    apply (z_iso_after_z_iso_inv (make_z_iso' (pr1 f) T)).\nDefined.\n\nDefinition algebra_iso_first_z_iso {X Y : FunctorAlg F}\n  : z_iso X Y ≃ ∑ f : X --> Y, is_z_isomorphism (pr1 f).\nProof.\n  apply (weqbandf (idweq _ )).\n  unfold idweq. simpl.\n  intro f.\n  apply weqimplimpl.\n  - apply is_z_iso_from_is_algebra_iso.\n  - apply is_algebra_iso_from_is_z_iso.\n  - apply (isaprop_is_z_isomorphism (C:=FunctorAlg F) f).\n  - apply (isaprop_is_z_isomorphism (pr1 f)).\nDefined.\n\nDefinition swap (A B : UU) : A × B → B × A.\nProof.\n  intro ab.\n  exists (pr2 ab).\n  exact (pr1 ab).\nDefined.\n\nDefinition swapweq (A B : UU) : (A × B) ≃ (B × A).\nProof.\n  exists (swap A B).\n  apply (isweq_iso _ (swap B A)).\n  - abstract ( intro ab; destruct ab; apply idpath ).\n  - abstract ( intro ba; destruct ba; apply idpath ).\nDefined.\n\nDefinition algebra_z_iso_rearrange {X Y : FunctorAlg F}\n  : (∑ f : X --> Y, is_z_isomorphism (pr1 f)) ≃ algebra_eq_type X Y.\nProof.\n  eapply weqcomp.\n  - apply weqtotal2asstor.\n  - simpl. unfold algebra_eq_type.\n    apply invweq.\n    eapply weqcomp.\n    + apply weqtotal2asstor.\n    + simpl. apply (weqbandf (idweq _ )).\n      unfold idweq. simpl.\n      intro f; apply swapweq.\nDefined.\n\nDefinition algebra_idtoiso (X Y : FunctorAlg F) :\n  (X = Y) ≃ z_iso X Y.\nProof.\n  eapply weqcomp.\n  - apply algebra_ob_eq.\n  - eapply weqcomp.\n    + apply (invweq (algebra_z_iso_rearrange)).\n    + apply (invweq algebra_iso_first_z_iso).\nDefined.\n\nLemma isweq_idtoiso_FunctorAlg (X Y : FunctorAlg F)\n  : isweq (@idtoiso _ X Y).\nProof.\n  apply (isweqhomot (algebra_idtoiso X Y)).\n  - intro p. induction p.\n    simpl.\n    apply (z_iso_eq(C:=FunctorAlg F)). apply algebra_mor_eq.\n    apply idpath.\n  - apply (pr2 _ ).\nDefined.\n\nLemma is_univalent_FunctorAlg : is_univalent (FunctorAlg F).\nProof.\n  intros X Y.\n  apply isweq_idtoiso_FunctorAlg.\nDefined.\n\nLemma idtomor_FunctorAlg_commutes (X Y: FunctorAlg F) (e: X = Y)\n  : mor_from_algebra_mor F (idtomor _ _ e) = idtomor _ _ (maponpaths (alg_carrier F) e).\nProof.\n  induction e.\n  apply idpath.\nQed.\n\nCorollary idtoiso_FunctorAlg_commutes (X Y: FunctorAlg F) (e: X = Y)\n  : mor_from_algebra_mor F (morphism_from_z_iso _ _ (idtoiso e))\n    = idtoiso (maponpaths (alg_carrier F) e).\nProof.\n  unfold morphism_from_z_iso.\n  rewrite eq_idtoiso_idtomor.\n  etrans.\n  2: { apply pathsinv0, eq_idtoiso_idtomor. }\n  apply idtomor_FunctorAlg_commutes.\nQed.\n\n\nEnd FunctorAlg_saturated.\n\n(** ** Lambek's lemma: If (A,a) is an initial F-algebra then a is an iso *)\n\nSection Lambeks_lemma.\n\nVariables (C : category) (F : functor C C).\nVariables (Aa : FunctorAlg F) (AaIsInitial : isInitial (FunctorAlg F) Aa).\n\nLocal Definition AaInitial : Initial (FunctorAlg F) :=\n  make_Initial _ AaIsInitial.\n\nLocal Notation A := (alg_carrier _ Aa).\nLocal Notation a := (alg_map _ Aa).\n\n(* (FA,Fa) is an F-algebra *)\nLocal Definition FAa : FunctorAlg F := tpair (λ X, C ⟦F X,X⟧) (F A) (# F a).\nLocal Definition Fa' := InitialArrow AaInitial FAa.\nLocal Definition a' : C⟦A,F A⟧ := mor_from_algebra_mor F Fa'.\nLocal Definition Ha' := algebra_mor_commutes _ _ _ Fa'.\n\nLemma initialAlg_is_iso_subproof : is_inverse_in_precat a a'.\nProof.\n  assert (Ha'a : a' · a = identity A).\n  { assert (algMor_a'a : is_algebra_mor _ _ _ (a' · a)).\n    { unfold is_algebra_mor, a'; rewrite functor_comp.\n      eapply pathscomp0; [|eapply cancel_postcomposition; apply Ha'].\n      apply assoc. }\n    apply pathsinv0; set (X := tpair _ _ algMor_a'a).\n    apply (maponpaths pr1 (!@InitialEndo_is_identity _ AaInitial X)).\n  }\n  split; trivial.\n  eapply pathscomp0; [apply Ha'|]; cbn.\n  rewrite <- functor_comp.\n  eapply pathscomp0; [eapply maponpaths; apply Ha'a|].\n  apply functor_id.\nQed.\n\nLemma initialAlg_is_z_iso : is_z_isomorphism a.\nProof.\n  exists a'.\n  exact initialAlg_is_iso_subproof.\nDefined.\n\nEnd Lambeks_lemma.\n\n\n(** ** The natural numbers are intial for X ↦ 1 + X *)\n\n(** This can be used as a definition of a natural numbers object (NNO) in\n    any category with binary coproducts and a terminal object. We prove\n    the universal property of NNOs below. *)\n\nSection Nats.\n  Context (C : category).\n  Context (bc :  BinCoproducts C).\n  Context (hsC :  has_homsets C).\n  Context (T : Terminal C).\n\n  Local Notation \"1\" := T.\n  Local Notation \"f + g\" := (BinCoproductOfArrows _ _ _ f g).\n  Local Notation \"[ f , g ]\" := (BinCoproductArrow _ _ f g).\n\n  Let F : functor C C := BinCoproduct_of_functors _ _ bc\n                                                  (constant_functor _ _ 1)\n                                                  (functor_identity _).\n\n  (** F on objects: X ↦ 1 + X *)\n  Definition F_compute1 : ∏ c : C, F c = BinCoproductObject (bc 1 c) :=\n    fun c => (idpath _).\n\n  (** F on arrows: f ↦ [identity 1, f] *)\n  Definition F_compute2 {x y : C} : ∏ f : x --> y, # F f = (identity 1) + f :=\n    fun c => (idpath _).\n\n  Definition nat_ob : UU := Initial (FunctorAlg F).\n\n  Definition nat_ob_carrier (N : nat_ob) : ob C :=\n    alg_carrier _ (InitialObject N).\n  Local Coercion nat_ob_carrier : nat_ob >-> ob.\n\n  (** We have an arrow alg_map : (F N = 1 + N) --> N,\n      so by the η-rule (UMP) for the coproduct, we can assume that it\n      arises from a pair of maps [nat_ob_z,nat_ob_s] by composing with\n      coproduct injections.\n<<\n                  in1         in2\n               1 ----> 1 + N <---- N\n               |         |         |\n      nat_ob_z |         | alg_map | nat_ob_s\n               |         V         |\n               +-------> N <-------+\n>>\n   *)\n  Definition nat_ob_z (N : nat_ob) : (1 --> N) :=\n    BinCoproductIn1 (bc 1 (alg_carrier F (pr1 N))) · (alg_map _ (pr1 N)).\n\n  Definition nat_ob_s (N : nat_ob) : (N --> N) :=\n    BinCoproductIn2 (bc 1 (alg_carrier F (pr1 N))) · (alg_map _ (pr1 N)).\n\n  Local Notation \"0\" := (nat_ob_z _).\n\n  (** Use the universal property of the coproduct to make any object with a\n      point and an endomorphism into an F-algebra *)\n  Definition make_F_alg {X : ob C} (f : 1 --> X) (g : X --> X) : ob (FunctorAlg F).\n  Proof.\n    refine (X,, _).\n    exact (BinCoproductArrow _ f g).\n  Defined.\n\n  (** Using make_F_alg, X will be an F-algebra, and by initiality of N, there will\n      be a unique morphism of F-algebras N --> X, which can be projected to a\n      morphism in C. *)\n  Definition nat_ob_rec (N : nat_ob) {X : ob C} :\n    ∏ (f : 1 --> X) (g : X --> X), (N --> X) :=\n    fun f g => mor_from_algebra_mor F (InitialArrow N (make_F_alg f g)).\n\n  (** When calling the recursor on 0, you get the base case.\n      Specifically,\n\n        nat_ob_z · nat_ob_rec = f\n   *)\n  Lemma nat_ob_rec_z (N : nat_ob) {X : ob C} :\n    ∏ (f : 1 --> X) (g : X --> X), nat_ob_z N · nat_ob_rec N f g = f.\n  Proof.\n    intros f g.\n\n    pose (inlN := BinCoproductIn1 (bc 1 N)).\n    pose (succ := nat_ob_s N).\n\n    (** By initiality of N, there is a unique morphism making the following\n        diagram commute:\n<<\n               inlN         identity 1 + nat_ob_rec\n            1 -----> 1 + N -------------------------> 1 + X\n                       |                                |\n             alg_map N |                                | alg_map X\n                       V                                V\n                       N   -------------------------->  X\n                                   nat_ob_rec\n>>\n\n        This proof uses somewhat idiosyncratic \"forward reasoning\", transforming\n        the term \"diagram\" rather than the goal.\n     *)\n    pose\n      (diagram :=\n         maponpaths\n           (fun x => inlN · x)\n           (algebra_mor_commutes F (pr1 N) _ (InitialArrow N (make_F_alg f g)))).\n    rewrite (F_compute2 _) in diagram.\n\n    (** Using the η-rules for coproducts, we can assume that alg_map X = [f,g]\n        for f : 1 --> X, g : X --> X. *)\n    rewrite (BinCoproductArrowEta C 1 X (bc _ _) _ _) in diagram.\n\n    (** Using the β-rules for coproducts, we can simplify some of the terms *)\n    (** (identity 1 + _) · [f, g] --β--> [identity 1 · f, _ · g] *)\n    rewrite (precompWithBinCoproductArrow C (bc 1 N) (bc 1 X)\n                                          (identity 1) _ _ _) in diagram.\n\n    (** inl · [identity 1 · f, _ · g] --β--> identity 1 · f *)\n    rewrite (BinCoproductIn1Commutes C 1 N (bc 1 _) _ _ _) in diagram.\n\n    (** We can dispense with the identity *)\n    rewrite (id_left _) in diagram.\n\n    rewrite assoc in diagram.\n    rewrite (BinCoproductArrowEta C 1 N (bc _ _) _ _) in diagram.\n\n    refine (_ @ (BinCoproductIn1Commutes C _ _ (bc 1 _) _ f g)).\n    rewrite (!BinCoproductIn1Commutes C _ _ (bc 1 _) _ 0 succ).\n    unfold nat_ob_rec in *.\n    exact diagram.\n  Defined.\n\n  Opaque nat_ob_rec_z.\n\n  (** The succesor case:\n\n        nat_ob_s · nat_ob_rec = nat_ob_rec · g\n\n      The proof is very similar.\n   *)\n  Lemma nat_ob_rec_s (N : nat_ob) {X : ob C} :\n    ∏ (f : 1 --> X) (g : X --> X),\n    nat_ob_s N · nat_ob_rec N f g = nat_ob_rec N f g · g.\n  Proof.\n    intros f g.\n\n    pose (inrN := BinCoproductIn2 (bc 1 N)).\n    pose (succ := nat_ob_s N).\n\n    (** By initiality of N, there is a unique morphism making the same diagram\n        commute as above, but with \"inrN\" in place of \"inlN\". *)\n    pose\n      (diagram :=\n         maponpaths\n           (fun x => inrN · x)\n           (algebra_mor_commutes F (pr1 N) _ (InitialArrow N (make_F_alg f g)))).\n    rewrite (F_compute2 _) in diagram.\n\n    rewrite (BinCoproductArrowEta C 1 X (bc _ _) _ _) in diagram.\n\n    (** Using the β-rules for coproducts, we can simplify some of the terms *)\n    (** (identity 1 + _) · [f, g] --β--> [identity 1 · f, _ · g] *)\n    rewrite (precompWithBinCoproductArrow C (bc 1 N) (bc 1 X)\n                                          (identity 1) _ _ _) in diagram.\n\n    (** inl · [identity 1 · f, _ · g] --β--> identity 1 · f *)\n    rewrite (BinCoproductIn2Commutes C 1 N (bc 1 _) _ _ _) in diagram.\n\n    rewrite assoc in diagram.\n    rewrite (BinCoproductArrowEta C 1 N (bc _ _) _ _) in diagram.\n\n    refine\n      (_ @ maponpaths (fun x => nat_ob_rec N f g · x)\n         (BinCoproductIn2Commutes C _ _ (bc 1 _) _ f g)).\n    rewrite (!BinCoproductIn2Commutes C _ _ (bc 1 _) _ 0 (nat_ob_s N)).\n    unfold nat_ob_rec in *.\n    exact diagram.\n  Defined.\n\n  Opaque nat_ob_rec_s.\n\nEnd Nats.\n\n(** nat_ob implies NNO *)\nLemma nat_ob_NNO {C : category} (BC : BinCoproducts C) (hsC : has_homsets C) (TC : Terminal C) :\n  nat_ob _ BC TC → NNO TC.\nProof.\nintros N.\nuse make_NNO.\n- exact (nat_ob_carrier _ _ _  N).\n- apply nat_ob_z.\n- apply nat_ob_s.\n- intros n z s.\n  use unique_exists.\n  + apply (nat_ob_rec _ _ _ _ z s).\n  + split; [ apply nat_ob_rec_z | apply nat_ob_rec_s ].\n  + intros x; apply isapropdirprod; apply hsC.\n  + intros x [H1 H2].\n    transparent assert (xalg : (FunctorAlg (BinCoproduct_of_functors C C BC\n                                              (constant_functor C C TC)\n                                              (functor_identity C))\n                                              ⟦ InitialObject N, make_F_alg C BC TC z s ⟧)).\n    { refine (x,,_).\n      abstract (apply pathsinv0; etrans; [apply precompWithBinCoproductArrow |];\n                rewrite id_left, <- H1;\n                etrans; [eapply maponpaths, pathsinv0, H2|];\n                now apply pathsinv0, BinCoproductArrowUnique; rewrite assoc;\n                apply maponpaths).\n    }\n    exact (maponpaths pr1 (InitialArrowUnique N (make_F_alg C BC TC z s) xalg)).\nDefined.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/CategoryTheory/FunctorAlgebras.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759128, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6577704225950581}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import Bvector.\nRequire Import Setoid.\n\nDefinition byte := Bvector 8.\nDefinition xor  := BVxor.\n\nLemma xor_commut : forall n x y, @xor n x y = xor y x.\nProof.\n  intros.\n  unfold xor, BVxor.\n  apply (Vector.rect2 (fun m v1 v2 =>\n    Vector.map2 (n:=m) xorb v1 v2 = Vector.map2 xorb v2 v1)).\n  - reflexivity.\n  - intros; cbn.\n    now rewrite xorb_comm, H.\nQed.\n\nLemma xor_assoc : forall n x y z, @xor n x (xor y z) = xor (xor x y) z.\nProof.\n  intros.\n  unfold xor, BVxor.\n  (* TODO: Finish this proof. *)\nAdmitted.\n\nLemma xor_nilpotent : forall n x, xor x x = Bvect_false n.\nProof.\n  intros.\n  unfold xor, BVxor, Bvect_false.\n  induction x.\n  - reflexivity.\n  - now cbn; rewrite IHx, xorb_nilpotent.\nQed.\n\nLemma xor_false_r : forall n x, xor x (Bvect_false n) = x.\nProof.\n  induction x.\n  - reflexivity.\n  - now cbn; rewrite IHx, xorb_false_r.\nQed.\n\nLemma xor_false_l : forall n x, xor (Bvect_false n) x = x.\nProof.\n  induction x.\n  - reflexivity.\n  - cbn; rewrite IHx.\n    now destruct h.\nQed.\n\nDefinition swap (vars : byte * byte) :=\n  let '(x, y) := vars in\n  let x := xor x y in\n  let y := xor y x in\n  let x := xor x y in\n      (x, y).\n\nTheorem swap_correct : forall x y, swap (x, y) = (y, x).\nProof.\n  intros; unfold swap.\n  rewrite (xor_commut y (xor x y)), xor_assoc.\n  rewrite xor_nilpotent, xor_false_l.\n  rewrite <- xor_assoc, xor_nilpotent, xor_false_r.\n  reflexivity.\nQed.\n", "meta": {"author": "mgrabovsky", "repo": "fm-notes", "sha": "6c38cee5a4390c4543d6a404bd88909f3116bafe", "save_path": "github-repos/coq/mgrabovsky-fm-notes", "path": "github-repos/coq/mgrabovsky-fm-notes/fm-notes-6c38cee5a4390c4543d6a404bd88909f3116bafe/sketches/xorswap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6577704198807797}}
{"text": "(* Exercise 123 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\nTheorem exercise_123 : ((A \\/ (A -> B)) -> B) -> B.\nProof.\nimp_i a1.\nimp_e (A \\/ (A -> B)).\nhyp a1.\ndis_e (A \\/ ~A) a2 a2.\nLEM.\ndis_i1.\nhyp a2.\ndis_i2.\nimp_i a3.\nneg_e A.\nhyp a2.\nhyp a3.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop123.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6576836658689641}}
{"text": "\n(*Axioms*)\nRequire Import Classical.\nRequire Import ClassicalChoice.\nRequire Import FunctionalExtensionality.\nRequire Import PropExtensionality.\nRequire Import Description.\nRequire Import ClassicalDescription.\nRequire Import List.\nRequire Import Psatz.\nRequire Import Rbase.\nRequire Import Rfunctions.\nRequire Import Sets_basics.\n\nLoad Measure_basics.\n\nOpen Scope R_scope.\n\nCheck R.\n\n\n\n(***********)\n(*Notations*)\n(***********)\n\nDefinition is_open_R (A : R -> Prop) :=\n  forall x, A x -> exists epsilon, 0 < epsilon /\\ forall y, 0 < y -> y < epsilon -> A (x - y) /\\ A (x + y).\n\n\nDefinition M_interesting :=\n  generated_sig_alg (fun x => True) (fun A => exists (a : R), A = right_infinite_open_int a).\nDefinition M_reals_borelian :=\n  generated_sig_alg (fun x => True) (fun A => is_open_R A).\n\n(*We want to show that M_reals_borelian = M_interesting.*)\n\n\n(*First, we want to show that any open set in R is a countable union of intervals\n of the form ]- \\infty ; a [, ]a ; b[ and ]b ; + \\infty[.\nWe will call this important_lemma.*)\n\n(*****************)\n(*Important lemma*)\n(*****************)\n", "meta": {"author": "Upkco", "repo": "Coq_proofs", "sha": "fc0189a80435d40ba011ce20d4da8dd76edae548", "save_path": "github-repos/coq/Upkco-Coq_proofs", "path": "github-repos/coq/Upkco-Coq_proofs/Coq_proofs-fc0189a80435d40ba011ce20d4da8dd76edae548/Probabilities/Reals/Reals_int_elem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356994, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6576377798060321}}
{"text": "(** ** DTMC *)\nRequire Import Reals.\nRequire Import List.\nRequire Import ListSet.\n\nOpen Scope R_scope.\n\nRequire Import State.\nRequire Import TransitionMatrix.Definitions.\nRequire Import TransitionMatrix.Real.\nRequire Import Probabilities.\n\n\nRecord DTMC : Type := { S:  set State;\n                        s0: State;\n                        P:  TransitionMatrix R;\n                        T:  set State }.\n\n\n(** Well-formed DTMC *)\n\nDefinition wf_DTMC (d: DTMC) : Prop :=\n  (In d.(s0) d.(S))\n  /\\ (incl d.(T) d.(S))\n  /\\ (forall s: State, In s d.(S) <-> StateMaps.In s d.(P))\n  /\\ (is_stochastic_matrix d.(P)).\n\n\n(** Probability of going from a given state to any other within a set of target states. *)\n\nVariable pr_set: DTMC -> State -> set State -> R.\n\nHypothesis wf_dtmc_yields_valid_probability:\n  forall (d: DTMC) (s: State) (Tgt: set State),\n    (wf_DTMC d /\\ In s d.(S) /\\ incl Tgt d.(T)) -> is_valid_prob (pr_set d s Tgt).\n\n\n(** Probability of going from a given state to another within a DTMC. *)\n\nDefinition pr (d: DTMC) (s t: State): R := pr_set d s (set_add State.eq_dec t (empty_set State)).\n", "meta": {"author": "thiagomael", "repo": "proof-assistants-poc", "sha": "8e88b5e6761a1c4012d5cd93a88fa7b74cd5ddb7", "save_path": "github-repos/coq/thiagomael-proof-assistants-poc", "path": "github-repos/coq/thiagomael-proof-assistants-poc/proof-assistants-poc-8e88b5e6761a1c4012d5cd93a88fa7b74cd5ddb7/Coq/Markov/DTMC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.6575760124909703}}
{"text": "Require Export LL.Misc.Utils. \nRequire Export LL.PLL.Syntax.\n\nExport ListNotations.\nSet Implicit Arguments.\n\nSection LL2Sequent.\n  Definition multiset := list.\n \n  Reserved Notation \"n '|--' B ';' L \" (at level 80).\n\n  Inductive LL2N:  nat -> multiset oo -> multiset oo -> Prop :=\n  (* axioms *)\n  | ll2_init : forall B A L n, Permutation L [atom A; perp A] -> n |-- B ; L\n  | ll2_one : forall B n, n |-- B ; [One]\n  | ll2_top : forall B M L n, Permutation L (Top :: M) ->\n      n |-- B ; L\n  (* additives *)      \n  | ll2_plus1 : forall B M F G L n, Permutation L ((AOr F G)::M) ->\n      n |-- B ; F::M -> S n |-- B ; L\n  | ll2_plus2 : forall B M F G L n, Permutation L ((AOr F G)::M) ->\n      n |-- B ; G::M -> S n |-- B ; L\n  | ll2_with : forall B M F G L n, Permutation L ((AAnd F G)::M) ->\n      n |-- B ; F :: M ->\n      n |-- B ; G :: M -> S n |-- B ; L \n  (* multiplicatives *)     \n  | ll2_bot : forall B M L n, Permutation L (Bot :: M) ->\n      n |-- B ; M -> S n |-- B ; L\n  | ll2_par : forall B M F G L n, Permutation L ((MOr F G) :: M) ->\n      n |-- B ; F::G::M -> S n |-- B ; L         \n  | ll2_tensor : forall B M N F G L n, Permutation L ((MAnd F G)::(M ++ N)) ->\n                                        (n |-- B ; F::M) ->\n                                        (n |-- B ; G::N) ->\n                                        (S n) |-- B ; L \n   (* exponentials *)          \n  | ll2_quest : forall B M F L n, Permutation L ((Quest F) :: M) ->\n      n |-- F::B ; M -> S n |-- B ; L   \n  | ll2_bang : forall B F n,\n      n |-- B ; [F] -> S n |-- B ; [Bang F]\n  (* structurals *)            \n  | ll2_abs : forall B L F n, \n     In F B -> n |-- B ; F::L -> S n |-- B ; L \n  \n                                                                                                                    \n  where \"n '|--' B ';' L \" := (LL2N n B L).\n   \n  Reserved Notation \"'|--' B ';' L\" (at level 80).\n\n  Inductive LL2S:  multiset oo -> multiset oo -> Prop :=\n  (* axioms *)  \n  | ll2_init' : forall B A L, Permutation L [atom A; perp A] -> |-- B ; L\n  | ll2_one' : forall B, |-- B ; [One]\n  | ll2_top' : forall B M L, Permutation L (Top :: M) ->\n      |-- B ; L\n  (* additives *)  \n  | ll2_plus1' : forall B M F G L, Permutation L ((AOr F G)::M) ->\n      |-- B ; F::M -> |-- B ; L\n  | ll2_plus2' : forall B M F G L, Permutation L ((AOr F G)::M) ->\n      |-- B ; G::M -> |-- B ; L    \n  | ll2_with' : forall B M F G L, Permutation L ((AAnd F G)::M) ->\n      |-- B ; F :: M ->\n      |-- B ; G :: M -> |-- B ; L      \n  (* multiplicatives *)  \n  | ll2_bot' : forall B M L, Permutation L (Bot :: M) ->\n      |-- B ; M -> |-- B ; L\n  | ll2_par' : forall B M F G L, Permutation L ((MOr F G) :: M) ->\n      |-- B ; F::G::M -> |-- B ; L  \n  | ll2_tensor' : forall B M N F G L, Permutation L ((MAnd F G)::(M ++ N)) ->\n                                        |-- B ; F::M ->\n                                        |-- B ; G::N ->\n                                        |-- B ; L       \n  (* exponentials *) \n  | ll2_quest' : forall B M F L, Permutation L ((Quest F) :: M) ->\n      |-- F::B ; M -> |-- B ; L      \n  | ll2_bang' : forall B F,\n      |-- B ; [F] -> |-- B ; [Bang F]     \n  (* structurals *)     \n  | ll2_abs' : forall B L F, \n     In F B -> |-- B ; F::L -> |-- B ; L \n  where \"'|--' B ';' L \" := (LL2S B L).\n\n  \n End LL2Sequent .\n\nGlobal Hint Constructors LL2N : core .\nGlobal Hint Constructors LL2S : core. \n \nNotation \"'LL2' n '|--' B ';' L \" := (LL2N n B L)  (at level 80).\nNotation \"'LL2' '|--' B ';' L \" := (LL2S B L)  (at level 80).\n\n", "meta": {"author": "brunofx86", "repo": "LLFramework", "sha": "d12e01875912ef52397d8cd899b7fb0e26977ac5", "save_path": "github-repos/coq/brunofx86-LLFramework", "path": "github-repos/coq/brunofx86-LLFramework/LLFramework-d12e01875912ef52397d8cd899b7fb0e26977ac5/PLL/Sequent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6575759949575354}}
{"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(** * bmx: Boolean matrices, characterisation of reflexive transitive closure *)\n\nRequire Import kleene boolean sups matrix.\nSet Implicit Arguments.\n\nNotation bmx := (mx_ops bool_ops bool_tt).\n\n(** intermediate alternative definition of the star of a Boolean matrix *)\n\nFixpoint bmx_str n: bmx n n -> bmx n n :=\n  match n with\n    | O => fun M => M\n    | S n => fun M =>\n      let b := sub01_mx (n1:=1) (m1:=1) M in\n      let c := sub10_mx (n1:=1) (m1:=1) M in\n      let d := bmx_str (sub11_mx (n1:=1) (m1:=1)  M) in\n      blk_mx 1 (b*d) (d*c) (d+d*c*(b*d))\n  end.\n\nLemma bmx_top_1: top == (1: bmx 1%nat 1%nat).\nProof. intros i j. now setoid_rewrite ord0_unique. Qed.\n\nLemma bmx_str_str n (M: bmx n n): M^* == bmx_str M.\nProof.\n  induction n as [|n IHn]. intro i. elim (ord_0_empty i).\n  change (M^*) with (mx_str _ _ _ M).\n  simpl mx_str. simpl bmx_str. unfold mx_str_build.\n  ra_fold (mx_ops bool_ops bool_tt). rewrite bmx_top_1.\n  now rewrite IHn, dot1x, dotx1. \nQed.\n\n(** reflexive transitive closure as an inductive predicate *)\n\nInductive rt_clot n (M: bmx n n): ord n -> ord n -> Prop :=\n| clot_nil: forall i, rt_clot M i i\n| clot_cons: forall i j k, M i j -> rt_clot M j k -> rt_clot M i k.\n\nLemma clot_app n (M: bmx n n): forall i j k, rt_clot M i j -> rt_clot M j k -> rt_clot M i k.\nProof. induction 1; eauto using clot_cons. Qed.\n\nLemma clot_snoc n (M: bmx n n): forall i j k, rt_clot M i j -> M j k -> rt_clot M i k.\nProof. intros. eapply clot_app. eassumption. eapply clot_cons. eassumption. constructor. Qed.\n\nLemma rt_clot_S_S n (M: bmx (1+n)%nat (1+n)%nat): forall i j,\n  rt_clot (sub11_mx M) i j -> rt_clot M (rshift i) (rshift j).\nProof. induction 1. constructor. eapply clot_cons; eassumption. Qed.\n\n(** characterisation theorem  *)\n\nTheorem bmx_str_clot n (M: bmx n n) i j: M^* i j <-> rt_clot M i j. \nProof.\nsplit.\n- assert (M^* i j == bmx_str M i j). (*MS: FIXME, why is it needed now ? *)\n  apply bmx_str_str. rewrite H. clear H. revert i j. \n  induction n as [|n IH]; intros i' j'. \n   simpl. intro. eapply clot_cons. eassumption. constructor. \n  unfold bmx_str; fold (@bmx_str n). set (M' := sub11_mx (n1:=1) (m1:=1) M). \n  specialize (IH M'). unfold blk_mx, row_mx, col_mx. \n  case ordinal.split_spec; intros i ->; case ordinal.split_spec; intros j -> Hij.\n  + setoid_rewrite ord0_unique. constructor. \n  + setoid_rewrite is_true_sup in Hij. destruct Hij as [k [_ Hk]].\n    apply Bool.andb_true_iff in Hk as [Hik Hkj]. \n    apply IH in Hkj. unfold M' in Hkj. \n    eapply clot_cons. eassumption. now apply rt_clot_S_S. \n  + setoid_rewrite is_true_sup in Hij. destruct Hij as [k [_ Hk]].\n    apply Bool.andb_true_iff in Hk as [Hik Hkj]. \n    apply IH in Hik. unfold M' in Hik. \n    eapply clot_snoc. apply rt_clot_S_S; eassumption. assumption.\n  + setoid_rewrite Bool.orb_true_iff in Hij. destruct Hij as [Hij|Hij].\n     apply IH in Hij. now apply rt_clot_S_S.\n    setoid_rewrite is_true_sup in Hij. destruct Hij as [k [_ Hk]].\n    apply Bool.andb_true_iff in Hk as [Hik Hkj]. \n    setoid_rewrite is_true_sup in Hik. destruct Hik as [i' [_ Hi']].\n    apply Bool.andb_true_iff in Hi' as [Hii' Hi'k]. \n    setoid_rewrite is_true_sup in Hkj. destruct Hkj as [j' [_ Hj']].\n    apply Bool.andb_true_iff in Hj' as [Hkj' Hj'j]. \n    apply IH in Hii'. apply IH in Hj'j. \n    eapply clot_app. apply rt_clot_S_S, Hii'. \n    eapply clot_cons. apply Hi'k. \n    eapply clot_cons. apply Hkj'. \n    apply rt_clot_S_S, Hj'j. \n- induction 1 as [i|i j k Hij Hjk IH]. \n  + pose proof (str_refl (X:=bmx) M i i). simpl in H. \n    setoid_rewrite le_bool_spec in H. apply H. unfold mx_one. now rewrite eqb_refl. \n  + pose proof (str_cons (X:=bmx) M i k). simpl in H. \n    setoid_rewrite le_bool_spec in H. apply H. clear H. \n    unfold mx_dot. rewrite is_true_sup. eexists. split. apply in_seq.  \n    apply Bool.andb_true_iff. split; eassumption. \nQed.\n", "meta": {"author": "coq-contribs", "repo": "relation-algebra", "sha": "2d9066e917400dc3e2b10ad9c12710620d20644b", "save_path": "github-repos/coq/coq-contribs-relation-algebra", "path": "github-repos/coq/coq-contribs-relation-algebra/relation-algebra-2d9066e917400dc3e2b10ad9c12710620d20644b/bmx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6575742319964163}}
{"text": "(* -*- coding: utf-8 -*- *)\n(************************************************************************)\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(** Bit vectors interpreted as integers.\n    Contribution by Jean Duprat (ENS Lyon). *)\n\nRequire Import Bvector.\nRequire Import ZArith.\nRequire Export Zpower.\nRequire Import Omega.\n\n(** The evaluation of boolean vector is done both in binary and\n    two's complement. The computed number belongs to Z.\n    We hence use Omega to perform computations in Z.\n    Moreover, we use functions [2^n] where [n] is a natural number\n    (here the vector length).\n*)\n\n\nSection VALUE_OF_BOOLEAN_VECTORS.\n\n(** Computations are done in the usual convention.\n    The values correspond either to the binary coding (nat) or\n    to the two's complement coding (int).\n    We perform the computation via Horner scheme.\n    The two's complement coding only makes sense on vectors whose\n    size is greater or equal to one (a sign bit should be present).\n*)\n\n  Definition bit_value (b:bool) : Z :=\n    match b with\n      | true => 1%Z\n      | false => 0%Z\n    end.\n\n  Lemma binary_value : forall n:nat, Bvector n -> Z.\n  Proof.\n    simple induction n; intros.\n    exact 0%Z.\n\n    inversion H0.\n    exact (bit_value h + 2 * H H2)%Z.\n  Defined.\n\n  Lemma two_compl_value : forall n:nat, Bvector (S n) -> Z.\n  Proof.\n    simple induction n; intros.\n    inversion H.\n    exact (- bit_value h)%Z.\n\n    inversion H0.\n    exact (bit_value h + 2 * H H2)%Z.\n  Defined.\n\nEnd VALUE_OF_BOOLEAN_VECTORS.\n\nSection ENCODING_VALUE.\n\n(** We compute the binary value via a Horner scheme.\n    Computation stops at the vector length without checks.\n    We define a function Zmod2 similar to Zdiv2 returning the\n    quotient of division z=2q+r with 0<=r<=1.\n    The two's complement value is also computed via a Horner scheme\n    with Zmod2, the parameter is the size minus one.\n*)\n\n  Definition Zmod2 (z:Z) :=\n    match z with\n      | Z0 => 0%Z\n      | Zpos p => match p with\n\t\t    | xI q => Zpos q\n\t\t    | xO q => Zpos q\n\t\t    | xH => 0%Z\n\t\t  end\n      | Zneg p =>\n\tmatch p with\n\t  | xI q => (Zneg q - 1)%Z\n\t  | xO q => Zneg q\n\t  | xH => (-1)%Z\n\tend\n    end.\n\n\n  Lemma Zmod2_twice :\n    forall z:Z, z = (2 * Zmod2 z + bit_value (Zeven.Zodd_bool z))%Z.\n  Proof.\n    destruct z; simpl in |- *.\n    trivial.\n\n    destruct p; simpl in |- *; trivial.\n\n    destruct p; simpl in |- *.\n    destruct p as [p| p| ]; simpl in |- *.\n    rewrite <- (Pdouble_minus_one_o_succ_eq_xI p); trivial.\n\n    trivial.\n\n    trivial.\n\n    trivial.\n\n    trivial.\n  Qed.\n\n  Lemma Z_to_binary : forall n:nat, Z -> Bvector n.\n  Proof.\n    simple induction n; intros.\n    exact Bnil.\n\n    exact (Bcons (Zeven.Zodd_bool H0) n0 (H (Zeven.Zdiv2 H0))).\n  Defined.\n\n  Lemma Z_to_two_compl : forall n:nat, Z -> Bvector (S n).\n  Proof.\n    simple induction n; intros.\n    exact (Bcons (Zeven.Zodd_bool H) 0 Bnil).\n\n    exact (Bcons (Zeven.Zodd_bool H0) (S n0) (H (Zmod2 H0))).\n  Defined.\n\nEnd ENCODING_VALUE.\n\nSection Z_BRIC_A_BRAC.\n\n  (** Some auxiliary lemmas used in the next section. Large use of ZArith.\n      Deserve to be properly rewritten.\n  *)\n\n  Lemma binary_value_Sn :\n    forall (n:nat) (b:bool) (bv:Bvector n),\n      binary_value (S n) ( b :: bv) =\n      (bit_value b + 2 * binary_value n bv)%Z.\n  Proof.\n    intros; auto.\n  Qed.\n\n  Lemma Z_to_binary_Sn :\n    forall (n:nat) (b:bool) (z:Z),\n      (z >= 0)%Z ->\n      Z_to_binary (S n) (bit_value b + 2 * z) = Bcons b n (Z_to_binary n z).\n  Proof.\n    destruct b; destruct z; simpl in |- *; auto.\n    intro H; elim H; trivial.\n  Qed.\n\n  Lemma binary_value_pos :\n    forall (n:nat) (bv:Bvector n), (binary_value n bv >= 0)%Z.\n  Proof.\n    induction bv as [| a n v IHbv]; simpl in |- *.\n    omega.\n\n    destruct a; destruct (binary_value n v); simpl in |- *; auto.\n    auto with zarith.\n  Qed.\n\n  Lemma two_compl_value_Sn :\n    forall (n:nat) (bv:Bvector (S n)) (b:bool),\n      two_compl_value (S n) (Bcons b (S n) bv) =\n      (bit_value b + 2 * two_compl_value n bv)%Z.\n  Proof.\n    intros; auto.\n  Qed.\n\n  Lemma Z_to_two_compl_Sn :\n    forall (n:nat) (b:bool) (z:Z),\n      Z_to_two_compl (S n) (bit_value b + 2 * z) =\n      Bcons b (S n) (Z_to_two_compl n z).\n  Proof.\n    destruct b; destruct z as [| p| p]; auto.\n    destruct p as [p| p| ]; auto.\n    destruct p as [p| p| ]; simpl in |- *; auto.\n    intros; rewrite (Psucc_o_double_minus_one_eq_xO p); trivial.\n  Qed.\n\n  Lemma Z_to_binary_Sn_z :\n    forall (n:nat) (z:Z),\n      Z_to_binary (S n) z =\n      Bcons (Zeven.Zodd_bool z) n (Z_to_binary n (Zeven.Zdiv2 z)).\n  Proof.\n    intros; auto.\n  Qed.\n\n  Lemma Z_div2_value :\n    forall z:Z,\n      (z >= 0)%Z -> (bit_value (Zeven.Zodd_bool z) + 2 * Zeven.Zdiv2 z)%Z = z.\n  Proof.\n    destruct z as [| p| p]; auto.\n    destruct p; auto.\n    intro H; elim H; trivial.\n  Qed.\n\n  Lemma Pdiv2 : forall z:Z, (z >= 0)%Z -> (Zeven.Zdiv2 z >= 0)%Z.\n  Proof.\n    destruct z as [| p| p].\n    auto.\n\n    destruct p; auto.\n    simpl in |- *; intros; omega.\n\n    intro H; elim H; trivial.\n  Qed.\n\n  Lemma Zdiv2_two_power_nat :\n    forall (z:Z) (n:nat),\n      (z >= 0)%Z ->\n      (z < two_power_nat (S n))%Z -> (Zeven.Zdiv2 z < two_power_nat n)%Z.\n  Proof.\n    intros.\n    cut (2 * Zeven.Zdiv2 z < 2 * two_power_nat n)%Z; intros.\n    omega.\n\n    rewrite <- two_power_nat_S.\n    destruct (Zeven.Zeven_odd_dec z); intros.\n    rewrite <- Zeven.Zeven_div2; auto.\n\n    generalize (Zeven.Zodd_div2 z z0); omega.\n  Qed.\n\n  Lemma Z_to_two_compl_Sn_z :\n    forall (n:nat) (z:Z),\n      Z_to_two_compl (S n) z =\n      Bcons (Zeven.Zodd_bool z) (S n) (Z_to_two_compl n (Zmod2 z)).\n  Proof.\n    intros; auto.\n  Qed.\n\n  Lemma Zeven_bit_value :\n    forall z:Z, Zeven.Zeven z -> bit_value (Zeven.Zodd_bool z) = 0%Z.\n  Proof.\n    destruct z; unfold bit_value in |- *; auto.\n    destruct p; tauto || (intro H; elim H).\n    destruct p; tauto || (intro H; elim H).\n  Qed.\n\n  Lemma Zodd_bit_value :\n    forall z:Z, Zeven.Zodd z -> bit_value (Zeven.Zodd_bool z) = 1%Z.\n  Proof.\n    destruct z; unfold bit_value in |- *; auto.\n    intros; elim H.\n    destruct p; tauto || (intros; elim H).\n    destruct p; tauto || (intros; elim H).\n  Qed.\n\n  Lemma Zge_minus_two_power_nat_S :\n    forall (n:nat) (z:Z),\n      (z >= - two_power_nat (S n))%Z -> (Zmod2 z >= - two_power_nat n)%Z.\n  Proof.\n    intros n z; rewrite (two_power_nat_S n).\n    generalize (Zmod2_twice z).\n    destruct (Zeven.Zeven_odd_dec z) as [H| H].\n    rewrite (Zeven_bit_value z H); intros; omega.\n\n    rewrite (Zodd_bit_value z H); intros; omega.\n  Qed.\n\n  Lemma Zlt_two_power_nat_S :\n    forall (n:nat) (z:Z),\n      (z < two_power_nat (S n))%Z -> (Zmod2 z < two_power_nat n)%Z.\n  Proof.\n    intros n z; rewrite (two_power_nat_S n).\n    generalize (Zmod2_twice z).\n    destruct (Zeven.Zeven_odd_dec z) as [H| H].\n    rewrite (Zeven_bit_value z H); intros; omega.\n\n    rewrite (Zodd_bit_value z H); intros; omega.\n  Qed.\n\nEnd Z_BRIC_A_BRAC.\n\nSection COHERENT_VALUE.\n\n(** We check that the functions are reciprocal on the definition interval.\n    This uses earlier library lemmas.\n*)\n\n  Lemma binary_to_Z_to_binary :\n    forall (n:nat) (bv:Bvector n), Z_to_binary n (binary_value n bv) = bv.\n  Proof.\n    induction bv as [| a n bv IHbv].\n    auto.\n\n    rewrite binary_value_Sn.\n    rewrite Z_to_binary_Sn.\n    rewrite IHbv; trivial.\n\n    apply binary_value_pos.\n  Qed.\n\n  Lemma two_compl_to_Z_to_two_compl :\n    forall (n:nat) (bv:Bvector n) (b:bool),\n      Z_to_two_compl n (two_compl_value n (Bcons b n bv)) = Bcons b n bv.\n  Proof.\n    induction bv as [| a n bv IHbv]; intro b.\n    destruct b; auto.\n\n    rewrite two_compl_value_Sn.\n    rewrite Z_to_two_compl_Sn.\n    rewrite IHbv; trivial.\n  Qed.\n\n  Lemma Z_to_binary_to_Z :\n    forall (n:nat) (z:Z),\n      (z >= 0)%Z ->\n      (z < two_power_nat n)%Z -> binary_value n (Z_to_binary n z) = z.\n  Proof.\n    induction n as [| n IHn].\n    unfold two_power_nat, shift_nat in |- *; simpl in |- *; intros; omega.\n\n    intros; rewrite Z_to_binary_Sn_z.\n    rewrite binary_value_Sn.\n    rewrite IHn.\n    apply Z_div2_value; auto.\n\n    apply Pdiv2; trivial.\n\n    apply Zdiv2_two_power_nat; trivial.\n  Qed.\n\n  Lemma Z_to_two_compl_to_Z :\n    forall (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.\n  Proof.\n    induction n as [| n IHn].\n    unfold two_power_nat, shift_nat in |- *; simpl in |- *; intros.\n    assert (z = (-1)%Z \\/ z = 0%Z). omega.\n    intuition; subst z; trivial.\n\n    intros; rewrite Z_to_two_compl_Sn_z.\n    rewrite two_compl_value_Sn.\n    rewrite IHn.\n    generalize (Zmod2_twice z); omega.\n\n    apply Zge_minus_two_power_nat_S; auto.\n\n    apply Zlt_two_power_nat_S; auto.\n  Qed.\n\nEnd COHERENT_VALUE.\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/Zdigits.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6575742232924673}}
{"text": "Require Export Coq.Init.Nat.\nDefinition FILL_IN_HERE {T: Type} : T.  Admitted.\n\nInductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\nArguments nil {X}.\nArguments cons {X} _ _.\n\nFixpoint app {X : Type} (l1 l2 : list X)\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\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n\nDefinition natlist := list nat.\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\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 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", "meta": {"author": "snu-sf-class", "repo": "sf202002", "sha": "dcc8ab303e7bcccebff51ef00929c91a26e45c4f", "save_path": "github-repos/coq/snu-sf-class-sf202002", "path": "github-repos/coq/snu-sf-class-sf202002/sf202002-dcc8ab303e7bcccebff51ef00929c91a26e45c4f/2-lists_poly/D.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.657550955521825}}
{"text": "Lemma s : 3*3=9.\nProof.\n\tapply eq_refl.\nQed.\n(* (a) *)\nInductive aexpr (N:Type)  := \n| cst : N -> aexpr N\n| var : nat -> aexpr N\n| add : aexpr N -> aexpr N -> aexpr N\n.\n(* (b) *)\nCheck (cst).\n\n(* (c) *)\nPrint aexpr_ind.\n\nFixpoint aexpr_iter (N : Type) (P : Type)\n           (Pcst : N -> P)\n           (Pvar : nat -> P)\n           (Padd : aexpr N -> P -> aexpr N -> P -> P)\n           (e : aexpr N) : P :=\n  match e with\n    | cst _ n => Pcst n\n    | var _ n => Pvar n\n    | add _ x y => Padd x (aexpr_iter N P Pcst Pvar Padd x)\n                      y (aexpr_iter N P Pcst Pvar Padd y)\n  end.\n\nInductive iff (A B:Prop) : Prop :=\n|iff_intro : (A -> B) -> (B -> A) -> iff A B\n.\n\nDefinition iff_rd := \nfun (A B:Prop) (P: iff A B -> Type) \n (f: forall (a : A -> B) (b : B -> A), P(iff_intro A B a b))\n (i: iff A B) => \n match i  with \n | iff_intro _ _ x x0 => f x x0\n end\n \n.\n\nPrint iff_ind.\nPrint aexpr_rect.\n\nDefinition iff_l (A B:Prop) (e: iff A B) :=  \n  iff_rd A B (fun _ => A -> B) (fun l _ => l) e.\n\n  Definition iff_out (A B : Prop) (e : iff A B) : A -> B :=\n  iff_ind A B (A -> B) (fun l _ => l) e.\nParameter (A B:Prop).\nCheck (iff_out B  (iff A B )).\nCheck (iff_l B  (iff A B )).", "meta": {"author": "sebastienPatte", "repo": "Coq", "sha": "1c031f13db8d7101ca356c23b36d560c0a194de1", "save_path": "github-repos/coq/sebastienPatte-Coq", "path": "github-repos/coq/sebastienPatte-Coq/Coq-1c031f13db8d7101ca356c23b36d560c0a194de1/PA/2021/exam_2018.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443252, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6575509511576717}}
{"text": "\nRequire Import FiatFormal.Data.List.Base.\nRequire Import FiatFormal.Data.Nat.\nRequire Import FiatFormal.Tactics.\n\n\n(* Insert a new element at a place in the list.\n   All the elements above that place are shifted up one.\n   The resulting list is one element larger. *)\nFixpoint insert {A: Type} (ix: nat) (x: A) (xs: list A) : list A :=\n match ix, xs with\n | _,     nil      => x :: nil\n | S ix', y :: xs' => y :: (insert ix' x xs')\n | O    , xs'      => x :: xs'\n end.\n\n(* When using the 'simpl' tactic we don't want to do a reduction\n   that will leave the inner match expression in head position. *)\nArguments insert A ix x xs : simpl nomatch.\n\n\n\n(********************************************************************)\n(** Lemmas: insert *)\n\nLemma insert_rewind\n :  forall {A} ix t1 t2 (xx: list A)\n ,  insert ix t2 xx :> t1 = insert (S ix) t2 (xx :> t1).\nProof. auto. Qed.\n\n\nLemma insert_zero\n :  forall {A} x (xs : list A)\n ,  insert 0 x xs = xs :> x.\nProof.\n rip. destruct xs; auto.\nQed.\nHint Resolve insert_zero.\n\n\n(* If we insert an element at a particular point in a list,\n   then we can still get the elements above that point\n   provided we increment their original indices. *)\nLemma get_insert_above\n :  forall {A: Type} n ix (xx: list A) x1 x2\n ,  n >= ix\n -> get n xx                    = Some x1\n -> get (S n) (insert ix x2 xx) = Some x1.\nProof.\n intros. gen n xx.\n induction ix; intros.\n  destruct xx.\n   false.\n   destruct n; auto.\n  destruct xx.\n   false.\n   destruct n.\n    false. omega.\n    simpl in H0. simpl. apply IHix.\n     omega.\n     auto.\nQed.\nHint Resolve get_insert_above.\n\n\n(* If we insert an element at a particular point in a list,\n   then we can still get the elements below that point\n   using their original indices. *)\nLemma get_insert_below\n :  forall {A: Type} n ix (xx: list A) x1 x2\n ,  n < ix\n -> get n xx                = Some x1\n -> get n (insert ix x2 xx) = Some x1.\nProof.\n intros. gen n xx.\n induction ix; intros.\n  destruct xx.\n   false.\n   destruct n.\n    false. omega.\n    false. omega.\n  destruct xx.\n   false.\n   destruct n.\n    simpl in H0. auto.\n    simpl in H0. simpl. apply IHix. omega. auto.\nQed.\nHint Resolve get_insert_below.\n\n\n(* Inserting a new element into a list then applying a function to\n   all elements is the same as applying the function to all the\n   original elements, then inserting the new one with the function\n   already applied. *)\nLemma map_insert\n : forall {A B: Type} (f: A -> B) ix x (xs: list A)\n , map f (insert ix x xs)\n = insert ix (f x) (map f xs).\nProof.\n intros. gen ix x.\n induction xs; intros.\n  simpl. destruct ix; auto.\n  simpl. destruct ix; auto.\n   rewrite <- insert_rewind. simpl.\n   rewrite IHxs. auto.\nQed.\n\n\nLemma insert_app\n : forall {A : Type} ix (x: A) xs ys\n , insert ix x xs >< ys = insert (ix + length ys) x (xs >< ys).\nProof.\n intros.\n induction ys.\n  simpl. norm_nat.  auto.\n  simpl. rewrite IHys.\n   rewrite insert_rewind.\n   assert (S (ix + length ys) = ix + S (length ys)). auto.\n   rewrite H. auto.\nQed.\n", "meta": {"author": "paulkrog", "repo": "formalized-fiat", "sha": "8f9022980c038f500aeea9b2f85062f0bfc33eb6", "save_path": "github-repos/coq/paulkrog-formalized-fiat", "path": "github-repos/coq/paulkrog-formalized-fiat/formalized-fiat-8f9022980c038f500aeea9b2f85062f0bfc33eb6/FiatFormal/Data/List/Insert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6575509494838334}}
{"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(* ************************************************************************* *)\n(*                                                                           *)\n(*          Buchberger : ordering: lexi and total                            *)\n(*                                                                           *)\n(*          Laurent Thery \t                                             *)\n(*                                                                           *)\n(* ************************************************************************* *)\n\nFrom Coq Require Import Arith Compare_dec.\nFrom Buchberger Require Import Monomials LetP.\n\nSet Default Proof Using \"Type\".\n\nSection lexi_order.\n\nInductive orderc : forall n : nat, mon n -> mon n -> Prop :=\n  | lo1 :\n      forall (n a b : nat) (p : mon n),\n      b < a -> orderc (S n) (c_n n a p) (c_n n b p)\n  | lo2 :\n      forall (n a b : nat) (p q : mon n),\n      orderc n p q -> orderc (S n) (c_n n a p) (c_n n b q).\n\nLocal Hint Resolve lo1 lo2 : core.\n\nDefinition orderc_dec :\n forall (n : nat) (a b : mon n), {orderc n a b} + {orderc n b a} + {a = b}.\nintros n a; elim a; auto.\nintro b.\nrewrite <- (mon_0 b); auto.\nintros d n0 m H' b; try assumption.\nrewrite <- (proj_ok d b).\ncase (H' (pmon2 (S d) b)).\nintro H'0; case H'0.\nintro H'1.\nleft; left; auto.\nintro H'1; left; right; auto.\nintro H'0.\nelim (lt_eq_lt_dec n0 (pmon1 (S d) b)); [ intro H'1; elim H'1 | idtac ];\n intro H'2; auto.\nleft; right; auto.\nrewrite H'0; auto.\nright; rewrite H'0; rewrite H'2; auto.\nleft; left; rewrite H'0; auto.\nDefined.\n\nDefinition degc : forall n : nat, mon n -> nat.\nintros n H'; elim H'.\nexact 0.\nintros d n1 M n2; exact (n1 + n2).\nDefined.\n\nInductive total_orderc : forall n : nat, mon n -> mon n -> Prop :=\n  | total_orderc0 :\n      forall (n : nat) (p q : mon n),\n      degc n p < degc n q -> total_orderc n p q\n  | total_orderc1 :\n      forall (n : nat) (p q : mon n),\n      degc n p = degc n q -> orderc n p q -> total_orderc n p q.\n\nLocal Hint Resolve total_orderc0 total_orderc1 : core.\n\nDefinition total_orderc_dec :\n forall (n : nat) (a b : mon n),\n {total_orderc n a b} + {total_orderc n b a} + {a = b}.\nintros n a b.\napply LetP with (A := nat) (h := degc n a).\nintros u H'; apply LetP with (A := nat) (h := degc n b).\nintros u0 H'0.\ncase (le_lt_dec u u0); auto.\nintro H'1; case (le_lt_eq_dec u u0); auto.\nrewrite H'0; rewrite H'; auto.\nrewrite H'0; rewrite H'; intro H'2; case (orderc_dec n a b); auto.\nintro H'3; case H'3; auto.\nrewrite H'0; rewrite H'; auto.\nDefined.\n\nEnd lexi_order.\n", "meta": {"author": "coq-community", "repo": "buchberger", "sha": "7625647c300bb5f155f6bf40b69c232f64819a4f", "save_path": "github-repos/coq/coq-community-buchberger", "path": "github-repos/coq/coq-community-buchberger/buchberger-7625647c300bb5f155f6bf40b69c232f64819a4f/theories/LexiOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6575509467935182}}
{"text": "Require Import ct00.\n(* ct00 contains the original conjecture. *)\n\nRequire Import ct16.\n(* ct16 contains all necessary divide-and-conquer tactics *)\n\nRequire Import ct02 ct06 ct14 ct15 ct17.\n(* ct02 ct06 ct14 contains the following lemmas that are solved by the automated\n * system, CoqHammer:\n * - sort_prog_base\n * - sort_prog_one\n * - HdRel_merge_snd_cons\n * - sorted_merge_cons\n * - HdRel_merge_fst_cons\n * - permutation_merge_concat\n * - permutation_split\n *)\n\nFixpoint merge l1 l2 :=\n  let fix merge_aux l2 :=\n  match l1, l2 with\n  | [], _ => l2\n  | _, [] => l1\n  | a1::l1', a2::l2' =>\n      if (le_lt_dec a1 a2) then a1 :: merge l1' l2 else a2 :: merge_aux l2'\n  end\n  in merge_aux l2.\n\nLemma merge_sorted : forall (l1 l2 : list nat),\n  sorted l1 -> sorted l2 -> sorted (merge l1 l2).\nProof.\ninduction l1; induction l2; intros; simpl; auto.\ndestruct (le_lt_dec a a0).\n- constructor. apply IHl1; inversion H; auto. apply HdRel_merge_snd_cons; auto.\n- constructor. eapply sorted_merge_cons; eassumption. \n  apply HdRel_merge_fst_cons; auto.\nDefined.\n\nLemma merge_permutation : forall (l l1 l2 : list nat),\n  permutation l1 (fst (split nat l)) -> permutation l2 (snd (split nat l)) \n  -> permutation (merge l1 l2) l.\nProof.\nintros; rewrite permutation_merge_concat, H, H0; apply permutation_split.\nDefined.\n\nLemma sort_prog_split : forall (ls l' l'0: list nat),\n  sorted l'0 -> permutation l'0 (fst (split nat ls))\n  -> sorted l' -> permutation l' (snd (split nat ls))\n  -> {l'1 : list nat | sorted l'1 /\\ permutation l'1 ls}.\nProof.\nintros; exists (merge l'0 l'); split.\n  + apply merge_sorted; eassumption.\n  + apply merge_permutation; eassumption.\nDefined.\n\nLemma msort_prog : forall (l : list nat), \n  {l' : list nat | sorted l' /\\ permutation l' l}.\nProof.\ndiv_conq_split. \n- apply sort_prog_base.\n- apply sort_prog_one.\n- intros; destruct H; destruct a; destruct H0; destruct a; \n  eapply sort_prog_split. exact H. eassumption. exact H0. eassumption.\nDefined.\n\n(*---------------------------------Extraction---------------------------------*)\n\nRequire Extraction.\nRequire Import ExtrOcamlBasic.\nRequire Import ExtrOcamlNatInt.\n(* Suppose all the packages above are embedded in some trans *)\n\nExtraction Language OCaml.\nSet Extraction AccessOpaque.\n\nExtraction \"extraction/merge.ml\" merge.\nExtraction \"extraction/msort.ml\" msort_prog.\n\n(*----------------------------------------------------------------------------*)", "meta": {"author": "jinxinglim", "repo": "coq-chain", "sha": "e237c6b5f797f2af43237b68ff599d6cc0a8d60e", "save_path": "github-repos/coq/jinxinglim-coq-chain", "path": "github-repos/coq/jinxinglim-coq-chain/coq-chain-e237c6b5f797f2af43237b68ff599d6cc0a8d60e/contributions/ct18.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6575509343888531}}
{"text": "(* This file is generated by Why3's Coq driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import ZArith.\nRequire Import Rbase.\nParameter bag : forall (a:Type), Type.\n\nParameter nb_occ: forall (a:Type), a -> (bag a)  -> Z.\n\nImplicit Arguments nb_occ.\n\nAxiom occ_non_negative : forall (a:Type), forall (b:(bag a)) (x:a),\n  (0%Z <= (nb_occ x b))%Z.\n\nDefinition eq_bag (a:Type)(a1:(bag a)) (b:(bag a)): Prop := forall (x:a),\n  ((nb_occ x a1) = (nb_occ x b)).\nImplicit Arguments eq_bag.\n\nAxiom bag_extensionality : forall (a:Type), forall (a1:(bag a)) (b:(bag a)),\n  (eq_bag a1 b) -> (a1 = b).\n\nParameter empty_bag: forall (a:Type),  (bag a).\n\nSet Contextual Implicit.\nImplicit Arguments empty_bag.\nUnset Contextual Implicit.\n\nAxiom occ_empty : forall (a:Type), forall (x:a), ((nb_occ x (empty_bag:(bag\n  a))) = 0%Z).\n\nAxiom is_empty : forall (a:Type), forall (b:(bag a)), (forall (x:a),\n  ((nb_occ x b) = 0%Z)) -> (b = (empty_bag:(bag a))).\n\nParameter singleton: forall (a:Type), a  -> (bag a).\n\nImplicit Arguments singleton.\n\nAxiom occ_singleton_eq : forall (a:Type), forall (x:a) (y:a), (x = y) ->\n  ((nb_occ y (singleton x)) = 1%Z).\n\nAxiom occ_singleton_neq : forall (a:Type), forall (x:a) (y:a), (~ (x = y)) ->\n  ((nb_occ y (singleton x)) = 0%Z).\n\nParameter union: forall (a:Type), (bag a) -> (bag a)  -> (bag a).\n\nImplicit Arguments union.\n\nAxiom occ_union : forall (a:Type), forall (x:a) (a1:(bag a)) (b:(bag a)),\n  ((nb_occ x (union a1 b)) = ((nb_occ x a1) + (nb_occ x b))%Z).\n\nAxiom Union_comm : forall (a:Type), forall (a1:(bag a)) (b:(bag a)),\n  ((union a1 b) = (union b a1)).\n\nAxiom Union_identity : forall (a:Type), forall (a1:(bag a)), ((union a1\n  (empty_bag:(bag a))) = a1).\n\nAxiom Union_assoc : forall (a:Type), forall (a1:(bag a)) (b:(bag a)) (c:(bag\n  a)), ((union a1 (union b c)) = (union (union a1 b) c)).\n\n(* YOU MAY EDIT THE CONTEXT BELOW *)\n\n(* DO NOT EDIT BELOW *)\n\nTheorem bag_simpl : forall (a:Type), forall (a1:(bag a)) (b:(bag a)) (c:(bag\n  a)), ((union a1 b) = (union c b)) -> (a1 = c).\n(* YOU MAY EDIT THE PROOF BELOW *)\nintros X a b c H_union.\napply bag_extensionality; intro x.\nassert (h: (nb_occ x (union a b)) =  (nb_occ x (union c b)))\n  by (rewrite H_union; auto).\ndo 2 rewrite occ_union in h; auto with zarith.\nQed.\n(* DO NOT EDIT BELOW *)\n\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/tests/theory-sessions/bag/bag_Bag_bag_simpl_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6575509243153895}}
{"text": "Require Import SetoidCat Algebra.SetoidCat.SetoidUtils Algebra.Functor Algebra.Monoid PairUtils Algebra.Utils UnitUtils.\n\nRequire Import SetoidClass.\n\nSection Applicative.\n\n  Context\n    {t : forall A, Setoid A -> Type}\n    {tS : forall A (AS : Setoid A), Setoid (t A AS)}\n    {func : @Functor t tS}.\n\n  Definition left_unitor {A} {AS : Setoid A} : unitS ~*~ AS ~> AS := sndS.\n\n  Definition right_unitor {A} {AS : Setoid A} : AS ~*~ unitS ~> AS := fstS. \n  \n  Definition associator {A B C} {AS : Setoid A} {BS : Setoid B} {CS : Setoid C} : (AS ~*~ BS) ~*~ CS ~> AS ~*~ (BS ~*~ CS) := (fstS ∘ fstS) &&& ((sndS ∘ fstS) &&& sndS).\n                              \n  Class Applicative :=\n    {\n      unitA :  t unit _;\n      prod {A B} {AS : Setoid A} {BS : Setoid B} : tS _ AS ~> tS _ BS ~~> tS _ (AS ~*~ BS);\n      \n      left_unit_applicative :\n        forall {A} {AS : Setoid A} (a : t A _),\n          left_unitor <$> (prod  @ unitA @ a) == a;\n      right_unit_applicative :\n        forall {A} {AS : Setoid A} (a : t A _),\n          right_unitor <$> (prod  @ a @ unitA) == a;\n      associativity_applicative:\n        forall {A B C} {AS : Setoid A} {BS : Setoid B} {CS : Setoid C}\n               (a : t A _) (b : t B _) (c : t C _) ,\n          associator <$> (prod  @ (prod  @ a @ b) @ c) == prod  @ a @ (prod  @ b @ c);\n      naturality_prod:\n        forall {A B C D} {AS : Setoid A} {BS : Setoid B} {CS : Setoid C} {DS : Setoid D}\n               (f : AS ~> BS) (g : CS ~> DS) (a : t A _) (c : t C _),\n          prod  @ (f <$> a) @ (g <$> c) == (f *** g) <$> (prod  @ a @ c)\n    }.\n\n  Context\n    {app : Applicative}.\n\n  Definition pure  {A} {AS : Setoid A} : AS ~> tS _ AS := (flipS @ fmap @ unitA) ∘ constS unitS.\n\n  Definition ap {A B} {AS : Setoid A} {BS : Setoid B} : tS _ (AS ~~> BS) ~> tS _ AS ~~> tS _ BS :=\n    comp2S @ prod @ (fmap @ (uncurryS @ evalS)).\n\n  Definition produ {A B} {AS : Setoid A} {BS : Setoid B} : tS _ AS ~*~ tS _ BS ~> tS _ (AS ~*~ BS) := uncurryS @ prod  .\n\n\n  \nEnd Applicative.\n\n\nNotation \"a ** b\" := (prod @ a @ b) (at level 49, left associativity).\nNotation \"a <*> b\" := (ap @ a @ b) (at level 49, left associativity).\n\n", "meta": {"author": "xu-hao", "repo": "CertifiedQueryArrow", "sha": "8db512e0ebea8011b0468d83c9066e4a94d8d1c4", "save_path": "github-repos/coq/xu-hao-CertifiedQueryArrow", "path": "github-repos/coq/xu-hao-CertifiedQueryArrow/CertifiedQueryArrow-8db512e0ebea8011b0468d83c9066e4a94d8d1c4/Algebra/Applicative.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539553, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6574427010177946}}
{"text": "Require Import List ZArith.\nImport ListNotations.\n\nRequire Import formal_av1.basic_types.\n\nModule bit_index_order.\n\n  Definition t := byte.bit_index.\n\n  Inductive is_next (a b : t) : Prop :=\n  | is_index_intro :\n    proj1_sig (Fin.to_nat a) = S (proj1_sig (Fin.to_nat b)) ->\n      is_next a b.\n\n  Inductive is_previous (a b : t) : Prop :=\n    | is_previous_intro :\n      is_next b a -> is_previous a b.\n\n  Inductive is_last (a : t) : Prop :=\n    | is_last_intro :\n      ~(exists b, is_next a b) -> is_last a.\n\n  Inductive is_first (a : t) : Prop :=\n    | is_first_intro :\n      ~(exists b, is_previous a b) -> is_first a.\n\nEnd bit_index_order.\n\nModule bitstream_position.\n\n  Record t := t_intro {\n    byte_index : nat;\n    bit_index : byte.bit_index;\n  }.\n\n  (* Bitstream positions go from most significant bit to least significant bit. *)\n\n  Inductive is_next : t -> t -> Prop :=\n    | is_next_same_byte :\n      forall bit_pos_a bit_pos_b,\n        bit_index_order.is_previous bit_pos_a bit_pos_b ->\n      forall byte_pos, is_next\n        (t_intro byte_pos bit_pos_a)\n        (t_intro byte_pos bit_pos_b)\n    | is_next_next_byte :\n      forall bit_pos_a, bit_index_order.is_first bit_pos_a ->\n      forall bit_pos_b, bit_index_order.is_last bit_pos_b ->\n      forall byte_pos, is_next\n        (t_intro byte_pos bit_pos_a)\n        (t_intro (S byte_pos) bit_pos_b).\n\n  Inductive is_previous (bit_pos_a bit_pos_b : t) : Prop :=\n    | is_previous_intro :\n      is_next bit_pos_b bit_pos_a ->\n      is_previous bit_pos_a bit_pos_b.\n\nEnd bitstream_position.\n\nInductive bit_in_byte_relation\n    (bt : byte.t)\n    (index : byte.bit_index)\n    (b : bit)\n    : Prop :=\n  | bit_in_byte_intro :\n    Vector.nth bt index = b -> bit_in_byte_relation bt index b.\n\nInductive byte_in_obu_relation :\n    open_bitstream_unit -> nat -> byte.t -> Prop :=\n  byte_in_bitstream_relation_intro:\n    forall obu bp b,\n      nth_error obu bp = Some b ->\n        byte_in_obu_relation obu bp b.\n\nInductive obu_at_relation :\n    open_bitstream_unit -> bitstream_position.t -> bit -> Prop :=\n  obu_at_relation_intro :\n    forall obu byte_index bit_index byte value,\n      byte_in_obu_relation obu byte_index byte ->\n      bit_in_byte_relation byte bit_index value ->\n      obu_at_relation obu (bitstream_position.t_intro byte_index bit_index)\n        value.\n\nInductive read_bit_relation\n    (obu : open_bitstream_unit)\n    (bp_0 : bitstream_position.t)\n    (b : bit)\n    (bp_1 : bitstream_position.t)\n    : Prop :=\n  | read_bit_relation_intro :\n    obu_at_relation obu bp_0 b ->\n    bitstream_position.is_next bp_0 bp_1 ->\n    read_bit_relation obu bp_0 b bp_1.\n\nInductive read_bit_list_relation\n    (obu : open_bitstream_unit)\n    (bp_a : bitstream_position.t)\n    (bp_b : bitstream_position.t)\n    : list bit -> Prop :=\n  | read_bit_list_relation_first :\n    forall (b : bit),\n    read_bit_relation obu bp_a b bp_b ->\n    read_bit_list_relation obu bp_a bp_b [b]\n  | read_bit_list_relation_next :\n    forall (b : bit) (l : list bit) (bp_a_next : bitstream_position.t),\n    read_bit_relation obu bp_a b bp_a_next ->\n    read_bit_list_relation obu bp_a_next bp_b l ->\n    read_bit_list_relation obu bp_a bp_b (b :: l).", "meta": {"author": "domin144", "repo": "formal_av1", "sha": "595de6587bff6ffd6f8b9089f715dcab0c62ac5a", "save_path": "github-repos/coq/domin144-formal_av1", "path": "github-repos/coq/domin144-formal_av1/formal_av1-595de6587bff6ffd6f8b9089f715dcab0c62ac5a/entropy/bitstream_position.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320035, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6574426965272278}}
{"text": "Require Import Omega.\nRequire Import Imp.\n\n(* ((Evaluation Function)) *)\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    | 0    => None\n    | S i' =>\n    match c with\n      | CSkip     => Some st\n      | CAss  x a => Some (update st x (aeval st a))\n      | CSeq  c d => LETOPT st' <== ceval_step st c i' IN ceval_step st' d i'\n      | CIf b t e => if beval st b then ceval_step st t i'\n                                     else ceval_step st e i'\n      | CWhile b k => if beval st b\n                      then LETOPT st' <== ceval_step st k i'\n                           IN 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\n(* Exercise: 2 stars (pup_to_n) *)\n\nExample pup_to_n_1 :\n  test_ceval (update empty_state X 5) pup_to_n\n  = Some (0, 15, 0).\nProof. reflexivity. Qed.\n\n(* END pup_to_n. *)\n\n(* Exercise: 2 stars, optional (peven) *)\n\nDefinition peven : com :=\n  Z ::= ANum 1;;\n  WHILE BLe (ANum 1) (AId X) DO\n    X ::= AMinus (AId X) (ANum 1);;\n    IFB BEq (AId Z) (ANum 1) THEN Z ::= ANum 0 ELSE Z ::= ANum 1 FI\n  END\n.\n\nExample peven_test :\n  test_ceval (update empty_state X 5) peven\n  = Some (0, 0, 0).\nProof. reflexivity. Qed.\n\nExample peven_test2 :\n  test_ceval (update empty_state X 10) peven\n  = Some (0, 0, 1).\nProof. reflexivity. Qed.\n\n(* END peven. *)\n\nTheorem ceval_step__ceval : forall c st st',\n  (exists i, ceval_step st c i = Some st') ->\n  c / st ⇓ st'.\nProof.\n  intros.\n  inversion H as [i E].\n  clear H.\n  generalize dependent st.\n  generalize dependent st'.\n  generalize dependent c.\n  induction i; intros.\n  (* Case \"contradiction\" *)\n  - inversion E.\n  (* Case \"at least one level of execution was performed\" *)\n  - destruct c; inversion E; subst.\n      constructor.\n      constructor.\n      (* SCase \"c ;; d\" *)\n      + destruct (ceval_step st c1 i) eqn: H.\n        (* SSCase \"exists state `s`\" *)\n        * apply E_Seq with (st' := s). apply IHi. apply H. apply IHi. apply H0.\n        (* SSCase \"c1 did not execute\" *)\n        * inversion H0.\n      (* SCase \"IFB\" *)\n      + destruct (beval st b) eqn: H; apply IHi in H0;\n        [apply E_IfTrue | apply E_IfFalse]; try apply H; try apply H0.\n      (* SCase \"WHILE\" *)\n      + destruct (beval st b) eqn: H.\n        (* SSCase \"going on with the loop\" *)\n        * destruct (ceval_step st c i) eqn: I.\n          (* SSSCase \"current iteration returned a result\" *)\n          { apply E_WhileLoop with (st' := s). apply H.\n            apply (IHi _ _ _ I).\n            apply (IHi _ _ _ H0). }\n          (* SSSCase \"current iteration did not return\" *)\n          { inversion H0. }\n        (* SSCase \"leaving the loop\" *)\n        * inversion H0; subst.\n          apply E_WhileEnd.\n          apply H.\nQed.\n\n(* Exercise: 4 stars (ceval_step__ceval_inf) *)\n\n(* Theorem: if there exists some integer `i` after which ceval_step of command\nc with initial state st returns a new state st', then c / st ⇓ st'.\n\nLet's take a fixed value i. By induction on it,\n\nif i = 0, then ceval_step couldn't have returned a state; by contradiction,\nthe induction base is proved.\n\nThe inductive step is: if c / st ⇓ st' holds for a computation which returns\nafter i steps, then adding a new step does not change the result of the\ncomputation and, as such, does not break the relation.\n\nLet's analyze all the cases for command c and prove that for each of them\nincrementing i does not change the result.\n\nFor SKIP and assignment, the case is simple: it is evident that step counter is\nnot used in their operation simply by looking at the function definition.\n\nFor sequential execution c1 ;; c2, we analyze the two cases: if c1 executed\nnormally, then the process of updating the state corresponds to the one in the\nE_Seq. Otherwise, we arrive at contradiction: if c1 returned Nothing, the whole\nfunction couldn't have returned Some st'.\n\nFor conditional operator, we analyze `true` and `false` branches separately,\nfor each applying the corresponding constructor: E_IfTrue and E_IfFalse,\nrespectively.\n\nFor loops, the condition can be `true` or `false` for each iteration; we shall\nseparate the cases. If a new iteration occurs, then it must have returned some\nstate; otherwise, the whole loop would have returned Nothing; thus, relation\n(loop body) / (initial state on this iteration) ⇓ (state after iteration) holds\nby E_WhileTrue. If, on the other hand, we're leaving the loop, then the\nfunction does not change the state, and (loop) / st ⇓ st holds by E_WhileEnd.\n\n*)\n\n(* END ceval_step__ceval_inf. *)\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; intros.\n    - (* Case \"returned after 0 steps\" *)\n      inversion H0.\n    - (* Case \"returned after (S i1) steps\" *)\n      destruct i2.\n      + (* SCase \"S _ <= 0\" *)\n        inversion H.\n      + (* SCase \"S i1 <= S i2\" *)\n        apply le_S_n in H.\n        destruct c; inversion H0; simpl; try reflexivity.\n          * (* SSCase \";;  \" *)\n            destruct (ceval_step st c1 i1) eqn: Heq.\n              apply (IHi1 i2) in Heq; try assumption. rewrite -> Heq.\n                rewrite -> H2. apply IHi1; try assumption.\n              inversion H2.\n          * (* SSCase \"IFB \" *)\n            destruct (beval st b) eqn: Heq;\n              rewrite -> H2; apply IHi1; assumption.\n          * (* SSCase \"While\" *)\n            destruct (beval st b) eqn: Heq.\n              rewrite -> H2.\n              destruct (ceval_step st c i1) eqn: Heq'.\n                assert (ceval_step st c i2 = Some s)\n                  by apply (IHi1 _ _ _ _ H Heq').\n                rewrite -> H1.\n                apply IHi1; assumption.\n                inversion H2.\n             trivial.\nQed.\n\n(* Exercise: 3 stars (ceval__ceval_step) *)\n\nTheorem ceval__ceval_step : forall c st st',\n  c / st ⇓ st' -> exists i, ceval_step st c i = Some st'.\nProof.\n  intros c st st' Hce.\n  induction Hce; try (exists 1; reflexivity).\n    - (* Case \"c1 ;; c2\" *)\n      destruct IHHce1. destruct IHHce2.\n      exists (S (x + x0)).\n        simpl.\n        assert (ceval_step st c1 (x + x0) = Some st').\n          apply (ceval_step_more x). omega. assumption.\n        rewrite -> H1. apply (ceval_step_more x0). omega. assumption.\n    - (* Case \"IFB True\" *)\n      destruct IHHce. exists (S x). simpl. rewrite -> H. assumption.\n    - (* Case \"IFB False\" *)\n      destruct IHHce. exists (S x). simpl. rewrite -> H. assumption.\n    - (* Case \"While False\" *)\n      exists 1. simpl. rewrite -> H. trivial.\n    - (* Case \"While True\" *)\n      destruct IHHce1. destruct IHHce2.\n      exists (S (x + x0)).\n      simpl. rewrite -> H.\n      assert (ceval_step st c (x + x0) = Some st').\n        apply (ceval_step_more x). omega. assumption.\n      rewrite -> H2.\n      apply (ceval_step_more x0). omega. assumption.\nQed.\n\n(* END ceval__ceval_step. *)\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/ImpCEvalFun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.6574363051271478}}
{"text": "Require Export fin.\nRequire Import notations decidables Setoid Morphisms.\n\nDefinition vect A n := fin n -> A.\nDefinition vect_eq {A n} (v1 v2: vect A n) := forall i, v1 i = v2 i.\nDefinition vect_sym {A n} (v: vect A n): vect A n := fun i => v (fin_sym i).\n\nDefinition remove_element {A n} (num: fin (S n)) (v: vect A (S n)): vect A n :=\n fun i => if le_dec i.1 num.1 then v (le_to_fin (le_S _ _ i.2)) else v (le_to_fin (Le.le_n_S _ _ i.2)).\n\nDefinition vect_swap {A n} (i j: fin n) (v: vect A n): vect A n :=\n fun m => if eq_dec i.1 m.1 then v j else if eq_dec j.1 m.1 then v i else v m.\nTheorem vect_swap_involutive {A n} (i j: fin n) (v: vect A n): vect_eq (vect_swap i j (vect_swap i j v)) v.\n unfold vect_eq, vect_swap; intro; destruct i, j, i0; simpl; repeat destruct eq_dec; f_equal; apply fin_eq_thm; simpl;\n congruence.\nQed.\nTheorem vect_swap_sym {A n} (i j: fin n) (v: vect A n): vect_eq (vect_swap i j v) (vect_swap j i v).\n unfold vect_eq, vect_swap; intro; destruct i, j, i0; simpl; repeat destruct eq_dec; f_equal; apply fin_eq_thm; simpl;\n congruence.\nQed.\n\nDefinition vect_fold_right' {A B n} (f: B -> A -> B) (i: fin n) (start: B) (v: vect A n) :=\n let fix aux {A B n i} (f: B -> A -> B) (v: vect A n): i <= n -> B -> B :=\n  match i with\n  | O => fun (H: O <= n) b => f b (v (fin_zero n))\n  | S m => fun (H: S m <= n) b => f (aux f v (Le.le_Sn_le _ _ H) b) (v (le_to_fin H))\n  end\n in aux f v i.2 start.\nDefinition vect_fold_left' {A B n} (f: B -> A -> B) (i: fin n) (start: B) (v: vect A n) := vect_fold_right' f i start (vect_sym v).\nDefinition vect_fold_right {A B n} (f: B -> A -> B) (start: B) (v: vect A n) := vect_fold_right' f (fin_limit n) start v.\nDefinition vect_fold_left {A B n} (f: B -> A -> B) (start: B) (v: vect A n) := vect_fold_left' f (fin_limit n) start v.\n\nDefinition vect_to_list {A n} (v: vect A n): list A := vect_fold_left (fun x y => cons y x) nil v.\n\n\nInstance vect_eq_Equiv A n: Equivalence (vect_eq (A:=A) (n:=n)).\n split; unfold Reflexive, Symmetric, Transitive, vect_eq; congruence.\nQed.\nInstance vect_sym_Proper A n: Proper (vect_eq ==> vect_eq) (vect_sym (A:=A) (n:=n)).\n unfold Proper, respectful, vect_eq, vect_sym; auto.\nQed.\nInstance remove_element_Proper A n num: Proper (vect_eq ==> vect_eq) (remove_element (A:=A) (n:=n) num).\n unfold Proper, respectful, vect_eq, remove_element; intros; destruct le_dec; auto.\nQed.\nInstance vect_swap_Proper A n i j: Proper (vect_eq ==> vect_eq) (vect_swap (A:=A) (n:=n) i j).\n unfold Proper, respectful, vect_eq, vect_swap; intros; repeat destruct eq_dec; auto.\nQed.\nInstance vect_fold_right'_Proper A B n f i start: Proper (vect_eq ==> eq) (vect_fold_right' (A:=A) (B:=B) (n:=n) f i start).\n unfold Proper, respectful, vect_eq, vect_fold_right'; destruct i; simpl; intros;\n induction x; rewrite H; [| rewrite IHx]; auto.\nQed.\nInstance vect_fold_left'_Proper A B n f i start: Proper (vect_eq ==> eq) (vect_fold_left' (A:=A) (B:=B) (n:=n) f i start).\n unfold Proper, respectful, vect_fold_left'; intros; rewrite H; auto.\nQed.\nInstance vect_fold_right_Proper A B n f start: Proper (vect_eq ==> eq) (vect_fold_right (A:=A) (B:=B) (n:=n) f start) :=\n vect_fold_right'_Proper A B n f (fin_limit n) start.\nInstance vect_fold_left_Proper A B n f start: Proper (vect_eq ==> eq) (vect_fold_left (A:=A) (B:=B) (n:=n) f start) :=\n vect_fold_left'_Proper A B n f (fin_limit n) start.\n", "meta": {"author": "zaarcis", "repo": "linear_algebra_in_Coq", "sha": "9d091fbe61b6895f8e9e2b486e44827cd4c959dc", "save_path": "github-repos/coq/zaarcis-linear_algebra_in_Coq", "path": "github-repos/coq/zaarcis-linear_algebra_in_Coq/linear_algebra_in_Coq-9d091fbe61b6895f8e9e2b486e44827cd4c959dc/vectors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695208, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6574362912902307}}
{"text": "Require Export Logic_Property.\n\n(** The foramlization of axiomatic set theory **)\n\n\nModule AxiomaticSetTheory.\n\nParameter Class : Type.\n\n\n(* ∈: belongs to. x∈y : In x y. *)\n\nParameter In : Class -> Class -> Prop.\n\nNotation \"x ∈ y\" := (In x y) (at level 10).\n\n\n(* I Axiom of extent : For each x and each y it is true that x = y\n   if and only if for each z, z∈x when and only when z∈y. *)\n\nAxiom AxiomI : forall x y, x = y <-> (forall z, z∈x <-> z∈y).\n\nHint Resolve AxiomI : set.\n\n\n(* Definition1 : x is a set iff for some y, x∈y. *)\n\nDefinition Ensemble x : Prop := exists y, x∈y.\n\nLtac Ens := unfold Ensemble; eauto.\n\nLtac AssE x := assert (Ensemble x); Ens.\n\nHint Unfold Ensemble : set.\n\n\n(* II Classiferification axiom-scheme : For each b, b ∈ {a : P A} if and only\n   if b is a set and P b. *)\n\n(* {...:...} *)\n\nParameter Classifier : forall P: Class -> Prop, Class.\n\nNotation \"\\{ P \\}\" := (Classifier P) (at level 0).\n\nAxiom AxiomII : forall b P,\n  b ∈ \\{ P \\} <-> Ensemble b /\\ (P b).\n\nHint Resolve AxiomII : set.\n\n\n(* Definition2 : x∪y = {z : z∈x or z∈y}. *)\n\nDefinition Union x y : Class := \\{ λ z, z∈x \\/ z∈y \\}.\n\nNotation \"x ∪ y\" := (Union x y) (at level 65, right associativity).\n\nHint Unfold Union : set.\n\n\n(* Definition3 :  x∩y = {z : z∈x and z∈y}. *)\n\nDefinition Intersection x y : Class := \\{ λ z, z∈x /\\ z∈y \\}.\n\nNotation \"x ∩ y\" := (Intersection x y) (at level 60).\n\nHint Unfold Intersection : set.\n\n\n(* Theorem4 :  z∈x∪y iff z∈x or z∈y, z∈x∩y iff z∈x and z∈y. *)\n\nTheorem Theorem4 : forall (x y: Class) (z: Class),\n  z∈x \\/ z∈y <-> z∈(x ∪ y).\nProof.\n  intros; split; intros.\n  - unfold Union; apply AxiomII; split; auto.\n    destruct H; Ens.\n  - unfold Union in H; apply AxiomII in H; apply H.\nQed.\n\nTheorem Theorem4' : forall (x y: Class) (z: Class),\n  z∈x /\\ z∈y <-> z∈(x ∩ y).\nProof.\n  intros; unfold Intersection; split; intros.\n  - apply AxiomII; split; auto; destruct H; Ens.\n  - apply AxiomII in H; apply H.\nQed.\n\nHint Resolve Theorem4 Theorem4' : set.\n\n\n(* Theorem5 : x∪x = x and x∩x = x. *)\n\nTheorem Theorem5 : forall (x: Class), x ∪ x = x.\nProof.\n  intros.\n  apply AxiomI; split; intros.\n  - apply Theorem4 in H; destruct H; auto.\n  - apply Theorem4; left; apply H.\nQed.\n\nTheorem Theorem5' : forall (x: Class), x ∩ x = x.\nProof.\n  intros.\n  apply AxiomI; split; intros.\n  - apply Theorem4' in H; apply H.\n  - apply Theorem4'; split; apply H.\nQed.\n\nHint Rewrite Theorem5 Theorem5' : set.\n\n\n(* Theorem6 : x∪y = y∪x and x∩y = y∩x. *)\n\nTheorem Theorem6 : forall (x y: Class), x ∪ y = y ∪ x.\nProof.\n  intros; apply AxiomI; split; intro.\n  - apply Theorem4 in H; apply Theorem4; tauto.\n  - apply Theorem4 in H; apply Theorem4; tauto.\nQed.\n\nTheorem Theorem6' : forall (x y: Class), x ∩ y = y ∩ x.\nProof.\n  intros; apply AxiomI; split; intro.\n  - apply Theorem4' in H; apply Theorem4'; tauto.\n  - apply Theorem4' in H; apply Theorem4'; tauto.\nQed.\n\nHint Rewrite Theorem6 Theorem6' : set.\n\n\n(* Theorem7 : (x∪y)∪z = x∪(y∪z) and (x∩y)∩z = x∩(y∩z). *)\n\nTheorem Theorem7 : forall (x y z: Class),\n  (x ∪ y) ∪ z = x ∪ (y ∪ z).\nProof.\n  intros.\n  apply AxiomI; split; intro.\n  - apply Theorem4 in H; apply Theorem4; destruct H.\n    + apply Theorem4 in H; destruct H; try tauto.\n      right; apply Theorem4; auto.\n    + right; apply Theorem4; auto.\n  - apply Theorem4 in H; apply Theorem4; destruct H.\n    + left; apply Theorem4; auto.\n    + apply Theorem4 in H; destruct H; try tauto.\n      left; apply Theorem4; auto.\nQed.\n\nTheorem Theorem7' : forall (x y z: Class),\n  (x ∩ y) ∩ z = x ∩ (y ∩ z).\nProof.\n  intros.\n  apply AxiomI; split; intro.\n  - apply Theorem4' in H; destruct H.\n    apply Theorem4' in H; destruct H.\n    apply Theorem4'; split; auto.\n    apply Theorem4'; split; auto.\n  - apply Theorem4' in H; destruct H.\n    apply Theorem4' in H0; destruct H0.\n    apply Theorem4'; split; auto.\n    apply Theorem4'; split; auto.\nQed.\n\nHint Rewrite Theorem7 Theorem7' : set.\n\n\n(* Theorem8 : x∩(y∪z)= (x∩y)∪(x∩z) and x∪(y∩z) = (x∪y)∩(x∪z). *)\n\nTheorem Theorem8 : forall (x y z: Class),\n  x ∩ (y ∪ z) = (x ∩ y) ∪ (x ∩ z).\nProof.\n  intros; apply AxiomI; split; intros.\n  - apply Theorem4; apply Theorem4' in H; destruct H.\n    apply Theorem4 in H0; destruct H0.\n    + left; apply Theorem4'; split; auto.\n    + right; apply Theorem4'; split; auto.\n  - apply Theorem4 in H; apply Theorem4'; destruct H.\n    + apply Theorem4' in H; destruct H; split; auto.\n      apply Theorem4; left; auto.\n    + apply Theorem4' in H; destruct H; split; auto.\n      apply Theorem4; right; auto.\nQed.\n\nHint Rewrite Theorem8 : set.\n\n\n(* Definition9 : x∉y iff it is false that x∈y. *)\n\nDefinition NotIn x y : Prop := ~ x∈y.\n\nNotation \"x ∉ y\" := (NotIn x y) (at level 10).\n\nHint Unfold NotIn : set.\n\n\n(* Definition10 : ~x = {y : y∉x}. *)\n\nDefinition Complement x : Class := \\{ λ y, y ∉ x \\}.\n\nNotation \"¬ x\" := (Complement x) (at level 5, right associativity).\n\nHint Unfold Complement : set.\n\n\n(* Definition13 : x~y = x∩(~y). *)\n\nDefinition Setminus x y : Class := x ∩ (¬ y).\n\nNotation \"x ~ y\" := (Setminus x y) (at level 50, left associativity).\n\nHint Unfold Setminus : set.\n\n\n(* Definition Inequality : x≠y iff x=y is not true. *)\n\nDefinition Inequality (x y: Class) : Prop := ~ (x = y).\n\nNotation \"x ≠ y\" := (Inequality x y) (at level 70).\n\nCorollary Property_Ineq : forall x y, (x ≠ y) <-> (y ≠ x).\nProof.\n intros; split; intros; intro; apply H; auto.\nQed.\n\nHint Unfold Inequality: set.\nHint Resolve Property_Ineq: set.\n\n\n(* Definition15 : Φ = {x : x ≠ x}. *)\n\nDefinition Φ : Class := \\{ λ x, x ≠ x \\}.\n\nHint Unfold Φ : set.\n\n\n(* Theorem16 : x∉Φ. *)\n\nTheorem Theorem16 : forall (x: Class), x ∉ Φ.\nProof.\n  intros; unfold NotIn; intro.\n  unfold Φ in H; apply AxiomII in H.\n  destruct H; apply H0; auto.\nQed.\n\nHint Resolve Theorem16 : set.\n\n\n(* Theorem17 : Φ∪x = x and Φ∩x = Φ *)\n\nTheorem Theorem17 : forall x, Φ ∪ x = x.\nProof.\n  intros; apply AxiomI; split; intro.\n  - apply Theorem4 in H; destruct H; try tauto.\n    generalize (Theorem16 z); contradiction.\n  - apply Theorem4; tauto.\nQed.\n\nHint Rewrite Theorem17 : set.\n\n\n(* Definition18 : μ = {x : x=x}, the class μ is the universe. *)\n\nDefinition μ : Class := \\{ λ x, x = x \\}.\n\nLemma Property_μ : forall (x y: Class),\n  x ∪ (¬ x) = μ.\nProof.\n  intros.\n  apply AxiomI; split; intros.\n  - unfold μ; apply AxiomII; split; auto.\n    unfold Ensemble; exists (x ∪ ¬ x); auto.\n  - unfold μ in H; apply AxiomII in H; destruct H.\n    generalize (classic (z∈x)); intros.\n    destruct H1; apply Theorem4; try tauto.\n    right; apply AxiomII; split; auto.\nQed.\n\nHint Unfold μ : set.\nHint Resolve Property_μ : set.\n\n\n(* Theorem19 : x∈μ iff x is a set. *)\n\nTheorem Theorem19 : forall (x: Class),\n  x ∈ μ <-> Ensemble x.\nProof.\n  intros; split; intro.\n  - unfold μ in H; apply AxiomII in H; apply H.\n  - unfold μ; apply AxiomII; split; auto.\nQed.\n\nHint Resolve Theorem19 : set.\n\n\n(* Theorem20 : x∪μ = μ and x∩μ = x. *)\n\nTheorem Theorem20 : forall (x: Class), x ∪ μ = μ.\nProof.\n  intros.\n  apply AxiomI; split; intro.\n  - apply Theorem4 in H; destruct H; auto.\n    apply Theorem19; Ens.\n  - apply Theorem4; tauto.\nQed.\n\nTheorem Theorem20' : forall (x: Class), x ∩ μ = x.\nProof.\n  intros.\n  apply AxiomI; split; intro.\n  - apply Theorem4' in H; apply H.\n  - apply Theorem4'; split; auto.\n    apply Theorem19; Ens.\nQed.\n\nHint Resolve Theorem20 Theorem20' : set.\n\n\n(* Definition22 : ∩x = {z : for each y, if y∈x, then z∈y}. *) \n\nDefinition Element_I x : Class := \\{ λ z, forall y, y ∈ x -> z ∈ y \\}.\n\nNotation \"∩ x\" := (Element_I x) (at level 66).\n\nHint Unfold Element_I : set.\n\n\n(* Definition23 : ∪x = {z : for some y, z∈y and y∈x}. *)\n\nDefinition Element_U x : Class := \\{ λ z, exists y, z ∈ y /\\ y ∈ x \\}.\n\nNotation \"∪ x\" := (Element_U x) (at level 66).\n\nHint Unfold Element_U : set.\n\n\n(* Theorem24 : ∩Φ = μ and ∪Φ = Φ. *)\n\nTheorem Theorem24 : ∩ Φ = μ.\nProof.\n  intros; apply AxiomI; split; intros.\n  - apply Theorem19; Ens.\n  - apply AxiomII; apply Theorem19 in H; split; auto.\n    intros; generalize (Theorem16 y); contradiction.\nQed.\n\nTheorem Theorem24' : ∪ Φ = Φ.\nProof.\n  intros; apply AxiomI; split; intro.\n  - apply AxiomII in H; destruct H, H0, H0.\n    generalize (Theorem16 x); contradiction.\n  - generalize (Theorem16 z); contradiction.\nQed.\n\nHint Rewrite Theorem24 Theorem24' : set. \n\n\n(* Definition25 : x⊂y iff for each z, if z∈x, then z∈y. *)\n\nDefinition Included x y : Prop := forall z, z∈x -> z∈y.\n\nNotation \"x ⊂ y\" := (Included x y) (at level 70).\n\nHint Unfold Included : set.\n\n\n(* Theorem26 : Φ⊂x and x⊂μ. *)\n\nTheorem Theorem26 : forall (x: Class), Φ ⊂ x.\nProof.\n  intros.\n  unfold Included; intros.\n  generalize (Theorem16 z); intro; contradiction.\nQed.\n\nTheorem Theorem26' : forall x, x ⊂ μ.\nProof.\n  intros; unfold Included; intros; apply Theorem19; Ens.\nQed.\n\nHint Resolve Theorem26 Theorem26' : set.\n\n\n(* Theorem27 : x=y iff x⊂y and y⊂x. *)\n\nTheorem Theorem27 : forall (x y: Class),\n  (x ⊂ y /\\ y ⊂ x) <-> x = y.\nProof.\n  intros; split; intros.\n  - unfold Included in H; destruct H.\n    apply AxiomI; split; auto.\n  - rewrite <- H; unfold Included; split; auto.\nQed.\n\nHint Resolve Theorem27 : set.\n\n\n(* Theorem28 : If x⊂y and y⊂z, then x⊂z. *)\n\nTheorem Theorem28 : forall (x y z: Class),\n  x ⊂ y /\\ y ⊂ z -> x ⊂ z.\nProof.\n  intros; destruct H; unfold Included; intros.\n  unfold Included in H1; auto.\nQed.\n\nHint Resolve Theorem28 : set.\n\n\n(* Theorem29 : x⊂y iff x∪y=y. *)\n\nTheorem Theorem29 : forall (x y: Class),\n  x ∪ y = y <-> x ⊂ y.\nProof.\n  intros; split; intros.\n  - unfold Included; intros.\n    apply AxiomI with (z:=z) in H; apply H.\n    apply Theorem4; left; auto.\n  - apply AxiomI; split; intros.\n    + apply Theorem4 in H0; elim H0; intros; auto.\n    + apply Theorem4; tauto.\nQed.\n\nHint Resolve Theorem29 : set.\n\n\n(* Theorem30 : x⊂y iff x∩y=x. *)\n\nTheorem Theorem30 : forall x y, x ∩ y = x <-> x ⊂ y.\nProof.\n  intros; split; intros.\n  - unfold Included; intros; apply AxiomI with (z:=z) in H.\n    apply H in H0; apply Theorem4' in H0; tauto.\n  - apply AxiomI; split; intros.\n    + apply Theorem4' in H0; tauto.\n    + apply Theorem4'; split; auto.\nQed.\n\nHint Resolve Theorem30 : set.\n\n\n(* Theorem31 : If x⊂y, then ∪x⊂∪y and ∩y⊂∩x. *)\n\nTheorem Theorem31 : forall x y, x ⊂ y -> (∪x ⊂ ∪y) /\\ (∩y ⊂ ∩x).\nProof.\n  intros; split.\n  - unfold Included; intros; apply AxiomII in H0; destruct H0.\n    apply AxiomII; split; auto; intros; destruct H1.\n    exists x0; split; unfold Included in H; destruct H1; auto.\n  - unfold Included in H; unfold Included; intros.\n    apply AxiomII in H0; destruct H0; apply AxiomII; split; auto.\nQed.\n\nHint Resolve Theorem31 : set.\n\n\n(* Theorem32 : If x∈y, x⊂∪y and ∩y⊂x. *)\n\nTheorem Theorem32 : forall (x y: Class),\n  x ∈ y -> (x ⊂ ∪y) /\\ (∩y ⊂ x).\nProof.\n  intros; split.\n  - unfold Included; intros.\n    apply AxiomII; split; Ens.\n  - unfold Included; intros.\n    apply AxiomII in H0; destruct H0.\n    apply H1 in H; auto.\nQed.\n\nHint Resolve Theorem32 : set.\n\n\n(* Proper Subset *)\n\nDefinition ProperSubset x y : Prop := x ⊂ y /\\ x ≠ y.\n\nNotation \"x ⊊ y\" := (ProperSubset x y) (at level 70).\n\nLemma Property_ProperSubset : forall (x y: Class),\n  x ⊂ y -> (x ⊊ y) \\/ x = y.\nProof.\n  intros.\n  generalize (classic (x = y)); intros.\n  destruct H0; auto.\n  left; unfold ProperSubset; auto.\nQed.\n\nLemma Property_ProperSubset' : forall (x y: Class),\n  x ⊊ y -> exists z, z ∈ y /\\ z ∉ x.\nProof.\n  intros.\n  unfold ProperSubset in H; destruct H.\n  generalize (Theorem27 x y); intros.\n  apply definition_not with (B:= (x ⊂ y /\\ y ⊂ x)) in H0; try tauto.\n  apply not_and_or in H0; destruct H0; try tauto.\n  unfold Included in H0.\n  apply not_all_ex_not in H0; destruct H0.\n  apply imply_to_and in H0.\n  exists x0; auto.\nQed.\n\nLemma Property_ProperSubset'' : forall (x y: Class),\n  x ⊂ y \\/ y ⊂ x -> ~ (x ⊂ y) -> y ⊊ x.\nProof.\n  intros; destruct H.\n  - elim H0; auto.\n  - unfold ProperSubset; split; auto.\n    intro; rewrite H1 in H.\n    pattern x at 2 in H; rewrite <- H1 in H.\n    contradiction.\nQed.\n\nLemma Property_Φ : forall x y, y ⊂ x -> x ~ y = Φ <-> x = y.\nProof.\n  intros; split; intros.\n  - apply Property_ProperSubset in H; destruct H; auto.\n    apply Property_ProperSubset' in H; destruct H as [z H], H.\n    assert (z ∈ (x ~ y)).\n    { unfold Setminus; apply Theorem4'; split; auto.\n      unfold Complement; apply AxiomII; split; Ens. }\n    rewrite H0 in H2; generalize (Theorem16 z); intros.\n    contradiction.\n  - rewrite <- H0; apply AxiomI; split; intros.\n    + unfold Setminus in H1; apply Theorem4' in H1.\n      destruct H1; unfold Complement in H2.\n      apply AxiomII in H2; destruct H2; contradiction.\n    + generalize (Theorem16 z); intros; contradiction.\nQed.\n\nHint Unfold ProperSubset : Axiom_of_Choice.\nHint Resolve Property_ProperSubset Property_ProperSubset'\n             Property_ProperSubset'' Property_Φ: Axiom_of_Chioce.\n\n\n(* III Axiom of subsets : If x is a set there is a set y such that for\n   each z, if z⊂x, then z∈y. *)\n\nAxiom AxiomIII : forall (x: Class),\n  Ensemble x -> exists y, Ensemble y /\\ (forall z, z⊂x -> z∈y).\n\nHint Resolve AxiomIII : set.\n\n\n(* Theorem33 : If x is a set and z⊂x, then z is a set. *)\n\nTheorem Theorem33 : forall (x z: Class),\n  Ensemble x -> z ⊂ x -> Ensemble z.\nProof.\n  intros.\n  apply AxiomIII in H; destruct H.\n  apply H in H0; Ens.\nQed.\n\nHint Resolve Theorem33 : set.\n\n\n(* Theorem35 : If x≠Φ, then ∩x is a set. *)\n\nLemma Property_NotEmpty : forall x, x ≠ Φ <-> exists z, z∈x.\nProof.\n  intros; assert (x = Φ <-> ~ (exists y, y∈x)).\n  { split; intros.\n    - intro; destruct H0; rewrite H in H0.\n      apply AxiomII in H0; destruct H0; case H1; auto.\n    - apply AxiomI; split; intros.\n      + elim H; exists z; auto.\n      + generalize (Theorem16 z); contradiction. }\n  split; intros.\n  - apply definition_not with (B:= ~(exists y, y∈x)) in H0; auto.\n    apply NNPP in H0; destruct H0; exists x0; auto.\n  - apply definition_not with (A:=(~ (exists y, y∈x))); auto.\n    destruct H; split; auto.\nQed.\n\nTheorem Theorem35 : forall x, x ≠ Φ -> Ensemble (∩x).\nProof.\n  intros; apply Property_NotEmpty in H; destruct H; AssE x0.\n  generalize (Theorem32 x0 x H); intros.\n  destruct H1; apply Theorem33 in H2; auto.\nQed.\n\nHint Resolve Property_NotEmpty Theorem35 : set.\n\n\n(* Definition36 : 2*x = {y : y⊂x}. *)\n\nDefinition PowerSet x : Class := \\{ λ y, y ⊂ x \\}.\n\nNotation \"pow( x )\" := (PowerSet x) (at level 0, right associativity).\n\nHint Unfold PowerSet : set.\n\n\n(* Theorem38 : If x is a set, then 2*x is a set, and for each y,\n   y⊂x iff y∈2*x. *)\n\nTheorem Theorem38 : forall (x y: Class),\n  Ensemble x -> Ensemble pow(x) /\\ (y ⊂ x <-> y ∈ pow(x)).\nProof.\n  intros; split.\n  - apply AxiomIII in H; destruct H, H.\n    assert (pow(x) ⊂ x0).\n    { unfold Included; intros.\n      unfold PowerSet in H1; apply AxiomII in H1.\n      destruct H1; apply H0 in H2; auto. }\n    apply Theorem33 in H1; auto.\n  - split; intros.\n    + apply Theorem33 with (z:=y) in H; auto.\n      apply AxiomII; split; auto.\n    + apply AxiomII in H0; apply H0.\nQed.\n\nHint Resolve Theorem38 : set.\n\n\n(* Theorem39 : μ is not a set. *)\n\nLemma Lemma_N : ~ Ensemble \\{ λ x, x ∉ x \\}.\nProof.\n  generalize (classic (\\{ λ x, x ∉ x \\} ∈ \\{ λ x, x ∉ x \\})).\n  intros; destruct H.\n  - double H; apply AxiomII in H; destruct H; contradiction.\n  - intro; elim H; apply AxiomII; split; auto.\nQed.\n\nTheorem Theorem39 : ~ Ensemble μ.\nProof.\n  unfold not; generalize Lemma_N; intros.\n  generalize (Theorem26' \\{ λ x, x ∉ x \\}); intros.\n  apply Theorem33 in H1; auto.\nQed.\n\nHint Resolve Lemma_N Theorem39 : set.\n\nHint Resolve Theorem39 : set.\n\n\n(* Definition40 : {x} = {z : if x∈u, then z=x}. *)\n\nDefinition Singleton x : Class := \\{ λ z, x∈μ -> z=x \\}.\n\nNotation \"[ x ]\" := (Singleton x) (at level 0, right associativity).\n\nHint Unfold Singleton : set.\n\n\n(* Theorem42 : If x is a set, then {x} is a set. *)\n\nTheorem Theorem42 : forall (x: Class),\n  Ensemble x -> Ensemble [x].\nProof.\n  intros.\n  apply Lemma_x in H; elim H; intros.\n  apply Theorem33 with (x:= pow(x)); auto.\n  - apply Theorem38 in H0; auto.\n  - unfold Included; intros.\n    apply Theorem38 with (y:= z) in H0; auto.\n    elim H0; intros; apply H4.\n    unfold Singleton in H2.\n    apply AxiomII in H2; elim H2; intros.\n    rewrite H6; unfold Included; auto.\n    apply Theorem19; auto.\nQed.\n\nHint Resolve Theorem42 : set.\n\n\n(* Theorem43 : {x} = μ iff x is not a set. *)\n\nTheorem Theorem43 : forall (x: Class),\n  [x] = μ <-> ~Ensemble x.\nProof.\n  intros; split; intros.\n  - unfold not; intros.\n    apply Theorem42 in H0; auto.\n    rewrite H in H0; generalize Theorem39; intros.\n    absurd (Ensemble μ); auto.\n  - generalize (Theorem19 x); intros; unfold Singleton.\n    apply definition_not with (B:= x∈μ) in H; try tauto.\n    apply AxiomI; split; intros.\n    + apply AxiomII in H1; elim H1; intros.\n      apply Theorem19; auto.\n    + apply AxiomII; split; intros.\n      apply Theorem19 in H1; auto.\n      absurd (x∈μ); auto.\nQed.\n\nHint Rewrite Theorem43 : set.\n\n\n(* Theorem42' : If {x} is a set, x is a set. *)\n\nTheorem Theorem42' : forall x, Ensemble [x] -> Ensemble x.\nProof.\n  intros.\n  generalize (classic (Ensemble x)); intros.\n  destruct H0; auto; generalize (Theorem39); intros.\n  apply Theorem43 in H0; auto.\n  rewrite H0 in H; contradiction.\nQed.\n\nHint Resolve Theorem42' : set.\n\n\n(* IV Axiom of union : If x is a set and y is a set so is x∪y. *)\n\nAxiom AxiomIV : forall (x y: Class),\n  Ensemble x /\\ Ensemble y -> Ensemble (x∪y).\n\nLemma AxiomIV': forall (x y: Class),\n  Ensemble (x∪y) -> Ensemble x /\\ Ensemble y.\nProof.\n  intros; split.\n  - assert (x ⊂ (x∪y)).\n    { unfold Included; intros; apply Theorem4; tauto. }\n    apply Theorem33 in H0; auto.\n  - assert (y ⊂ (x∪y)).\n    { unfold Included; intros; apply Theorem4; tauto. }\n    apply Theorem33 in H0; auto.\nQed.\n\nHint Resolve AxiomIV AxiomIV' : set.\n\n\n(* Definition45 : {xy} = {x}∪{y}. *)\n\nDefinition Unordered x y : Class := [x]∪[y].\n\nNotation \"[ x | y ]\" := (Unordered x y) (at level 0).\n\nHint Unfold Unordered : set.\n\n\n(* Theorem46 : If x is a set and y is a set, then {xy} is a set and z∈{xy}\n   iff z=x or z=y; {xy}=μ if and only if x is not a set or y is not a set. *)\n\nTheorem Theorem46 : forall (x y: Class) (z: Class),\n  Ensemble x /\\ Ensemble y -> Ensemble [x|y] /\\ (z∈[x|y] <-> (z=x \\/ z=y)).\nProof.\n  intros.\n  unfold Unordered; split.\n  - apply AxiomIV; elim H; intros; split.\n    + apply Theorem42 in H0; auto.\n    + apply Theorem42 in H1; auto.\n  - split; intros.\n    + apply Theorem4 in H0; elim H0; intros.\n      * unfold Singleton in H1; apply AxiomII in H1.\n        elim H1; intros; left; apply H3.\n        apply Theorem19; apply H.\n      * unfold Singleton in H1; apply AxiomII in H1.\n        elim H1; intros; right; apply H3.\n        apply Theorem19; apply H.\n    + apply Theorem4; elim H0; intros.\n      * left; unfold Singleton; apply AxiomII.\n        split; try (rewrite H1; apply H); intro; apply H1.\n      * right; unfold Singleton; apply AxiomII.\n        split; try (rewrite H1; apply H); intro; apply H1.\nQed.\n\nHint Resolve Theorem46 : set.\n\n\n(* Theorem47 : If x and y are sets, then ∩{xy} = x∩y and ∪{xy} = x∪y. *)\n\nTheorem Theorem47 : forall x y,\n  Ensemble x /\\ Ensemble y -> (∩[x|y] = x ∩ y) /\\ (∪[x|y] = x ∪ y).\nProof.\n  intros; split; apply AxiomI; intros.\n  - split; intros.\n    + apply Theorem4'.\n      split; apply AxiomII in H0; destruct H0; apply H1; apply Theorem4.\n      * left; apply AxiomII; split; try apply H; auto.\n      * right; apply AxiomII; split; try apply H; auto.\n    + apply Theorem4' in H0; destruct H0.\n      apply AxiomII; split; intros; try AssE z.\n      apply Theorem4 in H2; destruct H2.\n      * apply AxiomII in H2; destruct H2; destruct H.\n        apply Theorem19 in H; apply H4 in H; rewrite H; auto.\n      * apply AxiomII in H2; destruct H2; destruct H.\n        apply Theorem19 in H5; apply H4 in H5; rewrite H5; auto.\n  - split; intros.\n    + apply AxiomII in H0; destruct H0; destruct H1; destruct H1.\n      apply Theorem4 in H2; apply Theorem4.\n      destruct H2; apply AxiomII in H2; destruct H2.\n      * left; destruct H; apply Theorem19 in H.\n        apply H3 in H; rewrite H in H1; auto.\n      * right; destruct H; apply Theorem19 in H4.\n        apply H3 in H4; rewrite H4 in H1; auto.\n    + apply Theorem4 in H0; apply AxiomII.\n      split; destruct H0; try AssE z.\n      * exists x; split; auto; apply Theorem4; left.\n        apply AxiomII; split; try apply H; trivial.\n      * exists y; split; auto; apply Theorem4; right.\n        apply AxiomII; split; try apply H; trivial.\nQed.\n\nHint Resolve Theorem47 : set.\n\n\n(* Definition48 : (x,y) = {{x}{y}}. *)\n\nDefinition Ordered x y : Class := [ [x] | [x|y] ].\n\nNotation \"[ x , y ]\" := (Ordered x y) (at level 0).\n\nHint Unfold Ordered : set.\n\n\n(* Theorem49 : (x,y) is a set if and only if x is a set and y is a set. *)\n\nTheorem Theorem49 : forall (x y: Class),\n  Ensemble [x,y] <-> Ensemble x /\\ Ensemble y.\nProof.\n  intros; split; intro.\n  - unfold Ordered in H; unfold Unordered in H.\n    apply AxiomIV' in H; elim H; intros.\n    apply Theorem42' in H0; auto.\n    apply Theorem42' in H0; auto.\n    apply Theorem42' in H1; auto; split; auto.\n    unfold Unordered in H1; apply AxiomIV' in H1.\n    elim H1; intros; apply Theorem42' in H3; auto.\n  - elim H; intros; unfold Ordered; unfold Unordered.\n    apply AxiomIV; split.\n    + apply Theorem42; auto; apply Theorem42; auto.\n    + apply Theorem42; auto; apply Theorem46; auto.\nQed.\n\nHint Resolve Theorem49 : set.\n\n\n(* Theorem50 : If x and y are sets, then ∪(x,y) = {xy}, ∩(x,y) = {x},\n   ∪∩(x,y) = x, ∩∩(x,y) = x, ∪∪(x,y) = x∪y, ∩∪(x,y) = x∩y. *)\n\nLemma Lemma50 : forall (x y: Class),\n  Ensemble x /\\ Ensemble y -> Ensemble [x] /\\ Ensemble [x | y].\nProof.\n  intros.\n  apply Theorem49 in H; auto.\n  unfold Ordered in H; unfold Unordered in H.\n  apply AxiomIV' in H; elim H; intros.\n  apply Theorem42' in H0; auto.\n  apply Theorem42' in H1; auto.\nQed.\n\nTheorem Theorem50 : forall (x y: Class),\n  Ensemble x /\\ Ensemble y -> (∪[x,y] = [x|y]) /\\ (∩[x,y] = [x]) /\\\n  (∪(∩[x,y]) = x) /\\ (∩(∩[x,y]) = x) /\\ (∪(∪[x,y])=x∪y) /\\ (∩(∪[x,y])=x∩y).\nProof.\n  intros; elim H; intros.\n  repeat unfold Ordered; apply Lemma50 in H.\n  apply Theorem47 in H; auto; elim H; intros; repeat split.\n  - rewrite H3; apply AxiomI; split; intros.\n    + apply Theorem4 in H4; elim H4; intros.\n      * unfold Unordered; apply Theorem4; left; apply H5.\n      * apply H5.\n    + apply Theorem4; right; apply H4.\n  - rewrite H2; apply AxiomI; split; intros.\n    + apply Theorem4' in H4; apply H4.\n    + apply Theorem4'; split; auto.\n      unfold Unordered; apply Theorem4; left; apply H4.\n  - rewrite H2; apply AxiomI; split; intros.\n    + apply AxiomII in H4; elim H4; intros.\n      elim H6; intros; elim H7; intros.\n      apply Theorem4' in H9; elim H9; intros.\n      unfold Singleton in H10; apply AxiomII in H10.\n      elim H10; intros; rewrite <- H13. apply H8.\n      apply Theorem19; apply H0.\n    + apply AxiomII; split.\n      * unfold Ensemble; exists x; apply H4.\n      * exists x; split. apply H4.\n        apply Theorem4'; split.\n        -- unfold Singleton; apply AxiomII; split; auto.\n        -- unfold Unordered; apply Theorem4.\n           left; unfold Singleton; apply AxiomII.\n           split; try apply H0; trivial.\n  - rewrite H2; apply AxiomI; split; intros.\n    + apply AxiomII in H4; elim H4; intros.\n      apply H6; apply Theorem4'; split.\n      * unfold Singleton; apply AxiomII; split; auto.\n      * unfold Unordered; apply Theorem4.\n        left; unfold Singleton; apply AxiomII; split; auto.\n    + apply AxiomII; split.\n      * unfold Ensemble; exists x; apply H4.\n      * intros; apply Theorem4' in H5; elim H5; intros.\n        unfold Singleton in H6; apply AxiomII in H6.\n        elim H6; intros;  rewrite H9. \n        apply H4. apply Theorem19; apply H0.\n  - rewrite H3; apply AxiomI; split; intros.\n    + apply Theorem4; apply AxiomII in H4; elim H4; intros.\n      elim H6; intros; elim H7; intros.\n      apply Theorem4 in H9; elim H9; intros.\n      * unfold Singleton in H10; apply AxiomII in H10.\n        elim H10; intros; left; rewrite <- H12; try apply H8.\n        apply Theorem19; apply H0.\n      * unfold Unordered in H10; apply Theorem4 in H10; elim H10; intros.\n        -- unfold Singleton in H11; apply AxiomII in H11.\n           elim H11; intros; left; rewrite <- H13.\n           apply H8. apply Theorem19; apply H0.\n        -- unfold Singleton in H11; apply AxiomII in H11.\n           elim H11; intros; right; rewrite <- H13.\n           apply H8. apply Theorem19; apply H1.\n    + apply AxiomII; apply Theorem4 in H4; split.\n      * unfold Ensemble; elim H4; intros.\n        -- exists x; apply H5.\n        -- exists y; apply H5.\n      * elim H4; intros.\n        -- exists x; split; auto.\n           apply Theorem4; left.\n           unfold Singleton; apply AxiomII; split; auto.\n        -- exists y; split; auto.\n           apply Theorem4; right.\n           unfold Unordered; apply Theorem4; right.\n           unfold Singleton; apply AxiomII; split; auto.\n  - rewrite H3; apply AxiomI; split; intros.\n    + apply Lemma_x in H4; elim H4; intros.\n      apply AxiomII in H5; apply AxiomII in H6.\n      elim H4; intros; apply Theorem4'; split; auto.\n      * apply H5; apply Theorem4; left.\n        unfold Singleton; apply AxiomII; split; auto.\n      * apply H6; apply Theorem4; right.\n        unfold Unordered; apply Theorem4; right.\n        unfold Singleton; apply AxiomII; split; auto.\n    + apply Theorem4' in H4; elim H4; intros.\n      apply AxiomII; split.\n      unfold Ensemble; exists x; apply H5.\n      intros; apply Theorem4 in H7; destruct H7.\n      * unfold Singleton in H7; apply AxiomII in H7.\n        destruct H7; rewrite H8; auto.\n        apply Theorem19; apply H0.\n      * unfold Unordered in H7; apply AxiomII in H7; destruct H7, H8.\n        -- unfold Singleton in H8; apply AxiomII in H8.\n           destruct H8; rewrite H9; auto.\n           apply Theorem19; apply H0.\n        -- unfold Singleton in H8; apply AxiomII in H8.\n           destruct H8; rewrite H9; auto.\n           apply Theorem19; apply H1.\nQed.\n\nHint Resolve Theorem50 : set.\n\n\n(* Definition51 : 1st coord z = ∩∩z. *)\n\nDefinition First (z: Class) := ∩∩z.\n\nHint Unfold First : set.\n\n\n(* Definition52 : 2nd coord z = (∩∪z)∪(∪∪z)~(∪∩z). *)\n\nDefinition Second (z: Class) := (∩∪z)∪(∪∪z)~(∪∩z).\n\nHint Unfold Second : set.\n\n\n(* Theorem54 : If x and y are sets, 1st coord (x,y)=x and 2nd coord (x,y)=y. *)\n\nLemma Lemma54 : forall (x y: Class),\n  (x ∪ y) ~ x = y ~ x.\nProof.\n  intros.\n  apply AxiomI; split; intros.\n  - apply Theorem4' in H; apply Theorem4'.\n    destruct H; apply Theorem4 in H; split; auto.\n    destruct H; auto.\n    unfold Complement in H0; apply AxiomII in H0.\n    destruct H0; unfold NotIn in H1; elim H1; auto.\n  - apply Theorem4' in H; apply Theorem4'.\n    destruct H; split; auto.\n    apply Theorem4; right; auto.\nQed.\n\nTheorem Theorem54 : forall (x y: Class),\n  Ensemble x /\\ Ensemble y -> First [x,y] = x /\\ Second [x,y] = y.\nProof.\n  intros.\n  apply Theorem50 in H; auto; split.\n  - unfold First; apply H.\n  - elim H; intros; elim H1; intros.\n    elim H3; intros; elim H5; intros.\n    elim H7; intros; unfold Second.\n    rewrite H9; rewrite H8; rewrite H4.\n    rewrite Lemma54; auto; unfold Setminus.\n    rewrite Theorem6'; auto; rewrite <- Theorem8; auto.\n    rewrite Property_μ; auto; rewrite Theorem20'; auto.\nQed.\n\nHint Resolve Theorem54 : set.\n\n\n(* Theorem55 : If x and y are sets and (x,y) = (u,v), then x = u and y = v. *)\n\nTheorem Theorem55 : forall (x y u v: Class),\n  Ensemble x /\\ Ensemble y -> ([x,y] = [u,v] <-> x = u /\\ y = v).\nProof.\n  intros.\n  apply Lemma_x in H; elim H; intros.\n  apply Theorem49 in H0; auto; apply Theorem54 in H1; auto.\n  elim H1; intros; split; intros.\n  - rewrite H4 in H0.\n    apply Theorem49 in H0; auto; apply Theorem54 in H0; auto.\n    elim H0; intros; split.\n    + rewrite <- H4 in H5; rewrite <- H2; rewrite H5; auto.\n    + rewrite <- H4 in H6; rewrite H3 in H6; apply H6.\n  - elim H4; intros; rewrite H5; rewrite H6; trivial.\nQed.\n\nHint Resolve Theorem55 : set.\n\n\n(* Definition56 : r is a relation iff for each member z of r there is x and y\n   such that z = (x,y). *)\n\nDefinition Relation r : Prop := forall z, z∈r -> exists x y, z = [x,y].\n\nHint Unfold Relation: set.\n\n\n(* { (x,y) : ... } *)\n\nParameter Classifier_P : (Class -> Class -> Prop) -> Class.\n\nNotation \"\\{\\ P \\}\\\" := (Classifier_P P) (at level 0).\n\nAxiom AxiomII_P : forall (a b: Class) (P: Class -> Class -> Prop),\n  [a,b] ∈ \\{\\ P \\}\\ <-> Ensemble [a,b] /\\ (P a b).\n\nAxiom Property_P : forall (z: Class) (P: Class -> Class -> Prop),\n  z ∈ \\{\\ P \\}\\ -> (exists a b, z = [a,b]) /\\ z ∈ \\{\\ P \\}\\.\n\nAxiom Property_P' : forall (z: Class) (P: Class -> Class -> Prop),\n  (forall a b, z = [a,b] -> z ∈ \\{\\ P \\}\\) -> z ∈ \\{\\ P \\}\\.\n\nLtac PP H a b:= apply Property_P in H; destruct H as [[a [b H]]];\nrewrite H in *.\n\nLtac PP' H := apply Property_P'; intros a b H; rewrite H in *.\n\nHint Resolve AxiomII_P Property_P Property_P': set.\n\n\n(* Definition60 : r ⁻¹ = {[x,y] : [y,x]∈r} *)\n\nDefinition Inverse r : Class := \\{\\ λ x y, [y,x]∈r \\}\\.\n\nNotation \"r ⁻¹\" := (Inverse r)(at level 5).\n\nHint Unfold Inverse : set.\n\n\n(* Theorem61 : (r ⁻¹)⁻¹ = r *)\n\nLemma Lemma61 : forall (x y: Class),\n  Ensemble [x,y] <-> Ensemble [y,x].\nProof.\n  intros; split; intros.\n  - apply Theorem49 in H; auto.\n    destruct H; apply Theorem49; auto.\n  - apply Theorem49 in H; auto.\n    destruct H; apply Theorem49; auto.\nQed.\n\nTheorem Theorem61 : forall (r: Class),\n  (r ⁻¹)⁻¹ = r.\nProof.\n  intros; apply AxiomI; split; intros.\n  - PP H a b; apply AxiomII_P in H0; destruct H0.\n    apply AxiomII_P in H1; apply H1.\n  - PP' H0; apply AxiomII_P; split; Ens.\n    apply AxiomII_P; split; auto.\n    apply Lemma61; auto; Ens.\nQed.\n\nHint Rewrite Theorem61 : set.\n\n\n(* Definition63 : f is a function iff f is a relation and for each x,\n   each y, each z, if (x,y)∈f and (x,z)∈f, then y = z. *)\n\nDefinition Function f : Prop :=\n  Relation f /\\ (forall x y z, [x,y] ∈ f /\\ [x,z] ∈ f -> y=z).\n\nHint Unfold Function : set.\n\n\n(* Definition65 : domain f = {x : for some y, (x,y)∈f}. *)\n\nDefinition Domain f : Class := \\{ λ x, exists y, [x,y] ∈ f \\}.\n\nNotation \"dom( f )\" := (Domain f)(at level 5).\n\nLemma Property_dom : forall x y f,\n  [x,y] ∈ f -> x ∈ dom( f ).\nProof.\n  intros; apply AxiomII.\n  split; eauto; AssE [x, y].\n  apply Theorem49 in H0; apply H0.\nQed.\n\nHint Unfold Domain : set.\n\n\n(* Definition66 : range f = {y : for some x, (x,y)∈f}. *)\n\nDefinition Range f : Class := \\{ λ y, exists x, [x,y] ∈ f \\}.\n\nNotation \"ran( f )\" := (Range f)(at level 5).\n\nLemma Property_ran : forall x y f,\n  [x,y] ∈ f -> y ∈ ran( f ).\nProof.\n  intros; apply AxiomII.\n  split; eauto; AssE [x,y].\n  apply Theorem49 in H0; apply H0.\nQed.\n\nHint Unfold Range : set.\n\n\n(* Definition68 : f(x) = ∩{y : (x,y)∈f}. *)\n\nDefinition Value f x : Class := ∩ \\{ λ y, [x,y] ∈ f \\}.\n\nNotation \"f [ x ]\" := (Value f x)(at level 5).\n\nLemma Property_Value : forall f x,\n  Function f -> x ∈ (dom( f )) -> [x,f[x]] ∈ f.\nProof.\n  intros; unfold Function in H;destruct H as [_ H].\n  apply AxiomII in H0; destruct H0, H1.\n  assert (x0=f[x]).\n  { apply AxiomI; split; intros.\n    - apply AxiomII; split; intros; try Ens.\n      apply AxiomII in H3; destruct H3.\n      assert (x0=y). { apply H with x; split; auto. }\n      rewrite <- H5; auto.\n    - apply AxiomII in H2; destruct H2 as [_ H2].\n      apply H2; apply AxiomII; split; auto.\n      AssE [x, x0]; apply Theorem49 in H3; apply H3. }\n  rewrite <- H2; auto.\nQed.\n\nHint Unfold Value : set.\n\n\n(* Theorem69 : If x ∉ domain f, then f(x)=μ; If x ∈ domain f, then f[x]∈μ. *)\n\nLemma Lemma69 : forall x f,\n  Function f -> ( x ∉ dom( f ) -> \\{ λ y, [x,y] ∈ f \\} = Φ ) /\\\n  ( x ∈ dom( f ) -> \\{ λ y, [x,y] ∈ f \\} <> Φ ).\nProof.\n  intros; split; intros.\n  - generalize (classic (\\{ λ y0, [x, y0] ∈ f \\} = Φ)); intro.\n    destruct H1; auto; apply Property_NotEmpty in H1; auto.\n    elim H1; intro z; intros; apply AxiomII in H2.\n    destruct H2 as [H2 H3]; apply Property_dom in H3; contradiction.\n  - apply Property_NotEmpty; auto; exists f[x].\n    apply AxiomII;eapply Property_Value in H0; auto.\n    split; auto; apply Property_ran in H0; Ens.\nQed.\n\nTheorem Theorem69 : forall x f,\n  ( x ∉ (dom( f )) -> f[x] = μ ) /\\ ( x ∈ dom( f ) -> (f[x]) ∈  μ ).\nProof.\n  intros; split; intros.\n  - assert (\\{ λ y, [x,y] ∈ f \\} = Φ).\n    { apply AxiomI; split; intros.\n       apply AxiomII in H0; destruct H0.\n       apply Property_dom in H1; contradiction.\n       generalize (Theorem16 z); intro; contradiction. }\n    unfold Value; rewrite H0; apply Theorem24.\n  - assert (\\{ λ y, [x,y] ∈ f \\} <> Φ).\n    { intro.\n       apply AxiomII in H; destruct H, H1.\n       generalize (AxiomI \\{ λ y : Class,[x, y] ∈ f \\} Φ); intro; destruct H2.\n       apply H2 with x0 in H0; destruct H0.\n       assert (x0 ∈ Φ).\n       { apply H0; apply AxiomII; split; auto.\n          AssE [x, x0];  apply Theorem49 in H5; tauto. }\n       eapply Theorem16; eauto. }\n     apply Theorem35 in H0; apply Theorem19; auto.\nQed.\n\nHint Resolve Theorem69 : set.\n\n\n(* Property Value *)\n\nCorollary Property_Value' : forall f x,\n  Function f -> f[x] ∈ ran(f) -> [x,f[x]] ∈ f.\nProof.\n  intros; apply Property_Value; auto.\n  apply AxiomII in H0; destruct H0, H1.\n  generalize (classic (x ∈ dom( f))); intros.\n  destruct H2; auto; apply Theorem69 in H2; auto.\n  rewrite H2 in H0; generalize (Theorem39); intro; contradiction.\nQed.\n\n\n(* Theorem70 : If f is a function, then f = {(x,y) : y = f(x)}. *)\n\nTheorem Theorem70 : forall (f: Class),\n  Function f -> f = \\{\\ λ x y, y = f[x] \\}\\.\nProof.\n  intros; apply AxiomI; split; intros.\n  - PP' H1; apply AxiomII_P; split; try Ens.\n    apply AxiomI; split; intros.\n    + apply AxiomII; split; intros; try Ens.\n      apply AxiomII in H3; destruct H3.\n      apply Lemma_xy with (y:=[a,y] ∈ f) in H0; auto.\n      unfold Function in H; apply H in H0.\n      rewrite <- H0; auto.\n    + unfold Element_I in H1; apply AxiomII in H2; destruct H2.\n      apply H3; apply AxiomII; split; auto; AssE [a,b].\n      apply Theorem49 in H4; try apply H4.\n  - PP H0 a b; apply AxiomII_P in H1; destruct H1.\n    generalize (classic (a ∈ dom(f))); intros; destruct H3.\n    + apply Property_Value in H3; auto; rewrite H2; auto.\n    + apply Theorem69 in H3; auto.\n      rewrite H3 in H2; rewrite H2 in H1.\n      apply Theorem49 in H1; destruct H1 as [_ H1].\n      generalize Theorem39; intro; contradiction.\nQed.\n\nHint Resolve Theorem70 : set.\n\n\n(* V Axiom of substitution : If f is a function and domain f is a set,\n   then range f is a set. *)\n\nAxiom AxiomV : forall (f: Class),\n  Function f -> Ensemble dom(f) -> Ensemble ran(f).\n\nHint Resolve AxiomV : set.\n\n\n(* VI Axiom of amalgamation : If x is a set so is ∪x. *)\n\nAxiom AxiomVI : forall (x: Class), Ensemble x -> Ensemble (∪ x).\n\nHint Resolve AxiomVI : set.\n\n\n(* Definition72 : x × y = {(u,v) : u∈x and v∈y}. *)\n\nDefinition Cartesian x y : Class := \\{\\ λ u v, u∈x /\\ v∈y \\}\\.\n\nNotation \"x × y\" := (Cartesian x y)(at level 0, right associativity).\n\nHint Unfold Cartesian : set.\n\n\n(* Theorem73 : If u and y are sets of is {u}×y. *)\n\nLemma Ex_Lemma73 : forall u y: Class, \n  Ensemble u /\\ Ensemble y -> \n  exists f, Function f /\\ dom(f) = y /\\ ran(f) = [u] × y.\nProof.\n  intros; destruct H.\n  exists (\\{\\ λ w z, (w∈y /\\ z = [u,w]) \\}\\).\n  repeat split; intros.\n  - red; intros; PP H1 a b.\n    exists a; exists b; auto.\n  - destruct H1.\n    apply AxiomII_P in H1; apply AxiomII_P in H2.\n    destruct H1 as [_ [_ H1]]; destruct H2 as [_ [_ H2]].\n    rewrite H2; auto.\n  - apply AxiomI; split; intros.\n    + apply AxiomII in H1; destruct H1 as [_ [t H1]].\n      apply AxiomII_P in H1; tauto.\n    + apply AxiomII; split; try Ens.\n      exists [u,z]; apply AxiomII_P; split; auto.\n      AssE z; apply Theorem49; split; auto.\n      apply Theorem49; tauto.\n  - apply AxiomI; split; intros.\n    + apply AxiomII in H1; destruct H1, H1, H2.\n      apply AxiomII_P in H2; destruct H2, H3.\n      rewrite H4; apply AxiomII_P; repeat split; auto.\n      * apply Theorem49; split; auto; AssE x0.\n      * apply AxiomII; split; auto.\n    + PP H1 a b; apply AxiomII_P in H2; destruct H2, H3.\n      apply AxiomII; split; auto; exists b.\n      apply AxiomII_P; repeat split; auto.\n      * apply Theorem49; split; auto; AssE b.\n      * apply Theorem19 in H; apply AxiomII in H3.\n        destruct H3; rewrite H5; auto.\nQed.\n\nTheorem Theorem73 : forall (u y:Class),\n  Ensemble u /\\ Ensemble y -> Ensemble ([u] × y).\nProof.\n  intros; elim H; intros; apply Ex_Lemma73 in H; auto.\n  destruct H,H,H2; rewrite <- H3; apply AxiomV; auto.\n  rewrite H2; auto.\nQed.\n\nHint Resolve Theorem73 : set.\n\n\n(* Theorem74 : If x and y are sets so is x×y. *)\n\nLemma Ex_Lemma74 : forall x y:Class, Ensemble x /\\ Ensemble y -> \n  exists f:Class, Function f /\\ dom( f ) = x /\\ \n  ran( f ) = \\{ λ z, (exists u, u∈x /\\ z = [u] × y) \\}.\nProof.\n  intros; destruct H.\n  exists (\\{\\ λ u z, (u∈x /\\ z = [u] × y) \\}\\).\n  repeat split; intros.\n  - red; intros; PP H1 a b; exists a; exists b; auto.\n  - destruct H1; apply AxiomII_P in H1; apply AxiomII_P in H2.\n    destruct H1, H2, H3, H4; subst z; auto.\n  - apply AxiomI; split; intros.\n    + apply AxiomII in H1; destruct H1, H2.\n      apply AxiomII_P in H2; tauto.\n    + apply AxiomII; split; try AssE z.\n      exists (([z]) × y); apply AxiomII_P.\n      repeat split; auto; apply Theorem49; split; auto.\n      apply Theorem73; auto.\n  - apply AxiomI; split; intros.\n    + apply AxiomII in H1; destruct H1, H2.\n      apply AxiomII_P in H2; apply AxiomII.\n      split; auto; exists x0; tauto.\n    + apply AxiomII in H1; destruct H1, H2, H2.\n      apply AxiomII; split; auto.\n      exists x0; apply AxiomII_P; repeat split; auto.\n      apply Theorem49; split; auto; AssE x0.\nQed.\n\nLemma Lemma74 : forall (x y:Class),Ensemble x /\\ Ensemble y -> \n  ∪ \\{ λ z, (exists u, u∈x /\\ z = [u] × y) \\} = x × y.\nProof.\n  intros; apply AxiomI; split; intros.\n  - apply AxiomII in H0; destruct H0, H1, H1.\n    apply AxiomII in H2; destruct H2, H3, H3.\n    rewrite H4 in H1; PP H1 a b.\n    apply AxiomII_P in H5; destruct H5, H6.\n    apply AxiomII_P; repeat split; auto.\n    apply AxiomII in H6; destruct H6 as [_ H6].\n    AssE x1; apply Theorem19 in H8.\n    rewrite <- H6 in H3; auto.\n  - PP H0 a b; apply AxiomII_P in H1; destruct H1, H2.\n    apply AxiomII; split; auto.\n    exists (([a]) × y); split; AssE a.\n    + apply AxiomII_P; repeat split; auto.\n      apply AxiomII; intros; auto.\n    + apply AxiomII; split.\n      * apply Theorem73; split; try apply H; auto.\n      * exists a; split; auto.\nQed.\n\nTheorem Theorem74 : forall (x y:Class), \n  Ensemble x /\\ Ensemble y -> Ensemble x × y.\nProof.\n  intros; double H; double H0; destruct H0.\n  apply Ex_Lemma74 in H; destruct H, H, H3.\n  rewrite <- H3 in H0; apply AxiomV in H0; auto.\n  rewrite H4 in H0; apply AxiomVI in H0.\n  rewrite Lemma74 in H0; auto.\nQed.\n\nHint Resolve Theorem74 : set.\n\n\n(* Theorem75 : If f is a function and domain f is a set,\n   then f is a set. *)\n\nTheorem Theorem75 : forall f, \n  Function f /\\ Ensemble dom( f ) -> Ensemble f.\nProof.\n  intros; destruct H.\n  assert (Ensemble ran(f)); try apply AxiomV; auto.\n  assert (Ensemble (dom( f)) × (ran( f))).\n  { apply Theorem74; split; auto. }\n  apply Theorem33 with (x:=(dom( f ) × ran( f ))); auto.\n  unfold Included; intros; rewrite Theorem70 in H3; auto.\n  PP H3 a b; rewrite <- Theorem70 in H4; auto; AssE [a,b].\n  repeat split; auto; apply AxiomII_P; split; auto.\n  generalize (Property_dom a b f H4); intro.\n  generalize (Property_ran a b f H4); intro; tauto.\nQed.\n\nHint Resolve Theorem75 : set.\n\n\n(* Definition81 : x r y if and only if (x,y)∈r. *)\n\nDefinition Rrelation x r y : Prop := [x,y] ∈ r.\n\nHint Unfold Rrelation : set.\n\n\n(* Definition82 : r connects x if and only if when u and v belong to x\n   either u r v or v r u or v = u. *)\n\nDefinition Connect r x : Prop :=\n  forall u v, u∈x /\\ v∈x -> (Rrelation u r v) \\/ (Rrelation v r u) \\/ u=v.\n\nHint Unfold Connect : set.\n\n\n(* Definition83 : r is transitive in x if and only if, when u, v, and w\n   are members of x and u r v and v r w, then u r w. *)\n\nDefinition Transitive r x : Prop :=\n  forall u v w, (u∈x /\\ v∈x /\\ w∈x /\\ Rrelation u r v /\\ Rrelation v r w)\n  -> Rrelation u r w.\n\nHint Unfold Transitive: set.\n\n\n(* Definition84 : r is asymmetric in x if and only if, when u and v are\n   members of x and u r v, then it is not true that v r u. *)\n\nDefinition Asymmetric r x : Prop :=\n  forall u v, (u ∈ x /\\ v ∈ x /\\ Rrelation u r v) -> ~ Rrelation v r u.\n\nCorollary Property_Asy : forall r x u,\n  Asymmetric r x -> u ∈ x -> ~ Rrelation u r u.\nProof.\n  intros; intro.\n  unfold Asymmetric in H; specialize H with u u.\n  apply H; repeat split; auto.\nQed.\n\nHint Unfold Asymmetric: set.\n\n\n(* Theorem86 : z is an r-first member of x if and only if z∈x and if y∈x,\n   then it is false that y r z. *)\n\nDefinition FirstMember z r x : Prop :=\n  z∈x /\\ (forall y, y∈x -> ~ Rrelation y r z).\n\nHint Unfold FirstMember : set.\n\n\n(* Strict and non-strict well orders are closely related. A non-strict well \norder may be converted to a strict partial order by removing all relationships\nof the form a ≤ a. Conversely, a strict well order may be converted to a non-\nstrict well order by adjoining all relationships of that form. Thus, if \"≤\" is\na non-strict well order, then the corresponding strict partial order \"<\" is\nthe irreflexive kernel given by:\n\n  a < b if a ≤ b and a ≠ b\n\nConversely, if \"<\" is a strict well order, then the corresponding non-strict\nwell order \"≤\" is the reflexive closure given by:\n\n  a ≤ b if a < b or a = b.  *)\n\n(* Definition87 : r well-orders x if and only if r connects x and if y⊂x and\n   y≠Φ, then there is an r-first member of y. It is a strict well order. *)\n\nDefinition KWellOrder r x : Prop :=\n  Connect r x /\\ (forall y, y⊂x /\\ y≠Φ -> exists z, FirstMember z r y).\n\nHint Unfold KWellOrder : set.\n\n\n(* Theorem88 : If r well-orders x, then r is transitive in x and r is\n   asymmetric in x. *)\n\nLemma Lemma88 : forall x u v w,\n  Ensemble u -> Ensemble v -> Ensemble w -> x ∈ ([u] ∪ [v] ∪ [w]) ->\n  x = u \\/ x= v \\/ x = w.\nProof.\n  intros; apply Theorem19 in H; apply Theorem19 in H0; apply Theorem19 in H1.\n  apply AxiomII in H2; destruct H2, H3.\n  - left; apply AxiomII in H3; destruct H3; auto.\n  - apply AxiomII in H3; destruct H3, H4.\n    + right; left; apply AxiomII in H4; destruct H4; auto.\n    + right; right; apply AxiomII in H4; destruct H4; auto.\nQed.\n\nTheorem Theorem88 : forall r x,\n  KWellOrder r x -> Transitive r x /\\ Asymmetric r x .\nProof.\n  intros; generalize H; intro; unfold KWellOrder in H0; destruct H0.\n  assert (Asymmetric r x).\n  { unfold Asymmetric; intros; destruct H2, H3; AssE u; AssE v.\n    assert (([u | v] ⊂ x) /\\ ([u | v] ≠ Φ)).\n    { split.\n      - unfold Included; intros; apply AxiomII in H7; destruct H7, H8.\n        + apply Theorem19 in H5; apply AxiomII in H8; destruct H8.\n          rewrite H9; auto.\n        + apply Theorem19 in H6; apply AxiomII in H8; destruct H8.\n          rewrite H9; auto.\n        - apply Property_NotEmpty; exists u; apply AxiomII; split; auto.\n          left; apply AxiomII; split; auto. }\n    apply H1 in H7; destruct H7; unfold FirstMember in H7; destruct H7.\n    apply Theorem46 in H7; auto; destruct H7; subst x0.\n    - apply H8; auto; apply AxiomII; split; auto; right; apply AxiomII; auto.\n    - assert (u ∈ [u | v]).\n      { apply AxiomII; split; auto; left; apply AxiomII; split; auto. }\n      apply H8 in H7; auto. }\n  split; auto; unfold Transitive; intros.\n  - destruct H3, H4, H5, H6; unfold Connect in H0; specialize H0 with w u.\n    destruct H0 as [H0 | [H0 | H0]]; try split; auto.\n    + assert (([u] ∪ [v] ∪ [w] ⊂ x) /\\ ([u] ∪ [v] ∪ [w] ≠ Φ)).\n      { split; unfold Included; intros.\n        - apply AxiomII in H8; destruct H8 as [_ H8], H8.\n          + AssE u; apply Theorem19 in H9; apply AxiomII in H8; destruct H8.\n            rewrite H10; auto.\n          + apply AxiomII in H8; destruct H8 as [_ H8]; destruct H8.\n            * AssE v; apply Theorem19 in H9; apply AxiomII in H8.\n              destruct H8; rewrite H10; auto.\n            * AssE w; apply Theorem19 in H9; apply AxiomII in H8.\n              destruct H8; rewrite H10; auto.\n        - intro; generalize (Theorem16 u); intro.\n          apply H9; rewrite <- H8; apply AxiomII; split; Ens.\n          left; apply AxiomII; split; intros; auto; Ens. }\n      apply H1 in H8; destruct H8; unfold FirstMember in H8; destruct H8.\n      assert (u ∈ ([u] ∪ [v] ∪ [w])).\n      { apply Theorem4; left; apply AxiomII; split; Ens. }\n      assert (v ∈ ([u] ∪ [v] ∪ [w])).\n      { apply Theorem4; right; apply AxiomII; split; Ens.\n        left; apply AxiomII; split; Ens. }\n      assert (w ∈ ([u] ∪ [v] ∪ [w])).\n      { apply Theorem4; right; apply AxiomII; split; Ens.\n        right; apply AxiomII; split; Ens. }\n      apply Lemma88 in H8; Ens; destruct H8 as [H8 | [H8 | H8]]; subst x0.\n      * apply H9 in H12; contradiction.\n      * apply H9 in H10; contradiction.\n      * apply H9 in H11; contradiction.\n    + subst w; unfold Asymmetric in H2; absurd (Rrelation u r v); auto.\nQed.\n\nHint Resolve Theorem88: set.\n\n\n(* Definition89 : y is an r-section of x if and only if y⊂x, r well-orders x,\n   and for each u and v such that u∈x, v∈y, and u r v it is true that u∈y. *)\n\nDefinition Section y r x : Prop :=\n  y ⊂ x /\\ KWellOrder r x /\\\n  (forall u v, (u ∈ x /\\ v ∈ y /\\ Rrelation u r v) -> u ∈ y).\n\nHint Unfold Section : set.\n\n\n(* Theorem91 : If y is an r-section of x an y≠x, then y = {u : u∈x and u r v}\n   for some v in x. *)\n\nTheorem Theorem91 : forall x y r,\n  Section y r x /\\ y ≠ x ->\n  (exists v, v ∈ x /\\ y = \\{ λ u, u ∈ x /\\ Rrelation u r v \\}).\nProof.\n  intros; destruct H.\n  assert (exists v, FirstMember v r (x ~ y)).\n  { unfold Section, KWellOrder in H; destruct H, H1, H1.\n    assert ((x ~ y) ⊂ x).\n    { red; intros; apply AxiomII in H4; tauto. }\n    generalize (classic (x ~ y = Φ)); intro; destruct H5.\n    - apply Property_Φ in H; apply H in H5.\n      apply Property_Ineq in H0; contradiction.\n    - apply H3; split; auto. }\n  destruct H1; unfold FirstMember in H1; destruct H1; exists x0.\n  apply AxiomII in H1; destruct H1, H3; split; auto.\n  apply AxiomI; split; intros.\n  - unfold Section in H; destruct H, H6; apply AxiomII.\n    repeat split; Ens; assert (z ∈ x); auto.\n    unfold KWellOrder, Connect in H6; destruct H6 as [H6 _].\n    specialize H6 with x0 z; destruct H6 as [H6|[H6|H6]]; auto.\n    + assert (x0 ∈ y).\n      { apply H7 with z; repeat split; auto. }\n      apply AxiomII in H4; destruct H4; contradiction.\n    + apply AxiomII in H4; destruct H4; subst x0; contradiction.\n  - apply AxiomII in H5; destruct H5, H6.\n    generalize (classic (z ∈ (x ~ y))); intro; destruct H8.\n    + apply H2 in H8; contradiction.\n    + generalize (classic (z ∈ y)); intro; destruct H9; auto.\n      elim H8; apply AxiomII; repeat split; auto; apply AxiomII; tauto.\nQed.\n\nHint Resolve Theorem91 : set.\n\n\n(* Theorem92 : If x and y are r-sections of z, then x⊂y or y⊂x. *)\n\nTheorem Theorem92 : forall x y z r,\n  Section x r z /\\ Section y r z -> x ⊂ y \\/ y ⊂ x.\nProof.\n  intros; destruct  H.\n  generalize (classic (x = z)); intro; destruct H1.\n  - right; red in H0; subst z; tauto.\n  - generalize (classic (y = z)); intro; destruct H2.\n    + left; red in H; subst z; tauto.\n    + apply Lemma_xy with (x:=(Section x r z)) in H1; auto.\n      apply Lemma_xy with (x:=(Section y r z)) in H2; auto.\n      apply Theorem91 in H1; destruct H1, H1; apply Theorem91 in H2.\n      destruct H2, H2; unfold Section in H; destruct H as [_ [H _]].\n      unfold KWellOrder in H; destruct H as [H _]; unfold Section in H0.\n      destruct H0, H5; apply Theorem88 in H5; destruct H5.\n      assert ((x0 ∈ z) /\\ (x1 ∈ z)); try split; auto.\n      unfold Connect in H; generalize (H _ _ H8); intros.\n      destruct H9 as [H9 | [H9 | H9]].\n      * left; unfold Included; intros; rewrite H3 in H10.\n        apply AxiomII in H10; destruct H10, H11; rewrite H4; apply AxiomII.\n        repeat split; auto; apply H5 with x0; auto.\n      * right; unfold Included; intros; rewrite H4 in H10.\n        apply AxiomII in H10; destruct H10, H11; rewrite H3; apply AxiomII.\n        repeat split; auto; apply H5 with x1; auto.\n      * right; subst x0; rewrite H3, H4; unfold Included; intros; auto.\nQed.\n\nHint Resolve Theorem92 : set.\n\n\n(* Definition93 : f is r-s order preserving if and only if f is a function,\n   r well-orders domain f, s well-orders range f, and f(u) s f(v) whenever u\n   and v are members of domain f such that u r v. *)\n\nDefinition Order_Pr f r s : Prop := \n  Function f /\\ KWellOrder r dom(f) /\\ KWellOrder s ran(f) /\\\n  (forall u v, u ∈ dom(f) /\\ v ∈ dom(f) /\\ Rrelation u r v ->\n  Rrelation f[u] s f[v]).\n\nHint Unfold Order_Pr : set.\n\n\n(* Definition95 : f is a 1_1 function iff both f and f ⁻¹ are functions.*)\n\nDefinition Function1_1 f : Prop := Function f /\\ Function (f ⁻¹).\n\nCorollary Property_F11 : forall f,\n  dom(f⁻¹) = ran(f) /\\ ran(f⁻¹) = dom(f).\nProof.\n  intros; unfold Domain, Range; split.\n  - apply AxiomI; split; intros.\n    + apply AxiomII in H; destruct H, H0; apply AxiomII_P in H0.\n      destruct H0; apply AxiomII; split; Ens.\n    + apply AxiomII in H; destruct H, H0; apply AxiomII; split; auto.\n      exists x; apply AxiomII_P; split; auto; apply Theorem49.\n      AssE [x,z]; apply Theorem49 in H1; destruct H1; auto.\n  - apply AxiomI; split; intros.\n    + apply AxiomII in H; destruct H, H0; apply AxiomII_P in H0.\n      destruct H0; apply AxiomII; split; Ens.\n    + apply AxiomII in H; destruct H, H0; apply AxiomII; split; auto.\n      exists x; apply AxiomII_P; split; auto; apply Theorem49.\n      AssE [z,x]; apply Theorem49 in H1; destruct H1; auto.\nQed.\n\nHint Unfold Function1_1 : set.\n\n\n(* Theorem96 : If f is r-s order preserving, then f is a 1_1 function and\n   f ⁻¹ is s-r order preserving. *)\n\nLemma Lemma96 : forall f, dom( f) = ran( f ⁻¹).\nProof.\n  intros; apply AxiomI; split; intros.\n  - apply AxiomII in H; destruct H, H0; apply AxiomII; split; auto.\n    exists x; apply AxiomII_P; split; auto; apply Lemma61; Ens.\n  - apply AxiomII in H; destruct H, H0.\n    apply AxiomII; split; auto; exists x; apply AxiomII_P in H0; tauto.\nQed.\n\nLemma Lemma96' : forall f, ran( f) = dom( f ⁻¹).\nProof.\n  intros; apply AxiomI; split; intros.\n  - apply AxiomII in H; destruct H, H0; apply AxiomII; split; auto.\n    exists x; apply AxiomII_P; split; auto; apply Lemma61; Ens.\n  - apply AxiomII in H; destruct H, H0.\n    apply AxiomII; split; auto; exists x; apply AxiomII_P in H0; tauto.\nQed.\n\nLemma Lemma96'' : forall f u,\n  Function f -> Function f ⁻¹ -> u ∈ ran(f) ->  (f⁻¹)[u] ∈ dom(f).\nProof.\n  intros; rewrite Lemma96' in H1;  apply Property_Value in H1; auto.\n  apply AxiomII_P in H1; destruct H1; apply Property_dom in H2; auto.\nQed.\n\nLemma Lemma96''' : forall f u,\n  Function f -> Function f ⁻¹ -> u ∈ ran(f) -> u = f  [(f ⁻¹) [u]].\nProof.\n  intros; generalize (Lemma96'' _ _ H H0 H1); intro.\n  apply Property_Value in H2; auto; rewrite Lemma96' in H1.\n  apply Property_Value in H1; auto; apply AxiomII_P in H1; destruct H1.\n  red in H; destruct H; eapply H4; eauto.\nQed.\n\nTheorem Theorem96 : forall f r s,\n  Order_Pr f r s -> Function1_1 f /\\ Order_Pr (f ⁻¹) s r.\nProof.\n  intros; unfold Order_Pr in H; destruct H, H0, H1.\n  assert (Function1_1 f).\n  { unfold Function1_1; split; auto; unfold Function; split; intros.\n    - red; intros; PP H3 a b; Ens.\n    - destruct H3; rename y into u; rename z into v.\n      apply AxiomII_P in H3; destruct H3; apply AxiomII_P in H4; destruct H4.\n      double H5; double H6; apply Property_dom in H5; apply Property_dom in H6.\n      double H7; double H8; apply Property_dom in H7; apply Property_dom in H8.\n      rewrite Theorem70 in H9; auto; apply AxiomII_P in H9.\n      destruct H9 as [_ H9]; rewrite Theorem70 in H10; auto.\n      apply AxiomII_P in H10; destruct H10 as [_ H10]; rewrite H10 in H9.\n      symmetry in H9; clear H10; apply Property_Value in H7; auto.\n      apply Property_Value in H8; auto; apply Property_ran in H7.\n      apply Property_ran in H8; double H0; double H1; apply Theorem88 in H11.\n      destruct H11; unfold KWellOrder in H1; destruct H1 as [H1 _].\n      unfold Connect in H1; specialize H1 with f [u] f [v]; destruct H0.\n      unfold Connect in H0; specialize H0 with u v.\n      destruct H0 as [H0 | [H0 | H0]]; try split; auto.\n      + assert (Rrelation f [u] s f [v]); try apply H2; try tauto.\n        rewrite H9 in H14; generalize (Property_Asy _ _ _ H12 H8); tauto.\n      + assert (Rrelation f [v] s f [u]); try apply H2; try tauto.\n        rewrite H9 in H14; generalize (Property_Asy _ _ _ H12 H8); tauto. }\n  split; auto.\n  - unfold Function1_1 in H3; destruct H3 as [_ H3]; unfold Order_Pr; intros.\n    repeat rewrite <- Lemma96; repeat rewrite <- Lemma96'; split; auto.\n    split; auto; split; intros; auto; destruct H4, H5.\n    assert ((f ⁻¹) [u] ∈ dom(f)); try apply Lemma96''; auto.\n    assert ((f ⁻¹) [v] ∈ dom(f)); try apply Lemma96''; auto.\n    unfold KWellOrder in H0; destruct H0 as [H0 _]; unfold Connect in H0.\n    specialize H0 with (f ⁻¹) [u] (f ⁻¹) [v].\n    destruct H0 as [H0 | [H0 | H0]]; try split; auto.\n    + assert (Rrelation f  [(f ⁻¹) [v]] s f [(f ⁻¹) [u]] ); auto.\n      rewrite <- Lemma96''' in H9; rewrite <- Lemma96''' in H9; auto.\n      apply Theorem88 in H1; destruct H1; unfold Asymmetric in H10.\n      generalize (Lemma_xy _ _ H5 (Lemma_xy _ _ H4 H9)); intro.\n      generalize (H10 _ _ H11); intro; contradiction.\n    + assert (f [(f ⁻¹) [u]] = f [(f ⁻¹) [v]]); rewrite H0; auto.\n      rewrite <- Lemma96''' in H9; rewrite <- Lemma96''' in H9; auto.\n      apply Theorem88 in H1; destruct H1.\n      rewrite H9 in H6; apply Property_Asy with (r:=s) in H5; tauto.\nQed.\n\nHint Resolve Theorem96 : set.\n\n\n(* Theorem97 : If f and g are r-s order preserving, domain f and domain g are r-\n   sections of x and range f and range g are s-sections of y, then f⊂g or g⊂f. *)\n\nLemma Lemma97 : forall y r x,\n  KWellOrder r x -> y ⊂ x -> KWellOrder r y.\nProof.\n  intros; unfold KWellOrder in H; destruct H.\n  unfold KWellOrder; intros; split; intros.\n  - red; intros; apply H; destruct H2; split; auto.\n  - specialize H1 with y0; apply H1; destruct H2.\n    split; auto; eapply Theorem28; eauto.\nQed.\n\nLemma Lemma97' :  forall f g u r s v x y, \n  Order_Pr f r s /\\ Order_Pr g r s ->\n  FirstMember u r (\\{ λ a ,a ∈ (dom( f) ∩ dom( g)) /\\ f [a] ≠ g [a] \\}) ->\n  g[v] ∈ ran( g) -> Section ran( f) s y -> Section dom( f) r x ->\n  Section dom( g) r x -> Rrelation g [v] s g [u] -> f[u] = g[v] ->\n  f ⊂ g \\/ g ⊂ f.\nProof.\n  intros.\n  unfold FirstMember in H0; destruct H0; apply AxiomII in H0; destruct H0, H8.\n  apply AxiomII in H8; destruct H8 as [_ [H8 H10]].\n  destruct H; unfold Order_Pr in H, H11.\n  apply Property_Value in H8; apply Property_Value in H10; try tauto.\n  apply Property_ran in H8; apply Property_ran in H10; auto.\n  assert (Rrelation v r u).\n  { elim H11; intros; clear H13; apply Theorem96 in H11.\n    destruct H11 as [_ H11]; red in H11; destruct H11 as [H11 [_ [_ H13]]].\n    double H1; double H10; rewrite Lemma96' in H14; rewrite Lemma96' in H15.\n    apply Property_Value' in H10; auto; apply Property_dom in H10.\n    rewrite Lemma96 in H10; apply Property_Value' in H1; auto.\n    apply Property_dom in H1; rewrite Lemma96 in H1.\n    rewrite Lemma96''' with (f:= g⁻¹); try rewrite Theorem61; auto; pattern v.\n    rewrite Lemma96''' with (f:= g⁻¹); try rewrite Theorem61; auto. }\n  assert (v ∈ \\{ λ a, a ∈ (dom( f) ∩ dom( g)) /\\ f [a] ≠ g [a] \\}).\n  { apply Property_Value' in H1; try tauto; apply Property_dom in H1.\n    apply Property_Value' in H8; try tauto; apply Property_dom in H8.\n    apply AxiomII; repeat split; try Ens; try intro.\n    - apply AxiomII; repeat split; try Ens; apply H3 with u; repeat split; auto.\n      unfold Section in H4; apply H4; auto.\n    - assert (v ∈ dom(f)).\n      { apply H3 with u; repeat split; auto; apply H4 in H1; auto. }\n      assert (Rrelation f [v] s f [u]). { apply H; repeat split; auto. }\n      rewrite H13 in H15; unfold Section in H2; destruct H2, H16.\n      generalize (Lemma97 _ _ _ H16 H2); intro; apply Theorem88 in H18.\n      destruct H18; rewrite <- H13 in H15; rewrite H6 in H15.\n      rewrite <- H13 in H15; apply Property_Value in H14; try tauto.\n      apply Property_ran in H14; generalize (Property_Asy _ _ _ H19 H14).\n      intro; contradiction. }\n  apply H7 in H13; contradiction.\nQed.\n\nTheorem Theorem97 : forall f g r s x y,\n  Order_Pr f r s /\\ Order_Pr g r s -> Section dom(f) r x /\\ Section dom(g) r x\n  -> Section ran(f) s y /\\ Section ran(g) s y -> f ⊂ g \\/ g ⊂ f.\nProof.\n  intros; destruct H, H0, H1.\n  assert (Order_Pr (g ⁻¹) s r). { apply Theorem96 in H2; tauto. }\n  generalize (classic (\\{ λ a, a ∈ (dom(f)∩dom(g)) /\\ f[a]≠g[a]\\} = Φ)); intro.\n  destruct H6.\n  - generalize (Lemma_xy _ _ H0 H3); intro.\n    unfold Order_Pr in H; destruct H; unfold Order_Pr in H2; destruct H2.\n    generalize (Theorem92 _ _ _ _ H7); intro; destruct H10.\n    + left; unfold Included; intros.\n      rewrite Theorem70 in H11; auto; PP H11 a b; double H12.\n      rewrite <- Theorem70 in H12; auto; apply Property_dom in H12.\n      apply AxiomII_P in H13; destruct H13; rewrite Theorem70; auto.\n      apply AxiomII_P; split; auto; rewrite H14.\n      generalize (classic (f[a] = g[a])); intro; destruct H15; auto.\n      assert (a ∈ \\{λ a, a ∈ (dom(f) ∩ dom(g)) /\\ f [a] ≠ g [a]\\}).\n      { apply AxiomII; split; Ens; split; auto; apply Theorem30 in H10.\n        rewrite H10; auto. }\n      eapply AxiomI in H6; apply H6 in H16.\n      generalize (Theorem16 a); contradiction.\n    + right; unfold Included; intros.\n      rewrite Theorem70 in H11; auto; PP H11 a b; double H12.\n      rewrite <- Theorem70 in H12; auto; apply Property_dom in H12.\n      apply AxiomII_P in H13; destruct H13; rewrite Theorem70; auto.\n      apply AxiomII_P; split; auto; rewrite H14.\n      generalize (classic (f[a] = g[a])); intro; destruct H15; auto.\n      assert (a ∈ \\{λ a, a ∈ (dom(f) ∩ dom(g)) /\\ f [a] ≠ g [a]\\}).\n      { apply AxiomII; split; Ens; split; auto; apply Theorem30 in H10.\n        rewrite Theorem6' in H10; rewrite H10; auto. }\n      eapply AxiomI in H6; apply H6 in H16.\n      generalize (Theorem16 a); contradiction.\n  - assert (\\{ λ a, a ∈ (dom(f) ∩ dom(g)) /\\ f [a] ≠ g [a] \\} ⊂ dom(f)).\n    { unfold Included; intros; apply AxiomII in H7; destruct H7, H8.\n      apply Theorem4' in H8; tauto. }\n    double H2; double H; unfold Order_Pr in H9; destruct H9, H10, H11.\n    unfold KWellOrder in H10; destruct H10.\n    generalize (Lemma_xy _ _ H7 H6); intro; apply H13 in H14.\n    destruct H14 as [u H14]; double H14; unfold FirstMember in H15.\n    destruct H15; apply AxiomII in H15; destruct H15, H17.\n    unfold Order_Pr in H2; destruct H2 as [H19 [_ [H2 _]]].\n    apply AxiomII in H17; destruct H17 as [_ [H17 H20]]; double H17; double H20.\n    apply Property_Value in H17; apply Property_Value in H20; auto.\n    apply Property_ran in H17; apply Property_ran in H20.\n    generalize (Lemma_xy _ _ H1 H4); intro.\n    apply Theorem92 in H23; auto; destruct H23.\n    + apply H23 in H17; double H17; apply AxiomII in H17.\n      destruct H17 as [_ [v H17]]; rewrite Theorem70 in H17; auto.\n      apply AxiomII_P in H17; destruct H17; rewrite H25 in H24.\n      generalize (Lemma_xy _ _ H24 H20); intro; unfold KWellOrder in H2.\n      destruct H2 as [H2 _]; unfold Connect in H2; apply H2 in H26.\n      destruct H26 as [H26 | [H26 | H26]].\n      * apply (Lemma97' f g u r s v x y); auto.\n      * red in H1; destruct H1 as [_ [_ H1]]; rewrite <- H25 in H26.\n        assert (g [u] ∈ ran( f)).\n        { apply H1 with f [u]; repeat split; auto; unfold Section in H4.\n          apply H4; apply Property_ran with u; apply Property_Value; auto.\n          apply Property_ran with u; apply Property_Value; auto. }\n        apply AxiomII in H27; destruct H27 as [_ [v1 H27]]; double H27.\n        apply Property_dom in H28; apply Property_Value in H28; auto.\n        rewrite Theorem70 in H27; auto; apply AxiomII_P in H27.\n        destruct H27 as [_ H27]; rewrite H27 in H26.\n        assert (g ⊂ f \\/ f ⊂ g).\n        { apply (Lemma97' g f u r s v1 x y); try tauto; try rewrite Theorem6'.\n          assert (\\{λ a, a ∈ (dom(f) ∩ dom(g)) /\\ f[a] ≠ g[a]\\} =\n                  \\{λ a, a ∈ (dom(f) ∩ dom(g)) /\\ g[a] ≠ f[a] \\}).\n          { apply AxiomI; split; intros; apply AxiomII in H29; apply AxiomII.\n            - repeat split; try tauto; apply Property_Ineq; tauto.\n            - repeat split; try tauto; apply Property_Ineq; tauto. }\n          rewrite <- H29; auto. apply Property_ran in H28; auto. }\n        tauto.\n      * rewrite <- H25 in H26; contradiction.\n    + apply H23 in H20; double H18.\n      apply AxiomII in H20; destruct H20 as [_ [v H20]]; double H20.\n      apply Property_dom in H25; apply Property_Value in H25; auto.\n      assert (f [v] = g [u]). { eapply H9; eauto. }\n      apply Property_ran in H20; generalize (Lemma_xy _ _ H17 H20); intro.\n      unfold KWellOrder in H11; destruct H11 as [H11 _]; apply H11 in H27.\n      destruct H27 as [H27 | [H27 | H27]]; try contradiction.\n      * unfold Section in H4; destruct H4 as [_ [_ H4]].\n        assert (f[u] ∈ ran( g)).\n        { apply H4 with g[u]; repeat split; auto. red in H1; apply H1.\n          apply Property_ran with u; apply Property_Value; auto.\n          apply Property_ran with u; apply Property_Value; auto. }\n        apply AxiomII in H28; destruct H28 as [_ [v1 H28]]; double H28.\n        apply Property_dom in H29; apply Property_Value in H29; auto.\n        rewrite Theorem70 in H28; auto; apply AxiomII_P in H28; destruct H28.\n        rewrite H30 in H27; apply (Lemma97' f g u r s v1 x y); try tauto; auto.\n        apply Property_ran with v1; auto.\n      * assert (g ⊂ f \\/ f ⊂ g).\n        { rewrite <- H26 in H27, H20.\n          apply (Lemma97' g f u r s v x y); try tauto; auto; rewrite Theorem6'.\n          assert (\\{λ a, a ∈ (dom(f) ∩ dom(g)) /\\ f[a] ≠ g[a]\\} =\n                  \\{λ a, a ∈ (dom(f) ∩ dom(g)) /\\ g[a] ≠ f[a]\\}).\n          { apply AxiomI; split; intros; apply AxiomII in H28; apply AxiomII.\n            - repeat split; try tauto; apply Property_Ineq; tauto.\n            - repeat split; try tauto; apply Property_Ineq; tauto. }\n          rewrite <- H28; auto. }\n        tauto.\nQed.\n\nHint Resolve Theorem97 : set.\n\n\n(* Definition98 : f is r-s order preserving in x and y if and only if r\n   well-orders x, s well-orders y, f is r-s order preserving, domain f is an\n   r-section of x, and range f is an s-section of y. *)\n\nDefinition Order_PXY  f x y r s : Prop :=\n  KWellOrder r x /\\ KWellOrder s y /\\ Order_Pr f r s /\\\n  Section dom(f) r x /\\ Section ran(f) s y.\n\nHint Unfold Order_PXY : set.\n\n\n(* Theorem99 : If r well-orders x and s well-orders y, then there is a function\n   f which is r-s order preserving in x and y such that either domain f = x or\n   range f = y.  *)\n\nDefinition En_f x y r s :=\n  \\{\\ λ u v, u ∈ x /\\ (exists g, Function g /\\ Order_PXY g x y r s /\\\n      u ∈ dom(g) /\\ [u,v] ∈ g ) \\}\\.\n\nLemma Lemma99 : forall y r x,\n  KWellOrder r x -> Section y r x -> KWellOrder r y.\nProof.\n  intros; red in H0; eapply Lemma97; eauto; tauto.\nQed.\n\nLemma Lemma99' : forall a b f z,\n  ~ a ∈ dom(f) -> Ensemble a -> Ensemble b -> (z ∈ dom(f) -> \n  (f ∪ [[a,b]]) [z] = f [z]).\nProof.\n  intros.\n  apply AxiomI; split; intros; apply AxiomII in H3; destruct H3;\n  apply AxiomII; split; intros; auto.\n  - apply H4; apply AxiomII in H5; destruct H5.\n    apply AxiomII; split; auto; apply AxiomII; split; Ens.\n  - apply H4; apply AxiomII in H5; destruct H5; apply AxiomII; split; auto.\n    apply AxiomII in H6; destruct H6, H7; auto; apply AxiomII in H7.\n    destruct H7; assert([a,b]∈μ). { apply Theorem19; apply Theorem49; tauto. }\n    generalize (H8 H9); intro; apply Theorem49 in H6.\n    apply Theorem55 in H10; auto; destruct H10.\n    rewrite H10 in H2; contradiction.\nQed.\n\nLemma Lemma99'' : forall a b f z,\n  ~ a ∈ dom(f) -> Ensemble a -> Ensemble b -> (z=a -> (f ∪ [[a,b]]) [z] = b).\nProof.\n  intros; apply AxiomI; split; intros; subst z.\n  - apply AxiomII in H3; destruct H3; apply H3; apply AxiomII; split; auto.\n    apply AxiomII; split; try apply Theorem49; try tauto.\n    right; apply AxiomII; split; try apply Theorem49; try tauto.\n  - apply AxiomII; split; intros; Ens; apply AxiomII in H2; destruct H2;\n    apply AxiomII in H4; destruct H4, H5.\n    + apply Property_dom in H5; contradiction.\n    + apply AxiomII in H5; destruct H5.\n      assert ([a, b] ∈ μ). { apply Theorem19; apply Theorem49; tauto. }\n      generalize (H6 H7); intro; apply Theorem49 in H4.\n      apply Theorem55 in H8; auto; destruct H8; rewrite H9; auto.\nQed.\n\nLemma Lemma99''' : forall y r x a b,\n  Section y r x -> a ∈ y -> ~ b ∈ y -> b ∈ x -> Rrelation a r b.\nProof.\n  intros; unfold Section in H; destruct H, H3.\n  unfold KWellOrder in H3; destruct H3; unfold Connect in H3.\n  assert (a ∈ x); auto; generalize (Lemma_xy _ _ H2 H6); intro.\n  apply H3 in H7; destruct H7 as [H7 | [H7 | H7]]; auto.\n  - assert (b ∈ y). { eapply H4; eauto. } contradiction.\n  - rewrite H7 in H1; contradiction.\nQed.\n\nTheorem Theorem99 : forall r s x y,\n  KWellOrder r x /\\ KWellOrder s y -> exists f, Function f /\\\n  Order_PXY f x y r s /\\ (dom(f) = x \\/ ran(f) = y).\nProof.\n  intros.\n  assert (Function (En_f x y r s)).\n  { unfold Function; split; intros.\n    - unfold Relation; intros; PP H0 a b; eauto.\n    - destruct H0; apply AxiomII_P in H0; destruct H0, H2, H3, H3, H4, H5.\n      unfold Order_PXY in H4; destruct H4 as [_ [_ [H4 [H7 H8]]]].\n      apply AxiomII_P in H1; destruct H1, H9, H10, H10, H11, H12.\n      unfold Order_PXY in H11; destruct H11 as [_ [_ [H11 [H14 H15]]]].\n      assert (x1 ⊂ x2 \\/ x2 ⊂ x1). { apply (Theorem97 x1 x2 r s x y); tauto. }\n      destruct H16.\n      + apply H16 in H6; eapply H10; eauto.\n      + apply H16 in H13; eapply H3; eauto. }\n  exists (En_f x y r s); split; auto.\n  assert (Section (dom(En_f x y r s)) r x).\n  { unfold Section; split.\n    - unfold Included; intros; apply AxiomII in H1; destruct H1, H2.\n      apply AxiomII_P in H2; tauto.\n    - split; try tauto; intros; destruct H1, H2; apply AxiomII in H2.\n      destruct H2, H4; apply AxiomII_P in H4; destruct H4, H5, H6.\n      apply AxiomII; split; Ens; exists ((En_f x y r s)[u]).\n      apply Property_Value; auto; apply AxiomII; split; Ens.\n      assert (u ∈ dom( x1)).\n      { destruct H6, H7; unfold Order_PXY in H7; destruct H7, H9, H10, H11.\n        unfold Section in H11; destruct H11, H13; apply H14 with v.\n        destruct H8; tauto. }\n      exists (x1[u]); apply AxiomII_P; repeat split; auto.\n      + apply Theorem49; split; Ens.\n        apply Theorem19; apply Theorem69; try tauto.\n      + exists x1; split; try tauto; split; try tauto.\n        split; auto; apply Property_Value; try tauto. }\n  assert (Section (ran(En_f x y r s)) s y).\n  { unfold Section; split.\n    - unfold Included; intros; apply AxiomII in H2; destruct H2, H3.\n      apply AxiomII_P in H3; destruct H3, H4, H5, H5, H6, H7.\n      unfold Order_PXY in H6; destruct H6 as [_ [_ [_ [_ H6]]]].\n      destruct H6 as [H6 _]; apply Property_ran in H8; auto.\n    - split; try tauto; intros; destruct H2, H3; apply AxiomII in H3.\n      destruct H3, H5; apply AxiomII_P in H5; destruct H5, H6, H7.\n      apply AxiomII; split; Ens; exists (x1⁻¹[u]); apply AxiomII_P.\n      destruct H7 as [H7 [H8 [H9 H10]]]; double H8; unfold Order_PXY in H8.\n      destruct H8 as [_ [_ [H12 [H13 H8]]]]; generalize H11 as H20; intro.\n      unfold Order_PXY in H11; destruct H11 as [H11 [_ H19]].\n      unfold Section in H8; destruct H8 as [H8 [_ H15]].\n      assert (u ∈ ran( x1)).\n      { apply Property_ran in H10; apply H15 with v; tauto. }\n      generalize H14 as H21; intro; apply Theorem96 in H12; destruct H12.\n      unfold Function1_1 in H12; destruct H12; apply Lemma96'' in H14; auto.\n      repeat split; auto.\n      + apply Theorem49; split; Ens.\n      + apply Property_Value in H14; auto; rewrite <- Lemma96''' in H14; auto.\n        apply Property_dom in H14; destruct H19 as [_ [[H19 _] _]]; auto.\n      + exists x1; split; try tauto; split; try tauto; split; auto.\n        apply Property_Value in H14; auto; rewrite <- Lemma96''' in H14; auto. }\n  assert (Order_PXY (En_f x y r s) x y r s).\n  { unfold Order_PXY; split; try tauto; split; try tauto; split; [idtac|tauto].\n    unfold Order_Pr; split; auto; destruct H; split; try eapply Lemma99; eauto.\n    split; intros; try eapply Lemma99; eauto; destruct H4, H5; double H4.\n    double H5; apply Property_Value in H4; apply Property_Value in H5; auto.\n    apply AxiomII_P in H4; destruct H4 as [H4 [H9 [g1 [H10 [H11 [H12 H13]]]]]].\n    apply AxiomII_P in H5; destruct H5 as [H5 [H14 [g2 [H15 [H16 [H17 H18]]]]]].\n    rewrite Theorem70 in H13; auto; apply AxiomII_P in H13.\n    destruct H13 as [_ H13]; rewrite Theorem70 in H18; auto.\n    apply AxiomII_P in H18; destruct H18 as [_ H18].\n    rewrite H13, H18; clear H13 H18.\n    unfold Order_PXY in H11; destruct H11 as [_ [_ [H11 [H13 H18]]]].\n    unfold Order_PXY in H16; destruct H16 as [_ [_ [H16 [H19 H20]]]].\n    generalize (Lemma_xy _ _ H11 H16); intro.\n    apply (Theorem97 g1 g2 r s x y) in H21; apply Property_Value in H12; auto.\n    apply Property_Value in H17; auto; destruct H21.\n    - apply H21 in H12; double H12; rewrite Theorem70 in H12; auto.\n      apply AxiomII_P in H12; destruct H12 as [_ H12]; rewrite H12.\n      apply Property_dom in H22; apply Property_dom in H17; apply H16; tauto.\n    - apply H21 in H17; double H17; rewrite Theorem70 in H17; auto.\n      apply AxiomII_P in H17; destruct H17 as [_ H17]; rewrite H17.\n      apply Property_dom in H12; apply Property_dom in H22; apply H11; tauto. }\n  split; auto; apply NNPP; intro; apply not_or_and in H4; destruct H4.\n  assert (exists u, FirstMember u r (x ~ dom( En_f x y r s))).\n  { unfold Section in H1; destruct H1, H6.\n    assert ((x ~ dom( En_f x y r s)) ⊂ x).\n    { red; intros; apply AxiomII in H8; tauto. }\n    assert ((x ~ dom( En_f x y r s)) <> Φ).\n    { intro; apply Property_Φ in H1; apply H1 in H9; apply H4; auto. }\n    generalize (Lemma97 _ _ _ H6 H8); intro; apply H10.\n    repeat split; auto; red; auto. }\n  assert (exists v, FirstMember v s (y ~ ran( En_f x y r s))).\n  { unfold Section in H2; destruct H2, H7.\n    assert ((y ~ ran( En_f x y r s)) ⊂ y).\n    { red; intros; apply AxiomII in H9; tauto. }\n    assert ((y ~ ran( En_f x y r s)) <> Φ).\n    { intro; apply Property_Φ in H2; apply H2 in H10; apply H5; auto. }\n    generalize (Lemma97 _ _ _ H7 H9); intro; apply H11.\n    repeat split; auto; red; auto. }\n  destruct H6 as [u H6]; destruct H7 as [v H7].\n  unfold FirstMember in H6; unfold FirstMember in H7; destruct H6, H7.\n  apply AxiomII in H6; destruct H6 as [_ [H6 H10]]; apply AxiomII in H10.\n  destruct H10 as [_ H10]; apply H10; apply AxiomII; split; Ens.\n  exists v; apply AxiomII_P; split; try apply Theorem49; split; try Ens.\n  exists ((En_f x y r s) ∪ [[u,v]]).\n  assert (Function (En_f x y r s ∪ [[u, v]])).\n  { assert ([u, v] ∈ μ) as H18.\n    { apply Theorem19; apply Theorem49; split; try Ens. }\n    unfold Function; split; intros.\n    - unfold Relation; intros.\n      apply AxiomII in H11; destruct H11 as [H11 [H12 | H12]].\n      + PP H12 a b; eauto.\n      + apply AxiomII in H12; exists u,v; apply H12; auto.\n    - destruct H11; apply AxiomII in H11; apply AxiomII in H12.\n      destruct H11 as [H11 [H13 | H13]], H12 as [H12 [H14 | H14]].\n      + unfold Function in H0; eapply H0; eauto.\n      + apply Property_dom in H13; apply AxiomII in H14; destruct H14.\n        apply Theorem55 in H15; apply Theorem49 in H12; auto.\n        destruct H15; rewrite H15 in H13; contradiction.\n      + apply Property_dom in H14; apply AxiomII in H13; destruct H13.\n        apply Theorem55 in H15; apply Theorem49 in H11; auto.\n        destruct H15; rewrite H15 in H14; contradiction.\n      + apply AxiomII in H13; destruct H13; apply Theorem49 in H13.\n        apply Theorem55 in H15; auto; apply AxiomII in H14; destruct H14.\n        apply Theorem55 in H16; apply Theorem49 in H12; auto.\n        destruct H15, H16; rewrite H17; auto. }\n  split; auto.\n  assert (Section (dom(En_f x y r s ∪ [[u, v]])) r x).\n  { unfold Section; split.\n    - unfold Included; intros; apply AxiomII in H12; destruct H12, H13.\n      apply AxiomII in H13; destruct H13, H14.\n      + apply Property_dom in H14; unfold Section in H1; apply H1; auto.\n      + apply AxiomII in H14; destruct H14.\n        assert ([u,v] ∈ μ). { apply Theorem19; apply Theorem49; split; Ens. }\n        apply H15 in H16; apply Theorem49 in H13; apply Theorem55 in H16; auto.\n        destruct H16; rewrite H16; auto.\n    - split; try tauto; intros; destruct H12, H13; apply AxiomII in H13.\n      destruct H13, H15; apply AxiomII in H15; destruct H15, H16.\n      + apply AxiomII; split; Ens.\n        assert ([u0,(En_f x y r s)[u0]] ∈ (En_f x y r s)).\n        { apply Property_dom in H16; apply Property_Value; auto.\n          apply H1 with v0; repeat split; auto. }\n        exists (En_f x y r s)[u0]; apply AxiomII; split; Ens.\n      + apply AxiomII in H16; destruct H16.\n        assert ([u,v] ∈ μ). { apply Theorem19; apply Theorem49; split; Ens. }\n        apply H17 in H18; apply Theorem49 in H16; apply Theorem55 in H18; auto.\n        destruct H18; subst v0.\n        assert ([u0,(En_f x y r s)[u0]] ∈ (En_f x y r s)).\n        { apply Property_Value; auto.\n          generalize (classic (u0 ∈ dom( En_f x y r s))); intro.\n          destruct H18; auto; absurd (Rrelation u0 r u); auto.\n          apply H8; apply AxiomII; repeat split; Ens.\n          apply AxiomII; split; Ens. }\n        apply AxiomII; split; Ens; exists ((En_f x y r s)[u0]).\n        apply AxiomII; split; Ens. }\n  assert (Section (ran(En_f x y r s ∪ [[u, v]])) s y).\n  { unfold Section; split.\n    - unfold Included; intros; apply AxiomII in H13; destruct H13, H14.\n      apply AxiomII in H7; destruct H7 as [_ [H7 _]] .\n      apply AxiomII in H14; destruct H14, H15.\n      + apply Property_ran in H15; unfold Section in H2; apply H2; auto.\n      + apply AxiomII in H15; destruct H15.\n        assert ([u, v] ∈ μ). { apply Theorem19; apply Theorem49; split; Ens. }\n        apply H16 in H17; apply Theorem55 in H17; apply Theorem49 in H14; auto.\n        destruct H17; rewrite H18; auto.\n    - split; try tauto; intros; destruct H13, H14; apply AxiomII in H14.\n      destruct H14, H16; unfold Order_PXY in H3; destruct H3 as [_ [_ [H3 _]]].\n      apply Theorem96 in H3; destruct H3 as [[_ H3] _].\n      apply AxiomII in H16; destruct H16, H17.\n      + apply AxiomII; split; Ens.\n        assert ([((En_f x y r s) ⁻¹) [u0], u0] ∈ (En_f x y r s)).\n        { assert (u0 ∈ ran( En_f x y r s)). \n          { apply Property_ran in H17; apply H2 with v0; repeat split; auto. }\n          pattern u0 at 2; rewrite Lemma96''' with (f:=(En_f x y r s)); auto.\n          apply Property_Value'; auto; rewrite <- Lemma96'''; auto. }\n        exists ((En_f x y r s) ⁻¹) [u0]; apply AxiomII; split; Ens.\n      + apply AxiomII in H17; destruct H17.\n        assert ([u,v] ∈ μ). { apply Theorem19; apply Theorem49; split; Ens. }\n        apply H18 in H19; apply Theorem55 in H19; apply Theorem49 in H16; auto.\n        destruct H19; subst v0.\n        assert ([((En_f x y r s) ⁻¹)[u0], u0] ∈ (En_f x y r s)).\n        { generalize (classic (u0 ∈ ran( En_f x y r s))); intro; destruct H20.\n          - pattern u0 at 2; rewrite Lemma96''' with (f:=(En_f x y r s)); auto.\n            apply Property_Value'; auto; rewrite <- Lemma96'''; auto.\n          - absurd (Rrelation u0 s v); auto; apply H9; apply AxiomII.\n            repeat split; Ens; apply AxiomII; split; Ens. }\n        apply AxiomII; split; Ens; exists ((En_f x y r s) ⁻¹)[u0].\n        apply AxiomII; split; Ens. }\n  split.\n  - unfold Order_PXY; split; try tauto; split; try tauto; split; [idtac|tauto].\n    unfold Order_Pr; intros; split; auto.\n    split; try eapply Lemma99; eauto; try apply H.\n    split; try eapply Lemma99; eauto; try apply H; intros; destruct H14, H15.\n    apply AxiomII in H14; destruct H14, H17; apply AxiomII in H17.\n    destruct H17 as [_ H17]; apply AxiomII in H15; destruct H15, H18.\n    apply AxiomII in H18; destruct H18 as [_ H18].\n    assert ([u,v]∈μ) as H20. { apply Theorem19; apply Theorem49; split; Ens. }\n    destruct H17, H18.\n    + apply Property_dom in H17; apply Property_dom in H18.\n      repeat rewrite Lemma99'; auto; Ens; unfold Order_PXY in H3.\n      destruct H3 as [_ [_ [H3 _]]]; unfold Order_Pr in H3; eapply H3; eauto.\n    + apply Property_dom in H17; rewrite Lemma99'; auto; Ens.\n      apply AxiomII in H18; destruct H18; apply H19 in H20.\n      apply Theorem55 in H20; destruct H20; apply Theorem49 in H18; auto.\n      rewrite Lemma99''; auto; Ens.\n      apply Lemma99''' with (y:=(ran( En_f x y r s))) (x:=y); auto.\n      * apply Property_Value in H17; auto; double H17.\n        apply Property_ran in H17; apply AxiomII; split; Ens.\n      * apply AxiomII in H7; destruct H7, H22; apply AxiomII in H23; tauto.\n      * apply AxiomII in H7; tauto.\n    + apply Property_dom in H18; pattern ((En_f x y r s ∪ [[u,v]])[v0]).\n      rewrite Lemma99'; Ens.\n      assert (u0 ∈ dom( En_f x y r s)).\n      { unfold Section in H1; apply H1 with v0; split; auto.\n        apply AxiomII in H17; destruct H17; apply H19 in H20.\n        apply Theorem55 in H20; apply Theorem49 in H17; auto.\n        destruct H20; rewrite H20; auto. }\n      rewrite Lemma99'; Ens; unfold Order_PXY in H3.\n      destruct H3 as [_ [_ [H3 _]]]; unfold Order_Pr in H3; eapply H3; eauto.\n    + double H20; apply AxiomII in H17; destruct H17; apply H21 in H19.\n      apply AxiomII in H18; destruct H18; apply H22 in H20.\n      apply Theorem55 in H20; destruct H20; apply Theorem49 in H18; auto.\n      apply Theorem55 in H19; destruct H19; apply Theorem49 in H17; auto.\n      subst u0 v0; destruct H as [H _]; apply Theorem88 in H.\n      destruct H as [_ H]; apply Property_Asy with (u:=u) in H; tauto.\n  - assert (Ensemble ([u,v])). { apply Theorem49; split; Ens. } split.\n    + apply AxiomII; split; Ens; exists v; apply AxiomII; split; Ens.\n      right; apply AxiomII; split; auto.\n    + apply AxiomII; split; Ens; right; apply AxiomII; split; auto.\nQed.\n\nHint Resolve Theorem99 : set.\n\n\n(* VII Axiom of regularity : If x ≠ Φ there is a member y of x such x∩y = Φ. *)\n\nAxiom AxiomVII : forall x, x ≠ Φ -> exists y, y∈x /\\ x ∩ y = Φ.\n\nHint Resolve AxiomVII : set.\n\n\n(* Theorem101 : x ∉ x. *)\n\nTheorem Theorem101 : forall x, x ∉ x.\nProof.\n  intros.\n  generalize (classic (x∈x)); intros.\n  destruct H; auto; assert ([x] ≠ Φ).\n  { apply Property_NotEmpty; exists x.\n    unfold Singleton; apply AxiomII; Ens. }\n  apply AxiomVII in H0; destruct H0 as [y H0], H0.\n  unfold Singleton in H0; apply AxiomII in H0; destruct H0.\n  rewrite H2 in H1; try (apply Theorem19); Ens.\n  assert (x ∈ ([x] ∩ x)).\n  { apply Theorem4'; split; auto.\n    unfold Singleton; apply AxiomII; Ens. }\n  rewrite H1 in H3; generalize (Theorem16 x); contradiction.\nQed.\n\nHint Resolve Theorem101 : set.\n\n\n(* Theorem102 : It is false that x∈y and y∈x. *)\n\nTheorem Theorem102 : forall x y, ~ (x ∈ y /\\ y ∈ x).\nProof.\n  intros; intro; destruct H.\n  assert (\\{ λ z, z = x \\/ z =y \\} ≠ Φ).\n  { apply Property_NotEmpty; exists x; apply AxiomII; split; Ens. }\n  apply AxiomVII in H1; destruct H1, H1; apply AxiomII in H1; destruct H1.\n  destruct H3; subst x0.\n  - assert (y ∈ (\\{ λ z, z = x \\/ z = y \\} ∩ x)).\n    { apply AxiomII; repeat split; Ens; apply AxiomII; split; Ens. }\n    rewrite H2 in H3; generalize (Theorem16 y); intro; contradiction.\n  - assert (x ∈ (\\{ λ z, z = x \\/ z = y \\} ∩ y)).\n    { apply AxiomII; repeat split; Ens; apply AxiomII; split; Ens. }\n    rewrite H2 in H3; generalize (Theorem16 x); intro; contradiction.\nQed.\n\nHint Resolve Theorem102 : set.\n\n\n(* Definition103 : E = {(x,y) : x∈y}. *)\n\nDefinition E : Class := \\{\\ λ x y, x∈y \\}\\.\n\nHint Unfold E : set.\n\n\n(* Definition105 : x is full iff each member of x is a subset of x. *)\n\nDefinition full x : Prop := forall m, m∈x -> m⊂x.\n\nCorollary Property_Full : forall x,\n  full x <-> (forall u v : Class, v ∈ x /\\ u ∈ v -> u ∈ x).\nProof.\n  intros; split; intros.\n  - unfold full in H; destruct H0; apply H in H0; auto.\n  - unfold full; intros; unfold Included; intros; apply H with m; tauto.\nQed.\n\nHint Unfold full : set.\n\n\n(* Definition106 : x is an ordinal iff E connects x and x is full.  *)\n\nDefinition Ordinal x : Prop := Connect E x /\\ full x.\n\nHint Unfold Ordinal : set.\n\n\n(* Theorem107 : If x is an ordinal E well-orders x. *)\n\nTheorem Theorem107 : forall x, Ordinal x -> KWellOrder E x.\nProof.\n  intros.\n  unfold Ordinal in H; destruct H.\n  unfold KWellOrder; intros.\n  split; auto; intros; destruct H1.\n  apply AxiomVII in H2; destruct H2, H2.\n  exists x0; unfold FirstMember; intros.\n  split; auto; intros; intro.\n  unfold Rrelation in H5; apply AxiomII_P in H5; destruct H5.\n  assert (y0 ∈ (y ∩ x0)). { apply AxiomII; split; Ens. }\n  rewrite H3 in H7; generalize (Theorem16 y0); contradiction.\nQed.\n\nHint Resolve Theorem107 : set.\n\n\n(* Theorem108 : If x is an ordinal, y⊂x, y≠x, and y is full, then y∈x. *)\n\nTheorem Theorem108 : forall x y,\n  Ordinal x -> y ⊂ x -> y ≠ x -> full y -> y ∈ x.\nProof.\n  intros.\n  assert (Section y E x).\n  { apply Theorem107 in H; unfold Section; intros.\n    split; auto; split; auto; intros; destruct H3, H4.\n    unfold Rrelation in H5; apply AxiomII_P in H5; destruct H5.\n    unfold full in H2; apply H2 in H4; auto. }\n  generalize (Lemma_xy _ _ H3 H1); intro.\n  apply Theorem91 in H4; destruct H4 as [v H4], H4.\n  assert (v = \\{ λ u, u ∈ x /\\ Rrelation u E v \\}).\n  { apply AxiomI; split; intros; AssE z.\n    - apply AxiomII; split; auto; unfold Ordinal in H; destruct H.\n      double H4; unfold full in H8; apply H8 in H4.\n      split; auto; apply AxiomII_P; split; auto; apply Theorem49; split; Ens.\n    - apply AxiomII in H6; destruct H6, H8.\n      unfold Rrelation in H9; apply AxiomII_P in H9; tauto. }\n  rewrite <- H6 in H5; subst v; auto.\nQed.\n\nHint Resolve Theorem108 : set.\n\n\n(* Theorem109 : If x is an ordinal an y is an ordinal, then x⊂y or y⊂x. *)\n\nLemma Lemma109 : forall x y, Ordinal x /\\ Ordinal y -> full (x ∩ y).\nProof.\n  intros; destruct H.\n  unfold Ordinal in H, H0; destruct H, H0.\n  unfold full in *; intros.\n  apply AxiomII in H3; destruct H3, H4.\n  apply H1 in H4; apply H2 in H5.\n  unfold Included; intros.\n  apply AxiomII; repeat split; Ens.\nQed.\n\nLemma Lemma109' : forall x y,\n  Ordinal x /\\ Ordinal y -> ((x ∩ y) = x) \\/ ((x ∩ y) ∈ x).\nProof.\n  intros; generalize (classic ((x ∩ y) = x)); intro.\n  destruct H0; try tauto. assert ((x ∩ y) ⊂ x).\n  { unfold Included; intros; apply Theorem4' in H1; tauto. }\n  elim H; intros; apply Lemma109 in H.\n  eapply Theorem108 in H2; eauto.\nQed.\n\nTheorem Theorem109 : forall x y,\n  Ordinal x /\\ Ordinal y -> x ⊂ y \\/ y ⊂ x.\nProof.\n  intros; elim H; intros.\n  generalize (Lemma_xy _ _ H1 H0); intro.\n  apply Lemma109' in H; apply Lemma109' in H2; destruct H.\n  - apply Theorem30 in H; tauto.\n  - destruct H2.\n    + apply Theorem30 in H2; tauto.\n    + assert ((x ∩ y) ∈ (x ∩ y)).\n      { rewrite Theorem6' in H2; apply AxiomII; Ens. }\n      apply Theorem101 in H3; elim H3.\nQed.\n\nHint Resolve Theorem109 : set.\n\n\n(* Theorem110 : If x is an ordinal an y is an ordinal, then x∈y or y∈x or\n   x = y. *)\n\nTheorem Theorem110 : forall x y,\n  Ordinal x /\\ Ordinal y -> x ∈ y \\/ y ∈ x \\/ x = y.\nProof.\n  intros; generalize (classic (x = y)); intro; destruct H0; try tauto.\n  elim H; intros; apply Theorem109 in H; destruct H.\n  - left; unfold Ordinal in H1; destruct H1; eapply Theorem108; eauto.\n  - right; left; unfold Ordinal in H2; destruct H2.\n    eapply Theorem108; eauto; intro; auto.\nQed.\n\nHint Resolve Theorem110 : set.\n\n\n(* Theorem111 : If x is an ordinal and y∈x, then y is an ordinal. *)\n\nTheorem Theorem111 : forall x y, Ordinal x /\\ y ∈ x -> Ordinal y.\nProof.\n  intros.\n  destruct H; double H; unfold Ordinal in H; destruct H.\n  assert (Connect E y).\n  { unfold Connect; intros; unfold Ordinal in H1; apply H1 in H0.\n    assert (u ∈ x /\\ v ∈ x). { destruct H3; split; auto. }\n    apply H; auto. }\n  unfold Ordinal; split; auto; unfold full; intros; unfold Included; intros.\n  apply Theorem107 in H1; unfold Ordinal in H1; assert (y ⊂ x); auto.\n  assert (m ∈ x); auto; assert (m⊂ x); auto; assert (z ∈ x); auto.\n  apply Theorem88 in H1; destruct H1; unfold Transitive in H1.\n  specialize H1 with z m y; assert (Rrelation z E y).\n  { apply H1; repeat split; Ens.\n    - unfold Rrelation; apply AxiomII_P; split; auto.\n      apply Theorem49; split; Ens.\n    - unfold Rrelation; apply AxiomII_P; split; auto.\n      apply Theorem49; split; Ens. }\n  unfold Rrelation in H11; apply AxiomII_P in H11; tauto.\nQed.\n\nHint Resolve Theorem111 : set.\n\n\n(* Definition112 : R = {x : x is an ordinal}. *)\n\nDefinition R : Class := \\{ λ x, Ordinal x \\}.\n\nHint Unfold R : set.\n\n\n(* Theorem113 : R is an ordinal and R is not a set. *)\n\nLemma Lemma113 :forall u v,\n  Ensemble u -> Ensemble v -> Ordinal u /\\ Ordinal v ->\n  (Rrelation u E v \\/ Rrelation v E u \\/ u = v) .\nProof.\n  intros; apply Theorem110 in H1.\n  destruct H1 as [H1 | [H1 | H1]].\n  - left; unfold Rrelation; apply AxiomII_P; split; Ens; apply Theorem49; auto.\n  - right; left; apply AxiomII_P; split; Ens; apply Theorem49; auto.\n  - right; right; auto.\nQed.\n\nTheorem Theorem113 : Ordinal R /\\ ~ Ensemble R.\nProof.\n  intros.\n  assert (Ordinal R).\n  { unfold Ordinal; intros; split.\n    - unfold Connect; intros; destruct H.\n      apply AxiomII in H; destruct H; apply AxiomII in H0; destruct H0.\n      generalize (Lemma_xy _ _ H1 H2); intro; apply Lemma113; auto.\n    - unfold full; intros; apply AxiomII in H; destruct H.\n      unfold Included; intros; apply AxiomII; split; Ens.\n      eapply Theorem111; eauto. }\n  split; auto; intro; assert (R ∈ R). { apply AxiomII; split; auto. }\n  apply Theorem101 in H1; auto.\nQed.\n\nHint Resolve Theorem113 : set.\n\n\n(* Theorem114 : Each E-section of R is an ordinal. *)\n\nTheorem Theorem114 : forall x, Section x E R -> Ordinal x.\nProof.\n  intros.\n  generalize (classic (x = R)); intro; destruct H0.\n  - rewrite H0; apply Theorem113.\n  - generalize (Lemma_xy _ _ H H0); intro.\n    apply Theorem91 in H1; destruct H1, H1.\n    assert (x0 = \\{ λ u, u ∈ R /\\ Rrelation u E x0 \\}).\n    { apply AxiomI; split; intros.\n      - apply AxiomII; repeat split; Ens.\n        + apply AxiomII in H1; destruct H1.\n          apply AxiomII; split; Ens; eapply Theorem111; eauto.\n        + red; apply AxiomII_P; split; auto; apply Theorem49; Ens.\n      - apply AxiomII in H3; destruct H3, H4.\n        unfold Rrelation in H5; apply AxiomII_P in H5; tauto. }\n    subst x; rewrite H3 in H1; apply AxiomII in H1; tauto.\nQed.\n\nCorollary Lemma114 : forall x, Ordinal x -> Section x E R.\nProof.\n  intros; unfold Section; split.\n  - unfold Included; intros; apply AxiomII; split; try Ens.\n    eapply Theorem111; eauto.\n  - split; intros; try (apply Theorem107; apply Theorem113).\n    destruct H0, H1; unfold Ordinal in H2; apply AxiomII_P in H2; destruct H2.\n    unfold Ordinal in H; destruct H; apply H4 in H1; auto.\nQed.\n\nHint Resolve Theorem114 : set.\n\n\n(* Definition115 : x is an ordinal number iff x ∈ R. *)\n\nDefinition Ordinal_Number x : Prop := x ∈ R.\n\nHint Unfold Ordinal_Number : set.\n\n\n(* Definition116 : x ≺ y if and only if x ∈ y. *)\n\nDefinition Less x y : Prop := x ∈ y.\n\nNotation \"x ≺ y\" := (Less x y)(at level 67, left associativity).\n\nHint Unfold Less : set.\n\n\n(* Definition117 : x ≼ y if and only if x ∈ y or x = y. *)\n\nDefinition LessEqual x y := x ∈ y \\/ x = y.\n\nNotation \"x ≼ y\" := (LessEqual x y)(at level 67, left associativity).\n\nHint Unfold LessEqual : set.\n\n\n(* Definition122 : x + 1 = x ∪ {x}. *)\n\nDefinition PlusOne x := x ∪ [x].\n\nHint Unfold PlusOne : set.\n\n\n(* Theorem123 : If x∈R, then x+1 is the E-first member of {y : y∈R and x≺y}. *)\n\nLemma Lemma123 : forall x, x ∈ R -> (PlusOne x) ∈ R.\nProof.\n  intros; apply AxiomII; split.\n  - apply AxiomIV; split; Ens; apply Theorem42; Ens.\n  - unfold Connect; split.\n    + unfold Connect; intros; destruct H0; apply AxiomII in H0; destruct H0.\n      apply AxiomII in H1; destruct H1, H2, H3.\n      *  apply AxiomII in H; destruct H as [_ H].\n         assert (Ordinal u). { eapply Theorem111; eauto. }\n         assert (Ordinal v). { eapply Theorem111; eauto. }\n         generalize (Lemma_xy _ _ H4 H5); intro; apply Lemma113; auto.\n      * apply AxiomII in H3; destruct H3; AssE x; apply Theorem19 in H5.\n        apply H4 in H5; subst v; left; unfold Rrelation; apply AxiomII_P.\n        split; auto; apply Theorem49; tauto.\n      * apply AxiomII in H2; destruct H2; AssE x; apply Theorem19 in H5.\n        apply H4 in H5; subst u; right; left; unfold Included.\n        apply AxiomII_P; split; auto; apply Theorem49; tauto.\n      * AssE x; apply Theorem19 in H4; double H4; apply AxiomII in H2.\n        destruct H2; apply H6 in H4; apply AxiomII in H3; destruct H3.\n        apply H7 in H5; subst u; subst v; tauto.\n    + unfold full; intros; unfold Included; intros; apply AxiomII in H0.\n      destruct H0; apply AxiomII in H; destruct H.\n      apply AxiomII; split; Ens; destruct H2.\n      * unfold Ordinal in H3; destruct H3; generalize (Property_Full x); intro.\n        destruct H5; apply H5 with (u:=z) (v:=m) in H4; tauto.\n      * apply AxiomII in H2; destruct H2.\n        apply Theorem19 in H; apply H4 in H; subst m; tauto.\nQed.\n\nTheorem Theorem123 : forall x,\n  x ∈ R -> FirstMember (PlusOne x) E (\\{ λ y, (In y R /\\ Less x y) \\}).\nProof.\n  intros; unfold FirstMember; split; intros.\n  - apply AxiomII; repeat split.\n    + unfold Ensemble; exists R; apply Lemma123; auto.\n    + apply Lemma123; auto.\n    + unfold Less; intros; apply AxiomII; split; Ens.\n      right; apply AxiomII; split; Ens.\n  - intro; apply AxiomII in H0; destruct H0, H2.\n    unfold Rrelation in H1; apply AxiomII_P in H1; destruct H1.\n    apply AxiomII in H4; destruct H4; unfold Less in H3; destruct H5.\n    + eapply Theorem102; eauto.\n    + AssE x; apply Theorem19 in H6; apply AxiomII in H5; destruct H5.\n      apply H7 in H6; subst y; eapply Theorem101; eauto.\nQed.\n\nHint Resolve Theorem123 : set.\n\n\n(* Definition125 : f|x = f ∩ (x × μ). *)\n\nDefinition Restriction f x : Class := f ∩ (x) × μ.\n\nNotation \"f | ( x )\" := (Restriction f x)(at level 40).\n\nHint Unfold Restriction : set.\n\n\n(* Theorem127 : Let f be a function such that domain f is an ordinal and\n   f(u) = g(f|u) for u in domain f. If h is also a function such that domain h\n   is an ordinal and h(u) = g(h|u) for u in domain h, then h ⊂ f or f ⊂ h. *)\n\nTheorem Theorem127 : forall f h g,\n  Function f -> Ordinal dom(f) ->\n  (forall u0, u0 ∈ dom(f) -> f[u0] = g[f | (u0)]) ->\n  Function h -> Ordinal dom(h) ->\n  (forall u1, u1 ∈ dom(h) -> h[u1] = g[h | (u1)]) -> h ⊂ f \\/ f ⊂ h.\nProof.\n  intros; generalize (Lemma_xy _ _ H0 H3); intro; apply Theorem109 in H5.\n  generalize (classic (\\{λ a, a∈(dom(f)∩dom(h))/\\f[a]≠h[a]\\}=Φ)); intro.\n  destruct H6.\n  - destruct H5.\n    + right; unfold Included; intros; rewrite Theorem70 in H7; auto; PP H7 a b.\n      double H8; rewrite <- Theorem70 in H8; auto; apply Property_dom in H8.\n      apply AxiomII_P in H9; destruct H9; rewrite Theorem70; auto.\n      apply AxiomII_P; split; auto; rewrite H10.\n      generalize (classic (f[a] = h[a])); intro; destruct H11; auto.\n      assert (a ∈ \\{ λ a, a ∈ (dom(f) ∩ dom(h)) /\\ f[a] ≠ h[a] \\}).\n      { apply AxiomII; split; Ens; split; auto.\n        apply Theorem30 in H5; rewrite H5; auto. }\n      eapply AxiomI in H6; apply H6 in H12.\n      generalize (Theorem16 a); intros; contradiction.\n    + left; unfold Included; intros; rewrite Theorem70 in H7; auto; PP H7 a b.\n      double H8; rewrite <- Theorem70 in H8; auto; apply Property_dom in H8.\n      apply AxiomII_P in H9; destruct H9; rewrite Theorem70; auto.\n      apply AxiomII_P; split; auto; rewrite H10.\n      generalize (classic (f[a] = h[a])); intro; destruct H11; auto.\n      assert (a ∈ \\{ λ a, a ∈ (dom(f) ∩ dom(h)) /\\ f[a] ≠ h[a] \\}).\n      { apply AxiomII; split; Ens; split; auto.\n        apply Theorem30 in H5; rewrite Theorem6'; rewrite H5; auto. }\n      eapply AxiomI in H6; apply H6 in H12.\n      generalize (Theorem16 a); intros; contradiction.\n  - assert (exists u, FirstMember u E \\{λ a, a∈(dom(f)∩dom(h))/\\f[a]≠h[a]\\}).\n    { apply Theorem107 in H0; unfold KWellOrder in H0; apply H0; split; auto.\n      unfold Included; intros; apply AxiomII in H7; destruct H7, H8.\n      apply AxiomII in H8; tauto. }\n    destruct H7 as [u H7]; unfold FirstMember in H7; destruct H7.\n    apply AxiomII in H7; destruct H7, H9; apply AxiomII in H9.\n    destruct H9 as [_ [H9 H11]]; generalize (H1 _ H9).\n    generalize (H4 _ H11); intros.\n    assert ((h | (u)) = (f | (u))).\n    { apply AxiomI; intros; split; intros.\n      - apply AxiomII in H14; destruct H14, H15; apply AxiomII.\n        repeat split; auto; PP H16 a b; apply AxiomII_P in H17.\n        destruct H17 ,H18; generalize H15 as H22; intro.\n        apply Property_dom in H22; rewrite Theorem70 in H15; auto.\n        rewrite Theorem70; auto; apply AxiomII_P in H15; destruct H15.\n        apply AxiomII_P; split; auto; rewrite H20; symmetry.\n        generalize (classic (f[a] = h[a])); intro; destruct H21; auto.\n        assert (a ∈ \\{ λ a, a ∈ (dom(f) ∩ dom(h)) /\\ f[a] ≠ h[a] \\}).\n        { apply AxiomII; repeat split; auto; try Ens; apply AxiomII.\n          repeat split; auto; try Ens; unfold Ordinal in H0; destruct H0.\n          unfold full in H23; apply H23 in H9; auto. }\n        apply H8 in H23; elim H23; red; apply AxiomII_P; split; auto.\n        apply Theorem49; split; try Ens.\n      - apply AxiomII in H14; destruct H14, H15; apply AxiomII.\n        repeat split; auto; PP H16 a b; apply AxiomII_P in H17.\n        destruct H17 ,H18; generalize H15 as H22; intro.\n        apply Property_dom in H22; rewrite Theorem70 in H15; auto.\n        rewrite Theorem70; auto; apply AxiomII_P in H15; destruct H15.\n        apply AxiomII_P; split; auto; rewrite H20; symmetry.\n        generalize (classic (f[a] = h[a])); intro; destruct H21; auto.\n        assert (a ∈ \\{ λ a, a ∈ (dom(f) ∩ dom(h)) /\\ f[a] ≠ h[a] \\}).\n        { apply AxiomII; repeat split; auto; try Ens; apply AxiomII.\n          repeat split; auto; try Ens; unfold Ordinal in H3; destruct H3.\n          unfold full in H23; apply H23 in H11; auto. }\n        apply H8 in H23; elim H23; red; apply AxiomII_P; split; auto.\n        apply Theorem49; split; try Ens. }\n    rewrite <- H14 in H13; rewrite <- H12 in H13; contradiction.\nQed.\n\nHint Resolve Theorem127 : set.\n\n\n(* Theorem128 : For each g there is a unique function f such that domain f is\n   an ordinal and f(x) = g(f|x) for each ordinal number x. *)\n\nDefinition En_f' g :=\n  \\{\\ λ u v, u ∈ R /\\ (exists h, Function h /\\ Ordinal dom(h) /\\\n  (forall z, z ∈ dom(h) -> h[z] = g [h | (z)] ) /\\ [u,v] ∈ h ) \\}\\.\n\nLemma Lemma128 : forall u v w, Ordinal u -> v ∈ u -> w ∈ v -> w ∈ u.\nProof.\n  intros; unfold Ordinal in H; destruct H.\n  generalize (Property_Full u); intro; destruct H3.\n  eapply H3; eauto.\nQed.\n\nLemma Lemma128' : forall f x,\n  Ordinal dom(f) -> Ordinal_Number x -> ~ x ∈ dom(f) -> f | (x) = f .\nProof.\n  intros; apply AxiomI; split; intros.\n  - apply AxiomII in H2; tauto.\n  - apply AxiomII; split; Ens; split; auto.\n    PP' H3; apply AxiomII_P; split; Ens; split.\n    + unfold Ordinal in H0; apply AxiomII in H0; destruct H0.\n      generalize (Theorem110 _ _ (Lemma_xy _ _ H H4)); intro.\n      apply Property_dom in H2; auto; destruct H5 as [H5|[H5|H5]]; try tauto.\n      * eapply Lemma128; eauto.\n      * rewrite H5 in H2; auto.\n    + apply Property_ran in H2; apply Theorem19; Ens.\nQed.\n\nTheorem Theorem128 :  forall g,\n  exists f, Function f /\\ Ordinal dom(f) /\\\n  (forall x, Ordinal_Number x -> f [x] = g [f | (x)]).\nProof.\n  intros; exists (En_f' g).\n  assert (Function (En_f' g)).\n  { unfold Function; intros; split; intros.\n    - unfold Relation; intros; PP H a b; eauto.\n    - destruct H; apply AxiomII_P in H; apply AxiomII_P in H0.\n      destruct H, H1, H2, H2, H3, H4, H0, H6, H7, H7, H8, H9.\n      generalize (Theorem127 _ _ _ H2 H3 H4 H7 H8 H9); intro; destruct H11.\n      + apply H11 in H10; eapply H2; eauto.\n      + apply H11 in H5; eapply H7; eauto. }\n  split; auto.\n  - assert (Ordinal dom( En_f' g)).\n    { apply Theorem114; unfold Section; intros; split.\n      - unfold Included; intros; apply AxiomII in H0; destruct H0, H1.\n        apply AxiomII_P in H1; tauto.\n      - split; intros.\n        + apply Theorem107; apply Theorem113.\n        + destruct H0, H1; apply AxiomII in H1; destruct H1, H3.\n          apply AxiomII_P in H3; destruct H3, H4, H5, H5, H6, H7.\n          apply AxiomII_P in H2; destruct H2; apply Theorem49 in H2.\n          destruct H2; apply AxiomII; split; auto; apply Property_dom in H8.\n          assert (u ∈ dom( x0)). { eapply Lemma128; eauto. } exists (x0[u]).\n          apply AxiomII_P; split; try apply Theorem49; split; auto.\n          * apply Theorem19; apply Theorem69; auto.\n          * exists x0; split; auto; split; auto; split; auto.\n            apply Property_Value; auto. }\n    split; intros; auto.\n    generalize (classic (x ∈ dom(En_f' g))); intro; destruct H2.\n    + apply AxiomII in H2; destruct H2, H3; apply AxiomII_P in H3.\n       destruct H2, H3, H4; destruct H5 as [h [H5 [H6 [H7 H8]]]].\n       assert (h ⊂ En_f' g).\n       { unfold Included; intros; PP' H10; apply AxiomII_P; split; try Ens.\n         double H9; apply Property_dom in H9; split; try apply AxiomII.\n         - split; try Ens; eapply Theorem111; eauto.\n         - exists h; tauto. }\n      generalize H8; intro; apply H9 in H10; generalize H8; intro.\n      apply Property_dom in H11; apply H7 in H11; generalize H8; intro.\n      apply Property_dom in H12; apply Property_dom in H8.\n      apply Property_Value in H8; auto; apply Property_dom in H10.\n      apply Property_Value in H10; auto; apply H9 in H8.\n      assert (h [x] = (En_f' g) [x]). { eapply H; eauto. }\n      rewrite <- H13; clear H13.\n      assert (h | (x) = En_f' g | (x)).\n      { apply AxiomI; split; intros; apply AxiomII in H13; destruct H13, H14.\n        - apply AxiomII; repeat split; auto.\n        - apply AxiomII; repeat split; auto; rewrite Theorem70; auto.\n          PP H15 a b; apply AxiomII_P in H16; apply AxiomII_P; split; auto.\n          destruct H16, H17. assert (a ∈ dom(h)). { eapply Lemma128; eauto. }\n         apply Property_Value in H19; auto; apply H9 in H19; eapply H; eauto. }\n      rewrite <- H13; auto.\n    + generalize H2; intro; apply Theorem69 in H2; auto.\n      rewrite (Lemma128' _ _ H0 H1 H3).\n      generalize (classic (En_f' g ∈ dom(g))); intro; destruct H4.\n      * generalize Theorem113; intro; destruct H5 as [H5 _].\n        apply Theorem107 in H5; unfold KWellOrder  in H5; destruct H5.\n        assert ((R ~ dom(En_f' g)) ⊂ R /\\ (R ~ dom(En_f' g)) ≠ Φ).\n        { split; try (red; intros; apply AxiomII in H7; tauto).\n          intro; generalize (Lemma114 _ H0); intro; unfold Section in H8.\n          destruct H8; apply Property_Φ in H8; apply H8 in H7.\n          rewrite <- H7 in H3; contradiction. }\n        apply H6 in H7; destruct H7 as [y H7].\n        assert (((En_f' g) ∪ [[y,g[En_f' g]]]) ⊂ (En_f' g)).\n        { unfold Included; intros; apply AxiomII in H8; destruct H8, H9; auto.\n          assert (Ensemble ([y, g [En_f' g]])).\n          { unfold FirstMember in H7; destruct H7; AssE y.\n            apply Theorem69 in H4; apply Theorem19 in H4.\n            apply Theorem49; tauto. }\n          apply AxiomII in H9; destruct H9.\n          rewrite H11; try apply Theorem19; auto.\n          apply AxiomII_P; split; auto; split.\n          - unfold FirstMember in H7; destruct H7; apply AxiomII in H7; tauto.\n          - exists ((En_f' g) ∪ [[y,g[En_f' g]]]).\n            assert (Function (En_f' g ∪ [[y, g [En_f' g]]])).\n            { unfold Function; split; intros.\n              - unfold Relation; intros; apply AxiomII in H12.\n                destruct H12, H13.\n                + PP H13 a b; eauto.\n                + apply AxiomII in H13; destruct H13; apply Theorem19 in H10.\n                  apply H14 in H10; eauto.\n              - destruct H12; apply AxiomII in H12; destruct H12 as [_ H12].\n                apply AxiomII in H13; destruct H13 as [_ H13].\n                unfold FirstMember in H7; destruct H7.\n                apply AxiomII in H7; destruct H7 as [_ [_ H7]].\n                apply AxiomII in H7; destruct H7; destruct H12, H13.\n                + eapply H; eauto.\n                + apply AxiomII in H13; destruct H13; apply Theorem19 in H10.\n                  apply H16 in H10; apply Theorem55 in H10; destruct H10;\n                  try apply Theorem49; auto; rewrite H10 in H12.\n                  apply Property_dom in H12; contradiction.\n                + apply AxiomII in H12; destruct H12; apply Theorem19 in H10.\n                  apply H16 in H10; apply Theorem55 in H10; destruct H10;\n                  try apply Theorem49; auto; rewrite H10 in H13.\n                  apply Property_dom in H13; contradiction.\n                + double H12; apply AxiomII in H12; apply AxiomII in H13.\n                  destruct H12, H13; double H10; apply Theorem19 in H10.\n                  apply H17 in H10; apply Theorem19 in H19; apply H18 in H19.\n                  apply Theorem55 in H10; destruct H10; apply Theorem49 in H12;\n                  auto; apply Theorem55 in H19; destruct H19;\n                  apply Theorem49 in H13; auto; rewrite H20, H21; auto. }\n            split; auto; split.\n            + apply Theorem114; unfold Section; intros; split.\n              * unfold Included; intros; apply AxiomII in H13.\n                destruct H13, H14; apply AxiomII in H14; destruct H14, H15.\n                { apply Property_dom in H15; apply AxiomII.\n                  split; Ens; eapply Theorem111; eauto. }\n                { apply AxiomII in H15; destruct H15; apply Theorem19 in H10.\n                  apply H16 in H10; apply Theorem55 in H10; destruct H10;\n                  try apply Theorem49; auto; unfold FirstMember in H7.\n                  destruct H7; apply AxiomII in H7; rewrite H10; tauto. }\n              * split; try (apply Theorem107; apply Theorem113); intros.\n                destruct H13, H14; apply AxiomII in H14; destruct H14, H16.\n                apply AxiomII in H16; destruct H16, H17.\n                { apply AxiomII; split; Ens.\n                  assert ([u, (En_f' g) [u]] ∈ (En_f' g)).\n                  { apply Property_Value; auto; apply Property_dom in H17.\n                    unfold Rrelation in H15; apply AxiomII_P in H15.\n                    destruct H15; eapply Lemma128; eauto. }\n                  exists ((En_f' g) [u]); apply AxiomII; split; Ens. }\n                { assert ([u, (En_f' g) [u]] ∈ (En_f' g)).\n                  { apply Property_Value; auto; apply AxiomII in H17.\n                    destruct H17; apply Theorem19 in H10; apply H18 in H10.\n                    apply Theorem55 in H10; destruct H10; try apply Theorem49;\n                    auto; subst v; unfold FirstMember in H7; destruct H7.\n                    generalize (classic (u ∈ dom( En_f' g))); intro.\n                    destruct H20; auto; absurd (Rrelation u E y); auto;\n                    try apply H10; apply AxiomII; repeat split; Ens.\n                    apply AxiomII; split; Ens. }\n                  apply AxiomII; split; Ens; exists ((En_f' g)[u]).\n                  apply AxiomII; split; Ens. }\n            + split; intros.\n              * apply Property_Value in H13; auto.\n                apply AxiomII in H13; destruct H13, H14.\n                { apply AxiomII_P in H14; destruct H14, H15.\n                  destruct H16 as [h [H16 [H17 [H18 H19]]]]; double H19.\n                  apply Property_dom in H20; rewrite Theorem70 in H19; auto.\n                  apply AxiomII_P in H19; destruct H19.\n                  assert (h ⊂ En_f' g).\n                  { unfold Included; intros; PP' H23; apply AxiomII_P.\n                    split; try Ens; double H22.\n                    apply Property_dom in H22; split; try apply AxiomII.\n                    - split; try Ens; eapply Theorem111; eauto.\n                    - exists h; tauto. }\n                  assert ((En_f' g ∪ [[y, g[En_f' g]]]) |\n                           (z0) = En_f' g | (z0)).\n                  { unfold Restriction; rewrite Theorem6'; rewrite Theorem8.\n                    assert ((z0) × μ ∩ [[y, g [En_f' g]]] = Φ).\n                    { apply AxiomI; split; intros; apply AxiomII in H23;\n                      destruct H23, H24; auto.\n                      PP H24 a b; apply AxiomII_P in H26; destruct H26, H27.\n                      apply AxiomII in H25; destruct H25.\n                      apply Theorem19 in H10; apply H29 in H10.\n                      apply Theorem55 in H10; apply Theorem49 in H25; auto.\n                      destruct H10; rewrite H10 in H27.\n                      assert (y ∈ dom( h)). { eapply Lemma128; eauto. }\n                      apply Property_Value in H31; auto; apply H22 in H31.\n                      apply Property_dom in H31; unfold FirstMember in H7.\n                      destruct H7; apply AxiomII in H7; destruct H7, H33.\n                      apply AxiomII in H34; destruct H34; contradiction. }\n                    rewrite H23; rewrite Theorem6; rewrite Theorem17.\n                    apply Theorem6'. }\n                  rewrite H21; rewrite H23.\n                  assert (h | (z0) = En_f' g | (z0)).\n                  { apply AxiomI; split; intros.\n                    - apply AxiomII in H24; destruct H24, H25.\n                      apply AxiomII; repeat split; auto.\n                    - apply AxiomII in H24; destruct H24, H25; apply AxiomII.\n                      repeat split; auto; rewrite Theorem70; auto.\n                      PP H26 a b; apply AxiomII_P in H27.\n                      apply AxiomII_P; split; auto; destruct H27 as [_ [H27 _]].\n                      assert (a ∈ dom(h)). { eapply Lemma128; eauto. }\n                      apply Property_Value in H28; auto; apply H22 in H28.\n                      eapply H; eauto. }\n                  rewrite <- H24; auto. }\n                { apply AxiomII in H14; destruct H14; double H10.\n                  apply Theorem19 in H10; apply H15 in H10.\n                  apply Theorem55 in H10; apply Theorem49 in H13; auto.\n                  destruct H10; subst z0; rewrite H17.\n                  assert ((En_f' g ∪ [[y, g[En_f' g]]]) | (y) = En_f' g | (y)).\n                  { apply AxiomI; split; intros.\n                    - apply AxiomII in H10; destruct H10, H18.\n                      apply AxiomII in H18; destruct H18, H20.\n                      + apply AxiomII; tauto.\n                      + PP H19 a b; apply AxiomII_P in H21; destruct H21, H22.\n                        apply AxiomII in H20; destruct H20.\n                        apply Theorem19 in H16; apply H24 in H16.\n                        apply Theorem55 in H16; apply Theorem49 in H21; auto.\n                        destruct H16; rewrite H16 in H22.\n                        generalize (Theorem101 y); intro; contradiction. \n                    - unfold Restriction; rewrite Theorem6'; rewrite Theorem8.\n                      apply AxiomII; split; Ens; left; rewrite Theorem6'; Ens. }\n                  rewrite H10; unfold FirstMember in H7; destruct H7.\n                  apply AxiomII in H7; destruct H7, H19; apply AxiomII in H20.\n                  destruct H20; rewrite Lemma128'; auto. }\n              * apply AxiomII; split; Ens; right; apply AxiomII; split; Ens. }\n        unfold FirstMember in H7; destruct H7.\n        assert (y ∈ dom(En_f' g ∪ [[y, g [En_f' g]]])).\n        { apply AxiomII; split; Ens; exists g [En_f' g].\n          assert (Ensemble ([y, g [En_f' g]])).\n          { apply Theorem49; split; Ens; apply Theorem69 in H4.\n            apply Theorem19; auto. }\n          apply AxiomII; split; Ens; right; apply AxiomII; auto. }\n        apply AxiomII in H7; destruct H7, H11; apply AxiomII in H12.\n        destruct H12; elim H13; apply AxiomII in H10; destruct H10, H14.\n        apply H8 in H14; apply Property_dom in H14; auto.\n      * apply Theorem69 in H4; rewrite H2, H4; auto.\nQed.\n\nHint Resolve Theorem128 : set.\n\n\n(* VIII Axiom of infinity : For some y, y is a set, Φ ∈ y and (x ∪ {x}) ∈ y\n   whenever x ∈ y. *)\n\nAxiom AxiomVIII : exists y, Ensemble y /\\ Φ ∈ y\n  /\\ (forall x, x ∈ y -> (x ∪ [x]) ∈ y).\n\nHint Resolve AxiomVIII : set.\n\n\n(* Definition129 : x is an integer if and only if x is an ordinal and E⁻¹\n   well-orders x. *)\n\nDefinition Integer x : Prop := Ordinal x /\\ KWellOrder (E ⁻¹) x.\n\nHint Unfold Integer : set.\n\n\n(* Definition130 : x is an E-last member of y is and only if x is an E⁻¹-first\n   member of y. *)\n\nDefinition LastMember x E y : Prop := FirstMember x (E ⁻¹) y.\n\nHint Unfold LastMember : set.\n\n\n(* Definition131 : W = {x : x is an integer}. *)\n\nDefinition W : Class := \\{ λ x, Integer x \\}.\n\nHint Unfold W : set.\n\n\n(* Theorem132 : A member of an integer is an integer. *)\n\nTheorem Theorem132 : forall x y, Integer x -> y∈x -> Integer y.\nProof.\n  intros.\n  unfold Integer in H; unfold Integer; destruct H.\n  double H; apply Lemma_xy with (y:= y∈x) in H2; auto.\n  apply Theorem111 in H2; split; auto.\n  unfold KWellOrder in H1; unfold KWellOrder.\n  unfold Ordinal in H; destruct H.\n  unfold full in H3; apply H3 in H0.\n  destruct H1; split; intros.\n  - unfold Connect in H1; unfold Connect; intros.\n    apply H1; destruct H5; unfold Included in H0.\n    apply H0 in H5; apply H0 in H6; split; auto.\n  - destruct H5; apply H4; split; auto.\n    apply (Theorem28 _ y _); auto.\nQed.\n\nHint Resolve Theorem132 : set.\n\n\n(* Theorem133 : If y∈R and x is an E-last member of y, then y = x+1. *)\n\nTheorem Theorem133 : forall x y,\n  y ∈ R /\\ LastMember x E y -> y = PlusOne x.\nProof.\n  intros; destruct H.\n  unfold LastMember, FirstMember in H0.\n  unfold R in H; apply AxiomII in H; destruct H, H0.\n  double H1; add (x ∈ y) H3; apply Theorem111 in H3.\n  assert (x ∈ R). { unfold R; apply AxiomII; Ens. }\n  apply Theorem123 in H4; unfold FirstMember in H4; destruct H4.\n  assert (y ∈ \\{ λ z, z ∈ R /\\ x ≺ z \\}).\n  { apply AxiomII; repeat split; auto.\n    unfold R; apply AxiomII; split; auto. }\n  apply H5 in H6; clear H5; generalize (Theorem113); intros.\n  destruct H5; clear H7; apply Theorem107 in H5.\n  unfold KWellOrder in H5; destruct H5; clear H7.\n  unfold Connect in H5; apply AxiomII in H4; destruct H4, H7.\n  clear H8; assert (y ∈ R /\\ (PlusOne x) ∈ R).\n  { split; auto; unfold R; apply AxiomII; Ens. }\n  apply H5 in H8; clear H5; destruct H8; try contradiction.\n  destruct H5; auto; unfold Rrelation, E in H5.\n  apply AxiomII_P in H5; destruct H5.\n  apply H2 in H8; elim H8; unfold Rrelation, Inverse.\n  apply AxiomII_P; split; try apply Theorem49; Ens.\n  unfold E; apply AxiomII_P; split; try apply Theorem49; Ens.\n  unfold PlusOne; apply Theorem4; right.\n  unfold Singleton; apply AxiomII; Ens.\nQed.\n\nHint Resolve Theorem133 : set.\n\n\n(* Theorem134 : If x ∈ W, then x+1 ∈ W. *)\n\nTheorem Theorem134 : forall x, x ∈ W -> (PlusOne x) ∈ W.\nProof.\n  intros.\n  unfold W in H; apply AxiomII in H; destruct H.\n  unfold Integer in H0; destruct H0.\n  unfold W; apply AxiomII; split.\n  - unfold PlusOne; apply AxiomIV; split; auto.\n    apply Theorem42 in H; auto.\n  - unfold Integer; split.\n    + assert (x ∈ R). { apply AxiomII; Ens. }\n      apply Lemma123 in H2; apply AxiomII in H2; apply H2.\n    + unfold KWellOrder in H1; unfold KWellOrder.\n      destruct H1; split; intros.\n      { clear H2; unfold Connect in H1; unfold Connect; intros.\n        unfold PlusOne in H2; destruct H2; apply Theorem4 in H2.\n        apply Theorem4 in H3; destruct H2, H3.\n        - apply H1; auto.\n        - unfold Singleton in H3; apply AxiomII in H3; destruct H3.\n          rewrite <- H4 in H2; try apply Theorem19; Ens.\n          right; left; unfold Rrelation, Inverse, E.\n          apply AxiomII_P; split; try apply Theorem49; Ens.\n          apply AxiomII_P; split; try apply Theorem49; Ens.\n        - unfold Singleton in H2; apply AxiomII in H2; destruct H2.\n          rewrite <- H4 in H3; try apply Theorem19; Ens.\n          left; unfold Rrelation, Inverse, E.\n          apply AxiomII_P; split; try apply Theorem49; Ens.\n          apply AxiomII_P; split; try apply Theorem49; Ens.\n        - unfold Singleton in H2; apply AxiomII in H2; destruct H2.\n          unfold Singleton in H3; apply AxiomII in H3; destruct H3.\n          right; right; rewrite H4, H5; try apply Theorem19; Ens. }\n      { destruct H3; unfold PlusOne in H3.\n        generalize (classic (x ∈ y)); intro; destruct H5.\n        - exists x; unfold FirstMember; split; intros; auto.\n          intro; unfold Rrelation in H7; apply AxiomII_P in H7.\n          destruct H7; apply AxiomII_P in H8; destruct H8.\n          apply H3 in H6; apply Theorem4 in H6; destruct H6.\n          + eapply Theorem102; eauto.\n          + apply AxiomII in H6; destruct H6.\n            rewrite H10 in H9; try apply Theorem19; Ens.\n            apply Theorem101 in H9; auto.\n        - apply H2; split; auto; unfold Included; intros; double H6.\n          apply H3 in H6; apply Theorem4 in H6; destruct H6; auto.\n          apply AxiomII in H6; destruct H6; apply Theorem19 in H.\n          rewrite <- H8 in H5; auto; contradiction. }\nQed.\n\nHint Resolve Theorem134 : set.\n\n\n(* Theorem135 :  Φ ∈ W and if x ∈ W, then Φ ≠ x+1. *)\n\nTheorem Theorem135 : forall x, \n  Φ ∈ W /\\ (x ∈ W -> Φ ≠ PlusOne x).\nProof.\n  intros; split; intros.\n  - unfold W; apply AxiomII; split.\n    + generalize AxiomVIII; intros; destruct H, H, H0; Ens.\n    + unfold Integer; split.\n      * unfold Ordinal; split.\n        -- unfold Connect; intros; destruct H.\n           generalize (Theorem16 u); contradiction.\n        -- unfold full; intros.\n           generalize (Theorem16 m); contradiction.\n      * unfold KWellOrder; split; intros.\n        -- unfold Connect; intros; destruct H.\n           generalize (Theorem16 u); contradiction.\n        -- destruct H; generalize (Theorem26 y); intros.\n           absurd (y = Φ); try apply Theorem27; auto.\n  - intro; unfold PlusOne in H0; assert (x ∈ Φ).\n    { rewrite H0; apply Theorem4; right.\n      unfold Singleton; apply AxiomII; split; Ens. }\n    generalize (Theorem16 x); intro; contradiction.\nQed.\n\nHint Resolve Theorem135 : set.\n\n\n(* Theorem137 : If x⊂W, Φ∈x and u+1∈x whenever u∈x, then x = w. *)\n\nCorollary Property_W : Ordinal W.\nProof.\n  unfold Ordinal; split.\n  - unfold Connect; intros; destruct H; unfold W in H, H0.\n    apply AxiomII in H; apply AxiomII in H0; destruct H, H0.\n    unfold Integer in H1, H2; destruct H1, H2; add (Ordinal v) H1.\n    apply Theorem110 in H1; destruct H1 as [H1|[H1|H1]]; try tauto.\n    + left; unfold Rrelation, E; apply AxiomII_P.\n      split; auto; apply Theorem49; split; auto.\n    + right; left; unfold Rrelation, E; apply AxiomII_P.\n      split; auto; apply Theorem49; split; auto.\n  - unfold full; intros; unfold Included; intros.\n    unfold W in H; apply AxiomII in H; destruct H.\n    apply (Theorem132 _ z) in H1; auto.\n    unfold W; apply AxiomII; Ens.\nQed.\n\nTheorem Theorem137 : forall x,\n  x ⊂ W -> Φ ∈ x ->\n  (forall u, u ∈ x -> (PlusOne u) ∈ x) -> x = W.\nProof.\n  intros.\n  generalize (classic (x = W)); intros; destruct H2; auto.\n  assert (exists y, FirstMember y E (W ~ x)).\n  { assert (KWellOrder E W).\n    { apply Theorem107; apply Property_W. }\n    unfold KWellOrder in H3; destruct H3; apply H4; split.\n    - unfold Included; intros; unfold Setminus in H5.\n      apply Theorem4' in H5; apply H5.\n    - intro; apply Property_Φ in H; apply H in H5.\n      symmetry in H5; contradiction. }\n  destruct H3 as [y H3]; unfold FirstMember in H3; destruct H3.\n  unfold Setminus in H3; apply Theorem4' in H3; destruct H3.\n  unfold W in H3; apply AxiomII in H3; destruct H3; double H6.\n  unfold Integer in H7; destruct H7; unfold KWellOrder in H8.\n  destruct H8; assert (y ⊂ y /\\ y ≠ Φ).\n  { split; try unfold Included; auto.\n    intro; rewrite H10 in H5; unfold Complement in H5.\n    apply AxiomII in H5; destruct H5; contradiction. }\n  apply H9 in H10; clear H9; destruct H10 as [u H9].\n  assert (u ∈ x).\n  { unfold FirstMember in H9; destruct H9; clear H10.\n    generalize (classic (u∈x)); intros; destruct H10; auto.\n    assert (u ∈ (W ~ x)).\n    { unfold Setminus; apply Theorem4'; split.\n      - unfold W; apply AxiomII; split; Ens.\n        apply Theorem132 in H9; auto.\n      - unfold Complement; apply AxiomII; Ens. }\n    apply H4 in H11; elim H11; unfold Rrelation, E.\n    apply AxiomII_P; split; try apply Theorem49; Ens. }\n  assert (y ∈ R /\\ LastMember u E y).\n  { split; auto; unfold R; apply AxiomII; Ens. }\n  apply Theorem133 in H11; apply H1 in H10; rewrite <- H11 in H10.\n  clear H11; unfold Complement in H5; apply AxiomII in H5.\n  destruct H5; unfold NotIn in H11; contradiction.\nQed.\n\nHint Resolve Theorem137 : set.\n\n\n(* Theorem138 : W ∈ R. *)\n\nTheorem Theorem138 : W ∈ R.\nProof.\n  unfold R; apply AxiomII; split; try apply Property_W.\n  generalize AxiomVIII; intros; destruct H, H, H0.\n  assert (W ∩ x = W).\n  { apply Theorem137; intros.\n    - unfold Included; intros; apply Theorem4' in H2; apply H2.\n    - apply Theorem4'; split; auto; apply Theorem135; auto.\n    - apply Theorem4' in H2; destruct H2; apply Theorem134 in H2.\n      apply H1 in H3; apply Theorem4'; split; auto. }\n  rewrite <- H2; apply Theorem33 with (x:=x); auto.\n  unfold Included; intros; apply Theorem4' in H3; apply H3.\nQed.\n\nHint Resolve Theorem138 : set.\n\n\n(* Mathematical Induction *)\n\nTheorem MiniMember_Principle : forall S,\n  S ⊂ W /\\ S ≠ Φ -> exists a, a ∈ S /\\ (forall c, c ∈ S -> a ≼ c).\nProof.\n  intros; destruct H.\n  assert (exists y, FirstMember y E S).\n  { assert (KWellOrder E W).\n    { apply Theorem107; apply Property_W. }\n    unfold KWellOrder in H1; destruct H1; apply H2; auto. }\n  destruct H1; exists x; unfold FirstMember in H1; destruct H1.\n  split; auto; intros; double H3; apply H2 in H4.\n  unfold Included in H; apply H in H1; apply H in H3.\n  unfold W in H1, H3; apply AxiomII in H1; apply AxiomII in H3.\n  destruct H1, H3; unfold Integer in H5, H6; destruct H5, H6.\n  add (Ordinal c) H5; clear H6 H7 H8; apply Theorem110 in H5.\n  unfold LessEqual; destruct H5 as [H5|[H5|H5]]; try tauto.\n  elim H4; unfold Rrelation, E; apply AxiomII_P; split; auto.\n  apply Theorem49; split; Ens.\nQed.\n\nDefinition En_S P : Class := \\{ λ x, x ∈ W /\\ ~ (P x) \\}.\n\nTheorem Mathematical_Induction : forall (P: Class -> Prop),\n  P Φ -> (forall k, k ∈ W /\\ P k -> P (PlusOne k)) ->\n  (forall n, n ∈ W -> P n).\nProof.\n  intros.\n  generalize (classic ((En_S P) = Φ)); intros; destruct H2.\n  - generalize (classic (P n)); intros; destruct H3; auto.\n    assert (n ∈ (En_S P)). { apply AxiomII; split; Ens. }\n    rewrite H2 in H4; generalize (Theorem16 n); contradiction.\n  - assert ((En_S P) ⊂ W).\n    { unfold En_S, Included; intros; apply AxiomII in H3; apply H3. }\n    add ((En_S P) <> Φ) H3; clear H2.\n    apply MiniMember_Principle in H3; destruct H3 as [h H3], H3.\n    unfold En_S in H2; apply AxiomII in H2; destruct H2, H4.\n    unfold W in H4; apply AxiomII in H4; clear H2; destruct H4.\n    double H4; unfold Integer in H6; destruct H6.\n    unfold KWellOrder in H7; destruct H7.\n    assert (h ⊂ h /\\ h ≠ Φ).\n    { split; try (unfold Included; intros; auto).\n      generalize (classic (h = Φ)); intros; destruct H9; auto.\n      rewrite H9 in H5; contradiction. }\n    apply H8 in H9; clear H8; destruct H9.\n    assert (h ∈ R /\\ LastMember x E h).\n    { split; auto; unfold R; apply AxiomII; split; auto. }\n    apply Theorem133 in H9; unfold PlusOne in H9.\n    unfold FirstMember in H8; destruct H8.\n    generalize (classic (x ∈ (En_S P))); intros; destruct H11.\n    + apply H3 in H11; assert (x ∈ h).\n      { rewrite H9; apply Theorem4; right; apply AxiomII; Ens. }\n      unfold LessEqual in H11; destruct H11.\n      * add (x ∈ h) H11; clear H12.\n        generalize (Theorem102 h x); intros; contradiction.\n      * rewrite H11 in H12; generalize (Theorem101 x); contradiction.\n    + assert (x ∈ (En_S P) <-> (Ensemble x /\\ x ∈ W /\\ ~ (P x))).\n      { unfold En_S; split; intros.\n        - apply AxiomII in H12; apply H12.\n        - apply AxiomII; auto. }\n      apply definition_not in H12; auto; clear H11.\n      apply not_and_or in H12; destruct H12.\n      * absurd (Ensemble x); Ens.\n      * assert (x ∈ W).\n        { unfold W; apply AxiomII; split; Ens.\n          apply Theorem132 in H8; auto. }\n        apply not_and_or in H11; destruct H11; try contradiction.\n        apply NNPP in H11; add (P x) H12; clear H11.\n        apply H0 in H12; unfold PlusOne in H12.\n        rewrite <- H9 in H12; contradiction.\nQed.\n\n\n(* Definition139 : c is a choice function if and only if c is a function and\n   c(x) ∈ x for each member x of domain c. *)\n\nDefinition ChoiceFunction c : Prop :=\n  Function c /\\ (forall x, x ∈ dom(c) -> c[x] ∈ x).\n\nHint Unfold ChoiceFunction : set.\n\n\n(* IX Axiom of Choice : There is a choice function c whose domain is μ ~ {Φ}. *)\n\nAxiom AxiomIX : exists c, ChoiceFunction c /\\ dom(c) = μ ~ [Φ].\n\nHint Resolve AxiomIX : set.\n\n\n(* Theorem140 : If x is a set there is a 1_1 function whose range is x and\n   whose domain is an ordinal number. *)\n\nLemma Ex_Lemma140 : forall x c,\n  Ensemble x -> ChoiceFunction c ->\n  (exists g, forall h, Ensemble h -> g[h] = c[x ~ ran(h)]).\nProof.\n  intros.\n  unfold ChoiceFunction in H0; destruct H0.\n  exists (\\{\\ λ u v, v = c [x ~ ran(u)] \\}\\); intros.\n  apply AxiomI; split; intros.\n  - apply AxiomII; split; Ens; intros.\n    apply AxiomII in H3; destruct H3.\n    apply H5; clear H5; apply AxiomII; split; Ens.\n    apply AxiomII_P; split; try apply Theorem49; Ens.\n    apply AxiomII in H4; destruct H4.\n    rewrite Theorem70 in H5; auto.\n    apply AxiomII_P in H5; apply H5.\n  - apply AxiomII; split; Ens; intros.\n    apply AxiomII in H4; destruct H4.\n    apply AxiomII_P in H5; destruct H5.\n    rewrite H6; auto.\nQed.\n\nLemma Lemma140 : forall f g y,\n  y ∈ dom(f) -> f [y] = g [f|(y)] -> Ensemble (f|(y)).\nProof.\n  intros.\n  generalize (classic ((f|(y)) ∈ dom(g))); intros; destruct H1; Ens.\n  apply Theorem69 in H1; rewrite H1 in H0; clear H1.\n  apply Theorem69 in H; rewrite H0 in *.\n  generalize (Theorem101 μ); intros; contradiction.\nQed.\n\nTheorem Theorem140 : forall x,\n  Ensemble x -> exists f, Function1_1 f /\\ ran(f) = x /\\ Ordinal_Number dom(f).\nProof.\n  intros.\n  generalize AxiomIX; intros; destruct H0 as [c H0], H0.\n  double H0; apply (Ex_Lemma140 x _) in H2; auto; destruct H2 as [g H2].\n  generalize (Theorem128 g); intros; destruct H3 as [f H3], H3, H4.\n  unfold ChoiceFunction in H0; destruct H0; exists f.\n  assert (Function1_1 f).\n  { unfold Function1_1; split; auto.\n    unfold Function; split; intros.\n    - unfold Relation; intros; PP H7 a b; Ens.\n    - unfold Inverse in H7; destruct H7.\n      apply AxiomII_P in H7; apply AxiomII_P in H8; destruct H7, H8.\n      clear H7 H8; double H9; apply Property_dom in H8.\n      double H10; apply Property_dom in H10.\n      generalize (classic (y = z)); intros; destruct H11; auto.\n      assert (Ordinal y /\\ Ordinal z).\n      { split; apply (Theorem111 dom(f) _); auto. }\n      elim H12; intros; apply Theorem110 in H12.\n      assert (Ordinal_Number y /\\ Ordinal_Number z).\n      { unfold Ordinal_Number, R; split; apply AxiomII; Ens. }\n      clear H13 H14; destruct H15; apply H5 in H13; apply H5 in H14.\n      rewrite H2 in H13, H14; try apply (Lemma140 _ g _); auto.\n      clear H2 H5; apply Property_Value in H8; auto.\n      apply Property_Value in H10; auto.\n      unfold Function in H3; destruct H3.\n      add ([y,f[y]] ∈ f) H7; add ([z,f[z]] ∈ f) H9.\n      apply H3 in H7; apply H3 in H9; rewrite H9 in H7; clear H9.\n      double H8; double H10; apply Property_ran in H8.\n      apply Property_ran in H10; destruct H12.\n      + assert (f[z] ∈ ran(f|(z))).\n        { rewrite H7; unfold Range; apply AxiomII; split; Ens.\n          exists y; unfold Restriction; apply Theorem4'; split; auto.\n          unfold Cartesian; apply AxiomII_P; split; Ens.\n          split; auto; apply Theorem19; Ens. }\n        assert ((x ~ ran(f|(z))) ∈ dom(c)).\n        { generalize (classic ((x ~ ran(f|(z))) ∈ dom(c))); intros.\n          destruct H16; auto; apply Theorem69 in H16; auto.\n          rewrite H16 in H14; rewrite H14 in H10; AssE μ.\n          generalize Theorem39; intros; contradiction. }\n        apply H6 in H16; unfold Setminus at 2 in H16.\n        rewrite <- H14 in H16; apply Theorem4' in H16; destruct H16.\n        unfold Complement in H17; apply AxiomII in H17; destruct H17.\n        unfold NotIn in H18; contradiction.\n      + destruct H12; try contradiction.\n        assert (f[y] ∈ ran(f|(y))).\n        { rewrite <- H7; unfold Range; apply AxiomII; split; Ens.\n          exists z; unfold Restriction; apply Theorem4'; split; auto.\n          unfold Cartesian; apply AxiomII_P; split; Ens.\n          split; auto; apply Theorem19; Ens. }\n        assert ((x ~ ran(f|(y))) ∈ dom(c)).\n        { generalize (classic ((x ~ ran(f|(y))) ∈ dom(c))); intros.\n          destruct H16; auto; apply Theorem69 in H16; auto.\n          rewrite H16 in H13; rewrite H13 in H8; AssE μ.\n          generalize Theorem39; intros; contradiction. }\n        apply H6 in H16; unfold Setminus at 2 in H16.\n        rewrite <- H13 in H16; apply Theorem4' in H16; destruct H16.\n        unfold Complement in H17; apply AxiomII in H17; destruct H17.\n        unfold NotIn in H18; contradiction. }\n  split; auto; assert (ran(f) ⊂ x).\n  { unfold Included; intros; unfold Range in H8; apply AxiomII in H8.\n    destruct H8, H9; double H9; apply Property_dom in H10.\n    assert (Ordinal_Number x0).\n    { unfold Ordinal_Number, R; apply AxiomII; split; Ens.\n      apply (Theorem111 dom(f) _); split; auto. }\n    apply H5 in H11; rewrite H2 in H11; try apply (Lemma140 _ g _); auto.\n    apply Property_Value in H10; auto; destruct H3.\n    add ([x0,f[x0]]∈f) H9; apply H12 in H9; rewrite <- H9 in H11.\n    assert ((x ~ ran(f|(x0))) ∈ dom(c)).\n    { generalize (classic ((x ~ ran(f|(x0))) ∈ dom(c))); intros.\n      destruct H13; auto; apply Theorem69 in H13; auto.\n      rewrite H13 in H11; rewrite H11 in H9; rewrite <- H9 in H10.\n      clear H9 H11 H13; apply Property_ran in H10; AssE μ.\n      generalize Theorem39; intros; contradiction. }\n    apply H6 in H13; rewrite <- H11 in H13.\n    unfold Setminus in H13; apply Theorem4' in H13; apply H13. }\n  assert (Ensemble dom(f)).\n  { unfold Function1_1 in H7; destruct H7 as [H9 H7]; clear H9.\n    generalize (Property_F11 f); intros; destruct H9; rewrite <- H9 in H8.\n    rewrite <- H10; apply AxiomV; apply Theorem33 in H8; auto. }\n  assert (Ordinal_Number dom(f)).\n  { unfold Ordinal_Number; apply AxiomII; split; auto. }\n  split; auto; apply H5 in H10.\n  assert (f|(dom(f)) = f).\n  { unfold Restriction; apply AxiomI; split; intros.\n    - apply AxiomII in H11; apply H11.\n    - apply AxiomII; repeat split; Ens.\n      PP' H12; apply AxiomII_P; repeat split; Ens.\n      + apply Property_dom in H11; auto.\n      + apply Property_ran in H11; apply Theorem19; Ens. }\n  rewrite H11 in *; clear H11.\n  rewrite H2 in H10; try apply Theorem75; auto.\n  generalize (Theorem101 dom(f)); intros.\n  apply Theorem69 in H11; auto; rewrite H10 in H11.\n  generalize (classic ((x ~ ran(f)) ∈ dom(c))); intros; destruct H12.\n  - apply Theorem69 in H12; auto; rewrite H11 in H12.\n    generalize (Theorem101 μ); intros; contradiction.\n  - rewrite H1 in H12; unfold Setminus at 2 in H12.\n    assert ((x ~ ran(f)) ∈ (μ ∩ ¬[Φ]) <-> (x ~ ran(f)) ∈ μ /\\\n            (x ~ ran(f)) ∈ ¬[Φ]).\n    { split; intros; try apply Theorem4'; auto. }\n    apply definition_not in H13; auto; clear H12.\n    assert (Ensemble (x ~ ran(f))).\n    { apply (Theorem33 x _); auto; unfold Included.\n      intros; apply AxiomII in H12; apply H12. }\n    apply not_and_or in H13; destruct H13.\n    + elim H13; apply Theorem19; auto.\n    + assert ((x ~ ran(f)) ∈ ¬[Φ] <-> Ensemble (x ~ ran(f)) /\\\n              (x ~ ran(f)) ∉ [Φ]).\n      { split; intros; try apply AxiomII; auto.\n        apply AxiomII in H14; apply H14. }\n      apply definition_not in H14; auto; clear H13.\n      apply not_and_or in H14; destruct H14; try contradiction.\n      unfold NotIn in H13; apply NNPP in H13.\n      unfold Singleton in H13; apply AxiomII in H13; destruct H13.\n      generalize AxiomVIII; intros; destruct H15, H15, H16.\n      AssE Φ; clear H15 H16 H17; apply Theorem19 in H18.\n      apply H14 in H18; symmetry; apply -> Property_Φ in H18; auto.\nQed.\n\nHint Resolve Theorem140 : set.\n\n\n(* Definition144 : x ≈ y if and only if there is a 1_1 function f with\n   domain f = x and range f = y. *)\n\nDefinition Equivalent x y : Prop :=\n  exists f, Function1_1 f /\\ dom(f) = x /\\ ran(f) = y.\n\nNotation \"x ≈ y\" := (Equivalent x y) (at level 70).\n\nHint Unfold Equivalent : set.\n\n\n(* Theorem145 : x ≈ x. *)\n\nTheorem Theorem145 : forall x, x ≈ x.\nProof.\n  intros.\n  unfold Equivalent.\n  exists (\\{\\ λ u v, u ∈ x /\\ u = v \\}\\); split.\n  - unfold Function1_1; split.\n    + unfold Function; split; intros.\n      * unfold Relation; intros; PP H a b; Ens.\n      * destruct H; apply AxiomII_P in H.\n        apply AxiomII_P in H0; destruct H, H0, H1, H2.\n        rewrite <- H3, <- H4; auto.\n    + unfold Function; split; intros.\n      * unfold Relation; intros; PP H a b; Ens.\n      * unfold Inverse in H; destruct H; apply AxiomII_P in H.\n        apply AxiomII_P in H0; destruct H, H0.\n        apply AxiomII_P in H1; apply AxiomII_P in H2.\n        destruct H1, H2, H3, H4; rewrite H5, H6; auto.\n   - split.\n     + apply AxiomI; split; intros.\n       * unfold Domain in H; apply AxiomII in H; destruct H, H0.\n         apply AxiomII_P in H0; apply H0.\n       * unfold Domain; apply AxiomII; split; Ens.\n         exists z; apply AxiomII_P; repeat split; auto.\n         apply Theorem49; split; Ens.\n     + apply AxiomI; split; intros.\n       * unfold Range in H; apply AxiomII in H; destruct H, H0.\n         apply AxiomII_P in H0; destruct H0, H1.\n         rewrite H2 in H1; auto.\n       * unfold Range; apply AxiomII; split; Ens.\n         exists z; apply AxiomII_P; repeat split; auto.\n         apply Theorem49; split; Ens.\nQed.\n\nHint Resolve Theorem145 : set.\n\n\n(* Theorem146 : If x ≈ y, then y ≈ x. *)\n\nTheorem Theorem146 : forall x y, x ≈ y -> y ≈ x.\nProof.\n  intros.\n  unfold Equivalent in H; destruct H as [f H], H, H0.\n  unfold Equivalent; exists f⁻¹; split.\n  - unfold Function1_1 in H; destruct H.\n    unfold Function1_1; split; try rewrite Theorem61; auto.\n  - unfold Inverse; split.\n    + unfold Domain; apply AxiomI; split; intros.\n      * apply AxiomII in H2; destruct H2, H3.\n        apply AxiomII_P in H3; destruct H3.\n        apply Property_ran in H4; rewrite H1 in H4; auto.\n      * apply AxiomII; split; Ens.\n        rewrite <- H1 in H2; unfold Range in H2.\n        apply AxiomII in H2; destruct H2, H3.\n        exists (x0); apply AxiomII_P; split; auto.\n        apply Theorem49; AssE ([x0,z]).\n        apply Theorem49 in H4; destruct H4; Ens.\n    + unfold Range; apply AxiomI; split; intros.\n      * apply AxiomII in H2; destruct H2, H3.\n        apply AxiomII_P in H3; destruct H3.\n        apply Property_dom in H4; rewrite H0 in H4; auto.\n      * apply AxiomII; split; Ens.\n        rewrite <- H0 in H2; unfold Domain in H2.\n        apply AxiomII in H2; destruct H2, H3.\n        exists (x0); apply AxiomII_P; split; auto.\n        apply Theorem49; AssE ([z,x0]).\n        apply Theorem49 in H4; destruct H4; Ens.\nQed.\n\nHint Resolve Theorem146 : set.\n\n\n(* Theorem147 : If x ≈ y and y ≈ z, then x ≈ z. *)\n\nTheorem Theorem147 : forall x y z,\n  x ≈ y -> y ≈ z -> x ≈ z.\nProof.\n  intros.\n  unfold Equivalent in H, H0; unfold Equivalent.\n  destruct H as [f1 H], H0 as [f2 H0], H, H0, H1, H2.\n  exists (\\{\\λ u v, exists w, [u,w] ∈ f1 /\\ [w,v] ∈ f2\\}\\); split.\n  - unfold Function1_1; unfold Function1_1 in H, H0.\n    destruct H, H0; split.\n    + unfold Function; split; intros.\n      * unfold Relation; intros; PP H7 a b; Ens.\n      * destruct H7; apply AxiomII_P in H7; destruct H7, H9.\n        apply AxiomII_P in H8; destruct H8, H10; clear H7 H8.\n        unfold Function in H, H0; destruct H9, H10, H, H0.\n        add ([x0,x2] ∈ f1) H7; apply H11 in H7; rewrite H7 in H8.\n        add ([x2,z0] ∈ f2) H8; apply H12 in H8; auto.\n    + unfold Function; split; intros.\n      * unfold Relation; intros; PP H7 a b; Ens.\n      * unfold Inverse in H7; destruct H7; apply AxiomII_P in H7.\n        apply AxiomII_P in H8; destruct H7, H8; clear H7 H8.\n        apply AxiomII_P in H9; destruct H9, H8.\n        apply AxiomII_P in H10; destruct H10, H10; clear H7 H9.\n        unfold Function in H5, H6; destruct H8, H10, H5, H6.\n        assert ([x0,x1] ∈ f2⁻¹ /\\ [x0,x2] ∈ f2⁻¹).\n        { unfold Inverse; split.\n          - apply AxiomII_P; split; auto; AssE [x1,x0].\n            apply Theorem49 in H13; destruct H13.\n            apply Theorem49; split; auto.\n          - apply AxiomII_P; split; auto; AssE [x2,x0].\n            apply Theorem49 in H13; destruct H13.\n            apply Theorem49; split; auto. }\n        apply H12 in H13; rewrite H13 in H7; clear H8 H10 H12 H13.\n        assert ([x2,y0] ∈ f1⁻¹ /\\ [x2,z0] ∈ f1⁻¹).\n        { unfold Inverse; split.\n          - apply AxiomII_P; split; auto; AssE [y0,x2].\n            apply Theorem49 in H8; destruct H8.\n            apply Theorem49; split; auto.\n          - apply AxiomII_P; split; auto; AssE [z0,x2].\n            apply Theorem49 in H8; destruct H8.\n            apply Theorem49; split; auto. }\n        apply H11 in H8; auto.\n  - rewrite <- H1, <- H4; split.\n    + apply AxiomI; split; intros.\n      * apply AxiomII in H5; destruct H5, H6.\n        apply AxiomII_P in H6; destruct H6, H7, H7.\n        apply Property_dom in H7; auto.\n      * apply AxiomII; split; Ens; apply AxiomII in H5.\n        destruct H5, H6; double H6; apply Property_ran in H7.\n        rewrite H3 in H7; rewrite <- H2 in H7; apply AxiomII in H7.\n        destruct H7, H8; exists x1; apply AxiomII_P; split; Ens.\n        AssE [z0,x0]; AssE [x0,x1]; apply Theorem49 in H9.\n        apply Theorem49 in H10; destruct H9, H10.\n        apply Theorem49; split; auto.\n    + apply AxiomI; split; intros.\n      * apply AxiomII in H5; destruct H5, H6.\n        apply AxiomII_P in H6; destruct H6, H7, H7.\n        apply Property_ran in H8; auto.\n      * apply AxiomII; split; Ens; apply AxiomII in H5.\n        destruct H5, H6; double H6; apply Property_dom in H7.\n        rewrite H2 in H7; rewrite <- H3 in H7; apply AxiomII in H7.\n        destruct H7, H8; exists x1; apply AxiomII_P; split; Ens.\n        AssE [x0,z0]; AssE [x1,x0]; apply Theorem49 in H9.\n        apply Theorem49 in H10; destruct H9, H10.\n        apply Theorem49; split; auto.\nQed.\n\nHint Resolve Theorem147 : set.\n\n\n(* Definition148 : x is a cardinal number if and onlu if x is a ordinal number\n   and, if y∈R and y≺x, then it is false that x ≈ y. *)\n\nDefinition Cardinal_Number x : Prop :=\n  Ordinal_Number x /\\ (forall y, y∈R -> y ≺ x -> ~ (x ≈ y)).\n\nHint Unfold Cardinal_Number : set.\n\n\n(* Definition149 : C = {x : x is a cardinal number}. *)\n\nDefinition C : Class := \\{ λ x, Cardinal_Number x \\}.\n\nHint Unfold C : set.\n\n\n(* Definition151 : P = {(x,y) : x ≈ y and y∈C}. *)\n\nDefinition P : Class := \\{\\ λ x y, x ≈ y /\\ y∈C \\}\\.\n\nHint Unfold P : set.\n\n\n(* Theorem152 : P is a function, domain P = μ and range P = C. *)\n\nTheorem Theorem152 : Function P /\\ dom(P) = μ /\\ ran(P) = C.\nProof.\n  unfold P; repeat split; intros.\n  - unfold Relation; intros; PP H a b; Ens.\n  - destruct H; apply AxiomII_P in H; apply AxiomII_P in H0.\n    destruct H, H0, H1, H2; apply Theorem146 in H1.\n    apply (Theorem147 _ _ z) in H1; auto; clear H H0 H2.\n    unfold C in H3, H4; apply AxiomII in H3; destruct H3.\n    apply AxiomII in H4; destruct H4.\n    unfold Cardinal_Number in H0, H3; destruct H0, H3.\n    unfold Ordinal_Number in H0, H3.\n    assert (Ordinal y /\\ Ordinal z).\n    { unfold R in H0, H3; apply AxiomII in H0.\n      apply AxiomII in H3; destruct H0, H3; split; auto. }\n    apply Theorem110 in H6; destruct H6.\n    + apply Theorem146 in H1; apply H5 in H0; auto; try contradiction.\n    + destruct H6; auto; apply H4 in H3; auto; try contradiction.\n  - apply AxiomI; split; intros; try apply Theorem19; Ens.\n    apply Theorem19 in H; double H; apply Theorem140 in H0.\n    destruct H0 as [f H0], H0, H1; apply AxiomII; split; auto.\n    assert (KWellOrder E \\{ λ x, x ≈ z /\\ Ordinal x \\}).\n    { assert (\\{ λ x, x ≈ z /\\ Ordinal x \\} ⊂ R).\n      { unfold Included; intros; apply AxiomII in H3.\n        destruct H3, H4; apply AxiomII; split; auto. }\n      apply (Lemma97 _ E _) in H3; auto.\n      apply Theorem107; apply Theorem113. }\n    unfold KWellOrder in H3; destruct H3 as [H4 H3]; clear H4.\n    assert (\\{ λ x, x ≈ z /\\ Ordinal x \\} ⊂ \\{ λ x, x ≈ z /\\ Ordinal x \\}\n            /\\ \\{ λ x, x ≈ z /\\ Ordinal x \\} ≠ Φ).\n    { split; try unfold Included; auto.\n      apply Property_NotEmpty; exists dom(f); apply AxiomII.\n      unfold Ordinal_Number, R in H2; apply AxiomII in H2; destruct H2.\n      split; auto; split; auto; unfold Equivalent; exists f; auto. }\n    apply H3 in H4; destruct H4; unfold FirstMember in H4; destruct H4.\n    apply AxiomII in H4; destruct H4, H6.\n    exists x; apply AxiomII_P.\n    repeat split; try apply Theorem49; auto.\n    + apply Theorem146; unfold Equivalent; Ens.\n    + unfold C; apply AxiomII; split; auto.\n      unfold Cardinal_Number; split; intros.\n      { unfold Ordinal_Number, R; apply AxiomII; auto. }\n      { unfold Less in H9; unfold R in H8.\n        apply AxiomII in H8; destruct H8; intro.\n        assert (y ∈ \\{ λ x,x ≈ z /\\ Ordinal x \\}).\n        { apply AxiomII; split; auto; split; auto.\n          apply Theorem146 in H11; apply (Theorem147 _ x _); auto. }\n        apply H5 in H12; apply H12; unfold Rrelation, E.\n        apply AxiomII_P; split; try apply Theorem49; auto. }\n  - unfold Range; apply AxiomI; split; intros.\n    + apply AxiomII in H; destruct H, H0.\n      apply AxiomII_P in H0; apply H0.\n    + apply AxiomII; split; Ens; exists z; apply AxiomII_P.\n      repeat split; try apply Theorem49; Ens.\n      apply Theorem145.\nQed.\n\nHint Resolve Theorem152 : set.\n\n\n(* Property of P *)\n\nCorollary Property_PClass : forall x, Ensemble x -> P [x] ∈ C.\nProof.\n  intros.\n  generalize Theorem152; intros; destruct H0, H1.\n  apply Theorem19 in H; rewrite <- H1 in H.\n  apply Property_Value in H; auto.\n  apply Property_ran in H; rewrite H2 in H; auto.\nQed.\n\nHint Resolve Property_PClass : set.\n\n\n(* Theorem153 : If x is a set, then P(x) ≈ x. *)\n\nTheorem Theorem153 : forall x, Ensemble x -> P[x] ≈ x.\nProof.\n  intros.\n  generalize Theorem152; intros; destruct H0, H1.\n  apply Theorem19 in H; rewrite <- H1 in H.\n  apply Property_Value in H; auto.\n  unfold P at 2 in H; apply AxiomII_P in H.\n  apply Theorem146; apply H.\nQed.\n\nHint Resolve Theorem153 : set.\n\n\n(* Theorem163 : If x∈w, y∈w and x+1 ≈ y+1, then x ≈ y. *)\n\nLtac SplitEns := apply AxiomII; split; Ens.\n\nLtac SplitEnsP := apply AxiomII_P; split; try apply Theorem49; Ens.\n\nDefinition En_g' f x y : Class :=\n  \\{\\ λ u v, [u,v] ∈ (f ~ ([[x,f[x]]] ∪ [[f⁻¹[y],y]])) \\/\n      [u,v] = [f⁻¹[y],f[x]] \\/ [u,v] = [x,y] \\}\\.\n\nTheorem Theorem163 : forall x y,\n  x∈W -> y∈W -> (PlusOne x) ≈ (PlusOne y) -> x ≈ y.\nProof.\n  intros.\n  unfold Equivalent in H1; destruct H1 as [f H1], H1, H2.\n  unfold Function1_1 in H1; destruct H1; unfold Equivalent.\n  exists ((En_g' f x y) | (x)); repeat split; intros.\n  - unfold Relation; intros; unfold Restriction in H5.\n    apply Theorem4' in H5; destruct H5; PP H6 a b; Ens.\n  - destruct H5; unfold Restriction in H5, H6.\n    apply Theorem4' in H5; apply Theorem4' in H6.\n    destruct H5, H6; clear H8; unfold En_g' in H5, H6.\n    apply AxiomII_P in H5; apply AxiomII_P in H6; destruct H5,H6.\n    unfold Cartesian in H7; apply AxiomII_P in H7; clear H5.\n    destruct H7, H7; clear H10; destruct H8, H9.\n    + unfold Setminus in H8, H9; apply Theorem4' in H8.\n      apply Theorem4' in H9; destruct H8, H9; clear H10 H11.\n      unfold Function in H1; apply H1 with (x:= x0); auto.\n    + destruct H9.\n      * unfold Setminus in H8; apply Theorem4' in H8; destruct H8.\n        unfold Complement in H10; apply AxiomII in H10; clear H5.\n        destruct H10; elim H10; clear H10; apply Theorem4.\n        right; apply AxiomII; split; auto; intros; clear H10.\n        apply Theorem49 in H6; apply Theorem55 in H9; auto.\n        destruct H9; clear H10; double H8; apply Property_dom in H10.\n        apply Property_Value in H10; auto; add ([x0,f[x0]] ∈ f) H8.\n        apply H1 in H8; clear H10; rewrite H9 in H8.\n        rewrite <- Lemma96''' in H8; auto. rewrite H8, H9; auto.\n        rewrite H3; unfold PlusOne; apply Theorem4; right.\n        unfold Singleton; apply AxiomII; split; Ens.\n      * apply Theorem49 in H6; apply Theorem55 in H9; auto; destruct H9.\n        rewrite H9 in H7; generalize (Theorem101 x); contradiction.\n    + destruct H8.\n      * unfold Setminus in H9; apply Theorem4' in H9; destruct H9.\n        unfold Complement in H10; apply AxiomII in H10; clear H6.\n        destruct H10; elim H10; clear H10; apply Theorem4.\n        right; apply AxiomII; split; auto; intros; clear H10.\n        apply Theorem49 in H5; apply Theorem55 in H8; auto.\n        destruct H8; clear H10; double H9; apply Property_dom in H10.\n        apply Property_Value in H10; auto; add ([x0,f[x0]] ∈ f) H9.\n        apply H1 in H9; clear H10; rewrite H8 in H9.\n        rewrite <- Lemma96''' in H9; auto. rewrite H8, H9; auto.\n        rewrite H3; unfold PlusOne; apply Theorem4; right.\n        unfold Singleton; apply AxiomII; split; Ens.\n      * apply Theorem49 in H5; apply Theorem55 in H8; auto; destruct H8.\n        rewrite H8 in H7; generalize (Theorem101 x); contradiction.\n    + apply Theorem49 in H5; apply Theorem49 in H6.\n      destruct H8, H9; apply Theorem55 in H8; apply Theorem55 in H9; auto.\n      * destruct H8, H9; rewrite H10, H11; auto.\n      * destruct H9; rewrite H9 in H7.\n        generalize (Theorem101 x); intros; contradiction.\n      * destruct H8; rewrite H8 in H7.\n        generalize (Theorem101 x); intros; contradiction.\n      * destruct H8; rewrite H8 in H7.\n        generalize (Theorem101 x); intros; contradiction.\n  - unfold Relation; intros; PP H5 a b; Ens.\n  - destruct H5; unfold Inverse, Restriction in H5, H6.\n    apply AxiomII_P in H5; apply AxiomII_P in H6; destruct H5, H6.\n    apply Theorem4' in H7; apply Theorem4' in H8; destruct H7, H8.\n    apply AxiomII_P in H7; apply AxiomII_P in H8; destruct H7, H8.\n    unfold Cartesian in H9; apply AxiomII_P in H9; clear H7.\n    destruct H9, H9; clear H13; apply AxiomII_P in H10; clear H8.\n    destruct H10, H10; clear H13; destruct H11, H12.\n    + unfold Setminus in H11, H12; apply Theorem4' in H11.\n      apply Theorem4' in H12; destruct H11, H12; clear H13 H14.\n      assert ([x0,y0] ∈ f⁻¹ /\\ [x0,z] ∈ f⁻¹).\n      { unfold Inverse; split; apply AxiomII_P; split; auto. }\n      unfold Function in H4; apply H4 in H13; auto.\n    + destruct H12.\n      * unfold Setminus in H11; apply Theorem4' in H11; destruct H11.\n        clear H13; apply Theorem49 in H8; apply Theorem55 in H12; auto.\n        destruct H12; rewrite H13 in *; double H11.\n        apply Property_ran in H14; apply Property_Value' in H14; auto.\n        assert ([f[x],y0] ∈ f⁻¹ /\\ [f[x],x] ∈ f⁻¹).\n        { unfold Inverse; split; apply AxiomII_P; split; auto; AssE [x,f[x]].\n          apply Theorem49 in H15; destruct H15; apply Theorem49; auto. }\n        unfold Function in H4; apply H4 in H15; auto.\n        rewrite H15 in H9; generalize (Theorem101 x); contradiction.\n      * unfold Setminus in H11; apply Theorem4' in H11; destruct H11.\n        unfold Complement in H13; apply AxiomII in H13; clear H7.\n        destruct H13; elim H13; clear H13; apply Theorem4.\n        right; apply AxiomII; split; auto; intros; clear H13.\n        apply Theorem49 in H8; apply Theorem55 in H12; auto.\n        destruct H12; rewrite H13 in *; clear H6 H8 H12 H13.\n        assert ([y,y0] ∈ f⁻¹). { apply AxiomII_P; Ens. }\n        double H6; apply Property_dom in H8; apply Property_Value in H8; auto.\n        add ([y,y0] ∈ f⁻¹) H8; apply H4 in H8; rewrite H8; auto.\n    + destruct H11.\n      * unfold Setminus in H12; apply Theorem4' in H12; destruct H12.\n        clear H13; apply Theorem49 in H7; apply Theorem55 in H11; auto.\n        destruct H11; rewrite H13 in *; double H12.\n        apply Property_ran in H14; apply Property_Value' in H14; auto.\n        assert ([f[x],z] ∈ f⁻¹ /\\ [f[x],x] ∈ f⁻¹).\n        { unfold Inverse; split; apply AxiomII_P; split; auto; AssE [x,f[x]].\n          apply Theorem49 in H15; destruct H15; apply Theorem49; auto. }\n        unfold Function in H4; apply H4 in H15; auto.\n        rewrite H15 in H10; generalize (Theorem101 x); contradiction.\n      * unfold Setminus in H12; apply Theorem4' in H12; destruct H12.\n        unfold Complement in H13; apply AxiomII in H13; clear H8.\n        destruct H13; elim H13; clear H13; apply Theorem4.\n        right; apply AxiomII; split; auto; intros; clear H13.\n        apply Theorem49 in H7; apply Theorem55 in H11; auto.\n        destruct H11; rewrite H13 in *; clear H5 H7 H11 H13.\n        assert ([y,z] ∈ f⁻¹). { apply AxiomII_P; Ens. }\n        double H5; apply Property_dom in H7; apply Property_Value in H7; auto.\n        add ([y,z] ∈ f⁻¹) H7; apply H4 in H7; rewrite H7; auto.\n    + apply Theorem49 in H7; apply Theorem49 in H8.\n      destruct H11, H12; apply Theorem55 in H11; apply Theorem55 in H12; auto.\n      * destruct H11, H12; rewrite H11, H12; auto.\n      * destruct H12; rewrite H12 in H10.\n        generalize (Theorem101 x); intros; contradiction.\n      * destruct H11; rewrite H11 in H9.\n        generalize (Theorem101 x); intros; contradiction.\n      * destruct H12; rewrite H12 in H10.\n        generalize (Theorem101 x); intros; contradiction.\n  - apply AxiomI; split; intros.\n    + unfold Domain in H5; apply AxiomII in H5; destruct H5, H6.\n      unfold Restriction in H6; apply Theorem4' in H6; destruct H6.\n      unfold Cartesian in H7; apply AxiomII_P in H7; apply H7.\n    + unfold Domain; apply AxiomII; split; Ens.\n      assert ([x,f[x]] ∈ f).\n      { apply Property_Value; auto; rewrite H2; unfold PlusOne.\n        apply Theorem4; right; apply AxiomII; split; Ens. }\n      generalize (classic (z = f⁻¹[y])); intros; destruct H7.\n      * rewrite H7 in *; AssE [x,f[x]]; clear H6 H7.\n        apply Theorem49 in H8; destruct H8.\n        exists f[x]; unfold Restriction; apply Theorem4'.\n        split; SplitEnsP; split; try apply Theorem19; auto.\n      * assert (z ∈ dom(f)). { rewrite H2; apply Theorem4; tauto. }\n        apply Property_Value in H8; auto; AssE [z,f[z]].\n        apply Theorem49 in H9; destruct H9; exists f[z].\n        unfold Restriction; apply Theorem4'; split; SplitEnsP.\n        { left; unfold Setminus; apply Theorem4'; split; auto.\n          unfold Complement; apply AxiomII; split; Ens.\n          intro; apply Theorem4 in H11; destruct H11.\n          - apply AxiomII in H11; destruct H11; clear H11.\n            assert ([x,f[x]] ∈ μ). { apply Theorem19; Ens. }\n            apply H12 in H11; clear H12; apply Theorem55 in H11; auto.\n            destruct H11; rewrite H11 in H5; generalize (Theorem101 x); auto.\n          - apply AxiomII in H11; destruct H11; clear H11.\n            assert ([(f⁻¹)[y],y] ∈ μ).\n            { apply Theorem19; Ens; exists f.\n              assert (y ∈ ran(f)).\n              { rewrite H3; unfold PlusOne; apply Theorem4; right.\n                apply AxiomII; split; Ens. }\n              rewrite Lemma96' in H11; apply Property_Value in H11; auto.\n              apply AxiomII_P in H11; apply H11. }\n            apply H12 in H11; clear H12; apply Theorem55 in H11; auto.\n            destruct H11; contradiction. }\n        { split; try apply Theorem19; auto. }\n  - apply AxiomI; split; intros.\n    + unfold Range in H5; apply AxiomII in H5; destruct H5, H6.\n      unfold Restriction in H6; apply Theorem4' in H6; destruct H6.\n      unfold Cartesian in H7; apply AxiomII_P in H7; destruct H7.\n      clear H7; destruct H8; clear H8; unfold En_g' in H6.\n      apply AxiomII_P in H6; destruct H6, H8 as [H8|[H8|H8]].\n      * unfold Setminus in H8; apply Theorem4' in H8; destruct H8.\n        unfold Complement in H9; apply AxiomII in H9; clear H6.\n        destruct H9; double H8; apply Property_ran in H10; rewrite H3 in H10.\n        unfold PlusOne in H10; apply Theorem4 in H10; destruct H10; auto.\n        apply AxiomII in H10; clear H5; destruct H10.\n        rewrite H10 in *; try apply Theorem19; Ens; clear H10.\n        double H8; apply Property_ran in H10; rewrite Lemma96' in H10.\n        apply Property_Value in H10; auto; apply Theorem49 in H6.\n        destruct H6; clear H11; add ([y,x0] ∈ f⁻¹) H10; try SplitEnsP.\n        apply H4 in H10; rewrite H10 in H9; elim H9.\n        apply Theorem4; right; SplitEns.\n      * apply Theorem49 in H6; apply Theorem55 in H8; auto; destruct H8.\n        assert (x ∈ dom(f)).\n        { rewrite H2; unfold PlusOne; apply Theorem4; right.\n          unfold Singleton; apply AxiomII; split; Ens. }\n        double H10; apply Property_Value in H11; auto.\n        apply Property_ran in H11; rewrite H3 in H11; unfold PlusOne in H11.\n        apply Theorem4 in H11; rewrite H9 in *; destruct H11; auto.\n        apply AxiomII in H11; clear H5; destruct H11.\n        rewrite <- H11 in H8; try apply Theorem19; Ens.\n        pattern f at 2 in H8; rewrite <- Theorem61 in H8.\n        rewrite <- Lemma96''' in H8; try rewrite Theorem61; auto.\n        { rewrite H8 in H7; generalize (Theorem101 x); contradiction. }\n        { rewrite <- Lemma96; auto. }\n      * apply Theorem49 in H6; apply Theorem55 in H8; auto; destruct H8.\n        rewrite H8 in H7; generalize (Theorem101 x); contradiction. \n    + unfold Range; apply AxiomII; split; Ens.\n      assert (z∈ran(f)). { rewrite H3; unfold PlusOne; apply Theorem4; auto. }\n      generalize (classic (z = f[x])); intros; destruct H7.\n      * rewrite H7 in *; clear H7.\n        assert (y ∈ ran(f)).\n        { rewrite H3; unfold PlusOne; apply Theorem4; right.\n          unfold Singleton; apply AxiomII; split; Ens. }\n        double H7; rewrite Lemma96' in H8; apply Property_Value in H8; auto.\n        apply Property_ran in H8; rewrite <- Lemma96 in H8; rewrite H2 in H8.\n        unfold PlusOne in H8; apply Theorem4 in H8; destruct H8.\n        { exists (f⁻¹)[y]; unfold Restriction; apply Theorem4'.\n          split; SplitEnsP; split; try apply Theorem19; Ens. }\n        { unfold Singleton in H8; apply AxiomII in H8; destruct H8.\n          rewrite <- H9 in H5; try apply Theorem19; Ens.\n          rewrite <- Lemma96''' in H5; auto.\n          generalize (Theorem101 y); intros; contradiction. }\n      * unfold Range in H6; apply AxiomII in H6; destruct H6, H8; exists x0.\n        AssE [x0,z]; unfold Restriction; apply Theorem4'; split.\n        { unfold En_g'; apply AxiomII_P; split; auto; left.\n          unfold Setminus; apply Theorem4'; split; auto; unfold Complement.\n          apply AxiomII; split; auto; intro; apply Theorem4 in H10.\n          destruct H10; apply AxiomII in H10; destruct H10.\n          - assert ([x,f[x]] ∈ μ); clear H10.\n            { apply Theorem19; Ens; exists f; apply Property_Value; auto.\n              rewrite H2; unfold PlusOne; apply Theorem4; right.\n              unfold Singleton; apply AxiomII; split; Ens. }\n            apply H11 in H12; clear H11; apply Theorem49 in H9.\n            apply Theorem55 in H12; auto; destruct H12; tauto.\n          - assert ([(f⁻¹)[y], y] ∈ μ); clear H10.\n            { apply Theorem19; Ens; exists f. assert (y ∈ ran(f)).\n              { rewrite H3; unfold PlusOne; apply Theorem4; right.\n                apply AxiomII; split; Ens. }\n              rewrite Lemma96' in H10; apply Property_Value in H10; auto.\n              apply AxiomII_P in H10; apply H10. }\n            apply H11 in H12; clear H11; apply Theorem49 in H9.\n            apply Theorem55 in H12; auto; destruct H12; rewrite H11 in H5.\n            generalize (Theorem101 y); intros; contradiction. }\n        { double H8; apply Property_dom in H10; rewrite H2 in H10.\n          unfold PlusOne in H10; apply Theorem4 in H10; unfold Cartesian.\n          apply AxiomII_P; repeat split; auto; try apply Theorem19; Ens.\n          destruct H10; auto; apply AxiomII in H10; destruct H10.\n          rewrite H11 in H8; try apply Theorem19; Ens; double H8.\n          apply Property_dom in H12; apply Property_Value in H12; auto.\n          add ([x,z] ∈ f) H12; apply H1 in H12; symmetry in H12; tauto. }\nQed.\n\nHint Resolve Theorem163 : set.\n\n(* Theorem164 : w ⊂ C. *)\n\nTheorem Theorem164 : W ⊂ C.\nProof.\n  intros.\n  unfold Included; apply Mathematical_Induction.\n  - assert (Φ ∈ W); try apply Theorem135; try apply W.\n    unfold W in H; apply AxiomII in H; destruct H; unfold Integer in H0.\n    destruct H0; unfold C; apply AxiomII.\n    unfold Cardinal_Number, Ordinal_Number; repeat split; intros; auto.\n    + unfold R; apply AxiomII; split; auto.\n    + unfold Less in H3; generalize (Theorem16 y); contradiction.\n  - intros; destruct H; double H; apply Theorem134 in H1; unfold W in H1.\n    apply AxiomII in H1; unfold Integer in H1; destruct H1, H2.\n    unfold C in H0; apply AxiomII in H0; destruct H0.\n    unfold Cardinal_Number, Ordinal_Number in H4; destruct H4.\n    unfold C; apply AxiomII; split; auto; split; intros.\n    + unfold Ordinal_Number, R; apply AxiomII; split; auto.\n    + unfold Less, PlusOne in H7; apply Theorem4 in H7; destruct H7.\n      * assert (y ∈ W).\n        { unfold W; apply AxiomII; split; Ens.\n          unfold W in H; apply AxiomII in H; destruct H.\n          apply Theorem132 in H7; auto. }\n        intro; clear H6; double H8; apply AxiomII in H6; destruct H6.\n        unfold Integer in H10; destruct H10; unfold KWellOrder in H11.\n        destruct H11 as [H12 H11]; clear H12.\n        generalize (classic (y = Φ)); intros; destruct H12.\n        { rewrite H12 in H9; clear H12; unfold Equivalent in H9.\n          destruct H9 as [f H9]; destruct H9, H12.\n          assert (k ∈ (PlusOne k)).\n          { unfold PlusOne; apply Theorem4; right; unfold Singleton.\n            apply AxiomII; split; Ens. }\n          rewrite <- H12 in H14; unfold Function1_1 in H9; destruct H9.\n          apply Property_Value in H14; auto; apply Property_ran in H14.\n          rewrite H13 in H14; generalize (Theorem16 f[k]); contradiction. }\n        { assert (y ⊂ y /\\ y ≠ Φ). { split; unfold Included; Ens. }\n          apply H11 in H13; clear H11 H12; destruct H13.\n          assert (y = PlusOne x).\n          { apply Theorem133; split; auto; try apply AxiomII; Ens. }\n          unfold FirstMember in H11; destruct H11; clear H13.\n          rewrite H12 in H9; apply Theorem163 in H9; auto.\n          - assert (x ∈ R /\\ x ≺ k).\n            { unfold Less; split.\n              - unfold R; apply AxiomII; split; Ens.\n                apply Theorem111 with (x:= y); auto.\n              - unfold R in H4; apply AxiomII in H4; destruct H4.\n                unfold Ordinal, full in H13; destruct H13.\n                apply H14 in H7; apply H7 in H11; auto. }\n            destruct H13; apply H5 in H14; auto.\n          - generalize Property_W; intros; unfold Ordinal, full in H13.\n            destruct H13; apply H14 in H8; apply H8 in H11; auto. }\n      * unfold Singleton in H7; apply AxiomII in H7; destruct H7.\n        assert (k ∈ μ); try apply Theorem19; Ens; apply H8 in H9.\n        clear H6 H7 H8; rewrite H9; intro; clear H9; double H.\n        apply AxiomII in H7; clear H0; destruct H7; unfold Integer in H7.\n        destruct H7; unfold KWellOrder in H8; destruct H8; clear H8.\n        generalize (classic (k = Φ)); intros; destruct H8.\n        { rewrite H8 in H6; clear H8; unfold Equivalent in H6.\n          destruct H6 as [f H6]; destruct H6, H8.\n          assert (Φ ∈ (PlusOne Φ)).\n          { unfold PlusOne; apply Theorem4; right; unfold Singleton.\n            apply AxiomII; split; auto; generalize AxiomVIII; intros.\n            destruct H11, H11, H12; Ens. }\n          rewrite <- H8 in H11; unfold Function1_1 in H6; destruct H6.\n          apply Property_Value in H11; auto; apply Property_ran in H11.\n          rewrite H10 in H11; generalize (Theorem16 f[Φ]); contradiction. }\n        { assert (k ⊂ k /\\ k ≠ Φ). { split; unfold Included; Ens. }\n          apply H9 in H10; clear H8 H9; destruct H10.\n          assert (k = PlusOne x).\n          { apply Theorem133; split; auto; try apply AxiomII; Ens. }\n          unfold FirstMember in H8; destruct H8; clear H10.\n          pattern k at 2 in H6; rewrite H9 in H6; apply Theorem163 in H6; auto.\n          - apply H5 in H8; try contradiction; unfold R; apply AxiomII.\n            split; Ens; apply Theorem111 with (x:= k); auto.\n          - unfold W; apply AxiomII; split; Ens.\n            apply AxiomII in H; destruct H; apply Theorem132 in H8; auto. }\nQed.\n\nHint Resolve Theorem164 : set.\n\n\n(* Definition166 : x is finite if and only if P(x)∈W. *)\n\nDefinition Finite (x: Class) : Prop := P [x] ∈ W.\n\nHint Unfold Finite : set.\n\n\n(* Theorem167 : x is finite if and only if there is r such that r well-orders x\n   and r⁻¹ well-orders x. *)\n\nLemma Lemma167 : forall r x f,\n  KWellOrder r P[x] -> Function1_1 f -> dom(f) = x ->\n  ran(f) = P[x] -> KWellOrder \\{\\ λ u v, Rrelation f[u] r f[v] \\}\\ x.\nProof.\n  intros.\n  unfold Function1_1 in H0; destruct H0.\n  unfold KWellOrder; split; intros.\n  - unfold Connect; intros; destruct H4; rewrite <- H1 in H4, H5.\n    AssE u; AssE v; apply Property_Value in H4; auto.\n    apply Property_Value in H5; auto; double H4; double H5.\n    apply Property_ran in H8; apply Property_ran in H9.\n    rewrite H2 in H8, H9; unfold KWellOrder, Connect in H.\n    destruct H; clear H10; add (f[v] ∈ P[x]) H8; apply H in H8.\n    clear H H9; destruct H8 as [H | [H | H]].\n    + left; unfold Rrelation; apply AxiomII_P; split; try apply Theorem49; auto.\n    + right; left; apply AxiomII_P; split; try apply Theorem49; auto.\n    + right; right; rewrite H in H4; clear H.\n      assert ([f[v],u] ∈ f⁻¹ /\\ [f[v],v] ∈ f⁻¹).\n      { unfold Inverse; split; apply AxiomII_P; split; auto.\n        - apply Theorem49; split; apply Property_ran in H4; Ens.\n        - apply Theorem49; split; apply Property_ran in H5; Ens. }\n      unfold Function in H3; apply H3 in H; auto.\n  - assert (ran(f|(y)) ⊂ P [x] /\\ ran(f|(y)) ≠ Φ).\n    { destruct H4; split.\n      - unfold Included; intros; unfold Range in H6; apply AxiomII in H6.\n        destruct H6, H7; unfold Restriction in H7; apply Theorem4' in H7.\n        destruct H7; apply Property_ran in H7; rewrite H2 in H7; auto.\n      - apply Property_NotEmpty in H5; destruct H5; double H5; apply H4 in H6.\n        rewrite <- H1 in H6; apply Property_Value in H6; auto.\n        double H6; apply Property_ran in H7; apply Property_NotEmpty.\n        exists f[x0]; unfold Range; apply AxiomII; split; Ens.\n        exists x0; unfold Restriction; apply Theorem4'; split; auto.\n        unfold Cartesian; apply AxiomII_P; repeat split; Ens.\n        apply Theorem19; Ens. }\n    apply H in H5; unfold FirstMember in H5; destruct H5, H5.\n    unfold Range in H5; apply AxiomII in H5; destruct H5, H7.\n    unfold Restriction in H7; apply Theorem4' in H7; destruct H7.\n    exists x1; unfold FirstMember; split; intros.\n    + unfold Cartesian in H8; apply AxiomII_P in H8; apply H8.\n    + clear H8; double H9; apply H4 in H9; rewrite <- H1 in H9.\n      apply Property_Value in H9; auto.\n      assert (f[y0] ∈ ran(f|(y))).\n      { AssE [y0,f[y0]]; apply Theorem49 in H10; destruct H10.\n        unfold Range; apply AxiomII; split; auto.\n        exists y0; unfold Restriction; apply Theorem4'; split; auto.\n        apply AxiomII_P; repeat split; try apply Theorem49; auto.\n        apply Theorem19; auto. }\n      apply H6 in H10; clear H6; intro; elim H10; clear H10.\n      unfold Rrelation at 1 in H6; apply AxiomII_P in H6; destruct H6.\n      double H7; apply Property_dom in H11; apply Property_Value in H11; auto.\n      add ([x1,f[x1]] ∈ f) H7; apply H0 in H7; rewrite H7; auto.\nQed.\n\nTheorem Theorem167 : forall x,\n  Finite x <-> exists r, KWellOrder r x /\\ KWellOrder (r⁻¹) x.\nProof.\n  intros; split; intros.\n  - unfold Finite in H.\n    generalize (classic (Ensemble x)); intros; destruct H0.\n    + unfold W in H; apply AxiomII in H; destruct H.\n      unfold Integer in H1; destruct H1; apply Theorem107 in H1.\n      apply Theorem153 in H0; apply Theorem146 in H0.\n      unfold Equivalent in H0; destruct H0 as [f H0], H0, H3.\n      exists (\\{\\ λ u v, Rrelation f[u] E f[v] \\}\\); split.\n      * apply Lemma167; auto.\n      * assert (\\{\\ λ u v, Rrelation f [u] E f [v] \\}\\⁻¹ = \n                \\{\\ λ u v, Rrelation f [u] E⁻¹ f [v] \\}\\).\n        { apply AxiomI; split; intros.\n          - PP H5 a b; apply AxiomII_P; apply AxiomII_P in H6; destruct H6.\n            apply AxiomII_P in H7; destruct H7; split; auto.\n            unfold Rrelation in H8; unfold Rrelation, Inverse.\n            apply AxiomII_P; split; auto; AssE [f[b],f[a]].\n            apply Theorem49 in H9; destruct H9; apply Theorem49; auto.\n          - PP H5 a b; apply AxiomII_P in H6; destruct H6.\n            unfold Rrelation, Inverse in H7; apply AxiomII_P in H7; destruct H7.\n            apply Theorem49 in H6; destruct H6; apply AxiomII_P.\n            split; try apply Theorem49; auto; apply AxiomII_P.\n            split; try apply Theorem49; auto. }\n        rewrite H5; apply Lemma167; auto.\n    + generalize Theorem152; intros; destruct H1, H2.\n      assert (x∉dom(P)). { rewrite H2; intro; apply Theorem19 in H4; tauto. }\n      apply Theorem69 in H4; rewrite H4 in H; AssE μ.\n      generalize Theorem39; intros; contradiction.\n  - destruct H as [r H], H; unfold Finite.\n    generalize Theorem113; intros; destruct H1; clear H2.\n    apply Theorem107 in H1; add (KWellOrder E R) H; clear H1.\n    apply Theorem99 in H; destruct H as [f H], H, H1.\n    unfold Order_PXY in H1; destruct H1, H3, H4, H5; double H6.\n    apply Theorem114 in H7; add (Ordinal W) H7; try apply Property_W.\n    apply Theorem110 in H7; destruct H7.\n    + destruct H2.\n      * assert (P[x] = ran(f)).\n        { apply Theorem164 in H7; clear H0; AssE ran(f).\n          apply Theorem96 in H4; destruct H4; clear H8.\n          assert (dom(f) ≈ ran(f)). { unfold Equivalent; exists f; auto. }\n          unfold Function1_1 in H4; destruct H4.\n          rewrite (Lemma96 f), (Lemma96' f) in *.\n          apply AxiomV in H0; auto; rewrite H2 in *; double H0.\n          apply Theorem153 in H0; apply Property_PClass in H10.\n          apply Theorem147 with (z:= dom(f⁻¹)) in H0; auto; clear H2 H8.\n          unfold C in H7, H10; apply AxiomII in H7; apply AxiomII in H10.\n          destruct H7, H10; clear H2 H8; unfold Cardinal_Number in H7, H10.\n          destruct H7, H10; unfold Ordinal_Number in H2, H8; double H2.\n          double H8; unfold R in H11, H12; apply AxiomII in H11.\n          apply AxiomII in H12; destruct H11, H12; clear H11 H12.\n          add (Ordinal dom(f⁻¹)) H14; clear H13.\n          apply Theorem110 in H14; destruct H14 as [H11 | [H11 | H11]]; auto.\n          - apply H7 in H11; auto; apply Theorem146 in H0; contradiction.\n          - apply H10 in H11; auto; contradiction. }\n          rewrite H8; auto.\n      * rewrite H2 in H7; add (W ∈ R) H7; try apply Theorem138.\n        generalize (Theorem102 R W); intros; contradiction.\n    + assert (W ⊂ ran(f)).\n      { destruct H7; try (rewrite H7; unfold Included; auto).\n        apply Theorem114 in H6; unfold Ordinal, full in H6.\n        destruct H6; apply H8 in H7; auto. }\n      assert (~ exists z, FirstMember z E⁻¹ W).\n      { intro; destruct H9; unfold FirstMember in H9; destruct H9.\n        AssE x0; apply Theorem134 in H9; AssE (PlusOne x0).\n        apply H10 in H9; elim H9; clear H9 H10.\n        unfold Rrelation, Inverse, E; apply AxiomII_P.\n        split; try apply Theorem49; auto; apply AxiomII_P.\n        split; try apply Theorem49; auto; unfold PlusOne.\n        apply Theorem4; right; apply AxiomII; auto. }\n      double H5; unfold Section in H10; destruct H10; clear H11.\n      apply Lemma97 with (r:= r⁻¹) in H10; auto; clear H6; double H4.\n      apply Theorem96 in H6; destruct H6; clear H11; destruct H6 as [H11 H6].\n      clear H11; elim H9; clear H9; unfold KWellOrder in H10; destruct H10.\n      assert (ran(f⁻¹|(W)) ⊂ dom(f) /\\ ran(f⁻¹|(W)) ≠ Φ).\n      { split; unfold Included; intros.\n        - unfold Range in H11; apply AxiomII in H11; destruct H11, H12.\n          unfold Restriction in H12; apply Theorem4' in H12; destruct H12.\n          unfold Inverse in H12; apply AxiomII_P in H12; destruct H12.\n          apply Property_dom in H14; auto.\n        - assert (Φ ∈ W); try apply Theorem135; auto; double H11.\n          apply H8 in H12; rewrite Lemma96' in H12.\n          apply Property_Value in H12; auto; AssE [Φ,(f⁻¹)[Φ]].\n          apply Theorem49 in H13; destruct H13; apply Property_NotEmpty.\n          exists f⁻¹[Φ]; unfold Range; apply AxiomII; split; auto.\n          exists Φ; unfold Restriction; apply Theorem4'; split; auto.\n          apply AxiomII_P; repeat split; try apply Theorem49; auto.\n          apply Theorem19; auto. }\n      apply H10 in H11; clear H10; destruct H11; exists f[x0].\n      unfold FirstMember in H10; destruct H10; split; intros.\n      * clear H11; unfold Range in H10; apply AxiomII in H10; destruct H10, H11.\n        unfold Restriction in H11; apply Theorem4' in H11; destruct H11.\n        apply AxiomII_P in H12; destruct H12; clear H12; destruct H13.\n        clear H13; apply AxiomII_P in H11; destruct H11; double H13.\n        apply Property_dom in H14; apply Property_Value in H14; auto.\n        add ([x0,f[x0]] ∈ f) H13; clear H14; apply H in H13.\n        rewrite H13 in H12; auto.\n      * double H12; apply H8 in H13; apply AxiomII in H13; destruct H13, H14.\n        AssE [x1,y]; apply Theorem49 in H15; destruct H15; clear H16.\n        assert (x1 ∈ ran(f⁻¹|(W))).\n        { unfold Range; apply AxiomII; split; auto; exists y.\n          unfold Restriction; apply Theorem4'; split.\n          - unfold Inverse; apply AxiomII_P; split; try apply Theorem49; auto.\n          - apply AxiomII_P; repeat split; try apply Theorem49; auto.\n            apply Theorem19; auto. }\n        apply H11 in H16; clear H11; unfold Range in H10; apply AxiomII in H10.\n        destruct H10, H11; unfold Restriction in H11; apply Theorem4' in H11.\n        destruct H11; clear H17; unfold Inverse in H11; apply AxiomII_P in H11.\n        clear H10; destruct H11; apply Property_dom in H11; double H14.\n        apply Property_dom in H17; add (x1∈dom(f)) H11; double H11; clear H17.\n        unfold Connect in H9; apply H9 in H18; clear H9; intro.\n        unfold Rrelation, Inverse, E in H9; apply AxiomII_P in H9; destruct H9.\n        clear H9; apply AxiomII_P in H17; destruct H17.\n        destruct H18 as [H18|[H18|H18]]; try contradiction.\n        { clear H16; unfold Order_Pr in H4; destruct H11.\n          assert (x1 ∈ dom(f) /\\ x0 ∈ dom(f) /\\ Rrelation x1 r x0).\n          { repeat split; auto; unfold Rrelation, Inverse in H18.\n            apply AxiomII_P in H18; unfold Rrelation; apply H18. }\n          apply H4 in H19; clear H4 H9 H13 H15; unfold Rrelation, E in H19.\n          apply AxiomII_P in H19; destruct H19; clear H4.\n          apply Property_Value in H16; auto; add ([x1,f[x1]] ∈ f) H14.\n          apply H in H14; rewrite H14 in H17; add (f[x1] ∈ f[x0]) H17.\n          generalize (Theorem102 f[x0] f[x1]); intros; contradiction. }\n        { rewrite H18 in H17; clear H9 H15 H16; destruct H11.\n          apply Property_Value in H11; auto; add ([x1,y] ∈ f) H11.\n          unfold Function in H; apply H in H11; rewrite H11 in H17.\n          generalize (Theorem101 y); intros; contradiction. }\nQed.\n\nHint Resolve Theorem167 : set.\n\n\n(* Theorem168 : If x and y are finite so is x∪y. *)\n\nTheorem Theorem168 : forall x y,\n  Finite x /\\ Finite y -> Finite (x ∪ y).\nProof.\n  intros; destruct H.\n  apply Theorem167 in H; apply Theorem167 in H0.\n  destruct H as [r H], H0 as [s H0], H, H0; apply Theorem167.\n  exists (\\{\\ λ u v, (u∈x /\\ v∈x /\\ Rrelation u r v) \\/\n  (u∈(y~x) /\\ v∈(y~x) /\\ Rrelation u s v) \\/ (u∈x /\\ v∈(y~x)) \\}\\); split.\n  - clear H1 H2; unfold KWellOrder in H, H0; destruct H, H0.\n    unfold KWellOrder; split; intros.\n    + clear H1 H2; unfold Connect in H, H0; unfold Connect; intros.\n      destruct H1; apply Theorem4 in H1; apply Theorem4 in H2.\n      unfold Rrelation; destruct H1, H2.\n      * clear H0; assert (u ∈ x /\\ v ∈ x); auto; apply H in H0.\n        clear H; destruct H0 as [H | [H | H]]; try tauto.\n        { left; SplitEnsP. } { right; left; SplitEnsP. }\n      * clear H0; generalize (classic (v ∈ x)); intros; destruct H0.\n        { assert (u ∈ x /\\ v ∈ x); auto; apply H in H3.\n          clear H; destruct H3 as [H | [H | H]]; try tauto.\n          - left; SplitEnsP.\n          - right; left; SplitEnsP. }\n        { left; SplitEnsP; right; right; split; auto; apply Theorem4'.\n          split; auto; unfold Complement; SplitEns. }\n      * clear H0; generalize (classic (u ∈ x)); intros; destruct H0.\n        { assert (u ∈ x /\\ v ∈ x); auto; apply H in H3.\n          clear H; destruct H3 as [H | [H | H]]; try tauto.\n          - left; SplitEnsP.\n          - right; left; SplitEnsP. }\n        { right; left; SplitEnsP.\n          right; right; split; auto; unfold Setminus; apply Theorem4'.\n          split; auto; unfold Complement; SplitEns. }\n      * generalize (classic (u∈x)) (classic (v∈x)); intros; destruct H3, H4.\n        { clear H0; assert (u ∈ x /\\ v ∈ x); auto; apply H in H0.\n          clear H; destruct H0 as [H | [H | H]]; try tauto.\n          - left; SplitEnsP.\n          - right; left; SplitEnsP. }\n        { left; SplitEnsP; right; right; split; auto; apply Theorem4'.\n          split; auto; unfold Complement; SplitEns. }\n        { right; left; SplitEnsP; right; right; split; auto; apply Theorem4'.\n          split; auto; unfold Complement; SplitEns. }\n        { clear H; assert (u ∈ y /\\ v ∈ y); auto; apply H0 in H.\n          clear H0; destruct H as [H | [H | H]]; try tauto.\n          - left; SplitEnsP; right; left; repeat split; auto.\n            + apply Theorem4'; split; auto; SplitEns.\n            + apply Theorem4'; split; auto; SplitEns.\n          - right; left; SplitEnsP.\n            right; left; unfold Setminus; repeat split; auto.\n            + apply Theorem4'; split; auto; SplitEns.\n            + apply Theorem4'; split; auto; SplitEns. }\n    + generalize (classic (\\{ λ z, z ∈ y0 /\\ z ∈ x \\} = Φ)).\n      clear H H0; destruct H3; intros; destruct H3.\n      * assert (y0 ⊂ y).\n        { unfold Included; intros; double H4.\n          apply H in H5; apply Theorem4 in H5; destruct H5; auto.\n          generalize (Theorem16 z); intros; elim H6; clear H6.\n          rewrite <- H3; apply AxiomII; repeat split; Ens. }\n        add (y0 ≠ Φ) H4; apply H2 in H4; clear H0 H1 H2.\n        destruct H4 as [z H0]; exists z; unfold FirstMember in H0.\n        destruct H0; unfold FirstMember; split; auto; intros.\n        double H2; apply H1 in H4; clear H1; intro; elim H4; clear H4.\n        unfold Rrelation in H1; apply AxiomII_P in H1; destruct H1.\n        unfold Rrelation; destruct H4 as [H4|[H4|H4]]; try apply H4.\n        { destruct H4; clear H5; generalize (Theorem16 y1); intros.\n          elim H5; rewrite <- H3; apply AxiomII; repeat split; Ens. }\n        { destruct H4; clear H5; generalize (Theorem16 y1); intros.\n          elim H5; rewrite <- H3; apply AxiomII; repeat split; Ens. }\n      * assert (\\{λ z, z∈y0 /\\ z∈x\\} ⊂ x).\n        { unfold Included; intros; apply AxiomII in H4; apply H4. }\n        add (\\{λ z, z∈y0 /\\ z∈x\\} <> Φ) H4; apply H1 in H4; clear H1 H2.\n        destruct H4 as [z H1]; exists z; unfold FirstMember in H1.\n        destruct H1; apply AxiomII in H1; destruct H1, H4.\n        unfold FirstMember; split; auto; intros.\n        generalize (classic (y1∈x)); intros; destruct H7.\n        { assert (y1 ∈ \\{λ z, z∈y0 /\\ z∈x\\}).\n          { apply AxiomII; repeat split; Ens. }\n          apply H2 in H8; intro; elim H8; clear H2 H8.\n          unfold Rrelation in H9; apply AxiomII_P in H9; destruct H9.\n          unfold Rrelation; destruct H8 as [H8|[H8|H8]]; try apply H8.\n          - destruct H8; clear H9; unfold Setminus in H8; apply AxiomII in H8.\n            destruct H8, H9; unfold Complement in H10; apply AxiomII in H10.\n            destruct H10; contradiction.\n          - destruct H8; clear H8; unfold Setminus in H9; apply AxiomII in H9.\n            destruct H9, H9; unfold Complement in H10; apply AxiomII in H10.\n            destruct H10; contradiction. }\n        { intro; unfold Rrelation in H8; apply AxiomII_P in H8.\n          destruct H8, H9 as [H9|[H9|H9]], H9; try contradiction.\n          destruct H10; clear H8 H9 H11; unfold Setminus in H10.\n          apply AxiomII in H10; destruct H10, H9; unfold Complement in H10.\n          apply AxiomII in H10; destruct H10; contradiction. }\n  - unfold KWellOrder; split; intros.\n    + clear H1 H2; unfold KWellOrder in H, H0; destruct H, H0.\n      clear H1 H2; unfold Connect in H, H0; unfold Connect; intros.\n      destruct H1; apply Theorem4 in H1; apply Theorem4 in H2.\n      unfold Rrelation; destruct H1, H2.\n      * clear H0; assert (u ∈ x /\\ v ∈ x); auto; apply H in H0.\n        clear H; destruct H0 as [H | [H | H]]; try tauto.\n        { right; left; unfold Inverse; SplitEnsP; SplitEnsP. }\n        { left; SplitEnsP; SplitEnsP. }\n      * clear H0; generalize (classic (v ∈ x)); intros; destruct H0.\n        { assert (u ∈ x /\\ v ∈ x); auto; apply H in H3.\n          clear H; destruct H3 as [H | [H | H]]; try tauto.\n          - right; left; SplitEnsP; SplitEnsP.\n          - left; SplitEnsP; SplitEnsP. }\n        { right; left; SplitEnsP; SplitEnsP.\n          right; right; split; auto; apply Theorem4'.\n          split; auto; unfold Complement; SplitEns. }\n      * clear H0; generalize (classic (u ∈ x)); intros; destruct H0.\n        { assert (u ∈ x /\\ v ∈ x); auto; apply H in H3.\n          clear H; destruct H3 as [H | [H | H]]; try tauto.\n          - right; left; SplitEnsP; SplitEnsP.\n          - left; SplitEnsP; SplitEnsP. }\n        { left; SplitEnsP; SplitEnsP.\n          right; right; split; auto; unfold Setminus; apply Theorem4'.\n          split; auto; unfold Complement; SplitEns. }\n      * generalize (classic (u∈x)) (classic (v∈x)); intros; destruct H3, H4.\n        { clear H0; assert (u ∈ x /\\ v ∈ x); auto; apply H in H0.\n          clear H; destruct H0 as [H | [H | H]]; try tauto.\n          - right; left; SplitEnsP; SplitEnsP.\n          - left; SplitEnsP; SplitEnsP. }\n        { right; left; SplitEnsP; SplitEnsP.\n          right; right; split; auto; apply Theorem4'.\n          split; auto; unfold Complement; SplitEns. }\n        { left; SplitEnsP; SplitEnsP.\n          right; right; split; auto; unfold Setminus; apply Theorem4'.\n          split; auto; unfold Complement; SplitEns. }\n        { clear H; assert (u ∈ y /\\ v ∈ y); auto; apply H0 in H.\n          clear H0; destruct H as [H | [H | H]]; try tauto.\n          - right; left; SplitEnsP; SplitEnsP.\n            right; left; unfold Setminus; repeat split; auto.\n            + apply Theorem4'; split; auto; SplitEns.\n            + apply Theorem4'; split; auto; SplitEns.\n          - left; SplitEnsP; SplitEnsP; right; left; repeat split; auto.\n            + apply Theorem4'; split; auto; SplitEns.\n            + apply Theorem4'; split; auto; SplitEns. }\n    + clear H H0; unfold KWellOrder in H1, H2.\n      destruct H1, H2; clear H H1; destruct H3.\n      generalize (classic (\\{λ z, z∈y0 /\\ z∈(y~x)\\}=Φ)); intros; destruct H3.\n      * assert (y0 ⊂ x).\n        { unfold Included; intros; double H4.\n          apply H in H5; apply Theorem4 in H5; destruct H5; auto.\n          generalize (classic (z ∈ x)); intros; destruct H6; auto.\n          generalize (Theorem16 z); intros; elim H7; clear H7.\n          rewrite <- H3; apply AxiomII; repeat split; Ens.\n          unfold Setminus; apply Theorem4'; split; auto.\n          unfold Complement; apply AxiomII; split; Ens. }\n        add (y0 ≠ Φ) H4; apply H0 in H4; clear H0 H1 H2.\n        destruct H4 as [z H0]; exists z; unfold FirstMember in H0.\n        destruct H0; unfold FirstMember; split; auto; intros.\n        double H2; apply H1 in H4; clear H1; intro; elim H4; clear H4.\n        unfold Rrelation in H1; apply AxiomII_P in H1; destruct H1.\n        apply AxiomII_P in H4; destruct H4 as [H5 H4]; clear H5.\n        unfold Rrelation, Inverse; apply AxiomII_P; split; auto.\n        destruct H4 as [H4|[H4|H4]]; try apply H4.\n        { destruct H4; clear H5; generalize (Theorem16 z); intros.\n          elim H5; rewrite <- H3; apply AxiomII; repeat split; Ens. }\n        { destruct H4; clear H4; generalize (Theorem16 y1); intros.\n          elim H4; rewrite <- H3; apply AxiomII; repeat split; Ens. }\n      * assert (\\{λ z, z∈y0 /\\ z∈(y~x)\\} ⊂ y).\n        { unfold Included; intros; apply AxiomII in H4; destruct H4, H5.\n          unfold Setminus in H6; apply Theorem4' in H6; apply H6. }\n        add (\\{λ z, z∈y0 /\\ z∈(y~x)\\} <> Φ) H4; apply H2 in H4; clear H0 H2.\n        destruct H4 as [z H0]; exists z; unfold FirstMember in H0.\n        destruct H0; apply AxiomII in H0; destruct H0, H4.\n        unfold Setminus in H5; apply Theorem4' in H5; destruct H5.\n        unfold Complement in H6; apply AxiomII in H6; clear H0; destruct H6.\n        unfold FirstMember; split; auto; intros.\n        generalize (classic (y1∈x)); intros; destruct H8.\n        { intro; unfold Rrelation in H9; apply AxiomII_P in H9; destruct H9.\n          apply AxiomII_P in H10; destruct H10 as [H11 H10]; clear H11.\n          destruct H10 as [H10|[H10|H10]], H10; try contradiction.\n          destruct H11; clear H9 H10 H12; unfold Setminus in H11.\n          apply AxiomII in H11; destruct H11, H10; unfold Complement in H11.\n          apply AxiomII in H11; destruct H11; contradiction. }\n        { assert (y1 ∈ \\{λ z, z ∈ y0 /\\ z ∈ (y ~ x)\\}).\n          { apply AxiomII; repeat split; Ens; apply H in H7.\n            apply Theorem4 in H7; destruct H7; try contradiction.\n            apply Theorem4'; split; auto; apply AxiomII; split; Ens. }\n          apply H2 in H9; intro; elim H9; clear H2 H9.\n          unfold Rrelation in H10; apply AxiomII_P in H10; destruct H10.\n          apply AxiomII_P in H9; destruct H9 as [H10 H9]; clear H10.\n          unfold Rrelation, Inverse; SplitEnsP.\n          destruct H9 as [H9|[H9|H9]], H9; try contradiction; apply H10. }\nQed.\n\nHint Resolve Theorem168 : set.\n\n\n(* Some properties about finite *)\n\nLemma Property_Finite : forall (A B: Class),\n  Finite A -> B ⊂ A -> Finite B.\nProof.\n  intros.\n  apply Theorem167 in H; destruct H as [r H], H.\n  apply Theorem167; exists r; split.\n  - unfold KWellOrder, Connect in H; destruct H.\n    unfold KWellOrder, Connect; split; intros.\n    + destruct H3; apply H; auto.\n    + destruct H3; apply H2; split; auto.\n      add (B ⊂ A) H3; apply Theorem28 in H3; auto.\n  - unfold KWellOrder, Connect in H1; destruct H1.\n    unfold KWellOrder, Connect; split; intros.\n    + destruct H3; apply H1; auto.\n    + destruct H3; apply H2; split; auto.\n      add (B ⊂ A) H3; apply Theorem28 in H3; auto.\nQed.\n\n\nLemma Finite_Single : forall z, Ensemble z -> Finite ([z]).\nProof.\n  intros.\n  apply Theorem167; exists E; split.\n  - unfold KWellOrder; split; intros.\n    + unfold Connect; intros; destruct H0.\n      unfold Singleton in H0, H1.\n      apply AxiomII in H0; apply AxiomII in H1.\n      destruct H0, H1; double H.\n      apply Theorem19 in H; apply Theorem19 in H4.\n      apply H2 in H; apply H3 in H4.\n      rewrite <- H4 in H; tauto.\n    + destruct H0; apply Property_NotEmpty in H1.\n      destruct H1; exists x; unfold FirstMember.\n      split; auto; intros; unfold Included in H0.\n      apply H0 in H1; apply H0 in H2.\n      unfold Singleton in H1, H2; double H.\n      apply AxiomII in H1; apply AxiomII in H2; destruct H1, H2.\n      apply Theorem19 in H; apply Theorem19 in H3.\n      apply H4 in H; apply H5 in H3.\n      rewrite <- H3 in H; rewrite H.\n      intro; unfold Rrelation in H6; unfold E in H6.\n      apply AxiomII_P in H6; destruct H6.\n      generalize (Theorem101 y0); intros; contradiction.\n  - unfold KWellOrder; split; intros.\n    + unfold Connect; intros; destruct H0.\n      unfold Singleton in H0, H1.\n      apply AxiomII in H0; apply AxiomII in H1.\n      destruct H0, H1; double H.\n      apply Theorem19 in H; apply Theorem19 in H4.\n      apply H2 in H; apply H3 in H4.\n      rewrite <- H4 in H; tauto.\n    + destruct H0; apply Property_NotEmpty in H1; auto.\n      destruct H1; exists x; unfold FirstMember.\n      split; auto; intros; unfold Included in H0.\n      apply H0 in H1; apply H0 in H2.\n      unfold Singleton in H1, H2; double H.\n      apply AxiomII in H1; apply AxiomII in H2; destruct H1, H2.\n      apply Theorem19 in H; apply Theorem19 in H3.\n      apply H4 in H; apply H5 in H3.\n      rewrite <- H3 in H; rewrite H.\n      intro; unfold Rrelation in H6; unfold Inverse in H6.\n      apply AxiomII_P in H6; destruct H6; unfold E in H7.\n      apply AxiomII_P in H7; destruct H7.\n      generalize (Theorem101 y0); intros; contradiction.\nQed.\n\n\nEnd AxiomaticSetTheory.\n\nExport AxiomaticSetTheory.\n", "meta": {"author": "BKLSIC", "repo": "Tukey_AC", "sha": "97b6f6697f79a63251b8d49a25d71eb515e8d871", "save_path": "github-repos/coq/BKLSIC-Tukey_AC", "path": "github-repos/coq/BKLSIC-Tukey_AC/Tukey_AC-97b6f6697f79a63251b8d49a25d71eb515e8d871/Kelley_Set_Theory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6574362892633799}}
{"text": "Require Import Ensembles ssrfun Description Relations_1 IndefiniteDescription\n  Classical_Prop.\n\nRequire Import base.\n\n(* 群的第一定义 *)\nModule group_first.\n\nRecord class_of {A : Type} (X : Ensemble A) := Class {\n  base :> assoc_law X;\n  _ : exists_solution base X;\n}.\n\nStructure type {A : Type} := Pack {sort :> Ensemble A; _ : class_of sort}.\n\nNotation Group_Fst := type.\nNotation Group_Fst_Class := class_of.\n\nDefinition is_fst_group {A: Type} (G : Ensemble A) (op: A -> A -> A) :=\n  binary_operation op G /\\ associative op /\\ exists_solution op G /\\ notEmpty G.\n\nEnd group_first.\n\nExport group_first.\n\n(* 群的第二定义 *)\nModule group_second.\n\nRecord class_of {A : Type} (X : Ensemble A) := Class {\n  base :> assoc_law X;\n  zero : A;\n  inv : A -> A;\n  _ : left_id zero base; (* 左单位元 *)\n  _ : left_inverse zero inv base;  (* 左逆元 *)\n}.\n\nStructure type {A : Type} := Pack {sort :> Ensemble A; _ : class_of sort}.\n\nNotation Group_Snd := type.\nNotation Group_Snd_Class := class_of.\n\nDefinition is_snd_group {A: Type} (G : Ensemble A) (op: A -> A -> A) :=\n  binary_operation op G /\\ associative op /\\ notEmpty G /\\\n  exists (zero: A), left_id zero op /\\ exists (inv: A -> A), left_inverse zero inv op.\n\nEnd group_second.\n\nExport group_second.\n\nModule group.\n\nRecord class_of {A : Type} (X : Ensemble A) := Class {\n  base :> assoc_law X;\n  zero : A;\n  inv : A -> A;\n  _ : left_id zero base; (* 左单位元 *)\n  _ : right_id zero base;\n  _ : left_inverse zero inv base;  (* 左逆元 *)\n  _ : right_inverse zero inv base;\n}.\n\nStructure type {A : Type} := Pack {sort :> Ensemble A; _ : class_of sort}.\n\nNotation Group := type.\nNotation Group_Class := class_of.\n\nDefinition is_group {A: Type} (G : Ensemble A) (op: A -> A -> A) :=\n  binary_operation op G /\\ associative op /\\ notEmpty G /\\\n  exists (zero: A), left_id zero op /\\ right_id zero op /\\ \n  exists (inv: A -> A), left_inverse zero inv op /\\ right_inverse zero inv op.\n\n\n\nEnd group.\n\nExport group.\n\nArguments group.Pack {A}.\nArguments group.Class {A}.\n\n(* 可证 *)\nLemma groupfsttosnd {A: Type} (G : Ensemble A) (op: A -> A -> A) :\n  is_fst_group G op <-> is_snd_group G op.\nProof.\n  split.\n  - intros. destruct H, H0, H1. red in H, H, H0, H1, H2.\n    split; auto. split; auto. split; auto.\n    assert (exists zero : A, left_id zero op).\n    { destruct H2. generalize H1 H2; intros.\n      specialize (H1 x x). destruct H1, H1, H5.\n      exists x1. red; intros.\n      specialize (H3 x x2). destruct H3, H3, H6.\n      rewrite <- H3. specialize (H0 x1 x x3).\n      rewrite  H0. rewrite H5; auto. }\n    destruct H3. exists x. split; auto.\n    rename x into e. unfold left_inverse.\n    assert (forall a, {a' : A | op a' a = e}).\n    { intros. apply constructive_indefinite_description.\n      specialize (H1 a e). destruct H1; auto. }\n    exists (fun a => proj1_sig (X a)); eauto.  \n    intros. \n    pose proof (X x). destruct (X x). simpl; auto. \n  - intros. destruct H,H0, H1, H2, H2, H3. \n    rename x into e; rename x0 into inv.\n    red in H, H, H0, H2, H3. split; auto.\n    split; auto. split; auto. red. intros.\nAdmitted.\n\n(* 可证 *)\nLemma groupsndto {A: Type} (G : Ensemble A) (op: A -> A -> A) :\n  is_snd_group G op <-> is_group G op.\nProof.\n  split.\n  - admit.\n  - intros. destruct H, H0, H1, H2, H2, H3, H4, H4. \n    repeat split; auto. exists x; split; auto.\n    exists x0; auto.\nAdmitted.\n\n(* 子群 *)\nSection subgroups.\n\nVariable A : Type.\n\nDefinition grouptoclass (G : @Group A) := let: group.Pack _ imp as G' := G \n  return Group_Class G' in imp.\n\nDefinition zeroG (G : @Group A) := zero G (grouptoclass G).\n\nDefinition invG (G : @Group A) := inv G (grouptoclass G).\n\nDefinition addG (G : @Group A) := add G (grouptoclass G).\n\nStructure sub_group (G : @Group A) := sub_Group{\n  subGens :> Ensemble A;\n  _ : notEmpty subGens;\n  _ : Included subGens G;\n  _ : is_group subGens (addG G); \n}.\n\n(* 由子群作成的群 *)\nDefinition subgrouptogroup (G : @Group A) (H : sub_group G) : @Group A.\n  destruct H, i0, H0. destruct H1 as [K H1]. \n  clear H1. unfold addG, grouptoclass in H,H0.\n  destruct G, c, base0. simpl in *.\n  Check (Assoc A subGens0 add0 H H0 K).\n  Check (group.Class subGens0 (Assoc A subGens0 add0 H H0 n) zero0 inv0 l r l0 r0).\n  Check (group.Pack subGens0 (group.Class subGens0 (Assoc A subGens0 add0 H H0 n) zero0 inv0 l r l0 r0)).\n  exact (group.Pack subGens0 (group.Class subGens0 (Assoc A subGens0 add0 H H0 n) zero0 inv0 l r l0 r0)).\nDefined.\n\nEnd subgroups.\n\n\nArguments grouptoclass {A}.\nArguments zeroG {A}.\nArguments invG {A}.\nArguments addG {A}.\nArguments sub_group {A}.\n\nSection groupTheorem.\nVariable A : Type.\nVariable G : @Group A.\n\nAxiom invG_pro : forall a, In G a -> In G (invG G a).\n\nLemma group_assoc : forall (a b c : A), addG G a (addG G b c) = addG G (addG G a b) c.\nProof. \n  intros. \n  unfold addG; unfold grouptoclass.\n  destruct G, c0, base0; simpl; auto.\nQed.\nLemma group_bin : binary_operation (addG G) G.\nProof.\n  red; red. unfold addG, grouptoclass.\n  destruct G, c, base0; simpl.\n  red in b, b; auto.\nQed.\n\nLemma group_operation_pro : forall a b, invG G (addG G a (invG G b)) = addG G b (invG G a).\nAdmitted.\n\nLemma group_operation_pro1 : forall x y z, \n  (addG G (addG G x (invG G y)) (addG G y (invG G z))) = addG G x (invG G z).\nAdmitted.\n\nLemma group_operation_pro2 : forall x, (addG G x (invG G x)) = zeroG G.\nProof.\n  unfold addG, invG, zeroG, grouptoclass.\n  destruct G, c; simpl; auto.\nQed.\n\n\nEnd groupTheorem.\n\nHint Rewrite group_assoc.\n\nSection II_8_Theorem.\n\nVariable A : Type.\n\nVariable G : @Group A.\n\n(* H是G的子群 则有如下性质 (1) 任意a b属于H 则 add a b 属于H  \n                        (2) a属于H，-> inv a 属于H *)\nTheorem theorem_II_8_1to (H : sub_group G) : \n  (forall a b, In H a -> In H b -> In H (addG G a b)) /\\ \n  (forall a, In H a -> In H (invG G a)).\nProof.\n  split.\n  - destruct H, i0; simpl; auto. red in b, b. intros.\n    apply (b a0 b0) in H; auto.\n    destruct H, H. rewrite H1; auto.\n  - intros. generalize invG_pro; intros.\n    specialize (H1 A (subgrouptogroup A G H) a).\n    destruct H; simpl in *; auto.\n    destruct i0; simpl in *; auto. \n    destruct a0; simpl in *; auto.\n    destruct a1; simpl in *; auto.\n    destruct G; simpl in *; auto.\n    destruct c; simpl in *; auto.\n    destruct base0; simpl in *; auto.\nQed.\n\n(* 集合X有如下性质 *)\nTheorem theorem_II_8_1from (X : Ensemble A) : notEmpty X -> Included X G -> \n  (forall a b, In X a -> In X b -> In X (addG G a b)) /\\ (forall a, In X a -> In X (invG G a)) ->\n  is_snd_group X (addG G).\nProof.\n  intros. destruct H1. split.\n  red; red. intros. exists (addG G x y). split; auto.\n  split. red. unfold addG, grouptoclass.\n  unfold addG, grouptoclass in H1, H2; simpl.\n  destruct G, c, base0; simpl; auto.  \n  split; auto. unfold addG, grouptoclass.\n  destruct G, c; simpl; auto.\n  exists zero0; split; auto. exists inv0; auto.\nQed.\n\nLemma inference_II_8' (H : sub_group G) : In H (zeroG G) /\\ zeroG (subgrouptogroup A G H) = zeroG G.\nProof.\n  split.\n  - generalize (theorem_II_8_1to H); intros. destruct H0.\n    destruct H; simpl. destruct n; simpl.\n    simpl in H1, H0. generalize i1; intros. apply H1 in i1.\n    apply (H0 x (invG G x)) in i2; auto. \n    rewrite group_operation_pro2 in i2; auto.\n  - unfold subgrouptogroup. destruct H; simpl in *; auto.\n    destruct i0; simpl in *; auto. destruct a; simpl in *; auto.\n    destruct a0; simpl in *; auto. destruct G; simpl in *; auto.\n    destruct c; simpl in *; auto. destruct base0; simpl in *; auto.\nQed.\n\nLemma inference_II_8'' (H : sub_group G) : forall a, In H a -> invG (subgrouptogroup A G H) a = invG G a.\nProof.\n  intros. \n  unfold subgrouptogroup. destruct H; simpl in *; auto.\n  destruct i0; simpl in *; auto.\n  destruct a0; simpl in *; auto.\n  destruct a1; simpl in *; auto.\n  destruct G; simpl in *; auto.\n  destruct c; simpl in *; auto.\n  destruct base0; simpl in *; auto.\nQed.\n\n(* 子群的充要条件 可证 *)\nTheorem theorem_II_8_2to (H : sub_group G) : forall a b, In H a -> In H b -> In H (addG G a (invG G b)).\nAdmitted.\n\n(* 可证 *)\nTheorem theorem_II_8_2from (X : Ensemble A) : notEmpty X -> Included X G -> \n  (forall a b, In X a -> In X b -> In X (addG G a (invG G b))) ->\n  is_snd_group X (addG G).\nAdmitted.\n\nEnd II_8_Theorem.\n\nSection coset.\n\nInductive right_coset {A : Type} (G : @Group A) (H : sub_group G) (a : A) : Ensemble A :=\n  right_coset_intro : forall b, In H (addG G a (invG G b)) -> In (right_coset G H a) b.\n\nInductive left_coset {A : Type} (G : @Group A) (H : sub_group G) (a : A) : Ensemble A :=\n  left_coset_intro : forall b,  In H (addG G (invG G b) a ) -> In (left_coset G H a) b.\nEnd coset.\n\nSection normal_subgroups.\n\nVariable A : Type.\n\nStructure normal_subgroup (G : @Group A) := normal_SubGroup{\n  normalSubGens :> sub_group G ;\n  _ : forall a, Same_set (right_coset G normalSubGens a) (left_coset G normalSubGens a);\n}.\n\nEnd normal_subgroups.\n\nArguments normal_subgroup {A}.\nArguments normal_SubGroup {A}.\n\n\nSection quotient_groups.\n\n(* 陪集 *)\nVariable A : Type.\n\n(* G是一个群，H是G的不变子群，给一个元素repr；返回其一个陪集类型 *)\nStructure coset (G: @Group A) (H: normal_subgroup G) : Type := makeCoset{\n  repr : A ;\n}.\n\n(* 提取出代表元 *)\nDefinition coset_to_repr G H (a : coset G H) : A.\n  destruct a as [a].\n  exact a.\nDefined.\n\n(* 元间的关系 即 a与b等价 <-> a*b逆 属于H  *)\nDefinition right_coset_element_relation (G: @Group A) (H: sub_group G) (a b : A) :=\n  In H (addG G a (invG G b)).\n\n\n(* 该关系是一个等价关系 *)\nLemma right_coset_relation_is_equivalence (G: @Group A) (H: sub_group G) :\n  Equivalence (right_coset_element_relation G H).\nProof.\n  split.\n  - red. red. intros. generalize inference_II_8'; intros.\n    specialize (H0 A G H). destruct H0. unfold addG, invG, grouptoclass.\n    destruct G, c; simpl. red in r0. remember r0; clear Heqe.\n    specialize (r0 x). rewrite r0; auto.\n  - red. unfold right_coset_element_relation.\n    intros.\n    generalize theorem_II_8_1to; intros. specialize (H2 A G H).\n    destruct H2. \n    apply (H2 (addG G x (invG G y)) (addG G y (invG G z))) in H0; auto.\n    rewrite group_operation_pro1 in H0; auto.\n  - red. unfold right_coset_element_relation. intros.\n    generalize theorem_II_8_1to; intro H2. specialize (H2 A G H).\n    destruct H2. apply H2 in H0.\n    rewrite group_operation_pro in H0; auto.\nQed.\n\n(* coset 相等 *)\nDefinition coset_eq (G: @Group A) (H: normal_subgroup G) (a b : coset G H) :=\n  exists c, In (right_coset G H c) (coset_to_repr G H a) /\\\n            In (right_coset G H c) (coset_to_repr G H b).\n\n\n(* coest相等的外延公理 *)\nAxiom coset_eq_axiom : forall (G: @Group A) (H: normal_subgroup G) (a b : coset G H),\n  a = b <-> coset_eq G H a b.\n\n(* 两个陪集相等 那么他们的代表元等价 即 addG a invG b 属于 H *)\nLemma coset_pro1 (G: @Group A) (H: normal_subgroup G) (a b : coset G H) : \n  coset_eq G H a b <-> In H (addG G (coset_to_repr G H a) (invG G (coset_to_repr G H b))).\nProof.\n  split.\n  - intros. destruct H0, H0.\n    generalize right_coset_relation_is_equivalence; intros.\n    specialize (H2 G H). destruct H2. \n    red in H2, H3, H4. unfold right_coset_element_relation in H3, H4.\n    destruct a, b; simpl.\n    simpl in H0, H1. destruct H0, H1.\n    apply H4 in H0. apply (H3 b x b0) in H0; auto.\n  - destruct a, b; simpl. intros.\n    red. exists repr0. split.\n    + apply right_coset_intro; simpl. \n      rewrite group_operation_pro2. generalize (inference_II_8' A G H); intros.\n      tauto.\n    + apply right_coset_intro in H0. auto.\nQed.\n\n(* 给一个a 返回包含a的陪集 *)\nDefinition quotient_mapping (G: @Group A) (H: normal_subgroup G) (a: A) : coset G H.\n  exact (makeCoset G H a).\nDefined.\n\n\nDefinition quotient_z G H : coset G H.\n    apply (makeCoset _ _ (zeroG G)).\nDefined.\n\n\nDefinition quotient_add G H : coset G H -> coset G H -> coset G H.\n    intros a b.\n    (* this is dumb,but basically we just don't care about the coset repr *)\n    destruct a as [a].\n    destruct b as [b].\n    exact (makeCoset _ _ ((addG G) a b)).\nDefined.\n\n\nDefinition quotient_inv G H: coset G H -> coset G H.\n  intros a.\n  destruct a as [a].\n  exact (makeCoset _ _ ((invG G) a)).\nDefined.\n\n\nInductive quotient_ens G H : Ensemble (coset G H) :=\n  quotient_ens_intro : forall a, In G a -> In (quotient_ens G H) (makeCoset G H a).\n\nLemma quotient_pro G H : binary_operation (quotient_add G H) (quotient_ens G H).\nProof.\n  red; red; intros.\n  destruct H0, H1.\n  destruct G; simpl. \n  unfold addG, grouptoclass. \n  destruct c, base0. red in b, b.\n  apply (b a a0) in H0; auto.\n  destruct H0, H0.\n  exists (makeCoset (Pack sort0 (Class sort0 (Assoc A sort0 add0 b a1 n) zero0 inv0 l r l0 r0)) H x).\n  split. apply quotient_ens_intro; auto.\n  simpl. rewrite H2; auto.\nQed.\n\nDefinition quotient_assoc_law (G: @Group A) (H: normal_subgroup G) : assoc_law (quotient_ens G H).\n  apply (base.Assoc _ _ (quotient_add G H)).\n  generalize group_bin; intros. \n  specialize (H0 A G).\n  red; red. intros. destruct H1, H2.\n  red in H0, H0. apply (H0 a a0) in H1; auto.\n  destruct H1, H1.\n  exists (makeCoset G H x).\n  split; auto. apply quotient_ens_intro; auto.\n  unfold quotient_add; auto. rewrite H3; auto.\n  red. intros [x] [y] [z].\n  unfold quotient_add. autorewrite with core; auto.\n  red. destruct G, c, base0, n; simpl.\n  exists (makeCoset (Pack sort0 (Class sort0 (Assoc A sort0 add0 b a (ex_intro [eta In sort0] x i)) zero0 inv0 l r l0 r0)) H x).\n  apply quotient_ens_intro; auto.\nDefined.\n\n\n(* 可证 *)\nDefinition quotient_Group_Class (G: @Group A) (H:  normal_subgroup G) : Group_Class (quotient_ens G H).\n  apply (group.Class _ (quotient_assoc_law G H) (quotient_z G H) (quotient_inv G H)).\n  - red; intros. unfold quotient_z. destruct x; simpl.\n    unfold addG, zeroG, grouptoclass.\n    destruct G, c; simpl; auto. red in l.\n    pose proof (l repr0). rewrite H0; auto.\n  - red; intros. unfold quotient_z. destruct x; simpl.\n    unfold addG, zeroG, grouptoclass.\n    destruct G, c; simpl; auto. red in r.\n    pose proof (r repr0). rewrite H0; auto.\n  - red; intros. unfold quotient_z, quotient_inv. destruct x; simpl.\n    unfold addG, invG, zeroG, grouptoclass; simpl; auto.\n    destruct G, c; simpl; auto.\n    red in l0. pose proof (l0 repr0).\n    rewrite H0; auto.\n  - red; intros. unfold quotient_z, quotient_inv. destruct x; simpl.\n    unfold addG, invG, zeroG, grouptoclass; simpl; auto.\n    destruct G, c; simpl; auto.\n    red in r0. pose proof (r0 repr0).\n    rewrite H0; auto.\nDefined.\n\n(* 商群  可证 *)\nDefinition quotient_group (G: @Group A) (H: normal_subgroup G) : @Group (coset G H).\n    apply (group.Pack _ (quotient_Group_Class G H)).\nDefined.\n\n\nEnd quotient_groups.\n\nArguments coset {A}.\nArguments makeCoset {A}.\n\n(* 加群 *)\nModule group_add.\n\nRecord class_of {A : Type} (X : Ensemble A) := Class {\n  base :> Group_Class X;\n  _ : commutative base;\n}.\n\nStructure type {A : Type} := Pack {sort :> Ensemble A; _ : class_of sort}.\n\nNotation Group_Add := type.\nNotation Group_Add_Class := class_of.\n\nDefinition is_add_group {A: Type} (G : Ensemble A) (op: A -> A -> A) :=\n  is_group G op /\\ commutative op.\n\nEnd group_add.\n\nExport group_add.\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Wangdake25", "repo": "Coq", "sha": "9affcd8a2699e31b818890ce46b65cfdca2c52c2", "save_path": "github-repos/coq/Wangdake25-Coq", "path": "github-repos/coq/Wangdake25-Coq/Coq-9affcd8a2699e31b818890ce46b65cfdca2c52c2/group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6574058031756294}}
{"text": "(***************************************************************************)\n(*   This is part of FA_3rdCalculus, it is distributed under the terms     *)\n(*         of the GNU Lesser General Public License version 3              *)\n(*                (see file LICENSE for more details)                      *)\n(*                                                                         *)\n(*            Copyright 2020-2022: Yaoshun Fu and Wensheng Yu.             *)\n(***************************************************************************)\n\nRequire Export DCF.\n\nDefinition additivity S a b:=\n  ∀ u v w, u ∈ [a|b] -> v ∈ [a|b] -> w ∈ [a|b] -> S u v + S v w = S u w. \n\nDefinition intermed S f a b :=\n  ∀ u v, u ∈ [a|b] -> v ∈ [a|b] -> v > u -> \n  ∃ p q, p ∈ [u|v] /\\ q ∈ [u|v] /\\ f(p)·(v-u) ≦ S u v /\\ S u v ≦ f(q)·(v-u).\n\nDefinition integralsystem S f a b := additivity S a b /\\ intermed S f a b.\n\nDefinition integrable S f a b :=\n  ∀ S', integralsystem S' f a b -> \n  (∀ x y, x ∈ [a|b] -> y ∈ [a|b] -> S x y = S' x y).\n\nDefinition definiteiInt S f a b := integralsystem S f a b /\\ integrable S f a b.\n\nNotation \" S =∫ f \" := (definiteiInt S f)(at level 10).\n\nTheorem Int_med : ∀ {S f a b},\n  integralsystem S f a b -> ∀ c, c ∈ [a|b] -> diff_quo_median (S c) f a b.\nProof.\n  intros. destruct H. red; intros.\n  pose proof (H _ _ _ H0 H2 H3). rewrite <- H4; Simpl_R.\n  destruct (H1 _ _ H2 H3 (Theorem182_1 _ _ l)) as [p [q [H5 [H6 [H7]]]]].\n  exists p, q. split; auto. split; auto.\n  split; apply LeTi_R2 with (z:=v-u); Simpl_R.\nQed.\n\nTheorem Med_Int : ∀ {F f a b},\n  diff_quo_median F f a b -> integralsystem F# f a b.\nProof.\n  intros. split; red; intros.\n  - unfold input2Mi. rewrite <- (Theorem181 (F v)); Simpl_R.\n    rewrite Mi_R'. Simpl_R. apply Theorem181.\n  - apply Theorem182_1' in H2.\n    destruct (H _ _ H2 H0 H1) as [p [q [H3 [H4 [H5]]]]].\n    apply LeTi_R1 with (z:=v-u) in H5; Simpl_Rin H5.\n    apply LeTi_R1 with (z:=v-u) in H6; Simpl_Rin H6. exists p, q; auto.\nQed.\n\nTheorem Int_DefInt : ∀ {S f a b}, S =∫ f a b ->\n  ∀ c, c ∈ [a|b] -> ∀ F, diff_quo_median F f a b -> \n  ∀ u v, u ∈ [a|b] -> v ∈ [a|b] -> (S c)# u v = F# u v.\nProof.\n  intros. destruct H. pose proof (Int_med H _ H0).\n  destruct H. pose proof (Med_Int H1). rewrite <- (H4 _ H7); auto.\n  unfold input2Mi; apply Theorem188_2 with (Θ:=S c u); Simpl_R.\n  rewrite Theorem175. rewrite H; auto.\nQed.\n\nTheorem DefInt_Int : ∀ {F f a b} , diff_quo_median F f a b ->\n  (∀ F', diff_quo_median F' f a b -> \n  ∀ u v, u ∈ [a|b] -> v ∈ [a|b] -> F# u v = F'# u v) -> F# =∫ f a b.\nProof.\n  intros. split; [apply Med_Int; auto|red; intros].\n  pose proof (Int_med H1 _ H2). destruct H1.\n  rewrite (H0 _ H4 _ _ H2 H3). unfold input2Mi.\n  pattern (S' x y) at 1. rewrite <- (H1 x x y); Simpl_R.\nQed.", "meta": {"author": "coderfys", "repo": "Analysis", "sha": "1610987e019c90a08db4b788564fb0c2c91eebed", "save_path": "github-repos/coq/coderfys-Analysis", "path": "github-repos/coq/coderfys-Analysis/Analysis-1610987e019c90a08db4b788564fb0c2c91eebed/Calculus_without_limt/IntSys.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6573170809971163}}
{"text": "(******************************************************************************)\n(* Dr Daniel Kirk (c) 2021                                                    *)\n(******************************************************************************)\n(* Let R : ringType                                                           *)\n(******************************************************************************)\n(* freeLmodType R == a record consisting of an lmodType R 'sort' and          *)\n(*                   a (lmodBasisType sort)                                   *)\n(*                   M : freeLmodType M coerces to its underlying lmodType    *)\n(******************************************************************************)\n(* Let M : freeLmodType R                                                     *)\n(* basis M             == underlying lmodBasisType object of M                *)\n(* \\freeBasisCoef_(b) x == \\basisProj_b^(basis M) x                           *)\n(******************************************************************************)\n(* fdFreeLmodType R == a record consisting of an lmodType R 'sort' and        *)\n(*                     a (lmodFinBasisType sort)                              *)\n(*                     M : fdFreeLmodType M coerces to its underlying         *)\n(*                     lmodType but not to freeLmodType                       *)\n(******************************************************************************)\n(* Let M : fdFreeLmodType R                                                   *)\n(*                fdBasis M == underlying lmodFinBasisType object of M        *)\n(* fdFreeLmod_to_freeLmod M == converts to underlying lmodBasisType           *)\n(*   \\fdFreeBasisCoef_(b) x == \\finBasisProj_b^(fdBasis M) x                  *)\n(******************************************************************************)\n(* null_fdFreeLmod R == the fdFreeLmodType structure for null_lmodType:       *)\n(*                        the trivial module over R. It has the null basis.   *)\n(* unit_fdFreeLmod R == the fdFreeLmodType structure for unit_lmodType:       *)\n(*                        R as a module over itself. It has a basis with one  *)\n(*                        element (unit).                                     *)\n(* matrix_fdFreeLmod R n m == the fdFreeLmodType structure for                *)\n(*                            matrix_lmodType n m: the matrix objects defined *)\n(*                            in mathcomp matrix.v. It has a basis 'I_n*'I_m  *)\n(* vector_fdFreeLmod R n   == the fdFreeLmodType structure for                *)\n(*                            matrix_lmodType 1 n, the row matrix objects.    *)\n(*                            It has a basis 'I_n                             *)\n(*        R\\lmod^n         == alias for vector_fdFreeLmod R n                 *)\n(* poly_fdFreeLmod R n     == the fdFreeLmodType structure for                *)\n(*                            poly_lmodType n. [TODO]                         *)\n(******************************************************************************)\n(* freeLinear.to_row   == linIsomType mapping a fdFreeLmod with basis         *)\n(*                        number n to R\\lmod^n                                *)\n(* freeLinear.to_map   == function mapping {linear M -> N} to the equivalent  *)\n(*                        {linear R\\lmod^m -> R\\lmod^n} where M and N have    *)\n(*                        basis numbers m and n respectively                  *)\n(* freeLinear.from_map == inverse of freeLinear.to_map                        *)\n(******************************************************************************)\n(*        M1 \\foplus M2  == the fdFreeLmodType given by M1 \\oplus M2 and      *)\n(*                          Pair.basis M1 M2                                  *)\n(*                          Pair.basis M1 M2 == finBasisType with index-set   *)\n(*                          (fdBasis M1) + (fdBasis M2) and                   *)\n(*                          elem x := match x with                            *)\n(*                            |inl y => (B1 y, 0)                             *)\n(*                            |inr y => (0, B2 y)                             *)\n(*                          end                                               *)\n(* \\fbigoplus_(f in L) I == the fdFreeLmodType given by \\bigoplus_(f in L) I  *)\n(*                          and Seq.basis I L                                 *)\n(*                          Seq.basis I nil has                               *)\n(*                            index-set == null_finType                       *)\n(*                            elem x    == tt                                 *)\n(*                          Seq.basis I a::L has                              *)\n(*                            index-set ==                                    *)\n(*                              Pair.basis (fdBasis (I a)) (Seq.basis I L)    *)\n(*                            elem x    ==  match x with                      *)\n(*                                          |inl y => (fdBasis (I a) y, 0)    *)\n(*                                          |inr y => (0, Seq.basis I L y)    *)\n(*                                          end                               *)\n(*       \\fbigoplus_F I == equivalent to \\fbigoplus_(f : F) I                 *)\n(*         \\fbigoplus I == equivalent to \\fbigoplus_(f : F) I                 *)\n(*                         where I : F -> lmodType R                          *)\n(******************************************************************************)\n(* FreeModule_UniversalProperty == [TODO] *)\n(******************************************************************************)\n\nRequire Import Coq.Program.Tactics.\nRequire Import Coq.Logic.ProofIrrelevance.\nRequire Import Coq.Logic.FunctionalExtensionality.\nFrom mathcomp Require Import ssreflect ssrfun seq.\nFrom mathcomp Require Import eqtype fintype bigop matrix poly.\n\nSet Warnings \"-parsing\". (* Some weird bug in ssrbool throws out parsing warnings*)\n  From mathcomp Require Import ssrbool ssrnat.\nSet Warnings \"parsing\".\n\nSet Warnings \"-ambiguous-paths\". (* Some weird bug in ssralg throws out coercion warnings*)\n    From mathcomp Require Import ssralg.\nSet Warnings \"ambiguous-paths\".\n\nRequire Import Modules Linears DirectSum FiniteSupport lmodLC Basis.\nSet Implicit Arguments.\nUnset Strict Implicit.\nOpen Scope ring_scope.\n\nInclude GRing.\n\nOpen Scope lmod_scope.\n(*\n  Definitions of the Free and Finite Dimensional Free Module Types\n    *)\n\nModule freeLmod.\n  Section Def.\n    Variable (R : ringType).\n    Record mixin (M : lmodType R) := Mixin { basis : lmodBasisType M; }.\n    Record type := Pack { sort : _ ;  class_of : mixin sort; }.\n    Definition Build {M : lmodType R} (B : lmodBasisType M) := Pack (Mixin B).\n  End Def.\n\n  Module Exports.\n    Coercion sort : type >-> lmodType.\n    Coercion class_of : type >-> mixin.\n    Notation freeLmodType := type.\n    Notation basis := basis.\n    Notation freeLmodPack := Build.\n    Notation coef := (fun (R : ringType) (M : type R) b => \\basisProj_b^(basis M)).\n    Notation \"\\freeBasisCoef_( b ) x\" := (@coef _ _ b x) (at level 36) : lmod_scope.\n  End Exports.\nEnd freeLmod.\nExport freeLmod.Exports.\n\n(* Finite dimenisonal free modules are compatible with finite direct sums\n   That is they can be built-up and have corresponding proj and inj morphisms *)\nModule fdFreeLmod.\n  Section Def.\n    Variable (R : ringType).\n    Record mixin (M : lmodType R) := Mixin { fdBasis : lmodFinBasis.type M; }.\n    Record type := Pack { sort : _ ;  class_of : mixin sort; }.\n    Definition Build {M : lmodType R} (B : lmodFinBasis.type M) := Pack (Mixin B).\n\n    Definition to_arb (F : type) := freeLmod.Build (lmodFinBasis.to_lmodBasis (fdBasis (class_of F))).\n    Definition erefl (B : type) := erefl (size (enum (to_FinType (fdBasis (class_of B))))).\n    Definition eqBn (B : type) (n : nat) := size (enum (to_FinType (fdBasis (class_of B)))) = n.\n    Definition eqnB (B : type) (n : nat) := n = size (enum (to_FinType (fdBasis (class_of B)))).\n  End Def.\n\n\n  Module Exports.\n    Coercion sort : type >-> lmodType.\n    Coercion class_of : type >-> mixin.\n    Notation fdFreeLmodType := type.\n    Notation fdBasis := fdBasis.\n    Notation fdFreeLmodPack := Build.\n\n    Notation coef := (fun (R : ringType) (M : type R) b => \\basisProj_b^(fdBasis M)).\n    Notation \"\\fdFreeBasisCoef_( b ) x\" := (@coef _ _ b x) (at level 36) : lmod_scope.\n    Notation fdFreeLmod_to_freeLmod := to_arb.\n  End Exports.\nEnd fdFreeLmod.\nExport fdFreeLmod.Exports.\n\n\n\n(*\n  Free Module Types of:\n    the trivial modules (null basis)\n    the ring as a module over itself (unit basis)\n    matrix modules over a ring\n    polynomial modules over a ring\n    *)\n\nModule fdFreeLmodNull.\n  Section Def.\n    Variable (R : ringType).\n    \n    Definition nullBasis_fn := fun x : void => match x with end : (lmodZeroType R).\n\n    Lemma null_injective : injective nullBasis_fn.\n    Proof. by move=>x; destruct x. Qed.\n\n    Lemma null_nondeg : non_degenerate nullBasis_fn.\n    Proof. by move=>x; destruct x. Qed.\n\n    Definition null_set := lmodFinSet.Build null_injective null_nondeg.\n\n    Lemma null_li : lmodBasis.li null_set.\n    Proof. move=>C H.\n      rewrite lmodLC.eqFSFun/=.\n      apply functional_extensionality=>b.\n      destruct C as [coef [s [U E]]].\n      by induction s.\n    Qed.\n    \n    Lemma null_sp : lmodBasis.span null_set.\n    Proof. move=>m;\n      apply (exist _ (nullFSType R null_set) (lmodLC.null_sumsTo _)).\n    Qed.\n    Definition basis := lmodFinBasis.Build null_li null_sp.\n  End Def.\n  Module Exports.\n    Canonical null_fdFreeLmod (R : ringType) := Eval hnf in @fdFreeLmodPack R _ (fdFreeLmodNull.basis R).\n  End Exports.\nEnd fdFreeLmodNull.\nExport fdFreeLmodNull.Exports.\n\n\n\n\n\nModule freeRingModule.\n  Section Def.\n    Variable (R : ringType).\n    Definition fn := fun _ : unit_eqType => (GRing.one R) : (ringModType R).\n    Lemma fn_injective : injective fn.\n      Proof. by move=>x y; destruct x, y. Qed.\n    Lemma fn_nondegen : non_degenerate fn.\n      Proof. rewrite /fn=>x; apply GRing.oner_neq0. Qed.\n\n    Definition bset := lmodFinSet.Build fn_injective fn_nondegen.\n\n    Lemma bset_li : lmodBasis.li bset.\n    Proof. move=>/=C S.\n      rewrite lmodLC.eqFSFun/=.\n      apply functional_extensionality=>/=b.\n      destruct S as [s [U [H S]]]; move: s U H S.\n      rewrite /bset/==>s U H S.\n      case(C b == 0) as []eqn:E.\n        by move/eqP in E.\n        \n        move/negbT in E.\n        destruct s; [by move:(H _ E); rewrite in_nil|destruct s=>//].\n          rewrite big_seq1/fn/(scale _)/= mulr1 in S; move/eqP in S;\n          by destruct b, u.\n    Qed.\n\n    Lemma bset_spanning : lmodBasis.span bset.\n    Proof. move=>x.\n      refine (exist _ (unitFSType (B:= bset) tt x) _).\n      move: (lmodLC.unit_sumsTo (B:=bset) tt x).\n      by rewrite /scale/= mulr1.\n    Qed.\n\n    Definition basis : lmodFinBasisType (ringModType R) := lmodFinBasis.Build bset_li bset_spanning.\n  End Def.\n  Module Exports.\n    Canonical unit_fdFreeLmod (R : ringType) := Eval hnf in @fdFreeLmodPack R (ringModType R) (freeRingModule.basis R).\n  End Exports.\nEnd freeRingModule.\nExport freeRingModule.Exports.\n\nModule freeLmodMatrix.\n  Section Def.\n    Variable (R : ringType) (m n : nat).\n    Definition fn pp := @delta_mx R m n pp.1 pp.2.\n    Lemma fn_injective : injective fn.\n      Proof. rewrite/fn=>x y; rewrite /delta_mx -matrixP/eqrel=>H.\n        move:(H y.1 y.2); clear H; rewrite !mxE !eq_refl/==>H.\n        have: (y.1 == x.1) by \n          case(y.1 == x.1) as []eqn:E=>//; move: H;\n          rewrite !E !(rwP eqP) eq_sym oner_eq0.\n        have: (y.2 == x.2) by\n          case(y.2 == x.2) as []eqn:E=>//; move: H;\n          rewrite E andbC !(rwP eqP) eq_sym oner_eq0.\n        destruct x, y; rewrite -!(rwP eqP)=>/=H1 H2.\n        by rewrite H1 H2.\n      Qed.\n\n      Lemma fn_nondegen : non_degenerate fn.\n      Proof. rewrite /fn=>x; rewrite /delta_mx -(rwP negP)-(rwP eqP)-matrixP=>H.\n        by move:(H x.1 x.2); rewrite !mxE !eq_refl (rwP eqP) oner_eq0.\n      Qed.\n\n      Definition fn_bset := lmodFinSet.Build fn_injective fn_nondegen.\n\n      Lemma big_or (T : finType) (M : zmodType) (F : T -> M)  P1 P2 : \\sum_(i | P1 i || P2 i)F i = \\sum_(i | P1 i)F i + \\sum_(i |P2 i)F i - \\sum_(i | P1 i && P2 i)F i.\n      Proof.\n        rewrite !big_mkcond !(big_mkcond P1) !(big_mkcond P2) !(big_mkcond (fun i => P1 i && P2 i)) -!big_enum-!big_mkcond.\n        induction (enum _).\n        by rewrite !big_nil subr0 addr0.\n        rewrite !big_cons.\n        case(P1 a) as []eqn:E1.\n        case(P2 a) as []eqn:E2=>/=.\n        rewrite (addrC _ (\\sum_(j <- _| P2 j) _)) !addrA.\n        by rewrite addrKA IHl !addrA/=.\n        by rewrite IHl/= !addrA.\n        case(P2 a) as []eqn:E2=>//=.\n        by rewrite !addrA (addrC (\\sum_(j <- _| P1 j) _) _) IHl !addrA/=.\n      Qed.\n\n      Lemma seq_basis (c : 'I_m*'I_n -> R) (x : seq ('I_m*'I_n)) (U : uniq x) : \\sum_(b <- x) c b *: delta_mx b.1 b.2 =  \\sum_(i < m) \\sum_(j < n) (if(i,j) \\in x then c (i,j) else 0) *: delta_mx i j.\n      Proof.\n        rewrite pair_big.\n        symmetry; under eq_bigr do rewrite (lmod_ifthenelse_sum (fun p => c p) (fun p => delta_mx p.1 p.2) (fun p => p \\in x)); symmetry.\n        simpl fst; simpl snd.\n        rewrite -big_mkcond/=.\n        induction x.\n        rewrite big_nil.\n        under eq_bigl do rewrite in_nil.\n        by rewrite big_pred0.\n\n        simpl in U; move/andP in U.\n        rewrite big_cons (IHx (proj2 U)).\n        symmetry; under eq_bigl do rewrite in_cons;symmetry.\n        rewrite big_or -(IHx (proj2 U)) (big_pred1 a).\n        destruct a as [a1 a2]=>/=.\n        rewrite (big_mkcond (fun _ => _ && (_ \\in _)))/=\n                (big1 _ _ (fun i => if _ then _ else _));\n        [by rewrite subr0|move=>i _].\n        case((i.1, i.2) == (a1, a2)) as []eqn:E1=>//.\n        case((i.1, i.2) \\in x) as []eqn:E2.\n        by move/eqP in E1; rewrite -E1 E2/= in U; destruct U.\n        by rewrite E2.\n        move=>i; destruct a as [a1 a2]=>//.\n      Qed.\n\n      Lemma fn_li : lmodBasis.li fn_bset.\n      Proof. rewrite/fn_bset/lmodFinSet.to_set/==>c H.\n        destruct c as [c V].\n        destruct H as [h [U [H S]]].\n        simpl in H, S, c, h; rewrite fsFun.eqFSFun/=; clear V.\n        rewrite /fn(seq_basis _ U) in S.\n        move:(matrix_sum_delta (\\matrix_(i < m, j < n)(if (i, j) \\in h then c (i, j) else 0))).\n        under eq_bigr do under eq_bigr do rewrite mxE.\n        move=>A. move/eqP in S; move:S.\n        rewrite -A -matrixP/eqrel=>/=S.\n        apply functional_extensionality=>b.\n        move:(S b.1 b.2)=>/=.\n        rewrite !mxE.\n        case(c b == 0) as []eqn:E.\n        by move/eqP in E.\n        move/negbT in E.\n        by destruct b=>/=; rewrite (H _ E).\n      Qed.\n\n    Lemma fn_spanning : lmodBasis.span fn_bset.\n    Proof. move=>A.\n      move:(matrix_sum_delta A)=>W.\n      rewrite pair_big/= in W.\n\n      have HS : hasSupport (fun i => A i.1 i.2) (index_enum (prod_finType (ordinal_finType m) (ordinal_finType n))) by\n      move=>b X; apply (mem_index_enum b).\n\n      have E : finSuppE (fun i => A i.1 i.2) by\n      refine (ex_intro _ _ (conj _ HS)); rewrite (index_enum_uniq _).\n\n      refine(exist _ (fsFun.Pack E) _).\n      refine (ex_intro _ _ (ex_intro _ (index_enum_uniq _) (ex_intro _ HS _))).\n      by rewrite {2}W/=/fn eq_refl.\n    Qed.\n\n    Definition basis : lmodFinBasisType (matrix_lmodType R m n) := lmodFinBasis.Build fn_li fn_spanning.\n  End Def.\n  Module Exports.\n    Canonical Structure fdFreeLmod_matrix (R : ringType) (m n : nat) := Eval hnf in fdFreeLmodPack (basis R m n).\n  End Exports.\nEnd freeLmodMatrix.\nExport freeLmodMatrix.Exports.\n\n\nDefinition vector_lmodType R n := matrix_lmodType R 1 n.\nModule freeLmodVector.\n  Section Def.\n    Variable (R : ringType) (n : nat).\n    Notation ord0 := (Ordinal (ltn0Sn 0)).\n\n    Definition fn pp := @delta_mx R 1 n ord0 pp.\n    Lemma fn_injective : injective fn.\n      Proof. move: (@freeLmodMatrix.fn_injective R 1 n).\n        rewrite /injective/freeLmodMatrix.fn/fn=>H x y P.\n        move: (H (ord0, x) (ord0, y) P).\n        by rewrite !(rwP eqP).\n      Qed.\n\n      Lemma fn_nondegen : non_degenerate fn.\n      Proof. move: (@freeLmodMatrix.fn_nondegen R 1 n).\n        rewrite /non_degenerate/freeLmodMatrix.fn/fn=>H i.\n        by move: (H (ord0, i)).\n      Qed.\n\n      Definition fn_bset := lmodFinSet.Build fn_injective fn_nondegen.\n\n      Section Bijection.\n        Lemma n_sizen : n = size (enum 'I_n).\n        Proof. by rewrite -cardT !card_ord. Qed.\n        (*ord_to_finBasis n_sizen (finBasis_to_ord n_size1n x).*)\n\n        Lemma n_size1n : n = size (enum (prod_finType (ordinal_finType 1) (ordinal_finType n))).\n        Proof. by rewrite -cardT card_prod !card_ord mul1n. Qed.\n        Definition vect_to_mat : fn_bset -> (@freeLmodMatrix.fn_bset R 1 n) := fun x =>\n        (ord0, x).\n        Definition mat_to_vect : (@freeLmodMatrix.fn_bset R 1 n) -> fn_bset :=\n          fun x => x.2.\n        \n        Lemma vect_to_matK : cancel mat_to_vect vect_to_mat.\n        Proof. rewrite /vect_to_mat/mat_to_vect=>x.\n          destruct x as [x1 x2]=>/=.\n          destruct x1.\n          by induction m; [rewrite -(proof_irrelevance _ _ (ltn0Sn 0)) |inversion i].\n        Qed.\n\n        Lemma mat_to_vectK : cancel vect_to_mat mat_to_vect.\n        Proof. by rewrite /vect_to_mat/mat_to_vect=>x. Qed.\n      End Bijection.\n\n      Lemma vector_to_matrix : forall i, fn (mat_to_vect i) = freeLmodMatrix.fn_bset R 1 n i.\n      Proof. rewrite/fn=>i; rewrite/freeLmodMatrix.fn_bset/freeLmodMatrix.fn.\n        destruct i, s as [s S], s=>//=.\n      Qed.\n\n      Lemma fn_li : lmodBasis.li fn_bset.\n      Proof. move: (@freeLmodMatrix.fn_li R 1 n)=>W C S.\n        rewrite /lmodBasis.li in W.\n        destruct C as [coef C].\n        destruct S as [s [U [H S]]].\n        move: s U H S.\n        rewrite/==>s U H S.\n        rewrite fsFun.eqFSFun/=; clear C.\n        pose(s' := map (fun i => (Ordinal (ltn0Sn 0),i)) s).\n\n        have U' : uniq s'.\n        rewrite map_inj_in_uniq=>//.\n        move=>x y X Y E.\n        by inversion E.\n\n        have H' : hasSupport (coef \\o snd) s'.\n        move=>b X.\n        destruct b as [b' b]; simpl in X.\n        rewrite /s'.\n\n        have BB: b' == ord0 by\n        destruct b'; rewrite /eq_op/=; destruct m=>//.\n        move/eqP in BB; destruct BB.\n\n        apply (map_f (fun b=> (b', b))).\n        apply (H _ X).\n\n        have Q: fsFun.finSuppE (B:= prod_eqType (ordinal_eqType 1) _) (coef \\o snd) by\n        refine(ex_intro _ s' _)=>//.\n\n        move:(W (fsFun.Pack Q))=>T.\n        have Y: lmodLCSumsTo (B:=freeLmodMatrix.fn_bset R 1 n) {| fsFun.sort := coef \\o snd; fsFun.hasFiniteSupport := Q |} 0.\n\n        rewrite /lmodLC.li.\n        refine(ex_intro _ s' (ex_intro _ U' (ex_intro _ H' _))).\n        rewrite/=/s' big_map/=/freeLmodMatrix.fn/=.\n        by rewrite /fn in S.\n        move:(T Y).\n        rewrite fsFun.eqFSFun/=/comp/==>O.\n        apply functional_extensionality=>b.\n        by move: (equal_f O (ord0,b)).\n      Qed.\n\n    Lemma fn_spanning : lmodBasis.span fn_bset.\n    Proof. move=>/=A.\n      move: (@freeLmodMatrix.fn_spanning R 1 n A)=>C;destruct C as [C S].\n      have E: fsFun.finSuppE (C \\o vect_to_mat). clear S.\n      destruct C as [coef [c [U H]]].\n      refine(ex_intro _ (map mat_to_vect c) _);split.\n      rewrite -(map_inj_in_uniq (f:=mat_to_vect)) in U=>//.\n      move=>[x1 x2] [y1 y2] X Y Z.\n      rewrite/mat_to_vect/= in Z.\n      destruct x1, y1; destruct m,m0=>//.\n      by rewrite Z (proof_irrelevance _ i i0).\n      move=>b X.\n      rewrite/comp/vect_to_mat in X.\n      rewrite -(rwP mapP).\n      refine(ex_intro2 _ _ (ord0,b) (H _ X) _)=>//.\n\n      refine(exist _ (fsFun.Pack E) _).\n      destruct S as [s [U [H S]]].\n      refine(ex_intro _ (map mat_to_vect s) _).\n      rewrite -(map_inj_in_uniq (f:=mat_to_vect)) in U.\n      refine(ex_intro _ U _).\n      have HS:hasSupport (C \\o vect_to_mat) [seq mat_to_vect i | i <- s].\n      move=> b X.\n      rewrite/comp/vect_to_mat in X.\n      rewrite -(rwP mapP).\n      refine(ex_intro2 _ _ (ord0,b) (H _ X) _)=>//.\n      refine(ex_intro _ HS _).\n      rewrite big_map/=.\n      under eq_bigr do rewrite vect_to_matK.\n      rewrite /freeLmodMatrix.fn_bset/=/freeLmodMatrix.fn in S.\n      move/eqP in S.\n      rewrite/fn/mat_to_vect -S -(rwP eqP).\n      apply eq_bigr=>i _.\n      destruct i as [[i1 I1] i2]=>/=.\n      destruct ord0 as [o1 O1].\n      destruct i1, o1=>//.\n      move=>[x1 x2] [y1 y2] _ _ Z.\n      rewrite/mat_to_vect/= in Z.\n      destruct x1, y1.\n      destruct m,m0=>//.\n      by rewrite Z (proof_irrelevance _ i i0).\n    Qed.\n\n    Definition basis : lmodFinBasisType (vector_lmodType R n) := lmodFinBasis.Build fn_li fn_spanning.\n  End Def.\n\n  Module Exports.\n    Canonical fdFreeLmod_vector (R : ringType) (n : nat) := Eval hnf in fdFreeLmodPack (basis R n).\n  End Exports.\nEnd freeLmodVector.\nExport freeLmodVector.Exports.\n\nModule freeLinear.\n  Section Def.\n    Variable (R : ringType).\n    Section VectorConversion.\n    Variable (M : fdFreeLmodType R) (n : nat) (E : fdFreeLmod.eqnB M n).\n\n      Definition to_row_raw : M -> vector_lmodType R n  := fun x =>\n      \\row_(i < n)\n        \\fdFreeBasisCoef_(lmodFinSet.from_ord E i) x.\n\n      Definition from_row_raw : vector_lmodType R n -> M  := fun x =>\n        \\sum_(b : fdBasis M)\n          x (Ordinal (ltn0Sn 0)) (lmodFinSet.to_ord E b) *: (fdBasis M b).\n\n      Lemma from_row_lin : linear to_row_raw /\\ linear from_row_raw.\n      Proof. split; rewrite/from_row_raw/to_row_raw=>r x y.\n      rewrite -matrixP /eqrel=>i j.\n      by rewrite !mxE linearP.\n      rewrite scaler_sumr -big_split.\n      apply eq_bigr=>i _.\n      by rewrite mxE mxE scalerDl scalerA. Qed.\n\n      Lemma from_rowK : cancel to_row_raw from_row_raw /\\ cancel from_row_raw to_row_raw.\n      Proof. split=>x; rewrite/from_row_raw/to_row_raw.\n        move:(lmodBasis.hasSpanEq (fdBasis M) x)=>H.\n        destruct H as [s [U [H S]]]; move/eqP in S.\n        rewrite (eqLCSumsTo H (@lmodFinBasis.hasSupport_enum _ _ (fdBasis M) x) U (enum_uniq _)) in S.\n        rewrite -big_enum-S.\n        apply eq_bigr=>i _.\n        rewrite mxE.\n        rewrite linear_sum ord_to_finBasisK scaler_suml.\n        by rewrite (lmodBasis.sum_trivialises (B:=fdBasis M) (enum_uniq _) i (lmodFinBasis.hasSupport_enum (x:=x))).\n\n        rewrite -matrixP=>i j.\n        rewrite mxE linear_sum.\n        under eq_bigr do rewrite linearZ (lmodBasis.orthonormP (B:=fdBasis M) (ord_to_finBasis E j)) eq_sym.\n        have Q: forall k (_ : true),\n          (x (Ordinal (ltn0Sn 0)) (finBasis_to_ord E k) * (if k == ord_to_finBasis E j then 1 else 0))\n            = if k == ord_to_finBasis E j then\n                x (Ordinal (ltn0Sn 0)) (finBasis_to_ord E k)\n              else\n                0\n        by move=>k _; case(k == ord_to_finBasis E j); [rewrite mulr1|rewrite mulr0].\n        rewrite (eq_bigr _ Q) -big_mkcond big_pred1_eq finBasis_to_ordK.\n        destruct i as [i I]; destruct i=>//.\n        by rewrite (proof_irrelevance _ (ltn0Sn 0) I).\n      Qed.\n      Definition to_row := linIsomBuildPack from_row_lin from_rowK.\n    End VectorConversion.\n\n    Section MatrixConversion.\n      Variable (M N : fdFreeLmodType R)\n      (m : nat) (Em : fdFreeLmod.eqnB M m)\n      (n : nat) (En : fdFreeLmod.eqnB N n).\n\n      Definition to_map (f : {linear M -> N}) : {linear (vector_lmodType R m) -> (vector_lmodType R n)}\n      := (to_row En) \\oLin f \\oLin inv(to_row Em).\n\n      Definition from_map (f : {linear (vector_lmodType R m) -> (vector_lmodType R n)}) : {linear M -> N}\n        := inv(to_row En) \\oLin f \\oLin (to_row Em).\n\n      Lemma from_mapK : cancel to_map from_map.\n      Proof. rewrite/from_map/to_map=>/=f.\n        rewrite !linear_eq.\n        apply functional_extensionality=>x.\n        by rewrite -!linCompChain !(isomlK _).\n      Qed.\n      \n      Lemma to_mapK : cancel from_map to_map.\n      Proof. rewrite/from_map/to_map=>f.\n        rewrite !linear_eq.\n        apply functional_extensionality=>x.\n        by rewrite -!linCompChain !(isomKl _).\n      Qed.\n    End MatrixConversion.\n  End Def.\nEnd freeLinear.\n\n\n(*\n\n  Direct Sums of Free Modules\n  \n    *)\n\nModule dsFdFreeLmod.\n  Module Pair.\n    Section Def.\n      Variable (R : ringType).\n      Variable (M1 M2 : lmodType R) (B1 : lmodFinBasisType M1) (B2 : lmodFinBasisType M2).\n\n      Section FiniteSuppSums.\n        Import FiniteSupport.\n        Lemma LCsumsTo_sums (C1 : lmodLCType B1) (C2 : lmodLCType B2) m1 m2 : lmodLC.sumsTo C1 m1 -> lmodLC.sumsTo C2 m2\n        -> lmodLC.sumsTo (lmodLC.sum C1 C2) (m1,m2).\n        Proof. move=>H1 H2.\n          destruct H1 as [s1 [U1 [H1 S1]]].\n          destruct H2 as [s2 [U2 [H2 S2]]].\n          refine(ex_intro _ (fsFun.sum_seq s1 s2) _).\n          refine(ex_intro _ (fsFun.sum_uniq U1 U2) _).\n          refine(ex_intro _ (fsFun.hasFunSupp_sum H1 H2) _).\n          rewrite big_cat/= !big_map/lmodSet.elem_sum.\n          under (eq_bigr (r:=s1)) do rewrite /(scale _)/=/scale_pair/= scaler0.\n          under (eq_bigr (r:=s2)) do rewrite /(scale _)/=/scale_pair/= scaler0.\n          by rewrite dsLmod.pair_eq_seq S1 S2.\n        Qed.\n\n\n        Lemma LCsumsTo_sumsI (C : lmodLCType (lmodSet.sum B1 B2)) m1 m2 : lmodLC.sumsTo C (m1,m2)\n            -> (lmodLC.sumsTo (fsFun.foldFSl C) m1 /\\ lmodLC.sumsTo (fsFun.foldFSr C) m2).\n        Proof. move=>H; split;destruct H as [h [U [E H]]].\n          refine(ex_intro _ (fsFun.foldL h) _).\n          refine(ex_intro _ (fsFun.foldL_uniq U) _).\n          refine(ex_intro _ (fsFun.foldL_fs E) _).\n          clear E U. move: m1 m2 H.\n          induction h=>//m1 m2.\n          rewrite !big_nil {1}/eq_op/= -(rwP andP)=>H;\n          apply (proj1 H).\n          destruct a; [rewrite fsFun.foldL_consl|rewrite fsFun.foldL_consr];\n            rewrite !big_cons /(scale _)/=/scale_pair/= scaler0 addrC eq_sym -subr_eq /(add _)/=/add_pair/= subr0 eq_sym=>H;\n            move: (IHh _ _ H)=> G//.\n            by rewrite eq_sym subr_eq eq_sym addrC in G.\n\n          refine(ex_intro _ (fsFun.foldR h) _).\n          refine(ex_intro _ (fsFun.foldR_uniq U) _).\n          refine(ex_intro _ (fsFun.foldR_fs E) _).\n          clear E U; move: m1 m2 H.\n          induction h=>//m1 m2.\n          rewrite !big_nil {1}/eq_op/= -(rwP andP)=>H;\n          apply (proj2 H).\n          destruct a; [rewrite fsFun.foldR_consl|rewrite fsFun.foldR_consr];\n            rewrite !big_cons;\n            rewrite /(scale _)/=/scale_pair/= scaler0 addrC eq_sym -subr_eq /(add _)/=/add_pair/= subr0 eq_sym=>H;\n            move: (IHh _ _ H) => G//.\n            by rewrite eq_sym subr_eq eq_sym addrC in G.\n        Qed.\n      End FiniteSuppSums.\n\n      Lemma pair_li : lmodBasis.li (lmodSet.sum B1 B2).\n      Proof. move=>c H.\n        apply (LCsumsTo_sumsI) in H. destruct H as [H1 H2].\n        move: (lmodBasis.hasLI (B:=B1) H1).\n        move: (lmodBasis.hasLI (B:=B2) H2).\n        rewrite !lmodLC.eqFSFun/==>Z2 Z1.\n        apply functional_extensionality=>b.\n        destruct b;[apply (equal_f Z1 s)|apply (equal_f Z2 s)].\n      Qed.\n      Lemma pair_sp : lmodBasis.span (lmodSet.sum B1 B2).\n      Proof. move=> m.\n        move: (lmodBasis.hasSpanEq B1 m.1)=>E1.\n        move: (lmodBasis.hasSpanEq B2 m.2)=>E2.\n        move:(LCsumsTo_sums E1 E2)=>E.\n        apply(exist _ (lmodLC.sum (lmodBasis.hasSpanLC B1 m.1) (lmodBasis.hasSpanLC B2 m.2)) E).\n      Qed.\n\n      Definition basis : lmodFinBasisType (pair_lmodType M1 M2) := lmodFinBasis.Build pair_li pair_sp.\n    End Def.\n\n    Definition fdFreeLmod (R : ringType) (m1 m2 : fdFreeLmodType R) := fdFreeLmodPack (basis (fdBasis m1) (fdBasis m2)).\n    Section Results.\n      Variable (R : ringType).\n      Variable (M1 M2 : fdFreeLmodType R).\n      Definition incl1 : {linear M1 -> fdFreeLmod M1 M2} := dsLmod.Pair.incl1 M1 M2.\n      Definition incl2 : {linear M2 -> fdFreeLmod M1 M2} := dsLmod.Pair.incl2 M1 M2.\n\n      Definition proj1 : {linear fdFreeLmod M1 M2 -> M1} := dsLmod.Pair.proj1 M1 M2.\n      Definition proj2 : {linear fdFreeLmod M1 M2 -> M2} := dsLmod.Pair.proj2 M1 M2.\n    End Results.\n\n    Module Exports.\n      Canonical fdFreeLmod.\n    End Exports.\n  End Pair.\n  Export Pair.Exports.\n\n  Module Seq.\n    Section Def.\n      Variable (R : ringType) (T : eqType) (I : T -> (fdFreeLmodType R)).\n      Fixpoint basis (L : seq T) := match L with\n      |nil    => fdBasis (null_fdFreeLmod R) : lmodFinBasisType (dsLmod.Seq.DS I nil)\n      |a::L'  => (Pair.basis (fdBasis (I a)) (basis L')) : lmodFinBasisType (dsLmod.Seq.DS I (a::L'))\n      end.\n    End Def.\n\n    Definition fdFreeLmod (R : ringType) (T : eqType) (I : T -> (fdFreeLmodType R)) (L : seq T) := fdFreeLmodPack (basis I L).\n    \n    Module Exports.\n      Canonical fdFreeLmod.\n    End Exports.\n  End Seq.\n\n  Section Def.\n    Variable (R : ringType) (F : finType) (I : F -> (fdFreeLmodType R)).\n    Definition type := Seq.fdFreeLmod I (enum F).\n  End Def.\n  Export Seq.Exports.\nEnd dsFdFreeLmod.\n\nReserved Notation \"\\fbigoplus_ i F\"\n  (at level 36, F at level 36, i at level 0,\n    right associativity,\n          format \"'[' \\fbigoplus_ i '/ ' F ']'\").\n\nReserved Notation \"\\fbigoplus F\"\n  (at level 36, F at level 36,\n    right associativity,\n          format \"'[' \\fbigoplus F ']'\").\n\nReserved Notation \"\\fbigoplus_ ( i <- r ) F\"\n  (at level 36, F at level 36, i, r at level 50,\n          format \"'[' \\fbigoplus_ ( i <- r ) '/ ' F ']'\").\n\nReserved Notation \"\\fbigoplus_ ( i : t ) F\"\n  (at level 36, F at level 36, i at level 50,\n          format \"'[' \\fbigoplus_ ( i : t ) '/ ' F ']'\").\n\nReserved Notation \"\\fbigoplus_ ( i 'in' A ) F\"\n  (at level 36, F at level 36, i, A at level 50,\n          format \"'[' \\fbigoplus_ ( i 'in' A ) '/ ' F ']'\").\n\n\nInfix \"\\lmod^\"  := (vector_lmodType) (at level 30) : lmod_scope.\nInfix \"\\foplus\" := (dsFdFreeLmod.Pair.fdFreeLmod) (at level 36) : lmod_scope.\nNotation \"\\fbigoplus_ i F\" := (dsFdFreeLmod.type (fun i => F)) : lmod_scope.\nNotation \"\\fbigoplus F\" := (dsFdFreeLmod.type F) : lmod_scope.\nNotation \"\\fbigoplus_ ( i : t ) F\" := (dsFdFreeLmod.type (fun i : t => F)) : lmod_scope.\nNotation \"\\fbigoplus_ ( i 'in' A ) F\" := (dsFdFreeLmod.Seq.fdFreeLmod (filter F (fun i => i \\in A))) : lmod_scope.\n\n\nExport dsFdFreeLmod.Pair.Exports.\nExport dsFdFreeLmod.Seq.Exports.\n(*\nTheorem FreeModule_UniversalProperty (R : ringType) (M : fdFreeLmodType R)\n    : forall (N : lmodType R) (f : (fdBasis M) -> N), \n      exists (g : {linear M -> N}),\n        f = g \\o (fdBasis M).\n  Proof.\n  Admitted.\n  *)\n\nClose Scope ring_scope.\nClose Scope lmod_scope.", "meta": {"author": "Modularius", "repo": "MathcompFreeModules", "sha": "5731747c5bcbafe914687d44e74f112632f07ec7", "save_path": "github-repos/coq/Modularius-MathcompFreeModules", "path": "github-repos/coq/Modularius-MathcompFreeModules/MathcompFreeModules-5731747c5bcbafe914687d44e74f112632f07ec7/theories/Modules/FreeModules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6573170762147266}}
{"text": "Require Import PropLang.\nRequire Import List.\n\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nSection SequentCalculus.\n\nContext {atom : Type}.\n\nReserved Notation \"Γ1 ---> Γ2\" (no associativity, at level 62).\n\nInductive G : list (prop atom) -> list (prop atom) -> Prop :=\n| leave_everything {Γ1 Γ2 Γ3 Γ4 X} :\n  [X] ---> [X] ->\n  Γ1 ++ [X] ++ Γ2 ---> Γ3 ++ [X] ++ Γ4\n| switch_arrow {Γ1 Γ2 Γ3 Γ4 X Y} :\n  Γ1 ++[Y] ++ Γ2 ++ [X] ++ Γ3 ---> Γ4 ->\n  Γ1 ++ [X] ++ Γ2 ++ [Y] ++ Γ3 ---> Γ4\n| arrow_switch {Γ1 Γ2 Γ3 Γ4 X Y} :\n  Γ1 ---> Γ2 ++ [Y] ++ Γ3 ++ [X] ++ Γ4 ->\n  Γ1 ---> Γ2 ++ [X] ++ Γ3 ++ [Y] ++ Γ4\n| axioma {X} : [X] ---> [X]\n| arrow_impl {Γ1 Γ2 X Y} :\n  [X] ++ Γ1 ---> [Y] ++ Γ2 ->\n  Γ1 ---> [X ⊃ Y] ++ Γ2\n| arrow_conj {Γ1 Γ2 X Y} :\n  Γ1 ---> [X] ++ Γ2 ->\n  Γ1 ---> [Y] ++ Γ2 ->\n  Γ1 ---> [X ∧ Y] ++ Γ2\n| arrow_disj {Γ1 Γ2 X Y} :\n  Γ1 ---> [X] ++ [Y] ++ Γ2 ->\n  Γ1 ---> [X ∨ Y] ++ Γ2\n| arrow_neg {Γ1 Γ2 X} :\n  [X] ++ Γ1 ---> Γ2 ->\n  Γ1 ---> [¬ X] ++ Γ2\n| impl_arrow {Γ1 Γ2 X Y} :\n  Γ1 ---> [X] ++ Γ2 ->\n  [Y] ++ Γ1 ---> Γ2 ->\n  [X ⊃ Y] ++ Γ1 ---> Γ2\n| conj_arrow {Γ1 Γ2 X Y} :\n  [X] ++ [Y] ++ Γ1 ---> Γ2 ->\n  [X ∧ Y] ++ Γ1 ---> Γ2\n| disj_arrow {Γ1 Γ2 X Y} :\n  [X] ++ Γ1 ---> Γ2 ->\n  [Y] ++ Γ1 ---> Γ2 ->\n  [X ∨ Y] ++ Γ1 ---> Γ2\n| neg_arrow {Γ1 Γ2 X} :\n  Γ1 ---> [X] ++ Γ2 ->\n  [¬ X] ++ Γ1 ---> Γ2\nwhere \"Γ1 ---> Γ2\" := (G Γ1 Γ2).\n\nTheorem addNilInSeq_L (Γ1: list (prop atom)) (Γ2 : list (prop atom)) :\n  nil ++ Γ1 ---> Γ2 = Γ1 ---> Γ2.\nProof.\n  rewrite app_nil_l.\n  reflexivity.\nQed.\n\nTheorem addNilInSeq_R (Γ1 : list (prop atom)) (Γ2 : list (prop atom)) :\n  Γ1 ---> nil ++ Γ2 = Γ1 ---> Γ2.\nProof.\n  rewrite app_nil_l.\n  reflexivity.\nQed.\n\nExample example1 {A B C} :\n  [A] ++ [B] ++ [¬C] ---> [¬C] ++ [¬A] ++ [A ∧ B].\nProof.\n  apply @arrow_neg with (X := C).\n  rewrite <- addNilInSeq_L.\n  apply @switch_arrow with (X := C) (Y := ¬C) (Γ1 := []) (Γ2 := [A]++[B]) (Γ3 := []).\n  apply @neg_arrow with (X := C).\n  rewrite <- addNilInSeq_R.\n  apply @leave_everything with (X := C).\n  apply @axioma.\nQed.\n\nExample example2 {A B C} :\n  [A] ++ [B] ++ [¬C] ---> [¬C] ++ [¬A] ++ [A ∧ B].\nProof.\n  rewrite <- addNilInSeq_R.\n  apply @arrow_switch with (X := ¬C) (Y := A ∧ B).\n  apply @arrow_conj with (X := A) (Y := B).\n  + rewrite <- addNilInSeq_R.\n    rewrite <- addNilInSeq_L.\n    apply @leave_everything with (X := A).\n    apply @axioma.\n  + rewrite <- addNilInSeq_R.\n    rewrite <- addNilInSeq_L.\n    apply @leave_everything with (X := B).\n    apply @axioma.\nQed.\n\n(*\\subset- implikálás*)\nExample example3 {A B}:\n  [¬(A ⊃ B)] ---> [¬A ∨ ¬B].\nProof.\n  apply @neg_arrow with(X:= A ⊃ B).\n  apply @arrow_impl with (X := A) (Y:= B).\n  rewrite <- addNilInSeq_R.\n  apply @arrow_switch with (X := B) (Y:= ¬A ∨ ¬B).\n  apply @arrow_disj with (X:= ¬A) (Y := ¬B).\n  rewrite <- addNilInSeq_R.\n  apply @arrow_switch with (X:= ¬A) (Y:= ¬B).\n  apply @arrow_neg with (X:= B).\n  rewrite <- addNilInSeq_L.\n  apply @leave_everything with (X := B).\n  apply @axioma.\nQed.\n\nExample example4 {A B C} :\n  [(A ∨ B) ⊃ C] ---> [(A ⊃ C) ∧ (B ⊃ C)].\n\nExample example5 {A B} :\n  [¬(A ⊃ B)] ---> [¬A ∨ ¬B].\n \n(*\\lnot!!*)\nExample nyomozos {F K A} :\n  [F ⊃ K] ++ [K ⊃ A] ++ [¬A] ---> [¬F].\n\n  ", "meta": {"author": "SandorBalazsHU", "repo": "elte-ik-logika-coq", "sha": "de90c589372ab2db675f7b744bf77eaab0506691", "save_path": "github-repos/coq/SandorBalazsHU-elte-ik-logika-coq", "path": "github-repos/coq/SandorBalazsHU-elte-ik-logika-coq/elte-ik-logika-coq-de90c589372ab2db675f7b744bf77eaab0506691/g_kalkulus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7520125626441471, "lm_q1q2_score": 0.6573170615652429}}
{"text": "(** * Tactics: More Basic Tactics *)\n\nRequire Export Poly.\n\n(** This chapter introduces several more proof strategies and\n    tactics that allow us to prove more interesting properties of\n    functional programs.  We will see:\n\n    - how to use auxiliary lemmas in both \"forward-style\" and\n      \"backward-style\" proofs;\n    - how to reason about data constructors (in particular, how to use\n      the fact that they are injective and disjoint);\n    - how to create a strong induction hypothesis (and when such\n      strengthening is required); and\n    - more details on how to reason by case analysis.\n *)\n\n(* ###################################################### *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    exactly the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n\n(** At this point, we could finish with \"[rewrite -> eq2.\n    reflexivity.]\" as we have done several times before.  We can\n    achieve the same effect in a single step by using the [apply]\n    tactic instead: *)\n\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** You may find it instructive to experiment with this proof\n    and see if there is a way to complete it using just [rewrite]\n    instead of [apply]. *)\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] that binds some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex)  *)\n(** Complete the following proof without using [simpl]. *)\n\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 3 = true ->\n     oddb 4 = true.\nProof.\n  intros H1 H2.\n  apply H1. apply H2.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal exactly -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  simpl.\n  (* Here we cannot use [apply] directly *)\nAbort.\n\n(** In this case we can use the [symmetry] tactic, which switches the\n    left and right sides of an equality in the goal. *)\n\nTheorem silly3 : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  symmetry.\n  simpl. (* Actually, this [simpl] is unnecessary, since\n            [apply] will perform simplification first. *)\n  apply H.  Qed.\n\n(** **** Exercise: 3 stars (apply_exercise1)  *)\n(** (_Hint_: You can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [SearchAbout] is\n    your friend.) *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  intros l l' H.\n  symmetry.\n  rewrite H.\n  apply rev_involutive.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (apply_rewrite)  *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  What are the situations where both can usefully be\n    applied?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might like to pull it out\n    as a lemma recording, once and for all, the fact that equality is\n    transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to prove the above\n    example.  However, to do this we need a slight refinement of the\n    [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n\n(** If we simply tell Coq [apply trans_eq] at this point, it can\n    tell (by matching the goal against the conclusion of the lemma)\n    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and\n    [o] with [[e,f]].  However, the matching process doesn't determine\n    an instantiation for [m]: we have to supply one explicitly by\n    adding [with (m:=[c,d])] to the invocation of [apply]. *)\n\n  apply trans_eq with (m:=[c;d]). apply eq1. apply eq2.   Qed.\n\n(** Actually, we usually don't have to include the name [m] in\n    the [with] clause; Coq is often smart enough to figure out which\n    instantiation we're giving. We could instead write: [apply\n    trans_eq with [c;d]]. *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o).\nProof.\n  intros n m o p H1 H2.\n  rewrite H2. apply H1.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * The [inversion] tactic *)\n\n(** Recall the definition of natural numbers:\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n    It is obvious from this definition that every number has one of\n    two forms: either it is the constructor [O] or it is built by\n    applying the constructor [S] to another number.  But there is more\n    here than meets the eye: implicit in the definition (and in our\n    informal understanding of how datatype declarations work in other\n    programming languages) are two more facts:\n\n    - The constructor [S] is _injective_.  That is, if [S n = S m], it\n      must be the case that [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n]. *)\n\n(** Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor\n    is injective and [nil] is different from every non-empty list.\n    For booleans, [true] and [false] are different.  (Since neither\n    [true] nor [false] take any arguments, their injectivity is not an\n    issue.)  And so on. *)\n\n(** Coq provides a tactic called [inversion] that allows us to\n    exploit these principles in proofs. To see how to use it, let's\n    show explicitly that the [S] constructor is injective: *)\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n\n(** By writing [inversion H] at this point, we ask Coq to\n    generate all equations that it can infer from [H] as additional\n    hypotheses, replacing variables in the goal as it goes. In the\n    present example, this amounts to adding a new hypothesis [H1 : n =\n    m] and replacing [n] by [m] in the goal. *)\n\n  inversion H. reflexivity.  Qed.\n\n(** Here's a more interesting example that shows how multiple\n    equations can be derived at once. *)\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity. Qed.\n\n(** It is possible to name the equations that [inversion]\n    generates with an [as ...] clause: *)\n\nTheorem inversion_ex2 : forall (n m : nat),\n  [n] = [m] ->\n  n = m.\nProof.\n  intros n o H. inversion H as [Hno]. reflexivity.  Qed.\n\n(** **** Exercise: 1 star (inversion_ex3)  *)\nExample inversion_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** While the injectivity of constructors allows us to reason\n    that [forall (n m : nat), S n = S m -> n = m], the converse of\n    this implication is an instance of a more general fact about\n    constructors and functions, which we will find useful below: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.\n\n(** When used on a hypothesis involving an equality between\n    _different_ constructors (e.g., [S n = O]), [inversion] solves the\n    goal immediately. To see why this makes sense, consider the\n    following proof: *)\n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  intros n.\n\n(** We can proceed by case analysis on [n]. The first case is\n    trivial. *)\n\n  destruct n as [| n'].\n  - (* n = 0 *)\n    intros H. reflexivity.\n\n(** However, the second one doesn't look so simple: assuming\n    [beq_nat 0 (S n') = true], we must show [S n' = 0], but the latter\n    clearly contradictory!  The way forward lies in the assumption.\n    After simplifying the goal state, we see that [beq_nat 0 (S n') =\n    true] has become [false = true]: *)\n\n  - (* n = S n' *)\n    simpl.\n\n(** If we use [inversion] on this hypothesis, Coq notices that\n    the subgoal we are working on is impossible, and therefore removes\n    it from further consideration. *)\n\n    intros H. inversion H. Qed.\n\n(** This is an instance of a general logical principle known as\n    the _principle of explosion_, which asserts that a contradiction\n    entails anything, even false things.  For instance: *)\n\nTheorem inversion_ex4 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem inversion_ex5 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. inversion contra. Qed.\n\n(** If you find the principle of explosion confusing, remember\n    that these proofs are not actually showing that the conclusion of\n    the statement holds.  Rather, they are arguing that the situation\n    described by the premise can never arise, so the implication is\n    vacuous.  We'll explore the principle of explosion of more detail\n    in the next chapter. *)\n\n(** **** Exercise: 1 star (inversion_ex6)  *)\nExample inversion_ex6 : forall (X : Type)\n                          (x y z : X) (l j : list X),\n  x :: y :: l = [] ->\n  y :: l = z :: j ->\n  x = z.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** To summarize this discussion, suppose [H] is a hypothesis in the\n    context or a previously proven lemma of the form\n      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] has the following effect:\n\n    - If [c] and [d] are the same constructor, then, by the\n      injectivity of this constructor, we know that [a1 = b1], [a2 =\n      b2], etc.; [inversion H] adds these facts to the context, and\n      tries to use them to rewrite the goal.\n\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory, and the current goal doesn't have to be\n      considered. In this case, [inversion H] marks the current goal\n      as completed and pops it off the goal stack. *)\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, [apply L in H] matches some conditional statement\n    [L] (of the form [L1 -> L2], say) against a hypothesis [H] in the\n    context.  However, unlike ordinary [apply] (which rewrites a goal\n    matching [L2] into a subgoal [L1]), [apply L in H] matches [H]\n    against [L1] and, if successful, replaces it with [L2].\n\n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\": from [L1 -> L2] and a hypothesis matching [L1], it\n    produces a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\": it says that if we know [L1->L2] and we are\n    trying to prove [L2], it suffices to prove [L1].\n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\nTheorem silly3' : forall (n : nat),\n  (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->\n  true = beq_nat n 5  ->\n  true = beq_nat (S (S n)) 7.\nProof.\n  intros n eq H.\n  symmetry in H. apply eq in H. symmetry in H.\n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, idiomatic use of Coq tends to favor backward reasoning,\n    but in some situations the forward style can be easier to think\n    about.  *)\n\n(** **** Exercise: 3 stars, recommended (plus_n_n_injective)  *)\n(** Practice using \"in\" variants in this exercise.  (Hint: use\n    [plus_n_Sm].) *)\n\nTheorem plus_n_n_injective : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Varying the Induction Hypothesis *)\n\n(** Sometimes it is important to control the exact form of the\n    induction hypothesis when carrying out inductive proofs in Coq.\n    In particular, we need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose\n    we want to show that the [double] function is injective -- i.e.,\n    that it always maps different arguments to different results:\n    Theorem double_injective: forall n m, \n      double n = double m -> n = m.\n    The way we _start_ this proof is a bit delicate: if we begin with\n      intros n. induction n.\n    all is well.  But if we begin it with\n      intros n m. induction n.\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  - (* n = O *) simpl. intros eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n  - (* n = S n' *) intros eq. destruct m as [| m'].\n    + (* m = O *) inversion eq.\n    + (* m = S m' *)  apply f_equal.\n\n(** At this point, the induction hypothesis, [IHn'], does not give us\n    [n' = m'] -- there is an extra [S] in the way -- so the goal is\n    not provable. *)\n\n      Abort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context --\n    intuitively, we have told Coq, \"Let's consider some particular [n]\n    and [m]...\" and we now have to prove that, if [double n = double\n    m] for _these particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove, for\n    _all_ [n], that the proposition\n\n      - [P n] = \"if [double n = double m], then [n = m]\"\n\n    holds, by showing\n\n      - [P O]\n\n         (i.e., \"if [double O = double m] then [O = m]\") and\n\n      - [P n -> P (S n)]\n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: it says that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help at all with proving\n    [R]!  (If we tried to prove [R] from [Q], we would start with\n    something like \"Suppose [double (S n) = 10]...\" but then we'd be\n    stuck: knowing that [double (S n)] is [10] tells us nothing about\n    whether [double n] is [10], so [Q] is useless.) *)\n\n(** 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    then trying to prove a relation involving _every_ [n] but just a\n    _single_ [m]. *)\n\n(** The good proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  - (* n = O *) simpl. intros m eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n\n  - (* n = S n' *) simpl.\n\n(** Notice that both the goal and the induction hypothesis are\n    different this time: the goal asks us to prove something more\n    general (i.e., to prove the statement for _every_ [m]), but the IH\n    is correspondingly more flexible, allowing us to choose any [m] we\n    like when we apply the IH. *)\n\n    intros m eq.\n\n(** Now we've chosen a particular [m] and introduced the assumption\n    that [double n = double m].  Since we are doing a case analysis on\n    [n], we also need a case analysis on [m] to keep the two \"in sync.\" *)\n\n    destruct m as [| m'].\n    + (* m = O *) simpl.\n\n(** The 0 case is trivial: *)\n\n      inversion eq.\n\n    + (* m = S m' *)\n      apply f_equal.\n\n(** At this point, since we are in the second branch of the [destruct\n    m], the [m'] mentioned in the context is the predecessor of the\n    [m] we started out talking about.  Since we are also in the [S]\n    branch of the induction, this is perfect: if we instantiate the\n    generic [m] in the IH with the current [m'] (this instantiation is\n    performed automatically by the [apply] in the next step), then\n    [IHn'] gives us exactly what we need to finish the proof. *)\n\n      apply IHn'. inversion eq. reflexivity. Qed.\n\n(** What you should take away from all this is that we need to be\n    careful about using induction to try to prove something too\n    specific: If we're proving a property of [n] and [m] by induction\n    on [n], we may need to leave [m] generic. *)\n\n(** The following exercise requires the same pattern. *)\n\n(** **** Exercise: 2 stars (beq_nat_true)  *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (beq_nat_true_informal)  *)\n(** Give a careful informal proof of [beq_nat_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** The strategy of doing fewer [intros] before an [induction] to\n    obtain a more general IH doesn't always work by itself; sometimes\n    a little _rearrangement_ of quantified variables is needed.\n    Suppose, for example, that we wanted to prove [double_injective]\n    by induction on [m] instead of [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  - (* m = O *) simpl. intros eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *)  apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem here 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 twist 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 quantified\n    variables and then _re-generalize_ one or more of them,\n    selectively taking variables out of the context and putting them\n    back at the beginning of the goal.  The [generalize dependent]\n    tactic does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m.\n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros n eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *) apply f_equal.\n      apply IHm'. inversion eq. reflexivity. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n    _Theorem_: For any nats [n] and [m], if [double n = double m], then\n      [n = m].\n\n    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n      any [n], if [double n = double m] then [n = m].\n\n      - First, suppose [m = 0], and suppose [n] is a number such\n        that [double n = double m].  We must show that [n = 0].\n\n        Since [m = 0], by the definition of [double] we have [double n =\n        0].  There are two cases to consider for [n].  If [n = 0] we are\n        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']\n        for some [n'], we derive a contradiction: by the definition of\n        [double], we can calculate [double n = S (S (double n'))], but\n        this contradicts the assumption that [double n = 0].\n\n      - Second, suppose [m = S m'] and that [n] is again a number such\n        that [double n = double m].  We must show that [n = S m'], with\n        the induction hypothesis that for every number [s], if [double s =\n        double m'] then [s = m'].\n\n        By the fact that [m = S m'] and the definition of [double], we\n        have [double n = S (S (double m'))].  There are two cases to\n        consider for [n].\n\n        If [n = 0], then by definition [double n = 0], a contradiction.\n\n        Thus, we may assume that [n = S n'] for some [n'], and again by\n        the definition of [double] we have [S (S (double n')) =\n        S (S (double m'))], which implies by inversion that [double n' =\n        double m'].  Instantiating the induction hypothesis with [n'] thus\n        allows us to conclude that [n' = m'], and it follows immediately\n        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just\n        what we wanted to show. [] *)\n\n(** Before we close this section and move on to some exercises, let's\n    digress briefly and use [beq_nat_true] to prove a similar property\n    about identifiers that we'll need in later chapters: *) \n\nTheorem beq_id_true : forall x y,\n  beq_id x y = true -> x = y.\nProof.\n  intros [m] [n]. simpl. intros H.\n  assert (H' : m = n). { apply beq_nat_true. apply H. }\n  rewrite H'. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, recommended (gen_dep_practice)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     nth_error l n = None.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (app_length_cons)  *)\n(** Prove this by induction on [l1], without using [app_length]\n    from [Lists]. *)\n\nTheorem app_length_cons : forall (X : Type) (l1 l2 : list X)\n                                  (x : X) (n : nat),\n     length (l1 ++ (x :: l2)) = n ->\n     S (length (l1 ++ l2)) = n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (app_length_twice)  *)\n(** Prove this by induction on [l], without using [app_length] from [Lists]. *)\n\nTheorem app_length_twice : forall (X:Type) (n:nat) (l:list X),\n     length l = n ->\n     length (l ++ l) = n + n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 3 stars, optional (double_induction)  *)\n(** Prove the following principle of induction over two naturals. *)\n\nTheorem double_induction: forall (P : nat -> nat -> Prop),\n  P 0 0 ->\n  (forall m, P m 0 -> P (S m) 0) ->\n  (forall n, P 0 n -> P 0 (S n)) ->\n  (forall m n, P m n -> P (S m) (S n)) ->\n  forall m n, P m n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Unfolding Definitions *)\n\n(** It sometimes happens that we need to manually unfold a Definition\n    so that we can manipulate its right-hand side.  For example, if we\n    define *)\n\nDefinition square n := n * n.\n\n(** and try to prove a simple fact about [square]... *)\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\n  simpl.\n\n(** ... we get stuck: [simpl] doesn't simplify anything at this point,\n    and since we haven't proved any other facts about [square], there\n    is nothing we can [apply] or [rewrite] with.\n\n    To make progress, we can manually [unfold] the definition of\n    [square]: *)\n\n  unfold square.\n\n(** Now we have plenty to work with: both sides of the equality are\n    expressions involving multiplication, and we have lots of facts\n    about multiplication at our disposal.  In particular, we know that\n    it is commutative and associative, and from these facts it is not\n    hard to finish the proof. *)\n  \n  rewrite mult_assoc.\n  assert (H : n * m * n = n * n * m).\n  { rewrite mult_comm. apply mult_assoc. }\n  rewrite H. rewrite mult_assoc. reflexivity.\nQed.\n\n(** At this point, a slightly deeper discussion of unfolding and\n    simplification 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 it 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 finish the proof is to explicitly\n    tell Coq to unfold [bar]. *)\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n\n(** Now it is apparent that we are stuck on the [match] expressions on\n    both sides of the [=], and we can use [destruct] to finish the\n    proof without thinking too hard. *)\n\n  destruct m.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ###################################################### *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where [destruct] is used to\n    perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (beq_nat n 3).\n    - (* beq_nat n 3 = true *) reflexivity.\n    - (* beq_nat n 3 = false *) destruct (beq_nat n 5).\n      + (* beq_nat n 5 = true *) reflexivity.\n      + (* beq_nat n 5 = false *) reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (beq_nat n 3) then ... else ...].  But either\n    [n] is equal to [3] or it isn't, so we can use [destruct (beq_nat\n    n 3)] to let us reason about the two cases.\n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c]. *)\n\n(** **** Exercise: 3 stars, optional (combine_split)  *)\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** However, [destruct]ing compound expressions requires a bit of\n    care, as such [destruct]s can sometimes erase information we need\n    to complete a proof. *)\n(** For example, suppose we define a function [sillyfun1] like\n    this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** Now suppose that we want to convince Coq of the (rather\n    obvious) fact that [sillyfun1 n] yields [true] only when [n] is\n    odd.  By analogy with the proofs we did with [sillyfun] above, it\n    is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAbort.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution 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 [beq_nat n 3 = true] in this\n    branch of the case analysis, it must be that [n = 3], from which\n    it follows that [n] is odd.\n\n    What we would really like is to substitute away all existing\n    occurences of [beq_nat n 3], but at the same time add an equation\n    to the context that records which case we are in.  The [eqn:]\n    qualifier allows us to introduce such an equation, giving it a\n    name that we choose. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got\n     stuck above, except that the context contains an extra\n     equality assumption, which is exactly what we need to\n     make progress. *)\n    - (* e3 = true *) apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    - (* e3 = false *)\n     (* When we come to the second equality test in the body\n        of the function we are reasoning about, we can use\n        [eqn:] again in the same way, allow us to finish the\n        proof. *)\n      destruct (beq_nat n 5) eqn:Heqe5.\n        + (* e5 = true *)\n          apply beq_nat_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + (* e5 = false *) inversion eq.  Qed.\n\n(** **** Exercise: 2 stars (destruct_eqn_practice)  *)\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################## *)\n(** * Review *)\n\n(** We've now seen many of Coq's most fundamental tactics.  We'll\n    introduce a few more in the coming chapters, and later on we'll\n    see some more powerful _automation_ tactics that make Coq help us\n    with low-level details.  But basically we've got what we need to\n    get work done.\n\n    Here are the ones we've seen:\n\n      - [intros]: move hypotheses/variables from goal to context\n\n      - [reflexivity]: finish the proof (when the goal looks like [e =\n        e])\n\n      - [apply]: prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: apply a hypothesis, lemma, or constructor to\n        a hypothesis in the context (forward reasoning)\n\n      - [apply... with...]: explicitly specify values for variables\n        that cannot be determined by pattern matching\n\n      - [simpl]: simplify computations in the goal\n\n      - [simpl in H]: ... or a hypothesis\n\n      - [rewrite]: use an equality hypothesis (or lemma) to rewrite\n        the goal\n\n      - [rewrite ... in H]: ... or a hypothesis\n\n      - [symmetry]: changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]: changes a hypothesis of the form [t=u] into\n        [u=t]\n\n      - [unfold]: replace a defined constant by its right-hand side in\n        the goal\n\n      - [unfold... in H]: ... or a hypothesis\n\n      - [destruct... as...]: case analysis on values of inductively\n        defined types\n\n      - [destruct... eqn:...]: specify the name of an equation to be\n        added to the context, recording the result of the case\n        analysis\n\n      - [induction... as...]: induction on values of inductively\n        defined types\n\n      - [inversion]: reason by injectivity and distinctness of\n        constructors\n\n      - [assert (e) as H]: introduce a \"local lemma\" [e] and call it\n        [H]\n\n      - [generalize dependent x]: move the variable [x] (and anything\n        else that depends on it) from the context back to an explicit\n        hypothesis in the goal formula\n*)\n\n(* ###################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (beq_nat_sym)  *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Proof:\n   (* FILL IN HERE *)\n[]\n *)\n\n(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine)  *)\n(** We proved, in an exercise above, that for all lists of pairs,\n    [combine] is the inverse of [split].  How would you formalize the\n    statement that [split] is the inverse of [combine]?  When is this\n    property true?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?)  *)\n\nDefinition split_combine_statement : Prop :=\n(* FILL IN HERE *) admit.\n\nTheorem split_combine : split_combine_statement.\nProof.\n(* FILL IN HERE *) Admitted.\n\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise)  *)\n(** This one is a bit challenging.  Pay attention to the form of your\n    induction hypothesis. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge)  *)\n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n      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    Finally, prove a theorem [existsb_existsb'] stating that\n    [existsb'] and [existsb] have the same behavior.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** $Date: 2016-01-30 17:02:58 -0500 (Sat, 30 Jan 2016) $ *)\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/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.8740772302445241, "lm_q1q2_score": 0.6573170578650827}}
{"text": "Require Import Coq.ZArith.Zpower Coq.ZArith.ZArith.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.ZUtil.\nRequire Crypto.BaseSystem.\nRequire Import Coq.Lists.List.\n\nLocal Open Scope Z_scope.\n\nSection Pow2Base.\n  Context (limb_widths : list Z).\n  Local Notation \"w[ i ]\" := (nth_default 0 limb_widths i).\n\n  Fixpoint base_from_limb_widths limb_widths :=\n    match limb_widths with\n    | nil => nil\n    | w :: lw => 1 :: map (Z.mul (two_p w)) (base_from_limb_widths lw)\n    end.\n\n  Local Notation base := (base_from_limb_widths limb_widths).\n\n\n  Definition bounded us := forall i, 0 <= nth_default 0 us i < 2 ^ w[i].\n\n  Definition upper_bound := 2 ^ (sum_firstn limb_widths (length limb_widths)).\n\n  Function decode_bitwise' us i acc :=\n    match i with\n    | O => acc\n    | S i' => decode_bitwise' us i' (Z.lor (nth_default 0 us i') (Z.shiftl acc w[i']))\n    end.\n\n  Definition decode_bitwise us := decode_bitwise' us (length us) 0.\n\n  (* i is current index, counts down *)\n  Fixpoint encode' z i :=\n    match i with\n    | O => nil\n    | S i' => let lw := sum_firstn limb_widths in\n       encode' z i' ++ (Z.shiftr (Z.land z (Z.ones (lw i))) (lw i')) :: nil\n    end.\n\n  Definition encodeZ x:= encode' x (length limb_widths).\n\n  (** ** Carrying *)\n  Section carrying.\n    (** Here we implement addition and multiplication with simple\n        carrying. *)\n    Notation log_cap i := (nth_default 0 limb_widths i).\n\n    Definition add_to_nth n (x:Z) xs :=\n      update_nth n (fun y => x + y) xs.\n    Definition carry_single i := fun di =>\n      (Z.pow2_mod di (log_cap i),\n       Z.shiftr di (log_cap i)).\n\n    (* [fi] is fed [length us] and [S i] and produces the index of\n         the digit to which value should be added;\n       [fc] modifies the carried value before adding it to that digit *)\n    Definition carry_gen fc fi i := fun us =>\n      let i := fi i in\n      let di := nth_default 0 us      i in\n      let '(di', ci) := carry_single i di in\n      let us' := set_nth i di' us in\n      add_to_nth (fi (S i)) (fc ci) us'.\n\n    (* carry_simple does not modify the carried value, and always adds it\n       to the digit with index [S i] *)\n    Definition carry_simple := carry_gen (fun ci => ci) (fun i => i).\n\n    Definition carry_simple_sequence is us := fold_right carry_simple us is.\n\n    Fixpoint make_chain i :=\n      match i with\n      | O => nil\n      | S i' => i' :: make_chain i'\n      end.\n\n    Definition full_carry_chain := make_chain (length limb_widths).\n\n    Definition carry_simple_full := carry_simple_sequence full_carry_chain.\n\n    Definition carry_simple_add us vs := carry_simple_full (BaseSystem.add us vs).\n\n    Definition carry_simple_sub us vs := carry_simple_full (BaseSystem.sub us vs).\n\n    Definition carry_simple_mul out_base us vs := carry_simple_full (BaseSystem.mul out_base us vs).\n  End carrying.\n\nEnd Pow2Base.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_crypto_vm_native_no_op/src/ModularArithmetic/Pow2Base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6573103987190193}}
{"text": "Section ml.\nTheorem Exor: forall (A B:Set -> Prop), \n(exists x:Set, ((A x) \\/ (B x))) -> \n(exists x:Set, A x) \\/ (exists x:Set, B x).\nProof.\nintros F G h0.\nelim h0; intros n h1.\nelim h1.\nintro fn; left; exists n; assumption.\nintro gn; right; exists n; assumption.\nQed.\nEnd ml.\n\nCheck Exor.", "meta": {"author": "ya0201", "repo": "mycoq-learning", "sha": "cc25eeeb8ef82917af329d69c4ea079935155005", "save_path": "github-repos/coq/ya0201-mycoq-learning", "path": "github-repos/coq/ya0201-mycoq-learning/mycoq-learning-cc25eeeb8ef82917af329d69c4ea079935155005/acintui/Exor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6573103973989133}}
{"text": "\n(* An operation that returns a (uniformly distributed) random element from a list *)\n\nSet Implicit Arguments.\n\nRequire Import FCF.\n\nSection RndListElem.\n\n  Variable A : Set.\n  Hypothesis eqd : EqDec A.\n\n  Local Open Scope list_scope.\n\n  Definition rndListElem(ls : list A) : Comp (option A) :=\n    match (length ls) with\n      | O => ret None\n      | S _ =>\n        i <-$ [0 .. (length ls));\n          ret (nth_option ls i)\n    end.\n\n  Theorem rndListElem_wf :\n    forall (ls : list A),\n      well_formed_comp (rndListElem ls).\n       \n    intuition.\n    unfold rndListElem.\n    case_eq (length ls); intuition; wftac.\n  Qed.\n\nEnd RndListElem.\n\nLocal Open Scope list_scope.\n\nLemma rndListElem_support: \n      forall (A : Set)(eqd : EqDec A)(ls : list A) a,\n        In a ls <-> \n        In (Some a) (getSupport (rndListElem eqd ls)).\n\n      intuition.\n      unfold rndListElem.\n      case_eq (length ls); intuition.\n      exfalso.\n      destruct ls; simpl in *; intuition.\n      \n      eapply getSupport_In_Seq.\n\n      eapply in_getSupport_RndNat.\n\n      Fixpoint firstIndexOf(A : Set)(eqd : eq_dec A)(ls : list A)(a : A)(def : nat) :=\n        match ls with\n            | nil => def\n            | a' :: ls' =>\n              if (eqd a a') then O else (S (firstIndexOf eqd ls' a def))\n        end.\n\n      Theorem firstIndexOf_in_lt : \n        forall (A : Set)(eqd : eq_dec A)(ls : list A)(a : A)(def : nat),\n          In a ls ->\n          firstIndexOf eqd ls a def < length ls.\n\n        induction ls; intuition; simpl in *;\n        intuition.\n        \n        subst.\n        destruct (eqd a0 a0); subst.\n        omega.\n        intuition.\n\n        destruct (eqd a0 a); subst.\n        omega.\n\n        eapply lt_n_S.\n        eauto.\n\n      Qed.\n      \n      Theorem nth_firstIndexOf : \n        forall (A : Set)(eqd : eq_dec A)(ls : list A)(a : A)(def : nat),\n          In a ls ->\n          nth_option ls (firstIndexOf eqd ls a def) = Some a.\n\n        induction ls; intuition; simpl in *.\n        intuition.\n\n        intuition.\n        subst.\n        destruct (eqd a0 a0); subst; intuition.\n        \n        destruct (eqd a0 a); subst; intuition.\n\n      Qed.\n\n      rewrite <- H0.\n      eapply firstIndexOf_in_lt; eauto.\n      simpl.\n      left.\n\n      eapply nth_firstIndexOf; trivial.\n      \n      unfold rndListElem in *.\n      repeat simp_in_support.\n      discriminate.\n      \n      Theorem nth_option_In : \n        forall (A : Set)(ls : list A)(a : A) i,\n          nth_option ls i = Some a ->\n          In a ls.\n\n        induction ls; intuition; simpl in *.\n        discriminate.\n\n        destruct i.\n        inversion H; clear H; subst.\n        intuition.\n        right.\n        eapply IHls.\n        eauto.\n\n      Qed.\n\n      eapply nth_option_In; eauto.\n\n      Grab Existential Variables.\n      apply O.\n      unfold eq_dec.\n      eapply (EqDec_dec eqd).\n    Qed.\n\n Theorem rndListElem_uniform : \n   forall (A : Set)(eqd : EqDec A)(ls : list A)(a1 a2 : option A),\n     NoDup ls ->\n     In a1 (getSupport (rndListElem _ ls)) ->\n     In a2 (getSupport (rndListElem _ ls)) ->\n     evalDist (rndListElem _ ls) a1 ==\n     evalDist (rndListElem _ ls) a2.\n   \n   intuition.\n   \n   destruct a1.\n   destruct a2.\n   \n   rewrite <- rndListElem_support in *.\n\n   unfold rndListElem.\n   case_eq (length ls); intuition.\n   destruct ls; simpl in *. intuition. omega.\n   \n   eapply comp_spec_impl_eq.\n   \n   eapply comp_spec_seq.\n   apply (Some a).\n   apply (Some a).\n   eapply eq_impl_comp_spec.\n   eapply well_formed_RndNat.\n   omega.\n   eapply well_formed_RndNat.\n   omega.\n   eapply RndNat_uniform.\n   Focus 3.\n   intros.\n   simpl in H5.\n\n   eapply comp_spec_ret.\n   assert (a1 = (firstIndexOf (EqDec_dec _) ls a 0) <->\n     b = (firstIndexOf (EqDec_dec _) ls a0 0)).\n   eapply H5.\n   clear H5.\n   intuition; subst.\n   \n   rewrite H5.\n   eapply nth_firstIndexOf; trivial.\n\n   Theorem nth_firstIndexOf_if : \n     forall (A : Set)(eqd : eq_dec A)(ls : list A) n a,\n       nth_option ls n = Some a ->\n       NoDup ls ->\n       firstIndexOf eqd ls a 0 = n.\n\n     induction ls; intuition; simpl in *.\n     discriminate.\n     inversion H0; clear H0; subst.\n     destruct n.\n     inversion H; clear H; subst.\n     destruct (eqd a0 a0); subst; intuition.\n\n     destruct (eqd a0 a); subst; intuition.\n     exfalso.\n     eapply H3.\n     \n     eapply nth_option_In.\n     eauto.\n\n   Qed.\n\n   symmetry.\n   eapply nth_firstIndexOf_if; intuition.\n\n   rewrite H7.\n   eapply nth_firstIndexOf; trivial.\n   symmetry.\n   eapply nth_firstIndexOf_if; intuition.\n   \n   rewrite <- H2.\n   apply firstIndexOf_in_lt; trivial.\n\n   rewrite <- H2.\n   apply firstIndexOf_in_lt; trivial.\n\n   apply rndListElem_support in H0.\n\n   Theorem nth_option_some : \n     forall (A : Set)(ls : list A) n,\n       n < length ls ->\n       exists a, nth_option ls n = Some a.\n     \n     induction ls; intuition; simpl in *.\n     omega.\n     \n     destruct n.\n     econstructor; eauto.\n     \n     destruct (IHls n).\n     omega.\n     \n     econstructor; eauto.\n     \n   Qed.\n   \n   Theorem rndListElem_support_None : \n     forall (A : Set) eqd (ls : list A),\n       In None (getSupport (rndListElem eqd ls)) <->\n       ls = nil.\n\n     intuition.\n     unfold rndListElem in *.\n     case_eq (length ls); intuition.\n     destruct ls; simpl in *; trivial; discriminate.\n\n     rewrite H0 in H.\n     repeat simp_in_support.\n     apply RndNat_support_lt in H1.\n     \n     edestruct (nth_option_some ls); eauto.\n     rewrite H0.\n     eauto.\n     congruence.\n\n     subst.\n     simpl.\n     intuition.\n\n   Qed.\n\n   Show.\n   \n   apply rndListElem_support_None in H1.\n   subst.\n   simpl in *.\n   intuition.\n\n   \n   destruct a2.\n   apply rndListElem_support in H1.\n   apply rndListElem_support_None in H0.\n   subst.\n   simpl in *.\n   intuition.\n\n   intuition.\n\nQed.\n\n      Theorem nth_firstIndexOf_None : \n        forall (A : Set)(eqd : eq_dec A)(ls : list A),\n          NoDup ls ->\n          forall (a a' : A) i,\n          In a ls ->\n          i <> firstIndexOf eqd ls a O ->\n          nth_option ls i = Some a' ->\n          a <> a'.\n\n        induction 1; intuition; simpl in *.\n        intuition; subst.\n        destruct (eqd a' a'); subst; intuition.\n       \n        destruct i; intuition.\n\n        Lemma not_in_nth_option : \n          forall (A : Set)(ls : list A)(a : A)(i : nat),\n            (~In a ls) ->\n            nth_option ls i = Some a -> \n            False.\n\n          induction ls; intuition; simpl in *.\n          discriminate.\n\n          destruct i.\n          inversion H0; clear H0; subst.\n          intuition.\n          \n          eapply IHls; eauto.\n\n        Qed.\n\n        eapply not_in_nth_option; eauto.\n\n        destruct i; intuition.\n        inversion H3; clear H3; subst.\n        destruct (eqd a' a'); subst; intuition.\n\n        destruct (eqd a' x); subst; intuition.\n        eapply IHNoDup; eauto.\n      Qed.\n\n        Lemma nth_option_not_None : \n          forall (A : Set)(ls : list A)(i : nat),\n            i < length ls ->\n            nth_option ls i = None ->\n            False.\n\n          induction ls; intuition; simpl in *.\n          omega.\n\n          destruct i.\n          discriminate.\n          assert (i < length ls).\n          omega.\n          eauto.\n\n        Qed.\n\n\n    Theorem rndListElem_uniform_gen : \n      forall (A B : Set)(eqda : EqDec A)(eqdb : EqDec B)(ls1 : list A)(ls2 : list B)(a1 :  A)(a2 : B),\n        NoDup ls1 ->\n        NoDup ls2 ->\n        length ls1 = length ls2 ->\n        In a1 ls1 ->\n        In a2 ls2 ->\n        comp_spec \n          (fun x y => x = Some a1 <-> y = Some a2)\n          (rndListElem _ ls1) (rndListElem _ ls2).\n\n      intuition.\n\n      unfold rndListElem.\n      case_eq (length ls1); intuition.\n      rewrite <- H1.\n      rewrite H4.\n\n      eapply comp_spec_ret; intuition.\n      discriminate.\n      discriminate.\n      \n      rewrite <- H1.\n      rewrite H4.\n\n      eapply comp_spec_seq; try eapply None.\n      eapply eq_impl_comp_spec.\n      eapply well_formed_RndNat; omega.\n      eapply well_formed_RndNat; omega.\n      eapply (@RndNat_uniform  (firstIndexOf (EqDec_dec _) ls1 a1 O) (firstIndexOf (EqDec_dec _) ls2 a2 O)).\n \n      rewrite <- H4.\n      apply firstIndexOf_in_lt; trivial.\n      rewrite <- H4.\n      rewrite H1.\n      apply firstIndexOf_in_lt; trivial.\n\n      intuition.\n      eapply comp_spec_ret.\n      intuition.\n      \n      destruct (eq_nat_dec a (firstIndexOf (EqDec_dec _) ls1 a1 O)).\n      subst.\n      assert (b = firstIndexOf (EqDec_dec _) ls2 a2 0); intuition.\n      subst.\n      repeat rewrite nth_firstIndexOf; intuition.\n\n      assert (b <> firstIndexOf (EqDec_dec _) ls2 a2 0).\n      intuition.\n\n      exfalso.\n      eapply nth_firstIndexOf_None.\n      eapply H.\n      eapply H2.\n      eapply n0.\n      eauto.\n      intuition.\n\n      destruct (eq_nat_dec a (firstIndexOf (EqDec_dec _) ls1 a1 O)).\n      subst.\n      assert (b = firstIndexOf (EqDec_dec _) ls2 a2 0); intuition.\n      subst.\n      repeat rewrite nth_firstIndexOf; intuition.\n\n      assert (b <> firstIndexOf (EqDec_dec _) ls2 a2 0).\n      intuition.\n\n      exfalso.\n      eapply nth_firstIndexOf_None.\n      eapply H0.\n      eapply H3.\n      eapply H10.\n      eauto.\n      intuition.\n    Qed.\n\n     Theorem rndListElem_support_exists : \n      forall (A : Set)(eqd : EqDec A)(ls : list A),\n        exists x,\n          In x (getSupport (rndListElem eqd ls)).\n\n      destruct ls; intuition.\n      econstructor.\n      left.\n      eauto.\n\n      unfold rndListElem.\n      unfold length.\n      econstructor.\n      eapply getSupport_In_Seq.\n\n      eapply (@in_getSupport_RndNat O).\n      omega.\n      simpl.\n      intuition.\n    Qed.\n\n    (*\n\n    Theorem rndListElem_uniform_remove_eq : \n      forall (A : Set)(eqd : EqDec A)(ls : list A)(a1 a2 : A),\n        NoDup ls ->\n        evalDist (rndListElem _ (removeFirst (EqDec_dec _) ls a1)) (Some a1) == 0.\n\n      intuition.\n      eapply getSupport_not_In_evalDist.\n      intuition.\n      rewrite <- rndListElem_support in H0.\n      eapply removeFirst_NoDup_not_in; eauto.\n    Qed.\n\n    Notation \"$ c1 \" := (rndListElem _ c1%comp)\n                          (right associativity, at level 89, c1 at next level) : comp_scope.\n\n Theorem rndListElem_support_exists : \n      forall (A : Set)(eqd : EqDec A)(ls : list A),\n        exists x,\n          In x (getSupport (rndListElem eqd ls)).\n\n      destruct ls; intuition.\n      econstructor.\n      left.\n      eauto.\n\n      unfold rndListElem.\n      unfold length.\n      econstructor.\n      eapply getSupport_In_Seq.\n\n      eapply (@in_getSupport_RndNat O).\n      omega.\n      simpl.\n      intuition.\n    Qed.\n\n*)", "meta": {"author": "FreeAndFair", "repo": "RLA", "sha": "4295e4bb700ebbfe69affeb35dda7ed42273c3a1", "save_path": "github-repos/coq/FreeAndFair-RLA", "path": "github-repos/coq/FreeAndFair-RLA/RLA-4295e4bb700ebbfe69affeb35dda7ed42273c3a1/src/fcf/RndListElem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6573066463377505}}
{"text": "Definition HYP (P Q : Prop) : Prop := (P->Q) /\\ P.\n\nDefinition THM := forall P Q : Prop, HYP P Q -> Q.\n\nTheorem thm_proof : THM.\nShow Proof.\nintros p q.\nShow Proof.\nintro conj.\nShow Proof.\ndestruct conj as [imp pp].\nShow Proof.\napply imp.\nShow Proof.\napply pp.\nQed.\n\nDefinition hypfun (P Q : Prop) (hyp : HYP P Q) : Q :=\nmatch hyp with\n| conj imp pp => imp pp\nend.\n\nDefinition thmfun : THM := hypfun.\n\nDefinition identity_nat : nat -> nat.\nintro n.\napply n.\nQed.\n\nDefinition zero_nat : nat -> nat.\nintro n.\napply O.\nQed.\n\nDefinition successor_nat : nat -> nat.\nintro n.\napply S.\napply n.\nQed.\n\nPrint identity_nat.\nPrint zero_nat.\nPrint successor_nat.\n", "meta": {"author": "xavierdpt", "repo": "adventures", "sha": "038a17cf71d8f9690ad168b2592b12e61d2e6c32", "save_path": "github-repos/coq/xavierdpt-adventures", "path": "github-repos/coq/xavierdpt-adventures/adventures-038a17cf71d8f9690ad168b2592b12e61d2e6c32/trove/SFV1CHI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.657306645992997}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint drop (drop_arg0 : natural) (drop_arg1 : lst) : lst\n           := match drop_arg0, drop_arg1 with\n              | x, Nil => Nil\n              | Zero, x => x\n              | Succ x, Cons y z => drop x z\n              end.\n\nLemma lem: forall n1 n2 l, drop (Succ n1) (drop n2 l) = drop n1 (drop (Succ n2) l).\nProof.\nintros. generalize dependent n1. generalize dependent n2. induction l.\n- intros. assert (forall n x l, drop (Succ n) (Cons x l) = drop n l). \n  + intros. reflexivity.\n  + destruct n2.\n    * rewrite H. rewrite H. rewrite <- IHl. reflexivity.\n    * simpl. destruct l. reflexivity. reflexivity.\n- intros. assert (forall n, drop n Nil = Nil).\n  + intros. destruct n. reflexivity. reflexivity.\n  + rewrite H. rewrite H. rewrite H. reflexivity.\nQed.\n\nTheorem theorem0 : forall (u : natural) (v : natural) (w : natural) (x : natural) (y : natural) (z : lst),\n  eq (drop (Succ u) (drop v (drop (Succ w) (Cons x (Cons y z))))) (drop (Succ u) (drop v (drop w (Cons x z)))).\nProof.\nintros. \nrewrite lem. \nrewrite lem. \nlfind. \nAdmitted.\n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal57_theorem0_37_lem/goal57.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6573066414225538}}
{"text": "\nRequire Export Iron.Language.SystemF2Effect.Type.\nRequire Export Iron.Language.SystemF2Effect.Value.\nRequire Export Iron.Language.SystemF2Effect.Store.Bind.\n\n\n(********************************************************************)\n(* Small Step Evaluation (pure rules)\n   These are pure transitions that don't depend on the store. *)\nInductive StepP : exp  -> exp -> Prop :=\n\n (* Value application. *)\n | SpAppSubst\n   :  forall t11 x12 v2\n   ,  StepP (XApp (VLam t11 x12) v2)\n            (substVX 0 v2 x12)\n\n (* Type application. *)\n | SpAPPSubst\n   :  forall k11 x12 t2      \n   ,  StepP (XAPP (VLAM k11 x12) t2)\n            (substTX 0 t2 x12)\n\n (* Take the successor of a natural. *)\n | SpSucc\n   :  forall n\n   ,  StepP (XOp1 OSucc (VConst (CNat n)))\n            (XVal (VConst (CNat (S n))))\n\n (* Test a natural for zero. *)\n | SpIsZero\n   :  forall n\n   ,  StepP (XOp1 OIsZero (VConst (CNat n)))\n            (XVal (VConst (CBool (beq_nat n 0)))).\n\nHint Constructors StepP.\n\n\n(********************************************************************)\n(* Preservation for pure single step rules. *)\nLemma stepp_preservation\n :  forall se sp x x' t e\n ,  StepP  x x'\n -> Forall ClosedT se\n -> TypeX  nil nil se sp x  t e\n -> TypeX  nil nil se sp x' t e.\nProof.\n intros se sp x x' t e HS HC HT. gen t e.\n induction HS; intros; inverts_type; rip.\n\n Case \"SpAppSubst\".\n  eapply subst_val_exp; eauto.\n\n Case \"SpAPPSubst\".\n  rrwrite (TBot KEffect = substTT 0 t2 (TBot KEffect)).\n  have HTE: (nil = substTE 0 t2 nil).\n  have HSE: (se  = substTE 0 t2 se) by (symmetry; auto).\n  rewrite HTE. rewrite HSE.\n  eapply subst_type_exp; eauto.\n   rrwrite (liftTE 0 se = se).\n   snorm.\n\n Case \"SpSucc\".\n  snorm. inverts H5. auto.\n\n Case \"SpIsZero\".\n  snorm. inverts H5. auto.\nQed.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Language/SystemF2Effect/Step/Pure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6573066390224138}}
{"text": "Require Export Coq.Unicode.Utf8.\nRequire Export FExistsProd.\n\n(*************************************************************************)\n(* Reduction relation                                                    *)\n(*************************************************************************)\n\nFixpoint Value (t : Tm) : Prop :=\n  match t with\n    | abs _ _    => True\n    | tabs _     => True\n    | pack _ t _ => Value t\n    | prod x y   => Value x ∧ Value y\n    | _          => False\n  end.\n\nInductive Match : Pat → Tm → Tm → Tm → Prop :=\n  | M_Var {T v t} :\n      Match (pvar T) v t (substTm X0 v t)\n  | M_Prod {p1 p2 v1 v2 t t' t''} :\n      Match p2 (weakenTm v2 (bindPat p1)) t t' →\n      Match p1 v1 t' t'' →\n      Match (pprod p1 p2) (prod v1 v2) t t''.\n\nInductive red : Tm → Tm → Prop :=\n  | appabs {T11 t12 t2} :\n      Value t2 → red (app (abs T11 t12) t2) (substTm X0 t2 t12)\n  | tapptabs {T2 t11} :\n      red (tapp (tabs t11) T2) (tsubstTm X0 T2 t11)\n  | E_UnpackPack {T11 v12 T1 t2} :\n      Value v12 →\n      red (unpack (pack T11 v12 (texist T1)) t2)\n          (tsubstTm X0 T11 (substTm X0 (tshiftTm C0 v12) t2))\n  | appfun {t1 t1' t2} :\n      red t1 t1' → red (app t1 t2) (app t1' t2)\n  | apparg {t1 t2 t2'} :\n      Value t1 → red t2 t2' → red (app t1 t2) (app t1 t2')\n  | typefun {t1 t1' T2} :\n      red t1 t1' → red (tapp t1 T2) (tapp t1' T2)\n  | E_pack {T11 t12 t12' T1} :\n      red t12 t12' → red (pack T11 t12 T1) (pack T11 t12' T1)\n  | E_unpack {t1 t1' t2} :\n      red t1 t1' → red (unpack t1 t2) (unpack t1' t2)\n  | prodl {t1 t1' t2} :\n      red t1 t1' → red (prod t1 t2) (prod t1' t2)\n  | prodr {t1 t2 t2'} :\n      Value t1 → red t2 t2' → red (prod t1 t2) (prod t1 t2')\n  | casep {p t1 t1' t2} :\n      red t1 t1' → red (case t1 p t2) (case t1' p t2)\n  | casev {p t1 t3 t2} :\n      Value t1 → Match p t1 t2 t3 → red (case t1 p t2) t3.\n", "meta": {"author": "Blaisorblade", "repo": "knot-esop-2017-case-study", "sha": "cf541cb38a483a514474f4c948bf005bc49b1e6f", "save_path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study", "path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study/knot-esop-2017-case-study-cf541cb38a483a514474f4c948bf005bc49b1e6f/casestudy/needle/fexistsprod/DeclarationEvaluation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6573066365073569}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.LetIn.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.Head.\n\nLocal Open Scope Z_scope.\n\nModule Z.\n  Definition eq_dec_cps {T} (x y : Z) (f : {x = y} + {x <> y} -> T) : T\n    := f (Z.eq_dec x y).\n  Definition eq_dec_cps_correct {T} x y f : @eq_dec_cps T x y f = f (Z.eq_dec x y)\n    := eq_refl.\n  Hint Rewrite @eq_dec_cps_correct : uncps.\n\n  Definition eqb_cps {T} (x y : Z) (f : bool -> T) : T\n    := f (Z.eqb x y).\n  Definition eqb_cps_correct {T} x y f : @eqb_cps T x y f = f (Z.eqb x y)\n    := eq_refl.\n  Hint Rewrite @eqb_cps_correct : uncps.\n\n  Local Ltac prove_cps_correct _ :=\n    try match goal with\n        | [ |- ?lhs ?f = ?f ?rhs ]\n          => let l := head lhs in\n             let r := head rhs in\n             cbv [l r] in *\n        end;\n    repeat first [ reflexivity\n                 | progress cbv [Decidable.dec Decidable.dec_eq_Z] in *\n                 | progress Z.ltb_to_lt\n                 | congruence\n                 | progress autorewrite with uncps\n                 | break_innermost_match_step ].\n\n  Definition get_carry_cps {T} (bitwidth : Z) (v : Z) (f : Z * Z -> T) : T\n    := f (Z.get_carry bitwidth v).\n  Definition get_carry_cps_correct {T} bitwidth v f\n    : @get_carry_cps T bitwidth v f = f (Z.get_carry bitwidth v)\n    := eq_refl.\n  Hint Rewrite @get_carry_cps_correct : uncps.\n  Definition add_with_get_carry_cps {T} (bitwidth : Z) (c : Z) (x y : Z) (f : Z * Z -> T) : T\n    := f (Z.add_with_get_carry bitwidth c x y).\n  Definition add_with_get_carry_cps_correct {T} bitwidth c x y f\n    : @add_with_get_carry_cps T bitwidth c x y f = f (Z.add_with_get_carry bitwidth c x y)\n    := eq_refl.\n  Hint Rewrite @add_with_get_carry_cps_correct : uncps.\n  Definition add_get_carry_cps {T} (bitwidth : Z) (x y : Z) (f : Z * Z -> T) : T\n    := f (Z.add_get_carry bitwidth x y).\n  Definition add_get_carry_cps_correct {T} bitwidth x y f\n    : @add_get_carry_cps T bitwidth x y f = f (Z.add_get_carry bitwidth x y)\n    := eq_refl.\n  Hint Rewrite @add_get_carry_cps_correct : uncps.\n\n  Definition get_borrow_cps {T} (bitwidth : Z) (v : Z) (f : Z * Z -> T)\n    := f (Z.get_borrow bitwidth v).\n  Definition get_borrow_cps_correct {T} bitwidth v f\n    : @get_borrow_cps T bitwidth v f = f (Z.get_borrow bitwidth v)\n    := eq_refl.\n  Hint Rewrite @get_borrow_cps_correct : uncps.\n  Definition sub_with_get_borrow_cps {T} (bitwidth : Z) (c : Z) (x y : Z) (f : Z * Z -> T) : T\n    := f (Z.sub_with_get_borrow bitwidth c x y).\n  Definition sub_with_get_borrow_cps_correct {T} (bitwidth : Z) (c : Z) (x y : Z) (f : Z * Z -> T)\n    : @sub_with_get_borrow_cps T bitwidth c x y f = f (Z.sub_with_get_borrow bitwidth c x y)\n    := eq_refl.\n  Hint Rewrite @sub_with_get_borrow_cps_correct : uncps.\n  Definition sub_get_borrow_cps {T} (bitwidth : Z) (x y : Z) (f : Z * Z -> T) : T\n    := f (Z.sub_get_borrow bitwidth x y).\n  Definition sub_get_borrow_cps_correct {T} (bitwidth : Z) (x y : Z) (f : Z * Z -> T)\n    : @sub_get_borrow_cps T bitwidth x y f = f (Z.sub_get_borrow bitwidth x y)\n    := eq_refl.\n  Hint Rewrite @sub_get_borrow_cps_correct : uncps.\n\n  (* splits at [bound], not [2^bitwidth]; wrapper to make add_getcarry\n  work if input is not known to be a power of 2 *)\n  Definition add_get_carry_full_cps {T} (bound : Z) (x y : Z) (f : Z * Z -> T) : T\n    := eqb_cps\n         (2 ^ (Z.log2 bound)) bound\n         (fun eqb\n          => if eqb\n             then add_get_carry_cps (Z.log2 bound) x y f\n             else f ((x + y) mod bound, (x + y) / bound)).\n  Lemma add_get_carry_full_cps_correct {T} (bound : Z) (x y : Z) (f : Z * Z -> T)\n    : @add_get_carry_full_cps T bound x y f = f (Z.add_get_carry_full bound x y).\n  Proof. prove_cps_correct (). Qed.\n  Hint Rewrite @add_get_carry_full_cps_correct : uncps.\n  Definition add_with_get_carry_full_cps {T} (bound : Z) (c x y : Z) (f : Z * Z -> T) : T\n    := eqb_cps\n         (2 ^ (Z.log2 bound)) bound\n         (fun eqb\n          => if eqb\n             then add_with_get_carry_cps (Z.log2 bound) c x y f\n             else f ((c + x + y) mod bound, (c + x + y) / bound)).\n  Lemma add_with_get_carry_full_cps_correct {T} (bound : Z) (c x y : Z) (f : Z * Z -> T)\n    : @add_with_get_carry_full_cps T bound c x y f = f (Z.add_with_get_carry_full bound c x y).\n  Proof. prove_cps_correct (). Qed.\n  Hint Rewrite @add_with_get_carry_full_cps_correct : uncps.\n  Definition sub_get_borrow_full_cps {T} (bound : Z) (x y : Z) (f : Z * Z -> T) : T\n    := eqb_cps\n         (2 ^ (Z.log2 bound)) bound\n         (fun eqb\n          => if eqb\n             then sub_get_borrow_cps (Z.log2 bound) x y f\n             else f ((x - y) mod bound, -((x - y) / bound))).\n  Lemma sub_get_borrow_full_cps_correct {T} (bound : Z) (x y : Z) (f : Z * Z -> T)\n    : @sub_get_borrow_full_cps T bound x y f = f (Z.sub_get_borrow_full bound x y).\n  Proof. prove_cps_correct (). Qed.\n  Hint Rewrite @sub_get_borrow_full_cps_correct : uncps.\n  Definition sub_with_get_borrow_full_cps {T} (bound : Z) (c x y : Z) (f : Z * Z -> T) : T\n    := eqb_cps\n         (2 ^ (Z.log2 bound)) bound\n         (fun eqb\n          => if eqb\n             then sub_with_get_borrow_cps (Z.log2 bound) c x y f\n             else f ((x - y - c) mod bound, -((x - y - c) / bound))).\n  Lemma sub_with_get_borrow_full_cps_correct {T} (bound : Z) (c x y : Z) (f : Z * Z -> T)\n    : @sub_with_get_borrow_full_cps T bound c x y f = f (Z.sub_with_get_borrow_full bound c x y).\n  Proof. prove_cps_correct (). Qed.\n  Hint Rewrite @sub_with_get_borrow_full_cps_correct : uncps.\n\n  Definition mul_split_at_bitwidth_cps {T} (bitwidth : Z) (x y : Z) (f : Z * Z -> T) : T\n    := dlet xy := x * y in\n        f (match bitwidth with\n           | Z.pos _ | Z0 => Z.land xy (Z.ones bitwidth)\n           | Z.neg _ => xy mod 2^bitwidth\n           end,\n           match bitwidth with\n           | Z.pos _ | Z0 => Z.shiftr xy bitwidth\n           | Z.neg _ => xy / 2^bitwidth\n           end).\n  Definition mul_split_at_bitwidth_cps_correct {T} (bitwidth : Z) (x y : Z) (f : Z * Z -> T)\n    : @mul_split_at_bitwidth_cps T bitwidth x y f = f (Z.mul_split_at_bitwidth bitwidth x y)\n    := eq_refl.\n  Hint Rewrite @mul_split_at_bitwidth_cps_correct : uncps.\n  Definition mul_split_cps {T} (s x y : Z) (f : Z * Z -> T) : T\n    := eqb_cps\n         s (2^Z.log2 s)\n         (fun b\n          => if b\n             then mul_split_at_bitwidth_cps (Z.log2 s) x y f\n             else f ((x * y) mod s, (x * y) / s)).\n  Lemma mul_split_cps_correct {T} (s x y : Z) (f : Z * Z -> T)\n    : @mul_split_cps T s x y f = f (Z.mul_split s x y).\n  Proof. prove_cps_correct (). Qed.\n  Hint Rewrite @mul_split_cps_correct : uncps.\n\n  Definition mul_split_cps' {T} (s x y : Z) (f : Z * Z -> T) : T\n    := eqb_cps\n         s (2^Z.log2 s)\n         (fun b\n          => if b\n             then f (Z.mul_split_at_bitwidth (Z.log2 s) x y)\n             else f ((x * y) mod s, (x * y) / s)).\n  Lemma mul_split_cps'_correct {T} (s x y : Z) (f : Z * Z -> T)\n    : @mul_split_cps' T s x y f = f (Z.mul_split s x y).\n  Proof. prove_cps_correct (). Qed.\n  Hint Rewrite @mul_split_cps'_correct : uncps.\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/CPS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.657306634107217}}
{"text": "Require Import Modal.\nRequire Import occ_in_phi.\nRequire Import Bool.\nRequire Import PeanoNat Nat Compare_dec.\n\n(* is_pos *)\n\nFixpoint is_pos_pre (phi : Modal) (i : nat) : bool :=\n  match phi with\n  | atom p => EqNat.beq_nat 1 i\n  | mneg psi => negb (is_pos_pre psi i)\n  | mconj psi1 psi2 => if le_dec i (length (pv_in psi1)) then is_pos_pre psi1 i\n                          else is_pos_pre psi2 (i-(length (pv_in psi1)))\n  | mdisj psi1 psi2 => if le_dec i (length (pv_in psi1)) then is_pos_pre psi1 i\n                          else is_pos_pre psi2 (i-(length (pv_in psi1)))\n  | mimpl psi1 psi2 => if le_dec i (length (pv_in psi1)) then negb (is_pos_pre psi1 i)\n                          else is_pos_pre psi2 (i-(length (pv_in psi1)))\n  | box psi => is_pos_pre psi i\n  | dia psi => is_pos_pre psi i\n  end.\n\nInductive is_pos phi i : Prop :=\n| occ_pos : occ_in_modal phi i -> is_pos_pre phi i = true -> is_pos phi i.\n\n(* ----------------------------------------------------------------- *)\n\n(* is_neg *)\n\nFixpoint is_neg_pre (phi : Modal) (i : nat) : bool :=\n  match phi with\n  | atom p => false\n  | mneg psi => negb (is_neg_pre psi i)\n  | mconj psi1 psi2 => if le_dec i (length (pv_in psi1)) then is_neg_pre psi1 i\n                          else is_neg_pre psi2 (i-(length (pv_in psi1)))\n  | mdisj psi1 psi2 => if le_dec i (length (pv_in psi1)) then is_neg_pre psi1 i\n                          else is_neg_pre psi2 (i-(length (pv_in psi1)))\n  | mimpl psi1 psi2 => if le_dec i (length (pv_in psi1)) then negb (is_neg_pre psi1 i)\n                          else is_neg_pre psi2 (i-(length (pv_in psi1)))\n  | box psi => is_neg_pre psi i\n  | dia psi => is_neg_pre psi i\n  end.\n\nInductive is_neg phi i : Prop :=\n  | occ_neg : occ_in_modal phi i -> is_neg_pre phi i = true -> is_neg phi i.", "meta": {"author": "caitlindabrera", "repo": "Sahlqvist", "sha": "d0a755fb663a6cabc0babb691564cdf575fc8b36", "save_path": "github-repos/coq/caitlindabrera-Sahlqvist", "path": "github-repos/coq/caitlindabrera-Sahlqvist/Sahlqvist-d0a755fb663a6cabc0babb691564cdf575fc8b36/vsSahlq/coq_code/is_pos_neg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6573066290771026}}
{"text": "Require Import Lia.\nRequire Import Coq.Vectors.Vector.\nRequire Import Coq.Logic.Eqdep_dec.\nRequire Import Coq.Logic.Classical_Prop.\nImport VectorNotations.\n\n(**\nI found myself looking for analogous functions as what could be found in the\n[List] standard library. I sadly found none. This forced me to implement\nmy own. And here they are!\n*)\n\nSection Vector.\nHint Constructors Vector.Exists : core.\nLemma Vector_Exists_cons {A} (P : A -> Prop) (x : A) {n} (l : Vector.t A n):\n      Vector.Exists P (x::l)%vector <-> P x \\/ Vector.Exists P l.\nProof.\n  split.\n  - intros. inversion H. apply inj_pair2_eq_dec in H3. left; assumption.\n    decide equality. apply inj_pair2_eq_dec in H3. 2: decide equality. right. rewrite H3 in H2. assumption.\n  - intros. destruct H. auto. auto.\nQed.\n\nLemma Vector_Exists_nil {A} (P : A -> Prop): Vector.Exists P []%vector <-> False.\nProof. split; inversion 1. Qed.\n\nLemma Vector_Forall_cons_iff  {A} (P : A -> Prop) : \n  forall (a:A) {n} (l : Vector.t A n), Vector.Forall P (a :: l)%vector <-> P a /\\ Vector.Forall P l.\nProof.\nintros. split. \n- intro H; inversion H.\n  apply inj_pair2_eq_dec in H2. 2: decide equality. rewrite H2 in H4. split.\n  apply H3. apply H4.\n- constructor. destruct H. apply H.  destruct H. apply H0.\nQed.\n\nLemma vector_de_morgan {A : Type} {n} : forall  (P : A -> Prop) (l : Vector.t A n),\n  ~(Vector.Exists P l) <-> Vector.Forall (fun a => ~(P a)) l.\nProof.\n  intros; split.\n  - intros. simpl; auto. induction l. apply Vector.Forall_nil.\n    assert (Vector.Exists P (h :: l)%vector <-> P h \\/ Vector.Exists P l). { apply Vector_Exists_cons. }\n    rewrite H0 in H.\n    apply Decidable.not_or in H.\n    apply Vector_Forall_cons_iff. split. destruct H. assumption.\n    destruct H. apply IHl in H1. assumption.\n  - intros. induction l.\n  + assert (Vector.Exists P []%vector <-> False). { apply Vector_Exists_nil. } rewrite H0. simpl; auto.\n  + assert (Vector.Exists P (h :: l)%vector <-> P h \\/ Vector.Exists P l). { apply Vector_Exists_cons. }\n    rewrite H0.\n    set (notP0 := (fun (a : A) => ~ P a)).\n    apply (Vector_Forall_cons_iff) in H. destruct H. apply IHl in H1 as IH.\n    apply and_not_or. split. assumption. assumption.\nQed.\nEnd Vector.", "meta": {"author": "pqnelson", "repo": "soft-type", "sha": "4a46a11ea98b89425d571fcb1ba0c73a30cd91c4", "save_path": "github-repos/coq/pqnelson-soft-type", "path": "github-repos/coq/pqnelson-soft-type/soft-type-4a46a11ea98b89425d571fcb1ba0c73a30cd91c4/ST/Vector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7662936324115012, "lm_q1q2_score": 0.6573022425119953}}
{"text": "Require Export Ensembles.\nRequire Import EnsemblesImplicit.\nRequire Export Families.\nRequire Export FiniteTypes.\nRequire Export IndexedFamilies.\n\nInductive finite_intersections {X:Type} (S:Family X) : Family X :=\n  | intro_full: In (finite_intersections S) Full_set\n  | intro_S: forall U:Ensemble X, In S U -> In (finite_intersections S) U\n  | intro_intersection: forall U V:Ensemble X,\n    In (finite_intersections S) U -> In (finite_intersections S) V ->\n    In (finite_intersections S) (Intersection U V).\n\nLemma finite_intersection_is_finite_indexed_intersection:\n  forall {X:Type} (S:Family X) (U:Ensemble X),\n  In (finite_intersections S) U -> exists J:Type, FiniteT J /\\\n  exists V:J->Ensemble X,\n  (forall j:J, In S (V j)) /\\ U = IndexedIntersection V.\nProof.\nintros.\ninduction H.\nexists False.\nsplit.\nconstructor.\nexists (False_rect _).\nsplit.\ndestruct j.\nsymmetry; apply empty_indexed_intersection.\n\nexists True.\nsplit.\nexact True_finite.\nexists (True_rect U).\nsplit.\ndestruct j.\nsimpl.\ntrivial.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\ndestruct a; simpl.\ntrivial.\ndestruct H0.\nexact (H0 I).\ndestruct IHfinite_intersections as [J0 [? [W []]]].\ndestruct IHfinite_intersections0 as [J1 [? [W' []]]].\nexists ((J0+J1)%type).\nsplit.\napply finite_sum; trivial.\nexists (fun s:J0+J1 => match s with\n  | inl j => W j\n  | inr j => W' j\nend).\nsplit.\ndestruct j; auto.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H7.\nrewrite H3 in H7; destruct H7.\nrewrite H6 in H8; destruct H8.\nconstructor.\ndestruct a as [j|j]; auto.\ndestruct H7.\nconstructor.\nrewrite H3; constructor.\nintro j.\nexact (H7 (inl _ j)).\nrewrite H6; constructor.\nintro j.\nexact (H7 (inr _ j)).\nQed.\n\nLemma finite_indexed_intersection_is_finite_intersection:\n  forall {X:Type} (S:Family X) (J:Type) (V:J->Ensemble X),\n  FiniteT J -> (forall j:J, In S (V j)) ->\n  In (finite_intersections S) (IndexedIntersection V).\nProof.\nintros.\ninduction H.\nrewrite empty_indexed_intersection.\nconstructor.\n\nassert (IndexedIntersection V = Intersection\n  (IndexedIntersection (fun j:T => V (Some j)))\n  (V None)).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H1.\nconstructor.\nconstructor.\ntrivial.\ntrivial.\ndestruct H1.\nconstructor.\ndestruct H1.\ndestruct a as [j|]; trivial.\nrewrite H1.\nconstructor 3; auto.\nconstructor 2; trivial.\n\ndestruct H1 as [g].\nassert (IndexedIntersection V =\n  IndexedIntersection (fun x:X0 => V (f x))).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H3.\nconstructor.\ntrivial.\ndestruct H3.\nconstructor.\nintro.\nrewrite <- (H2 a).\ntrivial.\nrewrite H3; auto.\nQed.\n", "meta": {"author": "dschepler", "repo": "coq-zorns-lemma", "sha": "4ad354c50f73758c094f43da5fc0f2c6dd8e3da2", "save_path": "github-repos/coq/dschepler-coq-zorns-lemma", "path": "github-repos/coq/dschepler-coq-zorns-lemma/coq-zorns-lemma-4ad354c50f73758c094f43da5fc0f2c6dd8e3da2/FiniteIntersections.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6573022377372075}}
{"text": "Require Import Notations.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.Le.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.omega.Omega.\nRequire Import Bool.Sumbool.\nRequire Import Bool.Bool.\nRequire Import Coq.Logic.ConstructiveEpsilon.\nRequire Import Coq.ZArith.ZArith.\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\n(* all_pairs computes all the pairs of candidates in l *)\nFixpoint all_pairs {A: Type} (l: list A): list (A * A) :=\n  match l with\n  | [] => []\n  | c::cs => (c, c) :: (all_pairs cs)\n                   ++  (map (fun x => (c, x)) cs)\n                   ++ (map (fun x => (x, c)) cs)\n  end.\n\n(* maxlist return the maximum number in list l. 0 in case of empty list *)\nFixpoint maxlist (l : list Z) : Z :=\n  match l with\n  | [] => 0%Z\n  | [h] => h\n  | h :: t => Z.max h (maxlist t)\n  end.\n\n(* give two numbers m and n with proof that m < n then it return the\n   proof that maximum of m and n is n *)\nLemma max_two_integer : forall (m n : Z), m < n -> Z.max m n = n.\nProof.\n  intros m n H; apply Z.max_r; omega.\nQed.\n\n(* Shows the prop level existence of element x in list l >=  s if maximum element of\n   list l >= s  *)\nLemma max_of_nonempty_list :\n  forall (A : Type) (l : list A) (H : l <> nil) (H1 : forall x y : A, {x = y} + {x <> y}) (s : Z) (f : A -> Z),\n    maxlist (map f l) >= s <-> exists (x:A), In x l /\\ f x >= s.\nProof.\n  split; intros. generalize dependent l.\n  induction l; intros. specialize (H eq_refl). inversion H.\n  pose proof (list_eq_dec H1 l []).\n  destruct H2. exists a. rewrite e. intuition. rewrite e in H0.\n  simpl in H0. auto.\n  assert (Hm : {f a >= maxlist (map f l)} + {f a < maxlist (map f l)}) by\n      apply (Z_ge_lt_dec (f a) (maxlist (map f l))).\n  destruct Hm. rewrite map_cons in H0.\n  pose proof (exists_last n).  destruct X as [l1 [x l2]].\n  assert (maxlist (f a :: map f l) = Z.max (f a) (maxlist (map f l))).\n  { destruct l1. simpl in l2. rewrite l2. simpl. auto.\n    rewrite l2. simpl. auto. }\n  pose proof (Z.ge_le _ _ g). pose proof (Z.max_l _ _ H3).\n  rewrite H2 in H0. rewrite H4 in H0. exists a. intuition.\n  rewrite map_cons in H0. pose proof (exists_last n). destruct X as [l1 [x l2]].\n  assert (maxlist (f a :: map f l) = Z.max (f a) (maxlist (map f l))).\n  { destruct l1. simpl in l2. rewrite l2. simpl. auto.\n    rewrite l2. simpl. auto. }\n  rewrite H2 in H0. pose proof (max_two_integer _ _ l0). rewrite H3 in H0.\n  specialize (IHl n H0). destruct IHl. exists x0. intuition.\n  destruct H0 as [x [H2 H3]].\n  induction l. specialize (H eq_refl). inversion H.\n  pose proof (list_eq_dec H1 l []). destruct H0.\n  (* empty list *)\n  subst. simpl in *. destruct H2. subst. auto. inversion H0.\n  (* not empty list *)\n  rewrite map_cons. pose proof (exists_last n). destruct X as [l1 [x0 H4]].\n  assert (maxlist (f a :: map f l) = Z.max (f a) (maxlist (map f l))).\n  { destruct l1. simpl in H4. rewrite H4. simpl. auto.\n    rewrite H4. simpl. auto. }\n  rewrite H0. unfold Z.max. destruct (f a ?= maxlist (map f l)) eqn:Ht.\n  destruct H2. subst. auto. pose proof (proj1 (Z.compare_eq_iff _ _) Ht).\n  specialize (IHl n H2). rewrite H5. auto.\n  destruct H2. subst.\n  pose proof (proj1 (Z.compare_lt_iff _ _) Ht). omega.\n  apply IHl. assumption. assumption.\n  destruct H2. subst. assumption. specialize (IHl n H2).\n  pose proof (proj1 (Z.compare_gt_iff _ _) Ht).  omega.\nQed.\n\n(* minimum of two integers m and n is >= s then both numbers are\n   >= s *)\nLemma z_min_lb : forall m n s, Z.min m n >= s <-> m >= s /\\ n >= s.\nProof.\n  split; intros. unfold Z.min in H.\n  destruct (m ?= n) eqn:Ht.\n  pose proof (proj1 (Z.compare_eq_iff _ _) Ht). intuition.\n  pose proof (proj1 (Z.compare_lt_iff _ _) Ht). intuition.\n  pose proof (proj1 (Z.compare_gt_iff _ _) Ht). intuition.\n  destruct H as [H1 H2].\n  unfold Z.min. destruct (m ?= n) eqn:Ht; auto.\nQed.\n\n(* if length of list l >= 1 then  l is nonempty *)\nLemma exists_list : forall (A : Type) (l : list A) (n : nat),\n    (length l >= S n)%nat -> exists a ls, l = a :: ls.\nProof.\n  intros A l. destruct l eqn: Ht; intros; simpl in H. inversion H.\n  exists a, l0. reflexivity.\nQed.\n\n(* If a in list l and x in not in list l then x <> a *)\nLemma not_equal_elem : forall (A : Type) (a x : A) (l : list A),\n    In a l -> ~ In x l -> x <> a.\nProof.\n  intros A a x l H1 H2.\n  induction l. inversion H1.\n  specialize (proj1 (not_in_cons x a0 l) H2); intros.\n  simpl in H1. destruct H as [H3 H4]. destruct H1.\n  subst. assumption. apply IHl. assumption. assumption.\nQed.\n\n(* all the elements appearing in l also appears in list c *)\nDefinition covers (A : Type) (c l : list A) := forall x : A, In x l -> In x c.\n\n(* split the list l at duplicate elements given the condition that c covers l *)\nLemma list_split_dup_elem : forall (A : Type) (n : nat) (c : list A) (H1 : forall x y : A, {x = y} + {x <> y}),\n    length c = n -> forall (l : list A) (H : (length l > length c)%nat),\n      covers A c l -> exists (a : A) l1 l2 l3, l = l1 ++ (a :: l2) ++ (a :: l3).\nProof.\n  intros A n. induction n; intros. unfold covers in H1. rewrite H in H0.\n  unfold covers in H2. pose proof (proj1 (length_zero_iff_nil c) H).\n  rewrite H3 in H2. simpl in H2. pose proof (exists_list _ _ _ H0).\n  destruct H4 as [a [ls H4]]. rewrite H4 in H2. specialize (H2 a (in_eq a ls)). inversion H2.\n  rewrite H in H0. pose proof (exists_list _ _ _ H0).\n  destruct H3 as [l0 [ls H3]].\n  pose proof (in_dec H1 l0 ls). destruct H4.\n  pose proof (in_split l0 ls i). destruct H4 as [l1 [l2 H4]].\n  rewrite H4 in H3. exists l0, [], l1, l2. simpl. auto.\n  unfold covers in H2. rewrite H3 in H2.\n  pose proof (H2 l0 (in_eq l0 ls)).\n  pose proof (in_split l0 c H4). destruct H5 as [l1 [l2 H5]].\n  rewrite H5 in H. rewrite app_length in H. simpl in H.\n  assert (Ht : (length l1 + S (length l2))%nat = (S (length l1 + length l2))%nat) by omega.\n  rewrite Ht in H. clear Ht. inversion H. clear H.\n  rewrite <- app_length in H7.\n  assert ((length ls > length (l1 ++ l2))%nat).\n  { rewrite H7. rewrite H3 in H0. simpl in H0. omega. }\n  specialize (IHn (l1 ++ l2) H1 H7 ls H).\n  assert (covers A (l1 ++ l2) ls).\n  { unfold covers. intros x Hin.\n    specialize (not_equal_elem _ x l0 ls Hin n0); intros.\n    specialize (H2 x (or_intror Hin)).\n    rewrite H5 in H2.\n    pose proof (in_app_or l1 (l0 :: l2) x H2). destruct H8.\n    apply in_or_app. left. assumption.\n    simpl in H8. destruct H8. contradiction.\n    apply in_or_app. right. assumption. }\n  specialize (IHn H6). destruct IHn as [a [l11 [l22 [l33 H10]]]].\n  exists a, (l0 :: l11), l22, l33.  simpl. rewrite H10 in H3. assumption.\nQed.\n\n(* if maximum of two numbers m, n >= s then either m >= s or\n   n >= s *)\nLemma z_max_lb : forall m n s, Z.max m n >= s <-> m >= s \\/ n >= s.\nProof.\n  split; intros. unfold Z.max in H. destruct (m ?= n) eqn : Ht.\n  left. auto. right. auto. left. auto.\n  destruct H. unfold Z.max. destruct (m ?= n) eqn: Ht.\n  auto. pose proof (proj1 (Z.compare_lt_iff _ _) Ht). omega. omega.\n  unfold Z.max. destruct (m ?= n) eqn:Ht.\n  pose proof (proj1 (Z.compare_eq_iff _ _) Ht). omega.\n  omega. pose proof (proj1 (Z.compare_gt_iff _ _) Ht). omega.\nQed.\n\n(* if length of list l is > n then there is a natural number\n   p such that p + n = length of list l *)\nLemma list_and_num : forall (A : Type) (n : nat) (l : list A),\n    (length l > n)%nat -> exists p, (length l = p + n)%nat.\nProof.\n  intros A n l H. induction l. inversion H.\n  simpl in *. apply gt_S in H. destruct H. specialize (IHl H). destruct IHl as [p IHl].\n  exists (S p). omega. exists 1%nat. omega.\nQed.\n\n(* if forallb f l returns false then existance of element x in list l\n   such that f x = false, and if x is in list l and f x = false then\n   forallb f l will evaluate to false *)\nLemma forallb_false : forall (A : Type) (f : A -> bool) (l : list A),\n    forallb f l = false <-> (exists x, In x l /\\ f x = false).\nProof.\n  intros A f l. split. intros H. induction l. simpl in H. inversion H.\n  simpl in H. apply andb_false_iff in H. destruct H.\n  exists a. split. simpl. left. auto. assumption.\n  pose proof IHl H. destruct H0. exists x. destruct  H0 as [H1 H2].\n  split. simpl. right. assumption. assumption.\n  intros. destruct H as [x [H1 H2]]. induction l. inversion H1.\n  simpl. apply andb_false_iff. simpl in H1. destruct H1.\n  left. congruence. right. apply IHl. assumption.\nQed.\n\n\n  \n(*  Shows the type level existence of element x in list l >=  s if maximum element of\n   list l >= s *)\nLemma max_of_nonempty_list_type :\n  forall (A : Type) (l : list A) (H : l <> nil) (H1 : forall x y : A, {x = y} + {x <> y})\n    (s : Z) (f : A -> Z), maxlist (map f l) >= s -> existsT (x:A), In x l /\\ f x >= s.\nProof.\n  intros A.\n  assert (Hm : forall (a b : A) (l : list A) (f : A -> Z),\n             maxlist (f a :: map f (b :: l)) = Z.max (f a) (maxlist (map f (b :: l)))) by auto.\n  refine (fix F l {struct l} :=\n            fun H H1 s f => \n              match l as l0 return (l = l0 -> l0 <> [] ->\n                                    maxlist (map f l0) >= s ->\n                                    existsT (x : A), In x l0 /\\ f x >= s) with\n              | [] => fun _ H =>  match H eq_refl with end\n              | h :: t =>\n                fun Heq Hn =>\n                  match t as t0 return (t = t0 -> (h :: t0) <> [] ->\n                                        maxlist (map f (h :: t0)) >= s ->\n                                        existsT (x : A), In x (h :: t0) /\\ f x >= s) with\n                  | [] => fun _ H1 H2 => existT _ h (conj (in_eq h []) H2)\n                  | h1 :: t1 =>\n                    let Hmax := (Z_ge_lt_dec (f h) (maxlist (map f (h1 :: t1)))) in\n                    match Hmax with\n                    | left e => fun H1 H2 H3 => _\n                    | right r => fun H1 H2 H3 => _\n                    end \n                  end eq_refl Hn\n            end eq_refl H).\n  \n  rewrite map_cons in H3. rewrite Hm in H3.\n  apply Z.ge_le in e. pose proof (Z.max_l _ _ e) as Hmx.\n  rewrite Hmx in H3.\n  exists h. intuition.\n\n  \n  rewrite map_cons in H3. rewrite Hm in H3.\n  pose proof (max_two_integer _ _ r) as Hmx.\n  rewrite Hmx in H3.\n  assert (Ht : [] <> h1 :: t1) by apply nil_cons.\n  apply not_eq_sym in Ht. \n  rewrite <- H1 in H2, H3, Hmx, Ht.\n  specialize (F _ Ht H0 s f H3).\n  destruct F as [x [Fin Fx]]. rewrite <- H1. \n  exists x. intuition.\nDefined.   \n   \n\n\n(* if forallb f l returns false then type level existance of element x in list l\n   such that f x = false *)\nLemma forallb_false_type : forall (A : Type) (f : A -> bool) (l : list A),\n    forallb f l = false -> existsT x, In x l /\\ f x = false.\nProof. \n  refine (fun A f =>\n            fix F l :=\n            match l as l0 return (forallb f l0 = false ->\n                                  existsT x, In x l0 /\\ f x = false) with\n            | [] => fun H => match (diff_true_false H) with end\n            | h :: t =>\n              fun H => match f h as v return (f h = v -> existsT x, In x (h :: t) /\\ f x = false) with\n                    | false => fun H1 => existT _ h (conj (in_eq h t) H1)\n                    | true => fun H1 => _\n                    end eq_refl                             \n            end).\n \n  simpl in H. rewrite H1 in H. simpl in H. pose proof (F t H) as Ft.\n  destruct Ft as [x [Fin Fx]]. exists x. intuition.\nDefined.\n(* End of List Lemma file *)\n\n", "meta": {"author": "mukeshtiwari", "repo": "formalized-voting", "sha": "44c001288087c96c0fe8569dcc6c9704e68fb9aa", "save_path": "github-repos/coq/mukeshtiwari-formalized-voting", "path": "github-repos/coq/mukeshtiwari-formalized-voting/formalized-voting-44c001288087c96c0fe8569dcc6c9704e68fb9aa/SchulzeCounting/ListLemma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6572282667780763}}
{"text": "Set Implicit Arguments.\nRequire Import List.\n\n\n(** * The Functor Type Class *)\n\nLocal Notation \"f ∘ g\" := (fun x => f (g x)) (at level 40, left associativity).\n\nClass Functor (f : Type -> Type) : Type :=\n{ fmap         : forall {A B}, (A -> B) -> f A -> f B }. \nClass Functor_Correct (f : Type -> Type) `{F : Functor f} :=\n{ fmap_id      : forall A, fmap (fun (x:A)=> x) = (fun x => x);\n  fmap_compose : forall A B C (g : A -> B) (f : B -> C), \n                 fmap (f ∘ g) = fmap f ∘ fmap g\n}.\nClass Applicative (f : Type -> Type) `{F : Functor f} : Type :=\n{ pure : forall {A}, A -> f A;\n  liftA : forall {A B}, f (A -> B) -> f A -> f B\n}.\nNotation \"f <*> a\" := (liftA f a) (left associativity, at level 25).\n\n\nClass Applicative_Correct (f : Type -> Type) `{Applicative f} :=\n{ applicative_id : forall A, liftA (pure (fun  (x:A) => x)) = (fun  x => x);\n  applicative_composition : forall {A B C} (u : f (B -> C)) (v : f (A -> B)) (w : f A),\n    pure (fun  x => fun  y => x ∘ y) <*> u <*> v <*> w = u <*> (v <*> w);\n  applicative_homomorphism : forall {A B} (f : A -> B) (x : A),\n    pure f <*> pure x = pure (f x);\n  applicative_interchange : forall {A B} (u : f (A -> B)) (y : A),\n    u <*> pure y = pure (fun x => x y) <*> u\n}.\n\nClass Monad (m: Type -> Type) `{M : Applicative m} : Type :=\n{ bind: forall {A}, m A -> forall {B}, (A -> m B) -> m B\n}.\nDefinition return_ {m : Type -> Type} `{M : Monad m} {A : Type} : A -> m A := pure.\nNotation \"a >>= f\" := (bind a f) (at level 50, left associativity).\n\nHint Unfold bind return_ : monad_db.\n\nClass Monad_Correct (m : Type -> Type) `{M : Monad m} := {\n  bind_right_unit: forall A (a: m A), a = a >>= return_;\n  bind_left_unit: forall A (a: A) B (f: A -> m B),\n             f a = return_ a >>= f;\n  bind_associativity: forall A (ma: m A) B f C (g: B -> m C),\n                 bind ma (fun  x=> f x >>= g) = (ma >>= f) >>= g\n}.\n\nArguments Functor f : assert.\nArguments Functor_Correct f {F}.\nArguments Applicative f [F]. \nArguments Applicative_Correct f {F} {A} : rename.\nArguments Monad m [F] [M].\nArguments Monad_Correct m [F] [A] [M] : rename.\n\nSection monadic_functions.\n Variable m : Type -> Type. \n Variable F : Functor m.\n Variable A : Applicative m.\n Variable M : Monad m.\n\n Definition wbind {A: Type} (ma: m A) {B: Type} (mb: m B) :=\n ma >>= fun  _=>mb.\n\n Definition liftM {A B: Type} (f: A->B) (ma: m A): m B :=\n ma >>= (fun  a => return_ (f a)).\n\n Definition join {A: Type} (mma: m (m A)): m A :=\n mma >>= (fun  ma => ma).\n\nEnd monadic_functions.\n\nNotation \"a >> f\" := (wbind _ a f) (at level 50, left associativity).\nNotation \"'do' a ← e ; c\" := (e >>= (fun  a => c)) (at level 60, right associativity).\n\n\nFixpoint foldM {A B m} `{Monad m} \n               (f : B -> A -> m B) (b : B) (ls : list A) : m B :=\n  match ls with\n  | nil      => return_ b\n  | x :: ls' => do y ← f b x;\n                foldM f y ls'\n  end.\nHint Unfold foldM : monad_db.\n\nAbout fmap_compose.\nLemma fmap_compose' {f} (F : Functor f) `{Functor_Correct f} : \n    forall {A B C} (g : A -> B) (h : B -> C) (a : f A),\n    fmap h (fmap g a) = fmap (h ∘ g) a.\nProof.\n  intros.\n  rewrite (fmap_compose g h).\n  reflexivity.\nQed.\n  \n\nRequire Import Program.\nLemma bind_eq : forall {A B m} `{Monad m} (a a' : m A) (f f' : A -> m B),\n      a = a' ->\n      (forall x, f x = f' x) ->\n      bind a f = bind a' f'.\nProof.\n  intros. subst.\n  f_equal.\n  apply functional_extensionality.\n  auto.\nQed.\n\nLtac simplify_monad_LHS :=\n  repeat match goal with\n  | [ |- bind (return_ _) _ = _ ] => rewrite <- bind_left_unit\n  | [ |- bind (bind _ _) _ = _ ]  => rewrite <- bind_associativity\n  | [ |- _ = _ ]                  => reflexivity\n  | [ |- bind ?a ?f = _ ]         => erewrite bind_eq; intros; \n                                     [ | simplify_monad_LHS | simplify_monad_LHS ]\n  end.\n\nLtac simplify_monad :=\n  simplify_monad_LHS;\n  apply eq_sym;\n  simplify_monad_LHS;\n  apply eq_sym.\n\nLtac simpl_m :=\n  repeat (try match goal with\n  [ |- bind ?a _ = bind ?a _ ] => apply bind_eq; [ reflexivity | intros ]\n  end; simplify_monad).\n\nProposition test : forall {m} `{Monad m} `{Monad_Correct m} (a b c : m unit),\n        do x ← a; do y ← b;  c\n      = do y ← (do x ← a; b); c.\nProof. intros.\nsimplify_monad.\nAbort.\n\n(** * Some classic Monads *)\n\n(** ** The list monad *)\n\nOpen Scope list_scope. \n(*\nDefinition list_fmap {A B} (f : A -> B) := \n  fix map (l : list A) : list B :=\n  match l with\n  | nil => nil\n  | a :: t => f a :: map t\n  end.\n*)\nDefinition list_fmap := map.\nHint Unfold list_fmap : monad_db.\n(*\nFixpoint list_fmap {A B} (f : A -> B) (ls : list A) : list B :=\n  match ls with\n  | nil => nil\n  | a :: ls' => f a :: list_fmap f ls'\n  end.  *)\n\n(*\nFixpoint concat {A} (xs : list (list A)) : list A :=\n  match xs with\n  | nil => nil\n  | ys :: xs' => ys ++ concat xs'\n  end.\n*)\n\nDefinition list_liftA {A B} (fs : list (A -> B)) (xs : list A) : list B :=\n  let g := fun a => list_fmap (fun f => f a) fs\n  in\n  concat (list_fmap g xs).\nHint Unfold list_liftA : monad_db.\n\nFixpoint list_bind {A} (xs : list A) {B} (f : A -> list B) : list B :=\n  match xs with\n  | nil => nil\n  | a :: xs' => f a ++ list_bind xs' f\n  end.\nHint Unfold list_bind : monad_db.\n\nInstance listF : Functor list := { fmap := @list_fmap }.\nInstance listA : Applicative list := { pure := fun _ x => x :: nil\n                                     ; liftA := @list_liftA }.\nInstance listM : Monad list := \n  { bind := @list_bind }.\n\nInstance listF_correct : Functor_Correct list.\nProof.\n  constructor.\n  * intros. simpl. apply functional_extensionality; intros x.\n    induction x; simpl; auto.\n    rewrite IHx; auto.\n  * intros. simpl. apply functional_extensionality; intros x.\n    induction x; simpl; auto.\n    rewrite IHx.\n    auto.\nQed.\n\nInstance listA_correct : Applicative_Correct list.\nProof.\n  constructor.\n  * intros. simpl. apply functional_extensionality; intros l.\n    induction l; simpl; auto.\n    unfold list_liftA in *. simpl in *.\n    rewrite IHl; easy.\nAbort.\n\nInstance listM_correct : Monad_Correct list.\nAbort.\n\n\n\n\nLemma fmap_app : forall {A B} (f : A -> B) ls1 ls2,\n      fmap f (ls1 ++ ls2) = fmap f ls1 ++ fmap f ls2.\nProof.\n  induction ls1; intros; simpl; auto.\n  rewrite IHls1. auto.\nQed.\n\n(** ** The Maybe monad (using option type) *) \n\nDefinition option_fmap {A B} (f : A -> B) (x : option A) : option B :=\n  match x with\n  | None => None\n  | Some a => Some (f a)\n  end.\nDefinition option_liftA {A B} (f : option (A -> B)) (x : option A) : option B :=\n  match f, x with\n  | Some f', Some a => Some (f' a)\n  | _, _ => None\n  end.\nInstance optionF : Functor option := { fmap := @option_fmap}.\nInstance optionA : Applicative option := { pure := @Some;\n                                           liftA := @option_liftA}.\nInstance optionM : Monad option :=\n  { bind := fun  A m B f => match m with None => None | Some a => f a end\n  }.\nInstance optionM_Laws : Monad_Correct option.\nProof. split.\n  - destruct a; auto.\n  - intros; auto.\n  - destruct ma; intros; auto.\nDefined.\n\n(* Monad Transformer *)\nClass MonadTrans (t : (Type -> Type) -> (Type -> Type)) :=\n  { liftT : forall {m} `{Monad m} {A}, m A -> t m A }.\n\n\n(** Option monad transformer *)\nDefinition optionT m (A : Type) : Type := m (option A).\n\nDefinition optionT_liftT {m} `{Monad m} {A} (x : m A) : optionT m A.\nProof.\n  unfold optionT.\n  refine (do a ← x; return_ (Some a)).\nDefined.\nInstance optionT_T : MonadTrans optionT := {liftT := @optionT_liftT}.\n\nDefinition optionT_fmap {f} `{Functor f} \n                        {A B} (g : A -> B) (x : optionT f A) : optionT f B :=\n  @fmap f _ _ _ (fmap g) x.\nDefinition optionT_liftA {f} `{Applicative f}\n                         {A B} (g : optionT f (A -> B)) (x : optionT f A) \n                       : optionT f B.\n(*  @liftA f _ _ _ _ (fmap liftA g) x.*)\nProof. \n  unfold optionT in *.\n  exact (fmap liftA g <*> x).\nDefined. \nDefinition optionT_pure {f} `{Applicative f}\n                        {A} (a : A) : optionT f A := @pure f _ _ _ (pure a).\nDefinition optionT_bind {m} `{Monad m}\n                        {A} (ma : optionT m A) {B} (f : A -> optionT m B)\n                        : optionT m B.\n  unfold optionT in *.\n  exact (do oa ← ma; \n         match oa with\n         | None => pure None\n         | Some a => f a\n         end\n  ).\nDefined.\n\nInstance optionT_F {f} `{Functor f} : Functor (optionT f) := \n    {fmap := @optionT_fmap f _}.\nInstance optionT_A {f} `{Applicative f} : Applicative (optionT f) :=\n  { pure := @optionT_pure f _ _;\n    liftA := @optionT_liftA f _ _ }.\nInstance optionT_M {m} `{Monad m} : Monad (optionT m) :=\n  { bind := @optionT_bind m _ _ _ }.\n\n(** The Reader monad *)\nAxiom Eta: forall A (B: A -> Type) (f: forall a, B a), f = fun  a=>f a.\n\nDefinition Reader (E : Type) := fun  X => E -> X.\nDefinition reader_fmap E A B (f : A -> B) (r : Reader E A) : Reader E B :=\n  fun x => f (r x).\nDefinition reader_liftA E A B (f : Reader E (A -> B)) (r : Reader E A) :=\n  fun x => (f x) (r x).\nDefinition reader_bind E A (r : Reader E A) B (f : A -> Reader E B) : Reader E B :=\n  fun x => f (r x) x.\n  \nInstance readerF E : Functor (Reader E) :=\n { fmap := @reader_fmap E }.\nInstance readerA E : Applicative (Reader E) :=\n { pure := fun  A (a:A) e=> a;\n   liftA := @reader_liftA E }.\nInstance readerM (E : Type): Monad (Reader E) :=\n { bind := @reader_bind E }.\n(*\n(* Checking the 3 laws *)\n - (* unit_left *)\n   intros; apply Eta.\n - (* unit_right *)\n   intros; apply Eta.\n - (* associativity *)\n   reflexivity.\nDefined.\n*)\n(** ** The State monad *)\n\nRequire Import Program.\nSection State.\n(*Axiom Ext: forall A (B: A->Type) (f g: forall a, B a), (forall a, f a = g a) -> f = g.*)\n\n  Variable S : Type.\n\n  Definition State (A : Type) := S -> A * S.\n  Definition state_fmap A B (f : A -> B) (st : State A) : State B :=\n    fun  s => let (a,s) := st s in (f a,s).\n  Definition state_liftA A B (st_f : State (A -> B)) (st_a : State A) :=\n    fun  s => let (f,s) := st_f s in\n              let (a,s) := st_a s in\n              (f a,s).\n  Definition state_bind A (st_a : State A) B  (f : A -> State B) :=\n    fun  s => let (a,s) := st_a s in\n              f a s.\n\n  Definition put (x : S) : State () :=\n    fun _ => (tt,x).\n  Definition get : State S :=\n    fun x => (x,x).\n  Definition runState  {A} (op : State A) : S -> A * S := op.\n  Definition evalState {A} (op : State A) : S -> A := fst ∘ op.\n  Definition execState {A} (op : State A) : S -> S := snd ∘ op.\n\n\n\nEnd State.\nHint Unfold put get runState evalState execState state_fmap state_liftA state_bind : monad_db.\nLtac fold_evalState :=\n  match goal with\n  | [ |- context[fst (?c ?v)] ] => replace (fst (c v)) with (evalState c v)\n                                                       by reflexivity\n  end.\n\nArguments get {S}.\nArguments put {S}.\n\nInstance stateF {A} : Functor (State A) :=\n    { fmap := @state_fmap A }.\nInstance stateA {A} : Applicative (State A) :=\n    { pure := fun  A a s=> (a,s);\n      liftA := @state_liftA A }.\nInstance stateM {A} : Monad (State A) :=\n    { bind := @state_bind A }.\n\n\nInstance stateF_correct {A} : Functor_Correct (State A).\n  Proof.\n    split; intros;\n      apply functional_extensionality; intros op;\n      apply functional_extensionality; intros x;\n      simpl; unfold state_fmap.\n    - destruct (op x); reflexivity.\n    - destruct (op x); reflexivity.\n  Qed.\n\nInstance stateA_correct {A} : Applicative_Correct (State A).\n  Proof. \n    split; intros;\n      apply functional_extensionality; intros op; \n      simpl; unfold state_liftA.\n    - apply functional_extensionality; intros x.\n      destruct (op x); reflexivity.\n    - destruct (u op).\n      destruct (v a).\n      destruct (w a0).\n      reflexivity.\n    - reflexivity.\n    - destruct (u op). \n      reflexivity.\n  Qed.\n\nInstance stateM_correct {A} : Monad_Correct (State A).\n  Proof.\n    split; intros; simpl; unfold state_bind.\n    - apply functional_extensionality; intros x. \n      destruct (a x); reflexivity.\n    - reflexivity.\n    - apply functional_extensionality; intros x.\n      destruct (ma x).\n      reflexivity.\n  Qed.\n\nHint Unfold Basics.compose : monad_db.\nHint Unfold stateM : monad_db.\n\n\n", "meta": {"author": "k4rtik", "repo": "rp1", "sha": "b50914211c6aaf30170c775c0d70708249977cad", "save_path": "github-repos/coq/k4rtik-rp1", "path": "github-repos/coq/k4rtik-rp1/rp1-b50914211c6aaf30170c775c0d70708249977cad/Monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6572282582641273}}
{"text": "Require Import ClassicalChoice.\n\nSection not_wf_with_choice.\n\n Variables (A:Set)(R: A -> A -> Prop).\n Hypothesis R_not_wf : not (well_founded R).\n\n Notation \"x > y\" := (R y x).\n\n Definition strictly_decreasing (seq: nat -> A) :=\n  forall n :nat, seq n > seq (S n).\n\n\n  Remark  ex_not_acc :  exists x:A, ~ (Acc R x).\n  Proof.\n   apply not_all_ex_not;auto.\n  Qed.\n \n \n Lemma go_down : forall x, ~ Acc R x -> exists y, x > y /\\ ~ Acc R y.\n Proof.\n intros x H; change (exists z, (fun y => x > y /\\ ~ Acc R y) z).\n apply not_all_not_ex.\n intro H0;  assert (H1: forall n, x > n -> Acc R n).\n -  intros n Hn;  specialize (H0 n).\n     case (not_and_or _ _ H0).\n    +  now destruct 1.\n    +  intros;apply NNPP;auto. \n -  apply H; split;apply H1.\n Qed.\n\n\n Lemma decrease : exists f, \n       forall x, ~ Acc R x ->  ~ Acc R (f x) /\\ x > f x.\n Proof.\n case (choice  (fun x y =>  Acc R x \\/ x > y /\\ ~ Acc R y)).\n -  intros x ; case (classic (Acc R x)).\n   +  exists x;auto.\n   + intros H; case (go_down _ H).\n     intros x0 [Hx0 H'x0]; exists x0; auto. \n - intros s Hs; exists s.\n   intros x;  case (Hs x); tauto.\nQed.\n\nTheorem infinite_descent : exists s : nat -> A, strictly_decreasing  s.\nProof.\n  destruct decrease as [s Hs].\n  case ex_not_acc;intros z0 Hz.\n  pose (F := fun n:nat => Nat.iter n s z0); exists F.\n  assert (H : forall n, F n > F (S n) /\\ ~ Acc R (F n) /\\ ~ Acc R (F (S n))).\n  - induction n as [| p IHp].\n   + unfold F; case (Hs z0 Hz);  tauto.\n   +  destruct IHp as [H [H0 H1]]; split; auto.\n    simpl; now case (Hs _ H1).\n    split;auto;    now case (Hs _ H1).\n -  simpl; red;  intros n; case (H n);simpl;auto.\nQed.\n\nEnd not_wf_with_choice.\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/new_exercises/SRC/notwf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6572269327825406}}
{"text": "(** * ugregex_dec: simple decision procedure for untyped generalised regular expressions *)\n\n(** We implement a rather basic algorithm consisting in trying to\n   build a bisimulation on-the-fly, using partial derivatives.\n   \n   We prove the correctness of this algorithm, but not completeness\n   (\"it merely let you sleep better\" according to Krauss and Nipkow).\n   \n   This very simple algorithm seems to be sufficient for reasonable\n   expressions; we plan to improve it to be able to handle larger\n   ones. *)\n\nRequire Import lset kat positives sums glang boolean comparisons powerfix.\nRequire Export ugregex.\nSet Implicit Arguments.\n\n\nSection l.\nVariable Pred: nat.\nNotation Sigma := positive.\nNotation Atom := (ord (pow2 Pred)).\nNotation tt := ugregex_tt. \nNotation ugregex := (ugregex_monoid_ops Pred tt tt).\nNotation uglang := (glang_kat_ops Pred Sigma traces_tt traces_tt).\nNotation lang := (@lang Pred).\n\nLtac fold_ugregex_type := change (@ugregex.ugregex Pred) with (@car ugregex) in *.\nLtac fold_ugregex := ra_fold ugregex_monoid_ops tt; fold_ugregex_type.\n\n(** * Partial derivatives *)\n\n(** reversed product *)\nNotation tod e := (fun f => u_dot f e) (only parsing).\n\n(** [pderiv a i e] returns the set of partial derivatives of [e] along\n   transition [(a,i)] (since we work with KAT regular expressions,\n   labels are composed of an atom together with a letter) *)\nFixpoint pderiv a i (e: ugregex): list ugregex :=\n  match e with\n    | u_prd _ => []\n    | u_var _ j => if eqb_pos i j then [u_one _] else []\n    | u_pls e f => union (pderiv a i e) (pderiv a i f)\n    | u_dot e f => \n        if epsilon a e then union (map (tod f) (pderiv a i e)) (pderiv a i f)\n        else map (tod f) (pderiv a i e)\n    | u_itr e => map (tod (u_str e)) (pderiv a i e)\n  end.\n\n(** [epsilon] was defined in [ugregex], \n   we now to extend both notions to sets of expressions, homomorphically: *)\n\nDefinition epsilon' a (l: list ugregex): bool :=\n  fold_right (fun e b => b ||| epsilon a e) false l.\n\nDefinition pderiv' a i (l: list ugregex): list ugregex :=\n  fold_right (fun e => union (pderiv a i e)) [] l.\n\n\n(** specification of [epsilon'] *)\nLemma epsilon'_eq a l: epsilon a (sup id l) ≡ epsilon' a l.\nProof.\n  induction l. reflexivity. simpl.\n  rewrite <- IHl. unfold id. \n  rewrite <-2Bool.orb_lazy_alt. apply Bool.orb_comm.\nQed.\n\n(** correctness of partial derivatives *)\nLemma deriv_eq a i e: deriv a i e ≡ sup id (pderiv (set.mem a) i e).\nProof.\n  induction e; simpl; fold_ugregex.\n   case eqb_pos. 2: reflexivity. now rewrite sup_singleton. \n   reflexivity.\n   rewrite union_app, sup_app. now apply cup_weq.\n   assert (H: deriv a i e1 ⋅ e2 ≡ sup id (map (tod e2) (pderiv (set.mem a) i e1))).\n    rewrite sup_map. setoid_rewrite <-(dotsumx (X:=ugregex_monoid_ops _)).\n    now apply dot_weq.\n   case epsilon.\n    rewrite union_app, sup_app.\n    setoid_rewrite dot1x. now apply cup_weq.\n    setoid_rewrite dot0x. now rewrite cupxb.\n   rewrite sup_map. setoid_rewrite <-(dotsumx (X:=ugregex_monoid_ops _)).\n    now apply dot_weq.\nQed.\n\nLemma deriv'_eq a i l: deriv a i (sup id l) ≡ sup id (pderiv' (set.mem a) i l).\nProof.\n  induction l. reflexivity. simpl (sup _ _).\n  rewrite union_app, sup_app.\n  apply cup_weq. apply deriv_eq. assumption.\nQed.\n\n(** Kleene variables of an expression *)\nFixpoint vars (e: ugregex): list Sigma :=\n  match e with\n    | u_prd _ => []\n    | u_var _ i => [i]\n    | u_pls e f | u_dot e f => union (vars e) (vars f)\n    | u_itr e => vars e\n  end.\n\n(** partial derivatives do not increase the set of Kleene variables *)\nLemma deriv_vars a i (e: ugregex): \\sup_(x\\in pderiv a i e) vars x ≦ vars e. \nProof.\n  induction e; simpl pderiv; simpl vars. \n   case eqb_pos; apply leq_bx. \n   apply leq_bx. \n   rewrite 2union_app, sup_app. now apply cup_leq.\n   setoid_rewrite union_app at 2.\n   assert (H: \\sup_(x\\in map (tod e2) (pderiv a i e1)) vars x ≦ vars e1 ++ vars e2).\n    rewrite sup_map. simpl vars. setoid_rewrite union_app. rewrite supcup. \n    apply cup_leq. assumption. now apply leq_supx.\n   case epsilon. rewrite union_app, sup_app, H. hlattice. assumption. \n   rewrite sup_map. simpl vars. setoid_rewrite union_app. rewrite supcup. \n    apply leq_cupx. assumption. now apply leq_supx.\nQed.\n \nLemma deriv'_vars a i l: \\sup_(x\\in pderiv' a i l) vars x ≦ sup vars l.\nProof.\n  induction l. reflexivity. setoid_rewrite union_app. rewrite sup_app. \n  apply cup_leq. apply deriv_vars. assumption.\nQed.\n\n\n(** deriving an expression w.r.t. a letter it does not contain necessarily gives [0] *)\nLemma deriv_out a i e I: vars e ≦ I -> ~In i I -> deriv a i e ≡ 0. \nProof.\n  intros He Hi. induction e; simpl deriv; simpl vars in He; fold_ugregex. \n   case eqb_spec. 2: reflexivity. intros <-. apply Hi in He as []. now left. \n   reflexivity. \n   rewrite union_app in He. \n    rewrite IHe1, IHe2 by (rewrite <-He; lattice). apply cupI. \n   rewrite union_app in He. \n    rewrite IHe1, IHe2 by (rewrite <-He; lattice). rewrite dot0x, dotx0. apply cupI. \n   rewrite IHe by assumption. apply dot0x. \nQed.\n\n\n(** we need binary relations on sets of expressions, we represent them\n   as lists of pairs (this could easily be optimised) *)\nDefinition rel_mem (p: list ugregex * list ugregex) := existsb (eqb p).\nNotation rel_insert p rel := (p::rel).\nNotation rel_empty := [].\n(* OPT *)\n(* Definition rel_mem := trees.mem (pair_compare (list_compare compare)).  *)\n(* Definition rel_insert := trees.insert (pair_compare (list_compare compare)).  *)\n(* Notation rel_empty := (@trees.L _) *)\n\nLemma rel_mem_spec p rel: reflect (In p rel) (rel_mem p rel).\nProof.\n  induction rel. constructor. tauto.\n  simpl rel_mem. case eqb_spec. \n  intros <-. constructor. now left.\n  case IHrel; constructor. now right. intros [?|?]; congruence.\nQed.\n\n\n(** * Main loop for the on-the-fly bisimulation algorithm *)\n\n(** [epsilon'] and [deriv'] provide us with a (generalised) DFA whose\n   states are sets of generalised expressions ([list ugregex]). We\n   simply try compute bisimulations in this DFA. *)\n\nSection a.\n\n(** we assume a set of Kleene variable, and a set of atoms; the\n   following algorithm tries to compute bisimulations w.r.t. those\n   sets. *)\nVariable I: list positive.\nVariable A: list (ord Pred -> bool).\n\nDefinition obind X Y (f: X -> option Y) (x: option X): option Y := \n  match x with Some x => f x | _ => None end.\n\nFixpoint ofold X Y (f: X -> Y -> option Y) (l: list X) (y: Y): option Y :=\n  match l with\n    | [] => Some y\n    | x::q => obind (f x) (ofold f q y)\n  end.\n\n(** [loop_aux e f a todo] checks the accepting status of [e] and [f] along [a], \n   - if a mismatch is found, we can stop (a counter example has bee found)\n   - otherwise, it inserts all derivatives of the pair [(e,f)] along [{a}⋅I] into [todo] *)\nDefinition loop_aux e f := \n  fun a todo => \n    if eqb_bool (epsilon' a e) (epsilon' a f) \n    then Some (fold_right (fun i => cons (pderiv' a i e, pderiv' a i f)) todo I)\n    else None.\n\n(** [ofold (loop_aux e f) A todo] does the same, for all [a\\in A] *)\n\n(** [loop n rel todo] is the main loop of the algorithm:\n   it tries to prove that all pairs in [todo] are bisimilar, assuming\n   that those in [rel] are bisimilar.\n   - if a pair of [todo] was already in [rel], it can be skipped;\n   - otherwise, its accepting status is checked, all derivatives are\n     inserted in [todo], and the pair is added to [rel]\n   The number of iterations is bounded by [2^n], using the [powerfix] operator. *)\nDefinition loop n := powerfix n (fun loop rel todo =>\n  match todo with\n    | [] => Some true\n    | (e,f)::todo => \n      if rel_mem (e,f) rel then loop rel todo else \n        match ofold (loop_aux e f) A todo with\n          | Some todo => loop (rel_insert (e,f) rel) todo\n          | None => Some false\n        end\n    end\n) (fun _ _ => None).\n\n\n\n\n(** * Correctness of the main loop *)\n\n(** [prog] is a predicate on binary relations:\n\n   [prog rel (rel++todo)] is the invariant of the main loop *)\n\nDefinition prog R S :=\n  forall e f, In (e,f) R -> sup vars (e++f) ≦ I /\\\n    forall a, In a A -> epsilon' a e = epsilon' a f /\\ \n      forall i, In i I -> In (pderiv' a i e, pderiv' a i f) S.\n\nLemma prog_cup_x R R' S: prog R S -> prog R' S -> prog (R++R') S.\nProof. intros H H' e f Hef. apply in_app_iff in Hef as [?|?]. now apply H. now apply H'. Qed.\n\nLemma prog_x_leq R S S': prog R S -> S ≦ S' -> prog R S'.\nProof. \n  intros H H' e f Hef. apply H in Hef as [? Hef]. \n  split. assumption. split. now apply Hef. intros. now apply H', Hef. \nQed.\n\nDefinition below_I todo := forall e f, In (e,f) todo -> sup vars (e++f) ≦ I.\n\n(** specification of the inner loop *)\n\nLemma loop_aux_spec e f a todo todo': \n  below_I ((e,f)::todo) ->\n  loop_aux e f a todo = Some todo' -> \n  epsilon' a e = epsilon' a f /\\\n  todo ≦ todo' /\\\n  below_I todo' /\\\n  forall i, In i I -> In (pderiv' a i e, pderiv' a i f) todo'.\nProof.\n  unfold loop_aux. case eqb_bool_spec. 2: discriminate. intros Heps Hvars E. \n  split. assumption. injection E. clear E Heps. revert todo'. \n  induction I as [|i J IH]; simpl fold_right; intro todo'. \n   intros <-. split. reflexivity. split. intros ? ? ?. apply Hvars; now right. intros _ []. \n   intro E. destruct todo' as [|p todo']. discriminate. \n   injection E. intros H <-. clear E. apply IH in H as [H1 [H2 H3]]. clear IH. \n   split. fold_cons. rewrite <- H1. lattice.\n   split. intros ? ? [E|H]. \n    injection E; intros <- <-. rewrite sup_app, 2deriv'_vars, <-sup_app. apply Hvars. now left.\n    now apply H2. \n   intros b [<-|Hb]. now left. right. now apply H3. \nQed.\n\nLemma fold_loop_aux_spec e f todo: forall todo',\n  below_I ((e,f)::todo) ->\n  ofold (loop_aux e f) A todo = Some todo' -> \n  todo ≦ todo' /\\\n  below_I todo' /\\\n  forall a, In a A -> epsilon' a e = epsilon' a f /\\\n  forall i, In i I -> In (pderiv' a i e, pderiv' a i f) todo'.\nProof.\n  induction A as [|b B IH]; simpl ofold; intros todo'.\n   intros Hvars H. injection H. intros <-. split. reflexivity. \n   split. intros ? ? ?. apply Hvars. now right. intros _ []. \n  unfold obind. fold_ugregex_type. case_eq (ofold (X:=ord Pred -> bool) (loop_aux e f) B todo). \n   2: discriminate. \n  intros todo'' Htodo'' Hvars Htodo'.\n  apply IH in Htodo'' as [Htodo''_leq [Hvars' Htodo'']]. 2: assumption. clear IH. \n  apply loop_aux_spec in Htodo' as (Heps&Htodo'_leq&Hvars''&Htodo'). \n  split. etransitivity; eassumption. \n  split. assumption. \n  intros a [<-|Ha]. now split. \n  apply Htodo'' in Ha as [Haeps Ha]. split. assumption. \n  intros. now apply Htodo'_leq, Ha. \n  intros ? ? [E|?]. injection E; intros <- <-. apply Hvars; now left. now apply Hvars'.\nQed.\n\nLemma In_cons X (a: X) l: In a l -> [a]++l ≦ l. \nProof. now intros ? ? [<-|?]. Qed.\n\n(** specification of the outer loop *)\n\nLemma prog_loop n: forall rel todo,\n  loop n rel todo = Some true ->\n  prog rel (rel++todo) -> \n  below_I todo ->\n  exists rel', rel++todo ≦ rel' /\\ prog rel' rel'.\nProof.\n  (* TODO: use powerfix_invariant *)\n  unfold loop. rewrite powerfix_linearfix. generalize (pow2 n). clear n. intro n.\n  induction n; intros rel todo Hloop Hrel Hvars. discriminate. \n  simpl in Hloop. destruct todo as [|[e f] todo]. \n   exists rel. split. now rewrite <- app_nil_end. now rewrite <-app_nil_end in Hrel. \n   revert Hloop. case rel_mem_spec. \n   intros Hef Hloop. apply IHn in Hloop as (rel'&H1&H2).\n    eexists. split. 2: eassumption. \n     rewrite <- H1. rewrite <-(In_cons Hef) at 2. fold_cons. lattice. \n    eapply prog_x_leq. apply Hrel. \n     rewrite <-(In_cons Hef) at 2. fold_cons. lattice. \n    intros ? ? ?. apply Hvars. now right. \n   intros _. fold_ugregex_type. case_eq (ofold (X:=ord Pred -> bool) (loop_aux e f) A todo). \n    2: discriminate. \n   intros todo' Htodo' Hloop. \n   apply fold_loop_aux_spec in Htodo' as [Htodo' [Hvars' Hef]]. 2: assumption.\n   destruct (IHn _ _ Hloop) as (rel'&Hrel'&Hrel''). 2: assumption. \n   clear - Hef Hvars Hvars' Hrel Htodo'. \n   apply (@prog_cup_x [_]). eapply prog_x_leq. \n    intros ? ? [E|[]]. injection E; intros <- <-; clear E. \n    split. apply Hvars. now left. apply Hef. lattice.\n   eapply prog_x_leq. apply Hrel. rewrite <- Htodo'. fold_cons. lattice. \n   eexists. split. 2: eassumption. rewrite <-Hrel', <-Htodo'. fold_cons. lattice.\nQed.\n\nEnd a.\n\nExisting Instance lang'_weq.\n\n(** correctness of the bisimulation proof method, at the abstract level *)\n\nLemma prog_correct I l rel: \n  (forall a, In (set.mem a) l) ->\n  prog I l rel rel -> below_I I rel -> \n  forall e f, In (e,f) rel -> sup lang e ≡ sup lang f.\nProof.\n  intros Hl Hrel Hvars e f Hef. \n  rewrite <-2lang_sup, 2lang_lang'. \n  intro w. revert e f Hef. induction w; simpl lang'; intros e f Hef. \n  - apply Hrel in Hef as [_ Hef]. \n    rewrite 2epsilon'_eq. destruct (Hef _ (Hl a)) as [-> _]. reflexivity. \n  - destruct (fun H => In_dec H i I) as [Hi|Hi]. decide equality.\n    etransitivity. apply lang'_weq. apply deriv'_eq. \n    etransitivity. 2: apply lang'_weq; symmetry; apply deriv'_eq. \n    apply IHw. apply Hrel. assumption. apply Hl. assumption. \n    clear IHw. revert w. apply lang'_weq. rewrite 2deriv_sup.\n    rewrite 2sup_b. reflexivity. \n     intros f' Hf. eapply deriv_out. 2: eassumption. \n      etransitivity. 2: apply Hvars. 2: apply Hef. apply leq_xsup. apply in_app_iff. now right. \n     intros e' He. eapply deriv_out. 2: eassumption. \n      etransitivity. 2: apply Hvars. 2: apply Hef. apply leq_xsup. apply in_app_iff. now left. \nQed.\n\n(** * Final algorithm, correctness *)\n\n(** the final algorithm is obtained by callign the main loop with\n   appropriate arguments *)\n\nDefinition eqb_kat (e f: ugregex) :=\n  let atoms := map (@set.mem _) (seq _) in\n  let vars := vars (e+f) in\n    loop vars atoms 1000 rel_empty [([e],[f])%list].\n(* stated as this, the algorithm is not complete: we would need to\n   replace 1000 with the size of [e+f]... bzzz *)\n\n(** correctness of the algorithm *)\n\nTheorem eqb_kat_correct e f: eqb_kat e f = Some true -> e ≡ f. \nProof.\n  unfold eqb_kat. intro H. apply prog_loop in H as [rel [Hef Hrel]]. \n  2: intros _ _ []. \n  2: simpl vars; intros ? ? [E|[]]; injection E; intros <- <-; \n      rewrite union_app, sup_app, 2sup_singleton; reflexivity.\n  eapply prog_correct in Hrel. \n   2: intro; apply in_map, in_seq. \n   3: apply Hef; now left.\n  rewrite 2sup_singleton in Hrel. assumption. \n  intros ? ? ?. now apply Hrel. \nQed.\n\nEnd l. \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/ugregex_dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6572269178436998}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import String.\nRequire Import List.\nImport ListNotations.\n\nRequire Import msl.eq_dec.\nImport Relations.\n\nDefinition table A B := list (A*B).\n\nFixpoint table_get {A B}{H: EqDec A} (rho: table A B) (x: A) : option B :=\n  match rho with\n  | (y,v)::ys => if eq_dec x y then Some v else table_get ys x\n  | nil => None\n end.\n\nDefinition table_set {A B}{H: EqDec A} (x: A) (v: B) (rho: table A B) : table A B := (x,v)::rho.\n\nLemma table_gss {A B}{H: EqDec A}: forall rho x (v : B), table_get (table_set x v rho) x = Some v.\nProof.\nintros.\nsimpl. destruct (eq_dec x x); auto. contradiction n; auto.\nQed.\n\nLemma table_gso {A B}{H: EqDec A}: forall rho x y (v : B), x<>y -> table_get (table_set x v rho) y = table_get rho y.\nProof.\nintros.\nsimpl. destruct (eq_dec y x); auto.  contradiction H0; auto.\nQed.\n\n\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/table.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6571970544683827}}
{"text": "Require Export Program Permutation.\n\nUnset Implicit Arguments.\n\n(* Enumerating the items of a Bag resulting from inserting\n   an item [inserted] into a bag [container] is a permutation\n   of adding [inserted] to the original set of elements.\n   *)\nDefinition BagInsertEnumerate\n           {TContainer TItem: Type}\n           (RepInv : TContainer -> Prop)\n           (benumerate : TContainer -> list TItem)\n           (binsert    : TContainer -> TItem -> TContainer) :=\n  forall inserted container\n         (containerCorrect : RepInv container),\n    Permutation\n      (benumerate (binsert container inserted))\n      (inserted :: benumerate container).\n\n(* The enumeration of an empty bag [bempty] is an empty list. *)\nDefinition BagEnumerateEmpty\n           {TContainer TItem: Type}\n           (benumerate : TContainer -> list TItem)\n           (bempty     : TContainer) :=\n  forall item, ~ List.In item (benumerate bempty).\n\n(* [bfind] returns a permutation of the elements in a bag\n   [container] filtered by the match function [bfind_matcher]\n   using the specified search term [search_term]. *)\nDefinition BagFindCorrect\n           {TContainer TItem TSearchTerm: Type}\n           (RepInv : TContainer -> Prop)\n           (bfind         : TContainer -> TSearchTerm -> list TItem)\n           (bfind_matcher : TSearchTerm -> TItem -> bool)\n           (benumerate : TContainer -> list TItem) :=\n  forall container search_term\n         (containerCorrect : RepInv container),\n    Permutation\n      (List.filter (bfind_matcher search_term) (benumerate container))\n      (bfind container search_term).\n\n(* The [bstar] search term matches every item in a bag. *)\nDefinition BagFindStar\n           {TContainer TItem TSearchTerm: Type}\n           (RepInv : TContainer -> Prop)\n           (bfind : TContainer -> TSearchTerm -> list TItem)\n           (benumerate : TContainer -> list TItem)\n           (bstar : TSearchTerm) :=\n  forall container\n    (containerCorrect : RepInv container),\n      bfind container bstar = benumerate container.\n\n(* [bcount] returns the number of elements in a bag which match\n   a search term [search_term]. *)\nDefinition BagCountCorrect\n           {TContainer TItem TSearchTerm: Type}\n           (RepInv : TContainer -> Prop)\n           (bcount        : TContainer -> TSearchTerm -> nat)\n           (bfind         : TContainer -> TSearchTerm -> list TItem) :=\n  forall container search_term\n  (containerCorrect : RepInv container),\n    List.length (bfind container search_term) = (bcount container search_term).\n\n(* The elements of a bag [container] from which all elements matching\n   [search_term] have been deleted is a permutation of filtering\n   the enumeration of [container] by the negation of [search_term]. *)\nDefinition BagDeleteCorrect\n           {TContainer TItem TSearchTerm: Type}\n           (RepInv : TContainer -> Prop)\n           (bfind         : TContainer -> TSearchTerm -> list TItem)\n           (bfind_matcher : TSearchTerm -> TItem -> bool)\n           (benumerate : TContainer -> list TItem)\n           (bdelete    : TContainer -> TSearchTerm -> (list TItem) * TContainer) :=\n  forall container search_term\n         (containerCorrect : RepInv container),\n    Permutation (benumerate (snd (bdelete container search_term)))\n                (snd (List.partition (bfind_matcher search_term)\n                                     (benumerate container)))\n    /\\ Permutation (fst (bdelete container search_term))\n                   (fst (List.partition (bfind_matcher search_term)\n                                     (benumerate container))).\n\n(* The elements of a bag [container] in which the function [f_update]\n   has been applied to all elements matching [search_term]\n   is a permutation of partitioning the list into non-matching terms\n   and matching terms and mapping [f_update] over the latter. *)\nDefinition BagUpdateCorrect\n           {TContainer TItem TSearchTerm TUpdateTerm : Type}\n           (RepInv : TContainer -> Prop)\n           (ValidUpdate : TUpdateTerm -> Prop)\n           (bfind         : TContainer -> TSearchTerm -> list TItem)\n           (bfind_matcher : TSearchTerm -> TItem -> bool)\n           (benumerate : TContainer -> list TItem)\n           (bupdate_transform : TUpdateTerm -> TItem -> TItem)\n           (bupdate    : TContainer -> TSearchTerm -> TUpdateTerm -> TContainer) :=\n  forall container search_term update_term\n         (containerCorrect : RepInv container)\n         (valid_update : ValidUpdate update_term),\n    Permutation (benumerate (bupdate container search_term update_term))\n                   ((snd (List.partition (bfind_matcher search_term)\n                                         (benumerate container)))\n                      ++ List.map (bupdate_transform update_term)\n                      (fst (List.partition (bfind_matcher search_term)\n                                           (benumerate container)))).\n\nDefinition binsert_Preserves_RepInv\n           {TContainer TItem: Type}\n           (RepInv : TContainer -> Prop)\n           (binsert    : TContainer -> TItem -> TContainer)\n    := forall container item\n              (containerCorrect : RepInv container),\n         RepInv (binsert container item).\n\nDefinition bdelete_Preserves_RepInv\n           {TContainer TItem TSearchTerm: Type}\n           (RepInv : TContainer -> Prop)\n           (bdelete    : TContainer -> TSearchTerm -> (list TItem) * TContainer)\n  := forall container search_term\n            (containerCorrect : RepInv container),\n       RepInv (snd (bdelete container search_term)).\n\nDefinition bupdate_Preserves_RepInv\n           {TContainer TSearchTerm TUpdateTerm : Type}\n           (RepInv : TContainer -> Prop)\n           (ValidUpdate       : TUpdateTerm -> Prop)\n           (bupdate    : TContainer -> TSearchTerm -> TUpdateTerm -> TContainer)\n  := forall container search_term update_term\n            (containerCorrect : RepInv container)\n            (valid_update : ValidUpdate update_term),\n       RepInv (bupdate container search_term update_term).\n\nClass Bag (BagType TItem SearchTermType UpdateTermType : Type) :=\n  {\n\n    bempty            : BagType;\n    bstar             : SearchTermType;\n    bfind_matcher     : SearchTermType -> TItem -> bool;\n    bupdate_transform : UpdateTermType -> TItem -> TItem;\n\n    benumerate : BagType -> list TItem;\n    bfind      : BagType -> SearchTermType -> list TItem;\n    binsert    : BagType -> TItem -> BagType;\n    bcount     : BagType -> SearchTermType -> nat;\n    bdelete    : BagType -> SearchTermType -> (list TItem) * BagType;\n    bupdate    : BagType -> SearchTermType -> UpdateTermType -> BagType\n  }.\n\n\nClass CorrectBag\n      {BagType TItem SearchTermType UpdateTermType : Type}\n      (RepInv            : BagType -> Prop)\n      (ValidUpdate       : UpdateTermType -> Prop)\n      (BagImplementation : Bag BagType TItem SearchTermType UpdateTermType) :=\n{\n\n  bempty_RepInv     : RepInv bempty;\n  binsert_RepInv    : binsert_Preserves_RepInv RepInv binsert;\n  bdelete_RepInv    : bdelete_Preserves_RepInv RepInv bdelete ;\n  bupdate_RepInv    : bupdate_Preserves_RepInv RepInv ValidUpdate bupdate;\n\n  bfind_star        : BagFindStar RepInv bfind benumerate bstar;\n\n  benumerate_empty  : BagEnumerateEmpty benumerate bempty;\n  binsert_enumerate : BagInsertEnumerate RepInv benumerate binsert;\n  bfind_correct     : BagFindCorrect RepInv bfind bfind_matcher benumerate;\n  bcount_correct    : BagCountCorrect RepInv bcount bfind;\n  bdelete_correct   : BagDeleteCorrect RepInv bfind bfind_matcher benumerate bdelete;\n  bupdate_correct   : BagUpdateCorrect RepInv ValidUpdate bfind bfind_matcher benumerate bupdate_transform bupdate\n}.\n\n(* [BagPlusProof] packages a container with its operations and\n   their correctness proofs. *)\nRecord BagPlusProof (TItem : Type) :=\n  { BagTypePlus : Type;\n    SearchTermTypePlus : Type;\n    UpdateTermTypePlus : Type;\n\n    RepInvPlus : BagTypePlus -> Prop;\n    ValidUpdatePlus : UpdateTermTypePlus -> Prop;\n\n    BagPlus : Bag BagTypePlus TItem SearchTermTypePlus UpdateTermTypePlus;\n    CorrectBagPlus : CorrectBag RepInvPlus ValidUpdatePlus BagPlus\n  }.\n\nArguments BagTypePlus [TItem] _.\nArguments SearchTermTypePlus [TItem] _.\nArguments UpdateTermTypePlus [TItem] _.\nArguments RepInvPlus [TItem] _ _.\nArguments ValidUpdatePlus [TItem] _ _.\nArguments BagPlus [TItem] _.\nArguments CorrectBagPlus [TItem] _.\n\nInstance BagPlusProofAsBag {TItem}\n         (bag : BagPlusProof TItem)\n: Bag _ _ _ _ := BagPlus bag.\n\nInstance BagPlusProofAsCorrectBag {TItem}\n         (bag : BagPlusProof TItem)\n: CorrectBag _ _ _ := CorrectBagPlus bag.\n\n(* We can bundle a container and its invariant if we so desire. *)\nDefinition WFBagPlusType {TItem} (Index : BagPlusProof TItem)\n  := sigT (RepInvPlus Index).\n\nInstance WFBagPlusTypeAsBag {TItem}\n         (Index : BagPlusProof TItem)\n: Bag (WFBagPlusType Index) TItem (SearchTermTypePlus Index)\n      (sigT (ValidUpdatePlus Index)).\nProof.\n  destruct Index as [? ? ? ? ? BagPlus' CorrectBagPlus'];\n  destruct BagPlus'; destruct CorrectBagPlus'; simpl in *.\n  econstructor 1; simpl; try solve [eassumption].\n  (* bempty *)\n  econstructor; eauto.\n  (* bupdate_transform *)\n  intro; apply bupdate_transform0; apply X.\n  (* benumerate *)\n  intros; apply benumerate0; apply X.\n  (* bfind *)\n  intros; destruct X; apply (bfind0 x X0).\n  (* binsert *)\n  intros; destruct X; econstructor; eapply binsert_RepInv0; apply r.\n  (* bcount *)\n  intros; destruct X; eapply bcount0; [apply x | apply X0 ].\n  (* bdelete *)\n  intros x search_term; constructor.\n  - eapply (fst (bdelete0 (projT1 x) search_term)).\n  - econstructor; eapply bdelete_RepInv0; apply (projT2 x).\n  (* bupdate *)\n  - intros x search_term update_term; destruct x; destruct update_term;\n    econstructor.\n    eapply bupdate_RepInv0.\n    apply r.\n    apply v.\n    Grab Existential Variables.\n    simpl; apply search_term.\n    simpl; apply search_term.\n    apply X0.\nDefined.\n\nInstance WFBagPlusTypeAsCorrectBag {TItem}\n         (Index : BagPlusProof TItem)\n: CorrectBag (fun _ => True) (fun _ => True) (WFBagPlusTypeAsBag Index).\nProof.\n  destruct Index as [? ? ? ? ? BagPlus' CorrectBagPlus'];\n  destruct BagPlus'; destruct CorrectBagPlus'; simpl in *.\n  constructor; simpl; eauto;\n  cbv delta [binsert_Preserves_RepInv\n               bupdate_Preserves_RepInv\n               bdelete_Preserves_RepInv\n               BagInsertEnumerate\n               BagEnumerateEmpty\n               BagFindStar\n               BagFindCorrect\n               BagCountCorrect\n               BagDeleteCorrect\n               BagUpdateCorrect]; simpl; eauto;\n  try (solve [intros; destruct container; eauto]).\n  (* bupdate_correct *)\n  destruct container; simpl; intros.\n  destruct update_term; eauto.\nQed.\n", "meta": {"author": "JasonGross", "repo": "adt-synthesis", "sha": "30a5cd361af029f42864e103a5a604ffa9ee07a7", "save_path": "github-repos/coq/JasonGross-adt-synthesis", "path": "github-repos/coq/JasonGross-adt-synthesis/adt-synthesis-30a5cd361af029f42864e103a5a604ffa9ee07a7/src/QueryStructure/Refinements/Bags/BagsInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6571970477669624}}
{"text": "Require Export A_14_1.\n\nModule A14_2.\n\n(* 定义：函数f在x0处的泰勒公式余项 *)\nDefinition TaylorRn f n x x0 :=\n  f[x] - (Σ {` λ k v, v = (dN f k)[x0] /\n      (INR (k!)) * (x - x0)^^k `} n).\n\nTheorem Theorem14_11 : ∀ f r x x0,\n  0 < r -> -r < x-x0 < r\n  -> limit_seq {` λ n s, s = TaylorRn f n x x0 `} 0\n  -> limit_seq {` λ n s, s = Σ {` λ k v, v = (dN f k)[x0] /\n      (INR (k!)) * (x - x0)^^k `} n `} f[x].\nProof.\n  intros f r x x0 H0 H1 H2.\n  split; try apply FunIsSeq.\n  intros ε H3. apply H2 in H3 as H4.\n  destruct H4 as [N H4].\n  exists N. intros n H5. apply H4 in H5.\n  rewrite FunValueR in H5.\n  rewrite FunValueR. unfold TaylorRn in H5.\n  rewrite Rminus_0_r in H5.\n  rewrite Abs_eq_neg. rewrite Ropp_minus_distr.\n  assumption.\nQed.\n\nEnd A14_2.\n\nExport A14_2.", "meta": {"author": "zhaobaoq", "repo": "MathAnalysis", "sha": "f51d41fc9ddfcbe4ac2560e4bda43540b1be2f6a", "save_path": "github-repos/coq/zhaobaoq-MathAnalysis", "path": "github-repos/coq/zhaobaoq-MathAnalysis/MathAnalysis-f51d41fc9ddfcbe4ac2560e4bda43540b1be2f6a/A_14_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6571970421894321}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import VST.msl.Coqlib2.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Import VST.floyd.sublist.\n\n(* from verif_revarray.v *)\n\nDefinition flip_between {A} lo hi (contents: list A) :=\n  firstn (Z.to_nat lo) (rev contents)\n  ++ firstn (Z.to_nat (hi-lo)) (skipn (Z.to_nat lo) contents)\n  ++ skipn (Z.to_nat hi) (rev contents).\n\nLemma flip_fact_0: forall {A} size (contents: list A),\n  Zlength contents = size ->\n  contents = flip_between 0 (size - 0) contents.\nProof.\n  intros.\n  assert (length contents = Z.to_nat size).\n    apply Nat2Z.inj. rewrite <- Zlength_correct, Z2Nat.id; auto.\n    subst; rewrite Zlength_correct; omega.\n  unfold flip_between.\n  rewrite !Z.sub_0_r. change (Z.to_nat 0) with O; simpl. rewrite <- H0.\n  rewrite skipn_short.\n  rewrite <- app_nil_end.\n  rewrite firstn_exact_length. auto.\n  rewrite rev_length. omega.\nQed.\n\nLemma flip_fact_1: forall A size (contents: list A) j,\n  Zlength contents = size ->\n  0 <= j ->\n  size - j - 1 <= j <= size - j ->\n  flip_between j (size - j) contents = rev contents.\nProof.\n  intros.\n  assert (length contents = Z.to_nat size).\n    apply Nat2Z.inj. rewrite <- Zlength_correct, Z2Nat.id; auto.\n    subst; rewrite Zlength_correct; omega.\n  unfold flip_between.\n  symmetry.\n  rewrite <- (firstn_skipn (Z.to_nat j)) at 1.\n  f_equal.\n  replace (Z.to_nat (size-j)) with (Z.to_nat j + Z.to_nat (size-j-j))%nat\n    by (rewrite <- Z2Nat.inj_add by omega; f_equal; omega).\n  rewrite <- skipn_skipn.\n  rewrite <- (firstn_skipn (Z.to_nat (size-j-j)) (skipn (Z.to_nat j) (rev contents))) at 1.\n  f_equal.\n  rewrite firstn_skipn_rev.\nFocus 2.\nrewrite H2.\napply Nat2Z.inj_le.\nrewrite Nat2Z.inj_add by omega.\nrewrite !Z2Nat.id by omega.\nomega.\n  rewrite len_le_1_rev.\n  f_equal. f_equal. f_equal.\n  rewrite <- Z2Nat.inj_add by omega. rewrite H2.\n  rewrite <- Z2Nat.inj_sub by omega. f_equal; omega.\n  rewrite firstn_length, min_l.\n  change 1%nat with (Z.to_nat 1). apply Z2Nat.inj_le; omega.\n  rewrite skipn_length.  rewrite H2.\n  rewrite <- Z2Nat.inj_sub by omega. apply Z2Nat.inj_le; omega.\nQed.\n\nLemma Zlength_flip_between:\n forall A i j (al: list A),\n 0 <= i  -> i<=j -> j <= Zlength al ->\n Zlength (flip_between i j al) = Zlength al.\nProof.\nintros.\nunfold flip_between.\nrewrite !Zlength_app, !Zlength_firstn, !Zlength_skipn, !Zlength_rev.\nforget (Zlength al) as n.\nrewrite (Z.max_comm 0 i).\nrewrite (Z.max_l i 0) by omega.\nrewrite (Z.max_comm 0 j).\nrewrite (Z.max_l j 0) by omega.\nrewrite (Z.max_comm 0 (j-i)).\nrewrite (Z.max_l (j-i) 0) by omega.\nrewrite (Z.max_comm 0 (n-i)).\nrewrite (Z.max_l (n-i) 0) by omega.\nrewrite Z.max_r by omega.\nrewrite (Z.min_l i n) by omega.\nrewrite Z.min_l by omega.\nomega.\nQed.\n\nLemma flip_fact_3:\n forall A (al: list A) (d: A) j size,\n  size = Zlength al ->\n  0 <= j < size - j - 1 ->\nfirstn (Z.to_nat j)\n  (firstn (Z.to_nat (size - j - 1)) (flip_between j (size - j) al) ++\n   firstn (Z.to_nat 1) (skipn (Z.to_nat j) (flip_between j (size - j) al)) ++\n   skipn (Z.to_nat (size - j - 1 + 1)) (flip_between j (size - j) al)) ++\nfirstn (Z.to_nat 1)\n  (skipn (Z.to_nat (size - j - 1)) al) ++\nskipn (Z.to_nat (j + 1))\n  (firstn (Z.to_nat (size - j - 1)) (flip_between j (size - j) al) ++\n   firstn (Z.to_nat 1) (skipn (Z.to_nat j) (flip_between j (size - j) al)) ++\n   skipn (Z.to_nat (size - j - 1 + 1)) (flip_between j (size - j) al)) =\nflip_between (Z.succ j) (size - Z.succ j) al.\nProof.\nintros.\nassert (Zlength (rev al) = size) by (rewrite Zlength_rev; omega).\nunfold flip_between.\nrewrite Zfirstn_app1.\nFocus 2. {\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite !Zlength_app.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite !Zlength_skipn.\nrewrite (Z.max_r 0 j) by omega.\nrewrite (Z.max_r 0 (size-j)) by omega.\nrewrite Z.max_r by omega.\nrewrite Z.max_r by omega.\nrewrite (Z.min_l j) by omega.\nrewrite (Z.min_l (size-j-j)) by omega.\nrewrite Z.min_l by omega.\nomega.\n} Unfocus.\nrewrite Zfirstn_app2\n by (rewrite Zlength_firstn, Z.max_r by omega;\n      rewrite Z.min_l by omega; omega).\nrewrite Zfirstn_app1\n by (rewrite Zlength_firstn, Z.max_r by omega;\n      rewrite Z.min_l by omega; omega).\nrewrite Zfirstn_firstn by omega.\nrewrite Zskipn_app1.\nFocus 2. {\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_rev.\nrewrite !Zlength_app.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Z.min_l by omega.\nrewrite Zlength_firstn.\nrewrite (Z.min_l j (Zlength al)) by omega.\nrewrite Z.max_r by omega.\nrewrite Zlength_app.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_skipn.\nrewrite (Z.max_r 0 j)  by omega.\nrewrite (Z.max_r 0 ) by omega.\nrewrite (Z.min_l  (size-j-j)) by omega.\nrewrite Zlength_skipn.\nrewrite (Z.max_r 0 (size-j)) by omega.\nrewrite Z.max_r by omega.\nrewrite Z.min_l by omega.\nomega.\n} Unfocus.\nrewrite Zskipn_app2\n by (rewrite Zlength_firstn, Z.max_r by omega;\n       rewrite Z.min_l by omega; omega).\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Z.min_l by omega.\nrewrite Zfirstn_app1.\nFocus 2. {\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_skipn, (Z.max_r 0 j) by omega.\nrewrite Z.max_r by omega.\nrewrite Z.min_l by omega. omega.\n} Unfocus.\nrewrite Zfirstn_firstn by omega.\nrewrite Zskipn_app2\n by (rewrite Zlength_firstn, Z.max_r by omega;\n       rewrite Z.min_l by omega; omega).\nrewrite Zskipn_app1.\nFocus 2. {\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Z.min_l by omega.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_skipn, (Z.max_r 0 j) by omega.\nrewrite Z.max_r by omega.\nrewrite Z.min_l by omega. omega.\n} Unfocus.\nrewrite Zfirstn_app1.\nFocus 2. {\nrewrite !Zlength_skipn, !Zlength_firstn.\nrewrite (Z.max_r 0 j) by omega.\nrewrite (Z.min_l j) by omega.\nrewrite Zlength_skipn.\nrewrite (Z.max_r 0 j) by omega.\nrewrite (Z.max_r 0 (Zlength al - j)) by omega.\nrewrite (Z.max_l 0 (j-j)) by omega.\nrewrite (Z.max_r 0 (size-j-j)) by omega.\nrewrite Z.min_l by omega.\nrewrite Z.max_r by omega.\nomega.\n} Unfocus.\nrewrite Zskipn_app2.\nFocus 2. {\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite (Z.min_l j) by omega.\nomega.\n} Unfocus.\nrewrite Zskipn_app2.\nFocus 2. {\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite (Z.min_l j) by omega.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_skipn, (Z.max_r 0 j) by omega.\nrewrite Z.max_r by omega.\nrewrite Z.min_l by omega.\nomega.\n} Unfocus.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_firstn, Z.max_r by omega.\nrewrite Zlength_skipn, (Z.max_r 0 j) by omega.\nrewrite Z.max_r by omega.\nrewrite Z.min_l by omega.\nrewrite Z.min_l by omega.\nrewrite Zskipn_skipn by omega.\nrewrite !Zskipn_firstn by omega.\nrewrite !Z.sub_diag.\nrewrite Z.sub_0_r.\nrewrite !Zskipn_skipn by omega.\nrewrite Zfirstn_firstn by omega.\nrewrite <- app_ass.\nf_equal.\nrewrite <- (firstn_skipn (Z.to_nat j) (rev al)) at 2.\nrewrite Zfirstn_app2\n  by (rewrite Zlength_firstn, Z.max_r by omega;\n        rewrite Z.min_l by omega; omega).\nrewrite Zlength_firstn, Z.max_r by omega;\nrewrite Z.min_l by omega.\nreplace (Z.succ j - j) with 1 by omega.\nf_equal.\nrewrite app_nil_end.\nrewrite app_nil_end at 1.\nrewrite <- Znth_cons with (d0:=d) by omega.\nrewrite <- Znth_cons with (d0:=d) by omega.\nf_equal.\nrewrite Znth_rev by omega.\nf_equal. omega.\nreplace (size - j - 1 - j - (j + 1 - j))\n  with (size- Z.succ j- Z.succ j) by omega.\nreplace (j+(j+1-j)) with (j+1) by omega.\nf_equal.\nrewrite Z.add_0_r.\nrewrite <- (firstn_skipn (Z.to_nat 1) (skipn (Z.to_nat (size- Z.succ j)) (rev al))).\nrewrite Zskipn_skipn by omega.\nf_equal.\nrewrite app_nil_end.\nrewrite app_nil_end at 1.\nrewrite <- Znth_cons with (d0:=d) by omega.\nrewrite <- Znth_cons with (d0:=d) by omega.\nf_equal.\nrewrite Znth_rev by omega.\nf_equal.\nomega.\nf_equal.\nf_equal.\nomega.\nQed.\n\nLemma flip_fact_2:\n  forall {A} (al: list A) size j d,\n Zlength al = size ->\n  j < size - j - 1 ->\n   0 <= j ->\n  Znth (size - j - 1) al d =\n  Znth (size - j - 1) (flip_between j (size - j) al) d.\nProof.\nintros.\nunfold flip_between.\nrewrite app_Znth2\n by (rewrite Zlength_firstn, Z.max_r by omega;\n      rewrite Zlength_rev, Z.min_l by omega; omega).\nrewrite Zlength_firstn, Z.max_r by omega;\nrewrite Zlength_rev, Z.min_l by omega.\nrewrite app_Znth1.\nFocus 2. {\nrewrite Zlength_firstn, Z.max_r by omega;\nrewrite Zlength_skipn by omega.\nrewrite (Z.max_r 0 j) by omega.\nrewrite Z.max_r by omega.\nrewrite Z.min_l by omega.\nomega. } Unfocus.\nrewrite Znth_firstn by omega.\nrewrite Znth_skipn by omega.\nf_equal; omega.\nQed.\n\nRequire Import VST.msl.shares.\nRequire Import VST.veric.shares.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.common.Values.\nRequire Import compcert.cfrontend.Ctypes.\nRequire Import VST.veric.expr.\n\nLemma verif_sumarray_example1:\nforall (sh : share) (contents : list int) (size : Z) (a : val),\nreadable_share sh ->\n0 <= size <= Int.max_signed ->\nis_pointer_or_null a ->\n@Zlength val (@map int val Vint contents) = size ->\n0 <= 0 /\\\n(0 <= size /\\ True) /\\\na = a /\\\nVint (Int.repr 0) = Vint (Int.repr 0) /\\\nVint (Int.repr size) = Vint (Int.repr size) /\\\nVint Int.zero = Vint (Int.repr 0) /\\ True.\nAbort.\n\nLemma verif_sumarray_example2:\nforall (sh : share) (contents : list int) (size : Z) (a : val),\nforall (sh : share) (contents : list int) (size a1 : Z) (a : val),\nreadable_share sh ->\n0 <= size <= Int.max_signed ->\na1 < size ->\n0 <= a1 <= size ->\nis_pointer_or_null a ->\nZlength (map Vint contents) = size ->\nis_int I32 Signed (Znth a1 (map Vint contents) Vundef).\nAbort.\n\nRequire Import compcert.exportclight.Clightdefs.\n\nRequire Import VST.veric.Clight_lemmas.  (* just for nullval? *)\n\nLemma verif_reverse_example1:\nforall (sum_int: list int -> int) (sh : share) (contents cts : list int) (t0 t_old t : val) (h : int),\nreadable_share sh ->\nisptr t0 ->\nt0 = t_old ->\nis_pointer_or_null t ->\nis_pointer_or_null t ->\n(t = nullval <-> map Vint cts = []) ->\nt = t /\\\nVint (Int.sub (sum_int contents) (sum_int cts)) =\nVint (Int.add (Int.sub (sum_int contents) (Int.add h (sum_int cts))) h) /\\\nTrue.\nAbort.\n\nLemma verif_reverse_example2:\nforall (sh : share) (contents cts1 : list val) (w h : val) (r : list val)\n  (w_ t_ : val),\nwritable_share sh ->\ncontents = rev cts1 ++ h :: r ->\nis_pointer_or_null t_ ->\nis_pointer_or_null w_ ->\nisptr w_ ->\nis_pointer_or_null t_ ->\nis_pointer_or_null t_ ->\n(t_ = nullval <-> r = []) ->\nis_pointer_or_null w ->\n(w = nullval <-> cts1 = []) ->\ncontents = (rev cts1 ++ [h]) ++ r /\\ True /\\ w_ = w_ /\\ t_ = t_ /\\ True.\nAbort.\n\n\n\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/floyd/smt_test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197768, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6571970351853073}}
{"text": "Require Import Nat Arith.\n\nFixpoint mult (mult_arg0 : nat) (mult_arg1 : nat) : nat\n           := match mult_arg0, mult_arg1 with\n              | n, m => if > m 0 then plus n (mult n (minus m 1)) else 0\n              end.\n\nTheorem theorem0 : forall (x : nat) (y : nat), eq (minus (mult x y) y) (mult (minus x 1) y).\nProof.\nAdmitted.\n\nTheorem theorem1 : forall (n : nat) (m : nat), eq (mult n m) (mult m n).\nProof.\nAdmitted.\n\n", "meta": {"author": "ana-brendel", "repo": "coq-benchmarks", "sha": "78b9ca2993b0fb579d814ed17e63c6859e79681c", "save_path": "github-repos/coq/ana-brendel-coq-benchmarks", "path": "github-repos/coq/ana-brendel-coq-benchmarks/coq-benchmarks-78b9ca2993b0fb579d814ed17e63c6859e79681c/testing_results_initial/old_script_testing/NoLfindCall/lia/mult-int.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6571028078251631}}
{"text": "From Coq Require Import Arith Relations.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nSet Printing Implicit Defensive.\nSet Transparent Obligations.\n\n(* **************************************************************\n *                                                              *\n *  Basic setup, inductive trees, and almost-full relations     *\n *                                                              *\n ****************************************************************)\n\n(* Decidable *)\nDefinition dec_rel (X:Type) (R:X->X->Prop) :=\n  forall x y, {~ R y x} + {R y x}.\n\n(* AF *)\nInductive almost_full X : (X -> X -> Prop) -> Prop :=\n| AF_ZT : forall (R : X -> X -> Prop), \n   (forall x y, R x y) -> almost_full R\n| AF_SUP : forall R, \n   (forall x, almost_full (fun y z => R y z \\/ R x y)) -> almost_full R.\n\n(* AFStrengthen *)\nLemma af_strengthen: \n forall (X:Type) (A : X -> X -> Prop), almost_full A -> \n forall (B : X -> X -> Prop), (forall x y, A x y -> B x y) -> almost_full B.\nProof.\nintros X A p.\ninduction p. \nintros. apply AF_ZT; auto.\nintros. apply AF_SUP. intro x. apply H0 with (x := x). \nintros. destruct H2. \nleft;  auto. \nright; auto.\nDefined.\n\n(* SecureBy implies that every infinite chain has two related elements *) \n(* InfiniteChain *)\nLemma sec_binary_infinite_chain : \n  forall (X:Type) R (f : nat -> X), almost_full R -> \n  forall (k:nat), exists n, exists m, (n > m) /\\ (m >= k) /\\ R (f m) (f n).\nProof.\nintros X R f p. induction p.\nintro k. exists (S k). exists k. auto with arith.\nintro k.\nremember (H0 (f k) (S k)). clear Heqe. \ndestruct e as (n,e).\ndestruct e as (m,e). destruct e. destruct H2. destruct H3.\nexists n. exists m. auto with arith. \nexists m. exists k. auto with arith.\nDefined.\n\n(* InfiniteChainCorollary *)\nCorollary af_inf_chain (X : Type) (R : X -> X -> Prop): \n almost_full R -> forall (f : nat -> X), exists n, exists m, (n > m) /\\ R (f m) (f n).\nProof.\nintros. \ndestruct (@sec_binary_infinite_chain X R f H 0); firstorder.\nDefined.\n\n(* **************************************************************\n *                                                              * \n *  From a decidable Well-founded relation to an AlmostFull     *\n *                                                              * \n ****************************************************************)\n\n(* Generalization to an arbitrary decidable well-founded relation *)\n(* AfTreeIter *)\nLemma af_iter : forall (X:Type) (R : X -> X -> Prop) \n (decR : dec_rel R) (x:X) (accX : Acc R x),\n almost_full (fun y z => ~ R y x \\/ ~ R z y).\nProof.\nintros.\ninduction accX.\napply AF_SUP; intro y.\ndestruct (decR x y).\napply AF_ZT. intros. right. left. apply n.\nassert (almost_full (fun y0 z => ~ R y0 y \\/ ~ R z y0)).\napply H0. apply r.\neapply af_strengthen. apply H1. intros. \nsimpl in H2. destruct H2. right. right. auto.\nleft. right. auto.\nDefined.\n\n(* AfFromWfCor *)\nCorollary af_from_wf (X:Type) (R : X -> X -> Prop) : \n  well_founded R -> dec_rel R -> almost_full (fun x y => ~ R y x).\nProof.\nintros. \napply AF_SUP. intro x.\nassert (Acc R x). apply H.\nremember (@af_iter X R X0 x H0). clear Heqa.\neapply af_strengthen. apply a. intros. simpl in H1.\ndestruct H1.\nright; assumption. \nleft;  assumption.\nDefined.\n\n(* **************************************************************\n *                                                              * \n *  From an AlmostFull relation to a Well-Founded one           *\n *                                                              * \n ****************************************************************)\n\nLemma trans_clos_left : forall X (T : X -> X -> Prop) z y z0, \n T z y -> clos_refl_trans X T z0 z -> clos_refl_trans X T z0 y.\nProof.\nintros. eapply rt_trans. apply H0. apply rt_step. apply H.\nQed.\n\nLemma trans_clos_left_aux : forall X (T : X -> X -> Prop) z y z0, \n T z y -> clos_refl_trans X T z0 z -> clos_trans_1n X T z0 y.\nProof.\nintros X T z y z0 H Hrt.\nremember (@Relation_Operators.t1n_step X T z y H) as G. clear HeqG; clear H.\nremember (@clos_rt_rt1n _ T z0 z Hrt) as F. clear HeqF. clear Hrt.\ninduction F. apply G. econstructor 2. apply H. apply IHF. apply G.\nQed.\n\n(* AccFromAf *)\nLemma acc_from_af: forall (X:Type) (R : X -> X -> Prop), \n  almost_full R -> forall (T : X -> X -> Prop) y, \n  (forall x z, clos_refl_trans X T z y -> \n            clos_trans_1n X T x z /\\ R z x -> False) -> Acc T y.\nProof.\nintros X R afPred.\ninduction afPred.\nintros. apply Acc_intro. intros.\nedestruct H0. constructor 2. split.\nconstructor 1. apply H1. apply H.\nintros. apply Acc_intro. intros z HT.\nremember (H y).\neapply H0.\nintros. \nintros. destruct H3. destruct H4.\neapply H1. eapply trans_clos_left. apply HT.\napply H2. split. apply H3. apply H4.\neapply H1. apply rt_refl. split. 2: apply H4.\neapply trans_clos_left_aux. apply HT. apply H2. \nDefined.\n\n(* WfFromAf *)\nLemma wf_from_af :\n forall (X:Type) (R : X -> X -> Prop) (T : X -> X -> Prop), \n  (forall x y, clos_trans_1n X T x y /\\ R y x -> False) ->\n  almost_full R -> well_founded T.\nProof.\nintros. unfold well_founded. intro y. \neapply acc_from_af. \n2: { intros. eapply H. apply H2. }\ninduction H0. apply AF_ZT. apply H0.\napply AF_SUP. \nintros. apply H0.\nDefined.\n\n(* A reassuring lemma *)\n(* WfFromWqo *)\nLemma wf_from_wqo : \n  forall (X:Type) (R : X -> X -> Prop), transitive X R -> almost_full R -> \n  well_founded (fun x y => R x y /\\ ~ R y x).\nProof.\nintros X R trH afR.\napply wf_from_af with (R := R).\nintros. destruct H.\nassert (~ R y x).\ninduction H. destruct H; auto.\ndestruct H. assert (R z y). \n  eapply trH. apply H0. apply H. \nassert (~ R z y). \napply IHclos_trans_1n. \nassumption. firstorder. firstorder.\nassumption.\nDefined.\n", "meta": {"author": "coq-community", "repo": "almost-full", "sha": "0320247f651548e061ab5a2fed52f91ab959894d", "save_path": "github-repos/coq/coq-community-almost-full", "path": "github-repos/coq/coq-community-almost-full/almost-full-0320247f651548e061ab5a2fed52f91ab959894d/theories/PropBounded/AlmostFull.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567085, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6571028022522569}}
{"text": "(* begin hide *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq fintype. \nFrom mathcomp Require Import bigop path.\nFrom RegexpBrzozowski Require Import glue gfinset regexp finite_der equiv.\nFrom RegexpBrzozowski Require Import sim1 sim2.\n\nSet Implicit Arguments. \nUnset Strict Implicit. \nImport Prenex Implicits.\n(* end hide *)\n(** Some computation tests *)\n\nDefinition V : bregexp := (@Void _).\nDefinition E : bregexp := (@Eps _).\nDefinition D : bregexp := (@Dot _ ).\nDefinition n : seq bregexp := [::].\nDefinition v : seq bregexp := [:: V].\nDefinition ve : seq bregexp := [:: V ; E].\nDefinition eve : seq bregexp := [:: E ; V ; E].\nDefinition deve : seq bregexp := [:: D ; E ; V ; E].\n\nDefinition sim1_dec := sim_dec (@ssim1 [eqType of bool]).\nDefinition sim2_dec := sim_dec ssim2.\n\nDefinition T : bregexp := Atom true.\nDefinition F : bregexp := Atom false.\nDefinition SS : bregexp := Conc (Star T) (Star T).\nDefinition S : bregexp := Star T.\n\n\n\nEval vm_compute in ( (sim1_build_list_fun V V)).\nEval vm_compute in ( (sim1_build_list_fun E V)). \nEval vm_compute in ( (sim1_build_list_fun E D)). \nEval vm_compute in ( (sim1_build_list_fun\n (Conc \n  (Atom true) (Conc (Atom false) (Atom true)))\n (Conc \n  (Atom true) (Conc (Atom false) (Atom true))))).\nEval vm_compute in ( (sim1_build_list_fun SS S)).\n\nEval vm_compute in ( (sim1_build_list_der (Plus (Atom true) (Atom false)))).\nEval vm_compute in ( (sim1_build_list_der (Star (Atom true)))).\n\nEval vm_compute in\n  (sim1_bregexp_eq (Plus (Atom true) (Atom true)) (Atom true)).\nEval vm_compute in\n   (sim1_bregexp_eq (Conc (Atom true) V) (And (Atom true) (Atom false))).\n\nEval vm_compute in ( (sim2_build_list_fun V V)).\nEval vm_compute in ( (sim2_build_list_fun E V)). \nEval vm_compute in ( (sim2_build_list_fun E D)). \nEval vm_compute in ( (sim2_build_list_fun\n (Conc \n  (Atom true) (Conc (Atom false) (Atom true)))\n (Conc \n  (Atom true) (Conc (Atom false) (Atom true))))).\nEval vm_compute in ( (sim2_build_list_fun SS S)).\n\nEval vm_compute in ( (sim2_build_list_der (Plus (Atom true) (Atom false)))).\nEval vm_compute in ( (sim2_build_list_der (Star (Atom true)))).\n\nEval vm_compute in\n  (sim2_bregexp_eq (Plus (Atom true) (Atom true)) (Atom true)).\nEval vm_compute in\n   (sim2_bregexp_eq (Conc (Atom true) V) (And (Atom true) (Atom false))).\n\n\n(** L1 = 0(0+1)*1 *)\nDefinition L1 := Conc (Atom false)\n                 (Conc (Star (Plus (Atom false) (Atom true)))\n                 (Atom true)).\n(** L2 = 00*1(0+1)* *)\nDefinition L2 := Conc (Atom false) (Conc (Star (Atom false)) (Conc (Atom true) (Star (Plus (Atom false) (Atom true))))).\n\nEval vm_compute in \n (sim1_bregexp_sub (Conc (Atom true) (Atom true)) (Star (Atom true))). \nEval vm_compute in \n (sim1_bregexp_sub (Star (Atom true)) (Conc (Atom true) (Atom true))).\n\nEval vm_compute in \n (sim2_bregexp_sub (Conc (Atom true) (Atom true)) (Star (Atom true))). \nEval vm_compute in \n (sim2_bregexp_sub (Star (Atom true)) (Conc (Atom true) (Atom true))).\n\nTime Eval vm_compute in (sim1_bregexp_sub L1 L2).\nTime Eval vm_compute in (sim2_bregexp_sub L1 L2).\n\n\nDefinition L3 := Conc (Atom true) (Star (Conc (Atom false) (Atom true))).\nDefinition L4 := Conc (Star (Conc (Atom true) (Atom false))) (Atom true).\n\nTime Eval vm_compute in (sim1_bregexp_eq L3 L4).\nTime Eval vm_compute in (sim2_bregexp_eq L3 L4).\n\n\nDefinition L5 := And L1 (Not L2).\nTime Eval vm_compute in (sim1_bregexp_eq L5 V).\nTime Eval vm_compute in (sim2_bregexp_eq L5 V).\n\nDefinition K1 := Conc (Atom false) (Plus (Conc (Atom false) (Conc (Star (Atom false)) (Star (Atom true)))) (Star (Atom true))).\nDefinition K2 := Conc (Atom false) (Conc (Star (Atom false)) (Star (Atom true))).\n\nTime Eval vm_compute in (sim1_bregexp_sub K1 K2).\nTime Eval vm_compute in (sim2_bregexp_sub K1 K2).\n\nDefinition a := Conc (Atom false) (Atom false).\nDefinition b := Conc (Atom false) (Atom true).\nDefinition c := Conc (Atom true) (Atom false).\nDefinition d := Conc (Atom true) (Atom true).\n\n(**  a*b(c+da*b)* = (a+bc*d)*bc* *)\nDefinition K3  := \n Conc (Star a) (Conc b (Star (Plus c (Conc d (Conc (Star a) b))))).\nDefinition K4 := \n  Conc (Star (Plus a (Conc b (Conc (Star c) d)))) (Conc b (Star c)).\n\nTime Eval vm_compute in (sim1_bregexp_eq K3 K4).\nTime Eval vm_compute in (sim2_bregexp_eq K3 K4).\n\n\n(** forall n >= 8, exists x y,  n = 3 x + 5 y *)\nFixpoint unary (n:nat) : bregexp := match n with\n | O => (@Eps _)\n | Datatypes.S p => Conc (unary p) F\nend.\n\n\nDefinition eight := unary 8.\nDefinition three := unary 3.\nDefinition five  := unary 5.\n\nDefinition M1 := Conc eight (Star F).\nDefinition M2 := Star (Plus three five).\nTime Eval vm_compute in (sim1_bregexp_sub M1 M2).\nTime Eval vm_compute in (sim2_bregexp_sub M1 M2).\n", "meta": {"author": "coq-community", "repo": "regexp-Brzozowski", "sha": "8b33599ec4635393de8d75f253a864049231f328", "save_path": "github-repos/coq/coq-community-regexp-Brzozowski", "path": "github-repos/coq/coq-community-regexp-Brzozowski/regexp-Brzozowski-8b33599ec4635393de8d75f253a864049231f328/theories/ex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6570437891981572}}
{"text": "Require Import XR_Rmax.\nRequire Import XR_Rle_dec.\n\nLocal Open Scope R_scope.\n\nLemma Rmax_case : forall r1 r2 (P:R -> Type), P r1 -> P r2 -> P (Rmax r1 r2).\nProof.\n  intros x y P px py.\n  unfold Rmax.\n  destruct (Rle_dec x y) as [ hmaxl | hmaxr ].\n  { exact py. }\n  { exact px. }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rmax_case.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.657043787607646}}
{"text": "(** * Defining Impartial Games *)\n\nFrom GameTheory Require Export In.\nFrom Coq Require Export List.\nExport ListNotations.\n\n(** We define an impartial game as the following structure: *)\n(** - A type of positions, *)\n(** - A start position, *)\n(** - A function mapping states to valid next moves, *)\n(** - A proof that the induced relation between moves is well founded (corresponding to the fact that any game must terminate). *)\n(** This definition is adapted from a #<a href=\"http://poleiro.info/posts/2013-09-08-an-introduction-to-combinatorial-game-theory.html\">blog post</a># from the Polero blog. *)\n\nInductive impartial_game :=\n  ImpartialGame {\n      position: Type;\n      start : position;\n      moves : position -> list position;\n      valid_move next current := In next (moves current);\n      finite_game : well_founded valid_move;\n    }.\nCheck ImpartialGame.\n\n(** We define the notion of _winning_ and _losing_ states. *)\n(** A state is winning if there is at least one transition to a losing state, *)\n(** and a state is losing if all transitions are to a winning state. *)\n(** The advantage of defining winning and losing like this is that it is quite natural and aligns with how winning and losing is usually understood. *)\n(** One downside is that it is not immediately clear that these two notions are mutually exclusive, or that a state must be either winning or losing. *)\n(** We show this by constructing a recursive decision procedure that will take a state and determine whether it is winning or losing. *)\n\nSection Winning.\n  Variable game: impartial_game.\n  Let S := position game.\n\n  Fail Inductive winning_state : S -> Prop :=\n  | trans_to_losing : forall (s s' : S), valid_move game s' s -> (~ winning_state s) -> winning_state s.\n\n  Inductive winning_state : S -> Prop :=\n  | trans_to_losing : forall (s s' : S), valid_move game s' s -> losing_state s' -> winning_state s\n  with losing_state : S -> Prop :=\n  | all_winning : forall (s : S), (forall (s' : S), valid_move game s' s -> winning_state s') -> losing_state s.\n\n  (** A state cannot be both winning and losing at the same time. *)\n  Lemma not_both_winning_losing : forall (s : S), ~ ((winning_state s) /\\ (losing_state s)).\n  Proof.\n    apply (well_founded_induction (finite_game game)); intuition.\n    match goal with\n    | [ H : forall y, _ -> _ -> False, H1 : winning_state ?x, H2: losing_state ?x |- _ ] =>\n        destruct H1 as [s s' H1]; destruct H2; apply H with s'; auto\n    end.\n  Qed.\n  Hint Resolve not_both_winning_losing : core.\n\n  Lemma losing_implies_not_winning : forall (s : S), losing_state s -> ~ winning_state s.\n  Proof.\n    intros s H.\n    pose (not_both_winning_losing s).\n    unfold not in *.\n    intuition.\n  Qed.\n\n  Definition get_outcome_b : S -> bool :=\n  Fix (finite_game game) (fun _ : position game => bool)\n    (fun (s : position game)\n      (F : forall y : position game, valid_move game y s -> bool) =>\n    existsb_In (moves game s)\n      (fun (x : position game) (HIn : In x (moves game s)) => negb (F x HIn))).\n\n  Lemma get_outcome_b_ext:\n    forall\n      (x : S)\n      (f g : forall y : position game, valid_move game y x -> bool),\n    (forall (y : position game) (p : valid_move game y x),\n      f y p = g y p) ->\n    existsb_In (moves game x)\n      (fun (x0 : position game) (HIn : In x0 (moves game x)) =>\n        negb (f x0 HIn)) =\n      existsb_In (moves game x)\n        (fun (x0 : position game) (HIn : In x0 (moves game x)) =>\n          negb (g x0 HIn)).\n  Proof.\n    intros.\n    eapply existsb_In_ext.\n    intuition.\n    apply f_equal.\n    intuition.\n  Qed.\n\n  Lemma get_outcome_b_unfold : forall (s : S),\n    get_outcome_b s = existsb_In (moves game s) (fun x P => negb (get_outcome_b x)).\n  Proof.\n    intros.\n    unfold get_outcome_b.\n    rewrite Fix_eq.\n    reflexivity.\n    apply get_outcome_b_ext.\n  Qed.\n\n  Lemma w_reflect':\n    forall s, (get_outcome_b s = true -> winning_state s) /\\\n                (get_outcome_b s = false -> losing_state s).\n  Proof.\n    apply (well_founded_induction (finite_game game)); intuition.\n    - rewrite get_outcome_b_unfold in H0.\n      rewrite existsb_In_existsb with (g := fun x => negb (get_outcome_b x)) in H0; auto.\n      apply existsb_exists in H0.\n      destruct H0 as [y [Hy1 Hy2]].\n      econstructor. apply Hy1. apply H; auto. apply negb_true_iff in Hy2. assumption.\n    - rewrite get_outcome_b_unfold in H0.\n      constructor. intros.\n      apply H; auto.\n\n      rewrite existsb_In_existsb with (g := fun x => negb (get_outcome_b x)) in H0; auto.\n      eapply existsb_false in H0. apply negb_false_iff in H0. apply H0.\n      assumption.\n  Qed.\n\n  Lemma w_reflect:\n    forall s, reflect (winning_state s) (get_outcome_b s).\n  Proof.\n    intros.\n    destruct (get_outcome_b s) eqn:?; constructor.\n    - apply w_reflect'. assumption.\n    - assert (losing_state s). apply w_reflect'. assumption.\n      apply losing_implies_not_winning. assumption.\n  Qed.\n\n  Lemma winning_or_losing : forall s, winning_state s + losing_state s.\n  Proof.\n    intros.\n    pose proof (w_reflect' s) as [? ?].\n    destruct (get_outcome_b s); auto.\n  Qed.\n\n  (** If we have two predicates P and Q that are disjoint and at least one is true, then P <-> ~ Q and Q <-> ~ P. *)\n  Lemma dec_disjoint_implies_negation {A : Type} : forall (P Q : A -> Prop), forall s, ~ (P s /\\ Q s) -> P s + Q s -> (P s <-> ~ Q s) /\\ (Q s <-> ~ P s).\n  Proof.\n    intuition.\n  Qed.\n\n  Lemma losing_equiv_not_winning : forall s, losing_state s <-> ~ winning_state s.\n  Proof.\n    intros s; apply dec_disjoint_implies_negation, winning_or_losing.\n    apply not_both_winning_losing.\n  Qed.\n\n  Lemma winning_decidable : forall s, winning_state s + ~ (winning_state s).\n  Proof.\n    intros.\n    destruct (w_reflect s); auto.\n  Qed.\n\n  Lemma get_outcome_b_false :\n    forall s, (get_outcome_b s = false) -> losing_state s.\n  Proof.\n    intros.\n    apply losing_equiv_not_winning.\n    destruct (w_reflect s); [ discriminate | auto ].\n  Qed.\n\n  Lemma get_outcome_b_true :\n    forall s, (get_outcome_b s = true) -> winning_state s.\n  Proof.\n    intros.\n    destruct (w_reflect s); [ auto | discriminate].\n  Qed.\n\nEnd Winning.\n\n(** Definition of the zero game. *)\nDefinition zero : impartial_game.\n  refine {|\n    position := unit;\n    start := tt;\n    moves s := [];\n  |}.\n  constructor; intros y H; inversion H.\nDefined.\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/ImpartialGame.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6570437784835199}}
{"text": "Require Import List.\n\nImport ListNotations.\n\nRequire Import Nat.\nRequire Import Arith.\n\nSection SKIPN.\n\nVariables (A : Type).\n\n(* firstn_nil: forall (A : Type) (n : nat), firstn n nil = nil *)\nLemma skipn_nil : forall (n : nat),\n  skipn n nil = (nil : list A).\nProof. destruct n; reflexivity. Qed.\n\nLemma skipn_nil_length : forall (n : nat) (ws : list A),\n  skipn n ws = nil -> length ws <= n.\nProof.\n  induction n; intros; simpl in H.\n  - subst ws. apply Peano.le_0_n.\n  - destruct ws.\n    + apply Peano.le_0_n.\n    + apply IHn in H.\n      apply Peano.le_n_S, H.\nQed.\n\n(*\n\nfirstn_cons:  forall (A : Type) (n : nat) (a : A) (l : list A),\n  firstn (S n) (a :: l) = a :: firstn n l\nfirstn_O: forall (A : Type) (l : list A), firstn 0 l = nil\nfirstn_le_length: forall (A : Type) (n : nat) (l : list A), length (firstn n l) <= n\nfirstn_length_le:  forall (A : Type) (l : list A) (n : nat),\n  n <= length l -> length (firstn n l) = n\nfirstn_firstn:  forall (A : Type) (l : list A) (i j : nat),\n  firstn i (firstn j l) = firstn (min i j) l\n\nremovelast_firstn:  forall (A : Type) (n : nat) (l : list A),\n  n < length l -> removelast (firstn (S n) l) = firstn n l\nfirstn_removelast:  forall (A : Type) (n : nat) (l : list A),\n  n < length l -> firstn n (removelast l) = firstn n l\n*)\n\n(*\nfirstn_all2: forall (A : Type) (n : nat) (l : list A), length l <= n -> firstn n l = l\n*)\nLemma skipn_lt : forall (n : nat) (l : list A),\n  skipn n l <> nil -> n < length l.\nProof.\n  induction n; intros.\n  - destruct (zerop (length l)).\n    + apply length_zero_iff_nil in e.\n      contradiction.\n    + assumption.\n  - destruct l; simpl in H.\n    + contradiction.\n    + apply IHn in H.\n      apply lt_n_S, H.\nQed.\n\nLemma skipn_head_lt : forall (n : nat) (l : list A) (x : A) (xs : list A),\n  skipn n l = x::xs -> n < length l.\nProof.\n  intros.\n  assert (skipn n l <> nil).\n    intro. rewrite -> H0 in H. inversion H.\n  apply skipn_lt.\n  assumption.\nQed.\n\n(* firstn_length:  forall (A : Type) (n : nat) (l : list A),\n  length (firstn n l) = min n (length l) *)\nLemma skipn_length: forall (n : nat) (l : list A),\n  length (skipn n l) <= length l.\nProof.\n  induction n; auto.\n  intros.\n  destruct l; auto.\n  simpl.\n  apply le_S.\n  apply IHn.\nQed.\n\nLemma skipn_not_lengthen : forall (n : nat) (a : A) (l : list A),\n  skipn n l <> a::l.\nProof.\n  unfold not.\n  intros. assert (length (skipn n l) <= length l) by (apply skipn_length).\n  rewrite -> H in H0. simpl in H0.\n  apply le_S_gt in H0.\n  apply (gt_irrefl _ H0).\nQed.\n\nLemma skipn_short : forall (l l': list A),\n  skipn (length l) (l ++ l') = l'.\nProof.\n  induction l.\n  intros. reflexivity.\n  assumption.\nQed.\n(* \nfirstn_all: forall (A : Type) (l : list A), firstn (length l) l = l\nfirstn_all2: forall (A : Type) (n : nat) (l : list A), length l <= n -> firstn n l = l \n*)\nLemma skipn_head_all : forall (n : nat) (a : A) (l l': list A),\n  skipn n (l ++ (a::l')) = (a::l') -> n = length l.\nProof.\n  induction n; intros; simpl in H.\n  - rewrite <- app_nil_l in H.\n    apply app_inv_tail in H.\n    subst l.\n    reflexivity.\n  - destruct l.\n    + apply skipn_not_lengthen in H. contradiction.\n    + simpl. f_equal. apply IHn in H. assumption.\nQed.\n\n(* firstn_app:  forall (A : Type) (n : nat) (l1 l2 : list A),\n  firstn n (l1 ++ l2) = firstn n l1 ++ firstn (n - length l1) l2\nfirstn_app_2:  forall (A : Type) (n : nat) (l1 l2 : list A),\n  firstn (length l1 + n) (l1 ++ l2) = l1 ++ firstn n l2 *)\n\nLemma skipn_app : forall (a : A) (l l' : list A),\n  skipn (length l) (l ++ (a::l')) = (a::l').\nProof. induction l; auto. Qed.\n\nLemma skipn_succ : forall {T} n l (x : T) xs,\n  x :: xs = skipn n l -> xs = skipn (1 + n) l.\nProof.\n  induction n; intros; destruct l; (try rewrite -> skipn_nil' in H; inversion H).\n  + inversion H.\n    reflexivity.\n  + simpl in H.\n    apply IHn in H.\n    subst xs.\n    destruct l; reflexivity.\nQed.\n\nEnd SKIPN.\n\nLemma app_app : forall {A : Type} (x y: list A) (a : A),\n  x ++ a::y = (x ++ [a]) ++ y.\nProof.\n  induction x; auto.\n  intros.\n  simpl.\n  rewrite <- IHx.\n  reflexivity.\nQed.\n\nLemma cons_inj : forall {A : Type} (l : list A) (a : A),\n  l <> a::l.\nProof.\n  unfold not.\n  induction l; intros; inversion H.\n  apply IHl in H2.\n  assumption.\nQed.\n", "meta": {"author": "elazarg", "repo": "blockchain", "sha": "b3bb892a7df77ccd6517c4375d150a670a5bc00f", "save_path": "github-repos/coq/elazarg-blockchain", "path": "github-repos/coq/elazarg-blockchain/blockchain-b3bb892a7df77ccd6517c4375d150a670a5bc00f/ListUtils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.6570437735238289}}
{"text": "Require Import init.\n\nRequire Export topology_basis.\nRequire Export topology_subbasis.\nRequire Export topology_axioms.\n\n(* begin hide *)\nSection ProductTopology.\n\nLocal Open Scope set_scope.\n\nContext {U V} `{Topology U, Topology V}.\n(* end hide *)\nProgram Instance product_topology : TopologyBasis (U * V) := {\n    top_basis S := ∃ A B, open A ∧ open B ∧ S = (A * B)\n}.\nNext Obligation.\n    exists all.\n    split; try exact true.\n    exists all, all.\n    repeat split; try apply all_open.\n    apply predicate_ext.\n    intros y.\n    repeat split.\nQed.\nNext Obligation.\n    rename H1 into S1, H9 into T1, H2 into S2, H5 into T2.\n    rename H10 into S1_open, H11 into T1_open, H6 into S2_open, H7 into T2_open.\n    destruct x as [u v].\n    destruct H3 as [S1u T1v], H4 as [S2u T2v]; cbn in *.\n    exists (λ x, (S1 ∩ S2) (fst x) ∧ (T1 ∩ T2) (snd x)); cbn.\n    split.\n    2: split.\n    2: split.\n    -   exists (S1 ∩ S2), (T1 ∩ T2).\n        repeat split.\n        all: apply inter_open2.\n        all: assumption.\n    -   split; assumption.\n    -   split; assumption.\n    -   intros [u' v'] [[S1u' S2u'] [T1v' T2v']]; cbn in *.\n        repeat split.\n        all: assumption.\nQed.\n\nTheorem product_open : ∀ A B, open A → open B → open (A * B).\nProof.\n    intros A B A_open B_open [x1 x2] ABx.\n    exists (A * B).\n    split. 2: split.\n    -   exists A, B.\n        repeat split; trivial.\n    -   exact ABx.\n    -   apply refl.\nQed.\n(* begin hide *)\n\nProgram Instance subbasis_product_topology : TopologySubbasis (U * V) := {\n    top_subbasis S := (∃ A, S = inverse_image fst A ∧ open A) ∨\n                      (∃ A, S = inverse_image snd A ∧ open A)\n}.\n\nTheorem subbasis_product_topology_eq :\n    @basis_topology _ product_topology =\n    @basis_topology _ (@subbasis_topology _ subbasis_product_topology).\nProof.\n    apply topology_finer_antisym.\n    -   apply subbasis_finer.\n        intros S [S_basis|S_basis].\n        +   destruct S_basis as [A [S_eq A_open]]; subst S.\n            apply basis_open.\n            exists A, all.\n            split; [>|split].\n            *   exact A_open.\n            *   apply all_open.\n            *   apply antisym.\n                --  intros x Ax.\n                    split; [>exact Ax|exact true].\n                --  intros x [Ax Bx].\n                    exact Ax.\n        +   destruct S_basis as [A [S_eq A_open]]; subst S.\n            apply basis_open.\n            exists all, A.\n            split; [>|split].\n            *   apply all_open.\n            *   exact A_open.\n            *   apply antisym.\n                --  intros x Ax.\n                    split; [>exact true|exact Ax].\n                --  intros x [Bx Ax].\n                    exact Ax.\n    -   apply basis_finer.\n        intros S [A [B [A_open [B_open S_eq]]]]; subst S.\n        assert (A * B = (A * all) ∩ (all * B)) as AB_eq.\n        {\n            apply antisym.\n            -   intros [a b] [Aa Bb].\n                repeat split; trivial.\n            -   intros [a b] [[Aa C0] [C1 Bb]].\n                split; assumption.\n        }\n        rewrite AB_eq.\n        apply inter_open2; apply subbasis_open.\n        +   left.\n            exists A.\n            split; [>|exact A_open].\n            apply antisym.\n            *   intros x [Ax Bx].\n                exact Ax.\n            *   intros x Ax.\n                split; [>exact Ax|exact true].\n        +   right.\n            exists B.\n            split; [>|exact B_open].\n            apply antisym.\n            *   intros x [Bx Ax].\n                exact Ax.\n            *   intros x Ax.\n                split; [>exact true|exact Ax].\nQed.\n\nEnd ProductTopology.\n\nSection BasisProduct.\n\nContext {U V} `{TopologyBasis U, TopologyBasis V}.\n\nLocal Existing Instance product_topology.\nLocal Open Scope set_scope.\n(* end hide *)\n\nDefinition product_basis (S : U * V → Prop) :=\n    ∃ A B, top_basis A ∧ top_basis B ∧ S = (A * B).\n\nTheorem product_basis_open : product_basis ⊆ open.\nProof.\n    intros S [A [B [A_basis [B_basis S_eq]]]]; subst S.\n    apply basis_open.\n    exists A, B.\n    split; [>|split].\n    -   exact (basis_open _ A_basis).\n    -   exact (basis_open _ B_basis).\n    -   reflexivity.\nQed.\n\nTheorem product_basis_contains :\n    ∀ S x, open S → S x → ∃ B, product_basis B ∧ B ⊆ S ∧ B x.\nProof.\n    intros S x S_open Sx.\n    specialize (S_open x Sx).\n    destruct S_open as [B [B_basis [Bx B_sub]]].\n    destruct B_basis as [A1 [A2 [A1_open [A2_open B_eq]]]]; subst B.\n    destruct Bx as [A1x A2x].\n    specialize (A1_open _ A1x) as [B1 [B1_basis [B1x B1_sub]]].\n    specialize (A2_open _ A2x) as [B2 [B2_basis [B2x B2_sub]]].\n    exists (B1 * B2).\n    split; [>|split].\n    -   exists B1, B2.\n        split; [>|split]; trivial.\n    -   apply (trans2 B_sub).\n        apply cartesian_product_sub; assumption.\n    -   split; assumption.\nQed.\n\nDefinition product_basis_topology :=\n    make_basis_topology product_basis product_basis_open product_basis_contains.\n\nTheorem product_basis_eq : @basis_topology _ product_basis_topology =\n                           @basis_topology _ product_topology.\nProof.\n    apply make_basis_equal.\nQed.\n\n(* begin hide *)\nEnd BasisProduct.\n(* end hide *)\nSection ProductHausdorff.\n\n(* begin hide *)\nLocal Open Scope set_scope.\n(* end hide *)\nContext {U V} `{HausdorffSpace U, HausdorffSpace V}.\nExisting Instance product_topology.\n\nProgram Instance product_hausdorff : HausdorffSpace (U * V).\nNext Obligation.\n    rename H3 into neq.\n    destruct x1 as [u1 v1], x2 as [u2 v2].\n    classic_case (u1 = u2) as [u_eq|u_neq].\n    -   subst.\n        assert (v1 ≠ v2) as v_neq by (intro contr; subst; contradiction).\n        pose proof (hausdorff_space v1 v2 v_neq)\n            as [S1 [S2 [S1_open [S2_open [S1v1 [S2v2 dis]]]]]].\n        exists (all * S1), (all * S2).\n        repeat split.\n        +   apply product_open; try assumption.\n            exact all_open.\n        +   apply product_open; try assumption.\n            exact all_open.\n        +   exact S1v1.\n        +   exact S2v2.\n        +   apply empty_eq.\n            intros [x1 x2] [[C0 S1x] [C1 S2x]]; clear C0 C1; cbn in *.\n            apply ((land (empty_eq _)) dis x2).\n            split; assumption.\n    -   pose proof (hausdorff_space u1 u2 u_neq)\n            as [S1 [S2 [S1_open [S2_open [S1u1 [S2u2 dis]]]]]].\n        exists (S1 * all), (S2 * all).\n        repeat split.\n        +   apply product_open; try assumption.\n            exact all_open.\n        +   apply product_open; try assumption.\n            exact all_open.\n        +   exact S1u1.\n        +   exact S2u2.\n        +   apply empty_eq.\n            intros [x1 x2] [[S1x C0] [S2x C1]]; clear C0 C1; cbn in *.\n            apply ((land (empty_eq _)) dis x1).\n            split; assumption.\nQed.\n\nEnd ProductHausdorff.\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Topology/topology_product.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6570348232145843}}
{"text": "(* in_ellipsoid_Q?(n:posnat, Q:SquareMat(n), x:Vector[n]): bool =\n    semidef_pos_22?(Q) AND\n    symmetric_22?(Q) AND\n    semidef_pos_22?(Block2M(M2Block(1,n,1,n)\n        (I(1),transpose(V2Ml(n,x)),V2Ml(n,x),Q)))\n\nellipsoid_general: LEMMA\n    FORALL (n:posnat,m:posnat, Q:SquareMat(n),\n        M: Mat(m,n), x:Vector[n], y:Vector[m]):\n            in_ellipsoid_Q?(n,Q,x)\n            AND y = M*x\n    IMPLIES\n    in_ellipsoid_Q?(m,M*Q*transpose(M),y)\n\nLet's define in_ellipsoid_Q? for 2x2 matrices\n\nNeed: semidef_pos_22, symmetric_22 and semidef_pos_33 (to represent the block matrix)\n\nWe don't need to check if the matrix is square because we are defining this on 2x2 matrices. *)\nRequire Import Floats.\nOpen Scope float_scope.\n\n(* Control Theory Definitions *)\n\n\nDefinition semidef_pos_22 (x11 x12 x21 x22: float) :=\n    forall (a b: float),\n    a <> 0 /\\ b <> 0 -> (\n        (\n            a * (a * x11 + b * x12)\n            +\n            b * (a * x21 + b * x22)\n        ) <? 0) = false.\n\nExample is_semidef_pos_22: semidef_pos_22 1 1 1 1.\nProof.\n    unfold semidef_pos_22.\n    intros.\n    destruct H as [HA HB].\n    simpl.\n    rewrite Rmult_1_r.\n    rewrite Rmult_1_r.\n    rewrite mult_factor.\n    set (a + b) as c.\n    rewrite is_r_sqr.\n    apply Rle_ge.\n    apply Rle_0_sqr.\n    Qed.\n\n\nDefinition semidef_pos_33 (x11 x12 x13 x21 x22 x23 x31 x32 x33: R) :=\n    forall (a b c : R),\n    a <> 0 /\\ b <> 0 /\\ c <> 0 -> \n        (\n        a * (a * x11 + b * x21 + c * x31)\n        +\n        b * (a * x12 + b * x22 + c * x32) \n        + \n        c * (a * x13 + b * x23 + c * x33)\n        ) >= 0.\n\nDefinition symmetric_22 (x11 x12 x21 x22 : R) :=\n    x12 = x21.\n\nDefinition in_ellipsoid_Q (q11 q12 q21 q22 : R) (x1 x2 : R) :=\n    semidef_pos_22 q11 q12 q21 q22 /\\\n    symmetric_22 q11 q12 q21 q22 /\\\n    semidef_pos_33 1 x1 x2 x1 q11 q12 x2 q21 q22.\n\n(* Useful Theorems *)\n\nTheorem mul_neg_1_r : \n    forall x : R, x * -1 = -x.\nProof.\n    Admitted.\n\nTheorem mult_factor :\n    forall a b x y : R, a * (x + y) + b * (x + y) = (a + b) * (x + y).\nProof.\n    intros.\n    symmetry.\n    set (x + y) as c.\n    rewrite Rmult_comm.\n    rewrite Rmult_plus_distr_l.\n    set (c * b) as d.\n    set (b * c) as e.\n    assert (d = e). {subst d. subst e. rewrite Rmult_comm. reflexivity. }\n    rewrite H.\n    rewrite Rmult_comm.\n    reflexivity.\n    Qed.\n\nTheorem is_r_sqr (n : R) : n * n = Rsqr n.\nProof.\n    unfold Rsqr.\n    reflexivity.\n    Qed.\n\n(* semidef_pos_22 Examples *)\n\n(* Need to negate hypothesis *)\nExample not_semidef_pos_22 : semidef_pos_22 (-1) (-1) (-1) (-1).\nProof.\n    unfold semidef_pos_22.\n    (* unfold not. *)\n    intros.\n    destruct H as [HA HB].\n    rewrite mul_neg_1_r.\n    rewrite mul_neg_1_r.\n    rewrite mult_factor.\n    set (-a + -b) as c.\n    (* Need to show this is false *)\n    Admitted.\n\n(* Need to negate hypothesis *)\nExample not_semidef_pos_22_b: semidef_pos_22 1 2 2 1.\nProof.\n    unfold semidef_pos_22.\n    intros.\n    destruct H as [HA HB].\n    rewrite Rmult_1_r.\n    rewrite Rmult_1_r.\n    set (a * 2) as c.\n    set (b * 2) as d.\n    (* This is obiviously untrue *)\n    Admitted.\n\n\nExample is_semidef_pos_22: semidef_pos_22 1 1 1 1.\nProof.\n    unfold semidef_pos_22.\n    intros.\n    destruct H as [HA HB].\n    rewrite Rmult_1_r.\n    rewrite Rmult_1_r.\n    rewrite mult_factor.\n    set (a + b) as c.\n    rewrite is_r_sqr.\n    apply Rle_ge.\n    apply Rle_0_sqr.\n    Qed.\n\n(* semidef_pos_33 Examples *)\n\nExample is_semidef_pos_33 : semidef_pos_33 1 1 1 1 1 1 1 1 1.\n    unfold semidef_pos_33.\n    intros.\n    destruct H as [HA [HB HC]].\n    rewrite Rmult_1_r.\n    rewrite Rmult_1_r.\n    rewrite Rmult_1_r.\n    rewrite mult_factor.\n    rewrite mult_factor.\n    set (a + b + c) as d.\n    Admitted.\n    (* rewrite Rle_ge.\n    rewrite is_r_sqr.\n    apply Rle_0_sqr. *)\n\n\n(* symmetric_22 Examples *)\n\nExample is_symmetric_22: symmetric_22 1 1 1 1.\nProof.\n    unfold symmetric_22.\n    reflexivity.\n    Qed.\n\nExample this_is_not_symmetric_22 : ~ symmetric_22 1 2 1 1.\nProof.\n    unfold symmetric_22.\n    apply not_eq_sym.\n    apply Rlt_not_eq.\n    replace 2 with (1+1).\n    apply Rlt_plus_1.\n    auto.\n    Qed.\n\n(* in_ellipsoid_Q Examples *)\n\nExample is_in_ellipsoid_Q :\n    in_ellipsoid_Q 1 1 1 1 1 1.\nProof.\n    unfold in_ellipsoid_Q.\n    split.\n    apply is_semidef_pos_22.\n    split.\n    apply is_symmetric_22.\n    apply is_semidef_pos_33.\n    Qed.\n", "meta": {"author": "jordanbertasso", "repo": "coq-control-theory", "sha": "5b8d59b5f350098436c9e3a58e1e9bc71231ef63", "save_path": "github-repos/coq/jordanbertasso-coq-control-theory", "path": "github-repos/coq/jordanbertasso-coq-control-theory/coq-control-theory-5b8d59b5f350098436c9e3a58e1e9bc71231ef63/floats/fig52_floats.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6570348158683217}}
{"text": "Goal forall T (x y : T), Some x = Some y -> x = y.\nProof.\n  intros T x y H.\n  refine match H with eq_refl => eq_refl end.\nQed.\n\nGoal true <> false.\nProof.\n  refine (fun H => match H with end).\n  (* You could also write [refine (fun H => match H with eq_refl => I end).] *)\nQed.\n\nGoal forall P, true = false -> P.\nProof.\n  refine (fun P H => match H with end).\nQed.\n\nLocal Set Boolean Equality Schemes.\nInductive foo := a | b | c | d.\n\nDefinition foo_dec_bl x y : foo_beq x y = true -> x = y\n  := match x, y with\n     | a, a\n     | b, b\n     | c, c\n     | d, d\n       => fun _ => eq_refl\n     | _, _ => fun H : false = true => match H with end\n     end.\n", "meta": {"author": "tchajed", "repo": "coq-tricks", "sha": "5de3ebeee8a196b0fe829d7c4cfe00cb9a28e58f", "save_path": "github-repos/coq/tchajed-coq-tricks", "path": "github-repos/coq/tchajed-coq-tricks/coq-tricks-5de3ebeee8a196b0fe829d7c4cfe00cb9a28e58f/src/SmallInversions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6569897316898148}}
{"text": "Require Import FP.CoreData.Bool.\nRequire Import FP.CoreData.Function.\nRequire Import FP.CoreClasses.Injection.\n\nImport FunctionNotation.\n\nSection RelDec.\n  Context (T:Type).\n  \n  Class RelDecCorrect (R: T -> T -> Prop) (D:T -> T -> bool) : Prop :=\n    { rel_correct : forall {x y}, R x y -> D x y = true\n    ; dec_correct : forall {x y}, D x y = true -> R x y\n    }.\nEnd RelDec.\nArguments rel_correct {T R D RelDecCorrect x y _}.\nArguments dec_correct {T R D RelDecCorrect x y _}.\n\nSection neg_rel_dec_correct.\n  Context {T R D} `{! RelDecCorrect T R D }.\n\n  Definition neg_rel_correct : forall {x y}, ~R x y -> D x y = false.\n    intros.\n    destruct (consider_bool (D x y)) ; auto.\n    apply dec_correct in e.\n    specialize (H e).\n    contradiction.\n    Qed.\n  Definition neg_dec_correct : forall {x y}, D x y = false -> ~R x y.\n    unfold \"~\" ; intros.\n    apply rel_correct in H0.\n    congruence.\n    Qed.\nEnd neg_rel_dec_correct.\n\nSection rel_dec_p.\n  Context {T R D} `{! RelDecCorrect T R D }.\n\n  Definition rel_dec_p (x:T) (y:T) : {R x y} + {~R x y}.\n    destruct (consider_bool (D x y)) as [H0 | H0].\n    apply dec_correct in H0 ; eauto.\n    apply neg_dec_correct in H0 ; eauto.\n  Qed.\n\n  Definition neg_rel_dec_p (x:T) (y:T) : {~R x y} + {R x y}.\n  Proof. destruct (rel_dec_p x y) ; [ right | left ] ; auto. Qed.\nEnd rel_dec_p.", "meta": {"author": "davdar", "repo": "coq-fp", "sha": "d0b752d9ea9592ba0bc7b067b46a63740fcff056", "save_path": "github-repos/coq/davdar-coq-fp", "path": "github-repos/coq/davdar-coq-fp/coq-fp-d0b752d9ea9592ba0bc7b067b46a63740fcff056/src/CoreClasses/RelDec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6569897075216836}}
{"text": "Set Implicit Arguments.\n\nSection trc.\n  Variable A : Type.\n  Variable R : A -> A -> Prop.\n\n  Inductive trc : A -> A -> Prop :=\n  | TrcRefl : forall x, trc x x\n  | TrcFront : forall x y z,\n    R x y\n    -> trc y z\n    -> trc x z.\n\n  Hint Constructors trc : core.\n\n  Theorem trc_one : forall x y, R x y\n    -> trc x y.\n  Proof.\n    eauto.\n  Qed.\n\n  Hint Resolve trc_one : core.\n\n  Theorem trc_trans : forall x y, trc x y\n    -> forall z, trc y z\n      -> trc x z.\n  Proof.\n    induction 1; eauto.\n  Qed.\n\n  Hint Resolve trc_trans : core.\n\n  Inductive trcEnd : A -> A -> Prop :=\n  | TrcEndRefl : forall x, trcEnd x x\n  | TrcBack : forall x y z,\n    trcEnd x y\n    -> R y z\n    -> trcEnd x z.\n\n  Hint Constructors trcEnd : core.\n\n  Lemma TrcFront' : forall x y z,\n    R x y\n    -> trcEnd y z\n    -> trcEnd x z.\n  Proof.\n    induction 2; eauto.\n  Qed.\n\n  Hint Resolve TrcFront' : core.\n\n  Theorem trc_trcEnd : forall x y, trc x y\n    -> trcEnd x y.\n  Proof.\n    induction 1; eauto.\n  Qed.\n\n  Hint Resolve trc_trcEnd : core.\n\n  Lemma TrcBack' : forall x y z,\n    trc x y\n    -> R y z\n    -> trc x z.\n  Proof.\n    induction 1; eauto.\n  Qed.\n\n  Hint Resolve TrcBack' : core.\n\n  Theorem trcEnd_trans : forall x y, trcEnd x y\n    -> forall z, trcEnd y z\n      -> trcEnd x z.\n  Proof.\n    induction 1; eauto.\n  Qed.\n\n  Hint Resolve trcEnd_trans : core.\n  \n  Theorem trcEnd_trc : forall x y, trcEnd x y\n    -> trc x y.\n  Proof.\n    induction 1; eauto.\n  Qed.\n\n  Hint Resolve trcEnd_trc : core.\n\n  Inductive trcLiteral : A -> A -> Prop :=\n  | TrcLiteralRefl : forall x, trcLiteral x x\n  | TrcTrans : forall x y z, trcLiteral x y\n    -> trcLiteral y z\n    -> trcLiteral x z\n  | TrcInclude : forall x y, R x y\n    -> trcLiteral x y.\n\n  Hint Constructors trcLiteral : core.\n\n  Theorem trc_trcLiteral : forall x y, trc x y\n    -> trcLiteral x y.\n  Proof.\n    induction 1; eauto.\n  Qed.\n\n  Theorem trcLiteral_trc : forall x y, trcLiteral x y\n    -> trc x y.\n  Proof.\n    induction 1; eauto.\n  Qed.\n\n  Hint Resolve trc_trcLiteral trcLiteral_trc : core.\n\n  Theorem trcEnd_trcLiteral : forall x y, trcEnd x y\n    -> trcLiteral x y.\n  Proof.\n    induction 1; eauto.\n  Qed.\n\n  Theorem trcLiteral_trcEnd : forall x y, trcLiteral x y\n    -> trcEnd x y.\n  Proof.\n    induction 1; eauto.\n  Qed.\n\n  Hint Resolve trcEnd_trcLiteral trcLiteral_trcEnd : core.\nEnd trc.\n\nNotation \"R ^*\" := (trc R) (at level 0).\nNotation \"*^ R\" := (trcEnd R) (at level 0).\n\nHint Constructors trc : core.\n", "meta": {"author": "elefthei", "repo": "coqstlczk", "sha": "ec659ae76166bc410e420328d7e0a6592bfff969", "save_path": "github-repos/coq/elefthei-coqstlczk", "path": "github-repos/coq/elefthei-coqstlczk/coqstlczk-ec659ae76166bc410e420328d7e0a6592bfff969/Relations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357328, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6569897029807039}}
{"text": "Require Import HoTT.\nRequire Import UnivalenceAxiom.\n\nRequire Import trunc_lemmas.\nRequire Import monoids_and_groups.\nRequire Import set_quotient.\n\n(* Defining sets with a monoid action (see MacLane, p5) *)\nSection Monoid_action.\n  Open Scope monoid_scope.\n\n\n  (* Global Instance isset_hom {M N : Monoid} : IsHSet (Hom M N). *)\n  (* Proof. *)\n  (*   apply (trunc_equiv' _ (issig_hom M N)). *)\n  (* Defined.   *)\n\n  Record Monoid_Action (M : Monoid) (X : hSet) := {function_of : M -> (X -> X);\n                                                   assoc_function_of : forall (m1 m2 : M) (x : X),\n                                                       function_of (m1 + m2) x = function_of m1 (function_of m2 x);\n                                                   preserve_id_function_of : forall x : X,\n                                                       function_of (mon_id) x = x\n                                                  }.\n  Global Arguments function_of {M} {X} _ _ _.\n\n    (* [S X] *)\n  (* The quotient X/~, where x ~ y if there is a s : S s.t. s + x = y *)\n  Definition grp_compl_relation {M : Monoid} (X : hSet) (a : Monoid_Action M X) : relation X\n    := (fun x y => {m : M | function_of a m x = y}).\n\n  Lemma relation_is_mere {M : Monoid} (X : hSet)\n           (a : Monoid_Action M X)\n           (isfree_a : forall (m1 m2 : M) (x : X), (function_of a m1 x = function_of a m2 x -> m1 = m2))\n    : is_mere_relation X (grp_compl_relation X a).\n  Proof.\n    intros.\n    unfold grp_compl_relation.\n    apply (trunc_sigma' _).\n    - intros [m1 p1] [m2 p2]. simpl.\n      apply (contr_inhabited_hprop _).\n      exact (isfree_a m1 m2 x (p1 @ p2^)).\n  Qed.\n\n  (* Lemma relation_is_transitive  *)\n\n  (* Lemma classes_eq_related *)\n\nEnd Monoid_action.\n\nSection Group_Completion_Quotient.\n  Open Scope monoid_scope.\n  Variable M : Symmetric_Monoid.\n  Variable right_cancellation_M : forall l m n : M, m + l = n + l -> m = n.\n  \n  Definition product_action : Monoid_Action M (BuildhSet (M*M)).\n  Proof.\n    srapply (@Build_Monoid_Action).\n    (* The action *)\n    - intro m.\n      intros [a b].\n      exact (m + a, m + b).\n    - intros m1 m2 [x1 x2].\n      apply path_prod; apply mon_assoc.\n    - intros [x1 x2]. apply path_prod; apply mon_lid.\n  Defined.\n  \n  Definition right_cancel_action : forall (m1 m2 : M) (x : M*M),\n      function_of product_action m1 x = function_of product_action m2 x -> m1 = m2.\n  Proof.\n    intros m1 m2 [x1 x2]. simpl.\n    intro p.\n    apply (right_cancellation_M x1).\n    exact (ap fst p).\n  Defined.\n\n  Instance product_action_is_mere : is_mere_relation (M*M) (grp_compl_relation (BuildhSet (M*M)) product_action) :=\n    relation_is_mere (BuildhSet (M*M)) (product_action) right_cancel_action.\n\n  Definition group_completion  :=\n    set_quotient (grp_compl_relation (BuildhSet (M*M)) product_action).\n\n  Definition group_completion_rec (Y : Type) {isset_Y : IsTrunc 0 Y}\n             (f : M -> M -> Y)\n             (cancel_f : forall (s : M) (a b : M),\n                 f a b = f (s + a) (s + b))\n    : group_completion -> Y.\n  Proof.\n    srapply @set_quotient_rec.\n    - intros [a b]. exact (f a b).\n    - intros [a1 b1] [a2 b2].\n      unfold grp_compl_relation. intros [s p].\n      set (pa := (fst ((equiv_path_prod (_,_) (_,_))^-1 p))). simpl in pa. destruct pa.\n      set (pb := (snd ((equiv_path_prod (_,_) (_,_))^-1 p))). simpl in pb. destruct pb. clear p.\n      apply cancel_f.\n  Defined.\n\n  Definition to_groupcompletion' : M -> M -> group_completion.\n  Proof.\n    intros m n. apply class_of.\n    exact (m, n).\n  Defined.\n  \n  Definition lcancel_to_groupcompletion (s a b : M)\n    : to_groupcompletion' a b =\n      to_groupcompletion' (mon_mult s a) (mon_mult s b).\n  Proof.\n    unfold to_groupcompletion'.\n    apply related_classes_eq. simpl.\n    unfold grp_compl_relation. exists s. simpl.\n    reflexivity.\n  Defined.\n\n  Definition group_completion_ind_prop\n             (P : group_completion -> Type)\n             {isprop_P : forall z : group_completion, IsHProp (P z)}\n             (f : forall (a b : M), P (to_groupcompletion' a b))\n    : forall z : group_completion, P z.\n  Proof.\n    apply (@set_quotient_ind_prop _ _ P isprop_P).\n    intros [a b]. exact (f a b).\n  Defined.\n\n\n  Definition grp_compl_mult : group_completion -> group_completion -> group_completion.\n  Proof.\n    srapply @set_quotient_rec2; simpl.\n    - intros [a1 a2] [b1 b2].\n      exact (to_groupcompletion' (a1 + b1) (a2 + b2)).\n      (* apply class_of. *)\n      (* exact (a1 + b1, a2 + b2).  *)\n    - intros [a1 a2] [b1 b2] [c1 c2].\n      intros [s p]. simpl in p.\n      apply related_classes_eq. red.\n      exists s. simpl.\n      apply path_prod; simpl; refine (mon_assoc^ @ _).\n      + apply (ap (fun x => x + c1)). apply (ap fst p).\n      + apply (ap (fun x => x + c2)). apply (ap snd p).\n    - intros [a1 a2] [b1 b2] [c1 c2].\n      intros [s p]. simpl in p.\n      apply related_classes_eq. red.\n      exists s. simpl.\n      apply path_prod; simpl;\n      refine (mon_assoc^ @ _).\n      + refine (ap (fun x => x + b1) mon_sym @ _).\n        refine (mon_assoc @ _).\n        apply (ap (mon_mult a1)). apply (ap fst p).\n      + refine (ap (fun x => x + b2) mon_sym @ _).\n        refine (mon_assoc @ _).\n        apply (ap (mon_mult a2)). apply (ap snd p).\n  Defined.\n\n  Definition grp_compl_inv : group_completion -> group_completion.\n  Proof.\n    srapply group_completion_rec.\n    - intros a b. exact (to_groupcompletion' b a).\n    - intros s a b. simpl.\n      apply lcancel_to_groupcompletion.\n  Defined.\n    \n  (*   srapply @set_quotient_functor. *)\n  (*   - intros [a1 a2]. exact (a2,a1). *)\n  (*   - intros [a1 a2] [b1 b2]. *)\n  (*     intros [s p].  *)\n  (*     exists s. simpl in p. simpl. *)\n  (*     apply path_prod. *)\n  (*     + apply (ap snd p). + apply (ap fst p). *)\n  (* Defined. *)\n\n  Definition grp_compl_linv :\n    forall x : group_completion,\n      grp_compl_mult (grp_compl_inv x) x = to_groupcompletion' mon_id mon_id.\n      (* class_of _ (mon_id,  mon_id). *)\n  Proof.\n    apply group_completion_ind_prop.\n    - intro x.\n      srefine (set_quotient_set (grp_compl_relation (BuildhSet (M * M)) product_action) _ _).\n    - intros a b. simpl.\n      apply inverse.\n      refine (lcancel_to_groupcompletion (a + b) _ _ @ _).\n      apply (ap011 to_groupcompletion');\n        refine (mon_rid _ @ _).\n      +  apply mon_sym. + reflexivity.\n  Defined.\n    \n  (*   apply set_quotient_ind_prop. *)\n  (*   - intro x. *)\n  (*     srefine (set_quotient_set (grp_compl_relation (BuildhSet (M * M)) product_action) _ _). *)\n  (*   - intros [a1 a2]. simpl. *)\n  (*     apply inverse. *)\n  (*     apply related_classes_eq. red. *)\n  (*     exists (a1 + a2). simpl. *)\n  (*     apply path_prod; simpl. *)\n  (*     + refine (mon_rid _ @ _). apply mon_sym. *)\n  (*     + apply mon_rid. *)\n  (* Defined. *)\n\n  Definition grp_compl_rinv :\n    forall x : group_completion,\n      grp_compl_mult x (grp_compl_inv x) = to_groupcompletion' mon_id mon_id.\n      (* class_of _ (mon_id,  mon_id). *)\n  Proof.\n    apply group_completion_ind_prop.\n    - intro x.\n      srefine (set_quotient_set (grp_compl_relation (BuildhSet (M * M)) product_action) _ _).\n    - intros a b. simpl.\n      apply inverse.\n      refine (lcancel_to_groupcompletion (a + b) _ _ @ _).\n      apply (ap011 to_groupcompletion');\n        refine (mon_rid _ @ _).\n      + reflexivity.\n      + apply mon_sym. \n  Defined.\n\n\n    \n  (*   apply set_quotient_ind_prop. *)\n  (*   - intro x. *)\n  (*     srefine (set_quotient_set _ _ _). *)\n  (*   - intros [a1 a2]. simpl. *)\n  (*     apply inverse. *)\n  (*     apply related_classes_eq. red. *)\n  (*     exists (a1 + a2). simpl. *)\n  (*     apply path_prod; simpl. *)\n  (*     + apply mon_rid. *)\n  (*     + refine (mon_rid _ @ _). apply mon_sym. *)\n  (* Defined. *)\n\n  (* Is group *)\n  Definition group_completion_group : Group.\n  Proof.\n    srapply @Build_Group.\n    { srapply @Build_Monoid.\n      - exact (BuildTruncType 0 group_completion).\n      - simpl.\n        apply grp_compl_mult.\n      - simpl.\n        exact (to_groupcompletion' mon_id mon_id).\n        (* apply class_of. *)\n        (* exact (mon_id, mon_id). *)\n      - unfold associative. simpl.\n        apply (group_completion_ind_prop\n                 (fun a : group_completion  => forall b c : group_completion,\n                      grp_compl_mult (grp_compl_mult a b) c = grp_compl_mult a (grp_compl_mult b c))).\n        intros a1 b1.\n        apply (group_completion_ind_prop\n                 (fun b : group_completion => forall c : group_completion,\n                      grp_compl_mult (grp_compl_mult (to_groupcompletion' a1 b1) b) c =\n                      grp_compl_mult (to_groupcompletion' a1 b1) (grp_compl_mult b c))).\n        intros a2 b2.\n        apply (group_completion_ind_prop _).\n        intros a3 b3. simpl.\n        apply (ap011 to_groupcompletion'); apply mon_assoc.\n      - unfold left_identity.\n        apply (group_completion_ind_prop _).\n        intros a b. simpl.\n        apply (ap011 to_groupcompletion'); apply mon_lid.\n      - unfold right_identity.\n        apply (group_completion_ind_prop _).\n        intros a b. simpl.\n        apply (ap011 to_groupcompletion'); apply mon_rid. }\n    - simpl.\n      apply grp_compl_inv.\n    - unfold left_inverse. simpl.\n      apply grp_compl_linv.\n    - unfold right_inverse. simpl.\n      apply grp_compl_rinv.\n  Defined.\n\n  Definition to_groupcompletion : Hom M (group_completion_group).\n  Proof.\n    srapply @Build_Homomorphism.\n    - intro a. apply (to_groupcompletion' a mon_id).\n      (* apply class_of. *)\n      (* exact (a, mon_id). *)\n    - simpl. reflexivity.\n    - simpl. intros a b.\n      apply (ap (to_groupcompletion' (a + b))).\n      apply inverse. apply mon_lid.      \n  Defined.\n\n\n  (* Definition antihom_inv {G : Group} : *)\n  (*   forall (g1 g2 : G), *)\n  (*     grp_inv (g1 + g2) = grp_inv g2 + grp_inv g1. *)\n  (* Proof. *)\n  (*   intros. *)\n  (*   apply grp_moveL_Vg. *)\n  (*   apply grp_moveL_V1. *)\n  (*   refine (mon_assoc^ @ _). *)\n  (*   apply (grp_rinv (g1 + g2)). *)\n  (* Defined. *)\n\n  Definition inverse_precompose_groupcompletion (G : Abelian_Group) :\n    Hom M G -> Hom group_completion_group G.\n  Proof.\n    intro g.\n    srapply @Build_Homomorphism.\n    { srapply @group_completion_rec.\n      - intros a b.\n        exact (g a - g b).\n      - intros s a b. simpl.\n        rewrite preserve_mult. rewrite preserve_mult.\n        rewrite grp_inv_distr.\n        rewrite (grp_sym (a := g s) (b := g a)).\n        rewrite (grp_sym (a := - g b) (b := - g s)).\n        refine (_ @ mon_assoc^).\n        refine (_ @ (ap (fun x => g a + x) mon_assoc)).\n        rewrite grp_rinv. rewrite mon_lid.\n        reflexivity. }\n    + simpl.\n      apply grp_rinv.\n    + intro a. \n      apply (group_completion_ind_prop _). intros a2 b2.\n      revert a.\n      apply (group_completion_ind_prop _). intros a1 b1. simpl.\n      rewrite preserve_mult. rewrite preserve_mult.\n      refine (mon_assoc @ _ @ mon_assoc^).\n      apply (ap (fun x => g a1 + x)).\n      rewrite grp_inv_distr.\n      refine (mon_assoc^ @ _ @ mon_assoc).\n      refine (grp_sym @ _).\n      apply (mon_assoc^).\n  Defined.  \n\n  Definition universal_groupcompletion (G : Abelian_Group) :\n    IsEquiv (fun f : Hom group_completion_group G => compose_hom f to_groupcompletion).\n  Proof.\n    srapply @isequiv_adjointify.\n    - apply inverse_precompose_groupcompletion.\n    - unfold Sect. intro f.\n      apply path_hom. apply path_arrow. intro x. simpl.\n      rewrite preserve_id.\n      rewrite inv_id.\n      apply mon_rid.\n    - unfold Sect.\n      intro g. apply path_hom. apply path_arrow. intro x.  revert x.\n      apply (group_completion_ind_prop _). intros a b. simpl.\n      rewrite <- preserve_inv.\n      rewrite <- preserve_mult. simpl.\n      rewrite mon_rid. rewrite mon_lid. reflexivity.\n  Defined.\n      \n    \n  (* This is more in line with the proof in the thesis *)\n  Definition universal_groupcompletion' (G : Abelian_Group) :\n    IsEquiv (fun f : Hom group_completion_group G => compose_hom f to_groupcompletion).\n  Proof.\n    apply (isequiv_isepi_ismono\n             (BuildhSet (Hom group_completion_group G))\n             (BuildhSet (Hom M G))).\n    - apply issurj_isepi.\n      apply BuildIsSurjection. intro f.\n      apply tr. unfold hfiber.\n      exists (inverse_precompose_groupcompletion G f).\n      apply path_hom. apply path_arrow.\n      intro x. simpl.\n      rewrite preserve_id. rewrite inv_id. apply mon_rid.\n    - apply isinj_ismono.      \n      unfold isinj.\n      intros f g.\n      intro H.\n      apply path_hom. apply path_arrow.\n      intro x. revert x.\n      apply (group_completion_ind_prop _).\n      intros a b.\n      cut (f (to_groupcompletion' a mon_id) - f (to_groupcompletion' b mon_id) =\n           g (to_groupcompletion' a mon_id) - g (to_groupcompletion' b mon_id)).\n      { intro p. refine (_ @ p @ _);\n                   rewrite <- preserve_inv;\n                   rewrite <- preserve_mult;\n                   apply (ap011 (fun x y => _ (to_groupcompletion' x y))).\n           - apply inverse. apply mon_rid.\n           - apply inverse. apply mon_lid.\n           - apply mon_rid.\n           - apply mon_lid. }\n      apply (ap011 (@mon_mult G)).\n      + apply\n          (ap10 (equiv_inverse (path_hom (f oH to_groupcompletion) (g oH to_groupcompletion)) H) a).\n      + apply (ap grp_inv).\n        apply\n          (ap10 (equiv_inverse (path_hom (f oH to_groupcompletion) (g oH to_groupcompletion)) H) b).\n  Defined.\n\nEnd Group_Completion_Quotient.\n\nSection Integers.\n  Definition Integers : Group.\n  Proof.\n    srapply group_completion_group.\n    - apply (Build_Symmetric_Monoid (nat_monoid)).\n      intros a b. simpl.\n      apply nat_plus_comm.\n    (* - simpl. intros l m n. *)\n    (*   intro p. *)\n    (*   apply (nat_lemmas.nat_plus_cancelL l) . *)\n    (*   refine (nat_plus_comm _ _ @ p @ nat_plus_comm _ _). *)\n  Defined.\n\n  Definition nat_to_integer : nat -> Integers.\n  Proof.\n    intro a.\n    apply to_groupcompletion.\n    exact a.\n  Defined.\n\n  Definition integer_to_nat : Integers -> nat.\n  Proof.\n    srapply group_completion_rec.\n    - simpl. intros a b.\n      apply (nat_lemmas.nat_minus b a).\n    - simpl.\n      intros s a b. induction s; try reflexivity.\n      apply IHs.\n  Defined.\n\n  Definition issect_to_groupcompletion (a : nat)\n    : integer_to_nat (nat_to_integer a) = a.\n  Proof.\n    reflexivity.\n  Defined.\n\n  Definition natnat_to_integer : nat -> nat -> Integers.\n  Proof.\n    intros a b.\n    unfold Integers. unfold group_completion_group. simpl.\n    apply (to_groupcompletion').\n    - exact a.\n    - exact b.\n    (* unfold group_completion_quotient.group_completion. *)\n    (* apply (set_quotient.Set_Quotient.class_of). *)\n    (* exact (a, b). *)\n  Defined.\n\n  Definition rcancel_integers (s a b : nat) :\n    natnat_to_integer a b = natnat_to_integer (s + a) (s + b).\n  Proof.\n    apply lcancel_to_groupcompletion.\n  Defined.\n\n  Definition inj_nat_to_integer (a b : nat) (p : nat_to_integer a = nat_to_integer b) : a = b.\n  Proof.\n    refine ((issect_to_groupcompletion a)^ @ _ @ issect_to_groupcompletion b).\n    apply (ap integer_to_nat p).\n  Defined.\n\n  Definition diff_zero (a b : nat) (p : natnat_to_integer a b = nat_to_integer 0) : a = b.\n  Proof.\n    apply inj_nat_to_integer. apply inverse.\n    apply grp_moveL_M1. refine (_ @ p).\n    apply (ap011 natnat_to_integer); simpl.\n    - reflexivity.\n    - apply inverse. apply nat_plus_n_O.\n  Defined.\n\n  (* This definition of integers is equivalent to the other *)\n    (* The function +1 from nat to the positives *)\n  Definition succ_nat_to_pos : nat -> Pos.\n  Proof.\n    intro a. induction a.\n    - exact Int.one.\n    - exact (succ_pos IHa).\n  Defined.\n\n  (* the inclution nat to int *)\n  Definition nat_to_int : nat -> Int.\n  Proof.\n    intro a.\n    destruct a.\n    - exact Int.zero.\n    - exact (pos (succ_nat_to_pos a)).\n  Defined.\n\n  (* the function - on Int *)\n  Definition int_neg : Int -> Int.\n  Proof.\n    intros [n | | p].\n    - exact (pos n).\n    - exact Int.zero.\n    - exact (neg p).\n  Defined.\n\n  (* the function a-b *)\n  Fixpoint nat_int_minus (a b : nat) : Int.\n  Proof.\n    destruct b.\n    (* a-0 = a *)\n    - exact (nat_to_int a).\n    - destruct a.\n      (* 0-(b+1) = -b+1 *)\n      + apply int_neg.\n        exact (nat_to_int b.+1).\n      (* (a+1) - (b+1) = a - b *)\n      + exact (nat_int_minus a b).\n  Defined.\n\n  Definition integers_to_int : Integers -> Int.\n  Proof.\n    srapply (group_completion_rec); simpl.\n    - intros a b. exact (nat_int_minus a b).\n    - intros s a b. simpl.\n      induction s; try reflexivity. apply IHs.\n  Defined.\n\n  (* the function -1 from pos to nat *)\n  Definition pred_pos_to_nat : Pos -> nat.\n  Proof.\n    intro p. induction p.\n    - exact 0.\n    - exact (IHp.+1).\n  Defined.\n    \n  (* The inclusion of positives in the natural numbers *)\n  Definition pos_to_nat (p : Pos) : nat\n    := (pred_pos_to_nat p).+1.\n  (* Proof. *)\n  (*   destruct p as [ | p]. *)\n  (*   - exact 1. *)\n  (*   - exact (pos_to_nat p).+1. *)\n  (* Defined. *)\n\n  Definition int_to_natnat : Int -> nat * nat.\n  Proof.\n    intros [n | | p].\n    - exact (0, pos_to_nat n).\n    - exact (0,0).\n    - exact (pos_to_nat p, 0).\n  Defined.\n\n\n  Definition int_to_integers : Int -> Integers.\n  Proof.\n    intro z.\n    apply natnat_to_integer.\n    - exact (fst (int_to_natnat z)).\n    - exact (snd (int_to_natnat z)).\n  Defined.\n\n  (*   destruct z as [neg | | pos]. *)\n  (*   - apply grp_inv. apply nat_to_integers. *)\n  (*     exact (pos_to_nat neg). *)\n  (*   - exact (nat_to_integers 0). *)\n  (*   - apply nat_to_integers. *)\n  (*     exact (pos_to_nat pos). *)\n  (* Defined. *)\n\n  Definition succ_pred_nat_pos (p : Pos)\n    : succ_nat_to_pos (pred_pos_to_nat p) = p.\n  Proof.\n    induction p; try reflexivity.\n    exact (ap (succ_pos) IHp).\n  Defined.\n\n  Definition pred_succ_nat_pos (a : nat)\n    : pred_pos_to_nat (succ_nat_to_pos a) = a.\n  Proof.\n    induction a; try reflexivity.\n    apply (ap S IHa).\n  Defined.\n\n  (* Fixpoint retr_nat (a b : nat) *)\n  (*   : int_to_integers (integers_to_int (natnat_to_integer a b)) = natnat_to_integer a b. *)\n  (* Proof. *)\n  (*   destruct a, b; simpl; try reflexivity. *)\n  (*   - unfold int_to_integers. simpl. *)\n  (*     apply (ap (natnat_to_int 0)). *)\n  (*     induction b. *)\n  (*     { reflexivity. } apply (ap S IHb). *)\n  (*   - unfold int_to_integers. simpl. *)\n  (*     refine (ap011 natnat_to_int _ idpath). *)\n  (*     induction a. { reflexivity. } apply (ap S IHa). *)\n  (*   - refine (retr_nat a b @ _). *)\n  (*     apply (rcancel_integers 1). *)\n  (* Defined. *)\n\n  Fixpoint retr_int_natnat (a b : nat) :\n    natnat_to_integer\n      (fst (int_to_natnat (nat_int_minus a b)))\n      (snd (int_to_natnat (nat_int_minus a b))) =\n    natnat_to_integer a b.\n  Proof.\n    destruct a, b; try reflexivity; simpl; unfold pos_to_nat.\n    - rewrite pred_succ_nat_pos. reflexivity.\n    - rewrite pred_succ_nat_pos. reflexivity.\n    - refine (retr_int_natnat _ _ @ _).\n      apply (rcancel_integers 1).\n  Defined.\n    \n\n  Definition equiv_integers :\n    Integers <~> Int.\n  Proof.\n    apply (equiv_adjointify integers_to_int int_to_integers).\n    - intro z. simpl. \n      destruct z as [n | | p]; try reflexivity.\n      + destruct n; try reflexivity.\n        simpl. apply (ap neg).\n        apply (ap succ_pos). apply succ_pred_nat_pos.\n      + simpl.\n        apply (ap pos).\n        apply succ_pred_nat_pos.\n    - intro z. revert z.\n      apply (group_completion_ind_prop _ _).\n      simpl. intros a b.\n      unfold int_to_integers.\n      apply retr_int_natnat.\n  Defined.\n\n  Definition nat_to_int_commute \n    : equiv_integers o nat_to_integer == nat_to_int.\n  Proof.\n    intro a. simpl.\n    destruct a; reflexivity.\n  Defined.\nEnd Integers.\n\n\n\n\n\n\n", "meta": {"author": "kalfsvag", "repo": "misc_coq", "sha": "9886ed4eb3dfc077afd1d769c910a729475fa173", "save_path": "github-repos/coq/kalfsvag-misc_coq", "path": "github-repos/coq/kalfsvag-misc_coq/misc_coq-9886ed4eb3dfc077afd1d769c910a729475fa173/basics/group_completion_quotient.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137997, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6568824288548408}}
{"text": "Fixpoint iseven (n:nat): bool.\nProof.\n  induction n.\n  - exact true.\n  - destruct n.\n    * exact false.\n    * exact (iseven n).\nDefined.\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/iseven-proof-mode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.656882426795174}}
{"text": "(****************************************************************************\n                                                                             \n          IEEE754  :  Fmin                                                     \n                                                                             \n          Laurent Thery                                                      \n                                                                             \n  ******************************************************************************)\nRequire Export Zenum.\nRequire Export FPred.\n \nSection FMinMax.\nVariable b : Fbound.\nVariable radix : Z.\nVariable precision : nat.\n \nLet FtoRradix := FtoR radix.\nCoercion FtoRradix : float >-> R.\nHypothesis radixMoreThanOne : (1 < radix)%Z.\n \nLet radixMoreThanZERO := Zlt_1_O _ (Zlt_le_weak _ _ radixMoreThanOne).\nHint Resolve radixMoreThanZERO: zarith.\nHypothesis precisionNotZero : precision <> 0.\nHypothesis pGivesBound : Zpos (vNum b) = Zpower_nat radix precision.\n(* a function that returns a boundd greater than a given nat *)\n \nDefinition boundNat (n : nat) := Float 1%nat (digit radix n).\n \nTheorem boundNatCorrect : forall n : nat, (n < boundNat n)%R.\nintros n; unfold FtoRradix, FtoR, boundNat in |- *; simpl in |- *.\nrewrite Rmult_1_l.\nrewrite <- Zpower_nat_Z_powerRZ; auto with real zarith.\nrewrite INR_IZR_INZ; auto with real zarith.\napply Rle_lt_trans with (Zabs n); [rewrite (Zabs_eq (Z_of_nat n))|idtac];auto with real zarith.\nQed.\n \nTheorem boundBoundNat : forall n : nat, Fbounded b (boundNat n).\nintros n; repeat split; unfold boundNat in |- *; simpl in |- *;\n auto with zarith.\napply vNumbMoreThanOne with (radix := radix) (precision := precision);\n auto with zarith.\napply Zle_trans with 0%Z;[case (dExp b)|idtac]; auto with zarith.\nQed.\n(* A function that returns a bounded greater than a given r *)\n \nDefinition boundR (r : R) := boundNat (Zabs_nat (up (Rabs r))).\n \nTheorem boundRCorrect1 : forall r : R, (r < boundR r)%R.\nintros r; case (Rle_or_lt r 0); intros H'.\napply Rle_lt_trans with (1 := H').\nunfold boundR, boundNat, FtoRradix, FtoR in |- *; simpl in |- *;\n auto with real.\nrewrite Rmult_1_l; auto with real zarith.\napply Rlt_trans with (2 := boundNatCorrect (Zabs_nat (up (Rabs r)))).\nreplace (Rabs r) with r; auto with real.\napply Rlt_le_trans with (r2 := IZR (up r)); auto with real zarith.\ncase (archimed r); auto.\nrewrite INR_IZR_INZ; auto with real zarith.\nunfold Rabs in |- *; case (Rcase_abs r); auto with real.\nintros H'0; Contradict H'0; auto with real.\nQed.\n \nTheorem boundRrOpp : forall r : R, boundR r = boundR (- r).\nintros R; unfold boundR in |- *.\nrewrite Rabs_Ropp; auto.\nQed.\n \nTheorem boundRCorrect2 : forall r : R, (Fopp (boundR r) < r)%R.\nintros r; case (Rle_or_lt r 0); intros H'.\nrewrite boundRrOpp.\npattern r at 2 in |- *; rewrite <- (Ropp_involutive r).\nunfold FtoRradix in |- *; rewrite Fopp_correct.\napply Ropp_lt_contravar; apply boundRCorrect1; auto.\napply Rle_lt_trans with 0%R; auto.\nreplace 0%R with (-0)%R; auto with real.\nunfold FtoRradix in |- *; rewrite Fopp_correct.\napply Ropp_le_contravar.\nunfold boundR, boundNat, FtoRradix, FtoR in |- *; simpl in |- *;\n auto with real zarith.\nrewrite Rmult_1_l; apply Rlt_le; auto with real zarith arith.\nQed.\n(* A function that returns a list containing all the bounded smaller than a given real *)\n \nDefinition mBFloat (p : R) :=\n  map (fun p : Z * Z => Float (fst p) (snd p))\n    (mProd Z Z (Z * Z)\n       (mZlist (- pPred (vNum b)) (pPred (vNum b)))\n       (mZlist (- dExp b) (Fexp (boundR p)))).\n \nTheorem mBFadic_correct1 :\n forall (r : R) (q : float),\n ~ is_Fzero q ->\n (Fopp (boundR r) < q)%R ->\n (q < boundR r)%R -> Fbounded b q -> In q (mBFloat r).\nintros r q.\ncase (Zle_or_lt (Fexp (boundR r)) (Fexp q)); intros H'.\nintros H'0 H'1 H'2 H'3; case H'0.\napply is_Fzero_rep2 with (radix := radix); auto.\nrewrite <-\n FshiftCorrect with (n := Zabs_nat (Fexp q - Fexp (boundR r))) (x := q);\n auto with arith.\napply is_Fzero_rep1 with (radix := radix).\nunfold is_Fzero in |- *.\ncut (forall p : Z, (- 1%nat < p)%Z -> (p < 1%nat)%Z -> p = 0%Z);\n [ intros tmp; apply tmp | idtac ].\nreplace (- 1%nat)%Z with (Fnum (Fopp (boundR r))).\napply Rlt_Fexp_eq_Zlt with (radix := radix); auto with real zarith.\nrewrite FshiftCorrect; auto.\nunfold Fshift in |- *; simpl in |- *.\nrewrite (fun x y => inj_abs (x - y)); auto with zarith.\nsimpl in |- *; auto.\nreplace (Z_of_nat 1) with (Fnum (boundR r)).\napply Rlt_Fexp_eq_Zlt with (radix := radix); auto with zarith.\nrewrite FshiftCorrect; auto.\nunfold Fshift in |- *; simpl in |- *.\nrewrite inj_abs; auto with zarith.\ngeneralize H'; simpl in |- *; auto with zarith.\nsimpl in |- *; auto.\nintros p0; case p0; simpl in |- *; auto with zarith.\nintros H'0 H'1 H'2 H'3; unfold mBFloat in |- *.\nreplace q with\n ((fun p : Z * Z => Float (fst p) (snd p)) (Fnum q, Fexp q)).\napply in_map with (f := fun p : Z * Z => Float (fst p) (snd p));\n auto.\napply mProd_correct; auto.\napply mZlist_correct; auto with float.\napply Zle_Zabs_inv1; auto with float.\nunfold pPred in |- *; apply Zle_Zpred; auto with float.\napply Zle_Zabs_inv2; auto with float.\nunfold pPred in |- *; apply Zle_Zpred; auto with float.\napply mZlist_correct; auto with float.\nauto with zarith.\ncase q; simpl in |- *; auto with zarith.\nQed.\n \nTheorem mBFadic_correct2 : forall r : R, In (boundR r) (mBFloat r).\nintros r; unfold mBFloat in |- *.\nreplace (boundR r) with\n ((fun p : Z * Z => Float (fst p) (snd p))\n    (Fnum (boundR r), Fexp (boundR r))).\napply in_map with (f := fun p : Z * Z => Float (fst p) (snd p));\n auto.\napply mProd_correct; auto.\napply mZlist_correct; auto.\nunfold boundR, boundNat in |- *; simpl in |- *; auto with zarith.\napply Zle_trans with (- (0))%Z; auto with zarith.\napply Zle_Zopp; unfold pPred in |- *; apply Zle_Zpred; simpl in |- *.\napply Zlt_trans with 1%Z; auto with zarith.\napply vNumbMoreThanOne with (3 := pGivesBound); auto.\nunfold boundR, boundNat in |- *; simpl in |- *; auto with zarith.\nunfold pPred in |- *; apply Zle_Zpred; simpl in |- *.\nunfold boundR, boundNat in |- *; simpl in |- *; auto with zarith.\napply vNumbMoreThanOne with (3 := pGivesBound); auto.\napply mZlist_correct; auto.\nunfold boundR, boundNat in |- *; simpl in |- *; auto with zarith.\napply Zle_trans with 0%Z; auto with zarith arith.\ncase (dExp b); auto with zarith.\ncase (boundR r); simpl in |- *; auto with zarith.\ncase (boundR r); simpl in |- *; auto with zarith.\nQed.\n \nTheorem mBFadic_correct3 : forall r : R, In (Fopp (boundR r)) (mBFloat r).\nintros r; unfold mBFloat in |- *.\nreplace (Fopp (boundR r)) with\n ((fun p : Z * Z => Float (fst p) (snd p))\n    (Fnum (Fopp (boundR r)), Fexp (Fopp (boundR r)))).\napply in_map with (f := fun p : Z * Z => Float (fst p) (snd p));\n auto.\napply mProd_correct; auto.\napply mZlist_correct; auto.\nunfold boundR, boundNat in |- *; simpl in |- *; auto with zarith.\nreplace (-1)%Z with (- Z_of_nat 1)%Z; auto with zarith.\napply Zle_Zopp.\nunfold pPred in |- *; apply Zle_Zpred; simpl in |- *.\napply (vNumbMoreThanOne radix) with (precision := precision);\n auto with zarith.\nunfold pPred in |- *; apply Zle_Zpred; simpl in |- *.\nred in |- *; simpl in |- *; auto.\napply mZlist_correct; auto.\nunfold boundR, boundNat in |- *; simpl in |- *; auto with zarith.\napply Zle_trans with 0%Z; auto with zarith.\ncase (dExp b); auto with zarith.\ncase (boundR r); simpl in |- *; auto with zarith.\ncase (boundR r); simpl in |- *; auto with zarith.\nQed.\n \nTheorem mBFadic_correct4 :\n forall r : R, In (Float 0%nat (- dExp b)) (mBFloat r).\nintros p; unfold mBFloat in |- *.\nreplace (Float 0%nat (- dExp b)) with\n ((fun p : Z * Z => Float (fst p) (snd p))\n    (Fnum (Float 0%nat (- dExp b)), Fexp (Float 0%nat (- dExp b)))).\napply in_map with (f := fun p : Z * Z => Float (fst p) (snd p));\n auto.\napply mProd_correct; auto.\napply mZlist_correct; auto.\nsimpl in |- *; auto with zarith.\nreplace 0%Z with (- (0))%Z; [ idtac | simpl in |- *; auto ].\napply Zle_Zopp; unfold pPred in |- *; apply Zle_Zpred.\nred in |- *; simpl in |- *; auto with zarith.\nsimpl in |- *; auto with zarith.\nunfold pPred in |- *; apply Zle_Zpred.\nred in |- *; simpl in |- *; auto with zarith.\napply mZlist_correct; auto.\nsimpl in |- *; auto with zarith.\nunfold boundR, boundNat in |- *; simpl in |- *; auto with zarith.\napply Zle_trans with 0%Z; auto with zarith.\ncase (dExp b); auto with zarith.\nsimpl in |- *; auto with zarith.\nQed.\n \nTheorem mBPadic_Fbounded :\n forall (p : float) (r : R), In p (mBFloat r) -> Fbounded b p.\nintros p r H'; red in |- *; repeat (split; auto).\napply Zpred_Zle_Zabs_intro.\napply mZlist_correct_rev1 with (q := Zpred (Zpos (vNum b)));\n auto with real.\napply\n mProd_correct_rev1\n  with\n    (l2 := mZlist (- dExp b) (Fexp (boundR r)))\n    (C := (Z * Z)%type)\n    (b := Fexp p); auto.\napply\n in_map_inv with (f := fun p : Z * Z => Float (fst p) (snd p));\n auto.\nintros a1 b1; case a1; case b1; simpl in |- *.\nintros z z0 z1 z2 H'0; inversion H'0; auto.\ngeneralize H'; case p; auto.\napply mZlist_correct_rev2 with (p := (- Zpred (Zpos (vNum b)))%Z);\n auto.\napply\n mProd_correct_rev1\n  with\n    (l2 := mZlist (- dExp b) (Fexp (boundR r)))\n    (C := (Z * Z)%type)\n    (b := Fexp p); auto.\napply\n in_map_inv with (f := fun p : Z * Z => Float (fst p) (snd p));\n auto.\nintros a1 b1; case a1; case b1; simpl in |- *.\nintros z z0 z1 z2 H'0; inversion H'0; auto.\ngeneralize H'; case p; auto.\napply mZlist_correct_rev1 with (q := Fexp (boundR r)); auto.\napply\n mProd_correct_rev2\n  with\n    (l1 := mZlist (- pPred (vNum b)) (pPred (vNum b)))\n    (C := (Z * Z)%type)\n    (a := Fnum p); auto.\napply\n in_map_inv with (f := fun p : Z * Z => Float (fst p) (snd p));\n auto.\nintros a1 b1; case a1; case b1; simpl in |- *.\nintros z z0 z1 z2 H'0; inversion H'0; auto.\ngeneralize H'; case p; auto.\nQed.\n(* Some general properties of rounded predicate :\n   -Projector A bounded is rounded to something equal to itself \n  - Monotone : the rounded predicate is monotone *)\n \nDefinition ProjectorP (P : R -> float -> Prop) :=\n  forall p q : float, Fbounded b p -> P p q -> p = q :>R.\n \nDefinition MonotoneP (P : R -> float -> Prop) :=\n  forall (p q : R) (p' q' : float),\n  (p < q)%R -> P p p' -> P q q' -> (p' <= q')%R.\n(* What it is to be a minimum*)\n \nDefinition isMin (r : R) (min : float) :=\n  Fbounded b min /\\\n  (min <= r)%R /\\\n  (forall f : float, Fbounded b f -> (f <= r)%R -> (f <= min)%R).\n(* Min is a projector *)\n \nTheorem isMin_inv1 : forall (p : float) (r : R), isMin r p -> (p <= r)%R.\nintros p r H; case H; intros H1 H2; case H2; auto.\nQed.\n \nTheorem ProjectMin : ProjectorP isMin.\nred in |- *.\nintros p q H' H'0; apply Rle_antisym.\nelim H'0; intros H'1 H'2; elim H'2; intros H'3 H'4; apply H'4; clear H'2;\n auto with real.\napply isMin_inv1 with (1 := H'0); auto.\nQed.\n(* It is monotone *)\n \nTheorem MonotoneMin : MonotoneP isMin.\nred in |- *.\nintros p q p' q' H' H'0 H'1.\nelim H'1; intros H'2 H'3; elim H'3; intros H'4 H'5; apply H'5; clear H'3 H'1;\n auto.\ncase H'0; auto.\napply Rle_trans with p; auto.\napply isMin_inv1 with (1 := H'0); auto.\napply Rlt_le; auto.\nQed.\n(* What it is to be a maximum *)\n \nDefinition isMax (r : R) (max : float) :=\n  Fbounded b max /\\\n  (r <= max)%R /\\\n  (forall f : float, Fbounded b f -> (r <= f)%R -> (max <= f)%R).\n(* It is a projector *)\n \nTheorem isMax_inv1 : forall (p : float) (r : R), isMax r p -> (r <= p)%R.\nintros p r H; case H; intros H1 H2; case H2; auto.\nQed.\n \nTheorem ProjectMax : ProjectorP isMax.\nred in |- *.\nintros p q H' H'0; apply Rle_antisym.\napply isMax_inv1 with (1 := H'0); auto.\nelim H'0; intros H'1 H'2; elim H'2; intros H'3 H'4; apply H'4; clear H'2;\n auto with real.\nQed.\n(* It is monotone *)\n \nTheorem MonotoneMax : MonotoneP isMax.\nred in |- *.\nintros p q p' q' H' H'0 H'1.\nelim H'0; intros H'2 H'3; elim H'3; intros H'4 H'5; apply H'5; clear H'3 H'0.\ncase H'1; auto.\napply Rle_trans with q; auto.\napply Rlt_le; auto.\napply isMax_inv1 with (1 := H'1); auto.\nQed.\n(* Minimun is defined upto equality *)\n \nTheorem MinEq :\n forall (p q : float) (r : R), isMin r p -> isMin r q -> p = q :>R.\nintros p q r H' H'0; apply Rle_antisym.\nelim H'0; intros H'1 H'2; elim H'2; intros H'3 H'4; apply H'4; clear H'2 H'0;\n auto.\ncase H'; auto.\napply isMin_inv1 with (1 := H'); auto.\nelim H'; intros H'1 H'2; elim H'2; intros H'3 H'4; apply H'4; clear H'2 H';\n auto.\ncase H'0; auto.\napply isMin_inv1 with (1 := H'0); auto.\nQed.\n(* Maximum is defined upto equality *)\n \nTheorem MaxEq :\n forall (p q : float) (r : R), isMax r p -> isMax r q -> p = q :>R.\nintros p q r H' H'0; apply Rle_antisym.\nelim H'; intros H'1 H'2; elim H'2; intros H'3 H'4; apply H'4; clear H'2 H';\n auto.\ncase H'0; auto.\napply isMax_inv1 with (1 := H'0); auto.\nelim H'0; intros H'1 H'2; elim H'2; intros H'3 H'4; apply H'4; clear H'2 H'0;\n auto.\ncase H'; auto.\napply isMax_inv1 with (1 := H'); auto.\nQed.\n(* Min and Max are related *)\n \nTheorem MinOppMax :\n forall (p : float) (r : R), isMin r p -> isMax (- r) (Fopp p).\nintros p r H'; split.\napply oppBounded; case H'; auto.\nsplit.\nunfold FtoRradix in |- *; rewrite Fopp_correct.\napply Ropp_le_contravar; apply isMin_inv1 with (1 := H'); auto.\nintros f H'0 H'1.\nrewrite <- (Fopp_Fopp f).\nunfold FtoRradix in |- *; rewrite Fopp_correct; rewrite Fopp_correct.\napply Ropp_le_contravar.\nelim H'.\nintros H'2 H'3; elim H'3; intros H'4 H'5; apply H'5; clear H'3.\napply oppBounded; case H'; auto.\nrewrite <- (Ropp_involutive r).\nunfold FtoRradix in |- *; rewrite Fopp_correct; auto with real.\nQed.\n(* Max and Min are related *)\n \nTheorem MaxOppMin :\n forall (p : float) (r : R), isMax r p -> isMin (- r) (Fopp p).\nintros p r H'; split.\napply oppBounded; case H'; auto.\nsplit.\nunfold FtoRradix in |- *; rewrite Fopp_correct.\napply Ropp_le_contravar; apply isMax_inv1 with (1 := H'); auto.\nintros f H'0 H'1.\nrewrite <- (Fopp_Fopp f).\nunfold FtoRradix in |- *; repeat rewrite Fopp_correct.\napply Ropp_le_contravar.\nrewrite <- (Fopp_correct radix f).\nelim H'.\nintros H'2 H'3; elim H'3; intros H'4 H'5; apply H'5; clear H'3.\napply oppBounded; auto.\nrewrite <- (Ropp_involutive r).\nunfold FtoRradix in |- *; rewrite Fopp_correct; auto with real.\nQed.\n(* If I have a strict min I can get a max using FNSucc *)\n \nTheorem MinMax :\n forall (p : float) (r : R),\n isMin r p -> r <> p :>R -> isMax r (FNSucc b radix precision p).\nintros p r H' H'0.\nsplit.\napply FcanonicBound with (radix := radix); auto with float.\napply FNSuccCanonic; auto.\ninversion H'; auto.\nsplit.\ncase (Rle_or_lt (FNSucc b radix precision p) r); intros H'2; auto.\nabsurd (FNSucc b radix precision p <= p)%R.\napply Rlt_not_le.\nunfold FtoRradix in |- *; apply FNSuccLt; auto.\ninversion H'; auto.\nelim H0; intros H'1 H'3; apply H'3; auto.\napply FcanonicBound with (radix := radix); auto with float.\napply Rlt_le; auto.\nintros f H'2 H'3.\nreplace (FtoRradix f) with (FtoRradix (Fnormalize radix b precision f)).\nunfold FtoRradix in |- *; apply FNSuccProp; auto.\ninversion H'; auto.\napply FcanonicBound with (radix := radix); auto with float.\napply Rlt_le_trans with r; auto.\ncase (Rle_or_lt r p); auto.\nintros H'4; Contradict H'0.\napply Rle_antisym; auto; apply isMin_inv1 with (1 := H'); auto.\nrewrite FnormalizeCorrect; auto.\nunfold FtoRradix in |- *; apply FnormalizeCorrect; auto.\nQed.\n(* Find a minimun in a given list if it exists *)\n \nTheorem MinExList :\n forall (r : R) (L : list float),\n (forall f : float, In f L -> (r < f)%R) \\/\n (exists min : float,\n    In min L /\\\n    (min <= r)%R /\\ (forall f : float, In f L -> (f <= r)%R -> (f <= min)%R)).\nintros r L; elim L; simpl in |- *; auto.\nleft; intros f H'; elim H'.\nintros a l H'.\nelim H';\n [ intros H'0; clear H'\n | intros H'0; elim H'0; intros min E; elim E; intros H'1 H'2; elim H'2;\n    intros H'3 H'4; try exact H'4; clear H'2 E H'0 H' ].\ncase (Rle_or_lt a r); intros H'1.\nright; exists a; repeat split; auto.\nintros f H'; elim H';\n [ intros H'2; rewrite <- H'2; clear H' | intros H'2; clear H' ];\n auto with real.\nintros H'; Contradict H'; auto with real.\napply Rlt_not_le; auto with real.\nleft; intros f H'; elim H';\n [ intros H'2; rewrite <- H'2; clear H' | intros H'2; clear H' ]; \n auto.\ncase (Rle_or_lt a min); intros H'5.\nright; exists min; repeat split; auto.\nintros f H'; elim H';\n [ intros H'0; rewrite <- H'0; clear H' | intros H'0; clear H' ]; \n auto.\ncase (Rle_or_lt a r); intros H'6.\nright; exists a; repeat split; auto.\nintros f H'; elim H';\n [ intros H'0; rewrite <- H'0; clear H' | intros H'0; clear H' ];\n auto with real.\nintros H'; apply Rle_trans with (FtoRradix min); auto with real.\nright; exists min; split; auto; split; auto.\nintros f H'; elim H';\n [ intros H'0; elim H'0; clear H' | intros H'0; clear H' ]; \n auto.\nintros H'; Contradict H'6; auto with real.\napply Rle_not_lt; auto.\nQed.\n \nTheorem MinEx : forall r : R, exists min : float, isMin r min.\nintros r.\ncase (MinExList r (mBFloat r)).\nintros H'0; absurd (Fopp (boundR r) <= r)%R; auto.\napply Rlt_not_le.\napply H'0.\napply mBFadic_correct3; auto.\n(* A minimum always exists *)\napply Rlt_le.\napply boundRCorrect2; auto.\nintros H'0; elim H'0; intros min E; elim E; intros H'1 H'2; elim H'2;\n intros H'3 H'4; clear H'2 E H'0.\nexists min; split; auto.\napply mBPadic_Fbounded with (r := r); auto.\nsplit; auto.\nintros f H'0 H'2.\ncase (Req_dec f 0); intros H'6.\nreplace (FtoRradix f) with (FtoRradix (Float 0%nat (- dExp b))).\napply H'4; auto.\napply mBFadic_correct4; auto.\nreplace (FtoRradix (Float 0%nat (- dExp b))) with (FtoRradix f); auto.\nrewrite H'6.\nunfold FtoRradix, FtoR in |- *; simpl in |- *; auto with real.\nrewrite H'6.\nunfold FtoRradix, FtoR in |- *; simpl in |- *; auto with real.\ncase (Rle_or_lt f (Fopp (boundR r))); intros H'5.\napply Rle_trans with (FtoRradix (Fopp (boundR r))); auto.\napply H'4; auto.\napply mBFadic_correct3; auto.\napply Rlt_le.\napply boundRCorrect2; auto.\ncase (Rle_or_lt (boundR r) f); intros H'7.\nContradict H'2; apply Rlt_not_le.\napply Rlt_le_trans with (FtoRradix (boundR r)); auto.\napply boundRCorrect1; auto.\napply H'4; auto.\napply mBFadic_correct1; auto.\nContradict H'6; unfold FtoRradix in |- *; apply is_Fzero_rep1; auto.\nQed.\n \nTheorem MaxEx : forall r : R, exists max : float, isMax r max.\nintros r; case (MinEx r).\nintros x H'.\ncase (Req_dec x r); intros H'1.\nexists x.\nrewrite <- H'1.\nred in |- *; split; [ case H' | split ]; auto with real.\n(* A maximum always exists *)\nexists (FNSucc b radix precision x).\napply MinMax; auto.\nQed.\n \nTheorem MinBinade :\n forall (r : R) (p : float),\n Fbounded b p ->\n (p <= r)%R -> (r < FNSucc b radix precision p)%R -> isMin r p.\nintros r p H' H'0 H'1.\nsplit; auto.\nsplit; auto.\nintros f H'2 H'3.\ncase (Rle_or_lt f p); auto; intros H'5.\nContradict H'3.\n(* If we are between a bound and its successor, it is our minimum *)\napply Rlt_not_le.\napply Rlt_le_trans with (1 := H'1); auto with real.\nreplace (FtoRradix f) with (FtoRradix (Fnormalize radix b precision f)).\nunfold FtoRradix in |- *; apply FNSuccProp; auto; try apply FnormalizeCanonic;\n auto.\nunfold FtoRradix in |- *; repeat rewrite FnormalizeCorrect; auto with real.\napply FcanonicBound with (radix := radix); auto.\napply FnormalizeCanonic; auto.\nunfold FtoRradix in |- *; rewrite FnormalizeCorrect; auto with real.\nunfold FtoRradix in |- *; rewrite FnormalizeCorrect; auto with real.\nQed.\n \nTheorem FminRep :\n forall p q : float,\n isMin p q -> exists m : Z, q = Float m (Fexp p) :>R.\nintros p q H'.\nreplace (FtoRradix q) with (FtoRradix (Fnormalize radix b precision q)).\n2: unfold FtoRradix in |- *; apply FnormalizeCorrect; auto.\ncase (Zle_or_lt (Fexp (Fnormalize radix b precision q)) (Fexp p)); intros H'1.\nexists (Fnum p).\nunfold FtoRradix in |- *; apply FSuccZleEq with (3 := pGivesBound); auto.\n(* A min of a float is always represnetable with the same exposant *)\nreplace (Float (Fnum p) (Fexp p)) with p; [ idtac | case p ]; auto.\nreplace (FtoR radix (Fnormalize radix b precision q)) with (FtoR radix q);\n [ idtac | rewrite FnormalizeCorrect ]; auto.\napply isMin_inv1 with (1 := H'); auto.\nreplace (FSucc b radix precision (Fnormalize radix b precision q)) with\n (FNSucc b radix precision q); [ idtac | case p ]; \n auto.\nreplace (Float (Fnum p) (Fexp p)) with p; [ idtac | case p ]; auto.\ncase (Req_dec p q); intros Eq0.\nunfold FtoRradix in Eq0; rewrite Eq0.\napply FNSuccLt; auto.\ncase (MinMax q p); auto.\nintros H'2 H'3; elim H'3; intros H'4 H'5; clear H'3.\ncase H'4; auto.\nintros H'0; absurd (p <= q)%R; rewrite H'0; auto.\napply Rlt_not_le; auto.\nunfold FtoRradix in |- *; apply FNSuccLt; auto.\ninversion H'.\nelim H0; intros H'3 H'6; apply H'6; clear H0; auto.\nrewrite <- H'0; auto with real.\nexists\n (Fnum\n    (Fshift radix (Zabs_nat (Fexp (Fnormalize radix b precision q) - Fexp p))\n       (Fnormalize radix b precision q))).\npattern (Fexp p) at 2 in |- *;\n replace (Fexp p) with\n  (Fexp\n     (Fshift radix\n        (Zabs_nat (Fexp (Fnormalize radix b precision q) - Fexp p))\n        (Fnormalize radix b precision q))).\nunfold FtoRradix in |- *;\n rewrite <-\n  FshiftCorrect\n                with\n                (n := \n                  Zabs_nat (Fexp (Fnormalize radix b precision q) - Fexp p))\n               (x := Fnormalize radix b precision q).\ncase\n (Fshift radix (Zabs_nat (Fexp (Fnormalize radix b precision q) - Fexp p))\n    (Fnormalize radix b precision q)); auto.\nauto with arith.\nsimpl in |- *; rewrite inj_abs; auto with zarith.\nQed.\n \nTheorem MaxBinade :\n forall (r : R) (p : float),\n Fbounded b p ->\n (r <= p)%R -> (FNPred b radix precision p < r)%R -> isMax r p.\nintros r p H' H'0 H'1.\nrewrite <- (Ropp_involutive r).\nrewrite <- (Fopp_Fopp p).\napply MinOppMax.\napply MinBinade; auto with real float.\nunfold FtoRradix in |- *; rewrite Fopp_correct; auto with real.\n(* Same for max *)\nrewrite <- (Fopp_Fopp (FNSucc b radix precision (Fopp p))).\nrewrite <- FNPredFopFNSucc; auto.\nunfold FtoRradix in |- *; rewrite Fopp_correct; auto with real arith.\nQed.\n \nTheorem MaxMin :\n forall (p : float) (r : R),\n isMax r p -> r <> p :>R -> isMin r (FNPred b radix precision p).\nintros p r H' H'0.\nrewrite <- (Fopp_Fopp (FNPred b radix precision p)).\nrewrite <- (Ropp_involutive r).\napply MaxOppMin.\nrewrite FNPredFopFNSucc; auto.\nrewrite Fopp_Fopp; auto.\n(* Taking the pred of a max we get a min *)\napply MinMax; auto.\napply MaxOppMin; auto.\nContradict H'0.\nrewrite <- (Ropp_involutive r); rewrite H'0; auto; unfold FtoRradix in |- *;\n rewrite Fopp_correct; auto; apply Ropp_involutive.\nQed.\n \nTheorem FmaxRep :\n forall p q : float,\n isMax p q -> exists m : Z, q = Float m (Fexp p) :>R.\nintros p q H'; case (FminRep (Fopp p) (Fopp q)).\nunfold FtoRradix in |- *; rewrite Fopp_correct.\napply MaxOppMin; auto.\nintros x H'0.\nexists (- x)%Z.\nrewrite <- (Ropp_involutive (FtoRradix q)).\n(* The max of a float can be represented with the same exposant *)\nunfold FtoRradix in |- *; rewrite <- Fopp_correct.\nunfold FtoRradix in H'0; rewrite H'0.\nunfold FtoR in |- *; simpl in |- *; auto with real.\nrewrite Ropp_Ropp_IZR; rewrite Ropp_mult_distr_l_reverse; auto.\nQed.\n \nEnd FMinMax.\nHint Resolve ProjectMax MonotoneMax MinOppMax MaxOppMin MinMax MinBinade\n  MaxBinade MaxMin: float.\n", "meta": {"author": "coq-contribs", "repo": "float", "sha": "b3bfbd67f7be553f169a5b257a848ea13654bbb3", "save_path": "github-repos/coq/coq-contribs-float", "path": "github-repos/coq/coq-contribs-float/float-b3bfbd67f7be553f169a5b257a848ea13654bbb3/Fmin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6568824257094661}}
{"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(** * powerfix: bounded fixpoint operator *)\n\n(** we define a fixpoint operator which recursively unfolds an\n   open-recursive function with recursive depth at most [2^n], for\n   arbitrary [n].  This allows us to define arbitrary recursive\n   functions, without needing to prove their termination. The operator\n   is defined in a computationally efficient way. (We already used\n   such a trick in ATBR ; it's simplified here thanks to the\n   introduction of eta in Coq v8.4 *)\n\nRequire Import common.\nSet Implicit Arguments.\n\nSection powerfix.\n\nVariables A B: Type.\nNotation Fun := (A -> B).\n\n(** the three following functions \"iterate\" their [f] argument lazily: \n   iteration stops whenever [f] no longer makes recursive calls.\n   - [powerfix' n f k] iterates [f] at most [(2^n-1)] times and then yields to [k] \n   - [powerfix n f k] iterates [f] at most [(2^n)] times and then yields to [k] \n   - [linearfix n f k] iterates [f] at most [n] times and then yields to [k] \n   *)\nFixpoint powerfix' n (f: Fun -> Fun) (k: Fun): Fun := \n  fun a => match n with O => k a | S n => f (powerfix' n f (powerfix' n f k)) a end.\nDefinition powerfix n f k a := f (powerfix' n f k) a.\n\nFixpoint linearfix n (f: Fun -> Fun) (k: Fun): Fun :=\n  fun a => match n with O => k a | S n => f (linearfix n f k) a end.\n\n(** simple lemmas about [2^n]  *)\nLemma pow2_S n: pow2 n = S (pred (pow2 n)).\nProof. induction n. reflexivity. simpl. now rewrite IHn. Qed.\n\nLemma pred_pow2_Sn n: pred (pow2 (S n)) = S (double (pred (pow2 n))).\nProof. simpl. now rewrite pow2_S. Qed.\n\n(** characterisation of [powerfix] with [linearfix] *)\nSection linear_carac.\n\n Variable f: Fun -> Fun.\n\n Lemma linearfix_S: forall n k, \n   f (linearfix n f k) = linearfix n f (f k).\n Proof. induction n; intros k; simpl. reflexivity. now rewrite IHn. Qed.\n\n Lemma linearfix_double: forall n k, \n   linearfix n f (linearfix n f k) = linearfix (double n) f k.\n Proof. \n   induction n; intros k. reflexivity. simpl linearfix.\n   now rewrite <-IHn, <-linearfix_S. \n Qed.\n\n Lemma powerfix'_linearfix: forall n k, \n   powerfix' n f k = linearfix (pred (pow2 n)) f k.\n Proof.\n   induction n; intros. reflexivity.\n   rewrite pred_pow2_Sn. simpl. \n   now rewrite <-linearfix_double, 2IHn.\n Qed.\n\n Theorem powerfix_linearfix: forall n k, \n   powerfix n f k = linearfix (pow2 n) f k.\n Proof. intros. unfold powerfix. now rewrite powerfix'_linearfix, pow2_S. Qed.\n\nEnd linear_carac.\n\n(** [powerfix_invariant] gives an induction principle for [powerfix],\n   that does not care about the number of iterations -- in particular,\n   the trivial \"emptyfix\" function : ([fun f k a => k a]) satisfies\n   the same induction principle, so that this can only be used to\n   reason about partial correctness. *)\nSection invariant.\n Variable P: Fun -> Prop.\n\n Lemma powerfix_invariant: forall n f g, \n   (forall k, P k -> P (f k)) -> P g -> P (powerfix n f g).\n Proof. \n   intros n f g Hf Hg. apply Hf. \n   revert g Hg. induction n; intros g Hg; simpl; auto. \n Qed.\n\nEnd invariant.\n\nEnd powerfix.\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/powerfix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478913248044, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.6568760632545103}}
{"text": "Require Export P04.\n\n\n\n(* Hint: \n\n   First study the chapter \"Auto.v\".\n\n   Using [;], [try] and [eauto], you can prove it in 7 lines thanks to:. \n     Hint Constructors bstep.\n\n   You can use the following intro pattern:\n     destruct ... as [[? | ?] | [? ?]].\n*)\n\nHint Constructors aval.\nHint Constructors bstep.\n\nTheorem bexp_strong_progress: forall st b,\n  (b = BTrue \\/ b = BFalse) \\/\n  exists b', b / st ==>b b'.\nProof.\n  intros st b.\n  induction b; eauto; try (destruct (aexp_strong_progress st a); destruct (aexp_strong_progress st a0); destruct H; destruct H0; subst; eauto).\n  - destruct IHb; destruct H; subst; eauto.\n  - destruct IHb1; destruct IHb2; destruct H; destruct H0; subst; eauto. \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/10/P05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673359709795, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.6568514375302996}}
{"text": "From Cat Require Import Imports Category Preorder Monoid Poset Isomorphism \nTerminal Dual Initial Product CoProduct Exponential CCC IPL STLC.\nRequire Import FunctionalExtensionality.\nRequire Import ProofIrrelevance.\nRequire Import Coq.Lists.List.\nRequire Import JMeq.\nRequire Import Coq.Program.Equality.\nSet Universe Polymorphism.\nLocal Open Scope list_scope.\n\nClass Functor (C D: Category): Type :=\n  mk_Functor\n  {\n    fobj            : @obj C -> @obj D;\n    fmap            : forall {a b: @obj C} (f: arrow b a), arrow (fobj b) (fobj a);\n    fmapP           :> forall x y, Proper (eq ==> eq) (@fmap x y);\n    preserve_id     : forall {a: @obj C}, fmap (@identity C a) = (@identity D (fobj a));\n    preserve_comp   : forall {a b c: @obj C} (g : @arrow C c b) (f: @arrow C b a),\n                        fmap (g o f) = (fmap g) o (fmap f)\n  }.\nCheck Functor.\n\nNotation \" C → D \" := (Functor C D) (at level 40, left associativity).\n\nArguments fmap {_} {_} _ _ _ _.\nArguments fobj {_} {_} _ _.\n\n(** sameness of Functors using heterogenous (John Major's) equality *)\nLemma F_split: forall (C D: Category) (F G: Functor C D),\n                 fobj F = fobj G -> JMeq (fmap F) (fmap G) -> F = G.\nProof.\n    destruct F; destruct G; cbn; intros; subst. f_equal.\n    now destruct (proof_irrelevance _ fmapP0 fmapP1).\n    now destruct (proof_irrelevance _ preserve_id0 preserve_id1).\n    now destruct (proof_irrelevance _ preserve_comp0 preserve_comp1).\nDefined.\n\n(** sameness of Functors, inspired by Amin Timany *)\nLemma F_splitA: forall\n                (C D  : Category)\n                (F G  : Functor C D)\n                (ObjEq: (fobj F) = (fobj G)),\n                ((fun a b => \n                    match ObjEq in _ = V return ((arrow b a) -> (arrow (V b) (V a))) with\n                     | eq_refl => (fmap F a b)\n                    end) = fmap G) -> F = G.\nProof.\n    destruct F; destruct G; simpl; intros; subst; f_equal.\n    now destruct (proof_irrelevance _ fmapP0 fmapP1).\n    now destruct (proof_irrelevance _ preserve_id0 preserve_id1).\n    now destruct (proof_irrelevance _ preserve_comp0 preserve_comp1).\nDefined.\n\n(** sameness of Functors using heterogenous (John Major's) equality *)\nLemma F_splitR: forall (C D: Category) (F G: Functor C D),\n                 F = G -> fobj F = fobj G /\\ JMeq (fmap F) (fmap G).\nProof. intros. subst. easy. Qed.\n\nDefinition Forgetful1: Functor Mon SetCat.\nProof. unshelve econstructor.\n       - intros (M, e, Mf, Mob1, Mob2, Mob3).\n         exact M.\n       - simpl.\n         intros (M1, e1, M1f, M1ob1, M1ob2, M1ob3).\n         intros (M2, e2, M2f, M2ob1, M2ob2, M2ob3).\n         intros (f, fax1, fax2).\n         exact f.\n       - simpl. repeat intro. now subst.\n       - simpl.\n         intros (M, e, Mf, Mob1, Mob2, Mob3).\n         simpl. reflexivity.\n       - simpl.\n         intros (M1, e1, M1f, M1ob1, M1ob2, M1ob3).\n         intros (M2, e2, M2f, M2ob1, M2ob2, M2ob3).\n         intros (M3, e3, M3f, M3ob1, M3ob2, M3ob3).\n         intros (f, fax1, fax2).\n         intros (g, gax1, gax2).\n         reflexivity.\nDefined.\n\nDefinition Forgetful2: Functor PreOrderCat SetCat.\nProof. unshelve econstructor.\n       - intros (pos, le, r, t).\n         exact pos.\n       - intros (pos1, le1, r1, t1) (pos2, le2, r2, t2).\n         intros (f, fax).\n         simpl in *. exact f.\n       - simpl. repeat intro. now subst.\n       - intros (pos, le, r, t).\n         simpl. reflexivity.\n       - intros (pos1, le1, r1, t1) (pos2, le2, r2, t2) (pos3, le3, r3, t3) (f, fax) (g, gax).\n         simpl. reflexivity.\nDefined.\n\nDefinition FreeMonoidPar (A: Set): Monoid.\nProof. unshelve econstructor.\n       - exact (list A).\n       - exact nil.\n       - intros xs ys. exact (xs ++ ys).\n       - intros. simpl. rewrite app_assoc. reflexivity.\n       - simpl. intro xs. reflexivity.\n       - simpl. intro xs. rewrite app_nil_r. reflexivity.\nDefined.\n\nDefinition FreeMonoidFunctor: Functor SetCat Mon.\nProof. unshelve econstructor.\n       - intro A. simpl in *.\n         exact (FreeMonoidPar A).\n       - simpl. intros A B f.\n         unshelve econstructor.\n         + simpl. intro l. \n           exact (map f l).\n         + simpl. reflexivity.\n         + simpl. intros x y.\n           rewrite map_app.\n           reflexivity.\n       - simpl. repeat intro. now subst.\n       - simpl. intro A.\n         apply MonoidMapEq.\n         simpl.\n         apply functional_extensionality.\n         intro l.\n         rewrite map_id.\n         reflexivity.\n       - simpl. intros A B C g f.\n         apply MonoidMapEq.\n         simpl.\n         apply functional_extensionality.\n         intro l.\n         rewrite map_map.\n         reflexivity.\nDefined.\n\nDefinition Compose_Functors (C D E: Category) \n                            (F    : Functor C D) \n                            (G    : Functor D E): (Functor C E).\nProof. unshelve econstructor.\n       - exact (fun a => fobj G (fobj F a)).\n       - intros. exact ((((@fmap D E G _ _\n                               (@fmap C D F a b f))))).\n       - repeat intro. subst. easy.\n       - intros. simpl.  \n         now rewrite (@preserve_id C D F), (@preserve_id D E G).\n       - intros. simpl.\n         now rewrite (@preserve_comp C D F), (@preserve_comp D E G).\nDefined.\n\nArguments Compose_Functors {_} {_} {_} _ _.\n\nDefinition IdFunctor {C: Category}: Functor C C.\nProof. unshelve econstructor.\n       - exact id.\n       - unfold id. intros. exact f.\n       - repeat intro. easy.\n       - intros. now destruct C.\n       - intros. now destruct C.\nDefined.\n\nDefinition Id {C: Category}: @Functor C C.\nProof. refine (@mk_Functor C C id (fun a b f => f) _ _ _);\n       intros; now unfold id.\nDefined.\n\n\nDefinition iProdFunctor: forall (C: Category) (X: @obj C) (hp: hasProducts C), Functor C C.\nProof. intros C X hp.\n       unshelve econstructor.\n       - intro A.\n         exact (@pobj C hp A X).\n       - simpl. intros A B f.\n         exact (@fprod C hp A X B X f (identity X)).\n       - repeat intro. now subst.\n       - simpl. intro A.\n         unfold fprod. simpl.\n         rewrite !identity_f.\n         unfold prod_f.\n         destruct (hasp A X).\n         simpl.\n         specialize (prod_f_uni (pobj A X) pi1 pi2 (identity (pobj A X))).\n         apply prod_f_uni.\n         + rewrite f_identity. reflexivity.\n\n         + rewrite f_identity. reflexivity.\n       - simpl. intros a b c g f.\n         specialize (@fprod_distr C hp b c X X a X g (identity X) f (identity X)); intro H.\n         destruct hp as (pobj, hasp).\n         rewrite f_identity in H.\n         rewrite <- H. reflexivity.\nDefined.\n\nDefinition iExpFunctor: forall (C: Category) (X: @obj C) (hp: hasProducts C) (he: hasExponentials C hp), Functor C C.\nProof. intros C X hp he.\n       unshelve econstructor.\n       - intro A.\n         destruct hp as (pobj, hasp).\n         destruct he as (eobj, hase).\n         exact (eobj X A).\n       - simpl. intros A B f.\n         specialize (@fExp C hp he A B X f); intro fX.\n         destruct he as (eobj, hase).\n(*       specialize (@Exponential.app C hp X A (eobj X A) (hase X A)); intro app.\n         specialize (@Exponential.cur C hp X B (eobj X B) (hase X B) (eobj X A) ); intro fx. *)\n         destruct hp as (pobj, hasp).\n         simpl in *.\n         exact fX.\n       - simpl. repeat intro. now subst.\n       - simpl. intro A.\n         destruct hp as (pobj, hasp).\n         destruct he as (eobj, hase).\n         unfold fExp.\n         simpl. rewrite identity_f.\n         destruct ( hase X A ).\n         simpl in *.\n         specialize (curuni (eobj X A) app (identity (eobj X A))).\n         rewrite curuni.\n         + reflexivity.\n         + rewrite fprod_id, f_identity. reflexivity.\n       - simpl. intros a b c g f.\n         specialize (@fExpDistributes C hp he a b c X f g); intro H.\n         destruct hp as (pobj, hasp).\n         destruct he as (eobj, hase).\n         destruct ( hase X c ).\n         destruct ( hase X b ).\n         destruct ( hase X a ).\n         simpl in *.\n         exact H.\nDefined.\n\nDefinition ContravariantFunctor (C D: Category) := Functor (DualCategory C) D.\n\nDefinition iExpContravariantFunctor: forall (C: Category) (X: @obj C) (hp: hasProducts C) (he: hasExponentials C hp), ContravariantFunctor C C.\nProof. intros C X hp he.\n       unshelve econstructor.\n       - intro A.\n         destruct hp as (pobj, hasp).\n         destruct he as (eobj, hase).\n         exact (eobj A X).\n       - simpl. intros A B f.\n         specialize (@Expf C hp he B A X f); intro fX.\n         destruct he as (eobj, hase).\n(*       specialize (@Exponential.app C hp X A (eobj X A) (hase X A)); intro app.\n         specialize (@Exponential.cur C hp X B (eobj X B) (hase X B) (eobj X A) ); intro fx. *)\n         destruct hp as (pobj, hasp).\n         simpl in *.\n         exact fX.\n       - simpl. repeat intro. now subst.\n       - simpl. unfold Expf, fprod. intro A.\n         specialize (prod_f_id C (eobj A X) A  (pobj (eobj A X) A) (hasp (eobj A X) A) ); intro h.\n         destruct hp as (pobj, hasp).\n         destruct he as (eobj, hase).\n         simpl in *.\n         destruct ( hase A X ).\n         simpl in *.\n         destruct ( hasp (eobj A X) A ).\n         simpl in *.\n         specialize (curuni (eobj A X) (app o prod_f (pobj (eobj A X) A) (identity (eobj A X) o pi1) (identity A o pi2)) \n                                       (identity (eobj A X))).\n         rewrite curuni.\n         + reflexivity.\n         + rewrite fprod_id, f_identity, !identity_f.\n           unfold fprod in curcomm.\n           simpl in *.\n           rewrite h, f_identity. reflexivity.\n       - simpl. intros a b c g f.\n         specialize (@ExpfDistributes C hp he c b a X g f); intro H.\n         destruct hp as (pobj, hasp).\n         destruct he as (eobj, hase).\n         destruct ( hase X c ).\n         destruct ( hase X b ).\n         destruct ( hase X a ).\n         simpl in *.\n         exact H.\nDefined.\n\nModule ME.\n\nContext (S: @obj SetCat).\n\nDefinition FunctorF: Functor SetCat SetCat.\nProof. specialize (hasProductsSetCat); intros (pobj, H).\n       unshelve econstructor.\n       - simpl. intro X.\n         exact (prod S X).\n       - simpl. intros X Y f.\n         exact (@fprod SetCat hasProductsSetCat _ _ _ _ (identity S) f); intro h.\n       - repeat intro. now subst.\n       - simpl. intros X.\n         unfold fprod.\n         simpl.\n         apply functional_extensionality.\n         intros (s, x).\n         reflexivity.\n       - simpl. intros X Y Z g f.\n         unfold fprod.\n         simpl.\n         apply functional_extensionality.\n         intros (s, x).\n         reflexivity.\nDefined.\n\nDefinition FunctorG: Functor SetCat SetCat.\nProof. specialize (hasProductsSetCat); intros (pobj, H).\n       unshelve econstructor.\n       - simpl. intro X.\n         exact (prod X S).\n       - simpl. intros X Y f.\n         exact (@fprod SetCat hasProductsSetCat _ _ _ _ f (identity S)); intro h.\n       - repeat intro. now subst.\n       - simpl. intros X.\n         unfold fprod.\n         simpl.\n         apply functional_extensionality.\n         intros (x, s).\n         reflexivity.\n       - simpl. intros X Y Z g f.\n         unfold fprod.\n         simpl.\n         apply functional_extensionality.\n         intros (x, s).\n         reflexivity.\nDefined.\n\nLemma IsoFXGX: forall (X: @obj SetCat), @Isomorphic SetCat (@fobj SetCat SetCat FunctorF X) (@fobj SetCat SetCat FunctorG X).\nProof. intro X.\n       unshelve econstructor.\n       - simpl. intros (s, x).\n         exact (x, s).\n       - unshelve econstructor.\n         + simpl. intros (x, s).\n           exact (s, x).\n         + simpl. apply functional_extensionality.\n           intros (x, s).\n           reflexivity.\n         + simpl. apply functional_extensionality.\n           intros (s, x).\n           reflexivity.\nQed.\n\nEnd ME.\n\n(** Associativity of functor composition *)\nLemma FunctorCompositionAssoc: forall {D C B A : Category} \n  (F : Functor C D) (G : Functor B C) (H : Functor A B),\n  Compose_Functors H (Compose_Functors G F) = Compose_Functors (Compose_Functors H G) F.\nProof. intros.\n       apply F_split.\n       - easy.\n       - apply eq_dep_id_JMeq, EqdepFacts.eq_sigT_iff_eq_dep, \n         eq_existT_uncurried; cbn.\n         now exists (eq_refl \n         (forall a b : obj, arrow b a ->\n           arrow (fobj F (fobj G (fobj H b))) (fobj F (fobj G (fobj H a))))).\nDefined.\n\n(** Identity functors cancels on the right *)\nLemma ComposeIdr: forall {C D: Category} (F: Functor C D),\n  Compose_Functors F IdFunctor = F.\nProof. intros.\n       apply F_split.\n       - easy.\n       - apply eq_dep_id_JMeq, EqdepFacts.eq_sigT_iff_eq_dep, \n         eq_existT_uncurried; cbn.\n       unfold id in *.\n       now exists (eq_refl \n       (forall a b : obj, arrow b a -> arrow (fobj F b) (fobj F a))).\nDefined.\n\n(** Identity functors cancels on the left *)\nLemma ComposeIdl: forall {C D: Category} (F: Functor C D),\n  Compose_Functors IdFunctor F = F.\nProof. intros.\n       apply F_split.\n       - easy.\n       - apply eq_dep_id_JMeq, EqdepFacts.eq_sigT_iff_eq_dep, \n         eq_existT_uncurried; cbn.\n       unfold id in *.\n       now exists (eq_refl \n       (forall a b : obj, arrow b a -> arrow (fobj F b) (fobj F a))).\nDefined.\n\n(** the 2-category Cat *)\nDefinition Cat: Category.\nProof. unshelve econstructor.\n       - exact Category.\n       - intros C D. exact (Functor D C).\n       - intro C. cbn in *. exact (@IdFunctor C).\n       - intros C D E F G. exact (Compose_Functors G F).\n       - repeat intro. now subst.\n       - intros A B C D F G H. cbn in *.\n         symmetry. \n         exact (FunctorCompositionAssoc H G F).\n       - intros C D F. exact (ComposeIdr F).\n       - intros D C F. exact (ComposeIdl F).\nDefined.\n\nDefinition sObjSetCat: @obj SetCat.\nProof. simpl. exact unit. Defined.\n\nDefinition sArrowSetCat: @arrow SetCat sObjSetCat sObjSetCat.\nProof. simpl. intro a. exact a. Defined.\n\nLemma SingletonCat: Category.\nProof. unshelve econstructor.\n       - exact unit.\n       - intros a b. exact unit.\n       - simpl. intros. exact tt.\n       - simpl. intros. exact tt.\n       - repeat intro. now subst.\n       - simpl. intros. reflexivity.\n       - simpl. intros. destruct f. reflexivity.\n       - simpl. intros. destruct f. reflexivity.\nDefined.\n\nLemma hasTerminalCat: hasTerminal Cat.\nProof. unshelve econstructor.\n       - simpl. exact SingletonCat.\n       - unshelve econstructor.\n         + simpl. intro C.\n           unshelve econstructor.\n           ++ simpl. intro a.\n              exact tt.\n           ++ simpl. intros. exact tt.\n           ++ simpl. repeat intro. now subst.\n           ++ simpl. intros. reflexivity.\n           ++ simpl. intros. reflexivity. \n         + simpl. intro C.\n           intros F G.\n           apply F_split.\n           ++ destruct F, G. simpl in *.\n              extensionality x.\n              destruct (fobj0 x), (fobj1 x).\n              reflexivity.\n           ++ destruct F, G. simpl in *.\n              apply eq_dep_id_JMeq, EqdepFacts.eq_sigT_iff_eq_dep, \n              eq_existT_uncurried; cbn.\n              exists eq_refl.\n              simpl.\n              extensionality a.\n              extensionality b.\n              extensionality f.\n              destruct (fmap0 a b f), (fmap1 a b f).\n              reflexivity.\nQed.\n\nDefinition ProductCategory (C D: Category): Category.\nProof. unshelve econstructor.\n         + simpl in *. exact (@obj C * @obj D)%type.\n         + simpl. intros (x, y) (x', y').\n           exact ((@arrow C x x') * (@arrow D y y'))%type.\n         + simpl. intros (x, y).\n           exact ((identity x), (identity y)).\n         + simpl. intros (a, b) (c, d) (i, j) (f1, f2) (g1, g2).\n           split.\n           ++ exact (f1 o g1).\n           ++ exact (f2 o g2).\n         + simpl. repeat intro. now subst.\n         + simpl. intros (a, b) (c, d) (i, j) (f1, f2) (g1, g2) (h1, h2) (k1, k2).\n           f_equal.\n           ++ rewrite assoc. reflexivity.\n           ++ rewrite assoc. reflexivity.\n         + simpl. intros (a, b) (c, d) (f, g).\n           f_equal.\n           ++ rewrite identity_f. reflexivity.\n           ++ rewrite identity_f. reflexivity.\n         + simpl. intros (a, b) (c, d) (f, g).\n           f_equal.\n           ++ rewrite f_identity. reflexivity.\n           ++ rewrite f_identity. reflexivity.\nDefined.\n\nDefinition ProductFunctor {A B C D: Category} (F: Functor A B) (G: Functor C D):\n Functor (ProductCategory A C) (ProductCategory B D).\nProof. unshelve econstructor.\n       - intros (a, c).\n         exact (fobj F a, fobj G c).\n       - intros (a, c) (b, d) (f, g).\n         exact (fmap F a b f, fmap G c d g).\n       - repeat intro. now subst.\n       - intros (a, c). simpl.\n         rewrite !preserve_id.\n         reflexivity.\n       - simpl. intros (a, d) (b, e) (c, f) (g1, g2) (f1, f2).\n         rewrite !preserve_comp.\n         reflexivity.\nDefined.\n\nLemma Fpi1 (A B: Category): Functor (ProductCategory A B) A.\nProof. unshelve econstructor. \n            +++ intros (a, b). exact a.\n            +++ intros (a, b) (c, d) (f, g). exact f.\n            +++ repeat intro. now subst.\n            +++ intros (a, b). reflexivity.\n            +++ intros (a, b) (c, d) (i, j) (f1, f2) (g1, g2).\n                reflexivity.\nDefined.\n\nLemma Fpi2 (A B: Category): Functor (ProductCategory A B) B.\nProof.   unshelve econstructor. \n            +++ intros (a, b). exact b.\n            +++ intros (a, b) (c, d) (f, g). exact g.\n            +++ repeat intro. now subst.\n            +++ intros (a, b). reflexivity.\n            +++ intros (a, b) (c, d) (i, j) (f1, f2) (g1, g2).\n                reflexivity.\nDefined.\n\nDefinition DualFunctor {C D: Category} (F: Functor C D): Functor (DualCategory C) (DualCategory D).\nProof. unshelve econstructor.\n       - intro a. exact (fobj F a).\n       - intros a b f. simpl.\n         exact (fmap F _ _ f).\n       - repeat intro. now subst.\n       - intros. simpl.\n         now rewrite preserve_id.\n       - intros. simpl.\n         now rewrite preserve_comp.\nDefined.\n\nClass Full {C D: Category} (F : Functor C D): Type := \n{\n  fmap_surj: forall {x y} (f g: arrow (fobj F y) (fobj F x)), \n    exists (f: arrow y x), fmap F _ _ f = g\n}.\n\nClass Faithful {C D: Category} (F : Functor C D): Type := \n{\n  fmap_inj: forall {x y} (f g: arrow y x), fmap F _ _ f = fmap F _ _ g -> f = g\n}.\n\nLemma PC1 (A B C: Category) (F: Functor C A) (G: Functor C B): Functor C (ProductCategory A B).\nProof.      destruct A, B, C, F, G.\n            unshelve econstructor.\n            +++ simpl in *.\n                intro a.\n                exact ((fobj0 a), (fobj1 a)).\n            +++ simpl in *.\n                intros a b f.\n                exact ((fmap0 a b f), (fmap1 a b f)).\n            +++ repeat intro. now subst.\n            +++ simpl in *.\n                intro a.\n                rewrite preserve_id0, preserve_id1.\n                reflexivity.\n            +++ simpl in *. intros a b c f g.\n                rewrite preserve_comp0, preserve_comp1.\n                reflexivity.\nDefined.\n\nDefinition pco (A B: Category) (a: @obj A) (b: @obj B): @obj (ProductCategory A B).\nProof. exact (a, b). Defined.\n\nDefinition pca (A B: Category) (a b: @obj A) (c d: @obj B) (f: arrow b a) (g: arrow d c): @arrow (ProductCategory A B) (b, d) (a, c).\nProof. exact (f, g). Defined.\n\nLemma Afst: forall (A B: Category) (a b: @obj A) (c d: @obj B) (f h: arrow b a) (g: arrow d c),\n  fmap (Fpi1 A B) (a, c) (b, d) (f, g) = fmap (Fpi1 A B) (a, c) (b, d) (h, g) -> f = h.\nProof. unfold Fpi1.\n       intros.\n       simpl in H.\n       easy.\nDefined.\n\nLemma Fpi1_id: forall (A B: Category) (a b: @obj A) (c d: @obj B) (f h: arrow b a) (g: arrow d c),\n  fmap (Fpi1 A B) (a, c) (b, d) (f, g) = f.\nProof. unfold Fpi1.\n       intros.\n       simpl.\n       easy.\nDefined.\n\nLemma fst_snd: forall (A B: Category) (a b: @obj A) (c d: @obj B)  (f h: @arrow (ProductCategory A B) (b, d) (a, c)),\n  fmap (Fpi1 A B) (a, c) (b, d) f = fmap (Fpi1 A B) (a, c) (b, d) h ->\n  fmap (Fpi2 A B) (a, c) (b, d) f = fmap (Fpi2 A B) (a, c) (b, d) h -> f = h.\nProof. unfold Fpi1, Fpi2.\n       intros.\n       simpl in *.\n       simpl in H, H0.\n       destruct f.\n       destruct h.\n       subst.\n       easy.\nDefined.\n\nArguments fmap {_} {_} _ {_} {_} _.\nLemma hasProductsCat: hasProducts Cat.\nProof. unshelve econstructor.\n       - simpl. intros C D.\n         exact (ProductCategory C D).\n       - simpl. intros.\n         unshelve econstructor.\n         ++ simpl.\n            exact (Fpi1 A B).\n         ++ simpl.\n            exact (Fpi2 A B).\n         ++ simpl. intros C F G.\n            exact (PC1 A B C F G).\n         ++ simpl. intros C F G.\n            destruct A, B, C, F, G.\n            simpl in *.\n            apply F_split.\n            +++ simpl. reflexivity.\n            +++ apply eq_dep_id_JMeq, EqdepFacts.eq_sigT_iff_eq_dep, \n                eq_existT_uncurried; cbn.\n                exists eq_refl.\n                simpl.\n                reflexivity.\n         ++ simpl. intros C F G.\n            destruct A, B, C, F, G.\n            apply F_split.\n            +++ simpl. reflexivity.\n            +++ apply eq_dep_id_JMeq, EqdepFacts.eq_sigT_iff_eq_dep, \n                eq_existT_uncurried; cbn.\n                exists eq_refl.\n                simpl. reflexivity.\n         ++ simpl. intros C F G H K L.\nAdmitted.\n\n\n\n\n", "meta": {"author": "ekiciburak", "repo": "CatTheo", "sha": "f80ac2700ca09eaff5c1bd6addcbf9ca2fdbb2fd", "save_path": "github-repos/coq/ekiciburak-CatTheo", "path": "github-repos/coq/ekiciburak-CatTheo/CatTheo-f80ac2700ca09eaff5c1bd6addcbf9ca2fdbb2fd/Functor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.6568514305326734}}
{"text": "Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(*******************************************************************************\n An efficient construction technique for balanced binary trees from lists:\n - This method can preserves the order of elements, and\n - All recursions used in this methods are structural.\n*******************************************************************************)\n\n(* Implementation 1: for binary trees with labeled leaves *)\n\nInductive tree (A : Type) := tbin of tree A & tree A | tsingle of A.\n\nModule Construction_1.\n\nSection Definitions.\n\nVariable (A : Type).\n\nFixpoint push (t : tree A) (ts : seq (option (tree A))) :\n  seq (option (tree A)) :=\n  match ts with\n    | [::] as ts' | None :: ts' => Some t :: ts'\n    | Some t' :: ts' => None :: push (tbin t' t) ts'\n  end.\n\nFixpoint pop (t : tree A) (ts : seq (option (tree A))) : tree A :=\n  match ts with\n    | [::] => t\n    | None :: ts' => pop t ts'\n    | Some t' :: ts' => pop (tbin t' t) ts'\n  end.\n\nFixpoint rep_push (ts : seq (option (tree A))) (xs : seq A) (x : A) :\n  tree A :=\n  match xs with\n    | [::] => pop (tsingle x) ts\n    | x' :: xs' => rep_push (push (tsingle x) ts) xs' x'\n  end.\n\nDefinition construct (xs : seq A) : option (tree A) :=\n  match xs with\n    | [::] => None\n    | x :: xs => Some (rep_push [::] xs x)\n  end.\n\nEnd Definitions.\n\nNotation \"#< x >\" := (tsingle x) (at level 75).\nNotation \"l ## r\" := (tbin l r) (at level 75, no associativity).\n\nEval compute in (construct (iota 0 30)).\nEval compute in (construct (iota 0 31)).\nEval compute in (construct (iota 0 32)).\nEval compute in (construct (iota 0 33)).\nEval compute in (construct (iota 0 34)).\n\nEnd Construction_1.\n\n\n(* Implementation 2: for binary trees with labeled nodes *)\n\nInductive tree' (A : Type) := tnode of tree' A & A & tree' A | tnil.\n\nArguments tnil {A}.\n\nModule Construction_2.\n\nSection Definitions.\n\nVariable (A : Type).\n\nFixpoint push (t : tree' A) (x : A) (ts : seq (option (tree' A * A))) :\n  seq (option (tree' A * A)) :=\n  match ts with\n    | [::] as ts' | None :: ts' => Some (t, x) :: ts'\n    | Some (t', x') :: ts' => None :: push (tnode t' x' t) x ts'\n  end.\n\nFixpoint pop (t : tree' A) (ts : seq (option (tree' A * A))) : tree' A :=\n  match ts with\n    | [::] => t\n    | None :: ts' => pop t ts'\n    | Some (t', x') :: ts' => pop (tnode t' x' t) ts'\n  end.\n\nFixpoint rep_push (ts : seq (option (tree' A * A))) (xs : seq A) : tree' A :=\n  match xs with\n    | [::] => pop tnil ts\n    | [:: x] => pop (tnode tnil x tnil) ts\n    | x :: x' :: xs' => rep_push (push (tnode tnil x tnil) x' ts) xs'\n  end.\n\nDefinition construct (xs : seq A) : tree' A := rep_push [::] xs.\n\nEnd Definitions.\n\nNotation \"l #< x ># r\" := (tnode l x r) (at level 75, no associativity).\n\nEval compute in (construct (iota 0 29)).\nEval compute in (construct (iota 0 30)).\nEval compute in (construct (iota 0 31)).\nEval compute in (construct (iota 0 32)).\nEval compute in (construct (iota 0 33)).\n\nEnd Construction_2.\n", "meta": {"author": "pi8027", "repo": "efficient-finfun", "sha": "205c380e0ea7c9a238e129ddba126c085709ca4c", "save_path": "github-repos/coq/pi8027-efficient-finfun", "path": "github-repos/coq/pi8027-efficient-finfun/efficient-finfun-205c380e0ea7c9a238e129ddba126c085709ca4c/theories/misc/bintree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.6568514248498634}}
{"text": "\n\n\n(* -------------------------Description--------------------------------------\n\n   In this file we capture the notion of ordType. This type has\n   elements with decidable equality. This is almost same and inspired by\n   ssreflect library.  \n   We also connect natural numbers and booleans to this type by creating\n   canonical instances nat_eqType and bool_eqType. \n \n\n   Structure type: Type:=  Pack {\n                             E: Type;\n                             eqb: E-> E -> bool;\n                             eqP: forall x y, reflect (eq x y)(eqb x y) }.\n\n \n  Notation \"x == y\":= (@Decidable.eqb _ x y)(at level 70, no associativity).\n\n \n\n  Some important results are:\n  \n  Lemma eqP  (T:ordType)(x y:T): reflect (x=y)(eqb  x y). \n  Lemma nat_eqP (x y:nat): reflect (x=y)(Nat.eqb x y).\n\n  Canonical nat_eqType: eqType:=\n                              {| Decidable.E:= nat; Decidable.eqb:= Nat.eqb;\n                                  Decidable.eqP:= nat_eqP |}.\n\n  Lemma bool_eqP (x y:bool): reflect (x=y)(Bool.eqb x y). \n  \n  Canonical bool_eqType: eqType:= \n                             {| Decidable.E:= bool; Decidable.eqb:= Bool.eqb;\n                                  Decidable.eqP:= bool_eqP |}.\n\n  \n   ------------------------------------------------------------------------- *)\n\nFrom Coq Require Export ssreflect  ssrbool. \nRequire Export  GenReflect Omega.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule Decidable.\n  Structure type: Type:= Pack {\n                             E: Type;\n                             eqb: E-> E -> bool;\n                             eqP: forall x y, reflect (eq x y)(eqb x y) }.\n  Module Exports.\n    Coercion E : type >-> Sortclass.\n    Notation eqType:= type.\n    End Exports.\nEnd Decidable.\nExport Decidable.Exports.\n\nNotation \"x == y\":= (@Decidable.eqb _ x y)(at level 70, no associativity): bool_scope.\n\n\n\nLemma eqP  (T:eqType)(x y:T): reflect (x=y)(x == y). \nProof. apply Decidable.eqP. Qed.\n\n\nHint Resolve eqP: core.\n\nLemma eq_to_eqb (T:eqType)(x y:T): (x=y)-> (x == y).\nProof.  intro; apply /eqP; auto. Qed.\nLemma eqb_to_eq (T:eqType) (x y:T): (x == y)-> (x=y).\nProof. intro;apply /eqP; auto. Qed.\n\nHint Immediate eq_to_eqb eqb_to_eq: core.\n\nLemma eq_refl (T: eqType)(x:T): x == x.\nProof. apply /eqP; auto. Qed.\nLemma eq_symm (T: eqType)(x y:T): (x == y)=(y == x).\nProof. { case (x== y) eqn:H1; case ( y== x) eqn:H2;  try(auto).\n       { assert (H3: x=y). apply /eqP;auto.\n         rewrite H3 in H2; rewrite eq_refl in H2; inversion H2. }\n       { assert (H3: y= x). apply /eqP; auto.\n         rewrite H3 in H1; rewrite eq_refl in H1; inversion H1.  } } Qed.\n\nHint Resolve eq_refl eq_symm: core.\n\n(*--------- Natural numbers as an instance of eqType---------------------*)\n\nLemma nat_eqb_ref (x:nat): Nat.eqb x x = true.\nProof. induction x;simpl;auto. Qed.\nHint Resolve nat_eqb_ref:core.\n\nLemma nat_eqb_elim (x y:nat):  Nat.eqb x y -> x = y.\nProof. { revert y. induction x.\n       { intro y. case y. tauto. simpl; intros n H; inversion H. }\n       intro y. case y. simpl; intro H; inversion H. simpl. eauto. } Qed.\nHint Resolve nat_eqb_elim: core.\n\nLemma nat_eqb_intro (x y:nat): x=y -> Nat.eqb x y.\nProof. intro H. subst x. eauto. Qed.\nHint Resolve nat_eqb_intro: core.\n\nLemma nat_eqP (x y:nat): reflect (x=y)(Nat.eqb x y).\nProof. apply reflect_intro.  split; eauto. Qed. \nHint Resolve nat_eqP: core.\n\n\nCanonical nat_eqType: eqType:= {| Decidable.E:= nat; Decidable.eqb:= Nat.eqb;\n                                  Decidable.eqP:= nat_eqP |}.\n\n(*--------- Bool as an instance of eqType --------------------------------*)\nLemma bool_eqb_ref (x:bool): Bool.eqb x x = true.\nProof. destruct x; simpl; auto. Qed.\nHint Resolve bool_eqb_ref: core.\n\nLemma bool_eqb_elim (x y:bool): (Bool.eqb x y) -> x = y.\nProof. destruct x; destruct y; simpl; try (auto || tauto). Qed.\n\nLemma bool_eqb_intro (x y:bool): x = y -> (Bool.eqb x y).\nProof. intros; subst y; destruct x; simpl; auto. Qed.\n\nHint Immediate bool_eqb_elim bool_eqb_intro: core.\n\nLemma bool_eqP (x y:bool): reflect (x=y)(Bool.eqb x y).\nProof. apply reflect_intro.\n       split. apply bool_eqb_intro. apply bool_eqb_elim. Qed.\nHint Resolve bool_eqP: core.\n\nCanonical bool_eqType: eqType:= {| Decidable.E:= bool; Decidable.eqb:= Bool.eqb;\n                                  Decidable.eqP:= bool_eqP |}.\n\nLtac conflict_eq :=\n    match goal with\n    | H:  (?x == ?x)= false  |- _\n      => switch_in H; cut(False);[tauto |auto]\n    | H: ~(is_true (?x == ?x)) |- _\n      => cut(False);[tauto |auto]             \n    | H: ~ (?x = ?x) |- _\n      => cut(False);tauto\n    | H: (?x == ?y) = true, H1: ?x <> ?y |- _\n      => absurd (x = y);auto\n    | H:  is_true (?x == ?y), H1: ?x <> ?y |- _\n      => absurd (x = y);auto                     \n    | H: (?x == ?y) = true, H1: ?y <> ?x |- _\n      => absurd (y = x);[auto | (symmetry;auto)]\n    | H: is_true (?x == ?y), H1: ?y <> ?x |- _\n      => absurd (y = x);[auto | (symmetry;auto)]                     \n    | H: (?x == ?y) = false, H1: ?x = ?y |- _\n      => switch_in H; absurd (x=y); auto\n    | H: (?x == ?y) = false, H1: ?y = ?x |- _\n      => switch_in H; symmetry in H1; absurd (x=y); auto\n    end.\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/DecType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6568514229712542}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Essentials.HoTT_Facts.\nRequire Import Category.Main.\n\n\n(**\nFro categories C and C', a functor F : C -> C' consists of an arrow map from objects of C to objects of C' and an arrow map from arrows of C to arrows of C' such that an arrow h : a -> b is mapped to (F h) : F a -> F b.\n\nFurthermore, we require functors to map identitiies to identities. Additionally, the immage of the coposition of two arrows must be the same as composition of their images.\n*)\nRecord Functor (C C' : Category) : Type := \n{\n  (** Object map *)\n  FO : C → C';\n\n  (** Arrow map *)\n  FA : ∀ {a b}, (a –≻ b)%morphism → ((FO a) –≻ (FO b))%morphism;\n\n  (** Mapping of identities *)\n  F_id : ∀ c, FA (id c) = id (FO c);\n  \n  (** Functor commuting with composition *)\n  F_compose : ∀ {a b c} (f : (a –≻ b)%morphism) (g : (b –≻ c)%morphism),\n      (FA (g ∘ f) = (FA g) ∘ (FA f))%morphism\n\n  (* F_id and F_compose together state the fact that functors are morphisms of categories (preserving the structure of categories!)*)\n}.\n\nArguments FO {_ _} _ _.\nArguments FA {_ _} _ {_ _} _, {_ _} _ _ _ _.\nArguments F_id {_ _} _ _.\nArguments F_compose {_ _} _ {_ _ _} _ _.\n\nNotation \"C –≻ D\" := (Functor C D) : functor_scope.\n\nBind Scope functor_scope with Functor.\n\nNotation \"F '_o'\" := (FO F) : object_scope.\n\nNotation \"F '@_a'\" := (@FA _ _ F) : morphism_scope.\n\nNotation \"F '_a'\" := (FA F) : morphism_scope.\n\nHint Extern 2 => (apply F_id).\n\nLocal Open Scope morphism_scope.\nLocal Open Scope object_scope.\n\nLtac Functor_Simplify :=\n  progress\n    (\n      repeat rewrite F_id;\n      (\n        repeat\n          match goal with\n          | [|- ?F _a ?A = id (?F _o ?x)] =>\n            (rewrite <- F_id; (cbn+idtac))\n          | [|- (id (?F _o ?x)) = ?F _a ?A] =>\n            (rewrite <- F_id; (cbn+idtac))\n          | [|- ?F _a ?A ∘ ?F _a ?B = ?F _a ?C ∘ ?F _a ?D] =>\n            (repeat rewrite <- F_compose; (cbn+idtac))\n          | [|- ?F _a ?A ∘ ?F _a ?B = ?F _a ?C] =>\n            (rewrite <- F_compose; (cbn+idtac))\n          | [|- ?F _a ?C = ?F _a ?A ∘ ?F _a ?B] =>\n            (rewrite <- F_compose; (cbn+idtac))\n          | [|- context [?F _a ?A ∘ ?F _a ?B]] =>\n            (rewrite <- F_compose; (cbn+idtac))\n          end\n      )\n    )\n.\n\nHint Extern 2 => Functor_Simplify.\n\nSection Functor_eq_simplification.\n\n  Context {C C' : Category} (F G : (C –≻ C')%functor).\n  \n  (** Two functors are equal if their object maps and arrow maps are. *)\n  Lemma Functor_eq_simplify (Oeq : F _o = G _o) :\n    ((fun x y => match Oeq in _ = V return ((x –≻ y) → ((V x) –≻ (V y)))%morphism with idpath => F  @_a x y end) = G @_a) -> F = G.\n  Proof.\n    destruct F as [Fo Fa Fi Fc]; destruct G as [Go Ga Gi Gc].\n    basic_simpl.\n    ElimEq.\n    doHomPIR.\n    trivial.\n  Defined.\n\n  (** Extensionality for arrow maps of functors. *)\n  Theorem FA_extensionality (Oeq : F _o = G _o) :\n    (\n      ∀ (a b : Obj)\n        (h : (a –≻ b)%morphism),\n        (\n          fun x y =>\n            match Oeq in _ = V return\n                  ((x –≻ y) → ((V x) –≻ (V y)))%morphism\n            with\n              idpath => F  @_a x y\n            end\n        ) _ _ h = G _a h\n    )\n    →\n    (\n      fun x y =>\n        match Oeq in _ = V return\n              ((x –≻ y) → ((V x) –≻ (V y)))%morphism\n        with\n          idpath => F  @_a x y\n        end\n    ) = G @_a.\n  Proof.\n    auto.\n  Defined.\n  \n  (** Fucntor extensionality: two functors are equal of their object maps are equal and their arrow maps are extensionally equal. *)\n  Lemma Functor_extensionality (Oeq : F _o = G _o) :\n    (\n      ∀ (a b : Obj) (h : (a –≻ b)%morphism),\n        (\n          fun x y =>\n            match Oeq in _ = V return\n                  ((x –≻ y) → ((V x) –≻ (V y)))%morphism\n            with\n              idpath => F  @_a x y\n            end\n        ) _ _ h = G _a h\n    ) → F = G.\n  Proof.\n    intros H.\n    apply (Functor_eq_simplify Oeq); trivial.\n    apply FA_extensionality; trivial.\n  Defined.\n\nEnd Functor_eq_simplification.\n\nHint Extern 2 => Functor_Simplify.\n\nLtac Func_eq_simpl :=\n  match goal with\n    [|- ?A = ?B :> Functor _ _] =>\n    (apply (Functor_eq_simplify A B (idpath : A _o = B _o)%object)) +\n    (cut (A _o = B _o)%object; [\n       let u := fresh \"H\" in\n       intros H;\n         apply (Functor_eq_simplify A B H)\n         |\n    ])\n  end.\n\nHint Extern 3 => Func_eq_simpl.\n\n\nLemma f_equal_Functor_eq_simplify_Oeq\n      {C C' : Category} (F G : (C –≻ C')%functor)\n      (Oeq : F _o = G _o)\n      (H : (fun x y =>\n              match Oeq in _ = V return\n                    ((x –≻ y) → ((V x) –≻ (V y)))%morphism\n              with\n                idpath => F  @_a x y\n              end\n           ) = G @_a\n      )\n  :\n    f_equal FO (Functor_eq_simplify _ _ Oeq H) = Oeq\n.\nProof.\n  destruct F as [Fo Fa Fi Fc]; destruct G as [Go Ga Gi Gc].\n  cbn in *.\n  destruct Oeq.\n  destruct H.\n  doHomPIR.\n  cbn.\n  repeat rewrite (@contr _ _ idpath).\n  trivial.\nQed.\n\n(** Given two categories C and D if the objects of D form a HSet then the type of functors\nC –≻ D also form a HSet.\n\nWe prove this by estabilishing a left inverse for the Functor_extensionality and showing that\nthe codomain type of Functor extensionenatilty forms a HSet.\n*)\nSection CoDom_Cat_HSet_Functor_HSet.\n  Context\n    (C D : Category)\n    {DHS : IsHSet D}\n  .\n\n  Lemma Functor_extensionality_inv\n        {F G : Functor C D}\n        (HO : F _o = G _o)\n        (H : F = G)\n    :\n      (\n        ∀ (a b : Obj) (h : (a –≻ b)%morphism),\n          (\n            fun x y =>\n              match HO in _ = V return\n                    ((x –≻ y) → ((V x) –≻ (V y)))%morphism\n              with\n                idpath => F  @_a x y\n              end\n          ) _ _ h = G _a h\n      ).\n  Proof.\n    destruct H.\n    match type of HO with\n      ?A = ?B =>\n      match type of A with\n        ?U =>\n        let H := fresh \"H\" in\n        assert (H : IsHSet U);\n          [\n            repeat (apply @trunc_forall; [typeclasses eauto|intros ?x]);\n            refine DHS\n          |\n          rewrite (@center _ (H _ _ HO idpath)); clear H\n          ]\n      end\n    end.\n    trivial.\n  Defined.    \n  \n  Theorem Functor_extensionality_inv_is_left_inverse\n          (F G : Functor C D)\n          (HO : F _o = G _o)\n          (H : F = G)\n    :\n      Functor_extensionality _ _ HO (Functor_extensionality_inv HO H) = H\n  .\n  Proof.\n    destruct H.\n    match type of HO with\n      ?A = ?B =>\n      match type of A with\n        ?U =>\n        let H := fresh \"H\" in\n        assert (H : IsHSet U);\n          [\n            repeat (apply @trunc_forall; [typeclasses eauto|intros ?x]);\n            refine DHS\n          |\n          rewrite (@center _ (H _ _ HO idpath)); clear H\n          ]\n      end\n    end.\n    unfold Functor_extensionality; unfold FA_extensionality.\n    match goal with\n      [|- _ _ _ _ ?A = _] =>\n      generalize A as H'\n    end.\n    intros H'.\n    match type of H' with\n      ?A = ?B =>\n      match type of A with\n        ?U =>\n        let H := fresh \"H\" in\n        assert (H : IsHSet U);\n          [\n            repeat (apply @trunc_forall; [typeclasses eauto|intros ?x]);\n            refine (Hom_HSet)\n          |\n          rewrite (@center _ (H _ _ H' idpath)); clear H H'\n          ]\n      end\n    end.\n    cbn.\n    repeat rewrite (@contr _ _ idpath).\n    trivial.\n  Qed.\n    \n  Theorem CoDom_Cat_HSet_Functor_HSet : IsHSet (Functor C D).\n  Proof.\n    intros f g H1 H2.\n    destruct H1.\n    cbn in *.\n    assert\n      (\n        Hc :\n          IsHProp\n            (\n               ∀ (a b : Obj) (h : (a –≻ b)%morphism),\n                 (\n                   fun x y =>\n                     match f_equal FO H2 in _ = V return\n                           ((x –≻ y) → ((V x) –≻ (V y)))%morphism\n                     with\n                       idpath => f  @_a x y\n                     end\n                 ) _ _ h = f _a h\n            )\n      ).\n    {\n      repeat (apply @trunc_forall; [typeclasses eauto|intros ?x]);\n      refine (Hom_HSet _ _).\n    }\n    {\n      apply\n        (\n          @left_inv_equi_trunc\n            (f = f)\n            _\n            _\n            Hc\n            (Functor_extensionality_inv (f_equal FO H2))\n            (Functor_extensionality _ _ (f_equal FO H2))\n            (Functor_extensionality_inv_is_left_inverse _ _ (f_equal FO H2))\n            idpath\n            H2\n        ).\n    }\n  Qed.\n\nEnd CoDom_Cat_HSet_Functor_HSet.", "meta": {"author": "amintimany", "repo": "Categories-HoTT", "sha": "fd6018c7abd496b44fd31b1119f6b31795c251d8", "save_path": "github-repos/coq/amintimany-Categories-HoTT", "path": "github-repos/coq/amintimany-Categories-HoTT/Categories-HoTT-fd6018c7abd496b44fd31b1119f6b31795c251d8/Functor/Functor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.6568514173354267}}
{"text": "Lemma succ_neq :\n  forall (n : nat),\n    n <> S n.\nProof.\n  intros.\n  intro.\n  induction n.\n  discriminate.\n  destruct IHn.\n  congruence.\nQed.\n\nLemma s_neq :\n  forall (n : nat) (m : nat),\n    n = S m -> n <> m.\nProof.\n  intros.\n  intro.\n  rewrite H0 in H.\n  apply succ_neq in H.\n  apply H.\nQed.\n\nLemma s_neq_2 :\n  forall (n : nat) (m : nat),\n    S n = S m <-> n = m.\nProof.\n  intros.\n  split. intro.\n  inversion H. tauto.\n  \n  intro. rewrite H.\n  tauto.\nQed.\n\nLemma l_sub :\n  forall (p : nat) (q : nat) (r : nat),\n    p + q = p + r <-> q = r.\nProof.\n  intros.\n  split.\n  intro.\n  induction p.\n  compute in H. apply H.\n\n  inversion H. apply IHp in H1. apply H1.\n\n  intro.\n  rewrite H.\n  tauto.\nQed.\n\nLemma succ_add :\n  forall (p : nat),\n    S p = p + 1.\nProof.\n  intro.\n\n  case_eq (p). intros. compute. auto.\n  intros. rewrite <- H.\n  assert (p = p + 0).\n  apply plus_n_O.\n  rewrite H0.\n  rewrite plus_n_Sm. rewrite <- H0.\n  tauto.  \nQed.\n", "meta": {"author": "MichaelBurge", "repo": "pornview", "sha": "b4aefdc0e49504aa88345b96710bd86645ab2477", "save_path": "github-repos/coq/MichaelBurge-pornview", "path": "github-repos/coq/MichaelBurge-pornview/pornview-b4aefdc0e49504aa88345b96710bd86645ab2477/PV/Nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.847967769904032, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6568217492875362}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nRequire Import Arith.\nFrom adtind Require Import goal50.\n\nSet Printing Depth 1000.\nDefinition lfind_eval  n y:=\ncount y n.\n\nCompute lfind_eval  (Succ Zero) (Cons Zero (Cons Zero Nil)).\n\nCompute lfind_eval  (Succ (Succ (Succ (Succ Zero)))) (Cons Zero (Cons Zero Nil)).\n\nCompute lfind_eval  (Zero) (Cons (Succ Zero) (Cons Zero (Cons (Succ Zero) Nil))).\n\nCompute lfind_eval  (Succ (Succ (Succ (Succ Zero)))) (Cons (Succ Zero) (Cons (Succ (Succ (Succ (Succ (Succ Zero))))) Nil)).\n\nCompute lfind_eval  (Zero) (Cons Zero Nil).\n\nCompute lfind_eval  (Succ Zero) (Cons (Succ Zero) (Cons (Succ Zero) (Cons Zero Nil))).\n\nCompute lfind_eval  (Zero) (Cons (Succ (Succ Zero)) Nil).\n\nCompute lfind_eval  (Zero) (Cons (Succ (Succ (Succ Zero))) Nil).\n\nCompute lfind_eval  (Succ (Succ (Succ Zero))) (Cons Zero Nil).\n\nCompute lfind_eval  (Succ Zero) (Cons Zero (Cons Zero (Cons Zero Nil))).\n\nCompute lfind_eval  (Succ (Succ Zero)) (Cons Zero Nil).\n\nCompute lfind_eval  (Succ (Succ Zero)) (Cons Zero (Cons Zero Nil)).\n\nCompute lfind_eval  (Succ Zero) (Cons (Succ (Succ (Succ Zero))) Nil).\n\nCompute lfind_eval  (Succ (Succ (Succ Zero))) (Cons Zero (Cons Zero (Cons (Succ Zero) Nil))).\n\nCompute lfind_eval  (Succ (Succ (Succ (Succ Zero)))) (Nil).\n\nCompute lfind_eval  (Zero) (Cons (Succ Zero) (Cons Zero Nil)).\n\nCompute lfind_eval  (Succ Zero) (Cons (Succ Zero) Nil).\n\nCompute lfind_eval  (Succ Zero) (Nil).\n\nCompute lfind_eval  (Succ (Succ Zero)) (Nil).\n\nCompute lfind_eval  (Succ Zero) (Cons Zero Nil).\n\nCompute lfind_eval  (Succ Zero) (Cons (Succ (Succ Zero)) Nil).\n\nCompute lfind_eval  (Succ (Succ Zero)) (Cons (Succ Zero) (Cons Zero Nil)).\n\nCompute lfind_eval  (Zero) (Nil).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal50_theorem0_194_count_insort/lfind_eval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6568217403595283}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(**********************************************************)\n(** Complements for the reals.Integer and fractional part *)\n(*                                                        *)\n(**********************************************************)\n\nRequire Import Rbase.\nRequire Import Omega.\nLocal Open Scope R_scope.\n\n(*********************************************************)\n(** *    Fractional part                                 *)\n(*********************************************************)\n\n(**********)\nDefinition Int_part (r:R) : Z := (up r - 1)%Z.\n\n(**********)\nDefinition frac_part (r:R) : R := r - IZR (Int_part r).\n\n(**********)\nLemma tech_up : forall (r:R) (z:Z), r < IZR z -> IZR z <= r + 1 -> z = up r.\nProof.\n  intros; generalize (archimed r); intro; elim H1; intros; clear H1;\n    unfold Rgt in H2; unfold Rminus in H3;\n      generalize (Rplus_le_compat_l r (IZR (up r) + - r) 1 H3);\n        intro; clear H3; rewrite (Rplus_comm (IZR (up r)) (- r)) in H1;\n          rewrite <- (Rplus_assoc r (- r) (IZR (up r))) in H1;\n            rewrite (Rplus_opp_r r) in H1; elim (Rplus_ne (IZR (up r)));\n              intros a b; rewrite b in H1; clear a b; apply (single_z_r_R1 r z (up r));\n                auto with zarith real.\nQed.\n\n(**********)\nLemma up_tech :\n  forall (r:R) (z:Z), IZR z <= r -> r < IZR (z + 1) -> (z + 1)%Z = up r.\nProof.\n  intros.\n  apply tech_up with (1 := H0).\n  rewrite plus_IZR.\n  now apply Rplus_le_compat_r.\nQed.\n\n(**********)\nLemma fp_R0 : frac_part 0 = 0.\nProof.\n  unfold frac_part, Int_part.\n  replace (up 0) with 1%Z.\n  now rewrite <- minus_IZR.\n  destruct (archimed 0) as [H1 H2].\n  apply lt_IZR in H1.\n  rewrite <- minus_IZR in H2.\n  apply le_IZR in H2.\n  omega.\nQed.\n\n(**********)\nLemma for_base_fp : forall r:R, IZR (up r) - r > 0 /\\ IZR (up r) - r <= 1.\nProof.\n  intro; split; cut (IZR (up r) > r /\\ IZR (up r) - r <= 1).\n  intro; elim H; intros.\n  apply (Rgt_minus (IZR (up r)) r H0).\n  apply archimed.\n  intro; elim H; intros.\n  exact H1.\n  apply archimed.\nQed.\n\n(**********)\nLemma base_fp : forall r:R, frac_part r >= 0 /\\ frac_part r < 1.\nProof.\n  intro; unfold frac_part; unfold Int_part; split.\n     (*sup a O*)\n  cut (r - IZR (up r) >= -1).\n  rewrite <- Z_R_minus; simpl; intro; unfold Rminus;\n    rewrite Ropp_plus_distr; rewrite <- Rplus_assoc;\n      fold (r - IZR (up r)); fold (r - IZR (up r) - -1);\n        apply Rge_minus; auto with zarith real.\n  rewrite <- Ropp_minus_distr; apply Ropp_le_ge_contravar; elim (for_base_fp r);\n    auto with zarith real.\n    (*inf a 1*)\n  cut (r - IZR (up r) < 0).\n  rewrite <- Z_R_minus; simpl; intro; unfold Rminus;\n    rewrite Ropp_plus_distr; rewrite <- Rplus_assoc;\n      fold (r - IZR (up r)); rewrite Ropp_involutive;\n        elim (Rplus_ne 1); intros a b; pattern 1 at 2;\n          rewrite <- a; clear a b; rewrite (Rplus_comm (r - IZR (up r)) 1);\n            apply Rplus_lt_compat_l; auto with zarith real.\n  elim (for_base_fp r); intros; rewrite <- Ropp_0; rewrite <- Ropp_minus_distr;\n    apply Ropp_gt_lt_contravar; auto with zarith real.\nQed.\n\n(*********************************************************)\n(** *    Properties                                      *)\n(*********************************************************)\n\n(**********)\nLemma base_Int_part :\n  forall r:R, IZR (Int_part r) <= r /\\ IZR (Int_part r) - r > -1.\nProof.\n  intro; unfold Int_part; elim (archimed r); intros.\n  split; rewrite <- (Z_R_minus (up r) 1); simpl.\n  apply Rminus_le.\n  replace (IZR (up r) - 1 - r) with (IZR (up r) - r - 1) by ring.\n  now apply Rle_minus.\n  apply Rminus_gt.\n  replace (IZR (up r) - 1 - r - -1) with (IZR (up r) - r) by ring.\n  now apply Rgt_minus.\nQed.\n\n(**********)\nLemma Int_part_INR : forall n:nat, Int_part (INR n) = Z.of_nat n.\nProof.\n  intros n; unfold Int_part.\n  cut (up (INR n) = (Z.of_nat n + Z.of_nat 1)%Z).\n  intros H'; rewrite H'; simpl; ring.\n  symmetry; apply tech_up; auto.\n  replace (Z.of_nat n + Z.of_nat 1)%Z with (Z.of_nat (S n)).\n  repeat rewrite <- INR_IZR_INZ.\n  apply lt_INR; auto.\n  rewrite Z.add_comm; rewrite <- Znat.Nat2Z.inj_add; simpl; auto.\n  rewrite plus_IZR; simpl; auto with real.\n  repeat rewrite <- INR_IZR_INZ; auto with real.\nQed.\n\n(**********)\nLemma fp_nat : forall r:R, frac_part r = 0 ->  exists c : Z, r = IZR c.\nProof.\n  unfold frac_part; intros; split with (Int_part r);\n    apply Rminus_diag_uniq; auto with zarith real.\nQed.\n\n(**********)\nLemma R0_fp_O : forall r:R, 0 <> frac_part r -> 0 <> r.\nProof.\n  red; intros; rewrite <- H0 in H; generalize fp_R0; intro;\n    auto with zarith real.\nQed.\n\n(**********)\nLemma Rminus_Int_part1 :\n  forall r1 r2:R,\n    frac_part r1 >= frac_part r2 ->\n    Int_part (r1 - r2) = (Int_part r1 - Int_part r2)%Z.\nProof.\n  intros; elim (base_fp r1); elim (base_fp r2); intros;\n    generalize (Rge_le (frac_part r2) 0 H0); intro; clear H0;\n      generalize (Ropp_le_ge_contravar 0 (frac_part r2) H4);\n        intro; clear H4; rewrite Ropp_0 in H0;\n          generalize (Rge_le 0 (- frac_part r2) H0); intro;\n            clear H0; generalize (Rge_le (frac_part r1) 0 H2);\n              intro; clear H2; generalize (Ropp_lt_gt_contravar (frac_part r2) 1 H1);\n                intro; clear H1; unfold Rgt in H2;\n                  generalize\n                    (sum_inequa_Rle_lt 0 (frac_part r1) 1 (-1) (- frac_part r2) 0 H0 H3 H2 H4);\n                    intro; elim H1; intros; clear H1; elim (Rplus_ne 1);\n                      intros a b; rewrite a in H6; clear a b H5;\n                        generalize (Rge_minus (frac_part r1) (frac_part r2) H);\n                          intro; clear H; fold (frac_part r1 - frac_part r2) in H6;\n                            generalize (Rge_le (frac_part r1 - frac_part r2) 0 H1);\n                              intro; clear H1 H3 H4 H0 H2; unfold frac_part in H6, H;\n                                unfold Rminus in H6, H;\n                                  rewrite (Ropp_plus_distr r2 (- IZR (Int_part r2))) in H;\n                                    rewrite (Ropp_involutive (IZR (Int_part r2))) in H;\n                                      rewrite (Rplus_assoc r1 (- IZR (Int_part r1)) (- r2 + IZR (Int_part r2)))\n                                        in H;\n                                        rewrite <- (Rplus_assoc (- IZR (Int_part r1)) (- r2) (IZR (Int_part r2)))\n                                          in H; rewrite (Rplus_comm (- IZR (Int_part r1)) (- r2)) in H;\n                                            rewrite (Rplus_assoc (- r2) (- IZR (Int_part r1)) (IZR (Int_part r2))) in H;\n                                              rewrite <- (Rplus_assoc r1 (- r2) (- IZR (Int_part r1) + IZR (Int_part r2)))\n                                                in H; rewrite (Rplus_comm (- IZR (Int_part r1)) (IZR (Int_part r2))) in H;\n                                                  fold (r1 - r2) in H; fold (IZR (Int_part r2) - IZR (Int_part r1)) in H;\n                                                    generalize\n                                                      (Rplus_le_compat_l (IZR (Int_part r1) - IZR (Int_part r2)) 0\n                                                        (r1 - r2 + (IZR (Int_part r2) - IZR (Int_part r1))) H);\n                                                      intro; clear H;\n                                                        rewrite (Rplus_comm (r1 - r2) (IZR (Int_part r2) - IZR (Int_part r1))) in H0;\n                                                          rewrite <-\n                                                            (Rplus_assoc (IZR (Int_part r1) - IZR (Int_part r2))\n                                                              (IZR (Int_part r2) - IZR (Int_part r1)) (r1 - r2))\n                                                            in H0; unfold Rminus in H0; fold (r1 - r2) in H0;\n                                                              rewrite\n                                                                (Rplus_assoc (IZR (Int_part r1)) (- IZR (Int_part r2))\n                                                                  (IZR (Int_part r2) + - IZR (Int_part r1))) in H0;\n                                                                rewrite <-\n                                                                  (Rplus_assoc (- IZR (Int_part r2)) (IZR (Int_part r2))\n                                                                    (- IZR (Int_part r1))) in H0;\n                                                                  rewrite (Rplus_opp_l (IZR (Int_part r2))) in H0;\n                                                                    elim (Rplus_ne (- IZR (Int_part r1))); intros a b;\n                                                                      rewrite b in H0; clear a b;\n                                                                        elim (Rplus_ne (IZR (Int_part r1) + - IZR (Int_part r2)));\n                                                                          intros a b; rewrite a in H0; clear a b;\n                                                                            rewrite (Rplus_opp_r (IZR (Int_part r1))) in H0; elim (Rplus_ne (r1 - r2));\n                                                                              intros a b; rewrite b in H0; clear a b;\n                                                                                fold (IZR (Int_part r1) - IZR (Int_part r2)) in H0;\n                                                                                  rewrite (Ropp_plus_distr r2 (- IZR (Int_part r2))) in H6;\n                                                                                    rewrite (Ropp_involutive (IZR (Int_part r2))) in H6;\n                                                                                      rewrite (Rplus_assoc r1 (- IZR (Int_part r1)) (- r2 + IZR (Int_part r2)))\n                                                                                        in H6;\n                                                                                        rewrite <- (Rplus_assoc (- IZR (Int_part r1)) (- r2) (IZR (Int_part r2)))\n                                                                                          in H6; rewrite (Rplus_comm (- IZR (Int_part r1)) (- r2)) in H6;\n                                                                                            rewrite (Rplus_assoc (- r2) (- IZR (Int_part r1)) (IZR (Int_part r2))) in H6;\n                                                                                              rewrite <- (Rplus_assoc r1 (- r2) (- IZR (Int_part r1) + IZR (Int_part r2)))\n                                                                                                in H6;\n                                                                                                rewrite (Rplus_comm (- IZR (Int_part r1)) (IZR (Int_part r2))) in H6;\n                                                                                                  fold (r1 - r2) in H6; fold (IZR (Int_part r2) - IZR (Int_part r1)) in H6;\n                                                                                                    generalize\n                                                                                                      (Rplus_lt_compat_l (IZR (Int_part r1) - IZR (Int_part r2))\n                                                                                                        (r1 - r2 + (IZR (Int_part r2) - IZR (Int_part r1))) 1 H6);\n                                                                                                      intro; clear H6;\n                                                                                                        rewrite (Rplus_comm (r1 - r2) (IZR (Int_part r2) - IZR (Int_part r1))) in H;\n                                                                                                          rewrite <-\n                                                                                                            (Rplus_assoc (IZR (Int_part r1) - IZR (Int_part r2))\n                                                                                                              (IZR (Int_part r2) - IZR (Int_part r1)) (r1 - r2))\n                                                                                                            in H;\n                                                                                                            rewrite <- (Ropp_minus_distr (IZR (Int_part r1)) (IZR (Int_part r2))) in H;\n                                                                                                              rewrite (Rplus_opp_r (IZR (Int_part r1) - IZR (Int_part r2))) in H;\n                                                                                                                elim (Rplus_ne (r1 - r2)); intros a b; rewrite b in H;\n                                                                                                                  clear a b; rewrite (Z_R_minus (Int_part r1) (Int_part r2)) in H0;\n                                                                                                                    rewrite (Z_R_minus (Int_part r1) (Int_part r2)) in H.\n    rewrite <- (plus_IZR (Int_part r1 - Int_part r2) 1) in H;\n      generalize (up_tech (r1 - r2) (Int_part r1 - Int_part r2) H0 H);\n        intros; clear H H0; unfold Int_part at 1;\n          omega.\nQed.\n\n(**********)\nLemma Rminus_Int_part2 :\n  forall r1 r2:R,\n    frac_part r1 < frac_part r2 ->\n    Int_part (r1 - r2) = (Int_part r1 - Int_part r2 - 1)%Z.\nProof.\n  intros; elim (base_fp r1); elim (base_fp r2); intros;\n    generalize (Rge_le (frac_part r2) 0 H0); intro; clear H0;\n      generalize (Ropp_le_ge_contravar 0 (frac_part r2) H4);\n        intro; clear H4; rewrite Ropp_0 in H0;\n          generalize (Rge_le 0 (- frac_part r2) H0); intro;\n            clear H0; generalize (Rge_le (frac_part r1) 0 H2);\n              intro; clear H2; generalize (Ropp_lt_gt_contravar (frac_part r2) 1 H1);\n                intro; clear H1; unfold Rgt in H2;\n                  generalize\n                    (sum_inequa_Rle_lt 0 (frac_part r1) 1 (-1) (- frac_part r2) 0 H0 H3 H2 H4);\n                    intro; elim H1; intros; clear H1; elim (Rplus_ne (-1));\n                      intros a b; rewrite b in H5; clear a b H6;\n                        generalize (Rlt_minus (frac_part r1) (frac_part r2) H);\n                          intro; clear H; fold (frac_part r1 - frac_part r2) in H5;\n                            clear H3 H4 H0 H2; unfold frac_part in H5, H1; unfold Rminus in H5, H1;\n                              rewrite (Ropp_plus_distr r2 (- IZR (Int_part r2))) in H5;\n                                rewrite (Ropp_involutive (IZR (Int_part r2))) in H5;\n                                  rewrite (Rplus_assoc r1 (- IZR (Int_part r1)) (- r2 + IZR (Int_part r2)))\n                                    in H5;\n                                    rewrite <- (Rplus_assoc (- IZR (Int_part r1)) (- r2) (IZR (Int_part r2)))\n                                      in H5; rewrite (Rplus_comm (- IZR (Int_part r1)) (- r2)) in H5;\n                                        rewrite (Rplus_assoc (- r2) (- IZR (Int_part r1)) (IZR (Int_part r2))) in H5;\n                                          rewrite <- (Rplus_assoc r1 (- r2) (- IZR (Int_part r1) + IZR (Int_part r2)))\n                                            in H5;\n                                            rewrite (Rplus_comm (- IZR (Int_part r1)) (IZR (Int_part r2))) in H5;\n                                              fold (r1 - r2) in H5; fold (IZR (Int_part r2) - IZR (Int_part r1)) in H5;\n                                                generalize\n                                                  (Rplus_lt_compat_l (IZR (Int_part r1) - IZR (Int_part r2)) (-1)\n                                                    (r1 - r2 + (IZR (Int_part r2) - IZR (Int_part r1))) H5);\n                                                  intro; clear H5;\n                                                    rewrite (Rplus_comm (r1 - r2) (IZR (Int_part r2) - IZR (Int_part r1))) in H;\n                                                      rewrite <-\n                                                        (Rplus_assoc (IZR (Int_part r1) - IZR (Int_part r2))\n                                                          (IZR (Int_part r2) - IZR (Int_part r1)) (r1 - r2))\n                                                        in H; unfold Rminus in H; fold (r1 - r2) in H;\n                                                          rewrite\n                                                            (Rplus_assoc (IZR (Int_part r1)) (- IZR (Int_part r2))\n                                                              (IZR (Int_part r2) + - IZR (Int_part r1))) in H;\n                                                            rewrite <-\n                                                              (Rplus_assoc (- IZR (Int_part r2)) (IZR (Int_part r2))\n                                                                (- IZR (Int_part r1))) in H;\n                                                              rewrite (Rplus_opp_l (IZR (Int_part r2))) in H;\n                                                                elim (Rplus_ne (- IZR (Int_part r1))); intros a b;\n                                                                  rewrite b in H; clear a b; rewrite (Rplus_opp_r (IZR (Int_part r1))) in H;\n                                                                    elim (Rplus_ne (r1 - r2)); intros a b; rewrite b in H;\n                                                                      clear a b; fold (IZR (Int_part r1) - IZR (Int_part r2)) in H;\n                                                                        fold (IZR (Int_part r1) - IZR (Int_part r2) - 1) in H;\n                                                                          rewrite (Ropp_plus_distr r2 (- IZR (Int_part r2))) in H1;\n                                                                            rewrite (Ropp_involutive (IZR (Int_part r2))) in H1;\n                                                                              rewrite (Rplus_assoc r1 (- IZR (Int_part r1)) (- r2 + IZR (Int_part r2)))\n                                                                                in H1;\n                                                                                rewrite <- (Rplus_assoc (- IZR (Int_part r1)) (- r2) (IZR (Int_part r2)))\n                                                                                  in H1; rewrite (Rplus_comm (- IZR (Int_part r1)) (- r2)) in H1;\n                                                                                    rewrite (Rplus_assoc (- r2) (- IZR (Int_part r1)) (IZR (Int_part r2))) in H1;\n                                                                                      rewrite <- (Rplus_assoc r1 (- r2) (- IZR (Int_part r1) + IZR (Int_part r2)))\n                                                                                        in H1;\n                                                                                        rewrite (Rplus_comm (- IZR (Int_part r1)) (IZR (Int_part r2))) in H1;\n                                                                                          fold (r1 - r2) in H1; fold (IZR (Int_part r2) - IZR (Int_part r1)) in H1;\n                                                                                            generalize\n                                                                                              (Rplus_lt_compat_l (IZR (Int_part r1) - IZR (Int_part r2))\n                                                                                                (r1 - r2 + (IZR (Int_part r2) - IZR (Int_part r1))) 0 H1);\n                                                                                              intro; clear H1;\n                                                                                                rewrite (Rplus_comm (r1 - r2) (IZR (Int_part r2) - IZR (Int_part r1))) in H0;\n                                                                                                  rewrite <-\n                                                                                                    (Rplus_assoc (IZR (Int_part r1) - IZR (Int_part r2))\n                                                                                                      (IZR (Int_part r2) - IZR (Int_part r1)) (r1 - r2))\n                                                                                                    in H0;\n                                                                                                    rewrite <- (Ropp_minus_distr (IZR (Int_part r1)) (IZR (Int_part r2))) in H0;\n                                                                                                      rewrite (Rplus_opp_r (IZR (Int_part r1) - IZR (Int_part r2))) in H0;\n                                                                                                        elim (Rplus_ne (r1 - r2)); intros a b; rewrite b in H0;\n                                                                                                          clear a b; rewrite <- (Rplus_opp_l 1) in H0;\n                                                                                                            rewrite <- (Rplus_assoc (IZR (Int_part r1) - IZR (Int_part r2)) (-(1)) 1)\n                                                                                                              in H0; fold (IZR (Int_part r1) - IZR (Int_part r2) - 1) in H0;\n                                                                                                                rewrite (Z_R_minus (Int_part r1) (Int_part r2)) in H0;\n                                                                                                                  rewrite (Z_R_minus (Int_part r1) (Int_part r2)) in H;\n                                                                                                                    auto with zarith real.\n  change (_ + -1) with (IZR (Int_part r1 - Int_part r2) - 1) in H;\n    rewrite (Z_R_minus (Int_part r1 - Int_part r2) 1) in H;\n      rewrite (Z_R_minus (Int_part r1 - Int_part r2) 1) in H0;\n        rewrite <- (plus_IZR (Int_part r1 - Int_part r2 - 1) 1) in H0;\n          generalize (Rlt_le (IZR (Int_part r1 - Int_part r2 - 1)) (r1 - r2) H);\n            intro; clear H;\n              generalize (up_tech (r1 - r2) (Int_part r1 - Int_part r2 - 1) H1 H0);\n                intros; clear H0 H1; unfold Int_part at 1;\n                  omega.\nQed.\n\n(**********)\nLemma Rminus_fp1 :\n  forall r1 r2:R,\n    frac_part r1 >= frac_part r2 ->\n    frac_part (r1 - r2) = frac_part r1 - frac_part r2.\nProof.\n  intros; unfold frac_part; generalize (Rminus_Int_part1 r1 r2 H);\n    intro; rewrite H0; rewrite <- (Z_R_minus (Int_part r1) (Int_part r2));\n      unfold Rminus;\n        rewrite (Ropp_plus_distr (IZR (Int_part r1)) (- IZR (Int_part r2)));\n          rewrite (Ropp_plus_distr r2 (- IZR (Int_part r2)));\n            rewrite (Ropp_involutive (IZR (Int_part r2)));\n              rewrite (Rplus_assoc r1 (- r2) (- IZR (Int_part r1) + IZR (Int_part r2)));\n                rewrite (Rplus_assoc r1 (- IZR (Int_part r1)) (- r2 + IZR (Int_part r2)));\n                  rewrite <- (Rplus_assoc (- r2) (- IZR (Int_part r1)) (IZR (Int_part r2)));\n                    rewrite <- (Rplus_assoc (- IZR (Int_part r1)) (- r2) (IZR (Int_part r2)));\n                      rewrite (Rplus_comm (- r2) (- IZR (Int_part r1)));\n                        auto with zarith real.\nQed.\n\n(**********)\nLemma Rminus_fp2 :\n  forall r1 r2:R,\n    frac_part r1 < frac_part r2 ->\n    frac_part (r1 - r2) = frac_part r1 - frac_part r2 + 1.\nProof.\n  intros; unfold frac_part; generalize (Rminus_Int_part2 r1 r2 H);\n    intro; rewrite H0; rewrite <- (Z_R_minus (Int_part r1 - Int_part r2) 1);\n      rewrite <- (Z_R_minus (Int_part r1) (Int_part r2));\n        unfold Rminus;\n          rewrite\n            (Ropp_plus_distr (IZR (Int_part r1) + - IZR (Int_part r2)) (- IZR 1))\n            ; rewrite (Ropp_plus_distr r2 (- IZR (Int_part r2)));\n              rewrite (Ropp_involutive (IZR 1));\n                rewrite (Ropp_involutive (IZR (Int_part r2)));\n                  rewrite (Ropp_plus_distr (IZR (Int_part r1)));\n                    rewrite (Ropp_involutive (IZR (Int_part r2))); simpl;\n                      rewrite <-\n                        (Rplus_assoc (r1 + - r2) (- IZR (Int_part r1) + IZR (Int_part r2)) 1)\n                        ; rewrite (Rplus_assoc r1 (- r2) (- IZR (Int_part r1) + IZR (Int_part r2)));\n                          rewrite (Rplus_assoc r1 (- IZR (Int_part r1)) (- r2 + IZR (Int_part r2)));\n                            rewrite <- (Rplus_assoc (- r2) (- IZR (Int_part r1)) (IZR (Int_part r2)));\n                              rewrite <- (Rplus_assoc (- IZR (Int_part r1)) (- r2) (IZR (Int_part r2)));\n                                rewrite (Rplus_comm (- r2) (- IZR (Int_part r1)));\n                                  auto with zarith real.\nQed.\n\n(**********)\nLemma plus_Int_part1 :\n  forall r1 r2:R,\n    frac_part r1 + frac_part r2 >= 1 ->\n    Int_part (r1 + r2) = (Int_part r1 + Int_part r2 + 1)%Z.\nProof.\n  intros; generalize (Rge_le (frac_part r1 + frac_part r2) 1 H); intro; clear H;\n    elim (base_fp r1); elim (base_fp r2); intros; clear H H2;\n      generalize (Rplus_lt_compat_l (frac_part r2) (frac_part r1) 1 H3);\n        intro; clear H3; generalize (Rplus_lt_compat_l 1 (frac_part r2) 1 H1);\n          intro; clear H1; rewrite (Rplus_comm 1 (frac_part r2)) in H2;\n            generalize\n              (Rlt_trans (frac_part r2 + frac_part r1) (frac_part r2 + 1) 2 H H2);\n              intro; clear H H2; rewrite (Rplus_comm (frac_part r2) (frac_part r1)) in H1;\n                unfold frac_part in H0, H1; unfold Rminus in H0, H1;\n                  rewrite (Rplus_assoc r1 (- IZR (Int_part r1)) (r2 + - IZR (Int_part r2)))\n                    in H1; rewrite (Rplus_comm r2 (- IZR (Int_part r2))) in H1;\n                      rewrite <- (Rplus_assoc (- IZR (Int_part r1)) (- IZR (Int_part r2)) r2)\n                        in H1;\n                        rewrite (Rplus_comm (- IZR (Int_part r1) + - IZR (Int_part r2)) r2) in H1;\n                          rewrite <- (Rplus_assoc r1 r2 (- IZR (Int_part r1) + - IZR (Int_part r2)))\n                            in H1;\n                            rewrite <- (Ropp_plus_distr (IZR (Int_part r1)) (IZR (Int_part r2))) in H1;\n                              rewrite (Rplus_assoc r1 (- IZR (Int_part r1)) (r2 + - IZR (Int_part r2)))\n                                in H0; rewrite (Rplus_comm r2 (- IZR (Int_part r2))) in H0;\n                                  rewrite <- (Rplus_assoc (- IZR (Int_part r1)) (- IZR (Int_part r2)) r2)\n                                    in H0;\n                                    rewrite (Rplus_comm (- IZR (Int_part r1) + - IZR (Int_part r2)) r2) in H0;\n                                      rewrite <- (Rplus_assoc r1 r2 (- IZR (Int_part r1) + - IZR (Int_part r2)))\n                                        in H0;\n                                        rewrite <- (Ropp_plus_distr (IZR (Int_part r1)) (IZR (Int_part r2))) in H0;\n                                          generalize\n                                            (Rplus_le_compat_l (IZR (Int_part r1) + IZR (Int_part r2)) 1\n                                              (r1 + r2 + - (IZR (Int_part r1) + IZR (Int_part r2))) H0);\n                                            intro; clear H0;\n                                              generalize\n                                                (Rplus_lt_compat_l (IZR (Int_part r1) + IZR (Int_part r2))\n                                                  (r1 + r2 + - (IZR (Int_part r1) + IZR (Int_part r2))) 2 H1);\n                                                intro; clear H1;\n                                                  rewrite (Rplus_comm (r1 + r2) (- (IZR (Int_part r1) + IZR (Int_part r2))))\n                                                    in H;\n                                                    rewrite <-\n                                                      (Rplus_assoc (IZR (Int_part r1) + IZR (Int_part r2))\n                                                        (- (IZR (Int_part r1) + IZR (Int_part r2))) (r1 + r2))\n                                                      in H; rewrite (Rplus_opp_r (IZR (Int_part r1) + IZR (Int_part r2))) in H;\n                                                        elim (Rplus_ne (r1 + r2)); intros a b; rewrite b in H;\n                                                          clear a b;\n                                                            rewrite (Rplus_comm (r1 + r2) (- (IZR (Int_part r1) + IZR (Int_part r2))))\n                                                              in H0;\n                                                              rewrite <-\n                                                                (Rplus_assoc (IZR (Int_part r1) + IZR (Int_part r2))\n                                                                  (- (IZR (Int_part r1) + IZR (Int_part r2))) (r1 + r2))\n                                                                in H0; rewrite (Rplus_opp_r (IZR (Int_part r1) + IZR (Int_part r2))) in H0;\n                                                                  elim (Rplus_ne (r1 + r2)); intros a b; rewrite b in H0;\n                                                                    clear a b;\n                                                                      change 2 with (1 + 1) in H0;\n                                                                      rewrite <- (Rplus_assoc (IZR (Int_part r1) + IZR (Int_part r2)) 1 1) in H0;\n                                                                        auto with zarith real.\n    rewrite <- (plus_IZR (Int_part r1) (Int_part r2)) in H;\n      rewrite <- (plus_IZR (Int_part r1) (Int_part r2)) in H0;\n        rewrite <- (plus_IZR (Int_part r1 + Int_part r2) 1) in H;\n          rewrite <- (plus_IZR (Int_part r1 + Int_part r2) 1) in H0;\n            rewrite <- (plus_IZR (Int_part r1 + Int_part r2 + 1) 1) in H0;\n              generalize (up_tech (r1 + r2) (Int_part r1 + Int_part r2 + 1) H H0);\n                intro; clear H H0; unfold Int_part at 1; omega.\nQed.\n\n(**********)\nLemma plus_Int_part2 :\n  forall r1 r2:R,\n    frac_part r1 + frac_part r2 < 1 ->\n    Int_part (r1 + r2) = (Int_part r1 + Int_part r2)%Z.\nProof.\n  intros; elim (base_fp r1); elim (base_fp r2); intros; clear H1 H3;\n    generalize (Rge_le (frac_part r2) 0 H0); intro; clear H0;\n      generalize (Rge_le (frac_part r1) 0 H2); intro; clear H2;\n        generalize (Rplus_le_compat_l (frac_part r1) 0 (frac_part r2) H1);\n          intro; clear H1; elim (Rplus_ne (frac_part r1)); intros a b;\n            rewrite a in H2; clear a b;\n              generalize (Rle_trans 0 (frac_part r1) (frac_part r1 + frac_part r2) H0 H2);\n                intro; clear H0 H2; unfold frac_part in H, H1; unfold Rminus in H, H1;\n                  rewrite (Rplus_assoc r1 (- IZR (Int_part r1)) (r2 + - IZR (Int_part r2)))\n                    in H1; rewrite (Rplus_comm r2 (- IZR (Int_part r2))) in H1;\n                      rewrite <- (Rplus_assoc (- IZR (Int_part r1)) (- IZR (Int_part r2)) r2)\n                        in H1;\n                        rewrite (Rplus_comm (- IZR (Int_part r1) + - IZR (Int_part r2)) r2) in H1;\n                          rewrite <- (Rplus_assoc r1 r2 (- IZR (Int_part r1) + - IZR (Int_part r2)))\n                            in H1;\n                            rewrite <- (Ropp_plus_distr (IZR (Int_part r1)) (IZR (Int_part r2))) in H1;\n                              rewrite (Rplus_assoc r1 (- IZR (Int_part r1)) (r2 + - IZR (Int_part r2)))\n                                in H; rewrite (Rplus_comm r2 (- IZR (Int_part r2))) in H;\n                                  rewrite <- (Rplus_assoc (- IZR (Int_part r1)) (- IZR (Int_part r2)) r2) in H;\n                                    rewrite (Rplus_comm (- IZR (Int_part r1) + - IZR (Int_part r2)) r2) in H;\n                                      rewrite <- (Rplus_assoc r1 r2 (- IZR (Int_part r1) + - IZR (Int_part r2)))\n                                        in H;\n                                        rewrite <- (Ropp_plus_distr (IZR (Int_part r1)) (IZR (Int_part r2))) in H;\n                                          generalize\n                                            (Rplus_le_compat_l (IZR (Int_part r1) + IZR (Int_part r2)) 0\n                                              (r1 + r2 + - (IZR (Int_part r1) + IZR (Int_part r2))) H1);\n                                            intro; clear H1;\n                                              generalize\n                                                (Rplus_lt_compat_l (IZR (Int_part r1) + IZR (Int_part r2))\n                                                  (r1 + r2 + - (IZR (Int_part r1) + IZR (Int_part r2))) 1 H);\n                                                intro; clear H;\n                                                  rewrite (Rplus_comm (r1 + r2) (- (IZR (Int_part r1) + IZR (Int_part r2))))\n                                                    in H1;\n                                                    rewrite <-\n                                                      (Rplus_assoc (IZR (Int_part r1) + IZR (Int_part r2))\n                                                        (- (IZR (Int_part r1) + IZR (Int_part r2))) (r1 + r2))\n                                                      in H1; rewrite (Rplus_opp_r (IZR (Int_part r1) + IZR (Int_part r2))) in H1;\n                                                        elim (Rplus_ne (r1 + r2)); intros a b; rewrite b in H1;\n                                                          clear a b;\n                                                            rewrite (Rplus_comm (r1 + r2) (- (IZR (Int_part r1) + IZR (Int_part r2))))\n                                                              in H0;\n                                                              rewrite <-\n                                                                (Rplus_assoc (IZR (Int_part r1) + IZR (Int_part r2))\n                                                                  (- (IZR (Int_part r1) + IZR (Int_part r2))) (r1 + r2))\n                                                                in H0; rewrite (Rplus_opp_r (IZR (Int_part r1) + IZR (Int_part r2))) in H0;\n                                                                  elim (Rplus_ne (IZR (Int_part r1) + IZR (Int_part r2)));\n                                                                    intros a b; rewrite a in H0; clear a b; elim (Rplus_ne (r1 + r2));\n                                                                      intros a b; rewrite b in H0; clear a b.\n    rewrite <- (plus_IZR (Int_part r1) (Int_part r2)) in H0;\n      rewrite <- (plus_IZR (Int_part r1) (Int_part r2)) in H1;\n        rewrite <- (plus_IZR (Int_part r1 + Int_part r2) 1) in H1;\n          generalize (up_tech (r1 + r2) (Int_part r1 + Int_part r2) H0 H1);\n            intro; clear H0 H1; unfold Int_part at 1;\n              omega.\nQed.\n\n(**********)\nLemma plus_frac_part1 :\n  forall r1 r2:R,\n    frac_part r1 + frac_part r2 >= 1 ->\n    frac_part (r1 + r2) = frac_part r1 + frac_part r2 - 1.\nProof.\n  intros; unfold frac_part; generalize (plus_Int_part1 r1 r2 H); intro;\n    rewrite H0; rewrite (plus_IZR (Int_part r1 + Int_part r2) 1);\n      rewrite (plus_IZR (Int_part r1) (Int_part r2)); simpl;\n        unfold Rminus at 3 4;\n          rewrite (Rplus_assoc r1 (- IZR (Int_part r1)) (r2 + - IZR (Int_part r2)));\n            rewrite (Rplus_comm r2 (- IZR (Int_part r2)));\n              rewrite <- (Rplus_assoc (- IZR (Int_part r1)) (- IZR (Int_part r2)) r2);\n                rewrite (Rplus_comm (- IZR (Int_part r1) + - IZR (Int_part r2)) r2);\n                  rewrite <- (Rplus_assoc r1 r2 (- IZR (Int_part r1) + - IZR (Int_part r2)));\n                    rewrite <- (Ropp_plus_distr (IZR (Int_part r1)) (IZR (Int_part r2)));\n                      unfold Rminus;\n                        rewrite\n                          (Rplus_assoc (r1 + r2) (- (IZR (Int_part r1) + IZR (Int_part r2))) (-(1)))\n                          ; rewrite <- (Ropp_plus_distr (IZR (Int_part r1) + IZR (Int_part r2)) 1);\n                            trivial with zarith real.\nQed.\n\n(**********)\nLemma plus_frac_part2 :\n  forall r1 r2:R,\n    frac_part r1 + frac_part r2 < 1 ->\n    frac_part (r1 + r2) = frac_part r1 + frac_part r2.\nProof.\n  intros; unfold frac_part; generalize (plus_Int_part2 r1 r2 H); intro;\n    rewrite H0; rewrite (plus_IZR (Int_part r1) (Int_part r2));\n      unfold Rminus at 2 3;\n        rewrite (Rplus_assoc r1 (- IZR (Int_part r1)) (r2 + - IZR (Int_part r2)));\n          rewrite (Rplus_comm r2 (- IZR (Int_part r2)));\n            rewrite <- (Rplus_assoc (- IZR (Int_part r1)) (- IZR (Int_part r2)) r2);\n              rewrite (Rplus_comm (- IZR (Int_part r1) + - IZR (Int_part r2)) r2);\n                rewrite <- (Rplus_assoc r1 r2 (- IZR (Int_part r1) + - IZR (Int_part r2)));\n                  rewrite <- (Ropp_plus_distr (IZR (Int_part r1)) (IZR (Int_part r2)));\n                    unfold Rminus; trivial with zarith real.\nQed.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Reals/R_Ifp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6568217299950347}}
{"text": "\n\n(* (** Finite Closure Iteration *) *)\n(* Section Fixedpoints. *)\n(*   Variable X: Type. *)\n(*   Variable f: X -> X. *)\n(*   Definition fp x := f x = x. *)\n\n(*   Lemma fp_trans x: fp x -> fp (f x). *)\n(*   Proof. *)\n(*     congruence. *)\n(*   Qed. *)\n  \n(*   Lemma fInduction (p: X -> Prop) (x:X) (px: p x) (IHf: forall y, p y -> p (f y)) n: p (Nat.iter n f x). *)\n(*   Proof. *)\n(*     induction n. *)\n(*     - exact px. *)\n(*     -  firstorder. *)\n(*   Qed. *)\n\n(* Lemma fp_iter_trans x n: fp (Nat.iter n f x) -> forall m, m >= n -> fp (Nat.iter m f x). *)\n(* Proof. *)\n(*   intros F m H. induction m. *)\n(*   - destruct n; auto. omega.  *)\n(*   - decide (S m = n). *)\n(*     + now rewrite e. *)\n(*     + assert (m >= n) as G by omega. *)\n(*       specialize (IHm G). simpl. now apply fp_trans. *)\n(* Qed. *)\n\n(* End Fixedpoints. *)\n\n(* Definition admissible (X: eqType) f := forall A: list X,  fp f A \\/ card (f A) > card A. *)\n  \n\n(* Lemma fp_card_admissible (X:eqType) f n: *)\n(*   admissible f -> forall A: list X, fp f (Nat.iter n f A) \\/ card (Nat.iter n f A) >= n. *)\n(*  Proof. *)\n(*    intros M A. induction n. *)\n(*      - cbn in *. right. omega. *)\n(*      - simpl in *. destruct IHn as [IHn | IHn] . *)\n(*        + left.  now apply fp_trans. *)\n(*        + destruct (M ((Nat.iter n f A))) as [M' | M']. *)\n(*          * left.  now apply fp_trans. *)\n(*          * right. omega.  *)\n(*  Qed. *)\n\n(*  Lemma fp_admissible (X:finType) (f: list X -> list X): *)\n(*    admissible f -> forall A, fp f (Nat.iter (Cardinality X) f A). *)\n(*  Proof. *)\n(*    intros F A. *)\n(*    destruct (fp_card_admissible (Cardinality X) F A) as [H | H]. *)\n(*    - exact H. *)\n(*    - specialize (F (Nat.iter (Cardinality X) f A)).  destruct F as [F |F]. *)\n(*      + tauto. *)\n(*      + pose proof (card_upper_bound (f (Nat.iter (Cardinality X) f A))). omega. *)\n(* Qed.  *)\n\n(* Section FiniteClosureIteration. *)\n(*   Variable X : finType. *)\n(*   Variable step:list X -> X -> Prop. *)\n(*   Variable step_dec: forall A x, dec (step A x). *)\n\n  \n(*   Lemma pick A : {x | step A x /\\ ~ (x el A)} + forall x, step A x -> x el A. *)\n(*   Proof. *)\n(*     decide (forall x, step A x -> x el A). *)\n(*     - tauto. *)\n(*     - left. destruct (DM_notAll _ (p:= fun x => step A x -> x el A)) as [H _]. *)\n(*       destruct (finType_cc _ (H n)) as [x H']. firstorder. *)\n(*   Defined. *)\n\n(*   Definition FCStep A := *)\n(*     match (pick A) with *)\n(*     | inl L => match L with *)\n(*                 exist _ x _ => x::A end *)\n(*     | inr _ => A end. *)\n\n(*   Definition FCIter := Nat.iter (Cardinality X) FCStep. *)\n\n(* Lemma FCStep_admissible: admissible FCStep. *)\n(* Proof. *)\n(*   intro A.  unfold fp. unfold FCStep. destruct (pick A) as [[y [S ne]] | S];auto. *)\n(*   right. cbn. dec. *)\n(*   - tauto. *)\n(*   - omega. *)\n(* Qed. *)\n\n(* Lemma FCIter_fp A: fp FCStep (FCIter A). *)\n(* Proof. *)\n(*   unfold FCIter. apply fp_admissible. exact FCStep_admissible. *)\n(* Qed.         *)\n\n(* (* inclp A p means every x in A satisfies p *) *)\n\n(* Lemma FCIter_ind (p: X -> Prop) A :  inclp A p ->  (forall A x , (inclp A p) -> (step A x -> p x)) -> inclp (FCIter A) p. *)\n(* Proof. *)\n(*   intros incl H. unfold FCIter. apply fInduction. *)\n(*   - assumption.  *)\n(*   - intros B H1 x E. unfold FCStep in E. destruct (pick B) as [[y [S nE]] | S]. *)\n(*     + destruct E as [E|E]; try subst x; eauto. *)\n(*     + auto. *)\n(* Qed.  *)\n\n(* Lemma Closure x A: fp FCStep A -> step A x -> x el A. *)\n(* Proof. *)\n(*   intros F. unfold fp in F.  unfold FCStep in F. destruct (pick A) as [[y _] | S]. *)\n(*   - contradiction (list_cycle F). *)\n(*   - exact (S x). *)\n(* Qed. *)\n\n(* Lemma Closure_FCIter x A: step (FCIter A) x -> x el (FCIter A). *)\n(* Proof. apply Closure. apply FCIter_fp. *)\n(* Qed. *)\n\n(* Lemma preservation_step A: A <<= FCStep A. *)\n(* Proof. *)\n(*   intro H. unfold FCStep. destruct (pick A) as [[y [S ne]] | S]; cbn; tauto. *)\n(* Qed. *)\n\n(* Lemma preservation_iter A n: A <<= Nat.iter n FCStep A. *)\n(* Proof. *)\n(*   intros x E. induction n. *)\n(*   - assumption. *)\n(*   - simpl. now apply preservation_step. *)\n(* Qed. *)\n\n(* Lemma preservation_FCIter A: A <<= FCIter A.  *)\n(* Proof. *)\n(*  apply preservation_iter. *)\n(* Qed. *)\n\n(* Definition least_fp_containing f (B A: list X) := fp f B /\\ A <<= B /\\ forall B', fp f B' /\\ A <<= B' -> B <<= B'. *)\n\n(* Definition step_consistent:= forall A x, step A x -> forall A', A <<= A' -> step A' x. *)\n\n(* Lemma step_iter_consistent: step_consistent -> forall A x n, step A x -> step (Nat.iter n FCStep A) x. *)\n(* Proof. *)\n(*   intros H A x n S. eapply H. *)\n(*   - exact S. *)\n(*   - apply preservation_iter. *)\n(* Qed. *)\n\n\n\n(* Lemma step_trans_fp_incl: step_consistent -> forall A B, fp FCStep B -> A <<= B -> forall n, Nat.iter n FCStep A <<= B. *)\n(* Proof. *)\n(*  intros ST A B F H n. apply fInduction. *)\n(*   - exact H. *)\n(*   - intros B' H'. unfold FCStep at 1. destruct (pick B') as [[y [S _]] | _]. *)\n(*     + specialize (ST  _ _ S _ H'). intros x [E |E]. *)\n(*       * subst x. now apply Closure. *)\n(*       * auto. *)\n(*     + exact H'. *)\n(* Qed. *)\n\n(* Lemma step_consistent_least_fp: step_consistent -> forall A, least_fp_containing FCStep (FCIter A) A. *)\n(* Proof. *)\n(*   intros ST A.  repeat split. *)\n(*   - apply FCIter_fp. *)\n(*   - apply preservation_FCIter. *)\n(*   - intros B [H H']. now apply step_trans_fp_incl. *)\n(* Qed. *)\n\n(*   (** Dupfreeness of FCIter *)\n(* - relict of an old proof *)\n(* - might still be useful in concrete applications *) *)\n\n(* Lemma dupfree_FCStep A: dupfree A -> dupfree (FCStep A). *)\n(* Proof. *)\n(*   intro DA. unfold FCStep. destruct (pick A) as [[y [S ne]] | S]; auto. now constructor. *)\n(* Qed. *)\n\n(*  Lemma dupfree_iterstep n A: dupfree A -> dupfree (Nat.iter n FCStep A). *)\n(*  Proof. *)\n(*    induction n. *)\n(*    -  now cbn. *)\n(*    - intro H. simpl. apply dupfree_FCStep; tauto. *)\n(*  Qed. *)\n\n(*  Lemma dupfree_FCIter A : dupfree A -> dupfree (FCIter A). *)\n(*  Proof. *)\n(*    apply dupfree_iterstep. *)\n(*  Qed. *)\n\n(* End FiniteClosureIteration. *)\n(* Arguments FCIter {X} step {step_dec} x. *)\n(* Arguments FCStep {X} step {step_dec} A. *)\n(* Arguments pick {X} {step} {step_dec} A. *)\n\n\n      \n", "meta": {"author": "uds-psl", "repo": "cbv-lambda-calculus-reasonable", "sha": "4f12b7c8ce2816cdd771d22d04943e0fa81c63fd", "save_path": "github-repos/coq/uds-psl-cbv-lambda-calculus-reasonable", "path": "github-repos/coq/uds-psl-cbv-lambda-calculus-reasonable/cbv-lambda-calculus-reasonable-4f12b7c8ce2816cdd771d22d04943e0fa81c63fd/Base/FiniteTypes/FCI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095495, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6568217152180525}}
{"text": "(* -*- mode: coq; mode: visual-line -*-  *)\n(** * HPropositions *)\n\nRequire Import HoTT.Basics HoTT.Types.\n\nLocal Open Scope path_scope.\n\nGeneralizable Variables A B.\n\n(** ** Truncatedness is an hprop *)\n\n(** If a type is contractible, then so is its type of contractions.\n    Using [issig_contr] and the [equiv_intro] tactic, we can transfer this to the equivalent problem of contractibility of a certain Sigma-type, in which case we can apply the general path-construction functions. *)\nGlobal Instance contr_contr `{Funext} (A : Type)\n  : Contr A -> Contr (Contr A) | 100.\nProof.\n  intros c; exists c; generalize c.\n  equiv_intro (issig_contr A) c'.\n  equiv_intro (issig_contr A) d'.\n  refine (ap _ _).\n  refine (path_sigma _ _ _ ((contr (c'.1))^ @ contr (d'.1)) _).\n  refine (path_forall _ _ _); intros x.\n  apply path2_contr.\nQed.\n\n(** This provides the base case in a proof that truncatedness is a proposition. *)\nGlobal Instance hprop_trunc `{Funext} (n : trunc_index) (A : Type)\n  : IsHProp (IsTrunc n A) | 0.\nProof.\n  apply hprop_inhabited_contr.\n  revert A.\n  simple_induction n n IH; unfold IsTrunc; simpl.\n  - intros A ?.\n    exact _.\n  - intros A AH1.\n    exists AH1.\n    intro AH2.\n    apply path_forall; intro x.\n    apply path_forall; intro y.\n    apply @path_contr.\n    apply IH, AH1.\nQed.\n(** By [trunc_hprop], it follows that [IsTrunc n A] is also [m]-truncated for any [m >= -1]. *)\n\n(** Similarly, a map being truncated is also a proposition. *)\nGlobal Instance isprop_istruncmap `{Funext} (n : trunc_index) {X Y : Type} (f : X -> Y)\n: IsHProp (IsTruncMap n f).\nProof.\n  unfold IsTruncMap.\n  exact _.\nDefined.\n\n(** ** Alternate characterization of hprops. *)\n\nTheorem equiv_hprop_allpath `{Funext} (A : Type)\n  : IsHProp A <~> (forall (x y : A), x = y).\nProof.\n  apply (equiv_adjointify (@path_ishprop A) (@hprop_allpath A));\n  (* The proofs of the two homotopies making up this equivalence are almost identical.  First we start with a thing [f]. *)\n    intro f;\n  (* Then we apply funext a couple of times *)\n    apply path_forall; intro x;\n    apply path_forall; intro y;\n  (* Now we conclude that [A] is contractible *)\n    try pose (C := Build_Contr A x (f x));\n    try pose (D := contr_inhabited_hprop A x);\n  (* And conclude because we have a path in a contractible space. *)\n    apply path_contr.\nDefined.\n\nTheorem equiv_hprop_inhabited_contr `{Funext} {A}\n  : IsHProp A <~> (A -> Contr A).\nProof.\n  apply (equiv_adjointify (@contr_inhabited_hprop A) (@hprop_inhabited_contr A)).\n  - intro ic. by_extensionality x.\n    apply @path_contr. apply contr_contr. exact (ic x).\n  - intro hp. by_extensionality x. by_extensionality y.\n    apply @path_contr. apply contr_contr. exact (hp x y).\nDefined.\n\n(** Being an hprop is also equivalent to the diagonal being an equivalence. *)\nDefinition ishprop_isequiv_diag {A} `{IsEquiv _ _ (fun (a:A) => (a,a))}\n: IsHProp A.\nProof.\n  apply hprop_allpath; intros x y.\n  set (d := fun (a:A) => (a,a)) in *.\n  transitivity (fst (d (d^-1 (x,y)))).\n  - exact (ap fst (eisretr d (x,y))^).\n  - transitivity (snd (d (d^-1 (x,y)))).\n    + unfold d; reflexivity.\n    + exact (ap snd (eisretr d (x,y))).\nDefined.\n\nGlobal Instance isequiv_diag_ishprop {A} `{IsHProp A}\n: IsEquiv (fun (a:A) => (a,a)).\nProof.\n  refine (isequiv_adjointify _ fst _ _).\n  - intros [x y].\n    apply path_prod; simpl.\n    + reflexivity.\n    + apply path_ishprop.\n  - intros a; simpl.\n    reflexivity.\nDefined.\n\n(** ** A map is an embedding as soon as its ap's have sections. *)\n\nDefinition isembedding_sect_ap {X Y} (f : X -> Y)\n           (s : forall x1 x2, (f x1 = f x2) -> (x1 = x2))\n           (H : forall x1 x2, Sect (s x1 x2) (@ap X Y f x1 x2))\n  : IsEmbedding f.\nProof.\n  intros y.\n  apply hprop_allpath.\n  intros [x1 p1] [x2 p2].\n  apply path_sigma with (s x1 x2 (p1 @ p2^)).\n  abstract (rewrite transport_paths_Fl; cbn;\n            rewrite (H x1 x2 (p1 @ p2^));\n            rewrite inv_pp, inv_V; apply concat_pV_p).\nDefined.\n\n(** ** Alternate characterizations of contractibility. *)\n\nTheorem equiv_contr_inhabited_hprop `{Funext} {A}\n  : Contr A <~> A * IsHProp A.\nProof.\n  assert (f : Contr A -> A * IsHProp A).\n  - intro P. split.\n    + exact (@center _ P).\n    + apply @trunc_succ. exact P.\n  - assert (g : A * IsHProp A -> Contr A).\n    + intros [a P]. apply (@contr_inhabited_hprop _ P a).\n    + refine (@equiv_iff_hprop _ _ _ _ f g).\n      apply hprop_inhabited_contr; intro p.\n      apply @contr_prod.\n      * exact (g p).\n      * apply (@contr_inhabited_hprop _ _ (snd p)).\nDefined.\n\nTheorem equiv_contr_inhabited_allpath `{Funext} {A}\n  : Contr A <~> A * forall (x y : A), x = y.\nProof.\n  transitivity (A * IsHProp A).\n  - apply equiv_contr_inhabited_hprop.\n  - exact (1 *E equiv_hprop_allpath _).\nDefined.\n\n(** ** Logical equivalence of hprops *)\n\n(** Logical equivalence of hprops is not just logically equivalent to equivalence, it is equivalent to it. *)\nGlobal Instance isequiv_equiv_iff_hprop_uncurried\n       `{Funext} {A B} `{IsHProp A} `{IsHProp B}\n: IsEquiv (@equiv_iff_hprop_uncurried A _ B _) | 0.\nProof.\n  pose (@istrunc_equiv).\n  refine (isequiv_adjointify\n            equiv_iff_hprop_uncurried\n            (fun e => (@equiv_fun _ _ e, @equiv_inv _ _ e _))\n            _ _);\n    intro;\n      by apply path_ishprop.\nDefined.\n\nDefinition equiv_equiv_iff_hprop\n       `{Funext} (A B : Type) `{IsHProp A} `{IsHProp B}\n  : (A <-> B) <~> (A <~> B)\n  := Build_Equiv _ _ (@equiv_iff_hprop_uncurried A _ B _) _.\n\n(** ** Inhabited and uninhabited hprops *)\n\n(** If an hprop is inhabited, then it is equivalent to [Unit]. *)\nLemma if_hprop_then_equiv_Unit (hprop : Type) `{IsHProp hprop} :  hprop -> hprop <~> Unit.\nProof.\n  intro p.\n  apply equiv_iff_hprop.\n  - exact (fun _ => tt).\n  - exact (fun _ => p).\nDefined.\n\n(** If an hprop is not inhabited, then it is equivalent to [Empty]. *)\nLemma if_not_hprop_then_equiv_Empty (hprop : Type) `{IsHProp hprop} : ~hprop -> hprop <~> Empty.\nProof.\n  intro np.\n  exact (Build_Equiv _ _ np _).\nDefined.\n\n(** Thus, a decidable hprop is either equivalent to [Unit] or [Empty]. *)\nDefinition equiv_decidable_hprop (hprop : Type)\n           `{IsHProp hprop} `{Decidable hprop}\n: (hprop <~> Unit) + (hprop <~> Empty).\nProof.\n  destruct (dec hprop) as [x|nx].\n  - exact (inl (if_hprop_then_equiv_Unit hprop x)).\n  - exact (inr (if_not_hprop_then_equiv_Empty hprop nx)).\nDefined.\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/theories/HProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.6567775406319758}}
{"text": "Open Scope list_scope.\nRequire Import List.\n\nDefinition queue (alpha: Set): Set := list alpha * list alpha.\n\nDefinition empty (alpha: Set): queue alpha := (nil, nil).\n\nDefinition isEmpty {alpha: Set} (q: queue alpha) :=\n  match q with\n  | (nil, _) => true\n  | _ => false\n  end.\n\nDefinition checkf {alpha: Set} (q: queue alpha) :=\n  match q with\n  | (nil, r) => (rev r, nil)\n  | q' => q'\n  end.\n\nDefinition fst {alpha: Set} (q: queue alpha) :=\n  match q with\n  | (f, _) => f\n  end.\n\nDefinition snd {alpha: Set} (q: queue alpha) :=\n  match q with\n  | (_, s) => s\n  end.\n\nDefinition snoc {alpha: Set} (q: queue alpha)(x: alpha) :=\n  checkf (fst q, x :: snd q).\n\nDefinition head {alpha: Set} (q: queue alpha) :=\n  match q with\n  | (nil, _) =>  None\n  | (x :: f, r) => Some(x)\n  end.\n\nDefinition tail {alpha: Set} (q: queue alpha) :=\n  match q with\n  | (nil, _) =>  None\n  | (x :: f, r) => Some(checkf (f, r))\n  end.\n\nDefinition Invaliant {A: Set} (q: queue A) :=\n  let '(f, r) := q in\n  f = nil -> r = nil.\n\nLemma snoc_invaliant : forall (A:Set) (q: queue A) (x : A),\n    Invaliant q -> Invaliant (snoc q x).\nProof.\n  intros A q x H. destruct q as [f r]. unfold snoc, checkf. simpl.\n  destruct f.\n  - now unfold Invaliant.\n  - now unfold Invaliant.\nQed.\n\nLemma tail_invaliant : forall (A:Set) (q q': queue A),\n    Invaliant q -> Some q' = tail q -> Invaliant q'.\nProof.\n  intros A q q' H. destruct q as [f r].\n  destruct f.\n  - now unfold tail.\n  - unfold tail, checkf. intros Heq. injection Heq. intros Heq'. clear Heq. subst q'.\n    destruct f.\n    + now unfold Invaliant.\n    + now unfold Invaliant.\nQed.", "meta": {"author": "yoshihiro503", "repo": "pfds_coq", "sha": "e7bf965ddeb329886210811e05f1bd4a1e7ccf53", "save_path": "github-repos/coq/yoshihiro503-pfds_coq", "path": "github-repos/coq/yoshihiro503-pfds_coq/pfds_coq-e7bf965ddeb329886210811e05f1bd4a1e7ccf53/5/BatchedQueue.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.6567775385418357}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Export NAdd.\n\nModule NOrderProp (Import N : NAxiomsMiniSig').\nInclude NAddProp N.\n\n\n\nTheorem lt_wf_0 : well_founded lt.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.lt_wf_0\".  \nsetoid_replace lt with (fun n m => 0 <= n < m).\napply lt_wf.\nintros x y; split.\nintro H; split; [apply le_0_l | assumption]. now intros [_ H].\nDefined.\n\n\n\nTheorem nlt_0_r : forall n, ~ n < 0.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.nlt_0_r\".  \nintro n; apply le_ngt. apply le_0_l.\nQed.\n\nTheorem nle_succ_0 : forall n, ~ (S n <= 0).\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.nle_succ_0\".  \nintros n H; apply le_succ_l in H; false_hyp H nlt_0_r.\nQed.\n\nTheorem le_0_r : forall n, n <= 0 <-> n == 0.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.le_0_r\".  \nintros n; split; intro H.\nle_elim H; [false_hyp H nlt_0_r | assumption].\nnow apply eq_le_incl.\nQed.\n\nTheorem lt_0_succ : forall n, 0 < S n.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.lt_0_succ\".  \ninduct n; [apply lt_succ_diag_r | intros n H; now apply lt_lt_succ_r].\nQed.\n\nTheorem neq_0_lt_0 : forall n, n ~= 0 <-> 0 < n.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.neq_0_lt_0\".  \ncases n.\nsplit; intro H; [now elim H | intro; now apply lt_irrefl with 0].\nintro n; split; intro H; [apply lt_0_succ | apply neq_succ_0].\nQed.\n\nTheorem eq_0_gt_0_cases : forall n, n == 0 \\/ 0 < n.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.eq_0_gt_0_cases\".  \ncases n.\nnow left.\nintro; right; apply lt_0_succ.\nQed.\n\nTheorem zero_one : forall n, n == 0 \\/ n == 1 \\/ 1 < n.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.zero_one\".  \nsetoid_rewrite one_succ.\ninduct n. now left.\ncases n. intros; right; now left.\nintros n IH. destruct IH as [H | [H | H]].\nfalse_hyp H neq_succ_0.\nright; right. rewrite H. apply lt_succ_diag_r.\nright; right. now apply lt_lt_succ_r.\nQed.\n\nTheorem lt_1_r : forall n, n < 1 <-> n == 0.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.lt_1_r\".  \nsetoid_rewrite one_succ.\ncases n.\nsplit; intro; [reflexivity | apply lt_succ_diag_r].\nintros n. rewrite <- succ_lt_mono.\nsplit; intro H; [false_hyp H nlt_0_r | false_hyp H neq_succ_0].\nQed.\n\nTheorem le_1_r : forall n, n <= 1 <-> n == 0 \\/ n == 1.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.le_1_r\".  \nsetoid_rewrite one_succ.\ncases n.\nsplit; intro; [now left | apply le_succ_diag_r].\nintro n. rewrite <- succ_le_mono, le_0_r, succ_inj_wd.\nsplit; [intro; now right | intros [H | H]; [false_hyp H neq_succ_0 | assumption]].\nQed.\n\nTheorem lt_lt_0 : forall n m, n < m -> 0 < m.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.lt_lt_0\".  \nintros n m; induct n.\ntrivial.\nintros n IH H. apply IH; now apply lt_succ_l.\nQed.\n\nTheorem lt_1_l' : forall n m p, n < m -> m < p -> 1 < p.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.lt_1_l'\".  \nintros. apply lt_1_l with m; auto.\napply le_lt_trans with n; auto. now apply le_0_l.\nQed.\n\n\n\nSection RelElim.\n\nVariable R : relation N.t.\nHypothesis R_wd : Proper (N.eq==>N.eq==>iff) R.\n\nTheorem le_ind_rel :\n(forall m, R 0 m) ->\n(forall n m, n <= m -> R n m -> R (S n) (S m)) ->\nforall n m, n <= m -> R n m.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.le_ind_rel\".  \nintros Base Step; induct n.\nintros; apply Base.\nintros n IH m H. elim H using le_ind.\nsolve_proper.\napply Step; [| apply IH]; now apply eq_le_incl.\nintros k H1 H2. apply le_succ_l in H1. apply lt_le_incl in H1. auto.\nQed.\n\nTheorem lt_ind_rel :\n(forall m, R 0 (S m)) ->\n(forall n m, n < m -> R n m -> R (S n) (S m)) ->\nforall n m, n < m -> R n m.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.lt_ind_rel\".  \nintros Base Step; induct n.\nintros m H. apply lt_exists_pred in H; destruct H as [m' [H _]].\nrewrite H; apply Base.\nintros n IH m H. elim H using lt_ind.\nsolve_proper.\napply Step; [| apply IH]; now apply lt_succ_diag_r.\nintros k H1 H2. apply lt_succ_l in H1. auto.\nQed.\n\nEnd RelElim.\n\n\n\nTheorem succ_pred_pos : forall n, 0 < n -> S (P n) == n.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.succ_pred_pos\".  \nintros n H; apply succ_pred; intro H1; rewrite H1 in H.\nfalse_hyp H lt_irrefl.\nQed.\n\nTheorem le_pred_l : forall n, P n <= n.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.le_pred_l\".  \ncases n.\nrewrite pred_0; now apply eq_le_incl.\nintros; rewrite pred_succ;  apply le_succ_diag_r.\nQed.\n\nTheorem lt_pred_l : forall n, n ~= 0 -> P n < n.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.lt_pred_l\".  \ncases n.\nintro H; exfalso; now apply H.\nintros; rewrite pred_succ;  apply lt_succ_diag_r.\nQed.\n\nTheorem le_le_pred : forall n m, n <= m -> P n <= m.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.le_le_pred\".  \nintros n m H; apply le_trans with n. apply le_pred_l. assumption.\nQed.\n\nTheorem lt_lt_pred : forall n m, n < m -> P n < m.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.lt_lt_pred\".  \nintros n m H; apply le_lt_trans with n. apply le_pred_l. assumption.\nQed.\n\nTheorem lt_le_pred : forall n m, n < m -> n <= P m.\n\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.lt_le_pred\".  \nintro n; cases m.\nintro H; false_hyp H nlt_0_r.\nintros m IH. rewrite pred_succ; now apply lt_succ_r.\nQed.\n\nTheorem lt_pred_le : forall n m, P n < m -> n <= m.\n\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.lt_pred_le\".  \nintros n m; cases n.\nrewrite pred_0; intro H; now apply lt_le_incl.\nintros n IH. rewrite pred_succ in IH. now apply le_succ_l.\nQed.\n\nTheorem lt_pred_lt : forall n m, n < P m -> n < m.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.lt_pred_lt\".  \nintros n m H; apply lt_le_trans with (P m); [assumption | apply le_pred_l].\nQed.\n\nTheorem le_pred_le : forall n m, n <= P m -> n <= m.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.le_pred_le\".  \nintros n m H; apply le_trans with (P m); [assumption | apply le_pred_l].\nQed.\n\nTheorem pred_le_mono : forall n m, n <= m -> P n <= P m.\n\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.pred_le_mono\".  \nintros n m H; elim H using le_ind_rel.\nsolve_proper.\nintro; rewrite pred_0; apply le_0_l.\nintros p q H1 _; now do 2 rewrite pred_succ.\nQed.\n\nTheorem pred_lt_mono : forall n m, n ~= 0 -> (n < m <-> P n < P m).\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.pred_lt_mono\".  \nintros n m H1; split; intro H2.\nassert (m ~= 0). apply neq_0_lt_0. now apply lt_lt_0 with n.\nnow rewrite <- (succ_pred n) in H2; rewrite <- (succ_pred m) in H2 ;\n[apply succ_lt_mono | | |].\nassert (m ~= 0). apply neq_0_lt_0. apply lt_lt_0 with (P n).\napply lt_le_trans with (P m). assumption. apply le_pred_l.\napply succ_lt_mono in H2. now do 2 rewrite succ_pred in H2.\nQed.\n\nTheorem lt_succ_lt_pred : forall n m, S n < m <-> n < P m.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.lt_succ_lt_pred\".  \nintros n m. rewrite pred_lt_mono by apply neq_succ_0. now rewrite pred_succ.\nQed.\n\nTheorem le_succ_le_pred : forall n m, S n <= m -> n <= P m.\n\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.le_succ_le_pred\".  \nintros n m H. apply lt_le_pred. now apply le_succ_l.\nQed.\n\nTheorem lt_pred_lt_succ : forall n m, P n < m -> n < S m.\n\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.lt_pred_lt_succ\".  \nintros n m H. apply lt_succ_r. now apply lt_pred_le.\nQed.\n\nTheorem le_pred_le_succ : forall n m, P n <= m <-> n <= S m.\nProof. hammer_hook \"NOrder\" \"NOrder.NOrderProp.le_pred_le_succ\".  \nintros n m; cases n.\nrewrite pred_0. split; intro H; apply le_0_l.\nintro n. rewrite pred_succ. apply succ_le_mono.\nQed.\n\nEnd NOrderProp.\n\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Numbers/Natural/Abstract/NOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.6567775368275184}}
{"text": "\n\n\n\n(* -----------------Description --------------------------------------------------\n   \n   This file summarises some useful results from List Module of standard Library. \n   We create a hint database to remember important results regarding lists (hint_list).\n\n   Some new definitions:\n   Definition Empty (s:list A):Prop := forall a : A, ~ In a s.\n   Definition Equal (s s': list A) := forall a : A, In a s <-> In a s'.\n   Definition Subset (s s': list A) := forall a : A, In a s -> In a s'.\n\n   Notation \"s [=] t\" := (Equal s t) (at level 70, no associativity).\n   Notation \"s [<=] t\" := (Subset s t) (at level 70, no associativity).\n   Notation \"| s |\":= (length s) (at level 70, no associativity).\n\n  --------------------   ------------------  ------------------------------------- *)\n\n\n\nFrom Coq Require Export ssreflect  ssrbool.\nRequire Export Lists.List Omega.\n\nSet Implicit Arguments.\n\nHint Resolve in_eq in_cons in_inv in_nil in_dec: core.\n\nSection BasicListFacts.\n  Variable A:Type.\n  Lemma in_inv1 : forall (a b:A) (l:list A), In b (a :: l) -> b = a \\/ In b l.\n  Proof. { intros  a b l H. cut (a=b \\/ In b l).\n       Focus 2. auto.  intros H1; destruct H1 as [H1 | H2].\n       left; symmetry; auto. right;auto. } Qed.\n  Lemma in_inv2: forall (x a:A) (l:list A), In x (a::l)-> x <> a -> In x l.\n  Proof.  { intros x a l H. cut (x=a \\/ In x l). intro H1;destruct H1 as [Hl1|Hr1].\n          intro;contradiction. auto. eapply in_inv1;auto. } Qed.\n  Lemma in_inv3: forall (x a:A) (l:list A), In x (a::l)-> ~ In x l -> x = a.\n    Proof.  { intros x a l H. cut (x=a \\/ In x l). intro H1;destruct H1 as [Hl1|Hr1].\n          intro;auto. intro;contradiction.  eapply in_inv1;auto. } Qed.\n  Hint Resolve in_inv1 in_inv2 in_inv3 : core.\n  (*---------Some facts about NoDup on a list --------------------------------*)\n  Lemma nodup_intro (a:A)(l: list A): ~ In a l -> NoDup l -> NoDup (a::l).\n    Proof.  intros H1 H2; eapply NoDup_cons_iff;tauto.  Qed. \n  Lemma nodup_elim1 (a:A)(l: list A): NoDup (a::l)-> NoDup (l).\n  Proof. intro H. eapply NoDup_cons_iff; eauto. Qed.\n  Lemma nodup_elim2 (a:A)(l: list A): NoDup (a::l) -> ~ In a l.\n    Proof. intro H. eapply NoDup_cons_iff; eauto. Qed. \n  \n  Hint Immediate nodup_elim1  nodup_elim2  nodup_intro : core.\n  End BasicListFacts.\nHint Resolve in_inv1 in_inv2 in_inv3: core.\nHint Immediate nodup_elim1  nodup_elim2  nodup_intro : core.\n\n\n\nSection SetSpec.\n  Variable A:Type.\n  Definition Empty (s:list A):Prop := forall a : A, ~ In a s.\n  \n  Definition Subset (s s': list A) := forall a : A, In a s -> In a s'.\n  Definition Equal (s s': list A):= Subset s s' /\\ Subset s' s.\n  \n  (* Inductive Forall (A : Type) (P : A -> Prop) : list A -> Prop := \n     | Forall_nil : Forall P nil \n     | Forall_cons : forall (x : A) (l : list A), P x -> Forall P l -> Forall P (x :: l)  *)\n  \n  (* Inductive Exists (A : Type) (P : A -> Prop) : list A -> Prop :=\n      |Exists_cons_hd : forall (x : A) (l : list A), P x -> Exists P (x :: l) \n      | Exists_cons_tl : forall (x : A) (l : list A), Exists P l -> Exists P (x :: l) *)\n  \n  (* Inductive NoDup (A : Type) : list A -> Prop := \n      | NoDup_nil : NoDup nil \n      | NoDup_cons : forall (x : A) (l : list A), ~ In x l -> NoDup l -> NoDup (x :: l) *)\nEnd SetSpec.\n\nLtac unfold_spec := try(unfold Equal);try(unfold Subset);try(unfold Empty).\n\n\n\n  Notation \"s [=] t\" := (Equal s t) (at level 70, no associativity).\n  Notation \"s [<=] t\" := (Subset s t) (at level 70, no associativity).\n  Notation \"| s |\":= (length s) (at level 70, no associativity).\n  \n\nSection BasicSetFacts.\n  Variable A:Type.\n\n  (*-----------------------Subset (spec) and its properties ------------------------*)\n  Lemma Subset_intro (a:A)(l s: list A): l [<=] s -> (a::l) [<=] (a::s).\n  Proof. intros H x H1.  destruct H1. subst a;auto. auto. Qed.\n  Lemma Subset_intro1 (a:A)(l s: list A): l [<=] s -> l [<=] (a::s).\n    Proof. intros H x H1. simpl;right;auto. Qed.\n  Lemma Subset_elim1 (a:A) (s s':list A): Subset (a:: s) s'-> In a s'.\n  Proof. { unfold Subset. intro H. apply H. auto. } Qed.\n   Lemma Subset_elim2 (a:A) (s s':list A): Subset (a:: s) s'->  Subset s s'.\n  Proof. { unfold Subset. intro H.  intros a1 H1.\n           apply H. auto. } Qed.\n  Lemma self_incl (l:list A): l [<=] l.\n  Proof. unfold Subset; tauto.  Qed. \n  Hint Resolve self_incl: core.\n\n  Lemma Subset_nil (l: list A): nil [<=] l.\n  Proof. unfold \"[<=]\"; simpl; intros; contradiction. Qed.\n  Lemma Subset_of_nil (l: list A): l [<=] nil -> l=nil.\n    Proof. induction l. auto. intro H. absurd (In a nil); auto. Qed.\n\n  Lemma Subset_trans (l1 l2 l3: list A): l1 [<=] l2 -> l2 [<=] l3 -> l1 [<=] l3.\n  Proof. intros H H1 x Hx1. eauto. Qed. \n   \nHint Extern 0 (?x [<=] ?z)  =>\nmatch goal with\n| H: (x [<=] ?y) |- _ => apply (@Subset_trans  x y z)\n| H: (?y [<=] z) |- _ => apply (@Subset_trans  x y z)                                   \nend.\n  \n  (* ---------------------- Equal (spec) and their properties--------------------*)\n  Lemma Eq_refl (s: list A):  s [=] s.\n  Proof.  unfold Equal. split;auto using self_incl.  Qed. \n  Lemma Eq_sym (s s':list A): s [=] s' -> s' [=] s.\n  Proof. unfold Equal.  tauto. Qed. \n  Lemma Eq_trans1 ( x y z : list A) : x [=] y -> y [=] z -> x [=] z.\n  Proof. { unfold Equal.  intros H H1. destruct H as [H0 H]; destruct H1 as [H1a H1].\n           split; auto. } Qed.\n\n Hint Extern 0 (?x [=] ?z)  =>\nmatch goal with\n| H: (x [=] ?y) |- _ => apply (@Eq_trans1  x y z)\n| H: (?y [=] z) |- _ => apply (@Eq_trans1  x y z)                                   \nend.\n\n\n  Lemma Equal_intro (s s': list A): s [<=] s' -> s' [<=] s -> s [=] s'.\n  Proof. unfold \"[=]\".  tauto. Qed.\n  Lemma Equal_intro1 (s s': list A): s = s' -> Equal s s'.\n  Proof. intro; subst s; apply Eq_refl; auto. Qed.\n  Lemma Equal_elim ( s s': list A): s [=] s' ->  s [<=] s' /\\ s' [<=] s.\n  Proof. unfold_spec; unfold iff. intros H; split; intro a;apply H. Qed.\n\n  (* ---------------- introduction and elimination for filter operation---------- *)\n  (* Check filter :  forall A : Type, (A -> bool) -> list A -> list A *)\n  (* Check filter_In : forall (A : Type) (f : A -> bool) (x : A) (l : list A),\n       In x (filter f l) <-> In x l /\\ f x = true *)\n  Lemma filter_elim1 (f: A->bool)(l: list A)(x: A): In x (filter f l)-> In x l.\n  Proof. apply filter_In. Qed.\n  Lemma filter_elim2 (f: A->bool)(l: list A)(x: A): In x (filter f l)-> (f x).\n  Proof. apply filter_In. Qed.\n  Lemma filter_intro (f: A->bool)(l: list A)(x: A): In x l -> (f x)-> In x (filter f l).\n  Proof. intros; apply filter_In; split;auto. Qed.\n\n  Hint Immediate filter_elim1 filter_elim2 filter_intro: core.\n\n\n (*--------Strong Induction, Well founded induction and set cardinality ----------*)\n\n  \nTheorem strong_induction: forall P : nat -> Prop,\n                    (forall n : nat, (forall k : nat, (k < n -> P k)) -> P n) ->\n                    forall n : nat, P n.\nProof. { intros P Strong_IH n.\n         pose (Q:= fun (n: nat)=> forall k:nat, k<= n -> P k). \n         assert (H: Q n);unfold Q. \n         { induction n. \n           { intros k H;apply Strong_IH.\n             intros k0 H1.  cut (k0 < 0). intro H2; inversion H2. omega.  } \n           { intros k H0.\n             assert (H1: k < (S n) \\/ k = (S n) ).  apply le_lt_or_eq; auto.\n             elim H1. intro. apply IHn. omega. \n             intro H. subst k. apply Strong_IH. intros. apply IHn. omega. } }\n         unfold Q in H. apply H. omega. }   Qed. \n\nDefinition lt_set (l1 l2: list A):= |l1| < |l2|.\n\nLemma lt_set_is_well_founded: well_founded lt_set.\nProof. { unfold well_founded. intro a.\n       remember (|a|) as n. revert Heqn. revert a.\n       induction n using strong_induction.\n       { intros a H1. apply Acc_intro.\n         intros a0 H2. apply H with (k:= |a0|).\n         subst n; apply H2. auto. } } Qed.\n\n\n\nLemma non_zero_size (a:A)(l: list A): In a l -> |l| > 0.\n  Proof. { induction l.\n         { simpl; tauto. }\n         { intros. simpl. omega. } } Qed.\n\nHint Resolve non_zero_size: core.  \n \nEnd BasicSetFacts.\n\n\n   \nHint Extern 0 (?x [<=] ?z)  =>\nmatch goal with\n| H: (x [<=] ?y) |- _ => apply (@Subset_trans _ x y z)\n| H: (?y [<=] z) |- _ => apply (@Subset_trans _ x y z)                                   \nend.\n\nHint Extern 0 (?x [=] ?z)  =>\nmatch goal with\n| H: (x [=] ?y) |- _ => apply (@Eq_trans1 _ x y z)\n| H: (?y [=] z) |- _ => apply (@Eq_trans1 _ x y z)                                   \nend.\n\n\nHint Immediate Eq_refl Eq_sym Equal_elim Equal_intro Equal_intro1: core.\nHint Immediate  Subset_elim1 Subset_elim2 Subset_nil Subset_of_nil: core.\nHint Resolve  self_incl: core.\nHint Resolve Subset_intro Subset_intro1: core.\n\nHint Immediate filter_elim1 filter_elim2 filter_intro: core.\n\nHint Resolve lt_set_is_well_founded: core.\n\nHint Resolve non_zero_size: 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/SetSpecs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.80563219364797, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.656777535113201}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun.\n\n(******************************************************************************)\n(* A theory of boolean predicates and operators. A large part of this file is *)\n(* concerned with boolean reflection.                                         *)\n(* Definitions and notations:                                                 *)\n(*               is_true b == the coercion of b : bool to Prop (:= b = true). *)\n(*                            This is just input and displayed as `b''.       *)\n(*             reflect P b == the reflection inductive predicate, asserting   *)\n(*                            that the logical proposition P : prop with the  *)\n(*                            formula b : bool. Lemmas asserting reflect P b  *)\n(*                            are often referred to as \"views\".               *)\n(*  iffP, appP, sameP, rwP :: lemmas for direct manipulation of reflection    *)\n(*                            views: iffP is used to prove reflection from    *)\n(*                            logical equivalence, appP to compose views, and *)\n(*                            sameP and rwP to perform boolean and setoid     *)\n(*                            rewriting.                                      *)\n(*                   elimT :: coercion reflect >-> Funclass, which allows the *)\n(*                            direct application of `reflect' views to        *)\n(*                            boolean assertions.                             *)\n(*             decidable P <-> P is effectively decidable (:= {P} + {~ P}.    *)\n(*    contra, contraL, ... :: contraposition lemmas.                          *)\n(*           altP my_viewP :: natural alternative for reflection; given       *)\n(*                            lemma myvieP: reflect my_Prop my_formula,       *)\n(*                              have [myP | not_myP] := altP my_viewP.        *)\n(*                            generates two subgoals, in which my_formula has *)\n(*                            been replaced by true and false, resp., with    *)\n(*                            new assumptions myP : my_Prop and               *)\n(*                            not_myP: ~~ my_formula.                         *)\n(*                            Caveat: my_formula must be an APPLICATION, not  *)\n(*                            a variable, constant, let-in, etc. (due to the  *)\n(*                            poor behaviour of dependent index matching).    *)\n(*        boolP my_formula :: boolean disjunction, equivalent to              *)\n(*                            altP (idP my_formula) but circumventing the     *)\n(*                            dependent index capture issue; destructing      *)\n(*                            boolP my_formula generates two subgoals with    *)\n(*                            assumtions my_formula and ~~ myformula. As      *)\n(*                            with altP, my_formula must be an application.   *)\n(*              unless C P <-> hP : P may be assumed when proving P.          *)\n(*                         := (P -> C) -> C (Pierce's law).                   *)\n(*                            This is slightly weaker but easier to use than  *)\n(*                            P \\/ C when P C : Prop.                         *)\n(*           classically P <-> hP : P can be assumed when proving is_true b   *)\n(*                         := forall b : bool, (P -> b) -> b.                 *)\n(*                            This is equivalent to ~ (~ P) when P : Prop.    *)\n(*                  a && b == the boolean conjunction of a and b.             *)\n(*                  a || b == then boolean disjunction of a and b.            *)\n(*                 a ==> b == the boolean implication of b by a.              *)\n(*                    ~~ a == the boolean negation of a.                      *)\n(*                 a (+) b == the boolean exclusive or (or sum) of a and b.   *)\n(*     [ /\\ P1 , P2 & P3 ] == multiway logical conjunction, up to 5 terms.    *)\n(*     [ \\/ P1 , P2 | P3 ] == multiway logical disjunction, up to 4 terms.    *)\n(*        [&& a, b, c & d] == iterated, right associative boolean conjunction *)\n(*                            with arbitrary arity.                           *)\n(*        [|| a, b, c | d] == iterated, right associative boolean disjunction *)\n(*                            with arbitrary arity.                           *)\n(*      [==> a, b, c => d] == iterated, right associative boolean implication *)\n(*                            with arbitrary arity.                           *)\n(*              and3P, ... == specific reflection lemmas for iterated         *)\n(*                            connectives.                                    *)\n(*       andTb, orbAC, ... == systematic names for boolean connective         *)\n(*                            properties (see suffix conventions below).      *)\n(*              prop_congr == a tactic to move a boolean equality from        *)\n(*                            its coerced form in Prop to the equality        *)\n(*                            in bool.                                        *)\n(*              bool_congr == resolution tactic for blindly weeding out       *)\n(*                            like terms from boolean equalities (can fail).  *)\n(* This file provides a theory of boolean predicates and relations:           *)\n(*                  pred T == the type of bool predicates (:= T -> bool).     *)\n(*            simpl_pred T == the type of simplifying bool predicates, using  *)\n(*                            the simpl_fun from ssrfun.v.                    *)\n(*                   rel T == the type of bool relations.                     *)\n(*                         := T -> pred T or T -> T -> bool.                  *)\n(*             simpl_rel T == type of simplifying relations.                  *)\n(*                predType == the generic predicate interface, supported for  *)\n(*                            for lists and sets.                             *)\n(*              pred_class == a coercion class for the predType projection to *)\n(*                            pred; declaring a coercion to pred_class is an  *)\n(*                            alternative way of equipping a type with a      *)\n(*                            predType structure, which interoperates better  *)\n(*                            with coercion subtyping. This is used, e.g.,    *)\n(*                            for finite sets, so that finite groups inherit  *)\n(*                            the membership operation by coercing to sets.   *)\n(* If P is a predicate the proposition \"x satisfies P\" can be written         *)\n(* applicatively as (P x), or using an explicit connective as (x \\in P); in   *)\n(* the latter case we say that P is a \"collective\" predicate. We use A, B     *)\n(* rather than P, Q for collective predicates:                                *)\n(*                 x \\in A == x satisfies the (collective) predicate A.       *)\n(*              x \\notin A == x doesn't satisfy the (collective) predicate A. *)\n(* The pred T type can be used as a generic predicate type for either kind,   *)\n(* but the two kinds of predicates should not be confused. When a \"generic\"   *)\n(* pred T value of one type needs to be passed as the other the following     *)\n(* conversions should be used explicitly:                                     *)\n(*             SimplPred P == a (simplifying) applicative equivalent of P.    *)\n(*                   mem A == an applicative equivalent of A:                 *)\n(*                            mem A x simplifies to x \\in A.                  *)\n(* Alternatively one can use the syntax for explicit simplifying predicates   *)\n(* and relations (in the following x is bound in E):                          *)\n(*            [pred x | E] == simplifying (see ssrfun) predicate x => E.      *)\n(*        [pred x : T | E] == predicate x => T, with a cast on the argument.  *)\n(*          [pred : T | P] == constant predicate P on type T.                 *)\n(*      [pred x | E1 & E2] == [pred x | E1 && E2]; an x : T cast is allowed.  *)\n(*           [pred x in A] == [pred x | x in A].                              *)\n(*       [pred x in A | E] == [pred x | x in A & E].                          *)\n(* [pred x in A | E1 & E2] == [pred x in A | E1 && E2].                       *)\n(*           [predU A & B] == union of two collective predicates A and B.     *)\n(*           [predI A & B] == intersection of collective predicates A and B.  *)\n(*           [predD A & B] == difference of collective predicates A and B.    *)\n(*               [predC A] == complement of the collective predicate A.       *)\n(*          [preim f of A] == preimage under f of the collective predicate A. *)\n(*          predU P Q, ... == union, etc of applicative predicates.           *)\n(*                   pred0 == the empty predicate.                            *)\n(*                   predT == the total (always true) predicate.              *)\n(*                            if T : predArgType, then T coerces to predT.    *)\n(*                   {: T} == T cast to predArgType (e.g., {: bool * nat})    *)\n(* In the following, x and y are bound in E:                                  *)\n(*           [rel x y | E] == simplifying relation x, y => E.                 *)\n(*       [rel x y : T | E] == simplifying relation with arguments cast.       *)\n(*  [rel x y in A & B | E] == [rel x y | [&& x \\in A, y \\in B & E]].          *)\n(*      [rel x y in A & B] == [rel x y | (x \\in A) && (y \\in B)].             *)\n(*      [rel x y in A | E] == [rel x y in A & A | E].                         *)\n(*          [rel x y in A] == [rel x y in A & A].                             *)\n(*                relU R S == union of relations R and S.                     *)\n(* Explicit values of type pred T (i.e., lamdba terms) should always be used  *)\n(* applicatively, while values of collection types implementing the predType  *)\n(* interface, such as sequences or sets should always be used as collective   *)\n(* predicates. Defined constants and functions of type pred T or simpl_pred T *)\n(* as well as the explicit simpl_pred T values described below, can generally *)\n(* be used either way. Note however that x \\in A will not auto-simplify when  *)\n(* A is an explicit simpl_pred T value; the generic simplification rule inE   *)\n(* must be used (when A : pred T, the unfold_in rule can be used). Constants  *)\n(* of type pred T with an explicit simpl_pred value do not auto-simplify when *)\n(* used applicatively, but can still be expanded with inE. This behavior can  *)\n(* be controlled as follows:                                                  *)\n(*   Let A : collective_pred T := [pred x | ... ].                            *)\n(*     The collective_pred T type is just an alias for pred T, but this cast  *)\n(*     stops rewrite inE from expanding the definition of A, thus treating A  *)\n(*     into an abstract collection (unfold_in or in_collective can be used to *)\n(*     expand manually).                                                      *)\n(*   Let A : applicative_pred T := [pred x | ...].                            *)\n(*     This cast causes inE to turn x \\in A into the applicative A x form;    *)\n(*     A will then have to unfolded explicitly with the /A rule. This will    *)\n(*     also apply to any definition that reduces to A (e.g., Let B := A).     *)\n(*   Canonical A_app_pred := ApplicativePred A.                               *)\n(*     This declaration, given after definition of A, similarly causes inE to *)\n(*     turn x \\in A into A x, but in addition allows the app_predE rule to    *)\n(*     turn A x back into x \\in A; it can be used for any definition of type  *)\n(*     pred T, which makes it especially useful for ambivalent predicates     *)\n(*     as the relational transitive closure connect, that are used in both    *)\n(*     applicative and collective styles.                                     *)\n(* Purely for aesthetics, we provide a subtype of collective predicates:      *)\n(*   qualifier q T == a pred T pretty-printing wrapper. An A : qualifier q T  *)\n(*                    coerces to pred_class and thus behaves as a collective  *)\n(*                    predicate, but x \\in A and x \\notin A are displayed as: *)\n(*             x \\is A and x \\isn't A when q = 0,                             *)\n(*         x \\is a A and x \\isn't a A when q = 1,                             *)\n(*       x \\is an A and x \\isn't an A when q = 2, respectively.               *)\n(*   [qualify x | P] := Qualifier 0 (fun x => P), constructor for the above.  *)\n(* [qualify x : T | P], [qualify a x | P], [qualify an X | P], etc.           *)\n(*                  variants of the above with type constraints and different *)\n(*                  values of q.                                              *)\n(* We provide an internal interface to support attaching properties (such as  *)\n(* being multiplicative) to predicates:                                       *)\n(*    pred_key p == phantom type that will serve as a support for properties  *)\n(*                  to be attached to p : pred_class; instances should be     *)\n(*                  created with Fact/Qed so as to be opaque.                 *)\n(* KeyedPred k_p == an instance of the interface structure that attaches      *)\n(*                  (k_p : pred_key P) to P; the structure projection is a    *)\n(*                  coercion to pred_class.                                   *)\n(* KeyedQualifier k_q == an instance of the interface structure that attaches *)\n(*                  (k_q : pred_key q) to (q : qualifier n T).                *)\n(* DefaultPredKey p == a default value for pred_key p; the vernacular command *)\n(*                  Import DefaultKeying attaches this key to all predicates  *)\n(*                  that are not explicitly keyed.                            *)\n(* Keys can be used to attach properties to predicates, qualifiers and        *)\n(* generic nouns in a way that allows them to be used tranparently. The key   *)\n(* projection of a predicate property structure such as unsignedPred should   *)\n(* be a pred_key, not a pred, and corresponding lemmas will have the form     *)\n(*    Lemma rpredN R S (oppS : @opprPred R S) (kS : keyed_pred oppS) :        *)\n(*       {mono -%R: x / x \\in kS}.                                            *)\n(* Because x \\in kS will be displayed as x \\in S (or x \\is S, etc), the       *)\n(* canonical instance of opprPred will not normally be exposed (it will also  *)\n(* be erased by /= simplification). In addition each predicate structure      *)\n(* should have a DefaultPredKey Canonical instance that simply issues the     *)\n(* property as a proof obligation (which can be caught by the Prop-irrelevant *)\n(* feature of the ssreflect plugin).                                          *)\n(*   Some properties of predicates and relations:                             *)\n(*                  A =i B <-> A and B are extensionally equivalent.          *)\n(*         {subset A <= B} <-> A is a (collective) subpredicate of B.         *)\n(*             subpred P Q <-> P is an (applicative) subpredicate or Q.       *)\n(*              subrel R S <-> R is a subrelation of S.                       *)\n(* In the following R is in rel T:                                            *)\n(*             reflexive R <-> R is reflexive.                                *)\n(*           irreflexive R <-> R is irreflexive.                              *)\n(*             symmetric R <-> R (in rel T) is symmetric (equation).          *)\n(*         pre_symmetric R <-> R is symmetric (implication).                  *)\n(*         antisymmetric R <-> R is antisymmetric.                            *)\n(*                 total R <-> R is total.                                    *)\n(*            transitive R <-> R is transitive.                               *)\n(*       left_transitive R <-> R is a congruence on its left hand side.       *)\n(*      right_transitive R <-> R is a congruence on its right hand side.      *)\n(*       equivalence_rel R <-> R is an equivalence relation.                  *)\n(* Localization of (Prop) predicates; if P1 is convertible to forall x, Qx,   *)\n(* P2 to forall x y, Qxy and P3 to forall x y z, Qxyz :                       *)\n(*            {for y, P1} <-> Qx{y / x}.                                      *)\n(*             {in A, P1} <-> forall x, x \\in A -> Qx.                        *)\n(*       {in A1 & A2, P2} <-> forall x y, x \\in A1 -> y \\in A2 -> Qxy.        *)\n(*           {in A &, P2} <-> forall x y, x \\in A -> y \\in A -> Qxy.          *)\n(*  {in A1 & A2 & A3, Q3} <-> forall x y z,                                   *)\n(*                            x \\in A1 -> y \\in A2 -> z \\in A3 -> Qxyz.       *)\n(*     {in A1 & A2 &, Q3} == {in A1 & A2 & A2, Q3}.                           *)\n(*      {in A1 && A3, Q3} == {in A1 & A1 & A3, Q3}.                           *)\n(*          {in A &&, Q3} == {in A & A & A, Q3}.                              *)\n(*    {in A, bijective f} == f has a right inverse in A.                      *)\n(*             {on C, P1} == forall x, (f x) \\in C -> Qx                      *)\n(*                           when P1 is also convertible to Pf f.             *)\n(*           {on C &, P2} == forall x y, f x \\in C -> f y \\in C -> Qxy        *)\n(*                           when P2 is also convertible to Pf f.             *)\n(*        {on C, P1' & g} == forall x, (f x) \\in cd -> Qx                     *)\n(*                           when P1' is convertible to Pf f                  *)\n(*                           and P1' g is convertible to forall x, Qx.        *)\n(*    {on C, bijective f} == f has a right inverse on C.                      *)\n(* This file extends the lemma name suffix conventions of ssrfun as follows:  *)\n(*   A -- associativity, as in andbA : associative andb.                      *)\n(*  AC -- right commutativity.                                                *)\n(* ACA -- self-interchange (inner commutativity), e.g.,                       *)\n(*        orbACA : (a || b) || (c || d) = (a || c) || (b || d).               *)\n(*   b -- a boolean argument, as in andbb : idempotent andb.                  *)\n(*   C -- commutativity, as in andbC : commutative andb,                      *)\n(*        or predicate complement, as in predC.                               *)\n(*  CA -- left commutativity.                                                 *)\n(*   D -- predicate difference, as in predD.                                  *)\n(*   E -- elimination, as in negbEf : ~~ b = false -> b.                      *)\n(*   F or f -- boolean false, as in andbF : b && false = false.               *)\n(*   I -- left/right injectivity, as in addbI : right_injective addb,         *)\n(*        or predicate intersection, as in predI.                             *)\n(*   l -- a left-hand operation, as andb_orl : left_distributive andb orb.    *)\n(*   N or n -- boolean negation, as in andbN : a && (~~ a) = false.           *)\n(*   P -- a characteristic property, often a reflection lemma, as in          *)\n(*        andP : reflect (a /\\ b) (a && b).                                   *)\n(*   r -- a right-hand operation, as orb_andr : rightt_distributive orb andb. *)\n(*   T or t -- boolean truth, as in andbT: right_id true andb.                *)\n(*   U -- predicate union, as in predU.                                       *)\n(*   W -- weakening, as in in1W : {in D, forall x, P} -> forall x, P.         *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nReserved Notation \"~~ b\" (at level 35, right associativity).\nReserved Notation \"b ==> c\" (at level 55, right associativity).\nReserved Notation \"b1  (+)  b2\" (at level 50, left associativity).\nReserved Notation \"x \\in A\"\n  (at level 70, format \"'[hv' x '/ '  \\in  A ']'\", no associativity).\nReserved Notation \"x \\notin A\"\n  (at level 70, format \"'[hv' x '/ '  \\notin  A ']'\", no associativity).\nReserved Notation \"p1 =i p2\"\n  (at level 70, format \"'[hv' p1 '/ '  =i  p2 ']'\", no associativity).\n\n(* We introduce a number of n-ary \"list-style\" notations that share a common  *)\n(* format, namely                                                             *)\n(*    [op arg1, arg2, ... last_separator last_arg]                            *)\n(* This usually denotes a right-associative applications of op, e.g.,         *)\n(*  [&& a, b, c & d] denotes a && (b && (c && d))                             *)\n(* The last_separator must be a non-operator token. Here we use &, | or =>;   *)\n(* our default is &, but we try to match the intended meaning of op. The      *)\n(* separator is a workaround for limitations of the parsing engine; the same  *)\n(* limitations mean the separator cannot be omitted even when last_arg can.   *)\n(*   The Notation declarations are complicated by the separate treatment for  *)\n(* some fixed arities (binary for bool operators, and all arities for Prop    *)\n(* operators).                                                                *)\n(*   We also use the square brackets in comprehension-style notations         *)\n(*    [type var separator expr]                                               *)\n(* where \"type\" is the type of the comprehension (e.g., pred) and \"separator\" *)\n(* is | or => . It is important that in other notations a leading square      *)\n(* bracket [ is always by an operator symbol or a fixed identifier.           *)\n\nReserved Notation \"[ /\\ P1 & P2 ]\" (at level 0, only parsing).\nReserved Notation \"[ /\\ P1 , P2 & P3 ]\" (at level 0, format\n  \"'[hv' [ /\\ '['  P1 , '/'  P2 ']' '/ '  &  P3 ] ']'\").\nReserved Notation \"[ /\\ P1 , P2 , P3 & P4 ]\" (at level 0, format\n  \"'[hv' [ /\\ '['  P1 , '/'  P2 , '/'  P3 ']' '/ '  &  P4 ] ']'\").\nReserved Notation \"[ /\\ P1 , P2 , P3 , P4 & P5 ]\" (at level 0, format\n  \"'[hv' [ /\\ '['  P1 , '/'  P2 , '/'  P3 , '/'  P4 ']' '/ '  &  P5 ] ']'\").\n\nReserved Notation \"[ \\/ P1 | P2 ]\" (at level 0, only parsing).\nReserved Notation \"[ \\/ P1 , P2 | P3 ]\" (at level 0, format\n  \"'[hv' [ \\/ '['  P1 , '/'  P2 ']' '/ '  |  P3 ] ']'\").\nReserved Notation \"[ \\/ P1 , P2 , P3 | P4 ]\" (at level 0, format\n  \"'[hv' [ \\/ '['  P1 , '/'  P2 , '/'  P3 ']' '/ '  |  P4 ] ']'\").\n\nReserved Notation \"[ && b1 & c ]\" (at level 0, only parsing).\nReserved Notation \"[ && b1 , b2 , .. , bn & c ]\" (at level 0, format\n  \"'[hv' [ && '['  b1 , '/'  b2 , '/'  .. , '/'  bn ']' '/ '  &  c ] ']'\").\n\nReserved Notation \"[ || b1 | c ]\" (at level 0, only parsing).\nReserved Notation \"[ || b1 , b2 , .. , bn | c ]\" (at level 0, format\n  \"'[hv' [ || '['  b1 , '/'  b2 , '/'  .. , '/'  bn ']' '/ '  |  c ] ']'\").\n\nReserved Notation \"[ ==> b1 => c ]\" (at level 0, only parsing).\nReserved Notation \"[ ==> b1 , b2 , .. , bn => c ]\" (at level 0, format\n  \"'[hv' [ ==> '['  b1 , '/'  b2 , '/'  .. , '/'  bn ']' '/'  =>  c ] ']'\").\n\nReserved Notation \"[ 'pred' : T => E ]\" (at level 0, format\n  \"'[hv' [ 'pred' :  T  => '/ '  E ] ']'\").\nReserved Notation \"[ 'pred' x => E ]\" (at level 0, x at level 8, format\n  \"'[hv' [ 'pred'  x  => '/ '  E ] ']'\").\nReserved Notation \"[ 'pred' x : T => E ]\" (at level 0, x at level 8, format\n  \"'[hv' [ 'pred'  x  :  T  => '/ '  E ] ']'\").\n\nReserved Notation \"[ 'rel' x y => E ]\" (at level 0, x, y at level 8, format\n  \"'[hv' [ 'rel'  x   y  => '/ '  E ] ']'\").\nReserved Notation \"[ 'rel' x y : T => E ]\" (at level 0, x, y at level 8, format\n  \"'[hv' [ 'rel'  x  y :  T  => '/ '  E ] ']'\").\n\n(* Shorter delimiter *)\nDelimit Scope bool_scope with B.\nOpen Scope bool_scope.\n\n(* An alternative to xorb that behaves somewhat better wrt simplification.    *)\nDefinition addb b := if b then negb else id.\n\n(* Notation for && and || is declared in Init.Datatypes. *)\nNotation \"~~ b\" := (negb b) : bool_scope.\nNotation \"b ==> c\" := (implb b c) : bool_scope.\nNotation \"b1 (+) b2\" := (addb b1 b2) : bool_scope.\n\n(* Constant is_true b := b = true is defined in Init.Datatypes. *)\nCoercion is_true : bool >-> Sortclass. (* Prop *)\n\nLemma prop_congr : forall b b' : bool, b = b' -> b = b' :> Prop.\nProof. by move=> b b' ->. Qed.\n\nLtac prop_congr := apply: prop_congr.\n\n(* Lemmas for trivial. *)\nLemma is_true_true : true.               Proof. by []. Qed.\nLemma not_false_is_true : ~ false.       Proof. by []. Qed.\nLemma is_true_locked_true : locked true. Proof. by unlock. Qed.\nHint Resolve is_true_true not_false_is_true is_true_locked_true.\n\n(* Shorter names. *)\nDefinition isT := is_true_true.\nDefinition notF := not_false_is_true.\n\n(* Negation lemmas. *)\n\n(* We generally take NEGATION as the standard form of a false condition:      *)\n(* negative boolean hypotheses should be of the form ~~ b, rather than ~ b or *)\n(* b = false, as much as possible.                                            *)\n\nLemma negbT b : b = false -> ~~ b.          Proof. by case: b. Qed.\nLemma negbTE b : ~~ b -> b = false.         Proof. by case: b. Qed.\nLemma negbF b : (b : bool) -> ~~ b = false. Proof. by case: b. Qed.\nLemma negbFE b : ~~ b = false -> b.         Proof. by case: b. Qed.\nLemma negbK : involutive negb.              Proof. by case. Qed.\nLemma negbNE b : ~~ ~~ b -> b.              Proof. by case: b. Qed.\n\nLemma negb_inj : injective negb. Proof. exact: can_inj negbK. Qed.\nLemma negbLR b c : b = ~~ c -> ~~ b = c. Proof. exact: canLR negbK. Qed.\nLemma negbRL b c : ~~ b = c -> b = ~~ c. Proof. exact: canRL negbK. Qed.\n\nLemma contra (c b : bool) : (c -> b) -> ~~ b -> ~~ c.\nProof. by case: b => //; case: c. Qed.\nDefinition contraNN := contra.\n\nLemma contraL (c b : bool) : (c -> ~~ b) -> b -> ~~ c.\nProof. by case: b => //; case: c. Qed.\nDefinition contraTN := contraL.\n\nLemma contraR (c b : bool) : (~~ c -> b) -> ~~ b -> c.\nProof. by case: b => //; case: c. Qed.\nDefinition contraNT := contraR.\n\nLemma contraLR (c b : bool) : (~~ c -> ~~ b) -> b -> c.\nProof. by case: b => //; case: c. Qed.\nDefinition contraTT := contraLR.\n\nLemma contraT b : (~~ b -> false) -> b. Proof. by case: b => // ->. Qed.\n\nLemma wlog_neg b : (~~ b -> b) -> b. Proof. by case: b => // ->. Qed.\n\nLemma contraFT (c b : bool) : (~~ c -> b) -> b = false -> c.\nProof. by move/contraR=> notb_c /negbT. Qed.\n\nLemma contraFN (c b : bool) : (c -> b) -> b = false -> ~~ c.\nProof. by move/contra=> notb_notc /negbT. Qed.\n\nLemma contraTF (c b : bool) : (c -> ~~ b) -> b -> c = false.\nProof. by move/contraL=> b_notc /b_notc/negbTE. Qed.\n\nLemma contraNF (c b : bool) : (c -> b) -> ~~ b -> c = false.\nProof. by move/contra=> notb_notc /notb_notc/negbTE. Qed.\n\nLemma contraFF (c b : bool) : (c -> b) -> b = false -> c = false.\nProof. by move/contraFN=> bF_notc /bF_notc/negbTE. Qed.\n\n(* Coercion of sum-style datatypes into bool, which makes it possible *)\n(* to use ssr's boolean if rather than Coq's \"generic\" if.            *)\n\nCoercion isSome T (u : option T) := if u is Some _ then true else false.\n\nCoercion is_inl A B (u : A + B) := if u is inl _ then true else false.\n\nCoercion is_left A B (u : {A} + {B}) := if u is left _ then true else false.\n\nCoercion is_inleft A B (u : A + {B}) := if u is inleft _ then true else false.\n\nPrenex Implicits  isSome is_inl is_left is_inleft.\n\nDefinition decidable P := {P} + {~ P}.\n\n(* Lemmas for ifs with large conditions, which allow reasoning about the  *)\n(* condition without repeating it inside the proof (the latter IS         *)\n(* preferable when the condition is short).                               *)\n(* Usage :                                                                *)\n(*   if the goal contains (if cond then ...) = ...                        *)\n(*     case: ifP => Hcond.                                                *)\n(*   generates two subgoal, with the assumption Hcond : cond = true/false *)\n(*     Rewrite if_same  eliminates redundant ifs                          *)\n(*     Rewrite (fun_if f) moves a function f inside an if                 *)\n(*     Rewrite if_arg moves an argument inside a function-valued if       *)\n\nSection BoolIf.\n\nVariables (A B : Type) (x : A) (f : A -> B) (b : bool) (vT vF : A).\n\nCoInductive if_spec (not_b : Prop) : bool -> A -> Set :=\n  | IfSpecTrue  of      b : if_spec not_b true vT\n  | IfSpecFalse of  not_b : if_spec not_b false vF.\n\nLemma ifP : if_spec (b = false) b (if b then vT else vF).\nProof. by case def_b: b; constructor. Qed.\n\nLemma ifPn : if_spec (~~ b) b (if b then vT else vF).\nProof. by case def_b: b; constructor; rewrite ?def_b. Qed.\n\nLemma ifT : b -> (if b then vT else vF) = vT. Proof. by move->. Qed.\nLemma ifF : b = false -> (if b then vT else vF) = vF. Proof. by move->. Qed.\nLemma ifN : ~~ b -> (if b then vT else vF) = vF. Proof. by move/negbTE->. 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\n(* Turning a boolean \"if\" form into an application.                           *)\nDefinition if_expr := if b then vT else vF.\nLemma ifE : (if b then vT else vF) = if_expr. Proof. by []. Qed.\n\nEnd BoolIf.\n\n(* The reflection predicate.                                          *)\n\nInductive reflect (P : Prop) : bool -> Set :=\n  | ReflectT  of   P : reflect P true\n  | ReflectF of ~ P : reflect P false.\n\n(* Core (internal) reflection lemmas, used for the three kinds of views. *)\n\nSection ReflectCore.\n\nVariables (P Q : Prop) (b c : bool).\n\nHypothesis Hb : reflect P b.\n\nLemma introNTF : (if c then ~ P else P) -> ~~ b = c.\nProof. by case c; case Hb. Qed.\n\nLemma introTF : (if c then P else ~ P) -> b = c.\nProof. by case c; case Hb. Qed.\n\nLemma elimNTF : ~~ b = c -> if c then ~ P else P.\nProof. by move <-; case Hb. Qed.\n\nLemma elimTF : b = c -> if c then P else ~ P.\nProof. by move <-; case Hb. Qed.\n\nLemma equivPif : (Q -> P) -> (P -> Q) -> if b then Q else ~ Q.\nProof. by case Hb; auto. Qed.\n\nLemma xorPif : Q \\/ P -> ~ (Q /\\ P) -> if b then ~ Q else Q.\nProof. by case Hb => [? _ H ? | ? H _]; case: H. Qed.\n\nEnd ReflectCore.\n\n(* Internal negated reflection lemmas *)\nSection ReflectNegCore.\n\nVariables (P Q : Prop) (b c : bool).\nHypothesis Hb : reflect P (~~ b).\n\nLemma introTFn : (if c then ~ P else P) -> b = c.\nProof. by move/(introNTF Hb) <-; case b. Qed.\n\nLemma elimTFn : b = c -> if c then ~ P else P.\nProof. by move <-; apply: (elimNTF Hb); case b. Qed.\n\nLemma equivPifn : (Q -> P) -> (P -> Q) -> if b then ~ Q else Q.\nProof. rewrite -if_neg; exact: equivPif. Qed.\n\nLemma xorPifn : Q \\/ P -> ~ (Q /\\ P) -> if b then Q else ~ Q.\nProof. rewrite -if_neg; exact: xorPif. Qed.\n\nEnd ReflectNegCore.\n\n(* User-oriented reflection lemmas *)\nSection Reflect.\n\nVariables (P Q : Prop) (b b' c : bool).\nHypotheses (Pb : reflect P b) (Pb' : reflect P (~~ b')).\n\nLemma introT  : P -> b.            Proof. exact: introTF true _. Qed.\nLemma introF  : ~ P -> b = false.  Proof. exact: introTF false _. Qed.\nLemma introN  : ~ P -> ~~ b.       Proof. exact: introNTF true _. Qed.\nLemma introNf : P -> ~~ b = false. Proof. exact: introNTF false _. Qed.\nLemma introTn : ~ P -> b'.         Proof. exact: introTFn true _. Qed.\nLemma introFn : P -> b' = false.   Proof. exact: introTFn false _. Qed.\n\nLemma elimT  : b -> P.             Proof. exact: elimTF true _. Qed.\nLemma elimF  : b = false -> ~ P.   Proof. exact: elimTF false _. Qed.\nLemma elimN  : ~~ b -> ~P.         Proof. exact: elimNTF true _. Qed.\nLemma elimNf : ~~ b = false -> P.  Proof. exact: elimNTF false _. Qed.\nLemma elimTn : b' -> ~ P.          Proof. exact: elimTFn true _. Qed.\nLemma elimFn : b' = false -> P.    Proof. exact: elimTFn false _. Qed.\n\nLemma introP : (b -> Q) -> (~~ b -> ~ Q) -> reflect Q b.\nProof. by case b; constructor; auto. Qed.\n\nLemma iffP : (P -> Q) -> (Q -> P) -> reflect Q b.\nProof. by case: Pb; constructor; auto. Qed.\n\nLemma equivP : (P <-> Q) -> reflect Q b.\nProof. by case; exact: iffP. Qed.\n\nLemma sumboolP (decQ : decidable Q) : reflect Q decQ.\nProof. by case: decQ; constructor. Qed.\n\nLemma appP : reflect Q b -> P -> Q.\nProof. by move=> Qb; move/introT; case: Qb. Qed.\n\nLemma sameP : reflect P c -> b = c.\nProof. case; [exact: introT | exact: introF]. Qed.\n\nLemma decPcases : if b then P else ~ P. Proof. by case Pb. Qed.\n\nDefinition decP : decidable P. by case: b decPcases; [left | right]. Defined.\n\nLemma rwP : P <-> b. Proof. by split; [exact: introT | exact: elimT]. Qed.\n\nLemma rwP2 : reflect Q b -> (P <-> Q).\nProof. by move=> Qb; split=> ?; [exact: appP | apply: elimT; case: Qb]. Qed.\n\n(*  Predicate family to reflect excluded middle in bool.                      *)\nCoInductive alt_spec : bool -> Type :=\n  | AltTrue of     P : alt_spec true\n  | AltFalse of ~~ b : alt_spec false.\n\nLemma altP : alt_spec b.\nProof. by case def_b: b / Pb; constructor; rewrite ?def_b. Qed.\n\nEnd Reflect.\n\nHint View for move/ elimTF|3 elimNTF|3 elimTFn|3 introT|2 introTn|2 introN|2.\n\nHint View for apply/ introTF|3 introNTF|3 introTFn|3 elimT|2 elimTn|2 elimN|2.\n\nHint View for apply// equivPif|3 xorPif|3 equivPifn|3 xorPifn|3.\n\n(* Allow the direct application of a reflection lemma to a boolean assertion. *)\nCoercion elimT : reflect >-> Funclass.\n\n(* Pierce's law, a weak form of classical reasoning. *)\nDefinition unless condition property := (property -> condition) -> condition.\n\nLemma bind_unless C P {Q} : unless C P -> unless (unless C Q) P.\nProof. by move=> haveP suffPQ suffQ; apply: haveP => /suffPQ; exact. Qed.\n\nLemma unless_contra b C : (~~ b -> C) -> unless C b.\nProof. by case: b => [_ haveC | haveC _]; exact: haveC. Qed.\n\n(* Classical reasoning becomes directly accessible for any bool subgoal.      *)\n(* Note that we cannot use \"unless\" here for lack of universe polymorphism.   *)\nDefinition classically P : Prop := forall b : bool, (P -> b) -> b.\n\nLemma classicP : forall P : Prop, classically P <-> ~ ~ P.\nProof.\nmove=> P; split=> [cP nP | nnP [] // nP]; last by case nnP; move/nP.\nby have: P -> false; [move/nP | move/cP].\nQed.\n\nLemma classic_bind : forall P Q,\n  (P -> classically Q) -> (classically P -> classically Q).\nProof. by move=> P Q IH IH_P b IH_Q; apply: IH_P; move/IH; exact. Qed.\n\nLemma classic_EM : forall P, classically (decidable P).\nProof.\nby move=> P [] // IH; apply IH; right => ?; apply: notF (IH _); left.\nQed.\n\nLemma classic_imply : forall P Q, (P -> classically Q) -> classically (P -> Q).\nProof.\nmove=> P Q IH [] // notPQ; apply notPQ; move/IH=> hQ; case: notF.\nby apply: hQ => hQ; case: notF; exact: notPQ.\nQed.\n\nLemma classic_pick : forall T P,\n  classically ({x : T | P x} + (forall x, ~ P x)).\nProof.\nmove=> T P [] // IH; apply IH; right=> x Px; case: notF.\nby apply: IH; left; exists x.\nQed.\n\n(* List notations for wider connectives; the Prop connectives have a fixed    *)\n(* width so as to avoid iterated destruction (we go up to width 5 for /\\, and *)\n(* width 4 for or. The bool connectives have arbitrary widths, but denote     *)\n(* expressions that associate to the RIGHT. This is consistent with the right *)\n(* associativity of list expressions and thus more convenient in most proofs. *)\n\nInductive and3 (P1 P2 P3 : Prop) : Prop := And3 of P1 & P2 & P3.\n\nInductive and4 (P1 P2 P3 P4 : Prop) : Prop := And4 of P1 & P2 & P3 & P4.\n\nInductive and5 (P1 P2 P3 P4 P5 : Prop) : Prop :=\n  And5 of P1 & P2 & P3 & P4 & P5.\n\nInductive or3 (P1 P2 P3 : Prop) : Prop := Or31 of P1 | Or32 of P2 | Or33 of P3.\n\nInductive or4 (P1 P2 P3 P4 : Prop) : Prop :=\n  Or41 of P1 | Or42 of P2 | Or43 of P3 | Or44 of P4.\n\nNotation \"[ /\\ P1 & P2 ]\" := (and P1 P2) (only parsing) : type_scope.\nNotation \"[ /\\ P1 , P2 & P3 ]\" := (and3 P1 P2 P3) : type_scope.\nNotation \"[ /\\ P1 , P2 , P3 & P4 ]\" := (and4 P1 P2 P3 P4) : type_scope.\nNotation \"[ /\\ P1 , P2 , P3 , P4 & P5 ]\" := (and5 P1 P2 P3 P4 P5) : type_scope.\n\nNotation \"[ \\/ P1 | P2 ]\" := (or P1 P2) (only parsing) : type_scope.\nNotation \"[ \\/ P1 , P2 | P3 ]\" := (or3 P1 P2 P3) : type_scope.\nNotation \"[ \\/ P1 , P2 , P3 | P4 ]\" := (or4 P1 P2 P3 P4) : type_scope.\n\nNotation \"[ && b1 & c ]\" := (b1 && c) (only parsing) : bool_scope.\nNotation \"[ && b1 , b2 , .. , bn & c ]\" := (b1 && (b2 && .. (bn && c) .. ))\n  : bool_scope.\n\nNotation \"[ || b1 | c ]\" := (b1 || c) (only parsing) : bool_scope.\nNotation \"[ || b1 , b2 , .. , bn | c ]\" := (b1 || (b2 || .. (bn || c) .. ))\n  : bool_scope.\n\nNotation \"[ ==> b1 , b2 , .. , bn => c ]\" :=\n   (b1 ==> (b2 ==> .. (bn ==> c) .. )) : bool_scope.\nNotation \"[ ==> b1 => c ]\" := (b1 ==> c) (only parsing) : bool_scope.\n\nSection AllAnd.\n\nVariables (T : Type) (P1 P2 P3 P4 P5 : T -> Prop).\nLocal Notation a P := (forall x, P x).\n\nLemma all_and2 (hP : forall x, [/\\ P1 x & P2 x]) : [/\\ a P1 & a P2].\nProof. by split=> x; case: (hP x). Qed.\n\nLemma all_and3 (hP : forall x, [/\\ P1 x, P2 x & P3 x]) :\n  [/\\ a P1, a P2 & a P3].\nProof. by split=> x; case: (hP x). Qed.\n\nLemma all_and4 (hP : forall x, [/\\ P1 x, P2 x, P3 x & P4 x]) :\n  [/\\ a P1, a P2, a P3 & a P4].\nProof. by split=> x; case: (hP x). Qed.\n\nLemma all_and5 (hP : forall x, [/\\ P1 x, P2 x, P3 x, P4 x & P5 x]) :\n  [/\\ a P1, a P2, a P3, a P4 & a P5].\nProof. by split=> x; case: (hP x). Qed.\n\nEnd AllAnd.\n\nLemma pair_andP P Q : P /\\ Q <-> P * Q. Proof. by split; case. Qed.\n\nSection ReflectConnectives.\n\nVariable b1 b2 b3 b4 b5 : bool.\n\nLemma idP : reflect b1 b1.\nProof. by case b1; constructor. Qed.\n\nLemma boolP : alt_spec b1 b1 b1.\nProof. exact: (altP idP). Qed.\n\nLemma idPn : reflect (~~ b1) (~~ b1).\nProof. by case b1; constructor. Qed.\n\nLemma negP : reflect (~ b1) (~~ b1).\nProof. by case b1; constructor; auto. Qed.\n\nLemma negPn : reflect b1 (~~ ~~ b1).\nProof. by case b1; constructor. Qed.\n\nLemma negPf : reflect (b1 = false) (~~ b1).\nProof. by case b1; constructor. Qed.\n\nLemma andP : reflect (b1 /\\ b2) (b1 && b2).\nProof. by case b1; case b2; constructor=> //; case. Qed.\n\nLemma and3P : reflect [/\\ b1, b2 & b3] [&& b1, b2 & b3].\nProof. by case b1; case b2; case b3; constructor; try by case. Qed.\n\nLemma and4P : reflect [/\\ b1, b2, b3 & b4] [&& b1, b2, b3 & b4].\nProof. by case b1; case b2; case b3; case b4; constructor; try by case. Qed.\n\nLemma and5P : reflect [/\\ b1, b2, b3, b4 & b5] [&& b1, b2, b3, b4 & b5].\nProof.\nby case b1; case b2; case b3; case b4; case b5; constructor; try by case.\nQed.\n\nLemma orP : reflect (b1 \\/ b2) (b1 || b2).\nProof. by case b1; case b2; constructor; auto; case. Qed.\n\nLemma or3P : reflect [\\/ b1, b2 | b3] [|| b1, b2 | b3].\nProof.\ncase b1; first by constructor; constructor 1.\ncase b2; first by constructor; constructor 2.\ncase b3; first by constructor; constructor 3.\nby constructor; case.\nQed.\n\nLemma or4P : reflect [\\/ b1, b2, b3 | b4] [|| b1, b2, b3 | b4].\nProof.\ncase b1; first by constructor; constructor 1.\ncase b2; first by constructor; constructor 2.\ncase b3; first by constructor; constructor 3.\ncase b4; first by constructor; constructor 4.\nby constructor; case.\nQed.\n\nLemma nandP : reflect (~~ b1 \\/ ~~ b2) (~~ (b1 && b2)).\nProof. by case b1; case b2; constructor; auto; case; auto. Qed.\n\nLemma norP : reflect (~~ b1 /\\ ~~ b2) (~~ (b1 || b2)).\nProof. by case b1; case b2; constructor; auto; case; auto. Qed.\n\nLemma implyP : reflect (b1 -> b2) (b1 ==> b2).\nProof. by case b1; case b2; constructor; auto. Qed.\n\nEnd ReflectConnectives.\n\nImplicit Arguments idP [b1].\nImplicit Arguments idPn [b1].\nImplicit Arguments negP [b1].\nImplicit Arguments negPn [b1].\nImplicit Arguments negPf [b1].\nImplicit Arguments andP [b1 b2].\nImplicit Arguments and3P [b1 b2 b3].\nImplicit Arguments and4P [b1 b2 b3 b4].\nImplicit Arguments and5P [b1 b2 b3 b4 b5].\nImplicit Arguments orP [b1 b2].\nImplicit Arguments or3P [b1 b2 b3].\nImplicit Arguments or4P [b1 b2 b3 b4].\nImplicit Arguments nandP [b1 b2].\nImplicit Arguments norP [b1 b2].\nImplicit Arguments implyP [b1 b2].\nPrenex Implicits idP idPn negP negPn negPf.\nPrenex Implicits andP and3P and4P and5P orP or3P or4P nandP norP implyP.\n\n(* Shorter, more systematic names for the boolean connectives laws.       *)\n\nLemma andTb : left_id true andb.       Proof. by []. Qed.\nLemma andFb : left_zero false andb.    Proof. by []. Qed.\nLemma andbT : right_id true andb.      Proof. by case. Qed.\nLemma andbF : right_zero false andb.   Proof. by case. Qed.\nLemma andbb : idempotent andb.         Proof. by case. Qed.\nLemma andbC : commutative andb.        Proof. by do 2!case. Qed.\nLemma andbA : associative andb.        Proof. by do 3!case. Qed.\nLemma andbCA : left_commutative andb.  Proof. by do 3!case. Qed.\nLemma andbAC : right_commutative andb. Proof. by do 3!case. Qed.\nLemma andbACA : interchange andb andb. Proof. by do 4!case. Qed.\n\nLemma orTb : forall b, true || b.      Proof. by []. Qed.\nLemma orFb : left_id false orb.        Proof. by []. Qed.\nLemma orbT : forall b, b || true.      Proof. by case. Qed.\nLemma orbF : right_id false orb.       Proof. by case. Qed.\nLemma orbb : idempotent orb.           Proof. by case. Qed.\nLemma orbC : commutative orb.          Proof. by do 2!case. Qed.\nLemma orbA : associative orb.          Proof. by do 3!case. Qed.\nLemma orbCA : left_commutative orb.    Proof. by do 3!case. Qed.\nLemma orbAC : right_commutative orb.   Proof. by do 3!case. Qed.\nLemma orbACA : interchange orb orb.    Proof. by do 4!case. Qed.\n\nLemma andbN b : b && ~~ b = false. Proof. by case: b. Qed.\nLemma andNb b : ~~ b && b = false. Proof. by case: b. Qed.\nLemma orbN b : b || ~~ b = true.   Proof. by case: b. Qed.\nLemma orNb b : ~~ b || b = true.   Proof. by case: b. Qed.\n\nLemma andb_orl : left_distributive andb orb.  Proof. by do 3!case. Qed.\nLemma andb_orr : right_distributive andb orb. Proof. by do 3!case. Qed.\nLemma orb_andl : left_distributive orb andb.  Proof. by do 3!case. Qed.\nLemma orb_andr : right_distributive orb andb. Proof. by do 3!case. Qed.\n\nLemma andb_idl (a b : bool) : (b -> a) -> a && b = b.\nProof. by case: a; case: b => // ->. Qed.\nLemma andb_idr (a b : bool) : (a -> b) -> a && b = a.\nProof. by case: a; case: b => // ->. Qed.\nLemma andb_id2l (a b c : bool) : (a -> b = c) -> a && b = a && c.\nProof. by case: a; case: b; case: c => // ->. Qed.\nLemma andb_id2r (a b c : bool) : (b -> a = c) -> a && b = c && b.\nProof. by case: a; case: b; case: c => // ->. Qed.\n\nLemma orb_idl (a b : bool) : (a -> b) -> a || b = b.\nProof. by case: a; case: b => // ->. Qed.\nLemma orb_idr (a b : bool) : (b -> a) -> a || b = a.\nProof. by case: a; case: b => // ->. Qed.\nLemma orb_id2l (a b c : bool) : (~~ a -> b = c) -> a || b = a || c.\nProof. by case: a; case: b; case: c => // ->. Qed.\nLemma orb_id2r (a b c : bool) : (~~ b -> a = c) -> a || b = c || b.\nProof. by case: a; case: b; case: c => // ->. Qed.\n\nLemma negb_and (a b : bool) : ~~ (a && b) = ~~ a || ~~ b.\nProof. by case: a; case: b. Qed.\n\nLemma negb_or (a b : bool) : ~~ (a || b) = ~~ a && ~~ b.\nProof. by case: a; case: b. Qed.\n\n(* Pseudo-cancellation -- i.e, absorbtion *)\n\nLemma andbK a b : a && b || a = a.  Proof. by case: a; case: b. Qed.\nLemma andKb a b : a || b && a = a.  Proof. by case: a; case: b. Qed.\nLemma orbK a b : (a || b) && a = a. Proof. by case: a; case: b. Qed.\nLemma orKb a b : a && (b || a) = a. Proof. by case: a; case: b. Qed.\n\n(* Imply *)\n\nLemma implybT b : b ==> true.           Proof. by case: b. Qed.\nLemma implybF b : (b ==> false) = ~~ b. Proof. by case: b. Qed.\nLemma implyFb b : false ==> b.          Proof. by []. Qed.\nLemma implyTb b : (true ==> b) = b.     Proof. by []. Qed.\nLemma implybb b : b ==> b.              Proof. by case: b. Qed.\n\nLemma negb_imply a b : ~~ (a ==> b) = a && ~~ b.\nProof. by case: a; case: b. Qed.\n\nLemma implybE a b : (a ==> b) = ~~ a || b.\nProof. by case: a; case: b. Qed.\n\nLemma implyNb a b : (~~ a ==> b) = a || b.\nProof. by case: a; case: b. Qed.\n\nLemma implybN a b : (a ==> ~~ b) = (b ==> ~~ a).\nProof. by case: a; case: b. Qed.\n\nLemma implybNN a b : (~~ a ==> ~~ b) = b ==> a.\nProof. by case: a; case: b. Qed.\n\nLemma implyb_idl (a b : bool) : (~~ a -> b) -> (a ==> b) = b.\nProof. by case: a; case: b => // ->. Qed.\nLemma implyb_idr (a b : bool) : (b -> ~~ a) -> (a ==> b) = ~~ a.\nProof. by case: a; case: b => // ->. Qed.\nLemma implyb_id2l (a b c : bool) : (a -> b = c) -> (a ==> b) = (a ==> c).\nProof. by case: a; case: b; case: c => // ->. Qed.\n\n(* Addition (xor) *)\n\nLemma addFb : left_id false addb.               Proof. by []. Qed.\nLemma addbF : right_id false addb.              Proof. by case. Qed.\nLemma addbb : self_inverse false addb.          Proof. by case. Qed.\nLemma addbC : commutative addb.                 Proof. by do 2!case. Qed.\nLemma addbA : associative addb.                 Proof. by do 3!case. Qed.\nLemma addbCA : left_commutative addb.           Proof. by do 3!case. Qed.\nLemma addbAC : right_commutative addb.          Proof. by do 3!case. Qed.\nLemma addbACA : interchange addb addb.          Proof. by do 4!case. Qed.\nLemma andb_addl : left_distributive andb addb.  Proof. by do 3!case. Qed.\nLemma andb_addr : right_distributive andb addb. Proof. by do 3!case. Qed.\nLemma addKb : left_loop id addb.                Proof. by do 2!case. Qed.\nLemma addbK : right_loop id addb.               Proof. by do 2!case. Qed.\nLemma addIb : left_injective addb.              Proof. by do 3!case. Qed.\nLemma addbI : right_injective addb.             Proof. by do 3!case. Qed.\n\nLemma addTb b : true (+) b = ~~ b. Proof. by []. Qed.\nLemma addbT b : b (+) true = ~~ b. Proof. by case: b. Qed.\n\nLemma addbN a b : a (+) ~~ b = ~~ (a (+) b).\nProof. by case: a; case: b. Qed.\nLemma addNb a b : ~~ a (+) b = ~~ (a (+) b).\nProof. by case: a; case: b. Qed.\n\nLemma addbP a b : reflect (~~ a = b) (a (+) b).\nProof. by case: a; case: b; constructor. Qed.\nImplicit Arguments addbP [a b].\n\n(* Resolution tactic for blindly weeding out common terms from boolean       *)\n(* equalities. When faced with a goal of the form (andb/orb/addb b1 b2) = b3 *)\n(* they will try to locate b1 in b3 and remove it. This can fail!            *)\n\nLtac bool_congr :=\n  match goal with\n  | |- (?X1 && ?X2 = ?X3) => first\n  [ symmetry; rewrite -1?(andbC X1) -?(andbCA X1); congr 1 (andb X1); symmetry\n  | case: (X1); [ rewrite ?andTb ?andbT // | by rewrite ?andbF /= ] ]\n  | |- (?X1 || ?X2 = ?X3) => first\n  [ symmetry; rewrite -1?(orbC X1) -?(orbCA X1); congr 1 (orb X1); symmetry\n  | case: (X1); [ by rewrite ?orbT //= | rewrite ?orFb ?orbF ] ]\n  | |- (?X1 (+) ?X2 = ?X3) =>\n    symmetry; rewrite -1?(addbC X1) -?(addbCA X1); congr 1 (addb X1); symmetry\n  | |- (~~ ?X1 = ?X2) => congr 1 negb\n  end.\n\n(******************************************************************************)\n(* Predicates, i.e., packaged functions to bool.                              *)\n(* - pred T, the basic type for predicates over a type T, is simply an alias  *)\n(* for T -> bool.                                                             *)\n(* We actually distinguish two kinds of predicates, which we call applicative *)\n(* and collective, based on the syntax used to test them at some x in T:      *)\n(* - For an applicative predicate P, one uses prefix syntax:                  *)\n(*     P x                                                                    *)\n(*   Also, most operations on applicative predicates use prefix syntax as     *)\n(*   well (e.g., predI P Q).                                                  *)\n(* - For a collective predicate A, one uses infix syntax:                     *)\n(*     x \\in A                                                                *)\n(*   and all operations on collective predicates use infix syntax as well     *)\n(*   (e.g., [predI A & B]).                                                   *)\n(* There are only two kinds of applicative predicates:                        *)\n(* - pred T, the alias for T -> bool mentioned above                          *)\n(* - simpl_pred T, an alias for simpl_fun T bool with a coercion to pred T    *)\n(*   that auto-simplifies on application (see ssrfun).                        *)\n(* On the other hand, the set of collective predicate types is open-ended via *)\n(* - predType T, a Structure that can be used to put Canonical collective     *)\n(*   predicate interpretation on other types, such as lists, tuples,          *)\n(*   finite sets, etc.                                                        *)\n(* Indeed, we define such interpretations for applicative predicate types,    *)\n(* which can therefore also be used with the infix syntax, e.g.,              *)\n(*     x \\in predI P Q                                                        *)\n(* Moreover these infix forms are convertible to their prefix counterpart     *)\n(* (e.g., predI P Q x which in turn simplifies to P x && Q x). The converse   *)\n(* is not true, however; collective predicate types cannot, in general, be    *)\n(* general, be used applicatively, because of the \"uniform inheritance\"       *)\n(* restriction on implicit coercions.                                         *)\n(*   However, we do define an explicit generic coercion                       *)\n(* - mem : forall (pT : predType), pT -> mem_pred T                           *)\n(*   where mem_pred T is a variant of simpl_pred T that preserves the infix   *)\n(*   syntax, i.e., mem A x auto-simplifies to x \\in A.                        *)\n(* Indeed, the infix \"collective\" operators are notation for a prefix         *)\n(* operator with arguments of type mem_pred T or pred T, applied to coerced   *)\n(* collective predicates, e.g.,                                               *)\n(*      Notation \"x \\in A\" := (in_mem x (mem A)).                             *)\n(* This prevents the variability in the predicate type from interfering with  *)\n(* the application of generic lemmas. Moreover this also makes it much easier *)\n(* to define generic lemmas, because the simplest type -- pred T -- can be    *)\n(* used as the type of generic collective predicates, provided one takes care *)\n(* not to use it applicatively; this avoids the burden of having to declare a *)\n(* different predicate type for each predicate parameter of each section or   *)\n(* lemma.                                                                     *)\n(*   This trick is made possible by the fact that the constructor of the      *)\n(* mem_pred T type aligns the unification process, forcing a generic          *)\n(* \"collective\" predicate A : pred T to unify with the actual collective B,   *)\n(* which mem has coerced to pred T via an internal, hidden implicit coercion, *)\n(* supplied by the predType structure for B. Users should take care not to    *)\n(* inadvertently \"strip\" (mem B) down to the coerced B, since this will       *)\n(* expose the internal coercion: Coq will display a term B x that cannot be   *)\n(* typed as such. The topredE lemma can be used to restore the x \\in B        *)\n(* syntax in this case. While -topredE can conversely be used to change       *)\n(* x \\in P into P x, it is safer to use the inE and memE lemmas instead, as   *)\n(* they do not run the risk of exposing internal coercions. As a consequence  *)\n(* it is better to explicitly cast a generic applicative pred T to simpl_pred *)\n(* using the SimplPred constructor, when it is used as a collective predicate *)\n(* (see, e.g., Lemma eq_big in bigop).                                        *)\n(*   We also sometimes \"instantiate\" the predType structure by defining a     *)\n(* coercion to the sort of the predPredType structure. This works better for  *)\n(* types such as {set T} that have subtypes that coerce to them, since the    *)\n(* same coercion will be inserted by the application of mem. It also lets us  *)\n(* turn any Type aT : predArgType into the total predicate over that type,    *)\n(* i.e., fun _: aT => true. This allows us to write, e.g., #|'I_n| for the    *)\n(* cardinal of the (finite) type of integers less than n.                     *)\n(*   Collective predicates have a specific extensional equality,              *)\n(*   - A =i B,                                                                *)\n(* while applicative predicates use the extensional equality of functions,    *)\n(*   - P =1 Q                                                                 *)\n(* The two forms are convertible, however.                                    *)\n(* We lift boolean operations to predicates, defining:                        *)\n(* - predU (union), predI (intersection), predC (complement),                 *)\n(*   predD (difference), and preim (preimage, i.e., composition)              *)\n(* For each operation we define three forms, typically:                       *)\n(* - predU : pred T -> pred T -> simpl_pred T                                 *)\n(* - [predU A & B], a Notation for predU (mem A) (mem B)                      *)\n(* - xpredU, a Notation for the lambda-expression inside predU,               *)\n(*     which is mostly useful as an argument of =1, since it exposes the head *)\n(*     head constant of the expression to the ssreflect matching algorithm.   *)\n(* The syntax for the preimage of a collective predicate A is                 *)\n(* - [preim f of A]                                                           *)\n(* Finally, the generic syntax for defining a simpl_pred T is                 *)\n(* - [pred x : T | P(x)], [pred x | P(x)], [pred x in A | P(x)], etc.         *)\n(* We also support boolean relations, but only the applicative form, with     *)\n(* types                                                                      *)\n(* - rel T, an alias for T -> pred T                                          *)\n(* - simpl_rel T, an auto-simplifying version, and syntax                     *)\n(*   [rel x y | P(x,y)], [rel x y in A & B | P(x,y)], etc.                    *)\n(* The notation [rel of fA] can be used to coerce a function returning a      *)\n(* collective predicate to one returning pred T.                              *)\n(*   Finally, note that there is specific support for ambivalent predicates   *)\n(* that can work in either style, as per this file's head descriptor.         *)\n(******************************************************************************)\n\nDefinition pred T := T -> bool.\n\nIdentity Coercion fun_of_pred : pred >-> Funclass.\n\nDefinition rel T := T -> pred T.\n\nIdentity Coercion fun_of_rel : rel >-> Funclass.\n\nNotation xpred0 := (fun _ => false).\nNotation xpredT := (fun _ => true).\nNotation xpredI := (fun (p1 p2 : pred _) x => p1 x && p2 x).\nNotation xpredU := (fun (p1 p2 : pred _) x => p1 x || p2 x).\nNotation xpredC := (fun (p : pred _) x => ~~ p x).\nNotation xpredD := (fun (p1 p2 : pred _) x => ~~ p2 x && p1 x).\nNotation xpreim := (fun f (p : pred _) x => p (f x)).\nNotation xrelU := (fun (r1 r2 : rel _) x y => r1 x y || r2 x y).\n\nSection Predicates.\n\nVariables T : Type.\n\nDefinition subpred (p1 p2 : pred T) := forall x, p1 x -> p2 x.\n\nDefinition subrel (r1 r2 : rel T) := forall x y, r1 x y -> r2 x y.\n\nDefinition simpl_pred := simpl_fun T bool.\nDefinition applicative_pred := pred T.\nDefinition collective_pred := pred T.\n\nDefinition SimplPred (p : pred T) : simpl_pred := SimplFun p.\n\nCoercion pred_of_simpl (p : simpl_pred) : pred T := fun_of_simpl p.\nCoercion applicative_pred_of_simpl (p : simpl_pred) : applicative_pred :=\n  fun_of_simpl p.\nCoercion collective_pred_of_simpl (p : simpl_pred) : collective_pred :=\n  fun x => (let: SimplFun f := p in fun _ => f x) x.\n(* Note: applicative_of_simpl is convertible to pred_of_simpl, while *)\n(* collective_of_simpl is not. *)\n\nDefinition pred0 := SimplPred xpred0.\nDefinition predT := SimplPred xpredT.\nDefinition predI p1 p2 := SimplPred (xpredI p1 p2).\nDefinition predU p1 p2 := SimplPred (xpredU p1 p2).\nDefinition predC p := SimplPred (xpredC p).\nDefinition predD p1 p2 := SimplPred (xpredD p1 p2).\nDefinition preim rT f (d : pred rT) := SimplPred (xpreim f d).\n\nDefinition simpl_rel := simpl_fun T (pred T).\n\nDefinition SimplRel (r : rel T) : simpl_rel := [fun x => r x].\n\nCoercion rel_of_simpl_rel (r : simpl_rel) : rel T := fun x y => r x y.\n\nDefinition relU r1 r2 := SimplRel (xrelU r1 r2).\n\nLemma subrelUl r1 r2 : subrel r1 (relU r1 r2).\nProof. by move=> *; apply/orP; left. Qed.\n\nLemma subrelUr r1 r2 : subrel r2 (relU r1 r2).\nProof. by move=> *; apply/orP; right. Qed.\n\nCoInductive mem_pred := Mem of pred T.\n\nDefinition isMem pT topred mem := mem = (fun p : pT => Mem [eta topred p]).\n\nStructure predType := PredType {\n  pred_sort :> Type;\n  topred : pred_sort -> pred T;\n  _ : {mem | isMem topred mem}\n}.\n\nDefinition mkPredType pT toP := PredType (exist (@isMem pT toP) _ (erefl _)).\n\nCanonical predPredType := Eval hnf in @mkPredType (pred T) id.\nCanonical simplPredType := Eval hnf in mkPredType pred_of_simpl.\nCanonical boolfunPredType := Eval hnf in @mkPredType (T -> bool) id.\n\nCoercion pred_of_mem mp : pred_sort predPredType := let: Mem p := mp in [eta p].\nCanonical memPredType := Eval hnf in mkPredType pred_of_mem.\n\nDefinition clone_pred U :=\n  fun pT & pred_sort pT -> U =>\n  fun a mP (pT' := @PredType U a mP) & phant_id pT' pT => pT'.\n\nEnd Predicates.\n\nImplicit Arguments pred0 [T].\nImplicit Arguments predT [T].\nPrenex Implicits pred0 predT predI predU predC predD preim relU.\n\nNotation \"[ 'pred' : T | E ]\" := (SimplPred (fun _ : T => E%B))\n  (at level 0, format \"[ 'pred' :  T  |  E ]\") : fun_scope.\nNotation \"[ 'pred' x | E ]\" := (SimplPred (fun x => E%B))\n  (at level 0, x ident, format \"[ 'pred'  x  |  E ]\") : fun_scope.\nNotation \"[ 'pred' x | E1 & E2 ]\" := [pred x | E1 && E2 ]\n  (at level 0, x ident, format \"[ 'pred'  x  |  E1  &  E2 ]\") : fun_scope.\nNotation \"[ 'pred' x : T | E ]\" := (SimplPred (fun x : T => E%B))\n  (at level 0, x ident, only parsing) : fun_scope.\nNotation \"[ 'pred' x : T | E1 & E2 ]\" := [pred x : T | E1 && E2 ]\n  (at level 0, x ident, only parsing) : fun_scope.\nNotation \"[ 'rel' x y | E ]\" := (SimplRel (fun x y => E%B))\n  (at level 0, x ident, y ident, format \"[ 'rel'  x  y  |  E ]\") : fun_scope.\nNotation \"[ 'rel' x y : T | E ]\" := (SimplRel (fun x y : T => E%B))\n  (at level 0, x ident, y ident, only parsing) : fun_scope.\n\nNotation \"[ 'predType' 'of' T ]\" := (@clone_pred _ T _ id _ _ id)\n  (at level 0, format \"[ 'predType'  'of'  T ]\") : form_scope.\n\n(* This redundant coercion lets us \"inherit\" the simpl_predType canonical    *)\n(* instance by declaring a coercion to simpl_pred. This hack is the only way *)\n(* to put a predType structure on a predArgType. We use simpl_pred rather    *)\n(* than pred to ensure that /= removes the identity coercion. Note that the  *)\n(* coercion will never be used directly for simpl_pred, since the canonical  *)\n(* instance should always be resolved.                                       *)\n\nNotation pred_class := (pred_sort (predPredType _)).\nCoercion sort_of_simpl_pred T (p : simpl_pred T) : pred_class := p : pred T.\n\n(* This lets us use some types as a synonym for their universal predicate.    *)\n(* Unfortunately, this won't work for existing types like bool, unless we     *)\n(* redefine bool, true, false and all bool ops.                               *)\nDefinition predArgType := Type.\nBind Scope type_scope with predArgType.\nIdentity Coercion sort_of_predArgType : predArgType >-> Sortclass.\nCoercion pred_of_argType (T : predArgType) : simpl_pred T := predT.\n\nNotation \"{ : T }\" := (T%type : predArgType)\n  (at level 0, format \"{ :  T }\") : type_scope.\n\n(* These must be defined outside a Section because \"cooking\" kills the        *)\n(* nosimpl tag.                                                               *)\n\nDefinition mem T (pT : predType T) : pT -> mem_pred T :=\n  nosimpl (let: PredType _ _ (exist mem _) := pT return pT -> _ in mem).\nDefinition in_mem T x mp := nosimpl pred_of_mem T mp x.\n\nPrenex Implicits mem.\n\nCoercion pred_of_mem_pred T mp := [pred x : T | in_mem x mp].\n\nDefinition eq_mem T p1 p2 := forall x : T, in_mem x p1 = in_mem x p2.\nDefinition sub_mem T p1 p2 := forall x : T, in_mem x p1 -> in_mem x p2.\n\nTypeclasses Opaque eq_mem.\n\nLemma sub_refl T (p : mem_pred T) : sub_mem p p. Proof. by []. Qed.\nImplicit Arguments sub_refl [[T] [p]].\n\nNotation \"x \\in A\" := (in_mem x (mem A)) : bool_scope.\nNotation \"x \\in A\" := (in_mem x (mem A)) : bool_scope.\nNotation \"x \\notin A\" := (~~ (x \\in A)) : bool_scope.\nNotation \"A =i B\" := (eq_mem (mem A) (mem B)) : type_scope.\nNotation \"{ 'subset' A <= B }\" := (sub_mem (mem A) (mem B))\n  (at level 0, A, B at level 69,\n   format \"{ '[hv' 'subset'  A '/   '  <=  B ']' }\") : type_scope.\nNotation \"[ 'mem' A ]\" := (pred_of_simpl (pred_of_mem_pred (mem A)))\n  (at level 0, only parsing) : fun_scope.\nNotation \"[ 'rel' 'of' fA ]\" := (fun x => [mem (fA x)])\n  (at level 0, format \"[ 'rel'  'of'  fA ]\") : fun_scope.\nNotation \"[ 'predI' A & B ]\" := (predI [mem A] [mem B])\n  (at level 0, format \"[ 'predI'  A  &  B ]\") : fun_scope.\nNotation \"[ 'predU' A & B ]\" := (predU [mem A] [mem B])\n  (at level 0, format \"[ 'predU'  A  &  B ]\") : fun_scope.\nNotation \"[ 'predD' A & B ]\" := (predD [mem A] [mem B])\n  (at level 0, format \"[ 'predD'  A  &  B ]\") : fun_scope.\nNotation \"[ 'predC' A ]\" := (predC [mem A])\n  (at level 0, format \"[ 'predC'  A ]\") : fun_scope.\nNotation \"[ 'preim' f 'of' A ]\" := (preim f [mem A])\n  (at level 0, format \"[ 'preim'  f  'of'  A ]\") : fun_scope.\n\nNotation \"[ 'pred' x 'in' A ]\" := [pred x | x \\in A]\n  (at level 0, x ident, format \"[ 'pred'  x  'in'  A ]\") : fun_scope.\nNotation \"[ 'pred' x 'in' A | E ]\" := [pred x | x \\in A & E]\n  (at level 0, x ident, format \"[ 'pred'  x  'in'  A  |  E ]\") : fun_scope.\nNotation \"[ 'pred' x 'in' A | E1 & E2 ]\" := [pred x | x \\in A & E1 && E2 ]\n  (at level 0, x ident,\n   format \"[ 'pred'  x  'in'  A  |  E1  &  E2 ]\") : fun_scope.\nNotation \"[ 'rel' x y 'in' A & B | E ]\" :=\n  [rel x y | (x \\in A) && (y \\in B) && E]\n  (at level 0, x ident, y ident,\n   format \"[ 'rel'  x  y  'in'  A  &  B  |  E ]\") : fun_scope.\nNotation \"[ 'rel' x y 'in' A & B ]\" := [rel x y | (x \\in A) && (y \\in B)]\n  (at level 0, x ident, y ident,\n   format \"[ 'rel'  x  y  'in'  A  &  B ]\") : fun_scope.\nNotation \"[ 'rel' x y 'in' A | E ]\" := [rel x y in A & A | E]\n  (at level 0, x ident, y ident,\n   format \"[ 'rel'  x  y  'in'  A  |  E ]\") : fun_scope.\nNotation \"[ 'rel' x y 'in' A ]\" := [rel x y in A & A]\n  (at level 0, x ident, y ident,\n   format \"[ 'rel'  x  y  'in'  A ]\") : fun_scope.\n\nSection simpl_mem.\n\nVariables (T : Type) (pT : predType T).\nImplicit Types (x : T) (p : pred T) (sp : simpl_pred T) (pp : pT).\n\n(* Bespoke structures that provide fine-grained control over matching the     *)\n(* various forms of the \\in predicate; note in particular the different forms *)\n(* of hoisting that are used. We had to work around several bugs in the       *)\n(* implementation of unification, notably improper expansion of telescope     *)\n(* projections and overwriting of a variable assignment by a later            *)\n(* unification (probably due to conversion cache cross-talk).                 *)\nStructure manifest_applicative_pred p := ManifestApplicativePred {\n  manifest_applicative_pred_value :> pred T;\n  _ : manifest_applicative_pred_value = p\n}.\nDefinition ApplicativePred p := ManifestApplicativePred (erefl p).\nCanonical applicative_pred_applicative sp :=\n  ApplicativePred (applicative_pred_of_simpl sp).\n\nStructure manifest_simpl_pred p := ManifestSimplPred {\n  manifest_simpl_pred_value :> simpl_pred T;\n  _ : manifest_simpl_pred_value = SimplPred p\n}.\nCanonical expose_simpl_pred p := ManifestSimplPred (erefl (SimplPred p)).\n\nStructure manifest_mem_pred p := ManifestMemPred {\n  manifest_mem_pred_value :> mem_pred T;\n  _ : manifest_mem_pred_value= Mem [eta p]\n}.\nCanonical expose_mem_pred p :=  @ManifestMemPred p _ (erefl _).\n\nStructure applicative_mem_pred p :=\n  ApplicativeMemPred {applicative_mem_pred_value :> manifest_mem_pred p}.\nCanonical check_applicative_mem_pred p (ap : manifest_applicative_pred p) mp :=\n  @ApplicativeMemPred ap mp.\n\nLemma mem_topred (pp : pT) : mem (topred pp) = mem pp.\nProof. by rewrite /mem; case: pT pp => T1 app1 [mem1 /= ->]. Qed.\n\nLemma topredE x (pp : pT) : topred pp x = (x \\in pp).\nProof. by rewrite -mem_topred. Qed.\n\nLemma app_predE x p (ap : manifest_applicative_pred p) : ap x = (x \\in p).\nProof. by case: ap => _ /= ->. Qed.\n\nLemma in_applicative x p (amp : applicative_mem_pred p) : in_mem x amp = p x.\nProof. by case: amp => [[_ /= ->]]. Qed.\n\nLemma in_collective x p (msp : manifest_simpl_pred p) :\n  (x \\in collective_pred_of_simpl msp) = p x.\nProof. by case: msp => _ /= ->. Qed.\n\nLemma in_simpl x p (msp : manifest_simpl_pred p) :\n  in_mem x (Mem [eta fun_of_simpl (msp : simpl_pred T)]) = p x.\nProof. by case: msp => _ /= ->. Qed.\n\n(* Because of the explicit eta expansion in the left-hand side, this lemma    *)\n(* should only be used in a right-to-left direction. The 8.3 hack allowing    *)\n(* partial right-to-left use does not work with the improved expansion        *)\n(* heuristics in 8.4.                                                         *)\nLemma unfold_in x p : (x \\in ([eta p] : pred T)) = p x.\nProof. by []. Qed.\n\nLemma simpl_predE p : SimplPred p =1 p.\nProof. by []. Qed.\n\nDefinition inE := (in_applicative, in_simpl, simpl_predE). (* to be extended *)\n\nLemma mem_simpl sp : mem sp = sp :> pred T.\nProof. by []. Qed.\n\nDefinition memE := mem_simpl. (* could be extended *)\n\nLemma mem_mem (pp : pT) : (mem (mem pp) = mem pp) * (mem [mem pp] = mem pp).\nProof. by rewrite -mem_topred. Qed.\n\nEnd simpl_mem.\n\n(* Qualifiers and keyed predicates. *)\n\nCoInductive qualifier (q : nat) T := Qualifier of predPredType T.\n\nCoercion has_quality n T (q : qualifier n T) : pred_class :=\n  fun x => let: Qualifier p := q in p x.\nImplicit Arguments has_quality [T].\n\nLemma qualifE n T p x : (x \\in @Qualifier n T p) = p x. Proof. by []. Qed.\n\nNotation \"x \\is A\" := (x \\in has_quality 0 A) \n  (at level 70, no associativity,\n   format \"'[hv' x '/ '  \\is  A ']'\") : bool_scope.\nNotation \"x \\is 'a' A\" := (x \\in has_quality 1 A) \n  (at level 70, no associativity,\n   format \"'[hv' x '/ '  \\is  'a'  A ']'\") : bool_scope.\nNotation \"x \\is 'an' A\" := (x \\in has_quality 2 A) \n  (at level 70, no associativity,\n   format \"'[hv' x '/ ' \\is  'an'  A ']'\") : bool_scope.\nNotation \"x \\isn't A\" := (x \\notin has_quality 0 A) \n  (at level 70, no associativity,\n   format \"'[hv' x '/ '  \\isn't  A ']'\") : bool_scope.\nNotation \"x \\isn't 'a' A\" := (x \\notin has_quality 1 A) \n  (at level 70, no associativity,\n   format \"'[hv' x '/ '  \\isn't  'a'  A ']'\") : bool_scope.\nNotation \"x \\isn't 'an' A\" := (x \\notin has_quality 2 A) \n  (at level 70, no associativity,\n   format \"'[hv' x '/ ' \\isn't  'an'  A ']'\") : bool_scope.\nNotation \"[ 'qualify' x | P ]\" := (Qualifier 0 (fun x => P%B))\n  (at level 0, x at level 99,\n   format \"'[hv' [  'qualify'  x  | '/ '  P ] ']'\") : form_scope.\nNotation \"[ 'qualify' x : T | P ]\" := (Qualifier 0 (fun x : T => P%B))\n  (at level 0, x at level 99, only parsing) : form_scope.\nNotation \"[ 'qualify' 'a' x | P ]\" := (Qualifier 1 (fun x => P%B))\n  (at level 0, x at level 99,\n   format \"'[hv' [ 'qualify'  'a'  x  | '/ '  P ] ']'\") : form_scope.\nNotation \"[ 'qualify' 'a' x : T | P ]\" := (Qualifier 1 (fun x : T => P%B))\n  (at level 0, x at level 99, only parsing) : form_scope.\nNotation \"[ 'qualify' 'an' x | P ]\" := (Qualifier 2 (fun x => P%B))\n  (at level 0, x at level 99,\n   format \"'[hv' [ 'qualify'  'an'  x  | '/ '  P ] ']'\") : form_scope.\nNotation \"[ 'qualify' 'an' x : T | P ]\" := (Qualifier 2 (fun x : T => P%B))\n  (at level 0, x at level 99, only parsing) : form_scope.\n\n(* Keyed predicates: support for property-bearing predicate interfaces. *)\n\nSection KeyPred.\n\nVariable T : Type.\nCoInductive pred_key (p : predPredType T) := DefaultPredKey.\n\nVariable p : predPredType T.\nStructure keyed_pred (k : pred_key p) :=\n  PackKeyedPred {unkey_pred :> pred_class; _ : unkey_pred =i p}.\n\nVariable k : pred_key p.\nDefinition KeyedPred := @PackKeyedPred k p (frefl _).\n\nVariable k_p : keyed_pred k.\nLemma keyed_predE : k_p =i p. Proof. by case: k_p. Qed.\n\n(* Instances that strip the mem cast; the first one has \"pred_of_mem\" as its  *)\n(* projection head value, while the second has \"pred_of_simpl\". The latter    *)\n(* has the side benefit of preempting accidental misdeclarations.             *)\n(* Note: pred_of_mem is the registered mem >-> pred_class coercion, while     *)\n(* simpl_of_mem; pred_of_simpl is the mem >-> pred >=> Funclass coercion. We  *)\n(* must write down the coercions explicitly as the Canonical head constant    *)\n(* computation does not strip casts !!                                        *)\nCanonical keyed_mem :=\n  @PackKeyedPred k (pred_of_mem (mem k_p)) keyed_predE.\nCanonical keyed_mem_simpl :=\n  @PackKeyedPred k (pred_of_simpl (mem k_p)) keyed_predE.\n\nEnd KeyPred.\n\nNotation \"x \\i 'n' S\" := (x \\in @unkey_pred _ S _ _)\n  (at level 70, format \"'[hv' x '/ '  \\i 'n'  S ']'\") : bool_scope.\n\nSection KeyedQualifier.\n\nVariables (T : Type) (n : nat) (q : qualifier n T).\n\nStructure keyed_qualifier (k : pred_key q) :=\n  PackKeyedQualifier {unkey_qualifier; _ : unkey_qualifier = q}.\nDefinition KeyedQualifier k := PackKeyedQualifier k (erefl q).\nVariables (k : pred_key q) (k_q : keyed_qualifier k).\nFact keyed_qualifier_suproof : unkey_qualifier k_q =i q.\nProof. by case: k_q => /= _ ->. Qed.\nCanonical keyed_qualifier_keyed := PackKeyedPred k keyed_qualifier_suproof.\n\nEnd KeyedQualifier.\n\nNotation \"x \\i 's' A\" := (x \\i n has_quality 0 A) \n  (at level 70, format \"'[hv' x '/ '  \\i 's'  A ']'\") : bool_scope.\nNotation \"x \\i 's' 'a' A\" := (x \\i n has_quality 1 A) \n  (at level 70, format \"'[hv' x '/ '  \\i 's'  'a'  A ']'\") : bool_scope.\nNotation \"x \\i 's' 'an' A\" := (x \\i n has_quality 2 A) \n  (at level 70, format \"'[hv' x '/ '  \\i 's'  'an'  A ']'\") : bool_scope.\n\nModule DefaultKeying.\n\nCanonical default_keyed_pred T p := KeyedPred (@DefaultPredKey T p).\nCanonical default_keyed_qualifier T n (q : qualifier n T) :=\n  KeyedQualifier (DefaultPredKey q).\n\nEnd DefaultKeying.\n\n(* Skolemizing with conditions. *)\n\nLemma all_tag_cond_dep I T (C : pred I) U :\n    (forall x, T x) -> (forall x, C x -> {y : T x & U x y}) ->\n  {f : forall x, T x & forall x, C x -> U x (f x)}.\nProof.\nmove=> f0 fP; apply: all_tag (fun x y => C x -> U x y) _ => x.\nby case Cx: (C x); [case/fP: Cx => y; exists y | exists (f0 x)].\nQed.\n\nLemma all_tag_cond I T (C : pred I) U :\n    T -> (forall x, C x -> {y : T & U x y}) ->\n  {f : I -> T & forall x, C x -> U x (f x)}.\nProof. by move=> y0; apply: all_tag_cond_dep. Qed.\n\nLemma all_sig_cond_dep I T (C : pred I) P :\n    (forall x, T x) -> (forall x, C x -> {y : T x | P x y}) ->\n  {f : forall x, T x | forall x, C x -> P x (f x)}.\nProof. by move=> f0 /(all_tag_cond_dep f0)[f]; exists f. Qed.\n\nLemma all_sig_cond I T (C : pred I) P :\n    T -> (forall x, C x -> {y : T | P x y}) ->\n  {f : I -> T | forall x, C x -> P x (f x)}.\nProof. by move=> y0; apply: all_sig_cond_dep. Qed.\n\nSection RelationProperties.\n\n(* Caveat: reflexive should not be used to state lemmas, as auto and trivial  *)\n(* will not expand the constant.                                              *)\n\nVariable T : Type.\n\nVariable R : rel T.\n\nDefinition total := forall x y, R x y || R y x.\nDefinition transitive := forall y x z, R x y -> R y z -> R x z.\n\nDefinition symmetric := forall x y, R x y = R y x.\nDefinition antisymmetric := forall x y, R x y && R y x -> x = y.\nDefinition pre_symmetric := forall x y, R x y -> R y x.\n\nLemma symmetric_from_pre : pre_symmetric -> symmetric.\nProof. move=> symR x y; apply/idP/idP; exact: symR. Qed.\n  \nDefinition reflexive := forall x, R x x.\nDefinition irreflexive := forall x, R x x = false.\n\nDefinition left_transitive := forall x y, R x y -> R x =1 R y.\nDefinition right_transitive := forall x y, R x y -> R^~ x =1 R^~ y.\n\nSection PER.\n\nHypotheses (symR : symmetric) (trR : transitive).\n\nLemma sym_left_transitive : left_transitive.\nProof. by move=> x y Rxy z; apply/idP/idP; apply: trR; rewrite // symR. Qed.\n\nLemma sym_right_transitive : right_transitive.\nProof. by move=> x y /sym_left_transitive Rxy z; rewrite !(symR z) Rxy. Qed.\n\nEnd PER.\n\n(* We define the equivalence property with prenex quantification so that it   *)\n(* can be localized using the {in ..., ..} form defined below.                *)\n\nDefinition equivalence_rel := forall x y z, R z z * (R x y -> R x z = R y z).\n\nLemma equivalence_relP : equivalence_rel <-> reflexive /\\ left_transitive.\nProof.\nsplit=> [eqiR | [Rxx trR] x y z]; last by split=> [|/trR->].\nby split=> [x | x y Rxy z]; [rewrite (eqiR x x x) | rewrite (eqiR x y z)].\nQed.\n\nEnd RelationProperties.\n\nLemma rev_trans T (R : rel T) : transitive R -> transitive (fun x y => R y x).\nProof. by move=> trR x y z Ryx Rzy; exact: trR Rzy Ryx. Qed.\n\n(* Property localization *)\n\nNotation Local \"{ 'all1' P }\" := (forall x, P x : Prop) (at level 0).\nNotation Local \"{ 'all2' P }\" := (forall x y, P x y : Prop) (at level 0).\nNotation Local \"{ 'all3' P }\" := (forall x y z, P x y z: Prop) (at level 0).\nNotation Local ph := (phantom _).\n\nSection LocalProperties.\n\nVariables T1 T2 T3 : Type.\n\nVariables (d1 : mem_pred T1) (d2 : mem_pred T2) (d3 : mem_pred T3).\nNotation Local ph := (phantom Prop).\n\nDefinition prop_for (x : T1) P & ph {all1 P} := P x.\n\nLemma forE x P phP : @prop_for x P phP = P x. Proof. by []. Qed.\n\nDefinition prop_in1 P & ph {all1 P} :=\n  forall x, in_mem x d1 -> P x.\n\nDefinition prop_in11 P & ph {all2 P} :=\n  forall x y, in_mem x d1 -> in_mem y d2 -> P x y.\n\nDefinition prop_in2 P & ph {all2 P} :=\n  forall x y, in_mem x d1 -> in_mem y d1 -> P x y.\n\nDefinition prop_in111 P & ph {all3 P} :=\n  forall x y z, in_mem x d1 -> in_mem y d2 -> in_mem z d3 -> P x y z.\n\nDefinition prop_in12 P & ph {all3 P} :=\n  forall x y z, in_mem x d1 -> in_mem y d2 -> in_mem z d2 -> P x y z.\n\nDefinition prop_in21 P & ph {all3 P} :=\n  forall x y z, in_mem x d1 -> in_mem y d1 -> in_mem z d2 -> P x y z.\n\nDefinition prop_in3 P & ph {all3 P} :=\n  forall x y z, in_mem x d1 -> in_mem y d1 -> in_mem z d1 -> P x y z.\n\nVariable f : T1 -> T2.\n\nDefinition prop_on1 Pf P & phantom T3 (Pf f) & ph {all1 P} :=\n  forall x, in_mem (f x) d2 -> P x.\n\nDefinition prop_on2 Pf P & phantom T3 (Pf f) & ph {all2 P} :=\n  forall x y, in_mem (f x) d2 -> in_mem (f y) d2 -> P x y.\n\nEnd LocalProperties.\n\nDefinition inPhantom := Phantom Prop.\nDefinition onPhantom T P (x : T) := Phantom Prop (P x).\n\nDefinition bijective_in aT rT (d : mem_pred aT) (f : aT -> rT) :=\n  exists2 g, prop_in1 d (inPhantom (cancel f g))\n           & prop_on1 d (Phantom _ (cancel g)) (onPhantom (cancel g) f).\n\nDefinition bijective_on aT rT (cd : mem_pred rT) (f : aT -> rT) :=\n  exists2 g, prop_on1 cd (Phantom _ (cancel f)) (onPhantom (cancel f) g)\n           & prop_in1 cd (inPhantom (cancel g f)).\n\nNotation \"{ 'for' x , P }\" :=\n  (prop_for x (inPhantom P))\n  (at level 0, format \"{ 'for'  x ,  P }\") : type_scope.\n\nNotation \"{ 'in' d , P }\" :=\n  (prop_in1 (mem d) (inPhantom P))\n  (at level 0, format \"{ 'in'  d ,  P }\") : type_scope.\n\nNotation \"{ 'in' d1 & d2 , P }\" :=\n  (prop_in11 (mem d1) (mem d2) (inPhantom P))\n  (at level 0, format \"{ 'in'  d1  &  d2 ,  P }\") : type_scope.\n\nNotation \"{ 'in' d & , P }\" :=\n  (prop_in2 (mem d) (inPhantom P))\n  (at level 0, format \"{ 'in'  d  & ,  P }\") : type_scope.\n\nNotation \"{ 'in' d1 & d2 & d3 , P }\" :=\n  (prop_in111 (mem d1) (mem d2) (mem d3) (inPhantom P))\n  (at level 0, format \"{ 'in'  d1  &  d2  &  d3 ,  P }\") : type_scope.\n\nNotation \"{ 'in' d1 & & d3 , P }\" :=\n  (prop_in21 (mem d1) (mem d3) (inPhantom P))\n  (at level 0, format \"{ 'in'  d1  &  &  d3 ,  P }\") : type_scope.\n\nNotation \"{ 'in' d1 & d2 & , P }\" :=\n  (prop_in12 (mem d1) (mem d2) (inPhantom P))\n  (at level 0, format \"{ 'in'  d1  &  d2  & ,  P }\") : type_scope.\n\nNotation \"{ 'in' d & & , P }\" :=\n  (prop_in3 (mem d) (inPhantom P))\n  (at level 0, format \"{ 'in'  d  &  & ,  P }\") : type_scope.\n\nNotation \"{ 'on' cd , P }\" :=\n  (prop_on1 (mem cd) (inPhantom P) (inPhantom P))\n  (at level 0, format \"{ 'on'  cd ,  P }\") : type_scope.\n\nNotation \"{ 'on' cd & , P }\" :=\n  (prop_on2 (mem cd) (inPhantom P) (inPhantom P))\n  (at level 0, format \"{ 'on'  cd  & ,  P }\") : type_scope.\n\nNotation \"{ 'on' cd , P & g }\" :=\n  (prop_on1 (mem cd) (Phantom (_ -> Prop) P) (onPhantom P g))\n  (at level 0, format \"{ 'on'  cd ,  P  &  g }\") : type_scope.\n\nNotation \"{ 'in' d , 'bijective' f }\" := (bijective_in (mem d) f)\n  (at level 0, f at level 8,\n   format \"{ 'in'  d ,  'bijective'  f }\") : type_scope.\n\nNotation \"{ 'on' cd , 'bijective' f }\" := (bijective_on (mem cd) f)\n  (at level 0, f at level 8,\n   format \"{ 'on'  cd ,  'bijective'  f }\") : type_scope.\n\n(* Weakening and monotonicity lemmas for localized predicates.                *)\n(* Note that using these lemmas in backward reasoning will force expansion of *)\n(* the predicate definition, as Coq needs to expose the quantifier to apply   *)\n(* these lemmas. We define a few specialized variants to avoid this for some  *)\n(* of the ssrfun predicates.                                                  *)\n\nSection LocalGlobal.\n\nVariables T1 T2 T3 : predArgType.\nVariables (D1 : pred T1) (D2 : pred T2) (D3 : pred T3).\nVariables (d1 d1' : mem_pred T1) (d2 d2' : mem_pred T2) (d3 d3' : mem_pred T3).\nVariables (f f' : T1 -> T2) (g : T2 -> T1) (h : T3).\nVariables (P1 : T1 -> Prop) (P2 : T1 -> T2 -> Prop).\nVariable P3 : T1 -> T2 -> T3 -> Prop.\nVariable Q1 : (T1 -> T2) -> T1 -> Prop.\nVariable Q1l : (T1 -> T2) -> T3 -> T1 -> Prop.\nVariable Q2 : (T1 -> T2) -> T1 -> T1 -> Prop.\n\nHypothesis sub1 : sub_mem d1 d1'.\nHypothesis sub2 : sub_mem d2 d2'.\nHypothesis sub3 : sub_mem d3 d3'.\n\nLemma in1W : {all1 P1} -> {in D1, {all1 P1}}.\nProof. by move=> ? ?. Qed.\nLemma in2W : {all2 P2} -> {in D1 & D2, {all2 P2}}.\nProof. by move=> ? ?. Qed.\nLemma in3W : {all3 P3} -> {in D1 & D2 & D3, {all3 P3}}.\nProof. by move=> ? ?. Qed.\n\nLemma in1T : {in T1, {all1 P1}} -> {all1 P1}.\nProof. by move=> ? ?; auto. Qed.\nLemma in2T : {in T1 & T2, {all2 P2}} -> {all2 P2}.\nProof. by move=> ? ?; auto. Qed.\nLemma in3T : {in T1 & T2 & T3, {all3 P3}} -> {all3 P3}.\nProof. by move=> ? ?; auto. Qed.\n\nLemma sub_in1 (Ph : ph {all1 P1}) : prop_in1 d1' Ph -> prop_in1 d1 Ph.\nProof. move=> allP x /sub1; exact: allP. Qed.\n\nLemma sub_in11 (Ph : ph {all2 P2}) : prop_in11 d1' d2' Ph -> prop_in11 d1 d2 Ph.\nProof. move=> allP x1 x2 /sub1 d1x1 /sub2; exact: allP. Qed.\n\nLemma sub_in111 (Ph : ph {all3 P3}) :\n  prop_in111 d1' d2' d3' Ph -> prop_in111 d1 d2 d3 Ph.\nProof. by move=> allP x1 x2 x3 /sub1 d1x1 /sub2 d2x2 /sub3; exact: allP. Qed.\n\nLet allQ1 f'' := {all1 Q1 f''}.\nLet allQ1l f'' h' := {all1 Q1l f'' h'}.\nLet allQ2 f'' := {all2 Q2 f''}.\n\nLemma on1W : allQ1 f -> {on D2, allQ1 f}. Proof. by move=> ? ?. Qed.\n\nLemma on1lW : allQ1l f h -> {on D2, allQ1l f & h}. Proof. by move=> ? ?. Qed.\n\nLemma on2W : allQ2 f -> {on D2 &, allQ2 f}. Proof. by move=> ? ?. Qed.\n\nLemma on1T : {on T2, allQ1 f} -> allQ1 f. Proof. by move=> ? ?; auto. Qed.\n\nLemma on1lT : {on T2, allQ1l f & h} -> allQ1l f h.\nProof. by move=> ? ?; auto. Qed.\n\nLemma on2T : {on T2 &, allQ2 f} -> allQ2 f.\nProof. by move=> ? ?; auto. Qed.\n\nLemma subon1 (Phf : ph (allQ1 f)) (Ph : ph (allQ1 f)) :\n  prop_on1 d2' Phf Ph -> prop_on1 d2 Phf Ph.\nProof. by move=> allQ x /sub2; exact: allQ. Qed.\n\nLemma subon1l (Phf : ph (allQ1l f)) (Ph : ph (allQ1l f h)) :\n  prop_on1 d2' Phf Ph -> prop_on1 d2 Phf Ph.\nProof. by move=> allQ x /sub2; exact: allQ. Qed.\n\nLemma subon2 (Phf : ph (allQ2 f)) (Ph : ph (allQ2 f)) :\n  prop_on2 d2' Phf Ph -> prop_on2 d2 Phf Ph.\nProof. by move=> allQ x y /sub2=> d2fx /sub2; exact: allQ. Qed.\n\nLemma can_in_inj : {in D1, cancel f g} -> {in D1 &, injective f}.\nProof. by move=> fK x y /fK{2}<- /fK{2}<- ->. Qed.\n\nLemma canLR_in x y : {in D1, cancel f g} -> y \\in D1 -> x = f y -> g x = y.\nProof. by move=> fK D1y ->; rewrite fK. Qed.\n\nLemma canRL_in x y : {in D1, cancel f g} -> x \\in D1 -> f x = y -> x = g y.\nProof. by move=> fK D1x <-; rewrite fK. Qed.\n\nLemma on_can_inj : {on D2, cancel f & g} -> {on D2 &, injective f}.\nProof. by move=> fK x y /fK{2}<- /fK{2}<- ->. Qed.\n\nLemma canLR_on x y : {on D2, cancel f & g} -> f y \\in D2 -> x = f y -> g x = y.\nProof. by move=> fK D2fy ->; rewrite fK. Qed.\n\nLemma canRL_on x y : {on D2, cancel f & g} -> f x \\in D2 -> f x = y -> x = g y.\nProof. by move=> fK D2fx <-; rewrite fK. Qed.\n\nLemma inW_bij : bijective f -> {in D1, bijective f}.\nProof. by case=> g' fK g'K; exists g' => * ? *; auto. Qed.\n\nLemma onW_bij : bijective f -> {on D2, bijective f}.\nProof. by case=> g' fK g'K; exists g' => * ? *; auto. Qed.\n\nLemma inT_bij : {in T1, bijective f} -> bijective f.\nProof. by case=> g' fK g'K; exists g' => * ? *; auto. Qed.\n\nLemma onT_bij : {on T2, bijective f} -> bijective f.\nProof. by case=> g' fK g'K; exists g' => * ? *; auto. Qed.\n\nLemma sub_in_bij (D1' : pred T1) :\n  {subset D1 <= D1'} -> {in D1', bijective f} -> {in D1, bijective f}.\nProof.\nby move=> subD [g' fK g'K]; exists g' => x; move/subD; [exact: fK | exact: g'K].\nQed.\n\nLemma subon_bij (D2' : pred T2) :\n  {subset D2 <= D2'} -> {on D2', bijective f} -> {on D2, bijective f}.\nProof.\nby move=> subD [g' fK g'K]; exists g' => x; move/subD; [exact: fK | exact: g'K].\nQed.\n\nEnd LocalGlobal.\n\nLemma sub_in2 T d d' (P : T -> T -> Prop) :\n  sub_mem d d' -> forall Ph : ph {all2 P}, prop_in2 d' Ph -> prop_in2 d Ph.\nProof. by move=> /= sub_dd'; exact: sub_in11. Qed.\n\nLemma sub_in3 T d d' (P : T -> T -> T -> Prop) :\n  sub_mem d d' -> forall Ph : ph {all3 P}, prop_in3 d' Ph -> prop_in3 d Ph.\nProof. by move=> /= sub_dd'; exact: sub_in111. Qed.\n\nLemma sub_in12 T1 T d1 d1' d d' (P : T1 -> T -> T -> Prop) :\n  sub_mem d1 d1' -> sub_mem d d' ->\n  forall Ph : ph {all3 P}, prop_in12 d1' d' Ph -> prop_in12 d1 d Ph.\nProof. by move=> /= sub1 sub; exact: sub_in111. Qed.\n\nLemma sub_in21 T T3 d d' d3 d3' (P : T -> T -> T3 -> Prop) :\n  sub_mem d d' -> sub_mem d3 d3' ->\n  forall Ph : ph {all3 P}, prop_in21 d' d3' Ph -> prop_in21 d d3 Ph.\nProof. by move=> /= sub sub3; exact: sub_in111. Qed.\n\nLemma equivalence_relP_in T (R : rel T) (A : pred T) :\n  {in A & &, equivalence_rel R}\n   <-> {in A, reflexive R} /\\ {in A &, forall x y, R x y -> {in A, R x =1 R y}}.\nProof.\nsplit=> [eqiR | [Rxx trR] x y z *]; last by split=> [|/trR-> //]; exact: Rxx.\nby split=> [x Ax|x y Ax Ay Rxy z Az]; [rewrite (eqiR x x) | rewrite (eqiR x y)].\nQed.\n\nSection MonoHomoMorphismTheory.\n\nVariables (aT rT sT : Type) (f : aT -> rT) (g : rT -> aT).\nVariables (aP : pred aT) (rP : pred rT) (aR : rel aT) (rR : rel rT).\n\nLemma monoW : {mono f : x / aP x >-> rP x} -> {homo f : x / aP x >-> rP x}.\nProof. by move=> hf x ax; rewrite hf. Qed.\n\nLemma mono2W :\n  {mono f : x y / aR x y >-> rR x y} -> {homo f : x y / aR x y >-> rR x y}.\nProof. by move=> hf x y axy; rewrite hf. Qed.\n\nHypothesis fgK : cancel g f.\n\nLemma homoRL :\n  {homo f : x y / aR x y >-> rR x y} -> forall x y, aR (g x) y -> rR x (f y).\nProof. by move=> Hf x y /Hf; rewrite fgK. Qed.\n\nLemma homoLR :\n  {homo f : x y / aR x y >-> rR x y} -> forall x y, aR x (g y) -> rR (f x) y.\nProof. by move=> Hf x y /Hf; rewrite fgK. Qed.\n\nLemma homo_mono :\n    {homo f : x y / aR x y >-> rR x y} -> {homo g : x y / rR x y >-> aR x y} ->\n  {mono g : x y / rR x y >-> aR x y}.\nProof.\nmove=> mf mg x y; case: (boolP (rR _ _))=> [/mg //|].\nby apply: contraNF=> /mf; rewrite !fgK.\nQed.\n\nLemma monoLR :\n  {mono f : x y / aR x y >-> rR x y} -> forall x y, rR (f x) y = aR x (g y).\nProof. by move=> mf x y; rewrite -{1}[y]fgK mf. Qed.\n\nLemma monoRL :\n  {mono f : x y / aR x y >-> rR x y} -> forall x y, rR x (f y) = aR (g x) y.\nProof. by move=> mf x y; rewrite -{1}[x]fgK mf. Qed.\n\nLemma can_mono :\n  {mono f : x y / aR x y >-> rR x y} -> {mono g : x y / rR x y >-> aR x y}.\nProof. by move=> mf x y /=; rewrite -mf !fgK. Qed.\n\nEnd MonoHomoMorphismTheory.\n\nSection MonoHomoMorphismTheory_in.\n\nVariables (aT rT sT : predArgType) (f : aT -> rT) (g : rT -> aT).\nVariable (aD : pred aT).\nVariable (aP : pred aT) (rP : pred rT) (aR : rel aT) (rR : rel rT).\n\nNotation rD := [pred x | g x \\in aD].\n\nLemma monoW_in :\n    {in aD &, {mono f : x y / aR x y >-> rR x y}} ->\n  {in aD &, {homo f : x y / aR x y >-> rR x y}}.\nProof. by move=> hf x y hx hy axy; rewrite hf. Qed.\n\nLemma mono2W_in :\n    {in aD, {mono f : x / aP x >-> rP x}} ->\n  {in aD, {homo f : x / aP x >-> rP x}}.\nProof. by move=> hf x hx ax; rewrite hf. Qed.\n\nHypothesis fgK_on : {on aD, cancel g & f}.\n\nLemma homoRL_in :\n    {in aD &, {homo f : x y / aR x y >-> rR x y}} ->\n  {in rD & aD, forall x y, aR (g x) y -> rR x (f y)}.\nProof. by move=> Hf x y hx hy /Hf; rewrite fgK_on //; apply. Qed.\n\nLemma homoLR_in :\n    {in aD &, {homo f : x y / aR x y >-> rR x y}} ->\n  {in aD & rD, forall x y, aR x (g y) -> rR (f x) y}.\nProof. by move=> Hf x y hx hy /Hf; rewrite fgK_on //; apply. Qed.\n\nLemma homo_mono_in :\n    {in aD &, {homo f : x y / aR x y >-> rR x y}} ->\n    {in rD &, {homo g : x y / rR x y >-> aR x y}} ->\n  {in rD &, {mono g : x y / rR x y >-> aR x y}}.\nProof.\nmove=> mf mg x y hx hy; case: (boolP (rR _ _))=> [/mg //|]; first exact.\nby apply: contraNF=> /mf; rewrite !fgK_on //; apply.\nQed.\n\nLemma monoLR_in :\n    {in aD &, {mono f : x y / aR x y >-> rR x y}} ->\n  {in aD & rD, forall x y, rR (f x) y = aR x (g y)}.\nProof. by move=> mf x y hx hy; rewrite -{1}[y]fgK_on // mf. Qed.\n\nLemma monoRL_in :\n    {in aD &, {mono f : x y / aR x y >-> rR x y}} ->\n  {in rD & aD, forall x y, rR x (f y) = aR (g x) y}.\nProof. by move=> mf x y hx hy; rewrite -{1}[x]fgK_on // mf. Qed.\n\nLemma can_mono_in :\n    {in aD &, {mono f : x y / aR x y >-> rR x y}} ->\n  {in rD &, {mono g : x y / rR x y >-> aR x y}}.\nProof. by move=> mf x y hx hy /=; rewrite -mf // !fgK_on. Qed.\n\nEnd MonoHomoMorphismTheory_in.\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/ssrbool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.656777521985511}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool List.\nFrom Coq Require Import FunctionalExtensionality.\nFrom Mon Require Export Base.\nFrom Coq Require Import Relation_Definitions Morphisms.\nFrom Mon Require Import SPropBase SPropMonadicStructures.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Primitive Projections.\n\nSection Monoid.\n  Record monoid :=\n    mkMonoid\n      { monoid_carrier :> Type\n      ; monoid_unit : monoid_carrier\n      ; monoid_mult : monoid_carrier -> monoid_carrier -> monoid_carrier\n      ; monoid_law1 : forall m, monoid_mult monoid_unit m = m\n      ; monoid_law2 : forall m, monoid_mult m monoid_unit = m\n      ; monoid_law3 : forall m1 m2 m3,\n          monoid_mult (monoid_mult m1 m2) m3 = monoid_mult m1 (monoid_mult m2 m3)\n      }.\n\n  Definition e := monoid_unit.\nEnd Monoid.\n\nNotation \"x ⋅ y\" := (monoid_mult x y) (at level 55).\n\nSection MonoidAction.\n\n  Record monoid_action (M : monoid) :=\n    mkAction\n      { monact_carrier :> Type\n      ; monact_action : M -> monact_carrier -> monact_carrier\n      ; monact_unit : forall x, monact_action (e M) x = x\n      ; monact_mult : forall m1 m2 x, monact_action (m1 ⋅ m2) x = monact_action m1 (monact_action m2 x)\n      }.\n\nEnd MonoidAction.\n\nNotation \"m ⧕ x\" := (monact_action m x) (at level 55).\n\n\nSection MonoidExamples.\n\n  Program Definition endMonoid (X : Type) : monoid :=\n    @mkMonoid (X -> X) id (fun f g x => f (g x)) _ _ _.\n\n  Program Definition unitMonoid : monoid :=\n    @mkMonoid unit tt (fun _ _ => tt) _ _ _.\n  (* This does not solve the goal but the latter does ??? *)\n  (* Solve Obligations with move: m => [] //. *)\n  Solve Obligations with destruct m ; reflexivity.\n\n  Program Definition oneMonoid : monoid := endMonoid False.\n\n  Import FunctionalExtensionality.\n  Program Definition pointwiseMonoid (X:Type) (M:monoid) : monoid :=\n    @mkMonoid (X -> M) (fun _ => e M) (fun f g x => f x ⋅ g x) _ _ _.\n  Next Obligation. extensionality y ; rewrite monoid_law1 //. Qed.\n  Next Obligation. extensionality y ; rewrite monoid_law2 //. Qed.\n  Next Obligation. extensionality y ; rewrite monoid_law3 //. Qed.\n\n  Program Definition listMonoid (X:Type) : monoid :=\n    @mkMonoid (list X) nil (@app _) _ (@List.app_nil_r _) (@List.app_assoc_reverse _).\n\n  Program Definition prodMonoid (M1 M2:monoid) : monoid :=\n    @mkMonoid (M1 × M2) ⟨e M1, e M2⟩ (fun x y => ⟨nfst x ⋅ nfst y, nsnd x ⋅ nsnd y⟩)\n              _ _ _.\n  Next Obligation. rewrite !monoid_law1 //. Qed.\n  Next Obligation. rewrite !monoid_law2 //. Qed.\n  Next Obligation. rewrite !monoid_law3 //. Qed.\n\n  Program Definition optionMonoid (X:Type) : monoid :=\n    @mkMonoid (option X) None (fun m1 m2 => match m1 with\n                                         | None => m2\n                                         | Some x => Some x end) _ _ _.\n  Next Obligation. move: m => [] //. Qed.\n  Next Obligation. move: m1 m2 m3 => [?|] [?|] [?|] //. Qed.\n\n  Import SPropNotations.\n  Program Definition overwriteMonoid (X:Type) : monoid :=\n    @mkMonoid { f : X -> X | exists (m: optionMonoid X), forall x, Some (f x) = m⋅(Some x)}\n              (exist _ id _)\n              (fun f g => exist _ (proj1_sig f \\o proj1_sig g) _) _ _ _.\n  Next Obligation. exists None. move=> ? //. Qed.\n  Next Obligation.\n    move: H1 H2 H H0 => mf Hf mg Hg.\n    exists (@monoid_mult (optionMonoid X) mf mg).\n    move=> ? ; move: mf mg Hf Hg => [?|] [?|] Hf Hg /= ; try by apply Hf.\n    all: eapply (eq_trans (Hf _)); apply Hg.\n  Qed.\n  Next Obligation.  compute. f_equal.\n    apply ax_proof_irrel.\n  Qed.\n  Next Obligation. compute. f_equal.\n    apply ax_proof_irrel.\n  Qed.\n  Next Obligation. compute. f_equal. apply ax_proof_irrel. Qed.\n\nEnd MonoidExamples.\n\nSection ActionExamples.\n  Program Definition multAction (M:monoid) : monoid_action M :=\n    @mkAction M M (fun m1 m2 => m1 ⋅ m2) _ _.\n  Next Obligation. rewrite monoid_law1 //. Defined.\n  Next Obligation. rewrite monoid_law3 //. Defined.\n\n  Program Definition trivialAction (M : monoid) : monoid_action M :=\n    @mkAction M unit (fun _ x => x) _ _.\n\n  Program Definition endAction (X:Type) : monoid_action (endMonoid X) :=\n    @mkAction _ X (fun f x => f x) _ _.\n\n  Program Definition unitAction (X:Type) : monoid_action unitMonoid :=\n   @mkAction _ X (fun _ x => x) _ _.\n\n  Program Definition oneAction (X:Type) : monoid_action oneMonoid :=\n    @mkAction _ X (fun _ x => x) _ _.\n\n  Section PointwiseAction.\n    Context (A:Type) (M:monoid) (X:monoid_action M).\n    Let A_M := pointwiseMonoid A M.\n    Definition pointwise_action (m:A_M) (x : A -> X) (a:A) := m a ⧕ x a.\n\n    Definition pointwiseActionFromLaws pf1 pf2 :=\n      @mkAction A_M (A -> X) pointwise_action pf1 pf2.\n\n    Import FunctionalExtensionality.\n    Program Definition pointwiseAction := pointwiseActionFromLaws _ _.\n    Next Obligation. cbv ; extensionality a ; rewrite monact_unit //. Qed.\n    Next Obligation. cbv ; extensionality a ; rewrite monact_mult //. Qed.\n\n  End PointwiseAction.\n\n  Section ProdAction.\n    Context (M1 M2: monoid) (X1: monoid_action M1) (X2: monoid_action M2).\n    Let M12 := prodMonoid M1 M2.\n    Let X12 := X1 × X2.\n    Definition product_action (m12 : M12) (x12:X12) :=\n      ⟨nfst m12 ⧕ nfst x12, nsnd m12 ⧕ nsnd x12⟩.\n    Definition prodActionFromLaws pf1 pf2 :=\n      @mkAction M12 (X1 × X2) product_action pf1 pf2.\n    Program Definition prodAction := prodActionFromLaws _ _.\n    Next Obligation. rewrite /product_action 2!monact_unit //. Qed.\n    Next Obligation. rewrite /product_action 2!monact_mult //. Qed.\n  End ProdAction.\n\n  Program Definition optionAction (X:Type) : monoid_action (optionMonoid X):=\n    @mkAction _ X (fun m x => match m with None => x | Some x' => x' end) _ _.\n  Next Obligation. move: m1 m2 => [?|] [?|] //. Qed.\n\n  Program Definition overwriteAction (X:Type)\n    : monoid_action (overwriteMonoid X) :=\n    @mkAction _ X (fun f x => proj1_sig f x) _ _.\nEnd ActionExamples.\n\nSection MonoidStrictification.\n  (* Given any monoid with monoid laws holding propositionally,\n     we can turn it into one where the laws hold definitionally *)\n  Context (M : monoid).\n  Import SPropNotations.\n\n  Definition SM := { f : M -> M | exists m, forall m', f m' = m ⋅ m'}.\n  Program Definition se : SM := exist _ id _.\n  Next Obligation.\n    exists (e M). intros ; rewrite monoid_law1 //.\n  Qed.\n\n  Program Definition smult (sm1 sm2 : SM) : SM :=\n    exist _ (proj1_sig sm1 \\o proj1_sig sm2) _.\n  Next Obligation.\n    move:sm1 sm2=> [? [m1 H1]] [? [m2 H2]].\n    exists (m1 ⋅ m2) ; move=> m /=.\n    rewrite monoid_law3. eelim (H2 _). eelim (H1 _) => //.\n  Qed.\n\n  Program Definition strict_monoid := @mkMonoid SM se smult _ _ _.\n\n  Program Definition embed (m:M) : SM := exist _ (monoid_mult m) _.\n  Next Obligation. exists m ; move=> ? //. Qed.\n\n  Definition project (sm : SM) : M := proj1_sig sm (e M).\n\n  Lemma embed_project_id : forall m, project (embed m) = m.\n  Proof. intro. cbv. rewrite monoid_law2 //. Qed.\n\n  Lemma sig_eq : forall (A : Type) (P : A -> Prop) (mx my : {x : A | P x}),\n       proj1_sig mx = proj1_sig my -> mx = my.\n  Proof.\n    intros A P [mx ?] [my ?] H. simpl in H.\n    induction H. compute. f_equal. apply ax_proof_irrel.\n  Qed.\n\n  Import SPropAxioms.\n  Lemma project_embed_id : forall sm, embed (project sm) = sm.\n  Proof.\n    intro sm. apply sig_eq ; extensionality m0.\n    cbv. move: (proj2_sig sm) => [m Hm].\n    pose (H0 := Hm m0).\n    apply eq_sym in H0.\n    unshelve eapply (eq_trans _ H0).\n    f_equiv. pose (He := Hm (e M)).\n    apply (eq_trans He).\n    rewrite monoid_law2 //.\n   Qed.\n  Next Obligation. compute. destruct m. f_equal. apply ax_proof_irrel. Qed.\n  Next Obligation. compute. destruct m. f_equal. apply ax_proof_irrel. Qed.\n  Next Obligation. compute. f_equal. apply ax_proof_irrel. Qed.\n\nEnd MonoidStrictification.\n\n(* A strictified version of the free monoid on a type O *)\n(* Useful to obtain update monads satisfying definitional monad laws *)\nSection StrictList.\n  Context (O:Type).\n  Definition strict_list_monoid : monoid := strict_monoid (listMonoid O).\n  Import SPropNotations.\n  Definition inject (o:O) : strict_list_monoid :=\n    @embed (listMonoid O) (cons o nil).\n  Definition snil : strict_list_monoid :=\n    @embed (listMonoid O) nil.\nEnd StrictList.\n", "meta": {"author": "SSProve", "repo": "ssprove", "sha": "5dce3e2eae195fc466035e314ef4463d956c9c6a", "save_path": "github-repos/coq/SSProve-ssprove", "path": "github-repos/coq/SSProve-ssprove/ssprove-5dce3e2eae195fc466035e314ef4463d956c9c6a/theories/Mon/Monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.6567394090331587}}
{"text": "Require Import Invariant Relations Sets.\n\nSet Implicit Arguments.\n\n\nDefinition oneStepClosure_current {state} (sys : trsys state)\n           (invariant1 invariant2 : state -> Prop) :=\n  forall st, invariant1 st\n             -> invariant2 st.\n\nDefinition oneStepClosure_new {state} (sys : trsys state)\n           (invariant1 invariant2 : state -> Prop) :=\n  forall st st', invariant1 st\n                 -> sys.(Step) st st'\n                 -> invariant2 st'.\n\nDefinition oneStepClosure {state} (sys : trsys state)\n           (invariant1 invariant2 : state -> Prop) :=\n  oneStepClosure_current sys invariant1 invariant2\n  /\\ oneStepClosure_new sys invariant1 invariant2.\n\nTheorem prove_oneStepClosure : forall state (sys : trsys state) (inv1 inv2 : state -> Prop),\n  (forall st, inv1 st -> inv2 st)\n  -> (forall st st', inv1 st -> sys.(Step) st st' -> inv2 st')\n  -> oneStepClosure sys inv1 inv2.\nProof.\n  unfold oneStepClosure; tauto.\nQed.\n\nTheorem oneStepClosure_done : forall state (sys : trsys state) (invariant : state -> Prop),\n  (forall st, sys.(Initial) st -> invariant st)\n  -> oneStepClosure sys invariant invariant\n  -> invariantFor sys invariant.\nProof.\n  unfold oneStepClosure, oneStepClosure_current, oneStepClosure_new.\n  intuition eauto using invariant_induction.\nQed.\n\nInductive multiStepClosure {state} (sys : trsys state)\n  : (state -> Prop) -> (state -> Prop) -> (state -> Prop) -> Prop :=\n| MscDone : forall inv worklist,\n    oneStepClosure sys inv inv\n    -> multiStepClosure sys inv worklist inv\n| MscStep : forall inv worklist inv' inv'',\n    oneStepClosure sys worklist inv'\n    -> multiStepClosure sys (inv \\cup inv') (inv' \\setminus inv) inv''\n    -> multiStepClosure sys inv worklist inv''.\n\nLemma multiStepClosure_ok' : forall state (sys : trsys state) (inv worklist inv' : state -> Prop),\n  multiStepClosure sys inv worklist inv'\n  -> (forall st, sys.(Initial) st -> inv st)\n  -> invariantFor sys inv'.\nProof.\n  induction 1; simpl; intuition eauto using oneStepClosure_done.\n\n  apply IHmultiStepClosure.\n  intuition.\n  apply H1 in H2.\n  sets idtac.\nQed.\n\nTheorem multiStepClosure_ok : forall state (sys : trsys state) (inv : state -> Prop),\n  multiStepClosure sys sys.(Initial) sys.(Initial) inv\n  -> invariantFor sys inv.\nProof.\n  eauto using multiStepClosure_ok'.\nQed.\n\nTheorem oneStepClosure_empty : forall state (sys : trsys state),\n  oneStepClosure sys (constant nil) (constant nil).\nProof.\n  unfold oneStepClosure, oneStepClosure_current, oneStepClosure_new; intuition.\nQed.\n\nTheorem oneStepClosure_split : forall state (sys : trsys state) st sts (inv1 inv2 : state -> Prop),\n  (forall st', sys.(Step) st st' -> inv1 st')\n  -> oneStepClosure sys (constant sts) inv2\n  -> oneStepClosure sys (constant (st :: sts)) (constant (st :: nil) \\cup inv1 \\cup inv2).\nProof.\n  unfold oneStepClosure, oneStepClosure_current, oneStepClosure_new; intuition.\n\n  inversion H0; subst.\n  unfold union; simpl; tauto.\n\n  unfold union; simpl; eauto.\n\n  unfold union in *; simpl in *.\n  intuition (subst; eauto).\nQed.\n\nTheorem singleton_in : forall {A} (x : A) rest,\n  (constant (x :: nil) \\cup rest) x.\nProof.\n  unfold union; simpl; auto.\nQed.\n\nTheorem singleton_in_other : forall {A} (x : A) (s1 s2 : set A),\n  s2 x\n  -> (s1 \\cup s2) x.\nProof.\n  unfold union; simpl; auto.\nQed.\n\n\n(** * Abstraction *)\n\nInductive simulates state1 state2 (R : state1 -> state2 -> Prop)\n  (sys1 : trsys state1) (sys2 : trsys state2) : Prop :=\n| Simulates :\n  (forall st1, sys1.(Initial) st1\n               -> exists st2, R st1 st2\n                              /\\ sys2.(Initial) st2)\n  -> (forall st1 st2, R st1 st2\n                      -> forall st1', sys1.(Step) st1 st1'\n                                      -> exists st2', R st1' st2'\n                                                      /\\ sys2.(Step) st2 st2')\n  -> simulates R sys1 sys2.\n\nInductive invariantViaSimulation state1 state2 (R : state1 -> state2 -> Prop)\n  (inv2 : state2 -> Prop)\n  : state1 -> Prop :=\n| InvariantViaSimulation : forall st1 st2, R st1 st2\n  -> inv2 st2\n  -> invariantViaSimulation R inv2 st1.\n\nLemma invariant_simulates' : forall state1 state2 (R : state1 -> state2 -> Prop)\n  (sys1 : trsys state1) (sys2 : trsys state2),\n  (forall st1 st2, R st1 st2\n                   -> forall st1', sys1.(Step) st1 st1'\n                                   ->  exists st2', R st1' st2'\n                                                    /\\ sys2.(Step) st2 st2')\n  -> forall st1 st1', sys1.(Step)^* st1 st1'\n                      -> forall st2, R st1 st2\n                                     -> exists st2', R st1' st2'\n                                                     /\\ sys2.(Step)^* st2 st2'.\nProof.\n  induction 2; simpl; intuition eauto.\n\n  eapply H in H2.\n  firstorder.\n  apply IHtrc in H2.\n  firstorder; eauto.\n  eauto.\nQed.\n\nLocal Hint Constructors invariantViaSimulation.\n\nTheorem invariant_simulates : forall state1 state2 (R : state1 -> state2 -> Prop)\n  (sys1 : trsys state1) (sys2 : trsys state2) (inv2 : state2 -> Prop),\n  simulates R sys1 sys2\n  -> invariantFor sys2 inv2\n  -> invariantFor sys1 (invariantViaSimulation R inv2).\nProof.\n  inversion_clear 1; intros.\n  unfold invariantFor; intros.\n  apply H0 in H2.\n  firstorder.\n  apply invariant_simulates' with (sys2 := sys2) (R := R) (st2 := x) in H3; auto.\n  firstorder; eauto.\nQed.\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/ModelCheck.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6567393969901478}}
{"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(** * dfa: Deterministic Finite Automata, decidability of language inclusion *)\n\nRequire Import comparisons positives ordinal pair lset.\nRequire Import monoid boolean prop sups bmx.\nSet Implicit Arguments.\nUnset Printing Implicit Defensive.\n\n(** * DFA and associated language *)\n\n(** A DFA is given by its number of states, a deterministic transition\n   function, an acceptance condition, and a finite subset of the\n   alphabet.\n\n   States are represented by ordinals of the appropriate size.  \n\n   Making the finite subset of the alphabet explicit avoids us to use\n   ordinals for the alphabet. *)\n\nRecord t := mk {\n  n: nat;\n  u: ord n;\n  M: ord n -> positive -> ord n;\n  v: ord n -> bool;\n  vars: list positive\n}.\nNotation \"x ^u\" := (u x) (at level 2, left associativity, format \"x ^u\").\nNotation \"x ^M\" := (M x) (at level 2, left associativity, format \"x ^M\").\nNotation \"x ^v\" := (v x) (at level 2, left associativity, format \"x ^v\").\n\n(** changing the initial state *)\nDefinition reroot A i := mk i A^M A^v (vars A).\n\nLemma reroot_id A: A = reroot A (A^u).\nProof. destruct A; reflexivity. Qed.\n\n(** language of a DFA [A], starting from state [i] *)\nFixpoint lang A i w := \n  match w with \n    | nil => is_true (A^v i)\n    | cons a w => In a (vars A) /\\ lang A (A^M i a) w\n  end.\n\n\n(** * Reduction of DFA language inclusion to DFA language emptiness  *)\n\nSection diff.\n\nVariables A B: t.\n\n(** automaton for [A\\B] *)\nDefinition diff := mk \n  (pair.mk (u A) (u B))\n  (fun p a => pair.mk (M A (pair.pi1 p) a) (M B (pair.pi2 p) a))\n  (fun p => v A (pair.pi1 p) \\cap ! v B (pair.pi2 p))\n  (vars A).\n\n(** specification of its language *)\nLemma diff_spec: vars A <== vars B -> \n  forall i j, lang A i <== lang B j <-> lang diff (pair.mk i j) <== bot. \nProof.\n  intro H. \n  cut (forall w i j, lang A i w <== lang B j w <-> ~ lang diff (pair.mk i j) w).\n   intros G i j. split. intros Hij w Hw. apply G in Hw as []. apply Hij.\n   intros Hij w. apply G. intro Hw. elim (Hij _ Hw).  \n  induction w; intros i j; simpl lang; rewrite pair.pi1mk, pair.pi2mk. \n   case (v A i); case (v B j); firstorder discriminate.\n    split. intros Hij [HaB Hw]. apply IHw in Hw as []. intro Aw. apply Hij. now split.\n    intros Hw [Ha Aw]. split. apply H, Ha. eapply IHw. 2: eassumption. tauto. \nQed.\n\nEnd diff.\n\n\n(** * Decidability of DFA language emptiness \n\n   We proceed as follows: \n   1. we forget all transition labels to get a directed graph whose\n      nodes have an accepting status.\n   2. we compute the reflexive and transitive closure of this graph\n   3. we deduce the set of all states reachable from the initial state.\n   4. the DFA is empty iff this set does not contain any accepting\n      states. \n\n   All these computations are straightforward, except for 2, for which\n   we exploit Kleene star on Boolean matrices.\n\n   The resulting algorithm is not efficient at all. We don't care\n   because this is not the one we execute in the end: this one is just\n   used to establish KA completeness. *)\n\nSection empty_dec.\n\nVariables A: t.\n\n(** erased transition graph, represented as a Boolean matrix *)\nDefinition step: bmx (n A) (n A) := fun i j => \\sup_(a\\in vars A) eqb_ord (M A i a) j.\n\n(** reflexive transitive closure of this graph *)\nDefinition steps := (@str bmx _ step). \n\nVariable i: ord (n A).\n\n(** basic properties of this closed graph *)\nLemma steps_refl: steps i i.\nProof. apply bmx_str_clot. constructor. Qed.\n\nLemma steps_snoc: forall j a, steps i j -> In a (vars A) -> steps i (M A j a).\nProof. \n  setoid_rewrite bmx_str_clot. intros. eapply clot_snoc. eassumption. \n  setoid_rewrite is_true_sup. eexists. split. eassumption. apply eqb_refl. \nQed.\n\n(** state reached from [i] by following a word [w] in the DFA *)\nFixpoint Ms i w := match w with nil => i | cons a w => Ms (M A i a) w end.\n\n(** each unlabelled path in the erased graph corresponds to a labelled\n   path (word) in the DFA *)\nLemma steps_least: forall j, steps i j -> exists w, w <== vars A /\\ j = Ms i w. \nProof.\n  intros j H. apply bmx_str_clot in H. induction H as [i|i j k Hij _ [w [Hw ->]]]. \n   exists nil. split. lattice. reflexivity.\n  setoid_rewrite is_true_sup in Hij. destruct Hij as [a [Ha Hij]]. \n  exists (a::w). split. intros b [<-|Hb]. assumption. now apply Hw. \n  revert Hij. case eqb_ord_spec. 2: discriminate. now intros <-. \nQed.\n\n(** can we reach an accepting state from [i] *)\nDefinition empty := \\inf_(j<_) (steps i j <<< !v A j).\n\n(* TODO: les deux lemmes suivants sont certainement simplifiables en\n   prouvant directement l'équivalence *)\n\n(** if not, all states reachable from [i] map to the empty language *)\nLemma empty_lang1 j: steps i j -> empty -> lang A j <== bot.\nProof.\n  intros Hj He. setoid_rewrite is_true_inf in He. setoid_rewrite le_bool_spec in He. \n  pose proof (fun i => He i (ordinal.in_seq _)) as H. clear He. \n  intro w. revert j Hj. induction w as [|a w IH]; simpl lang; intros j Hj. \n  apply (H j), negb_spec in Hj. rewrite Hj. discriminate. \n  intros [Ha Hj']. apply IH in Hj' as []. now apply steps_snoc.\nQed.\n\n(** conversely, if [i] maps to them empty language, then there is no\n   reachable accepting state *)\nLemma empty_lang2: lang A i <== bot -> empty.\nProof.\n  intro H. setoid_rewrite is_true_inf. intros j _. \n  rewrite le_bool_spec. intro Hj. apply steps_least in Hj as [w [Hw ->]].\n  generalize i (H w) Hw. clear. induction w; intros i Hi Hw. \n   simpl in *. destruct (v A i). now elim Hi. reflexivity. \n   apply IHw. intro H. elim Hi. split. apply Hw. now left. assumption. \n   intros ? ?. apply Hw. now right. \nQed.\n\n(** decidability of language emptiness follows *)\nTheorem empty_dec: {lang A i <== bot} + {~ (lang A i <== bot)}.\nProof.\n  case_eq empty; [left|right]. \n   apply (empty_lang1 _ steps_refl H). \n  intro E. apply empty_lang2 in E. rewrite H in E. discriminate. \nQed.\n\nEnd empty_dec.\n\n\n(** * Decidability of DFA language inclusion *)\n\nCorollary lang_incl_dec A B: vars A <== vars B -> \n  forall i j, {lang A i <== lang B j} + {~(lang A i <== lang B j)}.\nProof. intros. eapply sumbool_iff. symmetry. now apply diff_spec. apply empty_dec. Qed.\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/dfa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.656739387620885}}
{"text": "Require Import List PeanoNat Omega Recdef.\nSet Implicit Arguments.\n\nRecord CommSemigroup A := mkCSG\n  { CSelem : A;\n    CSplus : A -> A -> A;\n    CSplus_assoc : forall x y z : A, CSplus (CSplus x y) z = CSplus x (CSplus y z);\n    CSplus_comm : forall x y : A, CSplus x y = CSplus y x }.\n\nSection CommSemigroup.\n\n  Variable A : Type.\n  Variable A_CSG : CommSemigroup A.\n  Infix \"+!\" := A_CSG.(CSplus) (at level 50, left associativity).\n\n  Inductive Exp :=\n  | ExpVar : nat -> Exp\n  | ExpPlus : Exp -> Exp -> Exp.\n\n  Definition NF := list nat.\n\n  Fixpoint ins n (nf : NF) : NF :=\n    match nf with\n    | nil => n :: nil\n    | m::nf' =>\n      if le_dec n m\n        then n :: m :: nf'\n        else m :: ins n nf'\n    end.\n\n  Fixpoint exp2nf' (ex : Exp)(nf : NF) : NF :=\n    match ex with\n    | ExpVar n => ins n nf\n    | ExpPlus ey ez => exp2nf' ez (exp2nf' ey nf)\n    end.\n  Definition exp2nf ex := exp2nf' ex nil.\n\n  Fixpoint getKey (val : nat)(table : list (A * nat)) : A :=\n    match table with\n    | nil => A_CSG.(CSelem)\n    | (key,val')::table' =>\n      if Nat.eq_dec val val'\n        then key\n        else getKey val table'\n    end.\n\n  Fixpoint exp2A (ex : Exp)(table : list (A * nat)) : A :=\n    match ex with\n    | ExpVar n => getKey n table\n    | ExpPlus ey ez => exp2A ey table +! exp2A ez table\n    end.\n\n  Fixpoint nf2A nf table :=\n    match nf with\n    | nil => A_CSG.(CSelem)\n    | n::nil => getKey n table\n    | n::nf' => getKey n table +! nf2A nf' table\n    end.\n\n  Fixpoint addnf a nf table :=\n    match nf with\n    | nil => a\n    | n::nf' => getKey n table +! addnf a nf' table\n    end.\n\n  Lemma addnf_plus : forall table a b nf,\n    addnf (a +! b) nf table = a +! addnf b nf table.\n  Proof with simpl in *.\n    induction nf; [auto|]...\n    rewrite IHnf. repeat rewrite <- A_CSG.(CSplus_assoc).\n    rewrite (A_CSG.(CSplus_comm) a). reflexivity.\n  Qed.\n\n  Lemma addnf_comm : forall table a b nf,\n    a +! addnf b nf table = b +! addnf a nf table.\n  Proof with simpl in *.\n    intros. rewrite <- addnf_plus. rewrite A_CSG.(CSplus_comm). rewrite addnf_plus. auto.\n  Qed.\n\n  Lemma addnf_nf2A : forall table n nf,\n    addnf (getKey n table) nf table = nf2A (n::nf) table.\n  Proof with simpl in *.\n    induction nf; [auto|]... rewrite IHnf.\n    destruct nf.\n    - apply A_CSG.(CSplus_comm).\n    - repeat rewrite <- A_CSG.(CSplus_assoc). f_equal.\n      apply A_CSG.(CSplus_comm).\n  Qed.\n\n  Lemma addnf_left : forall table a n nf,\n    addnf a (n::nf) table = a +! nf2A (n::nf) table.\n  Proof with simpl in*.\n    intros.\n    rewrite <- (addnf_nf2A table n nf).\n    induction nf; simpl in *; [auto|].\n    - apply (A_CSG.(CSplus_comm)).\n    - rewrite (A_CSG.(CSplus_comm) (getKey a0 table)).\n      repeat rewrite <- A_CSG.(CSplus_assoc). rewrite IHnf.\n      repeat rewrite A_CSG.(CSplus_assoc). f_equal. apply A_CSG.(CSplus_comm).\n  Qed.\n\n  Lemma nf2A_ins : forall table n nf,\n    nf2A (ins n nf) table = nf2A (n::nf) table.\n  Proof with simpl in *.\n    induction n; induction nf; [auto..|]...\n    destruct (le_dec (S n) a)...\n     - auto.\n     - f_equal. rewrite IHnf.\n      destruct nf...\n       + apply A_CSG.(CSplus_comm).\n       + destruct (le_dec (S n) n1); simpl;\n        repeat rewrite <- A_CSG.(CSplus_assoc); f_equal; apply A_CSG.(CSplus_comm).\n  Qed.\n\n  Function list_ind2' X (P : list X -> Prop) (H : P nil) (H0 : forall x, P (x :: nil))\n    (H1 : forall x y l, P (y :: l) -> P (x :: y :: l)) l {measure length l} : P l :=\n    match l return P l with\n    | nil => H\n    | x::nil => H0 x\n    | x::y::l' => H1 x y l' (list_ind2' P H H0 H1 (y :: l'))\n    end.\n  Proof.\n    intros. subst. auto.\n  Qed.\n\n  Definition list_ind2 : forall X (P : list X -> Prop),\n    P nil ->\n    (forall x, P (x :: nil)) ->\n    (forall x y l, P (y:: l) -> (P (x :: y :: l))) ->\n    forall l, P l := fun X P H H0 H1 l => list_ind2' P H H0 H1 l.\n\n  Lemma exp2nf'_cons : forall ex nf,\n    exp2nf' ex nf <> nil.\n  Proof with simpl in *.\n    induction ex; induction nf...\n    - discriminate.\n    - destruct (le_dec n a); discriminate.\n    - intro. firstorder.\n    - intro. firstorder.\n  Qed.\n\n  Lemma nf_inj : forall ex nf table,\n    addnf (exp2A ex table) nf table = nf2A (exp2nf' ex nf) table.\n  Proof with simpl in *.\n    induction ex.\n    - apply (list_ind2 (fun nf => forall table,\n    addnf (exp2A (ExpVar n) table) nf table = nf2A (exp2nf' (ExpVar n) nf) table)); intros...\n      + auto.\n      + destruct (le_dec n x); simpl; [apply A_CSG.(CSplus_comm)|auto].\n      + specialize (H table).\n        destruct (le_dec n x); destruct (le_dec n y)...\n        * repeat rewrite <- A_CSG.(CSplus_assoc).\n          rewrite (A_CSG.(CSplus_comm) (getKey n table)).\n          repeat rewrite A_CSG.(CSplus_assoc). f_equal. auto.\n        * rewrite H. rewrite nf2A_ins...\n          destruct l...\n          { rewrite (A_CSG.(CSplus_comm) (getKey y table)).\n            repeat rewrite <- A_CSG.(CSplus_assoc).\n            f_equal. apply A_CSG.(CSplus_comm). }\n          { destruct (le_dec n n1); repeat rewrite <- A_CSG.(CSplus_assoc); f_equal;\n            rewrite (A_CSG.(CSplus_comm) (getKey n table)); repeat rewrite A_CSG.(CSplus_assoc); f_equal; apply A_CSG.(CSplus_comm). }\n        * f_equal. auto.\n        * rewrite H. auto.\n    - apply (list_ind2 (fun nf => forall (table : list (A * nat)),\n        addnf (exp2A (ExpPlus ex1 ex2) table) nf table =\n        nf2A (exp2nf' (ExpPlus ex1 ex2) nf) table)); intros...\n      + rewrite <- IHex2.\n        destruct (exp2nf' ex1 nil) eqn:?.\n        { apply exp2nf'_cons in Heqn. contradiction. }\n        rewrite addnf_left. rewrite A_CSG.(CSplus_comm). f_equal.\n        rewrite <- Heqn. rewrite <- IHex1... auto.\n      + rewrite <- IHex2.\n        destruct (exp2nf' ex1 (x :: nil)) eqn:?.\n        { apply exp2nf'_cons in Heqn. contradiction. }\n        rewrite addnf_left. rewrite <- Heqn. rewrite <- IHex1...\n        rewrite (A_CSG.(CSplus_comm) (exp2A ex1 table)). repeat rewrite <- A_CSG.(CSplus_assoc).\n        f_equal. apply A_CSG.(CSplus_comm).\n      + rewrite H. rewrite <- (IHex2 (exp2nf' ex1 (x :: y :: l))).\n        destruct (exp2nf' ex1 (x :: y :: l)) eqn:?.\n        { apply exp2nf'_cons in Heqn. contradiction. }\n        rewrite addnf_left. rewrite <- Heqn. rewrite <- IHex1.\n        rewrite addnf_left. simpl. rewrite <- A_CSG.(CSplus_assoc). rewrite <- A_CSG.(CSplus_assoc).\n        rewrite (A_CSG.(CSplus_comm) _ (getKey x table)). rewrite A_CSG.(CSplus_assoc). f_equal.\n        rewrite <- IHex2.\n        destruct (exp2nf' ex1 (y :: l)) eqn:?.\n        { apply exp2nf'_cons in Heqn1. contradiction. }\n        rewrite addnf_left. rewrite <- Heqn1. rewrite A_CSG.(CSplus_assoc). f_equal.\n        rewrite <- IHex1. rewrite addnf_left. auto.\n  Qed.\n\n  Lemma uniq' : forall table ex ey nf,\n    exp2nf' ex nf = exp2nf' ey nf ->\n    addnf (exp2A ex table) nf table = addnf (exp2A ey table) nf table.\n  Proof with simpl in *.\n    intros. rewrite nf_inj. rewrite nf_inj. rewrite H. auto.\n  Qed.\n\n  Lemma uniq : forall ex ey table,\n    exp2nf ex = exp2nf ey -> exp2A ex table = exp2A ey table.\n  Proof with simpl in *.\n    unfold exp2nf. intros. apply (uniq' table) in H... auto.\n  Qed.\n\nEnd CommSemigroup.\n\nLtac lookup key table :=\n  match table with\n  | nil => constr:(@None nat)\n  | ?t :: ?table' =>\n    match t with\n    | (key, ?n) => constr:(Some n)\n    | _ => lookup key table'\n    end\n  end.\n\nLtac get_CSelem csg := eval simpl in (CSelem csg).\nLtac get_CStype csg :=\n  let a0 := get_CSelem csg in\n  type of a0.\nLtac get_CSplus csg := eval simpl in (CSplus csg).\nLtac get_CSplus_assoc csg := eval simpl in (CSplus_assoc csg).\nLtac get_CSplus_comm csg := eval simpl in (CSplus_comm csg).\n\nLtac gen_table' csg x n table :=\n  let opt := lookup x table in\n  let csplus := get_CSplus csg in\n  match opt with\n  | None =>\n    match x with\n    | csplus ?y ?z =>\n      let res := gen_table' csg y n table in\n      match res with\n      | (?n', ?table') =>\n        gen_table' csg z n' table'\n      end\n    | _ => constr:(S n, (x, n)::table)\n    end\n  | Some ?n' => constr:(n, table)\n  end.\n\nLtac gen_table csg x :=\n  let A := get_CStype csg in\n  gen_table' csg x O (@nil (A * nat)).\n\nLtac to_exp csg table x :=\n  let csplus := get_CSplus csg in\n  match x with\n  | csplus ?y ?z =>\n    let ey := to_exp csg table y in\n    let ez := to_exp csg table z in\n    constr:(ExpPlus ey ez)\n  | _ =>\n    let ex_opt := lookup x table in\n    match ex_opt with\n    | Some ?ex => constr:(ExpVar ex)\n    end\n  end.\n\nLtac semigroup csg :=\n  match goal with\n  | |- ?x = ?y =>\n    let t := gen_table csg x in\n    match t with\n    | (_, ?table) =>\n      let ex := to_exp csg table x in\n      let ey := to_exp csg table y in\n      enough (exp2A csg ex table = exp2A csg ey table) by auto;\n      apply uniq;\n      unfold exp2nf;\n      auto\n    end\n  end.", "meta": {"author": "erutuf", "repo": "nfreasoning", "sha": "a7f8d4e19c35997c1ed2fe11ac51872acb4c66ea", "save_path": "github-repos/coq/erutuf-nfreasoning", "path": "github-repos/coq/erutuf-nfreasoning/nfreasoning-a7f8d4e19c35997c1ed2fe11ac51872acb4c66ea/Semigroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6567393816105226}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq div choice fintype.\nRequire Import finfun bigop prime binomial ssralg finset fingroup finalg.\nRequire Import perm zmodp.\n\n(******************************************************************************)\n(* Basic concrete linear algebra : definition of type for matrices, and all   *)\n(* basic matrix operations including determinant, trace and support for block *)\n(* decomposition. Matrices are represented by a row-major list of their       *)\n(* coefficients but this implementation is hidden by three levels of wrappers *)\n(* (Matrix/Finfun/Tuple) so the matrix type should be treated as abstract and *)\n(* handled using only the operations described below:                         *)\n(*   'M[R]_(m, n) == the type of m rows by n columns matrices with            *)\n(*   'M_(m, n)       coefficients in R; the [R] is optional and is usually    *)\n(*                   omitted.                                                 *)\n(*  'M[R]_n, 'M_n == the type of n x n square matrices.                       *)\n(* 'rV[R]_n, 'rV_n == the type of 1 x n row vectors.                          *)\n(* 'cV[R]_n, 'cV_n == the type of n x 1 column vectors.                       *)\n(*  \\matrix_(i < m, j < n) Expr(i, j) ==                                      *)\n(*                   the m x n matrix with general coefficient Expr(i, j),    *)\n(*                   with i : 'I_m and j : 'I_n. the < m bound can be omitted *)\n(*                   if it is equal to n, though usually both bounds are      *)\n(*                   omitted as they can be inferred from the context.        *)\n(*  \\row_(j < n) Expr(j), \\col_(i < m) Expr(i)                                *)\n(*                   the row / column vectors with general term Expr; the     *)\n(*                   parentheses can be omitted along with the bound.         *)\n(* \\matrix_(i < m) RowExpr(i) ==                                              *)\n(*                   the m x n matrix with row i given by RowExpr(i) : 'rV_n. *)\n(*          A i j == the coefficient of matrix A : 'M_(m, n) in column j of   *)\n(*                   row i, where i : 'I_m, and j : 'I_n (via the coercion    *)\n(*                   fun_of_matrix : matrix >-> Funclass).                    *)\n(*     const_mx a == the constant matrix whose entries are all a (dimensions  *)\n(*                   should be determined by context).                        *)\n(*     map_mx f A == the pointwise image of A by f, i.e., the matrix Af       *)\n(*                   congruent to A with Af i j = f (A i j) for all i and j.  *)\n(*            A^T == the matrix transpose of A.                               *)\n(*        row i A == the i'th row of A (this is a row vector).                *)\n(*        col j A == the j'th column of A (a column vector).                  *)\n(*       row' i A == A with the i'th row spliced out.                         *)\n(*       col' i A == A with the j'th column spliced out.                      *)\n(*   xrow i1 i2 A == A with rows i1 and i2 interchanged.                      *)\n(*   xcol j1 j2 A == A with columns j1 and j2 interchanged.                   *)\n(*   row_perm s A == A : 'M_(m, n) with rows permuted by s : 'S_m.            *)\n(*   col_perm s A == A : 'M_(m, n) with columns permuted by s : 'S_n.         *)\n(*   row_mx Al Ar == the row block matrix <Al Ar> obtained by contatenating   *)\n(*                   two matrices Al and Ar of the same height.               *)\n(*   col_mx Au Ad == the column block matrix / Au \\ (Au and Ad must have the  *)\n(*                   same width).            \\ Ad /                           *)\n(* block_mx Aul Aur Adl Adr == the block matrix / Aul Aur \\                   *)\n(*                                              \\ Adl Adr /                   *)\n(*   [l|r]submx A == the left/right submatrices of a row block matrix A.      *)\n(*                   Note that the type of A, 'M_(m, n1 + n2) indicates how A *)\n(*                   should be decomposed.                                    *)\n(*   [u|d]submx A == the up/down submatrices of a column block matrix A.      *)\n(* [u|d][l|r]submx A == the upper left, etc submatrices of a block matrix A.  *)\n(* castmx eq_mn A == A : 'M_(m, n) cast to 'M_(m', n') using the equation     *)\n(*                   pair eq_mn : (m = m') * (n = n'). This is the usual      *)\n(*                   workaround for the syntactic limitations of dependent    *)\n(*                   types in Coq, and can be used to introduce a block       *)\n(*                   decomposition. It simplifies to A when eq_mn is the      *)\n(*                   pair (erefl m, erefl n) (using rewrite /castmx /=).      *)\n(* conform_mx B A == A if A and B have the same dimensions, else B.           *)\n(*        mxvec A == a row vector of width m * n holding all the entries of   *)\n(*                   the m x n matrix A.                                      *)\n(* mxvec_index i j == the index of A i j in mxvec A.                          *)\n(*       vec_mx v == the inverse of mxvec, reshaping a vector of width m * n  *)\n(*                   back into into an m x n rectangular matrix.              *)\n(* In 'M[R]_(m, n), R can be any type, but 'M[R]_(m, n) inherits the eqType,  *)\n(* choiceType, countType, finType, zmodType structures of R; 'M[R]_(m, n)     *)\n(* also has a natural lmodType R structure when R has a ringType structure.   *)\n(* Because the type of matrices specifies their dimension, only non-trivial   *)\n(* square matrices (of type 'M[R]_n.+1) can inherit the ring structure of R;  *)\n(* indeed they then have an algebra structure (lalgType R, or algType R if R  *)\n(* is a comRingType, or even unitAlgType if R is a comUnitRingType).          *)\n(*   We thus provide separate syntax for the general matrix multiplication,   *)\n(* and other operations for matrices over a ringType R:                       *)\n(*         A *m B == the matrix product of A and B; the width of A must be    *)\n(*                   equal to the height of B.                                *)\n(*           a%:M == the scalar matrix with a's on the main diagonal; in      *)\n(*                   particular 1%:M denotes the identity matrix, and is is   *)\n(*                   equal to 1%R when n is of the form n'.+1 (e.g., n >= 1). *)\n(* is_scalar_mx A <=> A is a scalar matrix (A = a%:M for some A).             *)\n(*      diag_mx d == the diagonal matrix whose main diagonal is d : 'rV_n.    *)\n(*   delta_mx i j == the matrix with a 1 in row i, column j and 0 elsewhere.  *)\n(*       pid_mx r == the partial identity matrix with 1s only on the r first  *)\n(*                   coefficients of the main diagonal; the dimensions of     *)\n(*                   pid_mx r are determined by the context, and pid_mx r can *)\n(*                   be rectangular.                                          *)\n(*     copid_mx r == the complement to 1%:M of pid_mx r: a square diagonal    *)\n(*                   matrix with 1s on all but the first r coefficients on    *)\n(*                   its main diagonal.                                       *)\n(*      perm_mx s == the n x n permutation matrix for s : 'S_n.               *)\n(* tperm_mx i1 i2 == the permutation matrix that exchanges i1 i2 : 'I_n.      *)\n(*   is_perm_mx A == A is a permutation matrix.                               *)\n(*     lift0_mx A == the 1 + n square matrix block_mx 1 0 0 A when A : 'M_n.  *)\n(*          \\tr A == the trace of a square matrix A.                          *)\n(*         \\det A == the determinant of A, using the Leibnitz formula.        *)\n(* cofactor i j A == the i, j cofactor of A (the signed i, j minor of A),     *)\n(*         \\adj A == the adjugate matrix of A (\\adj A i j = cofactor j i A).  *)\n(*   A \\in unitmx == A is invertible (R must be a comUnitRingType).           *)\n(*        invmx A == the inverse matrix of A if A \\in unitmx A, otherwise A.  *)\n(* The following operations provide a correspondance between linear functions *)\n(* and matrices:                                                              *)\n(*     lin1_mx f == the m x n matrix that emulates via right product          *)\n(*                  a (linear) function f : 'rV_m -> 'rV_n on ROW VECTORS     *)\n(*      lin_mx f == the (m1 * n1) x (m2 * n2) matrix that emulates, via the   *)\n(*                  right multiplication on the mxvec encodings, a linear     *)\n(*                  function f : 'M_(m1, n1) -> 'M_(m2, n2)                   *)\n(* lin_mul_row u := lin1_mx (mulmx u \\o vec_mx) (applies a row-encoded        *)\n(*                  function to the row-vector u).                            *)\n(*       mulmx A == partially applied matrix multiplication (mulmx A B is     *)\n(*                  displayed as A *m B), with, for A : 'M_(m, n), a          *)\n(*                  canonical {linear 'M_(n, p) -> 'M(m, p}} structure.       *)\n(*      mulmxr A == self-simplifying right-hand matrix multiplication, i.e.,  *)\n(*                  mulmxr A B simplifies to B *m A, with, for A : 'M_(n, p), *)\n(*                  a canonical {linear 'M_(m, n) -> 'M(m, p}} structure.     *)\n(*   lin_mulmx A := lin_mx (mulmx A).                                         *)\n(*  lin_mulmxr A := lin_mx (mulmxr A).                                        *)\n(* We also extend any finType structure of R to 'M[R]_(m, n), and define:     *)\n(*     {'GL_n[R]} == the finGroupType of units of 'M[R]_n.-1.+1.              *)\n(*      'GL_n[R]  == the general linear group of all matrices in {'GL_n(R)}.  *)\n(*      'GL_n(p)  == 'GL_n['F_p], the general linear group of a prime field.  *)\n(*       GLval u  == the coercion of u : {'GL_n(R)} to a matrix.              *)\n(*   In addition to the lemmas relevant to these definitions, this file also  *)\n(* proves several classic results, including :                                *)\n(* - The determinant is a multilinear alternate form.                         *)\n(* - The Laplace determinant expansion formulas: expand_det_[row|col].        *)\n(* - The Cramer rule : mul_mx_adj & mul_adj_mx.                               *)\n(* Finally, as an example of the use of block products, we program and prove  *)\n(* the correctness of a classical linear algebra algorithm:                   *)\n(*    cormenLUP A == the triangular decomposition (L, U, P) of a nontrivial   *)\n(*                   square matrix A into a lower triagular matrix L with 1s  *)\n(*                   on the main diagonal, an upper matrix U, and a           *)\n(*                   permutation matrix P, such that P * A = L * U.           *)\n(* This is example only; we use a different, more precise algorithm to        *)\n(* develop the theory of matrix ranks and row spaces in mxalgebra.v           *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GroupScope.\nImport GRing.Theory.\nOpen Local Scope ring_scope.\n\nReserved Notation \"''M_' n\"     (at level 8, n at level 2, format \"''M_' n\").\nReserved Notation \"''rV_' n\"    (at level 8, n at level 2, format \"''rV_' n\").\nReserved Notation \"''cV_' n\"    (at level 8, n at level 2, format \"''cV_' n\").\nReserved Notation \"''M_' ( n )\" (at level 8, only parsing).\nReserved Notation \"''M_' ( m , n )\" (at level 8, format \"''M_' ( m ,  n )\").\nReserved Notation \"''M[' R ]_ n\"    (at level 8, n at level 2, only parsing).\nReserved Notation \"''rV[' R ]_ n\"   (at level 8, n at level 2, only parsing).\nReserved Notation \"''cV[' R ]_ n\"   (at level 8, n at level 2, only parsing).\nReserved Notation \"''M[' R ]_ ( n )\"     (at level 8, only parsing).\nReserved Notation \"''M[' R ]_ ( m , n )\" (at level 8, only parsing).\n\nReserved Notation \"\\matrix_ i E\" \n  (at level 36, E at level 36, i at level 2,\n   format \"\\matrix_ i  E\").\nReserved Notation \"\\matrix_ ( i < n ) E\"\n  (at level 36, E at level 36, i, n at level 50, only parsing).\nReserved Notation \"\\matrix_ ( i , j ) E\"\n  (at level 36, E at level 36, i, j at level 50,\n   format \"\\matrix_ ( i ,  j )  E\").\nReserved Notation \"\\matrix[ k ]_ ( i , j ) E\"\n  (at level 36, E at level 36, i, j at level 50,\n   format \"\\matrix[ k ]_ ( i ,  j )  E\").\nReserved Notation \"\\matrix_ ( i < m , j < n ) E\"\n  (at level 36, E at level 36, i, m, j, n at level 50, only parsing).\nReserved Notation \"\\matrix_ ( i , j < n ) E\"\n  (at level 36, E at level 36, i, j, n at level 50, only parsing).\nReserved Notation \"\\row_ j E\"\n  (at level 36, E at level 36, j at level 2,\n   format \"\\row_ j  E\").\nReserved Notation \"\\row_ ( j < n ) E\"\n  (at level 36, E at level 36, j, n at level 50, only parsing).\nReserved Notation \"\\col_ j E\"\n  (at level 36, E at level 36, j at level 2,\n   format \"\\col_ j  E\").\nReserved Notation \"\\col_ ( j < n ) E\"\n  (at level 36, E at level 36, j, n at level 50, only parsing).\n\nReserved Notation \"x %:M\"   (at level 8, format \"x %:M\").\nReserved Notation \"A *m B\" (at level 40, left associativity, format \"A  *m  B\").\nReserved Notation \"A ^T\"    (at level 8, format \"A ^T\").\nReserved Notation \"\\tr A\"   (at level 10, A at level 8, format \"\\tr  A\").\nReserved Notation \"\\det A\"  (at level 10, A at level 8, format \"\\det  A\").\nReserved Notation \"\\adj A\"  (at level 10, A at level 8, format \"\\adj  A\").\n\nNotation Local simp := (Monoid.Theory.simpm, oppr0).\n\n(*****************************************************************************)\n(****************************Type Definition**********************************)\n(*****************************************************************************)\n\nSection MatrixDef.\n\nVariable R : Type.\nVariables m n : nat.\n\n(* Basic linear algebra (matrices).                                       *)\n(* We use dependent types (ordinals) for the indices so that ranges are   *)\n(* mostly inferred automatically                                          *)\n\nInductive matrix : predArgType := Matrix of {ffun 'I_m * 'I_n -> R}.\n\nDefinition mx_val A := let: Matrix g := A in g.\n\nCanonical matrix_subType := Eval hnf in [newType for mx_val].\n\nFact matrix_key : unit. Proof. by []. Qed.\nDefinition matrix_of_fun_def F := Matrix [ffun ij => F ij.1 ij.2].\nDefinition matrix_of_fun k := locked_with k matrix_of_fun_def.\nCanonical matrix_unlockable k := [unlockable fun matrix_of_fun k].\n\nDefinition fun_of_matrix A (i : 'I_m) (j : 'I_n) := mx_val A (i, j).\n\nCoercion fun_of_matrix : matrix >-> Funclass.\n\nLemma mxE k F : matrix_of_fun k F =2 F.\nProof. by move=> i j; rewrite unlock /fun_of_matrix /= ffunE. Qed.\n\nLemma matrixP (A B : matrix) : A =2 B <-> A = B.\nProof.\nrewrite /fun_of_matrix; split=> [/= eqAB | -> //].\nby apply/val_inj/ffunP=> [[i j]]; exact: eqAB.\nQed.\n\nEnd MatrixDef.\n\nBind Scope ring_scope with matrix.\n\nNotation \"''M[' R ]_ ( m , n )\" := (matrix R m n) (only parsing): type_scope.\nNotation \"''rV[' R ]_ n\" := 'M[R]_(1, n) (only parsing) : type_scope.\nNotation \"''cV[' R ]_ n\" := 'M[R]_(n, 1) (only parsing) : type_scope.\nNotation \"''M[' R ]_ n\" := 'M[R]_(n, n) (only parsing) : type_scope.\nNotation \"''M[' R ]_ ( n )\" := 'M[R]_n (only parsing) : type_scope.\nNotation \"''M_' ( m , n )\" := 'M[_]_(m, n) : type_scope.\nNotation \"''rV_' n\" := 'M_(1, n) : type_scope.\nNotation \"''cV_' n\" := 'M_(n, 1) : type_scope.\nNotation \"''M_' n\" := 'M_(n, n) : type_scope.\nNotation \"''M_' ( n )\" := 'M_n (only parsing) : type_scope.\n\nNotation \"\\matrix[ k ]_ ( i , j ) E\" := (matrix_of_fun k (fun i j => E))\n  (at level 36, E at level 36, i, j at level 50): ring_scope.\n\nNotation \"\\matrix_ ( i < m , j < n ) E\" :=\n  (@matrix_of_fun _ m n matrix_key (fun i j => E)) (only parsing) : ring_scope.\n\nNotation \"\\matrix_ ( i , j < n ) E\" :=\n  (\\matrix_(i < n, j < n) E) (only parsing) : ring_scope.\n\nNotation \"\\matrix_ ( i , j ) E\" := (\\matrix_(i < _, j < _) E) : ring_scope.\n\nNotation \"\\matrix_ ( i < m ) E\" :=\n  (\\matrix_(i < m, j < _) @fun_of_matrix _ 1 _ E 0 j)\n  (only parsing) : ring_scope.\nNotation \"\\matrix_ i E\" := (\\matrix_(i < _) E) : ring_scope.\n\nNotation \"\\col_ ( i < n ) E\" := (@matrix_of_fun _ n 1 matrix_key (fun i _ => E))\n  (only parsing) : ring_scope.\nNotation \"\\col_ i E\" := (\\col_(i < _) E) : ring_scope.\n\nNotation \"\\row_ ( j < n ) E\" := (@matrix_of_fun _ 1 n matrix_key (fun _ j => E))\n  (only parsing) : ring_scope.\nNotation \"\\row_ j E\" := (\\row_(j < _) E) : ring_scope.\n\nDefinition matrix_eqMixin (R : eqType) m n :=\n  Eval hnf in [eqMixin of 'M[R]_(m, n) by <:].\nCanonical matrix_eqType (R : eqType) m n:=\n  Eval hnf in EqType 'M[R]_(m, n) (matrix_eqMixin R m n).\nDefinition matrix_choiceMixin (R : choiceType) m n :=\n  [choiceMixin of 'M[R]_(m, n) by <:].\nCanonical matrix_choiceType (R : choiceType) m n :=\n  Eval hnf in ChoiceType 'M[R]_(m, n) (matrix_choiceMixin R m n).\nDefinition matrix_countMixin (R : countType) m n :=\n  [countMixin of 'M[R]_(m, n) by <:].\nCanonical matrix_countType (R : countType) m n :=\n  Eval hnf in CountType 'M[R]_(m, n) (matrix_countMixin R m n).\nCanonical matrix_subCountType (R : countType) m n :=\n  Eval hnf in [subCountType of 'M[R]_(m, n)].\nDefinition matrix_finMixin (R : finType) m n :=\n  [finMixin of 'M[R]_(m, n) by <:].\nCanonical matrix_finType (R : finType) m n :=\n  Eval hnf in FinType 'M[R]_(m, n) (matrix_finMixin R m n).\nCanonical matrix_subFinType (R : finType) m n :=\n  Eval hnf in [subFinType of 'M[R]_(m, n)].\n\nLemma card_matrix (F : finType) m n : (#|{: 'M[F]_(m, n)}| = #|F| ^ (m * n))%N.\nProof. by rewrite card_sub card_ffun card_prod !card_ord. Qed.\n\n(*****************************************************************************)\n(****** Matrix structural operations (transpose, permutation, blocks) ********)\n(*****************************************************************************)\n\nSection MatrixStructural.\n\nVariable R : Type.\n\n(* Constant matrix *)\nFact const_mx_key : unit. Proof. by []. Qed.\nDefinition const_mx m n a : 'M[R]_(m, n) := \\matrix[const_mx_key]_(i, j) a.\nImplicit Arguments const_mx [[m] [n]].\n\nSection FixedDim.\n(* Definitions and properties for which we can work with fixed dimensions. *)\n\nVariables m n : nat.\nImplicit Type A : 'M[R]_(m, n).\n\n(* Reshape a matrix, to accomodate the block functions for instance. *)\nDefinition castmx m' n' (eq_mn : (m = m') * (n = n')) A : 'M_(m', n') :=\n  let: erefl in _ = m' := eq_mn.1 return 'M_(m', n') in\n  let: erefl in _ = n' := eq_mn.2 return 'M_(m, n') in A.\n\nDefinition conform_mx m' n' B A :=\n  match m =P m', n =P n' with\n  | ReflectT eq_m, ReflectT eq_n => castmx (eq_m, eq_n) A\n  | _, _ => B\n  end.\n\n(* Transpose a matrix *)\nFact trmx_key : unit. Proof. by []. Qed.\nDefinition trmx A := \\matrix[trmx_key]_(i, j) A j i.\n\n(* Permute a matrix vertically (rows) or horizontally (columns) *)\nFact row_perm_key : unit. Proof. by []. Qed.\nDefinition row_perm (s : 'S_m) A := \\matrix[row_perm_key]_(i, j) A (s i) j.\nFact col_perm_key : unit. Proof. by []. Qed.\nDefinition col_perm (s : 'S_n) A := \\matrix[col_perm_key]_(i, j) A i (s j).\n\n(* Exchange two rows/columns of a matrix *)\nDefinition xrow i1 i2 := row_perm (tperm i1 i2).\nDefinition xcol j1 j2 := col_perm (tperm j1 j2).\n\n(* Row/Column sub matrices of a matrix *)\nDefinition row i0 A := \\row_j A i0 j.\nDefinition col j0 A := \\col_i A i j0.\n\n(* Removing a row/column from a matrix *)\nDefinition row' i0 A := \\matrix_(i, j) A (lift i0 i) j.\nDefinition col' j0 A := \\matrix_(i, j) A i (lift j0 j).\n\nLemma castmx_const m' n' (eq_mn : (m = m') * (n = n')) a :\n  castmx eq_mn (const_mx a) = const_mx a.\nProof. by case: eq_mn; case: m' /; case: n' /. Qed.\n\nLemma trmx_const a : trmx (const_mx a) = const_mx a.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma row_perm_const s a : row_perm s (const_mx a) = const_mx a.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma col_perm_const s a : col_perm s (const_mx a) = const_mx a.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma xrow_const i1 i2 a : xrow i1 i2 (const_mx a) = const_mx a.\nProof. exact: row_perm_const. Qed.\n\nLemma xcol_const j1 j2 a : xcol j1 j2 (const_mx a) = const_mx a.\nProof. exact: col_perm_const. Qed.\n\nLemma rowP (u v : 'rV[R]_n) : u 0 =1 v 0 <-> u = v.\nProof. by split=> [eq_uv | -> //]; apply/matrixP=> i; rewrite ord1. Qed.\n\nLemma rowK u_ i0 : row i0 (\\matrix_i u_ i) = u_ i0.\nProof. by apply/rowP=> i'; rewrite !mxE. Qed.\n\nLemma row_matrixP A B : (forall i, row i A = row i B) <-> A = B.\nProof.\nsplit=> [eqAB | -> //]; apply/matrixP=> i j.\nby move/rowP/(_ j): (eqAB i); rewrite !mxE.\nQed.\n\nLemma colP (u v : 'cV[R]_m) : u^~ 0 =1 v^~ 0 <-> u = v.\nProof. by split=> [eq_uv | -> //]; apply/matrixP=> i j; rewrite ord1. Qed.\n\nLemma row_const i0 a : row i0 (const_mx a) = const_mx a.\nProof. by apply/rowP=> j; rewrite !mxE. Qed.\n\nLemma col_const j0 a : col j0 (const_mx a) = const_mx a.\nProof. by apply/colP=> i; rewrite !mxE. Qed.\n\nLemma row'_const i0 a : row' i0 (const_mx a) = const_mx a.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma col'_const j0 a : col' j0 (const_mx a) = const_mx a.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma col_perm1 A : col_perm 1 A = A.\nProof. by apply/matrixP=> i j; rewrite mxE perm1. Qed.\n\nLemma row_perm1 A : row_perm 1 A = A.\nProof. by apply/matrixP=> i j; rewrite mxE perm1. Qed.\n\nLemma col_permM s t A : col_perm (s * t) A = col_perm s (col_perm t A).\nProof. by apply/matrixP=> i j; rewrite !mxE permM. Qed.\n\nLemma row_permM s t A : row_perm (s * t) A = row_perm s (row_perm t A).\nProof. by apply/matrixP=> i j; rewrite !mxE permM. Qed.\n\nLemma col_row_permC s t A :\n  col_perm s (row_perm t A) = row_perm t (col_perm s A).\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nEnd FixedDim.\n\nLocal Notation \"A ^T\" := (trmx A) : ring_scope.\n\nLemma castmx_id m n erefl_mn (A : 'M_(m, n)) : castmx erefl_mn A = A.\nProof. by case: erefl_mn => e_m e_n; rewrite [e_m]eq_axiomK [e_n]eq_axiomK. Qed.\n\nLemma castmx_comp m1 n1 m2 n2 m3 n3 (eq_m1 : m1 = m2) (eq_n1 : n1 = n2)\n                                    (eq_m2 : m2 = m3) (eq_n2 : n2 = n3) A :\n  castmx (eq_m2, eq_n2) (castmx (eq_m1, eq_n1) A)\n    = castmx (etrans eq_m1 eq_m2, etrans eq_n1 eq_n2) A.\nProof.\nby case: m2 / eq_m1 eq_m2; case: m3 /; case: n2 / eq_n1 eq_n2; case: n3 /.\nQed.\n\nLemma castmxK m1 n1 m2 n2 (eq_m : m1 = m2) (eq_n : n1 = n2) :\n  cancel (castmx (eq_m, eq_n)) (castmx (esym eq_m, esym eq_n)).\nProof. by case: m2 / eq_m; case: n2 / eq_n. Qed.\n\nLemma castmxKV m1 n1 m2 n2 (eq_m : m1 = m2) (eq_n : n1 = n2) :\n  cancel (castmx (esym eq_m, esym eq_n)) (castmx (eq_m, eq_n)).\nProof. by case: m2 / eq_m; case: n2 / eq_n. Qed.\n\n(* This can be use to reverse an equation that involves a cast. *)\nLemma castmx_sym m1 n1 m2 n2 (eq_m : m1 = m2) (eq_n : n1 = n2) A1 A2 :\n  A1 = castmx (eq_m, eq_n) A2 -> A2 = castmx (esym eq_m, esym eq_n) A1.\nProof. by move/(canLR (castmxK _ _)). Qed.\n\nLemma castmxE m1 n1 m2 n2 (eq_mn : (m1 = m2) * (n1 = n2)) A i j :\n  castmx eq_mn A i j =\n     A (cast_ord (esym eq_mn.1) i) (cast_ord (esym eq_mn.2) j).\nProof.\nby do [case: eq_mn; case: m2 /; case: n2 /] in A i j *; rewrite !cast_ord_id.\nQed.\n\nLemma conform_mx_id m n (B A : 'M_(m, n)) : conform_mx B A = A.\nProof. by rewrite /conform_mx; do 2!case: eqP => // *; rewrite castmx_id. Qed.\n\nLemma nonconform_mx m m' n n' (B : 'M_(m', n')) (A : 'M_(m, n)) :\n  (m != m') || (n != n') -> conform_mx B A = B.\nProof. by rewrite /conform_mx; do 2!case: eqP. Qed.\n\nLemma conform_castmx m1 n1 m2 n2 m3 n3\n                     (e_mn : (m2 = m3) * (n2 = n3)) (B : 'M_(m1, n1)) A :\n  conform_mx B (castmx e_mn A) = conform_mx B A.\nProof. by do [case: e_mn; case: m3 /; case: n3 /] in A *. Qed.\n\nLemma trmxK m n : cancel (@trmx m n) (@trmx n m).\nProof. by move=> A; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma trmx_inj m n : injective (@trmx m n).\nProof. exact: can_inj (@trmxK m n). Qed.\n\nLemma trmx_cast m1 n1 m2 n2 (eq_mn : (m1 = m2) * (n1 = n2)) A :\n  (castmx eq_mn A)^T = castmx (eq_mn.2, eq_mn.1) A^T.\nProof.\nby case: eq_mn => eq_m eq_n; apply/matrixP=> i j; rewrite !(mxE, castmxE).\nQed.\n\nLemma tr_row_perm m n s (A : 'M_(m, n)) : (row_perm s A)^T = col_perm s A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_col_perm m n s (A : 'M_(m, n)) : (col_perm s A)^T = row_perm s A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_xrow m n i1 i2 (A : 'M_(m, n)) : (xrow i1 i2 A)^T = xcol i1 i2 A^T.\nProof. exact: tr_row_perm. Qed.\n\nLemma tr_xcol m n j1 j2 (A : 'M_(m, n)) : (xcol j1 j2 A)^T = xrow j1 j2 A^T.\nProof. exact: tr_col_perm. Qed.\n\nLemma row_id n i (V : 'rV_n) : row i V = V.\nProof. by apply/rowP=> j; rewrite mxE [i]ord1. Qed.\n\nLemma col_id n j (V : 'cV_n) : col j V = V.\nProof. by apply/colP=> i; rewrite mxE [j]ord1. Qed.\n\nLemma row_eq m1 m2 n i1 i2 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  row i1 A1 = row i2 A2 -> A1 i1 =1 A2 i2.\nProof. by move/rowP=> eqA12 j; have:= eqA12 j; rewrite !mxE. Qed.\n\nLemma col_eq m n1 n2 j1 j2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  col j1 A1 = col j2 A2 -> A1^~ j1 =1 A2^~ j2.\nProof. by move/colP=> eqA12 i; have:= eqA12 i; rewrite !mxE. Qed.\n\nLemma row'_eq m n i0 (A B : 'M_(m, n)) :\n  row' i0 A = row' i0 B -> {in predC1 i0, A =2 B}.\nProof.\nmove/matrixP=> eqAB' i; rewrite !inE eq_sym; case/unlift_some=> i' -> _ j.\nby have:= eqAB' i' j; rewrite !mxE.\nQed.\n\nLemma col'_eq m n j0 (A B : 'M_(m, n)) :\n  col' j0 A = col' j0 B -> forall i, {in predC1 j0, A i =1 B i}.\nProof.\nmove/matrixP=> eqAB' i j; rewrite !inE eq_sym; case/unlift_some=> j' -> _.\nby have:= eqAB' i j'; rewrite !mxE.\nQed.\n\nLemma tr_row m n i0 (A : 'M_(m, n)) : (row i0 A)^T = col i0 A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_row' m n i0 (A : 'M_(m, n)) : (row' i0 A)^T = col' i0 A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_col m n j0 (A : 'M_(m, n)) : (col j0 A)^T = row j0 A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_col' m n j0 (A : 'M_(m, n)) : (col' j0 A)^T = row' j0 A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLtac split_mxE := apply/matrixP=> i j; do ![rewrite mxE | case: split => ?].\n\nSection CutPaste.\n\nVariables m m1 m2 n n1 n2 : nat.\n\n(* Concatenating two matrices, in either direction. *)\n\nFact row_mx_key : unit. Proof. by []. Qed.\nDefinition row_mx (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) : 'M[R]_(m, n1 + n2) :=\n  \\matrix[row_mx_key]_(i, j)\n     match split j with inl j1 => A1 i j1 | inr j2 => A2 i j2 end.\n\nFact col_mx_key : unit. Proof. by []. Qed.\nDefinition col_mx (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) : 'M[R]_(m1 + m2, n) :=\n  \\matrix[col_mx_key]_(i, j)\n     match split i with inl i1 => A1 i1 j | inr i2 => A2 i2 j end.\n\n(* Left/Right | Up/Down submatrices of a rows | columns matrix.   *)\n(* The shape of the (dependent) width parameters of the type of A *)\n(* determines which submatrix is selected.                        *)\n\nFact lsubmx_key : unit. Proof. by []. Qed.\nDefinition lsubmx (A : 'M[R]_(m, n1 + n2)) :=\n  \\matrix[lsubmx_key]_(i, j) A i (lshift n2 j).\n\nFact rsubmx_key : unit. Proof. by []. Qed.\nDefinition rsubmx (A : 'M[R]_(m, n1 + n2)) :=\n  \\matrix[rsubmx_key]_(i, j) A i (rshift n1 j).\n\nFact usubmx_key : unit. Proof. by []. Qed.\nDefinition usubmx (A : 'M[R]_(m1 + m2, n)) :=\n  \\matrix[usubmx_key]_(i, j) A (lshift m2 i) j.\n\nFact dsubmx_key : unit. Proof. by []. Qed.\nDefinition dsubmx (A : 'M[R]_(m1 + m2, n)) :=\n  \\matrix[dsubmx_key]_(i, j) A (rshift m1 i) j.\n\nLemma row_mxEl A1 A2 i j : row_mx A1 A2 i (lshift n2 j) = A1 i j.\nProof. by rewrite mxE (unsplitK (inl _ _)). Qed.\n\nLemma row_mxKl A1 A2 : lsubmx (row_mx A1 A2) = A1.\nProof. by apply/matrixP=> i j; rewrite mxE row_mxEl. Qed.\n\nLemma row_mxEr A1 A2 i j : row_mx A1 A2 i (rshift n1 j) = A2 i j.\nProof. by rewrite mxE (unsplitK (inr _ _)). Qed.\n\nLemma row_mxKr A1 A2 : rsubmx (row_mx A1 A2) = A2.\nProof. by apply/matrixP=> i j; rewrite mxE row_mxEr. Qed.\n\nLemma hsubmxK A : row_mx (lsubmx A) (rsubmx A) = A.\nProof.\napply/matrixP=> i j; rewrite !mxE.\ncase: splitP => k Dk //=; rewrite !mxE //=; congr (A _ _); exact: val_inj.\nQed.\n\nLemma col_mxEu A1 A2 i j : col_mx A1 A2 (lshift m2 i) j = A1 i j.\nProof. by rewrite mxE (unsplitK (inl _ _)). Qed.\n\nLemma col_mxKu A1 A2 : usubmx (col_mx A1 A2) = A1.\nProof. by apply/matrixP=> i j; rewrite mxE col_mxEu. Qed.\n\nLemma col_mxEd A1 A2 i j : col_mx A1 A2 (rshift m1 i) j = A2 i j.\nProof. by rewrite mxE (unsplitK (inr _ _)). Qed.\n\nLemma col_mxKd A1 A2 : dsubmx (col_mx A1 A2) = A2.\nProof. by apply/matrixP=> i j; rewrite mxE col_mxEd. Qed.\n\nLemma eq_row_mx A1 A2 B1 B2 : row_mx A1 A2 = row_mx B1 B2 -> A1 = B1 /\\ A2 = B2.\nProof.\nmove=> eqAB; move: (congr1 lsubmx eqAB) (congr1 rsubmx eqAB).\nby rewrite !(row_mxKl, row_mxKr).\nQed.\n\nLemma eq_col_mx A1 A2 B1 B2 : col_mx A1 A2 = col_mx B1 B2 -> A1 = B1 /\\ A2 = B2.\nProof.\nmove=> eqAB; move: (congr1 usubmx eqAB) (congr1 dsubmx eqAB).\nby rewrite !(col_mxKu, col_mxKd).\nQed.\n\nLemma row_mx_const a : row_mx (const_mx a) (const_mx a) = const_mx a.\nProof. by split_mxE. Qed.\n\nLemma col_mx_const a : col_mx (const_mx a) (const_mx a) = const_mx a.\nProof. by split_mxE. Qed.\n\nEnd CutPaste.\n\nLemma trmx_lsub m n1 n2 (A : 'M_(m, n1 + n2)) : (lsubmx A)^T = usubmx A^T.\nProof. by split_mxE. Qed.\n\nLemma trmx_rsub m n1 n2 (A : 'M_(m, n1 + n2)) : (rsubmx A)^T = dsubmx A^T.\nProof. by split_mxE. Qed.\n\nLemma tr_row_mx m n1 n2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  (row_mx A1 A2)^T = col_mx A1^T A2^T.\nProof. by split_mxE. Qed.\n\nLemma tr_col_mx m1 m2 n (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  (col_mx A1 A2)^T = row_mx A1^T A2^T.\nProof. by split_mxE. Qed.\n\nLemma trmx_usub m1 m2 n (A : 'M_(m1 + m2, n)) : (usubmx A)^T = lsubmx A^T.\nProof. by split_mxE. Qed.\n\nLemma trmx_dsub m1 m2 n (A : 'M_(m1 + m2, n)) : (dsubmx A)^T = rsubmx A^T.\nProof. by split_mxE. Qed.\n\nLemma vsubmxK m1 m2 n (A : 'M_(m1 + m2, n)) : col_mx (usubmx A) (dsubmx A) = A.\nProof. by apply: trmx_inj; rewrite tr_col_mx trmx_usub trmx_dsub hsubmxK. Qed.\n\nLemma cast_row_mx m m' n1 n2 (eq_m : m = m') A1 A2 :\n  castmx (eq_m, erefl _) (row_mx A1 A2)\n    = row_mx (castmx (eq_m, erefl n1) A1) (castmx (eq_m, erefl n2) A2).\nProof. by case: m' / eq_m. Qed.\n\nLemma cast_col_mx m1 m2 n n' (eq_n : n = n') A1 A2 :\n  castmx (erefl _, eq_n) (col_mx A1 A2)\n    = col_mx (castmx (erefl m1, eq_n) A1) (castmx (erefl m2, eq_n) A2).\nProof. by case: n' / eq_n. Qed.\n\n(* This lemma has Prenex Implicits to help RL rewrititng with castmx_sym. *)\nLemma row_mxA m n1 n2 n3 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) (A3 : 'M_(m, n3)) :\n  let cast := (erefl m, esym (addnA n1 n2 n3)) in\n  row_mx A1 (row_mx A2 A3) = castmx cast (row_mx (row_mx A1 A2) A3).\nProof.\napply: (canRL (castmxKV _ _)); apply/matrixP=> i j.\nrewrite castmxE !mxE cast_ord_id; case: splitP => j1 /= def_j.\n  have: (j < n1 + n2) && (j < n1) by rewrite def_j lshift_subproof /=.\n  by move: def_j; do 2![case: splitP => // ? ->; rewrite ?mxE] => /ord_inj->.\ncase: splitP def_j => j2 ->{j} def_j; rewrite !mxE.\n  have: ~~ (j2 < n1) by rewrite -leqNgt def_j leq_addr.\n  have: j1 < n2 by rewrite -(ltn_add2l n1) -def_j.\n  by move: def_j; do 2![case: splitP => // ? ->] => /addnI/val_inj->.\nhave: ~~ (j1 < n2) by rewrite -leqNgt -(leq_add2l n1) -def_j leq_addr.\nby case: splitP def_j => // ? ->; rewrite addnA => /addnI/val_inj->.\nQed.\nDefinition row_mxAx := row_mxA. (* bypass Prenex Implicits. *)\n\n(* This lemma has Prenex Implicits to help RL rewrititng with castmx_sym. *)\nLemma col_mxA m1 m2 m3 n (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) (A3 : 'M_(m3, n)) :\n  let cast := (esym (addnA m1 m2 m3), erefl n) in\n  col_mx A1 (col_mx A2 A3) = castmx cast (col_mx (col_mx A1 A2) A3).\nProof. by apply: trmx_inj; rewrite trmx_cast !tr_col_mx -row_mxA. Qed.\nDefinition col_mxAx := col_mxA. (* bypass Prenex Implicits. *)\n\nLemma row_row_mx m n1 n2 i0 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  row i0 (row_mx A1 A2) = row_mx (row i0 A1) (row i0 A2).\nProof.\nby apply/matrixP=> i j; rewrite !mxE; case: (split j) => j'; rewrite mxE.\nQed.\n\nLemma col_col_mx m1 m2 n j0 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  col j0 (col_mx A1 A2) = col_mx (col j0 A1) (col j0 A2).\nProof. by apply: trmx_inj; rewrite !(tr_col, tr_col_mx, row_row_mx). Qed.\n\nLemma row'_row_mx m n1 n2 i0 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  row' i0 (row_mx A1 A2) = row_mx (row' i0 A1) (row' i0 A2).\nProof.\nby apply/matrixP=> i j; rewrite !mxE; case: (split j) => j'; rewrite mxE.\nQed.\n\nLemma col'_col_mx m1 m2 n j0 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  col' j0 (col_mx A1 A2) = col_mx (col' j0 A1) (col' j0 A2).\nProof. by apply: trmx_inj; rewrite !(tr_col', tr_col_mx, row'_row_mx). Qed.\n\nLemma colKl m n1 n2 j1 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  col (lshift n2 j1) (row_mx A1 A2) = col j1 A1.\nProof. by apply/matrixP=> i j; rewrite !(row_mxEl, mxE). Qed.\n\nLemma colKr m n1 n2 j2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  col (rshift n1 j2) (row_mx A1 A2) = col j2 A2.\nProof. by apply/matrixP=> i j; rewrite !(row_mxEr, mxE). Qed.\n\nLemma rowKu m1 m2 n i1 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  row (lshift m2 i1) (col_mx A1 A2) = row i1 A1.\nProof. by apply/matrixP=> i j; rewrite !(col_mxEu, mxE). Qed.\n\nLemma rowKd m1 m2 n i2 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  row (rshift m1 i2) (col_mx A1 A2) = row i2 A2.\nProof. by apply/matrixP=> i j; rewrite !(col_mxEd, mxE). Qed.\n\nLemma col'Kl m n1 n2 j1 (A1 : 'M_(m, n1.+1)) (A2 : 'M_(m, n2)) :\n  col' (lshift n2 j1) (row_mx A1 A2) = row_mx (col' j1 A1) A2.\nProof.\napply/matrixP=> i /= j; symmetry; rewrite 2!mxE.\ncase: splitP => j' def_j'.\n  rewrite mxE -(row_mxEl _ A2); congr (row_mx _ _ _); apply: ord_inj.\n  by rewrite /= def_j'.\nrewrite -(row_mxEr A1); congr (row_mx _ _ _); apply: ord_inj => /=.\nby rewrite /bump def_j' -ltnS -addSn ltn_addr.\nQed.\n\nLemma row'Ku m1 m2 n i1 (A1 : 'M_(m1.+1, n)) (A2 : 'M_(m2, n)) :\n  row' (lshift m2 i1) (@col_mx m1.+1 m2 n A1 A2) = col_mx (row' i1 A1) A2.\nProof.\nby apply: trmx_inj; rewrite tr_col_mx !(@tr_row' _.+1) (@tr_col_mx _.+1) col'Kl.\nQed.\n\nLemma mx'_cast m n : 'I_n -> (m + n.-1)%N = (m + n).-1.\nProof. by case=> j /ltn_predK <-; rewrite addnS. Qed.\n\nLemma col'Kr m n1 n2 j2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  col' (rshift n1 j2) (@row_mx m n1 n2 A1 A2)\n    = castmx (erefl m, mx'_cast n1 j2) (row_mx A1 (col' j2 A2)).\nProof.\napply/matrixP=> i j; symmetry; rewrite castmxE mxE cast_ord_id.\ncase: splitP => j' /= def_j.\n  rewrite mxE -(row_mxEl _ A2); congr (row_mx _ _ _); apply: ord_inj.\n  by rewrite /= def_j /bump leqNgt ltn_addr.\nrewrite 2!mxE -(row_mxEr A1); congr (row_mx _ _ _ _); apply: ord_inj.\nby rewrite /= def_j /bump leq_add2l addnCA.\nQed.\n\nLemma row'Kd m1 m2 n i2 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  row' (rshift m1 i2) (col_mx A1 A2)\n    = castmx (mx'_cast m1 i2, erefl n) (col_mx A1 (row' i2 A2)).\nProof. by apply: trmx_inj; rewrite trmx_cast !(tr_row', tr_col_mx) col'Kr. Qed.\n\nSection Block.\n\nVariables m1 m2 n1 n2 : nat.\n\n(* Building a block matrix from 4 matrices :               *)\n(*  up left, up right, down left and down right components *)\n\nDefinition block_mx Aul Aur Adl Adr : 'M_(m1 + m2, n1 + n2) :=\n  col_mx (row_mx Aul Aur) (row_mx Adl Adr).\n\nLemma eq_block_mx Aul Aur Adl Adr Bul Bur Bdl Bdr :\n block_mx Aul Aur Adl Adr = block_mx Bul Bur Bdl Bdr ->\n  [/\\ Aul = Bul, Aur = Bur, Adl = Bdl & Adr = Bdr].\nProof. by case/eq_col_mx; do 2!case/eq_row_mx=> -> ->. Qed.\n\nLemma block_mx_const a :\n  block_mx (const_mx a) (const_mx a) (const_mx a) (const_mx a) = const_mx a.\nProof. by split_mxE. Qed.\n\nSection CutBlock.\n\nVariable A : matrix R (m1 + m2) (n1 + n2).\n\nDefinition ulsubmx := lsubmx (usubmx A).\nDefinition ursubmx := rsubmx (usubmx A).\nDefinition dlsubmx := lsubmx (dsubmx A).\nDefinition drsubmx := rsubmx (dsubmx A).\n\nLemma submxK : block_mx ulsubmx ursubmx dlsubmx drsubmx = A.\nProof. by rewrite /block_mx !hsubmxK vsubmxK. Qed.\n\nEnd CutBlock.\n\nSection CatBlock.\n\nVariables (Aul : 'M[R]_(m1, n1)) (Aur : 'M[R]_(m1, n2)).\nVariables (Adl : 'M[R]_(m2, n1)) (Adr : 'M[R]_(m2, n2)).\n\nLet A := block_mx Aul Aur Adl Adr.\n\nLemma block_mxEul i j : A (lshift m2 i) (lshift n2 j) = Aul i j.\nProof. by rewrite col_mxEu row_mxEl. Qed.\nLemma block_mxKul : ulsubmx A = Aul.\nProof. by rewrite /ulsubmx col_mxKu row_mxKl. Qed.\n\nLemma block_mxEur i j : A (lshift m2 i) (rshift n1 j) = Aur i j.\nProof. by rewrite col_mxEu row_mxEr. Qed.\nLemma block_mxKur : ursubmx A = Aur.\nProof. by rewrite /ursubmx col_mxKu row_mxKr. Qed.\n\nLemma block_mxEdl i j : A (rshift m1 i) (lshift n2 j) = Adl i j.\nProof. by rewrite col_mxEd row_mxEl. Qed.\nLemma block_mxKdl : dlsubmx A = Adl.\nProof. by rewrite /dlsubmx col_mxKd row_mxKl. Qed.\n\nLemma block_mxEdr i j : A (rshift m1 i) (rshift n1 j) = Adr i j.\nProof. by rewrite col_mxEd row_mxEr. Qed.\nLemma block_mxKdr : drsubmx A = Adr.\nProof. by rewrite /drsubmx col_mxKd row_mxKr. Qed.\n\nLemma block_mxEv : A = col_mx (row_mx Aul Aur) (row_mx Adl Adr).\nProof. by []. Qed.\n\nEnd CatBlock.\n\nEnd Block.\n\nSection TrCutBlock.\n\nVariables m1 m2 n1 n2 : nat.\nVariable A : 'M[R]_(m1 + m2, n1 + n2).\n\nLemma trmx_ulsub : (ulsubmx A)^T = ulsubmx A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma trmx_ursub : (ursubmx A)^T = dlsubmx A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma trmx_dlsub : (dlsubmx A)^T = ursubmx A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma trmx_drsub : (drsubmx A)^T = drsubmx A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nEnd TrCutBlock.\n\nSection TrBlock.\nVariables m1 m2 n1 n2 : nat.\nVariables (Aul : 'M[R]_(m1, n1)) (Aur : 'M[R]_(m1, n2)).\nVariables (Adl : 'M[R]_(m2, n1)) (Adr : 'M[R]_(m2, n2)).\n\nLemma tr_block_mx :\n (block_mx Aul Aur Adl Adr)^T = block_mx Aul^T Adl^T Aur^T Adr^T.\nProof.\nrewrite -[_^T]submxK -trmx_ulsub -trmx_ursub -trmx_dlsub -trmx_drsub.\nby rewrite block_mxKul block_mxKur block_mxKdl block_mxKdr.\nQed.\n\nLemma block_mxEh :\n  block_mx Aul Aur Adl Adr = row_mx (col_mx Aul Adl) (col_mx Aur Adr).\nProof. by apply: trmx_inj; rewrite tr_block_mx tr_row_mx 2!tr_col_mx. Qed.\nEnd TrBlock.\n\n(* This lemma has Prenex Implicits to help RL rewrititng with castmx_sym. *)\nLemma block_mxA m1 m2 m3 n1 n2 n3\n   (A11 : 'M_(m1, n1)) (A12 : 'M_(m1, n2)) (A13 : 'M_(m1, n3))\n   (A21 : 'M_(m2, n1)) (A22 : 'M_(m2, n2)) (A23 : 'M_(m2, n3))\n   (A31 : 'M_(m3, n1)) (A32 : 'M_(m3, n2)) (A33 : 'M_(m3, n3)) :\n  let cast := (esym (addnA m1 m2 m3), esym (addnA n1 n2 n3)) in\n  let row1 := row_mx A12 A13 in let col1 := col_mx A21 A31 in\n  let row3 := row_mx A31 A32 in let col3 := col_mx A13 A23 in\n  block_mx A11 row1 col1 (block_mx A22 A23 A32 A33)\n    = castmx cast (block_mx (block_mx A11 A12 A21 A22) col3 row3 A33).\nProof.\nrewrite /= block_mxEh !col_mxA -cast_row_mx -block_mxEv -block_mxEh.\nrewrite block_mxEv block_mxEh !row_mxA -cast_col_mx -block_mxEh -block_mxEv.\nby rewrite castmx_comp etrans_id.\nQed.\nDefinition block_mxAx := block_mxA. (* Bypass Prenex Implicits *)\n\n(* Bijections mxvec : 'M_(m, n) <----> 'rV_(m * n) : vec_mx *)\nSection VecMatrix.\n\nVariables m n : nat.\n\nLemma mxvec_cast : #|{:'I_m * 'I_n}| = (m * n)%N. \nProof. by rewrite card_prod !card_ord. Qed.\n\nDefinition mxvec_index (i : 'I_m) (j : 'I_n) :=\n  cast_ord mxvec_cast (enum_rank (i, j)).\n\nCoInductive is_mxvec_index : 'I_(m * n) -> Type :=\n  IsMxvecIndex i j : is_mxvec_index (mxvec_index i j).\n\nLemma mxvec_indexP k : is_mxvec_index k.\nProof.\nrewrite -[k](cast_ordK (esym mxvec_cast)) esymK.\nby rewrite -[_ k]enum_valK; case: (enum_val _).\nQed.\n\nCoercion pair_of_mxvec_index k (i_k : is_mxvec_index k) :=\n  let: IsMxvecIndex i j := i_k in (i, j).\n\nDefinition mxvec (A : 'M[R]_(m, n)) :=\n  castmx (erefl _, mxvec_cast) (\\row_k A (enum_val k).1 (enum_val k).2).\n\nFact vec_mx_key : unit. Proof. by []. Qed.\nDefinition vec_mx (u : 'rV[R]_(m * n)) :=\n  \\matrix[vec_mx_key]_(i, j) u 0 (mxvec_index i j).\n\nLemma mxvecE A i j : mxvec A 0 (mxvec_index i j) = A i j.\nProof. by rewrite castmxE mxE cast_ordK enum_rankK. Qed.\n\nLemma mxvecK : cancel mxvec vec_mx.\nProof. by move=> A; apply/matrixP=> i j; rewrite mxE mxvecE. Qed.\n\nLemma vec_mxK : cancel vec_mx mxvec.\nProof.\nby move=> u; apply/rowP=> k; case/mxvec_indexP: k => i j; rewrite mxvecE mxE.\nQed.\n\nLemma curry_mxvec_bij : {on 'I_(m * n), bijective (prod_curry mxvec_index)}.\nProof.\nexists (enum_val \\o cast_ord (esym mxvec_cast)) => [[i j] _ | k _] /=.\n  by rewrite cast_ordK enum_rankK.\nby case/mxvec_indexP: k => i j /=; rewrite cast_ordK enum_rankK.\nQed.\n\nEnd VecMatrix.\n\nEnd MatrixStructural.\n\nImplicit Arguments const_mx [R m n].\nImplicit Arguments row_mxA [R m n1 n2 n3 A1 A2 A3].\nImplicit Arguments col_mxA [R m1 m2 m3 n A1 A2 A3].\nImplicit Arguments block_mxA\n  [R m1 m2 m3 n1 n2 n3 A11 A12 A13 A21 A22 A23 A31 A32 A33].\nPrenex Implicits const_mx castmx trmx lsubmx rsubmx usubmx dsubmx row_mx col_mx.\nPrenex Implicits block_mx ulsubmx ursubmx dlsubmx drsubmx.\nPrenex Implicits row_mxA col_mxA block_mxA.\nPrenex Implicits mxvec vec_mx mxvec_indexP mxvecK vec_mxK.\n\nNotation \"A ^T\" := (trmx A) : ring_scope.\n\n(* Matrix parametricity. *)\nSection MapMatrix.\n\nVariables (aT rT : Type) (f : aT -> rT).\n\nFact map_mx_key : unit. Proof. by []. Qed.\nDefinition map_mx m n (A : 'M_(m, n)) := \\matrix[map_mx_key]_(i, j) f (A i j).\n\nNotation \"A ^f\" := (map_mx A) : ring_scope.\n\nSection OneMatrix.\n\nVariables (m n : nat) (A : 'M[aT]_(m, n)).\n\nLemma map_trmx : A^f^T = A^T^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_const_mx a : (const_mx a)^f = const_mx (f a) :> 'M_(m, n).\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_row i : (row i A)^f = row i A^f.\nProof. by apply/rowP=> j; rewrite !mxE. Qed.\n\nLemma map_col j : (col j A)^f = col j A^f.\nProof. by apply/colP=> i; rewrite !mxE. Qed.\n\nLemma map_row' i0 : (row' i0 A)^f = row' i0 A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_col' j0 : (col' j0 A)^f = col' j0 A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_row_perm s : (row_perm s A)^f = row_perm s A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_col_perm s : (col_perm s A)^f = col_perm s A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_xrow i1 i2 : (xrow i1 i2 A)^f = xrow i1 i2 A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_xcol j1 j2 : (xcol j1 j2 A)^f = xcol j1 j2 A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_castmx m' n' c : (castmx c A)^f = castmx c A^f :> 'M_(m', n').\nProof. by apply/matrixP=> i j; rewrite !(castmxE, mxE). Qed.\n\nLemma map_conform_mx m' n' (B : 'M_(m', n')) :\n  (conform_mx B A)^f = conform_mx B^f A^f.\nProof.\nmove: B; have [[<- <-] B|] := eqVneq (m, n) (m', n'). \n  by rewrite !conform_mx_id.\nby rewrite negb_and => neq_mn B; rewrite !nonconform_mx.\nQed.\n\nLemma map_mxvec : (mxvec A)^f = mxvec A^f.\nProof. by apply/rowP=> i; rewrite !(castmxE, mxE). Qed.\n\nLemma map_vec_mx (v : 'rV_(m * n)) : (vec_mx v)^f = vec_mx v^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nEnd OneMatrix.\n\nSection Block.\n\nVariables m1 m2 n1 n2 : nat.\nVariables (Aul : 'M[aT]_(m1, n1)) (Aur : 'M[aT]_(m1, n2)).\nVariables (Adl : 'M[aT]_(m2, n1)) (Adr : 'M[aT]_(m2, n2)).\nVariables (Bh : 'M[aT]_(m1, n1 + n2)) (Bv : 'M[aT]_(m1 + m2, n1)).\nVariable B : 'M[aT]_(m1 + m2, n1 + n2).\n\nLemma map_row_mx : (row_mx Aul Aur)^f = row_mx Aul^f Aur^f.\nProof. by apply/matrixP=> i j; do 2![rewrite !mxE //; case: split => ?]. Qed.\n\nLemma map_col_mx : (col_mx Aul Adl)^f = col_mx Aul^f Adl^f.\nProof. by apply/matrixP=> i j; do 2![rewrite !mxE //; case: split => ?]. Qed.\n\nLemma map_block_mx :\n  (block_mx Aul Aur Adl Adr)^f = block_mx Aul^f Aur^f Adl^f Adr^f.\nProof. by apply/matrixP=> i j; do 3![rewrite !mxE //; case: split => ?]. Qed.\n\nLemma map_lsubmx : (lsubmx Bh)^f = lsubmx Bh^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_rsubmx : (rsubmx Bh)^f = rsubmx Bh^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_usubmx : (usubmx Bv)^f = usubmx Bv^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_dsubmx : (dsubmx Bv)^f = dsubmx Bv^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_ulsubmx : (ulsubmx B)^f = ulsubmx B^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_ursubmx : (ursubmx B)^f = ursubmx B^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_dlsubmx : (dlsubmx B)^f = dlsubmx B^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_drsubmx : (drsubmx B)^f = drsubmx B^f.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nEnd Block.\n\nEnd MapMatrix.\n\n(*****************************************************************************)\n(********************* Matrix Zmodule (additive) structure *******************)\n(*****************************************************************************)\n\nSection MatrixZmodule.\n\nVariable V : zmodType.\n\nSection FixedDim.\n\nVariables m n : nat.\nImplicit Types A B : 'M[V]_(m, n).\n\nFact oppmx_key : unit. Proof. by []. Qed.\nFact addmx_key : unit. Proof. by []. Qed.\nDefinition oppmx A := \\matrix[oppmx_key]_(i, j) (- A i j).\nDefinition addmx A B := \\matrix[addmx_key]_(i, j) (A i j + B i j).\n(* In principle, diag_mx and scalar_mx could be defined here, but since they *)\n(* only make sense with the graded ring operations, we defer them to the     *)\n(* next section.                                                             *)\n\nLemma addmxA : associative addmx.\nProof. by move=> A B C; apply/matrixP=> i j; rewrite !mxE addrA. Qed.\n\nLemma addmxC : commutative addmx.\nProof. by move=> A B; apply/matrixP=> i j; rewrite !mxE addrC. Qed.\n\nLemma add0mx : left_id (const_mx 0) addmx.\nProof. by move=> A; apply/matrixP=> i j; rewrite !mxE add0r. Qed.\n\nLemma addNmx : left_inverse (const_mx 0) oppmx addmx.\nProof. by move=> A; apply/matrixP=> i j; rewrite !mxE addNr. Qed.\n\nDefinition matrix_zmodMixin := ZmodMixin addmxA addmxC add0mx addNmx.\n\nCanonical matrix_zmodType := Eval hnf in ZmodType 'M[V]_(m, n) matrix_zmodMixin.\n\nLemma mulmxnE A d i j : (A *+ d) i j = A i j *+ d.\nProof. by elim: d => [|d IHd]; rewrite ?mulrS mxE ?IHd. Qed.\n\nLemma summxE I r (P : pred I) (E : I -> 'M_(m, n)) i j :\n  (\\sum_(k <- r | P k) E k) i j = \\sum_(k <- r | P k) E k i j.\nProof. by apply: (big_morph (fun A => A i j)) => [A B|]; rewrite mxE. Qed.\n\nLemma const_mx_is_additive : additive const_mx.\nProof. by move=> a b; apply/matrixP=> i j; rewrite !mxE. Qed.\nCanonical const_mx_additive := Additive const_mx_is_additive.\n\nEnd FixedDim.\n\nSection Additive.\n\nVariables (m n p q : nat) (f : 'I_p -> 'I_q -> 'I_m) (g : 'I_p -> 'I_q -> 'I_n).\n\nDefinition swizzle_mx k (A : 'M[V]_(m, n)) :=\n  \\matrix[k]_(i, j) A (f i j) (g i j).\n\nLemma swizzle_mx_is_additive k : additive (swizzle_mx k).\nProof. by move=> A B; apply/matrixP=> i j; rewrite !mxE. Qed.\nCanonical swizzle_mx_additive k := Additive (swizzle_mx_is_additive k).\n\nEnd Additive.\n\nLocal Notation SwizzleAdd op := [additive of op as swizzle_mx _ _ _].\n\nCanonical trmx_additive m n := SwizzleAdd (@trmx V m n).\nCanonical row_additive m n i := SwizzleAdd (@row V m n i).\nCanonical col_additive m n j := SwizzleAdd (@col V m n j).\nCanonical row'_additive m n i := SwizzleAdd (@row' V m n i).\nCanonical col'_additive m n j := SwizzleAdd (@col' V m n j).\nCanonical row_perm_additive m n s := SwizzleAdd (@row_perm V m n s).\nCanonical col_perm_additive m n s := SwizzleAdd (@col_perm V m n s).\nCanonical xrow_additive m n i1 i2 := SwizzleAdd (@xrow V m n i1 i2).\nCanonical xcol_additive m n j1 j2 := SwizzleAdd (@xcol V m n j1 j2).\nCanonical lsubmx_additive m n1 n2 := SwizzleAdd (@lsubmx V m n1 n2).\nCanonical rsubmx_additive m n1 n2 := SwizzleAdd (@rsubmx V m n1 n2).\nCanonical usubmx_additive m1 m2 n := SwizzleAdd (@usubmx V m1 m2 n).\nCanonical dsubmx_additive m1 m2 n := SwizzleAdd (@dsubmx V m1 m2 n).\nCanonical vec_mx_additive m n := SwizzleAdd (@vec_mx V m n).\nCanonical mxvec_additive m n :=\n  Additive (can2_additive (@vec_mxK V m n) mxvecK).\n\nLemma flatmx0 n : all_equal_to (0 : 'M_(0, n)).\nProof. by move=> A; apply/matrixP=> [] []. Qed.\n\nLemma thinmx0 n : all_equal_to (0 : 'M_(n, 0)).\nProof. by move=> A; apply/matrixP=> i []. Qed.\n\nLemma trmx0 m n : (0 : 'M_(m, n))^T = 0.\nProof. exact: trmx_const. Qed.\n\nLemma row0 m n i0 : row i0 (0 : 'M_(m, n)) = 0.\nProof. exact: row_const. Qed.\n\nLemma col0 m n j0 : col j0 (0 : 'M_(m, n)) = 0.\nProof. exact: col_const. Qed.\n\nLemma mxvec_eq0 m n (A : 'M_(m, n)) : (mxvec A == 0) = (A == 0).\nProof. by rewrite (can2_eq mxvecK vec_mxK) raddf0. Qed.\n\nLemma vec_mx_eq0 m n (v : 'rV_(m * n)) : (vec_mx v == 0) = (v == 0).\nProof. by rewrite (can2_eq vec_mxK mxvecK) raddf0. Qed.\n\nLemma row_mx0 m n1 n2 : row_mx 0 0 = 0 :> 'M_(m, n1 + n2).\nProof. exact: row_mx_const. Qed.\n\nLemma col_mx0 m1 m2 n : col_mx 0 0 = 0 :> 'M_(m1 + m2, n).\nProof. exact: col_mx_const. Qed.\n\nLemma block_mx0 m1 m2 n1 n2 : block_mx 0 0 0 0 = 0 :> 'M_(m1 + m2, n1 + n2).\nProof. exact: block_mx_const. Qed.\n\nLtac split_mxE := apply/matrixP=> i j; do ![rewrite mxE | case: split => ?].\n\nLemma opp_row_mx m n1 n2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  - row_mx A1 A2 = row_mx (- A1) (- A2).\nProof. by split_mxE. Qed.\n\nLemma opp_col_mx m1 m2 n (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  - col_mx A1 A2 = col_mx (- A1) (- A2).\nProof. by split_mxE. Qed.\n\nLemma opp_block_mx m1 m2 n1 n2 (Aul : 'M_(m1, n1)) Aur Adl (Adr : 'M_(m2, n2)) :\n  - block_mx Aul Aur Adl Adr = block_mx (- Aul) (- Aur) (- Adl) (- Adr).\nProof. by rewrite opp_col_mx !opp_row_mx. Qed.\n\nLemma add_row_mx m n1 n2 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) B1 B2 :\n  row_mx A1 A2 + row_mx B1 B2 = row_mx (A1 + B1) (A2 + B2).\nProof. by split_mxE. Qed.\n\nLemma add_col_mx m1 m2 n (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) B1 B2 :\n  col_mx A1 A2 + col_mx B1 B2 = col_mx (A1 + B1) (A2 + B2).\nProof. by split_mxE. Qed.\n\nLemma add_block_mx m1 m2 n1 n2 (Aul : 'M_(m1, n1)) Aur Adl (Adr : 'M_(m2, n2))\n                   Bul Bur Bdl Bdr :\n  let A := block_mx Aul Aur Adl Adr in let B := block_mx Bul Bur Bdl Bdr in\n  A + B = block_mx (Aul + Bul) (Aur + Bur) (Adl + Bdl) (Adr + Bdr).\nProof. by rewrite /= add_col_mx !add_row_mx. Qed.\n\nDefinition nz_row m n (A : 'M_(m, n)) :=\n  oapp (fun i => row i A) 0 [pick i | row i A != 0].\n\nLemma nz_row_eq0 m n (A : 'M_(m, n)) : (nz_row A == 0) = (A == 0).\nProof.\nrewrite /nz_row; symmetry; case: pickP => [i /= nzAi | Ai0].\n  by rewrite (negbTE nzAi); apply: contraTF nzAi => /eqP->; rewrite row0 eqxx.\nby rewrite eqxx; apply/eqP/row_matrixP=> i; move/eqP: (Ai0 i) ->; rewrite row0. \nQed.\n\nEnd MatrixZmodule.\n\nSection FinZmodMatrix.\nVariables (V : finZmodType) (m n : nat).\nLocal Notation MV := 'M[V]_(m, n).\n\nCanonical matrix_finZmodType := Eval hnf in [finZmodType of MV].\nCanonical matrix_baseFinGroupType :=\n  Eval hnf in [baseFinGroupType of MV for +%R].\nCanonical matrix_finGroupType := Eval hnf in [finGroupType of MV for +%R].\nEnd FinZmodMatrix.\n\n(* Parametricity over the additive structure. *)\nSection MapZmodMatrix.\n\nVariables (aR rR : zmodType) (f : {additive aR -> rR}) (m n : nat).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\nImplicit Type A : 'M[aR]_(m, n).\n\nLemma map_mx0 : 0^f = 0 :> 'M_(m, n).\nProof. by rewrite map_const_mx raddf0. Qed.\n\nLemma map_mxN A : (- A)^f = - A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE raddfN. Qed.\n\nLemma map_mxD A B : (A + B)^f = A^f + B^f.\nProof. by apply/matrixP=> i j; rewrite !mxE raddfD. Qed.\n\nLemma map_mx_sub A B : (A - B)^f = A^f - B^f.\nProof. by rewrite map_mxD map_mxN. Qed.\n\nDefinition map_mx_sum := big_morph _ map_mxD map_mx0.\n\nCanonical map_mx_additive := Additive map_mx_sub.\n\nEnd MapZmodMatrix.\n\n(*****************************************************************************)\n(*********** Matrix ring module, graded ring, and ring structures ************)\n(*****************************************************************************)\n\nSection MatrixAlgebra.\n\nVariable R : ringType.\n\nSection RingModule.\n\n(* The ring module/vector space structure *)\n\nVariables m n : nat.\nImplicit Types A B : 'M[R]_(m, n).\n\nFact scalemx_key : unit. Proof. by []. Qed.\nDefinition scalemx x A := \\matrix[scalemx_key]_(i, j) (x * A i j).\n\n(* Basis *)\nFact delta_mx_key : unit. Proof. by []. Qed.\nDefinition delta_mx i0 j0 : 'M[R]_(m, n) :=\n  \\matrix[delta_mx_key]_(i, j) ((i == i0) && (j == j0))%:R.\n\nLocal Notation \"x *m: A\" := (scalemx x A) (at level 40) : ring_scope.\n\nLemma scale1mx A : 1 *m: A = A.\nProof. by apply/matrixP=> i j; rewrite !mxE mul1r. Qed.\n\nLemma scalemxDl A x y : (x + y) *m: A = x *m: A + y *m: A.\nProof. by apply/matrixP=> i j; rewrite !mxE mulrDl. Qed.\n\nLemma scalemxDr x A B : x *m: (A + B) = x *m: A + x *m: B.\nProof. by apply/matrixP=> i j; rewrite !mxE mulrDr. Qed.\n\nLemma scalemxA x y A : x *m: (y *m: A) = (x * y) *m: A.\nProof. by apply/matrixP=> i j; rewrite !mxE mulrA. Qed.\n\nDefinition matrix_lmodMixin := \n  LmodMixin scalemxA scale1mx scalemxDr scalemxDl.\n\nCanonical matrix_lmodType :=\n  Eval hnf in LmodType R 'M[R]_(m, n) matrix_lmodMixin.\n\nLemma scalemx_const a b : a *: const_mx b = const_mx (a * b).\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma matrix_sum_delta A :\n  A = \\sum_(i < m) \\sum_(j < n) A i j *: delta_mx i j.\nProof.\napply/matrixP=> i j.\nrewrite summxE (bigD1 i) // summxE (bigD1 j) //= !mxE !eqxx mulr1.\nrewrite !big1 ?addr0 //= => [i' | j']; rewrite eq_sym => /negbTE diff.\n  by rewrite summxE big1 // => j' _; rewrite !mxE diff mulr0.\nby rewrite !mxE eqxx diff mulr0.\nQed.\n\nEnd RingModule.\n\nSection StructuralLinear.\n\nLemma swizzle_mx_is_scalable m n p q f g k :\n  scalable (@swizzle_mx R m n p q f g k).\nProof. by move=> a A; apply/matrixP=> i j; rewrite !mxE. Qed.\nCanonical swizzle_mx_scalable m n p q f g k :=\n  AddLinear (@swizzle_mx_is_scalable m n p q f g k).\n\nLocal Notation SwizzleLin op := [linear of op as swizzle_mx _ _ _].\n\nCanonical trmx_linear m n := SwizzleLin (@trmx R m n).\nCanonical row_linear m n i := SwizzleLin (@row R m n i).\nCanonical col_linear m n j := SwizzleLin (@col R m n j).\nCanonical row'_linear m n i := SwizzleLin (@row' R m n i).\nCanonical col'_linear m n j := SwizzleLin (@col' R m n j).\nCanonical row_perm_linear m n s := SwizzleLin (@row_perm R m n s).\nCanonical col_perm_linear m n s := SwizzleLin (@col_perm R m n s).\nCanonical xrow_linear m n i1 i2 := SwizzleLin (@xrow R m n i1 i2).\nCanonical xcol_linear m n j1 j2 := SwizzleLin (@xcol R m n j1 j2).\nCanonical lsubmx_linear m n1 n2 := SwizzleLin (@lsubmx R m n1 n2).\nCanonical rsubmx_linear m n1 n2 := SwizzleLin (@rsubmx R m n1 n2).\nCanonical usubmx_linear m1 m2 n := SwizzleLin (@usubmx R m1 m2 n).\nCanonical dsubmx_linear m1 m2 n := SwizzleLin (@dsubmx R m1 m2 n).\nCanonical vec_mx_linear m n := SwizzleLin (@vec_mx R m n).\nDefinition mxvec_is_linear m n := can2_linear (@vec_mxK R m n) mxvecK.\nCanonical mxvec_linear m n := AddLinear (@mxvec_is_linear m n).\n\nEnd StructuralLinear.\n\nLemma trmx_delta m n i j : (delta_mx i j)^T = delta_mx j i :> 'M[R]_(n, m).\nProof. by apply/matrixP=> i' j'; rewrite !mxE andbC. Qed.\n\nLemma row_sum_delta n (u : 'rV_n) : u = \\sum_(j < n) u 0 j *: delta_mx 0 j.\nProof. by rewrite {1}[u]matrix_sum_delta big_ord1. Qed.\n\nLemma delta_mx_lshift m n1 n2 i j :\n  delta_mx i (lshift n2 j) = row_mx (delta_mx i j) 0 :> 'M_(m, n1 + n2).\nProof.\napply/matrixP=> i' j'; rewrite !mxE -(can_eq (@splitK _ _)).\nby rewrite (unsplitK (inl _ _)); case: split => ?; rewrite mxE ?andbF.\nQed.\n\nLemma delta_mx_rshift m n1 n2 i j :\n  delta_mx i (rshift n1 j) = row_mx 0 (delta_mx i j) :> 'M_(m, n1 + n2).\nProof.\napply/matrixP=> i' j'; rewrite !mxE -(can_eq (@splitK _ _)).\nby rewrite (unsplitK (inr _ _)); case: split => ?; rewrite mxE ?andbF.\nQed.\n\nLemma delta_mx_ushift m1 m2 n i j :\n  delta_mx (lshift m2 i) j = col_mx (delta_mx i j) 0 :> 'M_(m1 + m2, n).\nProof.\napply/matrixP=> i' j'; rewrite !mxE -(can_eq (@splitK _ _)).\nby rewrite (unsplitK (inl _ _)); case: split => ?; rewrite mxE.\nQed.\n\nLemma delta_mx_dshift m1 m2 n i j :\n  delta_mx (rshift m1 i) j = col_mx 0 (delta_mx i j) :> 'M_(m1 + m2, n).\nProof.\napply/matrixP=> i' j'; rewrite !mxE -(can_eq (@splitK _ _)).\nby rewrite (unsplitK (inr _ _)); case: split => ?; rewrite mxE.\nQed.\n\nLemma vec_mx_delta m n i j :\n  vec_mx (delta_mx 0 (mxvec_index i j)) = delta_mx i j :> 'M_(m, n).\nProof.\nby apply/matrixP=> i' j'; rewrite !mxE /= [_ == _](inj_eq enum_rank_inj).\nQed.\n\nLemma mxvec_delta m n i j :\n  mxvec (delta_mx i j) = delta_mx 0 (mxvec_index i j) :> 'rV_(m * n).\nProof. by rewrite -vec_mx_delta vec_mxK. Qed.\n\nLtac split_mxE := apply/matrixP=> i j; do ![rewrite mxE | case: split => ?].\n\nLemma scale_row_mx m n1 n2 a (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :\n  a *: row_mx A1 A2 = row_mx (a *: A1) (a *: A2).\nProof. by split_mxE. Qed.\n\nLemma scale_col_mx m1 m2 n a (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)) :\n  a *: col_mx A1 A2 = col_mx (a *: A1) (a *: A2).\nProof. by split_mxE. Qed.\n\nLemma scale_block_mx m1 m2 n1 n2 a (Aul : 'M_(m1, n1)) (Aur : 'M_(m1, n2))\n                                   (Adl : 'M_(m2, n1)) (Adr : 'M_(m2, n2)) :\n  a *: block_mx Aul Aur Adl Adr\n     = block_mx (a *: Aul) (a *: Aur) (a *: Adl) (a *: Adr).\nProof. by rewrite scale_col_mx !scale_row_mx. Qed.\n\n(* Diagonal matrices *)\n\nFact diag_mx_key : unit. Proof. by []. Qed.\nDefinition diag_mx n (d : 'rV[R]_n) :=\n  \\matrix[diag_mx_key]_(i, j) (d 0 i *+ (i == j)).\n\nLemma tr_diag_mx n (d : 'rV_n) : (diag_mx d)^T = diag_mx d.\nProof. by apply/matrixP=> i j; rewrite !mxE eq_sym; case: eqP => // ->. Qed.\n\nLemma diag_mx_is_linear n : linear (@diag_mx n).\nProof.\nby move=> a A B; apply/matrixP=> i j; rewrite !mxE mulrnAr mulrnDl.\nQed.\nCanonical diag_mx_additive n := Additive (@diag_mx_is_linear n).\nCanonical diag_mx_linear n := Linear (@diag_mx_is_linear n).\n\nLemma diag_mx_sum_delta n (d : 'rV_n) :\n  diag_mx d = \\sum_i d 0 i *: delta_mx i i.\nProof.\napply/matrixP=> i j; rewrite summxE (bigD1 i) //= !mxE eqxx /=.\nrewrite eq_sym mulr_natr big1 ?addr0 // => i' ne_i'i.\nby rewrite !mxE eq_sym (negbTE ne_i'i) mulr0.\nQed.\n\n(* Scalar matrix : a diagonal matrix with a constant on the diagonal *)\nSection ScalarMx.\n\nVariable n : nat.\n\nFact scalar_mx_key : unit. Proof. by []. Qed.\nDefinition scalar_mx x : 'M[R]_n :=\n  \\matrix[scalar_mx_key]_(i , j) (x *+ (i == j)).\nNotation \"x %:M\" := (scalar_mx x) : ring_scope.\n\nLemma diag_const_mx a : diag_mx (const_mx a) = a%:M :> 'M_n.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma tr_scalar_mx a : (a%:M)^T = a%:M.\nProof. by apply/matrixP=> i j; rewrite !mxE eq_sym. Qed.\n\nLemma trmx1 : (1%:M)^T = 1%:M. Proof. exact: tr_scalar_mx. Qed.\n\nLemma scalar_mx_is_additive : additive scalar_mx.\nProof. by move=> a b; rewrite -!diag_const_mx !raddfB. Qed.\nCanonical scalar_mx_additive := Additive scalar_mx_is_additive.\n\nLemma scale_scalar_mx a1 a2 : a1 *: a2%:M = (a1 * a2)%:M :> 'M_n.\nProof. by apply/matrixP=> i j; rewrite !mxE mulrnAr. Qed.\n\nLemma scalemx1 a : a *: 1%:M = a%:M.\nProof. by rewrite scale_scalar_mx mulr1. Qed.\n\nLemma scalar_mx_sum_delta a : a%:M = \\sum_i a *: delta_mx i i.\nProof.\nby rewrite -diag_const_mx diag_mx_sum_delta; apply: eq_bigr => i _; rewrite mxE.\nQed.\n\nLemma mx1_sum_delta : 1%:M = \\sum_i delta_mx i i.\nProof. by rewrite [1%:M]scalar_mx_sum_delta -scaler_sumr scale1r. Qed.\n\nLemma row1 i : row i 1%:M = delta_mx 0 i.\nProof. by apply/rowP=> j; rewrite !mxE eq_sym. Qed.\n\nDefinition is_scalar_mx (A : 'M[R]_n) :=\n  if insub 0%N is Some i then A == (A i i)%:M else true.\n\nLemma is_scalar_mxP A : reflect (exists a, A = a%:M) (is_scalar_mx A).\nProof.\nrewrite /is_scalar_mx; case: insubP => [i _ _ | ].\n  by apply: (iffP eqP) => [|[a ->]]; [exists (A i i) | rewrite mxE eqxx].\nrewrite -eqn0Ngt => /eqP n0; left; exists 0.\nby rewrite raddf0; rewrite n0 in A *; rewrite [A]flatmx0.\nQed.\n\nLemma scalar_mx_is_scalar a : is_scalar_mx a%:M.\nProof. by apply/is_scalar_mxP; exists a. Qed.\n\nLemma mx0_is_scalar : is_scalar_mx 0.\nProof. by apply/is_scalar_mxP; exists 0; rewrite raddf0. Qed.\n\nEnd ScalarMx.\n\nNotation \"x %:M\" := (scalar_mx _ x) : ring_scope.\n\nLemma mx11_scalar (A : 'M_1) : A = (A 0 0)%:M.\nProof. by apply/rowP=> j; rewrite ord1 mxE. Qed.\n\nLemma scalar_mx_block n1 n2 a : a%:M = block_mx a%:M 0 0 a%:M :> 'M_(n1 + n2).\nProof.\napply/matrixP=> i j; rewrite !mxE -val_eqE /=.\nby do 2![case: splitP => ? ->; rewrite !mxE];\n  rewrite ?eqn_add2l // -?(eq_sym (n1 + _)%N) eqn_leq leqNgt lshift_subproof.\nQed.\n\n(* Matrix multiplication using bigops. *)\nFact mulmx_key : unit. Proof. by []. Qed.\nDefinition mulmx {m n p} (A : 'M_(m, n)) (B : 'M_(n, p)) : 'M[R]_(m, p) :=\n  \\matrix[mulmx_key]_(i, k) \\sum_j (A i j * B j k).\n\nLocal Notation \"A *m B\" := (mulmx A B) : ring_scope.\n\nLemma mulmxA m n p q (A : 'M_(m, n)) (B : 'M_(n, p)) (C : 'M_(p, q)) :\n  A *m (B *m C) = A *m B *m C.\nProof.\napply/matrixP=> i l; rewrite !mxE.\ntransitivity (\\sum_j (\\sum_k (A i j * (B j k * C k l)))).\n  by apply: eq_bigr => j _; rewrite mxE big_distrr.\nrewrite exchange_big; apply: eq_bigr => j _; rewrite mxE big_distrl /=.\nby apply: eq_bigr => k _; rewrite mulrA.\nQed.\n\nLemma mul0mx m n p (A : 'M_(n, p)) : 0 *m A = 0 :> 'M_(m, p).\nProof.\nby apply/matrixP=> i k; rewrite !mxE big1 //= => j _; rewrite mxE mul0r.\nQed.\n\nLemma mulmx0 m n p (A : 'M_(m, n)) : A *m 0 = 0 :> 'M_(m, p).\nProof.\nby apply/matrixP=> i k; rewrite !mxE big1 // => j _; rewrite mxE mulr0.\nQed.\n\nLemma mulmxN m n p (A : 'M_(m, n)) (B : 'M_(n, p)) : A *m (- B) = - (A *m B).\nProof.\napply/matrixP=> i k; rewrite !mxE -sumrN.\nby apply: eq_bigr => j _; rewrite mxE mulrN.\nQed.\n\nLemma mulNmx m n p (A : 'M_(m, n)) (B : 'M_(n, p)) : - A *m B = - (A *m B).\nProof.\napply/matrixP=> i k; rewrite !mxE -sumrN.\nby apply: eq_bigr => j _; rewrite mxE mulNr.\nQed.\n\nLemma mulmxDl m n p (A1 A2 : 'M_(m, n)) (B : 'M_(n, p)) :\n  (A1 + A2) *m B = A1 *m B + A2 *m B.\nProof.\napply/matrixP=> i k; rewrite !mxE -big_split /=.\nby apply: eq_bigr => j _; rewrite !mxE -mulrDl.\nQed.\n\nLemma mulmxDr m n p (A : 'M_(m, n)) (B1 B2 : 'M_(n, p)) :\n  A *m (B1 + B2) = A *m B1 + A *m B2.\nProof.\napply/matrixP=> i k; rewrite !mxE -big_split /=.\nby apply: eq_bigr => j _; rewrite mxE mulrDr.\nQed.\n\nLemma mulmxBl m n p (A1 A2 : 'M_(m, n)) (B : 'M_(n, p)) :\n  (A1 - A2) *m B = A1 *m B - A2 *m B.\nProof. by rewrite mulmxDl mulNmx. Qed.\n\nLemma mulmxBr m n p (A : 'M_(m, n)) (B1 B2 : 'M_(n, p)) :\n  A *m (B1 - B2) = A *m B1 - A *m B2.\nProof. by rewrite mulmxDr mulmxN. Qed.\n\nLemma mulmx_suml m n p (A : 'M_(n, p)) I r P (B_ : I -> 'M_(m, n)) :\n   (\\sum_(i <- r | P i) B_ i) *m A = \\sum_(i <- r | P i) B_ i *m A.\nProof.\nby apply: (big_morph (mulmx^~ A)) => [B C|]; rewrite ?mul0mx ?mulmxDl.\nQed.\n\nLemma mulmx_sumr m n p (A : 'M_(m, n)) I r P (B_ : I -> 'M_(n, p)) :\n   A *m (\\sum_(i <- r | P i) B_ i) = \\sum_(i <- r | P i) A *m B_ i.\nProof.\nby apply: (big_morph (mulmx A)) => [B C|]; rewrite ?mulmx0 ?mulmxDr.\nQed.\n\nLemma scalemxAl m n p a (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  a *: (A *m B) = (a *: A) *m B.\nProof.\napply/matrixP=> i k; rewrite !mxE big_distrr /=.\nby apply: eq_bigr => j _; rewrite mulrA mxE.\nQed.\n(* Right scaling associativity requires a commutative ring *)\n\nLemma rowE m n i (A : 'M_(m, n)) : row i A = delta_mx 0 i *m A.\nProof.\napply/rowP=> j; rewrite !mxE (bigD1 i) //= mxE !eqxx mul1r.\nby rewrite big1 ?addr0 // => i' ne_i'i; rewrite mxE /= (negbTE ne_i'i) mul0r.\nQed.\n\nLemma row_mul m n p (i : 'I_m) A (B : 'M_(n, p)) :\n  row i (A *m B) = row i A *m B.\nProof. by rewrite !rowE mulmxA. Qed.\n\nLemma mulmx_sum_row m n (u : 'rV_m) (A : 'M_(m, n)) :\n  u *m A = \\sum_i u 0 i *: row i A.\nProof.\nby apply/rowP=> j; rewrite mxE summxE; apply: eq_bigr => i _; rewrite !mxE.\nQed.\n\nLemma mul_delta_mx_cond m n p (j1 j2 : 'I_n) (i1 : 'I_m) (k2 : 'I_p) :\n  delta_mx i1 j1 *m delta_mx j2 k2 = delta_mx i1 k2 *+ (j1 == j2).\nProof.\napply/matrixP=> i k; rewrite !mxE (bigD1 j1) //=.\nrewrite mulmxnE !mxE !eqxx andbT -natrM -mulrnA !mulnb !andbA andbAC.\nby rewrite big1 ?addr0 // => j; rewrite !mxE andbC -natrM; move/negbTE->.\nQed.\n\nLemma mul_delta_mx m n p (j : 'I_n) (i : 'I_m) (k : 'I_p) :\n  delta_mx i j *m delta_mx j k = delta_mx i k.\nProof. by rewrite mul_delta_mx_cond eqxx. Qed.\n\nLemma mul_delta_mx_0 m n p (j1 j2 : 'I_n) (i1 : 'I_m) (k2 : 'I_p) :\n  j1 != j2 -> delta_mx i1 j1 *m delta_mx j2 k2 = 0.\nProof. by rewrite mul_delta_mx_cond => /negbTE->. Qed.\n\nLemma mul_diag_mx m n d (A : 'M_(m, n)) :\n  diag_mx d *m A = \\matrix_(i, j) (d 0 i * A i j).\nProof.\napply/matrixP=> i j; rewrite !mxE (bigD1 i) //= mxE eqxx big1 ?addr0 // => i'.\nby rewrite mxE eq_sym mulrnAl => /negbTE->.\nQed.\n\nLemma mul_mx_diag m n (A : 'M_(m, n)) d :\n  A *m diag_mx d = \\matrix_(i, j) (A i j * d 0 j).\nProof.\napply/matrixP=> i j; rewrite !mxE (bigD1 j) //= mxE eqxx big1 ?addr0 // => i'.\nby rewrite mxE eq_sym mulrnAr; move/negbTE->.\nQed.\n\nLemma mulmx_diag n (d e : 'rV_n) :\n  diag_mx d *m diag_mx e = diag_mx (\\row_j (d 0 j * e 0 j)).\nProof. by apply/matrixP=> i j; rewrite mul_diag_mx !mxE mulrnAr. Qed.\n\nLemma mul_scalar_mx m n a (A : 'M_(m, n)) : a%:M *m A = a *: A.\nProof.\nby rewrite -diag_const_mx mul_diag_mx; apply/matrixP=> i j; rewrite !mxE.\nQed.\n\nLemma scalar_mxM n a b : (a * b)%:M = a%:M *m b%:M :> 'M_n.\nProof. by rewrite mul_scalar_mx scale_scalar_mx. Qed.\n\nLemma mul1mx m n (A : 'M_(m, n)) : 1%:M *m A = A.\nProof. by rewrite mul_scalar_mx scale1r. Qed.\n\nLemma mulmx1 m n (A : 'M_(m, n)) : A *m 1%:M = A.\nProof.\nrewrite -diag_const_mx mul_mx_diag.\nby apply/matrixP=> i j; rewrite !mxE mulr1.\nQed.\n\nLemma mul_col_perm m n p s (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  col_perm s A *m B = A *m row_perm s^-1 B.\nProof.\napply/matrixP=> i k; rewrite !mxE (reindex_inj (@perm_inj _ s^-1)).\nby apply: eq_bigr => j _ /=; rewrite !mxE permKV.\nQed.\n\nLemma mul_row_perm m n p s (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  A *m row_perm s B = col_perm s^-1 A *m B.\nProof. by rewrite mul_col_perm invgK. Qed.\n\nLemma mul_xcol m n p j1 j2 (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  xcol j1 j2 A *m B = A *m xrow j1 j2 B.\nProof. by rewrite mul_col_perm tpermV. Qed.\n\n(* Permutation matrix *)\n\nDefinition perm_mx n s : 'M_n := row_perm s 1%:M.\n\nDefinition tperm_mx n i1 i2 : 'M_n := perm_mx (tperm i1 i2).\n\nLemma col_permE m n s (A : 'M_(m, n)) : col_perm s A = A *m perm_mx s^-1.\nProof. by rewrite mul_row_perm mulmx1 invgK. Qed.\n\nLemma row_permE m n s (A : 'M_(m, n)) : row_perm s A = perm_mx s *m A.\nProof.\nby rewrite -[perm_mx _]mul1mx mul_row_perm mulmx1 -mul_row_perm mul1mx.\nQed.\n\nLemma xcolE m n j1 j2 (A : 'M_(m, n)) : xcol j1 j2 A = A *m tperm_mx j1 j2.\nProof. by rewrite /xcol col_permE tpermV. Qed.\n\nLemma xrowE m n i1 i2 (A : 'M_(m, n)) : xrow i1 i2 A = tperm_mx i1 i2 *m A.\nProof. exact: row_permE. Qed.\n\nLemma tr_perm_mx n (s : 'S_n) : (perm_mx s)^T = perm_mx s^-1.\nProof. by rewrite -[_^T]mulmx1 tr_row_perm mul_col_perm trmx1 mul1mx. Qed.\n\nLemma tr_tperm_mx n i1 i2 : (tperm_mx i1 i2)^T = tperm_mx i1 i2 :> 'M_n.\nProof. by rewrite tr_perm_mx tpermV. Qed.\n\nLemma perm_mx1 n : perm_mx 1 = 1%:M :> 'M_n.\nProof. exact: row_perm1. Qed.\n\nLemma perm_mxM n (s t : 'S_n) : perm_mx (s * t) = perm_mx s *m perm_mx t.\nProof. by rewrite -row_permE -row_permM. Qed.\n\nDefinition is_perm_mx n (A : 'M_n) := [exists s, A == perm_mx s].\n\nLemma is_perm_mxP n (A : 'M_n) :\n  reflect (exists s, A = perm_mx s) (is_perm_mx A).\nProof. by apply: (iffP existsP) => [] [s /eqP]; exists s. Qed.\n\nLemma perm_mx_is_perm n (s : 'S_n) : is_perm_mx (perm_mx s).\nProof. by apply/is_perm_mxP; exists s. Qed.\n\nLemma is_perm_mx1 n : is_perm_mx (1%:M : 'M_n).\nProof. by rewrite -perm_mx1 perm_mx_is_perm. Qed.\n\nLemma is_perm_mxMl n (A B : 'M_n) :\n  is_perm_mx A -> is_perm_mx (A *m B) = is_perm_mx B.\nProof.\ncase/is_perm_mxP=> s ->.\napply/is_perm_mxP/is_perm_mxP=> [[t def_t] | [t ->]]; last first.\n  by exists (s * t)%g; rewrite perm_mxM.\nexists (s^-1 * t)%g.\nby rewrite perm_mxM -def_t -!row_permE -row_permM mulVg row_perm1.\nQed.\n\nLemma is_perm_mx_tr n (A : 'M_n) : is_perm_mx A^T = is_perm_mx A.\nProof.\napply/is_perm_mxP/is_perm_mxP=> [[t def_t] | [t ->]]; exists t^-1%g.\n  by rewrite -tr_perm_mx -def_t trmxK.\nby rewrite tr_perm_mx.\nQed.\n\nLemma is_perm_mxMr n (A B : 'M_n) :\n  is_perm_mx B -> is_perm_mx (A *m B) = is_perm_mx A.\nProof.\ncase/is_perm_mxP=> s ->.\nrewrite -[s]invgK -col_permE -is_perm_mx_tr tr_col_perm row_permE.\nby rewrite is_perm_mxMl (perm_mx_is_perm, is_perm_mx_tr).\nQed.\n\n(* Partial identity matrix (used in rank decomposition). *)\n\nFact pid_mx_key : unit. Proof. by []. Qed.\nDefinition pid_mx {m n} r : 'M[R]_(m, n) :=\n  \\matrix[pid_mx_key]_(i, j) ((i == j :> nat) && (i < r))%:R.\n\nLemma pid_mx_0 m n : pid_mx 0 = 0 :> 'M_(m, n).\nProof. by apply/matrixP=> i j; rewrite !mxE andbF. Qed.\n\nLemma pid_mx_1 r : pid_mx r = 1%:M :> 'M_r.\nProof. by apply/matrixP=> i j; rewrite !mxE ltn_ord andbT. Qed.\n\nLemma pid_mx_row n r : pid_mx r = row_mx 1%:M 0 :> 'M_(r, r + n).\nProof.\napply/matrixP=> i j; rewrite !mxE ltn_ord andbT.\ncase: splitP => j' ->; rewrite !mxE // .\nby rewrite eqn_leq andbC leqNgt lshift_subproof.\nQed.\n\nLemma pid_mx_col m r : pid_mx r = col_mx 1%:M 0 :> 'M_(r + m, r).\nProof.\napply/matrixP=> i j; rewrite !mxE andbC.\nby case: splitP => i' ->; rewrite !mxE // eq_sym.\nQed.\n\nLemma pid_mx_block m n r : pid_mx r = block_mx 1%:M 0 0 0 :> 'M_(r + m, r + n).\nProof.\napply/matrixP=> i j; rewrite !mxE row_mx0 andbC.\ncase: splitP => i' ->; rewrite !mxE //; case: splitP => j' ->; rewrite !mxE //=.\nby rewrite eqn_leq andbC leqNgt lshift_subproof.\nQed.\n\nLemma tr_pid_mx m n r : (pid_mx r)^T = pid_mx r :> 'M_(n, m).\nProof. by apply/matrixP=> i j; rewrite !mxE eq_sym; case: eqP => // ->. Qed.\n\nLemma pid_mx_minv m n r : pid_mx (minn m r) = pid_mx r :> 'M_(m, n).\nProof. by apply/matrixP=> i j; rewrite !mxE leq_min ltn_ord. Qed.\n \nLemma pid_mx_minh m n r : pid_mx (minn n r) = pid_mx r :> 'M_(m, n).\nProof. by apply: trmx_inj; rewrite !tr_pid_mx pid_mx_minv. Qed.\n\nLemma mul_pid_mx m n p q r :\n  (pid_mx q : 'M_(m, n)) *m (pid_mx r : 'M_(n, p)) = pid_mx (minn n (minn q r)).\nProof.\napply/matrixP=> i k; rewrite !mxE !leq_min.\nhave [le_n_i | lt_i_n] := leqP n i. \n  rewrite andbF big1 // => j _.\n  by rewrite -pid_mx_minh !mxE leq_min ltnNge le_n_i andbF mul0r.\nrewrite (bigD1 (Ordinal lt_i_n)) //= big1 ?addr0 => [|j].\n  by rewrite !mxE eqxx /= -natrM mulnb andbCA.\nby rewrite -val_eqE /= !mxE eq_sym -natrM => /negbTE->.\nQed.\n\nLemma pid_mx_id m n p r :\n  r <= n -> (pid_mx r : 'M_(m, n)) *m (pid_mx r : 'M_(n, p)) = pid_mx r.\nProof. by move=> le_r_n; rewrite mul_pid_mx minnn (minn_idPr _). Qed.\n\nDefinition copid_mx {n} r : 'M_n := 1%:M - pid_mx r.\n\nLemma mul_copid_mx_pid m n r :\n  r <= m -> copid_mx r *m pid_mx r = 0 :> 'M_(m, n).\nProof. by move=> le_r_m; rewrite mulmxBl mul1mx pid_mx_id ?subrr. Qed.\n\nLemma mul_pid_mx_copid m n r :\n  r <= n -> pid_mx r *m copid_mx r = 0 :> 'M_(m, n).\nProof. by move=> le_r_n; rewrite mulmxBr mulmx1 pid_mx_id ?subrr. Qed.\n\nLemma copid_mx_id n r :\n  r <= n -> copid_mx r *m copid_mx r = copid_mx r :> 'M_n.\nProof.\nby move=> le_r_n; rewrite mulmxBl mul1mx mul_pid_mx_copid // oppr0 addr0.\nQed.\n\n(* Block products; we cover all 1 x 2, 2 x 1, and 2 x 2 block products. *)\nLemma mul_mx_row m n p1 p2 (A : 'M_(m, n)) (Bl : 'M_(n, p1)) (Br : 'M_(n, p2)) :\n  A *m row_mx Bl Br = row_mx (A *m Bl) (A *m Br).\nProof.\napply/matrixP=> i k; rewrite !mxE.\nby case defk: (split k); rewrite mxE; apply: eq_bigr => j _; rewrite mxE defk.\nQed.\n\nLemma mul_col_mx m1 m2 n p (Au : 'M_(m1, n)) (Ad : 'M_(m2, n)) (B : 'M_(n, p)) :\n  col_mx Au Ad *m B = col_mx (Au *m B) (Ad *m B).\nProof.\napply/matrixP=> i k; rewrite !mxE.\nby case defi: (split i); rewrite mxE; apply: eq_bigr => j _; rewrite mxE defi.\nQed.\n\nLemma mul_row_col m n1 n2 p (Al : 'M_(m, n1)) (Ar : 'M_(m, n2))\n                            (Bu : 'M_(n1, p)) (Bd : 'M_(n2, p)) :\n  row_mx Al Ar *m col_mx Bu Bd = Al *m Bu + Ar *m Bd.\nProof.\napply/matrixP=> i k; rewrite !mxE big_split_ord /=.\ncongr (_ + _); apply: eq_bigr => j _; first by rewrite row_mxEl col_mxEu.\nby rewrite row_mxEr col_mxEd.\nQed.\n\nLemma mul_col_row m1 m2 n p1 p2 (Au : 'M_(m1, n)) (Ad : 'M_(m2, n))\n                                (Bl : 'M_(n, p1)) (Br : 'M_(n, p2)) :\n  col_mx Au Ad *m row_mx Bl Br\n     = block_mx (Au *m Bl) (Au *m Br) (Ad *m Bl) (Ad *m Br).\nProof. by rewrite mul_col_mx !mul_mx_row. Qed.\n\nLemma mul_row_block m n1 n2 p1 p2 (Al : 'M_(m, n1)) (Ar : 'M_(m, n2))\n                                  (Bul : 'M_(n1, p1)) (Bur : 'M_(n1, p2))\n                                  (Bdl : 'M_(n2, p1)) (Bdr : 'M_(n2, p2)) :\n  row_mx Al Ar *m block_mx Bul Bur Bdl Bdr\n   = row_mx (Al *m Bul + Ar *m Bdl) (Al *m Bur + Ar *m Bdr).\nProof. by rewrite block_mxEh mul_mx_row !mul_row_col. Qed.\n\nLemma mul_block_col m1 m2 n1 n2 p (Aul : 'M_(m1, n1)) (Aur : 'M_(m1, n2))\n                                  (Adl : 'M_(m2, n1)) (Adr : 'M_(m2, n2))\n                                  (Bu : 'M_(n1, p)) (Bd : 'M_(n2, p)) :\n  block_mx Aul Aur Adl Adr *m col_mx Bu Bd\n   = col_mx (Aul *m Bu + Aur *m Bd) (Adl *m Bu + Adr *m Bd).\nProof. by rewrite mul_col_mx !mul_row_col. Qed.\n\nLemma mulmx_block m1 m2 n1 n2 p1 p2 (Aul : 'M_(m1, n1)) (Aur : 'M_(m1, n2))\n                                    (Adl : 'M_(m2, n1)) (Adr : 'M_(m2, n2))\n                                    (Bul : 'M_(n1, p1)) (Bur : 'M_(n1, p2))\n                                    (Bdl : 'M_(n2, p1)) (Bdr : 'M_(n2, p2)) :\n  block_mx Aul Aur Adl Adr *m block_mx Bul Bur Bdl Bdr\n    = block_mx (Aul *m Bul + Aur *m Bdl) (Aul *m Bur + Aur *m Bdr)\n               (Adl *m Bul + Adr *m Bdl) (Adl *m Bur + Adr *m Bdr).\nProof. by rewrite mul_col_mx !mul_row_block. Qed.\n\n(* Correspondance between matrices and linear function on row vectors. *) \nSection LinRowVector.\n\nVariables m n : nat.\n\nFact lin1_mx_key : unit. Proof. by []. Qed.\nDefinition lin1_mx (f : 'rV[R]_m -> 'rV[R]_n) :=\n  \\matrix[lin1_mx_key]_(i, j) f (delta_mx 0 i) 0 j.\n\nVariable f : {linear 'rV[R]_m -> 'rV[R]_n}.\n\nLemma mul_rV_lin1 u : u *m lin1_mx f = f u.\nProof.\nrewrite {2}[u]matrix_sum_delta big_ord1 linear_sum; apply/rowP=> i.\nby rewrite mxE summxE; apply: eq_bigr => j _; rewrite linearZ !mxE.\nQed.\n\nEnd LinRowVector.\n\n(* Correspondance between matrices and linear function on matrices. *) \nSection LinMatrix.\n\nVariables m1 n1 m2 n2 : nat.\n\nDefinition lin_mx (f : 'M[R]_(m1, n1) -> 'M[R]_(m2, n2)) :=\n  lin1_mx (mxvec \\o f \\o vec_mx).\n\nVariable f : {linear 'M[R]_(m1, n1) -> 'M[R]_(m2, n2)}.\n\nLemma mul_rV_lin u : u *m lin_mx f = mxvec (f (vec_mx u)).\nProof. exact: mul_rV_lin1. Qed.\n\nLemma mul_vec_lin A : mxvec A *m lin_mx f = mxvec (f A).\nProof. by rewrite mul_rV_lin mxvecK. Qed.\n\nLemma mx_rV_lin u : vec_mx (u *m lin_mx f) = f (vec_mx u).\nProof. by rewrite mul_rV_lin mxvecK. Qed.\n\nLemma mx_vec_lin A : vec_mx (mxvec A *m lin_mx f) = f A.\nProof. by rewrite mul_rV_lin !mxvecK. Qed.\n\nEnd LinMatrix.\n\nCanonical mulmx_additive m n p A := Additive (@mulmxBr m n p A).\n\nSection Mulmxr.\n\nVariables m n p : nat.\nImplicit Type A : 'M[R]_(m, n).\nImplicit Type B : 'M[R]_(n, p).\n\nDefinition mulmxr_head t B A := let: tt := t in A *m B.\nLocal Notation mulmxr := (mulmxr_head tt).\n\nDefinition lin_mulmxr B := lin_mx (mulmxr B).\n\nLemma mulmxr_is_linear B : linear (mulmxr B).\nProof. by move=> a A1 A2; rewrite /= mulmxDl scalemxAl. Qed.\nCanonical mulmxr_additive B := Additive (mulmxr_is_linear B).\nCanonical mulmxr_linear B := Linear (mulmxr_is_linear B).\n\nLemma lin_mulmxr_is_linear : linear lin_mulmxr.\nProof.\nmove=> a A B; apply/row_matrixP; case/mxvec_indexP=> i j.\nrewrite linearP /= !rowE !mul_rV_lin /= vec_mx_delta -linearP mulmxDr.\ncongr (mxvec (_ + _)); apply/row_matrixP=> k.\nrewrite linearZ /= !row_mul rowE mul_delta_mx_cond.\nby case: (k == i); [rewrite -!rowE linearZ | rewrite !mul0mx raddf0]. \nQed.\nCanonical lin_mulmxr_additive := Additive lin_mulmxr_is_linear.\nCanonical lin_mulmxr_linear := Linear lin_mulmxr_is_linear.\n\nEnd Mulmxr.\n\n(* The trace. *)\nSection Trace.\n\nVariable n : nat.\n\nDefinition mxtrace (A : 'M[R]_n) := \\sum_i A i i.\nLocal Notation \"'\\tr' A\" := (mxtrace A) : ring_scope.\n\nLemma mxtrace_tr A : \\tr A^T = \\tr A.\nProof. by apply: eq_bigr=> i _; rewrite mxE. Qed.\n\nLemma mxtrace_is_scalar : scalar mxtrace.\nProof.\nmove=> a A B; rewrite mulr_sumr -big_split /=; apply: eq_bigr=> i _.\nby rewrite !mxE.\nQed.\nCanonical mxtrace_additive := Additive mxtrace_is_scalar.\nCanonical mxtrace_linear := Linear mxtrace_is_scalar.\n\nLemma mxtrace0 : \\tr 0 = 0. Proof. exact: raddf0. Qed.\nLemma mxtraceD A B : \\tr (A + B) = \\tr A + \\tr B. Proof. exact: raddfD. Qed.\nLemma mxtraceZ a A : \\tr (a *: A) = a * \\tr A. Proof. exact: scalarZ. Qed.\n\nLemma mxtrace_diag D : \\tr (diag_mx D) = \\sum_j D 0 j.\nProof. by apply: eq_bigr => j _; rewrite mxE eqxx. Qed.\n\nLemma mxtrace_scalar a : \\tr a%:M = a *+ n.\nProof.\nrewrite -diag_const_mx mxtrace_diag.\nby rewrite (eq_bigr _ (fun j _ => mxE _ _ 0 j)) sumr_const card_ord.\nQed.\n\nLemma mxtrace1 : \\tr 1%:M = n%:R. Proof. exact: mxtrace_scalar. Qed.\n\nEnd Trace.\nLocal Notation \"'\\tr' A\" := (mxtrace A) : ring_scope.\n\nLemma trace_mx11 (A : 'M_1) : \\tr A = A 0 0.\nProof. by rewrite {1}[A]mx11_scalar mxtrace_scalar. Qed.\n\nLemma mxtrace_block n1 n2 (Aul : 'M_n1) Aur Adl (Adr : 'M_n2) :\n  \\tr (block_mx Aul Aur Adl Adr) = \\tr Aul + \\tr Adr.\nProof.\nrewrite /(\\tr _) big_split_ord /=.\nby congr (_ + _); apply: eq_bigr => i _; rewrite (block_mxEul, block_mxEdr).\nQed.\n\n(* The matrix ring structure requires a strutural condition (dimension of the *)\n(* form n.+1) to statisfy the nontriviality condition we have imposed.        *)\nSection MatrixRing.\n\nVariable n' : nat.\nLocal Notation n := n'.+1.\n\nLemma matrix_nonzero1 : 1%:M != 0 :> 'M_n.\nProof. by apply/eqP=> /matrixP/(_ 0 0)/eqP; rewrite !mxE oner_eq0. Qed.\n\nDefinition matrix_ringMixin :=\n  RingMixin (@mulmxA n n n n) (@mul1mx n n) (@mulmx1 n n)\n            (@mulmxDl n n n) (@mulmxDr n n n) matrix_nonzero1.\n\nCanonical matrix_ringType := Eval hnf in RingType 'M[R]_n matrix_ringMixin.\nCanonical matrix_lAlgType := Eval hnf in LalgType R 'M[R]_n (@scalemxAl n n n).\n\nLemma mulmxE : mulmx = *%R. Proof. by []. Qed.\nLemma idmxE : 1%:M = 1 :> 'M_n. Proof. by []. Qed.\n\nLemma scalar_mx_is_multiplicative : multiplicative (@scalar_mx n).\nProof. by split=> //; exact: scalar_mxM. Qed.\nCanonical scalar_mx_rmorphism := AddRMorphism scalar_mx_is_multiplicative.\n\nEnd MatrixRing.\n\nSection LiftPerm.\n\n(* Block expresssion of a lifted permutation matrix, for the Cormen LUP. *)\n\nVariable n : nat.\n\n(* These could be in zmodp, but that would introduce a dependency on perm. *)\n\nDefinition lift0_perm s : 'S_n.+1 := lift_perm 0 0 s.\n\nLemma lift0_perm0 s : lift0_perm s 0 = 0.\nProof. exact: lift_perm_id. Qed.\n\nLemma lift0_perm_lift s k' :\n  lift0_perm s (lift 0 k') = lift (0 : 'I_n.+1) (s k').\nProof. exact: lift_perm_lift. Qed.\n\nLemma lift0_permK s : cancel (lift0_perm s) (lift0_perm s^-1).\nProof. by move=> i; rewrite /lift0_perm -lift_permV permK. Qed.\n\nLemma lift0_perm_eq0 s i : (lift0_perm s i == 0) = (i == 0).\nProof. by rewrite (canF_eq (lift0_permK s)) lift0_perm0. Qed.\n\n(* Block expresssion of a lifted permutation matrix *)\n\nDefinition lift0_mx A : 'M_(1 + n) := block_mx 1 0 0 A.\n\nLemma lift0_mx_perm s : lift0_mx (perm_mx s) = perm_mx (lift0_perm s).\nProof.\napply/matrixP=> /= i j; rewrite !mxE split1 /=; case: unliftP => [i'|] -> /=.\n  rewrite lift0_perm_lift !mxE split1 /=.\n  by case: unliftP => [j'|] ->; rewrite ?(inj_eq (@lift_inj _ _)) /= !mxE.\nrewrite lift0_perm0 !mxE split1 /=.\nby case: unliftP => [j'|] ->; rewrite /= mxE.\nQed.\n\nLemma lift0_mx_is_perm s : is_perm_mx (lift0_mx (perm_mx s)).\nProof. by rewrite lift0_mx_perm perm_mx_is_perm. Qed.\n\nEnd LiftPerm.\n\n(* Determinants and adjugates are defined here, but most of their properties *)\n(* only hold for matrices over a commutative ring, so their theory is        *)\n(* deferred to that section.                                                 *)\n\n(* The determinant, in one line with the Leibniz Formula *)\nDefinition determinant n (A : 'M_n) : R :=\n  \\sum_(s : 'S_n) (-1) ^+ s * \\prod_i A i (s i).\n\n(* The cofactor of a matrix on the indexes i and j *)\nDefinition cofactor n A (i j : 'I_n) : R :=\n  (-1) ^+ (i + j) * determinant (row' i (col' j A)).\n\n(* The adjugate matrix : defined as the transpose of the matrix of cofactors *)\nFact adjugate_key : unit. Proof. by []. Qed.\nDefinition adjugate n (A : 'M_n) := \\matrix[adjugate_key]_(i, j) cofactor A j i.\n\nEnd MatrixAlgebra.\n\nImplicit Arguments delta_mx [R m n].\nImplicit Arguments scalar_mx [R n].\nImplicit Arguments perm_mx [R n].\nImplicit Arguments tperm_mx [R n].\nImplicit Arguments pid_mx [R m n].\nImplicit Arguments copid_mx [R n].\nImplicit Arguments lin_mulmxr [R m n p].\nPrenex Implicits delta_mx diag_mx scalar_mx is_scalar_mx perm_mx tperm_mx.\nPrenex Implicits pid_mx copid_mx mulmx lin_mulmxr.\nPrenex Implicits mxtrace determinant cofactor adjugate.\n\nImplicit Arguments is_scalar_mxP [R n A].\nImplicit Arguments mul_delta_mx [R m n p].\nPrenex Implicits mul_delta_mx.\n\nNotation \"a %:M\" := (scalar_mx a) : ring_scope.\nNotation \"A *m B\" := (mulmx A B) : ring_scope.\nNotation mulmxr := (mulmxr_head tt).\nNotation \"\\tr A\" := (mxtrace A) : ring_scope.\nNotation \"'\\det' A\" := (determinant A) : ring_scope.\nNotation \"'\\adj' A\" := (adjugate A) : ring_scope.\n\n(* Non-commutative transpose requires multiplication in the converse ring.   *)\nLemma trmx_mul_rev (R : ringType) m n p (A : 'M[R]_(m, n)) (B : 'M[R]_(n, p)) :\n  (A *m B)^T = (B : 'M[R^c]_(n, p))^T *m (A : 'M[R^c]_(m, n))^T.\nProof.\nby apply/matrixP=> k i; rewrite !mxE; apply: eq_bigr => j _; rewrite !mxE.\nQed.\n\nCanonical matrix_finRingType (R : finRingType) n' :=\n  Eval hnf in [finRingType of 'M[R]_n'.+1].\n\n(* Parametricity over the algebra structure. *)\nSection MapRingMatrix.\n\nVariables (aR rR : ringType) (f : {rmorphism aR -> rR}).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\n\nSection FixedSize.\n\nVariables m n p : nat.\nImplicit Type A : 'M[aR]_(m, n).\n\nLemma map_mxZ a A : (a *: A)^f = f a *: A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE rmorphM. Qed.\n\nLemma map_mxM A B : (A *m B)^f = A^f *m B^f :> 'M_(m, p).\nProof.\napply/matrixP=> i k; rewrite !mxE rmorph_sum //.\nby apply: eq_bigr => j; rewrite !mxE rmorphM.\nQed.\n\nLemma map_delta_mx i j : (delta_mx i j)^f = delta_mx i j :> 'M_(m, n).\nProof. by apply/matrixP=> i' j'; rewrite !mxE rmorph_nat. Qed.\n\nLemma map_diag_mx d : (diag_mx d)^f = diag_mx d^f :> 'M_n.\nProof. by apply/matrixP=> i j; rewrite !mxE rmorphMn. Qed.\n\nLemma map_scalar_mx a : a%:M^f = (f a)%:M :> 'M_n.\nProof. by apply/matrixP=> i j; rewrite !mxE rmorphMn. Qed.\n\nLemma map_mx1 : 1%:M^f = 1%:M :> 'M_n.\nProof. by rewrite map_scalar_mx rmorph1. Qed.\n\nLemma map_perm_mx (s : 'S_n) : (perm_mx s)^f = perm_mx s.\nProof. by apply/matrixP=> i j; rewrite !mxE rmorph_nat. Qed.\n\nLemma map_tperm_mx (i1 i2 : 'I_n) : (tperm_mx i1 i2)^f = tperm_mx i1 i2.\nProof. exact: map_perm_mx. Qed.\n\nLemma map_pid_mx r : (pid_mx r)^f = pid_mx r :> 'M_(m, n).\nProof. by apply/matrixP=> i j; rewrite !mxE rmorph_nat. Qed.\n\nLemma trace_map_mx (A : 'M_n) : \\tr A^f = f (\\tr A).\nProof. by rewrite rmorph_sum; apply: eq_bigr => i _; rewrite mxE. Qed.\n\nLemma det_map_mx n' (A : 'M_n') : \\det A^f = f (\\det A).\nProof.\nrewrite rmorph_sum //; apply: eq_bigr => s _.\nrewrite rmorphM rmorph_sign rmorph_prod; congr (_ * _).\nby apply: eq_bigr => i _; rewrite mxE.\nQed.\n\nLemma cofactor_map_mx (A : 'M_n) i j : cofactor A^f i j = f (cofactor A i j).\nProof. by rewrite rmorphM rmorph_sign -det_map_mx map_row' map_col'. Qed.\n\nLemma map_mx_adj (A : 'M_n) : (\\adj A)^f = \\adj A^f.\nProof. by apply/matrixP=> i j; rewrite !mxE cofactor_map_mx. Qed.\n\nEnd FixedSize.\n\nLemma map_copid_mx n r : (copid_mx r)^f = copid_mx r :> 'M_n.\nProof. by rewrite map_mx_sub map_mx1 map_pid_mx. Qed.\n\nLemma map_mx_is_multiplicative n' (n := n'.+1) :\n  multiplicative ((map_mx f) n n).\nProof. by split; [exact: map_mxM | exact: map_mx1]. Qed.\n\nCanonical map_mx_rmorphism n' := AddRMorphism (map_mx_is_multiplicative n').\n\nLemma map_lin1_mx m n (g : 'rV_m -> 'rV_n) gf :\n  (forall v, (g v)^f = gf v^f) -> (lin1_mx g)^f = lin1_mx gf.\nProof.\nby move=> def_gf; apply/matrixP=> i j; rewrite !mxE -map_delta_mx -def_gf mxE.\nQed.\n\nLemma map_lin_mx m1 n1 m2 n2 (g : 'M_(m1, n1) -> 'M_(m2, n2)) gf : \n  (forall A, (g A)^f = gf A^f) -> (lin_mx g)^f = lin_mx gf.\nProof.\nmove=> def_gf; apply: map_lin1_mx => A /=.\nby rewrite map_mxvec def_gf map_vec_mx.\nQed.\n\nEnd MapRingMatrix.\n\nSection ComMatrix.\n(* Lemmas for matrices with coefficients in a commutative ring *)\nVariable R : comRingType.\n\nSection AssocLeft.\n\nVariables m n p : nat.\nImplicit Type A : 'M[R]_(m, n).\nImplicit Type B : 'M[R]_(n, p).\n\nLemma trmx_mul A B : (A *m B)^T = B^T *m A^T.\nProof.\nrewrite trmx_mul_rev; apply/matrixP=> k i; rewrite !mxE.\nby apply: eq_bigr => j _; rewrite mulrC.\nQed.\n\nLemma scalemxAr a A B : a *: (A *m B) = A *m (a *: B).\nProof. by apply: trmx_inj; rewrite trmx_mul !linearZ /= trmx_mul scalemxAl. Qed.\n\nLemma mulmx_is_scalable A : scalable (@mulmx _ m n p A).\nProof. by move=> a B; rewrite scalemxAr. Qed.\nCanonical mulmx_linear A := AddLinear (mulmx_is_scalable A).\n\nDefinition lin_mulmx A : 'M[R]_(n * p, m * p) := lin_mx (mulmx A).\n\nLemma lin_mulmx_is_linear : linear lin_mulmx.\nProof.\nmove=> a A B; apply/row_matrixP=> i; rewrite linearP /= !rowE !mul_rV_lin /=.\nby rewrite [_ *m _](linearP (mulmxr_linear _ _)) linearP.\nQed.\nCanonical lin_mulmx_additive := Additive lin_mulmx_is_linear.\nCanonical lin_mulmx_linear := Linear lin_mulmx_is_linear.\n\nEnd AssocLeft.\n\nSection LinMulRow.\n\nVariables m n : nat.\n\nDefinition lin_mul_row u : 'M[R]_(m * n, n) := lin1_mx (mulmx u \\o vec_mx).\n\nLemma lin_mul_row_is_linear : linear lin_mul_row.\nProof.\nmove=> a u v; apply/row_matrixP=> i; rewrite linearP /= !rowE !mul_rV_lin1 /=.\nby rewrite [_ *m _](linearP (mulmxr_linear _ _)).\nQed.\nCanonical lin_mul_row_additive := Additive lin_mul_row_is_linear.\nCanonical lin_mul_row_linear := Linear lin_mul_row_is_linear.\n\nLemma mul_vec_lin_row A u : mxvec A *m lin_mul_row u = u *m A.\nProof. by rewrite mul_rV_lin1 /= mxvecK. Qed.\n\nEnd LinMulRow.\n\nLemma mxvec_dotmul m n (A : 'M[R]_(m, n)) u v :\n  mxvec (u^T *m v) *m (mxvec A)^T = u *m A *m v^T.\nProof.\ntransitivity (\\sum_i \\sum_j (u 0 i * A i j *: row j v^T)).\n  apply/rowP=> i; rewrite {i}ord1 mxE (reindex _ (curry_mxvec_bij _ _)) /=.\n  rewrite pair_bigA summxE; apply: eq_bigr => [[i j]] /= _.\n  by rewrite !mxE !mxvecE mxE big_ord1 mxE mulrAC.\nrewrite mulmx_sum_row exchange_big; apply: eq_bigr => j _ /=.\nby rewrite mxE -scaler_suml.\nQed.\n\nSection MatrixAlgType.\n\nVariable n' : nat.\nLocal Notation n := n'.+1.\n\nCanonical matrix_algType :=\n  Eval hnf in AlgType R 'M[R]_n (fun k => scalemxAr k).\n\nEnd MatrixAlgType.\n\nLemma diag_mxC n (d e : 'rV[R]_n) :\n  diag_mx d *m diag_mx e = diag_mx e *m diag_mx d.\nProof.\nby rewrite !mulmx_diag; congr (diag_mx _); apply/rowP=> i; rewrite !mxE mulrC.\nQed.\n\nLemma diag_mx_comm n' (d e : 'rV[R]_n'.+1) : GRing.comm (diag_mx d) (diag_mx e).\nProof. exact: diag_mxC. Qed.\n\nLemma scalar_mxC m n a (A : 'M[R]_(m, n)) : A *m a%:M = a%:M *m A.\nProof.\nby apply: trmx_inj; rewrite trmx_mul tr_scalar_mx !mul_scalar_mx linearZ.\nQed.\n\nLemma scalar_mx_comm n' a (A : 'M[R]_n'.+1) : GRing.comm A a%:M.\nProof. exact: scalar_mxC. Qed.\n\nLemma mul_mx_scalar m n a (A : 'M[R]_(m, n)) : A *m a%:M = a *: A.\nProof. by rewrite scalar_mxC mul_scalar_mx. Qed.\n\nLemma mxtrace_mulC m n (A : 'M[R]_(m, n)) (B : 'M_(n, m)) :\n  \\tr (A *m B) = \\tr (B *m A).\nProof.\ntransitivity (\\sum_i \\sum_j A i j * B j i).\n  by apply: eq_bigr => i _; rewrite mxE.\nrewrite exchange_big; apply: eq_bigr => i _ /=; rewrite mxE.\napply: eq_bigr => j _; exact: mulrC.\nQed.\n\n(* The theory of determinants *)\n\nLemma determinant_multilinear n (A B C : 'M[R]_n) i0 b c :\n    row i0 A = b *: row i0 B + c *: row i0 C ->\n    row' i0 B = row' i0 A ->\n    row' i0 C = row' i0 A ->\n  \\det A = b * \\det B + c * \\det C.\nProof.\nrewrite -[_ + _](row_id 0); move/row_eq=> ABC.\nmove/row'_eq=> BA; move/row'_eq=> CA.\nrewrite !big_distrr -big_split; apply: eq_bigr => s _ /=.\nrewrite -!(mulrCA (_ ^+s)) -mulrDr; congr (_ * _).\nrewrite !(bigD1 i0 (_ : predT i0)) //= {}ABC !mxE mulrDl !mulrA.\nby congr (_ * _ + _ * _); apply: eq_bigr => i i0i; rewrite ?BA ?CA.\nQed.\n\nLemma determinant_alternate n (A : 'M[R]_n) i1 i2 :\n  i1 != i2 -> A i1 =1 A i2 -> \\det A = 0.\nProof.\nmove=> neq_i12 eqA12; pose t := tperm i1 i2.\nhave oddMt s: (t * s)%g = ~~ s :> bool by rewrite odd_permM odd_tperm neq_i12.\nrewrite [\\det A](bigID (@odd_perm _)) /=.\napply: canLR (subrK _) _; rewrite add0r -sumrN.\nrewrite (reindex_inj (mulgI t)); apply: eq_big => //= s.\nrewrite oddMt => /negPf->; rewrite mulN1r mul1r; congr (- _).\nrewrite (reindex_inj (@perm_inj _ t)); apply: eq_bigr => /= i _.\nby rewrite permM tpermK /t; case: tpermP => // ->; rewrite eqA12.\nQed.\n\nLemma det_tr n (A : 'M[R]_n) : \\det A^T = \\det A.\nProof.\nrewrite [\\det A^T](reindex_inj (@invg_inj _)) /=.\napply: eq_bigr => s _ /=; rewrite !odd_permV (reindex_inj (@perm_inj _ s)) /=.\nby congr (_ * _); apply: eq_bigr => i _; rewrite mxE permK.\nQed.\n\nLemma det_perm n (s : 'S_n) : \\det (perm_mx s) = (-1) ^+ s :> R.\nProof.\nrewrite [\\det _](bigD1 s) //= big1 => [|i _]; last by rewrite /= !mxE eqxx.\nrewrite mulr1 big1 ?addr0 => //= t Dst.\ncase: (pickP (fun i => s i != t i)) => [i ist | Est].\n  by rewrite (bigD1 i) // mulrCA /= !mxE (negbTE ist) mul0r.\nby case/eqP: Dst; apply/permP => i; move/eqP: (Est i).\nQed.\n\nLemma det1 n : \\det (1%:M : 'M[R]_n) = 1.\nProof. by rewrite -perm_mx1 det_perm odd_perm1. Qed.\n\nLemma det_mx00 (A : 'M[R]_0) : \\det A = 1.\nProof. by rewrite flatmx0 -(flatmx0 1%:M) det1. Qed.\n\nLemma detZ n a (A : 'M[R]_n) : \\det (a *: A) = a ^+ n * \\det A.\nProof.\nrewrite big_distrr /=; apply: eq_bigr => s _; rewrite mulrCA; congr (_ * _).\nrewrite -[n in a ^+ n]card_ord -prodr_const -big_split /=.\nby apply: eq_bigr=> i _; rewrite mxE.\nQed.\n\nLemma det0 n' : \\det (0 : 'M[R]_n'.+1) = 0.\nProof. by rewrite -(scale0r 0) detZ exprS !mul0r. Qed.\n\nLemma det_scalar n a : \\det (a%:M : 'M[R]_n) = a ^+ n.\nProof. by rewrite -{1}(mulr1 a) -scale_scalar_mx detZ det1 mulr1. Qed.\n\nLemma det_scalar1 a : \\det (a%:M : 'M[R]_1) = a.\nProof. exact: det_scalar. Qed.\n\nLemma det_mulmx n (A B : 'M[R]_n) : \\det (A *m B) = \\det A * \\det B.\nProof.\nrewrite big_distrl /=.\npose F := ('I_n ^ n)%type; pose AB s i j := A i j * B j (s i).\ntransitivity (\\sum_(f : F) \\sum_(s : 'S_n) (-1) ^+ s * \\prod_i AB s i (f i)).\n  rewrite exchange_big; apply: eq_bigr => /= s _; rewrite -big_distrr /=.\n  congr (_ * _); rewrite -(bigA_distr_bigA (AB s)) /=.\n  by apply: eq_bigr => x _; rewrite mxE.\nrewrite (bigID (fun f : F => injectiveb f)) /= addrC big1 ?add0r => [|f Uf].\n  rewrite (reindex (@pval _)) /=; last first.\n    pose in_Sn := insubd (1%g : 'S_n).\n    by exists in_Sn => /= f Uf; first apply: val_inj; exact: insubdK.\n  apply: eq_big => /= [s | s _]; rewrite ?(valP s) // big_distrr /=.\n  rewrite (reindex_inj (mulgI s)); apply: eq_bigr => t _ /=.\n  rewrite big_split /= mulrA mulrCA mulrA mulrCA mulrA.\n  rewrite -signr_addb odd_permM !pvalE; congr (_ * _); symmetry.\n  by rewrite (reindex_inj (@perm_inj _ s)); apply: eq_bigr => i; rewrite permM.\ntransitivity (\\det (\\matrix_(i, j) B (f i) j) * \\prod_i A i (f i)).\n  rewrite mulrC big_distrr /=; apply: eq_bigr => s _.\n  rewrite mulrCA big_split //=; congr (_ * (_ * _)).\n  by apply: eq_bigr => x _; rewrite mxE.\ncase/injectivePn: Uf => i1 [i2 Di12 Ef12].\nby rewrite (determinant_alternate Di12) ?simp //= => j; rewrite !mxE Ef12.\nQed.\n\nLemma detM n' (A B : 'M[R]_n'.+1) : \\det (A * B) = \\det A * \\det B.\nProof. exact: det_mulmx. Qed.\n\nLemma det_diag n (d : 'rV[R]_n) : \\det (diag_mx d) = \\prod_i d 0 i.\nProof.\nrewrite /(\\det _) (bigD1 1%g) //= addrC big1 => [|p p1].\n  by rewrite add0r odd_perm1 mul1r; apply: eq_bigr => i; rewrite perm1 mxE eqxx.\nhave{p1}: ~~ perm_on set0 p.\n  apply: contra p1; move/subsetP=> p1; apply/eqP; apply/permP=> i.\n  by rewrite perm1; apply/eqP; apply/idPn; move/p1; rewrite inE.\ncase/subsetPn=> i; rewrite !inE eq_sym; move/negbTE=> p_i _.\nby rewrite (bigD1 i) //= mulrCA mxE p_i mul0r.\nQed.\n\n(* Laplace expansion lemma *)\nLemma expand_cofactor n (A : 'M[R]_n) i j :\n  cofactor A i j =\n    \\sum_(s : 'S_n | s i == j) (-1) ^+ s * \\prod_(k | i != k) A k (s k).\nProof.\ncase: n A i j => [|n] A i0 j0; first by case: i0.\nrewrite (reindex (lift_perm i0 j0)); last first.\n  pose ulsf i (s : 'S_n.+1) k := odflt k (unlift (s i) (s (lift i k))).\n  have ulsfK i (s : 'S_n.+1) k: lift (s i) (ulsf i s k) = s (lift i k).\n    rewrite /ulsf; have:= neq_lift i k.\n    by rewrite -(inj_eq (@perm_inj _ s)) => /unlift_some[] ? ? ->.\n  have inj_ulsf: injective (ulsf i0 _).\n    move=> s; apply: can_inj (ulsf (s i0) s^-1%g) _ => k'.\n    by rewrite {1}/ulsf ulsfK !permK liftK.\n  exists (fun s => perm (inj_ulsf s)) => [s _ | s].\n    by apply/permP=> k'; rewrite permE /ulsf lift_perm_lift lift_perm_id liftK.\n  move/(s _ =P _) => si0; apply/permP=> k.\n  case: (unliftP i0 k) => [k'|] ->; rewrite ?lift_perm_id //.\n  by rewrite lift_perm_lift -si0 permE ulsfK.\nrewrite /cofactor big_distrr /=.\napply: eq_big => [s | s _]; first by rewrite lift_perm_id eqxx.\nrewrite -signr_odd mulrA -signr_addb odd_add -odd_lift_perm; congr (_ * _).\ncase: (pickP 'I_n) => [k0 _ | n0]; last first.\n  by rewrite !big1 // => [j /unlift_some[i] | i _]; have:= n0 i.\nrewrite (reindex (lift i0)).\n  by apply: eq_big => [k | k _] /=; rewrite ?neq_lift // !mxE lift_perm_lift.\nexists (fun k => odflt k0 (unlift i0 k)) => k; first by rewrite liftK.\nby case/unlift_some=> k' -> ->.\nQed.\n\nLemma expand_det_row n (A : 'M[R]_n) i0 :\n  \\det A = \\sum_j A i0 j * cofactor A i0 j.\nProof.\nrewrite /(\\det A) (partition_big (fun s : 'S_n => s i0) predT) //=.\napply: eq_bigr => j0 _; rewrite expand_cofactor big_distrr /=.\napply: eq_bigr => s /eqP Dsi0.\nrewrite mulrCA (bigID (pred1 i0)) /= big_pred1_eq Dsi0; congr (_ * (_ * _)).\nby apply: eq_bigl => i; rewrite eq_sym.\nQed.\n\nLemma cofactor_tr n (A : 'M[R]_n) i j : cofactor A^T i j = cofactor A j i.\nProof.\nrewrite /cofactor addnC; congr (_ * _).\nrewrite -tr_row' -tr_col' det_tr; congr (\\det _).\nby apply/matrixP=> ? ?; rewrite !mxE.\nQed.\n\nLemma cofactorZ n a (A : 'M[R]_n) i j : \n  cofactor (a *: A) i j = a ^+ n.-1 * cofactor A i j.\nProof. by rewrite {1}/cofactor !linearZ detZ mulrCA mulrA. Qed.\n\nLemma expand_det_col n (A : 'M[R]_n) j0 :\n  \\det A = \\sum_i (A i j0 * cofactor A i j0).\nProof.\nrewrite -det_tr (expand_det_row _ j0).\nby apply: eq_bigr => i _; rewrite cofactor_tr mxE.\nQed.\n\nLemma trmx_adj n (A : 'M[R]_n) : (\\adj A)^T = \\adj A^T.\nProof. by apply/matrixP=> i j; rewrite !mxE cofactor_tr. Qed.\n\nLemma adjZ n a (A : 'M[R]_n) : \\adj (a *: A) = a^+n.-1 *: \\adj A.\nProof. by apply/matrixP=> i j; rewrite !mxE cofactorZ. Qed.\n\n(* Cramer Rule : adjugate on the left *)\nLemma mul_mx_adj n (A : 'M[R]_n) : A *m \\adj A = (\\det A)%:M.\nProof.\napply/matrixP=> i1 i2; rewrite !mxE; case Di: (i1 == i2).\n  rewrite (eqP Di) (expand_det_row _ i2) //=.\n  by apply: eq_bigr => j _; congr (_ * _); rewrite mxE.\npose B := \\matrix_(i, j) (if i == i2 then A i1 j else A i j).\nhave EBi12: B i1 =1 B i2 by move=> j; rewrite /= !mxE Di eq_refl.\nrewrite -[_ *+ _](determinant_alternate (negbT Di) EBi12) (expand_det_row _ i2).\napply: eq_bigr => j _; rewrite !mxE eq_refl; congr (_ * (_ * _)).\napply: eq_bigr => s _; congr (_ * _); apply: eq_bigr => i _.\nby rewrite !mxE eq_sym -if_neg neq_lift.\nQed.\n\n(* Cramer rule : adjugate on the right *)\nLemma mul_adj_mx n (A : 'M[R]_n) : \\adj A *m A = (\\det A)%:M.\nProof.\nby apply: trmx_inj; rewrite trmx_mul trmx_adj mul_mx_adj det_tr tr_scalar_mx.\nQed.\n\nLemma adj1 n : \\adj (1%:M) = 1%:M :> 'M[R]_n.\nProof. by rewrite -{2}(det1 n) -mul_adj_mx mulmx1. Qed.\n\n(* Left inverses are right inverses. *)\nLemma mulmx1C n (A B : 'M[R]_n) : A *m B = 1%:M -> B *m A = 1%:M.\nProof.\nmove=> AB1; pose A' := \\det B *: \\adj A.\nsuffices kA: A' *m A = 1%:M by rewrite -[B]mul1mx -kA -(mulmxA A') AB1 mulmx1.\nby rewrite -scalemxAl mul_adj_mx scale_scalar_mx mulrC -det_mulmx AB1 det1.\nQed.\n\n(* Only tall matrices have inverses. *)\nLemma mulmx1_min m n (A : 'M[R]_(m, n)) B : A *m B = 1%:M -> m <= n.\nProof.\nmove=> AB1; rewrite leqNgt; apply/negP=> /subnKC; rewrite addSnnS.\nmove: (_ - _)%N => m' def_m; move: AB1; rewrite -{m}def_m in A B *.\nrewrite -(vsubmxK A) -(hsubmxK B) mul_col_row scalar_mx_block.\ncase/eq_block_mx=> /mulmx1C BlAu1 AuBr0 _ => /eqP/idPn[].\nby rewrite -[_ B]mul1mx -BlAu1 -mulmxA AuBr0 !mulmx0 eq_sym oner_neq0.\nQed.\n\nLemma det_ublock n1 n2 Aul (Aur : 'M[R]_(n1, n2)) Adr :\n  \\det (block_mx Aul Aur 0 Adr) = \\det Aul * \\det Adr.\nProof.\nelim: n1 => [|n1 IHn1] in Aul Aur *.\n  have ->: Aul = 1%:M by apply/matrixP=> i [].\n  rewrite det1 mul1r; congr (\\det _); apply/matrixP=> i j.\n  by do 2![rewrite !mxE; case: splitP => [[]|k] //=; move/val_inj=> <- {k}].\nrewrite (expand_det_col _ (lshift n2 0)) big_split_ord /=.\nrewrite addrC big1 1?simp => [|i _]; last by rewrite block_mxEdl mxE simp.\nrewrite (expand_det_col _ 0) big_distrl /=; apply eq_bigr=> i _.\nrewrite block_mxEul -!mulrA; do 2!congr (_ * _).\nby rewrite col'_col_mx !col'Kl raddf0 row'Ku row'_row_mx IHn1.\nQed.\n\nLemma det_lblock n1 n2 Aul (Adl : 'M[R]_(n2, n1)) Adr :\n  \\det (block_mx Aul 0 Adl Adr) = \\det Aul * \\det Adr.\nProof. by rewrite -det_tr tr_block_mx trmx0 det_ublock !det_tr. Qed.\n\nEnd ComMatrix.\n\nImplicit Arguments lin_mul_row [R m n].\nImplicit Arguments lin_mulmx [R m n p].\nPrenex Implicits lin_mul_row lin_mulmx.\n\n(*****************************************************************************)\n(********************** Matrix unit ring and inverse matrices ****************)\n(*****************************************************************************)\n\nSection MatrixInv.\n\nVariables R : comUnitRingType.\n\nSection Defs.\n\nVariable n : nat.\nImplicit Type A : 'M[R]_n.\n\nDefinition unitmx : pred 'M[R]_n := fun A => \\det A \\is a GRing.unit.\nDefinition invmx A := if A \\in unitmx then (\\det A)^-1 *: \\adj A else A.\n\nLemma unitmxE A : (A \\in unitmx) = (\\det A \\is a GRing.unit).\nProof. by []. Qed.\n\nLemma unitmx1 : 1%:M \\in unitmx. Proof. by rewrite unitmxE det1 unitr1. Qed.\n\nLemma unitmx_perm s : perm_mx s \\in unitmx.\nProof. by rewrite unitmxE det_perm unitrX ?unitrN ?unitr1. Qed.\n\nLemma unitmx_tr A : (A^T \\in unitmx) = (A \\in unitmx).\nProof. by rewrite unitmxE det_tr. Qed.\n\nLemma unitmxZ a A : a \\is a GRing.unit -> (a *: A \\in unitmx) = (A \\in unitmx).\nProof. by move=> Ua; rewrite !unitmxE detZ unitrM unitrX. Qed.\n\nLemma invmx1 : invmx 1%:M = 1%:M.\nProof. by rewrite /invmx det1 invr1 scale1r adj1 if_same. Qed.\n\nLemma invmxZ a A : a *: A \\in unitmx -> invmx (a *: A) = a^-1 *: invmx A.\nProof.\nrewrite /invmx !unitmxE detZ unitrM => /andP[Ua U_A].\nrewrite Ua U_A adjZ !scalerA invrM {U_A}//=.\ncase: (posnP n) A => [-> | n_gt0] A; first by rewrite flatmx0 [_ *: _]flatmx0.\nrewrite unitrX_pos // in Ua; rewrite -[_ * _](mulrK Ua) mulrC -!mulrA.\nby rewrite -exprSr prednK // !mulrA divrK ?unitrX.\nQed.\n\nLemma invmx_scalar a : invmx (a%:M) = a^-1%:M.\nProof.\ncase Ua: (a%:M \\in unitmx).\n  by rewrite -scalemx1 in Ua *; rewrite invmxZ // invmx1 scalemx1.\nrewrite /invmx Ua; have [->|n_gt0] := posnP n; first by rewrite ![_%:M]flatmx0.\nby rewrite unitmxE det_scalar unitrX_pos // in Ua; rewrite invr_out ?Ua.\nQed.\n\nLemma mulVmx : {in unitmx, left_inverse 1%:M invmx mulmx}.\nProof.\nby move=> A nsA; rewrite /invmx nsA -scalemxAl mul_adj_mx scale_scalar_mx mulVr.\nQed.\n\nLemma mulmxV : {in unitmx, right_inverse 1%:M invmx mulmx}.\nProof.\nby move=> A nsA; rewrite /invmx nsA -scalemxAr mul_mx_adj scale_scalar_mx mulVr.\nQed.\n\nLemma mulKmx m : {in unitmx, @left_loop _ 'M_(n, m) invmx mulmx}.\nProof. by move=> A uA /= B; rewrite mulmxA mulVmx ?mul1mx. Qed.\n\nLemma mulKVmx m : {in unitmx, @rev_left_loop _ 'M_(n, m) invmx mulmx}.\nProof. by move=> A uA /= B; rewrite mulmxA mulmxV ?mul1mx. Qed.\n\nLemma mulmxK m : {in unitmx, @right_loop 'M_(m, n) _ invmx mulmx}.\nProof. by move=> A uA /= B; rewrite -mulmxA mulmxV ?mulmx1. Qed.\n\nLemma mulmxKV m : {in unitmx, @rev_right_loop 'M_(m, n) _ invmx mulmx}.\nProof. by move=> A uA /= B; rewrite -mulmxA mulVmx ?mulmx1. Qed.\n\nLemma det_inv A : \\det (invmx A) = (\\det A)^-1.\nProof.\ncase uA: (A \\in unitmx); last by rewrite /invmx uA invr_out ?negbT.\nby apply: (mulrI uA); rewrite -det_mulmx mulmxV ?divrr ?det1.\nQed.\n\nLemma unitmx_inv A : (invmx A \\in unitmx) = (A \\in unitmx).\nProof. by rewrite !unitmxE det_inv unitrV. Qed.\n\nLemma unitmx_mul A B : (A *m B \\in unitmx) = (A \\in unitmx) && (B \\in unitmx).\nProof. by rewrite -unitrM -det_mulmx. Qed.\n\nLemma trmx_inv (A : 'M_n) : (invmx A)^T = invmx (A^T).\nProof. by rewrite (fun_if trmx) linearZ /= trmx_adj -unitmx_tr -det_tr. Qed.\n\nLemma invmxK : involutive invmx.\nProof.\nmove=> A; case uA : (A \\in unitmx); last by rewrite /invmx !uA.\nby apply: (can_inj (mulKVmx uA)); rewrite mulVmx // mulmxV ?unitmx_inv.\nQed.\n\nLemma mulmx1_unit A B : A *m B = 1%:M -> A \\in unitmx /\\ B \\in unitmx.\nProof. by move=> AB1; apply/andP; rewrite -unitmx_mul AB1 unitmx1. Qed.\n\nLemma intro_unitmx A B : B *m A = 1%:M /\\ A *m B = 1%:M -> unitmx A.\nProof. by case=> _ /mulmx1_unit[]. Qed.\n\nLemma invmx_out : {in [predC unitmx], invmx =1 id}.\nProof. by move=> A; rewrite inE /= /invmx -if_neg => ->. Qed.\n\nEnd Defs.\n\nVariable n' : nat.\nLocal Notation n := n'.+1.\n\nDefinition matrix_unitRingMixin :=\n  UnitRingMixin (@mulVmx n) (@mulmxV n) (@intro_unitmx n) (@invmx_out n).\nCanonical matrix_unitRing :=\n  Eval hnf in UnitRingType 'M[R]_n matrix_unitRingMixin.\nCanonical matrix_unitAlg := Eval hnf in [unitAlgType R of 'M[R]_n].\n\n(* Lemmas requiring that the coefficients are in a unit ring *)\n\nLemma detV (A : 'M_n) : \\det A^-1 = (\\det A)^-1.\nProof. exact: det_inv. Qed.\n\nLemma unitr_trmx (A : 'M_n) : (A^T  \\is a GRing.unit) = (A \\is a GRing.unit).\nProof. exact: unitmx_tr. Qed.\n\nLemma trmxV (A : 'M_n) : A^-1^T = (A^T)^-1.\nProof. exact: trmx_inv. Qed.\n\nLemma perm_mxV (s : 'S_n) : perm_mx s^-1 = (perm_mx s)^-1.\nProof.\nrewrite -[_^-1]mul1r; apply: (canRL (mulmxK (unitmx_perm s))).\nby rewrite -perm_mxM mulVg perm_mx1.\nQed.\n\nLemma is_perm_mxV (A : 'M_n) : is_perm_mx A^-1 = is_perm_mx A.\nProof.\napply/is_perm_mxP/is_perm_mxP=> [] [s defA]; exists s^-1%g.\n  by rewrite -(invrK A) defA perm_mxV.\nby rewrite defA perm_mxV.\nQed.\n\nEnd MatrixInv.\n\nPrenex Implicits unitmx invmx.\n\n(* Finite inversible matrices and the general linear group. *)\nSection FinUnitMatrix.\n\nVariables (n : nat) (R : finComUnitRingType).\n\nCanonical matrix_finUnitRingType n' :=\n  Eval hnf in [finUnitRingType of 'M[R]_n'.+1].\n\nDefinition GLtype of phant R := {unit 'M[R]_n.-1.+1}.\n\nCoercion GLval ph (u : GLtype ph) : 'M[R]_n.-1.+1 :=\n  let: FinRing.Unit A _ := u in A.\n\nEnd FinUnitMatrix.\n\nBind Scope group_scope with GLtype.\nArguments Scope GLval [nat_scope _ _ group_scope].\nPrenex Implicits GLval.\n\nNotation \"{ ''GL_' n [ R ] }\" := (GLtype n (Phant R))\n  (at level 0, n at level 2, format \"{ ''GL_' n [ R ] }\") : type_scope.\nNotation \"{ ''GL_' n ( p ) }\" := {'GL_n['F_p]}\n  (at level 0, n at level 2, p at level 10,\n    format \"{ ''GL_' n ( p ) }\") : type_scope.\n\nSection GL_unit.\n\nVariables (n : nat) (R : finComUnitRingType).\n\nCanonical GL_subType := [subType of {'GL_n[R]} for GLval].\nDefinition GL_eqMixin := Eval hnf in [eqMixin of {'GL_n[R]} by <:].\nCanonical GL_eqType := Eval hnf in EqType {'GL_n[R]} GL_eqMixin.\nCanonical GL_choiceType := Eval hnf in [choiceType of {'GL_n[R]}].\nCanonical GL_countType := Eval hnf in [countType of {'GL_n[R]}].\nCanonical GL_subCountType := Eval hnf in [subCountType of {'GL_n[R]}].\nCanonical GL_finType := Eval hnf in [finType of {'GL_n[R]}].\nCanonical GL_subFinType := Eval hnf in [subFinType of {'GL_n[R]}].\nCanonical GL_baseFinGroupType := Eval hnf in [baseFinGroupType of {'GL_n[R]}].\nCanonical GL_finGroupType := Eval hnf in [finGroupType of {'GL_n[R]}].\nDefinition GLgroup of phant R := [set: {'GL_n[R]}].\nCanonical GLgroup_group ph := Eval hnf in [group of GLgroup ph].\n\nImplicit Types u v : {'GL_n[R]}.\n\nLemma GL_1E : GLval 1 = 1. Proof. by []. Qed.\nLemma GL_VE u : GLval u^-1 = (GLval u)^-1. Proof. by []. Qed.\nLemma GL_VxE u : GLval u^-1 = invmx u. Proof. by []. Qed.\nLemma GL_ME u v : GLval (u * v) = GLval u * GLval v. Proof. by []. Qed.\nLemma GL_MxE u v : GLval (u * v) = u *m v. Proof. by []. Qed.\nLemma GL_unit u : GLval u \\is a GRing.unit. Proof. exact: valP. Qed.\nLemma GL_unitmx u : val u \\in unitmx. Proof. exact: GL_unit. Qed.\n\nLemma GL_det u : \\det u != 0.\nProof.\nby apply: contraL (GL_unitmx u); rewrite unitmxE => /eqP->; rewrite unitr0.\nQed.\n\nEnd GL_unit.\n\nNotation \"''GL_' n [ R ]\" := (GLgroup n (Phant R))\n  (at level 8, n at level 2, format \"''GL_' n [ R ]\") : group_scope.\nNotation \"''GL_' n ( p )\" := 'GL_n['F_p]\n  (at level 8, n at level 2, p at level 10,\n   format \"''GL_' n ( p )\") : group_scope.\nNotation \"''GL_' n [ R ]\" := (GLgroup_group n (Phant R)) : Group_scope.\nNotation \"''GL_' n ( p )\" := (GLgroup_group n (Phant 'F_p)) : Group_scope.\n\n(*****************************************************************************)\n(********************** Matrices over a domain *******************************)\n(*****************************************************************************)\n\nSection MatrixDomain.\n\nVariable R : idomainType.\n\nLemma scalemx_eq0 m n a (A : 'M[R]_(m, n)) :\n  (a *: A == 0) = (a == 0) || (A == 0).\nProof.\ncase nz_a: (a == 0) / eqP => [-> | _]; first by rewrite scale0r eqxx.\napply/eqP/eqP=> [aA0 | ->]; last exact: scaler0.\napply/matrixP=> i j; apply/eqP; move/matrixP/(_ i j)/eqP: aA0.\nby rewrite !mxE mulf_eq0 nz_a.\nQed.\n\nLemma scalemx_inj m n a :\n  a != 0 -> injective ( *:%R a : 'M[R]_(m, n) -> 'M[R]_(m, n)).\nProof.\nmove=> nz_a A B eq_aAB; apply: contraNeq nz_a.\nrewrite -[A == B]subr_eq0 -[a == 0]orbF => /negPf<-.\nby rewrite -scalemx_eq0 linearB subr_eq0 /= eq_aAB.\nQed.\n\nLemma det0P n (A : 'M[R]_n) :\n  reflect (exists2 v : 'rV[R]_n, v != 0 & v *m A = 0) (\\det A == 0).\nProof.\napply: (iffP eqP) => [detA0 | [v n0v vA0]]; last first.\n  apply: contraNeq n0v => nz_detA; rewrite -(inj_eq (scalemx_inj nz_detA)).\n  by rewrite scaler0 -mul_mx_scalar -mul_mx_adj mulmxA vA0 mul0mx.\nelim: n => [|n IHn] in A detA0 *.\n  by case/idP: (oner_eq0 R); rewrite -detA0 [A]thinmx0 -(thinmx0 1%:M) det1.\nhave [{detA0}A'0 | nzA'] := eqVneq (row 0 (\\adj A)) 0; last first.\n  exists (row 0 (\\adj A)) => //; rewrite rowE -mulmxA mul_adj_mx detA0.\n  by rewrite mul_mx_scalar scale0r.\npose A' := col' 0 A; pose vA := col 0 A.\nhave defA: A = row_mx vA A'.\n  apply/matrixP=> i j; rewrite !mxE.\n  case: splitP => j' def_j; rewrite mxE; congr (A i _); apply: val_inj => //=.\n  by rewrite def_j [j']ord1.\nhave{IHn} w_ j : exists w : 'rV_n.+1, [/\\ w != 0, w 0 j = 0 & w *m A' = 0].\n  have [|wj nzwj wjA'0] := IHn (row' j A').\n    by apply/eqP; move/rowP/(_ j)/eqP: A'0; rewrite !mxE mulf_eq0 signr_eq0.\n  exists (\\row_k oapp (wj 0) 0 (unlift j k)).\n  rewrite !mxE unlift_none -wjA'0; split=> //.\n    apply: contraNneq nzwj => w0; apply/eqP/rowP=> k'.\n    by move/rowP/(_ (lift j k')): w0; rewrite !mxE liftK.\n  apply/rowP=> k; rewrite !mxE (bigD1 j) //= mxE unlift_none mul0r add0r.\n  rewrite (reindex_onto (lift j) (odflt k \\o unlift j)) /= => [|k'].\n    by apply: eq_big => k'; rewrite ?mxE liftK eq_sym neq_lift eqxx.\n  by rewrite eq_sym; case/unlift_some=> ? ? ->.\nhave [w0 [nz_w0 w00_0 w0A']] := w_ 0; pose a0 := (w0 *m vA) 0 0.\nhave [j {nz_w0}/= nz_w0j | w00] := pickP [pred j | w0 0 j != 0]; last first.\n  by case/eqP: nz_w0; apply/rowP=> j; rewrite mxE; move/eqP: (w00 j).\nhave{w_} [wj [nz_wj wj0_0 wjA']] := w_ j; pose aj := (wj *m vA) 0 0.\nhave [aj0 | nz_aj] := eqVneq aj 0.\n  exists wj => //; rewrite defA (@mul_mx_row _ _ _ 1) [_ *m _]mx11_scalar -/aj.\n  by rewrite aj0 raddf0 wjA' row_mx0.\nexists (aj *: w0 - a0 *: wj).\n  apply: contraNneq nz_aj; move/rowP/(_ j)/eqP; rewrite !mxE wj0_0 mulr0 subr0.\n  by rewrite mulf_eq0 (negPf nz_w0j) orbF.\nrewrite defA (@mul_mx_row _ _ _ 1) !mulmxBl -!scalemxAl w0A' wjA' !linear0.\nby rewrite -mul_mx_scalar -mul_scalar_mx -!mx11_scalar subrr addr0 row_mx0.\nQed.\n\nEnd MatrixDomain.\n\nImplicit Arguments det0P [R n A].\n\n(* Parametricity at the field level (mx_is_scalar, unit and inverse are only *)\n(* mapped at this level).                                                    *)\nSection MapFieldMatrix.\n\nVariables (aF : fieldType) (rF : comUnitRingType) (f : {rmorphism aF -> rF}).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\n\nLemma map_mx_inj m n : injective ((map_mx f) m n).\nProof.\nmove=> A B eq_AB; apply/matrixP=> i j.\nby move/matrixP/(_ i j): eq_AB; rewrite !mxE; exact: fmorph_inj.\nQed.\n\nLemma map_mx_is_scalar n (A : 'M_n) : is_scalar_mx A^f = is_scalar_mx A.\nProof.\nrewrite /is_scalar_mx; case: (insub _) => // i.\nby rewrite mxE -map_scalar_mx inj_eq //; exact: map_mx_inj.\nQed.\n\nLemma map_unitmx n (A : 'M_n) : (A^f \\in unitmx) = (A \\in unitmx).\nProof. by rewrite unitmxE det_map_mx // fmorph_unit // -unitfE. Qed.\n\nLemma map_mx_unit n' (A : 'M_n'.+1) :\n  (A^f \\is a GRing.unit) = (A \\is a GRing.unit).\nProof. exact: map_unitmx. Qed.\n\nLemma map_invmx n (A : 'M_n) : (invmx A)^f = invmx A^f.\nProof.\nrewrite /invmx map_unitmx (fun_if ((map_mx f) n n)).\nby rewrite map_mxZ map_mx_adj det_map_mx fmorphV. \nQed.\n\nLemma map_mx_inv n' (A : 'M_n'.+1) : A^-1^f = A^f^-1.\nProof. exact: map_invmx. Qed.\n  \nLemma map_mx_eq0 m n (A : 'M_(m, n)) : (A^f == 0) = (A == 0).\nProof. by rewrite -(inj_eq (@map_mx_inj m n)) raddf0. Qed.\n\nEnd MapFieldMatrix.\n\n(*****************************************************************************)\n(****************************** LUP decomposion ******************************)\n(*****************************************************************************)\n\nSection CormenLUP.\n\nVariable F : fieldType.\n\n(* Decomposition of the matrix A to P A = L U with *)\n(*   - P a permutation matrix                      *)\n(*   - L a unipotent lower triangular matrix       *)\n(*   - U an upper triangular matrix                *)\n\nFixpoint cormen_lup {n} :=\n  match n return let M := 'M[F]_n.+1 in M -> M * M * M with\n  | 0 => fun A => (1, 1, A)\n  | _.+1 => fun A =>\n    let k := odflt 0 [pick k | A k 0 != 0] in\n    let A1 : 'M_(1 + _) := xrow 0 k A in\n    let P1 : 'M_(1 + _) := tperm_mx 0 k in\n    let Schur := ((A k 0)^-1 *: dlsubmx A1) *m ursubmx A1 in\n    let: (P2, L2, U2) := cormen_lup (drsubmx A1 - Schur) in\n    let P := block_mx 1 0 0 P2 *m P1 in\n    let L := block_mx 1 0 ((A k 0)^-1 *: (P2 *m dlsubmx A1)) L2 in\n    let U := block_mx (ulsubmx A1) (ursubmx A1) 0 U2 in\n    (P, L, U)\n  end.\n\nLemma cormen_lup_perm n (A : 'M_n.+1) : is_perm_mx (cormen_lup A).1.1.\nProof.\nelim: n => [|n IHn] /= in A *; first exact: is_perm_mx1.\nset A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/=.\nrewrite (is_perm_mxMr _ (perm_mx_is_perm _ _)).\ncase/is_perm_mxP => s ->; exact: lift0_mx_is_perm.\nQed.\n\nLemma cormen_lup_correct n (A : 'M_n.+1) :\n  let: (P, L, U) := cormen_lup A in P * A = L * U.\nProof.\nelim: n => [|n IHn] /= in A *; first by rewrite !mul1r.\nset k := odflt _ _; set A1 : 'M_(1 + _) := xrow _ _ _.\nset A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P' L' U']] /= IHn.\nrewrite -mulrA -!mulmxE -xrowE -/A1 /= -[n.+2]/(1 + n.+1)%N -{1}(submxK A1).\nrewrite !mulmx_block !mul0mx !mulmx0 !add0r !addr0 !mul1mx -{L' U'}[L' *m _]IHn.\nrewrite -scalemxAl !scalemxAr -!mulmxA addrC -mulrDr {A'}subrK.\ncongr (block_mx _ _ (_ *m _) _).\nrewrite [_ *: _]mx11_scalar !mxE lshift0 tpermL {}/A1 {}/k.\ncase: pickP => /= [k nzAk0 | no_k]; first by rewrite mulVf ?mulmx1.\nrewrite (_ : dlsubmx _ = 0) ?mul0mx //; apply/colP=> i.\nby rewrite !mxE lshift0 (elimNf eqP (no_k _)).\nQed.\n\nLemma cormen_lup_detL n (A : 'M_n.+1) : \\det (cormen_lup A).1.2 = 1.\nProof.\nelim: n => [|n IHn] /= in A *; first by rewrite det1.\nset A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/= detL.\nby rewrite (@det_lblock _ 1) det1 mul1r.\nQed.\n\nLemma cormen_lup_lower n A (i j : 'I_n.+1) :\n  i <= j -> (cormen_lup A).1.2 i j = (i == j)%:R.\nProof.\nelim: n => [|n IHn] /= in A i j *; first by rewrite [i]ord1 [j]ord1 mxE.\nset A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/= Ll.\nrewrite !mxE split1; case: unliftP => [i'|] -> /=; rewrite !mxE split1.\n  by case: unliftP => [j'|] -> //; exact: Ll.\nby case: unliftP => [j'|] ->; rewrite /= mxE.\nQed.\n\nLemma cormen_lup_upper n A (i j : 'I_n.+1) :\n  j < i -> (cormen_lup A).2 i j = 0 :> F.\nProof.\nelim: n => [|n IHn] /= in A i j *; first by rewrite [i]ord1.\nset A' := _ - _; move/(_ A'): IHn; case: cormen_lup => [[P L U]] {A'}/= Uu.\nrewrite !mxE split1; case: unliftP => [i'|] -> //=; rewrite !mxE split1.\nby case: unliftP => [j'|] ->; [exact: Uu | rewrite /= mxE].\nQed.\n\nEnd CormenLUP.\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/matrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.656727429395132}}
{"text": "Require Import FormalMath.lib.Sets_ext.\nRequire Import Coq.Logic.Description.\n\nInductive invertible {X Y: Type} (f: X -> Y): Prop :=\n| invertible_intro: forall g: Y -> X,\n    (forall x: X, g (f x) = x) -> (forall y: Y, f (g y) = y) -> invertible f.\n\nInductive FiniteT: Type -> Prop :=\n| empty_finite: FiniteT False\n| add_finite: forall T: Type, FiniteT T -> FiniteT (option T)\n| bij_finite: forall (X Y:Type) (f: X -> Y), FiniteT X -> invertible f -> FiniteT Y.\n\nLemma True_finite: FiniteT True.\nProof.\n  apply bij_finite with (option False) (fun _ => I). 1: constructor; constructor.\n  exists (True_rect None).\n  - intros. destruct x. 1: easy. remember (True_rect None I) as LHS.\n    destruct LHS; easy.\n  - exact (fun y: True => match y with | I => refl_equal I end).\nQed.\n\nLemma finite_dep_choice: forall (A: Type) (B: forall x: A, Type)\n                                (R: forall x: A, B x -> Prop),\n    FiniteT A -> (forall x: A, exists y: B x, R x y) ->\n    exists f: (forall x: A, B x), forall x: A, R x (f x).\nProof.\n  intros. revert B R H0. induction H; intros.\n  - exists (fun x: False => False_rect (B x) x). destruct x.\n  - pose proof (IHFiniteT (fun x: T => B (Some x)) (fun x: T => R (Some x))\n                          (fun x: T => H0 (Some x))). destruct H1.\n    pose proof (H0 None). destruct H2.\n    exists (fun y:option T => match y return (B y) with\n                              | Some y0 => x y0 | None => x0 end). destruct x1.\n    apply H1. assumption.\n  - destruct H0. pose proof (IHFiniteT (fun x: X => B (f x)) (fun x: X => R (f x))\n                                       (fun x: X => H1 (f x))). destruct H3.\n    pose (f0 := fun y: Y => x (g y)).\n    pose (conv := fun (y: Y) (a: B (f (g y))) => eq_rect (f (g y)) B a y (H2 y)).\n    exists (fun y:Y => conv y (x (g y))). intro. unfold conv; simpl.\n    generalize (H2 x0). pattern x0 at 2 3 6. rewrite <- H2. intro.\n    rewrite <- eq_rect_eq. apply H3.\nQed.\n\nLemma finite_choice:  forall (A B: Type) (R: A -> B -> Prop),\n    FiniteT A -> (forall x: A, exists y: B, R x y) ->\n    exists f: A -> B, forall x: A, R x (f x).\nProof. intros. now apply finite_dep_choice. Qed.\n\nLemma exclusive_dec: forall P Q: Prop, ~(P /\\ Q) -> (P \\/ Q) -> {P} + {Q}.\nProof.\n  intros. assert ({x: bool | if x then P else Q}). {\n    apply constructive_definite_description. case H0.\n    - exists true. red; split; auto. destruct x'; tauto.\n    - exists false. red; split; auto. destruct x'; tauto. }\n  destruct H1. destruct x; [left | right]; easy.\nQed.\n\nLemma EqDec_Finite_FiniteT: forall {X:Type} (S: Ensemble X),\n    (forall a b: X, {a = b} + {a <> b}) -> Finite S -> FiniteT {x: X | In S x}.\nProof.\n  intros. induction H.\n  - apply bij_finite with False (False_rect _). 1: constructor.\n    assert (g: {x:X | In Empty_set x} -> False). {\n      intro. destruct X1. destruct i. } exists g.\n    + destruct x.\n    + destruct y. destruct g.\n  - assert (Included A (Add A x)) by auto with sets.\n    assert (In (Add A x) x) by auto with sets.\n    pose (g := fun (y: option {x: X | In A x}) =>\n                 match y return {x0: X | In (Add A x) x0} with\n                 | Some (exist _ y0 i) =>\n                   exist (fun x2: X => In (Add A x) x2) y0 (H1 y0 i)\n                 | None => exist (fun x2: X => In (Add A x) x2) x H2\n                 end). apply bij_finite with _ g.\n    + now apply add_finite.\n    + assert (h:forall x0:X, In (Add A x) x0 -> { In A x0 } + { x0 = x }). {\n        clear -X0. intros. destruct (X0 x0 x). 1: right; auto. left.\n        destruct H; auto. inversion H. now subst. }\n      pose (ginv := fun s:{x0: X | In (Add A x) x0} =>\n                      match s return option {x: X | In A x} with\n                      | exist _ x0 i => match (h x0 i) with\n                                        | left iA => Some (exist _ x0 iA)\n                                        | right _ => None\n                                        end\n                      end). exists ginv.\n      * intro; destruct x0.\n        -- destruct s. simpl. remember (h x0 (H1 x0 i)) as sum; destruct sum.\n           ++ now destruct (proof_irrelevance _ i i0).\n           ++ now subst x0.\n        -- simpl. remember (h x H2) as sum; destruct sum; easy.\n      * intro. unfold ginv. destruct y. destruct (h x0 i); simpl.\n        -- generalize (H1 x0 i0); intro. now destruct (proof_irrelevance _ i i1).\n        -- destruct e. now destruct (proof_irrelevance _ H2 i).\nQed.\n\nLemma Finite_FiniteT: forall {X:Type} (S:Ensemble X),\n    Finite S -> FiniteT {x: X | In S x}.\nProof.\n  intros. induction H.\n  - apply bij_finite with False (False_rect _). 1: constructor.\n    assert (g: {x:X | In Empty_set x} -> False). {\n      intro. destruct X0. destruct i. } exists g.\n    + destruct x.\n    + destruct y. destruct g.\n  - assert (Included A (Add A x)) by auto with sets.\n    assert (In (Add A x) x) by auto with sets.\n    pose (g := fun (y: option {x: X | In A x}) =>\n                 match y return {x0: X | In (Add A x) x0} with\n                 | Some (exist _ y0 i) =>\n                   exist (fun x2: X => In (Add A x) x2) y0 (H1 y0 i)\n                 | None => exist (fun x2: X => In (Add A x) x2) x H2\n                 end). apply bij_finite with _ g.\n    + now apply add_finite.\n    + assert (h:forall x0:X, In (Add A x) x0 -> { In A x0 } + { x0 = x }). {\n        clear -H0. intros; apply exclusive_dec.\n        - intuition. subst; auto.\n        - destruct H. 1: now left. inversion H. now right. }\n      pose (ginv := fun s:{x0: X | In (Add A x) x0} =>\n                      match s return option {x: X | In A x} with\n                      | exist _ x0 i => match (h x0 i) with\n                                        | left iA => Some (exist _ x0 iA)\n                                        | right _ => None\n                                        end\n                      end). exists ginv.\n      * intro; destruct x0.\n        -- destruct s. simpl. remember (h x0 (H1 x0 i)) as sum; destruct sum.\n           ++ now destruct (proof_irrelevance _ i i0).\n           ++ now subst x0.\n        -- simpl. remember (h x H2) as sum; destruct sum; easy.\n      * intro. unfold ginv. destruct y. destruct (h x0 i); simpl.\n        -- generalize (H1 x0 i0); intro. now destruct (proof_irrelevance _ i i1).\n        -- destruct e. now destruct (proof_irrelevance _ H2 i).\nQed.\n\nLemma finite_or_exists: forall (X:Type) (P: X -> Prop),\n    FiniteT X -> (forall x:X, (P x) \\/ (~ P x)) ->\n    (exists x:X, P x) \\/ (forall x:X, ~ P x).\nProof.\n  intros. revert P H0. induction H.\n  - right. destruct x.\n  - intros. case (IHFiniteT (fun x:T => P (Some x)) (fun x:T => H0 (Some x))).\n    + left. destruct H1. exists (Some x). assumption.\n    + intro. case (H0 None).\n      * left. exists None. assumption.\n      * right. destruct x.\n        -- apply H1.\n        -- assumption.\n  - destruct H0. intros.\n    case (IHFiniteT (fun x:X => P (f x)) (fun x:X => H2 (f x))).\n    + left. destruct H3. exists (f x). assumption.\n    + right. intro. rewrite <- H1 with x. apply H3.\nQed.\n\nLemma FiniteT_img: forall (X Y:Type) (f:X->Y),\n    FiniteT X -> (forall y1 y2:Y, y1=y2 \\/ y1<>y2) ->\n    Finite (Im Full_set f).\nProof.\n  intros. induction H.\n  - replace (Im Full_set f) with (@Empty_set Y). 1: constructor.\n    apply Extensionality_Ensembles; split; red; intros; destruct H. destruct x.\n  - assert ((exists x:T, f (Some x) = f None) \\/ (forall x:T, f (Some x) <> f None)).\n    + apply finite_or_exists; auto.\n    + case H1.\n      * intro. pose (g := fun (x:T) => f (Some x)).\n        replace (Im Full_set f) with (Im Full_set g). 1: apply IHFiniteT.\n        apply Extensionality_Ensembles; split; red; intros.\n        -- destruct H3. subst. exists (Some x); easy.\n        -- destruct H3. subst. destruct x.\n           ++ exists t; easy.\n           ++ destruct H2. exists x.\n              ** constructor.\n              ** destruct H3. subst g. symmetry. assumption.\n      * intros. pose (g := fun x:T => f (Some x)).\n        replace (Im Full_set f) with (Add (Im Full_set g) (f None)).\n        -- constructor.\n           ++ apply IHFiniteT.\n           ++ red; intro. destruct H3. contradiction (H2 x). symmetry; assumption.\n        -- apply Extensionality_Ensembles; split; red; intros.\n           ++ red; intros. destruct H3, H3; [exists (Some x) | exists None]; easy.\n           ++ red; intros. destruct H3. destruct x.\n              ** left. exists t; easy.\n              ** right. auto with sets.\n  - pose (g := fun (x:X) => f (f0 x)).\n    replace (Im Full_set f) with (Im Full_set g). 1: apply IHFiniteT.\n    apply Extensionality_Ensembles; split; red; intros.\n    + destruct H2. exists (f0 x); easy.\n    + destruct H2, H1. subst. rewrite <- H4 with x. now exists (g0 x).\nQed.\n", "meta": {"author": "txyyss", "repo": "FormalMath", "sha": "35d2593efbc346433fe586b8f8dbaede046df6dc", "save_path": "github-repos/coq/txyyss-FormalMath", "path": "github-repos/coq/txyyss-FormalMath/FormalMath-35d2593efbc346433fe586b8f8dbaede046df6dc/lib/FiniteType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6567274179582527}}
{"text": "Require Import Bool.\n\nInductive bool := \n| true\n| false.\n\nDefinition negb (b : bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nTheorem negb_negb: forall (b : bool), negb (negb b) = b.\nProof.\n  intros b.\n  destruct b.\n  + simpl. reflexivity.\n  + simpl. reflexivity.\nQed.\n\nTheorem negb_trice : forall (b : bool), negb (negb (negb b)) = negb b.\nProof.\n  intros b.\n  destruct b.\n  + simpl. reflexivity.\n  + simpl. reflexivity. \nQed.\n\nDefinition andb (a b : bool) : bool :=\n  match a, b with\n  | true, true => true\n  | _, _ => false\n  end.\n\n  Theorem and_true_both_arg_true : forall (a b : bool),\n  a = true -> b = true ->  andb a b = true.\nProof.\n  intros a b Ha Hb.\n  rewrite Ha.\n  rewrite Hb.\n  simpl. reflexivity.\nQed.\n\nTheorem and_true_otherside : forall (a b : bool),\n  andb a b = true -> a = true /\\ b = true.\nProof.\n  intros a b Ha.\n  destruct a.\n  destruct b.\n  split. reflexivity.\n  reflexivity.\n  split. reflexivity.\n  simpl in Ha.\n  inversion Ha.\n  destruct b.\n  simpl in Ha.\n  inversion Ha.\n  simpl in Ha.\n  inversion Ha.\nQed.\n\nTheorem andb_associative : forall (a b c : bool),\n  andb a (andb b c) = andb (andb a b) c.\nProof.\n  intros [|] [|] [|];\n  reflexivity.\nQed.\n\nTheorem andb_comutative : forall a b, andb a b = andb b a.\nProof.\n  intros [|] [|]; simpl; reflexivity.\nQed.\n\nDefinition orb(a b : bool) : bool :=\n  match a, b with\n  | false, false => false\n  | _, _ => true\n  end.\n\nTheorem andb_negb_orb : forall (a b : bool),\n  negb (andb a b) = orb (negb a) (negb b).\nProof.\n  intros [|] [|]; simpl; reflexivity.\nQed.\n\nDefinition material(a b : bool) : bool :=\nmatch a,b with\n  | false, true => false\n  | _, _ => true\nend.\n\nTheorem positive_material : forall a b : bool, \n  a = true -> material a b = true.\n  Proof.\n    intros a b Ha.\n    destruct a eqn:E.\n    - simpl. destruct b; reflexivity.\n    - discriminate Ha. \n    Show Proof.\nQed.\n", "meta": {"author": "l3r8yJ", "repo": "phi-reducer", "sha": "5bcb75d101d672506f030d1f7c3226752891070d", "save_path": "github-repos/coq/l3r8yJ-phi-reducer", "path": "github-repos/coq/l3r8yJ-phi-reducer/phi-reducer-5bcb75d101d672506f030d1f7c3226752891070d/src/theorems/main.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6567274167593748}}
{"text": "Unset Boxed Definitions.\nUnset Boxed Values.\n\n\nRequire Export QArith_base.\nRequire Export Znumtheory.\n\n(* First, a function that (tries to) build a positive back from a Z. *)\n\nDefinition Z2P (z : Z) :=\n  match z with\n  | Z0 => 1%positive\n  | Zpos p => p\n  | Zneg p => p\n  end.\n\nLemma Z2P_correct : forall z : Z, (0 < z)%Z -> Zpos (Z2P z) = z.\nProof.\n simple destruct z; simpl in |- *; auto; intros; discriminate.\nQed.\n\nLemma Z2P_correct2 : forall z : Z, 0%Z <> z -> Zpos (Z2P z) = Zabs z.\nProof.\n simple destruct z; simpl in |- *; auto; intros; elim H; auto.\nQed.\n\n(* Simplification of fractions using the Zgcd. *)\n\nDefinition Qred (q : Q) :=\n  let (q1, q2) := q in\n  let g := Zgcd (Zpos q2) q1 in (q1 / g)#(Z2P (Zpos q2 / g)).\n\nLemma Qred_correct : forall q, (Qred q) == q.\nintros (n, d); unfold Qred, Qeq in |- *; simpl in |- *.\nunfold Zgcd in |- *; case (Zgcd_spec (Zpos d) n); intros g.\nintuition.\nelim H; intros.\nassert (0%Z <> g).\n  intro. \n  elim H1; intros.\n  rewrite <- H4 in H5.\n  rewrite Zmult_comm in H5; inversion H5.\n\nassert (0 < Zpos d / g)%Z.\n  apply Zmult_gt_0_lt_0_reg_r with g.\n  omega.\n  rewrite Zmult_comm.\n  rewrite <- Z_div_exact_2; auto with zarith.\n  compute in |- *; auto.\n  apply Zdivide_mod; auto with zarith.\nrewrite Z2P_correct; auto.\npattern n at 2 in |- *.\nrewrite (Z_div_exact_2 n g); try apply Zdivide_mod; auto with zarith.\npattern d at 2 in |- *.\nrewrite (Z_div_exact_2 (Zpos d) g); try apply Zdivide_mod; auto with zarith.\nring.\nQed.\n\nLemma Qred_complete : forall p q,  p==q -> Qred p = Qred q.\nintros (a, b) (c, d); unfold Qeq in |- *; simpl in |- *.\nunfold Zgcd in |- *; case (Zgcd_spec (Zpos b) a); intros g (Hg1, Hg2).\nunfold Zgcd in |- *; case (Zgcd_spec (Zpos d) c); intros g' (Hg'1, Hg'2).\nintros.\ninversion Hg1.\ninversion Hg'1.\nassert (g <> 0%Z).\n  intro. \n  elim H0; intros.\n  subst g.\n  rewrite Zmult_comm in H7; inversion H7.\nassert (g' <> 0%Z).\n  intro. \n  elim H3; intros.\n  subst g'.\n  rewrite Zmult_comm in H8; inversion H8.\nrewrite (Z_div_exact_2 a g) in H; try apply Zdivide_mod; auto with zarith.\nrewrite (Z_div_exact_2 (Zpos d) g') in H; try apply Zdivide_mod;\n auto with zarith.\nrewrite (Z_div_exact_2 (Zpos b) g) in H; try apply Zdivide_mod;\n auto with zarith.\nrewrite (Z_div_exact_2 c g') in H; try apply Zdivide_mod; auto with zarith.\nelim (rel_prime_cross_prod (a / g) (Zpos b / g) (c / g') (Zpos d / g')).\nintros.\nrewrite H8; rewrite H9; auto.\nunfold rel_prime in |- *; apply Zis_gcd_rel_prime; auto with zarith.\nunfold rel_prime in |- *; apply Zis_gcd_rel_prime; auto with zarith.\napply Zmult_gt_0_reg_l with g.\nomega.\nrewrite <- Z_div_exact_2; try apply Zdivide_mod; auto with zarith.\napply Zmult_gt_0_reg_l with g'.\nomega.\nrewrite <- Z_div_exact_2; try apply Zdivide_mod; auto with zarith.\napply Zmult_reg_l with (g * g')%Z.\nintro; elim (Zmult_integral _ _ H8); auto.\nreplace (g * g' * (a / g * (Zpos d / g')))%Z with\n (g * (a / g) * (g' * (Zpos d / g')))%Z.\nrewrite H.\nring.\nring.\nQed.\n\nAdd Morphism Qred : Qred_comp. \nintros q q' H.\nsetoid_rewrite (Qred_correct q); auto.\nsetoid_rewrite (Qred_correct q'); auto.\nQed.\n\nDefinition Qplus' (p q : Q) := Qred (Qplus p q).\nDefinition Qmult' (p q : Q) := Qred (Qmult p q). \n\nDefinition Qplus'_correct : forall p q : Q, Qeq (Qplus' p q) (Qplus p q).\nintros; unfold Qplus' in |- *; apply Qred_correct; auto.\nQed.\n\nDefinition Qmult'_correct : forall p q : Q, Qeq (Qmult' p q) (Qmult p q).\nintros; unfold Qmult' in |- *; apply Qred_correct; auto.\nQed.\n\nAdd Morphism Qplus' : Qplus'_comp.\nintros; unfold Qplus' in |- *.\nsetoid_rewrite H; setoid_rewrite H0; auto with qarith.\nQed.\n\nAdd Morphism Qmult' : Qmult'_comp.\nintros; unfold Qmult' in |- *.\nsetoid_rewrite H; setoid_rewrite H0; auto with qarith.\nQed.\n", "meta": {"author": "math-comp", "repo": "trajectories", "sha": "cc6e1298208a93592230f5b4ee3228a024aa03e7", "save_path": "github-repos/coq/math-comp-trajectories", "path": "github-repos/coq/math-comp-trajectories/trajectories-cc6e1298208a93592230f5b4ee3228a024aa03e7/attic/QArith/Qreduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985637, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6567274139001549}}
{"text": "From mathcomp Require Import ssreflect.\n\nRequire Import relation.\nRequire Import axiom_of_empty.\nRequire Import axiom_of_pair.\nRequire Import axiom_of_union.\n\nAxiom AxiomOfReplacement:\n  forall {U:Type}, forall {R:RelationLogicFunction U U},\n      (forall {x y z:U}, ((R x y /\\ R x z) -> y = z)) ->\n      forall {x': Collection U}, exists y':(Collection U), forall z:U, ( z ∈ y' <-> exists w:U, w ∈ x' /\\ R w z ).\n\nSection AxiomOfSeparationFromAxiomOfReplacement.\n  Variable U:Type.\n  Variable F: LogicFunction U.\n  Definition P: RelationLogicFunction U U := fun x y => F x /\\ x = y.\n\n  Lemma PisUniuqe: forall {x y z:U}, P x y /\\ P x z -> y = z.\n  Proof.\n    move => x y z.\n    case => HP1 HP2.\n    have L1: forall x y z : U, y = x /\\ z = x -> y = z.\n    move => x1 y1 z1.\n    case => H0 H1.\n    rewrite H0 H1.\n    reflexivity.\n    apply (L1 x y z).\n    suff: x = y /\\ x = z.\n    case => H0 H1.\n    split; [rewrite H0| rewrite H1]; reflexivity.\n    suff: (F x /\\ x = y) /\\ (F x /\\ x = z).\n    case => H0 H1.\n    split; [case H0 => H2 H3|case H1 => H2 H3]; by[].\n    split; by [].\n  Qed.\n\n  Theorem IntroAxiomOfSparation:\n    (forall {x': Collection U}, exists y':(Collection U), forall z:U,\n          ( z ∈ y' <-> exists w:U, w ∈ x' /\\ P w z )) ->\n    (forall {x': Collection U}, exists y':(Collection U), forall z:U,\n            ( z ∈ y' <-> z ∈ x' /\\ F z )).\n  Proof.\n    have L1: forall x': Collection U, forall y:U, (exists x:U, ( x ∈ x' /\\ P x y )) <->\n                                                    y ∈ x' /\\ F y.\n    move => x' y.\n    rewrite /iff. split.\n    case => x.\n    case => Hx.\n    case => HFx Hxy.\n    split; rewrite -Hxy. by []. by [].\n    case => Hyx HFy.\n    exists y.\n    split.\n    apply Hyx.\n    split. by[]. reflexivity.\n    move => HAF.\n    move => x'.\n    move: (L1 x') => L1x'.\n    move: (HAF x') => HAFx'.\n    case HAFx'.\n    move => w' HAF0.\n    exists w' => z.\n    move: (HAF0 z) => HAF0z.\n    move: (L1x' z) => L1x'z.\n    split.\n    move => H.\n    apply L1x'z.\n    apply HAF0z. by [].\n    case => H0 H1.\n    apply HAF0z.\n    apply L1x'z.\n    split; by [].\n  Qed.\n\nEnd AxiomOfSeparationFromAxiomOfReplacement.\n\nInductive CollectionSparation (U:Type) (F:LogicFunction U) : Collection U :=\n| intro_collection_sparation: forall x:U, F x -> x ∈ CollectionSparation U F.\n\nNotation \"{| : U | F |}\" := (CollectionSparation U F).\n\nInductive IntersectionOfCollection {U:Type} (A B:Collection U): Collection U :=\n| intro_intersection_of_collection: forall x:U, x ∈ A -> x ∈ B -> x ∈ IntersectionOfCollection A B\nwhere \"A ∩ B\" := (IntersectionOfCollection A B).\n\nInductive BigCapOfCollection {U:Type} (A': Collection (Collection U)): Collection U :=\n| intro_bigcap_of_collection: forall x:U, (forall X:Collection U, X ∈ A' -> x ∈ X) -> x ∈ BigCapOfCollection A'\nwhere  \"⋂ X\" := (BigCapOfCollection X).\n\nInductive CollectionMinus {U:Type} (A B:Collection U): Collection U :=\n| intro_collection_minus: forall x:U, x ∈ A -> x ∉ B -> x ∈ CollectionMinus A B\nwhere \"A \\ B\" := (CollectionMinus A B).\n\nTheorem in_intersection_to_in_and:\n  forall U:Type, forall x:U, forall {A B:Collection U}, x ∈ A ∩ B -> x ∈ A /\\ x ∈ B.\nProof.\n  move => U x A B.\n  case => x0 HA HB.\n  split; by [].\nQed.\n\nTheorem in_and_to_in_intersection:\n    forall U:Type, forall x:U, forall {A B:Collection U}, x ∈ A /\\ x ∈ B -> x ∈ A ∩ B.\nProof.\n  move => U x A B.\n  case => HA HB.\n  split; by [].\nQed.\n\nTheorem in_intersection_iff_in_and:\n  forall U:Type, forall x:U, forall {A B:Collection U}, x ∈ A ∩ B <-> x ∈ A /\\ x ∈ B.\nProof.\n  move => U x A B.\n  rewrite /iff. split.\n  apply in_intersection_to_in_and.\n  apply in_and_to_in_intersection.\nQed.\n\nTheorem triple_in_and_to_in_intersection:\n  forall U:Type, forall x:U, forall {A B C:Collection U}, x ∈ A /\\ x ∈ B /\\ x ∈ C -> x ∈ A ∩ B ∩ C.\nProof.\n  move => U x A B C.\n  case => HA HBC.\n  split. by [].\n  apply in_and_to_in_intersection.\n  by [].\nQed.\n\nTheorem triple_in_intersection_to_in_and:\n  forall U:Type, forall x:U, forall {A B C:Collection U}, x ∈ A ∩ B ∩ C -> x ∈ A /\\ x ∈ B /\\ x ∈ C.\nProof.\n  move => U x A B C.\n  case => x0 HA HBC.\n  split. by [].\n  apply in_intersection_iff_in_and in HBC. by [].\nQed.\n\nSection IntersectionTest.\n  Variable U:Type.\n  Variable A B C:Collection U.\n  Definition AndFunc A B := fun x:U => x ∈ A /\\ x ∈ B.\n  Definition DiffFunc A B := fun x:U => x ∈ A /\\ x ∉ B.\n\n  Goal {| : U | (AndFunc A B) |} = A ∩ B.\n  Proof.\n    apply mutally_included_iff_eq.\n    split => x; case => x0.\n    case => H0 H1.\n    split; [apply H0 | apply H1].\n    move => H0 H1.\n    split.\n    split; by [].\n  Qed.\n\n  Goal ⋂ (| A , B |) = A ∩ B.\n  Proof.\n    apply mutally_included_iff_eq.\n    split => x; case => x0.\n    move => H.\n    move: (H A) (H B) => HA HB.\n    split; [apply HA; left|apply HB; right].\n    move => HA HB.\n    apply: (intro_bigcap_of_collection (|A , B|)) => X.\n    case; by [].\n  Qed.\n\n  Goal ⋂ {| A, B, C |} = A ∩ B ∩ C.\n  Proof.\n    apply mutally_included_iff_eq.\n    split => x.\n    case => x0 H.\n    split.\n    apply H. left. left. apply singleton_iff_eq. reflexivity.\n    split; apply H.\n    left. right. apply singleton_iff_eq. reflexivity.\n    right. apply singleton_iff_eq. reflexivity.\n    case => x0 HA HBC.\n    split => X HABC.\n    apply triple_ext_notation_iff_or_eq in HABC.\n    case HABC => HAeq.\n    rewrite HAeq. by [].\n    apply in_intersection_iff_in_and in HBC.\n    case: HBC => HB HC.\n    case: HAeq => H; rewrite H; by [].\n  Qed.\n\n  Goal {| : U | (DiffFunc A B) |} = A \\ B.\n  Proof.\n    apply mutally_included_iff_eq.\n    split => x.\n    case => x0.\n    case => HA HNB.\n    split; by[].\n    case => x0 HA HNB.\n    split. split; by [].\n  Qed.\n\nEnd IntersectionTest.\n\nTheorem LawOfIdempotenceAtIntersection:\n  forall U:Type, forall {X:Collection U}, X = X ∩ X.\nProof.\n  move => U X.\n  apply mutally_included_iff_eq.\n  split => x.\n  move => H. split; by [].\n  case. exact.\nQed.\n\nTheorem LawOfCommutativeAtIntersection:\n  forall U:Type, forall {X Y:Collection U}, X ∩ Y = Y ∩ X.\nProof.\n  move => U X Y.\n  apply mutally_included_iff_eq.\n  split => x H; apply in_intersection_iff_in_and ;apply in_intersection_iff_in_and in H; apply and_comm; by [].\nQed.\n\nTheorem LawOfAssociateAtIntersection:\n  forall U:Type, forall {A B C:Collection U}, (A ∩ B) ∩ C = A ∩ (B ∩ C).\nProof.\n  move => U A B C.\n  apply mutally_included_iff_eq.\n  split => x.\n  case => x0 HAB HC.\n  apply in_intersection_iff_in_and in HAB.\n  case HAB => HA HB.\n  split. by [].\n  split; by [].\n  move => HABC.\n  apply triple_in_intersection_to_in_and in HABC.\n  case: HABC => HA.\n  case => HB HC.\n  split. split; by []. by [].\nQed.\n\nTheorem no_intersection_empty:\n  forall (U:Type), forall (A:Collection U), ( A ∩ `Ø` ) = `Ø`.\nProof.\n  move => U A.\n  apply mutally_included_iff_eq.\n  split => x.\n  case => x0. exact.\n  case.\nQed.\n\nTheorem collection_and_fullcollection_eq_collection:\n  forall (U:Type), forall (A:Collection U), ( A ∩ (FullCollection U) ) = A.\nProof.\n  move => U A.\n  apply mutally_included_iff_eq.\n  split => x.\n  case => x0 HA HF. by [].\n  move => HA.\n  split. by [].\n  move: HA.\n  apply collection_is_subcollect_of_fullcollection.\nQed.\n\nDefinition CoPrimeAtCollection (U:Type) (A B:Collection U) := A ∩ B = `Ø`.\n\nTheorem coprime_complement:\n  forall U:Type, forall A:Collection U, CoPrimeAtCollection U A (A^c).\nProof.\n  move => U A.\n  apply mutally_included_iff_eq.\n  split => x H.\n  apply in_intersection_iff_in_and in H.\n  case: H => H.\n  case. by [].\n  apply in_intersection_iff_in_and.\n  split; move: H; apply all_collection_included_empty.\nQed.\n\nTheorem intersection_to_subcollect:\n  forall U:Type, forall A B:Collection U, A ∩ B = A -> A ⊂ B.\nProof.\n  move => U A B H.\n  rewrite -H => x.\n  move => H0.\n  apply in_intersection_iff_in_and in H0.\n  case H0 => H1. exact.\nQed.\n\nTheorem subcollect_to_intersection:\n  forall U:Type, forall A B:Collection U, A ⊂ B -> A ∩ B = A.\nProof.\n  move => U A B H.\n  apply mutally_included_to_eq.\n  split => x.\n  case => x0 HA HB. by [].\n  move => H0.\n  split; [by []|apply H; by []].\nQed.\n\nTheorem intersection_iff_subcollect:\n  forall U:Type, forall A B:Collection U, A ∩ B = A <-> A ⊂ B.\nProof.\n  move => U A B.\n  rewrite /iff. split.\n  apply: intersection_to_subcollect.\n  apply: subcollect_to_intersection.\nQed.\n\nTheorem coprime_to_intersection_complement_and_other:\n  forall U:Type, forall A B:Collection U,\n      CoPrimeAtCollection U A B -> A ∩ B^c = A.\nProof.\n  move => U A B H.\n  apply mutally_included_to_eq.\n  split => x.\n  apply in_intersection_iff_in_and.\n  move => HA.\n  split. by [].\n  move: (notin_collect_iff_in_complement U B x) => H0.\n  rewrite /iff in H0. case H0 => H1 H2.\n  apply H1.\n  apply mutally_included_iff_eq in H.\n  case: H => HE0 HE1.\n  move => HB.\n  apply: (noone_in_empty U x).\n  apply HE0.\n  split; by [].\nQed.\n\nTheorem intersection_complement_and_other_to_coprime:\n  forall U:Type, forall A B:Collection U,\n      A ∩ B^c = A -> CoPrimeAtCollection U A B.\nProof.\n  move => U A B H.\n  apply empty_collection_is_noone_in_collection.\n  rewrite -H.\n  move => x.\n  rewrite LawOfAssociateAtIntersection.\n  case => x0.\n  move => HA.\n  rewrite LawOfCommutativeAtIntersection.\n  rewrite coprime_complement.\n  apply noone_in_empty.\nQed.\n\nTheorem coprime_to_complement_other_included:\n  forall U:Type, forall A B:Collection U,\n      CoPrimeAtCollection U A B -> A ⊂ B^c.\nProof.\n  move => U A B H.\n  apply coprime_to_intersection_complement_and_other in H.\n  apply intersection_iff_subcollect in H.\n    by [].\nQed.\n\nTheorem complement_other_included_to_coprime:\n  forall U:Type, forall A B:Collection U,\n      A ⊂ B^c -> CoPrimeAtCollection U A B.\nProof.\n  move => U A B H.\n  apply intersection_complement_and_other_to_coprime.\n  apply intersection_iff_subcollect in H.\n    by [].\nQed.\n\nGoal\n  forall (U:Type) (A B:Collection U), A \\ B = A ∩ B^c.\nProof.\n  move => U A B.\n  apply mutally_included_to_eq.\n  split => x H; inversion H; split; by [].\nQed.\n", "meta": {"author": "seisyuu-hantatsushi", "repo": "implement_set_theory_in_coq", "sha": "49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c", "save_path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq", "path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq/implement_set_theory_in_coq-49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c/coq/axiom_of_replacement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6567274020018103}}
{"text": "Require Import Setoid.\nRequire Import Common.\n\nSet Implicit Arguments.\n\nSet Asymmetric Patterns.\n\nSet Universe Polymorphism.\n\nSection Gen.\n  Variable A : Type.\n  Variable equiv : relation A.\n\n  Inductive EquivalenceOf : A -> A -> Prop :=\n  | gen_underlying : forall a b, equiv a b -> EquivalenceOf a b\n  | gen_refl : forall a, EquivalenceOf a a\n  | gen_sym : forall a b, EquivalenceOf a b -> EquivalenceOf b a\n  | gen_trans : forall a b c, EquivalenceOf a b -> EquivalenceOf b c -> EquivalenceOf a c.\n\n  Hint Constructors EquivalenceOf.\n\n  Lemma EquivalenceOf_Equivalence : Equivalence EquivalenceOf.\n    constructor; eauto.\n  Defined.\n\n  Definition generateEquivalence : { equiv' : A -> A -> Prop | Equivalence equiv' & forall a b, equiv a b -> equiv' a b }.\n    exists EquivalenceOf.\n    exact EquivalenceOf_Equivalence.\n    eauto.\n  Defined.\nEnd Gen.\n\nAdd Parametric Relation A equiv : _ (@EquivalenceOf A equiv)\n  reflexivity proved by (@gen_refl _ _)\n  symmetry proved by (@gen_sym _ _)\n  transitivity proved by (@gen_trans _ _)\n    as EquivalenceOf_rel.\n", "meta": {"author": "CategoricalData", "repo": "catdb", "sha": "ce74dd70c52116a29f4589fd8d12c6439181254e", "save_path": "github-repos/coq/CategoricalData-catdb", "path": "github-repos/coq/CategoricalData-catdb/catdb-ce74dd70c52116a29f4589fd8d12c6439181254e/EquivalenceRelationGenerator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.656719192605156}}
{"text": "Require Import NArith.\nRequire Import List.\nRequire Import smart_common monads. \n\nInductive term : Type :=\n| Var : N -> term\n| App : term -> term -> term\n| Abs : term -> term.\n\nFixpoint lifti n t k :=\n  match t with\n    | Var i => if N.ltb i k then Var i else Var (i + n)\n    | Abs t => Abs ( lifti n t (N.succ k))\n    | App t u => App (lifti n t k) (lifti n u k)\n  end.\nDefinition lift n t := lifti n t 0.\n\nFixpoint substi w t n :=\n  match t with\n      Var k => if N.eqb k n then lift n w else if N.ltb k n then Var k else Var (N.pred k)\n    | Abs t => Abs (substi w t (N.succ n))\n    | App t u => App (substi w t n) (substi w u n)\n  end.\nDefinition subst u t := substi u t 0.\n\nDefinition hnf : nat -> term  -> option (term) :=\n  fuel_fix (fun x => term)\n           (fun (t:term) hnf =>\n              match t with\n                | Var n => Some (Var n)\n                | Abs t => let! t = hnf (t);\n                              retn (Abs t)\n                | App t u =>\n                  let! t =  hnf (t);\n                     match t with\n                       | Abs w => hnf (subst u w)\n                       | h => retn (App h u)\n                     end\n              end).\n\nDefinition nf big_fuel :=\n  fuel_fix (fun x => term)\n           (fun (t: term) nf =>\n              match t with\n                | Var n => Some (Var n)\n                | Abs t => let! t = nf (t);\n                               retn (Abs t)\n                | App t u =>\n                  let! t = hnf big_fuel t;\n                     match t with\n                       | Abs w => let! t = nf (subst u w);\n                                     retn t\n                       | h => let! h = nf h;\n                              let! u = nf u;\n                                 retn (App h u)\n                     end\n              end).\n\nDefinition big := 10000.\n\nDefinition Nf t := nf big big t.\n\nNotation \"\\ x\" := (Abs x) (at level 20).\nNotation \"x # y\" := (App x y) (left associativity, at level 25).\nCoercion Var : N >-> term.\n\nModule T.\n\nOpen Scope N.\nDefinition K := \\\\1.\n\nDefinition false := \\\\ 0.\nDefinition true  := \\\\ 1.\nDefinition cond  := \\\\\\ (2 # 1 #  0).\n\nDefinition pair  := \\\\\\ (0 #  2 #  1).\nDefinition fst  := \\ (0 #  true).\nDefinition snd  := \\ (0 #  false).\n\nDefinition zero := \\\\ 0.\nDefinition succ := \\\\\\ (1 #  (2 #  1 #  0)).\nDefinition one  := succ #  zero.\n\nFixpoint church n := match n with O => zero | S n => (succ #  (church n)) end.\n\nDefinition null := \\ (0 #  ( K #  false) #  true).\n\nDefinition add := \\\\ \\\\ (3 #  1 #  (2 #  1 #  0)).\nDefinition pred :=\n  let loop := \\ (let pred := fst #  0 in\n                 pair #  (succ #  pred) #  pred )\n  in \\ (snd #  (0 #  loop #  (pair #  zero #  zero))).\n\nDefinition geq := \\\\ (1 #  pred #  0 #  (K #  false) #  true).\n\nDefinition iter := \\\\( 0 #  1 #  (1 #  one)).\nDefinition ack  := \\(0 #  iter #  succ #  0).\n\nDefinition Y := \\(  (\\ (1 #  (0 #  0) ))  #  (\\ ( 1 #  ( 0 #  0)))).\nDefinition FIX := let F := (\\\\\n                    let f := 0 in\n                    let x := 1 in\n                    (f #  ( x #  x #  f ) )) in F #  F.\n\nDefinition SUM :=\n  FIX # (\\\\ ( (cond # (null # 0)) # zero # (add # 0 # (1 # (pred # 0))))).\n\n\nDefinition nil := \\\\0.\nDefinition cons := \\\\ (\\\\ (1 #  3 #  (2 #  1 #  0))).\nDefinition isnil := \\(0 # (\\\\ false) # true).\nDefinition head  := \\ (0 # (\\\\ (1)) # false).\nDefinition tail  :=\n  \\(fst # (0 # (\\\\(pair # (snd # 0)# (cons#1#(snd#0))))#(pair#nil#nil))).\n\nDefinition append := \\\\ \\\\ (3 #  1 #  (2 #  1 #  0)).\n\n\n\nDefinition partition :=\n  \\\\\n    (let fork :=\n         \\\\\n           (\n             let pred := 3 in let l := 2 in let x := 1 in let acc := 0 in\n             let l1 := fst #  acc in\n             let l2 := snd #  acc in\n             pred #  x #  (pair #  (cons #  x #  l1) #  l2) #  (pair #  l1 #  (cons #  x #  l2))\n           )\n     in\n     0 #  fork #  (pair #  nil #  nil)\n    ).\n\n\nDefinition quicksort' :=\n  FIX #  (\\\n           (let sort :=\n               \\\\\n                 (let rec := 3 in let a := 1 in let l := 0 in\n                 let p := partition #  (geq #  a) #  l in\n                 append #  (rec # (fst #  p)) #  (cons #  a #  (rec #(snd #  p))))\n           in\n           \\ (0 #  sort #  nil))\n        ).\n\n(* A more usual presentation of quicksort. *)\nDefinition quicksort :=\n  FIX #  (\\\\\n            (cond\n                # (isnil # 0)\n                # (nil)\n                # (let hd := head # 0 in\n                    let tl := tail # 0 in\n                    let p := partition #  (geq #  hd) #  tl in\n                    let rec := 1 in\n                    append #  (rec # (fst #  p)) #  (cons # hd #  (rec #(snd #  p)))))).\n\nFixpoint list l :=\n  match l with\n    | List.cons t q => cons # t # (list q)\n    | List.nil => nil\n  end.\nEnd T.\n\n\nSection nat.\n  Context {A : Type}.\n  Variable iter : A -> A.\n  Variable init : A.\n  Fixpoint eval_rec t := match t with\n                           | Var 0 => retn init\n                           | App (Var 1) u => let! x = eval_rec u;\n                                              retn (iter x)\n                           | _ => None\n                         end.\n  Definition eval_nat t :=\n    match t with\n        | Abs (Abs t) => eval_rec t\n        | _ => None\n    end.\nEnd nat.\nDefinition compute_nat := eval_nat S O.\n\nDefinition normal_nat n := let! t = Nf n; compute_nat (t).\n\n(* Time Eval vm_compute in nf big big (T.SUM # T.church 1). *)\n(* Time Eval vm_compute in normal_nat (T.SUM # T.church 5). *)\n(* Eval compute in normal_nat (T.snd # (T.pair # T.zero # T.one)). *)\n(* Eval compute in normal_nat (T.pred # T.church 5). *)\n\nSection u.\n  Fixpoint eval_lrec t := match t with\n                           | Var 0 => retn (List.nil)\n                           | App (App (Var 1) x) l =>\n                             let! x = compute_nat x;\n                             let! q = eval_lrec l  ;\n                             retn (List.cons x q)\n                           | _ => None\n                         end.\n  Fixpoint eval_list_of_nats t :=\n    match t with\n        Abs (Abs t) => eval_lrec t\n      | _ => None\n    end.\nEnd u.\nDefinition normal_list_of_nats l := let! l = Nf l; eval_list_of_nats l.\n\nOpen Scope list_scope.\n\nDefinition list l := T.list (List.map T.church l).\n(* Eval vm_compute in normal_list_of_nats (list  (1::nil))%nat. *)\n(* Eval vm_compute in normal_list_of_nats (T.append #  (list  (1::2:: nil)) # (list  (nil)))%nat. *)\n(* Eval vm_compute in nf big big (T.geq # T.church 2 # T.church 1). *)\n\n(* Eval vm_compute in normal_list_of_nats (T.snd # (T.partition # (T.geq # T.church 3) # (list  (1::2 ::5::nil))))%nat. *)\n(* Eval vm_compute in normal_list_of_nats (T.append #  (list  (1::2:: nil)) # (list  (nil)))%nat. *)\n\nDefinition quicksort l := normal_list_of_nats  (T.quicksort # (list l)).\nDefinition quicksort' l := normal_list_of_nats  (T.quicksort' # (list l)).\n\n(* Time Eval vm_compute in quicksort' (0::3::5::2::4::1::nil). *)", "meta": {"author": "braibant", "repo": "hash-consing-coq", "sha": "e7bdcb3d5e73d523e056e9e0703d5731f1a6cdf6", "save_path": "github-repos/coq/braibant-hash-consing-coq", "path": "github-repos/coq/braibant-hash-consing-coq/hash-consing-coq-e7bdcb3d5e73d523e056e9e0703d5731f1a6cdf6/smart/reference_lambda.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6566860977001406}}
{"text": "Fixpoint 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.\n\nTheorem eqb_refl : forall n : nat,\n  (n =? n) = true.\nProof.\n  intros.\n  induction n.\n  - simpl. reflexivity.\n  - simpl. rewrite IHn. reflexivity.\nQed.", "meta": {"author": "cristianlepore", "repo": "Coq_exercises", "sha": "109d34794edee6bd2b255ed4f7fc3c91edb8c8f5", "save_path": "github-repos/coq/cristianlepore-Coq_exercises", "path": "github-repos/coq/cristianlepore-Coq_exercises/Coq_exercises-109d34794edee6bd2b255ed4f7fc3c91edb8c8f5/Software_foundation/Chapter2/eqb_refl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6566544010630981}}
{"text": "Require Export Metalib.Metatheory.\nRequire Export Transitions.\nRequire Export Ch6.\n\n(* Chapter 7: The Evaluation dynamics relation presented in this chapter is more commonly called\n   a \"bigstep\" semantics\" *)\n\n\n\n(*************************************************************************)\n(** * Structural Dynamics 7.1 *)\n(*************************************************************************)\n\n(* We can define the inductive relation shown in 7.1 as below *)\nInductive bigstep : exp -> exp -> Prop :=\n| big_num : forall i, bigstep (exp_num i) (exp_num i)\n                         \n| big_str : forall i, bigstep (exp_str i) (exp_str i)\n                         \n| big_plus : forall e1 i1 e2 i2,\n    bigstep e1 (exp_num i1) ->\n    bigstep e2 (exp_num i2) ->\n    bigstep (exp_op plus e1 e2) (exp_num (i1 + i2))\n            \n| big_let : forall e1 v1 e2 v2,\n    bigstep e1 v1 ->\n    bigstep (open e2 v1) v2 ->\n    bigstep (exp_let e1 e2) v2.\n\nHint Constructors bigstep.\n\n(* Lemma 7.1 *)\nLemma bigstep_value : forall e v, bigstep e v -> value v.\nProof.\n  intros e v B. induction B; auto.\nQed.\n\n(* Our representation requires this as well. *)\nLemma bigstep_lc_1 : forall e1 e2, bigstep e1 e2 -> lc e1.\nProof.\n  intros e1 e2 B. induction B; auto.\n  pick fresh x and apply lc_let; auto.\n  rewrite (subst_intro x) in IHB2; auto.\n  apply (subst_lc_inverse x v1) in IHB2.\n  auto. destruct (bigstep_value e1 v1 B1); auto.\nQed.  \n\n(*************************************************************************)\n(** * Relating Structural and Evaluation Dynamics 7.2 *)\n(*************************************************************************)\n\nLemma big_to_small : forall e v, bigstep e v -> multistep e v.\nProof.\nAdmitted.  (* needs congruence lemma from Ch5.v, as well as multistep_transitive *)\n\nLemma small_to_big : forall e e', step e e' -> forall v, bigstep e' v -> bigstep e v.\nProof.\nAdmitted.\n", "meta": {"author": "plclub", "repo": "cis670-16fa", "sha": "e123c26d06a883b599c9bbf2474610ad84975a8c", "save_path": "github-repos/coq/plclub-cis670-16fa", "path": "github-repos/coq/plclub-cis670-16fa/cis670-16fa-e123c26d06a883b599c9bbf2474610ad84975a8c/code/Ch7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.6566543922789182}}
{"text": "Set Implicit Arguments.\nSet Asymmetric Patterns.\n\n\n\n(* ================================================*)\n(* 0. Functional Programming                       *)\n(* ================================================*)\n\n(*\n    Functional programming (Coq's style)\n\n    1. Types provide guidance for building and\n       destructing data\n    2. Programs are data\n\n*)\n\n(* ----------------------------------------------- *)\n\n(*\n    Programs are data\n\n    There is no “return” keyword:\n      expression = statement\n\n    - The program that always returns 4 is:\n        4\n    - This program also returns (or better computes\n      to) 4:\n        if (false || true) then 2 + 2 else 7\n        if true then 2 + 2 else 7\n        2 + 2\n        4\n    - This program also computes to 4:\n        2 + (if 7 == 2 then 4 else 2)\n        2 + (if false then 4 else 2)\n        2 + 2\n        4\n*)\n\n(* ----------------------------------------------- *)\n\n(*\n    Programs are /really/ data\n\n    This data is actually a program that doubles\n    its input:\n\n      (fun x => x + x)\n\n    What does this evaluate to?\n\n      (fun x => x + x) 3\n    \n    Recall:  f(x) is written (f x) in Coq\n\n    This program takes in input a function f and\n    uses it twice\n\n      (fun f => f 3 + f 4)\n\n    What does this evaluate to?\n\n      (fun f => f 3 + f 4) (fun x => x + x)\n*)\n\n(* ================================================*)\n(* 1. Build and destruct simple data               *)\n(* ================================================*)\n\n(* Booleans *)\n\nCheck bool : Type.\nCheck true : bool.\nCheck false.\n\n(* Booleans are defined in the prelude as a data\n   type with exactly the two constructors\n   true and false:\n\n   Inductive bool : Type := true | false.\n\n   We can use this fact when we program with\n   booleans via the \"match .. with .. end\"\n   construct.\n*)\n\n(* Example: defining the negation *)\nDefinition negb (b : bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\n(* Let's look at the type of the function we've just\n   defined\n*)\nCheck negb.\n\n(* Given the type of negb, if we apply it to a\n   boolean expression we obtain a boolean.\n*)\nCheck (negb false).\n\n(* Actually, the outermost parentheses can be\n   omitted.  Like in:\n   Check negb false.\n*)\n\n(* In this lecture we are not going to prove that\n   our programs are correct, that is the topic of \n   the next lesson.  We are going to just test\n   our programs.\n*)\nEval compute in negb true.\nEval compute in negb false.\n\n(* The system provides syntactic sugar for\n   matching over a boolean.\n*)\nDefinition another_negb (b : bool) : bool :=\n  if b then false else true.\n\n(* Note that Definition is just a convenient syntax\n   to name an otherwise anonymous function *)\nDefinition yet_another_negb :=\n  (fun b : bool =>\n     if b then false else true). \n\n(* Definition of the boolean conjunction.\n\n   Note: pattern matching over multiple values\n   is just syntactic sugar.   \n*)\nDefinition andb (b1 : bool) (b2 : bool) :=\n  match b1, b2 with\n  | true, true => true\n  | _, _ => false\n  end.\n (* actually, this is equivalent to:\n    if b1 then b2 else false *)\n\n(* Some more syntactic sugar *)\nNotation \"x && y\" := (andb x y).\n\nEval compute in true && false.\nEval compute in true && true.\n\n\n(* ----------------------------------------------- *)\n\n(* Polymorphic data containers: the option type *)\n\n(* The simplest generic container is the option type.\n   Such container can either be empty, i.e. contain\n   no value, or it can contain some value.\n   Such container type is parametric over the\n   type A of the values it contains.\n\n   Inductive option (A : Type) : Type :=\n   | None\n   | Some (a : A).\n*)\n\nCheck option.\nCheck option bool : Type.\n\n\nCheck Some true. (* Implicit argument *)\nAbout Some.\n\n(* The @ locally disables the implicit arguments *)\nCheck @Some bool true.\nCheck @Some _ true.\n\n(* We now define a function checking if an\n   option holds a value or not.\n \n   Note the A parameter needed in order to wirte\n   the type of \"box\"\n*)\nDefinition is_empty A (box : option A) : bool :=\n  match box with\n  | None => true\n  | Some _ => false  (* Here _ means discard *)\n  end.\n\n(* Note the implicit argument (A not passed) *)\nEval compute in is_empty (Some true).\n\n(* Note: the function is polymorphic! *)\nEval compute in is_empty (Some 4).\n\n(* first example of match with a binder *)\nDefinition get_default A (box: option A) (a : A) : A :=\n  match box with\n  | None => a\n  | Some x => x\n  end.\n\nEval compute in get_default None 3.\n\n(* Here x binds the contents of the Some container,\n   the value 4, that is also the result. *)\nEval compute in get_default (Some 4) 3.\n\n\n\n(* Pairs *)\n\n(* There is only a way to build a pair, and any\n   two values can be paired\n\n   Inductive prod (A B : Type) : Type :=\n   | pair (a : A) (b : B).\n\n   Notation \"A * B\" := (prod A B).\n   Notation \"( x , y )\" := (pair x y).\n*)\n \nCheck (true, Some false).\n\nDefinition fst A B (p : A * B) :=\n  match p with (x, _) => x end.\n\nEval compute in fst (true, None).\n\n\n\n\nDefinition snd A B (p : A * B) :=\n  match p with (_, y) => y end.\n\n(* Exercises<<<<<<<<<                              *)\n\n(* 1.1 Write a comparison function for the bool\n   data type.\n   Such function must evaluate to true if and only if\n   the two input booleans b1 and b2 have the same\n   value\n*)\nDefinition eq_bool (b1 b2 : bool) : bool :=\n  match b1, b2 with\n  | true, true | false, false => true\n  | _, _ => false\n  end.\n\n(* 1.2 Test the function you just wrote *)\nEval compute in eq_bool true true.\nEval compute in eq_bool false false.\nEval compute in eq_bool true false.\nEval compute in eq_bool false true.\n\n(* 1.3 Write a function that computes the exclusive\n   or of the two booleans in input *)\nDefinition xorb (b1 b2 : bool) : bool :=\n  if eq_bool b1 b2 then false else true.\n\n(* 1.4 Test the function you just wrote *)\nEval compute in\n\n(* 1.5 Write and test a function that\n   applies the fst projection over the option\n   type.\n\t  \n   Hint: if o had type option (A * B) and, after\n   scrutiny o turns out to be \"Some x\", which is\n   the type of x?\t   \n *)\nDefinition ofst A B (o: option (A * B)) : option A :=\n\n(* Exercises>>>>>>>>>                              *)\n\n(* ================================================*)\n(* Recursive data and fixpoints *)\n(* ================================================*)\n\n(* Datatypes can be recursive\n\n   Inductive nat : Type :=\n   | O\n   | S (n : nat).\n*)\n\nCheck S (S O).\nCheck 1.\n\n(* Recursive types, recursive functions\n\n*)   \nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n  | O => m\n  | S n1 => S (plus n1 m)\n  end.\n\nInfix \"+\" := plus.\n\nCheck 1 + 2.\nEval compute in 1 + 2.\n\nFixpoint fast_plus (n : nat) (m : nat) : nat :=\n  match n with\n  | O => m\n  | S n1 => fast_plus n1 (S m)\n  end.\n\nCheck fast_plus 1 2.\n\n\nEval simpl in\n  (fun n => fast_plus (S n) 3).\nEval simpl in\n  (fun n => plus (S n) 3).\n\n\n(* Lists are pretty much like naturals \n   \n  Inductive list (A : Type) : Type :=\n  | nil\n  | cons (x : A) (xs : list A).\n  \n*)\nInfix \"::\" := cons.\nArguments nil {A}.\nArguments cons {A}.\n\n(* The type of lists imposes all the elements to\n    be in the same type! *)\nCheck true :: false :: nil.\nFail Check 1 :: false :: nil.\n\n(* A non recursive function on lists *)\nDefinition tl A (l : list A) : list A :=\n  match l with\n  | nil => nil\n  | _ :: xs => xs\n  end.\n\nEval compute in tl (6 :: 99 :: nil).\n\n(* The most popular function on lists *)\nFixpoint len A (l : list A) : nat :=\n  match l with\n  | nil => O\n  | x :: xs => 1 + (len xs)\n  end.\n\nEval compute in len (1 :: 2 :: 3 :: nil).\n\n(* Two other examples of function over lists:\n\n   - from a list of pairs, to a pair of lists\n   - from two lists, to a list of pairs\n\n   Note the let construction to name an\n   intermediate result used more than once.\n\n*)\nFixpoint split A B (l : list (A * B)) : list A * list B :=\n  match l with\n  | nil => (nil, nil)\n  | (x,y) :: rest =>\n      let xs_ys := split rest in\n      (x :: fst xs_ys, y :: snd xs_ys)\n  end.\n\nEval compute in\n  split ((1,2) :: (3,4) :: nil).\n\nFixpoint zip A B (la : list A) (lb : list B) : list (A * B) :=\n  match la, lb with\n  | nil, nil => nil\n  | x::xs, y::ys => (x,y) :: zip xs ys\n  | _, _ => nil\n  end.\n\nEval compute in\n  zip (1 :: 2 :: nil) (true :: false :: nil).\n\nEval compute in\n  let xs_ys := split ((1,2) :: (3,4) :: nil) in\n  zip (fst xs_ys) (snd xs_ys).\n\n(* Exercises<<<<<<<<<                              *)\n\n(* 2.1 Write a function to compare two natural\n   numbers n1 and n2.\n   It must evaluate to true if and only if the\n   two numbers are equal *)\nFixpoint eq_nat n1 n2 :=\n\nEval compute in eq_nat 7 4.\nEval compute in eq_nat 7 7.\nEval compute in eq_nat 7 (3 + 4).\n\n(* 2.2 Write a function that computes the product\n   of two natural numbers. Hint: you can use\n   (many times) the function that computes the\n   addition of natural numbers *)\nFixpoint mult n1 n2 :=\n\nInfix \"*\" := mult.\n\nEval compute in 3 * 4.\nEval compute in eq_nat (3 * 4) 12. \nEval compute in eq_nat (3 * 0) 0.\nEval compute in eq_nat 0 (3 * 0).\n\n(* 2.3 Write a function that appends two lists\n\n   Example:\n     append (1 :: 2 :: nil) (3 :: nil)\n   must evaluate to\n     (1 :: 2 :: 3 :: nil)\n\n*)\nFixpoint\n  append A (l1 : list A) (l2 : list A) : list A\n:=\n\nEval compute in append (1 :: 2 :: nil) (3 :: nil).\n\n(* 2.4 Write a function that reverses a list.\n   Hint: use append. *)\nFixpoint rev1 A (l : list A) : list A :=\n\nEval compute in rev1 (1 :: 2 :: 3 :: nil).\n\n\n(* 2.5 Again list reversal, but this time using\n   an auxiliary function that uses an accumulator. *)\nFixpoint rev2_aux A (acc l : list A) : list A :=\n  match l with\n  | nil => acc\n  end.\n\nDefinition rev2 A (l : list A) := rev2_aux nil l.\n\nEval compute in rev2 (1 :: 2 :: 3 :: nil). \n\n(* Exercises>>>>>>>>>                              *)\n\n(* ================================================*)\n(* Illegal data types and recursive functions *)\n(* ================================================*)\n\nFail\nFixpoint wrong A (l : list A) {struct l} :=\n  match l with\n  | nil => 0\n  | x :: xs => 1 + wrong (x :: nil)\n  end.\n\n(* RUN THAT IN A PATCHED (UNSOUND) COQ\n\n   Recall:\n   \n     Inductive False : Prop := .\n     \n   i.e. There is no way to build a value\n   of type False.\n\n*)\n\n(*\nFixpoint loop (n : nat) : False := loop n.\n\nCheck loop 3.\nFail Timeout 2 Eval compute in loop 3.\n\nInductive non_positive : Type :=\n| Call (f : non_positive -> False)\n\nDefinition self (t : non_positive) : False :=\n  match t with\n  | Call f => f t\n  end.\n\nDefinition loop2 : False := self (Call self).\n\nFail Timeout 2 Eval compute in loop2.\n*)\n\n(* \n   Note: for the experts in the room...\n   Yes, there are ways to use a well founded order\n   relation as the decreasing measure. See the\n     \n     Function ... {measure ...}\n\n   and\n\n     Function ... {wf ...}\n\n   in the Reference Manual.\n*)\n\n(* ================================================*)\n(* Higher order programming *)\n(* ================================================*)\n\n(* A function can be abstracted over another\n   function.  It is a useful mechanism to write\n   code that can be reused, especially in the context\n   of polymorphic containers\n*)\nFixpoint map A B (f : A -> B) (l : list A) : list B :=\n  match l with\n  | nil => nil\n  | x :: xs => f x :: map f xs\n  end.\n\nEval compute in\n  map (fun x => x + 2) (3 :: 4 :: 7 :: nil).\nEval compute in\n  map negb (true :: false :: nil).\n  \n(* fold f (x1 :: x2 :: .. xn :: nil) a\n     =\n\t    (f xn (.. (f x2 (f x1 a))))\n*)\nFixpoint fold A B (f : B -> A -> A) (l : list B) (a : A) : A :=\n  match l with\n  | nil => a\n  | x :: xs => fold f xs (f x a)\n  end.\n\nEval compute in fold plus (1 :: 2 :: 3 :: nil) 0.\n\n\n(* Exercises<<<<<<<<<                              *)\n\n(* 4.1 Write a function that reverses a list based on       fold.  Hint: use fold and cons.\n*)\nDefinition rev A (l : list A) :=\n\nEval compute in rev (1 :: 2 :: 3 :: 4 :: nil).\n\n(* 4.2 Write a function that appends two lists, this\n   time using fold and rev *)\nDefinition another_append A (l1 l2 : list A) :=\n\nEval compute in\n  another_append (1 :: 2 :: nil) (3 :: 4 :: nil).\n\n(* 4.3 The higher order function iter takes a\n   function f, an initial value a and a number n.\n   The result is (f (f ... (f a))),\n   where f is applied n times. *) \nFixpoint iter A (f : A -> A) a n :=\n\n(* 4.4 Write a function that computes the sum of\n   two natural numbers using iter *)\nDefinition another_plus n1 n2 :=\n\nEval compute in another_plus 3 4.\n\n(* 4.5 Write a function that computes the product of\n   two natural numbers using iter and plus *)\nDefinition another_mult n1 n2 :=\n\nEval compute in another_mult 3 7.\nEval compute in another_mult 3 0.\nEval compute in another_mult 0 7.\nEval compute in another_mult 2 4.\n\n(* Exercises>>>>>>>>>                              *)\n\n(* ================================================*)\n(* Code reuse: a taste of ad-hoc polymorphism *)\n(* ================================================*)\n\nClass Eq (A : Type) := cmp : A -> A -> bool.\n\nInfix \"==\" := cmp (at level 70, no associativity).\n\nFixpoint mem A `{Eq A} (y : A) (l : list A) : bool :=\n  match l with\n  | nil => false\n  | x :: xs => if x == y then true else mem y xs\n  end.\n\nInstance bool_Eq : Eq bool := eq_bool.\n\nCheck mem true (false :: false :: true :: nil).\nEval compute in\n  mem true (false :: false :: true :: nil).\n\nInstance pair_Eq A `{Eq A} B `{Eq B} : Eq (A * B) :=\n  fun (x y : A * B) =>\n    (fst x == fst y) && (snd x == snd y).\n\nEval compute in\n  mem (true,false)\n        ((false,false) :: (true,false) :: nil).\nEval compute in\n  mem (true,false)\n        ((false,false) :: (false,true) :: nil).\n\n(* Exercises<<<<<<<<<                              *)\n\n(* 5.1 Register eq_nat as the comparison function\n   for the nat type *)\nInstance nat_Eq : Eq nat :=\n\n(* Example: an associative list mapping numbers to\n   boolean values.\n   1 is mapped to true, 2 to false. *)\nDefinition an_associative_list : list (nat * bool) :=\n  (1,true) :: (2,false) :: nil.\n\n(* 5.2 Write a function that finds the value\n   associated to y in the associative list l.   *)\nFixpoint\n  find A {e : Eq A} (y : A) B (l : list (A * B))\n:\n  option B\n:=\n\nDefinition data := 1 :: 4 :: 7 :: nil.\n\n(* 5.3 Define a list of pairs of natural numbers\n   such that the first item is an element of the list\n   data (the one just defined) and the second item\n   is its square.\n   I.e.  the list must be (1,1)::(4,16)::... but\n   don't write it by hand.  Instead, use map. *)\nDefinition square_cache :=\n\nEval compute in find 3 square_cache.\n\n(* 5.4 The function square takes a cache c (that is\n   an associative list) and a number n.  It computes\n   a pair: the first component is the square of the\n   input n while the second component is\n   an (eventually) updated cache. *)\nDefinition square cache n :=\n\nEval compute in square square_cache 3.\n\n(* Exercises>>>>>>>>>                              *)\n\n(* vim: set tw=50 *)\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/coqITP2015-ex2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.6566543922789182}}
{"text": "From BraidsT Require Import CpdtTactics.\nFrom BraidsT Require Import supp.\n\nRequire Import Bool PeanoNat List Nat.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\n(* Unset Strict Implicit. *)\n(* Unset Printing Implicit Defensive. *)\n\nRequire Import ProofIrrelevance.\n\nRequire Import ZArith.\nRequire Import Coq.Sorting.Permutation.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nHint Rewrite app_nil_r : core.\n\nDefinition BNat lim := { n | n < lim }.\n\nModule Braids.\n\nSection Theory.\n\nVariable N : nat.\nHypothesis large_enough : 10 < N.\n\nDefinition free_braidlike_monoid := list (BNat (pred N)).\n\nDefinition mult_fbm : free_braidlike_monoid -> free_braidlike_monoid -> free_braidlike_monoid := app (A:=_).\n\nHint Unfold mult_fbm : core.\n\nNotation \"x * y\" := (mult_fbm x y).\n\nLemma braids_has_1 : exists e : free_braidlike_monoid, forall x, x * e = x /\\ e * x = x.\nProof.\n  unfold \"*\";\n  exists [];\n  crush.\nQed.\n\nLemma braids_assoc : forall (x y z : free_braidlike_monoid), (x * y) * z = x * (y * z).\nProof.\n  unfold \"*\";\n  crush.\nQed.\n  \nDefinition ns_list (n:nat) := rev ((fix F n :=\n  match n with\n  | 0 => []\n  | S n' => n :: (F n')\n  end) n).\n\nLemma ns_list_len : forall n, length(ns_list n) = n.\nProof.\n  intros.\n  induction n.\n  - trivial.\n  - unfold ns_list. rewrite rev_length.\n    unfold ns_list in IHn. rewrite rev_length in IHn.\n    simpl. rewrite IHn. trivial.\nQed. \n\nHint Rewrite ns_list_len.\n\nEval compute in ns_list 10.\n\nDefinition braid_perm := { perm : list nat | Permutation perm (ns_list N) }.\n\nLemma braid_perm_size : forall bp : braid_perm, length (proj1_sig bp) = N.\nProof.\n  intros.\n  destruct bp as [perm P].\n  simpl. apply Permutation_length in P. rewrite ns_list_len in P. apply P.\nQed.\n\nLemma braid_list_len : forall l, Permutation l (ns_list N) -> length l = N.\nProof.\n  intros l Hl.\n  crush.\nQed.\n\nHint Rewrite braid_perm_size.\n(* Hint Rewrite braid_list_len. *)\nHint Constructors Permutation : core.\n\nLemma Permutation_rev__l : forall {A} (l : list A), Permutation (rev l) l.\nProof.\n  intros A.\n  intros l.\n  replace l with (rev (rev l)) at 2.\n  apply Permutation_rev.\n  apply rev_involutive.\nQed.\n\nPrint braid_perm.\nCheck exist.\n\nLemma no_empty {T} : forall i, S (S i) <= length(@nil T) -> False.\nProof.\n  simpl. intros.\n  inversion H.\nQed.\n\nLemma no_single {T} : forall i (x:T), S (S i) <= length([x]) -> False.\nProof.\n  simpl. intros.\n  inversion H. inversion H1.\nQed.\n\nNotation \"[[ x ]]\" := (exist _ x _).\nNotation \"[[ x | P ]]\" := (exist _ x P).\n\nDefinition optionTest : option nat := Some 4.\n\nDefinition optionTestVal : nat :=\n  match optionTest with\n  | None => 0\n  | Some x => x\n  end.\n\nNotation \"x <?- e1 ;; e2\" := (match e1 with | None => None | Some x => e2 end)  (at level 50).\nNotation \"x <!- e1 ;; e2\" := (match e1 with | None => False | Some x => e2 end)  (at level 50).\n\nDefinition optionNotationTest x : option nat :=\n  y <?- optionTest;;\n  Some (x + y).\n\nEval compute in optionNotationTest 4.\n\nFixpoint transpose_if_lt (l : list nat) (i : nat) : option (list nat) :=\n  match l with\n  | [] => None\n  | [_] => None\n  | (x::y::xs) => (\n    match i with\n    | 0 => if x <? y then Some (y :: x :: xs) else Some (x :: y :: xs)\n    | S i' => (rec <?- transpose_if_lt (y::xs) i' ;; Some (x :: rec))\n    end\n  )\n  end.\n\nLemma transpose_if_lt_defined : forall l i (H: S i < length l), { res | transpose_if_lt l i = Some res }.\n  refine (fix F l i (H: S i < length l) {struct i} : { res | transpose_if_lt l i = Some res } := _).\n  generalize l i H.\n  clear l i H.\n  intros l.\n  refine (match l with | [] => _ | [_] => _ | (x::y::xs) => _ end); intros; try solve [clear F; crush].\n  destruct i. {\n  simpl. destruct (x <? y).\n  - exists (y :: x :: xs). trivial.\n  - exists (x :: y :: xs). trivial.\n  }\n  - assert (HRec: { rec | transpose_if_lt (y::xs) i = Some rec }).\n    { apply F. crush. }\n    Guarded.\n    destruct HRec as [rec HRec]. exists (x :: rec). simpl.\n    rewrite HRec. trivial.\nDefined.\n\n(*\nDefinition transpose_if_lt (l : list nat) (i:BNat (pred (length l))) : { l' : list nat | Permutation l' l }.\n  refine ((let fix F l i : (S (S i) <= length(l)) -> { l' : list nat | Permutation l' l } :=\n    match l return (S (S i) <= length(l) -> _) with\n    | []  => fun H => match (no_empty H) with end\n    | [x] => fun H => match (no_single H) with end\n    | (x::y::xs) => fun H => (match i as m return (i = m -> _ ) with\n      | (S i') => fun Heq => (match ((F (y::xs) i' _)) with | [[rec | Hind]]  => [[(x::rec)]] end)\n      | 0 => fun Heq => if x <? y then [[(y::x::xs)]] else [[(x::y::xs)]]\n      end) (eq_refl _)\n    end in F l (proj1_sig i) _)). \n    Unshelve.\n    { destruct i; crush. }\n    { apply perm_swap. }\n    { crush. }\n    { crush. }\n    { apply perm_skip. apply Hind. }\nDefined.\n*)\n\nInductive transpose_if_ltR : forall (l:list nat) (l':list nat) (i:nat), Prop :=\n| transpose_if_lt_step x xs l' n (H: transpose_if_ltR xs l' n) : transpose_if_ltR (x::xs) (x::l') (S n)\n| transpose_if_lt_swap x y xs (H: x < y) : transpose_if_ltR (x::y::xs) (y::x::xs) 0\n| transpose_if_lt_noswap x y xs (H: ~(x < y)) : transpose_if_ltR (x::y::xs) (x::y::xs) 0.\n\nLemma transpose_if_lt_FtR : forall (l:list nat) i (H: S i < length l),\n  l' <!- transpose_if_lt l i;;\n  transpose_if_ltR l l' i.\nProof.\n  refine (fix IH l i H {struct i} := _).\n  generalize l i H. clear l i H.\n  intros l.\n  refine (match l with | [] => _ | [_] => _ | (x::y::xs) => _ end); intros; try solve [clear IH; crush].\n  destruct i.\n  2: { simpl. destruct (@transpose_if_lt_defined (y::xs) i).\n       { crush. }\n       { rewrite e. apply transpose_if_lt_step.\n         refine (let IH := IH (y::xs) i _ in _).\n         Unshelve.\n         2: { crush. }\n         rewrite e in IH. assumption.\n       }\n  }\n  simpl. destruct (Nat.ltb_spec x y).\n  { apply transpose_if_lt_swap. assumption. }\n  { apply transpose_if_lt_noswap. apply le_not_lt. assumption. }\nQed.\n\nLemma transpose_if_lt_RtF : forall l l' i, transpose_if_ltR l l' i -> transpose_if_lt l i = Some l'.\nProof.\n  intros l l' i H.\n  induction H.\n  - destruct xs as [| y xs].\n    + exfalso. destruct n; crush.\n    + simpl. rewrite IHtranspose_if_ltR. trivial.\n  - simpl. destruct (Nat.ltb_spec x y). { trivial.} { apply le_not_lt in H0. contradiction. }\n  - simpl. destruct (Nat.ltb_spec x y). { contradiction. } { trivial. }\nQed.\n\nLemma transpose_if_lt_perm : forall l i (H: S i < length l),\n    { l' | transpose_if_lt l i = Some l' /\\ Permutation l l' }.\nProof.\n  intros l i H.\n  refine (let HRel := transpose_if_lt_FtR l H in _).\n  destruct (transpose_if_lt_defined l H) as [l' Hl].\n  rewrite Hl in HRel.\n  exists l'. split.\n  - apply Hl.\n  - induction HRel; try solve [  apply Permutation_refl || constructor ].\n    apply perm_skip. apply IHHRel.\n    { crush. }\n    apply transpose_if_lt_RtF. assumption.\nDefined.\n\nDefinition transpose_braid (bp : braid_perm) (i:BNat (pred N))\n  : braid_perm.\n  destruct bp as [l Hl].\n  destruct i as [i' Hi'].\n  assert (S i' < length l). { crush. }\n  destruct (transpose_if_lt_perm l H).\n  refine ([[x]]).\n  apply perm_trans with (l':=l).\n  - destruct a as [_ HP]. apply Permutation_sym. assumption.\n  - assumption.\n  Show Proof.\nDefined.\n\n\nFixpoint pi_braid (b : free_braidlike_monoid) : braid_perm.\n  refine ((match b as m return (b = m -> _) with\n    | [] => fun Heq => _\n    | (x::xs) => fun Heq => _\n    end) (eq_refl _)).\n  - refine [[ns_list N]]; trivial.\n  - refine (let xs' := pi_braid xs in (transpose_braid xs' x)).\nDefined.\n\nNotation \"'fbm'\" := free_braidlike_monoid.\n\nNotation \"x <- e1 ;; e2\" := (match e1 with [[x]] => e2 end) (at level 100).\n\n(* Definition twice_transpose_if_ltRT (l:list nat) (n:BNat (pred (length l))) : Prop.\n  refine (let l1 := @transpose_if_lt l n in _).\n  destruct l1 as [l1 Hl1].\n  refine (let l2 := @transpose_if_lt l n in _).\n  destruct l2 as [l2 Hl2].\n  destruct n as [n Hn].\n  refine (let l3 := @transpose_if_lt l2 [[n]] in _).\n  destruct l3 as [l3 Hl3].\n  exact (l1 = l3).\n  Unshelve.\n  apply Permutation_length in Hl2. rewrite Hl2. assumption.\nDefined.\n\nLemma twice_transpose_if_lt : forall l n, twice_transpose_if_ltRT l n.\nProof.\n  unfold twice_transpose_if_ltRT.\n  refine (fix F l n : twice_transpose_if_ltRT l n := _).\n  unfold twice_transpose_if_ltRT.\n  destruct n as [n Hn].\n  refine ((match l as m return (l = m -> _) with\n    | [] => _\n    | [x] => _\n    | (x::y::xs) => _\n    end) eq_refl).\n  - intros. exfalso. assert (2 <= length (l)); crush.\n  - intros. exfalso. assert (2 <= length (l)); crush.\n  - refine ((match n as m return (n = m -> _) with \n      | 0 => _\n      | S n' => _\n      end) eq_refl).\n  2: { intros. .\n\n\n - intros. crush. try solve [clear F; crush]. *)\n\n\nLemma twice_transpose_braid_0 : forall l n,\n  transpose_braid l n = (transpose_braid (transpose_braid l n) n).\nProof.\n  \n\n\n  intros [l Hl] [n Hn].\n  generalize dependent l.\n  induction n; intros l Hl.\n  - refine ((match l as l' return (l' = l -> _) with [] => _ | [x] => _ | (x::y::xs) => _ end) eq_refl).\n    + intros. exfalso. assert (2 <= length (l)); crush.\n    + intros. exfalso. assert (2 <= length (l)); crush.\n    + intros. subst l. destruct (x <? y) eqn:Heq.\n    * unfold transpose_braid. unfold transpose_if_lt. simpl. rewrite Heq.\n      assert ((y <? x) = false). { apply (lt_antisymm Heq). } rewrite H.\n      apply subset_eq_compat. trivial.\n    * unfold transpose_braid. unfold transpose_if_lt. simpl. rewrite Heq. rewrite Heq.\n      apply subset_eq_compat. trivial.\n  - refine ((match l as l' return (l' = l -> _) with [] => _ | [x] => _ | (x::y::xs) => _ end) eq_refl).\n    + intros. exfalso. assert (2 <= length (l)); crush.\n    + intros. exfalso. assert (2 <= length (l)); crush.\n    + intros. subst l.\n      unfold transpose_braid.\n      apply transpose_if_lt_ind with .\n\nDefinition sub_b : BNat (pred N) -> BNat (pred N) -> BNat (pred N).\n  intros n m.\n  destruct n as [n Hn]. destruct m as [m Hm].\n  exists (n - m).\n  crush.\nDefined.\n\nDefinition le_b : BNat (pred N) -> BNat (pred N) -> Prop.\n  intros n m.\n  destruct n as [n Hn]. destruct m as [m Hm].\n  exact (n <= m).\nDefined.\n\nDefinition lt_b : BNat (pred N) -> BNat (pred N) -> Prop.\n  intros n m.\n  destruct n as [n Hn]. destruct m as [m Hm].\n  exact (n < m).\nDefined.\n\nLemma lt_1_N : 1 < pred N.\nProof.\n  crush.\nQed.\n\nInductive braid_eq : fbm -> fbm -> Prop :=\n| braid_eq_refl : forall x, braid_eq x x\n| braid_eq_symm : forall x y, braid_eq x y -> braid_eq y x\n| braid_eq_trans : forall x y z, braid_eq x y -> braid_eq y z -> braid_eq x z\n| braid_eq_idemp : forall i, braid_eq [i; i] [i]\n| braid_eq_farcomm : forall i j : BNat (pred N), lt_b [[1 | lt_1_N ]] (sub_b j i) ->\n      braid_eq [i; j] [j; i]\n| braid_eq_braid : forall i j : (BNat (pred N)), [[1 | lt_1_N]] = (sub_b j i) -> \n      braid_eq [i; j; i] [j; i; j].\n\nTheorem braid_eq__pi_eq : forall b1 b2, braid_eq b1 b2 -> pi_braid b1 = pi_braid b2.\nProof.\n  intros.\n  induction H; try solve [crush].\n  - unfold pi_braid.\n  assert (forall l, transpose_braid (transpose_braid l i) i = \n    transpose_braid l i).\n  intros. unfold transpose_braid. \n  \n\n\nEnd braids.\n\n\n\n\n\n\n\n\n\n\n\n}\n", "meta": {"author": "ivankrut856", "repo": "Coq", "sha": "5f864f06db7bfc3c17a9566f79d15c9a8626b8b4", "save_path": "github-repos/coq/ivankrut856-Coq", "path": "github-repos/coq/ivankrut856-Coq/Coq-5f864f06db7bfc3c17a9566f79d15c9a8626b8b4/theories/main_rep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744717487329, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.6566543922789181}}
{"text": "Require Import   Algebra.SetoidCat Algebra.Monoid Algebra.NearSemiRing.\n\nRequire Import RelationClasses Relation_Definitions Morphisms SetoidClass.\n\nSection Instances.\n  Context\n    {A AS}\n    (nsr : @NearSemiRing A AS).\n  \n  Instance nearSemiRing_times_Monoid : @Monoid A AS.\n  Proof.\n    exists (one) (times).\n    apply times_left_unit.\n    apply times_right_unit.\n    apply times_associativity.\n  Defined.\nEnd Instances.\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/NearSemiRingTimes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6566223919213924}}
{"text": "(* Steve Awodey's book on category theory *)\n(******************************************************************************)\n(* Chapter 1.3: Categories                                                    *)\n(******************************************************************************)\n(* @suharahiromichi *)\n\n(*\n(1) ベースライン\nhttp://www.megacz.com/berkeley/coq-categories/\nこれをもとに改変。Instance ... Proper を使うようにした。\n *)\n\n(*\n(2) Proper関数の定義\nA Gentle Introduction to Type Classes and Relations in Coq\n*)\n\n(*\n(3) Setoid を使うようにし、Setsと(P,<=)のインスタンスをつくる。\nhttp://www.iij-ii.co.jp/lab/techdoc/category/category1.html\n *)\n\n(* \nできるだけ Generalizable を使う。\n *)\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nFrom mathcomp Require Import finset fintype.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import Morphisms.\nRequire Import Coq.Setoids.Setoid.\nRequire Import Notations.\n\n(*\nReserved Notation \"x ~> y\" (at level 51, left associativity).\n*)\nReserved Notation \"x \\\\o y\" (at level 51, left associativity).\nReserved Notation \"x === y\" (at level 71, left associativity).\n\nGeneralizable Variables a b c d e x.\nGeneralizable Variables Obj.\n\n(* Calss Setoid (carrier : Type) とするのは難しい。なぜ？ *)\nClass Setoid : Type :=\n  {\n    carrier : Type;\n    eqv : carrier -> carrier -> Prop;\n    eqv_equivalence : Equivalence eqv\n  }.\nCoercion carrier : Setoid >-> Sortclass.\nNotation \"x === y\" := (eqv x y).\n\nClass Category `(Hom : Obj -> Obj -> Setoid) : Type :=\n  {\n    hom := Hom where \"a ~> b\" := (hom a b);\n    obj := Obj;\n    id   : forall {a : Obj}, (a ~> a);\n    comp : forall {a b c : Obj},\n             (b ~> c) -> (a ~> b) -> (a ~> c)\n                                       where \"f \\\\o g\" := (comp f g);\n    comp_respects   : forall {a b c : Obj},\n                        Proper (eqv ==> eqv ==> eqv) (@comp a b c);\n    left_identity   : forall `{f : a ~> b}, id \\\\o f === f;\n    right_identity  : forall `{f : a ~> b}, f \\\\o id === f;\n    associativity   : forall `{f : c ~> d} `{g : b ~> c} `{h : a ~> b},\n                        f \\\\o g \\\\o h === f \\\\o (g \\\\o h)\n}.\nCoercion obj : Category >-> Sortclass.\n\nNotation \"a ~> b\"  := (hom a b).\nNotation \"f \\\\o g\" := (comp f g).\nNotation \"a ~~{ C }~~> b\" := (@hom _ _ C a b) (at level 100).\n\n(* eqv が、Reflexive と Symmetric と Transitive とを満たす。 *)\nInstance category_eqv_Equiv `(C : Category Obj) (a b : Obj) :\n  Equivalence (@eqv (a ~> b)).\nProof.\n  by apply eqv_equivalence.\nQed.\n\n(* comp は eqv について固有関数である。 *)\nInstance category_comp_Proper `(C : Category Obj) (a b c : Obj) :\n  Proper (@eqv (b ~> c) ==> @eqv (a ~> b) ==> @eqv (a ~> c)) comp.\nProof.\n  by apply comp_respects.\nQed.\n\n\n(* 可換性についての定理を証明する。 *)\nLemma juggle1 : forall `{C : Category}\n                       `(f : d ~> e) `(g : c ~> d) `(h : b ~> c) `(k : a ~> b),\n                  f \\\\o g \\\\o h \\\\o k === f \\\\o (g \\\\o h) \\\\o k.\nProof.\n  intros.\n  rewrite <- associativity.\n  reflexivity.\nDefined.\n\nLemma juggle2 : forall `{C : Category}\n                       `(f : d ~> e) `(g : c ~> d) `(h : b ~> c) `(k : a ~> b),\n                  f \\\\o (g \\\\o (h \\\\o k)) === f \\\\o (g \\\\o h) \\\\o k.\nProof.\n  intros.\n  do ! rewrite <- associativity.\n  reflexivity.\nDefined.\n\nLemma juggle3 : forall `{C : Category}\n                       `(f : d ~> e) `(g : c ~> d) `(h : b ~> c) `(k : a ~> b),\n                  f \\\\o g \\\\o (h \\\\o k) === f \\\\o (g \\\\o h) \\\\o k.\nProof.\n  intros.\n  do ! rewrite <- associativity.\n  reflexivity.\nDefined.\n\nReserved Notation \"x &&& y\" (at level 50, left associativity).\n\n(* 直積 *)\nClass Product `{C : Category Obj} (Prod : Obj -> Obj -> Obj) : Type :=\n  {\n    obj' := Obj;\n    proj1 : forall {a b : Obj}, (Prod a b) ~> a;\n    proj2 : forall {a b : Obj}, (Prod a b) ~> b;\n    \n    (* 仲介射 *)\n    mediating : forall {a b x : Obj},\n                  (x ~> a) -> (x ~> b) -> (x ~> (Prod a b))\n                                            where \"f &&& g\" := (mediating f g);\n    \n    med_commute1 : forall `(f : x ~> a) `(g : x ~> b),\n                     proj1 \\\\o (f &&& g) === f;\n    med_commute2 : forall `(f : x ~> a) `(g : x ~> b),\n                     proj2 \\\\o (f &&& g) === g;\n    med_unique : forall `(f : x ~> a) `(g : x ~> b) `(h : x ~> (Prod a b)),\n                   proj1 \\\\o h === f ->\n                   proj2 \\\\o h === g ->\n                   h === (f &&& g)\n  }.\nCoercion obj': Product >-> Sortclass.\nNotation \"x &&& y\" := (mediating x y).\n\nCheck @proj1 : ∀Obj Hom C Prod _ a b, Prod a b ~> a.\nCheck @proj2 : ∀Obj Hom C Prod _ a b, Prod a b ~> b.\n\nSet Printing All.\nGeneralizable Variables Prod.\nDefinition parallel `{C : Category Obj} {Prod : Obj -> Obj -> Obj} {CP : Product Prod}\n           `(f : a ~> b) `(g : c ~> d) : (Prod a c) ~> (Prod b d) :=\n  let p1 := @proj1 Obj Hom C Prod CP a c in\n  let p2 := @proj2 Obj Hom C Prod CP a c in\n  (f \\\\o p1) &&& (g \\\\o p2).\nNotation \"f *** g\" := (parallel f g).      (* <f,g> *)\n\n(* **** *)\n(* Sets *)\n(* **** *)\nInstance EquivExt : forall (A B : Set), Equivalence (@eqfun A B) := (* notu *)\n  {\n    Equivalence_Reflexive := @frefl A B;\n    Equivalence_Symmetric := @fsym A B;\n    Equivalence_Transitive := @ftrans A B\n  }.\n\nInstance EqMor : forall (A B : Set), Setoid :=\n  {\n    carrier := A -> B;\n    eqv := @eqfun B A\n  }.\n  \nCheck @Category Set : (Set → Set → Setoid) → Type.\nCheck @Category Set EqMor : Type.\nCheck EqMor : Set -> Set -> Setoid.\n\nProgram Instance Sets : @Category Set EqMor.\nObligation 3.\nProof.\n  rewrite /Sets_obligation_2.\n  move=> homab homab' Hhomab hombc hombc' Hhombc.\n  move=> x //=.\n  rewrite Hhomab.\n  rewrite Hhombc.\n    by [].\nQed.\n\nCheck prod : (Type → Type → Type).\nCheck @Product Sets EqMor Sets prod.\nCheck Product prod : Type.\n\nProgram Instance SetsProd : @Product Sets EqMor Sets prod :=\n  {\n    proj1 A B := @fst A B;\n    proj2 A B := @snd A B;\n    mediating A B X := fun f g x => (f x, g x)\n  }.\nObligation 3.\nProof.\n  move: H H0.\n  rewrite /Sets_obligation_2 => H1 H2 x'.\n  rewrite -(H1 x').\n  rewrite -(H2 x').\n  by apply surjective_pairing.\nQed.\n\n(* **** *)\n(* P,<= *)\n(* **** *)\nOpen Scope coq_nat_scope.\nSearch \"_ <= _\".\nCheck 0 <= 0 : Prop.\n\nDefinition eq_le m n (p q : m <= n) := True.\n  \nInstance EquivGeq : forall (m n : nat), Equivalence (@eq_le m n). (* notu *)\nProof.\n    by [].\nQed. \n  \nInstance EqLe : forall (m n : nat), Setoid :=\n  {\n    carrier := m <= n;\n    eqv := @eq_le m n\n  }.\n\nCheck @Category nat : (nat → nat → Setoid) → Type.\nCheck EqLe : nat → nat → Setoid.\nCheck @Category nat EqLe.\n\nProgram Instance P_LE : @Category nat EqLe.\nObligation 2.\nProof.\n    by apply (@Le.le_trans a b c).\nDefined.\nObligation 3.\nProof.\n  rewrite /P_LE_obligation_1.\n  rewrite /P_LE_obligation_2.\n  move=> homab homab' Hhomab hombc hombc' Hhombc.\n  by rewrite /eq_le.\nDefined.\nObligation 4.\nProof.\n  rewrite /P_LE_obligation_1.\n  rewrite /P_LE_obligation_2.\n  by rewrite /eq_le.\nDefined.\nObligation 5.\nProof.\n  rewrite /P_LE_obligation_1.\n  rewrite /P_LE_obligation_2.\n  by rewrite /eq_le.\nDefined.\nObligation 6.\nProof.\n  rewrite /P_LE_obligation_2.\n  by rewrite /eq_le.\nDefined.\n\nCheck P_LE.\n\nCheck min : nat -> nat -> nat.\nCheck @Product P_LE EqLe P_LE min.\n\nProgram Instance P_LE_Prod : @Product P_LE EqLe P_LE min.\nObligation 1.\nProof.\n  Search (min _ _ <= _).\n  by apply PeanoNat.Nat.le_min_l.\nDefined.\nObligation 2.\n  by apply PeanoNat.Nat.le_min_r.\nDefined.\nObligation 3.\nProof.\n  Search (_ <= min _ _).\n  by apply PeanoNat.Nat.min_glb.\nDefined.\nObligation 4.\n  rewrite /P_LE_obligation_1.\n  rewrite /P_LE_obligation_2.\n  rewrite /P_LE_obligation_3.\n  by rewrite /eq_le.\nDefined.\nObligation 5.\n  rewrite /P_LE_obligation_1.\n  rewrite /P_LE_obligation_2.\n  rewrite /P_LE_obligation_3.\n  by rewrite /eq_le.\nDefined.\n\nCheck P_LE_Prod.\n\n(* an application of parallel (***) *)\nCheck @parallel.\nLemma parallel_min : forall (m n p q : nat),\n      m <= n -> p <= q -> min m p <= min n q.\nProof.\n  move=> m n p q Hmn Hpq.\n  Check @parallel nat EqLe P_LE min P_LE_Prod m n Hmn p q Hpq.\n    by apply: (@parallel nat EqLe P_LE min P_LE_Prod m n Hmn p q Hpq).\n    Undo 1.\n  Check Hmn *** Hpq.\n    by apply: (Hmn *** Hpq).\nQed.\nPrint parallel_min.\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/monad/Categories.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.656618042909112}}
{"text": "Require Import Basics.\nRequire Import Spaces.Pos.\nRequire Import Spaces.Int.Core.\nRequire Import Spaces.Int.Spec.\n\n(** ** Iteration of equivalences *)\n\n(** *** Iteration by arbitrary integers *)\n\nDefinition int_iter {A} (f : A -> A) `{!IsEquiv f} (n : Int) : A -> A\n  := match n with\n      | neg n => fun x => pos_iter f^-1 n x\n      | zero => idmap\n      | pos n => fun x => pos_iter f n x\n     end.\n\n(** Iteration by arbitrary integers requires the endofunction to be an equivalence, so that we can define a negative iteration by using its inverse. *)\n\n\nDefinition int_iter_succ_l {A} (f : A -> A) `{IsEquiv _ _ f}\n  (n : Int) (a : A)\n  : int_iter f (int_succ n) a = f (int_iter f n a).\nProof.\n  destruct n as [n| |n]; trivial.\n  + revert n f H a.\n    serapply pos_peano_ind.\n    { intros f H a.\n      symmetry.\n      apply eisretr. }\n    hnf; intros n p f H a.\n    refine (ap (fun x => _ x _) _ @ _).\n    1: rewrite int_neg_pos_succ.\n    1: exact (eisretr int_succ (neg n)).\n    apply moveL_equiv_M.\n    cbn; symmetry.\n    serapply pos_iter_succ_l.\n  + cbn.\n    rewrite pos_add_1_r.\n    serapply pos_iter_succ_l.\nQed.\n\nDefinition int_iter_succ_r {A} (f : A -> A) `{IsEquiv _ _ f}\n  (n : Int) (a : A) : int_iter f (int_succ n) a = int_iter f n (f a).\nProof.\n   destruct n as [n| |n]; trivial.\n+ revert n f H a.\n  serapply pos_peano_ind.\n  { intros f H a.\n    symmetry.\n    apply eissect. }\n  hnf; intros n p f H a.\n  rewrite int_neg_pos_succ.\n  refine (ap (fun x => _ x _) _ @ _).\n  1: exact (eisretr int_succ (neg n)).\n  cbn; rewrite pos_add_1_r.\n  rewrite pos_iter_succ_r.\n  rewrite eissect.\n  reflexivity.\n+ cbn.\n  rewrite pos_add_1_r.\n  serapply pos_iter_succ_r.\nQed.\n\nDefinition iter_int_pred_l {A} (f : A -> A) `{IsEquiv _ _ f}\n  (n : Int) (a : A)\n: int_iter f (int_pred n) a = f^-1 (int_iter f n a).\nProof.\n  destruct n as [n| |n]; trivial.\n  + cbn; rewrite pos_add_1_r.\n    by rewrite pos_iter_succ_l.\n  + revert n.\n    serapply pos_peano_ind.\n    - cbn; symmetry; apply eissect.\n    - hnf; intros p q.\n      rewrite <- pos_add_1_r.\n      change (int_pred (pos (p + 1)%pos))\n        with (int_pred (int_succ (pos p))).\n      rewrite int_pred_succ.\n      change (pos (p + 1)%pos)\n        with (int_succ (pos p)).\n      rewrite int_iter_succ_l.\n      symmetry.\n      apply eissect.\nQed.\n\nDefinition iter_int_pred_r {A} (f : A -> A) `{IsEquiv _ _ f}\n  (n : Int) (a : A)\n: int_iter f (int_pred n) a = int_iter f n (f^-1 a).\nProof.\n  revert f H n a.\n  destruct n as [n| |n]; trivial;\n  induction n as [|n nH] using pos_peano_ind; trivial.\n  2: hnf; intros; apply symmetry, eisretr.\n  all: rewrite <- pos_add_1_r.\n  all: intro a.\n  1: change (neg (n + 1)%pos) with (int_pred (neg n)).\n  2: change (pos (n + 1)%pos) with (int_succ (pos n)).\n  1: rewrite <- 2 int_neg_pos_succ.\n  1: cbn; apply pos_iter_succ_r.\n  rewrite int_pred_succ.\n  rewrite int_iter_succ_r.\n  rewrite eisretr.\n  reflexivity.\nQed.\n\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/theories/Spaces/Int/Equiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6566180312033145}}
{"text": "From Coq Require Import Arith Psatz Bool String List Program.Equality Logic.Eqdep_dec Nat.\n\nLocal Open Scope string_scope.\nLocal Open Scope nat_scope.\nLocal Open Scope list_scope.\n\nDefinition ident := string.\n\nDefinition store (T: Type): Type := ident -> T.\n\n\nDefinition update {T: Type} (x: ident) (v: T) (s: store T): store T :=\n  fun y => if string_dec x y then v else s y.\n\nLemma update_same:\n  forall (T: Type) (x: ident) (v: T) (s: store T), (update x v s) x = v.\nProof.\n  unfold update; intros. destruct (string_dec x x); congruence.\nQed.\n\nLemma update_other:\n  forall (T: Type) (x: ident) (v: T) (s: store T) (y: ident), x <> y -> (update x v s) y = s y.\nProof.\n  unfold update; intros. destruct (string_dec x y); congruence.\nQed.\n\nSection SEQUENCES.\n\nVariable A: Type.                 (**r the type of states *)\nVariable R: A -> A -> Prop.       (**r the transition relation between states *)\n\n(** ** Finite sequences of transitions *)\n\n(** Zero, one or several transitions: reflexive transitive closure of [R]. *)\n\nInductive star: A -> A -> Prop :=\n  | star_refl: forall a,\n      star a a\n  | star_step: forall a b c,\n      R a b -> star b c -> star a c.\n\nLemma star_one:\n  forall (a b: A), R a b -> star a b.\nProof.\n  eauto using star.\nQed.\n\nLemma star_trans:\n  forall (a b: A), star a b -> forall c, star b c -> star a c.\nProof.\n  induction 1; eauto using star. \nQed.\n\nEnd SEQUENCES.\n\n(*default function if not defined is the identity function. *)\n\n\n\nDefinition nat_env := store nat. \n\nDefinition init_nenv: nat_env := fun _ => 0.\n\nDefinition debruijn_env: Type := list nat.\n\nDefinition init_debruijn_env: debruijn_env := nil.\n\n\nInductive aexp_Dan :=\n| CONST_Dan (n: nat)\n| VAR_Dan (x: ident)\n| PARAM_Dan (n: nat)\n| PLUS_Dan (a1 a2: aexp_Dan)\n| MINUS_Dan (a1 a2: aexp_Dan)\n| APP_Dan (f: ident) (aexps : list aexp_Dan).\n\n(*\n * Custom induction principle with stronger handling of containers,\n * based on this trick: https://pastebin.com/BAvg3Jdh\n *)\nSection aexp_Dan_ind2.\n  Variable P: aexp_Dan -> Prop. (* this is the property we want to prove *)\n \n  (* For each constructor, we add a Variable *)\n  Variable fconst : forall n : nat, P (CONST_Dan n).\n  Variable fvar : forall x : ident, P (VAR_Dan x).\n  Variable fparam : forall n : nat, P (PARAM_Dan n).\n  Variable fplus :\n    forall a1 : aexp_Dan, P a1 -> forall a2 : aexp_Dan, P a2 -> P (PLUS_Dan a1 a2).\n  Variable fminus :\n    forall a1 : aexp_Dan, P a1 -> forall a2 : aexp_Dan, P a2 -> P (MINUS_Dan a1 a2).\n  Variable fapp :\n    forall f (aexps : list aexp_Dan), List.Forall P aexps -> P (APP_Dan f aexps).\n\n  Fixpoint aexp_Dan_ind2 (a : aexp_Dan) : P a :=\n    match a as a0 return (P a0) with\n    | CONST_Dan n => fconst n\n    | VAR_Dan x => fvar x\n    | PARAM_Dan n => fparam n\n    | PLUS_Dan a1 a2 => fplus a1 (aexp_Dan_ind2 a1) a2 (aexp_Dan_ind2 a2)\n    | MINUS_Dan a1 a2 => fminus a1 (aexp_Dan_ind2 a1) a2 (aexp_Dan_ind2 a2)\n    | APP_Dan f aexps =>\n        fapp f aexps\n          ((fix L aexps := \n             match aexps return (Forall P aexps) with\n             | nil => Forall_nil _\n             | cons a aexps_tl => Forall_cons a (aexp_Dan_ind2 a) (L aexps_tl) end) aexps)\n    end.\nEnd aexp_Dan_ind2.\n\n(* set version *)\nSection aexp_Dan_rec2.\n  Variable P: aexp_Dan -> Set. (* this is the property we want to prove *)\n \n  (* For each constructor, we add a Variable *)\n  Variable fconst : forall n : nat, P (CONST_Dan n).\n  Variable fvar : forall x : ident, P (VAR_Dan x).\n  Variable fparam : forall n : nat, P (PARAM_Dan n).\n  Variable fplus :\n    forall a1 : aexp_Dan, P a1 -> forall a2 : aexp_Dan, P a2 -> P (PLUS_Dan a1 a2).\n  Variable fminus :\n    forall a1 : aexp_Dan, P a1 -> forall a2 : aexp_Dan, P a2 -> P (MINUS_Dan a1 a2).\n\n   Inductive SForall : list aexp_Dan -> Set :=\n   | SForall_nil : SForall nil\n   | SForall_cons : forall x l, P x -> SForall l -> SForall (x::l).\n\n  Variable fapp :\n    forall f (aexps : list aexp_Dan), SForall aexps -> P (APP_Dan f aexps).\n\n  Fixpoint aexp_Dan_rec2 (a : aexp_Dan) : P a :=\n    match a as a0 return (P a0) with\n    | CONST_Dan n => fconst n\n    | VAR_Dan x => fvar x\n    | PARAM_Dan n => fparam n\n    | PLUS_Dan a1 a2 => fplus a1 (aexp_Dan_rec2 a1) a2 (aexp_Dan_rec2 a2)\n    | MINUS_Dan a1 a2 => fminus a1 (aexp_Dan_rec2 a1) a2 (aexp_Dan_rec2 a2)\n    | APP_Dan f aexps =>\n        fapp f aexps\n          ((fix L aexps := \n             match aexps return (SForall aexps) with\n             | nil => SForall_nil\n             | cons a aexps_tl => SForall_cons a _ (aexp_Dan_rec2 a) (L aexps_tl) end) aexps)\n    end.\nEnd aexp_Dan_rec2.\n\n(* Definition aexp_vector (n: nat): Type := VectorDef.t aexp_Dan n. *)\n\n(* Definition nil_aexp_vector: aexp_vector 0 := nil aexp_Dan. *)\n\nDeclare Scope dantrick_scope.\n\nInfix \"+d\" := PLUS_Dan (at level 76) : dantrick_scope.\nInfix \"-d\" := MINUS_Dan (at level 76) : dantrick_scope.\nInfix \"@d\" := APP_Dan (at level 76) : dantrick_scope.\n\nInductive bexp_Dan := \n| TRUE_Dan\n| FALSE_Dan\n| NEG_Dan (b: bexp_Dan)\n| AND_Dan (b1 b2: bexp_Dan)\n| OR_Dan  (b1 b2: bexp_Dan)\n| LEQ_Dan (a1 a2: aexp_Dan).\n\nDefinition eq_Dan (a b : aexp_Dan) : bexp_Dan :=\n  AND_Dan (LEQ_Dan a b) (LEQ_Dan b a).\nDefinition geq_Dan (a b : aexp_Dan) : bexp_Dan :=\n  LEQ_Dan b a.\nDefinition neq_Dan (a b : aexp_Dan) : bexp_Dan :=\n  NEG_Dan (eq_Dan a b).\nDefinition lt_Dan (a b : aexp_Dan) : bexp_Dan :=\n  AND_Dan (LEQ_Dan a b) (neq_Dan a b).\nDefinition gt_Dan (a b : aexp_Dan) : bexp_Dan :=\n  lt_Dan b a.\n\nNotation \"a '=d' b\" := (eq_Dan a b) (at level 50) : dantrick_scope.\nInfix \"&d\" := AND_Dan (at level 50) : dantrick_scope.\nInfix \"|d\" := OR_Dan (at level 50) : dantrick_scope.\nNotation \"'!d' a\" := (NEG_Dan a) (at level 80) : dantrick_scope.\nInfix \"<=d\" := LEQ_Dan (at level 90) : dantrick_scope.\nNotation \"a '>=d' b\" := (geq_Dan a b) (at level 90) : dantrick_scope.\nNotation \"a '!=d' b\" := (neq_Dan a b) (at level 90) : dantrick_scope.\nNotation \"a '<d' b\" := (lt_Dan a b) (at level 90) : dantrick_scope.\nNotation \"a '>d' b\" := (gt_Dan a b) (at level 90) : dantrick_scope.\n\nInductive imp_Dan :=\n  |IF_Dan (b: bexp_Dan) (i1 i2: imp_Dan)\n  |SKIP_Dan\n  |WHILE_Dan (b: bexp_Dan) (i: imp_Dan)\n  |ASSIGN_Dan (x: ident) (a: aexp_Dan)\n|SEQ_Dan (i1 i2: imp_Dan).\n\nSection imp_Dan_ind2.\n  Variable P: aexp_Dan -> Prop. (* this is the property we want to prove *)\n  Variable P0: bexp_Dan -> Prop.\n  Variable P1: imp_Dan -> Prop.\n \n  (* For each constructor, we add a Variable *)\n  Variable fconst : forall n : nat, P (CONST_Dan n).\n  Variable fvar : forall x : ident, P (VAR_Dan x).\n  Variable fparam : forall n : nat, P (PARAM_Dan n).\n  Variable fplus :\n    forall a1 : aexp_Dan, P a1 -> forall a2 : aexp_Dan, P a2 -> P (PLUS_Dan a1 a2).\n  Variable fminus :\n    forall a1 : aexp_Dan, P a1 -> forall a2 : aexp_Dan, P a2 -> P (MINUS_Dan a1 a2).\n  Variable fapp :\n    forall f (aexps : list aexp_Dan), List.Forall P aexps -> P (APP_Dan f aexps).\n  Variable ftrue : P0 (TRUE_Dan).\n  Variable ffalse : P0 (FALSE_Dan).\n  Variable fneg : forall b: bexp_Dan, P0 b -> P0 (NEG_Dan b).\n  Variable fand : forall b1: bexp_Dan, P0 b1 -> forall b2: bexp_Dan, P0 b2 -> P0 (AND_Dan b1 b2).\n  Variable f_or : forall b1: bexp_Dan, P0 b1 -> forall b2: bexp_Dan, P0 b2 -> P0 (OR_Dan b1 b2).\n  Variable fleq :\n    forall a1 : aexp_Dan, P a1 -> forall a2 : aexp_Dan, P a2 -> P0 (LEQ_Dan a1 a2).\n  Variable fskip : P1 SKIP_Dan.\n  Variable fassign : forall x: ident, forall a: aexp_Dan, P a -> P1 (ASSIGN_Dan x a).\n  Variable fseq : forall i1: imp_Dan, P1 i1 -> forall i2: imp_Dan, P1 i2 -> P1 (SEQ_Dan i1 i2).\n  Variable fif : forall b: bexp_Dan, P0 b -> forall i1: imp_Dan, P1 i1 -> forall i2: imp_Dan, P1 i2 -> P1 (IF_Dan b i1 i2).\n  Variable fwhile : forall b: bexp_Dan, P0 b -> forall i: imp_Dan, P1 i -> P1 (WHILE_Dan b i).\n\n  Fixpoint imp_aexp_Dan_ind2 (a : aexp_Dan) : P a :=\n    match a as a0 return (P a0) with\n    | CONST_Dan n => fconst n\n    | VAR_Dan x => fvar x\n    | PARAM_Dan n => fparam n\n    | PLUS_Dan a1 a2 => fplus a1 (imp_aexp_Dan_ind2 a1) a2 (imp_aexp_Dan_ind2 a2)\n    | MINUS_Dan a1 a2 => fminus a1 (imp_aexp_Dan_ind2 a1) a2 (imp_aexp_Dan_ind2 a2)\n    | APP_Dan f aexps =>\n        fapp f aexps\n          ((fix L aexps := \n             match aexps return (Forall P aexps) with\n             | nil => Forall_nil _\n             | cons a aexps_tl => Forall_cons a (imp_aexp_Dan_ind2 a) (L aexps_tl) end) aexps)\n    end.\n  Fixpoint imp_Dan_ind2 (i: imp_Dan): P1 i :=\n           match i as i0 return (P1 i0) with\n           | SKIP_Dan => fskip\n           | ASSIGN_Dan x a => fassign x a (imp_aexp_Dan_ind2 a)\n           | SEQ_Dan i1 i2 => fseq i1 (imp_Dan_ind2 i1) i2 (imp_Dan_ind2 i2)\n           | IF_Dan b i1 i2 =>\n               fif b ((fix imp_bexp_Dan_ind2 (b: bexp_Dan) : P0 b :=\n                         match b as b0 return (P0 b0) with\n                         | TRUE_Dan => ftrue\n                         | FALSE_Dan => ffalse\n                         | NEG_Dan b => fneg b (imp_bexp_Dan_ind2 b)\n                         | AND_Dan b1 b2 => fand b1 (imp_bexp_Dan_ind2 b1) b2 (imp_bexp_Dan_ind2 b2)\n                         | OR_Dan b1 b2 => f_or b1 (imp_bexp_Dan_ind2 b1) b2 (imp_bexp_Dan_ind2 b2)\n                         | LEQ_Dan a1 a2 => fleq a1 (imp_aexp_Dan_ind2 a1) a2 (imp_aexp_Dan_ind2 a2)\n                         end) b)\n                   i1 (imp_Dan_ind2 i1) i2 (imp_Dan_ind2 i2)\n           | WHILE_Dan b i =>\n               fwhile b ((fix imp_bexp_Dan_ind2 (b: bexp_Dan) : P0 b :=\n                            match b as b0 return (P0 b0) with\n                            | TRUE_Dan => ftrue\n                            | FALSE_Dan => ffalse\n                            | NEG_Dan b => fneg b (imp_bexp_Dan_ind2 b)\n                            | AND_Dan b1 b2 => fand b1 (imp_bexp_Dan_ind2 b1) b2 (imp_bexp_Dan_ind2 b2)\n                            | OR_Dan b1 b2 => f_or b1 (imp_bexp_Dan_ind2 b1) b2 (imp_bexp_Dan_ind2 b2)\n                            | LEQ_Dan a1 a2 => fleq a1 (imp_aexp_Dan_ind2 a1) a2 (imp_aexp_Dan_ind2 a2)\n                            end) b)\n                      i (imp_Dan_ind2 i)\n           end.\nEnd imp_Dan_ind2.\n\nNotation \"x <- e\" := (ASSIGN_Dan x e) (at level 75) : dantrick_scope.\nInfix \";;\" := SEQ_Dan (at level 76) : dantrick_scope.\nNotation \"'when' b 'then' t 'else' e 'done'\" :=\n  (IF_Dan b t e) (at level 75, b at level 0) : dantrick_scope.\nNotation \"'while' b 'loop' body 'done'\" :=\n  (WHILE_Dan b body) (at level 75) : dantrick_scope.\n\nLocal Open Scope dantrick_scope.\n\nRecord fun_Dan :=\n  { Name: ident\n  ; Args : nat\n  ; Ret: ident\n  ; Body: imp_Dan }.\n\nDefinition fun_env := store fun_Dan. \n\nDefinition init_fenv: fun_env := fun _ => {| Name := \"id\"\n                                          ; Args := 1\n                                          ; Ret := \"x\"\n                                          ; Body := \"x\" <- (PARAM_Dan 0) |}.\n\nInductive prog_Dan :=\n| PROF_Dan (l: list fun_Dan) (i: imp_Dan).\n\n\nLocal Open Scope vector_scope.\n\nInductive a_Dan : aexp_Dan -> list nat -> fun_env -> nat_env -> nat -> Prop :=\n| Dan_const : \n  forall dbenv fenv nenv n,\n    a_Dan (CONST_Dan n) dbenv fenv nenv n\n| Dan_var :\n  forall dbenv fenv nenv x n,\n    (nenv x = n) ->\n    a_Dan (VAR_Dan x) dbenv fenv nenv n\n| Dan_param :\n  forall dbenv fenv nenv n m,\n    0 <= n < List.length dbenv ->\n    nth_error dbenv n = Some m ->\n    a_Dan (PARAM_Dan n) dbenv fenv nenv m\n| Dan_plus : \n  forall dbenv fenv nenv a1 a2 n1 n2, \n    a_Dan a1 dbenv fenv nenv n1 ->\n    a_Dan a2 dbenv fenv nenv n2 -> \n    a_Dan (PLUS_Dan a1 a2) dbenv fenv nenv (n1 + n2)\n| Dan_minus : \n  forall dbenv fenv nenv a1 a2 n1 n2, \n    a_Dan a1 dbenv fenv nenv n1 ->\n    a_Dan a2 dbenv fenv nenv n2 -> \n    a_Dan (MINUS_Dan a1 a2) dbenv fenv nenv (n1 - n2)\n| Dan_app : \n  forall dbenv fenv nenv nenv'' func aexps ns ret f, \n    (fenv f = func) ->\n    (Args func) = Datatypes.length aexps ->\n    args_Dan aexps dbenv fenv nenv ns ->\n    (i_Dan (func).(Body) ns fenv init_nenv nenv'') ->\n    (nenv'' ((func).(Ret)) = ret) ->\n    a_Dan (APP_Dan f aexps) dbenv fenv nenv ret\nwith args_Dan: list aexp_Dan -> list nat -> fun_env -> nat_env -> list nat -> Prop :=\n| args_nil :\n  forall dbenv fenv nenv,\n    args_Dan nil dbenv fenv nenv nil%list\n| args_cons :\n  forall aexp aexps dbenv fenv nenv v vals,\n    a_Dan aexp dbenv fenv nenv v -> \n    args_Dan aexps dbenv fenv nenv vals ->\n    args_Dan (aexp :: aexps) dbenv fenv nenv (v :: vals)\nwith b_Dan: bexp_Dan -> list nat -> fun_env -> nat_env -> bool -> Prop :=\n|Dan_true : \n  forall dbenv fenv nenv,\n    b_Dan TRUE_Dan dbenv fenv nenv true\n|Dan_false : \n  forall dbenv fenv nenv,\n    b_Dan FALSE_Dan dbenv fenv nenv false\n|Dan_neg : \n  forall dbenv fenv nenv bexp b,\n    b_Dan bexp dbenv fenv nenv b ->\n    b_Dan (NEG_Dan bexp) dbenv fenv nenv (negb b)\n|Dan_and : \n  forall dbenv fenv nenv bexp1 bexp2 b1 b2, \n    b_Dan bexp1 dbenv fenv nenv b1 ->\n    b_Dan bexp2 dbenv fenv nenv b2 ->\n    b_Dan (AND_Dan bexp1 bexp2) dbenv fenv nenv (andb b1 b2)\n|Dan_or : \n  forall dbenv fenv nenv bexp1 bexp2 b1 b2, \n    b_Dan bexp1 dbenv fenv nenv b1 ->\n    b_Dan bexp2 dbenv fenv nenv b2 ->\n    b_Dan (OR_Dan bexp1 bexp2) dbenv fenv nenv (orb b1 b2)\n|Dan_leq : \n  forall dbenv fenv nenv a1 a2 n1 n2, \n      a_Dan a1 dbenv fenv nenv n1 ->\n      a_Dan a2 dbenv fenv nenv n2 -> \n      b_Dan (LEQ_Dan a1 a2) dbenv fenv nenv (Nat.leb n1 n2)\nwith i_Dan : imp_Dan -> list nat -> fun_env -> nat_env -> nat_env -> Prop := \n| Dan_skip : \n  forall dbenv fenv nenv,\n    i_Dan SKIP_Dan dbenv fenv nenv nenv\n| Dan_if_true :\n  forall dbenv fenv nenv nenv' bexp i1 i2, \n    b_Dan bexp dbenv fenv nenv true ->\n    i_Dan i1 dbenv fenv nenv nenv' ->\n    i_Dan (IF_Dan bexp i1 i2) dbenv fenv nenv nenv'\n| Dan_if_false :\n  forall dbenv fenv nenv nenv' bexp i1 i2, \n    b_Dan bexp dbenv fenv nenv false ->\n    i_Dan i2 dbenv fenv nenv nenv' ->\n    i_Dan (IF_Dan bexp i1 i2) dbenv fenv nenv nenv'\n| Dan_assign :\n  forall dbenv fenv nenv x a n, \n    a_Dan a dbenv fenv nenv n ->\n    i_Dan (ASSIGN_Dan x a) dbenv fenv nenv (update x n nenv)\n| Dan_while_done :\n  forall dbenv fenv nenv bexp i, \n    b_Dan bexp dbenv fenv nenv false ->\n    i_Dan (WHILE_Dan bexp i) dbenv fenv nenv nenv\n| Dan_while_step :\n  forall dbenv fenv nenv nenv' nenv'' bexp i, \n    b_Dan bexp dbenv fenv nenv true ->\n    i_Dan i dbenv fenv nenv nenv' ->\n    i_Dan (WHILE_Dan bexp i) dbenv fenv nenv' nenv'' ->\n    i_Dan (WHILE_Dan bexp i) dbenv fenv nenv nenv''\n| Dan_seq : forall dbenv fenv nenv nenv' nenv'' i1 i2,\n    i_Dan i1 dbenv fenv nenv nenv' ->\n    i_Dan i2 dbenv fenv nenv' nenv'' -> \n    i_Dan (SEQ_Dan i1 i2) dbenv fenv nenv nenv''\n.\n\n\nScheme i_Dan_mut := Induction for i_Dan Sort Prop\n    with a_Dan_mut := Induction for a_Dan Sort Prop\n                      with b_Dan_mut := Induction for b_Dan Sort Prop\n                      with args_Dan_mut := Induction for args_Dan Sort Prop.\n\n\nCombined Scheme i_Dan_mutind from i_Dan_mut,a_Dan_mut,b_Dan_mut,args_Dan_mut.\n\n\nLtac inv H :=\n  inversion H; subst; try (reflexivity || assumption).\n\nLtac smart_inversion_helper :=\n  multimatch goal with\n  | [ IH : (forall x, ?dan ?dan_syntax _ _ ?nenv x -> _ = x),\n        H: ?dan ?dan_syntax _ _ ?nenv _ |- _ ] => apply IH in H; try (assumption || reflexivity)\n  | [ IH: forall n1, ?blah_Dan ?dan_syntax ?dbenv ?fenv ?nenv n1 -> ?nenv'' = n1, Heq: ?nenv = ?nenv''', Hblah_Dan: ?blah_Dan ?dan_syntax ?dbenv ?fenv ?nenv''' ?nenv' |- ?nenv'' = ?nenv' ] =>\n      rewrite <- Heq in Hblah_Dan; apply IH in Hblah_Dan; assumption\n  end.\n\nLtac smart_rewriter :=\n  match goal with\n  | [ a : ?T, b : ?T |- _ ] =>\n      match goal with\n      | [ H: a = b |- _ ] => rewrite H; try reflexivity\n      end\n  end.\n\n\n                      \nLtac det_smart_inversion :=\n  match goal with\n  | [ H': ?dan _ _ _ _ ?res' |- ?res = ?res' ] => inv H'; repeat smart_inversion_helper; repeat smart_rewriter\n  end.\n\nTactic Notation \"substs\" :=\n  repeat (match goal with H: ?x = ?y |- _ =>\n            first [ subst x | subst y ] end).\n\n\nTheorem big_step_deterministic :\n    (forall i dbenv fenv nenv nenv',\n        i_Dan i dbenv fenv nenv nenv' ->\n        forall nenv'',\n        i_Dan i dbenv fenv nenv nenv'' ->\n        nenv' = nenv'') /\\\n      (forall a dbenv fenv nenv n,\n          a_Dan a dbenv fenv nenv n ->\n          forall n',\n          a_Dan a dbenv fenv nenv n' ->\n          n = n')\n    /\\\n      (forall b dbenv fenv nenv v,\n          b_Dan b dbenv fenv nenv v ->\n          forall v',\n          b_Dan b dbenv fenv nenv v' ->\n          v = v')\n    /\\\n      (forall args dbenv fenv nenv vals,\n          args_Dan args dbenv fenv nenv vals ->\n          forall vals',\n          args_Dan args dbenv fenv nenv vals' ->\n          vals = vals').\nProof.\n  pose (fun i db f n n0 => fun H: i_Dan i db f n n0 => forall n1, i_Dan i db f n n1 -> n0 = n1) as P.\n  pose (fun a db f n n0 => fun Ha: a_Dan a db f n n0 => forall n1, a_Dan a db f n n1 -> n0 = n1) as P0.\n  pose (fun b db f n n0 => fun Hb: b_Dan b db f n n0 => forall n1, b_Dan b db f n n1 -> n0 = n1) as P1.\n  pose (fun args db f n n0 => fun Hargs: args_Dan args db f n n0 => forall n1, args_Dan args db f n n1 -> n0 = n1) as P2.\n  apply (i_Dan_mutind P P0 P1 P2); unfold P, P0, P1, P2 in *; intros; try det_smart_inversion; try discriminate; try (substs; reflexivity).\n  - (* The function application case is the one case I couldn't get the automation to work on lol *)\n    rewrite H2 in e.\n    inversion e.\n    reflexivity.\n  - rewrite <- H6 in H7.\n    apply H0 in H7.\n    smart_rewriter.\nQed.\n\nLtac destruct_dan H :=\n  destruct H as [Hi_Dan [Ha_Dan [Hb_Dan Hargs_Dan]]].\n\nTheorem big_step_deterministic_human_version :\n  forall dbenv fenv nenv,\n    (forall i nenv' nenv'',\n        i_Dan i dbenv fenv nenv nenv' ->\n        i_Dan i dbenv fenv nenv nenv'' ->\n        nenv' = nenv'')\n    /\\\n      (forall a n n',\n          a_Dan a dbenv fenv nenv n ->\n          a_Dan a dbenv fenv nenv n' ->\n          n = n')\n    /\\\n      (forall b v v',\n          b_Dan b dbenv fenv nenv v ->\n          b_Dan b dbenv fenv nenv v' ->\n          v = v')\n    /\\\n      (forall args vals vals',\n          args_Dan args dbenv fenv nenv vals ->\n          args_Dan args dbenv fenv nenv vals' ->\n          vals = vals').\nProof.\n  intros dbenv fenv nenv.\n  split; [ | split; [ | split ]]; intros; pose proof big_step_deterministic; destruct_dan H1.\n  - eapply Hi_Dan; eassumption.\n  - eapply Ha_Dan; eassumption.\n  - eapply Hb_Dan; eassumption.\n  - eapply Hargs_Dan; eassumption.\nQed.\n\n\n(* Helper theorems that just show that each relation is deterministic without\n * having to do all the splitting nonsense. *)\n\nTheorem i_Dan_deterministic :\n  forall dbenv fenv nenv i nenv' nenv'',\n    i_Dan i dbenv fenv nenv nenv' ->\n    i_Dan i dbenv fenv nenv nenv'' ->\n    nenv' = nenv''.\nProof.\n  intros. pose proof (big_step_deterministic_human_version dbenv fenv nenv) as DET.\n  destruct_dan DET. eapply Hi_Dan; eassumption.\nQed.\n\nTheorem a_Dan_deterministic :\n  forall dbenv fenv nenv a n n',\n    a_Dan a dbenv fenv nenv n ->\n    a_Dan a dbenv fenv nenv n' ->\n    n = n'.\nProof.\n  intros. pose proof (big_step_deterministic_human_version dbenv fenv nenv) as Hdet.\n  destruct_dan Hdet. eapply Ha_Dan; eassumption.\nQed.\n\nTheorem b_Dan_deterministic :\n  forall dbenv fenv nenv b v v',\n    b_Dan b dbenv fenv nenv v ->\n    b_Dan b dbenv fenv nenv v' ->\n    v = v'.\nProof.\n  intros. pose proof (big_step_deterministic_human_version dbenv fenv nenv) as Hdet.\n  destruct_dan Hdet. eapply Hb_Dan; eassumption.\nQed.\n\nTheorem args_Dan_deterministic :\n  forall dbenv fenv nenv args vals vals',\n    args_Dan args dbenv fenv nenv vals ->\n    args_Dan args dbenv fenv nenv vals' ->\n    vals = vals'.\nProof.\n  intros. pose proof (big_step_deterministic_human_version dbenv fenv nenv) as DET.\n  destruct_dan DET. eapply Hargs_Dan; eassumption.\nQed.\n\n\n\n\n \n\nDefinition options_to_prod_option {A B: Type} (a: option A) (b: option B) : option (A * B) :=\n  match (a, b) with\n  | (Some a', Some b') => Some (a', b')\n  | _ => None\n  end.\n\nDefinition prod_add (n: nat * nat): nat :=\n  match n with\n  | (n', n'') => n' + n''\n  end.\n\nDefinition prod_minus (n: nat * nat) : nat :=\n  match n with\n  | (n', n'') => n' - n''\n  end.\n               \nDefinition option_bind {A B: Type} (a: option A) (f: A -> option B): option B :=\n  match a with\n  | Some x => f x\n  | None => None\n  end.\n\nDefinition option_map_map {A B C: Type} (f: A -> B -> C) (a: option A) (b: option B): option C :=\n  match a with\n  | Some a' => option_map (f a') b\n  | _ => None\n  end.\n\nDefinition nat_option_map_2 (f: nat -> nat -> nat) (a b : option nat): option nat :=\n  option_map_map f a b.\n\nDefinition option_apply {A B : Type} (f: option (A -> B)) (a: A): option B :=\n  match f with\n  | Some f' => Some (f' a)\n  | _ => None\n  end.\n\n\n\nPrint option_map.\n\nPrint Nat.add.\nPrint Nat.sub.\nPrint Nat.leb.\n\nPrint Implicit option_map_map.\n\n\n(* Temporarily disable printing, without having to remove prints *)\nDefinition print {T: Type} (x: T) := x.\n\nDefinition print_id {T: Type}  (x: T) := x.\n\n\nFixpoint eval_aDan (a: aexp_Dan) (fuel: nat) (dbenv: list nat) (fenv: fun_env) (nenv: nat_env) : option nat :=\n  let blah := print \"[eval_aDan\" in\n  let blah2 := print a in\n  let blah3 := print nenv in\n  match (print_id fuel) with\n    | 0 =>\n        let big_res :=\n          (match a with\n           | CONST_Dan n => Some n\n           | VAR_Dan x => Some (nenv x)\n           | PARAM_Dan n => nth_error dbenv n                               \n           | _ => None\n           end) in\n        let blah4 := print \"eval_aDan]\" in\n        big_res\n    | S fuel' =>\n        let big_res :=\n          (\n            match a with\n            | CONST_Dan n => Some n\n            | VAR_Dan x => Some (nenv x)\n            | PARAM_Dan n => nth_error dbenv n\n            | PLUS_Dan a1 a2 =>\n                option_map_map\n                  Nat.add\n                  (eval_aDan a1 fuel' dbenv fenv nenv)\n                  (eval_aDan a2 fuel' dbenv fenv nenv)\n            | MINUS_Dan a1 a2 =>\n                option_map_map\n                  Nat.sub\n                  (eval_aDan a1 fuel' dbenv fenv nenv)\n                  (eval_aDan a2 fuel' dbenv fenv nenv)\n            | APP_Dan f a =>\n                let blah_app := print \"[app \" in\n                let eval_dbenv :=\n                  eval_args_Dan a\n                                fuel'\n                                dbenv\n                                fenv\n                                nenv in\n                let return_nenv :=\n                  (option_bind\n                     eval_dbenv\n                     (fun dbenv' =>\n                        eval_fuel_Dan ((fenv f).(Body)) fuel' dbenv' fenv init_nenv)) in\n                let res :=\n                  option_map\n                    (fun return_nenv => return_nenv ((fenv f).(Ret)))\n                    return_nenv in\n                let blah_app_1 := print \"app]\" in\n                res\n            end) in\n        let blah4' := print big_res in\n        let blah4 := print \"eval_aDan]\" in\n        big_res\n  end\nwith eval_args_Dan (arg_exprs: list aexp_Dan)  (fuel: nat) (dbenv: list nat) (fenv: fun_env) (nenv: nat_env) : option (list nat) :=\n       match fuel with\n       | 0 => None\n       | S fuel' =>\n           match arg_exprs with\n           | e :: exprs =>\n               let result_e := eval_aDan e fuel' dbenv fenv nenv in\n               match result_e with\n               | Some v =>\n                   match (eval_args_Dan exprs fuel' dbenv fenv nenv) with\n                   | None =>\n                       None\n                   | Some dbenv' =>\n                       Some (cons v dbenv')\n                       end\n               | None =>\n                   None\n               end\n           | nil =>\n               Some nil\n           end\n       end                                         \nwith eval_bDan (b: bexp_Dan) (fuel: nat) (dbenv: list nat) (fenv: fun_env) (nenv: nat_env) : option bool :=\n       let blah := print \"[eval_bDan\" in\n       let blah' := print b in\n       match fuel with\n       | 0 => let blah2 := print \"eval_bDan]\" in\n              None\n       | S fuel' =>\n           let big_res := (match b with\n           | TRUE_Dan => Some true\n           | FALSE_Dan => Some false\n           | NEG_Dan b' =>\n               option_map\n                 negb\n                 (eval_bDan b' fuel' dbenv fenv nenv)\n           | AND_Dan b1 b2 =>\n               option_map_map\n                 andb\n                 (eval_bDan b1 fuel' dbenv fenv nenv)\n                 (eval_bDan b2 fuel' dbenv fenv nenv)\n           | OR_Dan  b1 b2 =>\n               option_map_map\n                 orb\n                 (eval_bDan b1 fuel' dbenv fenv nenv)\n                 (eval_bDan b2 fuel' dbenv fenv nenv)\n           | LEQ_Dan a1 a2 =>\n               option_map_map\n                 Nat.leb\n                 (eval_aDan a1 fuel' dbenv fenv nenv)\n                 (eval_aDan a2 fuel' dbenv fenv nenv)\n                           end) in\n           let blah2' := print big_res in\n           let blah2 := print \"eval_bDan]\" in\n           big_res\n       end\nwith eval_fuel_Dan (i: imp_Dan) (fuel: nat) (dbenv: list nat) (fenv: fun_env) (nenv: nat_env) : option nat_env :=\n       let blah := print \"[eval_fuel_Dan\" in\n       let blah1 := print i in\n       let blah2 := print fuel in\n       let blah3 := print nenv in\n       match fuel with\n       | 0 => \n           match i with\n           | SKIP_Dan =>\n              Some nenv\n           | _ =>\n              let blah0 := print \"]\" in None\n           end\n       | S fuel' =>\n           match (print_id i) with\n           | SKIP_Dan =>\n               let blahskip1 := print \"]\" in\n               Some nenv\n           | ASSIGN_Dan x a =>\n               let res := eval_aDan a fuel' dbenv fenv nenv in\n               let res' := option_map (fun res => update (print_id x) (print_id res) nenv) res in\n               let blahassign1 := print \"]\" in\n               res'\n                 \n           | IF_Dan b i1 i2 =>\n               let bres := eval_bDan b fuel' dbenv fenv nenv in\n               let next_instruction := option_map (fun (bres': bool) => if bres' then i1 else i2) bres in\n               let res: option nat_env := option_bind next_instruction (fun (i: imp_Dan) => eval_fuel_Dan i fuel' dbenv fenv nenv) in\n               let blahif1 := print \"]\" in\n               res\n           | WHILE_Dan b i' =>\n               let bres := eval_bDan b fuel' dbenv fenv nenv in\n               option_bind bres (fun bres' =>\n                                   if bres' then\n                                     let new_nenv: option nat_env := eval_fuel_Dan i' fuel' dbenv fenv nenv in\n                                     let res: option nat_env := option_bind new_nenv (eval_fuel_Dan i fuel' dbenv fenv) in\n                                     let blahwhile1 := print \"]\" in\n                                     res\n                                   else\n                                     Some nenv)\n           | SEQ_Dan i1 i2 =>\n               let new_nenv: option nat_env := eval_fuel_Dan i1 fuel' dbenv fenv nenv in\n               let res: option nat_env := option_bind new_nenv (eval_fuel_Dan i2 fuel' dbenv fenv) in\n               let blahseq1 := print \"]\" in\n               res\n           end\n       end.\n\nDefinition default_fuel := 1000.\n\nLtac invc H :=\n  inversion H; subst; clear H.\n\nLtac duplicate_proof H H' :=\n  pose proof H as H'.\n\nTactic Notation \"dupe\" ident(H) \"as\" ident(H') := (duplicate_proof H H').\n\nFixpoint construct_fenv lst (f: fun_env) : fun_env :=\n  match lst with\n  | nil => f\n  | foo::foos => construct_fenv foos (update ((foo).(Name)) foo f)\n  end.\n\nDefinition eval_fuel_pDan (p: prog_Dan) (fuel: nat) (nenv: nat_env): option nat_env :=\n  match p with\n  | PROF_Dan lst imp =>\n      let new_fenv := construct_fenv lst init_fenv in\n      eval_fuel_Dan imp fuel nil new_fenv init_nenv\n  end.\n", "meta": {"author": "uwplse", "repo": "potpie", "sha": "d4814d315ff9d450a8d91ed77b22340b0ff35690", "save_path": "github-repos/coq/uwplse-potpie", "path": "github-repos/coq/uwplse-potpie/potpie-d4814d315ff9d450a8d91ed77b22340b0ff35690/DanTrickLanguage.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.6566180305280194}}
{"text": "Inductive day : Type :=\n| monday\n| tuesday\n| wednesday\n| thursday\n| friday\n| saturday\n| sunday.\n\nDefinition next_day (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\nend.\n\nCompute (next_day monday).\n\nCompute (next_day (next_day saturday)).\n\nExample test_next_day:\n  (next_day (next_day tuesday)) = thursday.\nProof. simpl. reflexivity. Qed.\n", "meta": {"author": "alexey-naydenov", "repo": "software-foundations", "sha": "f1a680ba831b872ad8ebe81c1349c08c6ee979d6", "save_path": "github-repos/coq/alexey-naydenov-software-foundations", "path": "github-repos/coq/alexey-naydenov-software-foundations/software-foundations-f1a680ba831b872ad8ebe81c1349c08c6ee979d6/src/playground.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6566180281080414}}
{"text": "Inductive seq (a : Set) :=\n  Nil  : seq a\n| Cons : a -> seq a -> seq a.\n\nNotation \"[]\" := (Nil _).\nNotation \"[ x | s ]\" := \n  (Cons _ x s) (x at level 0, s at level 200).\nNotation \"[ x ]\" := (Cons _ x (Nil _)) (x at level 0).\n\nPrint Grammar constr.\n\nFixpoint len (a : Set) (s : seq a) : nat :=\n  match s with\n         [] => 0\n  | [x | s] => 1 + len a s\n  end.\n\nFixpoint cat (a : Set) (s t : seq a) : seq a :=\n  match s with\n         [] => t               (* alpha *)\n  | [x | s] => [x | cat a s t] (* beta  *)\n  end.\n\n(* Page 13 *)\n\nTheorem cat_assoc : forall (a : Set) (s t u : seq a),\n  cat a s (cat a t u) = cat a (cat a s t) u.\n\nProof.\ninduction s as [| x s].\n  - intros t u.\n    change (cat a [] (cat a t u)) with (cat a t u).\n    change (cat a (cat a [] t) u) with (cat a t u).\n    reflexivity.\n  - intros t u.\n    unfold cat at 1.\n    fold cat.\n    rewrite (IHs t u).\n    unfold cat at -1. (* What? *)\n    fold cat.\n    reflexivity.\nQed.\n\n(*\n    let f replace :=\n      match goal with\n        [|- ?l = ?r] => \n          change l with replace\n      end \n    in f (cat t u).\n*)\n(*\n    match goal with\n      [H: ?toto |- ?l = ?r] => \n        idtac \"tutu\" \"l:\" l \"r:\" r;\n        match H with\n          t => idtac \"Found\"\n        end\n    end.\n*)\n\nTheorem cat_len : forall (a : Set) (s : seq a) (t : seq a),\n  len a (cat a s t) = len a s + len a t. \n\nRequire Import Omega.\n\nProof.\ninduction s.\n  - intros.\n    unfold cat.\n    unfold len at 2.\n    omega.\n  - intro t.\n    unfold cat.\n    fold cat.\n    unfold len at 1.\n    fold len.\n    unfold len at 2.\n    fold len.\n    apply eq_S.\n    apply IHs.\nQed.\n\nFixpoint rev0 (a : Set) (s : seq a) : seq a :=\n  match s with\n         [] => []                    (* gamma *)\n  | [x | s] => cat a (rev0 a s) [x]  (* delta *)\n  end.\n\nTheorem rev0_len : forall (a : Set) (s : seq a),\n  len a (rev0 a s) = len a s.\n\nRequire Import Nat.\n\nProof.\nintros.\ninduction s.\n  - unfold rev0.\n    reflexivity.\n  - unfold rev0.\n    fold rev0.\n    rewrite cat_len.\n    unfold len at 2.\n    unfold Nat.add at 2.\n    rewrite Nat.add_comm.\n    apply eq_S.\n    apply IHs.\nQed.\n\nLemma cat_nil : forall (a : Set) (s : seq a),\n  cat a s (Nil a) = s.\n\nProof.\nintros.\ninduction s.\n  - unfold cat.\n    reflexivity.\n  - unfold cat.\n    fold cat.\n    rewrite IHs.\n    reflexivity.\nQed.\n\nLemma cat_rev : forall (a : Set) (s t : seq a),\n  cat a (rev0 a t) (rev0 a s) = rev0 a (cat a s t).\n\nProof.\nintros.\ninduction s.\n  -rewrite cat_nil.\n   unfold cat.\n   reflexivity.\n - unfold rev0 at 2.\n   fold rev0.\n   rewrite cat_assoc.\n   rewrite IHs.\n   unfold cat at 3.\n   fold cat.\n   unfold rev0 at 2.\n   fold rev0.\n   reflexivity.\nQed.\n  \n\nTheorem idempotent : forall (a : Set) (s : seq a),\n  rev0 a (rev0 a s) = s.\n\nProof.\nintros.\ninduction s.\n  - unfold rev0 at 2.\n    reflexivity.\n  - unfold rev0 at 2.\n    fold rev0.\n    rewrite <- cat_rev.\n    rewrite IHs.\n    unfold rev0.\n    unfold cat.\n    reflexivity.\nQed.\n\nFixpoint rcat (a : Set) (l acc : seq a) :=\n  match l with\n           Nil _ => acc\n  | Cons _ hd tl => rcat a tl (Cons a hd acc)\n  end.\n\nDefinition rev (a : Set) (l : seq a) :=\n  rcat a l (Nil a).\n\nLemma rev_cat : forall a (s t : seq a),\n  rcat a s t = cat a (rev a s) t.\n\nProof.\nintros a s.\ninduction s as [|x s IH].\n  - unfold rcat.\n    unfold rev.\n    unfold rcat.\n    unfold cat.\n    reflexivity.\n  - intro t.\n    unfold rcat.\n    fold rcat.\n    rewrite -> (IH (Cons a x t)).\n    change t at 1 with (cat a (Nil a) t).\n    change (Cons a x (cat a (Nil a) t)) with\n           (cat a (Cons a x (Nil a)) t).\n    rewrite cat_assoc.\n    rewrite <- (IH (Cons a x (Nil a))).\n    unfold rev.\n    unfold rcat at 2.\n    fold rcat.\n    reflexivity.\nQed.\n\nTheorem eq_rev : forall a (s : seq a),\n  rev0 a s = rev a s.\n\nProof.\nintros.\ninduction s as [| x s IH].\n  - unfold rev0.\n    unfold rev.\n    unfold rcat.\n    reflexivity.\n  - unfold rev0.\n    fold rev0.\n    rewrite IH.\n    rewrite <- rev_cat. \n    unfold rev.\n    unfold rcat at 2.\n    fold rcat.\n    reflexivity.\nQed.\n\nFixpoint sfst1 (a : Set) (eq : a -> a -> bool) (s : seq a) (x : a) :=\n  match s with\n         Nil _ => s\n  | Cons _ y t => if eq x y then t \n                  else Cons a y (sfst1 a eq t x)\n  end.\n\n\nFixpoint sfst3 (a : Set) (eq : a -> a -> bool) (s : seq a) (x : a)\n               (t u : seq a) :=\n  match s with\n         Nil _ => u\n  | Cons _ y s => if eq x y then rcat a t s \n                  else sfst3 a eq s x (Cons a y t) u\n  end. \n\nDefinition sfst2 (a : Set) (eq : a -> a -> bool) \n           (s : seq a) (x : a ) :=\n  sfst3 a eq s x s.\n\nDefinition compose (a b c : Set) (g : b -> c) (f : a -> b) : a -> c :=\n   fun x => g (f x).\n\nFixpoint map (a b : Set) (f : a -> b) (s : seq a) : seq b :=\n  match s with\n    Nil _ => Nil b\n  | Cons _ hd tl => Cons b (f hd) (map a b f tl)\n  end.\n\nTheorem map_comp_comm :\n  forall (a b c : Set) (f : a -> b) (g : b -> c) (s : seq a),\n  map a c (compose a b c g f) s \n= compose (seq a) (seq b) (seq c) (map b c g) (map a b f) s.\n\nProof.\nintros.\ninduction s as [| x t].\n  - unfold map at 1.\n    unfold compose.\n    unfold map.\n    reflexivity.\n  - unfold map at 1.\n    fold map.\n    rewrite IHt.\n    unfold compose.\n    unfold map.\n    fold map.\n    reflexivity.\nQed.\n\nDefinition total_order (a : Set) : Set := { \n  cmp : a -> a -> bool | \n  forall x y, x = y \\/ cmp x y = true \\/ cmp y x = true \n}.\n\nRequire Import List.\n\nFixpoint ins (a : Set) (cmp : total_order a) \n             (s : list a) (x : a) :=\n  match s with\n    y::s' => \n      match cmp with \n        exist _ cmp' _ =>\n          if   cmp' x y\n          then x::s \n          else y :: ins a cmp s' x \n      end\n  | nil => x::s\n  end.\n\nFixpoint isrt (a : Set) (cmp : total_order a)\n              (s : list a) :=\n  match s with\n     nil => nil\n  | x::s => ins a cmp (isrt a cmp s) x\n  end.\n\n(* Set Implicit Arguments.*)\n\nInductive ord_list (a : Set) (cmp : total_order a)\n                 : list a -> Prop :=\n  ord_nil  : ord_list a cmp nil\n| ord_one  : forall x : a, ord_list a cmp (x::nil)\n| ord_more : forall (x y : a) (s : list a),\n             (let 'exist _ cmp' _ := cmp in\n                cmp' x y = true)\n             -> ord_list a cmp (y::s)\n             -> ord_list a cmp (x::y::s).\n\n(*\n(* Unmark View/Display notations for the following: *)\nPrint exist.\nLocate \"{ _ : _ | _ }\".\n{ x : nat | x < 10 }\n*)\n\n(* Arguments ord_nil [a]. *)\n\nPrint ord_list.\n\nSet Implicit Arguments.\n\n(* (* Three ways: *)\nInductive mylist a :=\n  my_nil\n| my_cons (hd: a) (tl: mylist a).\n\n| my_cons : a -> mylist a -> mylist a\n\n| my_cons : forall (hd : a) (tl : mylist a), mylist a.\n*)\n\n(*\nLemma len_ins : forall (a : Set) (gt : a -> a -> bool)\n                       (s : seq a) (x : a),\n  len a (Cons a x s) = len a (ins a gt s x).\n\nintros.\ninduction s as [| y t IH].\n  - unfold len at 1.\n    unfold ins.\n    unfold len.\n    reflexivity.\n  - unfold len.\n    fold len.\n    unfold ins.\n    fold ins.\n    case_eq (gt x y).\n    unfold len at 2.\n    fold len.\n    auto.\n    unfold len at 2.\n    fold len.\n*)\n", "meta": {"author": "rinderknecht", "repo": "Coq", "sha": "8c25f60c8aad69f7c7ff0c9b3289f1824cf65543", "save_path": "github-repos/coq/rinderknecht-Coq", "path": "github-repos/coq/rinderknecht-Coq/Coq-8c25f60c8aad69f7c7ff0c9b3289f1824cf65543/lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.6566180250127683}}
{"text": "Require Import Coq.Lists.List.\nSet Implicit Arguments. \n\n(* Functional Dependent Types *)\n(******************************)\n\n(* In addition to defining types inductively, we can also define types\n * using definitions and fixpoints. A simple example is n-tuples.\n *)\nSection tuple.\nVariable T : Type.\n\nFixpoint tuple (n : nat) : Type :=\n  match n with\n  | 0 => unit\n  | S n => T * tuple n\n  end%type.\n\n\nCheck @fst.\n\nDefinition tuple_hd {a} : tuple (S a) -> T :=\n  @fst _ _.\n\nPrint tuple_hd.\n\nDefinition tuple_tl {a} : tuple (S a) -> tuple a :=\n  @snd _ _.\n\n\n\nDefinition grabtype n:Type := match n with O => unit | S n => T end.\n\nLemma lastL: forall (n: nat), tuple n ->  grabtype n.\nProof.\ninduction n.\n- simpl; trivial.\n- simpl.\n  destruct n.\n  + intro H; destruct H; assumption.\n  + simpl in IHn. \n    intro.\n    apply IHn.\n    destruct X.\n    destruct t0.\n    split.\n    exact t0.\n    exact t1.\nDefined.\n\n\nFixpoint lastF (n: nat): tuple n ->  grabtype n:=\nmatch n as x return (tuple x -> grabtype x) with\n| O => fun t => t\n| S m => fun t (* tuple S m *) =>\n   (match m as n1 return ((tuple n1 -> grabtype n1) -> T * tuple n1 -> T)\n   with\n   | 0 => fun _ H => let (t, _) := H in t\n   | S n1 => fun IHn0 X => IHn0 (let (_,t0) := X in let (t1,t2) := t0 in (t1,t2))\n   end) (lastF m) t\nend.\n\nPrint lastL.\nPrint lastF.\n\nLemma last_eq: forall (n:nat)(t:tuple n), lastL n t = lastF n t.\nProof.\nintros.\nreflexivity.\nQed.\n\nLemma last_eqf: lastL = lastF.\nProof.\nintros.\nreflexivity.\nQed.\n\n\nDefinition lastOfNonempty (n:nat)(t:tuple (S n)):T := lastL (S n) t.\n\nVariable a b c: T.\n\nDefinition f: tuple 1 := (a,tt).\nDefinition g: tuple 2 := (b, f).\nDefinition h: tuple 3 := (c, g).\n\nEval compute in (lastOfNonempty h).\n\n\nEnd tuple.", "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/lastOfNonemptyTuple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6566024536392143}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import Psatz.\n\n(* this is for exercise at the moment *)\n\nTheorem double_negation_intrudoction (P : Prop) :\n  P -> ~(~ P).\nProof.\n  intro A.\n  intro B.\n  absurd P; auto.\nQed.\n(*\nCe se neko trditev lahko dokaze, \npotem ne obstaja dokaz o njeni nedokazljivosti.\n\nObratno pa ne znamo (double negation elimination)\nCe za neko trditev obstaja dokaz,\nda dokaz o njeni nedokazljivosti ne obstaja \nte trditve se vedno ne moremo dokazati.\n\nTo je tudi ena pomembnejsih ugotovitev logike.\nObstajajo trditve, ki se jih ne da dokazati niti ovreci.\nTo je dokazano. Ampak a se to zares lahko dokaze?\n*)\n\nTheorem d_n_double_negation_elimination (P : Prop) :\n  ~~(~~P -> P).\nProof.\n  intro.\n  absurd (~P).\n  - intro.\n    apply H.\n    intro.\n    absurd (~P); assumption.\n  - intro.\n    apply H.\n    intro.\n    assumption.\nQed.\n\nTheorem triple_negation_elimination (P : Prop) :\n  ~(~(~ P)) -> ~P.\nProof.\n  intro.\n  intro.\n  absurd P.\n  - intro.\n    apply H.\n    apply double_negation_intrudoction.\n    auto.\n  - auto.\nQed.\n\nLemma forall_forall_not (P: nat -> Prop) :\n  ~(~(forall x : nat, ~P x)) <-> forall x : nat, ~P x.\nProof.\n  split; try tauto.\n  intro.\n  intro x.\n  intro.\n  destruct H.\n  intro.\n  absurd (P x).\n  - auto.\n  - auto.\nQed.\n\nTheorem absurd_and (A :Prop) :\n  ~(A /\\ ~A).\nProof.\n  intro.\n  destruct H.\n  absurd A; auto.\nQed.\n\nTheorem double_negated_law_of_excluded_middle (P : Prop) :\n  ~~(P \\/ (~P)).\nProof.\n  intro.\n  absurd (~P).\n  - intro.\n    apply H.\n    right.\n    assumption.\n  - intro.\n    apply H.\n    left.\n    assumption.\nQed.\n(*\nPosledica: pri danih aksiomih nihce ne more \nimeti dokaza da zakon o izkljuceni tretji \nmoznosti ne drzi.\n\nMi lahko dokazemo da ni dokaza, \nki bi dokazal da ni dokaza, \nda zakon o izkljuceni tretji moznosti obstaja.\n*)\n\nLemma exists_forall (P : nat -> Prop):\n  ~ (exists x : nat, P x) <-> forall x : nat, ~ P x.\nProof.\n  (* firstorder. *)\n  split.\n  - intro A.\n    intro x.\n    intro B.\n    absurd (exists x : nat, P x); auto.\n    exists x.\n    apply B.\n  - intro A. \n    intro B.\n    destruct B.\n    absurd (P x); auto.\nQed.\n\nLemma exists_forall_n (P : nat -> Prop):\n  ~ (exists x : nat, ~P x) <-> forall x : nat, ~ ~ P x.\nProof.\n  split.\n  - intro A.\n    intro x.\n    intro B.\n    absurd (exists x : nat, ~P x); auto.\n    exists x.\n    apply B.\n  - intro A.\n    intro B.\n    destruct B.\n    absurd (~P x); auto.\nQed.\n\nLemma exists_forall_rev (P : nat -> Prop):\n  (forall x : nat, ~ P x) <-> ~(exists x : nat, P x).\nProof.\n  rewrite (exists_forall P).\n  split; auto.\nQed.\n\n(*\nTheorem zanikanje_implikacije (A B : Prop):\n  (A -> B) <-> (~B -> ~A).\nProof.\n  split; try tauto.\n  intro.\n  intro.\n  (* se ne da brez izkljucene tretje moznosti*)\n*)  \n\n(*\nTheorem law_of_excluded_middle_for_negated_exists (P: nat -> Prop) :\n  ~(exists x, P x) \\/ ~(~(exists x, P x)).\nProof.\n  pose (forall_forall_not P) as A.\n  rewrite (exists_forall_rev P) in A.\n  assert (~ (exists x : nat, P x) <-> ~ ~ ~ (exists x : nat, P x)).\n    - rewrite A; split; auto.\n    - do 10 rewrite H.\n*)\n\nLemma exists_nat (P: nat -> Prop) :\n  exists x : nat, True.\nProof.\n  exists 0; auto.\nQed.\n\nLemma exists_exists_not (P: nat -> Prop) :\n  ~(exists x : nat, ~P x) -> exists x : nat, ~~P x.\nProof.\n  rewrite exists_forall_n. (* ta mocnejsa *)\n  intro.\n  exists 0.\n  apply H.\nQed.\n\n\n(*\n\n\n(*\nto vrjetno ne drzi\nTheorem law_of_excluded_middle_propertie (P : Prop) :\n  ~P \\/ ~(~P) <-> P \\/ (~P).\nProof.\n  split.\n  - intro.\n*)\n\n(*\nTheorem law_of_excluded_middle_for_negated_prop (P : Prop) :\n  ~P \\/ ~(~P).\nProof.\n  pose (absurd_and P).\n*)\n\n\n(*\nTheorem pomozni (A B : Prop) :\n  (~A \\/ B) <-> (A -> B).\nProof.\n  split; try tauto.\n*)\n\nTheorem pomozna (A B : Prop) :\n  A -> ~(A /\\ B) -> ~B.\nProof.\n  intros P Q.\n  intro.\n  auto.\nQed.\n\n\n\nTheorem pomoznaC (A B : Prop) :\n  (A -> ~B) <-> (B -> ~A).\nProof.\n  split; try tauto.\nQed.\n\nTheorem pomoznaD (A B : Prop) :\n  (A -> B) -> (~B -> ~A).\nProof.\n  tauto.\nQed.\n\n\n\n\nLemma and_lasnost (A B : Prop) :\n  ~(~(~A /\\ ~B)) <-> (~A /\\ ~B).\nProof.\n  tauto.\nQed.\n\nLemma trikrat (P : Prop) :\n  ~(~(~P)) <-> ~P.\nProof.\n  tauto.\nQed.\n\nLemma trikratA (P : Prop) :\n  ~(~(~P)) -> ~P.\nProof.\n  tauto.\nQed.\n\nLemma pomozno (P : Prop) :\n   ~ (P \\/ ~ P) -> P.\nProof.\n  intro.\n  tauto.\n  Show Proof.\n\n\n\n\n\n  \nLemma forall_exists (P Q: nat -> Prop):\n  (forall n : nat, (P n = Q n)) -> ~(exists n : nat, ~(P n = Q n)).\nProof.\n  intro.\n  intro.\n  destruct H0.\n  auto.\nQed.\n  \n  \n(*\nTheorem multi_de_morgan (f : nat -> Prop) : \n  (forall n : nat, (f n)) -> ~(exists n : nat, ~(f n)).\n*)\n\nTheorem de_morgan (A B : Prop) :\n  (A /\\ B) -> ~(~A \\/ ~B).\nProof.\n  tauto.\nQed.\n\nTheorem de_morganX (A B : Prop) :\n  (~A /\\ ~B) <-> ~(A \\/ B).\nProof.\n  split; try tauto.\nQed.\n\nTheorem de_morganY (A B : Prop) :\n  ~(~A /\\ ~B) <-> (A \\/ B).\nProof.\n  split; try tauto.\nQed.\n\n\nTheorem de_morganX (A B : Prop) :\n  (A /\\ B) <-> ~(~A \\/ ~B).\nProof.\n  split; try tauto.\nQed.\n\n\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/kernel_logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245828938678, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6566024391080029}}
{"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(* ** Sparse ciphers *)\n\nRequire Import Arith Lia List Bool.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac gcd sums rel_iter bool_nat power_decomp prime.\n\nSet Implicit Arguments.\n\nLocal Notation power := (mscal mult 1).\nLocal Notation \"∑\" := (msum plus 0).\nLocal Infix \"≲\" := binary_le (at level 70, no associativity).\nLocal Infix \"⇣\" := nat_meet (at level 40, left associativity).\nLocal Infix \"⇡\" := nat_join (at level 50, left associativity).\n\n#[export] Hint Resolve power2_gt_0 : core.\n\nSection stability_of_power.\n\n  Fact mult_lt_power_2 u v k : u < power k 2 -> v < power k 2 -> u*v < power (2*k) 2.\n  Proof.\n    intros H1 H2.\n    replace (2*k) with (k+k) by lia.\n    rewrite power_plus.\n    apply Nat.lt_le_trans with ((S u)*S v).\n    simpl; rewrite (Nat.mul_comm _ (S _)); simpl; rewrite Nat.mul_comm; lia.\n    apply Nat.mul_le_mono; auto.\n  Qed.\n\n  Fact mult_lt_power_2_4 u v k : u < power k 2 -> v < power k 2 -> u*v < power (4*k) 2.\n  Proof.\n    intros H1 H2.\n    apply Nat.lt_le_trans with (1 := mult_lt_power_2 _ H1 H2).\n    apply power_mono_l; lia.\n  Qed.\n\n  Fact mult_lt_power_2_4' u1 v1 u2 v2 k : \n               u1 < power k 2 \n            -> v1 < power k 2\n            -> u2 < power k 2\n            -> v2 < power k 2\n            -> u1*v1+v2*u2 < power (4*k) 2.\n  Proof.\n    intros H1 H2 H3 H4.\n    destruct (eq_nat_dec k 0) as [ ? | Hk ].\n    - subst k; simpl.\n      rewrite power_0 in *.\n      destruct u1; destruct v1; destruct u2; destruct v2; subst; lia.\n    - apply Nat.lt_le_trans with (power (S (2*k)) 2). \n      + rewrite power_S, <- mult_2_eq_plus.\n        apply Nat.add_lt_mono; apply mult_lt_power_2; auto.\n      + apply power_mono_l; lia.\n  Qed.\n\nEnd stability_of_power.\n\nSection power_decomp.\n\n  Variable (p : nat) (Hp : 2 <= p).\n\n  Let power_nzero x : power x p <> 0.\n  Proof. generalize (@power_ge_1 x p); lia. Qed.\n\n  Fact power_decomp_lt n f a q :  \n           (forall i j, i < j < n -> f i < f j)\n        -> (forall i, i < n -> f i < q)\n        -> (forall i, i < n -> a i < p)\n        -> ∑ n (fun i => a i * power (f i) p) < power q p.\n  Proof using Hp.\n    revert q; induction n as [ | n IHn ]; intros q Hf1 Hf2 Ha.\n    + rewrite msum_0; apply power_ge_1; lia.\n    + rewrite msum_plus1; auto.\n      apply Nat.lt_le_trans with (1*power (f n) p + a n * power (f n) p).\n      * apply Nat.add_lt_le_mono; auto.\n        rewrite Nat.mul_1_l.\n        apply IHn.\n        - intros; apply Hf1; lia.\n        - intros; apply Hf1; lia.\n        - intros; apply Ha; lia.\n      * rewrite <- Nat.mul_add_distr_r.\n        replace q with (S (q-1)).\n        - rewrite power_S; apply Nat.mul_le_mono; auto.\n          ++ apply Ha; auto.\n          ++ apply power_mono_l; try lia.\n             generalize (Hf2 n); intros; lia.\n        - generalize (Hf2 0); intros; lia.\n  Qed.\n\n  Lemma power_decomp_is_digit n a f : \n           (forall i j, i < j < n -> f i < f j)\n        -> (forall i, i < n -> a i < p)\n        ->  forall i, i < n -> is_digit (∑ n (fun i => a i * power (f i) p)) p (f i) (a i).\n  Proof using Hp.\n    intros Hf Ha.\n    induction n as [ | n IHn ]; intros i Hi.\n    + lia.\n    + split; auto.\n      exists (∑ (n-i) (fun j => a (S i + j) * power (f (S i+j) - f i - 1) p)), \n             (∑ i (fun j => a j * power (f j) p)); split.\n      - replace (S n) with (S i + (n-i)) by lia.\n        rewrite msum_plus, msum_plus1; auto.\n        rewrite <- Nat.add_assoc, Nat.add_comm; f_equal.\n        rewrite Nat.mul_add_distr_r, Nat.add_comm; f_equal.\n        rewrite <- Nat.mul_assoc, Nat.mul_comm, <- sum_0n_scal_l.\n        apply msum_ext.\n        intros j Hj.\n        rewrite (Nat.mul_comm (_ * _));\n        repeat rewrite <- Nat.mul_assoc; f_equal.\n        rewrite <- power_S, <- power_plus; f_equal.\n        generalize (Hf i (S i+j)); intros; lia.\n      - apply power_decomp_lt; auto.\n        * intros; apply Hf; lia.\n        * intros; apply Ha; lia.\n  Qed.\n\n  Theorem power_decomp_unique n f a b :\n            (forall i j, i < j < n -> f i < f j)\n         -> (forall i, i < n -> a i < p)\n         -> (forall i, i < n -> b i < p)\n         -> ∑ n (fun i => a i * power (f i) p)\n          = ∑ n (fun i => b i * power (f i) p)\n         -> forall i, i < n -> a i = b i.\n  Proof using Hp.\n    intros Hf Ha Hb E i Hi.\n    generalize (power_decomp_is_digit _ _ Hf Ha Hi)\n               (power_decomp_is_digit _ _ Hf Hb Hi).\n    rewrite E; apply is_digit_fun.\n  Qed.\n\nEnd power_decomp.\n\nSection power_decomp_uniq.\n\n  Variable (p : nat) (Hp : 2 <= p).\n\n  Theorem power_decomp_factor n f a : \n           (forall i, 0 < i < S n -> f 0 < f i)\n        -> ∑ (S n) (fun i => a i * power (f i) p) \n         = ∑ n (fun i => a (S i) * power (f (S i) - f 0 - 1) p) * power (S (f 0)) p\n         + a 0 * power (f 0) p.\n  Proof using Hp.\n    intros Hf.\n    rewrite msum_S, Nat.add_comm; f_equal.\n    rewrite <- sum_0n_scal_r.\n    apply msum_ext.\n    intros i Hi.\n    rewrite <- Nat.mul_assoc; f_equal.\n    rewrite <- power_plus; f_equal.\n    generalize (Hf (S i)); intros; lia.\n  Qed.\n\n  Let power_nzero x : power x p <> 0.\n  Proof.\n    generalize (@power_ge_1 x p); lia.\n  Qed.\n\n  Let lt_minus_cancel a b c : a < b < c -> b - a - 1 < c - a - 1.\n  Proof. intros; lia. Qed. \n\n  (* Another proof of the above statement *)\n\n  Theorem power_decomp_unique' n f a b :\n            (forall i j, i < j < n -> f i < f j)\n         -> (forall i, i < n -> a i < p)\n         -> (forall i, i < n -> b i < p)\n         -> ∑ n (fun i => a i * power (f i) p)\n          = ∑ n (fun i => b i * power (f i) p)\n         -> forall i, i < n -> a i = b i.\n  Proof using Hp.\n    revert f a b.\n    induction n as [ | n IHn ]; intros f a b Hf Ha Hb.\n    + intros; lia.\n    + assert (forall i, 0 < i < S n -> f 0 < f i)\n        by (intros; apply Hf; lia). \n      do 2 (rewrite power_decomp_factor; auto).\n      intros E.\n      apply div_rem_uniq in E; auto.\n      * destruct E as (E1 & E2).\n        intros [ | i ] Hi.\n        - revert E2; rewrite Nat.mul_cancel_r; auto.\n        - apply IHn with (4 := E1); try lia.\n          ++ intros u j Hu; apply lt_minus_cancel; split; apply Hf; lia. \n          ++ intros; apply Ha; lia.\n          ++ intros; apply Hb; lia.\n      * rewrite power_S.\n        apply Nat.mul_lt_mono_pos_r.\n        - apply power_ge_1; lia.\n        - apply Ha; lia.\n      * rewrite power_S.\n        apply Nat.mul_lt_mono_pos_r.\n        - apply power_ge_1; lia.\n        - apply Hb; lia.\n  Qed.\n\nEnd power_decomp_uniq.\n\nFact mult_2_eq_plus x : x + x = 2 *x.\nProof. ring. Qed.\n\nSection power_injective.\n\n  Local Lemma power_2_inj_1 i j n : j < i -> 2* power n 2 <> power i 2 + power j 2.\n  Proof.\n    rewrite <- power_S; intros H4 E.\n     generalize (@power_ge_1 j 2); intro C.\n     destruct (lt_eq_lt_dec i (S n)) as [ [ H5 | H5 ] | H5 ].\n     + apply power_mono_l with (x := 2) in H5; auto.\n       rewrite power_S in H5.\n       apply power_mono_l with (x := 2) in H4; auto.\n       rewrite power_S in H4; lia.\n     + subst i; lia.\n     + apply power_mono_l with (x := 2) in H5; auto.\n      rewrite power_S in H5; lia.\n  Qed.\n\n  Fact power_2_n_ij_neq i j n : i <> j -> power (S n) 2 <> power i 2 + power j 2.\n  Proof.\n    intros H.\n    destruct (lt_eq_lt_dec i j) as [ [] | ]; try tauto.\n    + rewrite Nat.add_comm; apply power_2_inj_1; auto.\n    + apply power_2_inj_1; auto.\n  Qed.\n\n  Fact power_2_inj i j : power i 2 = power j 2 -> i = j.\n  Proof.\n    intros H.\n    destruct (lt_eq_lt_dec i j) as [ [ C | C ] | C ]; auto;\n      apply power_smono_l with (x := 2) in C; lia.\n  Qed.\n\n  Local Lemma power_plus_lt a b c : a < b < c -> power a 2 + power b 2 < power c 2.\n  Proof.\n    intros [ H1 H2 ].\n    apply power_mono_l with (x := 2) in H2; auto.\n    apply power_smono_l with (x := 2) in H1; auto.\n    rewrite power_S in H2; lia.\n  Qed.\n\n  Local Lemma power_inj_2 i1 j1 i2 j2 : \n             j1 < i1 \n          -> j2 < i2 \n          -> power i1 2 + power j1 2 = power i2 2 + power j2 2\n          -> i1 = i2 /\\ j1 = j2.\n  Proof.\n    intros H1 H2 H3.\n    destruct (lt_eq_lt_dec i1 i2) as [ [ C | C ] | C ].\n    + generalize (@power_plus_lt j1 i1 i2); intros; lia.\n    + split; auto; apply power_2_inj; subst; lia.\n    + generalize (@power_plus_lt j2 i2 i1); intros; lia.\n  Qed.\n\n  Theorem sum_2_power_2_injective i1 j1 i2 j2 :\n              j1 <= i1 \n           -> j2 <= i2 \n           -> power i1 2 + power j1 2 = power i2 2 + power j2 2 \n           -> i1 = i2 /\\ j1 = j2.\n  Proof.\n    intros H1 H2 E.\n    destruct (eq_nat_dec i1 j1) as [ H3 | H3 ];\n    destruct (eq_nat_dec i2 j2) as [ H4 | H4 ].\n    + subst j1 j2.\n      assert (i1 = i2); auto.\n      do 2 rewrite mult_2_eq_plus, <- power_S in E.\n      apply power_2_inj in E; lia.\n    + subst j1; rewrite mult_2_eq_plus in E.\n      apply power_2_inj_1 in E; lia.\n    + subst j2; symmetry in E.\n      rewrite mult_2_eq_plus in E.\n      apply power_2_inj_1 in E; lia.\n    + revert E; apply power_inj_2; lia.\n  Qed. \n \nEnd power_injective.\n\nFact divides_power p a b : a <= b -> divides (power a p) (power b p).\nProof.\n  (* split. *)\n  * induction 1 as [ | b H IH ].\n    + apply divides_refl.\n    + apply divides_trans with (1 := IH).\n      rewrite power_S; apply divides_mult, divides_refl.\n(*  * intros H.\n    apply divides_le in H. *)\nQed.\n\nFact divides_msum k n f : (forall i, i < n -> divides k (f i)) -> divides k (∑ n f).\nProof.\n  revert f; induction n as [ | n IHn ]; intros f Hf.\n  + rewrite msum_0; apply divides_0.\n  + rewrite msum_S; apply divides_plus.\n    * apply Hf; lia.\n    * apply IHn; intros; apply Hf; lia.\nQed.\n\nFact inc_seq_split_lt n f k : \n         (forall i j, i < j < n -> f i < f j) \n      -> { p | p <= n /\\ (forall i, i < p -> f i < k) /\\ forall i, p <= i < n -> k <= f i }.\nProof.\n  revert f; induction n as [ | n IHn ]; intros f Hf.\n  + exists 0; split; auto; split; intros; lia.\n  + destruct (le_lt_dec k (f 0)) as [ H | H ].\n    - exists 0; split; try lia.\n      split; intros i Hi; try lia.\n      destruct i as [ | i ]; auto.\n      apply Nat.le_trans with (1 := H), Nat.lt_le_incl, Hf; lia.\n    - destruct (IHn (fun i => f (S i))) as (p & H1 & H2 & H3).\n      * intros; apply Hf; lia.\n      * exists (S p); split; try lia; split.\n        ++ intros [ | i ] Hi; auto; apply H2; lia.\n        ++ intros [ | i ] Hi; try lia; apply H3; lia.\nQed.\n\nFact inc_seq_split_le n f h : (forall i j, i < j < n -> f i < f j) \n                   -> { q | q <= n \n                         /\\ (forall i, i < q      -> f i <= h)\n                         /\\ (forall i, q <= i < n -> h < f i) }.\nProof.\n  intros Hf.\n  destruct inc_seq_split_lt with (1 := Hf) (k := S h)\n    as (q & H1 & H2 & H3); exists q; split; auto; split.\n  + intros i Hi; specialize (H2 _ Hi); lia.\n  + intros i Hi; specialize (H3 _ Hi); lia.\nQed.\n\nFact divides_lt p q : q < p -> divides p q -> q = 0.\nProof.\n  intros H1 ([ | k] & H2); auto.\n  revert H2; simpl; generalize (k *p); intros; lia.\nQed.\n\nFact sum_powers_inc_lt_last n f r : \n        2 <= r\n     -> (forall i j, i < j <= n -> f i < f j)\n     -> ∑ (S n) (fun i => power (f i) r) < power (S (f n)) r.\nProof.\n  intros Hr.\n  revert f.\n  induction n as [ | n IHn ]; intros f Hf.\n  + rewrite msum_1; auto; apply power_smono_l; auto.\n  + rewrite msum_plus1; auto.\n    rewrite power_S.\n    apply Nat.lt_le_trans with (power (S (f n)) r + power (f (S n)) r).\n    * apply Nat.add_lt_mono_r; auto.\n      apply IHn; intros; apply Hf; lia.\n    * assert (power (S (f n)) r <= power (f (S n)) r) as H.\n      { apply power_mono_l; try lia; apply Hf; lia. }\n      apply Nat.le_trans with (2 * power (f (S n)) r); try lia.\n      apply Nat.mul_le_mono; auto.\nQed.\n\nFact sum_powers_inc_lt n f p r : \n        2 <= r\n     -> (forall i, i < n -> f i < p)\n     -> (forall i j, i < j < n -> f i < f j)\n     -> ∑ n (fun i => power (f i) r) < power p r.\nProof.\n  destruct n as [ | n ].\n  + intros H _ _; rewrite msum_0; apply power_ge_1; lia.\n  + intros H1 H2 H3.\n    apply Nat.lt_le_trans with (power (S (f n)) r).\n    * apply sum_powers_inc_lt_last; auto.\n      intros; apply H3; lia.\n    * apply power_mono_l; try lia.\n      apply H2; auto.\nQed.\n\n(* the value r^f1 + ... + f^fn uniquely determines n and f1 < ... < fn  *)\n\nFact sum_powers_injective r n f m g :\n       2 <= r\n    -> (forall i j, i < j < n -> f i < f j)\n    -> (forall i j, i < j < m -> g i < g j)\n    -> ∑ n (fun i => power (f i) r) = ∑ m (fun i => power (g i) r)\n    -> n = m /\\ forall i, i < n -> f i = g i.\nProof.\n  intros Hr; revert m f g.\n  induction n as [ | n IHn ]; intros m f g Hf Hg.\n  + rewrite msum_0.\n    destruct m as [ | m ].\n    * rewrite msum_0; split; auto; intros; lia.\n    * rewrite msum_S.\n      generalize (@power_ge_1 (g 0) r); intros; exfalso; lia.\n  + destruct m as [ | m ].\n    * rewrite msum_0, msum_S; intros; exfalso.\n       generalize (@power_ge_1 (f 0) r); intros; exfalso; lia.\n    * destruct (lt_eq_lt_dec (f n) (g m)) as [ [E|E]| E].\n      - rewrite msum_plus1 with (n := m); auto. \n        intros; exfalso.\n        assert (∑ (S n) (fun i => power (f i) r) < power (g m) r) as C; try lia.\n        apply sum_powers_inc_lt; auto.\n        intros i Hi.\n        destruct (eq_nat_dec i n); subst; auto.\n        apply Nat.lt_trans with (2 := E), Hf; lia.\n      - do 2 (rewrite msum_plus1; auto); intros C.\n        destruct (IHn m f g) as (H1 & H2).\n        ++ intros; apply Hf; lia.\n        ++ intros; apply Hg; lia.\n        ++ rewrite E in C; lia.\n        ++ split; subst; auto.\n           intros i Hi.\n           destruct (eq_nat_dec i m); subst; auto.\n           apply H2; lia.\n      - rewrite msum_plus1 with (n := n); auto. \n        intros; exfalso.\n        assert (∑ (S m) (fun i => power (g i) r) < power (f n) r) as C; try lia.\n        apply sum_powers_inc_lt; auto.\n        intros i Hi.\n        destruct (eq_nat_dec i m); subst; auto.\n        apply Nat.lt_trans with (2 := E), Hg; lia.\nQed.\n\nFact power_divides_sum_power r p n f :\n         2 <= r \n      -> 0 < n\n      -> (forall i j, i < j < n -> f i < f j) \n      -> divides (power p r) (∑ n (fun i => power (f i) r)) <-> p <= f 0.\nProof.\n  intros Hr Hn Hf.\n  split.\n  + destruct inc_seq_split_lt with (k := p) (1 := Hf) as (k & H1 & H2 & H3).\n    replace n with (k+(n-k)) by lia.\n    rewrite msum_plus; auto.\n    rewrite Nat.add_comm; intros H.\n    apply divides_plus_inv in H.\n    2: apply divides_msum; intros; apply divides_power, H3; lia.\n    destruct k as [ | k ].\n    * apply H3; lia.\n    * apply divides_lt in H.\n      - rewrite msum_S in H.\n        generalize (@power_ge_1 (f 0) r); intros; lia.\n      - apply sum_powers_inc_lt; auto.\n        intros; apply Hf; lia.\n  + intros H.\n    apply divides_msum.\n    intros i Hi; apply divides_power.\n    apply Nat.le_trans with (1 := H).\n    destruct i; auto. \n    generalize (Hf 0 (S i)); intros; lia.\nQed.\n\nFact smono_upto_injective n f :\n       (forall i j, i < j < n -> f i < f j)\n    -> (forall i j, i < n -> j < n -> f i = f j -> i = j).\nProof.\n  intros Hf i j Hi Hj E.\n  destruct (lt_eq_lt_dec i j) as [ [H|] | H ]; auto.\n  + generalize (@Hf i j); intros; lia.\n  + generalize (@Hf j i); intros; lia.\nQed.\n\nFact product_sums n f g : (∑ n f)*(∑ n g) \n                         = ∑ n (fun i => f i*g i) \n                         + ∑ n (fun i => ∑ i (fun j => f i*g j + f j*g i)).\nProof.\n  induction n as [ | n IHn ].\n  + repeat rewrite msum_0; auto.\n  + repeat rewrite msum_plus1; auto.\n    repeat rewrite Nat.mul_add_distr_l.\n    repeat rewrite Nat.mul_add_distr_r.\n    rewrite IHn, msum_sum; auto.\n    * rewrite sum_0n_scal_l, sum_0n_scal_r; ring.\n    * intros; ring.\nQed.\n\nSection sums.\n\n  Fact square_sum n f : (∑ n f)*(∑ n f) = ∑ n (fun i => f i*f i) + 2*∑ n (fun i => ∑ i (fun j => f i*f j)).\n  Proof.\n    rewrite product_sums, <- sum_0n_scal_l; f_equal.\n    apply msum_ext; intros; rewrite <- sum_0n_scal_l.\n    apply msum_ext; intros; ring.\n  Qed. \n\n  Fact sum_regroup r k n f :\n          (forall i, i < n -> f i < k) \n       -> (forall i j, i < j < n -> f i < f j)\n       -> { g | ∑ n (fun i => power (f i) r) \n              = ∑ k (fun i => g i * power i r) \n             /\\ (forall i, i < k  -> g i <= 1) \n             /\\ (forall i, k <= i -> g i = 0) }.\n  Proof.\n    revert k f; induction n as [ | n IHn ]; intros k f Hf1 Hf2.\n    + exists (fun _ => 0); split; auto.\n      rewrite msum_0, msum_of_unit; auto.\n    + destruct (IHn (f n) f) as (g & H1 & H2 & H3).\n      * intros; apply Hf2; lia.\n      * intros; apply Hf2; lia.\n      * exists (fun i => if eq_nat_dec i (f n) then 1 else g i).\n        split; [ | split ].\n        - rewrite msum_plus1, H1; auto.\n          replace k with (f n + S (k - f n -1)).\n          2: generalize (Hf1 n); intros; lia.\n          rewrite msum_plus; auto; f_equal.\n          ++ apply msum_ext.\n             intros i He.\n             destruct (eq_nat_dec i (f n)); try ring; lia.\n          ++ rewrite msum_S, msum_of_unit; auto.\n             ** repeat (rewrite Nat.add_comm; simpl). \n                destruct (eq_nat_dec (f n) (f n)); try ring; lia.\n             ** intros i Hi.\n                destruct (eq_nat_dec (f n+S i) (f n)); try lia.\n                rewrite H3; lia.\n        - intros i Hi.\n          destruct (eq_nat_dec i (f n)); auto.\n          destruct (le_lt_dec (f n) i).\n          ++ rewrite H3; lia.\n          ++ apply H2; lia.\n        - intros i Hi.\n          generalize (Hf1 n); intros.\n          destruct (eq_nat_dec i (f n)); try lia.\n          apply H3; lia.\n  Qed.\n \n  Section sum_sum_regroup.\n\n    Variable (r n k : nat) (f : nat -> nat)\n             (Hf1 : forall i, i < n -> f i <= k) \n             (Hf2 : forall i j, i < j < n -> f i < f j).\n\n    Theorem sum_sum_regroup : { g | ∑ n (fun i => ∑ i (fun j => power (f i + f j) r))\n                                  = ∑ (2*k) (fun i => g i * power i r) \n                                  /\\ forall i, g i <= n }.\n    Proof using Hf1 Hf2.\n      revert n f Hf1 Hf2. \n      induction n as [ | p IHp ]; intros f Hf1 Hf2.\n      + exists (fun _ => 0); split; auto.\n        rewrite msum_0.\n        simpl; rewrite msum_of_unit; auto.\n      + destruct (IHp f) as (g & H1 & H2).\n        * intros; apply Hf1; lia.\n        * intros; apply Hf2; lia.\n        * destruct sum_regroup with (r := r) (n := p) (f := fun j => f p + f j) (k := 2*k)\n            as (g1 & G1 & G2 & G3).\n          - intros i Hi; generalize (@Hf1 p) (@Hf2 i p); intros; lia.\n          - intros i j H; generalize (@Hf2 i j); intros; lia.\n          - assert (forall i, g1 i <= 1) as G4.\n            { intro i; destruct (le_lt_dec (2*k) i); auto; rewrite G3; lia. }\n            exists (fun i => g i + g1 i); split.\n            ++ rewrite msum_plus1; auto.\n               rewrite H1, G1, <- msum_sum; auto.\n               2: intros; ring.\n               apply msum_ext; intros; ring.\n            ++ intros i.\n               generalize (H2 i) (G4 i); intros; lia.\n    Qed.\n\n  End sum_sum_regroup.\n\n  Section all_ones.\n\n    Local Lemma equation_inj x y a b : 1 <= x -> 1+x*a = y -> 1+x*b = y -> a = b.\n    Proof.\n      intros H1 H2 H3.\n      rewrite <- H3 in H2; clear y H3.\n      rewrite <- (@Nat.mul_cancel_l _ _ x); lia.\n    Qed.\n\n    Variables (r : nat) (Hr : 2 <= r).\n\n    Fact all_ones_equation l : 1+(r-1)*∑ l (fun i => power i r) = power l r.\n    Proof using Hr.\n      induction l as [ | l IHl ].\n      * rewrite msum_0, Nat.mul_0_r, power_0; auto.\n      * rewrite msum_plus1; auto.\n        rewrite Nat.mul_add_distr_l, power_S.\n        replace r with (1+(r-1)) at 4 by lia.\n        rewrite Nat.mul_add_distr_r.\n        rewrite <- IHl at 2; ring.\n    Qed.\n\n    Fact all_ones_dio l w : w = ∑ l (fun i => power i r) <-> 1+(r-1)*w = power l r.\n    Proof using Hr.\n      split.\n      + intros; subst; apply all_ones_equation.\n      + intros H.\n        apply equation_inj with (2 := H).\n        * lia.\n        * apply all_ones_equation.\n    Qed.\n\n  End all_ones.\n\n  Section const_1.\n\n    Variable (l q : nat) (Hl : 0 < l) (Hlq : l+1 < q).\n\n    Let Hq : 1 <= q.     Proof. lia. Qed. \n    Let Hq' : 0 < 4*q.   Proof. lia. Qed.\n    \n    Let r := (power (4*q) 2).\n\n    Let Hr' : 4 <= r.    Proof. apply (@power_mono_l 2 (4*q) 2); lia. Qed.\n    Let Hr :  2 <= r.    Proof. lia. Qed.\n\n    Section all_ones.\n\n      Variable (n w : nat) (Hw : w = ∑ n (fun i => power i r)).\n\n      Local Lemma Hw_0 : w = ∑ n (fun i => 1*power i r).\n      Proof using Hw. rewrite Hw; apply msum_ext; intros; ring. Qed.\n\n      Fact all_ones_joins : w = msum nat_join 0 n (fun i => 1*power i r).\n      Proof using Hl Hlq Hw. \n        rewrite Hw_0.\n        apply sum_powers_ortho with (q := 4*q); auto; try lia.\n      Qed.\n\n      Local Lemma Hw_1 : 2*w = ∑ n (fun i => 2*power i r).\n      Proof using Hw. \n        rewrite Hw_0, <- sum_0n_scal_l.\n        apply msum_ext; intros; ring.\n      Qed.\n\n      Fact all_ones_2_joins : 2*w = msum nat_join 0 n (fun i => 2*power i r).\n      Proof using Hl Hlq Hw.\n        rewrite Hw_1.\n        apply sum_powers_ortho with (q := 4*q); auto; try lia.\n      Qed.\n\n    End all_ones.\n\n    Section increase.\n   \n      Variable (m k k' u w : nat) (f : nat -> nat) \n               (Hm : 2*m < r) \n               (Hf1 : forall i, i < m -> f i <= k)\n               (Hf2 : forall i j, i < j < m  -> f i < f j)\n               (Hw : w = ∑ k' (fun i => power i r))\n               (Hu : u = ∑ m (fun i => power (f i) r)).\n\n      Let Hf4 : forall i j, i < m -> j < m -> f i = f j -> i = j.\n      Proof. apply smono_upto_injective; auto. Qed.\n\n      Let u1 := ∑ m (fun i => power (2*f i) r).\n      Let u2 := ∑ m (fun i => ∑ i (fun j => 2*power (f i + f j) r)).\n\n      Fact const_u_square : u * u = u1 + u2.\n      Proof using Hl Hlq Hw Hu Hm.\n        unfold u1, u2.\n        rewrite Hu, square_sum; f_equal.\n        + apply msum_ext; intros; rewrite <- power_plus; f_equal; lia.\n        + rewrite <- sum_0n_scal_l; apply msum_ext; intros i Hi.\n          rewrite <- sum_0n_scal_l; apply msum_ext; intros j Hj.\n          rewrite power_plus; ring.\n      Qed.\n\n      Local Lemma Hu1_0 : u1 = ∑ m (fun i => 1*power (2*f i) r).\n      Proof. apply msum_ext; intros; ring. Qed.\n\n      Local Lemma Hseq_u a : a <= m -> ∑ a (fun i => 1*power (2*f i) r) = msum nat_join 0 a (fun i => 1*power (2*f i) r).\n      Proof using Hw Hf2 Hl Hlq Hm Hu.\n        intros Ha.\n        apply sum_powers_ortho with (q := 4*q); auto; try lia.\n        intros i j Hi Hj ?; apply Hf4; lia.\n      Qed.\n\n      Local Lemma Hu1 : u1 = msum nat_join 0 m (fun i => 1*power (2*f i) r).\n      Proof using Hw Hf2 Hl Hlq Hm Hu. \n        rewrite Hu1_0; apply Hseq_u; auto.\n      Qed.\n\n      Local Lemma Hu2_0 : u2 = 2 * ∑ m (fun i => ∑ i (fun j => power (f i + f j) r)).\n      Proof.\n        unfold u2; rewrite <- sum_0n_scal_l; apply msum_ext.\n        intros; rewrite <- sum_0n_scal_l; apply msum_ext; auto.\n      Qed.\n\n      (* MAJOR change in the argumentation ... one cannot show\n         in generalize that the powers r^(f i + f j) are distincts\n         powers for the values j < i < n, hence it is not correct\n         than the sum reduces to a join ... it works when \n         f i = 2^i but not for an arbitrary (increasing function) f \n\n         So we rewrite ∑ {j < i < n} r^(f i + f j) as\n            ∑ {i < k} (g i)*r^i for some small g i <= n\n         supposing n is low compared to r *) \n         \n\n      Local Lemma g_full : { g | ∑ m (fun i => ∑ i (fun j => power (f i + f j) r))\n                      = ∑ (2*k) (fun i : nat => g i * power i r) \n                      /\\ forall i : nat, g i <= m }.\n      Proof using Hf1 Hf2. apply sum_sum_regroup; auto. Qed.\n \n      Let g := proj1_sig g_full.\n      Local Lemma Hg1 : u2 = ∑ (2*k) (fun i => (2*g i) * power i r).\n      Proof. \n        rewrite Hu2_0, (proj1 (proj2_sig g_full)), <- sum_0n_scal_l.\n        apply msum_ext; unfold g; intros; ring.\n      Qed.\n\n      Local Lemma Hg2 i : 2*g i <= 2*m.\n      Proof. apply Nat.mul_le_mono; auto; apply (proj2_sig g_full). Qed.\n\n      Let Hg3 i : 2*g i < r.\n      Proof using Hm. apply Nat.le_lt_trans with (1 := Hg2 _); auto. Qed.\n      \n      Let Hu2 : u2 = msum nat_join 0 (2*k) (fun i => (2*g i) * power i r).  \n      Proof.\n        rewrite Hg1.\n        apply sum_powers_ortho with (q := 4*q); auto; lia.\n      Qed.\n  \n      Let Hu1_u2_1 : u1 ⇣ u2 = 0.\n      Proof.\n        rewrite Hu1, Hu2.\n        apply nat_ortho_joins.\n        intros i j Hi Hj.\n        destruct (eq_nat_dec j (2*f i)) as [ H | H ].\n        + unfold r; do 2 rewrite <- power_mult.\n          rewrite <- H.\n          rewrite nat_meet_mult_power2.\n          rewrite nat_meet_12n; auto.\n        + rewrite nat_meet_powers_neq with (q := 4*q); auto; lia.\n      Qed.\n\n      Let Hu1_u2 : u*u = u1 ⇡ u2.\n      Proof.\n        rewrite const_u_square.\n        apply nat_ortho_plus_join; auto.\n      Qed.\n   \n      Let Hw_1 : w = msum nat_join 0 k' (fun i => 1*power i r).\n      Proof. rewrite Hw; apply all_ones_joins; auto. Qed.\n\n      Let H2w_1 : 2*w = msum nat_join 0 k' (fun i => 2*power i r).\n      Proof. rewrite Hw; apply all_ones_2_joins; auto. Qed.\n\n      Local Lemma Hu2_w : u2 ⇣ w = 0.\n      Proof using Hf1 Hf2 H2w_1 Hu1_u2.\n        rewrite Hu2, Hw_1.\n        destruct (le_lt_dec k' (2*k)) as [ Hk | Hk ].\n        2: { apply nat_ortho_joins.\n             intros i j Hi Hj.\n             rewrite nat_meet_comm.\n             destruct (eq_nat_dec i j) as [ H | H ].\n             + subst j; rewrite nat_meet_powers_eq with (q := 4*q); auto.\n               rewrite nat_meet_12n; auto.\n             + apply nat_meet_powers_neq with (q := 4*q); auto; try lia. }\n        replace (2*k) with (k'+(2*k-k')) by lia.\n        rewrite msum_plus, nat_meet_comm, nat_meet_join_distr_l, nat_join_comm; auto.\n        rewrite (proj2 (nat_ortho_joins k' (2*k-k') _ _)), nat_join_0n.\n        2: { intros i j H1 H2.\n             apply nat_meet_powers_neq with (q := 4*q); auto; try lia. }\n        apply nat_ortho_joins.\n        intros i j Hi Hj.\n        destruct (eq_nat_dec i j) as [ H | H ].\n        + subst j; rewrite nat_meet_powers_eq with (q := 4*q); auto.\n          rewrite nat_meet_12n; auto.\n        + apply nat_meet_powers_neq with (q := 4*q); auto; try lia.\n      Qed.\n\n      Fact const_u1_prefix : { q | q <= m /\\ u*u ⇣ w = ∑ q (fun i => 1*power (2*f i) r) }.\n      Proof using H2w_1 Hf1 Hf2 Hu1_u2.\n        destruct inc_seq_split_lt with (n := m) (f := fun i => 2*f i) (k := k') as (a & H1 & H2 & H3).\n        + intros i j Hij; apply Hf2 in Hij; lia.\n        + exists a; split; auto.\n          rewrite Hu1_u2, nat_meet_comm, nat_meet_join_distr_l.\n          do 2 rewrite (nat_meet_comm w).\n          rewrite Hu2_w, nat_join_n0.\n          rewrite Hu1, Hw_1.\n          replace m with (a+(m-a)) by lia.\n          rewrite msum_plus, nat_meet_comm, nat_meet_join_distr_l.\n          rewrite nat_join_comm.\n          rewrite (proj2 (nat_ortho_joins k' (m-a) _ _)), nat_join_0n; auto.\n          3: apply nat_join_monoid.\n          * rewrite Hseq_u; auto.\n            rewrite nat_meet_comm.\n            apply binary_le_nat_meet.\n            apply nat_joins_binary_le.\n            intros i Hi.\n            exists (2*f i); split; auto.\n          * intros; apply  nat_meet_powers_neq with (q := 4*q); auto; try lia.\n            generalize (H3 (a + j)); intros; lia.\n      Qed. \n         \n      Hypothesis (Hk : 2*k < k').\n\n      Let Hu1_w : u1 ⇣ w = u1.\n      Proof.\n        apply binary_le_nat_meet.\n        rewrite Hu1, Hw_1.\n        apply nat_joins_binary_le.\n        intros i Hi.\n        exists (2*f i); split; auto.\n        apply Nat.le_lt_trans with (2 := Hk), Nat.mul_le_mono; auto.\n      Qed.\n\n      Let Hu1_2w : u1 ⇣ (2*w) = 0.\n      Proof.\n        rewrite H2w_1, Hu1, nat_ortho_joins.\n        intros i j Hi Hj.\n        destruct (eq_nat_dec j (2 * f i)) as [ H | H ].\n        + rewrite <- H, nat_meet_powers_eq with (q := 4*q); auto; try lia.\n          rewrite nat_meet_12; auto.\n        + apply nat_meet_powers_neq with (q := 4*q); auto; try lia.\n      Qed.\n\n      Fact const_u1_meet p : p = (u*u) ⇣ w <-> p = u1.\n      Proof using Hu1_w.\n        rewrite Hu1_u2, nat_meet_comm, nat_meet_join_distr_l.\n        do 2 rewrite (nat_meet_comm w).\n        rewrite Hu1_w, Hu2_w, nat_join_n0; tauto.\n      Qed.\n\n      Fact const_u1_eq : (u*u) ⇣ w = u1.\n      Proof using Hu1_w. apply const_u1_meet; auto. Qed.\n\n      Hypothesis Hf : forall i, i < m -> f i = power (S i) 2.\n\n      Let Hu2_1 : u2 = msum nat_join 0 m (fun i => msum nat_join 0 i (fun j => 2*power (f i + f j) r)).\n      Proof.\n        unfold u2.\n        apply double_sum_powers_ortho with (q := 4*q); auto; try lia.\n        intros ? ? ? ? ? ?; repeat rewrite Hf; try lia.\n        intros E.\n        apply sum_2_power_2_injective in E; lia.\n      Qed.\n\n      (* This cannot be proved anymore without stronger hypothesis on f *) \n\n      Let Hu2_2w : u2 ⇣ (2*w) = u2.\n      Proof.\n        apply binary_le_nat_meet.\n        rewrite H2w_1, Hu2_1.\n        apply nat_double_joins_binary_le.\n        intros i j Hij.\n        exists (f i + f j); split; auto.\n        apply Nat.le_lt_trans with (2*f i); auto.\n        + apply Hf2 in Hij; lia.\n        + apply Nat.le_lt_trans with (2 := Hk), Nat.mul_le_mono; auto.\n          apply Hf1; lia.\n      Qed. \n\n      Fact const_u2_meet p : p = (u*u) ⇣ (2*w) <-> p = u2.\n      Proof using Hu1_w Hu2_2w.\n        rewrite Hu1_u2, nat_meet_comm, nat_meet_join_distr_l.\n        do 2 rewrite (nat_meet_comm (2*w)).\n        rewrite Hu1_2w, Hu2_2w, nat_join_0n; tauto.\n      Qed.\n\n    End increase.\n\n    Let Hl'' : 2*l < r.\n    Proof.\n      unfold r.\n      rewrite (Nat.mul_comm _ q), power_mult.\n      change (power 4 2) with 16.\n      apply power_smono_l with (x := 16) in Hlq; try lia.\n      apply Nat.le_lt_trans with (2 := Hlq).\n      rewrite Nat.add_comm; simpl plus; rewrite power_S.\n      apply Nat.mul_le_mono; try lia.\n      apply power_ge_n; lia.\n    Qed.\n\n    Section const_1_cn.\n\n      (* Perhaps you should encode the predicate that \n          \n           w = ∑ {i=0..2^{l+1}} r^i\n           u = ∑ {1..l} r^{2^i} and u1 = u*u ⇣ w\n\n         as diophantine and use that predicate because\n         it is used for Const1 and the product and CodeNat *)\n\n      Variable (u u1 : nat) (Hu  : u = ∑ l (fun i => power (power (S i) 2) r))\n                            (Hu1 : u1 = ∑ l (fun i => power (power (S (S i)) 2) r)).\n \n      Let w  := ∑ (S (power (S l) 2)) (fun i => power i r).\n (*     Let u1 := ∑ l (fun i => power (power (S (S i)) 2) r). *)\n      Let u2 := ∑ l (fun i => ∑ i (fun j => 2*power (power (S i) 2 + power (S j) 2) r)).\n \n      Let H18 : 1+(r-1)*w = power (S (power (S l) 2)) r.\n      Proof. rewrite <- all_ones_dio; auto. Qed.\n\n      Let H19 : u*u = u1 + u2.\n      Proof.\n        rewrite Hu1, Hu. \n        apply const_u_square with (k' := 0) (w := 0); eauto.\n      Qed.\n\n      Let k := S (power (S l) 2).\n      Let f i := power (S i) 2.\n\n      Let Hf1 i : i < l -> 2*f i < k.\n      Proof.\n        unfold k, f.\n        intros; rewrite <- power_S; apply le_n_S, power_mono_l; lia.\n      Qed.\n\n      Let Hf2 i j : i < j < l -> f i < f j.\n      Proof. intros; apply power_smono_l; lia. Qed.\n\n      Let Hf3 i1 j1 i2 j2 : j1 <= i1 < l -> j2 <= i2 < l -> f i1 + f j1 = f i2 + f j2 -> i1 = i2 /\\ j1 = j2.\n      Proof.\n        unfold f; intros H1 H2 E.\n        apply sum_2_power_2_injective in E; lia.\n      Qed.\n\n      Let H20 : u1 = (u*u) ⇣ w.\n      Proof. \n        rewrite const_u1_meet with (k := power l 2) (m := l) (f := f); auto.\n        * intros i Hi; specialize (Hf1 Hi).\n          revert Hf1; unfold k; rewrite power_S; intros; lia.\n        * rewrite <- power_S; auto.\n      Qed. \n\n      Let H21 : u2 = (u*u) ⇣ (2*w).\n      Proof. \n        rewrite const_u2_meet with (k := power l 2) (m := l) (f := f); auto.\n        * intros i Hi; specialize (Hf1 Hi).\n          revert Hf1; unfold k; rewrite power_S; intros; lia.\n        * rewrite <- power_S; auto.\n     Qed. \n \n      Let H22 : power 2 r + u1 = u + power (power (S l) 2) r.\n      Proof.\n        rewrite Hu, Hu1.\n        destruct l.\n        + do 2 rewrite msum_0.\n          rewrite power_1; auto.\n        + rewrite msum_plus1, msum_S; auto.\n          rewrite power_1; ring.\n      Qed.\n  \n      Let H23 : divides (power 4 r) u1.\n      Proof.\n        rewrite Hu1.\n        apply divides_msum.\n        intros i _.\n        apply divides_power.\n        apply (@power_mono_l 2 _ 2); lia.\n      Qed.\n\n      Lemma const1_cn : exists w u2,    1+(r-1)*w = power (S (power (S l) 2)) r\n                                     /\\ u*u = u1 + u2\n                                     /\\ u1 = (u*u) ⇣ w\n                                     /\\ u2 = (u*u) ⇣ (2*w)\n                                     /\\ power 2 r + u1 = u + power (power (S l) 2) r\n                                     /\\ divides (power 4 r) u1.\n      Proof using Hu1 Hu Hr'.\n        exists w, u2; repeat (split; auto).\n      Qed.\n\n    End const_1_cn.\n\n    Section const_1_cs.\n\n      Variable (w u u1 u2 : nat).\n\n      Hypothesis (H18 : 1+(r-1)*w = power (S (power (S l) 2)) r)\n                 (H19 : u*u = u1 + u2)\n                 (H20 : u1 = (u*u) ⇣ w)\n                 (H21 : u2 = (u*u) ⇣ (2*w))\n                 (H22 : power 2 r + u1 = u + power (power (S l) 2) r)\n                 (H23 : divides (power 4 r) u1).\n\n      Let Hw_0 : w = ∑ (S (power (S l) 2)) (fun i => power i r).\n      Proof. apply all_ones_dio; auto. Qed.\n\n      Let Hw_1 : w = ∑ (S (power (S l) 2)) (fun i => 1*power i r).\n      Proof. rewrite Hw_0; apply msum_ext; intros; ring. Qed.\n\n      Let Hw : w = msum nat_join 0 (S (power (S l) 2)) (fun i => 1*power i r).\n      Proof. apply all_ones_joins; auto. Qed.\n\n      Let H2w : 2*w = msum nat_join 0 (S (power (S l) 2)) (fun i => 2*power i r).\n      Proof. apply all_ones_2_joins; auto. Qed.\n    \n      Let Hu1_0 : u1 ≲ ∑ (S (power (S l) 2)) (fun i => 1*power i r).\n      Proof. rewrite H20, <- Hw_1; auto. Qed.\n\n      Local Lemma mk_full : { m : nat & { k | u1 = ∑ (S m) (fun i => power (k i) r) \n                                /\\ m <= power (S l) 2\n                                /\\ (forall i, i < S m -> k i <= power (S l) 2) \n                                /\\ forall i j, i < j < S m -> k i < k j } }.\n      Proof using Hw Hu1_0 H19 H21 H22.\n        assert ({ k : nat &\n                 { g : nat -> nat & \n                 { h | u1 = ∑ k (fun i => g i * power (h i) r)\n                     /\\ k <= S (power (S l) 2)\n                     /\\ (forall i, i < k -> g i <> 0 /\\ g i ≲ 1)\n                     /\\ (forall i, i < k -> h i < S (power (S l) 2))\n                     /\\ (forall i j, i < j < k -> h i < h j) } } }) as H.\n        { apply (@sum_powers_binary_le_inv _ Hq' r eq_refl _ (fun _ => _) (fun i => i)); auto.\n          intros; lia. }\n        destruct H as (m' & g & h & H1 & H2 & H3 & H4 & H5).\n        assert (H6 : forall i, i < m' -> g i = 1).\n        { intros i Hi; generalize (H3 _ Hi).\n          intros (? & G2); apply binary_le_le in G2; lia. }\n        assert (H7 : u1 = ∑ m' (fun i => 1 * power (h i) r)).\n        { rewrite H1; apply msum_ext; intros; rewrite H6; try ring; lia. }\n        assert (H8 : u1 = ∑ m' (fun i => power (h i) r)).\n        { rewrite H7; apply msum_ext; intros; ring. }\n        assert (H9 : m' <> 0).\n        { intros E; rewrite E, msum_0 in H1.\n          assert (power 2 r < power (power (S l) 2) r) as C.\n          { apply power_smono_l; auto.\n            apply (@power_smono_l 1 _ 2); lia. }\n          lia. }\n        destruct m' as [ | m ]; try lia.\n        exists m, h; repeat (split; auto).\n        + lia.\n        + intros i; generalize (H4 i); intros; lia.\n      Qed.\n\n      Let m := projT1 mk_full.\n      Let k := proj1_sig (projT2 mk_full).\n\n      Let Hu1 : u1 = ∑ (S m) (fun i => power (k i) r).        Proof. apply (proj2_sig (projT2 mk_full)). Qed.\n      Let Hm : m <= (power (S l) 2).                          Proof. apply (proj2_sig (projT2 mk_full)). Qed.\n      Let Hk1 : forall i, i < S m -> k i <= power (S l) 2.    Proof. apply (proj2_sig (projT2 mk_full)). Qed.\n      Let Hk2 : forall i j, i < j < S m -> k i < k j.         Proof. apply (proj2_sig (projT2 mk_full)). Qed.\n\n      Let Hh_0 : 4 <= k 0.\n      Proof.\n        rewrite Hu1 in H23.\n        apply power_divides_sum_power in H23; auto; try lia.\n      Qed.\n\n      Let f1 i := match i with 0 => 2 | S i => k i end.\n      Let f2 i := if le_lt_dec i m then power (S l) 2 else k i.\n\n      Let Hf1_0 : forall i, i <= S m -> f1 i < S (power (S l) 2).\n      Proof.\n        intros [ | i ] Hi; simpl; apply le_n_S.\n        + rewrite power_S.\n          change 2 with (2*1) at 1.\n          apply Nat.mul_le_mono; auto.\n          apply power_ge_1; lia.\n        + apply Hk1; auto.\n      Qed.\n\n      Let Hf1_1 : forall i j, i < j <= S m -> f1 i < f1 j.\n      Proof.\n        intros [ | i ] [ | j ] Hij; simpl; try lia.\n        * apply Nat.lt_le_trans with (k 0); try lia.\n          destruct j; auto; apply Nat.lt_le_incl, Hk2; lia.\n        * apply Hk2; lia.\n      Qed.\n\n      Let Hf1_2 : ∑ (S (S m)) (fun i => power (f1 i) r) = u + power (power (S l) 2) r.\n      Proof.\n        rewrite msum_S; unfold f1.\n        rewrite <- Hu1; auto.\n      Qed.\n\n      Let Hh_1 : k m = power (S l) 2.\n      Proof.\n        destruct (le_lt_dec (power (S l) 2) (k m)) as [ H | H ].\n        + apply Nat.le_antisymm; auto.\n        + assert (∑ (S (S m)) (fun i => power (f1 i) r) < power (power (S l) 2) r); try lia.\n          apply sum_powers_inc_lt; auto.\n          - intros [ | i ] Hi; simpl.\n            * apply (@power_smono_l 1 _ 2); lia.\n            * apply Nat.le_lt_trans with (2 := H).\n              destruct (eq_nat_dec i m); subst; auto.\n              apply Nat.lt_le_incl, Hk2; lia.\n          - intros; apply Hf1_1; lia.\n      Qed.\n \n      Let Hu : u = ∑ (S m) (fun i => power (f1 i) r).\n      Proof.\n        rewrite msum_plus1 in Hf1_2; auto.\n        simpl f1 at 2 in Hf1_2.\n        rewrite Hh_1 in Hf1_2.\n        lia.\n      Qed.\n        \n      Let Huu : u*u = ∑ (S m) (fun i => power (2*f1 i) r)\n                    + ∑ (S m) (fun i => ∑ i (fun j => 2*power (f1 i + f1 j) r)).\n      Proof.\n        rewrite Hu, square_sum; f_equal.\n        + apply msum_ext; intros; rewrite <- power_plus; f_equal; lia.\n        + rewrite <- sum_0n_scal_l; apply msum_ext; intros i Hi.\n          rewrite <- sum_0n_scal_l; apply msum_ext; intros j Hj.\n          rewrite power_plus; ring.\n      Qed.\n\n      (* This one should not be that hard given S l < q but to check *)\n\n      Let HSl_q : 2 * S (power (S l) 2) < power (2 * q) 2.\n      Proof.\n        rewrite <- (mult_2_eq_plus q), power_plus.\n        apply Nat.le_lt_trans with (2*power q 2).\n        + apply Nat.mul_le_mono; auto.\n          apply power_smono_l; lia.\n        + assert (power 1 2 < power q 2) as H.\n          { apply power_smono_l; lia. }\n          rewrite power_1 in H.\n          apply Nat.mul_lt_mono_pos_r; lia.\n      Qed.\n  \n      Let Hu1_1 : { d | d <= S m /\\ u1 = ∑ d (fun i => power (2*f1 i) r) }.\n      Proof.\n        destruct const_u1_prefix with (m := S m) (k := power (S l) 2) (k' := S (power (S l) 2))\n           (u := u) (w := w) (f := fun i => f1 i)\n           as (d & H1 & H2); auto.\n        + unfold r.\n          apply Nat.le_lt_trans with (2*S (power (S l) 2)); try lia.\n          apply Nat.le_lt_trans with (power (S (S (S l))) 2).\n          do 4 rewrite power_S.\n          * generalize (@power_ge_1 l 2); intros; lia.\n          * apply power_smono_l; lia.\n        + intros i Hi; generalize (@Hf1_0 i); intros; lia.\n        + intros; apply Hf1_1; lia.\n        + exists d; split; auto.\n          rewrite H20, H2.\n          apply msum_ext; intros; ring.\n      Qed.\n\n      Let Hk_final : k 0 = 4 /\\ forall i, i < m -> k (S i) = 2*k i.\n      Proof.\n        destruct Hu1_1 as (d & Hd1 & E).\n        rewrite Hu1 in E.\n        apply sum_powers_injective in E; auto.\n        + destruct E as (? & E); subst d; split.\n          * rewrite E; try lia; auto.\n          * intros; rewrite E; auto; lia.\n        + intros i j H; specialize (@Hf1_1 i j); intros; lia.\n      Qed.\n\n      Let Hk_is_power i : i <= m -> k i = power (S (S i)) 2.\n      Proof.\n         induction i as [ | i IHi ]; intros Hi.\n         + rewrite (proj1 Hk_final); auto.\n         + rewrite (proj2 Hk_final), IHi, <- power_S; auto; lia.\n      Qed.\n\n      Let Hm_is_l : S m = l.\n      Proof.\n        rewrite Hk_is_power in Hh_1; auto.\n        apply power_2_inj in Hh_1; lia.\n      Qed.\n\n      Fact obtain_u_u1_value :  u  = ∑ l (fun i => power (power (S i) 2) r)\n                             /\\ u1 = ∑ l (fun i => power (power (S (S i)) 2) r).\n      Proof using Hu.\n        split.\n        + rewrite <- Hm_is_l, Hu.\n          apply msum_ext.\n          intros [ | i ]; simpl; auto.\n          intros; rewrite Hk_is_power; auto; lia.\n        + rewrite <- Hm_is_l, Hu1.\n          apply msum_ext.\n          intros [ | i ]; simpl; auto.\n          * rewrite Hk_is_power; auto; lia.\n          * intros; rewrite Hk_is_power; auto; lia.\n      Qed.\n\n    End const_1_cs.\n\n  End const_1.\n\n  Variable (l q : nat).\n\n  Notation r := (power (4*q) 2).\n\n  Definition seqs_of_ones u u1 :=\n                   l+1 < q \n                /\\ u  = ∑ l (fun i => power (power (S i) 2) r)\n                /\\ u1 = ∑ l (fun i => power (power (S (S i)) 2) r).\n\n  (* This lemma shows that seqs_of_ones can be encoded by a diophantine expression *)\n\n  Lemma seqs_of_ones_dio u u1 :\n            seqs_of_ones u u1 \n        <-> l = 0 /\\ u = 0 /\\ u1 = 0 /\\ 2 <= q\n         \\/ 0 < l /\\ l+1 < q\n         /\\ exists u2 w r0 r1 p1 p2,\n                r0 = r \n             /\\ r1+1 = r0\n             /\\ p1 = power (1+l) 2\n             /\\ p2 = power p1 r0\n             /\\ 1+r1*w = r0*p2\n             /\\ u*u = u1 + u2\n             /\\ u1 = (u*u) ⇣ w\n             /\\ u2 = (u*u) ⇣ (2*w)\n             /\\ r0*r0 + u1 = u + p2\n             /\\ divides (r0*r0*r0*r0) u1. \n  Proof.\n    split.\n    + intros (H2 & H3 & H4).\n      destruct (le_lt_dec l 0) as [ H1 | H1 ].\n      - assert (l=0) by lia; subst l.\n        rewrite msum_0 in H3, H4; subst; left; lia.\n      - right; split; auto; split; auto.\n        destruct (const1_cn H1 H2 H3 H4) as (w & u2 & E1 & E2 & E3 & E4 & E5 & E6).\n        exists u2, w, r, (r-1), (power (S l) 2), (power (power (S l) 2) r); repeat (split; auto).\n        * generalize (@power_ge_1 (4*q) 2); intros; lia.\n        * revert E5; rewrite power_S, power_1; auto.\n        * revert E6; do 3 rewrite power_S; rewrite power_1.\n          repeat rewrite Nat.mul_assoc; auto.\n    + intros [ (H1 & H2 & H3 & H4)\n             | (H1 & H2 & u2 & w & r0 & r1 & p1 & p2 & ? & H0 & ? & ? & E1 & E2 & E3 & E4 & E5 & E6) ].\n      - red; subst; do 2 rewrite msum_0; lia.\n      - assert (r1 = r0-1) by lia; clear H0.\n        subst r0 r1 p1 p2; split; auto.\n        apply obtain_u_u1_value with w u2; auto.\n        * rewrite power_S, power_1; auto.\n        * do 3 rewrite power_S; rewrite power_1.\n          repeat rewrite Nat.mul_assoc; auto.\n  Qed.\n\n  Definition is_cipher_of f a :=\n                 l+1 < q\n              /\\ (forall i, i < l -> f i < power q 2)\n              /\\ a = ∑ l (fun i => f i * power (power (S i) 2) r).\n\n  Fact is_cipher_of_0 f a : l = 0 -> is_cipher_of f a <-> 1 < q /\\ a = 0.\n  Proof.\n    intros ?; unfold is_cipher_of; subst l.\n    rewrite msum_0; simpl.\n    repeat (split; try tauto).\n    intros; lia.\n  Qed.\n\n  Fact is_cipher_of_inj f1 f2 a : is_cipher_of f1 a -> is_cipher_of f2 a -> forall i, i < l -> f1 i = f2 i.\n  Proof.\n    intros (H1 & H2 & H3) (_ & H4 & H5).\n    rewrite H3 in H5.\n    revert H5; apply power_decomp_unique.\n    + apply (@power_mono_l 1 _ 2); lia.\n    + intros; apply power_smono_l; lia.\n    + intros i Hi; apply Nat.lt_le_trans with (1 := H2 _ Hi), power_mono_l; lia.\n    + intros i Hi; apply Nat.lt_le_trans with (1 := H4 _ Hi), power_mono_l; lia.\n  Qed.\n\n  Fact is_cipher_of_fun f1 f2 a b : \n          (forall i, i < l -> f1 i = f2 i)\n        -> is_cipher_of f1 a \n        -> is_cipher_of f2 b\n        -> a = b.\n  Proof.\n    intros H1 (_ & _ & H2) (_ & _ & H3); subst a b.\n    apply msum_ext; intros; f_equal; auto.\n  Qed.\n\n  Lemma is_cipher_of_equiv f1 f2 a b : \n           is_cipher_of f1 a \n        -> is_cipher_of f2 b\n        -> a = b <-> forall i, i < l -> f1 i = f2 i.\n  Proof.\n    intros Ha Hb; split.\n    + intro; subst; revert Ha Hb; apply is_cipher_of_inj.\n    + intro; revert Ha Hb; apply is_cipher_of_fun; auto.\n  Qed.\n\n  Lemma is_cipher_of_const_1 u : 0 < l -> is_cipher_of (fun _ => 1) u\n                                     <-> l+1 < q /\\ exists u1, seqs_of_ones u u1.\n  Proof.\n    intros Hl.\n    split.\n    + intros (H1 & H2 & H3); split; auto.\n      exists (∑ l (fun i => power (power (S (S i)) 2) r)).\n      rewrite H3; split; auto; split; auto.\n      apply msum_ext; intros; ring.\n    + intros (H1 & u1 & _ & H2).\n      apply proj1 in H2.\n      repeat (split; auto).\n      * intros; apply (@power_smono_l 0); lia.\n      * rewrite H2; apply msum_ext; intros; ring.\n  Qed.\n\n  Fact is_cipher_of_u : l+1 < q -> is_cipher_of (fun _ => 1) (∑ l (fun i => power (power (S i) 2) r)).\n  Proof.\n    intros H; split; auto; split.\n    + intros; apply (@power_mono_l 1 _ 2); lia.\n    + apply msum_ext; intros; lia.\n  Qed.\n (*\n  Fact is_cipher_of_u1 : l+1 < q -> is_cipher_of (fun _ => 1) (∑ l (fun i => power (power (S (S i)) 2) r)).\n  Proof.\n    intros H; split; auto; split.\n    + intros; apply (@power_mono_l 1 _ 2); lia.\n    + apply msum_ext; intros; lia.\n  Qed.\n *)\n\n  Definition the_cipher f : l+1 < q -> (forall i, i < l -> f i < power q 2) -> { c | is_cipher_of f c }.\n  Proof.\n    intros H1 H2.\n    exists (∑ l (fun i => f i * power (power (S i) 2) r)); split; auto.\n  Qed.\n\n  Definition Code a := exists f, is_cipher_of f a.\n\n  Lemma Code_dio a : Code a <-> l = 0 /\\ 1 < q /\\ a = 0\n                             \\/ 0 < l /\\ l+1 < q /\\ exists p u u1, p+1 = power q 2 /\\ seqs_of_ones u u1 /\\ a ≲ p*u.\n  Proof.\n    split.\n    + intros (f & H1 & H2 & H3).\n      destruct (eq_nat_dec l 0) as [ Hl | Hl ].\n      * left; subst l; rewrite msum_0 in H3; lia.\n      * right; split; try lia; split; auto.\n        exists (power q 2-1), (∑ l (fun i => power (power (S i) 2) r)), (∑ l (fun i => power (power (S (S i)) 2) r)).\n        repeat (split; auto).\n        - generalize (@power_ge_1 q 2); intros; lia.\n        - rewrite H3.\n          apply sum_power_binary_lt with (q := 4*q); auto; try lia.\n          intros; apply power_smono_l; lia.\n    + intros [ (H1 & H2 & H3) | (H1 & H2 & p & u1 & u2 & ? & H3 & H4) ].\n      * exists (fun _ => 0); subst a; apply is_cipher_of_0; auto.\n      * destruct H3 as (_ & H3 & _).\n        assert (p = power q 2 -1) by lia; subst p.\n        rewrite H3 in H4. \n        apply sum_power_binary_lt_inv with (q := 4*q) (e := fun i => power (S i) 2) in H4; auto; try lia.\n        2,3: intros; apply power_smono_l; lia.\n        destruct H4 as (f & H4 & H5).\n        exists f; split; auto.\n  Qed.\n\n  Definition Const c v := exists f, is_cipher_of f v /\\ forall i, i < l -> f i = c.\n\n  Lemma Const_dio c v : Const c v <-> l = 0 /\\ 1 < q /\\ v = 0\n                                   \\/ 0 < l /\\ l+1 < q /\\\n                                      exists p u u1, p = power q 2 /\\ c < p /\\ seqs_of_ones u u1 /\\ v = c*u.\n  Proof.\n    split.\n    + intros (f & (H1 & H2 & H3) & H4).\n      destruct (eq_nat_dec l 0) as [ Hl | Hl ].\n      * left; subst l; rewrite msum_0 in H3; lia.\n      * right; split; try lia; split; auto.\n        exists (power q 2), (∑ l (fun i => power (power (S i) 2) r)), (∑ l (fun i => power (power (S (S i)) 2) r)).\n        repeat (split; auto).\n        - rewrite <- (H4 0); try lia; apply H2; lia.\n        - rewrite H3, <- sum_0n_scal_l; apply msum_ext.\n          intros; f_equal; auto.\n    + intros [ (H1 & H2 & H3) | (H1 & H2 & p & u1 & u2 & ? & H3 & H4 & H5) ].\n      * exists (fun _ => 0); subst v; split.\n        - apply is_cipher_of_0; auto.\n        - subst l; intros; lia.\n      * destruct H4 as (_ & H4 & _).\n        rewrite H4, <- sum_0n_scal_l in H5.\n        exists (fun _ => c); split; auto.\n        split; auto; split; auto.\n        intros; lia.\n  Qed.\n\n  Let Hr : 1 < q -> 4 <= r. \n  Proof.\n    intros H.\n    replace (4*q) with (2*q+2*q) by lia.\n    rewrite power_plus.\n    change 4 with ((power 1 2)*(power 1 2)); apply Nat.mul_le_mono;\n    apply power_mono_l; try lia.\n  Qed.\n\n  Section plus.\n\n    Variable (a b c : nat-> nat) (ca cb cc : nat) \n             (Ha : is_cipher_of a ca)\n             (Hb : is_cipher_of b cb) \n             (Hc : is_cipher_of c cc).\n\n    Definition Code_plus := ca = cb + cc.\n \n    Lemma Code_plus_spec : Code_plus <-> forall i, i < l -> a i = b i + c i.\n    Proof using Ha Hb Hc.\n      symmetry; unfold Code_plus.\n      destruct Ha as (H & Ha1 & Ha2).\n      destruct Hb as (_ & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      destruct (eq_nat_dec l 0) as [ | Hl ].\n      + clear Hc Hb Ha. subst l; rewrite msum_0 in *; split; intros; lia.\n      + rewrite Hc2, Ha2, Hb2, <- sum_0n_distr_in_out.\n        split.\n        * intros; apply msum_ext; intros; f_equal; auto.\n        * intros E i Hi. \n          apply power_decomp_unique with (i := i) in E; auto; try lia; clear i Hi.\n          - intros; apply power_smono_l; lia.\n          - intros i Hi; apply Nat.lt_le_trans with (1 := Ha1 _ Hi), power_mono_l; lia.\n          - intros i Hi.\n            apply Nat.lt_le_trans with (power (S q) 2).\n            ++ rewrite power_S, <- mult_2_eq_plus.\n               generalize (Hb1 _ Hi) (Hc1 _ Hi); lia.\n            ++ apply power_mono_l; lia.\n    Qed.\n\n  End plus.\n\n  Notation u := (∑ l (fun i => power (power (S i) 2) r)).\n  Notation u1 := (∑ l (fun i => power (power (S (S i)) 2) r)).\n\n  Section mult_utils.\n \n    Variable (b c : nat-> nat) (cb cc : nat) \n             (Hb : is_cipher_of b cb) \n             (Hc : is_cipher_of c cc).\n\n    Let eq1 :    cb*cc = ∑ l (fun i => (b i*c i)*power (power (S (S i)) 2) r)\n                       + ∑ l (fun i => ∑ i (fun j => (b i*c j + b j*c i)*power (power (S i) 2 + power (S j) 2) r)).\n    Proof.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      rewrite Hb2, Hc2, product_sums; f_equal.\n      * apply msum_ext; intros; rewrite (power_S (S _)).\n        rewrite <- (mult_2_eq_plus (power _ _)), power_plus; ring.\n      * apply msum_ext; intros i Hi.\n        apply msum_ext; intros j Hj.\n        rewrite power_plus; ring.\n    Qed.\n\n    Let Hbc_1 i : i < l -> b i * c i < r.\n    Proof.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      intro; apply mult_lt_power_2_4; auto.\n    Qed.\n  \n    Let Hbc_2 i j : i < l -> j < l -> b i * c j + b j * c i < r.\n    Proof.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      intros; apply mult_lt_power_2_4'; auto.\n    Qed.\n\n    Let Hbc_3 : ∑ l (fun i => (b i*c i)*power (power (S (S i)) 2) r) \n              = msum nat_join 0 l (fun i => (b i*c i)*power (power (S (S i)) 2) r).\n    Proof.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      apply sum_powers_ortho with (q := 4*q); try lia; auto.\n      intros ? ? ? ? E; apply power_2_inj in E; lia.\n    Qed.\n\n    Let Hbc_4 : ∑ l (fun i => ∑ i (fun j => (b i*c j + b j*c i)*power (power (S i) 2 + power (S j) 2) r))\n              = msum nat_join 0 l (fun i => \n                           msum nat_join 0 i (fun j => (b i*c j + b j*c i)*power (power (S i) 2 + power (S j) 2) r)).\n    Proof.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      rewrite double_sum_powers_ortho with (q := 4*q); auto; try lia.\n      + intros; apply Hbc_2; lia.\n      + intros ? ? ? ? ? ? E; apply sum_2_power_2_injective in E; lia.\n    Qed.\n    \n    Let eq2 :   cb*cc = msum nat_join 0 l (fun i => (b i*c i)*power (power (S (S i)) 2) r)\n                      ⇡ msum nat_join 0 l (fun i => \n                           msum nat_join 0 i (fun j => (b i*c j + b j*c i)*power (power (S i) 2 + power (S j) 2) r)).\n    Proof.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      rewrite eq1, Hbc_3, Hbc_4.\n      apply nat_ortho_plus_join.\n      apply nat_ortho_joins.\n      intros i j Hi Hj; apply nat_ortho_joins_left.\n      intros k Hk.\n      apply nat_meet_powers_neq with (q := 4*q); auto; try lia.\n      * apply power_2_n_ij_neq; lia.\n      * apply Hbc_2; lia.\n    Qed.\n\n    Let Hr_1 : (r-1)*u1 = ∑ l (fun i => (r-1)*power (power (S (S i)) 2) r).\n    Proof. rewrite sum_0n_scal_l; auto. Qed.\n\n    Let Hr_2 : (r-1)*u1 = msum nat_join 0 l (fun i => (r-1)*power (power (S (S i)) 2) r).\n    Proof.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      rewrite Hr_1.\n      apply sum_powers_ortho with (q := 4*q); auto; try lia.\n      intros ? ? ? ? E; apply power_2_inj in E; lia.\n    Qed.\n   \n    Fact cipher_mult_eq : (cb*cc)⇣((r-1)*u1) = ∑ l (fun i => (b i*c i)*power (power (S (S i)) 2) r).\n    Proof using Hb Hc.\n      destruct Hb as (H1 & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      rewrite eq2, Hbc_3, Hr_2.\n      rewrite nat_meet_comm, nat_meet_join_distr_l.\n      rewrite <- Hr_2 at 1; rewrite Hr_1, <- Hbc_3.\n      rewrite meet_sum_powers with (q := 4*q); auto; try (intros; lia).\n      2: intros; apply power_smono_l; lia.\n      rewrite (proj2 (nat_ortho_joins _ _ _ _)), nat_join_n0.\n      * apply msum_ext; intros i Hi; f_equal.\n        rewrite nat_meet_comm; apply binary_le_nat_meet, power_2_minus_1_gt; auto.\n      * intros i j Hi Hj.\n        apply nat_ortho_joins_left.\n        intros k Hk; apply nat_meet_powers_neq with (q := 4*q); auto; try lia.\n        + apply power_2_n_ij_neq; lia.\n        + apply Hbc_2; lia.\n    Qed.\n\n  End mult_utils.\n  \n  Section mult.\n\n    Variable (a b c : nat-> nat) (ca cb cc : nat) \n             (Ha : is_cipher_of a ca)\n             (Hb : is_cipher_of b cb) \n             (Hc : is_cipher_of c cc).\n\n    Definition Code_mult := \n                l = 0 \n             \\/ l <> 0 \n             /\\ exists v v1 r' r'' p, \n                        r'' = r \n                     /\\ r'' = r'+1 \n                     /\\ seqs_of_ones v v1 \n                     /\\ p = (ca*v)⇣(r'*v1) \n                     /\\ p = (cb*cc)⇣(r'*v1).\n\n    Lemma Code_mult_spec : Code_mult <-> forall i, i < l -> a i = b i * c i. \n    Proof using Ha Hb Hc.\n      unfold Code_mult; symmetry.\n      destruct Ha as (Hlq & Ha1 & Ha2).\n      destruct Hb as (_ & Hb1 & Hb2).\n      destruct Hc as (_ & Hc1 & Hc2).\n      destruct (eq_nat_dec l 0) as [ | Hl ].\n      + rewrite e in *; split; intros; auto; lia.\n      + split.\n        * intros H; right; split; try lia.\n          exists u, u1, (r-1), r, (ca * u ⇣ ((r-1) * u1)).\n          split; auto; split; try lia.\n          repeat (split; auto).\n          generalize (is_cipher_of_u Hlq); intros H2.\n          rewrite cipher_mult_eq with (1 := Ha) (2 := H2).\n          rewrite cipher_mult_eq with (1 := Hb) (2 := Hc).\n          apply msum_ext; intros; rewrite H; try ring; lia.\n        * intros [ | (_ & v & v1 & r' & r'' & p & H0 & H1 & H2 & H3 & H4) ]; try (destruct Hl; auto; fail).\n          destruct H2 as (_ & ? & ?); subst v v1.\n          rewrite H3 in H4.\n          revert H4.\n          generalize (is_cipher_of_u Hlq); intros H2.\n          replace r' with (r-1) by lia.\n          rewrite cipher_mult_eq with (1 := Ha) (2 := H2).\n          rewrite cipher_mult_eq with (1 := Hb) (2 := Hc).\n          intros E.\n          intros i Hi. \n          rewrite <- power_decomp_unique with (5 := E); auto; try lia.\n          - intros; apply power_smono_l; lia.\n          - intros j Hj; rewrite Nat.mul_1_r.\n            apply Nat.lt_le_trans with (1 := Ha1 _ Hj), power_mono_l; lia.\n          - intros; apply mult_lt_power_2_4; auto.\n    Qed.\n\n  End mult.\n\n  Section inc_seq.\n\n    Definition CodeNat c := is_cipher_of (fun i => i) c.\n\n    Local Lemma IncSeq_dio_priv y : CodeNat y <-> l = 0 /\\ 1 < q /\\ y = 0 \n                                  \\/ 0 < l \n                                  /\\ exists z v v1, \n                                        seqs_of_ones v v1 \n                                     /\\ Code y\n                                     /\\ Code z\n                                     /\\ y + l*(power (power (S l) 2) r) = (z*v)⇣((r-1) * v1)\n                                     /\\ y+v1+power (power 1 2) r = z + power (power (S l) 2) r.\n    Proof.\n      split.\n      + intros (H1 & H2 & H3).\n        destruct (le_lt_dec l 0) as [ | Hl ].\n        - assert (l = 0) as -> by lia.\n          rewrite msum_0 in H3; left; lia.\n        - right; split; auto.\n          exists (∑ l (fun i => (S i) * power (power (S i) 2) r)), u, u1; split; auto.\n          { split; auto. }\n          split.\n          { rewrite H3; exists (fun i => i); split; auto. }\n          split.\n          { exists S; repeat (split; auto).\n            intros; apply Nat.lt_le_trans with q; try lia.\n            apply power_ge_n; auto. }\n          split.\n          { rewrite cipher_mult_eq with (b := S) (c := fun _ => 1).\n            * rewrite H3.\n              rewrite <- msum_plus1 with (f := fun i => i*power (power (S i) 2) r); auto.\n              rewrite msum_S, Nat.mul_0_l, Nat.add_0_l.\n              apply msum_ext; intros; ring.\n            * repeat split; auto; intros.\n              apply Nat.lt_le_trans with q; try lia.\n              apply power_ge_n; auto.\n            * apply is_cipher_of_u; auto. }\n          { rewrite H3.\n            destruct l as [ | l' ]; try lia.\n            rewrite msum_S, Nat.mul_0_l, Nat.add_0_l.\n            rewrite msum_plus1; auto.\n            rewrite Nat.add_assoc.\n            rewrite msum_S.\n            rewrite <- msum_sum; auto.\n            2: intros; ring.\n            rewrite Nat.mul_1_l, Nat.add_comm.\n            repeat rewrite <- Nat.add_assoc; do 2 f_equal.\n            apply msum_ext; intros; ring. }\n      + intros [ (H1 & H2 & H3) | (Hl & z & v & v1 & H1 & H2 & H3 & H4 & H5) ].\n        - split; subst; auto; split; intros; try lia.\n          rewrite msum_0; auto.\n        - destruct H1 as (Hq & ? & ?); subst v v1.\n          split; auto; split.\n          { intros i Hi; apply Nat.lt_le_trans with q; try lia.\n            apply power_ge_n; auto. }\n          destruct H2 as (f & Hf).\n          destruct H3 as (g & Hg).\n          generalize (is_cipher_of_u Hq); intros Hu.\n          rewrite cipher_mult_eq with (1 := Hg) (2 := Hu) in H4.\n          destruct Hf as (_ & Hf & Hy).\n          destruct Hg as (_ & Hg & Hz).\n          set (h i := if le_lt_dec l i then l else f i).\n          assert (y+l*power (power (S l) 2) r = ∑ (S l) (fun i => h i * power (power (S i) 2) r)) as H6.\n          { rewrite msum_plus1; auto; f_equal.\n            * rewrite Hy; apply msum_ext.\n              intros i Hi; unfold h.\n              destruct (le_lt_dec l i); try lia.\n            * unfold h.\n              destruct (le_lt_dec l l); try lia. }\n          rewrite H4 in H6.\n          set (g' i := match i with 0 => 0 | S i => g i end).\n          assert ( ∑ (S l) (fun i => g' i * power (power (S i) 2) r)\n                 = ∑ l (fun i : nat => g i * 1 * power (power (S (S i)) 2) r)) as H7.\n          { unfold g'; rewrite msum_S; apply msum_ext; intros; ring. }\n          rewrite <- H7 in H6.\n          assert (forall i, i < S l -> g' i = h i) as H8.\n          { apply power_decomp_unique with (5 := H6); try lia. \n            * intros; apply power_smono_l; lia. \n            * unfold g'; intros [ | i ] Hi; try lia.\n              apply Nat.succ_lt_mono in Hi.\n              apply Nat.lt_le_trans with (1 := Hg _ Hi), power_mono_l; lia.\n            * intros i Hi; unfold h.\n              destruct (le_lt_dec l i) as [ | Hi' ].\n              + apply Nat.lt_le_trans with (4*q); try lia.\n                apply power_ge_n; auto.\n              + apply Nat.lt_le_trans with (1 := Hf _ Hi'), power_mono_l; lia.  }\n          assert (h 0 = 0) as E0.\n          { rewrite <- H8; simpl; lia. }\n          assert (forall i, i < l -> h (S i) = g i) as E1.\n          { intros i Hi; rewrite <- H8; simpl; lia. }\n          assert (f 0 = 0) as E3.\n          { unfold h in E0; destruct (le_lt_dec l 0); auto; lia. }\n          assert (forall i, S i < l -> f (S i) = g i) as E4.\n          { intros i Hi; specialize (E1 i); unfold h in E1.\n            destruct (le_lt_dec l (S i)); lia. }\n          assert (g (l-1) = l) as E5.\n          { specialize (E1 (l-1)); unfold h in E1.\n            destruct (le_lt_dec l (S (l-1))); lia. }  \n          clear H6 H7 g' H8 E0 E1 h H4.\n          assert (y + u1 + power (power 1 2) r = \n                  ∑ l (fun i => (1+f i) * power (power (S i) 2) r)\n                + power (power (S l) 2) r) as E1.\n          { rewrite sum_0n_distr_in_out.\n            rewrite <- Hy, sum_0n_scal_l, Nat.mul_1_l.\n            destruct l as [ | l' ]; try lia.\n            rewrite msum_plus1; auto.\n            rewrite msum_S; ring. }\n          assert (forall i, i < l -> 1+f i = g i) as E2.\n          { apply power_decomp_unique with (f := fun i => power (S i) 2) (p := r); try lia.\n            + intros; apply power_smono_l; lia.\n            + intros i Hi; apply Nat.le_lt_trans with (power q 2); auto.\n              * apply Hf; auto.\n              * apply power_smono_l; lia. \n            + intros i Hi; apply Nat.lt_le_trans with (1 := Hg _ Hi), power_mono_l; lia. } \n          rewrite Hy; apply msum_ext.\n          clear Hy Hf Hg Hz H5 E5 E1 Hu.\n          intros i Hi; f_equal; revert i Hi.\n          induction i as [ | i IHi ]; intros Hi; auto.\n          rewrite E4, <- E2; try lia.\n    Qed.\n\n    Lemma CodeNat_dio y : CodeNat y <-> l = 0 /\\ 1 < q /\\ y = 0 \n                                  \\/ 0 < l \n                                  /\\ exists z v v1 p0 p1 p2 r1,\n                                        p0 = r\n                                     /\\ r1+1 = p0 \n                                     /\\ p1 = power (1+l) 2\n                                     /\\ p2 = power p1 p0 \n                                     /\\ seqs_of_ones v v1 \n                                     /\\ Code y\n                                     /\\ Code z\n                                     /\\ y + l*p2 = (z*v) ⇣ (r1 * v1)\n                                     /\\ y + v1 + p0*p0 = z + p2.\n    Proof.\n      rewrite IncSeq_dio_priv; split; (intros [ H | H ]; [ left | right ]); auto; revert H;\n        intros (H1 & H); split; auto; clear H1; revert H.\n      + intros (z & v & v1 & H1 & H2 & H3 & H4 & H5).\n        exists z, v, v1, r, (power (S l) 2), (power (power (S l) 2) r), (r-1); repeat (split; auto).\n        * destruct H1; lia.\n        * rewrite <- H5; f_equal.\n          rewrite power_1, power_S, power_1; auto.\n      + intros (z & v & v1 & p0 & p1 & p2 & r1 & H1 & H2 & H3 & H4 & H5 & H6 & H7 & H8 & H9).\n        assert (r1 = r - 1) by lia; clear H2; subst.\n        exists z, v, v1; repeat (split; auto).\n        simpl in H9 |- *; rewrite <- H9; f_equal.\n        rewrite power_1, power_S, power_1; auto.\n    Qed.\n      \n  End inc_seq.\n\nEnd sums.  \n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/H10/Matija/cipher.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6565761151316739}}
{"text": "Require Export pv_in is_pos is_neg occ_in_modal.\nRequire Import Compare_dec Lia.\nRequire Import ltac_gen.\n\n(* is_pos lemmas *)\n\nLemma is_pos_occ : forall (phi : Modal) (i : nat),\n  is_pos phi i -> occ_in_modal phi i.\nProof.\n  intros phi i Hpos. inversion Hpos. assumption.\nQed.\n\nLemma is_pos_notin : forall (phi : Modal) (i : nat),\n  is_pos phi i  -> le i (length (pv_in phi)).\nProof.\n  intros phi i H. inversion H.\n  apply occ_in_modal_le. auto.\nQed.\n\nLemma is_pos_atom : forall (q : propvar) (i : nat),\n  is_pos (atom q) i -> i = 1. \nProof.\n  intros q i [[H1 H3] H2]. simpl in *.\n  firstorder.\nQed.\n\nLemma is_pos_mneg : forall (psi : Modal) (i : nat),\n  is_pos (mneg psi) i -> ~ (is_pos psi i) .\nProof.\n  intros psi i [H1 H2] [H3 H4].\n  simpl in H2. destruct (is_pos_pre psi i);\n  discriminate.\nQed.\n\nLemma is_pos_mneg2 : forall (psi : Modal) (i : nat),\n  ~ is_pos psi i ->\n    occ_in_modal psi i ->\n      is_pos (mneg psi) i.\nProof.\n  intros phi i Hpos Hocc. constructor. apply occ_in_modal_mneg. auto.\n  simpl. case_eq (is_pos_pre phi i); intros Hpos2.\n  pose proof (occ_pos _ _ Hocc Hpos2). auto.\n  reflexivity.\nQed.\n\nLemma is_pos_mconj_l : forall (phi1 phi2 : Modal) (i : nat),\n  is_pos (mconj phi1 phi2) i ->\n    ( occ_in_modal phi1 i -> is_pos phi1 i).\nProof.\n  intros phi1 phi2 i [H1 H2] Hocc.\n  simpl in H2. constructor. auto.\n  apply occ_in_modal_le in Hocc. \n  if_then_else_dest_blind; auto.\nQed.\n\nLemma is_pos_mconj_r : forall (phi1 phi2 : Modal) (i : nat),\n  is_pos (mconj phi1 phi2) i ->\n    (le (length (pv_in phi1) + 1) i) ->\n      is_pos phi2 (i - (length (pv_in phi1))).\nProof.\n  intros phi1 phi2 i [H1 H2] Hocc.\n  simpl in H2.\n  if_then_else_dest_blind; auto. firstorder.\n  constructor; auto.\n  inversion H1 as [H3 H4].\n  constructor. simpl in *. rewrite app_length in H4.\n  intros H. firstorder. \n  simpl in H4. rewrite app_length in H4.\n  firstorder.\nQed.\n\nLemma is_pos_mdisj_l : forall (phi1 phi2 : Modal) (i : nat),\n  is_pos (mdisj phi1 phi2) i ->\n  ( occ_in_modal phi1 i ->  (is_pos phi1 i)).\nProof.\n  intros phi1 phi2 i [H1 H2] Hocc.\n  simpl in H2. constructor. auto.\n  apply occ_in_modal_le in Hocc.\n  if_then_else_dest_blind; auto.\nQed.\n\nLemma is_pos_mdisj_r : forall (phi1 phi2 : Modal) (i : nat),\n  is_pos (mdisj phi1 phi2) i ->\n    ((length (pv_in phi1) + 1) <= i) ->\n      is_pos phi2 (i - (length (pv_in phi1))).\nProof.\n  intros phi1 phi2 i [H1 H2] Hocc.\n  simpl in H2.\n  if_then_else_dest_blind; auto. firstorder.\n  constructor; auto.\n  inversion H1 as [H3 H4].\n  constructor. simpl in *. rewrite app_length in H4.\n  intros H. firstorder. \n  simpl in H4. rewrite app_length in H4.\n  firstorder.\nQed.\n\nLemma is_pos_mconj : forall (phi1 phi2 : Modal) (i : nat),\n  is_pos (mconj phi1 phi2) i ->\n    ( occ_in_modal phi1 i ->  (is_pos phi1 i)) /\\\n    ((le (length (pv_in phi1) + 1) i) ->\n       is_pos phi2 (i - (length (pv_in phi1)))).\nProof.\n  intros phi1 phi2 i Hpos.\n  pose proof is_pos_mconj_l.\n  pose proof is_pos_mconj_r.\n  firstorder.\nQed.\n\nLemma is_pos_mdisj : forall (phi1 phi2 : Modal) (i : nat),\n  is_pos (mdisj phi1 phi2) i ->\n    ( occ_in_modal phi1 i ->  (is_pos phi1 i)) /\\\n    (( (length (pv_in phi1) + 1) <= i) ->\n       is_pos phi2 (i - (length (pv_in phi1)))).\nProof.\n  intros phi1 phi2 i Hpos.\n  pose proof is_pos_mconj_l.\n  pose proof is_pos_mconj_r.\n  firstorder.\nQed.\n\nLemma is_pos_box : forall (phi : Modal) (i : nat),\n  is_pos (box phi) i <-> is_pos phi i.\nProof.\n  split; intros [H1 H2];\n    (constructor; [apply occ_in_modal_box|]; auto).\nQed.\n\nLemma is_pos_dia : forall (phi : Modal) (i : nat),\n  is_pos (dia phi) i <-> is_pos phi i.\nProof.\n  split; intros [H1 H2];\n    (constructor; [apply occ_in_modal_dia|]; auto).\nQed.\n\n(* ------------------------------------------------------------ *)\n\n(* is_neg lemmas *)\n\nLemma is_neg_occ : forall (phi : Modal) (i : nat),\n    is_neg phi i -> occ_in_modal phi i.\nProof.\n  intros phi i Hpos. inversion Hpos. assumption.\nQed.\n\nLemma is_neg_mneg : forall (psi : Modal) (i : nat),\n  is_neg (mneg psi) i -> ~(is_neg psi i).\nProof.\n  intros psi i [H1 H2] [H3 H4].\n  simpl in H2. destruct (is_neg_pre psi i);\n  discriminate.\nQed.\n\nLemma is_neg_mneg2 : forall (psi : Modal) (i : nat),\n  ~ is_neg psi i ->\n    occ_in_modal psi i ->\n      is_neg (mneg psi) i.\nProof.\n  intros phi i Hpos Hocc. constructor. apply occ_in_modal_mneg. auto.\n  simpl. case_eq (is_neg_pre phi i); intros Hpos2.\n  pose proof (occ_neg _ _ Hocc Hpos2). auto.\n  reflexivity.\nQed.\n\nLemma is_neg_box : forall (phi : Modal) (i : nat),\n    is_neg (box phi) i <-> is_neg phi i.\nProof.\n  split; intros [H1 H2];\n    (constructor; [apply occ_in_modal_box|]; auto).\nQed.\n\nLemma is_neg_dia: forall (phi : Modal) (i : nat),\n    is_neg (dia phi) i <-> is_neg phi i.\nProof.\n  split; intros [H1 H2];\n    (constructor; [apply occ_in_modal_dia|]; auto).\nQed.\n\nLemma is_neg_0 : forall (phi : Modal),\n  ~ is_neg phi 0.\nProof. intros phi [H1 H2]. firstorder. Qed.\n\n(* --------------------------------------------------------------- *)\n\nLemma is_pos_atom2 : forall p,\n    is_pos #p 1.\nProof.\n  intros p. constructor. apply occ_in_modal_atom2.\n  auto.\nQed.\n\nLemma is_pos_neg_pre_not_tf: forall phi i,\n    occ_in_modal phi i ->\n    ~ (is_pos_pre phi i = true /\\ is_neg_pre phi i = true) /\\\n    ~ (is_pos_pre phi i = false /\\ is_neg_pre phi i = false).\nProof.\n  induction phi; intros i Hocc.\n  - apply occ_in_modal_atom in Hocc. subst. simpl.\n    apply conj; intros [H1 H2]; discriminate.\n  - apply (occ_in_modal_mneg phi) in Hocc. simpl.\n    destruct (IHphi i Hocc) as [H1 H2].\n    destruct (is_pos_pre phi i); destruct (is_neg_pre phi i);\n      firstorder.\n  - destruct (occ_in_modal_dec phi1 i) as [Hocc1 | Hocc1].\n    pose proof (IHphi1 _ Hocc1) as Hocc2. destruct Hocc2 as [H1 H2].\n    inversion Hocc1 as [H3 H4]. \n    simpl. if_then_else_dest_blind; auto. \n    apply occ_in_modal_mconj in Hocc. simpl.\n    apply occ_in_modal_f in Hocc1. destruct Hocc1 as [H1 | H1].\n    subst. inversion Hocc. contradiction.\n    if_then_else_dest_blind; auto; firstorder. auto.\n  - destruct (occ_in_modal_dec phi1 i) as [Hocc1 | Hocc1].\n    pose proof (IHphi1 _ Hocc1) as Hocc2. destruct Hocc2 as [H1 H2].\n    inversion Hocc1 as [H3 H4]. \n    simpl. if_then_else_dest_blind; auto. \n    apply occ_in_modal_mdisj in Hocc. simpl.\n    apply occ_in_modal_f in Hocc1. destruct Hocc1 as [H1 | H1].\n    subst. inversion Hocc. contradiction.\n    if_then_else_dest_blind; auto; firstorder. auto.\n  - destruct (occ_in_modal_dec phi1 i) as [Hocc1 | Hocc1].\n    pose proof (IHphi1 _ Hocc1) as Hocc2. destruct Hocc2 as [H1 H2].\n    inversion Hocc1 as [H3 H4].\n    simpl. unfold negb. \n    if_then_else_dest_blind; auto; firstorder.\n    apply occ_in_modal_f in Hocc1. destruct Hocc1 as [H1 | H1].\n    subst. inversion Hocc. contradiction.\n    apply Gt.gt_not_le in H1. simpl.\n    if_then_else_dest_blind; auto.\n    assert (occ_in_modal phi2 (i - length (pv_in phi1))).\n      inversion Hocc. simpl in *. rewrite app_length in *. \n      constructor; firstorder.\n    apply conj; apply IHphi2; auto.\n  - simpl. apply IHphi. apply occ_in_modal_box. auto.\n  - simpl. apply IHphi. apply occ_in_modal_dia. auto.\nQed.\n\nLemma is_pos_neg_pre_not_t: forall phi i,\n    occ_in_modal phi i ->\n    ~ (is_pos_pre phi i = true /\\ is_neg_pre phi i = true).\nProof.\n  intros phi i Hocc. apply is_pos_neg_pre_not_tf. auto.\nQed.\n  \nLemma is_pos_neg_pre_not_f: forall phi i,\n    occ_in_modal phi i ->\n    ~ (is_pos_pre phi i = false /\\ is_neg_pre phi i = false).\nProof.\n  intros phi i Hocc. apply is_pos_neg_pre_not_tf. auto.\nQed. \n\nLemma is_pos_neg_not: forall phi i,\n    ~ (is_pos phi i /\\ is_neg phi i).\nProof.\n  intros phi i [[H1 H2] [H4 H3]].\n  apply (is_pos_neg_pre_not_t phi i); auto.\nQed.\n\nLemma is_pos_mconj_l2 : forall phi1 phi2 i,\n    is_pos phi1 i ->\n    is_pos (phi1 m∧ phi2) i.\nProof.\n  intros phi1 phi2 i [H1 H2].\n  constructor. apply occ_in_modal_mconj_l. auto.\n  simpl. rewrite H2. inversion H1 as [H3 H4].\n  if_then_else_dest_blind; auto.\nQed.\n\nLemma is_pos_mdisj_l2 : forall phi1 phi2 i,\n    is_pos phi1 i ->\n    is_pos (phi1 m∨ phi2) i.\nProof.\n  intros phi1 phi2 i [H1 H2].\n  constructor. apply occ_in_modal_mdisj_l. auto.\n  simpl. rewrite H2. inversion H1 as [H3 H4].\n  if_then_else_dest_blind; auto.\nQed.\n\nLemma is_pos_mimpl_l2 : forall phi1 phi2 i,\n    is_pos phi1 i ->\n    ~ is_pos (phi1 m→ phi2) i.\nProof.\n  intros phi1 phi2 i [H1 H2] [H5 H6].\n  simpl in H6. rewrite H2 in H6. inversion H1  as [H7 H8].\n  if_then_else_dest_blind; auto. unfold negb in *. \n  discriminate.\nQed.\n\nLemma is_pos_mconj_r2 : forall phi1 phi2 i,\n    is_pos phi2 (i - length (pv_in phi1)) ->\n    is_pos (phi1 m∧ phi2) i.\nProof.\n  intros phi1 phi2 i [H1 H2]. pose proof H1 as H1'.\n  apply occ_in_modal_mconj_r2 in H1.\n  constructor. auto.\n  simpl.  rewrite H2. if_then_else_dest_blind; auto.\n  inversion H1'. firstorder.\nQed.\n\nLemma is_pos_mdisj_r2 : forall phi1 phi2 i,\n    is_pos phi2 (i - length (pv_in phi1)) ->\n    is_pos (phi1 m∨ phi2) i.\nProof.\n  intros phi1 phi2 i [H1 H2]. pose proof H1 as H1'.\n  apply occ_in_modal_mdisj_r2 in H1.\n  constructor. auto.\n  simpl.  rewrite H2. if_then_else_dest_blind; auto.\n  inversion H1'. firstorder.\nQed.\n\nLemma is_pos_mimpl_l : forall phi1 phi2 i,\n    occ_in_modal phi1 i ->\n    ~ is_pos phi1 i ->\n    is_pos (phi1 m→ phi2) i.\nProof.\n  intros phi1 phi2 i H1 H3.\n  constructor. apply occ_in_modal_mimpl_l. auto.\n  simpl. inversion H1 as [H2 H4].\n  if_then_else_dest_blind; auto; firstorder.\nQed.\n\nLemma is_pos_mimpl_r : forall phi1 phi2 i,\n    is_pos phi2 (i - length (pv_in phi1)) ->\n    is_pos (phi1 m→ phi2) i.\nProof.\n  intros phi1 phi2 i [H1 H2].\n  constructor. apply occ_in_modal_mimpl_r2. auto.\n  simpl. unfold negb. if_then_else_dest_blind; auto. \n  firstorder.\nQed.\n\nLemma is_pos_mimpl_r2 : forall phi1 phi2 i,\n    is_pos (phi1 m→ phi2) i ->\n    occ_in_modal phi2 (i - length (pv_in phi1)) ->\n    is_pos phi2  (i - length (pv_in phi1)).\nProof.\n  intros phi1 phi2 i [H1 H2] H3.\n  constructor. auto.\n  simpl in H2. if_then_else_dest_blind; auto.\n  firstorder.\nQed.\n\nLemma is_pos_dec_occ : forall phi i,\n    occ_in_modal phi i -> {is_pos phi i} + {~ is_pos phi i}.\nProof.\n  induction phi; intros i Hocc.\n  - apply occ_in_modal_atom in Hocc. subst.\n    left. apply is_pos_atom2.\n  - apply  (occ_in_modal_mneg phi) in Hocc.\n    destruct (IHphi _ Hocc) as [H | H].\n    right. intros H2. apply is_pos_mneg in H2.\n    contradiction.\n    left. apply is_pos_mneg2; auto.\n  - destruct (occ_in_modal_dec phi1 i) as [H1 | H1].\n    destruct (IHphi1 _ H1) as [H2 | H2].\n    left. apply is_pos_mconj_l2. auto.\n    right. intros H3. apply is_pos_mconj_l in H3.\n    contradiction.  auto.\n    apply occ_in_modal_mconj in Hocc.\n    destruct (IHphi2 _ Hocc) as [H2 | H2]. left.\n    apply is_pos_mconj_r2. auto.\n    right. intros H3. apply is_pos_mconj_r in H3. auto.\n    apply occ_in_modal_f in H1. destruct H1 as [H4| H4].\n    subst. firstorder. apply Gt.gt_le_S in H4. firstorder.\n    auto.\n  - destruct (occ_in_modal_dec phi1 i) as [H1 | H1].\n    destruct (IHphi1 _ H1) as [H2 | H2].\n    left. apply is_pos_mdisj_l2. auto.\n    right. intros H3. apply is_pos_mdisj_l in H3.\n    contradiction.  auto.\n    apply occ_in_modal_mdisj in Hocc.\n    destruct (IHphi2 _ Hocc) as [H2 | H2]. left.\n    apply is_pos_mdisj_r2. auto.\n    right. intros H3. apply is_pos_mdisj_r in H3. auto.\n    apply occ_in_modal_f in H1. destruct H1 as [H4| H4].\n    subst. firstorder. apply Gt.gt_le_S in H4. firstorder.\n    auto.\n  - destruct (occ_in_modal_dec phi1 i) as [H1 | H1].\n    destruct (IHphi1 _ H1) as [H2 | H2].\n    right. apply is_pos_mimpl_l2. auto.\n    left. apply is_pos_mimpl_l; auto.\n    apply occ_in_modal_mimpl in Hocc.\n    apply IHphi2 in Hocc. destruct Hocc as [H3 | H3].\n    left. apply is_pos_mimpl_r. auto.\n    right. intros H4. pose proof (is_pos_occ _ _ H4) as H5.\n    apply occ_in_modal_mimpl in H5.\n    apply is_pos_mimpl_r2 in H4. all : auto.\n  - apply (occ_in_modal_box phi) in Hocc.\n    apply IHphi in Hocc. destruct Hocc as [H1 | H1].\n    left. apply is_pos_box. auto.\n    right. intros H2. apply (is_pos_box phi) in H2.\n    auto.\n  - apply (occ_in_modal_dia phi) in Hocc.\n    apply IHphi in Hocc. destruct Hocc as [H1 | H1].\n    left. apply is_pos_dia. auto.\n    right. intros H2. apply (is_pos_dia phi) in H2.\n    auto.\nQed.\n\nLemma is_pos_dec : forall phi i, {is_pos phi i} + {~ is_pos phi i}.\nProof.\n  intros phi i. destruct (occ_in_modal_dec phi i) as [H|H].\n  2 : (right; intros H2; apply is_pos_occ in H2; contradiction).\n  apply is_pos_dec_occ. auto.\nQed.\n\nLemma is_pos_neg_pre_f_t : forall (phi : Modal) (i : nat),\n  occ_in_modal phi i ->\n  (is_pos_pre phi i = false  -> is_neg_pre phi i = true) /\\\n  (is_pos_pre phi i = true -> is_neg_pre phi i = false).\nProof.\n  induction phi; intros i Hocc.\n  - apply occ_in_modal_atom in Hocc. subst. simpl. auto.\n  - apply (occ_in_modal_mneg phi) in Hocc. simpl.\n    apply IHphi in Hocc. destruct Hocc as [H1 H2].\n    destruct (is_pos_pre phi i); destruct (is_neg_pre phi  i);\n      firstorder.\n  - destruct (occ_in_modal_dec phi1 i) as [H1 | H1].\n    pose proof (IHphi1 _ H1) as H2. simpl.\n    inversion H1 as [H3 H4]. if_then_else_dest_blind; auto.\n    contradiction.\n\n    apply occ_in_modal_mconj in Hocc. pose proof (IHphi2 _ Hocc) as H2.\n    inversion Hocc as [H3 H4]. simpl. apply occ_in_modal_f in H1.\n    destruct H1. subst. contradiction. apply Gt.gt_not_le in H.\n    if_then_else_dest_blind; auto. firstorder. auto.\n  - destruct (occ_in_modal_dec phi1 i) as [H1 | H1].\n    pose proof (IHphi1 _ H1) as H2. simpl.\n    inversion H1 as [H3 H4]. if_then_else_dest_blind; auto.\n    contradiction.\n\n    apply occ_in_modal_mdisj in Hocc. pose proof (IHphi2 _ Hocc) as H2.\n    inversion Hocc as [H3 H4]. simpl. apply occ_in_modal_f in H1.\n    destruct H1. subst. contradiction. apply Gt.gt_not_le in H.\n    if_then_else_dest_blind; auto. firstorder. auto.\n  - destruct (occ_in_modal_dec phi1 i) as [H1 | H1].\n    pose proof (IHphi1 _ H1) as H2. simpl.\n    inversion H1 as [H3 H4]. unfold negb. \n    if_then_else_dest_blind; auto; firstorder.\n\n    apply occ_in_modal_mimpl in Hocc. pose proof (IHphi2 _ Hocc) as H2.\n    inversion Hocc as [H3 H4]. simpl. apply occ_in_modal_f in H1.\n    destruct H1. subst. contradiction. apply Gt.gt_not_le in H.\n    unfold negb. if_then_else_dest_blind; auto; firstorder. auto.\n  - simpl. apply IHphi. apply occ_in_modal_box. auto.\n  - simpl. apply IHphi. apply occ_in_modal_dia. auto.\nQed.\n  \nLemma is_pos_neg_f_t : forall (phi : Modal) (i : nat),\n  occ_in_modal phi i ->\n  (~ is_pos phi i  -> is_neg phi i) /\\\n  (is_pos phi i -> ~ is_neg phi i).\nProof.\n  intros phi i Hocc. destruct (is_pos_neg_pre_f_t phi i Hocc) as [H1 H2].\n  split; intros H.\n  constructor. auto.\n  apply H1. case_eq (is_pos_pre phi i); intros H3.\n  contradiction (H (occ_pos _ _ Hocc H3)).\n  reflexivity.\n\n  intros H3. apply (is_pos_neg_not phi i). auto.\nQed.\n\nLemma is_pos_neg_iff : forall phi i,\n    occ_in_modal phi i ->\n    is_pos phi i <-> ~ is_neg phi i.\nProof.\n  intros phi i  H. split; intros H2.\n  intros H3. apply (is_pos_neg_not phi i).\n  auto.\n  destruct (is_pos_dec phi i) as [H3 | H3]. auto.\n  apply is_pos_neg_f_t in H3. firstorder.\n  auto.\nQed.\n\nLemma is_pos_neg_f : forall (phi : Modal) (i : nat),\n  occ_in_modal phi i ->\n  (~ is_pos phi i -> is_neg phi i).\nProof.\n  intros phi i Hocc Hpos.\n  apply is_pos_neg_f_t; assumption.\nQed.\n\nLemma is_pos_neg_t : forall (phi : Modal) (i : nat),\n  (is_pos phi i -> ~is_neg phi i).\nProof.\n  intros phi i Hpos.\n  pose proof (is_pos_occ _ _ Hpos) as Hocc.\n  apply is_pos_neg_f_t; assumption.\nQed.\n\nLemma is_neg_pos_f : forall (phi : Modal) (i : nat),\n  occ_in_modal phi i ->\n  (~ is_neg phi i -> is_pos phi i).\nProof.\n  intros phi i Hocc Hpos.\n  destruct (is_pos_dec phi i) as [H1 | H1]. auto.\n  apply is_pos_neg_f in H1; firstorder.\nQed. \n\nLemma is_neg_pos_t : forall (phi : Modal) (i : nat),\n  (is_neg phi i -> ~ is_pos phi i).\nProof.\n  intros phi i H1 H2. apply (is_pos_neg_not phi i).\n  auto.\nQed.\n\n(* ------------------------------------------------------- *)\n\nLemma is_pos_neg_or : forall (phi : Modal) (i : nat),\n  occ_in_modal phi i ->\n  is_pos phi i  \\/ is_neg phi i.\nProof.\n  intros phi i H.\n  destruct (is_pos_dec phi i). auto.\n  right. apply is_pos_neg_f; auto.\nQed.\n\nLemma is_pos_neg_mimpl_l : forall (phi1 phi2 : Modal) (i : nat),\n  is_pos (mimpl phi1 phi2) i ->\n  occ_in_modal phi1 i -> is_neg phi1 i.\nProof.\n  intros phi1 phi2 i Hpos Hocc.\n  destruct (is_pos_neg_or phi1 i Hocc) as [H1|H1].\n  apply is_pos_mimpl_l2 with (phi2 := phi2)  in H1.\n  contradiction (H1 Hpos). auto.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n(* is_neg lemmas *)\n\nLemma is_neg_notin : forall (phi : Modal) (i : nat),\n  is_neg phi i  -> le i (length (pv_in phi)).\nProof.\n  intros phi i H. inversion H.\n  apply occ_in_modal_le. auto.\nQed.\n\nLemma is_neg_atom : forall (q : propvar) (i : nat),\n  is_neg (atom q) i -> i = 1. \nProof.\n  intros q i [[H1 H3] H2]. simpl in *.\n  firstorder.\nQed.\n\nLemma is_neg_mconj_l : forall (phi1 phi2 : Modal) (i : nat),\n  is_neg (mconj phi1 phi2) i ->\n    ( occ_in_modal phi1 i -> is_neg phi1 i).\nProof.\n  intros phi1 phi2 i [H1 H2] Hocc.\n  simpl in H2. constructor. auto.\n  apply occ_in_modal_le in Hocc.\n  if_then_else_dest_blind; auto.\nQed.\n\nLemma is_neg_mconj_r : forall (phi1 phi2 : Modal) (i : nat),\n  is_neg (mconj phi1 phi2) i ->\n    (le (length (pv_in phi1) + 1) i) ->\n      is_neg phi2 (i - (length (pv_in phi1))).\nProof.\n  intros phi1 phi2 i [H1 H2] Hocc.\n  simpl in H2. if_then_else_dest_blind; simpl in *;\n                 auto; firstorder.\n  simpl in *. rewrite app_length in *. firstorder.\nQed.\n\nLemma is_neg_mdisj_l : forall (phi1 phi2 : Modal) (i : nat),\n  is_neg (mdisj phi1 phi2) i ->\n  ( occ_in_modal phi1 i ->  (is_neg phi1 i)).\nProof.\n  intros phi1 phi2 i [H1 H2] Hocc.\n  simpl in H2. constructor. auto.\n  apply occ_in_modal_le in Hocc.\n  if_then_else_dest_blind; auto.\nQed.\n\nLemma is_neg_mdisj_r : forall (phi1 phi2 : Modal) (i : nat),\n  is_neg (mdisj phi1 phi2) i ->\n    ((length (pv_in phi1) + 1) <= i) ->\n      is_neg phi2 (i - (length (pv_in phi1))).\nProof.\n  intros phi1 phi2 i [H1 H2] Hocc.\n  simpl in H2. if_then_else_dest_blind; simpl in *;\n                 auto; firstorder.\n  simpl in *. rewrite app_length in *. firstorder.\nQed.\n\nLemma is_neg_mconj : forall (phi1 phi2 : Modal) (i : nat),\n  is_neg (mconj phi1 phi2) i ->\n    ( occ_in_modal phi1 i ->  (is_neg phi1 i)) /\\\n    ((le (length (pv_in phi1) + 1) i) ->\n       is_neg phi2 (i - (length (pv_in phi1)))).\nProof.\n  intros phi1 phi2 i Hpos.\n  apply conj.\n    apply is_neg_mconj_l with (phi2 := phi2); exact Hpos.\n\n    apply is_neg_mconj_r with (phi1 := phi1); exact Hpos.\nQed.\n\nLemma is_neg_mdisj : forall (phi1 phi2 : Modal) (i : nat),\n  is_neg (mdisj phi1 phi2) i ->\n    ( occ_in_modal phi1 i ->  (is_neg phi1 i)) /\\\n    (( (length (pv_in phi1) + 1) <= i) ->\n       is_neg phi2 (i - (length (pv_in phi1)))).\nProof.\n  intros phi1 phi2 i Hpos.\n  apply conj.\n    apply is_neg_mdisj_l with (phi2 := phi2); exact Hpos.\n\n    apply is_neg_mdisj_r with (phi1 := phi1); exact Hpos.\nQed.\n\n(* --------------------------------------------------------------- *)\nLemma is_neg_atom2 : forall p,\n    ~ is_neg #p 1.\nProof. intros p H. inversion H. firstorder. Qed.\n\nLemma is_neg_mconj_l2 : forall phi1 phi2 i,\n    is_neg phi1 i ->\n    is_neg (phi1 m∧ phi2) i.\nProof.\n  intros phi1 phi2 i [H1 H2].\n  constructor. apply occ_in_modal_mconj_l. auto.\n  simpl. rewrite H2. inversion H1 as [H3 H4].\n  if_then_else_dest_blind; auto.\nQed.\n\nLemma is_neg_mdisj_l2 : forall phi1 phi2 i,\n    is_neg phi1 i ->\n    is_neg (phi1 m∨ phi2) i.\nProof.\n  intros phi1 phi2 i [H1 H2].\n  constructor. apply occ_in_modal_mdisj_l. auto.\n  simpl. rewrite H2. inversion H1 as [H3 H4].\n  if_then_else_dest_blind; auto.\nQed.\n\nLemma is_neg_mimpl_l2 : forall phi1 phi2 i,\n    is_neg phi1 i ->\n    ~ is_neg (phi1 m→ phi2) i.\nProof.\n  intros phi1 phi2 i [H1 H2] [H5 H6].\n  simpl in H6. rewrite H2 in H6. inversion H1  as [H7 H8].\n  if_then_else_dest_blind; auto. unfold negb in *.\n  firstorder.\nQed.\n\nLemma is_neg_mconj_r2 : forall phi1 phi2 i,\n    is_neg phi2 (i - length (pv_in phi1)) ->\n    is_neg (phi1 m∧ phi2) i.\nProof.\n  intros phi1 phi2 i [H1 H2]. pose proof H1 as H1'.\n  apply occ_in_modal_mconj_r2 in H1.\n  constructor. auto.\n  simpl.  rewrite H2. if_then_else_dest_blind; auto.\n  firstorder.\nQed.\n\nLemma is_neg_mdisj_r2 : forall phi1 phi2 i,\n    is_neg phi2 (i - length (pv_in phi1)) ->\n    is_neg (phi1 m∨ phi2) i.\nProof.\n  intros phi1 phi2 i [H1 H2]. pose proof H1 as H1'.\n  apply occ_in_modal_mdisj_r2 in H1.\n  constructor. auto.\n  simpl.  rewrite H2. if_then_else_dest_blind; firstorder.\nQed.\n\nLemma is_neg_mimpl_l : forall phi1 phi2 i,\n    occ_in_modal phi1 i ->\n    ~ is_neg phi1 i ->\n    is_neg (phi1 m→ phi2) i.\nProof.\n  intros phi1 phi2 i H1 H3.\n  constructor. apply occ_in_modal_mimpl_l. auto.\n  simpl. inversion H1 as [H2 H4].\n  if_then_else_dest_blind; firstorder.\nQed.\n\nLemma is_neg_mimpl_r : forall phi1 phi2 i,\n    is_neg phi2 (i - length (pv_in phi1)) ->\n    is_neg (phi1 m→ phi2) i.\nProof.\n  intros phi1 phi2 i [H1 H2].\n  constructor. apply occ_in_modal_mimpl_r2. auto.\n  simpl. if_then_else_dest_blind; firstorder.\nQed.\n\nLemma is_neg_mimpl_r2 : forall phi1 phi2 i,\n    is_neg (phi1 m→ phi2) i ->\n    occ_in_modal phi2 (i - length (pv_in phi1)) ->\n    is_neg phi2  (i - length (pv_in phi1)).\nProof.\n  intros phi1 phi2 i [H1 H2] H3.\n  constructor. auto. simpl in *.\n  if_then_else_dest_blind; firstorder.\nQed.\n\nLemma is_neg_dec_occ : forall phi i,\n    occ_in_modal phi i -> {is_neg phi i} + {~ is_neg phi i}.\nProof.\n  induction phi; intros i Hocc.\n  - apply occ_in_modal_atom in Hocc. subst.\n    right. apply is_neg_atom2.\n  - apply  (occ_in_modal_mneg phi) in Hocc.\n    destruct (IHphi _ Hocc) as [H | H].\n    right. intros H2. apply is_neg_mneg in H2.\n    contradiction.\n    left. apply is_neg_mneg2; auto.\n  - destruct (occ_in_modal_dec phi1 i) as [H1 | H1].\n    destruct (IHphi1 _ H1) as [H2 | H2].\n    left. apply is_neg_mconj_l2. auto.\n    right. intros H3. apply is_neg_mconj_l in H3.\n    contradiction.  auto.\n    apply occ_in_modal_mconj in Hocc.\n    destruct (IHphi2 _ Hocc) as [H2 | H2]. left.\n    apply is_neg_mconj_r2. auto.\n    right. intros H3. apply is_neg_mconj_r in H3. auto.\n    apply occ_in_modal_f in H1. destruct H1 as [H4| H4].\n    subst. firstorder. apply Gt.gt_le_S in H4. firstorder.\n    auto.\n  - destruct (occ_in_modal_dec phi1 i) as [H1 | H1].\n    destruct (IHphi1 _ H1) as [H2 | H2].\n    left. apply is_neg_mdisj_l2. auto.\n    right. intros H3. apply is_neg_mdisj_l in H3.\n    contradiction.  auto.\n    apply occ_in_modal_mdisj in Hocc.\n    destruct (IHphi2 _ Hocc) as [H2 | H2]. left.\n    apply is_neg_mdisj_r2. auto.\n    right. intros H3. apply is_neg_mdisj_r in H3. auto.\n    apply occ_in_modal_f in H1. destruct H1 as [H4| H4].\n    subst. firstorder. apply Gt.gt_le_S in H4. firstorder.\n    auto.\n  - destruct (occ_in_modal_dec phi1 i) as [H1 | H1].\n    destruct (IHphi1 _ H1) as [H2 | H2].\n    right. apply is_neg_mimpl_l2. auto.\n    left. apply is_neg_mimpl_l; auto.\n    apply occ_in_modal_mimpl in Hocc.\n    apply IHphi2 in Hocc. destruct Hocc as [H3 | H3].\n    left. apply is_neg_mimpl_r. auto.\n    right. intros H4. pose proof (is_neg_occ _ _ H4) as H5.\n    apply occ_in_modal_mimpl in H5.\n    apply is_neg_mimpl_r2 in H4. all : auto.\n  - apply (occ_in_modal_box phi) in Hocc.\n    apply IHphi in Hocc. destruct Hocc as [H1 | H1].\n    left. apply is_neg_box. auto.\n    right. intros H2. apply (is_neg_box phi) in H2.\n    auto.\n  - apply (occ_in_modal_dia phi) in Hocc.\n    apply IHphi in Hocc. destruct Hocc as [H1 | H1].\n    left. apply is_neg_dia. auto.\n    right. intros H2. apply (is_neg_dia phi) in H2.\n    auto.\nQed.\n\nLemma is_neg_dec : forall phi i, {is_neg phi i} + {~ is_neg phi i}.\nProof.\n  intros phi i. destruct (occ_in_modal_dec phi i) as [H|H].\n  2 : (right; intros H2; apply is_neg_occ in H2; contradiction).\n  apply is_neg_dec_occ. auto.\nQed.\n\nLemma is_neg_pos_pre_f_t : forall (phi : Modal) (i : nat),\n  occ_in_modal phi i ->\n  (is_neg_pre phi i = false  -> is_pos_pre phi i = true) /\\\n  (is_neg_pre phi i = true -> is_pos_pre phi i = false).\nProof.\n  intros phi i Hocc.\n  case_eq (is_pos_pre phi i); intros H2; split; try auto;\n    intros H3; apply is_pos_neg_pre_f_t in H2; try rewrite H2 in *; auto.\nQed.\n\nLemma is_neg_pos_f_t : forall (phi : Modal) (i : nat),\n  occ_in_modal phi i ->\n  (~ is_neg phi i  -> is_pos phi i) /\\\n  (is_neg phi i -> ~ is_pos phi i).\nProof.\n  intros phi i Hocc.\n  destruct (is_pos_neg_f_t phi i Hocc) as [H1 H2].\n  destruct (is_pos_dec phi i) as [H3 | H3];\n    split; intros H4; try auto.\n  contradiction (is_pos_neg_not phi i). auto.\n  apply H1 in H3. contradiction.\nQed.\n\nLemma is_neg_pos_iff : forall phi i,\n    occ_in_modal phi i ->\n    is_neg phi i <-> ~ is_pos phi i.\nProof.\n  intros phi i  H. split; intros H2.\n  intros H3. apply (is_pos_neg_not phi i).\n  auto.\n  destruct (is_neg_dec phi i) as [H3 | H3]. auto.\n  apply is_neg_pos_f_t in H3. firstorder.\n  auto.\nQed.\n\n(* ------------------------------------------------------- *)\n\nLemma is_neg_pos_mimpl_l : forall (phi1 phi2 : Modal) (i : nat),\n  is_neg (mimpl phi1 phi2) i ->\n  occ_in_modal phi1 i -> is_pos phi1 i.\nProof.\n  intros phi1 phi2 i Hpos Hocc.\n  destruct (is_pos_neg_or phi1 i Hocc) as [H1|H1]. auto.\n  apply is_neg_mimpl_l2 with (phi2 := phi2)  in H1.\n  firstorder.\nQed.", "meta": {"author": "caitlindabrera", "repo": "Sahlqvist", "sha": "d0a755fb663a6cabc0babb691564cdf575fc8b36", "save_path": "github-repos/coq/caitlindabrera-Sahlqvist", "path": "github-repos/coq/caitlindabrera-Sahlqvist/Sahlqvist-d0a755fb663a6cabc0babb691564cdf575fc8b36/vsSahlq/coq_code/is_pos_neg_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.6564820385874396}}
{"text": "Require Import\n  Coq.Unicode.Utf8\n  HoTT.Basics.Overture\n  HoTT.Classes.implementations.list.\n\n(** The following section implements a datatype [FamilyProd] which\n    is a kind of product/tuple. *)\n\nSection family_prod.\n  Context {I : Type}.\n\n  (** [FamilyProd F ℓ] is a product type defined by\n  \n      <<\n        FamilyProd F [i1;i2;...;in] = F i1 * F i2 * ... * F in * Unit\n      >>\n\n      It is convenient to have the [Unit] in the end.\n  *)\n\n  Definition FamilyProd (F : I → Type) : list I → Type\n    := fold_right (λ (i:I) (A:Type), F i * A) Unit.\n\n  (** Map function for [FamilyProd F ℓ],\n\n      <<\n        map_family_prod f (x1, x2, ..., xn, tt)\n        = (f x1, f x2, ..., f xn, tt)\n      >> *)\n\n  Fixpoint map_family_prod {F G : I → Type} {ℓ : list I}\n      (f : ∀ i, F i → G i)\n      : FamilyProd F ℓ → FamilyProd G ℓ :=\n    match ℓ with\n    | nil => const tt\n    | i :: ℓ' => λ '(x,s), (f i x, map_family_prod f s)\n    end.\n\n  (** [for_all_family_prod F P (x1, ..., xn, tt) = True] if\n      [P i1 x1 ∧ P i2 x2 ∧ ... ∧ P in xn] holds. *)\n\n  Fixpoint for_all_family_prod (F : I → Type) {ℓ : list I}\n      (P : ∀ i, F i -> Type) : FamilyProd F ℓ → Type :=\n    match ℓ with\n    | nil => λ _, True\n    | i :: ℓ' => λ '(x,s), P i x ∧ for_all_family_prod F P s\n    end.\n\n  (** [for_all_2_family_prod F G R (x1,...,xn,tt) (y1,...,yn,tt) = True]\n      if [R i1 x1 y1 ∧ R i2 x2 y2 ∧ ... ∧ P in xn yn] holds. *)\n\n  Fixpoint for_all_2_family_prod (F G : I → Type) {ℓ : list I}\n      (R : ∀ i, F i -> G i -> Type)\n      : FamilyProd F ℓ → FamilyProd G ℓ → Type :=\n    match ℓ with\n    | nil => λ _ _, True\n    | i :: ℓ' => λ '(x,s) '(y,t), R i x y ∧ for_all_2_family_prod F G R s t\n    end.\n\n  (** If [R : ∀ i, relation (F i)] is a family of relations indexed by\n      [i:I] and [R i] is reflexive for all [i], then\n\n      <<\n        for_all_2_family_prod F F R s s\n      >>\n\n      holds. *)\n  Lemma reflexive_for_all_2_family_prod (F : I → Type)\n    (R : ∀ i, Relation (F i)) `{!∀ i, Reflexive (R i)}\n    {ℓ : list I} (s : FamilyProd F ℓ)\n    : for_all_2_family_prod F F R s s.\n  Proof with try reflexivity.\n    induction ℓ...\n    split...\n    apply IHℓ.\n  Defined.\nEnd family_prod.\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/Classes/implementations/family_prod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.6564820307886413}}
{"text": "Module Type MONAD.\n  Set Implicit Arguments. \n  \n  Parameter M : forall (A : Type), Type.\n  Parameter bind : forall (A B : Type),\n    M A -> (A -> M B) -> M B.\n  Parameter ret : forall (A : Type),\n    A -> M A.\n  \n  Infix \">>=\" := bind (at level 20, left associativity) : monad_scope.\n  Open Scope monad_scope.\n  \n  Axiom left_unit : forall (A B : Type) (f : A -> M B) (a : A),\n    (ret a) >>= f = f a.\n  Axiom right_unit : forall (A B : Type) (m : M A),\n    m >>= (fun a : A => ret a) = m.\n  Axiom bind_assoc : forall (A B C : Type) (m : M A) (f : A -> M B) (g : B -> M C) (x : B),\n    (m >>= f) >>= g = m >>= (fun x => (f x) >>= g).\n\nEnd MONAD.\n\nModule ListMonad <: MONAD. \n  \n  Require Import List.\n  \n  Set Implicit Arguments.\n  \n  Definition M := list.\n  \n  Fixpoint bind (A : Type) (B : Type) (l : M A) (f : A -> M B) {struct l} : M B :=\n    match l with\n      | nil => nil\n      | h::t => (f h)++(bind t f)\n    end.\n  \n  Infix \">>=\" := bind (at level 20, left associativity) : monad_scope.\n  Open Scope monad_scope.\n  \n  Definition ret (A : Type) := fun a : A => a::nil.\n  \n  Lemma left_unit : forall (A B : Type) (f : A -> M B) (a : A),\n    (ret a) >>= f = f a.\n  Proof.\n    intros ; simpl ; rewrite app_nil_end ; reflexivity.\n  Defined. \n  \n  Lemma right_unit : forall (A B : Type) (m : M A),\n    m >>= (fun a : A => ret a) = m.\n  Proof.\n    simple induction m.\n    simpl. reflexivity.\n    intros. simpl.\n    cut (bind l (fun a0 : A => ret a0) = l).\n    intros. rewrite H0. reflexivity.\n    exact H.\n  Defined. \n  \n  Lemma bind_assoc : forall (A B C : Type) (m : M A) (f : A -> M B) (g : B -> M C) (x : B),\n    (m >>= f) >>= g = m >>= (fun x => (f x) >>= g).\n  Proof.\n    simple induction m.\n    intros. simpl. reflexivity.\n    intros. simpl.\n    cut (l >>= f >>= g = l >>= (fun x0 : A => f x0 >>= g)).\n    intros. rewrite < - H0.\n    induction (f a).\n    simpl. reflexivity.\n    simpl. rewrite IHm0. rewrite app_ass. reflexivity.\n    apply H. exact x.\n  Defined.\n\nEnd ListMonad.\n\n(* Example *)\nImport ListMonad.\nRequire Import Peano.\nRequire Import List.\n\nFixpoint downfrom (n : nat) {struct n} : (list nat) :=\n  match n with\n    | 0 => n::nil\n    | S m => n::(downfrom m)\n  end.\n", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6564820276405785}}
{"text": "Require Import\n  Coq.Unicode.Utf8\n  HoTT.Basics.Overture\n  HoTTClasses.implementations.list.\n\n(** The following section implements a datatype [FamilyProd] which\n    is a kind of product/tuple. *)\n\nSection family_prod.\n  Context {I : Type}.\n\n  (** [FamilyProd F ℓ] is a product type defined by\n  \n      <<\n        FamilyProd F [i1;i2;...;in] = F i1 * F i2 * ... * F in * Unit\n      >>\n\n      It is convenient to have the [Unit] in the end.\n  *)\n\n  Definition FamilyProd (F : I → Type) : list I → Type\n    := fold_right (λ (i:I) (A:Type), F i * A) Unit.\n\n  (** Map function for [FamilyProd F ℓ],\n\n      <<\n        map_family_prod f (x1, x2, ..., xn, tt)\n        = (f x1, f x2, ..., f xn, tt)\n      >> *)\n\n  Fixpoint map_family_prod {F G : I → Type} {ℓ : list I}\n      (f : ∀ i, F i → G i)\n      : FamilyProd F ℓ → FamilyProd G ℓ :=\n    match ℓ with\n    | nil => const tt\n    | i :: ℓ' => λ '(x,s), (f i x, map_family_prod f s)\n    end.\n\n  (** [for_all_family_prod F P (x1, ..., xn, tt) = True] if\n      [P i1 x1 ∧ P i2 x2 ∧ ... ∧ P in xn] holds. *)\n\n  Fixpoint for_all_family_prod (F : I → Type) {ℓ : list I}\n      (P : ∀ i, F i -> Type) : FamilyProd F ℓ → Type :=\n    match ℓ with\n    | nil => λ _, True\n    | i :: ℓ' => λ '(x,s), P i x ∧ for_all_family_prod F P s\n    end.\n\n  (** [for_all_2_family_prod F G R (x1,...,xn,tt) (y1,...,yn,tt) = True]\n      if [R i1 x1 y1 ∧ R i2 x2 y2 ∧ ... ∧ P in xn yn] holds. *)\n\n  Fixpoint for_all_2_family_prod (F G : I → Type) {ℓ : list I}\n      (R : ∀ i, F i -> G i -> Type)\n      : FamilyProd F ℓ → FamilyProd G ℓ → Type :=\n    match ℓ with\n    | nil => λ _ _, True\n    | i :: ℓ' => λ '(x,s) '(y,t), R i x y ∧ for_all_2_family_prod F G R s t\n    end.\n\n  (** If [R : ∀ i, relation (F i)] is a family of relations indexed by\n      [i:I] and [R i] is reflexive for all [i], then\n\n      <<\n        for_all_2_family_prod F F R s s\n      >>\n\n      holds. *)\n  Lemma reflexive_for_all_2_family_prod (F : I → Type)\n    (R : ∀ i, relation (F i)) `{!∀ i, Reflexive (R i)}\n    {ℓ : list I} (s : FamilyProd F ℓ)\n    : for_all_2_family_prod F F R s s.\n  Proof with try reflexivity.\n    induction ℓ...\n    split...\n    apply IHℓ.\n  Defined.\nEnd family_prod.\n", "meta": {"author": "andreaslyn", "repo": "hott-classes", "sha": "22b9e99c670ad24e90dd75af6c897307a8482891", "save_path": "github-repos/coq/andreaslyn-hott-classes", "path": "github-repos/coq/andreaslyn-hott-classes/hott-classes-22b9e99c670ad24e90dd75af6c897307a8482891/implementations/family_prod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.6564820217914799}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\nFrom Coq Require FunctionalExtensionality List.\n\nFrom Mon Require Export Base.\nFrom Coq Require Import Relation_Definitions Morphisms.\nFrom Mon Require Import SPropBase SPropMonadicStructures MonadExamples SpecificationMonads Monoid DijkstraMonadExamples.\nSet Warnings \"-notation-overridden,-ambiguous-paths\".\nFrom mathcomp Require Import all_ssreflect all_algebra reals distr.\nSet Warnings \"notation-overridden,ambiguous-paths\".\nFrom Relational Require Import Commutativity.\n\nImport GRing.Theory Num.Theory.\nImport Order.POrderTheory.\n\nLocal Open Scope ring_scope.\n\nSection FinProb.\n\n  Context (R:realType).\n\n  Import SPropNotations.\n\n  Definition unit_interval := { r : R | 0 <= r <= 1 }.\n  Let I := unit_interval.\n\n\n  Definition Irel : relation I := fun i1 i2 => i1∙1 <= i2∙1.\n  Global Instance Irel_preorder : PreOrder Irel.\n  Proof.\n    constructor.\n    move=> ?; rewrite /Irel lexx //.\n    move=> x y z ; rewrite /Irel.\n    apply le_trans.\n  Qed.\n\n  Definition WI := @MonoCont I Irel _.\n\n  (* Lemma since_its_true (b:bool) : ⟦b⟧ -> b. *)\n  (* Proof. by case: b. Qed. *)\n\n  (* Lemma its_true_anyway (b:bool) : b -> ⟦b⟧. *)\n  (* Proof. by case: b. Qed. *)\n\n  Lemma I_ge0 (x:I) : 0 <= x∙1.\n  Proof. by move: (x∙2)=> /andP [-> _]. Qed.\n\n  Lemma I_le1 (x:I) : x∙1 <= 1.\n  Proof. by move: (x∙2)=> /andP [_ ->]. Qed.\n\n  Hint Resolve I_ge0 : core.\n  Hint Resolve I_le1 : core.\n\n  #[program] Definition addI (x y : I) : I := ⦑ (x∙1 + y∙1) / 2%:~R ⦒.\n  Next Obligation.\n    intros x y. simpl.\n    rewrite divr_ge0 ?Bool.andb_true_l ?ler0n ?addr_ge0 //.\n    rewrite ler_pdivr_mulr.\n    rewrite mul1r [2%:~R]/(1+1) ler_add //.\n    rewrite ltr0n //.\n  Qed.\n\n  #[program] Definition mulI (x y:I) : I := ⦑ x∙1 * y∙1 ⦒.\n  Next Obligation.\n    intros. simpl.\n    rewrite mulr_ge0 //=.\n    rewrite -{3}(mul1r 1).\n    rewrite ler_pmul //=.\n  Qed.\n\n  #[program] Definition negI (x:I) : I := ⦑ 1 - x∙1 ⦒.\n  Next Obligation.\n    intros. simpl.\n    rewrite subr_ge0 (I_le1 x) /= ler_subl_addr -{1}(addr0 1) ler_add ?lerr //.\n  Qed.\n\n  Definition ProbS := I.\n  Definition ProbAr (p:ProbS) := bool.\n\n  Definition ProbM : Monad := Free ProbAr.\n\n  #[program] Definition barycentric_sum (p:I) (x y: I) : I :=\n    ⦑ p∙1 * x∙1 + (1-p∙1) * y∙1 ⦒.\n  Next Obligation.\n    intros p x y. simpl.\n    set p' : I := negI p; change (1-p∙1) with p'∙1.\n    rewrite addr_ge0 ?mulr_ge0 //.\n    have: (1 = p∙1*1 + (1 - p∙1)*1) by rewrite !mulr1 addrA [_+1]addrC addrK.\n    move=> heq; rewrite [X in _ <= X]heq.\n    by rewrite ler_add // ler_pmul // (I_ge0 (negI p)).\n  Qed.\n\n  #[program] Definition wopProb (p:ProbS) : WI (ProbAr p) :=\n    ⦑ fun f => barycentric_sum p (f true) (f false) ⦒.\n  Next Obligation.\n    intros p ? ? H.\n    rewrite /Irel /=.\n    rewrite ler_add // ler_pmul //; try by apply H.\n    by rewrite (I_ge0 (negI p)).\n  Qed.\n\n  Definition θProb := OpSpecEffObs wopProb.\n\n  Lemma mulIDl : left_distributive mulI addI.\n  Proof.\n    move=> ? ? ? ; apply sig_eq=> /=.\n    by rewrite -mulrA [in t in (_ * t)]mulrC mulrA mulrDl.\n  Qed.\n\n  Lemma mulIDr : right_distributive mulI addI.\n  Proof.\n    move=> ? ? ? ; apply sig_eq=> /=; by rewrite mulrA mulrDr.\n  Qed.\n\n  Lemma addIX p1 p2 p3 p4 :\n    addI (addI p1 p2) (addI p3 p4) = addI (addI p1 p3) (addI p2 p4).\n  Proof.\n    apply sig_eq => /=;\n      by rewrite -2!mulrDl -2!addrA\n                 [in t in _+t]addrA (addrC (p2∙1) (p3∙1)) !addrA.\n  Qed.\n\n  Lemma addIC : commutative addI.\n  Proof. move=> ? ? ; apply sig_eq => /= ; by rewrite addrC. Qed.\n\n  Lemma mulIC : commutative mulI.\n  Proof. move=> ? ? ; apply sig_eq => /= ; by rewrite mulrC. Qed.\n\n  Lemma mulIA : associative mulI.\n  Proof. move=> ? ? ? ; apply sig_eq => /= ; by rewrite mulrA. Qed.\n\n  Import FunctionalExtensionality.\n  Lemma self_commute (p1 p2 : ProbS) : commute (wopProb p1) (wopProb p2).\n  Proof.\n    rewrite /commute /wopProb; apply sig_eq=> /=.\n    extensionality k; apply sig_eq=> /=.\n    rewrite !mulrDr !mulrA.\n    do 2 rewrite [((1 - _)* _)as t in t * _]mulrC.\n    rewrite 2![(p1∙1 * _)as t in t * _]mulrC.\n    rewrite -2!addrA [in t in _+t]addrA [in t in _ + (t + _)]addrC !addrA.\n    do 2 f_equal.\n  Qed.\nEnd FinProb.\n\n\n(* Reflection for SProp (not needed in the end) *)\n\n(* Inductive sreflect (P : SProp) : bool -> Type := *)\n(* | SReflectT : P -> sreflect P true *)\n(* | SReflectF : s~ P -> sreflect P false. *)\n\n(* Lemma andSP (b1 b2 : bool) : sreflect (⟦b1⟧ /\\ ⟦b2⟧) (b1 && b2). *)\n(* Proof. case: b1; case: b2 => /=; first left=> //=; right=> [[[] []]]. Qed. *)\n\n(* Definition elimST (P : SProp) (b : bool) : sreflect P b -> ⟦b⟧ -> P. *)\n(* Proof. by case=> ? []. Qed. *)\n\n(* Coercion elimST : sreflect >-> Funclass. *)\n", "meta": {"author": "SSProve", "repo": "ssprove", "sha": "5dce3e2eae195fc466035e314ef4463d956c9c6a", "save_path": "github-repos/coq/SSProve-ssprove", "path": "github-repos/coq/SSProve-ssprove/ssprove-5dce3e2eae195fc466035e314ef4463d956c9c6a/theories/Mon/FiniteProbabilities.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.656339327628269}}
{"text": "Add LoadPath \"../..\".\nRequire Export LFND_Shared.\n\nInductive vctx_LF :=\n| bctx: nat -> vctx_LF\n| cctx: ctx_LF -> vctx_LF\n.\n\nInductive te_LF :=\n| hyp_LF: vte -> te_LF\n| lam_LF: ty -> te_LF -> te_LF\n| appl_LF: te_LF -> te_LF -> te_LF\n| box_LF: te_LF -> te_LF\n| unbox_LF: te_LF -> te_LF\n.\n\nLemma eq_te_LF_dec:\nforall (M1: te_LF) (M2: te_LF),\n  {M1 = M2} + {M1 <> M2}.\ndecide equality.\napply eq_vte_dec.\napply eq_ty_dec.\nQed.\n\n\nInductive lc_t_n_LF : nat -> te_LF -> Prop :=\n | lc_t_hyp_bte_LF: forall v n, n > v -> lc_t_n_LF n (hyp_LF (bte v))\n | lc_t_hyp_fte_LF: forall v n, lc_t_n_LF n (hyp_LF (fte v))\n | lc_t_lam_LF: forall M t n,\n     lc_t_n_LF (S n) M ->\n     lc_t_n_LF n (lam_LF t M)\n | lc_t_appl_LF: forall M N n,\n     lc_t_n_LF n M -> lc_t_n_LF n N ->\n     lc_t_n_LF n (appl_LF M N)\n | lc_t_box_LF: forall M n,\n     lc_t_n_LF n M ->\n     lc_t_n_LF n (box_LF M)\n | lc_t_unbox_LF: forall M n,\n     lc_t_n_LF n M ->\n     lc_t_n_LF n (unbox_LF M)\n.\n\nDefinition lc_t_LF := lc_t_n_LF 0.\n\nFixpoint used_vars_te_LF (M: te_LF) : fset var :=\nmatch M with\n| hyp_LF (fte v) => \\{v}\n| hyp_LF (bte _) => \\{}\n| lam_LF _ M => used_vars_te_LF M\n| appl_LF M N => used_vars_te_LF M \\u used_vars_te_LF N\n| box_LF M => used_vars_te_LF M\n| unbox_LF M => used_vars_te_LF M\nend.\n\nLemma closed_t_succ_LF:\nforall M n,\n  lc_t_n_LF n M -> lc_t_n_LF (S n) M.\nintros; generalize dependent n;\ninduction M; intros; inversion H; subst;\neauto using lc_t_n_LF.\nQed.\n\nLemma closed_t_addition_LF:\nforall M n m,\n  lc_t_n_LF n M -> lc_t_n_LF (n + m) M.\nintros; induction m;\n[ replace (n+0) with n by auto |\n  replace (n + S m) with (S (n+m)) by auto] ;\ntry apply closed_t_succ_LF;\nassumption.\nQed.\n", "meta": {"author": "Ayertienna", "repo": "IS5", "sha": "3bfd1b8510f269071d59d77818f8936d194364bc", "save_path": "github-repos/coq/Ayertienna-IS5", "path": "github-repos/coq/Ayertienna-IS5/IS5-3bfd1b8510f269071d59d77818f8936d194364bc/src/LabelFree/NoDiamond/LFND_Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6563393156305095}}
{"text": "(*\n - Definition of wild categories\n - Lemmas for invertible 2-cells\n - Equivalence of object\n*)\n\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.Bicategories.Core.Bicat. Import Notations.\n\nLocal Open Scope cat.\n\n(** Definition of wild category **)\n(* They are just the data for prebicategories *)\nNotation wild_cat_2cell_struct := prebicat_2cell_struct.\nNotation wild_cat_1_id_comp_cells := prebicat_1_id_comp_cells.\nNotation wild_cat_cells := prebicat_cells.\nNotation wild_cat_2_id_comp_struct := prebicat_2_id_comp_struct.\nNotation wild_cat := prebicat_data.\nNotation make_wild_cat := make_prebicat_data.\nNotation build_wild_cat := build_prebicat_data.\n\n(** Lemmas for invertible 2-cells **)\nDefinition is_invertible_2cell {C : wild_cat}\n           {a b : C} {f g : a --> b} (θ : f ==> g)\n  : UU := g ==> f.\n\nDefinition make_is_invertible_2cell {C : wild_cat}\n           {a b : C} {f g : a --> b}\n           (θ : f ==> g)\n           (γ : g ==> f)\n  : is_invertible_2cell θ\n  := γ.\n\nDefinition inv_cell {C : wild_cat} {a b : C} {f g : a --> b} {θ : f ==> g}\n  (c : is_invertible_2cell θ) : g ==> f := c.\n\nNotation \"inv_θ ^-1\" := (inv_cell inv_θ) : bicategory_scope.\n\nDefinition is_invertible_2cell_inv {C : prebicat_data} {a b : C} {f g : a --> b}\n           {θ : f ==> g} (inv_θ : is_invertible_2cell θ)\n  : is_invertible_2cell (inv_θ^-1)\n  := make_is_invertible_2cell _ θ.\n\nDefinition is_invertible_2cell_id₂ {C : prebicat} {a b : C} (f : a --> b)\n  : is_invertible_2cell (id2 f)\n  := make_is_invertible_2cell (id2 f) (id2 f).\n\nDefinition invertible_2cell {C : wild_cat}\n           {a b : C} (f g : a --> b) : UU\n  := ∑ θ : f ==> g, is_invertible_2cell θ.\n\nDefinition make_invertible_2cell {C : wild_cat}\n           {a b : C} {f g : a --> b}\n           {θ : f ==> g} (inv_θ : is_invertible_2cell θ)\n  : invertible_2cell f g\n  := θ,, inv_θ.\n\nCoercion cell_from_invertible_2cell {C : wild_cat}\n         {a b : C} {f g : a --> b} (θ : invertible_2cell f g)\n  : f ==> g\n  := pr1 θ.\n\nCoercion property_from_invertible_2cell {C : wild_cat}\n         {a b : C} {f g : a --> b}\n         (θ : invertible_2cell f g)\n  : is_invertible_2cell θ\n  := pr2 θ.\n\nDefinition id2_invertible_2cell {C : prebicat} {a b : C} (f : a --> b)\n  : invertible_2cell f f\n  := make_invertible_2cell (is_invertible_2cell_id₂ f).\n\n(** Equivalence of objects **)\nDefinition are_equivalent {C : wild_cat} (a b : C)\n  : UU\n  := ∑ (f : a --> b) (g : b --> a), f · g ==> identity a × g · f ==> identity b.\n", "meta": {"author": "nmvdw", "repo": "Integers", "sha": "433c6af04e9dd265e1de5f57b1a98a742f4aaad1", "save_path": "github-repos/coq/nmvdw-Integers", "path": "github-repos/coq/nmvdw-Integers/Integers-433c6af04e9dd265e1de5f57b1a98a742f4aaad1/WildCategories/WildCat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6563393036327498}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra vector reals ereal classical_sets.\nFrom mathcomp Require Import zmodp.\nRequire Export preliminaries preliminaries_hull axiomsKnuth.\n\n(******************************************************************************)\n(*   encompass oriented s l == oriented is a ternary relation, s and l        *)\n(*                             are lists of points such that                  *)\n(*                             oriented l_i l_i.+1 s_k for all i and k        *)\n(*   encompass_aux oriented l h == h describes an open convex region that     *)\n(*                             contains l                                     *)\n(*   encompass oriented l h == h describes a convex hull for the set of       *)\n(*                             points l where the last segment is formed by   *)\n(*                             the last and first elements                    *)\n(******************************************************************************)\n\nImport Order.POrderTheory Order.TotalTheory GRing.Theory Num.Theory.\n\nLocal Open Scope ring_scope.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection spec.\nVariable plane : zmodType.\nVariable oriented : plane -> plane -> plane -> bool.\n\nDefinition is_left (p q r : plane) := [|| r == p, r == q | oriented p q r].\nHint Unfold is_left : core.\n\nDefinition all_left (x y : plane) : seq plane -> bool := all (is_left x y).\n\nFixpoint encompass_aux (l h : seq plane) : bool :=\n  match h with\n  | nil => false\n  | t1 :: nil => true\n  | t1 :: ((t2 :: _) as h') => all_left t1 t2 l && encompass_aux l h'\n  end.\n\nDefinition encompass (s h : seq plane) :=\n  match h with\n  | nil => false\n  | t :: h' => encompass_aux s (last t h' :: h)\n  end.\n\nLemma encompassl0 l : encompass l [::] = false.\nProof. by []. Qed.\n\nDefinition convexHullSpec (l h : seq plane) :=\n  uniq h && all (mem l) h && encompass l h.\n\n(* TOTHINK: replace encompass : seq -> seq -> bool by a predicate\n   seq -> plane -> bool? *)\n\nLemma encompass_auxE (l h : seq plane) :\n  encompass_aux l h = (h != [::]) && all (fun x => encompass_aux [:: x] h) l.\nProof.\nelim: h =>// a'; case=> [ _ | b' l' IHl'].\n   by elim: l.\nrewrite /= -/(encompass_aux l (b' :: l')) IHl' -all_predI; apply eq_all=>x.\nby rewrite /= andbT.\nQed.\n\nLemma encompassE (s h : seq plane) :\n  encompass s h = (h != [::]) && all (fun x => encompass [:: x] h) s.\nProof. by case: h =>// a l; rewrite {1}/encompass encompass_auxE. Qed.\n\nLemma encompass_aux_all_index (l h : seq plane) :\n  encompass_aux l h = (h != [::]) &&\n    [forall i : 'I_(size h), (i.+1mod == 0%N :> nat) || all_left h`_i h`_i.+1mod l].\nProof.\nelim: h=>// a; case.\n   by move=>/= _; apply/esym/forallP => i; rewrite modn1 eq_refl.\nmove=>b l' IHl' /=; rewrite -/(encompass_aux l (b :: l')) IHl' /=.\napply/idP/idP => [/andP[Habl H]|/forallP H].\n  apply/forallP => -[] [//|n/=].\n  rewrite ltnS => nlt.\n  move: H => /forallP/(_ (Ordinal nlt)).\n  move: nlt (nlt); rewrite {1}ltnS leq_eqVlt => /predU1P[-> mm _|nm nm1].\n    by rewrite modnn eqxx.\n  by rewrite modn_small ?ltnS// modn_small ?ltnS.\napply/andP; split; first by move: H => /(_ ord0).\napply/forallP => -[i ilt].\nmove: H => /(_ (lift ord0 (Ordinal ilt))).\nmove: ilt (ilt); rewrite {1}ltnS leq_eqVlt => /predU1P[-> mm _|ilt ilt1].\n  by rewrite modnn eqxx.\nby rewrite modn_small ?ltnS// modn_small ?ltnS.\nQed.\n\nLemma encompass_all_index (l s : seq plane) : encompass s l =\n  (l != [::]) && [forall i : 'I_(size l), all_left l`_i l`_i.+1mod s].\nProof.\ncase: l => // a l /=.\nrewrite -/(encompass_aux s (a :: l)) encompass_aux_all_index.\napply/idP/idP => [H|/forallP H].\n   apply/forallP => -[i ilt].\n   move: ilt (ilt); rewrite {1}ltnS leq_eqVlt => /predU1P[-> /= _|ilt ilt1].\n     by rewrite modnn nth_last /=; move: H => /andP[H _].\n   move: H => /andP[_ /andP [_ /forallP]] /(_ (Ordinal ilt1)) /=.\n   by rewrite modn_small ?ltnS.\napply/andP; split.\n   by move: H => /(_ ord_max); rewrite /= modnn nth_last.\napply/forallP => -[i ilt].\nmove: ilt (ilt); rewrite {1}ltnS leq_eqVlt => /predU1P[-> /= _|ilt ilt1].\n  by rewrite modnn.\nby move: H => /(_ (Ordinal ilt1))/=; rewrite modn_small ?ltnS.\nQed.\n\nEnd spec.\n\nModule SpecKA (KA : KnuthAxioms).\nSection Dummy.\nVariable R : realType.\nLet plane := pair_vectType (regular_vectType R) (regular_vectType R).\n\nLet oriented := KA.OT (R:=R).\nLet Ax1 := KA.Axiom1 (R:=R).\nLet Ax2 := KA.Axiom2 (R:=R).\nLet Ax5 := KA.Axiom5 (R:=R).\nLet Ax5' := KA.Axiom5' (R:=R).\n\nLemma encompassll_spec (l : seq plane) : uniq l ->\n  encompass oriented l l =\n  (l != [::]) &&\n    [forall i : 'I_(size l), [forall j : 'I_(size l), [forall k : 'I_(size l),\n      (i < j < k)%N ==> oriented l`_i l`_j l`_k]]].\nProof.\nmove=> /uniqP-/(_ 0%R) lu; apply/idP/idP.\n  rewrite encompassE => /andP[-> /allP] ll /=.\n  have sD i j : (i.+1 < size l)%N -> (j < size l)%N -> j != i -> j != i.+1 ->\n      oriented l`_i l`_i.+1 l`_j.\n    move=> isl jl ji jis.\n    have /ll : l`_j \\in l by rewrite mem_nth.\n    have il : (i < size l)%N by rewrite (leq_trans _ isl).\n    rewrite encompass_all_index => /andP[_] /forallP /(_ (Ordinal il)) /=.\n    rewrite Zp_succE andbT/= modn_small// => /or3P[| |//] /eqP/lu; rewrite 2!inE.\n       by move=> /(_ jl il)/eqP; rewrite (negbTE ji).\n    by move=>/(_ jl isl)/eqP; rewrite (negbTE jis).\n  apply/'forall_'forall_'forall_implyP => -[i ilt] [j jlt] [k klt] /= /andP[ij jk].\n  elim: k => // k IHk in klt jk *.\n  have {}IHk := IHk (ltnW klt).\n  move: jk; rewrite leq_eqVlt => /predU1P[[jk]|].\n    subst j.\n    do 2 apply: Ax1.\n    apply: sD => //; first by rewrite ltn_eqF.\n    by rewrite ltn_eqF// (leq_trans ij).\n  rewrite ltnS => jk; have {}IHk := IHk jk.\n  move: ij; rewrite leq_eqVlt => /predU1P[ij|ij].\n    subst j.\n    apply: sD => //.\n      by rewrite gtn_eqF// ltnS (leq_trans _ jk)// -addn2 leq_addr.\n    by rewrite gtn_eqF// (leq_trans jk).\n  apply: (@Ax5 _ l`_i.+1 _ l`_k).\n  - apply: sD => //; first by rewrite (leq_trans ij)// ltnW.\n      by rewrite gtn_eqF// (ltn_trans _ ij).\n    by rewrite gt_eqF.\n  - apply: sD; first by rewrite (leq_trans ij)// ltnW.\n        by rewrite (ltn_trans _ klt).\n      by rewrite gtn_eqF// (ltn_trans _ jk)// (ltn_trans _ ij).\n    by rewrite gtn_eqF// (ltn_trans ij).\n  - apply: sD => //; first by rewrite (leq_trans ij)// ltnW.\n      rewrite gtn_eqF// ltnS (leq_trans _ (ltnW jk))// (leq_trans _ ij)//.\n      by rewrite -addn2 leq_addr.\n    by rewrite gtn_eqF// (leq_trans ij)// (leq_trans (ltnW jk)).\n  - exact IHk.\n  - do 2 apply Ax1.\n    apply: sD => //.\n      by rewrite ltn_eqF// (ltn_trans _ jk)// (leq_trans _ ij).\n    by rewrite ltn_eqF// ltnS (leq_trans _ (ltnW jk))// ltnW// (ltn_trans _ ij).\nrewrite encompassE => /andP[l0 sD] /=; rewrite l0 /=.\nhave id x : x \\in l -> exists2 n, (n < size l)%N & l`_n = x.\n   by move=> xl; exists (index x l); [rewrite index_mem|rewrite nth_index].\napply/allP => _ /id[i il <-].\nrewrite encompass_all_index; rewrite l0; apply/forallP => -[j jlt].\nrewrite /all_left/= /is_left/= andbT.\nhave [->|ij] := eqVneq i j.\n   exact/or3P/Or31.\ndestruct l as [|a l] => //=.\nhave [ijs|ijs] := eqVneq i (j.+1 %% (size l).+1)%N.\n   by apply/or3P/Or32; rewrite -ijs.\napply/or3P/Or33; move: jlt; rewrite leq_eqVlt => /predU1P[[je]|jlt].\n   subst j; rewrite modnn.\n   do 2 apply Ax1.\n   move: sD => /'forall_'forall_'forall_implyP\n               /(_ ord0 (Ordinal il) (Ordinal (leqnn _)));\n               apply => /=.\n   rewrite lt0n.\n   move: ijs; rewrite modnn => ->/=.\n   move: il; rewrite leq_eqVlt => /predU1P[[/eqP]|].\n      by rewrite (negbTE ij).\n   by rewrite ltnS.\nmove:ijs; rewrite modn_small => // ijs.\nhave [ji|ji] := ltnP j.+1 i.\n   move: sD => /'forall_'forall_'forall_implyP\n               /(_ (Ordinal (leq_trans (leqnSn _) jlt)) (Ordinal jlt) (Ordinal il)).\n   apply => /=.\n   by rewrite ltnS leqnn.\napply: Ax1.\nmove: sD => /'forall_'forall_'forall_implyP\n            /(_ (Ordinal il) (Ordinal (leq_trans (leqnSn _) jlt)) (Ordinal jlt)).\napply => /=.\nrewrite ltnS leqnn andbT ltnNge.\nrewrite leq_eqVlt eq_sym (negbTE ij)/=.\nrewrite leq_eqVlt eq_sym (negbTE ijs)/=.\nby rewrite ltnNge ji.\nQed.\n\nLemma encompassll_subseq (l l' : seq plane) : uniq l ->\n  encompass oriented l l ->\n  subseq l' l ->\n  l' != [::] ->\n  encompass oriented l' l'.\nProof.\nmove=> lu; rewrite (encompassll_spec lu) => ll l'l l'0.\nhave l'u := subseq_uniq l'l lu; rewrite (encompassll_spec l'u) l'0 /=.\napply/'forall_'forall_'forall_implyP => i j k /andP[ij jk].\nmove: l'l => /subseq_incl-/(_ 0%R) [f [fl flt]].\nmove: ll => /andP[_] /'forall_'forall_'forall_implyP\n  /(_ (f i)) /(_ (f j)) /(_ (f k)); rewrite 3!fl; apply.\nby apply/andP; split; apply: flt.\nQed.\n\nEnd Dummy.\nEnd SpecKA.\n", "meta": {"author": "math-comp", "repo": "trajectories", "sha": "cc6e1298208a93592230f5b4ee3228a024aa03e7", "save_path": "github-repos/coq/math-comp-trajectories", "path": "github-repos/coq/math-comp-trajectories/trajectories-cc6e1298208a93592230f5b4ee3228a024aa03e7/theories/encompass.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6562876747917281}}
{"text": "Definition N := 4.\n\nInductive tree : Type :=\n| Leaf : tree\n| Node : nat -> tree -> tree -> tree.\n\nFixpoint binary_tree c n :=\n  match n with\n  | 0 => Leaf\n  | S n =>\n    let t := binary_tree c n in\n    Node c t t\n  end.\n\nDefinition t0 := Eval vm_compute in binary_tree 0 N.\nDefinition t1 := Eval vm_compute in binary_tree 1 N.\n", "meta": {"author": "eponier", "repo": "compare-eq", "sha": "cc2da184e747d0ad6ada8597e1ebf03377e413e2", "save_path": "github-repos/coq/eponier-compare-eq", "path": "github-repos/coq/eponier-compare-eq/compare-eq-cc2da184e747d0ad6ada8597e1ebf03377e413e2/equality_test/4/type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6562876645099357}}
{"text": "Set Implicit Arguments.\n\nLocal Open Scope nat.\n\nRequire Import Coq.Arith.Le.\nRequire Import Coq.Arith.Max.\n\nLtac max_solver :=\n  repeat\n    match goal with\n      | |- ?A <= ?A => eapply le_n\n      | |- 0 <= _ => eapply le_0_n\n      | |- max _ _ <= _ => eapply max_lub\n      | |- ?S <= max ?A _ =>\n        match A with\n            context [ S ] => eapply le_trans; [ | eapply le_max_l]\n        end\n      | |- ?S <= max _ ?B =>\n        match B with\n            context [ S ] => eapply le_trans; [ .. | eapply le_max_r]\n        end\n    end.\n\nLemma both_le : forall a b a' b', a <= a' -> b <= b' -> max a b <= max a' b'.\n  intros; max_solver; eauto.\n  eapply le_trans; [ | eapply le_max_l]; eauto.\n  eapply le_trans; [ | eapply le_max_r]; eauto.\nQed.\n\nLocal Close Scope nat.", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/Cito/MaxFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6562876542281428}}
{"text": "Require Import GeoCoq.Axioms.parallel_postulates.\nRequire Import GeoCoq.Tarski_dev.Annexes.saccheri.\n\nSection triangle_existential_triangle.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma triangle__existential_triangle : triangle_postulate -> postulate_of_existence_of_a_triangle_whose_angles_sum_to_two_rights.\nProof.\n  intro triangle.\n  destruct lower_dim_ex as [A [B [C]]].\n  assert(~ Col A B C) by (unfold Col; assumption).\n  assert_diffs.\n  destruct (ex_trisuma A B C) as [D [E [F]]]; auto.\n  exists A; exists B; exists C; exists D; exists E; exists F.\n  repeat split.\n    assumption.\n    assumption.\n    apply (triangle A B C); assumption.\nQed.\n\nEnd triangle_existential_triangle.", "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/triangle_existential_triangle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6562876473441447}}
{"text": "Require Import Lia.\nRequire Import Nat.\nFrom Cyclic_PA.Maths Require Import naturals.\nFrom Cyclic_PA.Maths Require Import ordinals.\nFrom Cyclic_PA.Logic Require Import definitions.\nFrom Cyclic_PA.Logic Require Import fol.\nFrom Cyclic_PA.Logic Require Import PA_omega.\nFrom Cyclic_PA.Logic Require Import proof_trees.\nFrom Cyclic_PA.Logic Require Import substitute.\n\nFrom Cyclic_PA.Logic Require Import formula_sub.\nFrom Cyclic_PA.Logic Require Import inverse_neg.\nFrom Cyclic_PA.Logic Require Import inverse_dem_1.\nFrom Cyclic_PA.Logic Require Import inverse_dem_2.\nFrom Cyclic_PA.Logic Require Import inverse_omega.\nFrom Cyclic_PA.Logic Require Import inverse_quantif.\n\nFixpoint cut_elimination_atom (P : ptree) : ptree :=\nmatch P with\n| cut_ca C (atom a) d1 d2 alpha1 alpha2 P1 P2 =>\n  (match PA_omega_axiom (atom a) with\n  | true =>\n      formula_sub_ptree P2 (neg (atom a)) C (1)\n  | false =>\n      contraction_a\n        C d1 alpha1\n        (formula_sub_ptree P1 (atom a) C (lor_ind (non_target C) (1)))\n  end)\n\n| cut_ad (atom a) D d1 d2 alpha1 alpha2 P1 P2 =>\n  (match PA_omega_axiom (atom a) with\n  | true =>\n      contraction_a\n        D d2 alpha2\n        (formula_sub_ptree P2 (neg (atom a)) D (lor_ind (1) (non_target D)))\n  | false =>\n      formula_sub_ptree P1 (atom a) D (1)\n  end)\n\n| cut_cad C (atom a) D d1 d2 alpha1 alpha2 P1 P2 =>\n  (match PA_omega_axiom (atom a) with\n  | true =>\n      weakening_ad C D d2 alpha2\n        (contraction_a\n          D d2 alpha2\n          (formula_sub_ptree P2 (neg (atom a)) D (lor_ind (1) (non_target D))))\n  | false =>\n      exchange_ab\n        D C d1 (ord_succ alpha1)\n        (weakening_ad\n          D C d1 alpha1\n          (contraction_a\n            C d1 alpha1\n            (formula_sub_ptree P1 (atom a) C (lor_ind (non_target C) (1)))))\n  end)\n| deg_up d P' => cut_elimination_atom P'\n| ord_up alpha P' => cut_elimination_atom P'\n| _ => P\nend.\n\nFixpoint cut_elimination_neg (P : ptree) : ptree :=\nmatch P with\n| cut_ca C (neg E) d1 d2 alpha1 alpha2 P1 P2 =>\n    cut_ad\n      E C d2 d1 alpha2 alpha1\n      (dub_neg_sub_ptree P2 E (1))\n      (exchange_ab C (neg E) d1 alpha1 P1)\n\n| cut_ad (neg E) D d1 d2 alpha1 alpha2 P1 P2 =>\n    cut_ca\n      D E d2 d1 alpha2 alpha1\n      (exchange_ab\n        E D d2 alpha2\n        (dub_neg_sub_ptree P2 E (lor_ind (1) (non_target D))))\n      P1\n\n| cut_cad C (neg E) D d1 d2 alpha1 alpha2 P1 P2 =>\n    exchange_ab\n      D C (ptree_deg (cut_cad\n      D E C d2 d1 alpha2 alpha1\n      (exchange_ab\n      E D d2 alpha2\n        (dub_neg_sub_ptree P2 E (lor_ind (1) (non_target D))))\n          (exchange_ab C (neg E) d1 alpha1 P1))) (ptree_ord P)\n        (cut_cad\n          D E C d2 d1 alpha2 alpha1\n          (exchange_ab\n          E D d2 alpha2\n            (dub_neg_sub_ptree P2 E (lor_ind (1) (non_target D))))\n              (exchange_ab C (neg E) d1 alpha1 P1))\n| deg_up d P' => cut_elimination_neg P'\n| ord_up alpha P' => cut_elimination_neg P'\n| _ => P\nend.\n\nDefinition associativity_1' (P : ptree) : ptree :=\nmatch ptree_formula P, ptree_deg P, ptree_ord P with\n| lor (lor C A) B, d, alpha =>\n    exchange_ab\n      (lor A B) C d alpha\n      (exchange_cab\n        A C B d alpha\n        (exchange_abd C A B d alpha P))\n\n| _, _, _ => P\nend.\n\nDefinition associativity_2' (P : ptree) : ptree :=\nmatch ptree_formula P, ptree_deg P, ptree_ord P with\n| lor C (lor A B), d, alpha =>\n    exchange_abd\n      A C B d alpha\n      (exchange_cab\n        A B C d alpha\n        (exchange_ab C (lor A B) d alpha P))\n\n| _, _, _ => P\nend.\n\nLemma associativity1_valid :\n    forall (P : ptree),\n        valid P ->\n            valid (associativity_1' P).\nProof.\nintros P PV.\nunfold associativity_1'.\ndestruct (ptree_formula P) eqn:PF;\ntry apply PV.\ndestruct f1;\ntry apply PV.\nrepeat split.\napply PF.\napply PV.\nQed.\n\nLemma associativity2_valid :\n    forall (P : ptree),\n        valid P ->\n            valid (associativity_2' P).\nProof.\nintros P PV.\nunfold associativity_2'.\ndestruct (ptree_formula P) eqn:PF;\ntry apply PV.\ndestruct f2;\ntry apply PV.\nrepeat split.\napply PF.\napply PV.\nQed.\n\nDefinition contraction_help (P : ptree) : ptree :=\nmatch ptree_formula P, ptree_deg P, ptree_ord P with\n| lor (lor C D) E, d, alpha =>\n    (match form_eqb D E with\n    | true =>\n        exchange_ab\n          D C d alpha\n          (contraction_ad\n            D C d alpha\n            (exchange_cab\n              D C D d alpha\n              (exchange_abd C D D d alpha P)))\n\n    | false => P\n    end)\n\n| _, _, _ => P\nend.\n\nFixpoint cut_elimination_lor (P : ptree) : ptree :=\nmatch P with\n| cut_ca C (lor E F) d1 d2 alpha1 alpha2 P1 P2 =>\n    cut_ca\n      C E\n      (max (max d1 d2) (S (num_conn F)))\n      d2\n      (ord_succ (ord_max alpha1 alpha2))\n      alpha2\n      (cut_ca (lor C E) F d1 d2 alpha1 alpha2\n        (associativity_2' P1)\n        (demorgan2_sub_ptree P2 E F (1)))\n      (demorgan1_sub_ptree P2 E F (1))\n\n| cut_ad (lor E F) D d1 d2 alpha1 alpha2 P1 P2 =>\n    contraction_a\n      D\n      (max (max d1 d2) (max (S (num_conn E)) (S (num_conn F))))\n      (ord_succ (ord_succ (ord_max alpha1 alpha2)))\n      (cut_cad\n        D E D\n        (max (max d1 d2) (S (num_conn F)))\n        d2\n        (ord_succ (ord_max alpha1 alpha2))\n        alpha2\n        (exchange_ab\n          E D\n          (max (max d1 d2) (S (num_conn F)))\n          (ord_succ (ord_max alpha1 alpha2))\n          (cut_cad\n            E F D d1 d2 alpha1 alpha2 P1\n            (demorgan2_sub_ptree P2 E F (lor_ind (1) (non_target D)))))\n        (demorgan1_sub_ptree P2 E F (lor_ind (1) (non_target D))))\n\n| cut_cad C (lor E F) D d1 d2 alpha1 alpha2 P1 P2 =>\n    contraction_help\n      (cut_cad\n        (lor C D) E D\n        (max (max d1 d2) (S (num_conn F)))\n        d2\n        (ord_succ (ord_max alpha1 alpha2))\n        alpha2\n        (exchange_cab\n          C E D\n          (max (max d1 d2) (S (num_conn F)))\n          (ord_succ (ord_max alpha1 alpha2))\n          (cut_cad (lor C E) F D d1 d2 alpha1 alpha2\n            (associativity_2' P1)\n            (demorgan2_sub_ptree P2 E F (lor_ind (1) (non_target D)))))\n        (demorgan1_sub_ptree P2 E F (lor_ind (1) (non_target D))))\n\n| deg_up d P' => cut_elimination_lor P'\n| ord_up alpha P' => cut_elimination_lor P'\n| _ => P\nend.\n\nFixpoint cut_elimination (P : ptree) : ptree :=\nmatch P with\n| cut_ca C A d1 d2 alpha1 alpha2 P1 P2 =>\n  (match A with\n  | atom a => cut_elimination_atom P\n  | neg E => cut_elimination_neg P\n  | lor E F => cut_elimination_lor P\n  | univ n E => P\n  end)\n| cut_ad A D d1 d2 alpha1 alpha2 P1 P2 =>\n  (match A with\n  | atom a => cut_elimination_atom P\n  | neg E => cut_elimination_neg P\n  | lor E F => cut_elimination_lor P\n  | univ n E => P\n  end)\n| cut_cad C A D d1 d2 alpha1 alpha2 P1 P2 =>\n  (match A with\n  | atom a => cut_elimination_atom P\n  | neg E => cut_elimination_neg P\n  | lor E F => cut_elimination_lor P\n  | univ n E => P\n  end)\n| deg_up d P' => cut_elimination P'\n| ord_up alpha P' => cut_elimination P'\n| _ => P\nend.\n\nTheorem cut_elimination_formula :\n    forall (P : ptree),\n        valid P ->\n            ptree_formula (cut_elimination P) = ptree_formula P.\nProof.\nintros P PV.\ninduction P;\nunfold cut_elimination, cut_elimination_atom, cut_elimination_neg, cut_elimination_lor; fold cut_elimination.\n\n1,2 : apply IHP;\n      apply PV.\n\nall : try reflexivity;\n      destruct PV as [[[[[[[P1F P1V] P2F] P2V] P1D] P2D] P1O] P2O];\n      unfold PA_omega_axiom.\n\n2 : destruct f.\n1,6 : destruct f0.\n1,5,9 : destruct (correct_a a).\n\nall : unfold ptree_formula;\n      fold ptree_formula;\n      try reflexivity.\n\n3 : { unfold contraction_help, ptree_formula;\n      rewrite form_eqb_refl;\n      reflexivity. }\n2 : { rewrite (formula_sub_ptree_formula_atom P1 a f0 P1V (1)).\n      rewrite P1F.\n      apply formula_sub_ind_1.\n      unfold subst_ind_fit.\n      reflexivity. }\n\n1 : { rewrite (formula_sub_ptree_formula_neg P2 a f P2V (1));\n      rewrite P2F.\n      apply formula_sub_ind_1.\n      unfold subst_ind_fit.\n      reflexivity. }\nQed.\n\n(*********TEMPORARY***********)\n\nLemma weak_ord_height :\n    forall (P : ptree) (alpha : ord),\n        ord_ltb alpha (ptree_ord P) = false ->\n            ptree_ord (weak_ord_up P alpha) = alpha .\nProof.\nintros P alpha IO.\nunfold weak_ord_up.\ndestruct (ord_semiconnex_bool (ptree_ord P) alpha) as [LT | [GT | EQ]].\nrewrite LT. reflexivity.\nrewrite GT in IO. inversion IO.\napply ord_eqb_eq in EQ. destruct EQ.\nrewrite ord_ltb_irrefl.\nreflexivity.\nQed.\n\n\nTheorem cut_elimination_ord :\n    forall (P : ptree),\n        valid P ->\n            ord_ltb (ord_2_exp (ptree_ord P)) (ptree_ord (cut_elimination P)) = false.\nProof.\nintros P PV.\npose (ptree_ord P) as alpha.\npose proof (ptree_ord_nf _ PV) as NA.\ninduction P;\nunfold cut_elimination, cut_elimination_atom, cut_elimination_neg, cut_elimination_lor; fold cut_elimination.\n\n1 : destruct PV as [ID PV].\n2 : destruct PV as [[IO PV] NO].\n4-9 : destruct PV as [[[PF PV] PD] PO].\n10 :  destruct PV as [[[[PF FC] PV] PD] PO].\n11,12 : destruct PV as [[[[[[[P1F P1V] P2F] P2V] P1D] P2D] P1O] P2O].\n13-16 : destruct PV as [[[PF PV] PD] PO].\n19-21 : destruct PV as [[[[[[[P1F P1V] P2F] P2V] P1D] P2D] P1O] P2O].\n\n2 : { fold cut_elimination cut_elimination_atom cut_elimination_neg cut_elimination_lor. fold cut_elimination.\n      unfold ptree_ord; fold ptree_ord.\n      pose proof (IHP PV (ptree_ord_nf _ PV)) as IHPV.\n      destruct (ord_semiconnex_bool (ord_2_exp (ptree_ord P)) (ptree_ord (cut_elimination P))) as [LT | [ GT | EQ]].\n    + rewrite LT in IHPV.\n      inversion IHPV.\n    + apply (ord_ltb_asymm _ _ (ord_ltb_trans _ _ _ GT (ord_lt_ltb _ _ (ord_2_exp_monot _ NO _ (ptree_ord_nf _ PV) IO)))).\n    + apply ord_eqb_eq in EQ.\n      destruct EQ.\n      apply (ord_ltb_asymm _ _ (ord_lt_ltb _ _ (ord_2_exp_monot _ NO _ (ptree_ord_nf _ PV) IO))). }\n\n1 : { fold cut_elimination cut_elimination_atom cut_elimination_neg cut_elimination_lor. fold cut_elimination.\n      unfold ptree_ord; fold ptree_ord.\n      apply (IHP PV NA). }\n\nall : unfold ptree_ord in *; fold ptree_ord in *;\n      try apply (ord_ltb_exp_false _ NA);\n      unfold PA_omega_axiom.\n\n2 : destruct f.\n1,6 : destruct f0.\n1,5,9 : destruct (correct_a a).\n\nall : unfold contraction_help, ptree_formula, ptree_ord;\n      try rewrite form_eqb_refl;\n      try rewrite formula_sub_ptree_ord_atom;\n      try rewrite formula_sub_ptree_ord_neg;\n      try rewrite P1O in *;\n      try rewrite P2O in *;\n      try apply P1V;\n      try apply P2V;\n      fold ptree_ord;\n      try apply ord_ltb_exp_false;\n      try apply NA.\n\n7,10 : rewrite (ord_max_symm (ptree_ord P2)).\n9,10 : rewrite (ord_max_ltb_not_l _ _ (ord_ltb_asymm _ _ (ord_lt_ltb _ _ (ord_lt_max_succ_r _ _)))).\n7,9,10 : apply (ord_ltb_succ_leb _ _ NA (nf_2_exp _ NA) (ord_lt_ltb _ _ (ord_succ_not_exp_fp _ NA))).\n\nall : apply (ord_geb_trans _ (ord_succ (ord_max (ptree_ord P1) (ptree_ord P2))));\n      try apply (ord_geb_trans (ord_2_exp (ord_succ (ord_succ (ord_max (ptree_ord P1) (ptree_ord P2))))) (ord_succ (ord_succ (ord_max (ptree_ord P1) (ptree_ord P2)))) (ord_succ (ord_max (ptree_ord P1) (ptree_ord P2))));\n      try apply (ord_ltb_asymm _ _ (ord_lt_ltb _ _ (ord_succ_monot _)));\n      try apply (ord_ltb_exp_false _ NA);\n      try apply ord_geb_succ;\n      try apply (ord_ltb_asymm _ _ (ord_lt_ltb _ _ (ord_lt_max_succ_l _ _)));\n      try apply (ord_ltb_asymm _ _ (ord_lt_ltb _ _ (ord_lt_max_succ_r _ _)));\n      try apply ord_ltb_irrefl;\n      try apply ord_max_geb_l;\n      try apply ord_max_geb_r.\nQed.\n\nTheorem cut_elimination_valid :\n    forall (P : ptree),\n        valid P ->\n            valid (cut_elimination P).\nProof.\nintros P PV.\npose (ptree_ord P) as alpha.\npose proof (ptree_ord_nf _ PV) as NA.\ninduction P;\nunfold cut_elimination, cut_elimination_atom, cut_elimination_neg, cut_elimination_lor; fold cut_elimination.\n\n1 : destruct PV as [ID PV].\n2 : destruct PV as [[IO PV] NO].\n4-9 : destruct PV as [[[PF PV] PD] PO].\n10 :  destruct PV as [[[[PF FC] PV] PD] PO].\n11,12 : destruct PV as [[[[[[[P1F P1V] P2F] P2V] P1D] P2D] P1O] P2O].\n13-16 : destruct PV as [[[PF PV] PD] PO].\n19-21 : destruct PV as [[[[[[[P1F P1V] P2F] P2V] P1D] P2D] P1O] P2O].\n\n1,2 : apply (IHP PV (ptree_ord_nf _ PV)).\n\n17,18,19 : unfold PA_omega_axiom.\n19 :  destruct f0; try case (correct_a a) eqn:Ra;\n      unfold contraction_help, ptree_formula;\n      try rewrite form_eqb_refl.\n18 : destruct f; try case (correct_a a) eqn:Ra.\n17 : destruct f0; try case (correct_a a) eqn:Ra.\n\nall : unfold associativity_1', associativity_2';\n      try rewrite P1F;\n      try rewrite P2F;\n      repeat split;\n      unfold ptree_ord, ptree_deg, ptree_formula;\n      fold ptree_ord ptree_deg ptree_formula;\n      try apply dub_neg_valid;\n      try apply demorgan1_valid;\n      try apply demorgan2_valid;\n      try rewrite (formula_sub_ptree_deg_atom _ _ _ P1V);\n      try rewrite (formula_sub_ptree_deg_neg _ _ _ P2V);\n      try rewrite (dub_neg_ptree_deg _ _ P2V);\n      try rewrite (demorgan1_ptree_deg _ _ _ P2V);\n      try rewrite (demorgan2_ptree_deg _ _ _ P2V);\n      try rewrite (formula_sub_ptree_ord_atom _ _ _ P1V);\n      try rewrite (formula_sub_ptree_ord_neg _ _ _ P2V);\n      try rewrite (dub_neg_ptree_ord _ _ P2V);\n      try rewrite (demorgan1_ptree_ord _ _ _ P2V);\n      try rewrite (demorgan2_ptree_ord _ _ _ P2V);\n      try rewrite (formula_sub_ptree_formula_atom _ _ _ P1V);\n      try rewrite (formula_sub_ptree_formula_neg _ _ _ P2V);\n      try rewrite (dub_neg_ptree_formula _ _ P2V);\n      try rewrite (demorgan1_ptree_formula _ _ _ P2V);\n      try rewrite (demorgan2_ptree_formula _ _ _ P2V);\n      try apply PF;\n      try apply P1F;\n      try apply P2F;\n      try rewrite P1F;\n      try rewrite P2F;\n      unfold dub_neg_sub_formula, demorgan1_sub_formula, demorgan2_sub_formula, formula_sub_ind, num_conn;\n      unfold subst_ind_fit; fold subst_ind_fit;\n      unfold formula_sub_ind_fit; fold formula_sub_ind_fit;\n      try rewrite non_target_fit;\n      try rewrite form_eqb_refl;\n      unfold \"&&\";\n      try rewrite non_target_sub';\n      try apply PV;\n      try apply P1V;\n      try apply P2V;\n      try apply PD;\n      try apply P1D;\n      try apply P2D;\n      try apply PO;\n      try apply P1O;\n      try apply P2O;\n      try apply FC;\n      try reflexivity;\n      try lia.\n\n10 :  rewrite ord_max_symm;\n      reflexivity.\n\n5 : rewrite (ord_max_ltb_not_l _ _ (ord_ltb_asymm _ _ (ord_lt_ltb _ _ (ord_lt_max_succ_r _ _))));\n    reflexivity.\n\nall : try apply (formula_sub_valid_atom _ _ _ P1V Ra);\n      try apply (formula_sub_valid_neg _ _ _ P2V Ra);\n      pose proof (provable_closed' _ _ P1V P1F) as Cfa;\n      pose proof (provable_closed' _ _ P2V P2F) as Cf0a0;\n      try destruct (and_bool_prop _ _ Cfa) as [Cf Ca];\n      try destruct (and_bool_prop _ _ Cf0a0) as [Ca0 Cf0];\n      try apply Cf;\n      try apply Cf0;\n      try rewrite P1F;\n      try rewrite P2F;\n      unfold subst_ind_fit;\n      fold subst_ind_fit;\n      try rewrite non_target_fit;\n      try reflexivity.\nQed.\n\nLemma cut_elim_ord_Zero :\n    forall (P : ptree) (A : formula) (d : nat),\n        P_proves P A (S d) Zero ->\n            provable A d (ord_2_exp Zero).\nProof.\nunfold provable, P_proves.\nintros P.\ninduction P;\nintros A d [[[PF' PV] PD'] PO'];\nunfold ptree_deg, ptree_ord, ptree_formula in *;\nfold ptree_deg ptree_ord ptree_formula in *.\n\n1 : destruct PV as [ID PV];\n    exists (ord_up (ord_2_exp Zero) P).\n3 : exists (ord_up (ord_2_exp Zero) (node f)).\n\n1,3 : repeat split;\n      unfold ptree_formula;\n      try apply PF';\n      try destruct PO';\n      try apply zero_lt;\n      try apply PV;\n      try apply nf_2_exp;\n      try apply zero_nf;\n      unfold ptree_deg; fold ptree_deg;\n      lia.\n1 : { destruct PV as [[IO PV] NO].\n      destruct PO'.\n      exfalso.\n      inversion IO. }\n\n7-18 :  try pose proof (ord_succ_neb_zero o) as NZ1;\n        try pose proof (ord_succ_neb_zero (ord_max o o0)) as NZ2;\n        try pose proof (ord_succ_neb_zero (ord_succ (ord_max o o0))) as NZ3;\n        destruct PO';\n        inversion NZ1;\n        inversion NZ2;\n        inversion NZ3.\n\n1-6 : destruct PV as [[[PF PV] PD] PO];\n      destruct PF',PO',PD.\n\n1 : destruct (IHP _ _ (PF , PV , PD' , PO)) as [P1 [[[P1F P1V] P1D] P1O]];\n    exists (exchange_ab f f0 (ptree_deg P1) (ptree_ord P1) P1).\n  \n2 : destruct (IHP _ _ (PF , PV , PD' , PO)) as [P1 [[[P1F P1V] P1D] P1O]];\n    exists (exchange_cab f f0 f1 (ptree_deg P1) (ptree_ord P1) P1).\n\n3 : destruct (IHP _ _ (PF , PV , PD' , PO)) as [P1 [[[P1F P1V] P1D] P1O]];\n    exists (exchange_abd f f0 f1 (ptree_deg P1) (ptree_ord P1) P1).\n\n4 : destruct (IHP _ _ (PF , PV , PD' , PO)) as [P1 [[[P1F P1V] P1D] P1O]];\n    exists (exchange_cabd f f0 f1 f2 (ptree_deg P1) (ptree_ord P1) P1).\n\n5 : destruct (IHP _ _ (PF , PV , PD' , PO)) as [P1 [[[P1F P1V] P1D] P1O]];\n    exists (contraction_a f (ptree_deg P1) (ptree_ord P1) P1).\n\n6 : destruct (IHP _ _ (PF , PV , PD' , PO)) as [P1 [[[P1F P1V] P1D] P1O]];\n    exists (contraction_ad f f0 (ptree_deg P1) (ptree_ord P1) P1).\n\nall : repeat split;\n      try apply P1F;\n      try apply P1V;\n      try apply P1D;\n      apply P1O.\nQed.\n\nLemma height_zero_not_lor :\n    forall (P : ptree),\n        valid P ->\n            Zero = (ptree_ord P) ->\n                forall (A B : formula),\n                    (ptree_formula P) <> lor A B.\nProof.\nintros P PV PO'.\ninduction P.\n\n1 : destruct PV as [ID PV].\n2 : destruct PV as [[IO PV] NO].\n4-9 : destruct PV as [[[PF PV] PD] PO].\n10 :  destruct PV as [[[[PF FC] PV] PD] PO].\n11,12 : destruct PV as [[[[[[[P1F P1V] P2F] P2V] P1D] P2D] P1O] P2O].\n13-16 : destruct PV as [[[PF PV] PD] PO].\n19-21 : destruct PV as [[[[[[[P1F P1V] P2F] P2V] P1D] P2D] P1O] P2O].\n\nall : unfold ptree_ord in PO'; fold ptree_ord in PO'.\n\n1 : { apply (IHP PV PO'). }\n1 : { destruct PO'.\n      inversion IO. }\n\n1 : { intros A B.\n      unfold ptree_formula.\n      unfold valid, PA_omega_axiom in PV.\n      destruct f;\n      discriminate. }\n\n7-18 :  try pose proof (ord_succ_neb_zero o) as NZ1;\n        try pose proof (ord_succ_neb_zero (ord_max o o0)) as NZ2;\n        try pose proof (ord_succ_neb_zero (ord_succ (ord_max o o0))) as NZ3;\n        destruct PO';\n        inversion NZ1;\n        inversion NZ2;\n        inversion NZ3.\n\nall : try assert (ptree_formula P = ptree_formula P) as EQ;\n      try reflexivity;\n      unfold \"<>\" in *;\n      intros A B PF';\n      destruct PO';\n      try rewrite PF in *;\n      refine (IHP PV PO _ _ EQ).\nQed.\n\n\nLemma cut_elim_ord_one :\n    forall (P : ptree) (A : formula) (d : nat),\n        P_proves P A (S d) (cons Zero 0 Zero) ->\n            provable A d (ord_2_exp (cons Zero 0 Zero)).\nProof.\nunfold provable, P_proves.\nintros P.\ninduction P;\nintros A d [[[PF' PV] PD'] PO'];\nunfold ptree_deg, ptree_ord, ptree_formula in *;\nfold ptree_deg ptree_ord ptree_formula in *.\n\n1 : destruct PV as [ID PV].\n2 : destruct PV as [[IO PV] NO].\n4-9 : destruct PV as [[[PF PV] PD] PO].\n10 :  destruct PV as [[[[PF FC] PV] PD] PO].\n11,12 : destruct PV as [[[[[[[P1F P1V] P2F] P2V] P1D] P2D] P1O] P2O].\n13-16 : destruct PV as [[[PF PV] PD] PO].\n18 : destruct (PV czero) as [[[PF PzV] PD] PO].\n19-21 : destruct PV as [[[[[[[P1F P1V] P2F] P2V] P1D] P2D] P1O] P2O].\n\n1 : { exists (ord_up (ord_2_exp (cons Zero 0 Zero)) P).\n      repeat split.\n      - apply PF'.\n      - destruct PO'.\n        apply coeff_lt.\n        lia.\n      - apply PV.\n      - apply single_nf.\n        apply zero_nf.\n      - unfold ptree_deg; fold ptree_deg.\n        lia. }\n\n1 : { rewrite <- PO' in *.\n      pose proof (ord_lt_one _ IO) as EQ.\n      rewrite <- EQ in *.\n      unfold P_proves in *.\n      destruct (cut_elim_ord_Zero P A _ (PF' , PV , PD' , EQ)) as [P1 [[[P1F P1V] P1D] P1O]].\n      exists (ord_up (ord_2_exp (ord_2_exp Zero)) P1).\n      repeat split.\n      - apply P1F.\n      - destruct P1O.\n        apply coeff_lt.\n        lia.\n      - apply P1V.\n      - apply single_nf.\n        apply zero_nf.\n      - unfold ptree_deg; fold ptree_deg.\n        lia. }\n\n1 : { inversion PO'. }\n\n9,15,16,18 :  apply ord_succ_one in PO';\n              try destruct (ord_max_zero _ _ PO') as [OZ1 OZ2];\n              try destruct PO';\n              try destruct OZ1,OZ2;\n              try pose proof (height_zero_not_lor _ P1V P1O (neg f) f1) as NE1;\n              try pose proof (height_zero_not_lor _ P1V P1O f f0) as NE2;\n              try pose proof (height_zero_not_lor _ PzV PO (substitution f n (projT1 czero)) f0) as NE3;\n              try rewrite P1F in *;\n              try rewrite PF in *;\n              contradiction.\n\n14 :  { apply ord_succ_one in PO'.\n        pose proof (ord_succ_neb_zero (ord_max o o0)) as NE. \n        destruct PO'.\n        inversion NE. }\n\n8 : { apply ord_succ_one in PO'.\n      try destruct (ord_max_zero _ _ PO') as [OZ1 OZ2].\n      try destruct OZ1,OZ2.\n      assert (S (pred n) >= ptree_deg P1) as IE1. lia.\n      destruct (cut_elim_ord_Zero _ _ _ (P1F, P1V, IE1, P1O)) as [P3 [[[P3F P3V] P3D] P3O]].\n      assert (S (pred n0) >= ptree_deg P2) as IE2. lia.\n      destruct (cut_elim_ord_Zero _ _ _ (P2F, P2V, IE2, P2O)) as [P4 [[[P4F P4V] P4D] P4O]].\n      exists (demorgan_ab f f0 (ptree_deg P3) (ptree_deg P4) (ptree_ord P3) (ptree_ord P4) P3 P4).\n      repeat split.\n      - apply PF'.\n      - apply P3F.\n      - apply P3V.\n      - apply P4F.\n      - apply P4V.\n      - unfold ptree_deg; fold ptree_deg.\n        lia.\n      - destruct P3O,P4O.\n        reflexivity. }\n\n7-12 : apply ord_succ_one in PO';\n      try destruct (ord_max_zero _ _ PO') as [OZ1 OZ2];\n      try destruct OZ1,OZ2;\n      try rewrite PD,PO in *;\n      try destruct (cut_elim_ord_Zero P _ _ (PF, PV, PD', PO')) as [P1 [[[P1F P1V] P1D] P1O]].\n\n1-6 : try destruct PF',PO';\n      try rewrite PD in PD';\n      destruct (IHP _ _ (PF , PV , PD' , PO)) as [P1 [[[P1F P1V] P1D] P1O]].\n\n12 :  assert (forall c, P_proves (p c) (substitution f n (projT1 c)) (S d) Zero) as IND.\n\n12 :  destruct PO';\n      intros c;\n      unfold P_proves;\n      destruct (PV c) as [[[PF PcV] PD] PO].\n\n1 : exists (exchange_ab f f0 (ptree_deg P1) (ptree_ord P1) P1).\n\n2 : exists (exchange_cab f f0 f1 (ptree_deg P1) (ptree_ord P1) P1).\n\n3 : exists (exchange_abd f f0 f1 (ptree_deg P1) (ptree_ord P1) P1).\n\n4 : exists (exchange_cabd f f0 f1 f2 (ptree_deg P1) (ptree_ord P1) P1).\n\n5 : exists (contraction_a f (ptree_deg P1) (ptree_ord P1) P1).\n\n6 : exists (contraction_ad f f0 (ptree_deg P1) (ptree_ord P1) P1).\n\n7 : exists (weakening_ad f f0 (ptree_deg P1) (ptree_ord P1) P1).\n\n8 : exists (negation_a f (ptree_deg P1) (ptree_ord P1) P1).\n\n9 : exists (negation_ad f f0 (ptree_deg P1) (ptree_ord P1) P1).\n\n10 : exists (quantification_a f n c (ptree_deg P1) (ptree_ord P1) P1).\n\n11 : exists (quantification_ad f f0 n c (ptree_deg P1) (ptree_ord P1) P1).\n\n13 : exists (w_rule_a f n d (cons Zero 0 Zero) (fun m => projT1(cut_elim_ord_Zero (p m) _ _ (IND m)))).\n\nall : repeat split;\n      try destruct (cut_elim_ord_Zero _ _ _ (IND t)) as [P1 [[[P1F P1V] P1D] P1O]];\n      try apply PF;\n      try apply P1F;\n      try apply PV;\n      try apply P1V;\n      try apply P1D;\n      try apply P1O;\n      try destruct PF';\n      unfold ptree_formula, ptree_ord, ptree_deg;\n      fold ptree_formula ptree_ord ptree_deg;\n      try destruct P1O;\n      try reflexivity;\n      try apply FC;\n      try lia.\nQed.\n\n\n(* *)\nDefinition cut_remove (alpha : ord) : Type :=\n    (forall (P : ptree) (A : formula) (d : nat),\n        P_proves P A (S d) alpha ->\n            provable A d (ord_2_exp alpha)).\n\nLemma cut_elim_aux0 :\n    forall (alpha : ord),\n        nf alpha ->\n            forall (P : ptree) (A : formula) (d : nat),\n                P_proves P A (S d) alpha ->\n                    provable A d (ord_2_exp alpha).\nProof.\napply (transfinite_induction cut_remove).\nintros alpha NA IND.\nunfold cut_remove.\ndestruct alpha as [| alpha1 n alpha2].\n\n1 : intros P A d PP.\n    apply (cut_elim_ord_Zero P _ _ PP).\n\ncase (ord_eqb (cons Zero 0 Zero) (cons alpha1 n alpha2)) eqn:EQO.\n\n1 : intros P A d PP.\n    apply ord_eqb_eq in EQO.\n    destruct EQO.\n    apply (cut_elim_ord_one P _ _ PP).\n    \nassert (ord_lt (cons Zero 0 Zero) (cons alpha1 n alpha2)) as IEO.\n{ destruct (ord_semiconnex (cons Zero 0 Zero) (cons alpha1 n alpha2)) as [O1 | [O1 | O1]].\n  - apply O1.\n  - inversion O1 as [ | a1h a2h a1c a2c a1t a2t LT O1H O2H | a1h a1c a2c a1t a2t LT O1H O2H | a1h a1c a1t a2t LT O1H O2H ];\n    inversion LT.\n  - destruct O1.\n    inversion EQO. }\n\nassert (forall y : ord, nf y -> ord_lt y (cons alpha1 n alpha2) -> forall (P : ptree) (A : formula) (d : nat), P_proves P A d y -> provable A (pred d) (ord_2_exp y)) as IHP_PRED.\n{ intros beta NB LT P A d PP.\n  destruct d.\n  - unfold pred.\n    exists (weak_ord_up P (ord_2_exp beta)).\n    unfold weak_ord_up.\n    destruct PP as [[[PF PV] PD] PO].\n    case (ord_ltb (ptree_ord P) (ord_2_exp beta)) eqn:IE;\n    repeat split;\n    try apply PF;\n    try apply PV;\n    try apply PD.\n    apply (ord_ltb_lt _ _ IE).\n    apply (nf_2_exp _ NB).\n    destruct PO.\n    destruct (ord_2_exp_fp (beta) NB) as [LTB | EQ].\n    + apply ord_lt_ltb in LTB.\n      rewrite IE in LTB.\n      inversion LTB.\n    + rewrite EQ.\n      reflexivity.\n  - apply (IND _ NB LT P _ _ PP). }\n\nintros P.\ninduction P;\nintros A d PP.\n\nall : destruct PP as [[[PF' PV] PD'] PO'];\n      unfold ptree_formula, ptree_deg, ptree_ord in *;\n      fold ptree_formula ptree_deg ptree_ord in *;\n      unfold cut_remove in IND.\n\n1 : destruct PV as [ID PV].\n2 : destruct PV as [[IO PV] NO].\n4-9 : destruct PV as [[[PF PV] PD] PO].\n10 :  destruct PV as [[[[PF FC] PV] PD] PO].\n11,12 : destruct PV as [[[[[[[P1F P1V] P2F] P2V] P1D] P2D] P1O] P2O].\n13-16 : destruct PV as [[[PF PV] PD] PO].\n17,18 : destruct (PV czero) as [[[PF PzV] PD] PO].\n19-21 : destruct PV as [[[[[[[P1F P1V] P2F] P2V] P1D] P2D] P1O] P2O].\n\n1 : apply IHP;\n    repeat split.\n    apply PF'.\n    apply PV.\n    lia.\n    apply PO'.\n\n1 : destruct PO'.\n    assert (ptree_ord P = ptree_ord P) as EQ. reflexivity.\n    destruct (IND (ptree_ord P) (ptree_ord_nf _ PV) IO P A d (PF', PV, PD', EQ)) as [P1 [[[P1F P1V] P1D] P1O]].\n    exists (ord_up (ord_2_exp (cons alpha1 n alpha2)) P1).\n    repeat split.\n    apply P1F.\n    destruct P1O.\n    apply (ord_2_exp_monot _ NO _ (ptree_ord_nf _ PV) IO).\n    apply P1V.\n    apply (nf_2_exp _ NO).\n    unfold ptree_deg; fold ptree_deg.\n    lia.\n\n1 : inversion PO'.\n\n1-6 : destruct PO';\n      try rewrite PD in *;\n      try destruct (IHP _ _ (PF, PV, PD', PO)) as [P1 [[[P1F P1V] P1D] P1O]].\n\n7 : rewrite PD,PO' in *;\n    destruct (IND _ (nf_succ_nf _ NA) (ord_succ_monot _) _ _ _ (PF, PV, PD', PO)) as [P1 [[[P1F P1V] P1D] P1O]].\n\n8,9 : assert (S d >= n0) as IE1;\n      assert (S d >= n1) as IE2;\n      rewrite P1D,P2D,PO' in *;\n      try lia;\n      destruct (IND _ (ptree_ord_nf_hyp _ _ P1O P1V) (ord_lt_max_succ_l _ _) _ _ _ (P1F, P1V, IE1, P1O)) as [P3 [[[P3F P3V] P3D] P3O]];\n      destruct (IND _ (ptree_ord_nf_hyp _ _ P2O P2V) (ord_lt_max_succ_r _ _) _ _ _ (P2F, P2V, IE2, P2O)) as [P4 [[[P4F P4V] P4D] P4O]].\n\n10-13 : rewrite PD,PO' in *;\n        destruct (IND _ (nf_succ_nf _ NA) (ord_succ_monot _) _ _ _ (PF, PV, PD', PO)) as [P1 [[[P1F P1V] P1D] P1O]].\n\n14 :  assert (forall c, P_proves (p c) (substitution f n0 (projT1 c)) (S d) o) as IHP.\n\n14 :  destruct PO';\n      intros c;\n      unfold P_proves;\n      destruct (PV c) as [[[PcF PcV] PcD] PcO].\n\n15 : rewrite PO' in *.\n\n16 : assert (forall m, P_proves (p m) (lor (substitution f n0 (projT1 m)) f0) (S d) o) as IHP.\n\n16 :  destruct PO';\n      intros c;\n      unfold P_proves;\n      destruct (PV c) as [[[PcF PcV] PcD] PcO].\n\n17 : rewrite PO' in *.\n\n1 : exists (exchange_ab f f0 (ptree_deg P1) (ptree_ord P1) P1).\n\n2 : exists (exchange_cab f f0 f1 (ptree_deg P1) (ptree_ord P1) P1).\n\n3 : exists (exchange_abd f f0 f1 (ptree_deg P1) (ptree_ord P1) P1).\n\n4 : exists (exchange_cabd f f0 f1 f2 (ptree_deg P1) (ptree_ord P1) P1).\n\n5 : exists (contraction_a f (ptree_deg P1) (ptree_ord P1) P1).\n\n6 : exists (contraction_ad f f0 (ptree_deg P1) (ptree_ord P1) P1).\n\n7 : exists (ord_up (ord_2_exp (ord_succ o)) (weakening_ad f f0 (ptree_deg P1) (ptree_ord P1) P1)).\n\n8 : exists (ord_up (ord_2_exp (ord_succ (ord_max o o0))) (demorgan_ab f f0 (ptree_deg P3) (ptree_deg P4) (ord_2_exp o) (ord_2_exp o0) P3 P4)).\n\n9 : exists (ord_up (ord_2_exp (ord_succ (ord_max o o0))) (demorgan_abd f f0 f1 (ptree_deg P3) (ptree_deg P4) (ord_2_exp o) (ord_2_exp o0) P3 P4)).\n\n10 : exists (ord_up (ord_2_exp (ord_succ o)) (negation_a f (ptree_deg P1) (ptree_ord P1) P1)).\n\n11 : exists (ord_up (ord_2_exp (ord_succ o)) (negation_ad f f0 (ptree_deg P1) (ptree_ord P1) P1)).\n\n12 : exists (ord_up (ord_2_exp (ord_succ o)) (quantification_a f n0 c (ptree_deg P1) (ptree_ord P1) P1)).\n\n13 : exists (ord_up (ord_2_exp (ord_succ o)) (quantification_ad f f0 n0 c (ptree_deg P1) (ptree_ord P1) P1)).\n\n15 : exists (ord_up (ord_2_exp (ord_succ o)) (w_rule_a f n0 d (ord_2_exp o) (fun m => projT1(IND _ (ptree_ord_nf_hyp _ _ PO PzV) (ord_succ_monot _) (p m) _ _ (IHP m))))).\n\n17 : exists (ord_up (ord_2_exp (ord_succ o)) (w_rule_ad f f0 n0 d (ord_2_exp o) (fun m => projT1(IND _ (ptree_ord_nf_hyp _ _ PO PzV) (ord_succ_monot _) (p m) _ _ (IHP m))))).\n\nall : repeat split;\n      try destruct IND as [P1 [[[P1F P1V] P1D] P1O]];\n      unfold projT1;\n      try apply PcF;\n      try apply PF';\n      try apply P1F;\n      try apply P3F;\n      try apply P4F;\n      try apply PcV;\n      try apply P1V;\n      try apply P3V;\n      try apply P4V;\n      try destruct PF';\n      unfold ptree_formula, ptree_ord, ptree_deg;\n      fold ptree_formula ptree_ord ptree_deg;\n      try lia;\n      try apply PcO;\n      try apply P1O;\n      try apply P3O;\n      try apply P4O;\n      try apply FC;\n      try rewrite <- P1O;\n      try apply nf_2_exp;\n      try apply NA.\n\n1,4-9 : apply ord_succ_lt_exp_succ;\n        try apply (nf_succ_nf _ NA);\n        try apply (ord_succ_lt Zero _ IEO).\n\n\n1,2 : rewrite ord_max_exp_comm;\n      try apply ord_succ_lt_exp_succ;\n      try apply (ord_succ_lt Zero _ IEO);\n      try apply nf_ord_max;\n      try apply (ptree_ord_nf_hyp _ _ P1O P1V);\n      try apply (ptree_ord_nf_hyp _ _ P2O P2V).\n\n3 : case (nat_eqb (max (max n0 n1) (S (num_conn f0))) (S (num_conn f0))) eqn:E1.\n2 : case (nat_eqb (max (max n0 n1) (S (num_conn f))) (S (num_conn f))) eqn:E1.\n1 : case (nat_eqb (max (max n0 n1) (S (num_conn f0))) (S (num_conn f0))) eqn:E1.\n\n2,6 : rewrite PO' in *;\n      assert (S d >= ptree_deg P1) as IE1;\n      assert (S d >= ptree_deg P2) as IE2;\n      try lia;\n      assert ((S (num_conn f0)) < (max n0 n1)) as E2;\n      rewrite nat_eqb_symm in E1;\n      try rewrite (nat_eqb_eq _ _ (nat_max_neb_r_eqb_l _ _ E1));\n      try apply (max_lem2 _ _ E1);\n      destruct (IND _ (ptree_ord_nf_hyp _ _ P1O P1V) (ord_lt_max_succ_l _ _) _ _ _ (P1F, P1V, IE1, P1O)) as [T1 [[[T1F T1V] T1D] T1O]];\n      destruct (IND _ (ptree_ord_nf_hyp _ _ P2O P2V) (ord_lt_max_succ_r _ _) _ _ _ (P2F, P2V, IE2, P2O)) as [T2 [[[T2F T2V] T2D] T2O]].\n      \n5 : rewrite PO' in *;\n    assert (S d >= ptree_deg P1) as IE1;\n    assert (S d >= ptree_deg P2) as IE2;\n    try lia;\n    assert ((S (num_conn f)) < (max n0 n1)) as E2;\n    rewrite nat_eqb_symm in E1;\n    try rewrite (nat_eqb_eq _ _ (nat_max_neb_r_eqb_l _ _ E1));\n    try apply (max_lem2 _ _ E1);\n    destruct (IND _ (ptree_ord_nf_hyp _ _ P1O P1V) (ord_lt_trans _ _ _ (ord_lt_max_succ_l _ _) (ord_succ_monot _)) _ _ _ (P1F, P1V, IE1, P1O)) as [T1 [[[T1F T1V] T1D] T1O]];\n    destruct (IND _ (ptree_ord_nf_hyp _ _ P2O P2V) (ord_lt_trans _ _ _ (ord_lt_max_succ_r _ _) (ord_succ_monot _)) _ _ _ (P2F, P2V, IE2, P2O)) as [T2 [[[T2F T2V] T2D] T2O]].\n\n\n2 : exists (ord_up (ord_2_exp (ord_succ (ord_max o o0))) (cut_ca f f0 (ptree_deg T1) (ptree_deg T2) (ptree_ord T1) (ptree_ord T2) T1 T2)).\n\n3 : exists (ord_up (ord_2_exp (ord_succ (ord_max o o0))) (cut_cad f f0 f1 (ptree_deg T1) (ptree_deg T2) (ptree_ord T1) (ptree_ord T2) T1 T2)).\n\n5 : exists (ord_up (ord_2_exp (ord_succ (ord_succ (ord_max o o0)))) (cut_ad f f0 (ptree_deg T1) (ptree_deg T2) (ptree_ord T1) (ptree_ord T2) T1 T2)).\n\n2,3,5 : repeat split;\n        unfold ptree_ord, ptree_deg; fold ptree_ord ptree_deg;\n        try apply T1F;\n        try apply T2F;\n        try apply T1V;\n        try apply T2V;\n        try apply nf_2_exp;\n        try apply NA;\n        unfold num_conn in *; fold num_conn in *;\n        try lia;\n        rewrite <- T1O, <- T2O;\n        rewrite ord_max_exp_comm;\n        try apply ord_succ_lt_exp_succ;\n        try apply dub_succ_exp_lt_exp_dub_succ;\n        try apply (ord_succ_lt Zero _ IEO);\n        try apply nf_ord_max;\n        try apply (ptree_ord_nf_hyp _ _ P1O P1V);\n        try apply (ptree_ord_nf_hyp _ _ P2O P2V).\n\n1,3 : rewrite PO' in *;\n      assert (n0 >= ptree_deg P1) as IE1;\n      assert (n1 >= ptree_deg P2) as IE2;\n      try lia;\n      apply nat_eqb_eq in E1;\n      destruct (IHP_PRED _ (ptree_ord_nf_hyp _ _ P1O P1V) (ord_lt_max_succ_l _ _) P1 _ _ (P1F, P1V, IE1, P1O)) as [T1 [[[T1F T1V] T1D] T1O]];\n      destruct (IHP_PRED _ (ptree_ord_nf_hyp _ _ P2O P2V) (ord_lt_max_succ_r _ _) P2 _ _ (P2F, P2V, IE2, P2O)) as [T2 [[[T2F T2V] T2D] T2O]];\n      unfold provable;\n      destruct f0.\n\n9 : rewrite PO' in *;\n    assert (n0 >= ptree_deg P1) as IE1;\n    assert (n1 >= ptree_deg P2) as IE2;\n    try lia;\n    apply nat_eqb_eq in E1;\n    destruct (IHP_PRED _ (ptree_ord_nf_hyp _ _ P1O P1V) (ord_lt_trans _ _ _ (ord_lt_max_succ_l _ _) (ord_succ_monot _ )) P1 _ _ (P1F, P1V, IE1, P1O)) as [T1 [[[T1F T1V] T1D] T1O]];\n    destruct (IHP_PRED _ (ptree_ord_nf_hyp _ _ P2O P2V) (ord_lt_trans _ _ _ (ord_lt_max_succ_r _ _) (ord_succ_monot _ )) P2 _ _ (P2F, P2V, IE2, P2O)) as [T2 [[[T2F T2V] T2D] T2O]];\n    unfold provable;\n    destruct f.\n\n1 : exists (weak_ord_up (cut_elimination (cut_ca f (atom a) (ptree_deg T1) (ptree_deg T2) (ptree_ord T1) (ptree_ord T2) T1 T2)) (ord_2_exp (ord_succ (ord_max o o0)))).\n2 : exists (weak_ord_up (cut_elimination (cut_ca f (neg f0) (ptree_deg T1) (ptree_deg T2) (ptree_ord T1) (ptree_ord T2) T1 T2)) (ord_2_exp (ord_succ (ord_max o o0)))).\n3 : exists (weak_ord_up (cut_elimination (cut_ca f (lor f0_1 f0_2) (ptree_deg T1) (ptree_deg T2) (ptree_ord T1) (ptree_ord T2) T1 T2)) (ord_2_exp (ord_succ (ord_max o o0)))).\n\n5 : exists (ord_up (ord_2_exp (ord_succ (ord_max o o0))) (cut_elimination (cut_cad f (atom a) f1 (ptree_deg T1) (ptree_deg T2) (ptree_ord T1) (ptree_ord T2) T1 T2))).\n6 : exists (ord_up (ord_2_exp (ord_succ (ord_max o o0))) (cut_elimination (cut_cad f (neg f0) f1 (ptree_deg T1) (ptree_deg T2) (ptree_ord T1) (ptree_ord T2) T1 T2))).\n7 : exists (weak_ord_up (cut_elimination (cut_cad f (lor f0_1 f0_2) f1 (ptree_deg T1) (ptree_deg T2) (ptree_ord T1) (ptree_ord T2) T1 T2)) (ord_2_exp (ord_succ (ord_max o o0)))).\n\n9 : exists (ord_up (ord_2_exp (ord_succ (ord_succ (ord_max o o0)))) (cut_elimination (cut_ad (atom a) f0 (ptree_deg T1) (ptree_deg T2) (ptree_ord T1) (ptree_ord T2) T1 T2))).\n10 : exists (ord_up (ord_2_exp (ord_succ (ord_succ (ord_max o o0)))) (cut_elimination (cut_ad (neg f) f0 (ptree_deg T1) (ptree_deg T2) (ptree_ord T1) (ptree_ord T2) T1 T2))).\n11 : exists (weak_ord_up (cut_elimination (cut_ad (lor f1 f2) f0 (ptree_deg T1) (ptree_deg T2) (ptree_ord T1) (ptree_ord T2) T1 T2)) (ord_2_exp (ord_succ (ord_succ (ord_max o o0))))).\n\n1-3,5-7,9-11 :  repeat split;\n                try rewrite weak_ord_formula;\n                try rewrite weak_ord_deg;\n                try apply weak_ord_valid;\n                unfold ptree_formula, ptree_deg, ptree_ord, valid;\n                fold ptree_formula ptree_deg ptree_ord valid;\n                try apply cut_elimination_formula;\n                try apply cut_elimination_valid;\n                try refine (T1F, T1V, T2F, T2V, _, _, _, _);\n                try reflexivity;\n                try apply dub_neg_valid;\n                try rewrite dub_neg_ptree_deg;\n                try rewrite dub_neg_ptree_formula;\n                try rewrite dub_neg_ptree_ord;\n                unfold dub_neg_sub_formula;\n                try apply T1V;\n                try apply T2V;\n                try apply T1O;\n                try apply T2O;\n                try rewrite T1F;\n                try rewrite T2F;\n                try rewrite formula_sub_ind_lor;\n                try rewrite non_target_sub;\n                unfold formula_sub_ind, subst_ind_fit;\n                fold subst_ind_fit;\n                unfold formula_sub_ind_fit;\n                try rewrite non_target_fit;\n                try apply nf_2_exp;\n                try apply NA;\n                unfold cut_elimination, cut_elimination_atom, cut_elimination_neg, cut_elimination_lor, contraction_help, PA_omega_axiom, weak_ord_up;\n                unfold ptree_formula; fold ptree_formula;\n                try rewrite form_eqb_refl;\n                try case (correct_a a) eqn:Ra;\n                unfold ptree_deg, ptree_ord; fold ptree_deg ptree_ord;\n                try rewrite (formula_sub_ptree_deg_neg _ _ _ T2V);\n                try rewrite (formula_sub_ptree_ord_neg _ _ _ T2V);\n                try rewrite (formula_sub_ptree_deg_atom _ _ _ T1V);\n                try rewrite (formula_sub_ptree_ord_atom _ _ _ T1V);\n                try rewrite <- T1O;\n                try rewrite <- T2O;\n                try rewrite (ord_lt_ltb _ _ (ord_2_exp_monot _ NA _ (ptree_ord_nf_hyp _ _ P2O P2V) (ord_lt_max_succ_r _ _)));\n                try rewrite (ord_lt_ltb _ _ (ord_2_exp_monot _ NA _ (ptree_ord_nf_hyp _ _ P1O P1V) (ord_lt_max_succ_l _ _)));\n                try rewrite (ord_max_ltb_not_l _ _ (ord_ltb_asymm _ _ (ord_lt_ltb _ _ (ord_lt_max_succ_r _ _))));\n                unfold ptree_ord; fold ptree_ord;\n                unfold num_conn in *; fold num_conn in *;\n                try lia;\n                try reflexivity;\n                try rewrite (ord_max_symm o o0) in *;\n                try rewrite (ord_max_symm (ord_2_exp o) _) in *;\n                case (ord_ltb (ord_succ (ord_succ (ord_max (ord_2_exp o0) (ord_2_exp o)))) (ord_2_exp (ord_succ (ord_max o0 o)))) eqn:IO1;\n                unfold ptree_ord; fold ptree_ord;\n                try refine (ord_lt_trans _ _ _ _ (ord_ltb_lt _ _ IO1));\n                try rewrite (ord_max_exp_comm _ _ (ptree_ord_nf_hyp _ _ P2O P2V) (ptree_ord_nf_hyp _ _ P1O P1V)) in *;\n                try rewrite <- (ord_eqb_eq _ _ (dub_succ_geb_exp_succ_eqb _ (ord_succ_lt Zero _ IEO) (nf_succ_nf _ NA) IO1));\n                try apply (ord_lt_trans _ _ _ (ord_succ_monot _) (dub_succ_exp_lt_exp_dub_succ _ (nf_succ_nf _ (nf_succ_nf _ NA))));\n                try rewrite (ord_lt_ltb _ _ (dub_succ_exp_lt_exp_dub_succ _ (nf_succ_nf _ (nf_succ_nf _ NA))));\n                try rewrite <- (ord_max_exp_comm _ _ (ptree_ord_nf_hyp _ _ P2O P2V) (ptree_ord_nf_hyp _ _ P1O P1V));\n                repeat apply ord_lt_succ;\n                try rewrite (ord_max_ltb_not_l _ _ (ord_ltb_asymm _ _ (ord_lt_ltb _ _ (ord_lt_max_succ_l _ _))));\n                try apply (ord_lt_max_succ_l _ _);\n                try apply (ord_lt_max_succ_r _ _);\n                try apply ord_succ_monot;\n                try apply (ord_2_exp_monot _ NA _ (ptree_ord_nf_hyp _ _ P2O P2V) (ord_lt_trans _ _ _ (ord_lt_max_succ_l _ _) (ord_succ_monot _)));\n                try apply (ord_2_exp_monot _ NA _ (ptree_ord_nf_hyp _ _ P1O P1V) (ord_lt_trans _ _ _ (ord_lt_max_succ_r _ _) (ord_succ_monot _)));\n                try reflexivity.\n\nall : try destruct (and_bool_prop _ _ (provable_closed' _ _ T1V T1F)) as [Cf Cuf];\n      try destruct (and_bool_prop _ _ (provable_closed' _ _ T2V T2F)) as [Cuf0 Cf0];\n      unfold num_conn in *; fold closed num_conn in *;\n      assert (ptree_deg T1 >= ptree_deg T1) as T1DE;\n      try lia.\n\n1,2 : assert (max (ptree_deg T1) (ptree_deg T2) < num_conn f0 + 2) as DLT; try lia.\n\n3 : assert (max (ptree_deg T1) (ptree_deg T2) < num_conn f + 2) as DLT; try lia;\n    assert (P_proves (weakening_ad f0 (univ n2 f) (ptree_deg T1) (ord_2_exp o) T1) (lor f0 (univ n2 f)) (ptree_deg T1) (ord_succ (ord_2_exp o))) as T3P.\n\n3 : { repeat split.\n      apply T1F.\n      apply Cf0.\n      apply T1V.\n      apply T1O.\n      unfold ptree_deg. lia. }\n\n1 : pose proof (quantif_ptree_deg _ _ _ _ _ _ _ (T1F, T1V, T1DE, T1O) T2V DLT (1)) as QSD;\n    exists (weak_ord_up (quantif_sub_ptree T2 _ _ _ _ _ _ (T1F, T1V, T1DE, T1O) (1)) (ord_2_exp (ord_succ (ord_max o o0)))).\n\n2 : pose proof (quantif_ptree_deg _ _ _ _ _ _ _ (T1F, T1V, T1DE, T1O) T2V DLT (lor_ind (1) (non_target f1))) as QSD;\n    exists (weak_ord_up (quantif_sub_ptree T2 _ _ _ _ _ _ (T1F, T1V, T1DE, T1O) (lor_ind (1) (non_target f1))) (ord_2_exp (ord_succ (ord_max o o0)))).\n\n3 : pose proof (quantif_ptree_deg _ _ _ _ _ _ _ T3P T2V DLT (lor_ind (1) (non_target f0))) as QSD;\n    exists (weak_ord_up (contraction_a f0 (ptree_deg (quantif_sub_ptree T2 _ _ _ _ _ _ T3P (lor_ind (1) (non_target f0)))) (ord_add (ord_succ (ord_2_exp o)) (ord_2_exp o0)) (weak_ord_up (quantif_sub_ptree T2 _ _ _ _ _ _ T3P (lor_ind (1) (non_target f0))) (ord_add (ord_succ (ord_2_exp o)) (ord_2_exp o0)))) (ord_2_exp (ord_succ (ord_succ (ord_max o o0))))).\n\nall : repeat split;\n      try apply weak_ord_valid;\n      repeat split;\n      try apply weak_ord_valid;\n      try apply (quantif_valid _ _ _ _ _ _ _ _ T2V Cf DLT);\n      try apply (quantif_valid _ _ _ _ _ _ _ _ T2V Cf0 DLT);\n      try rewrite weak_ord_formula;\n      try rewrite (quantif_ptree_formula _ _ _ _ _ _ _ _ T2V);\n      try rewrite T2F;\n      unfold quantif_sub_formula;\n      unfold formula_sub_ind, subst_ind_fit, formula_sub_ind_fit;\n      fold subst_ind_fit formula_sub_ind_fit;\n      try rewrite non_target_fit;\n      try rewrite non_target_sub';\n      try rewrite form_eqb_refl;\n      try reflexivity;\n      try apply nf_2_exp;\n      try apply NA;\n      try rewrite weak_ord_deg;\n      unfold ptree_deg; fold ptree_deg;\n      try lia;\n      try rewrite weak_ord_height;\n      unfold ptree_ord; fold ptree_ord;\n      try reflexivity.\n\n3 : { apply nf_add;\n      try apply nf_nf_succ;\n      try apply (ptree_ord_nf_hyp _ _ T1O T1V);\n      try apply (ptree_ord_nf_hyp _ _ T2O T2V). }\n\nall : try refine (ord_geb_trans _ _ _ _ (quantif_ptree_ord _ _ _ _ _ _ _ _ T2V _));\n      try rewrite <- T2O;\n      try rewrite ord_ltb_irrefl;\n      try apply (exp_succ_lt_add _ _ (ptree_ord_nf_hyp _ _ P1O P1V) (ptree_ord_nf_hyp _ _ P2O P2V));\n      try reflexivity.\n\n1 : rewrite <- ord_max_succ_succ.\n    apply (ord_geb_trans _ _ _ (exp_succ_lt_add _ _ (nf_nf_succ _ (ptree_ord_nf_hyp _ _ P1O P1V)) (nf_nf_succ _ (ptree_ord_nf_hyp _ _ P2O P2V)))).\n    apply (ord_geb_trans _ _ _ (ord_ltb_asymm _ _ (ord_lt_ltb _ _ (add_right_incr _ _ _ (ord_2_exp_monot _ (nf_nf_succ _ (ptree_ord_nf_hyp _ _ P2O P2V)) _ (ptree_ord_nf_hyp _ _ P2O P2V) (ord_succ_monot _)))))).\n    apply add_left_weak_monot.\n    destruct o.\n    apply ord_ltb_irrefl.\n    apply ord_ltb_asymm.\n    apply ord_lt_ltb.\n    apply ord_succ_lt_exp_succ.\n    apply (ptree_ord_nf_hyp _ _ P1O P1V).\n    apply zero_lt.\nQed.\n\nLemma cut_elim_aux1 :\n    forall (alpha : ord) (P : ptree) (A : formula) (d : nat),\n        P_proves P A (S d) alpha ->\n            provable A d (ord_2_exp alpha).\nProof.\nintros alpha P A d [[[PF' PV] PD'] PO'].\nrewrite PO'.\napply (cut_elim_aux0 _ (ptree_ord_nf _ PV) P _ _ (PF', PV, PD', (eq_refl _))).\nQed.\n\nLemma cut_elim_aux2 :\n    forall (A : formula) (d : nat),\n        {alpha : ord & provable A d alpha} ->\n            {beta : ord & provable A 0 beta}.\nProof.\nintros A d aAP.\ninduction d.\n- apply aAP.\n- apply IHd.\n  destruct aAP as [alpha [P PP]].\n  exists (ord_2_exp alpha).\n  apply (cut_elim_aux1 _ _ _ _ PP).\nQed.\n\nTheorem cut_elim :\n    forall (A : formula) (d : nat) (alpha : ord),\n        provable A d alpha ->\n            {beta : ord & provable A 0 beta}.\nProof.\nintros.\napply (cut_elim_aux2 A d).\nexists alpha.\nauto.\nQed.", "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/Logic/cut_elim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6562678390308055}}
{"text": "From mathcomp.ssreflect\nRequire Import ssreflect.\n\nFrom mathcomp.ssreflect\nRequire Import ssrnat seq ssrbool.\n\n\nTheorem one_eq_two : False -> 1 = 2.\nProof.\n    case.\nQed.\n\nTheorem one_eq_two' : False -> 1 = 2.\nProof.\n    exact: (False_ind (1 = 2)).\nQed.\n\nTheorem one_eq_two'': False -> 1 = 2.\nProof.\n    exact: (fun (f : False) => match f with end).\nQed.\n\nTheorem imp_trans: (forall (P Q R: Prop), (P -> Q) -> (Q -> R) -> P -> R).\nProof.\n    move=> A B C.\n    move=> H2 H1.\n    move=> a.\n    apply: H1.\n    apply: H2.\n    assumption.\nQed.\n\n\nTheorem imp_trans': (forall (P Q R: Prop), (P -> Q) -> (Q -> R) -> P -> R).\nProof.\n    move=> A B C.\n    move=> H1 H2 a.\n    exact: (H2 (H1 a)).\nQed.\n\nTheorem forall_distrib: (forall P Q : Prop -> Prop, (forall (x: Prop), (P x) -> (Q x)) -> ((forall (y : Prop), (P y)) -> (forall (z: Prop), (Q z)))).\nProof.\n    move=> P Q.\n    move=> H1.\n    move=> H2.\n    move=> z.\n    apply: H1.\n    apply: H2.\nQed.\n\nTheorem imp_trans'' (P Q R : Prop) : (Q -> R) -> (P -> Q) -> P -> R.\nProof.\n    move=> H1 H2.\n    move=> p.\n    apply: H1.\n    apply: H2.\n    exact: p.\nQed.\n\nTheorem imp_trans''' (P Q R : Prop) : (Q -> R) -> (P -> Q) -> P -> R.\nProof.\n    move=> H1 H2.\n    move: (imp_trans P Q R)=> H.\n    apply: H.\n    exact H2.\n    exact H1.\nQed.\n\n\nGoal forall P R : Prop, P -> R -> P /\\ R.\nProof.\n    move=> P R.\n    move=> p r.\n    constructor 1; done.\nQed.\n\n\nGoal forall P Q : Prop, P /\\ Q -> Q.\nProof.\n    move=> P Q.\n    move=> R.\n    destruct R as [ p q ].\n    done.\nQed.\n\nGoal forall P Q : Prop, P /\\ Q -> Q.\nProof.\n    move=> P Q.\n    case.\n    move=> p q.\n    done.\nQed.\n\n\n\nGoal forall P Q R : Prop, Q -> P \\/ Q \\/ R.\nProof.\n    move=> P Q R.\n    move=> q.\n    right.\n    left.\n    done.\nQed.\n\nGoal forall P Q : Prop, P \\/ Q -> Q \\/ P.\nProof.\n    move=> P Q.\n    move=> p_or_q.\n    case p_or_q.\n    move=> p.\n    right.\n    done.\n    move=> q.\n    left.\n    done.\nQed.\n\n\nGoal forall P Q : Prop, P \\/ Q -> Q \\/ P.\nProof.\n    move=> P Q.\n    case=> x.\n    right; done.\n    left; done.\nQed.\n\n\nTheorem absurd (P Q : Prop) : P -> ~P -> Q.\nProof.\n    move=> p H.\n    move : (H p).\n    apply: False_ind.\nQed.\n\n\nTheorem contapos (P Q : Prop) : (P -> Q) -> (~Q -> ~P).\nProof.\n    move=> H.\n    move=> Hq.\n    move /H.\n    assumption.\nQed.\n\n\nTheorem ex_imp_ex A (S T : A -> Prop): (exists a: A, S a) -> (forall x: A, S x -> T x) ->\n    exists b: A, T b.\nProof.\n    case=> a Hs Hst.  \n    exists a.\n    apply: Hst.\n    done.\nQed.\n\n\n\nInductive my_ex A (S: A -> Prop) : Prop := my_ex_intro x of S x.\n\nGoal forall A (S : A -> Prop), my_ex A S <-> exists y: A, S y.\nProof.\n    move=> A s.\n    split.\n    case.\n    move=> H.\n    move=> s_H.\n    by exists H.\n    move=> H; destruct H as [a s_x].\n    move: (my_ex_intro A s a)=> H.\n    by apply: H.\nQed.\n\n\n\n", "meta": {"author": "Gopiandcode", "repo": "coq-projects", "sha": "5408268dd954080a7a1956382238625bfd5d95b2", "save_path": "github-repos/coq/Gopiandcode-coq-projects", "path": "github-repos/coq/Gopiandcode-coq-projects/coq-projects-5408268dd954080a7a1956382238625bfd5d95b2/pnp_again.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.6562605041556577}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Eqdep_dec.\nRequire Import Peano_dec.\n\nInductive Vector (A : Set) : nat -> Set :=\n  | Vnil : Vector A 0\n  | Vcons : forall (a : A) (n : nat), Vector A n -> Vector A (S n).\n\nFixpoint vector2list (A : Set) (n : nat) (v : Vector A n) {struct v} :\n list A :=\n  match v with\n  | Vnil => nil (A:=A)\n  | Vcons a n v' => a :: vector2list A n v'\n  end.\n\nFixpoint list2vector (A : Set) (l : list A) {struct l} :\n Vector A (length l) :=\n  match l return (Vector A (length l)) with\n  | nil => Vnil A\n  | a :: l' => Vcons A a (length l') (list2vector A l')\n  end.\n\nSection VectorSizes.\n\nLet nilVectorHelp (A : Set) (n : nat) (p : n = 0) : Vector A n.\nintros.\ninduction n as [| n Hrecn].\napply Vnil.\ndiscriminate p.\nDefined.\n\nLemma nilVector : forall (A : Set) (x : Vector A 0), Vnil A = x.\nProof.\nintro.\nreplace (Vnil A) with (nilVectorHelp A 0 (refl_equal 0)).\ngeneralize (refl_equal 0).\nassert\n (forall (n : nat) (e : n = 0) (x : Vector A n), nilVectorHelp A n e = x).\nintros.\ninduction x as [| a n x Hrecx].\nreflexivity.\ndiscriminate e.\napply H.\nreflexivity.\nQed.\n\nLet consVectorHelp (A : Set) (n m : nat) (p : n = S m) \n  (a : A) (v : Vector A m) : Vector A n.\nintros.\ndestruct n.\ndiscriminate p.\nrewrite p.\napply Vcons.\napply a.\napply v.\nDefined.\n\nLemma consVector :\n forall (A : Set) (n : nat) (x : Vector A (S n)),\n {pair : A * Vector A n | Vcons A (fst pair) n (snd pair) = x}.\nProof.\nintros.\nassert\n {pair : A * Vector A n |\n consVectorHelp A _ _ (refl_equal (S n)) (fst pair) (snd pair) = x}.\ngeneralize (refl_equal (S n)).\nassert\n (forall (m : nat) (x : Vector A m) (e : m = S n),\n  {pair : A * Vector A n | consVectorHelp A m n e (fst pair) (snd pair) = x}).\nintros.\ndestruct x0 as [| a n0 v].\ndiscriminate e.\ngeneralize e.\ninversion e.\ngeneralize v.\nrewrite H0.\nintros.\nexists (a, v0).\nsimpl in |- *.\nunfold eq_rec_r in |- *.\ngeneralize (sym_eq e0). \nintro.\nelim e1 using K_dec_set.\napply eq_nat_dec.\nreflexivity.\napply H.\napply H.\nQed.\n\nEnd VectorSizes.", "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/vector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.6562605036862176}}
{"text": "Require Import Coq.Lists.List.\n\nSection List_Remove.\n\nVariable A : Set.\nHypothesis Aeq_dec : forall a b : A, {a = b} + {a <> b}.\n\nDefinition list_remove (x : A) (l : list A) : list A :=\n  list_rec (fun _ => list A) nil\n    (fun (a : A) _ (recl : list A) =>\n     match Aeq_dec a x with\n     | left _ => recl\n     | right _ => a :: recl\n     end) l.\n\nLemma In_list_remove1 :\n forall (a b : A) (l : list A), In a (list_remove b l) -> In a l.\nProof.\nintros.\ninduction l as [| a0 l Hrecl].\nelim H.\nsimpl in H.\ninduction (Aeq_dec a0 b).\nright.\nauto.\ninduction H as [H| H].\nsimpl in |- *; auto.\nright.\nauto.\nQed.\n\nLemma In_list_remove2 :\n forall (a b : A) (l : list A), In a (list_remove b l) -> a <> b.\nProof.\nintros.\ninduction l as [| a0 l Hrecl].\nelim H.\nsimpl in H.\ninduction (Aeq_dec a0 b).\nauto.\ninduction H as [H| H].\nrewrite H in b0.\nauto.\nauto.\nQed.\n\nLemma In_list_remove3 :\n forall (a b : A) (l : list A), In a l -> a <> b -> In a (list_remove b l).\nProof.\nintros.\ninduction l as [| a0 l Hrecl].\nelim H.\nsimpl in |- *.\ninduction H as [H| H].\ninduction (Aeq_dec a0 b).\nelim H0.\ntransitivity a0; auto.\nleft.\nauto.\ninduction (Aeq_dec a0 b).\nauto.\nright.\nauto.\nQed.\n\nEnd List_Remove.\n\nSection No_Duplicate.\n\nVariable A : Set.\nHypothesis Aeq_dec : forall a b : A, {a = b} + {a <> b}.\n\nDefinition no_dup (l : list A) : list A :=\n  list_rec (fun _ => list A) nil\n    (fun (a : A) _ (rec : list A) =>\n     match In_dec Aeq_dec a rec with\n     | left _ => rec\n     | right _ => a :: rec\n     end) l.\n\nLemma no_dup1 : forall (a : A) (l : list A), In a l -> In a (no_dup l).\nProof.\nintros.\ninduction l as [| a0 l Hrecl].\nelim H.\nsimpl in |- *.\ninduction H as [H| H].\ninduction (In_dec Aeq_dec a0 (no_dup l)).\nrewrite <- H.\nauto.\nleft.\nauto.\ninduction (In_dec Aeq_dec a0 (no_dup l)).\nauto.\nright.\nauto.\nQed.\n\nLemma no_dup2 : forall (a : A) (l : list A), In a (no_dup l) -> In a l.\nProof.\nintros.\ninduction l as [| a0 l Hrecl].\nelim H.\nsimpl in H.\ninduction (In_dec Aeq_dec a0 (no_dup l)).\nright.\nauto.\ninduction H as [H| H].\nleft.\nauto.\nright.\nauto.\nQed.\n\nLemma no_dup3 : forall (k l : list A) (a : A), no_dup k = a :: l -> ~ In a l.\nProof.\nintro.\ninduction k as [| a k Hreck].\nintros.\ndiscriminate H.\nunfold not in |- *; intros.\nsimpl in H.\ninduction (In_dec Aeq_dec a (no_dup k)).\nelim Hreck with l a0; auto.\nelim b.\ninversion H.\nrewrite H3.\nauto.\nQed.\n\nEnd No_Duplicate.", "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/ListExt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.6562604997391371}}
{"text": "\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** \n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Lesson 4: summary\n\n- generic notations and theories\n- interfaces and hierarchies\n- parametrizing theories\n- the BigOp library (the theories of fold)\n- subtypes\n\nLet's start with a lie and then make it true:\n\n#<div style='color: red; font-size: 150%;'>#\nCoq is an object oriented\nprogramming language.\n#</div>#\n\n\n#</div>#\n\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Generic notations and theories\n\nPolymorphism != overloading.\n\nExample: the [==] computable equality\n\n#<div>#\n*)\nCheck 3 == 4.\nCheck true == false.\nCheck [::] == [:: 2; 3; 4].\n\nEval lazy in 3 == 4.\nEval lazy in true == false.\nEval lazy in [::] == [:: 2; 3; 4].\n\nCheck (3, true) == (4, false).\nFail Check (fun x => x) == (fun y => y).\n\nCheck [eqType of nat].\nFail Check [eqType of nat -> nat].\n\nCheck [eqType of seq nat].\nFail Check [eqType of seq (nat -> nat)].\n\n(**\n#</div>#\n\nWe call [eqType] an interface. With some \"approximation\"\n[eqType] is defined as follows:\n\n<<\n\nModule Equality.\n\nStructure type : Type := Pack {\n  sort : Type;\n  op : sort -> sort -> bool;\n  axiom : ∀x y, reflect (x = y) (op x y)\n}.\n\n\nEnd Equality\n>>\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\nThis slide corresponds to\nsection 5.4 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n#<p><br/><p>#\n#</div>#\n\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Interfaces and hierarchies\n\nMathematical Components defines a hierarchy\nof interfaces. They group notations and\ntheorems.\n\n# <img style=\"width: 100%\" src=\"demo-support-master.png\"/>#\n\nLet's use the theory of [eqType]\n\n#<div>#\n*)\nAbout eqxx.\nAbout eq_refl.\nLemma test_eq (*(T : eqType) (x : T)*) :\n  (3 == 3) && (true == true) (*&& (x == x)*).\nProof.\nrewrite eqxx.\nrewrite eqxx.\n(* rewrite eqxx. *)\nby [].\nQed.\n(**\n#</div>#\n\nInterfaces do apply to registered, concrete examples\nsuch as [bool] or [nat]. They can also apply to variables,\nas long as their type is \"rich\" ([eqType] is richer than [Type]).\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\nThis slide corresponds to\nsection 5.5 and 7 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#<p><br/><p>#\n#</div>#\n\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Theories over an interface\n\nInterfaces can be used to parametrize an\nentire theory\n\n#<div>#\n*)\nModule Seq. Section Theory.\nVariable T : eqType.\nImplicit Type s : seq T.\n\nFixpoint mem_seq s x :=\n  if s is y :: s1\n  then (y == x) || mem_seq s1 x\n  else false.\n\n(* the infix \\in and \\notin are generic, not\n   just for sequences. *)\n\nFixpoint uniq s :=\n  if s is x :: s1\n  then (x \\notin s1) && uniq s1\n  else true.\n\nFixpoint undup s :=\n  if s is x :: s1 then\n    if x \\in s1 then undup s1 else x :: undup s1\n  else [::].\n\nEnd Theory. End Seq.\n\nAbout undup_uniq.\n\nEval lazy in (undup [::1;3;1;4]).\n\nLemma test : uniq (undup [::1;3;1;4]).\nProof.\nby rewrite undup_uniq.\nQed.\n\n\n(**\n#</div>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\nThis slide corresponds to\nsection 5.6 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#<p><br/><p>#\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Generic theories: the BigOp library\n\nThe BigOp library is the canonical example\nof a generic theory. It it about the\n[fold] iterator we studied in lesson 1,\nand the many uses it can have.\n\n#<div>#\n*)\n\nLemma sum_odd_3 :\n  \\sum_(0 <= i < 6 | odd i) i = 3^2.\nProof.\nrewrite unlock /=.\nby [].\nQed.\n\nAbout big_mkcond.\nAbout big_nat_recr.\nLemma sum_odd_3_bis :\n  \\sum_(0 <= i < 6 | odd i) i = 3^2.\nProof.\nrewrite big_mkcond big_nat_recr //= -big_mkcond /=.\nAbort.\n\nLemma prod_odd_3_bis : (* try [maxn/0] and also [maxn/1] *)\n  \\big[muln/1]_(0 <= i < 6 | odd i) i = 3^2.\nProof.\nrewrite big_mkcond big_nat_recr //= -big_mkcond /=.\nAbort.\n\n(**\n#</div>#\n\nMost of the lemmas require the operation to be a monoid,\nsome others to be a commutative monoid.\n\n#<div>#\n*)\n\nAbout eq_big_perm.\n\n(**\n#</div>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\nThis slide corresponds to\nsection 5.7 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n\n#<p><br/><p>#\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Sub types\n\nA sub type extends another type by adding a property.\nThe new type has a richer theory.\nThe new type inherits the original theory.\n\nLet's define the type of homogeneous tuples\n\n#<div>#\n*)\n\nModule Tup.\n\nStructure tuple_of n T := Tuple {\n  tval  :> seq T;\n  tsize :  size tval == n\n}.\nNotation \"n .-tuple\" := (tuple_of n) : type_scope.\n\nLemma size_tuple T n (t : n .-tuple T) : size t = n.\nProof. by case: t => s /= /eqP. Qed.\n\nExample seq_on_tuple n (t : n .-tuple nat) :\n  size (rev [seq 2 * x | x <- rev t]) = size t.\nProof. \nby rewrite map_rev revK size_map.\nUndo.\nrewrite size_tuple.\nFail rewrite size_tuple.\nAbort.\n\n\n(**\n#</div>#\n\nWe instrument Coq to automatically promote\nsequences to tuples.\n\n#<div>#\n*)\n\nLemma rev_tupleP n A (t : n .-tuple A) : size (rev t) == n.\nProof. by rewrite size_rev size_tuple. Qed.\nCanonical rev_tuple n A (t : n .-tuple A) := Tuple (rev_tupleP t).\n\nLemma map_tupleP n A B (f: A -> B) (t: n .-tuple A) : size (map f t) == n.\nProof. by rewrite size_map size_tuple. Qed.\nCanonical map_tuple n A B (f: A -> B) (t: n .-tuple A) := Tuple (map_tupleP f t).\n\nExample seq_on_tuple2 n (t : n .-tuple nat) :\n  size (rev [seq 2 * x | x <- rev t]) = size t.\nProof. rewrite size_tuple. rewrite size_tuple. by []. Qed.\n\n(**\n#</div>#\n\nNow we the tuple type to form an eqType,\nexactly as seq does.\n\nWhich is the expected comparison for tuples?\n\n#<div>#\n*)\n\nLemma p1 : size [:: 1;2] == 2. Proof. by []. Qed.\nLemma p2 : size ([:: 1] ++ [::2]) == 2. Proof. by rewrite cat_cons cat0s. Qed.\n\nDefinition t1 := {| tval := [::1;2];        tsize := p1 |}.\nDefinition t2 := {| tval := [::1] ++ [::2]; tsize := p2 |}.\n\nLemma tuple_uip : t1 = t2.\nProof.\nrewrite /t1 /t2. rewrite /=.\nFail by [].\ncongr (Tuple _).\nFail by [].\n(*About bool_irrelevance.*)\napply: bool_irrelevance.\nQed.\n\n(**\n#</div>#\n\nGiven that propositions are expressed (whenever possible)\nas booleans we can systematically prove that proofs\nof these properties are irrelevant.\n\nAs a consequence we can form subtypes and systematically\nprove that the projection to the supertype is injective,\nthat means we can craft an eqType.\n\n#<div>#\n*)\n\n\nCanonical tuple_subType n T := Eval hnf in [subType for (@tval n T)].\nDefinition tuple_eqMixin n (T : eqType) := Eval hnf in [eqMixin of n .-tuple T by <:].\nCanonical tuple_eqType n (T : eqType) := Eval hnf in EqType (n .-tuple T) (tuple_eqMixin n T).\n\nCheck [eqType of 3.-tuple nat].\n\nExample test_eqtype (x y : 3.-tuple nat) : x == y -> True.\nProof.\nmove=> /eqP H.\nAbort.\n\n(**\n#<div/>#\n\nTuples is not the only subtype part of the library.\nAnother one is ['I_n], the finite type of natural\nnumbers smaller than n.\n\n#<div>#\n*)\nPrint ordinal.\n\nAbout tnth. (* like the safe nth function for vectors *)\n\nEnd Tup.\n\n(**\n#</div>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\nThis slide corresponds to\nsection 6.1 and 6.2 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#<p><br/><p>#\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Sum up\n\n- Coq is an object oriented language ;-)\n\n- in the Mathematical Components library [xxType] is an\n  interface (eg [eqType] for types with an equality test).\n  Notations and theorems are linked to interfaces.\n  Interfaces are organized in hierarchies (we just saw a picture,\n  how it works can be found in the book).\n\n- subtypes add properties and inherit the theory of the supertype\n  thanks to boolean predicates (UIP).\n  In some cases the property can be inferred by Coq, letting one apply\n  a lemma about the subtype on terms of the supertype.\n\n\n#</div>#\n\n*)\n", "meta": {"author": "gares", "repo": "typesschool18", "sha": "c27fe831c750c948245593a5fa52f768dd990cb3", "save_path": "github-repos/coq/gares-typesschool18", "path": "github-repos/coq/gares-typesschool18/typesschool18-c27fe831c750c948245593a5fa52f768dd990cb3/lesson4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189134878876, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.6562604982350371}}
{"text": "(** * sups: finite joins (or supremums), a la ssreflect  *)\n\n(** We define a few operations for manipulating finite supremums or\n   intersections. We basically follow the scheme proposed for \"bigops\"\n   in ssreflect, but we simplify it as much as possible since we do\n   not need the whole machinery. The two main simplifications are:\n   - the fact that we restrict ourselves to the associative,\n     commutative, and idempotent operation [cup] of lattices\n     (intersections being obtained by working in the dual lattices)\n   - the fact that we do not include a \"selection\" operator *)\n\nRequire Import lset lattice.\nRequire Export ordinal.\n\nSection s.\nContext `{L:laws} `{Hl:BSL ≪ l}.\n\nUniverse S.\n\nSection i.\n\nContext {I: Type@{S}}.\n\n(** * Supremums *)\n\n(** the unique operator which we define is the following one, \n   which intuitively corresponds to [fold_right cup (map f J) bot],\n   we redefine it to get a better behaviour with [simpl] *)\n\n(** sup f [j1;...;jn] = f j1 ⊔ ... ⊔ f jn *)\nFixpoint sup (f: I -> X) J := \n  match J with\n    | nil => bot\n    | cons i J => f i ⊔ sup f J\n  end.\n\n(** sup specification *)\nLemma sup_spec f J x: sup f J ≦ x <-> forall i, In i J -> f i ≦ x.\nProof. \n  induction J; simpl. split. tauto. intro. lattice. \n  rewrite cup_spec, IHJ. clear IHJ. intuition. now subst. \nQed.\n\n(** ** basic facts about [sup] *)\nLemma sup_app f h k: sup f (h++k) ≡ sup f h ⊔ sup f k.\nProof. induction h; simpl. lattice. rewrite IHh. hlattice. Qed.\n\nLemma sup_singleton f i: sup f (i::nil) ≡ f i.\nProof. simpl. lattice. Qed.\n\nLemma leq_supx f J x: (forall i, In i J -> f i ≦ x) -> sup f J ≦ x.\nProof. apply sup_spec. Qed.\n\nLemma leq_xsup f J i: In i J -> f i ≦ sup f J.\nProof. now apply sup_spec. Qed.\n\nLemma leq_xsup' f J i x: In i J -> x ≦ f i -> x ≦ sup f J.\nProof. intros ? E. rewrite E. now apply leq_xsup. Qed.\n\n(** [sup] is monotone, w.r.t, both the function [f] and the set [J] *)\nGlobal Instance sup_leq: Proper (pwr leq ==> leq ==> leq) sup.\nProof.\n  intros f f' Hf J J' HJ. induction J. apply leq_bx.\n  simpl. apply leq_cupx. rewrite Hf. apply leq_xsup. apply HJ. now left. \n  apply IHJ. intros j ?. apply HJ. now right.\nQed.\n\nGlobal Instance sup_weq: Proper (pwr weq ==> weq ==> weq) sup.\nProof. simpl. setoid_rewrite weq_spec. split; apply sup_leq; firstorder. Qed.\n\nLemma supcup f g J: sup (fun i => f i ⊔ g i) J ≡ sup f J ⊔ sup g J.\nProof. induction J; simpl. lattice. rewrite IHJ. lattice. Qed.\n\n(** refined monotonicity result: the functions have to be pointwise\n   comparable only on the elements of [J] *)\nLemma sup_leq' J J' (f f': I -> X):\n  J ≦J' -> (forall i, In i J -> f i ≦ f' i) -> sup f J ≦ sup f' J'.\nProof. \n  induction J; intros HJ Hf. apply leq_bx. \n  simpl. apply leq_cupx. \n  rewrite Hf. apply leq_xsup. apply HJ. now left. now left.\n  apply IHJ. rewrite <- HJ. clear; firstorder. clear -Hf; firstorder. \nQed.\n\nLemma sup_weq' J J' (f f': I -> X):\n  J ≡J' -> (forall i, In i J -> f i ≡ f' i) -> sup f J ≡ sup f' J'.\nProof. setoid_rewrite weq_spec. split; apply sup_leq'; firstorder. Qed.\n\n(** the sup of empty elements is still empty *)\nLemma sup_b J (f: I -> X) (Hf: forall i, In i J -> f i ≡ bot): sup f J ≡ bot.  \nProof.\n  apply antisym. 2: apply leq_bx. \n  apply leq_supx. intros. now rewrite Hf. \nQed.\n\nEnd i.\n\n(** ** swapping and reindexing indices *)\n\nTheorem sup_swap I J (f: I -> J -> X) I' J':\n  sup (fun i => sup (fun j => f i j) J') I' ≡\n  sup (fun j => sup (fun i => f i j) I') J'.\nProof.\n  induction I'; simpl. apply antisym. apply leq_bx. apply leq_supx; trivial.\n  now rewrite IHI', supcup. \nQed.\n\nLemma sup_map I J (f: J -> X) (m: I -> J) I':\n  sup f (map m I') = sup (fun i => f (m i)) I'.\nProof. induction I'; simpl; congruence. Qed.\n\nEnd s.\n\n(** ** notations *)\n\n(** we use \"\\sup_(i\\in l) f\" in the general case *)\nNotation \"\\sup_ ( i \\in l ) f\" := (sup (fun i => f) l)\n  (at level 41, f at level 41, i, l at level 50,\n    format \"'[' \\sup_ ( i \\in  l ) '/  '  f ']'\"): ra_terms.\n\n(** and \"\\sup_(i<n) f\" when [l] is the set of ordinals smaller than [n] *)\nNotation \"\\sup_ ( i < n ) f\" := (\\sup_(i \\in seq n) f)\n  (at level 41, f at level 41, i, n at level 50,\n    format \"'[' \\sup_ ( i < n ) '/  '  f ']'\"): ra_terms.\n\n(** we shall moreover use the notation [\\sum] when the lattice\n   operations actually come from a partially ordered monoid (see sum.v) *)\n\n\n(** ** additional properties *)\n\n(** two \"meta\" results, to prove that some operation commutes with supremums *)\n\nLemma f_sup_weq {X: ops} {Y l} {L: laws l Y} `{Hl: CUP ≪ l} (f: X -> Y):\n  (f bot ≡ bot) ->\n  (forall x y, f (x ⊔ y) ≡ f x ⊔ f y) ->\n  forall I J (g: I -> X), f (sup g J) ≡ \\sup_(i\\in J) f (g i).\nProof.\n  intros Hbot Hcup I J g. induction J. apply Hbot. \n  simpl. rewrite Hcup. now apply cup_weq.\nQed.\n\nLemma f_sup_eq {X Y: ops} (f: X -> Y):\n  (f bot = bot) ->\n  (forall x y, f (x ⊔ y) = f x ⊔ f y) ->\n  forall I J (g: I -> X), f (sup g J) = \\sup_(i\\in J) f (g i).\nProof.\n  intros Hbot Hcup I J g. induction J. apply Hbot.\n  simpl. rewrite Hcup. congruence.\nQed.\n\n(** same thing, to prove that a predicate is preserved under supremums *)\n\nLemma P_sup {X: ops} {P: X -> Prop} I J (f: I -> X):\n  P bot -> \n  (forall x y, P x -> P y -> P (x ⊔ y)) ->\n  (forall i, In i J -> P (f i)) -> \n  P (sup f J).\nProof.\n  intros Hbot Hcup.\n  induction J; intro H; simpl. apply Hbot. \n  apply Hcup. apply H; now left. apply IHJ. intros. apply H. now right. \nQed.\n\n\n\n(** cutting a supremum over ordinals of size [n+m] *)\nLemma sup_cut `{L:laws} `{BSL ≪ l} n m f:\n  \\sup_(i<n+m) f i ≡ \\sup_(i<n) f (lshift i) ⊔ \\sup_(i<m) f (rshift i).\nProof. now rewrite seq_cut, sup_app, 2sup_map. Qed.\n\n(** supremums where the indices come from a supremum *)\nLemma sup_sup `{L: laws} `{BSL ≪ l} I (f: I -> X) A (J: A -> list I) h: \n  sup f (sup J h) ≡ sup (fun a => sup f (J a)) h.\nProof. induction h. reflexivity. simpl. now rewrite sup_app, IHh. Qed.\n\n(** belonging to a finite union *)\nLemma in_sup A I J (f: I -> list A) a: In a (sup f J) <-> exists i, In i J /\\ In a (f i).\nProof.\n  induction J; simpl. firstorder. \n  rewrite in_app_iff, IHJ. clear. firstorder congruence. \nQed.\n\n(** link between [map] and [sup] *)\nLemma map_sup A I J (f: I -> A): map f J = \\sup_(i\\in J) [f i].\nProof. induction J; simpl; congruence. Qed.\n\n\n(** distribution of meets over supremums *)\nLemma capxsup `{laws} `{BSL+CAP ≪ l} I J (f: I -> X) (x: X): \n  x ⊓ (\\sup_(i\\in J) f i) ≡ \\sup_(i\\in J) (x ⊓ f i).\nProof. apply f_sup_weq. apply capxb. intros; apply capcup. Qed.\n\nLemma capsupx `{laws} `{BSL+CAP ≪ l} I J (f: I -> X) (x: X): \n  (\\sup_(i\\in J) f i) ⊓ x ≡ \\sup_(i\\in J) (f i ⊓ x).\nProof. rewrite capC, capxsup. now setoid_rewrite capC at 1. Qed.\n\n\n(** * Infimum (or intersections) *)\n\n(** obtained for free, by duality *)\n\nNotation inf f l := (@sup (dual _) _ f l).\n\nNotation \"\\inf_ ( i \\in l ) f\" := (inf (fun i => f) l)\n  (at level 41, f at level 41, i, l at level 50,\n    format \"'[' \\inf_ ( i \\in  l ) '/  '  f ']'\"): ra_terms.\n\nNotation \"\\inf_ ( i < n ) f\" := (\\inf_(i \\in seq n) f)\n  (at level 41, f at level 41, i, n at level 50,\n    format \"'[' \\inf_ ( i < n ) '/  '  f ']'\"): ra_terms.\n\nSection inf.\nContext `{laws} `{CAP+TOP ≪ l} {I: Type}.\n\nGlobal Instance inf_leq:\n  Proper (pwr (@leq X) ==> leq --> @leq X) (@sup (dual X) I).\nProof. intros ? ? ? ? ?. now dual @sup_leq. Qed.\n\nLemma inf_spec (f: I -> X) J (x: X): \n  x ≦ \\inf_(i\\in J) f i <-> forall i, In i J -> x ≦ f i.\nProof. dual @sup_spec. Qed.\n\nLemma inf_singleton (f: I -> X) i: inf f (i::nil) ≡ f i.\nProof. dual @sup_singleton. Qed.\n\nLemma leq_xinf (f: I -> X) J x: (forall i, In i J -> x ≦ f i) -> x ≦ inf f J.\nProof. dual @leq_supx. Qed.\n\nLemma leq_infx (f: I -> X) J i: In i J -> @leq X (inf f J) (f i).\nProof. dual @leq_xsup. Qed.\n\nLemma leq_infx' (f: I -> X) J i x: In i J -> f i ≦ x -> @leq X (inf f J) x.\nProof. dual @leq_xsup'. Qed.\n\nEnd inf.\n\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/sups.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867825403177, "lm_q2_score": 0.8221891305219505, "lm_q1q2_score": 0.656260496730937}}
{"text": "(**\nParts of this file are copied and modified from the Coq Demos\nof the lecture Semantics at Saarland University\nhttp://www.ps.uni-saarland.de/courses/sem-ws17/confluence.v\n**)\n\nSet Implicit Arguments.\nRequire Import Morphisms FinFun.\n\n(** Pretty version of inversion *)\nLtac inv H := inversion H; subst; clear H.\n\nNotation \"R <<= S\" := (forall x y, R x y -> S x y) (at level 70).\nNotation \"R === S\" := (R <<= S /\\ S <<= R) (at level 70).\n\nSection ClosureRelations.\n  Variables (X: Type) (R: X -> X -> Prop).\n  Implicit Types x y z : X.\n\n  Definition functional := forall x y z, R x y -> R x z -> y = z.\n\n  Inductive star : X -> X -> Prop :=\n  | starRefl x     : star x x\n  | starStep x x' y : R x x' -> star x' y -> star x y.\n\n  Inductive plus : X -> X -> Prop :=\n  | plusSingle x y: R x y -> plus x y\n  | plusStep x x' y: R x x' -> plus x' y -> plus x y.\n\n  Inductive counted : nat -> X -> X -> Prop :=\n  | countedRefl x: counted 0 x x\n  | countedStep x x' y n: R x x' -> counted n x' y -> counted (S n) x y.\n\n  Inductive sym: X -> X -> Prop :=\n  | symId x y: R x y -> sym x y\n  | symInv x y: R y x -> sym x y.\n\n\n  Hint Constructors star plus counted.\n\n  Lemma star_trans x y z :\n    star x y -> star y z -> star x z.\n  Proof.\n    induction 1; eauto.\n  Qed.\n\n\n  Lemma plus_trans x y z :\n    plus x y -> plus y z -> plus x z.\n  Proof.\n    induction 1; eauto.\n  Qed.\n\n\n  Fact counted_trans x y z m n:\n    counted m x y -> counted n y z -> counted (m + n) x z.\n  Proof.\n    induction 1; cbn; eauto.\n  Qed.\n\n\n\n  Fact star_exp :\n    R <<= star.\n  Proof.\n    eauto.\n  Qed.\n\n  Fact plus_exp :\n    R <<= plus.\n  Proof.\n    eauto.\n  Qed.\n\n  Fact counted_exp :\n    R === counted 1.\n  Proof.\n    split; eauto.\n    intros x y H; inv H; inv H2; eauto.\n  Qed.\n\n\n  Lemma plus_star : plus <<= star.\n  Proof.\n    induction 1; eauto.\n  Qed.\n\n  Lemma plus_destruct x y: plus x y <-> exists2 x', (R x x') & (star x' y).\n  Proof.\n    split.\n    - induction 1; eauto.\n      destruct IHplus; eexists; eauto.\n    - intros [? H1 H2]; revert x H1; induction H2; eauto.\n  Qed.\n\n\n  Lemma step_star_plus x y z:\n    R x y -> star y z -> plus x z.\n  Proof.\n    intros H1 H2; apply plus_destruct; eauto.\n  Qed.\n\n  Lemma plus_star_step x y z :\n    plus x y -> star y z -> plus x z.\n  Proof.\n    intros [] % plus_destruct ?. eapply plus_destruct.\n    eexists; eauto using star_trans.\n  Qed.\n\nEnd ClosureRelations.\n\n\nDefinition equiv X (R: X -> X -> Prop) := star (sym R).\n\n\n\nHint Constructors star plus counted.\nHint Resolve star_trans plus_trans counted_trans star_exp plus_exp counted_exp.\n\n\n\n\nSection Properties.\n  Variable X: Type.\n  Implicit Types (x y z : X) (R S : X -> X -> Prop).\n\n  Fact star_mono R S :\n    R <<= S -> star R <<= star S.\n  Proof.\n    intros H x y.\n    induction 1; eauto.\n  Qed.\n\n  Fact plus_mono R S :\n    R <<= S -> plus R <<= plus S.\n  Proof.\n    intros H x y.\n    induction 1; eauto.\n  Qed.\n\n\n  Fact star_closure R S :\n    PreOrder S -> R <<= S -> star R <<= S.\n  Proof.\n    intros H1 H2 x y.\n    induction 1 as [x|x x' y H4 _ IH].\n    - reflexivity.\n    - transitivity x'; auto.\n  Qed.\n\n  Fact star_idem R :\n    star (star R) === star R.\n  Proof.\n    split.\n    - induction 1; eauto.\n    - apply star_mono, star_exp.\n  Qed.\n\n  Fact plus_idem R :\n    plus (plus R) === plus R.\n  Proof.\n    split; eauto.\n    induction 1; eauto.\n  Qed.\n\n  Fact plus_fixpoint R :\n    plus (star R) === star R.\n  Proof.\n    split.\n    - induction 1; eauto.\n    - eauto.\n  Qed.\n\n  Fact star_absorbtion R :\n    star (plus R) === star R.\n  Proof.\n    split.\n    - induction 1; eauto.\n      apply plus_destruct in H. destruct H. eauto.\n    - eapply star_mono. eauto.\n  Qed.\n\n\n  Lemma sym_symmetric R x y:\n    sym R x y -> sym R y x.\n  Proof.\n    intros []; eauto using sym.\n  Qed.\n\n  Lemma refl_star R x y:\n    x = y -> star R x y.\n  Proof.\n    intros ->; eauto.\n  Qed.\n\n  Lemma refl_equiv R x:\n    equiv R x x.\n  Proof.\n    constructor.\n  Qed.\n\n  Lemma equiv_trans R x y z:\n    equiv R x y -> equiv R y z -> equiv R x z.\n  Proof. eapply star_trans. Qed.\n\n  Lemma equiv_symm R x y:\n    equiv R x y -> equiv R y x.\n  Proof.\n    induction 1.\n    constructor; eauto.\n    eapply star_trans; eauto.\n    econstructor 2; eauto using refl_equiv, sym_symmetric.\n  Qed.\n\n\n  Lemma equiv_star R x y:\n    star R x y -> equiv R x y.\n  Proof.\n    induction 1; unfold equiv in *; eauto using sym, star.\n  Qed.\n\nEnd Properties.\n\n\n(** Strong normalisation *)\nSection StrongNormalisation.\n\n  Variables (X A: Type).\n  Variables (R: X -> X -> Prop) (S: A -> A -> Prop).\n\n  Definition Normal x := forall y, ~ R x y.\n  Definition evaluates s t := star R s t /\\ Normal t.\n\n  Inductive SN {X} (R: X -> X -> Prop) : X -> Prop :=\n  | SNC x : (forall y, R x y -> SN R y) -> SN R x.\n\n  Lemma SN_ext Q x :\n    (forall x y, R x y <-> Q x y) ->\n    SN R x <-> SN Q x.\n  Proof.\n    split; induction 1; econstructor; firstorder.\n  Qed.\n\n  Fact SN_unfold x :\n    SN R x <-> forall y, R x y -> SN R y.\n  Proof.\n    split.\n    - destruct 1 as [x H]. exact H.\n    - intros H. constructor. exact H.\n  Qed.\n\n  Fact Normal_SN x :\n    Normal x -> SN R x.\n  Proof.\n    intros H. constructor. intros y H1.\n    exfalso. eapply H; eauto.\n  Qed.\n\n\n  Fact Normal_star_stops x:\n    Normal x -> forall y, star R x y -> x = y.\n  Proof.\n    destruct 2; firstorder.\n  Qed.\n\n\n  Fact SN_plus x :\n    SN R x <-> SN (plus R) x.\n  Proof.\n    split.\n    - induction 1 as [x _ IH].\n      constructor. induction 1; eauto.\n      apply IHplus. intros z H1 % plus_exp.\n      destruct (IH x' H) as [H2].\n      apply H3. eauto.\n    - induction 1 as [x _ IH].\n      constructor. intros y H1. apply IH. eauto.\n  Qed.\n\n  Definition morphism  (f: X -> A) := forall x y, R x  y -> S (f x) (f y).\n\n  Fact SN_morphism f x :\n    morphism f -> SN S (f x) -> SN R x.\n  Proof.\n    intros H H1.\n    remember (f x) as a eqn:H2. revert x H2.\n    induction H1 as [a _ IH]. intros x ->.\n    constructor. intros y H1 % H.\n    apply (IH _ H1). reflexivity.\n  Qed.\n\n  Fact SN_finite_steps:\n     (forall x, (exists y, R x y) \\/ Normal x) -> forall x, SN R x -> exists2 y, star R x y & Normal y.\n  Proof.\n    intros H; induction 1 as [x H1 IH]. destruct (H x) as [[y H2]|].\n    + edestruct IH as [z H3 H4]; eauto.\n    + eexists; eauto.\n  Qed.\n\n\nEnd StrongNormalisation.\n\nSection Confluence.\n\n  Variable X: Type.\n  Implicit Types (x y z : X) (R S : X -> X -> Prop).\n\n\n  Definition joinable R x y := exists2 z, R x z & R y z.\n  Definition diamond R := forall x y z, R x y -> R x z -> joinable R y z.\n  Definition confluent R := diamond (star R).\n  Definition semi_confluent R :=\n    forall x y z, R x y -> star R x z -> joinable (star R) y z.\n\n\n  Fact diamond_semi_confluent R :\n    diamond R -> semi_confluent R.\n  Proof.\n    intros H x y1 y2 H1 H2. revert y1 H1.\n    induction H2 as [x|x x' y2 H2 _ IH]; intros y1 H1.\n    - exists y1; eauto.\n    - assert (joinable R y1 x') as [z H3 H4].\n      { eapply H; eauto. }\n      assert (joinable (star R) z y2) as [u H5 H6].\n      { apply IH; auto. }\n      exists u; eauto.\n  Qed.\n\n  Fact confluent_semi R :\n    confluent R <-> semi_confluent R.\n  Proof.\n    split.\n    - intros H x y1 y2 H1 H2.\n      eapply H; [|exact H2]. auto.\n    - intros H x y1 y2 H1 H2. revert y2 H2.\n      induction H1 as [x|x x' y1 H1 _ IH]; intros y2 H2.\n      + exists y2; auto.\n      + assert (joinable (star R) x' y2) as [z H3 H4].\n        { eapply H; eauto. }\n        assert (joinable (star R) y1 z) as [u H5 H6].\n        { apply IH; auto. }\n        exists u; eauto.\n  Qed.\n\n  Fact diamond_confluent R :\n    diamond R -> confluent R.\n  Proof.\n    intros H.\n    apply confluent_semi, diamond_semi_confluent, H.\n  Qed.\n\n  Fact joinable_ext R S x y:\n    R === S -> joinable R x y -> joinable S x y.\n  Proof.\n    firstorder.\n  Qed.\n\n  Fact diamond_ext R S:\n    R === S -> diamond S -> diamond R.\n  Proof.\n    intros H1 H2 x y z H3 H4.\n    assert (joinable S y z); firstorder.\n  Qed.\n\n  Lemma confluence_normal_left R x y z:\n    confluent R -> Normal R y ->\n    star R x y -> star R x z ->\n    star R z y.\n  Proof.\n    intros H1 H2 H3 H4. destruct (H1 _ _ _ H3 H4) as [x' A B].\n    enough (x' = y) by congruence.\n    destruct A; eauto; exfalso; eapply H2; eauto.\n  Qed.\n\n  Lemma confluence_normal_right R x y z:\n    confluent R -> Normal R z ->\n    star R x y -> star R x z ->\n    star R y z.\n  Proof.\n    intros H1 H2 H3 H4. destruct (H1 _ _ _ H3 H4) as [x' A B].\n    enough (x' = z) by congruence.\n    destruct B; eauto; exfalso; eapply H2; eauto.\n  Qed.\n\n\n  Lemma confluence_unique_normal_forms R x y z:\n    confluent R -> Normal R y -> Normal R z ->\n    star R x y -> star R x z -> y = z.\n  Proof.\n    intros H1 H2 H3 H4 H5. destruct (H1 _ _ _ H4 H5) as [x' A B].\n    destruct A; [destruct B | ]; eauto; exfalso; [ eapply H3 | eapply H2 ];  eauto.\n  Qed.\n\n\n  Lemma church_rosser (R: X -> X -> Prop) s t:\n    confluent R -> equiv R s t -> exists v: X, star R s v /\\ star R t v.\n  Proof.\n    induction 2.\n    - now (exists x).\n    - inv H0.\n      + destruct IHstar as [v];  exists v; intuition;  eauto.\n      + destruct IHstar; intuition.\n        edestruct H.\n        eapply H3. econstructor 2; eauto.\n        exists x1; split; eauto.\n  Qed.\n\n\nEnd Confluence.\n\n\n(** Right-recursive version of star. *)\n\nInductive starL {X: Type} (R: X -> X -> Prop) (x : X):  X -> Prop :=\n| starReflL : starL R x x\n| starStepL  y y':  starL R x y -> R y y' -> starL R x y'.\n\nHint Constructors starL.\n\nLemma star_starL X (R : X -> X -> Prop) x y :\n  starL R x y <-> star R x y .\nProof.\n  split.\n  - induction 1; auto. induction IHstarL; eauto.\n  - induction 1; eauto. clear H0. induction IHstar; eauto.\nQed.\n\n\n\n(**  Typeclass Instances **)\nGlobal Instance subrel_star {X} (R : X -> X -> Prop) :\n  subrelation (plus R) (star R).\nProof.\n  intros ?; eapply plus_star.\nQed.\n\nGlobal Instance subrel_star_mono {X} (R S: X -> X -> Prop) (H: subrelation R S) :\n  subrelation (star R) (star S).\nProof.\n  exact (star_mono _ H).\nQed.\n\nGlobal Instance subrel_plus_mono {X} (R S: X -> X -> Prop) (H: subrelation R S) :\n  subrelation (plus R) (plus S).\nProof.\n  exact (plus_mono _ H).\nQed.\n\nGlobal Instance subrel_star_equiv {X} (R: X -> X -> Prop) :\n  subrelation (star R) (equiv R).\nProof.\n  exact (@equiv_star _ R).\nQed.\n\n\nGlobal Instance star_preorder {X} (R: X -> X -> Prop):\n  PreOrder (star R).\nProof.\n  constructor; hnf; eauto using star_trans.\nQed.\n\nGlobal Instance star_expansive {X} (R: X -> X -> Prop):\n  subrelation R (star R).\nProof.\n  intros ?; eapply star_exp.\nQed.\n\n\nGlobal Instance plus_expansive {X} (R: X -> X -> Prop):\n  subrelation R (plus R).\nProof.\n  intros?; eapply plus_exp.\nQed.\n\nGlobal Instance plus_transitive {X} (R: X -> X -> Prop):\n  Transitive (plus R).\nProof.\n  intros ?; eapply plus_trans.\nQed.\n\nGlobal Instance sym_Symmetric {X} (R: X -> X -> Prop):\n  Symmetric (sym R).\nProof.\n  firstorder using sym_symmetric.\nQed.\n\n\nGlobal Instance equiv_Equivalence {X} (R: X -> X -> Prop):\n  Equivalence (equiv R).\nProof.\n  constructor; try firstorder using refl_equiv, equiv_trans, equiv_symm.\n  intros ? ? ? ; eapply equiv_trans.\nQed.\n", "meta": {"author": "euisuny", "repo": "logrel-iris", "sha": "37ad8f953c97cfa8c7eefa4a159dfbab6db6d17c", "save_path": "github-repos/coq/euisuny-logrel-iris", "path": "github-repos/coq/euisuny-logrel-iris/logrel-iris-37ad8f953c97cfa8c7eefa4a159dfbab6db6d17c/src/abstract_reduction_systems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.6562604967309369}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nTheorem append_Nil: forall (l: lst), append l Nil = l.\nProof.\n  induction l.\n  { simpl. f_equal. assumption. }\n  { simpl. reflexivity. }\nQed.\n\nTheorem append_assoc:\n  forall (l1 l2 l3: lst), append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\n  induction l1; induction l2; induction l3; try (simpl; reflexivity).\n  - simpl. rewrite <- IHl1. f_equal. \n  - simpl. rewrite 2 append_Nil. reflexivity. \n  - simpl. lfind.   reflexivity.  \nAdmitted.\n\nTheorem append_rev_Cons:\n  forall (l1 l2: lst) (x: natural),\n    rev (append l1 (Cons x l2)) = append (rev l2) (Cons x (rev l1)).\nProof.\n  induction l1; induction l2; try (simpl; reflexivity).\n  { intro. simpl. rewrite IHl1. simpl. rewrite <- append_assoc.\n    f_equal. }\n  { intro. simpl. rewrite IHl1. simpl. reflexivity. }\nQed.\n\nTheorem rev_append: forall (l1 l2: lst), rev (append l1 l2) = append (rev l2) (rev l1).\nProof.\n  induction l1.\n  { induction l2.\n    { simpl. rewrite append_rev_Cons.\n      rewrite <- 2 append_assoc.\n      f_equal. }\n    { simpl. rewrite append_Nil. reflexivity. }\n  }\n  { intro. simpl. rewrite append_Nil. reflexivity. }\nQed.\n\nTheorem theorem0 : forall (x : lst), eq (rev (rev x)) x.\nProof.\n  induction x.\n  { simpl. rewrite rev_append. simpl. f_equal.\n    assumption. }\n  { simpl. reflexivity. }\nQed.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/clam_lf_goal10_append_assoc_36_append_Nil/goal10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.6562604927838565}}
{"text": "(* Require Export Field_theory. *)\nRequire Import ZArith.\nOpen Scope Z_scope.\n\nGoal forall a b c : Z,\n  (a+b+c)^2 =\n  a * a + b^2 + c * c + 2 * a * b + 2 * a * c + 2 * b * c.\n  intros.\n  ring.\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/old/fields.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.947381048137938, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.6561958999880121}}
{"text": "Theorem 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 eqn: Eb.\n  - simpl. destruct c eqn: Ec.\n    -- reflexivity.\n    -- intros. rewrite <- H. reflexivity.\n  - simpl. destruct c eqn: Ec.\n    -- intros. rewrite <- H. reflexivity.\n    -- intros H. reflexivity.\nQed.", "meta": {"author": "cristianlepore", "repo": "Coq_exercises", "sha": "109d34794edee6bd2b255ed4f7fc3c91edb8c8f5", "save_path": "github-repos/coq/cristianlepore-Coq_exercises", "path": "github-repos/coq/cristianlepore-Coq_exercises/Coq_exercises-109d34794edee6bd2b255ed4f7fc3c91edb8c8f5/Software_foundation/Chapter1/andb_eq_orb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961427, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6561124015095925}}
{"text": "\nRequire Export Iron.Language.SimplePCF.SubstExpExp.\nRequire Export Iron.Language.SimplePCF.Exp.\n\n\n(*******************************************************************)\n(** Evaluation Contexts. *)\n(*  Describes a place in the AST where the subespression there\n    is able to take an evaluation step. Each contexts is represented\n    by the function that fills it. *)\nInductive exp_ctx : (exp -> exp) -> Prop :=\n | XcTop\n   :  exp_ctx (fun x => x)\n\n | XcApp1\n   :  forall x2\n   ,  exp_ctx (fun xx => XApp xx x2)\n\n (* The argument of an application can only step once the\n    function has already been evaluated. *)\n | XcApp2\n   :  forall v1\n   ,  wnfX v1\n   -> exp_ctx (fun xx => XApp v1 xx)\n\n | XcSucc\n   :  exp_ctx (fun xx => XSucc   xx)\n\n | XcPred\n   :  exp_ctx (fun xx => XPred   xx)\n\n | XcIsZero\n   :  exp_ctx (fun xx => XIsZero xx)\n\n | XcIf\n   :  forall x2 x3\n   ,  exp_ctx (fun xx => XIf xx x2 x3).\n\nHint Constructors exp_ctx.\n\n\n(********************************************************************)\n(** Single Small Step Evaluation *)\n(** The single step rules model the individual transitions that the\n    machine can make at runtime. *)\nInductive STEP : exp -> exp -> Prop :=\n\n | EsContext\n   :  forall C x x'\n   ,  exp_ctx C\n   -> STEP x x'\n   -> STEP (C x) (C x')\n\n (* Function application.\n    Substitute the value into the abstraction *)\n | EsLamApp\n   : forall t11 x12 v2\n   ,  wnfX v2\n   -> STEP (XApp   (XLam t11 x12) v2)\n           (substX 0 v2 x12)\n\n (* Fixpoint.\n    Substitute the abstraction into itself. *)\n | EsFix\n   :  forall t11 x12\n   ,  STEP (XFix t11 x12)\n           (substX 0 (XFix t11 x12) x12)\n\n (* Naturals **************************)\n (* Increment the primitive value *)\n | EsSucc\n   :  forall n\n   ,  STEP (XSucc (XNat n)) (XNat (S n))\n\n (* If we've got a Zero then just return Zero,\n    this way we don't need to worry about negative naturals. *)\n | EsPredZero\n   :  STEP (XPred (XNat O)) (XNat O)\n\n (* If we've got a Succ then return the inner expression. *)\n | EsPredSucc\n   :  forall n\n   ,  STEP (XPred (XNat (S n))) (XNat n)\n\n (* Booleans **************************)\n | EsIsZeroTrue\n   :  STEP (XIsZero (XNat O)) XTrue\n\n | EsIsZeroFalse\n   :  forall n\n   ,  STEP (XIsZero (XNat (S n))) XFalse\n\n (* Branching *************************)\n (* Take the 'then' branch. *)\n | EsIfThen\n   :  forall x2 x3\n   ,  STEP (XIf XTrue x2 x3) x2\n\n (* Take the 'else' branch. *)\n | EsIfElse\n   :  forall x2 x3\n   ,  STEP (XIf XFalse x2 x3) x3.\n\nHint Constructors STEP.\n\n\n(********************************************************************)\n(** Multi-step evaluation. *)\n(** A sequence of small step transitions.\n    As opposed to STEPSL, this version has an append constructor\n    ESAppend that makes it easy to join two evaluations together.\n    We use this when converting big-step evaluations to small-step. *)\nInductive STEPS : exp -> exp -> Prop :=\n\n (* After no steps, we get the same exp.\n    We need this constructor to match the EVDone constructor\n    in the big-step evaluation, so we can convert between big-step\n    and multi-step evaluations. *)\n | EsNone\n   :  forall x1\n   ,  STEPS x1 x1\n\n (* Take a single step. *)\n | EsStep\n   :  forall x1 x2\n   ,  STEP  x1 x2\n   -> STEPS x1 x2\n\n (* Combine two evaluations into a third. *)\n | EsAppend\n   :  forall x1 x2 x3\n   ,  STEPS x1 x2 -> STEPS x2 x3\n   -> STEPS x1 x3.\n\nHint Constructors STEPS.\n\n\n(* Multi-step evaluation in a context. *)\nLemma steps_context\n :  forall C x1 x1'\n ,  exp_ctx C\n -> STEPS x1 x1'\n -> STEPS (C x1) (C x1').\nProof.\n intros C x1 x1' HC HS.\n induction HS; burn.\nQed.\n\n\n(********************************************************************)\n(** Left linearised multi-step evaluation. *)\n(** As opposed to STEPS, this version provides a single step at a time\n    and does not have an append constructor. This is convenient\n    when converting a small-step evaluations to big-step, via the\n    eval_expansion lemma. *)\nInductive STEPSL : exp -> exp -> Prop :=\n | EslNone\n   : forall x1\n   , STEPSL x1 x1\n\n | EslCons\n   :  forall x1 x2 x3\n   ,  STEP   x1 x2 -> STEPSL x2 x3\n   -> STEPSL x1 x3.\n\nHint Constructors STEPSL.\n\n\n(* Transitivity of left linearised multi-step evaluation.\n   We use this when \"flattening\" a big step evaluation to the\n   small step one. *)\nLemma stepsl_trans\n :  forall x1 x2 x3\n ,  STEPSL x1 x2 -> STEPSL x2 x3\n -> STEPSL x1 x3.\nProof.\n intros. induction H; burn.\nQed.\n\n\n(* Linearise a regular multi-step evaluation.\n   This flattens out all the append constructors, leaving us with\n   a list of individual transitions. *)\nLemma stepsl_of_steps\n :  forall x1 x2\n ,  STEPS  x1 x2\n -> STEPSL x1 x2.\nProof.\n intros. induction H; burn using stepsl_trans.\nQed.\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/SimplePCF/Step.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924954, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6561123963304818}}
{"text": "Require Import Nat List Bool Logic Orders.\nRequire Import Coq.Sorting.Sorted.\nRequire Import Coq.Sorting.Permutation.\nRequire Import Coq.Relations.Relation_Definitions.\nImport ListNotations.\n\nHint Constructors LocallySorted.\n\nLemma LocallySorted_begin: forall {A:Type} {R:relation A} l x y,\n  LocallySorted R (x::l) ->\n  R y x ->\n  LocallySorted R (y::x::l).\nProof.\n  intros; constructor; auto.\nQed.\n\nLemma LocallySorted_end: forall {A:Type} {R:relation A} l x y,\n  LocallySorted R (l ++ [x]) ->\n  R x y ->\n  LocallySorted R (l ++ [x; y]).\nProof.\n  intros.\n  induction l; simpl in *.\n  - repeat constructor; auto.\n  - inversion H. symmetry in H3. apply app_eq_nil in H3; destruct H3. inversion H3.\n    rewrite H2 in *.\n    apply IHl in H3. change (l ++ [x; y]) with (l ++ [x] ++ [y]) in *.\n    rewrite app_assoc in *. rewrite <- H2 in *. simpl in H3.\n    change (a::(b::l0) ++ [y]) with (a::b::(l0 ++ [y])).\n    constructor; auto.\nQed.\n\nLemma LocallySorted_sum: forall {A:Type} {R:relation A} a b l l',\n  LocallySorted R (l ++ [a]) -> LocallySorted R (b::l') ->\n  R a b ->\n  LocallySorted R (l ++ [a;b] ++ l').\nProof.\n  intros.\n  induction l, l'; simpl.\n  - repeat constructor; auto.\n  - constructor; auto.\n  - simpl in H. inversion H. symmetry in H4. apply app_eq_nil in H4. destruct H4. inversion H4.\n    subst. rewrite H3 in H4.\n    apply IHl in H4. simpl in H4.\n    change (l ++ [a;b]) with (l ++ [a] ++ [b]) in *. rewrite app_assoc in *.\n    rewrite <- H3 in *.\n    change (a0::(b0::l0) ++ [b]) with (a0::b0::(l0 ++ [b])). constructor.\n    simpl in H4. auto. auto.\n  - simpl in H. inversion H. symmetry in H4. apply app_eq_nil in H4. destruct H4. inversion H4.\n    subst. rewrite H3 in H4. apply IHl in H4. simpl in H4.\n    change (l ++ a :: b :: a1 :: l') with (l ++ [a] ++ b :: a1 :: l') in *.\n    rewrite app_assoc in *. rewrite <- H3 in *.\n    simpl in *. constructor; auto.\nQed.\n\nLemma LocallySorted_hd_relation: forall {A: Type} {R: relation A} l x,\n  (forall t, In t l -> R x t) ->\n  LocallySorted R l ->\n  LocallySorted R (x::l).\nProof.\n  intros; generalize dependent l.\n  induction l; intros; auto.\n  constructor; auto.\n  apply H. simpl; auto.\nQed.\n\nLemma LocallySorted_end_relation: forall {A:Type} {R: relation A} l x,\n  Transitive R ->\n  (forall t : A, In t l -> R t x) -> LocallySorted R l ->\n    LocallySorted R (l ++ [x]).\nProof.\n  intros; generalize dependent l;\n  induction l; intros; simpl; auto.\n  apply LocallySorted_hd_relation; intros;\n  apply Sorted_LocallySorted_iff in H1;\n  apply Sorted_StronglySorted in H1; auto;\n  apply StronglySorted_inv in H1; destruct H1 as [EQ ED];\n  rewrite Forall_forall in ED. apply in_app_or in H2. destruct H2; auto.\n  - simpl in H1; intuition; subst.\n    apply H0. simpl. auto.\n  - apply IHl. intros.\n    apply H0. simpl. auto.\n    apply StronglySorted_Sorted in EQ. apply Sorted_LocallySorted_iff; auto.\nQed.\n\nDefinition is_sorting_algo {A: Type} (R: relation A) (f: list A -> list A) :=\n  forall l, Permutation l (f l) /\\ Sorted R (f l).\n\n\n", "meta": {"author": "holmuk", "repo": "Sorticoq", "sha": "ac115f2a80deb5c2db2a56ba6b7adfad043e84b5", "save_path": "github-repos/coq/holmuk-Sorticoq", "path": "github-repos/coq/holmuk-Sorticoq/Sorticoq-ac115f2a80deb5c2db2a56ba6b7adfad043e84b5/Essentials/SortedList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6561123898966797}}
{"text": "Require Import List Lia.\nImport ListNotations.\n\nRequire Import ssreflect ssrbool ssrfun.\n\nSet Default Goal Selector \"!\".\n\n(* Generic facts *)\n\n(* duplicates argument *)\nFact copy {A : Type} : A -> A * A.\nProof. done. Qed.\n\n(* transforms a goal (A -> B) -> C into goals A and B -> C *)\nLemma unnest : forall (A B C : Type), A -> (B -> C) -> (A -> B) -> C.\nProof. auto. Qed.\n\nLemma iter_plus {X: Type} {f: X -> X} {x: X} {n m: nat} : Nat.iter n f (Nat.iter m f x) = Nat.iter (n + m) f x.\nProof. elim: n; [done | by move=> n /= ->]. Qed.\n\nFact iter_last {X: Type} {f: X -> X} {n x} : Nat.iter n f (f x) = Nat.iter (1+n) f x.\nProof. elim: n x; [done | by move=> n /= + x => ->]. Qed.\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\n(* List facts *)\nLemma Forall_appI {X: Type} {P : X -> Prop} {A B}: Forall P A -> Forall P B -> Forall P (A ++ B).\nProof. move=> ? ?. apply /Forall_app. by constructor. Qed.\n\nLemma incl_nth_error {X: Type} {Gamma Gamma': list X} : \n  incl Gamma Gamma' -> exists ξ, forall x, nth_error Gamma x = nth_error Gamma' (ξ x).\nProof.\n  elim: Gamma Gamma'.\n  - move=> Gamma' _. exists (fun x => length Gamma').\n    move=> [|x] /=; apply /esym; by apply /nth_error_None.\n  - move=> x Gamma IH Gamma'. move=> /Forall_forall /Forall_cons_iff.\n    move=> [/(@In_nth_error _ _ _) [nx] Hnx /Forall_forall /IH] [ξ Hξ].\n    exists (fun y => if y is S y then ξ y else nx). by case.\nQed.\n\nLemma Forall_seqP {P : nat -> Prop} {m n: nat} : \n  Forall P (seq m n) <-> (forall i, m <= i < m + n -> P i).\nProof. rewrite Forall_forall. constructor; move=> H ? ?; apply H; by apply /in_seq. Qed.\n\nLemma Forall2_consE {X Y: Type} {R: X -> Y -> Prop} {x y l1 l2} : \n  Forall2 R (x :: l1) (y :: l2) -> R x y /\\ Forall2 R l1 l2.\nProof. move=> H. by inversion H. Qed.\n\nLemma Forall2_length_eq {X Y: Type} {R: X -> Y -> Prop} {l1 l2} : \n  Forall2 R l1 l2 -> length l1 = length l2.\nProof.\n  elim: l1 l2.\n  - move=> [| ? ?] H; first done. by inversion H.\n  - move=> ? ? IH [| ? ?] /= H; inversion H. congr S. by apply: IH.\nQed.\n\nLemma in_app_l {X: Type} {x: X} {l1 l2: list X} : In x l1 -> In x (l1 ++ l2).\nProof. move=> ?. apply /in_app_iff. by left. Qed.\n\nLemma in_app_r {X: Type} {x: X} {l1 l2: list X} : In x l2 -> In x (l1 ++ l2).\nProof. move=> ?. apply /in_app_iff. by right. Qed.\n\n(* construct choice function for a list over nat *)\nLemma list_choice {P : nat -> nat -> Prop} {l: list nat} : Forall (fun i : nat => exists n : nat, P i n) l ->\n  exists φ, Forall (fun i : nat => P i (φ i)) l.\nProof.\n  elim: l; first by exists id.\n  move=> k l IH /Forall_cons_iff [[n Hkn]] /IH [φ Hφ].\n  exists (fun i => if PeanoNat.Nat.eq_dec i k then n else φ i).\n  constructor; first by case: (PeanoNat.Nat.eq_dec k k).\n  apply: Forall_impl Hφ => i Hi.\n  case: (PeanoNat.Nat.eq_dec i k); [by move=> /= ->|done].\nQed.\n\nLemma map_id' {X: Type} {f: X -> X} {l: list X} : (forall x, f x = x) -> map f l = l.\nProof. move=> ?. rewrite -[RHS]map_id. by apply: map_ext => ?. Qed.\n\nLemma is_trueP {b1 b2: bool} : (is_true b1 <-> is_true b2) <-> b1 = b2.\nProof.\n  case: b1; case: b2; rewrite /is_true; firstorder done.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/SystemF/Util/Facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.6561123873071243}}
{"text": "Theorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\n\nProof.\n  intros b c. \n  destruct b.\n  - simpl. destruct c.\n    -- simpl. intros H. reflexivity.\n    -- simpl. intros H. rewrite H. reflexivity.\n  - simpl. destruct c. \n    -- simpl. intros H. reflexivity.\n    -- simpl. intros H. rewrite H. reflexivity.\nQed.", "meta": {"author": "cristianlepore", "repo": "Coq_exercises", "sha": "109d34794edee6bd2b255ed4f7fc3c91edb8c8f5", "save_path": "github-repos/coq/cristianlepore-Coq_exercises", "path": "github-repos/coq/cristianlepore-Coq_exercises/Coq_exercises-109d34794edee6bd2b255ed4f7fc3c91edb8c8f5/Software_foundation/Chapter1/andb_true_elim2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6561123866797787}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra.\nFrom mathcomp Require Import bigenough cauchyreals.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport Order.TTheory GRing.Theory Num.Theory BigEnough.\n\nLocal Open Scope ring_scope.\n\nSection ExtraCreals.\n\nVariable F : realFieldType.\n\nLemma eq_creal_ext (x y : creal F) : x =1 y ->  (x == y)%CR.\nProof.\nmove=> heq; apply/eq_crealP; exists (fun _ => 0%N) => * /=.\nby rewrite heq subrr normr0.\nQed.\n\nLemma ler_lecr  (x y : creal F) : (forall i, x i <= y i) ->  (x <= y)%CR.\nProof.\nmove=> heq; apply: (@le_crealP _ 0%N) => j _; exact: heq.\nQed.\n\n\nLemma ltcr_add2r (z x y : creal F) : (x < y)%CR -> (x + z < y + z)%CR.\nProof.\nmove=> lt_xy; pose_big_enough i.\n  apply: (@lt_crealP _ (diff lt_xy) i i); rewrite ?diff_gt0 //=.\n  by rewrite addrAC ler_add2r diffP.\nby close.\nQed.\n\nLemma ltcr_add2l (z x y : creal F) : (x < y)%CR -> (z + x < z + y)%CR.\nProof.\nmove=> lt_xy; pose_big_enough i.\n  apply: (@lt_crealP _ (diff lt_xy) i i); rewrite ?diff_gt0 //=.\n  rewrite -addrA ler_add2l diffP //.\nby close.\nQed.\n\nLemma addr_gtcr0 (x y : creal F) : (0 < x -> 0 < y -> 0 < x + y)%CR.\nmove=> lt_0x lt_0y.\nhave := ltcr_add2r y lt_0x; rewrite add_0creal => h.\nby apply: lt_creal_trans h.\nQed.\n\nLemma subcr_eq0  (x y : creal F) : (x - y == 0)%CR <-> (x == y)%CR.\nProof.\nsplit => h.\n  rewrite -[y]add_creal0 -h; apply: eq_creal_ext=> i /=; rewrite addrCA subrr.\n  by rewrite addr0.\nby rewrite h; apply: eq_creal_ext=> i /=; rewrite subrr.\nQed.\n\nLemma ltcr_mul2r (z x y : creal F) : \n  (x < y)%CR -> (0 < z)%CR -> (x * z < y * z)%CR.\nProof.\nmove=> ltxy lt0z; pose_big_enough i.\n  apply: (@lt_crealP _ ((diff ltxy) * (diff lt0z)) i i) => //=.\n  - apply: mulr_gt0; exact: diff_gt0.\n  rewrite -ler_sub_addl -mulrBl; apply: ler_pmul.\n  - by apply: ltW; apply: diff_gt0.\n  - by apply: ltW; apply: diff_gt0.\n  - by rewrite ler_sub_addl diffP.\n  - by rewrite -[X in X <= _]add0r -[0]/((0%:CR)%CR i) diffP.\nby close.\nQed.\n\nLemma mulcrN (x y : creal F) : (x * - y == - (x * y))%CR.\nProof. by apply: eq_creal_ext=> i /=; rewrite mulrN. Qed.\n\nLemma mulNcr (x y : creal F) : (- x * y == - (x * y))%CR.\nProof. by apply: eq_creal_ext=> i /=; rewrite mulNr. Qed.\n\nLemma mulcrC (x y : creal F) : (x * y == y * x)%CR.\nProof. by apply: eq_creal_ext=> i /=; rewrite mulrC. Qed.\n\nLemma mulcrA (x y z : creal F) : (x * (y * z) == x * y * z)%CR.\nProof. by apply: eq_creal_ext=> i /=; rewrite mulrA. Qed.\n\nLemma addcrC (x y : creal F) : (x + y == y + x)%CR.\nProof. by apply: eq_creal_ext=> i /=; rewrite addrC. Qed.\n\nLemma addcrA (x y z : creal F) : (x + (y + z) == x + y + z)%CR.\nProof. by apply: eq_creal_ext=> i /=; rewrite addrA. Qed.\n\nLemma addcrN (x : creal F) : (x - x == 0)%CR.\nProof. by apply: eq_creal_ext=> i /=; rewrite addrN. Qed.\n\nLemma mulcrDr (x y z : creal F) : (x * (y + z) == x * y + x * z)%CR.\nProof. by apply: eq_creal_ext=> i /=; rewrite mulrDr. Qed.\n\nLemma mulcrDl (x y z : creal F) : ((y + z) * x == y * x + z * x)%CR.\nProof. by apply: eq_creal_ext=> i /=; rewrite mulrDl. Qed.\n\nLemma ltcr_mul2l (z x y : creal F) : \n  (x < y)%CR -> (0 < z)%CR -> (z * x < z * y)%CR.\nProof. rewrite ![(z * _)%CR]mulcrC; exact: ltcr_mul2r. Qed.\n\n\nLemma ltcr_pmul (x1 y1 x2 y2 : creal F) :\n      (0 < x1)%CR -> (0 < y2)%CR -> (x1 < y1)%CR -> (x2 < y2)%CR -> \n      (x1 * x2 < y1 * y2)%CR.\nProof.\nmove=> px1 px2 lt1 lt2.\nhave aux : (x1 * x2 < x1 * y2)%CR by apply: ltcr_mul2l.\nby apply: lt_creal_trans aux _; apply: ltcr_mul2r.\nQed.\n\nLemma mulr_gtcr0 (x y : creal F) : (0 < x -> 0 < y -> 0 < x * y)%CR.\nmove=> lt_0x lt_0y; pose_big_enough i.\n  apply: (@lt_crealP _ ((diff lt_0x) * (diff lt_0y)) i i) => //=.\n  - apply: mulr_gt0; exact: diff_gt0.\n  rewrite add0r; apply: ler_pmul.\n  - by apply: ltW; apply: diff_gt0.\n  - by apply: ltW; apply: diff_gt0.\n  - by rewrite -[X in X <= _]add0r -[0]/((0%:CR)%CR i) diffP.\n  - by rewrite -[X in X <= _]add0r -[0]/((0%:CR)%CR i) diffP.\nby close.\nQed.\n\nLemma cst_crealM (x y : F) : ((x * y)%:CR == x%:CR * y%:CR)%CR.\nProof. by apply: eq_creal_ext=> i /=. Qed.\n\nLemma cst_crealD (x y : F) : ((x + y)%:CR == x%:CR + y%:CR)%CR.\nProof. by apply: eq_creal_ext=> i /=. Qed.\n\nLemma cst_crealB (x y : F) : ((x - y)%:CR == x%:CR - y%:CR)%CR.\nProof. by apply: eq_creal_ext=> i /=. Qed.\n\nLemma cst_crealN (x : F) : ((- x)%:CR == - x%:CR)%CR.\nProof. by apply: eq_creal_ext=> i /=. Qed.\n\nLemma le_ubound (x : creal F) : (x <= (ubound x)%:CR)%CR.\nProof.\napply: (@le_crealP _ 0%N) => j _ /=.\napply: le_trans (uboundP x j); exact: ler_norm.\nQed.\n\nLemma lt_ubound (x : creal F) : (x < (ubound x + 1)%:CR)%CR.\nProof.\npose_big_enough i.\n  apply: (@lt_crealP _ 1 i i) => //=; rewrite ler_add2r.\n  apply: le_trans (uboundP x i); exact: ler_norm.\nby close.\nQed.\n\nLemma ltcr_le_trans (y x z : creal F): (x < y -> y <= z -> x < z)%CR.\nProof.\nmove=> ltxy leyz; pose_big_enough i.\n  have hpos : 0 < diff ltxy / 2%:~R.\n    apply: divr_gt0; rewrite ?ltr0Sn //; exact: diff_gt0.\n  apply: (@lt_crealP _  ((diff ltxy) / 2%:~R) i i) => //=.\n  have -> : x i + diff ltxy / 2%:~R = x i + diff ltxy - diff ltxy / 2%:~R.\n    apply/eqP; rewrite eq_sym subr_eq -addrA -mulrDr.\n    have <- : 1 = 2%:~R^-1 + 2%:~R^-1 :> F by rewrite [LHS](splitf 2) div1r.\n    by rewrite mulr1.\n  rewrite ler_subl_addr; apply: le_trans (diffP _ _) _ => //; apply: ltW.\n  by apply: le_modP.\nby close.\nQed.\n\nLemma lecr_lt_trans (y x z : creal F): (x <= y)%CR -> (y < z)%CR -> (x < z)%CR.\nProof.\n(* We could just use the opposites but we do not have the lemmas... *)\n(* Hence we copy paste mutatis mutandis the previous proof *)\nmove=> lexy ltyz; pose_big_enough i.\n  have hpos : 0 < diff ltyz / 2%:~R.\n    apply: divr_gt0; rewrite ?ltr0Sn //; exact: diff_gt0.\n  apply: (@lt_crealP _  ((diff ltyz) / 2%:~R) i i) => //=.\n  apply: le_trans (@diffP _ _ _ ltyz _ _ _) => //; rewrite -ler_subr_addr.\n  suff <- : y i + diff ltyz / 2%:~R = y i + diff ltyz - diff ltyz / 2%:~R.\n    by apply: ltW; apply: le_modP.\n  apply/eqP; rewrite eq_sym subr_eq -addrA -mulrDr.\n  have <- : 1 = 2%:~R^-1 + 2%:~R^-1 :> F by rewrite [LHS](splitf 2) div1r.\n  by rewrite mulr1. \nby close.\nQed.\n\nLemma lecr_trans (y x z : creal F): (x <= y -> y <= z -> x <= z)%CR.\nProof.\nmove=> lexy leyz ltzx; apply: (@eq_creal_refl _ z); apply: lt_creal_neq.\nby apply: ltcr_le_trans leyz; apply: ltcr_le_trans lexy.\nQed.\n\nLemma lecr_mulf2r (z : F) (x y : creal F) : \n  (x <= y)%CR ->  0 <= z -> (x * z%:CR <= y * z%:CR)%CR.\nProof.\nmove=> lexy.\nrewrite le_eqVlt; case/orP=> [/eqP <- | lt0z]; first by rewrite !mul_creal0.\nmove => h; apply: lexy.\nhave aux t : (t == t * z%:CR * z^-1%:CR)%CR.\n  rewrite -mulcrA -cst_crealM mulfV ?mul_creal1 //; move: lt0z; rewrite lt0r.\n  by case/andP.\nrewrite [x]aux {}[y]aux; apply: ltcr_mul2r => //; apply/lt_creal_cst.\nby rewrite invr_gt0.\nQed.\n\n\nLemma lecr_mulf2l (z : F) (x y : creal F) : (x <= y)%CR ->  \n  0 <= z -> (z%:CR * x <= z%:CR * y)%CR.\nProof. by rewrite ![(z%:CR * _)%CR]mulcrC; apply: lecr_mulf2r. Qed.\n\nLemma lecr_lt_add (x y z t : creal F) : (x <= y -> z < t -> x + z < y + t)%CR.\nProof. \nmove=> lxy lzt; apply: (@lecr_lt_trans (y + z)%CR); last exact: ltcr_add2l.\nmove/(ltcr_add2l (-z)%CR)=> abs; apply: lxy; move: abs.\nby rewrite ![(- z + _)%CR]addcrC -!addcrA addcrN !add_creal0.\nQed.\n\nLemma ltcr_le_add (x y z t : creal F) : (x < y -> z <= t -> x + z < y + t)%CR.\nProof.\nmove=> *; rewrite [X in (X < _)%CR]addcrC [X in (_ < X)%CR]addcrC. \nby apply: lecr_lt_add. \nQed.\n\nLemma ltcr_spaddl (y x z : creal F) : (0 < x -> y <= z -> y < x + z)%CR.\nProof. move=> *; rewrite -[y]add_0creal; exact: ltcr_le_add. Qed.\n\nLemma ltcr_spaddr (y x z : creal F) : (0 < x -> y <= z -> y < z + x)%CR.\nProof. move=> *; rewrite -[y]add_creal0; exact: lecr_lt_add. Qed.\n\nLemma asympt_eq_creal (x : creal F) (y : nat -> F) :\n  {asympt e : i / `|x i - y i| < e} ->  creal_axiom y.\nProof.\ncase: x => x [mx mxP]; case=> M MP; \nexists_big_modulus m F.\n  move=> eps i j lt_eps_0 hmi hmj; pose d (k : nat) := x k - y k.\n  have -> : y i - y j = d j + (x i - x j) - d i.\n    rewrite /d [(_ - _) + _]addrC addrA addrNK opprB addrA [_ - x i]addrC.\n    by rewrite addrA addKr addrC.\n  suff step1 : `|d j + (x i - x j)| + `|d i| < eps.\n    by apply: le_lt_trans step1; rewrite -[`|d i|]normrN; apply: ler_norm_add.\n  suff step2 : `|d j| + `|x i - x j| + `|d i| < eps.\n    by apply: le_lt_trans step2; rewrite ler_add2r; apply: ler_norm_add.\n  have -> : eps = eps / 3%:~R + eps / 3%:~R + eps / 3%:~R.\n    rewrite /= in eps lt_eps_0 hmi hmj *.\n    rewrite -!mulrDl -[in X in _ = X](mulr1 eps) -!mulrDr -mulrA.\n    suff -> : (1 + 1 + 1) / 3%:~R = 1 :> F by rewrite mulr1.\n    rewrite -[X in (X + X + X) / _ = _]/(1%:~R) -!rmorphD /= mulfV //.\n    by rewrite intr_eq0.\n  have heps : 0 < eps / 3%:~R by apply: divr_gt0 => //; rewrite ltr0z.\n  apply: ltr_add => //; last exact: MP.\n  apply: ltr_add=> //; first by exact: MP.\n  by move=> {MP}; apply: mxP.\nby close.\nQed.\n\nEnd ExtraCreals.\n", "meta": {"author": "coq-community", "repo": "apery", "sha": "305046d98025d75ca426cc44283302963389f1dc", "save_path": "github-repos/coq/coq-community-apery", "path": "github-repos/coq/coq-community-apery/apery-305046d98025d75ca426cc44283302963389f1dc/theories/extra_cauchyreals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.6561123824817728}}
{"text": "(* Suppress some annoying warnings from Coq: *)\nSet Warnings \"-notation-overridden,-parsing\".\nAdd LoadPath \"lf/\"\nRequire Import lists.\n\n(* Polymorphic lists *)\nInductive list (X : Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n    | 0 => nil X\n    | S count' => cons X x (repeat X x count')\n  end.\n\nExample test_repeat_1:\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\n\nProof.\n  reflexivity. Qed.\n\nExample test_repeat_2:\n  repeat bool false 1 = cons bool false (nil bool).\n\nProof.\n  reflexivity. Qed.\n\n(* Exercise *)\nModule MumbleGrumble.\n\nInductive mumble : Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\n\nInductive grumble (X : Type) : Type :=\n  | d : mumble -> grumble X\n  | e : X -> grumble X.\n\n(* Check d (b a 5). *)\nCheck d mumble (b a 5).\nCheck d bool (b a 5).\nCheck e bool true.\nCheck e mumble (b c 0).\n(* Check e bool (b c 0). *)\nCheck c.\n\n(* Demonstrating type 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.\n\n(* and holes *)\nFixpoint repeat'' X x count : list X :=\n  match count with\n    | 0 => nil _\n    | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n(* and `Arguments` directive *)\nArguments nil {X}.\nArguments cons {X}.\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n    | 0 => nil\n    | S count' => cons x (repeat''' x count')\n  end.\n\nCheck repeat.\nCheck repeat'.\nCheck repeat''.\nCheck repeat'''.\n\n(* Reimplementing some standard list functions on the new polymorphic lists *)\nFixpoint app {X : Type} (m n : list X) : list X :=\n  match m with\n    | nil => n\n    | cons h t => cons h (app t n)\n  end.\n\nFixpoint rev {X : Type} (l : list X) : list X :=\n  match l with\n    | nil => nil\n    | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n    | nil => 0\n    | cons _ l' => S (length l')\n  end.\n\nExample test_rev_1:\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\n\nProof.\n  reflexivity. Qed.\n\nExample test_rev_2:\n  rev (cons true nil) = cons true nil.\n\nProof.\n  reflexivity. Qed.\n\nExample test_length_1:\n  length (cons 1 (cons 2 (cons 3 nil))) = 3.\n\nProof.\n  reflexivity. Qed.\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(* Exercise *)\nTheorem app_nil_r: forall (X : Type), forall l : list X,\n  l ++ [] = l.\n\nProof.\n  intros.\n  induction l as [| k l' IHl' ].\n  - simpl. 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.\n\nProof.\n  intros.\n  induction l as [| k l' IHl' ].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHl'. reflexivity.\n  Qed.\n\nLemma app_length: forall (X : Type) (m n : list X),\n  length (m ++ n) = length m + length n.\n\nProof.\n  intros.\n  induction m as [| l m' IHm' ].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHm'. reflexivity.\n  Qed.\n\n(* Exercise *)\nTheorem rev_app_distr: forall X (m n : list X),\n  rev (m ++ n) = rev n ++ rev m.\n\nProof.\n  intros.\n  induction m as [| k m' IHm' ].\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IHm', app_assoc. reflexivity.\n  Qed.\n\n(* Exercise *)\nTheorem rev_involutive: forall X : Type, forall l : list X,\n  rev (rev l) = l.\n\nProof.\n  intros.\n  induction l as [| k l' IHl' ].\n  - simpl. reflexivity.\n  - simpl.\n    rewrite -> rev_app_distr.\n    simpl. rewrite IHl'.\n    reflexivity.\n  Qed.\n\n(* Demonstrating 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\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 *)\nCompute (combine [1;2] [false;false;true;true]).\n\n(* Exercise *)\nFixpoint iter_fst {X Y : Type} (l : list (X * Y))\n  : list X :=\n  match l with\n    | [] => nil\n    | p :: t => cons (fst p) (iter_fst t)\n  end.\n\nFixpoint iter_snd {X Y : Type} (l : list (X * Y))\n  : list Y :=\n  match l with\n    | [] => nil\n    | p :: t => cons (snd p) (iter_snd t)\n  end.\n\nDefinition split {X Y : Type} (l : list (X * Y))\n  : (list X) * (list Y) := (iter_fst l, iter_snd l).\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\n\nProof.\n  reflexivity. Qed.\n\n(* Introducing functions *)\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 *)\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\n        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.\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 odd l).\nExample test_countoddmembers'1: countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers'2: countoddmembers' [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers'3: countoddmembers' nil = 0.\nProof. reflexivity. Qed.\n\n(* Demonstrating anonymous functions *)\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\n\nProof.\n  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] ].\n\nProof. reflexivity. Qed.\n\n(* Exercise *)\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun x => bgt_nat x 7) (filter even l).\n\nCompute filter_even_gt7  [1;2;6;9;10;3;12;8].\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\n\nProof.\n  reflexivity. Qed.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\n\nProof.\n  reflexivity. Qed.\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 odd [1;2;3;4;5] = ([1;3;5], [2;4]).\n\nProof.\n  reflexivity. Qed.\n\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\n\nProof.\n  reflexivity. Qed.\n\n(* 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\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\nExample test_map2:\n  map odd [2;1;2;5] = [false;true;false;true].\nProof. reflexivity. Qed.\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. reflexivity. Qed.\n\n(* Exercise *)\nLemma map_app_distr:\n  forall (X Y : Type) (f: X -> Y) (l: list X) (m: list X),\n  map f (l ++ m) = (map f l) ++ (map f m).\n\nProof.\n  intros.\n  induction l as [| k l' IHl' ].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHl'. reflexivity.\n  Qed.\n\nTheorem map_rev :\n  forall (X Y : Type) (f: X -> Y) (l: list X),\n  map f (rev l) = rev (map f l).\n\nProof.\n  intros.\n  induction l as [| k l' IHl' ].\n  - simpl. reflexivity.\n  - simpl.\n    rewrite -> map_app_distr.\n    simpl.\n    rewrite -> IHl'.\n    reflexivity.\n  Qed.\n\n(* Exercise *)\nFixpoint flat_map\n  {X Y: Type} (f: X -> list Y) (l: list X)\n  : (list Y) :=\n  match l with\n    | nil => nil\n    | h :: t => (f h) ++ (flat_map f t)\n  end.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\n\nProof.\n  reflexivity. Qed.\n\n(* Demonstrating fold *)\nFixpoint fold {X Y : Type} (f: X -> Y -> Y)\n  (l: list X) (b: Y) : Y :=\n  match l with\n    | nil => b\n    | h :: t => f h (fold f t b)\n  end.\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof.\n  reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof.\n  reflexivity. Qed.\n\nExample fold_example3 :\n  fold app [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof.\n  reflexivity. Qed.\n\nEnd MumbleGrumble.\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/poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.6561123808733224}}
{"text": "Require Import FunInd Arith Lia.\n\nInductive NETree (A : Type) : Type :=\n    | T : A -> Forest A -> NETree A\n\nwith Forest (A : Type) : Type :=\n    | E : Forest A\n    | F : NETree A -> Forest A -> Forest A.\n\nArguments T {A} _ _.\nArguments E {A}.\nArguments F {A} _ _ .\n\nFunction auxT {A : Type} (t : NETree A) (k : nat) (acc : nat)\n  : NETree (option nat) * nat :=\nmatch t with\n    | T _ f =>\n        let\n          '(f', acc') := auxF f k acc\n        in\n          if leb acc' k\n          then (T (Some acc') f', S acc')\n          else (T None f', acc')\nend\nwith auxF {A : Type} (f : Forest A) (k : nat) (acc : nat)\n  : Forest (option nat) * nat :=\nmatch f with\n    | E => (E, acc)\n    | F t f' =>\n        let\n          '(t', acc') := auxT t k acc\n        in let\n          '(f'', acc'') := auxF f' k acc\n        in\n          (F t' f'', max acc' acc'')\nend.\n\n(** An algorithm that colors a tree so that at most k nodes in each\n    path are colored. *)\nDefinition color {A : Type} (k : nat) (t : NETree A) : NETree (option nat) :=\n  fst (auxT t k 1).\n\nDefinition wut :=\n  T 1 (F (T 2 (F (T 5 E) E)) (F (T 3 E) (F (T 4 E) E))).\n\nLemma specT :\n  forall (A : Type) (t : NETree A) (t' : NETree (option nat)) (k acc acc' : nat),\n    acc <= k -> auxT t k acc = (t', acc') -> acc' <= S k\n\nwith specF :\n  forall (A : Type) (f : Forest A) (f' : Forest (option nat))\n  (k acc acc' : nat),\n    acc <= k -> auxF f k acc = (f', acc') -> acc' <= S k.\nProof.\n  destruct t; simpl; intros. case_eq (auxF f k acc); intros.\n  case_eq (n <=? k); intro; rewrite H1, H2 in H0;\n  inversion H0; subst; clear H0.\n    apply leb_complete in H2. apply le_n_S. assumption.\n    apply (specF A _ _ _ _ _ H H1).\n  destruct f; simpl; intros; inversion H0; subst; clear H0.\n    apply le_S. assumption.\n    case_eq (auxT n k acc); intros; case_eq (auxF f k acc); intros.\n      rewrite H0, H1 in H2. inversion H2; subst; clear H2.\n        apply Nat.max_lub; [eapply specT | eapply specF]; eauto.\nQed.\n\nInductive elem {A : Type} (x : A) : NETree A -> Prop :=\n    | elem0 :\n        forall (y : A) (f : Forest A),\n          x = y \\/ elemF x f -> elem x (T y f)\n\nwith elemF {A : Type} (x : A) : Forest A -> Prop :=\n    | elemF0 :\n        forall (t : NETree A) (f : Forest A),\n          elem x t \\/ elemF x f -> elemF x (F t f).\n\nLtac inv H := inversion H; subst; clear H.\n\nLemma auxT_spec2 :\n  forall (A : Type) (x : option nat) (t : NETree A) (t' : NETree (option nat))\n  (k acc acc' : nat),\n    acc <= k -> auxT t k acc = (t', acc') -> elem x t' ->\n      x = None \\/ exists k' : nat, x = Some k' /\\ k' <= k\n\nwith auxF_spec2 :\n  forall (A : Type) (x : option nat) (f : Forest A) (f' : Forest (option nat))\n  (k acc acc' : nat),\n    acc <= k -> auxF f k acc = (f', acc') -> elemF x f' ->\n      x = None \\/ exists k' : nat, x = Some k' /\\ k' <= k.\nProof.\n  destruct t; simpl; intros.\n  case_eq (auxF f k acc); intros. rewrite H2 in *.\n  case_eq (n <=? k); intros; rewrite H3 in *; inv H0.\n    inv H1. destruct H4.\n      right. exists n. split; auto. apply leb_complete. assumption.\n      eapply auxF_spec2; eauto.\n    inv H1. destruct H4.\n      left. assumption.\n      eapply auxF_spec2; eauto.\n  destruct f; simpl; intros; inv H0.\n    inv H1.\n    case_eq (auxT n k acc); intros; rewrite H0 in *.\n    case_eq (auxF f k acc); intros; rewrite H2 in *.\n      inv H3. inv H1. destruct H4.\n        eapply auxT_spec2; eauto.\n        eapply auxF_spec2; eauto.\nQed.", "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/Data/NonEmptyTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6560447297427706}}
{"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 Eqdep_dec.\n\nFrom Undecidability.Shared.Libs.DLW.Utils\n  Require Import utils_list finite.\n\nSet Implicit Arguments.\n\n(* * First order operators and their semantics *)\n\nInductive fol_bop := fol_conj | fol_disj | fol_imp.\nInductive fol_qop := fol_ex | fol_fa.\n\nDefinition fol_bin_sem b :=\n  match b with\n    | fol_conj => and\n    | fol_disj => or\n    | fol_imp  => fun A B => A -> B\n  end.\n\nFact fol_bin_sem_ext b A A' B B' :\n     (A <-> A') -> (B <-> B') -> (fol_bin_sem b A B <-> fol_bin_sem b A' B').\nProof.\n  intros E1 E2; destruct b; simpl; tauto.\nQed. \n\nFact fol_equiv_sem_ext A A' B B' : (A <-> A') -> (B <-> B') -> (A <-> B) <-> (A' <-> B').\nProof. tauto. Qed.\n\nFact fol_equiv_ext (P Q : Prop) : P = Q -> P <-> Q.\nProof. intros []; tauto. Qed.\n\nFact fol_equiv_impl A A' B B' : (A <-> A') -> (B <-> B') -> (A <-> B) -> (A' <-> B').\nProof. tauto. Qed.\n\nArguments fol_bin_sem b /.\n\nFact fol_bin_sem_dec b A B : \n       { A } + { ~ A } -> { B } + { ~ B } \n    -> { fol_bin_sem b A B } + { ~ fol_bin_sem b A B }.\nProof. revert b; intros [] HA HB; simpl; tauto. Qed.\n\nFact fol_equiv_dec A B : \n       { A } + { ~ A } -> { B } + { ~ B } \n    -> { A <-> B } + { ~ (A <-> B) }.\nProof. tauto. Qed.\n\nDefinition fol_quant_sem X q (P : X -> Prop) :=\n  match q with\n    | fol_ex => ex P\n    | fol_fa => forall x, P x \n  end.\n\nArguments fol_quant_sem X q P /.\n\nFact fol_quant_sem_ext X q (P Q : X -> Prop) : \n        (forall x, P x <-> Q x) \n      -> fol_quant_sem q P <-> fol_quant_sem q Q.\nProof.\n  revert q; intros [] H; simpl.\n  + split; intros (k & ?); exists k; apply H; auto.\n  + split; intros ? k; apply H; auto. \nQed.\n\nNotation forall_equiv := (@fol_quant_sem_ext _ fol_fa).\nNotation exists_equiv := (@fol_quant_sem_ext _ fol_ex).\n\nTactic Notation \"fol\" \"equiv\" \"fa\" := apply forall_equiv.\nTactic Notation \"fol\" \"equiv\" \"ex\" := apply exists_equiv.\nTactic Notation \"fol\" \"equiv\" \"iff\" := apply fol_equiv_sem_ext.\nTactic Notation \"fol\" \"equiv\" \"conj\" := apply (fol_bin_sem_ext fol_conj).\nTactic Notation \"fol\" \"equiv\" \"disj\" := apply (fol_bin_sem_ext fol_disj).\nTactic Notation \"fol\" \"equiv\" \"imp\" := apply (fol_bin_sem_ext fol_imp).\nTactic Notation \"fol\" \"equiv\" \"rel\" := apply fol_equiv_ext; f_equal.\n\nTactic Notation \"fol\" \"equiv\" :=\n  match goal with\n    | |- (forall _, _) <-> (forall _, _) => fol equiv fa\n    | |- (exists _, _) <-> (exists _, _) => fol equiv ex\n    | |- ( _ <-> _) <-> (_ <-> _) => fol equiv iff\n    | |- ( _ \\/ _) <-> (_ \\/ _) => fol equiv disj\n    | |- ( _ /\\ _) <-> (_ /\\ _) => fol equiv conj\n    | |- ( _ -> _) <-> (_ -> _) => fol equiv imp\n    | |- ?r _ _ <-> ?r _ _ => fol equiv rel\n  end.\n\nFact forall_list_sem_dec X (P : X -> Prop) (l : list X) :  \n       (forall x, { P x } + { ~ P x }) \n    -> { forall x, In x l -> P x } + { ~ forall x, In x l -> P x }.\nProof.\n  intros H. \n  destruct list_dec with (P := fun x => ~ P x) (Q := P) (l := l)\n      as [ (x & H1 & H2) | H1 ].\n  + firstorder.\n  + right; contradict H2; auto.\n  + left; intros x; apply H1; auto.\nQed.\n\nFact exists_list_sem_dec X (P : X -> Prop) (l : list X) :  \n       (forall x, { P x } + { ~ P x }) \n    -> { exists x, In x l /\\ P x } + { ~ exists x, In x l /\\ P x }.\nProof.\n  intros H. \n  destruct list_dec with (P := P) (Q := fun x => ~ P x) (l := l)\n      as [ (x & H1 & H2) | H1 ]; auto.\n  + left; firstorder.\n  + right; intros (y & Hy).\n    apply (H1 y); tauto.\nQed.\n\nFact fol_quant_sem_dec X q (P : X -> Prop) : \n       finite_t X \n    -> (forall x, { P x } + { ~ P x }) \n    -> { fol_quant_sem q P } + { ~ fol_quant_sem q P }.\nProof.\n  intros (lX & HlX). \n  revert q; intros [] H; simpl.\n  + destruct exists_list_sem_dec with (l := lX) (1 := H); firstorder.\n  + destruct forall_list_sem_dec with (l := lX) (1 := H); firstorder.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/FOL/TRAKHTENBROT/fol_ops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6560408441899787}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.proposition_05.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_equalanglesNC.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_supplements.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma proposition_05b : \n   forall A B C F G, \n   isosceles A B C -> BetS A B F -> BetS A C G ->\n   CongA C B F B C G.\nProof.\nintros.\nassert (CongA A B C A C B) by (conclude proposition_05).\nassert (eq C C) by (conclude cn_equalityreflexive).\nassert (nCol A C B) by (conclude lemma_equalanglesNC).\nassert (~ eq B C).\n {\n intro.\n assert (Col A B C) by (conclude_def Col ).\n assert (Col A C B) by (forward_using lemma_collinearorder).\n contradict.\n }\nassert (neq C B) by (conclude lemma_inequalitysymmetric).\nassert (Out B C C) by (conclude lemma_ray4).\nassert (Supp A B C C F) by (conclude_def Supp ).\nassert (eq B B) by (conclude cn_equalityreflexive).\nassert (Out C B B) by (conclude lemma_ray4).\nassert (Supp A C B B G) by (conclude_def Supp ).\nassert (CongA C B F B C G) by (conclude lemma_supplements).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/proposition_05b.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6560408222357368}}
{"text": "(** Adapted from \"Elements of Set Theory\" Chapter 2 **)\n(** Coq coding by choukh, May 2020 **)\n\nRequire Export ZFC.Lib.Essential.\n\n(*** EST第二章：补集，真子集，集合代数定律 ***)\n\n(** 补集 **)\nDefinition Complement : set → set → set := λ A B, {x ∊ A | x ∉ B}.\nNotation \"A - B\" := (Complement A B) : set_scope.\n\nLemma CompI : ∀ A B, ∀x ∈ A, x ∉ B → x ∈ A - B.\nProof. intros A B x Hx H. apply SepI. apply Hx. apply H. Qed.\n\nLemma CompE : ∀ A B, ∀x ∈ A - B, x ∈ A ∧ x ∉ B.\nProof. intros A B x Hx. apply SepE in Hx. apply Hx. Qed.\n\nLemma CompNE : ∀ A B x, x ∉ A - B → x ∉ A ∨ x ∈ B.\nProof.\n  intros. destruct (classic (x ∈ B)).\n  - right. apply H0.\n  - left. intros H1. apply H. apply CompI; assumption.\nQed.\n\nLemma sub_iff_no_comp : ∀ A B, A ⊆ B ↔ A - B = ∅.\nProof.\n  split; intros.\n  - apply EmptyI. intros x Hx. apply CompE in Hx as [H1 H2].\n    apply H2. apply H. apply H1.\n  - intros x Hx. apply EmptyE with (A - B) x in H.\n    destruct (classic (x ∈ B)). apply H0.\n    exfalso. apply H. apply CompI; assumption.\nQed.\n\nLemma comp_sub : ∀ A B, A - B ⊆ A.\nProof.\n  intros A B x Hx. apply CompE in Hx as []; auto.\nQed.\nGlobal Hint Immediate comp_sub : core.\n\n(* 空集的补集是原集合 *)\nLemma comp_empty : ∀ A, A - ∅ = A.\nProof with auto.\n  intros. ext Hx.\n  - apply SepE1 in Hx...\n  - apply SepI... intros H. exfalso0.\nQed.\n\n(* 空集里的补集是空集 *)\nLemma empty_comp : ∀ A, ∅ - A = ∅.\nProof with auto.\n  intros. ext Hx.\n  - apply SepE in Hx as []. exfalso0.\n  - exfalso0.\nQed.\n\n(* 集合加入自身的元素，集合不变 *)\nLemma add_no_member : ∀ A a, a ∈ A → A ∪ {a,} = A.\nProof with auto.\n  intros * Ha. ext Hx.\n  - apply BUnionE in Hx as []... apply SingE in H. subst...\n  - apply BUnionI1...\nQed.\n\n(* 集合除去非自身的元素，集合不变 *)\nLemma remove_no_member : ∀ A a, a ∉ A → A - {a,} = A.\nProof with auto.\n  intros * Ha. ext Hx.\n  - apply SepE1 in Hx...\n  - apply SepI... apply SingNI. intros Heq.\n    apply Ha. subst...\nQed.\n\n(* 集合加入一个不是自身的元素再去掉，集合不变 *)\nLemma add_one_member_then_remove : ∀ A a, a ∉ A → (A ∪ {a,}) - {a,} = A.\nProof with auto.\n  intros. ext Hx.\n  - apply SepE in Hx as [].\n    apply BUnionE in H0 as []... exfalso...\n  - apply SepI. apply BUnionI1...\n    apply SingNI. intros Heq. congruence.\nQed.\n\n(* 集合除去自身的一个元素再放回去，集合不变 *)\nLemma remove_one_member_then_return : ∀ A a, a ∈ A → (A - {a,}) ∪ {a,} = A.\nProof with auto.\n  intros. ext Hx.\n  - apply BUnionE in Hx as [].\n    + apply SepE1 in H0...\n    + apply SingE in H0. subst...\n  - destruct (classic (x = a)).\n    + subst. apply BUnionI2...\n    + apply BUnionI1. apply SepI... apply SingNI...\nQed.\n\n(* 从集合中取出一个元素组成单集，它与取完元素后的集合的并等于原集合 *)\nCorollary split_one_element : ∀ A a, a ∈ A → A = (A - {a,}) ∪ {a,}.\nProof. intros. symmetry. apply remove_one_member_then_return; auto. Qed.\n\n(** 真子集 **)\nNotation \"A ⊂ B\" := (A ⊆ B ∧ A ≠ B) (at level 70) : set_scope.\n\nLemma properSub_intro : ∀ A B, B ⊆ A → (∃ a, a ∈ A ∧ a ∉ B) → B ⊂ A.\nProof.\n  intros A B Hsub [a [Ha Ha']].\n  split. apply Hsub. intros Heq.\n  apply Ha'. congruence.\nQed.\n\nLemma comp_nonempty : ∀ B A, B ⊂ A → ⦿ (A - B).\nProof.\n  intros * [Hsub Hnq]. apply EmptyNE.\n  intros H0. apply sub_iff_no_comp in H0.\n  apply Hnq. apply sub_antisym. apply Hsub. apply H0.\nQed.\n\n(* 并，交，补运算与子集关系构成集合代数，\n  类似与自然数的加，乘，减运算与小于等于关系 *)\n\n(** 集合代数定律 **)\n\n(* 二元并交换律 *)\nLemma bunion_comm : ∀ A B, A ∪ B = B ∪ A.\nProof.\n  intros. ext.\n  - apply BUnionE in H. destruct H.\n    + apply BUnionI2. apply H.\n    + apply BUnionI1. apply H.\n  - apply BUnionE in H. destruct H.\n    + apply BUnionI2. apply H.\n    + apply BUnionI1. apply H.\nQed.\n\n(* 二元交交换律 *)\nLemma binter_comm : ∀ A B, A ∩ B = B ∩ A.\nProof.\n  intros. ext.\n  - apply BInterE in H as [H1 H2].\n    apply BInterI. apply H2. apply H1.\n  - apply BInterE in H as [H1 H2].\n    apply BInterI. apply H2. apply H1.\nQed.\n\n(* 二元并结合律 *)\nLemma bunion_assoc : ∀ A B C, A ∪ (B ∪ C) = (A ∪ B) ∪ C.\nProof.\n  intros. ext.\n  - apply BUnionE in H. destruct H.\n    + apply BUnionI1. apply BUnionI1. apply H.\n    + apply BUnionE in H. destruct H.\n      * apply BUnionI1. apply BUnionI2. apply H.\n      * apply BUnionI2. apply H.\n  - apply BUnionE in H. destruct H.\n    + apply BUnionE in H. destruct H.\n      * apply BUnionI1. apply H.\n      * apply BUnionI2. apply BUnionI1. apply H.\n    + apply BUnionI2. apply BUnionI2. apply H.\nQed.\n\n(* 二元交结合律 *)\nLemma binter_assoc : ∀ A B C, A ∩ (B ∩ C) = (A ∩ B) ∩ C.\nProof.\n  intros. ext.\n  - apply BInterE in H as [H1 H2].\n    apply BInterE in H2 as [H2 H3].\n    repeat apply BInterI; auto.\n  - apply BInterE in H as [H1 H2].\n    apply BInterE in H1 as [H0 H1].\n    repeat apply BInterI; auto.\nQed.\n\n(* 交并分配律 *)\nLemma binter_bunion_distr : ∀ A B C,\n  A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C).\nProof.\n  intros. ext.\n  - apply BInterE in H as [H1 H2].\n    apply BUnionE in H2. destruct H2.\n    + apply BUnionI1. apply BInterI; auto.\n    + apply BUnionI2. apply BInterI; auto.\n  - apply BUnionE in H. destruct H.\n    + apply BInterE in H as [H1 H2].\n      apply BInterI. apply H1. apply BUnionI1. apply H2.\n    + apply BInterE in H as [H1 H2].\n      apply BInterI. apply H1. apply BUnionI2. apply H2.\nQed.\n\n(* 并交分配律 *)\nLemma bunion_binter_distr : ∀ A B C,\n  A ∪ (B ∩ C) = (A ∪ B) ∩ (A ∪ C).\nProof.\n  intros. ext.\n  - apply BUnionE in H. destruct H.\n    + apply BInterI; apply BUnionI1; apply H.\n    + apply BInterE in H as [H1 H2].\n      apply BInterI; apply BUnionI2; auto.\n  - apply BInterE in H as [H1 H2].\n    apply BUnionE in H1. apply BUnionE in H2.\n    destruct H1; destruct H2.\n    + apply BUnionI1. apply H.\n    + apply BUnionI1. apply H.\n    + apply BUnionI1. apply H0.\n    + apply BUnionI2. apply BInterI; auto.\nQed.\n\n(* 二元并德摩根定律 *)\nLemma bunion_demorgen : ∀ A B x, x ∉ A ∪ B ↔ x ∉ A ∧ x ∉ B.\nProof.\n  intros. split; intros.\n  - split; intros.\n    + intros HA. apply H. apply BUnionI1. apply HA.\n    + intros HB. apply H. apply BUnionI2. apply HB.\n  - destruct H as [H1 H2]. intros H.\n    apply BUnionE in H. destruct H; auto.\nQed.\n\n(* 并补对偶律 *)\nLemma bunion_comp : ∀ A B C, (A ∪ B) - C = (A - C) ∪ (B - C).\nProof.\n  intros. ext.\n  - apply CompE in H. destruct H as [H HC].\n    apply BUnionE in H. destruct H.\n    + apply BUnionI1. apply CompI. apply H. apply HC.\n    + apply BUnionI2. apply CompI. apply H. apply HC.\n  - apply BUnionE in H. destruct H.\n    + apply CompE in H as [HA HC].\n      apply CompI. apply BUnionI1. apply HA. apply HC.\n    + apply CompE in H as [HB HC].\n      apply CompI. apply BUnionI2. apply HB. apply HC.\nQed.\n\n(* 补并对偶律 *)\nLemma comp_bunion : ∀ A B C, C - (A ∪ B) = (C - A) ∩ (C - B).\nProof.\n  intros. ext.\n  - apply CompE in H as [H1 H2].\n    apply bunion_demorgen in H2. destruct H2 as [H2 H3].\n    apply BInterI; apply CompI; auto.\n  - apply BInterE in H as [H1 H2].\n    apply CompE in H1 as [HC HA].\n    apply CompE in H2 as [_ HB].\n    apply CompI. apply HC. apply bunion_demorgen. auto.\nQed.\n\n(* 二元交德摩根定律 *)\nLemma binter_demorgen : ∀ A B x, x ∉ A ∩ B ↔ x ∉ A ∨ x ∉ B.\nProof.\n  intros. split; intros.\n  - destruct (classic (x ∈ A)).\n    + right. intros HB. apply H.\n      apply BInterI; auto.\n    + left. apply H0.\n  - intros H0. destruct H.\n    + apply H. apply BInterE in H0 as [H0 _]. apply H0.\n    + apply H. apply BInterE in H0 as [_ H0]. apply H0.\nQed.\n\n(* 交补结合律 *)\nLemma binter_comp : ∀ A B C, (A ∩ B) - C = A ∩ (B - C).\nProof with auto.\n  intros. ext.\n  - apply CompE in H as [H1 H2].\n    apply BInterE in H1 as [H0 H1].\n    apply BInterI... apply CompI...\n  - apply BInterE in H as [H1 H2].\n    apply CompE in H2 as [H2 H3].\n    apply CompI... apply BInterI...\nQed.\n\n(* 交补对偶律 *)\nLemma comp_binter : ∀ A B C, C - (A ∩ B) = (C - A) ∪ (C - B).\nProof.\n  intros. ext.\n  - apply CompE in H as [HC H].\n    apply binter_demorgen in H. destruct H.\n    + apply BUnionI1. apply CompI. apply HC. apply H.\n    + apply BUnionI2. apply CompI. apply HC. apply H.\n  - apply BUnionE in H. destruct H.\n    + apply CompE in H as [HC HA].\n      apply CompI. apply HC. apply binter_demorgen. left. apply HA.\n    + apply CompE in H as [HC HB].\n      apply CompI. apply HC. apply binter_demorgen. right. apply HB.\nQed.\n\n(* 涉及空集的同一性 *)\n\nLemma bunion_empty : ∀ A, A ∪ ∅ = A.\nProof.\n  intros. ext.\n  - apply BUnionE in H. destruct H. apply H. exfalso0.\n  - apply BUnionI1. apply H.\nQed.\n\nLemma binter_empty : ∀ A, A ∩ ∅ = ∅.\nProof.\n  intros. apply EmptyI. intros x H.\n  apply BInterE in H as [_ H]. exfalso0.\nQed.\n\n(* 涉及全集的同一性 *)\n\nLemma bunion_parent : ∀ A S, A ⊆ S → A ∪ S = S.\nProof.\n  intros. ext.\n  - apply BUnionE in H0. destruct H0.\n    + apply H in H0. apply H0. \n    + apply H0.\n  - apply BUnionI2. apply H0.\nQed.\n\nLemma binter_parent : ∀ A S, A ⊆ S → A ∩ S = A.\nProof.\n  intros. ext.\n  - apply BInterE in H0 as [H0 _]. apply H0.\n  - apply BInterI. apply H0. apply H in H0. apply H0.\nQed.\n\nLemma bunion_comp_parent : ∀ A S, A ⊆ S → A ∪ (S - A) = S.\nProof.\n  intros. ext.\n  - apply BUnionE in H0. destruct H0.\n    + apply H in H0. apply H0.\n    + apply CompE in H0 as [H0 _]. apply H0.\n  - destruct (classic (x ∈ A)).\n    + apply BUnionI1. apply H1.\n    + apply BUnionI2. apply CompI. apply H0. apply H1.\nQed.\n\nLemma binter_comp_empty : ∀ A S, A ∩ (S - A) = ∅.\nProof.\n  intros. apply EmptyI. intros x H.\n  apply BInterE in H as [H1 H2].\n  apply CompE in H2. destruct H2 as [_ H2]. auto.\nQed.\n\n(* 子集关系的单调性 *)\n\nLemma sub_mono_bunion : ∀ A B C, A ⊆ B → A ∪ C ⊆ B ∪ C.\nProof.\n  intros. intros x Hx. apply BUnionE in Hx. destruct Hx.\n  - apply H in H0. apply BUnionI1. apply H0.\n  - apply BUnionI2. apply H0.\nQed.\n\nLemma sub_mono_binter : ∀ A B C, A ⊆ B → A ∩ C ⊆ B ∩ C.\nProof.\n  intros. intros x Hx. apply BInterE in Hx as [H1 H2].\n  apply H in H1. apply BInterI. apply H1. apply H2.\nQed.\n\nLemma sub_mono_union : ∀ A B, A ⊆ B → ⋃A ⊆ ⋃B.\nProof.\n  intros. intros x Hx. apply UnionAx in Hx as [y [H1 H2]].\n  eapply UnionI. apply H in H1. apply H1. apply H2.\nQed.\n\nLemma sub_mono_cprd : ∀ A B C, A ⊆ B → A × C ⊆ B × C.\nProof with auto.\n  intros * H x Hx.\n  apply CPrdE1 in Hx as [a [Ha [b [Hb Hx]]]].\n  subst x. apply CPrdI...\nQed.\n\nLemma sub_mono_cprd' : ∀ A B C, A ⊆ B → C × A ⊆ C × B.\nProof with auto.\n  intros * H x Hx.\n  apply CPrdE1 in Hx as [a [Ha [b [Hb Hx]]]].\n  subst x. apply CPrdI...\nQed.\n\n(* 子集关系的反单调性 *)\n\nLemma sub_amono_comp : ∀ A B C, A ⊆ B → C - B ⊆ C - A.\nProof.\n  intros. intros x Hx. apply CompE in Hx as [HC HB].\n  apply CompI. apply HC. intros HA.\n  apply HB. apply H. apply HA.\nQed.\n\nLemma sub_amono_inter : ∀ A B, ⦿ A → A ⊆ B → ⋂B ⊆ ⋃A.\nProof.\n  intros. intros x Hx. apply InterE in Hx as [_ Hy].\n  destruct H as [a Ha]. eapply UnionI. apply Ha.\n  apply H0 in Ha. apply Hy in Ha. apply Ha.\nQed.\n\n(* 二元并任意交分配律 *)\nLemma bunion_inter_distr : ∀ A ℬ,\n  ⦿ ℬ → A ∪ ⋂ℬ = ⋂{A ∪ X | X ∊ ℬ}.\nProof.\n  intros * Hi. ext.\n  - apply InterI...\n    + destruct Hi as [b Hb]. exists (A ∪ b).\n      apply ReplAx... exists b. split; auto.\n    + intros y Hy. apply ReplAx in Hy as [z [Hz Hu]]. subst y. \n      apply BUnionE in H as [].\n      * apply BUnionI1. apply H.\n      * apply BUnionI2. apply InterE in H as [_ H].\n        apply H. apply Hz.\n  - destruct (classic (x ∈ A)) as [HA|HA].\n    + apply BUnionI1. apply HA.\n    + apply BUnionI2. apply InterI... apply Hi. intros b Hb.\n      assert (Hu: A ∪ b ∈ {A ∪ X | X ∊ ℬ}). {\n        apply ReplI. apply Hb.\n      }\n      apply InterE in H as [_ H]...\n      apply H in Hu. apply BUnionE in Hu as [].\n      * exfalso. apply HA. apply H0.\n      * apply H0.\nQed.\n\n(* 二元交任意并的分配律 *)\nLemma binter_union_distr : ∀ A ℬ,\n  A ∩ ⋃ℬ = ⋃{A ∩ X | X ∊ ℬ}.\nProof.\n  intros. ext.\n  - apply BInterE in H as [HA Hu].\n    apply UnionAx in Hu as [b [Hb1 Hb2]].\n    eapply FUnionI.\n    + apply Hb1.\n    + apply BInterI; assumption.\n  - apply FUnionE in H as [y [H1 H2]].\n    apply BInterE in H2 as [H2 H3].\n    apply BInterI. apply H2.\n    eapply UnionI. apply H1. apply H3.\nQed.\n\n(* 补并德摩根定律 *)\nLemma comp_union_demorgen : ∀ 𝒜 C,\n  ⦿ 𝒜 → C - ⋃𝒜 = ⋂{C - X | X ∊ 𝒜}.\nProof.\n  intros * [a Ha]. ext.\n  - apply CompE in H as [HC HU]. apply InterI.\n    + exists (C - a). apply ReplI. apply Ha.\n    + intros y Hy. apply ReplAx in Hy as [b [Hb Hc]].\n      rewrite <- Hc. apply CompI. apply HC. intros H.\n      apply HU. eapply UnionI. apply Hb. apply H.\n  - apply InterE in H as [_ H]. apply CompI.\n    + assert (C - a ∈ {C - X | X ∊ 𝒜}). {\n        apply ReplI. apply Ha.\n      }\n      apply H in H0. apply CompE in H0 as [HC _]. apply HC.\n    + intros HU. apply UnionAx in HU as [b [Hb1 Hb2]].\n      assert (C - b ∈ {C - X | X ∊ 𝒜}). {\n        apply ReplI. apply Hb1.\n      }\n      apply H in H0. apply CompE in H0 as [_ Hb3]. auto.\nQed.\n\n(* 经典引理：并非所有都否定，则存在肯定 *)\nLemma quantified_imply_to_and : ∀ (A : Type) (P Q : A → Prop),\n  ¬ (∀ a, P a → Q a) → ∃ a, P a ∧ ¬ Q a.\nProof.\n  intros.\n  apply not_all_ex_not in H as [a H].\n  apply imply_to_and in H. \n  exists a. apply H.\nQed.\n\n(* x不在𝒜的交集里，则存在𝒜的成员A，x不是A的成员 *)\nLemma not_in_inter_intro : ∀ 𝒜 x, ⦿ 𝒜 → x ∉ ⋂ 𝒜 → ∃A ∈ 𝒜, x ∉ A.\nProof.\n  intros * Hi Hx. apply quantified_imply_to_and.\n  intros H. apply Hx. apply InterI.\n  apply Hi. intros y Hy. apply H. apply Hy.\nQed.\n\n(* 补交德摩根定律 *)\nLemma comp_inter_demorgen : ∀ 𝒜 C,\n  ⦿ 𝒜 → C - ⋂𝒜 = ⋃{C - X | X ∊ 𝒜}.\nProof.\n  intros * Hi. ext.\n  - apply CompE in H as [HC HU].\n    apply (not_in_inter_intro _ _ Hi) in HU as [a [Ha1 Ha2]].\n    eapply FUnionI. apply Ha1.\n    apply CompI. apply HC. apply Ha2.\n  - apply FUnionE in H as [y [Hy1 Hy2]].\n    apply CompE in Hy2 as [HC Hy2].\n    apply CompI. apply HC. intros HU.\n    apply InterE in HU as [_ H].\n    apply Hy2. apply H. apply Hy1.\nQed.\n\n(* 替代二元并分配律 *)\nLemma repl_bunion_distr : ∀ F A B,\n  {F x | x ∊ A ∪ B} = {F x | x ∊ A} ∪ {F x | x ∊ B}.\nProof with auto.\n  intros. ext y H.\n  - apply ReplAx in H as [x [Hx HFx]].\n    apply BUnionE in Hx as [].\n    + apply BUnionI1. apply ReplAx. exists x...\n    + apply BUnionI2. apply ReplAx. exists x...\n  - apply BUnionE in H as [];\n    apply ReplAx in H as [x [Hx HFx]];\n    apply ReplAx; exists x; split...\n    apply BUnionI1... apply BUnionI2...\nQed.\n\n(* 任意并二元并分配律 *)\nLemma union_bunion_distr : ∀ A B, ⋃ (A ∪ B) = ⋃ A ∪ ⋃ B.\nProof with auto.\n  intros. ext y H.\n  - apply UnionAx in H as [x [Hx HFx]].\n    apply BUnionE in Hx as [].\n    + apply BUnionI1. apply UnionAx. exists x...\n    + apply BUnionI2. apply UnionAx. exists x...\n  - apply BUnionE in H as [];\n    apply UnionAx in H as [x [Hx HFx]];\n    apply UnionAx; exists x; split...\n    apply BUnionI1... apply BUnionI2...\nQed.\n", "meta": {"author": "choukh", "repo": "Set-Theory", "sha": "5677d0d9cc3814adfb9bc1286a826f9d620fcc2e", "save_path": "github-repos/coq/choukh-Set-Theory", "path": "github-repos/coq/choukh-Set-Theory/Set-Theory-5677d0d9cc3814adfb9bc1286a826f9d620fcc2e/Elements/EST2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.656016184461515}}
{"text": "Require Import Reals Rpower Ranalysis Fourier.\n\nCheck MVT_cor1.\n(* MVT_cor1 requires us to show that f is derivable, but we also need to\n   reason about the derivative at the value c provided by the theorem.\n\n   In order to do this eaisily, we want to use the lemmas\n   derive_pt_plus, derive_pt_minus, etc..., but these lemmas\n   require our proof of derivability to be constructed in a \n   particular way.  \n*)\n\n(* Two ways to build the proof of derivable so we can use the\n   afformentioned lemmas:\n    - Interactively => aux_const.\n    - Manually => aux_const'.\n*)\nLemma aux_const : derivable (fun x => (exp x - (1 +x))%R).\nProof.\n  unfold derivable. intros x.\n  apply derivable_pt_minus.\n  apply derivable_pt_exp.\n  apply derivable_pt_plus.\n  apply derivable_pt_const.\n  apply derivable_pt_id.\nDefined. (* Later we'll need to reason about how this proof\n            was built, so we end the proof with defined rather\n            than Qed. *)\n\nDefinition aux_const' x : derivable_pt (fun x => (exp x - (1 +x))%R) x :=\n  derivable_pt_minus exp (Rplus 1) x (derivable_pt_exp x)\n    (derivable_pt_plus (fun _ : R => 1%R) id x (derivable_pt_const 1 x)\n    (derivable_pt_id x)).\n\n(* Really these are the same things, and we can prove it... *)\nLemma aux_eq : aux_const = aux_const'.\nProof.\n  auto.\nQed.\n\n(* Proof: If y < 0, then the derivative of this function at y is negative *)\nLemma aux_neg y (H :(y < 0)%R) :\n  (derive (fun x => (exp x - (1 + x))%R) aux_const y < 0)%R.\nProof.\n  unfold derive, aux_const.\n  (* The rewritng here isn't as good as ssreflect's, so we need to\n     apply the decomposition manually *)\n  rewrite (derive_pt_minus (fun x => exp x) (fun x => (1 + x)%R)).\n  rewrite derive_pt_exp.\n  rewrite (derive_pt_plus (fun _ : R => 1) id).\n  rewrite (derive_pt_const 1).\n  rewrite (derive_pt_id).\n  apply Rlt_minus.\n  rewrite <- exp_0.\n  rewrite Rplus_0_l.\n  apply exp_increasing; exact H.\nQed.\n\n(* Proof: If 0 <= y, then the derivative of this function at y is positive *)\nLemma aux_pos y (H :(0 <= y)%R) :\n  (derive (fun x => (exp x - (1 + x))%R) aux_const y >= 0)%R.\nProof.\n  unfold derive, aux_const.\n  rewrite (derive_pt_minus (fun x => exp x) (fun x => (1 + x)%R)).\n  rewrite derive_pt_exp.\n  rewrite (derive_pt_plus (fun _ : R => 1) id).\n  rewrite (derive_pt_const 1).\n  rewrite (derive_pt_id).\n  rewrite Rplus_0_l.\n  apply Rge_minus.\n  rewrite <- exp_0.\n  destruct H.\n  left. apply exp_increasing. auto.\n  subst. fourier.\nQed.\n\n(* We use the MVT + the above results to show that *)\nLemma ln_Taylor_upper' x : ((1 + x) <= exp x)%R.\nProof.\n  apply Rge_le.\n  apply Rminus_ge.\n  set (f := fun x => (exp x - (1 + x))%R).\n  assert (f x = exp x - (1 + x)%R) as H0.\n    unfold f. auto.\n  rewrite <- H0; clear H0.\n  assert (f 0 = 0)%R as H0.\n    unfold f. rewrite exp_0, Rplus_0_r.\n    apply Rminus_diag_eq; auto.\n  rewrite <- H0.\n  case_eq (Rtotal_order x 0); intros H.\n  {\n    left. clear H1.\n    apply (MVT_cor1 f x 0 aux_const) in H.\n    destruct H as [c [H1 [H2 H3]]].\n    rewrite H0, Rminus_0_l, Rminus_0_l in H1.\n    rewrite H0.\n    assert (x < 0)%R as H4. apply (Rlt_trans x c 0); auto.\n    apply Ropp_eq_compat in H1.\n    rewrite Ropp_involutive in H1.\n    rewrite H1.\n    apply Rlt_gt.\n    rewrite Ropp_mult_distr_l.\n    apply Rmult_lt_0_compat.\n    apply Ropp_0_gt_lt_contravar.\n    apply Rlt_gt.\n    apply aux_neg; auto.\n    fourier.\n  }\n  {\n    destruct H as [H | H].\n    { intros _; subst; right; auto. }\n    intros _.\n    apply (MVT_cor1 f 0 x aux_const) in H.\n    destruct H as [c [H1 [H2 H3]]].\n    rewrite H0, Rminus_0_r, Rminus_0_r in H1.\n    rewrite H0.\n    assert (0 <= x)%R as H4. fourier.\n    rewrite H1.\n    apply Rle_ge.\n    rewrite <- (Rmult_0_l x).\n    apply Rmult_le_compat; try fourier.\n    apply Rge_le.\n    apply aux_pos.\n    left; auto.\n  }\nQed.\n\nLemma ln_Taylor_upper x : (x < 1)%R ->  (ln (1 - x) <= -x)%R.\nProof.\n  intros h.\n  unfold ln.\n  case_eq (Rlt_dec 0 (1-x)); intros h1 h2;\n  last by apply False_rec; apply h1; fourier.\n  unfold Rln; simpl.\n  destruct (ln_exists (1 - x) h1) as [x0 e0].\n  apply Rplus_le_reg_l with (r := 1%R).\n  unfold Rminus in e0.\n  rewrite e0.\n  apply ln_Taylor_upper'.\nQed.\n", "meta": {"author": "gstew5", "repo": "coq-tutorial-summer2016", "sha": "a68f81725388326f953a94c9143176075a90fe9e", "save_path": "github-repos/coq/gstew5-coq-tutorial-summer2016", "path": "github-repos/coq/gstew5-coq-tutorial-summer2016/coq-tutorial-summer2016-a68f81725388326f953a94c9143176075a90fe9e/calc_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619306896955, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.655989813346963}}
{"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\n(* Finite sets library.  \n * Authors: Pierre Letouzey and Jean-Christophe Filliâtre \n * Institution: LRI, CNRS UMR 8623 - Université Paris Sud\n *              91405 Orsay, France *)\n\n(* $Id$ *)\n\nRequire Import Bool.\nRequire Import NArith Ndigits Ndec Nnat. \nRequire Import Allmaps.\nRequire Import OrderedType.\nRequire Import OrderedTypeEx.\nRequire Import FMapInterface FMapList.\n\n\nSet Implicit Arguments.\n\n(** * An implementation of [FMapInterface.S] based on [IntMap] *)\n\n(** Keys are of type [N]. The main functions are directly taken from \n  [IntMap]. Since they have no exact counterpart in [IntMap], functions \n  [fold], [map2] and [equal] are for now obtained by translation \n  to sorted lists. *)\n\n(** [N] is an ordered type, using not the usual order on numbers, \n   but lexicographic ordering on bits (lower bit considered first). *) \n\nModule NUsualOrderedType <: UsualOrderedType.\n  Definition t:=N.\n  Definition eq:=@eq N.\n  Definition eq_refl := @refl_equal t.\n  Definition eq_sym := @sym_eq t.\n  Definition eq_trans := @trans_eq t.\n\n  Definition lt p q:= Nless p q = true.\n \n  Definition lt_trans := Nless_trans.\n\n  Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y.\n  Proof.\n  intros; intro.\n  rewrite H0 in H.\n  red in H.\n  rewrite Nless_not_refl in H; discriminate.\n  Qed.\n\n  Definition compare : forall x y : t, Compare lt eq x y.\n  Proof.\n  intros x y.\n  destruct (Nless_total x y) as [[H|H]|H].\n  apply LT; unfold lt; auto.\n  apply GT; unfold lt; auto.\n  apply EQ; auto.\n  Qed.\n\n  Definition eq_dec := N_as_OT.eq_dec.\n\nEnd NUsualOrderedType.\n \n\n(** The module of maps over [N] keys based on [IntMap] *)\n\nModule MapIntMap <: S with Module E:=NUsualOrderedType.\n\n  Module E:=NUsualOrderedType.\n  Module ME:=OrderedTypeFacts(E).\n  Module PE:=KeyOrderedType(E).\n\n  Definition key := N.\n\n  Definition t := Map.\n\n  Section A.\n  Variable A:Type.\n\n  Definition empty : t A := M0 A.\n \n  Definition is_empty (m : t A) : bool := \n    MapEmptyp _ (MapCanonicalize _ m).\n\n  Definition find (x:key)(m: t A) : option A := MapGet _ m x.\n\n  Definition mem (x:key)(m: t A) : bool := \n    match find x m with \n     | Some _ => true\n     | None => false\n    end.\n\n  Definition add (x:key)(v:A)(m:t A) : t A := MapPut _ m x v.\n  \n  Definition remove (x:key)(m:t A) : t A := MapRemove _ m x.\n\n  Definition elements (m : t A) : list (N*A) := alist_of_Map _ m.\n\n  Definition cardinal (m : t A) : nat := MapCard _ m.\n\n  Definition MapsTo (x:key)(v:A)(m:t A) := find x m = Some v.\n\n  Definition In (x:key)(m:t A) := exists e:A, MapsTo x e m.\n\n  Definition Empty m := forall (a : key)(e:A) , ~ MapsTo a e m.\n\n  Definition eq_key (p p':key*A) := E.eq (fst p) (fst p').\n      \n  Definition eq_key_elt (p p':key*A) := \n          E.eq (fst p) (fst p') /\\ (snd p) = (snd p').\n\n  Definition lt_key (p p':key*A) := E.lt (fst p) (fst p').\n\n  Lemma Empty_alt : forall m, Empty m <-> forall a, find a m = None.\n  Proof.\n  unfold Empty, MapsTo.\n  intuition.\n  generalize (H a).\n  destruct (find a m); intuition.\n  elim (H0 a0); auto.\n  rewrite H in H0; discriminate.\n  Qed.\n\n  Section Spec. \n  Variable  m m' m'' : t A.\n  Variable x y z : key.\n  Variable e e' : A.\n\n  Lemma MapsTo_1 : E.eq x y -> MapsTo x e m -> MapsTo y e m.\n  Proof. intros; rewrite <- H; auto. Qed.\n\n  Lemma find_1 : MapsTo x e m -> find x m = Some e.\n  Proof. unfold MapsTo; auto. Qed.\n\n  Lemma find_2 : find x m = Some e -> MapsTo x e m.\n  Proof. red; auto. Qed.\n\n  Lemma empty_1 : Empty empty.\n  Proof.\n  rewrite Empty_alt; intros; unfold empty, find; simpl; auto.\n  Qed.\n\n  Lemma is_empty_1 : Empty m -> is_empty m = true. \n  Proof.\n  unfold Empty, is_empty, find; intros.\n  cut (MapCanonicalize _ m = M0 _).\n  intros; rewrite H0; simpl; auto.\n  apply mapcanon_unique.\n  apply mapcanon_exists_2.\n  constructor.\n  red; red; simpl; intros.\n  rewrite <- (mapcanon_exists_1 _ m).\n  unfold MapsTo, find in *.\n  generalize (H a).\n  destruct (MapGet _ m a); auto.\n  intros; generalize (H0 a0); destruct 1; auto.\n  Qed.  \n\n  Lemma is_empty_2 : is_empty m = true -> Empty m.\n  Proof.\n  unfold Empty, is_empty, MapsTo, find; intros.\n  generalize (MapEmptyp_complete _ _ H); clear H; intros.\n  rewrite (mapcanon_exists_1 _ m).\n  rewrite H; simpl; auto.\n  discriminate.\n  Qed.\n\n  Lemma mem_1 : In x m -> mem x m = true.\n  Proof.\n  unfold In, MapsTo, mem.\n  destruct (find x m); auto.\n  destruct 1; discriminate.\n  Qed.\n\n  Lemma mem_2 : forall m x, mem x m = true -> In x m. \n  Proof.\n  unfold In, MapsTo, mem.\n  intros.\n  destruct (find x0 m0); auto; try discriminate.\n  exists a; auto.\n  Qed.\n\n  Lemma add_1 : E.eq x y -> MapsTo y e (add x e m).\n  Proof.\n  unfold MapsTo, find, add.\n  intro H; rewrite H; clear H.\n  rewrite MapPut_semantics.\n  rewrite Neqb_correct; auto.\n  Qed.\n\n  Lemma add_2 : ~ E.eq x y -> MapsTo y e m -> MapsTo y e (add x e' m).\n  Proof.\n  unfold MapsTo, find, add.\n  intros.\n  rewrite MapPut_semantics.\n  rewrite H0.\n  generalize (Neqb_complete x y).\n  destruct (Neqb x y); auto.\n  intros.\n  elim H; auto.\n  apply H1; auto.\n  Qed.\n\n  Lemma add_3 : ~ E.eq x y -> MapsTo y e (add x e' m) -> MapsTo y e m.\n  Proof.\n  unfold MapsTo, find, add.\n  rewrite MapPut_semantics.\n  intro H.\n  generalize (Neqb_complete x y).\n  destruct (Neqb x y); auto.\n  intros; elim H; auto.\n  apply H0; auto.\n  Qed.\n\n  Lemma remove_1 : E.eq x y -> ~ In y (remove x m).\n  Proof. \n  unfold In, MapsTo, find, remove.\n  rewrite MapRemove_semantics.\n  intro H.\n  rewrite H; rewrite Neqb_correct.\n  red; destruct 1; discriminate.\n  Qed.\n\n  Lemma remove_2 : ~ E.eq x y -> MapsTo y e m -> MapsTo y e (remove x m).\n  Proof.\n  unfold MapsTo, find, remove.\n  rewrite MapRemove_semantics.\n  intros.\n  rewrite H0.\n  generalize (Neqb_complete x y).\n  destruct (Neqb x y); auto.\n  intros; elim H; apply H1; auto.\n  Qed.\n\n  Lemma remove_3 : MapsTo y e (remove x m) -> MapsTo y e m.\n  Proof. \n  unfold MapsTo, find, remove.\n  rewrite MapRemove_semantics.\n  destruct (Neqb x y); intros; auto.\n  discriminate.\n  Qed.\n\n  Lemma alist_sorted_sort : forall l, alist_sorted A l=true -> sort lt_key l.\n  Proof.\n  induction l.\n  auto.\n  simpl.\n  destruct a.\n  destruct l.\n  auto.\n  destruct p.\n  intros; destruct (andb_prop _ _ H); auto.\n  Qed.\n\n  Lemma elements_3 : sort lt_key (elements m). \n  Proof.\n  unfold elements.\n  apply alist_sorted_sort.\n  apply alist_of_Map_sorts.\n  Qed.\n\n  Lemma elements_3w : NoDupA eq_key (elements m). \n  Proof.\n  change eq_key with (@PE.eqk A).\n  apply PE.Sort_NoDupA; apply elements_3; auto.\n  Qed. \n\n  Lemma elements_1 : \n     MapsTo x e m -> InA eq_key_elt (x,e) (elements m).\n  Proof.\n  unfold MapsTo, find, elements.\n  rewrite InA_alt.\n  intro H.\n  exists (x,e).\n  split.\n  red; simpl; unfold E.eq; auto.\n  rewrite alist_of_Map_semantics in H.\n  generalize H.\n  set (l:=alist_of_Map A m); clearbody l; clear.\n  induction l; simpl; auto.\n  intro; discriminate.\n  destruct a; simpl; auto.\n  generalize (Neqb_complete a x).\n  destruct (Neqb a x); auto.\n  left.\n  injection H0; auto.\n  intros; f_equal; auto.\n  Qed.\n\n  Lemma elements_2 : \n     InA eq_key_elt (x,e) (elements m) -> MapsTo x e m.\n  Proof.\n  generalize elements_3.\n  unfold MapsTo, find, elements.\n  rewrite InA_alt.\n  intros H ((e0,a),(H0,H1)).\n  red in H0; simpl in H0; unfold E.eq in H0; destruct H0; subst.\n  rewrite alist_of_Map_semantics.\n  generalize H H1; clear H H1.\n  set (l:=alist_of_Map A m); clearbody l; clear.\n  induction l; simpl; auto.\n  intro; contradiction.\n  intros.\n  destruct a0; simpl.\n  inversion H1. \n  injection H0; intros; subst.\n  rewrite Neqb_correct; auto.\n  assert (InA eq_key (e0,a) l).\n  rewrite InA_alt.\n  exists (e0,a); split; auto.\n  red; simpl; auto; red; auto.\n  generalize (PE.Sort_In_cons_1 H H2).\n  unfold PE.ltk; simpl.\n  intros H3; generalize (E.lt_not_eq H3).\n  generalize (Neqb_complete a0 e0).\n  destruct (Neqb a0 e0); auto.\n  destruct 2.\n  apply H4; auto.\n  inversion H; auto.\n  Qed.\n\n  Lemma cardinal_1 : forall m, cardinal m = length (elements m).\n  Proof. exact (@MapCard_as_length _). Qed.\n\n  Definition Equal m m' := forall y, find y m = find y m'.\n  Definition Equiv (eq_elt:A->A->Prop) m m' := \n    (forall k, In k m <-> In k m') /\\ \n    (forall k e e', MapsTo k e m -> MapsTo k e' m' -> eq_elt e e').  \n  Definition Equivb (cmp: A->A->bool) := Equiv (Cmp cmp).\n\n  (** unfortunately, the [MapFold] of [IntMap] isn't compatible with \n   the FMap interface. We use a naive version for now : *)\n\n  Definition fold (B:Type)(f:key -> A -> B -> B)(m:t A)(i:B) : B := \n    fold_left (fun a p => f (fst p) (snd p) a) (elements m) i.\n\n  Lemma fold_1 :\n\tforall (B:Type) (i : B) (f : key -> A -> B -> B),\n        fold f m i = fold_left (fun a p => f (fst p) (snd p) a) (elements m) i.\n  Proof. auto. Qed.\n\n  End Spec.\n\n  Variable B : Type.\n\n  Fixpoint mapi_aux (pf:N->N)(f : N -> A -> B)(m:t A) { struct m }: t B := \n    match m with \n      | M0 => M0 _ \n      | M1 x y => M1 _ x (f (pf x) y)\n      | M2 m0 m1 =>  M2 _ (mapi_aux (fun n => pf (Ndouble n)) f m0)\n                                         (mapi_aux (fun n => pf (Ndouble_plus_one n)) f m1)\n    end.\n    \n  Definition mapi := mapi_aux (fun n => n).\n\n  Definition map (f:A->B) := mapi (fun _ => f).\n \n  End A.\n\n  Lemma mapi_aux_1 : forall (elt elt':Type)(m: t elt)(pf:N->N)(x:key)(e:elt)\n        (f:key->elt->elt'), MapsTo x e m -> \n        exists y, E.eq y x /\\ MapsTo x (f (pf y) e) (mapi_aux pf f m).\n  Proof.\n  unfold MapsTo; induction m; simpl; auto.\n  inversion 1.\n\n  intros.\n  exists x; split; [red; auto|].\n  generalize (Neqb_complete a x).\n  destruct (Neqb a x); try discriminate.\n  injection H; intros; subst; auto.\n  rewrite H1; auto.\n\n  intros.\n  exists x; split; [red;auto|].\n  destruct x; simpl in *.\n  destruct (IHm1 (fun n : N => pf (Ndouble n)) _ _ f H) as (y,(Hy,Hy')).\n  rewrite Hy in Hy'; simpl in Hy'; auto.\n  destruct p; simpl in *.\n  destruct (IHm2 (fun n : N => pf (Ndouble_plus_one n)) _ _ f H) as (y,(Hy,Hy')).\n  rewrite Hy in Hy'; simpl in Hy'; auto.\n  destruct (IHm1 (fun n : N => pf (Ndouble n)) _ _ f H) as (y,(Hy,Hy')).\n  rewrite Hy in Hy'; simpl in Hy'; auto.\n  destruct (IHm2 (fun n : N => pf (Ndouble_plus_one n)) _ _ f H) as (y,(Hy,Hy')).\n  rewrite Hy in Hy'; simpl in Hy'; auto.\n  Qed.\n\n  Lemma mapi_1 : forall (elt elt':Type)(m: t elt)(x:key)(e:elt)\n        (f:key->elt->elt'), MapsTo x e m -> \n        exists y, E.eq y x /\\ MapsTo x (f y e) (mapi f m).\n  Proof.\n  intros elt elt' m; exact (mapi_aux_1 (fun n => n)).\n  Qed.\n\n  Lemma mapi_aux_2 : forall (elt elt':Type)(m: t elt)(pf:N->N)(x:key)\n        (f:key->elt->elt'), In x (mapi_aux pf f m) -> In x m.\n  Proof.\n  unfold In, MapsTo.\n  induction m; simpl in *.\n  intros pf x f (e,He); inversion He.\n  intros pf x f (e,He).\n  exists a0.\n  destruct (Neqb a x); try discriminate; auto.\n  intros pf x f (e,He).\n  destruct x; [|destruct p]; eauto.\n  Qed.\n\n  Lemma mapi_2 : forall (elt elt':Type)(m: t elt)(x:key)\n        (f:key->elt->elt'), In x (mapi f m) -> In x m.\n  Proof.\n  intros elt elt' m. exact (@mapi_aux_2 _ elt' m (fun n => n)).\n  Qed.\n\n  Lemma map_1 : forall (elt elt':Type)(m: t elt)(x:key)(e:elt)(f:elt->elt'),\n        MapsTo x e m -> MapsTo x (f e) (map f m).\n  Proof.\n  unfold map; intros.\n  destruct (@mapi_1 _ _ m x e (fun _ => f)) as (e',(_,H0)); auto.\n  Qed.\n\n  Lemma map_2 : forall (elt elt':Type)(m: t elt)(x:key)(f:elt->elt'), \n        In x (map f m) -> In x m.\n  Proof.\n  unfold map; intros.\n  eapply mapi_2; eauto.\n  Qed.\n\n  Module L := FMapList.Raw E.\n\n  (** Not exactly pretty nor perfect, but should suffice as a first naive implem. \n    Anyway, map2 isn't in Ocaml...\n  *)\n\n  Definition anti_elements (A:Type)(l:list (key*A)) := L.fold (@add _) l (empty _).\n\n  Definition map2 (A B C:Type)(f:option A->option B -> option C)(m:t A)(m':t B) : t C := \n    anti_elements (L.map2 f (elements m) (elements m')).\n\n  Lemma add_spec : forall (A:Type)(m:t A) x y e, \n    find x (add y e m) = if E.eq_dec x y then Some e else find x m.\n  Proof.\n  intros.\n  destruct (E.eq_dec x y).\n  apply find_1.\n  eapply MapsTo_1 with y; eauto.\n  red; auto.\n  apply add_1; auto.\n  red; auto.\n  case_eq (find x m); intros.\n  apply find_1.\n  apply add_2; unfold E.eq in *; auto.\n  case_eq (find x (add y e m)); auto; intros.\n  rewrite <- H; symmetry.\n  apply find_1; auto.\n  apply (@add_3 _ m y x a e); unfold E.eq in *; auto.\n  Qed.\n  \n  Lemma anti_elements_mapsto_aux : forall (A:Type)(l:list (key*A)) m k e,\n    NoDupA (eq_key (A:=A)) l -> \n    (forall x, L.PX.In x l -> In x m -> False) -> \n    (MapsTo k e (L.fold (@add _) l m) <-> L.PX.MapsTo k e l \\/ MapsTo k e m).\n  Proof.\n  induction l. \n  simpl; auto.\n  intuition.\n  inversion H2.\n  simpl; destruct a; intros.\n  inversion_clear H.\n  rewrite IHl; clear IHl; auto.\n  intuition.\n  red in H3.\n  rewrite add_spec in H3; auto.\n  destruct (E.eq_dec k0 k).\n  inversion_clear H3; subst; auto.\n  right; apply find_2; auto.\n  inversion_clear H3; auto.\n  compute in H; destruct H.\n  subst; right; apply add_1; auto.\n  red; auto.\n  destruct (E.eq_dec k0 k) as [H|H].\n  subst.\n  destruct (H0 k); eauto.\n  red; eauto.\n  right; apply add_2; unfold E.eq in *; auto.\n  (* proof of precondition of IHl *)\n  intros.\n  assert (~E.eq x k).\n   contradict H1.\n   destruct H.\n   apply InA_eqA with (x,x0); eauto with *.\n  apply (H0 x).\n  destruct H; exists x0; auto.\n  revert H3.\n  unfold In.\n  intros (e',He').\n  exists e'; apply (@add_3 _ m k x e' a); unfold E.eq; auto.\n  Qed.\n  \n  Lemma anti_elements_mapsto : forall (A:Type) l k e, NoDupA (eq_key (A:=A)) l ->\n    (MapsTo k e (anti_elements l) <-> L.PX.MapsTo k e l).\n  Proof. \n  intros. \n  unfold anti_elements.\n  rewrite anti_elements_mapsto_aux; auto; unfold empty; auto.\n  intuition.\n  inversion H1.\n  inversion 2.\n  inversion H2.\n  Qed.\n  \n  Lemma find_anti_elements : forall (A:Type)(l: list (key*A)) x, sort (@lt_key _) l -> \n    find x (anti_elements l) = L.find x l.\n  Proof.\n  intros.\n  case_eq (L.find x l); intros.\n  apply find_1.\n  rewrite anti_elements_mapsto; auto using L.PX.Sort_NoDupA, L.find_2.\n  case_eq (find x (anti_elements l)); auto; intros.\n  rewrite <- H0; symmetry.\n  apply L.find_1; auto.\n  rewrite <- anti_elements_mapsto; auto using L.PX.Sort_NoDupA, find_2.\n  Qed.\n\n  Lemma find_elements : forall (A:Type)(m: t A) x,  \n    L.find x (elements m) = find x m.\n  Proof. \n  intros.\n  case_eq (find x m); intros.\n  apply L.find_1.\n  apply elements_3; auto.\n  red; apply elements_1.\n  apply find_2; auto.\n  case_eq (L.find x (elements m)); auto; intros.\n  rewrite <- H; symmetry.\n  apply find_1; auto.\n  apply elements_2.\n  apply L.find_2; auto.\n  Qed.\n  \n  Lemma elements_in : forall (A:Type)(s:t A) x, L.PX.In x (elements s) <-> In x s.\n  Proof.\n   intros.\n   unfold L.PX.In, In.\n   firstorder.\n   exists x0.\n   red; rewrite <- find_elements; auto.\n   apply L.find_1; auto.\n   apply elements_3.\n   exists x0.\n   apply L.find_2.\n   rewrite find_elements; auto.\n  Qed.\n  \n  Lemma map2_1 : forall (A B C:Type)(m: t A)(m': t B)(x:key)\n    (f:option A->option B ->option C), \n    In x m \\/ In x m' -> find x (map2 f m m') = f (find x m) (find x m').       \n  Proof. \n  unfold map2; intros.\n  rewrite find_anti_elements; auto.\n  rewrite <- find_elements; auto.\n  rewrite <- find_elements; auto.\n  apply L.map2_1; auto.\n  apply elements_3; auto.\n  apply elements_3; auto.\n  do 2 rewrite elements_in; auto.\n  apply L.map2_sorted; auto.\n  apply elements_3; auto.\n  apply elements_3; auto.\n  Qed.\n  \n  Lemma map2_2 : forall (A B C:Type)(m: t A)(m': t B)(x:key)\n      (f:option A->option B ->option C), \n    In x (map2 f m m') -> In x m \\/ In x m'.\n  Proof.\n  unfold map2; intros.\n  do 2 rewrite <- elements_in.\n  apply L.map2_2 with (f:=f); auto.\n  apply elements_3; auto.\n  apply elements_3; auto.\n  destruct H.\n  exists x0.\n  rewrite <- anti_elements_mapsto; auto.\n  apply L.PX.Sort_NoDupA; auto.\n  apply L.map2_sorted; auto.\n  apply elements_3; auto.\n  apply elements_3; auto.\n  Qed.\n\n  (** same trick for [equal] *)\n\n  Definition equal (A:Type)(cmp:A -> A -> bool)(m m' : t A) : bool := \n    L.equal cmp (elements m) (elements m').\n  \n  Lemma equal_1 : \n    forall (A:Type)(m: t A)(m': t A)(cmp: A -> A -> bool), \n    Equivb cmp m m' -> equal cmp m m' = true. \n  Proof.\n  unfold equal, Equivb, Equiv, Cmp.\n  intros.\n  apply L.equal_1.\n  apply elements_3.\n  apply elements_3.\n  unfold L.Equivb.\n  destruct H.\n  split; intros.\n  do 2 rewrite elements_in; auto.\n  apply (H0 k); \n    red; rewrite <- find_elements; apply L.find_1; auto; \n    apply elements_3.\n  Qed.  \n\n  Lemma equal_2 : \n    forall (A:Type)(m: t A)(m': t A)(cmp: A -> A -> bool), \n    equal cmp m m' = true -> Equivb cmp m m'.\n  Proof.\n  unfold equal, Equivb, Equiv, Cmp.\n  intros.\n  destruct (L.equal_2 (elements_3 m) (elements_3 m') H); clear H.\n  split.\n  intros; do 2 rewrite <- elements_in; auto.\n  intros; apply (H1 k); \n    apply L.find_2; rewrite find_elements;auto.\n  Qed.\n\nEnd MapIntMap.\n\n", "meta": {"author": "coq-contribs", "repo": "int-map", "sha": "42342f3b4152419faf17c7ac9afd90e337d68637", "save_path": "github-repos/coq/coq-contribs-int-map", "path": "github-repos/coq/coq-contribs-int-map/int-map-42342f3b4152419faf17c7ac9afd90e337d68637/FMapIntMap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6559898070465328}}
{"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(** Properties of [abs] and [sgn] *)\n\nRequire Import ZMulOrder.\n\n(** Since we already have [max], we could have defined [abs]. *)\n\nModule GenericAbs (Import Z : ZAxiomsMiniSig')\n                  (Import ZP : ZMulOrderProp Z) <: HasAbs Z.\n Definition abs n := max n (-n).\n Lemma abs_eq : forall n, 0<=n -> abs n == n.\n Proof.\n  intros. unfold abs. apply max_l.\n  apply le_trans with 0; auto.\n  rewrite opp_nonpos_nonneg; auto.\n Qed.\n Lemma abs_neq : forall n, n<=0 -> abs n == -n.\n Proof.\n  intros. unfold abs. apply max_r.\n  apply le_trans with 0; auto.\n  rewrite opp_nonneg_nonpos; auto.\n Qed.\nEnd GenericAbs.\n\n(** We can deduce a [sgn] function from a [compare] function *)\n\nModule Type ZDecAxiomsSig := ZAxiomsMiniSig <+ HasCompare.\nModule Type ZDecAxiomsSig' := ZAxiomsMiniSig' <+ HasCompare.\n\nModule Type GenericSgn (Import Z : ZDecAxiomsSig')\n                       (Import ZP : ZMulOrderProp Z) <: HasSgn Z.\n Definition sgn n :=\n  match compare 0 n with Eq => 0 | Lt => 1 | Gt => -1 end.\n Lemma sgn_null : forall n, n==0 -> sgn n == 0.\n Proof. unfold sgn; intros. destruct (compare_spec 0 n); order. Qed.\n Lemma sgn_pos : forall n, 0<n -> sgn n == 1.\n Proof. unfold sgn; intros. destruct (compare_spec 0 n); order. Qed.\n Lemma sgn_neg : forall n, n<0 -> sgn n == -1.\n Proof. unfold sgn; intros. destruct (compare_spec 0 n); order. Qed.\nEnd GenericSgn.\n\n\n(** Derived properties of [abs] and [sgn] *)\n\nModule Type ZSgnAbsProp (Import Z : ZAxiomsSig')\n                        (Import ZP : ZMulOrderProp Z).\n\nLtac destruct_max n :=\n destruct (le_ge_cases 0 n);\n  [rewrite (abs_eq n) by auto | rewrite (abs_neq n) by auto].\n\nInstance abs_wd : Proper (eq==>eq) abs.\nProof.\n intros x y EQ. destruct_max x.\n rewrite abs_eq; trivial. now rewrite <- EQ.\n rewrite abs_neq; try order. now rewrite opp_inj_wd.\nQed.\n\nLemma abs_max : forall n, abs n == max n (-n).\nProof.\n intros n. destruct_max n.\n rewrite max_l; auto with relations.\n apply le_trans with 0; auto.\n rewrite opp_nonpos_nonneg; auto.\n rewrite max_r; auto with relations.\n apply le_trans with 0; auto.\n rewrite opp_nonneg_nonpos; auto.\nQed.\n\nLemma abs_neq' : forall n, 0<=-n -> abs n == -n.\nProof.\n intros. apply abs_neq. now rewrite <- opp_nonneg_nonpos.\nQed.\n\nLemma abs_nonneg : forall n, 0 <= abs n.\nProof.\n intros n. destruct_max n; auto.\n now rewrite opp_nonneg_nonpos.\nQed.\n\nLemma abs_eq_iff : forall n, abs n == n <-> 0<=n.\nProof.\n split; try apply abs_eq. intros EQ.\n rewrite <- EQ. apply abs_nonneg.\nQed.\n\nLemma abs_neq_iff : forall n, abs n == -n <-> n<=0.\nProof.\n split; try apply abs_neq. intros EQ.\n rewrite <- opp_nonneg_nonpos, <- EQ. apply abs_nonneg.\nQed.\n\nLemma abs_opp : forall n, abs (-n) == abs n.\nProof.\n intros. destruct_max n.\n rewrite (abs_neq (-n)), opp_involutive. reflexivity.\n now rewrite opp_nonpos_nonneg.\n rewrite (abs_eq (-n)). reflexivity.\n now rewrite opp_nonneg_nonpos.\nQed.\n\nLemma abs_0 : abs 0 == 0.\nProof.\n apply abs_eq. apply le_refl.\nQed.\n\nLemma abs_0_iff : forall n, abs n == 0 <-> n==0.\nProof.\n split. destruct_max n; auto.\n now rewrite eq_opp_l, opp_0.\n intros EQ; rewrite EQ. rewrite abs_eq; auto using eq_refl, le_refl.\nQed.\n\nLemma abs_pos : forall n, 0 < abs n <-> n~=0.\nProof.\n intros. rewrite <- abs_0_iff. split; [intros LT| intros NEQ].\n intro EQ. rewrite EQ in LT. now elim (lt_irrefl 0).\n assert (LE : 0 <= abs n) by apply abs_nonneg.\n rewrite lt_eq_cases in LE; destruct LE; auto.\n elim NEQ; auto with relations.\nQed.\n\nLemma abs_eq_or_opp : forall n, abs n == n \\/ abs n == -n.\nProof.\n intros. destruct_max n; auto with relations.\nQed.\n\nLemma abs_or_opp_abs : forall n, n == abs n \\/ n == - abs n.\nProof.\n intros. destruct_max n; rewrite ? opp_involutive; auto with relations.\nQed.\n\nLemma abs_involutive : forall n, abs (abs n) == abs n.\nProof.\n intros. apply abs_eq. apply abs_nonneg.\nQed.\n\nLemma abs_spec : forall n,\n  (0 <= n /\\ abs n == n) \\/ (n < 0 /\\ abs n == -n).\nProof.\n intros. destruct (le_gt_cases 0 n).\n left; split; auto. now apply abs_eq.\n right; split; auto. apply abs_neq. now apply lt_le_incl.\nQed.\n\nLemma abs_case_strong :\n  forall (P:t->Prop) n, Proper (eq==>iff) P ->\n    (0<=n -> P n) -> (n<=0 -> P (-n)) -> P (abs n).\nProof.\n intros. destruct_max n; auto.\nQed.\n\nLemma abs_case : forall (P:t->Prop) n, Proper (eq==>iff) P ->\n P n -> P (-n) -> P (abs n).\nProof. intros. now apply abs_case_strong. Qed.\n\nLemma abs_eq_cases : forall n m, abs n == abs m -> n == m \\/ n == - m.\nProof.\n intros n m EQ. destruct (abs_or_opp_abs n) as [EQn|EQn].\n rewrite EQn, EQ. apply abs_eq_or_opp.\n rewrite EQn, EQ, opp_inj_wd, eq_opp_l, or_comm. apply abs_eq_or_opp.\nQed.\n\nLemma abs_lt : forall a b, abs a < b <-> -b < a < b.\nProof.\n intros a b.\n destruct (abs_spec a) as [[LE EQ]|[LT EQ]]; rewrite EQ; clear EQ.\n split; try split; try destruct 1; try order.\n apply lt_le_trans with 0; trivial. apply opp_neg_pos; order.\n rewrite opp_lt_mono, opp_involutive.\n split; try split; try destruct 1; try order.\n apply lt_le_trans with 0; trivial. apply opp_nonpos_nonneg; order.\nQed.\n\nLemma abs_le : forall a b, abs a <= b <-> -b <= a <= b.\nProof.\n intros a b.\n destruct (abs_spec a) as [[LE EQ]|[LT EQ]]; rewrite EQ; clear EQ.\n split; try split; try destruct 1; try order.\n apply le_trans with 0; trivial. apply opp_nonpos_nonneg; order.\n rewrite opp_le_mono, opp_involutive.\n split; try split; try destruct 1; try order.\n apply le_trans with 0. order. apply opp_nonpos_nonneg; order.\nQed.\n\n(** Triangular inequality *)\n\nLemma abs_triangle : forall n m, abs (n + m) <= abs n + abs m.\nProof.\n intros. destruct_max n; destruct_max m.\n rewrite abs_eq. apply le_refl. now apply add_nonneg_nonneg.\n destruct_max (n+m); try rewrite opp_add_distr;\n  apply add_le_mono_l || apply add_le_mono_r.\n apply le_trans with 0; auto. now rewrite opp_nonneg_nonpos.\n apply le_trans with 0; auto. now rewrite opp_nonpos_nonneg.\n destruct_max (n+m); try rewrite opp_add_distr;\n  apply add_le_mono_l || apply add_le_mono_r.\n apply le_trans with 0; auto. now rewrite opp_nonneg_nonpos.\n apply le_trans with 0; auto. now rewrite opp_nonpos_nonneg.\n rewrite abs_neq, opp_add_distr. apply le_refl.\n now apply add_nonpos_nonpos.\nQed.\n\nLemma abs_sub_triangle : forall n m, abs n - abs m <= abs (n-m).\nProof.\n intros.\n rewrite le_sub_le_add_l, add_comm.\n rewrite <- (sub_simpl_r n m) at 1.\n apply abs_triangle.\nQed.\n\n(** Absolute value and multiplication *)\n\nLemma abs_mul : forall n m, abs (n * m) == abs n * abs m.\nProof.\n assert (H : forall n m, 0<=n -> abs (n*m) == n * abs m).\n  intros. destruct_max m.\n  rewrite abs_eq. apply eq_refl. now apply mul_nonneg_nonneg.\n  rewrite abs_neq, mul_opp_r. reflexivity. now apply mul_nonneg_nonpos .\n intros. destruct_max n. now apply H.\n rewrite <- mul_opp_opp, H, abs_opp. reflexivity.\n now apply opp_nonneg_nonpos.\nQed.\n\nLemma abs_square : forall n, abs n * abs n == n * n.\nProof.\n intros. rewrite <- abs_mul. apply abs_eq. apply le_0_square.\nQed.\n\n(** Some results about the sign function. *)\n\nLtac destruct_sgn n :=\n let LT := fresh \"LT\" in\n let EQ := fresh \"EQ\" in\n let GT := fresh \"GT\" in\n destruct (lt_trichotomy 0 n) as [LT|[EQ|GT]];\n [rewrite (sgn_pos n) by auto|\n  rewrite (sgn_null n) by auto with relations|\n  rewrite (sgn_neg n) by auto].\n\nInstance sgn_wd : Proper (eq==>eq) sgn.\nProof.\n intros x y Hxy. destruct_sgn x.\n rewrite sgn_pos; auto with relations. rewrite <- Hxy; auto.\n rewrite sgn_null; auto with relations. rewrite <- Hxy; auto with relations.\n rewrite sgn_neg; auto with relations. rewrite <- Hxy; auto.\nQed.\n\nLemma sgn_spec : forall n,\n  0 < n /\\ sgn n == 1 \\/\n  0 == n /\\ sgn n == 0 \\/\n  0 > n /\\ sgn n == -1.\nProof.\n intros n.\n destruct_sgn n; [left|right;left|right;right]; auto with relations.\nQed.\n\nLemma sgn_0 : sgn 0 == 0.\nProof.\n now apply sgn_null.\nQed.\n\nLemma sgn_pos_iff : forall n, sgn n == 1 <-> 0<n.\nProof.\n split; try apply sgn_pos. destruct_sgn n; auto.\n intros. elim (lt_neq 0 1); auto. apply lt_0_1.\n intros. elim (lt_neq (-1) 1); auto.\n apply lt_trans with 0. rewrite opp_neg_pos. apply lt_0_1. apply lt_0_1.\nQed.\n\nLemma sgn_null_iff : forall n, sgn n == 0 <-> n==0.\nProof.\n split; try apply sgn_null. destruct_sgn n; auto with relations.\n intros. elim (lt_neq 0 1); auto with relations. apply lt_0_1.\n intros. elim (lt_neq (-1) 0); auto.\n rewrite opp_neg_pos. apply lt_0_1.\nQed.\n\nLemma sgn_neg_iff : forall n, sgn n == -1 <-> n<0.\nProof.\n split; try apply sgn_neg. destruct_sgn n; auto with relations.\n intros. elim (lt_neq (-1) 1); auto with relations.\n apply lt_trans with 0. rewrite opp_neg_pos. apply lt_0_1. apply lt_0_1.\n intros. elim (lt_neq (-1) 0); auto with relations.\n rewrite opp_neg_pos. apply lt_0_1.\nQed.\n\nLemma sgn_opp : forall n, sgn (-n) == - sgn n.\nProof.\n intros. destruct_sgn n.\n apply sgn_neg. now rewrite opp_neg_pos.\n setoid_replace n with 0 by auto with relations.\n  rewrite opp_0. apply sgn_0.\n rewrite opp_involutive. apply sgn_pos. now rewrite opp_pos_neg.\nQed.\n\nLemma sgn_nonneg : forall n, 0 <= sgn n <-> 0 <= n.\nProof.\n split.\n destruct_sgn n; intros.\n now apply lt_le_incl.\n order.\n elim (lt_irrefl 0). apply lt_le_trans with 1; auto using lt_0_1.\n  now rewrite <- opp_nonneg_nonpos.\n rewrite lt_eq_cases; destruct 1.\n rewrite sgn_pos by auto. apply lt_le_incl, lt_0_1.\n rewrite sgn_null by auto with relations. apply le_refl.\nQed.\n\nLemma sgn_nonpos : forall n, sgn n <= 0 <-> n <= 0.\nProof.\n intros. rewrite <- 2 opp_nonneg_nonpos, <- sgn_opp. apply sgn_nonneg.\nQed.\n\nLemma sgn_mul : forall n m, sgn (n*m) == sgn n * sgn m.\nProof.\n intros. destruct_sgn n; nzsimpl.\n destruct_sgn m.\n  apply sgn_pos. now apply mul_pos_pos.\n  apply sgn_null. rewrite eq_mul_0; auto with relations.\n  apply sgn_neg. now apply mul_pos_neg.\n apply sgn_null. rewrite eq_mul_0; auto with relations.\n destruct_sgn m; try rewrite mul_opp_opp; nzsimpl.\n  apply sgn_neg. now apply mul_neg_pos.\n  apply sgn_null. rewrite eq_mul_0; auto with relations.\n  apply sgn_pos. now apply mul_neg_neg.\nQed.\n\nLemma sgn_abs : forall n, n * sgn n == abs n.\nProof.\n intros. symmetry.\n destruct_sgn n; try rewrite mul_opp_r; nzsimpl.\n apply abs_eq. now apply lt_le_incl.\n rewrite abs_0_iff; auto with relations.\n apply abs_neq. now apply lt_le_incl.\nQed.\n\nLemma abs_sgn : forall n, abs n * sgn n == n.\nProof.\n intros.\n destruct_sgn n; try rewrite mul_opp_r; nzsimpl; auto.\n apply abs_eq. now apply lt_le_incl.\n rewrite eq_opp_l. apply abs_neq. now apply lt_le_incl.\nQed.\n\nLemma sgn_sgn : forall x, sgn (sgn x) == sgn x.\nProof.\n intros.\n destruct (sgn_spec x) as [(LT,EQ)|[(EQ',EQ)|(LT,EQ)]]; rewrite EQ.\n apply sgn_pos, lt_0_1.\n now apply sgn_null.\n apply sgn_neg. rewrite opp_neg_pos. apply lt_0_1.\nQed.\n\nEnd ZSgnAbsProp.\n\n\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/Numbers/Integer/Abstract/ZSgnAbs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634456, "lm_q2_score": 0.7956581000631541, "lm_q1q2_score": 0.6559898064834173}}
{"text": "Variables A B C : Prop.\nLemma ex5 : (A -> B -> C) -> ((A /\\ B) -> C).\nProof.\n  intro Ha_implies_Hb_implies_Hc.\n  intro Ha_and_Hb.\n  destruct Ha_and_Hb as [Ha Hb].\n  apply Ha_implies_Hb_implies_Hc.\n    +\n      assumption.\n    +\n      assumption.\nQed.", "meta": {"author": "alvarofpp", "repo": "course-coq", "sha": "64dc0d9a2e6564f9fa5df508fa946a137901feee", "save_path": "github-repos/coq/alvarofpp-course-coq", "path": "github-repos/coq/alvarofpp-course-coq/course-coq-64dc0d9a2e6564f9fa5df508fa946a137901feee/logica_proposicional_e_predicados/conjuncao/exercicio_05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.655987377452925}}
{"text": "Require Import Reals.\nLocal Open Scope R_scope.\nFrom ValidSDP Require Import validsdp.\n\nLet p (x0 x1 x2 x3 x4 x5 : R) :=\n  x0 * x3 * (0 - x0 + x1 + x2 - x3 + x4 + x5)\n  + x1 * x4 * (x0 - x1 + x2 + x3 - x4 + x5)\n  + x2 * x5 * (x0 + x1 - x2 + x3 + x4 - x5) - x1 * x2 * x3 - x0 * x2 * x4\n  - x0 * x1 * x5 - x3 * x4 * x5.\n\nLet b1 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x0 - 4/1) * (63504/10000 - x0).\n\nLet b2 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x1 - 4/1) * (63504/10000 - x1).\n\nLet b3 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x2 - 4/1) * (63504/10000 - x2).\n\nLet b4 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x3 - 4/1) * (63504/10000 - x3).\n\nLet b5 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x4 - 4/1) * (63504/10000 - x4).\n\nLet b6 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x5 - 4/1) * (63504/10000 - x5).\n\nTheorem p_nonneg (x0 x1 x2 x3 x4 x5 : R) :\n  b1 x0 x1 x2 x3 x4 x5 >= 0 ->\n  b2 x0 x1 x2 x3 x4 x5 >= 0 ->\n  b3 x0 x1 x2 x3 x4 x5 >= 0 ->\n  b4 x0 x1 x2 x3 x4 x5 >= 0 ->\n  b5 x0 x1 x2 x3 x4 x5 >= 0 ->\n  b6 x0 x1 x2 x3 x4 x5 >= 0 ->\n  p x0 x1 x2 x3 x4 x5 >= 0.\nProof.\nunfold b1, b2, b3, b4, b5, b6, p.\nvalidsdp.\nQed.\n", "meta": {"author": "validsdp", "repo": "validsdp", "sha": "135dd32a2b1166f357df764b469ce14e24711536", "save_path": "github-repos/coq/validsdp-validsdp", "path": "github-repos/coq/validsdp-validsdp/validsdp-135dd32a2b1166f357df764b469ce14e24711536/benchs/flyspeck/fs745.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.655987371573365}}
{"text": "Require Import Frap Pset1Sig.\n\nTheorem another_important_theorem : length [1; 2; 3] = 1 + length [4; 5].\nProof.\nsimplify.\nequality.\nQed.\n\nTheorem length_concat : forall A (xs ys : list A),\n    length (xs ++ ys) = length xs + length ys.\nProof.\n\n intros A.\n induction xs.\n intros ys.\n simplify.\n equality.\n intros ys.\n simplify.\n rewrite IHxs.\n equality.\nQed. \n\nTheorem length_rev : forall A (xs : list A),\n    length xs = length (rev xs).\nProof.\n induction xs; simpl; auto.\n rewrite length_concat.\n rewrite IHxs.\n simplify.\n intuition.\nQed.", "meta": {"author": "blakeelias", "repo": "6.887", "sha": "27a033ae339fbd0a53ebe2d361c68db416c6970a", "save_path": "github-repos/coq/blakeelias-6.887", "path": "github-repos/coq/blakeelias-6.887/6.887-27a033ae339fbd0a53ebe2d361c68db416c6970a/pset1/Pset1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6559656932861845}}
{"text": "Definition N := 19.\n\nInductive tree : Type :=\n| Leaf : tree\n| Node : nat -> tree -> tree -> tree.\n\nFixpoint binary_tree c n :=\n  match n with\n  | 0 => Leaf\n  | S n =>\n    let t := binary_tree c n in\n    Node c t t\n  end.\n\nDefinition t0 := Eval vm_compute in binary_tree 0 N.\nDefinition t1 := Eval vm_compute in binary_tree 1 N.\n", "meta": {"author": "eponier", "repo": "compare-eq", "sha": "cc2da184e747d0ad6ada8597e1ebf03377e413e2", "save_path": "github-repos/coq/eponier-compare-eq", "path": "github-repos/coq/eponier-compare-eq/compare-eq-cc2da184e747d0ad6ada8597e1ebf03377e413e2/equality_test/19/type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6559656843110249}}
{"text": "\nRequire Import ssr.\nRequire Import lib.\nRequire Import withzero.\n\nSet Implicit Arguments. \nUnset Strict Implicit. \nImport Prenex Implicits.\n\nOpen Scope dnat_scope.\n\nModule Type GALOIS.\n\n  (* -------------------------------------------------------------------------- *)\n  (*  Rings                                                                     *)\n  (* -------------------------------------------------------------------------- *)\n\n   Section Ring.\n  \n    Section Axioms.\n\n      Variable d' : eqType.\n      Notation d := (withzeroData d').\n      Notation \"0\" := (@Zero _).\n\n      Definition lift_opp (f:d'->d') x :=\n        match x with\n          | Zero => 0\n          | Nz x => Nz (f x)\n        end.\n\n      Definition lift_add (add:d'->d'->d) x y := \n        match x, y with \n          | Zero, _ => y\n          | _, Zero => x\n          | Nz x, Nz y => add x y\n        end.\n\n      Definition lift_mul (mul:d'->d'->d) x y := \n        match x, y with \n          | Nz x, Nz y => mul x y\n          | _, _ => 0\n        end.\n\n      Variable addr' : d'->d'->d.\n      Variable mulr' : d'->d'->d.\n      Variable oppr' : d'->d'.\n      Variable oner' : d'.\n\n      Notation \"x1 + x2\" := (lift_add addr' x1 x2).\n      Notation \"x1 * x2\" := (lift_mul mulr' x1 x2).\n      Notation \"- x\" := (lift_opp oppr' x).\n      Notation \"1\" := (Nz oner').\n\n      Structure ring_axioms : Type := Ring_axioms {\n        addC'    : forall x1 x2, x1 + x2 = x2 + x1;\n        addA'    : forall x1 x2 x3, x1 + (x2 + x3) = (x1 + x2) + x3;   \n        oppL'    : forall x,  - x + x = 0;\n        mulC'    : forall x1 x2, x1 * x2 = x2 * x1;\n        mulA'    : forall x1 x2 x3, x1 * (x2 * x3) = x1 * x2 * x3;\n        mul1r'   : forall x, 1 * x = x;\n        distPM'  : forall x1 x2 x3, (x1 + x2) * x3 = x1 * x3 + x2 * x3;\n        distMP'  : forall x1 x2 x3, x1 * (x2 + x3) = x1 * x2 + x1 * x3\n      }.\n\n    End Axioms.\n\n    Structure ring : Type := Ring {\n      rbase'    : eqType;\n      addr'     : rbase' -> rbase' -> withzero rbase';\n      oppr'     : rbase' -> rbase';\n      oner'     : rbase';\n      mulr'     : rbase' -> rbase' -> withzero rbase';\n      axioms    : ring_axioms addr' mulr' oppr' oner'\n    }.\n\n    Definition rbase r := withzeroData (rbase' r).\n    Coercion rbase : ring >-> eqType.\n\n    Variable r:ring.\n\n    Definition addr (x y:r) := lift_add (@addr' r) x y.\n    Definition mulr (x y:r) := lift_mul (@mulr' r) x y.\n    Definition oppr (x:r)   := lift_opp (@oppr' r) x.\n    Definition oner         := Nz (oner' r).\n\n    Notation \"x1 + x2\" := (addr x1 x2).\n    Notation \"x1 * x2\" := (mulr x1 x2).\n    Notation \"- x\"     := (oppr x).\n    Notation \"x - y\"   := (x + (- y)).\n    Notation \"1\"       := (oner).\n    Notation \"0\"       := (@Zero _).\n\n    Definition divides (a b:r) := exists a', a * a' = b.\n    Notation \"x |` y\" := (divides x y) (at level 55).\n\n    CoInductive gcd (f g d:r) : Type :=\n      Gcd : (d |` f) -> (d |` g) -> \n      (forall d', (d' |` f) -> (d' |` g) -> (d' |` d)) -> gcd f g d.\n\n    Definition unit (x:r) := exists x', (x * x' = 1).\n\n    Definition associates x y := exists u : r, unit u /\\ x = u * y.  \n\n    Definition irreducible p := forall x y, x * y = p -> (unit x \\/ unit y).\n\n    Definition prime (p:r) := ~ (unit p) /\\ irreducible p.\n\n    Definition rel_prime x y := forall d:r, gcd x y d -> unit d.\n\n    Fixpoint pow (x:r) (n:nat) {struct n} : r := \n      if n is S n' then x * pow x n' else 1.\n\n    Fixpoint cmul (n:nat) (a:r) {struct n} : r := \n      if n is S n' then a + cmul n' a else 1.\n\n    Fixpoint dot (s1 s2:seq r) {struct s1} : r := \n      match s1,s2 with \n        | seq0, seq0 => 1\n        | Adds h1 t1, Adds h2 t2 => h1 * h2 + dot t1 t2\n        | _, _ => 0\n      end.\n\n  End Ring.\n\n  Notation \"x1 + x2\" := (addr x1 x2)         : ring_scope.\n  Notation \"x1 * x2\" := (mulr x1 x2)         : ring_scope.\n  Notation \"- x\"     := (oppr x)             : ring_scope.\n  Notation \"0\"       := (@Zero _)            : ring_scope.\n  Notation \"1\"       := (oner _)             : ring_scope.\n  Notation \"x - y\"   := (x + oppr y)         : ring_scope.\n  Notation addrr   := (fun x y => y + x).\n  Notation mulrr   := (fun x y => y * x).\n  Open Scope ring_scope.\n\n  (* -------------------------------------------------------------------------- *)\n  (*  Domains                                                                   *)\n  (* -------------------------------------------------------------------------- *)\n \n  Section Domain.\n\n    Structure domain : Type := Domain {\n      dbase    :> ring;\n      domainP  : forall x1 x2:rbase' dbase, mulr' x1 x1 <> 0\n    }.\n\n  End Domain.\n\n  (* -------------------------------------------------------------------------- *)\n  (*  Fields                                                                    *)\n  (* -------------------------------------------------------------------------- *)\n\n  Section Field.\n\n    Structure field : Type := Field {\n      fbase :> domain;\n      invr' : rbase' fbase -> rbase' fbase;\n      unitPL0 : forall x, mulr' x (invr' x) = 1\n    }.\n\n    Definition invr (f:field) (x:f) := if x is Nz x' then Nz(invr' x') else 0.\n\n  End Field.\n\n  Notation \"x '^-1'\" := (invr x) (at level 9, format \"x '^-1'\") : ring_scope.\n\n  (* -------------------------------------------------------------------------- *)\n  (*  Subrings                                                                  *)\n  (* -------------------------------------------------------------------------- *)\n  \n  Section Subring.\n\n    Variable u:ring.\n\n    Structure subring : Type := Subring {\n      srbase :> set u;\n      zeroP  : srbase 0;\n      oneP   : srbase 1;\n      addP   : forall x y, srbase x -> srbase y -> srbase (x + y);\n      mulP   : forall x y, srbase x -> srbase y -> srbase (x * y);\n      oppP   : forall x, srbase x -> srbase (- x)\n    }.\n\n  End Subring.\n\n  (* -------------------------------------------------------------------------- *)\n  (*  Subfields                                                                 *)\n  (* -------------------------------------------------------------------------- *)\n\n  Section Subfield.\n\n    Variable f:field.\n\n    Structure subfield : Type := Subfield {\n      sfbase :> subring f;\n      invP   : forall x, sfbase x -> sfbase (invr x)\n    }.\n    \n  End Subfield.\n\n  (* -------------------------------------------------------------------------- *)\n  (*  Homomorphisms                                                             *)\n  (* -------------------------------------------------------------------------- *)\n  \n  Section Homomorphism.\n\n    Variable u v:ring.\n    Variable r:subring u.\n    Variable s:subring v.\n\n    Structure homo : Type := Homo {\n      hbase    :> u->v;\n      homoP    : forall x, r x -> s (hbase x);\n      homoAddP : forall x y, r x -> r y -> hbase (x + y) = hbase x + hbase y;\n      homoMulP : forall x y, r x -> r y -> hbase (x * y) = hbase x * hbase y;\n      homoJunk : forall x, ~ (r x) -> hbase x = 0\n    }.\n\n    Definition kernel (h:homo) := fun x => r x && (h x == 0).\n    \n    Structure iso : Type := Iso {\n      isbase :> homo;\n      imonoP : forall x y, r x -> r y -> isbase x = isbase y -> x = y;\n      iontoP : surj r s isbase\n    }.\n\n  End Homomorphism.\n  \n  (* -------------------------------------------------------------------------- *)\n  (*  Ideals                                                                    *)\n  (* -------------------------------------------------------------------------- *)\n  \n  Section Ideal.\n    \n    Variable u:ring.\n    Variable r:subring u.\n\n    Structure ideal : Type := Ideal {\n      idbase :> set u;\n      id_ss  : sub_set idbase r;\n      id0    : idbase 0;\n      id_add : forall x y, idbase x -> idbase y -> idbase (x + y);\n      idPL   : forall x y, idbase x -> r y -> idbase (x * y);\n      idPR   : forall x y, r x -> idbase y -> idbase (x * y)\n    }.\n\n    Parameter ring_to_ideal : forall r:subring u, ideal.\n\n    Variable i:ideal.\n\n    Definition maximal_ideal := \n      i <> ring_to_ideal r /\\  \n      forall j : ideal, sub_set i j -> j = i \\/ j = ring_to_ideal r.\n\n    Parameter principle_ideal : forall a:u, ideal.\n\n    Definition pid := forall i:ideal, exists a, i = principle_ideal a.\n\n  End Ideal.\n\n  (* -------------------------------------------------------------------------- *)\n  (*  Quotients                                                                 *)\n  (* -------------------------------------------------------------------------- *)\n\n  Section Quotient.\n    \n    Variable U:ring.\n    Variable R:subring U.\n    Variable I:ideal R.\n\n    Definition coset_pred (s:set U) := \n      exists a, s a /\\ forall x, s x <-> exists i, I i /\\ x = a + i.\n\n    Structure coset : Type := Coset {\n      cosetS :> set U; \n      coset_mem : coset_pred cosetS\n    }.\n\n    Definition eqcoset (c1 c2:coset) := Pb (forall x, cosetS c1 x == cosetS c2 x).\n    Axiom eqcosetPx : reflect_eq eqcoset.\n    Canonical Structure cosetData := EqType eqcosetPx.\n\n    Parameter elem_of_coset : coset -> U.\n    Parameter coset_of_elem : U -> coset.\n\n    Definition addq c1 c2 := coset_of_elem ((elem_of_coset c1) + (elem_of_coset c2)).\n    Definition mulq c1 c2 := coset_of_elem ((elem_of_coset c1) * (elem_of_coset c2)).\n    Definition oppq c     := coset_of_elem (- (elem_of_coset c)).\n    Definition zeroq      := coset_of_elem 0.\n    Definition oneq       := coset_of_elem 1.\n\n    Notation \"x1 +` x2\" := (addq x1 x2) (at level 50).\n    Notation \"x1 *` x2\" := (mulq x1 x2) (at level 40).\n    Notation \"-` x\"     := (oppq x) (at level 35).\n\n    Axiom addqC    : forall c1 c2:cosetData, c1 +` c2 = c2 +` c1.\n    Axiom addqA    : forall c1 c2 c3, c1 +` (c2 +` c3) = c1 +` c2 +` c3.\n    Axiom addq0    : forall c, c +` zeroq = c.\n    Axiom oppqL    : forall c, -` c +` c = zeroq.\n    Axiom mulqC    : forall x y, x *` y = y *` x.\n    Axiom mulqA    : forall c1 c2 c3, c1 *` (c2 *` c3) = c1 *` c2 *` c3.\n    Axiom mul1q    : forall x, oneq *` x = x.\n    Axiom distqPM  : forall x1 x2 x3, (x1 +` x2) *` x3 = x1 *` x3 +` x2 *` x3.\n    Axiom distqMP  : forall x1 x2 x3, x1 *` (x2 +` x3) = x1 *` x2 +` x1 *` x3.\n\n    Canonical Structure quotient := Ring (Ring_axioms addqC addqA oppqL mulqC mulqA mul1q distqPM distqMP).\n  End Quotient.\n\n  (* -------------------------------------------------------------------------- *)\n  (*  Polynomials                                                               *)\n  (* -------------------------------------------------------------------------- *)\n  \n  Section Poly.\n\n    Variable r:domain_z.\n\n    Inductive polyz : Type := Lc (c:rbase_z r) | Pcons (h:r) (t:polyz).\n\n    Notation \"h :: t\" := (Pcons h t) (at level 70).\n\n    Fixpoint eqpolyz (p1 p2:polyz) {struct p1} : bool := \n      match p1, p2 with\n        | Lc c1, Lc c2 => c1 == c2\n        | c1::t1, c2::t2 => (c1 == c2) && eqpolyz t1 t2 \n        | _, _ => false\n      end.\n\n    Axiom eqpolyzPx : reflect_eq eqpolyz.\n\n    Canonical Structure polyzData := EqType eqpolyzPx.\n\n    Definition poly := (withzeroData polyzData).\n\n    Definition onep := Lc (oner_z _).\n\n    Notation \"1\" := onep.\n\n    Definition const c := if c is Nz c' then Nz (Lc c') else Zero.\n    \n    Definition X := Nz(0::onep).\n\n    Definition horner c p := if p is Nz p' then Nz (c::p') else const c.\n\n    Fixpoint addpz (p1 p2:polyz) {struct p2} : poly :=\n      match p1, p2 with\n        | h::t, Lc c => Nz (addrz h (Nz c) :: t)\n        | Lc c, h::t => Nz (addrz (Nz c) h :: t)\n        | Lc c1, Lc c2 => const (addr_z c1 c2)\n        | h1 :: t1, h2 :: t2 => horner (h1 + h2) (addpz t1 t2)\n      end.\n\n    Definition addp (p1 p2:poly) : poly := lift_add addpz p1 p2.\n    \n    Fixpoint cmulpz (c:rbase_z r) (p:polyz) {struct p} : polyz := \n      match p with\n        | Lc c' => Lc (if mulr_z c c' is Nz c'' then c'' else c')\n        | h :: t => (mulrz (Nz c) h)::(cmulpz c t) \n      end.\n\n    Definition cmulp (c:r) (p:poly) : poly := \n      match c, p with\n        | Zero, _ => Zero\n        | _, Zero => Zero\n        | Nz c', Nz p' => Nz (cmulpz c' p')\n      end.\n\n    Definition mulpz_aux (c:r) p : poly := if c is Nz c' then Nz (cmulpz c' p) else Zero.\n\n    Fixpoint mulpz (p1 p2 : polyz) {struct p1} : poly := \n      match p1 with \n        | Lc c => Nz (cmulpz c p2)\n        | h :: t => \n          addp (mulpz_aux h p2) (horner Zero (mulpz t p2))\n      end.\n\n    Definition mulp (p1 p2:poly) : poly := lift_mul mulpz p1 p2.\n\n    Fixpoint opppz (p:polyz) {struct p} : polyz := \n      match p with\n        | h::t => - h::opppz t \n        | Lc c => Lc (oppr_z c)\n      end.\n\n    Definition oppp (p:poly) : poly := if p is Nz p' then Nz(opppz p') else Zero.\n\n    Fixpoint coefz (p:polyz) (i:nat) {struct i} : r := \n      match p, i with\n        | h::t, S n => coefz t n\n        | h::t, O => h\n        | Lc c, O => Nz c\n        | Lc c, S n => 0\n      end.\n\n    Definition coef (p:poly) i : r := if p is Nz p' then coefz p' i else 0.\n\n    Notation \"x1 + x2\" := (addp x1 x2).\n    Notation \"x1 * x2\" := (mulp x1 x2).\n    Notation \"- x\"     := (oppp x).\n    Notation \"x - y\"   := (x + (- y)).\n    Notation \"0\"       := (Zero).\n    Notation \"1\"       := (Nz onep).\n    Notation \"x <= y\"  := (nati.leq x y).\n    Notation \"x < y\"   := (nati.lt x y).\n\n    Axiom poly_indh : forall (P:poly->Prop),\n      P Zero -> (forall c p, P p -> P (horner c p)) -> (forall p, P p).\n\n    Axiom opppL     : forall p, - p + p = Zero.\n    Axiom addpA     : forall p1 p2 p3, p1 + (p2 + p3) = p1 + p2 + p3.\n    Axiom addpC     : forall p1 p2, p1 + p2 = p2 + p1.\n    Axiom mul1p     : forall p, 1 * p = p.\n    Axiom distpMP   : forall p1 p2 p3, p1 * (p2 + p3) = p1 * p2 + p1 * p3.\n    Axiom distpPM   : forall p1 p2 p3, (p1 + p2) * p3 = p1 * p3 + p2 * p3.\n    Axiom mulp1     : forall p, p * 1 = p.\n    Axiom mulpA     : forall p1 p2 p3, p1 * (p2 * p3) = p1 * p2 * p3.\n    Axiom mulpC     : forall p1 p2, p1 * p2 = p2 * p1.\n\n    Canonical Structure poly_ring := Ring_z (Ringz_axioms opppL addpA addpC mul1p mulp1 mulpA distpPM distpMP mulpC).\n    \n    Fixpoint degpz (p:polyz) {struct p} : nat :=\n      if p is h::t then S (degpz t) else O. \n\n    Definition degp p := if p is Nz p' then Nat (degpz p') else -oo.\n\n    Definition constant p    := degp p = Nat O \\/ degp p = -oo.\n    Definition linear p      := degp p = Nat 1.\n    Definition quadratic p   := degp p = Nat 2.\n    Definition cubic p       := degp p = Nat 3.\n    Definition quartic p     := degp p = Nat 4.\n    Definition quintic p     := degp p = Nat 5.\n\n    Axiom degp_const       : forall c, degp (const c) = if c is Nz _ then Nat O else -oo.\n    Axiom degp_add_unevenL : forall p1 p2, degp p2 < degp p1 -> degp (p1 + p2) = degp p1.\n    Axiom degp_add_unevenR : forall p1 p2, degp p1 < degp p2 -> degp (p1 + p2) = degp p2.\n    Axiom degp_inf         : forall p, degp p = -oo -> p = 0.\n    Axiom degp_add         : forall p q:poly, nati.leq (degp (p + q)) (maxi (degp p) (degp q)).\n    Axiom degp_opp         : forall p, degp (- p) = degp p.\n\n    Fixpoint lcz (p:polyz) {struct p} : rbase_z r :=\n      match p with \n        | Lc c => c\n        | h::t => lcz t\n      end.\n\n    Definition lc (p:poly) : r := if p is Nz p' then Nz (lcz p') else 0.\n\n    Definition monic p := lc p = (@onerz _).\n\n    Definition irreduciblep p := forall p1 p2, p = p1 * p2 -> degp p1 = Nat O \\/ degp p2 = Nat O.\n\n  End Poly.\n\n  Notation \"h :: t\" := (Pcons h t) (at level 70) : ring_scope.\n\n  (* -------------------------------------------------------------------------- *)\n  (*  Field Extensions                                                          *)\n  (* -------------------------------------------------------------------------- *)\n\n  Section Fields.\n\n    Variable U:field.\n    Variable K F : subfield U.\n\n    Definition extension (K F : subfield U) := sub_set F K.\n\n    Structure lcomb (vs' : seq U) (x : U) : Prop := Lcomb {\n      fs' : seq U;\n      fsP' : all F fs';\n      leP : dot fs' vs' = x\n    }.\n\n    Structure lcomb_ext (vs' : seq U) (x : U) : Prop := Lcomb_ext {\n      fs0 : seq U;\n      fsP0 : all F fs0;\n      leP0 : dot fs0 vs' = x;\n      leP1 : size fs0 = size vs' \n    }. \n \n    Axiom lcomb_extend : forall vs x, lcomb vs x <-> lcomb_ext vs x.\n\n    Definition span vs := fun x => Pb (lcomb vs x).\n\n    Fixpoint linind (vs : seq U) : bool := \n      if vs is Adds v vs' then ~~ (span vs' v) && linind vs' else true.\n\n    Structure lindep (vs : seq U) : Prop := Linind_spec {\n      fs : seq U;\n      nz : U;\n      nzP : nz != 0;\n      nzM : fs nz;\n      fsP : all F fs;\n      fvP : (size fs) <= (size vs);\n      depP : dot fs vs = 0\n    }.\n\n    Definition basis bs := linind bs && Pb (span bs = srbase K).\n\n    Definition finD := exists b, basis b.\n\n    Axiom inhabit : inhabited (seq U).\n  \n    Definition index := if Pb finD then Nat(size(epsilon inhabit basis)) else -oo.\n\n    Definition finite_ext := extension K F /\\ finD.\n\n    Structure splits_def (K F : subfield U) (p : poly U) (sseq : seq (polyData U)) : Prop := Splits_def {\n      sseqP      : all F p;\n      sseq_lin   : all (@linear U) sseq;\n      sseq_k     : all (all K \\o (@coefs _)) sseq;\n      sseq_mul   : foldr (@mul (poly_idom U)) 1 sseq = p\n    }.\n\n    Definition splits K F p := exists s, splits_def K F p s.\n\n    Structure splitting_field (K F : subfield U) (p : poly U) : Prop := Splitting_field {\n      sfQ    : all F p;\n      sf_spl : splits K F p;\n      sfP    : forall K' : subfield U, extension K K' -> splits K' F p -> K = K'\n    }.\n\n    Structure min_poly (F : subfield U) (p : poly U) (a : U) : Prop := Minp {\n      minpQ      : all F p;\n      minp_monic : monic p;\n      minpP      : root a p;\n      minpH      : forall (p' : poly U), all F p' -> root a p' -> degp p <= degp p'\n    }.\n\n    Structure algebraic (F : subfield U) (a : U) : Prop := Algebraic_spec {\n      algp : poly U;\n      algP : all F algp;\n      anz  : algp <> 0;\n      art  : root a algp\n    }.\n\n  (* Note!  one is not a galois automorphism if K is not an extension of F,\n     so take the fixed field to be the intersection of F,K *)\n    Definition galois_auto (a : auto_ty K) := Pb (forall x, F x -> K x -> auto a x = x).\n\n    Definition galois_fauto := fun (K F : subfield U) (Ekf : finite_ext K F) => \n      let (_, T) := finite_finite Ekf in\n        FinType (proj2 T).\n\n    Definition galois_group (K F : subfield U) : finGroupType. \n\n      Canonical Structure galois_group := Subgroup galois_mul galois_inv galois1.\n\n      Pb(forall a, H a -> (auto a) x = x).\n\n      Definition fixed_ring (H : subgroup(auto_group U)) : subring U.\n   (* {{{ *)\nmove=> H.\nexists (fixed H).\n- abstract(\n  apply/PbP; move=> a Ha /=;\n  rewrite /auto;\n  exact: homo0 (autoP a)).\n- abstract(\n  apply/PbP; move=> a Ha /=;\n  exact: iso1 (autoP a)).\n- abstract(\n  move=> x y Hx Hy;\n  move/PbP: (Hx) => Hx'; \n  move/PbP: (Hy) => Hy'; \n  apply/PbP; move=> a Ha;\n  rewrite (homoAddP (autoP a)); eauto;\n  rewrite Hx'; eauto;\n  by rewrite Hy'; eauto).\n- abstract(\n  move=> x y Hx Hy;\n  move/PbP: (Hx) => Hx'; \n  move/PbP: (Hy) => Hy'; \n  apply/PbP; move=> a Ha;\n  rewrite (homoMulP (autoP a)); eauto;\n  rewrite Hx'; eauto;\n  by rewrite Hy'; eauto).\nabstract(\nmove=> x Hx;\nmove/PbP: (Hx) => Hx'; apply/PbP;\nmove=> a Ha;\nrewrite (homoOpp (autoP a)); eauto;\nby rewrite Hx';eauto).\n (* }}} *)\n    Defined.\n\n    Definition fixed_field (H : subgroup(auto_group U)) : subfield U.\n   (* {{{ *)\nmove=> H;exists (fixed_ring H).\nabstract(\nmove=> x Hx; move/PbP: (Hx) => Hx'; apply/PbP;\nmove=> a Ha;\nmove: Hx; rewrite /= => Hx;\n(case H0 : (x == 0); first by move/eqP: H0 => ->;rewrite inv0 (homo0 (autoP a)));\nmove/eqP: H0 => H0;\nrewrite (inv_iso (autoP a)) => //;\nby rewrite (Hx' a Ha)).\n (* }}} *)\n  Defined.\n\n  Definition normal_ext := fixed_field galois_group = F.\n\n\n\n\n\n\n  End Fields.\n  \n\n\n\n\n", "meta": {"author": "kallol26", "repo": "coq-galois-theory", "sha": "4fff4d1b919d79f4dc4ba5afa126aa995e577489", "save_path": "github-repos/coq/kallol26-coq-galois-theory", "path": "github-repos/coq/kallol26-coq-galois-theory/coq-galois-theory-4fff4d1b919d79f4dc4ba5afa126aa995e577489/src/modules/galois_sig.old.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.6559656840734128}}
{"text": "(** A formalization of denumerable sets. *)\n(** by Florian Hatat, ENS-Lyon *)\n\n\nFrom Coq Require Import Ensembles  Arith ArithRing (* Even Div2 *)\n     Wellfounded Relations  Wf_nat  Finite_sets\n     Logic.Epsilon  Sets.Image Lia.\n\nFrom hydras Require Import MoreEpsilonIota PartialFun  GRelations\n     Prelude.More_Arith.\n\nImport Nat.\n\nSet Implicit Arguments.\n\nArguments rel_injection {A B}.\nArguments rel_surjection {A B}.\n\nSection Countable.\n\n  Section Definitions.\n    Variable U : Type.\n    Variable A : Ensemble U.\n    Let Dnat : Ensemble nat := Full_set nat.\n\n    (** Predicate for relations which number the elements of A.\n\n  These relations map each element of A to at least one integer, but they\n  are not required to be functional (injectivity is only needed to ensure that\n  A is countable). *)\n\n   \n    \n    Definition rel_numbers (R: GRelation U nat) := rel_injection A Dnat R.\n\n    (** Predicate for relations which enumerate A. *)\n    Definition rel_enumerates (R : GRelation nat U) := rel_surjection Dnat A R.\n\n     (** A is countable if there exists an injection from [A] to \n        [Full_set nat]. *)\n    \n    Definition countable : Prop := exists R, rel_numbers R.\n\n    Section Equivalence_with_surjection.\n\n      Theorem countable_surj :\n        countable <-> exists R, rel_enumerates R.\n      Proof.\n        split.\n        - intros   (R, R_enum).\n          exists (rel_inv A Dnat R).\n          red; apply R_inv_surj; trivial.\n        - destruct 1 as [R R_surj].\n        exists (rel_inv Dnat A R); red;  apply R_inv_inj; trivial.\n      Qed.\n    End Equivalence_with_surjection.\n\n  End Definitions.\n\n  Variable U : Type.\n\n  (** [Union _ A B] is countable if [A] and [B] are countable. *)\n  \n  Section Countable_union.\n\n    Section Countable_union_lemmas.\n\n      Variables E F : Ensemble U.\n      Variables RE RF : U -> nat -> Prop.\n\n      Hypothesis RE_enum : rel_numbers E RE.\n      Hypothesis RF_enum : rel_numbers F RF.\n\n      Inductive R_union (x : U) : nat -> Prop :=\n        from_E : forall n : nat, In E x -> RE x n -> R_union x (double n)\n      | from_F : forall n : nat, In F x -> RF x n -> R_union x (S (double n)).\n\n      Lemma R_union_domain : rel_domain (Union U E F) R_union.\n      Proof.\n        intros a aInUnion.\n        induction aInUnion.\n        - red in RE_enum; destruct RE_enum as (Hdomain, _, _).\n          destruct (Hdomain x).\n          + assumption.\n          + exists (double x0); apply from_E; assumption.\n         - destruct RF_enum as (Hdomain, _ , _);  destruct (Hdomain x).\n           + assumption.\n           + exists (S (double x0)); apply from_F; assumption.\n      Qed.\n\n      Lemma R_union_codomain :\n        rel_codomain (Union U E F) (Full_set nat) R_union.\n      Proof.\n        split.\n      Qed.\n\n      Remark R_union_double:\n        forall (x : U) (n : nat), R_union x (double n) -> RE x n.\n      Proof.\n        intros x n R_x_2n; inversion R_x_2n.\n        - replace n with n0; trivial.\n          apply double_inj; assumption.\n        - destruct (not_double_is_s_double _ _ H).\n      Qed.\n\n      Remark R_union_S_double :\n        forall (x : U) (n : nat), R_union x (S (double n)) -> RF x n.\n      Proof.\n        intros x n R_x_s2n; inversion R_x_s2n.\n        - symmetry in H;  case (not_double_is_s_double _ _ H).\n        - replace n with n0.\n         + assumption.\n         + apply double_inj; assumption.\n      Qed.\n\n      Lemma R_union_inj : rel_inj (Union U E F) R_union.\n      Proof.\n        intros a a' b a_In_Union a'_In_Union a_R_b a'_R_b.\n        inversion a_R_b as [na a_In_E a_RE_na dna_b |\n                            na a_In_F a_RF_na sdna_b].\n        - inversion a'_R_b as\n            [na' a'_In_E a'_RE_na' dna'_b |\n             na' a'_In_F a'_RF_na' sdna'_b].\n          + destruct RE_enum as (_, _, RE_inj);\n              apply RE_inj with na'; try assumption.\n            replace na' with na; try assumption.\n            apply double_inj.\n            symmetry in dna'_b; transitivity b; assumption.\n          + rewrite <- dna_b in sdna'_b.\n            case not_double_is_s_double with na' na; assumption.\n        - inversion a'_R_b as\n              [na' a'_In_E a'_RE_na' dna'_b |\n               na' a'_In_F a'_RF_nb sdna'_b].\n          + rewrite <- sdna_b in dna'_b.\n            symmetry in dna'_b.\n            case not_double_is_s_double with na na'; assumption.\n          + destruct RF_enum as (_, _, RF_inj).\n            apply RF_inj with na'; try assumption.\n            replace na' with na; try assumption.\n            apply double_inj.\n            symmetry in sdna'_b;  rewrite <- sdna_b in sdna'_b.\n            injection sdna'_b; trivial.\n      Qed.\n\n      Lemma R_union_enumerates : rel_numbers (Union U E F) R_union.\n      Proof.\n        split.\n        - apply R_union_domain.\n        - apply R_union_codomain.\n        - apply R_union_inj.\n      Qed.\n\n    End Countable_union_lemmas.\n\n    Theorem countable_union (E : Ensemble U) (F : Ensemble U) : \n      countable E -> countable F -> countable (Union U E F).\n    Proof.\n      intros E_den F_den;  destruct E_den as (RE, RE_enum);\n       destruct F_den as (RF, RF_enum).\n      exists (R_union E F RE RF); apply R_union_enumerates; assumption.\n    Qed.\n\n  End Countable_union.\n\n  Section Countable_inclusion.\n\n    Variables E F : Ensemble U.\n\n    Section Countable_inclusion_lemmas.\n\n      Variable RE : U -> nat -> Prop.\n      Hypothesis RE_enum : rel_numbers E RE.\n      Hypothesis F_in_E : Included _ F E.\n\n      Lemma R_inclusion_domain : rel_domain F RE.\n      Proof.\n        intros a a_In_F; destruct RE_enum as (RE_domain, _, _).\n        apply RE_domain, F_in_E; assumption.\n      Qed.\n\n      Lemma R_inclusion_codomain : rel_codomain F (Full_set nat) RE.\n      Proof.\n        split.\n      Qed.\n\n      Lemma R_inclusion_inj : rel_inj F RE.\n      Proof.\n        intros a a' b a_In_F a'_In_F a_R_B a_'R_b;\n        destruct RE_enum as (_, _, RE_inj);\n        apply (RE_inj a a' b); try apply F_in_E; assumption.\n      Qed.\n\n      Lemma R_inclusion_enumerates : rel_numbers F RE.\n      Proof.\n        split.\n        - apply R_inclusion_domain.\n        - apply R_inclusion_codomain.\n        - apply R_inclusion_inj.\n      Qed.\n\n    End Countable_inclusion_lemmas.\n\n    Theorem countable_inclusion :\n      countable E -> Included _ F E -> countable F.\n    Proof.\n      intros E_denum F_in_E; destruct E_denum as (RE, RE_enum).\n      exists RE; apply R_inclusion_enumerates; assumption.\n    Qed.\n\n  End Countable_inclusion.\n\n  (* Union of all sets B with B in A. *)\n  Section Infinite_union.\n\n    Variable A : Ensemble (Ensemble U).\n\n    Definition Infinite_union (x : U) : Prop :=\n      exists b, In A b /\\ In b x.\n\n    Section Infinite_union_lemmas.\n\n      Variable R : Ensemble U -> nat -> Prop.\n      Variable R_n : nat -> U -> nat -> Prop.\n\n      Hypothesis R_enums : rel_numbers A R.\n      Hypothesis R_n_enums :\n        forall n : nat, forall b : Ensemble U,\n\t    In A b -> R b n -> rel_numbers b (R_n n).\n\n      Fixpoint K (n : nat) : nat * nat :=\n        match n with\n          0 => (0, 0)\n        | S n => match K n with\n                   (0, m) => (S m, 0)\n                 | (S n, m) => (n, S m)\n                 end\n        end.\n\n      Definition K_1 : nat * nat -> nat :=\n        fun couple =>\n          let (p, q) := couple in\n          div2 ((p+q+1)*(p+q)) + q.\n\n      Let K_rel (p1 : nat*nat) (p2 : nat*nat) : Prop :=\n        let (p, q) := p1 in\n        let (p', q') := p2 in\n        (p + q < p' + q') \\/ (p + q = p' + q' /\\ p' < p).\n\n      Let f : nat * nat -> sigT (fun _ : nat => nat) :=\n        fun cpl =>\n          let (p, q) := cpl in\n          existT (fun _ : nat => nat) (p + q) q.\n      \n      Let R_K :=\n        (fun x y => (lexprod _ (fun _ => nat) lt (fun _ => lt)) (f x) (f y)).\n\n      Lemma lexof_wf :\n        well_founded R_K.\n      Proof.\n        unfold R_K;\n        apply wf_inverse_image with\n            (R := lexprod _ (fun _ => nat) lt (fun _ => lt)).\n        apply wf_lexprod; intros; apply Wf_nat.lt_wf.  \n      Qed.\n\n      Lemma K_rel_wf :  well_founded K_rel.\n      Proof.\n        apply wf_incl with R_K.\n        - intros (p, q) (p', q') HK_rel.\n          case HK_rel.\n          + intros Hin; unfold R_K; unfold f; apply left_lex; assumption.\n          + intros (Hdiag, Hin).\n            unfold R_K, f; rewrite Hdiag; apply right_lex.\n            case (le_lt_dec q' q).\n            * intros Hqin; case (lt_irrefl (p + q)).\n              pattern (p + q) at 1; rewrite Hdiag.\n              apply Nat.add_lt_le_mono ; assumption.\n            * trivial.\n        - apply lexof_wf.\n      Qed.\n\n      Remark double_K_1 :\n        forall p q, double (K_1 (p, q)) = ((p+q+1)*(p+q)) + double q.\n      Proof.\n        intros p q; unfold K_1. (* Here *)\n\n        rewrite double_plus.  f_equal.\n        rewrite div2_of_Even; trivial. \n        apply even_prod. \n      Qed. \n\n      Lemma K_bij :\n        forall p q, K (K_1 (p, q)) = (p, q).\n      Proof.\n        intros p q;  generalize (p, q);\n        intros p0; pattern p0; apply (well_founded_ind K_rel_wf).\n        clear p q p0; intros (p, q) IH.\n        induction q.\n        - induction p.\n          + trivial.\n          + replace (K_1 (S p, 0)) with (S (K_1 (0, p))).\n            simpl K; replace (K (div2 ((p + 1) * p) + p)) with (0, p).\n            trivial.\n            symmetry; unfold K_1 in IH; apply (IH (0, p)).\n            left; auto with arith.\n            apply double_inj.\n            rewrite (double_S (K_1 (0, p))).\n            rewrite (double_K_1 0 p).\n            rewrite (double_K_1 (S p) 0).\n            rewrite <- (plus_n_O (S p)).\n            rewrite (plus_O_n p).\n            unfold double.\n            rewrite (plus_O_n 0); rewrite <- (plus_n_O ((S p + 1) * S p)).\n            replace (S p) with (p + 1).\n            rewrite (plus_2 ((p + 1) * p + (p + p))).\n            ring.\n            lia.\n        - replace (K_1 (p, S q)) with (S (K_1 (S p, q))).\n          unfold K; fold K.\n          replace (K (K_1 (S p, q))) with (S p, q).\n          + trivial.\n          + symmetry; apply IH.\n            right; split; lia.\n          + apply double_inj.\n            rewrite (double_S (K_1 (S p, q))).\n            rewrite (double_K_1 (S p) q).\n            rewrite (double_K_1 p (S q)).\n            rewrite (plus_2 ((S p + q + 1) * (S p + q) + double q)).\n            replace (S q) with (q + 1).\n            replace (S p) with (p + 1).\n            unfold double.\n            ring.\n            lia.\n            lia.\n      Qed.\n\n      Lemma K_rel_dec :\n        forall x y, {K_rel x y} + {x = y} + {K_rel y x}.\n      Proof.\n        intros (p, q) (p', q').\n        case lt_eq_lt_dec with (p + q) (p' + q').\n        - intros Hcp; case Hcp.\n\n        (* p + q < p' + q' *)\n        + intros Hlt; repeat left; assumption.\n\n        (* p + q = p' + q' *)\n        + intros Heq; case lt_eq_lt_dec with p p'.\n          intros Hcpp; case Hcpp.\n          intros Hlt; repeat right; split; [symmetry |]; assumption.\n          intros Heqp; left; right; apply injective_projections; compute.\n          assumption.\n          erewrite <- (Nat.add_cancel_l _ _ p').  \n          rewrite Heqp in Heq; assumption.\n          intros Hlt; left; left; right; split; assumption.\n\n        (* p' + q' < p + q *)\n        - intros Hlt; right; left; assumption.\n      Qed.\n\n      Remark K_S_O :\n        forall n, K (S n) <> (0, 0).\n      Proof.\n        intros n Heq; simpl in Heq; symmetry in Heq.\n        case_eq (K n); intros p q Kn_pq.\n        rewrite Kn_pq in Heq.\n        case_eq p.\n        (* p = 0 *)\n        - intros p_eq; rewrite p_eq in Heq.\n          case O_S with q.\n          replace 0 with (fst (0, 0)); replace (S q) with (fst (S q, 0));\n          try (compute; trivial; fail).\n          apply (f_equal (fst (A := nat) (B := nat))); assumption.\n\n        (* p = S r *)\n        - intros r p_eq; rewrite p_eq in Heq.\n          case O_S with q.\n          replace 0 with (snd (0, 0)); replace (S q) with (snd (r, S q));\n          try (compute; trivial; fail).\n          apply (f_equal (snd (A := nat) (B := nat))); assumption.\n      Qed.\n\n      Lemma K_inj :\n        forall n m, K n = K m -> n = m.\n      Proof.\n        intros n m; pattern n, m.\n        apply nat_double_ind; clear n m.\n        - intros n Heq; simpl in Heq; case_eq n.\n        (* n = 0 *)\n          + trivial.\n        (* n = S m *)\n          + intros m n_Sm; rewrite n_Sm in Heq; symmetry in Heq;\n              case K_S_O with m; assumption.\n\n        - intros n Heq; simpl in Heq; case K_S_O with n; assumption.\n        - intros n m Hin Heq; apply eq_S; apply Hin.\n          case_eq (K n); case_eq (K m).\n          intros p' q' Km p q Kn.\n          simpl in Heq; rewrite Km in Heq; rewrite Kn in Heq.\n          case_eq p; case_eq p'.\n        (* p = 0 ; p' = 0 *)\n          + intros p'_eq p_eq; rewrite p_eq in Heq; rewrite p'_eq in Heq.\n            apply injective_projections; compute; auto.\n            injection Heq; auto.\n\n        (* p = 0 ; p' = S r *)\n          + intros r p'_eq p_eq; rewrite p_eq in Heq; rewrite p'_eq in Heq.\n            case O_S with q'.\n            replace 0 with (snd (S q, 0));\n              replace (S q') with (snd (r, S q'));\n          try (compute; trivial; fail).\n            apply (f_equal (snd (A := nat) (B := nat))); assumption.\n\n        (* p = S r ; p' = 0 *)\n          + intros p'_eq r p_eq; rewrite p_eq in Heq; rewrite p'_eq in Heq.\n            case O_S with q;  symmetry;  replace 0 with (snd (S q', 0));\n              replace (S q) with (snd (r, S q));\n              try (compute; trivial; fail).\n            apply (f_equal (snd (A := nat) (B := nat))); assumption.\n\n        (* p = S r ; p' = S r' *)\n          + intros r' p'_eq r p_eq; rewrite p_eq in Heq;\n              rewrite p'_eq in Heq.\n        injection Heq; auto.\n      Qed.\n\n      Definition R_union_qcq (x : U) (n : nat) :=\n        match K n with\n\t  (p, q) => exists b, (In A b /\\ R b p) /\\ (In b x /\\ R_n p x q)\n        end.\n\n      Lemma R_union_qcq_domain :\n        rel_domain Infinite_union R_union_qcq.\n      Proof.\n        intros a a_In_Union; elim a_In_Union.\n        intros b (b_In_A, a_In_b).\n        assert (ex_p: exists p, R b p).\n        { destruct R_enums as (R_domain, _, _).\n          now apply R_domain.\n        }\n        elim ex_p; intros p b_R_p.\n        \n        assert (ex_q : exists q, R_n p a q).  {\n          destruct (R_n_enums b_In_A b_R_p) as (R_n_domain, _, _).\n          apply R_n_domain.\n          assumption...\n        }\n        elim ex_q; intros q a_Rn_q.\n        exists (K_1 (p, q)).\n        red; replace (K (K_1 (p, q))) with (p, q).\n        exists b.\n        repeat split; assumption...\n        symmetry; apply K_bij...\n      Qed.\n\n      Lemma R_union_qcq_codomain :\n        rel_codomain Infinite_union (Full_set nat) R_union_qcq.\n      Proof.\n        split.\n      Qed.\n\n      Lemma R_union_qcq_inj :\n        rel_inj Infinite_union R_union_qcq.\n      Proof.\n        intros a a' n a_In_Union a'_In_Union a_Ru_n a'_Ru_n.\n        red in a_Ru_n; generalize a_Ru_n; case_eq (K n).\n        intros p q K_eq ex_b.\n        red in a'_Ru_n; generalize a'_Ru_n; case_eq (K n).\n        intros p' q' K'_eq.\n        assert (p_eq : p = p').\n        { transitivity (fst (K n));\n          [rewrite K_eq | rewrite K'_eq]; compute; trivial.\n        }\n        assert (q_eq : q = q'). {\n          transitivity (snd (K n));\n          [rewrite K_eq | rewrite K'_eq]; compute; trivial.\n        }\n        rewrite <- p_eq; rewrite <- q_eq.\n        intro ex_b';elim ex_b;\n          intros b ((b_In_A, b_R_p), (b_In_a, a_Rnp_q)).\n        elim ex_b'; intros b' ((b'_In_A, b'_R_p), (b'_In_a', a'_Rnp_q)).\n        assert (b_eq : b = b'). {\n          destruct R_enums as (_, _, R_inj).\n          apply R_inj with p; assumption.\n        }\n        rewrite <- b_eq in b'_In_a'.\n        destruct (R_n_enums b_In_A b_R_p) as (_, _, Rn_inj).\n        apply Rn_inj with q; assumption.\n      Qed.\n\n      Lemma R_union_qcq_numbers :\n        rel_numbers Infinite_union R_union_qcq.\n      Proof.\n        split.\n        - apply R_union_qcq_domain.\n        - apply R_union_qcq_codomain.\n        - apply R_union_qcq_inj.\n      Qed.\n\n    End Infinite_union_lemmas.\n\n    Section Indexed_union_lemmas_2.\n\n      Variable R : GRelation (Ensemble U) nat.\n      Hypothesis R_enum : rel_numbers A R.\n      Hypothesis all_b_denum : forall b : Ensemble U, In A b -> countable b.\n\n\n      \n      Remark inh_U_sets : inhabited (Ensemble U).\n      Proof inhabits  (Empty_set U).\n\n\n      Let b_n (n : nat) :=\n        epsilon inh_U_sets (fun b => In A b /\\ R b n).\n\n      Remark bn_R_n :\n        forall n, (exists b, In A b /\\ R b n) -> R (b_n n) n.\n      Proof.\n        intros n ex_b; pattern (b_n n); epsilon_elim.\n        intros a (_, a_R_n); assumption.\n      Qed.\n\n      Remark inh_grel_U_nat : inhabited (GRelation U nat).\n      Proof inhabits  (fun (u:U)(n:nat) => True).\n\n      Let R_b (b : Ensemble U) :=\n        epsilon inh_grel_U_nat (fun R => rel_numbers b R).\n\n      Remark Rb_numbers_b :\n        forall b, In A b -> rel_numbers b (R_b b).\n      Proof. \n        intros b b_In_A;\n        pattern (R_b b);  epsilon_elim.\n        apply all_b_denum.\n        assumption.\n      Qed.\n\n      Let R_n (n : nat) (x : U) (m : nat) :=\n        (exists b, R b n) /\\ R_b (b_n n) x m.\n\n      Remark Rn_numbers_bn :\n        forall n : nat, In A (b_n n) -> R (b_n n) n ->\n                        rel_numbers (b_n n) (R_n n).\n      Proof.\n        intros n bn_In_A; split.\n        intros x x_In_b.\n        destruct (Rb_numbers_b bn_In_A) as (Rb_dom, _, _).\n        - elim (Rb_dom x); try assumption.\n          intros m x_Rb_m; exists m.\n          split; [exists (b_n n) | idtac]; assumption.\n        - split.\n        - intros x x' m x_In_bn x'_In_bn (ex_b, x_Rb_m) (_, x'_Rb_m).\n          destruct (Rb_numbers_b bn_In_A) as (_, _, Rb_inj).\n          apply Rb_inj with m; assumption.\n      Qed.\n      \n\n      Let b_p (b : Ensemble U) :=\n        epsilon (inhabits 0) (fun p => b = b_n p).\n\n      Remark b_is_nth :\n        forall b : Ensemble U, In A b -> b = b_n (b_p b).\n      Proof.\n        intros b b_In_A;  pattern (b_p b); epsilon_elim.\n        destruct R_enum as (R_dom, _, R_inj); elim (R_dom b b_In_A).\n        intros p b_R_p; exists p; pattern (b_n p); epsilon_elim.\n        exists b; split; assumption.\n        intros a (a_In_A, a_R_p); apply R_inj with p; assumption.\n      Qed.\n\n      Lemma all_b_relation :\n        exists R_n : nat -> U -> nat -> Prop,\n        forall n : nat, forall b : Ensemble U,\n            In A b -> R b n -> rel_numbers b (R_n n).\n      Proof.\n        exists R_n; intros n b b_In_A b_R_n.\n        assert (b = b_n n). {\n          pattern (b_n n); epsilon_elim.\n          exists b; split; assumption.\n          destruct R_enum as (_, _, R_inj).\n          intros a (a_In_A, a_R_p).\n          apply R_inj with n; assumption.\n        }\n        rewrite H; rewrite H in b_In_A; rewrite H in b_R_n.\n        apply Rn_numbers_bn; assumption.\n      Qed.\n\n    End Indexed_union_lemmas_2.\n\n    Theorem countable_union_qcq :\n      countable A ->\n      (forall b : Ensemble U, In A b -> countable b) ->\n      countable Infinite_union.\n    Proof.\n      intros A_denum all_b_denum; elim A_denum; intros R R_enum.\n      elim all_b_relation with R; try assumption.\n      intros R_n R_n_enum; exists (R_union_qcq R R_n).\n      apply R_union_qcq_numbers; assumption.\n    Qed.\n\n  End Infinite_union.\n\n  Section Countable_empty.\n\n    Lemma countable_empty :\n      countable (Empty_set U).\n    Proof.\n      (* Any relation would fit here... *)\n      pose (R := fun (_ : U) (_ : nat) => False).\n      exists R; split.\n      - intros x; destruct 1.\n      -  split.\n      - intros x x' n x_In_empty; case x_In_empty.\n    Qed.\n\n  End Countable_empty.\n\n  Section Countable_singleton.\n\n    Variable x : U.\n\n    Lemma countable_singleton :\n      countable (Singleton _ x).\n    Proof.\n      pose (R := fun (y : U) (n : nat) => y = x).\n      exists R; split.\n      - intros y y_In_s; exists 0.\n        inversion y_In_s.\n        rewrite <- H; unfold R; reflexivity.\n      - split.\n      - intros y y' n y_In_s y'_In_s _ _.\n        inversion y_In_s.\n        inversion y'_In_s.\n        subst y; auto.\n    Qed.\n\n  End Countable_singleton.\n\n  Section Countable_seq_range.\n\n\n\n    Definition seq_range (f : nat -> U) : Ensemble U :=\n      image (Full_set nat) f.\n\n    Lemma seq_range_countable :\n      forall f, countable (seq_range f).\n    Proof.\n      intros f; pose (R := fun (x : U) (n : nat) => f n = x).\n      exists R; split.\n      - intros x; destruct 1.\n        exists x0; unfold R. tauto. \n      - split.\n      -  intros x x' n x_In_sr x'_In_sr x_R_n x'_R_n.\n         unfold R in x_R_n.\n         unfold R in x'_R_n.\n         subst x; auto.\n    Qed.\n\n  End Countable_seq_range.\n\n  Section Countable_bijection.\n\n    Variable V : Type.\n\n    Variable A : Ensemble U.\n    Variable B : Ensemble V.\n    Variable g : U -> V.\n\n    Hypothesis g_bij : fun_bijection A B g.\n\n    Lemma countable_bij_fun :\n      countable A -> countable B.\n    Proof.\n      intro A_denum; red in A_denum.\n      elim A_denum; intros Ru Ru_num.\n      pose (Rv := fun (y : V) (n : nat) =>\n                    exists x : U, In A x /\\ g x = y /\\ Ru x n).\n      exists Rv.\n      split.\n      - intros y y_In_B; destruct Ru_num as (Ru_dom, _, _).\n        unfold Rv; destruct g_bij as (_, g_onto, _).\n        elim g_onto with y; try assumption.\n        intros x (x_In_A, gx_eq_y).\n        elim Ru_dom with x; try assumption.\n        intros b x_Ru_b.\n        exists b; exists x; repeat split; assumption.\n      - split.\n      - intros y y' n y_In_B y'_In_B y_Rv_n y'_Rv_n.\n        unfold Rv in y_Rv_n; unfold Rv in y'_Rv_n.\n        elim y_Rv_n; intros x (x_In_A, (gx_eq_y, x_Ru_n)).\n        elim y'_Rv_n; intros x' (x'_In_A, (gx'_eq_y', x'_Ru_n)).\n        assert (x_eq : x = x'). {\n          destruct Ru_num as (_, _, Ru_inj).\n          apply Ru_inj with n; assumption.\n        }\n        rewrite <- gx_eq_y; rewrite x_eq; assumption.\n    Qed.\n\n    Lemma countable_bij_funR :\n      countable B -> countable A.\n    Proof.\n      intro B_denum; elim B_denum; intros Rv Rv_num.\n      pose (Ru := fun (x : U) (n : nat) => Rv (g x) n).\n      exists Ru; split.\n      - intros x x_In_A; unfold Ru.\n        destruct Rv_num.\n        apply H.\n        destruct g_bij.\n        apply H2; assumption.\n      - split.\n      - intros x x' n x_In_A x'_In_A x_Ru_n x'_Ru_n.\n        unfold Ru in x_Ru_n; unfold Ru in x'_Ru_n.\n        destruct Rv_num.\n        destruct g_bij; auto.\n        apply H4; auto.\n        apply H1 with n; auto.\n    Qed.\n\n  End Countable_bijection.\n\n  Section Countable_finite.\n\n\n\n    Variable A : Ensemble U.\n    Hypothesis A_finite : Finite _ A.\n\n    Theorem countable_finite : countable A.\n    Proof.\n      elim A_finite.\n      - apply countable_empty.\n      - intros A0 A0_finite A0_denum x x_nIn_A0.\n        unfold Add; apply countable_union.\n        assumption.\n        apply countable_singleton.\n    Qed.\n\n  End Countable_finite.\n\nEnd Countable.\n\nLemma countable_image : forall (U V:Type)(DA : Ensemble U)(f:U->V),\n    countable DA -> countable (image DA f).\nProof.\n  intros U V DA f H; case H; intros R HR.\n  case HR; intros H0 H1 H2.\n  exists (fun y n => exists x, DA x /\\ R x n /\\ f x = y).\n  split.\n  -   intros a (a0,(Ha0,H'a0)); case (H0 a0).\n      auto.\n      intros; exists x.\n      exists a0;auto.\n  - split.\n  -  intros a a' b (a0,(Ha0,H'a0)) (a1,(Ha1,H'a1)) (x,(Hx,(H'x,H''x)))\n         (y,(Hy,(H'y,H''y))).\n     generalize (H2 x y b Hx Hy H'x H'y);auto.\n     intro;subst y.\n     transitivity (f x);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/Schutte/Countable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6559656840734126}}
{"text": "(* (c) Copyright ? *)\n\n(*****************************************************************************\n  Verification of formula deductions in the appendix of paper \"Exact-Wiberg \n  Algorithm for Matrix Factorization with Missing Data\" (ECCV 2014 submission)\n\n  Main definitions:\n            sym A == A^T + A. A must be a square matrix.\n  mupinv_core u A == A^T *m A + u *ml: I\n           A ^- u == (mupinv_core u A)^^-1 *m A^T\n                  == (A^T *m A + u *ml: I)^^-1 *m A^T\n                     The mu-pseudoinverse.\n           pinv A == A ^- 0\n\n  Main results: \n        dm_mupinv : \n        \\\\d (A^-u) = 0 - A^-u *ml \\\\d A *mr A^-u + (A^T *m A + u *ml: I)^-1 \n                     *ml (\\\\d A)^T *mr (I - A *m A^-u)\n                     The first result in Appendix A.\n      dm_AmupinvA : \n   \\\\d (A *m A^-u) = sym ((I - A *m A^-u) *ml \\\\d A *mr A^-u)\n                     The second result in Appendix A.\n\n  All results are under the assumption: invertible (mupinv_core u A)).\n  Sometimes I write (0 - a *m b) instead of (- a *m b) because the unary minus \n  sign binds tighter than *m, which I find counter-intuitive.\n\n******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive. \n\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat div seq choice fintype.\nRequire Import finfun bigop prime binomial.\n\nRequire Import matrix.\nRequire Import ssralg.\nImport GRing.Theory.\nOpen Local Scope ring_scope.\n\nRequire Import mxutil.\nImport Notations.\nRequire Import bimodule.\nRequire Import derivation.\nRequire Import mxmodule.\nImport Notations.\nRequire Import mxdiff.\n\nSection Sym.\n\nVariable V : zmodType.\nVariable n : nat.\nImplicit Types A : 'M[V]_n.\n\nDefinition sym A := A^T + A.\n\nLemma fold_sym A : A^T + A = sym A.\nProof. by []. Qed.\n\nEnd Sym.\n\nSection MuPseudoinverse.\n\nVariable R : ringType.\n(* invmx requires comRing *)\nVariable E : unitComAlgType R.\n\nImplicit Types u : R.\nVariable m n : nat.\nImplicit Types A : 'M[E]_(m, n).\nImplicit Types B : 'M[E]_m.\n\nDefinition mupinv_core u A := A^T *m A + u *ml: I.\nDefinition mupinv_def u A := (mupinv_core u A)^^-1 *m A^T.\nFact mupinv_key : unit. by []. Qed. \nDefinition mupinv := locked_with mupinv_key mupinv_def.\nCanonical mupinv_unlockable := [unlockable fun mupinv].\n\nLocal Notation \"A ^- u\" := (mupinv u A) : ring_scope.\n\nLemma fold_mupinv u A : (A^T *m A + u *ml: I)^^-1 *m A^T = A^-u.\nProof. by rewrite unlock. Qed.\n\nLemma fold_mupinvT u A : A *m (A^T *m A + u *ml: I)^^-1 = (A^-u)^T.\nProof. \n  set goal := LHS.\n  by rewrite unlock trmx_mul trmxK trmx_inv linearD /= trmx_mul trmxK trmx_lscalemx trmx1.\nQed.\n\nEnd MuPseudoinverse.\n\nLocal Notation \"A ^- u\" := (mupinv u A) : ring_scope.\n\nSection Appendix.\n\n(* Scalar type *)\nVariable R : ringType.\n(* Element type *)\nVariable E : unitComAlgType R.\nVariable D : comBimodType E.\nVariable der : {linearDer E -> D}.\nNotation \"\\d\" := (LinearDer.apply der).\nNotation \"\\\\d\" := (map_mx \\d).\n\nVariable m n' : nat.\nLocal Notation n := n'.+1.\nImplicit Types A : 'M[E]_(m, n).\nImplicit Types B : 'M[E]_n.\n\nVariable A : 'M[E]_(m, n).\nVariable u : R.\n\nHypothesis h_invertible : invertible (mupinv_core u A).\n\nLemma AmupinvA_sym : (A *m A^-u)^T = A *m A^-u.\nProof. by rewrite trmx_mul -fold_mupinvT -fold_mupinv mulmxA. Qed.\n\nLemma dm_mupinv : \\\\d (A^-u) = 0 - A^-u *ml \\\\d A *mr A^-u + (A^T *m A + u *ml: I)^-1 *ml (\\\\d A)^T *mr (I - A *m A^-u).\nProof.\n  set goal := RHS.\n  rewrite unlock dmM /mupinv_core /=.\n  rewrite !invmx_inv (derV _ h_invertible) /mupinv_core -!invmx_inv /= rmulNmx -sub0r scale_lmul rscale_rmul.\n  rewrite raddfD /= dmcs dmI lscalemx0 addr0 dmM /=.\n  rewrite -rmulmxA fold_mupinv lmulmxDr rmulmxDl lrmulmxA lmulmxA opprD addrA.\n  by rewrite fold_mupinv sub0r [in - _ - _]addrC -addrA [in - _ + (_ *ml \\\\d _)](addrC) -rmulmxA -rmulmx1Br -map_trmx -sub0r.\nQed.\n\nLemma dm_AmupinvA : \\\\d (A *m A^-u) = sym ((I - A *m A^-u) *ml \\\\d A *mr A^-u).\nProof.\n  set goal := RHS.\n  rewrite dmM /=.\n  rewrite dm_mupinv sub0r !(lmulmxDr A) lmulmxN !addrA !lrmulmxA !lmulmxA.\n  rewrite fold_mupinvT.\n  rewrite !rmulmxDr rmulmx1 rmulmxN !rmulmxA !addrA.\n  rewrite -trmx_rmulmx -rmulmxA -[in _ *mr (A *m _) ]AmupinvA_sym -trmx_lmulmx -addrA -raddfB /= lrmulmxA addrC fold_sym.\n  by rewrite -lrmulmxA /= -(lmulmx1Br (A *m _)) lrmulmxA.\nQed.\n\nEnd Appendix.\n\nLemma mover {V : zmodType} (a b c : V) : a + b = c -> a = c - b.\nProof.\n  by move => h; apply (addIr b); rewrite addrNK.\nQed.\n\nLemma moveinvmx {R : comUnitRingType} m n A (B : 'M[R]_(m,n)) C : invertible A -> A *m B = C -> B = A^^-1 *m C.\nProof.\n  by move => hi h; rewrite -h (mulKmx hi).\nQed.\n\nLtac right_first name :=\n  match goal with\n    | |- _ /\\ ?R => have name: R; [ | split; [ | auto ] ]\n  end.\n\nLemma Schur_complement {R : comUnitRingType} m1 m2 n (A : 'M[R]_m1) B BT (C : 'M_m2) (x : 'M_(m1, n)) y a b :\n  block_mx A B BT C *m col_mx x y = col_mx a b -> \n  invertible C ->\n  BT = B^T ->\n  (A - B *m C^^-1 *m B^T) *m x = a - B *m C^^-1 *m b /\\ \n  y = C^^-1 *m (b - B^T *m x).\nProof.\n  move => h hi hb.\n  subst.\n  rewrite mul_block_col in h.\n  apply eq_col_mx in h.\n  move: h => [h1 h2].\n  right_first hy.\n  rewrite addrC in h2.\n  apply mover in h2.\n  by apply (moveinvmx hi).\n  set goal := _ = _.\n  move: h1.\n  rewrite hy !mulmxA !mulmxBr !mulmxA [in _ - _] addrC addrA -mulmxBl.\n  by apply mover.\nQed.\n\nModule Notations.\n\nNotation \"A ^- u\" := (mupinv u A) : ring_scope.\n\nEnd Notations.", "meta": {"author": "wangpengmit", "repo": "ssmatrix-theory", "sha": "aaec1c9a0cbd9df317272e4283937abc02b236fd", "save_path": "github-repos/coq/wangpengmit-ssmatrix-theory", "path": "github-repos/coq/wangpengmit-ssmatrix-theory/ssmatrix-theory-aaec1c9a0cbd9df317272e4283937abc02b236fd/theories/example_appendix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102419, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6559656668224009}}
{"text": "\nRequire Export Coq.Classes.RelationClasses.\n\nSet Default Goal Selector \"all\".\n\nClass Ordered(A : Set) :=\n  { lt : A -> A -> Prop;\n    lt_strict :> StrictOrder lt\n  }.\n\nClass OrderedKeyed (A K : Set) :=\n  { keyof : A -> K;\n    OA :> Ordered A\n  }.\n\nClass KeyOrdered (A K : Set) :=\n  { getkey : A -> K;\n    OK :> Ordered K\n  }.\n\nDefinition KOlt{A K : Set}`{KeyOrdered A K}(a b : A) : Prop := lt (getkey a) (getkey b).\n\nInstance KOisO A K `{KeyOrdered A K} : Ordered A.\nProof.\n  destruct (_:KeyOrdered A K) as [gk [ltk [SOI SOT]]]. unshelve eexists.\n  - intros a b. exact (ltk (gk a) (gk b)).\n  - split.\n    + unfold Irreflexive, Reflexive, complement in *. intro. apply SOI.\n    + unfold Transitive in *. intros x y z. apply SOT.\nDefined.\n\nInstance KOisOK A K `{KeyOrdered A K} : OrderedKeyed A K :=\n  { keyof := getkey }.\n\nClass ComparableKeyed (A K : Set) :=\n  { OKOK :> OrderedKeyed A K;\n    compare : K -> K -> comparison;\n    compare_spec x y: CompareSpecT (eq x y)\n                                   (forall (a b : A), x = keyof a -> y = keyof b -> lt a b)\n                                   (forall (a b : A), x = keyof a -> y = keyof b -> lt b a)\n                                   (compare x y);\n    lt_same_keys w x y z: lt w y -> keyof x = keyof w -> keyof z = keyof y -> lt x z\n  }.\n\nRequire Coq.Init.Nat.\nRequire Coq.Arith.PeanoNat.\n\nModule Test.\n\n  Import Nat.\n  Import PeanoNat.\n  \n  Open Scope nat_scope.\n\n  Context {A : Set}.\n  Context {Ord : Ordered A}.\n\n  Record OK : Set := { val : A; key : nat }.\n\n  Definition OKlt (a b : OK) : Prop := a.(key) < b.(key).\n\n  Lemma le_Sn_n : forall n, S n <= n -> False.\n  Proof.\n    induction n as [|? IHn]. intro H.\n    - inversion H.\n    - apply IHn. apply le_S_n. assumption.\n  Qed.\n\n  Lemma OKlt_strict : StrictOrder OKlt.\n  Proof.\n    eexists. red.\n    - red. red. intros [v k]. cbv. apply le_Sn_n.\n    - intros [? ?] [? ykey] [? ?]. unfold OKlt, key. transitivity ykey. assumption.\n  Qed.\n\n  Instance OKOrd : Ordered OK := { lt := OKlt; lt_strict := OKlt_strict }.\n\n  Lemma OKOrd_compare_spec (x y:nat) :\n    CompareSpecT (eq x y)\n                 (forall (a b : OK), x = a.(key) -> y = b.(key) -> OKlt a b)\n                 (forall (a b : OK), x = a.(key) -> y = b.(key) -> OKlt b a)\n                 (Nat.compare x y).\n  Proof.\n    destruct (CompareSpec2Type (Nat.compare_spec x y)). constructor.\n    - assumption.\n    - intros ? ? -> -> . assumption.\n    - intros ? ? -> -> . assumption.\n  Qed.\n\n  Lemma OKOrd_lt_same_keys w x y z :\n    OKlt w y -> x.(key) = w.(key) -> z.(key) = y.(key) -> OKlt x z.\n  Proof.\n    unfold OKlt. intros H -> -> . assumption.\n  Qed.\n\n  Instance OKnat : OrderedKeyed OK nat := { keyof := key }.\n \n  Instance CKnat : ComparableKeyed OK nat :=\n    { compare := Nat.compare;\n      compare_spec := OKOrd_compare_spec;\n      lt_same_keys := OKOrd_lt_same_keys\n    }.\n\nEnd Test.\n\n", "meta": {"author": "jonleivent", "repo": "mindless-coding-phase2", "sha": "74da2602ec6950c0e34141562a29bfd77682c88f", "save_path": "github-repos/coq/jonleivent-mindless-coding-phase2", "path": "github-repos/coq/jonleivent-mindless-coding-phase2/mindless-coding-phase2-74da2602ec6950c0e34141562a29bfd77682c88f/ordered.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6559595595703779}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Naturals -- TODO: use typeclasses                                       *\n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Export Arith Div2 Omega.\nRequire Import LibTactics LibReflect LibBool LibOperation LibRelation LibOrder.\nRequire Export LibOrder.\nGlobal Close Scope positive_scope.\n\n(* ********************************************************************** *)\n(** * Inhabited and comparable *)\n\nInstance nat_inhab : Inhab nat.\nProof. intros. apply (prove_Inhab 0). Qed.\n\nFixpoint nat_compare (x y : nat) :=\n  match x, y with\n  | O, O => true\n  | S x', S y' => nat_compare x' y'\n  | _, _ => false\n  end.\n\nInstance nat_comparable : Comparable nat.\nProof.\n  applys (comparable_beq nat_compare).\n  induction x; destruct y; simpl.\n  auto*.\n  auto_false.\n  auto_false.\n  asserts_rewrite ((S x = S y) = (x = y)).\n    extens. iff; omega.\n  auto*.\nQed.\n\n\n(* ********************************************************************** *)\n(** * Order on natural numbers *)\n\nInstance le_nat_inst : Le nat := Build_Le Peano.le.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Relation to Peano, for tactic [omega] *)\n\nLemma le_peano : le = Peano.le.\nProof. extens*. Qed.\n\nGlobal Opaque le_nat_inst.\n\nLemma lt_peano : lt = Peano.lt.\nProof.\n  extens. rew_to_le. rewrite le_peano. \n  unfold strict. intros. omega.\nQed.\n\nLemma ge_peano : ge = Peano.ge.\nProof.\n  extens. rew_to_le. rewrite le_peano. \n  unfold flip. intros. omega.\nQed.\n\nLemma gt_peano : gt = Peano.gt.\nProof.\n  extens. rew_to_le. rewrite le_peano. \n  unfold strict, flip. intros. omega.\nQed.\n\nHint Rewrite le_peano lt_peano ge_peano gt_peano : rew_nat_comp.\nLtac nat_comp_to_peano := \n  autorewrite with rew_nat_comp in *.\n\n(** [nat_math] calls [omega] after basic pre-processing\n    ([intros] and [split]) and after replacing comparison\n    operators with the ones defined in [Peano] library. *)\n\nLtac nat_math_setup :=\n  intros; \n  try match goal with |- _ /\\ _ => split end;\n  try match goal with |- _ = _ :> Prop => apply prop_ext; iff end;\n  nat_comp_to_peano.\n\nLtac nat_math :=\n  nat_math_setup; omega.\n\n\n(* ********************************************************************** *)\n(** * Operations *)\n\nDefinition div (n q : nat) := \n  match q with \n  | 0 => 0\n  | S predq => \n  let aux := fix aux (m r : nat) {struct m} :=\n    match m,r with\n    | 0, _ => 0\n    | S m',0 => (1 + aux m' predq)%nat\n    | S m', S r' => aux m' r'\n    end in \n  aux n predq\n  end.\n\nFixpoint factorial (n:nat) : nat := \n  match n with\n  | 0 => 1\n  | S n' => n * (factorial n')\n  end.\n\n\n(* ********************************************************************** *)\n(** * Induction *)\n\nLemma peano_induction : \n  forall (P:nat->Prop),\n    (forall n, (forall m, m < n -> P m) -> P n) ->\n    (forall n, P n).\nProof.\n  introv H. cuts* K: (forall n m, m < n -> P m).\n  nat_comp_to_peano.\n  induction n; introv Le. inversion Le. apply H.\n  intros. apply IHn. nat_math. \nQed.\n\nLemma measure_induction : \n  forall (A:Type) (mu:A->nat) (P:A->Prop),\n    (forall x, (forall y, mu y < mu x -> P y) -> P x) ->\n    (forall x, P x).\nProof.\n  introv IH. intros x. gen_eq n: (mu x). gen x.\n  induction n using peano_induction. introv Eq. subst*.\nQed.\n\n\n(* ********************************************************************** *)\n(** * Simplification lemmas *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Addition and substraction *)\n\nLemma plus_zero_r : forall n,\n  n + 0 = n.\nProof. nat_math. Qed.\nLemma plus_zero_l : forall n,\n  0 + n = n.\nProof. nat_math. Qed. \nLemma minus_zero : forall n,\n  n - 0 = n.\nProof. nat_math. Qed.\n\nHint Rewrite plus_zero_r plus_zero_l minus_zero : rew_nat.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Comparison *)\n\nSection CompProp.\nImplicit Types a b c n m : nat.\n\nLemma le_SS : forall n m, (S n <= S m) = (n <= m).\nProof. nat_math. Qed.\nLemma ge_SS : forall n m, (S n >= S m) = (n >= m).\nProof. nat_math. Qed.\nLemma lt_SS : forall n m, (S n < S m) = (n < m).\nProof. nat_math. Qed.\nLemma gt_SS : forall n m, (S n > S m) = (n > m).\nProof. nat_math. Qed.\n\nLemma plus_le_l : forall a b c,\n  (a + b <= a + c) = (b <= c).\nProof. nat_math. Qed.\nLemma plus_ge_l : forall a b c,\n  (a + b >= a + c) = (b >= c).\nProof. nat_math. Qed.\nLemma plus_lt_l : forall a b c,\n  (a + b < a + c) = (b < c).\nProof. nat_math. Qed.\nLemma plus_gt_l : forall a b c,\n  (a + b > a + c) = (b > c).\nProof. nat_math. Qed.\n\nLemma plus_le_r : forall a b c,\n  (b + a <= c + a) = (b <= c).\nProof. nat_math. Qed.\nLemma plus_ge_r : forall a b c,\n  (b + a >= c + a) = (b >= c).\nProof. nat_math. Qed.\nLemma plus_lt_r : forall a b c,\n  (b + a < c + a) = (b < c).\nProof. nat_math. Qed.\nLemma plus_gt_r : forall a b c,\n  (b + a > c + a) = (b > c).\nProof. nat_math. Qed.\n\nEnd CompProp.\n\n(* todo: negation *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Simplification tactic *)\n\n(** [rew_nat] performs some basic simplification on \n    expressions involving natural numbers *)\n\nHint Rewrite le_SS ge_SS lt_SS gt_SS : rew_nat.\nHint Rewrite plus_le_l plus_ge_l plus_lt_l plus_gt_l : rew_nat.\nHint Rewrite plus_le_r plus_ge_r plus_lt_r plus_gt_r : rew_nat.\n\nTactic Notation \"rew_nat\" :=\n  autorewrite with rew_nat.\nTactic Notation \"rew_nat\" \"~\" :=\n  rew_nat; auto_tilde.\nTactic Notation \"rew_nat\" \"*\" :=\n  rew_nat; auto_star.\nTactic Notation \"rew_nat\" \"in\" \"*\" :=\n  autorewrite with rew_nat in *.\nTactic Notation \"rew_nat\" \"~\" \"in\" \"*\" :=\n  rew_nat in *; auto_tilde.\nTactic Notation \"rew_nat\" \"*\" \"in\" \"*\" :=\n  rew_nat in *; auto_star.\nTactic Notation \"rew_nat\" \"in\" hyp(H) :=\n  autorewrite with rew_nat in H.\nTactic Notation \"rew_nat\" \"~\" \"in\" hyp(H) :=\n  rew_nat in H; auto_tilde.\nTactic Notation \"rew_nat\" \"*\" \"in\" hyp(H) :=\n  rew_nat in H; auto_star.\n\n\n(* ********************************************************************** *)\n(** * Other lemmas *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Div2 *)\n\nLemma div2_lt : forall n m, m <= n -> n > 0 -> div2 m < n.\nProof.\n  nat_comp_to_peano.\n  induction n using peano_induction. introv Le Gt.\n(* todo: fix this proof that broken when migrating to v8.3\n  do 2 (destruct n; try solve [omega]). \n  do 2 (destruct m; try solve [omega]).\n  do 2 destruct~ m. simpl. cuts~: (div2 m < S n). apply H.\n  nat_math. nat_math. auto. \n*) skip.\nQed.\n\nLemma div2_grows : forall n m, m <= n -> div2 m <= div2 n.\nProof.\n  nat_comp_to_peano.\n  induction n using peano_induction. introv Le.\n  destruct~ m. simpl. omega.\n  destruct~ n. simpl. omega.\n  destruct~ m. simpl. omega.\n  destruct~ n. simpl. omega.\n  simpl. rew_nat. apply~ H. nat_math. nat_math.\nQed.\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/LibNat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764119, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6559595369065083}}
{"text": "(* begin hide *)\nSet Implicit Arguments.\nSet Asymmetric Patterns.\nRequire Import Cpdt.CpdtTactics.\nRequire Import List. \n(* end hide *)\n\n(* 06. FROM DATA STRUCT *)\n\n(* Some of the type family definitions and associated functions from this chapter are dupli-\ncated in the DepList module of the book source. Some of their names have been changed to\nbe more sensible in a general context. *)\n\n(*\n1. Define a tree analogue of hlist. That is, define a parameterized type of binary trees with\ndata at their leaves, and define a type family htree indexed by trees. The structure of\nan htree mirrors its index tree, with the type of each data element (which only occur\nat leaves) determined by applying a type function to the corresponding element of the\nindex tree. *)\n\nSection htree.\n  Variable A : Type.\n  Variable B : A -> Type.\n\n  Inductive tree (T : Type) : Type :=\n  | Leaf : T -> tree T\n  | Node : tree T -> tree T -> tree T.                   \n\n  Inductive htree : tree A -> Type :=\n  | HLeaf : forall (x : A), B x -> htree (Leaf x)\n  | HNode : forall (tr1 : tree A) (tr2 : tree A), htree tr1 ->\n                                                  htree tr2 ->\n                                                  htree (Node tr1 tr2).\n\n(* Define a type standing for all possible paths from the root of a tree to\nleaves and use it to implement a function tget for extracting an element of an htree\nby path. *)\n\n Variable elm : A.\n\n Inductive membert : tree A -> Type :=\n | HThis : membert (Leaf elm)\n | HLeft : forall tr1 tr2, membert tr1 -> membert (Node tr1 tr2)\n | HRight : forall tr1 tr2, membert tr2 -> membert (Node tr1 tr2).     \n\n Print Empty_set. \n(*\nFixpoint tget tr (mtr : htree tr) : membert tr -> B elm :=\n  match mtr with\n  | HLeaf _ bx => fun mem => (match mem in membert (Leaf h) return (B h -> B elm) with\n                             | HThis => fun x => x\n                             | _ => fun x => x\n                             end) bx\n  | HNode t1 t2 Ht1 Ht2 => fun mem => match mem in membert tr' return (match tr' with\n                                                                      | Leaf _ => unit\n                                                                      | Node lt rt =>\n                                                                        (membert lt -> B elm) ->\n                                                                        (membert rt -> B elm) ->\n                                                                        B elm\n                                                                      end) with\n                                      | HThis => tt\n                                      | HLeft _ _ meml => tget t1 _ Ht1\n                                      | HRight _ _ memr => tget t2 _ Ht2\n                                      end  \n  end.                                        \n*)\nEnd htree. \n\nSection hlist.\n  Variable A : Type.\n  Variable B : A -> Type.\n\n  Inductive hlist : list A -> Type :=\n  | HNil : hlist nil\n  | HCons : forall (x : A) (ls : list A), B x -> hlist ls -> hlist (x :: ls).    \n\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     ls - список эл-в типа A (ANat | ABool) \n     mls : hlist ls\n     возвращает (B elm) - элемент типа nat, 3, например *)\n   \n  Fixpoint hget ls (mls : hlist ls) : member ls -> B elm :=\n    match mls with\n      | HNil => match\n\n\nEnd hlist.         \n\n(* Example of HList by Adam Chlipala, from the book *)\nArguments HNil {A B}.\nArguments HCons {A B x ls}.\nArguments HFirst {A elm ls}.\nArguments HNext {A elm x ls}.\n\nDefinition someTypes : list Set := nat :: bool :: nil. \nExample someValues : hlist (fun T : Set => T) someTypes := HCons 5 (HCons true HNil).\n\nEval simpl in hget someValues HFirst. \nEval simpl in hget someValues (HNext HFirst). \n\nExample somePairs : hlist (fun T : Set => T * T)%type someTypes := HCons (1,2) (HCons (true, false)HNil).\n\n(* Example of hlist by Natasha*)\nInductive atype := ANat | ABool. (*  elements of type A  *)\n\nDefinition b_type : atype -> Type := (*  function B  *)\n  fun x => match x with\n           | ANat => nat\n           | ABool => bool\n           end.              \n\nCheck HCons.\nCheck (@HCons atype b_type ANat nil 3 (@HNil atype b_type)).\nCheck @HCons atype b_type ABool (ANat :: nil) true (@HCons atype b_type ANat nil 3 (@HNil atype b_type)).\n\n(* Define a function htmap2 for \"mapping over two trees in parallel.\" That is,\nhtmap2 takes in two htrees with the same index tree, and it forms a new htree with\nthe same index by applying a binary function pointwise.\nRepeat this process so that you implement each definition for each of the three defini-\ntion styles covered in this chapter: inductive, recursive, and index function.\n *)\n", "meta": {"author": "klausnat", "repo": "Adam_Chlipala_Certified_Programming_with_Dependent_Types_Exercises", "sha": "1b38f49e21dbc64d0daea30eb2af1301ed142616", "save_path": "github-repos/coq/klausnat-Adam_Chlipala_Certified_Programming_with_Dependent_Types_Exercises", "path": "github-repos/coq/klausnat-Adam_Chlipala_Certified_Programming_with_Dependent_Types_Exercises/Adam_Chlipala_Certified_Programming_with_Dependent_Types_Exercises-1b38f49e21dbc64d0daea30eb2af1301ed142616/Exercises_06_From_DataStruct_Natasha.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6559595251476125}}
{"text": "Require Import Compare_dec.\nRequire Import Utils.\n\nRequire Import Le Lt.\nRequire Import Plus.\n\nDefinition varBump n l i := match nat_compare i l with\n\tLt => i |\n\t_ => n + i\nend.\n\nDefinition varSubst l b i := match nat_compare i l with\n\tLt => i |\n\tEq => l + b |\n\tGt => pred i\nend.\n\nLemma lt_ltdHi n l i : ~(i < l)->ltd l (S n + i).\n\tintro.\n\tapply lt_ltd.\n\tsimpl.\n\tapply le_n_S.\n\trewrite <- plus_comm.\n\tapply le_plus_trans.\n\texact (not_lt _ _ H).\nQed.\nImplicit Arguments lt_ltdHi [l i].\n\nLemma varBumpLo n l i : (i < l)->(varBump n l i = i).\n\tintro.\n\tunfold varBump.\n\trewrite (proj1 (nat_compare_lt _ _) H).\n\treflexivity.\nQed.\n\nLemma varBumpHi n l i : ~(i < l)->(varBump n l i = n + i).\n\tintro.\n\tunfold varBump.\n\tdestruct (nat_compare_spec i l);try reflexivity.\n\texact (match H H0 with end).\nQed.\n\nLemma varSubstLt l b i : (i < l)->(varSubst l b i = i).\n\tintro.\n\tunfold varSubst.\n\trewrite (proj1 (nat_compare_lt _ _) H).\n\treflexivity.\nQed.\n\nLemma varSubstEq l b i : (i = l)->varSubst l b i = l + b.\n\tintro.\n\tunfold varSubst.\n\trewrite (proj2 (nat_compare_eq_iff _ _) H).\n\treflexivity.\nQed.\n\nLemma varSubstGt l b i : (i > l)->(varSubst l b i = pred i).\n\tintro.\n\tunfold varSubst.\n\trewrite (proj1 (nat_compare_gt _ _) H).\n\treflexivity.\nQed.\n\nLemma varBump_Bump n1 n2 l1 l2 i : (l1 <= l2)->\n(varBump n2 (n1 + l2) (varBump n1 l1 i) = varBump n1 l1 (varBump n2 l2 i)).\n\tintro.\n\tdestruct (lt_dec i l1).\n\n\tassert (i < l2).\n\t\texact (le_trans _ _ _ l H).\n\trewrite varBumpLo with (1 := l).\n\trewrite varBumpLo with (1 := H0).\n\trewrite varBumpLo with (1 := l).\n\tapply varBumpLo.\n\tapply le_trans with (1 := H0).\n\tapply le_plus_r.\n\n\trewrite varBumpHi with (1 := n).\n\tdestruct (lt_dec i l2).\n\t\trewrite varBumpLo with (1 := l).\n\t\trewrite varBumpHi with (1 := n).\n\t\tapply varBumpLo.\n\t\tapply plus_lt_compat_l with (1 := l).\n\n\t\trewrite varBumpHi with (1 := n0).\n\t\trewrite varBumpHi;[| intro;apply n0;apply plus_lt_reg_l with (1 := H0)].\n\t\trewrite varBumpHi;\n\t\t[|\n\t\t\tintro;\n\t\t\tapply n;\n\t\t\tapply le_trans with (2 := H0);\n\t\t\tapply le_n_S;\n\t\t\tapply le_plus_r\n\t\t].\n\t\trewrite plus_assoc.\n\t\trewrite <- (plus_comm n1).\n\t\trewrite <- plus_assoc.\n\t\treflexivity.\nQed.\n\nLemma varBumpDiv a b n l i : (n <= b)->(varBump a (l + n) (varBump b l i) = varBump (a + b) l i).\n\tintro.\n\tdestruct (lt_dec i l).\n\n\trewrite varBumpLo with (1 := l0).\n\trewrite varBumpLo with (1 := l0).\n\tapply varBumpLo.\n\tapply le_trans with (1 := l0).\n\tapply le_plus_l.\n\n\trewrite varBumpHi with (1 := n0).\n\trewrite varBumpHi with (1 := n0).\n\trewrite <- plus_assoc.\n\tapply varBumpHi.\n\tintro.\n\tapply n0.\n\tapply plus_lt_reg_l with n.\n\trewrite <- (plus_comm l).\n\tapply le_trans with (2 := H0).\n\tapply le_n_S.\n\tapply plus_le_compat_r with (1 := H).\nQed.\n\nLemma varBump_Subst n x l b i :\nvarBump n (x + l) (varSubst l b i) = varSubst l (varBump n x b) (varBump n (S x + l) i).\n\tdestruct (lt_dec i (S x + l)).\n\n\trewrite varBumpLo with (1 := l0).\n\tdestruct (lt_eq_lt_dec i l);[destruct s |].\n\t\trewrite varSubstLt with (1 := l1).\n\t\trewrite varSubstLt with (1 := l1).\n\t\tapply varBumpLo.\n\t\tapply le_trans with (1 := l1).\n\t\tapply le_plus_r.\n\n\t\trewrite varSubstEq with (1 := e).\n\t\trewrite varSubstEq with (1 := e).\n\t\tassert (forall k,varBump l O k = l + k).\n\t\t\tintro.\n\t\t\tapply varBumpHi.\n\t\t\tapply lt_n_O.\n\t\trewrite <- H.\n\t\trewrite <- plus_comm.\n\t\trewrite varBump_Bump with (1 := le_O_n _).\n\t\tapply H.\n\n\t\trewrite varSubstGt with (1 := l1).\n\t\trewrite varSubstGt with (1 := l1).\n\t\tapply varBumpLo.\n\t\tdestruct i.\n\t\t\tdestruct lt_n_O with (1 := l1).\n\t\tsimpl in l0 |- *.\n\t\tapply lt_S_n with (1 := l0).\n\n\trewrite varBumpHi with (1 := n0).\n\tassert (l < i).\n\t\tapply not_lt.\n\t\tintro.\n\t\tapply n0.\n\t\tapply le_trans with (1 := H).\n\t\tsimpl.\n\t\trewrite plus_n_Sm.\n\t\tapply le_plus_r.\n\trewrite varSubstGt with (1 := H).\n\trewrite varSubstGt;[| apply le_trans with (1 := H);apply le_plus_r].\n\tdestruct i.\n\t\tdestruct lt_n_O with (1 := H).\n\trewrite <- plus_n_Sm.\n\tsimpl.\n\tapply varBumpHi.\n\tintro.\n\tapply n0.\n\tsimpl.\n\tapply lt_n_S with (1 := H0).\nQed.\n\nLemma varSubst_Bump n l1 l2 b i : (l1 <= l2)->\n(varSubst (n + l2) b (varBump n l1 i) = varBump n l1 (varSubst l2 b i)).\n\tintro.\n\tdestruct (lt_eq_lt_dec i l2);[destruct s |].\n\n\trewrite varSubstLt with (1 := l).\n\tdestruct (lt_dec i l1).\n\t\trewrite varBumpLo with (1 := l0).\n\t\tapply varSubstLt.\n\t\tapply le_trans with (1 := l).\n\t\tapply le_plus_r.\n\n\t\trewrite varBumpHi with (1 := n0).\n\t\tapply varSubstLt.\n\t\tapply plus_lt_compat_l with (1 := l).\n\n\trewrite varSubstEq with (1 := e).\n\trewrite e.\n\tclear i e.\n\trewrite varBumpHi with (1 := le_not_lt _ _ H).\n\trewrite varBumpHi;[| apply le_not_lt;apply le_trans with (1 := H);apply le_plus_l].\n\trewrite varSubstEq with (1 := eq_refl _).\n\trewrite <- plus_assoc.\n\treflexivity.\n\n\trewrite varSubstGt with (1 := l).\n\trewrite varBumpHi;[| apply le_not_lt;apply le_trans with (2 := l);apply le_S with (1 := H)].\n\trewrite varSubstGt with (1 := plus_lt_compat_l _ _ _ l).\n\tdestruct i.\n\t\tdestruct lt_n_O with (1 := l).\n\trewrite <- plus_n_Sm.\n\tsimpl.\n\trewrite varBumpHi.\n\t\treflexivity.\n\tapply le_not_lt.\n\texact (le_trans _ _ _ H (le_S_n _ _ l)).\nQed.\n\nLemma varSubstDiv n l1 l2 b i : (l1 <= l2 <= l1 + n)->(varSubst l2 b (varBump (S n) l1 i) = varBump n l1 i).\n\tintro.\n\tdestruct H.\n\tdestruct (lt_dec i l1).\n\n\trewrite varBumpLo with (1 := l).\n\trewrite varBumpLo with (1 := l).\n\tapply varSubstLt.\n\tapply le_trans with (1 := l) (2 := H).\n\n\trewrite varBumpHi with (1 := n0).\n\trewrite varBumpHi with (1 := n0).\n\tapply varSubstGt.\n\tsimpl.\n\tapply le_n_S.\n\tapply le_trans with (1 := H0).\n\trewrite <- plus_comm.\n\tapply plus_le_compat_l.\n\tapply not_lt with (1 := n0).\nQed.\n\nLemma varSubst_Subst x l b1 b2 i : varSubst (x + l) b1 (varSubst l b2 i) =\nvarSubst l (varSubst x b1 b2) (varSubst (S x + l) b1 i).\n\tdestruct (lt_eq_lt_dec i (S x + l));[destruct s |].\n\n\trewrite varSubstLt with (1 := l0).\n\tdestruct (lt_eq_lt_dec i l);[destruct s |].\n\t\trewrite varSubstLt with (1 := l1).\n\t\trewrite varSubstLt with (1 := l1).\n\t\tapply varSubstLt.\n\t\tapply le_trans with (1 := l1).\n\t\tapply le_plus_r.\n\n\t\trewrite varSubstEq with (1 := e).\n\t\trewrite varSubstEq with (1 := e).\n\t\tassert (forall k,varBump l O k = l + k).\n\t\t\tintro.\n\t\t\tapply varBumpHi.\n\t\t\tapply lt_n_O.\n\t\trewrite <- H.\n\t\trewrite <- plus_comm.\n\t\trewrite varSubst_Bump with (1 := le_O_n _).\n\t\tapply H.\n\n\t\trewrite varSubstGt with (1 := l1).\n\t\trewrite varSubstGt with (1 := l1).\n\t\tapply varSubstLt.\n\t\tdestruct i.\n\t\t\tdestruct lt_n_O with (1 := l1).\n\t\tsimpl in l0 |- *.\n\t\tapply lt_S_n with (1 := l0).\n\n\trewrite varSubstEq with (1 := e).\n\tsubst i.\n\trewrite varSubstGt with (l := l);[| simpl;apply le_n_S;apply le_plus_r].\n\trewrite varSubstGt with (l := l);[| simpl;apply le_n_S;rewrite <- plus_comm;rewrite plus_assoc;apply le_plus_r].\n\tsimpl.\n\tapply varSubstEq with (1 := eq_refl _).\n\n\trewrite varSubstGt with (1 := l0).\n\trewrite varSubstGt with (l := l);[| apply le_trans with (2 := l0);apply le_n_S;apply le_plus_r].\n\tdestruct i.\n\t\tdestruct lt_n_O with (1 := l0).\n\tsimpl in l0 |- *.\n\tpose proof (lt_S_n _ _ l0).\n\tclear l0.\n\trewrite varSubstGt with (1 := H).\n\trewrite varSubstGt with (l := l);[| apply le_trans with (2 := H);apply le_n_S;apply le_plus_r].\n\treflexivity.\nQed.\n", "meta": {"author": "GallagherCommaJack", "repo": "outrageous-interpreter", "sha": "5556e2aafe45f4efc73c3fb1f58b5d3e833fc617", "save_path": "github-repos/coq/GallagherCommaJack-outrageous-interpreter", "path": "github-repos/coq/GallagherCommaJack-outrageous-interpreter/outrageous-interpreter-5556e2aafe45f4efc73c3fb1f58b5d3e833fc617/SimpSubst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6558903642928837}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\nFrom Coq Require Import Omega.\n\nSection InductionExercises.\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.\nProof.\n  elim: n.\n  - by [].\n  - move=> n IHn //=.\n    rewrite IHn.\n    About mulnS.\n    rewrite mulnS.\n    move=>//=.\n    Undo.\n    done.\n\n  Restart.\n\n  by elim: n => //= n IHn; rewrite IHn mulnS.\n\n  Restart.\n\n  by elim: n=> //= n ->; rewrite mulnS.\nQed.\n\nLemma double_inj m n :\n  m + m = n + n -> m = n.\nProof.\n  elim: m n.\n  - rewrite addn0.\n    case.\n    + rewrite add0n. done.\n    + move=> n. rewrite addSn addnS. by [].\n    move=> n IHn m.\n    rewrite addnS addSn.\n    case: m.\n    + rewrite add0n. by [].\n    move=> m.\n    rewrite !addnS !addSn.\n    case.\n    move/IHn.\n    Search _ (?n = ?m -> ?n.+1 = ?m.+1).\n    About eq_S.\n    apply: eq_S.\nQed.\n\n(** Write a tail-recursive variation of the [addn] function\n    (let's call it [addn_iter]). *)\nFixpoint add_iter (n m : nat) {struct n}: nat :=\n  if n is n'.+1 then S (add_iter n' m)\n  else m.\n\nLemma add_iter_correct m n :\n  add_iter m n = m + n.\nProof.\n  move: n.\n  elim.\n  Restart.\n  by elim/nat_ind: n.\n  Restart.\n  by move: n; elim.\nQed.\n\nFixpoint fib (n : nat) : nat :=\n  if n is (n''.+1 as n').+1 then fib n'' + fib n'\n  else n.\nArguments fib n : simpl nomatch.\n\nLemma leq_add1l p m n :\n  m <= n -> m <= p + n.\nProof.\n  (* Search _ ((is_true (?m <= ?n)) -> (is_true (?n <= ?p)) -> (is_true (?m <= ?p))). *)\n  (* Search _ ((?m <= ?n) -> _). *)\n\n  (* leq_trans      forall n m p : nat, m <= n -> n <= p -> m <= p *)\n  (* leq_ltn_trans  forall n m p : nat, m <= n -> n < p -> m < p *)\n\n  (* leq_sub2r  forall p m n : nat, m <= n -> m - p <= n - p *)\n  (* addnBA     forall m n p : nat, p <= n -> m + (n - p) = m + n - p *)\n  (* addnBAC    forall m n p : nat, n <= m -> m - n + p = m + p - n *)\n  (* addnBCA    forall m n p : nat, p <= m -> p <= n -> m + (n - p) = n + (m - p) *)\n  (* addnABC    forall m n p : nat, p <= m -> p <= n -> m + (n - p) = m - p + n *)\n  (* subnBA     forall m n p : nat, p <= n -> m - (n - p) = m + p - n *)\n\n  move=> H.\nAdmitted.\n\nLemma fib_monotone m n :\n  m <= n -> fib m <= fib n.\nProof.\nAdmitted.\n\nLemma fib_add_succ m n :\n  fib (m + n).+1 = fib m.+1 * fib n.+1 + fib m * fib n.\nAdmitted.\n\nEnd InductionExercises.\n\n\n\n(* Thanks to Mike Potanin for pointing me to this example *)\n(* https://en.wikipedia.org/wiki/Eckmann–Hilton_argument *)\n\nSection EckmannHilton.\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\nLemma units_same :\n  e1 = e2.\nAdmitted.\n\nLemma operations_equal :\n  f1 =2 f2.\nAdmitted.\n\nLemma I1 : interchange f1 f1.\nAdmitted.\n\nLemma operations_comm :\n  commutative f1.\nAdmitted.\n\nLemma operations_assoc :\n  associative f1.\nAdmitted.\n\nEnd EckmannHilton.\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/seminar04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6558903499208122}}
{"text": "Require Export XR_R.\nRequire Export XR_Rle.\nRequire Export XR_Rlt_trans.\n\nImplicit Type r : R.\nLocal Open Scope R_scope.\n\nLemma Rle_lt_trans : forall r1 r2 r3, r1 <= r2 -> r2 < r3 -> r1 < r3.\nProof.\n  intros x y z.\n  intros hxy hyz.\n  unfold \"<=\" in hxy.\n  destruct hxy as [ hxy | heq ].\n  {\n    apply Rlt_trans with y.\n    { exact hxy. }\n    { exact hyz. }\n  }\n  {\n    subst y.\n    exact hyz.\n  }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rle_lt_trans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6558332989837192}}
{"text": "(* A simple test on how to extract code from something written in coq *)\nSection square_root.\nRequire Import Compare_dec.\n\n(* define the search of some nat with the prop n*n <= m -> n is square of m *)\nFixpoint square_root (n:nat) (m:nat): nat :=\n  if le_lt_dec (n*n) m then\n  if le_lt_dec (S n * S n) m then S n else n\n  else\n    match n with\n    | 0 => 0\n    | 1 => 1\n    | (S (S n')) => square_root n' m\n    end.\n\n(* define some handy call *)\nDefinition square (n:nat) : nat := square_root n n.\n\n(* test some examples which get not extracted *)\nCompute (square 0).\nCompute (square 1).\nCompute (square 4).\nCompute (square 16).\nCompute (square 6).\nCompute (square 250).\nCompute (square 400).\nCompute (square 600).\n\nEnd square_root.\n\n\nRequire Extraction.\nExtraction Language Ocaml.\nSet Extraction AccessOpaque.\n\n(* extract the specs *)\nExtraction \"square_root.ml\" square.\n(* also generates some interface file mli with the type definitions *)", "meta": {"author": "santifa", "repo": "masterarbeit", "sha": "088210e071464831d3e496d3a8faac0aac494228", "save_path": "github-repos/coq/santifa-masterarbeit", "path": "github-repos/coq/santifa-masterarbeit/masterarbeit-088210e071464831d3e496d3a8faac0aac494228/learn-coq/extraction/square_root.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6558332922818308}}
{"text": "(* week-03_induction-over-binary-trees.v *)\n(* FPP 2020 - YSC3236 2020-2021, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 27 Aug 2020 *)\n\n(* Your name: Koo Zhengqun\n   Your e-mail address: zhengqun.koo@u.nus.edu\n   Your student number: A0164207L\n *)\n\n(* Your name: Bobbie Soedirgo\n   Your e-mail address: sram-b@comp.nus.edu.sg\n   Your student number: A0181001A\n *)\n\n(* Your name: Kuan Wei Heng\n   Your e-mail address: kuanwh@u.nus.edu\n   Your student number: A0121712X\n *)\n\n(* ********** *)\n\nInductive binary_tree (V : Type) : Type :=\n| Leaf : V -> binary_tree V\n| Node : binary_tree V -> binary_tree V -> binary_tree V.\n\n(* ********** *)\n\nDefinition specification_of_mirror (mirror : forall V : Type, binary_tree V -> binary_tree V) : Prop :=\n  (forall (V : Type)\n          (v : V),\n      mirror V (Leaf V v) =\n      Leaf V v)\n  /\\\n  (forall (V : Type)\n          (t1 t2 : binary_tree V),\n      mirror V (Node V t1 t2) =\n      Node V (mirror V t2) (mirror V t1)).\n\n(* ***** *)\n\n(* Exercise 9a *)\n\n(** This proof goes mostly the same way as the one for relative number of leaves and nodes in the lecture notes. We induct on [t] and apply the hypotheses in the inductive case. We also destruct within the cases to keep the assumptions clean.\n\n    We show that the specification of the mirror function is indeed unambiguous, as proven below:\n *)\nProposition there_is_at_most_one_mirror_function :\n  forall mirror1 mirror2 : forall V : Type, binary_tree V -> binary_tree V,\n    specification_of_mirror mirror1 ->\n    specification_of_mirror mirror2 ->\n    forall (V : Type)\n           (t : binary_tree V),\n      mirror1 V t = mirror2 V t.\nProof.\n  intros mirror1 mirror2.\n  intros S_mirror1 S_mirror2.\n  intros V t.\n  induction t as [ v | t1 IHt1 t2 IHt2 ].\n  - unfold specification_of_mirror in S_mirror1.\n    destruct S_mirror1 as [S_Leaf1 _].\n    unfold specification_of_mirror in S_mirror2.\n    destruct S_mirror2 as [S_Leaf2 _].\n    rewrite -> (S_Leaf2 V v).\n    exact (S_Leaf1 V v).\n  - unfold specification_of_mirror in S_mirror1.\n    destruct S_mirror1 as [_ S_Node1].\n    unfold specification_of_mirror in S_mirror2.\n    destruct S_mirror2 as [_ S_Node2].\n    (** Here we can do forward rewrites and end it with [reflexivity], or we can do it slightly differently and save one proof step:\n     *)\n    (*\n    rewrite -> (S_Node1 V t1 t2).\n    rewrite -> (S_Node2 V t1 t2).\n    rewrite -> IHt1.\n    rewrite -> IHt2.\n    reflexivity.\n     *)\n    rewrite -> (S_Node2 V t1 t2).\n    rewrite <- IHt1.\n    rewrite <- IHt2.\n    exact (S_Node1 V t1 t2).\nQed.\n\n(* ********** *)\n\nDefinition specification_of_number_of_leaves (number_of_leaves : forall V : Type, binary_tree V -> nat) : Prop :=\n  (forall (V : Type)\n          (v : V),\n      number_of_leaves V (Leaf V v) =\n      1)\n  /\\\n  (forall (V : Type)\n          (t1 t2 : binary_tree V),\n      number_of_leaves V (Node V t1 t2) =\n      number_of_leaves V t1 + number_of_leaves V t2).\n\n(* Exercise 9b *)\n\n(** The other two works exactly the same as 9a, modulo the specifications and the names involved. We also reach the same conclusion: the specifications are unambiguous.\n *)\nProposition there_is_at_most_one_number_of_leaves_function :\n  forall nol1 nol2 : forall V : Type, binary_tree V -> nat,\n    specification_of_number_of_leaves nol1 ->\n    specification_of_number_of_leaves nol2 ->\n    forall (V : Type)\n           (t : binary_tree V),\n      nol1 V t = nol2 V t.\nProof.\n  intros nol1 nol2.\n  intros S_nol1 S_nol2.\n  intros V t.\n  induction t as [ v | t1 IHt1 t2 IHt2 ].\n  - unfold specification_of_number_of_leaves in S_nol1.\n    destruct S_nol1 as [S_Leaf1 _].\n    unfold specification_of_number_of_leaves in S_nol2.\n    destruct S_nol2 as [S_Leaf2 _].\n    rewrite -> (S_Leaf2 V v).\n    exact (S_Leaf1 V v).\n  - unfold specification_of_number_of_leaves in S_nol1.\n    destruct S_nol1 as [_ S_Node1].\n    unfold specification_of_number_of_leaves in S_nol2.\n    destruct S_nol2 as [_ S_Node2].\n    rewrite -> (S_Node2 V t1 t2).\n    rewrite <- IHt1.\n    rewrite <- IHt2.\n    exact (S_Node1 V t1 t2).\nQed.\n\nDefinition specification_of_number_of_nodes (number_of_nodes : forall V : Type, binary_tree V -> nat) : Prop :=\n  (forall (V : Type)\n          (v : V),\n      number_of_nodes V (Leaf V v) =\n      0)\n  /\\\n  (forall (V : Type)\n          (t1 t2 : binary_tree V),\n      number_of_nodes V (Node V t1 t2) =\n      S (number_of_nodes V t1 + number_of_nodes V t2)).\n\n(* Exercise 9c *)\n\nProposition there_is_at_most_one_number_of_nodes_function :\n  forall non1 non2 : forall V : Type, binary_tree V -> nat,\n    specification_of_number_of_nodes non1 ->\n    specification_of_number_of_nodes non2 ->\n    forall (V : Type)\n           (t : binary_tree V),\n      non1 V t = non2 V t.\nProof.\n  intros non1 non2.\n  intros S_non1 S_non2.\n  intros V t.\n  induction t as [ v | t1 IHt1 t2 IHt2 ].\n  - unfold specification_of_number_of_nodes in S_non1.\n    destruct S_non1 as [S_Leaf1 _].\n    unfold specification_of_number_of_nodes in S_non2.\n    destruct S_non2 as [S_Leaf2 _].\n    rewrite -> (S_Leaf2 V v).\n    exact (S_Leaf1 V v).\n  - unfold specification_of_number_of_nodes in S_non1.\n    destruct S_non1 as [_ S_Node1].\n    unfold specification_of_number_of_nodes in S_non2.\n    destruct S_non2 as [_ S_Node2].\n    rewrite -> (S_Node2 V t1 t2).\n    rewrite <- IHt1.\n    rewrite <- IHt2.\n    exact (S_Node1 V t1 t2).\nQed.\n\n(* ********** *)\n\n(* end of week-03_induction-over-binary-trees.v *)\n", "meta": {"author": "soedirgo", "repo": "fpp", "sha": "5a43df151c5c8bc3f49d449ffd6f3eac67a16eab", "save_path": "github-repos/coq/soedirgo-fpp", "path": "github-repos/coq/soedirgo-fpp/fpp-5a43df151c5c8bc3f49d449ffd6f3eac67a16eab/w03/week-03_induction-over-binary-trees.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.6558332905313977}}
{"text": "From Coq Require Import Arith.Arith.\nFrom Coq Require Import Bool.Bool.\nFrom Coq Require Import Arith.PeanoNat.\nFrom Coq Require Import micromega.Lia.\nFrom Coq Require Import Lists.List.\nFrom Coq Require Import Reals.Reals. Import Rdefinitions. Import RIneq.\nFrom Coq Require Import ZArith.Int. Import Znat.\nFrom Coq Require Import Setoids.Setoid.\nFrom Coq Require Import Logic.FunctionalExtensionality.\nRequire Coq.derive.Derive.\nImport ListNotations.\n\nFrom ATL Require Import ATL Common CommonTactics Tactics GenPushout LetLifting.\n\nDefinition im2colmini K W RR (w : (list (list R))) (x : list R) :=\n    GEN [ k < K ]\n      GEN [ p < W ]\n        SUM [ r < RR ]\n        |[ p + r <? K ]| (w _[ k ; r ] * x _[ p + r ])%R.\n\nDefinition im2col B K W C RR (w x : (list (list (list R)))) :=\n    GEN [ n < B ]\n    GEN [ k < K ]\n    GEN [ p < W ]\n    SUM [ c < C ]\n    SUM [ r < RR ]\n    (w _[ k ; c ; r ] * x _[ n ; c ; p + r ])%R.\n\nHint Unfold im2col im2colmini : examples.  \n\nSection Mini.\n  Variables (K W RR : Z) (w : (list (list R))) (x : list R).\n  Derive im2colminilifted SuchThat\n     ((0 < RR)%Z ->\n     im2colmini K W RR w x = im2colminilifted) As miniim2col.         \n  Proof.\n    reschedule.\n\n    setoid_rewrite <- guard_mul_r.\n\n    rw^ @lbind_helper for (fun e => _ * e)%R.\n\n    time rw ll_sum.\n\n    rw @ll_gen.\n\n    rw @ll_gen_indep.\n\n    done.\n  Defined.\nEnd Mini.\n\nSection Im2col.\n  Variables (B K W C RR : Z) (w x : (list (list (list R)))).\n  Derive im2col_lifted SuchThat\n         (im2col B K W C RR w x =\n          im2col_lifted) As im2col_sched.\n  Proof.\n    reschedule.\n\n    rw^ @lbind_helper for (fun e => _ * e)%R.\n\n    rw @ll_sum.\n\n    rw @ll_sum.\n\n    rw @ll_gen.\n    \n    rw @ll_gen_indep.\n\n    rw @ll_gen.\n\n    done.    \n  Qed.\nEnd Im2col.\n\nHint Unfold im2col_lifted im2colminilifted : examples.  \n\nGoal forall B K W C RR w x,\n    im2col_lifted B K W C RR w x =\n    tlet x0\n  := GEN [ i < B ]\n         GEN [ i0 < W ]\n         GEN [ i1 < C ]\n         GEN [ i2 < RR ]\n         x _[ i; i1; i0 + i2]\n    in GEN [ n' < B ]\n           GEN [ n'0 < K ]\n           GEN [ n'1 < W ]\n           SUM [ n'2 < C ]\n           SUM [ n'3 < RR ]\n           (w _[ n'0; n'2; n'3] * x0 _[ n'; n'1; n'2; n'3])%R.\nProof. reflexivity. Qed.\n    \nGoal forall K W RR w x,\n    im2colminilifted K W RR w x =\n    tlet x0 := GEN [ i < W ]\n                   GEN [ i0 < RR ]\n                   (|[ i + i0 <? K ]| x _[ i + i0])\n    in GEN [ n' < K ]\n           GEN [ n'0 < W ]\n           SUM [ n'1 < RR ]\n           (w _[ n'; n'1] * x0 _[ n'0; n'1])%R.\nProof. reflexivity. Qed.\n    \n", "meta": {"author": "ChezJrk", "repo": "verified-scheduling", "sha": "e9876602147114e4378f10ac1402bd5705c0cef0", "save_path": "github-repos/coq/ChezJrk-verified-scheduling", "path": "github-repos/coq/ChezJrk-verified-scheduling/verified-scheduling-e9876602147114e4378f10ac1402bd5705c0cef0/src/Im2col.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.7341195385342972, "lm_q1q2_score": 0.6557958972817117}}
{"text": "Require Import GeoCoq.Axioms.parallel_postulates.\nRequire Import GeoCoq.Tarski_dev.Ch12_parallel.\n\nSection playfair_alternate_interior_angles.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma playfair__alternate_interior :  playfair_s_postulate -> alternate_interior_angles_postulate.\nProof.\nintros playfair A B C D Hts HPar.\nassert(~ Col B A C) by (destruct Hts; auto).\nassert(HD' := ex_conga_ts B A C A C B).\ndestruct HD' as [D' []]; Col.\napply (conga_trans _ _ _ D' C A).\nCongA.\nassert_diffs.\napply out2__conga; [|apply out_trivial; auto].\napply (col_one_side_out _ A).\nassert (HP := playfair A B C D C D' C).\ndestruct HP; Col.\napply l12_21_b; CongA; Side.\napply invert_one_side; exists B; split; Side.\nQed.\n\nEnd playfair_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/playfair_alternate_interior_angles.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.6557958920852799}}
{"text": "Set Implicit Arguments.\nRequire Import Lia List.\nFrom Undecidability.HOU Require Import std.lists.basics std.misc std.decidable.\nImport ListNotations.\n\nSection Reductions.\n\n  Variable (X Y Z: Type).\n  Implicit Types (P: X -> Prop) (Q: Y -> Prop) (R: Z -> Prop).\n\n  Definition reduction {X Y: Type} (P: X -> Prop) (Q: Y -> Prop) :=\n    exists f, forall x, P x <-> Q (f x).\n  \n  Notation \"P ⪯ Q\" := (reduction P Q) (at level 60).\n  \n  Lemma reduction_transitive P Q R:\n    P ⪯ Q -> Q ⪯ R -> P ⪯ R.\n  Proof.\n    intros [f H1] [g H2]; exists (f >> g).\n    intros x; rewrite H1, H2. reflexivity.\n  Qed.\n  \n  Lemma reduction_reflexive P: P ⪯ P.\n  Proof.\n    exists id; reflexivity.\n  Qed.\n\n\nEnd Reductions.\n\n#[export] Hint Resolve reduction_reflexive reduction_transitive : core.\nNotation \"P ⪯ Q\" := (reduction P Q) (at level 60).\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/HOU/std/reductions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6557921506418969}}
{"text": "Require Import rt.util.all.\nRequire Import rt.model.arrival.basic.task rt.model.arrival.basic.job rt.model.arrival.basic.arrival_sequence.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq.\n\n(* Definitions of FP, JLFP and JLDP priority relations. *)\nModule Priority.\n\n  Import SporadicTaskset ArrivalSequence.\n\n  Section PriorityDefs.\n\n    Variable Task: eqType.\n    Variable Job: eqType.\n    \n    (* We define an FP policy as a relation between tasks, ... *)\n    Definition FP_policy := rel Task.\n\n    (* ...JLFP policy as a relation between jobs, ... *)\n    Definition JLFP_policy := rel Job.\n\n    (* ...and JLDP as any time-dependent relation between jobs. *)\n    Definition JLDP_policy := time -> rel Job.\n\n  End PriorityDefs.\n\n  (* Since FP policies are also JLFP and JLDP policies, we define\n     next conversion functions to do the generalization. *)\n  Section Generalization.\n\n    (* Consider any arrival sequence of jobs spawned by tasks. *)\n    Context {Task: eqType}.\n    Context {Job: eqType}.\n    Variable job_task: Job -> Task.\n\n    (* We show how to convert FP to JLFP,... *)\n    Definition FP_to_JLFP (task_hp: FP_policy Task) :=\n      fun (jhigh jlow: Job) =>\n        task_hp (job_task jhigh) (job_task jlow).\n    \n    (* ...FP to JLDP, ... *)\n    Definition FP_to_JLDP (task_hp: FP_policy Task) :=\n      fun (t: time) => FP_to_JLFP task_hp.\n\n    (* ...and JLFP to JLDP. *)\n    Definition JLFP_to_JLDP (job_hp: JLFP_policy Job) :=\n      fun (t: time) => job_hp.\n    \n  End Generalization.\n\n  (* Next we define properties of an FP policy. *)\n  Section PropertiesFP.\n\n    (* Assume that jobs are spawned by tasks. *)\n    Context {Job: eqType}.\n    Context {Task: eqType}.\n    Variable job_task: Job -> Task.\n\n    (* Let task_priority be any FP policy. *)\n    Variable task_priority: FP_policy Task.\n\n    (* Now we define the properties. *)\n    \n    (* Whether the FP policy is reflexive. *)\n    Definition FP_is_reflexive := reflexive task_priority.\n\n    (* Whether the FP policy is irreflexive. *)\n    Definition FP_is_irreflexive := irreflexive task_priority.\n\n    (* Whether the FP policy is transitive. *)\n    Definition FP_is_transitive := transitive task_priority.\n    \n    Section Antisymmetry.\n\n      (* Consider any task set ts. *)\n      Variable ts: seq Task.\n\n      (* First we define whether task set ts is totally ordered with\n         the priority. *)\n      Definition FP_is_total_over_task_set :=\n        total_over_list task_priority ts. \n      \n      (* Then we define whether an FP policy is antisymmetric over task set ts, i.e.,\n         whether the task set has unique priorities. *)\n      Definition FP_is_antisymmetric_over_task_set :=\n        antisymmetric_over_list task_priority ts. \n                  \n    End Antisymmetry.\n\n  End PropertiesFP. \n    \n  (* Next, we define properties of a JLFP policy. *)\n  Section PropertiesJLFP.\n\n    (* Consider any JLFP policy. *)\n    Context {Job: eqType}.\n    Variable arr_seq: arrival_sequence Job.\n\n    Variable job_priority: JLFP_policy Job.\n\n    (* Now we define the properties. *)\n    \n    (* Whether the JLFP policy is reflexive. *)\n    Definition JLFP_is_reflexive := reflexive job_priority.\n\n    (* Whether the JLFP policy is irreflexive. *)\n    Definition JLFP_is_irreflexive := irreflexive job_priority.\n\n    (* Whether the JLFP policy is transitive. *)\n    Definition JLFP_is_transitive := transitive job_priority.\n\n    (* Whether the JLFP policy is total over the arrival sequence. *)\n    Definition JLFP_is_total :=\n      forall j1 j2,\n        arrives_in arr_seq j1 ->\n        arrives_in arr_seq j2 ->\n        job_priority j1 j2 || job_priority j2 j1.\n\n  End PropertiesJLFP.\n\n  (* Next, we define properties of a JLDP policy. *)\n  Section PropertiesJLDP.\n\n    (* Consider any JLDP policy. *)\n    Context {Job: eqType}.\n    Variable arr_seq: arrival_sequence Job.\n    \n    Variable job_priority: JLDP_policy Job.\n\n    (* Now we define the properties. *)\n    \n    (* Whether the JLDP policy is reflexive. *)\n    Definition JLDP_is_reflexive :=\n      forall t, reflexive (job_priority t).\n\n    (* Whether the JLDP policy is irreflexive. *)\n    Definition JLDP_is_irreflexive :=\n      forall t, irreflexive (job_priority t).\n\n    (* Whether the JLDP policy is transitive. *)\n    Definition JLDP_is_transitive :=\n      forall t, transitive (job_priority t).\n\n    (* Whether the JLDP policy is total. *)\n    Definition JLDP_is_total :=\n      forall j1 j2 t,\n        arrives_in arr_seq j1 ->\n        arrives_in arr_seq j2 ->\n        job_priority t j1 j2 || job_priority t j2 j1.\n\n  End PropertiesJLDP.\n\n  (* Next we define some known FP policies. *)\n  Section KnownFPPolicies.\n\n    Context {Job: eqType}.\n    Context {Task: eqType}.\n    Variable task_period: Task -> time.\n    Variable task_deadline: Task -> time.\n    Variable job_task: Job -> Task.\n    \n    (* Rate-monotonic orders tasks by smaller periods. *)\n    Definition RM (tsk1 tsk2: Task) :=\n      task_period tsk1 <= task_period tsk2.\n\n    (* Deadline-monotonic orders tasks by smaller relative deadlines. *)\n    Definition DM (tsk1 tsk2: Task) :=\n      task_deadline tsk1 <= task_deadline tsk2.\n\n    Section Properties.\n\n      (* RM is reflexive. *)\n      Lemma RM_is_reflexive : FP_is_reflexive RM.\n      Proof.\n        unfold FP_is_reflexive, reflexive, RM.\n        by intros tsk; apply leqnn.\n      Qed.\n\n      (* RM is transitive. *)\n      Lemma RM_is_transitive : FP_is_transitive RM.\n      Proof.\n        unfold FP_is_transitive, transitive, RM.\n        by intros y x z; apply leq_trans.\n      Qed.\n\n      (* DM is reflexive. *)\n      Lemma DM_is_reflexive : FP_is_reflexive DM.\n      Proof.\n        unfold FP_is_reflexive, reflexive, DM.\n        by intros tsk; apply leqnn.\n      Qed.\n\n      (* DM is transitive. *)\n      Lemma DM_is_transitive : FP_is_transitive DM.\n      Proof.\n        unfold FP_is_transitive, transitive, DM.\n        by intros y x z; apply leq_trans.\n      Qed.\n\n    End Properties.\n\n  End KnownFPPolicies.\n\n  (* In this section, we define known JLFP policies. *)\n  Section KnownJLFPPolicies.\n\n    Context {Job: eqType}.\n    Variable job_arrival: Job -> time.\n    Variable job_deadline: Job -> time.\n\n    Variable arr_seq: arrival_sequence Job.\n\n    (* We define earliest deadline first (EDF) as ordering jobs by absolute deadlines. *)\n    Definition EDF (j1 j2: Job) :=\n      job_arrival j1 + job_deadline j1 <= job_arrival j2 + job_deadline j2.\n\n    Section Properties.\n      \n      (* EDF is reflexive. *)\n      Lemma EDF_is_reflexive : JLFP_is_reflexive EDF.\n      Proof.\n        by intros j; apply leqnn.\n      Qed.\n\n      (* EDF is transitive. *)\n      Lemma EDF_is_transitive : JLFP_is_transitive EDF.\n      Proof.\n        by intros y x z; apply leq_trans.\n      Qed.\n\n      (* EDF is total. *)\n      Lemma EDF_is_total : JLFP_is_total arr_seq EDF.\n      Proof.\n        unfold EDF; intros x y ARRx ARRy.\n        case (leqP (job_arrival x + job_deadline x)\n                    (job_arrival y + job_deadline y));\n          [by rewrite orTb | by move/ltnW => ->].\n      Qed.\n\n    End Properties.\n\n  End KnownJLFPPolicies.\n\n  (* In this section, we define the notion of a possible interfering task. *)\n  Section PossibleInterferingTasks.\n\n    Context {sporadic_task: eqType}.\n    Variable task_cost: sporadic_task -> time.\n    Variable task_period: sporadic_task -> time.\n    Variable task_deadline: sporadic_task -> time.\n\n    Section FP.\n\n      (* Assume an FP policy. *)\n      Variable higher_eq_priority: FP_policy sporadic_task.\n\n      (* Let tsk be the task to be analyzed ... *)\n      Variable tsk: sporadic_task.\n\n      (* ...and let tsk_other be another task. *)\n      Variable tsk_other: sporadic_task.\n\n      (* Under FP scheduling with constrained deadlines, tsk_other can only interfere\n         with tsk if it is a different task with higher priority. *)\n      Definition higher_priority_task :=\n        higher_eq_priority tsk_other tsk &&\n        (tsk_other != tsk).\n\n    End FP.\n\n    Section JLFP.\n\n      (* Let tsk be the task to be analyzed ... *)\n      Variable tsk: sporadic_task.\n\n      (* ...and let tsk_other be another task. *)\n      Variable tsk_other: sporadic_task.\n\n      (* Under JLFP/JLDP scheduling with constrained deadlines, tsk_other can only interfere\n         with tsk if it is a different task. *)\n      Definition different_task := tsk_other != tsk.\n\n    End JLFP.\n    \n  End PossibleInterferingTasks.  \n\nEnd Priority.", "meta": {"author": "cd-public", "repo": "rt-proofs", "sha": "ebef0b65460fe009c51f638fe2b459f16a6d1dd5", "save_path": "github-repos/coq/cd-public-rt-proofs", "path": "github-repos/coq/cd-public-rt-proofs/rt-proofs-ebef0b65460fe009c51f638fe2b459f16a6d1dd5/model/priority.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6557921433244941}}
{"text": "Require Import Coq.Logic.Classical_Prop.\nRequire Import Logic.lib.Ensembles_ext.\nRequire Import Logic.GeneralLogic.Base.\nRequire Import Logic.MinimumLogic.Syntax.\nRequire Import Logic.MinimumLogic.Semantics.Trivial.\n\nLocal Open Scope logic_base.\nLocal Open Scope syntax.\n\nSection Sound.\n\nContext {L: Language}\n        {minL: MinimumLanguage L}\n        {MD: Model}\n        {SM: Semantics L MD}\n        {tminSM: TrivialMinimumSemantics L MD SM}.\n\nLemma sound_modus_ponens:\n  forall x y m,\n    m |= (x --> y) -> m |= x -> m |= y.\nProof.\n  intros.\n  rewrite sat_impp in H.\n  apply H; auto.\nQed.\n\nLemma sound_axiom1:\n  forall x y m,\n    m |= x --> y --> x.\nProof.\n  intros.\n  rewrite !sat_impp.\n  intros ? ?; auto.\nQed.\n\nLemma sound_axiom2:\n  forall x y z m,\n    m |= (x --> y --> z) --> (x --> y) --> (x --> z).\nProof.\n  intros.\n  rewrite !sat_impp.\n  intros ? ? ?.\n  specialize (H H1).\n  specialize (H0 H1).\n  auto.\nQed.\n\nEnd Sound.\n", "meta": {"author": "QinxiangCao", "repo": "UnifySL", "sha": "cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d", "save_path": "github-repos/coq/QinxiangCao-UnifySL", "path": "github-repos/coq/QinxiangCao-UnifySL/UnifySL-cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d/MinimumLogic/Sound/Sound_Classical_Trivial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6557887833551622}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\nRequire Import mathcomp.ssreflect.ssrbool.\nRequire Import mathcomp.ssreflect.eqtype.\nRequire Import mathcomp.ssreflect.ssrnat.\n\nLemma foo : forall n: nat, n + 0 = n.\nProof.\n  intros.\n  induction n.\n  do 2 (try (move => n)).\n  reflexivity.\n  done.\nQed.", "meta": {"author": "ml4tp", "repo": "gamepad", "sha": "7092f50a96eae9a862e72ecb8a55a217fa97723c", "save_path": "github-repos/coq/ml4tp-gamepad", "path": "github-repos/coq/ml4tp-gamepad/gamepad-7092f50a96eae9a862e72ecb8a55a217fa97723c/examples/do.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6557542902489859}}
{"text": "\nDefinition choice A B :=\n  forall (R:A->B->Prop),\n  (forall x:A, exists y:B, R x y) ->\n  exists f:A->B, forall x:A, R x (f x).\n\nAxiom choice_axiom : forall A B, choice A B.\n\nDefinition unique_choice A B (E:B->B->Prop) :=\n  forall (R:A->B->Prop),\n  (forall x:A, exists y:B, R x y) ->\n  (forall x y y', R x y -> (R x y' <-> E y y')) ->\n  exists f:A->B, forall x:A, R x (f x).\n", "meta": {"author": "barras", "repo": "cic-model", "sha": "dcc38f3104048aa50d230f819085131b16702d3d", "save_path": "github-repos/coq/barras-cic-model", "path": "github-repos/coq/barras-cic-model/cic-model-dcc38f3104048aa50d230f819085131b16702d3d/Choice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6557542888123385}}
{"text": "\nTheorem eq_trans : forall (A:Set) (a b c:A), a = b -> b = c -> a = c.\nProof.\n intros A a b c H.\n pattern b.\n apply eq_ind with A a.\n trivial.\n assumption.\nQed.\n\nTheorem eq_trans' : forall (A:Set) (a b c:A), a = b -> b = c -> a = c.\nProof.\n intros A a b c H; rewrite H.\n trivial.\nQed.\n\n\nTheorem eq_trans'' : forall (A:Set) (a b c:A), a = b -> b = c -> a = c.\nProof.\n intros A a b c H H0.\n rewrite H; assumption.\nQed.\n\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/depprod/SRC/eq_trans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6557542778452343}}
{"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).\nEval compute in (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\nProof. simpl. reflexivity. Qed.\n\nCheck next_weekday.", "meta": {"author": "nimishgupta", "repo": "CPDT", "sha": "ce92051b376041833f06327705cf9e5586a3d94c", "save_path": "github-repos/coq/nimishgupta-CPDT", "path": "github-repos/coq/nimishgupta-CPDT/CPDT-ce92051b376041833f06327705cf9e5586a3d94c/Coq/first_program.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.6556700535702353}}
{"text": "(* -*- coding: utf-8 -*- *)\n(************************************************************************)\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: Pnat.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\nRequire Import BinPos.\n\n(**********************************************************************)\n(** Properties of the injection from binary positive numbers to Peano\n    natural numbers *)\n\n(** Original development by Pierre Crégut, CNET, Lannion, France *)\n\nRequire Import Le.\nRequire Import Lt.\nRequire Import Gt.\nRequire Import Plus.\nRequire Import Mult.\nRequire Import Minus.\nRequire Import Compare_dec.\n\nLocal Open Scope positive_scope.\nLocal Open Scope nat_scope.\n\n(** [nat_of_P] is a morphism for addition *)\n\nLemma Pmult_nat_succ_morphism :\n forall (p:positive) (n:nat), Pmult_nat (Psucc p) n = n + Pmult_nat p n.\nProof.\nintro x; induction x as [p IHp| p IHp| ]; simpl in |- *; auto; intro m;\n rewrite IHp; rewrite plus_assoc; trivial.\nQed.\n\nLemma nat_of_P_succ_morphism :\n forall p:positive, nat_of_P (Psucc p) = S (nat_of_P p).\nProof.\n  intro; change (S (nat_of_P p)) with (1 + nat_of_P p) in |- *;\n   unfold nat_of_P in |- *; apply Pmult_nat_succ_morphism.\nQed.\n\nTheorem Pmult_nat_plus_carry_morphism :\n forall (p q:positive) (n:nat),\n   Pmult_nat (Pplus_carry p q) n = n + Pmult_nat (p + q) n.\nProof.\nintro x; induction x as [p IHp| p IHp| ]; intro y;\n [ destruct y as [p0| p0| ]\n | destruct y as [p0| p0| ]\n | destruct y as [p| p| ] ]; simpl in |- *; auto with arith;\n intro m;\n [ rewrite IHp; rewrite plus_assoc; trivial with arith\n | rewrite IHp; rewrite plus_assoc; trivial with arith\n | rewrite Pmult_nat_succ_morphism; rewrite plus_assoc; trivial with arith\n | rewrite Pmult_nat_succ_morphism; apply plus_assoc_reverse ].\nQed.\n\nTheorem nat_of_P_plus_carry_morphism :\n forall p q:positive, nat_of_P (Pplus_carry p q) = S (nat_of_P (p + q)).\nProof.\nintros; unfold nat_of_P in |- *; rewrite Pmult_nat_plus_carry_morphism;\n simpl in |- *; trivial with arith.\nQed.\n\nTheorem Pmult_nat_l_plus_morphism :\n forall (p q:positive) (n:nat),\n   Pmult_nat (p + q) n = Pmult_nat p n + Pmult_nat q n.\nProof.\nintro x; induction x as [p IHp| p IHp| ]; intro y;\n [ destruct y as [p0| p0| ]\n | destruct y as [p0| p0| ]\n | destruct y as [p| p| ] ]; simpl in |- *; auto with arith;\n [ intros m; rewrite Pmult_nat_plus_carry_morphism; rewrite IHp;\n    rewrite plus_assoc_reverse; rewrite plus_assoc_reverse;\n    rewrite (plus_permute m (Pmult_nat p (m + m)));\n    trivial with arith\n | intros m; rewrite IHp; apply plus_assoc\n | intros m; rewrite Pmult_nat_succ_morphism;\n    rewrite (plus_comm (m + Pmult_nat p (m + m)));\n    apply plus_assoc_reverse\n | intros m; rewrite IHp; apply plus_permute\n | intros m; rewrite Pmult_nat_succ_morphism; apply plus_assoc_reverse ].\nQed.\n\nTheorem nat_of_P_plus_morphism :\n forall p q:positive, nat_of_P (p + q) = nat_of_P p + nat_of_P q.\nProof.\nintros x y; exact (Pmult_nat_l_plus_morphism x y 1).\nQed.\n\n(** [Pmult_nat] is a morphism for addition *)\n\nLemma Pmult_nat_r_plus_morphism :\n forall (p:positive) (n:nat),\n   Pmult_nat p (n + n) = Pmult_nat p n + Pmult_nat p n.\nProof.\nintro y; induction y as [p H| p H| ]; intro m;\n [ simpl in |- *; rewrite H; rewrite plus_assoc_reverse;\n    rewrite (plus_permute m (Pmult_nat p (m + m)));\n    rewrite plus_assoc_reverse; auto with arith\n | simpl in |- *; rewrite H; auto with arith\n | simpl in |- *; trivial with arith ].\nQed.\n\nLemma ZL6 : forall p:positive, Pmult_nat p 2 = nat_of_P p + nat_of_P p.\nProof.\nintro p; change 2 with (1 + 1) in |- *; rewrite Pmult_nat_r_plus_morphism;\n trivial.\nQed.\n\n(** [nat_of_P] is a morphism for multiplication *)\n\nTheorem nat_of_P_mult_morphism :\n forall p q:positive, nat_of_P (p * q) = nat_of_P p * nat_of_P q.\nProof.\nintros x y; induction x as [x' H| x' H| ];\n [ change (xI x' * y)%positive with (y + xO (x' * y))%positive in |- *;\n    rewrite nat_of_P_plus_morphism; unfold nat_of_P at 2 3 in |- *;\n    simpl in |- *; do 2 rewrite ZL6; rewrite H; rewrite mult_plus_distr_r;\n    reflexivity\n | unfold nat_of_P at 1 2 in |- *; simpl in |- *; do 2 rewrite ZL6; rewrite H;\n    rewrite mult_plus_distr_r; reflexivity\n | simpl in |- *; rewrite <- plus_n_O; reflexivity ].\nQed.\n\n(** [nat_of_P] maps to the strictly positive subset of [nat] *)\n\nLemma ZL4 : forall p:positive,  exists h : nat, nat_of_P p = S h.\nProof.\nintro y; induction y as [p H| p H| ];\n [ destruct H as [x H1]; exists (S x + S x); unfold nat_of_P in |- *;\n    simpl in |- *; change 2 with (1 + 1) in |- *;\n    rewrite Pmult_nat_r_plus_morphism; unfold nat_of_P in H1;\n    rewrite H1; auto with arith\n | destruct H as [x H2]; exists (x + S x); unfold nat_of_P in |- *;\n    simpl in |- *; change 2 with (1 + 1) in |- *;\n    rewrite Pmult_nat_r_plus_morphism; unfold nat_of_P in H2;\n    rewrite H2; auto with arith\n | exists 0; auto with arith ].\nQed.\n\n(** Extra lemmas on [lt] on Peano natural numbers *)\n\nLemma ZL7 : forall n m:nat, n < m -> n + n < m + m.\nProof.\nintros m n H; apply lt_trans with (m := m + n);\n [ apply plus_lt_compat_l with (1 := H)\n | rewrite (plus_comm m n); apply plus_lt_compat_l with (1 := H) ].\nQed.\n\nLemma ZL8 : forall n m:nat, n < m -> S (n + n) < m + m.\nProof.\nintros m n H; apply le_lt_trans with (m := m + n);\n [ change (m + m < m + n) in |- *; apply plus_lt_compat_l with (1 := H)\n | rewrite (plus_comm m n); apply plus_lt_compat_l with (1 := H) ].\nQed.\n\n(** [nat_of_P] is a morphism from [positive] to [nat] for [lt] (expressed\n    from [compare] on [positive])\n\n    Part 1: [lt] on [positive] is finer than [lt] on [nat]\n*)\n\nLemma nat_of_P_lt_Lt_compare_morphism :\n forall p q:positive, (p ?= q) Eq = Lt -> nat_of_P p < nat_of_P q.\nProof.\nintro x; induction x as [p H| p H| ]; intro y; destruct y as [q| q| ];\n intro H2;\n [ unfold nat_of_P in |- *; simpl in |- *; apply lt_n_S; do 2 rewrite ZL6;\n    apply ZL7; apply H; simpl in H2; assumption\n | unfold nat_of_P in |- *; simpl in |- *; do 2 rewrite ZL6; apply ZL8;\n    apply H; simpl in H2; apply Pcompare_Gt_Lt; assumption\n | simpl in |- *; discriminate H2\n | simpl in |- *; unfold nat_of_P in |- *; simpl in |- *; do 2 rewrite ZL6;\n    elim (Pcompare_Lt_Lt p q H2);\n    [ intros H3; apply lt_S; apply ZL7; apply H; apply H3\n    | intros E; rewrite E; apply lt_n_Sn ]\n | simpl in |- *; unfold nat_of_P in |- *; simpl in |- *; do 2 rewrite ZL6;\n    apply ZL7; apply H; assumption\n | simpl in |- *; discriminate H2\n | unfold nat_of_P in |- *; simpl in |- *; apply lt_n_S; rewrite ZL6;\n    elim (ZL4 q); intros h H3; rewrite H3; simpl in |- *;\n    apply lt_O_Sn\n | unfold nat_of_P in |- *; simpl in |- *; rewrite ZL6; elim (ZL4 q);\n    intros h H3; rewrite H3; simpl in |- *; rewrite <- plus_n_Sm;\n    apply lt_n_S; apply lt_O_Sn\n | simpl in |- *; discriminate H2 ].\nQed.\n\n(** [nat_of_P] is a morphism from [positive] to [nat] for [gt] (expressed\n    from [compare] on [positive])\n\n    Part 1: [gt] on [positive] is finer than [gt] on [nat]\n*)\n\nLemma nat_of_P_gt_Gt_compare_morphism :\n forall p q:positive, (p ?= q) Eq = Gt -> nat_of_P p > nat_of_P q.\nProof.\nintros p q GT. unfold gt.\napply nat_of_P_lt_Lt_compare_morphism.\nchange ((q ?= p) (CompOpp Eq) = CompOpp Gt).\nrewrite <- Pcompare_antisym, GT; auto.\nQed.\n\n(** [nat_of_P] is a morphism for [Pcompare] and [nat_compare] *)\n\nLemma nat_of_P_compare_morphism : forall p q,\n (p ?= q) Eq = nat_compare (nat_of_P p) (nat_of_P q).\nProof.\n intros p q; symmetry.\n destruct ((p ?= q) Eq) as [ | | ]_eqn.\n rewrite (Pcompare_Eq_eq p q); auto.\n apply <- nat_compare_eq_iff; auto.\n apply -> nat_compare_lt. apply nat_of_P_lt_Lt_compare_morphism; auto.\n apply -> nat_compare_gt. apply nat_of_P_gt_Gt_compare_morphism; auto.\nQed.\n\n(** [nat_of_P] is hence injective. *)\n\nLemma nat_of_P_inj : forall p q:positive, nat_of_P p = nat_of_P q -> p = q.\nProof.\nintros.\napply Pcompare_Eq_eq.\nrewrite nat_of_P_compare_morphism.\napply <- nat_compare_eq_iff; auto.\nQed.\n\n(** [nat_of_P] is a morphism from [positive] to [nat] for [lt] (expressed\n    from [compare] on [positive])\n\n    Part 2: [lt] on [nat] is finer than [lt] on [positive]\n*)\n\nLemma nat_of_P_lt_Lt_compare_complement_morphism :\n forall p q:positive, nat_of_P p < nat_of_P q -> (p ?= q) Eq = Lt.\nProof.\n intros. rewrite nat_of_P_compare_morphism.\n apply -> nat_compare_lt; auto.\nQed.\n\n(** [nat_of_P] is a morphism from [positive] to [nat] for [gt] (expressed\n    from [compare] on [positive])\n\n    Part 2: [gt] on [nat] is finer than [gt] on [positive]\n*)\n\nLemma nat_of_P_gt_Gt_compare_complement_morphism :\n forall p q:positive, nat_of_P p > nat_of_P q -> (p ?= q) Eq = Gt.\nProof.\n intros. rewrite nat_of_P_compare_morphism.\n apply -> nat_compare_gt; auto.\nQed.\n\n\n(** [nat_of_P] is strictly positive *)\n\nLemma le_Pmult_nat : forall (p:positive) (n:nat), n <= Pmult_nat p n.\ninduction p; simpl in |- *; auto with arith.\nintro m; apply le_trans with (m + m); auto with arith.\nQed.\n\nLemma lt_O_nat_of_P : forall p:positive, 0 < nat_of_P p.\nintro; unfold nat_of_P in |- *; apply lt_le_trans with 1; auto with arith.\napply le_Pmult_nat.\nQed.\n\n(** Pmult_nat permutes with multiplication *)\n\nLemma Pmult_nat_mult_permute :\n forall (p:positive) (n m:nat), Pmult_nat p (m * n) = m * Pmult_nat p n.\nProof.\n  simple induction p. intros. simpl in |- *. rewrite mult_plus_distr_l. rewrite <- (mult_plus_distr_l m n n).\n  rewrite (H (n + n) m). reflexivity.\n  intros. simpl in |- *. rewrite <- (mult_plus_distr_l m n n). apply H.\n  trivial.\nQed.\n\nLemma Pmult_nat_2_mult_2_permute :\n forall p:positive, Pmult_nat p 2 = 2 * Pmult_nat p 1.\nProof.\n  intros. rewrite <- Pmult_nat_mult_permute. reflexivity.\nQed.\n\nLemma Pmult_nat_4_mult_2_permute :\n forall p:positive, Pmult_nat p 4 = 2 * Pmult_nat p 2.\nProof.\n  intros. rewrite <- Pmult_nat_mult_permute. reflexivity.\nQed.\n\n(** Mapping of xH, xO and xI through [nat_of_P] *)\n\nLemma nat_of_P_xH : nat_of_P 1 = 1.\nProof.\n  reflexivity.\nQed.\n\nLemma nat_of_P_xO : forall p:positive, nat_of_P (xO p) = 2 * nat_of_P p.\nProof.\n  intros.\n  change 2 with (nat_of_P 2).\n  rewrite <- nat_of_P_mult_morphism.\n  f_equal.\nQed.\n\nLemma nat_of_P_xI : forall p:positive, nat_of_P (xI p) = S (2 * nat_of_P p).\nProof.\n  intros.\n  change 2 with (nat_of_P 2).\n  rewrite <- nat_of_P_mult_morphism, <- nat_of_P_succ_morphism.\n  f_equal.\nQed.\n\n(**********************************************************************)\n(** Properties of the shifted injection from Peano natural numbers to\n    binary positive numbers *)\n\n(** Composition of [P_of_succ_nat] and [nat_of_P] is successor on [nat] *)\n\nTheorem nat_of_P_o_P_of_succ_nat_eq_succ :\n forall n:nat, nat_of_P (P_of_succ_nat n) = S n.\nProof.\ninduction n as [|n H].\nreflexivity.\nsimpl; rewrite nat_of_P_succ_morphism, H; auto.\nQed.\n\n(** Miscellaneous lemmas on [P_of_succ_nat] *)\n\nLemma ZL3 :\n forall n:nat, Psucc (P_of_succ_nat (n + n)) = xO (P_of_succ_nat n).\nProof.\ninduction n as [| n H]; simpl;\n [ auto with arith\n | rewrite plus_comm; simpl; rewrite H;\n    rewrite xO_succ_permute; auto with arith ].\nQed.\n\nLemma ZL5 : forall n:nat, P_of_succ_nat (S n + S n) = xI (P_of_succ_nat n).\nProof.\ninduction n as [| n H]; simpl;\n [ auto with arith\n | rewrite <- plus_n_Sm; simpl; simpl in H; rewrite H;\n    auto with arith ].\nQed.\n\n(** Composition of [nat_of_P] and [P_of_succ_nat] is successor on [positive] *)\n\nTheorem P_of_succ_nat_o_nat_of_P_eq_succ :\n forall p:positive, P_of_succ_nat (nat_of_P p) = Psucc p.\nProof.\nintros.\napply nat_of_P_inj.\nrewrite nat_of_P_o_P_of_succ_nat_eq_succ, nat_of_P_succ_morphism; auto.\nQed.\n\n(** Composition of [nat_of_P], [P_of_succ_nat] and [Ppred] is identity\n    on [positive] *)\n\nTheorem pred_o_P_of_succ_nat_o_nat_of_P_eq_id :\n forall p:positive, Ppred (P_of_succ_nat (nat_of_P p)) = p.\nProof.\nintros; rewrite P_of_succ_nat_o_nat_of_P_eq_succ, Ppred_succ; auto.\nQed.\n\n(**********************************************************************)\n(** Extra properties of the injection from binary positive numbers to Peano\n    natural numbers *)\n\n(** [nat_of_P] is a morphism for subtraction on positive numbers *)\n\nTheorem nat_of_P_minus_morphism :\n forall p q:positive,\n   (p ?= q) Eq = Gt -> nat_of_P (p - q) = nat_of_P p - nat_of_P q.\nProof.\nintros x y H; apply plus_reg_l with (nat_of_P y); rewrite le_plus_minus_r;\n [ rewrite <- nat_of_P_plus_morphism; rewrite Pplus_minus; auto with arith\n | apply lt_le_weak; exact (nat_of_P_gt_Gt_compare_morphism x y H) ].\nQed.\n\n\nLemma ZL16 : forall p q:positive, nat_of_P p - nat_of_P q < nat_of_P p.\nProof.\nintros p q; elim (ZL4 p); elim (ZL4 q); intros h H1 i H2; rewrite H1;\n rewrite H2; simpl in |- *; unfold lt in |- *; apply le_n_S;\n apply le_minus.\nQed.\n\nLemma ZL17 : forall p q:positive, nat_of_P p < nat_of_P (p + q).\nProof.\nintros p q; rewrite nat_of_P_plus_morphism; unfold lt in |- *; elim (ZL4 q);\n intros k H; rewrite H; rewrite plus_comm; simpl in |- *;\n apply le_n_S; apply le_plus_r.\nQed.\n\n(** Comparison and subtraction *)\n\nLemma Pcompare_minus_r :\n forall p q r:positive,\n   (q ?= p) Eq = Lt ->\n   (r ?= p) Eq = Gt ->\n   (r ?= q) Eq = Gt -> (r - p ?= r - q) Eq = Lt.\nProof.\nintros; apply nat_of_P_lt_Lt_compare_complement_morphism;\n rewrite nat_of_P_minus_morphism;\n [ rewrite nat_of_P_minus_morphism;\n    [ apply plus_lt_reg_l with (p := nat_of_P q); rewrite le_plus_minus_r;\n       [ rewrite plus_comm; apply plus_lt_reg_l with (p := nat_of_P p);\n          rewrite plus_assoc; rewrite le_plus_minus_r;\n          [ rewrite (plus_comm (nat_of_P p)); apply plus_lt_compat_l;\n             apply nat_of_P_lt_Lt_compare_morphism;\n             assumption\n          | apply lt_le_weak; apply nat_of_P_lt_Lt_compare_morphism;\n             apply ZC1; assumption ]\n       | apply lt_le_weak; apply nat_of_P_lt_Lt_compare_morphism; apply ZC1;\n          assumption ]\n    | assumption ]\n | assumption ].\nQed.\n\nLemma Pcompare_minus_l :\n forall p q r:positive,\n   (q ?= p) Eq = Lt ->\n   (p ?= r) Eq = Gt ->\n   (q ?= r) Eq = Gt -> (q - r ?= p - r) Eq = Lt.\nProof.\nintros p q z; intros; apply nat_of_P_lt_Lt_compare_complement_morphism;\n rewrite nat_of_P_minus_morphism;\n [ rewrite nat_of_P_minus_morphism;\n    [ unfold gt in |- *; apply plus_lt_reg_l with (p := nat_of_P z);\n       rewrite le_plus_minus_r;\n       [ rewrite le_plus_minus_r;\n          [ apply nat_of_P_lt_Lt_compare_morphism; assumption\n          | apply lt_le_weak; apply nat_of_P_lt_Lt_compare_morphism;\n             apply ZC1; assumption ]\n       | apply lt_le_weak; apply nat_of_P_lt_Lt_compare_morphism; apply ZC1;\n          assumption ]\n    | assumption ]\n | assumption ].\nQed.\n\n(** Distributivity of multiplication over subtraction *)\n\nTheorem Pmult_minus_distr_l :\n forall p q r:positive,\n   (q ?= r) Eq = Gt ->\n   (p * (q - r) = p * q - p * r)%positive.\nProof.\nintros x y z H; apply nat_of_P_inj; rewrite nat_of_P_mult_morphism;\n rewrite nat_of_P_minus_morphism;\n [ rewrite nat_of_P_minus_morphism;\n    [ do 2 rewrite nat_of_P_mult_morphism;\n       do 3 rewrite (mult_comm (nat_of_P x)); apply mult_minus_distr_r\n    | apply nat_of_P_gt_Gt_compare_complement_morphism;\n       do 2 rewrite nat_of_P_mult_morphism; unfold gt in |- *;\n       elim (ZL4 x); intros h H1; rewrite H1; apply mult_S_lt_compat_l;\n       exact (nat_of_P_gt_Gt_compare_morphism y z H) ]\n | assumption ].\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/NArith/Pnat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.6556700525852235}}
{"text": "(* author: Dimitur Krustev *)\n(* started: 20170521 *)\n\nRequire Import Arith List.\n\nFixpoint replicate {A: Type} (n: nat) (x: A) : list A :=\n  match n with\n  | 0 => nil\n  | S n => x :: replicate n x\n  end.\n\nLemma cons_replicate_swap: forall (A: Type) (n: nat) (x: A),\n  x :: replicate n x = replicate n x ++ x::nil.\nProof.\n  induction n; auto.\n  intros. simpl. rewrite IHn. reflexivity.\nQed.\n\nSection RLE.\n\nVariable A: Type.\nVariable Adec: forall x y: A, {x = y} + {x <> y}.\n\nLet RLEncHelper := fix RLEncHelper (n: nat) (x: A) (xs: list A) : list (nat * A) :=\n  match xs with\n  | nil => (n, x)::nil\n  | x1::xs => match Adec x x1 with\n    | left Heq => RLEncHelper (S n) x xs\n    | right Hneq => (n, x) :: RLEncHelper 1 x1 xs\n    end\n  end.\n\nDefinition RLEnc (xs: list A) : list (nat * A) :=\n  match xs with\n  | nil => nil\n  | x::xs => RLEncHelper 1 x xs\n  end.\n\nDefinition RLDec (nxs: list (nat * A)) : list A :=\n  flat_map (fun nx => let '(n, x) := nx in replicate n x) nxs.\n\nLemma RLEncHelper_correct: forall n x xs, RLDec (RLEncHelper n x xs) = replicate n x ++ xs.\nProof.\n  intros. revert n x. induction xs; auto.\n  { intros. simpl. destruct (Adec x a) as [Heq | Hneq].\n    - subst. rewrite IHxs. simpl.\n      change ((a :: replicate n a) ++ xs = replicate n a ++ a :: xs).\n      rewrite cons_replicate_swap.\n      rewrite <- app_assoc. reflexivity.\n    - simpl. rewrite IHxs. reflexivity.\n  }\nQed.\n\nTheorem RLEnc_correct: forall xs, RLDec (RLEnc xs) = xs.\nProof.\n  destruct xs.\n  - simpl. reflexivity.\n  - simpl. apply RLEncHelper_correct.\nQed.\n\nEnd RLE.\n\nRecursive Extraction RLDec RLEnc.", "meta": {"author": "dkrustev", "repo": "coq-misc-essays", "sha": "3cecd11e601dc64447820207240123e8f978366e", "save_path": "github-repos/coq/dkrustev-coq-misc-essays", "path": "github-repos/coq/dkrustev-coq-misc-essays/coq-misc-essays-3cecd11e601dc64447820207240123e8f978366e/RunLengthEnc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117812622843, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6556700396973519}}
{"text": "Require Import GHC.Base.\n(* _==_ notation *)\n\nRequire Import ZArith.\nRequire Import ZArith.BinInt.\n\n(* Hand-translated version of the prelude definitions\n   of these functions. *)\n\nFixpoint take {a:Type} (n:Z) (xs:list a) : list a :=\n  if (n <=? 0)%Z then nil\n  else match xs with\n       | nil => nil\n       | cons y ys => cons y (take (n - 1) ys)\n       end.\n\nFixpoint drop {a:Type} (n:Z) (xs:list a) : list a :=\n  if (n <=? 0)%Z then xs\n  else match xs with\n       | nil => nil\n       | cons y ys => drop (n - 1) ys\n       end.\n\n(* TODO: mark impossible case with default. *)\n\nFixpoint scanr {a b:Type} (f : a -> b -> b) (q0 : b)\n        (xs: list a) :=\n match xs with\n | nil => (cons q0 nil)\n | cons y ys => match (scanr f q0 ys) with\n               | cons q qs => cons (f y q) (cons q qs)\n               | nil => nil  (* impossible case  *)\n               end\nend.\n\n\nDefinition splitAt {a : Type}(n:Z)(xs:list a) :=\n  (take n xs, drop n xs).\n\nDefinition replicate {a:Type}(n:Z): a -> list a.\ndestruct (0 <=? n)%Z eqn:E; [|exact (fun _ => nil)].\napply Zle_bool_imp_le in E.\napply natlike_rec2 with (P := fun _ => a -> list a)(z := n).\n- exact (fun _ => nil).\n- intros n1 Pf rec x. exact (cons x (rec x)).\n- exact E.\nDefined.\n", "meta": {"author": "DavidFHCh", "repo": "Tesis-FTW", "sha": "f84ab8eb92f3984e973ce6a441262d9a8a62e9b0", "save_path": "github-repos/coq/DavidFHCh-Tesis-FTW", "path": "github-repos/coq/DavidFHCh-Tesis-FTW/Tesis-FTW-f84ab8eb92f3984e973ce6a441262d9a8a62e9b0/tesis/hs-to-coq/examples/base-src/module-edits/GHC/List/preamble.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6556700370192721}}
{"text": "Require Import Program.Basics.\nFrom hahn Require Import Hahn.\n\nSet Implicit Arguments.\nLocal Open Scope program_scope.\n\nSection AuxRel.\n\n  Definition clos_sym {A : Type} (r : relation A) : relation A := \n    r ∪ r⁻¹. \n\n  Definition clos_refl_sym {A : Type} (r : relation A) : relation A := \n    (r ∪ r⁻¹)^?. \n\n  Definition eq_opt {A : Type} (a: option A) : A -> Prop := \n    fun b => \n      match a with\n      | None => False\n      | Some a => eq a b\n      end.\n  \n  Definition compl_rel {A : Type} (r : relation A) : relation A := \n    fun a b => ~ r a b.\n\n  Definition inj_dom {A B : Type} (s : A -> Prop) (f : A -> B) := \n    forall (x y : A) (SX : s x) (SY: s y) (EQ : f x = f y), \n      x = y.\n\n  Definition restr_fun {A B : Type} (s : A -> Prop) (f g : A -> B) := \n    fun x => if excluded_middle_informative (s x) then f x else g x.\n\n  Definition fixset {A : Type} (s : A -> Prop) (f : A -> A) := \n    forall (x : A) (SX : s x), f x = x.\n\n  Definition downward_total {A : Type} (r : relation A) := \n    forall x y z (Rxz : r x z) (Ryz : r y z), clos_refl_sym r x y.\n\n  Definition set_map {A B : Type} (f : A -> B) (s : B -> Prop) := \n    fun x => s (f x).\n\nEnd AuxRel.\n\nNotation \"⊤₁\" := set_full.\nNotation \"⊤₂\" := (fun _ _ => True).\n\nNotation \"a ⁼\" := (clos_refl_sym a) (at level 1, format \"a ⁼\").\nNotation \"a ^=\" := (clos_refl_sym a) (at level 1, only parsing).\nNotation \"f ⋄₁ s\"  := (set_map f s) (at level 39).\nNotation \"f □₁ s\" := (set_collect f s) (at level 39).\nNotation \"f ⋄ r\"  := (map_rel f r) (at level 45).\nNotation \"f □ r\"  := (collect_rel f r) (at level 45).\n\nHint Unfold \n     clos_sym clos_refl_sym \n     inj_dom restr_fun set_map\n     eq_opt compl_rel fixset : unfolderDb. \n\nSection Props.\n\nVariables A B C : Type.\nVariables s s' s'' : A -> Prop.\nVariables p p' p'' : B -> Prop.\nVariables r r' r'' : relation A.\n\n(******************************************************************************)\n(** ** clos_sym/clos_refl_sym properties *)\n(******************************************************************************)\n\nLemma csE : r^⋈  ≡ r ∪ r⁻¹.\nProof. basic_solver. Qed.\n\nLemma crsE : r⁼ ≡ ⦗⊤₁⦘ ∪ r ∪ r⁻¹.\nProof. basic_solver. Qed.\n\nLemma crs_cs : r⁼ ≡ ⦗⊤₁⦘ ∪ r^⋈.\nProof. basic_solver. Qed. \n\nLemma cs_union : (r ∪ r')^⋈  ≡ r^⋈ ∪ r'^⋈.\nProof. basic_solver. Qed.\n\nLemma crs_union : (r ∪ r')⁼  ≡ r⁼ ∪ r'⁼.\nProof. basic_solver. Qed.\n\nLemma cs_cross : (s × s')^⋈ ≡ s × s' ∪ s' × s.\nProof. basic_solver. Qed.\n\nLemma crs_cross : (s × s')⁼ ≡ ⦗⊤₁⦘ ∪ s × s' ∪ s' × s.\nProof. basic_solver. Qed.\n\nLemma cs_restr : (restr_rel s r)^⋈ ≡ restr_rel s r^⋈.\nProof. basic_solver. Qed.\n\nLemma crs_restr1 : (restr_rel s r)⁼ ≡ ⦗⊤₁⦘ ∪ restr_rel s r^⋈.\nProof. basic_solver 10. Qed.\n\nLemma crs_restr2 : restr_rel s r⁼ ≡ restr_rel s ⦗⊤₁⦘ ∪ restr_rel s r^⋈.\nProof. basic_solver 10. Qed.\n\n(******************************************************************************)\n(** ** symmetry of relations *)\n(******************************************************************************)\n\nLemma cr_sym : symmetric r -> symmetric r^?.\nProof. basic_solver. Qed.\n\nLemma cs_sym : symmetric r^⋈.\nProof. basic_solver. Qed.\n\nLemma crs_sym : symmetric r⁼.\nProof. basic_solver. Qed.\n\nLemma eqv_sym : forall (s : A -> Prop), symmetric ⦗s⦘.\nProof. basic_solver. Qed.\n\nLemma union_sym : symmetric r -> symmetric r' -> symmetric (r ∪ r').\nProof. basic_solver. Qed.\n\nLemma inter_sym : symmetric r -> symmetric r' -> symmetric (r ∩ r').\nProof. basic_solver. Qed.\n\nLemma minus_sym : symmetric r -> symmetric r' -> symmetric (r \\ r').\nProof. basic_solver. Qed.\n\nLemma transp_sym : symmetric r -> symmetric r⁻¹.\nProof. basic_solver. Qed.\n\nLemma restr_sym : symmetric r -> symmetric (restr_rel s r). \nProof. basic_solver. Qed.\n\n(******************************************************************************)\n(** ** dom/codom properties *)\n(******************************************************************************)\n\nLemma dom_singl_rel (x y : A) : dom_rel (singl_rel x y) ≡₁ eq x. \nProof. basic_solver. Qed.\n\nLemma codom_singl_rel (x y : A) : codom_rel (singl_rel x y) ≡₁ eq y. \nProof. basic_solver. Qed.\n\nLemma dom_seq : dom_rel (r ⨾ r') ⊆₁ dom_rel r.\nProof. basic_solver. Qed.\n\nLemma dom_minus : dom_rel (r \\ r') ⊆₁ dom_rel r. \nProof. basic_solver. Qed.\n\n(* TODO : rename *)\nLemma seq_codom_dom_inter : codom_rel r ∩₁ dom_rel r' ≡₁ ∅ -> r ⨾ r' ≡ ∅₂.\nProof.\n  unfold set_equiv, set_subset; ins; desf. \n  unfold same_relation; splits; [|basic_solver].\n  unfold seq, inclusion. \n  intros x y [z HH]. \n  specialize (H z).\n  apply H. \n  basic_solver.\nQed.\n\n(******************************************************************************)\n(** ** cross_rel properties *)\n(******************************************************************************)\n\nLemma cross_union_l : s × (s' ∪₁ s'') ≡ s × s' ∪ s × s''.\nProof. basic_solver. Qed.\n\nLemma cross_union_r : (s ∪₁ s') × s'' ≡ s × s'' ∪ s' × s''.\nProof. basic_solver. Qed.\n\nLemma cross_inter_l : (s ∩₁ s') × s'' ≡ ⦗s⦘ ⨾ s' × s''.\nProof. basic_solver. Qed.\n\nLemma cross_inter_r : s × (s' ∩₁ s'') ≡ s × s' ⨾ ⦗s''⦘.\nProof. basic_solver. Qed.\n\nLemma seq_cross_eq x : s × eq x ⨾ eq x × s' ≡ s × s'.\nProof. basic_solver 10. Qed.\n\n(* Lemma seq_eqv_cross : ⦗q⦘ ⨾ s × s' ⨾ ⦗q'⦘ ≡ (q ∩₁ s) × (q' ∩₁ s'). *)\n(* Proof. basic_solver. Qed. *)\n\nLemma restr_cross : restr_rel s r ≡ r ∩ s × s.\nProof. basic_solver. Qed.\n\nLemma seq_cross_singl_l x y : s' x -> s × s' ⨾ singl_rel x y ≡ s × eq y.\nProof. \n  ins. \n  autounfold with unfolderDb.\n  splits; ins; splits; desf; eauto. \nQed.\n\nLemma seq_cross_singl_r x y : s y -> singl_rel x y ⨾ s × s' ≡ eq x × s'.\nProof. \n  ins. \n  autounfold with unfolderDb.\n  splits; ins; splits; desf; eauto. \nQed.\n\n(******************************************************************************)\n(** ** transp properties *)\n(******************************************************************************)\n\nLemma transp_singl_rel (x y : A) : (singl_rel x y)⁻¹ ≡ singl_rel y x.\nProof. basic_solver. Qed.\n\nLemma transp_sym_equiv : symmetric r -> r⁻¹ ≡ r. \nProof. basic_solver. Qed.\n\nLemma sym_transp_equiv : symmetric r <-> r⁻¹ ≡ r. \nProof.\n  split.\n  { basic_solver. }\n  intros HH.\n  red. ins. by apply HH.\nQed.\n\n(* TODO : rename *)\nLemma seq_transp_sym : symmetric r -> ⦗ s ⦘ ⨾ r ⨾ ⦗ s' ⦘ ≡ (⦗ s' ⦘ ⨾ r ⨾ ⦗ s ⦘)⁻¹.\nProof. \n  ins. \n  rewrite !transp_seq. \n  rewrite !seqA.\n  rewrite !transp_sym_equiv; auto. \n  rewrite !transp_eqv_rel. \n  done.\nQed.\n\n(******************************************************************************)\n(** ** set_collect properties *)\n(******************************************************************************)\n\nLemma set_collect_eq_dom (f g : A -> B) (EQ : eq_dom s f g) :\n  f □₁ s ≡₁ g □₁ s.\nProof. \n  unfolder in *. \n  split. \n  { ins. desf. \n    specialize (EQ y H).\n    eauto. }\n  ins. desf. eauto. \nQed.\n\n(* Note that inclusion in other direction doesn't hold.\n   For example, if `f` is constant and `a <> b`, then\n   `f □₁ (eq a ∩₁ eq b) ≡₁ ∅` and `f □₁ eq a ∩₁ f □₁ eq b ≡₁ f □₁ eq a`.\n *)\nLemma set_collect_inter (f g : A -> B) : \n  f □₁ (s ∩₁ s') ⊆₁ f □₁ s ∩₁ f □₁ s'.\nProof. basic_solver. Qed.\n\nLemma set_collect_dom (f : A -> B) : \n  f □₁ dom_rel r ≡₁ dom_rel (f □ r).\nProof.\n  unfolder.\n  split; intros x HH; desf; eauto.\n  repeat eexists. eauto.\nQed.\n\nLemma set_collect_eq_opt (f : A -> B) (a : option A) : \n  f □₁ eq_opt a ≡₁ eq_opt (option_map f a).\nProof. unfold eq_opt, option_map. basic_solver. Qed.\n\nLemma set_collect_compose (f : A -> B) (g : B -> C) :\n  g □₁ (f □₁ s) ≡₁ (g ∘ f) □₁ s.\nProof. \n  autounfold with unfolderDb. unfold set_subset. \n  ins; splits; ins; splits; desf; eauto.\nQed.\n\nLemma set_collect_updo (f : A -> B) (a : A) (b : B) (NC : ~ s a) : \n  (upd f a b) □₁ s ≡₁ f □₁ s.\nProof.\n  assert (forall x: A, s x -> x <> a). \n  { ins. intros HH. by subst. }\n  unfolder.\n  splits; unfold set_subset; ins.\n  all: desf; eexists; splits; eauto.\n  all: rewrite updo; auto.\nQed.\n\nLemma set_collect_restr_fun (f g : A -> B) : \n  s' ⊆₁ s -> (restr_fun s f g) □₁ s' ≡₁ f □₁ s'.\nProof. \n  clear.\n  unfolder. ins. split. \n  all : \n    ins; desc; \n    eexists; split; eauto; \n    destruct (excluded_middle_informative (s y)); \n    eauto; exfalso; intuition. \nQed.\n\nLemma set_collect_if_then (ft fe: A -> B) (HH : s ⊆₁ s') :\n  (fun e : A =>\n     if excluded_middle_informative (s' e)\n     then ft e\n     else fe e) □₁ s ≡₁ ft □₁ s.\nProof.\n  unfolder. split; ins; desf; eauto.\n  2: eexists; splits; eauto; desf.\n  all: by exfalso; match goal with H : ~ _ |- _ => apply H end; apply HH.\nQed.\n\nLemma set_collect_if_else (ft fe: A -> B) (HH : s ∩₁ s' ⊆₁ ∅) :\n  (fun e : A =>\n     if excluded_middle_informative (s' e)\n     then ft e\n     else fe e) □₁ s ≡₁ fe □₁ s.\nProof.\n  unfolder. split; ins; desf; eauto.\n  2: eexists; splits; eauto; desf.\n  all: exfalso; eapply HH; split; eauto.\nQed.\n\n(******************************************************************************)\n(** ** collect_rel properties *)\n(******************************************************************************)\n\n(* Lemma collect_rel_eq_dom : *)\n(*   forall (s s': A -> Prop) (EQs: eq_dom s f g) (EQs': eq_dom s' f g), *)\n(*   f □ (⦗ s ⦘ ⨾ r ⨾ ⦗ s' ⦘) ≡ g □ (⦗ s ⦘ ⨾ r ⨾ ⦗ s' ⦘). *)\n(* Proof. *)\n(*   ins. *)\n(*   unfolder. *)\n(*   splits; ins; desf; repeat eexists; eauto; symmetry. *)\n(*   { by apply EQs. } *)\n(*   by apply EQs'. *)\n(* Qed. *)\n\nLemma collect_rel_restr_eq_dom (f g : A -> B) (EQ : eq_dom s f g) :\n  f □ (restr_rel s r) ≡ g □ (restr_rel s r).\nProof. \n  unfolder. split.\n  { ins; desf; repeat eexists; eauto; \n      symmetry; eapply EQ; auto. }\n  ins; desf; repeat eexists; eauto; \n    symmetry; eapply EQ; auto.\nQed.\n\nLemma collect_rel_singl (f : A -> B) x y : \n  f □ singl_rel x y ≡ singl_rel (f x) (f y).\nProof. basic_solver 42. Qed.\n\nLemma collect_rel_transp (f : A -> B) : \n  f □ r⁻¹ ≡ (f □ r)⁻¹.\nProof. basic_solver 42. Qed.\n\nLemma collect_rel_eqv (f : A -> B) : \n  f □ ⦗ s ⦘ ≡ ⦗ f □₁ s ⦘.\nProof.\n  unfolder.\n  splits; ins; desf; eauto.\n  eexists. eexists.\n  splits; eauto.\nQed.\n\nLemma collect_rel_interi (f : A -> B) : \n  f □ (r ∩ r') ⊆ (f □ r) ∩ (f □ r').\nProof. basic_solver 10. Qed.\n\nLemma collect_rel_seqi (f : A -> B) : \n  f □ (r ⨾ r') ⊆ (f □ r) ⨾ (f □ r').\nProof. basic_solver 30. Qed.\n\nLemma collect_rel_seq (f : A -> B)\n      (INJ : inj_dom (codom_rel r ∪₁ dom_rel r') f) : \n  f □ (r ⨾ r') ≡ (f □ r) ⨾ (f □ r').\nProof.\n  split; \n    [by apply collect_rel_seqi|].\n  unfolder.\n  ins; desf; eauto.\n  repeat eexists; eauto.\n  erewrite INJ; eauto;\n    unfolder; eauto.\nQed.\n\nLemma collect_rel_cr (f : A -> B) (rr : relation A) : \n  f □ rr^? ⊆  (f □ rr)^?.\nProof.\n  unfolder. ins; desf; auto.\n  right. eexists. eexists. eauto.\nQed.\n\nLemma collect_rel_ct (f : A -> B) (rr : relation A) : \n  f □ rr⁺ ⊆ (f □ rr)⁺.\nProof.\n  unfolder. ins. desf.\n  induction H.\n  { apply ct_step. eexists. eexists. splits; eauto. }\n  eapply t_trans; eauto.\nQed.\n\nLemma collect_rel_crt (f : A -> B) (rr : relation A) : \n  f □ rr＊ ⊆  (f □ rr)＊.\nProof.\n  by rewrite <- !cr_of_ct, \n             <- collect_rel_ct, \n             <- collect_rel_cr.\nQed.\n\nLemma collect_rel_irr (f : A -> B) (Irr : irreflexive (f □ r)): \n  irreflexive r.\nProof. generalize Irr. basic_solver 10. Qed.\n\nLemma collect_rel_acyclic (f : A -> B) (ACYC : acyclic (f □ r)): \n  acyclic r.\nProof.\n  red. red.\n  assert (forall x y, r⁺ x y -> x <> y) as AA.\n  2: { ins. eapply AA; eauto. }\n  ins. induction H; intros BB; subst.\n  { eapply ACYC. apply ct_step. red.\n    eexists. eexists. splits; eauto. }\n  eapply ACYC.\n  apply collect_rel_ct.\n  red. eexists. eexists. splits.\n  { eapply t_trans; eauto. }\n  all: done.\nQed.\n\nLemma collect_rel_compose (f : A -> B) (g : B -> C) :\n  g □ (f □ r) ≡ (g ∘ f) □ r.\nProof. \n  unfolder. unfold compose.\n  ins; splits; ins; splits; desf; eauto.\n  do 2 eexists. splits; eauto.\nQed.\n\nLemma collect_rel_fixset (f : A -> A) (FIX : fixset s f) :\n  f □ restr_rel s r ≡ restr_rel s r.\nProof.\n  unfolder in *.\n  split; ins; desf.\n  2: { do 2 eexists. splits; eauto. }\n  assert (f x' = x') as HX. \n  { specialize (FIX x'). auto. }\n  assert (f y' = y') as HY. \n  { specialize (FIX y'). auto. }\n  splits; congruence.\nQed.\n\nLemma collect_rel_if_then\n      (ft fe: A -> B) (DOM : dom_rel r ⊆₁ s) (CODOM : codom_rel r ⊆₁ s) :\n  (fun e : A =>\n     if excluded_middle_informative (s e)\n     then ft e\n     else fe e) □ r ≡ ft □ r.\nProof.\n  unfolder. split; ins; desf; eauto.\n  4: do 2 eexists; splits; eauto; desf.\n  1,3,5: by exfalso; match goal with H : ~ _ |- _ => apply H end;\n    eapply CODOM; eexists; eauto.\n  all: by exfalso; match goal with H : ~ _ |- _ => apply H end;\n    eapply DOM; eexists; eauto.\nQed.\n\nLemma collect_rel_if_else\n      (ft fe: A -> B) (DOM : dom_rel r ∩₁ s ⊆₁ ∅) (CODOM : codom_rel r ∩₁ s ⊆₁ ∅) :\n  (fun e : A =>\n     if excluded_middle_informative (s e)\n     then ft e\n     else fe e) □ r ≡ fe □ r.\nProof.\n  unfolder. split; ins; desf; eauto.\n  4: do 2 eexists; splits; eauto; desf.\n  1,2,4: by exfalso; eapply DOM; split; [eexists|]; eauto.\n  all: exfalso; eapply CODOM; split; [eexists|]; eauto.\nQed.\n\n(******************************************************************************)\n(** ** set_map properties *)\n(******************************************************************************)\n\nLemma set_map_union (f : A -> B) : \n  f ⋄₁ (p ∪₁ p') ⊆₁ f ⋄₁ p ∪₁ f ⋄₁ p'.\nProof. basic_solver. Qed.\n\nLemma set_map_inter (f : A -> B) : \n  f ⋄₁ (p ∩₁ p') ⊆₁ f ⋄₁ p ∩₁ f ⋄₁ p'.\nProof. basic_solver. Qed.\n\n(******************************************************************************)\n(** ** set_map/set_collect properties *)\n(******************************************************************************)\n\nLemma collect_map_in_set (f : A -> B) : \n  f □₁ (f ⋄₁ p) ⊆₁ p.\nProof. basic_solver. Qed.\n\nLemma set_in_map_collect (f : A -> B) : \n  s ⊆₁ f ⋄₁ (f □₁ s).\nProof. basic_solver. Qed.\n\n(******************************************************************************)\n(** ** inj_dom properties *)\n(******************************************************************************)\n\nLemma inj_dom_union \n      (f : A -> B)\n      (INJ : inj_dom s f) \n      (INJ' : inj_dom s' f) \n      (DISJ : set_disjoint (f □₁ s) (f □₁ s')) :\n  inj_dom (s ∪₁ s') f. \nProof. \n  unfolder in *. \n  ins; desf; \n    try (by exfalso; eapply DISJ; eauto).\n  { by apply INJ. }\n    by apply INJ'. \nQed.\n\nLemma inj_dom_eq (f : A -> B) (a : A) :\n  inj_dom (eq a) f. \nProof. basic_solver. Qed.\n\nLemma inj_dom_eq_opt (f : A -> B) (a : option A) :\n  inj_dom (eq_opt a) f. \nProof. basic_solver. Qed.\n\n(******************************************************************************)\n(** ** fixset properties *)\n(******************************************************************************)\n\nLemma fixset_union (f : A -> A) : \n  fixset (s ∪₁ s') f <-> fixset s f /\\ fixset s' f.\nProof. clear; unfolder; split; ins; intuition. Qed.\n\nLemma fixset_eq_dom (f g : A -> A) (EQD : eq_dom s f g) : \n  fixset s f <-> fixset s g.\nProof. \n  unfolder in *. \n  split; ins; \n    specialize (EQD x SX);\n    specialize (H x SX);\n    congruence.\nQed.\n\nLemma fixset_set_fixpoint (f : A -> A) : \n  fixset s f -> s ≡₁ f □₁ s.\nProof. \n  autounfold with unfolderDb; unfold set_subset.\n  intros FIX.\n  splits. \n  { ins. eexists. \n    specialize (FIX x). \n    splits; eauto. } \n  ins; desf. \n  erewrite (FIX y); auto. \nQed.\n\nLemma fixset_swap (f' : A -> B) (g' : B -> A) : \n  fixset s (g' ∘ f') -> fixset (f' □₁ s) (f' ∘ g').\nProof.\n  unfolder.\n  intros FIX x [y [DOM Fy]].\n  unfold compose. \n  rewrite <- Fy.\n  fold (compose g' f' y).\n  rewrite FIX; auto. \nQed.\n\n(******************************************************************************)\n(** ** TODO : structure other properties *)\n(******************************************************************************)\n\nLemma seq_eqv : ⦗ s ⦘ ⨾ ⦗ s' ⦘ ≡ ⦗ s ∩₁ s' ⦘.\nProof. basic_solver. Qed.\n\nLemma set_compl_inter_id : set_compl s ∩₁ s ≡₁ ∅.\nProof. basic_solver. Qed.\n\nLemma eq_opt_someE (a : A) : eq_opt (Some a) ≡₁ eq a.\nProof. basic_solver. Qed. \n\nLemma eq_opt_noneE : eq_opt (None : option A) ≡₁ ∅.\nProof. basic_solver. Qed. \n\nLemma empty_irr : r ≡ ∅₂ -> irreflexive r. \nProof. basic_solver. Qed.\n\nLemma restr_fun_fst (f g : A -> B) x : \n  s x -> restr_fun s f g x = f x. \nProof. clear. unfolder. basic_solver. Qed.\n\nLemma restr_fun_snd (f g : A -> B) x : \n  ~ s x -> restr_fun s f g x = g x. \nProof. clear. unfolder. basic_solver. Qed.\n\nLemma set_subset_union_minus : s ⊆₁ s \\₁ s' ∪₁ s'. \nProof. \n  by unfold set_minus, set_union, set_subset; clear; intros; tauto.\nQed.\n\nLemma set_union_minus : s' ⊆₁ s -> s ≡₁ s \\₁ s' ∪₁ s'. \nProof. \n  intros. \n  unfold set_equiv; splits; \n    [by apply set_subset_union_minus|basic_solver].\nQed.\n\nLemma union_minus : r' ⊆ r -> r ≡ r \\ r' ∪ r'.\nProof. \n  intros H.\n  unfold same_relation; splits.\n  { by apply inclusion_union_minus. }\n  basic_solver.\nQed.\n\nLemma minus_eqv_absorb_rr : r' ⨾ ⦗ s ⦘ ≡ ∅₂ -> (r \\ r') ⨾ ⦗ s ⦘ ≡ r ⨾ ⦗ s ⦘.\nProof. \n  unfolder.\n  ins; splits; ins; desf.\n  eexists; splits; eauto. \nQed.\n\nLemma minus_eqv_absorb_rl : ⦗ s ⦘ ⨾ r' ≡ ∅₂ -> ⦗ s ⦘ ⨾ (r \\ r') ≡ ⦗ s ⦘ ⨾ r.\nProof. \n  unfolder.\n  ins; splits; ins; desf.\n  eexists; splits; eauto.\nQed.\n\nLemma minus_disjoint : r ∩ r' ≡ ∅₂ -> r \\ r' ≡ r. \nProof. clear. basic_solver 5. Qed.\n\nLemma cross_minus_compl_l : s × s' \\ (set_compl s) × s'' ≡ s × s'.\nProof. \n  unfolder; splits; ins; splits; desf; unfold not; ins; desf. \nQed.\n\nLemma cross_minus_compl_r : s × s' \\ s'' × (set_compl s') ≡ s × s'.\nProof. \n  unfolder; splits; ins; splits; desf; unfold not; ins; desf. \nQed.\n  \nLemma set_minus_inter_set_compl : s \\₁ s' ≡₁ s ∩₁ set_compl s'.\nProof. basic_solver. Qed.\n\nLemma minus_inter_compl : r \\ r' ≡ r ∩ compl_rel r'.\nProof. basic_solver. Qed.\n\nLemma compl_top_minus : forall (r : relation A), compl_rel r ≡ (fun _ _ => True) \\ r.\nProof. basic_solver. Qed.\n\nLemma minus_union_r : forall (r r' r'': relation A), r \\ (r' ∪ r'') ≡ (r \\ r') ∩ (r \\ r'').\nProof. \n  unfolder; splits; ins; desf; splits; auto.\n  unfold not; basic_solver.\nQed.\n\nLemma compl_union : compl_rel (r ∪ r')  ≡ compl_rel r ∩ compl_rel r'.\nProof. \n  rewrite !compl_top_minus; by apply minus_union_r.\nQed.\n\nLemma seq_eqv_inter : ⦗s⦘ ⨾ (r ∩ r') ⨾ ⦗s'⦘ ≡ (⦗s⦘ ⨾ r ⨾ ⦗s'⦘) ∩ (⦗s⦘ ⨾ r' ⨾ ⦗s'⦘).\nProof. \n  rewrite !seq_eqv_lr. \n  unfold inter_rel.\n  unfold same_relation, inclusion.\n  splits; ins; splits; desf. \nQed.\n\nLemma seq_eqv_inter_rr :\n        r ∩ (r' ⨾ ⦗s⦘) ≡ r ∩ r' ⨾ ⦗s⦘.\nProof. basic_solver. Qed.\n\nLemma map_collect_id (f : A -> B) :\n  r ⊆ f ⋄ (f □ r).\nProof. basic_solver 10. Qed.\n\nLemma set_subset_inter_l (LL : s ⊆₁ s'' \\/ s' ⊆₁ s'') :\n  s ∩₁ s' ⊆₁ s''.\nProof.\n  desf.\n  all: rewrite LL.\n  all: basic_solver.\nQed.\n\nLemma set_minus_remove_l (IN : s ⊆₁ s') :\n  s \\₁ s'' ⊆₁ s'.\nProof. generalize IN. basic_solver. Qed.\n\nLemma restr_set_subset \n      (SUBS : s' ⊆₁ s) \n      (EQ   : restr_rel s r ≡ restr_rel s r') :\n  restr_rel s' r ≡ restr_rel s' r'.\nProof. \n  unfolder in *.\n  destruct EQ as [INCL INCR].\n  splits; ins; splits; desf;\n    [ apply (INCL x y) | apply (INCR x y) ]; \n    auto.\nQed.\n\nLemma restr_set_union :\n  restr_rel (s ∪₁ s') r ≡\n    restr_rel s r ∪ restr_rel s' r ∪\n    ⦗ s ⦘ ⨾ r ⨾ ⦗ s' ⦘ ∪ ⦗ s' ⦘ ⨾ r ⨾ ⦗ s ⦘.\nProof.\n  unfolder.\n    by splits; ins; desf; splits; eauto; left; left; [left|right].\nQed.\n\nLemma restr_set_inter :\n  restr_rel (s ∩₁ s') r ≡ restr_rel s r ∩ restr_rel s' r.\nProof.\n  unfolder.\n  splits; ins; desf. \nQed.\n\nLemma restr_inter_absorb_l :\n  restr_rel s r ∩ restr_rel s r' ≡ r ∩ restr_rel s r'.\nProof. basic_solver. Qed.\n\nLemma restr_inter_absorb_r :\n  restr_rel s r ∩ restr_rel s r' ≡ restr_rel s r ∩ r'.\nProof. basic_solver. Qed.\n\nLemma restr_irrefl_eq (IRRFLX: irreflexive r):\n  forall x:A, (restr_rel (eq x) r) ≡ ∅₂.\nProof. basic_solver. Qed.\n\nLemma restr_clos_trans : (restr_rel s r)⁺ ⊆ restr_rel s r⁺.\nProof.\n  unfold inclusion, restr_rel; ins. \n  induction H; desf; splits; eauto using t_step, t_trans. \nQed.\n\nLemma rt_dom_ri (HH : r ⊆ ⦗ s ⦘ ⨾ r) : r＊ ⨾ ⦗ s ⦘ ⊆ (r ⨾ ⦗ s ⦘)＊.\nProof.\n  rewrite rtE at 1.\n  rewrite seq_union_l.\n  apply inclusion_union_l; [basic_solver|].\n  rewrite HH at 1.\n  rewrite clos_trans_rotl.\n  rewrite !seqA.\n  rewrite <- ct_end.\n  rewrite inclusion_t_rt.\n  basic_solver.\nQed. \n\nLemma restr_clos_trans_eq (Hrestr : r ≡ restr_rel s r) : \n  clos_trans (r) ≡ restr_rel s (clos_trans (r)).\nProof. \n  split; [|basic_solver].\n  rewrite <- restr_clos_trans. \n  by rewrite Hrestr at 1.\nQed.\n\nLemma clos_refl_trans_union_ext (Hrr : r ⨾ r ≡ ∅₂) (Hrr' : r ⨾ r' ≡ ∅₂) : \n  (r ∪ r')＊ ≡ r'＊ ⨾ r^?.\nProof. \n  clear r'' s s' s'' p p' p'' B C.\n  rewrite crE, seq_union_r, seq_id_r.\n  rewrite rt_unionE.\n  rewrite <- cr_of_ct with (r := (r ⨾ r'＊)).\n  rewrite crE, seq_union_r.\n  apply union_more.\n  { basic_solver. }\n  arewrite (r ⨾ r'＊ ≡ r). \n  { rewrite <- cr_of_ct, crE, seq_union_r.\n    arewrite (r ⨾ r'⁺ ≡ ∅₂).\n    { split; [|basic_solver].\n      intros x y HH.  \n      destruct HH as [z [HA HB]].\n      induction HB. \n      { eapply Hrr'. unfolder. eauto. }\n      intuition. }\n    basic_solver. }\n  arewrite (r⁺ ≡ r); auto. \n  split. \n  { intros x y HH. \n    induction HH; auto.  \n    exfalso. eapply Hrr. unfolder. eauto. }\n  red. ins. constructor. auto. \nQed.\n\nLemma clos_trans_union_ext (Hrr : r ⨾ r ≡ ∅₂) (Hrr' : r ⨾ r' ≡ ∅₂) : \n  (r ∪ r')⁺ ≡ r'⁺ ∪ r'＊ ⨾ r.\nProof. \n  rewrite ct_unionE.\n  arewrite ((r ⨾ r'＊)⁺ ≡ r); auto. \n  unfold same_relation; splits.\n  { unfold inclusion; ins. \n    induction H. \n    { eapply seq_rtE_r in H. \n      unfold union in H; desf.\n      repeat unfold seq in *; desf. \n      exfalso. \n      eapply Hrr'. \n      eexists; splits; eauto. }\n    exfalso. \n    eapply Hrr. \n    unfold seq; exists y; splits; eauto. }\n  rewrite seq_rtE_r.\n  unfold inclusion; ins. \n  eapply clos_trans_mori.\n  2: { eapply t_step. eauto. }\n  apply inclusion_union_r1.\nQed.   \n\nLemma set_compl_union_id : s ∪₁ set_compl s ≡₁ ⊤₁.\nProof.\n  split; [basic_solver|].\n  intros x _.\n  destruct (classic (s x)).\n  { by left. }\n    by right.\nQed.\n\nLemma set_split : s' ∪₁ s'' ≡₁ ⊤₁ -> s ≡₁ s ∩₁ s' ∪₁ s ∩₁ s''.\nProof. \n  unfolder. intros [_ HS]. \n  split; [|basic_solver].\n  intros x Sx. \n  specialize (HS x I).\n  basic_solver. \nQed.\n\nLemma set_split_comlete : s' ≡₁ s' ∩₁ s ∪₁ s' ∩₁ (set_compl s).\nProof. \n  (* copy paste of previous lemma because of section variables :( *)\n  unfolder. \n  split; [|basic_solver].\n  intros x Sx. \n  pose proof set_compl_union_id as [_ HH].\n  specialize (HH x I).\n  unfolder in HH.\n  basic_solver. \nQed.\n\nLemma eqv_l_set_compl_eqv_l : r ⊆ ⦗s⦘ ⨾ r ∪ r' -> ⦗set_compl s⦘ ⨾ r ⊆ r'.\nProof. \n  rewrite !seq_eqv_l.\n  intros Hr x y [nSx Rxy].\n  apply Hr in Rxy.\n  unfolder in Rxy. desf.\nQed.\n\nLemma dom_r2l_rt (HH : r ⨾ ⦗s⦘ ⊆ ⦗s⦘ ⨾ r') : r＊ ⨾ ⦗s⦘ ⊆ ⦗s⦘ ⨾ r'＊.\nProof.\n  unfolder in *. ins. desf.\n  induction H.\n  { edestruct HH; eauto. split; auto.\n      by apply rt_step. }\n  { split; auto. apply rt_refl. }\n  destruct IHclos_refl_trans2; auto.\n  destruct IHclos_refl_trans1; auto.\n  split; auto.\n  eapply transitive_rt; eauto.\nQed.\n\nLemma inter_trans : transitive r -> transitive r' -> transitive (r ∩ r').\nProof. \n  clear.\n  unfolder.\n  intros TR TR' x y z.\n  specialize (TR x y z).\n  specialize (TR' x y z).\n  intuition.\nQed.\n\nLemma immediate_in : immediate r ⊆ r. \nProof. basic_solver. Qed.\n\nLemma immediate_inter : \n  (immediate r) ∩ r' ⊆ immediate (r ∩ r').\nProof. basic_solver. Qed.\n\nLemma immediate_transp :\n  (immediate r)⁻¹ ≡ immediate (r⁻¹).\nProof. basic_solver. Qed.\n\nLemma trans_prcl_immediate_seqr_split x y\n      (TRANS : transitive r) (PRCL : downward_total r) (IMM : (immediate r) x y) :\n  r ⨾ ⦗ eq y ⦘ ≡ (eq x ∪₁ dom_rel (r ⨾ ⦗ eq x ⦘)) × eq y.\nProof. \n  red; split. \n  { unfolder.\n    intros z y' [Rzy EQy].\n    split; auto.\n    assert (r^= z x) as Rzx. \n    { eapply PRCL; eauto; desf.  \n      by apply immediate_in. }\n    unfolder in *.\n    unfold clos_refl_sym in Rzx.\n    desf; eauto. \n    exfalso. eapply IMM0; eauto. }\n  unfolder.  ins. desf.\n  { splits; desf.\n    by apply immediate_in. }\n  splits; desf. \n  eapply TRANS; eauto. \n  by apply immediate_in.\nQed. \n\nLemma clos_refl_trans_ind_step_left \n        (R : relation A) (P : A -> Prop) x y (Px : P x)\n        (rtR : R＊ x y)\n        (STEP : forall z z', P z -> R z z' -> R＊ z' y -> P z') :\n    P y.\nProof. \n  generalize dependent Px.\n  induction rtR; auto.\n  { intros Px.\n    specialize (STEP x y).\n    apply STEP; auto.\n    apply rt_refl. }\n  intros Px.\n  apply IHrtR2; auto.\n  apply IHrtR1; auto.\n  ins. eapply STEP; eauto.\n  eapply rt_trans; eauto.\nQed.\n\nLemma set_equiv_exp_equiv :\n  s ≡₁ s' <-> forall x : A, s x <-> s' x.\nProof.\n  split.\n  { apply set_equiv_exp. }\n  intros HH. by split; red; ins; apply HH.\nQed.\n\nLemma minus_eqv_r : r ⨾ ⦗ s ⦘ \\ r' ≡ (r \\ r') ⨾ ⦗ s ⦘.\nProof.\nbasic_solver 21.\nQed.\n\nEnd Props.\n\nRequire Import Setoid.\n\nAdd Parametric Morphism A : (@symmetric A) with signature\n  same_relation ==> iff as symmetric_more.\nProof. unfolder. ins. desf. split; ins; auto. Qed.\n\nAdd Parametric Morphism A : (@clos_sym A) with signature \n  inclusion ==> inclusion as clos_sym_mori.\nProof. basic_solver. Qed.\n\nAdd Parametric Morphism A : (@clos_sym A) with signature \n  same_relation  ==> same_relation as clos_sym_more.\nProof. basic_solver. Qed.\n\nAdd Parametric Morphism A : (@clos_refl_sym A) with signature \n  inclusion ==> inclusion as clos_refl_sym_mori.\nProof. basic_solver. Qed.\n\nAdd Parametric Morphism A : (@clos_refl_sym A) with signature \n  same_relation  ==> same_relation as clos_refl_sym_more.\nProof. basic_solver. Qed.\n\nAdd Parametric Morphism A : (@compl_rel A) with signature \n  same_relation ==> same_relation as compl_more.\nProof. red; unfolder; splits; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A : (@compl_rel A) with signature \n  inclusion --> inclusion as compl_mori.\nProof. red; unfolder; splits; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A : (@downward_total A) with signature \n    same_relation ==> iff as downward_total_more.\nProof. \n  intros x y EQ. unfold downward_total. split; ins.\n  eapply clos_refl_sym_more; [symmetry|]; eauto.\n  2: eapply clos_refl_sym_more; eauto.\n  all: apply EQ in Rxz.\n  all: apply EQ in Ryz.\n  all: eapply H; eauto.\nQed.\n\nAdd Parametric Morphism A B : (@eq_dom A B) with signature \n    set_equiv ==> eq ==> eq ==> iff as eq_dom_more.\nProof. \n  intros s s' Heq f g. \n  unfold eq_dom. \n  split; ins; \n    specialize (H x); \n    apply H; auto; \n    apply Heq; auto.\nQed.\n\nAdd Parametric Morphism A B : (@eq_dom A B) with signature \n    set_subset --> eq ==> eq ==> impl as eq_dom_mori.\nProof. basic_solver. Qed.\n\nAdd Parametric Morphism A B : (@inj_dom A B) with signature \n    set_equiv ==> eq ==> iff as inj_dom_more.\nProof. \n  intros s s' Heq f. red. \n  unfold inj_dom in *.\n  splits; ins; specialize (H x y); apply H; auto; apply Heq; auto.\nQed.\n\nAdd Parametric Morphism A B : (@inj_dom A B) with signature \n  set_subset --> eq ==> impl as inj_dom_mori.\nProof. basic_solver. Qed.\n\nAdd Parametric Morphism A : (@fixset A) with signature \n    set_equiv ==> eq ==> iff as fixset_more.\nProof. \n  intros s s' Heq f. red. \n  unfold fixset.\n  splits; ins; specialize (H x); apply H; auto; apply Heq; auto.\nQed.\n\nAdd Parametric Morphism A : (@fixset A) with signature \n  set_subset --> eq ==> impl as fixset_mori.\nProof. unfold impl, fixset. basic_solver. Qed.\n\nAdd Parametric Morphism A : (@set_compl A) with signature \n  set_equiv ==> set_equiv as set_compl_more.\nProof. red; unfolder; splits; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A : (@set_compl A) with signature \n  set_subset --> set_subset as set_compl_mori.\nProof. red; unfolder; splits; 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. red; unfolder; splits; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A B : (@set_collect A B) with signature \n  eq ==> set_subset ==> set_subset as set_collect_mori.\nProof. red; unfolder; 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. red; unfolder; 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. red; unfolder; splits; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A : (@dom_rel A) with signature\n   inclusion ==> set_subset as dom_rel_mori.\nProof. red; unfolder; splits; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A : (@dom_rel A) with signature\n   same_relation ==> set_equiv as dom_rel_more.\nProof. red; unfolder; splits; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A : (@codom_rel A) with signature\n   inclusion ==> set_subset as codom_rel_mori.\nProof. red; unfolder; splits; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A : (@codom_rel A) with signature\n   same_relation ==> set_equiv as codom_rel_more.\nProof. red; unfolder; splits; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A : (@set_minus A) with signature \n  set_equiv ==> set_equiv ==> set_equiv as set_minus_more.\nProof. red; unfolder; splits; ins; desf; split; eauto. Qed.\n\nAdd Parametric Morphism A : (@set_minus A) with signature \n  set_subset ==> set_subset --> set_subset as set_minus_mori.\nProof. red; unfolder; splits; ins; desf; eauto. Qed.\n", "meta": {"author": "weakmemory", "repo": "promising2ToImm", "sha": "8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c", "save_path": "github-repos/coq/weakmemory-promising2ToImm", "path": "github-repos/coq/weakmemory-promising2ToImm/promising2ToImm-8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c/src/lib/AuxRel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117812622843, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.6556700336331355}}
{"text": "\nFrom mathcomp\n     Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict  Implicit.\nImport Prenex Implicits.\n\nDefinition mySet (M : Type) := M -> Prop.\nDefinition belong {M : Type} (A : mySet M) (x : M) :\n  Prop := A x.\n\nNotation \"x ∈ A\" := (belong A x) (at level 11).\n\nAxiom axiom_mySet : forall (M :Type) (A : mySet M),\n    forall (x : M), (x ∈ A) \\/ ~(x ∈ A).\n\nDefinition myEmptySet  {M : Type} : mySet M := fun _ => False.\nDefinition myMotherSet {M : Type} : mySet M := fun _ => True.\n\nDefinition mySub {M} :=\n  fun (A B : mySet M) => (forall (x : M), (x ∈ A) -> (x ∈ B)).\nNotation \"A ⊂ B\" := (mySub A B) (at level 11).\n\nSection Relation_Of_Inclustion.\n  Variable M : Type.\n\n  Lemma Sub_Mother (A : mySet M) : A ⊂ myMotherSet.\n  Proof. by []. Qed.\n\n  Lemma Sub_Empty (A : mySet M) : myEmptySet ⊂ A.\n  Proof. by []. Qed.\n\n  Lemma rfl_Sub (A : mySet M) : (A ⊂ A).\n  Proof. by []. Qed.\n\n  Lemma transitive_Sub (A B C : mySet M):\n    (A ⊂ B) -> (B ⊂ C) -> (A ⊂ C).\n  Proof.\n    move => H1 H2 t H3.\n    apply: H2.\n    apply: H1.\n    apply: H3.\n  Qed.\n\nEnd Relation_Of_Inclustion.\n\nDefinition eqmySet {M : Type} :=\n    fun (A B : mySet M) => (A ⊂ B /\\ B ⊂ A).\nAxiom axiom_ExteqmySet : forall {M :Type} (A B : mySet M), eqmySet A B -> A = B.\n\nSection equal_sign.\n  Variable Mother : Type.\n\n  Lemma rfl_eqS (A : mySet Mother) : A = A.\n  Proof. by []. Qed.\n\n  Lemma sym_eqS (A B : mySet Mother) : A = B -> B = A.\n  Proof.\n    move => H.\n    rewrite H.\n    apply rfl_eqS.\n  Qed.\nEnd equal_sign.\n\nDefinition myComplement {M :Type} (A : mySet M) : mySet M :=\n  fun (x : M) => ~(A x).\nNotation \"A ^c\" := (myComplement A) (at level 11).\n\nDefinition myCup {M : Type} (A B : mySet M) : mySet M :=\n  fun (x : M) => (x ∈ A) \\/ (x ∈ B).\n\nNotation \"A ∪ B\" := (myCup A B) (at level 11).\n\nDefinition myCap {M : Type} (A B : mySet M) : mySet M :=\n  fun (x : M) => (x ∈ A) /\\ (x ∈ B).\n\nNotation \"A ∩ B\" := (myCap A B) (at level 11).\n\nDefinition mySetDiff {M : Type} (A B : mySet M) : mySet M :=\n  fun (x : M) => (x ∈ A) /\\ (x ∈ (myComplement B)).\n\nNotation \"A \\ B\" := (mySetDiff A B) (at level 11).\n\nSection Set_Operation.\n  Variable M : Type.\n\n  Lemma cEmpty_Mother: (@myEmptySet M)^c = myMotherSet.\n  Proof.\n    apply: axiom_ExteqmySet.\n    rewrite /eqmySet.\n    apply conj.\n    rewrite /mySub /myComplement //.\n    rewrite /mySub.\n    move => x Hfull.\n    rewrite /belong.\n    rewrite /myMotherSet /belong in Hfull.\n    rewrite /myComplement /myEmptySet.\n      by [].\n  Qed.\n\n  Lemma cc_cancel (A : mySet M) : (A^c)^c = A.\n  Proof.\n    apply: axiom_ExteqmySet; rewrite /eqmySet.\n    apply: conj.\n    rewrite /mySub /myComplement => x H //.\n    move : (axiom_mySet A x); by case.\n    rewrite /mySub /myComplement => x H //.\n  Qed.\n\n  Lemma cMother_Empty: (@myMotherSet M)^c = myEmptySet.\n  Proof.\n    rewrite -cEmpty_Mother.\n    rewrite cc_cancel.\n    by [].\n  Qed.\n\n  Lemma myUnionCompMother (A : mySet M) : A ∪ (A^c) = myMotherSet.\n  Proof.\n    apply: axiom_ExteqmySet.\n    rewrite /eqmySet /mySub; apply: conj => [x | x H1].\n    -by case.\n    -case: (axiom_mySet A x).\n     move => HAx.\n     apply: or_introl; apply HAx.\n     move => HAx.\n     by apply: or_intror.\n  Qed.\n\n  Lemma myIntersectionCompEmpty (A : mySet M) : A ∩ (A^c) = myEmptySet.\n  Proof.\n    apply: axiom_ExteqmySet.\n    rewrite /eqmySet /mySub.\n    split => x.\n    case => HA HnA.\n    rewrite /myEmptySet.\n    apply: HnA HA.\n    by [].\n  Qed.\n\n  Lemma myCupUnionRule (A B C : mySet M) : (A ∪ B) ∪ C = A ∪ (B ∪ C).\n  Proof.\n    apply: axiom_ExteqmySet.\n    rewrite /eqmySet.\n    apply conj => x [H1 | H2].\n    -case H1 => t.\n     apply: or_introl; apply t.\n     apply: or_intror; apply: or_introl; apply t.\n     apply: or_intror; apply: or_intror; apply H2.\n     apply: or_introl; apply: or_introl; apply H1.\n    -case H2 => t.\n     apply: or_introl; apply: or_intror; apply t.\n     apply: or_intror; apply t.\n  Qed.\n\n  Lemma myCapUnionRule (A B C: mySet M) : A ∩ (B ∩ C) = (A ∩ B) ∩ C.\n  Proof.\n    apply: axiom_ExteqmySet.\n    rewrite /eqmySet.\n    apply: conj => x [H1 H2].\n    apply conj. apply conj.\n    apply: H1.\n    move: H2; by case.\n    move: H2; by case.\n    apply: conj.\n    move: H1; by case.\n    apply: conj.\n    move: H1; by case.\n    by [].\n  Qed.\n\n  Lemma mySetCommutativeCup (A B: mySet M): A ∪ B = B ∪ A.\n  Proof.\n    apply: axiom_ExteqmySet.\n    rewrite /eqmySet.\n    split => t.\n    case => H1.\n      by right. by left.\n    case => H1.\n      by right. by left.\n  Qed.\n\n  Lemma mySetCommutativeCap (A B: mySet M): A ∩ B = B ∩ A.\n  Proof.\n    apply: axiom_ExteqmySet.\n    rewrite /eqmySet.\n    split => t.\n    case => H1 H2.\n    split; by[].\n    case => H1 H2.\n    split; by [].\n  Qed.\n\n  Lemma myCapDistributeRule (A B C: mySet M): A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C).\n  Proof.\n    apply: axiom_ExteqmySet.\n    rewrite /eqmySet.\n    split; move => t.\n    case => H1.\n    case => H2.\n    left; split; by [].\n    right; split; by [].\n    case; case => H1 H2.\n    split. by [].\n    left. by [].\n    split. by [].\n    right. by[].\n  Qed.\n\n  Lemma mySetDemorgan_1 (A B: mySet M): (A ∪ B)^c = (A^c) ∩ (B^c).\n  Proof.\n    apply: axiom_ExteqmySet.\n    rewrite /eqmySet.\n    split.\n    move => x HABc.\n    split.\n    rewrite /myComplement /not.\n    move => H1.\n    apply: HABc.\n    left.\n    apply H1.\n    rewrite /myComplement /not.\n    move => H1.\n    apply: HABc.\n    by right.\n    move => x.\n    case => H1 H2 H3.\n    apply: H1.\n    by case: H3.\n  Qed.\n\n  Lemma mySetDemorgan_2 (A B: mySet M): (A ∩ B)^c = (A^c) ∪ (B^c).\n    move: (cc_cancel ((A^c) ∪ (B^c))) (cc_cancel (A ∩ B)).\n    move => Hcc_cancel_or Hcc_cancel_and.\n    apply: axiom_ExteqmySet.\n    rewrite /eqmySet.\n    split.\n    rewrite -Hcc_cancel_and -Hcc_cancel_or.\n    rewrite mySetDemorgan_1.\n    rewrite Hcc_cancel_and.\n    rewrite cc_cancel cc_cancel.\n      by [].\n    rewrite -Hcc_cancel_or.\n    rewrite mySetDemorgan_1.\n    rewrite cc_cancel cc_cancel.\n      by [].\n  Qed.\n\n  Lemma mySetDiffSelfEmpty (A: mySet M): A \\ A = myEmptySet.\n  Proof.\n    rewrite -(myIntersectionCompEmpty A).\n    by rewrite /mySetDiff.\n  Qed.\n\n  Lemma mySetDiffEq (A B: mySet M): B \\ A = A^c ∩ B.\n  Proof.\n    rewrite -mySetCommutativeCap.\n    by rewrite /mySetDiff /myCap.\n  Qed.\n\n  Lemma mySetDiffComplement (A B: mySet M): (B \\ A)^c = A ∪ (B^c).\n  Proof.\n    move: (cc_cancel (A ∪ (B^c))).\n    move => H1.\n    rewrite -H1.\n    rewrite mySetDemorgan_1 cc_cancel mySetDiffEq.\n      by [].\n  Qed.\n\n  Lemma mySetDiffDistCap (A B C: mySet M): C \\ (A ∩ B) = (C \\ A) ∪ (C \\ B).\n  Proof.\n    rewrite mySetDiffEq mySetDemorgan_2.\n    rewrite mySetCommutativeCap.\n    rewrite myCapDistributeRule.\n      by rewrite mySetDiffEq mySetCommutativeCap.\n  Qed.\n\nEnd Set_Operation.\n\nDefinition myMap {M1 M2 : Type} (A: mySet M1) (B: mySet M2) (f: M1 -> M2) :=\n  (forall (x : M1), (x ∈ A) -> ((f x) ∈ B)).\nNotation \"f |: A |→ B\" := (myMap A B f) (at level 11).\n\nDefinition MapCompsite {M1 M2 M3: Type} (f: M2 -> M3) (g: M1 -> M2): M1 -> M3 := fun (x: M1) => f (g x).\n\nNotation \"f ・ g\" := (MapCompsite f g) (at level 11).\n\n(* 像の形式化 *)\nDefinition ImgOf\n           {M1 M2 : Type} (f: M1 -> M2)\n           {A : mySet M1} {B : mySet M2} (_ : f |: A |→ B) : mySet M2 :=\n  fun (y : M2) => (exists (x : M1), y = f x /\\ x ∈ A).\n\n(* 単射の形式化 *)\nDefinition mySetInj {M1 M2 : Type} (f: M1 -> M2) (A : mySet M1) (B : mySet M2) (_ : f |: A |→ B) :=\n  forall (x y : M1), (x ∈ A) -> (y ∈ A) -> (f x = f y) -> (x = y).\n(* 全射の形式化 *)\nDefinition mySetSur {M1 M2 : Type} (f: M1 -> M2) (A : mySet M1) (B : mySet M2) (_ : f |: A |→ B) :=\n  forall (y : M2), (y ∈ B) -> (exists (x : M1), (x ∈ A) -> (f x = y)).\n(* 全単射の形式化 *)\nDefinition mySetBi {M1 M2 : Type} (f: M1 -> M2) (A : mySet M1) (B : mySet M2) (fAB : f |: A |→ B) :=\n  (mySetInj fAB) /\\ (mySetSur fAB).\n\nDefinition myMapId {M : Type} (A: mySet M) (f: M -> M) :=\n  forall (x : M), (x ∈ A) -> (x = f x).\n\n(* formalize of inverse mapping. g is inverse mapping of f. *)\n\n\nSection Mapping.\n  Variables M1 M2 M3 : Type.\n  Variable f : M2 -> M3.\n  Variable g : M1 -> M2.\n  Variable A : mySet M1.\n  Variable B : mySet M2.\n  Variable C : mySet M3.\n  Hypothesis gAB : g |: A |→ B.\n  Hypothesis fBC : f |: B |→ C.\n\n  Lemma transitive_Inj (fgAC : (f ・ g) |: A |→ C) :\n    mySetInj fBC -> mySetInj gAB -> mySetInj fgAC.\n  Proof.\n    rewrite /mySetInj => Hinjf Hinjg x y HxA HyA H.\n    apply: (Hinjg x y HxA HyA).\n    apply: (Hinjf (g x) (g y)).\n    apply: gAB HxA.\n    apply: gAB HyA.\n    apply: H.\n  Qed.\n\n  Lemma CompoTrans : (f ・ g) |: A |→ C.\n  Proof.\n    move: gAB fBC.\n    rewrite /MapCompsite /myMap => Hab Hbc t Ha.\n    move: (Hbc (g t) (Hab t Ha)).\n      by [].\n  Qed.\n\n  Lemma ImSub : (ImgOf gAB) ⊂ B.\n  Proof.\n    rewrite /mySub => x; case => x0; case => H1 H2.\n    rewrite H1; apply: gAB; apply: H2.\n  Qed.\n\nEnd Mapping.\n\nSection MappingProblem.\n  Variables M1 M2 : Type.\n  Variable f : M1 -> M2.\n  Variable g : M2 -> M1.\n  Variable idM1 : M1 -> M1.\n  Variable idM2 : M2 -> M2.\n  Variables A A1 A2 : mySet M1.\n  Variables B B1 B2 B3 B4 B5 : mySet M2.\n  Hypothesis fAB : f |: A |→ B.\n  Hypothesis gBA : g |: B |→ A.\n  Hypothesis fA1B1 : f |: A1 |→ B1.\n  Hypothesis fA2B2 : f |: A2 |→ B2.\n  Hypothesis fA1cupA2_B3 : f |: (A1 ∪ A2) |→ B3.\n  Hypothesis fA1capA2_B4 : f |: (A1 ∩ A2) |→ B4.\n  Hypotheses fAdiffA1_B5: f |: (A \\ A1) |→ B5.\n  Hypotheses idA : myMapId A idM1.\n  Hypotheses idB : myMapId B idM2.\n\n  (* A1 ⊂ A2 ならば f(A1) ⊂ f(A2) *)\n  Lemma ImgSub: A1 ⊂ A2 -> (ImgOf fA1B1) ⊂ (ImgOf fA2B2).\n  Proof.\n    rewrite /mySub => HS.\n    move => x.\n    case => x0; case => H1 H2.\n    rewrite /ImgOf.\n    exists x0.\n    split.\n    apply: H1.\n    apply: HS.\n    apply: H2.\n  Qed.\n\n  (* f(A1 ∪ A2) = f(A1) ∪ f(A2) *)\n  Lemma ImgCup: (ImgOf fA1cupA2_B3) = (ImgOf fA1B1) ∪ (ImgOf fA2B2).\n  Proof.\n    apply: axiom_ExteqmySet.\n    rewrite /eqmySet.\n    split.\n    rewrite /mySub /ImgOf.\n    move => x.\n    case => x0.\n    case => H1.\n    case => H2.\n    +left.\n     exists x0; split.\n     apply: H1.\n     apply: H2.\n    +right.\n     exists x0; split.\n     apply: H1.\n     apply: H2.\n    rewrite /mySub /ImgOf.\n    move => x.\n    case; case => x0; case => fx H1; exists x0.\n    split.\n    apply: fx.\n    left; by [].\n    split.\n    apply: fx.\n    right; by[].\n  Qed.\n\n  (* f(A1 ∩ A2) ⊂ f(A1) ∩ f(A2) *)\n  Lemma ImgCap: (ImgOf fA1capA2_B4) ⊂ ((ImgOf fA1B1) ∩ (ImgOf fA2B2)).\n  Proof.\n    rewrite /mySub.\n    move => x.\n    case => x0.\n    case => fx.\n    case => H1 H2.\n    rewrite /ImgOf.\n    split; exists x0.\n    split.\n    apply: fx.\n    apply: H1.\n    split.\n    apply: fx.\n    apply: H2.\n  Qed.\n\n  (* A1 ⊂ A2 -> A2^c ⊂ A1^c *)\n  Lemma Contraposition: A1 ⊂ A2 -> (A2^c) ⊂ (A1^c).\n  Proof.\n    rewrite /mySub /myComplement /not /belong.\n    move => H1 x H2 H3.\n    apply /H2 /(H1 x) /H3.\n  Qed.\n\n  (* A1 ⊂ A -> f(A)\\f(A1) ⊂ f(A\\A1) *)\n  Lemma diffImgOf: A1 ⊂ A -> (ImgOf fAB) \\ (ImgOf fA1B1) ⊂ (ImgOf fAdiffA1_B5).\n  Proof.\n    rewrite /mySub /mySetDiff /belong /ImgOf /myComplement /not.\n    move => H1 x2.\n    case.\n    case.\n    move => x1.\n    case.\n    move => H2 H3 H4.\n    exists x1.\n    split.\n    apply /H2.\n    split.\n    apply /H3.\n    move => H5.\n    apply /H4.\n    exists x1.\n    split.\n    -apply /H2.\n    -apply /H5.\n  Qed.\n\n  Lemma diffImgOf': (ImgOf fAB) \\ (ImgOf fA1B1) ⊂ (ImgOf fAdiffA1_B5).\n  Proof.\n    rewrite /mySub /mySetDiff /belong /ImgOf /myComplement /not.\n    move => x2.\n    case.\n    case.\n    move => x1.\n    case.\n    move => H1 H2.\n    exists x1.\n    split.\n    -apply: H1.\n     split.\n     apply: H2.\n     move => H3.\n    -apply: b.\n     exists x1.\n     split.\n     +apply: H1.\n      apply: H3.\n  Qed.\n\n  Lemma Identity_Compsite_R: (myMapId A idM1) -> (f ・ idM1) |: A |→ B.\n  Proof.\n    rewrite /myMapId /MapCompsite.\n    move => H1 x1 H2.\n    rewrite -H1.\n    apply : fAB.\n    apply /H2.\n    apply /H2.\n  Qed.\n\n  Lemma Identity_Compsite_L: (myMapId B idM2) -> (idM2 ・ f) |: A |→ B.\n  Proof.\n    rewrite /myMapId /MapCompsite.\n    move => H1 x1 H2.\n    rewrite -H1; apply: fAB; apply: H2.\n  Qed.\n\nEnd MappingProblem.\n\nVariable M :finType.\n\nDefinition p2S (pA: pred M) : mySet M :=\n  fun (x : M) => if (x \\in pA) then True else False.\n\nNotation \"\\{ x 'in' pA \\}\" := (p2S pA).\n\nSection finiteSet_UsingFintype.\n  Lemma Mother_predT : myMotherSet = \\{ x in M \\}.\n  Proof.\n      by [].\n  Qed.\n\n  Lemma myFinBelongP (x : M) (pA : pred M): reflect (x ∈ \\{ x in pA \\}) (x \\in pA).\n  Proof.\n    rewrite /belong /p2S; apply/ (iffP idP) => H1.\n    -by rewrite (_ : (x \\in pA) = true).\n     -+have testH : (x \\in pA) || ~~(x \\in pA).\n     set t := x \\in pA.\n       by case: t.\n     move: testH.\n     case/orP => [| Harg]; first by [].\n     rewrite (_ : (x \\in pA) = false) in H1; first by [].\n     by apply : negbTE.\n  Qed.\n\n  Lemma myFinSubsetP (pA pB : pred M) :\n    reflect (\\{ x in pA \\} ⊂ \\{ x in pB \\}) (pA \\subset pB).\n  Proof.\n    rewrite /mySub; apply/ (iffP idP) => H.\n    -move => x /myFinBelongP => H2.\n     apply /myFinBelongP.\n     move: H => /subsetP.\n       by rewrite /sub_mem; apply.\n    -apply/ subsetP.\n     rewrite /sub_mem=> x /myFinBelongP => HpA.\n       by apply/ myFinBelongP; apply H.\n  Qed.\n\n  Lemma Mother_Sub (pA : pred M) :\n    myMotherSet ⊂ \\{ x in pA \\} -> forall x, x ∈ \\{ x in pA \\}.\n  Proof.\n    rewrite Mother_predT => /myFinSubsetP => H x; apply /myFinBelongP.\n      by apply: predT_subset.\n  Qed.\n\n  Lemma transitive_Sub' (pA pB pC : pred M):\n    \\{ x in pA \\} ⊂ \\{ x in pB \\} ->\n    \\{ x in pB \\} ⊂ \\{ x in pC \\} ->\n    \\{ x in pA \\} ⊂ \\{ x in pC \\}.\n  Proof.\n    move /myFinSubsetP => HAB /myFinSubsetP => HBC.\n    apply /myFinSubsetP /(subset_trans HAB HBC).\n  Qed.\n\n  Lemma transitive_Sub'' (pA pB pC : pred M):\n    \\{ x in pA \\} ⊂ \\{ x in pB \\} ->\n    \\{ x in pB \\} ⊂ \\{ x in pC \\} ->\n    \\{ x in pA \\} ⊂ \\{ x in pC \\}.\n  Proof.\n    apply: transitive_Sub.\n  Qed.\nEnd finiteSet_UsingFintype.", "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/formalizing_set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6556619491336645}}
{"text": "(** * Unit Interval Lemmas *)\n\nRequire Export Reals.\nRequire Export Psatz.\n\nOpen Scope R_scope.\n\nLemma mult_by_lt_1 : forall a b c,\n  0 < a < 1 ->\n  0 < b < 1 ->\n  0 < c < 1 -> \n  a = b*c ->\n  a < b.\nProof.\n  intros.\n  assert (c < 1). lra.\n  assert (/ 1 <  / c). apply Rinv_lt_contravar; lra.  \n  assert (a * / 1 < a * / c). apply Rmult_lt_compat_l; lra.\n  assert (a * / 1 < b * c * / c). rewrite <- H2. assumption. \n  rewrite Rmult_assoc in H6. \n  rewrite Rinv_r in H6; lra.\nQed.\n\nLemma plus_by_gt_0 : forall a b c,\n  0 < c < 1 ->\n  a = b + c ->\n  b < a.\nProof.\n  intros.\n  rewrite H0.\n  lra.\nQed.  \n\nLemma one_minus_p : forall a,\n  0 < a < 1 ->\n  0 < 1 - a < 1.\nProof.\n  intro. lra.\nQed.\n\nLemma negation_flip : forall a b,\n  a < b ->\n  (1-a) > (1-b).\nProof.\n  intros.\n  apply Ropp_gt_contravar in H.\n  apply Rplus_gt_compat_l with (r:=1) in H.\n  unfold Rminus; assumption.\nQed.\n\nLemma divide_by_lt : forall a b,\n  0 < a < 1 ->\n  0 < b < 1 ->\n  a < b ->\n  0 < a / b < 1.\nProof.\n  intros.\n  apply Rmult_lt_compat_r with (r:= /b) in H1.\n  rewrite Rinv_r in H1; try lra.\n  assert (0 < a * / b). apply Rmult_lt_0_compat; try lra.\n  apply Rinv_0_lt_compat; lra.\n  lra.\n  apply Rinv_0_lt_compat; lra.\nQed.\n\nLemma mult_stable: forall a b,\n  0 < a < 1 ->\n  0 < b < 1 ->\n  0 < a * b < 1.\nProof. \n  intros. \n  assert (0<a*b).\n  apply Rmult_lt_0_compat; lra.\n  assert (a*b < 1*1).\n  apply Rmult_gt_0_lt_compat; lra.\n  lra.\nQed.\n\nLemma mult_lt_0_compat : forall p a,\n  0 < p < 1 ->\n  (0 < a <-> 0 < p * a).\nProof.\n  split; intros.\n  + apply Rmult_lt_0_compat; lra.\n  + apply Rlt_gt in H0.\n    apply Rmult_gt_compat_l with (r:=/p) in H0.\n    rewrite <- Rmult_assoc in H0.\n    rewrite Rinv_l in H0; lra.\n    apply Rinv_0_lt_compat. lra.\nQed.\n\nLemma mult_le_0_compat : forall p a,\n  0 < p < 1 ->\n  (0 <= a <-> 0 <= p * a).\nProof.\n  split; intros.\n  + apply Rmult_le_pos; lra.\n  + apply Rle_ge in H0.\n    apply Rmult_ge_compat_l with (r:=/p) in H0.\n    rewrite <- Rmult_assoc in H0.\n    rewrite Rinv_l in H0; lra.\n    destruct H. \n    apply Rinv_0_lt_compat in H. lra.\nQed.\n\nLemma in_0_1_open : forall p a b,\n  0 < p < 1 ->\n  0 < a < 1 ->\n  0 < b < 1 ->\n  0 < p * a + (1 - p) * b < 1.\nProof.\n  intros.\n  destruct H.\n  apply conj.\n  + apply Rplus_lt_0_compat.\n    apply Rmult_lt_0_compat; lra. \n    apply Rmult_lt_0_compat; lra. \n  + destruct Rle_or_lt with (r1:=a) (r2:=b).\n    - assert (p * b + (1 - p) * b < 1). lra. \n      assert (p * a <= p * b). \n      eapply Rmult_le_compat_l; lra.\n      lra.\n    - assert (p * a + (1 - p) * a < 1). lra. \n      assert ((1- p) * b <= (1 - p) * a). \n      eapply Rmult_le_compat_l; lra.\n      lra.\nQed.\n\nLemma in_0_1_closed : forall p a b,\n  0 < p < 1 ->\n  0 <= a <= 1 ->\n  0 <= b <= 1 ->\n  0 <= p * a + (1 - p) * b <= 1.\nProof.\n  intros.\n  destruct H.\n  apply conj.\n  + apply Rplus_le_le_0_compat.\n    apply Rmult_le_pos; lra.\n    apply Rmult_le_pos; lra.\n  + destruct Rle_or_lt with (r1:=a) (r2:=b).\n    - assert (p * b + (1 - p) * b <= 1). lra. \n      assert (p * a <= p * b). \n      eapply Rmult_le_compat_l; lra.\n      lra.\n    - assert (p * a + (1 - p) * a <= 1). lra. \n      assert ((1- p) * b <= (1 - p) * a). \n      eapply Rmult_le_compat_l; lra.\n      lra.\nQed.\n\nLemma sum_to_0 : forall p a b,\n 0 < p < 1 ->\n 0 <= a <= 1 ->\n 0 <= b <= 1 ->\n( p * a + (1-p) * b = 0 <-> (a = 0 /\\ b = 0) ).\nProof. \n  split; intros.\n  + assert (0 * a <= p * a). \n    apply Rmult_le_compat_r; lra. rewrite Rmult_0_l in H3.\n    assert (0 * b <= (1-p) * b). \n      apply Rmult_le_compat_r; lra. rewrite Rmult_0_l in H4.\n    assert  (p * a = 0). lra.\n    assert ((1 - p) * b = 0). lra.\n    split.\n    apply Rmult_integral in H5. lra.\n    apply Rmult_integral in H6. lra.\n  + destruct H2.\n    rewrite H2, H3.\n    lra.\nQed.\n\n\nLemma sum_to_1 : forall p a b,\n 0 < p < 1 ->\n 0 <= a <= 1 ->\n 0 <= b <= 1 ->\n( p * a + (1-p) * b = 1 <-> (a = 1 /\\ b = 1) ).\nProof.\n  split; intros.\n  + destruct H.\n    assert (a < 1 \\/ a = 1). lra.\n    assert (b < 1 \\/ b = 1). lra.\n    destruct H4, H5.\n  (* First 3 cases contradict premise H *)\n    - apply Rmult_lt_compat_l with (r:=p) in H4; trivial.\n      rewrite Rmult_1_r in H4.\n      apply Rmult_lt_compat_l with (r:=(1-p)) in H5; try lra.\n    - apply Rmult_lt_compat_l with (r:=p) in H4; trivial.\n      rewrite Rmult_1_r in H4.\n      rewrite H5 in H2. rewrite Rmult_1_r in H2.\n      lra.\n    - apply Rmult_lt_compat_l with (r:=(1-p)) in H5; try lra.\n      rewrite Rmult_1_r in H5.\n      rewrite H4 in H2. rewrite Rmult_1_r in H2.\n      lra.\n    - lra.\n  + destruct H2.\n    rewrite H2, H3.\n    lra.\nQed.\n\n(* Connected to some_state_true *)\n\nLemma sum_to_gt_0 : forall p a b,\n 0 < p < 1 ->\n 0 <= a <= 1 ->\n 0 <= b <= 1 ->\n( 0 < p * a + (1-p) * b <-> (0 < a \\/ 0 < b) ).\nProof.\n  split; intros.\n  + assert (0 < p * a \\/ 0 < (1-p) * b). lra.\n    destruct H3.\n    - left.\n      apply mult_lt_0_compat with (p:=p) (a:=a); assumption.\n    - right.\n      apply mult_lt_0_compat with (p:=(1-p)) (a:=b); lra.\n  + destruct H2.\n    - apply mult_lt_0_compat with (p:=p) in H2; trivial.\n      destruct H1.\n      apply mult_le_0_compat with (p:=(1-p)) in H1; lra.\n    - apply mult_lt_0_compat with (p:=(1-p)) in H2; try lra.\n      destruct H0.\n      apply mult_le_0_compat with (p:=p) in H0; try lra.\nQed.\n    \n(*\n\nLemma sum_to_lt_1 : forall p a b,\n 0 < p < 1 ->\n 0 <= a <= 1 ->\n 0 <= b <= 1 ->\n( p * a + (1-p) * b < 1 <-> (a < 1 \\/ b < 1) ).\n\n*)\n\nLemma scale_eq : forall p a,\n  0 < p < 1 ->\n  p * a + (1 - p) * a = a.\nProof.\n  intros.\n  lra.\nQed.\n\nLemma scale_lt : forall p a b r,\n  0 < p < 1 ->\n  a < r ->\n  b < r ->\n  p * a + (1 - p) * b < r.\nProof.\n  intros.\n  rewrite <- scale_eq with (p:=p); trivial.\n  apply Rplus_lt_compat. \n  - apply Rmult_lt_compat_l; lra.\n  - apply Rmult_lt_compat_l; lra.  \nQed.\n\nLemma scale_gt : forall p a b r,\n  0 < p < 1 ->\n  a > r ->\n  b > r ->\n  p * a + (1 - p) * b > r.\nProof.\n  intros.\n  rewrite <- scale_eq with (p:=p); trivial.\n  apply Rplus_gt_compat. \n  - apply Rmult_gt_compat_l; lra.\n  - apply Rmult_gt_compat_l; lra.  \nQed.\n\n", "meta": {"author": "rnrand", "repo": "VPHL", "sha": "db939e605c2ed5ac9693558b3ad3b79d49edf26a", "save_path": "github-repos/coq/rnrand-VPHL", "path": "github-repos/coq/rnrand-VPHL/VPHL-db939e605c2ed5ac9693558b3ad3b79d49edf26a/Intervals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017536, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6556619417673514}}
{"text": "(** ** Natural numbers\n\n    The natural numbers are a motivating example of W-types, and one of the only\n    W-types readily available in UniMath. We show that they are an initial\n    algebra for a polynomial functor, and satisfy a few other properties.\n\n    Author: Langston Barrett (@siddharthist)\n *)\nRequire Import UniMath.Foundations.Preamble.\nRequire Import UniMath.Foundations.PartA.\nRequire Import UniMath.Foundations.PartD.\nRequire Import UniMath.Foundations.UnivalenceAxiom.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.categories.Type.Core.\nRequire Import UniMath.Induction.FunctorAlgebras_legacy.\nRequire Import UniMath.Induction.PolynomialFunctors.\nRequire Import UniMath.Induction.W.Core.\nRequire Import UniMath.Induction.W.Fibered.\n\nLocal Notation ℕ := nat.\n\n(** The signature for the nat functor is (bool, [true ↦ empty; false ↦ unit])\n    since the naturals have two constructors: one for zero and one for successor.\n *)\nDefinition nat_functor : functor type_precat type_precat :=\n  polynomial_functor bool (bool_rect (λ _, UU) empty unit).\n\n(** The functor deals with functions from ∅ and unit; these lemmas will come in\n    handy in several proofs. *)\nLemma eqfromempty {X : UU} (f : empty -> X) : f = fromempty.\nProof. apply proofirrelevancecontr, iscontrfunfromempty. Defined.\n\nLemma eta_unit {X : UU} (f : unit -> X) : f = λ _, f tt.\nProof. apply funextfun; intro; induction _; reflexivity. Defined.\n\n(** Simplifying the action of the functor on arrows *)\n\nLemma nat_functor_arr_true {X Y : UU} (f : X -> Y) g :\n  (functor_on_morphisms nat_functor) f (true,, g) = (true,, fromempty).\nProof.\n  cbn; unfold polynomial_functor_arr; cbn.\n  apply maponpaths, eqfromempty.\nDefined.\n\nLemma nat_functor_arr_false {X Y : UU} (f : X -> Y) g :\n  (functor_on_morphisms nat_functor) f (false,, g) = (false,, λ _, f (g tt)).\nProof.\n  cbn; unfold polynomial_functor_arr; cbn.\n  apply maponpaths, eta_unit.\nDefined.\n\n(** Here's how to prove two functions from a nat_functor are equal:\n    check both cases. *)\nLemma from_nat_functor_eq {X Y : UU} :\n  ∏ f g : nat_functor X → Y,\n    (f (true,, fromempty) = g (true,, fromempty)) ->\n    (∏ h, f (false,, λ _, h tt) = g (false,, λ _, h tt)) -> f = g.\nProof.\n  intros f g ? eqfalse.\n  apply funextsec; intro pair.\n  induction pair as [b bfun].\n  induction b.\n  - refine (maponpaths (λ z, f (true,, z)) (eqfromempty bfun) @ _).\n    refine (_ @ !maponpaths (λ z, g (true,, z)) (eqfromempty bfun)).\n    assumption.\n  - cbn in eqfalse.\n    refine (maponpaths (λ z, f (false,, z)) (eta_unit bfun) @ _).\n    refine (_ @ !maponpaths (λ z, g (false,, z)) (eta_unit bfun)).\n    apply eqfalse.\nDefined.\n\n(** The intuition is that an algebra X for this functor is given by a constant\n    x : X and a function X → X. The following equivalence verifies this. *)\nDefinition nat_functor_equiv :\n  ∏ {X : UU}, (X × (X → X)) ≃ (nat_functor X -> X).\nProof.\n  intro X.\n  use weq_iso.\n  * intros dprodpair.\n    intros pairfun.\n    induction pairfun as [b bfun]; induction b.\n    - exact (pr1 dprodpair).\n    - exact (pr2 dprodpair (bfun tt)).\n  * intro pairfun.\n    exact (make_dirprod (pairfun (true,, fromempty))\n                       (λ x, pairfun (false,, λ _, x))).\n  * reflexivity.\n  * intro Y; apply from_nat_functor_eq; reflexivity.\nDefined.\n\n(** Using our equivalence, we can consisely define the algebra corresponding to\n    ℕ. Any choice of zero results in an isomorphic algebra.\n *)\nDefinition nat_alg (n : ℕ) : algebra_ob nat_functor :=\n  (ℕ,, nat_functor_equiv (make_dirprod n S)).\n\nDefinition nat_alg_z : algebra_ob nat_functor := nat_alg 0.\n\n(** We may also define it directly. This will be judgmentally equal\n    to [nat_alg_z]. *)\nExample nat_alg' : algebra_ob nat_functor.\nProof.\n  unfold algebra_ob, nat_functor; cbn; unfold polynomial_functor_obj; cbn.\n  refine (ℕ,, λ pair, _).\n  induction pair as [b rect].\n  induction b; cbn in rect.\n  - exact 0.\n  - exact (S (rect tt)).\nDefined.\nLemma nat_algs_eq : nat_alg_z = nat_alg'. Proof. reflexivity. Defined.\n\n(** An algebra morphism between algebras for the nat functor is a\n    function that respects all the relevant structure. *)\nDefinition make_nat_functor_algebra_mor {X Y : algebra_ob nat_functor} :\n  let X' := invmap nat_functor_equiv (pr2 X) in\n  let Y' := invmap nat_functor_equiv (pr2 Y) in\n  ∏ (f : pr1 X → pr1 Y),\n    (f (pr1 X') = (pr1 Y')) × (f ∘ (pr2 X') = (pr2 Y') ∘ f)\n  → is_algebra_mor _ X Y f.\nProof.\n  intros X' Y' f p.\n  apply from_nat_functor_eq.\n  + refine (_ @ !maponpaths _ (nat_functor_arr_true f _)).\n    refine (pr1 p @ _).\n    apply (maponpaths (pr2 Y)), maponpaths.\n    reflexivity.\n  + intro; apply (eqtohomot (pr2 p)).\nDefined.\n\n(** Define the unique algebra morphism out of ℕ *)\nLemma nat_alg_is_preinitial : is_preinitial nat_alg_z.\nProof.\n  intro X; pose (x := pr2 X).\n\n  (** X has a \"zero\" and a \"successor\", just like ℕ, given by the algebra\n      structure. We use these to define the unique morphism ℕ -> X\n      by induction. *)\n  pose (x0    := x (true,, fromempty)).\n  pose (xsucc := (λ y, x (false,, λ _, y)) : pr1 X -> pr1 X).\n\n  (** The recursor for ℕ gets an extra argument of type ℕ, which we don't pass\n      to xsucc. Compare to [CategoryTheory.FunctorAlgebras.nat_ob_rec]. *)\n  refine ((nat_rect _ x0 (λ _, xsucc)),, _).\n  apply make_nat_functor_algebra_mor; split; reflexivity.\nDefined.\n\n(** The first projection of the morphism out of ℕ (the actual function)\n    is unique. *)\nLemma nat_alg_func_is_unique :\n  ∏ X, ∏ (mor : algebra_mor _ nat_alg_z X), pr1 mor = pr1 (nat_alg_is_preinitial X).\nProof.\n  intros X mor.\n  induction X as [X x]; induction mor as [mor is_mor]; cbn in x.\n  cbn in mor.\n  apply funextfun; intros n; induction n; cbn.\n  - unfold is_algebra_mor in is_mor; cbn in mor, is_mor.\n    (** Use the condition that mor is an algebra morphism *)\n    refine ((eqtohomot is_mor (true,, fromempty)) @ _).\n    apply (maponpaths x).\n    apply nat_functor_arr_true.\n  - (** Use the condition that mor is an algebra morphism *)\n    refine ((eqtohomot is_mor (false,, _)) @ _); cbn.\n    apply (maponpaths x).\n    unfold polynomial_functor_arr; cbn.\n    apply maponpaths.\n    apply funextsec; intros ttt; induction ttt.\n    apply IHn.\nDefined.\n\n(** Since fibered algebras are the \"dependent version\" of normal algebras,\n    we need some kind of \"dependent version\" of the lemmas above.\n *)\nLemma sec_fromempty {X : UU} {Y : X -> UU}\n      (f : ∅ -> X)\n      (t : ∏ z : ∅, Y (f z)) : t = λ e, fromempty e.\nProof.\n  apply funextsec; intro; induction _.\nDefined.\n\n(** A fibered algebra over ℕ consists of a family ℕ → UU, a point x0 : X 0,\n    and a function from each X n to X (S n).\n *)\nDefinition fibered_algebra_nat :\n  fibered_alg nat_alg_z ≃ ∑ (X : ∏ n : ℕ, UU), (X 0) × (∏ n, X n → X (S n)).\nProof.\n  apply weqfibtototal; intro X; cbn in X.\n  use weq_iso.\n  - intro x.\n    apply make_dirprod.\n    + exact (x (true,, fromempty) (λ e, fromempty e)).\n    + refine (λ n xn, _).\n      unfold fibered_alg in x; cbn in x.\n      apply (x (false,, λ _, n) (λ _, xn)).\n  - intro x.\n    unfold fibered_alg; cbn.\n    intros pair from; induction pair as [b bfun].\n    induction b; cbn in *.\n    + exact (pr1 x).\n    + exact (pr2 x (bfun tt) (from tt)).\n  - cbn. intro g.\n    apply funextsec; intro pair.\n    induction pair as [b bfun].\n    induction b; cbn; cbn in bfun.\n    + apply funextsec; intro z.\n      rewrite (sec_fromempty bfun z).\n      rewrite (eqfromempty bfun).\n      reflexivity.\n    + rewrite (eta_unit bfun).\n      apply funextsec; intro z.\n      apply maponpaths.\n      exact (!eta_unit z).\n  - reflexivity.\nDefined.\n\n(** A section from ℕ consists of a \"point\" x : ∏ n, X n such that\n    x agrees with the function which is a part of the fibered\n    algebra (see above).\n *)\nDefinition make_nat_alg_sec :\n  ∏ (FA : fibered_alg nat_alg_z),\n  let FA' := fibered_algebra_nat FA\n  in ∏ (x : ∏ n : ℕ, pr1 FA' n)\n       (p1 : x 0 = pr1 (pr2 FA'))\n       (p2 : (∏ n, pr2 (pr2 FA') n (x n) = x (S n))),\n  algebra_section FA.\nProof.\n  intros FA FA' x p1 p2.\n  unfold algebra_section.\n  refine (x,, _).\n  intro pair.\n  induction pair as [b bfun].\n  induction b; cbn; cbn in bfun.\n  - (** They are equal at 0 by hypothesis p1, the rest is noise. *)\n    refine (p1 @ _).\n    unfold FA', fibered_algebra_nat; cbn.\n    rewrite (eqfromempty bfun).\n    apply maponpaths.\n    apply funextsec.\n    intro e; induction e.\n  - refine (!p2 (bfun tt) @ _).\n    rewrite (eta_unit (bfun)).\n    reflexivity.\nDefined.\n\n(** Another way to make an algebra section given different starting data. *)\nDefinition make_nat_alg_sec' {X : ℕ -> UU} {ρ : ∏ n, X n → X (S n)}\n           (x : ∏ n : ℕ, X n) (H : ∏ n : ℕ, x (S n) = ρ n (x n)) :\n  algebra_section\n    (invmap fibered_algebra_nat (X,, (x 0,, ρ))).\nProof.\n  refine (x,, _).\n  intros pair; induction pair as [b bfun]; induction b.\n  - reflexivity.\n  - apply H.\nDefined.\n\n(** Define the section out of ℕ, prove it's really a section *)\nLemma nat_alg_is_preinitial_sec : is_preinitial_sec nat_alg_z.\nProof.\n  intro E. pose (x := pr2 E).\n  unfold is_preinitial, algebra_section.\n  use make_nat_alg_sec.\n  - apply nat_rect.\n    + exact (x (true,, fromempty) (empty_rect (pr1 E ∘ fromempty))).\n    + intros ? fn.\n      refine (x (false,, λ _, n) (λ b : unit, fn)).\n  - cbn.\n    apply maponpaths.\n    apply funextsec; intro e; induction e.\n  - reflexivity.\nDefined.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/Induction/W/Naturals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.7577943603346811, "lm_q1q2_score": 0.6556619249355219}}
{"text": "Require Import A1_Plan A2_Orientation A4_Droite A7_Tactics .\nRequire Import B7_Tactics .\nRequire Import G1_Angles .\nRequire Import I2_Supplement .\nRequire Import K1_RightAngle .\nRequire Import L2_StrictParallelogramm L6_Tactics .\nRequire Import M1_SuperImposedLines M4_PerpendicularLines M5_Tactics .\nRequire Import N1_DrawingPerpendicularLines N5_UniqueParallel.\n\nSection PARALLEL_AND_PERPENDICULAR_LINES.\n\nLemma RightRightEqMLine : forall A B C D : Point, forall Hab : A <> B, forall Hdb : D <> B,\n\tRightAngle A B C  ->\n\tRightAngle C B D ->\n\tEqLine (Ruler A B Hab) (Ruler D B Hdb).\nProof.\n\tintros.\n\tstep12 Hab.\n\tsince12 (~ Collinear A B C).\n\t since12 (~ Collinear C B D).\n\t  by2Cases1 H1; by2Cases1 H2.\n\t   since12 (Supplement C B A D B C).\n\t    from12 H5 (Between A B D).\n\t   since12 (CongruentAngle A B C D B C).\n\t    from12 H5 (OpenRay B A D).\n\t   since12 (CongruentAngle C B A C B D).\n\t    from12 H5 (OpenRay B A D).\n\t   since12 (Supplement C B A D B C).\n\t    from12 H5 (Between A B D).\nQed.\n\nLemma PerpendicularPerpendicularParallel : forall d1 d2 d3 : Line,\n\tPerpendicular d1 d2 ->\n\tPerpendicular d2 d3 ->\n\tParallelLines d1 d3.\nProof.\n\tintros.\n\tinversion H; inversion H0.\n\tby3Cases1 A B B0.\n\t setStrictParallelogramm11 A B B0 ipattern:(E).\n\t   DestructSP11 H12.\n\t   since12 (RightAngle B B0 E).\n\t  as12 (Supplement B B0 E A B B0).\n\t    left; step12 H.\n\t  from12 H0 (RightAngle B B0 C0).\n\t    setLine0 A B ipattern:(d4).\n\t   immediate12.\n\t   since12 (EqLine d1 d4).\n\t    step12 (A, B).\n\t    step12 H18.\n\t      setLine0 E B0 ipattern:(d5).\n\t     immediate12.\n\t     setLine0 C0 B0 ipattern:(d6).\n\t      immediate12.\n\t      since12 (EqLine d5 d6).\n\t       unfold d5 in |- *; unfold d6 in |- *; apply (RightRightEqMLine E B0 B).\n\t        immediate12.\n\t        immediate12.\n\t       from12 (B0, C0) (EqLine d3 d6).\n\t         step12 H22.\n\t         step12 H21.\n\t setStrictParallelogramm11 B0 B A ipattern:(E).\n\t   since12 (RightAngle B B0 E).\n\t  as12 (Supplement B B0 E A B B0).\n\t    left; step12 H.\n\t  from12 H0 (RightAngle B B0 C0).\n\t    setLine0 A B ipattern:(d4).\n\t   immediate12.\n\t   since12 (EqLine d1 d4).\n\t    step12 (A, B).\n\t    step12 H16.\n\t      setLine0 E B0 ipattern:(d5).\n\t     immediate12.\n\t     setLine0 C0 B0 ipattern:(d6).\n\t      immediate12.\n\t      since12 (EqLine d5 d6).\n\t       unfold d5 in |- *; unfold d6 in |- *; apply (RightRightEqMLine E B0 B).\n\t        immediate12.\n\t        immediate12.\n\t       from12 (B0, C0) (EqLine d3 d6).\n\t         step12 H20.\n\t         step12 H19.\n\t from12 H12 (OnLine d1 B0).\n\t   since12 (SecantLines d1 d2).\n\t   from12 H13 (B0 = B).\n\t   subst.\n\t   from12 H0 (RightAngle C B C0).\n\t   setLine0 C0 B ipattern:(d4).\n\t  immediate12.\n\t  setLine0 A B ipattern:(d5).\n\t   immediate12.\n\t   since12 (EqLine d4 d5).\n\t    unfold d4 in |- *; unfold d5 in |- *; apply (RightRightEqMLine C0 B C).\n\t     immediate12.\n\t     immediate12.\n\t    from12 (A, B) (EqLine d1 d5).\n\t      step12 H18.\n\t      from12 (C0, B) (EqLine d3 d4).\n\t      step12 H19.\nQed.\n\nLemma UniquePerpendicular : forall d1 d2 d3 : Line, forall A : Point,\n\tPerpendicular d1 d3 ->\n\tPerpendicular d2 d3 ->\n\tOnLine d1 A ->\n\tOnLine d2 A ->\n\tEqLine d1 d2.\nProof.\n\tintros.\n\tsince12 (ParallelLines d1 d2).\n\t apply (PerpendicularPerpendicularParallel d1 d3 d2).\n\t  immediate12.\n\t  immediate12.\n\t step12 H3.\nQed.\n\nLemma PerpendicularParallelPerpendicular : forall d1 d2 d3 : Line,\n\tPerpendicular d1 d2 ->\n\tParallelLines d1 d3 ->\n\tPerpendicular d2 d3.\nProof.\n\tintros.\n\tsetInterLines d3 d2 ipattern:(A).\n\t apply (ParallelSecant d1); immediate12.\n\t pose (d4 := PerpendicularUp d2 A Hol0).\n\t   assert (H1 := PerpendicularUpPerpendicular d2 A Hol0); fold d4 in H1.\n\t   since12 (ParallelLines d1 d4).\n\t  apply (PerpendicularPerpendicularParallel d1 d2 d4); immediate12.\n\t  since12 (OnLine d4 A).\n\t   apply (PerpendicularUpOnLine d2 A Hol0).\n\t   since12 (EqLine d3 d4).\n\t    apply (UniqueParallel d1 d3 d4 A); immediate12.\n\t    step12 H4.\nQed.\n\nLemma SecantPerpendicularSecant : forall d1 d2 d3 d4 : Line,\n\tSecantLines d1 d2 ->\n\tPerpendicular d1 d3 ->\n\tPerpendicular d2 d4 ->\n\tSecantLines d3 d4.\nProof.\n\tintros.\n\tcontrapose0 H.\n\tapply (PerpendicularPerpendicularParallel d1 d3 d2 H0).\n\tapply PerpendicularSym; apply (PerpendicularParallelPerpendicular d4);\n\t immediate12.\nQed.\n\nLemma SecantParallelSecant : forall d1 d2 d3 d4 : Line,\n\tSecantLines d1 d2 ->\n\tParallelLines d1 d3 ->\n\tParallelLines d2 d4 ->\n\tSecantLines d3 d4.\nProof.\n\tintros.\n\tcontrapose0 H.\n\tapply (ParallelTrans d1 d3 d2 H0).\n\tapply (ParallelTrans d3 d4); immediate12.\nQed.\n\nEnd PARALLEL_AND_PERPENDICULAR_LINES.\n", "meta": {"author": "coq-contribs", "repo": "euclidean-geometry", "sha": "06838851a5924918d98e5a9c07ffa84021e13af7", "save_path": "github-repos/coq/coq-contribs-euclidean-geometry", "path": "github-repos/coq/coq-contribs-euclidean-geometry/euclidean-geometry-06838851a5924918d98e5a9c07ffa84021e13af7/N6_ParallelAndPerpendicularLines.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6555737169229007}}
{"text": "Require Import HoTT.\nFrom GR.bicategories Require Import\n     bicategory.bicategory_laws\n     lax_functor.lax_functor\n     lax_transformation.lax_transformation\n     lax_transformation.examples.identity\n     lax_transformation.examples.composition\n     modification.modification.\n\nSection LeftIdentityInv.\n  Context `{Univalence}\n          {C D : BiCategory}\n          {F₁ F₂ : LaxFunctor C D}.\n  Variable (η : LaxTransformation F₁ F₂).\n\n  Local Notation left_identity_inv_mod_d\n    := (fun (A : C) =>\n          left_unit_inv (η A) : (η A ==> compose η (identity_transformation F₂) A)).\n\n  Definition left_identity_inv_is_mod : is_modification left_identity_inv_mod_d.\n  Proof.\n    intros A B f ; cbn in *.\n    unfold bc_whisker_l, bc_whisker_r.\n    rewrite !vcomp_assoc.\n    rewrite <- (vcomp_left_identity (id₂ (η A))).\n    rewrite interchange.\n    rewrite !vcomp_assoc.\n    rewrite triangle_r.\n    rewrite !vcomp_assoc.\n    rewrite !(ap (fun z => _ ∘ (_ ∘ (_ ∘ (_ ∘ (_ ∘ z))))) (vcomp_assoc _ _ _)^).\n    rewrite assoc_left.\n    rewrite vcomp_left_identity.\n    rewrite <- !vcomp_assoc.\n    rewrite !vcomp_assoc.\n    rewrite !(ap (fun z => _ ∘ z) (vcomp_assoc _ _ _)^).\n    pose @left_unit_inv_assoc as p.\n    unfold bc_whisker_r in p.\n    rewrite p ; clear p.\n    rewrite !vcomp_assoc.\n    rewrite !(ap (fun z => _ ∘ (_ ∘ z)) (vcomp_assoc _ _ _)^).\n    rewrite assoc_left.\n    rewrite vcomp_left_identity.\n    rewrite !vcomp_assoc.\n    rewrite <- interchange.\n    rewrite left_unit_left.\n    rewrite vcomp_left_identity, hcomp_id₂, vcomp_right_identity.\n    rewrite <- left_unit_inv_natural.\n    rewrite <- !vcomp_assoc.\n    rewrite <- left_unit_inv_assoc.\n    reflexivity.\n  Qed.\n\n  Definition left_identity_inv_modification\n    : Modification η (compose η (identity_transformation F₂))\n    := Build_Modification left_identity_inv_mod_d left_identity_inv_is_mod.\n\n  Definition left_identity_inv_modification_is_iso\n    : iso_modification left_identity_inv_modification.\n  Proof.\n    intros X ; cbn.\n    apply _.\n  Qed.\n\n  Definition left_identity_inv_mod\n    : IsoModification η (compose η (identity_transformation F₂)).\n  Proof.\n    make_iso_modification.\n    - exact left_identity_inv_modification.\n    - exact left_identity_inv_modification_is_iso.\n  Defined.\nEnd LeftIdentityInv.\n", "meta": {"author": "nmvdw", "repo": "groupoids", "sha": "dd54321b2589c7cf31f379bd63b4a86cf9052792", "save_path": "github-repos/coq/nmvdw-groupoids", "path": "github-repos/coq/nmvdw-groupoids/groupoids-dd54321b2589c7cf31f379bd63b4a86cf9052792/bicategories/modification/examples/left_identity_inv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6555217251482678}}
{"text": "\nRequire Import List.\nRequire Import Arith.\n\nFixpoint\n  update_primes (k:nat) (l: list (nat*nat)) {struct l} : list (nat*nat)*bool :=\n  match l with\n  | nil => (nil,false)\n  | (p,n)::tl => \n    let (l',b) := update_primes k tl in\n    match Nat.compare  k n with\n    | Lt => ((p, n)::l', b)\n    | Eq => ((p, n+p)::l', true)\n    | Gt => ((p, n+p)::l', b)\n    end\n  end.\n\nFixpoint prime_sieve (n:nat) : list (nat*nat) :=\n  match n with\n  | O => nil\n  | 1 => nil\n  | S k' => \n    let (l', b) := update_primes (S k')(prime_sieve k') in\n    if b then l' else ((S k', 2*S k')::l')\n  end.\n\nDefinition prime_fun (n:nat) : bool :=\n  match prime_sieve n with\n  | nil => false\n  | (p,q)::tl => \n    match Nat.compare p n with\n    | Eq => true\n    | _ => false\n    end\n  end.\n\n(** The rest of the file shows that we can prove interesting facts\n   about our function using only the notions that have been introduced \n   in the book up to chapter 6.  However, an expert user would rather\n   also rely on notions that are introduced later, like the inductive\n   properties found in chapter 8. *)\n \n\n\nDefinition divides (p n:nat) := exists q:nat, n = p*q.\n\nDefinition prime (n:nat) :=\n  (n<>0/\\n<>1)/\\~(exists k:nat, 1 < k < n /\\ divides k n).\n\nDefinition all_list(P:nat->nat->Prop) (l:list(nat*nat)):=\n forall (l1 l2:list(nat*nat))(p n:nat),\n   l = l1++(p, n)::l2 -> (P p n).\n\nDefinition all_first_less_than (k:nat) :=\n all_list (fun p n:nat => p < k).\n\nDefinition all_first_prime :=\n all_list (fun p n:nat => prime p).\n\nDefinition all_intervals (k:nat) :=\n all_list (fun p n:nat => n-p<k<=n).\n\nDefinition all_multiples :=\n all_list (fun p n:nat => exists q:nat, n=p*q).\n\nDefinition all_greater_than_one :=\n all_list (fun p n => 1 < p).\n\nDefinition all_prime_in_first (k:nat)(l:list (nat*nat)) :=\n forall n:nat, 0 < n < k -> prime n ->\n  (exists l1: list (nat*nat),\n    (exists l2: list (nat*nat),\n      (exists p: nat, l= l1++(n,p)::l2))).\n\n(** A theorem that should be in the general libraries. *)\n\n\nTheorem mult_lt_reg_l : \n  forall m n p, m * n < m * p -> n < p.\nProof.\n intros m n; elim n.\n -  intros p; case p.\n  +  repeat (rewrite mult_comm; simpl); auto.\n  +  auto with arith.\n -  intros n' Hrec p; case p.\n  +  rewrite <- (mult_comm 0); simpl; intros Hlt; elim (lt_n_O (m*S n'));auto.\n  + intros p'; repeat rewrite <- mult_n_Sm.\n    repeat rewrite <- (plus_comm m).\n    intros Hlt; assert (Hlt' : m*n' < m* p').\n    *  apply plus_lt_reg_l with m; auto.\n    * auto with arith.\nQed.\n\n\n\n(** A bunch of generic proofs about the all_list predicate. *)\n\nTheorem all_list_transmit :\n forall (P:nat->nat->Prop)(p:nat*nat)(l:list(nat*nat)),\n   all_list P (p::l)-> all_list P l.\nProof.\n intros P fst_elem l H l1 l2 p n Heq.\n unfold all_list in H.\n apply H with (fst_elem::l1) l2; rewrite Heq; auto.\nQed.\n\nTheorem all_list_add :\n forall (P:nat->nat->Prop)(l:list(nat*nat))(p n:nat),\n P p n -> all_list P l -> all_list P ((p,n)::l).\nProof.\n intros P l p n Hp Hal l1; case l1.\n intros l2 p' n' Heq; injection Heq; intros Hl Hn' Hp';\n rewrite <- Hn'; rewrite <- Hp'; auto.\n\n simpl; clear l1; intros fst_elem l1 l2 p' n' Heq; injection Heq;\n intros Hl Hfst; apply (Hal l1 l2); assumption.\nQed.\n\nTheorem absurd_decompose_list :\n forall (A:Set) (l1 l2:list A) (p:A), nil = l1++p::l2 -> False.\nProof.\n intros A l1; case l1; simpl; intros; discriminate.\nQed.\n\nTheorem all_list_nil :\n forall (P:nat->nat->Prop),\n  all_list P nil. \nProof.\n intros P l1 l2 p n Heq; elim (absurd_decompose_list _ _ _ _ Heq).\nQed. \n\n(** As corollaries, we get transmission theorems for the main predicates. *)\n\nTheorem all_intervals_transmit :\n forall (k:nat)(p:nat*nat)(l: list(nat*nat)),\n  all_intervals k (p::l) -> all_intervals k l.\nProof.\n intros k; exact (all_list_transmit (fun p n => n-p<k<=n)).\nQed.\n\nTheorem all_multiples_transmit :\n forall (p:nat*nat)(l: list(nat*nat)),\n  all_multiples (p::l) -> all_multiples l.\nProof.\n exact (all_list_transmit (fun p n => exists q:nat, n=p*q)).\nQed.\n\nTheorem all_greater_than_one_transmit :\n forall (p:nat*nat)(l: list(nat*nat)),\n  all_greater_than_one (p::l) -> all_greater_than_one l.\nProof.\n exact (all_list_transmit (fun p n => 1<p)).\nQed.\n\nTheorem all_first_prime_transmit :\n forall (p:nat*nat)(l:list(nat*nat)),\n  all_first_prime(p::l) -> all_first_prime l.\nProof.\n exact (all_list_transmit (fun p n => prime p)).\nQed.\n\nTheorem all_first_less_than_transmit :\n forall k (p:nat*nat)(l: list(nat*nat)),\n  all_first_less_than k (p::l) -> all_first_less_than k l.\nProof.\n intros k; exact (all_list_transmit (fun p n => p < k)).\nQed.\n\n(** Theorems about invariants in update_primes *)\n\nTheorem update_primes_all_list_invariant :\n forall (P:nat->nat->nat->Prop),\n (forall k p n:nat, k = n -> P k p n -> P k p (n+p))->\n (forall k p n:nat, n < k -> P k p n -> P k p (n+p))->\n forall (k:nat)(l l':list(nat*nat))(b:bool),\n  all_list (P k) l ->\n  update_primes k l = (l',b) -> all_list (P k) l'.\nProof.\n  intros P Hp2 Hp3 k l; elim l.\n  -  simpl; intros Hal l' b Hup; injection Hup; intros Hb Hl';\n       rewrite <- Hl'; apply (all_list_nil (P k)).\n  -  simpl; intros (p, n) l0 Hrec l' b Hal;\n       case_eq (update_primes k l0); intros l'0 b0 Hup0.\n     case_eq (Nat.compare k n); intros Htwc Hup; injection Hup;\n       intros Hb Hl'; rewrite <- Hl';\n         generalize (Hal nil l0 p n (refl_equal _)); intros HPkpn;\n           generalize (Hrec l'0 b0 (all_list_transmit (P k) (p,n) l0 Hal) Hup0);\n           intros Hal'; apply all_list_add; auto.\n     +  apply Hp2;[apply nat_compare_eq;auto| auto].\n     + apply Hp3;[apply nat_compare_Gt_gt;auto| auto].\nQed.\n\n(** Now a few proofs about divides and prime *)\n\nTheorem divides_dec_aux : \n  forall k n p:nat, n <= k -> divides p n \\/ ~divides p n.\nProof.\n  intros k; elim k.\n  -  intros n p Hle; left; exists 0; rewrite mult_comm; simpl; \n       symmetry; apply le_n_O_eq; auto.\n  - intros k' Hrec n p Hlt; elim (le_lt_or_eq n (S k')).\n    + auto with arith.\n    + intros Heq; rewrite Heq.\n      case p.\n      *  right; intros (q, Heq').\n         discriminate Heq'.\n      *  intros p'; case_eq (Nat.compare (S p') (S k')); intros Htwc.\n         --  assert (H:S p' = S k').\n             { apply nat_compare_eq; auto. }\n             left; exists 1; rewrite H.\n             auto with arith.\n         -- \n           assert (S p' < S k').\n           apply nat_compare_Lt_lt; auto.\n           elim (Hrec (minus (S k') (S p')) (S p')).\n           ++ intros (q, Heq'); left; exists (S q).\n              rewrite (le_plus_minus (S p') (S k')).\n              ** rewrite Heq'.\n                 repeat rewrite (mult_comm (S p')).\n                 reflexivity.\n              **  auto with arith.\n           ++  intros Hndiv; right; intros Hdiv.\n               apply Hndiv.\n               elim Hdiv.\n               intros q; case q.\n               **  rewrite mult_comm;  simpl; intros; discriminate.\n               **  intros q' Heq'; exists q'.\n                   apply plus_reg_l with (S p').\n                   rewrite le_plus_minus_r.\n                   { rewrite Heq'.\n                     rewrite plus_comm; rewrite mult_n_Sm; reflexivity.\n                   }\n                   auto with arith.\n           ++ simpl; apply le_minus.\n              \n         -- assert (Hlt': S k' < S p').\n            { apply nat_compare_Gt_gt; auto. }\n            right; intros Hdiv; elim Hdiv; intros q; case q.\n            ++  rewrite mult_comm; simpl; intros; discriminate.\n            ++ intros q' Heq'; elim (lt_not_le _ _ Hlt').\n               rewrite Heq'.\n               rewrite mult_comm; simpl; auto with arith.\n    +  trivial.\nQed.\n\n\nTheorem eq_nat_or :\n forall n m:nat, n=m \\/ ~n=m.\nProof.\n  decide equality.\nQed.\n\nTheorem prime_dec_aux :\n forall n k:nat,\n  (n=0\\/n=1)\\/\n  (exists p:nat, 1<p<k /\\ (exists q:nat, n=p*q))\\/\n  ((n<>0/\\n<>1)/\\~(exists p:nat, 1<p<k/\\ (exists q:nat, n=p*q))).\nProof.\n intros n; elim (eq_nat_or n 1).\n -  auto.\n - intros Hnneq1.\n   elim (eq_nat_or n 0).\n   +  auto.\n   + intros Hnneq0 k; elim k.\n    *  right; right; split.\n     --   auto.\n     -- intros (p, ((_,Hlt0), (q, Heq))).\n        elim (lt_n_O p); auto.\n    * intros k'; case k'.\n     --  intros; right; right; split.\n         ++ auto.\n         ++ intros (p, ((Hpgt1, Hplt1),_)).\n            elim (lt_irrefl 1); apply lt_trans with p;auto.\n     -- intros k''; case k''.\n        ++ intros; right; right; split; auto; intros (p, ((Hpgt1, Hplt2),_)).\n           elim (lt_irrefl p); apply le_lt_trans with 1; auto with arith.\n        ++ intros k''' Hrec; case (divides_dec_aux n n (S (S k'''))).\n           ** auto with arith.\n           ** intros Hdiv; right; left; exists (S (S k'''));\n                repeat split; auto with arith.\n           **  intros Hndiv; elim Hrec.\n               { auto. }\n               {  intros Hrec'; elim Hrec'.\n                  intros (p, ((Hpgt1, Hplt), Hex));\n                    right; left; exists p; repeat split;\n                      auto with arith.\n                  intros (_, Hnodiv); right; right; split; auto;\n                    intros (p, ((Hpgt1, Hplt), Hex)).\n                  assert (Hple : p <= S (S k''')).\n                  { auto with arith. }\n                  elim (le_lt_or_eq _ _ Hple).\n                  intros Hplt'.\n                  elim Hnodiv; exists p; repeat split; auto with arith.\n                  intros Hpeq.\n                  elim Hndiv; rewrite <- Hpeq; exact Hex.\n               }\nQed.\n\nTheorem prime_dec :\n forall n:nat, (n=0\\/n=1)\\/(exists p:nat, 1<p<n /\\ (exists q:nat, n=p*q))\\/\n  prime n.\nProof.\n intros n; exact (prime_dec_aux n n).\nQed.\n\n\nTheorem div_by_prime_aux :\n forall k:nat, forall n:nat, n <= k ->\n 1 < n -> (exists p:nat, 1 < p < n /\\ (exists q : nat, n=p*q)) ->\n (exists p:nat, 1 < p < n /\\ (prime p) /\\ (exists q:nat, n=p*q)).\nProof.\n intros k; elim k.\n -  intros n Hle Hlt Hn.\n    elim (lt_asym 1 0). \n  +  apply lt_le_trans with n; assumption.\n  + auto with arith.\n -  intros k' Hrec n Hle Hlt Hn.\n    elim (le_lt_or_eq n (S k')).\n    +  intros Hle'; apply Hrec; auto with arith.\n    + elim Hn; intros p ((Hpgt1, Hpltn),(q,Heq)).\n      intros HneqSk'.\n      elim (prime_dec p).\n    *  intros Hpeq0or1; elim Hpeq0or1.\n     --  intros Hpeq0.\n         rewrite Hpeq0 in Hpgt1; elim (lt_n_O 1); assumption.\n     -- intros Hpeq1;\n          rewrite Hpeq1 in Hpgt1; elim (lt_irrefl 1); assumption.\n    *  intros Hpdec; elim Hpdec.\n       -- intros Hexp.\n          elim (Hrec p); auto with arith.\n          ++ intros p' ((Hp'gt1,Hp'ltp), (Hpr,(q', Heq'))).\n             exists p'.\n             split;[split|split]; auto with arith.\n             ** apply lt_trans with p; auto with arith.\n             **  exists (q' * q).\n                 rewrite mult_assoc.\n                 rewrite Heq; rewrite Heq'; trivial.\n          ++  unfold lt in Hpltn.\n              rewrite HneqSk' in Hpltn; auto with arith.\n       --  exists p;split;[split|split]; auto with arith.\n           exists q; auto with arith.\n    + trivial.\nQed.\n\nTheorem div_by_prime :\n forall n:nat, 1 < n -> (exists p:nat, 1 < p < n /\\ (exists q : nat, n=p*q)) ->\n (exists p:nat, 1 < p < n /\\ (prime p) /\\ (exists q:nat, n=p*q)).\nProof.\n intros n; apply (div_by_prime_aux n n).\n auto with arith.\nQed.\n\n(** Now, theorems about update_primes. *)\n\nTheorem update_primes_true_aux :\n  forall (k:nat) (l1 l2 l3 l4: list(nat*nat))(b:bool),\n    update_primes k l1 = (l2, true) ->\n    update_primes k (l3++l1) = (l4, b) -> b=true.\nProof.\n  intros k l1 l2 l3; elim l3.\n  - simpl; intros l4 b Heq1; rewrite Heq1; intros Heq2; injection Heq2; auto.\n  - simpl; intros (p,n) l; case (update_primes k (l++l1)).\n    intros l4 b Hrec l4' b'; case (Nat.compare k n).\n  + intros Heq1 Heq2; injection Heq2; auto.\n  +  intros Heq1 Heq2; injection Heq2.\n     intros Heq3 Heq4; rewrite <- Heq3; apply Hrec with l4; auto.\n  + intros Heq1 Heq2; injection Heq2.\n    intros Heq3 Heq4; rewrite <- Heq3; apply Hrec with l4; auto.\nQed.\n\nTheorem update_primes_true_imp_div :\n  forall (k:nat)(l: list (nat*nat)),\n    all_first_less_than k l ->\n    all_multiples l ->\n    all_greater_than_one l ->\n    forall l1, update_primes k l = (l1, true) ->\n               (exists p:nat, 1< p < k /\\ (exists q:nat, k = p*q)).\nProof.\n  intros k l; elim l.\n  -  simpl; intros; discriminate.\n  - intros (p,n) l0 Hrec Haf Ham Hal l1; simpl.\n    case_eq (update_primes k l0).\n    intros l2 b Hup; case_eq (Nat.compare k n).\n    +  intros Htwc Heq; generalize (nat_compare_eq _ _ Htwc).\n       intros Hk; exists p; split.\n       *  split.\n          unfold all_greater_than_one in Hal;\n            apply Hal with (nil (A:=nat*nat)) l0 n; auto.\n          unfold all_first_less_than in Haf;\n            apply Haf with (nil (A:=nat*nat)) l0 n; auto.\n       * unfold all_multiples in Ham.\n         rewrite Hk; apply Ham with (nil (A:=nat*nat)) l0; auto.\n    + intros Htwc Heq; injection Heq; intros Hb Hl1.\n      * rewrite Hb in Hup; apply Hrec with l2.\n        -- apply all_first_less_than_transmit with (p,n); auto.\n        -- apply all_multiples_transmit with (p,n); auto.\n        --  apply all_greater_than_one_transmit with (p,n); auto.\n        -- auto.\n           \n    + intros Htwc Heq; injection Heq; intros Hb Hl1.\n      rewrite Hb in Hup; apply Hrec with l2.\n      * apply all_first_less_than_transmit with (p,n); auto.\n      * apply all_multiples_transmit with (p,n); auto.\n      *  apply all_greater_than_one_transmit with (p,n); auto.\n      *  auto.\nQed.\n\nTheorem interval_eq :\n  forall p q q', p*q'-p < p*q <= p*q' -> q=q'.\nProof.\n  intros p; case p.\n  -  simpl; intros q q' (Hlt, Hle); elim (lt_irrefl 0);assumption.\n  - intros p' q q' (Hlt, Hle).\n    apply le_antisym.\n    + apply mult_S_le_reg_l with p'; auto.\n    + assert (Hlt' : (q' - 1)*S p' < S p' * q).\n     { rewrite mult_minus_distr_r.\n       rewrite mult_1_l.\n       rewrite (mult_comm q').\n       assumption.\n     }\n     rewrite (mult_comm (q' - 1)) in Hlt'.\n     generalize (mult_lt_reg_l _ _ _ Hlt').\n     case q'; simpl.\n     * auto with arith.\n       * intros n; rewrite <- minus_n_O; auto with arith.\nQed.\n\n\nTheorem update_primes_false_imp_prime :\n forall k l l1,\n   1 < k ->\n   all_multiples l ->\n   all_intervals k l ->\n   all_prime_in_first k l ->\n   update_primes k l = (l1,false) -> prime k.\nProof.\n intros k l l1 Hkgt1 Ham Hai Hap Heq.\n elim (prime_dec k); auto.\n -  intros Hkeq0or1;elim Hkeq0or1.\n    + intros Hkeq0.\n      rewrite Hkeq0 in Hkgt1; elim (lt_n_O 1); assumption.\n    + intros Hkeq1; rewrite Hkeq1 in Hkgt1; elim (lt_irrefl 1); assumption.\n- intros Hpdec; elim Hpdec.\n  + intros Hexdiv.\n    generalize (div_by_prime _ Hkgt1 Hexdiv).\n    intros (p, ((Hpgt1,Hpltk), (Hpr, Hex))).\n    elim (Hap p); auto.\n    *  intros l'1 (l2, (n, Heq')).\n       elim Hex; intros q Heq''. \n       assert (Hint: n - p < k <= n).\n     { unfold all_intervals in Hai.\n       apply Hai with l'1 l2. \n       auto.\n     }\n     assert (Hmult : (exists q':nat, n = p*q')).\n     {\n       unfold all_multiples in Ham.\n       apply Ham with l'1 l2.\n       auto.\n     }\n     elim Hmult; intros q' Heq3.\n     assert (Heq4: q=q').\n     {\n       apply interval_eq with p.\n       rewrite <- Heq3.\n       rewrite <- Heq''.\n       assumption.\n     }\n     assert (false= true).\n     { \n       case_eq (update_primes k ((p,n)::l2)).\n       intros l3 b Hup.\n       generalize (update_primes_true_aux k ((p,n)::l2) l3 l'1 l1 false).\n       intros H; apply H.\n       - generalize Hup.\n         simpl.\n         case (update_primes k l2).\n         intros l5 b2.\n         rewrite Heq''; rewrite Heq3; rewrite Heq4.\n         rewrite Nat.compare_refl.\n         intros Heq5; injection Heq5; intros Heq6 Heq7;\n           rewrite Heq6;rewrite Heq7;\n             auto with arith.\n       -  rewrite <- Heq'.\n          assumption.\n     }  \n     discriminate.\n    * auto with arith.\n  + trivial.\nQed.\n\n(** We can now prove that all properties are invariant. *)\n\nTheorem update_primes_all_multiples :\n  forall k l l' b,\n    all_multiples l ->\n       update_primes k l = (l', b) -> all_multiples l'.\nProof.\n apply (update_primes_all_list_invariant (fun k p n => exists q:nat, n=p*q));\n try (intros k p n Hcomp (q, Heq);exists (S q);rewrite Heq;\n rewrite <- mult_n_Sm; reflexivity).\nQed.\n\n\nTheorem update_primes_all_first_less_than :\n forall k l l' b,\n all_first_less_than k l ->\n update_primes k l = (l',b) ->\n all_first_less_than k l'.\nProof.\n apply (update_primes_all_list_invariant (fun k p n => p < k)); auto.\nQed.\n\n\nTheorem update_primes_all_greater_than_one :\n forall k l l' b,\n  all_greater_than_one l ->\n  update_primes k l = (l',b) ->\n  all_greater_than_one l'.\nProof.\n apply (update_primes_all_list_invariant (fun k p n => 1 < p)); auto.\nQed.\n\nTheorem update_primes_all_first_prime :\n forall k l l' b,\n  all_first_prime l -> update_primes k l = (l',b) -> all_first_prime l'.\nProof.\n apply (update_primes_all_list_invariant (fun k p n => prime p)); auto.\nQed.\n\nTheorem update_primes_all_intervals :\n forall (k:nat)(l:list(nat*nat)),\n   all_intervals k l -> all_greater_than_one l ->\n   forall l' b, update_primes k l = (l',b) -> all_intervals (S k) l'.\nProof.\n intros k l; elim l.\n -  simpl; intros Hai Hal l' b Hup; injection Hup;\n      intros Hb Hl'; rewrite <- Hl'.\n    intros l1 l2 n p Heq; elim (absurd_decompose_list _ _ _ _ Heq).\n -  simpl; intros (p, n) l0 Hrec Hai Hal l' b;\n      case_eq (update_primes k l0); intros l'0 b0 Hup0 Hup l1.\n    case l1.\n    + unfold all_intervals in Hai.\n      case_eq (Nat.compare k n); simpl; intros Htwc l2 p' n' Heq;\n        rewrite Htwc in Hup; injection Hup; intros Hb Hl';\n          rewrite <- Hl' in Heq; injection Heq; intros Hl2 Hn' Hp';\n            rewrite <- Hp'; rewrite <- Hn';\n              generalize (Hai nil l0 p n (refl_equal _));\n              intros (Hlt, Hle);split; \n                (generalize (nat_compare_Lt_lt _ _ Htwc) ||\n                 generalize (nat_compare_eq _ _ Htwc) ||\n                 generalize (nat_compare_Gt_gt _ _ Htwc));\n                auto with arith. (* ICI *)\n      *  intros Heq2; rewrite Heq2; rewrite plus_comm; rewrite minus_plus;\n           auto with arith.\n      * intros Heq2; rewrite Heq2; unfold all_greater_than_one in Hal;\n          generalize (Hal nil l0 p n (refl_equal _)); intros Hpgt1.\n        pattern n at 1; rewrite plus_n_O; rewrite plus_n_Sm;\n          apply plus_le_compat; auto with arith.\n      * rewrite plus_comm; rewrite minus_plus; auto with arith.\n      *  generalize (Hal nil l0 p n (refl_equal _)); intros Hpgt1.\n         intros Hkltn; pattern k at 1; rewrite plus_n_O; rewrite plus_n_Sm;\n           apply plus_le_compat; auto with arith.\n    + generalize (all_intervals_transmit _ _ _ Hai); intros Hai'.\n      generalize (all_greater_than_one_transmit _ _ Hal); intros Hal'.\n      simpl; clear l1; intros fst_elem l1 l2 p' n' Heq; generalize Hup;\n        rewrite Heq.\n      case (Nat.compare k n); intros Hup'; injection Hup'; \n        intros Hb Hl' _; apply (Hrec Hai' Hal' l'0 b0 Hup0 l1 l2); assumption.\nQed.\n\nTheorem all_first_less_than_S :\n  forall k l, all_first_less_than k l -> all_first_less_than (S k) l.\nProof.\n  intros k l; elim l.\n  -  intros Haf l1 l2 p n Heq; elim (absurd_decompose_list _ _ _ _ Heq).\n  -  intros (p,n) l0 Hrec Haf l1.\n     case l1.\n     +  intros l2 p' n' Heq;\n          generalize (Haf nil l2 p' n' Heq); intros Hpltk.\n        auto with arith.\n     + simpl; clear l1; intros fst_elem l1 l2 p' n' Heq.\n       injection Heq; intros; \n         apply (Hrec (all_first_less_than_transmit _ _ _ Haf) l1 l2 p' n');\n         assumption.\nQed.\n\nTheorem all_intervals_add :\n forall (l:list(nat*nat))(k p n:nat),\n  n-p < k <= n ->\n  all_intervals k l ->\n  all_intervals k ((p,n)::l).\nProof.\n intros l k p n Hint Hai l1; case l1.\n - intros l2 p' n' Heq; injection Heq; intros Hl Hn' Hp';\n     rewrite <- Hn'; rewrite <- Hp'; auto.\n -  simpl; clear l1; intros fst_elem l1 l2 p' n' Heq; injection Heq;\n      intros Hl Hfst; apply (Hai l1 l2); assumption.\nQed.\n\nTheorem all_first_prime_add :\n  forall (l:list(nat*nat))(p n:nat),\n    prime p ->\n    all_first_prime l -> all_first_prime ((p,n)::l).\nProof.\n  intros l p n Hlt Haf l1; case l1.\n  -  intros l2 p' n' Heq; injection Heq; intros Hl Hn' Hp';\n       rewrite <- Hp'; assumption.\n  -  simpl; clear l1; intros fst_elem l1 l2 p' n' Heq; injection Heq;\n       intros Hl Hfst; apply (Haf l1 l2 p' n' Hl).\nQed.\n\nTheorem all_multiples_add :\n  forall l n p,\n    (exists q:nat, n=p*q)->\n    all_multiples l ->\n    all_multiples ((p,n)::l).\nProof.\n  intros l n p Hdiv Ham l1; case l1.\n  - simpl; intros l2 p' n' Heq; injection Heq;\n      intros Hl2 Hn' Hp'; rewrite <- Hn'; rewrite <- Hp';\n        assumption.\n\n  - clear l1; simpl; intros fst_elem l1 l2 p' n' Heq; injection Heq;\n      intros Hl Hfst; apply (Ham l1 l2); assumption.\nQed.\n\nTheorem all_greater_than_one_add :\n  forall l n p,\n    1 < p -> all_greater_than_one l ->\n    all_greater_than_one ((p,n)::l).\nProof.\n  intros l n p Hlt Hal  l1; case l1.\n  - simpl; intros l2 p' n' Heq; injection Heq;\n      intros Hl2 Hn' Hp'; rewrite <- Hp';\n        assumption.\n  -  clear l1; simpl; intros fst_elem l1 l2 p' n' Heq; injection Heq;\n       intros Hl Hfst; apply (Hal l1 l2 p' n'); assumption.\nQed.\n\nFixpoint same_first (l1 l2:list(nat*nat)) {struct l1} : bool :=\n  match l1, l2 with\n    nil, nil => true\n  | ((a, _)::l'1), ((b, _)::l'2) =>\n    match Nat.compare a b with\n    | Eq => same_first l'1 l'2\n    | _ => false\n    end\n  | _, _ => false\n  end.\n\nTheorem update_primes_same_first :\n  forall k l l' b,\n    update_primes k l = (l', b) ->\n    forall l1 l2 p n,\n      l = l1++(p,n)::l2 -> \n      (exists l'1 : list(nat*nat),\n          (exists l'2 : list(nat*nat),\n              (exists n': nat,\n                  l'=l'1++(p,n')::l'2))).\nProof.\n  intros k l; elim l.\n  - intros l' b Hup l1 l2 p n Heq; elim (absurd_decompose_list _ _ _ _ Heq).\n\n  - intros (p,n) l0 Hrec l' b.\n    simpl; case_eq (update_primes k l0); intros l'0 b0 Hup'.\n    case (Nat.compare k n); intros Hup; injection Hup;\n      intros Hb Hl'; intros l1; (case l1; [simpl; intros l2 p0 n0 Heq;\n                                           injection Heq; intros Hl2 Hn0 Hp0; rewrite <- Hl'; rewrite <- Hp0;\n                                           exists (nil (A:=nat*nat)); exists l'0 | \n                                           clear l1; simpl; intros fst_elem l1 l2 p0 n0 Heq; injection Heq;\n                                           intros Hl0 Hfst_elem; rewrite <- Hl';\n                                           elim (Hrec l'0 b0 Hup' l1 l2 p0 n0 Hl0); intros l'1 (l'2, (n', Heq2));\n                                           rewrite Heq2]).\n    +  exists (n+p); reflexivity.\n    +  exists ((p,n+p)::l'1); exists l'2; exists n'; reflexivity.\n    + exists n; reflexivity.\n    +  exists ((p,n)::l'1); exists l'2; exists n'; reflexivity.\n    +  exists (n+p); reflexivity.\n    + exists ((p,n+p)::l'1); exists l'2; exists n'; reflexivity.\nQed.\n\nTheorem update_primes_all_prime_in_first :\n forall k l l' b,\n  all_prime_in_first k l ->\n  update_primes k l = (l', b) ->\n  all_prime_in_first k l'.\nProof.\n intros k l l' b Hap Hup p Hplek Hpr.\n elim (Hap p Hplek Hpr); intros l'1 (l'2, (n', Heq)).\n apply (update_primes_same_first k l l' b Hup l'1 l'2 p n' Heq).\nQed.\n\n\nTheorem prime_sieve_invariant :\n  forall k l,\n    prime_sieve (S k)=l ->\n    all_first_less_than (S (S k)) l /\\\n    all_first_prime l /\\\n    all_prime_in_first (S (S k)) l /\\\n    all_intervals (S (S k)) l /\\\n    all_multiples l /\\\n    all_greater_than_one l.\nProof.\n  intros k; elim k.\n  -   simpl; intros l Hl; rewrite <- Hl; clear Hl l.\n      split;[idtac | split; [idtac | split;[idtac|split;[idtac|split]]]];\n        try (intros l1 l2 p n Heq; elim (absurd_decompose_list _ _ _ _ Heq)).\n      intros n Hle1 ((Hnneq0, Hnneq1),_); elim Hnneq1.\n      elim Hle1; intros; apply (le_antisym n 1); auto with arith.\n  - \n    intros k' Hrec l Hps.\n    change ((let (l', b) := \n                 update_primes (S (S k')) (prime_sieve (S k')) in\n             if b then l' else (S (S k'), 2*S (S k'))::l') = l) in Hps.\n    case_eq (update_primes (S (S k')) (prime_sieve (S k'))); intros l' b Heq.\n    generalize (Hrec (prime_sieve (S k'))); intros Hrec'.\n    assert (Hal: all_first_less_than (S (S k')) l').\n    {\n      apply update_primes_all_first_less_than with (prime_sieve (S k')) b; auto.\n      intuition.\n    }\n    assert (Hafp: all_first_prime l').\n    { apply update_primes_all_first_prime \n        with (S (S k')) (prime_sieve (S k')) b; auto.\n      intuition.\n    }\n    assert (Hapf: all_prime_in_first (S (S k')) l').\n    { apply update_primes_all_prime_in_first with (prime_sieve (S k')) b; auto.\n      intuition.\n    }\n    assert (Hai : all_intervals (S (S (S k'))) l').\n    {\n      apply update_primes_all_intervals with (prime_sieve (S k')) b; auto.\n      intuition.\n      intuition.\n    }\n\n    assert (Ham : all_multiples l').\n    { apply update_primes_all_multiples \n        with (S (S k')) (prime_sieve (S k')) b; auto.\n      intuition.\n    }\n    assert (Ha1 : all_greater_than_one l').\n    {\n      apply update_primes_all_greater_than_one with (S (S k')) (prime_sieve (S k')) b; auto.\n      intuition.\n    }\n    case_eq b; intros Heqb; rewrite Heqb in Heq; rewrite Heq in Hps.\n    + rewrite <- Hps.\n      split;[idtac|split;[idtac|split;[idtac|split;[idtac|split;[idtac|idtac]]]]]; \n        auto.\n      * apply all_first_less_than_S; assumption.\n      * unfold all_prime_in_first.\n        intros n Hint Hpr; unfold all_prime_in_first in Hapf; apply Hapf; auto.\n        split.\n        -- intuition.\n        -- elim Hint.\n           intros Hngt0 Hnlek.\n           elim (le_lt_or_eq _ _ Hnlek).\n           ++ auto with arith; fail.\n           ++ intros Hn'; injection Hn'.\n              intros Hn; rewrite Hn in Hpr; elim Hpr.\n              intros _ Hnex; elim Hnex.\n              unfold divides.\n              apply update_primes_true_imp_div with (prime_sieve (S k')) l'.\n              ** intuition.\n              ** intuition.\n              ** intuition.\n              ** auto.\n    + split.\n      * \n        intros l1; case l1.\n        -- simpl; intros l2 p n; rewrite <- Hps; intros Heq2;injection Heq2.\n           intros Hl2 Hn Hp; rewrite <- Hp; auto with arith.\n        -- intros fst_elem l'1 l2 p n; simpl; rewrite <- Hps; intros Heq2;\n             injection Heq2; intros Hl' Hfst_elem.\n           assert (Hal' : all_first_less_than (S (S (S k'))) l').\n           { apply all_first_less_than_S; auto. }\n           apply (Hal' l'1 l2 p n); auto.\n      * split.\n        -- rewrite <- Hps; apply all_first_prime_add; auto.\n           apply update_primes_false_imp_prime with (prime_sieve (S k')) l';\n             try tauto.\n           auto with arith.\n        -- split.\n           ++ rewrite <- Hps.\n              intros n (Hpos, Hle) Hpr.\n              elim (le_lt_or_eq _ _ Hle).\n              ** intros Hlt; elim (Hapf n); auto with arith.\n                 intros l'1 (l'2, (p, Heq2));\n                   exists ((S (S k'), 2*S(S k'))::l'1); exists l'2; exists p.\n                 rewrite Heq2;reflexivity.\n              ** intros Hn'; injection Hn'; intros Hn.\n                 exists (nil (A:=nat*nat)); exists l'; exists (2*S (S k')).\n                 rewrite Hn;reflexivity.\n           ++ split.\n              ** rewrite <- Hps; apply all_intervals_add; auto with arith.\n                 split.\n                 { simpl.\n                   rewrite minus_plus.\n                   rewrite <- plus_n_O.\n                   auto with arith.\n                 }\n                 { simpl.\n                   repeat rewrite <- plus_n_Sm.\n                   auto with arith.\n                 }\n\n              ** split.\n                 { rewrite <- Hps; apply all_multiples_add; auto with arith. \n                   exists 2; rewrite (mult_comm 2); reflexivity. }\n\n                 rewrite <- Hps.\n                 apply all_greater_than_one_add; auto with arith.\nQed.\n\nTheorem prime_fun_sound :\n  forall k, prime_fun k = true -> prime k.\nProof.\n  intros k0; case k0.\n  - simpl; intros; discriminate.\n  -  intros k; unfold prime_fun.\n     case_eq (prime_sieve (S k)).\n     +  \n       intros; discriminate.\n     + intros (p,n) l Heq; case_eq (Nat.compare p (S k));\n         try(intros; discriminate; fail).\n       intros Htwc _.\n       assert (Hap:all_first_prime ((p,n)::l)).\n       {  generalize (prime_sieve_invariant k ((p,n)::l) Heq); intuition. }\n       rewrite <- (nat_compare_eq _ _ Htwc).\n       apply (Hap nil l p n); auto.\nQed.\n\nTheorem prime_fun_complete :\n  forall k, prime k -> prime_fun k = true.\nProof.\n  intros k; case k.\n  -  intros ((Hneq0, Hneq1),Hnex); elim Hneq0; auto.\n  - intros k'; case k'.\n    +  intros ((Hneq0, Hneq1),Hnex); elim Hneq1; auto.\n    + intros k'' ((_,_),Hnex); unfold prime_fun.\n      assert (Hps: prime_sieve (S (S k'')) = \n                   let (l',b) := (update_primes (S (S k'')) (prime_sieve (S k''))) \n                   in\n                   if b then l' else ((S (S k''), 2*S (S k''))::l')).\n      {  auto. }\n      rewrite Hps.\n      case_eq  (update_primes (S (S k'')) (prime_sieve (S k''))).\n      intros l' b; case b; intros Hup.\n      *  elim Hnex.\n         unfold divides.\n         generalize (prime_sieve_invariant k'' (prime_sieve (S k'')));\n           intros Hinv.\n         apply (update_primes_true_imp_div (S (S k''))\n                                           (prime_sieve (S k''))) with l';\n           intuition.\n      *  rewrite (Nat.compare_refl (S (S k''))); 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/ch6_inductive_data/SRC/erato.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6555217156036736}}
{"text": "Require Import Coq.ZArith.Int.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import PeanoNat.\nRequire Import Coq.Arith.Arith.\n\n(* Option monad utilities *)\nDefinition bind{A B: Type} (x : option A) (f : A -> B) :=\n  match x with\n  | None => None\n  | Some x => Some (f x)\n  end.\n\n(* Variables are just a nat *)\nDefinition Var := nat.\n\n(* Registers (infinite) map nats to Z *)\nDefinition Regs := nat -> Z.\n\nDefinition get (var : Var) (r : Regs) := r var.\n\nDefinition put (var : Var) v (r : Regs) :=\n  fun var' => if var' =? var then v else r var'.\n\n(* Registers are zeroed by default *)\nDefinition emptyRegs :=\n  fun (var' : Var) => Z0.\n\nInductive Stmt :=\n  | SAdd (a b c : Var) (* a = b + c *)\n  | SIf (cond : Var) (trueEval falseEval : Stmt) (* if cond == 0 then falseEval else trueEval *)\n  | SSeq (s1 s2 : Stmt) (* s1 ; s2 *)\n  | SLit (a : Var) (v : Z) (* a = $v *)\n  | SNop\n  .\n\nOpen Scope Z_scope.\n\nDefinition inc_eval_log (inc : Z) (res : option (Z * Regs)) :=\n  bind res (fun x => ((fst x) + inc, snd x)).\n\nFixpoint eval_stmt_log (fuel : nat) (s : Stmt) (r : Regs) :=\n  match fuel with\n  | O => None\n  | S f => match s with\n           | SAdd a b c => Some (1, put a ((get b r) + (get c r)) r)\n           | SIf cond trueEval falseEval => if (Z.eqb (get cond r) 0%Z) then\n                                              inc_eval_log 1 (eval_stmt_log f falseEval r)\n                                            else\n                                              inc_eval_log 1 (eval_stmt_log f trueEval r)\n           | SSeq s1 s2 => match eval_stmt_log f s1 r with\n                           | None => None\n                           | Some (count, r') => inc_eval_log count (eval_stmt_log f s2 r')\n                           end\n           | SLit a v => Some (1, put a v r)\n           | SNop => Some (1, r)\n           end\n  end.\n\nClose Scope Z_scope.\n\nDefinition var_a := 1.\nDefinition var_b := 2.\nDefinition var_tmp := 3.\n\n(* Test stmt, loads n into var_a and doubles it *)\nDefinition eg_double_stmt n :=\n  SSeq (SLit var_a n) (SAdd var_a var_a var_a).\n\nDefinition eg_double_res n := (eval_stmt_log 5 (eg_double_stmt n) emptyRegs).\n\nDefinition eg_double_instructions n := bind (eg_double_res n) fst.\nDefinition eg_double_regs n := bind (eg_double_res n) snd.\nDefinition eg_double_val n := bind (eg_double_regs n) (get var_a).\n\nLemma eg_double_5_correct : eg_double_val 5%Z = Some 10%Z.\nProof. reflexivity. Qed.\n\nLemma eg_double_neg12_correct : eg_double_val (Z.neg 12) = Some (Z.neg 24).\nProof. reflexivity. Qed.\n\nInductive Instr :=\n  | IAdd (a b c : Var)\n  | IJump (pc : nat) \n  | IBeqz (a : Var) (pc : nat)\n  | IImm (a : Var) (v : Z)\n  | INop\n  .\n\nFixpoint compile_stmt (s : Stmt) :=\n  match s with\n  | SAdd a b c => [IAdd a b c]\n  | SIf c t f => match (compile_stmt t) with\n                 | t' => match (compile_stmt f) with\n                         | f' => [IBeqz c (1 + (length t'))] ++ t' ++ [IJump (length f')] ++ f'\n                         end\n                 end\n  | SSeq s1 s2 => (compile_stmt s1) ++ (compile_stmt s2)\n  | SLit a v => [IImm a v]\n  | SNop => [INop]\n  end.\n\nRecord InstrMachineLog := mkInstrMachineLog {\n  Iregs : Regs;\n  Ipc : nat;\n  Icount : Z;\n}.\n\nDefinition emptyMachineLog := mkInstrMachineLog emptyRegs 0 0.\n\nDefinition with_Iregs r m := mkInstrMachineLog r m.(Ipc) m.(Icount).\nDefinition with_Ipc p m := mkInstrMachineLog m.(Iregs) p m.(Icount).\nDefinition with_Icount c m := mkInstrMachineLog m.(Iregs) m.(Ipc) c.\n\nDefinition inc_count (n : Z) m := with_Icount (m.(Icount) + n) m.\nDefinition inc_pc p m := with_Ipc ((m.(Ipc) + p)) m.\n\nDefinition add_regs a b c m := with_Iregs (put a ((get b m.(Iregs)) + (get c m.(Iregs))) m.(Iregs)) m.\nDefinition load_imm a v m := with_Iregs (put a v m.(Iregs)) m.\n\n\nFixpoint eval_instr_log fuel (m : InstrMachineLog) (instrs : list Instr) pcf : option InstrMachineLog :=\n  match fuel with\n  | O => None\n  | S fuel' => if pcf =? m.(Ipc) then Some m else\n                 match nth_error instrs m.(Ipc) with\n                 | None => None (* Should never happen *)\n                 | Some i => eval_instr_log fuel' (inc_count 1 (\n                               match i with\n                               | IAdd a b c => inc_pc 1 (add_regs a b c (m))\n                               | IJump pc' => inc_pc (pc' + 1) m\n                               | IBeqz a pc' => inc_pc (if (Z.eqb (get a m.(Iregs)) 0%Z) then pc' + 1 else 1) m\n                               | IImm a v => inc_pc 1 (load_imm a v m)\n                               |  INop => inc_pc 1 m\n                               end)) instrs pcf\n                 end\n  end.\n\nDefinition get_compiled_result (s: Stmt) (result_var : Var) :=\n  let c := compile_stmt s in\n    match eval_instr_log 100 emptyMachineLog c ((length c) - 1) with\n    | None => None\n    | Some m => Some (get result_var m.(Iregs))\n    end.\n\nFixpoint stmt_list_to_stmt l :=\n  match l with\n  | [] => SNop\n  | hd :: tl => SSeq hd (stmt_list_to_stmt tl)\n  end.\n\n(* if (a == 5) then b = 500 else b = 100 *)\n\nDefinition eg_cond_stmt a := stmt_list_to_stmt\n  [\n    (SLit var_a a);\n    (SLit var_tmp (Z.neg 5));\n    (SAdd var_a var_a var_tmp);\n    (SIf var_a \n      (SLit var_b 100) \n      (SLit var_b 500)\n    )\n  ].\n\nCompute (compile_stmt (eg_cond_stmt 5%Z)).\n\nLemma eg_cond_5_correct : get_compiled_result (eg_cond_stmt 5%Z) var_b = Some 500%Z.\nProof. reflexivity. Qed.\n\nLemma eg_cond_neg12_correct : get_compiled_result (eg_cond_stmt (Z.neg 12)) var_b = Some 100%Z.\nProof. reflexivity. Qed.\n\nLemma inc_log : forall n x countH Hfr,\n  inc_eval_log n x = Some (countH, Hfr) ->\n  x = Some ((countH - n)%Z, Hfr).\nProof.\nintros. unfold inc_eval_log in H.\ndestruct x.\n- inversion H. f_equal. rewrite Z.add_simpl_r. apply surjective_pairing.\n- discriminate.\nQed.\n\nLemma fetch_inst : forall (instsBefore instsAfter : list Instr) x,\n  nth_error (instsBefore ++ x :: instsAfter) (length instsBefore) = Some x.\nProof.\ninduction instsBefore.\n- reflexivity.\n- auto.\nQed.\n\nOpen Scope Z_scope.\n\nLemma bounded_instrs :\nforall (fuelH fuelL: nat) (s : Stmt) countH Hfr Lfr instsBefore instsAfter startCountL endCountL ir,\n  eval_stmt_log fuelH s ir = Some (countH, Hfr) ->\n  eval_instr_log fuelL\n    (mkInstrMachineLog ir (length instsBefore) startCountL)\n    (instsBefore ++ compile_stmt s ++ instsAfter)\n    (length (instsBefore ++ compile_stmt s))%nat\n    = Some (mkInstrMachineLog Lfr (length (instsBefore ++ compile_stmt s))%nat endCountL) ->\n  (endCountL - startCountL) < 3 * countH.\nProof.\ninduction fuelH.\n- discriminate.\n- destruct s.\n  + (* s = SAdd a b c *) \n    intros countH Hfr Lfr instsBefore instsAfter startCountL endCountL ir HHi HLo.\n    inversion HHi.\n    destruct fuelL. discriminate.\n    rewrite app_length in HLo. simpl in HLo.\n    replace (_ + 1 =? _)%nat with false in HLo.\n    2 : { symmetry. rewrite Nat.eqb_neq. omega. }\n    replace (nth_error (_) (_)) with (Some (IAdd a b c)) in HLo.\n    2 : { symmetry. apply fetch_inst. }\n    destruct fuelL. discriminate.\n    simpl in HLo.\n    replace (_ =? _)%nat with true in HLo.\n    2 : { symmetry. rewrite Nat.eqb_eq. reflexivity. }\n    inversion HLo. omega.\n  + (* s = SIf cond trueEval falseEval *)\n    intros countH Hfr Lfr instsBefore instsAfter startCountL endCountL ir HHi HLo.\n    simpl in HHi. \n    destruct fuelL. discriminate.\n    simpl in HLo.\n    replace (_ =? _)%nat with false in HLo.\n    2 : { symmetry. rewrite Nat.eqb_neq. rewrite app_length. simpl. omega. }\n    replace (nth_error _ _) with (Some (IBeqz cond (S (length (compile_stmt s1))))) in HLo.\n    2 : { rewrite (\n              fetch_inst\n              instsBefore\n              ((compile_stmt s1 ++ IJump (length (compile_stmt s2)) :: compile_stmt s2) ++ instsAfter)\n              (IBeqz cond (S (length (compile_stmt s1))))). f_equal. }\n    destruct fuelL. discriminate.\n    destruct fuelH. { destruct (get cond ir =? 0). discriminate. discriminate. } \n    destruct (get cond ir =? 0) eqn:HCond.\n    * (* False condition (s2) *)\n      apply (inc_log 1 (eval_stmt_log (S fuelH) s2 ir) countH Hfr) in HHi.\n      specialize (\n        IHfuelH (S fuelL) s2 (countH - 1) Hfr Lfr\n        ((instsBefore ++ [IBeqz cond (1 + (length (compile_stmt s1)))]) ++ (compile_stmt s1) ++ [IJump (length (compile_stmt s2))])\n        instsAfter (startCountL + 1) endCountL ir).\n      assert (HIneq: endCountL - (startCountL + 1) < 3 * (countH - 1) -> endCountL - startCountL < 3 * countH). omega.\n      apply HIneq.\n      apply IHfuelH.\n      ** apply HHi.\n      ** assert(HPc: length\n                 (instsBefore ++\n                  IBeqz cond (S (length (compile_stmt s1)))\n                  :: compile_stmt s1 ++ IJump (length (compile_stmt s2)) :: compile_stmt s2) =\n                length\n                 (((instsBefore ++ [IBeqz cond (1 + length (compile_stmt s1))]) ++\n                  compile_stmt s1 ++ [IJump (length (compile_stmt s2))]) ++ compile_stmt s2)).\n         { repeat rewrite <- app_assoc. repeat rewrite app_length.\n           f_equal. simpl. rewrite app_length. simpl. reflexivity. }\n         rewrite HPc in HLo.\n         rewrite <- HLo. repeat rewrite <- app_assoc. f_equal.\n         *** unfold inc_count. unfold inc_pc. unfold with_Icount. unfold with_Ipc.\n             unfold Iregs. unfold Ipc. unfold Icount. f_equal.\n             repeat rewrite app_length. reflexivity.\n    * (* True condition (s1) *)\n      apply (inc_log 1 (eval_stmt_log (S fuelH) s1 ir) countH Hfr) in HHi.\n      admit.\n  + (* s = SSeq s1 s2 *)\n    admit.\n  + (* s = SLit a v *)\n    admit.\n  + (* s = SNop *)\n    admit.\nAdmitted.", "meta": {"author": "Carotti", "repo": "dummy-compiler", "sha": "cda717fc79ec12ce2bb70dda1ca686ec7f441932", "save_path": "github-repos/coq/Carotti-dummy-compiler", "path": "github-repos/coq/Carotti-dummy-compiler/dummy-compiler-cda717fc79ec12ce2bb70dda1ca686ec7f441932/compiler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6555217117423994}}
{"text": "(**\n  This formalises Theorem 3.6 from \"The Joy of Cryptography\" (p. 51).\n  It is a simple 2-out-of-2 secret-sharing scheme with perfect security,\n  based on XOR.\n\n  It is fairly simple to understand. The hardest part is probably the definition\n  of [plus] (XOR), which is not really necessary to understand the proof.\n\n  The final statement ([unconditional_secrecy]) is equivalent to that of the\n  books: The scheme achieves perfect secerery with up to two shares\n  (non-inclusive).\n*)\n\nFrom Relational Require Import OrderEnrichedCategory GenericRulesSimple.\n\nSet Warnings \"-notation-overridden,-ambiguous-paths\".\nFrom mathcomp Require Import all_ssreflect all_algebra reals distr realsum\n  ssrnat ssreflect ssrfun ssrbool ssrnum eqtype choice seq.\nSet Warnings \"notation-overridden,ambiguous-paths\".\n\nFrom Mon Require Import SPropBase.\nFrom Crypt Require Import Axioms ChoiceAsOrd SubDistr Couplings\n  UniformDistrLemmas FreeProbProg Theta_dens RulesStateProb\n  pkg_core_definition choice_type pkg_composition pkg_rhl Package Prelude.\n\nFrom extructures Require Import ord fset fmap.\n\nImport SPropNotations.\n\nImport PackageNotation.\n\nFrom Equations Require Import Equations.\nRequire Equations.Prop.DepElim.\n\nSet Equations With UIP.\n\nSet Bullet Behavior \"Strict Subproofs\".\nSet Default Goal Selector \"!\".\nSet Primitive Projections.\n\nImport Num.Def.\nImport Num.Theory.\nImport Order.POrderTheory.\n\nSection SecretSharing_example.\n\nVariable (n: nat).\n\nDefinition Word_N: nat := 2^n.\nDefinition Word: choice_type := chFin (mkpos Word_N).\n\n(**\n  The first bit is a formalisation of [plus] (XOR).\n  It is similar to the definitions in OTP.v and PRF.v, but it has been split\n  into lemmas to hopefully be easier to read.\n  It is still somewhat unwieldy though.\n*)\n\n(**\n  Lemmas for the [plus] obligation.\n*)\nLemma pow2_inj m:\n  (2 ^ m)%N = BinNat.N.to_nat (BinNat.N.pow (BinNums.Npos (BinNums.xO 1%AC)) (BinNat.N.of_nat m)).\nProof.\n  elim: m => [// | m IHm].\n  rewrite expnSr Nnat.Nat2N.inj_succ BinNat.N.pow_succ_r' Nnat.N2Nat.inj_mul PeanoNat.Nat.mul_comm.\n  by apply: f_equal2.\nQed.\n\nLemma log2_lt_pow2 w m:\n  (w.+1 < 2^m)%N ->\n  BinNat.N.lt (BinNat.N.log2 (BinNat.N.of_nat w.+1)) (BinNat.N.of_nat m).\nProof.\n  move=> H.\n  rewrite -BinNat.N.log2_lt_pow2.\n  - rewrite /BinNat.N.lt Nnat.N2Nat.inj_compare PeanoNat.Nat.compare_lt_iff -pow2_inj Nnat.Nat2N.id.\n    by apply /ltP.\n  - rewrite Nnat.Nat2N.inj_succ.\n    by apply: BinNat.N.lt_0_succ.\nQed.\n\n#[program] Definition plus (w k: Word): Word :=\n  @Ordinal _ (BinNat.N.to_nat (BinNat.N.lxor\n    (BinNat.N.of_nat (nat_of_ord w))\n    (BinNat.N.of_nat (nat_of_ord k)))) _.\nNext Obligation.\n  move: w k => [[|w] Hw] [[|k] Hk].\n  1-3: by rewrite /= ?Pnat.SuccNat2Pos.id_succ.\n  move: (log2_lt_pow2 _ _ Hw) => H1.\n  move: (log2_lt_pow2 _ _ Hk) => H2.\n  move: (BinNat.N.max_lub_lt _ _ _ H1 H2) => Hm.\n  case: (BinNat.N.eq_dec (BinNat.N.lxor (BinNat.N.of_nat w.+1) (BinNat.N.of_nat k.+1)) BinNat.N0) => H0.\n  1: by rewrite H0 expn_gt0.\n  move: (BinNat.N.log2_lxor (BinNat.N.of_nat w.+1) (BinNat.N.of_nat k.+1)) => Hbound.\n  move: (BinNat.N.le_lt_trans _ _ _ Hbound Hm).\n  rewrite -BinNat.N.log2_lt_pow2.\n  2: by apply BinNat.N.neq_0_lt_0.\n  rewrite /BinNat.N.lt Nnat.N2Nat.inj_compare PeanoNat.Nat.compare_lt_iff -pow2_inj.\n  by move /ltP.\nQed.\n\nNotation \"m ⊕ k\" := (plus m k) (at level 70).\n\n(**\n  Some lemmas for [plus] itself.\n*)\nLemma plus_comm m k:\n  (m ⊕ k) = (k ⊕ m).\nProof.\n  apply: ord_inj.\n  case: m => m ? /=.\n  by rewrite BinNat.N.lxor_comm.\nQed.\n\nLemma plus_assoc m l k:\n  ((m ⊕ l) ⊕ k) = (m ⊕ (l ⊕ k)).\nProof.\n  apply: ord_inj.\n  case: m => m ? /=.\n  rewrite !Nnat.N2Nat.id.\n  by rewrite BinNat.N.lxor_assoc.\nQed.\n\nLemma plus_involutive m k:\n  (m ⊕ k) ⊕ k = m.\nProof.\n  rewrite plus_assoc.\n  apply: ord_inj.\n  case: m => m ? /=.\n  rewrite Nnat.N2Nat.id.\n  rewrite BinNat.N.lxor_nilpotent.\n  rewrite BinNat.N.lxor_0_r.\n  by rewrite Nnat.Nat2N.id.\nQed.\n\n#[local] Open Scope package_scope.\n\nNotation \" 'word \" := (Word) (in custom pack_type at level 2).\nNotation \" 'word \" := (Word) (at level 2): package_scope.\n\n(**\n  We can't use sequences directly in [choice_type] so instead we use a map from\n  natural numbers to the type.\n*)\nDefinition chSeq t := chMap 'nat t.\n\nNotation \" 'seq t \" := (chSeq t) (in custom pack_type at level 2).\nNotation \" 'seq t \" := (chSeq t) (at level 2): package_scope.\n\n(**\n  We can't use sets directly in [choice_type] so instead we use a map to units.\n  We can then use [domm] to get the domain, which is a set.\n*)\nDefinition chSet t := chMap t 'unit.\n\nNotation \" 'set t \" := (chSet t) (in custom pack_type at level 2).\nNotation \" 'set t \" := (chSet t) (at level 2): package_scope.\n\nDefinition shares: nat := 0.\n\nDefinition SHARE_pkg_tt:\n  package fset0 [interface]\n    [interface #val #[shares]: ('word × 'word) × 'set 'nat → 'seq 'word ] :=\n  [package\n    #def #[shares] ('(ml, mr, U): ('word × 'word) × 'set 'nat): 'seq 'word {\n      if size (domm U) >= 2 then ret emptym\n      else\n      s0 <$ uniform (2^n) ;;\n      let s1 := s0 ⊕ ml in\n      let sh := [fmap (0, s0) ; (1, s1)] in\n      ret (fmap_of_seq (pmap sh (domm U)))\n    }\n  ].\n\nDefinition SHARE_pkg_ff:\n  package fset0 [interface]\n    [interface #val #[shares]: ('word × 'word) × 'set 'nat → 'seq 'word ] :=\n  [package\n    #def #[shares] ('(ml, mr, U): ('word × 'word) × 'set 'nat): 'seq 'word {\n      if size (domm U) >= 2 then ret emptym\n      else\n      s0 <$ uniform (2^n) ;;\n      let s1 := s0 ⊕ mr in\n      let sh := [fmap (0, s0) ; (1, s1)] in\n      ret (fmap_of_seq (pmap sh (domm U)))\n    }\n  ].\n\nDefinition mkpair {Lt Lf E}\n  (t: package Lt [interface] E) (f: package Lf [interface] E):\n  loc_GamePair E := fun b => if b then {locpackage t} else {locpackage f}.\n\nDefinition SHARE := mkpair SHARE_pkg_tt SHARE_pkg_ff.\n\nLemma SHARE_equiv:\n  SHARE true ≈₀ SHARE false.\nProof.\n  apply: eq_rel_perf_ind_eq.\n  simplify_eq_rel m.\n  apply rpost_weaken_rule with eq;\n    last by move=> [? ?] [? ?] [].\n  case m => [[ml mr] U].\n  case: (_ (domm U)) => {U} [|a U] /=.\n  1: by apply: rreflexivity_rule.\n  case: U => [|b U] /=.\n  2: by apply: rreflexivity_rule.\n  case: a => [|[|a]] /=.\n  1,3: by apply: rreflexivity_rule.\n  apply: r_uniform_bij => [|s0].\n  1: {\n    exists (fun x => x ⊕ (ml ⊕ mr)) => x.\n    all: by apply: plus_involutive.\n  }\n  rewrite plus_assoc plus_involutive.\n  by apply: rreflexivity_rule.\nQed.\n\n(**\n  This corresponds to Theorem 3.6 from \"The Joy of Cryptography\".\n*)\nTheorem unconditional_secrecy LA A:\n  ValidPackage LA\n    [interface #val #[shares]: ('word × 'word) × 'set 'nat → 'seq 'word ]\n    A_export A ->\n  Advantage SHARE A = 0%R.\nProof.\n  move=> vA.\n  rewrite Advantage_E Advantage_sym.\n  by rewrite SHARE_equiv ?fdisjoints0.\nQed.\n\nEnd SecretSharing_example.\n", "meta": {"author": "SSProve", "repo": "ssprove", "sha": "5dce3e2eae195fc466035e314ef4463d956c9c6a", "save_path": "github-repos/coq/SSProve-ssprove", "path": "github-repos/coq/SSProve-ssprove/ssprove-5dce3e2eae195fc466035e314ef4463d956c9c6a/theories/Crypt/examples/SecretSharing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6555217095080877}}
{"text": "Require\n  MathClasses.interfaces.naturals MathClasses.theory.naturals MathClasses.implementations.peano_naturals MathClasses.theory.integers.\nRequire Import\n  Coq.ZArith.BinInt Coq.setoid_ring.Ring Coq.Arith.Arith Coq.NArith.NArith Coq.ZArith.ZArith Coq.Numbers.Integer.Binary.ZBinary\n  MathClasses.interfaces.abstract_algebra MathClasses.interfaces.integers\n  MathClasses.implementations.natpair_integers MathClasses.implementations.stdlib_binary_naturals\n  MathClasses.interfaces.additional_operations MathClasses.interfaces.orders\n  MathClasses.implementations.nonneg_integers_naturals.\n\n(* canonical names: *)\nInstance Z_equiv: Equiv Z := eq.\nInstance Z_plus: Plus Z := Zplus.\nInstance Z_0: Zero Z := 0%Z.\nInstance Z_1: One Z := 1%Z.\nInstance Z_mult: Mult Z := Zmult.\nInstance Z_negate: Negate Z := Zopp.\n  (* some day we'd like to do this with [Existing Instance] *)\n\nInstance: Ring Z.\nProof.\n  repeat (split; try apply _); repeat intro.\n           now apply Zplus_assoc.\n          now apply Zplus_0_r.\n         now apply Zplus_opp_l.\n        now apply Zplus_opp_r.\n       now apply Zplus_comm.\n      now apply Zmult_assoc.\n     now apply Zmult_1_l.\n    now apply Zmult_1_r.\n   now apply Zmult_comm.\n  now apply Zmult_plus_distr_r.\nQed.\n\n(* misc: *)\nInstance: ∀ x y : Z, Decision (x = y) := ZArith_dec.Z_eq_dec.\n\nAdd Ring Z: (rings.stdlib_ring_theory Z).\n\n(* * Embedding N into Z *)\nInstance inject_N_Z: Cast N Z := Z_of_N.\n\nInstance: SemiRing_Morphism Z_of_N.\nProof.\n  repeat (split; try apply _).\n   exact Znat.Z_of_N_plus.\n  exact Znat.Z_of_N_mult.\nQed.\n\nInstance: Injective Z_of_N.\nProof.\n  repeat (split; try apply _).\n  intros x y E. now apply Znat.Z_of_N_eq_iff.\nQed.\n\n(* SRpair N and Z are isomorphic *)\nDefinition Npair_to_Z (x : SRpair N) : Z := ('pos x - 'neg x)%mc.\n\nInstance: Proper (=) Npair_to_Z.\nProof.\n  intros [xp xn] [yp yn] E; do 2 red in E; unfold Npair_to_Z; simpl in *.\n  apply (right_cancellation (+) ('yn + 'xn)); ring_simplify.\n  now rewrite <-?rings.preserves_plus, E, commutativity.\nQed.\n\nInstance: SemiRing_Morphism Npair_to_Z.\nProof.\n  repeat (split; try apply _).\n   intros [xp xn] [yp yn].\n   change ('(xp + yp) - '(xn + yn) = 'xp - 'xn + ('yp - 'yn)).\n   rewrite ?rings.preserves_plus. ring.\n  intros [xp xn] [yp yn].\n  change ('(xp * yp + xn * yn) - '(xp * yn + xn * yp) = ('xp - 'xn) * ('yp - 'yn)).\n  rewrite ?rings.preserves_plus, ?rings.preserves_mult. ring.\nQed.\n\nInstance: Injective Npair_to_Z.\nProof.\n  split; try apply _.\n  intros [xp xn] [yp yn] E.\n  unfold Npair_to_Z in E. do 2 red. simpl in *.\n  apply (injective (cast N Z)).\n  rewrite ?rings.preserves_plus.\n  apply (right_cancellation (+) ('xp - 'xn)). rewrite E at 1. ring.\nQed.\n\nInstance Z_to_Npair: Inverse Npair_to_Z := λ x,\n  match x with\n  | Z0 => C 0 0\n  | Zpos p => C (Npos p) 0\n  | Zneg p => C 0 (Npos p)\n  end.\n\nInstance: Surjective Npair_to_Z.\nProof. split; try apply _. intros [|?|?] ? E; now rewrite <-E. Qed. \n\nInstance: Bijective Npair_to_Z := {}.\n\nInstance: SemiRing_Morphism Z_to_Npair.\nProof. change (SemiRing_Morphism (Npair_to_Z⁻¹)). split; apply _. Qed.\n\nInstance: IntegersToRing Z := integers.retract_is_int_to_ring Npair_to_Z.\nInstance: Integers Z := integers.retract_is_int Npair_to_Z.\n\nInstance Z_le: Le Z := Zle.\nInstance Z_lt: Lt Z := Zlt.\n\nInstance: SemiRingOrder Z_le.\nProof.\n  assert (PartialOrder Z_le).\n   repeat (split; try apply _).\n   exact Zorder.Zle_antisym.\n  rapply rings.from_ring_order.\n   repeat (split; try apply _).\n   intros x y E. now apply Zorder.Zplus_le_compat_l.\n  intros x E y F. now apply Zorder.Zmult_le_0_compat.\nQed.\n\nInstance: TotalRelation Z_le.\nProof.\n  intros x y.\n  destruct (Zorder.Zle_or_lt x y); intuition.\n  right. now apply Zorder.Zlt_le_weak.\nQed.\n\nInstance: FullPseudoSemiRingOrder Z_le Z_lt.\nProof.\n  rapply semirings.dec_full_pseudo_srorder.\n  split.\n   intro. split. now apply Zorder.Zlt_le_weak. now apply Zorder.Zlt_not_eq.\n  intros [E1 E2]. destruct (Zorder.Zle_lt_or_eq _ _ E1). easy. now destruct E2.\nQed.\n\n(* * Embedding of the Peano naturals into [Z] *)\nInstance inject_nat_Z: Cast nat Z := Z_of_nat.\n\nInstance: SemiRing_Morphism Z_of_nat.\nProof.\n  repeat (split; try apply _).\n   exact Znat.inj_plus.\n  exact Znat.inj_mult.\nQed.\n\n(* absolute value *)\nProgram Instance Z_abs_nat: IntAbs Z nat := λ x,\n  match x with\n  | Z0 => inl (0:nat)\n  | Zpos p => inl (nat_of_P p)\n  | Zneg p => inr (nat_of_P p)\n  end.\nNext Obligation. reflexivity. Qed.\nNext Obligation. now rewrite <-(naturals.to_semiring_unique Z_of_nat), Znat.Z_of_nat_of_P. Qed.\nNext Obligation. now rewrite <-(naturals.to_semiring_unique Z_of_nat), Znat.Z_of_nat_of_P. Qed.\n\nProgram Instance Z_abs_N: IntAbs Z N := λ x,\n  match x with\n  | Z0 => inl (0:N)\n  | Zpos p => inl (Npos p)\n  | Zneg p => inr (Npos p)\n  end.\nNext Obligation. reflexivity. Qed.\nNext Obligation. now rewrite <-(naturals.to_semiring_unique Z_of_N). Qed.\nNext Obligation. now rewrite <-(naturals.to_semiring_unique Z_of_N). Qed.\n\n(* Efficient nat_pow *)\nProgram Instance Z_pow: Pow Z (Z⁺) := Z.pow.\n\nInstance: NatPowSpec Z (Z⁺) Z_pow.\nProof.\n  split; unfold pow, Z_pow.\n    intros x1 y1 E1 [x2 Ex2] [y2 Ey2] E2.\n    unfold equiv, sig_equiv in E2.\n    simpl in *. now rewrite E1, E2.\n   intros. now apply Z.pow_0_r.\n  intros x n.\n  rewrite rings.preserves_plus, rings.preserves_1.\n  rewrite <-(Z.pow_1_r x) at 2. apply Z.pow_add_r.\n   auto with zarith.\n  now destruct n.\nQed.\n\nInstance Z_Npow: Pow Z N := λ x n, Z.pow x ('n).\n\nInstance: NatPowSpec Z N Z_Npow.\nProof.\n  split; unfold pow, Z_Npow.\n    solve_proper.\n   intros. now apply Z.pow_0_r.\n  intros x n.\n  rewrite rings.preserves_plus, rings.preserves_1.\n  rewrite <-(Z.pow_1_r x) at 2. apply Z.pow_add_r.\n   auto with zarith.\n  now destruct n.\nQed.\n\n(* Efficient shiftl *)\nProgram Instance Z_shiftl: ShiftL Z (Z⁺) := Z.shiftl.\n\nInstance: ShiftLSpec Z (Z⁺) Z_shiftl.\nProof.\n  apply shiftl_spec_from_nat_pow.\n  intros x [n En].\n  apply Z.shiftl_mul_pow2.\n  now apply En.\nQed.\n\nInstance Z_Nshiftl: ShiftL Z N := λ x n, Z.shiftl x ('n).\n\nInstance: ShiftLSpec Z N Z_Nshiftl.\nProof.\n  apply shiftl_spec_from_nat_pow.\n  intros x n.\n  apply Z.shiftl_mul_pow2.\n  now destruct n.\nQed.\n\nProgram Instance Z_abs: Abs Z := Zabs.\nNext Obligation.\n  split; intros E.\n   now apply Z.abs_eq.\n  now apply Z.abs_neq.\nQed.\n\nInstance Z_div: DivEuclid Z := Zdiv.\nInstance Z_mod: ModEuclid Z := Zmod.\n\nInstance: EuclidSpec Z _ _.\nProof.\n  split; try apply _.\n     exact Z_div_mod_eq_full.\n    intros x y Ey. destruct (Z_mod_remainder x y); intuition.\n   now intros [].\n  now intros [].\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_integers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6555216965144842}}
{"text": "(* Interface of MetricSpace type with types from the Coqeulicot Hierarchy *)\nFrom mathcomp Require Import all_ssreflect.\nFrom rlzrs Require Import all_rlzrs.\nRequire Import pointwise reals pseudo_metrics pseudo_metric_spaces metrics metric_spaces standard.\nRequire Import Reals Psatz Classical ChoiceFacts.\nFrom Coquelicot Require Import Coquelicot.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection infima.\n  Local Open Scope metric_scope.\n  Implicit Types (A: subset R).  \n\n  Definition is_lower_bound A x:= forall a, a \\from A -> x <= a.\n  \n  Definition lower_bounds A:= make_subset (fun x => is_lower_bound A x).\n\n  Definition is_infimum A x := is_lower_bound A x /\\ is_upper_bound (lower_bounds A) x.\n  \n  Lemma is_infimum_glb_Rbar A x: is_infimum A x <-> is_glb_Rbar A (Finite x).\n  Proof.\n    rewrite is_glb_Rbar_correct.\n    split => [[lb inf] | [lb inf]].\n    - split.\n      + case; try by case.\n        by move => y [_ Ay]; apply/lb.\n      case => //[ y ass | ass].\n      + apply/inf => z Az.\n        have /=ass' := ass z.\n        by apply/ass'.\n      suff: (x + 1 <= x) by lra.\n      apply/inf => y Ay; have /= ass' := ass (Finite y).\n      by exfalso; apply/ass'.\n    split => y Ay; first exact/(lb y).\n    apply/(inf y); case => // [z [_ ] | []]//.\n    exact/Ay.\n  Qed.\n  \n  Definition mf_infimum:= make_mf is_infimum.\n\n  Lemma inf_sing: mf_infimum \\is_singlevalued.\n  Proof.\n    move => A inf inf' [bnd sup] [bnd' sup'].\n    suff: inf <= inf' /\\ inf' <= inf by lra.\n    by split; [apply/sup' | apply/sup].\n  Qed.\n      \n  Definition p_infimum A := match Glb_Rbar A with\n                        | Finite r => Some r\n                        | _ => None\n                        end.\n\n  Lemma p_inf_spec: pf2MF p_infimum =~= mf_infimum.\n  Proof.\n    move => A infA; rewrite /p_infimum /=.\n    split => [/= | /is_infimum_glb_Rbar spec]; last by have -> := is_glb_Rbar_unique _ _ spec.\n    case spec: (Glb_Rbar A) => [x | | ] // <-.\n    apply/is_infimum_glb_Rbar; rewrite -spec.\n    exact/Glb_Rbar_correct.\n  Qed.\n    \n  Definition infimum A := match Glb_Rbar A with\n                      | Finite r => r\n                      | _ => 0\n                      end.\n\n  Notation inf := infimum.\n  \n  Lemma inf_icf: infimum \\is_choice_for mf_infimum.\n  Proof.\n    rewrite /infimum => A [infA val].\n    rewrite (is_glb_Rbar_unique A infA) //.\n    exact/is_infimum_glb_Rbar.\n  Qed.\n  \n  Definition nonempty A:= exists a, a \\from A.\n\n  Definition nonempties := make_subset nonempty.\n  \n  Definition bounded_from_below A := exists a, a \\from lower_bounds A.\n\n  Definition lower_boundeds:= make_subset bounded_from_below.\n \n  Lemma dom_inf: FunctionalCountableChoice_on R -> dom mf_infimum === lower_boundeds \\n nonempties.\n  Proof.\n    move => choice A; split => [[x [lb inf]] | [[y lb] [x Ax]]].\n    - split; first by exists x.\n      apply/not_all_not_ex => mty.\n      suff: x + 1 <= x by lra.\n      by apply/inf => y Ay; exfalso; apply/mty/Ay.\n    have := lb x Ax.\n    case => [ineq | eq]; last by exists x; split => [ | z lbz]; [rewrite -eq | exact/lbz].\n    suff /choice [xn xnprp]:\n      forall n, exists (xn: M2PM metric_R), lower_bounds A xn\n                           /\\\n                           exists z, A z /\\ d (xn, z) <= /2^n.\n    - have xnbnd: forall n, is_lower_bound A (xn n) by move => n; have []:= xnprp n.\n      have /(@fchy_lim_eff R_MetricSpace R_cmplt) [infA lmt]:\n        (xn: sequence_in (M2PM R_MetricSpace)) \\fast_Cauchy.\n      + apply cchy_eff_suff => n m nlm.\n        have [_ [z [Az dst]]]:= xnprp m.\n        have [_ [z' [Az' dst']]]:= xnprp n.\n        have := xnbnd n z Az; have := xnbnd m z' Az'.\n        by move : dst dst' => /=; split_Rabs; lra.\n      exists infA.\n      split => [z Az | x' lbx'].\n      + apply/lim_inc; last apply lim_cnst; last apply lim_eff_lim; last by apply lmt.\n        by move => n; rewrite/cnst; apply/xnbnd.\n      apply/cond_leq => eps eg0.\n      have /accf_tpmn [N [pos Nle]] : 0 < eps/2 by lra.\n      have [_ [z [Az dst]]]:= xnprp N.\n      have := lbx' z Az; have := lmt N.\n      by move: dst => /=; split_Rabs; lra.\n    suff prp: forall n, exists (xn: M2PM metric_R), lower_bounds A xn\n                                   /\\\n                                   exists z, A z /\\ d(xn, z) <= (x - y)/2^n.\n    - move => n.\n      have /accf_tpmn [N [pos Nlxy]]: 0 < /(x - y) by apply/Rinv_0_lt_compat; lra.\n      have [xn [xnlb [z [Az dst]]]]:= prp (N + n)%nat.\n      exists xn; split => //.\n      exists z; split => //.\n      have lt: 0 < 2^n by apply pow_lt; lra.\n      have lt': 0< 2^N by apply/pow_lt; lra.\n      apply/Rle_trans; first exact/dst.\n      rewrite pow_add /Rdiv Rinv_mult_distr; try lra.\n      rewrite -Rmult_assoc -{2}(Rmult_1_l (/2^n)).\n      apply/Rmult_le_compat_r; first by apply/Rlt_le/Rinv_0_lt_compat.\n      rewrite -(Rinv_r (2^N)); try lra.\n      apply/Rmult_le_compat_r; first by apply/Rlt_le/Rinv_0_lt_compat.\n      rewrite -(Rinv_involutive (2^N)); try lra.\n      rewrite -(Rinv_involutive (x - y)); try lra.\n      by apply/Rinv_le_contravar; lra.\n    elim => [ | n [xn [xnlb [z [Az dst]]]]].\n    - by exists y; split; last by exists x; split; last by simpl; split_Rabs; lra.\n    case: (classic (exists z', A z' /\\ d(xn, z') <= (x - y)/2^n.+1)) => [ex | /not_ex_all_not nex].\n    - by exists xn.\n    exists (xn + (x-y)/2^n.+1).\n    split => [z' Az' |].\n    - have /not_and_or [nAz' | /Rnot_le_lt dst']:= nex z'; first by exfalso; apply/nAz'.\n      by have := xnlb z' Az'; move: dst' => /=; split_Rabs; lra.\n    have /not_and_or [nAz | /Rnot_le_lt dst']:= nex z; first by exfalso; apply/nAz.\n    exists z; split => //; have xnlz:= xnlb z Az.\n    have xn'lz: xn + (x - y) /2^n.+1 <= z.    \n    - have : 0 < (x - y) /2^n.+1 by apply/Rdiv_lt_0_compat/pow_lt; lra.\n      by simpl in dst; move : dst' dst; rewrite [X in _ < X]/=; split_Rabs; lra.\n    rewrite /Rdiv (tpmn_half n) in dst.\n    by move: xn'lz dst' dst => /=; split_Rabs; lra.\n  Qed.\n  \n  Lemma inf_spec A: A \\from dom mf_infimum -> mf_infimum A (inf A).\n  Proof. exact/inf_icf. Qed.\n\n  Lemma inf_eq A r: A \\from dom mf_infimum -> mf_infimum A r -> inf A = r.\n  Proof.\n    move => fd val.\n    exact/inf_sing/val/inf_icf.\n  Qed.\n\n  Lemma inf_leq A x: A \\from dom mf_infimum -> x \\from A -> inf A <= x.\n  Proof.\n    move => Afd xfa.\n    have [lb _]:= inf_icf Afd.\n    exact/lb.\n  Qed.\n\n  Lemma bnds_inf_leq A x: FunctionalCountableChoice_on R ->\n                          A \\from lower_boundeds -> x \\from A -> inf A <= x.\n  Proof.\n    move => choice bnd elt; apply/inf_leq => //.\n    by rewrite dom_inf //; split; last exists x.\n  Qed.\n  \n  Lemma inf_geq A x: A \\from dom mf_infimum -> x \\from lower_bounds A -> x <= inf A.\n  Proof.\n    move => Afd lb.\n    have [lbs nf]:= inf_icf Afd.\n    exact/nf.\n  Qed.\n\n  Lemma ne_inf_geq A x: FunctionalCountableChoice_on R ->\n                        A \\from nonempties -> x \\from lower_bounds A -> x <= inf A.\n  Proof. by move => choice ne lb; apply/inf_geq; first by rewrite dom_inf//; split => //; exists x. Qed.\n\n  Lemma inf_approx A infA: mf_infimum A infA -> \n                      forall eps, 0 < eps -> exists x, x \\from A /\\ x <= infA + eps.\n  Proof.\n    move => [lb nf] eps eg0.\n    apply/not_all_not_ex => all.\n    have := nf (infA + eps).\n    suff: infA + eps <= infA by lra.\n    apply/nf => z Az.\n    have /not_and_or [nAz | /Rnot_le_lt]:= all z; try lra.\n    by exfalso; apply/nAz.\n  Qed.\nEnd infima.  \nNotation inf:= infimum.\n\nSection suprema.  \n  Implicit Types (A: subset R).\n  Local Open Scope metric_scope.\n  Definition upper_bounds A:= make_subset (fun x => is_upper_bound A x).\n\n  Definition is_supremum A x := is_upper_bound A x /\\ is_lower_bound (upper_bounds A) x.\n  \n  Lemma is_supremum_lub_Rbar A x: is_supremum A x <-> is_lub_Rbar A (Finite x).\n  Proof.\n    rewrite is_lub_Rbar_correct.\n    split => [[ub sup] | [ub sup]].\n    - split.\n      + case; try by case.\n        by move => y [_ Ay]; apply/ub.\n      case => //[ y ass | ass].\n      + apply/sup => z Az.\n        have /=ass' := ass z.\n        by apply/ass'.\n      suff: (x <= x - 1) by lra.\n      apply/sup => y Ay; have /= ass' := ass (Finite y).\n      by exfalso; apply/ass'.\n    split => y Ay; first exact/(ub y).\n    apply/(sup y); case => // [z [_ ] | []]//.\n    exact/Ay.\n  Qed.\n  \n  Definition mf_supremum:= make_mf is_supremum.\n\n  Lemma sup_sing: mf_supremum \\is_singlevalued.\n  Proof.\n    move => A sup sup' [bnd inf] [bnd' inf'].\n    suff: sup <= sup' /\\ sup' <= sup by lra.\n    by split; [apply/inf | apply/inf'].\n  Qed.\n      \n  Definition p_supremum A := match Lub_Rbar A with\n                        | Finite r => Some r\n                        | _ => None\n                        end.\n\n  Lemma p_sup_spec: pf2MF p_supremum =~= mf_supremum.\n  Proof.\n    move => A supA; rewrite /p_supremum /=.\n    split => [/= | /is_supremum_lub_Rbar spec]; last by have -> := is_lub_Rbar_unique _ _ spec.\n    case spec: (Lub_Rbar A) => [x | | ] // <-.\n    apply/is_supremum_lub_Rbar; rewrite -spec.\n    exact/Lub_Rbar_correct.\n  Qed.\n    \n  Definition supremum A := match Lub_Rbar A with\n                      | Finite r => r\n                      | _ => 0\n                      end.\n  Notation sup := supremum.\n  \n  Lemma sup_icf: supremum \\is_choice_for mf_supremum.\n  Proof.\n    rewrite /supremum => A [supA val].\n    rewrite (is_lub_Rbar_unique A supA) //.\n    exact/is_supremum_lub_Rbar.\n  Qed.\n    \n  Definition bounded_from_above A := upper_bounds A \\from nonempties.\n\n  Definition upper_boundeds:= make_subset bounded_from_above.\n\n  Lemma dom_sup: FunctionalCountableChoice_on R -> dom mf_supremum === upper_boundeds \\n nonempties.\n  Proof.\n    move => choice A; split => [[x [ub sup]] | [[y ub] [x Ax]]].\n    - split; first by exists x.\n      apply/not_all_not_ex => mty.\n      suff: x <= x - 1 by lra.\n      by apply/sup => y Ay; exfalso; apply/mty/Ay.\n    have := ub x Ax.\n    case => [ineq | eq]; last by exists x; split => [ | z ubz]; [rewrite eq | exact/ubz].\n    suff /choice [xn xnprp]:\n      forall n, exists (xn: M2PM metric_R), upper_bounds A xn\n                           /\\\n                           exists z, A z /\\ d (xn, z) <= /2^n.\n    - have xnbnd: forall n, is_upper_bound A (xn n) by move => n; have []:= xnprp n.\n      have /(@fchy_lim_eff R_MetricSpace R_cmplt) [supA lmt]:\n        (xn: sequence_in (M2PM R_MetricSpace)) \\fast_Cauchy.\n      + apply cchy_eff_suff => n m nlm.\n        have [_ [z [Az dst]]]:= xnprp m.\n        have [_ [z' [Az' dst']]]:= xnprp n.\n        have := xnbnd n z Az; have := xnbnd m z' Az'.\n        by move : dst dst' => /=; split_Rabs; lra.\n      exists supA.\n      split => [z Az | x' lbx'].\n      + apply/Rge_le/lim_dec/lim_cnst/lim_eff_lim/lmt.\n        by move => n; rewrite/cnst; apply/Rle_ge/xnbnd.\n      apply/cond_leq => eps eg0.\n      have /accf_tpmn [N [pos Nle]] : 0 < eps/2 by lra.\n      have [_ [z [Az dst]]]:= xnprp N.\n      have := lbx' z Az; have := lmt N.\n      by move: dst => /=; split_Rabs; lra.\n    suff prp: forall n, exists (xn: M2PM metric_R), upper_bounds A xn\n                                   /\\\n                                   exists z, A z /\\ d(xn, z) <= (y - x)/2^n.\n    - move => n.\n      have /accf_tpmn [N [pos Nlxy]]: 0 < /(y - x) by apply/Rinv_0_lt_compat; lra.\n      have [xn [xnlb [z [Az dst]]]]:= prp (N + n)%nat.\n      exists xn; split => //.\n      exists z; split => //.\n      have lt: 0 < 2^n by apply pow_lt; lra.\n      have lt': 0< 2^N by apply/pow_lt; lra.\n      apply/Rle_trans; first exact/dst.\n      rewrite pow_add /Rdiv Rinv_mult_distr; try lra.\n      rewrite -Rmult_assoc -{2}(Rmult_1_l (/2^n)).\n      apply/Rmult_le_compat_r; first by apply/Rlt_le/Rinv_0_lt_compat.\n      rewrite -(Rinv_r (2^N)); try lra.\n      apply/Rmult_le_compat_r; first by apply/Rlt_le/Rinv_0_lt_compat.\n      rewrite -(Rinv_involutive (2^N)); try lra.\n      rewrite -(Rinv_involutive (y - x)); try lra.\n      by apply/Rinv_le_contravar; lra.\n    elim => [ | n [xn [xnlb [z [Az dst]]]]].\n    - by exists y; split; last by exists x; split; last by simpl; split_Rabs; lra.\n    case: (classic (exists z', A z' /\\ d(xn, z') <= (y - x)/2^n.+1)) => [ex | /not_ex_all_not nex].\n    - by exists xn.\n    exists (xn - (y - x)/2^n.+1).\n    split => [z' Az' |].\n    - have /not_and_or [nAz' | /Rnot_le_lt dst']:= nex z'; first by exfalso; apply/nAz'.\n      by have := xnlb z' Az'; move: dst' => /=; split_Rabs; lra.\n    have /not_and_or [nAz | /Rnot_le_lt dst']:= nex z; first by exfalso; apply/nAz.\n    exists z; split => //; have xnlz:= xnlb z Az.\n    have xn'lz: z <= xn - (x - y) /2^n.+1.    \n    - have : 0 < (y - x) /2^n.+1 by apply/Rdiv_lt_0_compat/pow_lt; lra.\n      by simpl in dst; move : dst' dst; rewrite [X in _ < X]/=; split_Rabs; lra.\n    rewrite /Rdiv (tpmn_half n) in dst.\n    by move: xn'lz dst' dst => /=; split_Rabs; lra.\n  Qed.\n  \n  Lemma sup_spec A: A \\from dom mf_supremum -> sup A \\from mf_supremum A.\n  Proof. exact/sup_icf. Qed.\n\n  Lemma sup_eq A r: A \\from dom mf_supremum -> r \\from mf_supremum A -> sup A = r.\n  Proof.\n    move => fd val.\n    exact/sup_sing/val/sup_icf.\n  Qed.\n\n  Lemma sup_leq A x: A \\from dom mf_supremum -> x \\from A -> x <= sup A.\n  Proof.\n    move => Afd xfa.\n    have [ub _]:= sup_icf Afd.\n    exact/ub.\n  Qed.\n\n  Lemma bnds_sup_leq A x: FunctionalCountableChoice_on R ->\n                          A \\from upper_boundeds -> x \\from A -> x <= sup A.\n  Proof.\n    move => choice bnd elt; apply/sup_leq => //.\n    by rewrite dom_sup//; split; last exists x.\n  Qed.\n  \n  Lemma sup_geq A x: A \\from dom mf_supremum -> x \\from upper_bounds A -> sup A <= x.\n  Proof.\n    move => Afd lb.\n    have [lbs nf]:= sup_icf Afd.\n    exact/nf.\n  Qed.\n\n  Lemma ne_sup_geq A x: FunctionalCountableChoice_on R ->\n                        A \\from nonempties -> x \\from upper_bounds A -> sup A <= x.\n  Proof. by move => choice ne ub; apply/sup_geq; first by rewrite dom_sup//; split => //; exists x. Qed.\n\n  Lemma sup_approx A supA: supA \\from mf_supremum A  -> \n                      forall eps, 0 < eps -> exists x, x \\from A /\\ supA - eps <= x.\n  Proof.\n    move => [ub nf] eps eg0.\n    apply/not_all_not_ex => all.\n    have := nf (supA - eps).\n    suff: supA <= supA - eps by lra.\n    apply/nf => z Az.\n    have /not_and_or [nAz | /Rnot_le_lt]:= all z; try lra.\n    by exfalso; apply/nAz.\n  Qed.\nEnd suprema.\n", "meta": {"author": "FlorianSteinberg", "repo": "metric", "sha": "b34f29091173ffe079b4d4b6eab21061b81a930c", "save_path": "github-repos/coq/FlorianSteinberg-metric", "path": "github-repos/coq/FlorianSteinberg-metric/metric-b34f29091173ffe079b4d4b6eab21061b81a930c/infima_suprema.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6553296067185522}}
{"text": "Require Import Lia.\nRequire Import List.\nRequire Import PeanoNat.\nImport Nat Le Lt.\nImport ListNotations.\nRequire Import Compare_dec.\nRequire Import Coq.Program.Wf.\nRequire Import Wf_nat.\nRequire Import IndefiniteDescription.\nRequire Import ClassicalDescription.\nRequire Import Sequences.\nRequire Import Tree.\nRequire Import CPO.\nRequire Import FuncDef.\n\nFixpoint f2l{A : Type} (n : nat)( f : nat -> A) : list A :=\nmatch n with\n|0 => []\n|S m => (f 0) :: (f2l m (fun i => f (S i)))\nend.\n\nLemma f2l_length{A: Type} : forall n (f : nat ->A),  length (f2l n f) = n.\nProof.\ninduction n; intro f; auto.\ncbn.\nrewrite IHn; auto.\nQed.\n\nLemma f2l_elts{A : Type} : forall n (f: nat -> A) i d,\n    i < n -> nth i (f2l n f) d = f i.\nProof.\ninduction n; intros f i d Hlt; try lia.\ndestruct i; auto.\ncbn.\nrewrite IHn; auto ; lia.\nQed.\n\nDefinition f2l_dep{A : Type} (n : nat)(f  : forall i,  i < n -> A)(d:A) : list A :=\nf2l n\n    (fun k =>\n       match (le_lt_dec n k ) with\n         |left _   => d\n         |right p => f k p\n       end).\n\n\nLemma f2l_dep_length{A: Type} :\n  forall n (f  : forall i,  i < n -> A) d,   length (f2l_dep n f d) = n.\nProof.\nintros n f d.\nunfold f2l_dep.\nrewrite f2l_length; auto.\nQed.\n\nLemma f2l_dep_elts{A : Type} :\n  forall n (f:  forall i,  i < n -> A) i d(Hlt:   i < n),\n    nth i (f2l_dep n f d) d = f i Hlt.\nProof.\nintros n f i d Hlt.\nunfold f2l_dep.\nrewrite f2l_elts; auto.\ndestruct ( le_lt_dec n i) ; try lia.\nf_equal.\nerewrite proof_irrelevance; eauto.\nQed.\n\n\nLemma list_max_rev : forall l, list_max l = list_max (rev l).\nProof.  \ninduction l ; auto.\ncbn [rev].\nreplace (a :: l) with ([a] ++ l); auto.\ndo 2 rewrite list_max_app.\nrewrite IHl.\napply Max.max_comm.\nQed.\n\n\nModule FmirrorMod(TM : TypeMod).\nImport TM.  \nModule F := FtreeMod TM.\nImport F.\nImport Tree.\n\nObligation Tactic := idtac.\nProgram Fixpoint fmirror (t : (Ftree(A :=A))) {measure (height t)}: Ftree(A :=A) :=\n  match t with\n     | ftree a l =>  ftree a (\n                          f2l_dep (length l)\n                                  (fun n _ => fmirror (nth n (rev l) F.bot))\n                                  F.bot )\n    |  bot => bot  \n  end.  \nNext Obligation.\nintros t Hall a l Heq n Hlt.\nrewrite <- Heq.\ncbn.\napply le_n_S.\nrewrite rev_nth; auto.\napply max_list_max; lia.\nQed.\n\nNext Obligation.\nintros.\napply well_founded_ltof.\nQed.\n\nLemma fmirror_eta : forall t, fmirror t =\n    match t with\n     | ftree a l =>  ftree a (\n                             f2l_dep (length l)\n                                     (fun n _ => fmirror (nth n (rev l ) bot))\n                                     bot )\n  |  bot => bot\n \n  end.\nProof.  \nintro t.\ndestruct t.  \n*\n  unfold fmirror.\n  rewrite Wf.WfExtensionality.fix_sub_eq_ext; auto.\n*\n  unfold fmirror.\n  rewrite Wf.WfExtensionality.fix_sub_eq_ext; auto.\nQed.\n\nLemma f2l_dep_map :\nforall l (f : Ftree(A:=A) -> Ftree(A :=A)), f2l_dep (length l) (fun n _ =>  f (nth n l bot)) bot = map f l.\nintros l f.  \neapply nth_ext with (d := bot) (d' := f bot).\n*\n  rewrite f2l_dep_length.\n  rewrite map_length; auto.\n*\n  rewrite f2l_dep_length.\n  intros n Hlt.\n  rewrite f2l_dep_elts ; auto.\n  rewrite map_nth; auto.\nQed.\n\nLemma fmirror_eta_plus : forall t, fmirror t =\n  match t with\n  | ftree a l =>ftree a (map fmirror (rev l))\n  |  bot => bot                         \n  end.\nProof.  \nintro t.\nrewrite fmirror_eta.\ndestruct t ; auto.\nf_equal.\nrewrite <- rev_length.\nrewrite f2l_dep_map; auto.\nQed.\n\nLemma fmirror_eta_bot : fmirror bot = bot.\nProof.  \nrewrite fmirror_eta; auto.\nQed.\n\nLemma fmirror_eta_plus_ftree : forall a l,\n    fmirror (ftree a l) = ftree a (map fmirror (rev l)).\nProof.\nintros a l.\nrewrite fmirror_eta_plus; auto.\nQed.\n\nLemma fmirror_height : forall t,  height (fmirror t) = height t.\nProof.\ninduction t0 using Ftree_induct.\n*\n  cbn.\n  rewrite fmirror_eta_bot; auto.\n*\n  rewrite fmirror_eta_plus_ftree.\n  cbn.\n  f_equal.\n  rewrite map_map.\n  rewrite map_rev.\n  rewrite <- list_max_rev.\n  induction l; auto.\n  cbn [map height].\n  replace ((height (fmirror a0)\n     :: map (fun x : Ftree => height (fmirror x))\n          l)) with ([height (fmirror a0)]\n      ++ map (fun x : Ftree => height (fmirror x))\n          l); auto.\n  replace (height a0 :: map height l) with ([height a0] ++ map height l); auto.\n  do 2 rewrite list_max_app.\n  rewrite IHl; auto.\n  +\n    specialize (H 0).\n    cbn in H.\n    rewrite H; lia.\n  +\n    intros n Hlt.\n    specialize (H  (S n)).\n    cbn in H.\n    rewrite H; lia.\nQed.\n\nLemma fmirror_cut : forall n t,  cut n (fmirror t) = fmirror (cut n t).\nProof.  \ninduction n; intro t; cbn.\n*\n  rewrite fmirror_eta_bot ; auto.\n*\n  destruct t.\n  +\n    rewrite fmirror_eta_bot ; auto.\n  +\n    do 2 rewrite fmirror_eta_plus_ftree.\n    f_equal.\n    rewrite map_map.\n    repeat rewrite map_rev.\n    f_equal.\n   induction l ; auto.\n   cbn.\n   f_equal.\n   -\n     apply IHn.\n   -\n     apply IHl.\nQed.\n\n\nLemma fmirror_inv : forall t, fmirror (fmirror t) = t.\nProof.\n  eapply well_founded_ind with\n      (R := fun t1 t2 => height t1 < height t2); [apply well_founded_ltof |].\nintros t Hind.\ndestruct t.\n*\n  do  2 rewrite fmirror_eta_bot; auto.\n*\n   do 2 rewrite fmirror_eta_plus_ftree.\n   f_equal.\n   rewrite map_rev .\n   rewrite map_map.\n   rewrite map_rev.\n   rewrite rev_involutive.\n   induction l; auto.\n   cbn.\n   f_equal.\n   +\n    apply Hind; cbn; lia.\n   +\n     rewrite IHl ; auto.\n     intros y Hlt.\n     apply Hind.\n     eapply Nat.lt_le_trans; eauto.\n     cbn [height].\n     apply le_n_S.\n     replace (a0 :: l) with ([a0] ++l); auto.\n     rewrite map_app, list_max_app.\n     lia.\nQed.\n\nLemma fmirror_mono : forall t1 t2,  fprefix t1 t2 -> fprefix (fmirror t1) (fmirror t2).\nProof.\nintros t1 t2 Hpre.\ngeneralize Hpre; intro Hpre'.\napply fprefix_height in Hpre'.\nunfold fprefix in *.\nrewrite fmirror_height.\nrewrite Hpre at 1.\nrewrite fmirror_cut; auto.\nQed.\n\n\nLemma fmirror_asc : forall (q : Seq (A := Ftree)),\n    ascending fprefix q -> ascending fprefix (fun n => fmirror (q n)).\nProof.\nintros q Hasc.\nrewrite  subsequence_iff_ascending;\n  [| apply fprefix_refl | apply fprefix_trans | apply fprefix_antisym].\nrewrite  subsequence_iff_ascending in Hasc;\n  [| apply fprefix_refl | apply fprefix_trans | apply fprefix_antisym].\ndestruct Hasc as (Hinc & (q' & (f & Hfi & Hall) & Hsi)).\nsplit.\n*\n  intro n.\n  apply fmirror_mono, Hinc.\n*\n  exists (fun n => fmirror (q' n)).\n  split.\n  +\n    exists f; split; auto.\n    intro n.\n    now rewrite Hall.\n  +\n    destruct Hsi as (Hi & Hn).\n    split.\n    - \n      intro n.\n      apply fmirror_mono, Hi.\n   -\n     intros n Heq.\n     apply (Hn n).\n     apply f_equal with (f := fmirror) in Heq.\n     now do 2 rewrite fmirror_inv in Heq.\nQed.\n\n Fixpoint fpos (p : list nat) (t : Ftree) : option A :=\nmatch p with\n  [] =>\n  match t with\n    bot => None\n   | ftree a _ => Some a            \n  end  \n| n :: p' =>\n   match t with\n    bot => None\n   | ftree _ l =>\n     if le_lt_dec (length l) n then None else\n     fpos p' (nth n l bot)  \n  end     \nend.\n\n\nFixpoint fpos_sym (p : list nat) (t : Ftree) : option A :=\nmatch p with\n  [] =>\n  match t with\n    bot => None\n   | ftree a _ => Some a            \n  end  \n| n :: p' =>\n   match t with\n    bot => None\n   | ftree _ l =>\n     if  le_lt_dec (length l) n then None else\n       fpos_sym p' (nth (length l - (S n)) l bot)         \n  end     \nend.    \n\n\nLemma fmirror_fpos : forall p t,  fpos p (fmirror t) = fpos_sym p t.\nProof.\ninduction p; intros t.\n*\n  destruct t.\n  +\n    rewrite fmirror_eta_bot ; auto.\n  +\n    rewrite fmirror_eta_plus_ftree; auto.\n *\n   destruct t.\n   +\n     rewrite fmirror_eta_bot ; auto.\n   +\n      rewrite fmirror_eta_plus_ftree.\n      cbn.\n      rewrite map_length, rev_length.\n      destruct (le_lt_dec (length l) a); auto.\n      rewrite <- IHp.\n      replace (nth a (map fmirror (rev l)) bot) with\n          (nth a (map fmirror (rev l)) (fmirror bot)) ; [| rewrite fmirror_eta_bot; auto].\n      rewrite map_nth.\n      rewrite rev_nth; auto.\nQed.\n\n\nLemma fpos_fprefix :\n  forall p t t',  length p < height t ->  fprefix t t' ->\n                  fpos p t' = fpos p t.\nProof.  \ninduction p ; intros t t' Hle1 Hle2.\n*\n  generalize Hle2 ; intros Hh; apply fprefix_height in Hh.\n  unfold fprefix in Hle2.\n  rewrite Hle2.\n  destruct t; cbn in Hle1; try lia.\n  destruct t'; cbn in Hh; try lia; auto.\n*\n  generalize Hle2 ; intros Hh; apply fprefix_height in Hh.\n  destruct t; cbn in Hle1; try lia.\n  destruct t'; cbn in Hh; try lia.\n  inversion Hle2; subst.\n  cbn.\n  rewrite map_length.\n  destruct (le_lt_dec (length l0) a); auto.\n  replace  (nth a\n       (map\n          (cut\n             (list_max (map height l)))\n          l0) bot) with  (nth a\n       (map\n          (cut\n             (list_max (map height l)))\n          l0) (cut (list_max (map height l)) bot));\n    [|destruct (list_max (map height l)); auto].\n  rewrite map_nth.\n  apply lt_S_n in Hle1.\n  apply le_S_n in Hh.\n  destruct (le_lt_dec ((list_max (map height l))) (height (nth a l0 bot))).\n  +\n    eapply IHp.\n    -\n      rewrite cut_below_height; auto.\n    -\n      unfold fprefix.\n      rewrite cut_below_height; auto.\n  +\n    rewrite cut_above_height; auto ; lia.\nQed.\n\n\n\nLemma fpos_sym_fprefix :\n  forall p t t',  length p < height t ->  fprefix t t' ->\n                  fpos_sym p t' = fpos_sym p t.\nProof.\nintros p t t' Hlt Hle.\ndo 2 rewrite <- fmirror_fpos.\napply fpos_fprefix.\n*\n  rewrite fmirror_height; auto.\n*\n  apply fmirror_mono; auto.\nQed.\n\n\nEnd FmirrorMod.\n\nModule NatTypeMod <: TypeMod.\nDefinition A := nat.\nEnd NatTypeMod.  \n\nModule TreeDom := FtreeMod NatTypeMod.\nModule TreeRan := FtreeMod NatTypeMod.\n\n\nModule ProductiveMirrorMod <: ProductiveFuncMod TreeDom TreeRan.\n\nModule Export CPO1 :=CPOMod TreeDom.\nModule Export CPO2 :=CPOMod TreeRan.\n\nModule FM := FmirrorMod NatTypeMod.\nImport FM.\n\nDefinition fc : TreeDom.Cc -> TreeDom.Cc := fmirror.\n\nLemma fc_mono :\n  forall x y,  TreeDom.ordc x y -> TreeRan.ordc (fc x) (fc y).\nProof.\nintros x y HD.  \nnow apply fmirror_mono.\nQed.\n\nLemma increasing_image :\n  forall q,  increasing TreeDom.ordc q ->\n               increasing  TreeRan.ordc (fun n =>  fc (q n)).\nProof.\nintros q Hi n.\napply fc_mono, Hi.  \nQed.\n\nLemma fc_prod : forall (q: Seq (A := TreeDom.Cc))\n                       (Hi : increasing TreeDom.ordc q),\n    CPO1.is_cls(CPO1.lim (fun n => CPO1.elt (q n))\n                         (CPO1.map_elt_increasing _ Hi)) ->\n    CPO2.is_cls(CPO2.lim (fun n => CPO2.elt (fc (q n)))\n               (CPO2.map_elt_increasing  _ (increasing_image _ Hi))).\nintros q Hi Hc. \nunfold fc.  \nremember ((lim (fun n : nat => elt (fmirror (q n)))\n       (map_elt_increasing\n          (fun n : nat => fmirror (q n))\n          (increasing_image q Hi)))) as c.\ndestruct c; try constructor.\nexfalso.\nunfold lim in Heqc.\ndestruct (excluded_middle_informative\n             (stabilizing\n                (fun n : nat =>\n                   elt (fmirror (q n))))) ; try discriminate.\nclear Heqc.\nunfold CPO1.lim in Hc.\ndestruct (excluded_middle_informative\n             (stabilizing (fun n : nat => CPO1.elt (q n)))).\n*\n  destruct ( constructive_indefinite_description _ s0).\n  destruct x; try inversion Hc.\n  destruct s1 as (n & Hall).\n  specialize (Hall _ (le_refl _)).\n  discriminate.\n*\n  clear Hc.\n  apply n; clear n.\n  destruct s as (a & n & Hall).\n  destruct a.\n  +\n    unfold stabilizing.\n    exists (CPO1.elt (fmirror e0)), n.\n    intros m Hle.\n    f_equal.\n    specialize (Hall _ Hle).\n    injection Hall; clear Hall; intro Hall; subst.\n    now rewrite fmirror_inv.\n  +\n    specialize (Hall _ (le_refl _)).\n    discriminate.\nQed.\n\nEnd ProductiveMirrorMod.\n\n\nModule MirrorProperties.\nModule MD := FuncDefMod TreeDom TreeRan ProductiveMirrorMod.\nImport MD.\nImport TreeDom TreeRan ProductiveMirrorMod.\nModule FM := FmirrorMod NatTypeMod.\nImport FM.\nDefinition mirror := f.\n\nDefinition rpos (p : list nat) (c : CPO2.EC.EqClass) : option nat:=\n  fpos p (proj1_sig (CPO2.EC.representative c) \n         (proj1_sig (constructive_indefinite_description _\n                                          (CPO2.SEM.ascending_mu_unbounded_alt\n                                            (CPO2.EC.representative c)   (S (length p)))))).\n\nLemma rpos_fpos :\n  forall p c,  exists k,  mu (proj1_sig (CPO2.EC.representative c) k) >= S (length p) /\\\n                rpos p c = fpos p (proj1_sig (CPO2.EC.representative c) k).\nProof.\nintros p c.\nremember  (EC.representative c) as q.\ndestruct q as (q & Ha).\ncbn.\nunfold rpos.\ncbn.\nexists\n         (proj1_sig\n            (constructive_indefinite_description\n               (fun n : nat =>\n                mu\n                  (proj1_sig\n                     (EC.representative\n                     c) n) >=\n                S (length p))\n               (SEM.ascending_mu_unbounded_alt\n                  (EC.representative\n                     c)\n                  (S (length p))))).\nsplit; auto.\n*\n  remember ((constructive_indefinite_description\n       (fun n : nat =>\n        mu (proj1_sig (EC.representative c) n) >=\n        S (length p))\n       (SEM.ascending_mu_unbounded_alt\n          (EC.representative c) \n          (S (length p))))) as c'.\n  destruct c' as (k & Hk).\n  cbn.\n  clear Heqc'.\n  now rewrite <- Heqq in Hk.\n*\n  now rewrite <- Heqq.\nQed.\n  \nDefinition pos (p : list nat) (c:CPO2.C) : option nat :=\n  match c with\n  | CPO2.elt e => fpos p e\n  | CPO2.cls c => rpos p c                \n  end.  \n\n\nDefinition rpos_sym (p : list nat) (c : CPO1.EC.EqClass) : option nat:=\n  fpos_sym p ((proj1_sig (CPO1.EC.representative c))\n             (proj1_sig (constructive_indefinite_description _\n                                                             (CPO1.SEM.ascending_mu_unbounded_alt\n                                                                (CPO1.EC.representative c) (S (length p)))))). \n\nLemma rpos_sym_fpos_sym :\n  forall p c,  exists k,  mu (proj1_sig (CPO1.EC.representative c) k) >= S (length p) /\\\n                rpos_sym p c = fpos_sym p (proj1_sig (CPO1.EC.representative c) k).\nProof.\nintros p c.\nremember  (CPO1.EC.representative c) as q.\ndestruct q as (q & Ha).\ncbn.\nunfold rpos_sym.\ncbn.\nexists\n         (proj1_sig\n            (constructive_indefinite_description\n               (fun n : nat =>\n                mu\n                  (proj1_sig\n                     (CPO1.EC.representative\n                     c) n) >=\n                S (length p))\n               (CPO1.SEM.ascending_mu_unbounded_alt\n                  (CPO1.EC.representative\n                     c)\n                  (S (length p))))).\nsplit; auto.\n*\n  remember ((constructive_indefinite_description\n       (fun n : nat =>\n        mu (proj1_sig (CPO1.EC.representative c) n) >=\n        S (length p))\n       (CPO1.SEM.ascending_mu_unbounded_alt\n          (CPO1.EC.representative c) \n          (S (length p))))) as c'.\n  destruct c' as (k & Hk).\n  cbn.\n  clear Heqc'.\n  now rewrite <- Heqq in Hk.\n*\n   now rewrite <- Heqq.\nQed.\n\nDefinition pos_sym (p : list nat) (c:CPO1.C) : option nat :=\n  match c with\n  | CPO1.elt e => fpos_sym p e\n  | CPO1.cls c => rpos_sym p c                \n  end.  \n\nLemma mirror_pos : forall p t,  pos p (mirror t) = pos_sym p t.\nProof.\nintros p t.\ndestruct t.\n*\n  cbn.\n  apply ProductiveMirrorMod.FM.fmirror_fpos.\n*\n  cbn.\n remember (CPO1.EC.representative ec) as q.\n destruct q as (q & Ha).\n cbn.\n destruct (rpos_fpos p  (CPO2.EC.class_of\n       (exist (ascending ordc)\n          (fun n : nat => fc (q n))\n          (fc_prod_asc q Ha)))) as (k1 & Hm1 & Heq1).\n \n unfold Cc, Seq in *.\n rewrite Heq1.\n destruct (rpos_sym_fpos_sym  p ec) as (k1' & Hm1' & Heq'1).\n rewrite <-  Heqq in *.\n cbn in *.\n rewrite Heq'1.\n unfold fc in *.\n clear Heq1 Heq'1 Heqq.\n generalize (EC.sim_representative   (exist \n                                (ascending ordc)\n                                (fun n : nat =>\n                                 ProductiveMirrorMod.FM.fmirror\n                                   (q n))\n                                (fc_prod_asc q Ha))); intro Hsim.\n unfold Cc, Seq in *.\n cbn.\nremember   (EC.representative\n              (EC.class_of\n                 (@exist\n                    (forall _ : nat,\n                     @Ftree NatTypeMod.A)\n                    (@ascending (@Ftree NatTypeMod.A)\n                       ordc)\n                    (fun n : nat =>\n                     ProductiveMirrorMod.FM.fmirror\n                       (q n)) (fc_prod_asc q Ha)))) as r.\ndestruct r  as (r & Har).\ncbn in *.\ndestruct  (Hsim (S (length p))) as (x & (n & Ho1 & Ho2 & Hge)).\nremember (k1 + k1' + n) as N.\nunfold ordc, mu in *.\nreplace height with F.height in *; auto.   \nassert (Heq1 : fpos p (r N) = fpos p (r k1)).\n{\n  eapply fpos_fprefix; try lia.\n  apply increasing_alt;\n    [apply fprefix_refl | apply fprefix_trans | apply fprefix_antisym | now destruct Har | lia ].\n}\nrewrite <- Heq1.\nassert (Heq2 : fpos p (r N) = fpos p x ).\n{\n  eapply fpos_fprefix; try lia.\n  apply fprefix_trans with (t2 := r n); auto.\n  apply increasing_alt;\n    [apply fprefix_refl | apply fprefix_trans | apply fprefix_antisym | now destruct Har | lia ].\n}\nrewrite Heq2.\nassert (Heq3 : fpos p (ProductiveMirrorMod.FM.fmirror (q N)) = fpos p x).\n{\n  eapply fpos_fprefix; try lia.\n  apply fprefix_trans with (t2 := (ProductiveMirrorMod.FM.fmirror\n             (q n))); auto.\n  eapply increasing_alt with (q0:= fun n => (ProductiveMirrorMod.FM.fmirror (q n)))(i := n)(j := N);\n    [apply fprefix_refl | apply fprefix_trans | apply fprefix_antisym |  | lia ].\n  intro z.\n  replace fprefix with ProductiveMirrorMod.FM.F.fprefix; auto.\n  apply ProductiveMirrorMod.FM.fmirror_mono.\n  destruct Ha as (Hi & Hns).\n  apply Hi.\n}\nrewrite <- Heq3.\nrewrite ProductiveMirrorMod.FM.fmirror_fpos.\nreplace (ProductiveMirrorMod.FM.fpos_sym) with fpos_sym in *; auto.\neapply fpos_sym_fprefix; try lia.\n  apply increasing_alt;\n    [apply fprefix_refl | apply fprefix_trans | apply fprefix_antisym | now destruct Ha | lia].\nQed.\n  \nEnd MirrorProperties.\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/second_method/Mirror.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6553296059847147}}
{"text": "Require Import ZArith_base Lia.\nRequire Import QArith Qabs.\nRequire Import Setoid SetoidClass Morphisms.\n\nRequire Import Rcauchy_lemmas.\n\nDefinition R := nat -> Q.\nLocal Open Scope Q_scope.\n\nDefinition Req u v := \n  forall ε, ε > 0 -> exists N:nat, forall n m, (n > N)%nat -> (m > N)%nat -> \n      Qabs (u n - v m) < ε.\n\nLemma equiv_trans : Transitive Req.\nintros x y z H1 H2 ε ?. \nassert (Hε : (ε * (1#2)) > 0).\napply Qdiv_pos.\nassumption.\n\ndestruct (H1 (ε * (1#2)) Hε) as [N₁ H₁].\ndestruct (H2 (ε * (1#2)) Hε) as [N₂ H₂].\nexists (Max.max N₁ N₂).\nintros n m Hn Hm.\napply Qle_lt_trans with (Qabs ((x n - y m) + (y m - z m))).\nsetoid_replace (x n - y m + (y m - z m)) with (x n - z m); [|ring].\napply Qle_refl.\napply Qle_lt_trans with ((Qabs (x n - y m)) + (Qabs (y m - z m))).\neapply Qabs_triangle.\nsetoid_replace ε with (ε * (1#2) + ε*(1#2)); [|field].\nassert (Qabs (x n - y m) < ε * (1#2)).\napply H₁. \napply le_lt_trans with (Max.max N₁ N₂); [ apply Max.le_max_l | assumption].\napply le_lt_trans with (Max.max N₁ N₂); [ apply Max.le_max_l | assumption].\nassert (Qabs (y m - z m) < ε * (1#2)).\napply H₂.\napply le_lt_trans with (Max.max N₂ N₁); [ apply Max.le_max_l | rewrite Max.max_comm; assumption].\napply le_lt_trans with (Max.max N₂ N₁); [ apply Max.le_max_l | rewrite Max.max_comm; assumption].\nauto with qarith.\napply Qplus_lt_morphism; assumption.\nQed.\n\nLemma equiv_sym : Symmetric Req.\nintros x y H.\nintros ε Hpos.\ndestruct (H ε Hpos) as [N Hε].\nexists N.\nintros.\nsetoid_replace (y n - x m) with (- (x m - y n)).\nrewrite Qabs_opp.\napply Hε; assumption.\nring.\nQed.\n\nAdd Parametric Relation : R Req \n   symmetry proved by equiv_sym \n   transitivity proved by equiv_trans\n as Req_per.\nInstance defaut_relation_Req : DefaultRelation Req.\nDefined.\n\nProgram Instance R_partial_setoid : PartialSetoid R := {\n  pequiv := Req\n}.\n\nDeclare Scope R_scope.\nDelimit Scope R_scope with R.\nLocal Open Scope R_scope.\n\nDefinition R0 : R := fun _ => 0%Q.\nDefinition R1 : R := fun _ => 1%Q.\nDefinition Rplus (u v : R) : R := fun n => (u n) + (v n).\nDefinition Rmult (u v : R) : R := fun n => (u n) * (v n).\nDefinition Ropp (u : R) : R := fun n => - (u n).\nDefinition Rabs (u : R) := fun n => Qabs (u n).\nDefinition Rpositive (u : R) := exists v, u =~= v /\\ forall n, (v n > 0)%Q.\nDefinition Rlt u v := Rpositive (Rplus v (Ropp u)).\n\nDefinition Rinv u (H : ~(u =~= R0)) := fun n => Qinv (u n).\n\nInfix \"+\" := Rplus : R_scope.\nInfix \"*\" := Rmult : R_scope.\nNotation \"- x\" := (Ropp x) : R_scope.\nNotation \"/ x H\" := (Rinv x H) (at level 100) : R_scope.\nInfix \"<\" := Rlt : R_scope.\n\n\n(* A bit too much... why omega can't do that ? *)\nLtac max_solve trm := match trm with \n    O => fail\n | S ?p => \n       eassumption \n    || (eapply Max.le_max_l; max_solve p)\n    || (eapply Max.le_max_r; max_solve p)\n    || eauto with zarith\n    || (eapply le_lt_trans; max_solve p)\n    || (rewrite Max.max_comm; max_solve p)\n   end.\nTactic Notation \"max_solve\" := max_solve 6%nat. \n\nAdd Morphism Rplus with signature (Req ==> Req ==> Req) as Rplus_comp.\nintros u₁ u₂ H1 v₁ v₂ H2.\nintros ε Hpos.\nassert (Hε : (ε * (1#2)) > 0).\napply Qdiv_pos.\nassumption.\ndestruct (H1 (ε*(1#2)) Hε)%Q as [N₁ H₁]; clear H1.\ndestruct (H2 (ε*(1#2))%Q Hε) as [N₂ H₂]; clear H2.\nexists (Max.max N₁ N₂).\nintros n m Hn Hm.\nunfold Rplus.\nsetoid_replace (u₁ n + v₁ n - (u₂ m + v₂ m))%Q with ((u₁ n - u₂ m) + (v₁ n - v₂ m))%Q;[|ring].\napply Qle_lt_trans with ((Qabs (u₁ n - u₂ m)) + (Qabs (v₁ n - v₂ m)))%Q.\napply Qabs_triangle.\nsetoid_replace ε with (ε * (1#2) + ε*(1#2))%Q; [|field].\napply Qplus_lt_morphism.\napply H₁; max_solve.\napply H₂; eapply le_lt_trans; try eapply Max.le_max_r; eauto with arith.\nQed.\n\nFixpoint bounded_abs_max u n := match n with \n   O => Qabs (u O)\n | S p => Qmax (bounded_abs_max u p) (Qabs (u p))\nend.\n\nLemma bounded_correct: \n  forall u N n, (n < N)%nat -> (Qabs (u n) <= (bounded_abs_max u N))%Q.\nintros u N n Hn.\ninduction N; simpl.\ninversion Hn.\n\ninversion Hn.\nrewrite Qmax_comm.\n\napply le_Qmax.\napply Qle_refl.\napply le_Qmax.\napply IHN.\nlia.\nQed.\n\nLemma bounded : \n  forall u v:R, u =~= u -> exists M, forall n:nat, (Qabs (u n) <= M)%Q.\nintros.\ndestruct (H 1%Q) as [N HN].\nauto with qarith.\nexists (Qmax (bounded_abs_max u (S N)) (Qabs (u (S N)) + 1))%Q.\nintros n. \nelim (le_lt_dec n N); intros Hdec.\napply le_Qmax.\napply bounded_correct.\nlia.\nrewrite Qmax_comm.\napply le_Qmax.\nassert (Qabs (u n) - Qabs(u (S N)) <= 1).\napply Qle_trans with (Qabs (u n - u(S N))).\napply Qabs_triangle_reverse.\napply Qlt_le_weak.\napply HN.\nassumption.\nlia.\nrewrite Qplus_comm.\nsetoid_replace (Qabs (u n)) with \n               ((Qabs (u n) - Qabs (u (S N))) + Qabs (u (S N)))%Q;[|ring].\napply Qplus_le_compat.\nassumption.\napply Qle_refl.\nQed.\n\nAdd Morphism Rmult with signature (Req ==> Req ==> Req) as Rmult_comp.\nintros u₁ u₂ H1 v₁ v₂ H2.\nintros ε Hpos.\n\nassert (EC : (exists C, forall n, Qabs (u₁ n) < C /\\ Qabs (u₂ n) < C /\\ Qabs (v₁ n) < C /\\ Qabs (v₂ n) < C)%Q).\n(** skip at first read **)\nassert (EA₁ :(exists A₁, forall n, Qabs (u₁ n) < A₁)%Q).\ndestruct (bounded u₁ u₁) as [A₁ HA₁].\neapply transitivity; [|symmetry];eassumption.\nexists (A₁ + 1)%Q.\nintros n; eapply Qle_lt_trans.\neapply HA₁.\nsetoid_replace A₁ with (A₁ + 0)%Q at 1; [|ring].\napply Qplus_le_lt_compat; auto with qarith.\ndestruct EA₁ as [A₁ HA₁]. \nassert (EA₂ :(exists A₂, forall n, Qabs (u₂ n) < A₂)%Q).\ndestruct (bounded u₂ u₂) as [A₂ HA₂].\neapply transitivity; [symmetry|];eassumption.\nexists (A₂ + 1)%Q.\nintros n; eapply Qle_lt_trans.\neapply HA₂.\nsetoid_replace A₂ with (A₂ + 0)%Q at 1; [|ring].\napply Qplus_le_lt_compat; auto with qarith.\ndestruct EA₂ as [A₂ HA₂]. \n\nassert (EB₁ :(exists B₁, forall n, Qabs (v₁ n) < B₁)%Q).\ndestruct (bounded v₁ v₁) as [B₁ HB₁].\neapply transitivity; [|symmetry];eassumption.\nexists (B₁ + 1)%Q.\nintros n; eapply Qle_lt_trans.\neapply HB₁.\nsetoid_replace B₁ with (B₁ + 0)%Q at 1; [|ring].\napply Qplus_le_lt_compat; auto with qarith.\ndestruct EB₁ as [B₁ HB₁]. \nassert (EB₂ :(exists B₂, forall n, Qabs (v₂ n) < B₂)%Q).\ndestruct (bounded v₂ v₂) as [B₂ HB₂].\neapply transitivity; [symmetry|];eassumption.\nexists (B₂ + 1)%Q.\nintros n; eapply Qle_lt_trans.\neapply HB₂.\nsetoid_replace B₂ with (B₂ + 0)%Q at 1; [|ring].\napply Qplus_le_lt_compat; auto with qarith.\ndestruct EB₂ as [B₂ HB₂]. \nexists (Qmax (Qmax A₁ A₂) (Qmax B₁ B₂)).\nintros n.\nlet rec t trm := match trm with \n    O => fail\n | S ?p => \n   first [ apply HA₁ | apply HA₂ | apply HB₁ | apply HB₂  | apply lt_Qmax; t p| rewrite Qmax_comm; t p]\nend in repeat split; t 6%nat.\n(** Ok, you can continue your reading here. *)\ndestruct EC as [C HC].\nassert (Hpos_C : C > 0).\napply Qle_lt_trans with (Qabs (u₁ O)).\napply Qabs_nonneg.\nelim (HC O); intuition.\nassert (Hpos_complique : (ε * (Qinv C)*(1#3)) > 0).\napply Qdiv_pos.\napply Qmult_pos_compat.\nassumption.\napply Qinv_lt_0_compat.\nassumption.\ndestruct (H1 (ε * (Qinv C)*(1#3))%Q Hpos_complique) as [N₁ H₁]; clear H1.\ndestruct (H2 (ε * (Qinv C)*(1#3))%Q Hpos_complique) as [N₂ H₂]; clear H2.\nexists (Max.max N₁ N₂).\nintros n m Hn Hm.\nunfold Rmult.\nsetoid_replace (u₁ n * v₁ n - u₂ m * v₂ m) \n               with (u₁ n * (v₁ n - v₂ m) + v₂ m * (u₁ n - u₂ m))%Q; [|ring].\neapply Qle_lt_trans.\neapply Qabs_triangle.\ndo 2 rewrite Qabs_Qmult.\napply Qle_lt_trans with \n    ((C * (ε * / C * (1 # 3))+ (C * (ε * / C * (1 # 3)))))%Q.\napply Qplus_le_morphism; (apply Qmult_pos_le_compat; (split; [ apply Qabs_nonneg | ])).\nelim (HC n); intuition.\napply Qlt_le_weak; apply H₂; eapply le_lt_trans; try eapply Max.le_max_r; eauto with arith.\nelim (HC m); intuition.\napply Qlt_le_weak; apply H₁; max_solve.\nsetoid_replace (C * (ε * / C * (1 # 3)) + C * (ε * / C * (1 # 3)))%Q\n               with ((2#3)*ε)%Q.\nsetoid_replace ε with (1*ε)%Q at 2.\napply Qmult_lt_compat_r.\nassumption.\nauto with qarith.\nfield.\nfield.\nintro Abs; rewrite Abs in Hpos_C.\ninversion Hpos_C.\nQed.\n\nLemma far_from_zero : \n  forall u:R, u =~= u -> ~(u =~= R0) -> exists N, forall n:nat, (n > N)%nat -> (Qabs (u n) > 0)%Q.\n(* Il faut EM pour prouver ça. *)\nAdmitted.\n\n(* This is the most difficult thing I have ever written with setoids. *)\nDefinition sign_rinv : relation (forall x:R, ~(x=~=R0) -> R).\nrefine (respectful_hetero R R (fun x => ~(x =~= R0) -> R) (fun x => ~(x =~= R0) -> R) \n           Req \n           _).\nintros x y. \nrefine (respectful_hetero (~(x =~= R0)) (~(y =~= R0)) (fun _ => R) (fun _ => R) \n           (fun x y => True) (fun _ _ => Req)).\nDefined. \n\n(* It's complicated. Ok. But no body has to understand it. \n   The important thing is that the following morphism just say \n   what we want it to say. *)\nInstance Rinv_comp : Proper sign_rinv Rinv.\nintros u v Huv π₁ π₂ _.\nintros ε Hpos.\n\ndestruct (far_from_zero u) as [Nu].\neapply transitivity;[|symmetry];eassumption.\nassumption.\ndestruct (far_from_zero v) as [Nv].\neapply transitivity;[symmetry|];eassumption.\nassumption.\nexists (Max.max Nu Nv).\nintros n m Hn Hm.\nunfold Rinv.\n\nAdmitted.\n", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/src/Reals/Raxioms/Rcauchy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656671, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6553295931975199}}
{"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\nSet Implicit Arguments.\nRequire Import BinPos.\nRequire Export List.\nRequire Export ListTactics.\nOpen Local Scope positive_scope.\n\nSection MakeBinList.\n Variable A : Type.\n Variable default : A.\n\n Fixpoint jump (p:positive) (l:list A) {struct p} : list A :=\n  match p with\n  | xH => tail l\n  | xO p => jump p (jump p l)\n  | xI p  => jump p (jump p (tail l))\n  end.\n\n Fixpoint nth (p:positive) (l:list A) {struct p} : A:=\n  match p with\n  | xH => hd default l\n  | xO p => nth p (jump p l)\n  | xI p => nth p (jump p (tail l))\n  end.\n\n Lemma jump_tl : forall j l, tail (jump j l) = jump j (tail l).\n Proof.\n  induction j;simpl;intros.\n  repeat rewrite IHj;trivial.\n  repeat rewrite IHj;trivial.\n  trivial.\n Qed.\n\n Lemma jump_Psucc : forall j l,\n  (jump (Psucc j) l) = (jump 1 (jump j l)).\n Proof.\n  induction j;simpl;intros.\n  repeat rewrite IHj;simpl;repeat rewrite jump_tl;trivial.\n  repeat rewrite jump_tl;trivial.\n  trivial.\n Qed.\n\n Lemma jump_Pplus : forall i j l,\n  (jump (i + j) l) = (jump i (jump j l)).\n Proof.\n  induction i;intros.\n  rewrite xI_succ_xO;rewrite Pplus_one_succ_r.\n  rewrite <- Pplus_diag;repeat rewrite <- Pplus_assoc.\n  repeat rewrite IHi.\n  rewrite Pplus_comm;rewrite <- Pplus_one_succ_r;rewrite jump_Psucc;trivial.\n  rewrite <- Pplus_diag;repeat rewrite <- Pplus_assoc.\n  repeat rewrite IHi;trivial.\n  rewrite Pplus_comm;rewrite <- Pplus_one_succ_r;rewrite jump_Psucc;trivial.\n Qed.\n\n Lemma jump_Pdouble_minus_one : forall i l,\n  (jump (Pdouble_minus_one i) (tail l)) = (jump i (jump i l)).\n Proof.\n  induction i;intros;simpl.\n  repeat rewrite jump_tl;trivial.\n  rewrite IHi. do 2 rewrite <- jump_tl;rewrite IHi;trivial.\n  trivial.\n Qed.\n\n\n Lemma nth_jump : forall p l, nth p (tail l) = hd default (jump p l).\n Proof.\n  induction p;simpl;intros.\n  rewrite <-jump_tl;rewrite IHp;trivial.\n  rewrite <-jump_tl;rewrite IHp;trivial.\n  trivial.\n Qed.\n\n Lemma nth_Pdouble_minus_one :\n  forall p l, nth (Pdouble_minus_one p) (tail l) = nth p (jump p l).\n Proof.\n  induction p;simpl;intros.\n  repeat rewrite jump_tl;trivial.\n  rewrite jump_Pdouble_minus_one.\n  repeat rewrite <- jump_tl;rewrite IHp;trivial.\n  trivial.\n Qed.\n\nEnd MakeBinList.\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/plugins/setoid_ring/BinList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.6553012668112953}}
{"text": "(*===========================================================================\n  Properties of bit vectors\n  ===========================================================================*)\nFrom Coq\n    Require Import ZArith.ZArith.\n(*Require Import common.tuplehelp common.nathelp.*)\nRequire Import mathcomp.ssreflect.ssreflect.\n\nFrom mathcomp Require Import ssrfun ssrbool eqtype ssrnat seq fintype tuple div zmodp ssralg.\nRequire Import ssrextra.nat ssrextra.tuple.\nRequire Import spec.spec.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLemma trivialBits (p q: BITS 0) : p = q.\nProof. by rewrite (tuple0 p) (tuple0 q). Qed.\n\n(*---------------------------------------------------------------------------\n    Properties of conversion to and from natural numbers.\n  ---------------------------------------------------------------------------*)\nLemma toNatCons n b (p:BITS n) : toNat (consB b p) = b + (toNat p).*2.\nProof. done. Qed.\n\nLemma toNatNil (p:BITS 0) : toNat p = 0.\nProof. by rewrite (tuple0 p). Qed.\n\n(* toNat is left-inverse to fromNat *)\nLemma toNatK n : cancel (@toNat n) (@fromNat n).\nProof. induction n; first (move => p; apply trivialBits).\n+ case/tupleP => b x. rewrite toNatCons/fromNat-/fromNat /= half_bit_double.\nrewrite IHn oddD odd_double. by case b.\nQed.\n\n(* Hence toNat is injective *)\nDefinition toNat_inj n := can_inj (@toNatK n).\n\n(* toNat result is bounded *)\nLemma toNatBounded n : forall (p: BITS n), toNat p < 2^n.\nProof. induction n. move => p. by rewrite toNatNil.\ncase/tupleP => [b p].\nrewrite expnS mul2n toNatCons.\ncase b.\n+ rewrite ltn_Sdouble. apply IHn.\n+ rewrite ltn_double. apply IHn.\nQed.\n\nLemma toNat_fromNatBounded n : forall m, m < 2^n -> toNat (fromNat (n:=n) m) = m.\nProof. induction n.\n+ rewrite expn0. by case.\n+ rewrite expnS. move => m.  specialize (IHn m./2).\n  move => LT.\n  assert (m./2 < 2^n).\n  rewrite -ltn_double. rewrite -(odd_double_half m) mul2n in LT.\n  rewrite -(ltn_add2l (odd m)).\n  by apply ltn_addl.\n  specialize (IHn H).\n  rewrite /toNat-/toNat/=.\n  rewrite /toNat/= in IHn. rewrite IHn.\n  by rewrite odd_double_half.\nQed.\n\nLemma fromNatBounded_eq m1 m2 n : m1 < 2^n -> m2 < 2^n ->\n  (m1==m2) = (fromNat (n:=n) m1 == fromNat m2).\nProof. move => B1 B2.\ncase E: (m1 == m2);\ncase E': (#m1 == #m2) => //. by rewrite (eqP E) eq_refl in E'.\nrewrite -(toNat_fromNatBounded B1) -(toNat_fromNatBounded B2) in E.\nby rewrite (eqP E') eq_refl in E.\nQed.\n\nLemma fromNatHalf n m : cons_tuple (odd m) (fromNat (n:=n) m./2) = fromNat m.\nProof. done. Qed.\n\nLemma fromNat_wrap n : forall m, fromNat (n:=n) m = fromNat (n:=n) (m + 2^n).\nProof. induction n => //.\nrewrite expnS.\nmove => m.\ncase ODD: (odd m); rewrite /fromNat-/fromNat /=ODD oddD oddM/=ODD/= halfD ODD/=.\nspecialize (IHn m./2). by rewrite oddM/= add0n mul2n doubleK IHn.\nspecialize (IHn m./2). by rewrite add0n mul2n doubleK IHn.\nQed.\n\nLemma fromNat_wrapMany n c : forall m, fromNat (n:=n) m = fromNat (n:=n) (m + c * 2^n).\nProof. induction c => m. by rewrite mul0n addn0.\nrewrite mulSn (addnC (2^n)) addnA fromNat_wrap. rewrite IHc.\nby rewrite -addnA (addnC (2^n)) addnA.\nQed.\n\nLemma toNat_mod n (p:BITS n): toNat p = toNat p %% 2^n.\nProof. rewrite modn_small => //. apply toNatBounded. Qed.\n\nLemma toNat_fromNat n m : @toNat n (fromNat m) = m %% 2^n.\nProof. have H:= divn_eq m (2^n). rewrite {1}H.\nhave HH:= @fromNat_wrapMany n (m %/ 2^n) (m %% 2^n). rewrite addnC in HH. rewrite -HH.\nrewrite toNat_fromNatBounded. done. apply ltn_pmod. apply expn_gt0. Qed.\n\n(* TODO: remove *)\nLemma splitTuple {X n} {a b:X} {c d:n.-tuple X} : cons_tuple a c = cons_tuple b d -> a = b /\\ c = d.\nProof. move => H. split. by inversion H. apply val_inj. by inversion H. Qed.\n\n\nLemma fromNat_succn n : forall b c, @fromNat n b = fromNat c -> @fromNat n (b.+1) = fromNat(c.+1).\nProof. induction n => //.\nmove => b c EQ. rewrite /fromNat-/fromNat. rewrite /fromNat-/fromNat in EQ.\nelim: (splitTuple EQ) => [EQ1 EQ2]. simpl in EQ1. simpl in EQ2.\nspecialize (IHn _ _ EQ2). rewrite/= !uphalf_half /=EQ1.\ncase ODD: (odd c). + by rewrite !add1n IHn. + by rewrite !add0n EQ2.\nQed.\n\nLemma fromNat_addn n : forall a b c, @fromNat n b = fromNat c -> @fromNat n (a+b) = fromNat(a+c).\nProof. induction a => //.\nmove => b c EQ. rewrite -addn1 -!addnA !add1n. apply IHa. by apply fromNat_succn.\nQed.\n\nLemma toZp_fromNat n m : toZp (fromNat (n:=n.+1) m) = (m%:R)%R.\nProof. apply val_inj.\nrewrite /toZp toNat_fromNat Zp_nat.\nrewrite /=Zp_cast; last apply pow2_gt1.\nby rewrite modn_mod.\nQed.\n\nLemma toZpAux_fromNat n c : toZpAux (m:=n.+1) (fromNat (n:=n.+1) c) = (c%:R)%R.\nProof. apply val_inj.\nrewrite /toZpAux toNat_fromNat Zp_nat.\nrewrite /=Zp_cast; last apply pow2_gt1.\nby rewrite modn_mod.\nQed.\n\n#[export]\nHint Rewrite toZp_fromNat toZpAux_fromNat : ZpHom.\n\nLemma toNat_droplsb n (p: BITS n.+1) : toNat (droplsb p) = (toNat p)./2.\nProof. case/tupleP: p => [b p]. rewrite /droplsb/splitlsb beheadCons theadCons.\nby rewrite toNatCons/= half_bit_double.\nQed.\n\nLemma toNatCat m n (p : BITS m) (q: BITS n) :\n  toNat (p ## q) = toNat p * 2^n + toNat q.\nProof.\nelim: n q; first by move=> q; rewrite (tuple0 q) addn0 expn0 muln1.\nmove=> n IHn; case/tupleP => [b q].\nrewrite /catB catCons !toNatCons IHn expnS -!muln2; ring.\nQed.\n\n(*---------------------------------------------------------------------------\n    Properties of conversion to and from 'Z_(2^n)\n  ---------------------------------------------------------------------------*)\n\n(* This only holds for n.+1 because 'Z_1 actually has two elements - it's\n   definitionally the same as 'Z_2 in order to force a ring structure. See zmodp\n   for more details *)\nLemma fromZpK n : cancel (@fromZp n.+1) (@toZp n.+1).\nProof.\n  move => x. rewrite /toZp/fromZp. rewrite  toNat_fromNat modn_small. apply valZpK.\n  destruct x. simpl. rewrite Zp_cast in i => //.\n  apply pow2_gt1.\nQed.\n\nLemma toZpK n : cancel (@toZp n) (@fromZp n).\nProof. case E: (n == 0).\n+ rewrite /cancel. rewrite (eqP E). move => x. apply trivialBits.\n+ move => x. rewrite /fromZp/toZp/=.\n  rewrite Zp_cast. by rewrite (modn_small (toNatBounded _)) toNatK.\n  apply negbT in E. destruct n => //. apply pow2_gt1.\nQed.\n\nLemma toZp_inj n : injective (@toZp n).\nProof. apply (can_inj (@toZpK _)). Qed.\n\nLemma fromZp_inj n : injective (@fromZp n.+1).\nProof. apply (can_inj (@fromZpK _)). Qed.\n\nLemma toZp_eq n (x y: BITS n) : (x == y) = (toZp x == toZp y).\nProof. destruct n. by rewrite (tuple0 x) (tuple0 y).\ncase E: (toZp x == toZp y).\nrewrite (toZp_inj (eqP E)). by rewrite eq_refl.\napply (contraFF (b:=false)) => // => H.\nrewrite (eqP H) (eq_refl) in E. done.\nQed.\n\nCorollary toZp_neq n (x y: BITS n) : (x != y) = (toZp x != toZp y).\nProof. by rewrite toZp_eq. Qed.\n\n(*---------------------------------------------------------------------------\n    Properties of bit get and set\n  ---------------------------------------------------------------------------*)\n\nLemma setBitThenGetSame n : forall (p: BITS n) i b, i<n -> getBit (setBit p i b) i = b.\nProof.\ninduction n => //.\ncase/tupleP => [b' p]. move => i b LT.\ndestruct i => //.\nsimpl. rewrite theadCons beheadCons. assert (LT' : i < n) by done.\nrewrite /getBit/=. apply IHn; done.\nQed.\n\nLemma setBitThenGetDistinct n :\n  forall (p: BITS n) i i' b, i<n -> i'<n -> i<>i' -> getBit (setBit p i b) i' = getBit p i'.\nProof.\ninduction n => //.\ncase/tupleP => [b' p]. move => i i' b LT LT' NEQ.\ndestruct i.\n(* i = 0 *) simpl. rewrite beheadCons. destruct i' => //.\n(* i <> 0 *)\ndestruct i' => //.\nrewrite /= theadCons beheadCons /getBit/=.\nassert (lt : i < n) by done.\nassert (lt' : i' < n) by done.\nassert (neq' : i <> i') by  intuition.\nspecialize (IHn p _ _ b lt lt' neq'). apply IHn.\nQed.\n\nLemma getBit_joinmsb :\n  forall n (bs: BITS n) k,\n    k <= n ->\n    getBit (joinmsb (false , bs)) k = getBit bs k.\nProof.\n  elim=> [|n IHn] bs k leq_k_n.\n  - (* Case: n ~ 0 *)\n    rewrite leqn0 in leq_k_n.\n    move/eqP: leq_k_n=> ->.\n    by rewrite !tuple0.\n  - (* Case: n ~ n.+1 *)\n    case/tupleP: bs=> [b bs].\n    case: k leq_k_n => [|k leq_k_n].\n    + (* Case: k ~ 0 *)\n      by trivial.\n    + (* Case: k ~ k.+1 *)\n      rewrite /joinmsb/splitlsb tuple.beheadCons\n              tuple.theadCons -/joinmsb /joinlsb //=.\n      by apply: IHn; assumption.\nQed.\n\nLemma getBit_dropmsb:\n  forall n (bs : BITS n.+1) k, k < n ->\n    getBit (dropmsb bs) k = getBit bs k.\nProof.\n  elim=> // n /= IHn /tupleP[b bs] k le_k.\n  rewrite /dropmsb /splitmsb /=\n          tuple.theadCons tuple.beheadCons /=\n          -/splitmsb.\n  set cr := splitmsb bs; rewrite (surjective_pairing cr).\n  have ->: ((cr.1, joinlsb (cr.2, b))).2 = joinlsb (dropmsb bs, b)\n    by rewrite /dropmsb.\n  case: k le_k => // k le_k.\n  + (* k ~ k + 1 *)\n    have H: forall bs', getBit (joinlsb (bs', b)) k.+1 = getBit bs' k by compute.\n    by rewrite !H; auto with arith.\nQed.\n\n(*---------------------------------------------------------------------------\n    Properties of all zeroes and all ones\n  ---------------------------------------------------------------------------*)\nLemma fromNat0 n : #0 = zero n.\nProof. induction n; first apply trivialBits.\n+ rewrite /zero /copy. rewrite /zero /copy in IHn. by rewrite /fromNat-/fromNat IHn nseqCons.\nQed.\n\nLemma count_ones:\n  forall n, (count_mem true (ones n)) = n.\nProof.\n  elim=> //=.\n  auto with arith.\nQed.\n\nLemma getBit_zero:\n  forall n k, getBit (n := n) #0 k = false.\nProof.\n  move=> n k.\n  rewrite fromNat0 /zero /copy /getBit nth_nseq if_same //.\nQed.\n\nLemma getBit_ones:\n  forall n k, k < n -> getBit (ones n) k = true.\nProof.\n  move=> n k le_k.\n  by rewrite /getBit nth_nseq le_k.\nQed.\n\nLemma toNat_zero n : toNat (zero n) = 0.\nProof. induction n => //. rewrite /toNat/=. rewrite /toNat in IHn. by rewrite IHn. Qed.\n\nCorollary toNat_fromNat0 n : @toNat n #0 = 0.\nProof. by rewrite fromNat0 toNat_zero. Qed.\n\nLemma msb_zero n : msb (zero n) = false.\nProof. by induction n. Qed.\n\nLemma toNat_ones_succ n : (toNat (ones n)).+1 = 2^n.\nProof. induction n => //.\nrewrite /toNat/=. rewrite /toNat/= in IHn.\nby rewrite expnS mul2n addnC addn1 -doubleS IHn.\nQed.\n\nCorollary toNat_ones n : toNat (ones n) = (2^n).-1.\nProof. by rewrite -toNat_ones_succ succnK. Qed.\n\nLemma msb_ones n : msb (ones n.+1) = true.\nProof. by induction n. Qed.\n\nLemma toZp_zero n : toZp (zero n) = 0%R.\nProof. rewrite /toZp toNat_zero. by apply val_inj. Qed.\n\nLemma toZpAux_zero m n : toZpAux (m:=m) (zero n) = 0%R.\nProof. rewrite /toZpAux toNat_zero. by apply val_inj. Qed.\n\nLemma toZp_ones n : toZp (ones n.+1) = (-1)%R.\nProof. rewrite /toZp toNat_ones. apply val_inj.\nrewrite /= Zp_cast; last apply pow2_gt1.\nrewrite -subn1. replace (1 %% 2^n.+1) with 1 => //.\nby rewrite modn_small; last apply pow2_gt1.\nQed.\n\n#[export]\nHint Rewrite toZpK fromZpK toZp_zero toZpAux_zero toZp_ones : ZpHom.\n\n\n(*---------------------------------------------------------------------------\n    Properties of joinmsb and splitmsb\n  ---------------------------------------------------------------------------*)\n\nLemma toNat_joinmsb n : forall c (p: BITS n), toNat (joinmsb (c, p)) = c * 2^n + toNat p.\nProof. induction n.\n+ move => c p. by rewrite /joinmsb (tuple0 p) expn0 muln1.\n+ move => c. case/tupleP => [b p].\n  rewrite /joinmsb-/joinmsb /splitlsb theadCons beheadCons !toNatCons expnS IHn.\n  by rewrite doubleD addnCA -mul2n mulnCA.\nQed.\n\nLemma toNat_joinmsb0 n (p: BITS n) : toNat (joinmsb0 p) = toNat p.\nProof. by rewrite toNat_joinmsb. Qed.\n\nLemma splitmsb_fromNat n :\n  forall m, splitmsb (n:=n) (fromNat m) = (odd (m %/ 2^n), fromNat m).\nProof. induction n => m.\n+ by rewrite /dropmsb/=beheadCons!theadCons expn0 divn1.\n+ rewrite expnS. rewrite /fromNat-/fromNat/=.\n  rewrite /joinlsb !beheadCons!theadCons fromNatHalf. specialize (IHn m./2). rewrite IHn.\n  by rewrite -divn2 -divnMA.\nQed.\n\nCorollary dropmsb_fromNat n m : dropmsb (n:=n) (fromNat m) = (fromNat m).\nProof. by rewrite /dropmsb splitmsb_fromNat. Qed.\n\nCorollary toNat_dropmsb n (p: BITS n.+1) : toNat (dropmsb p) = toNat p %% 2^n.\nProof. rewrite -{1}(toNatK p). rewrite dropmsb_fromNat. by rewrite toNat_fromNat. Qed.\n\nLemma toZp_joinmsb0 n (p: BITS n) : toZp (joinmsb0 p) = toZpAux p.\nProof. apply val_inj.\nrewrite /toZp/toZpAux/= Zp_cast; last apply pow2_gt1.\nby rewrite toNat_joinmsb0.\nQed.\n\nLemma toZp_dropmsb n (p: BITS n.+2) : toZp (n:=n.+1) (dropmsb p) = toZpAux (m:=n.+1) p.\nProof.\napply val_inj.\nrewrite /toZp/toZpAux/= Zp_cast; last apply pow2_gt1.\nrewrite toNat_dropmsb.\nby rewrite modn_mod.\nQed.\n\n#[export]\nHint Rewrite toZp_joinmsb0 toZp_dropmsb : ZpHom.\n\nLemma splitmsbK n : cancel (@splitmsb n) (@joinmsb n).\nProof. induction n.\n+ case/tupleP => [b p]. by rewrite (tuple0 p).\n+ case/tupleP => [b p]. rewrite /= beheadCons theadCons. specialize (IHn p).\ncase E: (splitmsb p) => [b' p'].\nrewrite beheadCons theadCons.\nrewrite E in IHn. by rewrite IHn.\nQed.\n\nLemma joinmsbK n : cancel (@joinmsb n) (@splitmsb n).\nProof. induction n.\n+ move => [b p]. by rewrite !(tuple0 p) /= theadCons beheadCons.\n+ move => [c p]. case/tupleP: p => [b p].\n  by rewrite /= !theadCons !beheadCons IHn.\nQed.\n\nCorollary dropmsb_joinmsb n b (p:BITS n) : dropmsb (joinmsb (b, p)) = p.\nProof. by rewrite /dropmsb joinmsbK. Qed.\n\nLemma splitlsbK n : cancel (@splitlsb n) (@joinlsb n).\nProof. case/tupleP => [b p]. by rewrite /splitlsb beheadCons theadCons. Qed.\n\nLemma joinlsbK n : cancel (@joinlsb n) (@splitlsb n).\nProof. move => [p b]. by rewrite /joinlsb /splitlsb beheadCons theadCons. Qed.\n\nLemma toNat_joinlsb n (p:BITS n) b : toNat (joinlsb (p, b)) = b + (toNat p).*2.\nProof. done. Qed.\n\n(* Totally ridiculous proof *)\nLemma splitmsb_rev n : forall (b: BITS n.+1) hi (lo:BITS n),\n   splitmsb b = (hi,lo) -> rev b = hi::rev lo.\nProof. induction n => b hi lo/=.\n+ move => [<- <-] {lo}/=. case/tupleP:b => [b u]//=. by rewrite tuple0/=.\n+ move => H.\nspecialize (IHn (behead_tuple b) hi).\ndestruct (splitmsb (behead_tuple b)).\ninjection H => [H1 H2] {H}. rewrite H2 {H2} in IHn.\nspecialize (IHn b1 refl_equal). rewrite -H1/=.\ncase/tupleP E: b => [b' u]/=. rewrite E/= in IHn.\nby rewrite 2!rev_cons IHn rcons_cons.\nQed.\n\n(*---------------------------------------------------------------------------\n    Properties of concatenation and splitting of bit strings\n  ---------------------------------------------------------------------------*)\nLemma high_catB n2 n1 (p:BITS n1) (q:BITS n2) : high n1 (p ## q) = p.\nProof. induction n2.\n- rewrite /high (tuple0 q). by apply catNil.\n- case/tupleP: q => x q. rewrite /catB catCons /= beheadCons. apply IHn2.\nQed.\n\nLemma low_catB n2 n1 (p:BITS n1) (q:BITS n2) : low n2 (p ## q) = q.\nProof. induction n2; first apply trivialBits.\ncase/tupleP: q => x q. rewrite /catB catCons /= beheadCons. by rewrite IHn2.\nQed.\n\nLemma low_fromNat n2 n1: forall m, low n2 (fromNat (n:=n2+n1) m) = fromNat (n:=n2) m.\nProof. induction n2 => m //. by rewrite /= /joinlsb !beheadCons !theadCons/= IHn2. Qed.\n\nLemma split2eta : forall n2 n1 p, let (p1,p2) := split2 n1 n2 p in p = p1 ## p2.\nProof. unfold split2. induction n2.\n- move =>n1 p. by rewrite /catB catNil.\n- move => n1. case/tupleP => x p. rewrite /= (IHn2 n1 p).\nrewrite beheadCons theadCons high_catB low_catB. by rewrite /catB catCons. Qed.\n\nLemma split2app n2 n1 p1 p2 : split2 n1 n2 (p1 ## p2) = (p1,p2).\nProof. by rewrite /split2 high_catB low_catB. Qed.\n\nLemma split3app n3 n2 n1 p1 p2 p3 : split3 n1 n2 n3 (p1 ## p2 ## p3) = (p1,p2,p3).\nProof. by rewrite /split3 !split2app. Qed.\n\nLemma split4app n4 n3 n2 n1 p1 p2 p3 p4 :\n  split4 n1 n2 n3 n4 (p1 ## p2 ## p3 ## p4) = (p1,p2,p3,p4).\nProof. by rewrite /split4 !split2app. Qed.\n\nLemma split3eta n3 n2 n1 p: match split3 n1 n2 n3 p with (p1,p2,p3) => p1 ## p2 ## p3 end = p. Proof. rewrite /split3 /=. by rewrite -!split2eta. Qed.\n\nLemma split4eta n4 n3 n2 n1 p:\n  match split4 n1 n2 n3 n4 p with (p1,p2,p3,p4) => p1 ## p2 ## p3 ## p4 end = p.\nProof. rewrite /split4 /=. by rewrite -!split2eta. Qed.\n\nLemma split4eta' n4 n3 n2 n1 p:\n  let: (p1,p2,p3,p4) := split4 n1 n2 n3 n4 p in p1 ## p2 ## p3 ## p4 = p.\nProof. rewrite /split4 /=. by rewrite -!split2eta. Qed.\n\nLemma catB_inj n1 n2 (p1 q1: BITS n1) (p2 q2: BITS n2) :\n  p1 ## p2 = q1 ## q2 -> p1 = q1 /\\ p2 = q2.\nProof.\nmove => EQ.\nhave H1 := high_catB p1 p2.\nhave H2 := high_catB q1 q2.\nhave L1 := low_catB p1 p2.\nhave L2 := low_catB q1 q2.\nsplit. by rewrite -H1 -H2 EQ.\nby rewrite -L1 -L2 EQ.\nQed.\n\nLemma toNat_low n1 n2 (p: BITS (n1+n2)) : toNat (low n1 p) = toNat p %% 2^n1.\nProof. by rewrite -{1}(toNatK p) low_fromNat toNat_fromNat. Qed.\n\nLemma allBitsEq n (p q: BITS n) : (forall i, i < n -> getBit p i = getBit q i) -> p = q.\nProof. induction n. by rewrite (tuple0 p) (tuple0 q). \ncase/tupleP: p => [b p]. \ncase/tupleP: q => [c q]. \nmove => H. have H0:= H 0. rewrite /getBit/= in H0. rewrite H0 => //. \nrewrite (IHn p q). done.\nmove => i LT. apply (H i.+1 LT). \nQed. \n\nLemma lowBitsEq n1 n2 (p q: BITS (n1+n2)) : \n  (forall i, i < n1 -> getBit p i = getBit q i) <-> low n1 p = low n1 q.\nProof. induction n1 => //=.\ncase/tupleP: p => [b p]. fold plus in p.\ncase/tupleP: q => [c q]. fold plus in q. \nrewrite 2!beheadCons 2!theadCons /getBit/=. split => H. \n+ have H0:= H 0. rewrite /= in H0. rewrite H0 => //. \n  rewrite (proj1 (IHn1 p q)). done. move => i LT. apply (H i.+1 LT). \n+ move => i LT. destruct i. by injection H. \n  injection H => H1 H2. subst. apply (IHn1 p q). apply val_inj. apply H1. apply LT. \nQed. \n\nLemma highBitsEq n1 n2 (p q: BITS (n1+n2)) : \n  (forall i, n1 <= i -> getBit p i = getBit q i) <-> high n2 p = high n2 q.\nProof. induction n1 => /=.\nsplit.  \nhave ABE := @allBitsEq _ p q. move => H. apply: ABE. move => i H'. rewrite H => //.\nby move => ->.\ncase/tupleP: p => [b p]. fold plus in p. \ncase/tupleP: q => [c q]. fold plus in q. \nrewrite 2!beheadCons /getBit/=. split => H. \n+ apply IHn1. move => i LE. apply (H i.+1 LE). \n+ have IH' := (proj2 (IHn1 p q)). case => // i. by apply IH'. \nQed. \n\nLemma getBit_low n1: forall n2 (p: BITS (n1+n2)) i,\n  getBit (low n1 p) i = if i < n1 then getBit p i else false.\nProof. induction n1 => // n2 p i. destruct i => //. case/tupleP: p => [b p]. \nrewrite /getBit/joinlsb/= beheadCons theadCons. destruct i => //. apply IHn1. \nQed. \n\nLemma getBit_high n1: forall n2 (p: BITS (n1+n2)) i,\n  getBit (high n2 p) i = getBit p (i+n1).\nProof. induction n1 => // n2 p i. by rewrite addn0.  \nrewrite addnS. case/tupleP: p => [b p]. apply IHn1. Qed. \n\nLemma getBit_catB n1 n2 (p:BITS n1) (q:BITS n2) : \n  forall i, getBit (p ## q) i = if i < n2 then getBit q i else getBit p (i-n2).\nProof. induction n2 => // i. \nrewrite (tuple0 q). destruct i => //. \ncase/tupleP: q => [b q] //. destruct i => //. apply IHn2. \nQed. \n\nLemma sliceEq n1 n2 n3 (p q: BITS (n1+n2+n3)) : \n  (forall i, n1 <= i < n1+n2 -> getBit p i = getBit q i) <->\n  slice n1 n2 n3 p = slice n1 n2 n3 q.\nProof. rewrite /slice/split3/split2. \nrewrite <-highBitsEq. split. \nmove => H1 i LE. rewrite 2!getBit_low. \ncase LT: (i < (n1+n2)) => //.\n- apply H1. by rewrite LE LT. \nmove => H i. move/andP => [LE LT]. \nspecialize (H i LE). by rewrite 2!getBit_low LT in H. \nQed. \n\nLemma getUpdateSlice n1 n2 n3 (p: BITS (n1+n2+n3)) (q: BITS n2) :\n  slice n1 n2 n3 (updateSlice _ _ _ p q) = q.\nProof. rewrite /slice/updateSlice/split3/split2.\nby rewrite low_catB high_catB.\nQed.\n\nLemma bitsToBytesK n : cancel (@bitsToBytes n) (@bytesToBits n).\nProof. induction n.\n+ move => x. by rewrite (tuple0 _) (tuple0 x). \n+ move => xs. rewrite /bitsToBytes-/bitsToBytes.\nrewrite /splitAtByte. rewrite (split2eta xs) split2app. \nby rewrite /bytesToBits-/bytesToBits beheadCons theadCons IHn. \nQed. \n\nLemma bytesToBitsK n : cancel (@bytesToBits n) (@bitsToBytes n).\nProof. induction n.\n+ move => x. by rewrite (tuple0 _) (tuple0 x). \n+ move => xs. rewrite /bitsToBytes-/bitsToBytes/splitAtByte. \nrewrite (split2eta (bytesToBits xs)) split2app. \ncase/tupleP: xs => [x xs].\nrewrite /bytesToBits-/bytesToBits beheadCons theadCons. \nby rewrite high_catB IHn low_catB. Qed. \n\n(*---------------------------------------------------------------------------\n    Zero and sign extension\n  ---------------------------------------------------------------------------*)\n\nLemma signExtendK extra n : pcancel (@signExtend extra n) (signTruncate extra).\nProof. move => p. rewrite /signExtend /signTruncate split2app.\ncase: (msb p).\n+ by rewrite /ones eq_refl.\n+ by rewrite /zero eq_refl.\nQed.\n\nLemma signTruncateK extra n p q :\n  signTruncate extra (n:=n) p = Some q ->\n  signExtend extra (n:=n) q = p.\nProof. rewrite /signTruncate/signExtend.\nrewrite (split2eta p) split2app.\ncase P: (_ || _) => // H.\nhave EQ: low n.+1 p = q by congruence. subst.\ncase M: (msb _).\n+ rewrite M andTb andFb orbF in P. by rewrite (eqP P).\n+ rewrite M andTb andFb orFb in P. by rewrite (eqP P).\nQed.\n\nLemma zeroExtendK extra n : pcancel (@zeroExtend extra n) (zeroTruncate extra).\nProof. move => p. by rewrite /zeroExtend/zeroTruncate split2app eq_refl. Qed.\n\nLemma zeroTruncateK extra n p q :\n  zeroTruncate extra (n:=n) p = Some q ->\n  zeroExtend extra (n:=n) q = p.\nProof. rewrite /zeroTruncate/zeroExtend.\nrewrite (split2eta p) split2app.\ncase P: (high extra p == zero extra) => // H.\nhave EQ: low n p = q by congruence. subst.\nby rewrite (eqP P).\nQed.\n\n\n\nLemma toNat_zeroExtend extra n (p: BITS n) : toNat (zeroExtend extra p) = toNat p.\nProof. rewrite /zeroExtend. rewrite toNatCat. by rewrite toNat_zero. Qed.\n\nLemma toNat_zeroExtendAux extra n (p: BITS n) : toNat (zeroExtendAux extra p) = toNat p.\nProof. induction extra => //. by rewrite /= toNat_joinmsb0 IHextra. Qed.\n\nLemma zeroExtend_fromNat extra n m : \n  m < 2^n ->\n  zeroExtend extra (fromNat (n:=n) m) = #m. \nProof. move => LT. \napply toNat_inj. rewrite toNat_zeroExtend. rewrite toNat_fromNatBounded => //. \nrewrite toNat_fromNatBounded => //. \nrewrite expnD. \napply (leq_trans LT). apply leq_pmulr. apply expn_gt0. \nQed.\n\nLemma msbNonNil n (p: BITS n.+1) b : msb p = last b p. \nProof. by case/tupleP: p => b' q. Qed. \n\nLemma splitmsb_msb n (p:BITS n.+1) : (splitmsb p).1 = msb p.\nProof. induction n. \n+ case/tupleP: p => b q. by rewrite (tuple0 q)/= theadCons. \n+ case/tupleP: p => b q. rewrite /= beheadCons theadCons. case E: (splitmsb q) => [b' q'].\nspecialize (IHn q). rewrite E/= in IHn. simpl. rewrite (msbNonNil q b) in IHn. by subst. \nQed. \n\nLemma signExtend_fromNat extra n m : \n  m < 2^n ->\n  signExtend extra (fromNat (n:=n.+1) m) = #m. \nProof. move => LT. \nunfold signExtend. rewrite -splitmsb_msb. \nrewrite splitmsb_fromNat. simpl. \nrewrite divn_small => //. simpl. \nreplace (copy extra false ## (fromNat (n:=n.+1) m)) with (zeroExtend extra (fromNat (n:=n.+1) m)). apply zeroExtend_fromNat. rewrite expnS. \napply: (ltn_trans LT). apply ltn_Pmull => //. apply expn_gt0. \ndone. \nQed. \n\n(*---------------------------------------------------------------------------\n    Properties of equality\n  ---------------------------------------------------------------------------*)\n\nLemma iffBool (b1 b2:bool) : (b1 <-> b2) -> b1==b2.\nProof. destruct b1; destruct b2; intuition. Qed.\n\nLemma bitsEq_nat n {b1 b2: BITS n} :  (b1 == b2) = (toNat b1 == toNat b2).\nProof. suff: b1 == b2 <-> (toNat b1 == toNat b2).\n\nmove => H. assert (H' := iffBool H). apply (eqP H').\nsplit. move => H. rewrite (eqP H). done.\nmove => H. assert (EQ:toNat b1 = toNat b2) by apply (eqP H). by rewrite (toNat_inj EQ).\nQed.\n", "meta": {"author": "coq-community", "repo": "bits", "sha": "acaa1284f7786f488510bbf48ec061c4a9c15716", "save_path": "github-repos/coq/coq-community-bits", "path": "github-repos/coq/coq-community-bits/bits-acaa1284f7786f488510bbf48ec061c4a9c15716/src/spec/spec/properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6553012628906298}}
{"text": "Require Export ZArith.\nRequire Export PosAux.\nRequire Export List.\nRequire Export Bool.\n\nModule Type MAPLIST.\n \n  Parameter t : Type -> Type.\n  Parameter key : Set.  \n  Parameter eq_key : key -> key -> bool.\n  Parameter eq_key_spec :\n      forall k1 k2, if eq_key k1 k2 then k1 = k2 else k1 <> k2.\n\n  Parameter key_dec : forall k1 k2:key, k1=k2 \\/ ~k1=k2. \n\n  Parameter get : forall A:Type, t A -> key -> option A. \n  Parameter update : forall A:Type, t A -> key -> A -> t A.\n\n  Parameter get_update1 : forall A t k v,\n    get A (update A t k v) k = Some v.\n  Parameter get_update2 : forall A t k1 k2 v,\n    k1 <> k2 ->\n    get A (update A t k2 v) k1 = get A t k1.\n\n  Parameter empty : forall (A:Type), t A.\n  Parameter get_empty : forall A k, get A (empty A) k = None.\n\n  Parameter fold : forall (A B:Type), \n   (key->A->B->B) -> t A -> B -> B.\n\n  Parameter dom : forall A, t A -> list key.\n  Parameter in_dom_get_some : forall A m p,\n    In p (dom A m) -> get A m p <> None.\n  Parameter get_some_in_dom : forall A m p,\n    get A m p <> None -> In p (dom A m).\n  Parameter domain_inv : forall A m v p, \n    In p (dom A m) -> dom A (update A m p v) = dom A m.\n\n  Parameter for_all : forall A : Type, (key -> A -> bool) -> t A -> bool.\n  Parameter for_all_true : forall (A : Type) (test:key -> A -> bool) (m : t A),\n    for_all A test m = true -> forall k a, get A m k = Some a -> test k a = true.\n\n  Definition Empty (A:Type) (t:t A) : Prop :=\n    forall k, get A t k = None.\n\n  Implicit Arguments get.\n  Implicit Arguments update.\n  Implicit Arguments empty.\n  Implicit Arguments fold.\n  Implicit Arguments dom.\n  Implicit Arguments Empty.\n\nEnd MAPLIST.\n\nModule MapList_Base <: MAPLIST with Definition key:=N.\n\n  Definition key := N.\n  Definition t A := list (key * A).\n  Definition eq_key := Neq.\n  Lemma eq_key_spec : forall k1 k2, if eq_key k1 k2 then k1 = k2 else k1 <> k2.\n  Proof. exact Neq_spec. Qed.\n\n  Lemma key_dec : forall k1 k2:key, k1=k2 \\/ ~k1=k2.\n  Proof.\n   intros k1 k2;generalize (eq_key_spec k1 k2);destruct (eq_key k1 k2);auto.\n  Qed.\n\n  Fixpoint get (A:Type) (l:t A) (k:key) := \n    match l with\n      | nil => None\n      | h :: t => if Neq k (fst h) then Some (snd h) else get A t k\n    end.\n\n  Fixpoint update (A:Type) (l:t A) (k:N) (v:A) : t A :=\n    match l with\n      | nil => (k, v) :: nil\n      | h :: t => if Neq k (fst h) then (k, v) :: t else h :: (update A t k v)\n    end.\n\n  Lemma get_update1 : forall A t k v,\n    get A (update A t k v) k = Some v.\n  Proof.\n    induction t0; intros.\n    simpl. rewrite Neq_refl. auto.\n    simpl. \n    generalize (Neq_spec k (fst a));destruct (Neq k (fst a)) eqn:Heq; intros.\n    simpl. rewrite Neq_refl; auto.\n    simpl. rewrite Heq. apply IHt0.\n  Qed.\n\n  Lemma get_update2 : forall A t k1 k2 v,\n    k1 <> k2 ->\n    get A (update A t k2 v) k1 = get A t k1.\n  Proof.\n    induction t0; intros.\n    simpl. generalize (Neq_spec k1 k2);destruct (Neq k1 k2) eqn:Heq; intros; auto.\n      contradiction.\n    simpl. \n    generalize (Neq_spec k2 (fst a));destruct (Neq k2 (fst a)) eqn:Heq; intros.\n    simpl.\n    generalize (Neq_spec k1 k2);destruct (Neq k1 k2) eqn:Heq'; intros. contradiction.\n    generalize (Neq_spec k1 (fst a));destruct (Neq k1 (fst a)) eqn:Heq''; intros.\n    rewrite <- H0 in H2; contradiction.\n    auto.\n    simpl.\n    generalize (Neq_spec k1 (fst a));destruct (Neq k1 (fst a)) eqn:Heq''; intros; auto.\n  Qed.\n\n  Definition empty (A:Type) := @nil (key * A).\n  Lemma get_empty : forall A k, get A (empty A) k = None.\n  Proof.\n    unfold empty. auto.\n  Qed.\n\n  Definition fold (A B:Type) (f:key->A->B->B) (l:t A) (acc:B) := \n    fold_right (fun (pa : key * A) (b0 : B) => let (p0, a) := pa in f p0 a b0) acc l.\n\n  Fixpoint dom (A:Type) (l:t A) :=\n    match l with\n      | nil => nil\n      | h :: t => (fst h) :: (dom A t)\n    end.\n\n  Lemma in_dom_get_some_aux : forall A m p, get A m p = None -> ~In p (dom A m).\n  Proof.\n    induction m.\n    unfold not; intros. inversion H0.\n    unfold not; simpl; intros.\n    generalize (Neq_spec (fst a) p); destruct (Neq (fst a) p) eqn:Heq; intros.\n    subst. rewrite Neq_refl in H. inversion H.\n    rewrite Neq_sym in Heq.\n    rewrite Heq in H. apply IHm in H. inversion H0; auto.\n  Qed.\n\n  Lemma in_dom_get_some : forall A m p,\n    In p (dom A m) -> get A m p <> None.\n  Proof.\n    unfold not; intros.\n    apply in_dom_get_some_aux in H0. auto.\n  Qed.\n  \n  Lemma in_dom_get_some' : forall A m p,\n    In p (dom A m) -> exists v, get A m p = Some v.\n  Proof.\n    intros. apply in_dom_get_some in H.\n    destruct (get A m p). exists a; auto.\n      apply False_ind; auto.\n  Qed.\n\n  Lemma get_some_in_dom' : forall A m p v,\n    get A m p = Some v -> In p (dom A m).\n  Proof.\n    induction m.\n    intros. inversion H.\n    intros. inversion H.\n    destruct (Neq p (fst a)) eqn:Heq.\n    left. generalize (Neq_spec p (fst a)). rewrite Heq; intros; subst; auto.\n    right; apply IHm with (v:=v); auto.\n  Qed.\n\n  Lemma get_some_in_dom : forall A m p,\n    get A m p <> None -> In p (dom A m).\n  Proof.\n    intros.\n    assert (exists v, get A m p = Some v). destruct (get A m p). exists a; auto.\n      apply False_ind; auto.\n    destruct H0. apply get_some_in_dom' in H0; auto.\n  Qed.\n\n  Lemma domain_inv : forall A m v p, \n    In p (dom A m) -> dom A (update A m p v) = dom A m.\n  Proof.\n    induction m; intros.\n    inversion H.\n    simpl.\n    generalize (Neq_spec (fst a) p); destruct (Neq (fst a) p) eqn:Heq; intros.\n    subst. rewrite Neq_refl; auto.\n    inversion H. contradiction.\n    rewrite Neq_sym in Heq; rewrite Heq. simpl.\n    apply IHm with (v:=v) in H1; rewrite H1; auto.\n  Qed.\n\n  Fixpoint for_all (A:Type) (f:key -> A -> bool) (l:t A) := \n    match l with\n      | nil => true\n      | (k, v) :: l' => (f k v) && (for_all A f l')\n    end.\n\n  Lemma for_all_true : forall (A : Type) (test:key -> A -> bool) (m : t A),\n    for_all A test m = true -> forall k a, get A m k = Some a -> test k a = true.\n  Proof.\n    induction m; simpl; intros.\n    inversion H0. destruct a.\n    elim (andb_prop _ _ H); intros; auto.\n    simpl in H0.\n    generalize (Neq_spec k k0); destruct (Neq k k0) eqn:Heq; intros. \n    inversion H0. subst. auto.\n    apply IHm; auto.\n  Qed.\n\n  Definition Empty (A:Type) (t:t A) : Prop :=\n    forall k, get A t k = None.\n\n  Implicit Arguments get.\n  Implicit Arguments update.\n  Implicit Arguments empty.\n  Implicit Arguments fold.\n  Implicit Arguments dom.\n  Implicit Arguments for_all.\n\nEnd MapList_Base.\n\nModule MapList <: MAPLIST  with Definition key := N := MapList_Base.", "meta": {"author": "h3nd24", "repo": "DEX_formalization", "sha": "8f56f3ee473701aa70ad7621355481dc8df0d1b4", "save_path": "github-repos/coq/h3nd24-DEX_formalization", "path": "github-repos/coq/h3nd24-DEX_formalization/DEX_formalization-8f56f3ee473701aa70ad7621355481dc8df0d1b4/DEX_O/MapList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.6553012586296193}}
{"text": "Require Import Crypto.Util.Relations Crypto.Util.Tactics Crypto.Util.Notations.\nRequire Import Coq.Classes.RelationClasses Coq.Classes.Morphisms.\nRequire Import Crypto.Algebra Crypto.Algebra.Ring Crypto.Algebra.IntegralDomain.\nRequire Coq.setoid_ring.Field_theory.\n\nSection Field.\n  Context {T eq zero one opp add mul sub inv div} `{@field T eq zero one opp add sub mul inv div}.\n  Local Infix \"=\" := eq : type_scope. Local Notation \"a <> b\" := (not (a = b)) : type_scope.\n  Local Notation \"0\" := zero. Local Notation \"1\" := one.\n  Local Infix \"+\" := add. Local Infix \"*\" := mul.\n\n  Lemma right_multiplicative_inverse : forall x : T, ~ eq x zero -> eq (mul x (inv x)) one.\n  Proof.\n    intros. rewrite commutative. auto using left_multiplicative_inverse.\n  Qed.\n\n  Lemma left_inv_unique x ix : ix * x = one -> ix = inv x.\n  Proof.\n    intro Hix.\n    assert (ix*x*inv x = inv x).\n    - rewrite Hix, left_identity; reflexivity.\n    - rewrite <-associative, right_multiplicative_inverse, right_identity in H0; trivial.\n      intro eq_x_0. rewrite eq_x_0, Ring.mul_0_r in Hix.\n      apply (zero_neq_one(eq:=eq)). assumption.\n  Qed.\n  Definition inv_unique := left_inv_unique.\n\n  Lemma right_inv_unique x ix : x * ix = one -> ix = inv x.\n  Proof. rewrite commutative. apply left_inv_unique. Qed.\n\n  Lemma div_one x : div x one = x.\n  Proof.\n    rewrite field_div_definition.\n    rewrite <-(inv_unique 1 1); apply monoid_is_right_identity.\n  Qed.\n\n  Lemma mul_cancel_l_iff : forall x y, y <> 0 ->\n                                       (x * y = y <-> x = one).\n  Proof.\n    intros.\n    split; intros.\n    + rewrite <-(right_multiplicative_inverse y) by assumption.\n      rewrite <-H1 at 1; rewrite <-associative.\n      rewrite right_multiplicative_inverse by assumption.\n      rewrite right_identity.\n      reflexivity.\n    + rewrite H1; apply left_identity.\n  Qed.\n\n  Lemma field_theory_for_stdlib_tactic : Field_theory.field_theory 0 1 add mul sub opp div inv eq.\n  Proof.\n    constructor.\n    { apply Ring.ring_theory_for_stdlib_tactic. }\n    { intro H01. symmetry in H01. auto using (zero_neq_one(eq:=eq)). }\n    { apply field_div_definition. }\n    { apply left_multiplicative_inverse. }\n  Qed.\n\n  Context {eq_dec:DecidableRel eq}.\n\n  Global Instance is_mul_nonzero_nonzero : @is_zero_product_zero_factor T eq 0 mul.\n  Proof.\n    split. intros x y Hxy.\n    eapply not_not; try typeclasses eauto; []; intuition idtac; eapply (zero_neq_one(eq:=eq)).\n    transitivity ((inv y * (inv x * x)) * y).\n    - rewrite <-!associative, Hxy, !Ring.mul_0_r; reflexivity.\n    - rewrite left_multiplicative_inverse, right_identity, left_multiplicative_inverse by trivial.\n      reflexivity.\n  Qed.\n\n  Global Instance integral_domain : @integral_domain T eq zero one opp add sub mul.\n  Proof.\n    split; auto using field_commutative_ring, field_is_zero_neq_one, is_mul_nonzero_nonzero.\n  Qed.\nEnd Field.\n\nLemma isomorphism_to_subfield_field\n      {T EQ ZERO ONE OPP ADD SUB MUL INV DIV}\n      {Equivalence_EQ: @Equivalence T EQ}\n      {Proper_OPP:Proper(EQ==>EQ)OPP}\n      {Proper_ADD:Proper(EQ==>EQ==>EQ)ADD}\n      {Proper_SUB:Proper(EQ==>EQ==>EQ)SUB}\n      {Proper_MUL:Proper(EQ==>EQ==>EQ)MUL}\n      {Proper_INV:Proper(EQ==>EQ)INV}\n      {Proper_DIV:Proper(EQ==>EQ==>EQ)DIV}\n      {R eq zero one opp add sub mul inv div} {fieldR:@field R eq zero one opp add sub mul inv div}\n      {phi}\n      {eq_phi_EQ: forall x y, eq (phi x) (phi y) -> EQ x y}\n      {neq_zero_one : (not (EQ ZERO ONE))}\n      {phi_opp : forall a, eq (phi (OPP a)) (opp (phi a))}\n      {phi_add : forall a b, eq (phi (ADD a b)) (add (phi a) (phi b))}\n      {phi_sub : forall a b, eq (phi (SUB a b)) (sub (phi a) (phi b))}\n      {phi_mul : forall a b, eq (phi (MUL a b)) (mul (phi a) (phi b))}\n      {phi_inv : forall a, eq (phi (INV a)) (inv (phi a))}\n      {phi_div : forall a b, eq (phi (DIV a b)) (div (phi a) (phi b))}\n      {phi_zero : eq (phi ZERO) zero}\n      {phi_one : eq (phi ONE) one}\n  : @field T EQ ZERO ONE OPP ADD SUB MUL INV DIV.\nAdmitted. (* TODO: remove all uses of this theorem *)\n\nLemma equivalent_operations_field\n      {T EQ ZERO ONE OPP ADD SUB MUL INV DIV}\n      {EQ_equivalence : Equivalence EQ}\n      {zero one opp add sub mul inv div}\n      {fieldR:@field T EQ zero one opp add sub mul inv div}\n      {EQ_opp : forall a, EQ (OPP a) (opp a)}\n      {EQ_inv : forall a, EQ (INV a) (inv a)}\n      {EQ_add : forall a b, EQ (ADD a b) (add a b)}\n      {EQ_sub : forall a b, EQ (SUB a b) (sub a b)}\n      {EQ_mul : forall a b, EQ (MUL a b) (mul a b)}\n      {EQ_div : forall a b, EQ (DIV a b) (div a b)}\n      {EQ_zero : EQ ZERO zero}\n      {EQ_one : EQ ONE one}\n  : @field T EQ ZERO ONE OPP ADD SUB MUL INV DIV.\nProof. Admitted. (* TODO: remove all uses of this theorem *)\n\nSection Homomorphism.\n  Context {F EQ ZERO ONE OPP ADD MUL SUB INV DIV} `{@field F EQ ZERO ONE OPP ADD SUB MUL INV DIV}.\n  Context {K eq zero one opp add mul sub inv div} `{@field K eq zero one opp add sub mul inv div}.\n  Context {phi:F->K}.\n  Local Infix \"=\" := eq. Local Infix \"=\" := eq : type_scope.\n  Context `{@Ring.is_homomorphism F EQ ONE ADD MUL K eq one add mul phi}.\n\n  Lemma homomorphism_multiplicative_inverse\n    : forall x, not (EQ x ZERO)\n                -> phi (INV x) = inv (phi x).\n  Proof.\n    intros.\n    eapply inv_unique.\n    rewrite <-Ring.homomorphism_mul.\n    rewrite left_multiplicative_inverse; auto using Ring.homomorphism_one.\n  Qed.\n\n  Lemma homomorphism_multiplicative_inverse_complete\n        { EQ_dec : DecidableRel EQ }\n    : forall x, (EQ x ZERO -> phi (INV x) = inv (phi x))\n                -> phi (INV x) = inv (phi x).\n  Proof.\n    intros x ?; destruct (dec (EQ x ZERO)); auto using homomorphism_multiplicative_inverse.\n  Qed.\n\n  Lemma homomorphism_div\n    : forall x y, not (EQ y ZERO)\n                  -> phi (DIV x y) = div (phi x) (phi y).\n  Proof.\n    intros. rewrite !field_div_definition.\n    rewrite Ring.homomorphism_mul, homomorphism_multiplicative_inverse;\n      (eauto || reflexivity).\n  Qed.\n\n  Lemma homomorphism_div_complete\n        { EQ_dec : DecidableRel EQ }\n    : forall x y, (EQ y ZERO -> phi (INV y) = inv (phi y))\n                  -> phi (DIV x y) = div (phi x) (phi y).\n  Proof.\n    intros. rewrite !field_div_definition.\n    rewrite Ring.homomorphism_mul, homomorphism_multiplicative_inverse_complete;\n      (eauto || reflexivity).\n  Qed.\nEnd Homomorphism.\n\nSection Homomorphism_rev.\n  Context {F EQ ZERO ONE OPP ADD SUB MUL INV DIV} {fieldF:@field F EQ ZERO ONE OPP ADD SUB MUL INV DIV}.\n  Context {H} {eq : H -> H -> Prop} {zero one : H} {opp : H -> H} {add sub mul : H -> H -> H} {inv : H -> H} {div : H -> H -> H}.\n  Context {phi:F->H} {phi':H->F}.\n  Local Infix \"=\" := EQ. Local Infix \"=\" := EQ : type_scope.\n  Context (phi'_phi_id : forall A, phi' (phi A) = A)\n          (phi'_eq : forall a b, EQ (phi' a) (phi' b) <-> eq a b)\n          {phi'_zero : phi' zero = ZERO}\n          {phi'_one : phi' one = ONE}\n          {phi'_opp : forall a, phi' (opp a) = OPP (phi' a)}\n          (phi'_add : forall a b, phi' (add a b) = ADD (phi' a) (phi' b))\n          (phi'_sub : forall a b, phi' (sub a b) = SUB (phi' a) (phi' b))\n          (phi'_mul : forall a b, phi' (mul a b) = MUL (phi' a) (phi' b))\n          {phi'_inv : forall a, phi' (inv a) = INV (phi' a)}\n          (phi'_div : forall a b, phi' (div a b) = DIV (phi' a) (phi' b)).\n\n  Lemma field_and_homomorphism_from_redundant_representation\n    : @field H eq zero one opp add sub mul inv div\n      /\\ @Ring.is_homomorphism F EQ ONE ADD MUL H eq one add mul phi\n      /\\ @Ring.is_homomorphism H eq one add mul F EQ ONE ADD MUL phi'.\n  Proof.\n    repeat match goal with\n           | [ H : field |- _ ] => destruct H; try clear H\n           | [ H : commutative_ring |- _ ] => destruct H; try clear H\n           | [ H : ring |- _ ] => destruct H; try clear H\n           | [ H : abelian_group |- _ ] => destruct H; try clear H\n           | [ H : group |- _ ] => destruct H; try clear H\n           | [ H : monoid |- _ ] => destruct H; try clear H\n           | [ H : is_commutative |- _ ] => destruct H; try clear H\n           | [ H : is_left_multiplicative_inverse |- _ ] => destruct H; try clear H\n           | [ H : is_left_distributive |- _ ] => destruct H; try clear H\n           | [ H : is_right_distributive |- _ ] => destruct H; try clear H\n           | [ H : is_zero_neq_one |- _ ] => destruct H; try clear H\n           | [ H : is_associative |- _ ] => destruct H; try clear H\n           | [ H : is_left_identity |- _ ] => destruct H; try clear H\n           | [ H : is_right_identity |- _ ] => destruct H; try clear H\n           | [ H : Equivalence _ |- _ ] => destruct H; try clear H\n           | [ H : is_left_inverse |- _ ] => destruct H; try clear H\n           | [ H : is_right_inverse |- _ ] => destruct H; try clear H\n           | _ => intro\n           | _ => split\n           | [ H : eq _ _ |- _ ] => apply phi'_eq in H\n           | [ |- eq _ _ ] => apply phi'_eq\n           | [ H : (~eq _ _)%type |- _ ] => pose proof (fun pf => H (proj1 (@phi'_eq _ _) pf)); clear H\n           | [ H : EQ _ _ |- _ ] => rewrite H\n           | _ => progress erewrite ?phi'_zero, ?phi'_one, ?phi'_opp, ?phi'_add, ?phi'_sub, ?phi'_mul, ?phi'_inv, ?phi'_div, ?phi'_phi_id by reflexivity\n           | [ H : _ |- _ ] => progress erewrite ?phi'_zero, ?phi'_one, ?phi'_opp, ?phi'_add, ?phi'_sub, ?phi'_mul, ?phi'_inv, ?phi'_div, ?phi'_phi_id in H by reflexivity\n           | _ => solve [ eauto ]\n           end.\n  Qed.\nEnd Homomorphism_rev.\n\nLtac guess_field :=\n  match goal with\n  | |- ?eq _ _ =>  constr:(_:Algebra.field (eq:=eq))\n  | |- not (?eq _ _) =>  constr:(_:Algebra.field (eq:=eq))\n  | [H: ?eq _ _ |- _ ] =>  constr:(_:Algebra.field (eq:=eq))\n  | [H: not (?eq _ _) |- _] =>  constr:(_:Algebra.field (eq:=eq))\n  end.\n\nLtac goal_to_field_equality fld :=\n  let eq := match type of fld with Algebra.field(eq:=?eq) => eq end in\n  match goal with\n  | [ |- eq _ _] => idtac\n  | [ |- not (eq ?x ?y) ] => apply not_exfalso; intro; goal_to_field_equality fld\n  | _ => exfalso;\n         match goal with\n         | H: not (eq _ _) |- _ => apply not_exfalso in H; apply H\n         | _ => apply (field_is_zero_neq_one(field:=fld))\n         end\n  end.\n\nLtac inequalities_to_inverse_equations fld :=\n  let eq := match type of fld with Algebra.field(eq:=?eq) => eq end in\n  let zero := match type of fld with Algebra.field(zero:=?zero) => zero end in\n  let div := match type of fld with Algebra.field(div:=?div) => div end in\n  let sub := match type of fld with Algebra.field(sub:=?sub) => sub end in\n  repeat match goal with\n         | [H: not (eq _ _) |- _ ] =>\n           lazymatch type of H with\n           | not (eq ?d zero) =>\n             unique pose proof (right_multiplicative_inverse(H:=fld) _ H)\n           | not (eq zero ?d) =>\n             unique pose proof (right_multiplicative_inverse(H:=fld) _ (symmetry(R:=fun a b => not (eq a b)) H))\n           | not (eq ?x ?y) => \n             unique pose proof (right_multiplicative_inverse(H:=fld) _ (Ring.neq_sub_neq_zero _ _ H))\n           end\n         end.\n\nLtac unique_pose_implication pf :=\n  let B := match type of pf with ?A -> ?B => B end in\n  match goal with\n             | [H:B|-_] => fail 1\n             | _ => unique pose proof pf\n  end.\n\nLtac inverses_to_conditional_equations fld :=\n  let eq := match type of fld with Algebra.field(eq:=?eq) => eq end in\n  let inv := match type of fld with Algebra.field(inv:=?inv) => inv end in\n  repeat match goal with\n         | |- context[inv ?d] =>\n           unique_pose_implication constr:(right_multiplicative_inverse(H:=fld) d)\n         | H: context[inv ?d] |- _ => \n           unique_pose_implication constr:(right_multiplicative_inverse(H:=fld) d)\n         end.\n\nLtac clear_hypotheses_with_nonzero_requirements fld :=\n  let eq := match type of fld with Algebra.field(eq:=?eq) => eq end in\n  let zero := match type of fld with Algebra.field(zero:=?zero) => zero end in\n  repeat match goal with\n           [H: not (eq _ zero) -> _ |- _ ] => clear H\n         end.\n\nLtac forward_nonzero fld solver_tac :=\n  let eq := match type of fld with Algebra.field(eq:=?eq) => eq end in\n  let zero := match type of fld with Algebra.field(zero:=?zero) => zero end in\n  repeat match goal with\n         | [H: not (eq ?x zero) -> _ |- _ ]\n           => let H' := fresh in\n              assert (H' : not (eq x zero)) by (clear_hypotheses_with_nonzero_requirements; solver_tac); specialize (H H')\n         | [H: not (eq ?x zero) -> _ |- _ ]\n           => let H' := fresh in\n              assert (H' : not (eq x zero)) by (clear H; solver_tac); specialize (H H')\n         end.\n\nLtac divisions_to_inverses fld :=\n  rewrite ?(field_div_definition(field:=fld)) in *.\n\nLtac fsatz_solve_on fld :=\n  goal_to_field_equality fld;\n  forward_nonzero fld ltac:(fsatz_solve_on fld);\n  nsatz;\n  solve_debugfail ltac:(IntegralDomain.solve_constant_nonzero).\n\nLtac fsatz_solve :=\n  let fld := guess_field in\n  fsatz_solve_on fld.\n\nLtac fsatz_prepare_hyps_on fld :=\n  divisions_to_inverses fld;\n  inequalities_to_inverse_equations fld;\n  inverses_to_conditional_equations fld;\n  forward_nonzero fld ltac:(fsatz_solve_on fld).\n\nLtac fsatz_prepare_hyps :=\n  let fld := guess_field in\n  fsatz_prepare_hyps_on fld.\n\nLtac fsatz :=\n  let fld := guess_field in\n  fsatz_prepare_hyps_on fld;\n  fsatz_solve_on fld.\n\n\nSection FieldSquareRoot.\n  Context {T eq zero one opp add mul sub inv div} `{@field T eq zero one opp add sub mul inv div} {eq_dec:DecidableRel eq}.\n  Local Infix \"=\" := eq : type_scope. Local Notation \"a <> b\" := (not (a = b)) : type_scope.\n  Local Infix \"+\" := add. Local Infix \"*\" := mul.\n  Lemma only_two_square_roots_choice x y z : x * x = z -> y * y = z -> x = y \\/ x = opp y.\n  Proof.\n    intros.\n    setoid_rewrite <-sub_zero_iff.\n    eapply zero_product_zero_factor.\n    fsatz.\n  Qed.\nEnd FieldSquareRoot.", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_crypto_defined/src/Algebra/Field.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.6552529693264376}}
{"text": "Require Import Classical.\nRequire Import List.\nRequire Import Arith.\n\nRequire Import Ranked_properties.\nRequire Import SF_spec.\nRequire Import SF_tactic.\nRequire Import SF_properties.\n\n(**  The formal specification given in SF_spec always chooses exactly one loser at each\n     round; the choice is nondeterministic in the case of ties.  However, the statute\n     text and actual election practice is to implement the following optimization:\n\n         In a given round, choose the largest set of losers such that the combined sum\n         of continuing votes for all losing candidates is less than the continuing votes\n         for all other candidates.  Simultaneously eliminate all losing candidates in this set.\n\n     Here we prove that this procedure is indeed just an optimization of the simple procedure\n     that chooses exactly one loser at each round.  Actually, we prove something slightly more\n     general, which is that one may chose _any_ set satisfying the condition above and the\n     result is unchanged (i.e., prefering the largest such set makes no difference in the end).\n  *)\n\nLemma first_choice_loser_set :\n  forall (candidate:Set) e c cs elim x y,\n    In c cs ->\n    count_votes candidate (fun b => exists c, selected_candidate _ elim b c /\\ In c cs) e x ->\n    first_choices _ elim c e y ->\n    y <= x.\nProof.\n  intros candidate e. induction e; simpl; intros.\n  * inv H0. inv H1. auto.\n  * inv H0; inv H1; auto.\n    cut (n' <= n). omega.\n    eapply IHe; eauto.\n    cut (y <= n). omega.\n    eapply IHe; eauto.\n    elim H4.\n    exists c. split; auto.\n    eapply IHe; eauto.\nQed.\n\nLemma count_votes_total candidates P e :\n  exists c, count_votes candidates P e c.\nProof.\n  induction e.\n  * exists 0. constructor.\n  * destruct IHe as [n ?].\n    destruct (classic (P a)).\n    exists (S n).\n    apply count_satisfies; auto.\n    exists n.\n    apply count_not_satisfies; auto.\nQed.\n\nLemma count_votes_monotone candidates (P P':ballot candidates -> Prop) e x y :\n  (forall b, P b -> P' b) ->\n  count_votes candidates P e x ->\n  count_votes candidates P' e y ->\n  x <= y.\nProof.\n  intros. revert x y H0 H1. induction e; intros.\n  * inv H0. inv H1. auto.\n  * inv H0; inv H1; auto.\n    cut ( n <= n0 ). omega.\n    apply IHe; auto.\n    elim H3. apply H. auto.\nQed.\n\nLemma majority_unique :\n  forall candidate r e x x',\n    SF_spec.majority candidate r e x ->\n    SF_spec.majority candidate r e x' ->\n    x = x'.\nProof.\n  intros.\n  destruct (classic (x = x')); auto. elimtype False.\n  destruct (SF_spec.total_selected_total candidate r e) as [t ?].\n  destruct (SF_spec.sf_first_choices_total candidate r e x) as [n ?].\n  destruct (SF_spec.sf_first_choices_total candidate r e x') as [n' ?].\n  generalize (H t n H2 H3); intro.\n  generalize (H0 t n' H2 H4); intro.\n  assert ( n + n' <= t ).\n  { clear H H0 H5 H6.\n    revert t n n' H2 H3 H4.\n    induction e; simpl; intros.\n    inv H2. inv H3. inv H4. auto.\n    inv H2. inv H3. inv H4.\n    elim H1.\n    eapply selected_candidate_unique; eauto.\n    cut (n'0 + n' <= n0). omega.\n    apply IHe; eauto.\n    inv H4.\n    cut (n + n'0 <= n0). omega.\n    apply IHe; eauto.\n    cut (n + n' <= n0). omega.\n    apply IHe; eauto.\n    inv H3.\n    rewrite exhausted_ballot_next_ranking_iff in H5.\n    destruct H2.\n    destruct H0 as [q [??]].\n    elim H.\n    right. exists q. split; auto.\n    inv H4.\n    rewrite exhausted_ballot_next_ranking_iff in H5.\n    destruct H3.\n    destruct H0 as [q [??]].\n    elim H.\n    right. exists q. split; auto.\n    apply IHe; auto.\n  }\n  omega.\nQed.\n\nLemma exhausted_ballot_monotone :\n  forall (candidate:Set) (elim elim':candidate -> Prop) b,\n    (forall x, (exists r, In r b /\\ In x r) -> elim x -> elim' x) ->\n    SF_spec.exhausted_ballot candidate elim b ->\n    SF_spec.exhausted_ballot candidate elim' b.\nProof.\n  unfold exhausted_ballot. intuition.\n  left. intros [r ?].\n  induction H0.\n  destruct (classic (Forall elim r')).\n  apply IHnext_ranking.\n  intros.\n  apply (H x); auto.\n  { destruct H5 as [r0 [??]]. exists r0. split; simpl; auto. }\n  intro.\n  apply H1.\n  destruct H5 as [r0 ?].\n  exists r0.\n  apply SF_spec.next_ranking_eliminated; auto.\n  elim H1.\n  exists r'.\n  destruct r'.\n  elim H4.\n  rewrite Forall_forall.\n  simpl; intuition.\n  apply SF_spec.next_ranking_valid with c; simpl; auto.\n  right.\n  intro.\n  apply H4.\n  rewrite Forall_forall; intros.\n  destruct (classic (x = c)).\n  subst x; auto.\n  elim H2.\n  exists x. exists c.\n  simpl; intuition.\n  apply H1. exists r.\n  apply SF_spec.next_ranking_valid with c; auto.\n  intuition.\n  right. intro.\n  apply H3; auto.\n  apply H; auto.\n  exists r; split; simpl; auto. \n  destruct H1 as [r [??]].\n  right. exists r. split; auto.\n  induction H0.\n  apply SF_spec.next_ranking_eliminated; auto.\n  rewrite Forall_forall. intros.\n  apply H.\n  exists r'; split; simpl; auto.\n  rewrite Forall_forall in H0; auto.\n  apply IHnext_ranking.\n  intros. apply H; auto.\n  destruct H4 as [r0 [??]].\n  exists r0; split; simpl; auto.\n  auto.\n  apply SF_spec.next_ranking_valid with c; auto.\nQed.\n\nLemma total_selected_elim_eq :\n  forall candidate elim elim' e n,\n    (forall x, participates _ x e -> (elim x <-> elim' x)) ->\n    SF_spec.total_selected candidate elim e n ->\n    SF_spec.total_selected candidate elim' e n.\nProof.\n  intros.\n  induction H0.\n  * apply total_nil.\n  * apply total_continuing; auto.\n    intro. apply H0.\n    eapply exhausted_ballot_monotone. 2: eauto.\n    intros. rewrite H; auto.\n    hnf; simpl; eauto.\n    apply IHtotal_selected.\n    intros. apply H.\n    destruct H2 as [q [??]].\n    exists q; split; simpl; auto.\n  * apply total_exhausted; auto.\n    eapply exhausted_ballot_monotone. 2: eauto.\n    intros. rewrite <- H; auto.\n    hnf; simpl; eauto.\n    apply IHtotal_selected.\n    intros. apply H.\n    destruct H2 as [q [??]].\n    hnf; simpl; eauto.\nQed.\n\nLemma next_ranking_elim_eq :\n  forall candidate elim elim' b r,\n    (forall x, (exists r, In r b /\\ In x r) -> (elim x <-> elim' x)) ->\n    SF_spec.next_ranking candidate elim b r ->\n    SF_spec.next_ranking candidate elim' b r.\nProof.\n  intros. induction H0.\n  * apply next_ranking_eliminated; auto.\n    rewrite Forall_forall; intros.\n    rewrite <- H.\n    rewrite Forall_forall in H0. auto.\n    simpl; eauto.\n    apply IHnext_ranking; auto.\n    intros.\n    apply H.\n    destruct H3 as [r0 [??]].\n    simpl; eauto.\n  * apply next_ranking_valid with c; intuition.\n    right.\n    rewrite <- H. auto.\n    simpl; eauto.\nQed.\n\n\nLemma selected_candidate_elim_eq :\n  forall candidate elim elim' b c,\n    (forall x, (exists r, In r b /\\ In x r) -> (elim x <-> elim' x)) ->\n    SF_spec.selected_candidate candidate elim b c ->\n    SF_spec.selected_candidate candidate elim' b c.\nProof.\n  intros.\n  destruct H0; split.\n  intro. apply H0.\n  eapply exhausted_ballot_monotone. 2: eauto.\n  intuition. rewrite H; auto.\n  destruct H1 as [r [??]].\n  exists r; split; auto.\n  eapply next_ranking_elim_eq. 2: eauto.\n  auto.\nQed.\n\nLemma first_choices_elim_eq :\n  forall candidate elim elim' e c n,\n    (forall x, SF_spec.participates _ x e -> (elim x <-> elim' x)) ->\n    SF_spec.first_choices candidate elim c e n ->\n    SF_spec.first_choices candidate elim' c e n.\nProof.\n  intros.\n  induction H0.\n  * apply first_choices_nil.\n  * apply first_choices_selected; auto.\n    eapply selected_candidate_elim_eq. 2: eauto.\n    intros; apply H.\n    hnf; simpl; eauto.\n    apply IHfirst_choices.\n    intros. apply H.\n    destruct H2 as [q [??]].\n    exists q; simpl; eauto.\n  * eapply first_choices_not_selected; auto.\n    intro. apply H0.\n    eapply selected_candidate_elim_eq. 2: eauto.\n    intros. rewrite H; intuition.\n    hnf; simpl; eauto.\n    apply IHfirst_choices.\n    intros; apply H.\n    destruct H2 as [q [??]].\n    exists q; simpl; eauto.\nQed.\n\nLemma majority_elim_eq :\n  forall candidate elim elim' e c,\n    (forall x, SF_spec.participates _ x e -> (elim x <-> elim' x)) ->\n    SF_spec.majority candidate elim e c ->\n    SF_spec.majority candidate elim' e c.\nProof.\n  intros; hnf; intros.\n  apply H0; auto.\n  eapply total_selected_elim_eq; eauto.\n  intros. rewrite H; auto.\n  intuition.\n  eapply first_choices_elim_eq; eauto.\n  intros. rewrite H; auto.\n  intuition.\nQed.\n\nLemma is_loser_elim_eq :\n  forall candidate elim elim' e c,\n    (forall x, SF_spec.participates _ x e -> (elim x <-> elim' x)) ->\n    SF_spec.is_loser candidate elim e c ->\n    SF_spec.is_loser candidate elim' e c.\nProof.\n  repeat intro.\n  destruct H0. split.\n  destruct H0. split; auto.\n  rewrite <- H; auto.\n  intros.\n  eapply H1.\n  2: eapply first_choices_elim_eq. 3: eauto.\n  3: eapply first_choices_elim_eq. 4: eauto.\n  destruct H2; split; auto.\n  rewrite H; auto.\n  intro. symmetry. auto.\n  intro. symmetry. auto.\nQed.\n\nLemma winner_elim_eq :\n  forall candidate elim elim' e c,\n    (forall x, SF_spec.participates _ x e -> (elim x <-> elim' x)) ->\n    SF_spec.winner candidate e elim c ->\n    SF_spec.winner candidate e elim' c.\nProof.\n  intros.\n  revert elim' H.\n  induction H0; intros.\n  * apply winner_now.\n    eapply majority_elim_eq; eauto.\n  * apply winner_elimination with loser; auto.\n    red; intros [c ?].\n    apply H. exists c.\n    eapply majority_elim_eq; eauto.\n    intro. intro.\n    rewrite H2; intuition.\n    eapply is_loser_elim_eq; eauto.\n    apply IHwinner.\n    unfold eliminated'.\n    unfold update_eliminated.\n    intuition.\n    rewrite H2 in H5; auto.\n    rewrite H2; auto.\nQed.\n\nLemma disjoint_first_choices :\n  forall (candidate:Set) (eliminated:candidate -> Prop) e c1 c2 n1 n2 t,\n    c1 <> c2 ->\n    first_choices _ eliminated c1 e n1 ->\n    first_choices _ eliminated c2 e n2 ->\n    total_selected _ eliminated e t ->\n    n1 + n2 <= t.\nProof.\n  intros until e. induction e; intros.\n  * inv H0. inv H1. inv H2. omega.\n  * inv H2. inv H0; inv H1.\n    + elim H. eapply selected_candidate_unique; eauto.\n    + cut (n' + n2 <= n). omega.\n      eapply IHe; eauto.\n    + cut (n1 + n' <= n). omega.\n      eapply IHe; eauto.\n    + cut (n1 + n2 <= n). omega.\n      eapply IHe; eauto.\n    + eapply IHe; eauto.\n      inv H0; auto.\n      destruct H4. elim H0; auto.\n      inv H1; auto.\n      destruct H4. elim H1; auto.\nQed.\n\n\nSection sf_spec_opt.\n  Variable candidate : Set.\n  Variable e : election candidate.\n  Variable losers : list candidate.\n  Variable loserCount : nat.\n\n  Variables eliminated eliminated':candidate -> Prop.\n\n  Hypothesis Hdups : NoDup losers.\n\n  Hypothesis Hcount : count_votes _ (fun b => exists c, SF_spec.selected_candidate _ eliminated b c /\\ In c losers) e loserCount.\n  Hypothesis Hviable : forall l, In l losers -> viable_candidate _ eliminated e l.\n  Hypothesis Hnonloser : exists c, ~In c losers /\\ SF_spec.viable_candidate _ eliminated e c.\n  Hypothesis Hdominated :\n      forall c count,\n         ~In c losers ->\n         SF_spec.viable_candidate _ eliminated e c ->\n         SF_spec.first_choices _ eliminated c e count ->\n         loserCount < count.\n  Hypothesis Helim_eq :\n      forall x, eliminated' x <-> eliminated x \\/ In x losers.\n\n  Lemma sf_opt_loser_in_set :\n    forall\n      (loser : candidate),\n      length losers > 0 ->\n      is_loser candidate eliminated e loser ->\n      In loser losers.\n  Proof.\n    intros.\n    destruct (classic (In loser losers)); auto. elimtype False.\n    destruct (SF_spec.sf_first_choices_total _ eliminated e loser) as [lCount HlCount].\n    assert (loserCount < lCount).\n    apply Hdominated with loser; auto.\n    destruct H0; auto.\n    destruct losers.\n    simpl in H. omega.\n    destruct H0.\n    destruct (SF_spec.sf_first_choices_total _ eliminated e c) as [cn Hcn].\n    assert( lCount <= loserCount ).\n    transitivity cn.\n    apply H3 with c; auto.\n    apply Hviable. simpl; auto.\n    eapply first_choice_loser_set; eauto. simpl; auto.\n    simpl in H2.\n    omega.\n  Qed.\n\n  Lemma sf_opt_inductive_step :\n    forall\n      (loser : candidate)\n      (losers' : list candidate),\n\n      is_loser candidate eliminated e loser ->\n      (forall x0 : candidate, In x0 losers <-> x0 = loser \\/ In x0 losers') ->\n\n      forall (c : candidate) (count : nat),\n        ~ In c losers' ->\n        viable_candidate candidate (update_eliminated candidate eliminated loser) e c ->\n        first_choices candidate (update_eliminated candidate eliminated loser) c e count ->\n        loserCount < count.\n   Proof.\n     intros.\n     destruct (SF_spec.sf_first_choices_total _ eliminated e c) as [count0 ?].\n     destruct (SF_spec.sf_first_choices_total _ eliminated e loser) as [lCount HlCount].\n     assert ( count0 > 0 \\/ (lCount = 0 /\\ count0 = 0) ).\n     { destruct count0. auto.\n       cut ( lCount <= 0 ). omega.\n       destruct H.\n       apply H5 with c; auto.\n       destruct H2; split; auto.\n       intro. apply H2; hnf; auto.\n       left. omega.\n     }\n     destruct H5.\n     apply lt_le_trans with count0; auto.\n     apply (Hdominated c count0); auto.\n     intro.\n     rewrite H0 in H6.\n     destruct H6; auto.\n     { subst c. destruct H2. elim H2; hnf; auto. }\n     { destruct H2; split; auto.\n       intro. apply H2; hnf; auto. }\n     apply first_choices_monotone with candidate eliminated (SF_spec.update_eliminated _ eliminated loser) e c; auto.\n     unfold update_eliminated; simpl; auto.\n     { intros [?|?].\n       destruct H2.\n       elim H2; hnf; simpl; auto.\n       subst c.\n       destruct H2. elim H2; hnf; auto.\n     }\n     unfold update_eliminated; simpl; auto.\n     destruct H5. subst.\n     destruct (classic (In c losers)).\n     rewrite H0 in H5.\n     destruct H5. 2: elim H1; auto.\n     subst c.\n     destruct H2.\n     elim H2; hnf; simpl; auto.\n     assert (loserCount < 0).\n     apply Hdominated with c; auto.\n     destruct H2; split; auto.\n     intro; apply H2; hnf; auto.\n     elimtype False; omega.\n   Qed.\n\n   Lemma sf_opt_majority_forward :\n     forall w,\n       majority _ eliminated e w ->\n       majority _ eliminated' e w.\n   Proof.\n     repeat intro.\n     destruct (SF_spec.sf_first_choices_total _ eliminated e w) as [wc ?].\n     destruct (SF_spec.total_selected_total _ eliminated e) as [t ?].\n     generalize (H t wc H3 H2). intros.\n     red. red in H4.\n     assert ( wc <= winner_votes ).\n     { eapply first_choices_monotone.\n       2: apply H2.\n       2: apply H1.\n       rewrite Helim_eq. intros [?|?].\n       destruct (nonzero_first_choices_selected _ eliminated w e wc) as [b [??]]; auto.\n       omega.\n       eapply selected_candidate_not_eliminated; eauto.\n       { destruct Hnonloser as [c [??]].\n         destruct (sf_first_choices_total _ eliminated e c) as [cn ?].\n         assert (loserCount < cn).\n         eapply Hdominated; eauto.\n         assert ( cn + wc <= t ).\n         { eapply disjoint_first_choices.\n           2: eauto. 2: eauto. 2: eauto.\n           intro. subst c. contradiction.\n         }\n         assert ( wc <= loserCount ).\n         {\n           clear -Hcount H5 H2.\n           revert wc loserCount Hcount H2.\n           induction e; intros.\n           * inv H2. omega.\n           * inv H2; inv Hcount.\n             + cut (n' <= n). omega.\n               apply IHe0; auto.\n             + elim H2; eauto.\n             + cut (wc <= n). omega.\n               apply IHe0; eauto.\n             + apply IHe0; eauto.\n         }\n         omega.\n       }\n       intros. rewrite Helim_eq. auto.\n     }\n     assert ( total_votes <= t ).\n     { clear -H0 H3 Helim_eq.\n       revert total_votes t H0 H3.\n       induction e; intros.\n       inv H3. inv H0. auto.\n       inv H3. inv H0.\n       cut (n0 <= n). omega.\n       apply IHe0; auto.\n       transitivity n.\n       apply IHe0; auto.\n       omega.\n       inv H0.\n       elim H3.\n       eapply exhausted_ballot_monotone.\n       2: eauto.\n       intros. rewrite Helim_eq. auto.\n       apply IHe0; auto.\n     }\n     omega.\n  Qed.\n\nEnd sf_spec_opt.\n\n\nLemma next_ranking_back :\n  forall (candidate:Set) (elim elim':candidate -> Prop) b r c,\n    (forall x, elim x -> elim' x) ->\n    In c r ->\n    next_ranking _ elim' b r ->\n    next_ranking _ elim b r \\/\n    (exists c' r',\n       ~overvote _ r' /\\\n       next_ranking _ elim b r' /\\\n       In c' r' /\\ elim' c' /\\ ~elim c').\nProof.\n  intros. induction H1.\n  * destruct (classic (Forall elim r')).\n    destruct IHnext_ranking; auto.\n    left. apply SF_spec.next_ranking_eliminated; auto.\n    destruct H5 as [c' [q [?[?[?[??]]]]]].\n    right.\n    exists c'. exists q. intuition.\n    apply SF_spec.next_ranking_eliminated; auto.\n    destruct (classic (exists x, In x r' /\\ ~elim x)).\n    destruct H5 as [x [??]].\n    right. exists x. exists r'.\n    repeat split; auto.\n    apply SF_spec.next_ranking_valid with x; auto.\n    rewrite Forall_forall in H1.\n    apply H1; auto.\n    elim H4.\n    rewrite Forall_forall; intros.\n    destruct (classic (elim x)); auto.\n    elim H5.\n    eauto.\n  * left. apply SF_spec.next_ranking_valid with c0; auto.\n    intuition.\nQed.\n\nLemma continuing_ballot_back :\n  forall (candidate:Set) (elim elim':candidate -> Prop) b,\n  (forall x, elim x -> elim' x) ->\n  continuing_ballot _ elim' b ->\n  continuing_ballot _ elim b.\nProof.\n  repeat intro.\n  apply H0.\n  destruct H1.\n  left. intros [r ?]. elim H1.\n  clear H0 H1.\n  induction H2.\n  destruct (classic (exists x, In x r' /\\ ~elim x)).\n  destruct H3 as [x [??]].\n  exists r'.\n  apply SF_spec.next_ranking_valid with x; auto.\n  destruct IHnext_ranking as [q ?].\n  exists q.\n  apply SF_spec.next_ranking_eliminated; auto.\n  rewrite Forall_forall; intros.\n  destruct (classic (elim x)); auto.\n  elim H3; eauto.\n  exists r.\n  apply SF_spec.next_ranking_valid with c; auto.\n  intuition.\n  destruct H1 as [r [??]].\n  clear H0.\n  hnf.\n  right.\n  exists r. split; auto.\n  induction H1.\n  apply SF_spec.next_ranking_eliminated; auto.\n  rewrite Forall_forall; intros.\n  apply H.\n  rewrite Forall_forall in H0.\n  apply H0; auto.\n  apply SF_spec.next_ranking_valid with c; auto.\nQed.\n\n\nLemma selected_candidate_back :\n  forall (candidate:Set) (elim elim':candidate -> Prop) b c,\n    (forall x, elim x -> elim' x) ->\n    selected_candidate _ elim' b c ->\n    selected_candidate _ elim b c \\/\n    (exists x, selected_candidate _ elim b x /\\ elim' x /\\ ~elim x).\nProof.\n  intros.\n  destruct H0.\n  destruct H1 as [r [??]].\n  destruct (next_ranking_back candidate elim elim' b r c); auto.\n  left. split; auto.\n  eapply continuing_ballot_back; eauto.\n  eauto.\n  destruct H3 as [c' [r' [?[?[?[??]]]]]].\n  right. exists c'.\n  repeat split; auto.\n  eapply continuing_ballot_back; eauto.\n  exists r'; split; auto.\nQed.\n\nLemma count_votes_unique :\n  forall (candidate:Set) (P:ballot candidate -> Prop) e n1 n2,\n    count_votes _ P e n1 ->\n    count_votes _ P e n2 ->\n    n1 = n2.\nProof.\n  intros until e. induction e; intros.\n  * inv H. inv H0. auto.\n  * inv H; inv H0; auto.\n    elim H2; auto.\n    elim H3; auto.\nQed.\n\nLemma count_votes_add :\n  forall (candidate:Set) (P1 P2 P:ballot candidate -> Prop) e n1 n2,\n    (forall b, P b <-> P1 b \\/ P2 b) ->\n    (forall b, P1 b -> P2 b -> False) ->\n    count_votes _ P1 e n1 ->\n    count_votes _ P2 e n2 ->\n    count_votes _ P e (n1+n2).\nProof.\n  intros. revert n1 n2 H1 H2.\n  induction e; intros.\n  * inv H1. inv H2. simpl. constructor.\n  * inv H1; inv H2.\n    elim (H0 a); auto.\n    simpl.\n    apply count_satisfies.\n    apply H. auto.\n    apply IHe; auto.\n    replace (n1 + S n) with (S (n1 + n)) by omega.\n    apply count_satisfies.\n    apply H; auto.\n    apply IHe; auto.\n    apply count_not_satisfies.\n    intro.\n    rewrite H in H1.\n    intuition.\n    apply IHe; auto.\nQed.\n\nLemma elim_loser_list :\n  forall\n    (candidate:Set)\n    (eliminated:candidate -> Prop)\n    (losers : list candidate)\n    (losers' : list candidate)\n    (loser  : candidate)\n    b,\n\n    (In loser losers) ->\n    (forall x, In x losers <-> x = loser \\/ In x losers') ->\n    (exists c, SF_spec.selected_candidate _ (update_eliminated _ eliminated loser) b c /\\ In c losers') ->\n    (exists c, SF_spec.selected_candidate _ eliminated b c /\\ In c losers).\nProof.\n  intros.\n  destruct H1 as [c [??]].\n  destruct (selected_candidate_back _ eliminated (update_eliminated _ eliminated loser) b c); auto.\n  { unfold update_eliminated; auto. }\n  exists c; split; auto.\n  rewrite H0; auto.\n  destruct H3 as [x [?[??]]].\n  hnf in H4.\n  destruct H4. contradiction.\n  subst x.\n  exists loser; auto.\nQed.\n\nLemma decompose_losers' :\n forall\n    (candidate:Set)\n    (eliminated:candidate -> Prop)\n    (e:election candidate)\n    (losers : list candidate)\n    (loser  : candidate),\n   NoDup losers ->\n   In loser losers ->\n   (forall l, In l losers -> viable_candidate _ eliminated e l) ->\n\n   exists losers',\n     NoDup losers' /\\\n     (forall l, In l losers' -> viable_candidate _ (update_eliminated _ eliminated loser) e l) /\\\n     length losers = S (length losers') /\\\n     (~In loser losers') /\\\n     (forall x, In x losers <-> x = loser \\/ In x losers').\nProof.\n  intros until losers. induction losers; intros. elim H0.\n  inv H.\n  simpl in H0. destruct H0.\n  * subst a.\n    exists losers.\n    intuition.\n    destruct (H1 loser); simpl; auto.\n    split; auto.\n    unfold update_eliminated.\n    intuition.\n    destruct (H1 l); simpl; auto.\n    subst l; auto.\n    destruct (H1 l); simpl; auto.\n    simpl in H. intuition.\n    simpl; auto.\n  * destruct (IHlosers loser) as [losers' [?[?[?[??]]]]]; auto.\n    intros; apply H1; simpl; auto.\n    exists (a::losers'); intuition.\n    constructor; auto.\n    intro.\n    apply H4.\n    rewrite H7. auto.\n    simpl in H8. destruct H8.\n    subst l.\n    destruct (H1 a); simpl; auto.\n    split; auto.\n    unfold update_eliminated; auto.\n    intuition.\n    subst a. contradiction.\n    destruct (H1 l); simpl; auto.\n    rewrite H7; auto.\n    simpl. omega.\n    simpl in H8.\n    destruct H8.\n    subst a.\n    contradiction.\n    contradiction.\n    simpl in H8.\n    rewrite H7 in H8.\n    simpl. intuition.\n    simpl; auto.\n    subst x; auto.\n    simpl in H9; simpl.\n    rewrite H7.\n    intuition.\nQed.\n\n\nLemma decompose_losers :\n forall\n    (candidate:Set)\n    (eliminated:candidate -> Prop)\n    (e:election candidate)\n    (losers : list candidate)\n    (loser  : candidate)\n    (loserCount : nat),\n   NoDup losers ->\n   In loser losers ->\n   count_votes _ (fun b => exists c, SF_spec.selected_candidate _ eliminated b c /\\ In c losers) e loserCount ->\n   (forall l, In l losers -> viable_candidate _ eliminated e l) ->\n\n   exists losers' loserCount',\n     NoDup losers' /\\\n     count_votes _ (fun b => exists c, SF_spec.selected_candidate _ (update_eliminated _ eliminated loser) b c /\\ In c losers') e loserCount' /\\\n     (forall l, In l losers' -> viable_candidate _ (update_eliminated _ eliminated loser) e l) /\\\n     loserCount' <= loserCount /\\\n     length losers = S (length losers') /\\\n     (~In loser losers') /\\\n     (forall x, In x losers <-> x = loser \\/ In x losers').\nProof.\n  intros.\n  destruct (decompose_losers' candidate eliminated e losers loser)\n           as [losers' [?[?[?[??]]]]]; auto.\n  destruct (count_votes_total _\n        (fun b : list (list candidate) =>\n        exists c : candidate,\n          selected_candidate candidate\n            (update_eliminated candidate eliminated loser) b c /\\\n          In c losers') e) as [loserCount' ?].\n  exists losers', loserCount'.\n  intuition.\n  eapply count_votes_monotone.\n  2: eauto. 2: eauto.\n  simpl.\n  intro b.\n  apply elim_loser_list; auto.\nQed.\n\nLemma sf_spec_optimization_backward :\n  forall (candidate:Set)\n         (len : nat)\n         (eliminated eliminated':candidate -> Prop)\n         (e:election candidate)\n         (losers:list candidate)\n         (loserCount:nat),\n\n      len = length losers ->\n      NoDup losers ->\n      (forall l, In l losers -> viable_candidate _ eliminated e l) ->\n      count_votes _ (fun b =>\n                       exists c, SF_spec.selected_candidate _ eliminated b c /\\ In c losers)\n                  e loserCount ->\n      (forall c count,\n         ~In c losers ->\n         SF_spec.viable_candidate _ eliminated e c ->\n         SF_spec.first_choices _ eliminated c e count ->\n         loserCount < count) ->\n      (exists c, ~In c losers /\\ SF_spec.viable_candidate _ eliminated e c) ->\n      (forall x, eliminated' x <-> eliminated x \\/ In x losers) ->\n      (forall x,\n         SF_spec.winner candidate e eliminated' x ->\n         SF_spec.winner candidate e eliminated x).\nProof.\n  intros candidate n.\n  induction n.\n  * intros.\n    eapply winner_elim_eq. 2: eauto.\n    intros.\n    rewrite H5.\n    intuition.\n    destruct losers. elim H9.\n    inv H.\n  * intros.\n    destruct (classic (exists winner, majority _ eliminated e winner)).\n    + destruct H7 as [winner ?].\n      apply SF_spec.winner_now.\n      replace x with winner; auto.\n      inv H6.\n      symmetry.\n      eapply majority_unique.\n      apply H8.\n      eapply sf_opt_majority_forward; eauto.\n      elim H8.\n      exists winner.\n      eapply sf_opt_majority_forward; eauto.\n    + assert (exists loser, In loser losers /\\ is_loser _ eliminated e loser).\n      { destruct (sf_loser_exists _ e eliminated) as [loser ?].\n        destruct losers. inversion H.\n        exists c; auto.\n        destruct (H1 c); simpl; auto.\n        exists loser; split; auto.\n        eapply sf_opt_loser_in_set; eauto.\n        rewrite <- H. omega.\n      }\n      destruct H8 as [loser [??]].\n      apply SF_spec.winner_elimination with loser; auto.\n      destruct (decompose_losers _ eliminated e losers loser loserCount) as [losers' [loserCount' [?[?[?[?[?[??]]]]]]]]; auto.\n      apply (IHn _ eliminated' e losers' loserCount'); auto.\n      omega.\n      eapply sf_opt_inductive_step; eauto.\n      intros.\n      apply le_lt_trans with loserCount; eauto.\n      destruct H4 as [c [??]].\n      exists c. split; auto.\n      intro. apply H4.\n      rewrite H16. auto.\n      destruct H17; split; auto.\n      unfold update_eliminated.\n      intuition.\n      subst c.\n      contradiction.\n\n      unfold update_eliminated.\n      intro.\n      rewrite H5.\n      rewrite H16.\n      intuition.\nQed.\n\nLemma sf_spec_optimization_forward :\n  forall (candidate:Set)\n         (len : nat)\n         (eliminated eliminated':candidate -> Prop)\n         (e:election candidate)\n         (losers:list candidate)\n         (loserCount:nat),\n\n      len = length losers ->\n      NoDup losers ->\n      (forall l, In l losers -> viable_candidate _ eliminated e l) ->\n      count_votes _ (fun b =>\n                       exists c, SF_spec.selected_candidate _ eliminated b c /\\ In c losers)\n                  e loserCount ->\n      (exists c, ~In c losers /\\ SF_spec.viable_candidate _ eliminated e c) ->\n      (forall c count,\n         ~In c losers ->\n         SF_spec.viable_candidate _ eliminated e c ->\n         SF_spec.first_choices _ eliminated c e count ->\n         loserCount < count) ->\n      (forall x, eliminated' x <-> eliminated x \\/ In x losers) ->\n      (forall x,\n         SF_spec.winner candidate e eliminated x ->\n         SF_spec.winner candidate e eliminated' x).\nProof.\n  intros candidate n.\n  induction n.\n  * intros.\n    eapply winner_elim_eq. 2: eauto.\n    intros.\n    rewrite H5.\n    intuition.\n    destruct losers. elim H9.\n    inv H.\n  * intros.\n    inv H6.\n      - apply SF_spec.winner_now.\n        eapply sf_opt_majority_forward; eauto.\n      - assert (In loser losers).\n        { eapply sf_opt_loser_in_set; eauto.\n          rewrite <- H. omega.\n        }\n        destruct (decompose_losers _ eliminated e losers loser loserCount) as [losers' [loserCounts' [?[?[?[?[?[??]]]]]]]]; auto.\n        apply (IHn (SF_spec.update_eliminated _ eliminated loser) eliminated' e losers' loserCounts'); auto.\n        rewrite H14 in H.\n        injection H; auto.\n\n        destruct H3 as [c [??]].\n        exists c. split; auto.\n        intro. apply H3.\n        rewrite H16. auto.\n        destruct H17; split; auto.\n        unfold update_eliminated.\n        intuition.\n        subst c.\n        contradiction.\n\n        eapply sf_opt_inductive_step; eauto.\n        intros.\n        apply le_lt_trans with loserCount; eauto.\n        unfold update_eliminated.\n        intro.\n        rewrite H5.\n        rewrite H16.\n        intuition.\nQed.\n\nTheorem sf_spec_optimization :\n  forall (candidate:Set)\n         (eliminated eliminated':candidate -> Prop)\n         (e:election candidate)\n         (losers:list candidate)\n         (loserCount:nat),\n\n      count_votes _ (fun b =>\n                       exists c, SF_spec.selected_candidate _ eliminated b c /\\ In c losers)\n                  e loserCount ->\n\n      (exists c, ~In c losers /\\ SF_spec.viable_candidate _ eliminated e c) ->\n\n      (forall c count,\n         ~In c losers ->\n         SF_spec.viable_candidate _ eliminated e c ->\n         SF_spec.first_choices _ eliminated c e count ->\n         loserCount < count) ->\n      (forall x, eliminated' x <-> eliminated x \\/ In x losers) ->\n      (forall x,\n         SF_spec.winner candidate e eliminated x <-> SF_spec.winner candidate e eliminated' x).\nProof.\n  intros.\n  assert (exists losers',\n            NoDup losers' /\\\n            (forall l, In l losers' <-> viable_candidate _ eliminated e l /\\ In l losers)).\n  { clear. induction losers.\n    * exists nil. simpl; intuition. constructor.\n    * destruct IHlosers as [losers' [??]].\n      destruct (classic (In a losers')).\n      + exists losers'. intuition.\n        rewrite H0 in H2; intuition.\n        rewrite H0 in H2; simpl; intuition.\n        rewrite H0. split; simpl in *; intuition.\n        subst l. auto.\n        rewrite H0 in H1.\n        intuition.\n      + destruct (classic (viable_candidate _ eliminated e a)).\n        - exists (a::losers').\n          split. constructor; auto.\n          simpl; intuition subst; auto.\n          rewrite H0 in H4; intuition.\n          rewrite H0 in H4; intuition.\n          rewrite H0; intuition.\n        - exists losers'.\n          simpl; intuition subst; auto.\n          rewrite H0 in H3; intuition.\n          rewrite H0 in H3; intuition.\n          rewrite H0; intuition.\n          rewrite H0; intuition.\n  }\n  destruct H3 as [losers' [??]].\n  set (eliminated'' c := eliminated c \\/ In c losers').\n\n  cut (winner _ e eliminated x <-> winner _  e eliminated'' x).\n  { intros. rewrite H5.\n    cut (forall c, SF_spec.participates _ c e -> (eliminated'' c <-> eliminated' c)).\n    intros. split; apply winner_elim_eq; auto.\n    intros. symmetry; apply H6; auto.\n    intros. unfold eliminated''.\n    rewrite H2.\n    intuition.\n    right.\n    rewrite H4 in H9. intuition.\n    destruct (classic (eliminated c)); auto.\n    right.\n    rewrite H4. split; auto.\n    split; auto.\n  }\n\n  assert (Hviable : \n   forall l : candidate,\n   In l losers' -> viable_candidate candidate eliminated e l).\n  { intros. rewrite H4 in H5. intuition. }\n\n  assert (Hcount :    count_votes candidate\n     (fun b : list (list candidate) =>\n      exists c : candidate,\n        selected_candidate candidate eliminated b c /\\ In c losers') e\n     loserCount).\n  { revert H. apply count_eq.\n    intuition.\n    destruct H5 as [c [??]]. exists c; split; auto.\n    rewrite H4; auto. split; auto.\n    split.\n    eapply selected_candidate_not_eliminated; eauto.\n    destruct H5.\n    destruct H7 as [r [??]].\n    hnf; eauto.\n    exists b; split; auto.\n    exists r; split; auto.\n    eapply next_ranking_in_ballot; eauto.\n    destruct H5 as [c [??]].\n    exists c; split; auto.\n    rewrite H4 in H6. intuition.\n  }\n  assert (Hnonloser :    exists c : candidate,\n     ~ In c losers' /\\ viable_candidate candidate eliminated e c).\n  { destruct H0 as [c [??]].\n    exists c; split; auto.\n    intro.\n    apply H0.\n    rewrite H4 in H6. intuition.\n  }\n  assert (Hdominated : forall (c : candidate) (count : nat),\n   ~ In c losers' ->\n   viable_candidate candidate eliminated e c ->\n   first_choices candidate eliminated c e count -> loserCount < count).\n  { intros.\n    eapply H1; eauto.\n    intro. apply H5.\n    apply H4. split; auto.\n  }\n  assert (Helim :\n     forall x0 : candidate, eliminated'' x0 <-> eliminated x0 \\/ In x0 losers').\n  { unfold eliminated''. intuition. }\n\n  split.\n  apply sf_spec_optimization_forward with (length losers') losers' loserCount; auto.\n  apply sf_spec_optimization_backward with (length losers') losers' loserCount; auto.\nQed.\n", "meta": {"author": "cjerdonek", "repo": "formal-rcv", "sha": "73498644b06c33564d61886177238aa3f63d86ba", "save_path": "github-repos/coq/cjerdonek-formal-rcv", "path": "github-repos/coq/cjerdonek-formal-rcv/formal-rcv-73498644b06c33564d61886177238aa3f63d86ba/src/SF_opt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245618, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6552529572926564}}
{"text": "Set Implicit Arguments.\nRequire Import List.\n\n\n(** * The Functor Type Class *)\n\nLocal Notation \"f ∘ g\" := (fun x => f (g x)) (at level 40, left associativity).\n\nClass Functor (f : Type -> Type) : Type :=\n{ fmap         : forall {A B}, (A -> B) -> f A -> f B }. \nClass Functor_Correct (f : Type -> Type) `{F : Functor f} :=\n{ fmap_id      : forall A, fmap (fun (x:A)=> x) = (fun x => x);\n  fmap_compose : forall A B C (g : A -> B) (f : B -> C), \n                 fmap (f ∘ g) = fmap f ∘ fmap g\n}.\nClass Applicative (f : Type -> Type) `{F : Functor f} : Type :=\n{ pure : forall {A}, A -> f A;\n  liftA : forall {A B}, f (A -> B) -> f A -> f B\n}.\nNotation \"f <*> a\" := (liftA f a) (left associativity, at level 25).\n\n\nClass Applicative_Correct (f : Type -> Type) `{Applicative f} :=\n{ applicative_id : forall A, liftA (pure (fun  (x:A) => x)) = (fun  x => x);\n  applicative_composition : forall {A B C} (u : f (B -> C)) (v : f (A -> B)) (w : f A),\n    pure (fun  x => fun  y => x ∘ y) <*> u <*> v <*> w = u <*> (v <*> w);\n  applicative_homomorphism : forall {A B} (f : A -> B) (x : A),\n    pure f <*> pure x = pure (f x);\n  applicative_interchange : forall {A B} (u : f (A -> B)) (y : A),\n    u <*> pure y = pure (fun x => x y) <*> u\n}.\n\nClass Monad (m: Type -> Type) `{M : Applicative m} : Type :=\n{ bind: forall {A}, m A -> forall {B}, (A -> m B) -> m B\n}.\nDefinition return_ {m : Type -> Type} `{M : Monad m} {A : Type} : A -> m A := pure.\nNotation \"a >>= f\" := (bind a f) (at level 50, left associativity).\n\nHint Unfold bind return_ : monad_db.\n\nClass Monad_Correct (m : Type -> Type) `{M : Monad m} := {\n  bind_right_unit: forall A (a: m A), a = a >>= return_;\n  bind_left_unit: forall A (a: A) B (f: A -> m B),\n             f a = return_ a >>= f;\n  bind_associativity: forall A (ma: m A) B f C (g: B -> m C),\n                 bind ma (fun  x=> f x >>= g) = (ma >>= f) >>= g\n}.\n\nArguments Functor f : assert.\nArguments Functor_Correct f {F}.\nArguments Applicative f {F}.\nArguments Applicative_Correct f {F} {A} : rename.\nArguments Monad m {F} {M}.\nArguments Monad_Correct m {F} {A} {M} : rename.\n\nSection monadic_functions.\n Variable m : Type -> Type. \n Variable F : Functor m.\n Variable A : Applicative m.\n Variable M : Monad m.\n\n Definition wbind {A: Type} (ma: m A) {B: Type} (mb: m B) :=\n ma >>= fun  _=>mb.\n\n Definition liftM {A B: Type} (f: A->B) (ma: m A): m B :=\n ma >>= (fun  a => return_ (f a)).\n\n Definition join {A: Type} (mma: m (m A)): m A :=\n mma >>= (fun  ma => ma).\n\nEnd monadic_functions.\n\nNotation \"a >> f\" := (wbind _ a f) (at level 50, left associativity).\nNotation \"'do' a ← e ; c\" := (e >>= (fun  a => c)) (at level 60, right associativity).\n\n\nFixpoint foldM {A B m} `{Monad m} \n               (f : B -> A -> m B) (b : B) (ls : list A) : m B :=\n  match ls with\n  | nil      => return_ b\n  | x :: ls' => do y ← f b x;\n                foldM f y ls'\n  end.\nHint Unfold foldM : monad_db.\n\nAbout fmap_compose.\nLemma fmap_compose' {f} (F : Functor f) `{Functor_Correct f} : \n    forall {A B C} (g : A -> B) (h : B -> C) (a : f A),\n    fmap h (fmap g a) = fmap (h ∘ g) a.\nProof.\n  intros.\n  rewrite (fmap_compose g h).\n  reflexivity.\nQed.\n  \n\nRequire Import Program.\nLemma bind_eq : forall {A B m} `{Monad m} (a a' : m A) (f f' : A -> m B),\n      a = a' ->\n      (forall x, f x = f' x) ->\n      bind a f = bind a' f'.\nProof.\n  intros. subst.\n  f_equal.\n  apply functional_extensionality.\n  auto.\nQed.\n\nLtac simplify_monad_LHS :=\n  repeat match goal with\n  | [ |- bind (return_ _) _ = _ ] => rewrite <- bind_left_unit\n  | [ |- bind (bind _ _) _ = _ ]  => rewrite <- bind_associativity\n  | [ |- _ = _ ]                  => reflexivity\n  | [ |- bind ?a ?f = _ ]         => erewrite bind_eq; intros; \n                                     [ | simplify_monad_LHS | simplify_monad_LHS ]\n  end.\n\nLtac simplify_monad :=\n  simplify_monad_LHS;\n  apply eq_sym;\n  simplify_monad_LHS;\n  apply eq_sym.\n\nLtac simpl_m :=\n  repeat (try match goal with\n  [ |- bind ?a _ = bind ?a _ ] => apply bind_eq; [ reflexivity | intros ]\n  end; simplify_monad).\n\nProposition test : forall {m} `{Monad m} `{Monad_Correct m} (a b c : m unit),\n        do x ← a; do y ← b;  c\n      = do y ← (do x ← a; b); c.\nProof. intros.\nsimplify_monad.\nAbort.\n\n(** * Some classic Monads *)\n\n(** ** The list monad *)\n\nOpen Scope list_scope. \n(*\nDefinition list_fmap {A B} (f : A -> B) := \n  fix map (l : list A) : list B :=\n  match l with\n  | nil => nil\n  | a :: t => f a :: map t\n  end.\n*)\nDefinition list_fmap := map.\nHint Unfold list_fmap : monad_db.\n(*\nFixpoint list_fmap {A B} (f : A -> B) (ls : list A) : list B :=\n  match ls with\n  | nil => nil\n  | a :: ls' => f a :: list_fmap f ls'\n  end.  *)\n\n(*\nFixpoint concat {A} (xs : list (list A)) : list A :=\n  match xs with\n  | nil => nil\n  | ys :: xs' => ys ++ concat xs'\n  end.\n*)\n\nDefinition list_liftA {A B} (fs : list (A -> B)) (xs : list A) : list B :=\n  let g := fun a => list_fmap (fun f => f a) fs\n  in\n  concat (list_fmap g xs).\nHint Unfold list_liftA : monad_db.\n\nFixpoint list_bind {A} (xs : list A) {B} (f : A -> list B) : list B :=\n  match xs with\n  | nil => nil\n  | a :: xs' => f a ++ list_bind xs' f\n  end.\nHint Unfold list_bind : monad_db.\n\nInstance listF : Functor list := { fmap := @list_fmap }.\nInstance listA : Applicative list := { pure := fun _ x => x :: nil\n                                     ; liftA := @list_liftA }.\nInstance listM : Monad list := \n  { bind := @list_bind }.\n\nInstance listF_correct : Functor_Correct list.\nProof.\n  constructor.\n  * intros. simpl. apply functional_extensionality; intros x.\n    induction x; simpl; auto.\n    rewrite IHx; auto.\n  * intros. simpl. apply functional_extensionality; intros x.\n    induction x; simpl; auto.\n    rewrite IHx.\n    auto.\nQed.\n\nInstance listA_correct : Applicative_Correct list.\nProof.\n  constructor.\n  * intros. simpl. apply functional_extensionality; intros l.\n    induction l; simpl; auto.\n    unfold list_liftA in *. simpl in *.\n    rewrite IHl; easy.\nAbort.\n\nInstance listM_correct : Monad_Correct list.\nAbort.\n\n\n\n\nLemma fmap_app : forall {A B} (f : A -> B) ls1 ls2,\n      fmap f (ls1 ++ ls2) = fmap f ls1 ++ fmap f ls2.\nProof.\n  induction ls1; intros; simpl; auto.\n  rewrite IHls1. auto.\nQed.\n\n(** ** The Maybe monad (using option type) *) \n\nDefinition option_fmap {A B} (f : A -> B) (x : option A) : option B :=\n  match x with\n  | None => None\n  | Some a => Some (f a)\n  end.\nDefinition option_liftA {A B} (f : option (A -> B)) (x : option A) : option B :=\n  match f, x with\n  | Some f', Some a => Some (f' a)\n  | _, _ => None\n  end.\nInstance optionF : Functor option := { fmap := @option_fmap}.\nInstance optionA : Applicative option := { pure := @Some;\n                                           liftA := @option_liftA}.\nInstance optionM : Monad option :=\n  { bind := fun  A m B f => match m with None => None | Some a => f a end\n  }.\nInstance optionM_Laws : Monad_Correct option.\nProof. split.\n  - destruct a; auto.\n  - intros; auto.\n  - destruct ma; intros; auto.\nDefined.\n\n(* Monad Transformer *)\nClass MonadTrans (t : (Type -> Type) -> (Type -> Type)) :=\n  { liftT : forall {m} `{Monad m} {A}, m A -> t m A }.\n\n\n(** Option monad transformer *)\nDefinition optionT m (A : Type) : Type := m (option A).\n\nDefinition optionT_liftT {m} `{Monad m} {A} (x : m A) : optionT m A.\nProof.\n  unfold optionT.\n  refine (do a ← x; return_ (Some a)).\nDefined.\nInstance optionT_T : MonadTrans optionT := {liftT := @optionT_liftT}.\n\nDefinition optionT_fmap {f} `{Functor f} \n                        {A B} (g : A -> B) (x : optionT f A) : optionT f B :=\n  @fmap f _ _ _ (fmap g) x.\nDefinition optionT_liftA {f} `{Applicative f}\n                         {A B} (g : optionT f (A -> B)) (x : optionT f A) \n                       : optionT f B.\n(*  @liftA f _ _ _ _ (fmap liftA g) x.*)\nProof. \n  unfold optionT in *.\n  exact (fmap liftA g <*> x).\nDefined. \nDefinition optionT_pure {f} `{Applicative f}\n                        {A} (a : A) : optionT f A := @pure f _ _ _ (pure a).\nDefinition optionT_bind {m} `{Monad m}\n                        {A} (ma : optionT m A) {B} (f : A -> optionT m B)\n                        : optionT m B.\n  unfold optionT in *.\n  exact (do oa ← ma; \n         match oa with\n         | None => pure None\n         | Some a => f a\n         end\n  ).\nDefined.\n\nInstance optionT_F {f} `{Functor f} : Functor (optionT f) := \n    {fmap := @optionT_fmap f _}.\nInstance optionT_A {f} `{Applicative f} : Applicative (optionT f) :=\n  { pure := @optionT_pure f _ _;\n    liftA := @optionT_liftA f _ _ }.\nInstance optionT_M {m} `{Monad m} : Monad (optionT m) :=\n  { bind := @optionT_bind m _ _ _ }.\n\n(** The Reader monad *)\nAxiom Eta: forall A (B: A -> Type) (f: forall a, B a), f = fun  a=>f a.\n\nDefinition Reader (E : Type) := fun  X => E -> X.\nDefinition reader_fmap E A B (f : A -> B) (r : Reader E A) : Reader E B :=\n  fun x => f (r x).\nDefinition reader_liftA E A B (f : Reader E (A -> B)) (r : Reader E A) :=\n  fun x => (f x) (r x).\nDefinition reader_bind E A (r : Reader E A) B (f : A -> Reader E B) : Reader E B :=\n  fun x => f (r x) x.\n  \nInstance readerF E : Functor (Reader E) :=\n { fmap := @reader_fmap E }.\nInstance readerA E : Applicative (Reader E) :=\n { pure := fun  A (a:A) e=> a;\n   liftA := @reader_liftA E }.\nInstance readerM (E : Type): Monad (Reader E) :=\n { bind := @reader_bind E }.\n(*\n(* Checking the 3 laws *)\n - (* unit_left *)\n   intros; apply Eta.\n - (* unit_right *)\n   intros; apply Eta.\n - (* associativity *)\n   reflexivity.\nDefined.\n*)\n(** ** The State monad *)\n\nRequire Import Program.\nSection State.\n(*Axiom Ext: forall A (B: A->Type) (f g: forall a, B a), (forall a, f a = g a) -> f = g.*)\n\n  Variable S : Type.\n\n  Definition State (A : Type) := S -> A * S.\n  Definition state_fmap A B (f : A -> B) (st : State A) : State B :=\n    fun  s => let (a,s) := st s in (f a,s).\n  Definition state_liftA A B (st_f : State (A -> B)) (st_a : State A) :=\n    fun  s => let (f,s) := st_f s in\n              let (a,s) := st_a s in\n              (f a,s).\n  Definition state_bind A (st_a : State A) B  (f : A -> State B) :=\n    fun  s => let (a,s) := st_a s in\n              f a s.\n\n  Definition put (x : S) : State () :=\n    fun _ => (tt,x).\n  Definition get : State S :=\n    fun x => (x,x).\n  Definition runState  {A} (op : State A) : S -> A * S := op.\n  Definition evalState {A} (op : State A) : S -> A := fst ∘ op.\n  Definition execState {A} (op : State A) : S -> S := snd ∘ op.\n\n\n\nEnd State.\nHint Unfold put get runState evalState execState state_fmap state_liftA state_bind : monad_db.\nLtac fold_evalState :=\n  match goal with\n  | [ |- context[fst (?c ?v)] ] => replace (fst (c v)) with (evalState c v)\n                                                       by reflexivity\n  end.\n\nArguments get {S}.\nArguments put {S}.\n\nInstance stateF {A} : Functor (State A) :=\n    { fmap := @state_fmap A }.\nInstance stateA {A} : Applicative (State A) :=\n    { pure := fun  A a s=> (a,s);\n      liftA := @state_liftA A }.\nInstance stateM {A} : Monad (State A) :=\n    { bind := @state_bind A }.\n\n\nInstance stateF_correct {A} : Functor_Correct (State A).\n  Proof.\n    split; intros;\n      apply functional_extensionality; intros op;\n      apply functional_extensionality; intros x;\n      simpl; unfold state_fmap.\n    - destruct (op x); reflexivity.\n    - destruct (op x); reflexivity.\n  Qed.\n\nInstance stateA_correct {A} : Applicative_Correct (State A).\n  Proof. \n    split; intros;\n      apply functional_extensionality; intros op; \n      simpl; unfold state_liftA.\n    - apply functional_extensionality; intros x.\n      destruct (op x); reflexivity.\n    - destruct (u op).\n      destruct (v a).\n      destruct (w a0).\n      reflexivity.\n    - reflexivity.\n    - destruct (u op). \n      reflexivity.\n  Qed.\n\nInstance stateM_correct {A} : Monad_Correct (State A).\n  Proof.\n    split; intros; simpl; unfold state_bind.\n    - apply functional_extensionality; intros x. \n      destruct (a x); reflexivity.\n    - reflexivity.\n    - apply functional_extensionality; intros x.\n      destruct (ma x).\n      reflexivity.\n  Qed.\n\nHint Unfold Basics.compose : monad_db.\nHint Unfold stateM : monad_db.\n\n\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/Monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.655252949882262}}
{"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.\nRequire int.Abs.\nRequire int.EuclideanDivision.\nRequire int.ComputerDivision.\nRequire number.Parity.\n\n(* Hack so that Why3 does not override the notation below.\n\n(* Why3 assumption *)\nDefinition divides (d:Z) (n:Z): Prop := exists q:Z, (n = (q * d)%Z).\n\n*)\n\nRequire Import Znumtheory.\nNotation divides := Zdivide (only parsing).\n\n(* Why3 goal *)\nLemma divides_refl :\nforall (n:Z), (divides n n).\nProof.\nexact Zdivide_refl.\nQed.\n\n(* Why3 goal *)\nLemma divides_1_n :\nforall (n:Z), (divides 1%Z n).\nProof.\nexact Zone_divide.\nQed.\n\n(* Why3 goal *)\nLemma divides_0 :\nforall (n:Z), (divides n 0%Z).\nProof.\nexact Zdivide_0.\nQed.\n\n(* Why3 goal *)\nLemma divides_left :\nforall (a:Z) (b:Z) (c:Z), (divides a b) -> (divides (c * a)%Z (c * b)%Z).\nProof.\nexact Zmult_divide_compat_l.\nQed.\n\n(* Why3 goal *)\nLemma divides_right :\nforall (a:Z) (b:Z) (c:Z), (divides a b) -> (divides (a * c)%Z (b * c)%Z).\nProof.\nexact Zmult_divide_compat_r.\nQed.\n\n(* Why3 goal *)\nLemma divides_oppr :\nforall (a:Z) (b:Z), (divides a b) -> (divides a (-b)%Z).\nProof.\nexact Zdivide_opp_r.\nQed.\n\n(* Why3 goal *)\nLemma divides_oppl :\nforall (a:Z) (b:Z), (divides a b) -> (divides (-a)%Z b).\nProof.\nexact Zdivide_opp_l.\nQed.\n\n(* Why3 goal *)\nLemma divides_oppr_rev :\nforall (a:Z) (b:Z), (divides (-a)%Z b) -> (divides a b).\nProof.\nexact Zdivide_opp_l_rev.\nQed.\n\n(* Why3 goal *)\nLemma divides_oppl_rev :\nforall (a:Z) (b:Z), (divides a (-b)%Z) -> (divides a b).\nProof.\nexact Zdivide_opp_r_rev.\nQed.\n\n(* Why3 goal *)\nLemma divides_plusr :\nforall (a:Z) (b:Z) (c:Z),\n (divides a b) -> ((divides a c) -> (divides a (b + c)%Z)).\nProof.\nexact Zdivide_plus_r.\nQed.\n\n(* Why3 goal *)\nLemma divides_minusr :\nforall (a:Z) (b:Z) (c:Z),\n (divides a b) -> ((divides a c) -> (divides a (b - c)%Z)).\nProof.\nexact Zdivide_minus_l.\nQed.\n\n(* Why3 goal *)\nLemma divides_multl :\nforall (a:Z) (b:Z) (c:Z), (divides a b) -> (divides a (c * b)%Z).\nProof.\nintros a b c.\napply Zdivide_mult_r.\nQed.\n\n(* Why3 goal *)\nLemma divides_multr :\nforall (a:Z) (b:Z) (c:Z), (divides a b) -> (divides a (b * c)%Z).\nProof.\nexact Zdivide_mult_l.\nQed.\n\n(* Why3 goal *)\nLemma divides_factorl :\nforall (a:Z) (b:Z), (divides a (b * a)%Z).\nProof.\nexact Zdivide_factor_l.\nQed.\n\n(* Why3 goal *)\nLemma divides_factorr :\nforall (a:Z) (b:Z), (divides a (a * b)%Z).\nProof.\nexact Zdivide_factor_r.\nQed.\n\n(* Why3 goal *)\nLemma divides_n_1 :\nforall (n:Z), (divides n 1%Z) -> ((n = 1%Z) \\/ (n = (-1%Z)%Z)).\nProof.\nexact Zdivide_1.\nQed.\n\n(* Why3 goal *)\nLemma divides_antisym :\nforall (a:Z) (b:Z),\n (divides a b) -> ((divides b a) -> ((a = b) \\/ (a = (-b)%Z))).\nProof.\nexact Zdivide_antisym.\nQed.\n\n(* Why3 goal *)\nLemma divides_trans :\nforall (a:Z) (b:Z) (c:Z), (divides a b) -> ((divides b c) -> (divides a c)).\nProof.\nexact Zdivide_trans.\nQed.\n\n(* Why3 goal *)\nLemma divides_bounds :\nforall (a:Z) (b:Z),\n (divides a b) ->\n ((~ (b = 0%Z)) -> ((ZArith.BinInt.Z.abs a) <= (ZArith.BinInt.Z.abs b))%Z).\nProof.\nexact Zdivide_bounds.\nQed.\n\nImport EuclideanDivision.\n\n(* Why3 goal *)\nLemma mod_divides_euclidean :\nforall (a:Z) (b:Z),\n (~ (b = 0%Z)) -> (((int.EuclideanDivision.mod1 a b) = 0%Z) -> (divides b a)).\nProof.\nintros a b Zb H.\nexists (div a b).\nrewrite (Div_mod a b Zb) at 1.\nrewrite H.\nring.\nQed.\n\n(* Why3 goal *)\nLemma divides_mod_euclidean :\nforall (a:Z) (b:Z),\n (~ (b = 0%Z)) -> ((divides b a) -> ((int.EuclideanDivision.mod1 a b) = 0%Z)).\nProof.\nintros a b Zb H.\nassert (Zmod a b = Z0).\nnow apply Zdivide_mod.\nunfold mod1, div.\nrewrite H0.\ncase Z_le_dec ; intros H1.\nrewrite (Z_div_exact_full_2 a b Zb H0) at 1.\napply Zminus_diag.\nnow elim H1.\nQed.\n\n(* Why3 goal *)\nLemma mod_divides_computer :\nforall (a:Z) (b:Z),\n (~ (b = 0%Z)) -> (((ZArith.BinInt.Z.rem a b) = 0%Z) -> (divides b a)).\nProof.\nintros a b Zb H.\nexists (Z.quot a b).\nrewrite Zmult_comm.\nnow apply Zquot.Z_quot_exact_full.\nQed.\n\n(* Why3 goal *)\nLemma divides_mod_computer :\nforall (a:Z) (b:Z),\n (~ (b = 0%Z)) -> ((divides b a) -> ((ZArith.BinInt.Z.rem a b) = 0%Z)).\nProof.\nintros a b Zb (q,H).\nrewrite H.\napply Zquot.Z_rem_mult.\nQed.\n\n(* Why3 goal *)\nLemma even_divides :\nforall (a:Z), (number.Parity.even a) <-> (divides 2%Z a).\nProof.\nsplit ;\n  intros (q,H) ; exists q ; now rewrite Zmult_comm.\nQed.\n\n(* Why3 goal *)\nLemma odd_divides :\nforall (a:Z), (number.Parity.odd a) <-> ~ (divides 2%Z a).\nProof.\nsplit.\nintros H.\ncontradict H.\napply Parity.even_not_odd.\nnow apply <- even_divides.\nintros H.\ndestruct (Parity.even_or_odd a).\nelim H.\nnow apply -> even_divides.\nexact H0.\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/Divisibility.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6552529468738165}}
{"text": "Definition NonEmpty_foldr1 {a} (f : a -> a -> a) (x: GHC.Base.NonEmpty a) : a :=\n  match x with \n    | GHC.Base.NEcons a as_ => List.fold_right f a as_\n  end.\n\nDefinition NonEmpty_maximum {a} `{GHC.Base.Ord a} (x:GHC.Base.NonEmpty a) : a :=\n  NonEmpty_foldr1 GHC.Base.max x.\n\nDefinition NonEmpty_minimum {a} `{GHC.Base.Ord a} (x:GHC.Base.NonEmpty a) : a :=\n  NonEmpty_foldr1 GHC.Base.min x.\n\nDefinition toList {a} : GHC.Base.NonEmpty a -> list a :=\n  fun arg_0__ => match arg_0__ with | GHC.Base.NEcons a as_ => cons a as_ end.\n\n\nDefinition List_size {a} : list a -> nat :=\nList.fold_right (fun x y => S y) O .\nDefinition NonEmpty_size {a} : GHC.Base.NonEmpty a -> nat :=\n  fun arg_0__ =>\n    match arg_0__ with\n      | GHC.Base.NEcons _ xs => 1 + List_size xs\n    end.\n\nProgram Fixpoint insertBy {a} (cmp: a -> a -> comparison) (x : a)\n        (xs : GHC.Base.NonEmpty a) {measure (NonEmpty_size xs)} : GHC.Base.NonEmpty a :=\n  match xs with\n  | GHC.Base.NEcons x nil => GHC.Base.NEcons x nil\n  | (GHC.Base.NEcons y ((cons y1 ys') as ys)) => \n    match cmp x y with\n    | Gt  => GHC.Base.NEcons y (toList (insertBy cmp x (GHC.Base.NEcons y1 ys')))\n    | _   => GHC.Base.NEcons x ys\n    end\n  end.\n\nProgram Fixpoint insertBy' {a} (cmp: a -> a -> comparison) (x : a)\n        (xs : list a) {measure (List_size xs)} : GHC.Base.NonEmpty a :=\n  match xs with\n  | nil => GHC.Base.NEcons x nil\n  | cons x nil => GHC.Base.NEcons x nil\n  | (cons y ((cons y1 ys') as ys)) => \n    match cmp x y with\n    | Gt  => GHC.Base.NEcons y (toList (insertBy' cmp x (cons y1 ys')))\n    | _   => GHC.Base.NEcons x ys\n    end\n  end.\n\n\nDefinition insert {a} `{GHC.Base.Ord a} : a ->  GHC.Base.NonEmpty a -> GHC.Base.NonEmpty a :=\n  insertBy GHC.Base.compare.\n\nDefinition sortBy {a} : (a -> a -> comparison) -> GHC.Base.NonEmpty a -> GHC.Base.NonEmpty a :=\n  fun f ne => match ne with\n           | GHC.Base.NEcons x xs => insertBy' f x (Data.OldList.sortBy f xs)\n           end.\n\nDefinition sort {a} `{GHC.Base.Ord a} : GHC.Base.NonEmpty a -> GHC.Base.NonEmpty a :=\n             sortBy GHC.Base.compare.\n\n\n", "meta": {"author": "DavidFHCh", "repo": "Tesis-FTW", "sha": "f84ab8eb92f3984e973ce6a441262d9a8a62e9b0", "save_path": "github-repos/coq/DavidFHCh-Tesis-FTW", "path": "github-repos/coq/DavidFHCh-Tesis-FTW/Tesis-FTW-f84ab8eb92f3984e973ce6a441262d9a8a62e9b0/tesis/hs-to-coq/examples/base-src/module-edits/Data/List/NonEmpty/midamble.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6552529410783636}}
{"text": "From Coq Require Import Relations.Relations.\nFrom Coq Require Import Classes.RelationClasses.\nFrom VSA Require Import Basics.\nFrom VSA Require Import Lattice.\nFrom VSA Require Import LatticeProperties.\nFrom VSA Require Import Functions.\n\nImport SetNotations.\n\nDefinition PreFixpoints {A: Type} (f: A -> A) `{Increasing A A f}: ℘ A :=\n  fun x => x ⊑ f x.\n\nDefinition PostFixpoints {A: Type} (f: A -> A) `{Increasing A A f}: ℘ A :=\n  fun x => f x ⊑ x.\n\nDefinition Fixpoints {A: Type} (f: A -> A) `{Increasing A A f}: ℘ A :=\n  fun x => f x = x.\n\nDefinition lfp {A: Type} (f: A -> A) `{Increasing A A f} (u: A) :=\n  LowerBound (Fixpoints f) u /\\ u ∈ (Fixpoints f).\n\nDefinition glp {A: Type} (f: A -> A) `{Increasing A A f} (u: A) :=\n  UpperBound (Fixpoints f) u /\\ u ∈ (Fixpoints f).\n\nSection Tarski.\n\n  Context {A: Type} `{CompleteLattice A} (f: A -> A) {I: Increasing f}.\n\n  Definition lfp_tarski: A := inf (PostFixpoints f).\n\n  Lemma lfp_tarski_fixpoint:\n    f (lfp_tarski) = lfp_tarski.\n  Proof.\n    assert (f lfp_tarski ⊑ lfp_tarski).\n    {\n      apply inf_glb. intros x H__x.\n      transitivity (f x); auto.\n      apply increasing.\n      apply inf_lb.\n      assumption.\n    }\n    apply antisymmetry; auto.\n    apply inf_lb. apply increasing. assumption.\n  Qed.\n\n  Lemma lfp_tarski_leastfixpoint:\n    LowerBound (Fixpoints f) lfp_tarski.\n  Proof.\n    intros u H__u.\n    apply inf_lb. unfold PostFixpoints. rewrite H__u. reflexivity.\n  Qed.\n\n  Theorem lfp_tarski_iff:\n    lfp f lfp_tarski.\n  Proof.\n    split.\n    - apply lfp_tarski_leastfixpoint.\n    - apply lfp_tarski_fixpoint.\n  Qed.\n\nEnd Tarski.\n", "meta": {"author": "Gogume1er", "repo": "verified-static-analyzer", "sha": "faa20dc58ad1fcc8a13ee8b875b99e0f26a36e33", "save_path": "github-repos/coq/Gogume1er-verified-static-analyzer", "path": "github-repos/coq/Gogume1er-verified-static-analyzer/verified-static-analyzer-faa20dc58ad1fcc8a13ee8b875b99e0f26a36e33/Fixpoints.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6552200744745765}}
{"text": "Require Import Coq.ZArith.ZArith Coq.ZArith.Zcomplements. Open Scope Z_scope.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import Coq.Logic.Classical.\nRequire Import Coq.micromega.Lia.\n\nSet Implicit Arguments.\n\nDefinition Znth{T: Type}(l: list T)(i: Z)(default: T): T := nth (Z.to_nat i) l default.\n\nParameter Error: Prop.\n\n(* number of variables and list of clauses *)\nDefinition Input: Type := Z * list (list Z).\n\nExample test1 := (5, [\n  [1; -5; 4];\n  [-1; 5; 3; 4];\n  [-3; -4]\n]).\n\nDefinition interp_lit(env: list Prop)(l: Z): Prop :=\n  let x := Znth env (Z.abs l) Error in\n  match l with\n  | Z0 => Error\n  | Zpos _ => x\n  | Zneg _ => ~ x\n  end.\n\nFixpoint interp_clause(env: list Prop)(c: list Z): Prop :=\n  match c with\n  | nil => False\n  | [x] => interp_lit env x\n  | x :: rest => interp_lit env x \\/ interp_clause env rest\n  end.\n\nFixpoint interp_formula(env: list Prop)(f: list (list Z)): Prop :=\n  match f with\n  | nil => True\n  | [c] => interp_clause env c\n  | c :: rest => interp_clause env c /\\ interp_formula env rest\n  end.\n\nEval cbv -[not] in (forall (x1 x2 x3 x4 x5: Prop),\n                       interp_formula [Error; x1; x2; x3; x4; x5] (snd test1)).\n\nFixpoint foralls(n: nat)(acc: list Prop)(body: list Prop -> Prop): Prop :=\n  match n with\n  | O => body (rev acc)\n  | S n' => forall (x: Prop), foralls n' (x :: acc) body\n  end.\n\nDefinition claim_unsat(inp: Input): Prop :=\n  let '(nvars, clauses) := inp in\n  forall (x x0: Prop), (* dummy vars to make Coq's auto naming scheme match *)\n    foralls (Z.to_nat nvars) [x0]\n            (fun env =>\n               forall e, e = env -> (* dummy equation to easily get env later *)\n               True -> (* dummy hypothesis to get auto naming of hypotheses match *)\n               interp_formula env clauses -> False).\n\nEval cbv -[not] in (claim_unsat test1).\n\nLemma resolution: forall x1 A B,\n    x1 \\/ A ->\n    ~ x1 \\/ B ->\n    A \\/ B.\nProof. tauto. Qed.\n\nLemma resolution1: forall C1 A1 D,\n    C1 \\/ A1 ->\n    ~A1 \\/ D ->\n    C1 \\/ D.\nProof. tauto. Qed.\n\nLemma resolution2: forall C1 A1 C2 A2 D,\n    C1 \\/ A1 ->\n    C2 \\/ A2 ->\n    ~A1 \\/ ~A2 \\/ D ->\n    C1 \\/ C2 \\/ D.\nProof. tauto. Qed.\n\nLemma resolution3: forall C1 A1 C2 A2 C3 A3 D,\n    C1 \\/ A1 ->\n    C2 \\/ A2 ->\n    C3 \\/ A3 ->\n    ~A1 \\/ ~A2 \\/ ~A3 \\/ D ->\n    C1 \\/ C2 \\/ C3 \\/ D.\nProof. tauto. Qed.\n\nLemma resolution4: forall C1 A1 C2 A2 C3 A3 C4 A4 D,\n    C1 \\/ A1 ->\n    C2 \\/ A2 ->\n    C3 \\/ A3 ->\n    C4 \\/ A4 ->\n    ~A1 \\/ ~A2 \\/ ~A3 \\/ ~A4 \\/ D ->\n    C1 \\/ C2 \\/ C3 \\/ C4 \\/ D.\nProof. tauto. Qed.\n\nLemma resolution5: forall C1 A1 C2 A2 C3 A3 C4 A4 C5 A5 D,\n    C1 \\/ A1 ->\n    C2 \\/ A2 ->\n    C3 \\/ A3 ->\n    C4 \\/ A4 ->\n    C5 \\/ A5 ->\n    ~A1 \\/ ~A2 \\/ ~A3 \\/ ~A4 \\/ ~A5 \\/ D ->\n    C1 \\/ C2 \\/ C3 \\/ C4 \\/ C5 \\/ D.\nProof. tauto. Qed.\n\nLtac indexOf firstIndex default e l :=\n  match l with\n  | nil => default\n  | e :: _ => firstIndex\n  | _ :: ?rest => indexOf (firstIndex + 1) default e rest\n  end.\n\nLtac reify_lit env l :=\n  lazymatch l with\n  | ~ ?x => let r := indexOf 0 0 x env in constr:(-r)\n  | ?x => indexOf 0 0 x env\n  end.\n\nLtac reify_clause env c :=\n  lazymatch c with\n  | ?c1 \\/ ?c2 =>\n    let r1 := reify_clause env c1 in\n    let r2 := reify_clause env c2 in\n    constr:(r1 ++ r2)\n  | ?l =>\n    let r := reify_lit env l in\n    constr:([r])\n  end.\n\nFixpoint insert(lit: Z)(c: list Z): list Z :=\n  match c with\n  | nil => [lit]\n  | h :: t => match Z.compare (Z.abs lit) (Z.abs h) with\n              | Eq => if h =? lit then c (* x \\/ x \\/ rest *) else lit :: h :: nil (* x \\/ ~x *)\n              | Gt => h :: (insert lit t)\n              | Lt => lit :: h :: t\n              end\n  end.\n\nLemma interp_lit_neg: forall env l,\n    interp_lit env (- l) <-> ~ interp_lit env l.\nProof.\n  unfold interp_lit.\n  split; intros; destruct l; simpl in *; auto.\n  - admit.\n  - admit.\n  - apply NNPP. assumption.\nAdmitted.\n\nLemma insert_sound: forall env l c,\n    interp_clause env (insert l c) ->\n    interp_lit env l \\/ interp_clause env c.\nProof.\n  induction c; intros; simpl in *; auto.\n  destruct (Z.abs l ?= Z.abs a) eqn: E.\n  - apply Z.compare_eq in E.\n    destruct (a =? l) eqn: F.\n    + apply Z.eqb_eq in F. subst a. simpl in *.\n      right. exact H.\n    + apply Z.eqb_neq in F. assert (a = -l) by lia. subst a.\n      destruct c; rewrite interp_lit_neg;\n      destruct (classic (interp_lit env l)); auto.\n  - simpl in *.  exact H.\n  - simpl in *.\n    destruct (insert l c) eqn: F.\n    + destruct c eqn: G; auto.\n    + destruct c eqn: G.\n      * intuition idtac. simpl in *. contradiction.\n      * intuition idtac.\nQed.\n\nLemma insert_complete: forall env l c,\n    interp_lit env l \\/ interp_clause env c ->\n    interp_clause env (insert l c).\nProof.\n  induction c; intros; simpl in *; try solve [intuition idtac].\n  destruct (Z.abs l ?= Z.abs a) eqn: E.\n  - apply Z.compare_eq in E.\n    destruct (a =? l) eqn: F.\n    + apply Z.eqb_eq in F. subst a. simpl in *.\n      destruct c; tauto.\n    + apply Z.eqb_neq in F. assert (a = -l) by lia. subst a.\n      destruct c.  simpl in *. (*[simpl in *; contradiction|].\n      rewrite interp_lit_neg.\n      destruct (classic (interp_lit env l)); auto.\n  - simpl in *.  exact H.\n  - simpl in *.\n    destruct (insert l c) eqn: F.\n    + destruct c eqn: G; auto.\n    + destruct c eqn: G.\n      * intuition idtac. simpl in *. contradiction.\n      * intuition idtac.\nQed.\n*)\nAbort.\n\nGoal claim_unsat test1.\n  cbv -[not].\n  intros.\n  repeat match goal with\n         | H: _ /\\ _ |- _ => destruct H\n         end.\n  destruct (classic (x1 = True)).\n  - subst.\n    destruct (classic (x5 = True)).\n    + subst.\n      destruct (classic (x4 = False)).\n      * subst.\n        (* SAT *)\nAbort.\n\n\n(* TODO claim_sat *)\n\nGoal claim_unsat test1.\n  cbv -[not].\n  intros.\n  repeat match goal with\n         | H: _ /\\ _ |- _ => destruct H\n         end.\n  pose proof (resolution H1 H2). (* contains x5 and ~x5, so it's useless *) clear H4.\n  assert (H1': x4 \\/ x1 \\/ ~ x5) by tauto. clear H1.\n  assert (H3': ~x4 \\/ ~x3) by tauto. clear H3.\n  pose proof (resolution H1' H3') as H4.\n\n  match goal with\n  | H: _ = ?l |- _ => let res := indexOf 0 0 x4 l in let res' := eval cbv in res in idtac res'\n  end.\n\n  match goal with\n  | H: _ = ?env |- _ => let res := reify_lit env (~x3) in let res' := eval cbv in res in idtac res'\n  end.\n\n  match goal with\n  | H: _ = ?env |- _ =>\n    let T := type of H4 in\n    let res := reify_clause env T in let r := eval cbv in res in idtac r\n  end.\nAbort.\n\nExample test2 := (4, [\n  [ 1;  2; -3];\n  [-1; -2;  3];\n  [ 2;  3; -4];\n  [-2; -3;  4];\n  [ 1;  3;  4];\n  [-1; -3; -4];\n  [-1;  2;  4];\n  [ 1; -2; -4]\n]).\n\n(* from https://www.satcompetition.org/2013/certunsat.shtml *)\n\n(* resolution proof *)\nGoal claim_unsat test2.\n  cbv -[not].\n  intros.\n  repeat match goal with\n         | H: _ /\\ _ |- _ => destruct H\n         end.\n\n  (* 9  1  2  0 1 3 5 0 *)\n  assert (H9: x1 \\/ x2) by (clear -H1 H3 H5; tauto).\n  (* 10  1  0  9 4 5 8 0 *)\n  assert (H10: x1) by (clear -H9 H4 H5 H8; tauto).\n  (* 11  2  0  9 3 6 7 0 *)\n  assert (H11: x2) by (clear -H9 H3 H6 H7; tauto).\n  (* 12  0 10 11 2 4 6 0 *)\n  assert (H12: False) by (clear -H10 H11 H2 H4 H6; tauto).\n\n  exact H12.\nQed.\n\n(* RUP proof: would have to delete the \"clear\" clauses but then tauto is too slow *)\nGoal claim_unsat test2.\n  cbv -[not].\n  intros.\n  repeat match goal with\n         | H: _ /\\ _ |- _ => destruct H\n         end.\n  (* 1 2 0 *)\n  assert (H9: x1 \\/ x2) by (clear -H1 H3 H5; tauto).\n  (* 1 0 *)\n  assert (H10: x1) by (clear -H9 H4 H5 H8; tauto).\n  (* 2 0 *)\n  assert (H11: x2) by (clear -H9 H3 H6 H7; tauto).\n  (* 0 *)\n  assert (H12: False) by (clear -H10 H11 H2 H4 H6; tauto).\n\n  exact H12.\nQed.\n\n\n(* DRUP proof: deletion & reverse unit progagation (should not need the \"clear -...\" but tauto is too slow otherwise) *)\nGoal claim_unsat test2.\n  cbv -[not].\n  intros.\n  repeat match goal with\n         | H: _ /\\ _ |- _ => destruct H\n         end.\n  (*    1  2  0 *)\n  assert (H9: x1 \\/ x2) by (clear -H1 H3 H5; tauto).\n  (* d  1  2 -3 0 *)\n  clear H1.\n  (*    1  0 *)\n  assert (H10: x1) by (clear -H9 H4 H5 H8; tauto).\n  (* d  1  2  0 *)\n  (* clear H9. not sure if we can really clear that one?? *)\n  (* d  1  3  4 0 *)\n  clear H5.\n  (* d  1 -2 -4 0 *)\n  clear H8.\n  (*    2  0 *)\n  assert (H11: x2) by (clear -H9 H3 H6 H7; tauto).\n  (*    0 *)\n  assert (H12: False) by (clear -H10 H11 H2 H4 H6; tauto).\n\n  exact H12.\nQed.\n\n(* details of how resolution works *)\nGoal claim_unsat test2.\n  cbv -[not].\n  intros.\n  repeat match goal with\n         | H: _ /\\ _ |- _ => destruct H\n         end.\n\n  (* 9  1  2  0 1 3 5 0 *)\n  assert (H9: x1 \\/ x2). {\n    clear -H1 H3 H5.\n\n    assert (H1': ~x3 \\/ x1 \\/ x2) by (clear -H1; tauto).\n    assert (H3': x3 \\/ x2 \\/ ~ x4) by (clear -H3; tauto).\n    pose proof (resolution H3' H1') as H_1_3'. clear H1' H3'.\n    assert (H_1_3: x1 \\/ x2 \\/ ~x4) by (clear -H_1_3'; tauto). clear H_1_3'.\n\n    assert (H1': ~x3 \\/ x1 \\/ x2) by (clear -H1; tauto).\n    assert (H5': x3 \\/ x1 \\/ x4) by (clear -H5; tauto).\n    pose proof (resolution H5' H1') as H_1_5'. clear H1' H5'.\n    assert (H_1_5: x1 \\/ x2 \\/ x4) by (clear -H_1_5'; tauto). clear H_1_5'.\n\n    assert (H_1_3': ~x4 \\/ x1 \\/ x2) by (clear -H_1_3; tauto).\n    assert (H_1_5': x4 \\/ x1 \\/ x2) by (clear -H_1_5; tauto).\n    pose proof (resolution H_1_5' H_1_3') as H_1_3_5.\n    clear -H_1_3_5.\n    tauto.\n  }\n\n  (* 10  1  0  9 4 5 8 0 *)\n  assert (H10: x1). {\n    clear -H9 H4 H5 H8.\n    tauto.\n  }\n\n  (* 11  2  0  9 3 6 7 0 *)\n  assert (H11: x2) by (clear -H9 H3 H6 H7; tauto).\n  (* 12  0 10 11 2 4 6 0 *)\n  assert (H12: False) by (clear -H10 H11 H2 H4 H6; tauto).\n\n  exact H12.\nQed.\n\n(*\nLtac resolvent allvars on acc cl1 cl2 :=\n  match allvars with\n  | nil => acc\n  | on :: ?rest => resolvent rest on acc cl1 cl2\n  | ?v :: ?rest =>\n    lazymatch cl1 with\n    | context [~v] => resolvent rest on (~v \\/ acc) cl1 cl2\n    | context [ v] => resolvent rest on ( v \\/ acc) cl1 cl2\n    | _ => lazymatch cl2 with\n           | context [~v] => resolvent rest on (~v \\/ acc) cl1 cl2\n           | context [ v] => resolvent rest on ( v \\/ acc) cl1 cl2\n           | _ => resolvent rest on acc cl1 cl2\n           end\n    end\n  end.\n*)\nLtac resolvent allvars on cl1 cl2 :=\n  match allvars with\n  | nil => constr:(False)\n  | on :: ?rest => resolvent rest on cl1 cl2\n  | ?v :: ?rest =>\n    let r := resolvent rest on cl1 cl2 in\n    lazymatch cl1 with\n    | context [~v] => constr:(~v \\/ r)\n    | context [ v] => constr:( v \\/ r)\n    | _ => lazymatch cl2 with\n           | context [~v] => constr:(~v \\/ r)\n           | context [ v] => constr:( v \\/ r)\n           | _ => constr:(r)\n           end\n    end\n  end.\n\nLtac do_one_resolution :=\n  match goal with\n      | A: context[?X1], B: context[~?X1] |- _ =>\n        is_var X1;\n        (*idtac \"----\" A B \"on\" X1;*)\n        tryif (match type of A with\n               | context[?X2] =>\n                 is_var X2;\n                 tryif (unify X1 X2) then fail else\n                 (match type of B with\n                  | context[~ X2] => idtac (* \"no because\" X2 *)\n                  end)\n               end)\n        then fail\n        else\n          (tryif (match type of B with\n                  | context[?X2] =>\n                    is_var X2;\n                    tryif (unify X1 X2) then fail else\n                      (match type of A with\n                       | context[~ X2] => idtac (* \"no because\" X2 *)\n                       end)\n                  end)\n            then fail\n            else (idtac \"yes\" A B;\n                  lazymatch goal with\n                  | H: _ = ?env |- _ =>\n                    let P1 := type of A in\n                    let P2 := type of B in\n                    let res := resolvent env X1 P1 P2 in idtac res;\n                    lazymatch goal with\n                    | _: res |- _ => fail\n                    | |- _ => assert res by (clear -A B; tauto)\n                    end\n                  end))\n      end.\n\n\nGoal claim_unsat test2.\n  cbv -[not].\n  intros.\n  repeat match goal with\n         | H: _ /\\ _ |- _ => destruct H\n         end.\n  repeat do_one_resolution.\n  assumption.\nQed.\n", "meta": {"author": "samuelgruetter", "repo": "ltac-sat", "sha": "96447a3f627e5e8d8f29e6eff4353cf75d4e82ff", "save_path": "github-repos/coq/samuelgruetter-ltac-sat", "path": "github-repos/coq/samuelgruetter-ltac-sat/ltac-sat-96447a3f627e5e8d8f29e6eff4353cf75d4e82ff/LtacSat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6552200654561992}}
{"text": "(* This file is generated by Why3's Coq driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire int.Int.\nRequire list.List.\nRequire list.Length.\nRequire list.Mem.\nRequire list.Append.\n\n(* Why3 assumption *)\nDefinition unit := unit.\n\n(* Why3 assumption *)\nInductive tree :=\n  | Leaf : tree\n  | Node : tree -> tree -> tree.\nAxiom tree_WhyType : WhyType tree.\nExisting Instance tree_WhyType.\n\n(* Why3 assumption *)\nFixpoint depths (d:Z) (t:tree) {struct t}: (list Z) :=\n  match t with\n  | Leaf => (cons d nil)\n  | (Node l r) => (List.app (depths (d + 1%Z)%Z l) (depths (d + 1%Z)%Z r))\n  end.\n\nAxiom depths_head : forall (t:tree) (d:Z), match (depths d\n  t) with\n  | (cons x _) => (d <= x)%Z\n  | nil => False\n  end.\n\nAxiom depths_unique : forall (t1:tree) (t2:tree) (d:Z) (s1:(list Z))\n  (s2:(list Z)), ((List.app (depths d t1) s1) = (List.app (depths d\n  t2) s2)) -> ((t1 = t2) /\\ (s1 = s2)).\n\nAxiom depths_prefix : forall (t:tree) (d1:Z) (d2:Z) (s1:(list Z))\n  (s2:(list Z)), ((List.app (depths d1 t) s1) = (List.app (depths d2\n  t) s2)) -> (d1 = d2).\n\nAxiom depths_prefix_simple : forall (t:tree) (d1:Z) (d2:Z), ((depths d1\n  t) = (depths d2 t)) -> (d1 = d2).\n\nAxiom depths_subtree : forall (t1:tree) (t2:tree) (d1:Z) (d2:Z)\n  (s1:(list Z)), ((List.app (depths d1 t1) s1) = (depths d2 t2)) ->\n  (d2 <= d1)%Z.\n\nAxiom depths_unique2 : forall (t1:tree) (t2:tree) (d1:Z) (d2:Z), ((depths d1\n  t1) = (depths d2 t2)) -> ((d1 = d2) /\\ (t1 = t2)).\n\n(* Why3 assumption *)\nDefinition lex (x1:((list Z)* Z)%type) (x2:((list Z)* Z)%type): Prop :=\n  match x1 with\n  | (s1, d1) =>\n      match x2 with\n      | (s2, d2) => ((list.Length.length s1) < (list.Length.length s2))%Z \\/\n          (((list.Length.length s1) = (list.Length.length s2)) /\\ match (s1,\n          s2) with\n          | ((cons h1 _), (cons h2 _)) => ((d2 < d1)%Z /\\ (d1 <= h1)%Z) /\\\n              (h1 = h2)\n          | _ => False\n          end)\n      end\n  end.\n\n\n(* Why3 goal *)\nTheorem WP_parameter_build : forall (s:(list Z)), (forall (t:tree)\n  (s':(list Z)), ~ ((List.app (depths 0%Z t) s') = s)) -> forall (t:tree),\n  ~ ((depths 0%Z t) = s).\n(* Why3 intros s h1 t. *)\nintuition.\nreplace (depths 0 t) with (app (depths 0 t) nil) in H0.\napply (H _ _ H0).\napply Append.Append_l_nil.\nQed.\n\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/examples/vstte12_tree_reconstruction/vstte12_tree_reconstruction_WP_TreeReconstruction_WP_parameter_build_4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6552122561380653}}
{"text": "(** Catalan number via generating functions *)\n(******************************************************************************)\n(*       Copyright (C) 2019 Florent Hivert <florent.hivert@lri.fr>            *)\n(*                                                                            *)\n(*  Distributed under the terms of the GNU General Public License (GPL)       *)\n(*                                                                            *)\n(*    This code 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 GNU       *)\n(*    General Public License for more details.                                *)\n(*                                                                            *)\n(*  The full text of the GPL is available at:                                 *)\n(*                                                                            *)\n(*                  http://www.gnu.org/licenses/                              *)\n(******************************************************************************)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nFrom mathcomp Require Import fintype div bigop ssralg binomial rat ssrnum.\n\nRequire tfps.\nRequire Import auxresults fps.\n\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\nSection Catalan.\n\nVariable (C : nat -> nat).\n\nHypothesis C0 : C 0 = 1%N.\nHypothesis CS : forall n : nat, C n.+1 = \\sum_(i < n.+1) C i * C (n - i).\n\nLocal Definition Csimpl := (C0, CS, big_ord0, big_ord_recl).\nExample C1 : C 1 = 1.  Proof. by rewrite !Csimpl. Qed.\nExample C2 : C 2 = 2.  Proof. by rewrite !Csimpl. Qed.\nExample C3 : C 3 = 5.  Proof. by rewrite !Csimpl. Qed.\nExample C4 : C 4 = 14. Proof. by rewrite !Csimpl. Qed.\nExample C5 : C 5 = 42. Proof. by rewrite !Csimpl. Qed.\n\nImport GRing.Theory.\n\nLocal Definition Rat := [fieldType of rat].\nLocal Definition char_Rat := Num.Theory.char_num [numDomainType of Rat].\nLocal Definition nat_unit := tfps.TFPSField.nat_unit_field char_Rat.\nLocal Definition fact_unit := tfps.TFPSField.fact_unit char_Rat.\nHint Resolve char_Rat nat_unit : core.\n\nSection GenSeries.\n\nLocal Open Scope ring_scope.\nLocal Open Scope fps_scope.\n\nDefinition FC : {fps Rat} := \\fps (C i)%:R .X^i.\n\nLemma FC_in_coef0_eq1 : FC \\in coefs0_eq1.\nProof. by rewrite coefs0_eq1E coefs_FPSeries C0. Qed.\n\nProposition FC_algebraic_eq : FC = 1 + ''X * FC ^+ 2.\nProof.\nrewrite /FC; apply/fpsP => i.\nrewrite !(coefs_FPSeries, coefs_simpl, coef_fpsXM).\ncase: i => [|i]; first by rewrite C0 addr0.\nrewrite add0r CS /= expr2 coefsM natr_sum.\napply eq_bigr => [[j /= _]] _.\nby rewrite !coefs_FPSeries natrM.\nQed.\n\nEnd GenSeries.\n\n\n(** Extraction of the coefficient using square root and Newton's formula *)\nSection AlgebraicSolution.\n\nLocal Open Scope ring_scope.\nLocal Open Scope fps_scope.\n\nLemma mulr_nat i (f : {fps Rat}) : i%:R *: f = i%:R * f.\nProof. by rewrite scaler_nat -[f *+ i]mulr_natr mulrC. Qed.\n\nTheorem FC_algebraic_solution :\n  ''X * FC = 2%:R^-1 *: (1 - \\sqrt (1 - 4%:R *: ''X)).\nProof.\nhave co1 : 1 - 4%:R *: ''X \\in @coefs0_eq1 Rat.\n  by rewrite mulr_nat coefs0_eq1E !coefs_simpl mulrC coef_fpsXM subr0.\nhave: (2%:R *: ''X * FC - 1) ^+ 2 = 1 - 4%:R *: ''X.\n  apply/eqP; rewrite !mulr_nat sqrrB1 !exprMn 2!expr2 -natrM.\n  rewrite mulrA -subr_eq0 opprB [_ - 1]addrC addrA addrK addrC addrA.\n  rewrite -{1}(mulr1 (4%:R * _)) -[X in _ + X + _]mulrA -mulrDr.\n  rewrite -FC_algebraic_eq.\n  by rewrite -[_ *+ 2]mulr_natl !mulrA -natrM subrr.\nmove/(sqrtE nat_unit) => /(_ co1) [HeqP | HeqN].\n  exfalso; move: HeqP => /(congr1 (fun x => x``_0)).\n  rewrite mulr_nat coefsB -mulrA mulrC -mulrA coef_fpsXM coefs1.\n  rewrite (eqP (coefs0_eq1_expr _ _)) /= => /eqP.\n  rewrite -subr_eq0 add0r -oppr_eq0 opprD opprK -mulr2n => /eqP Habs.\n  by have:= char_Rat 2; rewrite !inE Habs /= eq_refl.\nhave neq20 : 2%:R != 0 :> Rat by rewrite Num.Theory.pnatr_eq0.\napply (scalerI neq20); rewrite scalerA divff // scale1r -HeqN.\nby rewrite addrC subrK scalerAl.\nQed.\n\nTheorem coefFC i : FC``_i = i.*2`!%:R / i`!%:R /i.+1`!%:R.\nProof.\nhave:= congr1 (fun x => x``_i.+1) FC_algebraic_solution.\nrewrite coef_fpsXM ![X in (X = _)]/= => ->.\nrewrite coefsZ coefsB coefs1 sub0r -scaleNr coef_expr1cX ?{}Hi //.\nrewrite mulrN mulrA -mulNr; congr (_ / (i.+1)`!%:R).\nrewrite -[4]/(2 * 2)%N mulrnA -mulNrn -[(1 *- 2 *+ 2)]mulr_natl.\nrewrite exprMn -mulrA.\nhave -> : (1 *- 2)^+ i.+1 = \\prod_(i0 < i.+1) (1 *- 2) :> rat.\n  by rewrite prodr_const /= card_ord.\nrewrite -big_split /= big_ord_recl /=.\nrewrite subr0 mulNr divrr // mulN1r 2!mulrN [LHS]opprK.\nrewrite exprS !mulrA [2%:R^-1 * 2%:R]mulVf // mul1r.\nrewrite (eq_bigr (fun j : 'I_i => (2 * j + 1)%:R)) /=; last first.\n  move=> j _; rewrite /bump /=.\n  rewrite mulNr -mulrN opprD addrC opprK addnC natrD 2!mulrDr.\n  rewrite mulrN divff // mulr1 -{2}addn1 {2}natrD addrA addrK.\n  by rewrite natrD natrM.\nelim: i => [|i IHi]; first by rewrite expr0 big_ord0 double0 fact0 mulr1.\nrewrite big_ord_recr /= exprS -mulrA mulrC mulrA {}IHi.\nrewrite doubleS !factS 3!natrM.\nset F := (i.*2)`!%:R; rewrite [_ * F]mulrC mulrA [_ * F]mulrC -!mulrA.\ncongr (_ * _); rewrite {F} mulrC invfM // !mulrA; congr (_ * _).\nrewrite mul2n -{2}[i.*2.+1]addn1 [X in X / _]mulrC -mulrA; congr (_ * _).\nrewrite -[i.*2.+2]addn1 addSnnS -mul2n -[X in (_ + X)%N]muln1.\nrewrite -mulnDr addn1 natrM mulfK //.\nby have /charf0P -> := char_Rat.\nQed.\n\nTheorem Cat_rat i : (C i)%:R = i.*2`!%:R / i`!%:R /i.+1`!%:R :> Rat.\nProof. by rewrite -coefFC coefs_FPSeries. Qed.\n\nLocal Close Scope ring_scope.\n\nTheorem CatM i : C i * i`! * i.+1`! = i.*2`!.\nProof.\nhave:= Cat_rat i.\nmove/(congr1 (fun x => x * (i.+1)`!%:R * i`!%:R)%R).\nrewrite (divrK (fact_unit i.+1)) (divrK (fact_unit i)) // -!natrM => /eqP.\nrewrite Num.Theory.eqr_nat => /eqP <-.\nby rewrite -[RHS]mulnA [_`! * i`!]mulnC mulnA.\nQed.\n\nTheorem CatV i : C i = i.*2`! %/ (i`! * i.+1`!).\nProof.\nhave:= CatM i; rewrite -mulnA => /(congr1 (fun j => j %/ (i`! * (i.+1)`!))).\nby rewrite mulnK // muln_gt0 !fact_gt0.\nQed.\n\nTheorem Cat i : C i = 'C(i.*2, i) %/ i.+1.\nProof.\ncase: (ltnP 0 i)=> [Hi|]; last first.\n  by rewrite leqn0 => /eqP ->; rewrite C0 bin0 divn1.\nrewrite (CatV i) factS [i.+1 * _]mulnC mulnA.\nby rewrite -{3}(addnK i i) addnn divnMA bin_factd // double_gt0.\nQed.\n\nEnd AlgebraicSolution.\n\n\n(** Extraction of the coefficient using Lagrange inversion formula *)\nSection LagrangeSolution.\n\nLocal Open Scope ring_scope.\nLocal Open Scope tfps_scope.\n\nLemma one_plusX_2_unit : ((1 + ''X) ^+ 2 : {fps Rat}) \\is a GRing.unit.\nProof.\nrewrite unit_fpsE coefs0M coefsD coefs1.\nby rewrite coef_fpsX addr0 mulr1.\nQed.\n\nProposition FC_fixpoint_eq : FC - 1 = lagrfix ((1 + ''X) ^+ 2).\nProof.\napply: (lagrfix_uniq one_plusX_2_unit).\nrewrite {1}FC_algebraic_eq -addrA addrC subrK.\nrewrite rmorphX rmorphD /= comp_fps1 comp_fpsX //; first last.\n  rewrite coefs0_eq0E coefsB coefs1.\n  by rewrite coefs_FPSeries /= C0 subrr.\nby rewrite addrC subrK.\nQed.\n\nTheorem CatM_Lagrange i : (i.+1 * (C i))%N = 'C(i.*2, i).\nProof.\ncase: i => [|i]; first by rewrite C0 mul1n bin0.\napply/eqP; rewrite -(Num.Theory.eqr_nat [numDomainType of Rat]); rewrite natrM.\nhave:= (congr1 (fun s => s``_i.+1) FC_fixpoint_eq).\nrewrite coefsD coefs_FPSeries.\nrewrite coefsN coefs1 subr0 /= => ->.\nrewrite (coefs_lagrfix nat_unit) ?one_plusX_2_unit //.\nrewrite -exprM mul2n addrC exprD1n coefs_sum.\nhave Hord : (i < (i.+1).*2.+1)%N.\n  by rewrite ltnS doubleS -addnn -!addnS leq_addr.\nrewrite (bigD1 (Ordinal Hord)) //= -!/(_`_i.+1).\nrewrite coefsMn coef_fpsXn // eqxx /=.\nrewrite big1 ?addr0 => [|[j /= Hj]]; first last.\n  rewrite -val_eqE /= => {Hj} /negbTE Hj.\n  by rewrite coefsMn coef_fpsXn eq_sym Hj mul0rn.\nrewrite ltnS in Hord.\nrewrite -bin_sub // -{2}addnn -addSnnS addnK.\nby rewrite mulrA -natrM mul_bin_left -addnn addnK natrM mulrC mulKr.\nQed.\n\nLocal Close Scope ring_scope.\n\nTheorem Cat_Lagrange i : C i = 'C(i.*2, i) %/ i.+1.\nProof.\nby have:= congr1 (fun m => m %/ i.+1) (CatM_Lagrange i); rewrite mulnC mulnK.\nQed.\n\nEnd LagrangeSolution.\n\n\n(** Extraction of the coefficient using Holonomic differential equation *)\nSection HolonomicSolution.\n\nLocal Open Scope ring_scope.\nLocal Open Scope fps_scope.\n\nProposition FC_differential_eq :\n  (1 - ''X *+ 2) * FC + (1 - ''X *+ 4) * ''X * FC^`()%fps = 1.\nProof.\nhave X2Fu : (1 - ''X *+ 2 * FC) \\is a GRing.unit.\n  rewrite unit_fpsE coefsB coefs1.\n  by rewrite mulrnAl coefsMn coef_fpsXM.\nrewrite -mulrA.\nhave FalgN : ''X * FC ^+ 2 = FC - 1.\n  by apply/eqP; rewrite eq_sym subr_eq addrC -FC_algebraic_eq.\nhave -> : ''X * FC^`()%fps = (FC - 1)/(1 - ''X *+ 2 * FC).\n  rewrite -[LHS]divr1; apply/eqP.\n  rewrite (eq_divr (''X * _)) ?unitr1 // ?X2Fu // mulr1.\n  have /= := congr1 ((fun s => ''X * s) \\o (@deriv_fps _)) FC_algebraic_eq.\n  rewrite derivD_fps deriv_fps1 add0r.\n  rewrite derivM_fps /= deriv_fpsX mul1r derivX_fps /= expr1.\n  rewrite mulrDr FalgN => /eqP; rewrite -(subr_eq _ _ (''X * _)) => /eqP <-.\n  rewrite mulrBr mulr1 -!mulrA; apply/eqP; congr (_ - ''X * _).\n  by rewrite !(mulrnAr, mulrnAl) mulrC mulrA.\nrewrite mulrA -[X in X + _](mulrK X2Fu) -mulrDl -[RHS]divr1.\napply/eqP; rewrite eq_divr ?unitr1 // mulr1 mul1r.\nrewrite -mulrA [FC * _]mulrC [(1 - _ * FC) * FC]mulrBl -mulrA -expr2.\nrewrite mul1r mulrnAl FalgN.\nrewrite !mulrnBl opprB addrA (mulr2n FC) (opprD FC) addrA.\nrewrite [_ - FC]addrC 2!addrA [-FC + _]addrC subrr add0r.\nrewrite !mulrBr mulr1 addrA addrC !addrA.\nrewrite opprB mulrBl mul1r mulr_natr -mulrnA -[(2 * 2)%N]/4.\nrewrite [''X *+ 4 - 1 + _]addrC addrA subrK addrK.\nrewrite -addrA -mulNr -mulrDl.\nrewrite opprD [-1 + _]addrC addrA subrK -opprD mulNr.\nrewrite -[4]/(2 + 2)%N mulrnDr addrA.\nby rewrite [_ *- _ + _]addrC subrK.\nQed.\n\nLocal Close Scope ring_scope.\nLocal Close Scope tfps_scope.\n\nProposition Catalan_rec n : n.+2 * C (n.+1) = (4 * n + 2) * C n.\nProof.\nhave := congr1 (fun x => (x``_n.+1)%R) FC_differential_eq.\nrewrite coefs1 coefsD !mulrDl !mul1r !coefsD.\nrewrite -!mulNrn !(mulrnAl, coefsMn, mulNr, coefsN).\nrewrite -mulrA !coef_fpsXM /= !coef_deriv_fps !coefs_FPSeries.\ncase: n => [|n] /=; first by rewrite !Csimpl.\nmove: {n} n.+1 => n; move: (C n.+1) (C n) => Cn1 Cn.\nrewrite !mulNrn addrA [X in (X - _)%R]addrC addrA -mulrSr -!mulrnA.\nmove/eqP; rewrite subr_eq add0r subr_eq -natrD Num.Theory.eqr_nat => /eqP.\nrewrite mulnC -mulnDr => ->.\nby rewrite mulnC [n * 4]mulnC.\nQed.\n\nTheorem CatM_from_rec n : n.+1 * C n = 'C(n.*2, n).\nProof.\nelim: n => [| n IHn] /=; first by rewrite C0 bin0.\nrewrite Catalan_rec doubleS !binS.\nhave leq_n2 : n <= n.*2 by rewrite -addnn leq_addr.\nrewrite -[X in _ + _ + X]bin_sub; last exact: (leq_trans leq_n2 (leqnSn _)).\nrewrite subSn // -{4}addnn addnK binS addnn.\nrewrite addn2 -[4]/(2 * 2) -mulnA !mul2n -doubleS -doubleMl; congr _.*2.\nrewrite -IHn -{1}addnn -addnS mulnDl; congr (_ + _).\nhave:= mul_bin_down n.*2 n.\nrewrite mul_bin_diag -{2}addnn addnK -{}IHn mulnA [n * n.+1]mulnC.\nrewrite -mulnA ![n.+1 * _]mulnC => /(congr1 (fun m => m %/ n.+1)).\nby rewrite !mulnK.\nQed.\n\nTheorem Cat_from_rec i : C i = 'C(i.*2, i) %/ i.+1.\nProof.\nby have:= congr1 (fun m => m %/ i.+1) (CatM_from_rec i); rewrite mulnC mulnK.\nQed.\n\nEnd HolonomicSolution.\n\nEnd Catalan.\n", "meta": {"author": "hivert", "repo": "FormalPowerSeries", "sha": "a138e2c5dc8da635ab2d7bd37aed35831850296f", "save_path": "github-repos/coq/hivert-FormalPowerSeries", "path": "github-repos/coq/hivert-FormalPowerSeries/FormalPowerSeries-a138e2c5dc8da635ab2d7bd37aed35831850296f/theories/catalan_fps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6552122383574477}}
{"text": "(* mathcomp analysis (c) 2017 Inria and AIST. License: CeCILL-C.              *)\nFrom mathcomp Require Import all_ssreflect ssralg ssrnum ssrint interval.\nFrom mathcomp Require Import finmap fingroup perm rat.\nFrom mathcomp.classical Require Import boolp classical_sets functions.\nFrom mathcomp.classical Require Import cardinality fsbigop mathcomp_extra.\nRequire Import reals ereal signed topology numfun normedtype.\nFrom HB Require Import structures.\nRequire Import sequences esum measure real_interval realfun exp.\n\n(******************************************************************************)\n(*                            Lebesgue Measure                                *)\n(*                                                                            *)\n(* This file contains a formalization of the Lebesgue measure using the       *)\n(* Caratheodory's theorem available in measure.v and further develops the     *)\n(* theory of measurable functions.                                            *)\n(*                                                                            *)\n(* Main reference:                                                            *)\n(* - Daniel Li, Intégration et applications, 2016                             *)\n(* - Achim Klenke, Probability Theory 2nd edition, 2014                       *)\n(*                                                                            *)\n(*             hlength A == length of the hull of the set of real numbers A   *)\n(*                 ocitv == set of open-closed intervals ]x, y] where         *)\n(*                            x and y are real numbers                        *)\n(*      lebesgue_measure == the Lebesgue measure                              *)\n(*                                                                            *)\n(*              ps_infty == inductive definition of the powerset              *)\n(*                          {0, {-oo}, {+oo}, {-oo,+oo}}                      *)\n(*         emeasurable G == sigma-algebra over \\bar R built out of the        *)\n(*                          measurables G of a sigma-algebra over R           *)\n(*     elebesgue_measure == the Lebesgue measure extended to \\bar R           *)\n(*                                                                            *)\n(* The modules RGenOInfty, RGenInftyO, RGenCInfty, RGenOpens provide proofs   *)\n(* of equivalence between the sigma-algebra generated by list of intervals    *)\n(* and the sigma-algebras generated by open rays, closed rays, and open       *)\n(* intervals.                                                                 *)\n(*                                                                            *)\n(* The modules ErealGenOInfty, ErealGenCInfty, ErealGenInftyO provide proofs  *)\n(* of equivalence between emeasurable and the sigma-algebras generated open   *)\n(* rays and closed rays.                                                      *)\n(*                                                                            *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nImport Order.TTheory GRing.Theory Num.Def Num.Theory.\nImport numFieldTopology.Exports.\n\nLocal Open Scope classical_set_scope.\nLocal Open Scope ring_scope.\n\nReserved Notation \"R .-ocitv\" (at level 1, format \"R .-ocitv\").\nReserved Notation \"R .-ocitv.-measurable\"\n (at level 2, format \"R .-ocitv.-measurable\").\n\nSection hlength.\nLocal Open Scope ereal_scope.\nVariable R : realType.\nImplicit Types i j : interval R.\n\nDefinition hlength (A : set R) : \\bar R := let i := Rhull A in i.2 - i.1.\n\nLemma hlength0 : hlength (set0 : set R) = 0.\nProof. by rewrite /hlength Rhull0 /= subee. Qed.\n\nLemma hlength_singleton (r : R) : hlength `[r, r] = 0.\nProof.\nrewrite /hlength /= asboolT// sup_itvcc//= asboolT//.\nby rewrite asboolT inf_itvcc//= ?subee// inE.\nQed.\n\nLemma hlength_setT : hlength setT = +oo%E :> \\bar R.\nProof. by rewrite /hlength RhullT. Qed.\n\nLemma hlength_itv i : hlength [set` i] = if i.2 > i.1 then i.2 - i.1 else 0.\nProof.\ncase: ltP => [/lt_ereal_bnd/neitvP i12|]; first by rewrite /hlength set_itvK.\nrewrite le_eqVlt => /orP[|/lt_ereal_bnd i12]; last first.\n  rewrite (_ : [set` i] = set0) ?hlength0//.\n  by apply/eqP/negPn; rewrite -/(neitv _) neitvE -leNgt (ltW i12).\ncase: i => -[ba a|[|]] [bb b|[|]] //=.\n- rewrite /= => /eqP[->{b}]; move: ba bb => -[] []; try\n    by rewrite set_itvE hlength0.\n  by rewrite hlength_singleton.\n- by move=> _; rewrite set_itvE hlength0.\n- by move=> _; rewrite set_itvE hlength0.\nQed.\n\nLemma hlength_finite_fin_num i : neitv i -> hlength [set` i] < +oo ->\n  ((i.1 : \\bar R) \\is a fin_num) /\\ ((i.2 : \\bar R) \\is a fin_num).\nProof.\nmove: i => [[ba a|[]] [bb b|[]]] /neitvP //=; do ?by rewrite ?set_itvE ?eqxx.\nby move=> _; rewrite hlength_itv /= ltry.\nby move=> _; rewrite hlength_itv /= ltNyr.\nby move=> _; rewrite hlength_itv.\nQed.\n\nLemma finite_hlengthE i : neitv i -> hlength [set` i] < +oo ->\n  hlength [set` i] = (fine i.2)%:E - (fine i.1)%:E.\nProof.\nmove=> i0 ioo; have [ri1 ri2] := hlength_finite_fin_num i0 ioo.\nrewrite !fineK// hlength_itv; case: ifPn => //.\nrewrite -leNgt le_eqVlt => /predU1P[->|]; first by rewrite subee.\nby move/lt_ereal_bnd/ltW; rewrite leNgt; move: i0 => /neitvP => ->.\nQed.\n\nLemma hlength_infty_bnd b r :\n  hlength [set` Interval -oo%O (BSide b r)] = +oo :> \\bar R.\nProof. by rewrite hlength_itv /= ltNyr. Qed.\n\nLemma hlength_bnd_infty b r :\n  hlength [set` Interval (BSide b r) +oo%O] = +oo :> \\bar R.\nProof. by rewrite hlength_itv /= ltry. Qed.\n\nLemma pinfty_hlength i : hlength [set` i] = +oo ->\n  (exists s r, i = Interval -oo%O (BSide s r) \\/ i = Interval (BSide s r) +oo%O)\n  \\/ i = `]-oo, +oo[.\nProof.\nrewrite hlength_itv; case: i => -[ba a|[]] [bb b|[]] //= => [|_|_|].\n- by case: ifPn.\n- by left; exists ba, a; right.\n- by left; exists bb, b; left.\n- by right.\nQed.\n\nLemma hlength_ge0 i : 0 <= hlength [set` i].\nProof.\nrewrite hlength_itv; case: ifPn => //; case: (i.1 : \\bar _) => [r| |].\n- by rewrite suber_ge0//; exact: ltW.\n- by rewrite ltNge leey.\n- by case: (i.2 : \\bar _) => //= [r _]; rewrite leey.\nQed.\nLocal Hint Extern 0 (0%:E <= hlength _) => solve[apply: hlength_ge0] : core.\n\nLemma hlength_Rhull (A : set R) : hlength [set` Rhull A] = hlength A.\nProof. by rewrite /hlength Rhull_involutive. Qed.\n\nLemma le_hlength_itv i j : {subset i <= j} -> hlength [set` i] <= hlength [set` j].\nProof.\nset I := [set` i]; set J := [set` j].\nhave [->|/set0P I0] := eqVneq I set0; first by rewrite hlength0 hlength_ge0.\nhave [J0|/set0P J0] := eqVneq J set0.\n  by move/subset_itvP; rewrite -/J J0 subset0 -/I => ->.\nmove=> /subset_itvP ij; apply: lee_sub => /=.\n  have [ui|ui] := asboolP (has_ubound I).\n    have [uj /=|uj] := asboolP (has_ubound J); last by rewrite leey.\n    by rewrite lee_fin le_sup // => r Ir; exists r; split => //; apply: ij.\n  have [uj /=|//] := asboolP (has_ubound J).\n  by move: ui; have := subset_has_ubound ij uj.\nhave [lj /=|lj] := asboolP (has_lbound J); last by rewrite leNye.\nhave [li /=|li] := asboolP (has_lbound I); last first.\n  by move: li; have := subset_has_lbound ij lj.\nrewrite lee_fin ler_oppl opprK le_sup// ?has_inf_supN//; last exact/nonemptyN.\nmove=> r [r' Ir' <-{r}]; exists (- r')%R.\nby split => //; exists r' => //; apply: ij.\nQed.\n\nLemma le_hlength : {homo hlength : A B / (A `<=` B) >-> A <= B}.\nProof.\nmove=> a b /le_Rhull /le_hlength_itv.\nby rewrite (hlength_Rhull a) (hlength_Rhull b).\nQed.\n\nEnd hlength.\nArguments hlength {R}.\n#[global] Hint Extern 0 (0%:E <= hlength _) => solve[apply: hlength_ge0] : core.\n\nSection itv_semiRingOfSets.\nVariable R : realType.\nImplicit Types (I J K : set R).\nDefinition ocitv_type : Type := R.\n\nDefinition ocitv := [set `]x.1, x.2]%classic | x in [set: R * R]].\n\nLemma is_ocitv a b : ocitv `]a, b]%classic.\nProof. by exists (a, b); split => //=; rewrite in_itv/= andbT. Qed.\nHint Extern 0 (ocitv _) => solve [apply: is_ocitv] : core.\n\nLemma ocitv0 : ocitv set0.\nProof. by exists (1, 0); rewrite //= set_itv_ge ?bnd_simp//= ltr10. Qed.\nHint Resolve ocitv0 : core.\n\nLemma ocitvP X : ocitv X <-> X = set0 \\/ exists2 x, x.1 < x.2 & X = `]x.1, x.2]%classic.\nProof.\nsplit=> [[x _ <-]|[->//|[x xlt ->]]]//.\ncase: (boolP (x.1 < x.2)) => x12; first by right; exists x.\nby left; rewrite set_itv_ge.\nQed.\n\nLemma ocitvD : semi_setD_closed ocitv.\nProof.\nmove=> _ _ [a _ <-] /ocitvP[|[b ltb]] ->.\n  rewrite setD0; exists [set `]a.1, a.2]%classic].\n  by split=> [//|? ->//||? ? -> ->//]; rewrite bigcup_set1.\nrewrite setDE setCitv/= setIUr -!set_itvI.\nrewrite /Order.meet/= /Order.meet/= /Order.join/=\n         ?(andbF, orbF)/= ?(meetEtotal, joinEtotal).\nrewrite -negb_or le_total/=; set c := minr _ _; set d := maxr _ _.\nhave inside : a.1 < c -> d < a.2 -> `]a.1, c] `&` `]d, a.2] = set0.\n  rewrite -subset0 lt_minr lt_maxl => /andP[a12 ab1] /andP[_ ba2] x /= [].\n  have b1a2 : b.1 <= a.2 by rewrite ltW// (lt_trans ltb).\n  have a1b2 : a.1 <= b.2 by rewrite ltW// (lt_trans _ ltb).\n  rewrite /c /d (min_idPr _)// (max_idPr _)// !in_itv /=.\n  move=> /andP[a1x xb1] /andP[b2x xa2].\n  by have := lt_le_trans b2x xb1; case: ltgtP ltb.\nexists ((if a.1 < c then [set `]a.1, c]%classic] else set0) `|`\n        (if d < a.2 then [set `]d, a.2]%classic] else set0)); split.\n- by rewrite finite_setU; do! case: ifP.\n- by move=> ? []; case: ifP => ? // ->//=.\n- by rewrite bigcup_setU; congr (_ `|` _);\n     case: ifPn => ?; rewrite ?bigcup_set1 ?bigcup_set0// set_itv_ge.\n- move=> I J/=; case: ifP => //= ac; case: ifP => //= da [] // -> []// ->.\n    by rewrite inside// => -[].\n  by rewrite setIC inside// => -[].\nQed.\n\nLemma ocitvI : setI_closed ocitv.\nProof.\nmove=> _ _ [a _ <-] [b _ <-]; rewrite -set_itvI/=.\nrewrite /Order.meet/= /Order.meet /Order.join/=\n        ?(andbF, orbF)/= ?(meetEtotal, joinEtotal).\nby rewrite -negb_or le_total/=.\nQed.\n\nDefinition ocitv_display : Type -> measure_display. Proof. exact. Qed.\n\nHB.instance Definition _ :=\n  @isSemiRingOfSets.Build (ocitv_display R)\n    ocitv_type (Pointed.class R) ocitv ocitv0 ocitvI ocitvD.\n\nNotation \"R .-ocitv\" := (ocitv_display R) : measure_display_scope.\nNotation \"R .-ocitv.-measurable\" := (measurable : set (set (ocitv_type))) :\n  classical_set_scope.\n\nLemma hlength_ge0' (I : set ocitv_type) : (0 <= hlength I)%E.\nProof. by rewrite -hlength0 le_hlength. Qed.\n\n(* Unused *)\n(* Lemma hlength_semi_additive2 : semi_additive2 hlength. *)\n(* Proof. *)\n(* move=> I J /ocitvP[|[a a12]] ->; first by rewrite set0U hlength0 add0e. *)\n(* move=> /ocitvP[|[b b12]] ->; first by rewrite setU0 hlength0 adde0. *)\n(* rewrite -subset0 => + ab0 => /ocitvP[|[x x12] abx]. *)\n(*   by rewrite setU_eq0 => -[-> ->]; rewrite setU0 hlength0 adde0. *)\n(* rewrite abx !hlength_itv//= ?lte_fin a12 b12 x12/= -!EFinB -EFinD. *)\n(* wlog ab1 : a a12 b b12 ab0 abx / a.1 <= b.1 => [hwlog|]. *)\n(*   have /orP[ab1|ba1] := le_total a.1 b.1; first by apply: hwlog. *)\n(*   by rewrite [in RHS]addrC; apply: hwlog => //; rewrite (setIC, setUC). *)\n(* have := ab0; rewrite subset0 -set_itv_meet/=. *)\n(* rewrite /Order.join /Order.meet/= ?(andbF, orbF)/= ?(meetEtotal, joinEtotal). *)\n(* rewrite -negb_or le_total/=; set c := minr _ _; set d := maxr _ _. *)\n(* move=> /eqP/neitvP/=; rewrite bnd_simp/= /d/c (max_idPr _)// => /negP. *)\n(* rewrite -leNgt le_minl orbC lt_geF//= => {c} {d} a2b1. *)\n(* have ab i j : i \\in `]a.1, a.2] -> j \\in `]b.1, b.2] -> i <= j. *)\n(*   by move=> ia jb; rewrite (le_le_trans _ _ a2b1) ?(itvP ia) ?(itvP jb). *)\n(* have /(congr1 sup) := abx; rewrite sup_setU// ?sup_itv_bounded// => bx. *)\n(* have /(congr1 inf) := abx; rewrite inf_setU// ?inf_itv_bounded// => ax. *)\n(* rewrite -{}ax -{x}bx in abx x12 *. *)\n(* case: ltgtP a2b1 => // a2b1 _; last first. *)\n(*   by rewrite a2b1 [in RHS]addrC subrKA. *)\n(* exfalso; pose c := (a.2 + b.1) / 2%:R. *)\n(* have /predeqP/(_ c)[_ /(_ _)/Box[]] := abx. *)\n(*   apply: subset_itv_oo_oc; have := mid_in_itvoo a2b1. *)\n(*   by apply/subitvP; rewrite subitvE ?bnd_simp/= ?ltW. *)\n(* apply/not_orP; rewrite /= !in_itv/=. *)\n(* by rewrite lt_geF ?midf_lt//= andbF le_gtF ?midf_le//= ltW. *)\n(* Qed. *)\n\nLemma hlength_semi_additive : semi_additive (hlength : set ocitv_type -> _).\nProof.\nmove=> /= I n /(_ _)/cid2-/all_sig[b]/all_and2[_]/(_ _)/esym-/funext {I}->.\nmove=> Itriv [[/= a1 a2] _] /esym /[dup] + ->.\nrewrite hlength_itv ?lte_fin/= -EFinB.\ncase: ifPn => a12; last first.\n  pose I i :=  `](b i).1, (b i).2]%classic.\n  rewrite set_itv_ge//= -(bigcup_mkord _ I) /I => /bigcup0P I0.\n  by under eq_bigr => i _ do rewrite I0//= hlength0; rewrite big1.\nset A := `]a1, a2]%classic.\nrewrite -bigcup_pred; set P := xpredT; rewrite (eq_bigl P)//.\nmove: P => P; have [p] := ubnP #|P|; elim: p => // p IHp in P a2 a12 A *.\nrewrite ltnS => cP /esym AE.\nhave : A a2 by rewrite /A /= in_itv/= lexx andbT.\nrewrite AE/= => -[i /= Pi] a2bi.\ncase: (boolP ((b i).1 < (b i).2)) => bi; last by rewrite itv_ge in a2bi.\nhave {}a2bi : a2 = (b i).2.\n  apply/eqP; rewrite eq_le (itvP a2bi)/=.\n  suff: A (b i).2 by move=> /itvP->.\n  by rewrite AE; exists i=> //=; rewrite in_itv/= lexx andbT.\nrewrite {a2}a2bi in a12 A AE *.\nrewrite (bigD1 i)//= hlength_itv ?lte_fin/= bi !EFinD -addeA.\ncongr (_ + _)%E; apply/eqP; rewrite addeC -sube_eq// 1?adde_defC//.\nrewrite ?EFinN oppeK addeC; apply/eqP.\ncase: (eqVneq a1 (b i).1) => a1bi.\n  rewrite {a1}a1bi in a12 A AE {IHp} *; rewrite subee ?big1// => j.\n  move=> /andP[Pj Nji]; rewrite hlength_itv ?lte_fin/=; case: ifPn => bj//.\n  exfalso; have /trivIsetP/(_ j i I I Nji) := Itriv.\n  pose m := ((b j).1 + (b j).2) / 2%:R.\n  have mbj : `](b j).1, (b j).2]%classic m.\n     by rewrite /= !in_itv/= ?(midf_lt, midf_le)//= ltW.\n  rewrite -subset0 => /(_ m); apply; split=> //.\n  by suff: A m by []; rewrite AE; exists j => //.\nhave a1b2 j : P j -> (b j).1 < (b j).2 -> a1 <= (b j).2.\n  move=> Pj bj; suff /itvP-> : A (b j).2 by [].\n  by rewrite AE; exists j => //=; rewrite ?in_itv/= bj//=.\nhave a1b j : P j -> (b j).1 < (b j).2 -> a1 <= (b j).1.\n  move=> Pj bj; case: ltP=> // bj1a.\n  suff : A a1 by rewrite /A/= in_itv/= ltxx.\n  by rewrite AE; exists j; rewrite //= in_itv/= bj1a//= a1b2.\nhave bbi2 j : P j -> (b j).1 < (b j).2 -> (b j).2 <= (b i).2.\n  move=> Pj bj; suff /itvP-> : A (b j).2 by [].\n  by rewrite AE; exists j => //=; rewrite ?in_itv/= bj//=.\napply/IHp.\n- by rewrite lt_neqAle a1bi/= a1b.\n- rewrite (leq_trans _ cP)// -(cardID (pred1 i) P).\n  rewrite [X in (_ < X + _)%N](@eq_card _ _ (pred1 i)); last first.\n    by move=> j; rewrite !inE andbC; case: eqVneq => // ->.\n  rewrite ?card1 ?ltnS// subset_leq_card//.\n  by apply/fintype.subsetP => j; rewrite -topredE/= !inE andbC.\napply/seteqP; split=> /= [x [j/= /andP[Pj Nji]]|x/= xabi].\n  case: (boolP ((b j).1 < (b j).2)) => bj; last by rewrite itv_ge.\n  apply: subitvP; rewrite subitvE ?bnd_simp a1b//= leNgt.\n  have /trivIsetP/(_ j i I I Nji) := Itriv.\n  rewrite -subset0 => /(_ (b j).2); apply: contra_notN => /= bi1j2.\n  by rewrite !in_itv/= bj !lexx bi1j2 bbi2.\nhave: A x.\n  rewrite /A/= in_itv/= (itvP xabi)/= ltW//.\n  by rewrite (le_lt_trans _ bi) ?(itvP xabi).\nrewrite AE => -[j /= Pj xbj].\nexists j => //=.\napply/andP; split=> //; apply: contraTneq xbj => ->.\nby rewrite in_itv/= le_gtF// (itvP xabi).\nQed.\n\nHB.instance Definition _ := isContent.Build _ _ R\n  (hlength : set ocitv_type -> _) (@hlength_ge0') hlength_semi_additive.\n\nHint Extern 0 ((_ .-ocitv).-measurable _) => solve [apply: is_ocitv] : core.\n\nLemma hlength_sigma_sub_additive :\n  sigma_sub_additive (hlength : set ocitv_type -> _).\nProof.\nmove=> I A /(_ _)/cid2-/all_sig[b]/all_and2[_]/(_ _)/esym AE.\nmove=> [a _ <-]; rewrite hlength_itv ?lte_fin/= -EFinB => lebig.\ncase: ifPn => a12; last by rewrite nneseries_esum// esum_ge0.\napply: lee_adde => e.\nrewrite [e%:num]splitr [in leRHS]EFinD addeA -lee_subl_addr//.\napply: le_trans (epsilon_trick _ _ _) => //=.\nhave eVn_gt0 n : 0 < e%:num / 2 / (2 ^ n.+1)%:R.\n  by rewrite divr_gt0// ltr0n// expn_gt0.\nhave eVn_ge0 n := ltW (eVn_gt0 n).\npose Aoo i : set ocitv_type :=\n  `](b i).1, (b i).2 + e%:num / 2 / (2 ^ i.+1)%:R[%classic.\npose Aoc i : set ocitv_type :=\n  `](b i).1, (b i).2 + e%:num / 2 / (2 ^ i.+1)%:R]%classic.\nhave: `[a.1 + e%:num / 2, a.2] `<=` \\bigcup_i Aoo i.\n  apply: (@subset_trans _ `]a.1, a.2]).\n    move=> x; rewrite /= !in_itv /= => /andP[+ -> //].\n    by move=> /lt_le_trans-> //; rewrite ltr_addl.\n  apply: (subset_trans lebig); apply: subset_bigcup => i _; rewrite AE /Aoo/=.\n  move=> x /=; rewrite !in_itv /= => /andP[-> /le_lt_trans->]//=.\n  by rewrite ltr_addl.\nhave := @segment_compact _ (a.1 + e%:num / 2) a.2; rewrite compact_cover.\nmove=> /[apply]-[i _|X _ Xc]; first exact: interval_open.\nhave: `](a.1 + e%:num / 2), a.2] `<=` \\bigcup_(i in [set` X]) Aoc i.\n  move=> x /subset_itv_oc_cc /Xc [i /= Xi] Aooix.\n  by exists i => //; apply: subset_itv_oo_oc Aooix.\nhave /[apply] := @content_sub_fsum _ _ _\n  [the content _ _ of hlength : set ocitv_type -> _] _ [set` X].\nmove=> /(_ _ _ _)/Box[]//=; apply: le_le_trans.\n  rewrite hlength_itv ?lte_fin -?EFinD/= -addrA -opprD.\n  by case: ltP => //; rewrite lee_fin subr_le0.\nrewrite nneseries_esum//; last by move=> *; rewrite adde_ge0//= ?lee_fin.\nrewrite esum_ge//; exists [set` X] => //; rewrite fsbig_finite// ?set_fsetK//=.\nrewrite fsbig_finite//= set_fsetK//.\nrewrite lee_sum // => i _; rewrite ?AE// !hlength_itv/= ?lte_fin -?EFinD/=.\ndo !case: ifPn => //= ?; do ?by rewrite ?adde_ge0 ?lee_fin// ?subr_ge0// ?ltW.\n  by rewrite addrAC.\nby rewrite addrAC lee_fin ler_add// subr_le0 leNgt.\nQed.\n\nLemma hlength_sigma_finite : sigma_finite setT (hlength : set ocitv_type -> _).\nProof.\nexists (fun k : nat => `] (- k%:R)%R, k%:R]%classic).\n  apply/esym; rewrite -subTset => x _ /=; exists `|(floor `|x| + 1)%R|%N => //=.\n  rewrite in_itv/= !natr_absz intr_norm intrD.\n  suff: `|x| < `|(floor `|x|)%:~R + 1| by rewrite ltr_norml => /andP[-> /ltW->].\n  by rewrite ger0_norm ?addr_ge0 ?ler0z ?floor_ge0// lt_succ_floor.\nby move=> k; split => //; rewrite hlength_itv/= -EFinB; case: ifP; rewrite ltry.\nQed.\n\nDefinition lebesgue_measure := Hahn_ext\n  [the content _ _ of hlength : set ocitv_type -> _].\n\nLet lebesgue_measure0 : lebesgue_measure set0 = 0%E.\nProof. by []. Qed.\n\nLet lebesgue_measure_ge0 : forall x, (0 <= lebesgue_measure x)%E.\nProof. exact: measure.Hahn_ext_ge0. Qed.\n\nLet lebesgue_measure_semi_sigma_additive : semi_sigma_additive lebesgue_measure.\nProof. exact/measure.Hahn_ext_sigma_additive/hlength_sigma_sub_additive. Qed.\n\nHB.instance Definition _ := isMeasure.Build _ _ _ lebesgue_measure\n  lebesgue_measure0 lebesgue_measure_ge0 lebesgue_measure_semi_sigma_additive.\n\nEnd itv_semiRingOfSets.\nArguments lebesgue_measure {R}.\n\nNotation \"R .-ocitv\" := (ocitv_display R) : measure_display_scope.\nNotation \"R .-ocitv.-measurable\" := (measurable : set (set (ocitv_type R))) :\n  classical_set_scope.\n\nSection lebesgue_measure.\nVariable R : realType.\nLet gitvs := [the measurableType _ of salgebraType (@ocitv R)].\n\nLemma lebesgue_measure_unique (mu : {measure set gitvs -> \\bar R}) :\n  (forall X, ocitv X -> hlength X = mu X) ->\n  forall X, measurable X -> lebesgue_measure X = mu X.\nProof.\nmove=> muE X mX; apply: Hahn_ext_unique => //=.\n- exact: hlength_sigma_sub_additive.\n- exact: hlength_sigma_finite.\nQed.\n\nEnd lebesgue_measure.\n\nSection ps_infty.\nContext {T : Type}.\nLocal Open Scope ereal_scope.\n\nInductive ps_infty : set \\bar T -> Prop :=\n| ps_infty0 : ps_infty set0\n| ps_ninfty : ps_infty [set -oo]\n| ps_pinfty : ps_infty [set +oo]\n| ps_inftys : ps_infty [set -oo; +oo].\n\nLemma ps_inftyP (A : set \\bar T) : ps_infty A <-> A `<=` [set -oo; +oo].\nProof.\nsplit => [[]//|Aoo].\nby have [] := subset_set2 Aoo; move=> ->; constructor.\nQed.\n\nLemma setCU_Efin (A : set T) (B : set \\bar T) : ps_infty B ->\n  ~` (EFin @` A) `&` ~` B = (EFin @` ~` A) `|` ([set -oo%E; +oo%E] `&` ~` B).\nProof.\nmove=> ps_inftyB.\nhave -> : ~` (EFin @` A) = EFin @` (~` A) `|` [set -oo; +oo]%E.\n  by rewrite EFin_setC setDKU // => x [|] -> -[].\nrewrite setIUl; congr (_ `|` _); rewrite predeqE => -[x| |]; split; try by case.\nby move=> [] x' Ax' [] <-{x}; split; [exists x'|case: ps_inftyB => // -[]].\nQed.\n\nEnd ps_infty.\n\nSection salgebra_ereal.\nVariables (R : realType) (G : set (set R)).\nLet measurableR : set (set R) := G.-sigma.-measurable.\n\nDefinition emeasurable : set (set \\bar R) :=\n  [set EFin @` A `|` B | A in measurableR & B in ps_infty].\n\nLemma emeasurable0 : emeasurable set0.\nProof.\nexists set0; first exact: measurable0.\nby exists set0; rewrite ?setU0// ?image_set0//; constructor.\nQed.\n\nLemma emeasurableC (X : set \\bar R) : emeasurable X -> emeasurable (~` X).\nProof.\nmove => -[A mA] [B PooB <-]; rewrite setCU setCU_Efin //.\nexists (~` A); [exact: measurableC | exists ([set -oo%E; +oo%E] `&` ~` B) => //].\ncase: PooB.\n- by rewrite setC0 setIT; constructor.\n- rewrite setIUl setICr set0U -setDE.\n  have [_ ->] := @setDidPl (\\bar R) [set +oo%E] [set -oo%E]; first by constructor.\n  by rewrite predeqE => x; split => // -[->].\n- rewrite setIUl setICr setU0 -setDE.\n  have [_ ->] := @setDidPl (\\bar R) [set -oo%E] [set +oo%E]; first by constructor.\n  by rewrite predeqE => x; split => // -[->].\n- by rewrite setICr; constructor.\nQed.\n\nLemma bigcupT_emeasurable (F : (set \\bar R)^nat) :\n  (forall i, emeasurable (F i)) -> emeasurable (\\bigcup_i (F i)).\nProof.\nmove=> mF; pose P := fun i j => measurableR j.1 /\\ ps_infty j.2 /\\\n                            F i = [set x%:E | x in j.1] `|` j.2.\nhave [f fi] : {f : nat -> (set R) * (set \\bar R) & forall i, P i (f i) }.\n  by apply: choice => i; have [x mx [y PSoo'y] xy] := mF i; exists (x, y).\nexists (\\bigcup_i (f i).1).\n  by apply: bigcupT_measurable => i; exact: (fi i).1.\nexists (\\bigcup_i (f i).2).\n  apply/ps_inftyP => x [n _] fn2x.\n  have /ps_inftyP : ps_infty(f n).2 by have [_ []] := fi n.\n  exact.\nrewrite [RHS](@eq_bigcupr _ _ _ _\n    (fun i => [set x%:E | x in (f i).1] `|` (f i).2)); last first.\n  by move=> i; have [_ []] := fi i.\nrewrite bigcupU; congr (_ `|` _).\nrewrite predeqE => i /=; split=> [[r [n _ fn1r <-{i}]]|[n _ [r fn1r <-{i}]]];\n by [exists n => //; exists r | exists r => //; exists n].\nQed.\n\nDefinition ereal_isMeasurable :\n  isMeasurable default_measure_display (\\bar R) :=\n  isMeasurable.Build _ _ (Pointed.class _)\n    emeasurable0 emeasurableC bigcupT_emeasurable.\n\nEnd salgebra_ereal.\n\nSection puncture_ereal_itv.\nVariable R : realDomainType.\nImplicit Types (y : R) (b : bool).\nLocal Open Scope ereal_scope.\n\nLemma punct_eitv_bndy b y : [set` Interval (BSide b y%:E) +oo%O] =\n  EFin @` [set` Interval (BSide b y) +oo%O] `|` [set +oo].\nProof.\nrewrite predeqE => x; split; rewrite /= in_itv andbT.\n- move: x => [x| |] yxb; [|by right|by case: b yxb].\n  by left; exists x => //; rewrite in_itv /= andbT; case: b yxb.\n- move=> [[r]|->].\n  + by rewrite in_itv /= andbT => yxb <-; case: b yxb.\n  + by case: b => /=; rewrite ?(ltry, leey).\nQed.\n\nLemma punct_eitv_Nybnd b y : [set` Interval -oo%O (BSide b y%:E)] =\n  [set -oo%E] `|` EFin @` [set x | x \\in Interval -oo%O (BSide b y)].\nProof.\nrewrite predeqE => x; split; rewrite /= in_itv.\n- move: x => [x| |] yxb; [|by case: b yxb|by left].\n  by right; exists x => //; rewrite in_itv /= andbT; case: b yxb.\n- move=> [->|[r]].\n  + by case: b => /=; rewrite ?(ltNyr, leNye).\n  + by rewrite in_itv /= => yxb <-; case: b yxb.\nQed.\n\nLemma punct_eitv_setTR : range (@EFin R) `|` [set +oo] = [set~ -oo].\nProof.\nrewrite eqEsubset; split => [a [[a' _ <-]|->]|] //.\nby move=> [x| |] //= _; [left; exists x|right].\nQed.\n\nLemma punct_eitv_setTL : range (@EFin R) `|` [set -oo] = [set~ +oo].\nProof.\nrewrite eqEsubset; split => [a [[a' _ <-]|->]|] //.\nby move=> [x| |] //= _; [left; exists x|right].\nQed.\n\nEnd puncture_ereal_itv.\n\nLemma set1_bigcap_oc (R : realType) (r : R) :\n   [set r] = \\bigcap_i `]r - i.+1%:R^-1, r]%classic.\nProof.\napply/seteqP; split=> [x ->|].\n  by move=> i _/=; rewrite in_itv/= lexx ltr_subl_addr ltr_addl invr_gt0 ltr0n.\nmove=> x rx; apply/esym/eqP; rewrite eq_le (itvP (rx 0%N _))// andbT.\napply/ler_addgt0Pl => e e_gt0; rewrite -ler_subl_addl ltW//.\nhave := rx `|floor e^-1%R|%N I; rewrite /= in_itv => /andP[/le_lt_trans->]//.\nrewrite ler_add2l ler_opp2 -lef_pinv ?invrK//; last by rewrite qualifE.\nby rewrite -natr1 natr_absz ger0_norm ?floor_ge0 ?invr_ge0 1?ltW// lt_succ_floor.\nQed.\n\nLemma itv_bnd_open_bigcup (R : realType) b (r s : R) :\n  [set` Interval (BSide b r) (BLeft s)] =\n  \\bigcup_n [set` Interval (BSide b r) (BRight (s - n.+1%:R^-1))].\nProof.\napply/seteqP; split => [x/=|]; last first.\n  move=> x [n _ /=] /[!in_itv] /andP[-> /le_lt_trans]; apply.\n  by rewrite ltr_subl_addr ltr_addl invr_gt0 ltr0n.\nrewrite in_itv/= => /andP[sx xs]; exists `|ceil ((s - x)^-1)|%N => //=.\nrewrite in_itv/= sx/= ler_subr_addl addrC -ler_subr_addl.\nrewrite -[in X in _ <= X](invrK (s - x)) ler_pinv.\n- rewrite -natr1 natr_absz ger0_norm; last first.\n    by rewrite ceil_ge0// invr_ge0 subr_ge0 ltW.\n  by rewrite (@le_trans _ _ (ceil (s - x)^-1)%:~R)// ?ler_addl// ceil_ge.\n- by rewrite inE unitfE ltr0n andbT pnatr_eq0.\n- by rewrite inE invr_gt0 subr_gt0 xs andbT unitfE invr_eq0 subr_eq0 gt_eqF.\nQed.\n\nLemma itv_open_bnd_bigcup (R : realType) b (r s : R) :\n  [set` Interval (BRight s) (BSide b r)] =\n  \\bigcup_n [set` Interval (BLeft (s + n.+1%:R^-1)) (BSide b r)].\nProof.\nhave /(congr1 (fun x => -%R @` x)) := itv_bnd_open_bigcup (~~ b) (- r) (- s).\nrewrite opp_itv_bnd_bnd/= !opprK negbK => ->; rewrite image_bigcup.\napply eq_bigcupr => k _; apply/seteqP; split=> [_/= [y ysr] <-|x/= xsr].\n  by rewrite oppr_itv/= opprD.\nby exists (- x); rewrite ?oppr_itv//= opprK// negbK opprB opprK addrC.\nQed.\n\nLemma itv_bnd_infty_bigcup (R : realType) b (x : R) :\n  [set` Interval (BSide b x) +oo%O] =\n  \\bigcup_i [set` Interval (BSide b x) (BRight (x + i%:R))].\nProof.\napply/seteqP; split=> y; rewrite /= !in_itv/= andbT; last first.\n  by move=> [k _ /=]; move: b => [|] /=; rewrite in_itv/= => /andP[//] /ltW.\nmove=> xy; exists `|ceil (y - x)|%N => //=; rewrite in_itv/= xy/= -ler_subl_addl.\nrewrite !natr_absz/= ger0_norm ?ceil_ge0 ?subr_ge0 ?ceil_ge//.\nby case: b xy => //= /ltW.\nQed.\n\nLemma itv_infty_bnd_bigcup (R : realType) b (x : R) :\n  [set` Interval -oo%O (BSide b x)] =\n  \\bigcup_i [set` Interval (BLeft (x - i%:R)) (BSide b x)].\nProof.\nhave /(congr1 (fun x => -%R @` x)) := itv_bnd_infty_bigcup (~~ b) (- x).\nrewrite opp_itv_bnd_infty negbK opprK => ->; rewrite image_bigcup.\napply eq_bigcupr => k _; apply/seteqP; split=> [_ /= -[r rbxk <-]|y/= yxkb].\n   by rewrite oppr_itv/= opprB addrC.\nby exists (- y); [rewrite oppr_itv/= negbK opprD opprK|rewrite opprK].\nQed.\n\nSection salgebra_R_ssets.\nVariable R : realType.\n\nDefinition measurableTypeR := salgebraType (R.-ocitv.-measurable).\nDefinition measurableR : set (set R) :=\n  (R.-ocitv.-measurable).-sigma.-measurable.\n\nHB.instance Definition R_isMeasurable :\n  isMeasurable default_measure_display R :=\n  @isMeasurable.Build _ measurableTypeR (Pointed.class R) measurableR\n    measurable0 (@measurableC _ _) (@bigcupT_measurable _ _).\n(*HB.instance (Real.sort R) R_isMeasurable.*)\n\nLemma measurable_set1 (r : R) : measurable [set r].\nProof.\nrewrite set1_bigcap_oc; apply: bigcap_measurable => k // _.\nby apply: sub_sigma_algebra; exact/is_ocitv.\nQed.\n#[local] Hint Resolve measurable_set1 : core.\n\nLemma measurable_itv (i : interval R) : measurable [set` i].\nProof.\nhave moc (a b : R) : measurable `]a, b]%classic.\n  by apply: sub_sigma_algebra; apply: is_ocitv.\nhave mopoo (x : R) : measurable `]x, +oo[%classic.\n  by rewrite itv_bnd_infty_bigcup; exact: bigcup_measurable.\nhave mnooc (x : R) : measurable `]-oo, x]%classic.\n  by rewrite -setCitvr; exact/measurableC.\nhave ooE (a b : R) : `]a, b[%classic = `]a, b]%classic `\\ b.\n  case: (boolP (a < b)) => ab; last by rewrite !set_itv_ge ?set0D.\n  by rewrite -setUitv1// setUDK// => x [->]; rewrite /= in_itv/= ltxx andbF.\nhave moo (a b : R) : measurable `]a, b[%classic.\n  by rewrite ooE; exact: measurableD.\nhave mcc (a b : R) : measurable `[a, b]%classic.\n  case: (boolP (a <= b)) => ab; last by rewrite set_itv_ge.\n  by rewrite -setU1itv//; apply/measurableU.\nhave mco (a b : R) : measurable `[a, b[%classic.\n  case: (boolP (a < b)) => ab; last by rewrite set_itv_ge.\n  by rewrite -setU1itv//; apply/measurableU.\nhave oooE (b : R) : `]-oo, b[%classic = `]-oo, b]%classic `\\ b.\n  by rewrite -setUitv1// setUDK// => x [->]; rewrite /= in_itv/= ltxx.\ncase: i => [[[] a|[]] [[] b|[]]] => //; do ?by rewrite set_itv_ge.\n- by rewrite -setU1itv//; exact/measurableU.\n- by rewrite oooE; exact/measurableD.\n- by rewrite set_itv_infty_infty.\nQed.\n\nHB.instance Definition _ :=\n  (ereal_isMeasurable (R.-ocitv.-measurable)).\n(* NB: Until we dropped support for Coq 8.12, we were using\nHB.instance (\\bar (Real.sort R))\n  (ereal_isMeasurable (@measurable (@itvs_semiRingOfSets R))).\nThis was producing a warning but the alternative was failing with Coq 8.12 with\n  the following message (according to the CI):\n  # [redundant-canonical-projection,typechecker]\n  # forall (T : measurableType) (f : T -> R), measurable_fun setT f\n  #      : Prop\n  # File \"./theories/lebesgue_measure.v\", line 4508, characters 0-88:\n  # Error: Anomaly \"Uncaught exception Failure(\"sep_last\").\"\n  # Please report at http://coq.inria.fr/bugs/.\n*)\n\nLemma measurable_EFin (A : set R) : measurableR A -> measurable (EFin @` A).\nProof.\nby move=> mA; exists A => //; exists set0; [constructor|rewrite setU0].\nQed.\n\nLemma emeasurable_set1 (x : \\bar R) : measurable [set x].\nProof.\ncase: x => [r| |].\n- by rewrite -image_set1; apply: measurable_EFin; apply: measurable_set1.\n- exists set0 => //; [exists [set +oo%E]; [by constructor|]].\n  by rewrite image_set0 set0U.\n- exists set0 => //; [exists [set -oo%E]; [by constructor|]].\n  by rewrite image_set0 set0U.\nQed.\n#[local] Hint Resolve emeasurable_set1 : core.\n\nLemma __deprecated__itv_cpinfty_pinfty : `[+oo%E, +oo[%classic = [set +oo%E] :> set (\\bar R).\nProof. by rewrite itv_cyy. Qed.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\", note=\"renamed `itv_cyy`\")]\nNotation itv_cpinfty_pinfty := __deprecated__itv_cpinfty_pinfty.\n\nLemma __deprecated__itv_opinfty_pinfty : `]+oo%E, +oo[%classic = set0 :> set (\\bar R).\nProof. by rewrite itv_oyy. Qed.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\", note=\"renamed `itv_oyy`\")]\nNotation itv_opinfty_pinfty := __deprecated__itv_opinfty_pinfty.\n\nLemma __deprecated__itv_cninfty_pinfty : `[-oo%E, +oo[%classic = setT :> set (\\bar R).\nProof. by rewrite itv_cNyy. Qed.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\", note=\"renamed `itv_cNyy`\")]\nNotation itv_cninfty_pinfty := __deprecated__itv_cninfty_pinfty.\n\nLemma __deprecated__itv_oninfty_pinfty :\n  `]-oo%E, +oo[%classic = ~` [set -oo]%E :> set (\\bar R).\nProof. by rewrite itv_oNyy. Qed.\n#[deprecated(since=\"mathcomp-analysis 0.6.0\", note=\"renamed `itv_oNyy`\")]\nNotation itv_oninfty_pinfty := __deprecated__itv_oninfty_pinfty.\n\nLet emeasurable_itv_bndy b (y : \\bar R) :\n  measurable [set` Interval (BSide b y) +oo%O].\nProof.\nmove: y => [y| |].\n- exists [set` Interval (BSide b y) +oo%O]; first exact: measurable_itv.\n  by exists [set +oo%E]; [constructor|rewrite -punct_eitv_bndy].\n- by case: b; rewrite ?itv_oyy ?itv_cyy.\n- case: b; first by rewrite itv_cNyy.\n  by rewrite itv_oNyy; exact/measurableC.\nQed.\n\nLet emeasurable_itv_Nybnd b (y : \\bar R) :\n  measurable [set` Interval -oo%O (BSide b y)].\nProof. by rewrite -setCitvr; exact/measurableC/emeasurable_itv_bndy. Qed.\n\nLemma emeasurable_itv (i : interval (\\bar R)) :\n  measurable ([set` i]%classic : set \\bar R).\nProof.\nrewrite -[X in measurable X]setCK; apply: measurableC.\nrewrite set_interval.setCitv /=; apply: measurableU => [|].\n- by move: i => [[b1 i1|[|]] i2] /=; rewrite ?set_interval.set_itvE.\n- by move: i => [i1 [b2 i2|[|]]] /=; rewrite ?set_interval.set_itvE.\nQed.\n\nDefinition elebesgue_measure : set \\bar R -> \\bar R :=\n  fun S => lebesgue_measure (fine @` (S `\\` [set -oo; +oo]%E)).\n\nLemma elebesgue_measure0 : elebesgue_measure set0 = 0%E.\nProof. by rewrite /elebesgue_measure set0D image_set0 measure0. Qed.\n\nLemma measurable_fine (X : set \\bar R) : measurable X ->\n  measurable [set fine x | x in X `\\` [set -oo; +oo]%E].\nProof.\ncase => Y mY [X' [ | <-{X} | <-{X} | <-{X} ]].\n- rewrite setU0 => <-{X}.\n  rewrite [X in measurable X](_ : _ = Y) // predeqE => r; split.\n    by move=> [x [[x' Yx' <-{x}/= _ <-//]]].\n  by move=> Yr; exists r%:E; split => [|[]//]; exists r.\n- rewrite [X in measurable X](_ : _ = Y) // predeqE => r; split.\n    move=> [x [[[x' Yx' <- _ <-//]|]]].\n    by move=> <-; rewrite not_orP => -[]/(_ erefl).\n  by move=> Yr; exists r%:E => //; split => [|[]//]; left; exists r.\n- rewrite [X in measurable X](_ : _ = Y) // predeqE => r; split.\n    move=> [x [[[x' Yx' <-{x} _ <-//]|]]].\n    by move=> ->; rewrite not_orP => -[_]/(_ erefl).\n  by move=> Yr; exists r%:E => //; split => [|[]//]; left; exists r.\n- rewrite [X in measurable X](_ : _ = Y) // predeqE => r; split.\n    by rewrite setDUl setDv setU0 => -[_ [[x' Yx' <-]] _ <-].\n  by move=> Yr; exists r%:E => //; split => [|[]//]; left; exists r.\nQed.\n\nLemma elebesgue_measure_ge0 X : (0 <= elebesgue_measure X)%E.\nProof. exact/measure_ge0. Qed.\n\nLemma semi_sigma_additive_elebesgue_measure :\n  semi_sigma_additive elebesgue_measure.\nProof.\nmove=> /= F mF tF mUF; rewrite /elebesgue_measure.\nrewrite [X in lebesgue_measure X](_ : _ =\n    \\bigcup_n (fine @` (F n `\\` [set -oo; +oo]%E))); last first.\n  rewrite predeqE => r; split.\n    by move=> [x [[n _ Fnx xoo <-]]]; exists n => //; exists x.\n  by move=> [n _ [x [Fnx xoo <-{r}]]]; exists x => //; split => //; exists n.\napply: (@measure_semi_sigma_additive _ _ _ [the measure _ _ of (@lebesgue_measure R)]\n  (fun n => fine @` (F n `\\` [set -oo; +oo]%E))).\n- move=> n; have := mF n.\n  move=> [X mX [X' mX']] XX'Fn.\n  apply: measurable_fine.\n  rewrite -XX'Fn.\n  apply: measurableU; first exact: measurable_EFin.\n  by case: mX' => //; exact: measurableU.\n- move=> i j _ _ [x [[a [Fia aoo ax] [b [Fjb boo] bx]]]].\n  move: tF => /(_ i j Logic.I Logic.I); apply.\n  suff ab : a = b by exists a; split => //; rewrite ab.\n  move: a b {Fia Fjb} aoo boo ax bx.\n  move=> [a| |] [b| |] /=.\n  + by move=> _ _ -> ->.\n  + by move=> _; rewrite not_orP => -[_]/(_ erefl).\n  + by move=> _; rewrite not_orP => -[]/(_ erefl).\n  + by rewrite not_orP => -[_]/(_ erefl).\n  + by rewrite not_orP => -[_]/(_ erefl).\n  + by rewrite not_orP => -[_]/(_ erefl).\n  + by rewrite not_orP => -[]/(_ erefl).\n  + by rewrite not_orP => -[]/(_ erefl).\n  + by rewrite not_orP => -[]/(_ erefl).\n- move: mUF.\n  rewrite {1}/measurable /emeasurable /= => -[X mX [Y []]] {Y}.\n  - rewrite setU0 => h.\n    rewrite [X in measurable X](_ : _ = X) // predeqE => r; split => [|Xr].\n      move=> -[n _ [x [Fnx xoo <-{r}]]].\n      have : (\\bigcup_n F n) x by exists n.\n      by rewrite -h => -[x' Xx' <-].\n    have [n _ Fnr] : (\\bigcup_n F n) r%:E by rewrite -h; exists r.\n    by exists n => //; exists r%:E => //; split => //; case.\n  - move=> h.\n    rewrite [X in measurable X](_ : _ = X) // predeqE => r; split => [|Xr].\n      move=> -[n _ [x [Fnx xoo <-]]].\n      have : (\\bigcup_n F n) x by exists n.\n      by rewrite -h => -[[x' Xx' <-//]|xoo']; move/not_orP : xoo => -[].\n    have [n _ Fnr] : (\\bigcup_n F n) r%:E by rewrite -h; left; exists r.\n    by exists n => //; exists r%:E => //; split => //; case.\n  - (* NB: almost the same as the previous one, factorize?*)\n    move=> h.\n    rewrite [X in measurable X](_ : _ = X) // predeqE => r; split => [|Xr].\n      move=> -[n _ [x [Fnx xoo <-]]].\n      have : (\\bigcup_n F n) x by exists n.\n      by rewrite -h => -[[x' Xx' <-//]|xoo']; move/not_orP : xoo => -[].\n    have [n _ Fnr] : (\\bigcup_n F n) r%:E by rewrite -h; left; exists r.\n    by exists n => //; exists r%:E => //; split => //; case.\n  - move=> h.\n    rewrite [X in measurable X](_ : _ = X) // predeqE => r; split => [|Xr].\n      move=> -[n _ [x [Fnx xoo <-]]].\n      have : (\\bigcup_n F n) x by exists n.\n      by rewrite -h => -[[x' Xx' <-//]|].\n    have [n _ Fnr] : (\\bigcup_n F n) r%:E by rewrite -h; left; exists r.\n    by exists n => //; exists r%:E => //; split => //; case.\nQed.\n\nHB.instance Definition _ := isMeasure.Build _ _ _ elebesgue_measure\n  elebesgue_measure0 elebesgue_measure_ge0\n  semi_sigma_additive_elebesgue_measure.\n\nEnd salgebra_R_ssets.\n#[global]\nHint Extern 0 (measurable [set _]) => solve [apply: measurable_set1|\n                                            apply: emeasurable_set1] : core.\n#[deprecated(since=\"mathcomp-analysis 0.6.2\",\n  note=\"use `emeasurable_itv` instead\")]\nNotation emeasurable_itv_bnd_pinfty := emeasurable_itv.\n#[deprecated(since=\"mathcomp-analysis 0.6.2\",\n  note=\"use `emeasurable_itv` instead\")]\nNotation emeasurable_itv_ninfty_bnd := emeasurable_itv.\n\nLemma measurable_fun_fine (R : realType) (D : set (\\bar R)) : measurable D ->\n  measurable_fun D fine.\nProof.\nmove=> mD _ /= B mB; rewrite [X in measurable X](_ : _ `&` _ = if 0%R \\in B then\n    D `&` ((EFin @` B) `|` [set -oo; +oo]%E) else D `&` EFin @` B); last first.\n  apply/seteqP; split=> [[r [Dr Br]|[Doo B0]|[Doo B0]]|[r| |]].\n  - by case: ifPn => _; split => //; left; exists r.\n  - by rewrite mem_set//; split => //; right; right.\n  - by rewrite mem_set//; split => //; right; left.\n  - by case: ifPn => [_ [Dr [[s + [sr]]|[]//]]|_ [Dr [s + [sr]]]]; rewrite sr.\n  - by case: ifPn => [/[!inE] B0 [Doo [[]//|]] [//|_]|B0 [Doo//] []].\n  - by case: ifPn => [/[!inE] B0 [Doo [[]//|]] [//|_]|B0 [Doo//] []].\ncase: ifPn => B0; apply/measurableI => //; last exact: measurable_EFin.\nby apply: measurableU; [exact: measurable_EFin|exact: measurableU].\nQed.\n\nSection lebesgue_measure_itv.\nVariable R : realType.\n\nLet lebesgue_measure_itvoc (a b : R) :\n  (lebesgue_measure (`]a, b] : set R) = hlength `]a, b])%classic.\nProof.\nrewrite /lebesgue_measure/= /Hahn_ext measurable_mu_extE//; last first.\n  by exists (a, b).\nexact: hlength_sigma_sub_additive.\nQed.\n\nLet lebesgue_measure_itvoo_subr1 (a : R) :\n  lebesgue_measure (`]a - 1, a[%classic : set R) = 1%E.\nProof.\nrewrite itv_bnd_open_bigcup//; transitivity (lim (lebesgue_measure \\o\n    (fun k => `]a - 1, a - k.+1%:R^-1]%classic : set R))).\n  apply/esym/cvg_lim => //; apply: nondecreasing_cvg_mu.\n  - by move=> ?; exact: measurable_itv.\n  - by apply: bigcup_measurable => k _; exact: measurable_itv.\n  - move=> n m nm; apply/subsetPset => x /=; rewrite !in_itv/= => /andP[->/=].\n    by move/le_trans; apply; rewrite ler_sub// ler_pinv ?ler_nat//;\n      rewrite inE ltr0n andbT unitfE.\nrewrite (_ : _ \\o _ = (fun n => (1 - n.+1%:R^-1)%:E)); last first.\n  apply/funext => n /=; rewrite lebesgue_measure_itvoc.\n  have [->|n0] := eqVneq n 0%N; first by rewrite invr1 subrr set_itvoc0.\n  rewrite hlength_itv/= lte_fin ifT; last first.\n    by rewrite ler_lt_sub// invr_lt1 ?unitfE// ltr1n ltnS lt0n.\n  by rewrite !(EFinB,EFinN) fin_num_oppeB// addeAC addeA subee// add0e.\napply/cvg_lim => //=; apply/fine_cvgP; split => /=; first exact: nearW.\napply/(@cvgrPdist_lt _ [pseudoMetricNormedZmodType R of R^o]) => _/posnumP[e].\nnear=> n; rewrite opprB addrCA subrr addr0 ger0_norm//.\nby near: n; exact: near_infty_natSinv_lt.\nUnshelve. all: by end_near. Qed.\n\nLemma lebesgue_measure_set1 (a : R) : lebesgue_measure [set a] = 0%E.\nProof.\nsuff : (lebesgue_measure (`]a - 1, a]%classic%R : set R) =\n        lebesgue_measure (`]a - 1, a[%classic%R : set R) +\n        lebesgue_measure [set a])%E.\n  rewrite lebesgue_measure_itvoo_subr1 lebesgue_measure_itvoc => /eqP.\n  rewrite hlength_itv lte_fin ltr_subl_addr ltr_addl ltr01.\n  rewrite [in X in X == _]/= EFinN EFinB fin_num_oppeB// addeA subee// add0e.\n  by rewrite addeC -sube_eq ?fin_num_adde_defl// subee// => /eqP.\nrewrite -setUitv1// ?bnd_simp; last by rewrite ltr_subl_addr ltr_addl.\nrewrite measureU//; first exact: measurable_itv.\napply/seteqP; split => // x []/=; rewrite in_itv/= => + xa.\nby rewrite xa ltxx andbF.\nQed.\n\nLet lebesgue_measure_itvoo (a b : R) :\n  (lebesgue_measure (`]a, b[ : set R) = hlength `]a, b[)%classic.\nProof.\nhave [ab|ba] := ltP a b; last by rewrite set_itv_ge ?measure0// -leNgt.\nhave := lebesgue_measure_itvoc a b.\nrewrite 2!hlength_itv => <-; rewrite -setUitv1// measureU//.\n- by have /= -> := lebesgue_measure_set1 b; rewrite adde0.\n- exact: measurable_itv.\n- by apply/seteqP; split => // x [/= + xb]; rewrite in_itv/= xb ltxx andbF.\nQed.\n\nLet lebesgue_measure_itvcc (a b : R) :\n  (lebesgue_measure (`[a, b] : set R) = hlength `[a, b])%classic.\nProof.\nhave [ab|ba] := leP a b; last by rewrite set_itv_ge ?measure0// -leNgt.\nhave := lebesgue_measure_itvoc a b.\nrewrite 2!hlength_itv => <-; rewrite -setU1itv// measureU//.\n- by have /= -> := lebesgue_measure_set1 a; rewrite add0e.\n- exact: measurable_itv.\n- by apply/seteqP; split => // x [/= ->]; rewrite in_itv/= ltxx.\nQed.\n\nLet lebesgue_measure_itvco (a b : R) :\n  (lebesgue_measure (`[a, b[ : set R) = hlength `[a, b[)%classic.\nProof.\nhave [ab|ba] := ltP a b; last by rewrite set_itv_ge ?measure0// -leNgt.\nhave := lebesgue_measure_itvoo a b.\nrewrite 2!hlength_itv => <-; rewrite -setU1itv// measureU//.\n- by have /= -> := lebesgue_measure_set1 a; rewrite add0e.\n- exact: measurable_itv.\n- by apply/seteqP; split => // x [/= ->]; rewrite in_itv/= ltxx.\nQed.\n\nLet lebesgue_measure_itv_bnd (x y : bool) (a b : R) :\n  lebesgue_measure ([set` Interval (BSide x a) (BSide y b)] : set R) =\n  hlength [set` Interval (BSide x a) (BSide y b)].\nProof.\nby move: x y => [|] [|]; [exact: lebesgue_measure_itvco |\n  exact: lebesgue_measure_itvcc | exact: lebesgue_measure_itvoo |\n  exact: lebesgue_measure_itvoc].\nQed.\n\nLet limnatR : lim (fun k => (k%:R)%:E : \\bar R) = +oo%E.\nProof. by apply/cvg_lim => //; apply/cvgenyP. Qed.\n\nLet lebesgue_measure_itv_bnd_infty x (a : R) :\n  lebesgue_measure ([set` Interval (BSide x a) +oo%O] : set R) = +oo%E.\nProof.\nrewrite itv_bnd_infty_bigcup; transitivity (lim (lebesgue_measure \\o\n    (fun k => [set` Interval (BSide x a) (BRight (a + k%:R))] : set R))).\n  apply/esym/cvg_lim => //; apply: nondecreasing_cvg_mu.\n  + by move=> k; exact: measurable_itv.\n  + by apply: bigcup_measurable => k _; exact: measurable_itv.\n  + move=> m n mn; apply/subsetPset => r/=; rewrite !in_itv/= => /andP[->/=].\n    by move=> /le_trans; apply; rewrite ler_add// ler_nat.\nrewrite (_ : _ \\o _ = (fun k => k%:R%:E))//.\napply/funext => n /=; rewrite lebesgue_measure_itv_bnd hlength_itv/=.\nrewrite lte_fin;  have [->|n0] := eqVneq n 0%N; first by rewrite addr0 ltxx.\nby rewrite ltr_addl ltr0n lt0n n0 EFinD addeAC EFinN subee ?add0e.\nQed.\n\nLet lebesgue_measure_itv_infty_bnd y (b : R) :\n  lebesgue_measure ([set` Interval -oo%O (BSide y b)] : set R) = +oo%E.\nProof.\nrewrite itv_infty_bnd_bigcup; transitivity (lim (lebesgue_measure \\o\n    (fun k => [set` Interval (BLeft (b - k%:R)) (BSide y b)] : set R))).\n  apply/esym/cvg_lim => //; apply: nondecreasing_cvg_mu.\n  + by move=> k; exact: measurable_itv.\n  + by apply: bigcup_measurable => k _; exact: measurable_itv.\n  + move=> m n mn; apply/subsetPset => r/=; rewrite !in_itv/= => /andP[+ ->].\n    by rewrite andbT; apply: le_trans; rewrite ler_sub// ler_nat.\nrewrite (_ : _ \\o _ = (fun k : nat => k%:R%:E))//.\napply/funext => n /=; rewrite lebesgue_measure_itv_bnd hlength_itv/= lte_fin.\nhave [->|n0] := eqVneq n 0%N; first by rewrite subr0 ltxx.\nrewrite ltr_subl_addr ltr_addl ltr0n lt0n n0 EFinN EFinB fin_num_oppeB// addeA.\nby rewrite subee// add0e.\nQed.\n\nLemma lebesgue_measure_itv (i : interval R) :\n  lebesgue_measure ([set` i] : set R) = hlength [set` i].\nProof.\nmove: i => [[x a|[|]]] [y b|[|]]; first exact: lebesgue_measure_itv_bnd.\n- by rewrite set_itvE ?measure0.\n- by rewrite lebesgue_measure_itv_bnd_infty hlength_bnd_infty.\n- by rewrite lebesgue_measure_itv_infty_bnd hlength_infty_bnd.\n- by rewrite set_itvE ?measure0.\n- rewrite set_itvE hlength_setT.\n  rewrite (_ : setT = [set` `]-oo, 0[] `|` [set` `[0, +oo[]); last first.\n    by apply/seteqP; split=> // => x _; have [x0|x0] := leP 0 x; [right|left];\n      rewrite /= in_itv//= x0.\n  rewrite measureU//=; try exact: measurable_itv.\n  + by rewrite lebesgue_measure_itv_infty_bnd lebesgue_measure_itv_bnd_infty.\n  + by apply/seteqP; split => // x []/=; rewrite !in_itv/= andbT leNgt => ->.\n- by rewrite set_itvE ?measure0.\n- by rewrite set_itvE ?measure0.\n- by rewrite set_itvE ?measure0.\nQed.\n\nEnd lebesgue_measure_itv.\n\nLemma lebesgue_measure_rat (R : realType) :\n  lebesgue_measure (range ratr : set R) = 0%E.\nProof.\nhave /pcard_eqP/bijPex[f bijf] := card_rat; set f1 := 'pinv_(fun=> 0) setT f.\nrewrite (_ : range _ = \\bigcup_n [set ratr (f1 n)]); last first.\n  apply/seteqP; split => [_ [q _ <-]|_ [n _ /= ->]]; last by exists (f1 n).\n  exists (f q) => //=; rewrite /f1 pinvKV// ?in_setE// => x y _ _.\n  by apply: bij_inj; rewrite -setTT_bijective.\nrewrite measure_bigcup//; last first.\n  apply/trivIsetP => i j _ _ ij; apply/seteqP; split => //= _ [/= ->].\n  move=> /fmorph_inj.\n  have /set_bij_inj /[apply] := bijpinv_bij (fun=> 0) bijf.\n  by rewrite in_setE => /(_ Logic.I Logic.I); exact/eqP.\nby rewrite eseries0// => n _; exact: lebesgue_measure_set1.\nQed.\n\nSection measurable_fun_measurable.\nLocal Open Scope ereal_scope.\nContext d (T : measurableType d) (R : realType).\nVariables (D : set T) (f : T -> \\bar R).\nHypotheses (mD : measurable D) (mf : measurable_fun D f).\nImplicit Types y : \\bar R.\n\nLemma emeasurable_fun_c_infty y : measurable (D `&` [set x | y <= f x]).\nProof. by rewrite -preimage_itv_c_infty; exact/mf/emeasurable_itv. Qed.\n\nLemma emeasurable_fun_o_infty y :  measurable (D `&` [set x | y < f x]).\nProof. by rewrite -preimage_itv_o_infty; exact/mf/emeasurable_itv. Qed.\n\nLemma emeasurable_fun_infty_o y : measurable (D `&` [set x | f x < y]).\nProof. by rewrite -preimage_itv_infty_o; exact/mf/emeasurable_itv. Qed.\n\nLemma emeasurable_fun_infty_c y : measurable (D `&` [set x | f x <= y]).\nProof. by rewrite -preimage_itv_infty_c; exact/mf/emeasurable_itv. Qed.\n\nLemma emeasurable_fin_num : measurable (D `&` [set x | f x \\is a fin_num]).\nProof.\nrewrite [X in measurable X](_ : _ =\n  \\bigcup_k (D `&` ([set  x | - k%:R%:E <= f x] `&` [set x | f x <= k%:R%:E]))).\n  apply: bigcupT_measurable => k; rewrite -(setIid D) setIACA.\n  by apply: measurableI; [exact: emeasurable_fun_c_infty|\n                          exact: emeasurable_fun_infty_c].\nrewrite predeqE => t; split => [/= [Dt ft]|].\n  have [ft0|ft0] := leP 0%R (fine (f t)).\n    exists `|ceil (fine (f t))|%N => //=; split => //; split.\n      by rewrite -{2}(fineK ft)// lee_fin (le_trans _ ft0)// ler_oppl oppr0.\n    by rewrite natr_absz ger0_norm ?ceil_ge0// -(fineK ft) lee_fin ceil_ge.\n  exists `|floor (fine (f t))|%N => //=; split => //; split.\n    rewrite natr_absz ltr0_norm ?floor_lt0// EFinN.\n    by rewrite -{2}(fineK ft) lee_fin mulrNz opprK floor_le.\n  by rewrite -(fineK ft)// lee_fin (le_trans (ltW ft0)).\nmove=> [n _] [/= Dt [nft fnt]]; split => //; rewrite fin_numElt.\nby rewrite (lt_le_trans _ nft) ?ltNyr//= (le_lt_trans fnt)// ltry.\nQed.\n\nLemma emeasurable_neq y : measurable (D `&` [set x | f x != y]).\nProof.\nrewrite (_ : [set x | f x != y] = f @^-1` (setT `\\ y)).\n  exact/mf/measurableD.\nrewrite predeqE => t; split; last by rewrite /preimage /= => -[_ /eqP].\nby rewrite /= => ft0; rewrite /preimage /=; split => //; exact/eqP.\nQed.\n\nEnd measurable_fun_measurable.\n\nModule RGenOInfty.\nSection rgenoinfty.\nVariable R : realType.\nImplicit Types x y z : R.\n\nDefinition G := [set A | exists x, A = `]x, +oo[%classic].\n\nLemma measurable_itv_bnd_infty b x :\n  G.-sigma.-measurable [set` Interval (BSide b x) +oo%O].\nProof.\ncase: b; last by apply: sub_sigma_algebra; eexists; reflexivity.\nrewrite itv_c_inftyEbigcap; apply: bigcapT_measurable => k.\nby apply: sub_sigma_algebra; eexists; reflexivity.\nQed.\n\nLemma measurable_itv_bounded a b x : a != +oo%O ->\n  G.-sigma.-measurable [set` Interval a (BSide b x)].\nProof.\ncase: a => [a r _|[_|//]].\n  by rewrite set_itv_splitD; apply: measurableD => //;\n    exact: measurable_itv_bnd_infty.\nby rewrite -setCitvr; apply: measurableC; apply: measurable_itv_bnd_infty.\nQed.\n\nLemma measurableE :\n  (R.-ocitv.-measurable).-sigma.-measurable = G.-sigma.-measurable.\nProof.\nrewrite eqEsubset; split => A.\n  apply: smallest_sub; first exact: smallest_sigma_algebra.\n  by move=> I [x _ <-]; exact: measurable_itv_bounded.\napply: smallest_sub; first exact: smallest_sigma_algebra.\nby move=> A' /= [x ->]; exact: measurable_itv.\nQed.\n\nEnd rgenoinfty.\nEnd RGenOInfty.\n\nModule RGenInftyO.\nSection rgeninftyo.\nVariable R : realType.\nImplicit Types x y z : R.\n\nDefinition G := [set A | exists x, A = `]-oo, x[%classic].\n\nLemma measurable_itv_bnd_infty b x :\n  G.-sigma.-measurable [set` Interval -oo%O (BSide b x)].\nProof.\ncase: b; first by apply sub_sigma_algebra; eexists; reflexivity.\nrewrite -setCitvr itv_o_inftyEbigcup; apply/measurableC/bigcupT_measurable => n.\nrewrite -setCitvl; apply: measurableC.\nby apply: sub_sigma_algebra; eexists; reflexivity.\nQed.\n\nLemma measurable_itv_bounded a b x : a != -oo%O ->\n  G.-sigma.-measurable [set` Interval (BSide b x) a].\nProof.\ncase: a => [a r _|[//|_]].\n  by rewrite set_itv_splitD; apply/measurableD => //;\n     rewrite -setCitvl; apply: measurableC; exact: measurable_itv_bnd_infty.\nby rewrite -setCitvl; apply: measurableC; apply: measurable_itv_bnd_infty.\nQed.\n\nLemma measurableE :\n  (R.-ocitv.-measurable).-sigma.-measurable = G.-sigma.-measurable.\nProof.\nrewrite eqEsubset; split => A.\n  apply: smallest_sub; first exact: smallest_sigma_algebra.\n  by move=> I [x _ <-]; apply: measurable_itv_bounded.\napply: smallest_sub; first exact: smallest_sigma_algebra.\nby move=> A' /= [x ->]; apply: measurable_itv.\nQed.\n\nEnd rgeninftyo.\nEnd RGenInftyO.\n\nModule RGenCInfty.\nSection rgencinfty.\nVariable R : realType.\nImplicit Types x y z : R.\n\nDefinition G : set (set R) := [set A | exists x, A = `[x, +oo[%classic].\n\nLemma measurable_itv_bnd_infty b x :\n  G.-sigma.-measurable [set` Interval (BSide b x) +oo%O].\nProof.\ncase: b; first by apply: sub_sigma_algebra; exists x; rewrite set_itv_c_infty.\nrewrite itv_o_inftyEbigcup; apply: bigcupT_measurable => k.\nby apply: sub_sigma_algebra; eexists; reflexivity.\nQed.\n\nLemma measurable_itv_bounded a b y : a != +oo%O ->\n  G.-sigma.-measurable [set` Interval a (BSide b y)].\nProof.\ncase: a => [a r _|[_|//]].\n  rewrite set_itv_splitD.\n  by apply: measurableD; apply: measurable_itv_bnd_infty.\nby rewrite -setCitvr; apply: measurableC; apply: measurable_itv_bnd_infty.\nQed.\n\nLemma measurableE :\n  (R.-ocitv.-measurable).-sigma.-measurable = G.-sigma.-measurable.\nProof.\nrewrite eqEsubset; split => A.\n  apply: smallest_sub; first exact: smallest_sigma_algebra.\n  by move=> I [x _ <-]; apply: measurable_itv_bounded.\napply: smallest_sub; first exact: smallest_sigma_algebra.\nby move=> A' /= [x ->]; apply: measurable_itv.\nQed.\n\nEnd rgencinfty.\nEnd RGenCInfty.\n\nModule RGenOpens.\nSection rgenopens.\nVariable R : realType.\nImplicit Types x y z : R.\n\nDefinition G := [set A | exists x y, A = `]x, y[%classic].\n\nLocal Lemma measurable_itvoo x y : G.-sigma.-measurable `]x, y[%classic.\nProof. by apply sub_sigma_algebra; eexists; eexists; reflexivity. Qed.\n\nLocal Lemma measurable_itv_o_infty x : G.-sigma.-measurable `]x, +oo[%classic.\nProof.\nrewrite itv_bnd_inftyEbigcup; apply: bigcupT_measurable => i.\nexact: measurable_itvoo.\nQed.\n\nLemma measurable_itv_bnd_infty b x :\n  G.-sigma.-measurable [set` Interval (BSide b x) +oo%O].\nProof.\ncase: b; last exact: measurable_itv_o_infty.\nrewrite itv_c_inftyEbigcap; apply: bigcapT_measurable => k.\nexact: measurable_itv_o_infty.\nQed.\n\nLemma measurable_itv_infty_bnd b x :\n  G.-sigma.-measurable [set` Interval -oo%O (BSide b x)].\nProof.\nby rewrite -setCitvr; apply: measurableC; exact: measurable_itv_bnd_infty.\nQed.\n\nLemma measurable_itv_bounded a x b y :\n  G.-sigma.-measurable [set` Interval (BSide a x) (BSide b y)].\nProof.\nmove: a b => [] []; rewrite -[X in measurable X]setCK setCitv;\n  apply: measurableC; apply: measurableU; try solve[\n    exact: measurable_itv_infty_bnd|exact: measurable_itv_bnd_infty].\nQed.\n\nLemma measurableE :\n  (R.-ocitv.-measurable).-sigma.-measurable = G.-sigma.-measurable.\nProof.\nrewrite eqEsubset; split => A.\n  apply: smallest_sub; first exact: smallest_sigma_algebra.\n  by move=> I [x _ <-]; apply: measurable_itv_bounded.\napply: smallest_sub; first exact: smallest_sigma_algebra.\nby move=> A' /= [x [y ->]]; apply: measurable_itv.\nQed.\n\nEnd rgenopens.\nEnd RGenOpens.\n\nSection erealwithrays.\nVariable R : realType.\nImplicit Types (x y z : \\bar R) (r s : R).\nLocal Open Scope ereal_scope.\n\nLemma EFin_itv_bnd_infty b r : EFin @` [set` Interval (BSide b r) +oo%O] =\n  [set` Interval (BSide b r%:E) +oo%O] `\\ +oo.\nProof.\nrewrite eqEsubset; split => [x [s /itvP rs <-]|x []].\n  split => //=; rewrite in_itv /=.\n  by case: b in rs *; rewrite /= ?(lee_fin, lte_fin) rs.\nmove: x => [s|_ /(_ erefl)|] //=; rewrite in_itv /= andbT; last first.\n  by case: b => /=; rewrite 1?(leNgt,ltNge) 1?(ltNyr, leNye).\nby case: b => /=; rewrite 1?(lte_fin,lee_fin) => rs _;\n  exists s => //; rewrite in_itv /= rs.\nQed.\n\nLemma EFin_itv r : [set s | r%:E < s%:E] = `]r, +oo[%classic.\nProof.\nby rewrite predeqE => s; split => [|]; rewrite /= lte_fin in_itv/= andbT.\nQed.\n\nLemma preimage_EFin_setT : @EFin R @^-1` [set x | x \\in `]-oo%E, +oo[] = setT.\nProof.\nby rewrite set_itvE predeqE => r; split=> // _; rewrite /preimage /= ltNyr.\nQed.\n\nLemma eitv_bnd_infty b r : `[r%:E, +oo[%classic =\n  \\bigcap_k [set` Interval (BSide b (r - k.+1%:R^-1)%:E) +oo%O] :> set _.\nProof.\nrewrite predeqE => x; split=> [|].\n- move: x => [s /=| _ n _|//].\n  + rewrite in_itv /= andbT lee_fin => rs n _ /=; rewrite in_itv/= andbT.\n    case: b => /=.\n    * by rewrite lee_fin ler_subl_addl (le_trans rs)// ler_addr.\n    * by rewrite lte_fin ltr_subl_addl (le_lt_trans rs)// ltr_addr.\n  + by rewrite /= in_itv /= andbT; case: b => /=; rewrite lteey.\n- move: x => [s| |/(_ 0%N Logic.I)] /=; rewrite ?in_itv/= ?leey//; last first.\n    by case: b.\n  move=> h; rewrite lee_fin leNgt andbT; apply/negP => /ltr_add_invr[k skr].\n  have {h} := h k Logic.I; rewrite /= in_itv /= andbT; case: b => /=.\n  + by rewrite lee_fin ler_subl_addr leNgt skr.\n  + by rewrite lte_fin ltr_subl_addr ltNge (ltW skr).\nQed.\n\nLemma eitv_infty_bnd b r : `]-oo, r%:E]%classic =\n  \\bigcap_k [set` Interval -oo%O (BSide b (r%:E + k.+1%:R^-1%:E))] :> set _.\nProof.\nrewrite predeqE => x; split=> [|].\n- move: x => [s /=|//|_ n _].\n  + rewrite in_itv /= lee_fin => sr n _; rewrite /= in_itv /= -EFinD.\n    case: b => /=.\n    * by rewrite lte_fin (le_lt_trans sr)// ltr_addl.\n    * by rewrite lee_fin (le_trans sr)// ler_addl.\n  + by rewrite /= in_itv /= -EFinD; case: b => //=; rewrite lteNye.\n- move: x => [s|/(_ 0%N Logic.I)|]/=; rewrite !in_itv/= ?leNye//; last first.\n    by case: b.\n  move=> h; rewrite lee_fin leNgt; apply/negP => /ltr_add_invr[k rks].\n  have {h} := h k Logic.I; rewrite /= in_itv /= -EFinD; case: b => /=.\n  + by rewrite lte_fin ltNge (ltW rks).\n  + by rewrite lee_fin leNgt rks.\nQed.\n\nLemma eset1Ny :\n  [set -oo] = \\bigcap_k `]-oo, (-k%:R%:E)[%classic :> set (\\bar R).\nProof.\nrewrite eqEsubset; split=> [_ -> i _ |]; first by rewrite /= in_itv /= ltNyr.\nmove=> [r|/(_ O Logic.I)|]//.\nmove=> /(_ `|floor r|%N Logic.I); rewrite /= in_itv/= ltNge.\nrewrite lee_fin; have [r0|r0] := leP 0%R r.\n  by rewrite (le_trans _ r0) // ler_oppl oppr0 ler0n.\nrewrite ler_oppl -abszN natr_absz gtr0_norm; last first.\n  by rewrite ltr_oppr oppr0 floor_lt0.\nby rewrite mulrNz ler_oppl opprK floor_le.\nQed.\n\nLemma eset1y : [set +oo] = \\bigcap_k `]k%:R%:E, +oo[%classic :> set (\\bar R).\nProof.\nrewrite eqEsubset; split=> [_ -> i _/=|]; first by rewrite in_itv /= ltry.\nmove=> [r| |/(_ O Logic.I)] // /(_ `|ceil r|%N Logic.I); rewrite /= in_itv /=.\nrewrite andbT lte_fin ltNge.\nhave [r0|r0] := ltP 0%R r; last by rewrite (le_trans r0).\nby rewrite natr_absz gtr0_norm // ?ceil_ge// ceil_gt0.\nQed.\n\nEnd erealwithrays.\n\nModule ErealGenOInfty.\nSection erealgenoinfty.\nVariable R : realType.\nImplicit Types (x y z : \\bar R) (r s : R).\n\nLocal Open Scope ereal_scope.\n\nDefinition G := [set A : set \\bar R | exists r, A = `]r%:E, +oo[%classic].\n\nLemma measurable_set1Ny : G.-sigma.-measurable [set -oo].\nProof.\nrewrite eset1Ny; apply: bigcap_measurable => i _.\nrewrite -setCitvr; apply: measurableC; rewrite (eitv_bnd_infty false).\napply: bigcap_measurable => j _; apply: sub_sigma_algebra.\nby exists (- (i%:R + j.+1%:R^-1))%R; rewrite opprD.\nQed.\n\nLemma measurable_set1y : G.-sigma.-measurable [set +oo].\nProof.\nrewrite eset1y; apply: bigcapT_measurable => i.\nby apply: sub_sigma_algebra; exists i%:R.\nQed.\n\nLemma measurableE : emeasurable (R.-ocitv.-measurable) = G.-sigma.-measurable.\nProof.\napply/seteqP; split; last first.\n  apply: smallest_sub.\n    split; first exact: emeasurable0.\n      by move=> *; rewrite setTD; exact: emeasurableC.\n    by move=> *; exact: bigcupT_emeasurable.\n  move=> _ [r ->]; rewrite /emeasurable /=.\n  exists `]r, +oo[%classic.\n    rewrite RGenOInfty.measurableE.\n    exact: RGenOInfty.measurable_itv_bnd_infty.\n  by exists [set +oo]; [constructor|rewrite -punct_eitv_bndy].\nmove=> A [B mB [C mC]] <-; apply: measurableU; last first.\n  case: mC; [by []|exact: measurable_set1Ny|exact: measurable_set1y|].\n  - by apply: measurableU; [exact: measurable_set1Ny|exact: measurable_set1y].\nrewrite RGenOInfty.measurableE in mB.\nhave smB := smallest_sub _ _ mB.\n(* BUG: elim/smB : _. fails !! *)\napply: (smB (G.-sigma.-measurable \\o (image^~ EFin))); last first.\n  move=> _ [r ->]/=; rewrite EFin_itv_bnd_infty; apply: measurableD.\n    by apply: sub_sigma_algebra => /=; exists r.\n  exact: measurable_set1y.\nsplit=> /= [|D mD|F mF]; first by rewrite image_set0.\n- rewrite setTD EFin_setC; apply: measurableD; first exact: measurableC.\n  by apply: measurableU; [exact: measurable_set1Ny| exact: measurable_set1y].\n- by rewrite EFin_bigcup; apply: bigcup_measurable => i _ ; exact: mF.\nQed.\n\nEnd erealgenoinfty.\nEnd ErealGenOInfty.\n\nModule ErealGenCInfty.\nSection erealgencinfty.\nVariable R : realType.\nImplicit Types (x y z : \\bar R) (r s : R).\nLocal Open Scope ereal_scope.\n\nDefinition G := [set A : set \\bar R | exists r, A = `[r%:E, +oo[%classic].\n\nLemma measurable_set1Ny : G.-sigma.-measurable [set -oo].\nProof.\nrewrite eset1Ny; apply: bigcapT_measurable=> i; rewrite -setCitvr.\nby apply: measurableC; apply: sub_sigma_algebra; exists (- i%:R)%R.\nQed.\n\nLemma measurable_set1y : G.-sigma.-measurable [set +oo].\nProof.\nrewrite eset1y; apply: bigcap_measurable => i _.\nrewrite -setCitvl; apply: measurableC; rewrite (eitv_infty_bnd true).\napply: bigcap_measurable => j _; rewrite -setCitvr; apply: measurableC.\nby apply: sub_sigma_algebra; exists (i%:R + j.+1%:R^-1)%R.\nQed.\n\nLemma measurableE : emeasurable (R.-ocitv.-measurable) = G.-sigma.-measurable.\nProof.\napply/seteqP; split; last first.\n  apply: smallest_sub.\n    split; first exact: emeasurable0.\n      by move=> *; rewrite setTD; exact: emeasurableC.\n    by move=> *; exact: bigcupT_emeasurable.\n  move=> _ [r ->]/=; exists `[r, +oo[%classic.\n    rewrite RGenOInfty.measurableE.\n    exact: RGenOInfty.measurable_itv_bnd_infty.\n  by exists [set +oo]; [constructor|rewrite -punct_eitv_bndy].\nmove=> _ [A' mA' [C mC]] <-; apply: measurableU; last first.\n  case: mC; [by []|exact: measurable_set1Ny| exact: measurable_set1y|].\n  by apply: measurableU; [exact: measurable_set1Ny|exact: measurable_set1y].\nrewrite RGenCInfty.measurableE in mA'.\nhave smA' := smallest_sub _ _ mA'.\n(* BUG: elim/smA' : _. fails !! *)\napply: (smA' (G.-sigma.-measurable \\o (image^~ EFin))); last first.\n  move=> _ [r ->]/=; rewrite EFin_itv_bnd_infty; apply: measurableD.\n    by apply: sub_sigma_algebra => /=; exists r.\n  exact: measurable_set1y.\nsplit=> /= [|D mD|F mF]; first by rewrite image_set0.\n- rewrite setTD EFin_setC; apply: measurableD; first exact: measurableC.\n  by apply: measurableU; [exact: measurable_set1Ny|exact: measurable_set1y].\n- by rewrite EFin_bigcup; apply: bigcup_measurable => i _; exact: mF.\nQed.\n\nEnd erealgencinfty.\nEnd ErealGenCInfty.\n\nModule ErealGenInftyO.\nSection erealgeninftyo.\nVariable R : realType.\n\nDefinition G := [set A : set \\bar R | exists r, A = `]-oo, r%:E[%classic].\n\nLemma measurableE : emeasurable (R.-ocitv.-measurable) = G.-sigma.-measurable.\nProof.\nrewrite ErealGenCInfty.measurableE eqEsubset; split => A.\n  apply: smallest_sub; first exact: smallest_sigma_algebra.\n  move=> _ [x ->]; rewrite -[X in _.-measurable X]setCK; apply: measurableC.\n  by apply: sub_sigma_algebra; exists x; rewrite setCitvr.\napply: smallest_sub; first exact: smallest_sigma_algebra.\nmove=> x Gx; rewrite -(setCK x); apply: measurableC; apply: sub_sigma_algebra.\nby case: Gx => y ->; exists y; rewrite setCitvl.\nQed.\n\nEnd erealgeninftyo.\nEnd ErealGenInftyO.\n\nSection trace.\nVariable (T : Type).\nImplicit Types (G : set (set T)) (A D : set T).\n\n(* intended as a trace sigma-algebra *)\nDefinition strace G D := [set x `&` D | x in G].\n\nLemma stracexx G D : G D -> strace G D D.\nProof. by rewrite /strace /=; exists D => //; rewrite setIid. Qed.\n\nLemma sigma_algebra_strace G D :\n  sigma_algebra setT G -> sigma_algebra D (strace G D).\nProof.\nmove=> [G0 GC GU]; split; first by exists set0 => //; rewrite set0I.\n- move=> S [A mA ADS]; have mCA := GC _ mA.\n  have : strace G D (D `&` ~` A).\n    by rewrite setIC; exists (setT `\\` A) => //; rewrite setTD.\n  rewrite -setDE => trDA.\n  have DADS : D `\\` A = D `\\` S by rewrite -ADS !setDE setCI setIUr setICr setU0.\n  by rewrite DADS in trDA.\n- move=> S mS; have /choice[M GM] : forall n, exists A, G A /\\ S n = A `&` D.\n    by move=> n; have [A mA ADSn] := mS n; exists A.\n  exists (\\bigcup_i (M i)); first by apply GU => i;  exact: (GM i).1.\n  by rewrite setI_bigcupl; apply eq_bigcupr => i _; rewrite (GM i).2.\nQed.\n\nEnd trace.\n\nLemma strace_measurable d (T : measurableType d) (A : set T) : measurable A ->\n  strace measurable A `<=` measurable.\nProof. by move=> mA=> _ [C mC <-]; apply: measurableI. Qed.\n\n(* more properties of measurable functions *)\n\nLemma is_interval_measurable (R : realType) (I : set R) :\n  is_interval I -> measurable I.\nProof. by move/is_intervalP => ->; exact: measurable_itv. Qed.\n\nSection coutinuous_measurable.\nVariable R : realType.\n\nLemma open_measurable (U : set R) : open U -> measurable U.\nProof.\nmove=> /open_bigcup_rat ->; rewrite bigcup_mkcond; apply: bigcupT_measurable_rat.\nmove=> q; case: ifPn => // qfab; apply: is_interval_measurable => //.\nexact: is_interval_bigcup_ointsub.\nQed.\n\nLemma open_measurable_subspace (D : set R) (U : set (subspace D)) :\n  measurable D -> open U -> measurable (D `&` U).\nProof.\nmove=> mD /open_subspaceP [V [oV] VD]; rewrite setIC -VD.\nby apply: measurableI => //; exact: open_measurable.\nQed.\n\nLemma subspace_continuous_measurable_fun (D : set R) (f : subspace D -> R) :\n  measurable D -> continuous f -> measurable_fun D f.\nProof.\nmove=> mD /continuousP cf; apply: (measurability (RGenOpens.measurableE R)).\nmove=> _ [_ [a [b ->] <-]]; apply: open_measurable_subspace => //.\nby exact/cf/interval_open.\nQed.\n\nCorollary open_continuous_measurable_fun (D : set R) (f : R -> R) :\n  open D -> {in D, continuous f} -> measurable_fun D f.\nProof.\nmove=> oD; rewrite -(continuous_open_subspace f oD).\nby apply: subspace_continuous_measurable_fun; exact: open_measurable.\nQed.\n\nLemma continuous_measurable_fun (f : R -> R) :\n  continuous f -> measurable_fun setT f.\nProof.\nby move=> cf; apply: open_continuous_measurable_fun => //; exact: openT.\nQed.\n\nEnd coutinuous_measurable.\n\nSection standard_measurable_fun.\n\nLemma measurable_fun_opp (R : realType) : measurable_fun [set: R] -%R.\nProof.\napply: continuous_measurable_fun.\nby have := @opp_continuous R [the normedModType R of R^o].\nQed.\n\nLemma measurable_fun_normr (R : realType) (D : set R) :\n  measurable_fun D (@normr _ R).\nProof.\nmove=> mD; apply: (measurability (RGenOInfty.measurableE R)) => //.\nmove=> /= _ [_ [x ->] <-]; apply: measurableI => //.\nhave [x0|x0] := leP 0 x.\n  rewrite [X in measurable X](_ : _ = `]-oo, (- x)[ `|` `]x, +oo[)%classic.\n    by apply: measurableU; apply: measurable_itv.\n  rewrite predeqE => r; split => [|[|]]; rewrite preimage_itv ?in_itv ?andbT/=.\n  - have [r0|r0] := leP 0 r; [rewrite ger0_norm|rewrite ltr0_norm] => // xr;\n      rewrite 2!in_itv/=.\n    + by right; rewrite xr.\n    + by left; rewrite ltr_oppr.\n  - move=> rx /=.\n    by rewrite ler0_norm 1?ltr_oppr// (le_trans (ltW rx))// ler_oppl oppr0.\n  - by rewrite in_itv /= andbT => xr; rewrite (lt_le_trans _ (ler_norm _)).\nrewrite [X in measurable X](_ : _ = setT)// predeqE => r.\nby split => // _; rewrite /= in_itv /= andbT (lt_le_trans x0).\nQed.\n\nEnd standard_measurable_fun.\n\n#[global] Hint Extern 0 (measurable_fun _ normr) =>\n  solve [exact: measurable_fun_normr] : core.\n\nSection measurable_fun_realType.\nContext d (T : measurableType d) (R : realType).\nImplicit Types (D : set T) (f g : T -> R).\n\nLemma measurable_funD D f g :\n  measurable_fun D f -> measurable_fun D g -> measurable_fun D (f \\+ g).\nProof.\nmove=> mf mg mD; apply: (measurability (RGenOInfty.measurableE R)) => //.\nmove=> /= _ [_ [a ->] <-]; rewrite preimage_itv_o_infty.\nrewrite [X in measurable X](_ : _ = \\bigcup_(q : rat)\n  ((D `&` [set x | ratr q < f x]) `&` (D `&` [set x | a - ratr q < g x]))).\n  apply: bigcupT_measurable_rat => q; apply: measurableI.\n  - by rewrite -preimage_itv_o_infty; apply: mf => //; apply: measurable_itv.\n  - by rewrite -preimage_itv_o_infty; apply: mg => //; apply: measurable_itv.\nrewrite predeqE => x; split => [|[r _] []/= [Dx rfx]] /= => [[Dx]|[_]].\n  rewrite -ltr_subl_addr => /rat_in_itvoo[r]; rewrite inE /= => /itvP h.\n  exists r => //; rewrite setIACA setIid; split => //; split => /=.\n    by rewrite h.\n  by rewrite ltr_subl_addr addrC -ltr_subl_addr h.\nby rewrite ltr_subl_addr=> afg; rewrite (lt_le_trans afg)// addrC ler_add2r ltW.\nQed.\n\nLemma measurable_funrM D f (k : R) : measurable_fun D f ->\n  measurable_fun D (fun x => k * f x).\nProof.\napply: (@measurable_funT_comp _ _ _ _ _ _ ( *%R k)).\nby apply: continuous_measurable_fun; apply: mulrl_continuous.\nQed.\n\nLemma measurable_funN D f : measurable_fun D f -> measurable_fun D (-%R \\o f).\nProof.\nmove=> mf mD; rewrite (_ : _ \\o _ = (fun x => - 1 * f x)).\n  exact: measurable_funrM.\nby under eq_fun do rewrite mulN1r.\nQed.\n\nLemma measurable_funB D f g : measurable_fun D f ->\n  measurable_fun D g -> measurable_fun D (f \\- g).\nProof.\nby move=> ? ? ?; apply: measurable_funD => //; exact: measurable_funN.\nQed.\n\nLemma measurable_fun_exprn D n f :\n  measurable_fun D f -> measurable_fun D (fun x => f x ^+ n).\nProof.\napply: measurable_funT_comp ((@GRing.exp R)^~ n) _ _ _.\nby apply: continuous_measurable_fun; apply: exprn_continuous.\nQed.\n\nLemma measurable_fun_sqr D f :\n  measurable_fun D f -> measurable_fun D (fun x => f x ^+ 2).\nProof. exact: measurable_fun_exprn. Qed.\n\nLemma measurable_funM D f g :\n  measurable_fun D f -> measurable_fun D g -> measurable_fun D (f \\* g).\nProof.\nmove=> mf mg mD; rewrite (_ : (_ \\* _) = (fun x => 2%:R^-1 * (f x + g x) ^+ 2)\n  \\- (fun x => 2%:R^-1 * (f x ^+ 2)) \\- (fun x => 2%:R^-1 * ( g x ^+ 2))).\n  apply: measurable_funB => //; last first.\n    by apply: measurable_funrM => //; exact: measurable_fun_sqr.\n  apply: measurable_funB => //; last first.\n    by apply: measurable_funrM => //; exact: measurable_fun_sqr.\n  apply: measurable_funrM => //.\n  by apply: measurable_fun_sqr => //; exact: measurable_funD.\nrewrite funeqE => x /=; rewrite -2!mulrBr sqrrD (addrC (f x ^+ 2)) -addrA.\nrewrite -(addrA (f x * g x *+ 2)) -opprB opprK (addrC (g x ^+ 2)) addrK.\nby rewrite -(mulr_natr (f x * g x)) -(mulrC 2) mulrA mulVr ?mul1r// unitfE.\nQed.\n\nLemma measurable_fun_max D f g :\n  measurable_fun D f -> measurable_fun D g -> measurable_fun D (f \\max g).\nProof.\nmove=> mf mg mD; apply (measurability (RGenCInfty.measurableE R)) => //.\nmove=> _ [_ [x ->] <-]; rewrite [X in measurable X](_ : _ =\n    (D `&` f @^-1` `[x, +oo[) `|` (D `&` g @^-1` `[x, +oo[)); last first.\n  rewrite predeqE => t /=; split.\n    by rewrite /= !in_itv /= !andbT le_maxr => -[Dx /orP[|]]; tauto.\n  by move=> [|]; rewrite !in_itv/= !andbT le_maxr => -[Dx ->]//; rewrite orbT.\nby apply: measurableU; [apply: mf|apply: mg] =>//; apply: measurable_itv.\nQed.\n\nLemma measurable_fun_sups D (h : (T -> R)^nat) n :\n  (forall t, D t -> has_ubound (range (h ^~ t))) ->\n  (forall m, measurable_fun D (h m)) ->\n  measurable_fun D (fun x => sups (h ^~ x) n).\nProof.\nmove=> f_ub mf mD; apply: (measurability (RGenOInfty.measurableE R)) => //.\nmove=> _ [_ [x ->] <-]; rewrite sups_preimage // setI_bigcupr.\nby apply: bigcup_measurable => k /= nk; apply: mf => //; exact: measurable_itv.\nQed.\n\nLemma measurable_fun_infs D (h : (T -> R)^nat) n :\n  (forall t, D t -> has_lbound (range (h ^~ t))) ->\n  (forall n, measurable_fun D (h n)) ->\n  measurable_fun D (fun x => infs (h ^~ x) n).\nProof.\nmove=> lb_f mf mD; apply: (measurability (RGenInftyO.measurableE R)) =>//.\nmove=> _ [_ [x ->] <-]; rewrite infs_preimage // setI_bigcupr.\nby apply: bigcup_measurable => k /= nk; apply: mf => //; exact: measurable_itv.\nQed.\n\nLemma measurable_fun_lim_sup D (h : (T -> R)^nat) :\n  (forall t, D t -> has_ubound (range (h ^~ t))) ->\n  (forall t, D t -> has_lbound (range (h ^~ t))) ->\n  (forall n, measurable_fun D (h n)) ->\n  measurable_fun D (fun x => lim_sup (h ^~ x)).\nProof.\nmove=> f_ub f_lb mf.\nhave : {in D, (fun x => inf [set sups (h ^~ x) n | n in [set n | 0 <= n]%N])\n              =1 (fun x => lim_sup (h^~ x))}.\n  move=> t; rewrite inE => Dt; apply/esym/cvg_lim; first exact: Rhausdorff.\n  rewrite [X in _ --> X](_ : _ = inf (range (sups (h^~t)))).\n    by apply: cvg_sups_inf; [exact: f_ub|exact: f_lb].\n  by congr (inf [set _ | _ in _]); rewrite predeqE.\nmove/eq_measurable_fun; apply; apply: measurable_fun_infs => //.\n  move=> t Dt; have [M hM] := f_lb _ Dt; exists M => _ [m /= nm <-].\n  rewrite (@le_trans _ _ (h m t)) //; first by apply hM => /=; exists m.\n  by apply: sup_ub; [exact/has_ubound_sdrop/f_ub|exists m => /=].\nby move=> k; exact: measurable_fun_sups.\nQed.\n\nLemma measurable_fun_cvg D (h : (T -> R)^nat) f :\n  (forall m, measurable_fun D (h m)) -> (forall x, D x -> h ^~ x --> f x) ->\n  measurable_fun D f.\nProof.\nmove=> mf_ f_f; have fE x : D x -> f x = lim_sup (h ^~ x).\n  move=> Dx; have /cvg_lim  <-// := @cvg_sups _ (h ^~ x) (f x) (f_f _ Dx).\n  exact: Rhausdorff.\napply: (@eq_measurable_fun _ _ _ _ D (fun x => lim_sup (h ^~ x))).\n  by move=> x; rewrite inE => Dx; rewrite -fE.\napply: (@measurable_fun_lim_sup _ h) => // t Dt.\n- apply/bounded_fun_has_ubound/(@cvg_seq_bounded _ [normedModType R of R^o]).\n  by apply/cvg_ex; eexists; exact: f_f.\n- apply/bounded_fun_has_lbound/(@cvg_seq_bounded _ [normedModType R of R^o]).\n  by apply/cvg_ex; eexists; exact: f_f.\nQed.\n\nEnd measurable_fun_realType.\n\nLemma measurable_fun_ln (R : realType) : measurable_fun [set~ (0:R)] (@ln R).\nProof.\nrewrite (_ : [set~ 0] = `]-oo, 0[ `|` `]0, +oo[); last first.\n  by rewrite -(setCitv `[0, 0]); apply/seteqP; split => [|]x/=;\n    rewrite in_itv/= -eq_le eq_sym; [move/eqP/negbTE => ->|move/negP/eqP].\napply/measurable_funU; [exact: measurable_itv|exact: measurable_itv|split].\n- apply/(@measurable_restrict _ _ _ _ _ setT)=> //; first exact: measurable_itv.\n  rewrite (_ : _ \\_ _ = cst (0:R)); first exact: measurable_fun_cst.\n  apply/funext => y; rewrite patchE.\n  by case: ifPn => //; rewrite inE/= in_itv/= => y0; rewrite ln0// ltW.\n- have : {in `]0, +oo[%classic, continuous (@ln R)}.\n    by move=> x; rewrite inE/= in_itv/= andbT => x0; exact: continuous_ln.\n  rewrite -continuous_open_subspace; last exact: interval_open.\n  by move/subspace_continuous_measurable_fun; apply; exact: measurable_itv.\nQed.\n\nLemma measurable_fun_power_pos (R : realType) p :\n  measurable_fun [set: R] (@power_pos R ^~ p).\nProof.\napply: measurable_fun_if => //.\n- apply: (measurable_fun_bool true); rewrite (_ : _ @^-1` _ = [set 0])//.\n  by apply/seteqP; split => [_ /eqP ->//|_ -> /=]; rewrite eqxx.\n- exact: measurable_fun_cst.\n- rewrite setTI; apply: (@measurable_fun_comp _ _ _ _ _ _ setT) => //.\n    by apply: continuous_measurable_fun; exact: continuous_expR.\n  rewrite (_ : _ @^-1` _ = [set~ 0]); last first.\n    by apply/seteqP; split => [x [/negP/negP/eqP]|x x0]//=; exact/negbTE/eqP.\n  by apply: measurable_funrM; exact: measurable_fun_ln.\nQed.\n\nSection standard_emeasurable_fun.\nVariable R : realType.\n\nLemma measurable_fun_EFin (D : set R) : measurable_fun D EFin.\nProof.\nmove=> mD; apply: (measurability (ErealGenOInfty.measurableE R)) => //.\nmove=> /= _ [_ [x ->]] <-; apply: measurableI => //.\nby rewrite preimage_itv_o_infty EFin_itv; exact: measurable_itv.\nQed.\n\nLemma measurable_fun_abse (D : set (\\bar R)) : measurable_fun D abse.\nProof.\nmove=> mD; apply: (measurability (ErealGenOInfty.measurableE R)) => //.\nmove=> /= _ [_ [x ->] <-].\nrewrite [X in _ @^-1` X](punct_eitv_bndy _ x) preimage_setU setIUr.\napply: measurableU; last first.\n  by rewrite preimage_abse_pinfty; apply: measurableI => //; exact: measurableU.\napply: measurableI => //; exists (normr @^-1` `]x, +oo[%classic).\n  rewrite -[X in measurable X]setTI.\n  by apply: measurable_fun_normr => //; exact: measurable_itv.\nexists set0; first by constructor.\nrewrite setU0 predeqE => -[y| |]; split => /= => -[r];\n  rewrite ?/= /= ?in_itv /= ?andbT => xr//.\n  + by move=> [ry]; exists `|y| => //=; rewrite in_itv/= andbT -ry.\n  + by move=> [ry]; exists y => //=; rewrite /= in_itv/= andbT -ry.\nQed.\n\nLemma emeasurable_fun_minus (D : set (\\bar R)) :\n  measurable_fun D (-%E : \\bar R -> \\bar R).\nProof.\nmove=> mD; apply: (measurability (ErealGenCInfty.measurableE R)) => //.\nmove=> _ [_ [x ->] <-]; rewrite (_ : _ @^-1` _ = `]-oo, (- x)%:E]%classic).\n  by apply: measurableI => //; exact: emeasurable_itv.\nby rewrite predeqE => y; rewrite preimage_itv !in_itv/= andbT in_itv lee_oppr.\nQed.\n\nEnd standard_emeasurable_fun.\n#[global] Hint Extern 0 (measurable_fun _ abse) =>\n  solve [exact: measurable_fun_abse] : core.\n#[global] Hint Extern 0 (measurable_fun _ EFin) =>\n  solve [exact: measurable_fun_EFin] : core.\n\n(* NB: real-valued function *)\nLemma EFin_measurable_fun d (T : measurableType d) (R : realType) (D : set T)\n    (g : T -> R) :\n  measurable_fun D (EFin \\o g) <-> measurable_fun D g.\nProof.\nsplit=> [mf mD A mA|]; last by move=> mg; exact: measurable_funT_comp.\nrewrite [X in measurable X](_ : _ = D `&` (EFin \\o g) @^-1` (EFin @` A)).\n  by apply: mf => //; exists A => //; exists set0; [constructor|rewrite setU0].\ncongr (_ `&` _);rewrite eqEsubset; split=> [|? []/= _ /[swap] -[->//]].\nby move=> ? ?; exact: preimage_image.\nQed.\n\nSection emeasurable_fun.\nLocal Open Scope ereal_scope.\nContext d (T : measurableType d) (R : realType).\nImplicit Types (D : set T).\n\nLemma emeasurable_fun_bool (D : set T) (f : T -> bool) b :\n  measurable (f @^-1` [set b]) -> measurable_fun D f.\nProof.\nhave FNT : [set false] = [set~ true] by apply/seteqP; split => -[]//=.\nwlog {b}-> : b / b = true.\n  case: b => [|h]; first exact.\n  by rewrite FNT -preimage_setC => /measurableC; rewrite setCK; exact: h.\nmove=> mfT mD /= Y; have := @subsetT _ Y; rewrite setT_bool => YT.\nhave [-> _|-> _|-> _ |-> _] := subset_set2 YT.\n- by rewrite preimage0 ?setI0.\n- by apply: measurableI => //; exact: mfT.\n- rewrite -[X in measurable X]setCK; apply: measurableC; rewrite setCI.\n  apply: measurableU; first exact: measurableC.\n  by rewrite FNT preimage_setC setCK; exact: mfT.\n- by rewrite -setT_bool preimage_setT setIT.\nQed.\nArguments emeasurable_fun_bool {D f} b.\n\nLemma measurable_fun_einfs D (f : (T -> \\bar R)^nat) :\n  (forall n, measurable_fun D (f n)) ->\n  forall n, measurable_fun D (fun x => einfs (f ^~ x) n).\nProof.\nmove=> mf n mD.\napply: (measurability (ErealGenCInfty.measurableE R)) => //.\nmove=> _ [_ [x ->] <-]; rewrite einfs_preimage -bigcapIr; last by exists n => /=.\nby apply: bigcap_measurable => ? ?; exact/mf/emeasurable_itv.\nQed.\n\nLemma measurable_fun_esups D (f : (T -> \\bar R)^nat) :\n  (forall n, measurable_fun D (f n)) ->\n  forall n, measurable_fun D (fun x => esups (f ^~ x) n).\nProof.\nmove=> mf n mD; apply: (measurability (ErealGenOInfty.measurableE R)) => //.\nmove=> _ [_ [x ->] <-];rewrite esups_preimage setI_bigcupr.\nby apply: bigcup_measurable => ? ?; exact/mf/emeasurable_itv.\nQed.\n\nLemma emeasurable_fun_max D (f g : T -> \\bar R) :\n  measurable_fun D f -> measurable_fun D g ->\n  measurable_fun D (fun x => maxe (f x) (g x)).\nProof.\nmove=> mf mg mD; apply: (measurability (ErealGenCInfty.measurableE R)) => //.\nmove=> _ [_ [x ->] <-]; rewrite [X in measurable X](_ : _ =\n    (D `&` f @^-1` `[x%:E, +oo[) `|` (D `&` g @^-1` `[x%:E, +oo[)); last first.\n  rewrite predeqE => t /=; split.\n    by rewrite !/= /= !in_itv /= !andbT le_maxr => -[Dx /orP[|]];\n      tauto.\n  by move=> [|]; rewrite !/= /= !in_itv/= !andbT le_maxr;\n    move=> [Dx ->]//; rewrite orbT.\nby apply: measurableU; [exact/mf/emeasurable_itv| exact/mg/emeasurable_itv].\nQed.\n\nLemma emeasurable_funN D (f : T -> \\bar R) :\n  measurable_fun D f -> measurable_fun D (\\- f).\nProof. by apply: measurable_funT_comp => //; exact: emeasurable_fun_minus. Qed.\n\nLemma emeasurable_fun_funepos D (f : T -> \\bar R) :\n  measurable_fun D f -> measurable_fun D f^\\+.\nProof.\nby move=> mf; apply: emeasurable_fun_max => //; exact: measurable_fun_cst.\nQed.\n\nLemma emeasurable_fun_funeneg D (f : T -> \\bar R) :\n  measurable_fun D f -> measurable_fun D f^\\-.\nProof.\nby move=> mf; apply: emeasurable_fun_max => //;\n  [exact: emeasurable_funN|exact: measurable_fun_cst].\nQed.\n\nLemma emeasurable_fun_min D (f g : T -> \\bar R) :\n  measurable_fun D f -> measurable_fun D g ->\n  measurable_fun D (fun x => mine (f x) (g x)).\nProof.\nmove=> /emeasurable_funN mf /emeasurable_funN mg.\nhave /emeasurable_funN := emeasurable_fun_max mf mg.\nby apply eq_measurable_fun => i Di; rewrite -oppe_min oppeK.\nQed.\n\nLemma measurable_fun_lim_esup D (f : (T -> \\bar R)^nat) :\n  (forall n, measurable_fun D (f n)) ->\n  measurable_fun D (fun x => lim_esup (f ^~ x)).\nProof.\nmove=> mf mD; rewrite (_ :  (fun _ => _) =\n    (fun x => ereal_inf [set esups (f^~ x) n | n in [set n | n >= 0]%N])).\n  by apply: measurable_fun_einfs => // k; exact: measurable_fun_esups.\nrewrite funeqE => t; apply/cvg_lim => //.\nrewrite [X in _ --> X](_ : _ = ereal_inf (range (esups (f^~t)))).\n  exact: cvg_esups_inf.\nby congr (ereal_inf [set _ | _ in _]); rewrite predeqE.\nQed.\n\n#[deprecated(since=\"mathcomp-analysis 0.6.0\",\n  note=\"renamed `measurable_fun_lim_esup`\")]\nNotation measurable_fun_elim_sup := measurable_fun_lim_esup.\n\nLemma emeasurable_fun_cvg D (f_ : (T -> \\bar R)^nat) (f : T -> \\bar R) :\n  (forall m, measurable_fun D (f_ m)) ->\n  (forall x, D x -> f_ ^~ x --> f x) -> measurable_fun D f.\nProof.\nmove=> mf_ f_f; have fE x : D x -> f x = lim_esup (f_^~ x).\n  by move=> Dx; have /cvg_lim  <-// := @cvg_esups _ (f_^~x) (f x) (f_f x Dx).\napply: (measurable_fun_ext (fun x => lim_esup (f_ ^~ x))) => //.\n  by move=> x; rewrite inE => Dx; rewrite fE.\nexact: measurable_fun_lim_esup.\nQed.\n\nEnd emeasurable_fun.\nArguments emeasurable_fun_cvg {d T R D} f_.\n", "meta": {"author": "math-comp", "repo": "analysis", "sha": "ee12aba894e8949a32daa9d2ee72b3a440c0609f", "save_path": "github-repos/coq/math-comp-analysis", "path": "github-repos/coq/math-comp-analysis/analysis-ee12aba894e8949a32daa9d2ee72b3a440c0609f/theories/lebesgue_measure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6551558087070207}}
{"text": "Require Import Inverse_Image.\nFrom mathcomp Require Import all_ssreflect all_algebra order.\nFrom SsrMultinomials Require Import ssrcomplements freeg mpoly.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport Monoid GRing.Theory.\n\nOpen Scope ring_scope.\n\n(******************************************************************************)\n(******************************************************************************)\n(*                                                                            *)\n(* This file contains a proof that membership to an ideal defined by a        *)\n(* sequence of polynomials can be decided using Buchberger's algorithm        *)\n(* It introduces the following definitions:                                   *)\n(*                                                                            *)\n(*  plt p p'      : p is lexicographically smaller than p' for the order <%O  *)\n(*  ideal L p     : p is in the ideal generated by L                          *)\n(*  mdiv m p q    : remove the monomial m in p using the polynomial q         *)\n(*  mreduce L p q : p can be reduced to p by a division of a poynomial in L   *)\n(*  irreducible L p : p is irreducible by a polynomial in L                   *)\n(*  mreducef L p  : return an option type that gives a witness of a reduction *)\n(*                  of p by a polynomial in L                                 *)\n(*  mreduceplus L p q : p can be reduced in multiple steps to q               *)\n(*  mreducestar L p q : p can be reduced in multiple steps to q and q is      *)\n(*                      irreducible                                           *)\n(*  mreduceplusf L p : compute one irreducible reduction of p                 *)\n(*  grobner L     : L is a grobner basis                                      *)\n(*  mconfluent L  : the reduction defined for L is confluent                  *)\n(*  spoly p q     : the S-polynomial of p and q                               *)\n(*  spoly_red L   : all the S-polynomials of L reduce to 0                    *)\n(*  splt L L'     : the sequence of polynomial L' is smaller than L iff       *)\n(*                  L'is p :: L where p cannot be reduced by L                *)\n(*  mbuch_all L   : complete the sequence L to build a Grobner basis using    *)\n(*                  Buchberger's algorithm                                    *)\n(*  idealf L p    : check if p is in the ideal generated by L                 *)\n(*                                                                            *)\n(******************************************************************************)\n(******************************************************************************)\n\nImport Order.TTheory.\n\nSection Grobner.\n\n(******************************************************************************)\n(*        Ideals with respect to a list of polynomials                        *)\n(******************************************************************************)\n\nSection Ideal.\n\nVariable R : ringType.\nVariable n : nat.\n\nImplicit Types p q : {mpoly R[n]}.\nImplicit Types m : 'X_{1..n}.\n\nVariable L : seq {mpoly R[n]}.\n\nDefinition ideal p : Prop :=\n  exists (t : (size L).-tuple _), p = \\sum_(i < size L) t`_i * L`_i.\n\nLemma ideal0 : ideal 0.\nProof.\nexists (nseq_tuple _ 0).\nrewrite big1 // => i /=.\nby rewrite nth_nseq if_same mul0r.\nQed.\n\nLemma idealZ a p : ideal p -> ideal (a *: p).\nProof.\ncase=>t ->.\nexists [tuple (a *: t`_i) | i < size L] => //.\nrewrite scaler_sumr; apply: eq_bigr => i _ /=.\nby rewrite (nth_map i) ?size_enum_ord // nth_enum_ord // mpoly_scaleAl.\nQed.\n\nLemma idealN p : ideal p -> ideal (-p).\nProof.\ncase=>t ->.\nexists [tuple - t`_i | i < size L] => //.\nrewrite -sumrN; apply: eq_bigr => i _ /=.\nby rewrite (nth_map i) ?size_enum_ord // nth_enum_ord // -mulNr.\nQed.\n\nLemma idealD p q : ideal p -> ideal q -> ideal (p + q).\nProof.\nmove=> [t1 ->][t2 ->].\nexists [tuple (t1`_i + t2`_i) | i < size L] => //.\nrewrite -big_split; apply: eq_bigr => i _ /=.\nby rewrite (nth_map i) ?size_enum_ord // nth_enum_ord // mulrDl.\nQed.\n\nLemma idealB p q : ideal p -> ideal q -> ideal (p - q).\nProof. by move=> Ip Iq; apply: idealD => //; apply: idealN. Qed.\n\nLemma idealM p q : ideal q -> ideal (p * q).\nProof.\ncase=>t ->.\nexists [tuple (p * t`_i) | i < size L] => //.\nrewrite mulr_sumr; apply: eq_bigr => i _ /=.\nby rewrite (nth_map i) ?size_enum_ord //  nth_enum_ord // mulrA.\nQed.\n\nLemma ideal_mem p : p \\in L -> ideal p.\nProof.\nmove=> Ip.\nhave Hp : (index p L < size L)%nat by rewrite index_mem.\npose j := Ordinal Hp.\nexists [tuple if i == j then 1 else 0 | i < size L].\nrewrite (bigD1 j) //= big1 /= => [|[i /= Hi] /= iDj]; last first.\n- rewrite (nth_map j) ?size_enum_ord //=.\n  case: ifP; last by rewrite mul0r.\n  move/eqP/val_eqP; rewrite /= nth_enum_ord => //= HH.\n  by case/eqP: iDj; apply/val_eqP => /=.\nrewrite (nth_map j) ?size_enum_ord //=.\ncase: ifP; last first.\n- by move/eqP/val_eqP; rewrite /= nth_enum_ord // eqxx.\nby rewrite nth_index // addr0 mul1r.\nQed.\n\nEnd Ideal.\n\nLemma ideal_consr (R : ringType) n l (p q : {mpoly R[n]}) :\n  ideal l p -> ideal (q::l) p.\nProof.\ncase=> t ->; exists [tuple of 0 :: t] => /=.\nby rewrite big_ord_recl /= mul0r add0r.\nQed.\n\nLemma ideal_consl (R : ringType) n l (p q : {mpoly R[n]}) :\n  ideal l p -> ideal (p::l) q -> ideal l q.\nProof.\ncase=> [t1] ->; case=> /= t2 ->.\nexists [tuple (t2`_0 * t1`_i + t2`_(fintype.lift ord0 i))| i < size l].\nrewrite big_ord_recl [X in _ * X + _ = _]/=.\nrewrite mulr_sumr -big_split.\napply: eq_bigr => i _ /=.\nrewrite (nth_map i); last by rewrite size_enum_ord ltn_ord.\nrewrite nth_enum_ord; last by apply: ltn_ord.\nby rewrite mulrDl mulrA.\nQed.\n\n(******************************************************************************)\n(*          Order on polynomials derived from (_ < _)%O                       *)\n(******************************************************************************)\n\nSection Order.\n\nVariable R : ringType.\nVariable n : nat.\n\nImplicit Types p q : {mpoly R[n]}.\nImplicit Types m : 'X_{1..n}.\n\nDefinition plt p q : bool :=\n  has (fun m2 =>\n         [&& m2 \\notin msupp p,\n            all (fun m1 => ((m1 < m2)%O || (m1 \\in msupp q))) (msupp p) &\n            all (fun m1 => ((m1 <= m2)%O || (m1 \\in msupp p))) (msupp q)])\n      (msupp q).\n\nLocal Notation \"a < b\" := (plt a b).\n\nLemma pltP p q :\n  reflect (exists m,\n             [/\\ m \\in msupp q, m \\notin msupp p &\n              forall m1, (m < m1)%O -> (m1 \\in msupp p) = (m1 \\in msupp q)])\n          (p < q).\nProof.\napply: (iffP hasP)=> [[m Im /and3P[NIm /allP /=Hq /allP Hp]]|[m [Im NIm HA]]].\n- exists m; split=> // m1 Lm.\n  have := Hq m1; have := Hp m1; do 2 case: (_ \\in _) => //=.\n  - by rewrite leNgt Lm => /(_ is_true_true).\n  by rewrite ltNge [(m <= _)%O]ltW // => _  /(_ is_true_true).\nexists m => //; apply/and3P; split=>//; apply/allP=> m1 Im1.\n- case: ltP=>//=.\n  by rewrite le_eqVlt => /orP[/eqP<-|/HA<-].\nby case: leP=>//= /HA->.\nQed.\n\nLemma plt_mlead p q : (mlead p < mlead q)%O -> (p < q).\nProof.\nhave [/eqP->|Zq] := boolP (q == 0); first by rewrite mlead0 ltx0.\nmove=> Lp; apply/pltP; exists (mlead q); split=> [||m1 Lm1].\n- by apply: mlead_supp.\n- by rewrite mcoeff_msupp negbK mcoeff_gt_mlead.\nrewrite !mcoeff_msupp !mcoeff_gt_mlead //.\nby apply: lt_trans Lm1.\nQed.\n\nLemma plt_anti p : p < p = false.\nProof. by apply/idP=> /hasP[x ->]. Qed.\n\nLemma plt0 p : (0 < p) = (p != 0).\nProof.\napply/pltP/idP=> [[m [Im NIm HA]]|Zp].\n- by apply/eqP=> Zp; move: Im; rewrite Zp msupp0 in_nil.\nexists (mlead p); rewrite msupp0 ?in_nil; split=> [||m1 HA] //=.\n- by apply: mlead_supp.\nby rewrite in_nil mcoeff_msupp mcoeff_gt_mlead ?eqxx.\nQed.\n\nLemma plt0r p : p < 0 = false.\nProof. by case: (boolP (_ < 0)) => // /hasP[m]; rewrite msupp0 // inE. Qed.\n\nLemma plt_trans : transitive plt.\nProof.\nmove=> r p q /pltP[m1 [Im1 NIm1 HAm1]] /pltP[m2 [Im2 NIm2 HAm2]].\nhave [Lm|Lm] := leP m1 m2.\n- apply/pltP; exists m2; split=> [||m3 Lm3] //.\n  - by move: Lm; rewrite le_eqVlt => /orP[/eqP<-//|/HAm1->].\n  by rewrite -HAm2 // HAm1 // (le_lt_trans Lm).\napply/pltP; exists m1; split=> [||m3 Lm3] //.\n- by rewrite -(HAm2 _ Lm).\nby rewrite HAm1 // -HAm2 // (lt_trans Lm).\nQed.\n\nLemma plt_lead (p q : {mpoly R[n]}) : (mlead p < mlead q)%O -> p < q.\nProof.\nhave [/eqP->|Zq] := boolP (q == 0); first by rewrite mlead0 ltx0.\nmove=> H; apply/pltP; exists (mlead q); split=> [||m1 Lm] //.\n- by apply: mlead_supp.\n- by rewrite mcoeff_msupp mcoeff_gt_mlead ?negbK.\nby rewrite !mcoeff_msupp !mcoeff_gt_mlead // (lt_trans _ Lm).\nQed.\n\nLemma plt_leadE (p q : {mpoly R[n]}) : p != 0 -> (p < q) ->\n  (mlead p < mlead q)%O ||\n  ((mlead p == mlead q) &&\n     (p - p@_(mlead q) *: 'X_[mlead q] < q - q@_(mlead q) *: 'X_[mlead q])).\nProof.\nhave [/eqP->|Zq] := boolP (q == 0); first by rewrite plt0r.\nmove=> Zp Lp.\nhave/pltP[m [Im NIm Lm]] := Lp; apply/orP.\nhave [/eqP Eq|Dq] := boolP (mlead q == m).\n- left; have [/Lm HH|] := boolP (m < mlead p)%O.\n  - have := mlead_supp Zp; rewrite HH => /msupp_le_mlead.\n    case: ltgtP=>// Ep _.\n    by case/negP: NIm; rewrite -Eq -Ep mlead_supp.\n  rewrite -leNgt le_eqVlt Eq => /orP[/eqP Ep|] //.\n  by case/negP: NIm; rewrite -Ep mlead_supp.\nright; apply/andP; split; last first.\n- apply/pltP; exists m; split=> [||m1 Lm1].\n  - rewrite (perm_mem (msupp_rem _ _)) (rem_filter _ (msupp_uniq _)).\n    by rewrite mem_filter /= eq_sym Dq.\n  - rewrite (perm_mem (msupp_rem _ _)) (rem_filter _ (msupp_uniq _)).\n    by rewrite mem_filter /= eq_sym Dq.\n  rewrite !(perm_mem (msupp_rem _ _)) !(rem_filter _ (msupp_uniq _)).\n  by rewrite !mem_filter /= Lm.\nhave: (mlead q <= mlead p)%O.\n- apply: msupp_le_mlead; rewrite Lm ?mlead_supp //.\n  by rewrite lt_neqAle eq_sym Dq msupp_le_mlead.\nrewrite le_eqVlt => /orP[/eqP->|] // /plt_mlead /(plt_trans Lp).\nby rewrite plt_anti.\nQed.\n\nLemma plt_mlast p q :\n  (p < q) ->\n  (exists p1 p2, [/\\ p = p1 + p2, perm_eq (msupp p1) (rem (mlast q) (msupp q))\n                     & p2 < 'X_[mlast q]])\n   \\/\n  (p < q - q@_(mlast q) *: 'X_[mlast q]).\nProof.\n(* Why this proof is so long? *)\nhave [/eqP->|Zq] := boolP (q == 0); first by rewrite plt0r.\ncase/pltP=> m [Im NIm Lm].\nhave [/eqP Eq|Dq] := boolP (mlast q == m); last first.\n- right; apply/pltP; exists m; split=> [||m3 Im3]//.\n  - rewrite (perm_mem (msupp_rem _ _)) rem_filter ?msupp_uniq //.\n    by rewrite mem_filter ?msupp_uniq //= eq_sym Dq.\n  rewrite (perm_mem (msupp_rem _ _)) rem_filter ?msupp_uniq //.\n  rewrite mem_filter ?msupp_uniq /=.\n  rewrite Lm // andbC; case: (boolP (_ \\in _)) => //=.\n  have: (mlast q < m3)%O.\n  - by apply: le_lt_trans Im3; apply: mlast_lemc.\n  by rewrite lt_neqAle [_ == m3]eq_sym => /andP[->].\npose p1 := \\sum_(i <- msupp p | (m < i)%O) p@_i *: 'X_[i].\npose p2 := \\sum_(i <- msupp p | (i < m)%O) p@_i *: 'X_[i].\nleft; exists p1, p2; split=> //.\n- rewrite [p]mpolyE (bigID (fun i => (m < i)%O)) /=; congr (_ + _).\n  rewrite big_seq_cond [p2]big_seq_cond.\n  apply: eq_bigl=> // m1.\n  rewrite -leNgt le_eqVlt.\n  by have [/eqP->|] := boolP (_ == _); first by rewrite (negPf NIm).\n- apply: uniq_perm=> [||m1]; first by apply: msupp_uniq.\n  - by apply/rem_uniq/msupp_uniq.\n  rewrite (rem_filter _ (msupp_uniq _)).\n  rewrite mem_filter /= (perm_mem (msupp_sum _ _ _))=>\n         [||m2 m3 Im2 Im3 Dm2m3 m4 /=].\n  - apply/flattenP/andP=>[[m2 /mapP[m3]]|[Dm LL]].\n      rewrite mem_filter => /andP[H1 H2] -> /msuppZ_le.\n      rewrite mcoeff_msupp mcoeffX.\n      have [/eqP<- _|] := boolP (_ == m1); last by rewrite eqxx.\n      split; last by rewrite -Lm.\n      have: (mlast q < m3)%O by rewrite (le_lt_trans (mlast_lemc _) H1).\n      by rewrite eq_sym lt_neqAle; case/andP.\n    exists [::m1]; last by rewrite inE.\n    apply/mapP; exists m1.\n    - rewrite mem_filter ?LL.\n      suff F : (m < m1)%O by rewrite F Lm.\n      by have := mlast_lemc LL; rewrite le_eqVlt eq_sym (negPf Dm) Eq.\n    by rewrite msuppMCX // -mcoeff_msupp Lm //\n               lt_neqAle -Eq eq_sym Dm mlast_lemc.\n  - by apply: msupp_uniq.\n  rewrite !msuppMCX -?mcoeff_msupp // !inE.\n  by case: (boolP (_ == m2)) => // /eqP->; rewrite (negPf Dm2m3).\napply/pltP; exists (mlast q); split=> //.\n- by rewrite msuppX inE.\n- apply/negP=> /msupp_sum_le /flattenP[p3 /mapP[m1]].\n  rewrite mem_filter =>/andP[H1 H2] ->.\n  rewrite !msuppMCX -?mcoeff_msupp // inE => /eqP Eq1.\n  by case/negP: NIm; rewrite -Eq Eq1.\nmove=> m1 Lm1.\nrewrite msuppX inE.\nhave: m1 \\notin msupp p2.\n- apply/negP=> /msupp_sum_le /flatten_mapP[m2].\n  rewrite mem_filter=> /andP[H1 H2].\n  rewrite msuppMCX -?mcoeff_msupp // inE => /eqP Em1.\n  have : (m2 < m1)%O by rewrite (lt_trans H1) // -Eq.\n  by rewrite Em1 ltxx.\nmove/negPf->.\nby move: Lm1; rewrite eq_sym lt_neqAle => /andP[/negPf->].\nQed.\n\nLemma mlast_ind P :\n  P 0 ->\n  (forall q, P (q - q@_(mlast q) *: 'X_[mlast q]) -> P q) ->\n  (forall p, P p).\nProof.\nmove=> HP IH p.\nhave [k sEk] : {k | size (msupp p) = k} by eexists; apply: refl_equal.\nelim: k p sEk => [p Ls| n1 IH1 p ES].\n- suff /eqP->: p == 0 by [].\n  by rewrite -msupp_eq0; case: msupp Ls.\napply/IH/IH1.\nrewrite (perm_size (msupp_rem _ _)) size_rem ?(eqP H) ?ES//.\nby apply/mlast_supp; rewrite -msupp_eq0; case: msupp ES.\nQed.\n\nLemma plt_msuppl (p q r : {mpoly R[n]}) :\n  perm_eq (msupp p) (msupp q) -> (p < r) = (q < r).\nProof.\nmove=> HS; apply/pltP/pltP.\n- case=> m [H1 H2 H3]; exists m; split=>//; first by rewrite -(perm_mem HS).\n  by move=> m1 Lm1; rewrite -(perm_mem HS) H3.\ncase=> m [H1 H2 H3]; exists m; split=>//; first by rewrite (perm_mem HS).\nby move=> m1 Lm1; rewrite (perm_mem HS) H3.\nQed.\n\nLemma plt_msuppr (p q r : {mpoly R[n]}) :\n  perm_eq (msupp p) (msupp q) -> (r < p) = (r < q).\nProof.\nmove=> HS; apply/pltP/pltP.\n- case=> m [H1 H2 H3]; exists m; split=>//; first by rewrite -(perm_mem HS).\n  by move=> m1 Lm1; rewrite -(perm_mem HS) H3.\ncase=> m [H1 H2 H3]; exists m; split=>//; first by rewrite (perm_mem HS).\nby move=> m1 Lm1; rewrite (perm_mem HS) H3.\nQed.\n\nLemma plt_wf : well_founded plt.\nProof.\nmove=> p; apply: Acc_intro.\nmove: p; apply: mlast_ind => [q|q].\n- by rewrite plt0r.\nmove: {1}(mlast q) (eqxx (mlast q))=> a; move: a q.\napply: (well_founded_induction (@ltom_wf n))=> /= m IH q Em H q1.\nmove=> /plt_mlast [[/= p1 [p2 [-> H1 H2]]]|]; last by apply: H.\nhave HA : Acc (fun p q0 : mpoly n R => p < q0) p1.\n- apply: Acc_intro=> q2 Lq2.\n  have: q2 < (q - q@_(mlast q) *: 'X_[(mlast q)]).\n  - rewrite (plt_msuppr _ (_ : perm_eq _ (msupp p1))) //.\n    by rewrite (perm_trans (msupp_rem _ _)) // perm_sym.\n  by apply: H.\nmove: p2 H2; apply: mlast_ind => [_|q2 IH1 Lq2].\n- by rewrite addr0.\nhave [/eqP->|Zq2] := boolP (q2 == 0).\n- by rewrite addr0.\nhave Lp1 : forall m1, m1 \\in msupp p1 -> (mlast q < m1)%O.\n- move=> m1; rewrite (perm_mem H1) (rem_filter _ (msupp_uniq _)) mem_filter.\n  by case/andP=> /= HH /mlast_lemc; rewrite le_eqVlt eq_sym (negPf HH).\nhave Lp2 : forall m1, m1 \\in msupp q2 -> (m1 < mlast q)%O.\n- move=> m1 Lm2.\n  case/pltP : Lq2 => m2 [].\n  rewrite msuppX !inE => /eqP-> Lq HH.\n  have Dm1 : mlast q != m1 by apply: contra Lq => /eqP->.\n  rewrite ltNge le_eqVlt negb_or Dm1.\n  apply/negP=> //.\n  by move=>/HH; rewrite Lm2 inE eq_sym (negPf Dm1).\nhave F0 : mlast q2 \\in msupp q2 by apply: mlast_supp.\nhave F1 : mlast q2 \\notin msupp p1.\n- apply/negP=> HH;\n  suff: (mlast q < mlast q)%O by rewrite ltxx.\n  by apply: lt_trans (Lp1 _ _) (Lp2 _ F0).\nhave F2 : (mlast q2 < m)%O by rewrite (eqP Em) Lp2.\nhave F3 : mlast (p1 + q2) = mlast q2.\n- apply: mlastE=> [|m1 /msuppD_le].\n  - rewrite (perm_mem (msuppD _)) ?mem_cat ?mlast_supp ?orbT //.\n    move=> m1; apply/negP=> /andP[/Lp1 O1 /Lp2 O2].\n    suff: (m1 < m1)%O by rewrite ltxx.\n    by apply: lt_trans O1.\n  rewrite mem_cat=> /orP[/Lp1 O1|/mlast_lemc//].\n  by apply: ltW; apply: lt_trans O1; rewrite -(eqP Em).\nhave F4 : (p1 + q2)@_(mlast q2) = q2@_(mlast q2).\n- have [/eqP->|Zp1] := boolP (p1 == 0); first by rewrite add0r.\n  rewrite mcoeffD mcoeff_lt_mlast ?add0r //.\n  by apply: lt_trans F2 _; rewrite (eqP Em) (Lp1 _ (mlast_supp _)).\napply: Acc_intro => q3.\napply: (IH _ F2)=> [|q4]; first by rewrite F3 eqxx.\nrewrite F3 F4 -addrA.\nsuff: Acc (fun p q0 : mpoly n R => p < q0)\n          (p1 + (q2 - q2@_(mlast q2) *: 'X_[(mlast q2)])).\n- by case=> JJ; apply: JJ.\napply: IH1.\napply/pltP; exists (mlast q); split=>//=.\n- by rewrite msuppX inE eqxx.\n- rewrite (perm_mem (msupp_rem _ _)) mem_rem_uniq ?msupp_uniq // !inE negb_and.\n  by rewrite mcoeff_msupp !negbK  mcoeff_gt_mlead ?eqxx ?orbT //\n             Lp2 // mlead_supp.\nmove=> m1 Lm1.\nrewrite msuppX inE (perm_mem (msupp_rem _ _)) mem_rem_uniq ?msupp_uniq // !inE.\nhave [/Lp2|] := boolP (m1 \\in msupp q2); first by rewrite ltNge ltW.\nby move: Lm1; rewrite andbF lt_neqAle eq_sym => /andP[/negPf->].\nQed.\n\nEnd Order.\n\nSection OrderIDomain.\n\nVariable R : idomainType.\nVariable n : nat.\n\nImplicit Types p q : {mpoly R[n]}.\nImplicit Types m : 'X_{1..n}.\n\nLocal Notation \"p < q\" := (plt p q).\n\nLemma plt_scalerl a p q : a != 0 -> (a *: p < q) = (p < q).\nProof.\nmove=> Za; apply/pltP/pltP=> [] [m [Im NIm H]]; exists m; split=>//.\n- by rewrite -(perm_mem (msuppZ _ Za)).\n- by move=> m1 /H; rewrite (perm_mem (msuppZ _ Za)).\n- by rewrite (perm_mem (msuppZ _ Za)).\nby move=> m1 /H; rewrite (perm_mem (msuppZ _ Za)).\nQed.\n\nLemma plt_scalerr a p q : a != 0 -> (p < a *: q) = (p < q).\nProof.\nmove=> Za; apply/pltP/pltP=> [] [m [Im NIm H]]; exists m; split=>//.\n- by rewrite -(perm_mem (msuppZ _ Za)).\n- by move=> m1 /H; rewrite (perm_mem (msuppZ _ Za)).\n- by rewrite (perm_mem (msuppZ _ Za)).\nby move=> m1 /H; rewrite (perm_mem (msuppZ _ Za)).\nQed.\n\nEnd OrderIDomain.\n\nSection Main.\n\nVariable R : fieldType.\nVariable n : nat.\n\nImplicit Types p q : {mpoly R[n]}.\nImplicit Types m : 'X_{1..n}.\n\nLocal Notation \"p < q\" := (plt p q).\n\nVariable L : seq {mpoly R[n]}.\n\n(******************************************************************************)\n(*          Division of a polynomial by another polynomial                    *)\n(******************************************************************************)\nDefinition mdiv m p q : {mpoly R[n]} :=\n  p - (p@_m/ mleadc q) *: 'X_[m - mlead q] * q.\n\nLemma mdiv_not_supp m p q :\n  q != 0 -> (mlead q <= m)%MM ->\n  m \\notin msupp (mdiv m p q).\nProof.\nmove=> Zq Lq; rewrite mcoeff_msupp negbK mcoeffB -scalerAl mcoeffZ.\nby rewrite -{3}(submK Lq) [_ * q]mulrC mcoeffMX divfK ?mleadc_eq0 // subrr.\nQed.\n\nLemma mdiv_not_supp_id m p q : m \\notin msupp p -> mdiv m p q = p.\nProof.\nby rewrite /mdiv => /memN_msupp_eq0->; rewrite mul0r scale0r mul0r subr0.\nQed.\n\nLemma mdiv_coef_id m p q : q != 0 -> (mlead q <= m)%MM -> (mdiv m p q)@_m = 0.\nProof.\nmove=> Zq Lq.\nrewrite /mdiv -scalerAl mcoeffB mcoeffZ.\nby rewrite -{3}(submK Lq) [_ * q]mulrC mcoeffMX divfK ?mleadc_eq0 // subrr.\nQed.\n\nLemma mdiv_coef_more m p q m1 :\n  (mlead q <= m)%MM -> (m < m1)%O -> (mdiv m p q)@_m1 = p@_m1.\nProof.\nmove=> Lq Lm.\nrewrite /mdiv -scalerAl mcoeffB !mcoeffZ [_ * q]mulrC.\nrewrite [X in _ - _ * X = _]mcoeff_gt_mlead.\n- by rewrite mulr0 subr0.\nhave [/eqP->|ZX] := boolP ('X_[(m - mlead q)] == 0 :> {mpoly R[n]}).\n- by rewrite mulr0 mlead0 (le_lt_trans (le0x _) Lm).\nhave [/eqP->|Zq] := boolP (q == 0).\n- by rewrite mul0r mlead0 (le_lt_trans (le0x _) Lm).\nby rewrite mleadM // mleadXm mpoly.addmC submK.\nQed.\n\nLemma mdiv_scalel a m p q : mdiv m (a *: p) q = a *: mdiv m p q.\nProof.\nby rewrite /mdiv mcoeffZ -mulrA -scalerA -scalerAl -scalerBr.\nQed.\n\nLemma mdivX m1 m p q :  q != 0 -> (mlead q <= m)%MM ->\n  mdiv (m1 + m)%MM ('X_[m1] * p) q = 'X_[m1] * mdiv m p q.\nProof.\nmove=> Zq Lq; rewrite /mdiv.\nby rewrite [_ * p]mulrC mcoeffMX mulrBr [p * _]mulrC\n           -!scalerAl !scalerAr mulrA -mpolyXD addmBA.\nQed.\n\nLemma mdivB m1 m2 p q1 q2 :\n  mdiv m1 p q1 - mdiv m2 p q2 =\n   (p@_m2/ mleadc q2) *: 'X_[m2 - mlead q2] * q2 -\n   (p@_m1/ mleadc q1) *: 'X_[m1 - mlead q1] * q1.\nProof. by rewrite /mdiv addrAC opprD addrA subrr sub0r opprK. Qed.\n\nLemma mdiv_lead m p q :\n  m \\in msupp p -> (mlead q <= m)%MM -> (mlead (mdiv m p q) <= mlead p)%O.\nProof.\nmove=> Im Lq.\napply: le_trans (mleadB_le _ _) _.\nhave [/eqP->|Zlp] := boolP (p@_m / mleadc q == 0).\n  by rewrite scale0r mul0r mlead0 /= joinx0.\nrewrite leEjoin joinAC joinxx joinC -leEjoin.\nrewrite -scalerAl mleadZ //.\napply: le_trans (mleadM_le _ _) _.\nby rewrite mleadXm submK // msupp_le_mlead.\nQed.\n\n(******************************************************************************)\n(*                   Division as a reduction relation                         *)\n(******************************************************************************)\n\nFact red_key : unit. Proof. by []. Qed.\n\nDefinition mreduce_lock p q : bool :=\n  has (fun m =>\n           has (fun r =>\n                   [&& r != 0, (mlead r <= m)%MM & q == mdiv m p r])\n                L)\n      (msupp p).\n\nDefinition mreduce : rel {mpoly R[n]} :=\n  locked_with red_key mreduce_lock.\nCanonical mreduce_unlockable := [unlockable fun mreduce].\n\nNotation \"a ->_1 b \" := (mreduce a b) (at level 52).\n\nLemma mreduceP p q :\n  reflect (exists m r,\n            [/\\ m \\in msupp p, r \\in L, r != 0, (mlead r <= m)%MM &\n                q = mdiv m p r])\n          (p ->_1 q).\nProof.\nrewrite unlock.\napply: (iffP hasP)=> [[m Im /hasP[r Ir /and3P[Zr Lm /eqP->]]]|\n                      [m [r [Im Ir Zr Lm ->]]]].\n- by exists m, r.\nby exists m=>//; apply/hasP; exists r=>//; rewrite Zr Lm /=.\nQed.\n\nLemma mreduce_mdiv m p q :\n  m \\in msupp p -> q \\in L -> q != 0 -> (mlead q <= m)%MM ->\n  p ->_1 mdiv m p q.\nProof.\nby move=> Im Iq Zq Lq; apply/mreduceP; exists m, q=>//; rewrite Zq Lq /=.\nQed.\n\nLemma mreduce_lt p q : p ->_1 q -> q < p.\nProof.\ncase/mreduceP=> m [r [Im Ir Zr Lm ->]].\napply/pltP; exists m; split=> [||m1 Lm1] //.\n- by rewrite mcoeff_msupp negbK mdiv_coef_id.\nby rewrite !mcoeff_msupp mdiv_coef_more.\nQed.\n\nLemma mreduce_lead p q : p ->_1 q -> (mlead q <= mlead p)%O.\nProof. by case/mreduceP=> m [r [Im Ir H1 H2 ->]]; apply: mdiv_lead. Qed.\n\nLemma mreduce_neq0 p q : p ->_1 q -> p != 0.\nProof. by rewrite unlock -msupp_eq0 /=; case: (msupp p). Qed.\n\nLemma mreduce_scale a p q : a != 0 -> p ->_1 q -> a *: p ->_1 a *: q.\nProof.\nmove=> Za /mreduceP[m [r [Im Ir Zr Lr ->]]].\napply/mreduceP; exists m, r; split=>//.\n- by rewrite mcoeff_msupp mcoeffZ mulf_neq0 // -mcoeff_msupp.\nby rewrite mdiv_scalel.\nQed.\n\nLemma mreduceXm m p q : p ->_1 q -> 'X_[m] * p ->_1 'X_[m] * q.\nProof.\ncase/mreduceP=> m1 [r [Im1 Ir Zr Lr ->]].\napply/mreduceP; exists (m + m1)%MM, r; split=>//; last by rewrite mdivX.\n- by rewrite mcoeff_msupp [_ * p]mulrC mcoeffMX -mcoeff_msupp.\nby rewrite (lepm_trans Lr) // lem_addl.\nQed.\n\nLemma mreduce_compatX a m p q :\n  (mlead p < m)%O -> p ->_1 q ->\n  (a *: 'X_[m]) + p ->_1 (a *: 'X_[m]) + q.\nProof.\nmove=> Lp /mreduceP[m1 [r [Im1 Ir Zr Lr ->]]].\nhave Dmm1 : m != m1.\n- move: Im1; rewrite mcoeff_msupp; apply: contra => /eqP<-.\n  by apply/eqP/mcoeff_gt_mlead.\napply/mreduceP; exists m1, r; split=>//.\n- rewrite !mcoeff_msupp mcoeffD mcoeffZ mcoeffX (negPf Dmm1).\n  by rewrite mulr0 add0r -mcoeff_msupp.\nby rewrite /mdiv mcoeffD mcoeffZ mcoeffX (negPf Dmm1) mulr0 add0r !addrA.\nQed.\n\nLemma ideal_reduce p q : p ->_1 q -> (ideal L p <-> ideal L q).\nProof.\ncase/mreduceP=> m [r [Im Ir Zr Lr ->]].\nrewrite /mdiv; split => H.\n- by apply: idealB =>//; apply/idealM/ideal_mem.\nrewrite -[p](subrK ((p@_m / mleadc r) *: 'X_[(m - mlead r)] * r)).\nby apply: idealD =>//; apply/idealM/ideal_mem.\nQed.\n\n(******************************************************************************)\n(*        Realization of divisibilty and irreducibility                       *)\n(******************************************************************************)\n\nDefinition mreducef p : option {mpoly R[n]} :=\n  let L1 := [seq if (mlead r <= m)%MM\n                 then Some (mdiv m p r) else None |\n                 m <- msupp p, r <- [seq x <- L | x != 0]] in\n  nth None L1 (find isSome L1).\n\nDefinition irreducible_lock p : bool := ~~ mreducef p.\nDefinition irreducible : pred {mpoly R[n]} :=\n  locked_with red_key irreducible_lock.\nCanonical irreducible_unlockable := [unlockable fun irreducible].\n\nLemma irreducibleP p : reflect (forall q, ~ p ->_1 q) (irreducible p).\nProof.\nrewrite [irreducible]unlock /mreducef.\nset L1 := [seq _ | _ <- _, _ <- _].\napply: (iffP idP)=> [H1 q /mreduceP[m [r [Im Ir Zr Lr Er]]]|H1].\n- suff /(nth_find None) : has isSome L1 by apply: negP.\n  apply/hasP; exists (Some q)=>//.\n  apply/allpairsP; exists (m,r)=>/=; split=>//.\n  - by rewrite mem_filter Zr.\n  by rewrite Lr Er.\nhave : ~~ has isSome L1.\n- apply/hasPn => /= [[q|] // /allpairsP[[/= m r [Im]]]].\n  rewrite mem_filter; case/andP=>Zr Ir; case: ifP=>// Lr [Er].\n  by case: (H1 q); apply/mreduceP; exists m, r.\nby rewrite has_find -leqNgt => /(nth_default None)->.\nQed.\n\nLemma irreducible0 : irreducible 0.\nProof. by apply/irreducibleP => m /mreduce_lt; rewrite plt0r. Qed.\n\nLemma mreducefE p :\n  if mreducef p is Some q then p ->_1 q else irreducible p.\nProof.\nrewrite [irreducible]unlock /mreducef.\nset L1 := [seq _ | _ <- _, _ <- _].\nhave [H|] := boolP (has isSome L1); last first.\n- by rewrite has_find -leqNgt=> /(nth_default None)->.\ncase E: nth (nth_find None H) => [a|] // _.\nmove: H; rewrite has_find => /(mem_nth None); rewrite E.\nmove/allpairsP=> [/=[m r]/= [Im]].\nrewrite mem_filter; case/andP=>Zr Ir; case: ifP=>// Lr [Er].\nby apply/mreduceP; exists m, r.\nQed.\n\n\n(******************************************************************************)\n(*        Multi-step reduction                                                *)\n(******************************************************************************)\n\nDefinition mr q p f : bool :=\n  (p == q) ||\n   let g y :=\n      (if y < p as b return ((b -> _) -> _)\n       then fun f => f is_true_true\n       else fun f => false) (f y) in\n   has (fun m =>\n           has (fun r =>\n                   [&& r != 0, (mlead r <= m)%MM & g (mdiv m p r)])\n                L)\n       (msupp p).\n\nLemma mr_ext p q f g :\n  (forall r (H : r < p), f r H = g r H) ->\n  mr q f = mr q g.\nProof.\nrewrite /mr => HH; case: (_ == _) => //=.\nelim: L => //= a l IH.\napply: eq_in_has => /= m Om; congr ([&& _, _ & _] || _).\n  by set a1 := mdiv _ _ _; case: (_ < _) (f a1) (g a1) (HH a1).\napply: eq_in_has => // r Hr; congr [&& _, _ & _].\nby set a1 := mdiv _ _ _; case: (_ < _) (f a1) (g a1) (HH a1).\nQed.\n\nDefinition mreduceplus p q : bool := Fix (@plt_wf R n) _ (mr q) p.\n\nNotation \" a ->_+ b \" := (mreduceplus a b) (at level 52).\n\nLemma mreduceplusP p q :\n  reflect (p = q \\/ exists2 r, p ->_1 r & r ->_+ q) (p ->_+ q).\nProof.\nrewrite {2}/mreduceplus Fix_eq //; last by move=> *; apply: mr_ext.\nrewrite {1}/mr.\nhave [/eqP E1|E1] := boolP (_ == _).\n- by apply: (iffP idP) => //=; left.\napply: (iffP hasP) => [/= [m Im]|].\n- case/hasP=>/= r Ir /and3P[Zr Lr].\n  rewrite mreduce_lt => [HH|].\n  - by right; exists (mdiv m p r)=>//; apply/mreduceP; exists m, r.\n  by apply/mreduceP; exists m, r.\ncase => [/eqP| [r /mreduceP[m [r1 [Im Ir1 Zr1 Lr1 ->]]] HH]].\n- by rewrite (negPf E1).\nexists m =>//; apply/hasP; exists r1 =>//=.\nrewrite Zr1 Lr1 mreduce_lt //.\nby apply/mreduceP; exists m, r1.\nQed.\n\nLemma mreduceplus_ref : reflexive mreduceplus.\nProof. by move=> p; apply/mreduceplusP; left. Qed.\n\nLemma mreduceplusW p q : p ->_1 q -> p ->_+ q.\nProof.\nmove=> H; apply/mreduceplusP; right; exists q=>//.\nby apply: mreduceplus_ref.\nQed.\n\nLemma mreduceplus_trans : transitive mreduceplus.\nProof.\nmove=> q p r H1 H2.\nmove: p H1; apply: (well_founded_induction (@plt_wf R n)) =>\n                p IH /mreduceplusP[->//|[r1 H1r1 H2r1]].\napply/mreduceplusP; right; exists r1 =>//.\napply: IH =>//.\nby apply: mreduce_lt.\nQed.\n\nLemma mreduceplus_scale a p q : p ->_+ q -> a *: p ->_+ a *: q.\nProof.\nhave [/eqP->_|Za] := boolP (a == 0).\n- by rewrite !scale0r mreduceplus_ref.\nmove: p q; apply: (well_founded_induction (@plt_wf R n))\n                => p IH q /mreduceplusP[<-|[r1]].\n- by apply: mreduceplus_ref.\nmove=> Ra /IH R1a; apply/mreduceplusP; right; exists (a *: r1).\n- by apply: mreduce_scale.\nby apply: R1a;  apply: mreduce_lt.\nQed.\n\nLemma mreduceplusXm m p q : p ->_+ q -> 'X_[m] * p ->_+ 'X_[m] * q.\nProof.\nmove: p q; apply: (well_founded_induction (@plt_wf R n))\n                 => p IH q /mreduceplusP[<-|[r1]].\n- by apply: mreduceplus_ref.\nmove=> Ra /IH R1a; apply/mreduceplusP; right; exists ('X_[m] * r1) => //.\n- by apply: mreduceXm.\napply: R1a.\nby apply: mreduce_lt.\nQed.\n\nLemma mreduceplus_compatX a m p q :\n  (mlead p < m)%O -> p ->_+ q ->\n  (a *: 'X_[m]) + p ->_+ (a *: 'X_[m]) + q.\nProof.\nmove: p q; apply: (well_founded_induction (@plt_wf R n)) => p IH q Lm.\ncase/mreduceplusP=> [<-|[r Rp Rr]].\n- by apply: mreduceplus_ref.\napply: mreduceplus_trans (IH r _ _ _ _) => //.\n- by apply: mreduceplusW; apply: mreduce_compatX.\n- by apply: mreduce_lt.\nrewrite ltNge.\napply/negP=> HH.\nhave: p < p.\n- apply: plt_trans (mreduce_lt Rp).\n  apply: plt_mlead.\n  by apply: lt_le_trans HH.\nby rewrite plt_anti.\nQed.\n\nLemma mreduceplus_0_mem p r : r \\in L -> p * r ->_+ 0.\nProof.\nmove=> Ir.\nhave [/eqP->|Zr] := boolP (r == 0).\n- by rewrite mulr0 mreduceplus_ref.\nhave Zlr : mleadc r != 0 by rewrite mleadc_eq0.\nmove: p; apply: (well_founded_induction (@plt_wf _ _)) => p IH.\nhave [/eqP->|Zp] := boolP (p == 0).\n- by rewrite mul0r mreduceplus_ref.\npose p1 := p - mleadc p *: 'X_[mlead p].\nhave /mreduceplus_trans -> //: p * r ->_+ p1 * r.\n- apply: mreduceplusW.\n  apply/mreduceP; exists (mlead (p * r)); exists r; split=> //.\n  - by apply: mlead_supp; rewrite mulf_eq0 negb_or Zp.\n  - by rewrite mleadM // lem_addl.\n  rewrite /mdiv /p1 mulrBl mleadM_proper; last first.\n  - by rewrite mulf_neq0 // mleadc_eq0.\n  by rewrite mleadcM mulfK // addmK.\napply/IH/pltP; exists (mlead p); split=>[||m1 Lm1].\n- by apply: mlead_supp.\n- by rewrite mcoeff_msupp mcoeffB mcoeffZ mcoeffX eqxx mulr1 subrr eqxx.\nrewrite !mcoeff_msupp mcoeffB mcoeffZ mcoeffX.\nrewrite mcoeff_gt_mlead //.\nmove: Lm1; rewrite lt_neqAle => /andP[/negPf-> _].\nby rewrite mulr0 subrr eqxx.\nQed.\n\nLemma ideal_reduceplus p q : p ->_+ q -> (ideal L p <-> ideal L q).\nProof.\nmove: p; apply: (well_founded_induction (@plt_wf _ _)) => p1 IH.\nmove/mreduceplusP=> [->//|[q1 H1 H2]].\nhave [H3 H4] := IH _ (mreduce_lt H1) H2.\nsplit=> H5; first by apply/H3/(ideal_reduce H1).\nby apply/(ideal_reduce H1)/H4.\nQed.\n\nLemma ideal_reduceplus_0 p : p ->_+ 0 -> ideal L p.\nProof. by case/ideal_reduceplus => _ /(_ (ideal0 _)). Qed.\n\nLemma reduceB_distr p q r :\n  p - q ->_1 r ->\n  exists p1 q1,\n    [/\\ p ->_+ p1, q ->_+ q1 & r = p1 - q1].\nProof.\ncase/mreduceP=> m [r1 [Im Ir1 Zr1 Lr1 ->]].\nhave Zmr1 : mleadc r1 != 0.\n- by move: Zr1; rewrite mleadc_eq0 /mdiv; case: (_ == _).\nexists (if m \\in msupp p then mdiv m p r1 else p).\nexists (if m \\in msupp q then mdiv m q r1 else q); split.\n- case: (boolP (_ \\in _)) => Imp; last by apply: mreduceplus_ref.\n  by apply/mreduceplusW; apply/mreduceP; exists m, r1.\n- case: (boolP (_ \\in _)) => Imq; last by apply: mreduceplus_ref.\n  by apply/mreduceplusW; apply/mreduceP; exists m, r1.\nmove/msuppB_le: Im; rewrite /mdiv mem_cat mcoeffB.\nhave [H1 _|/memN_msupp_eq0-> //= ->] := boolP (_ \\in _); last first.\n- by rewrite sub0r -!scalerAl mulNr scaleNr opprK opprB -!addrA [-_ + _]addrC.\nhave [H2|/memN_msupp_eq0->] := boolP (_ \\in _); last first.\n- by rewrite subr0 -!addrA [-_ + _]addrC.\nrewrite mulrBl -!scalerAl scalerBl !opprD !opprK.\nrewrite !addrA; congr (_ + _); rewrite -!addrA; congr (_ + _).\nby rewrite addrC.\nQed.\n\nLemma reduceplusB_distr p q :\n  p - q ->_+ 0 -> exists2 r, p ->_+ r & q ->_+ r.\nProof.\nmove: (p - q) {2 4}p {2 4}q (eqxx (p -q)).\napply: (well_founded_induction (@plt_wf _ _)) => r1 IH p1 q1 /eqP HH.\nmove/mreduceplusP => [Zr1|].\n- exists p1; first by apply: mreduceplus_ref.\n  by rewrite -[p1](subrK q1) -HH Zr1 add0r mreduceplus_ref.\nrewrite HH => [[r2 Hr2]].\nhave FF : r2 < r1 by apply: mreduce_lt; rewrite HH.\nmove: Hr2 => /reduceB_distr[p2 [q2 [H1 H2 H3]]] H4.\ncase: (IH r2 _ p2 q2)=> //; first by apply/eqP.\nmove=> r3 H5 H6; exists r3; first by apply: mreduceplus_trans H5.\nby apply: mreduceplus_trans H6.\nQed.\n\nLemma reduceB_compat p q r :\n  p ->_1 q -> exists2 r1, p - r ->_+ r1 & q - r ->_+ r1.\nProof.\ncase/mreduceP=> m [r1 [Im Ir1 Zr1 Lr1 Er1]].\nhave Zmr1 : mleadc r1 != 0.\n- by move: Zr1; rewrite mleadc_eq0 /mdiv; case: (_ == _).\nhave Zqm : q@_m = 0.\n- apply: memN_msupp_eq0.\n  by rewrite Er1; apply: mdiv_not_supp.\nhave [I1m|I1m] := boolP (m \\in msupp (p - r)); last first.\n- have F : p@_m = r@_m.\n  - by move: I1m; rewrite !mcoeff_msupp negbK mcoeffB subr_eq0 => /eqP.\n  exists (p - r); first by apply: mreduceplus_ref.\n  apply/mreduceplusW/mreduceP; exists m, r1; split=> //.\n  - by move: Im; rewrite !mcoeff_msupp mcoeffB Zqm sub0r oppr_eq0 F.\n  rewrite /mdiv mcoeffB Zqm sub0r Er1 /mdiv -F mulNr scaleNr mulNr opprK.\n  by rewrite addrAC subrK.\nexists (mdiv m (p - r) r1).\n  by apply/mreduceplusW/mreduceP; exists m, r1; split.\nhave [I2m|I2m] := boolP (m \\in msupp r); last first.\n- suff->: mdiv m (p - r) r1 = q - r by apply: mreduceplus_ref.\n  rewrite Er1 /mdiv mcoeffB.\n  move: I2m; rewrite mcoeff_msupp negbK => /eqP->.\n  by rewrite subr0 addrAC.\nsuff->: mdiv m (p - r) r1 = mdiv m (q - r) r1.\n- apply/mreduceplusW/mreduceP; exists m, r1; split=> //.\n  by move: I2m; rewrite !mcoeff_msupp mcoeffB Zqm sub0r oppr_eq0.\nrewrite /mdiv !mcoeffB Zqm sub0r Er1 /mdiv [_ - _ - r]addrAC.\nby rewrite mulrBl scalerBl mulrBl mulNr scaleNr mulNr opprD !opprK -!addrA.\nQed.\n\n(******************************************************************************)\n(*       Reduction till irreducibility                                        *)\n(******************************************************************************)\n\n\nDefinition mreducestar p q : bool := (p ->_+ q) && irreducible q.\n\nNotation \" a ->_* b \" := (mreducestar a b) (at level 40).\n\nDefinition mfr p f : {mpoly R[n]} :=\n  if mreducef p is Some q then\n  (if q < p as b return ((b -> _) -> _)\n      then fun f => f is_true_true\n      else fun f => 0) (f q)\n  else p.\n\nLemma mfr_ext p f g :\n  (forall r (H : r < p), f r H = g r H) ->\n  mfr f = mfr g.\nProof.\nrewrite /mfr => HH; case: mreducef => //= a.\nby case: (_ < _) (f a) (g a) (HH a).\nQed.\n\n(* Realisation of reduction till irreducibility *)\nDefinition mreduceplusf p : {mpoly R[n]} :=\n  Fix (@plt_wf _ _) _ mfr p.\n\nLemma mreducestar0W p : p ->_+ 0 -> p ->_* 0.\nProof.\nmove=> H; apply/andP; split=>//.\nby apply: irreducible0.\nQed.\n\nLemma mreducestar0 : 0 ->_* 0.\nProof. by apply/mreducestar0W/mreduceplus_ref. Qed.\n\nLemma mreducestar_trans r p q : p ->_+ r -> r ->_* q -> p ->_* q.\nProof.\nmove=> H1 /andP[H2 H3]; apply/andP; split => //.\nby apply: mreduceplus_trans H2.\nQed.\n\nLemma mreducestarfE p : p ->_* mreduceplusf p.\nProof.\nmove: p; apply: (well_founded_induction (@plt_wf _ _)) => p1 IH.\nrewrite /mreduceplusf Fix_eq /mfr //=.\n- case E: (mreducef p1) (mreducefE p1) => [r|] // Hr; last first.\n  - by rewrite /mreducestar mreduceplus_ref.\n  rewrite mreduce_lt /mreducestar //=.\n  have/andP[H1 /= ->]:= IH r (mreduce_lt Hr).\n  by rewrite (mreduceplus_trans (mreduceplusW Hr)).\nmove=> p f g H.\ncase E: (mreducef p) (mreducefE p) => [r|] //= Hr.\nby move: (f r) (g r) (H r); rewrite mreduce_lt.\nQed.\n\nLemma mreduceplusfE p : p ->_+ mreduceplusf p.\nProof. by case/andP: (mreducestarfE p). Qed.\n\nLemma ideal_reducestar p q : p ->_* q -> (ideal L p <-> ideal L q).\nProof. by case/andP=>/ideal_reduceplus. Qed.\n\nLemma ideal_reducestar_0  p : p ->_* 0 -> ideal L p.\nProof. by case/ideal_reducestar=>_ /(_ (ideal0 _)). Qed.\n\n\n(******************************************************************************)\n(*        Grobner Basis                                                       *)\n(******************************************************************************)\n\nDefinition grobner : Prop := forall p, ideal L p -> p ->_+ 0.\n\n(******************************************************************************)\n(*        Confluence                                                          *)\n(******************************************************************************)\n\nDefinition mconfluent : Prop :=\n  forall p q r, p ->_* q -> p ->_* r -> q = r.\n\nLemma mconfluent_grobner: mconfluent -> grobner.\nProof.\nmove=> HC p [t ->].\nsuff F L1 (t1 : (size L1).-tuple _) :\n  {subset L1 <= L} -> \\sum_(i < size L1) t1`_i * L1`_i ->_+ 0 by apply: F.\nelim: L1 {t}t1 => /= [t _ |r L1 IH t HS].\n- by rewrite big_ord0 mreduceplus_ref.\nrewrite big_ord_recl.\nset q := \\sum_(_ < _) _.\npose q1 := \\sum_(i < size L1) [tuple of behead t]`_i * L1`_i.\nhave F : q = q1.\n- by apply: eq_bigr => /= {q q1}i; case: t => [[]].\nhave F1 : q ->_* 0.\n- apply: mreducestar0W.\n  rewrite F.\n  by apply: IH => m Im; apply: HS; rewrite inE orbC Im.\nset p1 := _ * _.\nhave/reduceplusB_distr[r1 F2 F3]: p1 + q - q ->_+ 0.\n- by rewrite addrK mreduceplus_0_mem //= HS // inE eqxx.\napply: mreduceplus_trans F2 _.\nsuff <-: mreduceplusf r1 = 0 by apply: mreduceplusfE.\napply: HC F1.\napply: mreducestar_trans F3 _.\nby exact: mreducestarfE.\nQed.\n\n(******************************************************************************)\n(*        S-polynomials                                                       *)\n(******************************************************************************)\n\nDefinition spoly p q : {mpoly R[n]} :=\n  if p * q == 0 then 0 else\n    let m := mlcm (mlead p) (mlead q) in\n    mdiv m 'X_[m] p - mdiv m 'X_[m] q.\n\nLemma spolypp p : spoly p p = 0.\nProof. by rewrite /spoly subrr if_same. Qed.\n\nLemma spoly_sym p q : spoly p q = - (spoly q p).\nProof.\nrewrite /spoly [_ * p]mulrC; case: (_ == _); first by rewrite oppr0.\nby rewrite opprB [mlcm _ (mlead p)]mlcmC.\nQed.\n\nLemma ideal_spoly p q : ideal L p -> ideal L q -> ideal L (spoly p q).\nProof.\nmove=> Ip Iq; rewrite /spoly.\ncase: (_ == _); first by exact: ideal0.\nby rewrite mdivB; apply/idealB; apply: idealM.\nQed.\n\nDefinition spoly_red : Prop :=\n  forall p q, p \\in L -> q \\in L -> spoly p q ->_* 0.\n\nLemma spoly_red_conf: spoly_red -> mconfluent.\nProof.\nmove=> HS; apply: (well_founded_induction (@plt_wf _ _)) => p IH q r.\nhave [Ip|/negP Ip] := boolP (irreducible p).\n- case/andP=>\n      /mreduceplusP[<- _ /andP[/mreduceplusP[//|[r1 Rr1 _]]]|[r1 Rr1 _] _ _];\n  by have /irreducibleP/(_ r1)[] := Ip.\nhave Zp : p != 0.\n- by move/negP: Ip; apply: contra =>/eqP->; exact: irreducible0.\ncase/andP=> /mreduceplusP[<-//|[p1 R1p Rp1] Iq].\ncase/andP=> /mreduceplusP[<-//|[p2 R2p Rp2] Ir].\nsuff [p3 R1p1 R1p2]: exists2 p3, p1 ->_* p3 & p2 ->_* p3.\n- have->// := IH _ (mreduce_lt R1p) q p3; last by apply/andP; split.\n  apply: (IH _ (mreduce_lt R2p)) => //.\n  by apply/andP.\ncase/mreduceP : R1p => m1 [r1 [Im1 Ir1 Zr1 Lr1 ->]].\ncase/mreduceP : R2p => m2 [r2 [Im2 Ir2 Zr2 Lr2 ->]].\nwlog: m1 m2 r1 r2 Im1 Zr1 Lr1 Ir1 Im2 Zr2 Lr2 Ir2 / (m2 <= m1)%O => [HW|Lm2].\n- have [Lo|Lo] := boolP (m2 <= m1)%O; first by apply: HW.\n  case: (HW m2 m1 r2 r1 Im2 Zr2 Lr2 Ir2 Im1 Zr1 Lr1 Ir1) =>//.\n  - by rewrite leNgt lt_neqAle negb_and Lo orbT.\n  by move=> p3 H1 H2; exists p3.\nhave [/eqP Em1|Em1] := boolP (m1 == mlead p);\nhave [/eqP Em2|Em2] := boolP (m2 == mlead p).\n- pose m3 := mlcm (mlead r1) (mlead r2).\n  have F : (m3 <= mlead p)%MM.\n  - by rewrite lem_mlcm -{1}Em1 Lr1 -Em2 Lr2.\n  have /andP[/(mreduceplusXm (mlead p - m3))\n             /(mreduceplus_scale (mleadc p))] := (HS _ _ Ir1 Ir2).\n  have<-: mdiv m1 p r1 - mdiv m2 p r2 =\n                      (mleadc p) *: ('X_[mlead p - m3] * spoly r1 r2).\n  - rewrite /spoly !mdivB mulf_eq0 (negPf Zr1) (negPf Zr2) /= -/m3.\n    rewrite !mcoeffX eqxx Em1 Em2 !mul1r.\n    rewrite mulrBr scalerBr -!scalerAl -!scalerAr !scalerA !mulrA -!mpolyXD.\n    by rewrite !addmBA ?submK ?(lem_mlcml _ _) ?(lem_mlcmr _ _).\n  rewrite mulr0 scaler0 => /reduceplusB_distr=> [[p4 R1p1 R1p2]] _.\n  case/andP: (mreducestarfE p4) => Rp4 Ip4.\n  by exists (mreduceplusf p4); apply/andP; split=> //;\n     apply: mreduceplus_trans Rp4.\n- pose t : {mpoly R[n]} := mleadc p *: 'X_[mlead p].\n  pose q1 := p - t.\n  pose q2 := q1 - mdiv m1 p r1.\n  pose q3 := mdiv m2 p r2 - t.\n  have F1 : p ->_1 q1 - q2.\n  - by rewrite /q2 opprB addrC subrK mreduce_mdiv.\n  have F2 : p ->_1 t + q3.\n  - by rewrite /q3 addrC subrK mreduce_mdiv.\n  have F3 : q1 ->_1 q3.\n  - apply/mreduceP; exists m2, r2; split=> //.\n    - rewrite mcoeff_msupp mcoeffB mcoeffZ mcoeffX.\n      by rewrite [_ == m2]eq_sym (negPf Em2) mulr0 subr0 -mcoeff_msupp.\n    rewrite /mdiv mcoeffB mcoeffZ mcoeffX [_ == m2]eq_sym (negPf Em2).\n    by rewrite mulr0 subr0 addrAC.\n  have [q4 F5 F6] : exists2 q4, q1 - q2 ->_+ q4 & q3 - q2 ->_+ q4.\n  - by apply: reduceB_compat.\n  have /andP[F7 F8] := mreducestarfE q4.\n  exists (mreduceplusf q4); apply/andP; split => //.\n  - have->: mdiv m1 p r1 = q1 - q2 by rewrite /q2 opprB addrC subrK.\n    by apply: mreduceplus_trans F7.\n  suff/mreduceplusW/mreduceplus_trans->/=: mdiv m2 p r2 ->_1 q3 - q2.\n  - by [].\n  - by apply: mreduceplus_trans F7.\n  apply/mreduceP; exists m1, r1; split=>//.\n  - rewrite mcoeff_msupp mcoeffB -scalerAl mcoeffZ.\n    rewrite [(_ * _)@_ _]mcoeff_gt_mlead.\n    - by rewrite mulr0 subr0 -mcoeff_msupp.\n    rewrite mleadM //.\n    - rewrite mleadXm submK //.\n      by rewrite lt_neqAle Em1 Em2 -Em1.\n    by rewrite -mleadc_eq0 mleadXm mcoeffX eqxx oner_eq0.\n  rewrite /q3 /q2 /q1 /= /mdiv /t -Em1.\n  rewrite mcoeffB -scalerAl mcoeffZ.\n  - rewrite [(_ * _)@_ _]mcoeff_gt_mlead; last first.\n    rewrite mleadM //.\n    - rewrite mleadXm submK //.\n      by rewrite lt_neqAle Em1 Em2 -Em1.\n    by rewrite -mleadc_eq0 mleadXm mcoeffX eqxx oner_eq0.\n  rewrite mulr0 subr0.\n  rewrite -!addrA; congr (_ + (_ + _)).\n  rewrite opprB !addrA opprB !addrA !opprD opprK !addrA addrK.\n  by rewrite addNr sub0r.\n- case/negP: Em1; rewrite eq_le.\n  by rewrite msupp_le_mlead // -Em2 Lm2.\npose t := mleadc p *: 'X_[mlead p].\npose q1 := p - t.\npose q2 := mdiv m1 p r1 - t.\npose q3 := mdiv m2 p r2 - t.\nhave F1 : q1 ->_1 q2.\n- apply/mreduceP; exists m1, r1; split=>//.\n  - rewrite mcoeff_msupp mcoeffB mcoeffZ mcoeffX [_ == m1]eq_sym (negPf Em1).\n    by rewrite mulr0 subr0 -mcoeff_msupp.\n  rewrite /q2 /q1 /mdiv mcoeffB mcoeffZ mcoeffX [_ == m1]eq_sym (negPf Em1).\n  by rewrite mulr0 subr0 -!addrA [- _ - _]addrC.\nhave F2 : q1 ->_1 q3.\n  apply/mreduceP; exists m2, r2; split=>//.\n  - rewrite mcoeff_msupp mcoeffB mcoeffZ mcoeffX [_ == m2]eq_sym (negPf Em2).\n    by rewrite mulr0 subr0 -mcoeff_msupp.\n  rewrite /q3 /q1 /mdiv mcoeffB mcoeffZ mcoeffX [_ == m2]eq_sym (negPf Em2).\n  by rewrite mulr0 subr0 -!addrA [- _ - _]addrC.\nhave F3 : (q1 < p).\n- apply/pltP; exists (mlead p); split=> [||m3 Lm3]; first by apply: mlead_supp.\n  - by rewrite mcoeff_msupp negbK mcoeffB mcoeffZ mcoeffX eqxx mulr1 subrr eqxx.\n  rewrite !mcoeff_msupp mcoeffB mcoeffZ mcoeffX.\n  move: Lm3; rewrite lt_neqAle => /andP[/negPf-> _].\n  by rewrite mulr0 subr0.\nexists (mreduceplusf (t + mreduceplusf q1)); apply/andP; split.\n- have->: mdiv m1 p r1 = t + q2.\n  - by rewrite /q2 addrCA subrr addr0.\n  apply: mreduceplus_trans (mreduceplusfE _).\n  apply: mreduceplus_compatX => //.\n  - apply: le_lt_trans (mreduce_lead F1) _.\n    by apply: ltm_mleadD => //; apply: mreduce_neq0 F1.\n  have->: mreduceplusf q1 = mreduceplusf q2.\n  - apply: (IH q1) => //.\n    - by apply: mreducestarfE.\n    apply: mreducestar_trans (mreducestarfE _).\n    by apply: mreduceplusW.\n  by apply: mreduceplusfE.\n- by case/andP: (mreducestarfE (t + mreduceplusf q1)).\n- have->: mdiv m2 p r2 = t + q3.\n  - by rewrite /q3 addrCA subrr addr0.\n  apply: mreduceplus_trans (mreduceplusfE _).\n  apply: mreduceplus_compatX => //.\n  - apply: le_lt_trans (mreduce_lead F2) _.\n    by apply: ltm_mleadD => //; apply: mreduce_neq0 F1.\n  have->: mreduceplusf q1 = mreduceplusf q3.\n  - apply: (IH q1) => //.\n      by apply: mreducestarfE.\n    apply: mreducestar_trans (mreducestarfE _).\n    by apply: mreduceplusW.\n  by apply: mreduceplusfE.\nby case/andP: (mreducestarfE (t + mreduceplusf q1)).\nQed.\n\nEnd Main.\n\nLemma mreduce_subset (R: fieldType) n l1 l2 (p q : {mpoly R[n]}) :\n  {subset l1 <= l2} -> mreduce l1 p q -> mreduce l2 p q.\nProof.\nmove=> H /mreduceP[m [r [Im Ir Zr Lm ->]]].\napply/mreduceP; exists m, r; split => //.\nby apply: H.\nQed.\n\nLemma mreduceplus_subset (R: fieldType) n l1 l2 (p q : {mpoly R[n]}) :\n  {subset l1 <= l2} -> mreduceplus l1 p q -> mreduceplus l2 p q.\nProof.\nmove=> H; move: p q; apply: (well_founded_induction (@plt_wf _ _)) => p IH q.\nmove/mreduceplusP => [<-|[r H1 H2]]; first by apply: mreduceplus_ref.\napply: mreduceplus_trans (mreduceplusW _) (IH _ _ _ H2).\n- by apply: mreduce_subset H1.\napply: mreduce_lt H1.\nQed.\n\nLemma mreducestar_subset (R: fieldType) n l1 l2 (p : {mpoly R[n]}) :\n  {subset l1 <= l2} -> mreducestar l1 p 0 -> mreducestar l2 p 0.\nProof.\nmove=> H /andP[/(mreduceplus_subset H) H1 _].\nby apply: mreducestar0W.\nQed.\n\n(******************************************************************************)\n(*        Dickson                                                             *)\n(******************************************************************************)\n\n(* l can be written l1 ++ (a :: l2) ++ (b :: l3)\n   such that R b a *)\nFixpoint has_r A (R : rel A) (l : seq A) : bool :=\n  if l is a :: l1 then has (R^~ a) l1 || has_r R l1\n  else false.\n\nLemma has_r_catr A (R : rel A) l1 l2 :\n  has_r R l2 -> has_r R (l1 ++ l2).\nProof. by elim: l1 => //a l1 IH /IH /= ->; case: has. Qed.\n\nLemma has_r_ins A (R : rel A) l1 l2 l3 :\n  has_r R (l1 ++ l3) ->  has_r R (l1 ++ l2 ++ l3).\nProof.\nelim: l1 => /= [|a l1 IH /orP[|H1]]; first by exact: has_r_catr.\n- by rewrite !has_cat => /orP[] -> //=; rewrite !orbT.\nby rewrite IH // orbT.\nQed.\n\nLemma has_r_map A B (R : rel A) (S : rel B) f l :\n  (forall a b, R a b -> S (f a) (f b)) ->\n  has_r R l -> has_r S (map f l).\nProof.\nmove=> HRS; elim: l => //= a l IH /orP[|/IH->]; last by rewrite orbT.\nby elim: {IH}l => //= => a1 l IH /orP[Raa1|/IH /orP[]->];\n   rewrite ?orbT // HRS.\nQed.\n\nInductive bar A (P : pred (seq A)) (l : seq A) : Prop :=\n  | bar_0: P l -> bar P l\n  | bar_1: (forall a, bar P (a :: l)) -> bar P l.\n\nDefinition bar_r A (R : rel A) := bar (has_r R).\n\nLemma bar_r_catr A (R : rel A) l1 l2 : bar_r R l2 -> bar_r R (l1 ++ l2).\nProof.\nelim: l1 => //= a l1 IH /IH.\nelim => [l H|l H1 _] //.\nby apply: bar_0 => /=; rewrite H orbT.\nQed.\n\nLemma bar_r_ins A (R : rel A) l1 l2 l3 :\n  bar_r R (l1 ++ l3) -> bar_r R (l1 ++ l2 ++ l3).\nProof.\nmove=> H.\nelim : H {-1}l1 l2 {-1}l3 (refl_equal (l1 ++ l3))\n       => {l1 l3}//= [l |l IH] H l1 l2 l3 lE.\n- by apply/bar_0/has_r_ins; rewrite -lE.\napply: bar_1 => a.\nby apply: H (_ : a :: _ = (_ :: _) ++  _); rewrite lE.\nQed.\n\nLemma bar_r_map A B (R: rel A) (S: rel B) f :\n  (forall a b, R a b -> S (f a) (f b)) ->\n  (forall b: B, {a: A | b = f a}) ->\n  forall l, bar_r R l -> bar_r S (map f l).\nProof.\nmove=> HRS f_surj l.\nelim=> {l}/= [l Hh | l _ HBr]; first by apply/bar_0/(has_r_map HRS Hh).\napply: bar_1 => a.\nhave [b ->]:= f_surj a.\nby apply: HBr.\nQed.\n\nFixpoint min A (lt R : rel A) l : Prop :=\n  if l is a :: l then\n      min lt R l /\\ (forall y, lt y a -> bar_r R (y :: l))\n  else True.\n\n(* Open induction *)\nLemma open_ind A (lt R : rel A) l :\n  well_founded lt -> min lt R l ->\n  (forall a, min lt R (a :: l) -> bar_r R (a :: l)) ->\n  bar_r R l.\nProof.\nmove=> wflt Hm IH; apply: bar_1.\nelim/(well_founded_ind wflt)=> x IH1.\nby apply: IH.\nQed.\n\nSection Dickson.\n\nVariables A B : Type.\nVariable lt : rel A.\nVariable R : rel B.\nVariable wfgt: well_founded lt.\nVariable wr_R: bar_r R [::].\n\nLocal Infix \"<\" := lt.\nLocal Notation \"a <= b\" := (~~ (lt b a)).\n\n(* In order to do the proof by induction on the\n   dimension of the tuple, we have to consider\n   the concatenation of two relations (R will be\n   the recursive one) *)\nLemma bar_r_prod_nil :\n  bar_r [rel a b | (a.1 <= b.1) && R a.2 b.2] [::].\nProof.\nset prod := [rel _ _ | _].\nhave: min [rel a b | a.1 < b.1] prod [::] by [].\npose l1 := [seq x.2 | x <- ([::] : seq (A * B))].\nhave H1 : bar_r R l1 by [].\nhave := (refl_equal l1); rewrite {2}/l1.\nelim: {l1}H1 [::] => //= [|l H1 H2 l2 H3 H4].\n- elim => //= a l IH Ho [|b l1] //= [J1 J2] [Hmin Hbar].\n  have /orP[H | H] := Ho.\n  - move: H Hmin; rewrite J1 {J1 a l Ho IH Hbar}J2.\n    elim: l1 b => //= a l IH b /orP[Rav [Hmin Hbar]|Hh [Hmin Hbar]].\n    - case: (boolP (b.1 < a.1)) => [aLb|bLa].\n      - by have := bar_r_ins [::a] (Hbar _ aLb : _ ([::b] ++ l)).\n      by apply: bar_0 => /=; rewrite bLa Rav.\n    by apply: (bar_r_ins [::a] ((IH _ Hh Hmin) : _ _ ([::b] ++ l))).\n  apply: (bar_r_ins [::b] (_ : _ _ ([::] ++ l1))).\n  by apply: IH.\napply: open_ind (wf_inverse_image _ _ _ _ wfgt) H4 _ => a /= H5.\nby apply: (@H2 a.2) => //=; rewrite H3.\nQed.\n\nEnd Dickson.\n\nLemma bar_r_lem_nil n : bar_r (@lem n) [::].\nProof.\nelim: n => [|n IH].\n- apply: bar_1 => a; apply: bar_1 => b; apply: bar_0 =>/=.\n  by rewrite !orbF; apply/forallP =>/= [[]].\npose f (a : nat * 'X_{1..n}) := [multinom of a.1 :: a.2].\npose R1 := [rel a b | ((~~ (b.1 < a.1)) && (lem a.2 b.2))%N].\nrewrite [bar_r _ _]/(bar_r (@lem _)[seq f i | i <- [::]]).\nhave HR1R a b : R1 _ a b -> @lem _ (f a) (f b).\n- case/andP=> aLb /forallP Ht.\n  apply/mnm_lepP=> /= [[[|i] Hi]] /=.\n  - by rewrite /fun_of_multinom /= !(tnth_nth 0%N) /= leqNgt.\n  have := Ht (Ordinal (Hi : (i < n)%N)).\n  by rewrite /fun_of_multinom !(tnth_nth 0%N)  /=.\napply: bar_r_map HR1R _ _ _ => [a|].\n  case: a => t; exists (tnth t ord0, [multinom [tuple of behead t]]).\n  by apply/val_eqP=> /=; apply/eqP/val_eqP; case: t => /= [[]].\nhave Hlt a b : (a < b)%N -> (a < b)%coq_nat by move/ssrnat.ltP.\nby exact: bar_r_prod_nil (Wf_nat.well_founded_lt_compat _ _ _ Hlt) IH.\nQed.\n\n(* lplt lp lq = lp = p :: lq with the leading monomial of p is not divisble by\n                  any of the leading monomials of lq *)\nDefinition smlt n : rel (seq 'X_{1..n}) :=\n  [rel sp sq |\n    let p := head 0%MM sp in (sp == p :: sq) && ~~ has ((@lem n) ^~ p) sq].\n\nLemma wf_smlt n : well_founded (@smlt n).\nProof.\nmove=> l1.\napply: Acc_intro=> l2 /andP[/eqP-> _].\nset x := head _ _.\nrewrite -cat1s.\nhave : ~~ has_r (@lem n) [::x] by [].\nhave : bar_r (@lem n) [::x].\n- rewrite -[[::x]]cats0; apply: bar_r_catr.\n  by apply: bar_r_lem_nil.\nelim => [l H /negP[] // |l Hb IH NH] .\napply: Acc_intro => y /andP[/eqP-> Hb1].\napply: IH; rewrite /= negb_or NH andbT.\nby apply: contra Hb1; rewrite has_cat =>->.\nQed.\n\nDefinition splt n (R : ringType) (lp lq : seq {mpoly R[n]}) : bool :=\n  smlt [seq mlead p | p <- lp & p != 0]\n       [seq mlead q | q <- lq & q != 0].\n\nLemma wf_splt n R : well_founded (@splt n R).\nProof. by apply: wf_inverse_image (@wf_smlt n). Qed.\n\nSection Algo.\n\nVariable R : fieldType.\nVariable n : nat.\n\nImplicit Types p q : {mpoly R[n]}.\nImplicit Types m : 'X_{1..n}.\n\n\n(* Order on pairs of polynomials *)\nDefinition psplt (psp1 psp2 : seq {mpoly R[n]} * seq {mpoly R[n]}) : bool :=\n  (splt psp1.1 psp2.1) ||\n  ((psp1.1 == psp2.1) && (size psp1.2 < size psp2.2)%N).\n\nLemma wf_ltn : well_founded (ltn : nat -> nat -> bool).\nProof.\nelim=> [|n1 [IH]].\n- by apply: Acc_intro=> b; rewrite /= ltn0.\napply: Acc_intro => b H; apply: Acc_intro => c H1.\napply: IH.\nby apply: leq_ltn_trans H1 H.\nQed.\n\nLemma wf_psplt : well_founded psplt.\nProof.\ncase.\napply: (well_founded_induction (@wf_splt _ _))=> lp1 IH1.\napply: (well_founded_induction (wf_inverse_image _ _ _ size wf_ltn)) => lp2 IH2.\napply: Acc_intro=> [] [lp3 lp4]; rewrite /psplt /=.\nhave [H1 _|_ /=] := boolP (splt _ _); first by apply: IH1.\nhave [/eqP-> H1|//] := boolP (_ == _).\nby apply: IH2.\nQed.\n\nDefinition pbuch pr f : seq {mpoly R[n]} :=\n  if pr is (l, p :: r) then\n    let p1 := mreduceplusf l p in\n    if p1 == 0 then\n      let pr1 := (l, r) in\n      (if psplt pr1 pr as b return ((b -> _) -> _)\n       then fun f => f is_true_true\n       else fun f => l) (f pr1)\n    else\n    let pr1 := (p1 :: l, [seq (spoly p1 q) | q <- l] ++ r) in\n    (if psplt pr1 pr as b return ((b -> _) -> _)\n       then fun f => f is_true_true\n       else fun f => l) (f pr1)\n  else pr.1.\n\nDefinition mbuch b c : seq {mpoly R[n]} :=\n  Fix wf_psplt _ pbuch (b, c).\n\nLemma pbuch_ext pr f g :\n  (forall pr1 (H : psplt pr1 pr), f pr1 H = g pr1 H) ->\n  pbuch f = pbuch g.\nProof.\nrewrite /pbuch /=.\nmove: pr f g; case=> l [|p r] f g H //=.\nmove: (f (l, r)) (g (l, r)) (H (l, r)).\nhave->: psplt (l, r) (l, p :: r).\n- by rewrite /psplt /= eqxx orbC /= leqnn.\nmove=> f1 g1 H1.\ncase: (_ == _); first by apply: H1.\nby set u := (_, _); case: psplt (f u) (g u) (H u).\nQed.\n\nLemma mbuchE b c:\n  mbuch b c =\n  if c is p :: c1 then\n    let p1 := mreduceplusf b p in\n    if p1 == 0 then mbuch b c1 else\n    mbuch (p1 :: b) ([seq (spoly p1 q) | q <- b] ++ c1)\n  else b.\nProof.\nrewrite {1}/mbuch Fix_eq /=; last by exact: pbuch_ext.\ncase: c=> // p c.\ncase: (boolP (_ == 0))=> H.\n- by rewrite /psplt /= eqxx ltnS leqnn orbC.\nrewrite (_: psplt _ _) // /psplt /= (_ : splt _ _) //.\nrewrite /splt /smlt /= H eqxx /=.\nset p1 := mreduceplusf _ _.\napply/hasPn => m /mapP[q]; rewrite mem_filter => /andP[Zq Lm] ->.\nhave /andP[_ /irreducibleP/(_ (mdiv (mlead p1) p1 q))/negP]:= mreducestarfE b p.\napply: contra=> H1.\napply: mreduce_mdiv =>//.\nby apply: mlead_supp.\nQed.\n\nLemma mbuch_ind P :\n  (forall b, P b [::] b) ->\n  (forall b p c, let p1 := mreduceplusf b p in\n                 let c1 := [seq (spoly p1 q) | q <- b] ++ c in\n    p1 != 0 -> P (p1 :: b) c1 (mbuch (p1 :: b) c1) ->\n    P b (p :: c) (mbuch b (p :: c))) ->\n  (forall b p c, mreduceplusf b p == 0 ->\n                   P b c (mbuch b c) -> P b (p :: c) (mbuch b (p :: c))) ->\n  forall b c, P b c (mbuch b c).\nProof.\nmove=> IH1 IH2 IH3 b c.\npose p := (b,c); rewrite -[b]/p.1 -[c]/p.2; move: p.\napply: (well_founded_induction_type wf_psplt) => {b c}[] [b [|p c]] /= IH.\n- by rewrite mbuchE.\nhave /= IH' := fun b c => IH (b, c).\nhave [Zp1|Zp1] := boolP (mreduceplusf b p == 0).\n- apply: IH3 => //; apply: IH'.\n  by rewrite /psplt /= orbC eqxx leqnn.\napply: IH2 => //; apply: IH'.\nrewrite /psplt /= // /psplt /= (_ : splt _ _) //.\nrewrite /splt /smlt /= Zp1 eqxx /=.\nset p1 := mreduceplusf _ _.\napply/hasPn => m /mapP[q]; rewrite mem_filter => /andP[Zq Lm] ->.\nhave /andP[_ /irreducibleP/(_ (mdiv (mlead p1) p1 q))/negP]:= mreducestarfE b p.\napply: contra=> H1.\napply: mreduce_mdiv =>//.\nby apply: mlead_supp.\nQed.\n\n(* Two sequences define the same ideal *)\nDefinition same_ideal l1 l2 : Prop :=\n  forall p : {mpoly R[n]}, ideal l1 p <-> ideal l2 p.\n\nLemma same_ideal_id l : same_ideal l l.\nProof. by []. Qed.\n\nLemma same_ideal_sym l1 l2 : same_ideal l1 l2 -> same_ideal l2 l1.\nProof. by move=> H p; split; case: (H p). Qed.\n\nLemma same_ideal_trans l1 l2 l3 :\n  same_ideal l1 l3 -> same_ideal l3 l2 -> same_ideal l1 l2.\nProof.\nmove=> H1 H2 p.\nby (split; case: (H1 p); case: (H2 p) => P1 P2 P3 P4)=> [/P3|/P2].\nQed.\n\nLemma mbuch_grobner (b c : seq {mpoly R[n]}) :\n  (forall p q, p \\in b -> q \\in b ->\n                spoly p q \\notin c -> spoly q p \\notin c\n                          -> mreducestar b (spoly p q) 0) ->\n  (forall p, p \\in c -> ideal b p) ->\n  same_ideal b (mbuch b c) /\\ spoly_red (mbuch b c).\nProof.\napply mbuch_ind=>\n   [{c}b H _|{c}b p c p1 c1 E IH HS HI|b1 p c1 Em IH1 IH2 IH3].\n- by split=> // p q Ip Iq; apply: H.\n- rewrite mbuchE /= (negPf E) /= -/p1 -/c1.\n  case: IH => [p2 q2|p2|HS1 GB].\n  - rewrite !inE => /orP[/eqP->|H1] /orP[/eqP->|H2] H3 H4.\n    - by rewrite spolypp mreducestar0.\n    - by case/negP: H3; rewrite mem_cat map_f.\n    - by case/negP: H4; rewrite mem_cat map_f.\n    have [/eqP->|D1s] := boolP (spoly p2 q2 == p).\n    - apply: mreducestar0W.\n      apply: mreduceplus_trans (_ : mreduceplus _ p1 0).\n      - apply: mreduceplus_subset (mreduceplusfE b p) => m.\n        by rewrite inE orbC => ->.\n      apply/mreduceplusW/mreduceP; exists (mlead p1), p1; split=>//.\n      - by apply/mlead_supp.\n      - by rewrite inE eqxx.\n      - by apply: lepm_refl.\n      rewrite /mdiv -{3}(mpoly.add0m (mlead p1)) addmK mpolyX0 divff.\n      - by rewrite scale1r mul1r subrr.\n      by rewrite mleadc_eq0.\n    have [/eqP Hp|D2s] := boolP (spoly q2 p2 == p).\n    - apply: mreducestar0W.\n      rewrite -[spoly _ _]opprK -oppr0 -scaleN1r -[-0]scaleN1r.\n      apply: mreduceplus_scale.\n      rewrite -spoly_sym Hp.\n      apply: mreduceplus_trans (_ : mreduceplus _ p1 0).\n      - apply: mreduceplus_subset (mreduceplusfE b p) => m.\n        by rewrite inE orbC => ->.\n      apply/mreduceplusW/mreduceP; exists (mlead p1), p1; split=>//.\n      - by apply/mlead_supp.\n      - by rewrite inE eqxx.\n      - by apply: lepm_refl.\n      rewrite /mdiv -{3}(mpoly.add0m (mlead p1)) addmK mpolyX0 divff.\n      - by rewrite scale1r mul1r subrr.\n      by rewrite mleadc_eq0.\n    apply: mreducestar_subset (HS _ _ _ _ _ _)=> [m1||||] //.\n    - by rewrite inE orbC=> ->.\n    - by move: H3; rewrite inE mem_cat !negb_or D1s => /andP[].\n    by move: H4; rewrite inE mem_cat !negb_or D2s => /andP[].\n    - rewrite mem_cat => /orP[/mapP[p3 Ip3 ->]|Hp2].\n      - apply: ideal_spoly; apply: ideal_mem; first by rewrite inE eqxx.\n        by rewrite inE orbC Ip3.\n     by apply/ideal_consr/HI; rewrite inE orbC Hp2.\n  split=> //; apply: same_ideal_trans HS1 => p2; split=> // [H1|H1].\n  - by apply: ideal_consr.\n  apply: ideal_consl H1.\n  case: (ideal_reduceplus (mreduceplusfE b p)) => H1 _.\n  by apply/H1/HI; rewrite inE eqxx.\nrewrite mbuchE /= Em.\napply: IH1=> [p1 q1 Hp1 Hq1 Sp1 Sq1|p1 Ip1].\n- have [/eqP->|D1s] := boolP (spoly p1 q1 == p).\n  - apply: mreducestar0W.\n    rewrite -(eqP Em).\n    by apply: mreduceplusfE.\n  have [/eqP Hp|D2s] := boolP (spoly q1 p1 == p).\n  - apply: mreducestar0W.\n    rewrite -[spoly _ _]opprK -oppr0 -scaleN1r -[-0]scaleN1r.\n    apply: mreduceplus_scale.\n    rewrite -spoly_sym Hp -(eqP Em).\n    by apply: mreduceplusfE.\n  by apply: IH2; rewrite // inE negb_or ?D1s ?D2s.\nby apply: IH3; rewrite inE Ip1 orbT.\nQed.\n\nDefinition mbuch_all l : seq {mpoly R[n]} :=\n  mbuch l [seq spoly i j | i <- l, j <- l].\n\nLemma mbuch_all_grobner l :\n  same_ideal l (mbuch_all l) /\\ spoly_red (mbuch_all l).\nProof.\napply: mbuch_grobner=> [p q Ip Iq /negP[]|p /allpairsP[[p1 q1 [/=Ip1 Iq2 ->]]]].\n- by apply/allpairsP; exists (p,q).\nby apply: ideal_spoly; apply: ideal_mem.\nQed.\n\n(* Test if an element belongs to an ideal *)\nDefinition idealf l p : bool :=\n  mreduceplusf (mbuch_all l) p == 0.\n\n(*  *)\nLemma idealfP p l : reflect (ideal l p) (idealf l p).\nProof.\nhave [HS HB] := mbuch_all_grobner l.\napply: (iffP idP); rewrite /idealf => H.\n- have [_ H1] := HS p; apply: H1.\n  apply: ideal_reducestar_0.\n  by rewrite -(eqP H); exact: mreducestarfE.\napply/eqP.\napply: (spoly_red_conf HB) (mreducestarfE _  _) _.\napply: mreducestar0W.\napply: (mconfluent_grobner ((spoly_red_conf HB))).\nby have [H1 _] := HS p; apply: H1.\nQed.\n\nEnd Algo.\n\nEnd Grobner.\n", "meta": {"author": "thery", "repo": "grobner", "sha": "4c7f517900bdbfd30a63320ae67139e59fa65806", "save_path": "github-repos/coq/thery-grobner", "path": "github-repos/coq/thery-grobner/grobner-4c7f517900bdbfd30a63320ae67139e59fa65806/grobner.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.737158174177441, "lm_q1q2_score": 0.655155807323042}}
{"text": "(* Exercise 34 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\nTheorem exercise_034 : C -> ((~A -> ~C) -> ((A -> ~C) -> B)).\nProof.\nimp_i a1.\nimp_i a2.\nimp_i a3.\nneg_e C.\ndis_e (A \\/ ~A) a4 a4.\nLEM.\nimp_e A.\nhyp a3.\nhyp a4.\nimp_e (~A).\nhyp a2.\nhyp a4.\nhyp a1.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop034.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6550764784433698}}
{"text": "Require Import Utf8.\nRequire Import List.\n\nDefinition monotone (P : nat → Prop) := ∀ n, P (S n) → P n.\n\nModule Type IProp_S.\n\nParameter IProp : Type.\n\nParameter mk_IProp : ∀ P : nat → Prop, monotone P → IProp.\n\nParameter I_valid_at : nat -> IProp -> Prop.\n\nSection I_valid.\nVariable P : nat → Prop.\nVariable H : monotone P.\nVariable n : nat.\n\nParameter I_valid_intro : P n → I_valid_at n (mk_IProp P H).\nParameter I_valid_elim  : I_valid_at n (mk_IProp P H) → P n.\nEnd I_valid.\n\nParameter I_valid_monotone_S : ∀ (P : IProp) (n : nat),\n  I_valid_at (S n) P → I_valid_at n P.\n\nEnd IProp_S.\n\nModule IProp : IProp_S.\n\nDefinition IProp := { P : nat → Prop | monotone P }.\n\nDefinition mk_IProp (P : nat → Prop) (H : monotone P) :=\n  exist _ P H.\n\nDefinition I_valid_at (n : nat) (P : IProp) : Prop :=\n  proj1_sig P n.\n\nSection I_valid.\nVariable P : nat → Prop.\nVariable H : monotone P.\nVariable n : nat.\n\nLemma I_valid_intro : P n → I_valid_at n (mk_IProp P H).\nProof. auto. Qed.\nLemma I_valid_elim  : I_valid_at n (mk_IProp P H) → P n.\nProof. auto. Qed.\nEnd I_valid.\n\nLemma I_valid_monotone_S (P : IProp) (n : nat) :\n  I_valid_at (S n) P → I_valid_at n P.\nProof.\ndestruct P as [ P H ]; apply H.\nQed.\n\nEnd IProp.\n\nInclude IProp.\n\nFixpoint IRel (l : list Type) : Type :=\n  match l with\n  | nil    => IProp\n  | A :: l => A → IRel l\n  end.\n\nDefinition IRel_x {A : Type} (P : A → list Type) : Type :=\n  ∀ x : A, IRel (P x).\n\nDefinition IRel_xx {A B : Type} (P : A → B → list Type) : Type :=\n  ∀ x : A, ∀ y : B, IRel (P x y).\n\nDefinition I_valid (P : IProp) := ∀ n, I_valid_at n P.\n\nNotation \"n ⊨ P\" := (I_valid_at n P) (at level 98, no associativity).\nNotation \"⊨ P\" := (I_valid P) (at level 98, no associativity).\n\nLemma I_valid_monotone (P : IProp) (n m : nat) :\n  n ≤ m → (m ⊨ P) → (n ⊨ P).\nProof.\ninduction 1; trivial.\nintro; apply IHle; apply I_valid_monotone_S; assumption.\nQed.\n\n(* ========================================================================= *)\n(* Embeding Prop *)\n\nDefinition I_Prop (P : Prop) : IProp := mk_IProp (λ _, P) (λ _ H, H).\n\nNotation \"( P )ᵢ\" := (I_Prop P).\n\nLemma I_Prop_intro (P : Prop) n : P → (n ⊨ (P)ᵢ).\nProof.\nintro H; apply I_valid_intro; assumption.\nQed.\n\nLemma I_Prop_elim (P : Prop) n : (n ⊨ (P)ᵢ) → P.\nProof.\nintro H; apply I_valid_elim in H; apply H.\nQed.\n", "meta": {"author": "yizhouzhang", "repo": "ixfree", "sha": "e290bd1ff6d12156ad368e4f9100f1c4e865dab0", "save_path": "github-repos/coq/yizhouzhang-ixfree", "path": "github-repos/coq/yizhouzhang-ixfree/ixfree-e290bd1ff6d12156ad368e4f9100f1c4e865dab0/src/IxFree/Base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.654986534052711}}
{"text": "(* --------------------------------------------------------------------\n * (c) Copyright 2011--2012 Microsoft Corporation and Inria.\n * (c) Copyright 2012--2014 Inria.\n * (c) Copyright 2012--2014 IMDEA Software Institute.\n * -------------------------------------------------------------------- *)\n\n(* -------------------------------------------------------------------- *)\nFrom mathcomp Require Import ssreflect eqtype ssrbool ssrnat ssrfun.\nFrom mathcomp Require Import ssralg choice bigop generic_quotient.\n(* ------- *) Require Import fraction.\n\n(* -------------------------------------------------------------------- *)\nLocal Open Scope ring_scope.\nLocal Open Scope quotient_scope.\n\nImport GRing.\nImport FracField.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* -------------------------------------------------------------------- *)\nLocal Notation simp := Monoid.simpm.\n\nReserved Notation \"x // y\" (at level 50, no associativity).\n\n(* -------------------------------------------------------------------- *)\nNotation \"x %:F\"  := (tofrac x).\nNotation \"x // y\" := (x%:F / y%:F).\n\nLemma addr_cross:\n  forall (R : zmodType) (x1 x2 y1 y2 : R),\n    (x1 - y2 == x2 - y1) = (x1 + y1 == x2 + y2).\nProof.\n  move=> R x1 x2 y1 y2.\n  by rewrite subr_eq addrAC eq_sym subr_eq eq_sym.\nQed.\n\nSection FieldFracProps.\n  Variable K : fieldType.\n\n  Lemma mulf_cross (x1 x2 y1 y2 : K):\n    (x1 * x2) * (y1 * y2) = (x1 * y1) * (x2 * y2).\n  Proof.\n    by rewrite -!mulrA; congr (_ * _); rewrite mulrCA.\n  Qed.\n\n  Lemma mulfE (x1 x2 y1 y2 : K) :\n    (x1 / y1) * (x2 / y2) = (x1 * x2) / (y1 * y2).\n  Proof.\n    by rewrite invfM !mulrA [x1 / y1 * x2]mulrAC.\n  Qed.\n\n  Lemma invfE (x y : K) : (x / y)^-1 = y / x.\n  Proof. by rewrite invfM invrK mulrC. Qed.\n\n  Lemma divf_exp (x y : K) n : (x / y) ^+ n = (x ^+ n / y ^+ n).\n  Proof. by rewrite exprMn exprVn. Qed.\n\n  Lemma divf_mull (x y z : K) :\n    z != 0 -> (z * x) / (z * y) = x / y.\n  Proof.\n    move=> nz_z; rewrite invfM mulrAC !mulrA.\n    by rewrite divff // !simp mulrC.\n  Qed.\n\n  Lemma divf_mulr (x y z : K) :\n    z != 0 -> (x * z) / (y * z) = x / y.\n  Proof.\n    by move=> nz_z; rewrite ![_ * z]mulrC divf_mull.\n  Qed.\n\n  Lemma divff_eq (n1 n2 d1 d2 : K) :\n    d1 * d2 != 0 -> (n1 / d1 == n2 / d2) = (n1 * d2 == n2 * d1).\n  Proof.\n    rewrite mulf_eq0; case/norP => nz_d1 nz_d2.\n    rewrite -subr_eq0 -mulNr addf_div // mulNr.\n    rewrite mulf_eq0 invr_eq0 [d1*d2 == 0]mulf_eq0.\n    by rewrite (negbTE nz_d1) (negbTE nz_d2) !orbF subr_eq0.\n  Qed.\n\n  Lemma divf_neq0 : forall (K : fieldType) (x y : K),\n    (x / y != 0) = (x != 0) && (y != 0).\n  Proof.\n    by move=> K' x y; rewrite mulf_eq0 invr_eq0 negb_or.\n  Qed.\nEnd FieldFracProps.\n\n(* -------------------------------------------------------------------- *)\nModule FracField.\n  Section Props.\n    Variable R : idomainType.\n\n    Import fraction.FracField.\n\n    Lemma embed_Ratio (n d : R):\n      n // d = \\pi_{fraction R} (Ratio n d).\n    Proof.\n      case: RatioP=> [_|nz_d].\n      + rewrite invr0 mulr0 /GRing.zero /=; unlock tofrac.\n        by apply/eqP; rewrite -numer0 numden_Ratio // oner_eq0.\n      unlock tofrac; rewrite /GRing.inv /GRing.mul /= -pi_inv -pi_mul.\n      rewrite /invf /mulf /= !numden_Ratio ?oner_neq0 //.\n      by rewrite !simp /Ratio /insubd insubT.\n    Qed.\n\n    Definition piE := (@equal_toE, embed_Ratio).\n\n    Lemma Ratio0r: forall x, Ratio 0 x = ratio0 R %[mod {fraction R}].\n    Proof.\n      move=> x; case: RatioP=> [|nz_x] //=.\n      by apply/eqmodP; rewrite /= equivfE /= !simp.\n    Qed.\n\n    Lemma fracW:\n      forall (P : {fraction R} -> Type),\n           (forall (n d : R), d != 0 -> P (n // d))\n        -> forall f : {fraction R}, P f.\n    Proof.\n      move=> P H; elim/quotW=> [[[n d] /= nz_d]].\n      move: (H n d nz_d); rewrite piE /=.\n      by unlock Ratio; rewrite /insubd insubT.\n    Qed.\n\n    Lemma frac_eq:\n      forall (x1 x2 y1 y2 : R), y1 * y2 != 0 ->\n        ((x1 // y1) == (x2 // y2)) = (x1 * y2 == x2 * y1).\n    Proof.\n      move=> x1 x2 y1 y2 nz_y; rewrite divff_eq.\n      + by rewrite -!rmorphM /= tofrac_eq.\n      + by rewrite -!rmorphM /= tofrac_eq0.\n    Qed.\n\n    Lemma frac_eq0 (n d : R): (n // d == 0) = (n == 0) || (d == 0).\n    Proof. by rewrite mulf_eq0 invr_eq0 !tofrac_eq0. Qed.\n\n    Lemma frac_mull (p q r : R): r != 0 -> (r * p) // (r * q) = p // q.\n    Proof.\n      by move=> nz_r; rewrite !tofracM divf_mull ?tofrac_eq0.\n    Qed.\n  End Props.\nEnd FracField.\n\nImport FracField.\n\n(* -------------------------------------------------------------------- *)\nModule InjRMorphism.\n  Section ClassDef.\n    Variable R S : ringType.\n\n    Definition mixin_of (f : R -> S) := injective f.\n\n    Record class_of f : Prop := Class {\n      base  : rmorphism f;\n      mixin : mixin_of f\n    }.\n\n    Local Coercion base : class_of >-> rmorphism.\n\n    Structure map (phRS : phant (R -> S)) := Pack {apply; _ : class_of apply}.\n    Local Coercion apply : map >-> Funclass.\n\n    Variables (phRS : phant (R -> S)) (f g : R -> S) (cF : map phRS).\n\n    Definition class := let: Pack _ c as cF' := cF return class_of cF' in c.\n\n    Definition clone fM of phant_id g (apply cF) & phant_id fM class :=\n      @Pack phRS f fM.\n\n    Definition pack (fI : mixin_of f) :=\n      fun (bF : RMorphism.map phRS) fM & phant_id (RMorphism.class bF) fM =>\n        Pack phRS (Class fM fI).\n\n    Canonical rmorphism := RMorphism.Pack phRS class.\n  End ClassDef.\n\n  Module Exports.\n    Notation injrmorphism f := (class_of f).\n\n    Coercion base  : injrmorphism >-> RMorphism.class_of.\n    Coercion mixin : injrmorphism >-> mixin_of.\n    Coercion apply : map >-> Funclass.\n\n    Notation InjRMorphism fI := (Pack (Phant _) fI).\n    Notation AddInjRMorphism fI := (pack fI id).\n\n    Notation \"{ 'rimorphism' fR }\" := (map (Phant fR))\n      (at level 0, format \"{ 'rimorphism'  fR }\") : ring_scope.\n\n    Coercion rmorphism : map >-> RMorphism.map.\n    Canonical rmorphism.\n  End Exports.\nEnd InjRMorphism.\n\nExport InjRMorphism.Exports.\n\nSection InjRMorphismTheory.\n  Variable R S : ringType.\n  Variable f   : {rimorphism R -> S}.\n\n  Lemma rimorph_inj: injective f.\n  Proof. by case: f=> fa []. Qed.\n\n  Lemma rimorph_eq0 (x : R): (f x == 0) = (x == 0).\n  Proof.\n    apply/eqP/eqP; last by move=> ->; rewrite rmorph0.\n    by rewrite -{1}[0](rmorph0 f); move/rimorph_inj.\n  Qed.\nEnd InjRMorphismTheory.\n\n(* -------------------------------------------------------------------- *)\nSection RatioLiftDef.\n  Variable R S : idomainType.\n  Variable f : R -> S.\n\n  Definition rliftf (r : {ratio R}) : {ratio S} :=\n    Ratio (f \\n_r) (f \\d_r).\n\n  Definition rlift :=\n    lift_op11 {fraction R} {fraction S} rliftf.\nEnd RatioLiftDef.\n\n(* -------------------------------------------------------------------- *)\nSection RatioLiftMorph.\n  Variable R S : idomainType.\n  Variable f : R -> S.\n\n  Hypothesis fM : multiplicative f.\n  Hypothesis f_eq0 : forall x, (f x == 0) = (x == 0).\n\n  Local Notation rliftf := (rliftf f).\n  Local Notation rlift  := (rlift  f).\n\n  Lemma pi_M_rlift:\n    forall x, \\pi_{fraction S} (rliftf x) = rlift (\\pi_{fraction R} x).\n  Proof.\n    move=> x2; unlock rlift; set x1 := (repr _).\n    have: (x1 = x2 %[mod {fraction _}]) by rewrite reprK.\n    case: x2 x1 => [[n2 d2] /= nz_d2] [[n1 d1] /= nz_d1] /=.\n    move/eqmodP => /=; rewrite equivfE /= => /eqP eqE.\n    rewrite /rliftf /=; apply/eqmodP=> /=; rewrite equivfE.\n    by rewrite !numden_Ratio ?f_eq0 // -!fM mulrC -eqE mulrC.\n  Qed.\n\n  Canonical pi_M_rlift_morph := PiMorph11 pi_M_rlift.\n\n  Lemma M_rliftF (r : R): rlift (r%:F) = (f r)%:F.\n  Proof.\n    by rewrite !piE /rliftf /= !numden_Ratio ?oner_neq0 ?fM.\n  Qed.\n\n  Lemma M_rliftE (n d : R): rlift (n // d) = (f n) // (f d).\n  Proof.\n    have f0: f 0 = 0 by (apply/eqP; rewrite f_eq0 eqxx).\n    rewrite !piE /rliftf /=; case: (RatioP n d).\n    + by move=> z_d; rewrite !(f0, Ratio0) Ratio0r.\n    + by move=> nz_d; rewrite !numden_Ratio.\n  Qed.\n\n  Lemma M_rlift_is_multiplicative: multiplicative rlift.\n  Proof.\n    split; last by rewrite -tofrac1 M_rliftF fM.\n    elim/fracW=> n1 d1 nz_d1; elim/fracW=> n2 d2 nz_d2.\n    by rewrite !M_rliftE !mulf_div -!tofracM -!fM M_rliftE.\n  Qed.\nEnd RatioLiftMorph.\n\n(* -------------------------------------------------------------------- *)\nSection RatioLiftTheory.\n  Variable R S : idomainType.\n  Variable f : {rimorphism R -> S}.\n\n  Local Notation rliftf := (rliftf f).\n  Local Notation rlift  := (rlift  f).\n\n  Lemma pi_rlift:\n    forall x,\n      \\pi_{fraction S} (rliftf x) = rlift (\\pi_{fraction R} x).\n  Proof. by apply: pi_M_rlift; [apply: rmorphismMP | apply: rimorph_eq0]. Qed.\n\n  Canonical pi_rlift_morph := PiMorph11 pi_rlift.\n\n  Lemma rliftF (r : R): rlift (r%:F) = (f r)%:F.\n  Proof. by apply: M_rliftF; [apply: rmorphismMP | apply: rimorph_eq0]. Qed.\n\n  Lemma rliftE (n d : R): rlift (n // d) = (f n) // (f d).\n  Proof. by apply: M_rliftE; [apply: rmorphismMP | apply: rimorph_eq0]. Qed.\n\n  Lemma rlift_is_additive: additive rlift.\n  Proof.\n    elim/fracW=> n1 d1 nz_d1; elim/fracW=> n2 d2 nz_d2.\n    rewrite !rliftE -!mulNr !addf_div ?tofrac_eq0 ?rimorph_eq0 //.\n    by rewrite -!(rmorphM, rmorphD, rmorphN) /= !mulNr rliftE.\n  Qed.\n  Canonical rlift_additive := Additive rlift_is_additive.\n\n  Lemma rlift_is_multiplicative: multiplicative rlift.\n  Proof.\n    by apply: M_rlift_is_multiplicative;\n      [apply: rmorphismMP | apply: rimorph_eq0].\n  Qed.\n  Canonical rlift_rmorphism := AddRMorphism rlift_is_multiplicative.\n\n  Lemma rlift0     : 0%:F = 0 :> {fraction R}.    Proof. exact: rmorph0. Qed.\n  Lemma rliftN     : {morph rlift: x / - x}.      Proof. exact: rmorphN. Qed.\n  Lemma rliftD     : {morph rlift: x y / x + y}.  Proof. exact: rmorphD. Qed.\n  Lemma rliftB     : {morph rlift: x y / x - y}.  Proof. exact: rmorphB. Qed.\n  Lemma rliftMn  n : {morph rlift: x / x *+ n}.   Proof. exact: rmorphMn. Qed.\n  Lemma rliftMNn n : {morph rlift: x / x *- n}.   Proof. exact: rmorphMNn. Qed.\n  Lemma rlift1     : 1%:F = 1 :> {fraction R}.    Proof. exact: rmorph1. Qed.\n  Lemma rliftM     : {morph rlift: x y  / x * y}. Proof. exact: rmorphM. Qed.\n  Lemma rliftX   n : {morph rlift: x / x ^+ n}.   Proof. exact: rmorphX. Qed.\nEnd RatioLiftTheory.\n\n(* -------------------------------------------------------------------- *)\nSection FracOfField.\n  Variable K : fieldType.\n\n  Lemma tofracrV (R : idomainType):\n    {in GRing.unit, {morph (@tofrac R) : x / x^-1 >-> x^-1}}.\n  Proof.\n    move=> x unit_x /=; have nz_x: x != 0.\n      by apply/eqP=> z_x; rewrite z_x unitr0 in unit_x.\n    rewrite !piE -[X in _ = X]pi_inv /invf.\n    rewrite !numden_Ratio ?oner_eq0 //; apply/eqmodP => /=.\n    by rewrite equivfE !numden_Ratio ?oner_eq0 // mulVr // mulr1.\n  Qed.\n\n  Lemma tofracfV: {morph (@tofrac K) : x / x^-1 >-> x^-1}.\n  Proof.\n    move=> x /=; have [->|nz_x] := altP (x =P 0).\n      by rewrite !invr0 tofrac0.\n    by rewrite tofracrV // unitfE.\n  Qed.\nEnd FracOfField.\n", "meta": {"author": "strub", "repo": "elliptic-curves-ssr", "sha": "e736f1581d81c902bf56c7320e65ae28725a3cfd", "save_path": "github-repos/coq/strub-elliptic-curves-ssr", "path": "github-repos/coq/strub-elliptic-curves-ssr/elliptic-curves-ssr-e736f1581d81c902bf56c7320e65ae28725a3cfd/src/fracfield.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6549865328865583}}
{"text": "  (***************************************************************)\n  (*   This file is part of the static analyses developement -   *)\n  (*   specification of kildall's algorithm, and proof it is a   *)\n  (*   bytecode verifier -                                       *)\n  (*\t\t\t\t\t\t\t         *)\n  (*   File : tree.v\t\t\t\t\t         *)\n  (*   Authors : S. Coupet-Grimal, W. Delobel \t\t         *)\n  (*   Content : definition of type tree and facts about trees   *)\n  (*             and forests\t\t\t\t         *) \n  (***************************************************************)\n\n\nSection tree.\n\n  Require Export aux_arith.\n  Require Export relations.\n  Require Export Max.\n  Require Import List.\n\n  (* sets of node and leaves labels : *)\n  Variables N L : Set.\n  (* decidable equality on N and L are needed to have decidable equality on trees *)\n  Hypothesis eq_N_dec : forall (n n' : N), {n=n'} + {n<>n'}.\n  Hypothesis eq_L_dec : forall (l l' : L), {l=l'} + {l<>l'}.\n\n  Unset Elimination Schemes.\n\n  Inductive tree : Set :=\n    | Leaf : L -> tree\n    | Node : N -> (list tree) -> tree.\n\n  Set Elimination Schemes.\n\n  Notation forest := (list tree).\n \n  (* computes the number of nodes in the tree : *)\n  Fixpoint tree_size (t : tree) : nat := \n    match t with \n      | Leaf _ => 0\n      | Node _ l => S (fold_left (fun (s : nat) (t : tree) => s + (tree_size t)) l 0)\n    end.\n\n  (* proving a (useful) induction principle on trees : *)\n  Lemma fold_dom : forall (l : forest) (a : nat),  \n    a <= fold_left (fun (s : nat) (t : tree) => s + (tree_size t)) l a.\n  Proof.\n    induction l as [ | hl tl IHl]; simpl.\n          (* case l empty  *)\n    auto with arith.\n          (* case l = hl::tl *)\n    intro a; generalize (IHl (a + tree_size hl)); clear IHl; intro IHl.\n    apply le_trans with (a + tree_size hl); trivial.\n    auto with arith.\n  Qed.\n\n        (* fold monotone wrt initial value : *)\n  Lemma fold_inc : forall (l : forest) (a b : nat), a <= b -> \n    fold_left (fun (s : nat) (t : tree) => s + (tree_size t)) l a <= \n    fold_left (fun (s : nat) (t : tree) => s + (tree_size t)) l b.\n  Proof.\n    induction l as [ | hl tl IHl]; simpl.\n          (* case l empty : *)\n    trivial.\n          (* case l = hl :: tl : *)\n    intros a b a_le_b.\n    apply IHl.\n    generalize a_le_b; auto with arith.\n  Qed.\n\n      (* immediate strict subtree size is less than tree size : *)\n  Lemma immediate_subtree_size : forall (n : N) (l : forest) (t : tree), \n    In t l -> tree_size t < tree_size (Node n l).\n  Proof.\n    intros n l; induction l as [ | hl tl IHl].\n          (* case l empty : *)\n    intros t Hin; inversion Hin.\n          (* case l = hl :: tl *)\n    intros t Hin; elim Hin; clear Hin; intro Hin.\n            (* case hl = t *)\n    subst hl; simpl.\n    apply le_lt_n_Sm.\n    apply fold_dom.\n            (* case t in tl : *)\n    apply lt_le_trans with (tree_size (Node n tl)).\n    apply IHl; trivial.\n    simpl.\n    apply le_n_S.\n    apply fold_inc.\n    destruct (tree_size hl); auto with arith.\n  Qed.\n\n  Require Import Wf_nat. (* => lt_wf_ind *)\n\n  Lemma tree_ind_aux : forall (P : tree -> Prop),    \n    (forall (leaf : L), P (Leaf leaf)) ->\n    (forall (node : N) (l : forest), (forall (t : tree), In t l -> P t) -> P (Node node l)) ->\n    forall (n : nat) (t : tree), tree_size t = n ->  P t.\n  Proof.\n    intros P Hleaf Hnode n. \n    apply (lt_wf_ind n (fun (k : nat) => forall (t : tree), tree_size t = k -> P t)).\n    clear n; intros n IHn t Hsize.\n    destruct t as [leaf | node l]; [apply Hleaf | idtac].\n    apply Hnode.\n    intros t t_in_l.\n    apply (IHn (tree_size t)).\n    rewrite <- Hsize.\n    apply immediate_subtree_size; assumption.\n    trivial.\n  Qed.\n\n  Lemma tree_rec_aux : forall (P : tree -> Set),    \n    (forall (leaf : L), P (Leaf leaf)) ->\n    (forall (node : N) (l : forest), (forall (t : tree), In t l -> P t) -> P (Node node l)) ->\n    forall (n : nat) (t : tree), tree_size t = n ->  P t.\n  Proof.\n    intros P Hleaf Hnode n. \n    apply (lt_wf_rec n (fun (k : nat) => forall (t : tree), tree_size t = k -> P t)).\n    clear n; intros n IHn t Hsize.\n    destruct t as [leaf | node l]; [apply Hleaf | idtac].\n    apply Hnode.\n    intros t t_in_l.\n    apply (IHn (tree_size t)).\n    rewrite <- Hsize.\n    apply immediate_subtree_size; assumption.\n    trivial.\n  Qed.\n  \n  (* induction principles for tree : *)\n  Lemma tree_ind : forall (P : tree -> Prop),    \n    (forall (leaf : L), P (Leaf leaf)) ->\n    (forall (node : N) (l : forest), (forall (t : tree), In t l -> P t) -> P (Node node l)) ->\n    forall (t : tree), P t.\n  Proof.\n    intros P Pleaf Pnode t.\n    apply (tree_ind_aux P Pleaf Pnode (tree_size t) t); trivial.\n  Qed.\n\n  Lemma tree_rec : forall (P : tree -> Set),    \n    (forall (leaf : L), P (Leaf leaf)) ->\n    (forall (node : N) (l : forest), (forall (t : tree), In t l -> P t) -> P (Node node l)) ->\n    forall (t : tree), P t.\n  Proof.\n    intros P Pleaf Pnode t.\n    apply (tree_rec_aux P Pleaf Pnode (tree_size t) t); trivial.\n  Qed.\n  \n\n  Lemma eq_tree_dec : forall (t t' : tree), {t = t'} + {t <> t'}.\n  Proof.\n    induction t as [l | n l IHt] using tree_rec.\n      (* case t leaf : *)\n    destruct t' as [l' | n' l'].\n    elim (eq_L_dec l l'); intro case_l_l'; [left | right].\n    subst; trivial.\n    intro H; apply case_l_l'; inversion H; trivial.\n    right; intro H; inversion H.\n      (* case t = Node n l : *)\n    intro t'; destruct t' as [l' | n' l'].\n    right; intro H; inversion H.\n    elim (eq_N_dec n n'); intro case_n_n'.\n       (* case n = n' : *)\n    subst n'; assert (H : {l = l'} + {l <> l'}).\n    generalize l'; clear l'.\n    induction l as [ | hl tl]; intro l'; destruct l' as [ | hl' tl']. \n    left; trivial.\n    right; intro H; inversion H.\n    right; intro H; inversion H.\n    cut (In hl (hl :: tl)); [intro Hhl | left; trivial].\n    assert (H : forall t : tree, In t tl -> forall t' : tree, {t = t'} + {t <> t'}).\n    intros t t_in_tl; apply IHt.\n    right; assumption.\n    generalize (IHtl H); clear IHtl; intro IHtl.\n    elim (IHt hl Hhl hl'); intro case_hl_hl'.\n    subst; elim (IHtl tl'); intro case_tl_tl'.\n    subst; left; trivial.\n    right; injection; intros; apply case_tl_tl'; trivial.\n    right; injection; intros; apply case_hl_hl'; trivial.\n    elim H; clear H; intro H; [left | right].\n    subst; trivial.\n    intro H'; inversion H'; apply H; trivial.\n        (* case n <> n' : *)\n    right; intro H; inversion H; apply case_n_n'; trivial.\n  Qed.\n \n  (* subtree relation : *)\n  Inductive subtree : relation tree := \n    | subtree_refl : forall (t : tree), subtree t t\n    | subtree_cons : forall (n : N) (l : forest) (t t' : tree), \n        subtree t t' -> subtree t (Node n (t' :: l)).\n\n  (* results about subtree : *)\n  Lemma subtree_size : forall (t t' : tree), \n    subtree t t' -> tree_size t <= tree_size t'.\n  Proof.\n    intros t t' stt'.\n    apply (subtree_ind (fun (t t' : tree) => tree_size t <= tree_size t')); trivial.\n    clear stt' t t'; intros n f t t' stt' Hs; simpl.\n    apply le_trans with (m:=tree_size t'); try assumption.\n    apply le_trans with (fold_left (fun (s : nat) (t0 : tree) => s + tree_size t0) f\n      (tree_size t')); auto with arith.\n    apply fold_dom.\n  Qed.\n\n\n  (* strict subtree : *)\n  Inductive strict_subtree : relation tree := \n    strict_subtree_cons : forall (n : N) (l : forest) (t t' : tree), \n      subtree t t' -> strict_subtree t (Node n (t' :: l)).\n  \n\n  Lemma strict_subtree_size : forall (t t' : tree), \n    strict_subtree t t' -> tree_size t < tree_size t'.\n  Proof.\n    intros t t' stt'.\n    apply (strict_subtree_ind (fun (t t' : tree) => tree_size t < tree_size t')); trivial.\n    simpl; clear stt' t t'; intros n f t t' stt'.\n    apply le_lt_trans with (m:=tree_size t').\n    apply subtree_size; assumption. \n    apply lt_le_trans with (m:=S (tree_size t')); auto with arith.\n    apply le_n_S; apply fold_dom.\n  Qed.\n\n  Lemma strict_subtree_is_subtree_neq : forall (t t' : tree), \n    strict_subtree t t' <-> subtree t t' /\\ t <> t'.\n  Proof.\n    intros t t'; split.\n      (* => : *)\n    intro stt'; inversion stt' as [n l t0 t'0 H]; subst.\n    split.\n    constructor; assumption.\n    cut (strict_subtree t (Node n (t'0 :: l))); [intro Hsub | constructor; assumption]. \n    generalize (strict_subtree_size t (Node n (t'0 :: l)) Hsub); intros Hsize Heq.\n    rewrite <- Heq in Hsize; generalize Hsize; apply lt_irrefl.\n      (* <= : *)\n    intro H; elim H; clear H; intro stt'.\n    apply (subtree_ind (fun (t t' : tree) => t <> t' -> strict_subtree t t')).\n    clear stt' t t'; intros t H; elim H; trivial.\n    clear stt' t t'; intros n f t t' stt' H1 H2. \n    constructor; assumption.\n    assumption.\n  Qed.\n  \n\n  (* a tree cannot contain itself : *)\n  Lemma no_loop_tree : forall (t : tree) (n : N) (f : forest), \n    t <> Node n (t :: f).\n  Proof.\n    intros t n f; cut (strict_subtree t (Node n (t :: f))). \n    intro H; generalize (strict_subtree_size t (Node n (t :: f)) H); clear H; intros H H'.\n    rewrite <- H' in H; generalize H; apply lt_irrefl.\n    constructor; constructor.\n  Qed.\n\n  (* a forest cannot contain itself : *)\n  Lemma no_loop_forest : forall (t : tree) (f : forest), \n    f <> t :: f.\n  Proof.\n    intros t f H.\n    assert (H' : length (t :: f) = length f).\n    rewrite <- H; trivial.\n    simpl in H'.\n    apply neq_n_Sn with (length f); trivial.\n  Qed.\n\n  (* subtree is an order on trees : *)\n  Lemma order_subtree : order tree subtree.\n  Proof.\n    split.\n    (* reflexive : *)\n    intro t; constructor.\n    (* transitive : *)\n    intros x y z sxy syz.\n    apply (subtree_ind (fun (t t' : tree) => forall (y : tree), subtree y t-> subtree y t')) with y; try assumption.\n    intros; assumption.\n    clear sxy syz x y z.\n    intros n f z y Hzy H1 x H2.\n    constructor.\n    apply H1; assumption.\n    (* antisymmetric : *)\n    intros x y Hxy Hyx.\n    elim (eq_tree_dec x y); intro case; trivial.\n    elim (lt_irrefl (tree_size x)).\n    assert (H : strict_subtree x y). \n    elim (strict_subtree_is_subtree_neq x y); intros H H'; apply H'; split; assumption. \n    cut (tree_size x < tree_size y); [intro Hsxy | apply strict_subtree_size; assumption].\n    cut (tree_size y <= tree_size x); [intro Hsyx | apply subtree_size; assumption].\n    apply lt_le_trans with (tree_size y); assumption.\n  Qed.\n\n\nEnd tree.\n\nImplicit Arguments Node [N L].\nImplicit Arguments Leaf [N L].\n\n\n", "meta": {"author": "coq-contribs", "repo": "kildall", "sha": "87422e1815e22a3f4821b29a1fd7a7f385667b91", "save_path": "github-repos/coq/coq-contribs-kildall", "path": "github-repos/coq/coq-contribs-kildall/kildall-87422e1815e22a3f4821b29a1fd7a7f385667b91/aux/tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6549865297581462}}
{"text": "Require Export D.\n\n\n\n(** **** Exercise: 1 star (dist_not_exists)  *)\n(** Prove that \"[P] holds for all [x]\" implies \"there is no [x] for\n    which [P] does not hold.\" *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof. intros.  unfold not. intro Hcontra.\n  inversion Hcontra. apply proof in H. inversion H. 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/P23.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6549865266297339}}
{"text": "Require Import Undecidability.Synthetic.Definitions.\n\nSet Implicit Arguments.\n\n(* ** Pre-order properties *)\n\nSection Properties.\n\n  Variables (X : Type) (P : X -> Prop)\n            (Y : Type) (Q : Y -> Prop)\n            (Z : Type) (R : Z -> Prop).\n\n  Fact reduces_reflexive : P ⪯ P.\n  Proof. exists (fun x => x); red; tauto. Qed.\n\n  Fact reduces_transitive : P ⪯ Q -> Q ⪯ R -> P ⪯ R.\n  Proof.\n    unfold reduces, reduction.\n    intros (f & Hf) (g & Hg).\n    exists (fun x => g (f x)).\n    firstorder easy.\n  Qed.\n\n  (* ** An equivalent dependent definition *)\n\n  Fact reduces_dependent :\n    P ⪯ Q <-> inhabited (forall x, { y | P x <-> Q y }).\n  Proof.\n    constructor.\n    - intros [f Hf]. constructor. intros x. now exists (f x).\n    - intros [f]. exists (fun x => proj1_sig (f x)).\n      intros x. exact (proj2_sig (f x)).\n  Qed.\n\n  Fact reduces_complement : P ⪯ Q -> complement P ⪯ complement Q.\n  Proof.\n    intros [f Hf].\n    exists f. intros x. specialize (Hf x). split.\n    all: intros H Hc; apply H, Hf, Hc.\n  Qed.\n\nEnd Properties.\n\nLemma dec_red X (p : X -> Prop) Y (q : Y -> Prop) :\n  p ⪯ q -> decidable q -> decidable p.\nProof.\n  unfold decidable, decider, reduces, reduction, reflects.\n  intros [f] [d]. exists (fun x => d (f x)).\n  firstorder easy.\nQed.\n\nLemma red_comp X (p : X -> Prop) Y (q : Y -> Prop) :\n  p ⪯ q -> (fun x => ~ p x) ⪯ (fun y => ~ q y).\nProof.\n  intros [f Hf]. exists f. firstorder easy.\nQed.\n\nModule ReductionChainNotations.\n\n(* YF: Broken on Coq 8.13.2 \n\n(* DLW: Thx to M. Wuttke for the tip, see coq-club ML *)\n\nLtac redchain2Prop_rec xs :=\n  lazymatch xs with\n  | pair ?x (pair ?y ?xs) =>\n    let z := redchain2Prop_rec (pair y xs) in\n    constr:(x ⪯ y /\\ z)\n  | pair ?x ?y => constr:(x ⪯ y)\n  end.\n\nLtac redchain2Prop xs :=\n  let z := redchain2Prop_rec xs \n  in  exact z.\n\nDeclare Scope reduction_chain.\nDelimit Scope reduction_chain with redchain_scope.\nNotation \"x '⪯ₘ' y\" := (pair x y) (at level 80, right associativity, only parsing) : reduction_chain.\nNotation \"'⎩' xs '⎭'\" := (ltac:(redchain2Prop (xs % redchain_scope))) (only parsing).\n\n*)\n\n(*\nDefinition Undec_Problem := { X : Type & X -> Prop }.\n\nDefinition undec_problem X (P : X -> Prop) : Undec_Problem := existT _ X P.\n\nNotation \"⎩ p ⎭\" := (@undec_problem _ p) (format \"⎩ p ⎭\").\n\nInfix \"⪯ₚ\" := (fun p q : Undec_Problem => projT2 p ⪯ projT2 q : Prop) (at level 70).\n\nReserved Notation \"p '⪯ₗ' q 'by' l\" (at level 70).\n\nSection reduction_chain.\n\n  Inductive reduction_chain : Undec_Problem -> Undec_Problem -> list Undec_Problem -> Prop :=\n    | reduction_chain_nil  : forall p, p ⪯ₗ p by nil\n    | reduction_chain_cons : forall p q r l, p ⪯ₚ q -> q ⪯ₗ r by l -> p ⪯ₗ r by q::l\n  where \"p '⪯ₗ' q 'by' l\" := (reduction_chain p q l).\n\n  Fact reduction_chain_reduces p q l : p ⪯ₗ q by l -> p ⪯ₚ q.\n  Proof.\n    induction 1 as [ p | p q r l H1 _ ? ].\n    + apply reduces_reflexive.\n    + apply reduces_transitive with (1 := H1); trivial.\n  Qed.\n\n  Fact reduction_chain_app p q r l m : p ⪯ₗ q by l -> q ⪯ₗ r by m -> p ⪯ₗ r by l++m.\n  Proof.\n    induction 1; intros; auto.\n    constructor 2; auto.\n  Qed.\n\nEnd reduction_chain.\n\nNotation \"p '⪯ₗ' q 'by' l\" := (reduction_chain p q l).\n\nTactic Notation \"red\" \"chain\" \"stop\" := constructor 1.\nTactic Notation \"red\" \"chain\" \"step\" constr(H) := constructor 2; [ apply H | ].\nTactic Notation \"red\" \"chain\" \"app\" constr(H) := apply reduction_chain_app with (1 := H).\n*)\n\nTactic Notation \"reduce\" \"with\" \"chain\" constr(H) := \n  repeat (apply (reduces_reflexive _) || (eapply reduces_transitive; [ apply H | ])).\n\nEnd ReductionChainNotations.\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/Synthetic/ReducibilityFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.654986522335169}}
{"text": "(** **** bool 基本定义 *)  \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\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\n(* 为何取反的符号不能定义,报错： *)\n(* The reference x was not found in the current environment. *)\n(* Notation \"!x\" := (negb x). *)\nNotation \"! x\" := (negb x)(at level 70).\n\nExample test_orb:  false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_not:  !false = true.\nProof. simpl. reflexivity. Qed.", "meta": {"author": "TysonSir", "repo": "coq", "sha": "3d5cd319a377acbdad1bec34061d298043c9bc18", "save_path": "github-repos/coq/TysonSir-coq", "path": "github-repos/coq/TysonSir-coq/coq-3d5cd319a377acbdad1bec34061d298043c9bc18/week1/problem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6549865203729092}}
{"text": "(** * Extract: Running Coq Programs in OCaml *)\n\n(** Coq's [Extraction] feature enables you to write a functional\n    program inside Coq, use Coq's logic to prove some correctness\n    properties about it, and translate it into an OCaml program that\n    you can compile with your optimizing OCaml compiler.  Haskell is\n    also supported. *)\n\n(** The [Extraction] chapter of _Logical Foundations_ has\n    a simple example of Coq's program extraction features, but it's\n    not required reading. This chapter starts from scratch and goes\n    deeper. *)\n\nFrom VFA Require Import Perm.\nRequire Extraction.\n\n(* ################################################################# *)\n(** * Extraction *)\n\n(** As an example, let's extract insertion sort, which we implemented\n    in [Sort]. *)\n\nFixpoint ins (i : nat) (l : list nat) :=\n  match l with\n  | [] => [i]\n  | h :: t => if i <=? h then i :: h :: t else h :: ins i t\n  end.\n\nFixpoint sort (l : list nat) : list nat :=\n  match l with\n  | [] => []\n  | h :: t => ins h (sort t)\n  end.\n\n(** The [Extraction] command prints out a function as OCaml code. *)\n\nExtraction sort.\n\n(** You can see the translation of [sort] from Coq to OCaml in\n    your IDE.  Examine it there, and notice the similarities and\n    differences.  To get the whole program, we need [Recursive\n    Extraction]: *)\n\nRecursive Extraction sort.\n\n(** The first thing you see there is a redefinition of the [bool] type.\n    But OCaml already has a [bool] type whose inductive structure is\n    isomorphic. We want our extracted functions to be compatible\n    with, i.e. callable by, ordinary OCaml code. So we want to use\n    OCaml's standard definition of [bool] in place of Coq's inductive\n    definition, [bool]. You'll notice the same issue with lists. The\n    following directive causes Coq to use OCaml's definitions of [bool]\n    and [list] in the extracted code: *)\n\nExtract Inductive bool => \"bool\" [ \"true\" \"false\" ].\nExtract Inductive list => \"list\" [ \"[]\" \"(::)\" ].\nRecursive Extraction sort.\n\n(** But the program still uses a unary representation of natural\n    numbers: the number 7 is really [(S (S (S (S (S (S (S O)))))))],\n    which in OCaml will be a data structure that's seven pointers\n    deep. The [leb] function takes linear time, proportional to the\n    difference in value between [n] and [m]. *)\n\n(** We could instead use Coq's [Z], which is a binary representation\n    of integers. But that is logarithmic-time, not constant. *)\n\nRequire Import ZArith.\nOpen Scope Z_scope.\n\nFixpoint insertZ (i : Z) (l : list Z) :=\n  match l with\n  | [] => [i]\n  | h :: t => if i <=? h then i :: h :: t else h :: insertZ i t\n  end.\n\nFixpoint sortZ (l : list Z) : list Z :=\n  match l with\n  | [] => []\n  | h :: t => insertZ h (sortZ t)\n  end.\n\nRecursive Extraction sortZ.\n\n(** Of course, for that extraction to be meaningful, we would need\n    to prove that [sortZ] is a sorting algorithm. *)\n\n(** Other alternatives include:\n\n    - Extract [nat] directly to OCaml [int].  But [int] is finite (2^63\n      in modern implementations), so there are theorems we could prove\n      in Coq that wouldn't hold in OCaml.\n\n    - Use Coq's [Int63], which faithfully models 63-bit cyclic\n      arithmetic, and extract directly to OCaml [int]. But that's\n      painful.\n\n    - Define and axiomatize our own lightweight abstract type of\n      naturals, but extract it to OCaml [int].  But, this is\n      dangerous! If our axioms are inconsistent, we can prove anything\n      at all. If they are not faithful to OCaml, our proofs will be\n      meaningless. *)\n\n(* ################################################################# *)\n(** * Lightweight Extraction to [int] *)\n\n(** We begin by positing a Coq type [int] that will be extracted to\n    OCaml's [int]: *)\n\nParameter int : Type.\nExtract Inlined Constant int => \"int\".\n\n(** We'll abstract OCaml [int] to Coq [Z].  Every [int] does have a\n    representation as a [Z], though the other direction cannot\n    hold. *)\n\nParameter Abs : int -> Z.\nAxiom Abs_inj: forall (n m : int), Abs n = Abs m -> n = m.\n\n(** Nothing else is known so far about [int]. Let's add a less-than\n    operators, which are extracted to OCaml's: *)\n\nParameter ltb: int -> int -> bool.\nExtract Inlined Constant ltb => \"(<)\".\nAxiom ltb_lt : forall (n m : int), ltb n m = true <-> Abs n < Abs m.\n\nParameter leb: int -> int -> bool.\nExtract Inlined Constant leb => \"(<=)\".\nAxiom leb_le : forall (n m : int), leb n m = true <-> Abs n <= Abs m.\n\n(** Those axioms are sound: OCaml's [<] and [<=] are consistent with\n    Coq's on any [int]. Note that we do not give extraction directives\n    for [Abs], [ltb_lt], or [leb_le].  They will not appear in\n    programs, only in proofs --which are not meant to be extracted. *)\n\n(** You could imagine doing the same thing we just did with [(+)], but\n    that would be wrong:\n\n      Parameter ocaml_plus : int -> int -> int.\n      Extract Inlined Constant ocaml_plus => \"(+)\".\n      Axiom ocaml_plus_plus: forall a b c: int,\n        ocaml_plus a b = c <-> Abs a + Abs b = Abs c.\n\n    The first two lines are OK: there really is a [+] function in\n    OCaml, and its type really is [int -> int -> int].\n\n    But [ocaml_plus_plus] is unsound. From it, you could prove,\n\n      Abs max_int + Abs max_int = Abs (ocaml_plus max_int max_int)\n\n    which is not true in OCaml because of overflow.\n\n*)\n\n(** In [Perm] we proved several theorems showing that Boolean\n    operators were reflected in propositions.  Below, we do that\n    for [int] and [Z] comparisons. *)\n\nLemma int_ltb_reflect : forall x y, reflect (Abs x < Abs y) (ltb x y).\nProof.\n  intros x y.\n  apply iff_reflect. symmetry. apply ltb_lt.\nQed.\n\nLemma int_leb_reflect : forall x y, reflect (Abs x <= Abs y) (leb x y).\nProof.\n  intros x y.\n  apply iff_reflect. symmetry. apply leb_le.\nQed.\n\nLemma Z_eqb_reflect : forall x y, reflect (x = y) (Z.eqb x y).\nProof.\n  intros x y.\n  apply iff_reflect. symmetry. apply Z.eqb_eq.\nQed.\n\nLemma Z_ltb_reflect : forall x y, reflect (x < y) (Z.ltb x y).\nProof.\n  intros x y.\n  apply iff_reflect. symmetry. apply Z.ltb_lt.\nQed.\n\nLemma Z_leb_reflect : forall x y, reflect (x <= y) (Z.leb x y).\nProof.\n  intros x y.\n  apply iff_reflect. symmetry. apply Z.leb_le.\nQed.\n\nLemma Z_gtb_reflect : forall x y, reflect (x > y) (Z.gtb x y).\nProof.\n  intros x y.\n  apply iff_reflect. symmetry. rewrite Z.gtb_ltb. rewrite Z.gt_lt_iff. apply Z.ltb_lt.\nQed.\n\nLemma Z_geb_reflect : forall x y, reflect (x >= y) (Z.geb x y).\nProof.\n  intros x y.\n  apply iff_reflect. symmetry. rewrite Z.geb_leb. rewrite Z.ge_le_iff. apply Z.leb_le.\nQed.\n\n(** Now we upgrade [bdall] to work with [Z] and [int].  *)\n\nHint Resolve\n     int_ltb_reflect int_leb_reflect\n     Z_eqb_reflect Z_ltb_reflect Z_leb_reflect Z_gtb_reflect Z_geb_reflect\n  : bdestruct.\n\nLtac bdestruct_guard:=\n  match goal with\n  | |- context [ if Nat.eqb ?X ?Y then _ else _] => bdestruct (Nat.eqb X Y)\n  | |- context [ if Nat.ltb ?X ?Y then _ else _] => bdestruct (Nat.ltb X Y)\n  | |- context [ if Nat.leb ?X ?Y then _ else _] => bdestruct (Nat.leb X Y)\n  | |- context [ if Z.eqb ?X ?Y then _ else _] => bdestruct (Z.eqb X Y)\n  | |- context [ if Z.ltb ?X ?Y then _ else _] => bdestruct (Z.ltb X Y)\n  | |- context [ if Z.leb ?X ?Y then _ else _] => bdestruct (Z.leb X Y)\n  | |- context [ if Z.gtb ?X ?Y then _ else _] => bdestruct (Z.gtb X Y)\n  | |- context [ if Z.geb ?X ?Y then _ else _] => bdestruct (Z.geb X Y)\n  | |- context [ if ltb ?X ?Y then _ else _] => bdestruct (ltb X Y)\n  | |- context [ if leb ?X ?Y then _ else _] => bdestruct (leb X Y)\n  end.\n\nLtac bdall :=\n  repeat (simpl; bdestruct_guard; try omega; auto).\n\n(* ################################################################# *)\n(** * Insertion Sort, Extracted *)\n\n(** We're ready to state insertion sort with [int], and to extract it: *)\n\nFixpoint ins_int (i : int) (l : list int) :=\n  match l with\n  | [] => [i]\n  | h :: t => if leb i h then i :: h :: t else h :: ins_int i t\n  end.\n\nFixpoint sort_int (l : list int) : list int :=\n  match l with\n  | [] => []\n  | h :: t => ins_int h (sort_int t)\n  end.\n\nRecursive Extraction sort_int.\n\n(** Again, for that extraction to be meaningful, we need to prove that\n    [sort_int] is a sorting algorithm.  We can do that with the same\n    techniques we used in [Sort].  In particular, [omega] works\n    with [Z], so we can enjoy automation without having to do any\n    unnecessary work axiomatizing and proving lemmas about [int]. *)\n\n\nInductive sorted : list int -> Prop :=\n| sorted_nil:\n    sorted []\n| sorted_1: forall x,\n    sorted [x]\n| sorted_cons: forall x y l,\n    Abs x <= Abs y -> sorted (y :: l) -> sorted (x :: y :: l).\n\nHint Constructors sorted.\n\nLemma insert_sorted:\n  forall a l, sorted l -> sorted (ins_int a l).\nProof.\n  intros a l S. induction S; simpl.\n  - constructor.\n  - bdall; auto.\n    constructor; auto. omega.\n  - bdall; auto.\n    bdall.\n    + constructor; auto. omega.\n    + constructor; auto.\n      simpl in IHS. bdestruct (leb a y); auto.\n      unfold not in H0. unfold not in H1. auto. omega.\nQed.\n\nTheorem sort_sorted: forall l, sorted (sort_int l).\nProof.\n  induction l; simpl; auto.\n  apply insert_sorted. auto.\nQed.\n\nLemma insert_perm: forall x l,\n    Permutation (x :: l) (ins_int x l).\nProof.\n  induction l; simpl.\n  - apply Permutation_refl.\n  - destruct (leb x a).\n    + apply Permutation_refl.\n    + apply perm_trans with (a :: x :: l).\n      * apply perm_swap.\n      * apply perm_skip. assumption.\nQed.\n\n(** **** Exercise: 3 stars, standard (sort_int_correct)  *)\n\n(** Prove the correctness of [sort_int] by adapting your solution to\n    [insertion_sort_correct] from [Sort]. *)\n\nTheorem sort_int_correct : forall (al : list int),\n    Permutation al (sort_int al) /\\ sorted (sort_int al).\nProof.\n  split.\n  - induction al.\n    apply Permutation_refl.\n    simpl. apply Permutation_trans with (a :: (sort_int al)).\n    apply perm_skip. assumption.\n    + apply insert_perm.\n  - apply sort_sorted.\nQed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Binary Search Trees, Extracted *)\n\n(** We can reimplement BSTs with [int] keys. *)\n\nDefinition key := int.\n\nInductive tree (V : Type) : Type :=\n  | E : tree V\n  | T : tree V -> key -> V -> tree V -> tree V.\n\nArguments E {V}.\nArguments T {V}.\n\nDefinition empty_tree {V : Type} : tree V := E.\n\nFixpoint lookup {V : Type} (default : V) (x : key) (t : tree V) : V :=\n  match t with\n  | E => default\n  | T l k v r => if ltb x k then lookup default x l\n                else if ltb k x then lookup default x r\n                     else v\n  end.\n\nFixpoint insert {V : Type} (x : key) (v : V) (t : tree V) : tree V :=\n  match t with\n  | E => T E x v E\n  | T l y v' r => if ltb x y then T (insert x v l) y v' r\n                 else if ltb y x then T l y v' (insert x v r)\n                      else T l x v r\n  end.\n\nFixpoint elements_tr {V : Type}\n         (t : tree V) (acc : list (key * V)) : list (key * V) :=\n  match t with\n  | E => acc\n  | T l k v r => elements_tr l ((k, v) :: elements_tr r acc)\n  end.\n\nDefinition elements {V : Type} (t : tree V) : list (key * V) :=\n  elements_tr t [].\n\nTheorem lookup_empty : forall (V : Type) (default : V) (k : key),\n    lookup default k empty_tree = default.\nProof. auto. Qed.\n\n(** **** Exercise: 2 stars, standard (lookup_insert_eq)  *)\nTheorem lookup_insert_eq :\n  forall (V : Type) (default : V) (t : tree V) (k : key) (v : V),\n    lookup default k (insert k v t) = v.\nProof.\n  intros. induction t.\n  -  simpl. bdall.\n  - simpl. bdall.\nQed.\n(** [] *)\n\nLemma geimpeq : forall (k : int) (k' : int),\n    (Abs k' >= Abs k) -> (Abs k >= Abs k') -> (Abs k' = Abs k).\nProof.\n  intros. omega.\nQed.\n\n(** **** Exercise: 3 stars, standard (lookup_insert_neq)  *)\nTheorem lookup_insert_neq :\n  forall (V : Type) (default : V) (t : tree V) (k k' : key) (v : V),\n    k <> k' -> lookup default k' (insert k v t) = lookup default k' t.\nProof.\n  intros. induction t.\n  - simpl.  unfold not in H.\n    bdall.  apply Znot_lt_ge in H0. apply Znot_lt_ge in H1.\n    apply geimpeq in H0.  apply Abs_inj in H0. apply H in H0. inversion H0.\n    apply H1.\n  - simpl. bdall. apply Znot_lt_ge in H2. apply Znot_lt_ge in H3.\n    apply geimpeq in H2.  apply Abs_inj in H2. apply H in H2. inversion H2.\n    apply H3.\nQed.\n(** [] *)\n\n(** **** Exercise: 5 stars, standard, optional (int_elements)  *)\n\n(** Port the definition of [BST] and re-prove the properties of\n    [elements] for [int]-keyed trees. Send us your solution so\n    we can include it! *)\n\n(** [] *)\n\n(** Now see the extraction in your IDE: *)\n\nExtract Inductive prod => \"(*)\"  [ \"(,)\" ]. (* extract pairs natively *)\nRecursive Extraction empty_tree insert lookup elements.\n\n(* ################################################################# *)\n(** * Performance Tests *)\n\n(** Let's measure the performance of BSTs.  First, we extract to\n    an OCaml file: *)\n\nExtraction \"searchtree.ml\" empty_tree insert lookup elements.\n\n(** Second, in the same directory as this file ([Extract.v])\n    you will find the file [test_searchtree.ml]. You can\n    run it using the OCaml toplevel with these commands:\n\n# #use \"searchtree.ml\";;\n# #use \"test_searchtree.ml\";;\n\nOn a recent machine with a 2.9 GHz Intel Core i9 that prints:\n\nInsert and lookup 1000000 random integers in .889566 seconds.\nInsert and lookup 20000 random integers in 0.009918 seconds.\nInsert and lookup 20000 consecutive integers in 2.777335 seconds.\n\nThat execution uses the bytecode interpreter.  The native compiler\nwill have better performance:\n\n$ ocamlopt -c searchtree.mli searchtree.ml\n$ ocamlopt searchtree.cmx -open Searchtree test_searchtree.ml -o test_searchtree\n$ ./test_searchtree\n\nOn the same machine that prints,\n\nInsert and lookup 1000000 random integers in 0.488973 seconds.\nInsert and lookup 20000 random integers in 0.003237 seconds.\nInsert and lookup 20000 consecutive integers in 0.387535 seconds.\n*)\n\n(** Of course, the reason why the performance is so much worse with\n    consecutive integers is that BSTs exhibit worst-case performance\n    under that workload: linear time instead of logarithmic.  We need\n    balanced search trees to achieve logarithmic.  [Redblack]\n    will do that. *)\n\n(* Mon May 11 23:21:35 EDT 2020 *)\n", "meta": {"author": "maspin22", "repo": "CoqFormalVerification", "sha": "9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d", "save_path": "github-repos/coq/maspin22-CoqFormalVerification", "path": "github-repos/coq/maspin22-CoqFormalVerification/CoqFormalVerification-9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d/coq_4160/finalsrc/Extract.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.6549214278238519}}
{"text": "Require Import Program.Equality Lia SimplDec.\nRequire Export ListExtra PreSuffix ListOrder.\n\nDefinition Tag := list nat.\n\nInductive Taglt : Tag -> Tag -> Prop :=\n| TagltS (n m : nat) (i : Tag) : n < m -> Taglt (n :: i) (m :: i)\n| TagltCons (n m : nat) (i j : Tag) : Taglt i j -> Taglt (n :: i) (m :: j).\n\nDefinition Tagle (i j : Tag) : Prop := Taglt i j \\/ i = j.\n\nInfix \"⊴\" := Tagle (at level 70).\nInfix \"◁\" := Taglt (at level 70).\n\nLemma Tagle_refl (i : Tag)\n  : i ⊴ i.\nProof.\n  right;auto.\nQed.\n\nLemma Taglt_irrefl\n  : Irreflexive Taglt.\nProof.\n  unfold Irreflexive, Reflexive, complement.\n  intros x Hx.\n  dependent induction Hx.\n  - lia.\n  - auto.\nQed.\n\nLemma Taglt_trans\n  : Transitive Taglt.\nProof.\n  intros x y z Hxy Hyz.\n  revert dependent z.\n  dependent induction Hxy;intros.\n  - dependent destruction Hyz.\n    + econstructor. lia.\n    + econstructor. auto.\n  - dependent destruction Hyz.\n    + econstructor. auto.\n    + econstructor. eauto.\nQed.\n\nHint Resolve Taglt_irrefl Taglt_trans : tagle.\n\nGlobal Instance Taglt_StrictOrder : StrictOrder Taglt.\nProof.\n  split; eauto with tagle.\nQed.\n\nGlobal Instance Tagle_PreOrder : PreOrder Tagle.\nProof.\n  eapply StrictOrder_PreOrder;eauto.\nQed.\n\nGlobal Instance Tagle_PartialOrder : PartialOrder eq Tagle.\nProof.\n  eapply StrictOrder_PartialOrder;eauto.\nQed.\n\nLemma Taglt_non_nil1 (i : Tag)\n  : [] ◁ i -> False.\nProof.\n  intro H. inversion H.\nQed.\n\nLemma Taglt_non_nil2 (i : Tag)\n  : i ◁ [] -> False.\nProof.\n  intro H. inversion H.\nQed.\n\nHint Immediate Taglt_non_nil1 Taglt_non_nil2 : tagle.\n\nLemma Taglt_len (i j : Tag)\n      (Htaglt : i ◁ j)\n  : | i | = | j |.\nProof.\n  induction Htaglt;cbn;auto.\nQed.\n\nLemma Taglt_rcons_le (i j : Tag) (n m : nat)\n      (Htaglt : i ++ [n] ◁ j ++ [m])\n  : n <= m.\nProof.\n  dependent induction Htaglt.\n  - rewrite cons_rcons' in x0.\n    rewrite cons_rcons' in x.\n    eapply app_inj_tail in x0.\n    eapply app_inj_tail in x.\n    do 2 destructH. subst n m.\n    cbn in *.\n    rinduction i0; cbn in *.\n    + lia.\n    + rewrite rev_rcons. cbn. reflexivity.\n  - destruct i0. inversion Htaglt.\n    destruct j0. inversion Htaglt.\n    eapply (IHHtaglt (tl i) (tl j));eauto.\n    + destruct i;cbn in *;eauto. congruence. inversion x0. eauto.\n    + destruct j;cbn in *;eauto. congruence. inversion x. eauto.\nQed.\n\nLemma Taglt_eq_rcons_lt (i : Tag) (n m : nat)\n      (Htaglt : i ++ [n] ◁ i ++ [m])\n  : n < m.\nProof.\n  induction i;cbn in *.\n  - inversion Htaglt;subst;auto. inversion H0.\n  - eapply IHi. inversion Htaglt;subst.\n    + lia.\n    + auto.\nQed.\n\nHint Immediate Taglt_irrefl : tagle.\n\nLemma Taglt_eq_cons_lt (i : Tag) (n m : nat)\n      (Htaglt : n :: i ◁ m :: i)\n  : n < m.\nProof.\n  inversion Htaglt;subst;eauto.\n  exfalso. eapply Taglt_irrefl; eauto.\nQed.\n\nLemma Taglt_eq_rcons_Taglt (i j : Tag) (n : nat)\n      (Htaglt : i ++ [n] ◁ j ++ [n])\n  : i ◁ j.\nProof.\n  eapply Taglt_len in Htaglt as Hlen.\n  do 2 rewrite length_rcons in Hlen. eapply Nat.succ_inj in Hlen.\n  destruct i;[|revert dependent i; revert dependent n0];induction j;cbn in *;intros.\n  - exfalso. inversion Htaglt;subst. lia. eauto with tagle.\n  - lia.\n  - lia.\n  - dependent destruction Htaglt.\n    + eapply app_inj_tail in x; destruct x;subst.\n      econstructor;eauto.\n    + econstructor.\n      destruct i,j; cbn in *.\n      1: exfalso;eapply Taglt_irrefl;eauto.\n      1,2: lia.\n      eapply IHj;eauto.\nQed.\n\nLemma Taglt_le_rcons (n m : nat) (i j : Tag)\n      (Htaglt : i ◁ j)\n      (Hle : n <= m)\n  : i ++ [n] ◁ j ++ [m].\nProof.\n  induction Htaglt;cbn.\n  - eapply le_lt_or_eq in Hle. destruct Hle.\n    + econstructor;eauto. induction i; cbn; econstructor; eauto.\n    + subst. econstructor;eauto.\n  - econstructor;eauto.\nQed.\n\nLemma Taglt_lt_rcons (n m : nat) (i j : Tag)\n      (Hlen : |i| = |j|)\n      (Hlt : n < m)\n  : i ++ [n] ◁ j ++ [m].\nProof.\n  destruct i; intros.\n  - destruct j; cbn in *.\n    + econstructor; eauto.\n    + lia.\n  - revert n0 i Hlen.\n    induction j; cbn in *; intros.\n    + lia.\n    + destruct i; cbn in *.\n      * destruct j; cbn in *; [|lia].\n        econstructor;econstructor;eauto.\n      * econstructor.\n        eapply IHj.\n        lia.\nQed.\n\nLemma Taglt_ind_r\n      (P : Tag -> Tag -> Prop)\n      (Hbase : forall (n m : nat) (i j : Tag), |i| = |j| -> n < m -> P (i++[n]) (j++[m]))\n      (Hstep : forall (n : nat) (i j : Tag), Taglt i j -> P i j -> P (i++[n]) (j++[n]))\n      (i j : Tag)\n      (Htaglt : Taglt i j)\n  : P i j.\nProof.\n  revert dependent j.\n  rinduction i. 1: exfalso; eauto with tagle.\n  revert dependent l. revert dependent a.\n  rinduction j. 1: exfalso; eauto with tagle.\n  eapply Taglt_len in Htaglt as Hlen.\n  do 2 rewrite length_rcons in Hlen. eapply Nat.succ_inj in Hlen.\n  eapply Taglt_rcons_le in Htaglt as Hle.\n  eapply le_lt_or_eq in Hle.\n  destruct Hle.\n  - eapply Hbase;eauto.\n  - subst a0.\n    eapply Taglt_eq_rcons_Taglt in Htaglt.\n    eapply Hstep;eauto.\nQed.\n\nLemma taglt_tagle_trans (i j k : Tag)\n  : i ◁ j -> j ⊴ k -> i ◁ k.\nProof.\n  intros.\n  destruct H0.\n  - transitivity j;eauto.\n  - subst. auto.\nQed.\n\nLemma tagle_taglt_trans (i j k : Tag)\n  : i ⊴ j -> j ◁ k -> i ◁ k.\nProof.\n  intros.\n  destruct H.\n  - transitivity j;eauto.\n  - subst. auto.\nQed.\n\nLemma le_cons_tagle n1 n2 i\n      (Hlt : n1 <= n2)\n  : n1 :: i ⊴ n2 :: i.\nProof.\n  eapply le_lt_or_eq in Hlt. destruct Hlt.\n  - econstructor. econstructor. assumption.\n  - subst. reflexivity.\nQed.\n\nLemma lt_cons_ntagle n1 n2 i\n      (Hlt : n2 < n1)\n  : ~ n1 :: i ⊴ n2 :: i.\nProof.\n  simpl_dec.\n  split.\n  - intro N.\n    inv N.\n    + lia.\n    + eapply Taglt_irrefl;eauto.\n  - intro N. inv N. lia.\nQed.\n\nLemma taglt_trichotomy i j\n      (Hlen : |i| = |j|)\n  : i ◁ j \\/ i = j \\/ j ◁ i.\nProof.\n  remember (|i|) as n.\n  revert i j Heqn Hlen.\n  induction n;intros.\n  - destruct i,j;cbn in *;try congruence. right. left. reflexivity.\n  - destruct i,j;cbn in *;try congruence.\n    specialize (IHn i j).\n    exploit IHn.\n    destruct IHn as [IHn|[IHn|IHn]];[left| |right;right].\n    + econstructor;eauto.\n    + subst.\n      specialize (Nat.lt_trichotomy n0 n1) as Hcase.\n      destruct Hcase as [Hcase|Hcase];[left|right];[|destruct Hcase as [Hcase|Hcase];[left|right]].\n      * econstructor;eauto.\n      * subst. reflexivity.\n      * econstructor;eauto.\n    + econstructor;eauto.\nQed.\n\nLemma tagle_or i j\n      (Hlen : |i| = |j|)\n  : i ⊴ j \\/ j ⊴ i.\nProof.\n  eapply taglt_trichotomy in Hlen.\n  destruct Hlen as [Hlen|[Hlen|Hlen]];[left;left|left;right|right;left];eauto.\nQed.\n\nLemma Tagle_len: forall [i j : Tag], i ⊴ j -> | i | = | j |.\nProof.\n  intros. destruct H.\n  - eapply Taglt_len;eauto.\n  - subst. reflexivity.\nQed.\n", "meta": {"author": "cdl-saarland", "repo": "uniana", "sha": "abef56560e9b1b2e8653f732b4c14a823125f212", "save_path": "github-repos/coq/cdl-saarland-uniana", "path": "github-repos/coq/cdl-saarland-uniana/uniana-abef56560e9b1b2e8653f732b4c14a823125f212/uniana/tcfg/Tagleq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541611, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6548920136625356}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Export NOrder.\n\nModule NAddOrderProp (Import N : NAxiomsMiniSig').\nInclude NOrderProp N.\n\n\n\nTheorem le_add_r : forall n m, n <= n + m.\nProof. hammer_hook \"NAddOrder\" \"NAddOrder.NAddOrderProp.le_add_r\".  \nintro n; induct m.\nrewrite add_0_r; now apply eq_le_incl.\nintros m IH. rewrite add_succ_r; now apply le_le_succ_r.\nQed.\n\nTheorem lt_lt_add_r : forall n m p, n < m -> n < m + p.\nProof. hammer_hook \"NAddOrder\" \"NAddOrder.NAddOrderProp.lt_lt_add_r\".  \nintros n m p H; rewrite <- (add_0_r n).\napply add_lt_le_mono; [assumption | apply le_0_l].\nQed.\n\nTheorem lt_lt_add_l : forall n m p, n < m -> n < p + m.\nProof. hammer_hook \"NAddOrder\" \"NAddOrder.NAddOrderProp.lt_lt_add_l\".  \nintros n m p; rewrite add_comm; apply lt_lt_add_r.\nQed.\n\nTheorem add_pos_l : forall n m, 0 < n -> 0 < n + m.\nProof. hammer_hook \"NAddOrder\" \"NAddOrder.NAddOrderProp.add_pos_l\".  \nintros; apply add_pos_nonneg. assumption. apply le_0_l.\nQed.\n\nTheorem add_pos_r : forall n m, 0 < m -> 0 < n + m.\nProof. hammer_hook \"NAddOrder\" \"NAddOrder.NAddOrderProp.add_pos_r\".  \nintros; apply add_nonneg_pos. apply le_0_l. assumption.\nQed.\n\nEnd NAddOrderProp.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Numbers/Natural/Abstract/NAddOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6548920108865526}}
{"text": "(* This file is generated by Why3's Coq driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import ZArith.\nRequire Import Rbase.\nRequire int.Int.\n\nParameter bag : forall (a:Type), Type.\n\nParameter nb_occ: forall (a:Type), a -> (bag a) -> Z.\nImplicit Arguments nb_occ.\n\nAxiom occ_non_negative : forall (a:Type), forall (b:(bag a)) (x:a),\n  (0%Z <= (nb_occ x b))%Z.\n\n(* Why3 assumption *)\nDefinition mem (a:Type)(x:a) (b:(bag a)): Prop := (0%Z <  (nb_occ x b))%Z.\nImplicit Arguments mem.\n\n(* Why3 assumption *)\nDefinition eq_bag (a:Type)(a1:(bag a)) (b:(bag a)): Prop := forall (x:a),\n  ((nb_occ x a1) = (nb_occ x b)).\nImplicit Arguments eq_bag.\n\nAxiom bag_extensionality : forall (a:Type), forall (a1:(bag a)) (b:(bag a)),\n  (eq_bag a1 b) -> (a1 = b).\n\nParameter empty_bag: forall (a:Type), (bag a).\nSet Contextual Implicit.\nImplicit Arguments empty_bag.\nUnset Contextual Implicit.\n\nAxiom occ_empty : forall (a:Type), forall (x:a), ((nb_occ x (empty_bag :(bag\n  a))) = 0%Z).\n\nAxiom is_empty : forall (a:Type), forall (b:(bag a)), (forall (x:a),\n  ((nb_occ x b) = 0%Z)) -> (b = (empty_bag :(bag a))).\n\nParameter singleton: forall (a:Type), a -> (bag a).\nImplicit Arguments singleton.\n\nAxiom occ_singleton : forall (a:Type), forall (x:a) (y:a), ((x = y) /\\\n  ((nb_occ y (singleton x)) = 1%Z)) \\/ ((~ (x = y)) /\\ ((nb_occ y\n  (singleton x)) = 0%Z)).\n\nAxiom occ_singleton_eq : forall (a:Type), forall (x:a) (y:a), (x = y) ->\n  ((nb_occ y (singleton x)) = 1%Z).\n\nAxiom occ_singleton_neq : forall (a:Type), forall (x:a) (y:a), (~ (x = y)) ->\n  ((nb_occ y (singleton x)) = 0%Z).\n\nParameter union: forall (a:Type), (bag a) -> (bag a) -> (bag a).\nImplicit Arguments union.\n\nAxiom occ_union : forall (a:Type), forall (x:a) (a1:(bag a)) (b:(bag a)),\n  ((nb_occ x (union a1 b)) = ((nb_occ x a1) + (nb_occ x b))%Z).\n\nAxiom Union_comm : forall (a:Type), forall (a1:(bag a)) (b:(bag a)),\n  ((union a1 b) = (union b a1)).\n\nAxiom Union_identity : forall (a:Type), forall (a1:(bag a)), ((union a1\n  (empty_bag :(bag a))) = a1).\n\n\n(* Why3 goal *)\nTheorem Union_assoc : forall (a:Type), forall (a1:(bag a)) (b:(bag a))\n  (c:(bag a)), ((union a1 (union b c)) = (union (union a1 b) c)).\n(* YOU MAY EDIT THE PROOF BELOW *)\nintros X a b c.\napply bag_extensionality; intro x.\ndo 4 rewrite occ_union; auto with zarith.\nQed.\n\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/tests/theory-sessions/bag/bag_Bag_Union_assoc_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6548920062703935}}
{"text": "(* @Owner MattIrv *)\n\nRequire Export QArith.\nRequire Export String.\n\nModule BinStringToQ.\n\nInductive sign :=\n  | sZero: sign\n  | sPos: sign\n  | sNeg: sign.\n\nLocal Open Scope char_scope.\n\nFixpoint bin_str_to_pos (str: string) (cp: positive) (start: bool) :=\n  match start with\n    | true =>\n      match str with\n        | EmptyString => None\n        | String char s' =>\n          match char with\n            | \"0\" => bin_str_to_pos s' xH true\n            | \"1\" => bin_str_to_pos s' xH false\n            | _ => None\n          end\n      end\n    | false =>\n      match str with\n        | EmptyString => Some cp\n        | String char s' =>\n          match char with\n            | \"0\" => bin_str_to_pos s' (xO cp) false\n            | \"1\" => bin_str_to_pos s' (xI cp) false\n            | _ => None\n          end\n      end\n  end.\n\nLocal Close Scope char_scope.\n\nDefinition numstr_to_z (numStr: string) (s: sign) :=\n  match s with\n    | sZero => Some Z0\n    | sPos => let somepos := bin_str_to_pos numStr xH true in\n      match somepos with\n        | Some p => Some (Zpos p)\n        | None => None\n      end\n    | sNeg => let somepos := bin_str_to_pos numStr xH true in\n      match somepos with\n        | Some p => Some (Zneg p)\n        | None => None\n      end\n  end.\n\nDefinition bin_str_to_q (numStr denStr: string) (s: sign) :=\n  let num := numstr_to_z numStr s in\n  let denom := bin_str_to_pos denStr xH true in\n    match num, denom with\n      | None, _ => None\n      | _, None => None\n      | Some z, Some p => Some (Qmake z p)\n    end.\n\nLocal Open Scope char_scope.\n\nFixpoint hex_str_to_bin_str (hexstr: string) :=\n  match hexstr with\n    | EmptyString => EmptyString\n    | String char s' =>\n      match char with\n        | \"0\" => \"0000\" ++ hex_str_to_bin_str s'\n        | \"1\" => \"0001\" ++ hex_str_to_bin_str s'\n        | \"2\" => \"0010\" ++ hex_str_to_bin_str s'\n        | \"3\" => \"0011\" ++ hex_str_to_bin_str s'\n        | \"4\" => \"0100\" ++ hex_str_to_bin_str s'\n        | \"5\" => \"0101\" ++ hex_str_to_bin_str s'\n        | \"6\" => \"0110\" ++ hex_str_to_bin_str s'\n        | \"7\" => \"0111\" ++ hex_str_to_bin_str s'\n        | \"8\" => \"1000\" ++ hex_str_to_bin_str s'\n        | \"9\" => \"1001\" ++ hex_str_to_bin_str s'\n        | \"A\" => \"1010\" ++ hex_str_to_bin_str s'\n        | \"B\" => \"1011\" ++ hex_str_to_bin_str s'\n        | \"C\" => \"1100\" ++ hex_str_to_bin_str s'\n        | \"D\" => \"1101\" ++ hex_str_to_bin_str s'\n        | \"E\" => \"1110\" ++ hex_str_to_bin_str s'\n        | \"F\" => \"1111\" ++ hex_str_to_bin_str s'\n        | _ => \"ERROR\"%string\n      end\n  end\nwhere \"s1 ++ s2\" := (append s1 s2).\n\nLocal Close Scope char_scope.\n\nDefinition hex_str_to_q (numStr denStr: string) (s: sign) :=\n  let numBin := hex_str_to_bin_str numStr in\n  let denBin := hex_str_to_bin_str denStr in\n  bin_str_to_q numBin denBin s.\n\nExample e1 := bin_str_to_q \"0100101\" \"101010\" sPos.\nExample e2 := bin_str_to_q \"0\" \"1\" sPos.\nExample e3 := bin_str_to_q \"1\" \"10\" sNeg.\nExample h1 := hex_str_to_bin_str \"2A\".\n\nEnd BinStringToQ.\n\nExport BinStringToQ.", "meta": {"author": "kelloggm", "repo": "kodellama2", "sha": "da665384beb56b163961d7294420f5f7e4c8690b", "save_path": "github-repos/coq/kelloggm-kodellama2", "path": "github-repos/coq/kelloggm-kodellama2/kodellama2-da665384beb56b163961d7294420f5f7e4c8690b/BinStringToQ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6548835486316412}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nSection Inverse_Image.\n\nVariables A B : Type.\nVariable R : B -> B -> Prop.\nVariable f : A -> B.\n\nLet Rof (x y:A) : Prop := R (f x) (f y).\n\nRemark Acc_lemma : forall y:B, Acc R y -> forall x:A, y = f x -> Acc Rof x.\nProof. hammer_hook \"Inverse_Image\" \"Inverse_Image.Acc_lemma\".  \ninduction 1 as [y _ IHAcc]; intros x H.\napply Acc_intro; intros y0 H1.\napply (IHAcc (f y0)); try trivial.\nrewrite H; trivial.\nQed.\n\nLemma Acc_inverse_image : forall x:A, Acc R (f x) -> Acc Rof x.\nProof. hammer_hook \"Inverse_Image\" \"Inverse_Image.Acc_inverse_image\".  \nintros; apply (Acc_lemma (f x)); trivial.\nQed.\n\nTheorem wf_inverse_image : well_founded R -> well_founded Rof.\nProof. hammer_hook \"Inverse_Image\" \"Inverse_Image.wf_inverse_image\".  \nred; intros; apply Acc_inverse_image; auto.\nQed.\n\nVariable F : A -> B -> Prop.\nLet RoF (x y:A) : Prop :=\nexists2 b : B, F x b & (forall c:B, F y c -> R b c).\n\nLemma Acc_inverse_rel : forall b:B, Acc R b -> forall x:A, F x b -> Acc RoF x.\nProof. hammer_hook \"Inverse_Image\" \"Inverse_Image.Acc_inverse_rel\".  \ninduction 1 as [x _ IHAcc]; intros x0 H2.\nconstructor; intros y H3.\ndestruct H3.\napply (IHAcc x1); auto.\nQed.\n\n\nTheorem wf_inverse_rel : well_founded R -> well_founded RoF.\nProof. hammer_hook \"Inverse_Image\" \"Inverse_Image.wf_inverse_rel\".  \nred; constructor; intros.\ncase H0; intros.\napply (Acc_inverse_rel x); auto.\nQed.\n\nEnd Inverse_Image.\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/quick/Inverse_Image.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6548835395882406}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\nRequire Import Decidable PeanoNat.\nRequire Eqdep_dec.\nLocal Open Scope nat_scope.\n\nImplicit Types m n x y : nat.\n\nTheorem O_or_S n : {m : nat | S m = n} + {0 = n}.\nProof. hammer_hook \"Peano_dec\" \"Peano_dec.O_or_S\".  \ninduction n.\n- now right.\n- left; exists n; auto.\nDefined.\n\nNotation eq_nat_dec := Nat.eq_dec (compat \"8.4\").\n\nHint Resolve O_or_S eq_nat_dec: arith.\n\nTheorem dec_eq_nat n m : decidable (n = m).\nProof. hammer_hook \"Peano_dec\" \"Peano_dec.dec_eq_nat\".  \nelim (Nat.eq_dec n m); [left|right]; trivial.\nDefined.\n\nDefinition UIP_nat:= Eqdep_dec.UIP_dec Nat.eq_dec.\n\nImport EqNotations.\n\nLemma le_unique: forall m n (le_mn1 le_mn2 : m <= n), le_mn1 = le_mn2.\nProof. hammer_hook \"Peano_dec\" \"Peano_dec.le_unique\".  \nintros m n.\ngeneralize (eq_refl (S n)).\ngeneralize n at -1.\ninduction (S n) as [|n0 IHn0]; try discriminate.\nclear n; intros n [= <-] le_mn1 le_mn2.\npose (def_n2 := eq_refl n0); transitivity (eq_ind _ _ le_mn2 _ def_n2).\n2: reflexivity.\ngeneralize def_n2; revert le_mn1 le_mn2.\ngeneralize n0 at 1 4 5 7; intros n1 le_mn1.\ndestruct le_mn1; intros le_mn2; destruct le_mn2.\n+ now intros def_n0; rewrite (UIP_nat _ _ def_n0 eq_refl).\n+ intros def_n0; generalize le_mn2; rewrite <-def_n0; intros le_mn0.\nnow destruct (Nat.nle_succ_diag_l _ le_mn0).\n+ intros def_n0; generalize le_mn1; rewrite def_n0; intros le_mn0.\nnow destruct (Nat.nle_succ_diag_l _ le_mn0).\n+ intros def_n0. injection def_n0 as ->.\nrewrite (UIP_nat _ _ def_n0 eq_refl); simpl.\nassert (H : le_mn1 = le_mn2).\nnow apply IHn0.\nnow rewrite H.\nQed.\n\n\nRequire Import Le Lt.\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/Peano_dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6548835395882406}}
{"text": "(** * Basics: Functional Programming in Coq *)\n\n(*\n   [Admitted] is Coq's \"escape hatch\" that says accept this definition\n   without proof.  We use it to mark the 'holes' in the development\n   that should be completed as part of your homework exercises.  In\n   practice, [Admitted] is useful when you're incrementally developing\n   large proofs. *)\nDefinition admit {T: Type} : T.  Admitted.\n\n(* ###################################################################### *)\n(** * Introduction *)\n\n(** The functional programming style brings programming closer to\n    simple, everyday mathematics: 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 in this way enables a host of useful and powerful\n    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 shares all of these features.\n\n    The first half of this chapter introduces the most essential\n    elements of Coq's functional programming language.  The second\n    half introduces some basic _tactics_ that can be used to prove\n    simple properties of Coq programs.\n*)\n\n(* ###################################################################### *)\n(** * Enumerated Types *)\n\n(** One unusual aspect of Coq is that its set of built-in\n    features is _extremely_ small.  For example, instead of providing\n    the usual palette of atomic data types (booleans, integers,\n    strings, etc.), Coq offers a powerful mechanism for defining new\n    data types from scratch, from which all these familiar types arise\n    as instances.\n\n    Naturally, the Coq distribution comes with an extensive standard\n    library providing definitions of booleans, numbers, and many\n    common data structures like lists and hash tables.  But there is\n    nothing magic or primitive about these library definitions.  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    To see how this definition mechanism works, let's start with a\n    very simple example. *)\n\n(* ###################################################################### *)\n(** ** Days of the Week *)\n\n(** The following declaration tells Coq that we are defining\n    a new set of data values -- a _type_. *)\n\nInductive day : Type :=\n  | monday : day\n  | tuesday : day\n  | wednesday : day\n  | thursday : day\n  | friday : day\n  | saturday : day\n  | sunday : day.\n\n(** The type is called [day], and its members are [monday],\n    [tuesday], etc.  The second 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\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 performs\n    _type inference_ -- but we'll 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.\n\n    First, we can use the command [Compute] to evaluate a compound\n    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 accompanying Coq sources, find the above example,\n    submit it to Coq, and observe the result.) *)\n\n\n(** Second, we can record what we _expect_ the result to be in\n    the form of a Coq example: *)\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\n(** This declaration does two things: it makes an\n    assertion (that the second weekday after [saturday] is [tuesday]),\n    and it gives the assertion a name that can be used to refer to it\n    later. *)\n(** Having made the assertion, we can also ask Coq to verify it,\n    like this: *)\n\nProof. simpl. reflexivity.  Qed.\n\n(** The details are not important for now (we'll come back to\n    them in a bit), but essentially this can be read as \"The assertion\n    we've just made can be proved by observing that both sides of the\n    equality 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 in its standard\n    library, together with a multitude of useful functions and\n    lemmas.  (Take a look at [Coq.Init.Datatypes] in the Coq library\n    documentation if you're interested.)  Whenever possible, we'll\n    name our own definitions and theorems so that they exactly\n    coincide with the ones in the standard library. *)\n\n(** Functions over booleans can be defined in the same way as\n    above: *)\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\nDefinition orb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\n\n(** The last two illustrate Coq's syntax for multi-argument\n    function definitions.  The corresponding multi-argument\n    application syntax is illustrated by the following four \"unit\n    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 new,\n    infix 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 to\n    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 special phrases [Admitted] and [admit] can be used as a\n    placeholder for an incomplete definition or proof.  We'll use them\n    in exercises, to indicate the parts that we're leaving for you --\n    i.e., your job is to replace [admit] or [Admitted] with real\n    definitions or 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 :=\n  (* FILL IN HERE *) admit.\n\nExample test_nandb1:               (nandb true false) = true.\n(* FILL IN HERE *) Admitted.\nExample test_nandb2:               (nandb false false) = true.\n(* FILL IN HERE *) Admitted.\nExample test_nandb3:               (nandb false true) = true.\n(* FILL IN HERE *) Admitted.\nExample test_nandb4:               (nandb true true) = false.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (andb3)  *)\n(** Do the same for the [andb3] function below. This function should\n    return [true] when all of its inputs are [true], and [false]\n    otherwise. *)\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  (* FILL IN HERE *) admit.\n\nExample test_andb31:                 (andb3 true true true) = true.\n(* FILL IN HERE *) Admitted.\nExample test_andb32:                 (andb3 false true true) = false.\n(* FILL IN HERE *) Admitted.\nExample test_andb33:                 (andb3 true false true) = false.\n(* FILL IN HERE *) Admitted.\nExample test_andb34:                 (andb3 true true false) = false.\n(* FILL IN HERE *) Admitted.\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\n(** For example, the type of [negb true] is [bool]. *)\n\nCheck true.\n(* ===> true : bool *)\nCheck (negb true).\n(* ===> negb true : bool *)\n\n(** Functions like [negb] itself are also data values, just like\n    [true] and [false].  Their types are called _function types_, and\n    they are written with arrows. *)\n\nCheck negb.\n(* ===> negb : bool -> bool *)\n\n(** The type of [negb], written [bool -> bool] and pronounced\n    \"[bool] arrow [bool],\" can be read, \"Given an input of type\n    [bool], this function produces an output of type [bool].\"\n    Similarly, the type of [andb], written [bool -> bool -> bool], can\n    be read, \"Given two inputs, both of type [bool], this function\n    produces an output of type [bool].\" *)\n\n(* ###################################################################### *)\n(** ** 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].  Here, we 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 comes with a bit of special notational\n    magic.  *)\n\nModule Playground1.\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 the natural numbers as follows:  *)\n\nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\n(** The clauses of this definition can be read:\n      - [O] is a natural number (note that this is the letter \"[O],\" not\n        the numeral \"[0]\").\n      - [S] is a \"constructor\" that takes a natural number and yields\n        another one -- that is, if [n] is a natural number, then [S n]\n        is too.\n\n    Let's look at this in a little more detail.\n\n    Every inductively defined set ([day], [nat], [bool], etc.) is\n    actually a set of _expressions_.  The definition of [nat] says how\n    expressions in the set [nat] can be constructed:\n\n    - the expression [O] belongs to the set [nat];\n    - if [n] is an expression belonging to the set [nat], then [S n]\n      is also an expression belonging to the set [nat]; and\n    - expressions formed in these two ways are the only ones belonging\n      to the set [nat].\n *)\n\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(** These three conditions are the precise force of the\n    [Inductive] declaration.  They imply that the expression [O], the\n    expression [S O], the expression [S (S O)], the expression\n    [S (S (S O))], and so on all belong to the set [nat], while other\n    expressions like [true], [andb true false], and [S (S false)] do\n    not.\n\n    We can write simple functions that pattern match on natural\n    numbers just as we did above -- for example, 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 Playground1.\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n    | O => O\n    | S O => O\n    | S (S n') => n'\n  end.\n\n(** Because natural numbers are such a pervasive form of data,\n    Coq provides a tiny bit of built-in magic for parsing and printing\n    them: ordinary arabic numerals can be used as an alternative to\n    the \"unary\" notation defined by the constructors [S] and [O].  Coq\n    prints numbers in arabic form by default: *)\n\nCheck (S (S (S (S O)))).\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! *)\n\n(** For most function definitions over numbers, just pattern\n    matching is not enough: we also need recursion.  For example, to\n    check that a number [n] is even, we may need to recursively check\n    whether [n-2] is even.  To write such functions, we use the\n    keyword [Fixpoint]. *)\n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | O        => true\n  | S O      => false\n  | S (S n') => evenb n'\n  end.\n\n(** We can define [oddb] by a similar [Fixpoint] declaration, but here\n    is a simpler definition that is a bit easier to work with: *)\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\n    shortly.)  *)\n\n(** Naturally, we can also define multi-argument functions by\n    recursion.   *)\n\nModule Playground2.\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\n(** Adding three to two now gives us five, as we'd expect. *)\n\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 bogus\n    variable name. *)\n\nEnd Playground2.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n    | O => S O\n    | S p => mult base (exp base p)\n  end.\n\n(** **** Exercise: 1 star (factorial)  *)\n(** Recall the standard 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(* FILL IN HERE *) admit.\n\nExample test_factorial1:          (factorial 3) = 6.\n(* FILL IN HERE *) Admitted.\nExample test_factorial2:          (factorial 5) = (mult 10 12).\n(* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** We can make numerical expressions a little easier to read and\n    write by introducing _notations_ for addition, multiplication, and\n    subtraction. *)\n\nNotation \"x + y\" := (plus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x - y\" := (minus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x * y\" := (mult x y)\n                       (at level 40, left associativity)\n                       : nat_scope.\n\nCheck ((0 + 1) + 1).\n\n(** (The [level], [associativity], and [nat_scope] annotations\n   control how these notations are treated by Coq's parser.  The\n   details are not important, but interested readers can refer to the\n   optional \"More on Notation\" section at the end of this chapter.) *)\n\n(** Note that these do not change the definitions we've already\n    made: they are simply instructions to the Coq parser to accept [x\n    + y] in place of [plus x y] and, conversely, to the Coq\n    pretty-printer to display [plus x y] as [x + y]. *)\n\n(** When we say that Coq comes with nothing built-in, we really\n    mean it: even equality testing for numbers is a user-defined\n    operation! *)\n(** The [beq_nat] function tests [nat]ural numbers for [eq]uality,\n    yielding a [b]oolean.  Note the use of nested [match]es (we could\n    also have used a simultaneous match, as we did in [minus].)  *)\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\n(** The [leb] function tests natural numbers for inequality, yielding\n    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  (* FILL IN HERE *) admit.\n\nExample test_blt_nat1:             (blt_nat 2 2) = false.\n(* FILL IN HERE *) Admitted.\nExample test_blt_nat2:             (blt_nat 2 4) = true.\n(* FILL IN HERE *) Admitted.\nExample test_blt_nat3:             (blt_nat 4 2) = false.\n(* FILL IN HERE *) Admitted.\n\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\n    almost exactly the same as the simpler examples we saw earlier;\n    there are 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\ncontext and the goal change. *)\n(** You may want to add calls to [simpl] before [reflexivity] to\nsee the simplifications that Coq performs on the terms before checking\nthat they are equal. *)\n\n(** Although simplification is powerful enough to prove some\n    fairly general facts, there are many statements that cannot be\n    handled by simplification alone.  For instance, we cannot use it\n    to prove that [0] is also a neutral element for [+] _on the\n    right_. *)\n\nTheorem plus_n_O : forall n, n + 0 = n.\nProof.\n  intros n. simpl. (* Doesn't do anything! *)\n\n(** (Can you explain why this happens?  Step through both proofs\n    with Coq and notice how the goal and context change.)\n\n    When stuck in the middle of a proof, we can use the [Abort]\n    command to give up on it for the moment. *)\n\nAbort.\n\n(** The next chapter will introduce _induction_, a powerful\n    technique that can be used for proving this goal.  For the moment,\n    though, let's look at a few more simple tactics. *)\n\n(* ###################################################################### *)\n(** * Proof by Rewriting *)\n\n(** This theorem is a bit more interesting than the others we've\n    seen: *)\n\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + n = m + m.\n\n(** Instead of making a universal claim about all numbers [n] and [m],\n    it talks about a more specialized property that only holds when [n\n    = m].  The arrow symbol is pronounced \"implies.\"\n\n    As before, we need to be able to reason by assuming 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  (* FILL IN HERE *) Admitted.\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] (or\n    [admit]) you are leaving a door open for total nonsense to enter\n    Coq's nice, 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. *)\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  (* 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    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\n    c] line right above it.  Besides [-] and [+], Coq proofs can also\n    use [*] (asterisk) as a third kind of bullet. If we ever encounter\n    a proof that generates more than three levels of subgoals, we can\n    also enclose individual subgoals in curly braces ([{ ... }]): *)\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  intros x y. destruct y as [|y].\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\n\n(** Now state and prove a theorem [negation_fn_applied_twice] similar\n    to the previous one but where the second hypothesis says that the\n    function [f] has the property that [f x = negb x].*)\n\n(* FILL IN HERE *)\n(** [] *)\n\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  (* FILL IN HERE *) Admitted.\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] from class,\n    Inductive nat : Type :=\n      | O : nat\n      | S : nat -> nat.\n    says nothing about what [O] and [S] \"mean.\"  It just says \"[O] is\n    in the set called [nat], and if [n] is in the set then so is [S\n    n].\"  The interpretation of [O] as zero and [S] as successor/plus\n    one comes from the way that we _use_ [nat] values, by writing\n    functions to do things with them, proving things about them, and\n    so on.  Your definition of [bin] should be correspondingly simple;\n    it is the functions you will write next that will give it\n    mathematical meaning.)\n\n    (b) Next, write an increment function [incr] for binary numbers,\n        and a function [bin_to_nat] to convert binary numbers to unary numbers.\n\n    (c) Write five unit tests [test_bin_incr1], [test_bin_incr2], etc.\n        for your increment and binary-to-unary functions. Notice that\n        incrementing a binary number and then converting it to unary\n        should yield the same result as first converting it to unary and\n        then incrementing.\n*)\n\n(* FILL IN HERE *)\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] chapter.\n\n    Each notation symbol is also associated with a _notation scope_.\n    Coq tries to guess what scope you mean from context, so when you\n    write [S(O*O)] it guesses [nat_scope], but when you write the\n    cartesian product (tuple) type [bool*bool] it guesses\n    [type_scope].  Occasionally, you may have to help it out with\n    percent-notation by writing [(x*y)%nat], and sometimes in Coq's\n    feedback to you it will use [%nat] to indicate what scope a\n    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(** ** 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(** $Date: 2016-01-13 14:17:28 -0500 (Wed, 13 Jan 2016) $ *)\n", "meta": {"author": "lingxiao", "repo": "CIS500", "sha": "5b6e3a9cfe1ecaeaa9112b350022f3ca84924d4a", "save_path": "github-repos/coq/lingxiao-CIS500", "path": "github-repos/coq/lingxiao-CIS500/CIS500-5b6e3a9cfe1ecaeaa9112b350022f3ca84924d4a/hw2/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.8311430520409024, "lm_q1q2_score": 0.6548835304669576}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.Lists.List.\n\nSection TopSection.\n\n  Fixpoint app_all A (ls : list (list A)) :=\n    match ls with\n      | nil => nil\n      | x :: xs => x ++ app_all xs\n    end.\n\n  Definition Disjoint A (ls1 ls2 : list A) := forall e : A, ~ (In e ls1 /\\ In e ls2).\n\n  Definition IsInjection A B (f : A -> B) := forall x y, x <> y -> f x <> f y.\n\n  Definition Injective A B (f : A -> B) := forall x1 x2, f x1 = f x2 -> x1 = x2.\n\n  Lemma Injective_IsInjection A B (f : A -> B) : Injective f -> IsInjection f.\n  Proof.\n    unfold Injective, IsInjection in *; intuition.\n  Qed.\n\n  Variable t : Type.\n  Variable B : Type.\n\n  Implicit Types ls : list t.\n  Implicit Types f : t -> B.\n  Implicit Types x y e a : t.\n\n  Lemma map_app_all : forall f lsls, map f (app_all lsls) = app_all (map (fun ls => map f ls) lsls).\n    induction lsls; simpl; intros; eauto.\n    rewrite map_app; f_equal; eauto.\n  Qed.\n\n  Require Import Coq.Bool.Sumbool.\n  Require Import Platform.Cito.GeneralTactics.\n\n  Lemma find_spec : forall (f : t -> bool) ls a, find f ls = Some a -> f a = true /\\ In a ls.\n    induction ls; simpl; intuition; try discriminate;\n    (destruct (sumbool_of_bool (f a));\n     [rewrite e in H; injection H; intros; subst; eauto |\n      rewrite e in H; eapply IHls in H; openhyp; eauto]).\n  Qed.\n\n  Lemma find_spec_None : forall (f : t -> bool) ls, List.find f ls = None -> ~ exists a, List.In a ls /\\ f a = true.\n    induction ls; simpl; intuition.\n    openhyp; intuition.\n    openhyp.\n    subst.\n    rewrite H1 in H.\n    intuition.\n    eapply IHls.\n    discriminate.\n    discriminate.\n    destruct (f a); intuition.\n    discriminate.\n    eapply H2.\n    eexists; split; eauto.\n  Qed.\n\n  Lemma In_app_all_intro : forall lsls ls e, In e ls -> In ls lsls -> In e (app_all lsls).\n    induction lsls; simpl; intros.\n    eauto.\n    openhyp.\n    subst.\n    eapply in_or_app.\n    eauto.\n    eapply in_or_app.\n    right.\n    eauto.\n  Qed.\n\n  Lemma In_app_all_elim : forall lsls x, In x (app_all lsls) -> exists ls, In x ls /\\ In ls lsls.\n    induction lsls; simpl; intros.\n    intuition.\n    eapply in_app_or in H.\n    openhyp.\n    eexists.\n    eauto.\n    eapply IHlsls in H.\n    openhyp.\n    eexists; eauto.\n  Qed.\n\n  Lemma Disjoint_symm : forall ls1 ls2, Disjoint ls1 ls2 -> Disjoint ls2 ls1.\n    unfold Disjoint; intros; firstorder.\n  Qed.\n\n  Lemma Disjoint_incl : forall ls1 ls2 ls1' ls2', Disjoint ls1 ls2 -> incl ls1' ls1 -> incl ls2' ls2 -> Disjoint ls1' ls2'.\n    unfold Disjoint, incl; intros; firstorder.\n  Qed.\n\n  Lemma incl_map : forall f ls1 ls2, incl ls1 ls2 -> incl (map f ls1) (map f ls2).\n    unfold incl.\n    intros.\n    eapply in_map_iff in H0.\n    openhyp.\n    subst.\n    eapply H in H1.\n    eapply in_map_iff.\n    eexists.\n    eauto.\n  Qed.\n\n  Lemma Disjoint_map : forall f ls1 ls2, Disjoint (map f ls1) (map f ls2) -> Disjoint ls1 ls2.\n    unfold Disjoint; intros.\n    intuition.\n    eapply H.\n    split; eapply in_map; eauto.\n  Qed.\n\n  Lemma Injection_NoDup : forall f ls, IsInjection f -> NoDup ls -> NoDup (map f ls).\n    unfold IsInjection.\n    induction ls; simpl; intros.\n    econstructor.\n    inversion H0; subst.\n    econstructor.\n    intuition.\n    contradict H3.\n    eapply in_map_iff in H1.\n    openhyp.\n    eapply H in H1.\n    intuition.\n    intros.\n    subst.\n    inversion H0; subst.\n    contradiction.\n    eapply IHls.\n    eauto.\n    eauto.\n  Qed.\n\n  Lemma NoDup_app : forall ls1 ls2, NoDup ls1 -> NoDup ls2 -> Disjoint ls1 ls2 -> NoDup (ls1 ++ ls2).\n    unfold Disjoint.\n    induction ls1; simpl; intros.\n    eauto.\n    econstructor.\n    intuition.\n    eapply in_app_or in H2.\n    openhyp.\n    inversion H; subst.\n    contradiction.\n    eapply H1.\n    eauto.\n    eapply IHls1.\n    inversion H; subst.\n    eauto.\n    eauto.\n    intros.\n    firstorder.\n  Qed.\n\nEnd TopSection.\n\nRequire Import Coq.Bool.Bool.\n\nLocal Open Scope bool_scope.\n\nFixpoint forall2 A B (pred : A -> B -> bool) ls1 ls2 :=\n  match ls1, ls2 with\n    | a :: ls1', b :: ls2' => pred a b && forall2 pred ls1' ls2'\n    | nil, nil => true\n    | _, _ => false\n  end.\n\nLemma forall2_sound A B pred (P : A -> B -> Prop) : (forall a b, pred a b = true -> P a b) -> forall ls1 ls2, forall2 pred ls1 ls2 = true -> List.Forall2 P ls1 ls2.\nProof.\n  intros Hs.\n  induction ls1; destruct ls2; simpl; try solve [intros; try discriminate; intuition].\n  intros Hp; eapply andb_true_iff in Hp.\n  openhyp; econstructor; eauto.\nQed.", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/Cito/ListFacts1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.654872078517516}}
{"text": "Require Import ExtLib.Data.Fin.\n\nSet Implicit Arguments.\nSet Strict Implicit.\nSet Asymmetric Patterns.\n\nFixpoint vector (T : Type) (n : nat) : Type :=\n  match n with\n    | 0 => unit\n    | S n => prod T (vector T n)\n  end.\n\nFixpoint get {T} {n : nat} (f : fin n) : vector T n -> T :=\n  match f in fin n return vector T n -> T with\n    | F0 n => fun v : T * vector T n => fst v\n    | FS n f => fun v : T * vector T n => get f (snd v)\n  end.\n\nFixpoint put {T} {n : nat} (f : fin n) (t : T) : vector T n -> vector T n :=\n  match f in fin n return vector T n -> vector T n with\n    | F0 _ => fun v => (t, snd v)\n    | FS _ f => fun v => (fst v, put f t (snd v))\n  end.\n\nTheorem get_put_eq : forall {T n} (v : vector T n) (f : fin n) val,\n  get f (put f val v) = val.\nProof.\n  induction n.\n  { inversion f. }\n  { remember (S n). destruct f.\n    inversion Heqn0; subst; intros; reflexivity.\n    inversion Heqn0; subst; simpl; auto. }\nQed.\n\nTheorem get_put_neq : forall {T n} (v : vector T n) (f f' : fin n) val,\n  f <> f' ->\n  get f (put f' val v) = get f v.\nProof.\n  induction n.\n  { inversion f. }\n  { remember (S n); destruct f.\n    { inversion Heqn0; clear Heqn0; subst; intros.\n      destruct (fin_case f'); try congruence.\n      destruct H0; subst. auto. }\n    { inversion Heqn0; clear Heqn0; subst; intros.\n      destruct (fin_case f').\n      subst; auto.\n      destruct H0; subst. simpl.\n      eapply IHn. congruence. } }\nQed.\n\nDefinition vector_tl {T : Type} {n : nat} (v : vector T (S n)) : vector T n :=\n  snd v.\n\nDefinition vector_hd {T : Type} {n : nat} (v : vector T (S n)) : T :=\n  fst v.\n", "meta": {"author": "coq-community", "repo": "coq-ext-lib", "sha": "4811a83db9ccd81f4dcbf77eeff0484dfb21a48b", "save_path": "github-repos/coq/coq-community-coq-ext-lib", "path": "github-repos/coq/coq-community-coq-ext-lib/coq-ext-lib-4811a83db9ccd81f4dcbf77eeff0484dfb21a48b/theories/Data/Tuple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.654872076620806}}
{"text": "Require Export Lists.\n\n(** Insertion sort : algorithm.\n    Here we define the implementation of insertion sort\n    we'll be using. *)\n\n(** Insert an element in its place in a sorted list.\n   This is the main subroutine for insertion sort. *)\nFixpoint insert (v : nat) (l : natlist) : natlist :=\n  match l with\n  (* keep in mind that we're assuming l is sorted for this function\n     to make sense *)\n  | [] => [v]\n  | h :: t => match ble_nat v h with\n              | true => v :: h :: t\n              | false => h :: (insert v t)\n              end\n  end.\n\n(** This is the insertion sort algorithm: sort the tail\n    recursively and insert the head. *)\nFixpoint insertion_sort (l : natlist) : natlist :=\n  match l with\n  | [] => []\n  | h :: t => insert h (insertion_sort t)\n  end.\n\n", "meta": {"author": "mfount", "repo": "chicken", "sha": "83bb022522499272b4c246432188cfd5cce89c64", "save_path": "github-repos/coq/mfount-chicken", "path": "github-repos/coq/mfount-chicken/chicken-83bb022522499272b4c246432188cfd5cce89c64/coq/InsertionSortAlgorithm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.654872071142485}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Psatz.\nRequire Import SetsClass.SetsClass.\nRequire Import PV.Syntax.\nImport Lang_While.\nRequire Import PV.PracticalDenotations.\nImport DntSem_While.\nLocal Open Scope Z.\nLocal Open Scope sets.\nLocal Open Scope string.\nArguments Rels.concat: simpl never.\n\n(** 习题：*)\n\n(** 请证明以下两条关于_[Rels.test]_的性质。*)\n\nLemma Rels_test_empty: forall X: state -> Prop,\n  X == ∅ ->\n  Rels.test X == ∅.\nProof.\n  unfold_RELS_tac.\n  intros.\n  sets_unfold in H.\n  split.\n  - intro.\n    destruct H0.\n    rewrite <- (H a).\n    apply H0.\n  - tauto.\nQed.\n\nLemma Rels_test_full: forall X: state -> Prop,\n  X == Sets.full ->\n  Rels.test X == Rels.id.\nProof.\n  unfold_RELS_tac.\n  intros.\n  sets_unfold in H.\n  split; intro.\n  - destruct H0.\n    apply H1.\n  - split.\n    + apply H.\n      tauto.\n    + tauto.\nQed.\n\n\n(** 习题：*)\n\n(** 请证明：如果循环条件恒为真且循环体的行为不改变程序状态，循环是不会终止的。 *)\n\nLemma inf_loop_nrm: forall e c n,\n  test_true (eval_expr e) == Rels.id ->\n  test_false (eval_expr e) == ∅ ->\n  (eval_com c).(nrm) == Rels.id ->\n  iter_nrm_lt_n (eval_expr e) (eval_com c) n == ∅.\nProof.\n  intros.\n  induction n; try reflexivity.\n  simpl.\n  rewrite H, H0, H1, IHn.\n  rewrite ! Rels_concat_id_l.\n  rewrite Sets_union_empty.\n  reflexivity.\nQed.\n\n(** 习题：*)\n\n(** 请证明：如果循环条件恒为真且循环体的行为不改变程序状态，循环是不会运行出错的。 *)\n\nLemma inf_loop_err: forall e c n,\n  test_true (eval_expr e) == Rels.id ->\n  (eval_expr e).(err) == ∅ ->\n  (eval_com c).(nrm) == Rels.id ->\n  (eval_com c).(err) == ∅ ->\n  iter_err_lt_n (eval_expr e) (eval_com c) n == ∅.\nProof.\n  intros.\n  revert n.\n  induction n; try reflexivity.\n  simpl.\n  rewrite H, H0, H1, H2, IHn.\n  rewrite ! Rels_concat_id_l.\n  rewrite ! Sets_union_empty.\n  reflexivity.\nQed.\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/Assignment0302.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.6547733846734846}}
{"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 => saturday\n  | saturday => sunday\n  | sunday => monday\n  end.\n\nCompute ( next_weekday friday ).\n\nExample test_next_weekday:\n  (next_weekday ( next_weekday saturday)) = tuesday.\n\nProof. simpl. reflexivity. Qed.", "meta": {"author": "Garsojamec", "repo": "coq_software_foundations", "sha": "a35f476c1cda12b5427a3eae5b749fee1a769883", "save_path": "github-repos/coq/Garsojamec-coq_software_foundations", "path": "github-repos/coq/Garsojamec-coq_software_foundations/coq_software_foundations-a35f476c1cda12b5427a3eae5b749fee1a769883/vol1/1st_chapter/days_of_the_week.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.6547733810679743}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import Sorting.Permutation.\n\n(**\n  Lightly adapted from Coq stdlib mergesort to not be a functor.\n*)\n\nSection Sorting.\n  Variable t : Type.\n  Variable le : t -> t -> bool.\n\n  Variable le_reflexive :\n    forall x, le x x = true.\n\n  Variable le_transitive :\n    forall x y z,\n      le x y = true ->\n      le y z = true ->\n      le x z = true.\n\n  Variable le_total :\n    forall x y,\n      le x y = true \\/ le y x = true.\n\n  Inductive sorted : list t -> Prop :=\n  | SortedNil :\n      sorted []\n  | SortedSingleton :\n      forall x, sorted [x]\n  | SortedCons :\n      forall x y l,\n        sorted (y :: l) ->\n        le x y = true ->\n        sorted (x :: y :: l).\n\n  (* from Coq stdlib mergesort implementation *)\n  Fixpoint merge l1 l2 :=\n    let fix merge_aux l2 :=\n        match l1, l2 with\n        | [], _ => l2\n        | _, [] => l1\n        | a1::l1', a2::l2' =>\n          if le a1 a2\n          then a1 :: merge l1' l2\n          else a2 :: merge_aux l2'\n        end\n    in merge_aux l2.\n\n  Definition tstack : Type := list (option (list t)).\n\n  (* from Coq stdlib mergesort implementation *)\n  Fixpoint merge_list_to_stack (stack : tstack) (l : list t) : tstack :=\n    match stack with\n    | [] => [Some l]\n    | None :: stack' => Some l :: stack'\n    | Some l' :: stack' => None :: merge_list_to_stack stack' (merge l' l)\n    end.\n\n  (* from Coq stdlib mergesort implementation *)\n  Fixpoint merge_stack (stack : tstack) : list t :=\n    match stack with\n    | [] => []\n    | None :: stack' => merge_stack stack'\n    | Some l :: stack' => merge l (merge_stack stack')\n    end.\n\n  (* from Coq stdlib mergesort implementation *)\n  Fixpoint iter_merge (stack : tstack) (l : list t) : list t :=\n    match l with\n    | [] => merge_stack stack\n    | a::l' => iter_merge (merge_list_to_stack stack [a]) l'\n    end.\n\n  (* from Coq stdlib mergesort implementation *)\n  Definition sort : list t -> list t :=\n    iter_merge [].\n\n  (* all proofs below from Coq stdlib mergesort implementation *)\n\n  Local Ltac invert H := inversion H; subst; clear H.\n\n  Fixpoint flatten_stack (stack : list (option (list t))) :=\n    match stack with\n    | [] => []\n    | None :: stack' => flatten_stack stack'\n    | Some l :: stack' => l ++ flatten_stack stack'\n    end.\n\n  Theorem Permuted_merge :\n   forall l1 l2, Permutation (l1++l2) (merge l1 l2).\n  Proof.\n    induction l1; simpl merge; intro.\n    - assert (forall l, (fix merge_aux (l0 : list t) : list t := l0) l = l)\n      as -> by (destruct l; trivial). (* Technical lemma *)\n      apply Permutation_refl.\n    - induction l2.\n      rewrite app_nil_r. apply Permutation_refl.\n      destruct (le a a0).\n        + constructor; apply IHl1.\n        + apply Permutation_sym, Permutation_cons_app, Permutation_sym, IHl2.\n  Qed.\n\n  Theorem Permuted_merge_stack : forall stack,\n    Permutation (flatten_stack stack) (merge_stack stack).\n  Proof.\n    induction stack as [|[]]; simpl.\n    -  trivial.\n    -  transitivity (l ++ merge_stack stack).\n        + apply Permutation_app_head; trivial.\n        + apply Permuted_merge.\n    - assumption.\n  Qed.\n\n  Theorem Permuted_merge_list_to_stack :\n    forall stack l,\n      Permutation (l ++ flatten_stack stack)\n                  (flatten_stack (merge_list_to_stack stack l)).\n  Proof.\n    induction stack as [|[]]; simpl; intros.\n    - reflexivity.\n    - rewrite app_assoc.\n      etransitivity.\n      + apply Permutation_app_tail.\n        etransitivity.\n        * apply Permutation_app_comm.\n        * apply Permuted_merge.\n      + apply IHstack.\n    - reflexivity.\n  Qed.\n\n  Theorem Permuted_iter_merge : forall l stack,\n    Permutation (flatten_stack stack ++ l) (iter_merge stack l).\n  Proof.\n    induction l; simpl; intros.\n    - rewrite app_nil_r. apply Permuted_merge_stack.\n    - change (a::l) with ([a]++l).\n      rewrite app_assoc.\n      etransitivity.\n      +  apply Permutation_app_tail.\n         etransitivity.\n         apply Permutation_app_comm.\n         apply Permuted_merge_list_to_stack.\n      + apply IHl.\n  Qed.\n\n  Theorem sort_permutes :\n    forall l l',\n      l' = sort l ->\n      Permutation l l'.\n  Proof.\n    intros; subst; apply (Permuted_iter_merge l []).\n  Qed.\n\n  Fixpoint sorted_stack stack :=\n  match stack with\n  | [] => True\n  | None :: stack' => sorted_stack stack'\n  | Some l :: stack' => sorted l /\\ sorted_stack stack'\n  end.\n\n  Theorem sorted_merge : forall l1 l2,\n      sorted l1 -> sorted l2 -> sorted (merge l1 l2).\n  Proof.\n    induction l1; induction l2; intros; simpl; auto.\n    destruct (le a a0) eqn:Heq1.\n    - invert H.\n      simpl. constructor; trivial; rewrite Heq1; constructor.\n      assert (sorted (merge (y::l) (a0::l2))) by (apply IHl1; auto).\n      clear H0 H3 IHl1; simpl in *.\n      destruct (le y a0); constructor; auto || rewrite Heq1; constructor.\n    - assert (le a0 a = true).\n        (destruct (le_total a0 a)); auto.\n        rewrite H1 in Heq1.\n        congruence.\n      invert H0.\n      constructor; trivial.\n      assert (sorted (merge (a::l1) (y::l))) by auto using IHl1.\n      clear IHl2; simpl in *.\n      destruct (le a y); constructor; auto.\n  Qed.\n\n  Theorem sorted_merge_stack : forall stack,\n      sorted_stack stack -> sorted (merge_stack stack).\n  Proof.\n    induction stack as [|[|]]; simpl; intros.\n    constructor; auto.\n    apply sorted_merge; tauto.\n    auto.\n  Qed.\n\n  Theorem sorted_merge_list_to_stack : forall stack l,\n      sorted_stack stack -> sorted l -> sorted_stack (merge_list_to_stack stack l).\n  Proof.\n  induction stack as [|[|]]; intros; simpl.\n    auto.\n    apply IHstack. destruct H as (_,H1). fold sorted_stack in H1. auto.\n      apply sorted_merge; auto; destruct H; auto.\n      auto.\n  Qed.\n\n  Theorem sorted_iter_merge : forall stack l,\n      sorted_stack stack -> sorted (iter_merge stack l).\n  Proof.\n    intros stack l H; induction l in stack, H |- *; simpl.\n    auto using sorted_merge_stack.\n    assert (sorted [a]) by constructor.\n    auto using sorted_merge_list_to_stack.\n  Qed.\n\n  Theorem sorted_sort : forall l, sorted (sort l).\n  Proof.\n    intro; apply sorted_iter_merge. constructor.\n  Qed.\nEnd Sorting.\n", "meta": {"author": "DistributedComponents", "repo": "verdi-chord", "sha": "762fe660c648d7f2a009d2beaa5cf3b8ea4ac593", "save_path": "github-repos/coq/DistributedComponents-verdi-chord", "path": "github-repos/coq/DistributedComponents-verdi-chord/verdi-chord-762fe660c648d7f2a009d2beaa5cf3b8ea4ac593/lib/Sorting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324938410783, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6547733750714329}}
{"text": "From Coq Require Import Arith Lia ZArith List.\nFrom Coq Require Import Sorting.Permutation.\nFrom StructTact Require Import StructTactics ListTactics.\nImport ListNotations.\n\nSet Implicit Arguments.\n\nNotation member := (in_dec eq_nat_dec).\n\nLemma seq_range :\n  forall n a x,\n    In x (seq a n) ->\n    a <= x < a + n.\nProof.\n  induction n; intros; simpl in *.\n  - intuition auto.\n  - break_or_hyp; try find_apply_hyp_hyp; intuition lia.\nQed.\n\nLemma plus_gt_0 :\n  forall a b,\n    a + b > 0 ->\n    a > 0 \\/ b > 0.\nProof.\n  intros.\n  destruct (eq_nat_dec a 0); intuition lia.\nQed.\n\nSection list_util.\n  Variables A B C : Type.\n  Hypothesis A_eq_dec : forall x y : A, {x = y} + {x <> y}.\n\n  Lemma list_neq_cons :\n    forall (l : list A) x,\n      x :: l <> l.\n  Proof using.\n    intros l x H.\n    symmetry in H.\n    induction l;\n      now inversion H.\n  Qed.\n\n  Lemma remove_preserve :\n    forall (x y : A) xs,\n      x <> y ->\n      In y xs ->\n      In y (remove A_eq_dec x xs).\n  Proof using.\n    induction xs; intros.\n    - intuition auto.\n    - simpl in *.\n      concludes.\n      break_or_hyp; break_if; subst; try congruence; intuition (auto with datatypes).\n  Qed.\n\n  Lemma in_remove :\n    forall (x y : A) xs,\n      In y (remove A_eq_dec x xs) ->\n      In y xs.\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - simpl in *. break_if; simpl in *; intuition auto.\n  Qed.\n\n  Lemma remove_partition :\n    forall xs (p : A) ys,\n      remove A_eq_dec p (xs ++ p :: ys) = remove A_eq_dec p (xs ++ ys).\n  Proof using.\n    induction xs; intros; simpl; break_if; congruence.\n  Qed.\n\n  Lemma remove_not_in :\n    forall (x : A) xs,\n      ~ In x xs ->\n      remove A_eq_dec x xs = xs.\n  Proof using.\n    intros. induction xs; simpl in *; try break_if; intuition congruence.\n  Qed.\n\n  Lemma remove_app_comm :\n    forall a xs ys,\n      remove A_eq_dec a (xs ++ ys) = remove A_eq_dec a xs ++ remove A_eq_dec a ys.\n  Proof.\n    intros.\n    generalize dependent ys.\n    induction xs; intros.\n    - tauto.\n    - destruct (A_eq_dec a0 a);\n      simpl;\n      break_if;\n      try rewrite <- app_comm_cons;\n      rewrite IHxs; \n      congruence.\n  Qed.\n\n  Lemma filter_app : forall (f : A -> bool) xs ys,\n      filter f (xs ++ ys) = filter f xs ++ filter f ys.\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - simpl. rewrite IHxs. break_if; auto.\n  Qed.\n\n  Lemma filter_fun_ext_eq : forall f g xs,\n      (forall a : A, In a xs -> f a = g a) ->\n      filter f xs = filter g xs.\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - simpl. rewrite H by intuition (auto with datatypes). \n      rewrite IHxs by intuition (auto with datatypes). auto.\n  Qed.\n\n  Lemma not_in_filter_false :\n    forall (f : A -> bool) l x,\n      In x l ->\n      ~ In x (filter f l) ->\n      f x = false.\n  Proof.\n    intros.\n    destruct (f x) eqn:?H; [|tauto].\n    unfold not in *; find_false.\n    now eapply filter_In.\n  Qed.\n\n  Lemma filter_length_bound :\n    forall f (l : list A),\n      length (filter f l) <= length l.\n  Proof.\n    induction l.\n    - easy.\n    - simpl.\n      break_if; simpl; lia.\n  Qed.\n\n  Lemma NoDup_map_injective : forall (f : A -> B) xs,\n      (forall x y, In x xs -> In y xs ->\n              f x = f y -> x = y) ->\n      NoDup xs -> NoDup (map f xs).\n  Proof using.\n    induction xs; intros.\n    - constructor.\n    - simpl. invc_NoDup. constructor.\n      + intro. do_in_map.\n        assert (x = a) by intuition (auto with datatypes).\n        congruence.\n      + intuition (auto with datatypes).\n  Qed.\n\n  Lemma NoDup_disjoint_append :\n    forall (l : list A) l',\n      NoDup l ->\n      NoDup l' ->\n      (forall a, In a l -> ~ In a l') ->\n      NoDup (l ++ l').\n  Proof using.\n    induction l; intros.\n    - auto.\n    - simpl. invc_NoDup. constructor.\n      + intro. do_in_app. intuition eauto with datatypes.\n      + intuition eauto with datatypes.\n  Qed.\n\n  Lemma NoDup_map_partition :\n    forall (f : A -> B) xs l y zs xs' y' zs',\n      NoDup (map f l) ->\n      l = xs ++ y :: zs ->\n      l = xs' ++ y' :: zs' ->\n      f y = f y' ->\n      xs = xs'.\n  Proof using.\n    induction xs; simpl; intros; destruct xs'.\n    - auto.\n    - subst. simpl in *. find_inversion.\n      invc H. exfalso. rewrite map_app in *. simpl in *.\n      repeat find_rewrite. intuition (auto with datatypes).\n    - subst. simpl in *. find_inversion.\n      invc H. exfalso. rewrite map_app in *. simpl in *.\n      repeat find_rewrite. intuition (auto with datatypes).\n    - subst. simpl in *. find_injection. intros. subst.\n      f_equal. eapply IHxs; eauto. solve_by_inversion.\n  Qed.\n\n  Lemma filter_NoDup :\n    forall p (l : list A),\n      NoDup l ->\n      NoDup (filter p l).\n  Proof using.\n    induction l; intros.\n    - auto.\n    - invc_NoDup. simpl. break_if; auto.\n      constructor; auto.\n      intro. apply filter_In in H. intuition auto.\n  Qed.\n\n  Lemma NoDup_map_filter :\n    forall (f : A -> B) g l,\n      NoDup (map f l) ->\n      NoDup (map f (filter g l)).\n  Proof using.\n    intros. induction l; simpl in *.\n    - constructor.\n    - invc_NoDup. concludes.\n      break_if; simpl in *; auto.\n      constructor; auto.\n      intro. do_in_map.\n      find_apply_lem_hyp filter_In. intuition auto.\n      match goal with | H : _ -> False |- False => apply H end.\n      apply in_map_iff. eauto.\n  Qed.\n\n  Lemma filter_true_id : forall (f : A -> bool) xs,\n      (forall x, In x xs -> f x = true) ->\n      filter f xs = xs.\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - simpl. now rewrite H, IHxs by intuition (auto with datatypes).\n  Qed.\n\n  Lemma map_of_map : forall (f : A -> B) (g : B -> C) xs,\n      map g (map f xs) = map (fun x => g (f x)) xs.\n  Proof using.\n    induction xs; simpl; auto using f_equal2.\n  Qed.\n\n  Lemma filter_except_one : forall (f g : A -> bool) x xs,\n      (forall y, In y xs ->\n            x <> y ->\n            f y = g y) ->\n      g x = false ->\n      filter f (remove A_eq_dec x xs) = filter g xs.\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - simpl.\n      break_if.\n      + subst. repeat find_rewrite. eauto with datatypes.\n      + simpl. rewrite H by auto with datatypes.\n        break_if; eauto using f_equal2 with datatypes.\n  Qed.\n\n  Lemma flat_map_nil : forall (f : A -> list B) l,\n      flat_map f l = [] ->\n      l = [] \\/ (forall x, In x l -> f x = []).\n  Proof using.\n    induction l; intros.\n    - intuition auto.\n    - right. simpl in *.\n      apply app_eq_nil in H.\n      intros; break_and; break_or_hyp; concludes; break_or_hyp; auto.\n      contradiction.\n  Qed.\n\n  Theorem NoDup_Permutation_NoDup :\n    forall (l l' : list A),\n      NoDup l ->\n      Permutation l l' ->\n      NoDup l'.\n  Proof using.\n    intros l l' Hnd Hp.\n    induction Hp; auto; invc_NoDup; constructor;\n      eauto using Permutation_in, Permutation_sym;\n      simpl in *; intuition (auto with struct_util).\n  Qed.\n\n  Theorem NoDup_append :\n    forall l (a : A),\n      NoDup (l ++ [a]) <-> NoDup (a :: l).\n  Proof using. \n    intuition eauto using NoDup_Permutation_NoDup, Permutation_sym, Permutation_cons_append.\n  Qed.\n\n  Lemma NoDup_map_elim :\n    forall (f : A -> B) xs x y,\n      f x = f y ->\n      NoDup (map f xs) ->\n      In x xs ->\n      In y xs ->\n      x = y.\n  Proof using.\n    induction xs; intros; simpl in *.\n    - intuition auto.\n    - invc_NoDup. intuition auto; subst; auto; exfalso.\n      + repeat find_rewrite. auto using in_map.\n      + repeat find_reverse_rewrite. auto using in_map.\n  Qed.\n\n  Lemma remove_length_not_in : forall (x : A) xs,\n      ~ In x xs ->\n      length (remove A_eq_dec x xs) = length xs.\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - simpl in *. intuition auto.\n      break_if; subst; simpl; intuition auto.\n  Qed.\n\n  Lemma remove_length_in : forall (x : A) xs,\n      In x xs ->\n      NoDup xs ->\n      S (length (remove A_eq_dec x xs)) = length xs.\n  Proof using.\n    induction xs; intros; simpl in *; intuition; invc_NoDup;\n      break_if; subst; intuition (simpl; try congruence).\n    now rewrite remove_length_not_in.\n  Qed.\n\n  Lemma subset_size_eq :\n    forall xs,\n      NoDup xs ->\n      forall ys,\n        NoDup ys ->\n        (forall x : A, In x xs -> In x ys) ->\n        length xs = length ys ->\n        (forall x, In x ys -> In x xs).\n  Proof using.\n    induction xs; intros.\n    - destruct ys; simpl in *; congruence.\n    - invc_NoDup. concludes.\n      assert (In a ys) by eauto with datatypes.\n      find_apply_lem_hyp in_split.\n      break_exists_name l1.\n      break_exists_name l2.\n      subst.\n      specialize (IHxs (l1 ++ l2)).\n      conclude_using ltac:(eauto using NoDup_remove_1).\n      forward IHxs.\n      intros x' Hx'.\n      assert (In x' (l1 ++ a :: l2)) by eauto with datatypes.\n      do_in_app. simpl in *. intuition auto with datatypes. subst. congruence.\n      concludes.\n      forward IHxs.\n      rewrite app_length in *. simpl in *. lia.\n      concludes.\n      do_in_app. simpl in *. intuition auto with datatypes.\n  Qed.\n\n  Lemma remove_NoDup :\n    forall (x : A) xs,\n      NoDup xs ->\n      NoDup (remove A_eq_dec x xs).\n  Proof using.\n    induction xs; intros.\n    - auto with struct_util.\n    - invc_NoDup. simpl. break_if; eauto 6 using in_remove with struct_util.\n  Qed.\n\n  Lemma remove_length_ge : forall (x : A) xs,\n      NoDup xs ->\n      length (remove A_eq_dec x xs) >= length xs - 1.\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - invc_NoDup. simpl. break_if.\n      + rewrite Nat.sub_0_r.\n        subst.\n        rewrite remove_length_not_in; auto.\n      + simpl. concludes. lia.\n  Qed.\n\n  Lemma remove_length_le :\n    forall (x : A) xs eq_dec,\n      length xs >= length (remove eq_dec x xs).\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - simpl in *.\n      specialize (IHxs eq_dec).\n      break_if; subst; simpl; lia.\n  Qed.\n\n  Lemma remove_length_lt :\n    forall (x : A) xs eq_dec,\n      In x xs ->\n      length xs > length (remove eq_dec x xs).\n  Proof using.\n    induction xs; intros; simpl in *; [contradiction|]; break_or_hyp.\n    - subst.\n      break_if; try congruence.\n      pose proof remove_length_le x xs eq_dec.\n      lia.\n    - specialize (IHxs ltac:(eauto) ltac:(eauto)).\n      break_if; subst; simpl; lia.\n  Qed.\n\n  Lemma subset_length :\n    forall xs ys,\n      NoDup xs ->\n      (forall x : A, In x xs -> In x ys) ->\n      length ys >= length xs.\n  Proof using A_eq_dec.\n    induction xs; intros.\n    - simpl. lia.\n    - specialize (IHxs (remove A_eq_dec a ys)).\n      invc_NoDup.\n      concludes.\n      forward IHxs.\n      intros.\n      apply remove_preserve;\n       [congruence|intuition (auto with datatypes)].\n      concludes.\n      pose proof remove_length_lt a ys A_eq_dec.\n      assert (In a ys) by auto with datatypes.\n      concludes.\n      simpl. lia.\n  Qed.\n\n  Lemma app_cons_singleton_inv :\n    forall xs (y : A) zs w,\n      xs ++ y :: zs = [w] ->\n      xs = [] /\\ y = w /\\ zs = [].\n  Proof using.\n    intros.\n    destruct xs.\n    - solve_by_inversion.\n    - destruct xs; solve_by_inversion.\n  Qed.\n\n  Lemma app_cons_in :\n    forall (l : list A) xs a ys,\n      l = xs ++ a :: ys ->\n      In a l.\n  Proof using.\n    intros. subst. auto with datatypes.\n  Qed.\n  Hint Resolve app_cons_in : struct_util.\n\n  Lemma app_cons_in_rest:\n    forall (l : list A) xs a b ys,\n      l = xs ++ a :: ys ->\n      In b (xs ++ ys) ->\n      In b l.\n  Proof using.\n    intros. subst.\n    do_in_app; intuition auto with datatypes.\n  Qed.\n  Hint Resolve app_cons_in_rest : struct_util.\n\n  Lemma in_rest_app_cons:\n    forall (l xs ys : list A) a b,\n      l = xs ++ a :: ys ->\n      In b l ->\n      a <> b ->\n      In b (xs ++ ys).\n  Proof using.\n    intros.\n    subst_max.\n    do_in_app.\n    break_or_hyp.\n    - auto with datatypes.\n    - find_apply_lem_hyp in_inv.\n      break_or_hyp; auto using in_or_app || congruence.\n  Qed.\n  Hint Resolve in_rest_app_cons : struct_util.\n\n  Lemma remove_filter_commute :\n    forall (l : list A) A_eq_dec f x,\n      remove A_eq_dec x (filter f l) = filter f (remove A_eq_dec x l).\n  Proof using.\n    induction l; intros; simpl in *; auto.\n    repeat (break_if; subst; simpl in *; try congruence).\n  Qed.\n\n  Lemma In_filter_In :\n    forall (f : A -> bool) x l l',\n      filter f l = l' ->\n      In x l' -> In x l.\n  Proof using.\n    intros. subst.\n    eapply filter_In; eauto.\n  Qed.\n\n  Lemma filter_partition :\n    forall (l1 : list A) f l2 x l1' l2',\n      NoDup (l1 ++ x :: l2) ->\n      filter f (l1 ++ x :: l2) = (l1' ++ x :: l2') ->\n      filter f l1 = l1' /\\ filter f l2 = l2'.\n  Proof using.\n    induction l1; intros; simpl in *; break_if; simpl in *; invc_NoDup.\n    - destruct l1'; simpl in *.\n      + solve_by_inversion.\n      + find_inversion. exfalso. eauto using In_filter_In with datatypes.\n    - exfalso. eauto using In_filter_In with datatypes.\n    - destruct l1'; simpl in *; break_and; find_inversion.\n      + exfalso. eauto with datatypes.\n      + find_apply_hyp_hyp. intuition auto using f_equal2.\n    - eauto.\n  Qed.\n\n  Lemma map_inverses :\n    forall (la : list A) (lb : list B)  (f : A -> B) g,\n      (forall a, g (f a) = a) ->\n      (forall b, f (g b) = b) ->\n      lb = map f la ->\n      la = map g lb.\n  Proof using.\n    destruct la; intros; simpl in *.\n    - subst. reflexivity.\n    - destruct lb; try congruence.\n      simpl in *. find_inversion.\n      find_higher_order_rewrite.\n      f_equal.\n      rewrite map_map.\n      erewrite map_ext; [symmetry; apply map_id|].\n      simpl in *. auto.\n  Qed.\n\n  Lemma In_notIn_implies_neq :\n    forall x y l,\n      In(A:=A) x l ->\n      ~ In(A:=A) y l ->\n      x <> y.\n  Proof using.\n    intuition congruence.\n  Qed.\n\n  Lemma In_cons_neq :\n    forall a x xs,\n      In(A:=A) a (x :: xs) ->\n      a <> x ->\n      In a xs.\n  Proof using.\n    simpl.\n    intuition congruence.\n  Qed.\n\n  Lemma NoDup_app3_not_in_1 :\n    forall (xs ys zs : list A) b,\n      NoDup (xs ++ ys ++ b :: zs) ->\n      In b xs ->\n      False.\n  Proof using.\n    intros.\n    rewrite <- app_ass in *.\n    find_apply_lem_hyp NoDup_remove.\n    rewrite app_ass in *.\n    intuition (auto with datatypes).\n  Qed.\n\n  Lemma NoDup_app3_not_in_2 :\n    forall (xs ys zs : list A) b,\n      NoDup (xs ++ ys ++ b :: zs) ->\n      In b ys ->\n      False.\n  Proof using.\n    intros.\n    rewrite <- app_ass in *.\n    find_apply_lem_hyp NoDup_remove_2.\n    rewrite app_ass in *.\n    auto 10 with datatypes.\n  Qed.\n\n  Lemma NoDup_app3_not_in_3 :\n    forall (xs ys zs : list A) b,\n      NoDup (xs ++ ys ++ b :: zs) ->\n      In b zs ->\n      False.\n  Proof using.\n    intros.\n    rewrite <- app_ass in *.\n    find_apply_lem_hyp NoDup_remove_2.\n    rewrite app_ass in *.\n    auto 10 with datatypes.\n  Qed.\n\n  Lemma In_cons_2_3 :\n    forall xs ys zs x y a,\n      In (A:=A) a (xs ++ ys ++ zs) ->\n      In a (xs ++ x :: ys ++ y :: zs).\n  Proof using.\n    intros.\n    repeat (do_in_app; intuition auto 10 with datatypes).\n  Qed.\n\n  Lemma In_cons_2_3_neq :\n    forall a x y xs ys zs,\n      In (A:=A) a (xs ++ x :: ys ++ y :: zs) ->\n      a <> x ->\n      a <> y ->\n      In a (xs ++ ys ++ zs).\n  Proof using.\n    intros.\n    repeat (do_in_app; simpl in *; intuition (auto with datatypes; try congruence)).\n  Qed.\n\n  Lemma in_middle_reduce :\n    forall a xs y zs,\n      In (A:=A) a (xs ++ y :: zs) ->\n      a <> y ->\n      In a (xs ++ zs).\n  Proof using.\n    intros.\n    do_in_app; simpl in *; intuition auto with datatypes. congruence.\n  Qed.\n\n  Lemma in_middle_insert :\n    forall a xs y zs,\n      In (A:=A) a (xs ++ zs) ->\n      In a (xs ++ y :: zs).\n  Proof using.\n    intros.\n    do_in_app; simpl in *; intuition auto with datatypes.\n  Qed.\n\n  Lemma NoDup_rev :\n    forall l,\n      NoDup (A:=A) l ->\n      NoDup (rev l).\n  Proof using.\n    induction l; intros; simpl.\n    - auto.\n    - apply NoDup_append.\n      invc_NoDup.\n      constructor; auto.\n      intuition.\n      find_apply_lem_hyp in_rev.\n      auto.\n  Qed.\n\n  Lemma NoDup_map_map :\n    forall (f : A -> B) (g : A -> C) xs,\n      (forall x y, In x xs -> In y xs -> f x = f y -> g x = g y) ->\n      NoDup (map g xs) ->\n      NoDup (map f xs).\n  Proof using.\n    induction xs; intros; simpl in *.\n    - constructor.\n    - invc_NoDup.\n      constructor; auto.\n      intro.\n      do_in_map.\n      find_apply_hyp_hyp.\n      find_reverse_rewrite.\n      auto using in_map.\n  Qed.\n\n  Lemma pigeon :\n    forall (l : list A) sub1 sub2,\n      (forall a, In a sub1 -> In a l) ->\n      (forall a, In a sub2 -> In a l) ->\n      NoDup l ->\n      NoDup sub1 ->\n      NoDup sub2 ->\n      length sub1 + length sub2 > length l ->\n      exists a, In a sub1 /\\ In a sub2.\n  Proof using A_eq_dec.\n    induction l.\n    intros.\n    + simpl in *. find_apply_lem_hyp plus_gt_0. intuition.\n      * destruct sub1; simpl in *; [lia|].\n        specialize (H a). intuition.\n      * destruct sub2; simpl in *; [lia|].\n        specialize (H0 a). intuition.\n    + intros. simpl in *.\n      destruct (in_dec A_eq_dec a sub1);\n        destruct (in_dec A_eq_dec a sub2); eauto;\n          specialize (IHl (remove A_eq_dec a sub1) (remove A_eq_dec a sub2));\n          cut (exists a0, In a0 (remove A_eq_dec a sub1) /\\ In a0 (remove A_eq_dec a sub2));\n          try solve [intros; break_exists;\n                     intuition eauto using in_remove];\n          apply IHl; try solve [\n                           intros; find_copy_apply_lem_hyp in_remove;\n                           find_apply_hyp_hyp; intuition; subst; exfalso; eapply remove_In; eauto];\n          eauto using remove_NoDup; try solve_by_inversion;\n            repeat match goal with\n                   | H : ~ In a ?sub |- _ =>\n                     assert (length (remove A_eq_dec a sub) = length sub)\n                       by eauto using remove_length_not_in; clear H\n                   | H : In a ?sub |- _ =>\n                     assert (length (remove A_eq_dec a sub) >= length sub - 1)\n                       by eauto using remove_length_ge; clear H\n                   end; lia.\n  Qed.\n\n  Lemma snoc_assoc :\n    forall (l : list A) x y,\n      l ++ [x; y] = (l ++ [x]) ++ [y].\n  Proof using.\n    induction l; intros; simpl; intuition.\n    auto using f_equal.\n  Qed.\n\n  Lemma cons_cons_app :\n    forall (x y : A),\n      [x; y] = [x] ++ [y].\n  Proof using.\n    auto.\n  Qed.\n\n  Lemma map_eq_inv :\n    forall (f : A -> B) l xs ys,\n      map f l = xs ++ ys ->\n      exists l1 l2,\n        l = l1 ++ l2 /\\\n        map f l1 = xs /\\\n        map f l2 = ys.\n  Proof using.\n    induction l; simpl; intros xs ys H.\n    - symmetry in H. apply app_eq_nil in H. break_and. subst.\n      exists [], []. auto.\n    - destruct xs; simpl in *.\n      + exists [], (a :: l). intuition.\n      + invc H. find_apply_hyp_hyp.\n        break_exists_name l1.\n        break_exists_name l2.\n        break_and.\n        exists (a :: l1), l2. subst.\n        intuition.\n  Qed.\n\n  Lemma map_partition :\n    forall p l (x : B) p' (f : A -> B),\n      map f l = (p ++ x :: p') ->\n      exists ap a ap',\n        l = ap ++ a :: ap' /\\\n        map f ap = p /\\\n        f a = x /\\\n        map f ap' = p'.\n  Proof using.\n    intros p l x p' f H_m.\n    pose proof map_eq_inv f _ _ _ H_m.\n    break_exists_name l1.\n    break_exists_name l2.\n    break_and.\n    find_rewrite.\n    destruct l2; simpl in *.\n    - match goal with H : [] = _ :: _ |- _ => contradict H end.\n      auto with datatypes.\n    - repeat find_rewrite.\n      find_inversion.\n      exists l1, a, l2. auto.\n  Qed.\n\n  Lemma map_eq_inv_eq :\n    forall (f : A -> B),\n      (forall a a', f a = f a' -> a = a') ->\n      forall l l', map f l = map f l' -> l = l'.\n  Proof using.\n    induction l; simpl; intros l' Heq; destruct l'; simpl in *; try congruence.\n    find_inversion. auto using f_equal2.\n  Qed.\n\n  Lemma map_fst_snd_id :\n    forall l, map (fun t : A * B => (fst t, snd t)) l = l.\n  Proof using.\n    intros.\n    rewrite <- map_id.\n    apply map_ext.\n    destruct a; auto.\n  Qed.\n\n  Lemma in_firstn : forall n (x : A) xs,\n      In x (firstn n xs) -> In x xs.\n  Proof using.\n    induction n; simpl; intuition; break_match; simpl in *; intuition.\n  Qed.\n\n  Lemma firstn_NoDup : forall n (xs : list A),\n    NoDup xs ->\n    NoDup (firstn n xs).\n  Proof using.\n    induction n; intros; simpl; destruct xs; auto with struct_util.\n    invc_NoDup.\n    eauto 6 using in_firstn with struct_util.\n  Qed.\n\n  Lemma NoDup_mid_not_in :\n    forall (a : A) (l l' : list A),\n    NoDup (l ++ a :: l') ->\n    ~ In a (l ++ l').\n  Proof using.\n    induction l; intros; simpl in *.\n    - invc_NoDup; auto.\n    - invc_NoDup.\n      intro.\n      break_or_hyp.\n      * match goal with H: ~ In _ _ |- _ => contradict H end.\n        apply in_or_app.\n        right; left. auto.\n      * match goal with H: In _ _ |- _ => contradict H end.\n        eauto.\n    Qed.\n\n  Lemma Permutation_split :\n    forall (ns ns' : list A) (n : A),\n      Permutation (n :: ns) ns' ->\n      exists ns0, exists ns1, ns' = ns0 ++ n :: ns1.\n  Proof using.\n    intros l l' a H_pm.\n    assert (In a (a :: l)); auto with datatypes.\n    assert (In a l'); eauto using Permutation_in.\n    find_apply_lem_hyp In_split; auto.\n  Qed.\n\n  Lemma NoDup_app_left :\n    forall (l l' : list A),\n      NoDup (l ++ l') -> NoDup l.\n  Proof using.\n    induction l; intros; simpl in *.\n    - apply NoDup_nil.\n    - invc_NoDup.\n      find_apply_hyp_hyp.\n      apply NoDup_cons; auto.\n      intro.\n      match goal with H: ~ In _ _ |- _ => contradict H end.\n      apply in_or_app.\n      left; auto.\n  Qed.\n\n  Lemma NoDup_app_right :\n    forall (l l' : list A),\n      NoDup (l ++ l') -> NoDup l'.\n  Proof using.\n    induction l; intros; simpl in *; auto.\n    invc_NoDup.\n    find_apply_hyp_hyp; auto.\n  Qed.\n\n  Lemma NoDup_in_not_in_right :\n    forall (l l' : list A) (a : A),\n      NoDup (l ++ l') -> In a l -> ~ In a l'.\n  Proof using.\n    induction l; intros; simpl in *; auto.\n    invc_NoDup.\n    break_or_hyp; eauto with datatypes.\n  Qed.\n\n  Lemma NoDup_in_not_in_left :\n    forall (l l' : list A) (a : A),\n    NoDup (l ++ l') -> In a l' -> ~ In a l.\n  Proof using.\n    intros.\n    induction l; simpl in *; auto.\n    invc_NoDup.\n    concludes.\n    intro.\n    break_or_hyp; auto with datatypes.\n  Qed.\n\n  Lemma count_occ_app :\n    forall l l' (a : A),\n      count_occ A_eq_dec (l ++ l') a = count_occ A_eq_dec l a + count_occ A_eq_dec l' a.\n  Proof using.\n    intros.\n    induction l; simpl in *; auto.\n    break_if; auto.\n    find_rewrite.\n    auto.\n  Qed.\n\n  Lemma Permutation_map_fst :\n    forall l l' : list (A * B),\n      Permutation l l' ->\n      Permutation (map fst l) (map fst l').\n  Proof using.\n    induction l; intros; simpl in *.\n    - find_apply_lem_hyp Permutation_nil.\n      find_rewrite.\n      auto.\n    - assert (In a l').\n        apply Permutation_in with (l := a :: l); auto with datatypes.\n      find_apply_lem_hyp in_split.\n      break_exists.\n      find_rewrite.\n      find_apply_lem_hyp Permutation_cons_app_inv.\n      find_apply_hyp_hyp.\n      find_rewrite.\n      rewrite map_app.\n      simpl.\n      apply Permutation_cons_app.\n      rewrite <- map_app.\n      auto.\n     Qed.\n\n  Lemma snd_eq_not_in_map :\n    forall (l : list (A * B)) n m,\n      (forall nm, In nm l -> snd nm = m) ->\n      ~ In (n, m) l ->\n      ~ In n (map fst l).\n  Proof using.\n    intros.\n    induction l; simpl in *; auto.\n    intro.\n    break_or_hyp.\n    - match goal with H: ~ _ |- _ => contradict H end.\n      left.\n      destruct a.\n      match goal with H: forall _ : A * B, _ |- _ => specialize (H (a, b)) end.\n      simpl in *.\n      intuition eauto; repeat find_rewrite; auto.\n    - match goal with H: In _ _ |- _ => contradict H end.\n      apply IHl; eauto.\n  Qed.\n\n  Lemma NoDup_map_snd_fst :\n    forall nms : list (A * B),\n      NoDup nms ->\n      (forall nm nm', In nm nms -> In nm' nms -> snd nm = snd nm') ->\n      NoDup (map fst nms).\n  Proof using.\n    intros.\n    induction nms; simpl in *.\n    - apply NoDup_nil.\n    - invc_NoDup.\n      apply NoDup_cons.\n      * assert (forall nm, In nm nms -> snd nm = snd a).\n          intuition eauto.\n        destruct a.\n        apply snd_eq_not_in_map with (m := b); auto.\n      * apply IHnms; auto.\n  Qed.\n\n  Lemma in_fold_left_by_cons_in :\n    forall (l : list B) (g : B -> A) x acc,\n      In x (fold_left (fun a b => g b :: a) l acc) ->\n      In x acc \\/ exists y, In y l /\\ x = g y.\n  Proof using A_eq_dec.\n    intros until l.\n    induction l.\n    - auto.\n    - simpl; intros.\n      destruct (A_eq_dec x (g a)); subst.\n      + right; exists a; tauto.\n      + find_apply_lem_hyp IHl.\n        break_or_hyp; [left|right].\n        * find_apply_lem_hyp In_cons_neq; tauto.\n        * break_exists_exists; tauto.\n  Qed.\n\n  Lemma fold_left_for_each_not_in :\n    forall (f : A -> B -> A) (g : A -> B -> C),\n      (forall a b b',\n          b <> b' ->\n          g (f a b') b = g a b) ->\n      forall l a b,\n        ~ In b l ->\n        g (fold_left f l a) b = g a b.\n  Proof using A B C.\n    induction l as [| b' l']; simpl in *; auto.\n    - intros. intuition.\n      rewrite IHl'; auto.\n  Qed.\n\n  Lemma fold_left_for_each_in :\n    forall (f : A -> B -> A) (g : A -> B -> C) (B_eq_dec : forall x y : B, {x = y} + {x <> y}),\n      (forall a b b',\n          b <> b' ->\n          g (f a b') b = g a b) ->\n      forall l a b,\n        In b l ->\n        exists a',\n          g (fold_left f l a) b = g (f a' b) b.\n  Proof using A B C.\n    induction l as [|b' l']; simpl in *; intuition; subst.\n    destruct (in_dec B_eq_dec b l'); intuition.\n    find_eapply_lem_hyp fold_left_for_each_not_in; eauto.\n  Qed.\n\n  Lemma hd_error_tl_exists :\n    forall (l : list A) x,\n      hd_error l = Some x ->\n      exists tl,\n        l = x :: tl.\n  Proof.\n    intros.\n    destruct l; simpl in *.\n    - congruence.\n    - eexists; solve_by_inversion.\n  Qed.\n\n  Lemma hd_error_None :\n    forall (l : list A),\n      hd_error l = None ->\n      l = [].\n  Proof.\n    now destruct l.\n  Qed.\n\nEnd list_util.\n\n(* We have to repeat these Hint Resolve commands because hints don't survive\n   past the ends of sections *)\n#[global] Hint Resolve app_cons_in : struct_util.\n#[global] Hint Resolve app_cons_in_rest : struct_util.\n#[global] Hint Resolve in_rest_app_cons : struct_util.\n", "meta": {"author": "uwplse", "repo": "StructTact", "sha": "2f2ff253be29bb09f36cab96d036419b18a95b00", "save_path": "github-repos/coq/uwplse-StructTact", "path": "github-repos/coq/uwplse-StructTact/StructTact-2f2ff253be29bb09f36cab96d036419b18a95b00/theories/ListUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173791645582, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.6547733713482675}}
{"text": "Require Import MyTactics.\nRequire Import LCSyntax.\nRequire Import LCValues.\nRequire Import LCReduction.\nRequire Import Arith.\n\n(*|\n\n-----\nTypes\n-----\n\nHere is the syntax of simple types:\n\n|*)\n\nInductive ty :=\n| TyVar (x : var)\n| TyFun (A B : ty)\n| TyOption (T: ty).\n\nFixpoint size (T: ty) { struct T } :=\n  match T with\n  | TyVar _ => 0\n  | TyFun A B => 1 + size A + size B\n  | TyOption A => 1 + size A\n  end\n.\n\n(*|\n\nA type environment is viewed as a total function of variables to types.\n\nIn principle, an environment should be modeled as a list of types, which\nrepresents a partial function of variables to types. This introduces a few\ncomplications, and is left as an exercise for the reader.\n\n|*)\n\nDefinition tyenv := var -> ty.\n\n(*|\n\n--------------------\nThe typing judgement\n--------------------\n\nThe simply-typed lambda-calculus is defined by the following three\ntyping rules.\n\n|*)\n\nInductive jt : tyenv -> term -> ty -> Prop :=\n| JTVar:\n    forall Gamma x T,\n    Gamma x = T ->\n    jt Gamma (Var x) T\n| JTLam:\n    forall Gamma t T U,\n    jt (T .: Gamma) t U ->\n    jt Gamma (Lam t) (TyFun T U)\n| JTApp:\n    forall Gamma t1 t2 T U,\n    jt Gamma t1 (TyFun T U) ->\n    jt Gamma t2 T ->\n    jt Gamma (App t1 t2) U\n| JtNone:\n  forall Gamma T,\n  jt Gamma VariantNone (TyOption T)\n| JtSome:\n  forall Gamma t T,\n  jt Gamma t T ->\n  jt Gamma (VariantSome t) (TyOption T)\n| JtMatch:\n  forall Gamma tc t1 t2 T U,\n  jt Gamma tc (TyOption U) ->\n  jt Gamma t1 T ->\n  jt ( U .: Gamma) t2 T ->\n  jt Gamma (Match tc t1 t2) T\n.\n\n\nLemma empty_is_sound:\n  forall t T Gamma,\n  jt Gamma t T -> \n  forall k,\n  fv k t ->\n  forall Gamma',\n  (forall i, i < k  -> Gamma' i = Gamma i) -> jt Gamma' t T.\nProof.\n  intros t T Gamma H; induction H; intros.\n  * econstructor.\n    rewrite H1; eauto.\n    fv.\n  * econstructor.\n    eapply IHjt.\n    fv.\n    induction i; eauto.\n    simpl; intros. apply H1. lia.\n  * econstructor; fv; unpack.\n    - eapply IHjt1; eauto.\n    - eapply IHjt2; eauto.\n  * admit.\n  * admit.\n  * admit.\nAdmitted.\n\nLemma jt_determ:\n  forall Gamma x T,\n  jt Gamma (Var x) T ->\n  forall U,\n  jt Gamma (Var x) U ->\n  T = U.\nProof.\n  intros Gamma t x Hjtx.\n  inverts Hjtx.\n  intros.\n  now inverts H.\nQed.\n\n\nLemma exists_diff (T: ty):\n  exists U, T <> U.\nProof.\n  exists (TyFun T T).\n  remember (size T).\n  assert (size T <> 1 + size T + size T).\n  { lia. }\n  intro.\n  eapply H.\n  rewrite H0 at 1. simpl; eauto.\nQed.\n\n\nRequire Import PeanoNat.\nRequire Import Bool.\n\nLemma reflect_lt_ltb:\n  forall n m, reflect (n < m) (n <? m).\nProof.\n  intros.\n  remember (n <? m).\n  induction b; econstructor.\n  * eapply Nat.ltb_lt; eauto.\n  * eapply Nat.ltb_nlt; eauto.\nQed.\n\n\n\n(*|\n\nThe tactic [pick_jt t] picks a hypothesis [h] whose statement is a typing\njudgement about the term [t], and passes [h] to the Ltac continuation [k].\n\nThus, for instance, [pick_jt t invert] selects a typing judgement that is\nat hand for the term [t] and inverts it.\n\n|*)\n\nLtac pick_jt t k :=\n  match goal with h: jt _ t _ |- _ => k h end.\n\n(*|\n\nThe following hint allows `eauto with jt` to apply the above typing rules.\n\n|*)\n\nGlobal Hint Constructors jt : jt.\n\nRequire Import FunctionalExtensionality.\n\nLemma empty_is_complete:\nforall t T Gamma,\n  jt Gamma t T -> \n  forall k,\n  (forall Gamma', (forall i, i < k  -> Gamma' i = Gamma i) -> jt Gamma' t T) ->\n  fv k t.\nProof. (*| Let's start the proof. |*)\n  introv Hjt.\n  induction Hjt.\n  * introv Hsame; fv.\n    (*| Case JtVar. Either x < k or x >= k. In the first case, we are ok. In the second one, we build Gamma' as (fun i => if i <? k then Gamma i else U) where U is an element such that U <> T. |*)\n    destruct reflect_lt_ltb with x k.\n    - eauto.\n    - false.\n      forwards [U HU]: exists_diff T.\n      eapply HU.\n      eapply jt_determ with (fun i => if i <? k then Gamma i else U) x.\n      + eapply Hsame.\n        { intros.\n          replace (i <? k) with true; eauto.\n            { symmetry. destruct Nat.ltb_lt with i k. eauto. }\n        }\n      + econstructor.\n        replace (x <? k) with false; eauto.\n          { symmetry. eapply Nat.ltb_nlt. eauto. }\n  * (*| Case JtLam. By induction hypothesis, it suffice to prove |*)\n    introv Hsame; fv.\n    eapply IHHjt; intros.\n    assert (\n      exists Gamma'', T.: Gamma'' = Gamma' ).\n    { exists (fun x => Gamma' (S x)).\n      eapply functional_extensionality; intros.\n      induction x.\n      - rewrite H; simpl; eauto with lia.\n      - now simpl.\n    } unpack; replace Gamma' with (T .: Gamma'') in *; clear Gamma'; rename Gamma'' into Gamma'; clear H0.\n\n    forwards: Hsame Gamma'.\n    { intros. eapply (H (S i)). lia. }\n    now match goal with h: jt _ _ _ |- _ => inverts h end.\n  \n  * (*| Case JtApp |*)\n    introv Hsame; fv.\n    split.\n    - eapply IHHjt1; intros.\n      forwards tmp: Hsame Gamma' ; eauto. inverts tmp.\n      admit. (* ??? *)\n    - eapply IHHjt2; intros.\n      forwards tmp: Hsame Gamma'; eauto; inverts tmp. \n\n      admit.\n\n      (* eapply H1.\n      eapply jt_determ.\n      eapply Hsame.\n\n      eapply jt_determ. *)\n\n    \n\n    (* eapply (H0 (fun i => if i <=? k then Gamma i else U)).  *)\n  * set (Gamma' := (fun x: nat => TyFun T T)).\n    admit.\n    (*\n    assert (T = TyFun T T).\n    {\n      eapply jt_determ.\n      eapply (H Gamma').\n      econstructor.\n      subst Gamma'.\n      eauto.\n    }\n    false.\n    admit. (* with a size on types *) *)\n  *  \nAdmitted.\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/STLCDefinition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6547733695455124}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.omega.Omega.\n\nFixpoint delete_nth {A} (n: nat) (xs: list A) {struct n} : list A :=\n match n, xs with\n | O, y::ys => ys\n | S n', y::ys =>y :: delete_nth n' ys\n | _ , _ => nil\n end.\n\nInductive find_nth_preds_rec {A: Type} (pred: A -> Prop): nat -> list A -> option (nat * A) -> Prop :=\n| find_nth_preds_rec_cons_head: forall n R0 R, pred R0 -> find_nth_preds_rec pred n (R0 :: R) (Some (n, R0))\n| find_nth_preds_rec_cons_tail: forall n R0 R R_res, find_nth_preds_rec pred (S n) R R_res -> find_nth_preds_rec pred n (R0 :: R) R_res\n| find_nth_preds_rec_nil: forall n, find_nth_preds_rec pred n nil None.\n\nLocal Unset Elimination Schemes. (* ensure that we avoid name collision with the above *)\nInductive find_nth_preds {A: Type} (pred: A -> Prop): list A -> option (nat * A) -> Prop :=\n| find_nth_preds_constr: forall R R_res, find_nth_preds_rec pred 0 R R_res -> find_nth_preds pred R R_res.\nScheme Minimality for find_nth_preds Sort Prop.\nLocal Set Elimination Schemes.\n\nLemma find_nth_preds_Some: forall {A: Type} (pred: A -> Prop) R n R0, find_nth_preds pred R (Some (n, R0)) ->\n  nth_error R n = Some R0 /\\ pred R0.\nProof.\n  intros.\n  inversion H; subst; clear H.\n  replace n with (n - 0)%nat by omega.\n  assert ((n >= 0)%nat /\\ nth_error R (n - 0) = Some R0 /\\ pred R0); [| tauto].\n  revert H0; generalize 0%nat as m; intros.\n  remember (Some (n, R0)) as R_res eqn:?H in H0.\n  induction H0.\n  + inversion H; subst; clear H.\n    replace (n - n)%nat with 0%nat by omega.\n    simpl; auto.\n  + apply IHfind_nth_preds_rec in H.\n    destruct H as [? [? ?]].\n    replace (n - n0)%nat with (S (n - S n0)) by omega.\n    split; [omega |].\n    simpl; auto.\n  + inversion H.\nQed.\n\n(* Current not used. *)\nLemma find_nth_preds_rec_S: forall {A: Type} (pred: A -> Prop) z R n Rn,\n  find_nth_preds_rec pred z R (Some (n, Rn)) ->\n  find_nth_preds_rec pred (S z) R (Some (S n, Rn)).\nProof.\n  intros.\n  remember (Some (n, Rn)) as Res eqn:?H.\n  revert n Rn H0; induction H; intros.\n  + inversion H0; subst; clear H0.\n    eapply find_nth_preds_rec_cons_head; eauto.\n  + subst R_res.\n    apply find_nth_preds_rec_cons_tail; auto.\n  + inversion H0.\nQed.\n\n(* Current not used. *)\nLemma find_nth_preds_rec_delete_nth: forall {A: Type} (pred: A -> Prop) z m R Rn,\n  (exists n, find_nth_preds_rec pred z (delete_nth m R) (Some (n, Rn))) ->\n  (exists n, find_nth_preds_rec pred z R (Some (n, Rn))).\nProof.\n  intros.\n  revert z R H; induction m; intros; destruct R; auto.\n  + simpl in *.\n    destruct H as [n ?].\n    eexists.\n    eapply find_nth_preds_rec_cons_tail.\n    apply find_nth_preds_rec_S.\n    exact H.\n  + simpl in *.\n    destruct H as [n ?].\n    inversion H; subst; clear H.\n    - eexists; apply find_nth_preds_rec_cons_head; auto.\n    - specialize (IHm (S z) _ (ex_intro _ _ H4)).\n      clear n H4; destruct IHm as [n ?].\n      exists n.\n      apply find_nth_preds_rec_cons_tail; auto.\nQed.\n\n(* Current not used. *)\nLemma find_nth_preds_delete_nth: forall {A: Type} (pred: A -> Prop) m R Rn,\n  (exists n, find_nth_preds pred (delete_nth m R) (Some (n, Rn))) ->\n  (exists n, find_nth_preds pred R (Some (n, Rn))).\nProof.\n  intros ? ? ? ? ? [n ?].\n  inversion H; subst; clear H.\n  pose proof (ex_intro _ n H0): exists n, find_nth_preds_rec pred 0 (delete_nth m R) (Some (n, Rn)).\n  apply find_nth_preds_rec_delete_nth in H.\n  clear n H0.\n  destruct H as [n ?].\n  exists n.\n  apply find_nth_preds_constr; auto.\nQed.\n\nLtac find_nth_rec tac :=\n  first [ simple eapply find_nth_preds_rec_cons_head; tac\n        | simple eapply find_nth_preds_rec_cons_tail; find_nth_rec tac\n        | simple eapply find_nth_preds_rec_nil].\n\nLtac find_nth tac :=\n  eapply find_nth_preds_constr; find_nth_rec tac.\n(* The reason to use \"eapply\" instead of \"simple eapply\" is because \"find_nth\" may be buried in definitions. *)\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/floyd/find_nth_tactic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629214, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.6547733620991814}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\nRequire Import Arith.\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint less (less_arg0 : natural) (less_arg1 : natural) : bool\n           := match less_arg0, less_arg1 with\n              | x, Zero => false\n              | Zero, Succ x => true\n              | Succ x, Succ y => less x y\n              end.\n\nFixpoint eqb (n m: natural) : bool :=\n  match n, m with\n    | Zero, Zero => true\n    | Zero, Succ _ => false\n    | Succ _, Zero => false\n    | Succ n', Succ m' => eqb n' m'\n  end.\n\n\nFixpoint count  (count_arg1 : lst) (count_arg0 : natural): natural\n           := match  count_arg1,count_arg0 with\n              | Nil, x => Zero\n              | Cons y z, x => if eqb x y then Succ (count z x) else count z x\n              end.\n\n              Fixpoint insort  (insort_arg1 : lst) (insort_arg0 : natural) : lst\n              := match insort_arg1, insort_arg0 with\n                 |  Nil, i => Cons i Nil\n                 | Cons x y, i => if less i x then Cons i (Cons x y) else Cons x (insort y i)\n                 end.\n\n                 Fixpoint sort (sort_arg0 : lst) : lst\n                 := match sort_arg0 with\n                    | Nil => Nil\n                    | Cons x y => insort (sort y) x\n                    end.\n\nTheorem eqb_refl: forall n, eqb n n = true.\nProof.\n   induction n; simpl.\n   { assumption. }\n   { reflexivity. }\nQed.\n\nTheorem eqb_diff: forall (x y: natural), x <> y -> eqb x y = false.\nProof.\n   induction x; induction y; simpl.\n   {\n   intros.\n   apply IHx.\n   intro.\n   subst.\n   assert (Succ y = Succ y). reflexivity.\n   apply H in H0.\n   destruct H0.\n   }\n   {\n   intros. reflexivity.\n   }\n   {\n   intros. reflexivity.\n   }\n   {\n   intros.\n   assert (Zero = Zero). reflexivity.\n   apply H in H0.\n   destruct H0.\n   }\nQed.\n\nTheorem eqb_elim: forall (x y: natural), Bool.Is_true (eqb x y) -> x = y.\nProof.\n   induction x; induction y; simpl in *.\n   intros.\n   {\n   apply IHx in H.\n   subst.\n   reflexivity.\n   }\n   {\n   intros.\n   destruct H.\n   }\n   { intros; destruct H. }\n   {\n   intros. reflexivity.\n   }\nQed.\n\nTheorem count_cons: forall (x: natural) (l: lst), count (Cons x l) x = Succ (count l x).\nProof.\n   intros.\n   simpl.\n   rewrite eqb_refl.\n   reflexivity.\nQed.\n\nTheorem count_insort: forall (x: natural) (l: lst), count (insort l x) x= Succ (count l x).\nProof.\n   intros.\n   induction l.\n   {\n   simpl in *.\n   destruct (less x n).\n   {\n      rewrite count_cons.\n      f_equal.\n   }\n   {\n      destruct (eqb x n) eqn:E.\n      {\n         apply Bool.Is_true_eq_left in E.\n         apply eqb_elim in E.\n         rewrite E in *.\n         rewrite count_cons.\n         rewrite IHl.\n         reflexivity.\n      }\n      {\n         simpl.\n         rewrite E.\n         assumption.\n      }\n   }\n   }\n   {\n   simpl.\n   rewrite eqb_refl.\n   reflexivity.\n   }\nQed.\n\nTheorem count_cons_diff: forall (x y: natural) (l: lst), x <> y -> count (Cons y l) x= count l x.\nProof.\n   intros. simpl.\n   apply eqb_diff in H.\n   rewrite H.\n   reflexivity.\nQed.\n\nTheorem count_insort_diff: forall (x y: natural) (l: lst), x <> y -> count (insort l y) x= count l x.\nProof.\n   intros.\n   induction l.\n   {\n   simpl.\n   destruct (less y n) eqn:El; destruct (eqb x n) eqn:Ee.\n   {\n      simpl.\n      apply eqb_diff in H. rewrite H.\n      rewrite Ee.\n      reflexivity.\n   }\n   {\n      rewrite count_cons_diff.\n      { simpl. rewrite Ee. reflexivity. }\n      { assumption. }\n   }\n   {\n      simpl. rewrite Ee. f_equal.\n      assumption.\n   }\n   {\n      simpl. rewrite Ee. assumption.\n   }\n   }\n   {\n   simpl.\n   apply eqb_diff in H.\n   rewrite H.\n   reflexivity.\n   }\nQed.\n\nTheorem theorem0 : forall (x : natural) (y : lst), eq (count (sort y) x) (count y x).\nProof.\n   intros.\n   induction y.\n   {\n   simpl.\n   destruct (eqb x n) eqn:E.\n   {\n      apply Bool.Is_true_eq_left in E.\n      apply eqb_elim in E.\n      subst.\n      rewrite count_insort.\n      f_equal. assumption.\n   }\n   {\n      simpl.\n      rewrite count_insort_diff.\n      assumption.\n      intro.\n      rewrite H in E.\n      lfind. Admitted.\n", "meta": {"author": "ana-brendel", "repo": "coq-benchmarks", "sha": "78b9ca2993b0fb579d814ed17e63c6859e79681c", "save_path": "github-repos/coq/ana-brendel-coq-benchmarks", "path": "github-repos/coq/ana-brendel-coq-benchmarks/coq-benchmarks-78b9ca2993b0fb579d814ed17e63c6859e79681c/modifications/quickchick_fails/test66_goal50/lfind_goal50.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6547711339995161}}
{"text": "Require Import Coq.micromega.Lia.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Pow2.\nRequire Import Crypto.Util.ZUtil.Log2.\nRequire Import Crypto.Util.ZUtil.Tactics.PeelLe.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.ZUtil.Tactics.ReplaceNegWithPos.\nRequire Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.\nRequire Import Crypto.Util.ZUtil.Tactics.RewriteModSmall.\nRequire Import Crypto.Util.ZUtil.Tactics.LinearSubstitute.\nRequire Import Crypto.Util.ZUtil.Tactics.SplitMinMax.\nRequire Import Crypto.Util.ZUtil.Modulo.PullPush.\nRequire Import Crypto.Util.ZUtil.LandLorShiftBounds.\nRequire Import Crypto.Util.ZUtil.Modulo.\nRequire Import Crypto.Util.ZUtil.Ones.\nRequire Import Crypto.Util.ZUtil.Lnot.\nRequire Import Crypto.Util.ZUtil.Land.\nRequire Import Crypto.Util.Tactics.UniquePose.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma round_lor_land_bound_bounds x\n  : (0 <= x <= Z.round_lor_land_bound x) \\/ (Z.round_lor_land_bound x <= x <= -1).\n  Proof.\n    cbv [Z.round_lor_land_bound]; break_innermost_match; Z.ltb_to_lt.\n    all: constructor; split; try lia; [].\n    all: Z.replace_all_neg_with_pos.\n    all: match goal with |- context[2^Z.log2_up ?x] => pose proof (Z.log2_up_le_full x) end.\n    all: lia.\n  Qed.\n  Hint Resolve round_lor_land_bound_bounds : zarith.\n\n  Lemma round_lor_land_bound_bounds_pos x\n  : (0 <= Z.pos x <= Z.round_lor_land_bound (Z.pos x)).\n  Proof. generalize (round_lor_land_bound_bounds (Z.pos x)); lia. Qed.\n  Hint Resolve round_lor_land_bound_bounds_pos : zarith.\n\n  Lemma round_lor_land_bound_bounds_neg x\n  : Z.round_lor_land_bound (Z.neg x) <= Z.neg x <= -1.\n  Proof. generalize (round_lor_land_bound_bounds (Z.neg x)); lia. Qed.\n  Hint Resolve round_lor_land_bound_bounds_neg : zarith.\n\n  Local Ltac saturate :=\n    repeat first [ progress cbv [Z.round_lor_land_bound Proper respectful Basics.flip] in *\n                 | progress Z.ltb_to_lt\n                 | progress intros\n                 | break_innermost_match_step\n                 | lia\n                 | rewrite !Pos2Z.opp_neg\n                 | match goal with\n                   | [ |- context[Z.log2_up ?x] ]\n                     => unique pose proof (Z.log2_up_nonneg x)\n                   | [ |- context[2^?x] ]\n                     => unique assert (0 <= 2^x) by (apply Z.pow_nonneg; lia)\n                   | [ H : 0 <= ?x |- context[2^?x] ]\n                     => unique assert (0 < 2^x) by (apply Z.pow_pos_nonneg; lia)\n                   | [ H : Pos.le ?x ?y |- context[Z.pos ?x] ]\n                     => unique assert (Z.pos x <= Z.pos y) by lia\n                   | [ H : Pos.le ?x ?y |- context[Z.pos (?x+1)] ]\n                     => unique assert (Z.pos (x+1) <= Z.pos (y+1)) by lia\n                   | [ H : Z.le ?x ?y |- context[?x+1] ]\n                     => unique assert (x+1 <= y+1) by lia\n                   | [ H : Z.le ?x ?y |- context[2^Z.log2_up ?x] ]\n                     => unique assert (2^Z.log2_up x <= 2^Z.log2_up y) by (Z.peel_le; lia)\n                   | [ H : ?a^?b <= ?a^?c |- _ ]\n                     => unique assert (a^(c-b) = a^c/a^b) by auto with zarith;\n                       unique assert (a^c mod a^b = 0) by auto with zarith\n                   end ].\n  Local Ltac do_rewrites_step :=\n    match goal with\n    | [ |- ?R ?x ?x ] => reflexivity\n    (*| [ |- context[Z.land (-2^_) (-2^_)] ]\n      => rewrite <- !Z.lnot_ones_equiv, <- !Z.lnot_lor, !Z.lor_ones_ones, !Z.lnot_ones_equiv\n    | [ |- context[Z.lor (-2^_) (-2^_)] ]\n      => rewrite <- !Z.lnot_ones_equiv, <- !Z.lnot_land, !Z.land_ones_ones, !Z.lnot_ones_equiv\n    | [ |- context[Z.land (2^_-1) (2^_-1)] ]\n      => rewrite !Z.sub_1_r, <- !Z.ones_equiv, !Z.land_ones_ones, !Z.ones_equiv, <- !Z.sub_1_r\n    | [ |- context[Z.lor (2^_-1) (2^_-1)] ]\n      => rewrite !Z.sub_1_r, <- !Z.ones_equiv, !Z.lor_ones_ones, !Z.ones_equiv, <- !Z.sub_1_r\n    | [ |- context[Z.land (2^?x-1) (-2^?y)] ]\n      => rewrite (@Z.land_comm (2^x-1) (-2^y))\n    | [ |- context[Z.lor (2^?x-1) (-2^?y)] ]\n      => rewrite (@Z.lor_comm (2^x-1) (-2^y))\n    | [ |- context[Z.land (-2^_) (2^_-1)] ]\n      => rewrite !Z.sub_1_r, <- !Z.ones_equiv, !Z.land_ones, ?Z.ones_equiv, <- ?Z.sub_1_r by lia\n    | [ |- context[Z.lor (-2^?x) (2^?y-1)] ]\n      => rewrite <- !Z.lnot_ones_equiv, <- (Z.lnot_involutive (2^y-1)), <- !Z.lnot_land, ?Z.lnot_ones_equiv, (Z.lnot_sub1 (2^y)), !Z.ones_equiv, ?Z.lnot_equiv, <- !Z.sub_1_r\n    | [ |- context[-?x mod ?y] ]\n      => rewrite (@Z.opp_mod_mod_push x y) by Z.NoZMod*)\n    | [ |- context[Z.land (2^?y-1) ?x] ]\n      => is_var x; rewrite (Z.land_comm (2^y-1) x)\n    | [ |- context[Z.lor (2^?y-1) ?x] ]\n      => is_var x; rewrite (Z.lor_comm (2^y-1) x)\n    | [ |- context[Z.land (-2^?y) ?x] ]\n      => is_var x; rewrite (Z.land_comm (-2^y) x)\n    | [ |- context[Z.lor (-2^?y) ?x] ]\n      => is_var x; rewrite (Z.lor_comm (-2^y) x)\n    | [ |- context[Z.land _ (2^_-1)] ]\n      => rewrite !Z.sub_1_r, <- !Z.ones_equiv, !Z.land_ones by auto with zarith\n    | [ |- context[Z.land ?x (-2^?y)] ]\n      => is_var x;\n        rewrite <- !Z.lnot_ones_equiv, <- (Z.lnot_involutive x), <- !Z.lnot_lor, !Z.ones_equiv, !Z.lnot_equiv, <- !Z.sub_1_r;\n        let x' := fresh in\n        remember (-x-1) as x' eqn:?; Z.linear_substitute x;\n        rename x' into x\n    | [ |- context[Z.lor ?x (-2^?y)] ]\n      => is_var x;\n        rewrite <- !Z.lnot_ones_equiv, <- (Z.lnot_involutive x), <- !Z.lnot_land, !Z.ones_equiv, !Z.lnot_equiv, <- !Z.sub_1_r;\n        let x' := fresh in\n        remember (-x-1) as x' eqn:?; Z.linear_substitute x;\n        rename x' into x\n    | [ |- Z.lor ?x (?y-1) <= Z.lor ?x (?y'-1) ]\n      => rewrite (Z.div_mod'' (Z.lor x (y-1)) y), (Z.div_mod'' (Z.lor x (y'-1)) y') by auto with zarith\n    | [ |- Z.lor ?x (?y-1) = _ ]\n      => rewrite (Z.div_mod'' (Z.lor x (y-1)) y) by auto with zarith\n    | [ |- context[?m1 - 1 + (?x - ?x mod ?m1)] ]\n      => replace (m1 - 1 + (x - x mod m1)) with ((m1 - x mod m1) + (x - 1)) by lia\n    | _ => progress rewrite ?Z.lor_pow2_div_pow2_r, ?Z.lor_pow2_div_pow2_l, ?Z.lor_pow2_mod_pow2_r, ?Z.lor_pow2_mod_pow2_l by auto with zarith\n    | _ => rewrite !Z.mul_div_eq by lia\n    | _ => progress rewrite ?(Z.add_comm 1) in *\n    | [ |- context[?x mod 2^(Z.log2_up (?x + 1))] ]\n      => rewrite (Z.mod_small x (2^Z.log2_up (x+1))) by (rewrite <- Z.le_succ_l, <- Z.add_1_r, Z.log2_up_le_pow2 by lia; lia)\n    | [ H : ?a^?b <= ?a^?c |- context[?x mod ?a^?b] ]\n      => rewrite (@Z.mod_pow_r_split x a b c) by auto with zarith;\n        (Z.div_mod_to_quot_rem; nia)\n    | _ => progress Z.peel_le\n    (*| [ H : ?x <= ?x |- _ ] => clear H\n    | [ H : ?x < ?y, H' : ?y <= ?z |- _ ] => unique assert (x < z) by lia\n    | [ H : ?x < ?y, H' : ?a <= ?x |- _ ] => unique assert (a < y) by lia\n    | [ H : 2^?x < 2^?y |- context[2^?x mod 2^?y] ]\n      => repeat first [ rewrite (Z.mod_small (2^x) (2^y)) by lia\n                      | rewrite !(@Z_mod_nz_opp_full (2^x) (2^y)) ]\n    | [ H : ?x < ?y, H' : context[?x mod ?y] |- _ ] => rewrite (Z.mod_small x y) in H' by lia\n    | [ |- context[2^?x mod 2^?y] ]\n      => let H := fresh in\n         destruct (@Z.pow2_lt_or_divides x y ltac:(lia)) as [H|H];\n         [ repeat first [ rewrite (Z.mod_small (2^x) (2^y)) by lia\n                        | rewrite !(@Z_mod_nz_opp_full (2^x) (2^y)) ]\n         | rewrite H ]*)\n    | _ => progress autorewrite with zsimplify_fast in *\n    | [ |- context[-(-?x-1)] ] => replace (-(-x-1)) with (1+x) by lia\n    | [ H : 0 > -(1+?x) |- _ ] => assert (0 <= x) by (clear -H; lia); clear H\n    | [ H : 0 > -(?x+1) |- _ ] => assert (0 <= x) by (clear -H; lia); clear H\n    | [ |- ?a - ?b = ?a' - ?b' ] => apply f_equal2; try reflexivity; []\n    | [ |- -?a = -?a' ] => apply f_equal\n    | _ => rewrite <- !Z.sub_1_r\n    | _ => lia\n    end.\n  Local Ltac do_rewrites := repeat do_rewrites_step.\n  Local Ltac fin_t :=\n    repeat first [ progress destruct_head'_and\n                 | match goal with\n                   | [ H : orb _ _ = _ |- _ ]\n                     => progress rewrite ?Bool.orb_true_iff, ?Bool.orb_false_iff, ?Z.ltb_lt, ?Z.ltb_ge in *\n                   end\n                 | break_innermost_match_step\n                 | progress destruct_head'_or\n                 | lia\n                 | progress Z.peel_le ].\n  Local Ltac t :=\n    saturate; do_rewrites.\n\n  Local Instance land_round_Proper_pos_r x\n    : Proper (Pos.le ==> Z.le) (fun y => Z.land x (Z.round_lor_land_bound (Z.pos y))).\n  Proof. t. Qed.\n\n  Local Instance land_round_Proper_pos_l y\n    : Proper (Pos.le ==> Z.le) (fun x => Z.land (Z.round_lor_land_bound (Z.pos x)) y).\n  Proof. t. Qed.\n\n  Local Instance lor_round_Proper_pos_r x\n    : Proper (Pos.le ==> Z.le) (fun y => Z.lor x (Z.round_lor_land_bound (Z.pos y))).\n  Proof. t. Qed.\n\n  Local Instance lor_round_Proper_pos_l y\n    : Proper (Pos.le ==> Z.le) (fun x => Z.lor (Z.round_lor_land_bound (Z.pos x)) y).\n  Proof. t. Qed.\n\n  Local Instance land_round_Proper_neg_r x\n    : Proper (Basics.flip Pos.le ==> Z.le) (fun y => Z.land x (Z.round_lor_land_bound (Z.neg y))).\n  Proof. t. Qed.\n\n  Local Instance land_round_Proper_neg_l y\n    : Proper (Basics.flip Pos.le ==> Z.le) (fun x => Z.land (Z.round_lor_land_bound (Z.neg x)) y).\n  Proof. t. Qed.\n\n  Local Instance lor_round_Proper_neg_r x\n    : Proper (Basics.flip Pos.le ==> Z.le) (fun y => Z.lor x (Z.round_lor_land_bound (Z.neg y))).\n  Proof. t. Qed.\n\n  Local Instance lor_round_Proper_neg_l y\n    : Proper (Basics.flip Pos.le ==> Z.le) (fun x => Z.lor (Z.round_lor_land_bound (Z.neg x)) y).\n  Proof. t. Qed.\n\n  Lemma land_round_lor_land_bound_r x\n    : Z.land x (Z.round_lor_land_bound x) = if (0 <=? x) then x else Z.round_lor_land_bound x.\n  Proof. t. Qed.\n  Hint Rewrite land_round_lor_land_bound_r : zsimplify_fast zsimplify.\n  Lemma land_round_lor_land_bound_l x\n    : Z.land (Z.round_lor_land_bound x) x = if (0 <=? x) then x else Z.round_lor_land_bound x.\n  Proof. rewrite Z.land_comm, land_round_lor_land_bound_r; reflexivity. Qed.\n  Hint Rewrite land_round_lor_land_bound_l : zsimplify_fast zsimplify.\n\n  Lemma lor_round_lor_land_bound_r x\n    : Z.lor x (Z.round_lor_land_bound x) = if (0 <=? x) then Z.round_lor_land_bound x else x.\n  Proof. t. Qed.\n  Hint Rewrite lor_round_lor_land_bound_r : zsimplify_fast zsimplify.\n  Lemma lor_round_lor_land_bound_l x\n    : Z.lor (Z.round_lor_land_bound x) x = if (0 <=? x) then Z.round_lor_land_bound x else x.\n  Proof. rewrite Z.lor_comm, lor_round_lor_land_bound_r; reflexivity. Qed.\n  Hint Rewrite lor_round_lor_land_bound_l : zsimplify_fast zsimplify.\n\n  Lemma land_round_bound_pos_r v x\n    : 0 <= Z.land v (Z.pos x) <= Z.land v (Z.round_lor_land_bound (Z.pos x)).\n  Proof.\n    rewrite Z.land_nonneg; split; [ lia | ].\n    replace (Z.pos x) with (Z.land (Z.pos x) (Z.round_lor_land_bound (Z.pos x))) at 1\n      by now rewrite land_round_lor_land_bound_r.\n    rewrite (Z.land_comm (Z.pos x)), Z.land_assoc.\n    apply Z.land_upper_bound_l; rewrite ?Z.land_nonneg; t.\n  Qed.\n  Hint Resolve land_round_bound_pos_r (fun v x => proj1 (land_round_bound_pos_r v x)) (fun v x => proj2 (land_round_bound_pos_r v x)) : zarith.\n  Lemma land_round_bound_pos_l v x\n    : 0 <= Z.land (Z.pos x) v <= Z.land (Z.round_lor_land_bound (Z.pos x)) v.\n  Proof. rewrite <- !(Z.land_comm v); apply land_round_bound_pos_r. Qed.\n  Hint Resolve land_round_bound_pos_l (fun v x => proj1 (land_round_bound_pos_l v x)) (fun v x => proj2 (land_round_bound_pos_l v x)) : zarith.\n\n  Lemma land_round_bound_neg_r v x\n    : Z.land v (Z.round_lor_land_bound (Z.neg x)) <= Z.land v (Z.neg x) <= v.\n  Proof.\n    assert (0 < 2 ^ Z.log2_up (Z.pos x)) by auto with zarith.\n    split; [ | apply Z.land_le; lia ].\n    replace (Z.round_lor_land_bound (Z.neg x)) with (Z.land (Z.neg x) (Z.round_lor_land_bound (Z.neg x)))\n      by now rewrite land_round_lor_land_bound_r.\n    rewrite !Z.land_assoc.\n    etransitivity; [ apply Z.land_le; cbn; lia | ]; lia.\n  Qed.\n  Hint Resolve land_round_bound_neg_r (fun v x => proj1 (land_round_bound_neg_r v x)) (fun v x => proj2 (land_round_bound_neg_r v x)) : zarith.\n  Lemma land_round_bound_neg_l v x\n    : Z.land (Z.round_lor_land_bound (Z.neg x)) v <= Z.land (Z.neg x) v <= v.\n  Proof. rewrite <- !(Z.land_comm v); apply land_round_bound_neg_r. Qed.\n  Hint Resolve land_round_bound_neg_l (fun v x => proj1 (land_round_bound_neg_l v x)) (fun v x => proj2 (land_round_bound_neg_l v x)) : zarith.\n\n  Lemma lor_round_bound_neg_r v x\n    : Z.lor v (Z.round_lor_land_bound (Z.neg x)) <= Z.lor v (Z.neg x) <= -1.\n  Proof.\n    change (-1) with (Z.pred 0); rewrite <- Z.lt_le_pred.\n    rewrite Z.lor_neg; split; [ | lia ].\n    replace (Z.neg x) with (Z.lor (Z.neg x) (Z.round_lor_land_bound (Z.neg x))) at 2\n      by now rewrite lor_round_lor_land_bound_r.\n    rewrite (Z.lor_comm (Z.neg x)), Z.lor_assoc.\n    cbn; rewrite <- !Z.lnot_ones_equiv, <- (Z.lnot_involutive v), <- (Z.lnot_involutive (Z.neg x)), <- !Z.lnot_land, !Z.ones_equiv, !Z.lnot_equiv, <- !Z.sub_1_r, !Pos2Z.opp_neg.\n    Z.peel_le.\n    apply Z.land_upper_bound_l; rewrite ?Z.land_nonneg; t.\n  Qed.\n  Hint Resolve lor_round_bound_neg_r (fun v x => proj1 (lor_round_bound_neg_r v x)) (fun v x => proj2 (lor_round_bound_neg_r v x)) : zarith.\n  Lemma lor_round_bound_neg_l v x\n    : Z.lor (Z.round_lor_land_bound (Z.neg x)) v <= Z.lor (Z.neg x) v <= -1.\n  Proof. rewrite <- !(Z.lor_comm v); apply lor_round_bound_neg_r. Qed.\n  Hint Resolve lor_round_bound_neg_l (fun v x => proj1 (lor_round_bound_neg_l v x)) (fun v x => proj2 (lor_round_bound_neg_l v x)) : zarith.\n\n  Lemma lor_round_bound_pos_r v x\n    : v <= Z.lor v (Z.pos x) <= Z.lor v (Z.round_lor_land_bound (Z.pos x)).\n  Proof.\n    assert (0 < 2 ^ Z.log2_up (Z.pos (x + 1))) by auto with zarith.\n    split; [ apply Z.lor_lower; lia | ].\n    replace (Z.round_lor_land_bound (Z.pos x)) with (Z.lor (Z.pos x) (Z.round_lor_land_bound (Z.pos x)))\n      by now rewrite lor_round_lor_land_bound_r.\n    rewrite !Z.lor_assoc.\n    etransitivity; [ | apply Z.lor_lower; rewrite ?Z.lor_nonneg; cbn; lia ]; lia.\n  Qed.\n  Hint Resolve lor_round_bound_pos_r (fun v x => proj1 (lor_round_bound_pos_r v x)) (fun v x => proj2 (lor_round_bound_pos_r v x)) : zarith.\n  Lemma lor_round_bound_pos_l v x\n    : v <= Z.lor (Z.pos x) v <= Z.lor (Z.round_lor_land_bound (Z.pos x)) v.\n  Proof. rewrite <- !(Z.lor_comm v); apply lor_round_bound_pos_r. Qed.\n  Hint Resolve lor_round_bound_pos_l (fun v x => proj1 (lor_round_bound_pos_l v x)) (fun v x => proj2 (lor_round_bound_pos_l v x)) : zarith.\n\n  Lemma land_round_bound_pos_r' v x : Z.land v (Z.pos x) <= Z.land v (Z.round_lor_land_bound (Z.pos x)). Proof. auto with zarith. Qed.\n  Lemma land_round_bound_pos_l' v x : Z.land (Z.pos x) v <= Z.land (Z.round_lor_land_bound (Z.pos x)) v. Proof. auto with zarith. Qed.\n  Lemma land_round_bound_neg_r' v x : Z.land v (Z.round_lor_land_bound (Z.neg x)) <= Z.land v (Z.neg x). Proof. auto with zarith. Qed.\n  Lemma land_round_bound_neg_l' v x : Z.land (Z.round_lor_land_bound (Z.neg x)) v <= Z.land (Z.neg x) v. Proof. auto with zarith. Qed.\n  Lemma lor_round_bound_neg_r' v x : Z.lor v (Z.round_lor_land_bound (Z.neg x)) <= Z.lor v (Z.neg x). Proof. auto with zarith. Qed.\n  Lemma lor_round_bound_neg_l' v x : Z.lor (Z.round_lor_land_bound (Z.neg x)) v <= Z.lor (Z.neg x) v. Proof. auto with zarith. Qed.\n  Lemma lor_round_bound_pos_r' v x : Z.lor v (Z.pos x) <= Z.lor v (Z.round_lor_land_bound (Z.pos x)). Proof. auto with zarith. Qed.\n  Lemma lor_round_bound_pos_l' v x : Z.lor (Z.pos x) v <= Z.lor (Z.round_lor_land_bound (Z.pos x)) v. Proof. auto with zarith. 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/LandLorBounds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6547711138264795}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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) : natural := 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/goal33conj238_coqofml_YWPhdM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.654760080118476}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import riscv.Utility.\nRequire Import riscv.util.Monads.\nRequire Import riscv.Memory.\nImport ListNotations.\nLocal Open Scope Z_scope.\n\n\nSection Memory.\n\n  Definition mem := list (word 8).\n  Definition mem_size(m: mem): Z := Zlength m.\n\n  Definition read_byte(m: mem)(a: Z): word 8 := Znth m a (ZToWord _ 0).\n\n  Definition write_byte'(m: mem)(a: Z)(v: word 8): mem :=\n    (Zfirstn a m) ++ [v] ++ (Zskipn (a + 1) m).\n\n  (* fix for the case when a is out of bounds to make sure length is always preserved:\n     allows for _preserves_mem_size lemmas with no hypotheses, and ensures things which\n     should not work because out of bounds writes-then-reads don't work *)\n  Definition write_byte(m: mem)(a: Z)(v: word 8): mem :=\n    firstn (length m) (write_byte' m a v).\n  \n  Definition read_half(m: mem)(a: Z): word 16 :=\n    let v0 := read_byte m a in let v1 := read_byte m (a + 1) in wappend v1 v0.\n  Definition read_word(m: mem)(a: Z): word 32 :=\n    let v0 := read_half m a in let v1 := read_half m (a + 2) in wappend v1 v0.\n  Definition read_double(m: mem)(a: Z): word 64 :=\n    let v0 := read_word m a in let v1 := read_word m (a + 4) in wappend v1 v0.\n\n  Definition write_half(m: mem)(a: Z)(v: word 16): mem :=\n    let m := write_byte m a (lobits 8 v) in write_byte m (a + 1) (hibits 8 v).\n  Definition write_word(m: mem)(a: Z)(v: word 32): mem :=\n    let m := write_half m a (lobits 16 v) in write_half m (a + 2) (hibits 16 v).\n  Definition write_double(m: mem)(a: Z)(v: word 64): mem :=\n    let m := write_word m a (lobits 32 v) in write_word m (a + 4) (hibits 32 v).\n\n  Definition const_mem(default: word 8)(size: Z): mem :=\n    map_range (fun _: Z => default) size.\n\n  Lemma const_mem_mem_size: forall default size,\n      0 <= size ->\n      mem_size (const_mem default size) = size.\n  Proof.\n    intros. unfold mem_size, const_mem. apply Zlength_map_range. assumption.\n  Qed.\n\n  Definition zero_mem: Z -> mem := const_mem (ZToWord 8 0).\n\nEnd Memory.\n\nLtac omega' := zify; rewrite Z2Nat.id in *; omega.\n\nLemma write_read_byte_eq': forall m a1 a2 v,\n    0 <= a1 < mem_size m ->\n    a2 = a1 ->\n    read_byte (write_byte' m a1 v) a2 = v.\nProof.\n  intros. subst. unfold write_byte', read_byte, mem_size in *.\n  unfold Zfirstn, Zskipn, Znth, Zlength in *.\n  pose proof (@firstn_length_le _ m (Z.to_nat a1)).\n  rewrite app_nth2 by omega'.\n  rewrite H0 by omega'.\n  replace (Z.to_nat a1 - Z.to_nat a1)%nat with 0%nat by omega.\n  reflexivity.\nQed.\n\nLemma Z_bounds_to_nat_bound: forall (a: Z) (n: nat),\n    0 <= a < Z.of_nat n ->\n    (Z.to_nat a < n)%nat.\nProof.\n  intros. omega'.\nQed.\n\nLemma Z_ne_to_nat_ne: forall (a b: Z),\n    0 <= a ->\n    0 <= b ->\n    a <> b ->\n    Z.to_nat a <> Z.to_nat b.\nProof.\n  intros. intro. apply H1. apply Z2Nat.inj; assumption.\nQed.\n\nLemma write_read_byte_ne': forall m a1 a2 v,\n    0 <= a1 < mem_size m ->\n    0 <= a2 < mem_size m ->\n    a2 <> a1 ->\n    read_byte (write_byte' m a1 v) a2 = read_byte m a2.\nProof.\n  intros. unfold write_byte', read_byte, mem_size in *.\n  pose proof (@firstn_length_le _ m (Z.to_nat a1)).\n  pose proof (@firstn_length_le _ m (Z.to_nat a2)).\n  unfold Znth, Zfirstn, Zskipn, Zlength in *.\n  rewrite Z2Nat.inj_add by omega.\n  apply Z_ne_to_nat_ne in H1; [|omega..].\n  apply Z_bounds_to_nat_bound in H.\n  apply Z_bounds_to_nat_bound in H0.\n  remember (Z.to_nat a1) as a1'. clear Heqa1' a1. rename a1' into a1.\n  remember (Z.to_nat a2) as a2'. clear Heqa2' a2. rename a2' into a2.\n  replace (a1 + Z.to_nat 1)%nat with (S a1) by omega'.\n  assert (a2 < a1 \\/ a1 < a2 < length m)%nat as P by omega.\n  destruct P as [P | P].\n  - rewrite app_nth1 by omega.\n    clear H2 H3.\n    generalize dependent m. generalize dependent a1.\n    induction a2; intros.\n    + destruct a1; [omega|simpl]. destruct m; reflexivity.\n    + destruct a1; [omega|simpl]. destruct m.\n      * simpl in H; omega.\n      * simpl in *. apply IHa2; omega.\n  - rewrite app_nth2 by omega.\n    rewrite app_nth2 by (simpl; omega).\n    rewrite H2 by omega.\n    replace (a2 - a1 - length [v])%nat with (a2 - (S a1))%nat by (simpl; omega).\n    clear H2 H3.\n    generalize dependent m. generalize dependent a1.\n    induction a2; intros.\n    + omega.\n    + replace (S a2 - S a1)%nat with (a2 - a1)%nat by omega.\n      destruct a1.\n      * replace (a2 - 0)%nat with a2 by omega. destruct m; [simpl in *; omega|reflexivity].\n      * destruct m; [simpl in *; omega|].\n        change (skipn (S (S a1)) (w :: m)) with (skipn (S a1) m).\n        change (nth (S a2) (w :: m)) with (nth a2 m).\n        apply IHa2; simpl in *; try omega.\nQed.\n\nLemma skipn_length_le: forall A n (l: list A),\n    (n <= length l)%nat ->\n    length (skipn n l) = (length l - n)%nat.\nProof.\n  induction n; intros.\n  - simpl. omega.\n  - simpl. destruct l; [simpl in *; omega|].\n    simpl in *.\n    apply IHn; omega.\nQed.\n\nLemma write_byte_preserves_mem_size': forall m a v,\n    0 <= a < mem_size m ->\n    mem_size (write_byte' m a v) = mem_size m.\nProof.\n  intros. unfold mem_size, write_byte' in *.\n  unfold Zlength, Zfirstn, Zskipn in *.\n  repeat rewrite app_length.\n  rewrite firstn_length_le by omega'.\n  rewrite skipn_length_le by omega'.\n  simpl.\n  omega'.\nQed.\n\nLemma firstn_all_write_byte': forall m a1 v,\n    0 <= a1 < mem_size m ->\n    firstn (length m) (write_byte' m a1 v) = write_byte' m a1 v.\nProof.\n  intros.\n  replace (length m) with (length (write_byte' m a1 v)).\n  - rewrite firstn_all. reflexivity.\n  - pose proof (write_byte_preserves_mem_size' m a1 v H) as P.\n    unfold mem_size, Zlength in *.\n    apply Nat2Z.inj in P.\n    assumption.\nQed.\n\nLemma write_read_byte_eq: forall m a1 a2 v,\n    0 <= a1 < mem_size m ->\n    a2 = a1 ->\n    read_byte (write_byte m a1 v) a2 = v.\nProof.\n  intros. unfold write_byte in *.\n  erewrite <- write_read_byte_eq' by eassumption.\n  rewrite firstn_all_write_byte' by assumption.\n  reflexivity.\nQed.\n\nLemma write_read_byte_ne: forall m a1 a2 v,\n    0 <= a1 < mem_size m ->\n    0 <= a2 < mem_size m ->\n    a2 <> a1 ->\n    read_byte (write_byte m a1 v) a2 = read_byte m a2.\nProof.\n  intros. unfold write_byte in *.\n  rewrite <- (write_read_byte_ne' m a1 a2 v);\n    rewrite? firstn_all_write_byte' by assumption;\n    rewrite? write_byte_preserves_mem_size' by assumption;\n    [reflexivity | eassumption ..].\nQed.\n\nLemma Z2Nat_nonpos: forall (a: Z),\n    a <= 0 ->\n    Z.to_nat a = 0%nat.\nProof.\n  intros.\n  destruct a.\n  - reflexivity.\n  - lia.\n  - apply Z2Nat.inj_neg.\nQed.\n\nLemma write_byte_preserves_mem_size: forall m a v,\n    mem_size (write_byte m a v) = mem_size m.\nProof.\n  intros. unfold write_byte.\n  assert (a < 0 \\/ 0 <= a < mem_size m \\/ a >= mem_size m) as C by omega.\n  destruct C as [H | [H | H]].\n  - unfold write_byte', Zfirstn, Zskipn.\n    rewrite! Z2Nat_nonpos by omega.\n    simpl.\n    unfold mem_size, Zlength in *.\n    apply Znat.inj_eq.\n    apply firstn_length_le.\n    simpl.\n    repeat constructor.\n  - pose proof write_byte_preserves_mem_size' as P.\n    specialize P with (1 := H).\n    unfold mem_size, Zlength in *.\n    rewrite <- (P v) at 1.\n    rewrite firstn_all_write_byte' by assumption.\n    reflexivity.\n  - unfold mem_size, Zlength in *.\n    apply Znat.inj_eq.\n    apply firstn_length_le.\n    unfold write_byte', Zfirstn, Zskipn.\n    rewrite? app_length.\n    rewrite firstn_length.\n    omega'.\nQed.\n\nLemma write_read_half_eq: forall m a1 a2 v,\n    0 <= a1 ->\n    a1 + 1 < mem_size m ->\n    a2 = a1 ->\n    read_half (write_half m a1 v) a2 = v.\nProof.\n  intros. subst. unfold write_half, read_half in *.\n  pose proof H.\n  rewrite (write_read_byte_eq _ (a1 + 1) (a1 + 1)); try reflexivity.\n  - rewrite write_read_byte_ne; try omega.\n    + rewrite write_read_byte_eq; try reflexivity; try omega.\n      apply (wappend_split 8 8); omega.\n    + rewrite write_byte_preserves_mem_size; omega.\n    + rewrite write_byte_preserves_mem_size; omega.\n  - rewrite write_byte_preserves_mem_size; omega.\nQed.\n\nLemma write_read_half_ne: forall m a1 a2 v,\n    a1 + 1 < mem_size m ->\n    a1 mod 2 = 0 ->\n    a2 + 1 < mem_size m ->\n    a2 mod 2 = 0 ->\n    a2 <> a1 ->\n    0 <= a1 ->\n    0 <= a2 ->\n    read_half (write_half m a1 v) a2 = read_half m a2.\nProof.\n  intros. unfold write_half, read_half in *.\n  f_equal.\n  - rewrite write_read_byte_ne.\n    + apply write_read_byte_ne; try omega.\n      intro. subst. rewrite Z.add_mod in H0; try omega.\n      rewrite H2 in H0.\n      simpl in H0.\n      discriminate.\n    + rewrite write_byte_preserves_mem_size; omega.\n    + rewrite write_byte_preserves_mem_size; omega.\n    + omega.\n  - rewrite write_read_byte_ne.\n    + apply write_read_byte_ne; omega.\n    + rewrite write_byte_preserves_mem_size; omega.\n    + rewrite write_byte_preserves_mem_size; omega.\n    + intro. subst. rewrite Z.add_mod in H2; try omega.\n      rewrite H0 in H2.\n      simpl in H2.\n      discriminate.\nQed.\n\nLemma add_mod_r: forall a m,\n    m <> 0 ->\n    (a + m) mod m = a mod m.\nProof.\n  intros.\n  rewrite Z.add_mod by assumption.\n  rewrite Z.mod_same by assumption.\n  rewrite Z.add_0_r.\n  apply Z.mod_mod.\n  assumption.\nQed.\n\nLemma weaken_alignment: forall n al,\n    n mod (al * 2) = 0 ->\n    al <> 0 ->\n    n mod al = 0.\nProof.\n  intros.\n  pose proof H.\n  apply Z.mod_divide in H; try omega.\n  destruct H as [n' H]. subst.\n  replace (n' * (al * 2)) with (n' * 2 * al) by ring.\n  apply Z.mod_mul.\n  assumption.\nQed.  \n\nLemma write_half_preserves_mem_size: forall m a v,\n    mem_size (write_half m a v) = mem_size m.\nProof.\n  intros. unfold write_half, mem_size in *.\n  repeat rewrite write_byte_preserves_mem_size; unfold mem_size; omega.\nQed.\n\nLemma diviBy4_implies_diviBy2: forall n,\n    n mod 4 = 0 ->\n    n mod 2 = 0.\nProof.\n  intros.\n  apply weaken_alignment; [assumption | omega].\nQed.  \n\nLemma write_read_word_eq: forall m a1 a2 v,\n    a1 + 4 <= mem_size m ->\n    a1 mod 4 = 0 ->\n    a2 = a1 ->\n    0 <= a1 ->\n    read_word (write_word m a1 v) a2 = v.\nProof.\n  intros. subst. unfold write_word, read_word in *.\n  pose proof H.\n  rewrite (write_read_half_eq _ (a1 + 2) (a1 + 2)); try reflexivity; try omega.\n  - rewrite write_read_half_ne; try omega.\n    + rewrite write_read_half_eq; try reflexivity; try omega.\n      apply (wappend_split 16 16); omega.\n    + rewrite write_half_preserves_mem_size; omega.\n    + apply diviBy4_implies_diviBy2 in H0. rewrite Z.add_mod by omega.\n      rewrite H0.\n      reflexivity.\n    + rewrite write_half_preserves_mem_size; omega.\n    + apply diviBy4_implies_diviBy2. assumption.\n  - rewrite write_half_preserves_mem_size; omega.\nQed.\n\nLemma write_read_word_ne: forall m a1 a2 v,\n    a1 + 4 <= mem_size m ->\n    a1 mod 4 = 0 ->\n    a2 + 4 <= mem_size m ->\n    a2 mod 4 = 0 ->\n    a2 <> a1 ->\n    0 <= a1 ->\n    0 <= a2 ->\n    read_word (write_word m a1 v) a2 = read_word m a2.\nProof.\n  intros. unfold write_word, read_word in *.\n  rename H4 into H6, H5 into H7.\n  pose proof (diviBy4_implies_diviBy2 _ H0).\n  pose proof (diviBy4_implies_diviBy2 _ H2).\n  f_equal.\n  - rewrite write_read_half_ne.\n    + apply write_read_half_ne; try omega.\n      * rewrite add_mod_r; omega.\n      * intro. subst. rewrite Z.add_mod in H0; try omega.\n        rewrite H2 in H0.\n        simpl in H0.\n        discriminate.\n    + rewrite write_half_preserves_mem_size; omega.\n    + rewrite add_mod_r; omega.\n    + rewrite write_half_preserves_mem_size; omega.\n    + rewrite add_mod_r; omega.\n    + omega.\n    + omega.\n    + omega.\n  - rewrite write_read_half_ne.\n    + apply write_read_half_ne; omega.\n    + rewrite write_half_preserves_mem_size; omega.\n    + rewrite Z.add_mod by omega.\n      rewrite H4.\n      reflexivity.\n    + rewrite write_half_preserves_mem_size; omega.\n    + assumption.\n    + intro. subst. rewrite Z.add_mod in H2; try omega.\n      rewrite H0 in H2.\n      simpl in H2.\n      discriminate.\n    + omega.\n    + assumption.\nQed.\n\nLemma write_word_preserves_mem_size: forall m a v,\n    mem_size (write_word m a v) = mem_size m.\nProof.\n  intros. unfold write_word, mem_size in *.\n  repeat rewrite write_half_preserves_mem_size; unfold mem_size; omega.\nQed.\n\nLemma diviBy8_implies_diviBy4: forall n,\n    n mod 8 = 0 ->\n    n mod 4 = 0.\nProof.\n  intros.\n  apply weaken_alignment; [assumption | omega].\nQed.  \n\nLemma write_read_double_eq: forall m a1 a2 v,\n    a1 + 8 <= mem_size m ->\n    a1 mod 8 = 0 ->\n    a2 = a1 ->\n    0 <= a1 ->\n    read_double (write_double m a1 v) a2 = v.\nProof.\n  intros. subst. unfold write_double, read_double in *.\n  pose proof H.\n  rewrite (write_read_word_eq _ (a1 + 4) (a1 + 4)); try reflexivity; try omega.\n  - rewrite write_read_word_ne; try omega.\n    + rewrite write_read_word_eq; try reflexivity; try omega.\n      * apply (wappend_split 32 32); omega.\n      * apply diviBy8_implies_diviBy4. assumption.\n    + rewrite write_word_preserves_mem_size; omega.\n    + apply diviBy8_implies_diviBy4 in H0. rewrite Z.add_mod by omega.\n      rewrite H0.\n      reflexivity.\n    + rewrite write_word_preserves_mem_size; omega.\n    + apply diviBy8_implies_diviBy4. assumption.\n  - rewrite write_word_preserves_mem_size; omega.\n  - rewrite add_mod_r by omega.\n    apply diviBy8_implies_diviBy4. assumption.\nQed.\n\nLemma write_read_double_ne: forall m a1 a2 v,\n    a1 + 8 <= mem_size m ->\n    a1 mod 8 = 0 ->\n    a2 + 8 <= mem_size m ->\n    a2 mod 8 = 0 ->\n    a2 <> a1 ->\n    0 <= a1 ->\n    0 <= a2 ->\n    read_double (write_double m a1 v) a2 = read_double m a2.\nProof.\n  intros. unfold write_double, read_double in *.\n  rename H4 into H6, H5 into H7.\n  pose proof (diviBy8_implies_diviBy4 _ H0).\n  pose proof (diviBy8_implies_diviBy4 _ H2).\n  f_equal.\n  - rewrite write_read_word_ne.\n    + apply write_read_word_ne; try omega.\n      * rewrite add_mod_r; omega.\n      * intro. subst. rewrite Z.add_mod in H0; try omega.\n        rewrite H2 in H0.\n        simpl in H0.\n        discriminate.\n    + rewrite write_word_preserves_mem_size; omega.\n    + rewrite add_mod_r; omega.\n    + rewrite write_word_preserves_mem_size; omega.\n    + rewrite add_mod_r; omega.\n    + omega.\n    + omega.\n    + omega.\n  - rewrite write_read_word_ne.\n    + apply write_read_word_ne; omega.\n    + rewrite write_word_preserves_mem_size; omega.\n    + rewrite Z.add_mod by omega.\n      rewrite H4.\n      reflexivity.\n    + rewrite write_word_preserves_mem_size; omega.\n    + assumption.\n    + intro. subst. rewrite Z.add_mod in H2; try omega.\n      rewrite H0 in H2.\n      simpl in H2.\n      discriminate.\n    + omega.\n    + omega.\nQed.\n\nLemma write_double_preserves_mem_size: forall m a v,\n    mem_size (write_double m a v) = mem_size m.\nProof.\n  intros. unfold write_double, mem_size in *.\n  repeat rewrite write_word_preserves_mem_size; unfold mem_size; omega.\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/ListMemoryZAddr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6547600727833451}}
{"text": "Require Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Lists.List.\nRequire Import Basics.\nRequire Import Logic.JMeq.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(** Module defining fingertrees ala Hinze and Paterson and verifying them*)\n\nModule FingerTrees.\n\n  Import List.ListNotations.\n\n  Open Scope list_scope.\n\n  (** ============================================================================== *)\n  (**                                 type classes                                   *)\n  (** ============================================================================== *)\n\n  (** A Functor typeclass *)\n  Class functor F := Functor {\n    map : forall {A B : Type}, (A -> B) -> F A -> F B;\n\n    map_id : forall {A : Type} (f : F A), map (fun x => x) f = f;\n    map_comp : forall {A B C : Type} (f : B -> C) (g : A -> B) (x : F A),\n        map (fun x => f (g x)) x = (fun x => map f (map g x)) x;\n  }.\n\n  (** Something that can be reduced *)\n  Class reduce F := Reduce {\n    reducer : forall {A} {B}, (A -> B -> B) -> (F A -> B -> B);\n    reducel : forall {A} {B}, (B -> A -> B) -> (B -> F A -> B);\n  }.\n\n  (** ============================================================================== *)\n  (**                                 list instances                                 *)\n  (** ============================================================================== *)\n\n  (** All reducibles can be folded into a list *)\n  Definition to_list {F: Type -> Type} {r: reduce F} {A : Type} (s : F A) : list A :=\n    reducer cons s nil.\n\n  (** List can be reduced using fold_right/left *)\n  Instance list_reduce : reduce list :=\n    {|\n      reducer := fun _ _ fn xs z => List.fold_right fn z xs;\n      reducel := fun _ _ fn z xs => List.fold_left fn xs z;\n    |}.\n\n  (** Lists are functors *)\n  Instance list_functor : functor list :=\n    {|\n      map := @List.map;\n    |}.\n  Proof.\n    - intros. induction f; [reflexivity|]. simpl. rewrite IHf. reflexivity.\n    - induction x; [reflexivity|]. simpl. rewrite IHx. reflexivity.\n  Qed.\n\n  (** ============================================================================== *)\n  (**                                    node                                        *)\n  (** ============================================================================== *)\n\n  (** A node contains two or three values *)\n  Inductive node (A:Type) : Type :=\n  | node2: A -> A -> node A\n  | node3: A -> A -> A -> node A.\n\n  Arguments node2 {A} _ _.\n  Arguments node3 {A} _ _ _.\n\n  (** Right-reduce a node *)\n  Definition nd_reducer {A B : Type} : (A -> B -> B) -> node A -> B -> B :=\n    fun op nd z => match nd with\n                | node2 a b => op a (op b z)\n                | node3 a b c => op a (op b (op c z))\n                end.\n\n  (** Left-reduce a node *)\n  Definition nd_reducel {A B : Type} : (B -> A -> B) -> B -> node A -> B :=\n    fun op z nd => match nd with\n                | node2 b a => op (op z b) a\n                | node3 c b a => op (op (op z c) b) a\n                end.\n\n  (** Nodes can be reduced *)\n  Instance node_reduce : reduce node :=\n    {|\n      reducer := @nd_reducer;\n      reducel := @nd_reducel;\n    |}.\n\n  (** Right-reducing a node over an accumulator that is the concatenation\n      of two lists xs and ys is the same as using just xs as the accumulator\n      and then appending ys. I.e. reducer does not touch the accumulator.\n      Only works if the operator associates over append.\n  *)\n  Lemma nd_reducer_app :\n    forall {A B} (op : A -> list B -> list B) (a : node A) (xs ys : list B),\n      (forall a (xs ys : list B), op a (xs ++ ys) = (op a xs) ++ ys) ->\n      nd_reducer op a (xs ++ ys) = nd_reducer op a xs ++ ys.\n  Proof.\n    intros. destruct a; simpl; rewrite ?H; reflexivity.\n  Qed.\n\n  Definition nd_map {A B : Type} (fn : A -> B) (x : node A) :=\n    match x with\n    | node2 a b => node2 (fn a) (fn b)\n    | node3 a b c => node3 (fn a) (fn b) (fn c)\n    end.\n\n  (** Nodes are functors *)\n  Instance node_functor : functor node :=\n    {|\n      map := @nd_map\n    |}.\n  Proof.\n    - intros. destruct f; reflexivity.\n    - intros. destruct x; reflexivity.\n  Defined.\n\n  (** ============================================================================== *)\n  (**                                    digit                                       *)\n  (** ============================================================================== *)\n\n  (** Digits hold one to four elements *)\n  Inductive digit (A:Type) : Type :=\n  | one : A -> digit A\n  | two : A -> A -> digit A\n  | three : A -> A -> A -> digit A\n  | four : A -> A -> A -> A -> digit A.\n\n  Arguments one {A} _.\n  Arguments two {A} _ _.\n  Arguments three {A} _ _ _.\n  Arguments four {A} _ _ _ _.\n\n  (** Digits can be reduced right *)\n  Definition digit_reducer {A B : Type} (op: A -> B -> B) dg z :=\n    match dg with\n    | one a => op a z\n    | two a b => op a (op b z)\n    | three a b c => op a (op b (op c z))\n    | four a b c d => op a (op b (op c (op d z)))\n    end.\n\n  (** Digits can be reduced left *)\n  Definition digit_reducel {A B : Type} (op: B -> A -> B) z dg :=\n    match dg with\n    | one a => op z a\n    | two b a => op (op z b) a\n    | three c b a => op (op (op z c) b) a\n    | four d c b a => op (op (op (op z d) c) b) a\n    end.\n\n  (** Digits can be reduced *)\n  Instance digit_reduce : reduce digit :=\n    {|\n      reducer := @digit_reducer;\n      reducel := @digit_reducel;\n    |}.\n\n  Definition digit_map {A B : Type} (fn : A -> B) (x : digit A) :=\n    match x with\n    | one a => one (fn a)\n    | two a b => two (fn a) (fn b)\n    | three a b c => three (fn a) (fn b) (fn c)\n    | four a b c d => four (fn a) (fn b) (fn c) (fn d)\n    end.\n\n  (** Digits are functors *)\n  Instance digit_functor : functor digit :=\n    {|\n      map := @digit_map;\n    |}.\n  Proof.\n    - intros. destruct f; reflexivity.\n    - intros. destruct x; reflexivity.\n  Defined.\n\n  (** Convert a node to a digit *)\n  Fixpoint to_digit {A:Type} (nd:node A) : digit A :=\n    match nd with\n    | node2 a b => two a b\n    | node3 a b c => three a b c\n    end.\n\n  (** ============================================================================== *)\n  (**                                    fingertree                                  *)\n  (** ============================================================================== *)\n\n  (** A fingertree is either empty, a single thing, or a deeper fingertree\n      along with a prefix digit and a suffix digit *)\n  Inductive fingertree (A:Type) : Type :=\n  | empty : fingertree A\n  | single : A -> fingertree A\n  | deep : digit A -> fingertree (node A) -> digit A -> fingertree A.\n\n  Arguments empty {A}.\n  Arguments single {A} _.\n  Arguments deep {A} _ _ _.\n\n  Example ft_ex_01 : fingertree nat :=\n    deep (two 1 2)\n         (deep (two (node2 3 4) (node2 5 6))\n               empty\n               (two (node3 7 8 9) (node2 10 11))\n         )\n         (three 12 13 14).\n\n  (** Fingertrees can be reduced right *)\n  Fixpoint ft_reducer {A:Type} {B:Type}\n             (op: A -> B -> B) (tr : fingertree A) (z : B) : B :=\n      match tr with\n      | empty => z\n      | single x => op x z\n      | deep pr m sf =>\n        let op' := reducer op in\n        let op'' := ft_reducer (reducer op) in\n        op' pr (op'' m (op' sf z))\n      end.\n\n\n  (** Fingertrees can be reduced left *)\n  Fixpoint ft_reducel {A:Type} {B:Type}\n           (op: B -> A -> B) (z : B) (tr : fingertree A) : B :=\n      match tr with\n      | empty => z\n      | single x => op z x\n      | deep pr m sf =>\n        let op'  := reducel op in\n        let op'' := ft_reducel (reducel op) in\n        op' (op'' (op' z pr) m) sf\n      end.\n\n  (** Fingertrees can be reduced *)\n  Instance fingertree_reduce : reduce fingertree :=\n    {|\n      reducer := @ft_reducer;\n      reducel := @ft_reducel;\n    |}.\n\n  Example ft_ex_01_to_list : to_list ft_ex_01 = [1;2;3;4;5;6;7;8;9;10;11;12;13;14].\n  Proof. reflexivity. Qed.\n\n  (** You can map over a fingertree *)\n  Fixpoint ft_map {A B : Type} (fn : A -> B) (tr : fingertree A) : fingertree B :=\n    match tr with\n    | empty => empty\n    | single a => single (fn a)\n    | deep pf m sf =>\n      deep (map fn pf)\n            (ft_map (map fn) m)\n            (map fn sf)\n    end.\n\n  (** ID law for functors for fingertrees *)\n  Lemma ft_map_id : forall (A : Type) (tr : fingertree A),\n   ft_map (fun x => x) tr = tr.\n  Proof.\n    Opaque map.\n    induction tr; intros; simpl in *; [reflexivity | reflexivity |].\n    rewrite !map_id.\n    replace (map (fun x : A => x)) with (fun x : node A => x).\n    rewrite IHtr. reflexivity.\n    apply functional_extensionality. intros. symmetry. apply map_id.\n    Transparent map.\n  Qed.\n\n  (** Composition law for functors for fingertrees *)\n  Lemma ft_map_comp {A B C: Type} (f: B -> C) (g: A -> B) (tr: fingertree A) :\n    ft_map (fun x => f (g x)) tr = ft_map f (ft_map g tr).\n  Proof.\n    Opaque map.\n    intros. generalize dependent B. generalize dependent C.\n    induction tr; intros; simpl in *; [reflexivity | reflexivity |].\n    rewrite map_comp with (x := d).\n    rewrite map_comp with (x := d0).\n    replace (map (fun x : A => f (g x))) with (fun n : node A => map f (map g n)).\n    rewrite (IHtr _ _ (map f) (map g)). reflexivity.\n    apply functional_extensionality.\n    intros. symmetry. apply map_comp.\n    Transparent map.\n  Qed.\n\n  (** Fingertrees are functors *)\n  Instance ft_functor : functor fingertree :=\n    {|\n      map := @ft_map;\n      map_id := ft_map_id;\n      map_comp := @ft_map_comp;\n    |}.\n\n\n  (** Tree equivalence relation!\n      Two trees are equal if they reduce to the same thing no matter what\n      operator.\n   *)\n  Definition tree_eq {A : Type} (t1 t2 : fingertree A) :=\n    forall (B : Type) (acc : B) (op : A -> B -> B), reducer op t1 acc = reducer op t2 acc.\n\n  Notation \"t1 >=< t2\" := (tree_eq t1 t2)\n                            (at level 90, right associativity).\n\n  (** ============================================================================== *)\n  (**                                    adding                                      *)\n  (** ============================================================================== *)\n\n  (** Add to the left of a fingertree *)\n  Fixpoint addl {A:Type} (a:A) (tr:fingertree A) : fingertree A  :=\n    match tr with\n    | empty => single a\n    | single b => deep (one a) empty (one b)\n    | deep (four b c d e) m sf => deep (two a b) (addl (node3 c d e) m) sf\n    | deep (three b c d) m sf => deep (four a b c d) m sf\n    | deep (two b c) m sf => deep (three a b c) m sf\n    | deep (one b) m sf => deep (two a b) m sf\n    end.\n\n  (** Add to the right of a fingertree *)\n  Fixpoint addr {A:Type} (tr:fingertree A) (a:A) : fingertree A  :=\n    match tr with\n    | empty => single a\n    | single b => deep (one b) empty (one a)\n    | deep pr m (four e d c b) => deep pr (addr m (node3 e d c)) (two b a)\n    | deep pr m (three e c b) => deep pr m (four e c b a)\n    | deep pr m (two c b) => deep pr m (three c b a)\n    | deep pr m (one b) => deep pr m (two b a)\n    end.\n\n  (** Notation for adding to the left and right of fingertrees *)\n  Notation \"x <| t\" := (addl x t)\n                     (at level 60, right associativity).\n  Notation \"x |> t\" := (addr x t)\n                     (at level 61, left associativity).\n\n  (** Mapping f over (x <| tr) is same as applying x to f and then adding it\n      to map f tr.\n   *)\n  Lemma map_addl {A : Type} (tr : fingertree A) :\n    forall B (f: A -> B) x, map f (x <| tr) = f x <| map f tr.\n  Proof.\n    unfold \"<|\". induction tr; intros; simpl in *; try reflexivity.\n    - unfold map. destruct digit_functor.\n      destruct d, d0; simpl; try (rewrite IHtr); try reflexivity.\n  Qed.\n\n  (** As above but with adding to the right *)\n  Lemma map_addr {A : Type} (tr : fingertree A) :\n    forall B (f: A -> B) x, ft_map f (tr |> x) = ft_map f tr |> f x .\n  Proof.\n    induction tr; intros; try reflexivity.\n    destruct d, d0; simpl; try (rewrite IHtr); try reflexivity.\n  Qed.\n\n  (** Add all the things in a reducible value to the left of the tree *)\n  Definition addl' {F: Type -> Type} {r:reduce F} {A:Type} :\n    F A -> fingertree A -> fingertree A :=\n      reducer addl.\n\n  (** Add all the things in a reducible value to the right of the tree *)\n  Definition addr' {F: Type -> Type} {r:reduce F} {A:Type} :\n    fingertree A -> F A -> fingertree A :=\n      reducel addr.\n\n  (** Convert any reducible to a fingertree! *)\n  Definition to_tree {F:Type -> Type} {A:Type} {r:reduce F} (s:F A) :\n    fingertree A := addl' s empty.\n\n\n  (** ============================================================================== *)\n  (**                                  viewing                                       *)\n  (** ============================================================================== *)\n\n  (** View a tree from the left as empty or (an x and the rest of the tree) *)\n  Inductive View_l (S:Type -> Type) (A:Type): Type :=\n  | nil_l : View_l S A\n  | cons_l : A -> S A -> View_l S A.\n\n  Arguments nil_l {S} {A}.\n  Arguments cons_l {S} {A} _ _.\n\n  (** View a tree from the left! *)\n  Fixpoint view_l {A:Type} (tr:fingertree A) : View_l fingertree A :=\n    match tr with\n    | empty => nil_l\n    | single x => cons_l x empty\n    | deep (one x) m sf =>\n      let tail := match view_l m with\n                  | nil_l => to_tree sf\n                  | cons_l a m' => deep (to_digit a) m' sf\n                  end\n      in cons_l x tail\n    | deep (two x y) m sf => cons_l x (deep (one y) m sf)\n    | deep (three x y z) m sf => cons_l x (deep (two y z) m sf)\n    | deep (four x y z u) m sf => cons_l x (deep (three y z u) m sf)\n    end.\n\n  (** Check if a tree is empty (with a boolean) *)\n  Definition is_emptyb {A:Type} (tr:fingertree A) : bool :=\n    match view_l tr with\n    | nil_l => true\n    | cons_l _ _ => false\n    end.\n\n  (** Check if a tree is empty (returning a proposition) *)\n  Definition is_empty {A:Type} (tr:fingertree A) : Prop :=\n    match view_l tr with\n    | nil_l => True\n    | cons_l _ _ => False\n    end.\n\n\n  (** Iff a view of a tree is empty, then it is empty *)\n  Lemma view_l_nil_empty : forall {A : Type} (tr : fingertree A),\n      view_l tr = nil_l <-> tr = empty.\n  Proof.\n    intros. split.\n    - intros. destruct tr; [reflexivity | inversion H |]. simpl in H.\n      destruct d, (view_l tr), d0; inversion H.\n    - intros. destruct tr; [reflexivity | inversion H |].\n      destruct d, (view_l tr), d0; inversion H.\n  Qed.\n\n  (** Converting an empty list to a tree gives an empty tree *)\n  Lemma to_tree_empty : forall {A : Type}, @is_empty A (to_tree []).\n  Proof.\n    intros. simpl. unfold is_empty. destruct (view_l empty) eqn:Heq.\n    - apply I.\n    - inversion Heq.\n  Qed.\n\n  (** Adding something to the left of a tree can never result in an empty tree *)\n  Lemma addl_not_empty : forall {A : Type} (tr : fingertree A) x, ~(addl x tr = empty).\n  Proof.\n    intros A tr x H. induction tr; inversion H.\n    destruct d; inversion H1.\n  Qed.\n\n  (** Adding something to the left of a single can never result in a new single *)\n  Lemma addl_not_2single : forall {A : Type} (x y z : A), ~(addl x (single y) = single z).\n  Proof.\n    intros A x y z H. simpl in H. inversion H.\n  Qed.\n\n  (** Adding something to the right of a tree can never result in an empty tree *)\n  Lemma addr_not_empty : forall {A : Type} (tr : fingertree A) x, ~(addr tr x = empty).\n    intros A tr x H. induction tr; inversion H.\n    destruct d0; inversion H1.\n  Qed.\n\n  (** Viewing the result of adding somehing to a tree can never be nil *)\n  Lemma addl_not_nil : forall {A : Type} (tr : fingertree A) x,\n      ~(view_l (addl x tr) = nil_l).\n  Proof.\n    intros A tr x H. induction tr; inversion H.\n    destruct d; inversion H1.\n  Qed.\n\n  (** Get the left head of a tree *)\n  Definition head_l {A:Type} (a:A) (tr:fingertree A) : A :=\n    match view_l tr with\n    | nil_l => a\n    | cons_l x _ => x\n    end.\n\n  (** Get the left tail of a tree *)\n  Definition tail_l {A:Type} (tr:fingertree A) : fingertree A :=\n    match view_l tr with\n    | nil_l => tr\n    | cons_l _ tl => tl\n    end.\n\n  (** If you add an x to the left of a tree tr and then convert it to a list, it is\n     the same as converting tr to a list and then consing x.\n     This is the general version of the above, i.e\n     to_list (x <| tr) = x :: (to_list tr) <=>\n     ft_reducer cons (x <| tr) [] = cons x (tr_reducer cons tr [])\n  *)\n  Lemma ft_reducer_addl : forall {A B : Type}\n                         (tr : fingertree A) xs x\n                         (op : A -> B -> B),\n      ft_reducer op (x <| tr) xs = op x (ft_reducer op tr xs).\n  Proof.\n    intros A B tr.\n    induction tr; intros; try reflexivity.\n    destruct d; try reflexivity.  simpl.\n    do 2 (apply f_equal).\n    apply (IHtr (digit_reducer op d0 xs) (node3 a0 a1 a2) (nd_reducer op)).\n  Qed.\n\n  (** Converting a list to a tree and then back again gives you the same list.\n      I.e. to_list and to_tree are inverses of each other (on lists).\n      So there is an isomorphism between (fingertree A) and (list A).\n   *)\n  Theorem to_tree_to_list_id : forall {A:Type} (xs : list A),\n      to_list (to_tree xs) = xs.\n  Proof.\n    intros. induction xs; [reflexivity |].\n    simpl. rewrite (ft_reducer_addl _ [] a _).\n    apply f_equal. simpl in IHxs. assumption.\n  Qed.\n\n  (** ============================================================================== *)\n  (**                                    append                                      *)\n  (** ============================================================================== *)\n\n\n  (**\n     We need this data structure to represent lists that can be converted into\n     lists of nodes in a total way.\n  **)\n  Inductive app3_list (A : Type) : Type :=\n  | app3_two   : A -> A -> app3_list A\n  | app3_three : A -> A -> A -> app3_list A\n  | app3_four  : A -> A -> A -> A -> app3_list A\n  | app3_more  : A -> A -> A -> app3_list A -> app3_list A.\n\n  Arguments app3_two {A} _ _.\n  Arguments app3_three {A} _ _ _.\n  Arguments app3_four {A} _ _ _ _.\n  Arguments app3_more {A} _ _ _ _.\n\n  (** app3_lists can be right-reduced *)\n  Fixpoint a3_reducer {A B : Type} (op : A -> B -> B) (xs : app3_list A) (ys : B) : B :=\n    match xs with\n    | app3_two a b => op a (op b ys)\n    | app3_three a b c => op a (op b (op c ys))\n    | app3_four a b c d => op a (op b (op c (op d ys)))\n    | app3_more a b c xs' => op a (op b (op c (a3_reducer op xs' ys)))\n    end.\n\n  (** app3_lists can be left-reduced *)\n  Fixpoint a3_reducel {A B : Type} (op : B -> A -> B) (ys : B) (xs : app3_list A) : B :=\n    match xs with\n    | app3_two a b => op (op ys a) b\n    | app3_three a b c => op (op (op ys a) b) c\n    | app3_four a b c d => op (op (op (op ys a) b) c) d\n    | app3_more a b c xs' => a3_reducel op (op (op (op ys a) b) c) xs'\n    end.\n\n  (** app3_lists are reducible *)\n  Instance a3_reduce : reduce app3_list :=\n    {|\n      reducer := @a3_reducer;\n      reducel := @a3_reducel;\n    |}.\n\n  (**\n     Yeah, this is a doosie, but I don't know how to define it in more succint terms\n     while still retaining its total properties.\n     In the original paper, this is much simpler since we do not have to use an\n     app3_list and can write partial functions, but we cannot do proper proofs\n     if we do this (believe me, I've wasted many hours on trying).\n   **)\n  Fixpoint dig_app3 {A:Type} (d1 : digit A) (xs : list A) (d2 : digit A): app3_list A :=\n    match d1, xs, d2 with\n    | one a,        [], one b        => app3_two a b\n    | one a,        [], two b c      => app3_three a b c\n    | one a,        [], three b c d  => app3_four a b c d\n    | one a,        [], four b c d e => app3_more a b c (app3_two d e)\n\n    | two a b,      [], one c        => app3_three a b c\n    | two a b,      [], two c d      => app3_four a b c d\n    | two a b,      [], three c d e  => app3_more a b c (app3_two d e)\n    | two a b,      [], four c d e f => app3_more a b c (app3_three d e f)\n\n    | three a b c,  [], one d        => app3_four a b c d\n    | three a b c,  [], two d e      => app3_more a b c (app3_two d e)\n    | three a b c,  [], three d e f  => app3_more a b c (app3_three d e f)\n    | three a b c,  [], four d e f g => app3_more a b c (app3_four d e f g)\n\n    | four a b c d, [], one e        => app3_more a b c (app3_two d e)\n    | four a b c d, [], two e f      => app3_more a b c (app3_three d e f)\n    | four a b c d, [], three e f g  => app3_more a b c (app3_four d e f g)\n    | four a b c d, [], four e f g h => app3_more a b c (app3_more d e f (app3_two g h))\n\n    | one a,        (x :: xs), _     => dig_app3 (two a x) xs d2\n    | two a b,      (x :: xs), _     => dig_app3 (three a b x) xs d2\n    | three a b c,  (x :: xs), _     => dig_app3 (four a b c x) xs d2\n    | four a b c d, (x :: xs), _     => app3_more a b c (dig_app3 (two d x) xs d2)\n    end.\n\n  (**\n     group a list of A's into a list of nodes of A'\n     uses the app3_list data type to ensure totality and make proofs\n     about nodes possible\n   **)\n  Fixpoint nodes {A : Type} (xs : app3_list A) : list (node A) :=\n    match xs with\n    | app3_two a b        => [node2 a b]\n    | app3_three a b c    => [node3 a b c]\n    | app3_four a b c d   => [node2 a b; node2 c d]\n    | app3_more a b c xs' => node3 a b c :: nodes xs'\n    end.\n\n  (**\n     append two fingertrees with a list of \"remainder-values\".\n     This does all the hard work of append. Should be amortized logarithmic time\n   **)\n  Fixpoint app3 {A:Type} (tr1:fingertree A) (rem : list A) (tr2:fingertree A)\n    : fingertree A :=\n    match tr1, tr2 with\n    | empty, _ => addl' rem tr2\n    | _, empty => addr' tr1 rem\n    | single x, _ => x <| addl' rem tr2\n    | _, single x => addr' tr1 rem |> x\n    | deep pr1 m1 sf1, deep pr2 m2 sf2 =>\n        let a3l := dig_app3 sf1 rem pr2 in\n        deep pr1 (app3 m1 (nodes a3l) m2) sf2\n    end.\n\n  (** Two append two trees, we just call app3 with an empty remainder-list *)\n  Definition append {A:Type}\n           (tr1 : fingertree A) (tr2 : fingertree A) : fingertree A :=\n    app3 tr1 [] tr2.\n\n\n  Notation \"t1 >< t2\" := (append t1 t2)\n                     (at level 62, left associativity).\n\n\n  (** ============================================================================== *)\n  (**                                 proving append                                 *)\n  (** ============================================================================== *)\n\n  (** Right-reducing a digit over an accumulator that is the concatenation\n      of two lists xs and ys is the same as using just xs as the accumulator\n      and then appending ys. I.e. reducer does not touch the accumulator.\n      Only works if the operator associates over append.\n  *)\n  Theorem digit_reducer_app :\n    forall {A B : Type} (xs ys : list B) d (op : A -> list B -> list B),\n      (forall a xs ys, op a (xs ++ ys) = (op a xs) ++ ys) ->\n      (digit_reducer op d (xs ++ ys) = digit_reducer op d xs ++ ys).\n  Proof.\n    intros.\n    destruct d; simpl; rewrite ?H; reflexivity.\n  Qed.\n\n  (** Same as above, but with adding to the right of the list/tree *)\n  Lemma ft_reducer_addr : forall {A B : Type}\n                         (tr : fingertree A) xs x\n                         (op : A -> B -> B),\n      ft_reducer op (tr |> x) xs = (ft_reducer op tr (op x xs)).\n  Proof.\n    intros A B tr.\n    induction tr; intros; simpl; [reflexivity | reflexivity |].\n    destruct d0; simpl; try reflexivity.\n    rewrite (IHtr (op a2 (op x xs)) (node3 a a0 a1) (nd_reducer op)).\n    reflexivity.\n  Qed.\n\n  Lemma addl_addr_assoc {A : Type} (tr : fingertree A) :\n    forall x y, x <| (tr |> y) >=< (x <| tr) |> y.\n  Proof.\n    unfold \">=<\". induction tr; simpl in *; intros; [reflexivity | reflexivity |].\n    destruct d0,d; simpl in *; try reflexivity.\n    - apply f_equal. apply f_equal.\n      rewrite IHtr. reflexivity.\n  Qed.\n\n  (**\n     Reducing a fingertree with an accumulator that is the concatenation of two\n     lists xs and ys, is the same as just reducing with xs and then appending ys\n     given that the operation we use for reduction has the same property\n   **)\n  Theorem ft_reducer_app :\n    forall {A : Type} {F : Type -> Type}\n      (tr : fingertree (F A)) (xs ys : list A)\n      (op : F A -> list A -> list A),\n      (forall a (xs ys : list A), op a (xs ++ ys) = (op a xs) ++ ys) ->\n      ft_reducer op tr (xs ++ ys) = (ft_reducer op tr xs) ++ ys.\n  Proof.\n    intros A F tr. induction tr; intros; [reflexivity | apply H |]; simpl.\n    - rewrite (digit_reducer_app xs ys d0 op H).\n      rewrite IHtr.\n      + remember (ft_reducer (nd_reducer op) tr (digit_reducer op d0 xs)) as xs'.\n        apply (digit_reducer_app xs' ys d op H).\n      + intros. apply nd_reducer_app. assumption.\n  Qed.\n\n  (** Helper lemma for second single of ft_reducer_addl' *)\n  Lemma ft_reducer_addl'_single : forall {A B : Type} a op (xs : list A) (ys : B),\n      ft_reducer op (addl' xs (single a)) ys =\n      ft_reducer op (to_tree xs) (op a ys).\n  Proof.\n    induction xs.\n    - intros. reflexivity.\n    - intros. simpl. rewrite ft_reducer_addl.\n      simpl in IHxs. rewrite (ft_reducer_addl _ (op a ys) a0).\n      rewrite IHxs. reflexivity.\n  Qed.\n\n  (** Helper lemma for second deep of ft_reducer_addl' *)\n  Lemma ft_reducer_addl'_deep : forall {A B : Type} op (xs : list A) (ys : B) pf sf m,\n      ft_reducer op (addl' xs (deep pf m sf)) ys =\n      ft_reducer op (to_tree xs) (ft_reducer op (deep pf m sf) ys).\n  Proof.\n    induction xs.\n    - reflexivity.\n    - intros. simpl in *. rewrite (ft_reducer_addl _ ys a op).\n      remember (\n          digit_reducer op pf (ft_reducer (nd_reducer op) m (digit_reducer op sf ys))\n        ) as ys'.\n      rewrite (ft_reducer_addl _ ys' a op).\n      rewrite IHxs. rewrite Heqys'. reflexivity.\n  Qed.\n\n  (** Adding all elements in xs to the left of a fingertree tr and then\n      reducing the result from the right, is the same as\n      simply reducing the tree-version of xs with an accumulator that\n      is tr reduced. Can be seen as another form of the lemma:\n      reducer op (tr1 >< tr2) xs = reducer op tr1 (reducer op tr2 xs)\n   *)\n  Theorem ft_reducer_addl' : forall {A B : Type} op (xs : list A) (ys : B) (tr : fingertree A),\n      ft_reducer op (addl' xs tr) ys =\n      ft_reducer op (to_tree xs) (ft_reducer op tr ys).\n  Proof.\n    destruct tr.\n    - reflexivity.\n    - rewrite ft_reducer_addl'_single. reflexivity.\n    - rewrite ft_reducer_addl'_deep. reflexivity.\n  Qed.\n\n  (** Same as above, but with addr' instead of addl' *)\n  Theorem ft_reducer_addr' : forall {A B : Type} op (xs : list A) (ys : B) (tr : fingertree A),\n      ft_reducer op (addr' tr xs) ys =\n      ft_reducer op tr (ft_reducer op (to_tree xs) ys).\n  Proof.\n    induction xs; intros; simpl in *; [reflexivity |].\n    destruct tr; simpl.\n    - rewrite (ft_reducer_addl (fold_right addl empty xs) ys a op).\n      rewrite IHxs. reflexivity.\n    - rewrite IHxs. simpl. rewrite (ft_reducer_addl _ ys a op). reflexivity.\n    - rewrite IHxs. destruct d0;\n                      simpl; rewrite (ft_reducer_addl _ ys a op); try reflexivity.\n      rewrite (ft_reducer_addr tr _ (node3 a0 a1 a2) (nd_reducer op)).\n      simpl. reflexivity.\n  Qed.\n\n  (** Helper lemma *)\n  Lemma ft_reducer_deep : forall {A B : Type} op (m : fingertree (node A)) pf sf (ys : B),\n      ft_reducer op (deep pf m sf) ys =\n      digit_reducer op pf (ft_reducer (nd_reducer op) m (digit_reducer op sf ys)).\n  Proof.\n    intros. reflexivity.\n  Qed.\n\n  (**\n     Converting an app3_list of as to a list of node of As and then\n     reducing the list of nodes with a node reducer, is the same as\n     simply reducing the original app3_list.\n  **)\n  Lemma nodes_reducer : forall {A B : Type} (xs : app3_list A) (op : A -> B -> B) ys,\n      reducer (nd_reducer op) (nodes xs) ys =\n      reducer op xs ys.\n  Proof.\n    induction xs; intros; simpl in *; try reflexivity.\n    rewrite IHxs. reflexivity.\n  Qed.\n\n  (** Same as above, but with to_tree injected *)\n  Lemma nodes_to_list : forall {A B : Type} xs (op : A -> B -> B) ys,\n      reducer (nd_reducer op) (to_tree (nodes xs)) ys =\n      reducer op (to_tree xs) ys.\n  Proof.\n    intros A B xs. induction xs; intros; simpl in *; try reflexivity.\n    rewrite (ft_reducer_addl _ _ (node3 a a0 a1) _). simpl.\n    rewrite 3!(ft_reducer_addl _ _ _ op). rewrite IHxs. reflexivity.\n  Qed.\n\n  (** Helper lemma. *)\n  Lemma dig_app3_to_list : forall {A B : Type}\n                             (m : list A) (op : A -> B -> B) (pf sf : digit A) (ys : B),\n      ft_reducer (nd_reducer op) (to_tree (nodes (dig_app3 pf m sf))) ys =\n      digit_reducer op pf (ft_reducer op (to_tree m) (digit_reducer op sf ys)).\n  Proof.\n    intros A B. induction m; intros.\n    - destruct pf, sf; try reflexivity.\n    - simpl. destruct pf; simpl in *;\n               try (rewrite IHm; simpl; rewrite (ft_reducer_addl _ _ a _); reflexivity).\n      rewrite (ft_reducer_addl _ _ (node3 a0 a1 a2) _). simpl.\n      rewrite (ft_reducer_addl _ _ a _ ). do 3 (apply f_equal).\n      simpl in *.  rewrite IHm. reflexivity.\n  Qed.\n\n\n  (**\n     Reducing over app3 tr1 xs tr2 \"distributes\".\n     So reducing over appending two trees tr1 and tr2 with some remainder xs,\n     is the same as reducing over tr1 with the result of reducing over xs\n     with the result of reducing over tr2 with ys as the accumulator.\n  **)\n  Theorem app3_to_list :\n    forall {A B:Type} (op : A -> B -> B) (tr1 tr2 : fingertree A) xs (acc : B),\n    ft_reducer op (app3 tr1 xs tr2) acc =\n    ft_reducer op tr1 (ft_reducer op (to_tree xs) (ft_reducer op tr2 acc)).\n  Proof.\n    intros A B op tr1.\n    Opaque addl' addr' to_tree. induction tr1 as [| A a | A pf1 m1 IH sf1 ]; intros.\n    - simpl. rewrite (ft_reducer_addl' op xs acc tr2). reflexivity.\n    - destruct tr2 as [| a0 | pf m sf]; simpl.\n      + rewrite (ft_reducer_addr'). reflexivity.\n      + rewrite (ft_reducer_addl _ acc a op).\n        rewrite (ft_reducer_addl'_single a0 op xs). reflexivity.\n      + rewrite (ft_reducer_addl _ acc a op).\n        rewrite (ft_reducer_addl'_deep op xs acc pf sf m).\n        reflexivity.\n    - destruct tr2 as [| a | pf2 m2 sf2 ].\n      + simpl. rewrite ft_reducer_addr'. reflexivity.\n      + simpl. rewrite (ft_reducer_addr _ _ a op).\n        rewrite ft_reducer_addr'. reflexivity.\n      + simpl in *. rewrite IH. do 2 (apply f_equal).\n        rewrite (@dig_app3_to_list A B). reflexivity.\n        Transparent addr' addl' to_tree.\n  Qed.\n\n  (**\n     Theorem!\n     Appending to trees and converting the to lists is the same as converting\n     them to lists separately and appending the lists together.\n   *)\n  Theorem tree_append_hom : forall {A:Type} (tr1 : fingertree A) (tr2 : fingertree A),\n    to_list (tr1 >< tr2) = to_list tr1 ++ to_list tr2.\n  Proof.\n    intros A tr1 tr2. simpl. unfold \"><\". rewrite app3_to_list. simpl.\n    rewrite <- (ft_reducer_app tr1 ); [reflexivity |].\n    intros. reflexivity.\n  Qed.\n\n  (**\n     Theorem!\n     Appending two trees is associative with respect to to_list\n  *)\n  Theorem tree_append_assoc : forall {A : Type} (tr1 tr2 tr3 : fingertree A),\n      (tr1 >< (tr2 >< tr3)) >=< ((tr1 >< tr2) >< tr3).\n  Proof.\n    intros A B tr1. unfold \">=<\". unfold \"><\".\n    induction tr1; intros; rewrite ?app3_to_list; reflexivity.\n  Qed.\n\n  (** Same as above, but with to_list *)\n  Corollary tree_append_assoc_to_list :\n    forall {A B : Type} (tr1 tr2 tr3 : fingertree A),\n      to_list (tr1 >< (tr2 >< tr3)) = to_list ((tr1 >< tr2) >< tr3).\n  Proof.\n    intros. simpl. apply tree_append_assoc.\n  Qed.\n\n  (** Same as above, but with sums *)\n  Corollary tree_append_assoc_sum :\n    forall {A : Type} (tr1 tr2 tr3 : fingertree nat),\n      reducer plus (tr1 >< (tr2 >< tr3)) 0 = reducer plus ((tr1 >< tr2) >< tr3) 0.\n  Proof.\n    intros. simpl. apply tree_append_assoc.\n  Qed.\n\n  (** ============================================================================== *)\n  (**                                    reverse                                     *)\n  (** ============================================================================== *)\n\n  (** You can reverse a node *)\n  Definition reverse_node {A: Type}\n            (f: A -> A) (n: node A): node A  :=\n    match n with\n    | (node2  a b)  => node2 (f b) (f a)\n    | (node3 a b c) => node3 (f c) (f b) (f a)\n    end.\n\n  (** You can reverse a digit *)\n  Definition reverse_digit {A: Type}\n           (f: A -> A) (d: digit A): digit A  :=\n    match d with\n    | one a        => one (f a)\n    | two a b      => two (f b) (f a)\n    | three a b c  => three (f c) (f b) (f a)\n    | four a b c d => four (f d) (f c) (f b) (f a)\n    end.\n\n  (** You can reverse a fingertree *)\n  Fixpoint reverse_tree {A: Type}\n           (f: A -> A)(tr: fingertree A) : fingertree A :=\n    match tr with\n    | empty        => empty\n    | single x     => single (f x)\n    | deep pr m sf =>\n      deep (reverse_digit f sf)\n           (reverse_tree (reverse_node f) m)\n           (reverse_digit f pr)\n    end.\n\n  (** the identity function *)\n  Definition ident {A:Type} (x:A) :=  x.\n\n  (** Reverse a tree by calling reverse_tree starting with the identity function *)\n  Definition reverse {A: Type} : fingertree A -> fingertree A :=\n    reverse_tree ident.\n\n  (** Some examples *)\n  Example reverse_ex01 :\n     reverse (single 1)  = single 1.\n  Proof. reflexivity. Qed.\n\n  Example reverse_ex02:forall (A : Type),\n      reverse (@empty A)  = (@empty A).\n  Proof. reflexivity. Qed.\n\n  Example reverse_ex03 :\n    reverse (deep (two 0 1) (single (node2 2 3)) (three 4 5 6)) =\n            deep (three 6 5 4) (single (node2 3 2)) (two 1 0).\n  Proof. unfold reverse. unfold reverse_tree. unfold reverse_digit.\n         simpl. reflexivity. Qed.\n\n  (** ============================================================================== *)\n  (**                               proving reverse                                  *)\n  (** ============================================================================== *)\n\n  (** Reversing (x <| tr) is the same as reversing tr and adding x to the right*)\n  Lemma reverse_addl {A : Type} (tr : fingertree A) :\n    forall x fn, reverse_tree fn (x <| tr) = reverse_tree fn tr |> fn x.\n  Proof.\n    unfold reverse. induction tr; simpl in *; intros; try reflexivity.\n    destruct d; try reflexivity.\n    simpl in *. rewrite IHtr. reflexivity.\n  Qed.\n\n  (**\n     Theorem!\n     Reversing a tree twice gives you an equivalent tree\n   *)\n  Theorem reverse_involutive {A B : Type} (tr : fingertree A) :\n    forall fn (H : forall x, fn (fn x) = x),\n          (reverse_tree fn (reverse_tree fn tr)) = tr.\n  Proof.\n    induction tr as [| A a | A pf m IH sf] ; intros; simpl in *; [reflexivity | |].\n    - rewrite H. reflexivity.\n    - rewrite IH.\n      + destruct pf, sf; simpl in *;\n          rewrite !H; reflexivity.\n      + intros. destruct x; simpl; rewrite !H; reflexivity.\n  Qed.\n\n  (** Helper lemma *)\n  Lemma nd_reducer_cons_app {A:Type} : forall (a1 : node A) (xs ys : list A),\n      nd_reducer cons a1 (xs ++ ys) = nd_reducer cons a1 xs ++ ys.\n  Proof. destruct a1; reflexivity. Qed.\n\n  (**\n    Reversing [x <| tr] is the same as just reversing [tr] and adding [fn x]\n    to the right\n  *)\n  Lemma reverse_tree_addl {A : Type} (tr : fingertree A) (x : A) :\n    forall fn, (forall x, fn (fn x) = x) ->\n          reverse_tree fn (x <| tr) = reverse_tree fn tr |> fn x .\n  Proof.\n    induction tr; intros; simpl in *.\n    - reflexivity.\n    - reflexivity.\n    - destruct d; simpl in *; try reflexivity.\n      rewrite IHtr. reflexivity.\n      intros. destruct x0; simpl; rewrite !H; reflexivity.\n  Qed.\n\n  (** [reverse_node] is involutive *)\n  Lemma reverse_node_invol {A : Type} :\n    forall fn (H: forall x, fn (fn x) = x) (n : node A),\n      reverse_node fn (reverse_node fn n) = n.\n  Proof.\n    destruct n; simpl; intros; rewrite !H; reflexivity.\n  Qed.\n\n  (** [reverse_node] is also \"cons-like\" in the way it interacts with [reverse] *)\n  Lemma reverse_node_helper {A B : Type} :\n    forall op fn (H: forall x, fn (fn x) = x)\n      (H0 : forall (a : A) (acc acc' : list B),\n          rev acc' ++ op (fn a) acc = rev (op a acc') ++ acc)\n      (n : node A) acc (acc' : list B),\n      rev acc' ++ nd_reducer op (reverse_node fn n) acc =\n      rev (nd_reducer op n acc') ++ acc.\n  Proof.\n    intros. destruct n; simpl; rewrite !H0; reflexivity.\n  Qed.\n\n  (** reducing a reversed tree to a list is like reducing the tree and\n      then reversing the list (generalized)\n  *)\n  Lemma reverse_reducer\n          {A B : Type} (tr : fingertree A) :\n    forall acc acc' (fn : A -> A) (op : A -> list B -> list B),\n      (forall x, fn (fn x) = x) ->\n      (forall a acc acc', rev acc' ++ op (fn a) acc = rev (op a acc') ++ acc) ->\n      rev acc' ++ reducer op (reverse_tree fn tr) acc =\n      rev (reducer op tr acc') ++ acc.\n  Proof.\n    induction tr; intros.\n    - reflexivity.\n    - simpl. apply H0.\n    - destruct d,d0; simpl in *; rewrite !H0;\n        (rewrite IHtr; [ | apply (reverse_node_invol fn H)\n                         | apply (reverse_node_helper op fn H H0)]);\n        rewrite !H0; reflexivity.\n  Qed.\n\n  (** [cons] is well-behaved with [rev] *)\n  Lemma cons_reverse {A : Type} : forall (a : A) (acc acc' : list A),\n      rev acc' ++ a :: acc = rev (a :: acc') ++ acc.\n  Proof.\n    intros. simpl. rewrite <- app_assoc.\n    replace ([a] ++ acc) with (a :: acc) by reflexivity.\n    reflexivity.\n  Qed.\n\n  (**\n     Theorem!\n     reversing a (tree converted to a list) is the same as\n     is reversing the tree and then converting it to a list.\n   *)\n  Theorem reverse_to_list {A : Type} (tr : fingertree A) :\n    rev (to_list tr) = to_list (reverse tr).\n  Proof.\n    simpl.\n    rewrite <- app_nil_r with (l := rev (ft_reducer cons tr [])).\n    unfold reverse.\n    symmetry.\n    specialize (@reverse_reducer A A tr [] [] ident).\n    unfold ident in *.\n    intros. simpl in H.\n    rewrite H; [|intros; reflexivity | apply cons_reverse ].\n    reflexivity.\n  Qed.\n\n\n  (* ============================================================================== *)\n  (*                      reverse_to_list  with node_lift                           *)\n  (* ============================================================================== *)\n\n  (** Lift a type n times into node *)\n  Fixpoint node_lift (n:nat) (A:Type) : Type :=\n    match n with\n    | O => A\n    | S n' => node (node_lift n' A)\n    end.\n\n  (** Reverse a value of a type lifted into node n times *)\n  Fixpoint rev_lift (n:nat) {A:Type} (fn: A -> A) : (node_lift n A -> node_lift n A) :=\n    match n with\n    | O => fn\n    | S n' => reverse_node (rev_lift n' fn)\n    end.\n\n  (** Reduce a type lifted into node n times *)\n  Fixpoint nd_red_lift {A B : Type} (n:nat) (op : A -> B -> B) :\n    (node_lift n A) -> B -> B :=\n    match n with\n    | O => op\n    | S n' => nd_reducer (nd_red_lift n' op)\n    end.\n\n  (** (node A) lifted into node n times is the same as node (A lifted into node n times).\n      So it describes an unfolding of node_lift.\n   *)\n  Lemma node_lift_eq (A : Type) (n : nat) :\n    node_lift n (node A) = node (node_lift n A).\n  Proof.\n    induction n.\n    - reflexivity.\n    - simpl in *. rewrite IHn. reflexivity.\n  Qed.\n\n  (** Represent as fingertree of nodes by its node-lifted type. *)\n  Program Fixpoint node_lift_tr {A : Type} (n : nat)\n             (tr : fingertree (node_lift n (node A))) :\n    fingertree (node (node_lift n A)) :=\n    match n with\n    | O => _\n    | S n' => _\n    end.\n  Next Obligation.\n    simpl in *. rewrite node_lift_eq in tr. assumption.\n  Defined.\n\n  (** A new induction principle for fingertrees whose types are described in terms of\n      a type [A] lifted [n] times into [node].\n      We cannot prove it, regrettably, because Coq chokes in the induction hypothesis,\n      but we *think* it's consistent.\n   *)\n  Axiom fingertree_lift_ind\n     : forall P : (forall (n : nat) (A : Type), fingertree (node_lift n A) -> Prop),\n       (forall (n:nat) (A : Type), P n A empty) ->\n       (forall (n:nat) (A : Type) (a : node_lift n A), P n A (single a)) ->\n       (forall (n:nat) (A : Type) (d : digit (node_lift n A))\n          (f1 : fingertree (node_lift (S n) A)),\n           P (S n) A f1 -> forall d0 : digit (node_lift n A), P n A (deep d f1 d0)) ->\n       forall (n:nat) (A : Type) (f2 : fingertree (node_lift n A)), P n A f2.\n\n  (** nd_red_lift on cons distributes over append in the accumulator. *)\n  Lemma nd_red_lift_app {A:Type} (n : nat) (x y : node_lift n A) :\n    forall acc1 acc2,\n      nd_red_lift n cons x acc1 ++ nd_red_lift n cons y acc2 =\n      nd_red_lift n cons x (acc1 ++ nd_red_lift n cons y acc2).\n  Proof.\n    induction n; intros; simpl in *.\n    - reflexivity.\n    - destruct x, y; simpl in *; rewrite ?IHn; reflexivity.\n  Qed.\n\n  (** same as above, but specialized to empty lists *)\n  Lemma nd_red_lift_app' {A:Type} (n : nat) (x y : node_lift n A) :\n    forall acc,\n      nd_red_lift n cons x [] ++ nd_red_lift n cons y acc =\n      nd_red_lift n cons x (nd_red_lift n cons y acc).\n  Proof.\n    apply nd_red_lift_app with (acc1 := []).\n  Qed.\n\n  (** same as above, but specialized to a single nd_red_lift *)\n  Lemma nd_red_lift_app'' {A:Type} (n : nat) (x : node_lift n A) :\n    forall xs ys,\n      nd_red_lift n cons x xs ++ ys =\n      nd_red_lift n cons x (xs ++ ys).\n  Proof.\n    induction n; intros; simpl in *.\n    - reflexivity.\n    - destruct x; simpl;\n        rewrite !IHn; reflexivity.\n  Qed.\n\n  (** specialize above *)\n  Lemma nd_red_lift_app''' {A:Type} (n : nat) (x : node_lift n A) :\n    forall ys,\n      nd_red_lift n cons x [] ++ ys =\n      nd_red_lift n cons x ys.\n  Proof.\n    apply nd_red_lift_app''.\n  Qed.\n\n  (**\n     Proof of [reducer cons (reverse_node x) acc = rev (reducer cons x []) ++ acc],\n     but lifted [n] times into [node].\n   *)\n  Lemma nd_red_lift_rev {A : Type} (n : nat) (x : node_lift n A) :\n    forall acc,\n    nd_red_lift n cons (rev_lift n ident x) acc =\n    rev (nd_red_lift n cons x []) ++ acc.\n  Proof.\n    induction n; intros; simpl in *.\n    - unfold ident. reflexivity.\n    - destruct x; simpl in *.\n      + rewrite !IHn. rewrite app_assoc. rewrite <- rev_app_distr.\n        rewrite nd_red_lift_app'''. reflexivity.\n      + rewrite !IHn. rewrite 2!app_assoc. rewrite <- 2!rev_app_distr.\n        rewrite !nd_red_lift_app'''. reflexivity.\n  Qed.\n\n  (**\n     Proof of\n     [rev acc' ++ reducer cons (reverse_node nd) acc =\n     rev (reducer cons nd acc') ++ acc]\n     but lifted to node n times\n   *)\n  Lemma rev_node_lem {A : Type} (n : nat) (nd : node (node_lift n A)) :\n    forall (acc acc' : list A) ,\n      (rev acc') ++ reducer (nd_red_lift n cons) (reverse_node (rev_lift n ident) nd) acc =\n      rev (reducer (nd_red_lift n cons) nd acc') ++ acc.\n  Proof.\n    destruct nd; simpl in *.\n    - induction n; simpl in *; intros.\n      + rewrite <- !app_assoc. reflexivity.\n      +  destruct n0, n1; simpl in *; try (rewrite !IHn; reflexivity);\n         rewrite !IHn;\n           rewrite <- !nd_red_lift_app';\n           remember (nd_red_lift n cons n1 []) as n1s;\n           remember (nd_red_lift n cons n2 []) as n2s;\n           remember (nd_red_lift n cons n3 []) as n3s;\n           remember (nd_red_lift n cons n4 acc') as n4s;\n           rewrite <- nd_red_lift_app''' with (x := n0);\n           rewrite rev_app_distr with (x := nd_red_lift n cons n0 []);\n           rewrite <- !app_assoc;\n           apply f_equal; apply nd_red_lift_rev.\n    - induction n; simpl in *; intros.\n      + rewrite <- !app_assoc. reflexivity.\n      +  destruct n0, n1, n2; simpl in *; try (rewrite !IHn; reflexivity);\n         rewrite !IHn;\n           rewrite <- !nd_red_lift_app';\n           (* remember (nd_red_lift n cons n1 []) as n1s; *)\n           (* remember (nd_red_lift n cons n2 []) as n2s; *)\n           (* remember (nd_red_lift n cons n3 []) as n3s; *)\n           (* remember (nd_red_lift n cons n4 []) as n4s; *)\n           (* remember (nd_red_lift n cons n5 []) as n5s; *)\n           (* remember (nd_red_lift n cons n6 []) as n6s; *)\n           try (remember (nd_red_lift n cons n7 acc') as n7s);\n           rewrite <- nd_red_lift_app''' with (x := n0);\n           try (rewrite <- nd_red_lift_app''' with (x := n3));\n           rewrite ?app_nil_r;\n           rewrite rev_app_distr with (x := nd_red_lift n cons n0 []);\n           try (rewrite rev_app_distr with (x := nd_red_lift n cons n3 []));\n           rewrite <- !app_assoc;\n           apply f_equal; rewrite !nd_red_lift_rev; rewrite ?app_nil_r;\n             reflexivity.\n  Qed.\n\n  (** Same as above, just with digits instead *)\n  Lemma reverse_rev_digit {A : Type} (n : nat) (d : digit (node_lift n A)) :\n    forall (acc acc' : list A),\n      (rev acc') ++ digit_reducer (nd_red_lift n cons) (reverse_digit (rev_lift n ident) d) acc =\n      rev (digit_reducer (nd_red_lift n cons) d acc') ++ acc.\n  Proof.\n    unfold ident. remember n as m. induction m;\n                    [ destruct d; intros; simpl; rewrite <- !app_assoc; reflexivity |].\n    destruct d; intros; simpl in *; rewrite !rev_node_lem; reflexivity.\n  Qed.\n\n  (**\n     Proof of\n     [rev acc' ++ reducer cons (reverse tr) acc =\n     rev (reducer cons tr acc') ++ acc]\n     but lifted [n] times into [node].\n     Uses the custom induction principle.\n   *)\n  Lemma reverse_reducer_lift {A : Type} (n : nat) (tr : fingertree (node_lift n A)) :\n    forall (acc acc' : list A),\n      rev acc' ++ ft_reducer (nd_red_lift n cons) (reverse_tree (rev_lift n ident) tr) acc =\n      rev (ft_reducer (nd_red_lift n cons) tr acc') ++ acc.\n  Proof.\n    apply fingertree_lift_ind with (f2 := tr); simpl in *.\n    - reflexivity.\n    - induction n0; simpl in *.\n      + intros. unfold ident. rewrite <- app_assoc. reflexivity.\n      + intros. unfold ident. destruct a; simpl in *; rewrite !IHn0; reflexivity.\n    - induction n0; intros.\n      + simpl in *; unfold ident.\n        destruct d; simpl in *;\n          [ replace (a :: acc) with ([a] ++ acc)\n            by reflexivity\n          | replace (a0 :: a :: acc) with ([a0] ++ (a :: acc))\n            by reflexivity\n          | replace (a1 :: a0 :: a :: acc) with ([a1] ++ (a0 :: a :: acc))\n            by reflexivity\n          | replace (a2 :: a1 :: a0 :: a :: acc) with ([a2] ++ (a1 :: a0 :: a :: acc))\n            by reflexivity\n          ];\n          rewrite <- H;\n          rewrite <- !app_assoc;\n          unfold ident;\n          rewrite ft_reducer_app by (apply nd_reducer_cons_app);\n          (destruct d0;\n            simpl; rewrite <- !app_assoc; reflexivity).\n      + rewrite reverse_rev_digit.\n        rewrite H. rewrite reverse_rev_digit.\n        reflexivity.\n  Qed.\n\n\n  (**\n     Theorem!\n     reversing a (tree converted to a list) is the same as\n     is reversing the tree and then converting it to a list.\n   *)\n  Theorem reverse_to_list_lift {A : Type} (tr : fingertree A) :\n    rev (to_list tr) = to_list (reverse tr).\n  Proof.\n    simpl.\n    specialize @reverse_reducer_lift with (A := A) (n := O) (acc' := []) (acc := []).\n    intros. simpl in H.\n    rewrite <- app_nil_r with (l := rev (ft_reducer cons tr [])).\n    rewrite <- H with (tr := tr) (acc := []) (acc' := []).\n    reflexivity.\n  Qed.\n\n  (* ============================================================================== *)\n  (*                   reverse_to_list with sequential induction                    *)\n  (* ============================================================================== *)\n\n  Axiom ft_left_ind :\n    forall (P : (forall (A : Type), fingertree A -> Prop)),\n           (forall (A : Type), P A empty) ->\n           (forall (A : Type) (tr : fingertree A) (x : A), P A tr -> P A (x <| tr)) ->\n           forall (A : Type) (tr : fingertree A), P A tr.\n\n  Lemma reverse_reducer_left_ind {A : Type} (tr : fingertree A) :\n    forall acc acc' fn, (forall x, fn (fn x) = x) ->\n                   rev acc' ++ reducer cons (reverse_tree fn tr) acc =\n                   rev (reducer cons (map fn tr) acc') ++ acc.\n  Proof.\n    induction tr using ft_left_ind; intros; simpl in *.\n    - reflexivity.\n    - rewrite reverse_tree_addl; [| apply H].\n      rewrite ft_reducer_addr. rewrite IHtr; [| apply H].\n      rewrite map_addl.\n      rewrite ft_reducer_addl. simpl.\n      rewrite <- app_assoc. reflexivity.\n  Qed.\n\n  Theorem reverse_to_list_left_ind {A : Type} (tr : fingertree A) :\n    rev (to_list tr) = to_list (reverse tr).\n  Proof.\n    Opaque map.\n    simpl.\n    specialize (reverse_reducer_left_ind tr [] [] ident).\n    intros. simpl in H.\n    rewrite <- app_nil_r with (l := rev (ft_reducer cons tr [])).\n    unfold reverse. unfold ident in *. rewrite map_id in H.\n    symmetry.\n    rewrite H; [|intros; reflexivity].\n    reflexivity.\n    Transparent map.\n  Qed.\n\nEnd FingerTrees.\n\n\n", "meta": {"author": "adamschoenemann", "repo": "verified_finger_trees", "sha": "507d78e6105c008c457fcb38475dc2835d647b5e", "save_path": "github-repos/coq/adamschoenemann-verified_finger_trees", "path": "github-repos/coq/adamschoenemann-verified_finger_trees/verified_finger_trees-507d78e6105c008c457fcb38475dc2835d647b5e/FingerTrees.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6547196660890878}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype seq div prime.\nFrom mathcomp Require Import path fintype bigop.\nAdd LoadPath \"~/git/git.graillo.tf/stage/2019-06/src\".\nRequire Import seq2 arith.\n\n\nLemma legendre_formula :\n  forall n p, prime p\n  -> logn p (n`!) = \\sum_(1 <= a < (trunc_log p n).+1) n %/ p ^ a.\nProof.\n  move=> n p p_prime.\n  assert (\n    \\sum_(1 <= a < (trunc_log p n).+1) n %/ p ^ a\n    = \\sum_(1 <= a < (trunc_log p n).+1) \\sum_(1 <= i < n.+1) (p ^ a %| i)\n    ) as step1.\n  apply eq_big ; first by [].\n  move=> i _ ; rewrite divn_count_dvd //.\n  rewrite step1.\n  rewrite exchange_big /= fact_prod logn_prod_f.\n  apply eq_big_nat.\n  move=> m H.\n  move/andP in H.\n  destruct H as [m_gt_0 m_lt_Sn].\n  rewrite (big_cat_nat _ _ _ (ltn0Sn (trunc_log p m))) /=.\n  rewrite -(addn0 (logn p m)).\n  congr addn.\n  rewrite logn_count_dvd //.\n  rewrite (big_cat_nat _ _ _ (ltn0Sn (trunc_log p m))) /=.\n  rewrite -{2}(addn0 (\\sum_(1 <= i < (trunc_log p m).+1) (p ^ i %| m))).\n  congr addn.\n  apply/eqP.\n  rewrite eqn_0_sum.\n  apply/allP.\n  move=> f f_in.\n  move/nthP in f_in.\n  destruct (f_in 0) as [i Hi Hf].\n  rewrite size_map in Hi.\n  rewrite (nth_map 0) // in Hf.\n  rewrite size_iota in Hi.\n  rewrite nth_iota // in Hf.\n  rewrite eqnE eq_sym -Hf pfactor_dvdn //.\n  assert (forall b : bool, (nat_of_bool b == 0) = ~~ b) as H by by case.\n  rewrite H -ltnNge.\n  apply ltn_addr.\n  rewrite ltnS.\n  apply leq_logn_trunc_log ; first by [].\n  by apply prime_gt1.\n  apply expn_ltn_exp with p ; first by apply prime_gt1.\n  by apply trunc_logP ; first by apply prime_gt1.\n  apply/eqP.\n  rewrite eq_sym eqn_0_sum.\n  apply/allP.\n  move=> f f_in.\n  move/nthP in f_in.\n  destruct (f_in 0) as [i Hi Hf].\n  rewrite size_map in Hi.\n  rewrite (nth_map 0) // in Hf.\n  rewrite size_iota in Hi.\n  rewrite nth_iota // in Hf.\n  rewrite eqnE eq_sym -Hf pfactor_dvdn //.\n  assert (forall b : bool, (nat_of_bool b == 0) = ~~ b) as H by by case.\n  rewrite H -ltnNge.\n  apply ltn_addr.\n  rewrite ltnS.\n  apply leq_logn_trunc_log ; first by [].\n  by apply prime_gt1.\n  apply leq_trunc_log ; first by apply prime_gt1.\n  apply/andP ; by split.\n  apply/allP.\n  move=> i Hi.\n  rewrite map_id mem_iota in Hi.\n  move/andP in Hi.\n  by destruct Hi.\nQed.\n", "meta": {"author": "esum", "repo": "internship2019", "sha": "17e55dbe0e3ad5da653a4b8086714a4b61c4177a", "save_path": "github-repos/coq/esum-internship2019", "path": "github-repos/coq/esum-internship2019/internship2019-17e55dbe0e3ad5da653a4b8086714a4b61c4177a/src/legendre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6547196442288659}}
{"text": "(* https://lawrencecpaulson.github.io/2022/08/31/Ackermann-not-PR-I.html *)\nRequire Import Arith Lia.\nFrom Equations Require Import Equations.\n\nEquations ack (p : nat * nat) : nat by wf p (lexprod _ _ lt lt) :=\nack (0, n) := S n;\nack (S m, 0) := ack (m, 1);\nack (S m, S n) := ack (m, ack (S m, n)).\n\nImport Nat Peano.\n\nLemma lt_ack2 i j: j < ack(i,j).\nProof. funelim (ack (i, j)).\n- constructor.\n- eapply lt_trans. 2: exact H. constructor.\n- exact (le_lt_trans _ _ _ H H0).\nQed.\n\nLemma ack_lt_ack_S2 i j: ack(i, j) < ack (i, S j).\nProof. induction i, j; simp ack; apply lt_ack2. Qed.\n\nLemma ack_lt_mono2 i j k: j < k -> ack(i,j) < ack(i,k).\nProof. intro H. induction H.\n- apply ack_lt_ack_S2.\n- eapply lt_trans. exact IHle. apply ack_lt_ack_S2.\nQed.\n\nLemma lt_mono_imp_le_mono f (LTM: forall n m, n < m -> f n < f m):\nforall n m, n <= m -> f n <= f m.\nProof. intros n m H. induction H.\n- constructor.\n- eapply le_trans. exact IHle. apply lt_le_incl, LTM, lt_succ_diag_r.\nQed.\n\nLemma ack_le_mono2 k i j: j <= k -> ack(i,j) <= ack(i,k).\nProof. apply (lt_mono_imp_le_mono (fun n => ack(i,n))). apply ack_lt_mono2. Qed.\n\nLemma ack2_le_ack1 i j: ack (i, S j) <= ack (S i, j).\nProof. induction j; simp ack.\n- constructor.\n- apply ack_le_mono2. eapply le_trans. exact (lt_ack2 i (S j)). exact IHj.\nQed.\n\nLemma S_less_ack_S1 i j: S j < ack(S i, j).\nProof. induction j; simp ack.\n- apply lt_ack2.\n- eapply lt_le_trans. apply lt_ack2. exact (ack_le_mono2 _ _ _ IHj).\nQed.\n\nLemma ack_lt_ack_S1 i j: ack(i,j) < ack(S i, j).\nProof. induction j; simp ack; apply ack_lt_mono2.\n- exact lt_0_1.\n- apply S_less_ack_S1.\nQed.\n\nLemma lt_ack1 i j: i < ack(i,j).\nProof. induction i; simp ack.\n- apply lt_0_succ.\n- eapply le_lt_trans. exact IHi. apply ack_lt_ack_S1.\nQed.\n\nLemma ack_1 j: ack(1,j) = j + 2.\nProof. induction j; simp ack.\n- constructor.\n- now rewrite IHj.\nQed.\n\nLemma ack_2 j: ack(2,j) = 2 * j + 3.\nProof. induction j; simp ack.\n- trivial.\n- rewrite IHj, ack_1. lia.\nQed.\n\nLemma ack_lt_mono1 k i j: i < j -> ack(i, k) < ack(j, k).\nProof. intro H. induction H.\n- apply ack_lt_ack_S1.\n- eapply lt_trans. apply IHle. apply ack_lt_ack_S1.\nQed.\n\nLemma ack_le_mono1 k i j: i <= j -> ack(i, k) <= ack(j, k).\nProof. apply (lt_mono_imp_le_mono (fun n => ack(n, k))). apply ack_lt_mono1. Qed.\n\nLemma ack_nest_bound i1 i2 j: ack(i1, ack(i2,j)) < ack(2 + i1 + i2, j).\nProof.\nassert (ack (i1, ack (i2, j)) < ack(i1 + i2, ack(S (i1 + i2), j))). {\neapply Nat.le_lt_trans. apply ack_le_mono1. 2: apply ack_lt_mono2.\n- apply le_add_r.\n- apply ack_lt_mono1. auto with arith.\n}\neapply Nat.lt_le_trans. apply H. rewrite <- ack_equation_3.\napply ack2_le_ack1.\nQed.\n\nLemma ack_add_bound i1 i2 j: ack(i1,j) + ack(i2,j) < ack (4 + i1 + i2, j).\nProof.\napply (lt_trans _ (ack(2, ack(i1 + i2, j))) _).\n- rewrite ack_2.\npose (H1 := ack_le_mono1 j i1 (i1 + i2)).\npose (H2 := ack_le_mono1 j i2 (i1 + i2)).\nlia.\n- apply ack_nest_bound.\nQed.\n\nLemma ack_add_bound2 i j k (H: i < ack(k,j)): i + j < ack (4 + k, j).\nProof.\nreplace (4 + k) with (4 + k + 0) by apply add_0_r.\neapply lt_trans. 2: apply (ack_add_bound k 0 j).\nrewrite ack_equation_1. apply add_lt_mono.\n- exact H.\n- apply lt_succ_diag_r.\nQed.\n", "meta": {"author": "mattam82", "repo": "Coq-Equations", "sha": "5603bfff39f3866eed8f010591b5503d5776fa4e", "save_path": "github-repos/coq/mattam82-Coq-Equations", "path": "github-repos/coq/mattam82-Coq-Equations/Coq-Equations-5603bfff39f3866eed8f010591b5503d5776fa4e/test-suite/ack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.654719641666181}}
{"text": "Require Export Coq.Sets.Ensembles.\nRequire Export Coq.Lists.List.\nRequire Import Logic.lib.Coqlib.\n\nClass Language: Type := {\n  expr: Type\n}.\n\nDefinition context {L: Language}: Type := expr -> Prop. (* better to be (Ensemble model) if Ensemble is polymorphic *)\n\nDefinition empty_context {L: Language}: context := Empty_set _.\n\nClass Provable (L: Language): Type := {\n  provable: expr -> Prop\n}.\n\nClass Derivable (L: Language): Type := {\n  derivable: context -> expr -> Prop\n}.\n\nClass Derivable1 (L:Language): Type := {\n  derivable1: expr -> expr -> Prop\n}.\n\nClass LogicEquiv (L:Language): Type := {\n  logic_equiv: expr -> expr -> Prop\n}.\n\nClass Model: Type := {\n  model: Type\n}.\n\nClass Semantics (L: Language) (MD: Model): Type := {\n  denotation: expr -> model -> Prop (* better to be (expr -> Ensemble model) if Ensemble is polymorphic *)\n}.\n\nDefinition satisfies {L: Language} {MD: Model} {SM: Semantics L MD}: model -> expr -> Prop :=\n  fun (m: model) (x: expr) => denotation x m.\n\nDefinition ModelClass (MD: Model) := model -> Prop.\n\nClass KripkeModel (MD: Model): Type := {\n  Kmodel: Type;\n  Kworlds: Kmodel -> Type;\n  build_model: forall M: Kmodel, Kworlds M -> model\n}.\n\nDefinition Kdenotation {L: Language} {MD: Model} {kMD: KripkeModel MD} (M: Kmodel) {SM: Semantics L MD}: expr -> Ensemble (Kworlds M) := fun x m => denotation x (build_model M m).\n\nDefinition unit_MD: Model := Build_Model unit.\n\nDefinition unit_kMD (MD: Model): KripkeModel MD :=\n  Build_KripkeModel MD unit (fun _ => model) (fun _ m => m).\n\nDefinition AllModel (MD: Model): ModelClass MD := fun _ => True.\n\nInductive KripkeModelClass (MD: Model) {kMD: KripkeModel MD} (H: Kmodel -> Prop): ModelClass MD :=\n| Build_KripkeModelClass: forall (M: Kmodel) (m: Kworlds M), H M -> KripkeModelClass MD H (build_model M m).\n\nDefinition consistent {L: Language} {Gamma: Derivable L}: context -> Prop :=\n  fun Phi =>\n    exists x: expr, ~ derivable Phi x.\n\nDefinition satisfiable {L: Language} {MD: Model} {SM: Semantics L MD}: ModelClass MD -> context -> Prop :=\n  fun MC Phi =>\n    exists m: model, MC m /\\ forall x: expr, Phi x -> satisfies m x.\n\nDefinition consequence {L: Language} {MD: Model} {MD: Model} {SM: Semantics L MD}: ModelClass MD -> context -> expr -> Prop :=\n  fun MC Phi y =>\n    forall m: model, MC m -> (forall x, Phi x -> satisfies m x) -> satisfies m y.\n\nDefinition valid {L: Language} {MD: Model} {SM: Semantics L MD}: ModelClass MD -> expr -> Prop :=\n  fun MC x =>\n    forall m: model, MC m -> satisfies m x.\n\nDefinition provable_sound {L: Language} (Gamma: Provable L) {MD: Model} (SM: Semantics L MD) (MC: ModelClass MD): Prop :=\n  forall x: expr, provable x -> valid MC x.\n\nDefinition derivable_sound {L: Language} (Gamma: Derivable L) {MD: Model} (SM: Semantics L MD) (MC: ModelClass MD): Prop :=\n  forall Phi x, derivable Phi x -> consequence MC Phi x.\n\nDefinition weakly_complete {L: Language} (Gamma: Provable L) {MD: Model} (SM: Semantics L MD) (MC: ModelClass MD): Prop :=\n  forall x: expr, valid MC x -> provable x.\n\nDefinition strongly_complete {L: Language} (Gamma: Derivable L) {MD: Model} (SM: Semantics L MD) (MC: ModelClass MD): Prop :=\n  forall (Phi: context) (x: expr), consequence MC Phi x -> derivable Phi x.\n\nDeclare Scope logic_base.\nDeclare Scope syntax.\nDeclare Scope kripke_model.\nDeclare Scope kripke_model_class.\n\nNotation \"m  |=  x\" := (satisfies m x) (at level 70, no associativity) : logic_base.\nNotation \"|--  x\" := (provable x) (at level 71, no associativity) : logic_base.\nNotation \"Phi |---  x\" := (derivable Phi x) (at level 70, no associativity) : logic_base.\nNotation \"Phi ;; x\" := (Union _ Phi (Singleton _ x)) (at level 69, left associativity) : logic_base.\nNotation \"x --||-- y\" := (logic_equiv x  y) (at level 71, no associativity): logic_base.\nNotation \"x |-- y\" := (derivable1 x y) (at level 70, no associativity) : logic_base.\n\nModule KripkeModelFamilyNotation.\nNotation \"'KRIPKE:'  M , m\" := (build_model M m) (at level 59, no associativity) : kripke_model.\nEnd KripkeModelFamilyNotation.\n\nModule KripkeModelSingleNotation.\nNotation \"'KRIPKE:'  m\" := (@build_model _ (unit_kMD _) tt m) (at level 59, no associativity) : kripke_model.\nEnd KripkeModelSingleNotation.\n\nModule KripkeModelClass.\n\nDefinition kripke_model_class_join {MD: Model} {kMD: KripkeModel MD} (X Y: Kmodel -> Prop): Kmodel -> Prop := fun M => X M /\\ Y M.\n\nNotation \"x + y\" := (kripke_model_class_join x y) : kripke_model_class.\n\nEnd KripkeModelClass.\n\n", "meta": {"author": "QinxiangCao", "repo": "LOGIC", "sha": "d1476d57345c87447ea500b3d5ea99ee6d0f6863", "save_path": "github-repos/coq/QinxiangCao-LOGIC", "path": "github-repos/coq/QinxiangCao-LOGIC/LOGIC-d1476d57345c87447ea500b3d5ea99ee6d0f6863/GeneralLogic/Base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6547196394474791}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Functor.Main.\nRequire Import Cat.Cat.\nRequire Import Ext_Cons.Prod_Cat.Prod_Cat.\n\nLocal Obligation Tactic := idtac.\n\nLocal Open Scope functor_scope.\n\nProgram Definition Prod_Functor\n        {C1 C2 C1' C2' : Category} (F : C1 –≻ C2) (F' : C1' –≻ C2')\n  : (C1 × C1') –≻ (C2 × C2') :=\n{|\n  FO := fun a => (F _o (fst a), F' _o (snd a))%object;\n  FA := fun _ _ f => (F _a (fst f), F' _a (snd f))%morphism\n|}.\n\nNext Obligation.\n  intros; cbn; repeat rewrite F_id; trivial.\nQed.\n\nNext Obligation.\n  intros; cbn; repeat rewrite F_compose; trivial.\nQed.\n\nDefinition Bi_Func_1 {Cx C1 C1' Cy : Category} (F : Cx –≻ C1) (F' : (C1 × C1') –≻ Cy)\n  : (Cx × C1') –≻ Cy :=\n  F' ∘ (Prod_Functor F (@Functor_id C1')).\n\nDefinition Bi_Func_2 {Cx C1 C1' Cy : Category} (F : Cx –≻ C1') (F' : (C1 × C1') –≻ Cy) : (C1 × Cx) –≻ Cy :=\n  Functor_compose (Prod_Functor (@Functor_id C1) F) F'.\n\nLocal Hint Extern 2 => cbn.\n\nLocal Obligation Tactic := basic_simpl; do 2 auto.\n\nProgram Definition Fix_Bi_Func_1 {C1 C1' Cy : Category} (x : C1) (F : (C1 × C1') –≻ Cy)\n  : C1' –≻ Cy :=\n{|\n  FO := fun a => (F _o (x, a))%object;\n  FA := fun _ _ f => (F @_a (_, _) (_, _) (@id _ x, f))%morphism\n|}.\n\nProgram Definition Fix_Bi_Func_2 {C1 C1' Cy : Category} (x : C1') (F : (C1 × C1') –≻ Cy)\n  : C1 –≻ Cy :=\n{|\n  FO := fun a => (F _o (a, x))%object;\n  FA := fun _ _ f => (F @_a (_, _) (_, _) (f, @id _ x))%morphism\n|}.\n\nProgram Definition Diag_Func (C : Category) : C –≻ (C × C) :=\n{|\n  FO := fun a => (a, a);\n  FA := fun _ _ f => (f, f);\n  F_id := fun _ => idpath;\n  F_compose := fun _ _ _ _ _ => idpath\n|}.\n\nTheorem Prod_Functor_Cat_Proj {C D D' : Category} (F : C –≻ (D × D')) : ((Prod_Functor ((Cat_Proj1 _ _) ∘ F) ((Cat_Proj2 _ _) ∘ F)) ∘ (Diag_Func C))%functor = F.\nProof.\n  Func_eq_simpl; trivial.\nQed.  \n\nProgram Definition Twist_Func (C C' : Category) : (C × C') –≻ (C' × C) :=\n{|\n  FO := fun a => (snd a, fst a);\n  FA := fun _ _ f => (snd f, fst f);\n  F_id := fun _ => idpath;\n  F_compose := fun _ _ _ _ _ => idpath\n|}.\n\nSection Twist_Prod_Func_Twist.\n  Context {C C' : Category} (F : C –≻ C') {D D' : Category} (G : D –≻ D').\n\n  Theorem Twist_Prod_Func_Twist : (((Twist_Func _ _) ∘ (Prod_Functor F G)) ∘ (Twist_Func _ _))%functor = Prod_Functor G F.\n  Proof.  \n    Func_eq_simpl; trivial.\n  Qed.\n\nEnd Twist_Prod_Func_Twist.\n\nSection Prod_Functor_compose.\n  Context {C D E: Category} (F : C –≻ D) (G : D –≻ E)\n          {C' D' E': Category} (F' : C' –≻ D') (G' : D' –≻ E').\n\n  Theorem Prod_Functor_compose : ((Prod_Functor G G') ∘ (Prod_Functor F F') = Prod_Functor (G ∘ F) (G' ∘ F'))%functor.\n  Proof.\n    Func_eq_simpl; trivial.\n  Qed.    \n                                   \nEnd Prod_Functor_compose.", "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/Ext_Cons/Prod_Cat/Operations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6547001123006834}}
{"text": "(* begin hide *)\nRequire Import CoList.\nRequire Import CoTree.\nRequire Import PArith.\nRequire Import QArith.\n(* end hide *)\n\n(** * Enumerating The Rationals: Naive Tree *)\n\n(** _Current Status: it seems to be quite diffucult to prove the correctness\n    of [find] on a specific tree. The problem with an induction proof here is\n    that the tree's structure is hard-coded in the [find] function, but is\n    passed as an argument to the [lookup] function_.\n  *)\n  \n(** Though not presented in the paper, we have constructed this simple\n    example to test the CoTree module, and the general proof strategy.\n    \n    The properties of this naive approach are even worse than those of\n    the naive enumeration presented in [NaiveEnum], as the tree will\n    contain many duplicates of the same _unreduced_ rational.\n  *)\n\nModule Naive.\n\n  (** The [next] function for this tree can be seen as the equivalent Haskell function below.\n<<\n    next (n,d) = ((n + 1, d), n / d, (n, d + 1))\n>>\n      Below you can find the Coq translation of this function, as well as the [tree] and [enum]\n      definition using this function.\n    *)\n\n  Definition next (p: positive*positive) : (positive*positive)*Q*(positive*positive) :=\n    match p with (n,d) => ((Pos.succ n, d), Z.pos n # d, (n, Pos.succ d)) end.\n\n  Definition tree := CoTree.unfold next (1,1)%positive.\n\n  Definition enum := CoTree.bf tree.\n  \n  (** Next, we define a [find] function that maps rationals to their position in the\n      tree--in this case, it maps it to the rightmost version.\n      The idea is that proving the correctness of this function will bring us a long\n      way towards proving our enumeration.\n    *)\n  \n  Definition findp (n d: positive) : path :=\n    Pos.peano_rec\n      (*Type*) (fun _ => path)\n      (*Zero*) (Pos.peano_rec\n               (*Type*) (fun _ => path)\n               (*Zero*) (CoTree.Here)\n               (*Succ*) (fun _ p => CoTree.Right p)\n               (*Args*) d\n               )\n      (*Succ*) (fun _ p => CoTree.Left p)\n      (*Args*) n.\n\n  Lemma findp_l (n d: positive) : findp (Pos.succ n) d = CoTree.Left (findp n d).\n  Proof.\n    unfold findp,Pos.peano_rec.\n    rewrite Pos.peano_rect_succ.\n    reflexivity.\n  Qed.\n\n  Lemma findp_r (d: positive) : findp 1 (Pos.succ d) = CoTree.Right (findp 1 d).\n  Proof.\n    unfold findp,Pos.peano_rec.\n    rewrite Pos.peano_rect_succ.\n    reflexivity.\n  Qed.\n\n  (** We have to somehow prove a duality between [next] and [findp],\n      where in [next] if [n] increases we consume a [Left] path, if [d]\n      increases we consume a [Right] path, and in [findp] we generate\n      a [Left] path as long as we can consume successors of [n], and \n      [Right] paths as long as we can consume successors of [d].\n    *)\n\n  Lemma findp_correct (n d: positive) : CoTree.lookup (findp n d) tree = 'n # d.\n  Proof.\n    unfold tree.\n    induction n as [|n] using Pos.peano_ind.\n    - induction d as [|d] using Pos.peano_ind.\n      * reflexivity.\n      * rewrite findp_r.\n  Admitted.\n\n  Definition find (q: Q) : 0 < q -> CoTree.path.\n    intros Hq.\n    destruct q as [n d].\n    destruct n as [|n|n]; try discriminate Hq.\n    apply (findp n d).\n  Defined.\n  \n  Theorem find_correct (q: Q) (H: 0 < q) : CoTree.lookup (find q H) tree = q.\n  Proof.\n    case q as [n d].\n    case n as [|n|n].\n    - inversion H.\n    - unfold find; apply findp_correct.\n    - inversion H.\n  Qed.\nEnd Naive.\n", "meta": {"author": "wenkokke", "repo": "EnumeratingTheRationals", "sha": "3257aa8c6ece5d1ad631a3295be4ef11e2e58f7e", "save_path": "github-repos/coq/wenkokke-EnumeratingTheRationals", "path": "github-repos/coq/wenkokke-EnumeratingTheRationals/EnumeratingTheRationals-3257aa8c6ece5d1ad631a3295be4ef11e2e58f7e/Enums/NaiveTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6547000925240205}}
{"text": "From mathcomp Require Import ssreflect.\nRequire Import NPeano ZArith.\nFrom Coquelicot Require Import Coquelicot.\nRequire Import Reals Field Psatz Plouffe CPlouffe Million0.\n\n(*\nTime Eval native_compute in sumV cprecision cdigit 6.\n*)\n\nDefinition comp4 := 173751857.\n\nLemma comp4_def : comp4 = sumV cprecision cdigit 6.\nProof.\nnative_cast_no_check (refl_equal comp4).\nTime Qed.\n\n", "meta": {"author": "thery", "repo": "Plouffe", "sha": "c87255de87fe5a845fbed4b19932bf41f1ea5507", "save_path": "github-repos/coq/thery-Plouffe", "path": "github-repos/coq/thery-Plouffe/Plouffe-c87255de87fe5a845fbed4b19932bf41f1ea5507/Million4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6546958975735347}}
{"text": "Require Import Problem.\n\nTheorem solution: task.\nProof.\n  unfold task.\n  intro.\n  apply gcd_swap.\n  apply gcd_step.\n  induction n; [apply gcd_O|].\n  apply gcd_swap.\n  replace (S n) with (1 + n) by auto.\n  apply gcd_step.\n  apply gcd_swap.\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/016/Solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.654695894317553}}
{"text": "(*\n(C) Copyright 2010, COQTAIL team\n\nProject Info: http://sourceforge.net/projects/coqtail/\n\nThis library is free software; you can redistribute it and/or modify it\nunder the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation; either version 2.1 of the License, or\n(at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\nor FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\nLicense for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,\nUSA.\n*)\n\n(** Common definitions of real functions sequences. *)\nRequire Import Cbase.\nRequire Import Cfunctions.\nRequire Import Csequence.\nRequire Import Canalysis_def.\n\nDeclare Scope CFseq_scope.\nDelimit Scope CFseq_scope with Cseq_scope.\n\nLocal Open Scope C_scope.\nLocal Open Scope CFseq_scope.\n\nImplicit Type n : nat.\nImplicit Type fn gn : nat -> C -> C.\nImplicit Type f g : C -> C.\n\n(** * Morphism of functions on R -> R to sequences. *)\n\nDefinition CFseq_plus fn gn n := (fn n + gn n)%F.\nDefinition CFseq_mult fn gn n := (fn n * gn n)%F.\nDefinition CFseq_opp fn n := (fun x => Copp (fn n x))%F.\nDefinition CFseq_inv fn n := (fun x => Cinv (fn n x))%F.\n\nInfix \"+\" := CFseq_plus : CFseq_scope.\nInfix \"*\" := CFseq_mult : CFseq_scope.\nNotation \"- u\" := (CFseq_opp u) : CFseq_scope.\nNotation \"/ u\" := (CFseq_inv u) : CFseq_scope.\n\nDefinition CFseq_minus fn gn n := (fn n - gn n)%F.\nDefinition CFseq_div fn gn n := (fn n / gn n)%F.\n\nInfix \"-\" := CFseq_minus : CFseq_scope.\nInfix \"/\" := CFseq_div : CFseq_scope.\n\n(** * Convergence of functions sequences. *)\n\nDefinition CFseq_cv fn f := forall x, Cseq_cv (fun n => fn n x) (f x).\nDefinition CFseq_cv_boule fn f (c : C) (r : posreal) := forall x,  Boule c r x -> Cseq_cv (fun n => fn n x) (f x).\n\nDefinition CFseq_cvu fn f (x : C) (r : posreal) := forall eps : R, 0 < eps ->\n        exists N : nat, forall n (y : C), (N <= n)%nat -> Boule x r y ->\n        C_dist (fn n y) (f y) < eps.\n\nDefinition CFpartial_sum (fn : nat -> C) N := sum_f_C0 fn 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/Complex/CFsequence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.6546253502032786}}
{"text": "(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\n\n(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\n\n(* Why3 comment *)\n(* infix_ls is replaced with (x < x1)%Z by the coq driver *)\n\n(* Why3 goal *)\nLemma infix_lseq_def : forall (x:Z) (y:Z), (x <= y)%Z <-> ((x < y)%Z \\/\n  (x = y)).\nexact Zle_lt_or_eq_iff.\nQed.\n\n(* Why3 comment *)\n(* infix_pl is replaced with (x + x1)%Z by the coq driver *)\n\n(* Why3 comment *)\n(* prefix_mn is replaced with (-x)%Z by the coq driver *)\n\n(* Why3 comment *)\n(* infix_as is replaced with (x * x1)%Z by the coq driver *)\n\n(* Why3 goal *)\nLemma Assoc : forall (x:Z) (y:Z) (z:Z),\n  (((x + y)%Z + z)%Z = (x + (y + z)%Z)%Z).\nProof.\nintros x y z.\napply sym_eq.\napply Zplus_assoc.\nQed.\n\n(* Why3 goal *)\nLemma Unit_def_l : forall (x:Z), ((0%Z + x)%Z = x).\nProof.\nexact Zplus_0_l.\nQed.\n\n(* Why3 goal *)\nLemma Unit_def_r : forall (x:Z), ((x + 0%Z)%Z = x).\nProof.\nexact Zplus_0_r.\nQed.\n\n(* Why3 goal *)\nLemma Inv_def_l : forall (x:Z), (((-x)%Z + x)%Z = 0%Z).\nProof.\nexact Zplus_opp_l.\nQed.\n\n(* Why3 goal *)\nLemma Inv_def_r : forall (x:Z), ((x + (-x)%Z)%Z = 0%Z).\nProof.\nexact Zplus_opp_r.\nQed.\n\n(* Why3 goal *)\nLemma Comm : forall (x:Z) (y:Z), ((x + y)%Z = (y + x)%Z).\nProof.\nexact Zplus_comm.\nQed.\n\n(* Why3 goal *)\nLemma Assoc1 : forall (x:Z) (y:Z) (z:Z),\n  (((x * y)%Z * z)%Z = (x * (y * z)%Z)%Z).\nProof.\nintros x y z.\napply sym_eq.\napply Zmult_assoc.\nQed.\n\n(* Why3 goal *)\nLemma Mul_distr_l : forall (x:Z) (y:Z) (z:Z),\n  ((x * (y + z)%Z)%Z = ((x * y)%Z + (x * z)%Z)%Z).\nProof.\nintros x y z.\napply Zmult_plus_distr_r.\nQed.\n\n(* Why3 goal *)\nLemma Mul_distr_r : forall (x:Z) (y:Z) (z:Z),\n  (((y + z)%Z * x)%Z = ((y * x)%Z + (z * x)%Z)%Z).\nProof.\nintros x y z.\napply Zmult_plus_distr_l.\nQed.\n\n(* Why3 goal *)\nLemma infix_mn_def : forall (x:Z) (y:Z), ((x - y)%Z = (x + (-y)%Z)%Z).\nreflexivity.\nQed.\n\n(* Why3 goal *)\nLemma Comm1 : forall (x:Z) (y:Z), ((x * y)%Z = (y * x)%Z).\nProof.\nexact Zmult_comm.\nQed.\n\n(* Why3 goal *)\nLemma Unitary : forall (x:Z), ((1%Z * x)%Z = x).\nProof.\nexact Zmult_1_l.\nQed.\n\n(* Why3 goal *)\nLemma NonTrivialRing : ~ (0%Z = 1%Z).\nProof.\ndiscriminate.\nQed.\n\n(* Why3 goal *)\nLemma Refl : forall (x:Z), (x <= x)%Z.\nProof.\nintros x.\napply Zle_refl.\nQed.\n\n(* Why3 goal *)\nLemma Trans : forall (x:Z) (y:Z) (z:Z), (x <= y)%Z -> ((y <= z)%Z ->\n  (x <= z)%Z).\nProof.\nexact Zle_trans.\nQed.\n\n(* Why3 goal *)\nLemma Antisymm : forall (x:Z) (y:Z), (x <= y)%Z -> ((y <= x)%Z -> (x = y)).\nProof.\nexact Zle_antisym.\nQed.\n\n(* Why3 goal *)\nLemma Total : forall (x:Z) (y:Z), (x <= y)%Z \\/ (y <= x)%Z.\nProof.\nintros x y.\ndestruct (Zle_or_lt x y) as [H|H].\nleft.\nassumption.\nright.\nnow apply Zlt_le_weak.\nQed.\n\n(* Why3 goal *)\nLemma ZeroLessOne : (0%Z <= 1%Z)%Z.\nProof.\napply Zle_lt_or_eq_iff.\nnow left.\nQed.\n\n(* Why3 goal *)\nLemma CompatOrderAdd : forall (x:Z) (y:Z) (z:Z), (x <= y)%Z ->\n  ((x + z)%Z <= (y + z)%Z)%Z.\nProof.\nexact Zplus_le_compat_r.\nQed.\n\n(* Why3 goal *)\nLemma CompatOrderMult : forall (x:Z) (y:Z) (z:Z), (x <= y)%Z ->\n  ((0%Z <= z)%Z -> ((x * z)%Z <= (y * z)%Z)%Z).\nProof.\nexact Zmult_le_compat_r.\nQed.\n\n", "meta": {"author": "schrodibear", "repo": "why3", "sha": "9f8eb767380987a28e43b81729ae1d682363bb49", "save_path": "github-repos/coq/schrodibear-why3", "path": "github-repos/coq/schrodibear-why3/why3-9f8eb767380987a28e43b81729ae1d682363bb49/lib/coq/int/Int.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.6546253454914923}}
{"text": "(* author: Dimitur Krustev *)\n(* started: 20170526 *)\n\n(* partially inspired by: https://medium.com/@deathmood/how-to-write-your-own-virtual-dom-ee74acc13060 *)\n\nRequire Import List Arith.\nRequire String.\nRequire Fin.\n\nFixpoint replaceNth {A} (n: nat) (xs: list A) (y: A) {struct xs} : list A :=\n  match xs with\n  | nil => nil\n  | x::xs => match n with\n    | 0 => y::xs\n    | S n => x :: replaceNth n xs y\n    end\n  end.\n\nLemma length_replaceNth: forall A (xs: list A) n y, length (replaceNth n xs y) = length xs.\nProof.\n  induction xs; auto.\n  simpl. intros. destruct n; auto. \n  simpl. f_equal. auto.\nQed.\n\nLemma nth_replaceNth_sameInd: forall A (xs: list A) n y default,\n  nth n (replaceNth n xs y) default =  if n <? length xs then y else default.\nProof.\n  induction xs.\n  - simpl. intros. destruct n; auto.\n  - simpl. intros. destruct n; auto.\n    simpl. rewrite IHxs. unfold Nat.ltb. reflexivity.\nQed.\n\nLemma nth_replaceNth_diffInd: forall A (xs: list A) n m y default,\n  n <> m -> nth n (replaceNth m xs y) default = nth n xs default.\nProof.\n  induction xs; auto.\n  simpl. destruct m.\n  - simpl. intros. destruct n; try congruence.\n  - simpl. intros. destruct n; auto.\nQed.\n\nLemma replaceNth_app_l: forall A (xs ys: list A) n y,\n  n < length xs -> replaceNth n (xs ++ ys) y = replaceNth n xs y ++ ys.\nProof.\n  induction xs.\n  - simpl. intros. contradict H. auto with arith.\n  - simpl. intros. destruct n; auto.\n    rewrite IHxs; auto with arith.\nQed.\n\nLemma replaceNth_app_r: forall A (xs ys: list A) n y,\n  n >= length xs -> replaceNth n (xs ++ ys) y = xs ++ replaceNth (n - length xs) ys y.\nProof.\n  induction xs; auto.\n  - simpl. intros. rewrite <- minus_n_O. reflexivity.\n  - simpl. intros. destruct n.\n    + contradict H. unfold ge. auto with arith.\n    + f_equal. rewrite Nat.sub_succ. auto with arith.\nQed.\n\n(*\nFixpoint optionMap {A B: Type} (f: A -> option B) (xs: list A) : option (list B) :=\n  match xs with\n  | nil => Some nil\n  | x::xs => match f x with\n    | None => None\n    | Some y => match optionMap f xs with\n      | None => None\n      | Some ys => Some (y::ys)\n      end\n    end\n  end.\n\nSection MonadOps.\n\nVariable M: Type -> Type.\nVariable mret: forall {X}, X -> M X.\nVariable mbind: forall {X Y}, M X -> (X -> M Y) -> M Y.\n\nFixpoint mapM {A B} (f: A -> M B) (xs: list A) {struct xs} : M (list B) :=\n  match xs with\n  | nil => mret _ nil\n  | x::xs => mbind _ _ (f x) (fun y => mbind _ _ (mapM f xs) (fun ys => mret _ (y::ys)))\n  end.\n\nEnd MonadOps.\n\nImplicit Arguments mapM [M A B].\n*)\n\n(* *** *)\n\nInductive State (S A: Type) := MkState (f: S -> A * S).\nImplicit Arguments MkState [S A].\n\nDefinition stRet {S A} (x: A) : State S A := MkState (fun s => (x, s)).\nDefinition stBind {S A B} (m: State S A) (f: A -> State S B) : State S B :=\n  let '(MkState g) := m in MkState (fun s0 : S =>\n     let '(a, s1) := g s0 in\n     let '(MkState h) := f a in\n     h s1).\n\nDefinition stGet {S} : State S S := MkState (fun s => (s, s)).\nDefinition stPut {S} (s: S) : State S unit := MkState (fun _ => (tt, s)).\nDefinition stRun {S A} (m: State S A) (s0: S) : A * S :=\n  let '(MkState f) := m in f s0.\nDefinition stEval {S A} (m: State S A) s0 := fst (stRun m s0).\n\nNotation \"m >>= f\" := (stBind m f) (at level 50, left associativity).\nNotation \"'do' a <- e ; c\" := (e >>= (fun a => c)) (at level 60, right associativity).\n\n(*\nFixpoint stMapM {S A B} (f: A -> State S B) (xs: list A) : State S (list B) :=\n  match xs with\n  | nil => stRet nil\n  | x::xs => stBind (f x) (fun y => stBind (stMapM f xs) (fun ys => stRet (y::ys)))\n  end.\n*)\n\nRequire Import FunctionalExtensionality.\n\nLemma stBind_assoc: forall S A B C (m: State S A) (f: A -> State S B) (g: B -> State S C),\n  stBind (stBind m f) g = stBind m (fun x => stBind (f x) g).\nProof.\n  destruct m as [fm]. simpl. intros. f_equal. extensionality s0.\n  destruct (fm s0) as [a s1]. destruct (f a) as [h]. reflexivity.\nQed.\n\nLemma stRun_stBind: forall S A B (m: State S A) (f: A -> State S B) s,\n  stRun (stBind m f) s = let p := stRun m s in stRun (f (fst p)) (snd p).\nProof.\n  destruct m as [g]. simpl. intros. destruct (g s) as [a s1].\n  simpl. destruct (f a) as [h]. reflexivity.\nQed.\n\nLemma stEval_stBind: forall S A B (m: State S A) (f: A -> State S B) s,\n  stEval (stBind m f) s = let p := stRun m s in stEval (f (fst p)) (snd p).\nProof.\n  destruct m as [g]. simpl. intros. unfold stEval. simpl. destruct (g s) as [a s1].\n  simpl. destruct (f a) as [h]. reflexivity.\nQed.\n\n(* *** *)\n\nSection VDom.\n\nInductive DomNodeType := TextNode | ElementNode.\n\nRecord DomOps (Dom: Type) (DomNode: Type) := MkDomOps {\n  (* nodeEqDec: forall x y: DomNode, {x = y} + {x <> y}; *)\n  getNodeType: DomNode -> State Dom DomNodeType;\n  childrenCount: DomNode -> State Dom nat;\n  getChildNode: DomNode -> nat -> State Dom DomNode;\n  createTextNode: String.string -> State Dom DomNode;\n  createElement: String.string -> State Dom DomNode;\n  appendChild: DomNode -> DomNode -> State Dom unit;\n  removeChildAt: DomNode -> nat -> State Dom unit;\n  replaceChildAt: DomNode -> nat -> DomNode -> State Dom unit;\n  getTagName: DomNode -> State Dom String.string;\n  getText: DomNode -> State Dom String.string;\n  setText: DomNode -> String.string -> State Dom unit;\n  }.\n\nImplicit Arguments getNodeType [Dom DomNode].\nImplicit Arguments childrenCount [Dom DomNode].\nImplicit Arguments getChildNode [Dom DomNode].\nImplicit Arguments createTextNode [Dom DomNode].\nImplicit Arguments createElement [Dom DomNode].\nImplicit Arguments appendChild [Dom DomNode].\nImplicit Arguments removeChildAt [Dom DomNode].\nImplicit Arguments replaceChildAt [Dom DomNode].\nImplicit Arguments getTagName [Dom DomNode].\nImplicit Arguments getText [Dom DomNode].\nImplicit Arguments setText [Dom DomNode].\n\nDefinition DomNode := nat.\n\nInductive DomNodeCell: Set  := \n  | DomText (t: String.string) \n  | DomElement (name: String.string) (children: list DomNode).\n\nDefinition Dom := list DomNodeCell.\n\nDefinition getNodeCell dom node := nth node dom (DomText String.EmptyString).\n\nDefinition domOps: DomOps Dom DomNode := {|\n  getNodeType node := \n    do dom <- stGet;\n    match getNodeCell dom node with\n    | DomText _ => stRet TextNode\n    | DomElement _ _ => stRet ElementNode\n    end;\n  childrenCount node :=\n    do dom <- stGet;\n    match getNodeCell dom node with\n    | DomText _ => stRet 0\n    | DomElement _ children => stRet (length children)\n    end;\n  getChildNode node index :=\n    do dom <- stGet;\n    match getNodeCell dom node with\n    | DomText _ => stRet 0\n    | DomElement _ children => stRet (nth index children 0)\n    end;\n  createTextNode text :=\n    do dom <- stGet;\n    let len := length dom in\n    do _ <- stPut (dom ++ (DomText text :: nil));\n    stRet len;\n  createElement tag :=\n    do dom <- stGet;\n    let len := length dom in\n    do _ <- stPut (dom ++ (DomElement tag nil :: nil));\n    stRet len;\n  appendChild parent child :=\n    do dom <- stGet;\n    match getNodeCell dom parent with\n    | DomText _ => stRet tt\n    | DomElement tag children => \n        stPut (replaceNth parent dom (DomElement tag (children ++ child::nil)))\n    end;\n  removeChildAt node index :=\n    do dom <- stGet;\n    match getNodeCell dom node with\n    | DomText _ => stRet tt\n    | DomElement tag children => \n        stPut (replaceNth node dom (DomElement tag \n          (firstn index children ++ skipn (S index) children)))\n    end;\n  replaceChildAt node index newChild :=\n    do dom <- stGet;\n    match getNodeCell dom node with\n    | DomText _ => stRet tt\n    | DomElement tag children => \n        stPut (replaceNth node dom (DomElement tag (replaceNth index children newChild)))\n    end;\n  getTagName node :=\n    do dom <- stGet;\n    match getNodeCell dom node with\n    | DomText _ => stRet String.EmptyString\n    | DomElement tag _ => stRet tag\n    end;\n  getText node :=\n    do dom <- stGet;\n    match getNodeCell dom node with\n    | DomText text => stRet text\n    | DomElement _ _ => stRet String.EmptyString\n    end;\n  setText node newText :=\n    do dom <- stGet;\n    match getNodeCell dom node with\n    | DomText _ => \n        stPut (replaceNth node dom (DomText newText))\n    | DomElement tag children => stRet tt\n    end;\n  |}.\n\n(* *** *)\n\nInductive VDomNode := \n  VText (t: String.string) | VElement (name: String.string) (children: list VDomNode).\n\nFixpoint vdomDepth (node: VDomNode) : nat :=\n  match node with\n  | VText _ => 0\n  | VElement _ children => S (fold_right max 0 (map vdomDepth children))\n  end.\n\nSection VDomNodeFullInd.\n\nVariable P: VDomNode -> Prop.\nVariable PText: forall text, P (VText text).\nVariable PElement: forall name children, Forall P children -> P (VElement name children).\n\nFixpoint VDomNode_fullInd (node: VDomNode) : P node :=\n  match node with\n  | VText text => PText text\n  | VElement name children =>\n      PElement name _ ((fix nodesInd (nodes: list VDomNode) : Forall P nodes :=\n        match nodes return Forall P nodes with\n        | nil => Forall_nil _\n        | node::nodes => Forall_cons node (VDomNode_fullInd node) (nodesInd nodes)\n        end) children)\n  end.\n\nEnd VDomNodeFullInd.\n\n(* *** *)\n\nFixpoint createNode (node: VDomNode) : State Dom DomNode :=\n  let createNodes := fix createNodes (parent: DomNode) (nodes: list VDomNode) \n    : State Dom (list DomNode) :=\n    match nodes with\n    | nil => stRet nil\n    | node::nodes => \n      do n <- createNode node;\n      do _ <- domOps.(appendChild) parent n;\n      do ns <- createNodes parent nodes;\n      stRet (n::ns)\n    end in\n  match node with\n  | VText t => domOps.(createTextNode) t\n  | VElement name children =>\n    do el <- domOps.(createElement) name;\n    do els <- createNodes el children;\n    stRet el\n  end.\n\nFixpoint removeNodes (parent: DomNode) (from: nat) (count: nat) \n  {struct count} : State Dom unit :=\n  match count with\n  | 0 => stRet tt\n  | S count => \n      do _ <- domOps.(removeChildAt) parent (count + from);\n      removeNodes parent from count\n  end.\n\nFixpoint updateNode (parent: DomNode) (newNode: VDomNode) (index: nat) {struct newNode} \n  : State Dom unit :=\n  let updateNodes := \n    fix updateNodes (parent: DomNode) (newNodes: list VDomNode) (index: nat)\n      {struct newNodes} : State Dom unit :=\n      match newNodes with\n      | nil => stRet tt\n      | newNode::newNodes =>\n          do len <- domOps.(childrenCount) parent;\n          do _ <- \n            if index <? len then\n              updateNode parent newNode index\n            else\n              do node <- createNode newNode;\n              domOps.(appendChild) parent node;\n          updateNodes parent newNodes (S index)\n      end\n    in\n  do oldNode <- domOps.(getChildNode) parent index;\n  do oldNodeType <- domOps.(getNodeType) oldNode;\n  match newNode, oldNodeType with\n  | VElement name children, ElementNode => \n      do oldName <- domOps.(getTagName) oldNode;\n      if String.string_dec name oldName then\n        do oldLen <- domOps.(childrenCount) oldNode;\n        let newLen := length children in\n        do _ <- if newLen <? oldLen then removeNodes oldNode newLen (oldLen - newLen) else stRet tt;\n        updateNodes oldNode children 0\n      else\n        do node <- createNode newNode;\n        domOps.(replaceChildAt) parent index node\n  | VText text, TextNode =>\n      do oldText <- domOps.(getText) oldNode;\n      if String.string_dec text oldText then stRet tt\n      else domOps.(setText) oldNode text\n  | _, _ => \n      do node <- createNode newNode;\n      domOps.(replaceChildAt) parent index node\n  end.\n\n(* *** *)\n\nFixpoint dom2vdom (maxDepth: nat) (root: DomNode) {struct maxDepth} : State Dom VDomNode :=\n  do type <- domOps.(getNodeType) root;\n  match type with\n  | TextNode => \n      do text <- domOps.(getText) root;\n      stRet (VText text)\n  | ElementNode =>\n      do tag <- domOps.(getTagName) root;\n      do children <- match maxDepth with\n        | 0 => stRet nil\n        | S maxDepth => \n            let convChildren :=\n              fix convChildren index count :=\n                match count with\n                | 0 => stRet nil\n                | S count =>\n                    do childNode <- domOps.(getChildNode) root index;\n                    do vnode <- dom2vdom maxDepth childNode;\n                    do vnodes <- convChildren (S index) count;\n                    stRet (vnode::vnodes)\n                end\n              in\n            do count <- domOps.(childrenCount) root;\n            convChildren 0 count\n        end;\n      stRet (VElement tag children)\n  end.\n\nDefinition ValidDomNode (dom: Dom) (node: DomNode) : Prop := node < length dom.\n\nDefinition ValidDom (dom: Dom) : Prop :=\n  exists nodeDepth: DomNode -> nat,\n    forall node: DomNode, exists tag children, \n      getNodeCell dom node = DomElement tag children -> \n      forall child, In child children -> nodeDepth child > nodeDepth node.\n\nLemma createNode_correct: forall vnode,\n  exists f, createNode vnode = MkState f\n    /\\ forall dom, exists dom1, f dom = (length dom, dom ++ dom1)\n      /\\ forall dom2, length dom = length dom2 ->\n          stEval (dom2vdom (vdomDepth vnode) (length dom)) (dom2 ++ dom1) = vnode.\nProof.\n  intros. exists (stRun (createNode vnode)).\n  induction vnode using VDomNode_fullInd.\n  - simpl. intros. split; auto. intros.\n    exists (DomText text :: nil). split; auto. intros.\n    unfold stEval, stRun. unfold getNodeCell at 1.\n    rewrite app_nth2; try (rewrite H; auto with arith).\n    rewrite <- minus_diag_reverse. simpl.\n    unfold getNodeCell at 1.\n    rewrite app_nth2; auto with arith.\n    rewrite <- minus_diag_reverse. reflexivity.\n  - split; auto. unfold createNode. fold createNode.\n    assert (HcreateNodes: forall dom dom1 tag nodes0 depth, \n      depth > fold_right max 0 (map vdomDepth children) ->\n      exists nodes, exists dom2,\n      (stRun ((fix createNodes (parent : DomNode) (nodes : list VDomNode) {struct nodes} :\n        State Dom (list DomNode) :=\n        match nodes with\n        | nil => stRet nil\n        | node :: nodes0 =>\n            do n <- createNode node;\n            do _ <- appendChild domOps parent n;\n            do ns <- createNodes parent nodes0; stRet (n :: ns)\n        end) (length dom) children) (dom ++ DomElement tag nodes0 :: dom1) \n        = (nodes, dom ++ DomElement tag (nodes0 ++ nodes) :: dom1 ++ dom2)\n      /\\ forall dom3, length dom = length dom3 -> \n        Forall2 (fun node child => stEval (dom2vdom depth node) \n            (dom3 ++ DomElement tag (nodes0 ++ nodes) :: dom1 ++ dom2) = child)\n          nodes children)).\n    { clear name. revert H. induction children.\n      - simpl. intros. exists nil. exists nil. intros. \n        repeat (rewrite app_nil_r). split; auto.\n      - intros. inversion H. subst.\n        rewrite stRun_stBind. destruct H3 as [Hcn1 Hcn2].\n        specialize (Hcn2 (dom ++ DomElement tag nodes0 :: dom1)).\n        destruct Hcn2 as [dom2 [Hcn2 Hcn3]].\n        rewrite app_length in Hcn2. simpl in Hcn2. rewrite plus_comm in Hcn2. \n        simpl in Hcn2. rewrite Hcn2. cbn [fst snd].\n        rewrite stRun_stBind. unfold stRun at 1.\n        unfold appendChild at 2.\n        cbn [domOps].\n        unfold stBind at 5. unfold stGet at 1.\n        unfold getNodeCell. rewrite <- app_assoc. cbn [app].\n        rewrite app_nth2; auto with arith.\n        rewrite <- minus_diag_reverse. cbn [nth].\n        unfold stPut at 1.\n        rewrite replaceNth_app_r; auto with arith.\n        rewrite <- minus_diag_reverse. cbn [replaceNth snd app].\n        rewrite stRun_stBind.\n        simpl in H0.\n        specialize (IHchildren H4).\n        assert (Hgt: depth > fold_right Init.Nat.max 0 (map vdomDepth children)).\n        { unfold gt in *. rewrite Nat.max_lub_lt_iff in H0.\n          destruct H0. assumption. }\n        specialize (IHchildren dom (dom1 ++ dom2) tag \n          (nodes0 ++ S (length dom1 + length dom) :: nil) depth Hgt).\n        destruct IHchildren as [nodes [dom3 [IH1 IH2]]].\n        rewrite IH1. simpl.\n        exists (S (length dom1 + length dom) :: nodes). simpl.\n        exists (dom2 ++ dom3).\n        split.\n        + f_equal. f_equal.\n          repeat (rewrite <- app_assoc). reflexivity.\n        + intros. constructor.\n          * rewrite app_length in Hcn3. simpl in Hcn3.\n            admit.\n          * admit.\n    }\n    intros. \n    assert (Hgt: vdomDepth (VElement name children) >\n     fold_right Init.Nat.max 0 (map vdomDepth children)); auto with arith.\n    destruct (HcreateNodes dom nil name nil  \n      (vdomDepth (VElement name children)) Hgt) as [nodes [dom1 [Hcns1 Hcns2]]].\n    exists (DomElement name nodes :: dom1).\n    split.\n    { rewrite stRun_stBind. unfold domOps at 1. unfold createElement.\n      repeat (rewrite stRun_stBind).\n      remember (fix createNodes (parent : DomNode) (nodes : list VDomNode) {struct nodes} :\n        State Dom (list DomNode) :=\n        match nodes with\n        | nil => stRet nil\n        | node :: nodes0 =>\n            do n <- createNode node;\n            do _ <- appendChild domOps parent n;\n            do ns <- createNodes parent nodes0; stRet (n :: ns)\n        end)\n        as createNodes.\n      simpl. f_equal. \n      subst.\n      rewrite Hcns1. reflexivity.\n    }\n    { simpl. intros. unfold stEval, stRun. rewrite H0.\n      unfold getNodeCell at 1. \n      rewrite app_nth2; auto with arith.\n      rewrite <- minus_diag_reverse. simpl.\n      unfold getNodeCell at 1. \n      rewrite app_nth2; auto with arith.\n      rewrite <- minus_diag_reverse. simpl.\n      unfold getNodeCell at 1. \n      rewrite app_nth2; auto with arith.\n      rewrite <- minus_diag_reverse. simpl.\n      admit.\n    }\nAdmitted.\n\nTheorem updateNode_correct: forall vdom dom parent index,\n  ValidDomNode dom parent ->\n  stEval (domOps.(getNodeType) parent) dom = ElementNode ->\n  index < stEval (domOps.(childrenCount) parent) dom ->\n  stEval (\n    do _ <- updateNode parent vdom index;\n    do node <- domOps.(getChildNode) parent index;\n    dom2vdom (vdomDepth vdom) node) dom \n  = vdom.\nProof.\n  induction vdom using VDomNode_fullInd.\n  - simpl. intros. unfold stEval, stRun in *.\n    destruct (getNodeCell dom parent) as [oldText | parentTag nodes] eqn: Heq; \n      try (simpl in *; congruence).\n    unfold stRet in *. simpl in *.\n    destruct (getNodeCell dom (nth index nodes 0)) as [oldText | tag children] eqn: Heq1.\n    + rewrite Heq1. destruct (String.string_dec text oldText) as [Heq2 | Hneq].\n      * subst. rewrite Heq. repeat (rewrite Heq1). reflexivity.\n      * rewrite Heq1. unfold stPut. unfold getNodeCell at 1.\n        rewrite nth_replaceNth_diffInd.\n        2: admit. (* try to use [ValidDom]/[nodeDepth] to discharge *)\n        fold (getNodeCell dom parent).\n        rewrite Heq. unfold getNodeCell at 1.\n        rewrite nth_replaceNth_sameInd.\n        destruct (nth index nodes 0 <? length dom) eqn: Hltb.\n        2: admit.\n        unfold getNodeCell at 1.\n        rewrite nth_replaceNth_sameInd.\n        rewrite Hltb. reflexivity.\n    + unfold getNodeCell at 1. rewrite app_nth1; auto.\n      fold (getNodeCell dom parent).\n      rewrite Heq. unfold stPut. \n      unfold getNodeCell at 1.\n      rewrite nth_replaceNth_sameInd.\n      rewrite app_length. simpl. rewrite plus_comm. simpl.\n      destruct (parent <? S (length dom)) eqn: Hltb.\n      2: admit.\n      rewrite nth_replaceNth_sameInd.\n      destruct (index <? length nodes) eqn: Hltb1.\n      2: admit.\n      unfold getNodeCell at 1.\n      rewrite replaceNth_app_l; auto.\n      rewrite app_nth2.\n      2: rewrite length_replaceNth; auto with arith.\n      rewrite length_replaceNth. rewrite <- minus_diag_reverse. simpl.\n      unfold getNodeCell at 1.\n      rewrite app_nth2.\n      2: rewrite length_replaceNth; auto with arith.\n      rewrite length_replaceNth. rewrite <- minus_diag_reverse. reflexivity.\n  - cbn -[createNode updateNode dom2vdom].\n    intros. unfold stEval, stRun in *. \n    cbn -[createNode dom2vdom].\n    destruct (getNodeCell dom parent) as [oldText | parentTag nodes] eqn: Heq; \n      try (simpl in *; congruence).\n    unfold stRet in *. simpl in * |-.\n    destruct (getNodeCell dom (nth index nodes 0)) as [text | tag oldChildren] eqn: Heq1.\n    + unfold stBind.\n      destruct (createNode_correct (VElement name children)) as [f [Heqcn Hcn]].\n      rewrite Heqcn. destruct (Hcn dom) as [dom1 [Heqcn1 Heqcn2]].\n      rewrite Heqcn1. unfold getNodeCell at 1.\n      rewrite app_nth1; auto with arith.\n      fold (getNodeCell dom parent). rewrite Heq.\n      unfold stPut. rewrite replaceNth_app_l; auto.\n      unfold getNodeCell at 1. \n      rewrite app_nth1.\n      2: rewrite length_replaceNth; auto with arith.\n      rewrite nth_replaceNth_sameInd.\n      destruct (parent <? length dom) eqn: Hltb.\n      2: admit.\n      unfold stEval, stRun, vdomDepth in Heqcn2. fold vdomDepth in Heqcn2.\n      rewrite nth_replaceNth_sameInd.\n      destruct (index <? length nodes) eqn: Hltb1.\n      2: admit.\n      rewrite Heqcn2; auto.\n      rewrite length_replaceNth. reflexivity.\n    + admit. \n\nQed.\n\n\nEnd VDom.\n", "meta": {"author": "dkrustev", "repo": "coq-misc-essays", "sha": "3cecd11e601dc64447820207240123e8f978366e", "save_path": "github-repos/coq/dkrustev-coq-misc-essays", "path": "github-repos/coq/dkrustev-coq-misc-essays/coq-misc-essays-3cecd11e601dc64447820207240123e8f978366e/VirtualDom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.6546253417678048}}
{"text": "Require Coq.Setoids.Setoid.\nRequire Import Coq.Classes.Morphisms.\nRequire Export Coq.Classes.Equivalence.\nRequire Export Coq.Sets.Ensembles.\nRequire Import Coq.Sets.Constructive_sets.\nRequire Import RamifyCoq.lib.Coqlib.\nRequire Import RamifyCoq.lib.EquivDec_ext.\n\nLemma Full_set_spec: forall A (v: A), Full_set A v <-> True.\nProof.\n  intros.\n  split; intros; constructor.\nQed.\n\nLemma Empty_set_spec: forall A (v: A), Empty_set A v <-> False.\n  intros.\n  split; intros [].\nQed.\n\nLemma Intersection_spec: forall A (v: A) P Q, Intersection _ P Q v <-> P v /\\ Q v.\nProof.\n  intros.\n  split; intros.\n  + inversion H; auto.\n  + constructor; tauto.\nQed.\n\nLemma Union_spec: forall A (v: A) P Q, Union _ P Q v <-> P v \\/ Q v.\nProof.\n  intros.\n  split; intros.\n  + inversion H; auto.\n  + destruct H; [apply Union_introl | apply Union_intror]; auto.\nQed.\n\nLemma Disjoint_spec: forall A P Q, Disjoint A P Q <-> (forall x, P x -> Q x -> False).\nProof.\n  intros; split; intros.\n  + inversion H.\n    eapply H2.\n    unfold In; rewrite Intersection_spec; split; eauto.\n  + constructor.\n    intros.\n    unfold In; rewrite Intersection_spec.\n    intro; apply H with x; tauto.\nQed.\n\nLemma Included_Full_set: forall A P, Included A P (Full_set A).\nProof.\n  intros.\n  hnf; unfold In; intros.\n  apply Full_set_spec; auto.\nQed.\n\nLemma Intersection_Complement: forall A (P Q: Ensemble A),\n  Same_set A\n  (Intersection A (Complement A P) (Complement A Q))\n  (Complement A (Union A P Q)).\nProof.\n  intros.\n  unfold Same_set, Included, Complement, Ensembles.In.\n  split; intros.\n  + rewrite Union_spec.\n    rewrite Intersection_spec in H.\n    tauto.\n  + rewrite Union_spec in H.\n    rewrite Intersection_spec.\n    tauto.\nQed.\n\nLemma Union_iff: forall U A B x, Ensembles.In U (Union U A B) x <-> Ensembles.In U A x \\/ Ensembles.In U B x.\nProof.\n  intros; split; intros.\n  + apply Constructive_sets.Union_inv; auto.\n  + destruct H; [apply Union_introl | apply Union_intror]; auto.\nQed.\n\nLemma Empty_set_iff: forall U x, Ensembles.In U (Empty_set U) x <-> False.\nProof.\n  intros; split; intro; inversion H.\nQed.\n\nLemma Singleton_iff: forall U x y, Ensembles.In U (Singleton U x) y <-> x = y.\nProof.\n  intros; split; intro.\n  + inversion H; auto.\n  + subst; constructor.\nQed.\n\nArguments Included {U} B C.\nArguments Same_set {U} B C.\n\nLemma Same_set_refl: forall A (S : Ensemble A), Same_set S S. Proof. intros; split; intro; tauto. Qed.\n\nLemma Same_set_sym: forall A (S1 S2 : Ensemble A), Same_set S1 S2 -> Same_set S2 S1. Proof. intros; destruct H; split; auto. Qed.\n\nLemma Same_set_trans: forall A (S1 S2 S3: Ensemble A), Same_set S1 S2 -> Same_set S2 S3 -> Same_set S1 S3.\nProof. intros; destruct H, H0; split; repeat intro; [apply H0, H, H3 | apply H1, H2, H3]. Qed.\n\nAdd Parametric Relation {A} : (Ensemble A) Same_set\n    reflexivity proved by (Same_set_refl A)\n    symmetry proved by (Same_set_sym A)\n    transitivity proved by (Same_set_trans A) as Same_set_rel.\n\nLemma Same_set_spec: forall A P Q, Same_set P Q <-> (pointwise_relation A iff) P Q.\nProof.\n  intros.\n  unfold Same_set, Included, In, pointwise_relation.\n  firstorder.\nQed.\n\nLemma Complement_Empty_set: forall A, Same_set (Complement A (Empty_set _)) (Full_set _).\nProof.\n  intros.\n  rewrite Same_set_spec.\n  intro a.\n  unfold Complement, Ensembles.In.\n  pose proof Empty_set_iff _ a.\n  pose proof Full_set_spec _ a.\n  tauto.\nQed.\n\nLemma Intersection_comm: forall A P Q, Same_set (Intersection A P Q) (Intersection A Q P).\nProof.\n  intros.\n  rewrite Same_set_spec; hnf; intros.\n  rewrite !Intersection_spec.\n  tauto.\nQed.\n\nLemma Intersection_assoc: forall A P Q R, Same_set (Intersection A (Intersection A P Q) R) (Intersection A P (Intersection A Q R)).\nProof.\n  intros.\n  rewrite Same_set_spec; hnf; intros.\n  rewrite !Intersection_spec.\n  tauto.\nQed.\n\nLemma Union_comm: forall A P Q, Same_set (Union A P Q) (Union A Q P).\nProof.\n  intros.\n  rewrite Same_set_spec; hnf; intros.\n  rewrite !Union_spec.\n  tauto.\nQed.\n\nLemma Union_assoc: forall A P Q R, Same_set (Union A (Union A P Q) R) (Union A P (Union A Q R)).\nProof.\n  intros.\n  rewrite Same_set_spec; hnf; intros.\n  rewrite !Union_spec.\n  tauto.\nQed.\n\nLemma Intersection_Union_distr_l: forall A P Q R,\n  Same_set (Intersection A (Union A Q R) P)\n   (Union A (Intersection A Q P) (Intersection A R P)).\nProof.\n  intros.\n  rewrite Same_set_spec; intro x.\n  rewrite !Intersection_spec, !Union_spec, !Intersection_spec.\n  tauto.\nQed.\n\nLemma Intersection_Union_distr_r: forall A P Q R,\n  Same_set (Intersection A P (Union A Q R))\n   (Union A (Intersection A P Q) (Intersection A P R)).\nProof.\n  intros.\n  rewrite Same_set_spec; intro x.\n  rewrite !Intersection_spec, !Union_spec, !Intersection_spec.\n  tauto.\nQed.\n\nInstance Included_proper (V: Type): Proper (Same_set ==> Same_set ==> iff) (@Included V).\nProof.\n  hnf; intros.\n  hnf; intros.\n  rewrite Same_set_spec in *.\n  unfold pointwise_relation, Included, Ensembles.In in *.\n  firstorder.\nDefined.\n\nInstance complement_proper (V: Type): Proper (Same_set ==> Same_set) (Complement V).\n  hnf; intros.\n  rewrite Same_set_spec in *.\n  hnf; intros.\n  unfold Complement, Ensembles.In.\n  specialize (H a).\n  tauto.\nDefined.\n\nInstance Union_proper (V: Type): Proper (Same_set ==> Same_set ==> Same_set) (Union V).\n  hnf; intros.\n  hnf; intros.\n  rewrite Same_set_spec in *.\n  unfold pointwise_relation in *; intros.\n  rewrite !Union_spec.\n  firstorder.\nDefined.\n\nInstance Disjoint_proper (V: Type): Proper (Same_set ==> Same_set ==> iff) (Disjoint V).\n  hnf; intros.\n  hnf; intros.\n  rewrite Same_set_spec in *.\n  unfold pointwise_relation in *.\n  rewrite !Disjoint_spec.\n  firstorder.\nDefined.\n\nLemma Union_Included {A: Type}: forall P Q R, Included (Union A P Q) R <-> Included P R /\\ Included Q R.\nProof.\n  intros.\n  unfold Included.\n  pose proof Union_iff A P Q.\n  firstorder.\nQed.\n\nLemma left_Included_Union {A: Type}: forall P Q, Included P (Union A P Q).\nProof.\n  intros.\n  intros ? ?.\n  rewrite Union_iff.\n  tauto.\nQed.\n\nLemma right_Included_Union {A: Type}: forall P Q, Included Q (Union A P Q).\nProof.\n  intros.\n  intros ? ?.\n  rewrite Union_iff.\n  tauto.\nQed.\n\nLemma Union_Empty_left {A: Type}: forall P, Same_set (Union _ (Empty_set A) P) P.\nProof.\n  intros.\n  rewrite Same_set_spec.\n  hnf; intros.\n  rewrite Union_spec.\n  pose proof Noone_in_empty A a.\n  tauto.\nQed.\n\nLemma Union_Empty_right {A: Type}: forall P, Same_set (Union _ P (Empty_set A)) P.\nProof.\n  intros.\n  rewrite Same_set_spec.\n  hnf; intros.\n  rewrite Union_spec.\n  pose proof Noone_in_empty A a.\n  tauto.\nQed.\n\nLemma Intersection_Full_left {A: Type}: forall P, Same_set (Intersection _ (Full_set A) P) P.\nProof.\n  intros.\n  rewrite Same_set_spec.\n  hnf; intros.\n  rewrite Intersection_spec.\n  pose proof Full_set_spec A a.\n  tauto.\nQed.\n\nLemma Intersection_Full_right {A: Type}: forall P, Same_set (Intersection _ P (Full_set A)) P.\nProof.\n  intros.\n  rewrite Same_set_spec.\n  hnf; intros.\n  rewrite Intersection_spec.\n  pose proof Full_set_spec A a.\n  tauto.\nQed.\n\nLemma Intersection_Empty_left {A: Type}: forall P, Same_set (Intersection _ (Empty_set A) P) (Empty_set A).\nProof.\n  intros.\n  rewrite Same_set_spec.\n  hnf; intros.\n  rewrite Intersection_spec.\n  pose proof Empty_set_spec A a.\n  tauto.\nQed.\n\nLemma Intersection_Empty_right {A: Type}: forall P, Same_set (Intersection _ P (Empty_set A)) (Empty_set A).\nProof.\n  intros.\n  rewrite Same_set_spec.\n  hnf; intros.\n  rewrite Intersection_spec.\n  pose proof Empty_set_spec A a.\n  tauto.\nQed.\n\nLemma Intersection_absort_right: forall U (A B: Ensemble U), Included A B -> Same_set (Intersection _ A B) A.\nProof.\n  intros.\n  rewrite Same_set_spec; intro x.\n  rewrite Intersection_spec.\n  specialize (H x); unfold Ensembles.In in H.\n  tauto.\nQed.\n\nLemma Intersection_absort_left: forall U (A B: Ensemble U), Included B A -> Same_set (Intersection _ A B) B.\nProof.\n  intros.\n  rewrite Same_set_spec; intro x.\n  rewrite Intersection_spec.\n  specialize (H x); unfold Ensembles.In in H.\n  tauto.\nQed.\n\nLemma Complement_Included_rev: forall (U: Type) P Q, Included P Q -> Included (Complement U Q) (Complement U P).\nProof.\n  unfold Included, Complement, Ensembles.In.\n  intros.\n  firstorder.\nQed.\n\nLemma Prop_join_shrink: forall {U} (A B C R: Ensemble U),\n  Included B R ->\n  Prop_join A B C ->\n  Prop_join (Intersection _ A R) B (Intersection _ C R).\nProof.\n  unfold Prop_join, Included, Ensembles.In.\n  intros.\n  split; intros; rewrite !Intersection_spec in *; auto.\n  + split; firstorder.\n  + firstorder.\nQed.\n\nLemma Prop_join_shrink1: forall {U} (A B C: Ensemble U) (x: U),\n  A x ->\n  Prop_join A B C ->\n  Prop_join (Intersection _ A (fun x0 => x <> x0)) B (Intersection _ C (fun x0 => x <> x0)).\nProof.\n  intros.\n  apply Prop_join_shrink; auto.\n  unfold Included, In; intros.\n  intro.\n  subst x0.\n  destruct H0.\n  apply (H2 x); auto.\nQed.\n\nLemma Ensemble_join_Intersection_Complement: forall {A} P Q,\n  Included Q P ->\n  (forall x, Q x \\/ ~ Q x) ->\n  Prop_join Q (Intersection A P (Complement A Q)) P.\nProof.\n  intros.\n  unfold Prop_join.\n  unfold Included, Ensembles.In in H.\n  split; intros x; specialize (H0 x); specialize (H x);\n  rewrite Intersection_spec; unfold Complement, Ensembles.In; try tauto.\nQed.\n\nInstance Intersection_proper {A}: Proper (Same_set ==> Same_set ==> Same_set) (Intersection A).\nProof.\n  do 2 (hnf; intros).\n  rewrite Same_set_spec in *.\n  intro a; specialize (H0 a); specialize (H a).\n  rewrite !Intersection_spec.\n  tauto.\nDefined.\n\nInstance Prop_join_proper {A}: Proper (@Same_set A ==> Same_set ==> Same_set ==> iff) Prop_join.\nProof.\n  intros.\n  do 3 (hnf; intros).\n  rewrite Same_set_spec in *.\n  unfold pointwise_relation in *.\n  split; intros [? ?]; split; intro; firstorder.\nDefined.\n\nLemma Included_Disjoint: forall A P Q P' Q',\n  Included P P' ->\n  Included Q Q' ->\n  Disjoint A P' Q' ->\n  Disjoint A P Q.\nProof.\n  intros.\n  rewrite Disjoint_spec in H1 |- *.\n  intros; apply (H1 x).\n  + apply H; auto.\n  + apply H0; auto.\nQed.\n\nLemma Union_left_Disjoint: forall A P Q R,\n  Disjoint A (Union A P Q) R <-> Disjoint A P R /\\ Disjoint A Q R.\nProof.\n  intros.\n  rewrite !Disjoint_spec.\n  pose proof (fun x => Union_spec A x P Q).\n  firstorder.\nQed.\n\nLemma Union_right_Disjoint: forall A P Q R,\n  Disjoint A R (Union A P Q) <-> Disjoint A R P /\\ Disjoint A R Q.\nProof.\n  intros.\n  rewrite !Disjoint_spec.\n  pose proof (fun x => Union_spec A x P Q).\n  firstorder.\nQed.\n\nLemma Included_Complement_Disjoint: forall A P Q,\n  (Included P (Complement _ Q)) <-> Disjoint A P Q.\nProof.\n  intros.\n  unfold Included, Complement, In.\n  rewrite Disjoint_spec.\n  firstorder.\nQed.\n\nLemma Disjoint_comm: forall A P Q,\n  Disjoint A P Q <-> Disjoint A Q P.\nProof.\n  intros.\n  rewrite !Disjoint_spec.\n  firstorder.\nQed.\n\nLemma Disjoint_Empty_set_right: forall {A} (P: Ensemble A), Disjoint A P (Empty_set A).\nProof.\n  intros.\n  rewrite Disjoint_comm.\n  apply Included_Complement_Disjoint.\n  apply Constructive_sets.Included_Empty.\nQed.\n\nLemma Disjoint_Empty_set_left: forall {A} (P: Ensemble A), Disjoint A (Empty_set A) P.\nProof.\n  intros.\n  apply Included_Complement_Disjoint.\n  apply Constructive_sets.Included_Empty.\nQed.\n\nLemma Disjoint_x1: forall {U} {UE: EqDec U eq} (A B: Ensemble U) (x0: U),\n  Disjoint U (fun x: U => A x /\\ x0 <> x) B ->\n  ~ B x0 ->\n  Disjoint U A B.\nProof.\n  intros.\n  rewrite Disjoint_spec in H |- *.\n  intros.\n  specialize (H x).\n  destruct_eq_dec x0 x; [subst |]; tauto.\nQed.\n\nLemma Disjoint_x1': forall {U} {UE: EqDec U eq} (A B: Ensemble U) (x0: U),\n  Disjoint U (Intersection _ A (fun x: U => x0 <> x)) B ->\n  ~ B x0 ->\n  Disjoint U A B.\nProof.\n  intros.\n  rewrite Disjoint_spec in H |- *.\n  intros.\n  specialize (H x).\n  rewrite Intersection_spec in H.\n  destruct_eq_dec x0 x; [subst |]; tauto.\nQed.\n\nLemma Included_trans: forall {A} (P Q R: Ensemble A), Included P Q -> Included Q R -> Included P R.\nProof.\n  unfold Included, Ensembles.In.\n  intros; firstorder.\nQed.\n\nLemma Intersection1_Included: forall {A} P Q R, Included P R -> Included (Intersection A P Q) R.\nProof.\n  unfold Included, Ensembles.In.\n  intros.\n  rewrite Intersection_spec in H0.\n  firstorder.\nQed.\n\nLemma Intersection2_Included: forall {A} P Q R, Included Q R -> Included (Intersection A P Q) R.\nProof.\n  unfold Included, Ensembles.In.\n  intros.\n  rewrite Intersection_spec in H0.\n  firstorder.\nQed.\n\nLemma Included_refl: forall A P, @Included A P P.\nProof.\n  intros; hnf; auto.\nQed.\n\nLemma Prop_join_Disjoint:\n  forall {A : Type} (P Q R : Ensemble A),\n  Prop_join P Q R -> Disjoint A P Q.\nProof.\n  intros.\n  destruct H.\n  rewrite Disjoint_spec; auto.\nQed.\n\nLemma Prop_join_assoc: forall A (P1 P2 P3 Q R: A -> Prop),\n  Prop_join P1 Q P2 ->\n  Prop_join P2 R P3 ->\n  Prop_join P1 (Union _ Q R) P3.\nProof.\n  unfold Prop_join.\n  intros.\n  destruct H, H0.\n  split; intro a; rewrite Union_spec.\n  + rewrite H0, H.\n    tauto.\n  + intros.\n    destruct H4; firstorder.\nQed.\n\nLemma Prop_join_comm: forall {A : Type} (P Q R : Ensemble A),\n  Prop_join P Q R <-> Prop_join Q P R.\nProof.\n  intros.\n  unfold Prop_join.\n  firstorder.\nQed.\n\nLemma Disjoint_Union_Prop_join: forall A P Q, Disjoint A P Q -> Prop_join P Q (Union A P Q).\nProof.\n  intros.\n  rewrite Disjoint_spec in H.\n  split.\n  + intros; rewrite Union_spec; tauto.\n  + auto.\nQed.\n\nLemma Prop_join_Empty: forall {U} (A: Ensemble U), Prop_join A (Empty_set _) A.\nProof.\n  intros.\n  split; intros.\n  + rewrite Empty_set_spec.\n    tauto.\n  + rewrite Empty_set_spec in H0; auto.\nQed.\n\nLemma Prop_join_x1: forall {U} (A: Ensemble U) (a: U),\n  ~ A a ->\n  Prop_join A (eq a) (fun x => A x \\/ x = a).\nProof.\n  intros.\n  split; intros.\n  + assert (a = a0 <-> a0 = a) by (split; intros; congruence).\n    tauto.\n  + subst; auto.\nQed.\n\nDefinition app_same_set {A: Type} {P Q: Ensemble A} (H: Same_set P Q) (x: A): P x <-> Q x := proj1 (Same_set_spec A P Q) H x.\n\nCoercion app_same_set : Same_set >-> Funclass.\n\n(* TODO: rename it into preimage set *)\nDefinition respectful_set {A B: Type} (X: Ensemble B) (f: A -> B): Ensemble A := fun x => X (f x).\n\nInductive image_set {A B: Type}: Ensemble A -> (A -> B) -> Ensemble B :=\n  | image_set_intro: forall (X: Ensemble A) (f: A -> B) (x: A), X x -> image_set X f (f x).\n\nLemma image_set_spec: forall {A B: Type} f X (y: B),\n  image_set X f y <-> exists x: A, X x /\\ y = f x.\nProof.\n  intros.\n  split; intros.\n  + inversion H; subst.\n    exists x.\n    split; auto.\n  + destruct H as [x [?H ?H]].\n    subst.\n    constructor; auto.\nQed.\n\nInstance respectful_set_proper {A B: Type}: Proper (Same_set ==> pointwise_relation A (@eq B) ==> Same_set) respectful_set.\nProof.\n  intros.\n  do 2 (hnf; intros).\n  rewrite Same_set_spec in *.\n  unfold pointwise_relation in *.\n  unfold respectful_set.\n  firstorder.\n  + rewrite <- H, <- H0; firstorder.\n  + rewrite H, H0; firstorder.\nQed.\n\nInstance image_set_proper2 {A B: Type}: Proper (Same_set ==> eq ==> Same_set) (@image_set A B).\nProof.\n  intros.\n  do 2 (hnf; intros).\n  rewrite Same_set_spec in *.\n  unfold pointwise_relation in *.\n  intros.\n  rewrite !image_set_spec.\n  firstorder.\n  + subst. firstorder.\n  + subst. firstorder.\nQed.\n\nLemma resp_Included: forall {A B: Type} (X Y: Ensemble B) (f: A -> B),\n  Included X Y ->\n  Included (respectful_set X f) (respectful_set Y f).\nProof.\n  intros.\n  unfold respectful_set, Included, In.\n  intro x.\n  apply H.\nQed.\n\nLemma resp_Same_set: forall {A B: Type} (X Y: Ensemble B) (f: A -> B),\n  Same_set X Y ->\n  Same_set (respectful_set X f) (respectful_set Y f).\nProof.\n  intros.\n  unfold Same_set in *.\n  split; apply resp_Included; tauto.\nQed.\n\nLemma resp_Intersection: forall {A B: Type} (X Y: Ensemble B) (f: A -> B),\n  Same_set\n   (respectful_set (Intersection _ X Y) f)\n   (Intersection _ (respectful_set X f) (respectful_set Y f)).\nProof.\n  intros.\n  rewrite Same_set_spec; intros x.\n  unfold respectful_set.\n  rewrite !Intersection_spec.\n  reflexivity.\nQed.\n\nLemma resp_Union: forall {A B: Type} (X Y: Ensemble B) (f: A -> B) ,\n  Same_set\n   (respectful_set (Union _ X Y) f)\n   (Union _ (respectful_set X f) (respectful_set Y f)).\nProof.\n  intros.\n  rewrite Same_set_spec; intros x.\n  unfold respectful_set.\n  rewrite !Union_spec.\n  reflexivity.\nQed.\n\nLemma resp_Complement: forall {A B: Type} (X: Ensemble B) (f: A -> B),\n  Same_set\n   (respectful_set (Complement _ X) f)\n   (Complement _ (respectful_set X f)).\nProof.\n  intros.\n  rewrite Same_set_spec; intros x.\n  unfold respectful_set, Complement, In.\n  reflexivity.\nQed.\n\nLemma resp_Disjoint: forall {A B: Type} (X Y: Ensemble B) (f: A -> B),\n  Disjoint _ X Y ->\n  Disjoint _ (respectful_set X f) (respectful_set Y f).\nProof.\n  intros.\n  rewrite <- Included_Complement_Disjoint in *.\n  rewrite <- resp_Complement.\n  apply resp_Included; auto.\nQed.\n\nLemma resp_Empty: forall {A B: Type} (f: A -> B),\n  Same_set (respectful_set (Empty_set _) f) (Empty_set _).\nProof.\n  intros.\n  rewrite Same_set_spec.\n  intro x.\n  pose proof Noone_in_empty A.\n  pose proof Noone_in_empty B.\n  firstorder.\nQed.\n\nLemma image_Included: forall {A B: Type} (f: A -> B) (X Y: Ensemble A),\n  Included X Y ->\n  Included (image_set X f) (image_set Y f).\nProof.\n  intros.\n  unfold Included, In.\n  intro y.\n  rewrite !image_set_spec.\n  intros [x [? ?]].\n  exists x; split; auto.\n  apply H; auto.\nQed.\n\nLemma image_Same_set: forall {A B: Type} (f: A -> B) (X Y: Ensemble A),\n  Same_set X Y ->\n  Same_set (image_set X f) (image_set Y f).\nProof.\n  intros.\n  unfold Same_set in *.\n  split; apply image_Included; tauto.\nQed.\n\nLemma image_Intersection: forall {A B: Type} (X Y: Ensemble A) (f: A -> B),\n  Included\n   (image_set (Intersection _ X Y) f)\n   (Intersection _ (image_set X f) (image_set Y f)).\nProof.\n  intros.\n  unfold Included, In; intros y.\n  rewrite !Intersection_spec, !image_set_spec.\n  intros [x [? ?]].\n  rewrite Intersection_spec in H.\n  split; exists x; tauto.\nQed.\n\nLemma image_Union: forall {A B: Type} (X Y: Ensemble A) (f: A -> B),\n  Same_set\n   (image_set (Union _ X Y) f)\n   (Union _ (image_set X f) (image_set Y f)).\nProof.\n  intros.\n  rewrite Same_set_spec; intros y.\n  rewrite !Union_spec, !image_set_spec.\n  pose proof (fun x => Union_spec A x X Y).\n  firstorder.\nQed.\n\nLemma image_Disjoint_rev: forall {A B: Type} (X Y: Ensemble A) (f: A -> B),\n  Disjoint _ (image_set X f) (image_set Y f) ->\n  Disjoint _ X Y.\nProof.\n  intros.\n  rewrite Disjoint_spec in *.\n  intros x ? ?.\n  apply (H (f x)); constructor; auto.\nQed.\n\nLemma image_Empty: forall {A B: Type} (f: A -> B),\n  Same_set (image_set (Empty_set _) f) (Empty_set _).\nProof.\n  intros.\n  rewrite Same_set_spec.\n  intro x.\n  rewrite image_set_spec.\n  pose proof Noone_in_empty A.\n  pose proof Noone_in_empty B.\n  firstorder.\nQed.\n\nLemma image_single: forall {A B: Type} (a: A) (f: A -> B),\n  Same_set (image_set (eq a) f) (eq (f a)).\nProof.\n  intros.\n  rewrite Same_set_spec.\n  intro x.\n  rewrite image_set_spec.\n  split; intros; eauto.\n  destruct H as [? [? ?]]; subst; auto.\nQed.\n\nDefinition Countable_Union (A: Type) (P: nat -> Ensemble A) : Ensemble A :=\n  fun x => exists i, P i x.\n\nDefinition Non_Empty {U: Type} (A: Ensemble U): Prop := exists x, A x.\n\nDefinition Binart_set_list (U: Type) (A B: Ensemble U): nat -> Ensemble U :=\n  fun n => match n with | 0 => A | 1 => B | _ => Empty_set _ end.\n\nLemma Union_is_Countable_Union: forall {U: Type} (A B: Ensemble U),\n  Same_set (Union _ A B) (Countable_Union _ (Binart_set_list _ A B)).\nProof.\n  intros.\n  rewrite Same_set_spec.\n  intros x.\n  rewrite Union_spec; unfold Countable_Union.\n  split.\n  + intros [? | ?].\n    - exists 0; auto.\n    - exists 1; auto.\n  + intros [[ | [ | ]] ?].\n    - left; auto.\n    - right; auto.\n    - intros; inversion H.\nQed.\n\nLemma Intersection_is_Complement_Union (classic: forall P: Prop, P \\/ ~ P): forall {U: Type} (A B: Ensemble U),\n  Same_set (Intersection _ A B) (Complement _ (Union _ (Complement _ A) (Complement _ B))).\nProof.\n  intros.\n  rewrite Same_set_spec.\n  intros x; unfold Complement, Ensembles.In.\n  rewrite Union_spec, Intersection_spec.\n  destruct (classic (A x)), (classic (B x)); tauto.\nQed.\n\n(*\n\nLemma Finite_spec: forall A U, Finite A U <-> exists l, NoDup l /\\ forall x, In x l <-> Ensembles.In A U x.\nProof.\n  intros.\n  split; intros.\n  + induction H.\n    - exists nil.\n      split; [constructor |].\n      intros.\n      rewrite Empty_set_iff; simpl; tauto.\n    - destruct IHFinite as [l [? ?]].\n      exists (x :: l).\n      split; [constructor; auto; rewrite H2; auto |]. \n      intros x0; specialize (H2 x0).\n      simpl.\n      unfold Add.\n      rewrite Union_iff, Singleton_iff.\n      tauto.\n  + destruct H as [l [? ?]].\n    revert U H0; induction l; intros.\n    - replace U with (Empty_set A); [apply Empty_is_finite |].\n      apply Extensionality_Ensembles.\n      split; intros x ?; specialize (H0 x); simpl in *; repeat rewrite Empty_set_iff in *; tauto.\n    - replace U with (Add A (Subtract A U a) a);\n      [apply Union_is_finite | apply Extensionality_Ensembles].\n      * inversion H; subst.\n        apply IHl; [auto |].\n        intros x; specialize (H0 x).\n        unfold Subtract, Setminus; unfold Ensembles.In at 1.\n        simpl in H0.\n        rewrite Singleton_iff.\n        assert (a = x -> ~ In x l) by (intro; subst; auto).\n        tauto.\n      * unfold Subtract, Setminus; unfold Ensembles.In at 1.\n        rewrite Singleton_iff.\n        tauto.\n      * unfold Add, Subtract, Setminus.\n        split; intros ?; rewrite Union_iff;\n          [unfold Ensembles.In at 1 | unfold Ensembles.In at 2];\n          rewrite  Singleton_iff; intro;\n          specialize (H0 x); simpl in H0; [tauto |].\n        inversion H; subst.\n        assert (a = x -> ~ In x l) by (intro; subst; auto).\n        tauto.\nQed.\n\n*)\n", "meta": {"author": "johndoe20190406", "repo": "RamifyCoq", "sha": "72fb538b40ee8ea641e4bf5fe6cd232756d0929c", "save_path": "github-repos/coq/johndoe20190406-RamifyCoq", "path": "github-repos/coq/johndoe20190406-RamifyCoq/RamifyCoq-72fb538b40ee8ea641e4bf5fe6cd232756d0929c/lib/Ensembles_ext.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.8006920068519378, "lm_q1q2_score": 0.6546253409764013}}
{"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 monday.\n\nExample test_next_weekday:\n  next_weekday (next_weekday saturday) = tuesday.\nProof. simpl. reflexivity. Qed.\n", "meta": {"author": "GanZiheng", "repo": "learn-coq", "sha": "6d915f299e0b483ba53a8184c9ec13ac275aeca6", "save_path": "github-repos/coq/GanZiheng-learn-coq", "path": "github-repos/coq/GanZiheng-learn-coq/learn-coq-6d915f299e0b483ba53a8184c9ec13ac275aeca6/Src/day.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.6546253312554748}}
{"text": "Require Import Coqlib.\nRequire Import RelationPairs.\nRequire Import AST.\nRequire Import Decision.\nRequire Import Structures.\nRequire Import PseudoJoin.\n\nModule PJR.\n\n  (** * Syntax *)\n\n  Section SYNTAX.\n    Inductive term :=\n      | empty: term\n      | var: nat -> term\n      | combine: term -> term -> term.\n\n    (** Normalization *)\n\n    Fixpoint insert (i: nat) (t: term): term :=\n      match t with\n        | combine (var j) u =>\n          if decide (i <= j)%nat then\n            combine (var i) (combine (var j) u)\n          else\n            combine (var j) (insert i u)\n        | _ =>\n          combine (var i) t\n      end.\n\n    Fixpoint insert_term (t u: term): term :=\n      match t with\n        | empty => u\n        | var i => insert i u\n        | combine t1 t2 => insert_term t1 (insert_term t2 u)\n      end.\n\n    Definition sort (t: term) :=\n      insert_term t empty.\n  End SYNTAX.\n\n  (** * Semantics *)\n\n  Section SEMANTICS.\n    Context {E} `{Ee: Emptyset E} `{HE: PseudoJoin E ∅}.\n    Local Opaque equiv.\n\n    Fixpoint lookup (i: nat) (env: list E) :=\n      match i, env with\n        | O, x::xs => x\n        | S j, x::xs => lookup j xs\n        | _, _ => ∅\n      end.\n\n    Fixpoint eval (env: list E) (t: term): E :=\n      match t with\n        | empty => ∅\n        | var i => lookup i env\n        | combine t1 t2 => eval env t1 ⊕ eval env t2\n      end.\n\n    Lemma insert_sound env i t:\n      eval env (insert i t) ≡ eval env (combine (var i) t).\n    Proof.\n      simpl.\n      induction t; try reflexivity.\n      - simpl.\n        destruct t1 as [ | j | u1 u2]; simpl; try reflexivity.\n        destruct (decide _); simpl; try reflexivity.\n        rewrite IHt2.\n        rewrite <- !associativity.\n        rewrite (commutativity (lookup _ _)).\n        reflexivity.\n    Qed.\n\n    Lemma insert_term_sound env t u:\n      eval env (insert_term t u) ≡ eval env (combine t u).\n    Proof.\n      revert u.\n      induction t as [ | i | t1 IHt1 t2 IHt2 ]; intro u.\n      - simpl.\n        split.\n        + apply right_upper_bound.\n        + apply id_left.\n      - transitivity (eval env (insert i u)).\n        + reflexivity.\n        + apply insert_sound.\n      - simpl.\n        rewrite IHt1; simpl.\n        rewrite IHt2; simpl.\n        symmetry.\n        apply associativity.\n    Qed.\n\n    Lemma sort_sound env t:\n      eval env (sort t) ≡ eval env t.\n    Proof.\n      unfold sort.\n      transitivity (eval env (combine t empty)).\n      - apply insert_term_sound.\n      - simpl.\n        split.\n        + apply id_right.\n        + apply left_upper_bound.\n    Qed.\n  End SEMANTICS.\n\n  (** * Verification conditions *)\n\n  Section VERIF.\n    Context {E} `{Ee: Emptyset E} `{HE: PseudoJoin E ∅}.\n\n    (** Sufficient check for 〚t〛 ≤ 〚u〛. Works on terms n normalize\n      by [sort] above. *)\n    Fixpoint termcmp (t u: term): bool :=\n      match t, u with\n        | empty, _ =>\n          true\n        | combine (var i) t', combine (var j) u' =>\n          if decide (i = j) then\n            termcmp t' u'\n          else\n            termcmp t u'\n        | _, _ =>\n          false\n      end.\n\n    Lemma termcmp_sound env t u:\n      termcmp t u = true ->\n      eval env t ≤ eval env u.\n    Proof.\n      revert t.\n      induction u as [ | i | [ | i | u11 u12] IHu1 u2 IHu2];\n        intros t;\n        destruct t as [ | j | [ | j | t11 t12] t2];\n        inversion 1;\n        try apply lower_bound.\n      destruct (decide _); subst.\n      - simpl.\n        monotonicity.\n        + reflexivity.\n        + eauto.\n      - transitivity (eval env u2).\n        + eauto.\n        + simpl.\n          apply right_upper_bound.\n    Qed.\n\n    Lemma termcmp_sort_sound env t u:\n      termcmp (sort t) (sort u) = true ->\n      eval env t ≤ eval env u.\n    Proof.\n      intros H.\n      rewrite <- (sort_sound env t).\n      rewrite <- (sort_sound env u).\n      apply termcmp_sound.\n      assumption.\n    Qed.\n  End VERIF.\n\n  (** Lookup [x] in list [env]. If it's not in there, a corresponding\n    element is added at the end of the list. Then pass the potentially\n    extended environment and index to the continuation [cont]. *)\n  Ltac l env x cont :=\n    let rec iter i e :=\n      lazymatch e with\n        | x::?xs => cont env i\n        | _::?xs => iter (S i) xs\n        | _ =>\n          let newenv := eval cbv [app] in (env++(x::nil)) in\n          cont newenv i\n      end in\n    iter O env.\n\n  (** Quote the pseudo-join expression [x] with the starting\n    environment [env] for variables. The extended environment and\n    quoted term are then passed to the continuation [cont]. *)\n  Ltac q env x cont :=\n    lazymatch x with\n      | ∅ => cont env empty\n      | ?x1 ⊕ ?x2 =>\n        let cont1 env1 t1 :=\n          let cont2 env2 t2 :=\n            cont env2 (combine t1 t2) in\n          q env1 x2 cont2 in\n        q env x1 cont1\n      | _ =>\n        let lcont env i := cont env (var i) in\n        l env x lcont\n    end.\n\n  Ltac quoteineq :=\n    lazymatch goal with\n      | |- le (A := ?E) ?x ?y =>\n        let xcont xenv t :=\n          let ycont yenv u :=\n            (change (eval yenv t ≤ eval yenv u)) in\n          q xenv y ycont in\n        q (@nil E) x xcont\n    end.\nEnd PJR.\n\nLtac pjr :=\n  PJR.quoteineq;\n  eapply PJR.termcmp_sort_sound;\n  reflexivity.\n\nSection TEST.\n  Context {E} `{Ee: Emptyset E} `{HE: PseudoJoin E ∅}.\n  Context {a b c d e: E}.\n\n  Goal a ⊕ ∅ ⊕ d ≤ b ⊕ e ⊕ d ⊕ a ⊕ b.\n  Proof.\n    pjr.\n  Qed.\nEnd TEST.\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/CAL/liblayers/logic/PseudoJoinReflection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6545802174087504}}
{"text": "From mathcomp Require Import\n  ssreflect ssrfun ssrbool ssrnat eqtype seq choice fintype path\n  ssrint rat bigop.\n\nFrom extructures Require Import ord fset fmap ffun.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope fset_scope.\n\nDefinition int_ordMixin := CanOrdMixin natsum_of_intK.\nCanonical int_ordType := Eval hnf in OrdType int int_ordMixin.\n\nDefinition rat_ordMixin := [ordMixin of rat by <:].\nCanonical rat_ordType := Eval hnf in OrdType rat rat_ordMixin.\n\nSection Update.\n\nContext {T : ordType} {S : eqType} {def : T -> S}.\n\nDefinition updm (f : ffun def) (xs : {fmap T -> S}) : ffun def :=\n  mkffun (fun v => if xs v is Some x then x else f v)\n         (supp f :|: domm xs).\n\nLemma updmE f xs x :\n  updm f xs x = if xs x is Some y then y else f x.\nProof.\nrewrite /updm mkffunE in_fsetU orbC mem_domm.\ncase e: (xs x)=> [y|] //=.\nby case: ifPn=> // /suppPn ->.\nQed.\n\nEnd Update.\n\nArguments bigcupP {_ _ _ _ _ _}.\nArguments mkfmap {_ _}.\n", "meta": {"author": "arthuraa", "repo": "netter", "sha": "ea824a5f6207acb70b245a10d5a38db0551af4a8", "save_path": "github-repos/coq/arthuraa-netter", "path": "github-repos/coq/arthuraa-netter/netter-ea824a5f6207acb70b245a10d5a38db0551af4a8/coq/Extra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778823, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6545802054222338}}
{"text": "Definition N := 23.\n\nInductive tree : Type :=\n| Leaf : tree\n| Node : nat -> tree -> tree -> tree.\n\nFixpoint binary_tree c n :=\n  match n with\n  | 0 => Leaf\n  | S n =>\n    let t := binary_tree c n in\n    Node c t t\n  end.\n\nDefinition t0 := Eval vm_compute in binary_tree 0 N.\nDefinition t1 := Eval vm_compute in binary_tree 1 N.\n", "meta": {"author": "eponier", "repo": "compare-eq", "sha": "cc2da184e747d0ad6ada8597e1ebf03377e413e2", "save_path": "github-repos/coq/eponier-compare-eq", "path": "github-repos/coq/eponier-compare-eq/compare-eq-cc2da184e747d0ad6ada8597e1ebf03377e413e2/equality_test/23/type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970748488296, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.654580203096822}}
{"text": "(* Implementation of the compiler (both tree-based and graph-based\nvariant) and proof of Lemma 1 from the paper (compT e = unravel (compG\ne).  *)\n\n\nRequire Import Graph.\nRequire Import Tree.\nRequire Import GraphUnravel.\nRequire Import Coq.Program.Basics.\nRequire Import CalculationTactics.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(* Source language. *)\n\nInductive Expr : Set :=\n  | Val : nat -> Expr\n  | Add : Expr -> Expr -> Expr\n  | Throw  : Expr\n  | Catch : Expr -> Expr -> Expr.\n\n(* For the definition of the source language we have to use containers\nin order to instantiate the definition of trees and graphs (which use\ncontainers to represent strictly positive functors). *)\n\n(* The shape type. *)\n\nInductive CodeSh : Set := \n| PUSH : nat -> CodeSh\n| ADD : CodeSh\n| THROW : CodeSh\n| MARK : CodeSh\n| UNMARK : CodeSh\n| HALT : CodeSh.\n\n(* Definition of the container to represent the functor [Code] from\nthe paper. *)\n\nDefinition Code : Cont := \n  {| shapes := CodeSh;\n    pos := fun s => match s with\n                      | PUSH _ => unit\n                      | ADD => unit\n                      | THROW => Zero\n                      | MARK => sum unit unit\n                      | UNMARK => unit\n                      | HALT => Zero\n                    end\n   |}.\n\n(* Functions to define unary and binary constructors (of the functor). *)\nDefinition one {A} (a : A) (x : unit) : A := a.\nDefinition two {A} (a b : A) (x : sum unit unit) : A := \n  match x with\n            | inl _  => a\n            | inr _ => b\n  end.\n\n\n(* Definition of the constructors for the [Code] functor. *)\nDefinition mkPUSH {A} i (c : A) : Ext Code A := (ext Code (PUSH i) (one c)).\nDefinition mkADD {A} (c : A) : Ext Code A := (ext Code ADD (one c)).\nDefinition mkTHROW {A} : Ext Code A := (ext Code THROW (zero _)).\nDefinition mkMARK {A} (c c' : A) : Ext Code A := (ext Code MARK (two c c')).\nDefinition mkUNMARK {A} (c : A) : Ext Code A := (ext Code UNMARK (one c)).\nDefinition mkHALT {A}  : Ext Code A := (ext Code HALT (zero _)).\n\n(* Graph variants of the constructors. *)\nImport Graph.\nDefinition gPUSH {A} i c : GraphM Code A := In (mkPUSH i c).\nDefinition gADD {A} c : GraphM Code A := In (mkADD c).\nDefinition gTHROW {A} : GraphM Code A := In mkTHROW.\nDefinition gMARK {A} c c' : GraphM Code A := In (mkMARK c c').\nDefinition gUNMARK {A} c : GraphM Code A := In (mkUNMARK c).\nDefinition gHALT {A} : GraphM Code A := In mkHALT.\n\n(* Tree variants of the constructors. *)\nImport Tree.\nDefinition tPUSH i c : Tree Code := In (mkPUSH i c).\nDefinition tADD c : Tree Code := In (mkADD c).\nDefinition tTHROW : Tree Code := In mkTHROW.\nDefinition tMARK c c' : Tree Code := In (mkMARK c c').\nDefinition tUNMARK c : Tree Code := In (mkUNMARK c).\nDefinition tHALT : Tree Code := In mkHALT.\n\n\nInfix \"|>\" := (apply) (at level 60, right associativity).\n\n(* Definition of the graph-based compiler. *)\nFixpoint compG' {A} (e : Expr) (c : GraphM Code A) : GraphM Code A :=\n  match e with\n      | Val n =>  gPUSH n |> c\n      | Add x y =>  compG' x |> compG' y |> gADD |> c\n      | Throw =>  gTHROW\n      | Catch x h => letx c (fun _ c' =>\n                               gMARK (compG' h |> var c') (compG' x |> gUNMARK |> var c'))\n  end.\n\nDefinition compG (e : Expr) : Graph Code := compG' e |> gHALT.\n\n(* Definition of the tree-based compiler. *)\nFixpoint compT' (e : Expr) (c : Tree Code) : Tree Code :=\n  match e with\n      | Val n =>  tPUSH n |> c\n      | Add x y =>  compT' x |> compT' y |> tADD |> c\n      | Throw =>  tTHROW\n      | Catch x h => tMARK (compT' h |> c) (compT' x |> tUNMARK |> c)\n  end.\n\nDefinition compT (e : Expr) : Tree Code := compT' e |> tHALT.\n\n(* Convenience lemmas that state how unravelling works on the\nconstructors. *)\n\nLemma unravelM_mark {A env} {c1 c2 : GraphM Code A} : \n  unravelM env (gMARK c1 c2) = tMARK (unravelM env c1) (unravelM env c2).\nProof.\n  unfold unravelM, ufoldM, tMARK, gMARK, mkMARK. simpl. unfold cmap, two. simpl. repeat f_equal.\n  apply functional_extensionality. intros. destruct x; reflexivity. \nQed.\n\nLemma unravelM_throw {A} {env : Env _ A} :  unravelM env gTHROW = tTHROW.\nProof. \n  unfold gTHROW, tTHROW, mkTHROW, unravelM, ufoldM.  simpl. unfold cmap. simpl. repeat f_equal.\n  apply zero_unique.\nQed.\n\nLemma unravelM_halt {A} {env : Env _ A} :  unravelM env gHALT = tHALT.\nProof. \n  unfold gHALT, tHALT, mkHALT, unravelM, ufoldM.  simpl. unfold cmap. simpl. repeat f_equal.\n  apply zero_unique.\nQed.\n\n(* Proof of Lemma 1 from the paper. The following is the main lemma\nfor the proof, which corresponds to the induction proof from the\npaper. *)\n\nLemma comp_unravelM {A} {e : Expr} {env} {c : GraphM Code A} : compT' e (unravelM env c)\n                                                              = unravelM env (compG' e c).\nProof.   Begin.\n  unfold compT, unravel, compG, apply. \n\n  generalize dependent A.  induction e; intros; simpl; unfold apply. \n\n  reflexivity. \n\n  rewrite <- IHe1.  rewrite <- IHe2. reflexivity.\n\n  rewrite unravelM_throw. reflexivity.\n\n\n  RHS\n  = { rewrite unravelM_letx }\n  (unravelM (Extend (unravelM env c) env)\n            (gMARK (compG' e2 (var tt)) (compG' e1 (gUNMARK (var tt))))).\n  = { rewrite unravelM_mark }\n  (tMARK ( unravelM (Extend (unravelM env c) env) (compG' e2 (var tt)))\n         ( unravelM (Extend (unravelM env c) env) (compG' e1 (gUNMARK (var tt))))).\n  = { rewrite IHe1 }\n      (tMARK ( unravelM (Extend (unravelM env c) env) (compG' e2 (var tt)))\n             ( compT' e1 (unravelM (Extend (unravelM env c) env) (gUNMARK (var tt))))).\n  = { rewrite IHe2 }\n      (tMARK ( compT' e2 (unravelM (Extend (unravelM env c) env)(var tt)))\n             ( compT' e1 (unravelM (Extend (unravelM env c) env) (gUNMARK (var tt))))).\n  = { reflexivity }\n      (tMARK ( compT' e2 (unravelM env c))\n             ( compT' e1 (tUNMARK (unravelM env c)))).\n  [].\nQed.\n\n(* From the above lemma we can then derive Lemma 1. *)\n\nLemma comp_unravel {e : Expr} : compT e = unravel (compG e).\nProof.\n  unfold compT, compG, apply, unravel. erewrite <- unravelM_halt. eapply comp_unravelM.\nQed.\n  \n\n  ", "meta": {"author": "pa-ba", "repo": "graph-comp", "sha": "7d9a35c2731672914c60a3eb5642c8c8146fa1a9", "save_path": "github-repos/coq/pa-ba-graph-comp", "path": "github-repos/coq/pa-ba-graph-comp/graph-comp-7d9a35c2731672914c60a3eb5642c8c8146fa1a9/Compiler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6545382991930379}}
{"text": "(******************************************************************************)\n(* Chapter 1.5: Isomorphisms                                                  *)\n(******************************************************************************)\n\n(*\n(0)\n同じディレクトリにある Categories.v と Functor.v を使う。\n\n(1) ベースライン\nhttp://www.megacz.com/berkeley/coq-categories/\nこれをもとに改変。Instance ... Proper を使うようにした。\n *)\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import Morphisms.                   (* coq standard libs. *)\nRequire Import Notations.                   (* same dir. *)\nRequire Import Categories.                  (* same dir. *)\nRequire Import Functors.                    (* same dir. *)\n\n(* 圏Cにおいて、同型射 f : a ~> b が存在するとき、a と b は同型である。 *)\n(* 同型射とは、g \\\\o f === id かつ f \\\\o g === id なる f *)\nClass Isomorphism `{C : Category} {a b : C} (f : a ~> b) (g : b ~> a) : Prop :=\n  {\n    iso_cmp1  : g \\\\o f === id;             (* id a *)\n    iso_cmp2  : f \\\\o g === id              (* id b *)\n  }.\n(* TO DO: show isos are unique when they exist *)\n\n(* f と g をメンバで定義した版 *)\nClass Isomorphic `{C : Category} (a b : C) :=\n  {\n    iso_forward  :  a ~> b;\n    iso_backward :  b ~> a;\n    iso_comp1    :  iso_backward \\\\o iso_forward === id; (* id a *)\n    iso_comp2    :  iso_forward \\\\o iso_backward === id  (* id b *)\n(* TO DO: merge this with Isomorphism *)\n}.\n(* 同型射 f は、ひとつの同型(な関係にあるaとb)を与えないと決まらない。\n   Isomorphic a b をexplicitに与えるようにする。 *)\nCheck @iso_forward : ∀Obj Hom C a b _, a ~> b.\nCheck iso_forward : _ ~> _.\nArguments iso_forward  {Obj Hom C a b} i : rename.\nArguments iso_backward {Obj Hom C a b} i : rename.\nArguments iso_comp1    {Obj Hom C a b} i : rename.\nArguments iso_comp2    {Obj Hom C a b} i : rename.\nCheck iso_forward _ : _ ~> _.                 (* 最初の _ は、Isomorphic a b *)\nCheck iso_forward : Isomorphic _ _ -> _ ~> _. (* _ は、圏Cの対象 a b *)\n\nNotation \"a ≅ b\" := (Isomorphic a b) : isomorphism_scope.\n(* the sharp symbol \"casts\" an isomorphism to the morphism in the forward direction *)\nNotation \"# f\" := (iso_forward f) : isomorphism_scope.\nOpen Scope isomorphism_scope.\n\n\n(* 同型a,bに対して、同型b,aを求めることができる。 *)\n(* aに対してbが同型なら、bに対してaも同型である。 *)\n(* the inverse of an isomorphism is an isomorphism *)\nDefinition iso_inv `{C : Category} (a b : C) (iso : Isomorphic a b) : Isomorphic b a.\nProof.\n  Check iso_backward.\n  Check @Build_Isomorphic _ _ _ _ _ (iso_backward iso) (iso_forward iso).\n  apply (@Build_Isomorphic _ _ _ _ _ (iso_backward iso) (iso_forward iso)).\n  - by apply iso_comp2.\n  - by apply iso_comp1.\nDefined.\nCheck @iso_inv : ∀Obj Hom C a b _, b ≅ a.\nArguments iso_inv {Obj Hom C a b} f : rename.\nCheck iso_inv _ : _ ≅ _.                    (* 最初の _ は a ≅ b *)\nCheck iso_inv : _ ≅ _ -> _ ≅ _.             (* _ は、圏Cの対象 a b *)\nNotation \"f '⁻¹'\" := (iso_inv f) : isomorphism_scope.\n\n(* 同型a,a *)\n(* aとaは同型である。 *)\n(* identity maps are isomorphisms *)\nDefinition iso_id `{C : Category} (a : C) : Isomorphic a a.\nProof.\n  Check @Build_Isomorphic _ _ C a a id id.\n  apply (@Build_Isomorphic _ _ C a a id id).\n  now rewrite left_identity.\n  now rewrite left_identity.\nDefined.\nCheck @iso_id.\nArguments iso_id {Obj Hom C a} : rename.\nCheck iso_id : _ ≅ _.                       (* _ は、圏Cの対象a *)\n\n(* 同型a,b と 同型b,c なら、同型a,c *)\n(* the composition of two isomorphisms is an isomorphism *)\nDefinition iso_comp `{C : Category} {a b c : C}\n           (i1 : Isomorphic a b) (i2 : Isomorphic b c) : Isomorphic a c.\nProof.\n  Check #i1 : a ~> b.                       (* iso_forward i1 *)\n  Check #i2 : b ~> c.                       (* iso_forward i2 *)\n  Check #i2 \\\\o #i1 : a ~> c.\n  Check #i1⁻¹ : b ~> a.                     (* iso_inv (iso_forward i1) *)\n  Check #i2⁻¹ : c ~> b.                     (* iso_inv (iso_forward i2) *)\n  Check iso_comp1 i1 : iso_backward i1 \\\\o #i1 === id.\n  Check iso_comp2 i1 : #i1 \\\\o iso_backward i1 === id.\n  Check iso_comp1 i2 : iso_backward i2 \\\\o #i2 === id.\n  Check iso_comp2 i2 : #i2 \\\\o iso_backward i2 === id.\n\n  Check (@Build_Isomorphic _ _ C a c (#i2 \\\\o #i1) (#i1⁻¹ \\\\o #i2⁻¹)).\n  apply (@Build_Isomorphic _ _ C a c (#i2 \\\\o #i1) (#i1⁻¹ \\\\o #i2⁻¹)).\n  - rewrite juggle3 (iso_comp1 i2).\n    rewrite associativity left_identity (iso_comp1 i1).\n    reflexivity.\n  - rewrite juggle3 (iso_comp2 i1).\n    rewrite associativity left_identity (iso_comp2 i2).\n    reflexivity.\nDefined.\nCheck @iso_comp : ∀Obj Hom C a b c _ _, a ≅ c.\nCheck iso_comp _ _ : _ ≅ _.\nArguments iso_comp {Obj Hom C} a b c i1 i2 : rename.\nCheck iso_comp : ∀a b c _ _, a ≅ c.\nNotation \"a >>≅>> b\" := (iso_comp a b).\n\n(* 関手は同型を保存する。 *)\nDefinition functors_preserve_isos `{C1 : Category} `{C2 : Category} {Fo : C1 -> C2}\n           (F : Functor Fo) {a b : C1} (i : Isomorphic a b) : Isomorphic (F a) (F b).\nProof.\n  (* 圏C1を関手で写した先の圏C2、C2の同型を作る。 *)\n  Check F \\ (iso_forward i) : F a ~> F b.\n  Check F \\ #i : F a ~> F b.\n  Check F \\ (iso_backward i) : F b ~> F a.\n  Check {| iso_forward  := F \\ (iso_forward  i);\n           iso_backward := F \\ (iso_backward i)\n        |}.\n  Check (@Build_Isomorphic).\n  Check (@Build_Isomorphic Obj0 Hom0 C2 (F a) (F b)\n                           (F \\ (# i))\n                           (F \\ (iso_backward i))).\n  Check (@Build_Isomorphic _ _ _ (F a) (F b)\n                           (F \\ (# i))\n                           (F \\ (iso_backward i))).\n  (* Standard Coq の refine は、SSReflect の apply: である。 *)\n  refine {| iso_forward  := F \\ (iso_forward  i);\n            iso_backward := F \\ (iso_backward i)\n         |}.\n  Undo 1.\n  apply: {| iso_forward  := F \\ (iso_forward  i);\n            iso_backward := F \\ (iso_backward i)\n         |}.\n  Undo 1.\n  apply (@Build_Isomorphic _ _ _ _ _\n                           (F \\ (# i))\n                           (F \\ (iso_backward i))).\n  (* F \\ iso_backward i \\\\o F \\ #i === id *)\n  - rewrite fmor_preserves_comp.\n    rewrite iso_comp1.\n    apply fmor_preserves_id.\n  (* F \\ #i \\\\o F \\ iso_backward i === id *)\n  - rewrite fmor_preserves_comp.\n    rewrite iso_comp2.\n    apply fmor_preserves_id.\nDefined.\n\n(* 圏Cの対象b,aが同型である（同型射 b ~> c がある）とき、\n   圏Cの射f : b ~> c と、射g : a ~> c の関係を示す。\n *)\nLemma iso_shift_right `{C : Category} {a b c : C}\n      (f : b ~> c) (g : a ~> c) (i : Isomorphic b a) :\n  f \\\\o #i⁻¹ === g -> f === g \\\\o #i.\nProof.\n  move=> H.\n  rewrite -H associativity iso_comp1 right_identity.\n  reflexivity.\nQed.  \n\nLemma iso_shift_right' `{C : Category} {a b c : C}\n      (f : b ~> c) (g : a ~> c) (i : Isomorphic a b) :\n  f \\\\o #i === g -> f === g \\\\o #i⁻¹.\nProof.\n  move=> H.\n  rewrite -H.\n  rewrite associativity.                    (* assoc の定義がオリジナルと異なる。 *)\n  rewrite iso_comp2 right_identity.         (* あとは、少し証明が変わる。 *)\n  reflexivity.\nQed.  \n\nLemma iso_shift_left `{C : Category} {a b c : C}\n      (f : a ~> b) (g : a ~> c) (i : Isomorphic c b) :\n  #i⁻¹ \\\\o f === g -> f === #i \\\\o g.\nProof.\n  move=> H.\n  rewrite -H -associativity iso_comp2 left_identity.\n  reflexivity.\nQed.\n\nLemma iso_shift_left' `{C : Category} {a b c : C}\n      (f : a ~> b) (g : a ~> c) (i : Isomorphic b c) :\n  #i \\\\o f === g -> f === #i⁻¹ \\\\o g.\nProof.\n  move=> H.\n  rewrite -H -associativity iso_comp1 left_identity.\n  reflexivity.\nQed.  \n\n(* 圏Cの対象aとbに対して、a,bの同型（同型射 a ~> b）が同じなら、\nb,aの同型（同型射 b ~> a）も同じである。 *)\nLemma isos_forward_equal_then_backward_equal `{C : Category} {a b : C}\n      (i1 i2 : Isomorphic a b)  :  #i1 === #i2 ->  #i1⁻¹ === #i2⁻¹.\nProof.\n  move=> H.\n  rewrite -[#i1 ⁻¹]left_identity.\n  rewrite -(iso_comp1 i2).\n  rewrite associativity.\n  rewrite -H.\n  rewrite (iso_comp2 i1).\n  rewrite right_identity.\n  rewrite /=.\n  reflexivity.\nQed.\n\n(* 圏Cの対象aとbに対して、a,bの同型（同型射 a ~> b）の逆の逆は同じ *)\nLemma iso_inv_inv `{C : Category} {a b : C} (i : Isomorphic a b) :\n  #(i⁻¹)⁻¹ === #i.\nProof.\n  rewrite /iso_inv /=.\n  reflexivity.\nQed.\n\n(* the next four lemmas are handy for setoid_rewrite; they let you\navoid having to get the associativities right *)\n\nLemma iso_comp2_right  `{C : Category} {a b c : C} (i : Isomorphic a b)  (g : b ~> c) :\n  g \\\\o iso_forward i \\\\o iso_backward i === g.\nProof.\n  rewrite associativity.\n  rewrite iso_comp2.\n  rewrite right_identity.\n  reflexivity.\nQed.\n\nLemma iso_comp2_left `{C : Category} {a b c : C} (i : Isomorphic a b)  (g : c ~> b) :\n  iso_forward i \\\\o (iso_backward i \\\\o g)  === g.\nProof.\n  rewrite -associativity.\n  rewrite iso_comp2.\n  rewrite left_identity.\n  reflexivity.\nQed.\n\nLemma iso_comp1_right `{C : Category} {a b c : C} (i : Isomorphic a b)  (g : a ~> c) :\n  g \\\\o iso_backward i \\\\o iso_forward i === g.\nProof.\n  rewrite associativity.\n  rewrite iso_comp1.\n  rewrite right_identity.\n  reflexivity.\nQed.\n\nLemma iso_comp1_left `{C : Category} {a b c : C} (i : Isomorphic a b)  (g : c ~> a) :\n  iso_backward i \\\\o (iso_forward i \\\\o g)  === g.\nProof.\n  rewrite -associativity.\n  rewrite iso_comp1.\n  rewrite left_identity.\n  reflexivity.\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/monad/Isomorphisms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6545382970059246}}
{"text": "Set Implicit Arguments. \nRequire Import FinFun.\nFrom Undecidability.HOU Require Import std.decidable.\n  \nInductive diag: nat -> nat -> Type :=\n  | diagB: diag 0 0\n  | diagC: forall m, diag 0 m -> diag (S m) 0\n  | diagS: forall n m, diag (S n) m -> diag n (S m).\n\n\nFixpoint diagStepR m n (d: diag m n) : diag m (S n) :=\n  match d with\n  | diagB => diagS (diagC diagB)\n  | diagC H => diagS (diagC (diagStepR H))\n  | diagS H => diagS (diagStepR H)\n  end.\n\nFixpoint diagStepL m n (d: diag m n) : diag (S m) n :=\n  match d with\n  | diagB => diagC diagB\n  | diagC H => diagC (diagS (diagStepL H))\n  | diagS H => diagS (diagStepL H)\n  end.\n\nFixpoint diagZero (a: nat) : diag 0 a :=\n  match a with\n  | 0 => diagB\n  | S a => diagStepR (diagZero a)\n  end.\n\nFixpoint diagId m n: diag m n :=\n  match m with\n  | O => diagZero n\n  | S m => diagStepL (diagId m n)\n  end.\n\nDefinition I__P (p: nat * nat) :=\n  let (m, n) := p in\n  diag_rect (fun _ _ _ => nat) 0 (fun _ _ => S)  (fun _ _ _ => S) (diagId m n): nat.\n\nFixpoint R__P (n: nat) : nat * nat  :=\n  match n with \n    | 0 =>  (0,0) \n    | S n => match R__P n with \n            | (0, b)  => (S b, 0)\n            | (S a, b) => (a, S b)\n      end\n   end.\n\nLemma R__P_I__P p: R__P (I__P p) = p.\nProof.\n  unfold I__P; destruct p as [m n]; induction (diagId m n); cbn.\n  - reflexivity.\n  - now rewrite IHd.\n  - now rewrite IHd.\nQed.\n\nLemma R__P_injective n m: R__P n = R__P m -> n = m.\nProof.\n  induction n in m |-*; destruct m; cbn; eauto.\n  1: destruct (R__P m) as [[] b]; discriminate.\n  1: destruct (R__P n) as [[] b]; discriminate.\n  destruct (R__P n) as [[|k] p] eqn: H1, (R__P m) as [[|k'] p'] eqn: H2.\n  all: injection 1; intros; subst.\n  all: erewrite IHn; eauto.\n  all: discriminate.\nQed.\n\nLemma I__P_R__P n: I__P (R__P n) = n.\nProof.\n  eapply R__P_injective; now rewrite R__P_I__P.\nQed.\n\n\nRequire Import Arith Lia Nat Arith.Div2.\n\nDefinition I__S (s: nat + nat) :=\n  match s with\n  | inl n => double n\n  | inr n => S (double n)\n  end.\n\n\nDefinition R__S (n: nat) :=\n  if even n then inl (div2 n) else inr (div2 n).\n\nLemma I__S_R__S n: I__S (R__S n) = n.\nProof.\n  unfold I__S, R__S.\n  destruct Nat.even eqn: H1.\n  - symmetry. eapply even_double.  \n    now eapply Even.even_equiv, Nat.even_spec.\n  - symmetry. eapply odd_double; eauto.\n    eapply Even.odd_equiv, Nat.odd_spec.\n    unfold odd; rewrite H1; eauto.\nQed.\n\nLemma R__S_I__S s: (R__S (I__S s)) = s.\nProof.\n  unfold I__S, R__S.\n  destruct s.\n  - specialize (Nat.even_spec (Nat.double n)) as [_ H].\n    rewrite H, Nat.double_twice, Nat.div2_double; eauto.\n    eapply Nat.even_spec. \n    unfold Nat.double.\n    rewrite Nat.even_add.\n    destruct (Nat.even n); reflexivity.\n  - specialize (Nat.even_spec (Nat.double n)) as [_ H].\n    rewrite Nat.even_succ, <-Nat.negb_even.\n    rewrite H; cbn [negb].\n    rewrite Nat.double_twice, Nat.div2_succ_double; eauto.\n    eapply Nat.even_spec; unfold Nat.double;\n      rewrite ?Nat.even_add; destruct (Nat.even n); reflexivity.\nQed.\n\n\nLemma injective_I__S : Injective I__S.\nProof.\n  intros s s' H % (f_equal R__S). now rewrite !R__S_I__S in H.\nQed.\n\nLemma injective_I__P : Injective I__P.\nProof.\n  intros s s' H % (f_equal R__P). now rewrite !R__P_I__P in H.\nQed.\n\nArguments I__P p : simpl never.\nArguments R__P n : simpl never.\nArguments I__S s : simpl never.\nArguments R__S n : simpl never.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/HOU/std/countability.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6545382940056346}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\n\nRequire Import Setoid.\nFrom Coq Require Import Ensembles.\nFrom Coq.Logic Require Import FunctionalExtensionality.\nFrom Coq.Logic Require Import PropExtensionality ClassicalFacts.\n\nFrom stdpp Require Import base list sets propset.\n\nFrom MatchingLogic Require Import\n  Syntax\n  Semantics\n  DerivedOperators_Syntax\n  DerivedOperators_Semantics\n  monotonic\n  Utils.Lattice\n  Utils.stdpp_ext\n  IndexManipulation\n.\n\nImport MatchingLogic.Syntax.Notations.\nImport MatchingLogic.Substitution.Notations.\nImport MatchingLogic.DerivedOperators_Syntax.Notations.\n\n\nSection with_signature.\n  Context {Σ : Signature}.\n  Open Scope ml_scope.\n\n  Lemma eval_mu_lfp_fixpoint M ρ ϕ :\n    well_formed_positive (patt_mu ϕ) ->\n    let X := fresh_svar ϕ in\n    let F := Fassoc ρ (ϕ^{svar: 0 ↦ X}) X in\n    let Sfix := @eval Σ M ρ (patt_mu ϕ) in\n    F Sfix = Sfix.\n  Proof.\n    simpl.\n    remember (fresh_svar ϕ) as X.\n    remember (Fassoc ρ (ϕ^{svar: 0 ↦ X}) X) as F.\n    remember (@eval _ M ρ (patt_mu ϕ)) as Sfix.\n    pose (OS := PropsetOrderedSet (Domain M)).\n    pose (L := PowersetLattice (Domain M)).\n    intros Hwfp.\n\n    assert (HFmono: MonotonicFunction F).\n    { rewrite HeqF. rewrite /Fassoc. apply is_monotonic. apply Hwfp.\n      rewrite HeqX. apply set_svar_fresh_is_fresh.\n    }\n\n    assert (Ffix : Lattice.isFixpoint F (Lattice.LeastFixpointOf F)).\n    { apply Lattice.LeastFixpoint_fixpoint. apply HFmono.\n    }\n\n    unfold isFixpoint in Ffix.\n    rewrite eval_mu_simpl in HeqSfix.\n    simpl in HeqSfix.\n    unfold Fassoc in HeqF.\n    rewrite HeqX in HeqF.\n    rewrite -HeqF in HeqSfix.\n    rewrite -HeqSfix in Ffix.\n    apply Ffix.\n  Qed.\n\n\n  Lemma eval_mu_lfp_least M ρ ϕ S:\n    well_formed_positive (patt_mu ϕ) ->\n    let X := fresh_svar ϕ in\n    let F := Fassoc ρ (ϕ^{svar: 0 ↦ X}) X in\n    let Sfix := @eval Σ M ρ (patt_mu ϕ) in\n    (F S) ⊆ S ->\n    Sfix ⊆ S.\n  Proof.\n    simpl.\n    remember (fresh_svar ϕ) as X.\n    remember (Fassoc ρ (ϕ^{svar: 0 ↦ X}) X) as F.\n    remember (@eval _ M ρ (patt_mu ϕ)) as Sfix.\n    pose (OS := PropsetOrderedSet (Domain M)).\n    pose (L := PowersetLattice (Domain M)).\n    intros Hwfp.\n\n    assert (HFmono: MonotonicFunction F).\n    { rewrite HeqF. rewrite /Fassoc. apply is_monotonic. apply Hwfp.\n      rewrite HeqX. apply set_svar_fresh_is_fresh.\n    }\n\n    assert (Hlfp: LeastFixpointOf F = Sfix).\n    { subst. rewrite eval_mu_simpl. simpl. unfold Fassoc. reflexivity. }\n\n    intros Hincl.\n\n    pose proof (Hleast := LeastFixpoint_LesserThanPrefixpoint _ _ _ F S).\n    simpl in Hleast. specialize (Hleast Hincl).\n    rewrite Hlfp in Hleast. apply Hleast.\n  Qed.\n\n  Lemma eval_mu_if_lfp M ρ ϕ Sfix :\n    well_formed_positive (patt_mu ϕ) ->\n    let X := fresh_svar ϕ in\n    let F := Fassoc ρ (ϕ^{svar: 0 ↦ X}) X in\n    (F Sfix) ⊆ Sfix ->\n    (∀ S, (F S) ⊆ S -> Sfix ⊆ S) ->\n    Sfix = @eval Σ M ρ (patt_mu ϕ).\n  Proof.\n    intros Hwfp. simpl.\n    remember (fresh_svar ϕ) as X.\n    remember (Fassoc ρ (ϕ^{svar: 0 ↦ X}) X) as F.\n    intros Hprefix Hleast.\n    rewrite eval_mu_simpl. simpl.\n    unfold Fassoc in HeqF. rewrite HeqX in HeqF. rewrite -HeqF.\n    apply LeastFixpoint_unique. { apply Hprefix. } apply Hleast.\n  Qed.\n\n  Lemma eval_mu_lfp_iff M ρ ϕ Sfix :\n    well_formed_positive (patt_mu ϕ) ->\n    let X := fresh_svar ϕ in\n    let F := Fassoc ρ (ϕ^{svar: 0 ↦ X}) X in\n    (\n    (F Sfix) ⊆ Sfix /\\\n    (∀ S, (F S) ⊆ S -> Sfix ⊆ S)\n    ) <-> Sfix = @eval Σ M ρ (patt_mu ϕ).\n  Proof.\n    intros Hwfp. simpl.\n    remember (fresh_svar ϕ) as X.\n    remember (Fassoc ρ (ϕ^{svar: 0 ↦ X}) X) as F.\n    remember (@eval Σ M ρ (patt_mu ϕ)) as Sfix'.\n    split.\n    - intros [H1 H2]. subst.\n      auto using eval_mu_if_lfp.\n    - intros H. split.\n      + subst.\n        match goal with\n        | |- ?L ⊆ ?R => assert (H: L = R)\n        end.\n        apply eval_mu_lfp_fixpoint. apply Hwfp.\n        rewrite H. apply reflexivity.\n      + intros S. subst. apply eval_mu_lfp_least. apply Hwfp.\n  Qed.\n\n  (* mu X. base \\/ step X *)\n  (* [Nats] = mu X. 0 \\/ succ X *)\n  (* [Nats] = \\{ x | \\ex x0,x1,..x_n . x0 \\in 0 /\\ x(i+1) \\in succ xi }*)\n  (*  0, 1, 2,... x*)\n  Section inductive_generation.\n    Context (base step : Pattern).\n\n    Let patt_ind_gen_body := (patt_or (nest_mu base) (patt_app (nest_mu step) (patt_bound_svar 0))).\n    Let patt_ind_gen_simple_body := (patt_or base (patt_app step (patt_free_svar (fresh_svar patt_ind_gen_body)))).\n\n    Definition patt_ind_gen := patt_mu patt_ind_gen_body.\n\n    Hypothesis (Hwfpbase : well_formed_positive base).\n    Hypothesis (Hwfpstep : well_formed_positive step).\n\n    Lemma patt_ind_gen_wfp:\n      well_formed_positive patt_ind_gen.\n    Proof.\n      unfold patt_ind_gen. simpl.\n      rewrite !andb_true_r.\n      rewrite !well_formed_positive_nest_mu_aux.\n      rewrite Hwfpbase.\n      rewrite Hwfpstep.\n      rewrite !andb_true_r.\n\n      cbn. fold no_negative_occurrence_db_b.\n\n      rewrite !no_negative_occurrence_db_nest_mu_aux. simpl.\n      auto.\n    Qed.\n\n    Lemma svar_open_patt_ind_gen_body_simpl M ρ X:\n      svar_is_fresh_in X patt_ind_gen_body ->\n      @eval Σ M ρ (patt_ind_gen_body^{svar: 0 ↦ X})\n      = @eval Σ M ρ (patt_or base (patt_app step (patt_free_svar X))).\n    Proof.\n      intros Hfr.\n      unfold svar_is_fresh_in in Hfr. simpl in Hfr.\n      rewrite !simpl_free_svars in Hfr.\n      apply sets.not_elem_of_union in Hfr.\n      destruct Hfr as [Hfr1 Hfr2].\n\n      rewrite /patt_ind_gen_body.\n      unfold svar_open.\n      mlSimpl. simpl.\n      rewrite 2!eval_or_simpl.\n      unfold nest_mu. rewrite 2!nest_mu_same.\n      reflexivity.\n    Qed.\n    \n    \n    Section with_eval.\n      Context (M : @Model Σ).\n      Context (ρ : @Valuation Σ M).\n\n\n      Let F := let X := fresh_svar patt_ind_gen_body in\n               @Fassoc Σ M ρ (patt_ind_gen_body^{svar: 0 ↦ X}) X.\n      (*\n      Lemma svar_open_patt_ind_gen_body_assoc S:\n        let X := fresh_svar patt_ind_gen_body in\n        eval ρₑ (update_svar_val X S ρₛ) (svar_open 0 X patt_ind_gen_body)\n        = F S.\n      Proof. reflexivity.\n             (*\n        cbv zeta.\n        rewrite svar_open_patt_ind_gen_body_simpl.\n        { apply set_svar_fresh_is_fresh. }\n        subst F. unfold Fassoc.\n        rewrite svar_open_patt_ind_gen_body_simpl.\n        { apply set_svar_fresh_is_fresh.  }\n        reflexivity.*)\n      Qed.\n       *)\n\n      (* I can imagine this lemma to be proven automatically. *)\n      Lemma F_interp: F = λ A, (eval ρ base)\n                                 ∪ (app_ext (eval ρ step) A).\n      Proof.\n        unfold F. unfold Fassoc. apply functional_extensionality.\n        intros A. rewrite svar_open_patt_ind_gen_body_simpl.\n        { apply set_svar_fresh_is_fresh. }\n\n        rewrite eval_or_simpl.\n        rewrite eval_app_simpl.\n        rewrite eval_free_svar_simpl.\n        rewrite update_svar_val_same.\n        rewrite eval_free_svar_independent.\n        {\n          eapply svar_is_fresh_in_richer.\n          2: { apply set_svar_fresh_is_fresh. }\n          solve_free_svars_inclusion 5.\n        }\n        rewrite eval_free_svar_independent.\n        {\n          eapply svar_is_fresh_in_richer.\n          2: { apply set_svar_fresh_is_fresh. }\n          solve_free_svars_inclusion 5.\n        }\n        reflexivity.\n      Qed.\n\n      Definition is_witnessing_sequence_old (m : Domain M) (l : list (Domain M)) :=\n        (last l = Some m) /\\\n        (match l with\n         | [] => False\n         | m₀::ms => (m₀ ∈ @eval Σ M ρ base)\n                     /\\  (@Forall _\n                                  (λ (x : (Domain M) * (Domain M)),\n                                   let (old, new) := x in\n                                   new ∈ \n                                  app_ext\n                                    (@eval Σ M ρ step)\n                                    {[ old ]}\n                                 )\n                                 (zip (m₀::ms) ms)\n                         )\n\n         end).\n\n      Definition is_witnessing_sequence (m : Domain M) (l : list (Domain M)) :=\n        (∃ lst, last l = Some lst /\\ lst ∈ @eval Σ M ρ base)\n          /\\\n          hd_error l = Some m\n          /\\\n          ((@Forall _ (uncurry (λ new old,\n                              new ∈\n                     app_ext\n                       (@eval Σ M ρ step)\n                       {[old]}\n                    ))\n                    (zip l (tail l))\n          )).\n\n      (* If we have a witnessing sequence x₁ x₂ ... xₙ xₙ₊₁ ... xlast\n         and xₙ matches `base`, then xₙ xₙ₊₁ is a witnessing sequence, too.\n       *)\n      Lemma witnessing_sequence_middle (m : Domain M) (l : list (Domain M)) (n : nat) (m' : Domain M) :\n        is_witnessing_sequence m l ->\n        l !! n = Some m' ->\n        m' ∈ @eval Σ M ρ base ->\n        is_witnessing_sequence m' (drop n l).\n      Proof.\n        intros [[lst [Hlst Hbase] ] [Hhd Hfa] ] Hm' Hbase'.\n        split.\n        { exists lst. split.\n          rewrite -> last_drop with (x := lst).\n          { reflexivity. }\n          { apply Hlst. }\n          { apply lookup_lt_is_Some_1.\n            rewrite Hm'. exists m'. reflexivity.\n          }\n          apply Hbase.\n        }\n        split.\n        { apply hd_drop_lookup. apply Hm'. }\n        { rewrite tail_drop_comm.\n          rewrite -zip_with_drop.\n          apply Forall_drop.\n          apply Hfa.\n        }\n      Qed.\n\n      Lemma witnessing_sequence_tail (m : Domain M) (l : list (Domain M)) (m' : Domain M) :\n        is_witnessing_sequence m l ->\n        head (tail l) = Some m' ->\n        is_witnessing_sequence m' (tail l).\n      Proof.\n        intros Hw Hhead.\n        unfold is_witnessing_sequence in Hw.\n        destruct Hw as [[lst [Hlst1 Hlst2] ] Hw].\n        unfold is_witnessing_sequence.\n        split.\n        { exists lst.\n          split. 2: apply Hlst2.\n          eapply last_tail. 2: apply Hhead. apply Hlst1.\n        }\n        split.\n        { apply Hhead. }\n        rewrite -tail_zip.\n        apply Forall_tail.\n        destruct Hw as [Hw1 Hw2].\n        apply Hw2.\n      Qed.\n      \n\n      Lemma is_witnessing_sequence_iff_is_witnessing_sequence_old_reverse (m : Domain M) (l : list (Domain M)) :\n        is_witnessing_sequence m l <-> is_witnessing_sequence_old m (reverse l).\n      Proof.\n        assert (Feq: (uncurry\n                        (flip\n                           (λ new old : Domain M,\n                                        new ∈\n                                        app_ext\n                                          (eval ρ step)\n                                          {[old]})\n                     ))\n                     =  (λ x : Domain M * Domain M,\n                               let (old, new) := x in\n                               new ∈\n                               app_ext\n                                 (eval ρ step)\n                                 {[old]})).\n\n        { apply functional_extensionality. intros [x₁ x₂].\n          reflexivity.\n        }\n\n        split.\n        - intros [[m' [Hlast Hbase] ] [Hhd Hfa] ].\n          destruct l as [|x l].\n          { simpl in Hhd. inversion Hhd. }\n          simpl in Hhd. inversion Hhd. subst. clear Hhd.\n          split.\n          { rewrite reverse_cons. rewrite last_app_singleton.\n            reflexivity.\n          }\n\n          (* reverse (m::l) <> nil *)\n          destruct (reverse (m::l)) eqn:Heq.\n          { assert ( length (reverse (m::l)) = @length (Domain M) []).\n            { rewrite Heq. reflexivity. }\n            rewrite reverse_length in H.\n            simpl in H. inversion H.\n          }\n\n          assert (Hm'd: m' = d).\n          {\n            rewrite reverse_cons in Heq.\n            pose proof (H := last_reverse_head _ l m).\n            rewrite Hlast in H.\n            unfold reverse in Heq.\n            rewrite Heq in H.\n            simpl in H.\n            inversion H. subst.\n            reflexivity.\n          }\n          subst.\n          split.\n          { apply Hbase. }\n          clear Hbase.\n\n          pose proof (Heq' := f_equal reverse Heq).\n          rewrite reverse_involutive in Heq'.\n          assert (Heq'' : l0 = tail (d::l0)).\n          { reflexivity. }\n          rewrite -> Heq'' at 2. clear Heq''.\n          rewrite -Heq.\n          clear Heq' Heq l0.\n          apply Forall_zip_flip_reverse in Hfa.\n          clear Hlast.\n\n          rewrite Feq in Hfa.\n          apply Hfa.\n        - intros H.\n          destruct H as [Hlast H2].\n          destruct l as [|x l].\n          { simpl in Hlast. inversion Hlast. }\n\n          destruct (reverse (x::l)) as [|y ys] eqn:Heq.\n          { inversion H2. }\n          destruct H2 as [Hbase Hfa].\n\n          rewrite -(reverse_involutive (y::ys)) in Heq.\n          apply (@inj _ _ (=) _ reverse) in Heq.\n          2: typeclasses eauto.\n          \n          split.\n          { exists y.\n            split.\n            rewrite Heq.\n            rewrite last_reverse.\n            reflexivity.\n            apply Hbase.\n          }\n\n          split.\n          {\n            rewrite Heq.\n            rewrite head_reverse.\n            apply Hlast.\n          }\n\n          assert (Hfeq': (λ new old : Domain M, new ∈ app_ext (eval ρ step) {[old]}) = flip (flip (λ new old : Domain M, new ∈ app_ext (eval ρ step) {[old]}))).\n          { apply functional_extensionality. intros x0.\n            apply functional_extensionality. intros x1.\n            reflexivity.\n          }\n          rewrite Hfeq'.\n          rewrite Heq.\n          rewrite -Forall_zip_flip_reverse.\n          rewrite Feq.\n          apply Hfa.\n      Qed.\n\n      Lemma witnessing_sequence_extend (m m' : Domain M) (l : list (Domain M)) :\n        (is_witnessing_sequence m l\n         /\\ (∃ step', step' ∈ eval ρ step /\\ m' ∈ app_interp _ step' m)\n        ) <-> (is_witnessing_sequence m' (m'::l) /\\ l ≠ []).\n      Proof.\n        split.\n        - intros [[[lst [Hlst Hbase] ] [Hhd Hwit] ] [step' [Hstep' Hm'] ] ].\n          split.\n          2: { destruct l. simpl in Hhd. inversion Hhd. discriminate. }\n          move: m Hhd m' step' Hm' Hstep'.\n          induction l; intros m Hhd m' step' Hm' Hstep'.\n          + simpl in Hhd. inversion Hhd.\n          + simpl in Hhd. inversion Hhd. subst a. clear Hhd.\n            unfold is_witnessing_sequence.\n            destruct l.\n            { simpl in Hlst. inversion Hlst. subst m. clear Hlst.\n              split.\n              { exists lst. simpl. split. reflexivity. apply Hbase. }\n              simpl. split. reflexivity. apply Forall_cons.\n              split. exists step'. exists lst. split.\n              apply Hstep'. split. constructor. apply Hm'.\n              apply Forall_nil. exact I.\n            }\n            split.\n            { exists lst. split. simpl. simpl in Hlst. apply Hlst. apply Hbase. }\n            split.\n            { reflexivity. }\n            simpl in Hwit. simpl.\n            apply Forall_cons.\n            simpl in IHl. simpl in Hlst.\n            specialize (IHl Hlst).\n            inversion Hwit. subst. clear Hwit.\n            specialize (IHl H2). clear Hlst H2.\n            split.\n            { exists step'. exists m. split. apply Hstep'. split. constructor. apply Hm'. }\n            apply Forall_cons.\n            split.\n            { apply H1. }\n            specialize (IHl d erefl).\n            destruct H1 as [step'' [d'' [Hstep'' [Hd'' Hstep''d''] ] ] ].\n            inversion Hd''. subst d''. clear Hd''.\n            specialize (IHl m step'' Hstep''d'' Hstep'').\n            unfold is_witnessing_sequence in IHl.\n            simpl in IHl.\n            destruct IHl as [_ [_ Hforall] ].\n            inversion Hforall. subst. apply H2.\n        -\n      Abort.\n\n\n      Lemma witnessing_sequence_old_extend\n            (m x m' : Domain M) (l : list (Domain M)):\n        (is_witnessing_sequence_old m (x::l) /\\\n        ∃ step', (step' ∈ eval ρ step /\\\n        m' ∈ app_interp _ step' m)) <->\n        (last (x::l) = Some m /\\ is_witnessing_sequence_old m' ((x::l) ++ [m'])).\n      Proof.\n        split.\n        -\n          intros [Hwit [step' [Hstep' Hm'] ] ].\n          destruct Hwit as [Hwit1 [Hwit2 Hwit3] ].\n          split.\n          { apply Hwit1. }\n          split.\n          { apply last_snoc. }\n          simpl.\n          split.\n          { apply Hwit2. }\n\n          destruct l.\n          { simpl. apply Forall_cons. split. 2: { apply Forall_nil. exact I. }\n            exists step'. exists x. split.\n            { apply Hstep'. }\n            split.\n            { constructor. }\n            simpl in Hwit1. inversion Hwit1. subst. apply Hm'.\n          }\n          simpl.\n          apply Forall_cons.\n          simpl in Hwit3. inversion Hwit3. subst. clear Hwit3.\n          rename H1 into Hd. rename H2 into Hwit.\n          split.\n          { apply Hd. } clear Hd.\n\n          move: d Hwit1 Hwit.\n          induction l.\n          + intros D Hm _.\n            simpl. simpl in Hm. inversion Hm. subst.\n            clear Hm.\n            apply Forall_cons.\n            split.\n            2: { apply Forall_nil. exact I. }\n            exists step'. exists m. split.\n            { apply Hstep'. }\n            split.\n            { constructor. }\n            apply Hm'.\n          + intros d Hlast Hwit. simpl.\n            inversion Hwit. subst.\n            apply Forall_cons.\n            split.\n            { apply H1. }\n            apply IHl. simpl in Hlast. simpl. apply Hlast.\n            apply H2.\n        - intros [Hlast H].\n          unfold is_witnessing_sequence in H.\n          destruct H as [_ H].\n          remember (length l) as len.\n          assert (Hlen: length l <= len).\n          { lia. }\n          clear Heqlen. simpl in H.\n          destruct H as [Hbase Hall].\n          unfold is_witnessing_sequence.\n          apply and_assoc.\n          split.\n          { apply Hlast. }\n          apply and_assoc.\n          split.\n          { apply Hbase. }\n          clear Hbase.\n\n          move: x l Hlast Hall Hlen.\n          induction len.\n          + intros x l Hlast Hall Hlen.\n            destruct l.\n            2: { simpl in Hlen. lia.  }\n            simpl. simpl in Hall.\n            split.\n            { apply Forall_nil. exact I. }\n            inversion Hall. subst. clear Hall. clear H2.\n            destruct H1 as [step' [m'' [Hstep' [Hm'm'' Hstep'm''] ] ] ].\n            inversion Hm'm''. subst. clear Hm'm''.\n            exists step'. split. apply Hstep'.\n            simpl in Hlast. inversion Hlast. subst.\n            apply Hstep'm''.\n          + intros x l Hlast Hall Hlen.\n            destruct l as [|x' l'].\n            { simpl in Hlast. inversion Hlast. clear Hlast. subst.\n              simpl in Hall.\n              inversion Hall. subst. clear Hall.\n              clear H2.\n              simpl.\n              split.\n              { apply Forall_nil. exact I. }\n              destruct H1 as [step' Hstep'].\n              exists step'.\n              destruct Hstep' as [m'' [Hstep' [Hmm'' Hm''] ] ].\n              split.\n              { apply Hstep'. }\n              inversion Hmm''. subst.\n              apply Hm''.\n            }\n            simpl in Hall. simpl in IHlen. simpl in Hlast.\n            inversion Hall. subst. clear Hall.\n            specialize (IHlen x' l' Hlast H2).\n            simpl.\n            rewrite Forall_cons.\n            apply and_assoc.\n            split.\n            { apply H1. }\n            apply IHlen.\n            simpl in Hlen. lia.\n      Qed.\n\n      Definition witnessed_elements_old : propset (Domain M) :=\n        PropSet (λ m, ∃ l, is_witnessing_sequence_old m l).\n\n      Lemma witnessed_elements_old_prefixpoint : (F witnessed_elements_old) ⊆ witnessed_elements_old.\n      Proof.\n        rewrite elem_of_subseteq. intros x Hx.\n        unfold F in Hx. unfold Fassoc in Hx. unfold svar_open in Hx. simpl in Hx.\n        rewrite eval_or_simpl in Hx.\n        fold ((nest_mu base)^{svar: 0 ↦ (fresh_svar patt_ind_gen_body)}) in Hx.\n        fold ((nest_mu step)^{svar: 0 ↦ (fresh_svar patt_ind_gen_body)}) in Hx.\n        destruct Hx.\n        - unfold Ensembles.In in H.\n          unfold witnessed_elements_old.\n          exists [x]. unfold is_witnessing_sequence_old.\n          simpl.\n          split.\n          { reflexivity. }\n          split.\n          2: { constructor. }\n          rewrite eval_free_svar_independent in H.\n          {\n            eapply svar_is_fresh_in_richer. 2: { subst. auto. }\n            unfold svar_open.\n            solve_free_svars_inclusion 5.\n          }\n          simpl. unfold svar_open in H.\n          rewrite nest_mu_same in H. auto.\n        - unfold Ensembles.In in H.\n          rewrite eval_app_simpl in H.\n          rewrite eval_free_svar_simpl in H.\n          rewrite update_svar_val_same in H.\n          unfold app_ext in H.\n          destruct H as [step' [m [H1 [H2 Happ] ] ] ].\n          unfold witnessed_elements_old in H2.\n          destruct H2 as [l Hl].\n\n          unfold witnessed_elements_old.\n          exists (l ++ [x]).\n\n          (* `l` is not empty *)\n          destruct l as [|m₀ l'] eqn:Heql.\n          { unfold is_witnessing_sequence in Hl. destruct Hl. simpl in H. inversion H. }\n\n          unfold svar_open in H1. rewrite nest_mu_same in H1.\n          rewrite eval_free_svar_independent in H1.\n          {\n            eapply svar_is_fresh_in_richer.\n            2: { apply set_svar_fresh_is_fresh. }\n            solve_free_svars_inclusion 2.\n          }\n\n          epose proof (P := @witnessing_sequence_old_extend _ _ _ _).\n          destruct P as [P _].\n          specialize (P (conj Hl (@ex_intro _ _ step' (conj H1 Happ)))).\n          apply P.\n      Qed.\n\n      Lemma interp_included_in_witnessed_elements_old:\n        (@eval Σ M ρ patt_ind_gen) ⊆ witnessed_elements_old.\n      Proof.\n        apply eval_mu_lfp_least.\n        { apply patt_ind_gen_wfp. }\n        apply witnessed_elements_old_prefixpoint.\n      Qed.\n\n      Lemma eval_patt_ind_gen_fix :\n        let Sfix := eval ρ patt_ind_gen in\n        F Sfix = Sfix.\n      Proof.\n        apply eval_mu_lfp_fixpoint.\n        apply patt_ind_gen_wfp.\n      Qed.\n\n\n      Definition witnessed_elements_old_of_max_len len : propset (Domain M) :=\n        PropSet (λ m, ∃ l, is_witnessing_sequence_old m l /\\ length l <= len).\n\n      Lemma witnessed_elements_old_of_max_len_included_in_interp len:\n        (witnessed_elements_old_of_max_len (S len)) ⊆ (@eval Σ M ρ patt_ind_gen).\n      Proof.\n        induction len.\n        - unfold Included. intros m.\n          rewrite -eval_patt_ind_gen_fix.\n          unfold Ensembles.In.\n          intros H.\n          unfold witnessed_elements_old_of_max_len.\n          rewrite F_interp.\n          destruct H as [l [Hwit Hlen] ].\n          unfold is_witnessing_sequence in Hwit.\n          destruct Hwit as [Hlast Hm].\n          destruct l.\n          { simpl in Hlast. inversion Hlast. }\n          destruct l.\n          2: { simpl in Hlen. lia. }\n          simpl in Hlast. inversion Hlast. clear Hlast. subst.\n          destruct Hm as [Hm _].\n          left. unfold Ensembles.In. apply Hm.\n        - unfold Included. intros m.\n          rewrite -eval_patt_ind_gen_fix.\n          unfold Ensembles.In. intros H.\n          destruct H as [l [Hwit Hlen] ].\n          unfold Included in IHlen. unfold Ensembles.In in IHlen.\n          rewrite F_interp.\n          pose proof (Hwit' := Hwit).\n          unfold is_witnessing_sequence in Hwit.\n          destruct Hwit as [Hlast Hl].\n          destruct l.\n          { contradiction. }\n\n          simpl in Hlen.\n          destruct Hl as [Hd Hl].\n          destruct l.\n          + simpl in Hlast. inversion Hlast. clear Hlast. subst.\n            left. unfold Ensembles.In. apply Hd.\n          + right. unfold Ensembles.In.\n            pose proof (P := witnessing_sequence_old_extend).\n            destruct l as [|x' l'].\n            { simpl in Hlast. inversion Hlast. subst.\n              specialize (P d d m []).\n              destruct P as [_ P]. simpl in P.\n              simpl in Hl.\n              inversion Hl. subst. clear Hl.\n              assert (Hsomed: Some d = Some d).\n              { reflexivity. }\n              specialize (P (conj Hsomed Hwit')).\n              destruct P as [Hwitd [step' Hstep'] ].\n              exists step'. exists d.\n              destruct Hstep' as [Hstep' Hm].\n              split.\n              { apply Hstep'. }\n              split.\n              { apply IHlen. unfold witnessed_elements_old_of_max_len.\n                exists [d].\n                split.\n                2: { simpl. lia. }\n                unfold is_witnessing_sequence. simpl.\n                split.\n                { reflexivity. }\n                split.\n                { apply Hd. }\n                apply Forall_nil.\n                exact I.\n              }\n              apply Hm.\n            }\n            simpl in P.\n            simpl in Hlast.\n            simpl in Hl.\n            inversion Hl. subst. clear Hl.\n            inversion H2. subst. clear H2.\n            pose (mp := (rev (d0 :: x' :: l')) !! 1).\n            simpl in mp.\n            epose proof (Htot := (list_lookup_lookup_total_lt (rev (d0 :: x' :: l')) 1 _)).\n            Unshelve. 2: { constructor. exact d0. }\n            2: { simpl. rewrite app_length. rewrite app_length. simpl.  lia.  }\n\n            remember (@lookup_total nat (@Domain Σ M) (list (@Domain Σ M))\n                 (@list_lookup_total (@Domain Σ M) {| inhabitant := d0 |}) (S O)\n                 (@rev (@Domain Σ M) (@cons (@Domain Σ M) d0 (@cons (@Domain Σ M) x' l')))) as mprev.\n\n            specialize (IHlen mprev).\n            unfold witnessed_elements_old_of_max_len in IHlen.\n            specialize (P mprev d m  (rev (tl (rev (d0::x'::l'))))).\n\n            assert (Heq1: d::d0::x'::l' = d::(rev (tail (rev (d0::x'::l')))) ++ [m]).\n            {\n              apply f_equal.\n              simpl.\n              assert (Hx'r: [x'] = rev [x']).\n              { reflexivity. }\n              rewrite Hx'r.\n              rewrite -rev_app_distr.\n              assert (Hd0r: [d0] = rev [d0]).\n              { reflexivity. }\n              rewrite Hd0r.\n              rewrite -rev_app_distr.\n              rewrite rev_tail_rev_app_last.\n              simpl.\n              apply Hlast.\n              reflexivity.\n            }\n            destruct P as [_ P].\n\n\n            destruct (rev (tail (rev (d0 :: x' :: l')))) eqn:Heqrev.\n            {\n              apply length_zero_iff_nil in Heqrev.\n              rewrite rev_length in Heqrev.\n              apply length_tail_zero in Heqrev.\n              rewrite rev_length in Heqrev.\n              simpl in Heqrev. lia.\n            }\n\n            simpl in Heq1. inversion Heq1. subst d0. clear Heq1.\n            simpl in P.\n            rewrite -H2 in P.\n\n            assert (Hm : (match l with [] => Some d1 | _ :: _ => last l end ) = Some mprev).\n            {\n              clear P Heqrev H1 H3 H4 mp.\n              destruct l.\n              { simpl in H2. inversion H2. subst. reflexivity. }\n              simpl.\n              simpl in H2.\n              inversion H2. subst x' l'. clear H2.\n              simpl in Htot.\n              destruct (l ++ [m]) eqn:Hcontra.\n              { pose proof (Hcontra' := @app_length _ l [m]).\n                rewrite Hcontra in Hcontra'.\n                simpl in Hcontra'. lia.\n              }\n              rewrite -Hcontra in Htot.\n              rewrite rev_app_distr in Htot. simpl in Htot.\n\n              destruct l.\n              { simpl in Htot. apply Htot. }\n              simpl in Htot.\n              rewrite -Htot.\n              rewrite hd_error_lookup.\n              rewrite hd_error_app. rewrite hd_error_app.\n              simpl.\n              apply last_rev_head.\n            }\n            specialize (P (@conj _ _ Hm Hwit')). clear Hm Hwit'.\n            destruct P as [Hwitmprev [step' [Hstep' Hm] ] ].\n            exists step'. exists mprev.\n            split.\n            { apply Hstep'. }\n            split.\n            2: { apply Hm. }\n            apply IHlen.\n            exists (d::d1::l).\n            split.\n            { apply Hwitmprev. }\n            simpl. simpl in Hlen.\n            assert (Hlen': S (length l') <= len).\n            { lia. }\n            assert (length (l') = length (l)).\n            { apply (@list_len_slice _ _ _ _ _ H2). }\n            rewrite -H. lia.\n      Qed.\n\n      Lemma witnessed_elements_old_included_in_interp:\n        witnessed_elements_old ⊆ (@eval Σ M ρ patt_ind_gen).\n      Proof.\n        intros x H.\n        unfold Ensembles.In in H. unfold witnessed_elements_old in H.\n        destruct H as [wit Hwit].\n        assert (H': x ∈ (witnessed_elements_old_of_max_len (length wit))).\n        { unfold Ensembles.In. exists wit. split. apply Hwit. lia. }\n        destruct wit as [|y l'] eqn:Hl.\n        { unfold is_witnessing_sequence in Hwit. destruct Hwit. contradiction. }\n        eapply witnessed_elements_old_of_max_len_included_in_interp.\n        simpl in H'.\n        apply H'.\n      Qed.\n\n      Definition witnessed_elements : propset (Domain M) :=\n        PropSet (λ m, ∃ l, is_witnessing_sequence m l).\n\n      Lemma witnessed_elements_old_eq_witnessed_elements :\n        witnessed_elements_old = witnessed_elements.\n      Proof.\n        rewrite -> set_eq_subseteq.\n        repeat rewrite -> elem_of_subseteq.\n        split;\n          unfold witnessed_elements_old; unfold witnessed_elements; intros m; intros [l H].\n        + exists (reverse l).\n          apply is_witnessing_sequence_iff_is_witnessing_sequence_old_reverse.\n          rewrite reverse_involutive.\n          exact H.\n        + exists (reverse l).\n          apply is_witnessing_sequence_iff_is_witnessing_sequence_old_reverse.\n          apply H.\n      Qed.\n\n      Lemma patt_ind_gen_simpl:\n        @eval Σ M ρ patt_ind_gen = witnessed_elements.\n      Proof.\n        rewrite -witnessed_elements_old_eq_witnessed_elements.\n        rewrite -> set_eq_subseteq.\n        split.\n        + apply interp_included_in_witnessed_elements_old.\n        + apply witnessed_elements_old_included_in_interp.\n      Qed.\n\n      Section injective.\n        Hypothesis (Domain_eq_dec : EqDecision (Domain M)).\n        Hypothesis (Hstep_total_function : @is_total_function _ M step witnessed_elements witnessed_elements ρ).\n        Hypothesis (Hstep_injective : @total_function_is_injective _ M step witnessed_elements ρ).\n\n        Hypothesis (Hbase_step_no_confusion\n                    : (eval ρ base)\n                        ∩ (app_ext (eval ρ step) witnessed_elements) = ∅).\n\n        Lemma witnessed_elements_unique_seq :\n          ∀ m l₁ l₂, is_witnessing_sequence m l₁ -> is_witnessing_sequence m l₂ -> l₁ = l₂.\n        Proof.\n          intros m l₁ l₂.\n          wlog: l₁ l₂ / (length l₂ <= length l₁).\n          { intros H Hw₁ Hw₂.\n            destruct (decide (length l₁ <= length l₂)).\n            - symmetry. apply H; auto.\n            - apply H. lia. auto. auto.\n          }\n          intros Hlen12 Hw₁ Hw₂.\n\n          assert (Hmwit: m ∈ witnessed_elements).\n          { exists l₁. apply Hw₁. }\n\n          assert (Hlcom:  (common_length l₁ l₂ = length l₂)).\n          {\n            destruct Hw₁ as [[lst₁ [Hlst₁ Hbase₁] ] [Hhd₁ Hfa₁] ].\n            destruct l₁ as [|m₁ l₁].\n            { simpl in Hlst₁. inversion Hlst₁. }\n            simpl in Hhd₁. inversion Hhd₁. subst. clear Hhd₁.\n\n            destruct Hw₂ as [[lst₂ [Hlst₂ Hbase₂] ] [Hhd₂ Hfa₂] ].\n            destruct l₂ as [|m₂ l₂].\n            { simpl in Hlst₂. inversion Hlst₂. }\n            simpl in Hhd₂. inversion Hhd₂. subst. clear Hhd₂.\n\n            simpl.\n            destruct (decide (m=m)).\n            2: { contradiction. }\n            clear e.\n            apply f_equal.\n\n            simpl in Hlen12. rename Hlen12 into Hlen12'.\n            assert (Hlen12: length l₂ <= length l₁).\n            { lia. }\n            clear Hlen12'.\n\n            remember (length l₁) as len₁.\n            rewrite Heqlen₁ in Hlen12.\n            assert (Hlen₁ : length l₁ <= len₁).\n            { lia. }\n            clear Heqlen₁.\n\n            move: m l₁ l₂ Hlen12 Hlen₁ Hlst₁ Hlst₂ Hfa₁ Hfa₂ Hmwit.\n            induction len₁; intros m l₁ l₂ Hlen12 Hlen₁ Hlst₁ Hlst₂ Hfa₁ Hfa₂ Hmwit.\n            - destruct l₁.\n              2: { simpl in Hlen₁. lia. }\n              destruct l₂.\n              + reflexivity.\n              + assert (length (d::l₂) = 0).\n                { simpl in Hlen12. lia. }\n                rewrite H. reflexivity.\n            - destruct l₂ as [|b l₂].\n              { rewrite common_length_l_nil. reflexivity. }\n\n              destruct l₁ as [|a l'₁] eqn:Heq.\n              { simpl in Hlen12. lia. }\n\n\n              simpl in Hfa₁. inversion Hfa₁. subst. clear Hfa₁.\n              rename H1 into Hma. rename H2 into Hfa₁.\n              simpl in Hfa₂. inversion Hfa₂. subst. clear Hfa₂.\n              rename H1 into Hmb. rename H2 into Hfa₂.\n\n              assert (Hwita: a ∈ witnessed_elements).\n              { exists (a::l'₁).\n                split.\n                { exists lst₁. split.\n                  { simpl in Hlst₁. simpl. apply Hlst₁. }\n                  apply Hbase₁.\n                }\n                split.\n                { reflexivity. }\n                simpl. apply Hfa₁.\n              }\n\n              assert (Hwitb: b ∈ witnessed_elements).\n              { exists (b::l₂).\n                split.\n                { exists lst₂. split.\n                  { simpl in Hlst₂. simpl. apply Hlst₂. }\n                  apply Hbase₂.\n                }\n                split.\n                { reflexivity. }\n                simpl. apply Hfa₂.\n              }\n\n              simpl in Hma. simpl in Hmb.\n\n              assert (Ham: app_ext (eval ρ step) {[a]} = {[m]}).\n              {\n                unfold is_total_function in Hstep_total_function.\n                pose proof (Hstep_total_function _ Hwita).\n                destruct H as [a' [_ Ha'] ].\n                rewrite Ha' in Hma.\n                inversion Hma. subst.\n                apply Ha'.\n              }\n\n              assert (Hbm: app_ext (eval ρ step) {[b]} = {[m]}).\n              {\n                unfold is_total_function in Hstep_total_function.\n                pose proof (Hstep_total_function _ Hwitb).\n                destruct H as [b' [_ Hb'] ].\n                rewrite Hb' in Hmb.\n                inversion Hmb. subst.\n                apply Hb'.\n              }\n\n              assert (Haeqb: a = b).\n              { apply Hstep_injective.\n                apply Hwita. apply Hwitb.\n                unfold rel_of.\n                rewrite Ham.\n                rewrite Hbm.\n                reflexivity.\n              }\n              subst.\n              clear Ham Hbm Hwita Hma.\n\n              simpl.\n              destruct (decide (b=b)).\n              2: { contradiction. }\n              apply f_equal.\n\n              apply IHlen₁ with (m := b).\n              { simpl in Hlen12.  lia. }\n              { simpl in Hlen₁. lia. }\n              simpl in Hlst₁. simpl. apply Hlst₁.\n              simpl in Hlst₂. simpl. apply Hlst₂.\n\n              simpl. apply Hfa₁.\n              simpl. apply Hfa₂.\n              apply Hwitb.\n          }\n\n          assert (Hlast12: l₁ !! (length l₂ - 1) = l₂ !! (length l₂ - 1)).\n          {\n            eapply equal_up_to_common_length.\n            erewrite Hlcom.\n            assert (length l₂ > 0).\n            {\n              destruct l₂.\n              { unfold is_witnessing_sequence in Hw₂.\n                simpl in Hw₂. destruct Hw₂ as [_ [Contra _] ].\n                inversion Contra.\n              }\n              simpl. lia.\n            }\n            lia.\n          }\n\n          (*assert (Hbasem': eval ρ base lst).*)\n\n          assert (~ (length l₁ > length l₂)).\n          {\n            intros Hcontra.\n            assert (Hlt : length l₂ - 1 < length l₁).\n            { lia. }\n            pose proof (Hexm := list_ex_elem l₁ (length l₂ - 1) Hlt). clear Hlt.\n            destruct Hexm as [m' Hm'].\n            pose proof (Hwsm := witnessing_sequence_middle _ _ _ _ Hw₁ Hm').\n            pose proof (Hw₂' := Hw₂).\n            unfold is_witnessing_sequence in Hw₂'.\n            destruct Hw₂' as [[lst [Hlst1 Hlst2] ] _].\n            rewrite list_last_length in Hlst1.\n            assert (Hlsteqm' : m' = lst).\n            {\n              assert (Some m' = Some lst).\n              { rewrite -Hm'. rewrite -Hlst1. apply Hlast12.  }\n              inversion H. reflexivity.\n            }\n            subst lst.\n            specialize (Hwsm Hlst2).\n            clear Hm' Hlst1.\n\n            destruct (drop (length l₂ - 1) l₁) eqn:Heq.\n            {\n              destruct Hwsm as [_ [Contra _] ].\n              inversion Contra.\n            }\n            (* if `l` is empty, then length l₁ = length l₂ -> Contradiction *)\n            destruct l.\n            {\n              assert (Hlendrop: length (drop (length l₂ - 1) l₁) = 1).\n              { rewrite Heq. reflexivity. }\n              rewrite drop_length in Hlendrop.\n              assert (length l₂ <> 0).\n              { intros Hcontra'.\n                apply nil_length_inv in Hcontra'.\n                subst l₂.\n                destruct Hw₂ as [_ [HContra'' _] ].\n                inversion HContra''.\n              }\n              lia.\n            }\n            (* `d0` is a member of `witnessed_elements` *)\n            epose proof (Hwd0 := witnessing_sequence_tail _ _ _ Hwsm).\n            simpl in Hwd0.\n            assert (Htmp: Some d0 = Some d0).\n            { reflexivity. }\n            specialize (Hwd0 Htmp). clear Htmp.\n\n            assert (Hd0we : d0 ∈ witnessed_elements).\n            { exists (d0::l). apply Hwd0. }\n\n            assert (Heqm'd : m' = d).\n            { unfold is_witnessing_sequence in Hwsm.\n              destruct Hwsm as [_ [H _] ].\n              simpl in H. inversion H.\n              reflexivity.\n            }\n            subst m'.\n\n            (* `m'=d` matches `app_ext (eval ρ step) d0` *)\n            assert (d ∈ app_ext\n                      (eval ρ step)\n                      {[d0]}).\n            {\n              unfold is_witnessing_sequence in Hwsm.\n              simpl in Hwsm.\n              destruct Hwsm as [_ [_ Hwsm] ].\n              inversion Hwsm. subst.\n              simpl in H1.\n              apply H1.\n            }\n            rewrite -> set_eq_subseteq in Hbase_step_no_confusion.\n            destruct Hbase_step_no_confusion as [H1 _].\n            rewrite -> elem_of_subseteq in H1.\n            specialize (H1 d).\n            apply not_elem_of_empty in H1.\n            { exact H1. }\n            clear H1.\n            split.\n            - apply Hlst2.\n            - unfold Ensembles.In.\n              unfold app_ext.\n              destruct H as [le' [re' [H1 [H2 H3] ] ] ].\n              exists le'. exists d0.\n              split.\n              { apply H1. }\n              split.\n              { apply Hd0we. }\n              inversion H2. subst. apply H3.\n          }\n          assert (Hlength12: length l₁ = length l₂).\n          { lia. }\n          clear Hlen12 H.\n\n          apply (common_length_impl_eq _ _ Hlength12 Hlcom).\n        Qed.\n\n      End injective.\n\n    End with_eval.\n\n  End inductive_generation.\n\nEnd with_signature.\n", "meta": {"author": "harp-project", "repo": "AML-Formalization", "sha": "ee6fd737632e1bb2737b22cbbbca3b8a3e68f89d", "save_path": "github-repos/coq/harp-project-AML-Formalization", "path": "github-repos/coq/harp-project-AML-Formalization/AML-Formalization-ee6fd737632e1bb2737b22cbbbca3b8a3e68f89d/matching-logic/src/FixpointReasoning.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6545382866311181}}
{"text": "(** * TAL-0 Typed Assembly Language *)\n\n(** Based on paper by Greg Morrisett , TAL-0 is the design of a RISC-style typed assembly language which focuses on control-flow safety. This post provides a mechanized metatheory, particularly a machine checked proof of soundness of the TAL-0 type system as proposed by the author in section 4.2.10 of the book Advanced Topics in Types and Programming Languages.  *)\n\n(** The TAL-0 language runs on an abstract machine which is represented by 3 components :\n\n1. A heap H which is a finite, partial map from labels to heap values\n\n2. a register file R which is a total map from registers to values, and \n\n3. a current instruction sequence I.  \n *)\n\nRequire Import Bool Arith Vector LibTactics.\nRequire Import Maps.\n\nDefinition registers := total_map nat.\nDefinition empty_regs : registers := t_empty 0.\n\nInductive val : Type :=\n| ANum : nat -> val\n| AReg : nat -> val\n| ALab : nat -> val.\n\n(** We denote addresses of instructions stored in the heap as labels. Unlike a typical machine where labels are resolved to some machine address, which are integers, we maintain a distinction between labels and arbit integers, as this complies with our goal to state and prove the control-flow safety i.e. we can only branch to a valid label, and not to any arbit integer. This will ensure that the machine never gets stuck while trying to do some invalid operation. *)\n(*define relations for aeval , ieval*)\nFixpoint aeval (a : val) (R : registers) : nat :=\n  match a with\n  | ANum n => n\n  | AReg d => R (Id d)\n  | ALab l => l\n  end.\n\n\nInductive instr : Type :=\n| IMov : forall d : nat,\n    val -> instr\n| IAdd : forall d s : nat,\n    instr\n| ISub : forall d v : nat,\n    instr\n| IIf : forall d : nat,\n    val -> instr.\n\nInductive instr_seq : Type :=\n| ISeq : instr -> instr_seq -> instr_seq\n| IJmp : val -> instr_seq.\n\n(** Simple Notations are chosen for the sake of clarity while writing programs.*)\nNotation \"'R(' d ')' ':=' a\" :=\n  (IMov d (ANum a)) (at level 60).\nNotation \"'R(' d ')' '+:=' 'R(' s ')'\" :=\n  (IAdd d s) (at level 60).\nNotation \"'R(' s ')' '-:=' v\" :=\n  (ISub s v) (at level 60).\nNotation \"i1 ;; i2\" :=\n  (ISeq i1 i2) (at level 80, right associativity).\nNotation \"'JIF' 'R(' d ')' v\" :=\n  (IIf d (ANum v)) (at level 70).\nNotation \"'JMP' v\" :=\n  (IJmp (ALab v)) (at level 80).\nNotation \"'JMP' 'R(' r ')'\" :=\n  (IJmp (AReg r)) (at level 80).\n\nCheck JIF R(1) 2.\nCheck R(1) := 10.\nCheck R(2) +:= R(1).\nCheck R(2) -:= 1.\nCheck R(2) +:= R(1) ;; R(2) -:= 1 ;; JMP 2.\nCheck JMP 2.\nCheck JMP R(2).\n\n\nDefinition heaps := partial_map instr_seq.\nDefinition empty_heap : heaps := empty.\n\n(* Machine State *)\nInductive st : Type :=\n| St : heaps -> registers -> instr_seq -> st.\n\n(** Evaluation of instructions is supposed to change the Machine State and thus some of its components H, R or I. These changes are posed as relations between initial and final state of the machine. *)\nInductive ieval : st -> st -> Prop :=\n| R_IMov : forall H R I d a,\n    ieval (St H R (R(d) := a ;; I)) (St H (t_update R (Id d) a) I)\n| R_IAdd : forall H R I d s,\n    ieval (St H R (R(d) +:= R(s) ;; I)) (St H (t_update R (Id d) (aeval (AReg d) R + aeval (AReg s) R)) I)\n| R_ISub : forall H R I d v,\n    ieval (St H R (R(d) -:= v ;; I)) (St H (t_update R (Id d) (aeval (AReg d) R - aeval (ANum v) R)) I)\n| R_IJmp_Succ : forall H R I' a l,\n    l = (aeval a R) -> H (Id l) = Some I' -> ieval (St H R (JMP l)) (St H R I')\n| R_IJmpR_Succ : forall H R I' r,\n    H (Id (R (Id r))) = Some I' -> ieval (St H R (JMP R(r))) (St H R I')\n| R_IJmp_Fail : forall H R I a,\n    H (Id (aeval a R)) = None -> ieval (St H R I) (St H R I)\n| R_IIf_EQ : forall H R I I2 r v,\n    aeval (AReg r) R = 0 -> (H (Id v)) = Some I2 -> ieval (St H R (JIF R(r) v ;; I)) (St H R I2)\n| R_IIf_NEQ : forall H R I r v,\n    aeval (AReg r) R <> 0 -> ieval (St H R (JIF R(r) v ;; I)) (St H R I)   \n| R_ISeq : forall st st' st'',\n    ieval st st' -> ieval st' st'' -> ieval st st''.\n\n(** Example of a program fragment that multiplies 2 numbers stored in registers 1 and 2 and stores their product in register 3, before finally looping in its final state register 4. *)\nDefinition init_heap := update (update (update empty_heap (Id 1) (R(3) := 0 ;; JMP 2)) (Id 2) (JIF R(1) 3 ;; R(2) +:= R(3) ;; R(1) -:= 1 ;; JMP 2) ) (Id 3) (JMP R(4)).\n\nDefinition init_regs : registers :=  (t_update (t_update  (t_update (t_update (t_update empty_regs (Id 5) 1) (Id 6) 2) (Id 7) 3) (Id 1) 1) (Id 2) 2).\nDefinition final_regs : registers := (t_update (t_update (t_update  (t_update (t_update (t_update empty_regs (Id 5) 1) (Id 6) 2) (Id 4) 1) (Id 1) 0) (Id 2) 2) (Id 3) 2).\n\nEval compute in init_heap (Id (init_regs (Id 6))).\n\n(* jump to a label proof *)\nExample ieval_example1 : ieval (St init_heap init_regs\n                                   (R(3) := 0 ;; JMP 2))\n                               (St init_heap (t_update init_regs (Id 3) 0)\n                                   (JIF R(1) 3 ;; R(2) +:= R(3) ;; R(1) -:= 1 ;; JMP 2)).\nProof.\n  apply R_ISeq with (St init_heap (t_update init_regs (Id 3) 0) (IJmp (ALab 2))).\n  apply R_IMov.\n  apply R_IJmp_Succ with (a := ALab 2).\n  simpl.\n  reflexivity.\n  unfold init_heap.\n  rewrite update_neq.\n  rewrite update_eq.\n  reflexivity.\n  rewrite <- beq_id_false_iff; trivial.\nQed.\n\n\n(** The types consist of\n1. int -> represents arbit integer stored in a register\n\n2. reg -> a type constructor. Takes as input, the type of the register, to which this register is pointing.\n\n3. code -> takes as input a typing context Γ, and gives type (code Γ) which is the type of an instruction sequence that expects type of the Register file to be Γ before it begins execution \n\n4. arrow -> represents type of a single instruction (excluding JMP), which expects register file of type Γ1 before execution, and changes it to Γ2 after it has executed.\n\n5. T -> It is the super type. It is used to represent the type of a register in R, which contains the label of the instruction currently executing. Because in such a case, we have the equation : Γ (r) = code Γ, which in the absence of subtyping or polymorphic types can't be solved. Hence T is assigned the type for such a register as it subsumes all types including itself. When we jump through a register of type T, we forget the type assigned to it, and reassign T to it.\nMorrisett's paper uses the polymorphic type for due to some more benefits it affords. However we have used T type for its simplicity.\n *)\n\nInductive ty : Type :=\n| int : ty\n| reg : ty -> ty\n| code : partial_map ty -> ty\n| arrow : partial_map ty -> partial_map ty -> ty\n| True : ty.\n\n\nDefinition context := partial_map ty.\n\n(* register file types *)\nDefinition empty_Gamma : context := empty.\n\n(* heap types *)\nDefinition empty_Psi : context := empty.\n\n(** The Typing Rules *)\n(** Ψ is a partial map containing types of instruction sequences. As all instruction sequences end in a JMP statement, all valid values in Ψ are Some (code Γ) where Γ is the initial type state of register expected by that instruction sequence. Now, typing rules may require presence of either both Ψ and Γ, or only Ψ or neither. Hence, we introduce a combined context structure, that handles all the 3 cases. *)\nInductive cmbnd_ctx :=\n| EmptyCtx : cmbnd_ctx\n| PsiCtx : context -> cmbnd_ctx\n| PsiGammaCtx : context -> context -> cmbnd_ctx.\n\n(** Typing rules for arithmetic expressions *)\nInductive ahas_type : cmbnd_ctx -> val -> ty -> Prop :=\n| S_Int : forall Ψ n,\n    ahas_type (PsiCtx Ψ) (ANum n) int\n| S_Lab : forall Ψ Γ l v R,\n    Ψ (Id l) = Some (code Γ) -> l = aeval (ALab v) R -> ahas_type (PsiCtx Ψ) (ALab v) (code Γ)\n| S_Reg : forall Ψ Γ r,\n    Γ (Id r) = Some (reg int) -> ahas_type (PsiGammaCtx Ψ Γ) (AReg r) (reg int)\n| S_RegV : forall Ψ Γ r,\n    ahas_type (PsiGammaCtx Ψ Γ) (AReg r) (reg (code Γ))\n| S_RegT : forall Ψ Γ r,\n    ahas_type (PsiGammaCtx Ψ Γ) (AReg r) True\n| S_Val : forall Ψ Γ a tau,\n    ahas_type (PsiCtx Ψ) a tau -> ahas_type (PsiGammaCtx Ψ Γ) a tau.\n\nHint Constructors ahas_type.\n\n(** Typing rules for instructions *)\nInductive ihas_type : cmbnd_ctx -> instr -> ty -> Prop :=\n| S_Mov : forall Ψ Γ R d a tau,\n    ahas_type (PsiGammaCtx Ψ Γ) a tau -> ahas_type (PsiGammaCtx Ψ Γ) (AReg d) (reg tau) -> (update Γ (Id d) (reg tau)) = Γ -> ihas_type (PsiCtx Ψ) (R(d) := aeval a R) (arrow Γ Γ)\n| S_Add : forall Ψ Γ d s,\n    ahas_type (PsiGammaCtx Ψ Γ) (AReg s) (reg int) -> ahas_type (PsiGammaCtx Ψ Γ) (AReg d) (reg int) -> update Γ (Id d) (reg int) = Γ -> ihas_type (PsiCtx Ψ) (R(d) +:= R(s)) (arrow Γ Γ)\n| S_Sub : forall Ψ Γ s a v,\n    ahas_type (PsiGammaCtx Ψ Γ) a int -> ahas_type (PsiGammaCtx Ψ Γ) (AReg s) (reg int) -> a = ANum v -> ihas_type (PsiCtx Ψ) (R(s) -:= v) (arrow Γ Γ)\n| S_If :  forall Ψ Γ r v,\n    ahas_type (PsiGammaCtx Ψ Γ) (AReg r) (reg int) -> ahas_type (PsiGammaCtx Ψ Γ) (ALab v) (code Γ) -> ihas_type (PsiCtx Ψ) (JIF R(r) v) (arrow Γ Γ).\nHint Constructors ihas_type.\n\n\nInductive iseq_has_type : cmbnd_ctx -> instr_seq -> ty -> Prop :=\n| S_Jmp :  forall Ψ Γ v,\n    ahas_type (PsiGammaCtx Ψ Γ) (ALab v) (code Γ) -> iseq_has_type (PsiCtx Ψ) (JMP v) (code Γ)\n| S_JmpT :  forall Ψ Γ v,\n    ahas_type (PsiGammaCtx Ψ Γ) (AReg v) True -> iseq_has_type (PsiCtx Ψ) (JMP R(v)) (code Γ)\n| S_Seq :  forall Ψ i1 i2 Γ Γ2,\n    ihas_type (PsiCtx Ψ) i1 (arrow Γ Γ2) -> iseq_has_type (PsiCtx Ψ) i2 (code Γ2) -> iseq_has_type (PsiCtx Ψ) (ISeq i1 i2) (code Γ).                                           Hint Constructors iseq_has_type.\n\n\n\nDefinition init_Gamma : context := update (update (update (update empty_Gamma (Id 1) (reg int)) (Id 2) (reg int)) (Id 3) (reg int)) (Id 4) True.\nCheck init_Gamma.\nHint Unfold init_Gamma.\n\nDefinition init_Psi : context := update (update (update empty_Psi (Id 1) (code init_Gamma))(Id 3) (code init_Gamma)) (Id 2) (code init_Gamma).\nHint Unfold init_Psi.\n\n\nLtac match_map := repeat (try rewrite update_neq; try rewrite update_eq; try reflexivity).\nLtac inequality := (rewrite <- beq_id_false_iff; trivial).\nLtac crush_map := match_map ; inequality; try reflexivity.\n\nLtac rewrite_hyp :=\n  match goal with\n  | [ H : ?n = _ |- context[?n] ] => rewrite H\n  end.\n\nLtac crush_generic :=\n  repeat match goal with\n         | [ H : ?T |- ?T    ] => exact T\n         | [ |- ?T = ?T ] => reflexivity\n         | [ |- True         ] => constructor\n         | [ |- _ /\\ _       ] => constructor\n         | [ |- _ /\\ _ -> _  ] => intro\n         | [ H : _ /\\ _ |- _ ] => destruct H\n         | [ |- nat -> _     ] => intro\n         | _ => rewrite_hyp || eauto || jauto\n         end.\n\nLtac crush :=\n  repeat (crush_generic; match goal with\n                         | [ |- update _ _ _ _ = _ ] => crush_map\n                         | [ |- init_Gamma _ = _ ] => unfold init_Gamma\n                         | [ |- init_Psi _ = _ ] => unfold init_Psi\n                         | [ |- ieval _ _ ] => constructor; auto\n                         | [ |- ihas_type _ _ _] => constructor; auto\n                         | [ |- ?T -> False  ]  => assert T\n                         | _ => try subst; trivial\n                         end).\n\n\n\nExample heap_2_type : forall I (R : registers), (init_heap (Id 2)) = Some I -> iseq_has_type (PsiCtx init_Psi) I (code init_Gamma).\nProof.\n  intros.\n  unfold init_heap in H.\n  rewrite update_neq in H.\n  rewrite update_eq in H.\n  symmetry in H.\n  inversion H.\n  apply S_Seq with (Γ2 := init_Gamma).\n  crush.\n  constructor; auto.\n  apply S_Lab with (l := 3) (R := R).\n  crush.\n  trivial.\n  apply S_Seq with (Γ2 := init_Gamma).\n  constructor; auto.\n  crush.\n  apply update_same.\n  crush.\n  apply S_Seq with (Γ2 := init_Gamma).\n  unfold init_Psi.\n  apply S_Sub with (a := ANum 1).\n  unfold init_Psi.\n  constructor; auto.\n  constructor; auto.\n  constructor; auto.\n  constructor; auto.\n  constructor; auto.\n  apply S_Lab with (l := 2) (R := R).\n  crush.\n  trivial.\n  trivial.\n  rewrite <- beq_id_false_iff.\n  trivial.\nQed.\n\n(** Typing rule for register file *)\nInductive Rhas_type : cmbnd_ctx -> registers -> context -> Prop :=\n| S_Regfile : forall Ψ Γ R r tau a,\n    (Γ (Id r)) = Some tau -> aeval a R = R (Id r) -> ahas_type (PsiGammaCtx Ψ Γ) a tau -> Rhas_type (PsiCtx Ψ) R Γ.\n\nHint Constructors Rhas_type.\n\n(** Typing rule for Heap *)\nInductive Hhas_type : cmbnd_ctx -> heaps -> context -> Prop :=\n| S_Heap : forall Ψ H,\n    (forall l tau, exists is, Ψ (Id l) = Some tau /\\ H (Id l) = Some is /\\ iseq_has_type (PsiCtx Ψ) is tau) -> Hhas_type EmptyCtx H Ψ.\n\nHint Constructors Hhas_type.\n\n(** Typing rule for a valid Machine State *)\nInductive M_ok : cmbnd_ctx -> heaps -> registers -> instr_seq -> Prop :=\n| S_Mach : forall H R Is Ψ Γ,\n    Hhas_type EmptyCtx H Ψ -> Rhas_type (PsiCtx Ψ) R Γ -> iseq_has_type (PsiCtx Ψ) Is (code Γ) -> M_ok EmptyCtx H R Is.\n\nHint Constructors M_ok.\n\n(** We will require some Canonical Values Lemmas in our proof of Soundness *)\nLemma Canonical_Values_Int : forall H Ψ Γ v tau,\n    Hhas_type EmptyCtx H Ψ -> ahas_type (PsiGammaCtx Ψ Γ) v tau -> tau = int -> exists n, v = ANum n.\nProof.\n  intros.\n  subst.\n  inversion H1.\n  inversion H6.\n  exists n.\n  crush.\nQed.\n\n\nLemma Canonical_Values_Reg :forall H Ψ Γ r R,\n    Hhas_type EmptyCtx H Ψ -> Rhas_type (PsiCtx Ψ) R Γ -> ahas_type (PsiGammaCtx Ψ Γ) (AReg r) (reg int) -> exists (n : nat), R (Id r) = n.\nProof.\n  intros.\n  exists (R (Id r)).\n  crush.\nQed.\n\nLemma Canonical_Values_label1 : forall H Ψ Γ v,\n    Hhas_type EmptyCtx H Ψ -> ahas_type (PsiGammaCtx Ψ Γ) (ALab v) (code Γ) ->  Ψ (Id v) = Some (code Γ) -> exists is, H (Id v) = Some is /\\ iseq_has_type (PsiCtx Ψ) is (code Γ).\nProof.\n  intros.\n  inversion H0.\n  inversion H1.\n  inversion H7.\n  simpl in H5.\n  specialize H4 with ( l := v) (tau := code Γ).\n  destruct H4 as [i G].\n  exists i.\n  crush.\nQed.\n\nLemma Canonical_Values_label2 : forall H Ψ Γ R r,\n    Hhas_type EmptyCtx H Ψ -> ahas_type (PsiGammaCtx Ψ Γ) (AReg r) True -> exists is, H (Id (R (Id r))) = Some is /\\ iseq_has_type (PsiCtx Ψ) is (code Γ).\nProof.\n  intros.\n  inversion H0.\n  inversion H1.\n  specialize H3 with ( l := R (Id r)) (tau := (code Γ)).\n  destruct H3 as [i G].\n  exists i.\n  apply G.\n  specialize H3 with ( l := R (Id r)) (tau := (code Γ)).\n  destruct H3 as [i G].\n  exists i.\n  crush.\nQed.\n\n(** Finally the proof of Soundness *)\nTheorem Soundness : forall H R Is,\n    M_ok EmptyCtx H R Is -> exists H' R' Is', ieval (St H R Is) (St H' R' Is') /\\ M_ok EmptyCtx H' R' Is'.\nProof.\n  intros.\n  inversion H0 ; induction Is; inverts H4.\n  induction i; inversion H12;\n    try match goal with\n        | [H : Γ = Γ2 |- _ ] => symmetry in H\n        end;\n    try subst.\n\n\n  (* ISeq IMov I *)\n  exists H (t_update R (Id d) (aeval a R1)) Is.\n  crush.\n  apply S_Mach with (Ψ := Ψ) (Γ := Γ).\n  crush.\n  apply S_Regfile with (r := d) (tau := reg tau) (a := AReg d).\n  rewrite <- H16.\n  rewrite update_eq.\n  crush.\n  crush.\n  crush.\n  crush.\n  \n  (* ISeq IAdd I *)\n  exists H (t_update R (Id d) (aeval (AReg d) R + aeval (AReg s) R)) Is.\n  split.\n  crush.\n  apply S_Mach with (Ψ := Ψ) (Γ := Γ).\n  crush.\n  apply S_Regfile with (a := AReg d) (r := d) (tau := reg int).\n  rewrite <- H16; apply update_eq.\n  crush.\n  crush.\n  crush.\n  \n  (* ISeq ISub I *)\n  exists H (t_update R (Id d) (aeval (AReg d) R - aeval (ANum v) R)) Is.\n  split.\n  crush.\n  apply S_Mach with (Ψ := Ψ) (Γ := Γ).\n  crush.\n  apply S_Regfile with (a := AReg d) (r := d) (tau := reg int).\n  inversion H15.\n  crush.\n  crush.\n  inversion H15.\n  crush.\n  inversion H7.\n  trivial.\n  crush.\n  crush.\n  \n  (* ISeq IIf I *)\n  inversion H12.\n  inversion H9.\n  inversion H18.\n  subst.\n  simpl in H22.\n  \n  remember (R (Id d)) as rd; destruct rd.\n  pose proof Canonical_Values_label1 H Ψ Γ v0 H2 H9 H22 as CVL1.\n  destruct CVL1 as [Is' G].\n  exists H R Is'.\n  crush.\n\n  exists H R Is.\n  \n  split.\n  apply R_IIf_NEQ.\n  simpl.\n  symmetry in Heqrd; rewrite Heqrd.\n  apply beq_nat_false_iff.\n  trivial.\n  crush.\n  \n  (*IJmp*)\n  inversion H11; inversion H12.\n  simpl in H17.\n  subst.\n  pose proof Canonical_Values_label1 H Ψ Γ v0 H2 H11 H16 as CVL1.\n  destruct CVL1 as [Is G].\n\n  exists H R Is.\n  crush.\n  apply R_IJmp_Succ with (a := ALab v0).\n  crush.\n  crush.\n  \n  (*IJmpT*)\n  pose proof Canonical_Values_label2 H Ψ Γ R v0 H2 H11 as CVL3.\n  destruct CVL3 as [Is G].\n\n  exists H R Is.\n  crush.\nQed.\n", "meta": {"author": "ankitku", "repo": "awotap", "sha": "1354a1f0e2f77c0157398553e666b6ff0be6d1ee", "save_path": "github-repos/coq/ankitku-awotap", "path": "github-repos/coq/ankitku-awotap/awotap-1354a1f0e2f77c0157398553e666b6ff0be6d1ee/TAL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6544984110623752}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Shallow.Imp Shallow.Embeddings.\n\nInductive aexp : Type :=\n  | ANum (n : Z)\n  | AId (X : var)\n  | APlus (a1 a2 : aexp)\n  | AMinus (a1 a2 : aexp)\n  | AMult (a1 a2 : aexp)\n  | ADiv (a1 a2 : aexp).\n\nModule OptF.\n\nDefinition add {A : Type} (f g : A -> option Z) : A -> option Z :=\n  fun st =>\n    match f st, g st with\n      | Some v1, Some v2 => Some (v1 + v2)\n      | _, _ => None\n    end.\n\nDefinition sub {A : Type} (f g : A -> option Z) : A -> option Z :=\n  fun st =>\n    match f st, g st with\n      | Some v1, Some v2 => Some (v1 - v2)\n      | _, _ => None\n    end.\n\nDefinition mul {A : Type} (f g : A -> option Z) : A -> option Z :=\n  fun st =>\n    match f st, g st with\n      | Some v1, Some v2 => Some (v1 * v2)\n      | _, _ => None\n    end.\n\nDefinition div {A : Type} (f g : A -> option Z) : A -> option Z :=\n  fun st =>\n    match f st, g st with\n      | Some v1, Some v2 =>\n          if Z.eq_dec v2 0 then None else Some (v1 / v2)\n      | _, _ => None\n    end.\n\nEnd OptF.\n\nModule Denote_Aexp.\n\nFixpoint aeval (a : aexp) : state -> option Z :=\n  match a with\n    | ANum n => fun _ => Some n\n    | AId X => fun st => Some (st X)\n    | APlus a1 a2 => OptF.add (aeval a1) (aeval a2)\n    | AMinus a1 a2 => OptF.sub (aeval a1) (aeval a2)\n    | AMult a1 a2 => OptF.mul (aeval a1) (aeval a2)\n    | ADiv a1 a2 => OptF.div (aeval a1) (aeval a2)\n  end.\n\nEnd Denote_Aexp.\n\nInductive bexp : Type :=\n  | BTrue\n  | BFalse\n  | BEq (a1 a2 : aexp)\n  | BLe (a1 a2 : aexp)\n  | BNot (b : bexp)\n  | BAnd (b1 b2 : bexp).\n\nRecord bexp_denote : Type := {\n  true_set : state -> Prop;\n  false_set : state -> Prop;\n  error_set : state -> Prop; }.\n\nDefinition opt_test (R: Z -> Z -> Prop) (X Y: state -> option Z): bexp_denote :=\n  {|\n    true_set := fun st =>\n      match X st, Y st with\n        | Some n1, Some n2 => R n1 n2\n        | _, _ => False\n      end;\n    false_set := fun st =>\n      match X st, Y st with\n        | Some n1, Some n2 => ~R n1 n2\n        | _, _ => False\n      end;\n    error_set := fun st =>\n      match X st, Y st with\n        | Some n1, Some n2 => False\n        | _, _ => True\n      end;\n  |}.\n\nModule Sets.\n\nDefinition union {A : Type} (X Y : A -> Prop) : A -> Prop :=\n  fun a => X a \\/ Y a.\n\nDefinition omega_union {A} (X : nat -> A -> Prop) : A -> Prop :=\n  fun a => exists n, X n a.\n\nEnd Sets.\n\nModule Denote_Bexp.\nImport Denote_Aexp.\n\nFixpoint beval (b : bexp) : bexp_denote :=\n  match b with\n  | BTrue =>\n      {| true_set := Sets.full;\n         false_set := Sets.empty;\n         error_set := Sets.empty; |}\n  | BFalse =>\n      {| true_set := Sets.empty;\n         false_set := Sets.full;\n         error_set := Sets.empty; |}\n  | BEq a1 a2 => \n      opt_test Z.eq (aeval a1) (aeval a2)\n  | BLe a1 a2 =>\n      opt_test Z.le (aeval a1) (aeval a2)\n  | BNot b =>\n      {| true_set := false_set (beval b);\n         false_set := true_set (beval b);\n         error_set := error_set (beval b); |}\n  | BAnd b1 b2 =>\n      {| true_set := Sets.intersect (true_set (beval b1)) (true_set (beval b2));\n         false_set := Sets.union (false_set (beval b1))\n                                 (Sets.intersect (true_set (beval b1))\n                                                 (false_set (beval b2)));\n         error_set := Sets.union (error_set (beval b1))\n                                 (Sets.intersect (true_set (beval b1))\n                                                 (error_set (beval b2))); |}\n  end.\n\nEnd Denote_Bexp.\n\nInductive com : Type :=\n  | CSkip\n  | CAss (X : var) (a : aexp)\n  | CSeq (c1 c2 : com)\n  | CIf (b : bexp) (c1 c2 : com)\n  | CFor (c1 c2 : com)\n  | CBreak\n  | CCont.\n\nRecord com_denote : Type := {\n  com_normal : state -> state -> Prop;\n  com_break : state -> state -> Prop;\n  com_cont : state -> state -> Prop;\n  com_error : state -> Prop }.\n\nModule Denote_Com.\nImport Denote_Aexp.\nImport Denote_Bexp.\n\nDefinition skip_sem : com_denote := {|\n  com_normal := fun st1 st2 => st1 = st2;\n  com_break := fun st1 st2 => False;\n  com_cont := fun st1 st2 => False;\n  com_error := fun st => False; |}.\n\nDefinition asgn_sem (X : var) (DA : state -> option Z) : com_denote := {|\n  com_normal := fun st1 st2 => (Some (st2 X) = DA st1) /\\ (forall Y, Y <> X -> st2 Y = st1 Y);\n  com_break := fun st1 st2 => False;\n  com_cont := fun st1 st2 => False;\n  com_error := fun st => DA st = None; |}.\n\nDefinition seq_sem (DC1 DC2 : com_denote) : com_denote := {|\n  com_normal := fun st1 st2 =>\n    exists st3, com_normal DC1 st1 st3 /\\ com_normal DC2 st3 st2;\n  com_break := fun st1 st2 =>\n    (com_break DC1 st1 st2) \\/\n    (exists st3, com_normal DC1 st1 st3 /\\ com_break DC2 st3 st2);\n  com_cont := fun st1 st2 =>\n    (com_cont DC1 st1 st2) \\/\n    (exists st3, com_normal DC1 st1 st3 /\\ com_cont DC2 st3 st2);\n  com_error := fun st =>\n    (com_error DC1 st) \\/ (exists st', com_normal DC1 st st' /\\ com_error DC2 st'); |}.\n\nDefinition if_sem (DB : bexp_denote) (DC1 DC2 : com_denote) : com_denote := {|\n  com_normal := fun st1 st2 =>\n    (true_set DB st1 /\\ com_normal DC1 st1 st2) \\/\n    (false_set DB st1 /\\ com_normal DC2 st1 st2);\n  com_break := fun st1 st2 =>\n    (true_set DB st1 /\\ com_break DC1 st1 st2) \\/\n    (false_set DB st1 /\\ com_break DC2 st1 st2);\n  com_cont := fun st1 st2 =>\n    (true_set DB st1 /\\ com_cont DC1 st1 st2) \\/\n    (false_set DB st1 /\\ com_cont DC2 st1 st2);\n  com_error := fun st =>\n    (error_set DB st) \\/\n    (true_set DB st /\\ com_error DC1 st) \\/\n    (false_set DB st /\\ com_error DC2 st) |}.\n\nFixpoint iter_loop_body (DC1 DC2 : com_denote) (n : nat) : com_denote :=\n  match n with\n  | O => {|\n      com_normal := fun st1 st2 =>\n        (com_break DC1 st1 st2) \\/\n        (exists st3, com_normal DC1 st1 st3 /\\ com_break DC2 st3 st2);\n      com_break := fun st1 st2 => False;\n      com_cont := fun st1 st2 => False;\n      com_error := fun st =>\n        (com_error DC1 st) \\/\n        (exists st', com_normal DC1 st st' /\\ com_error DC2 st') |}\n  | S n' => {|\n      com_normal := fun st1 st2 => exists st3,\n        ((com_normal (seq_sem DC1 DC2) st1 st3) \\/ (com_cont (seq_sem DC1 DC2) st1 st3)) /\\\n        (com_normal (iter_loop_body DC1 DC2 n') st3 st2);\n      com_break := fun st1 st2 => False;\n      com_cont := fun st1 st2 => False;\n      com_error := fun st => exists st',\n        ((com_normal (seq_sem DC1 DC2) st st') \\/ (com_cont (seq_sem DC1 DC2) st st')) /\\\n        (com_error (iter_loop_body DC1 DC2 n') st') |}\n  end.\n\nDefinition for_sem (DC1 DC2 : com_denote) : com_denote := {|\n  com_normal := fun st1 st2 =>\n    exists n, com_normal (iter_loop_body DC1 DC2 n) st1 st2;\n  com_break := fun st1 st2 => False;\n  com_cont := fun st1 st2 => False;\n  com_error := fun st =>\n    exists n, com_error (iter_loop_body DC1 DC2 n) st |}.\n\nDefinition break_sem : com_denote := {|\n  com_normal := fun st1 st2 => False;\n  com_break := fun st1 st2 => st1 = st2;\n  com_cont := fun st1 st2 => False;\n  com_error := fun st => False |}.\n\nDefinition cont_sem : com_denote := {|\n  com_normal := fun st1 st2 => False;\n  com_break := fun st1 st2 => False;\n  com_cont := fun st1 st2 => st1 = st2;\n  com_error := fun st => False |}.\n\nFixpoint ceval (c : com) : com_denote :=\n  match c with \n  | CSkip => skip_sem\n  | CAss X a => asgn_sem X (aeval a)\n  | CSeq c1 c2 => seq_sem (ceval c1) (ceval c2)\n  | CIf b c1 c2 => if_sem (beval b) (ceval c1) (ceval c2)\n  | CFor c1 c2 => for_sem (ceval c1) (ceval c2)\n  | CBreak => break_sem\n  | CCont => cont_sem\n  end.\n\nEnd Denote_Com.\n\nModule Assertion_Shallow.\nImport Denote_Aexp.\nImport Denote_Bexp.\n  \nDefinition Assertion : Type := state -> Prop.\n\nDefinition Assertion_denote : state -> Assertion -> Prop :=\n  fun st P => P st.\n\nDefinition andp : Assertion -> Assertion -> Assertion :=\n  fun P Q st => P st /\\ Q st. \n\nDefinition orp : Assertion -> Assertion -> Assertion :=\n  fun P Q st => P st \\/ Q st.\n\nDefinition negp : Assertion -> Assertion :=\n  fun P st => ~ P st.\n\nDefinition falsep : Assertion :=\n  fun st => False.\n\nDefinition inj : bexp -> Assertion :=\n  fun b st => true_set (beval b) st.\n\nDefinition safea : aexp -> Assertion :=\n  fun a st => ~ (aeval a) st = None.\n\nDefinition safeb : bexp -> Assertion :=\n  fun b st => ~ error_set (beval b) st. \n\nDefinition derives : Assertion -> Assertion -> Prop :=\n  fun P Q => forall st, P st -> Q st.\n\nDefinition state_update (st : state) (X : var) (v : option Z) : state :=\n  match v with\n  | Some n => fun Y => if (Nat.eq_dec X Y) then n else st Y\n  | None => fun Y => 0\n  end.\n  \nDefinition subst_assertion (P : Assertion) (X : var) (v : state -> option Z) : Assertion :=\n  fun st => P (state_update st X (v st)).\n\nEnd Assertion_Shallow.\n\nModule Denote_Embeddings.\nImport Denote_Com.\nImport Assertion_Shallow.\n\nDefinition com_term : com_denote -> state -> state -> Prop :=\n  fun DC st1 st2 =>\n    (com_normal DC st1 st2) \\/ (com_break DC st1 st2) \\/ (com_cont DC st1 st2).\n\nDefinition partial_valid (P : Assertion) (c : com) (Q R1 R2 : Assertion) : Prop :=\n  forall st1 st2, Assertion_denote st1 P ->\n    (~ com_error (ceval c) st1) /\\\n    ((com_normal (ceval c) st1 st2) -> Assertion_denote st2 Q) /\\\n    ((com_break (ceval c) st1 st2) -> Assertion_denote st2 R1) /\\\n    ((com_cont (ceval c) st1 st2) -> Assertion_denote st2 R2).\n\nDefinition total_valid (P : Assertion) (c : com) (Q R1 R2 : Assertion) : Prop :=\n  (forall st1, Assertion_denote st1 P -> exists st2, com_term (ceval c) st1 st2) /\\\n  (partial_valid P c Q R1 R2).\n\nEnd Denote_Embeddings.\n\nModule rules_sound.\nImport Denote_Com.\nImport Denote_Embeddings.\nImport Assertion_Shallow.\n\nDefinition WP (c : com) (Q R1 R2 : Assertion) : state -> Prop :=\n  fun st =>\n    (~ (com_error (ceval c) st)) /\\\n    (forall st',\n      (com_normal (ceval c) st st' -> Assertion_denote st' Q) /\\\n      (com_break (ceval c) st st' -> Assertion_denote st' R1) /\\\n      (com_cont (ceval c) st st' -> Assertion_denote st' R2)).\n\nTheorem seq_inv_sound_bigstep : forall P c1 c2 Q R1 R2,\n  partial_valid P (CSeq c1 c2) Q R1 R2 ->\n    (exists Q', partial_valid P c1 Q' R1 R2 /\\ partial_valid Q' c2 Q R1 R2).\nProof.\n  intros.\n  exists (WP c2 Q R1 R2).\n  remember (WP c2 Q R1 R2) as Q'.\n  split.\n  + (* partial_valid P c1 Q' R1 R2 *)\n    unfold partial_valid in *.\n    intros.\n    split; try split; try split; intros.\n    - specialize (H st1 st2 H0).\n      destruct H as [HE [HN [HB HC]]].\n      simpl in HE.\n      unfold not in *; intros; apply HE; tauto.\n    - subst Q'; unfold WP, Assertion_denote in *.\n      split.\n      { specialize (H st1 st2 H0).\n        destruct H as [HE [HN [HB HC]]].\n        unfold not in *.\n        intros; apply HE. \n        simpl; right; exists st2; tauto. }\n      intros st3.\n      specialize (H st1 st3 H0).\n      destruct H as [HE [HN [HB HC]]].\n      split; try split; intros; \n        [apply HN | apply HB | apply HC]; simpl;\n        [ | right | right]; exists st2; tauto.\n    - specialize (H st1 st2 H0).\n      destruct H as [HE [HN [HB HC]]].\n      apply HB; simpl; tauto.\n    - specialize (H st1 st2 H0).\n      destruct H as [HE [HN [HB HC]]].\n      apply HC; simpl; tauto.\n  + unfold partial_valid; subst Q'; unfold WP, Assertion_denote.\n    intros.\n    destruct H0 as [HE ?].\n    specialize (H0 st2); tauto.\nQed.\n\nTheorem if_seq_sound_bigstep : forall P b c1 c2 c3 Q R1 R2,\n  partial_valid P (CIf b (CSeq c1 c3) (CSeq c2 c3)) Q R1 R2 ->\n  partial_valid P (CSeq (CIf b c1 c2) c3) Q R1 R2.\nProof.\n  intros.\n  unfold partial_valid in *.\n  intros.\n  specialize (H st1 st2 H0).\n  destruct H as [HE [HN [HB HC]]].\n  split; [| split;[| split]].\n  + unfold not in *; intros; apply HE.\n    simpl in H; simpl.\n    destruct H; try tauto.\n    destruct H as [st3 [? ?]].\n    right; destruct H; [left | right]; split; try tauto;\n      right; exists st3; try tauto.\n  + intros; apply HN.\n    simpl in H; simpl.\n    destruct H as [st3 [[? | ?] ?]]; [left | right];\n      split; try tauto; exists st3; tauto.\n  + intros; apply HB.\n    simpl in H; simpl.\n    destruct H; try tauto.\n    destruct H as [st3 [[? | ?] ?]]; [left | right];\n      split; try tauto; right; exists st3; tauto.\n  + intros; apply HC.\n    simpl in H; simpl.\n    destruct H; try tauto.\n    destruct H as [st3 [[? | ?] ?]]; [left | right];\n      split; try tauto; right; exists st3; tauto.\nQed.\n\nFixpoint nocontinue (c : com) : Prop :=\n  match c with\n  | CSkip         => True\n  | CAss _ _      => True\n  | CSeq c1 c2    => (nocontinue c1) /\\ (nocontinue c2)\n  | CIf b c1 c2   => (nocontinue c1) /\\ (nocontinue c2)\n  | CFor c1 c2    => True\n  | CBreak        => True \n  | CCont         => False\n  end.\n\nLemma nocontinue_nocontexit : forall (c : com) st1,\n  nocontinue c ->\n  ~(exists st2, com_cont (ceval c) st1 st2).\nProof.\n  intros; revert st1.\n  induction c; unfold not; intros; destruct H0 as [st2 ?].\n  + inversion H0.\n  + inversion H0.\n  + simpl in H; destruct H as [Hc1 Hc2].\n    unfold not in *.\n    simpl in H0; destruct H0.\n    - specialize (IHc1 Hc1 st1).\n      apply IHc1; exists st2; tauto.\n    - destruct H as [st3 ?].\n      specialize (IHc2 Hc2 st3).\n      apply IHc2; exists st2; tauto.\n  + simpl in H0; simpl in H; destruct H as [Hc1 Hc2]; destruct H0.\n    - specialize (IHc1 Hc1 st1).\n      unfold not in IHc1; apply IHc1.\n      exists st2; tauto.\n    - specialize (IHc2 Hc2 st1).\n      unfold not in IHc2; apply IHc2.\n      exists st2; tauto.\n  + simpl in H0; tauto.\n  + simpl in H0; tauto.\n  + simpl in H; tauto.\nQed.  \n\nTheorem nocontinue_sound_bigstep : forall P c Q R1 R2 R2',\n  nocontinue c ->\n  partial_valid P c Q R1 R2 ->\n  partial_valid P c Q R1 R2'.\nProof.\n  intros.\n  unfold partial_valid in *.\n  intros.\n  specialize (H0 st1 st2 H1).\n  split; [tauto | split; [tauto | split; try tauto]].\n  clear H0; intros.\n  pose proof (nocontinue_nocontexit c st1 H).\n  exfalso; unfold not in H2; apply H2.\n  exists st2; tauto.\nQed.\n\nLemma loop_nocontinue_error : forall c1 c2 st1,\n  com_error (ceval (CFor c1 c2)) st1 ->\n  com_error (ceval (CFor (CSeq c1 c2) CSkip)) st1.\nProof.\n  intros.\n  simpl in *.\n  destruct H as [n ?]; exists n.\n  revert st1 H; induction n; intros.\n  + simpl in *.\n    destruct H; try tauto.\n  + simpl in *.\n    destruct H as [st2 [? ?]].\n    exists st2; split.\n    2:{ pose proof (IHn st2 H0); tauto. }\n    destruct H.\n    - destruct H as [st3 [? ?]].\n      left. exists st2; split; try tauto.\n      exists st3; tauto.\n    - destruct H as [? | [st3 [? ?]]]; try tauto.\n      right. left. right. exists st3; tauto.\nQed.\n\nLemma loop_nocontinue_normal : forall c1 c2 st1 st2,\n  com_normal (ceval (CFor c1 c2)) st1 st2 ->\n  com_normal (ceval (CFor (CSeq c1 c2) CSkip)) st1 st2.\nProof.\n  intros.\n  simpl in *.\n  destruct H as [n ?]; exists n.\n  revert st1 st2 H; induction n; intros.\n  + simpl in *.\n    destruct H; try tauto.\n  + simpl in *.\n    destruct H as [st3 [? ?]].\n    exists st3; split.\n    2:{ pose proof (IHn st3 st2 H0); tauto. }\n    destruct H.\n    - destruct H as [st4 ?].\n      left. exists st3; split; try tauto; exists st4; tauto.\n    - destruct H as [? | [st4 ?]]; try tauto.\n      right. left. right. exists st4; tauto.\nQed.\n\nTheorem loop_nocontinue_sound_bigstep : forall P c1 c2 Q R1 R2,\n  nocontinue c1 ->\n  nocontinue c2 ->\n  partial_valid P (CFor (CSeq c1 c2) CSkip) Q R1 R2 ->\n  partial_valid P (CFor c1 c2) Q R1 R2.\nProof.\n  intros.\n  unfold partial_valid in *.\n  intros.\n  specialize (H1 st1 st2 H2).\n  destruct H1 as [HE [HN [HB HC]]].\n  split; try split; try split.\n  + unfold not in *; intros; apply HE.\n    pose proof (loop_nocontinue_error c1 c2 st1); tauto.\n  + intros; apply HN.\n    pose proof (loop_nocontinue_normal c1 c2 st1 st2); tauto.\n  + intros.\n    simpl in H1. tauto.\n  + intros.\n    simpl in H1. tauto.\nQed.\n\nEnd rules_sound.\n\nModule basic_rules.\nImport Denote_Aexp.\nImport Denote_Bexp.\nImport Denote_Com.\nImport Denote_Embeddings.\nImport Assertion_Shallow.\n\nTheorem hoare_seq_sound : forall P Q R R1 R2 c1 c2,\n  partial_valid P c1 Q R1 R2 ->\n  partial_valid Q c2 R R1 R2 ->\n  partial_valid P (CSeq c1 c2) R R1 R2.\nProof.\n  intros.\n  unfold partial_valid in *.\n  intros.\n  split; try split; try split.\n  + unfold not; intros.\n    simpl in H2.\n    destruct H2.\n    - specialize (H st1 st2 H1); tauto.\n    - destruct H2 as  [st3 [? ?]].\n      specialize (H st1 st3 H1).\n      assert (Assertion_denote st3 Q). { tauto. }\n      specialize (H0 st3 st2 H4); tauto.\n  + intros.\n    simpl in H2.\n    destruct H2 as [st3 [? ?]].\n    specialize (H st1 st3 H1).\n    assert (Assertion_denote st3 Q). { tauto. }\n    specialize (H0 st3 st2 H4). tauto.\n  + intros.\n    simpl in H2.\n    destruct H2.\n    - specialize (H st1 st2 H1); tauto.\n    - destruct H2 as [st3 [? ?]].\n      specialize (H st1 st3 H1).\n      assert (Assertion_denote st3 Q). { tauto. }\n      specialize (H0 st3 st2 H4). tauto.\n  + intros.\n    simpl in H2.\n    destruct H2.\n    - specialize (H st1 st2 H1); tauto.\n    - destruct H2 as [st3 [? ?]].\n      specialize (H st1 st3 H1).\n      assert (Assertion_denote st3 Q). { tauto. }\n      specialize (H0 st3 st2 H4). tauto.\nQed.\n\nTheorem hoare_skip_sound : forall P, \n  partial_valid P CSkip P falsep falsep.\nProof.\n  intros.\n  unfold partial_valid.\n  intros.\n  split; try split; try split.\n  + unfold not; intros. inversion H0.\n  + intros. simpl in H0; subst; tauto.\n  + intros. inversion H0.\n  + intros. inversion H0.\nQed.\n\nLemma true_notfalse : forall b st,\n  true_set (beval b) st ->\n  false_set (beval b) st -> False.\nProof.\n  induction b; intros.\n  + inversion H0.\n  + inversion H.\n  + simpl in *.\n    destruct (aeval a1 st), (aeval a2 st); tauto. \n  + simpl in *.\n    destruct (aeval a1 st), (aeval a2 st); tauto.\n  + simpl in *. apply (IHb st); tauto.\n  + simpl in *. \n    unfold Sets.intersect, Sets.union in *.\n    specialize (IHb1 st); specialize (IHb2 st); tauto.\nQed.\n\nTheorem hoare_if_sound : forall P Q R1 R2 b c1 c2,\n  partial_valid (andp P (inj b)) c1 Q R1 R2 ->\n  partial_valid (andp P (negp (inj b))) c2 Q R1 R2 ->\n  partial_valid (andp P (safeb b)) (CIf b c1 c2) Q R1 R2.\nProof.\n  unfold partial_valid in *.\n  intros.\n  unfold safeb, andp, inj, negp, Assertion_denote in *.\n  split; try split; try split.\n  + simpl. unfold not; intros.\n    destruct H2 as [? | [? | ?]].\n    - tauto.\n    - specialize (H st1 st2); tauto.\n    - specialize (H0 st1 st2).\n      destruct H2.\n      assert (~ true_set (beval b) st1).\n      { unfold not; intros. apply (true_notfalse b st1); tauto. }\n      tauto.\n  + simpl; intros.\n    destruct H2.\n    - specialize (H st1 st2). tauto.\n    - specialize (H0 st1 st2).\n      assert (~ true_set (beval b) st1).\n      { unfold not; intros. apply (true_notfalse b st1); tauto. }\n      tauto.\n  + simpl; intros.\n    destruct H2.\n    - specialize (H st1 st2). tauto.\n    - specialize (H0 st1 st2).\n      assert (~ true_set (beval b) st1).\n      { unfold not; intros. apply (true_notfalse b st1); tauto. }\n      tauto.\n    + simpl; intros.\n    destruct H2.\n    - specialize (H st1 st2). tauto.\n    - specialize (H0 st1 st2).\n      assert (~ true_set (beval b) st1).\n      { unfold not; intros. apply (true_notfalse b st1); tauto. }\n      tauto.\nQed.\n\nTheorem hoare_break_sound : forall P,\n  partial_valid P CBreak falsep P falsep.\nProof.\n  unfold partial_valid.\n  intros.\n  split; try split; try split.\n  + unfold not; intros. inversion H0.\n  + intros. inversion H0.\n  + intros. inversion H0. subst. tauto.\n  + intros. inversion H0.\nQed.\n\nTheorem hoare_cont_sound : forall P,\n  partial_valid P CCont falsep falsep P.\nProof.\n  unfold partial_valid.\n  intros.\n  split; try split; try split.\n  + unfold not; intros. inversion H0.\n  + intros. inversion H0.\n  + intros. inversion H0.\n  + intros. inversion H0. subst. tauto.\nQed.\n\nTheorem hoare_consequence_sound : forall P P' Q Q' R1 R1' R2 R2' c,\n  derives P P' ->\n  partial_valid P' c Q' R1' R2' ->\n  derives Q' Q ->\n  derives R1' R1 ->\n  derives R2' R2 ->\n  partial_valid P c Q R1 R2.\nProof.\n  unfold derives, partial_valid, Assertion_denote in *.\n  intros.\n  specialize (H st1).\n  specialize (H0 st1 st2).\n  specialize (H1 st2).\n  specialize (H2 st2).\n  specialize (H3 st2).\n  split; try split; try split; tauto.\nQed.\n\nTheorem hoare_for_sound : forall I P c1 c2,\n  partial_valid I (CSeq c1 c2) I P I ->\n  partial_valid I (CFor c1 c2) (orp I P) falsep falsep.\nProof.\n  unfold partial_valid, orp, falsep, Assertion_denote.\n  intros.\n  split; try split; try split; try tauto.\n  + unfold not; intros.\n    simpl in H1.\n    destruct H1 as [n ?].\n    revert st1 H1 H0; induction n; intros.\n    - simpl in H1.\n      specialize (H st1 st2 H0); destruct H.\n      simpl in H. tauto.\n    - simpl in H1.\n      destruct H1 as [st3 [? ?]].\n      specialize (IHn st3); apply IHn; try tauto.\n      clear IHn H2.\n      destruct H1 as [? | [? | ?]].\n      * destruct H1 as [st4 [? ?]].\n        specialize (H st1 st3 H0).\n        assert (com_normal (ceval (CSeq c1 c2)) st1 st3).\n        { simpl. exists st4; tauto. }\n        tauto.\n      * specialize (H st1 st3 H0).\n        assert (com_cont (ceval (CSeq c1 c2)) st1 st3).\n        { simpl. tauto. }\n        tauto.\n      * specialize (H st1 st3 H0).\n        destruct H1 as [st4 [? ?]].\n        assert (com_cont (ceval (CSeq c1 c2)) st1 st3).\n        { simpl. right. exists st4; tauto. }\n        tauto.\n  + intros.\n    simpl in H1.\n    destruct H1 as [n ?].\n    revert st1 st2 H0 H1; induction n; intros.\n    - simpl in H1.\n      destruct H1.\n      * specialize (H st1 st2).\n        assert (com_break (ceval (CSeq c1 c2)) st1 st2).\n        { simpl. tauto. }\n        tauto.\n      * specialize (H st1 st2).\n        assert (com_break (ceval (CSeq c1 c2)) st1 st2).\n        { simpl. tauto. }\n        tauto.\n    - simpl in H1.\n      destruct H1 as [st3 [? ?]].\n      specialize (IHn st3 st2); apply IHn; try tauto.\n      clear IHn H2.\n      destruct H1 as [? | [? | ?]].\n      * specialize (H st1 st3); tauto.\n      * specialize (H st1 st3).\n        assert (com_cont (ceval (CSeq c1 c2)) st1 st3).\n        { simpl. tauto. }\n        tauto.\n      * specialize (H st1 st3).\n        assert (com_cont (ceval (CSeq c1 c2)) st1 st3).\n        { simpl. tauto. }\n        tauto.\nQed.\n\nTheorem hoare_asgn_sound : forall P (X : var) (E : aexp),\n  partial_valid (andp (safea E) (subst_assertion P X (aeval E))) (CAss X E) P falsep falsep.\nProof.\n  unfold partial_valid.\n  intros.\n  unfold Assertion_denote, andp, safea, subst_assertion in *.\n  split; try split; try split.\n  + unfold not; intros.\n    simpl in *; tauto.\n  + intros; simpl in *.\n    destruct H, H0.\n    remember (state_update st1 X (aeval E st1)) as st2'.\n    assert (forall X, st2 X = st2' X).\n    { intros.\n      subst st2'.\n      destruct (aeval E st1); try tauto.\n      unfold state_update.\n      destruct (Nat.eq_dec X X0).\n      - subst. inversion H0. tauto.\n      - specialize (H2 X0); auto. }\n    assert (st2 = state_update st1 X (aeval E st1)).\n    { eapply FunctionalExtensionality.functional_extensionality_dep.\n      subst. tauto. }\n    subst; tauto.\n  + intros; simpl in *; tauto.\n  + intros; simpl in *; tauto.\nQed.\n\nEnd basic_rules.", "meta": {"author": "TaoYC0904", "repo": "ExtendedProofRules", "sha": "6bdb28b03e4a6427ae82b0855c27e77c5a2e7308", "save_path": "github-repos/coq/TaoYC0904-ExtendedProofRules", "path": "github-repos/coq/TaoYC0904-ExtendedProofRules/ExtendedProofRules-6bdb28b03e4a6427ae82b0855c27e77c5a2e7308/BigStep_NonDet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6544983962307772}}
{"text": "Definition tautology : forall P : Prop, P -> P\n  := fun P p => p.\n\nDefinition Modus_tollens : forall P Q : Prop, ~Q /\\ (P -> Q) -> ~P\n  := fun P Q H p => let (nQ, p_q) := H in nQ (p_q p).\n \nDefinition Disjunctive_syllogism : forall P Q : Prop, (P \\/ Q) -> ~P -> Q\n  := fun P Q p_or_q n_p =>\n  match p_or_q with\n  | or_introl p => False_ind Q (n_p p)\n  | or_intror q => q\n  end.\n\nDefinition tautology_on_Set : forall A : Set, A -> A\n  := fun A p => p.\n\nDefinition Modus_tollens_on_Set : forall A B : Set, (B -> Empty_set) * (A -> B) -> (A -> Empty_set)\n  := fun A B H a => let (b_emp, a_b) := H in b_emp (a_b a).\n\nDefinition Disjunctive_syllogism_on_Set : forall A B : Set, (A + B) -> (A -> Empty_set) -> B\n  := fun A B in_a_b a_emp =>\n  match in_a_b with\n  | inl a => Empty_set_rec (fun _ : Empty_set => B) (a_emp a)\n  | inr b => b\n  end.\n\n", "meta": {"author": "spinylobster", "repo": "Coqex2014", "sha": "090f49c87abead6ea0b1c1a346817523efb777b0", "save_path": "github-repos/coq/spinylobster-Coqex2014", "path": "github-repos/coq/spinylobster-Coqex2014/Coqex2014-090f49c87abead6ea0b1c1a346817523efb777b0/第4回/16.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6544524400752191}}
{"text": "(***********************************************************)\n(*      This file contains the abstract term structure for *)\n(*      the Fourier-Motzkin procedure                      *)\n(***********************************************************)\n\nRequire Import ZArith.\n\nOpen Scope Z_scope.\n\nStructure Fmodule: Type := {\n   T: Type;\n   injT: Z -> T;         (* injection of Z *)\n   scalT: Z -> T -> T;   (* scalar multiplication *)\n   opT: T -> T;          (* opposite *)\n   plusT: T -> T -> T;   (* addition *)\n   minusT: T -> T -> T;  (* subtraction *)\n   leT: T -> T -> Prop;  (* comparison *)\n   ltT: T -> T -> Prop   (* strict comparison *)\n}.\n\nSection Init.\n\nVariable FT : Fmodule.\n\n(* Unusal notation *)\nDeclare Scope F_scope.\nNotation \"x + y\" := (plusT FT x y) : F_scope.\nNotation \"x - y\" := (minusT FT x y) : F_scope.\nNotation \"x * y\" := (scalT FT x y) : F_scope.\nNotation \"x <= y\" := (leT FT x y) : F_scope.\nNotation \"x < y\" := (ltT FT x y) : F_scope.\n\nLet injT1: Z -> (T FT) := (injT FT).\nCoercion injT1 : Z >-> T.\nOpen Scope F_scope.\n\n \n(* Sets of axioms of the T type (not minimal!) *)\nStructure Faxiom: Prop := {\n (* Arithmetic part *)\n injT_plus: forall z1 z2 : Z, (z1 + z2)%Z = z1 + z2 :> T _;\n scalT_plus_l: forall z1 z2 t, (z1 + z2) * t = z1 * t + z2 * t;\n scalT_mul: forall z1 z2 t, z1 * z2 * t = z1 * (z2 * t);\n injT_0_r: forall t, t + 0%Z = t :> T _;\n plusT_C: forall t1 t2, t1 + t2 = t2 + t1;\n plusT_A: forall t1 t2 t3, t1 + t2 + t3 = t1 + (t2 + t3);\n plusT_0: forall t1, t1 + (-1) * t1 = 0%Z;\n scalT_1: forall t, 1%Z * t = t;\n opT_def: forall t, opT _ t = (-1) * t;\n minusT_def: forall t1 t2, t1 - t2 = t1 + (-1) * t2;\n (* Inequality part *)\n leT_refl: forall x, x <= x;\n leT_compat: forall x y z t, x <= y -> z <= t -> x + z <= y + t;\n ltT_01: 0 < 1;\n ltT_compat: forall x y z t, x < y -> z <= t -> x + z < y + t;\n ltT_W: forall x y, x < y -> x <= y;\n leT_neg: forall x, (x < 0)%Z -> ~ 0 <= x;\n ltT_neg: forall x, (x <= 0)%Z -> ~ 0 < x\n}.\nVariable FA : Faxiom.\n\nLet injT_plus := (injT_plus FA).\nLet scalT_plus_l := (scalT_plus_l FA).\nLet scalT_mul := (scalT_mul FA).\nLet injT_0_r := (injT_0_r FA).\nLet plusT_C := (plusT_C FA).\nLet plusT_A := (plusT_A FA).\nLet plusT_0 := (plusT_0 FA).\nLet scalT_1 := (scalT_1 FA).\nLet opT_def := (opT_def FA).\nLet minusT_def := (minusT_def FA).\nLet leT_refl := (leT_refl FA).\nLet leT_compat := (leT_compat FA).\nLet ltT_01 := (ltT_01 FA).\nLet ltT_compat := (ltT_compat FA).\nLet ltT_W := (ltT_W FA).\nLet leT_neg := (leT_neg FA).\n\n(************************************************************)\n(*       Derived facts about the arithmetic fragment        *)\n(************************************************************)\n\nLemma injT_0_l: forall t, 0%Z + t = t.\nProof.\nintros t; rewrite plusT_C; auto; apply injT_0_r; auto.\nQed.\n\nLemma plusT_cancel: forall t t1 t2: T _, t + t1 = t + t2 -> t1 = t2.\nintros t t1 t2 H.\nProof.\nrewrite <- (injT_0_r t1); rewrite <- (plusT_0 t);\n  rewrite <- plusT_A; rewrite (plusT_C t1);\n  rewrite H; rewrite (plusT_C t); rewrite plusT_A;\n  rewrite plusT_0; rewrite injT_0_r; trivial.\nQed.\n\nLemma scalT_0: forall t, 0%Z * t = 0%Z.\nProof.\nintros t; rewrite <- (plusT_0 t).\npattern t at 2; rewrite <- (scalT_1 t).\nrewrite <- scalT_plus_l; auto.\nQed.\n\nLemma scalT_m1: forall t, (-1) * ((-1) * t) = t.\nProof.\nintros t; rewrite <- scalT_mul; rewrite scalT_1; auto.\nQed.\n\nLemma scalT_inj0: forall z, z * 0%Z = 0%Z.\nProof.\nassert (Hp: forall p, (Zpos p) * 0 = 0).\nintros p; induction p as [p Hrec | p Hrec |].\nrewrite Zpos_xI; rewrite Zmult_comm; \n  rewrite <- Zplus_diag_eq_mult_2.\nrepeat rewrite scalT_plus_l; rewrite Hrec.\nrewrite injT_0_r; rewrite plusT_C; rewrite injT_0_r.\nrewrite scalT_1; auto.\nrewrite Zpos_xO; rewrite Zmult_comm; \n  rewrite <- Zplus_diag_eq_mult_2.\nrepeat rewrite scalT_plus_l; rewrite Hrec.\nrewrite injT_0_r; auto.\nrewrite scalT_1; auto.\nintros z; destruct z as [| p | p]; auto.\napply scalT_0; auto.\nchange (Zneg p) with ((-1) * (Zpos p))%Z.\nrewrite scalT_mul; rewrite Hp.\napply plusT_cancel with (0:T _).\nrewrite plusT_0; rewrite injT_0_r; auto.\nQed.\n\nLemma scalT_plus_r: forall z t1 t2, z * (t1 + t2)= z * t1 + z * t2.\nProof.\nassert (Hp0: forall t1 t2, (-1) * (t1 + t2)= (-1) * t1 + (-1) * t2).\nintros p1 p2.\napply plusT_cancel with (p1 + p2).\nrewrite plusT_0.\nrewrite (plusT_C p1); rewrite plusT_A; rewrite (plusT_C p2).\nrepeat rewrite <- plusT_A; rewrite plusT_0; rewrite injT_0_l.\nrewrite plusT_C; rewrite plusT_0; auto.\nassert (Hp: forall p t1 t2,\n (Zpos p) * (t1 + t2)= (Zpos p) * t1 + (Zpos p) * t2).\nintros p; induction p as [p Hrec | p Hrec|]; intros t1 t2.\nrewrite Zpos_xI; repeat rewrite scalT_plus_l.\nrepeat rewrite (Zmult_comm 2); rewrite <- Zplus_diag_eq_mult_2.\nrepeat rewrite scalT_plus_l; repeat rewrite scalT_1.\nrewrite Hrec.\nrepeat rewrite plusT_A; apply f_equal2 with (f := plusT FT); auto.\nrewrite plusT_C.\nrepeat rewrite plusT_A; apply f_equal2 with (f := plusT FT); auto.\nrewrite plusT_C.\nrepeat rewrite plusT_A; apply f_equal2 with (f := plusT FT); auto.\nrewrite plusT_C.\nrepeat rewrite plusT_A; apply f_equal2 with (f := plusT FT); auto.\nrewrite Zpos_xO.\nrepeat rewrite (Zmult_comm 2); rewrite <- Zplus_diag_eq_mult_2.\nrepeat rewrite scalT_plus_l; repeat rewrite scalT_1.\nrewrite Hrec.\nrepeat rewrite plusT_A; apply f_equal2 with (f := plusT FT); auto.\nrewrite plusT_C.\nrepeat rewrite plusT_A; apply f_equal2 with (f := plusT FT); auto.\nrepeat rewrite scalT_1; auto.\nintros z; destruct z as [|p | p]; intros t1 t2; auto.\n  repeat rewrite scalT_0; rewrite injT_0_r; auto.\nchange (Zneg p) with ((-1) * (Zpos p))%Z.\nrepeat rewrite scalT_mul; rewrite Hp; rewrite Hp0; auto.\nQed.\n\nLemma injT_mul: forall z1 z2, (z1 * z2)%Z = z1 * z2 :> T _.\nProof.\nassert (Hp: forall p z2, (Zpos p * z2)%Z = (Zpos p) * z2 :> T _).\nintros p; induction p as [p Hrec | p Hrec|]; intros z2.\nrewrite Zpos_xI.\nreplace ((2 * Zpos p + 1) * z2)%Z with (Zpos p * (2 * z2) + z2)%Z;\n  try ring.\nrewrite scalT_plus_l; rewrite injT_plus; rewrite Hrec.\nrewrite Zmult_comm; rewrite <- Zplus_diag_eq_mult_2.\nrewrite injT_plus; rewrite scalT_plus_r.\nrewrite (Zmult_comm 2); \n  rewrite <- Zplus_diag_eq_mult_2.\nrewrite scalT_plus_l; rewrite scalT_1; auto.\nrewrite Zpos_xO; rewrite (Zmult_comm 2); rewrite <- Zmult_assoc.\nrewrite Hrec; rewrite scalT_mul.\nreplace (2 * z2)%Z with (z2 + z2)%Z; try ring.\nchange 2%Z with (1 + 1)%Z.\nrewrite scalT_plus_l; rewrite injT_plus; rewrite scalT_1; auto.\nrewrite scalT_1; rewrite Zmult_1_l; auto.\nintros z1 z2; destruct z1 as [| p | p]; auto.\nrewrite scalT_0; auto.\nchange (Zneg p) with ((-1) * (Zpos p))%Z.\nrewrite <-Zmult_assoc. repeat rewrite scalT_mul; auto.\nrewrite <- Hp.\napply plusT_cancel with (injT1 (Zpos p * z2)).\nrewrite <- injT_plus; rewrite plusT_0.\napply f_equal with (f := injT1); ring.\nQed.\n\n(*************************.***********************************)\n(*       Derived facts about the comparison                 *)\n(************************************************************)\n\nLemma ltT_cancel_l: forall x y z, x + y < x + z -> y < z.\nProof.\nintros x y z H.\nreplace y with ((x + y) + (-1) * x).\nreplace z with ((x + z) + (-1) * x).\napply ltT_compat; auto.\nrewrite (plusT_C x); rewrite plusT_A; rewrite plusT_0;\n  rewrite injT_0_r; auto.\nrewrite (plusT_C x); rewrite plusT_A; rewrite plusT_0;\n  rewrite injT_0_r; auto.\nQed.\n\nLemma leT_cancel_l: forall x y z, x + y <= x + z -> y <= z.\nProof.\nintros x y z H.\nreplace y with ((-1) * x + (x + y)).\nreplace z with ((-1) * x + (x + z)).\napply leT_compat; auto.\nrewrite <- plusT_A; rewrite (fun z => plusT_C z x); rewrite plusT_0;\n  rewrite injT_0_l; auto.\nrewrite <- plusT_A; rewrite (fun z => plusT_C z x); rewrite plusT_0;\n  rewrite injT_0_l; auto.\nQed.\n\nLemma leT_trans: forall x y z, x <= y -> y <= z -> x <= z.\nProof.\nintros x y z H1 H2.\napply leT_cancel_l with y.\nrewrite (plusT_C y).\napply leT_compat; auto.\nQed.\n\nLemma leT_opp: forall x y, x <= y -> (-1) * y <= (-1) * x.\nProof.\nintros x y H.\napply leT_cancel_l with x.\nrewrite plusT_0.\napply leT_cancel_l with y.\nrewrite injT_0_r.\nrewrite (plusT_C x); rewrite <- plusT_A; rewrite plusT_0;\n  rewrite injT_0_l; auto.\nQed.\n\nLemma plusTss_pos: forall x y, 0 < x -> 0 < y -> 0 < x + y.\nProof.\nintros x y Hx Hy.\nrewrite <- (injT_0_r 0).\napply ltT_compat; auto; apply ltT_W; auto.\nQed.\n\nLemma plusT1s_pos: forall x y, 0 <= x -> 0 < y -> 0 < x + y.\nProof.\nintros x y Hx Hy.\nrewrite plusT_C; rewrite <- (injT_0_r 0).\napply ltT_compat; auto.\nQed.\n\nLemma plusTs1_pos: forall x y, 0 < x -> 0 <= y -> 0 < x + y.\nProof.\nintros x y Hx Hy.\nrewrite <- (injT_0_r 0).\napply ltT_compat; auto.\nQed.\n\nLemma plusT_pos: forall x y, 0 <= x -> 0 <= y -> 0 <= x + y.\nProof.\nintros x y Hx Hy.\nrewrite <- (injT_0_r 0).\napply leT_compat; auto.\nQed.\n\nLemma eqT_pos: forall x y, (0:T _) = x -> (0:T _) = y -> (0:T _) = x + y.\nProof.\nintros x y Hx Hy; rewrite <- Hx; rewrite <- Hy; rewrite injT_0_r; auto.\nQed.\n\nLemma injT_pos: forall x, (0 <= x)%Z -> 0 <= x.\nProof.\napply natlike_ind.\napply leT_refl.\nintros x Hx H1x.\nunfold Z.succ; rewrite injT_plus.\napply plusT_pos; auto.\nQed.\n\nLemma injT_spos: forall x, (0 < x)%Z -> 0 < x.\nProof.\nintros x; destruct x as [|p|p]; intros HH;\n  try (discriminate HH).\nchange 0 with (0+0)%Z.\nreplace (Zpos p) with (1 + (Zpos p - 1))%Z.\nrepeat rewrite injT_plus.\napply ltT_compat.\napply ltT_01.\napply injT_pos; case p; intros; intros HH1; discriminate HH1.\nring.\nQed.\n\n\nLemma scalT_pos: forall x y, (0 <= x)%Z -> 0 <= y -> 0 <= x * y.\nProof.\nintros x y Hx Hy.\ngeneralize x Hx; apply natlike_ind; auto; clear x Hx.\nrewrite scalT_0; apply leT_refl.\nintros x Hx Hp.\nunfold Z.succ; rewrite scalT_plus_l.\napply plusT_pos; auto; rewrite scalT_1; auto.\nQed.\n\nLemma scalT_spos: forall x y, (0 < x)%Z -> 0 < y -> 0 < x * y.\nProof.\nintros x y Hx Hy.\ndestruct x as [|p|p]; try discriminate Hx.\nchange 0 with (0+0)%Z.\nreplace (Zpos p) with (1 + (Zpos p - 1))%Z.\nrepeat rewrite injT_plus.\nrewrite scalT_plus_l; rewrite scalT_1.\napply ltT_compat; auto.\napply scalT_pos; auto.\ncase p; intros; intros HH1; discriminate HH1.\nring.\nQed.\n\nLemma scalT_eq: forall x y, 0 = y -> (0:T _) = x * y.\nProof.\nintros x y Hy; rewrite <- Hy; rewrite scalT_inj0; auto.\nQed.\n\nEnd Init.\n\n(* Unusal notation *)\nDeclare Scope F_scope.\nNotation \"x + y\" := (plusT _ x y) : F_scope.\nNotation \"x - y\" := (minusT _ x y) : F_scope.\nNotation \"x * y\" := (scalT _ x y) : F_scope.\nNotation \"x <= y\" := (leT _ x y) : F_scope.\nNotation \"x < y\" := (ltT _ x y) : F_scope.\n\n", "meta": {"author": "thery", "repo": "Fourier", "sha": "6fa6a74940c5c8289f770910a6eea5f40cc0ab4c", "save_path": "github-repos/coq/thery-Fourier", "path": "github-repos/coq/thery-Fourier/Fourier-6fa6a74940c5c8289f770910a6eea5f40cc0ab4c/FourierConcTerm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.798186784940666, "lm_q1q2_score": 0.6544280328125143}}
{"text": "Set Implicit Arguments.\nUnset Standard Proposition Elimination Names.\n\nRequire Import util.\nRequire Import Le.\nRequire Import Lt.\nRequire Import Rbase.\nRequire Import Plus.\nRequire Import Mult.\nRequire Import Arith.\nRequire Import Omega.\nRequire Import Div2.\nRequire Import Recdef.\nRequire Import Rbase.\nRequire Import Morphisms.\n\n(* nat misc *)\n\nDefinition ltb (x y: nat): bool := negb (leb y x).\nDefinition geb (x y: nat): bool := leb y x.\n\nLtac subst_tac x y z := (* todo: rename *)\n  match z with\n  | x => y\n  | ?l + ?r =>\n      let l' := subst_tac x y l in\n      let r' := subst_tac x y r in\n        constr: (l' + r')\n  | ?l * ?r =>\n      let l' := subst_tac x y l in\n      let r' := subst_tac x y r in\n        constr: (l' * r')\n  | _ => z\n  end.\n\nLtac deep_le_trans h :=\n  match type of h with\n  | ?n <= ?u =>\n    match goal with\n    | |- ?l <= _ =>\n      let q := subst_tac n u l\n      in apply le_trans with q\n    end\n  end.\n\nInstance Transitive_le: Transitive le := le_trans.\n\nLemma minus_plus_same (y x: nat): x <= x - y + y.\nProof. intros. omega. Qed.\n\nLemma ltb_complete m n: ltb m n = true -> m < n.\nProof with auto.\n  unfold ltb.\n  intros.\n  apply leb_complete_conv.\n  apply negb_inv...\nQed.\n\nLemma ltb_complete_conv m n: ltb m n = false -> n <= m.\nProof. unfold ltb. intros. apply leb_complete. apply negb_inv; auto. Qed.\n\nLemma lt_0_mult x y: 0 < x -> 0 < y -> 0 < x * y.\nProof with auto.\n  destruct x.\n    intros.\n    inversion H.\n  simpl.\n  intros.\n  apply lt_plus_trans...\nQed.\n\nLemma mult_ne_0 a b: (a <> 0 -> b <> 0 -> mult a b <> 0)%nat.\nProof with auto with arith.\n  destruct a... destruct b...\n  intros. simpl. discriminate.\nQed.\n\nLemma weak_lt_S_n n m: S n < m -> n < m.\nProof with auto with arith.\n  intros.\n  apply lt_S_n.\n  apply lt_trans with m...\nQed.\n\nLemma le_exists_plus (x y: nat) (p: x <= y): exists d, y = x + d.\nProof with auto.\n  induction p.\n    exists 0...\n  destruct IHp.\n  exists (S x0).\n  subst...\nQed.\n\nLemma lt_exists_plus (x y: nat) (p: x < y): exists d, y = S (x + d).\nProof.\n  unfold lt in p.\n  destruct (le_exists_plus p).\n  exists x0.\n  assumption.\nQed.\n\nLemma n_lt_n_plus_Sm n m: n < n + S m.\nProof. intros. omega. Qed.\n\nLemma ne_le_impl_lt x y: x <> y -> x <= y -> x < y.\nProof. auto with *. Qed.\n\nHint Rewrite plus_0_r : arith_norm.\nHint Rewrite mult_plus_distr_r mult_plus_distr_l plus_assoc : arith_norm.\n\nLemma beq_nat_false x y: x <> y -> beq_nat x y = false.\nProof with auto.\n  intros.\n  case_eq (beq_nat x y)...\n  intros.\n  elimtype False.\n  apply H.\n  apply beq_nat_eq...\nQed.\n\nLemma minus_lt_compat_l x y z: (y <= x -> z < y -> x - y < x - z)%nat.\nProof with auto.\n  intros.\n  omega.\nQed.\n\nLemma minus_eq_inv_r d x y: (x <= d -> y <= d -> (d - x = d - y) -> x = y)%nat.\nProof with auto with arith.\n  revert x y.\n  induction d.\n    simpl.\n    intros.\n    destruct x...\n    inversion H.\n  simpl.\n  intros.\n  destruct x.\n    destruct y...\n    elimtype False.\n    apply le_Sn_n with d...\n    rewrite H1.\n    apply le_minus.\n  destruct y.\n    elimtype False.\n    apply le_Sn_n with d.\n    rewrite <- H1.\n    apply le_minus.\n  apply eq_S.\n  apply IHd...\nQed.\n\nLemma le_ne_lt x y: x <= y -> x <> y -> x < y.\nProof. intros. omega. Qed.\n\nLemma ne_nlt_lt x y: x <> y -> ~ x < y -> y < x.\nProof with auto.\n  intros.\n  destruct (le_gt_dec x y)...\n  destruct (le_lt_eq_dec _ _ l)...\n    elimtype False...\n  elimtype False...\nQed.\n\nLemma lt_not_eq x y: (x < y -> x <> y)%nat.\nProof. intros. omega. Qed.\n\nLemma lt_not_eq_sym x y: (y < x -> x <> y)%nat.\nProof. intros. omega. Qed.\n\nHint Resolve lt_not_eq.\nHint Resolve lt_not_eq_sym.\n\n(* sqrd *)\n\nDefinition sqrd n := n * n.\n\nLemma sqrd_S n: sqrd (S n) = sqrd n + n + n + 1.\nProof with auto with arith.\n  induction n...\n  rewrite IHn.\n  clear IHn.\n  unfold sqrd.\n  ring.\nQed.\n\nLemma sqrd_plus x y: sqrd x + sqrd y <= sqrd (x + y).\nProof with auto with arith.\n  intros.\n  unfold sqrd.\n  autorewrite with arith_norm...\nQed.\n\nLemma sqrd_le x y: x <= y -> sqrd x <= sqrd y.\n  intros.\n  unfold sqrd.\n  apply mult_le_compat; auto.\nQed.\n\nHint Resolve sqrd_plus sqrd_le.\n\n(* div2 properties *)\n\nLemma div2_preserves_le x y: x <= y -> div2 x <= div2 y.\nProof.\n  rewrite !Nat.div2_div. now apply Nat.div_le_mono.\nQed.\n\nLemma Sdiv2_eq_div2SS x: S (div2 x) = div2 (S (S x)).\nProof. reflexivity. Qed.\n\nLemma div2S_le_Sdiv2 x: div2 (S x) <= S (div2 x).\nProof with auto with arith.\n  destruct x...\n  rewrite <- Sdiv2_eq_div2SS.\n  apply -> Nat.succ_le_mono. apply div2_preserves_le...\nQed.\n\nLemma div2_x_plus_Sx b: div2 (b + S b) = b.\nProof with auto with arith.\n  induction b...\n  rewrite plus_Sn_m.\n  rewrite <- plus_Snm_nSm.\n  rewrite plus_Sn_m.\n  simpl...\nQed.\n\nLemma div2_x_plus_2y a b: div2 (a + 2 * b) = div2 a + b.\nProof.\n  rewrite !Nat.div2_div, Nat.mul_comm. now apply Nat.div_add.\nQed.\n\nLemma div2_sqrdSn n: div2 (sqrd n) + n <= div2 (sqrd (S n)).\nProof with auto with arith.\n  intros.\n  unfold sqrd.\n  replace (S n * S n) with (n * n + 2 * n + 1) by ring.\n  replace (div2 (n * n) + n) with (div2 (n * n + 2 * n)).\n    apply div2_preserves_le...\n  rewrite div2_x_plus_2y...\nQed.\n\nLemma le_div2 n: div2 n <= n.\nProof. apply Nat.div2_decr; auto with arith. Qed.\n\nLemma div2_lt_inv0 x y: div2 x < div2 y -> x < y.\nProof.\n  rewrite !Nat.lt_nge. intros H H'. contradict H. now apply div2_preserves_le.\nQed.\n\nLemma div2_lt_inv x y: div2 x < div2 y -> x <= y.\nProof.\n  intros. now apply Nat.lt_le_incl, div2_lt_inv0.\nQed.\n\nLemma div2_le_div2_inv x y: div2 x <= div2 y -> x <= S y.\nProof with auto with arith.\n destruct x as [|[|x]]...\n simpl. intros H. apply div2_lt_inv0 in H...\nQed.\n\nLemma div2_cancel n: div2 (2 * n) = n.\nProof with auto.\n  induction n...\n  simpl mult.\n  rewrite <- plus_n_Sm.\n  simpl in *...\nQed.\n\nLemma div2_le_inv x n: div2 x <= n -> x <= S (2 * n).\nProof. intros. rewrite <- (div2_cancel n) in H. apply (div2_le_div2_inv _ _ H). Qed.\n\n(* pow *)\n\nFixpoint pow (b e: nat) {struct e}: nat :=\n  match e with\n  | 0 => 1\n  | S e' => b * pow b e'\n  end.\n\nLemma pow_S x y: pow x (S y) = x * pow x y.\nProof. auto. Qed.\n\nLemma pow_min x: x <> 0%nat -> forall y, 0 < pow x y.\nProof with auto with arith.\n  intros H.\n  induction y...\n  simpl.\n  apply lt_0_mult...\n  destruct x...\nQed.\n\n(* log2 *)\n\nFunction ceil_log2_S (n: nat) {wf lt n}: nat :=\n  match n with\n  | 0 => 0\n  | S _ => S (ceil_log2_S (div2 n))\n  end.\nProof.\n  intros.\n  apply lt_div2; auto with arith.\n  apply lt_wf.\nDefined.\n\nLemma ceil_log2_S_def n: ceil_log2_S n =\n  match n with\n  | 0 => 0\n  | S _ => S (ceil_log2_S (div2 n))\n  end.\nProof. functional induction (ceil_log2_S n); auto. Qed.\n\nDefinition log2ceil (n: nat): nat :=\n  match n with\n  | 0 => 0\n  | S n' => ceil_log2_S n'\n  end.\n\nFunction floor_log2_S (n: nat) {wf lt n}: nat :=\n  match n with\n  | 0 => 0\n  | S n' => S (floor_log2_S (div2 n'))\n  end.\nProof.\n  intros.\n  apply le_lt_trans with n'; auto with arith.\n  apply le_div2.\n  apply lt_wf.\nDefined.\n\nLemma pow2_ceil_log2: forall n, S n <= pow 2 (ceil_log2_S n).\nProof with auto.\n  intro.\n  functional induction (ceil_log2_S n).\n    simpl...\n  rewrite pow_S.\n  cset' (pow 2 (ceil_log2_S (div2 (S _x)))).\n  destruct H.\n    inversion IHn0.\n  cset (le_S_n _ _ IHn0).\n  cset (div2_le_inv (S _x) H0).\n  omega.\nQed.\n\nLemma ceil_log2_Sn_le_n: forall n, ceil_log2_S n <= n.\nProof with auto with arith.\n  intro.\n  functional induction (ceil_log2_S n)...\n  apply le_n_S.\n  apply le_trans with (div2 (S _x))...\n  apply lt_n_Sm_le.\n  apply lt_div2...\nQed.\n\nLemma log2ceil_lt: forall n, 0 < n -> log2ceil n < n.\nProof with auto.\n  destruct n...\n  simpl.\n  unfold lt.\n  intros.\n  apply le_n_S.\n  apply ceil_log2_Sn_le_n.\nQed.\n\nLemma log2ceil_le: forall n, log2ceil n <= n.\nProof with auto with arith.\n  destruct n...\n  apply lt_le_weak.\n  apply log2ceil_lt...\nQed.\n\nLemma log2ceil_S_preserves_le x y: x <= y -> ceil_log2_S x <= ceil_log2_S y.\nProof with auto with arith.\n  revert y.\n  functional induction (ceil_log2_S x)...\n  intros.\n  destruct y.\n    inversion H.\n  apply le_trans with (S (ceil_log2_S (div2 (S y)))).\n    apply le_n_S...\n    apply IHn.\n    apply div2_preserves_le...\n  rewrite (ceil_log2_S_def (S y))...\nQed.\n\nLemma log2ceil_preserves_le x y: x <= y -> log2ceil x <= log2ceil y.\nProof with auto with arith.\n  destruct x.\n    destruct y...\n  destruct y.\n    intros.\n    inversion H.\n  simpl.\n  intros.\n  apply log2ceil_S_preserves_le...\nQed.\n\n(* INR comparisons *)\n\nLemma INR_S_ne_0 n: INR (S n) <> 0%R.\nProof. apply not_O_INR. discriminate. Qed.\n\nHint Resolve INR_S_ne_0.\n\nLemma O_le_inv_INR_S n: (0 <= / INR (S n))%R.\nProof. intros. apply Rlt_le. apply Rinv_0_lt_compat. apply lt_INR_0. auto with arith. Qed.\n\nHint Resolve O_le_inv_INR_S.\n\nLemma INR_0_inv n: INR n = 0%R -> n = 0.\nProof with auto.\n  destruct n...\n  intros.\n  elimtype False.\n  apply (INR_S_ne_0 _ H).\nQed.\n\nLemma O_lt_INR_S n: (0 < INR (S n))%R.\nProof. intros. apply lt_INR_0. auto with arith. Qed.\n\nHint Resolve O_lt_INR_S.\n\nRequire Import Fourier.\n\n(* R misc *)\n\nLtac deep_Rle_trans h :=\n  match type of h with\n  | ?n <= ?u =>\n    match goal with\n    | |- (?l <= _)%R =>\n      let q := subst_tac n u l\n      in apply Rle_trans with q\n    | _ => assert (False)\n    end\n  end.\n\nLemma Rmult_eq_compat_r (r r1 r2: R): (r1 = r2 -> r1 * r = r2 * r)%R.\nProof. intros. subst. reflexivity. Qed.\n\nLemma Rle_eq_trans x y z: (x <= y -> y = z -> x <= z)%R.\nProof. intros. fourier. Qed.\n\nLemma Req_ne_dec (x y: R): { x = y } + { x <> y }.\nProof with auto.\n  intros.\n  destruct (Rlt_le_dec x y).\n    right. intro. subst. apply (Rlt_irrefl y)...\n  destruct (Rle_lt_or_eq_dec _ _ r); [right | left]...\n  intro. subst. apply (Rlt_irrefl y)...\nQed.\n\nLemma Rmult_0_inv (a b: R): (a * b)%R = 0%R -> (a = 0%R \\/ b = 0%R).\nProof with auto with real.\n  intros.\n  destruct (Req_ne_dec a 0%R)...\n    destruct (Req_ne_dec b 0%R).\n    right...\n  elimtype False.\n  apply (prod_neq_R0 a b)...\nQed.\n\nLemma Req_le_trans x y z: x = y -> y <= z -> x <= z.\nProof. intros. subst. assumption. Qed.\n\nLemma Rle_plus_trans_l r a b c: a <= r -> r + b <= c -> a + b <= c.\nProof. intros. apply Rle_trans with (r + b); auto with real. Qed.\n\nLemma Rne_nlt_lt x y: x <> y -> ~ x < y -> y < x.\nProof with auto with real.\n  intros.\n  destruct (Rlt_le_dec x y)...\n    elimtype False...\n  destruct (Rle_lt_or_eq_dec y x r)...\n  elimtype False...\nQed.\n\nLemma Rdiv_le_1 a b: 0 < a -> a <= b -> 1 <= b / a.\nProof with auto with real.\n  intros.\n  unfold Rdiv.\n  rewrite <- (Rinv_r a)...\nQed.\n\nLemma Rdiv_lt_1 n m: 0 <= n -> n < m -> n / m < 1.\nProof with auto with real.\n  unfold Rdiv.\n  intros.\n  rewrite <- (Rinv_r m)...\n    apply Rmult_lt_compat_r...\n    apply Rinv_0_lt_compat...\n    fourier.\n  intro.\n  subst.\n  apply (Rlt_not_le _ _ H0 H).\nQed.\n\nLemma zero_le_2_div_Sn n: 0 <= (2 * / INR (S n))%R.\nProof with auto with real.\n  intros.\n  unfold Rdiv...\n  apply Rle_mult_inv_pos...\nQed.\n\nHint Resolve zero_le_2_div_Sn.\n\nDefinition bigO (f g: nat -> R): Prop := exists c, exists n, forall x, (n <= x)%nat -> f x <= c * g x.\n\nDefinition measured_bigO (X: Set) (m: X -> nat) (f: X -> R) (g: nat -> R): Prop\n  := exists c, exists n, forall x, (n <= m x)%nat -> f x <= c * g (m x).\n\nNotation \"'over' m , f =O( g )\" := (measured_bigO m f g).\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/quicksort-complexity/arith_lems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.6544280238190731}}
{"text": "(********** Translating Expressions in Time **********)\n\n(* This module defines the operation [translateExp] on expressions,\nwhich corresponds to the [Translate] constructs on contracts. In\ncontrast to [Translate], however, [translateExp] works on [Z] instead of\nonly on [nat]. *)\n\nRequire Import Denotational.\nRequire Import Tactics.\nRequire Import Typing.\nRequire Import FunctionalExtensionality.\n\nFixpoint translateExp (d : Z) (e : Exp) : Exp :=\n  match e with\n    | OpE op args => OpE op (map (translateExp d) args)\n    | Obs l i => Obs l (d + i)\n    | VarE a => VarE a\n    | Acc f n z => Acc (translateExp d f) n (translateExp d z)\n  end.\n\n\n\nLemma translateExp_ope d op args : translateExp d (OpE op args) = OpE op (map (translateExp d) args).\nreflexivity. Qed.\n\nLtac rewr_assumption := idtac; match goal with\n                          | [R:  _ |- _ ] => rewrite R\n                        end.\n\n\nLemma translateExp_ext (env : Env) d (e : Exp) ext : \n  E[|translateExp d e|] env ext = E[|e|] env (adv_ext d ext).\nProof.\n  generalize dependent ext.   generalize dependent env. \n  induction e using Exp_ind';intros; \n  try solve [simpl; repeat rewr_assumption; reflexivity].\n  rewrite translateExp_ope. simpl. rewrite map_map.\n  eapply all_apply with (p:= env) in H.\n  eapply all_apply with (p:= ext) in H.\n  apply map_rewrite in H. rewrite H. reflexivity.\n\n  generalize dependent ext.   generalize dependent env. \n  simpl. unfold Fsem in *. induction d0; intros.\n  - simpl. apply IHe2.\n  - repeat rewrite adv_ext_step. simpl. rewrite IHd0. \n    repeat rewrite adv_ext_iter. apply bind_equals. \n    f_equal; try (f_equal; omega). f_equal.\n    f_equal; try (f_equal;f_equal; omega). do 2 (apply functional_extensionality; intro).\n    do 3 f_equal. apply functional_extensionality. intros. do 3 f_equal. omega. do 2 f_equal. omega.\n    intros.    rewrite IHe1.\n    repeat rewrite Zpos_P_of_succ_nat. do 2 f_equal. omega. rewrite <- adv_ext_0. f_equal.\n    omega.\nQed.\n\nOpen Scope Z.\n\nLemma translateExp_ext_opp (env : Env) (d d' : Z) (e : Exp) (ext : ExtEnv):\n  d' + d = 0 -> E[|translateExp d e|] env (adv_ext d' ext) = E[|e|] env ext.\nProof.\n  intro H. rewrite translateExp_ext. rewrite adv_ext_opp; auto.\nQed.\n\n\nLemma translateExp_type g d e t : g |-E e ∶ t -> g |-E translateExp d e ∶ t.\nProof.\n  intro T. generalize dependent g.  generalize dependent t. \n  induction e using Exp_ind'; intros; simpl; inversion T; subst; auto.\n  - econstructor. eassumption. eapply all_apply' in H. apply all_zip; eauto. \nQed.\n", "meta": {"author": "HIPERFIT", "repo": "contracts", "sha": "dba6cb226b8f8dae7b375b8a0006217e7268dc53", "save_path": "github-repos/coq/HIPERFIT-contracts", "path": "github-repos/coq/HIPERFIT-contracts/contracts-dba6cb226b8f8dae7b375b8a0006217e7268dc53/Coq/TranslateExp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.6544280069535138}}
{"text": "Require Import QArith_base.\nRequire Import Qcanon.\nRequire Import Equalities.\nRequire Import Orders.\nRequire Import OrdersTac.\n\nLocal Open Scope Qc_scope.\n\n\nModule Qc_as_DT <: DecidableTypeFull.\n  Lemma  Qc_eq_bool_iff : forall x y, Qc_eq_bool x y = true <-> x = y.\n  Proof.\n  intros. split.\n    apply Qc_eq_bool_correct.\n    intro. unfold Qc_eq_bool. destruct (Qc_eq_dec x y). reflexivity. contradiction.\n  Qed.\n  \n  Definition t := Qc.\n  Definition eq := @eq Qc.\n  Definition eq_equiv := @eq_equivalence Qc.\n  Definition eqb := Qc_eq_bool.\n  Definition eqb_eq := Qc_eq_bool_iff.\n  \n  Include BackportEq.\n  Include HasEqBool2Dec.\n  \nEnd Qc_as_DT.\n\n\nModule Qc_as_OT <: OrderedTypeFull.\n  Lemma Qccompare_spec (x y : Qc) : CompareSpec (x=y) (x<y) (x>y) (x ?= y).\n  Proof. now case_eq (x ?= y); constructor; [rewrite Qceq_alt | rewrite Qclt_alt | rewrite Qcgt_alt]. Qed.\n  \n  Include Qc_as_DT.\n  Definition lt := Qclt.\n  Definition le := Qcle.\n  Definition compare := Qccompare.\n  \n  Instance lt_strorder : StrictOrder Qclt.\n  Proof. split.\n    intro. apply Qlt_irrefl.\n    intros x y z. apply Qlt_trans.\n  Qed.\n\n  Instance lt_compat : Proper (eq==>eq==>iff) Qclt.\n  Proof. intros x y Hxy z t Hzt. now rewrite Hxy, Hzt. Qed.\n  \n  Theorem le_lteq : forall x y : t, le x y <-> lt x y \\/ eq x y.\n  Proof.\n  intros x y. unfold le,lt,eq. split; intro H.\n    destruct (Qcle_lt_or_eq _ _ H). now left. right. assumption.\n    destruct H. now apply Qlt_le_weak. subst. now apply Qcle_refl.\n  Qed.\n  Definition compare_spec (x y : Qc) := Qccompare_spec x y.\n  \nEnd Qc_as_OT.\n", "meta": {"author": "coq-contribs", "repo": "classical-realizability", "sha": "8c6187da3ba58bdbbbdbb9ec091c4aa738820361", "save_path": "github-repos/coq/coq-contribs-classical-realizability", "path": "github-repos/coq/coq-contribs-classical-realizability/classical-realizability-8c6187da3ba58bdbbbdbb9ec091c4aa738820361/QcOrderedType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6544169595505082}}
{"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\nSection Sets.\n  Variable U : Type.\n\n  Definition set := U -> Prop.\n  \n  Definition In (A:set) x : Prop := A x.\n  \n  Definition Set_included A B := forall x, In A x -> In B x.\n  \n  Inductive Set_inter (A B:set) : set :=\n    Set_inter_intro : forall x, In A x -> In B x -> In (Set_inter A B) x.\n  \n  Inductive Set_union (A B:set) : set :=\n    | Set_union_intro_l : forall x, In A x -> In (Set_union A B) x\n    | Set_union_intro_r : forall x, In B x -> In (Set_union A B) x.\n  \n  Inductive Set_empty : set :=.\n  \n  Inductive Set_full : set :=\n    | Set_full_intro : forall x, In Set_full x.\n  \n  Inductive Set_singleton (x:U) : set :=\n    Set_singleton_intro : In (Set_singleton x) x.\n  \n  Inductive Set_couple (x y:U) : set :=\n    | Set_couple_l : In (Set_couple x y) x\n    | Set_couple_r : In (Set_couple x y) y.\n  \n  Inductive Set_triple (x y z:U) : set :=\n    | Set_triple_l : In (Set_triple x y z) x\n    | Set_triple_m : In (Set_triple x y z) y\n    | Set_triple_r : In (Set_triple x y z) z.\n  \n  Definition Set_complement (A:set) : set := fun x:U => ~ In A x.\n  \n  Definition Set_minus (B C:set) : set := fun x:U => In B x /\\ ~ In C x.\n  \n  Definition Set_subtract (B:set) (x:U) : set := Set_minus B (Set_singleton x).\n  \n  Inductive Set_disjoint (B C:set) : Prop :=\n    Set_disjoint_intro : (forall x:U, ~ In (Set_inter B C) x) -> Set_disjoint B C.\n  \n  Inductive Set_inhabited (B:set) : Prop :=\n    Inhabited_intro : forall x:U, In B x -> Set_inhabited B.\n  \n  Definition Set_strict_included (B C:set) : Prop := Set_included B C /\\ B <> C.\n  \n  Definition Set_same (B C:set) : Prop := Set_included B C /\\ Set_included C B.\n  \n  Axiom Set_Extensionality : forall A B:set, Set_same A B -> A = B.\nEnd Sets.\n\nArguments set {U}.\nArguments In {U} A x.\nArguments Set_included {U} A B.\nArguments Set_inter {U} A B _.\nArguments Set_union {U} A B _.\nArguments Set_empty {U} _.\nArguments Set_full {U} _.\nArguments Set_singleton {U} x _.\nArguments Set_couple {U} x y _.\nArguments Set_triple {U} x y z _.\nArguments Set_complement {U} A _.\nArguments Set_minus {U} B C _.\nArguments Set_subtract {U} B x _.\nArguments Set_disjoint {U} B C.\nArguments Set_inhabited {U} B.\nArguments Set_strict_included {U} B C.\nArguments Set_same {U} B C.\nArguments Set_Extensionality {U} A B _.\n", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/src/Topology/Sets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6544169576775815}}
{"text": "\n(*I will introduce you to how to operate with Coq\nin the very basic steps\n\n Coq as a language is very raw and with not many\n in built structures.\n\n Instead, Coq allows for more control by the user\n (even the equalities are defined by the user!)\n\n Coq works with Inductive, Module, Definition and a\n proof mode.\n\n Already implemented Types are: nat naturals, bool booleans,\n Prop propositions, Set set.\n\n Let us work first on Prop.\n*)\n\nCheck Prop. Check 2 = 1. Check True -> True.\n\nCheck False -> False. Eval compute in 10 + 10.\n\nEval compute in true. Compute false. Compute True -> True.\n\n(* We enter proof mode by defining a goal/theorem\n about a proposition. the followint is the structure of a\n well written proof.*)\n\nGoal forall (A:Prop), A -> A. (* Goal, definition of A, Prop.*)\nProof. (*Start of your proof.*)\n  intros A. (*Introduces A as a given fact.*)\n  intros Hypoth. (*Same as above*)\n  (*We now know that A is a given fact because of Hypoth,\n   and that we want to prove A.*)\n  exact Hypoth. (* \"Same as Hypoth\"*)\n  (*Now we can close our proof with Qed.*)\nQed.\n\nGoal forall A B : Prop, (A -> A) /\\ (B -> B).\nProof.\n  intros. (*This command introduces everything automatically.*)\n  (*Well, we met this: (A -> A) /\\ (B -> B) which is \"And\".*)\n  refine(conj _ _). (*This separates 1 goal into 2.*)\n  (*In Coq, we always prove the topmost subgoals first.\n  If you want to skip any of them for the time being, you\n  can call the \"admit.\" command, and it eliminates the\n  topmost goal.*)\n  admit.\n  intro H.\n  exact H.\n  (*At this point, the following message displays:\n  No more subgoals, but there are some goals you gave up:\n\n  A -> A\n\n  You need to go back and solve them.\n  Let us end our proof and do it the right way.*)\n  Admitted.\n  (*The command Admitted. closes an entire proof under \n  the assumption that it is an axiom/unfinished proof.*)\n\nGoal forall A B : Prop, (A -> A) /\\ (B -> B).\nProof.\n  intros.\n  refine(conj _ _).\n  trivial.\n  auto.\nQed.\n\nTheorem n_equals_n : forall n:nat, n = n.\nProof.\n  (*Whenever we have \"forall\", it is a good idea to \n  introduce the variables/facts.*)\n  intros.\n  (*To prove this, you can use auto/trivial/intuition etc.\n  The ideal argument instead is \"reflexivity.\". Let us use\n  that.*)\n  reflexivity.\nQed.\n\nGoal forall n m:nat, n = n /\\ m = m.\nProof.\n  intros.\n  refine(conj _ _).\n  (*We can use flexibility again, but let use our recently\n  proven theorem/lemma.*)\n  apply n_equals_n.\n  (*Or, we can introduce our lemma for later.*)\n  pose proof n_equals_n as theorem.\n  (* pose [args]. takes some arguments and generates a new\n  fact object which we can use later.*)\n  apply theorem.\nQed.\n\nGoal true = true.\nProof.\n  (*We could just use reflex. or apply a previous theorem,\n  but let me show you another strategy.*)\n  \n  pose(x := true). (*Declares \"obj\" defined as \"true\".*)\n  (*We can create facts which will be added as a subgoal,\n  and we will need to prove such fact.*)\n  assert(x = true). trivial.\n  (*Now, we can rewrite our goal.*)\n  rewrite <- H.\n  pose proof n_equals_n as T.\n  trivial.\nQed.\n\nGoal 5 < 6.\nProof.\n  intuition.\nQed.\n\nGoal 5 <> 6. (* 5 not equal 6*)\nProof.\n  (*reflexivity here fails. lets try unfolding this.*)\n  unfold not. (*you can try autounfold.*)\n  intro H.\n  (*We ended up in false. It means one of our Props is\n  false by nature, and we need to check which one.\n  Thankfully, since the statement H is simple enough,\n  we use discriminate.*)\n  discriminate.\nQed.\n\nGoal False -> False.\nProof.\n  intro.\n  (*One of our facts is false, let us use that.*)\n  exact H.\nQed.\n\nGoal forall a b:Prop, a -> b \\/ a.\nProof.\n  intros.\n  pose (H0 := or_intror H : b \\/ a).\n  Check H0.\n  (*We created a fact \"b \\/ a\" with the argument H. Only\n  demanding part was \"or_intro(l/r)\".*)\n  exact H0.\nQed.\n  \n(*Here is a nice exercise:*)\nGoal (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 (*pose (proof_of_B := proof_of_A A_implies_B).\n  this is the incorrect order.*)\n exact proof_of_B.\nQed.\n\nGoal (forall A B : Prop, A\\/B -> B\\/A).\nProof.\n  intros.\n  case H.\n\n    intro.\n    refine(or_intror _).\n    exact H0.\n    \n    intro.\n    refine(or_introl _). (*this one is different from above*)\n    exact H0.\nQed.\n\nGoal forall (a b:Prop), exists x:Prop, x -> (a->b) -> b.\nProof.\n  intros.\n  (*We have an existence question. we can either prove it,\n  with an example, prove it in a shady way, or disprove it.*)\n  pose(example := a).\n  (*We have our example, let us substitute in our goal.*)\n  refine(ex_intro _ example _).\n  (*refine(ex_intro function example _). more on documentation*)\n\n  (*We eliminated the existencial condition. we proceed.*)\n  intros.\n  pose(H1 := H0 H).\n  exact H1.\nQed.\n\n(*We will need the following knowledge.*)\nGoal True.\nProof. exact I. Qed.\n\n(*Let us make a tiny exercise.*)\nLemma x_not_false_and_x_true : forall x:Prop, x <> False /\\ x -> True.\nProof.\n  intros.\n  destruct H as [].\n  exact I.\nQed.\n\n(*Little challenge for you.*)\nTheorem a_true_false : forall a:Prop, ((a->True)/\\(a->False))->False.\nProof.\n  (*Write proof here*)\nAdmitted. \n\n\nGoal ~exists x:Prop, \n  x <> False /\\ x -> False.\nProof.\n  intros.\n\n  (*It may not tell you, but the negation of existence is\n  for all. Let us use that.*)\n  \n  pose proof x_not_false_and_x_true as H.\n  unfold not.\n  \n  intro.\n  case H0.\n  unfold not in H.\n  (*Okay, now our lemma comes in place to help us.\n  we will use the last two lemmas.*)\n  \n  intros.\n\n  pose proof a_true_false as T. (*challenge lemma*)\n\n  pose(s := ((x = False) -> False) /\\ x). (*lets make a \n  variable substitution.*)\n  assert(s = (((x = False) -> False) /\\ x)). intuition.\n  (*do not forget that we need to prove both are equal.*)\n  (*we are rewriting so that we get the shape that\n  lemma T requires.*)\n  \n  rewrite <- H2 in H1.\n  (*since our prior lemma is for all x, we need to specify\n  one x.*)\n  assert((((x = False) -> False) /\\ x) -> True). apply H.\n\n  rewrite <- H2 in H3.\n  (*we make more asserts to finish with T*)\n  assert((s -> True) /\\ (s -> False)). intuition.\n  assert(((s -> True) /\\ (s -> False))->False). apply T.\n\n  pose(finale := H5 H4).\n  exact finale.\nQed.\n\n\n(*Since the last proof was on the heavy end of a simple\n  proof, we shall have a break to explore the nat set.*)\n\nPrint nat.\n\n(*Inductive nat : Set :=  \n| O : nat \n| S : nat -> nat.*)\n\n(*We define nat as an inductive type, which constructors\n  are O and S (uppercase O, not zero.*)\n\nEval compute in 5 - 3.\n\n(*Every simple natural operation except division is defined.\n  With subtraction there is a catch, 3 - 5 = 0.*)\n\nEval  compute in 3 - 5.\n\nLemma sub_in_nat_is_weird : 3 - 5 = 0.\nProof.\n  simpl. (*This simplifies an expression.*)\n  reflexivity.\nQed.\n\n(*Proving in naturals function the same way as we did\n  before.*)\n\n(*We define 3 as S(S(S(O))).*)\n\nGoal S(S(S(0))) = 3.\nProof.\n  reflexivity. Qed.\n\n(*let us define a function that detects a zero.*)\n\nDefinition is_zero (n:nat) := (*parameters*)\nmatch n with (*works in a similar fashion of switch case*)\n| O => true (*if base constructor (aka 0), then true*)\n| S n' => false (* if it is a sucessor of any number, false*)\nend.\n\nEval compute in is_zero 0. Compute is_zero 11.\n\n(*Let us create a definition*)\nDefinition n_not_0 : forall n:nat, is_zero n = false -> n > 0.\nAdmitted.\n\nGoal is_zero 0 = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n(*We can define recursive functions.*)\n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\nEval compute in evenb 2. Compute evenb 4.\n\n(*Let us define some facts.*)\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  (*Can you prove it?*)\nAdmitted.\n\nDefinition a2 : forall (n:nat),\n  evenb n = negb (evenb(n+1)).\nProof.\n  (*Yet again another challenge.*)\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\n(*Here we start the real theorems!*)\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\n(*This one will be really complicated to follow through.*)\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(*If you could figure out what was happening there, please\n  tell me!!*)\n\n(*Let us stray away from evenb functions.*)\n\nRequire Import Arith.\n(*We imported a library!*)\n\nCompute 5 mod 3.\n\n(*Now we can talk about notations. Let us define a notation.*)\n\nNotation \"x ! y\" := (y mod x =0) (at level 35).\n\nCompute 3 ! 7.\n\nGoal 3 ! 6.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nGoal ~ (3 ! 7).\nProof.\n  simpl.\n  unfold not.\n  intro.\n  discriminate.\nQed.\n\nGoal forall (x:nat) (k:nat), x ! (k * x).\nProof.\n  intros.\n  elim k. simpl. \n    assert(x * 0 = 0). intuition. admit.\n    intros. simpl.\n    \n    \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Caue-Aramaki", "repo": "random_pushes_caue_aramaki", "sha": "da1274778c7106d6e3cb46e21f0b0f7bb0eef624", "save_path": "github-repos/coq/Caue-Aramaki-random_pushes_caue_aramaki", "path": "github-repos/coq/Caue-Aramaki-random_pushes_caue_aramaki/random_pushes_caue_aramaki-da1274778c7106d6e3cb46e21f0b0f7bb0eef624/coq codes/Tutorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245994514084, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.654416950239729}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\nRequire Export Iterator.\nRequire Import ZArith.\nRequire Export UList.\nOpen Scope Z_scope.\n\nTheorem next_n_Z: forall n m,  next_n Z.succ n m = n + Z_of_nat m.\nintros n m; generalize n; elim m; clear n m.\nintros n; simpl; auto with zarith.\nintros m H n.\nreplace (n + Z_of_nat (S m)) with (Z.succ n + Z_of_nat m); auto with zarith.\nrewrite <- H; auto with zarith.\nrewrite inj_S; auto with zarith.\nQed.\n\nTheorem Zprogression_end:\n forall n m,\n  progression Z.succ n (S m) =\n  app (progression Z.succ n m) (cons (n + Z_of_nat m) nil).\nintros n m; generalize n; elim m; clear n m.\nsimpl; intros; apply f_equal2 with ( f := @cons Z ); auto with zarith.\nintros m1 Hm1 n1.\napply trans_equal with (cons n1 (progression Z.succ (Z.succ n1) (S m1))); auto.\nrewrite Hm1.\nreplace (Z.succ n1 + Z_of_nat m1) with (n1 + Z_of_nat (S m1)); auto with zarith.\nreplace (Z_of_nat (S m1)) with (1 + Z_of_nat m1); auto with zarith.\nrewrite inj_S; auto with zarith.\nQed.\n\nTheorem Zprogression_pred_end:\n forall n m,\n  progression Z.pred n (S m) =\n  app (progression Z.pred n m) (cons (n - Z_of_nat m) nil).\nintros n m; generalize n; elim m; clear n m.\nsimpl; intros; apply f_equal2 with ( f := @cons Z ); auto with zarith.\nintros m1 Hm1 n1.\napply trans_equal with (cons n1 (progression Z.pred (Z.pred n1) (S m1))); auto.\nrewrite Hm1.\nreplace (Z.pred n1 - Z_of_nat m1) with (n1 - Z_of_nat (S m1)); auto with zarith.\nreplace (Z_of_nat (S m1)) with (1 + Z_of_nat m1); auto with zarith.\nrewrite inj_S; auto with zarith.\nQed.\n\nTheorem Zprogression_opp:\n forall n m,\n  rev (progression Z.succ n m) = progression Z.pred (n + Z_of_nat (pred m)) m.\nintros n m; generalize n; elim m; clear n m.\nsimpl; auto.\nintros m Hm n.\nrewrite (Zprogression_end n); auto.\nrewrite distr_rev.\nrewrite Hm; simpl; auto.\ncase m.\nsimpl; auto.\nintros m1;\n replace (n + Z_of_nat (pred (S m1))) with (Z.pred (n + Z_of_nat (S m1))); auto.\nrewrite inj_S; simpl; (unfold Z.pred; unfold Z.succ); auto with zarith.\nQed.\n\nTheorem Zprogression_le_init:\n forall n m p, In p (progression Z.succ n m) ->  (n <= p).\nintros n m; generalize n; elim m; clear n m; simpl; auto.\nintros; contradiction.\nintros m H n p [H1|H1]; auto with zarith.\ngeneralize (H _ _ H1); auto with zarith.\nQed.\n\nTheorem Zprogression_le_end:\n forall n m p, In p (progression Z.succ n m) ->  (p < n + Z_of_nat m).\nintros n m; generalize n; elim m; clear n m; auto.\nintros; contradiction.\nintros m H n p H1; simpl in H1 |-; case H1; clear H1; intros H1;\n auto with zarith.\nsubst n; auto with zarith.\napply Z.le_lt_trans  with (p + 0); auto with zarith.\napply Zplus_lt_compat_l; red; simpl; auto with zarith.\napply Z.lt_le_trans with (Z.succ n + Z_of_nat m); auto with zarith.\nrewrite inj_S; rewrite Zplus_succ_comm; auto with zarith.\nQed.\n\nTheorem ulist_Zprogression: forall a n,  ulist (progression Z.succ a n).\nintros a n; generalize a; elim n; clear a n; simpl; auto with zarith.\nintros n H1 a; apply ulist_cons; auto.\nintros H2; absurd (Z.succ a <= a); auto with zarith.\napply Zprogression_le_init with ( 1 := H2 ).\nQed.\n\nTheorem in_Zprogression:\n forall a b n, ( a <= b < a + Z_of_nat n ) ->  In b (progression Z.succ a n).\nintros a b n; generalize a b; elim n; clear a b n; auto with zarith.\nsimpl; auto with zarith.\nintros n H a b.\nreplace (a + Z_of_nat (S n)) with (Z.succ a + Z_of_nat n); auto with zarith.\nintros [H1 H2]; simpl; auto with zarith.\ncase (Zle_lt_or_eq _ _ H1); auto with zarith.\nrewrite inj_S; auto with zarith.\nQed.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-coqprime/coq-coqprime.1.0.3/src/Coqprime/List/ZProgression.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.654347930289891}}
{"text": "(* -*- mode: coq; mode: visual-line -*-  *)\n(** * H-Sets *)\n\nRequire Import Basics.\nRequire Import Types.\nRequire Import HProp.\n\n\nLocal Open Scope path_scope.\n\n(** A type is a set if and only if it satisfies Axiom K. *)\n\nDefinition axiomK A := forall (x : A) (p : x = x), p = idpath x.\n\nDefinition axiomK_hset {A} : IsHSet A -> axiomK A.\nProof.\n  intros H x p.\n  apply (H x x p (idpath x)).\nDefined.\n\nDefinition hset_axiomK {A} `{axiomK A} : IsHSet A.\nProof.\n  intros x y H.\n  apply @hprop_allpath.\n  intros p q.\n  by induction p.\nDefined.\n\nSection AssumeFunext.\nContext `{Funext}.\n\nTheorem equiv_hset_axiomK {A} : IsHSet A <~> axiomK A.\nProof.\n  apply (equiv_adjointify (@axiomK_hset A) (@hset_axiomK A)).\n  - intros K. by_extensionality x. by_extensionality x'.\n    cut (Contr (x=x)).\n    + intro. eapply path_contr.\n    + exists 1. intros. symmetry; apply K.\n  - intro K. by_extensionality x. by_extensionality x'.\n    eapply path_ishprop.\nDefined.\n\nGlobal Instance axiomK_isprop A : IsHProp (axiomK A) | 0.\nProof.\n  apply (trunc_equiv _ equiv_hset_axiomK).\nDefined.\n\nTheorem hset_path2 {A} `{IsHSet A} {x y : A} (p q : x = y):\n  p = q.\nProof.\n  induction q.\n  apply axiomK_hset; assumption.\nDefined.\n\n(** Recall that axiom K says that any self-path is homotopic to the\n   identity path.  In particular, the identity path is homotopic to\n   itself.  The following lemma says that the endo-homotopy of the\n   identity path thus specified is in fact (homotopic to) its identity\n   homotopy (whew!).  *)\n(* TODO: What was the purpose of this lemma?  Do we need it at all?  It's actually fairly trivial. *)\nLemma axiomK_idpath {A} (x : A) (K : axiomK A) :\n  K x (idpath x) = idpath (idpath x).\nProof.\n  pose (T1A := @trunc_succ _ A (@hset_axiomK A K)).\n  exact (@hset_path2 (x=x) (T1A x x) _ _ _ _).\nDefined.\n\nEnd AssumeFunext.\n\n(** We prove that if [R] is a reflexive mere relation on [X] implying identity, then [X] is an hSet, and hence [R x y] is equivalent to [x = y]. *)\nLemma ishset_hrel_subpaths\n      {X R}\n      `{Reflexive X R}\n      `{forall x y, IsHProp (R x y)}\n      (f : forall x y, R x y -> x = y)\n: IsHSet X.\nProof.\n  apply @hset_axiomK.\n  intros x p.\n  refine (_ @ concat_Vp (f x x (transport (R x) p^ (reflexivity _)))).\n  apply moveL_Vp.\n  refine ((transport_paths_r _ _)^ @ _).\n  refine ((transport_arrow _ _ _)^ @ _).\n  refine ((ap10 (apD (f x) p) (@reflexivity X R _ x)) @ _).\n  apply ap.\n  apply path_ishprop.\nDefined.\n\nGlobal Instance isequiv_hrel_subpaths\n       X R\n       `{Reflexive X R}\n       `{forall x y, IsHProp (R x y)}\n       (f : forall x y, R x y -> x = y)\n       x y\n: IsEquiv (f x y) | 10000.\nProof.\n  pose proof (ishset_hrel_subpaths f).\n  refine (isequiv_adjointify\n            (f x y)\n            (fun p => transport (R x) p (reflexivity x))\n            _\n            _);\n  intro;\n  apply path_ishprop.\nDefined.\n\n(** We will now prove that for sets, monos and injections are equivalent.*)\nDefinition ismono {X Y} (f : X -> Y)\n  := forall (Z : hSet),\n     forall g h : Z -> X, f o g = f o h -> g = h.\n\nDefinition isinj {X Y} (f : X -> Y)\n  := forall x0 x1 : X,\n       f x0 = f x1 -> x0 = x1.\n\nLemma isinj_embedding {A B : Type} (m : A -> B) : IsEmbedding m -> isinj m.\nProof.\n  intros ise x y p.\n  pose (ise (m y)).\n  assert (q : (x;p) = (y;1) :> hfiber m (m y)) by apply path_ishprop.\n  exact (ap pr1 q).\nDefined.\n\nLemma isembedding_isinj_hset {A B : Type} `{IsHSet B} (m : A -> B)\n: isinj m -> IsEmbedding m.\nProof.\n  intros isi b.\n  apply hprop_allpath; intros [x p] [y q].\n  apply path_sigma_hprop; simpl.\n  exact (isi x y (p @ q^)).\nDefined.\n\nLemma ismono_isinj `{Funext} {X Y} (f : X -> Y) : isinj f -> ismono f.\nProof.\n  intros ? ? ? ? H'.\n  apply path_forall.\n  apply ap10 in H'.\n  hnf in *.\n  eauto.\nQed.\n\nDefinition isinj_ismono {X Y} (f : X -> Y)\n           (H : ismono f)\n: isinj f\n  := fun x0 x1 H' =>\n       ap10 (H (BuildhSet Unit)\n               (fun _ => x0)\n               (fun _ => x1)\n               (ap (fun x => unit_name x) H'))\n            tt.\n\nLemma ismono_isequiv `{Funext} X Y (f : X -> Y) `{IsEquiv _ _ f}\n: ismono f.\nProof.\n  intros ? g h H'.\n  apply ap10 in H'.\n  apply path_forall.\n  intro x.\n  transitivity (f^-1 (f (g x))).\n  - by rewrite eissect.\n  - transitivity (f^-1 (f (h x))).\n    * apply ap. apply H'.\n    * by rewrite eissect.\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/theories/HSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.654347922883503}}
{"text": "Require Import While String.\nRequire Import ZArith.\nOpen Scope Z_scope.\n\nDefinition fac :=\n  Seq\n    (Assign \"res\" (Const 1))\n    (Seq\n       (While (Lt (Const 0) (Var \"n\"))\n              (Seq\n                 (Assign \"res\" (Binop Bmul (Var \"res\") (Var \"n\")))\n                 (Assign \"n\" (Binop Bsub (Var \"n\") (Const 1)))\n              )\n       )\n       (Output (Var \"res\"))\n    ).\n\n", "meta": {"author": "pwilke", "repo": "seculog", "sha": "95c58f7b7f47f27124fb589b89672670600a8b06", "save_path": "github-repos/coq/pwilke-seculog", "path": "github-repos/coq/pwilke-seculog/seculog-95c58f7b7f47f27124fb589b89672670600a8b06/Fac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6543432113838004}}
{"text": "(**\nThis file is part of the Coq.Interval library for proving bounds of\nreal-valued expressions in Coq: http://coq-interval.gforge.inria.fr/\n\nCopyright (C) 2007-2016, Inria\n\nThis library is governed by the CeCILL-C license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the library under the terms of the CeCILL-C\nlicense as circulated by CEA, CNRS and Inria at the following URL:\nhttp://www.cecill.info/\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided\nonly with a limited warranty and the library's author, the holder of\nthe economic rights, and the successive licensors have only limited\nliability. See the COPYING file for more details.\n*)\n\nFrom Coq Require Import Reals Psatz.\n\nRequire Import Xreal.\nRequire Import Basic.\nRequire Import Sig.\nRequire Import Interval.\nRequire Import Float.\nRequire Import Transcend.\n\nModule FloatIntervalFull (F : FloatOps with Definition even_radix := true) <: IntervalOps.\n\nModule F' := FloatExt F.\nModule T := TranscendentalFloatFast F.\nInclude FloatInterval F.\n\nDefinition s1 := F.ZtoS 1.\nDefinition s2 := F.ZtoS 2.\nDefinition s3 := F.ZtoS 3.\nDefinition sm1 := F.ZtoS (-1).\nDefinition c1 := F.fromZ 1.\nDefinition cm1 := F.fromZ (-1).\nDefinition c3 := F.fromZ 3.\n\nDefinition pi prec :=\n  scale2 (T.pi4 prec) s2.\n\nLemma pi_correct :\n  forall prec, contains (convert (pi prec)) (Xreal PI).\nProof.\nintros prec.\nunfold pi.\nreplace (Xreal PI) with (Xmul (Xreal (PI/4)) (Xreal (Raux.bpow radix2 2))).\n  apply scale2_correct, T.pi4_correct.\nchange (Raux.bpow _ _) with 4%R.\nsimpl.\napply f_equal.\nfield.\nQed.\n\n(* accurate only for |xi| <= 2 * pi *)\nDefinition cos prec xi :=\n  match abs xi with\n  | Ibnd xl xu =>\n    if F'.le xu xl then T.cos_fast prec xl else\n    let pi4 := T.pi4 prec in\n    if F'.le xu (F.scale2 (lower pi4) s2) then\n      bnd (lower (T.cos_fast prec xu)) (upper (T.cos_fast prec xl))\n    else\n      if F'.le xu (F.scale2 (lower pi4) s3) then\n        if F'.le (F.scale2 (upper pi4) s2) xl then\n          bnd (lower (T.cos_fast prec xl)) (upper (T.cos_fast prec xu))\n        else\n          bnd cm1 (F.max (upper (T.cos_fast prec xl)) (upper (T.cos_fast prec xu)))\n      else\n        let d := F.sub_exact xu xl in\n        if F'.le d c3 then\n          let m := F.scale2 (F.add_exact xl xu) sm1 in\n          let d := F.scale2 d sm1 in\n          let c := T.cos_fast prec m in\n          meet (bnd cm1 c1) (add prec c (bnd (F.neg d) d))\n        else bnd cm1 c1\n  | Inan => Inan\n  end.\n\nLemma cos_correct :\n  forall prec, extension Xcos (cos prec).\nProof.\nintros prec xi x Hx.\nunfold cos.\ngeneralize (abs_correct xi x Hx) (abs_ge_0' xi).\ndestruct (abs xi) as [|xl xu].\neasy.\nintros Ha Hal.\nsimpl in Hal.\ndestruct x as [|x] ; try easy.\nunfold Xbind.\nreplace (Rtrigo_def.cos x) with (Rtrigo_def.cos (Rabs x)).\n2: unfold Rabs ; case Rcase_abs ; intros _ ; try easy ; apply cos_neg.\nclear Hx.\nassert (Hcxl := T.cos_fast_correct prec xl).\nassert (Hcxu := T.cos_fast_correct prec xu).\ncase_eq (F'.le xu xl).\n  intros Hl.\n  apply F'.le_correct in Hl.\n  simpl in Ha.\n  destruct (F.toX xu) as [|xur] ; try easy.\n  destruct (F.toX xl) as [|xlr] ; try easy.\n  replace (Rabs x) with xlr.\n  exact Hcxl.\n  apply Rle_antisym.\n  apply Ha.\n  now apply Rle_trans with (2 := Hl).\nintros _.\nunfold cm1, c1, c3, sm1, s2, s3.\ncase_eq (F'.le xu (F.scale2 (lower (T.pi4 prec)) (F.ZtoS 2))).\n  intros Hu.\n  apply F'.le_correct in Hu.\n  simpl in Ha.\n  destruct (F.toX xu) as [|xur] ; try easy.\n  assert (Hxur: (xur <= PI)%R).\n    revert Hu.\n    rewrite F.scale2_correct by easy.\n    change (Raux.bpow _ _) with 4%R.\n    generalize (T.pi4_correct prec).\n    destruct (T.pi4 prec) as [|pi4l pi4u] ; simpl.\n    now rewrite F.nan_correct.\n    intros [H _] Hu.\n    destruct (F.toX pi4l) as [|pi4r] ; try easy.\n    apply Rle_trans with (1 := Hu).\n    lra.\n  clear Hu.\n  split.\n    apply proj2 in Ha.\n    destruct (T.cos_fast prec xu) as [|cu cu'] ; simpl.\n      now rewrite F.nan_correct.\n    destruct Hcxu as [Hcu _].\n    destruct (F.toX cu) as [|cur] ; try easy.\n    apply Rle_trans with (1 := Hcu).\n    apply cos_decr_1 with (4 := Hxur) (5 := Ha).\n    apply Rabs_pos.\n    now apply Rle_trans with xur.\n    apply Rle_trans with (2 := Ha).\n    apply Rabs_pos.\n  generalize (T.cos_fast_correct prec xl).\n  destruct (T.cos_fast prec xl) as [|cl' cl] ; simpl.\n    intros _.\n    now rewrite F.nan_correct.\n  destruct (F.toX xl) as [|xlr] ; try easy.\n  intros [_ Hl].\n  destruct (F.toX cl) as [|clr] ; try easy.\n  apply Rle_trans with (2 := Hl).\n  apply cos_decr_1 with (1 := Hal).\n  apply Rle_trans with (2 := Hxur).\n  now apply Rle_trans with (Rabs x).\n  apply Rabs_pos.\n  now apply Rle_trans with xur.\n  apply Ha.\nintros _.\ncase_eq (F'.le xu (F.scale2 (lower (T.pi4 prec)) (F.ZtoS 3))).\n  intros Hu.\n  apply F'.le_correct in Hu.\n  simpl in Ha.\n  destruct (F.toX xu) as [|xur] ; try easy.\n  assert (Hxur: (xur <= 2 * PI)%R).\n    revert Hu.\n    rewrite F.scale2_correct by easy.\n    change (Raux.bpow _ _) with 8%R.\n    generalize (T.pi4_correct prec).\n    destruct (T.pi4 prec) as [|pi4l pi4u] ; simpl.\n    now rewrite F.nan_correct.\n    intros [H _] Hu.\n    destruct (F.toX pi4l) as [|pi4r] ; try easy.\n    apply Rle_trans with (1 := Hu).\n    lra.\n  clear Hu.\n  case_eq (F'.le (F.scale2 (upper (T.pi4 prec)) (F.ZtoS 2)) xl).\n    intros Hl.\n    apply F'.le_correct in Hl.\n    destruct (F.toX xl) as [|xlr].\n    now destruct (F.toX (F.scale2 (upper (T.pi4 prec)) (F.ZtoS 2))).\n    assert (Hxlr: (PI <= xlr)%R).\n      revert Hl.\n      rewrite F.scale2_correct by easy.\n      change (Raux.bpow _ _) with 4%R.\n      generalize (T.pi4_correct prec).\n      destruct (T.pi4 prec) as [|pi4l pi4u] ; simpl.\n      now rewrite F.nan_correct.\n      intros [_ H] Hl.\n      destruct(F.toX pi4u) as [|pi4r] ; try easy.\n      apply Rle_trans with (2 := Hl).\n      lra.\n    clear Hl.\n    split.\n      destruct (T.cos_fast prec xl) as [|cl cl'] ; simpl.\n        now rewrite F.nan_correct.\n      destruct Hcxl as [Hcl _].\n      destruct (F.toX cl) as [|clr] ; try easy.\n      apply Rle_trans with (1 := Hcl).\n      apply cos_incr_1 with (1 := Hxlr) (5 := proj1 Ha).\n      apply Rle_trans with (2 := Hxur).\n      apply Rle_trans with (1 := proj1 Ha) (2 := proj2 Ha).\n      apply Rle_trans with (1 := Hxlr) (2 := proj1 Ha).\n      apply Rle_trans with (1 := proj2 Ha) (2 := Hxur).\n    destruct (T.cos_fast prec xu) as [|cu' cu] ; simpl.\n      now rewrite F.nan_correct.\n    destruct Hcxu as [_ Hcu].\n    destruct (F.toX cu) as [|cur] ; try easy.\n    apply Rle_trans with (2 := Hcu).\n    apply cos_incr_1 with (4 := Hxur) (5 := proj2 Ha).\n    apply Rle_trans with (1 := Hxlr) (2 := proj1 Ha).\n    apply Rle_trans with (1 := proj2 Ha) (2 := Hxur).\n    apply Rle_trans with (1 := Hxlr).\n    apply Rle_trans with (1 := proj1 Ha) (2 := proj2 Ha).\n  intros _.\n  split.\n    rewrite F.fromZ_correct.\n    apply COS_bound.\n  rewrite F.max_correct.\n  destruct (T.cos_fast prec xl) as [|cl' cl] ; simpl.\n    now rewrite F.nan_correct.\n  destruct (F.toX xl) as [|xlr] ; try easy.\n  destruct Hcxl as [_ Hcl].\n  destruct (F.toX cl) as [|clr] ; try easy.\n  destruct (T.cos_fast prec xu) as [|cu' cu] ; simpl.\n    now rewrite F.nan_correct.\n  destruct Hcxu as [_ Hcu].\n  destruct (F.toX cu) as [|cur] ; try easy.\n  destruct (Rle_dec (Rabs x) PI) as [Hx|Hx].\n    apply Rle_trans with (2 := Rmax_l _ _).\n    apply Rle_trans with (2 := Hcl).\n    apply cos_decr_1 with (1 := Hal) (3 := Rabs_pos _) (4 := Hx) (5 := proj1 Ha).\n    apply Rle_trans with (1 := proj1 Ha) (2 := Hx).\n  apply Rle_trans with (2 := Rmax_r _ _).\n  apply Rle_trans with (2 := Hcu).\n  apply Rnot_le_lt, Rlt_le in Hx.\n  apply cos_incr_1 with (1 := Hx) (4 := Hxur) (5 := proj2 Ha).\n  apply Rle_trans with (1 := proj2 Ha) (2 := Hxur).\n  apply Rle_trans with (1 := Hx) (2 := proj2 Ha).\nintros _.\ncase_eq (F'.le (F.sub_exact xu xl) (F.fromZ 3)).\n  intros Hd.\n  apply F'.le_correct in Hd.\n  revert Hd.\n  rewrite F.sub_exact_correct, F.fromZ_correct.\n  case_eq (F.toX xu) ; try easy ; intros xur Hur.\n  case_eq (F.toX xl) ; try easy ; intros xlr Hlr.\n  intros _.\n  apply meet_correct.\n    unfold convert, bnd.\n    rewrite 2!F.fromZ_correct.\n    apply COS_bound.\n  set (m := ((xlr + xur) / 2)%R).\n  replace (Xreal (Rtrigo_def.cos (Rabs x)))\n      with (Xadd (Xcos (Xreal m)) (Xreal (Rtrigo_def.cos (Rabs x) - Rtrigo_def.cos m)))\n      by (apply (f_equal Xreal) ; ring).\n  apply add_correct.\n    replace (Xreal m) with (F.toX (F.scale2 (F.add_exact xl xu) (F.ZtoS (-1)))).\n      apply T.cos_fast_correct.\n    unfold m, T.toR.\n    rewrite F.scale2_correct, F.add_exact_correct by easy.\n    now rewrite Hlr, Hur.\n  simpl.\n  rewrite F.neg_correct, F.scale2_correct by easy.\n  rewrite F.sub_exact_correct, Hlr, Hur.\n  simpl.\n  apply Raux.Rabs_le_inv.\n  destruct (MVT_abs Rtrigo_def.cos (fun t => Ropp (sin t)) m (Rabs x)) as [v [-> _]].\n  intros c _.\n  apply derivable_pt_lim_cos.\n  apply Rle_trans with (1 * Rabs (Rabs x - m))%R.\n  apply Rmult_le_compat_r.\n  apply Rabs_pos.\n  rewrite Rabs_Ropp.\n  apply Rabs_le, SIN_bound.\n  rewrite Rmult_1_l.\n  apply Rabs_le.\n  revert Ha.\n  simpl.\n  rewrite Hlr, Hur.\n  unfold m.\n  change (Z.pow_pos 2 1) with 2%Z.\n  lra.\nintros _.\nunfold convert, bnd.\nrewrite 2!F.fromZ_correct.\napply COS_bound.\nQed.\n\n(* accurate only for |xi| <= 5/2*pi *)\nDefinition sin prec xi :=\n  match xi with\n  | Ibnd xl xu =>\n    if F'.le xu xl then T.sin_fast prec xl else\n    let pi4 := T.pi4 prec in\n    let pi2 := F.scale2 (lower pi4) s1 in\n    match F'.le (F.neg pi2) xl, F'.le xu pi2 with\n    | true, true =>\n      bnd (lower (T.sin_fast prec xl)) (upper (T.sin_fast prec xu))\n    | true, false =>\n      cos prec (sub prec (scale2 pi4 s1) xi)\n    | _, _ =>\n      neg (cos prec (add prec xi (scale2 pi4 s1)))\n    end\n  | Inan => Inan\n  end.\n\nTheorem sin_correct :\n  forall prec, extension Xsin (sin prec).\nProof.\nintros prec [|xl xu] [|x] Hx ; try easy.\ngeneralize Hx.\nintros [Hxl Hxu].\nsimpl.\ncase_eq (F'.le xu xl).\n  intros Hl.\n  apply F'.le_correct in Hl.\n  assert (Hsxl := T.sin_fast_correct prec xl).\n  destruct (F.toX xu) as [|xur] ; try easy.\n  destruct (F.toX xl) as [|xlr] ; try easy.\n  replace x with xlr.\n  exact Hsxl.\n  apply Rle_antisym with (1 := Hxl).\n  now apply Rle_trans with (2 := Hl).\nintros _.\nunfold s1.\nset (pi2 := F.scale2 (lower (T.pi4 prec)) (F.ZtoS 1)).\ncase_eq (F'.le (F.neg pi2) xl).\n  intros Hpl.\n  generalize (F'.le_correct _ _ Hpl).\n  xreal_tac xl.\n    now case (F.toX (F.neg pi2)).\n  clear Hpl. intros Hpl.\n  case_eq (F'.le xu pi2).\n    intros Hpu.\n    generalize (F'.le_correct _ _ Hpu).\n    xreal_tac xu. easy.\n    xreal_tac pi2. easy.\n    clear Hpu. intros Hpu.\n    revert Hpl.\n    rewrite F.neg_correct, X1.\n    simpl.\n    intros Hpl.\n    generalize (F.scale2_correct (lower (T.pi4 prec)) 1 (refl_equal _)).\n    intros X2.\n    change (F.toX pi2 = Xmul (F.toX (lower (T.pi4 prec))) (Xreal 2)) in X2.\n    rewrite X1 in X2. clear X1.\n    revert X2.\n    generalize (T.pi4_correct prec).\n    case (T.pi4 prec) ; simpl.\n      now rewrite F.nan_correct.\n    intros p.\n    xreal_tac p. easy.\n    intros _ [Hp _] H.\n    injection H.\n    clear H X1. intros H.\n    assert (Hpl': (-(PI/2) <= r)%R).\n      apply Rle_trans with (2 := Hpl).\n      apply Ropp_le_contravar.\n      rewrite H.\n      replace (PI / 2)%R with (PI / 4 * 2)%R by field.\n      apply Rmult_le_compat_r with (2 := Hp).\n      now apply IZR_le.\n    assert (Hpu': (r0 <= PI/2)%R).\n      apply Rle_trans with (1 := Hpu).\n      rewrite H.\n      replace (PI / 2)%R with (PI / 4 * 2)%R by field.\n      apply Rmult_le_compat_r with (2 := Hp).\n      now apply IZR_le.\n    split.\n      generalize (T.sin_fast_correct prec xl).\n      destruct (T.sin_fast prec xl) as [|yl yu].\n        simpl.\n        now rewrite F.nan_correct.\n      rewrite X.\n      simpl.\n      xreal_tac yl. easy.\n      intros [Hy _].\n      apply Rle_trans with (1 := Hy).\n      assert (H' := Rle_trans _ _ _ Hxu Hpu').\n      apply sin_incr_1 ; try easy.\n      now apply Rle_trans with x.\n      now apply Rle_trans with r.\n    generalize (T.sin_fast_correct prec xu).\n    destruct (T.sin_fast prec xu) as [|yl yu].\n      simpl.\n      now rewrite F.nan_correct.\n    rewrite X0.\n    simpl.\n    xreal_tac yu. easy.\n    intros [_ Hy].\n    apply Rle_trans with (2 := Hy).\n    assert (H' := Rle_trans _ _ _ Hpl' Hxl).\n    apply sin_incr_1 ; try easy.\n    now apply Rle_trans with r0.\n    now apply Rle_trans with x.\n  intros _.\n  rewrite <- cos_shift.\n  change (Xreal (Rtrigo_def.cos (PI / 2 - x))) with (Xcos (Xsub (Xreal (PI / 2)) (Xreal x))).\n  apply cos_correct.\n  apply sub_correct with (2 := Hx).\n  replace (PI / 2)%R with (PI / 4 * 2)%R by field.\n  apply (scale2_correct _ (Xreal (PI / 4)) 1%Z).\n  apply T.pi4_correct.\nintros _.\nrewrite <- (Ropp_involutive x).\nrewrite sin_neg.\napply (neg_correct _ (Xreal _)).\nrewrite <- cos_shift.\nreplace (PI / 2 - - x)%R with (x + PI / 2)%R by ring.\nchange (Xreal (Rtrigo_def.cos (x + PI / 2))) with (Xcos (Xadd (Xreal x) (Xreal (PI / 2)))).\napply cos_correct.\napply (add_correct _ _ _ _ _ Hx).\nreplace (PI / 2)%R with (PI / 4 * 2)%R by field.\napply (scale2_correct _ (Xreal (PI / 4)) 1%Z).\napply T.pi4_correct.\nQed.\n\n(* meaningful only for |xi| <= pi/2 *)\nDefinition tan prec xi :=\n  match xi with\n  | Ibnd xl xu =>\n    if F'.le xu xl then T.tan_fast prec xl else\n    let pi2 := F.scale2 (lower (T.pi4 prec)) s1 in\n    match F'.lt (F.neg pi2) xl, F'.lt xu pi2 with\n    | true, true =>\n      bnd (lower (T.tan_fast prec xl)) (upper (T.tan_fast prec xu))\n    | _, _ => Inan\n    end\n  | Inan => Inan\n  end.\n\nLemma tan_correct :\n  forall prec, extension Xtan (tan prec).\nProof.\nintros prec [|xl xu] [|x] Hx ; try easy.\nunfold tan.\ncase_eq (F'.le xu xl).\n  intros Hl.\n  apply F'.le_correct in Hl.\n  assert (Htxl := T.tan_fast_correct prec xl).\n  unfold convert in Hx, Hl.\n  destruct (F.toX xu) as [|xur] ; try easy.\n  destruct (F.toX xl) as [|xlr] ; try easy.\n  replace x with xlr.\n  exact Htxl.\n  apply Rle_antisym with (1 := proj1 Hx).\n  apply Rle_trans with (2 := Hl).\n  apply Hx.\nunfold s1.\nintros _.\ncase_eq (F'.lt (F.neg (F.scale2 (lower (T.pi4 prec)) (F.ZtoS 1))) xl) ; try easy.\nintros Hlt1.\napply F'.lt_correct in Hlt1.\ncase_eq (F'.lt xu (F.scale2 (lower (T.pi4 prec)) (F.ZtoS 1))) ; try easy.\nintros Hlt2.\napply F'.lt_correct in Hlt2.\ngeneralize (T.tan_correct prec xl) (T.tan_correct prec xu).\nsimpl in Hx.\ndestruct (F.toX xl) as [|rl].\nnow destruct (F.toX (F.neg (F.scale2 (lower (T.pi4 prec)) (F.ZtoS 1)))).\ndestruct (F.toX xu) as [|ru] ; try easy.\nintros Hl Hu.\nrewrite bnd_correct.\nrewrite F.neg_correct in Hlt1.\nrewrite F.scale2_correct in Hlt1, Hlt2 by easy.\ngeneralize (T.pi4_correct prec).\ndestruct (T.pi4 prec) as [|pi4l pi4u].\nsimpl in Hlt1.\nnow rewrite F.nan_correct in Hlt1.\nintros [Hpil _].\nsimpl in Hlt1, Hlt2.\ndestruct (F.toX pi4l) as [|pi4r] ; try easy.\nsimpl in Hlt1, Hlt2.\napply (Rmult_le_compat_r 2) in Hpil.\n2: now apply IZR_le.\nunfold Rdiv in Hpil.\nreplace (PI * /4 * 2)%R with (PI / 2)%R in Hpil by field.\nassert (H1: (- PI / 2 < rl)%R).\n  apply Rle_lt_trans with (2 := Hlt1).\n  unfold Rdiv.\n  rewrite Ropp_mult_distr_l_reverse.\n  now apply Ropp_le_contravar.\nassert (H2: (ru < PI / 2)%R).\n  now apply Rlt_le_trans with (pi4r * 2)%R.\nunfold Xtan'.\nsimpl.\ncase is_zero_spec.\nsimpl in Hx.\napply Rgt_not_eq, cos_gt_0.\napply Rlt_le_trans with (2 := proj1 Hx).\nunfold Rdiv.\nnow rewrite <- Ropp_mult_distr_l_reverse.\nnow apply Rle_lt_trans with ru.\nunfold Xtan' in Hl, Hu.\nintros _.\nsplit.\n- destruct (T.tan_fast prec xl) as [|tl tu].\n  simpl.\n  now rewrite F.nan_correct.\n  revert Hl.\n  simpl.\n  case is_zero_spec ; try easy.\n  intros _ [H _].\n  destruct (F.toX tl) as [|rtl] ; try easy.\n  apply Rle_trans with (1 := H).\n  destruct (proj1 Hx) as [Hx'|Hx'].\n  apply Rlt_le.\n  apply tan_increasing ; try easy.\n  now apply Rle_lt_trans with ru.\n  rewrite Hx'.\n  apply Rle_refl.\n- destruct (T.tan_fast prec xu) as [|tl tu].\n  simpl.\n  now rewrite F.nan_correct.\n  revert Hu.\n  simpl.\n  case is_zero_spec ; try easy.\n  intros _ [_ H].\n  destruct (F.toX tu) as [|rtu] ; try easy.\n  apply Rle_trans with (2 := H).\n  destruct (proj2 Hx) as [Hx'|Hx'].\n  apply Rlt_le.\n  apply tan_increasing ; try easy.\n  now apply Rlt_le_trans with rl.\n  rewrite Hx'.\n  apply Rle_refl.\nQed.\n\nDefinition atan prec xi :=\n  match xi with\n  | Ibnd xl xu =>\n    Ibnd\n     (if F.real xl then lower (T.atan_fast prec xl)\n      else F.neg (F.scale2 (upper (T.pi4 prec)) s1))\n     (if F.real xu then upper (T.atan_fast prec xu)\n      else F.scale2 (upper (T.pi4 prec)) s1)\n  | Inan => Inan\n  end.\n\nLemma atan_correct :\n  forall prec, extension Xatan (atan prec).\nProof.\nintros prec [|xl xu] [|x] Hx ; try easy.\nassert (Hpi := T.pi4_correct prec).\nsimpl.\nrewrite 2!F.real_correct.\nsimpl in Hx.\nunfold s1.\nsplit.\n- generalize (proj1 Hx). clear Hx.\n  case_eq (F.toX xl).\n  intros _ _.\n  rewrite F.neg_correct.\n  rewrite F.scale2_correct by easy.\n  destruct (T.pi4 prec) as [|pi4l pi4u] ; simpl.\n  now rewrite F.nan_correct.\n  simpl in Hpi.\n  destruct (F.toX pi4u) as [|rpi4] ; try easy.\n  apply Rlt_le.\n  apply Rle_lt_trans with (2 := proj1 (atan_bound x)).\n  replace (- PI / 2)%R with (-(PI / 4 * 2))%R by field.\n  apply Ropp_le_contravar.\n  apply Rmult_le_compat_r with (2 := proj2 Hpi).\n  now apply IZR_le.\n  intros rl Hl Hx.\n  generalize (T.atan_correct prec xl).\n  destruct (T.atan_fast prec xl) as [|al au].\n  intros _.\n  simpl.\n  now rewrite F.nan_correct.\n  simpl.\n  rewrite Hl.\n  destruct (F.toX al) as [|ral] ; try easy.\n  intros [H _].\n  apply Rle_trans with (1 := H).\n  destruct Hx as [Hx|Hx].\n  now apply Rlt_le, atan_increasing.\n  rewrite Hx.\n  apply Rle_refl.\n- generalize (proj2 Hx). clear Hx.\n  case_eq (F.toX xu).\n  intros _ _.\n  rewrite F.scale2_correct by easy.\n  destruct (T.pi4 prec) as [|pi4l pi4u] ; simpl.\n  now rewrite F.nan_correct.\n  simpl in Hpi.\n  destruct (F.toX pi4u) as [|rpi4] ; try easy.\n  apply Rlt_le.\n  apply Rlt_le_trans with (1 := proj2 (atan_bound x)).\n  replace (PI / 2)%R with (PI / 4 * 2)%R by field.\n  apply Rmult_le_compat_r with (2 := proj2 Hpi).\n  now apply IZR_le.\n  intros rl Hl Hx.\n  generalize (T.atan_correct prec xu).\n  destruct (T.atan_fast prec xu) as [|al au].\n  intros _.\n  simpl.\n  now rewrite F.nan_correct.\n  simpl.\n  rewrite Hl.\n  destruct (F.toX au) as [|rau] ; try easy.\n  intros [_ H].\n  apply Rle_trans with (2 := H).\n  destruct Hx as [Hx|Hx].\n  now apply Rlt_le, atan_increasing.\n  rewrite Hx.\n  apply Rle_refl.\nQed.\n\nDefinition exp prec xi :=\n  match xi with\n  | Ibnd xl xu =>\n    Ibnd\n     (if F.real xl then lower (T.exp_fast prec xl) else F.zero)\n     (if F.real xu then upper (T.exp_fast prec xu) else F.nan)\n  | Inan => Inan\n  end.\n\nTheorem exp_correct :\n  forall prec, extension Xexp (exp prec).\nProof.\nintros prec [|xl xu].\ntrivial.\nintros [|x].\ntrivial.\nintros (Hxl, Hxu).\nsplit.\n(* lower *)\nclear Hxu.\nrewrite F.real_correct.\nxreal_tac xl.\nrewrite F.zero_correct.\nsimpl.\napply Rlt_le.\napply exp_pos.\ngeneralize (T.exp_fast_correct prec xl).\ndestruct (T.exp_fast prec xl) as [|yl yu].\nunfold lower.\nnow rewrite F.nan_correct.\nrewrite X.\nintros (H, _).\nsimpl.\nxreal_tac2.\napply Rle_trans with (1 := H).\nnow apply Raux.exp_le.\n(* upper *)\nclear Hxl.\nrewrite F.real_correct.\nxreal_tac xu.\nnow rewrite F.nan_correct.\ngeneralize (T.exp_fast_correct prec xu).\ndestruct (T.exp_fast prec xu) as [|yl yu].\nunfold upper.\nnow rewrite F.nan_correct.\nrewrite X.\nintros (_, H).\nsimpl.\nxreal_tac2.\napply Rle_trans with (2 := H).\nnow apply Raux.exp_le.\nQed.\n\nDefinition ln prec xi :=\n  match xi with\n  | Ibnd xl xu =>\n    if F'.lt F.zero xl then\n      Ibnd\n        (lower (T.ln_fast prec xl))\n        (if F.real xu then upper (T.ln_fast prec xu) else F.nan)\n    else Inan\n  | Inan => Inan\n  end.\n\nTheorem ln_correct :\n  forall prec, extension Xln (ln prec).\nProof.\nintros prec [|xl xu].\neasy.\nunfold Xln'.\nintros [|x].\neasy.\nsimpl.\nintros [Hl Hu].\ncase_eq (F'.lt F.zero xl) ; intros Hlt ; try easy.\napply F'.lt_correct in Hlt.\nrewrite F.zero_correct in Hlt.\nsimpl in Hlt.\ncase is_positive_spec.\nintros Hx.\nsplit.\ngeneralize (T.ln_fast_correct prec xl).\ncase T.ln_fast.\nintros _.\nsimpl.\nnow rewrite F.nan_correct.\nintros l u.\nsimpl.\ncase_eq (Xln (F.toX xl)).\neasy.\nintros lnx Hlnx.\nintros [H _].\ndestruct (F.toX l) as [|lr].\neasy.\napply Rle_trans with (1 := H).\ndestruct (F.toX xl) as [|xlr].\neasy.\nrevert Hlnx.\nunfold Xln'.\nsimpl.\ncase is_positive_spec.\nintros _ H'.\ninjection H'.\nintros <-.\ndestruct Hl as [Hl|Hl].\nnow apply Rlt_le, ln_increasing.\nrewrite Hl.\napply Rle_refl.\neasy.\nrewrite F.real_correct.\ncase_eq (F.toX xu).\nnow rewrite F.nan_correct.\nintros xur Hxu.\nrewrite Hxu in Hu.\ngeneralize (T.ln_fast_correct prec xu).\ncase T.ln_fast.\nintros _.\nsimpl.\nnow rewrite F.nan_correct.\nintros l u.\nsimpl.\nrewrite Hxu.\nunfold Xln'.\nsimpl.\ncase is_positive_spec.\nintros _.\nintros [_ H].\ndestruct (F.toX u) as [|ur].\neasy.\napply Rle_trans with (2 := H).\ndestruct Hu as [Hu|Hu].\nnow apply Rlt_le, ln_increasing.\nrewrite Hu.\napply Rle_refl.\neasy.\nintros Hx.\ndestruct (F.toX xl) as [|xlr].\neasy.\nelim Rle_not_lt with (1 := Hx).\nnow apply Rlt_le_trans with xlr.\nQed.\n\nEnd FloatIntervalFull.\n", "meta": {"author": "MSoegtropIMC", "repo": "interval", "sha": "2d7d7fe5d7e150372008924487186215774ba535", "save_path": "github-repos/coq/MSoegtropIMC-interval", "path": "github-repos/coq/MSoegtropIMC-interval/interval-2d7d7fe5d7e150372008924487186215774ba535/src/Interval/Float_full.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.654343208578298}}
{"text": "Require Import ZArith.\nRequire Import Reals.\nRequire Import RPolS.\nRequire Import PolSBase.\nRequire Import PolFBase.\nRequire Import PolAux.\nRequire Import PolAuxList.\nRequire Import RSignTac.\n\n\nDefinition Rfactor :=\n  factor Z Zplus Zmult Z.opp 0%Z 1%Z is_Z1 is_Z0 is_Zpos is_Zdiv Z.div Zgcd.\n\nDefinition Rfactor_minus :=\n  factor_sub Z Zplus Zmult Z.opp 0%Z 1%Z is_Z1 is_Z0 is_Zpos is_Zdiv Z.div Zgcd.\n\n\nLtac Rfactor_term term1 term2 :=\nlet term := constr:(Rminus term1 term2) in\nlet rfv := FV RCst Rplus Rmult Rminus Ropp term (@nil R) in\nlet fv := Trev rfv in\nlet expr1 := mkPolexpr Z RCst Rplus Rmult Rminus Ropp term1 fv in\nlet expr2 := mkPolexpr Z RCst Rplus Rmult Rminus Ropp term2 fv in\nlet re := eval vm_compute in (Rfactor_minus (PEsub expr1 expr2)) in\nlet factor := match re with (PEmul ?X1 _) => X1 end in\nlet expr3 := match re with (PEmul _ (PEsub ?X1 _)) => X1 end in\nlet expr4 := match re with (PEmul _ (PEsub _ ?X1 )) => X1 end in\nlet\n re1' :=\n  eval\n     unfold\n      Rconvert_back, convert_back,  pos_nth,  jump,\n         hd,  tl, Z2R, P2R in (Rconvert_back (PEmul factor expr3) fv) in\nlet re1'' := eval lazy beta in re1' in\nlet\n re2' :=\n  eval\n     unfold\n      Rconvert_back, convert_back,  pos_nth,  jump,\n         hd,  tl, Z2R, P2R in (Rconvert_back (PEmul factor expr4) fv) in\nlet re2'' := eval lazy beta in re2' in\nreplace2_tac term1 term2 re1'' re2''; [idtac| ring | ring].\n\nLtac rpolf :=\nprogress (\n(try\nmatch goal with\n| |- (?X1 = ?X2)%R =>  Rfactor_term X1 X2\n| |- (?X1 <> ?X2)%R =>  Rfactor_term X1 X2\n| |- Rlt ?X1 ?X2 => Rfactor_term X1 X2\n| |- Rgt ?X1 ?X2 =>Rfactor_term X1 X2\n| |- Rle ?X1 ?X2 => Rfactor_term X1 X2\n| |- Rge ?X1 ?X2 =>Rfactor_term X1 X2\n| _ => fail end)); try (rsign_tac); try repeat (rewrite Rmult_1_l || rewrite Rmult_1_r).\n\n\nLtac hyp_rpolf H :=\nprogress (\ngeneralize H;\n(try\nmatch type of H with\n  (?X1 = ?X2)%R =>  Rfactor_term X1 X2\n| (?X1 <> ?X2)%R =>  Rfactor_term X1 X2\n| Rlt ?X1 ?X2 => Rfactor_term X1 X2\n| Rgt ?X1 ?X2 =>Rfactor_term X1 X2\n| Rle ?X1 ?X2 => Rfactor_term X1 X2\n| Rge ?X1 ?X2 =>Rfactor_term X1 X2\n| _ => fail end)); clear H; intros H; try (hyp_rsign_tac H); try repeat rewrite Rmult_1_l in H.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/PolTac/RPolF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6543432068611125}}
{"text": "(* Función de búsqueda *)\nFixpoint lookup1 (key: N) (t: binTrie1) : option nat :=\nmatch t with\n| empty1 => None\n| leaf1 x => Some x\n| trie1 t1 t2 => if (N.even key) then lookup1 (N.div2 key) t1\n                else lookup1 (N.div2 key) t2\nend.\n", "meta": {"author": "victorz3", "repo": "CoqPatriciaTrees", "sha": "8ffecd6276845d20b954283f08936367e87eed1d", "save_path": "github-repos/coq/victorz3-CoqPatriciaTrees", "path": "github-repos/coq/victorz3-CoqPatriciaTrees/CoqPatriciaTrees-8ffecd6276845d20b954283f08936367e87eed1d/Reporte/src/lookup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6542733075712974}}
{"text": "(** Coq coding by choukh, Aug 2020 **)\n\nRequire Import ZFC.Lib.Natural.\n\n(* 以ω为指标集的集族的并 *)\nDefinition IFUnion : (set → set) → set :=\n  λ F, ⋃{F n | n ∊ ω}.\nNotation \"'⋃ᵢ' F\" := (IFUnion F)\n  (at level 9, right associativity).\n\nLemma IFUnionI : ∀ F : set → set, ∀n ∈ ω, F n ⊆ ⋃ᵢ F.\nProof.\n  intros F n Hn. unfold Sub. now apply FUnionI.\nQed.\n\nLemma IFUnionE : ∀ F : set → set, ∀x ∈ ⋃ᵢ F, ∃n ∈ ω, x ∈ F n.\nProof.\n  intros F x Hx. apply FUnionE in Hx as [n [Hn H]].\n  exists n. split; auto.\nQed.\n\nLemma nat_IFUnionI : ∀ F : nat → set, ∀ n : nat, F n ⊆ ⋃ᵢ F.\nProof.\n  intros * x Hx. eapply FUnionI. apply (embed_ran n).\n  rewrite proj_embed_id. apply Hx.\nQed.\n\nLemma nat_IFUnionE : ∀ F : nat → set, ∀x ∈ ⋃ᵢ F, ∃ n, x ∈ F n.\nProof.\n  intros F x Hx. apply FUnionE in Hx as [n [Hn H]].\n  exists n. apply H.\nQed.\n", "meta": {"author": "choukh", "repo": "Set-Theory", "sha": "5677d0d9cc3814adfb9bc1286a826f9d620fcc2e", "save_path": "github-repos/coq/choukh-Set-Theory", "path": "github-repos/coq/choukh-Set-Theory/Set-Theory-5677d0d9cc3814adfb9bc1286a826f9d620fcc2e/Lib/IndexedFamilyUnion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064587, "lm_q2_score": 0.7577943767446201, "lm_q1q2_score": 0.6542733043029069}}
{"text": "\nRequire Export Iron.Language.SystemF2r.TyEnv.\nRequire Export Iron.Language.SystemF2r.Ty.\nRequire Export Iron.Language.SystemF2r.Ki.\n\n\n(* Expressions *)\nInductive exp : Type :=\n | XVar  : nat -> exp\n | XLAM  : exp -> exp\n | XAPP  : exp -> ty  -> exp\n | XLam  : ty  -> exp -> exp\n | XApp  : exp -> exp -> exp.\nHint Constructors exp.\n\n\n(* Weak normal forms cannot be reduced further by \n   call-by-value evaluation. *)\nInductive wnfX : exp -> Prop :=\n | Wnf_XVar \n   : forall i\n   , wnfX (XVar i)\n\n | Wnf_XLAM\n   : forall x1\n   , wnfX (XLAM x1)\n\n | Wnf_XLam\n   : forall t1 x2\n   , wnfX (XLam t1 x2).\nHint Constructors wnfX.\n\n\n(* A well formed expression is closed under the given environments *)\nFixpoint wfX (kn: nat) (tn: nat) (xx: exp) : Prop := \n match xx with \n | XVar ti    => ti < tn\n | XLAM x     => wfX (S kn) tn x\n | XAPP x t   => wfX kn tn x  /\\ wfT kn t\n | XLam t x   => wfT kn t     /\\ wfX kn (S tn) x\n | XApp x1 x2 => wfX kn tn x1 /\\ wfX kn tn x2\n end.\nHint Unfold wfX.\n\n\n(* A closed expression is well formed under an empty environment. *)\nDefinition closedX (xx: exp) : Prop\n := wfX O O xx.\nHint Unfold closedX.\n\n\n(* Values are closed expressions that cannot be reduced further *)\nInductive value : exp -> Prop :=\n | Value\n   :  forall xx\n   ,  wnfX xx -> closedX xx\n   -> value xx.\nHint Constructors value.\n\n\nLemma value_wnfX \n : forall xx, value xx -> wnfX xx.\n Proof. intros. inverts H. auto. Qed.\nHint Resolve value_wnfX.\n\nLemma value_closedX \n : forall xx, value xx -> closedX xx.\n Proof. intros. inverts H. auto. Qed.\nHint Resolve value_closedX.\n\n\n(********************************************************************)\n(* Lift type indices in expressions. *)\nFixpoint liftTX (d: nat) (xx: exp) : exp :=\n  match xx with\n  |  XVar _     => xx\n\n  |  XLAM x     \n  => XLAM (liftTX (S d) x)\n\n  |  XAPP x t \n  => XAPP (liftTX d x)   (liftTT 1 d t)\n \n  |  XLam t x   \n  => XLam (liftTT 1 d t) (liftTX d x)\n\n  |  XApp x1 x2\n  => XApp (liftTX d x1)  (liftTX d x2)\n end.\n\n\n(* Lift value indices in expressions. *)\nFixpoint liftXX (d: nat) (xx: exp) : exp :=\n  match xx with\n  |  XVar ix    \n  => if le_gt_dec d ix\n      then XVar (S ix)\n      else xx\n\n  |  XLAM x\n  => XLAM (liftXX d x)\n\n  |  XAPP x t\n  => XAPP (liftXX d x) t\n \n  |  XLam t x   \n  => XLam t (liftXX (S d) x)\n\n  |  XApp x1 x2\n  => XApp (liftXX d x1) (liftXX d x2)\n end.\n\n\n(********************************************************************)\n(* Substitution of Types in Exps *)\nFixpoint substTX (d: nat) (u: ty) (xx: exp) : exp :=\n  match xx with\n  | XVar _     => xx\n\n  |  XLAM x     \n  => XLAM (substTX (S d) (liftTT 1 0 u) x)\n\n  |  XAPP x t\n  => XAPP (substTX d u x)  (substTT d u t)\n\n  |  XLam t x\n  => XLam (substTT d u t)  (substTX d u x)\n\n  |  XApp x1 x2\n  => XApp (substTX d u x1) (substTX d u x2)\n end.\n\n\n(* Substitution of Exps in Exps *)\nFixpoint substXX (d: nat) (u: exp) (xx: exp) : exp :=\n  match xx with\n  | XVar ix    \n  => match nat_compare ix d with\n     | Eq => u\n     | Gt => XVar (ix - 1)\n     | _  => XVar  ix\n     end\n\n  |  XLAM x\n  => XLAM (substXX d (liftTX 0 u) x)\n\n  |  XAPP x t\n  => XAPP (substXX d u x) t\n\n  |  XLam t x\n  => XLam t (substXX (S d) (liftXX 0 u) x)\n\n  |  XApp x1 x2\n  => XApp (substXX d u x1) (substXX d u x2)\n  end.\n\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/tmp/Iron/Language/SystemF2r/Exp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6542733016391984}}
{"text": "Require Import List.\n\nSection NoetherianImplStreamless.\n  Variable A : Set. \n\n  Fixpoint existsLi (P:A->Prop) (l:list A) : Prop :=\n    match l with\n      | nil => False\n      | h::tail => (P h \\/ (existsLi P tail))\n    end.\n\n  Fixpoint goodLi (R:A-> A->Prop) (l:list A) : Prop :=\n    match l with\n      | nil => False\n      | a::tail => (existsLi (R a) tail \\/ goodLi R tail)\n    end.                             \n\n  Inductive accessible (P: list A->Prop) (l:list A): Prop:=\n  | accessibleBase: P l -> accessible P l\n  | accessibleInd: (forall x : A, accessible P (x :: l)) -> accessible P l.\n \n  Fixpoint Initials (n:nat) (f: nat -> A) : list A :=\n    match n with\n      | 0 => nil \n      | S n => (f n) :: (Initials n f)\n    end.\n\n  Definition Noetherian (R: A -> A ->Prop) : Prop := accessible (goodLi R) nil.\n  Definition Streamless  (R: A -> A ->Prop) : Prop := forall f:nat -> A,exists n:nat, (goodLi R) (Initials n f).\n\n  Definition goodLiImplGoodF (R:A-> A->Prop)  (f:nat -> A) (l:list A) : Prop :=  goodLi R l -> goodLi R (Initials (length l) f).\n  Definition raListImpliesRaF (R:A->A->Prop)  (f:nat -> A) (l:list A) : Prop :=  forall a:A, existsLi (R a) l -> existsLi (R a) (Initials (length l) f).\n\n\n  (* This version is rather verbose to make clear what happens, it can be made shorter by using \"inversion H1;auto\"  *)\n  Lemma noeimplstrHelp (R: A -> A ->Prop) (f:nat->A) : forall l:list A, accessible (goodLi R) l  -> (goodLiImplGoodF R f l) -> (raListImpliesRaF R f l) -> exists m, (goodLi R) (Initials m f).\n  Proof.\n    intros l acc eqGood eqRRel .   \n    unfold goodLiImplGoodF in eqGood.\n    unfold raListImpliesRaF in eqRRel.\n    induction acc.  \n    exists (length l).\n    apply eqGood;auto.\n    pose (H0 (f (length l))).\n    apply e.\n    intro H1.\n    simpl.    \n    inversion H1.\n    left.   \n    apply eqRRel.\n    exact H2.\n    right.   \n    apply eqGood.\n    exact H2.\n    (* inversion H1;auto. *)\n    intros a H1.\n    inversion H1.\n    simpl.\n    left.\n    exact H2.\n    right.\n    pose (eqRRel a) as e0.\n    apply e0;auto.\n  Qed.\n\n  Lemma NoeimplStr (R:A->A->Prop) : Noetherian R -> Streamless R.\n  Proof.\n    unfold Noetherian.\n    intros acc f.\n    apply noeimplstrHelp with (l:=nil);auto.\n    intro H; contradiction H.\n    intros a H; contradiction H.\n  Qed.  \n\nEnd NoetherianImplStreamless.\n", "meta": {"author": "epa095", "repo": "noetherian-implies-streamless", "sha": "bc53d954d1721bea07e347cd2e4219bc1a7b1650", "save_path": "github-repos/coq/epa095-noetherian-implies-streamless", "path": "github-repos/coq/epa095-noetherian-implies-streamless/noetherian-implies-streamless-bc53d954d1721bea07e347cd2e4219bc1a7b1650/noe-impl-str-noneq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6542732895300207}}
{"text": "(* experimentations on HoTT *)\n(* requires coq 8.5 *)\n\nRequire Import Utf8 QArith NPeano.\nRequire Import chap1 chap2.\nSet Universe Polymorphism.\n\n(* no default implicit without arguments *)\nArguments eq_refl [A] x.\n\nNotation \"⊥\" := False.\nNotation \"⊤\" := True.\nNotation \"'ℬ'\" := (bool : Type).\nNotation \"A ⇔ B\" := ((A → B) * (B → A))%type (at level 100).\nNotation \"( x , y ) '_{' P }\" := (existT P x y)\n  (at level 0, format \"'[' ( x ,  y ) _{ P } ']'\", only parsing).\n\n(*\nTactic Notation \"transparent\" \"assert\" \"(\" ident(H) \":\" lconstr(type) \")\" :=\n refine (let H := (_ : type) in _).\n*)\nTactic Notation \"transparent\" \"assert\" \"(\" ident(H) \":\" lconstr(type) \")\" :=\n unshelve (refine (let H := (_ : type) in _)).\n\nOpen Scope nat_scope.\n\nTheorem Nat_le_neq_lt : ∀ a b, a ≤ b → a ≠ b → a < b.\nProof.\nintros a b Hab Hnab.\napply le_lt_eq_dec in Hab.\ndestruct Hab as [Hle| Heq]; [ assumption | idtac ].\nexfalso; apply Hnab; assumption.\nQed.\n\n(* Chapter 3 - Sets and logic *)\n\n(* 3.1 Sets and n-types *)\n\n(* Definition 3.1 *)\n\nDefinition isSet A := ∀ (x y : A) (p q : x = y), p = q.\n\n(* personal solution *)\nDefinition ex_3_1_2_tac : isSet True.\nProof.\nintros x y p q.\ndestruct x, y.\nrefine (match p with eq_refl _ => _ end).\nrefine (match q with eq_refl _ => _ end).\nreflexivity.\nDefined.\n\nDefinition ex_3_1_2 : isSet True :=\n  λ (x y : True),\n  match x with\n  | I =>\n      match y with\n      | I =>\n          λ p q,\n          match p with\n          | eq_refl _ => match q with eq_refl _ => eq_refl _ end\n          end\n      end\n  end.\n\n(* \"For by Theorem 2.8.1, for any x, y : 1 the type (x = y) is\n    equivalent to 1. Since any two elements of 1 are equal, this\n    implies that any two elements of x = y are equal.\" *)\n\n(* hott_2_8_1 : ∀ x y : True, (x = y) ≃ True *)\n\n(* ex_3_1_2_alt_tac *)\n\nDefinition isSet_True : isSet ⊤.\nProof.\nintros x y p q.\npose proof hott_2_8_1 x y as r.\ndestruct r as (f, ((g, Hg), (h, Hh))).\nunfold \"◦\", \"∼\", id in Hg, Hh.\npose proof Hh p as Hp.\npose proof Hh q as Hq.\ndestruct (f p), (f q).\nsubst p q; reflexivity.\nDefined.\n\n(* \"Example 3.1.3. The type 0 is a set, for given any x, y : 0 we may\n    deduce anything we like, by the induction principle of 0.\" *)\n\nDefinition ex_3_1_3_tac : isSet False.\nProof.\nintros x y p q.\ndestruct x.\nDefined.\n\nDefinition ex_3_1_3 : isSet False := λ x y, match x with end.\n\n(* bool is also a set *)\n\nDefinition isSet_bool : isSet ℬ.\nProof.\nintros x y p q.\ndestruct x, y; try discriminate p.\n refine (match p with eq_refl _ => _ end).\n refine (match q with eq_refl _ => _ end).\n reflexivity.\n\n refine (match p with eq_refl _ => _ end).\n refine (match q with eq_refl _ => _ end).\n reflexivity.\nDefined.\n\n(* \"Example 3.1.4. The type ℕ of natural numbers is also a set. This\n    follows from Theorem 2.13.1, since all equality types x =_{ℕ} y\n    are equivalent to either 1 or 0, and any two inhabitants of 1 or 0\n    are equal. We will see another proof of this fact in Chapter 7.\" *)\n\n(* ℕ.hott_2_13_1 : ∀ m n : ℕ, (m = n) ≃ ℕ.code m n *)\n\nDefinition N_code_equiv_1_or_0 m n :\n  (N.code m n ≃ True) + (N.code m n ≃ False).\nProof.\ndestruct (eq_nat_dec m n) as [H1| H1].\n left; subst m.\n exists (λ c, I); apply qinv_isequiv.\n exists (λ _, N.r n).\n unfold \"◦\", \"∼\", id; simpl.\n split; [ intros u; destruct u; reflexivity | intros c ].\n induction n; [ destruct c; reflexivity | apply IHn ].\n\n right.\n exists (λ c, H1 (N.decode m n c)); apply qinv_isequiv.\n exists (λ p : False, match p with end).\n unfold \"◦\", \"∼\", id.\n split; [ intros p; destruct p | ].\n intros c; destruct (H1 (N.decode m n c)).\nDefined.\n\n(* ex_3_1_4 *)\n\nDefinition isSet_nat_tac : isSet ℕ.\nProof.\nintros m n p q.\npose proof N.hott_2_13_1 m n as r.\npose proof N_code_equiv_1_or_0 m n as s.\ndestruct s as [s| s].\n eapply equiv_compose in s; [ | apply r ].\n destruct s as (f, ((g, Hg), (h, Hh))).\n unfold \"◦\", \"∼\", id in Hg, Hh.\n pose proof Hh p as Hp.\n pose proof Hh q as Hq.\n destruct (f p), (f q).\n subst p q; reflexivity.\n\n eapply equiv_compose in s; [ | apply r ].\n destruct s as (f, ((g, Hg), (h, Hh))).\n exfalso; apply f, p.\nDefined.\n\nDefinition isSet_nat : isSet ℕ :=\n  λ (m n : ℕ) (p q : m = n),\n  match N_code_equiv_1_or_0 m n with\n  | inl s =>\n      match s ◦◦ N.hott_2_13_1 m n with\n      | existT _ f (existT _ g Hg, existT _ h Hh) =>\n          match f p with\n          | I =>\n              λ (Hp0 : h I = p),\n              match f q as u1 return (h u1 = q → p = q) with\n              | I =>\n                  λ Hq0 : h I = q,\n                  eq_ind (h I) (λ p0 : m = n, p0 = q)\n                    (eq_ind (h I)\n                       (λ q0 : m = n, h I = q0) (eq_refl _) q Hq0) p\n                    Hp0\n              end (Hh q)\n          end (Hh p)\n      end\n  | inr s =>\n      match s ◦◦ N.hott_2_13_1 m n with\n      | existT _ f _ => match f p with end\n      end\n  end.\n\n(* \"Example 3.1.5. If A and B are sets, then so is A × B.\" *)\n\n(* not sure of what I've done in this proof, but I completed it;\n   perhaps simplifiable, understandable? *)\nDefinition ex_3_1_5 {A B} : isSet A → isSet B → isSet (A * B).\nProof.\nintros r s x y p q.\npose proof cartesian.hott_2_6_2 x y as e.\ndestruct x as (xa, xb).\ndestruct y as (ya, yb); simpl in e.\napply quasi_inv in e.\ndestruct e as (f, ((g, Hg), (h, Hh))).\nunfold \"◦\", \"∼\", id in Hg, Hh.\npose proof Hh p as Hhp.\npose proof Hh q as Hhq.\ndestruct (f p) as (fpa, fpb).\ndestruct (f q) as (fqa, fqb).\npose proof r xa ya fpa fqa as Hra.\npose proof s xb yb fpb fqb as Hrb.\ndestruct Hra, Hrb.\ndestruct Hhp; assumption.\nDefined.\n\n(* \"Similarly, if A is a set and B : A → U is such that each B(x) is a\n    set, then Σ(x:A),B(x) is a set.\" *)\n\n(* just like ex_3_1_5 above, not sure of what I've done in this proof,\n   but I completed it; perhaps simplifiable, understandable too? *)\nDefinition ex_3_1_5_bis A B :\n  isSet A → (Π (x : A), isSet (B x)) → isSet (Σ (x : A), B x).\nProof.\nintros r s x y p q.\npose proof Σ_type.hott_2_7_2 B x y as e.\ndestruct x as (xa, xb).\ndestruct y as (ya, yb); simpl in e.\ndestruct e as (f, ((g, Hg), (h, Hh))).\nunfold \"◦\", \"∼\", id in Hg, Hh.\npose proof Hh p as Hhp.\npose proof Hh q as Hhq.\ndestruct (f p) as (fpa, fpb).\ndestruct (f q) as (fqa, fqb).\npose proof r xa ya fpa fqa as Hra.\ndestruct Hhp.\nsubst fpa.\nrewrite <- Hhq.\napply ap, ap, s.\nDefined.\n\n(* \"Example 3.1.6. If A is any type and B : A → U is such that each\n    B(x) is a set, then the type Π (x:A), B(x) is a set.\" *)\n\nSection ex_3_1_6.\n\nImport Π_type.\n\nDefinition ex_3_1_6 A B : (Π (a : A), isSet (B a)) → isSet (Π (a : A), B a).\nProof.\nintros r f g p q.\nunfold isSet in r.\npose proof funext_prop_uniq_princ f g p as Hp.\npose proof funext_prop_uniq_princ f g q as Hq.\nassert (∀ x : A, happly _ _ p x = happly _ _ q x) as Hx by (intros; apply r).\napply funext in Hx.\nrewrite Hp, Hq, Hx.\nreflexivity.\nDefined.\n\nEnd ex_3_1_6.\n\n(* \"Definition 3.1.7. A type A is a 1-type if for all x, y : A and p,\n    q : x = y and r, s : p = q, we have r = s.\" *)\n\nDefinition is1Type A := ∀ (x y : A) (p q : x = y) (r s : p = q), r = s.\n\n(* \"Lemma 3.1.8. If A is a set (that is, isSet(A) is inhabited), then\n    A is a 1-type.\" *)\n\nSection lemma_3_1_8.\n\nImport Σ_type2.\n\n(* required, but general purpose lemma, tac and exp versions *)\nDefinition compose_cancel_l_tac {A} {x y z : A} (p : x = y) (q r : y = z) :\n  p • q = p • r\n  → q = r.\nProof.\nintros H.\neapply (dotl p⁻¹) in H.\neapply compose.\n eapply compose; [ | apply H ].\n eapply compose; [ | eapply invert, compose_assoc ].\n eapply compose; [ apply lu | apply dotr ].\n apply invert, compose_invert_l.\n\n eapply compose; [ eapply compose_assoc | ].\n eapply compose; [ | eapply invert, lu ].\n apply dotr, compose_invert_l.\nDefined.\n\nDefinition compose_cancel_l {A} {x y z : A} (p : x = y) (q r : y = z) :\n  p • q = p • r\n  → q = r\n:=\n  λ s,\n  lu q • ((compose_invert_l p)⁻¹ •r q) • (compose_assoc p⁻¹ p q)⁻¹ •\n  (p⁻¹ •l s) •\n  compose_assoc p⁻¹ p r • (compose_invert_l p •r r) • (lu r)⁻¹.\n\nDefinition compose_cancel_r_tac {A} {x y z : A} (p q : x = y) (r : y = z) :\n  p • r = q • r\n  → p = q.\nProof.\nintros H.\neapply (dotr r⁻¹) in H.\neapply compose.\n eapply compose; [ | apply H ].\n eapply compose; [ | eapply compose_assoc ].\n eapply compose; [ apply ru | apply dotl ].\n apply invert, compose_invert_r.\n\n eapply compose; [ eapply invert, compose_assoc | ].\n eapply compose; [ | eapply invert, ru ].\n apply dotl, compose_invert_r.\nDefined.\n\nDefinition compose_cancel_r {A} {x y z : A} (p q : x = y) (r : y = z) :\n  p • r = q • r\n  → p = q\n:=\n  λ s,\n  ru p • (p •l (compose_invert_r r)⁻¹) • compose_assoc p r r⁻¹\n  • (s •r r⁻¹)\n  • (compose_assoc q r r⁻¹)⁻¹ • (q •l compose_invert_r r) • (ru q)⁻¹.\n\n(* magic lemma to prove isSet → is1Type and also used later for\n   ispType → isSpType *)\nDefinition compose_insert_tac {A x} (f : Π (y : A), x = y) {y z} (p : y = z) :\n  f y • p = f z.\nProof.\neapply compose; [ | apply (apd f p) ].\neapply invert; destruct p; simpl; apply ru.\nDefined.\n\nDefinition compose_insert {A x} (f : Π (y : A), x = y) {y z} (p : y = z) :\n  f y • p = f z\n:=\n  match p return f y • p = transport (eq x) p (f y) with\n  | eq_refl _ => (ru (f y))⁻¹\n  end\n  • apd f p.\n\n(* done but not obvious at all; I had to look at the way they did it,\n   and I am sure I don't understand the point *)\nDefinition hott_3_1_8_tac {A} : isSet A → is1Type A.\nProof.\nintros f x y p q r s.\napply (compose_cancel_l (f x y p p)).\neapply compose; [ eapply (compose_insert (f x y p)) | ].\napply invert, compose_insert.\nDefined.\n\nDefinition hott_3_1_8 {A} : isSet A → is1Type A :=\n  λ f x y p q r s,\n  let g := f x y p in\n  compose_cancel_l (g p) r s (compose_insert g r • (compose_insert g s)⁻¹).\n\nEnd lemma_3_1_8.\n\n(* generalization *)\n\nDefinition isProp A : Type := Π (x : A), Π (y : A), x = y.\n\nFixpoint ispType (A : Type) p : Type :=\n  match p with\n  | 0 => isProp A\n  | S p' => ∀ x y : A, ispType (x = y) p'\n  end.\n\n(* A n-type has property 'ispType A (S n)', because the n of n-types\n   starts at -1 *)\n\nDefinition ispType_isSpType_tac {A : Type} n : ispType A n → ispType A (S n).\nProof.\nintros f x y.\nrevert A f x y.\ninduction n; intros.\n intros p q.\n apply (compose_cancel_l (f x x)).\n eapply compose; [ eapply (compose_insert (f x)) | ].\n apply invert, compose_insert.\n\n intros p q; apply IHn, f.\nDefined.\n\nDefinition ispType_isSpType {A : Type} n : ispType A n → ispType A (S n) :=\n  nat_rect\n    (λ n, ∀ A, ispType A n → ispType A (S n))\n    (λ A f x y p q,\n     compose_cancel_l (f x x) p q\n       (compose_insert (f x) p • (compose_insert (f x) q)⁻¹))\n    (λ n IHn A f x y, IHn (x = y) (f x y))\n    n A.\n\n(* \"Example 3.1.9. The universe U is not a set.\" *)\n\nDefinition ex_3_1_9_tac : ¬isSet Type.\nProof.\nintros r.\nunfold isSet in r.\npose proof r bool bool (ua bool_eq_bool_id) (ua bool_eq_bool_negb) as s.\napply (ap idtoeqv) in s.\neapply compose in s; [ | eapply invert, idtoeqv_ua ].\neapply invert, compose in s; [ | eapply invert, idtoeqv_ua ].\nunfold bool_eq_bool_id, bool_eq_bool_negb in s.\nsimpl in s.\ninjection s; intros H _ _.\nassert (negb true = true) as H1; [ rewrite H; reflexivity | ].\nrevert H1; apply Σ_type2.hott_2_12_6.\nDefined.\n\nDefinition isSet_Type_counterex (r : isSet Type) {A B} (p q : A ≃ B) : p = q :=\n (idtoeqv_ua p)⁻¹ • ap idtoeqv (r A B (ua p) (ua q)) • idtoeqv_ua q.\n\nDefinition ex_3_1_9 : ¬ isSet Type :=\n  λ r : isSet Type,\n  let ni : negb = id :=\n    match isSet_Type_counterex r bool_eq_bool_negb bool_eq_bool_id with\n    | eq_refl _ => eq_refl (Σ_type.pr₁ (pr₂ (Σ_type.pr₂ bool_eq_bool_negb)))\n    end\n  in\n  Σ_type2.hott_2_12_6 (eq_ind_r (λ b, b true = true) (eq_refl true) ni).\n\n(* 3.2 Propositions as types? *)\n\nSection hott_3_2_2.\nImport Σ_type.\nImport Π_type.\n\n(* \"Theorem 3.2.2. It is not the case that for all A : Type we have\n    ¬(¬A)→A.\" *)\n\nDefinition hott_3_2_2_tac : notT (∀ A, notT (notT A) → A).\nProof.\nintros f.\nset (u := (λ g, g true) : notT (notT bool)); simpl in u.\nset (nn A := notT (notT A)).\nassert (p : pr₁ bool_eq_bool_negb (f _ u) = f _ u).\n eapply compose; [ eapply invert, ua_pcr | ].\n eapply compose; [ | apply (happly _ _ (apd f (ua bool_eq_bool_negb))) ].\n eapply invert, compose.\n  apply\n    (happly _ _ (@hott_2_9_4 _ nn id _ _ (ua bool_eq_bool_negb) (f bool)) u).\n\n  apply ap, ap, funext; intros g; destruct (g true).\n\n eapply no_fixpoint_negb, p.\nDefined.\n\nDefinition hott_3_2_2 : notT (∀ A : Type, notT (notT A) → A)\n:=\n  λ f,\n  let e := bool_eq_bool_negb in\n  let u (x : notT ℬ) := x true in\n  let nn A := notT (notT A) in\n  no_fixpoint_negb (f bool u)\n    ((ua_pcr e (f bool u))⁻¹\n      • (happly _ _ (@hott_2_9_4 _ nn id _ _ (ua e) (f bool)) u\n         • ap ((ua e)⁎ ◦ f bool)\n             (funext (λ (x : notT bool), match x true with end)))⁻¹\n      • happly _ _ (apd f (ua e)) u).\n\nEnd hott_3_2_2.\n\n(* \"Corollary 3.2.7. It is not the case that for all A : Type we have\n    A+(¬A).\" *)\n\nDefinition hott_3_2_7_tac : notT (∀ A, A + notT A).\nProof.\nintros g.\napply hott_3_2_2; intros A u.\ndestruct (g A) as [a| w]; [ apply a | destruct (u w) ].\nDefined.\n\nDefinition hott_3_2_7 : notT (∀ A, A + notT A)\n:=\n  λ g,\n  hott_3_2_2\n    (λ A u,\n     match g A with\n     | inl a => a\n     | inr w => match u w with end\n     end).\n\n(* \"3.3 Mere propositions\" *)\n\n(* \"Definition 3.3.1. A type P is a mere proposition if for all x, y :\n    P we have x = y.\" *)\n\n(* Print isProp. *)\n\n(* \"Lemma 3.3.2. If P is a mere proposition and x0 : P, then P ≃ 1.\" *)\n\nDefinition hott_3_3_2_tac P : isProp P → ∀ x₀ : P, P ≃ True.\nProof.\nintros HP x₀.\nexists (λ _, I); apply qinv_isequiv.\nexists (λ _, x₀).\nsplit; intros x; [ destruct x; reflexivity | apply HP ].\nDefined.\n\nDefinition hott_3_3_2 P : isProp P → ∀ x₀ : P, P ≃ True\n:=\n  λ (HP : isProp P) (x₀ : P),\n  existT isequiv (λ _, I)\n    (qinv_isequiv (λ _, I)\n       (existT _ (λ _, x₀)\n          (λ x, match x with I => eq_refl (id I) end,  λ x, HP _ x))).\n\n(* \"Lemma 3.3.3. If P and Q are mere propositions such that P → Q and\n    Q → P, then P ≃ Q.\" *)\n\nDefinition hott_3_3_3_tac P Q :\n  isProp P → isProp Q → (P → Q) → (Q → P) → P ≃ Q.\nProof.\nintros p q f g.\nexists f; apply qinv_isequiv; exists g.\nsplit; intros x; [ apply q | apply p ].\nDefined.\n\nDefinition hott_3_3_3 P Q : isProp P → isProp Q → (P → Q) → (Q → P) → P ≃ Q\n:=\n  λ (p : isProp P) (q : isProp Q) (f : P → Q) (g : Q → P),\n  existT isequiv f (qinv_isequiv f (existT _ g (λ y, q _ y, λ x, p _ x))).\n\nDefinition isContractible P := (isProp P * (P ≃ True))%type.\n\n(* \"Lemma 3.3.4. Every mere proposition is a set.\" *)\n\nDefinition isProp_isSet A : isProp A → isSet A := ispType_isSpType 0.\n\n(* \"Lemma 3.3.5. For any type A, the types isProp(A) and isSet(A)\n    are mere propositions.\" *)\n\nSection Lemma_3_3_5.\n\nImport Π_type.\n\nDefinition hott_3_3_5_i_tac A : isProp (isProp A).\nProof.\nintros f g.\neapply funext; intros x.\neapply funext; intros y.\napply (isProp_isSet _ f).\nDefined.\n\nDefinition hott_3_3_5_i A : isProp (isProp A) :=\n  λ f g, funext (λ x, funext (λ y, isProp_isSet A f x y (f x y) (g x y))).\n\nDefinition hott_3_3_5_ii_tac A : isProp (isSet A).\nProof.\nintros f g.\neapply funext; intros x.\neapply funext; intros y.\neapply funext; intros p.\neapply funext; intros q.\napply (ispType_isSpType 1), f.\nDefined.\n\nDefinition hott_3_3_5_ii A : isProp (isSet A) :=\n  λ f g,\n  funext\n    (λ x,\n     funext\n       (λ y,\n        funext\n          (λ p,\n           funext\n             (λ q, ispType_isSpType 1 f x y p q (f x y p q) (g x y p q))))).\n\nDefinition isProp_isequiv {A B} (f : A → B) : isProp (isequiv f).\nProof.\nintros e₁ e₂.\npose proof equivalence_isequiv f as pf.\ndestruct pf as ((qi, iq), eqv).\napply eqv.\nDefined.\n\nEnd Lemma_3_3_5.\n\n(* \"3.4 Classical vs. intuitionistic logic\" *)\n\n(* \"law of excluded middle in homotopy type theory:\n       LEM : Π (A:Type), (isProp(A) → (A + ¬A))      (3.4.1)\" *)\n\nDefinition LEM := Π (A : Type), (isProp A → (A + notT A)).\n\n(* \"law of double negation\n       Π (A:Type), (isProp A → (¬¬A → A))            (3.4.2)\" *)\n\nDefinition LDN := Π (A : Type), (isProp A → (notT (notT A) → A)).\n\n(* LEM and LDN are logically equivalent (ex 3.18) *)\n\nDefinition isProp_notT_tac A : isProp (A → ⊥).\nProof.\nintros x y.\napply Π_type.funext; intros z; destruct (x z).\nDefined.\n\nDefinition isProp_notT A : isProp (A → ⊥) :=\n  λ x y : A → ⊥, Π_type.funext (λ (z : A), match x z with end).\n\nDefinition LEM_LDN : (LEM → LDN) * (LDN → LEM).\nProof.\nsplit.\n intros HLEM A HP HNA.\n destruct (HLEM A HP) as [x| x]; [ apply x | destruct (HNA x) ].\n\n intros HLDN A HPA.\n apply HLDN.\n intros x y.\n destruct x as [x| x].\n  destruct y as [y| y]; [ apply Σ_type2.inl_equal, HPA | destruct (y x) ].\n\n  destruct y as [y| y]; [ destruct (x y) | ].\n  apply Σ_type2.inr_equal.\n  apply HLDN; [ apply (ispType_isSpType 0), isProp_notT | ].\n  intros HNE; apply HNE, isProp_notT.\n\n  intros HNA; apply HNA.\n  right; intros HA; apply HNA.\n  left; apply HA.\nDefined.\n\n(* \"For emphasis, the proper version (3.4.1) may be denoted LEM-₁\" *)\n\nDefinition LEM_p p := Π (A : Type), (ispType A p → (A + notT A)).\nDefinition LEM_inf := Π (A : Type), (A + notT A).\n\n(* \"Definition 3.4.3.\n      (i) A type A is called decidable if A + ¬A.\n     (ii) Similarly, a type family B : A → Type is decidable if\n              Π(a:A)(B(a) + ¬B(a)).\n    (iii) In particular, A has decidable equality if\n              Π(a,b:A)((a = b) + ¬(a = b)).\" *)\n\nDefinition isDecidable A := (A + notT A)%type.\nDefinition isDecidableFamily A B := Π (a : A), (B a + notT (B a)).\nDefinition hasDecidableEq A := Π (a : A), Π (b : A), ((a = b) + notT (a = b)).\n\n(* \"3.5 Subsets and propositional resizing\" *)\n\nSection hott_3_5.\n\nImport Σ_type.\n\n(* \"Lemma 3.5.1. Suppose P : A → Type is a type family such that P(x) is\n    a mere proposition for all x : A. If u, v : Σ(x:A) P(x) are such\n    that pr₁(u) = pr₁(v), then u = v.\" *)\n\nDefinition hott_3_5_1_my_proof_tac {A} (P : A → Type) :\n  (Π (x : A), isProp (P x))\n  → ∀ u v : (Σ (x : A), P x),\n  pr₁ u = pr₁ v\n  → u = v.\nProof.\nintros HP u v p.\ndestruct u as (ua, up); simpl in p.\ndestruct v as (va, vp); simpl in p.\neapply compose; [ eapply (pair_eq p), HP | reflexivity ].\nDefined.\n\nDefinition hott_3_5_1_my_proof {A} (P : A → Type) :\n  (Π (x : A), isProp (P x))\n  → ∀ u v : (Σ (x : A), P x),\n  pr₁ u = pr₁ v\n  → u = v\n:=\n  λ HP u v,\n  match u with existT _ ua up =>\n    match v with existT _ va vp =>\n    λ p, pair⁼ p (HP va (transport P p up) vp)\n    end\n  end.\n\n(* their proof *)\n\nDefinition hott_3_5_1_tac A (P : A → Type) :\n  (Π (x : A), isProp (P x))\n  → ∀ u v : (Σ (x : A), P x),\n  pr₁ u = pr₁ v\n  → u = v.\nProof.\nintros HP u v p.\npose proof @hott_2_7_2 A P u v as H.\ndestruct H as (f, ((g, Hg), (h, Hh))).\napply g, (existT _ p), HP.\nDefined.\n\nDefinition hott_3_5_1 A (P : A → Type) :\n  (Π (x : A), isProp (P x))\n  → ∀ u v : (Σ (x : A), P x),\n  pr₁ u = pr₁ v\n  → u = v\n:=\n  λ HP u v p,\n  match hott_2_7_2 P u v with\n  | existT _ _ (existT _ g _, _) =>\n      g (existT _ p (HP (pr₁ v) (p⁎ (pr₂ u)) (pr₂ v)))\n  end.\n\nDefinition SetU := {A : Type & isSet A}.\nDefinition PropU := {A : Type & isProp A}.\n\nDefinition SetU_equiv_eq A B s t :\n  (existT isSet A s = existT isSet B t) ≃ (A = B).\nProof.\nexists\n  (λ p : existT isSet A s = existT isSet B t,\n   match p in (_ = s0) return (let (b, _) := s0 in A = b) with\n   | eq_refl _ => eq_refl A\n   end).\napply qinv_isequiv.\nexists (hott_3_5_1 _ isSet hott_3_3_5_ii (existT isSet A s) (existT isSet B t)).\nunfold \"◦\", \"∼\", id; simpl.\nsplit.\n intros p.\n unfold hott_3_5_1; simpl.\n destruct (hott_2_7_2 isSet (existT isSet A s) (existT isSet B t)) as (f, H).\n destruct H as ((g, Hg), (h, Hh)).\n unfold hott_3_3_5_ii; simpl.\n destruct p; simpl.\n (* equivalent, equivalent... are they really equivalent?\n    or just logically equivalent? *)\nAbort.\n\nEnd hott_3_5.\n\n(* \"Recall that for any two universes Ui and Ui+1, if A : Ui then also\n    A : Ui+1. Thus, for any (A, s) : SetUi we also have (A, s) : SetUi+1,\n    and similarly for PropUi , giving natural maps\n       SetUi → SetUi+1,              (3.5.3)\n       PropUi → PropUi+1.            (3.5.4)\" *)\n\n(* ok, but I don't know how to program the hierarchy of universes in Coq;\n   and the following axiom cannot be written either *)\n\n(* \"Axiom 3.5.5 (Propositional resizing). The map PropUi → PropUi+1 is\n    an equivalence.\" *)\n\n(* \"3.6 The logic of mere propositions\" *)\n\nSection hott_3_6.\n\n(* \"Example 3.6.1. If A and B are mere propositions, so is A x B.\" *)\n\nDefinition ex_3_6_1 {A B} : isProp A → isProp B → isProp (A * B).\nProof.\nintros HA HB x y.\ndestruct x as (xa, xb).\ndestruct y as (ya, yb).\napply cartesian.pair_eq; simpl.\nsplit; [ apply HA | apply HB ].\nDefined.\n\n(* \"Example 3.6.2. If A is any type and B : A → Type is such that for all\n    x : A, the type B(x) is a mere proposition, then Π(x:A) B(x) is a\n    mere proposition.\" *)\n\nImport Π_type.\n\nDefinition ex_3_6_2 {A B} :\n  (Π (x : A), isProp (B x)) → isProp (Π (x : A), B x).\nProof.\nintros HP f g.\napply funext; intros x; apply HP.\nDefined.\n\nDefinition isPropImp {A B} : isProp B → isProp (A → B).\nProof.\nintros * H.\nintros; apply ex_3_6_2; intros x; apply H.\nDefined.\n\nDefinition isPropNot {A} : isProp A → isProp (notT A).\nProof.\nintros. apply isPropImp; intros x y; destruct x.\nDefined.\n\nEnd hott_3_6.\n\n(* \"3.7 Propositional truncation\" *)\n\nAxiom PT : Type → Type.\nArguments PT _%type.\nNotation \"∥ A ∥\" := (PT A) (A at level 0, format \"∥ A ∥\") : type_scope.\n\nAxiom PT_intro : ∀ A, A → ∥A∥.\nArguments PT_intro [A] x.\nNotation \"╎ A ╎\" := (PT_intro A) (A at level 0, format \"╎ A ╎\") : type_scope.\n\nAxiom PT_eq : ∀ A, isProp ∥A∥.\n(* Arguments PT_eq [A] x y. *)\n\n(* \"If B is a mere proposition and we have f : A → B, then there is an\n    induced g : ∥A∥ → B such that g(|a|) ≡ f(a) for all a : A.\" *)\n\nAxiom PT_rec : ∀ A B (f : A → B), isProp B →\n  Σ (g : ∥A∥ → B), ∀ a, g (PT_intro a) = f a.\n\nDefinition PT_elim {A} : isProp A → ∥A∥ → A :=\n  λ PA, Σ_type.pr₁ (PT_rec A A id PA).\nDefinition PT_intro_not {A} : notT A → notT ∥A∥ :=\n  λ f, Σ_type.pr₁ (PT_rec A ⊥ f (λ x y : ⊥, match x with end)).\n\n(* \"3.8 The axiom of choice\" *)\n\nDefinition ACX X :=\n  ∀ (A : X → Type) (P : Π (x : X), (A x → Type)),\n  isSet X\n  → (Π (x : X), isSet (A x))\n  → (Π (x : X), Π (a : A x), isProp (P x a))\n  → (Π (x : X), ∥ (Σ (a : A x), P x a) ∥)\n  → ∥ (Σ (g : Π (x : X), A x), Π (x : X), P x (g x)) ∥.\n\nDefinition AC := ∀ (X : Type), ACX X.\n\nDefinition AC_3_8_3 :=\n  ∀ (X : Type) (Y : X → Type), isSet X → (Π (x : X), isSet (Y x))\n  → (Π (x : X), ∥ (Y x) ∥) → ∥ (Π (x : X), Y x) ∥.\n\nDefinition hott_3_8_2 : AC ≃ AC_3_8_3.\nProof.\napply hott_3_3_3.\n do 7 (apply ex_3_6_2; intros); apply PT_eq.\n\n do 5 (apply ex_3_6_2; intros); apply PT_eq.\n\n intros AC₁ X Y SX SY YX.\n unfold AC in AC₁; rename AC₁ into AC.\n assert (H1 : ∀ x : X, Y x → isProp ⊤).\n  intros _ _ x y.\n  apply (Σ_type.pr₁ (quasi_inv (hott_2_8_1 x y))), x.\n\n  assert (H2 : ∀ x : X, ∥{_ : Y x & ⊤}∥).\n   intros x.\n   apply (PT_rec (Y x)); [ | apply PT_eq | apply YX ].\n   intros y; apply PT_intro, (existT (λ (_ : Y x), True) (y : Y x) I).\n\n   pose proof AC X Y (λ _ _, ⊤) SX SY H1 H2 as H; simpl in H.\n   assert (f : {_ : ∀ x : X, Y x & X → ⊤} → ∥(∀ x : X, Y x)∥).\n    intros H3; apply PT_intro, H3.\n\n    assert (PB : isProp ∥(∀ x : X, Y x)∥) by apply PT_eq.\n    apply (Σ_type.pr₁ (PT_rec _ _ f PB) H).\n\n unfold AC.\n intros H X A P SX SA PP H1.\n pose proof (λ A P, ua (quasi_inv (@UnivProp.hott_2_15_7 X A P))) as H3.\n rewrite H3.\n apply (λ S, H X (λ x, Σ (a : A x), P x a) SX S H1); intros x.\n apply ex_3_1_5_bis; [ apply SA | intros y; apply isProp_isSet, PP ].\nDefined.\n\nDefinition isProp_Σ_type_tac {A B} :\n  isProp A → (Π (x : A), isProp (B x)) → isProp Σ (x : A), B x.\nProof.\nintros PA PB (x₁, x₂) (y₁, y₂).\npose proof (PA x₁ y₁) as H; destruct H.\npose proof (PB x₁ x₂ y₂) as H; destruct H.\nreflexivity.\nDefined.\n\nDefinition isProp_Σ_type {A B} :\n  isProp A → (Π (x : A), isProp (B x)) → isProp Σ (x : A), B x\n:=\n  λ PA PB x,\n  match x with\n  | existT _ x₁ x₂ =>\n      λ y,\n      match y with\n      | existT _ y₁ y₂ =>\n          match PA x₁ y₁ with\n          | eq_refl _ =>\n              λ y₂,\n              match PB x₁ x₂ y₂  with\n              | eq_refl _ => eq_refl (existT B x₁ x₂)\n              end\n          end y₂\n      end\n  end.\n\nDefinition AC_3_8_3_equiv :=\n  ∀ (X : Type) (Y : X → Type), isSet X → (Π (x : X), isSet (Y x))\n  → (Π (x : X), ∥ (Y x) ∥) ≃ ∥ (Π (x : X), Y x) ∥.\n\nDefinition AC_equiv_3_8_3_equiv : AC ≃ AC_3_8_3_equiv.\nProof.\neapply equiv_compose; [ apply hott_3_8_2 |  ].\napply hott_3_3_3.\n do 5 (apply ex_3_6_2; intros).\n intros u v; apply PT_eq.\n\n do 4 (apply ex_3_6_2; intros).\n unfold equivalence.\n apply isProp_Σ_type.\n  apply ex_3_6_2; intros.\n  intros u v; apply PT_eq.\n\n  intros y; apply isProp_isequiv.\n\n unfold AC_3_8_3, AC_3_8_3_equiv.\n intros AC X Y SX SY.\n apply hott_3_3_3.\n  apply ex_3_6_2; intros; intros u v; apply PT_eq.\n\n  intros u v; apply PT_eq.\n\n  intros H; apply AC; assumption.\n\n  intros H x.\n  pose proof (λ B PB H1, Σ_type.pr₁ (PT_rec (∀ x : X, Y x) B H1 PB) H) as H1.\n  apply H1; [ apply PT_eq | intros H2; apply PT_intro, H2 ].\n\n unfold AC_3_8_3, AC_3_8_3_equiv.\n intros AC X Y SX SY.\n apply hott_3_3_3.\n  apply ex_3_6_2; intros; intros u v; apply PT_eq.\n\n  intros u v; apply PT_eq.\n\n  intros H; apply AC; assumption.\n\n  intros H x.\n  pose proof (λ B PB H1, Σ_type.pr₁ (PT_rec (∀ x : X, Y x) B H1 PB) H) as H1.\n  apply H1; [ apply PT_eq | intros H2; apply PT_intro, H2 ].\nDefined.\n\n(* equivalence is a set, whenever A and B are *)\n\nDefinition isSet_equiv {A B : Set} : isSet A → isSet B → isSet (A ≃ B).\nProof.\nintros SA SB.\napply ex_3_1_5_bis; [ apply ex_3_1_6; intros; apply SB | idtac ].\nintros f; apply isProp_isSet, isProp_isequiv.\nDefined.\n\n(* \"Lemma 3.8.5. There exists a type X and a family Y : X → Type such\n    that each Y(x) is a set, but such that (3.8.3) is false.\" *)\n\n(* If I understand well, the axiom of choice is not compatible with\n   families of sets whose father is not a set. *)\n\nDefinition pair_eq_bool_trunc := Σ (A : Type), ∥(ℬ = A)∥.\n\nDefinition equiv_eq_pair_trunc A B p q :\n  ((existT _ A p : pair_eq_bool_trunc) = existT _ B q) ≃ (A ≃ B).\nProof.\nintros; simpl.\nexists\n  (λ H,\n   (λ\n    H2 : Σ_type.pr₁ (existT (λ A0 : Type, ∥(ℬ = A0)∥) A p)\n         ≃ Σ_type.pr₁ (existT (λ A0 : Type, ∥(ℬ = A0)∥) B q), H2)\n     (idtoeqv (ap Σ_type.pr₁ H))).\napply qinv_isequiv.\nexists (λ r : A ≃ B, Σ_type.pair_eq (ua r) (PT_eq _ ((ua r)⁎ p) q)).\nunfold \"◦\", \"∼\", id; simpl.\nsplit.\n intros r.\n rewrite <- idtoeqv_ua; f_equal.\n destruct (ua r); simpl; unfold id.\n destruct (PT_eq _ p q); reflexivity.\n\n intros r.\n rewrite ua_idtoeqv.\n refine match r with\n        | eq_refl _ => _\n        end; simpl; unfold id.\n assert (SA : isSet ∥(ℬ = A)∥) by apply isProp_isSet, PT_eq.\n assert (H : PT_eq _ p p = eq_refl p) by apply SA.\n rewrite H; reflexivity.\nDefined.\n\nDefinition equiv_eq_bool_trunc :\n  (existT (λ A, ∥(ℬ = A)∥) ℬ (PT_intro (eq_refl ℬ)) =\n   existT (λ A, ∥(ℬ = A)∥) ℬ (PT_intro (eq_refl ℬ))) ≃\n   (ℬ ≃ ℬ).\nProof.\nintros; apply equiv_eq_pair_trunc.\nDefined.\n\nDefinition hott_3_8_5 :\n  Σ (X : Type), Σ (Y : X → Type),\n  notT ((Π (x : X), ∥(Y x)∥) → ∥(Π (x : X), Y x)∥).\nProof.\nset (X := Σ (A : Type), ∥(ℬ = A)∥).\nset (x₀ := existT _ ℬ (PT_intro (eq_refl ℬ)):X); simpl in x₀.\nset (Y := λ x, x₀ = x : Type); simpl in Y.\nexists X, Y; intros H1.\napply (@PT_intro_not (∀ x, Y x)).\n intros H2; subst Y; simpl in H2.\n assert (PX : isProp X).\n  intros x y.\n  transitivity x₀; [ symmetry; apply H2 | apply H2 ].\n\n  apply isProp_isSet in PX.\n  destruct equiv_eq_bool_trunc as (f, ((g, Hg), _)).\n  pose proof (PX x₀ x₀ (g bool_eq_bool_id) (g bool_eq_bool_negb)) as s.\n  unfold bool_eq_bool_id, bool_eq_bool_negb in s; simpl in s.\n  apply (ap f) in s.\n  eapply compose in s; [ symmetry in s | eapply invert, Hg ].\n  eapply compose in s; [ symmetry in s | eapply invert, Hg ].\n  apply EqdepFacts.eq_sigT_fst in s.\n  pose proof (hap s false) as H3.\n  revert H3; apply Σ_type2.hott_2_12_6.\n\n apply H1; intros (A, p); subst x₀.\n apply (PT_rec (ℬ = A)); [ | apply PT_eq | assumption ].\n intros q; destruct q.\n apply PT_intro, (Σ_type.pair_eq (eq_refl ℬ)), PT_eq.\nDefined.\n\n(* \"3.9 The principle of unique choice\" *)\n\n(* Lemma 3.9.1 *)\n\nDefinition hott_3_9_1_tac {P} : isProp P → P ≃ ∥P∥.\nProof.\nintros PP.\napply hott_3_3_3; [ assumption | apply PT_eq | apply PT_intro | ].\napply PT_elim; assumption.\nDefined.\n\nDefinition hott_3_9_1 {P} : isProp P → P ≃ ∥P∥ :=\n  λ (PP : isProp P),\n  hott_3_3_3 P ∥P∥ PP (PT_eq P) (PT_intro (A:=P)) (PT_elim PP).\n\n(* \"Corollary 3.9.2 (The principle of unique choice). Suppose a type\n    family P : A → U such that\n         (i) For each x, the type P(x) is a mere proposition, and\n        (ii) For each x we have ∥P(x)∥.\n    Then we have ∏ (x:A) P(x).\" *)\n\nDefinition hott_3_9_2 {A P} :\n  (Π (x : A), isProp (P x)) → (Π (x : A), ∥(P x)∥) → Π (x : A), P x.\nProof.\nintros PP PTP x.\napply PT_elim; [ apply PP | apply PTP ].\nDefined.\n\n(* \"3.10 When are propositions truncated?\" *)\n\n(* \"3.11 Contractibility\" *)\n\nSection Contr.\nImport Σ_type.\n\n(* \"In Lemma 3.3.2 we observed that a mere proposition which is\n    inhabited must be equivalent to 1, and it is not hard to see\n    that the converse also holds.\" *)\n\nDefinition hott_3_3_2_conv P : ∀ x₀ : P, P ≃ ⊤ → isProp P.\nProof.\nintros x₀ H x y.\ndestruct H as (f, ((g, Hg), (h, Hh))).\nunfold \"◦\", \"∼\", id in Hg, Hh.\ndo 2 (rewrite <- Hh; symmetry).\napply ap.\ndestruct (f x), (f y); reflexivity.\nDefined.\n\n(* \"Definition 3.11.1. A type A is *contractible*, or a *singleton*,\n    if there is a : A, called the *center of contraction*, such that\n    a = x for all x : A. We denote the specified path a = x by contr_x.\" *)\n\nDefinition isContr A := Σ (a : A), Π (x : A), a = x.\n\n(* \"Lemma 3.11.3. For a type A, the following are logically\n    equivalent.\n        (i) A is contractible in the sense of Definition 3.11.1.\n       (ii) A is a mere proposition, and there is a point a : A.\n      (iii) A is equivalent to 1.\" *)\n\nDefinition isContr_isProp A : isContr A → isProp A.\nProof.\nintros p x y.\ndestruct p as (a, p).\ntransitivity a; [ symmetry; apply p | apply p ].\nDefined.\n\nDefinition hott_3_11_3_i_ii A : isContr A → isProp A * Σ (a : A), ⊤.\nProof.\nintros p.\nsplit; [ apply isContr_isProp; assumption | ].\ndestruct p as (a, p).\nexists a; constructor.\nDefined.\n\nDefinition hott_3_11_3_ii_iii A : isProp A * (Σ (a : A), ⊤) → A ≃ ⊤.\nProof.\nintros (p, (a, _)).\napply hott_3_3_2; assumption.\nDefined.\n\nDefinition hott_3_11_3_iii_i A : A ≃ ⊤ → isContr A.\nProof.\nintros p.\napply EqStr.equiv_fun in p.\ndestruct p as (f, (g, (Hg, Hh))).\nexists (g I); intros x.\netransitivity; [ | apply Hg ].\ndestruct (f x); reflexivity.\nDefined.\n\n(* \"Lemma 3.11.4. For any type A, the type isContr(A) is a mere\n    proposition.\" *)\n\nDefinition hott_3_11_4 A : isProp (isContr A).\nProof.\nintros c c'.\nassert (isProp A) as r by (apply isContr_isProp; assumption).\ndestruct c as (a, p).\ndestruct c' as (a', p').\nset (q := p a').\napply (pair_eq q).\nunfold transport.\ndestruct q; unfold id.\napply isProp_isSet in r.\napply Π_type.funext; intros x; apply r.\nDefined.\n\n(* \"Corollary 3.11.5. If A is contractible, then so is isContr(A).\" *)\n\nDefinition hott_3_11_5 A : isContr A → isContr (isContr A).\nProof.\nintros c.\napply hott_3_11_3_iii_i, hott_3_11_3_ii_iii.\nsplit; [ apply hott_3_11_4 | ].\nexists c; constructor.\nDefined.\n\n(* \"Lemma 3.11.6. If P : A → U is a type family such that each P(a)\n    is contractible, then ∏ (x:A) P(x) is contractible.\" *)\n\nDefinition hott_3_11_6 {A P} :\n  (Π (a : A), isContr (P a)) → isContr (Π (x : A), P x).\nProof.\nintros p.\nunfold isContr.\nexists (λ a, pr₁ (p a)); intros f.\napply Π_type.funext; intros x.\npose proof p x as q.\napply isContr_isProp in q; apply q.\nDefined.\n\n(* \"Of course, if A is equivalent to B and A is contractible, then so\n    is B.\" *)\n\nDefinition equiv_contr {A B} : A ≃ B → isContr A → isContr B.\nProof.\nintros p q.\napply hott_3_11_3_i_ii, hott_3_11_3_ii_iii in q.\napply quasi_inv in p.\neapply equiv_compose in q; [ | apply p ].\napply hott_3_11_3_iii_i; assumption.\nDefined.\n\n(* \"By definition, a *retraction* is a function r : A → B such that\n    there exists a function s : B → A, called its *section*, and a\n    homotopy : ∏ (y:B) (r(s(y)) = y); then we say that B is a\n    *retract* of A.\" *)\n\nDefinition retraction A B :=\n  Σ (r : A → B), Σ (s : B → A), Π (y : B), (r (s y) = y).\n\nDefinition section {A B} : retraction A B → B → A := λ r, pr₁ (pr₂ r).\n\nDefinition retract A : Type := Σ (B : Type), retraction A B.\n\n(* \"Lemma 3.11.7. If B is a retract of A, and A is contractible, then\n    so is B.\" *)\n\nDefinition hott_3_11_7_tac A B (r : retraction A B) : isContr A → isContr B.\nProof.\nintros p.\ndestruct r as (r, (s, q)).\ndestruct p as (a₀, p).\nexists (r a₀); intros b₀.\neapply compose; [ | apply (q b₀) ].\napply ap, p.\nDefined.\n\nDefinition hott_3_11_7 A B (r : retraction A B) : isContr A → isContr B\n:=\n  λ (p : isContr A),\n  match r with\n  | existT _ r (existT _ s q) =>\n      match p with\n      | existT _ a₀ p =>\n          existT (λ b, ∀ b₀, b = b₀) (r a₀) (λ b₀, ap r (p (s b₀)) • q b₀)\n      end\n  end.\n\n(* \"Lemma 3.11.8. For any A and any a : A, the type Σ (x:A) (a = x)\n    is contractible.\" *)\n\nDefinition hott_3_11_8 {A} : ∀ a : A, isContr (Σ (x : A), a = x).\nProof.\nintros a.\nexists (existT _ a (eq_refl a)).\nintros (x, p).\ndestruct p; reflexivity.\nDefined.\n\n(* \"Lemma 3.11.9. Let P : A → U be a type family.\n      (i) If each P(x) is contractible, then ∑(x:A) P(x) is\n          equivalent to A.\n     (ii) If A is contractible with center a, then ∑(x:A) P(x) is\n          equivalent to P(a).\" *)\n\nDefinition hott_3_11_9_i {A P} :\n  (Π (x : A), isContr (P x)) → (Σ (x : A), P x) ≃ A.\nProof.\nintros p.\nexists pr₁; apply qinv_isequiv.\nexists (λ x, existT _ x (pr₁ (p x))).\nunfold \"◦\", \"∼\", id; simpl.\nsplit; [ reflexivity | intros x ].\ndestruct x as (a, q); simpl.\napply (pair_eq (eq_refl a)); simpl; unfold id.\nassert (isProp (P a)) as H; [ | apply H ].\napply isContr_isProp, p.\nDefined.\n\nDefinition hott_3_11_9_ii_tac {A P} (p : isContr A) (a := pr₁ p) :\n  (Σ (x : A), P x) ≃ P a.\nProof.\nsubst a; destruct p as (a, p); simpl.\nexists (λ q : {x : A & P x}, transport P (p (pr₁ q))⁻¹ (pr₂ q)).\napply qinv_isequiv.\nexists (λ q : P a, existT (λ x : A, P x) a (transport P (p a) q)).\nunfold \"◦\", \"∼\", id; simpl.\nsplit.\n intros x.\n eapply compose; [ apply transport_compose |  ].\n eapply compose; [ apply transport_compat, compose_invert_r | reflexivity ].\n\n intros (b, q); simpl.\n apply (pair_eq (p b)).\n eapply compose; [ apply transport_compose |  ].\n eapply compose; [ apply transport_compose |  ].\n eapply compose; [ apply transport_compat, compose_assoc |  ].\n eapply compose; [ eapply invert, transport_compose | ].\n set (x := (p b)⁻¹).\n set (y := p b).\n destruct y; simpl; subst x; unfold id.\n eapply (@compose _ _ (transport P (eq_refl a) q)); [ | reflexivity ].\n apply hap, ap, compose_invert_l.\nDefined.\n\nDefinition hott_3_11_9_ii {A P} (p : isContr A) (a := pr₁ p) :\n  (Σ (x : A), P x) ≃ P a\n:=\n  let _ := pr₁ p in\n  match p return (Σ (x : A), P x) ≃ P (pr₁ p) with\n  | existT _ a p =>\n      existT isequiv\n        (λ q, transport P (p (pr₁ q))⁻¹ (pr₂ q))\n        (qinv_isequiv (λ q : {x : A & P x}, transport P (p (pr₁ q))⁻¹ (pr₂ q))\n           (existT _\n              (λ q, existT P a (transport P (p a) q))\n              (λ x,\n               transport_compose P (p a) (p a)⁻¹ x\n               • transport_compat (p a • (p a)⁻¹) (eq_refl a)\n                   (compose_invert_r (p a)),\n               λ x,\n               match x return\n                 existT P a\n                   (transport P (p a) (transport P (p (pr₁ x))⁻¹ (pr₂ x)))\n                 = x\n               with\n               | existT _ b q =>\n                   pair⁼ (p b)\n                     (transport_compose P (p a) (p b) (transport P (p b)⁻¹ q)\n                      • transport_compose P (p b)⁻¹ (p a • p b) q\n                      • transport_compat ((p b)⁻¹ • (p a • p b))\n                           ((p b)⁻¹ • p a • p b)\n                           (compose_assoc (p b)⁻¹ (p a) (p b))\n                      • (transport_compose P ((p b)⁻¹ • p a) (p b) q)⁻¹\n                      • match p b as e in (_ = y) return\n                          (∀ q,\n                           transport P e (transport P ((p y)⁻¹ • p a) q) = q)\n                        with\n                        | eq_refl _ =>\n                            hap (ap (transport P) (compose_invert_l (p a)))\n                        end q)\n               end)))\n  end.\n\n(* \"Lemma 3.11.10. A type A is a mere proposition if and only if for\n    all x, y : A, the type x =_{A} y is contractible.\" *)\n\nDefinition hott_3_11_10 {A} : isProp A ⇔ ∀ x y : A, isContr (x = y).\nProof.\nsplit; intros p x y; [ | apply p ].\nexists (p x y); intros q.\ngeneralize p; intros r.\napply isProp_isSet in p.\napply p.\nDefined.\n\nEnd Contr.\n\n(* \"Exercises\" *)\n\n(* \"Exercise 3.1. Prove that if A ≃ B and A is a set, then so is B.\" *)\n\nSection ex_3_1.\nImport Σ_type.\n\nDefinition ex_3_1_tac A B : A ≃ B → isSet A → isSet B.\nProof.\nintros AB SA x y p q.\ndestruct AB as (f, ((g, fg), _)).\napply Π_type.funext in fg.\nassert (r : ∀ p, ap id p = transport (λ u, u x = u y) fg (ap (f ◦ g) p)).\n intros t; destruct fg; reflexivity.\n\n apply (@compose _ _ (ap id p)); [ destruct p; reflexivity | apply invert ].\n apply (@compose _ _ (ap id q)); [ destruct q; reflexivity | ].\n eapply compose; [ apply r | apply invert ].\n eapply compose; [ apply r | apply ap ].\n eapply compose; [ eapply invert | eapply ap_composite ].\n eapply compose; [ | eapply ap_composite ].\n apply ap, SA.\nDefined.\n\nDefinition ex_3_1 A B : A ≃ B → isSet A → isSet B\n:=\n  λ (AB : A ≃ B) (SA : isSet A) (x y : B) (p q : x = y),\n  match AB with\n  | existT _ f (existT _ g fg, _) =>\n      let fg := Π_type.funext fg in\n      let r t :=\n        match fg in (_ = z) return\n          (ap z t = transport (λ u : B → B, u x = u y) fg (ap (f ◦ g) t))\n        with\n        | eq_refl _ =>\n            eq_refl\n              (transport (λ u : B → B, u x = u y) \n                 (eq_refl (f ◦ g)) (ap (f ◦ g) t))\n        end\n      in \n      match p return (p = ap id p) with\n      | eq_refl _ => eq_refl (ap id (eq_refl x))\n      end\n      • r p\n      • ap (transport (λ u : B → B, u x = u y) fg)\n          ((ap_composite g f p)⁻¹\n           • (ap (ap f) (SA (g x) (g y) (ap g q) (ap g p)))⁻¹\n           • ap_composite g f q)\n      • (r q)⁻¹\n      • match q return (ap id q = q) with\n        | eq_refl _ => eq_refl (ap id (eq_refl x))\n        end\n  end.\n\nEnd ex_3_1.\n\n(* \"Exercise 3.2. Prove that if A and B are sets, then so is A + B.\" *)\n\nSection ex_3_2.\nImport Σ_type.\n\nDefinition ex_3_2 {A B} : isSet A → isSet B → isSet (A + B).\nProof.\nintros SA SB x y p q.\ndestruct x as [x| x].\n destruct y as [y| y]; [ | discriminate p ].\n set (e := @Σ_type2.inl_eq_equiv A B x y).\n set (f := pr₁ e).\n set (g := pr₁ (fst (pr₂ e))).\n assert (r : ∀ p, g (f p) = p).\n  intros r; subst f g.\n  destruct e as (f, ((g, Hg), (h, Hh))); simpl in *.\n  pose proof EqStr.quasi_inv_l_eq_r f g h Hg Hh as H.\n  eapply compose; [ apply H | apply Hh ].\n\n  eapply compose; [ eapply invert | apply r ].\n  eapply compose; [ eapply invert | apply r ].\n  apply ap, SA.\n\n destruct y as [y| y]; [ discriminate p | ].\n set (e := @Σ_type2.inr_eq_equiv A B x y).\n set (f := pr₁ e).\n set (g := pr₁ (fst (pr₂ e))).\n assert (r : ∀ p, g (f p) = p).\n  intros r; subst f g.\n  destruct e as (f, ((g, Hg), (h, Hh))); simpl in *.\n  pose proof EqStr.quasi_inv_l_eq_r f g h Hg Hh as H.\n  eapply compose; [ apply H | apply Hh ].\n\n  eapply compose; [ eapply invert | apply r ].\n  eapply compose; [ eapply invert | apply r ].\n  apply ap, SB.\nDefined.\n\nEnd ex_3_2.\n\n(* \"Exercise 3.3. Prove that if A is a set and B : A → U is a type\n    family such that B (x) is a set for all x : A, then ∑ (x:A) B(x)\n    is a set.\" *)\n\n(* already done in 3.1.5 *)\nDefinition ex_3_3 {A B} : isSet A → (Π (x : A), isSet (B x))\n  → isSet (Σ (x : A), B x).\nProof.\nintros SA SB.\napply ex_3_1_5_bis; assumption.\nDefined.\n\n(* \"Exercise 3.4. Show that A is a mere proposition if and only if\n    A → A is contractible.\" *)\n\nDefinition ex_3_4 {A} : isProp A ⇔ isContr (A → A).\nProof.\nsplit; intros p.\n exists id; intros f.\n apply Π_type.funext; intros; apply p.\n\n destruct p as (f, p).\n intros x y.\n set (g := (λ _ : A, x)).\n set (h := (λ _ : A, y)).\n eapply (@compose _ _ (g x)); [ apply eq_refl | destruct (p g) ].\n eapply (@compose _ _ (h x)); [ destruct (p h) | apply eq_refl ].\n apply eq_refl.\nDefined.\n\n(* \"Exercise 3.5. Show that isProp A ≃ (A → isContr A).\" *)\n\nDefinition ex_3_5 {A} : isProp A ≃ (A → isContr A).\nProof.\napply hott_3_3_3.\n apply hott_3_3_5_i.\n\n apply isPropImp, hott_3_11_4.\n\n intros p a.\n exists a; intros b; apply p.\n\n intros f x y.\n destruct (f x) as (a, p).\n destruct (f y) as (b, q).\n eapply compose; [ | apply p ].\n eapply compose; [ | apply q ].\n eapply invert, q.\nDefined.\n\n(* \"Exercise 3.6. Show that if A is a mere proposition, then so is\n     A + (¬A). Thus, there is no need to insert a propositional\n     truncation in (3.4.1).\" *)\n\nDefinition ex_3_6 {A} : isProp A → isProp (A + notT A).\nProof.\nintros SA x y.\ndestruct x as [x| x].\n destruct y as [y| y]; [ apply ap, SA | destruct (y x) ].\n destruct y as [y| y]; [ destruct (x y) | ].\n apply ap, Π_type.funext; intros a; destruct (x a).\nDefined.\n\n(* \"Exercise 3.7. More generally, show that if A and B are mere\n    propositions and ¬(A×B), then A+B is also a mere proposition.\" *)\n\nDefinition ex_3_7 {A B} : isProp A → isProp B → notT (A * B) → isProp (A + B).\nProof.\nintros SA SB NAB x y.\ndestruct x as [x| x].\n destruct y as [y| y]; [ apply ap, SA | destruct (NAB (x, y)) ].\n destruct y as [y| y]; [ destruct (NAB (y, x)) | apply ap, SB ].\nDefined.\n\n(* \"Exercise 3.8. Assuming that some type isequiv(f) satisfies\n    conditions (i)–(iii) of §2.4, show that the type ∥qinv(f)∥\n    satisfies the same conditions and is equivalent to isequiv(f).\" *)\n\nSection ex_3_8.\nImport Σ_type.\n\nDefinition ex_3_8_i {A B} (isequiv : (A → B) → Type) :\n  equiv_prop isequiv\n  → ∀ f : A → B,\n    (qinv f → ∥(qinv f)∥) *\n    (∥(qinv f)∥ → qinv f) *\n    (∀ e₁ e₂ : ∥(qinv f)∥, e₁ = e₂).\nProof.\nintros p f.\npose proof p f as H.\ndestruct H as ((qi, iq), pf).\nsplit; [ | apply PT_eq ].\nsplit; [ apply PT_intro | ].\nintros q.\npose proof (PT_rec (qinv f) (isequiv f) qi pf) as r.\ndestruct r as (h, r).\napply iq, h, q.\nDefined.\n\nDefinition ex_3_8_ii {A B} (isequiv : (A → B) → Type) :\n  equiv_prop isequiv\n  → ∀ f : A → B, isequiv f ≃ ∥(qinv f)∥.\nProof.\nintros p f.\npose proof p f as H.\ndestruct H as ((qi, iq), pf).\npose proof ex_3_8_i isequiv p f as H.\ndestruct H as ((qf, fq), pq).\napply hott_3_3_3.\n intros e₁ e₂; apply pf.\n\n intros e₁ e₂; apply pq.\n\n intros r; apply qf, iq, r.\n\n intros r; apply qi, fq, r.\nDefined.\n\nEnd ex_3_8.\n\n(* \"Exercise 3.9. Show that if LEM holds, then the type\n    Prop : ≡ ∑ (A:U) isProp(A) is equivalent to 2.\" *)\n\nDefinition uip_refl_True : ∀ p : I = I, p = eq_refl I.\nProof.\nintros p; refine (match p with eq_refl _ => _ end); reflexivity.\nDefined.\n\nDefinition ex_3_9 : LEM → (Σ (A : Type), isProp A) ≃ ℬ.\nProof.\nintros lem.\nset\n  (f := λ p : {A : Type & isProp A},\n   match p with\n   | existT _ A PA => match lem A PA with inl _ => true | inr _ => false end\n   end).\nexists f; apply qinv_isequiv.\nset\n  (g x y :=\n   match x return (x = y) with I => match y with I => eq_refl I end end).\nset (h (x y : ⊥) := match x return x = y with end).\nexists\n  (λ b : bool,\n   if b then existT (λ A : Type, isProp A) ⊤ g\n   else existT (λ A : Type, isProp A) ⊥ h).\nunfold \"◦\", \"∼\", id; simpl.\nsplit.\n intros b; destruct b; simpl.\n  destruct (lem ⊤ g) as [x| x]; [ apply eq_refl | destruct x; constructor ].\n  destruct (lem ⊥ h) as [x| x]; [ destruct x | reflexivity ].\n\n intros (A, PA); simpl.\n destruct (lem A PA) as [a| b].\n  assert (p : ⊤ ≃ A) by (apply quasi_inv, hott_3_3_2; [ apply PA | apply a]).\n  eapply (Σ_type.pair_eq (ua p)).\n  destruct (ua p); simpl; unfold id; simpl.\n  apply Π_type.funext; intros x.\n  apply Π_type.funext; intros y.\n  destruct x, y.\n  subst g; simpl.\n  set (u := PA I I); simpl in u.\n  refine (match u with eq_refl _ => _ end).\n  apply eq_refl.\n\n  assert (p : ⊥ ≃ A).\n   exists (λ a : ⊥, match a with end); apply qinv_isequiv; exists b.\n   unfold \"◦\", \"∼\", id.\n   split; [ intros a; destruct (b a) | intros x; destruct x ].\n\n   eapply (Σ_type.pair_eq (ua p)).\n   destruct (ua p); simpl; unfold id; simpl.\n   apply Π_type.funext; intros x; destruct x.\nDefined.\n\n(* \"Exercise 3.10. Show that if U_{i+1} satisfies LEM, then the\n    canonical inclusion Prop_{U_{i}} → Prop_{U+{i+1}} is an\n    equivalence.\" *)\n\n(* don't know how to define Prop_{i} in Coq... *)\n\n(* \"Exercise 3.11. Show that it is not the case that for all A : U we\n    have ∥A∥ → A. (However, there can be particular types for which\n    ∥A∥ → A. Exercise 3.8 implies that qinv (f) is such.)\" *)\n\n(* With the recursion principle of ∥A∥ (§3.7) that we defined as\n   \"PT_rec\", we can define the case A≡B and f≡id, resulting on the\n   existence of the function g of type isProp A → ∥A∥ → A. Therefore,\n   if A is a mere proposition, we indeed have ∥A∥ → A. We named\n   this particular case \"PT_elim\". *)\n\n(* and since ∥qinv f∥ ≃ isequiv f (exercise 3.8), there is a function\n   of type ∥qinv f∥ → isequiv f. But by the property (ii) of isequiv\n   in §2.4, we have isequiv f → qinv f. So ∥qinv f∥ → qinv f. *)\n\n(* \"Exercise 3.12. Show that if LEM holds, then for all A : U we have\n    ∥(∥A∥ → A)∥. (This property is a very simple form of the axiom of\n    choice, which can fail in the absence of LEM; see [KECA13].)\" *)\n\n(* very strange proof; in the case when A is not a mere proposition,\n   we artifially create an element of A by the following steps:\n   - using LEM to save the opposite of the goal in the hypotheses, as H\n   - the new goal is then the contradiction ⊥\n   - putting isProp A as new goal by applying notT (isProp A)\n   - introducing then x et y as elements of A\n   - setting it is a contradiction (exfalso)\n   - putting H back as goal\n   Since we have values of type A, x and y, in the hypotheses, we can\n   prove A, therefore ∥A∥→A, therefore ∥(∥A∥→A)∥. *)\n\nDefinition ex_3_12_tac : LEM → ∀ A, ∥(∥A∥ → A)∥.\nProof.\nintros lem A.\npose proof hott_3_3_5_i A as PPA.\npose proof lem (isProp A) PPA as H.\ndestruct H as [PA| NPA]; [ apply PT_intro, PT_elim, PA; assumption | ].\npose proof lem _ (PT_eq (∥A∥ → A)) as H.\ndestruct H as [H| H]; [ apply H | exfalso ].\napply NPA; intros x y.\nexfalso; apply H.\napply PT_intro; intros; apply x.\nDefined.\n\nDefinition ex_3_12 : LEM → ∀ A, ∥(∥A∥ → A)∥ :=\n  λ (lem : LEM) (A : Type),\n  match lem (isProp A) (hott_3_3_5_i A) with\n  | inl PA => PT_intro (PT_elim PA)\n  | inr NPA =>\n      match lem ∥(∥A∥ → A)∥ (PT_eq (∥A∥ → A)) with\n      | inl H => H\n      | inr H =>\n          match NPA (λ x y, match H (PT_intro (λ _, x)) with end) with end\n      end\n  end.\n\n(* \"Exercise 3.13. We showed in Corollary 3.2.7 that the following\n    naive form of LEM is inconsistent with univalence:\n                 Π (A : U) (A + (¬A))\n    In the absence of univalence, this axiom is consistent. However,\n    show that it implies the axiom of choice (3.8.1).\" *)\n\n(* according to hott_3_8_2, AC ≃ AC_3_8_3, but hott_3_8_2 uses ua *)\n(* according to AC_equiv_3_8_3_equiv, AC ≃ AC_3_8_3_equiv, but\n   AC_equiv_3_8_3_equiv uses AC_3_8_3 that uses ua *)\n\n(* So this exercise, which is said to be in a context where univalence\n   is not set, is not allowed to use these lemmas; the definition of\n   AC must remain the initial one. *)\n\nDefinition ex_3_13_tac : (Π (A : Type), A + notT A) → AC.\nProof.\nintros lem.\nintros X A P SX SA PXA T.\nclear SX SA PXA. (* not used hypotheses *)\napply PT_intro.\nexists\n   (λ (x : X),\n    match lem (Σ (a : A x), P x a) with\n    | inl (existT _ a _) => a\n    | inr p => match PT_intro_not p (T x) with end\n    end).\nintros x.\ndestruct (lem (Σ (a : A x), P x a)) as [(a, p)| p]; [ apply p | ].\ndestruct (PT_intro_not p (T x)).\nDefined.\n\nDefinition ex_3_13 : (Π (A : Type), A + notT A) → AC\n:=\n  λ lem X A P _ _ _ T,\n  PT_intro\n    (existT (λ g : ∀ x : X, A x, ∀ x : X, P x (g x))\n       (λ x : X,\n        match lem {a : A x & P x a} with\n        | inl (existT _ a _) => a\n        | inr p => match PT_intro_not p (T x) return (A x) with end\n        end)\n       (λ (x : X),\n        let s := lem {a : A x & P x a} in\n        match s return\n          (P x\n             match s with\n             | inl (existT _ a _) => a\n             | inr p => match PT_intro_not p (T x) return (A x) with end\n             end)\n        with\n        | inl (existT _ a p) => p\n        | inr p => match PT_intro_not p (T x) with end\n        end)).\n\n(* \"Exercise 3.14. Show that assuming LEM, the double negation ¬¬A\n    has the same universal property as the propositional truncation\n    ∥A∥, and is therefore equivalent to it. Thus, under LEM, the\n    propositional truncation can be defined rather than taken as a\n    separate type former.\" *)\n\n(*\nPT_intro: ∀ A : Type, A → ∥A∥\nPT_eq: ∀ A : Type, isProp ∥A∥\nPT_rec:\n  ∀ (A B : Type) (f : A → B),\n  isProp B → Σ (g : ∥A∥ → B), ∀ a : A, g (PT_intro a) = f a\n*)\n\nDefinition DN_intro {A} : A → notT (notT A).\nProof.\nintros a p; destruct (p a).\nDefined.\n\n(* no need to LEM, but uses function extensionality *)\nDefinition DN_eq₀ {A} : isProp (notT (notT A)).\nProof.\nintros x y.\napply Π_type.funext; intros a; destruct (x a).\nDefined.\n\nDefinition DN_eq : LEM → ∀ A : Type, isProp (notT (notT A)).\nProof.\nintros lem A x y.\nunfold LEM in lem.\ndestruct (lem _ (hott_3_3_5_i A)) as [p| p].\n apply (isPropNot (isPropNot p)).\n\nAbort. (* blocked; perhaps DN_eq₀ is the only solution? *)\n\nDefinition DN_rec : LEM\n  → ∀ A B (f : A → B), isProp B\n  → Σ (g : notT (notT A) → B), ∀ a, g (DN_intro a) = f a.\nProof.\nintros lem A B f PB.\nunfold LEM in lem.\ndestruct (lem _ (hott_3_3_5_i A)) as [PA| NPA].\n destruct (lem A PA) as [a| na].\n  exists (λ _, f a).\n  intros a'; apply PB.\n\n  exists (λ nna : notT (notT A), match nna na return B with end).\n  intros a; destruct (na a).\n\n destruct (lem B PB) as [b| nb].\n  exists (λ _, b).\n  intros a; apply PB.\n\n  exfalso; apply NPA; intros a.\n  destruct (nb (f a)).\nDefined.\n\nDefinition ex_3_14 : LEM → ∀ A, notT (notT A) ≃ ∥A∥.\nProof.\nintros lem A.\ndestruct (lem _ (hott_3_3_5_i A)) as [PA| NPA].\n exists (λ p, PT_intro (pr₁ LEM_LDN lem A PA p)); apply qinv_isequiv.\n exists (λ p q, q (Σ_type.pr₁ (PT_rec A A id PA) p)); simpl.\n split; [ intros x; apply PT_eq | ].\n intros f; apply Π_type.funext; intros x; destruct (f x).\n\n assert (f : notT (notT A) → ∥A∥).\n  intros nna.\n  apply PT_intro.\n  unfold LEM in lem.\n  (* wrong if A is not a Prop; cf 3.2.2 *)\nAbort.\n\n(* version where hypothesis \"isProp A\" has been added *)\n(* but not satisfactory since when A is a mere proposition, ∥A∥ is\n   not interesting at all *)\nDefinition ex_3_14_not_satis : LEM → ∀ A, isProp A → (notT (notT A) ≃ ∥A∥).\nProof.\nintros HLEM A HPA.\nexists (λ p, PT_intro (pr₁ LEM_LDN HLEM A HPA p)); apply qinv_isequiv.\nexists (λ p q, q (Σ_type.pr₁ (PT_rec A A id HPA) p)); simpl.\nsplit; [ intros x; apply PT_eq | ].\nintros f; apply Π_type.funext; intros x; destruct (f x).\nDefined.\n\n(* version with naive version of LEM, instead of normal LEM *)\nDefinition ex_3_14 : (Π (A : Type), A + notT A) → ∀ A, notT (notT A) ≃ ∥A∥.\nProof.\nintros lem A.\nexists\n  (λ nna : notT (notT A),\n   PT_intro\n     (match lem A with\n      | inl a => a\n      | inr na => match nna na return A with end\n      end)).\napply qinv_isequiv.\nexists\n  (λ (x : ∥A∥),\n   match lem A with\n   | inl a => λ (na : notT A), match na a with end\n   | inr na => match PT_intro_not na x with end\n   end).\nunfold \"◦\", \"∼\", id; simpl.\nsplit.\n intros x.\n destruct (lem A) as [a| na]; [ apply PT_eq | ].\n destruct (PT_intro_not na x).\n\n intros nna.\n destruct (lem A) as [a| na]; [ | destruct (nna na) ].\n apply Π_type.funext; intros na; destruct (nna na).\nDefined.\n\n(* \"Exercise 3.15. Show that if we assume propositional resizing as in\n    §3.5, then the type\n          Π (P : Prop), (A → P) → P\n    has the same universal property as ∥A∥. Thus, we can also define\n    the propositional truncation in this case.\" *)\n\n(*\nPT_intro: ∀ A : Type, A → ∥A∥\nPT_eq: ∀ A : Type, isProp ∥A∥\nPT_rec:\n  ∀ (A B : Type) (f : A → B),\n  isProp B → Σ (g : ∥A∥ → B), ∀ a : A, g (PT_intro a) = f a\n*)\n\nDefinition APP A := Π (P : Type), isProp P → (A → P) → P.\n\nDefinition APP_intro {A} : A → APP A.\nProof.\nintros a P PP p; apply p, a.\nDefined.\n\nDefinition APP_eq {A} : isProp (APP A).\nProof.\nintros f g.\napply Π_type.funext; intros P.\napply Π_type.funext; intros PP.\napply Π_type.funext; intros h.\napply PP.\nDefined.\n\nDefinition APP_rec {A B} (f : A → B) :\n  isProp B → Σ (g : APP A → B), ∀ a : A, g (APP_intro a) = f a.\nProof.\nintros PB.\nexists (λ (g : APP A), g B PB f).\nintros a; apply eq_refl.\nDefined.\n\nDefinition ex_3_15 {A} : APP A ≃ ∥A∥.\nProof.\nexists (λ g : APP A, g ∥A∥ (PT_eq A) (@PT_intro A)).\napply qinv_isequiv.\nassert (∥A∥ → APP A) as g.\n intros x P PP i.\n exfalso; revert x.\n pose proof (@APP_rec P P id PP) as R.\n destruct R as (h, R); unfold id in R.\n (* Seems not working; perhaps they are not equivalent? This is indeed\n    possible, since the wording of this exercise does not say they are. *)\nAbort.\n\n(* \"Exercise 3.16. Assuming LEM, show that double negation commutes\n    with universal quantification of mere propositions over sets. That\n    is, show that if X is a set and each Y(x) is a mere proposition,\n    then LEM implies\n          (Π (x:X) ¬¬Y(x)) ≃ ¬¬ (Π (x:X) Y(x))\n    Observe that if we assume instead that each Y(x) is a set, then\n    (3.11.11) becomes equivalent to the axiom of choice (3.8.3).\" *)\n\nSection ex_3_16.\nImport Σ_type.\n\nDefinition ex_3_16_i {X Y} : isSet X → (Π (x : X), isProp (Y x))\n  → LEM → (Π (x : X), notT (notT (Y x))) ≃ notT (notT (Π (x : X), Y x)).\nProof.\nintros SX PY lem.\napply hott_3_3_3.\n apply ex_3_6_2; intros x; apply isPropNot, isPropNot, PY.\n\n apply isPropNot, isPropNot, ex_3_6_2, PY.\n\n intros NNY NY; apply NY; intros x.\n destruct (lem (Y x) (PY x)) as [p| p]; [ apply p | ].\n destruct (NNY x p).\n\n intros NNY x q; apply q.\n destruct (lem (Y x) (PY x)) as [p| p]; [ apply p | ].\n exfalso; apply NNY; intros r.\n destruct (p (r x)).\nDefined.\n\nDefinition ex_3_16_ii :\n  LEM\n  → (∀ X Y, isSet X → (Π (x : X), isSet (Y x))\n     → (Π (x : X), notT (notT (Y x))) ≃ notT (notT (Π (x : X), Y x)))\n    ≃ AC_3_8_3.\nProof.\nintros lem.\n(*\nassert\n  ((∀ X Y, isSet X → (Π (x : X), isSet (Y x))\n    → (Π (x : X), notT (notT (Y x))) ≃ notT (notT (Π (x : X), Y x)))\n   → AC_3_8_3) as ffff.\n intros p X Y SX SY q.\n destruct (lem _ (PT_eq (∀ x : X, Y x))) as [r| r]; [ apply r | ].\n exfalso; apply r, PT_intro; intro x.\n destruct (lem _ (hott_3_3_5_i (Y x))) as [PY| NPY].\n  apply PT_elim; [ apply PY | apply q ].\n\n  assert (s : ∀ x : X, notT (notT (Y x))).\n   intros x' nx'.\n   apply PT_intro_not in nx'.\n   destruct (nx' (q x')).\n\n   pose proof pr₁ (p X Y SX SY) s as t.\n   exfalso; apply t; intros u.\n   apply r, PT_intro, u.\nShow Proof.\n*)\nexists\n  (λ p X Y SX SY q,\n   match lem ∥(∀ x : X, Y x)∥ (PT_eq (∀ x : X, Y x)) with\n   | inl r => r\n   | inr r =>\n       match\n         (r\n            (PT_intro\n               (λ x,\n                match lem (isProp (Y x)) (hott_3_3_5_i (Y x)) with\n                | inl PY => PT_elim PY (q x)\n                | inr _ =>\n                    match\n                      (((pr₁ (p X Y SX SY)\n                           (λ x' nx',\n                            match PT_intro_not nx' (q x') return ⊥ with end)\n                           (λ u, r (PT_intro u)))) : ⊥)\n                    with end\n                end)))\n       with end\n   end).\napply qinv_isequiv.\nassert\n  (AC_3_8_3\n   → (∀ X Y, isSet X → (Π (x : X), isSet (Y x))\n     → (Π (x : X), notT (notT (Y x))) ≃ notT (notT (Π (x : X), Y x))))\n  as gggg.\n intros ac X Y SX SY.\n pose proof ac X Y SX SY as p.\n assert (isProp (∀ x : X, ∥(Y x)∥)) as q.\n  apply ex_3_6_2; intros x; apply PT_eq.\n\n  destruct (lem (∀ x : X, ∥(Y x)∥) q) as [r| r].\n   pose proof p r as s.\n(*\n   assert ((∀ x : X, notT (notT (Y x))) → notT (notT (∀ x : X, Y x))) as ffff.\n    intros t u; apply u; intros x.\n    apply PT_intro_not in u; destruct (u s).\n   Show Proof.\n*)\n   exists (λ _ u, u (λ x, match PT_intro_not u s with end)).\n   apply qinv_isequiv.\n(*\n   assert (notT (notT (∀ x : X, Y x)) → (∀ x : X, notT (notT (Y x)))) as ffff.\n    intros t x u; apply u.\n    apply PT_intro_not in u; destruct (u (r x)).\n   Show Proof.\n*)\n   exists (λ _ x u, u (match PT_intro_not u (r x) with end)).\n   unfold \"◦\", \"∼\", id; simpl.\n   split.\n    intros x; apply Π_type.funext; intros nx; destruct (x nx).\n\n    intros f; apply Π_type.funext; intros x.\n    apply Π_type.funext; intros nx; destruct (f x nx).\n\n   assert ((∀ x : X, notT (notT (Y x))) → notT (notT (∀ x : X, Y x))) as ffff.\n    intros t u; apply u; intros x.\n    pose proof t x as v.\n    exfalso; apply v; intros w.\n(* well, the proof seems not trivial; it is perhaps the reason why the\n   wording of this exercise says \"observe that\" instead of \"prove that\";\n   I give up. *)\nAbort.\n\nEnd ex_3_16.\n\n(* \"Exercise 3.17. Show that the rules for the propositional\n    truncation given in §3.7 are sufficient to imply the following\n    induction principle: for any type family B:∥A∥→U such that each\n    B(x) is a mere proposition, if for every a:A we have B(|a|), then\n    for every x:∥A∥ we have B(x).\" *)\n\nDefinition ex_3_17 A B : (Π (x : ∥A∥), isProp (B x))\n  → (Π (a : A), B (PT_intro a)) → (Π (x : ∥A∥), B x).\nProof.\nintros PB BA x.\nassert (f : A → B x).\n intros a.\n pose proof BA a as s.\n destruct (PT_eq _ x (PT_intro a)); apply s.\n\n destruct (PT_rec A (B x) f (PB x)) as (g, s).\n apply g, x.\nDefined.\n\n(* \"Exercise 3.18. Show that the law of excluded middle (3.4.1) and\n    the law of double negation (3.4.2) are logically equivalent.\" *)\n\n(* already done *)\nDefinition ex_3_18 : LEM ⇔ LDN.\nProof. apply LEM_LDN. Defined.\n\n(* \"Exercise 3.19. Suppose P:ℕ→U is a decidable family of mere\n    propositions. Prove that\n         ∥Σ (n:ℕ) P(n)∥ → Σ (n:ℕ) P(n).\" *)\n\n(* return 0 if not enough iterations, else S n for n *)\nFixpoint first_such_that P (DP : isDecidableFamily ℕ P) m n :=\n  match m with\n  | 0 => 0\n  | S m' =>\n      match DP n with\n      | inl _ => S n\n      | inr _ => first_such_that P DP m' (S n)\n      end\n  end.\n\nDefinition first_such_that_prop P (DP : isDecidableFamily ℕ P) m n a :\n  first_such_that P DP (S n) a = S m\n  → P m * ∀ b, a ≤ b → b < m → notT (P b).\nProof.\nintros p; simpl in p.\ndestruct (DP a) as [q| q].\n injection p; intros; subst a.\n split; [ apply q | intros b Ha Hb ].\n apply Nat.nlt_ge in Ha; destruct (Ha Hb).\n\n revert m a p q.\n induction n; intros; [ discriminate p | simpl in p ].\n destruct (DP (S a)) as [r| r].\n  injection p; intros; subst m.\n  split; [ apply r | intros b Ha Hb ].\n  apply Nat.succ_le_mono, Nat.le_antisymm in Hb; [ | apply Ha ].\n  destruct Hb; apply q.\n\n  eapply IHn in p; [ | apply r ].\n  destruct p as (p, s).\n  split; [ apply p | intros b Ha Hb ].\n  destruct (le_dec (S a) b) as [t| t].\n   apply s; [ apply t | apply Hb ].\n\n   apply Nat.nle_gt in t.\n   apply Nat.succ_le_mono, Nat.le_antisymm in t; [ | apply Ha ].\n   destruct t; apply q.\nDefined.\n\nDefinition no_first_such_that_prop P (DP : isDecidableFamily ℕ P) n a :\n  first_such_that P DP (S n) a = 0\n  → notT (P (a + n)).\nProof.\nintros p; simpl in p.\ndestruct (DP a) as [q| q]; [ discriminate p | ].\nrevert a p q.\ninduction n; intros; [ rewrite Nat.add_0_r; apply q | ].\nsimpl in p.\ndestruct (DP (S a)) as [r| r]; [ discriminate p | ].\nrewrite <- Nat.add_succ_comm.\napply IHn; [ apply p | apply r ].\nDefined.\n\nDefinition smallest_such_that P : isDecidableFamily ℕ P\n  → (Σ (n : ℕ), P n)\n  → (Σ (n : ℕ), (P n * ∀ m, m < n → notT (P m))%type).\nProof.\nintros DP (n, p).\nremember (first_such_that P DP (S n) 0) as x eqn:Hx; symmetry in Hx.\ndestruct x as [| m].\n apply no_first_such_that_prop in Hx; destruct (Hx p).\n\n exists m; apply first_such_that_prop in Hx.\n destruct Hx as (q, r); split; [ apply q | intros a Ha ].\n apply r; [ apply Nat.le_0_l | apply Ha ].\nDefined.\n\nDefinition isProp_first_such_that P (PP : Π (n : ℕ), isProp (P n)) :\n  isProp (Σ (n : ℕ), (P n * (∀ m : ℕ, m < n → notT (P m)))%type).\nProof.\nintros q r.\ndestruct q as (m, (pm, q)).\ndestruct r as (n, (pn, r)).\ndestruct (lt_eq_lt_dec m n) as [[Hmn| Hmn] | Hmn].\n destruct (r m Hmn pm).\n\n subst m.\n apply (Σ_type.pair_eq (eq_refl n)); simpl; unfold id.\n apply split_pair_eq.\n split; [ apply PP | ].\n apply Π_type.funext; intros m.\n apply Π_type.funext; intros s.\n apply isPropNot, PP.\n\n destruct (q n Hmn pn).\nDefined.\n\nDefinition ex_3_19_tac P : isDecidableFamily ℕ P\n  → (Π (n : ℕ), isProp (P n))\n  → ∥(Σ (n : ℕ), P n)∥\n  → Σ (n : ℕ), P n.\nProof.\nintros DP PP p.\nset (A := Σ (n : ℕ), P n) in p |-*.\nset (B := Σ (n : ℕ), (P n * (∀ m : ℕ, m < n → notT (P m)))%type).\nset (f := smallest_such_that P DP : A → B).\nset (PB := isProp_first_such_that P PP : isProp B).\nset (g := Σ_type.pr₁ (PT_rec A B f PB)).\ndestruct (g p) as (n, (pn, _)).\nexists n; apply pn.\nDefined.\n\nDefinition ex_3_19 P : isDecidableFamily ℕ P\n  → (Π (n : ℕ), isProp (P n))\n  → ∥(Σ (n : ℕ), P n)∥\n  → Σ (n : ℕ), P n\n:=\n  λ DP PP p,\n  let f := smallest_such_that P DP in\n  let PB := isProp_first_such_that P PP in\n  match Σ_type.pr₁ (PT_rec _ _ f PB) p with\n  | existT _ n (pn, _) => existT P n pn\n  end.\n\n(* \"Exercise 3.20. Prove Lemma 3.11.9(ii): if A is contractible with\n    center a, then Σ (x:A) P(x) is equivalent to P(a).\" *)\n\n(* already done: see hott_3_11_9_ii *)\n\n(* \"Exercise 3.21. Prove that isProp(P) ≃ (P ≃ ∥P∥).\" *)\n\nDefinition ex_3_21 P : isProp P ≃ (P ≃ ∥P∥).\nProof.\napply hott_3_3_3.\n apply hott_3_3_5_i.\n\n intros p q.\n destruct p as (f, p).\n destruct q as (g, q).\n assert (PP : isProp (P → ∥P∥)) by (apply isPropImp, PT_eq).\n assert (f = g) by apply PP; subst g.\n destruct (equivalence_isequiv f) as (r, s).\n assert (p = q) by apply s; subst q.\n reflexivity.\n\n apply hott_3_9_1.\n\n intros p q r.\n destruct p as (f, (_, (h, Hh))).\n unfold \"◦\", \"∼\", id in Hh.\n eapply compose; [ eapply invert | apply Hh ].\n eapply compose; [ eapply invert | apply Hh ].\n apply ap, PT_eq.\nDefined.\n\n(* \"Exercise 3.22. As in classical set theory, the finite version of\n    the axiom of choice is a theorem. Prove that the axiom of choice\n    (3.8.1) holds when X is a finite type Fin(n) (as defined in\n    Exercise 1.9).\" *)\n\nDefinition Fin_succ_equiv : ∀ n, Fin (S n) ≃ Fin n + ⊤.\nProof.\nintros n.\nexists\n  (λ (p : Fin (S n)),\n   match p with\n   | elem _ i _ =>\n       match lt_dec i n with\n       | left p => inl (elem n i p)\n       | right _ => inr I\n       end\n   end).\napply qinv_isequiv.\nexists\n  (λ p : Fin n + ⊤,\n   match p with\n   | inl (elem _ i ilt) => elem (S n) i (Nat.lt_lt_succ_r i n ilt)\n   | inr _ => elem (S n) n (Nat.lt_succ_diag_r n)\n   end).\nunfold \"◦\", \"∼\", id; simpl.\nsplit.\n intros [ (i, ilt) | x].\n  destruct (lt_dec i n) as [p| p]; [ | destruct (p ilt) ].\n  apply ap, ap, le_unique.\n\n  destruct (lt_dec n n) as [p| p]; [ | destruct x; apply eq_refl ].\n  exfalso; revert p; apply Nat.lt_irrefl.\n\n intros (i, ilt).\n destruct (lt_dec i n) as [p| p]; [ apply ap, le_unique | ].\n apply Nat.nlt_ge, Nat.succ_le_mono in p.\n apply Nat.le_antisymm in p; [ | apply ilt ].\n apply Nat.succ_inj in p; subst i.\n apply ap, le_unique.\nDefined.\n\nDefinition isSet_Fin : ∀ n, isSet (Fin n).\nProof.\nintros n.\ninduction n.\n intros x y p q.\n destruct x as (i, ilt).\n exfalso; clear p q; apply Nat.nlt_0_r in ilt; destruct ilt.\n\n eapply ex_3_1; [ eapply quasi_inv, Fin_succ_equiv | ].\n eapply ex_3_2; [ apply IHn | apply isSet_True ].\nDefined.\n\nDefinition Fin_x n := elem (S n) n (Nat.lt_succ_diag_r n).\n\nDefinition PT_and_elim A B : ∥(A * B)∥ → ∥A∥ * ∥B∥.\nProof.\nintros p.\nsplit.\n set (q := PT_rec (A * B) ∥A∥ (λ p, PT_intro (fst p)) (PT_eq _)).\n destruct q as (g, q); apply g, p.\n\n set (q := PT_rec (A * B) ∥B∥ (λ p, PT_intro (snd p)) (PT_eq _)).\n destruct q as (g, q); apply g, p.\nDefined.\n\nDefinition PT_and_intro A B : ∥A∥ → ∥B∥ → ∥(A * B)∥.\nProof.\nintros x y.\nassert (f : A → ∥(A * B)∥).\n intros a.\n assert (f : B → ∥(A * B)∥) by (intros b; apply PT_intro; split; assumption).\n set (r := PT_rec B ∥(A * B)∥ f (PT_eq _)).\n destruct r as (g, r); apply g, y.\n\n set (r := PT_rec A ∥(A * B)∥ f (PT_eq _)).\n destruct r as (g, r); apply g, x.\nDefined.\n\nDefinition PT_and_equiv A B : ∥(A * B)∥ ≃ ∥A∥ * ∥B∥.\nProof.\napply hott_3_3_3.\n apply PT_eq.\n\n apply ex_3_6_1; apply PT_eq.\n\n apply PT_and_elim.\n\n intros (x, y).\n apply PT_and_intro; assumption.\nDefined.\n\nDefinition ex_3_22_Fin_0 : ACX (Fin 0).\nProof.\nintros A P SX SA PP T.\napply PT_intro.\nassert (g : ∀ x : Fin 0, A x).\n destruct x as (n, nlt); destruct (Nat.nlt_0_r n nlt).\n\n exists g; intros x.\n destruct x as (n, nlt); destruct (Nat.nlt_0_r n nlt).\nDefined.\n\nDefinition and_imp A B C : (A → B) → (A * C → B * C)%type.\nProof.\nintros p (a, c).\nsplit; [ apply p, a | apply c ].\nDefined.\n\nDefinition ex_3_22 n : ACX (Fin n).\nProof.\nintros A P SX SA PP T.\nrevert A P SX SA PP T.\ninduction n; intros; [ apply ex_3_22_Fin_0; assumption |  ].\nset\n (An :=\n  λ x : Fin n,\n  match x with\n  | elem _ i lti => A (elem (S n) i (Nat.lt_lt_succ_r i n lti))\n  end).\nset\n (Pn :=\n  λ x : Fin n,\n  match x return (An x → Type) with\n  | elem _ i ilt => P (elem (S n) i (Nat.lt_lt_succ_r i n ilt))\n  end).\npose proof\n (λ x : Fin n,\n  match x return (isSet (An x)) with\n  | elem _ i ilt => SA (elem (S n) i (Nat.lt_lt_succ_r i n ilt))\n  end) as SAn.\npose proof\n (λ x : Fin n,\n  match x return (∀ a : An x, isProp (Pn x a)) with\n  | elem _ i ilt => PP (elem (S n) i (Nat.lt_lt_succ_r i n ilt))\n  end) as PPn.\npose proof\n (λ x : Fin n,\n  match x return ∥{a : An x & Pn x a}∥ with\n  | elem _ i ilt => T (elem (S n) i (Nat.lt_lt_succ_r i n ilt))\n  end) as Tn.\nassert\n (H1 : (Π (x : Fin (S n)), ∥(Σ (a : A x), P x a)∥) ≃\n  (Π (x : Fin (n)), ∥(Σ (a : An x), Pn x a)∥) *\n   ∥(Σ (a : A (Fin_x n)), P (Fin_x n) a)∥).\n apply hott_3_3_3.\n  apply ex_3_6_2; intros x; apply PT_eq.\n\n  apply ex_3_6_1; [ apply ex_3_6_2; intros y; apply PT_eq | apply PT_eq ].\n\n  intros p.\n  split; [ intros y; apply Tn | apply T ].\n\n  intros (p, q); apply T.\n\n eapply ua in H1.\n pose proof (IHn An Pn (isSet_Fin n) SAn PPn) as p.\n apply and_imp with (C := ∥{a : A (Fin_x n) & P (Fin_x n) a}∥) in p.\n  destruct p as (p, q).\n  eapply PT_and_intro in p; [ clear q | apply q ].\n  set\n   (A₀ :=\n    ({a : A (Fin_x n) & P (Fin_x n) a} *\n     {g : ∀ x : Fin n, An x & ∀ x : Fin n, Pn x (g x)})%type).\n  set (B₀ := ∥{g : ∀ x : Fin (S n), A x & ∀ x : Fin (S n), P x (g x)}∥).\n  assert (f₀ : A₀ → B₀).\n   intros ((an, q), (g, r)); subst B₀; apply PT_intro.\n   set\n    (h :=\n     λ x : Fin (S n),\n     match x as f return (A f) with\n     | elem _ i ilt =>\n         let s1 := lt_dec i n in\n         match s1 with\n         | left H3 =>\n             let x0 := g (elem n i H3) in\n             transport A\n               (ap (elem (S n) i)\n                  (le_unique (S i) (S n) (Nat.lt_lt_succ_r i n H3) ilt)) x0\n         | right H3 =>\n             (λ H : ∀ n1 m : ℕ, ¬ n1 < m → m ≤ n1,\n              (λ H4 : n ≤ i,\n               (λ H0 : ∀ n1 m : ℕ, n1 ≤ m → S n1 ≤ S m,\n                (λ H5 : S n ≤ S i,\n                 (λ H6 : S i = S n,\n                  (λ H7 : i = n,\n                   eq_rect_r\n                     (λ i0 : ℕ, ∀ ilt0 : i0 < S n, A (elem (S n) i0 ilt0))\n                     (λ ilt0 : n < S n,\n                      transport A\n                        (ap (elem (S n) n)\n                           (le_unique (S n) (S n) (Nat.lt_succ_diag_r n) ilt0))\n                        an) H7 ilt) (Nat.succ_inj i n H6))\n                   (Nat.le_antisymm (S i) (S n) ilt H5))\n                  (H0 n i H4))\n                 (λ n1 m : ℕ,\n                  match Nat.succ_le_mono n1 m with\n                  | conj x0 _ => x0\n                  end)) (H i n H3))\n               (λ n1 m : ℕ, match Nat.nlt_ge n1 m with\n                            | conj x0 _ => x0\n                            end)\n         end\n     end).\n   exists h.\n   intros (i, ilt); subst h; simpl.\n   destruct (lt_dec i n) as [H2| H2].\n    unfold Fin_x in q.\n    set (x := r (elem n i H2)).\n    unfold Pn in x; simpl in x.\n    unfold transport.\n    destruct\n     (ap (elem (S n) i) (le_unique (S i) (S n) (Nat.lt_lt_succ_r i n H2) ilt)).\n    apply x.\n\n    unfold eq_rect_r; simpl.\n    unfold eq_rect; simpl.\n    destruct\n     (eq_sym\n        (Nat.succ_inj i n\n           (Nat.le_antisymm (S i) (S n) ilt\n              (match Nat.succ_le_mono n i with\n               | conj x0 _ => x0\n               end (match Nat.nlt_ge i n with\n                    | conj x0 _ => x0\n                    end H2))))).\n    unfold transport; simpl.\n    destruct\n     (ap (elem (S n) n) (le_unique (S n) (S n) (Nat.lt_succ_diag_r n) ilt)).\n    apply q.\n\n   pose proof (PT_rec A₀ B₀ f₀ (PT_eq _)) as q.\n   destruct q as (g, q).\n   apply g, p.\n\n  split; [ intros x; apply Tn | apply T ].\nDefined.\n", "meta": {"author": "roglo", "repo": "mycoqhott", "sha": "406068f6fe9893baf32d3eaf13759318c6871fc7", "save_path": "github-repos/coq/roglo-mycoqhott", "path": "github-repos/coq/roglo-mycoqhott/mycoqhott-406068f6fe9893baf32d3eaf13759318c6871fc7/chap3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580952177051, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.6541814409664194}}
{"text": "Require Import Reals.\nLocal Open Scope R_scope.\nFrom ValidSDP Require Import validsdp.\n\nLet p (x0 x1 x2 x3 x4 x5 : R) :=\n  (0 - x1) * x2 - x0 * x3 + x1 * x4 + x2 * x5 - x4 * x5\n  + x0 * (0 - x0 + x1 + x2 - x3 + x4 + x5).\n\nLet b1 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x0 - 4/1) * (63504/10000 - x0).\n\nLet b2 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x1 - 4/1) * (63504/10000 - x1).\n\nLet b3 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x2 - 4/1) * (63504/10000 - x2).\n\nLet b4 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x3 - 4/1) * (63504/10000 - x3).\n\nLet b5 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x4 - 4/1) * (63504/10000 - x4).\n\nLet b6 (x0 x1 x2 x3 x4 x5 : R) :=\n  (x5 - 8/1) * (254016/10000 - x5).\n\nTheorem p_nonneg (x0 x1 x2 x3 x4 x5 : R) :\n  b1 x0 x1 x2 x3 x4 x5 >= 0 ->\n  b2 x0 x1 x2 x3 x4 x5 >= 0 ->\n  b3 x0 x1 x2 x3 x4 x5 >= 0 ->\n  b4 x0 x1 x2 x3 x4 x5 >= 0 ->\n  b5 x0 x1 x2 x3 x4 x5 >= 0 ->\n  b6 x0 x1 x2 x3 x4 x5 >= 0 ->\n  p x0 x1 x2 x3 x4 x5 >= 0.\nProof.\nunfold b1, b2, b3, b4, b5, b6, p.\nvalidsdp.\nQed.\n", "meta": {"author": "validsdp", "repo": "validsdp", "sha": "135dd32a2b1166f357df764b469ce14e24711536", "save_path": "github-repos/coq/validsdp-validsdp", "path": "github-repos/coq/validsdp-validsdp/validsdp-135dd32a2b1166f357df764b469ce14e24711536/benchs/flyspeck/fs752.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480248488136, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6541711935610359}}
{"text": "Require Import FP.Data.Function.\nRequire Import FP.Structures.Eqv.\nRequire Import FP.Relations.Setoid.\nRequire Import FP.Relations.Function.\n\nImport FunctionNotation.\nImport ProperNotation.\n\nSection Eqv.\n  Context {A} {A_Eqv:Eqv A}.\n  Context {B} {B_Eqv:Eqv B}.\n  Definition function_Eqv : Eqv (A -> B) :=\n    { eqv := (eqv ==> eqv) }.\nEnd Eqv.", "meta": {"author": "davdar", "repo": "coq-fp", "sha": "d0b752d9ea9592ba0bc7b067b46a63740fcff056", "save_path": "github-repos/coq/davdar-coq-fp", "path": "github-repos/coq/davdar-coq-fp/coq-fp-d0b752d9ea9592ba0bc7b067b46a63740fcff056/tmp/Data/FunctionRelations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818987, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6540101177002805}}
{"text": "Definition rInv {T1 T2:Set}  (R: T1 -> T2 -> Prop) :=\n  fun a b => R b a.\n\n\nDefinition TotalHalf {T1 T2 : Set} (R: T1 -> T2 -> Prop) : Type :=\n(forall (t1:T1), @sigT T2 (R t1)).\n\nDefinition OneToOneHalf  {A B : Set} (R : A -> B -> Prop) : Prop :=\nforall a b1 b2,\n  R a b1\n  -> R a b2\n  ->  b1=b2.\n\nDefinition Total {T1 T2 : Set} (R: T1 -> T2 -> Prop) : Type :=\n(TotalHalf R) *\n(TotalHalf (rInv R)).\n\nDefinition OneToOne  {A B : Set} (R : A -> B -> Prop) : Prop :=\nOneToOneHalf R /\\ (OneToOneHalf (rInv R)).\n\nRequire Import SquiggleEq.tactics.\n\nDefinition left_identity {S T : Type} (f: S -> T) (g: T-> S): Prop :=\n  forall s: S , (g (f s)) = s.\n\nDefinition isomorphic (A B : Set)  :=\n  sigT (fun f: A->B => sig (fun g: B->A =>  left_identity f g /\\ left_identity g f)).\n\nDefinition isomorphic2 (A B : Set) : Type :=\n  sigT (fun R: A -> B -> Prop => (Total R * OneToOne R)%type).\n\nSection iff.\n  Variables (A B: Set).\n  Lemma same12: isomorphic A B -> isomorphic2 A B.\n  Proof.\n    intros Hiso.\n    destruct Hiso as [f Hiso].\n    destruct Hiso as [g Hiso].\n    hnf in Hiso. unfold left_identity in Hiso.\n    repnd.\n    exists (fun a b => f a = b).\n    split; split.\n    - intros a. exists (f a). reflexivity.\n    - intros b. exists (g b). hnf. auto.\n    - intros ? ? ? H1eq H2eq. congruence.\n    - intros ? ? ? H1eq H2eq. congruence.\n  Qed.\n\n  Lemma same21: isomorphic2 A B -> isomorphic A B.\n  Proof.\n    intros Hiso.\n    destruct Hiso as [R Hiso].\n    destruct Hiso as [Tot One].\n    unfold Total, OneToOne, TotalHalf, OneToOneHalf in *.\n    repnd.\n    exists (fun a => projT1 (Tot0 a)).\n    exists (fun b => projT1 (Tot b)).\n    split; unfold rInv in *.\n    - intros a.\n      destruct (Tot0 a) as [b ab].\n      simpl. destruct (Tot b) as [a' ab'].\n      simpl. hnf in ab'. unfold rInv in *. eauto.\n    - intros b.\n      destruct (Tot b) as [a ab]. \n      simpl. destruct (Tot0 a) as [b' ab'].\n      simpl. hnf in ab'. unfold rInv in *. eauto.\n  Qed.\n\nEnd iff.\n\nPrint sigT.\n\n\nInductive sigTS (A : Set) (P : A -> Prop) : Prop :=  existT : forall x : A, P x -> sigTS A P.\nInductive sigTS2 (A : Set) (P : A -> Type) : Prop :=  existT2 : forall x : A, P x -> sigTS2 A P.\n\n(*\nDefinition isomorphic3 (A B : Set) : Type := *)\n\nFail Check  (fun (A B : Set) => sigTS _ (fun R: A -> B -> Prop => (Total R * OneToOne R)%type)).\n(*\nThe term \"(Total R * OneToOne R)%type\" has type \"Type\" while it is expected to have type \n\"Prop\" (universe inconsistency).\n *)\n\nFail Check  (fun (A B : Set) => sigTS2 _ (fun R: A -> B -> Prop => (Total R * OneToOne R)%type)).\n(*\nThe term \"sigTS2\" of type \"forall A : Set, (A -> Type) -> Prop\"\ncannot be applied to the terms\n \"A -> B -> Prop\" : \"Type\"\n \"fun R : A -> B -> Prop => (Total R * OneToOne R)%type\" : \"(A -> B -> Prop) -> Type\"\nThe 1st term has type \"Type\" which should be coercible to \"Set\".\n *)\n\nCheck  (fun (A B : Set) => sigTS (A->B) (fun f: A -> B => sigTS (B->A) (fun g => left_identity f g /\\ left_identity g f ))).\n\nGoal False.\n  set (t:= isomorphic).\n  unfold isomorphic in t.\n  unfold left_identity in t.\nAbort.", "meta": {"author": "aa755", "repo": "paramcoq-iff", "sha": "3ec9ce96fd5233c0a1c7e83b1dab8e526e4bcad8", "save_path": "github-repos/coq/aa755-paramcoq-iff", "path": "github-repos/coq/aa755-paramcoq-iff/paramcoq-iff-3ec9ce96fd5233c0a1c7e83b1dab8e526e4bcad8/examples/isomorphism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6540101155017829}}
{"text": "Require 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    simpl in H.\n    apply False_ind, (Lt.lt_irrefl 0 H).\n\n    assert ((exists x : nat, 1 < x /\\ In x xs) -> forall n, exists x : nat, 1 < x /\\ In x (n :: xs)).\n      intros.\n      destruct H0. destruct H0.\n      exists x.\n      split.\n        assumption. assert (In x (n :: xs)) by (apply (in_cons n x xs H1)); assumption.\n\n    induction a.\n      simpl in H.\n      assert (forall n m, S n < m -> n < m).\n        intros.\n        induction m.\n          apply False_ind, (Lt.lt_n_0 (S n) H1).\n          apply (Lt.lt_S n m (Lt.lt_S_n n m H1)).\n      assert (exists x : nat, 1 < x /\\ In x xs) by (apply (IHxs (H1 (length xs) (sum xs) H))).\n      apply (H0 H2).\n\n      induction a.\n        simpl in H.\n        apply (H0 (IHxs (Lt.lt_S_n (length xs) (sum xs) H))).\n\n        exists (S (S a)).\n        split.\n          apply (Lt.lt_n_S 0 (S a)), (Lt.lt_0_Sn a).\n          apply (in_eq).\nQed.\n", "meta": {"author": "spinylobster", "repo": "Coqex2014", "sha": "090f49c87abead6ea0b1c1a346817523efb777b0", "save_path": "github-repos/coq/spinylobster-Coqex2014", "path": "github-repos/coq/spinylobster-Coqex2014/Coqex2014-090f49c87abead6ea0b1c1a346817523efb777b0/第3回/12.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6540100935371237}}
{"text": "Require Import Tapl.LambdaSub.Base.\n\n(* Our presentation of simply typed lambda calculus has a single base type, Unit. *)\nInductive type : Type :=\n  | ty_unit  : type \n  | ty_arrow : type → type → type\n  | ty_top   : type.\n\nInductive term : Type :=\n  | tm_var  : nat → term\n  | tm_abs  : type → term → term\n  | tm_app  : term → term → term\n  | tm_unit : term.\n\nCoercion tm_var : nat >-> term.\n\n(* Values *)\n\nDefinition context := list type.\nInductive wf : context -> term -> Prop :=\n  | wf_var  : forall G i, \n         (exists T, get i G = Some T)\n      -> wf G (tm_var i)\n  | wf_abs  : forall G T t,\n         wf (T :: G) t \n      -> wf G (tm_abs T t)\n  | wf_app  : forall G t1 t2,\n         wf G t1\n      -> wf G t2\n      -> wf G (tm_app t1 t2)\n  | wf_unit : forall G, \n      wf G tm_unit.\nGlobal Hint Constructors wf : core.\n\nDefinition closed (t: term) := wf nil t.\n\nInductive wnfX : term → Prop :=\n  | wnf_val : ∀ T t, wnfX (tm_abs T t)\n  | wnf_unit : wnfX tm_unit.\nGlobal Hint Constructors wnfX : core.\n\nDefinition value (t : term) := wnfX t ∧ closed t.\n\n(* Substitution *)\n\n(* lift shifts all the free variables over by 1 *)\n\nFixpoint lift (k : nat) (t : term) :=\n  match t with\n  | tm_var i => match compare i k with \n                | Lt => tm_var i\n                | _  => tm_var (S i)\n                end\n  | tm_abs T t' => tm_abs T (lift (S k) t')\n  | tm_app t1 t2 => tm_app (lift k t1) (lift k t2)\n  | tm_unit => tm_unit\n  end.\n\n(*\nFixpoint lift (k : nat) (t : term) :=\n  match t with\n  | tm_var i => if leb k i\n                then tm_var (S i)\n                else tm_var i\n  | tm_abs T t' => tm_abs T (lift (S k) t')\n  | tm_app t1 t2 => tm_app (lift k t1) (lift k t2)\n  | tm_unit => tm_unit\n  end.\n*)\n(* [k -> s]t *)\n(* substX replaces the k'th free variable with s in t.\n   if s has free variables, s is lifted when substituting over binders to make sure the free variables in s are correct.\n   All free variables j > k are shifted down one, to account for the fact that the k'th free variable has been substituted.\n*)\nFixpoint substX (k : nat) (s : term) (t : term) :=\n  match t with\n  | tm_var i => match compare i k with\n                | Eq => s\n                | Lt => tm_var i\n                | Gt => tm_var (pred i)\n                end\n  | tm_abs T t' => tm_abs T (substX (S k) (lift 0 s) t')\n  | tm_app t1 t2 => tm_app (substX k s t1) (substX k s t2)\n  | tm_unit => tm_unit\n  end.\n\n(* Examples *)\n(* [0 -> (λ.T 0)] (1 0 2) = 0 (λ.T 0) 1*)\nExample ex1 : substX 0 (tm_abs ty_unit 0) (tm_app (tm_app 1 0) 2)\n            = tm_app (tm_app 0 (tm_abs ty_unit 0)) 1.\nProof.\n  simpl. reflexivity.\nQed.\n\n\n\n\n(* Evaluation *)\n\nReserved Notation \"t '-->' t'\" (at level 40).\nInductive step : term -> term -> Prop :=\n  | st_app1 : forall t1 t1' t2,\n      t1 --> t1' ->\n      tm_app t1 t2 --> tm_app t1' t2\n  | st_app2 : forall v1 t2 t2',\n      value v1 ->\n      t2 --> t2' ->\n      tm_app v1 t2 --> tm_app v1 t2'\n  | st_appAbs : forall T t1 v2,\n      value v2 ->\n      tm_app (tm_abs T t1) v2 --> substX 0 v2 t1\n      \nwhere \"t '-->' t'\" := (step t t').\nGlobal Hint Constructors step : core.\n\n(* multi_step is the reflexive/transitive closure of the step relation *)\n\nDefinition multi_step := multi_rel step.\nNotation \"t '-->*' t'\" := (multi_step t t') (at level 40).\n(*\nInductive multi_step : term -> term -> Prop := \n  | ms_refl : forall t, \n      t -->* t\n  | ms_trans : forall t1 t2 t3,\n      t1 --> t2 ->\n      t2 -->* t3 ->\n      t1 -->* t3\nwhere \"t '-->*' t'\" := (multi_step t t').\n*)\n\n\n\n\n\n", "meta": {"author": "tmoux", "repo": "coq-pl", "sha": "fe79928ab82daebe5012cd3204a0eeff83ee8ade", "save_path": "github-repos/coq/tmoux-coq-pl", "path": "github-repos/coq/tmoux-coq-pl/coq-pl-fe79928ab82daebe5012cd3204a0eeff83ee8ade/tapl/LambdaSub/Exp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6539037964485248}}
{"text": "Add LoadPath \"../Basics\".\nAdd LoadPath \"../Induction\".\nRequire Import EnumTypes.\nRequire Import Induction.\nRequire Import NamingCases.\nRequire Import Lists.\nRequire Import Reasoning.\n\n(** Below is an implementation of the [!!] operation. What do we do if\n    the given index is too high? In this case, we return the arbitrary\n    value 42. *)\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(** Introducing [natoption], an inductive type for handling errors. It's\n    basically just [Maybe Int] *)\nInductive natoption : Type :=\n   | Some : nat -> natoption\n   | None : natoption.\n\n(** Let's rewrite [index_bad] with the added convenience of [natoption] *)\nFixpoint index (n:nat) (l:natlist) : natoption :=\n   match l with\n   | nil => None (* arbitrary *)\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(* Some examples *)\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(** Here's a function for taking the [nat] out of a [natoption]. The\n    function returns a supplied default [d] if the [natoption] is\n    [None] *)\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n   match o with\n   | Some n => n\n   | None   => d\n   end.\n\n(** EXERCISE [**]: Fix the hd function from earlier, so we don't have to\n    pass a default case *)\nDefinition hd_opt (l : natlist) : natoption :=\n   match l with\n   | []     => None\n   | h :: t => Some h\n   end.\n\n(* Tests *)\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 [*]: Prove the following theorem, relating [hd_opt] to\n    [hd] *)\nTheorem option_elim_hd : forall (l : natlist) (default : nat),\n   hd default l = option_elim default (hd_opt l).\n\nProof.\n   intros l default. destruct l as [| x l'].\n   Case \"l = []\".\n      reflexivity.\n   Case \"l = x :: l'\".\n      reflexivity. Qed.\n", "meta": {"author": "madelgi", "repo": "software-foundations", "sha": "7f533d9596c4408eedd02bb7463f4ed532e9541e", "save_path": "github-repos/coq/madelgi-software-foundations", "path": "github-repos/coq/madelgi-software-foundations/software-foundations-7f533d9596c4408eedd02bb7463f4ed532e9541e/Lists/Options.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.8596637487122112, "lm_q1q2_score": 0.6539037915409479}}
{"text": "Require Import Coq.ZArith.BinInt.\nRequire Import Coq.ZArith.Zcomplements.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.ZArith.Znat.\n\nRequire Import compcert.lib.Integers.\nRequire Import compcert.common.Values.\nRequire Import compcert.exportclight.Clightdefs.\n\nRequire Import VST.veric.expr.\nRequire Import VST.veric.mpred.\nRequire Import VST.floyd.forward.\nRequire Import VST.floyd.sublist.\nRequire Import VST.floyd.field_at.\nRequire Import VST.floyd.coqlib3.\nRequire Import VST.msl.iter_sepcon.\nRequire Import VST.msl.seplog.\n\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.lib.List_ext.\nRequire Import CertiGraph.graph.MathAdjMatGraph.\n\nSection Spatial_AdjMat_Model_2.\n  (* Model 2 is for a stack-allocated graph,\n     where the graph is declared on the stack\n     as a single-dimension array of size \"size^2\". \n     Access to graph[u][v] is via graph[size*u + v].\n   *)\n\n  Context {size : Z}. \n  Context {CompSpecs : compspecs}.\n  Context {V_EqDec : EquivDec.EqDec V eq}. \n  Context {E_EqDec: EquivDec.EqDec E eq}.\n  \n  (* SPATIAL REPRESENTATION *)\n\n  (* Assumption: \n     (v,0), (v,1) ... (v, size-1) are edges.\n   \n   Action: \n    Makes a list containing each edge's elabel.\n    The argument f is an opportunity to tweak the edges as needed\n   *)  \n  Definition vert_to_list (g: AdjMatLG) (f : E -> E) (v : V) :=\n    map (elabel g)\n        (map (fun x => f (v,x))\n             (nat_inc_list (Z.to_nat size))).\n\n  (* Assumptions: \n     1. 0, 1, ... (size-1) are vertices\n     2. for any vertex v,\n          (v,0), (v,1) ... (v, size-1) are edges.\n          \n     Action:\n      Makes a list of lists, where each member list \n      is a vertex's edge-label-list (see helper above).\n   *)\n  Definition graph_to_mat (g: AdjMatLG) (f : E -> E) : list (list Z) :=\n    map (vert_to_list g f)\n        (nat_inc_list (Z.to_nat size)).\n\n  Lemma graph_to_mat_Zlength:\n    forall g (f : E -> E),\n      0 <= size ->\n      Zlength (graph_to_mat g f) = size.\n  Proof.\n    intros. unfold graph_to_mat.\n    rewrite Zlength_map, nat_inc_list_Zlength, Z2Nat.id; trivial.\n  Qed.\n\n  Lemma elabel_Znth_graph_to_mat:\n    forall (g: AdjMatLG) (f: E -> E) src dst,\n      0 <= size ->\n      0 <= src < size ->\n      0 <= dst < size ->\n      elabel g (f (src, dst)) =\n      Znth dst (Znth src (graph_to_mat g f)).\n  Proof.\n    intros. \n    unfold graph_to_mat.\n    rewrite Znth_map, nat_inc_list_i.\n    unfold vert_to_list. rewrite Znth_map.\n    rewrite Znth_map. rewrite nat_inc_list_i.\n    reflexivity.\n    3: rewrite Zlength_map.\n    2, 3, 5: rewrite nat_inc_list_Zlength.\n    all: rewrite Z2Nat.id; trivial.\n  Qed.\n\n  Definition graph_to_list (g: AdjMatLG) (f : E -> E) : list Z :=\n    (concat (graph_to_mat g f)).\n\n   Lemma Zlength_concat:\n   forall size n f,\n     0 <= n ->\n     Forall (fun list : list Z => Zlength list = n)\n            (map f (nat_inc_list size)) ->\n     Zlength (concat (map f (nat_inc_list size))) =\n     Z.of_nat size * n.\n Proof.\n   intros.\n   clear H. induction size0.\n   1: simpl; apply Zlength_nil.\n   rewrite Nat2Z.inj_succ, Z.mul_succ_l.\n   simpl. rewrite map_app, concat_app, Zlength_app.\n   simpl. rewrite app_nil_r.\n   f_equal.\n   - apply IHsize0.\n     rewrite Forall_forall in H0 |- *.\n     intros. apply H0.\n     simpl. rewrite map_app.\n     apply in_or_app; left; trivial.\n   - rewrite Forall_forall in H0. apply H0.\n     apply in_map. rewrite nat_inc_list_in_iff. lia.\n Qed.\n\n Lemma graph_to_list_Zlength:\n    forall g (f : E -> E) n,\n      0 <= size ->\n      0 <= n ->\n      Forall (fun list => Zlength list = n) (graph_to_mat g f) ->\n      Zlength (graph_to_list g f) = size * n.\n  Proof.\n    intros.\n    rewrite <- (Z2Nat.id size); trivial.\n    unfold graph_to_list, graph_to_mat in *.\n    apply Zlength_concat; trivial.\n  Qed.\n\n  Lemma graph_to_list_to_mat:\n    forall g (f : E -> E) u i,\n      0 <= u < size ->\n      0 <= i < size ->\n      0 < size ->\n      Forall (fun list => Zlength list = size)\n             (graph_to_mat g f) ->\n      Znth (u * size + i) (graph_to_list g f) =\n      Znth i (Znth u (graph_to_mat g f)).\n  Proof.\n    intros.\n    assert (Htemp: 0 <= size) by lia.\n    clear Htemp.\n    unfold graph_to_list, graph_to_mat in *.\n    rewrite <- (Z2Nat.id size) in H by lia.\n    generalize dependent u.\n    induction (Z.to_nat size).\n    1: intros; lia.\n    intros. simpl.\n    rewrite map_app, concat_app.\n    assert (Forall (fun list : list Z => Zlength list = size)\n                   (map (vert_to_list g f) (nat_inc_list n))). {\n      rewrite Forall_forall in H2 |- *.\n      intros. apply H2. simpl. rewrite map_app.\n      apply in_or_app. left; trivial.\n    }\n    specialize (IHn H3).\n    destruct H.\n    rewrite Nat2Z.inj_succ in H4.\n    apply Z.lt_succ_r in H4.\n    rewrite Z.le_lteq in H4. destruct H4.\n    - repeat rewrite app_Znth1.\n      + apply IHn; trivial; lia.\n      + rewrite Zlength_map, nat_inc_list_Zlength; lia.\n      + rewrite (Zlength_concat _ size); trivial; [|lia].\n        rewrite <- (Z.succ_pred (Z.of_nat n)).\n        rewrite Z.mul_succ_l.\n        apply Z.add_le_lt_mono; try lia.\n        apply Zorder.Zmult_le_compat_r; lia.\n    - clear IHn. repeat rewrite app_Znth2.\n      + rewrite (Zlength_concat _ size); trivial; [|lia].\n        replace (u * size + i - Z.of_nat n * size)\n          with\n            (u * size - Z.of_nat n * size  + i) by lia.\n        replace (u * size - Z.of_nat n * size)\n          with\n            ((u - Z.of_nat n) * size) by lia.\n        rewrite Zlength_map, nat_inc_list_Zlength.\n        simpl. rewrite app_nil_r.\n        replace (u - Z.of_nat n) with 0 by lia.\n        rewrite Znth_0_cons.\n        replace (0 * size + i) with i by lia.\n        reflexivity.\n      + rewrite Zlength_map, nat_inc_list_Zlength; lia.\n      + rewrite (Zlength_concat _ size); trivial; lia.\n  Qed.\n\n  Definition SpaceAdjMatGraph' sh g_contents gaddr : mpred :=\n    data_at sh (tarray tint (size * size))\n            (map Vint (map Int.repr g_contents))\n            gaddr.\n\n  Definition SpaceAdjMatGraph sh (f : E -> E) g gaddr : mpred :=\n    SpaceAdjMatGraph' sh (graph_to_list g f) gaddr.\n\nEnd Spatial_AdjMat_Model_2.\n\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/graph/SpaceAdjMatGraph2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6539037912977741}}
{"text": "(*\n * --------------------\n * Avtor : Bespalov V.\n * Resheno zadach: 21\n * --------------------\n*)\n\nRequire Import List.\nRequire Import Arith.\nRequire Import Setoid.\nOpen Scope list_scope.\n\nTheorem simpl_succ: forall n: nat, S n = 1 + n.\nProof.\n  intros. compute. reflexivity.\nQed.\n\nTheorem O_is_min: forall n: nat, 0 <= n.\nProof.\n  intros. induction n. apply (le_O_n 0). rewrite simpl_succ.\n  apply (le_plus_trans 0 1 n).\n  rewrite plus_n_O. apply le_plus_r.\nQed.\n\nTheorem app_assoc: forall (A: Type) (l m n: list A), l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros. induction l. simpl. reflexivity.\n  simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem app_nil_r: forall (A : Type) (l: list A), l ++ nil = l.\nProof.\n  intros. induction l. simpl. reflexivity.\n  simpl. rewrite IHl. reflexivity.\nQed.\n\n(* 1_1 *)\nTheorem app_ge_0: forall (A : Type)\n                         (l : list A),\n                     0 <= length l.\nProof.\n  intros. apply O_is_min.\nQed.\n\n(* 1_2 *)\nTheorem app_length: forall (A : Type)\n                           (l l' : list A),\n             length (l ++ l') = length l + length l'.\nProof.\n  intros. induction l. simpl. reflexivity.\n  simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem Свойство_1: forall ls1 ls2 ls3 : list Set,\n                       app (app ls1 ls2) ls3\n                               = app ls1 (app ls2 ls3).\nProof.\n  intros. induction ls1. simpl. reflexivity.\n  rewrite <- app_assoc. reflexivity.\nQed.\n\nTheorem Свойство_2: forall (x  : Set)\n                           (ls : list Set),\n                       app (cons x nil) ls = cons x ls.\nProof.\n  intros. simpl. reflexivity.\nQed.\n\nTheorem Свойство_3: forall (ys  : list Set)\n                           (x z : Set),\n                       app (z :: ys) (x :: nil)\n                          = z :: (app ys (x :: nil)).\nProof.\n  intros. reflexivity.\nQed.\n\nTheorem rev_length': forall (A : Type)\n                            (l : list A),\n                        length (rev l) = length l.\nProof.\n  intros. induction l. simpl. reflexivity.\n  simpl. rewrite app_length.\n  simpl. rewrite IHl. rewrite (simpl_succ (length l)).\n  rewrite (plus_comm 1 (length l)). reflexivity.\nQed.\n\nTheorem distr_rev': forall (A : Type)\n                           (x y : list A),\n                       rev (x ++ y) = rev y ++ rev x.\nProof.\n  intros. induction x. simpl. rewrite app_nil_r. reflexivity.\n  simpl. rewrite IHx. rewrite app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive': forall (A : Type)\n                                (l : list A),\n                            rev (rev l) = l.\nProof.\n  intros. induction l. simpl. reflexivity.\n  simpl. rewrite distr_rev'. rewrite IHl.\n  simpl. reflexivity.\nQed.\n\nTheorem rev_one': forall {A : Type}\n                         (x : A),\n                     rev (x :: nil) = x :: nil.\nProof.\n  intros. simpl. reflexivity.\nQed.\n\nTheorem rev_unit': forall (A : Type)\n                          (l : list A)\n                          (a : A),\n                      rev (l ++ a :: nil) = a :: rev l.\nProof.\n  intros. rewrite distr_rev'. simpl. reflexivity.\nQed.\n\nTheorem rev_append_rev: forall (A : Type)\n                               (l l' : list A),\n                         rev_append l l' = rev l ++ l'.\nProof.\n  intros until l. induction l. simpl. reflexivity. \n  intro. simpl. rewrite <- app_assoc. simpl. \n  apply (IHl (a :: l')).\nQed.\n\nTheorem rev_alt: forall (A : Type)\n                        (l : list A),\n                    rev l = rev_append l nil.\nProof.\n  intros. rewrite rev_append_rev. rewrite app_nil_r. reflexivity.\nQed.\n\nTheorem map_app': forall (A B : Type)\n                         (f : A -> B)\n                         (l l' : list A),\n                  map f (l ++ l') = map f l ++ map f l'.\nProof.\n  intros. induction l; induction l'. simpl. reflexivity.\n  simpl. reflexivity. simpl. rewrite app_nil_r. rewrite app_nil_r.\n  reflexivity. simpl. rewrite IHl. simpl. reflexivity.\nQed.\n  \nTheorem map_map': forall (A B C : Type)\n                         (f : A -> B)\n                         (g : B -> C)\n                         (l : list A),\n         map g (map f l) = map (fun x : A => g (f x)) l.\nProof.\n  intros. induction l. simpl. reflexivity. simpl.\n  rewrite IHl. reflexivity.\nQed.\n\nTheorem map_ext': forall (A B : Type)\n                         (f g : A -> B),\n            (forall a : A, f a = g a)\n                -> forall l : list A, map f l = map g l.\nProof.\n  intros. induction l. simpl. reflexivity. \n  simpl. rewrite (H a). rewrite IHl. reflexivity.\nQed.\n\nTheorem map_length': forall (A B : Type)\n                            (f : A -> B)\n                            (l : list A),\n                        length (map f l) = length l.\nProof.\n  intros. induction l. simpl. reflexivity. simpl.\n  rewrite IHl. reflexivity.\nQed.\n\nTheorem map_rev: forall (A B : Type)\n                        (f   : A -> B)\n                        (ls  : list A),\n                    map f (rev ls) = rev (map f ls).\nProof.\n  intros. induction ls. simpl. reflexivity.\n  simpl. rewrite map_app'. rewrite IHls.\n  simpl. reflexivity.\nQed.\n\nTheorem foldСвойство_1: forall (A B : Type)\n                         (l : list B)\n                         (e : A)\n                         (x : B)\n                         (f : B -> A -> A), \n                    fold_right f e (x :: nil) = f x e.\nProof.\n  intros. unfold fold_right. reflexivity.\nQed.\n\nTheorem fold_right_length: forall (A : Type)\n                                  (l : list A),\n              fold_right (fun (_ : A) (x : nat) => S x)\n                         0\n                         l\n                  = length l.\nProof.\n  intros. induction l. simpl. reflexivity.\n  simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem fold_right_app': forall (A B : Type)\n                                (f : A -> B -> B)\n                                (l l' : list A)\n                                (i : B),\n         fold_right f i (l ++ l')\n                  = fold_right f (fold_right f i l') l.\nProof.\n  intros. induction l. simpl. reflexivity. \n  simpl. rewrite <- IHl. reflexivity.\nQed.\n\nTheorem foldСвойство_2: forall (A : Type)\n                           (g : A -> A)\n                           (l : list A)\n                           (e : A),\n      map g l = fold_right (fun (x : A)\n                                (y : list A) => g x :: y)\n                           nil\n                           l.\nProof.\n  intros. induction l. simpl. reflexivity. \n  simpl. rewrite IHl. reflexivity.\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-08/U308.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997898, "lm_q2_score": 0.7826624840223699, "lm_q1q2_score": 0.6539016237152335}}
{"text": "Require Import Arith List.\n\nSet Implicit Arguments.\n\n\n(** * A simple expression language and its semantics, the old-fashioned way *)\n\nInductive exp1 : Set :=\n  | Num1 : nat -> exp1\n  | Bool1 : bool -> exp1\n  | Plus1 : exp1 -> exp1 -> exp1\n  | Eq1 : exp1 -> exp1 -> exp1.\n\nDefinition eq_nat n1 n2 :=\n  if eq_nat_dec n1 n2\n    then true\n    else false.\n\nInductive run_exp1 : exp1 -> exp1 -> Prop :=\n  | RunNum1 : forall n,\n    run_exp1 (Num1 n) (Num1 n)\n  | RunBool1 : forall b,\n    run_exp1 (Bool1 b) (Bool1 b)\n  | RunPlus1 : forall e1 e2 n1 n2,\n    run_exp1 e1 (Num1 n1)\n    -> run_exp1 e2 (Num1 n2)\n    -> run_exp1 (Plus1 e1 e2) (Num1 (n1 + n2))\n  | RunEq1 : forall e1 e2 n1 n2,\n    run_exp1 e1 (Num1 n1)\n    -> run_exp1 e2 (Num1 n2)\n    -> run_exp1 (Eq1 e1 e2) (Bool1 (eq_nat n1 n2)).\n\nInductive type1 : Set :=\n  | TyNum1 : type1\n  | TyBool1 : type1.\n\nInductive hasType1 : exp1 -> type1 -> Prop :=\n  | HT_Num1 : forall n,\n    hasType1 (Num1 n) TyNum1\n  | HT_Bool1 : forall b,\n    hasType1 (Bool1 b) TyBool1\n  | HT_Plus1 : forall e1 e2,\n    hasType1 e1 TyNum1\n    -> hasType1 e2 TyNum1\n    -> hasType1 (Plus1 e1 e2) TyNum1\n  | HT_Eq1 : forall e1 e2,\n    hasType1 e1 TyNum1\n    -> hasType1 e2 TyNum1\n    -> hasType1 (Eq1 e1 e2) TyBool1.\n\n\nHint Constructors run_exp1.\n\nInductive valueOf1 : exp1 -> type1 -> Prop :=\n  | VO_Num1 : forall n, valueOf1 (Num1 n) TyNum1\n  | VO_Bool1 : forall b, valueOf1 (Bool1 b) TyBool1.\n\nHint Constructors valueOf1.\n\nLtac ics H := inversion H; clear H; subst.\n\nLtac inverter1 :=\n  match goal with\n    | [ H : run_exp1 (Num1 _) _ |- _ ] => ics H\n    | [ H : run_exp1 (Bool1 _) _ |- _ ] => ics H\n    | [ H : run_exp1 (Plus1 _ _) _ |- _ ] => ics H\n    | [ H : run_exp1 (Eq1 _ _) _ |- _ ] => ics H\n  end.\n\nLtac magic_solver1 := repeat progress (firstorder eauto; repeat inverter1).\n\nTheorem run_exp1_preserves : forall (e : exp1) (t : type1),\n  hasType1 e t\n  -> forall e', run_exp1 e e'\n    -> valueOf1 e' t.\n  induction 1; magic_solver1.\nQed.\n\nLtac use_preserves1 :=\n  match goal with\n    | [ H1 : hasType1 ?e1 _, H2 : run_exp1 ?e1 _ |- _ ] =>\n      generalize (run_exp1_preserves H1 H2); clear H1; intro H1\n  end.\n\nLtac inverter1' :=\n  match goal with\n    | [ H : valueOf1 _ TyNum1 |- _ ] => ics H\n    | [ H : valueOf1 _ TyBool1 |- _ ] => ics H\n  end.\n\nLtac magic_solver1' := repeat progress (magic_solver1; repeat use_preserves1; repeat inverter1').\n\nTheorem run_exp1_terminates : forall (e : exp1) (t : type1),\n  hasType1 e t\n  -> exists e', run_exp1 e e'.\n  induction 1; magic_solver1'.\nQed.\n\n(** ** Let's start some running examples: *)\n\nHint Constructors hasType1.\n\nDefinition one : exp1 := Num1 1.\n\nTheorem one_type : hasType1 one TyNum1.\n  unfold one; auto.\nQed.\n\nPrint one_type.\n\nTheorem one_result1 : run_exp1 one one.\n  unfold one; auto.\nQed.\n\nPrint one_result1.\n\nDefinition zero : exp1 := Num1 0.\nDefinition test : exp1 := Eq1 (Plus1 one zero) (Plus1 zero one).\n\nTheorem test_type : hasType1 test TyBool1.\n  unfold test, zero, one; auto.\nQed.\n\nPrint test_type.\n\nTheorem test_result1 : run_exp1 test (Bool1 true).\n  unfold test, zero, one.\n  change true with (eq_nat (1 + 0) (0 + 1)); auto.\nQed.\n\nPrint test_result1.\n\n\n(** * Now let's try using a function instead of a relation.... *)\n\nInductive value2 : Set :=\n  | VNum2 : nat -> value2\n  | VBool2 : bool -> value2.\n\nFixpoint run_exp2 (e : exp1) : option value2 :=\n  match e with\n    | Num1 n => Some (VNum2 n)\n    | Bool1 b => Some (VBool2 b)\n    | Plus1 e1 e2 =>\n      match run_exp2 e1, run_exp2 e2 with\n\t| Some (VNum2 n1), Some (VNum2 n2) =>\n\t  Some (VNum2 (n1 + n2))\n\t| _, _ => None\n      end\n    | Eq1 e1 e2 =>\n      match run_exp2 e1, run_exp2 e2 with\n\t| Some (VNum2 n1), Some (VNum2 n2) =>\n\t  Some (VBool2 (eq_nat n1 n2))\n\t| _, _ => None\n      end\n  end.\n\nInductive valueOf2 : value2 -> type1 -> Prop :=\n  | VO_Num2 : forall n, valueOf2 (VNum2 n) TyNum1\n  | VO_Bool2 : forall b, valueOf2 (VBool2 b) TyBool1.\n\nHint Constructors valueOf2.\n\nLtac inverter2 :=\n  match goal with\n    | [ H : hasType1 (Num1 _) _ |- _ ] => ics H\n    | [ H : hasType1 (Bool1 _) _ |- _ ] => ics H\n    | [ H : hasType1 (Plus1 _ _) _ |- _ ] => ics H\n    | [ H : hasType1 (Eq1 _ _) _ |- _ ] => ics H\n  end.\n\nLtac magic_solver2 := repeat progress (simpl in *; subst; firstorder eauto; repeat inverter2).\n\nTheorem run_exp2_preserves : forall (e : exp1) (t : type1),\n  hasType1 e t\n  -> match run_exp2 e with\n       | None => True\n       | Some v => valueOf2 v t\n     end.\n  intros until e;\n    functional induction run_exp2 e;\n      magic_solver2.\nQed.\n\nLtac use_preserves2 :=\n  match goal with\n    | [ H1 : hasType1 ?e1 _ |- _ ] =>\n      generalize (run_exp2_preserves H1); clear H1\n  end.\n\nLtac rewriter :=\n  match goal with\n    | [ H : _ |- _ ] => rewrite H\n  end.\n\nLtac inverter2' :=\n  match goal with\n    | [ H : valueOf2 _ TyNum1 |- _ ] => ics H\n    | [ H : valueOf2 _ TyBool1 |- _ ] => ics H\n  end.\n\nLtac magic_solver2' := repeat progress (magic_solver2; repeat use_preserves2; repeat rewriter; repeat inverter2').\n\nTheorem run_exp2_terminates : forall (e : exp1) (t : type1),\n  hasType1 e t\n  -> exists v, run_exp2 e = Some v.\n  induction 1; magic_solver2'.\nQed.\n\n\n(** ** Back to our running examples.... *)\n\nTheorem one_result2 : run_exp2 one = Some (VNum2 1).\n  reflexivity.\nQed.\n\nPrint one_result2.\n\nTheorem test_result2 : run_exp2 test = Some (VBool2 true).\n  reflexivity.\nQed.\n\nPrint test_result2.\n\n\n(** * Time to wheel in the dependent types! *)\n\nDefinition value3 (t : type1) : Set :=\n  match t with\n    | TyNum1 => nat\n    | TyBool1 => bool\n  end.\n\nDefinition run_exp3 : forall (e : exp1) (t : type1), hasType1 e t -> value3 t.\n  refine (fix run_exp3 (e : exp1) (t : type1) {struct e} : hasType1 e t -> value3 t :=\n    match e return (hasType1 e t -> value3 t) with\n      | Num1 n =>\n\tmatch t return (hasType1 (Num1 n) t -> value3 t) with\n\t  | TyNum1 => fun _ => n\n\t  | _ => fun pf => False_rec _ _\n\tend\n      | Bool1 b =>\n\tmatch t return (hasType1 (Bool1 b) t -> value3 t) with\n\t  | TyBool1 => fun _ => b\n\t  | _ => fun pf => False_rec _ _\n\tend\n      | Plus1 e1 e2 =>\n\tmatch t return (hasType1 (Plus1 e1 e2) t -> value3 t) with\n\t  | TyNum1 => fun pf => run_exp3 e1 TyNum1 _ + run_exp3 e2 TyNum1 _\n\t  | _ => fun pf => False_rec _ _\n\tend\n      | Eq1 e1 e2 =>\n\tmatch t return (hasType1 (Eq1 e1 e2) t -> value3 t) with\n\t  | TyBool1 => fun pf => eq_nat (run_exp3 e1 TyNum1 _) (run_exp3 e2 TyNum1 _)\n\t  | _ => fun pf => False_rec _ _\n\tend\n    end); magic_solver2.\nDefined.\n\n\n(** ** And the running examples: *)\n\nTheorem one_result3 : run_exp3 one_type = 1.\n  reflexivity.\nQed.\n\nPrint one_result3.\n\nTheorem test_result3 : run_exp3 test_type = true.\n  reflexivity.\nQed.\n\nPrint test_result3.\n\n\n(** * Finally, the slickest formalization of this language :-) *)\n\nInductive exp4 : type1 -> Set :=\n  | Num4 : nat -> exp4 TyNum1\n  | Bool4 : bool -> exp4 TyBool1\n  | Plus4 : exp4 TyNum1 -> exp4 TyNum1 -> exp4 TyNum1\n  | Eq4 : exp4 TyNum1 -> exp4 TyNum1 -> exp4 TyBool1.\n\nFixpoint run_exp4 (t : type1) (e : exp4 t) {struct e} : value3 t :=\n  match e in (exp4 t) return (value3 t) with\n    | Num4 n => n\n    | Bool4 b => b\n    | Plus4 e1 e2 => run_exp4 e1 + run_exp4 e2\n    | Eq4 e1 e2 => eq_nat (run_exp4 e1) (run_exp4 e2)\n  end.\n\n\n(** ** And the running examples: *)\n\nDefinition one4 : exp4 TyNum1 := Num4 1.\n\nTheorem one_result4 : run_exp4 one4 = 1.\n  reflexivity.\nQed.\n\nPrint one_result4.\n\nDefinition zero4 : exp4 TyNum1 := Num4 0.\nDefinition test4 : exp4 TyBool1 := Eq4 (Plus4 one4 zero4) (Plus4 zero4 one4).\n\nTheorem test_result4 : run_exp4 test4 = true.\n  reflexivity.\nQed.\n\nPrint test_result4.\n\n\n(** * Now it's time for some lambda calculus. *)\n\nRequire Import LambdaTamer.LambdaTamer.\n(** I haven't released this library yet.  If you want to run this code yourself,\n  * e-mail me.... *)\n\nInductive ty : Set :=\n  | Nat : ty\n  | Arrow : ty -> ty -> ty.\n\nInductive term : list ty -> ty -> Set :=\n  | Const : forall (G : list ty),\n    nat\n    -> term G Nat\n\n  | EVar : forall (G : list ty) (t : ty),\n    Var G t\n    -> term G t\n  | App : forall (G : list ty) (dom ran : ty),\n    term G (Arrow dom ran)\n    -> term G dom\n    -> term G ran\n  | Lam : forall (G : list ty) (dom ran : ty),\n    term (dom :: G) ran\n    -> term G (Arrow dom ran).\n\nFixpoint tyDenote (t : ty) : Set :=\n  match t with\n    | Nat => nat\n    | Arrow t1 t2 => tyDenote t1 -> tyDenote t2\n  end.\n\nFixpoint termDenote (G : list ty) (t : ty) (e : term G t) {struct e}\n  : Subst tyDenote G -> tyDenote t :=\n  match e in (term G t) return (Subst tyDenote G -> tyDenote t) with\n    | Const _ n => fun _ => n\n    | EVar _ _ x => fun s => VarDenote x s\n    | App _ _ _ e1 e2 => fun s => (termDenote e1 s) (termDenote e2 s)\n    | Lam _ _ _ e' => fun s => fun x => termDenote e' (SCons _ x s)\n  end.\n\n\n(** ** Some examples *)\n\nDefinition two : term nil Nat := Const _ 2.\n\nDefinition id : term nil (Arrow Nat Nat) := Lam (EVar (First _ _)).\n\nDefinition app_id : term nil Nat := App id two.\n\nEval compute in termDenote app_id (SNil _).\n\n\nDefinition call : term nil (Arrow (Arrow Nat Nat) (Arrow Nat Nat)) :=\n  Lam (Lam (App (EVar (Next _ (First _ _))) (EVar (First _ _)))).\n\nEval compute in termDenote (App (App call id) two) (SNil _).\n\n\n(** * A tiny compiler and its correctness proof *)\n\nInductive let_term : list ty -> ty -> Set :=\n  | LConst : forall (G : list ty),\n    nat\n    -> let_term G Nat\n\n  | LVar : forall (G : list ty) (t : ty),\n    Var G t\n    -> let_term G t\n  | LApp : forall (G : list ty) (dom ran : ty),\n    let_term G (Arrow dom ran)\n    -> let_term G dom\n    -> let_term G ran\n  | LLam : forall (G : list ty) (dom ran : ty),\n    let_term (dom :: G) ran\n    -> let_term G (Arrow dom ran)\n\n  | LLet : forall (G : list ty) (bound body : ty),\n    let_term G bound\n    -> let_term (bound :: G) body\n    -> let_term G body.\n\nFixpoint let_termDenote (G : list ty) (t : ty) (e : let_term G t) {struct e}\n  : Subst tyDenote G -> tyDenote t :=\n  match e in (let_term G t) return (Subst tyDenote G -> tyDenote t) with\n    | LConst _ n => fun _ => n\n    | LVar _ _ x => fun s => VarDenote x s\n    | LApp _ _ _ e1 e2 => fun s => (let_termDenote e1 s) (let_termDenote e2 s)\n    | LLam _ _ _ e' => fun s => fun x => let_termDenote e' (SCons _ x s)\n\n    | LLet _ _ _ e1 e2 => fun s => let_termDenote e2 (SCons _ (let_termDenote e1 s) s)\n  end.\n\nFixpoint compiler (G : list ty) (t : ty) (e : let_term G t) {struct e} : term G t :=\n  match e in (let_term G t) return (term G t) with\n    | LConst _ n => Const _ n\n    | LVar _ _ x => EVar x\n    | LApp _ _ _ e1 e2 => App (compiler e1) (compiler e2)\n    | LLam _ _ _ e' => Lam (compiler e')\n\n    | LLet _ _ _ e1 e2 => App (Lam (compiler e2)) (compiler e1)\n  end.\n\nCheck ext_eqT.\n\nTheorem compiler_correct : forall G t (e : let_term G t),\n  termDenote (compiler e) = let_termDenote e.\n  induction e; simpl; intuition; repeat (apply ext_eqT; intro);\n    repeat rewriter; trivial.\nQed.\n\n", "meta": {"author": "SatyendraBanjare", "repo": "itp", "sha": "80831ac497c7e000e964587eb0233adb7382ee88", "save_path": "github-repos/coq/SatyendraBanjare-itp", "path": "github-repos/coq/SatyendraBanjare-itp/itp-80831ac497c7e000e964587eb0233adb7382ee88/lecture_codes/Lect12/lecture12.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6539016194798061}}
{"text": "Require Import Classical.\nFrom src Require Export Props_LC.\nFrom src Require Export Props_LI.\nFrom src Require Export Props_LM.\n\n(* Parte 5 de la tarea. *)\n\n(* Lema auxiliar. El otro lado de Modus Tollens \n * Propiedad de lógica clásica *)\nLemma modus_tollens_2: forall (A B: Prop), (~A -> ~B) -> (B -> A).\nProof.\nintros.\nassert (~~B -> ~~A).\n+ apply modus_tollens.\n  trivial.\n+ assert (~~B).\n  - apply double_neg_intro.\n    trivial.\n  - apply H1 in H2.\n    apply NNPP.\n    trivial.\nQed.\n\n(* Ejercicio 5a \n * Se usó lógica clásica. *)\nTheorem fivea: forall (A B C D : Prop), (A -> B) /\\ (~(A \\/ C) -> D) /\\\n(A \\/ B -> C) -> (~D -> C).\nProof.\nintros.\ndestruct H.\ndestruct H1.\napply modus_tollens in H1.\n+ apply NNPP in H1.\n  destruct H1.\n  - assert (A \\/ B).\n    * left; trivial.\n    * apply H2; trivial.\n  - trivial.\n+ trivial.\nQed.\n\n(* Ejercicio 5b\n * Se usó lógica clásica *)\nTheorem fiveb: forall (A B C D: Prop), A \\/ B -> (~D -> C) /\\ (~B -> ~A) -> (C -> ~B) -> D.\nProof.\nintros.\ndestruct H0.\ndestruct H.\n+ assert (A -> B).\n  - apply modus_tollens_2.\n    trivial.\n  - apply H3 in H.\n    assert (B -> ~C).\n    * apply modus_tollens_2.\n      intro.\n      apply NNPP in H4.\n      apply H1.\n      trivial.\n    * apply H4 in H.\n      assert (~C -> ~~D).\n      ++ apply modus_tollens.\n         trivial.\n      ++ apply H5 in H.\n         apply NNPP.\n         trivial.\n+ assert (B -> ~C).\n  - apply modus_tollens_2.\n    intro.\n    apply H1.\n    apply NNPP; trivial.\n  - apply H3 in H.\n    assert (~C -> D).\n    * apply modus_tollens_2.\n      intro.\n      apply H0 in H4.\n      apply double_neg_intro.\n      trivial.\n    * apply H4 in H.\n      trivial.\nQed.\n\n\n(* Ejercicio 5c \n * Se utilizó lógica clásica (modus tollens).*)\nTheorem fivec: forall (T: Type) (a: T) (P B R: T -> Prop),\n(forall x:T, P x -> ~B x) -> R a -> (forall x: T, R x -> B x) -> ~P a.\nProof.\nintros.\nintro.\napply H in H2.\nassert (forall x: T, ~B x -> ~R x).\n+ intro.\n  apply modus_tollens.\n  apply H1.\n+ apply H3 in H2.\n  contradiction.\nQed.\n\n(* Ejercicio 5d \n * Se usó lógica clásica *)\nTheorem fived: forall (T1: Type) (P B R S T: T1 -> Prop), \n(forall x:T1, P x \\/ B x -> ~R x) /\\ (forall x:T1, S x -> R x) -> (forall x:T1, P x -> ~S x \\/ T x).\nProof.\nintros.\ndestruct H.\nassert (P x \\/ B x).\n+ left; trivial.\n+ apply H in H2.\n  assert (forall x:T1, ~R x -> ~S x).\n  - intro.\n    apply modus_tollens.\n    apply H1.\n  - left;apply H3.\n    trivial.\nQed.\n\n(* Ejercicio 5e \n * La propiedad no se cumple para T vacío, por lo que agregamos la hipótesis\n * de que existe alguien en T. \n * Se usó lógica minimal. *)\nTheorem fivee: forall (T: Type) (x: T) (P B: T -> Prop),(forall x:T, P x /\\ exists y:T, B y) -> (exists x:T, P x /\\ B x).\nProof.\nintros.\napply H in x.\ndestruct x.\nexists x.\nsplit.\n+ apply H.\n+ trivial.\nQed.\n\n(* Ejercicio 5f\n * Se usó lógica minimal *)\nTheorem fivef: forall (T1 T2: Type) (P: T1 -> Prop) (R: T1 -> T2 -> Prop), \n(forall x:T1, exists y:T2, P x -> R x y) -> (forall x:T1, P x -> exists y:T2, R x y).\nProof.\nintros.\nassert (exists y:T2, P x -> R x y).\n+ apply H.\n+ destruct H1.\n  exists x0.\n  apply H1; trivial.\nQed.\n\n(* Ejercicio 5g \n * Se usó lógica minimal.*)\nTheorem fiveg: forall (T : Type) (P B: T -> Prop), \n(forall x:T, P x -> ~B x) -> (~exists x:T, P x /\\ B x).\nProof.\nintros.\nintro.\ndestruct H0.\ndestruct H0.\napply H in H0.\napply H0.\ntrivial.\nQed.\n\n(* Ejercicio 5h \n * Se usó lógica minimal. *)\nTheorem fiveh: forall (T1 T2: Type) (P: T1 -> T2 -> Prop), \n(exists x:T1, forall y:T2, P x y) -> (forall y:T2, exists x:T1, P x y).\nProof.\nintros.\ndestruct H.\nexists x.\napply H.\nQed.\n\n", "meta": {"author": "victorz3", "repo": "Tarea3VF", "sha": "bfc5507760c435bae5358e4e70b14862e3f33ca1", "save_path": "github-repos/coq/victorz3-Tarea3VF", "path": "github-repos/coq/victorz3-Tarea3VF/Tarea3VF-bfc5507760c435bae5358e4e70b14862e3f33ca1/Examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6539016098616208}}
{"text": "Require Import Setoid.\nRequire Import Morphisms.\nRequire Import Coq.Program.Basics.\nRequire Import NArith.\nRequire Import List.\nImport ListNotations.\nOpen Scope list.\nRequire Import Lia.\n\nUnset Printing Records.\n\nFrom Ordinal Require Import Defs.\nFrom Ordinal Require Import Operators.\nFrom Ordinal Require Import Arith.\nFrom Ordinal Require Import Cantor.\nFrom Ordinal Require Import Fixpoints.\nFrom Ordinal Require Import Reflection.\nFrom Ordinal Require Import VeblenDefs.\nFrom Ordinal Require Import VeblenCon.\nFrom Ordinal Require Import VeblenFacts.\n\nOpen Scope ord_scope.\n\nFixpoint vtower_fin (n:nat) : Ord -> Ord :=\n  match n with\n  | O    => addOrd 1\n  | S n' => fun x => veblen (vtower_fin n') (1+x) 0\n  end.\n\nDefinition SmallVeblenOrdinal := supOrd (fun i => vtower_fin i 0).\n\nLemma vtower_fin_succ n x : vtower_fin (S n) x = veblen (vtower_fin n) (1+x) 0.\nProof.\n  reflexivity.\nQed.\n\nLemma vtower_fin_normal n :\n  normal_function (vtower_fin n).\nProof.\n  induction n; simpl.\n  - apply onePlus_normal.\n  - apply veblen_first_onePlus_normal; auto.\nQed.\n\nLemma vtower_fin_eq_mor n x y :\n  x ≈ y -> vtower_fin n x ≈ vtower_fin n y.\nProof.\n  intros; split; apply normal_monotone; auto.\n  apply vtower_fin_normal.\n  apply H.\n  apply vtower_fin_normal.\n  apply H.\nQed.\n\nLemma vtower_fin_complete n :\n  forall x, complete x -> complete (vtower_fin n x).\nProof.\n  apply normal_complete. apply vtower_fin_normal; auto.\nQed.\n\nAdd Parametric Morphism n : (veblen (vtower_fin n))\n    with signature ord_le ==> ord_le ==> ord_le\n      as veblen_vtower_fin_le_mor.\nProof.\n  intros.\n  apply veblen_le_mor; auto.\n  intros; apply normal_monotone; auto.\n  apply vtower_fin_normal; auto.\nQed.\n\nAdd Parametric Morphism n : (veblen (vtower_fin n))\n    with signature ord_eq ==> ord_eq ==> ord_eq\n      as veblen_vtower_fin_eq_mor.\nProof.\n  intros.\n  apply veblen_eq_mor; auto.\n  intros; apply normal_monotone; auto.\n  apply vtower_fin_normal; auto.\nQed.\n\nLemma zero_lt_onePlus x : 0 < 1 + x.\nProof.\n  apply ord_lt_le_trans with 1; [ apply succ_lt | apply addOrd_le1 ].\nQed.\n\nLocal Hint Resolve\n      vtower_fin_complete\n      vtower_fin_normal\n      veblen_complete\n      veblen_normal\n      veblen_first_normal\n      veblen_first_onePlus_normal\n      normal_monotone\n      onePlus_normal\n      powOmega_normal\n      addOrd_complete\n      addOrd_increasing\n      succ_complete\n      zero_complete\n      natOrdSize_complete\n      zero_lt_onePlus\n  : core.\n\nLemma vtower_fin_succ_monotone :\n  forall n i, complete i -> vtower_fin n i ≤ vtower_fin (S n) i.\nProof.\n  induction n; simpl; intros.\n  - apply (onePlus_least_normal (fun i => veblen (addOrd 1) (1+i) 0)); auto.\n  - apply veblen_monotone_func; auto.\nQed.\n\nLemma vtower_fin_index_monotone :\n  forall m n, (m <= n)%nat ->\n    forall i, complete i -> vtower_fin m i ≤ vtower_fin n i.\nProof.\n  intros. induction H; auto with ord.\n  rewrite IHle.\n  apply vtower_fin_succ_monotone; auto.\nQed.\n\nLemma vtower_fin_fixpoints_succ n : forall a x,\n  0 < a ->\n  complete a ->\n  complete x ->\n  veblen (vtower_fin (S n)) a x ≈ veblen (vtower_fin n) (veblen (vtower_fin (S n)) a x) 0.\nProof.\n  intros.\n  simpl.\n  rewrite <- (veblen_fixpoints _ (vtower_fin_normal (S n)) 0 a x) at 1; auto.\n  rewrite veblen_zero.\n  simpl.\n  rewrite onePlus_veblen; auto.\n  reflexivity.\nQed.\n\nTheorem vtower_fin_fixpoints n : forall m a x,\n  (m < n)%nat ->\n  0 < a ->\n  complete a ->\n  complete x ->\n  veblen (vtower_fin n) a x ≈ veblen (vtower_fin m) (veblen (vtower_fin n) a x) 0.\nProof.\n  destruct n.\n  - intros. inversion H.\n  - intros. inversion H.\n    + subst m. apply vtower_fin_fixpoints_succ; auto.\n    + split; simpl.\n      * apply (normal_inflationary (fun i => veblen (vtower_fin m) i 0)); auto.\n      * rewrite <- (veblen_fixpoints _ (vtower_fin_normal (S n)) 0 a x) at 2; auto.\n        rewrite veblen_zero.\n        simpl.\n        rewrite onePlus_veblen; auto.\n        apply veblen_monotone_func; auto.\n        apply vtower_fin_index_monotone; auto.\n        lia.\nQed.\n\nLemma vtower_fin_0_0 : vtower_fin 0 0 ≈ 1.\nProof.\n  simpl.\n  rewrite addOrd_zero_r.\n  reflexivity.\nQed.\n\nLemma vtower_fin_1_func : forall x, complete x -> vtower_fin 1 x ≈ expOrd ω (1+x).\nProof.\n  simpl; intros.\n  rewrite veblen_onePlus; auto.\n  rewrite addOrd_zero_r.\n  reflexivity.\nQed.\n\nLemma vtower_fin_1_0 : vtower_fin 1 0 ≈ ω.\nProof.\n  rewrite vtower_fin_1_func; auto.\n  rewrite addOrd_zero_r.\n  rewrite expOrd_one'; auto with ord.\n  apply (index_lt _ 0%nat).\nQed.\n\nLemma vtower_fin_2_func : forall x, complete x -> vtower_fin 2 x ≈ veblen powOmega (1+x) 0.\nProof.\n  intros.\n  rewrite vtower_fin_succ.\n  simpl.\n  rewrite (veblen_func_onePlus (fun i => veblen (addOrd 1) i 0)); auto.\n  split; apply veblen_monotone_func; auto.\n  intros; rewrite veblen_onePlus; auto.\n  rewrite addOrd_zero_r. reflexivity.\n  intros; rewrite veblen_onePlus; auto.\n  rewrite addOrd_zero_r. reflexivity.\nQed.\n\nLemma vtower_fin_2_0 : vtower_fin 2 0 ≈ ε 0.\nProof.\n  rewrite vtower_fin_2_func; auto.\n  rewrite addOrd_zero_r.\n  rewrite veblen_succ; auto.\n  unfold ε.\n  split; apply enum_fixpoints_func_mono; auto;\n    intros; rewrite veblen_zero; auto with ord.\nQed.\n\nLemma vtower_fin_3_func :\n  forall x, complete x -> vtower_fin 3 x ≈ veblen (fun i => veblen powOmega i 0) (1+x) 0.\nProof.\n  intros.\n  rewrite vtower_fin_succ.\n  symmetry.\n  rewrite <- veblen_func_onePlus; auto.\n  split; apply veblen_monotone_func; auto;\n    intros; rewrite vtower_fin_2_func; auto with ord.\nQed.\n\nLemma vtower_fin_3_0 : vtower_fin 3 0 ≈ Γ 0.\nProof.\n  rewrite vtower_fin_3_func; auto.\n  transitivity (veblen (fun i : Ord => veblen powOmega i 0) 1 0).\n  apply veblen_eq_mor; auto with ord.\n  intros; apply veblen_monotone_first; auto.\n  rewrite addOrd_zero_r; auto with ord.\n  rewrite veblen_succ; auto.\n  unfold Γ.\n  split; apply enum_fixpoints_func_mono; auto;\n    intros; rewrite veblen_zero; auto with ord.\nQed.\n", "meta": {"author": "robdockins", "repo": "ordinals", "sha": "063164521baddfc99ab8c2d222cb01637e8833e1", "save_path": "github-repos/coq/robdockins-ordinals", "path": "github-repos/coq/robdockins-ordinals/ordinals-063164521baddfc99ab8c2d222cb01637e8833e1/Ordinal/VTowerFin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.653891992487531}}
{"text": "Set Implicit Arguments.\nRequire Import ZArith.\n\nInductive htree (A:Set) : nat -> Set :=\n  | hleaf : htree A 0\n  | hnode : forall n:nat, A -> htree A n -> htree A n -> htree A (S n).\n\nCheck htree_ind.\n(*\nforall (A : Set) (P : forall n : nat, htree A n -> Prop),\n  P 0 (hleaf A) -> (forall (n : nat) (a : A) (left : htree A n), P n left -> forall right : htree A n, P n right -> P (S n) (hnode a left right)) \n  -> forall (n : nat) (h : htree A n), P n h\n*)\nInductive Z_btree : Set :=\n  | Z_leaf : Z_btree\n  | Z_bnode : Z -> Z_btree -> Z_btree -> Z_btree.\n\n\nFixpoint htree_to_btree (n:nat)(t: htree Z n) : Z_btree :=\n  match t with \n    | hleaf             => Z_leaf\n    | hnode n v t1 t2   => Z_bnode v (htree_to_btree t1) (htree_to_btree t2)\n  end.\n\n\nFixpoint invert (A:Set)(n:nat)(t: htree A n) : htree A n :=\n  match t in htree _ x return htree A x with\n    | hleaf             => hleaf A\n    | hnode n v t1 t2   => hnode v (invert t2) (invert t1)\n  end.\n\n\nDefinition left (n:nat)(t: htree nat n) := \n  match t in htree _ x return htree nat x with \n    | hleaf             =>  hleaf nat\n    | hnode n v t1 t2   =>  t2\n  end.\n\n(*\nLemma injection: forall (n:nat)(t1 t2 t3 t4:htree nat n),\n  hnode 0 t1 t2 = hnode 0 t3 t4 -> t1 = t3.\nProof.\n  intros n t1 t2 t3 t4 H. discriminate H.\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/htree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6538856671755053}}
{"text": "Require Import EquivDec.\nImport ListNotations.\n\n(** Alphabet of two letters a b *)\n\nModule BiLetters <: FiniteOrderedType.\n Inductive letter := a | b.\n Definition enumeration := [a;b].\n Lemma enumeration_spec : forall (x:letter), In x enumeration.\n Proof.\n  intros [ ]; compute; intuition.\n Qed.\n Definition t := letter.\n Definition eq := @eq letter.\n Definition compare x y :=\n   match x, y with\n   | a,a | b,b => Eq\n   | a,b => Lt\n   | b,a => Gt\n   end.\n Definition lt x y := compare x y = Lt.\n Definition eq_equiv := @eq_equivalence letter.\n Lemma lt_compat : Proper (eq==>eq==>iff) lt.\n Proof. now intros ? ? -> ? ? ->. Qed.\n Global Instance lt_strorder : StrictOrder lt.\n Proof. split; red. now intros [ ]. now intros [ ] [ ] [ ]. Qed.\n Lemma compare_spec (x y : letter) :\n  CompareSpec (x=y) (lt x y) (lt y x) (compare x y).\n Proof. destruct x, y; now constructor. Qed.\n Definition eq_dec (x y : letter) : { x = y } + { x <> y }.\n Proof. destruct x, y; auto; now right. Qed.\n Definition eqb x y :=\n   match x,y with a,a | b,b => true | _,_ => false end.\n Lemma eqb_eq (x y:t) : eqb x y = true <-> x = y.\n Proof. now destruct x,y. Qed.\nEnd BiLetters.\nImport BiLetters.\n\nModule Import Regexp := RegEquivDec(BiLetters).\n\nCoercion Letter : letter >-> re.\n\nBind Scope re_scope with re.\nDelimit Scope re_scope with re.\nOpen Scope re.\n\n(* Cat · \\cdot\n   Star ★ \\bigstar\n   Not ¬ \\neg\n*)\n\nLocal Infix \"·\" := Cat (at level 40, left associativity) : re_scope.\nLocal Infix \"+\" := Or : re_scope.\nLocal Notation \"r ★\" := (Star r) (at level 30, right associativity) : re_scope.\nLocal Notation \"0\" := Void : re_scope.\nLocal Notation \"1\" := Epsilon : re_scope.\nLocal Notation \"¬ r\" := (Not r) (at level 35, no associativity) : re_scope.\n\nDefinition a_regexp := a★·b★.\n\nCompute matching a_regexp [a;a;b;b;b].\nCompute matching a_regexp [a;a;a;b;b;b;a].\n\n(* The bound on the derivative number is quickly huge *)\nCompute derivs_bound a_regexp. (* 4608 *)\n(* In fact, there's lots of redundancy in [over_derivs] : *)\nCompute REs.cardinal (list2set (over_derivs a_regexp)).\n(* ... only 16 distincts possible derivatives *)\n\n(* Only 3 are really derivatives *)\nCompute REs.elements (exact_derivs a_regexp).\n\nCompute is_empty a_regexp. (* false : a_regexp isn't equivalent to Void *)\n\nCompute is_equiv (a★·a★) (a★). (* true *)\nCompute is_equiv (a·a★) (a★). (* false *)\n\n(* all the 3 previous derivatives are distinct up to equiv,\n   hence the minimal automata reckognizing a*.b* will have 3 states\n   (including a sink state) *)\nCompute minimal_derivs a_regexp.\n\n(* You can try you own regexps ...\n   If a alphabet with only two letters isn't enough, you could\n   adapt to use Coq's Ascii type ! *)\n", "meta": {"author": "herbelin", "repo": "cours-preuves-ordinateur", "sha": "c638a7591e40af35fce450b4282b6dd717935aed", "save_path": "github-repos/coq/herbelin-cours-preuves-ordinateur", "path": "github-repos/coq/herbelin-cours-preuves-ordinateur/cours-preuves-ordinateur-c638a7591e40af35fce450b4282b6dd717935aed/projet/Test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7931059462938814, "lm_q1q2_score": 0.6538856631436964}}
{"text": "(* \n  Autor(s):\n    Andrej Dudenhefner (1) \n    Johannes Hostert (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\nRequire Import Arith Lia List.\nFrom Undecidability.DiophantineConstraints Require Import H10C.\n\nSet Default Proof Using \"Type\".\n\n(* Utils for H10UPC *)\n\n(* This section contains useful functions and lemmas for proofs later on. *)\nSection Utils.\n\n  (* In the relation h10upc_sem_direct ((a,b),(c,d)), d is a function of b. *)\n  Lemma c2_full (x:nat) : {y:nat | x * S x = y+y}.\n  Proof. \n    induction x as [|x [y' IH]].\n    - exists 0. lia.\n    - exists (y'+x+1). nia.\n  Qed.\n\n  Definition c2 (x:nat) := match (c2_full x) with exist _ y _ => y end.\n\n  Lemma c2_descr (x:nat) : x * S x = c2 x + c2 x.\n  Proof.\n    unfold c2. now destruct (c2_full x).\n  Qed. \n\n  (* Inversion lemma for h10upc_sem_direct (basically axiom 2) *)\n  Lemma h10upc_inv (a b c d : nat) : h10upc_sem_direct ((a,S b),(c,d)) -> \n           {c':nat & {d':nat & h10upc_sem_direct ((a,b),(c',d')) \n                               /\\ S c' = c /\\ d' + b + 1 = d}}.\n  Proof.\n  intros [Hl Hr].\n  exists (a + S b). exists (c2 b).\n  repeat split.\n  - lia.\n  - apply c2_descr.\n  - lia.\n  - enough (2*(c2 b + b + 1) = d+d) by nia. rewrite <- Hr.\n    cbn. rewrite Nat.mul_comm. cbn. symmetry.\n    pose (c2_descr b) as Hb. nia.\n  Qed.\n\n  (* h10upc_sem_direct is irreflexive *)\n  Lemma h10_rel_irref (p:nat*nat) : ~ (h10upc_sem_direct (p,p)).\n  Proof.\n  intros H. destruct p as [a b]. cbn in H. lia.\n  Qed.\n\n  (* Utility function for finding the highest variable in a h10upc constraint *)\n  Definition highest_var (x:h10upc) := match x with ((a,b),(c,d)) => Nat.max a (Nat.max b (Nat.max c d)) end.\n  Lemma highest_var_descr (x:h10upc) : let hv := highest_var x in match x with ((a,b),(c,d)) => a <= hv /\\ b <= hv /\\ c <= hv /\\ d <= hv end.\n  Proof.\n  destruct x as [[a b] [c d]]. cbn. repeat split; lia.\n  Qed.\n\n  (* Utility function for finding the highest variable in a h10upc constraint collection *)\n  Fixpoint highest_var_list (x:list h10upc) := match x with nil => 0 | x::xr => Nat.max (highest_var x) (highest_var_list xr) end.\n  Lemma highest_var_list_descr (x:list h10upc) (h:h10upc) : In h x ->  highest_var h <= highest_var_list x.\n  Proof.\n  induction x as [|hh x IH].\n  - intros [].\n  - intros [hhh|hx].\n    + cbn. rewrite hhh. lia.\n    + cbn. specialize (IH hx). lia.\n  Qed.\n\n  (* Utility function for finding the highest value in an environment, considering variables up to some n *)\n  Fixpoint highest_num (env: nat -> nat) (n:nat) : nat := match n with 0 => env 0 | S n => Nat.max (env (S n)) (highest_num env n) end.\n  Lemma highest_num_descr (env:nat -> nat) (n:nat) (m:nat) : m <= n -> env m <= highest_num env n.\n  Proof.\n  induction n as [|n IH].\n  - intros Hm. assert (m=0) as Hm0. 1:lia. cbn. rewrite Hm0. lia.\n  - intros HmSn. cbn. destruct (Nat.eq_dec (S n) m) as [Heq|Hneq].\n    + rewrite <- Heq. lia.\n    + assert (m <= n) as Hmn. 1:lia. specialize (IH Hmn). lia.\n  Qed.\n\nEnd Utils.\n\n(* This section contains an alternative characterization of h10upc_sem_direct and some meta-theory.\n    h10upc_sem_direct is the equational characterization of the H10UPC relation.\n    h10upc_ind is presented as an alternative, inductive characterization of that relation. *)\nSection InductiveCharacterization.\n\n  (* Characterizing equations for h10upc_sem_direct *)\n\n  Definition ax1 (P : (nat*nat)*(nat*nat) -> Prop) := forall a c, P ((a,0),(c,0)) <-> a + 1 = c.\n  Definition ax2 (P : (nat*nat)*(nat*nat) -> Prop) := forall a b c d , (b <> 0 /\\ P ((a,b),(c,d))) <->\n               (exists b' c' d', P ((a,b'),(c',d')) /\\ P ((d',b'),(d,d')) /\\ P ((b',0),(b,0)) /\\ P ((c',0),(c,0))).\n  Definition ax2w (P : (nat*nat)*(nat*nat) -> Prop) := forall a b c d ,\n               (exists b' c' d', P ((a,b'),(c',d')) /\\ P ((d',b'),(d,d')) /\\ P ((b',0),(b,0)) /\\ P ((c',0),(c,0)))\n               -> (P ((a,b),(c,d))).\n  Definition ax3 (P : (nat*nat)*(nat*nat) -> Prop) := forall a c d, P ((a,0),(c,d)) -> d = 0.\n\n  Definition sat P := ax1 P /\\ ax2 P /\\ ax3 P.\n  Definition satw P := ax1 P /\\ ax2w P.\n\n  (* Inductive definition of h10upc_sem_direct *)\n  Inductive h10upc_ind : nat -> nat -> nat -> nat -> Prop :=\n    base : forall a, h10upc_ind a 0 (S a) 0\n  | step : forall a b c d b' c' d', h10upc_ind a b' c' d'\n                                 -> h10upc_ind d' b' d d'\n                                 -> h10upc_ind b' 0 b 0\n                                 -> h10upc_ind c' 0 c 0\n                                 -> h10upc_ind a b c d.\n\n  (* Prove that h10upc_ind and h10upc_sem_direct are equivalent. *)\n  (* First step: Show that there is no k < 0, since h10upc_ind is inductive. *)\n  Lemma h10upc_ind_not_less_0 : forall k, h10upc_ind k 0 0 0 -> False.\n  Proof.\n  enough (forall a b c d, h10upc_ind a b c d -> b = 0 -> c = 0 -> d = 0 -> False) as H.\n  1: intros k H1; apply (H k 0 0 0 H1); easy.\n  intros a b c d H.\n  unshelve eapply (h10upc_ind_ind\n                   (fun a b c d => b = 0 -> c = 0 -> d = 0 -> False)\n                   _ _ a b c d H); clear a b c d H.\n  - intros a Hb Hc Hd. lia.\n  - intros a b c d b' c' d' Hab'c'd' Eab'c'd' Hd'b'dd' Ed'b'dd' Hb'zbz Eb'zbz Hc'0c0 Ec'0c0 Hb Hc Hd; cbn in *; subst.\n    apply Ec'0c0; easy.\n  Qed.\n\n\n  (* Next step: show equivalence for the base case. *)\n  Lemma base_equiv a c d : h10upc_sem_direct ((a,0),(c,d)) <-> h10upc_ind a 0 c d.\n  Proof. split.\n  * intros [H1 H2]. assert (d=0) as -> by lia. assert (c = S a) as -> by lia. apply base.\n  * intros H. inversion H as [a' H1|a' b' c' d' b'' c'' d'' H1 H2 H3 H4 H5].\n    - cbn. lia.\n    - exfalso. now eapply h10upc_ind_not_less_0 with b''.\n  Qed.\n\n  (* Last step: show equivalence for the \"step\" case. *)\n  Lemma h10_equiv a b c d  : h10upc_sem_direct ((a,b),(c,d)) <-> h10upc_ind a b c d.\n  Proof. induction b as [|b IH] in a,c,d|-*.\n  - apply base_equiv.\n  - symmetry. split.\n    * intros H. inversion H; subst.\n      rewrite <- base_equiv in H2, H3. cbn in H2,H3.\n      assert (b' = b) as -> by lia.\n      assert (S c' = c) as <- by lia.\n      rewrite <- IH in H0,H1. cbn in H0,H1. cbn. lia.\n    * intros [H1 H2]. eapply step with b (c-1) (d-b-1).\n      + rewrite <- IH. cbn; lia.\n      + rewrite <- IH. cbn; lia.\n      + rewrite <- base_equiv. cbn; lia.\n      + rewrite <- base_equiv. cbn; lia.\n  Qed.\n\n\n  (* Show that h10upc_sem_direct satisfies the axioms. *)\n  Lemma eqRelSat : sat h10upc_sem_direct.\n  Proof.\n  split. 2:split.\n  - intros a c. cbn. lia.\n  - intros a. intros. split.\n    * intros [H1 [H2 H3]]. destruct b as [|b']. 1:easy.\n      exists b', (c-1), (d-b'-1). repeat split.\n      all: lia.\n    * intros [b' [c' [d' [H1 [H2 [H3 H4]]]]]]. cbn in H1,H2,H3,H4. cbn; lia.\n  - intros a c d. cbn. lia.\n  Qed.\n\n\n  (* If P fulfills the axioms, and Q fulfills the weak axioms, then P is stronger than Q. *)\n  (* Again, first the base case: *)\n  Lemma satEquiv0 P Q : sat P -> satw Q -> forall a c d, P ((a,0),(c,d)) -> Q ((a,0),(c,d)).\n  Proof. intros [HP1 [HP2 HP3]] [HQ1 HQ2] a c d.\n  intros H.\n  * pose proof (HP3 a c d H) as k. rewrite k in *.\n    rewrite (HP1 a c) in H. rewrite (HQ1 a c). easy.\n  Qed.\n\n  (* Then the step case: *)\n  Lemma satEquiv P Q : sat P -> satw Q -> forall a b c d, P ((a,b),(c,d)) -> Q ((a,b),(c,d)).\n  Proof. intros [HP1 [HP2 HP3]] [HQ1 HQ2] a b c d.\n  induction b as [|b' IH] in a,c,d|-*.\n  * apply satEquiv0; firstorder.\n  * destruct (HP2 a (S b') c d) as [HP21 HP22].\n    pose proof (HQ2 a (S b') c d) as HQ22.\n    intros H.\n    - apply HQ22. destruct HP21 as [b'' [c' [d' [H1 [H2 [H3 H4]]]]]].\n      + split; easy.\n      + exists b'', c', d'. unfold ax1 in HP1. rewrite HP1 in H3. assert (b'' = b') as -> by lia.\n        unfold ax1 in HQ1. rewrite !HQ1. rewrite <- !HP1. rewrite <- HP1 in H3. split. 2:split. 3:tauto.\n        all: apply IH; easy.\n  Qed.\n\n  (* Congruence lemma: equivalent P,Q fulfill the same axioms *)\n  Lemma satCongr P Q : (forall a b c d, P ((a,b),(c,d)) <-> Q ((a,b),(c,d))) -> sat P -> sat Q.\n  Proof.\n  intros H [H1 [H2 H3]]. split. 2:split.\n  - unfold ax1 in *. intros a c. rewrite <- H. apply H1.\n  - unfold ax2 in *. intros a b c d. rewrite <- H. split.\n    * destruct (H2 a b c d) as [H2' _]. intros H4.\n      destruct (H2' H4) as [b' [c' [d' H5]]].\n      exists b', c', d'. rewrite <- !H. apply H5.\n    * destruct (H2 a b c d) as [_ H2']. intros [b' [c' [d' H4]]].\n      apply H2'. exists b',c',d'. rewrite !H. apply H4.\n  - unfold ax3 in *. intros a c d. rewrite <- H. apply H3.\n  Qed.\n\n  Definition h10upc_ind' '((a,b),(c,d)) := h10upc_ind a b c d.\n\n  (* It follows that h10upc_ind also fulfills the axioms. *)\n  Lemma indRelSat : sat h10upc_ind'.\n  Proof.\n  eapply satCongr with h10upc_sem_direct.\n  - intros a b c d. apply h10_equiv.\n  - apply eqRelSat.\n  Qed.\n\n  (* The weak axioms are weaker. *)\n  Lemma sat_satw P : sat P -> satw P.\n  Proof.\n  intros [H1 [H2 H3]]. split.\n  * easy.\n  * intros a b c d H. destruct (H2 a b c d) as [_ H2R]. now apply H2R.\n  Qed.\n\n\nEnd InductiveCharacterization.\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/DiophantineConstraints/Util/H10UPC_facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.6538856623498797}}
{"text": "(*|\n#################################################\nHow can I automate counting within proofs in Coq?\n#################################################\n\n:Link: https://stackoverflow.com/q/42662141\n|*)\n\n(*|\nQuestion\n********\n\nI have a function ``count`` that counts how many times a given\npredicate is provable when applied to elements of a list. It is\ndefined as follows:\n|*)\n\nParameter T : Type.\n\nParameter dec : forall (p : T -> Prop) (w : T), {p w} + {~ p w}.\n\nFixpoint count (p : T -> Prop) (l : list T) := match l with\n  | nil => 0\n  | cons head tail => if dec p head then 1 + count p tail else count p tail\nend.\n\n(*| I then use this function to state lemmas like the following: |*)\n\nParameter a b c : T.\nParameter q : T -> Prop.\n\nAxiom Aa : q a.\nAxiom Ab : q b.\nAxiom Ac : ~ q c.\n\nLemma example : count q (cons a (cons b (cons c nil))) = 2.\n\n(*| My proofs of such lemmas tend to be quite tedious: |*)\n\nProof.\n  unfold count.\n  assert (q a); [apply Aa | auto].\n  assert (q b); [apply Ab | auto].\n  assert (~ q c); [apply Ac | auto].\n  destruct (dec q a); [auto | contradiction].\n  destruct (dec q b); [auto | contradiction].\n  destruct (dec q c); [contradiction | auto].\nQed.\n\n(*|\nWhat can I do to automate such tedious proofs that involve computation\nwith my ``count`` function?\n|*)\n\n(*|\nAnswer (Zimm i48)\n*****************\n\nThis is typically the kind of cases where you are better off proving\nthings by reflection. See how things go smoothly (of course I modified\na bit your example to avoid all these axioms):\n|*)\n\nReset Initial. (* .none *)\nRequire Import List.\nImport ListNotations.\n\nFixpoint count {T : Type} (p : T -> bool) (l : list T) :=\n  match l with\n  | [] => 0\n  | h :: t => if p h then S (count p t) else (count p t)\n  end.\n\nInductive T := a | b | c.\n\nDefinition q x :=\n  match x with\n  | a => true\n  | b => true\n  | c => false\n  end.\n\nLemma example : count q [a; b; c] = 2.\nProof.\n  reflexivity.\nQed.\n\n(*|\nI realize that your definition of ``count`` was taking a propositional\npredicate on type ``T`` (but with the assumption that all predicates\non type ``T`` are decidable) and instead I propose to define ``count``\nto take a boolean predicate. But you may realize that having a\ndecidable propositional predicate or having a boolean predicate is\nactually equivalent.\n\nE.g. from your axioms, I can define a function which transform any\npropositional predicate into a boolean one:\n|*)\n\nReset Initial. (* .none *)\nParameter T : Type.\n\nParameter dec : forall (p : T -> Prop) (w : T), {p w} + {~ p w}.\n\nDefinition prop_to_bool_predicate (p : T -> Prop) (x : T) : bool :=\n  if dec p x then true else false.\n\n(*|\nOf course, because there are axioms involved in your example, it won't\nactually be possible to compute with the boolean predicate. But I'm\nassuming that you put all these axioms for the purpose of the example\nand that your actual application doesn't have them.\n\nAnswer to your comment\n======================\n\nAs I told you, as soon as you have defined some function in terms of\nan axiom (or of a `Parameter\n<https://coq.inria.fr/refman/language/gallina-specification-language.html#coq:cmdv.parameter>`__\nsince this is the same thing), there is no way you can compute with it\nanymore.\n\nHowever, here is a solution where the decidability of propositional\npredicate ``p`` is a lemma instead. I ended the proof of the lemma\nwith `Defined\n<https://coq.inria.fr/refman/language/gallina-specification-language.html#coq:cmdv.defined>`__\ninstead of `Qed\n<https://coq.inria.fr/refman/language/gallina-specification-language.html#coq:cmd.qed>`__\nto allow computing with it (otherwise, it wouldn't be any better than\nan axiom). As you can see I also redefined the ``count`` function to\ntake a predicate and a proof of its decidability. The proof by\nreflection still works in that case. There is no ``bool`` but it is\nstrictly equivalent.\n|*)\n\nReset Initial. (* .none *)\nRequire Import List.\nImport ListNotations.\n\nFixpoint count {T : Type} (p : T -> Prop)\n         (dec : forall (w: T), {p w} + {~ p w}) (l : list T) :=\n  match l with\n  | [] => 0\n  | h :: t => if dec h then S (count p dec t) else count p dec t\n  end.\n\nInductive T := a | b | c.\n\nDefinition p x := match x with | a => True | b => True | c => False end.\n\nLemma dec_p : forall (w : T), {p w} + {~ p w}.\nProof.\n  intros []; simpl; auto.\nDefined.\n\nLemma example2: count p dec_p [a; b; c] = 2.\nProof. reflexivity. Qed.\n\n(*|\nAnswer (Anton Trunov)\n*********************\n\nLet's create our custom hint database and add your axioms there:\n\n.. coq:: none\n|*)\n\nReset Initial.\n\nParameter T : Type.\n\nParameter dec : forall (p : T -> Prop) (w : T), {p w} + {~ p w}.\n\nFixpoint count (p : T -> Prop) (l : list T) := match l with\n  | nil => 0\n  | cons head tail => if dec p head then 1 + count p tail else count p tail\nend.\n\nParameter a b c : T.\nParameter q : T -> Prop.\n\nAxiom Aa : q a.\nAxiom Ab : q b.\nAxiom Ac : ~ q c.\n\n(*||*)\n\nHint Resolve Aa : axiom_db.\nHint Resolve Ab : axiom_db.\nHint Resolve Ac : axiom_db.\n\n(*|\nNow, the ``firstorder`` tactic can make use of the hint database:\n|*)\n\nLemma example : count q (cons a (cons b (cons c nil))) = 2.\nProof.\n  unfold count.\n  destruct (dec q a), (dec q b), (dec q c); firstorder with axiom_db.\nQed.\n\n(*|\n----\n\nWe can automate our solution using the following piece of Ltac:\n|*)\n\nLtac solve_the_probem :=\n  match goal with\n    |- context [if dec ?q ?x then _ else _] =>\n      destruct (dec q x);\n      firstorder with axioms_db;\n      solve_the_probem\n  end.\n\n(*|\nThen, ``unfold count; solve_the_probem.`` will be able to prove the\nlemma.\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/how-can-i-automate-counting-within-proofs-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634457, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.6538856589291147}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import List. Import ListNotations.\nRequire Import Coq.ZArith.BinInt. (* Z *)\nRequire Import Coq.ZArith.Zcomplements. (* Zlength *)\nRequire Import compcert.lib.Integers.          (* byte *)\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\n\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Program.Tactics.\nRequire Import sha.XorCorrespondence. (* Blist *)\nRequire Import sha.Bruteforce.\nRequire Import sha.general_lemmas.\nRequire Import sha.hmac_pure_lemmas.\n\nDefinition Blist := list bool.\nOpen Scope Z_scope.\n\nInductive InBlocks {A : Type} (n : nat) : list A -> Prop :=\n  | InBlocks_nil : InBlocks n []\n  | InBlocks_block : forall (front back full : list A),\n                   length front = n ->\n                   full = front ++ back ->\n                   InBlocks n back ->\n                   InBlocks n full.\n\nLemma InBlocks_len : forall {A : Type} (l : list A) (n : nat),\n                       PeanoNat.Nat.divide (n) (length l) -> InBlocks n l.\nProof.\n  intros A l n div.\n  destruct div.\n  revert A l n H.\n  induction x; intros; simpl in *.\n  - destruct l; simpl in *. constructor. inversion H.\n  - destruct (list_splitLength _ _ _ H) as [l1 [l2 [L [L1 L2]]]]. clear H; subst.\n    apply IHx in L2. clear IHx.\n    apply (InBlocks_block _ l1 l2); trivial.\nQed.\n\n(* ----- Inductive *)\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\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\nLemma bitsToByte_isbyteZ b0 b1 b2 b3 b4 b5 b6 b7:\n      isbyteZ (bitsToByte [b0; b1; b2; b3; b4; b5; b6; b7]).\nProof. simpl. unfold asZ, isbyteZ.\n  destruct b0; destruct b1; destruct b2; destruct b3;\n  destruct b4; destruct b5; destruct b6; destruct b7; simpl; omega.\nQed.\n\n(* -------------------- Various theorems and lemmas *)\n\nLemma byteToBits_length bt: length (byteToBits bt) = 8%nat.\nProof. reflexivity. Qed.\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\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  - rewrite -> IHcorr; clear IHcorr corr.\n    * unfold bitsToBytes.\n      fold bitsToBytes.\n      f_equal. unfold convertByteBits in H.\n        destruct H as [b8 [b9 [b10 [b11 [b12 [b13 [b14 [b15 [B BT]]]]]]]]].\n        inversion B; clear B. subst. reflexivity.\n    * eapply Forall_tl. eassumption.\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    eapply Forall_tl. eassumption.\nQed.\n\n(* ----------------------------- *)\n(* Relating bits to bytes *)\n\nLemma bitsToBytes_app : forall (l m : Blist),\n                          InBlocks 8 l ->\n                          bitsToBytes (l ++ m) = bitsToBytes l ++ bitsToBytes m.\nProof.\n  intros l m len_l. revert m.\n  induction len_l.\n  * intros. reflexivity.\n  *\n    intros m.\n    rewrite -> H0.\n    rewrite <- app_assoc.\n    destruct front as [ | x0 [| x1 [ | x2 [ | x3 [ | x4 [ | x5 [ | x6 [ | x7 ]]]]]]]];\n      inversion H.\n    unfold bitsToBytes.\n    Opaque bitsToByte.\n    simpl.\n    fold bitsToBytes.\n    apply list_nil in H2.\n    rewrite -> H2.\n    simpl.\n    rewrite -> IHlen_l.\n    reflexivity.\nQed.\n\nLemma bitsToBytes_len_gen : forall (l : Blist) (n : nat),\n                          length l = (n * 8)%nat ->\n                          length (bitsToBytes l) = n.\nProof.\n  intros l n len.\n  assert (blocks : InBlocks 8 l).\n    apply InBlocks_len. rewrite -> len. exists n. reflexivity.\n  revert n len.\n  induction blocks.\n  * intros. simpl in *. omega.\n  *\n    intros n len.\n    rewrite -> H0.\n    rewrite -> bitsToBytes_app.\n    rewrite -> app_length.\n    rewrite -> H0 in len.\n    rewrite -> app_length in len.\n    rewrite -> H in len.\n\n    destruct n as [ | n'].\n    (* strange that destruct works here but not after [rewrite -> IHblocks] *)\n    - simpl in *.\n      inversion len.\n    -\n      destruct front as [ | x0 [| x1 [ | x2 [ | x3 [ | x4 [ | x5 [ | x6 [ | x7 ]]]]]]]];\n      inversion H.\n\n      simpl.\n      apply list_nil in H2.\n      rewrite -> H2. simpl.\n      assert (minus : forall (n m : nat), n = m -> (n - 8)%nat = (m - 8)%nat).\n        intros. omega.\n      apply minus in len.\n      simpl in len.\n      assert (min_zero : forall (n : nat), (n - 0)%nat = n). intros. omega.\n      repeat rewrite -> min_zero in len.\n      clear H2 minus min_zero.\n      specialize (IHblocks n').\n      rewrite -> IHblocks.\n      reflexivity.\n      apply len.\n      -\n        apply InBlocks_len.\n        rewrite -> H. unfold PeanoNat.Nat.divide.\n        exists 1%nat. reflexivity.\nQed.\n\nLemma bitsToBytes_len : forall (l : Blist),\n                          length l = 512%nat ->\n                          Zlength (bitsToBytes l) = 64%Z.\nProof.\n  intros l len.\n  rewrite -> Zlength_correct.\n  pose proof bitsToBytes_len_gen as len_gen.\n  specialize (len_gen l 64%nat).\n  rewrite -> len_gen.\n  - reflexivity.\n  - apply len.\nQed.\n\nLemma bits_bytes_bits_id : forall (l : Blist),\n                             InBlocks 8 l ->\n                             bytesToBits (bitsToBytes l) = l.\nProof.\n  intros l len.\n  induction len.\n  - reflexivity.\n  -\n    rewrite -> H0.\n    destruct front as [ | x0 [| x1 [ | x2 [ | x3 [ | x4 [ | x5 [ | x6 [ | x7 ]]]]]]]];\n      inversion H.\n    simpl.\n    apply list_nil in H2. rewrite -> H2. simpl.\n    rewrite -> IHlen.\n\n    destruct x0; destruct x1; destruct x2; destruct x3;\n    destruct x4; destruct x5; destruct x6; destruct x7; reflexivity.\nQed.\n\nLemma bytes_bits_lists_append:\n  forall (l1 : Blist) (l2 : list Z) (m1 : Blist) (m2 : list Z),\n    bytes_bits_lists l1 l2\n    -> bytes_bits_lists m1 m2\n    -> bytes_bits_lists (l1 ++ m1) (l2 ++ m2).\nProof.\n  intros l1 l2 m1 m2.\n  intros fst_eq snd_eq.\n  generalize dependent m1. generalize dependent m2.\n  induction fst_eq; intros.\n  - repeat rewrite app_nil_l.\n    apply snd_eq.\n  - simpl.\n    apply eq_cons.\n    + apply IHfst_eq.\n      apply snd_eq.\n    + apply H.\nQed.\n\n\nLemma bytesToBits_nil_inv l: nil = bytesToBits l -> l = nil.\nProof. destruct l; trivial. simpl; intros. discriminate. Qed.\n\nLemma bytesToBits_cons b l:\n      bytesToBits (b::l) = byteToBits b ++ bytesToBits l.\nProof. reflexivity. Qed.\n\nLemma byteToBits_injective: forall a b,\n      byteToBits a = byteToBits b ->\n      isbyteZ a -> isbyteZ b -> a = b.\nProof. intros. unfold isbyteZ in *.\nassert (bitsToByte (byteToBits a) = bitsToByte (byteToBits b)).\n  rewrite H; trivial.\nclear H.\nrewrite byte_bit_byte_id in H2; trivial.\nrewrite byte_bit_byte_id in H2; trivial.\nQed.\n\nLemma bytesToBits_injective: forall b1 b2, bytesToBits b1 = bytesToBits b2 ->\n      Forall isbyteZ b1 -> Forall isbyteZ b2 -> b1=b2.\nProof. induction b1.\n  intros; destruct b2; trivial. discriminate.\n  destruct b2. discriminate.\n  do 2 rewrite bytesToBits_cons.\n  intros. destruct (app_inj1 _ _ _ _ H). reflexivity.\n  rewrite (IHb1 _ H3).\n  rewrite (byteToBits_injective _ _ H2). trivial.\n    eapply Forall_inv; eassumption.\n    eapply Forall_inv; eassumption.\n    eapply Forall_tl; eassumption.\n    eapply Forall_tl; eassumption.\nQed.\n\nLemma bitsToBytes_injective8 b1 b2 (B: bitsToBytes b1 = bitsToBytes b2)\n       (L1: PeanoNat.Nat.divide 8 (length b1))\n       (L2: PeanoNat.Nat.divide 8 (length b2)): b1 = b2.\nProof. intros.\n  assert (bytesToBits (bitsToBytes b1) = bytesToBits (bitsToBytes b2)).\n    rewrite B; trivial.\n  rewrite bits_bytes_bits_id in H.\n    rewrite bits_bytes_bits_id in H. trivial.\n    apply InBlocks_len; assumption.\n  apply InBlocks_len; assumption.\nQed.\n\nLemma bitsToByte_cons: forall bits h t, (h::t) = bitsToBytes bits ->\n      exists b0, exists b1, exists b2, exists b3,\n      exists b4, exists b5, exists b6, exists b7, exists xs,\n      bits = b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: xs /\\\n      h = bitsToByte [b0; b1; b2; b3; b4; b5; b6; b7] /\\\n      t = bitsToBytes xs.\nProof. intros.\n  destruct bits. inv H.\n  destruct bits. inv H.\n  destruct bits. inv H.\n  destruct bits. inv H.\n  destruct bits. inv H.\n  destruct bits. inv H.\n  destruct bits. inv H.\n  destruct bits; inv H.\n  eexists; eexists; eexists; eexists; eexists; eexists; eexists; eexists; eexists.\n  split. reflexivity.\n  split; reflexivity.\nQed.\n\nDefinition intsToBits (l : list Int.int) : list bool :=\n  bytesToBits (intlist_to_Zlist l).\n\nDefinition bitsToInts (l : Blist) : list Int.int :=\n  Zlist_to_intlist (bitsToBytes l).\n\nLemma bitsToBytes_isbyteZ: forall bytes bits,\n                             bytes = bitsToBytes bits -> Forall isbyteZ bytes.\nProof. intros bytes.\n  induction bytes; simpl; intros.\n     constructor.\n  apply bitsToByte_cons in H.\n  destruct H as [b0 [b1 [b2 [b3 [b4 [b5 [b6 [b7 [xs [BITS [A BYTES]]]]]]]]]]].\n  constructor.\n     subst. apply bitsToByte_isbyteZ.\n     eauto.\nQed.\n\nLemma convertByteBits_isbyteZ b0 b1 b2 b3 b4 b5 b6 b7 byte:\n      convertByteBits [b0; b1; b2; b3; b4; b5; b6; b7] byte ->\n      isbyteZ byte.\nProof. intros.\n  destruct H as [b8 [b9 [b10 [b11 [b12 [b13 [b14 [b15 [BITS ZZ]]]]]]]]].\n  inversion BITS. subst. clear BITS.\n  unfold asZ, isbyteZ.\n  destruct b8; destruct b9; destruct b10; destruct b11;\n  destruct b12; destruct b13; destruct b14; destruct b15; simpl; omega.\nQed.\n\nLemma bytesBitsLists_isbyteZ bytes bits: bytes_bits_lists bits bytes -> Forall isbyteZ bytes.\nProof. intros.\n  induction H. constructor.\n  constructor; trivial. eapply convertByteBits_isbyteZ. apply H0.\nQed.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/sha/ByteBitRelations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634457, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.6538856548973059}}
{"text": "Load \"include/ops_header.v\".\n\nModule precond.\n\nDefinition Sn (n k m : int) := (n >= 0) /\\ (m > 0) /\\ (n >= m).\nDefinition Sk (n k m : int) := true.\nDefinition Sm (n k m : int) := (n > 0) /\\ (m > 0) /\\ (n > m).\n\nEnd precond.\n\nDefinition not_D1 (n k m : int) := (0 < m) && (m < n).\nDefinition not_D2 (n k m : int) := (0 < m) && (m < n).\nDefinition not_D3 (n k m : int) := (0 < m) && (m < n).\nDefinition not_D4 (n k m : int) := (0 < m) && (m < n).\n\nLoad \"include/ann_d.v\".\n\nDefinition CT1  (d : int -> int -> int -> rat) : Prop := forall (n_ k_ m_ : int),\n  not_D1 n_ k_ m_ -> P1_horner (punk.pfun2 d m_) n_ k_ = Q1_flat d n_ k_ (int.shift 1 m_) - Q1_flat d n_ k_ m_.\n\nDefinition CT2  (d : int -> int -> int -> rat) := forall (n_ k_ m_ : int),\n  not_D2 n_ k_ m_ -> P2_horner (punk.pfun2 d m_) n_ k_ = Q2_flat d n_ k_ (int.shift 1 m_) - Q2_flat d n_ k_ m_.\n\nDefinition CT3  (d : int -> int -> int -> rat) := forall (n_ k_ m_ : int),\n  not_D3 n_ k_ m_ -> P3_horner (punk.pfun2 d m_) n_ k_ = Q3_flat d n_ k_ (int.shift 1 m_) - Q3_flat d n_ k_ m_.\n\nDefinition CT4  (d : int -> int -> int -> rat) := forall (n_ k_ m_ : int), \n  not_D4 n_ k_ m_ -> P4_horner (punk.pfun2 d m_) n_ k_ = Q4_flat d n_ k_ (int.shift 1 m_) - Q4_flat d n_ k_ m_.\n\nRecord Ann d : Type := ann {\n  Sn_  : Sn d;\n  Sk_  : Sk d;\n  Sm_  : Sm d\n}.\n", "meta": {"author": "coq-community", "repo": "apery", "sha": "305046d98025d75ca426cc44283302963389f1dc", "save_path": "github-repos/coq/coq-community-apery", "path": "github-repos/coq/coq-community-apery/apery-305046d98025d75ca426cc44283302963389f1dc/theories/annotated_recs_d.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.7248702880639792, "lm_q1q2_score": 0.6537755082507475}}
{"text": "Require Import Utf8.\nRequire Import GroupDefinition.\nRequire Import GroupAction.\nRequire Import GroupProofs.\nRequire Import Setoid.\n\nGeneralizable Variables G.\n\nDefinition operation_as_action `{Group G} : GroupActionOp G G := λ g h, g·h.\n\nProposition groups_act_over_themselves\n    {G : Set} {op : SemiGroupOp G} {i : GroupInv G} {e : G} {P : @Group G op i e} :\n    @GroupAction G e _ _ _ _ G operation_as_action.\nProof.\n  split.\n  intros.\n  compute.\n  rewrite (@sg_assoc G op _).\n  reflexivity.\n  intros.\n  compute.\n  rewrite (@left_identity G op i e P _).\n  reflexivity.\nQed.", "meta": {"author": "Echogene", "repo": "Oilar", "sha": "61383eee23d3b798e5dcb128dfd9fe5452f324ad", "save_path": "github-repos/coq/Echogene-Oilar", "path": "github-repos/coq/Echogene-Oilar/Oilar-61383eee23d3b798e5dcb128dfd9fe5452f324ad/GroupTheory/GroupActionProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.65377548760227}}
{"text": "Theorem Disjunctive_syllogism : forall P Q : Prop, (P \\/ Q) -> ~P -> Q.\nProof.\n  intros.\n  destruct H as [ H1 | H2 ].\n  absurd P.\n  apply H0.\n  apply H1.\n  assumption.\nQed.", "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/3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6537712997633709}}
{"text": "Require Export SpecSyntax.\nSet Implicit Arguments.\n\n(******************************************************************************)\n(* Shifting                                                                   *)\n(******************************************************************************)\n\nFixpoint shiftIndex (c : nat) (i : nat) : nat :=\n  match c with\n    | O   => S i\n    | S c =>\n      match i with\n        | O   => O\n        | S i => S (shiftIndex c i)\n      end\n  end.\n\nFixpoint tshiftTy (c : nat) (T : Ty) : Ty :=\n  match T with\n    | tvar X       => tvar (shiftIndex c X)\n    | tabs K T     => tabs K (tshiftTy (S c) T)\n    | tapp T1 T2   => tapp (tshiftTy c T1) (tshiftTy c T2)\n    | tarr T1 T2   => tarr (tshiftTy c T1) (tshiftTy c T2)\n    | tall K T     => tall K (tshiftTy (S c) T)\n  end.\n\nFixpoint tshiftTm (c : nat) (t : Tm) : Tm :=\n  match t with\n    | var x        => var x\n    | abs T  t     => abs (tshiftTy c T) (tshiftTm c t)\n    | app t1 t2    => app (tshiftTm c t1) (tshiftTm c t2)\n    | tyabs K t    => tyabs K (tshiftTm (S c) t)\n    | tyapp t T    => tyapp (tshiftTm c t) (tshiftTy c T)\n  end.\n\n\nFixpoint shiftTm (c : nat) (t : Tm) : Tm :=\n  match t with\n    | var x        => var (shiftIndex c x)\n    | abs T1 t2    => abs T1 (shiftTm (S c) t2)\n    | app t1 t2    => app (shiftTm c t1) (shiftTm c t2)\n    | tyabs K1 t2  => tyabs K1 (shiftTm c t2)\n    | tyapp t1 T2  => tyapp (shiftTm c t1) T2\n  end.\n\n(******************************************************************************)\n(* Type substitution.                                                         *)\n(******************************************************************************)\n\nFixpoint tsubstIndex (X : nat) (T' : Ty) (Y : nat) : Ty :=\n  match X , Y with\n    | O   , O      => T'\n    | O   , S Y    => tvar Y\n    | S X , O      => tvar O\n    | S X , S Y    => tshiftTy 0 (tsubstIndex X T' Y)\n  end.\n\nFixpoint tsubstTy (X : nat) (T' : Ty) (T : Ty) : Ty :=\n  match T with\n    | tvar Y       => tsubstIndex X T' Y\n    | tabs K T     => tabs K (tsubstTy (S X) T' T)\n    | tapp T1 T2   => tapp (tsubstTy X T' T1) (tsubstTy X T' T2)\n    | tarr T1 T2   => tarr (tsubstTy X T' T1) (tsubstTy X T' T2)\n    | tall K T     => tall K (tsubstTy (S X) T' T)\n  end.\n\nFixpoint tsubstTm (X : nat) (T' : Ty) (t : Tm) : Tm :=\n  match t with\n    | var x        => var x\n    | abs T1 t2    => abs  (tsubstTy X T' T1) (tsubstTm X T' t2)\n    | app t1 t2    => app  (tsubstTm X T' t1) (tsubstTm X T' t2)\n    | tyabs K1 t2  => tyabs K1 (tsubstTm (S X) T' t2)\n    | tyapp t1 T2  => tyapp (tsubstTm X T' t1) (tsubstTy X T' T2)\n\n  end.\n\n(******************************************************************************)\n(* Term substitutions.                                                        *)\n(******************************************************************************)\n\nInductive Trace : Set :=\n  | I0\n  | IV (i : Trace)\n  | IT (i : Trace).\n\n(*  means [x |-> t] y  *)\nFixpoint substIndex (x : Trace) (t : Tm) (y : nat) : Tm :=\n  match x , y with\n    | I0   , O     => t\n    | I0   , S y   => var y\n    | IV x , O     => var O\n    | IV x , S y   => shiftTm O (substIndex x t y)\n    | IT x , y     => tshiftTm 0 (substIndex x t y)\n  end.\n\n(*  means [x |-> t'] t  *)\nFixpoint substTm (x : Trace) (t' : Tm) (t : Tm) : Tm :=\n  match t with\n    | var y        => substIndex x t' y\n    | abs T1 t2    => abs T1 (substTm (IV x) t' t2)\n    | app t1 t2    => app (substTm x t' t1) (substTm x t' t2)\n    | tyabs K1 t2  => tyabs K1 (substTm (IT x) t' t2)\n    | tyapp t1 T2  => tyapp (substTm x t' t1) T2\n  end.\n\n(******************************************************************************)\n(* Context lookups.                                                           *)\n(******************************************************************************)\n\n(* lookup_evar Γ x T  means  x:T ∈ Γ  *)\nInductive lookup_evar : Env → nat → Ty → Prop :=\n  | lookup_evar_here {Γ T} :\n      lookup_evar (evar Γ T) 0 T\n  | lookup_evar_there_evar {Γ T T' x} :\n      lookup_evar Γ x T →\n      lookup_evar (evar Γ T') (S x) T\n  | lookup_evar_there_etvar {Γ T K x} :\n      lookup_evar Γ x T →\n      lookup_evar (etvar Γ K) x (tshiftTy 0 T).\nHint Constructors lookup_evar.\n\nInductive lookup_etvar : Env → nat → Kind → Prop :=\n  | lookup_etvar_here {Γ K} :\n      lookup_etvar (etvar Γ K) 0 K\n  | lookup_etvar_there_evar {Γ T T' X} :\n      lookup_etvar Γ X T →\n      lookup_etvar (evar Γ T') X T\n  | lookup_etvar_there_etvar {Γ K K' X} :\n      lookup_etvar Γ X K →\n      lookup_etvar (etvar Γ K') (S X) K.\nHint Constructors lookup_etvar.\n", "meta": {"author": "Blaisorblade", "repo": "knot-esop-2017-case-study", "sha": "cf541cb38a483a514474f4c948bf005bc49b1e6f", "save_path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study", "path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study/knot-esop-2017-case-study-cf541cb38a483a514474f4c948bf005bc49b1e6f/casestudy/manual/fomega/BoilerplateFunctions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6536960451982242}}
{"text": "Add LoadPath \"C:\\Users\\Jonathan\\source\\repos\\PLT-Coq\\Software Foundations\\Logical Foundations\".\nRequire Export Lists.\n\n\nInductive list (X: Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\nCheck list.\n\nCheck (nil nat).\n\nCheck (cons nat 3 (nil nat)).\n\nCheck nil.\n\nCheck cons.\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\nFixpoint repeat (X : Type) (x : X) (count : nat)\n  : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\nend.\n\nExample test_repeat1 : repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity. Qed.\n\nExample test_repeat2 : repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity. Qed.\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')\nend.\n\nCheck repeat'.\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')\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 _))).\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\nFixpoint repeat''' {X: Type} (x: X) (count: nat) : list X :=\n  match count with\n  | 0 => nil\n  | S count' => cons x (repeat''' x count')\nend.\n\nFixpoint app {X : Type} (l_1 l_2 : list X) : list X :=\n  match l_1 with\n  | nil => l_2\n  | cons h t => cons h (app t l_2)\nend.\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 => 0\n  | cons _ l' => S (length l')\nend.\n\nExample test_rev1: rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\n\nExample test_rev2 : rev (cons true nil) = cons true nil.\nProof. reflexivity. Qed.\n\nExample test_length1 : length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity. Qed.\n\nFail Definition mynil := nil.\n\nDefinition mynil : list nat := nil.\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\n(* Exercises poly_exercises *)\n\nTheorem app_nil_r : forall (X : Type), forall l: list X,\n  l ++ [] = l.\nProof.\n  induction l as [| h l' IHl'].\n  + reflexivity.\n  + simpl. rewrite IHl'. reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n : list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  induction l as [| h l' IHl'].\n  + reflexivity.\n  + intros. simpl. rewrite <- IHl'. reflexivity.\nQed.\n\nLemma app_length : forall (X: Type) (l_1 l_2 : list X),\n  length (l_1 ++ l_2) = length l_1 + length l_2.\nProof.\n  induction l_1 as [| h l_1' IHl1'].\n  - reflexivity.\n  - intros. simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\n(* Exercises more_poly exercises *)\n\nTheorem rev_app_distr : forall X (l_1 l_2 : list X),\n  rev (l_1 ++ l_2) = rev l_2 ++ rev l_1.\nProof.\n  intros. induction l_1 as [| h l_1' IHl1'].\n  - rewrite app_nil_r. reflexivity.\n  - simpl. rewrite IHl1'. rewrite app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall X: Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros. induction l as [| h l' IHl'].\n  - reflexivity.\n  - simpl. rewrite -> rev_app_distr. rewrite -> IHl'. reflexivity.\nQed.\n\n(* Polymorphic pairs *)\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, s) => x\nend.\n\nDefinition snd {X Y : Type} (p: X * Y) : Y :=\n  match p with  \n  | (x, y) => y\nend.\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)\nend.\n\n(* Exercise combine_checks *)\n\nCheck @combine.\nCompute (combine [1;2] [false;false;true;true]).\n\n(* Exercise split *)\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      | (xs, ys) => (x::xs, y::ys)\n    end\nend.\n\nExample test_split:\n  split [(1, false);(2, false)] = ([1;2], [false;false]).\nProof. reflexivity. Qed.\n\nModule OptionPlayground.\n\nInductive option (X: Type) : Type :=\n  | Some : X -> option X\n  | None : option X.\n\nArguments Some {X} _.\nArguments None {X}.\n\nEnd OptionPlayground.\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if beq_nat n O \n                then Some a \n                else nth_error l' (pred n)\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 [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\n\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) \n  : option X :=\n    match l with\n    | [] => None\n    | h :: t => Some h\nend.\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\n(* Functions as Data *)\n\nDefinition doit3times {X: Type} (f: X -> X) (n : X) : X :=\nf (f (f (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\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 := 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.\n\nExample test_countoddmembers'2: countoddmembers' [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_anon_fun': 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]] = [[3];[4];[8]].\nProof. reflexivity. Qed.\n\n(* Exercise filter_even_gt7 *)\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n => (andb (evenb n) (negb (blt_nat n 7)))) l.\n\nExample test_filter_even_gt7_1 : filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity. Qed.\n\nExample test_filter_event_gt7_2 : filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\n\n(* Exercise partition *)\nDefinition partition {X : Type} (test : X -> bool) (l : list X) : list X * list X :=\n  ((filter test l), (filter (fun n => (negb (test n))) l)).\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\n\nExample test_partition2 : partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n\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 (fun x => plus 3 x) [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 : 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_app_distr : forall (X Y: Type) (f : X -> Y) (l_1 l_2 : list X),\n  map f (l_1 ++ l_2) = (map f l_1) ++ (map f l_2).\nProof.\n  intros.\n  induction l_1 as [| h_1 l_1' IHl1'].\n  - reflexivity.\n  - simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros. induction l as [| h l' IHl'].\n  - reflexivity.\n  - simpl. rewrite -> map_app_distr. rewrite IHl'. reflexivity.\nQed.\n\n(* Exercise flat_map *)\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: 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\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)\nend.\n\nCheck (fold andb).\n\nExample fold_example1 : fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2: fold andb [true; true; false; true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3: fold app [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\nDefinition constfun {X : Type} (x : X) : nat -> X :=\n  fun (k : nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\nCheck plus.\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 : plus3 4 = 7.\nProof. reflexivity. Qed.\n\nExample test_plus3' : doit3times plus3 0 = 9.\nProof. reflexivity. Qed.\n\nExample test_plus3'' : doit3times (plus 3) 0 = 9.\nProof. reflexivity. Qed.\n\n(* Exercise fold_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\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros. induction l as [| h l' IHl'].\n  - reflexivity.\n  - simpl.\n    rewrite <- IHl'.\n    unfold fold_length.\n    reflexivity.\nQed.\n\n(* Exercise fold_map *)\n\nDefinition fold_map {X Y: Type} (f : X -> Y) (l : list X) : list Y :=\n  fold (fun h t => (f h) :: t) l [].\n\nExample test_fold_map : fold_map (fun x => x) [1;2;3;4] = [1;2;3;4].\nProof. reflexivity. Qed.\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  intros. induction l as [| h l' IHl'].\n  - reflexivity.\n  - simpl. \n    rewrite <- IHl'.\n    unfold fold_map.\n    reflexivity.\nQed.\n\n\n(* Exercise currying *)\n\nDefinition prod_curry {X Y Z : Type} (f : X * Y -> Z) (x : X) (y : Y) : Z := f(x, y).\n\nDefinition prod_uncurry {X Y Z : Type} (f : X -> Y -> Z) (p : X * Y) : Z := f (fst p) (snd p).\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type) (f : X -> Y -> Z) x y, \n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  intros.\n  unfold prod_curry.\n  unfold prod_uncurry.\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.\n  destruct p.\n  unfold prod_uncurry.\n  simpl.\n  unfold prod_curry.\n  reflexivity.\nQed.\n\n(* Exercise church_numerals *)\n\nModule Church.\n\nDefinition nat := forall X : Type, (X -> X) -> X -> X.\n\nDefinition one : nat := fun (X : Type) (f : X -> X) (x : X) => f x.\n\nDefinition two : nat := fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\nDefinition zero : nat := fun (X : Type) (f : X -> X) (x : X) => x.\n\nDefinition three : nat := @doit3times.\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 : plus (plus two two) three = plus one (plus three three).\nProof. reflexivity. Qed.\n\nDefinition mult (n m : nat) : nat :=  \n  fun (X : Type) (f : X -> X) (x : X) => (n X (m X f) x).\n\nExample mult_1 : mult one one = one.\nProof. reflexivity. Qed.\n\nExample mult_2 : mult zero (plus three three) = zero.\nProof. reflexivity. Qed.\n\nExample mult_3 : mult two three = plus three three.\nProof. reflexivity. Qed.\n\nDefinition exp (n m  : nat) : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => (m (X -> X) (n X) f) 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.\n\n\n\n", "meta": {"author": "Ryxai", "repo": "PLT-Coq", "sha": "c8f6670e65cafc933ea67e890ceb6c5c80976816", "save_path": "github-repos/coq/Ryxai-PLT-Coq", "path": "github-repos/coq/Ryxai-PLT-Coq/PLT-Coq-c8f6670e65cafc933ea67e890ceb6c5c80976816/Software Foundations/Logical Foundations/Polymorphic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.6536960408140084}}
{"text": "Require Import CT.Algebra.Lattice.\nRequire Import CT.Order.PartiallyOrderedSet.\nRequire Import Coq.Program.Basics.\nRequire Setoid.\n\n(** * Boolean Algebras\n\nThere are many equivalent definitions of a boolean algebra, but the one we take\nbuilds on our definition of a [Lattice]. In this definition, a [BooleanAlgebra]\nis a [Lattice] with an additional function [notB] which is an endomorphism over\nthe carrier set that satisfies:\n\n  - le (meet a b) c  iff  le a (join (notB b) c)\n\nWe use [notB] instead of [not] so as not to conflict with\n[not : Prop -> Prop].\n*)\n\nRecord BooleanAlgebra :=\n  { L :> Lattice;\n    notB : element L -> element L;\n    condB : forall a b c : element L,\n        le (poset L) (meet L a b) c <-> le (poset L) a (join L (notB b) c)\n  }.\n\n(* Play around in the context of [Prop]. *)\n(*\nSection ToyProp.\n  Program Definition prop_poset : PartiallyOrderedSet :=\n    {| le := fun a b => (a = (b /\\ a)) <-> ((a \\/ b) = b) |}.\n  Next Obligation.\n\n  Program Definition prop_lat : Lattice :=\n    {| element := Prop;\n       poset := prop_poset;\n       meet := fun a b => a /\\ b;\n       join := fun a b => a \\/ b;\n    |}.\n  Next Obligation.\n*)", "meta": {"author": "relrod", "repo": "ct", "sha": "abd8b0067e219ee4867f7136bdf1b35885224cb4", "save_path": "github-repos/coq/relrod-ct", "path": "github-repos/coq/relrod-ct/ct-abd8b0067e219ee4867f7136bdf1b35885224cb4/CT/Algebra/BooleanAlgebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6536748858411423}}
{"text": "(* The two Four Lemmas *)\n\nRequire Import Utf8.\nRequire Import AbGroup Setoid.\n\n(* Four lemma #1\n           g       h        j\n        B------>C------>D------>E\n        |       |       |       ∩\n       b|      c|      d|      e|\n        v       |       v       |\n        v       v       v       v\n        B'----->C'----->D'----->E'\n           g'      h'      j'\n\n  If 1/ the diagram is commutative,\n     2/ (g, h, j) and (g', h', j') are exact,\n     3/ b and d are epimorphisms,\n     4/ e is monomorphism,\n  Then\n     c is an epimorphism.\n*)\n\nLemma four_1 :\n  ∀ (B C D E B' C' D' E' : AbGroup)\n     (g : HomGr B C) (h : HomGr C D) (j : HomGr D E)\n     (g' : HomGr B' C') (h' : HomGr C' D') (j' : HomGr D' E')\n     (b : HomGr B B') (c : HomGr C C')\n     (d : HomGr D D') (e : HomGr E E'),\n  diagram_commutes g b c g'\n  → diagram_commutes h c d h'\n  → diagram_commutes j d e j'\n  → exact_sequence [g; h; j]\n  → exact_sequence [g'; h'; j']\n  → is_epi b ∧ is_epi d ∧ is_mono e\n  → is_epi c.\nProof.\nintros * Hcgg' Hchh' Hcjj' s s' (Heb & Hed & Hme).\nunfold is_epi.\nenough\n  (∀ T (g₁ g₂ : HomGr C' T),\n   (∀ z, z ∈ C → (Happ g₁ (Happ c z) = Happ g₂ (Happ c z))%G)\n   → ∀ z', z' ∈ C' → (Happ g₁ z' = Happ g₂ z')%G). {\n  now intros T g₁ g₂ H1; apply H.\n}\nintros * Hgc * Hz'.\nassert (H : ∃ t, t ∈ D ∧ (Happ d t = Happ h' z')%G). {\n  apply epi_is_surj; [ easy | now apply h' ].\n}\ndestruct H as (t & Ht & Hdt).\nmove t after z'; move Ht after Hz'.\nassert (H : ∃ z, z ∈ C ∧ (Happ h z = t)%G). {\n  assert (H : t ∈ Ker j). {\n    split; [ easy | ].\n    assert (H : (Happ e (Happ j t) = 0)%G). {\n      rewrite Hcjj'.\n(* works not: a coq morphism is required\nrewrite Hdt.\n*)\n      etransitivity; [ apply Happ_compat | ]; [ | apply Hdt | ]; cycle 1.\n      -assert (H : Happ h' z' ∈ Im h') by (exists z'; easy).\n       now apply s' in H; simpl in H.\n      -now apply d.\n    }\n    specialize (mono_is_inj Hme) as H1.\n    apply H1; [ now apply j | apply E | now rewrite Hzero ].\n  }\n  apply s in H.\n  destruct H as (z & Hz & Hhz).\n  now exists z.\n}\ndestruct H as (z & Hz & Hhz).\nmove z after t; move Hz after Ht.\nassert (H : Happ c z - z' ∈ Ker h'). {\n  split.\n  -apply C'; [ now apply c | now apply C' ].\n  -rewrite Hadditive; [ | now apply c | now apply C' ].\n   rewrite Hopp; [ | easy ].\n   rewrite <- Hchh'.\n   apply gr_sub_move_r.\n   rewrite gr_add_0_l.\n   etransitivity; [ apply Happ_compat | ]; [ | apply Hhz | ]; try easy.\n   now apply h.\n}\napply s' in H.\ndestruct H as (y' & Hy' & Hgy').\nmove y' after z'; move Hy' before Hz'.\nassert (H : ∃ y, y ∈ B ∧ (Happ b y = y')%G) by now apply epi_is_surj.\ndestruct H as (y & Hy & Hby).\nmove y after z; move Hy before Hz.\nspecialize (Hgc (z - Happ g y)) as H1.\nassert (H : z - Happ g y ∈ C). {\n  apply C; [ easy | now apply C, g ].\n}\nspecialize (H1 H); clear H.\nassert (H : (Happ c (z - Happ g y) = z')%G). {\n  rewrite Hadditive; [ | easy | now apply C, g ].\n  rewrite Hopp; [ | now apply g ].\n  apply gr_sub_move_r.\n  apply gr_sub_move_l.\n  rewrite <- Hgy'.\n  rewrite Hcgg'.\n  apply g'; [ easy | now symmetry ].\n}\nsymmetry in H.\netransitivity; [ apply Happ_compat | ]; [ | apply H | ]; cycle 1.\n-rewrite H1.\n apply g₂; [ | easy ].\n apply c, C; [ easy | now apply C, g ].\n-easy.\nQed.\n\n(* Four lemma #2\n            f      g       h\n        A------>B------>C------>D\n        |       ∩       |       ∩\n       a|      b|      c|      d|\n        v       |       |       |\n        v       v       v       v\n        A'----->B'----->C'----->D'\n           f'      g'      h'\n\n  If 1/ the diagram is commutative,\n     2/ (f, g, h) and (f', g', h') are exact,\n     3/ b and d are monomorphisms,\n     4/ a is epimorphism,\n  Then\n     c is an monomorphism.\n*)\n\nLemma four_2 :\n  ∀ (A B C D A' B' C' D' : AbGroup)\n     (f : HomGr A B) (g : HomGr B C) (h : HomGr C D)\n     (f' : HomGr A' B') (g' : HomGr B' C') (h' : HomGr C' D')\n     (a : HomGr A A') (b : HomGr B B')\n     (c : HomGr C C') (d : HomGr D D'),\n  diagram_commutes f a b f'\n  → diagram_commutes g b c g'\n  → diagram_commutes h c d h'\n  → exact_sequence [f; g; h]\n  → exact_sequence [f'; g'; h']\n  → is_mono b ∧ is_mono d ∧ is_epi a\n  → is_mono c.\nProof.\nintros * Hcff' Hcgg' Hchh' s s' (Hmb & Hmd & Hea).\nintros T g₁ g₂ Hcg u Hu.\nspecialize (Hcg u Hu) as H.\nassert (H1 :( Happ c (Happ g₁ u - Happ g₂ u) = 0)%G). {\n  rewrite Hadditive; [ | now apply g₁ | now apply C, g₂ ].\n  rewrite Hopp; [ | now apply g₂ ].\n  now rewrite H, gr_add_opp_r.\n}\nclear H.\nsymmetry; rewrite <- gr_add_0_r; symmetry.\napply gr_sub_move_l.\nset (z := Happ g₁ u - Happ g₂ u) in H1 |-*.\nassert (Hz : z ∈ C) by (apply C; [ now apply g₁ | now apply C, g₂ ]).\nmove Hz before z.\ngeneralize H1; intros H2.\napply (Happ_compat _ _ h') in H2; [ | now apply c ].\nrewrite <- Hchh', Hzero in H2.\nassert (H3 : z ∈ Ker h). {\n  split; [ easy | ].\n  apply (mono_is_inj Hmd); [ now apply h | apply D | now rewrite Hzero ].\n}\napply s in H3.\ndestruct H3 as (y & Hy & Hgy).\ngeneralize Hgy; intros H3.\napply (Happ_compat _ _ c) in H3; [ | now apply g ].\nrewrite Hcgg', H1 in H3.\nassert (H4 : Happ b y ∈ Ker g') by (split; [ now apply b | easy ]).\napply s' in H4.\ndestruct H4 as (x' & Hx' & Hfx').\nassert (H : ∃ x, x ∈ A ∧ (Happ a x = x')%G) by now apply epi_is_surj.\ndestruct H as (x & Hx & Hax).\nassert (H4 : (Happ f' (Happ a x) = Happ b y)%G). {\n  etransitivity; [ apply Happ_compat | ]; [ | apply Hax | ]; try easy.\n  now apply a.\n}\nrewrite <- Hcff' in H4.\napply mono_is_inj in H4; [ | easy | now apply f | easy ].\nassert (H5 : (Happ g (Happ f x) = z)%G). {\n  etransitivity; [ apply Happ_compat | ]; [ | apply H4 | ]; try easy.\n  now apply f.\n}\nrewrite <- H5.\nassert (H : Happ f x ∈ Im f) by now exists x.\napply s in H.\nnow destruct H.\nQed.\n\n", "meta": {"author": "roglo", "repo": "coq_homol_algeb", "sha": "17ddb3146c93fe9bc88a71b6f9e89ba3793f01b1", "save_path": "github-repos/coq/roglo-coq_homol_algeb", "path": "github-repos/coq/roglo-coq_homol_algeb/coq_homol_algeb-17ddb3146c93fe9bc88a71b6f9e89ba3793f01b1/four.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.653667137931342}}
{"text": "Load FJ_tactics.\nRequire Import List.\nRequire Import FunctionalExtensionality.\n\nSection Folds.\n\n  (* ============================================== *)\n  (* ALGEBRAS AND FOLDS                             *)\n  (* ============================================== *)\n\n  (* Ordinary Algebra *)\n  Definition Algebra (F: Set -> Set) (A : Set) :=\n    F A -> A.\n\n  (* Mixin Algebra *)\n  Definition Mixin (T: Set) (F: Set -> Set) (A : Set) :=\n    (T -> A) -> F T -> A.\n\n  (* Mendler Algebra *)\n  Definition MAlgebra (F: Set -> Set) (A : Set) :=\n    forall (R : Set), Mixin R F A.\n\n  Definition Fix (F : Set -> Set) : Set :=\n    forall (A : Set), MAlgebra F A -> A.\n\n  Definition mfold {F : Set -> Set} :\n    forall (A : Set) (f : MAlgebra F A),\n      Fix F -> A:= fun A f e => e A f.\n\n  Class Functor (F : Set -> Set) :=\n    { fmap :\n        forall {A B : Set} (f : A -> B), F A -> F B;\n      fmap_fusion :\n        forall (A B C: Set) (f : A -> B) (g : B -> C) (a : F A),\n          fmap g (fmap f a) = fmap (fun e => g (f e)) a;\n      fmap_id :\n        forall (A : Set) (a : F A),\n          fmap (@id A) a = a\n    }.\n\n  Definition in_t {F} : F (Fix F) -> Fix F :=\n    fun F_e A f => f _ (mfold _ f) F_e.\n\n  Definition fold_ {F : Set -> Set} {functor : Functor F} :\n    forall (A : Set) (f : Algebra F A), Fix F -> A :=\n      fun A f => mfold _ (fun r rec fa => f (fmap rec fa)).\n\n  Definition out_t {F : Set -> Set} {fun_F : Functor F} : Fix F -> F (Fix F) :=\n    @fold_ F fun_F _ (fmap in_t).\n\n  Fixpoint boundedFix {A: Set}\n    {Exp: Set -> Set}\n    {fun_F: Functor Exp}\n    (n : nat)\n    (fM: Mixin (Fix Exp) Exp A)\n    (default: A)\n    (e: Fix Exp): A :=\n    match n with\n      | 0   => default\n      | S n => fM (boundedFix n fM default) (out_t e)\n    end.\n\n  (* Indexed Algebra *)\n  Definition iAlgebra {I : Set} (F : (I -> Prop) -> I -> Prop) (A : I -> Prop) :=\n    forall i, F A i -> A i.\n\n  (* Indexed Mendler Algebra *)\n  Definition iMAlgebra {I : Set} (F : (I -> Prop) -> I -> Prop) (A : I -> Prop) :=\n    forall i (R : I -> Prop), (forall i, R i -> A i) -> F R i -> A i.\n\n  Definition iFix {I : Set} (F : (I -> Prop) -> I -> Prop) (i : I) : Prop :=\n    forall (A : I -> Prop), iMAlgebra F A -> A i.\n\n  Definition imfold {I : Set} (F : (I -> Prop) -> I -> Prop) :\n    forall (A : I -> Prop) (f : iMAlgebra F A) (i : I),\n      iFix F i -> A i := fun A f i e => e A f.\n\n  Class iFunctor {I : Set} (F : (I -> Prop) -> I -> Prop) :=\n    { ifmap :\n        forall {A B : I -> Prop} i (f : forall i, A i -> B i), F A i -> F B i;\n      ifmap_fusion :\n        forall (A B C: I -> Prop) i (f : forall i, A i -> B i) (g : forall i, B i -> C i) (a : F A i),\n          ifmap i g (ifmap i f a) = ifmap i (fun i e => g _ (f i e)) a;\n      ifmap_id :\n        forall (A : I -> Prop) i (a : F A i),\n          ifmap i (fun _ => id) a = a\n    }.\n\n  Definition in_ti {I : Set} {F} : forall i : I, F (iFix F) i -> iFix F i :=\n    fun i F_e A f => f _ _ (imfold _ _ f) F_e.\n\n  Definition ifold_ {I : Set} (F : (I -> Prop) -> I -> Prop) {iFun_F : iFunctor F} :\n    forall (A : I -> Prop) (f : iAlgebra F A) (i : I),\n      iFix F i -> A i := fun A f i e => imfold _ _ (fun i' r rec fa => f i' (ifmap i' rec fa)) i e.\n\n  Definition out_ti {I : Set} {F} {fun_F : iFunctor F} : forall i : I, iFix F i -> F (iFix F) i :=\n    @ifold_ I F fun_F _ (fun i => ifmap i in_ti).\n\n  (* Universal Property of Mendler Folds *)\n\n  Lemma Universal_Property (F : Set -> Set) (A : Set) (f : MAlgebra F A) :\n    forall (h : Fix F -> A),\n      h = mfold _ f -> forall e, h (in_t e) = f _ h e.\n  Proof.\n    intros; rewrite H. unfold in_t. unfold mfold.\n    reflexivity.\n  Qed.\n\n  Class Universal_Property' {F} {Fun_F : Functor F} (e : Fix F) :=\n    { E_UP' : forall (A : Set) (f : MAlgebra F A) (h : Fix F -> A),\n                (forall e, h (in_t e) = f _ h e) ->\n                h e = mfold _ f e\n    }.\n\n  Lemma Fix_id F {fun_F : Functor F} e {UP' : Universal_Property' e} :\n    mfold _ (fun _ rec x => in_t (fmap rec x)) e = e.\n  Proof.\n    intros; apply sym_eq.\n    fold (id e); unfold id at 2; apply (E_UP'); intros.\n    unfold id.\n    unfold in_t.\n    eapply (@functional_extensionality_dep Set).\n    intros; eapply @functional_extensionality_dep; intros.\n    rewrite fmap_id.\n    reflexivity.\n  Defined.\n\n  Definition MAlg_to_Alg {F : Set -> Set} {A : Set} :\n    MAlgebra F A -> Algebra F A := fun MAlg f => MAlg A id f.\n\n  (* Universal Property of regular folds. *)\n\n  Lemma Universal_Property_fold (F : Set -> Set) {fun_F : Functor F} (B : Set)\n    (f : Algebra F B) : forall (h : Fix F -> B), h = fold_ _ f ->\n      forall e, h (in_t e) = f (fmap h e).\n  Proof.\n    intros; rewrite H; reflexivity.\n  Qed.\n\n  Class Universal_Property'_fold {F} {fun_F : Functor F} (e : Fix F) :=\n    { E_fUP' : forall (B : Set) (f : Algebra F B) (h : Fix F -> B),\n                 (forall e, h (in_t e) = f (fmap h e)) ->\n                 h e = fold_ _ f e\n    }.\n\n  Lemma Fix_id_fold F {fun_F : Functor F} e {UP' : Universal_Property'_fold e} :\n    fold_ _ (@in_t F) e = e.\n  Proof.\n    intros; apply sym_eq.\n    fold (id e); unfold id at 2; apply (E_fUP'); intros.\n    rewrite fmap_id.\n    unfold id.\n    reflexivity.\n  Qed.\n\n  Lemma Fusion F {fun_F : Functor F} e {e_UP' : Universal_Property'_fold e} :\n    forall (A B : Set) (h : A -> B) (f : Algebra F A) (g : Algebra F B),\n      (forall a, h (f a) = g (fmap h a)) ->\n      (fun e' => h (fold_ _ f e')) e = fold_ _ g e.\n  Proof.\n    intros; eapply E_fUP'; try eassumption; intros.\n    rewrite (Universal_Property_fold F _ f _ (refl_equal _)).\n    rewrite H.\n    rewrite fmap_fusion; reflexivity.\n  Qed.\n\n  Lemma in_out_inverse (F : Set -> Set) (Fun_F : Functor F) :\n    forall (e : Fix F) {fUP' : Universal_Property'_fold e},\n      in_t (out_t e) = e.\n  Proof.\n    intros.\n    rewrite <- (@Fix_id_fold _ _ e fUP') at -1.\n    eapply E_fUP' with (h := fun e => in_t (out_t e)).\n    intro.\n    cut (out_t (in_t e0) = fmap (fun e1 => in_t (out_t e1)) e0); intros.\n    rewrite H; reflexivity.\n    unfold out_t.\n    rewrite Universal_Property with (f := (fun (R : Set) (rec : R -> F (Fix F)) (fp : F R) =>\n      fmap (fun r : R => in_t (rec r)) fp)); eauto.\n    unfold fold_; unfold mfold.\n    eapply functional_extensionality; intro.\n    cut ((fun (r : Set) (rec : r -> F (Fix F)) (fa : F r) =>\n      fmap in_t (fmap rec fa)) =\n      fun (R : Set) (rec : R -> F (Fix F)) (fp : F R) =>\n      fmap (fun r : R => in_t (rec r)) fp).\n    intro; rewrite H; reflexivity.\n    eapply (@functional_extensionality_dep Set); intro.\n    eapply functional_extensionality_dep; intro.\n    eapply functional_extensionality_dep; intro.\n    rewrite fmap_fusion; reflexivity.\n  Qed.\n\n  Definition in_t_UP' (F : Set -> Set) (Fun_F : Functor F) :\n    F (sig (@Universal_Property'_fold F Fun_F)) ->\n    sig (@Universal_Property'_fold F Fun_F).\n  Proof.\n    intro e; intros.\n    constructor 1 with (x := in_t (fmap (@proj1_sig _ _) e)).\n    constructor; intros.\n    rewrite H.\n    unfold fold_, mfold.\n    unfold in_t.\n    repeat rewrite fmap_fusion.\n    assert ((fun e0 : sig Universal_Property'_fold => h (proj1_sig e0)) =\n      (fun e0 : sig Universal_Property'_fold =>\n         mfold B (fun (r : Set) (rec : r -> B) (fa : F r) => f (fmap rec fa))\n           (proj1_sig e0))) by\n    (eapply @functional_extensionality_dep; intros e'; destruct e' as [e' e'_UP'];\n      simpl; eapply E_fUP'; eauto).\n    rewrite H0; reflexivity.\n  Defined.\n\n  Definition out_t_UP' (F : Set -> Set) (Fun_F : Functor F) :\n    forall (e : Fix F),\n      F (sig (@Universal_Property'_fold F Fun_F)).\n  Proof.\n    intros.\n    eapply fold_; try assumption.\n    unfold Algebra; intros.\n    eapply fmap.\n    apply in_t_UP'.\n    assumption.\n  Defined.\n\n  Lemma out_in_inverse (F : Set -> Set) (Fun_F : Functor F) :\n    forall (e : F (sig (@Universal_Property'_fold F Fun_F))),\n      out_t (in_t (fmap (@proj1_sig _ _) e)) = fmap (@proj1_sig _ _) e.\n  Proof.\n    intros.\n    unfold out_t.\n    erewrite Universal_Property_fold; try reflexivity.\n    rewrite fmap_fusion.\n    rewrite fmap_fusion.\n    assert ((fun e0 : sig Universal_Property'_fold =>\n      in_t (fold_ (F (Fix F)) (fmap in_t) (proj1_sig e0))) =\n    @proj1_sig _ _) by\n    (eapply functional_extensionality; intros;\n      fold (out_t (proj1_sig x));\n        rewrite in_out_inverse; destruct x; simpl; eauto).\n    rewrite H; reflexivity.\n  Qed.\n\n  Lemma in_t_UP'_inject (F : Set -> Set) (Fun_F : Functor F) :\n    forall (e e' : F (sig (@Universal_Property'_fold F Fun_F))),\n      in_t (fmap (@proj1_sig _ _) e) = in_t (fmap (@proj1_sig _ _) e') ->\n      fmap (@proj1_sig _ _) e = fmap (@proj1_sig _ _) e'.\n  Proof.\n    intros; apply (f_equal out_t) in H;\n      repeat rewrite out_in_inverse in H; eauto.\n  Qed.\n\n  Lemma in_out_UP'_inverse (H : Set -> Set) (Fun_H : Functor H) :\n    forall (h : Fix H),\n      Universal_Property'_fold h ->\n      proj1_sig (in_t_UP' H Fun_H (out_t_UP' H Fun_H h)) = h.\n  Proof.\n    intros; simpl.\n    assert ((fmap (@proj1_sig _ _) (out_t_UP' H Fun_H h)) = out_t h).\n    unfold out_t.\n    eapply E_fUP' with (h0 := fun e => fmap (@proj1_sig _ _) (out_t_UP' H Fun_H e)).\n    intros.\n    rewrite fmap_fusion.\n    assert (out_t_UP' H Fun_H (in_t e) =\n            fmap (fun e => in_t_UP' _ _ (out_t_UP' _ _ e)) e).\n    unfold out_t_UP' at 1.\n    erewrite Universal_Property_fold with\n      (f := (fun H2 : H (H (sig Universal_Property'_fold)) =>\n        fmap (in_t_UP' H Fun_H) H2)) (fun_F := Fun_H); eauto.\n    rewrite fmap_fusion; reflexivity.\n    rewrite H1; rewrite fmap_fusion; simpl; reflexivity.\n    rewrite H1.\n    rewrite in_out_inverse; unfold mfold; eauto.\n  Qed.\n\n  Lemma out_in_fmap (F : Set -> Set) (Fun_F : Functor F) :\n    forall (e : F (Fix F)),\n      out_t_UP' F _ (in_t e) =\n      fmap (fun e => in_t_UP' _ _ (out_t_UP' _ _ e)) e.\n  Proof.\n    intros; unfold out_t_UP' at 1.\n    erewrite Universal_Property_fold with\n    (f := (fun H2 : F (F (sig Universal_Property'_fold)) =>\n      fmap (in_t_UP' F Fun_F) H2)) (fun_F := Fun_F); eauto.\n    rewrite fmap_fusion; reflexivity.\n  Qed.\n\n  Definition UP'_P {F : Set -> Set} {Fun_F : Functor F}\n    (P : forall e : Fix F, Universal_Property'_fold e -> Prop) (e : Fix F) :=\n    sigT (P e).\n\n  Definition UP'_P2 {F F' : Set -> Set}\n    {Fun_F : Functor F} {Fun_F' : Functor F'}\n    (P : forall e : (Fix F) * (Fix F'),\n      Universal_Property'_fold (fst e) /\\ Universal_Property'_fold (snd e) -> Prop)\n    (e : (Fix F) * (Fix F')) := sig (P e).\n\n  Definition UP'_F (F : Set -> Set) {Fun_F : Functor F} :=\n    sig (Universal_Property'_fold (F := F)).\n\n  Fixpoint boundedFix_UP {A: Set}\n    {Exp: Set -> Set}\n    {fun_F: Functor Exp}\n    (n : nat)\n    (fM: Mixin (UP'_F Exp) Exp A)\n    (default: A)\n    (e: UP'_F Exp): A :=\n    match n with\n      | 0   => default\n      | S n => fM (boundedFix_UP n fM default) (out_t_UP' _ _ (proj1_sig e))\n    end.\n\n  Lemma bF_UP_in_out : forall {A: Set}\n    {Exp: Set -> Set}\n    {fun_F: Functor Exp}\n    (n : nat)\n    (fM: Mixin (UP'_F Exp) Exp A)\n    (default: A)\n    (e: Fix Exp)\n    (e_UP' : Universal_Property'_fold e),\n    boundedFix_UP n fM default (in_t_UP' _ _ (out_t_UP' _ _ e)) =\n    boundedFix_UP n fM default (exist _ e e_UP').\n  Proof.\n    induction n; simpl; intros; eauto.\n    generalize in_out_UP'_inverse as H0; intro; simpl in H0; rewrite H0; auto.\n  Qed.\n\n  (* ============================================== *)\n  (* FUNCTOR COMPOSITION                            *)\n  (* ============================================== *)\n\n  Definition inj_Functor {F G : Set -> Set} {A : Set} : Set := sum (F A) (G A).\n\n  Notation \"A :+: B\"  := (@inj_Functor A B) (at level 80, right associativity).\n\n  Global Instance Functor_Plus G H {fun_G : Functor G} {fun_H : Functor H} :\n    Functor (G :+: H) :=\n    {| fmap :=\n         fun (A B : Set) (f : A -> B) (a : (G :+: H) A) =>\n           match a with\n             | inl G' => inl _ (fmap f G')\n             | inr H' => inr _ (fmap f H')\n           end\n    |}.\n  Proof.\n    (* fmap_fusion *)\n    intros; destruct a;\n    rewrite fmap_fusion; reflexivity.\n    (* fmap_id *)\n    intros; destruct a;\n    rewrite fmap_id; reflexivity.\n  Defined.\n\n  Class Sub_Functor (sub_F sub_G : Set -> Set) : Set :=\n    { inj : forall {A : Set}, sub_F A -> sub_G A;\n      prj : forall {A : Set}, sub_G A -> option (sub_F A);\n      inj_prj : forall {A : Set} (ga : sub_G A) (fa : sub_F A),\n                  prj ga = Some fa -> ga = inj fa;\n      prj_inj : forall {A : Set} (fa : sub_F A),\n                  prj (inj fa) = Some fa\n    }.\n\n  Notation \"A :<: B\"  := (Sub_Functor A B) (at level 80, right associativity).\n\n  (* Need the 'Global' modifier so that the instance survives the Section.*)\n  Global Instance Sub_Functor_inl (F G H : Set -> Set) (sub_F_G : F :<: G) :\n    F :<: (G :+: H) :=\n    {| inj := fun (A : Set) (e : F A) => inl _ (@inj F G sub_F_G _ e);\n       prj := fun (A: Set) (e : (G :+: H) A) =>\n                match e with\n                  | inl e' => prj e'\n                  | inr _  => None\n                end\n    |}.\n  Proof.\n    intros; destruct ga; [rewrite (inj_prj _ _ H0); reflexivity | discriminate].\n    intros; simpl; rewrite prj_inj; reflexivity.\n  Defined.\n\n  Global Instance Sub_Functor_inr (F G H : Set -> Set) (sub_F_H : F :<: H) :\n    F :<: (G :+: H) :=\n    {| inj := fun (A : Set) (e : F A) => inr _ (@inj F H sub_F_H _ e);\n       prj := fun (A : Set) (e : (G :+: H) A) =>\n                match e with\n                  | inl _  => None\n                  | inr e' => prj e'\n                end\n    |}.\n  Proof.\n    intros; destruct ga; [discriminate | rewrite (inj_prj _ _ H0); reflexivity ].\n    intros; simpl; rewrite prj_inj; reflexivity.\n  Defined.\n\n  Global Instance Sub_Functor_id {F : Set -> Set} : F :<: F :=\n    {| inj := fun A => @id (F A);\n       prj := fun A => @Some (F A)\n    |}.\n  Proof.\n    unfold id; congruence.\n    reflexivity.\n  Defined.\n\n  (* ============================================== *)\n  (* WELL-FORMEDNESS OF FUNCTORS                    *)\n  (* ============================================== *)\n\n  Class WF_Functor (F G: Set -> Set)\n    (subfg: F :<: G)\n    {Fun_F: Functor F}\n    {Fun_G: Functor G} : Set :=\n    { wf_functor :\n        forall (A B : Set) (f : A -> B) (fa: F A) ,\n          fmap f (inj fa) (F := G) = inj (fmap f fa)\n    }.\n\n  Global Instance WF_Functor_id {F : Set -> Set} {Fun_F : Functor F} :\n    WF_Functor F F Sub_Functor_id.\n  Proof.\n    econstructor; intros; reflexivity.\n  Defined.\n\n  Global Instance WF_Functor_plus_inl {F G H : Set -> Set}\n    {Fun_F : Functor F}\n    {Fun_G : Functor G}\n    {Fun_H : Functor H}\n    {subfg : F :<: G}\n    {WF_Fun_F : WF_Functor F _ subfg}\n    :\n    WF_Functor F (G :+: H) (Sub_Functor_inl F G H _).\n  Proof.\n    econstructor; intros.\n    simpl; rewrite wf_functor; reflexivity.\n  Defined.\n\n  Global Instance WF_Functor_plus_inr {F G H : Set -> Set}\n    {Fun_F : Functor F}\n    {Fun_G : Functor G}\n    {Fun_H : Functor H}\n    {subfh : F :<: H}\n    {WF_Fun_F : WF_Functor F _ subfh}\n    :\n    WF_Functor F (G :+: H) (Sub_Functor_inr F G H _ ).\n  Proof.\n    econstructor; intros.\n    simpl; rewrite wf_functor; reflexivity.\n  Defined.\n\n  (* ============================================== *)\n  (* INJECTION + PROJECTION                         *)\n  (* ============================================== *)\n\n  Definition inject' {F G: Set -> Set} {Fun_F : Functor F} {subGF: G :<: F} :\n    G (sig (@Universal_Property'_fold F Fun_F)) -> (sig (@Universal_Property'_fold F Fun_F)) :=\n    fun gexp => in_t_UP' _ _ (inj gexp).\n\n  Definition inject {F G: Set -> Set} {Fun_F : Functor F} {subGF: G :<: F} :\n    G (sig (@Universal_Property'_fold F Fun_F)) -> Fix F :=\n      fun gexp => proj1_sig (in_t_UP' _ _ (inj gexp)).\n\n  Definition project {F G: Set -> Set} {Fun_F: Functor F} {subGF : G :<: F } :\n    Fix F -> option (G (sig (@Universal_Property'_fold F Fun_F))) :=\n      fun exp => prj (out_t_UP' _ _ exp).\n\n  Lemma project_inject : forall (G H : Set -> Set)\n    (Fun_G : Functor G)\n    (Fun_H : Functor H)\n    (sub_G_H : G :<: H)\n    (h : Fix H) (g : G (sig (@Universal_Property'_fold H Fun_H))),\n    Universal_Property'_fold h ->\n    project h = Some g -> h = inject g.\n  Proof.\n    intros.\n    apply inj_prj in H1.\n    unfold inject; rewrite <- H1.\n    erewrite in_out_UP'_inverse; eauto.\n  Qed.\n\n  Lemma inject_project : forall (F G  : Set -> Set)\n    (Fun_F : Functor F)\n    (Fun_G : Functor G)\n    (sub_G_F : G :<: F)\n    (g : G (sig (@Universal_Property'_fold F Fun_F))),\n    fmap (@proj1_sig _ _) (out_t_UP' _ _ (inject g)) =\n    (fmap (@proj1_sig _ _) (inj g)).\n  Proof.\n    unfold inject; intros; simpl.\n    rewrite out_in_fmap.\n    rewrite fmap_fusion.\n    assert (forall e : sig Universal_Property'_fold,\n      proj1_sig (in_t_UP' F Fun_F (out_t_UP' F Fun_F (proj1_sig e))) = proj1_sig e).\n    intros; eapply in_out_UP'_inverse.\n    intros; destruct e as [e e_UP']; eassumption.\n    rewrite fmap_fusion.\n    rewrite (functional_extensionality _ _ H).\n    reflexivity.\n  Qed.\n\n  Class Distinct_Sub_Functor (F G H : Set -> Set)\n    {Fun_H : Functor H}\n    {sub_F_H : F :<: H}\n    {sub_G_H : G :<: H}\n    : Set :=\n    { inj_discriminate :\n        forall A f g,\n          inj (Sub_Functor := sub_F_H) (A := A) f\n          <> inj (Sub_Functor := sub_G_H) (A := A) g\n    }.\n\n  Global Instance Distinct_Sub_Functor_plus\n    (F G H I : Set -> Set)\n    (Fun_G : Functor G)\n    (Fun_I : Functor I)\n    (sub_F_G : F :<: G)\n    (sub_H_I : H :<: I)\n    :\n    Distinct_Sub_Functor F H (G :+: I).\n  Proof.\n    econstructor; intros.\n    unfold not; simpl; unfold id; intros.\n    discriminate.\n  Defined.\n\n  Global Instance Distinct_Sub_Functor_plus'\n    (F G H I : Set -> Set)\n    (Fun_G : Functor G)\n    (Fun_I : Functor I)\n    (sub_F_G : F :<: G)\n    (sub_H_I : H :<: I)\n    :\n    Distinct_Sub_Functor F H (I :+: G).\n  Proof.\n    econstructor; intros.\n    unfold not; simpl; unfold id; intros.\n    discriminate.\n  Defined.\n\n  Global Instance Distinct_Sub_Functor_inl\n    (F G H I : Set -> Set)\n    (Fun_G : Functor G)\n    (Fun_I : Functor I)\n    (sub_F_G : F :<: G)\n    (sub_H_G : H :<: G)\n    (Dist_inl : Distinct_Sub_Functor F H G)\n    :\n    Distinct_Sub_Functor F H (G :+: I).\n  Proof.\n    econstructor; intros.\n    unfold not; intros.\n    simpl in H0; injection H0; intros.\n    eapply (inj_discriminate (Distinct_Sub_Functor := Dist_inl) _ f g H1).\n  Defined.\n\n  Global Instance Distinct_Sub_Functor_inr\n    (F G H I : Set -> Set)\n    (Fun_G : Functor G)\n    (Fun_I : Functor I)\n    (sub_F_G : F :<: G)\n    (sub_H_G : H :<: G)\n    (Dist_inl : Distinct_Sub_Functor F H G)\n    :\n    Distinct_Sub_Functor F H (I :+: G).\n  Proof.\n    econstructor; intros.\n    unfold not; intros.\n    simpl in H0; injection H0; intros.\n    eapply (inj_discriminate (Distinct_Sub_Functor := Dist_inl) _ f g H1).\n  Defined.\n\n  Lemma inject_discriminate : forall {F G H : Set -> Set}\n    {Fun_F : Functor F}\n    {Fun_G : Functor G}\n    {Fun_H : Functor H}\n    {sub_F_H : F :<: H}\n    {sub_G_H : G :<: H}\n    {WF_F : WF_Functor _ _ sub_F_H}\n    {WF_G : WF_Functor _ _ sub_G_H},\n    Distinct_Sub_Functor F G H ->\n    forall f g, inject (subGF := sub_F_H) f <> inject (subGF := sub_G_H) g.\n  Proof.\n    unfold inject; simpl; intros.\n    unfold not; intros H3; apply in_t_UP'_inject in H3.\n    repeat rewrite wf_functor in H3.\n    eapply (inj_discriminate _ _ _ H3).\n  Qed.\n\n  (* ============================================== *)\n  (* INDEXED FUNCTOR COMPOSITION                    *)\n  (* ============================================== *)\n\n  Definition inj_iFunctor {I : Set} {F G : (I -> Prop) -> I -> Prop} {A : I -> Prop} : I -> Prop :=\n    fun i => or (F A i) (G A i).\n\n  Notation \"A ::+:: B\"  := (@inj_iFunctor _ A B) (at level 80, right associativity).\n\n  Global Instance iFunctor_Plus {I : Set} (G H : (I -> Prop) -> I -> Prop)\n    {fun_G : iFunctor G} {fun_H : iFunctor H} : iFunctor (G ::+:: H) :=\n    {| ifmap :=\n         fun (A B : I -> Prop) (i : I) (f : forall i, A i -> B i) (a : (G ::+:: H) A i) =>\n           match a with\n             | or_introl G' => or_introl _ (ifmap i f G')\n             | or_intror H' => or_intror _ (ifmap i f H')\n           end\n    |}.\n  Proof.\n    (* ifmap_fusion *)\n    intros; destruct a;\n    rewrite ifmap_fusion; reflexivity.\n    (* ifmap_id *)\n    intros; destruct a;\n    rewrite ifmap_id; reflexivity.\n  Defined.\n\n  Class Sub_iFunctor {I : Set} (sub_F sub_G : (I -> Prop) -> I -> Prop) : Prop :=\n    { inj_i : forall {A : I -> Prop} i, sub_F A i -> sub_G A i;\n         prj_i : forall {A : I -> Prop} i, sub_G A i -> (sub_F A i) \\/ True\n    }.\n\n  Notation \"A ::<:: B\"  := (Sub_iFunctor A B) (at level 80, right associativity).\n\n  (* Need the 'Global' modifier so that the instance survives the Section.*)\n\n  Global Instance Sub_iFunctor_inl {I' : Set} (F G H : (I' -> Prop) -> I' -> Prop) (sub_F_G : F ::<:: G) :\n    F ::<:: (G ::+:: H) :=\n    {| inj_i := fun (A : I' -> Prop) i (e : F A i) =>\n                  or_introl _ (@inj_i _ F G sub_F_G _ _ e);\n       prj_i := fun (A: I' -> Prop) i (e : (G ::+:: H) A i) =>\n                  match e with\n                    | or_introl e' => prj_i _ e'\n                    | or_intror _  => or_intror _ I\n                  end\n    |}.\n\n  Global Instance Sub_iFunctor_inr {I' : Set} (F G H : (I' -> Prop) -> I' -> Prop) (sub_F_H : F ::<:: H) :\n    F ::<:: (G ::+:: H) :=\n    {| inj_i := fun (A : I' -> Prop) i (e : F A i) =>\n                    or_intror _ (@inj_i _ F H sub_F_H _ _ e);\n       prj_i := fun (A: I' -> Prop) i (e : (G ::+:: H) A i) =>\n                  match e with\n                    | or_intror e' => prj_i _ e'\n                    | or_introl _  => or_intror _ I\n                  end\n    |}.\n\n  Global Instance Sub_iFunctor_id {I : Set} {F : (I -> Prop) -> I -> Prop} : F ::<:: F :=\n    {| inj_i := fun A i e => e;\n       prj_i := fun A i e => or_introl _ e\n    |}.\n\n  Definition inject_i {I : Set} {F G: (I -> Prop) -> I -> Prop} {subGF: Sub_iFunctor G F} :\n    forall i, G (iFix F) i -> iFix F i:=\n    fun i gexp => in_ti i (inj_i i gexp).\n\n  Definition project_i {I : Set} {F G: (I -> Prop) -> I -> Prop}\n    {fun_F: iFunctor F}\n    {subGF: Sub_iFunctor G F} :\n    forall i, iFix F i -> (G (iFix F) i) \\/ True :=\n      fun i fexp => prj_i i (out_ti i fexp).\n\nEnd Folds.\n\nNotation \"A :+: B\"  := (@inj_Functor A B) (at level 80, right associativity).\nNotation \"A :<: B\"  := (Sub_Functor A B) (at level 80, right associativity).\nNotation \"A ::+:: B\"  := (@inj_iFunctor _ A B) (at level 80, right associativity).\nNotation \"A ::<:: B\"  := (Sub_iFunctor _ A B) (at level 80, right associativity).\n\nDefinition inj'' {F G : Set -> Set} (sub_F_G: F :<: G) {A : Set} := @inj F G sub_F_G A.\n\nSection FAlgebra.\n\n  (* ============================================== *)\n  (* OPERATIONS INFRASTRUCTURE                      *)\n  (* ============================================== *)\n\n  Class FAlgebra (Name : Set) (T: Set) (A: Set) (F: Set -> Set) : Set :=\n    { f_algebra : Mixin T F A }.\n\n  (* Definition FAlgebra_Plus (Name: Set) (T: Set) (A : Set) (F G : Set -> Set)\n    {falg: FAlgebra Name T A F} {galg: FAlgebra Name T A G} :\n    FAlgebra Name T A (F :+: G) :=\n    Build_FAlgebra Name T A _\n    (fun f fga =>\n      (match fga with\n         | inl fa => f_algebra f fa\n         | inr ga => f_algebra f ga\n       end)). *)\n\n  Global Instance FAlgebra_Plus (Name: Set) (T: Set) (A : Set) (F G : Set -> Set)\n    {falg: FAlgebra Name T A F} {galg: FAlgebra Name T A G} :\n    FAlgebra Name T A (F :+: G) | 6 :=\n    {| f_algebra := fun f fga =>\n                      match fga with\n                        | inl fa => f_algebra f fa\n                        | inr ga => f_algebra f ga\n                      end\n    |}.\n\n  (* The | 6 gives the generated Hint a priority of 6. If this is\n     less than that of other instances for FAlgebra, the\n     typeclass inference algorithm will loop.\n     *)\n\n  Class WF_FAlgebra (Name T A: Set) (F G: Set -> Set)\n    (subfg: F :<: G)\n    (falg: FAlgebra Name T A F)\n    (galg: FAlgebra Name T A G): Set :=\n    { wf_algebra :\n        forall rec (fa: F T),\n          @f_algebra Name T A G galg rec (@inj F G subfg T fa)\n          = @f_algebra Name T A F falg rec fa\n    }.\n\n  Global Instance WF_FAlgebra_id {Name T A : Set} {F} {falg: FAlgebra Name T A F}:\n    WF_FAlgebra Name T A F F Sub_Functor_id falg falg.\n  Proof.\n    econstructor. intros.\n    unfold inj.\n    unfold Sub_Functor_id.\n    unfold id.\n    reflexivity.\n  Defined.\n\n  Global Instance WF_FAlgebra_inl\n    {Name A T : Set}\n    {F G H}\n    {falg: FAlgebra Name T A F}\n    {galg: FAlgebra Name T A G}\n    {halg: FAlgebra Name T A H}\n    {sub_F_G: F :<: G}\n    {wf_F_G: WF_FAlgebra Name T A F G sub_F_G falg galg}\n    :\n    WF_FAlgebra Name T A F (G :+: H) (Sub_Functor_inl F G H sub_F_G) falg (@FAlgebra_Plus Name T A G H galg halg).\n  Proof.\n    econstructor. intros.\n    unfold inj. unfold Sub_Functor_inl.\n    simpl.\n    rewrite (wf_algebra rec fa).\n    reflexivity.\n  Defined.\n\n  Global Instance WF_FAlgebra_inr\n    {Name T A : Set}\n    {F G H}\n    {falg: FAlgebra Name T A F}\n    {galg: FAlgebra Name T A G}\n    {halg: FAlgebra Name T A H}\n    {sub_F_H: F :<: H}\n    {wf_G_H: WF_FAlgebra Name T A F H sub_F_H falg halg}\n    :\n    WF_FAlgebra Name T A F (G :+: H) (Sub_Functor_inr F G H sub_F_H) falg (@FAlgebra_Plus Name T A G H galg halg).\n  Proof.\n    econstructor. intros.\n    unfold inj.\n    unfold Sub_Functor_inr.\n    simpl.\n    rewrite (wf_algebra rec fa).\n    reflexivity.\n  Defined.\n\nEnd FAlgebra.\n\n  (* ============================================== *)\n  (* INDUCTION PRINCIPLES INFRASTRUCTURE            *)\n  (* ============================================== *)\n\nSection WF_Ind_FAlgebras.\n\n  Class PAlgebra (Name : Set) (A: Set) (F: Set -> Set) : Set :=\n    { p_algebra : Algebra F A}.\n\n  (* Definition PAlgebra_Plus (Name: Set) (A : Set) (F G : Set -> Set)\n    {falg: PAlgebra Name A F} {galg: PAlgebra Name A G} :\n    PAlgebra Name A (F :+: G) :=\n    Build_PAlgebra Name A _\n    (fun fga =>\n      (match fga with\n         | inl fa => p_algebra fa\n         | inr ga => p_algebra ga\n       end)). *)\n\n  Global Instance PAlgebra_Plus (Name: Set) (A : Set) (F G : Set -> Set)\n    {falg: PAlgebra Name A F} {galg: PAlgebra Name A G} :\n    PAlgebra Name A (F :+: G) | 6 :=\n    {| p_algebra := fun fga =>\n                      match fga with\n                        | inl fa => p_algebra fa\n                        | inr ga => p_algebra ga\n                      end\n    |}.\n\n  Class WF_Ind {E F: Set -> Set} {Name : Set} {Fun_E : Functor E} {Fun_F : Functor F}\n    {P : Fix E -> Prop} {sub_F_E : F :<: E}\n    (F_Alg : PAlgebra Name (sig P) F) :=\n    { proj_eq :\n        forall e,\n          proj1_sig (p_algebra (PAlgebra := F_Alg) e) =\n          in_t (inj (Sub_Functor := sub_F_E) (fmap (@proj1_sig _ _) e))\n    }.\n\n  Instance Sub_Functor_inl' (F G H : Set -> Set) (sub_F_G : (F :+: G) :<: H) :\n    F :<: H :=\n    {| inj := fun (A : Set) (e : F A) => @inj _ _ sub_F_G A (inl _ e);\n       prj := fun (A : Set) (ha : H A) =>\n                match @prj _ _ sub_F_G A ha with\n                  | Some (inl f) => Some f\n                  | Some (inr g) => None\n                  | None => None\n                end\n    |}.\n  Proof.\n    intros until fa; caseEq (prj ga);\n      [rewrite (inj_prj _ _ H0); destruct i; congruence | discriminate].\n    intros; rewrite prj_inj; reflexivity.\n  Defined.\n\n  Instance Sub_Functor_inr' (F G H : Set -> Set) (sub_F_G : (F :+: G) :<: H) :\n    G :<: H :=\n    {| inj := fun (A : Set) (e : G A) => (@inj _ _ sub_F_G A (inr _ e));\n       prj := fun (A : Set) (H0 : H A) =>\n                match @prj _ _ sub_F_G A H0 with\n                  | Some (inl f) => None\n                  | Some (inr g) => Some g\n                  | None => None\n                end\n    |}.\n  Proof.\n    intros until fa; caseEq (prj ga);\n      [rewrite (inj_prj _ _ H0); destruct i; congruence | discriminate].\n    intros; rewrite prj_inj; reflexivity.\n  Defined.\n\n  Global Instance WF_Ind_Plus_split {F G H}\n    {Fun_F : Functor F}\n    {Fun_G : Functor G}\n    {Fun_H : Functor H}\n    {sub_F_G_H : (F :+: G) :<: H}\n    {Name : Set}\n    {P : Fix H -> Prop}\n    {F_Alg: PAlgebra Name (sig P) F}\n    {G_Alg: PAlgebra Name (sig P) G}\n    (WF_falg : @WF_Ind H F Name Fun_H Fun_F _ (Sub_Functor_inl' _ _ _ sub_F_G_H)\n      F_Alg)\n    (WF_falg : @WF_Ind H G Name Fun_H Fun_G _ (Sub_Functor_inr' _ _ _ sub_F_G_H)\n      G_Alg)\n    :\n    @WF_Ind H (F :+: G) _ _ _ P _ (PAlgebra_Plus Name _ F G) | 0.\n  Proof.\n    econstructor; intros.\n    destruct e; simpl.\n    rewrite (proj_eq (sub_F_E := Sub_Functor_inl' _ _ _ sub_F_G_H)); simpl;\n    reflexivity.\n    rewrite (proj_eq (sub_F_E := Sub_Functor_inr' _ _ _ sub_F_G_H)); simpl;\n    reflexivity.\n  Defined.\n\n  (* The key reasoning lemma. *)\n  Lemma Ind {F : Set -> Set}\n    {Fun_F : Functor F}\n    {P : Fix F -> Prop}\n    {N : Set}\n    {Ind_Alg : PAlgebra N (sig P) F}\n    {WF_Ind_Alg : WF_Ind Ind_Alg}\n    :\n    forall (f : Fix F)\n      (fUP' : Universal_Property'_fold f),\n      P f.\n  Proof.\n    intros.\n    cut (proj1_sig (fold_ _(@p_algebra _ _ _ Ind_Alg) f) = id f).\n    unfold id.\n    intro f_eq; rewrite <- f_eq.\n    eapply (proj2_sig (fold_ _ (@p_algebra _ _ _ Ind_Alg) f)).\n    erewrite (@Fusion _ Fun_F f fUP' _ _ (@proj1_sig (Fix F) P)\n                      (@p_algebra _ _ _ Ind_Alg) in_t).\n    eapply Fix_id_fold; unfold id; assumption.\n    intros; rewrite (proj_eq (WF_Ind := WF_Ind_Alg)).\n    simpl; unfold id; reflexivity.\n  Defined.\n\n  Class WF_Ind2 {E E' F: Set -> Set} {Name : Set}\n    {Fun_E : Functor E} {Fun_E : Functor E'} {Fun_F : Functor F}\n    {P : (Fix E) * (Fix E') -> Prop} {sub_F_E : F :<: E} {sub_F_E' : F :<: E'}\n    (F_Alg : PAlgebra Name (sig P) F) :=\n    { proj1_eq :\n        forall e,\n          fst (proj1_sig (p_algebra (PAlgebra := F_Alg) e)) =\n          in_t (inj (Sub_Functor := sub_F_E) (fmap (fun e => fst (proj1_sig e)) e));\n      proj2_eq :\n        forall e,\n          snd (proj1_sig (p_algebra (PAlgebra := F_Alg) e)) =\n          in_t (inj (Sub_Functor := sub_F_E') (fmap (fun e => snd (proj1_sig e)) e))\n    }.\n\n  Global Instance WF_Ind2_Plus_split {F G H H'}\n    {Fun_F : Functor F}\n    {Fun_G : Functor G}\n    {Fun_H : Functor H}\n    {Fun_H' : Functor H'}\n    {sub_F_G_H : (F :+: G) :<: H}\n    {sub_F_G_H' : (F :+: G) :<: H'}\n    {Name : Set}\n    {P : (Fix H) * (Fix H') -> Prop}\n    {F_Alg: PAlgebra Name (sig P) F}\n    {G_Alg: PAlgebra Name (sig P) G}\n    (WF_falg : @WF_Ind2 H H' F Name Fun_H Fun_H' Fun_F _\n      (Sub_Functor_inl' _ _ _ sub_F_G_H) (Sub_Functor_inl' _ _ _ sub_F_G_H')\n      F_Alg)\n    (WF_falg : @WF_Ind2 H H' G Name Fun_H Fun_H' Fun_G _\n      (Sub_Functor_inr' _ _ _ sub_F_G_H) (Sub_Functor_inr' _ _ _ sub_F_G_H')\n      G_Alg)\n    :\n    @WF_Ind2 H H' (F :+: G) _ _ _ _ P _ _ (PAlgebra_Plus Name _ F G) | 0.\n  Proof.\n    econstructor; intros; destruct e; simpl.\n    rewrite (proj1_eq (sub_F_E := Sub_Functor_inl' _ _ _ sub_F_G_H)\n                      (sub_F_E' := Sub_Functor_inl' _ _ _ sub_F_G_H')); simpl;\n    reflexivity.\n    rewrite (proj1_eq (sub_F_E := Sub_Functor_inr' _ _ _ sub_F_G_H)\n                      (sub_F_E' := Sub_Functor_inr' _ _ _ sub_F_G_H')); simpl;\n    reflexivity.\n    rewrite (proj2_eq (sub_F_E := Sub_Functor_inl' _ _ _ sub_F_G_H)\n                      (sub_F_E' := Sub_Functor_inl' _ _ _ sub_F_G_H')); simpl;\n    reflexivity.\n    rewrite (proj2_eq (sub_F_E := Sub_Functor_inr' _ _ _ sub_F_G_H)\n                      (sub_F_E' := Sub_Functor_inr' _ _ _ sub_F_G_H')); simpl;\n    reflexivity.\n  Defined.\n\n  Lemma Ind2 {F : Set -> Set}\n    {Fun_F : Functor F}\n    {P : (Fix F) * (Fix F) -> Prop}\n    {N : Set}\n    {Ind_Alg : PAlgebra N (sig P) F}\n    {WF_Ind_Alg : WF_Ind2 Ind_Alg}\n    :\n    forall (f : Fix F)\n      (fUP' : Universal_Property'_fold f),\n      P (f, f).\n  Proof.\n    intros.\n    cut (fst (proj1_sig (fold_ _(@p_algebra _ _ _ Ind_Alg) f)) = f).\n    cut (snd (proj1_sig (fold_ _(@p_algebra _ _ _ Ind_Alg) f)) = f).\n    intros f2_eq f1_eq; rewrite <- f1_eq at 1; rewrite <- f2_eq at -1.\n    generalize (proj2_sig (fold_ _ (@p_algebra _ _ _ Ind_Alg) f)).\n    destruct (proj1_sig (fold_ (sig P) p_algebra f)); simpl; auto.\n    erewrite (@Fusion _ Fun_F f fUP' _ _ (fun e => snd (proj1_sig e))\n      (@p_algebra _ _ _ Ind_Alg) in_t).\n    eapply Fix_id_fold; unfold id; assumption.\n    intros; rewrite (proj2_eq (WF_Ind2 := WF_Ind_Alg)).\n    simpl; unfold id; reflexivity.\n    erewrite (@Fusion _ Fun_F f fUP' _ _ (fun e => fst (proj1_sig e))\n      (@p_algebra _ _ _ Ind_Alg) in_t).\n    eapply Fix_id_fold; unfold id; assumption.\n    intros; rewrite (proj1_eq (WF_Ind2 := WF_Ind_Alg)).\n    simpl; unfold id; reflexivity.\n  Defined.\n\n  Class iPAlgebra (Name : Set) {I : Set} (A : I -> Prop) (F: (I -> Prop) -> I -> Prop) : Prop :=\n    { ip_algebra : iAlgebra F A}.\n\n  (* Definition iPAlgebra_Plus (Name: Set) {I : Set} (A : I -> Prop)\n    (F G : (I -> Prop) -> I -> Prop)\n    {falg: iPAlgebra Name A F} {galg: iPAlgebra Name A G} :\n    iPAlgebra Name A (F ::+:: G) :=\n      Build_iPAlgebra Name _ A _\n      (fun f fga =>\n        (match fga with\n           | or_introl fa => ip_algebra f fa\n           | or_intror ga => ip_algebra f ga\n         end)). *)\n\n  Global Instance iPAlgebra_Plus (Name: Set) {I : Set} (A : I -> Prop)\n    (F G : (I -> Prop) -> I -> Prop)\n    {falg: iPAlgebra Name A F} {galg: iPAlgebra Name A G} :\n    iPAlgebra Name A (F ::+:: G) | 6 :=\n    {| ip_algebra := fun f fga =>\n                       match fga with\n                         | or_introl fa => ip_algebra f fa\n                         | or_intror ga => ip_algebra f ga\n                       end\n    |}.\n\n  Class iWF_Ind {I : Set} {E F: (I -> Prop) -> I -> Prop} {Name : Set}\n    {Fun_E : iFunctor E} {Fun_F : iFunctor F}\n    {P : forall i, iFix E i -> Prop} {sub_F_E : Sub_iFunctor F E}\n    (F_Alg : iPAlgebra Name (fun i => sig (P i)) F) :=\n    { iproj_eq :\n        forall i e,\n          proj1_sig (ip_algebra (iPAlgebra := F_Alg) i e) =\n          in_ti i (inj_i (Sub_iFunctor := sub_F_E) i\n                         (ifmap i (fun i => proj1_sig (P := P i)) e))\n    }.\n\n  Definition Sub_iFunctor_inl' {I' : Set} (F G H : (I' -> Prop) -> I' -> Prop)\n    (isub_F_G : Sub_iFunctor (F ::+:: G) H) :\n    Sub_iFunctor F H :=\n    {| inj_i := fun (A : I' -> Prop) (i : I') (fai : F A i) =>\n                  @inj_i _ _ _ isub_F_G _ _ (or_introl (G A i) fai);\n       prj_i := fun (A : I' -> Prop) (i : I') (hai : H A i) =>\n                  let o := prj_i i hai in\n                  match o with\n                    | or_introl (or_introl H2) => or_introl True H2\n                    | or_introl (or_intror _) => or_intror (F A i) I\n                    | or_intror H1 => or_intror (F A i) H1\n                  end\n    |}.\n\n  Definition Sub_iFunctor_inr' {I' : Set} (F G H : (I' -> Prop) -> I' -> Prop)\n    (isub_F_G : Sub_iFunctor (F ::+:: G) H) :\n    Sub_iFunctor G H :=\n    {| inj_i := fun (A : I' -> Prop) (i : I') (gai : G A i) =>\n                  @inj_i _ _ _ isub_F_G _ _ (or_intror _ gai);\n       prj_i := fun (A : I' -> Prop) (i : I') (hai : H A i) =>\n                  let o := prj_i i hai in\n                  match o with\n                    | or_introl (or_intror H2) => or_introl True H2\n                    | or_introl (or_introl _) => or_intror _ I\n                    | or_intror H1 => or_intror _ H1\n                  end\n    |}.\n\n  Global Instance iWF_Ind_Plus_split {I : Set}\n    {F G H : (I -> Prop) -> I -> Prop}\n    {Fun_F : iFunctor F}\n    {Fun_G : iFunctor G}\n    {Fun_H : iFunctor H}\n    {sub_F_G_H : Sub_iFunctor (F ::+:: G) H}\n    {Name : Set}\n    {P : forall i, iFix H i -> Prop}\n    {F_Alg: iPAlgebra Name (fun i => sig (P i)) F}\n    {G_Alg: iPAlgebra Name (fun i => sig (P i)) G}\n    {WF_falg : @iWF_Ind _ H F Name Fun_H Fun_F _ (Sub_iFunctor_inl' _ _ _ sub_F_G_H)\n      F_Alg}\n    {WF_falg : @iWF_Ind _ H G Name Fun_H Fun_G _ (Sub_iFunctor_inr' _ _ _ sub_F_G_H)\n      G_Alg}\n    :\n    @iWF_Ind _ H (F ::+:: G) _ _ _ P _ (iPAlgebra_Plus Name _ F G) | 0.\n  Proof.\n    econstructor; intros.\n    destruct e; simpl.\n    rewrite (iproj_eq (sub_F_E := @Sub_iFunctor_inl' _ _ _ _ sub_F_G_H)); simpl;\n    reflexivity.\n    rewrite (iproj_eq (sub_F_E := @Sub_iFunctor_inr' _ _ _ _ sub_F_G_H)); simpl;\n    reflexivity.\n  Defined.\n\nEnd WF_Ind_FAlgebras.\n\n(* ============================================== *)\n(* ADDTIONAL MENDLER ALGEBRA INFRASTRUCTURE       *)\n(* ============================================== *)\n\nSection WF_MAlgebras.\n\n  Class WF_MAlgebra {Name : Set} {F : Set -> Set} {A : Set}\n    {Fun_F : Functor F}(MAlg : forall R, FAlgebra Name R A F) :=\n    { wf_malgebra :\n        forall (T T' : Set) (f : T' -> T) (rec : T -> A) (ft : F T'),\n          f_algebra (FAlgebra := MAlg T) rec (fmap f ft) =\n          f_algebra (FAlgebra := MAlg T') (fun ft' => rec (f ft')) ft\n    }.\n\n  Global Instance WF_MAlgebra_Plus {Name : Set} {F G : Set -> Set} {A : Set}\n    {Fun_F : Functor F}\n    {Fun_G : Functor G}\n    (MAlg_F : forall R, FAlgebra Name R A F)\n    (MAlg_G : forall R, FAlgebra Name R A G)\n    {WF_MAlg_F : WF_MAlgebra MAlg_F}\n    {WF_MAlg_G : WF_MAlgebra MAlg_G}\n    :\n    @WF_MAlgebra Name (F :+: G) A _ (fun R => FAlgebra_Plus Name R A F G).\n  Proof.\n    constructor; intros.\n    destruct ft; simpl; apply wf_malgebra.\n  Qed.\n\nEnd WF_MAlgebras.\n\nDefinition Smarked (S: Set) : Set := S.\n\nLtac Smark H :=\n  let t := type of H in\n  let n:= fresh in\n    (assert (n:Smarked t); [exact H | clear H; rename n into H]).\n\nLtac unSmark H := unfold Smarked in H.\n\nLtac unSmark_all := unfold Smarked in *|-.\n\nLtac WF_Falg_rewrite' :=\n  match goal with\n    | H : WF_FAlgebra _ _ _ _ _ _ _ |- _ =>\n      try rewrite (wf_algebra (WF_FAlgebra := H)); Smark H; WF_Falg_rewrite'\n    | _ => simpl\n  end;\n  unSmark_all.\n\nLtac WF_Falg_rewrite := unfold inject, in_t; WF_Falg_rewrite'.\n\nLtac fold_ind := eapply Ind.\n\nHint Extern 0 (FAlgebra _ _ _ (_ :+: _)) =>\n  apply FAlgebra_Plus; eauto with typeclass_instances : typeclass_instances.\n\nHint Extern 0 (forall _, FAlgebra _ _ _ _) =>\n  intros; eauto with typeclass_instances : typeclass_instances.\n\nHint Extern 0 (forall _, PAlgebra _ _ _) =>\n  intros; eauto with typeclass_instances : typeclass_instances.\n\nHint Extern 0 (PAlgebra _ _ (_ :+: _)) =>\n  apply PAlgebra_Plus; eauto with typeclass_instances : typeclass_instances.\n\nHint Extern 0 (iPAlgebra _ _ (_ :+: _)) =>\n  apply iPAlgebra_Plus; eauto with typeclass_instances : typeclass_instances.\n\nHint Extern 0 (WF_Ind _) =>\n  let e := fresh in\n    constructor; intro e; destruct e; reflexivity : typeclass_instances.\n\nHint Extern 0 (WF_Ind2 _) =>\n  let e := fresh in\n    constructor; intro e; destruct e; reflexivity : typeclass_instances.\n\nHint Extern 0 (WF_MAlgebra _) =>\n  let T := fresh in\n    let T' := fresh in\n      let f' := fresh in\n        let rec' := fresh in\n          let ft := fresh in\n            constructor; intros T T' f' rec' ft; destruct ft;\n              simpl; auto; fail : typeclass_instances.\n\nLtac discriminate_inject H :=\n  first [ apply inj_prj in H | idtac ];\n    contradict H;\n      solve [ apply inject_discriminate; auto with typeclass_instances\n            | apply not_eq_sym; apply inject_discriminate; auto with typeclass_instances\n            | apply inj_discriminate; auto with typeclass_instances\n            | apply not_eq_sym; apply inj_discriminate; auto with typeclass_instances\n            ].\n\n(*\n*** Local Variables: ***\n*** coq-prog-args: (\"-emacs-U\" \"-impredicative-set\") ***\n*** End: ***\n*)\n", "meta": {"author": "skeuchel", "repo": "mtc", "sha": "cf3c295664ce019fa370fc2dc73bd05eae94f64b", "save_path": "github-repos/coq/skeuchel-mtc", "path": "github-repos/coq/skeuchel-mtc/mtc-cf3c295664ce019fa370fc2dc73bd05eae94f64b/Functors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6536671365810942}}
{"text": "Require Export ZArith  List  Arith Bool.\n\nSection Minimal_propositional_logic.\n  Variables P Q R T : Prop.\n\n(* Exercise 3.2 *)\n\nLemma idP : P -> P.\nProof.\n  intro p; assumption.\nQed.\n\nLemma idPP : (P -> P) -> (P -> P).\nProof.\n  intros _ p; assumption.\nQed.\n\nLemma imp_trans: (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n  intros Hpq Hqr p; apply Hqr; apply Hpq; assumption.\nQed.\n\nLemma imp_perm : (P -> Q -> R) -> (Q -> P -> R).\nProof.\n  intros Hpqr q p; apply Hpqr; assumption.\nQed.\n\nLemma ignore_Q : (P -> R) -> P -> Q -> R.\nProof.\n  intros Hpr p q; apply Hpr; assumption.\nQed.\n\nLemma delta_imp : (P -> P -> Q) -> P -> Q.\nProof.\n  intros Hpr p; apply Hpr;  assumption.\nQed.\n\nLemma delta_impR : (P -> Q) -> (P -> P -> Q).\nProof.\n  intros Hpq p _; apply Hpq; assumption.\nQed.\n\nLemma diamond : (P -> Q) -> (P -> R) -> (Q -> R -> T) -> P -> T.\nProof.\n  intros Hpq Hpr Hqrt p; apply Hqrt; [apply Hpq | apply Hpr]; assumption.\nQed.\n\nLemma weak_peirce : ((((P -> Q) -> P) -> P) -> Q) -> Q.\nProof.\n  intros H0; apply H0.\n  intros H1; apply H1.\n  intros p ; apply H0.\n  intros H2. assumption.\nQed.\n\n(* Exercise 3.4 -- needs paper *)\n\n(* Exercise 3.5 *)\n\nSection section_for_cut_example.\n  Hypotheses (H: P -> Q)\n             (H0: Q -> R)\n             (H1: (P -> R) -> T -> Q)\n             (H2: (P -> R) -> T).\n\n  Theorem cut_example : Q.\n  Proof.\n    cut (P -> R).\n    intro H3.\n    apply H1; [assumption | apply H2; assumption].\n    intro p ; apply H0; apply H; assumption.\n  Qed.\n\n  Theorem cut_example' : Q.\n  Proof.\n    apply H1; [intro p; apply H0; apply H; assumption | idtac].\n    apply H2; intro p; apply H0; apply H; assumption.\n  Qed.\n\n  Print cut_example.\n  Print cut_example'.\n\n(*\ncut_example = \nlet H3 : P -> R := fun p : P => H0 (H p) in (fun H4 : P -> R => H1 H4 (H2 H4)) H3\n     : Q\n\ncut_example' = H1 (fun p : P => H0 (H p)) (H2 (fun p : P => H0 (H p)))\n     : Q\n*)\n\nEnd section_for_cut_example.\n\n\nEnd Minimal_propositional_logic.\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch3_propositions_proofs/hw3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6536671183348064}}
{"text": "(*\n  Copyright 2022 ZhengPu Shi\n  This file is part of CoqMatrix. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : Vector Theory implemented with SafeNatFun (no Module)\n  author    : ZhengPu Shi\n  date      : 2021.12\n  \n  remark    :\n  1. This is safe version of NatFun, which corrected the shape problem\n *)\n\n\nRequire Export SafeNatFun.Matrix.\n\n\nGeneralizable Variable A B C Aeq Beq Ceq Aadd Aopp Amul Ainv.\n\n(** Control the scope *)\nOpen Scope nat_scope.\nOpen Scope A_scope.\nOpen Scope mat_scope.\nOpen Scope vec_scope.\n\n(* ######################################################################### *)\n(** * Basic vector theory *)\n\nSection basic_vectory_theory.\n  \n  Context `{Equiv_Aeq : Equivalence A Aeq} {A0:A}.\n  Infix \"==\" := (Aeq) : A_scope.\n  Infix \"==\" := (eqlistA Aeq) : list_scope.\n\n  (** Vector type *)\n  Definition vec n := @mat A n 1.\n\n  (** make a vector by a function *)\n  Definition mk_vec {n : nat} (f : nat -> A) : vec n :=\n    mk_mat (fun i j => if j =? 0 then f i else A0).\n\n  (** matrix equality *)\n  Definition veq {n} (v1 v2 : vec n) := meq (Aeq:=Aeq) v1 v2.\n  Infix \"==\" := veq : vec_scope.\n\n  Notation \"m ! i ! j \" := (mnth (A0:=A0) m i j) : mat_scope.\n\n  (** veq is equivalence relation *)\n  Lemma veq_equiv : forall n, Equivalence (veq (n:=n)).\n  Proof.\n    intros. unfold veq. unfold meq.\n    apply meq_equiv.\n  Qed.\n\n  (** Get element of vector (unsafe) *)\n  Notation \"v $ i \" := (matf v i 0) : vec_scope.\n  \n  (** Get element of vector (safe) *)\n  Definition vnth {n} (v : vec n) i : A := v!i!0.\n  Notation \"v ! i \" := (vnth v i) : vec_scope.\n\n  Lemma vnth_eq_vnth_raw : forall {n : nat} (v : vec n),\n      (forall i, i < n -> v!i == v$i)%A.\n  Proof.\n    intros. unfold vnth. apply mnth_eq_mnth_raw; auto.\n  Qed.\n\n  (** veq and mnth should satisfy this constraint *)\n  Lemma veq_iff_vnth : forall {n : nat} (v1 v2 : vec n),\n      (v1 == v2) <-> (forall i, i < n -> (v1!i == v2!i)%A).\n  Proof.\n    unfold veq, vec, vnth.\n    intros;  split; intros.\n    - rewrite (meq_iff_mnth (A0:=A0)) in H. apply H; auto.\n    - apply (meq_iff_mnth (A0:=A0)). intros.\n      assert (j = 0) by lia. rewrite H2. apply H. auto.\n  Qed.\n\n  (* ==================================== *)\n  (** ** List like operations for vector *)\n\n  (** vcons *)\n  Definition vcons {n} (a : A) (v : vec n) : vec (S n) :=\n    mk_vec (fun i => match i with 0 => a | S i' => v $ i' end).\n\n  Lemma vcons_spec : forall n a (v : vec n) i,\n      ((vcons a v) $ 0 == a)%A /\\ (i < n -> v $ i == (vcons a v) $ (S i))%A.\n  Proof.\n    intros. unfold vcons. split.\n    - intros. solve_mnth.\n    - solve_mnth.\n  Qed.\n    \n\n  (** Get a vector from a given vector by remove one element *)\n  Definition vremove {n : nat} (v : vec (S n)) (k : nat) : vec n :=\n    mk_vec (fun i => if i <? k then v ! i else v ! (S i)).\n\n\n  (* ==================================== *)\n  (** ** Convert between list and vector *)\n  (* Definition v2l {n} (v : vec n) : list A := @Matrix.mcol _ n 1 0 v. *)\n  (* Definition l2v {n} (l : list A) : vec n := l2m (A0:=A0) (row2col l). *)\n\n  Definition v2l {n} (v : vec n) : list A := map (fun i : nat => v $ i) (seq 0 n).\n\n  Definition l2v n (l : list A) : vec n :=\n    mk_mat (fun i j => if (i <? n) && (j =? 0) then nth i l A0 else A0).\n\n  (** list of vector to dlist *)\n  Definition vl2dl {n} (l : list (vec n)) : list (list A) :=\n    map v2l l.\n    \n\n  Lemma v2l_length : forall {n} (v : vec n), length (v2l v) = n.\n  Proof.\n    intros. unfold v2l. rewrite map_length, seq_length; auto.\n  Qed.\n\n  Lemma v2l_l2v_id : forall {n} (l : list A),\n      length l = n -> (@v2l n (@l2v n l) == l)%list.\n  Proof.\n    intros. unfold l2v,v2l. simpl.\n    rewrite (list_eq_iff_nth A0 n); auto.\n    - intros. rewrite ?nth_map_seq; auto.\n      rewrite ?Nat.add_0_r. apply Nat.ltb_lt in H0. rewrite H0; simpl. easy.\n    - rewrite map_length, seq_length; auto.\n  Qed.\n\n  Lemma l2v_v2l_id : forall {n} (v : vec n), l2v n (v2l v) == v.\n  Proof.\n    intros. destruct v as [v].\n    unfold l2v,v2l. simpl. lma.\n    rewrite ?nth_map_seq; auto.\n    rewrite Nat.add_0_r. easy.\n  Qed. \n\n  (* ==================================== *)\n  (** ** Make concrete vector *)\n  Definition mk_vec2 (a0 a1 : A) : vec 2 := l2v 2 [a0;a1].\n  Definition mk_vec3 (a0 a1 a2 : A) : vec 3 := l2v 3 [a0;a1;a2].\n  Definition mk_vec4 (a0 a1 a2 a3 : A) : vec 4 := l2v 4 [a0;a1;a2;a3].\n\n  (* ==================================== *)\n  (** ** Convert between tuples and vector *)\n  Definition t2v_2 (t : @T2 A) : vec 2 :=\n    let '(a,b) := t in l2v 2 [a;b].\n  Definition t2v_3 (t : @T3 A) : vec 3 :=\n    let '(a,b,c) := t in l2v 3 [a;b;c].\n  Definition t2v_4 (t : @T4 A) : vec 4 :=\n    let '(a,b,c,d) := t in l2v 4 [a;b;c;d].\n\n  Definition v2t_2 (v : vec 2) : @T2 A := (v$0, v$1).\n  Definition v2t_3 (v : vec 3) : @T3 A := (v$0, v$1, v$2).\n  Definition v2t_4 (v : vec 4) : @T4 A := (v$0, v$1, v$2, v$3).\n\n  Lemma v2t_t2v_id_2 : forall (t : A * A), v2t_2 (t2v_2 t) = t.\n  Proof.\n    intros. destruct t. simpl. unfold v2t_2. f_equal.\n  Qed.\n\n  Lemma t2v_v2t_id_2 : forall (v : vec 2), t2v_2 (v2t_2 v) == v.\n  Proof.\n    intros. apply veq_iff_vnth. intros i Hi. simpl.\n    repeat (try destruct i; auto; try lia); easy.\n  Qed.\n\n  (** mapping of a vector *)\n  Definition vmap {n} (v : vec n) f : vec n := mmap f v.\n\n  (** folding of a vector *)\n  (*   Definition vfold : forall {B : Type} {n} (v : vec n) (f : A -> B) (b : B), B. *)\n\n  (** mapping of two matrices *)\n  Definition vmap2 {n} (v1 v2 : vec n) f : vec n := mmap2 f v1 v2.\n\n  (* ======================================================================= *)\n  (** ** Advanced matrix construction by mixing vectors and matrices *)\n  Section AdvancedConstrtuct.\n\n    (* Check A. *)\n    (* Check Equiv_Aeq. *)\n    (* Context `{Equiv_Aeq : Equivalence A Aeq} {A0 A1 : A}. *)\n    (* Infix \"==\" := (meq (Aeq:=Aeq)) : mat_scope. *)\n\n    (* (** Vector type *) *)\n    (* Definition vecr n := @mat A 1 n. *)\n    (* Definition vecc n := @mat A n 1. *)\n    \n    (** Construct a matrix with a vector and a matrix by row *)\n    Definition mconsr {r c} (v : vec c) (m : mat r c) : mat (S r) c :=\n      mk_mat (fun i j => match i with\n                         | O => v $ j\n                         | S i' => m $ i' $ j\n                         end).\n    \n    (** Construct a matrix with a vector and a matrix by column *)\n    Definition mconsc {r c} (v : vec r) (m : mat r c) : mat r (S c) :=\n      mk_mat (fun i j => match j with\n                         | O => v $ i\n                         | S j' => m $ i $ j'\n                         end).\n    \n    (* (** Equality of two forms of ConstructByRow *) *)\n    (* Lemma mconsr_eq {r c} (v : vecr c) (m : @mat A r c) : mconsr v m == (v, m). *)\n    (* Proof. unfold mconsr. auto. Qed. *)\n    \n    (* (** Construct a matrix by rows with the matrix which row number is 0 *) *)\n    (* Lemma mconsr_mr0 : forall {n} (v : @vec A n) (m : @mat A 0 n), *)\n    (*   mconsr v m = [v]. *)\n    (* Proof. intros. destruct m. unfold mconsr. auto. Qed. *)\n    \n    (* (** Construct a matrix by rows with the matrix which row column is 0 *) *)\n    (* Lemma mconsr_mc0 : forall {n} (v : @vec A 0) (m : @mat A n 0), *)\n    (*   mconsr v m = (tt, m). *)\n    (* Proof. intros. destruct v. unfold mconsr. auto. Qed. *)\n    \n    (* (** Construct a matrix by columns with the matrix which row number is 0 *) *)\n    (* Lemma mconsc_mr0 : forall {n} (v : @vec A 0) (m : @vec (@vec A n) 0), *)\n    (*   mconsc v m = tt. *)\n    (* Proof. intros. destruct m. unfold mconsc. auto. Qed.   *)\n\n  End AdvancedConstrtuct.\n\nEnd basic_vectory_theory.\nArguments l2v {A}.\nNotation \"v $ i \" := (matf v i 0) : vec_scope.\n\nSection test.\n  Notation \"v ! i \" := (vnth (A0:=0) v i) : vec_scope.\n  Definition v1 : vec 3 := l2v 0 3 [1;2;3].\n  Definition m1 : mat 3 3 := l2m (A0:=0) [[10;11;12];[13;14;15];[16;17;18]].\n  Goal v1!(v1!0) = 2. auto. Qed.\n  Goal m2l (mconsr v1 m1) = [[1;2;3];[10;11;12];[13;14;15];[16;17;18]]. auto. Qed.\n  Goal m2l (mconsc v1 m1) = [[1;10;11;12];[2;13;14;15];[3;16;17;18]]. auto. Qed.\nEnd test.\n\n\n(* ######################################################################### *)\n(** * Ring vector theory implemented with SafeNatFun *)\n\nSection ring_vector_theory.\n\n  Context `{AG : AGroup}.\n  Infix \"+\" := Aadd : A_scope.\n  Infix \"+\" := (ladd (Aadd:=Aadd)) : list_scope.\n  Notation \"- a\" := (Aopp a) : A_scope.\n  Infix \"-\" := (fun a b => a + (-b)) : A_scope.\n  Infix \"==\" := Aeq : A_scope.\n  Infix \"==\" := (eqlistA Aeq) : list_scope.\n  Infix \"==\" := (meq (Aeq:=Aeq)) : mat_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vec_scope.\n\n  (** ** Zero vector *)\n  Definition vec0 {n} : vec n := mat0 A0 n 1.\n\n  (** Assert that a vector is an zero vector. *)\n  Definition vzero {n} (v : vec n) : Prop := v == vec0.\n\n  (** Assert that a vector is an non-zero vector. *)\n  Definition vnonzero {n} (v : vec n) : Prop := ~(vzero v).\n  \n  (** vec0 is equal to mat0 with column 1 *)\n  Lemma vec0_eq_mat0 : forall n, vec0 == mat0 A0 n 1.\n  Proof.\n    intros. easy.\n  Qed.\n  \n  \n  (** *** Vector addition *)\n\n  Definition vadd {n} (v1 v2 : vec n) : vec n := madd (Aadd:=Aadd) v1 v2.\n  Infix \"+\" := vadd : vec_scope.\n\n  (** v1 + v2 = v2 + v1 *)\n  Lemma vadd_comm : forall {n} (v1 v2 : vec n), (v1 + v2) == (v2 + v1).\n  Proof.\n    intros. apply madd_comm.\n  Qed.\n\n  (** (v1 + v2) + v3 = v1 + (v2 + v3) *)\n  Lemma vadd_assoc : forall {n} (v1 v2 v3 : vec n), (v1 + v2) + v3 == v1 + (v2 + v3).\n  Proof.\n    intros. apply madd_assoc.\n  Qed.\n\n  (** vec0 + v = v *)\n  Lemma vadd_0_l : forall {n} (v : vec n), vec0 + v == v.\n  Proof.\n    intros. apply madd_0_l.\n  Qed.\n\n  (** v + vec0 = v *)\n  Lemma vadd_0_r : forall {n} (v : vec n), v + vec0 == v.\n  Proof.\n    intros. apply madd_0_r.\n  Qed.\n\n  \n  (** *** Vector opposite *)\n  \n  Definition vopp {n} (v : vec n) : vec n := mopp (Aopp:=Aopp) v.\n  Notation \"- v\" := (vopp v) : vec_scope.\n\n  (** v + (- v) = vec0 *)\n  Lemma vadd_opp : forall {n} (v : vec n), v + (- v) == vec0.\n  Proof.\n    intros. apply madd_opp.\n  Qed.\n  \n\n  (** *** Vector subtraction *)\n\n  Definition vsub {n} (v1 v2 : vec n) : vec n := v1 + (- v2).\n  Infix \"-\" := vsub : vec_scope.\n\n\n  (** *** Below, we need a ring structure *)\n  Context `{R : Ring A Aadd A0 Aopp Amul A1 Aeq}.\n  Infix \"*\" := Amul : A_scope.\n  \n  Add Ring ring_inst : make_ring_theory.\n\n  (** *** Vector scalar multiplication *)\n\n  Definition vcmul {n} a (v : vec n) : vec n := mcmul (Amul:=Amul) a v.\n  Definition vmulc {n} (v : vec n) a : vec n := mmulc (Amul:=Amul) v a.\n  Infix \"c*\" := vcmul : vec_scope.\n  Infix \"*c\" := vmulc : vec_scope.\n\n  (** v *c a = a c* v *)\n  Lemma vmulc_eq_vcmul : forall {n} a (v : vec n), (v *c a) == (a c* v).\n  Proof.\n    intros. apply mmulc_eq_mcmul.\n  Qed.\n\n  (** a c* (b c* v) = (a * b) c* v *)\n  Lemma vcmul_assoc : forall {n} a b (v : vec n), a c* (b c* v) == (a * b)%A c* v.\n  Proof.\n    intros. apply mcmul_assoc.\n  Qed.\n\n  (** a c* (b c* v) = b c* (a c* v) *)\n  Lemma vcmul_perm : forall {n} a b (v : vec n), a c* (b c* v) == b c* (a c* v).\n  Proof.\n    intros. apply mcmul_perm.\n  Qed.\n\n  (** (a + b) c* v = (a c* v) + (b c* v) *)\n  Lemma vcmul_add_distr_l : forall {n} a b (v : vec n),\n      (a + b)%A c* v == (a c* v) + (b c* v).\n  Proof.\n    intros. apply mcmul_add_distr_r.\n  Qed.\n\n  (** a c* (v1 + v2) = (a c* v1) + (a c* v2) *)\n  Lemma vcmul_add_distr_r : forall {n} a (v1 v2 : vec n), \n      a c* (v1 + v2) == (a c* v1) + (a c* v2).\n  Proof.\n    intros. apply mcmul_add_distr_l.\n  Qed.\n\n  (** 1 c* v = v *)\n  Lemma vcmul_1_l : forall {n} (v : vec n), A1 c* v == v.\n  Proof.\n    intros. apply mcmul_1_l.\n  Qed.\n\n  (** 0 c* v = vec0 *)\n  Lemma vcmul_0_l : forall {n} (v : vec n), A0 c* v == vec0.\n  Proof.\n    intros. apply mcmul_0_l.\n  Qed.\n\n  \n  (** *** Vector dot product *)\n  \n  (** dot production of two vectors. *)\n  Definition vdot {n : nat} (v1 v2 : vec n) : A :=\n    fold_left Aadd (map (fun i => v1$i * v2$i) (seq 0 n)) A0.\n  \n  Infix \"⋅\" := vdot : vec_scope.\n\n  (** vdot is a proper morphism respect to Aeq *)\n  Lemma vdot_aeq_mor {n} :\n    Proper (veq (Aeq:=Aeq) ==> veq (Aeq:=Aeq) ==> Aeq) (@vdot n).\n  Proof.\n    repeat (hnf; intros).\n    apply fold_left_aeq_mor; try easy.\n    rewrite (veq_iff_vnth (A0:=A0)) in H,H0.\n    rewrite (list_eq_iff_nth A0 n); auto.\n    - intros. rewrite !nth_map_seq; auto.\n      rewrite Nat.add_0_r. rewrite <- ?(vnth_eq_vnth_raw (A0:=A0)); auto.\n      rewrite H,H0; auto. easy.\n    - rewrite map_length, seq_length; auto.\n    - rewrite map_length, seq_length; auto.\n  Qed.\n  Global Existing Instance vdot_aeq_mor.\n\n  (** dot production is commutative *)\n  Lemma vdot_comm : forall {n} (v1 v2 : vec n), (v1 ⋅ v2 == v2 ⋅ v1)%A.\n  Proof.\n    intros. unfold vdot.\n    apply fold_left_aeq_mor; try easy.\n    apply SetoidListExt.map_ext. intros. ring.\n  Qed.\n\n  (** 0 * v = 0 *)\n  Lemma vdot_0_l : forall {n} (v : vec n), (vec0 ⋅ v == A0)%A.\n  Proof.\n    intros.\n    unfold vdot. cbn.\n    destruct v as [v]; simpl.\n    assert (map (fun i => A0 * v i 0) (seq 0 n) == map (fun i => A0) (seq 0 n))%list.\n    { apply SetoidListExt.map_ext. intros. ring. }\n    rewrite H. clear H.\n    induction n; simpl; try easy.\n    rewrite <- seq_shift. rewrite map_map. monoid_rw. auto.\n  Qed.\n\n  (** v * 0 = 0 *)\n  Lemma vdot_0_r : forall {n} (v : vec n), (v ⋅ vec0 == A0)%A.\n  Proof. intros. rewrite vdot_comm, vdot_0_l. easy. Qed.\n\nEnd ring_vector_theory.\n\nSection test.\n  Import ZArith.\n  Open Scope Z_scope.\n  Open Scope vec_scope.\n  \n  Infix \"+\" := (vadd (Aadd:=Z.add)) : vec_scope.\n  Notation \"- v\" := (vopp (Aopp:=Z.opp) v) : vec_scope.\n  Infix \"-\" := (vsub (Aadd:=Z.add)(Aopp:=Z.opp)) : vec_scope.\n  Infix \"c*\" := (vcmul (Amul:=Z.mul)) : vec_scope.\n  Infix \"⋅\" := (vdot (A0:=0) (Aadd:=Z.add) (Amul:=Z.mul)) : vec_scope.\n\n  Let v1 := l2v 0 3 [1;2;3].\n  Let v2 := l2v 0 3 [4;5;6].\n  (* Compute v2l (-v1). *)\n  (* Compute v2l (v1 + v2). *)\n  (* Compute v2l (v2 - v1). *)\n  (* Compute v2l (3 c* v1). *)\n  (* Compute v1⋅v2. *)\n\nEnd test.\n\n\n\n(* ######################################################################### *)\n(** * Decidable-field vector theory implemented with SafeNatFun  *)\n\nSection decidable_vector_theory.\n\n  Context `{Dec_Aeq : @Decidable A Aeq} {A0:A}.\n  \n  Open Scope mat_scope.\n  Open Scope vec_scope.\n\n  (** veq is decidable *)\n  Lemma veq_dec : forall (n : nat), Decidable (@veq A Aeq n).\n  Proof. intros. apply meq_dec. Qed.\n\n  Global Existing Instance veq_dec.\n\n  (** It is decidable that if a vector is zero vector. *)\n  Lemma vzero_dec : forall {n} (v : vec n),\n      {vzero (A0:=A0)(Aeq:=Aeq) v} + {vnonzero (A0:=A0)(Aeq:=Aeq) v}.\n  Proof.\n    intros. apply veq_dec.\n  Qed.\n  \nEnd decidable_vector_theory.\n\n\n(** ** Others, later ... *)\n(* \n\n  Lemma vec_eq_vcmul_imply_coef_neq0 : forall {n} (v1 v2 : V n) k,\n    vnonzero v1 -> vnonzero v2 -> v1 = k c* v2 -> k <> X0.\n  Proof.\n    intros. intro. subst. rewrite vcmul_0_l in H. destruct H. easy.\n  Qed.\n  \n  (* ==================================== *)\n  (** ** 2-dim vector operations *)\n\n  Definition vlen2 (v : V 2) : X :=\n    let '(x,y) := v2t_2 v in\n      (x * x + y * y)%X.\n  \n  (* ==================================== *)\n  (** ** 3-dim vector operations *)\n\n  Definition vlen3 (v : V 3) : X :=\n    let '(x,y,z) := v2t_3 v in\n      (x * x + y * y + z * z)%X.\n      \n  Definition vdot3 (v0 v1 : V 3) : X :=\n    let '(a0,b0,c0) := v2t_3 v0 in\n    let '(a1,b1,c1) := v2t_3 v1 in\n      (a0 * a1 + b0 * b1 + c0 * c1)%X.\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/SafeNatFun/Vector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6536671166440055}}
{"text": "From Coqprime Require Import PocklingtonRefl.\n\nLocal Open Scope positive_scope.\n\nLemma primo43 : prime 401928217.\nProof.\n apply (Pocklington_refl\n         (Pock_certif 401928217 5 ((1109, 1)::(2,3)::nil) 9814)\n        ((Proof_certif 1109 prime1109) ::\n         (Proof_certif 2 prime2) ::\n          nil)).\n native_cast_no_check (refl_equal true).\nQed.\n\n", "meta": {"author": "mukeshtiwari", "repo": "Formally_Verified_Verifiable_Group_Generator", "sha": "e80e8d43e81b5201d6ab82a8ebc07a5cef03476b", "save_path": "github-repos/coq/mukeshtiwari-Formally_Verified_Verifiable_Group_Generator", "path": "github-repos/coq/mukeshtiwari-Formally_Verified_Verifiable_Group_Generator/Formally_Verified_Verifiable_Group_Generator-e80e8d43e81b5201d6ab82a8ebc07a5cef03476b/primality/p2_43.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6536602238085084}}
{"text": "(** * Exploring equality via homotopy and proof assistants - Day 3 - Inductive types and their equalities *)\n(** This file contains the exercises for Day 3.  Some are explicitly marked as \"Homework\"; the rest can be done either in class or for homework.\n\n  If the Macs in the computer lab do not have CoqIDE installed, you can go to https://coq.inria.fr/coq-85, download CoqIDE_8.5beta2.dmg, open it, and run CoqIDE directly, without installing it.\n\n  When doing exercises on your own, feel free to skip around; there are some interesting puzzles near the bottom.\n\n  If you feel like you know exactly how a proof will go, but find it painful and tedious to write out the proof terms explicitly, come find me.  Coq has a lot of support for automation and taking care of things that are easy and verbose, so you don't have to. Proving should feel like a game.  If it doesn't, I can probably help you with that.  *)\n\n(** The following are placeholders; [admit] indicates that something should be filled in later. *)\n\nAxiom admit : forall {T}, T.\n\n(** Compatibility between Coq 8.5 and 8.4 *)\nSet Universe Polymorphism.\nSet Asymmetric Patterns.\n\n(* begin hide *)\n(** Some filled in exercises from yesterday; feel free to paste more here. *)\n\nNotation refl := eq_refl.\nDefinition sym : forall A (x y : A), x = y -> y = x := eq_sym.\n(** We allow writing [sym p] to mean [sym _ _ _ p] *)\nArguments sym {A x y} p, A x y p.\nDefinition trans : forall A (x y z : A), x = y -> y = z -> x = z\n  := eq_trans.\nArguments trans {A x y z} p q, A x y z p q.\nDefinition J : forall (A : Type) (x : A) (y : A)\n                      (H : x = y)\n                      (P : forall (y' : A) (H' : x = y'), Type),\n                 P x refl -> P y H\n  := fun A x y H P k => match H with\n                          | refl => k\n                        end.\nArguments J {A} {x} {y} H P _.\nDefinition ap : forall A B (f : A -> B) (x y : A), x = y -> f x = f y\n  := fun A B f x y p\n     => match p with\n          | refl => refl\n        end.\n\nArguments ap {A B} f {x y} p, {A B} f x y p, A B f x y p.\n\n(** A polymorphic definition of sigma types *)\nRecord sigT {A} P := existT { projT1 : A ; projT2 : P projT1 }.\nArguments projT1 {A P} _.\nArguments projT2 {A P} _.\nArguments existT {A} P _ _.\nNotation \"{ x : A  & P }\" := (sigT (A:=A) (fun x => P)) : type_scope.\n\n(* end hide *)\n\n(** ** Guiding Puzzles *)\n\n(** There are three guiding questions for today:\n\n 1. What are (inductive) types?\n 2. What does it mean to say that two inhabitants of a given type are equal?\n 3. Where is equality under-specified, and how can we extend the patterns we see to fill in these areas? *)\n\n(** *** Puzzle 1: contractibility of based path spaces *)\n\n(** We use the notation [{ x : T | P x }] to denote the type of pairs [(x; p)] which consist of an inhabitant [x : T] and a proof [p : P x]. *)\n\nNotation \"{ x  |  P }\" := ({ x : _ & P }) : type_scope.\nNotation \"{ x : A  |  P }\" := ({ x : A & P }) : type_scope.\nNotation \"( x ; p )\" := (existT _ x p).\nNotation \"x .1\" := (projT1 x) (at level 3, format \"x '.1'\").\nNotation \"x .2\" := (projT2 x) (at level 3, format \"x '.2'\").\n\n\n(** A type is called contractible if there is a (continuous!) function showing that all inhabitants are equal to a particular one. *)\n\nDefinition is_contractible : Type -> Type\n  := fun A => { center : A | forall y : A, center = y }.\n\n(** Puzzle: The following theorem is provable.  Prove it. *)\n\nDefinition contractible_pointed\n: forall (A : Type) (y : A),\n    is_contractible { x : A | x = y }.\nProof.\n  refine (fun A y => _).\n  refine ((y; refl); _).\n  refine (fun y' => _).\n  refine admit.\nDefined.\n\n(** Note that [x = y :> T] means [x : T], [y : T], and [x = y].  It is the notation for [@eq T x y].  It is how we write $x =_T y$ #<span class=\"inlinecode\">x =<sub>T</sub> y</span># in Coq. *)\n\n(** Since equals are inter-substitutable, we should be able to prove: *)\n\nDefinition contractible_to_UIP\n: forall (A : Type) (y : A)\n         (x : A)\n         (p p' : y = x),\n    ((x; p) = (x; p') :> { x : A | y = x })\n    -> p = p'\n  := admit.\n\n(** But it turns out that we can't prove this.  Why not?  Give both a formal, type theoretic reason (what terms don't typecheck?), and a topological reason. *)\n\n(** *** Puzzle 2: understanding the encode-decode method *)\n\n(** Here is a concrete puzzle for the second question:\n\n  To classify the equality of a given type, we give a \"code\" for each pair of elements.  We must say how to \"encode\" equality proofs, and how to \"decode\" codes into equality proofs.  We want this to be an isomorphism, i.e., [encode ∘ decode] and [decode ∘ encode] should both be the identity function.  It turns out that we don't need to know anything about [encode] or [decode] other than their existance to ensure this; we can always adjust [decode] to create an inverse to [encode], as long as a particular property holds of [code].  What is that property?\n\n  More concretely, the puzzle is to fill in the following holes. *)\n\nSection general_classification.\n\n  Definition code_correct_P\n  : forall {A : Type} (code : A -> A -> Type), Type\n    := admit.\n\n  (** We assume we are given a type, a [code], an [encode], and a [decode].  We introduce the assumptions as we get to definitions that should need them. *)\n\n  Context {A : Type} (code : A -> A -> Type)\n          (decode' : forall x y, code x y -> x = y).\n\n  Definition decode\n  : forall {x y}, code x y -> x = y\n    := admit.\n\n  Context (encode : forall x y, x = y -> code x y).\n\n  Definition deencode\n  : forall {x y} (p : x = y),\n      decode (encode _ _ p) = p\n    := admit.\n\n  (** For this last one, we'll need the correctness property on codes. *)\n\n  Context (code_correct : code_correct_P code).\n\n  Definition endecode\n  : forall {x y} (p : code x y),\n      encode _ _ (decode p) = p\n    := admit.\n\nEnd general_classification.\n\n(** The following sanity check on the classification should be provable: *)\n\nSection sanity_checks.\n\n  (** [x = y] should be a valid code *)\n\n  Definition eq_is_valid_code\n  : forall {A : Type},\n      code_correct_P (fun x y : A => x = y)\n    := admit.\n\n  (** If you didn't choose a silly correctness property like [code = (fun x y => x = y)], then your proof should generalize to the following: *)\n\n  (** Suppose we are given a valid encoding. *)\n\n  Context {A : Type} (code : A -> A -> Type)\n          (encode : forall x y, x = y -> code x y)\n          (decode : forall x y, code x y -> x = y)\n          (endecode : forall x y (p : code x y), encode _ _ (decode _ _ p) = p)\n          (deencode : forall x y (p : x = y), decode _ _ (encode _ _ p) = p).\n\n  (** Then it should satisfy your validity principle. *)\n\n  Definition valid_code_is_valid : code_correct_P code\n    := admit.\n\nEnd sanity_checks.\n\n(** *** Puzzle 3 *)\n\n(** Classify the equalities of types.  That is, fill in the following: *)\n\nDefinition Type_code\n: forall (x y : Type), Type\n  := admit.\n\nDefinition Type_encode\n: forall {x y : Type}, x = y -> Type_code x y\n  := admit.\n\n(** The following are unprovable in Coq, currently.  They are collectively known as the \"univalence axiom\". *)\n\nAxiom Type_decode\n: forall {x y : Type}, Type_code x y -> x = y.\nAxiom Type_endecode\n: forall {x y : Type} (p : Type_code x y),\n    Type_encode (Type_decode p) = p.\nAxiom Type_deencode\n: forall {x y : Type} (p : x = y),\n    Type_decode (Type_encode p) = p.\n\n(** This was all very abstract.  Let's drill down with some exmples. *)\n\n(** * Class Notes *)\n\n(** *** Provable equalities *)\n\n(** What equalities of types are provable? *)\n\n\nDefinition some_type_equality : unit = unit\n  := refl.\n\nInductive unit1 : Type := tt1.\nInductive unit2 : Type := tt2.\n\nFail Definition unit1_equals_unit2 : unit1 = unit2\n  := refl.\n\n(** Can you prove other ones? *)\n\n(** *** Provable inequalities *)\n\n(** What equalities of types are provably absurd? *)\n\nDefinition unit_ne_empty_set\n : unit = Empty_set -> Empty_set.\nProof.\n  refine (fun P => _).\n  refine (J P (fun x _ => x) _).\n  refine tt.\nDefined.\n\nDefinition true_ne_false\n: true = false -> Empty_set.\nProof.\n  refine (fun P => _).\n  refine (J P (fun f _ => if f then unit else Empty_set) _).\n  refine tt.\nDefined.\n\nDefinition unit_ne_bool\n : bool = unit -> Empty_set.\nProof.\n  refine (fun P => _).\n  refine (let alleq : forall x y : unit, x = y := _ in _).\n  { refine (fun x y => match x, y with\n                         | tt, tt => refl\n                       end). }\n  refine (J P (fun T _ => (forall x y : T, x = y) -> Empty_set) _ alleq).\n  refine (fun alleq_bool => _).\n  refine (true_ne_false (alleq_bool true false)).\nDefined.\n\n(** *** Isomorphisms *)\n\n(** We can define a notion of isomorphism: *)\n\nClass IsIsomorphism {A B} (f : A -> B)\n  := { iso_inv : B -> A;\n       right_inv : forall x : B, f (iso_inv x) = x;\n       left_inv : forall x : A, iso_inv (f x) = x }.\n\nArguments iso_inv {A B} f {_} _.\nArguments right_inv {A B f _ _}, {A B} f {_} _.\nArguments left_inv {A B f _ _}, {A B} f {_} _.\n\nRecord Isomorphic A B\n  := { iso_fun : A -> B;\n       iso_isiso : IsIsomorphism iso_fun }.\n\nArguments iso_fun {A B} _ _.\n\n(** Let us use an object of type [Isomorphic] as a function: *)\n\nCoercion iso_fun : Isomorphic >-> Funclass.\n\n(** Tell Coq that the function associated to an [Isomorphic] object is always an isomorphism. *)\n\nExisting Instance iso_isiso.\n\nNotation \"A <~=~> B\" := (Isomorphic A B) (at level 70).\nNotation \"A ≅ B\" := (Isomorphic A B) (at level 70).\n\n(** We can prove the standard properties about isomorphisms: *)\n\nDefinition Isomorphic_refl : forall {A}, A ≅ A\n  := fun A => {| iso_fun x := x;\n                 iso_isiso := {| iso_inv x := x;\n                                 right_inv x := refl : (fun x => x) x = x;\n                                 left_inv x := refl |} |}.\n\nDefinition Isomorphic_inverse : forall {A B}, A ≅ B -> B ≅ A\n  := fun A B e =>\n       {| iso_fun := iso_inv e;\n          iso_isiso := {| iso_inv := iso_fun e;\n                          right_inv := left_inv e;\n                          left_inv := right_inv e |} |}.\n\nDefinition Isomorphic_compose : forall {A B C}, A ≅ B -> B ≅ C -> A ≅ C.\nProof.\n  refine (fun A B C e1 e2 =>\n            {| iso_fun x := iso_fun e2 (iso_fun e1 x);\n               iso_isiso := {| iso_inv x := iso_inv e1 (iso_inv e2 x) |} |}).\n  { refine (fun x => trans (ap e2 (right_inv e1 (iso_inv e2 x)))\n                           (right_inv e2 x)). }\n  { refine (fun x => trans (ap (iso_inv e1) (left_inv e2 (e1 x)))\n                           (left_inv e1 x)). }\nDefined.\n\n\n(** We would like to prove the last corresponding law: *)\n\nDefinition Isomorphic_ap : forall (f : Type -> Type) {A B}, A ≅ B -> f A ≅ f B\n  := admit.\n\n(** But it's not provable!  Here's a counter-example: *)\n\n(** Recall the taboo from earlier; we can't prove equality of two identical types defined separately.  But if we could prove [Isomorphic_ap], then we could prove this! *)\n\nDefinition iso_unit2_unit1 : unit2 ≅ unit1.\nProof.\n  refine {| iso_fun := fun x => tt1;\n            iso_isiso := {| iso_inv := fun x => tt2 |} |}.\n  { refine (fun x => match x with tt1 => refl end). }\n  { refine (fun x => match x with tt2 => refl end). }\nDefined.\n\nDefinition taboo1 : unit1 = unit2 :> Type\n  := Isomorphic_ap (fun T => T = unit2) iso_unit2_unit1 refl.\n\n(** Ooops!  We'll be coming back to this soon. *)\n\n(** Before dealing with the taboo above, let's classify the equality space of isomorphisms. *)\n\n(** Two isomorphisms should be equal if the underlying functions are equal. *)\n\nDefinition iso_code : forall {A B} (x y : A ≅ B), Type\n  := fun A B x y => iso_fun x = iso_fun y.\n\nDefinition iso_encode : forall {A B} {x y : A ≅ B}, x = y -> iso_code x y\n  := fun A B x y H => match H with\n                       | refl => refl\n                      end.\n\nDefinition iso_decode : forall {A B} {x y : A ≅ B}, iso_code x y -> x = y\n  := admit.\n\n(** Ooops.  Turns out this isn't provable.  Challenge: Figure out why. *)\n\n(** *** Equivalences *)\n\n(** We can define a slight variation on isomorphisms, called \"contractible fibers\", which generalizes the notion of injective+surjective.  If you're interested in the various ways of formulating equivalences, Chapter 4 of the HoTT Book (http://homotopytypetheory.org/book/) is an excellent resource. *)\n\nClass Contr (A : Type)\n  := { center : A;\n       contr : forall y, center = y }.\n\nArguments center A {_}.\n\nClass IsEquiv {A B} (f : A -> B)\n  := Build_IsEquiv : forall b, Contr { a : A | f a = b }.\n\nRecord Equiv A B\n  := { equiv_fun : A -> B;\n       equiv_isequiv : IsEquiv equiv_fun }.\n\nArguments equiv_fun {A B} _ _.\nArguments equiv_isequiv {A B} _ _.\n\n(** Let us use an object of type [Equiv] as a function: *)\n\nCoercion equiv_fun : Equiv >-> Funclass.\n\n(** Tell Coq that the function associated to an [Equiv] object is\n    always an equivalence. *)\n\nExisting Instance equiv_isequiv.\n\nNotation \"A <~> B\" := (Equiv A B) (at level 70).\nNotation \"A ≃ B\" := (Equiv A B) (at level 70).\n\nDefinition Equiv_refl : forall A, A ≃ A.\nProof.\n  refine (fun A => {| equiv_fun := fun x => x;\n                      equiv_isequiv := fun b => _ |}).\n  refine ({| center := (b; refl) |}).\n  refine (fun y => match y with\n                     | existT a p => _\n                   end).\n  refine (match p with\n            | refl => refl\n          end).\nDefined.\n\n(** We can now state univalence; take on faith for now that all proofs of \"f is an equivalence are equal\"; there is a homework problem to prove it below. *)\n\n(** Now that we have a \"good\" type of isomorphism/equivalence (one with the right equality type), we can go back to the question of [Isomorphic_ap]; Recall that we want to prove:\n\n<<\nDefinition Isomorphic_ap : forall (f : Type -> Type) {A B}, A ≅ B -> f A ≅ f B.\n>> *)\n\n(** We can prove this by axiomatizing the codes for types: *)\n\nDefinition Type_code' : forall (x y : Type), Type\n  := fun x y => x ≃ y.\n\nDefinition Type_encode' : forall {x y : Type}, x = y -> Type_code' x y\n  := fun x y H => match H with\n                    | refl => Equiv_refl x\n                  end.\n\n(** The following are unprovable in Coq, currently.  They are collectively known as the \"univalence axiom\". *)\n\nAxiom Type_decode' : forall {x y : Type}, Type_code' x y -> x = y.\nAxiom Type_endecode' : forall {x y : Type} (p : Type_code' x y),\n                         Type_encode' (Type_decode' p) = p.\nAxiom Type_deencode' : forall {x y : Type} (p : x = y),\n                         Type_decode' (Type_encode' p) = p.\n\n(** We can collect these together into a single axiom: *)\n\nAxiom Univalence : forall {x y : Type}, IsEquiv (@Type_encode' x y).\n\n(** * Homework (Optional) *)\n\n(** Now we go back and see these things in more detail.  The goal of these exercises is to make the above seem obvious. *)\n\n(** ** Inductive Types *)\n\n(** First, we must understand the types which we are classifying the path-spaces of. *)\n\n(** An inductive type is specified by introduction and elimination rules; introduction rules tell you how to create inhabitants (elements) of a type, and elimination rules tell you how to use such inhabitants.  Coq generate eliminations rules automatically, but we will try to come up with the first few without peeking. *)\n\n(** Here are some examples. *)\n\nInductive unit : Type := tt.\n\n(** To prove a property of any unit, it suffices to prove that property of [tt]. *)\n\nDefinition unit_elim : forall (P : unit -> Type) (x : unit), P tt -> P x\n  := fun P x Ptt => match x with\n                      | tt => Ptt\n                    end.\n\nInductive bool : Type := true | false.\n\n(** To prove a property of any boolean, it suffices to prove that property of [true] and [false]. *)\n\nDefinition bool_elim : forall (P : bool -> Type) (x : bool), P true -> P false -> P x\n  := fun P x Pt Pf => match x with\n                        | true => Pt\n                        | false => Pf\n                      end.\n\n(** A notational helper. *)\n\nAdd Printing If bool.\n\n(** Coq has special syntax for [nat], so we don't overwrite it. *)\n\nInductive nat' : Type := zero | successor (x : nat').\n\n(** We use [Fixpoint] to allow recursion. *)\n\nFixpoint nat'_elim (P : nat' -> Type) (x : nat')\n: P zero\n  -> (forall n, P n -> P (successor n))\n  -> P x\n  := fun Pz Ps => match x with\n                    | zero => Pz\n                    | successor x' => Ps x' (nat'_elim P x' Pz Ps)\n                  end.\n\nInductive Empty_set : Type := .\n\n(** How can you prove this one? *)\n\nDefinition Empty_set_elim : forall (P : Empty_set -> Type) (x : Empty_set), P x\n  := admit.\n\n(** Anecdote: Proving [unit -> Empty_set] (i.e., [True -> False]) by recursion on [unit], if we assume that [True = (False -> False)] *)\n\nInductive prod (A B : Type) : Type := pair (a : A) (b : B).\n\n(** Some notational helpers *)\n\nArguments pair {A B} _ _.\n\nAdd Printing Let prod.\n\nNotation \"x * y\" := (prod x y) : type_scope.\nNotation \"( x , y , .. , z )\" := (pair .. (pair x y) .. z) : core_scope.\n\nExample prod_1 := (1, 1) : nat * nat.\nExample prod_2 := (1, 2) : nat * nat.\nExample prod_3 := (true, true) : bool * bool.\nExample prod_4 := (1, true) : nat * bool.\n\n(** We use curlie braces so that we don't have to pass the arguments explicitly all the time. *)\n\n(** Try filling these in. *)\n\n(**\n<<\nDefinition prod_elim : admit\n  := admit.\n\nDefinition fst : forall {A B}, A * B -> A\n:= admit.\n\nDefinition snd : forall {A B}, A * B -> B\n:= admit.\n\n>> *)\n\n(** [sum A B], written [A + B], is the disjoint sum of [A] and [B] *)\n\n(** Inductive sum (A B : Type) : Type := ... *)\n\n(** Notational helpers *)\n\n(**\n<<\nNotation \"x + y\" := (sum x y) : type_scope.\n\nArguments inl {A B} _ , [A] B _.\nArguments inr {A B} _ , A [B] _.\n>> *)\n\nExample sum_1 := inl tt : unit + nat.\nExample sum_2 := inr 0 : unit + nat.\n\n(** Inductive sigT A (B : A -> Type) : Type := ... *)\n\n(** Notational helpers *)\n\n(**\n<<\nArguments sigT {A} B.\nArguments existT {A} B _ _.\nNotation \"{ a : A  & B }\" := (sigT (A:=A) (fun a => B)) : type_scope.\n>> *)\n\nNotation \"{ a  |  B }\" := ({ a : _ & B }) : type_scope.\nNotation \"{ a : A  |  B }\" := ({ a : A & B }) : type_scope.\nNotation \"( a ; b )\" := (existT _ a b).\n\nExample non_dependent_pair_1 :=\n  (true; 0) : sigT (fun a : bool => nat).\nExample non_dependent_pair_2 :=\n  (true; 1) : { a : bool | nat }.\nExample non_dependent_pair_3 :=\n  (false; 1) : { a : bool | nat }.\nExample dependent_pair_1 :=\n  (true; 1) : { a : bool | if a then nat else unit }.\nExample dependent_pair_2 :=\n  (true; 0) : { a : bool | if a then nat else unit }.\nExample dependent_pair_3 :=\n  (false; tt) : { a : bool | if a then nat else unit }.\nFail Example dependent_pair_4 :=\n  (false; 0) : { a : bool | if a then nat else unit }.\n\n(** The projections *)\n\n(**\n<<\nDefinition projT1 : forall {A B}, { a : A | B a } -> A\n  := admit.\n\nDefinition projT2 : forall {A B} (x : { a : A | B a}), B (projT1 x)\n  := admit.\n>> *)\n\n(** Notational helpers for the projections *)\n\nNotation \"x .1\" := (projT1 x) (at level 3, format \"x '.1'\").\nNotation \"x .2\" := (projT2 x) (at level 3, format \"x '.2'\").\n\n(** Inductive option (A : Type) : Type := ... *)\n\n(** Inductive list (A : Type) : Type := ... *)\n\n(** Function types also have intro and elim rules, though they don't have syntactic forms.  Can you describe them? *)\n\n(** Note well: [J] is the eliminator for the equality type. *)\n\n(** ** Equality classification *)\n\n(** We can classify the equality types.  For each type, we come up with a simpler type that represents (\"codes for\") its equality type.  Then we prove that this type is isomorphic to the given equality type. *)\n\n(** *** [unit] *)\n\nDefinition unit_code : forall (x y : unit), Type\n  := admit.\n\n(** We use curlie braces to not have to pass the [x] and [y] around all the time. *)\n\nDefinition unit_encode : forall {x y : unit}, x = y -> unit_code x y\n  := admit.\n\nDefinition unit_decode : forall {x y : unit}, unit_code x y -> x = y\n  := admit.\n\nDefinition unit_endecode : forall {x y} (p : unit_code x y),\n                             unit_encode (unit_decode p) = p\n  := admit.\n\nDefinition unit_deencode : forall {x y} (p : x = y),\n                             unit_decode (unit_encode p) = p\n  := admit.\n\n\n(** *** [bool] *)\n\nDefinition bool_code : forall (x y : bool), Type\n  := admit.\n\nDefinition bool_encode : forall {x y : bool}, x = y -> bool_code x y\n  := admit.\n\nDefinition bool_decode : forall {x y : bool}, bool_code x y -> x = y\n  := admit.\n\nDefinition bool_endecode : forall {x y : bool} (p : bool_code x y),\n                             bool_encode (bool_decode p) = p\n  := admit.\n\nDefinition bool_deencode : forall {x y : bool} (p : x = y),\n                             bool_decode (bool_encode p) = p\n  := admit.\n\n\n(** *** [prod] *)\n\nDefinition prod_code : forall {A B} (x y : A * B), Type\n  := admit.\n\nDefinition prod_encode : forall {A B} {x y : A * B}, x = y -> prod_code x y\n  := admit.\n\nDefinition prod_decode : forall {A B} {x y : A * B}, prod_code x y -> x = y\n  := admit.\n\nDefinition prod_endecode : forall {A B} {x y : A * B} (p : prod_code x y),\n                             prod_encode (prod_decode p) = p\n  := admit.\n\nDefinition prod_deencode : forall {A B} {x y : A * B} (p : x = y),\n                             prod_decode (prod_encode p) = p\n  := admit.\n\n\n(** *** [Empty_set] *)\n\nDefinition Empty_set_code : forall (x y : Empty_set), Type\n  := admit.\n\nDefinition Empty_set_encode : forall {x y : Empty_set},\n                                x = y -> Empty_set_code x y\n  := admit.\n\nDefinition Empty_set_decode : forall {x y : Empty_set},\n                                Empty_set_code x y -> x = y\n  := admit.\n\nDefinition Empty_set_endecode : forall {x y : Empty_set} (p : Empty_set_code x y),\n                                  Empty_set_encode (Empty_set_decode p) = p\n  := admit.\n\nDefinition Empty_set_deencode : forall {x y : Empty_set} (p : x = y),\n                                  Empty_set_decode (Empty_set_encode p) = p\n  := admit.\n\n\n(** *** [sum] *)\n\nDefinition sum_code : forall {A B} (x y : A + B), Type\n  := admit.\n\nDefinition sum_encode : forall {A B} {x y : A + B}, x = y -> sum_code x y\n  := admit.\n\nDefinition sum_decode : forall {A B} {x y : A + B}, sum_code x y -> x = y\n  := admit.\n\nDefinition sum_endecode : forall {A B} {x y : A + B} (p : sum_code x y),\n                             sum_encode (sum_decode p) = p\n  := admit.\n\nDefinition sum_deencode : forall {A B} {x y : A + B} (p : x = y),\n                             sum_decode (sum_encode p) = p\n  := admit.\n\n\n(** *** [sigma] (dependent pairs) *)\n\nDefinition sigma_code : forall {A B} (x y : { a : A | B a }), Type\n  := admit.\n\nDefinition sigma_encode : forall {A B} {x y : { a : A | B a }}, x = y -> sigma_code x y\n  := admit.\n\nDefinition sigma_decode : forall {A B} {x y : { a : A | B a }}, sigma_code x y -> x = y\n  := admit.\n\nDefinition sigma_endecode : forall {A B} {x y : { a : A | B a }} (p : sigma_code x y),\n                             sigma_encode (sigma_decode p) = p\n  := admit.\n\nDefinition sigma_deencode : forall {A B} {x y : { a : A | B a }} (p : x = y),\n                             sigma_decode (sigma_encode p) = p\n  := admit.\n\n\n(** *** [nat] *)\n\n(** Homework: *)\n\n(** Warmup: *)\n\nDefinition zero_ne_one : 0 = 1 -> Empty_set\n  := admit.\n\n(** Hint for the above: Use [J]. *)\n\nDefinition zero_ne_succ : forall n, 0 = S n -> Empty_set\n  := admit.\n\nDefinition nat_code : forall (x y : nat), Type\n  := admit.\n\nDefinition nat_encode : forall {x y : nat},\n                                x = y -> nat_code x y\n  := admit.\n\nDefinition nat_decode : forall {x y : nat},\n                                nat_code x y -> x = y\n  := admit.\n\nDefinition nat_endecode : forall {x y : nat} (p : nat_code x y),\n                                  nat_encode (nat_decode p) = p\n  := admit.\n\nDefinition nat_deencode : forall {x y : nat} (p : x = y),\n                                  nat_decode (nat_encode p) = p\n  := admit.\n\n\n(** *** [option] *)\n\n(** Homework: *)\n\nDefinition option_code : forall {A} (x y : option A), Type\n  := admit.\n\nDefinition option_encode : forall {A} {x y : option A}, x = y -> option_code x y\n  := admit.\n\nDefinition option_decode : forall {A} {x y : option A}, option_code x y -> x = y\n  := admit.\n\nDefinition option_endecode : forall {A} {x y : option A} (p : option_code x y),\n                             option_encode (option_decode p) = p\n  := admit.\n\nDefinition option_deencode : forall {A} {x y : option A} (p : x = y),\n                             option_decode (option_encode p) = p\n  := admit.\n\n\n(** *** [list] *)\n\n(** Homework: *)\n\nDefinition list_code : forall {A} (x y : list A), Type\n  := admit.\n\nDefinition list_encode : forall {A} {x y : list A}, x = y -> list_code x y\n  := admit.\n\nDefinition list_decode : forall {A} {x y : list A}, list_code x y -> x = y\n  := admit.\n\nDefinition list_endecode : forall {A} {x y : list A} (p : list_code x y),\n                             list_encode (list_decode p) = p\n  := admit.\n\nDefinition list_deencode : forall {A} {x y : list A} (p : x = y),\n                             list_decode (list_encode p) = p\n  := admit.\n\n\n(** *** arrow types *)\n\nDefinition arrow_code : forall {A B} (f g : A -> B), Type\n  := fun A B f g => forall a, f a = g a.\n\nDefinition arrow_encode : forall {A B} {f g : A -> B}, f = g -> arrow_code f g\n  := fun A B f g H\n       => match H with\n           | refl => fun a => refl (f a)\n          end.\n\n(** The rest aren't currently provable in Coq; it's the axiom of functional extensionality. *)\n\nAxiom arrow_decode : forall {A B} {f g : A -> B}, arrow_code f g -> f = g.\nAxiom arrow_endecode : forall {A B} {f g : A -> B} (p : arrow_code f g),\n                         arrow_encode (arrow_decode p) = p.\nAxiom arrow_deencode : forall {A B} {f g : A -> B} (p : f = g),\n                         arrow_decode (arrow_encode p) = p.\n\n(** *** Pi types (dependent function types) *)\n\nDefinition function_code : forall {A B} (f g : forall a : A, B a), Type\n  := fun A B f g => forall a, f a = g a.\n\nDefinition function_encode : forall {A B} {f g : forall a : A, B a}, f = g -> function_code f g\n  := fun A B f g H\n       => match H with\n           | refl => fun a => refl (f a)\n          end.\n\n(** The rest aren't currently provable in Coq; it's the axiom of functional extensionality. *)\n\nAxiom function_decode : forall {A B} {f g : forall a : A, B a}, function_code f g -> f = g.\nAxiom function_endecode : forall {A B} {f g : forall a : A, B a} (p : function_code f g),\n                            function_encode (function_decode p) = p.\nAxiom function_deencode : forall {A B} {f g : forall a : A, B a} (p : f = g),\n                            function_decode (function_encode p) = p.\n\n(** **** Homework: mere propositions *)\n\n(** Homework; challenging problem *)\n\n(** Recall the definition of contractibility above.  The reason that we can safely call this contractible is that all of the higher structure collapses.  That is, if all inhabitants of [A] are (continuously) equal, then all inhabitants of [x = y] for [x : A] and [y : A] are also equal.  Prove this, as follows. *)\n\n(** First we define what it means for a type to be a \"mere proposition\", or to satisfy the uniqueness of identity proofs. *)\n\nDefinition is_prop : Type -> Type\n  := fun A => forall x y : A, x = y.\n\n(** We classify the equality type of propositions. *)\n\nDefinition prop_code : forall {A} (allpaths : is_prop A) (x y : A), Type\n  := fun A allpaths x y => unit.\n\nDefinition prop_encode : forall {A} (allpaths : is_prop A) {x y : A},\n                           x = y -> prop_code allpaths x y\n  := admit.\n\nDefinition prop_decode : forall {A} (allpaths : is_prop A) {x y : A},\n                           prop_code allpaths x y -> x = y\n  := admit.\n\nDefinition prop_endecode : forall {A} (allpaths : is_prop A) {x y : A} (p : prop_code allpaths x y),\n                            prop_encode allpaths (prop_decode allpaths p) = p\n  := admit.\n\n(** If you find this proof hard, and can't figure out why, think about the proof of [dec_deencode].  If you're still having trouble, look a bit further down for a hint. *)\n\nDefinition prop_deencode : forall {A} (allpaths : is_prop A) {x y : A} (p : x = y),\n                             prop_decode allpaths (prop_encode allpaths p) = p\n  := admit.\n\n(** Hint: you may need to rewrite your [prop_decode] function.  The following lemmas may prove helpful. *)\n\n(** Try to write an \"adjuster\" for [is_prop] that will always return something equal to [refl] (provably) when handed two judgmentally equal things. *)\n\nDefinition adjust_allpaths : forall {A}, is_prop A -> is_prop A\n  := admit.\n\nDefinition adjust_allpaths_refl : forall {A} (allpaths : is_prop A) x,\n                                   adjust_allpaths allpaths x x = refl\n  := admit.\n\n(** Now move these lemmas above [prop_decode] and try re-writing the codes so that you expect [prop_deencode] to work. *)\n\n(** *** decidable types *)\n\n(** Homework; challenging problem *)\n\n(** More generally, we can do this for any type with decidable equality. *)\n\n(** First we define what it means for a type to have decidable equality: it means that we have a (continuous!) function from pairs of inhabitants to proofs that either they are equal, or that their equality is absurd. *)\n\nDefinition decidable : Type -> Type\n  := fun A => forall x y : A, (x = y) + (x = y -> Empty_set).\n\nDefinition dec_code : forall {A} (dec : decidable A) (x y : A), Type\n  := admit.\n\nDefinition dec_encode : forall {A} (dec : decidable A) {x y : A},\n                          x = y -> dec_code dec x y\n  := admit.\n\nDefinition dec_decode : forall {A} (dec : decidable A) {x y : A},\n                          dec_code dec x y -> x = y\n  := admit.\n\nDefinition dec_endecode : forall {A} (dec : decidable A) {x y : A} (p : dec_code dec x y),\n                            dec_encode dec (dec_decode dec p) = p\n  := admit.\n\n(** If you find this proof hard, and can't figure out why, look a bit further down for a hint. *)\n\nDefinition dec_deencode : forall {A} (dec : decidable A) {x y : A} (p : x = y),\n                             dec_decode dec (dec_encode dec p) = p\n  := admit.\n\n(** Hint: you may need to rewrite your [dec_decode], [dec_code], and [dec_encode] functions, just as you did with [prop_decode].  The following lemmas may prove helpful. *)\n\n(** Try to write an \"adjuster\" for decidable equality that will always return something equal to [refl] (provably) when handed two equal things. *)\n\nDefinition adjust_dec : forall {A}, decidable A -> decidable A\n  := admit.\n\nDefinition adjust_dec_refl : forall {A} (dec : decidable A) (x : A),\n                               adjust_dec dec x x = inl refl\n  := admit.\n\n(** Now move these lemmas above [dec_code] and try re-writing the codes so that you expect [dec_deencode] to work. *)\n\n(** *** Pushing Further *)\n\n(** Homework: Generalize the above two proofs to solve \"Puzzle 2\" far above.  (Don't forget to also do puzzle 1 while you're at it.) *)\n\n(** Homework: Using the solution to Puzzle 2, show that it is sufficient to assume [function_decode] an axiom; the endecode and [deencode] proofs follow from puzzle 2. *)\n\nDefinition function_code' : forall {A B} (f g : forall a : A, B a), Type\n  := admit.\n\nDefinition function_encode' : forall {A B} {f g : forall a : A, B a}, f = g -> function_code' f g\n  := admit.\n\nAxiom function_decode' : forall {A B} {f g : forall a : A, B a}, function_code' f g -> f = g.\n\nDefinition function_decode_adjusted' : forall {A B} {f g : forall a : A, B a}, function_code' f g -> f = g\n  := admit.\n\nDefinition function_endecode' : forall {A B} {f g : forall a : A, B a} (p : function_code' f g),\n                                  function_encode' (function_decode_adjusted' p) = p\n  := admit.\nDefinition function_deencode' : forall {A B} {f g : forall a : A, B a} (p : f = g),\n                                  function_decode_adjusted' (function_encode' p) = p\n  := admit.\n\n(** ** Isomorphisms *)\n\n(** We can prove that an equivalence gives us an isomorphism very easily. *)\n\nDefinition iso_of_equiv : forall {A B}, A ≃ B -> A ≅ B.\nProof.\n  refine (fun A B e\n          => {| iso_fun x := e x;\n                iso_isiso := {| iso_inv x := (@center _ (equiv_isequiv e x)).1 |} |}).\n  { intro x.\n    refine ((center {a : A | e a = x}).2). }\n  { intro x.\n    refine (@trans _ _ (existT (fun a => e a = e x) x (refl (e x))).1 _ _ _).\n    { refine (ap _ _).\n      refine (contr _). }\n    { simpl.\n      refine (refl x). } }\nDefined.\n\n(** We can go the other way with more work. *)\n\n(** Optional Homework: Complete this proof. *)\n\nDefinition equiv_of_iso : forall {A B}, A ≅ B -> A ≃ B.\nProof.\n  refine (fun A B e\n          => {| equiv_fun := e |}).\n  refine (fun b => _).\n  refine {| center := existT (fun a => e a = b) (iso_inv e b) (right_inv e b);\n            contr := _ |}.\n  refine admit.\nDefined.\n\n\n(** Now, prove the following helper lemma, which lets us get the right codes for [Equiv].  You will need [function_code] and [sigma_code]. *)\n\nDefinition allpath_contr : forall {A} (x y : Contr A), x = y.\nProof.\n  refine admit.\nDefined.\n\nDefinition allpath_isequiv : forall {A B} (f : A -> B) (e1 e2 : IsEquiv f), e1 = e2.\nProof.\n  refine admit.\nDefined.\n\nDefinition equiv_code : forall {A B} (f g : A ≃ B), Type\n  := fun A B f g => equiv_fun f = equiv_fun g.\n\nDefinition equiv_encode : forall {A B} {f g : A ≃ B}, f = g -> equiv_code f g\n  := admit.\n\nDefinition equiv_decode : forall {A B} {f g : A ≃ B}, equiv_code f g -> f = g\n  := admit.\n\nDefinition equiv_endecode : forall {A B} {f g : A ≃ B} (p : equiv_code f g),\n                              equiv_encode (equiv_decode p) = p\n  := admit.\n\nDefinition equiv_deencode : forall {A B} {f g : A ≃ B} (p : f = g),\n                              equiv_decode (equiv_encode p) = p\n  := admit.\n\n(** *** More Homework: Playing with univalence *)\n\n(** Using univalence, we can prove some things. *)\n\nDefinition Empty_set_eq : (Empty_set = Empty_set) = unit :> Type\n  := admit.\n\nDefinition unit_eq : (unit = unit) = unit :> Type\n  := admit.\n\nDefinition bool_eq : (bool = bool) = bool :> Type\n  := admit.\n\nDefinition bool_arrow_bool_eq : (bool -> bool) = (bool * bool)%type\n  := admit.\n\nDefinition prod_commutes : forall (A B : Type), (A * B = B * A)%type\n  := admit.\n\n(** Challenge: Show, without axioms, that univalence implies functional extensionality: *)\n\nDefinition univalence_implies_funext\n: (forall A B, IsEquiv (@Type_encode' A B))\n  -> (forall A B (f g : forall a : A, B a), (forall a, f a = g a) -> f = g)\n  := admit.\n\n(** Exercise 2.17 from the HoTT Book (http://homotopytypetheory.org/book/ - don't worry about reading the book):\n\n  Show that if [A ≃ A'] and [B ≃ B'], then [(A * B) ≃ (A' * B')] in two ways: once using univalence, and once without assuming it. *)\n\nDefinition equiv_functor_prod_univalence\n: (forall A B, IsEquiv (@Type_encode A B))\n  -> forall A A' B B',\n       A ≃ A' -> B ≃ B' -> (A * B ≃ A' * B')%type\n  := admit.\n\nDefinition equiv_functor_prod_no_univalence\n: forall A A' B B',\n    A ≃ A' -> B ≃ B' -> (A * B ≃ A' * B')%type\n  := admit.\n\n(** Now prove that these two ways are equal *)\n\nDefinition equiv_functor_prod_eq\n: forall univalence,\n    equiv_functor_prod_univalence univalence = equiv_functor_prod_no_univalence\n  := admit.\n", "meta": {"author": "JasonGross", "repo": "HoTT-mathcamp-2015-class", "sha": "ff2022e7e12d45470d95249d6731bb20b3335747", "save_path": "github-repos/coq/JasonGross-HoTT-mathcamp-2015-class", "path": "github-repos/coq/JasonGross-HoTT-mathcamp-2015-class/HoTT-mathcamp-2015-class-ff2022e7e12d45470d95249d6731bb20b3335747/exercises_and_homework_day_3_homework.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.8902942348544447, "lm_q1q2_score": 0.6535823824933054}}
{"text": "Require Import Coq.Unicode.Utf8_core.\nRequire Import Coq.Bool.Bool.\n\nRequire Import VarAssign.\n\nInductive boolExpr : Type :=\n| Atom : nat -> bool -> boolExpr\n| And  : boolExpr -> boolExpr -> boolExpr\n| Or   : boolExpr -> boolExpr -> boolExpr.\n\nDefinition optional_and (a b:option bool) : option bool :=\nmatch a with\n| None => None\n| Some ba => (match b with\n             | None => None\n             | Some bb => Some (ba && bb) end)\nend.\n\nDefinition optional_or (a b:option bool) : option bool :=\nmatch a with\n| None => None\n| Some ba => (match b with\n             | None => None\n             | Some bb => Some (ba || bb)\n             end)\nend.\n\nDefinition optional_not (a:option bool) : option bool :=\nmatch a with\n| None => None\n| Some ba => Some (negb ba)\nend.\n\n\nFixpoint eval_ (be:boolExpr) (va:varAssign) : option bool :=\nmatch be with\n| Atom n same => let value := lookup va n in\n                 if same then value else (optional_not value)\n| And e1 e2   => optional_and (eval_ e1 va) (eval_ e2 va)\n| Or e1 e2    => optional_or (eval_ e1 va) (eval_ e2 va)\nend.\n\nInductive eval : boolExpr -> bool -> varAssign -> Prop :=\n| eval_atom_same : forall n va res, (assigns va n res) ->\n                                    eval (Atom n true) res va\n| eval_atom_neg  : forall n va res, (assigns va n res) ->\n                                    eval (Atom n false) (negb res) va\n| eval_and       : forall e1 res1 e2 res2 va, (eval e1 res1 va) -> (eval e2 res2 va) ->\n                                              eval (And e1 e2) (andb res1 res2) va\n| eval_or        : forall e1 res1 e2 res2 va, (eval e1 res1 va) -> (eval e2 res2 va) ->\n                                              eval (Or e1 e2) (orb res1 res2) va.\n\n\nInductive boolExpr' : Type :=\n| Atom' : nat -> boolExpr'\n| Not'  : boolExpr' -> boolExpr'\n| And'  : boolExpr' -> boolExpr' -> boolExpr'\n| Or'  : boolExpr' -> boolExpr' -> boolExpr'.\n\nFixpoint eval_' (be:boolExpr') (va:varAssign) : option bool :=\nmatch be with\n| Atom' n     => lookup va n\n| Not' e      => optional_not (eval_' e va)\n| And' e1 e2  => optional_and (eval_' e1 va) (eval_' e2 va)\n| Or' e1 e2  => optional_or (eval_' e1 va) (eval_' e2 va)\nend.\n\nInductive eval' : boolExpr' -> bool -> varAssign -> Prop :=\n| eval'_atom : forall n va res, (assigns va n res) -> eval' (Atom' n) res va\n| eval'_not  : forall b' res va, eval' b' res va -> eval' (Not' b') (negb res) va\n| eval'_and  : forall b1' res1 b2' res2 va, eval' b1' res1 va ->\n                                           eval' b2' res2 va ->\n                                           eval' (And' b1' b2') (andb res1 res2) va\n| eval'_or   : forall b1' res1 b2' res2 va, eval' b1' res1 va ->\n                                           eval' b2' res2 va ->\n                                           eval' (Or' b1' b2') (orb res1 res2) va.\n\n\nFixpoint b_b'_equivalent (be:boolExpr) (be':boolExpr') : bool :=\nmatch be with\n| Atom n same => if same\n                 then (match be' with\n                       | Atom' n => true\n                       | _ => false\n                      end)\n                 else (match be' with\n                       | Not' (Atom' n) => true\n                       | _ => false\n                       end)\n| And e1 e2   => (match be' with\n                  | And' e1' e2' => (b_b'_equivalent e1 e1') && (b_b'_equivalent e2 e2')\n                  | _ => false\n                  end)\n| Or e1 e2    => (match be' with\n                  | Or' e1' e2' => (b_b'_equivalent e1 e1') && (b_b'_equivalent e2 e2')\n                  | _ => false\n                  end)\nend.\n\nInductive eq_b_b' : boolExpr -> boolExpr' -> Prop :=\n| eq_atom_atom' : forall n, eq_b_b' (Atom n true) (Atom' n)\n| eq_natom_not' : forall n, eq_b_b' (Atom n false) (Not' (Atom' n))\n| eq_and_and'   : forall b1 b1' b2 b2', eq_b_b' b1 b1' -> eq_b_b' b2 b2' ->\n                                        eq_b_b' (And b1 b2) (And' b1' b2')\n| eq_or_or'     : forall b1 b1' b2 b2', eq_b_b' b1 b1' -> eq_b_b' b2 b2' ->\n                                        eq_b_b' (Or b1 b2) (Or' b1' b2').\n\n\nCompute (b_b'_equivalent (And (Atom 1 true) (Atom 1 false)) (And' (Atom' 1) (Not' (Atom' 1)))).\n\nLemma same_assigns :\n  forall res res' va n, assigns va n res -> assigns va n res' -> res = res'.\nProof.\n  intros. induction va.\n  - inversion H.\n  - inversion H; inversion H0.\n    + rewrite H5 in H10. assumption.\n    + unfold not in H11. symmetry in H1. apply H11 in H1. inversion H1.\n    + unfold not in H6. symmetry in H8. apply H6 in H8. inversion H8.\n    + apply IHva. assumption. assumption.\nQed.\n\nLemma eqb_and :\n  forall a b c d, eqb a c = true -> eqb b d = true -> eqb (a && b) (c && d) = true.\nintros. destruct a; destruct b; destruct c; destruct d; simpl;\n          try reflexivity; try inversion H; try inversion H0.\nQed.\n\nLemma eqb_or :\n  forall a b c d, eqb a c = true -> eqb b d = true -> eqb (a || b) (c || d) = true.\nintros. destruct a; destruct b; destruct c; destruct d; simpl;\n          try reflexivity; try inversion H; try inversion H0.\nQed.\n\nTheorem eq_b_b'_sameResult :\n  forall b res b' res' va, eq_b_b' b b' -> eval b res va -> eval' b' res' va ->\n                           (eqb res res') = true.\nProof.\n  intro. intro. intro. intro. intro. intro. generalize res res'.\n  induction H; intros.\n  - inversion H. inversion H0. apply (same_assigns res0 res'0 va n) in H2.\n    + rewrite H2. apply eqb_reflx.\n    + assumption.\n  - inversion H. inversion H0. inversion H6. apply (same_assigns res1 res2 va n) in H2.\n    + rewrite H2. destruct res2; reflexivity.\n    + assumption.\n  - inversion H1. inversion H2.\n     apply (IHeq_b_b'1 res1 res3) in H5. apply (IHeq_b_b'2 res2 res4) in H8.\n     apply eqb_and. assumption. assumption. assumption. assumption.\n  - inversion H1. inversion H2.\n     apply (IHeq_b_b'1 res1 res3) in H5. apply (IHeq_b_b'2 res2 res4) in H8.\n     apply eqb_or. assumption. assumption. assumption. assumption.\nQed.\n\n\n(*-----------------------------------------*)\n\nDefinition eqOptBool (a b:option bool) : bool :=\nmatch a with\n| None    => (match b with\n              | None => true\n              | Some _ => false\n              end)\n| Some ba => (match b with\n              | None => false\n              | Some bb => (eqb ba bb)\n              end)\nend.\n\n(*\nLemma eq_atom_atom' :\n  forall n n0 b, b_b'_equivalent (Atom n b) (Atom' n0) = true -> ((n = n0) /\\ (b = true)).\nAdmitted.\n*)\nLemma eq_atom_false_not' :\n  forall n b', b_b'_equivalent (Atom n false) (Not' b') = true ->\n                    (b' = (Atom' n)).\nAdmitted.\n\nLemma neq_atom_not' :\n  forall n n0, b_b'_equivalent (Atom n true) (Not' n0) = false.\nAdmitted.\n\nLemma neq_atom_and' :\n  forall n b b'1 b'2, b_b'_equivalent (Atom n b) (And' b'1 b'2) = false.\nAdmitted.\n\nLemma neq_atom_or' :\n  forall n b b'1 b'2, b_b'_equivalent (Atom n b) (Or' b'1 b'2) = false.\nAdmitted.\n\n\nLemma neq_and_atom' :\n  forall n b1 b2, b_b'_equivalent (And b1 b2) (Atom' n) = false.\nAdmitted.\n\nLemma neq_and_not' :\n  forall b1 b2 b', b_b'_equivalent (And b1 b2) (Not' b') = false.\nAdmitted.\n(*\nLemma eq_and_and' :\n  forall b1 b2 b'1 b'2, b_b'_equivalent b1 b'1 = true ->\n                        b_b'_equivalent b2 b'2 = true ->\n                        b_b'_equivalent (And b1 b2) (And' b'1 b'2) = true.\nAdmitted.\n*)\nLemma neq_and_or' :\n  forall b1 b2 b'1 b'2, b_b'_equivalent (And b1 b2) (Or' b'1 b'2) = false.\nAdmitted.\n\n\nLemma eqOptBool_lookup :\n  forall n va, eqOptBool (lookup va n) (lookup va n) = true.\nProof.\n  intros. destruct (lookup va n); simpl.\n  - apply eqb_reflx.\n  - reflexivity.\nQed.\n\n(*\nTheorem b_b'_equivalent_sameResult :\n  forall b b' va, (b_b'_equivalent b b') = true ->\n                  eqOptBool (eval_ b va) (eval_' b' va) = true.\nProof.\n  induction b; induction b'; intros.\n  * apply eq_atom_atom' in H. inversion H. rewrite H0. rewrite H1. simpl.\n    apply (eqOptBool_lookup n0 va).\n  * destruct b.\n    + rewrite neq_atom_not' in H. inversion H.\n    + apply eq_atom_false_not' in H. rewrite H. simpl. destruct (lookup va n); simpl.\n      { destruct b; simpl; reflexivity. }\n      { reflexivity. }\n  * rewrite neq_atom_and' in H. inversion H.\n  * rewrite neq_atom_or'  in H. inversion H.\n  * rewrite neq_and_atom' in H. inversion H.\n  * rewrite neq_and_not'  in H. inversion H.\n  * Admitted.\n\n\n\n*)\n\n", "meta": {"author": "SHoltzen", "repo": "verified-sdd", "sha": "d400630db6526997226d6723ff8aedc0f1466901", "save_path": "github-repos/coq/SHoltzen-verified-sdd", "path": "github-repos/coq/SHoltzen-verified-sdd/verified-sdd-d400630db6526997226d6723ff8aedc0f1466901/coq/BoolExp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.653540751515227}}
{"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(** Euclidean Division *)\n\nRequire Import NZAxioms NZMulOrder.\n\n(** The first signatures will be common to all divisions over NZ, N and Z *)\n\nModule Type DivMod (Import T:Typ).\n Parameters Inline div modulo : t -> t -> t.\nEnd DivMod.\n\nModule Type DivModNotation (T:Typ)(Import NZ:DivMod T).\n Infix \"/\" := div.\n Infix \"mod\" := modulo (at level 40, no associativity).\nEnd DivModNotation.\n\nModule Type DivMod' (T:Typ) := DivMod T <+ DivModNotation T.\n\nModule Type NZDivCommon (Import NZ : NZAxiomsSig')(Import DM : DivMod' NZ).\n Declare Instance div_wd : Proper (eq==>eq==>eq) div.\n Declare Instance mod_wd : Proper (eq==>eq==>eq) modulo.\n Axiom div_mod : forall a b, b ~= 0 -> a == b*(a/b) + (a mod b).\nEnd NZDivCommon.\n\n(** The different divisions will only differ in the conditions\n    they impose on [modulo]. For NZ, we only describe behavior\n    on positive numbers.\n\n    NB: This axiom would also be true for N and Z, but redundant.\n*)\n\nModule Type NZDivSpecific (Import NZ : NZOrdAxiomsSig')(Import DM : DivMod' NZ).\n Axiom mod_bound : forall a b, 0<=a -> 0<b -> 0 <= a mod b < b.\nEnd NZDivSpecific.\n\nModule Type NZDiv (NZ:NZOrdAxiomsSig)\n := DivMod NZ <+ NZDivCommon NZ <+ NZDivSpecific NZ.\n\nModule Type NZDiv' (NZ:NZOrdAxiomsSig) := NZDiv NZ <+ DivModNotation NZ.\n\nModule NZDivPropFunct\n (Import NZ : NZOrdAxiomsSig')\n (Import NZP : NZMulOrderPropSig NZ)\n (Import NZD : NZDiv' NZ)\n.\n\n(** Uniqueness theorems *)\n\nTheorem div_mod_unique :\n forall b q1 q2 r1 r2, 0<=r1<b -> 0<=r2<b ->\n  b*q1+r1 == b*q2+r2 -> q1 == q2 /\\ r1 == r2.\nProof.\nintros b.\nassert (U : forall q1 q2 r1 r2,\n            b*q1+r1 == b*q2+r2 -> 0<=r1<b -> 0<=r2 -> q1<q2 -> False).\n intros q1 q2 r1 r2 EQ LT Hr1 Hr2.\n contradict EQ.\n apply lt_neq.\n apply lt_le_trans with (b*q1+b).\n rewrite <- add_lt_mono_l. tauto.\n apply le_trans with (b*q2).\n rewrite mul_comm, <- mul_succ_l, mul_comm.\n apply mul_le_mono_nonneg_l; intuition; try order.\n rewrite le_succ_l; auto.\n rewrite <- (add_0_r (b*q2)) at 1.\n rewrite <- add_le_mono_l. tauto.\n\nintros q1 q2 r1 r2 Hr1 Hr2 EQ; destruct (lt_trichotomy q1 q2) as [LT|[EQ'|GT]].\nelim (U q1 q2 r1 r2); intuition.\nsplit; auto. rewrite EQ' in EQ. rewrite add_cancel_l in EQ; auto.\nelim (U q2 q1 r2 r1); intuition.\nQed.\n\nTheorem div_unique:\n forall a b q r, 0<=a -> 0<=r<b ->\n   a == b*q + r -> q == a/b.\nProof.\nintros a b q r Ha (Hb,Hr) EQ.\ndestruct (div_mod_unique b q (a/b) r (a mod b)); auto.\napply mod_bound; order.\nrewrite <- div_mod; order.\nQed.\n\nTheorem mod_unique:\n forall a b q r, 0<=a -> 0<=r<b ->\n  a == b*q + r -> r == a mod b.\nProof.\nintros a b q r Ha (Hb,Hr) EQ.\ndestruct (div_mod_unique b q (a/b) r (a mod b)); auto.\napply mod_bound; order.\nrewrite <- div_mod; order.\nQed.\n\n\n(** A division by itself returns 1 *)\n\nLemma div_same : forall a, 0<a -> a/a == 1.\nProof.\nintros. symmetry.\napply div_unique with 0; intuition; try order.\nnow nzsimpl.\nQed.\n\nLemma mod_same : forall a, 0<a -> a mod a == 0.\nProof.\nintros. symmetry.\napply mod_unique with 1; intuition; try order.\nnow nzsimpl.\nQed.\n\n(** A division of a small number by a bigger one yields zero. *)\n\nTheorem div_small: forall a b, 0<=a<b -> a/b == 0.\nProof.\nintros. symmetry.\napply div_unique with a; intuition; try order.\nnow nzsimpl.\nQed.\n\n(** Same situation, in term of modulo: *)\n\nTheorem mod_small: forall a b, 0<=a<b -> a mod b == a.\nProof.\nintros. symmetry.\napply mod_unique with 0; intuition; try order.\nnow nzsimpl.\nQed.\n\n(** * Basic values of divisions and modulo. *)\n\nLemma div_0_l: forall a, 0<a -> 0/a == 0.\nProof.\nintros; apply div_small; split; order.\nQed.\n\nLemma mod_0_l: forall a, 0<a -> 0 mod a == 0.\nProof.\nintros; apply mod_small; split; order.\nQed.\n\nLemma div_1_r: forall a, 0<=a -> a/1 == a.\nProof.\nintros. symmetry.\napply div_unique with 0; try split; try order; try apply lt_0_1.\nnow nzsimpl.\nQed.\n\nLemma mod_1_r: forall a, 0<=a -> a mod 1 == 0.\nProof.\nintros. symmetry.\napply mod_unique with a; try split; try order; try apply lt_0_1.\nnow nzsimpl.\nQed.\n\nLemma div_1_l: forall a, 1<a -> 1/a == 0.\nProof.\nintros; apply div_small; split; auto. apply le_succ_diag_r.\nQed.\n\nLemma mod_1_l: forall a, 1<a -> 1 mod a == 1.\nProof.\nintros; apply mod_small; split; auto. apply le_succ_diag_r.\nQed.\n\nLemma div_mul : forall a b, 0<=a -> 0<b -> (a*b)/b == a.\nProof.\nintros; symmetry.\napply div_unique with 0; try split; try order.\napply mul_nonneg_nonneg; order.\nnzsimpl; apply mul_comm.\nQed.\n\nLemma mod_mul : forall a b, 0<=a -> 0<b -> (a*b) mod b == 0.\nProof.\nintros; symmetry.\napply mod_unique with a; try split; try order.\napply mul_nonneg_nonneg; order.\nnzsimpl; apply mul_comm.\nQed.\n\n\n(** * Order results about mod and div *)\n\n(** A modulo cannot grow beyond its starting point. *)\n\nTheorem mod_le: forall a b, 0<=a -> 0<b -> a mod b <= a.\nProof.\nintros. destruct (le_gt_cases b a).\napply le_trans with b; auto.\napply lt_le_incl. destruct (mod_bound a b); auto.\nrewrite lt_eq_cases; right.\napply mod_small; auto.\nQed.\n\n\n(* Division of positive numbers is positive. *)\n\nLemma div_pos: forall a b, 0<=a -> 0<b -> 0 <= a/b.\nProof.\nintros.\nrewrite (mul_le_mono_pos_l _ _ b); auto; nzsimpl.\nrewrite (add_le_mono_r _ _ (a mod b)).\nrewrite <- div_mod by order.\nnzsimpl.\napply mod_le; auto.\nQed.\n\nLemma div_str_pos : forall a b, 0<b<=a -> 0 < a/b.\nProof.\nintros a b (Hb,Hab).\nassert (LE : 0 <= a/b) by (apply div_pos; order).\nassert (MOD : a mod b < b) by (destruct (mod_bound a b); order).\nrewrite lt_eq_cases in LE; destruct LE as [LT|EQ]; auto.\nexfalso; revert Hab.\nrewrite (div_mod a b), <-EQ; nzsimpl; order.\nQed.\n\nLemma div_small_iff : forall a b, 0<=a -> 0<b -> (a/b==0 <-> a<b).\nProof.\nintros a b Ha Hb; split; intros Hab.\ndestruct (lt_ge_cases a b); auto.\nsymmetry in Hab. contradict Hab. apply lt_neq, div_str_pos; auto.\napply div_small; auto.\nQed.\n\nLemma mod_small_iff : forall a b, 0<=a -> 0<b -> (a mod b == a <-> a<b).\nProof.\nintros a b Ha Hb. split; intros H; auto using mod_small.\nrewrite <- div_small_iff; auto.\nrewrite <- (mul_cancel_l _ _ b) by order.\nrewrite <- (add_cancel_r _ _ (a mod b)).\nrewrite <- div_mod, H by order. now nzsimpl.\nQed.\n\nLemma div_str_pos_iff : forall a b, 0<=a -> 0<b -> (0<a/b <-> b<=a).\nProof.\nintros a b Ha Hb; split; intros Hab.\ndestruct (lt_ge_cases a b) as [LT|LE]; auto.\nrewrite <- div_small_iff in LT; order.\napply div_str_pos; auto.\nQed.\n\n\n(** As soon as the divisor is strictly greater than 1,\n    the division is strictly decreasing. *)\n\nLemma div_lt : forall a b, 0<a -> 1<b -> a/b < a.\nProof.\nintros.\nassert (0 < b) by (apply lt_trans with 1; auto using lt_0_1).\ndestruct (lt_ge_cases a b).\nrewrite div_small; try split; order.\nrewrite (div_mod a b) at 2 by order.\napply lt_le_trans with (b*(a/b)).\nrewrite <- (mul_1_l (a/b)) at 1.\nrewrite <- mul_lt_mono_pos_r; auto.\napply div_str_pos; auto.\nrewrite <- (add_0_r (b*(a/b))) at 1.\nrewrite <- add_le_mono_l. destruct (mod_bound a b); order.\nQed.\n\n(** [le] is compatible with a positive division. *)\n\nLemma div_le_mono : forall a b c, 0<c -> 0<=a<=b -> a/c <= b/c.\nProof.\nintros a b c Hc (Ha,Hab).\nrewrite lt_eq_cases in Hab. destruct Hab as [LT|EQ];\n [|rewrite EQ; order].\nrewrite <- lt_succ_r.\nrewrite (mul_lt_mono_pos_l c) by order.\nnzsimpl.\nrewrite (add_lt_mono_r _ _ (a mod c)).\nrewrite <- div_mod by order.\napply lt_le_trans with b; auto.\nrewrite (div_mod b c) at 1 by order.\nrewrite <- add_assoc, <- add_le_mono_l.\napply le_trans with (c+0).\nnzsimpl; destruct (mod_bound b c); order.\nrewrite <- add_le_mono_l. destruct (mod_bound a c); order.\nQed.\n\n(** The following two properties could be used as specification of div *)\n\nLemma mul_div_le : forall a b, 0<=a -> 0<b -> b*(a/b) <= a.\nProof.\nintros.\nrewrite (add_le_mono_r _ _ (a mod b)), <- div_mod by order.\nrewrite <- (add_0_r a) at 1.\nrewrite <- add_le_mono_l. destruct (mod_bound a b); order.\nQed.\n\nLemma mul_succ_div_gt : forall a b, 0<=a -> 0<b -> a < b*(S (a/b)).\nProof.\nintros.\nrewrite (div_mod a b) at 1 by order.\nrewrite (mul_succ_r).\nrewrite <- add_lt_mono_l.\ndestruct (mod_bound a b); auto.\nQed.\n\n\n(** The previous inequality is exact iff the modulo is zero. *)\n\nLemma div_exact : forall a b, 0<=a -> 0<b -> (a == b*(a/b) <-> a mod b == 0).\nProof.\nintros. rewrite (div_mod a b) at 1 by order.\nrewrite <- (add_0_r (b*(a/b))) at 2.\napply add_cancel_l.\nQed.\n\n(** Some additionnal inequalities about div. *)\n\nTheorem div_lt_upper_bound:\n  forall a b q, 0<=a -> 0<b -> a < b*q -> a/b < q.\nProof.\nintros.\nrewrite (mul_lt_mono_pos_l b) by order.\napply le_lt_trans with a; auto.\napply mul_div_le; auto.\nQed.\n\nTheorem div_le_upper_bound:\n  forall a b q, 0<=a -> 0<b -> a <= b*q -> a/b <= q.\nProof.\nintros.\nrewrite (mul_le_mono_pos_l _ _ b) by order.\napply le_trans with a; auto.\napply mul_div_le; auto.\nQed.\n\nTheorem div_le_lower_bound:\n  forall a b q, 0<=a -> 0<b -> b*q <= a -> q <= a/b.\nProof.\nintros a b q Ha Hb H.\ndestruct (lt_ge_cases 0 q).\nrewrite <- (div_mul q b); try order.\napply div_le_mono; auto.\nrewrite mul_comm; split; auto.\napply lt_le_incl, mul_pos_pos; auto.\napply le_trans with 0; auto; apply div_pos; auto.\nQed.\n\n(** A division respects opposite monotonicity for the divisor *)\n\nLemma div_le_compat_l: forall p q r, 0<=p -> 0<q<=r ->\n    p/r <= p/q.\nProof.\n intros p q r Hp (Hq,Hqr).\n apply div_le_lower_bound; auto.\n rewrite (div_mod p r) at 2 by order.\n apply le_trans with (r*(p/r)).\n apply mul_le_mono_nonneg_r; try order.\n apply div_pos; order.\n rewrite <- (add_0_r (r*(p/r))) at 1.\n rewrite <- add_le_mono_l. destruct (mod_bound p r); order.\nQed.\n\n\n(** * Relations between usual operations and mod and div *)\n\nLemma mod_add : forall a b c, 0<=a -> 0<=a+b*c -> 0<c ->\n (a + b * c) mod c == a mod c.\nProof.\n intros.\n symmetry.\n apply mod_unique with (a/c+b); auto.\n apply mod_bound; auto.\n rewrite mul_add_distr_l, add_shuffle0, <- div_mod by order.\n now rewrite mul_comm.\nQed.\n\nLemma div_add : forall a b c, 0<=a -> 0<=a+b*c -> 0<c ->\n (a + b * c) / c == a / c + b.\nProof.\n intros.\n apply (mul_cancel_l _ _ c); try order.\n apply (add_cancel_r _ _ ((a+b*c) mod c)).\n rewrite <- div_mod, mod_add by order.\n rewrite mul_add_distr_l, add_shuffle0, <- div_mod by order.\n now rewrite mul_comm.\nQed.\n\nLemma div_add_l: forall a b c, 0<=c -> 0<=a*b+c -> 0<b ->\n (a * b + c) / b == a + c / b.\nProof.\n intros a b c. rewrite (add_comm _ c), (add_comm a).\n intros. apply div_add; auto.\nQed.\n\n(** Cancellations. *)\n\nLemma div_mul_cancel_r : forall a b c, 0<=a -> 0<b -> 0<c ->\n (a*c)/(b*c) == a/b.\nProof.\n intros.\n symmetry.\n apply div_unique with ((a mod b)*c).\n apply mul_nonneg_nonneg; order.\n split.\n apply mul_nonneg_nonneg; destruct (mod_bound a b); order.\n rewrite <- mul_lt_mono_pos_r; auto. destruct (mod_bound a b); auto.\n rewrite (div_mod a b) at 1 by order.\n rewrite mul_add_distr_r.\n rewrite add_cancel_r.\n rewrite <- 2 mul_assoc. now rewrite (mul_comm c).\nQed.\n\nLemma div_mul_cancel_l : forall a b c, 0<=a -> 0<b -> 0<c ->\n (c*a)/(c*b) == a/b.\nProof.\n intros. rewrite !(mul_comm c); apply div_mul_cancel_r; auto.\nQed.\n\nLemma mul_mod_distr_l: forall a b c, 0<=a -> 0<b -> 0<c ->\n  (c*a) mod (c*b) == c * (a mod b).\nProof.\n intros.\n rewrite <- (add_cancel_l _ _ ((c*b)* ((c*a)/(c*b)))).\n rewrite <- div_mod.\n rewrite div_mul_cancel_l; auto.\n rewrite <- mul_assoc, <- mul_add_distr_l, mul_cancel_l by order.\n apply div_mod; order.\n rewrite <- neq_mul_0; intuition; order.\nQed.\n\nLemma mul_mod_distr_r: forall a b c, 0<=a -> 0<b -> 0<c ->\n  (a*c) mod (b*c) == (a mod b) * c.\nProof.\n intros. rewrite !(mul_comm _ c); now rewrite mul_mod_distr_l.\nQed.\n\n(** Operations modulo. *)\n\nTheorem mod_mod: forall a n, 0<=a -> 0<n ->\n (a mod n) mod n == a mod n.\nProof.\n intros. destruct (mod_bound a n); auto. now rewrite mod_small_iff.\nQed.\n\nLemma mul_mod_idemp_l : forall a b n, 0<=a -> 0<=b -> 0<n ->\n ((a mod n)*b) mod n == (a*b) mod n.\nProof.\n intros a b n Ha Hb Hn. symmetry.\n generalize (mul_nonneg_nonneg _ _ Ha Hb).\n rewrite (div_mod a n) at 1 2 by order.\n rewrite add_comm, (mul_comm n), (mul_comm _ b).\n rewrite mul_add_distr_l, mul_assoc.\n intros. rewrite mod_add; auto.\n now rewrite mul_comm.\n apply mul_nonneg_nonneg; destruct (mod_bound a n); auto.\nQed.\n\nLemma mul_mod_idemp_r : forall a b n, 0<=a -> 0<=b -> 0<n ->\n (a*(b mod n)) mod n == (a*b) mod n.\nProof.\n intros. rewrite !(mul_comm a). apply mul_mod_idemp_l; auto.\nQed.\n\nTheorem mul_mod: forall a b n, 0<=a -> 0<=b -> 0<n ->\n (a * b) mod n == ((a mod n) * (b mod n)) mod n.\nProof.\n intros. rewrite mul_mod_idemp_l, mul_mod_idemp_r; trivial. reflexivity.\n now destruct (mod_bound b n).\nQed.\n\nLemma add_mod_idemp_l : forall a b n, 0<=a -> 0<=b -> 0<n ->\n ((a mod n)+b) mod n == (a+b) mod n.\nProof.\n intros a b n Ha Hb Hn. symmetry.\n generalize (add_nonneg_nonneg _ _ Ha Hb).\n rewrite (div_mod a n) at 1 2 by order.\n rewrite <- add_assoc, add_comm, mul_comm.\n intros. rewrite mod_add; trivial. reflexivity.\n apply add_nonneg_nonneg; auto. destruct (mod_bound a n); auto.\nQed.\n\nLemma add_mod_idemp_r : forall a b n, 0<=a -> 0<=b -> 0<n ->\n (a+(b mod n)) mod n == (a+b) mod n.\nProof.\n intros. rewrite !(add_comm a). apply add_mod_idemp_l; auto.\nQed.\n\nTheorem add_mod: forall a b n, 0<=a -> 0<=b -> 0<n ->\n (a+b) mod n == (a mod n + b mod n) mod n.\nProof.\n intros. rewrite add_mod_idemp_l, add_mod_idemp_r; trivial. reflexivity.\n now destruct (mod_bound b n).\nQed.\n\nLemma div_div : forall a b c, 0<=a -> 0<b -> 0<c ->\n (a/b)/c == a/(b*c).\nProof.\n intros a b c Ha Hb Hc.\n apply div_unique with (b*((a/b) mod c) + a mod b); trivial.\n (* begin 0<= ... <b*c *)\n destruct (mod_bound (a/b) c), (mod_bound a b); auto using div_pos.\n split.\n apply add_nonneg_nonneg; auto.\n apply mul_nonneg_nonneg; order.\n apply lt_le_trans with (b*((a/b) mod c) + b).\n rewrite <- add_lt_mono_l; auto.\n rewrite <- mul_succ_r, <- mul_le_mono_pos_l, le_succ_l; auto.\n (* end 0<= ... < b*c *)\n rewrite (div_mod a b) at 1 by order.\n rewrite add_assoc, add_cancel_r.\n rewrite <- mul_assoc, <- mul_add_distr_l, mul_cancel_l by order.\n apply div_mod; order.\nQed.\n\n(** A last inequality: *)\n\nTheorem div_mul_le:\n forall a b c, 0<=a -> 0<b -> 0<=c -> c*(a/b) <= (c*a)/b.\nProof.\n intros.\n apply div_le_lower_bound; auto.\n apply mul_nonneg_nonneg; auto.\n rewrite mul_assoc, (mul_comm b c), <- mul_assoc.\n apply mul_le_mono_nonneg_l; auto.\n apply mul_div_le; auto.\nQed.\n\n(** mod is related to divisibility *)\n\nLemma mod_divides : forall a b, 0<=a -> 0<b ->\n (a mod b == 0 <-> exists c, a == b*c).\nProof.\n split.\n intros. exists (a/b). rewrite div_exact; auto.\n intros (c,Hc). rewrite Hc, mul_comm. apply mod_mul; auto.\n rewrite (mul_le_mono_pos_l _ _ b); auto. nzsimpl. order.\nQed.\n\nEnd NZDivPropFunct.\n\n", "meta": {"author": "JasonGross", "repo": "category-coq-experience-tests", "sha": "f9949ede618788fd051fe8327f997ee683388e49", "save_path": "github-repos/coq/JasonGross-category-coq-experience-tests", "path": "github-repos/coq/JasonGross-category-coq-experience-tests/category-coq-experience-tests-f9949ede618788fd051fe8327f997ee683388e49/coq/coq-8.3pl5-foundations/theories/Numbers/NatInt/NZDiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.6535407306338792}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Proof of the axioms of choice                                           *\n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibTactics LibLogic LibEpsilon LibRelation.\nGeneralizable Variables A B.\n\n(** This files includes several versions of the axiom of choice.\n    This \"axiom\" is actually proved in terms of indefinite description.\n    Remark: the choice results contained in this file are not very\n    useful in practice since it is usually more convenient to use\n    the epsilon operator directly. *)\n\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Functional choice *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Functional choice *)\n\n(** This result can be used to build a function from a relation that maps\n    every input to at least one output. *)\n\nLemma functional_choice : forall A B (R:A->B->Prop),\n  (forall x, exists y, R x y) -> \n  (exists f, forall x, R x (f x)).\nProof using.\n  intros. exists (fun x => sig_val (indefinite_description (H x))).\n  intro x. apply (sig_proof (indefinite_description (H x))).\nQed.\n(* --LATER: the premise is called [defined] in LibRelation *)\n(* --LATER: functionality -> definedness? *)\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Dependent functional choice *)\n\n(** It is a generalization of functional choice to dependent functions. *)\n\nScheme and_indd := Induction for and Sort Prop.\nScheme eq_indd := Induction for eq Sort Prop.\n\nLemma dependent_functional_choice :\n  forall A (B:A->Type) (R:forall x, B x -> Prop),\n  (forall x, exists y, R x y) ->\n  (exists f, forall x, R x (f x)).\nProof using.\n  introv H.\n  pose (B' := { x:A & B x }).\n  pose (R' := fun (x:A) (y:B') => projT1 y = x /\\ R (projT1 y) (projT2 y)).\n  destruct (functional_choice R') as (f,Hf).\n    intros x. destruct (H x) as (y,Hy).\n     exists (existT (fun x => B x) x y). split~.\n  sets proj1_transparent: (fun P Q (p:P/\\Q) => let (a,b) := p in a).\n  exists (fun x => eq_rect _ _ (projT2 (f x)) _ (proj1_transparent _ _ (Hf x))).\n  intros x. destruct (Hf x) as (Heq,HR) using and_indd.\n  destruct (f x). simpls. destruct Heq using eq_indd. apply HR.\nQed.\n\nArguments dependent_functional_choice [A] [B].\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Guarded functional choice *)\n\n(** Similar to functional choice, except that it targets partial functions *)\n\nLemma guarded_functional_choice : forall A `{Inhab B} (P : A->Prop) (R : A->B->Prop),\n  (forall x, P x -> exists y, R x y) ->\n  (exists f, forall x, P x -> R x (f x)).\nProof using.\n  intros. apply (functional_choice (fun x y => P x -> R x y)).\n  intros. apply~ indep_general_premises.\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Omniscient functional choice *)\n\n(** Similar to functional choice except that the proof of functionality\n    of the relation is given after the fact, for each argument. *)\n\nLemma omniscient_functional_choice : forall A `{Inhab B} (R : A->B->Prop),\n  exists f, forall x, (exists y, R x y) -> R x (f x).\nProof using. intros. apply~ guarded_functional_choice. Qed.\n\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Functional unique choice *)\n\n(** This section provides a similar set of results excepts that it is\n    specialized for the case where each argument has a unique image. *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Functional unique choice *)\n\nLemma functional_unique_choice : forall A B (R:A->B->Prop),\n  (forall x , exists! y, R x y) ->\n  (exists! f, forall x, R x (f x)).\nProof using.\n  intros. destruct (functional_choice R) as [f Hf].\n  intros. apply (ex_of_ex_unique (H x)).\n  exists f. split. auto.\n   intros g Hg. apply fun_ext_1. intros y.\n   apply~ (at_most_one_of_ex_unique (H y)).\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Dependent functional unique choice *)\n\nTheorem dependent_functional_unique_choice :\n  forall (A:Type) (B:A->Type) (R:forall (x:A), B x -> Prop),\n  (forall (x:A), exists! y : B x, R x y) ->\n  (exists! f : (forall (x:A), B x), forall (x:A), R x (f x)).\nProof using.\n  intros. destruct (dependent_functional_choice R) as [f Hf].\n  intros. apply (ex_of_ex_unique (H x)).\n  exists f. split. auto.\n   intros g Hg. extens. intros y.\n   apply~ (at_most_one_of_ex_unique (H y)).\n Qed.\n\nArguments dependent_functional_unique_choice [A] [B].\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Guarded functional unique choice *)\n\nLemma guarded_functional_unique_choice :\n  forall A `{Inhab B} (P : A->Prop) (R : A->B->Prop),\n  (forall x, P x -> exists! y, R x y) ->\n  (exists f, forall x, P x -> R x (f x)).\nProof using.\n  introv I M. apply (functional_choice (fun x y => P x -> R x y)).\n  intros. apply indep_general_premises.\n  introv H. destruct* (M _ H) as (y&Hy&_).\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Omniscient functional unique choice *)\n\nLemma omniscient_functional_unique_choice :\n  forall A `{Inhab B} (R : A->B->Prop),\n  exists f, forall x, (exists! y, R x y) -> R x (f x).\nProof using.\n  intros. destruct (omniscient_functional_choice R) as [f F].\n  exists f. introv (y&Hy&Uy). autos*.\nQed.\n\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Relational choice *)\n\n(** Relational choice can be used to extract from a relation a subrelation\n    that describes a function, by mapping every argument to a unique image. *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Relational choice *)\n\nLemma rel_choice : forall A B (R:A->B->Prop),\n  (forall x, exists y, R x y) ->\n  (exists R', rel_incl R' R\n           /\\ forall x, exists! y, R' x y).\nProof using.\n  introv H. destruct~ (functional_choice R) as [f Hf].\n  exists (fun x y => f x = y). split.\n    introv E. simpls. subst~.\n    intros x. exists~ (f x).\nQed.\n\n(* --TODO: Dependent relational choice, is it meaningful?, useful? *)\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Guarded relational choice *)\n\nLemma guarded_rel_choice : forall A B (P : A->Prop) (R : A->B->Prop),\n  (forall x, P x -> exists y, R x y) ->\n  (exists R', rel_incl R' R\n           /\\ forall x, P x -> exists! y, R' x y).\nProof using.\n  intros. destruct (rel_choice (fun (x:sig P) (y:B) => R (sig_val x) y))\n   as (R',(HR'R,M)).\n    intros (x,HPx). destruct (H _ HPx) as (y,HRxy). exists~ y.\n  set (R'' := fun (x:A) (y:B) => exists (H : P x), R' (exist P x H) y).\n  exists R''. split.\n    intros x y (HPx,HR'xy). apply (HR'R _ _ HR'xy).\n    intros x HPx. destruct (M (exist P x HPx)) as (y,(HR'xy,Uniq)).\n     exists y. split.\n       exists~ HPx.\n       intros y' (H'Px,HR'xy'). apply Uniq.\n        rewrite~ (proof_irrelevance HPx H'Px).\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Omniscient relation choice *)\n\nLemma omniscient_rel_choice : forall A B (R : A->B->Prop),\n  exists R', rel_incl R' R\n          /\\ forall x, (exists y, R x y) -> (exists! y, R' x y).\nProof using. intros. apply~ guarded_rel_choice. Qed.\n\n\n\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/LibChoice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6535001438484316}}
{"text": "\nLemma NotnotP_andP : (forall (P : Prop), ~(~P /\\ ~~P)).\nProof.\n  intros.\n  easy.\nQed.\n\nTheorem modDeMorgan_imply_TE : (forall (P Q : Prop), ~(~P /\\ ~Q) -> P \\/ Q) \n                               -> (forall (P : Prop), P \\/ ~ P).\nProof.\n  intros.\n  apply H.\n  apply NotnotP_andP.\nQed.\n\nTheorem TE_imply_modDN : (forall (P : Prop), P \\/ ~P)\n                         -> forall (P : Prop), (~P -> P) -> P.\nProof.\n  intros.\n  destruct (H P).\n  + easy.\n  + apply H0.\n    apply H1.\nQed.\n\n<<<<<<< HEAD\n(* En coq, not P = p -> false *)\n=======\nTheorem modDN_imply_Pierce : (forall (P : Prop), (~P -> P) -> P)\n                             -> (forall (P Q : Prop), ((P -> Q) -> P) -> P).\nProof.\n  intros.\n  \nQed.\n>>>>>>> 00e85d079641e974cef87d45fe3b169c1e270f46\n", "meta": {"author": "Adrien987k", "repo": "Coq", "sha": "bc35b10c27f630bcb9b33c46ee934928f9931d7f", "save_path": "github-repos/coq/Adrien987k-Coq", "path": "github-repos/coq/Adrien987k-Coq/Coq-bc35b10c27f630bcb9b33c46ee934928f9931d7f/projet_temp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6535001392300329}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) : natural := Succ x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_91_mult_succ/goal33conj66_coqofml_uElLic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.653464278596126}}
{"text": "(**\nHere we interpret HIT signatures in the category of setoids.\n *)\nRequire Import prelude.all.\nRequire Import syntax.hit_signature.\nRequire Import setoids.base.\nRequire Import setoids.setoid_category.\n\nRequire Import algebras.univalent_algebra.\nRequire Import algebras.set_algebra.\n\nOpen Scope cat.\n\n(**\nAction of polynomials on equivalence relations.\n *)\nDefinition poly_eq_rel\n           (P : poly_code)\n           (X : setoid)\n  : eqrel (⦃ P ⦄ (carrier X)).\nProof.\n  induction P as [T | | P₁ IHP₁ P₂ IHP₂ | P₁ IHP₁ P₂ IHP₂].\n  - exact (path_rel T).\n  - exact (carrier_eq X).\n  - exact (sum_rel IHP₁ IHP₂).\n  - exact (prod_rel IHP₁ IHP₂).\nDefined.\n\n(**\nAction of polynomials on setoids\n *)\nDefinition setoid_poly_obj\n           (P : poly_code)\n           (X : setoid)\n  : setoid.\nProof.\n  use make_setoid.\n  - exact (⦃ P ⦄ (carrier X)).\n  - exact (poly_eq_rel P X).\nDefined.\n\n(**\nThis gives rises to a functor\n *)\nDefinition setoid_poly_mor\n           (P : poly_code)\n           {X Y : setoid_cat}\n           (f : X --> Y)\n  : setoid_poly_obj P X → setoid_poly_obj P Y\n  := #⦃ P ⦄ (map_carrier f).\n\nDefinition setoid_poly_mor_is_morphism\n           (P : poly_code)\n           {X Y : setoid_cat}\n           (f : X --> Y)\n           {x y : setoid_poly_obj P X}\n           (p : x ≡ y)\n  : setoid_poly_mor P f x ≡ setoid_poly_mor P f y.\nProof.\n  induction P as [T | | P₁ IHP₁ P₂ IHP₂ | P₁ IHP₁ P₂ IHP₂].\n  - exact p.\n  - exact (map_eq f p).\n  - induction x as [x | x], y as [y | y].\n    + exact (IHP₁ _ _ p).\n    + exact (fromempty p).\n    + exact (fromempty p).\n    + exact (IHP₂ _ _ p).\n  - exact (IHP₁ _ _ (pr1 p) ,, IHP₂ _ _ (pr2 p)).\nQed.\n\nDefinition setoid_poly_data\n           (P : poly_code)\n  : functor_data setoid_cat setoid_cat.\nProof.\n  use make_functor_data.\n  - exact (setoid_poly_obj P).\n  - intros X Y f.\n    use make_setoid_morphism.\n    + exact (setoid_poly_mor P f).\n    + exact (@setoid_poly_mor_is_morphism P _ _ f).\nDefined.\n\nDefinition setoid_poly_is_functor\n           (P : poly_code)\n  : is_functor (setoid_poly_data P).\nProof.\n  split.\n  - intros X.\n    use setoid_morphism_eq.\n    intros x ; cbn.\n    induction P as [T | | P₁ IHP₁ P₂ IHP₂ | P₁ IHP₁ P₂ IHP₂].\n    + reflexivity.\n    + reflexivity.\n    + induction x as [x | x].\n      * exact (maponpaths inl (IHP₁ x)).\n      * exact (maponpaths inr (IHP₂ x)).\n    + apply pathsdirprod.\n      * exact (IHP₁ (pr1 x)).\n      * exact (IHP₂ (pr2 x)).\n  - intros X Y Z f g.\n    use setoid_morphism_eq.\n    intros x ; cbn.\n    induction P as [T | | P₁ IHP₁ P₂ IHP₂ | P₁ IHP₁ P₂ IHP₂].\n    + reflexivity.\n    + reflexivity.\n    + induction x as [x | x].\n      * exact (maponpaths inl (IHP₁ x)).\n      * exact (maponpaths inr (IHP₂ x)).\n    + apply pathsdirprod.\n      * exact (IHP₁ (pr1 x)).\n      * exact (IHP₂ (pr2 x)).\nQed.\n\nDefinition setoid_poly\n           (P : poly_code)\n  : setoid_cat ⟶ setoid_cat.\nProof.\n  use make_functor.\n  - exact (setoid_poly_data P).\n  - exact (setoid_poly_is_functor P).\nDefined.\n\nNotation \"⟨ P ⟩\" := (setoid_poly P) (at level 10). (* \\< \\>} *)\nNotation \"⟨ P ⟩ X\" := (setoid_poly P X : setoid) (at level 10).\nNotation \"# ⟨ P ⟩\" := (#(setoid_poly P)) (at level 10).\n\n(**\nUnivalent category of setoid prealgebras\n *)\nDefinition setoid_prealgebras\n           (P : poly_code)\n  : univalent_category.\nProof.\n  use make_univalent_category.\n  - exact (FunctorAlg (⟨ P ⟩)).\n  - apply is_univalent_FunctorAlg.\n    apply setoid_cat_is_univalent.\nDefined.\n\n(**\nThe carrier of a setoid prealgebra is a set prealgebra\n *)\nDefinition setoid_prealgebra_to_set_prealgebra\n           (P : poly_code)\n  : setoid_prealgebras P → set_prealgebras P.\nProof.\n  intros X.\n  use tpair.\n  - exact (pr11 X).\n  - exact (pr12 X).\nDefined.\n\n(**\nForgetful functor of setoid prealgebras\n *)\nDefinition prealgebra_setoid\n           (P : poly_code)\n  : setoid_prealgebras P ⟶ setoid_cat\n  := forget_algebras _.\n\n(**\nInterpretation of endpoins\n *)\nDefinition setoid_endpoint\n           {A P Q : poly_code}\n           (e : endpoint A P Q)\n           (X : setoid_prealgebras A)\n  : setoid_cat ⟦ ⟨ P ⟩ (pr1 X) , ⟨ Q ⟩ (pr1 X) ⟧.\nProof.\n  use make_setoid_morphism.\n  - exact (set_endpoint e (setoid_prealgebra_to_set_prealgebra A X)).\n  - intros x y p.\n    induction e.\n    + exact p.\n    + exact (IHe2 _ _ (IHe1 _ _ p)).\n    + exact p.\n    + exact p.\n    + exact (pr1 p).\n    + exact (pr2 p).\n    + split.\n      * exact (IHe1 _ _ p).\n      * exact (IHe2 _ _ p).\n    + reflexivity.\n    + exact (maponpaths f p).\n    + exact (map_eq _ p).\nDefined.\n\n(**\nDefinition of algebras of HIT signatures in setoids\n *)\nDefinition is_setoid_algebra\n           (Σ : hit_signature)\n  : hsubtype (setoid_prealgebras (point_arg Σ)).\nProof.\n  intro X.\n  refine (∀ (j : path_index Σ)\n            (x : ⟨ path_arg Σ j ⟩ (prealgebra_setoid _ X)),\n             _).\n  simple refine (make_hProp _ _).\n  + exact (\n        (pr1 (setoid_endpoint (path_lhs Σ j) X) x)\n          ≡\n          pr1 (setoid_endpoint (path_rhs Σ j) X) x).\n  + apply isaprop_setoid_eq.\nDefined.\n\n(**\nUnivalent category of setoid algebras\n *)\nDefinition setoid_algebra\n           (Σ : hit_signature)\n  : univalent_category.\nProof.\n  use make_univalent_category.\n  - exact (full_sub_precategory (is_setoid_algebra Σ)).\n  - apply is_univalent_full_subcat.\n    apply univalent_category_is_univalent.\nDefined.\n\n(**\nProjections of algebras\n *)\nSection AlgebraProjections.\n  Context {Σ : hit_signature}.\n  Variable (X : setoid_algebra Σ).\n  \n  Definition alg_to_prealg\n    : setoid_prealgebras (point_arg Σ)\n    := pr1 X.\n\n  Definition alg_carrier\n    : setoid\n    := pr1 alg_to_prealg.\n\n  Definition alg_operation\n    : setoid_cat ⟦ ⟨ point_arg Σ ⟩ alg_carrier , alg_carrier ⟧\n    := pr2 alg_to_prealg.\n\n  Definition alg_paths\n             (j : path_index Σ)\n             (x : ⟨ path_arg Σ j ⟩ alg_carrier)\n    : pr1 (setoid_endpoint (path_lhs Σ j) alg_to_prealg) x\n      ≡\n      pr1 (setoid_endpoint (path_rhs Σ j) alg_to_prealg) x\n    := pr2 X j x.\nEnd AlgebraProjections.\n\n(**\nProjections of algebra maps\n *)\nSection AlgebraMapProjections.\n  Context {Σ : hit_signature}\n          {X Y : setoid_algebra Σ}.\n  Variable (f : X --> Y).\n\n  Definition alg_map_carrier\n    : setoid_morphism (alg_carrier X) (alg_carrier Y)\n    := pr11 f.\n\n  Definition alg_map_is_alg_mor\n    : is_algebra_mor (⟨ point_arg Σ ⟩) (alg_to_prealg X) (alg_to_prealg Y) alg_map_carrier\n    := pr21 f.\nEnd AlgebraMapProjections.\n\n(**\nBuilder\n *)\nDefinition make_prealgebra\n           {P : poly_code}\n           (X : setoid)\n           (c : setoid_cat ⟦ ⟨ P ⟩ X , X ⟧)\n  : setoid_prealgebras P.\nProof.\n  use tpair.\n  - exact X.\n  - exact c.\nDefined.\n           \nDefinition make_algebra\n           {Σ : hit_signature}\n           (X : setoid)\n           (c : setoid_cat ⟦ ⟨ point_arg Σ ⟩ X , X ⟧)\n           (p : ∏ (j : path_index Σ) (x : ⟨ path_arg Σ j ⟩ X),\n                pr1 (setoid_endpoint (path_lhs Σ j) (make_prealgebra X c)) x\n                ≡\n                pr1 (setoid_endpoint (path_rhs Σ j) (make_prealgebra X c)) x)\n  : setoid_algebra Σ.\nProof.\n  use tpair.\n  - exact (make_prealgebra X c).\n  - exact p.\nDefined.\n\nDefinition make_algebra_map\n           {Σ : hit_signature}\n           {X Y : setoid_algebra Σ}\n           (f : setoid_cat ⟦ alg_carrier X , alg_carrier Y ⟧)\n           (p : ∏ (x : ⦃ point_arg Σ ⦄ (pr1 (alg_carrier X))),\n                pr1 f (pr1 (alg_operation X) x)\n                =\n                pr1 (alg_operation Y) (#⦃ point_arg Σ ⦄ (pr1 f) x))\n  : X --> Y.\nProof.\n  use tpair.\n  - use tpair.\n    + exact f.\n    + use setoid_morphism_eq.\n      exact p.\n  - exact tt.\nDefined.\n\n(**\nEquality principle for maps beween algebras\n *)\nDefinition algebra_map_eq\n           {Σ : hit_signature}\n           {X Y : setoid_algebra Σ}\n           {f g : X --> Y}\n           (e : ∏ (x : alg_carrier X), alg_map_carrier f x = alg_map_carrier g x)\n  : f = g.\nProof.\n  use subtypePath.\n  {\n    intro ; exact isapropunit.\n  }\n  use subtypePath.\n  {\n    intro ; simpl.\n    apply setoid_cat.\n  }\n  exact (setoid_morphism_eq _ _ e).\nQed.\n", "meta": {"author": "UniMath", "repo": "SetHITs", "sha": "512f3c76926f458a130786891c2e325e66afeb21", "save_path": "github-repos/coq/UniMath-SetHITs", "path": "github-repos/coq/UniMath-SetHITs/SetHITs-512f3c76926f458a130786891c2e325e66afeb21/code/algebras/setoid_algebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6534642687376554}}
{"text": "(** * StlcProp: Properties of STLC *)\n\nRequire Import SfLib.\nRequire Import Maps.\nRequire Import Types.\nRequire Import Stlc.\nRequire Import Smallstep.\nModule STLCProp.\nImport STLC.\n\n(** In this chapter, we develop the fundamental theory of the Simply\n    Typed Lambda Calculus -- in particular, the type safety\n    theorem. *)\n\n(* ###################################################################### *)\n(** * Canonical Forms *)\n\n(** As we saw for the simple calculus in the [Types] chapter, the\n    first step in establishing basic properties of reduction and types\n    is to identify the possible _canonical forms_ (i.e., well-typed\n    closed values) belonging to each type.  For [Bool], these are the boolean\n    values [ttrue] and [tfalse].  For arrow types, the canonical forms\n    are lambda-abstractions.  *)\n\nLemma canonical_forms_bool : forall t,\n  empty |- t \\in TBool ->\n  value t ->\n  (t = ttrue) \\/ (t = tfalse).\nProof.\n  intros t HT HVal.\n  inversion HVal; intros; subst; try inversion HT; auto.\nQed.\n\nLemma canonical_forms_fun : forall t T1 T2,\n  empty |- t \\in (TArrow T1 T2) ->\n  value t ->\n  exists x u, t = tabs x T1 u.\nProof.\n  intros t T1 T2 HT HVal.\n  inversion HVal; intros; subst; try inversion HT; subst; auto.\n  exists x0. exists t0.  auto.\nQed.\n\n(* ###################################################################### *)\n(** * Progress *)\n\n(** As before, the _progress_ theorem tells us that closed, well-typed\n    terms are not stuck: either a well-typed term is a value, or it\n    can take a reduction step.  The proof is a relatively\n    straightforward extension of the progress proof we saw in the\n    [Types] chapter.  We'll give the proof in English first, then the\n    formal version. *)\n\nTheorem progress : forall t T,\n     empty |- t \\in T ->\n     value t \\/ exists t', t ==> t'.\n\n(** _Proof_: By induction on the derivation of [|- t \\in T].\n\n    - The last rule of the derivation cannot be [T_Var], since a\n      variable is never well typed in an empty context.\n\n    - The [T_True], [T_False], and [T_Abs] cases are trivial, since in\n      each of these cases we can see by inspecting the rule that [t]\n      is a value.\n\n    - If the last rule of the derivation is [T_App], then [t] has the\n      form [t1 t2] for som e[t1] and [t2], where we know that [t1] and\n      [t2] are also well typed in the empty context; in particular,\n      there exists a type [T2] such that [|- t1 \\in T2 -> T] and [|-\n      t2 \\in T2].  By the induction hypothesis, either [t1] is a value\n      or it can take a reduction step.\n\n        - If [t1] is a value, then consider [t2], which by the other\n          induction hypothesis must also either be a value or take a step.\n\n            - Suppose [t2] is a value.  Since [t1] is a value with an\n              arrow type, it must be a lambda abstraction; hence [t1\n              t2] can take a step by [ST_AppAbs].\n\n            - Otherwise, [t2] can take a step, and hence so can [t1\n              t2] by [ST_App2].\n\n        - If [t1] can take a step, then so can [t1 t2] by [ST_App1].\n\n    - If the last rule of the derivation is [T_If], then [t = if t1\n      then t2 else t3], where [t1] has type [Bool].  By the IH, [t1]\n      either is a value or takes a step.\n\n        - If [t1] is a value, then since it has type [Bool] it must be\n          either [true] or [false].  If it is [true], then [t] steps\n          to [t2]; otherwise it steps to [t3].\n\n        - Otherwise, [t1] takes a step, and therefore so does [t] (by\n          [ST_If]). *)\n\nProof with eauto.\n  intros t T Ht.\n  remember (@empty ty) as Gamma.\n  induction Ht; subst Gamma...\n  - (* T_Var *)\n    (* contradictory: variables cannot be typed in an\n       empty context *)\n    inversion H.\n\n  - (* T_App *)\n    (* [t] = [t1 t2].  Proceed by cases on whether [t1] is a\n       value or steps... *)\n    right. destruct IHHt1...\n    + (* t1 is a value *)\n      destruct IHHt2...\n      * (* t2 is also a value *)\n        assert (exists x0 t0, t1 = tabs x0 T11 t0).\n        eapply canonical_forms_fun; eauto.\n        destruct H1 as [x0 [t0 Heq]]. subst.\n        exists ([x0:=t2]t0)...\n\n      * (* t2 steps *)\n        inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...\n\n    + (* t1 steps *)\n      inversion H as [t1' Hstp]. exists (tapp t1' t2)...\n\n  - (* T_If *)\n    right. destruct IHHt1...\n\n    + (* t1 is a value *)\n      destruct (canonical_forms_bool t1); subst; eauto.\n\n    + (* t1 also steps *)\n      inversion H as [t1' Hstp]. exists (tif t1' t2 t3)...\nQed.\n\n(** **** Exercise: 3 stars, optional (progress_from_term_ind)  *)\n(** Show that progress can also be proved by induction on terms\n    instead of induction on typing derivations. *)\n\nTheorem progress' : forall t T,\n     empty |- t \\in T ->\n     value t \\/ exists t', t ==> t'.\nProof.\n  intros t.\n  induction t; intros T Ht; auto.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################################### *)\n(** * Preservation *)\n\n(** The other half of the type soundness property is the preservation\n    of types during reduction.  For this, we need to develop some\n    technical machinery for reasoning about variables and\n    substitution.  Working from top to bottom (from the high-level\n    property we are actually interested in to the lowest-level\n    technical lemmas that are needed by various cases of the more\n    interesting proofs), the story goes like this:\n\n      - The _preservation theorem_ is proved by induction on a typing\n        derivation, pretty much as we did in the [Types] chapter.  The\n        one case that is significantly different is the one for the\n        [ST_AppAbs] rule, whose definition uses the substitution\n        operation.  To see that this step preserves typing, we need to\n        know that the substitution itself does.  So we prove a...\n\n      - _substitution lemma_, stating that substituting a (closed)\n        term [s] for a variable [x] in a term [t] preserves the type\n        of [t].  The proof goes by induction on the form of [t] and\n        requires looking at all the different cases in the definition\n        of substitition.  This time, the tricky cases are the ones for\n        variables and for function abstractions.  In both cases, we\n        discover that we need to take a term [s] that has been shown\n        to be well-typed in some context [Gamma] and consider the same\n        term [s] in a slightly different context [Gamma'].  For this\n        we prove a...\n\n      - _context invariance_ lemma, showing that typing is preserved\n        under \"inessential changes\" to the context [Gamma] -- in\n        particular, changes that do not affect any of the free\n        variables of the term.  And finally, for this, we need a\n        careful definition of...\n\n      - the _free variables_ of a term -- i.e., those variables\n        mentioned in a term and not in the scope of an enclosing\n        function abstraction binding a variable of the same name.\n\n   To make Coq happy, we need to formalize the story in the opposite\n   order... *)\n\n(* ###################################################################### *)\n(** ** Free Occurrences *)\n\n(** A variable [x] _appears free in_ a term _t_ if [t] contains some\n    occurrence of [x] that is not under an abstraction labeled [x].\n    For example:\n      - [y] appears free, but [x] does not, in [\\x:T->U. x y]\n      - both [x] and [y] appear free in [(\\x:T->U. x y) x]\n      - no variables appear free in [\\x:T->U. \\y:T. x y]\n\n    Formally: *)\n\nInductive appears_free_in : id -> tm -> Prop :=\n  | afi_var : forall x,\n      appears_free_in x (tvar x)\n  | afi_app1 : forall x t1 t2,\n      appears_free_in x t1 -> appears_free_in x (tapp t1 t2)\n  | afi_app2 : forall x t1 t2,\n      appears_free_in x t2 -> appears_free_in x (tapp t1 t2)\n  | afi_abs : forall x y T11 t12,\n      y <> x  ->\n      appears_free_in x t12 ->\n      appears_free_in x (tabs y T11 t12)\n  | afi_if1 : forall x t1 t2 t3,\n      appears_free_in x t1 ->\n      appears_free_in x (tif t1 t2 t3)\n  | afi_if2 : forall x t1 t2 t3,\n      appears_free_in x t2 ->\n      appears_free_in x (tif t1 t2 t3)\n  | afi_if3 : forall x t1 t2 t3,\n      appears_free_in x t3 ->\n      appears_free_in x (tif t1 t2 t3).\n\nHint Constructors appears_free_in.\n\n(** A term in which no variables appear free is said to be _closed_. *)\n\nDefinition closed (t:tm) :=\n  forall x, ~ appears_free_in x t.\n\n(** **** Exercise: 1 star (afi)  *)\n(** If the definition of [appears_free_in] is not crystal clear to\n    you, it is a good idea to take a piece of paper and write out the\n    rules in informal inference-rule notation.  (Although it is a\n    rather low-level, technical definition, understanding it is\n    crucial to understanding substitution and its properties, which\n    are really the crux of the lambda-calculus.) *)\n(** [] *)\n\n(* ###################################################################### *)\n(** ** Substitution *)\n\n(** To prove that substitution preserves typing, we first need a\n    technical lemma connecting free variables and typing contexts: If\n    a variable [x] appears free in a term [t], and if we know [t] is\n    well typed in context [Gamma], then it must be the case that\n    [Gamma] assigns a type to [x]. *)\n\nLemma free_in_context : forall x t T Gamma,\n   appears_free_in x t ->\n   Gamma |- t \\in T ->\n   exists T', Gamma x = Some T'.\n\n(** _Proof_: We show, by induction on the proof that [x] appears\n      free in [t], that, for all contexts [Gamma], if [t] is well\n      typed under [Gamma], then [Gamma] assigns some type to [x].\n\n      - If the last rule used was [afi_var], then [t = x], and from\n        the assumption that [t] is well typed under [Gamma] we have\n        immediately that [Gamma] assigns a type to [x].\n\n      - If the last rule used was [afi_app1], then [t = t1 t2] and [x]\n        appears free in [t1].  Since [t] is well typed under [Gamma],\n        we can see from the typing rules that [t1] must also be, and\n        the IH then tells us that [Gamma] assigns [x] a type.\n\n      - Almost all the other cases are similar: [x] appears free in a\n        subterm of [t], and since [t] is well typed under [Gamma], we\n        know the subterm of [t] in which [x] appears is well typed\n        under [Gamma] as well, and the IH gives us exactly the\n        conclusion we want.\n\n      - The only remaining case is [afi_abs].  In this case [t =\n        \\y:T11.t12], and [x] appears free in [t12]; we also know that\n        [x] is different from [y].  The difference from the previous\n        cases is that whereas [t] is well typed under [Gamma], its\n        body [t12] is well typed under [(Gamma, y:T11)], so the IH\n        allows us to conclude that [x] is assigned some type by the\n        extended context [(Gamma, y:T11)].  To conclude that [Gamma]\n        assigns a type to [x], we appeal to lemma [update_neq], noting\n        that [x] and [y] are different variables. *)\n\nProof.\n  intros x t T Gamma H H0. generalize dependent Gamma.\n  generalize dependent T.\n  induction H;\n         intros; try solve [inversion H0; eauto].\n  - (* afi_abs *)\n    inversion H1; subst.\n    apply IHappears_free_in in H7.\n    rewrite update_neq in H7; assumption.\nQed.\n\n(** Next, we'll need the fact that any term [t] which is well typed in\n    the empty context is closed (it has no free variables). *)\n\n(** **** Exercise: 2 stars, optional (typable_empty__closed)  *)\nCorollary typable_empty__closed : forall t T,\n    empty |- t \\in T  ->\n    closed t.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Sometimes, when we have a proof [Gamma |- t : T], we will need to\n    replace [Gamma] by a different context [Gamma'].  When is it safe\n    to do this?  Intuitively, it must at least be the case that\n    [Gamma'] assigns the same types as [Gamma] to all the variables\n    that appear free in [t]. In fact, this is the only condition that\n    is needed. *)\n\nLemma context_invariance : forall Gamma Gamma' t T,\n     Gamma |- t \\in T  ->\n     (forall x, appears_free_in x t -> Gamma x = Gamma' x) ->\n     Gamma' |- t \\in T.\n\n(** _Proof_: By induction on the derivation of \n    [Gamma |- t \\in T].\n\n      - If the last rule in the derivation was [T_Var], then [t = x]\n        and [Gamma x = T].  By assumption, [Gamma' x = T] as well, and\n        hence [Gamma' |- t \\in T] by [T_Var].\n\n      - If the last rule was [T_Abs], then [t = \\y:T11. t12], with [T\n        = T11 -> T12] and [Gamma, y:T11 |- t12 \\in T12].  The\n        induction hypothesis is that, for any context [Gamma''], if\n        [Gamma, y:T11] and [Gamma''] assign the same types to all the\n        free variables in [t12], then [t12] has type [T12] under\n        [Gamma''].  Let [Gamma'] be a context which agrees with\n        [Gamma] on the free variables in [t]; we must show [Gamma' |-\n        \\y:T11. t12 \\in T11 -> T12].\n\n        By [T_Abs], it suffices to show that [Gamma', y:T11 |- t12 \\in\n        T12].  By the IH (setting [Gamma'' = Gamma', y:T11]), it\n        suffices to show that [Gamma, y:T11] and [Gamma', y:T11] agree\n        on all the variables that appear free in [t12].\n\n        Any variable occurring free in [t12] must be either [y] or\n        some other variable.  [Gamma, y:T11] and [Gamma', y:T11]\n        clearly agree on [y].  Otherwise, note that any variable other\n        than [y] that occurs free in [t12] also occurs free in [t =\n        \\y:T11. t12], and by assumption [Gamma] and [Gamma'] agree on\n        all such variables; hence so do [Gamma, y:T11] and [Gamma',\n        y:T11].\n\n      - If the last rule was [T_App], then [t = t1 t2], with [Gamma |-\n        t1 \\in T2 -> T] and [Gamma |- t2 \\in T2].  One induction\n        hypothesis states that for all contexts [Gamma'], if [Gamma']\n        agrees with [Gamma] on the free variables in [t1], then [t1]\n        has type [T2 -> T] under [Gamma']; there is a similar IH for\n        [t2].  We must show that [t1 t2] also has type [T] under\n        [Gamma'], given the assumption that [Gamma'] agrees with\n        [Gamma] on all the free variables in [t1 t2].  By [T_App], it\n        suffices to show that [t1] and [t2] each have the same type\n        under [Gamma'] as under [Gamma].  But all free variables in\n        [t1] are also free in [t1 t2], and similarly for [t2]; hence\n        the desired result follows from the induction hypotheses. *)\n\nProof with eauto.\n  intros.\n  generalize dependent Gamma'.\n  induction H; intros; auto.\n  - (* T_Var *)\n    apply T_Var. rewrite <- H0...\n  - (* T_Abs *)\n    apply T_Abs.\n    apply IHhas_type. intros x1 Hafi.\n    (* the only tricky step... the [Gamma'] we use to\n       instantiate is [update Gamma x T11] *)\n    unfold update. unfold t_update. destruct (beq_id x0 x1) eqn: Hx0x1...\n    rewrite beq_id_false_iff in Hx0x1. auto.\n  - (* T_App *)\n    apply T_App with T11...\nQed.\n\n(** Now we come to the conceptual heart of the proof that reduction\n    preserves types -- namely, the observation that _substitution_\n    preserves types.\n\n    Formally, the so-called _Substitution Lemma_ says this: Suppose we\n    have a term [t] with a free variable [x], and suppose we've been\n    able to assign a type [T] to [t] under the assumption that [x] has\n    some type [U].  Also, suppose that we have some other term [v] and\n    that we've shown that [v] has type [U].  Then, since [v] satisfies\n    the assumption we made about [x] when typing [t], we should be\n    able to substitute [v] for each of the occurrences of [x] in [t]\n    and obtain a new term that still has type [T]. *)\n\n(** _Lemma_: If [Gamma,x:U |- t \\in T] and [|- v \\in U], then [Gamma |-\n    [x:=v]t \\in T]. *)\n\nLemma substitution_preserves_typing : forall Gamma x U t v T,\n     update Gamma x U |- t \\in T ->\n     empty |- v \\in U   ->\n     Gamma |- [x:=v]t \\in T.\n\n(** One technical subtlety in the statement of the lemma is that\n    we assign [v] the type [U] in the _empty_ context -- in other\n    words, we assume [v] is closed.  This assumption considerably\n    simplifies the [T_Abs] case of the proof (compared to assuming\n    [Gamma |- v \\in U], which would be the other reasonable assumption\n    at this point) because the context invariance lemma then tells us\n    that [v] has type [U] in any context at all -- we don't have to\n    worry about free variables in [v] clashing with the variable being\n    introduced into the context by [T_Abs].\n\n    The substitution lemma can be viewed as a kind of \"commutation\"\n    property.  Intuitively, it says that substitution and typing can\n    be done in either order: we can either assign types to the terms\n    [t] and [v] separately (under suitable contexts) and then combine\n    them using substitution, or we can substitute first and then\n    assign a type to [ [x:=v] t ] -- the result is the same either\n    way.\n\n    _Proof_: We show, by induction on [t], that for all [T] and\n    [Gamma], if [Gamma,x:U |- t \\in T] and [|- v \\in U], then [Gamma\n    |- [x:=v]t \\in T].\n\n      - If [t] is a variable there are two cases to consider,\n        depending on whether [t] is [x] or some other variable.\n\n          - If [t = x], then from the fact that [Gamma, x:U |- x \\in\n            T] we conclude that [U = T].  We must show that [[x:=v]x =\n            v] has type [T] under [Gamma], given the assumption that\n            [v] has type [U = T] under the empty context.  This\n            follows from context invariance: if a closed term has type\n            [T] in the empty context, it has that type in any context.\n\n          - If [t] is some variable [y] that is not equal to [x], then\n            we need only note that [y] has the same type under [Gamma,\n            x:U] as under [Gamma].\n\n      - If [t] is an abstraction [\\y:T11. t12], then the IH tells us,\n        for all [Gamma'] and [T'], that if [Gamma',x:U |- t12 \\in T']\n        and [|- v \\in U], then [Gamma' |- [x:=v]t12 \\in T'].\n\n        The substitution in the conclusion behaves differently\n        depending on whether [x] and [y] are the same variable.\n\n        First, suppose [x = y].  Then, by the definition of\n        substitution, [[x:=v]t = t], so we just need to show [Gamma |-\n        t \\in T].  But we know [Gamma,x:U |- t : T], and, since [y]\n        does not appear free in [\\y:T11. t12], the context invariance\n        lemma yields [Gamma |- t \\in T].\n\n        Second, suppose [x <> y].  We know [Gamma,x:U,y:T11 |- t12 \\in\n        T12] by inversion of the typing relation, from which\n        [Gamma,y:T11,x:U |- t12 \\in T12] follows by the context\n        invariance lemma, so the IH applies, giving us [Gamma,y:T11 |-\n        [x:=v]t12 \\in T12].  By [T_Abs], [Gamma |- \\y:T11. [x:=v]t12\n        \\in T11->T12], and by the definition of substitution (noting\n        that [x <> y]), [Gamma |- \\y:T11. [x:=v]t12 \\in T11->T12] as\n        required.\n\n      - If [t] is an application [t1 t2], the result follows\n        straightforwardly from the definition of substitution and the\n        induction hypotheses.\n\n      - The remaining cases are similar to the application case.\n\n    One more technical note: This proof is a rare case where an\n    induction on terms, rather than typing derivations, yields a\n    simpler argument.  The reason for this is that the assumption\n    [update Gamma x U |- t \\in T] is not completely generic, in the\n    sense that one of the \"slots\" in the typing relation -- namely the\n    context -- is not just a variable, and this means that Coq's\n    native induction tactic does not give us the induction hypothesis\n    that we want.  It is possible to work around this, but the needed\n    generalization is a little tricky.  The term [t], on the other\n    hand, _is_ completely generic. *)\n\nProof with eauto.\n  intros Gamma x U t v T Ht Ht'.\n  generalize dependent Gamma. generalize dependent T.\n  induction t; intros T Gamma H;\n    (* in each case, we'll want to get at the derivation of H *)\n    inversion H; subst; simpl...\n  - (* tvar *)\n    rename i into y. destruct (beq_idP x y) as [Hxy|Hxy].\n    + (* x=y *)\n      subst.\n      rewrite update_eq in H2.\n      inversion H2; subst. clear H2.\n                  eapply context_invariance... intros x Hcontra.\n      destruct (free_in_context _ _ T empty Hcontra) as [T' HT']...\n      inversion HT'.\n    + (* x<>y *)\n      apply T_Var. rewrite update_neq in H2...\n  - (* tabs *)\n    rename i into y. apply T_Abs.\n    destruct (beq_idP x y) as [Hxy | Hxy].\n    + (* x=y *)\n      subst.\n      eapply context_invariance...\n      intros x Hafi. unfold update, t_update.\n      destruct (beq_id y x) eqn: Hyx...\n    + (* x<>y *)\n      apply IHt. eapply context_invariance...\n      intros z Hafi. unfold update, t_update.\n      destruct (beq_idP y z) as [Hyz | Hyz]; subst; trivial.\n      rewrite <- beq_id_false_iff in Hxy.\n      rewrite Hxy...\nQed.\n\n(* ###################################################################### *)\n(** ** Main Theorem *)\n\n(** We now have the tools we need to prove preservation: if a closed\n    term [t] has type [T] and takes a step to [t'], then [t']\n    is also a closed term with type [T].  In other words, the small-step\n    reduction relation preserves types. *)\n\nTheorem preservation : forall t t' T,\n     empty |- t \\in T  ->\n     t ==> t'  ->\n     empty |- t' \\in T.\n\n(** _Proof_: By induction on the derivation of [|- t \\in T].\n\n    - We can immediately rule out [T_Var], [T_Abs], [T_True], and\n      [T_False] as the final rules in the derivation, since in each of\n      these cases [t] cannot take a step.\n\n    - If the last rule in the derivation was [T_App], then [t = t1\n      t2].  There are three cases to consider, one for each rule that\n      could have been used to show that [t1 t2] takes a step to [t'].\n\n        - If [t1 t2] takes a step by [ST_App1], with [t1] stepping to\n          [t1'], then by the IH [t1'] has the same type as [t1], and\n          hence [t1' t2] has the same type as [t1 t2].\n\n        - The [ST_App2] case is similar.\n\n        - If [t1 t2] takes a step by [ST_AppAbs], then [t1 =\n          \\x:T11.t12] and [t1 t2] steps to [[x:=t2]t12]; the\n          desired result now follows from the fact that substitution\n          preserves types.\n\n    - If the last rule in the derivation was [T_If], then [t = if t1\n      then t2 else t3], and there are again three cases depending on\n      how [t] steps.\n\n        - If [t] steps to [t2] or [t3], the result is immediate, since\n          [t2] and [t3] have the same type as [t].\n\n        - Otherwise, [t] steps by [ST_If], and the desired conclusion\n          follows directly from the induction hypothesis. *)\n\nProof with eauto.\n  remember (@empty ty) as Gamma.\n  intros t t' T HT. generalize dependent t'.\n  induction HT;\n       intros t' HE; subst Gamma; subst;\n       try solve [inversion HE; subst; auto].\n  - (* T_App *)\n    inversion HE; subst...\n    (* Most of the cases are immediate by induction,\n       and [eauto] takes care of them *)\n    + (* ST_AppAbs *)\n      apply substitution_preserves_typing with T11...\n      inversion HT1...\nQed.\n\n(** **** Exercise: 2 stars, recommended (subject_expansion_stlc)  *)\n(** An exercise in the [Types] chapter asked about the subject\n    expansion property for the simple language of arithmetic and\n    boolean expressions.  Does this property hold for STLC?  That is,\n    is it always the case that, if [t ==> t'] and [has_type t' T],\n    then [empty |- t \\in T]?  If so, prove it.  If not, give a\n    counter-example not involving conditionals.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(* ###################################################################### *)\n(** * Type Soundness *)\n\n(** **** Exercise: 2 stars, optional (type_soundness)  *)\n(** Put progress and preservation together and show that a well-typed\n    term can _never_ reach a stuck state.  *)\n\nDefinition stuck (t:tm) : Prop :=\n  (normal_form step) t /\\ ~ value t.\n\nCorollary soundness : forall t t' T,\n  empty |- t \\in T ->\n  t ==>* t' ->\n  ~(stuck t').\nProof.\n  intros t t' T Hhas_type Hmulti. unfold stuck.\n  intros [Hnf Hnot_val]. unfold normal_form in Hnf.\n  induction Hmulti.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################################### *)\n(** * Uniqueness of Types *)\n\n(** **** Exercise: 3 stars (types_unique)  *)\n(** Another nice property of the STLC is that types are unique: a\n    given term (in a given context) has at most one type. *)\n(** Formalize this statement and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ###################################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 1 star (progress_preservation_statement)  *)\n(** Without peeking at their statements above, write down the progress\n    and preservation theorems for the simply typed lambda-calculus. *)\n(** [] *)\n\n(** **** Exercise: 2 stars (stlc_variation1)  *)\n(** Suppose we add a new term [zap] with the following reduction rule\n\n                         ---------                  (ST_Zap)\n                         t ==> zap\n\nand the following typing rule:\n\n                      ----------------               (T_Zap)\n                      Gamma |- zap : T\n\n    Which of the following properties of the STLC remain true in\n    the presence of these rules?  For each property, write either\n    \"remains true\" or \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n[]\n*)\n\n(** **** Exercise: 2 stars (stlc_variation2)  *)\n(** Suppose instead that we add a new term [foo] with the following \n    reduction rules:\n\n                       -----------------                (ST_Foo1)\n                       (\\x:A. x) ==> foo\n\n                         ------------                   (ST_Foo2)\n                         foo ==> true\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n[]\n*)\n\n(** **** Exercise: 2 stars (stlc_variation3)  *)\n(** Suppose instead that we remove the rule [ST_App1] from the [step]\n    relation. Which of the following properties of the STLC remain\n    true in the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation4)  *)\n(** Suppose instead that we add the following new rule to the \n    reduction relation:\n\n            ----------------------------------        (ST_FunnyIfTrue)\n            (if true then t1 else t2) ==> true\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation5)  *)\n(** Suppose instead that we add the following new rule to the typing \n    relation:\n\n                 Gamma |- t1 \\in Bool->Bool->Bool\n                     Gamma |- t2 \\in Bool\n                 ------------------------------          (T_FunnyApp)\n                    Gamma |- t1 t2 \\in Bool\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation6)  *)\n(** Suppose instead that we add the following new rule to the typing \n    relation:\n\n                     Gamma |- t1 \\in Bool\n                     Gamma |- t2 \\in Bool\n                    ---------------------               (T_FunnyApp')\n                    Gamma |- t1 t2 \\in Bool\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n*)\n\n(** **** Exercise: 2 stars, optional (stlc_variation7)  *)\n(** Suppose we add the following new rule to the typing relation \n    of the STLC:\n\n                         ------------------- (T_FunnyAbs)\n                         |- \\x:Bool.t \\in Bool\n\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n[]\n*)\n\nEnd STLCProp.\n\n(* ###################################################################### *)\n(* ###################################################################### *)\n(** ** Exercise: STLC with Arithmetic *)\n\n(** To see how the STLC might function as the core of a real\n    programming language, let's extend it with a concrete base\n    type of numbers and some constants and primitive\n    operators. *)\n\nModule STLCArith.\n\n(** To types, we add a base type of natural numbers (and remove\n    booleans, for brevity). *)\n\nInductive ty : Type :=\n  | TArrow : ty -> ty -> ty\n  | TNat   : ty.\n\n(** To terms, we add natural number constants, along with\n    successor, predecessor, multiplication, and zero-testing. *)\n\nInductive tm : Type :=\n  | tvar : id -> tm\n  | tapp : tm -> tm -> tm\n  | tabs : id -> ty -> tm -> tm\n  | tnat  : nat -> tm\n  | tsucc : tm -> tm\n  | tpred : tm -> tm\n  | tmult : tm -> tm -> tm\n  | tif0  : tm -> tm -> tm -> tm.\n\n(** **** Exercise: 4 stars (stlc_arith)  *)\n(** Finish formalizing the definition and properties of the STLC extended\n    with arithmetic.  Specifically:\n\n    - Copy the whole development of STLC that we went through above (from\n      the definition of values through the Type Soundness theorem), and\n      paste it into the file at this point.\n\n    - Extend the definitions of the [subst] operation and the [step]\n      relation to include appropriate clauses for the arithmetic operators.\n\n    - Extend the proofs of all the properties (up to [soundness]) of\n      the original STLC to deal with the new syntactic forms.  Make\n      sure Coq accepts the whole file. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd STLCArith.\n\n(** $Date: 2016-05-26 16:17:19 -0400 (Thu, 26 May 2016) $ *)\n\n", "meta": {"author": "colinmccabe", "repo": "software-foundations", "sha": "d581e89d47978ed9acc9e2a64ba6209a614fd9f1", "save_path": "github-repos/coq/colinmccabe-software-foundations", "path": "github-repos/coq/colinmccabe-software-foundations/software-foundations-d581e89d47978ed9acc9e2a64ba6209a614fd9f1/StlcProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220786, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.653464261194103}}
{"text": "(** * Maps: Total and Partial Maps *)\n\n(** _Maps_ (or _dictionaries_) are ubiquitous data structures both\n    generally and in the theory of programming languages in\n    particular; we're going to need them in many places in the coming\n    chapters.  They also make a nice case study using ideas we've seen\n    in previous chapters, including building data structures out of\n    higher-order functions (from [Basics] and [Poly]) and the use of\n    reflection to streamline proofs (from [IndProp]).\n\n    We'll define two flavors of maps: _total_ maps, which include a\n    \"default\" element to be returned when a key being looked up\n    doesn't exist, and _partial_ maps, which return an [option] to\n    indicate success or failure.  The latter is defined in terms of\n    the former, using [None] as the default element. *)\n\n(* ################################################################# *)\n(** * The Coq Standard Library *)\n\n(** One small digression before we begin...\n\n    Unlike the chapters we have seen so far, this one does not\n    [Require Import] the chapter before it (and, transitively, all the\n    earlier chapters).  Instead, in this chapter and from now, on\n    we're going to import the definitions and theorems we need\n    directly from Coq's standard library stuff.  You should not notice\n    much difference, though, because we've been careful to name our\n    own definitions and theorems the same as their counterparts in the\n    standard library, wherever they overlap. *)\n\nFrom Coq Require Import Arith.Arith.\nFrom Coq Require Import Bool.Bool.\nRequire Export Coq.Strings.String.\nFrom Coq Require Import Logic.FunctionalExtensionality.\nFrom Coq Require Import Lists.List.\nImport ListNotations.\n\n(** Documentation for the standard library can be found at\n    http://coq.inria.fr/library/.\n\n    The [Search] command is a good way to look for theorems involving\n    objects of specific types.  Take a minute now to experiment with it. *)\n\n(* ################################################################# *)\n(** * Identifiers *)\n\n(** First, we need a type for the keys that we use to index into our\n    maps.  In [Lists.v] we introduced a fresh type [id] for a similar\n    purpose; here and for the rest of _Software Foundations_ we will\n    use the [string] type from Coq's standard library. *)\n\n(** To compare strings, we define the function [eqb_string], which\n    internally uses the function [string_dec] from Coq's string\n    library. *)\n\nDefinition eqb_string (x y : string) : bool :=\n  if string_dec x y then true else false.\n\n(** (The function [string_dec] comes from Coq's string library.\n    If you check the result type of [string_dec], you'll see that it\n    does not actually return a [bool], but rather a type that looks\n    like [{x = y} + {x <> y}], called a [sumbool], which can be\n    thought of as an \"evidence-carrying boolean.\"  Formally, an\n    element of [sumbool] is either a proof that two things are equal\n    or a proof that they are unequal, together with a tag indicating\n    which.  But for present purposes you can think of it as just a\n    fancy [bool].) *)\n\n(** Now we need a few basic properties of string equality... *)\nTheorem eqb_string_refl : forall s : string, true = eqb_string s s.\nProof. intros s. unfold eqb_string. destruct (string_dec s s) as [|Hs].\n  - reflexivity.\n  - destruct Hs. reflexivity.\nQed.\n\n(** The following useful property follows from an analogous\n    lemma about strings: *)\n\nTheorem eqb_string_true_iff : forall x y : string,\n    eqb_string x y = true <-> x = y.\nProof.\n   intros x y.\n   unfold eqb_string.\n   destruct (string_dec x y) as [|Hs].\n   - subst. split. reflexivity. reflexivity.\n   - split.\n     + intros contra. discriminate contra.\n     + intros H. rewrite H in Hs. destruct Hs. reflexivity.\nQed.\n\n(** Similarly: *)\n\nTheorem eqb_string_false_iff : forall x y : string,\n    eqb_string x y = false <-> x <> y.\nProof.\n  intros x y. rewrite <- eqb_string_true_iff.\n  rewrite not_true_iff_false. reflexivity. Qed.\n\n(** This handy variant follows just by rewriting: *)\n\nTheorem false_eqb_string : forall x y : string,\n   x <> y -> eqb_string x y = false.\nProof.\n  intros x y. rewrite eqb_string_false_iff.\n  intros H. apply H. Qed.\n\n(* ################################################################# *)\n(** * Total Maps *)\n\n(** Our main job in this chapter will be to build a definition of\n    partial maps that is similar in behavior to the one we saw in the\n    [Lists] chapter, plus accompanying lemmas about its behavior.\n\n    This time around, though, we're going to use _functions_, rather\n    than lists of key-value pairs, to build maps.  The advantage of\n    this representation is that it offers a more _extensional_ view of\n    maps, where two maps that respond to queries in the same way will\n    be represented as literally the same thing (the very same function),\n    rather than just \"equivalent\" data structures.  This, in turn,\n    simplifies proofs that use maps. *)\n\n(** We build partial maps in two steps.  First, we define a type of\n    _total maps_ that return a default value when we look up a key\n    that is not present in the map. *)\n\nDefinition total_map (A : Type) := string -> A.\n\n(** Intuitively, a total map over an element type [A] is just a\n    function that can be used to look up [string]s, yielding [A]s. *)\n\n(** The function [t_empty] yields an empty total map, given a default\n    element; this map always returns the default element when applied\n    to any string. *)\n\nDefinition t_empty {A : Type} (v : A) : total_map A :=\n  (fun _ => v).\n\n(** More interesting is the [update] function, which (as before) takes\n    a map [m], a key [x], and a value [v] and returns a new map that\n    takes [x] to [v] and takes every other key to whatever [m] does. *)\n\nDefinition t_update {A : Type} (m : total_map A)\n                    (x : string) (v : A) :=\n  fun x' => if eqb_string x x' then v else m x'.\n\n(** This definition is a nice example of higher-order programming:\n    [t_update] takes a _function_ [m] and yields a new function\n    [fun x' => ...] that behaves like the desired map. *)\n\n(** For example, we can build a map taking [string]s to [bool]s, where\n    [\"foo\"] and [\"bar\"] are mapped to [true] and every other key is\n    mapped to [false], like this: *)\n\nDefinition examplemap :=\n  t_update (t_update (t_empty false) \"foo\" true)\n           \"bar\" true.\n\n(** Next, let's introduce some new notations to facilitate working\n    with maps. *)\n\n(** First, we will use the following notation to create an empty\n    total map with a default value. *)\nNotation \"'_' '!->' v\" := (t_empty v)\n  (at level 100, right associativity).\n\nExample example_empty := (_ !-> false).\n\n(** We then introduce a convenient notation for extending an existing\n    map with some bindings. *)\nNotation \"x '!->' v ';' m\" := (t_update m x v)\n                              (at level 100, v at next level, right associativity).\n\n(** The [examplemap] above can now be defined as follows: *)\n\nDefinition examplemap' :=\n  ( \"bar\" !-> true;\n    \"foo\" !-> true;\n    _     !-> false\n  ).\n\n(** This completes the definition of total maps.  Note that we\n    don't need to define a [find] operation because it is just\n    function application! *)\n\nExample update_example1 : examplemap' \"baz\" = false.\nProof. reflexivity. Qed.\n\nExample update_example2 : examplemap' \"foo\" = true.\nProof. reflexivity. Qed.\n\nExample update_example3 : examplemap' \"quux\" = false.\nProof. reflexivity. Qed.\n\nExample update_example4 : examplemap' \"bar\" = true.\nProof. reflexivity. Qed.\n\n(** To use maps in later chapters, we'll need several fundamental\n    facts about how they behave. *)\n\n(** Even if you don't work the following exercises, make sure\n    you thoroughly understand the statements of the lemmas! *)\n\n(** (Some of the proofs require the functional extensionality axiom,\n    which is discussed in the [Logic] chapter.) *)\n\n(** **** Exercise: 1 star, standard, optional (t_apply_empty)  \n\n    First, the empty map returns its default element for all keys: *)\n\nLemma t_apply_empty : forall (A : Type) (x : string) (v : A),\n    (_ !-> v) x = v.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (t_update_eq)  \n\n    Next, if we update a map [m] at a key [x] with a new value [v]\n    and then look up [x] in the map resulting from the [update], we\n    get back [v]: *)\n\nLemma t_update_eq : forall (A : Type) (m : total_map A) x v,\n    (x !-> v ; m) x = v.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (t_update_neq)  \n\n    On the other hand, if we update a map [m] at a key [x1] and then\n    look up a _different_ key [x2] in the resulting map, we get the\n    same result that [m] would have given: *)\n\nTheorem t_update_neq : forall (A : Type) (m : total_map A) x1 x2 v,\n    x1 <> x2 ->\n    (x1 !-> v ; m) x2 = m x2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (t_update_shadow)  \n\n    If we update a map [m] at a key [x] with a value [v1] and then\n    update again with the same key [x] and another value [v2], the\n    resulting map behaves the same (gives the same result when applied\n    to any key) as the simpler map obtained by performing just\n    the second [update] on [m]: *)\n\nLemma t_update_shadow : forall (A : Type) (m : total_map A) x v1 v2,\n    (x !-> v2 ; x !-> v1 ; m) = (x !-> v2 ; m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** For the final two lemmas about total maps, it's convenient to use\n    the reflection idioms introduced in chapter [IndProp].  We begin\n    by proving a fundamental _reflection lemma_ relating the equality\n    proposition on [id]s with the boolean function [eqb_id]. *)\n\n(** **** Exercise: 2 stars, standard, optional (eqb_stringP)  \n\n    Use the proof of [eqbP] in chapter [IndProp] as a template to\n    prove the following: *)\n\nLemma eqb_stringP : forall x y : string,\n    reflect (x = y) (eqb_string x y).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Now, given [string]s [x1] and [x2], we can use the tactic\n    [destruct (eqb_stringP x1 x2)] to simultaneously perform case\n    analysis on the result of [eqb_string x1 x2] and generate\n    hypotheses about the equality (in the sense of [=]) of [x1]\n    and [x2]. *)\n\n(** **** Exercise: 2 stars, standard (t_update_same)  \n\n    With the example in chapter [IndProp] as a template, use\n    [eqb_stringP] to prove the following theorem, which states that\n    if we update a map to assign key [x] the same value as it already\n    has in [m], then the result is equal to [m]: *)\n\nTheorem t_update_same : forall (A : Type) (m : total_map A) x,\n    (x !-> m x ; m) = m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, recommended (t_update_permute)  \n\n    Use [eqb_stringP] to prove one final property of the [update]\n    function: If we update a map [m] at two distinct keys, it doesn't\n    matter in which order we do the updates. *)\n\nTheorem t_update_permute : forall (A : Type) (m : total_map A)\n                                  v1 v2 x1 x2,\n    x2 <> x1 ->\n    (x1 !-> v1 ; x2 !-> v2 ; m)\n    =\n    (x2 !-> v2 ; x1 !-> v1 ; m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Partial maps *)\n\n(** Finally, we define _partial maps_ on top of total maps.  A partial\n    map with elements of type [A] is simply a total map with elements\n    of type [option A] and default element [None]. *)\n\nDefinition partial_map (A : Type) := total_map (option A).\n\nDefinition empty {A : Type} : partial_map A :=\n  t_empty None.\n\nDefinition update {A : Type} (m : partial_map A)\n           (x : string) (v : A) :=\n  (x !-> Some v ; m).\n\n(** We introduce a similar notation for partial maps: *)\nNotation \"x '|->' v ';' m\" := (update m x v)\n  (at level 100, v at next level, right associativity).\n\n(** We can also hide the last case when it is empty. *)\nNotation \"x '|->' v\" := (update empty x v)\n  (at level 100).\n\nExample examplepmap :=\n  (\"Church\" |-> true ; \"Turing\" |-> false).\n\n(** We now straightforwardly lift all of the basic lemmas about total\n    maps to partial maps.  *)\n\nLemma apply_empty : forall (A : Type) (x : string),\n    @empty A x = None.\nProof.\n  intros. unfold empty. rewrite t_apply_empty.\n  reflexivity.\nQed.\n\nLemma update_eq : forall (A : Type) (m : partial_map A) x v,\n    (x |-> v ; m) x = Some v.\nProof.\n  intros. unfold update. rewrite t_update_eq.\n  reflexivity.\nQed.\n\nTheorem update_neq : forall (A : Type) (m : partial_map A) x1 x2 v,\n    x2 <> x1 ->\n    (x2 |-> v ; m) x1 = m x1.\nProof.\n  intros A m x1 x2 v H.\n  unfold update. rewrite t_update_neq. reflexivity.\n  apply H. Qed.\n\nLemma update_shadow : forall (A : Type) (m : partial_map A) x v1 v2,\n    (x |-> v2 ; x |-> v1 ; m) = (x |-> v2 ; m).\nProof.\n  intros A m x v1 v2. unfold update. rewrite t_update_shadow.\n  reflexivity.\nQed.\n\nTheorem update_same : forall (A : Type) (m : partial_map A) x v,\n    m x = Some v ->\n    (x |-> v ; m) = m.\nProof.\n  intros A m x v H. unfold update. rewrite <- H.\n  apply t_update_same.\nQed.\n\nTheorem update_permute : forall (A : Type) (m : partial_map A)\n                                x1 x2 v1 v2,\n    x2 <> x1 ->\n    (x1 |-> v1 ; x2 |-> v2 ; m) = (x2 |-> v2 ; x1 |-> v1 ; m).\nProof.\n  intros A m x1 x2 v1 v2. unfold update.\n  apply t_update_permute.\nQed.\n\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/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.875787001374006, "lm_q1q2_score": 0.6534588412023001}}
{"text": "Require Import ZArith Arith Bool Omega.\n\nOpen Scope Z_scope.\n\n(* The key to this corollary is that if s=Zsqrt_plain x, then\n  s*s < (s+1) * (s+1), as stated by the companion theorem\n  Zsqrt_interval, and the squaring operation is monotonic only\n  for positive values. *)\n\nTheorem div_Zsqrt :\n forall m n p:Z, 0 < m < n ->\n  n=m*p-> 0 < m <= Z.sqrt n \\/ 0 < p <= Z.sqrt n.\nProof.\n intros m n p Hint Heq.\n elim (Z_lt_le_dec (Z.sqrt n) m); \n elim (Z_lt_le_dec (Z.sqrt n) p).\n -  intros Hltm Hltp.\n    assert (Hlem : (Z.sqrt n)+1 <= m) by  omega.\n    assert (Hlep : (Z.sqrt n)+1 <= p) by  omega.\n    elim (Z.lt_irrefl n).\n    apply Z.lt_le_trans with (((Z.sqrt n)+1)*((Z.sqrt n)+1)).\n    assert (Hposn : 0 <= n) by  omega.\n    generalize (Z.sqrt_spec n Hposn);cbv zeta;intro H23.\n    intuition. \n    pattern n at 3; rewrite Heq.\n    apply Zmult_le_compat; try omega.\n    generalize (Z.sqrt_nonneg n).\n    omega.\n    generalize (Z.sqrt_nonneg n).\n    omega.\n - intros Hple _; right; split; auto.\n   apply Zmult_lt_0_reg_r with m; try tauto.\n   rewrite Zmult_comm; omega.\n -  intros _ Hmle; left; split; tauto.\n -  intros _ Hmle; left; split; tauto.\nQed.\n\n\nDefinition divides_bool (p t:Z) : bool :=\n match t mod p with\n   0 => true\n | _ => false\n end.\n\nFixpoint test_odds (n:nat) (p t:Z) {struct n} : bool :=\n match n with\n | 0%nat => negb (divides_bool 2 t)\n | S n' =>\n   if test_odds n' (p - 2) t then negb (divides_bool p t) else false\n end.\n\n\nDefinition prime_test (n:nat) : bool :=\n match n with\n | 0%nat => false\n | 1%nat => false\n | S (S n) => \n  let x := (Z_of_nat (S (S n))) in\n  let s := (Z.sqrt x) in\n  let (half_s, even_bit) :=\n    match s with\n    | Zpos(xI h) => (Zpos h, 0)\n    | Zpos(xO h) => (Zpos h, 1)\n    | Zpos xH => (0, 0)\n    | _ => (0, 1)  \n    end  in\n  test_odds (Z.abs_nat half_s) (s + even_bit) x\n end.\n\nTime Eval lazy beta iota delta zeta in (prime_test 2333).\n\n(* Time Eval compute in (prime_test 2333). \n \n  This command takes a much longer time.  The reason is that Z.sqrt_plain\n  calls a strongly specified function, which builds a proof term that is\n  large, but is discarded later.  Lazy computation avoid the useless \n  work. *)\n\n(* we use the same axiom as in the book, it is corrected in another exercise.\n *)\n\nAxiom verif_divide :\n  (forall m p:nat, 0 < m -> 0 < p ->\n   (exists q:nat, m = q*p) ->(Z_of_nat m mod Z_of_nat p = 0)%Z )%nat.\n\n(* This axiom is actually a lemma used in the same other exercise. *)\n\nAxiom Z_to_nat_and_back :\n forall x:Z, (0 <= x)%Z -> (Z_of_nat (Z.abs_nat x))=x.\n\nTheorem test_odds_correct2 :\n  forall n x:nat,\n    (1 < x)%nat ->\n  forall p:Z,\n    test_odds n p (Z_of_nat x) = true ->\n    ~(exists y:nat, x = y*2)%nat.\nProof.\n intros n; elim n.\n - unfold test_odds, divides_bool; intros x H1ltx _ Heq Hex.\n   assert (Heq' : Z_of_nat x mod Z_of_nat 2 = 0).\n  +  apply verif_divide; auto with zarith.\n  +  simpl (Z_of_nat 2) in Heq'; rewrite Heq' in Heq; simpl in Heq; discriminate.\n\n - clear n; intros n IHn x H1ltx p; simpl.\n   case_eq (test_odds n (p - 2) (Z_of_nat x)).\n   +  intros Htest' _ ; apply (IHn x H1ltx (p -2)); auto.\n   +  intros; discriminate.\nQed.\n\nTheorem Z_of_nat_le :\n  forall x y, Z_of_nat x <= Z_of_nat y -> (x <= y)%nat.\nProof.\n intros; omega.\nQed.\n\n\nTheorem test_odds_correct :\n  forall (n x:nat)(p:Z),\n   p = 2*(Z_of_nat n)+1 ->\n   (1 < x)%nat -> test_odds n p (Z_of_nat x) = true -> \n   forall q:nat, (1 < q <= 2*n+1)%nat -> ~(exists y:nat, x = q*y)%nat.\nProof.\n induction n.\n -  intros x p Hp1 H1ltx Hn q Hint.\n    elimtype False;  omega.\n  - intros x p Hp H1ltx; simpl (test_odds (S n) p (Z_of_nat x));\n    intros Htest q (H1ltq, Hqle).\n    case_eq (test_odds n (p -2) (Z_of_nat x)).\n    + intros Htest'true.\n      rewrite Htest'true in Htest.\n      unfold divides_bool in Htest.\n      elim (le_lt_or_eq q (2*S n + 1)%nat Hqle).\n      *  intros Hqlt.\n         assert (Hqle': (q <= (2* S n))%nat) by  omega.\n         elim (le_lt_or_eq q (2 * S n)%nat Hqle').\n         replace (2*S n)%nat with (2*n +2)%nat.\n         intros Hqlt'.\n         assert (Hqle'' : (q <= 2*n +1)%nat) by omega.\n         apply (IHn x (p - 2)); auto with zarith arith;\n         try (rewrite Hp; rewrite inj_S; unfold Z.succ); ring.\n         ring.\n         intros Hq (y, Hdiv); elim (test_odds_correct2 n x H1ltx (p - 2)); auto.\n         exists (S n * y)%nat; rewrite Hdiv; rewrite Hq; ring.\n  \n      * intros Hq Hex; assert (Hp' : p = Z_of_nat q).\n        rewrite Hp; rewrite Hq; rewrite inj_plus; rewrite inj_mult; auto.\n        rewrite Hp' in Htest; rewrite (verif_divide x q) in Htest.\n        simpl in Htest; discriminate.\n        omega.\n        omega.\n        elim Hex; intros y Hdiv; exists y; rewrite Hdiv; ring.\n    + intros Htest'; rewrite Htest' in Htest; simpl in Htest; discriminate.\nQed.\n\nAxiom divisor_smaller :\n  (forall m p:nat, 0 < m -> forall q:nat, m = q*p -> q <= m)%nat.\n\n\nTheorem lt_Zpos : forall p:positive, 0 < Zpos p.\nProof.\n intros p; elim p.\n -  intros; rewrite Zpos_xI; omega.\n -  intros; rewrite Zpos_xO; omega.\n -  auto with zarith.\nQed.\n\nTheorem Zneg_lt : forall p:positive, Zneg p < 0.\nProof.\n intros p; elim p.\n -  intros; rewrite Zneg_xI; omega.\n -  intros; rewrite Zneg_xO; omega.\n -  auto with zarith.\nQed.\n\n\nTheorem prime_test_correct :\n forall n:nat, prime_test n = true ->\n ~(exists k:nat, k <> 1 /\\ k <> n /\\ (exists q:nat, n = q*k))%nat.\nProof.\n intros n; case_eq n.\n -  simpl;  intros Heq Hd; discriminate.\n -  intros n0; case_eq n0.\n   +  simpl; intros Heq1 Heq2 Hd; discriminate.\n   + unfold prime_test; intros n1 Heqn0 Heqn.\n     assert (H1ltn : (1 < n)%nat).\n     *  rewrite Heqn; auto with arith.\n     * rewrite <- Heqn.\n       lazy beta zeta delta [prime_test].\n       case_eq (Z.sqrt (Z_of_nat n)).\n       intros Hsqrt_eq.\n       elim (Zlt_asym 1 (Z_of_nat n)).\n       omega.\n       lapply (Z.sqrt_spec (Z_of_nat n)).\n       rewrite Hsqrt_eq; simpl.\n       omega.\n       omega.\n       intros p Hsqrt_eq Htest_eq (k, (Hn1, (Hnn, (q,Heq)))).\n       assert (H0ltn:(0 < n)%nat) by  omega.\n       assert (Hkltn:(k < n)%nat).\n       assert (Heq' : n=(k*q)%nat).\n       rewrite Heq; ring.\n       generalize (divisor_smaller n q H0ltn k Heq'). \n       omega.\n       assert (Hex: exists k':nat, (1 < (Z_of_nat k') <= (Z.sqrt (Z_of_nat n))) /\\\n               (exists q':nat, n=(k'*q')%nat)).\n       elim (div_Zsqrt (Z_of_nat k) (Z_of_nat n) (Z_of_nat q)).\n       intros Hint1; exists k;split.\n       omega.\n       exists q; rewrite Heq; ring.\n       intros Hint2; exists q; split.\n       split.\n       elim (Zle_or_lt (Z_of_nat q) 1); auto.\n       intros hqle1;  assert (Hq1: q = 1%nat).\n       omega.\n       rewrite Hq1 in Heq; simpl in Heq; elim Hnn; rewrite Heq; ring.\n       tauto.\n       exists k; auto.\n       split.\n       case_eq k.\n       intros Hk0; rewrite Hk0 in Heq; rewrite Heq in H1ltn;\n       rewrite mult_0_r in H1ltn; omega.\n       intros; unfold Z.lt; simpl; auto.\n       omega.\n       rewrite Zmult_comm; rewrite <- inj_mult; rewrite Heq;auto.\n       elim Hex; intros k' ((H1ltk', Hk'ltsqrt), Hex'); clear Hex.\n       case_eq p.\n       intros p' Hp; rewrite Hp in Htest_eq.\n       elim (test_odds_correct (Z.abs_nat (Zpos p'))\n           n (Zpos p)) with k'.\n       rewrite Z_to_nat_and_back.\n       rewrite Hp.\n       auto with zarith.\n       auto with zarith.\n       auto.\n       repeat rewrite Zminus_0_r in Htest_eq.\n       rewrite Hp; auto.\n       split.\n       omega.\n       apply Z_of_nat_le.\n       rewrite inj_plus.\n       rewrite inj_mult.\n       rewrite Z_to_nat_and_back.\n       simpl (Z_of_nat 2).\n       simpl (Z_of_nat 1).\n       rewrite <- Zpos_xI.\n       rewrite <- Hp.\n       rewrite <- Hsqrt_eq; auto.\n       auto with zarith.\n       auto.\n       intros p' Hp; rewrite Hp in Htest_eq.\n       elim (test_odds_correct (Z.abs_nat (Zpos p')) n (Zpos p + 1))\n       with k'.\n       rewrite Z_to_nat_and_back.\n       rewrite Hp; rewrite Zpos_xO; ring.\n       generalize (lt_Zpos p'); intros; omega.\n       auto.\n       rewrite <- Hp in Htest_eq; auto.\n       split; try omega.\n       apply Z_of_nat_le.\n       rewrite inj_plus.\n       rewrite inj_mult.\n       rewrite Z_to_nat_and_back.\n       simpl (Z_of_nat 2); simpl (Z_of_nat 1).\n       rewrite <- Zpos_xO.\n       rewrite <- Hp; omega.\n       auto with zarith.\n       auto.\n       intros Hp; rewrite Hp in Hsqrt_eq.\n       rewrite Hsqrt_eq in Hk'ltsqrt.\n       omega.\n       intros p Hsqrt_eq.\n       elim (Zle_not_lt 0 (Z.sqrt (Z_of_nat n))).\n       apply Z.sqrt_nonneg.\n       rewrite Hsqrt_eq.\n       apply Zneg_lt.\nQed.\n\n", "meta": {"author": "baberrehman", "repo": "interactive-theorem-proving", "sha": "e8e9de4bc664f4dd1b0fd72d6edf84f736da8874", "save_path": "github-repos/coq/baberrehman-interactive-theorem-proving", "path": "github-repos/coq/baberrehman-interactive-theorem-proving/interactive-theorem-proving-e8e9de4bc664f4dd1b0fd72d6edf84f736da8874/coq-art-8.13.0/ch16_proof_by_reflection/SRC/prime_sqrt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6534588288956245}}
{"text": "(* Ord: type class for ordered types. *)\n\nRequire Import EquivDec Compare_dec Relation_Definitions Le.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Equal Relations.\n\nOpen Scope list_scope.\n\nCheck transitive.\n\nClass Ord (T: Type) {eq_: Eq T} := {\n  lessthan: relation T;\n  lt_trans: transitive lessthan;\n  lt_asym: asymmetric lessthan;\n  lt_dec: forall a b: T, {lessthan a b} + {a = b} + {lessthan b a}\n}.\n\nInstance ord_nat : Ord nat := {\n  lessthan := lt;\n  lt_dec := lt_eq_lt_dec\n}.\nProof.\n  unfold transitive. \n  apply Lt.lt_trans.\n  unfold asymmetric.\n  apply NPeano.Nat.lt_asymm.\nDefined.\n\nSection ListLt.\n  Context {T: Type}.\n  Context {eq_elem: Eq T}.\n  Context {ord_elem: Ord T}.\n  \n  Inductive list_lt: list T -> list T -> Prop :=\n    | lt_nil  : forall x l, list_lt nil (x::l)\n    | lt_cons : forall x xs y ys,\n        lessthan x y -> list_lt (x::xs) (y::ys).\n  \n  Lemma list_lt_trans: transitive list_lt.\n  Proof.\n    unfold transitive. intros xs ys zs H1 H2.\n    generalize dependent ys.\n    generalize dependent zs.\n    induction xs.\n      intros.\n      destruct zs. inversion H1. inversion H2. constructor.\n      intros.\n      inversion H1.\n      destruct zs. subst. inversion H2.\n      subst. inversion H2. subst.\n      constructor. apply (lt_trans a y t H4 H0).\n  Qed.\n\n  Lemma list_lt_asym: asymmetric list_lt.\n  Proof.\n    unfold asymmetric. unfold not. intros.\n    inversion H. subst. inversion H0. subst.\n    inversion H0. subst. apply (lt_asym x y H1 H3).\n  Qed.\n\n  (* Theorem list_lt_asym_dec: forall l l', {list_lt l l'} + {~list_lt l l'}. *)\n  (* Proof. *)\n  (*   intros l. induction l. *)\n  (*   destruct l'. right. intuition. inversion H. *)\n  (*   left. constructor. *)\n  (*   intros l'. *)\n  (*   destruct l'. right. intuition. inversion H. *)\n  (*   destruct (lt_dec a t). *)\n  (*   destruct s. *)\n  (*   destruct (IHl l'). *)\n  (*   left. constructor. apply l0. apply l1. *)\n  (*   right. intuition. inversion H. subst. contradiction. *)\n  (*   right. intuition. inversion H. subst.  *)\n  (*   apply (lt_asym t t). apply H3. apply H3. *)\n  (*   right. intuition. inversion H. subst. apply (lt_asym a t). *)\n  (*   apply H3. apply l0. *)\n  (* Defined. *)\n\n  Theorem list_lt_dec: forall l l', {list_lt l l'} + {l = l'} + {list_lt l' l}.\n  Proof.\n    intros l. \n    induction l.\n      intros l'.\n      destruct l'. auto. left. left. constructor.\n      intros l'.\n      destruct l'.\n        right. constructor.\n        destruct (lt_dec a t).\n        inversion s.\n        left. left. constructor. apply H.\n        destruct (IHl l').\n        inversion s0. left. left.\n        \n        destruct (list_lt_asym_dec l l').\n    auto. induction l. destruct l'. left. auto.\n    elimtype False. apply b. constructor.\n    destruct l'. right. constructor.\n    \n\n  Instance list_ord\n    {eqlist: Eq (list T)}: Ord (list T) := {\n    lessthan := list_lt;\n    lt_trans := list_lt_trans;\n    lt_asym := list_lt_asym\n  }.\n  (* decision procedure *)\n  \nTheorem list_leq_partialorder:\n  forall T {eq_elem: Eq T} {ord_elem: Ord T}, partial_order list_leq.\nProof.\n  intros.\n  unfold partial_order.\n  split. unfold preorder.\n  split. unfold reflexive. intros l.\n  induction l. constructor. constructor. apply eq_implies_leq. reflexivity.\n  apply IHl.\n  unfold transitive.\n    intros xs ys zs H.\n    \n    \n  \n\n\n(* Instance list_leq_partial_order  *)\n(*    {T: Type} {eq_elem: Eq T} {ord_elem: Ord T}:  *)\n(*    PartialOrder eq (@list_leq T eq_elem ord_elem). *)\n(* Proof. *)\n(*   split. *)\n(*   (* Prove reflexivity *) *)\n(*     unfold Reflexive. *)\n(*     intros l. *)\n(*     induction l. constructor. *)\n(*     constructor. apply eq_implies_leq. reflexivity. apply IHl. *)\n(*   (* Prove symmetry *) *)\n(*     unfold Symmetric. *)\n(*     intros xs ys H. *)\n(*     induction xs. *)\n\nInstance ord_list \n  {T: Type} \n  {eq_elem: Eq T}\n  {ord_elem: Ord T} \n  {eq_list: Eq (list T)}: \n  Ord (list T) := {\n  leq := list_leq\n}.\n\n", "meta": {"author": "thinkpad20", "repo": "simple-coq-classes", "sha": "ef2c84fa5a8c851e06831ac5623037a7c3971535", "save_path": "github-repos/coq/thinkpad20-simple-coq-classes", "path": "github-repos/coq/thinkpad20-simple-coq-classes/simple-coq-classes-ef2c84fa5a8c851e06831ac5623037a7c3971535/Ord.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6534588265824712}}
{"text": "(* \n  Author(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\n(* \n  Reduction from:\n    Finite Multiset Constraint Solvability (FMsetC_SAT)\n  to:\n    Linear Polynomial (over N) Constraint Solvability (LPolyNC_SAT)\n*)\n\nRequire Import List PeanoNat Lia Permutation.\nImport ListNotations.\n\nRequire Import Undecidability.SetConstraints.FMsetC.\nRequire Import Undecidability.PolynomialConstraints.LPolyNC.\n\nRequire Import Undecidability.Synthetic.Definitions.\n\nRequire Import ssreflect ssrbool ssrfun.\n\nSet Default Goal Selector \"!\".\n\nModule Argument.\nLocal Arguments poly_add !p !q.\n\nLocal Notation \"p ≃ q\" := (poly_eq p q) (at level 65).\nLocal Notation \"A ≡ B\" := (mset_eq A B) (at level 65).\n\nLemma poly_add_nthP {i p q} : nth i (poly_add p q) 0 = (nth i p 0) + (nth i q 0).\nProof. elim: i p q => [|i IH] [|a p [|b q]] /=; by [|lia]. Qed.\n\nDefinition encode_msetc (c : msetc) : polyc :=\n  match c with\n  | msetc_zero x => polyc_one x\n  | msetc_sum x y z => polyc_sum x y z\n  | msetc_h x y => polyc_prod x y\n  end.\n\n(* count the number of occurrences of each element *)\nFixpoint mset_to_poly (A: list nat) := \n  match A with\n  | [] => []\n  | a :: A => poly_add (repeat 0 a ++ [1]) (mset_to_poly A)\n  end.\n\nLemma mset_to_poly_shift {a A B} : mset_to_poly (A ++ a :: B) ≃ mset_to_poly (a :: A ++ B).\nProof.\n  elim: A; first done.\n  move=> c A + i => /(_ i) /=. rewrite ?poly_add_nthP. by lia.\nQed.\n\nLemma mset_to_poly_appP {A B} : mset_to_poly (A ++ B) ≃ poly_add (mset_to_poly A) (mset_to_poly B).\nProof. \n  elim: A; first done.\n  move=> a A + i => /(_ i) /=. rewrite ?poly_add_nthP. by lia.\nQed.\n\nLemma mset_to_poly_mapP {A} : mset_to_poly (map S A) ≃ 0 :: mset_to_poly A.\nProof. \n  elim: A; first by (case; [done | by case]).\n  move=> a A + i => /(_ i). case: i.\n  - by rewrite /map -/(map _ _) ?poly_add_nthP.\n  - move=> i. rewrite /map -/(map _ _) /mset_to_poly -/(mset_to_poly).\n    rewrite /= ?poly_add_nthP /=. by lia.\nQed.\n\nLemma poly_add_0I {p q r} : r ≃ [] -> p ≃ q -> p ≃ poly_add q r.\nProof.\n  move=> + + i => /(_ i) + /(_ i). rewrite poly_add_nthP.\n  case: i=> /=; by lia.\nQed.\n\nLemma poly_shiftI {p} : poly_mult [0; 1] p ≃ (0 :: p).\nProof.\n  rewrite /poly_mult => i /=. rewrite poly_add_nthP /=.\n  have ->: nth i (map (fun=> 0) p) 0 = 0. { by elim: i p => [|i IH] [|? p] /=. }\n  move: i => [|i] /=; first done.\n  rewrite poly_add_nthP.\n  have ->: nth i [0] 0 = 0. { by move: i => [|[|i]]. }\n  elim: i p => [|i IH] [|? p] /=; by [|lia].\nQed.\n\nLemma mset_to_poly_eqI {A B} : A ≡ B -> mset_to_poly A ≃ mset_to_poly B.\nProof.\n  move=> /Permutation_count_occ. elim: A B.\n  - by move=> B /Permutation_nil ->.\n  - move=> a A IH B /[dup] /(Permutation_in a) /(_ (in_eq _ _)).\n    move=> /(@in_split nat) [B1 [B2 ->]] /(@Permutation_cons_app_inv nat) /IH {}IH i.\n    move: (IH i) (@mset_to_poly_shift a B1 B2 i).\n    rewrite /= !poly_add_nthP. by lia.\nQed.\n\nLemma completeness {l} : FMsetC_SAT l -> LPolyNC_SAT (map encode_msetc l).\nProof.\n  move=> [φ]. rewrite -Forall_forall => Hφ.\n  exists (fun x => mset_to_poly (φ x)). rewrite -Forall_forall Forall_map.\n  apply: Forall_impl; last by eassumption. case.\n  - by move=> x /= /mset_to_poly_eqI.\n  - move=> x y z /= /mset_to_poly_eqI + i => /(_ i) ->.\n    by apply mset_to_poly_appP.\n  - move=> x y /= /mset_to_poly_eqI + i => /(_ i) ->.\n    move: (@poly_shiftI (mset_to_poly (φ y)) i) => /= ->.\n    by apply: mset_to_poly_mapP.\nQed.\n\nFixpoint poly_to_mset (p: list nat) := \n  match p with\n  | [] => []\n  | a :: p => (repeat 0 a) ++ map S (poly_to_mset p)\n  end.\n\nLemma count_occ_poly_to_msetP {a p}: count_occ Nat.eq_dec (poly_to_mset p) a = nth a p 0.\nProof.\n  elim: a p.\n  - case; first done.\n    move=> + p /=. elim; first by elim: (poly_to_mset p).\n    by move=> ? /= ->.\n  - move=> i IH. case; first done.\n    move=> a p /=. rewrite count_occ_app.\n    rewrite -(count_occ_map S Nat.eq_dec) ?IH; first by lia.\n    by elim a.\nQed.\n\nLemma poly_to_mset_eqI {p q} : p ≃ q -> poly_to_mset p ≡ poly_to_mset q.\nProof. move=> + a. by rewrite ?count_occ_poly_to_msetP. Qed.\n\nLemma poly_to_mset_addP {p q} : poly_to_mset (poly_add p q) ≡ poly_to_mset p ++ poly_to_mset q.\nProof. move=> a. by rewrite count_occ_app ? count_occ_poly_to_msetP poly_add_nthP. Qed.\n\nLemma poly_to_mset_consP {p} : poly_to_mset (0 :: p) = map S (poly_to_mset p).\nProof. done. Qed.\n\nLemma soundness {l} : LPolyNC_SAT (map encode_msetc l) -> FMsetC_SAT l.\nProof.\n  have eq_trans A B C : A ≡ B -> B ≡ C -> A ≡ C.\n  { move=> H1 H2 c. by rewrite (H1 c) (H2 c). }\n  move=> [ψ]. rewrite -Forall_forall Forall_map => Hψ.\n  exists (fun x => poly_to_mset (ψ x)). rewrite -Forall_forall.\n  apply: Forall_impl; last by eassumption. case.\n  - by move=> x /= /poly_to_mset_eqI.\n  - move=> x y z /= /poly_to_mset_eqI. move /eq_trans. apply.\n    by apply: poly_to_mset_addP.\n  - move=> x y /= /poly_to_mset_eqI. move /eq_trans. apply.\n    move: (ψ y) => p. rewrite -poly_to_mset_consP. apply: poly_to_mset_eqI.\n    by apply: poly_shiftI.\nQed.\n\nEnd Argument.\n\n(* many-one reduction from FMsetC_SAT to LPolyNC_SAT *)\nTheorem reduction : FMsetC_SAT ⪯ LPolyNC_SAT.\nProof.\n  exists (map Argument.encode_msetc) => l. constructor.\n  - exact Argument.completeness.\n  - exact Argument.soundness.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/PolynomialConstraints/Reductions/FMsetC_SAT_to_LPolyNC_SAT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6534588264766272}}
{"text": "Require Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Omega.\n\nRequire Import Graph.\n\nOpen Scope program_scope.\n\n(* An homomorphism is a morphism preserving the graph structure *)\nClass Homomorphism {A B:Type} (f : Graph A -> Graph B) : Prop := {\n  Hom_Empty :> f Empty = Empty;\n  Hom_Overlay :> forall a b, f (Overlay a b) = Overlay (f a) (f b) ;\n  Hom_Connect :> forall a b, f (Connect a b) = Connect (f a) (f b)\n }.\n\nLemma bind_is_hom {A B} (f: A -> Graph B): Homomorphism (bind f).\nProof.\n  intros.\n  repeat split.\nQed.\n\nLemma hom_is_bind {A B} {hom: Graph A -> Graph B}: Homomorphism hom -> hom = bind (hom ∘ Vertex).\nProof.\n  intros H.\n  apply FunctionalExtensionality.functional_extensionality.\n  intro g.\n  induction g.\n  - compute. apply Hom_Empty.\n  - auto.\n  - rewrite Hom_Overlay.\n    rewrite IHg1.\n    rewrite IHg2.\n    auto.\n  - rewrite Hom_Connect.\n    rewrite IHg1.\n    rewrite IHg2.\n    auto.\nQed.\n\n(* Homomorphisms are exactly bind-functions *)\nTheorem equiv_bind_hom {A B} (f : Graph A -> Graph B) :\n  Homomorphism f <-> f = bind (f ∘ Vertex).\nProof.\n  intros.\n  split.\n  - intro H.\n    apply (hom_is_bind H).\n  - intro H.\n    rewrite H.\n    apply bind_is_hom.\nQed.\n\n(* The composition of a foldg function and a graph homorphism is a foldg-function *)\nTheorem foldg_bind {A B C} {e : C} {v: B -> C} {o:C -> C -> C} {c:C -> C -> C} {f_v : A -> Graph B}:\n  foldg e v o c ∘ bind f_v = foldg e (foldg e v o c ∘ f_v) o c.\nProof.\n  apply FunctionalExtensionality.functional_extensionality.\n  intro g.\n  unfold compose.\n  induction g.\n  - auto.\n  - auto.\n  - pose (H :=bind_is_hom f_v).\n    rewrite Hom_Overlay.\n    repeat rewrite foldg_overlay.\n    rewrite IHg1.\n    rewrite IHg2.\n    reflexivity.\n  - pose (H :=bind_is_hom f_v).\n    rewrite Hom_Connect.\n    repeat rewrite foldg_connect.\n    rewrite IHg1.\n    rewrite IHg2.\n    reflexivity.\nQed.\n\n(* The composition of two graphs homomorphisms is a graph homomorphism *)\nTheorem bind_compo {A B C} {hom1 : Graph A -> Graph B} {hom2 : Graph B -> Graph C}:\n (Homomorphism hom1) /\\ (Homomorphism hom2) -> \n  hom2 ∘ hom1 = bind (hom2 ∘ hom1 ∘ Vertex).\nProof.\n  intros H.\n  destruct H as (H1,H2).\n  rewrite (hom_is_bind H2).\n  rewrite (hom_is_bind H1).\n  rewrite (inline_bind B C).\n  rewrite foldg_bind.\n  auto.\nQed.\n\nLemma size_ov {A} {g1 g2 : Graph A} : size (Overlay g1 g2) = size g1 + size g2.\nProof. auto. Qed.\n\nLemma size_co {A} {g1 g2 : Graph A} : size (Connect g1 g2) = size g1 + size g2.\nProof. auto. Qed.\n\nLemma sup1 (m n: nat) : (n >= 1) -> m + n >= 1.\nProof. omega. Qed.\n\nLemma size_sup1 A (g:Graph A) : size g >= 1.\nProof.\n  induction g.\n  - compute. auto.\n  - compute. auto.\n  - rewrite size_ov.\n    apply sup1.\n    exact IHg2.\n  - rewrite size_co.\n    apply sup1.\n    exact IHg2.\nQed.\n\nLemma hom_leq_size A B (f: Graph A -> Graph B) : (Homomorphism f) -> forall g, size g <= size (f g).\nProof.\n  intros H g.\n  induction g.\n  - rewrite Hom_Empty.\n    auto.\n  - apply size_sup1.\n  - rewrite Hom_Overlay.\n    repeat rewrite size_ov.\n    omega.\n  - rewrite Hom_Connect.\n    repeat rewrite size_co.\n    omega.\nQed.", "meta": {"author": "nobrakal", "repo": "coq-alga", "sha": "a8d45e3b96d39b8cf79f259540ec29204ede7e5c", "save_path": "github-repos/coq/nobrakal-coq-alga", "path": "github-repos/coq/nobrakal-coq-alga/coq-alga-a8d45e3b96d39b8cf79f259540ec29204ede7e5c/src/Homomorphism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6534588216386322}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nImplicit Type p q r: bool.\nImplicit Type m n a b c: nat.\n\nLemma orbC p q: p || q = q || p.\n  by case: p; case q. Qed.\n\nLemma Pirce p q: ((p ==> q) ==> p) ==> p.\n  by case: p; case q. Qed.\n\nLemma bool_gimmics1 a: a != a.-1 -> a != 0.\n  by elim: a. Qed.\n\nLemma find_me p q: ~~p = q -> p (+) q.\n  by case: p; case q. Qed.\n\nLemma view_gimmics1 p a b: p -> (p ==> (a == b.*2)) -> a./2 = b.\n  case p => //= _ => /eqP ->; exact: doubleK.\nQed.\n\nLemma view_gimmics2 p q r: ~~p && (r == q) -> q ==> (p || r).\n  by case: p; case q; case r.\nQed.\n\nLemma iterSr A n (f: A -> A) x: iter n.+1 f x = iter n f (f x).\n  elim: n => //= _ -> //.\nQed.\n\nLemma iter_predn m n: iter n predn m = m - n.\n  elim: n => //=.\n    by rewrite subn0.\n    by move=> n ->; rewrite subnS.\nQed.\n\nLemma ltn_nqqAle m n: (m < n) = (m != n) && (m <= n).\n    by rewrite ltnNge leq_eqVlt negb_or -leqNgt eq_sym.\nQed.\n\nLemma maxn_idPl m n: reflect (maxn m n = m) (m >= n).\n  rewrite -subn_eq0 -(eqn_add2l m) addn0 maxnE.\n  apply: eqP.\nQed.", "meta": {"author": "hanazuki", "repo": "advanced-coq-16", "sha": "6aa0075fdb6fe4604186eab763a890ffcc480676", "save_path": "github-repos/coq/hanazuki-advanced-coq-16", "path": "github-repos/coq/hanazuki-advanced-coq-16/advanced-coq-16-6aa0075fdb6fe4604186eab763a890ffcc480676/exercise1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639065, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6534588192196346}}
{"text": "Section InAHurry.\n\nLemma AndComm : forall a b : Prop, a /\\ b -> b /\\ a.\nProof.\nintros a b H.\nsplit.\n  destruct H as [H1 H2].\n  exact H2. \n  destruct H as [H1 H2].\n  exact H1. \nQed.\n\nLemma AndComm2 : forall a b : Prop, a /\\ b -> b /\\ a.\nProof.\nintros a b H.\nsplit; destruct H as [H1 H2].\n  exact H2.\n  exact H1. \nQed.\n\nLemma OrComm : forall a b : Prop, a \\/ b -> b \\/ a.\nProof.\nintros a b H.\ndestruct H as [H1 | H2].\n  right.\n  exact H1.\n  left.\n  exact H2.\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/in_a_hurry.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6534284751689438}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq             *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later            *)\nFrom mathcomp Require Import all_ssreflect ssralg fingroup finalg matrix.\nRequire Import Reals.\nFrom mathcomp Require Import Rstruct.\nRequire Import ssrR Reals_ext logb ssr_ext ssralg_ext bigop_ext Rbigop fdist.\nRequire Import proba entropy jfdist_cond.\n\n(******************************************************************************)\n(*                 Definition of channels and of the capacity                 *)\n(*                                                                            *)\n(*  `Ch(A, B) == discrete channel of input alphabet A and output alphabet B;  *)\n(*               it is a collection of probability mass functions, one for    *)\n(*               each a in A (i.e., a probability transition matrix           *)\n(* `Ch*(A, B) == channels with non-empty alphabet                             *)\n(* W `(b | a) == probability of receiving b knowing a was sent over the       *)\n(*               channel W                                                    *)\n(* W ``^ n, W ``(| x), W ``(y | x) == definition of a discrete memoryless     *)\n(*               channel (DMC, or nth extension of the discrete memoryless    *)\n(*               channel); W(y|x) = \\Pi_i W_0(y_i|x_i) where W_0 is a         *)\n(*               probability transition matrix                                *)\n(*   `O(P, W) == output distribution for the channel                          *)\n(* `H(P `o W) == output entropy for the channel                               *)\n(* The input/output joint distribution for the channel is P `X W.             *)\n(*  `H(P , W) == the input/output joint entropy for the channel               *)\n(*  `H(W | P) == definition of conditional entropy using an input             *)\n(*               distribution and a channel                                   *)\n(*   `I(P, W) == the input/output mutual information for the channel          *)\n(*   capacity == capacity of a channel                                        *)\n(*                                                                            *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nDeclare Scope channel_scope.\nDelimit Scope fdist_scope with channel.\nLocal Open Scope channel_scope.\n\nReserved Notation \"'`Ch(' A ',' B ')'\" (at level 10, A, B at next level).\nReserved Notation \"'`Ch*(' A ',' B ')'\" (at level 10, A, B at next level).\nReserved Notation \"W '`(' b '|' a ')'\" (at level 10, b, a at next level).\nReserved Notation \"W '``^' n\" (at level 10).\nReserved Notation \"W '``(|' x ')'\" (at level 10, x at next level).\nReserved Notation \"W '``(' y '|' x ')'\" (at level 10, y, x at next level).\nReserved Notation \"'`O(' P , W )\" (at level 10, P, W at next level,\n  format \"'`O(' P ,  W )\").\nReserved Notation \"'`H(' P '`o' W )\" (at level 10, P, W at next level,\n  format \"'`H(' P  '`o'  W )\").\nReserved Notation \"`H( P , W )\" (at level 10, P, W at next level,\n  format \"`H( P ,  W )\").\nReserved Notation \"`H( W | P )\" (at level 10, W, P at next level).\nReserved Notation \"`I( P , W )\" (at level 50, format \"`I( P ,  W )\").\n\nLocal Open Scope R_scope.\n\nModule Channel1.\nSection channel1.\nVariables A B : finType.\n\nLocal Notation \"'`Ch'\" := (A -> fdist B) (only parsing).\n\nRecord chan_star := mkChan {\n  c :> `Ch ;\n  input_not_0 : (0 < #|A|)%nat }.\n\nLocal Notation \"'`Ch*'\" := (chan_star).\n\nLemma chan_star_eq (c1 c2 : `Ch*) : c c1 = c c2 -> c1 = c2.\nProof.\nmove: c1 c2 => [c1 Hc1] [c2 Hc2] /= <-{c2}; congr mkChan; exact: eq_irrelevance.\nQed.\n\nEnd channel1.\nEnd Channel1.\n\nDefinition chan_star_coercion := Channel1.c.\nCoercion chan_star_coercion : Channel1.chan_star >-> Funclass.\n\nLocal Open Scope fdist_scope.\nLocal Open Scope proba_scope.\n\nNotation \"'`Ch(' A ',' B ')'\" := (A -> {fdist B}) (only parsing) : channel_scope.\nNotation \"'`Ch*(' A ',' B ')'\" := (@Channel1.chan_star A B) : channel_scope.\nNotation \"W '`(' b '|' a ')'\" := ((W : `Ch(_, _)) a b) (only parsing) : channel_scope.\n\nLocal Open Scope proba_scope.\nLocal Open Scope vec_ext_scope.\nLocal Open Scope entropy_scope.\n\nModule DMC.\nSection def.\nLocal Open Scope ring_scope.\nVariables (A B : finType) (W : `Ch(A, B)) (n : nat).\n\nDefinition f (x : 'rV[A]_n) :=\n  [ffun y : 'rV[B]_n => (\\prod_(i < n) W `(y ``_ i | x ``_ i))].\n\nLemma f0 x y : 0 <= f x y. Proof. rewrite ffunE; exact: prodR_ge0. Qed.\n\nLemma f1 x : (\\sum_(y in 'rV_n) f x y = 1)%R.\nProof.\nset f' := fun i b => W (x ``_ i) b.\nsuff H : (\\sum_(g : {ffun 'I_n -> B}) \\prod_(i < n) f' i (g i) = 1)%R.\n  rewrite -{}[RHS]H /f'.\n  rewrite (reindex_onto (fun vb : 'rV_n => [ffun x => vb ``_ x])\n    (fun g  => \\row_(k < n) g k)) /=; last first.\n    move=> g _; apply/ffunP => /= i; by rewrite ffunE mxE.\n  apply eq_big => vb.\n  - rewrite inE.\n    apply/esym/eqP/rowP => a; by rewrite mxE ffunE.\n  - move=> _; rewrite ffunE; apply eq_bigr => i _; by rewrite ffunE.\nby rewrite -bigA_distr_bigA /= /f' big1 // => i _; rewrite FDist.f1.\nQed.\n\nDefinition c : `Ch('rV[A]_n, 'rV[B]_n) :=\n  locked (fun x => FDist.make (f0 x) (f1 x)).\n\nEnd def.\nEnd DMC.\n\nArguments DMC.c {A} {B}.\n\nNotation \"W '``^' n\" := (DMC.c W n) : channel_scope.\nNotation \"W '``(|' x ')'\" := (DMC.c W _ x) : channel_scope.\nNotation \"W '``(' y '|' x ')'\" := (DMC.c W _ x y) : channel_scope.\n\nLemma DMCE (A B : finType) n (W : `Ch(A, B)) b a :\n  W ``(b | a) = \\prod_(i < n) W (a ``_ i) (b ``_ i).\nProof. by rewrite /DMC.c; unlock; rewrite ffunE. Qed.\n\nSection DMC_sub_vec.\nVariables (A B : finType) (W : `Ch(A, B)) (n : nat) (tb : 'rV[B]_n).\n\nLemma rprod_sub_vec (D : {set 'I_n}) (t : 'rV_n) :\n  \\prod_(i < #|D|) W ((t \\# D) ``_ i) ((tb \\# D) ``_ i) =\n  \\prod_(i in D) W (t ``_ i) (tb ``_ i).\nProof.\nhave [->|/set0Pn[i iD]] := eqVneq D set0.\n  by rewrite big_set0 big_hasC //; apply/hasPn => /=; rewrite cards0; case.\npose f : 'I_n -> 'I_#|D| :=\n  fun i => match Bool.bool_dec (i \\in D) true with\n             | left H => enum_rank_in H i\n             | _ => enum_rank_in iD i\n           end.\nrewrite (reindex_onto (fun i : 'I_#|D| => enum_val i) f) /=.\n  apply: eq_big => j; last by rewrite /sub_vec 2!mxE.\n  rewrite /f /=; case: Bool.bool_dec => [a|].\n    by rewrite enum_valK_in a eqxx.\n  by rewrite enum_valP.\nmove=> j jD.\nby rewrite /f /=; case: Bool.bool_dec => [a| //]; rewrite enum_rankK_in.\nQed.\n\nLemma DMC_sub_vecE (V : {set 'I_n}) (t : 'rV_n) :\n  W ``(tb \\# V | t \\# V) = \\prod_(i in V) W (t ``_ i) (tb ``_ i).\nProof. by rewrite DMCE -rprod_sub_vec. Qed.\n\nEnd DMC_sub_vec.\n\nSection fdist_out.\nVariables (A B : finType) (P : fdist A) (W  : A -> fdist B).\n\nDefinition f := [ffun b : B => \\sum_(a in A) W a b * P a].\n\nLet f0 (b : B) : 0 <= f b.\nProof. by rewrite ffunE; apply: sumR_ge0 => a _; exact: mulR_ge0. Qed.\n\nLet f1 : \\sum_(b in B) f b = 1.\nProof.\nunder eq_bigr do rewrite ffunE /=.\nrewrite exchange_big /= -(FDist.f1 P).\nby apply eq_bigr => a _; rewrite -big_distrl /= (FDist.f1 (W a)) mul1R.\nQed.\n\nDefinition fdist_out : fdist B := locked (FDist.make f0 f1).\n\nLemma fdist_outE b : fdist_out b = \\sum_(a in A) W a b * P a.\nProof. by rewrite /fdist_out; unlock; rewrite ffunE. Qed.\n\nEnd fdist_out.\n\nNotation \"'`O(' P , W )\" := (fdist_out P W) : channel_scope.\n\nNotation \"'`H(' P '`o' W )\" := (`H ( `O( P , W ) )) : channel_scope.\n\nSection fdist_out_prop.\nVariables A B : finType.\n\nLocal Open Scope ring_scope.\nLemma fdist_rV_out (W : `Ch(A, B)) (P : fdist A) n (b : 'rV_n):\n  `O(P, W) `^ _ b =\n  \\sum_(j : 'rV[A]_n) (\\prod_(i < n) W j ``_ i b ``_ i) * P `^ _ j.\nProof.\nrewrite fdist_rVE.\nunder eq_bigr do rewrite fdist_outE.\nrewrite bigA_distr_big_dep /=.\nrewrite (reindex_onto (fun p : 'rV_n => [ffun x => p ``_ x])\n                      (fun y => \\row_(k < n) y k)) //=; last first.\n  by move=> i _; apply/ffunP => /= n0; rewrite ffunE mxE.\napply: eq_big.\n- move=> a /=; apply/andP; split; first exact/finfun.familyP.\n  by apply/eqP/rowP => a'; rewrite mxE ffunE.\n- move=> a Ha; rewrite big_split /=; congr (_ * _)%R.\n  + by apply eq_bigr => i /= _; rewrite ffunE.\n  + by rewrite fdist_rVE; apply eq_bigr => i /= _; rewrite ffunE.\nQed.\nLocal Close Scope ring_scope.\n\nLemma fdistX_prod_out (W : `Ch(A, B)) (P : fdist A) : (fdistX (P `X W))`1 = `O(P, W).\nProof.\nrewrite fdistX1; apply/fdist_ext => b; rewrite fdist_outE fdist_sndE.\nby under eq_bigr do rewrite fdist_prodE mulRC.\nQed.\n\nEnd fdist_out_prop.\n\nSection Pr_fdist_prod.\nVariables (A B : finType) (P : fdist A) (W : `Ch(A, B)) (n : nat).\n\nLemma Pr_DMC_rV_prod (Q : 'rV_n * 'rV_n -> bool) :\n  Pr (((P `^ n) `X (W ``^ n))) [set x | Q x] =\n  Pr ((P `X W) `^ n)           [set x | Q (rV_prod x)].\nProof.\nrewrite /Pr [RHS]big_rV_prod /=; apply: eq_big => y.\n  by rewrite !inE prod_rVK.\nrewrite inE => Qy; rewrite fdist_prodE DMCE fdist_rVE -big_split /= fdist_rVE.\napply: eq_bigr => i /= _.\nby rewrite fdist_prodE -snd_tnth_prod_rV -fst_tnth_prod_rV.\nQed.\n\nLemma Pr_DMC_fst (Q : 'rV_n -> bool) :\n  Pr ((P `X W) `^ n) [set x | Q (rV_prod x).1 ] =\n  Pr P `^ n          [set x | Q x].\nProof.\nrewrite {1}/Pr big_rV_prod /= -(pair_big_fst _ _ [pred x | Q x]) //=; last first.\n  move=> t /=.\n  rewrite SetDef.pred_of_setE /= SetDef.finsetE /= ffunE. (* TODO: clean? *)\n  congr (Q _).\n  by apply/rowP => a; rewrite !mxE.\ntransitivity (\\sum_(i | Q i) P `^ n i * (\\sum_(y in 'rV[B]_n) W ``(y | i))).\n  apply: eq_bigr => ta Sta; rewrite big_distrr; apply: eq_bigr => tb _ /=.\n  rewrite DMCE [in RHS]fdist_rVE -[in RHS]big_split /= fdist_rVE.\n  by apply eq_bigr => j _; rewrite fdist_prodE /= -fst_tnth_prod_rV -snd_tnth_prod_rV.\ntransitivity (\\sum_(i | Q i) P `^ _ i).\n  by apply eq_bigr => i _; rewrite (FDist.f1 (W ``(| i))) mulR1.\nby rewrite /Pr; apply eq_bigl => t; rewrite !inE.\nQed.\n\nLocal Open Scope ring_scope.\nLemma Pr_DMC_out m (S : {set 'rV_m}) :\n  Pr ((P `X W) `^ m) [set x | (rV_prod x).2 \\notin S] =\n  Pr (`O(P , W) `^ m) (~: S).\nProof.\nrewrite {1}/Pr big_rV_prod /= -(pair_big_snd _ _ [pred x | x \\notin S]) //=; last first.\n  move=> tab /=.\n  rewrite SetDef.pred_of_setE /= SetDef.finsetE /= ffunE. (* TODO: clean *)\n  do 2 f_equal.\n  by apply/rowP => a; rewrite !mxE.\nrewrite /= /Pr /= exchange_big /=; apply: eq_big => tb; first by rewrite !inE.\nmove=> Htb.\nrewrite fdist_rVE.\nunder [RHS]eq_bigr do rewrite fdist_outE.\nrewrite bigA_distr_bigA /=.\nrewrite (reindex_onto (fun p : 'rV[A]_m => [ffun x => p ord0 x])\n    (fun y : {ffun 'I_m -> A} => \\row_(i < m) y i)) /=; last first.\n  by move=> f _; apply/ffunP => /= m0; rewrite ffunE mxE.\napply: eq_big => ta.\n  by rewrite inE; apply/esym/eqP/rowP => a; rewrite mxE ffunE.\nmove=> Hta.\nrewrite fdist_rVE /=; apply eq_bigr => l _.\nby rewrite fdist_prodE -fst_tnth_prod_rV -snd_tnth_prod_rV ffunE mulRC.\nQed.\nLocal Close Scope ring_scope.\n\nEnd Pr_fdist_prod.\n\nLemma channel_jcPr (A B : finType) (W : `Ch(A, B)) (P : fdist A) a b :\n  P a != 0 ->\n  W a b = \\Pr_(fdistX (P `X W))[ [set b] | [set a] ].\nProof. by move=> Pa0; rewrite jcPr_fdistX_prod//; exact/eqP. Qed.\n\nNotation \"`H( P , W )\" := (`H (P `X W)) : channel_scope.\n\nSection conditional_entropy_chan.\nVariables (A B : finType) (W : `Ch(A, B)) (P : fdist A).\n\nDefinition cond_entropy_chan := `H(P, W) - `H P.\nEnd conditional_entropy_chan.\n\nNotation \"`H( W | P )\" := (cond_entropy_chan W P) : channel_scope.\n\nSection condentropychan_prop.\nVariables (A B : finType) (W : `Ch(A, B)) (P : fdist A).\n\nLemma cond_entropy_chanE : `H(W | P) = cond_entropy (fdistX (P `X W)).\nProof.\nrewrite /cond_entropy_chan.\nhave := chain_rule (P `X W); rewrite /joint_entropy => ->.\nby rewrite fdist_prod1 addRC addRK.\nQed.\n\nLemma cond_entropy_chanE2 : `H(W | P) = \\sum_(a in A) P a * `H (W a).\nProof.\nrewrite cond_entropy_chanE cond_entropyE big_morph_oppR; apply: eq_bigr => a _.\nrewrite big_morph_oppR /entropy mulRN -mulNR big_distrr/=; apply: eq_bigr => b _.\nrewrite fdistXI fdist_prodE /= mulNR mulRA; congr (- _).\nhave [->|Pa0] := eqVneq (P a) 0; first by rewrite !(mulR0,mul0R).\nby rewrite -channel_jcPr.\nQed.\n\nEnd condentropychan_prop.\n\nSection mutual_info_chan.\nLocal Open Scope fdist_scope.\nVariables A B : finType.\n\nDefinition mutual_info_dist (P : {fdist A * B}) := `H P`1 + `H P`2 - `H P.\n\nDefinition mutual_info_chan P (W : `Ch(A, B)) := `H P + `H(P `o W) - `H(P , W).\n\nEnd mutual_info_chan.\n\nNotation \"`I( P , W )\" := (mutual_info_chan P W) : channel_scope.\n\nSection mutual_info_chan_prop.\nVariables (A B : finType) (W : `Ch(A, B)) (P : fdist A).\n\nLemma mutual_info_chanE : `I(P, W) = mutual_info (fdistX (P `X W)).\nProof.\nrewrite /mutual_info_chan mutual_infoE -cond_entropy_chanE.\nby rewrite -[in RHS]addR_opp oppRB addRCA addRA fdistX_prod_out.\nQed.\n\nEnd mutual_info_chan_prop.\n\nFrom mathcomp Require Import classical_sets.\nLocal Open Scope classical_set_scope.\n\nDefinition capacity (A B : finType) (W : `Ch(A, B)) :=\n  reals.sup [set `I(P, W) | P in [set: fdist A]].\n", "meta": {"author": "affeldt-aist", "repo": "infotheo", "sha": "5f9efb859dbadcbcae2330e2e21e76f9b632d879", "save_path": "github-repos/coq/affeldt-aist-infotheo", "path": "github-repos/coq/affeldt-aist-infotheo/infotheo-5f9efb859dbadcbcae2330e2e21e76f9b632d879/information_theory/channel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6534284649488825}}
{"text": "(** Simple Policy Optimizer based on Smart Constructors.\n    This example nicely illustrates fully automatic axiomatic reasoning *)\n\nRequire Export NetKAT.\n\nModule Optimize (F : FIELDSPEC) (V : VALUESPEC(F)).\n\nInclude NetKAT.NetKAT(F)(V).\n\nDefinition mk_union (p1 p2 : policy) :=\n  match p1,p2 with\n    | Drop, _ => p2\n    | _, Drop => p1\n    | _,_ => p1 + p2\n  end.\n\nDefinition mk_seq (p1 p2 : policy) :=\n  match p1,p2 with\n    | Drop, _\n    | _, Drop => Drop\n    | Id, _ => p2\n    | _, Id => p1\n    | _, _ => p1;; p2\n  end.\n\nFixpoint mk_star (p : policy) :=\n  match p with\n    | Drop\n    | Id => Id\n    | q* => mk_star q \n    | _ => p*\n  end.\n\nFixpoint optimize (p : policy) :=\n  match p with\n    | p1 + p2 => mk_union (optimize p1) (optimize p2)\n    | p1;; p2 => mk_seq (optimize p1) (optimize p2)\n    | p0* => mk_star (optimize p0)\n    | _ => p\n  end.\n\n\n\nLemma mk_union_sound: forall p q : policy, mk_union p q === p + q.\nProof. netkat_cases. Qed.\n\nLemma mk_seq_sound: forall p q : policy, mk_seq p q === p;;q.\nProof. netkat_cases. Qed.\n\nLemma star_zero: Drop* === Id.\nProof. rewrite <- ka_unroll_l. netkat. Qed.\nHint Rewrite star_zero : netkat.\n\nLemma star_one_aux: forall n h, eq (power n [|Id|] h) ([|Id|] h).\nProof.\n  induction n; intros h h'; intuition.\n  simpl in H. destruct H as [h'' [H0 H1]].\n  + apply IHn in H1. congruence.\n  + simpl. exists h. intuition. apply IHn. assumption.\nQed.\n\nLemma star_one: Id* === Id.\nProof.\n  intros h h'.\n  split; intros H.\n  destruct H as [n].\n  apply (star_one_aux n h). assumption.\n  exists 0. simpl. apply H.\nQed.\nHint Rewrite star_one : netkat.\n\nLemma star_star p: p * * === p*.\nProof.\n  intro h. split; intro H;\n  destruct H as [n H]; generalize dependent x; generalize dependent h;\n  induction n; intros.\n  - exists 0. auto.\n  - repeat destruct H.\n    assert ([|p*|] x0 x) by eauto.\n    destruct H1 as [m H1].\n    exists ((x1 + m)%nat).\n    apply power_decompose.\n    exists x0; intuition.\n  - exists 0. auto.\n  - simpl in H. destruct H as [h'' [H0 H1]].\n    assert (H2 := IHn _ _ H1); clear IHn H1 n.\n    destruct H2 as [n]. exists (S n). simpl. exists h''.\n    intuition. exists 1. simpl. exists h''; auto.\nQed.\nHint Rewrite star_star : netkat.\n  \n\nLemma mk_star_sound p: mk_star p === p*.\nProof. netkat_induction p. Qed.\n\nHint Rewrite mk_union_sound mk_seq_sound mk_star_sound : netkat.\n\nTheorem optimize_sound p: optimize p === p.\nProof. netkat_induction p. Qed.\n\n\nEnd Optimize.", "meta": {"author": "smolkaj", "repo": "coq-netkat", "sha": "9d3342218b309a3a50a0716f3e2749ed58cca0cb", "save_path": "github-repos/coq/smolkaj-coq-netkat", "path": "github-repos/coq/smolkaj-coq-netkat/coq-netkat-9d3342218b309a3a50a0716f3e2749ed58cca0cb/Optimize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.653428454728821}}
{"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(** Definition of a square root function for Z. *)\n\nRequire Import BinPos BinInt Psqrt.\n\nLocal Open Scope Z_scope.\n\nDefinition Zsqrtrem n :=\n match n with\n  | 0 => (0, 0)\n  | Zpos p =>\n    match Psqrtrem p with\n     | (s, IsPos r) => (Zpos s, Zpos r)\n     | (s, _) => (Zpos s, 0)\n    end\n  | Zneg _ => (0,0)\n end.\n\nDefinition Zsqrt n :=\n match n with\n  | 0 => 0\n  | Zpos p => Zpos (Psqrt p)\n  | Zneg _ => 0\n end.\n\nLemma Zsqrtrem_spec : forall n, 0<=n ->\n let (s,r) := Zsqrtrem n in n = s*s + r /\\ 0 <= r <= 2*s.\nProof.\n destruct n. now repeat split.\n generalize (Psqrtrem_spec p). simpl.\n destruct 1; simpl; subst; now repeat split.\n now destruct 1.\nQed.\n\nLemma Zsqrt_spec : forall n, 0<=n ->\n let s := Zsqrt n in s*s <= n < (Zsucc s)*(Zsucc s).\nProof.\n destruct n. now repeat split. unfold Zsqrt.\n rewrite <- Zpos_succ_morphism. intros _. apply (Psqrt_spec p).\n now destruct 1.\nQed.\n\nLemma Zsqrt_neg : forall n, n<0 -> Zsqrt n = 0.\nProof.\n intros. now destruct n.\nQed.\n\nLemma Zsqrtrem_sqrt : forall n, fst (Zsqrtrem n) = Zsqrt n.\nProof.\n destruct n; try reflexivity.\n unfold Zsqrtrem, Zsqrt, Psqrt.\n destruct (Psqrtrem p) as (s,r). now destruct r.\nQed.", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/ZArith/Zsqrt_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6534284491146021}}
{"text": "Require Import init.\n\nRequire Export mult_ring.\n\n#[universes(template)]\nClass Div U := {\n    div : U → U\n}.\n\nNotation \"/ a\" := (div a) : algebra_scope.\nNotation \"a / b\" := (a * /b) : algebra_scope.\n\nClass MultLinv U `{Zero U, Mult U, One U, Div U} := {\n    mult_linv : ∀ a, 0 ≠ a → /a * a = 1\n}.\nClass MultRinv U `{Zero U, Mult U, One U, Div U} := {\n    mult_rinv : ∀ a, 0 ≠ a → a / a = 1\n}.\n\nClass FieldBase U `{\n    FM : AllMult U,\n    UD : Div U,\n    UMD : @MultLinv U UZ UM UE UD,\n    UMDR : @MultRinv U UZ UM UE UD\n}.\n\nClass Field U `{\n    FF : FieldBase U,\n    NotTrivial U\n}.\n\nClass HomomorphismDiv {U V} `{Zero U, Div U, Div V} (f : U → V) := {\n    homo_div : ∀ a, 0 ≠ a → f (/a) = /f a\n}.\n\n(* begin hide *)\nArguments div : simpl never.\n\nSection FieldImply1.\n\nContext {U} `{Field U}.\n\nGlobal Instance mult_linv_rinv : MultRinv U.\nProof.\n    split.\n    intros a a_nz.\n    rewrite mult_comm.\n    apply mult_linv.\n    exact a_nz.\nQed.\n\nEnd FieldImply1.\n\nSection FieldImply2.\n\nContext {U} `{Field U}.\n\nGlobal Instance mult_linv_lcancel : MultLcancel U.\nProof.\n    split.\n    intros a b c c_nz eq.\n    apply lmult with (/c) in eq.\n    do 2 rewrite mult_assoc in eq.\n    rewrite mult_linv in eq by exact c_nz.\n    do 2 rewrite mult_lid in eq.\n    exact eq.\nQed.\n\nGlobal Instance mult_rinv_rcancel : MultRcancel U.\nProof.\n    split.\n    intros a b c c_nz eq.\n    apply rmult with (/c) in eq.\n    do 2 rewrite <- mult_assoc in eq.\n    rewrite mult_rinv in eq by exact c_nz.\n    do 2 rewrite mult_rid in eq.\n    exact eq.\nQed.\n\nEnd FieldImply2.\n\nSection Field.\n\nContext {U} `{Field U}.\n\n(* end hide *)\nTheorem div_nz : ∀ a, 0 ≠ a → 0 ≠ /a.\nProof.\n    intros a a_nz eq.\n    apply rmult with a in eq.\n    rewrite mult_lanni in eq.\n    rewrite mult_linv in eq by exact a_nz.\n    exact (not_trivial_one eq).\nQed.\n\nTheorem div_div : ∀ a, 0 ≠ a → /(/a) = a.\nProof.\n    intros a a_nz.\n    pose proof (div_nz a a_nz) as a'_nz.\n    apply mult_lcancel with (/a); [>exact a'_nz|].\n    rewrite mult_linv by exact a_nz.\n    rewrite mult_rinv by exact a'_nz.\n    reflexivity.\nQed.\n\nTheorem mult_rrinv : ∀ a b, 0 ≠ b → a * b / b = a.\nProof.\n    intros a b b_nz.\n    rewrite <- mult_assoc.\n    rewrite mult_rinv by exact b_nz.\n    apply mult_rid.\nQed.\nTheorem mult_rlinv : ∀ a b, 0 ≠ b → a / b * b = a.\nProof.\n    intros a b b_nz.\n    rewrite <- mult_assoc.\n    rewrite mult_linv by exact b_nz.\n    apply mult_rid.\nQed.\nTheorem mult_lrinv : ∀ a b, 0 ≠ b → b * (/b * a) = a.\nProof.\n    intros a b b_nz.\n    rewrite mult_assoc.\n    rewrite mult_rinv by exact b_nz.\n    apply mult_lid.\nQed.\nTheorem mult_llinv : ∀ a b, 0 ≠ b → /b * (b * a) = a.\nProof.\n    intros a b b_nz.\n    rewrite mult_assoc.\n    rewrite mult_linv by exact b_nz.\n    apply mult_lid.\nQed.\n\nTheorem mult_llmove : ∀ a b c, 0 ≠ a → a * b = c ↔ b = /a * c.\nProof.\n    intros a b c a_nz.\n    split; intros eq.\n    -   apply lmult with (/a) in eq.\n        rewrite mult_llinv in eq by exact a_nz.\n        exact eq.\n    -   apply lmult with a in eq.\n        rewrite mult_lrinv in eq by exact a_nz.\n        exact eq.\nQed.\nTheorem mult_lrmove : ∀ a b c, 0 ≠ b → a * b = c ↔ a = c / b.\nProof.\n    intros a b c b_nz.\n    split; intros eq.\n    -   apply rmult with (/b) in eq.\n        rewrite mult_rrinv in eq by exact b_nz.\n        exact eq.\n    -   apply rmult with b in eq.\n        rewrite mult_rlinv in eq by exact b_nz.\n        exact eq.\nQed.\nTheorem mult_rlmove : ∀ a b c, 0 ≠ b → a = b * c ↔ /b * a = c.\nProof.\n    intros a b c b_nz.\n    split; intros eq.\n    -   apply lmult with (/b) in eq.\n        rewrite mult_llinv in eq by exact b_nz.\n        exact eq.\n    -   apply lmult with b in eq.\n        rewrite mult_lrinv in eq by exact b_nz.\n        exact eq.\nQed.\nTheorem mult_rrmove : ∀ a b c, 0 ≠ c → a = b * c ↔ a / c = b.\nProof.\n    intros a b c c_nz.\n    split; intros eq.\n    -   apply rmult with (/c) in eq.\n        rewrite mult_rrinv in eq by exact c_nz.\n        exact eq.\n    -   apply rmult with c in eq.\n        rewrite mult_rlinv in eq by exact c_nz.\n        exact eq.\nQed.\n\nTheorem mult_1_ab_da_b : ∀ a b, 0 ≠ a → 1 = a * b ↔ /a = b.\nProof.\n    intros a b a_nz.\n    rewrite mult_rlmove by exact a_nz.\n    rewrite mult_rid.\n    reflexivity.\nQed.\nTheorem mult_1_ab_db_a : ∀ a b, 0 ≠ b → 1 = a * b ↔ /b = a.\nProof.\n    intros a b b_nz.\n    rewrite mult_rrmove by exact b_nz.\n    rewrite mult_lid.\n    reflexivity.\nQed.\nTheorem mult_1_ab_a_db : ∀ a b, 0 ≠ b → 1 = a * b ↔ a = /b.\nProof.\n    intros a b b_nz.\n    rewrite mult_rrmove by exact b_nz.\n    rewrite mult_lid.\n    apply eq_iff.\nQed.\nTheorem mult_1_ab_b_da : ∀ a b, 0 ≠ a → 1 = a * b ↔ b = /a.\nProof.\n    intros a b a_nz.\n    rewrite mult_rlmove by exact a_nz.\n    rewrite mult_rid.\n    apply eq_iff.\nQed.\n\nTheorem mult_1_a_ab_b : ∀ a b, 0 ≠ b → 1 = a ↔ a * b = b.\nProof.\n    intros a b b_nz.\n    rewrite mult_lrmove by exact b_nz.\n    rewrite mult_rinv by exact b_nz.\n    apply eq_iff.\nQed.\nTheorem mult_1_a_ba_b : ∀ a b, 0 ≠ b → 1 = a ↔ b * a = b.\nProof.\n    intros a b b_nz.\n    rewrite mult_llmove by exact b_nz.\n    rewrite mult_linv by exact b_nz.\n    apply eq_iff.\nQed.\nTheorem mult_1_a_b_ab : ∀ a b, 0 ≠ b → 1 = a ↔ b = a * b.\nProof.\n    intros a b b_nz.\n    rewrite mult_rrmove by exact b_nz.\n    rewrite mult_rinv by exact b_nz.\n    reflexivity.\nQed.\nTheorem mult_1_a_b_ba : ∀ a b, 0 ≠ b → 1 = a ↔ b = b * a.\nProof.\n    intros a b b_nz.\n    rewrite mult_rlmove by exact b_nz.\n    rewrite mult_linv by exact b_nz.\n    reflexivity.\nQed.\n\nTheorem mult_1_dab_a_b : ∀ a b, 0 ≠ a → 1 = /a * b ↔ a = b.\nProof.\n    intros a b a_nz.\n    rewrite mult_1_ab_da_b by (apply div_nz; exact a_nz).\n    rewrite div_div by exact a_nz.\n    reflexivity.\nQed.\nTheorem mult_1_adb_a_b : ∀ a b, 0 ≠ b → 1 = a / b ↔ a = b.\nProof.\n    intros a b b_nz.\n    rewrite mult_1_ab_a_db by (apply div_nz; exact b_nz).\n    rewrite div_div by exact b_nz.\n    reflexivity.\nQed.\nTheorem mult_1_dab_b_a : ∀ a b, 0 ≠ a → 1 = /a * b ↔ b = a.\nProof.\n    intros a b a_nz.\n    rewrite mult_1_ab_b_da by (apply div_nz; exact a_nz).\n    rewrite div_div by exact a_nz.\n    reflexivity.\nQed.\nTheorem mult_1_adb_b_a : ∀ a b, 0 ≠ b → 1 = a / b ↔ b = a.\nProof.\n    intros a b b_nz.\n    rewrite mult_1_ab_db_a by (apply div_nz; exact b_nz).\n    rewrite div_div by exact b_nz.\n    reflexivity.\nQed.\n\nTheorem neg_div : ∀ a, 0 ≠ a → /(-a) = -/a.\nProof.\n    intros a a_nz.\n    pose proof (land (neg_nz _) a_nz) as na_nz.\n    apply mult_rcancel with (-a); [>exact na_nz|].\n    rewrite mult_linv by exact na_nz.\n    rewrite mult_lneg, mult_rneg, neg_neg.\n    rewrite mult_linv by exact a_nz.\n    reflexivity.\nQed.\n\nTheorem div_mult : ∀ a b, 0 ≠ a → 0 ≠ b → /(a * b) = /a * /b.\nProof.\n    intros a b a_nz b_nz.\n    apply mult_lcancel with a; [>exact a_nz|].\n    rewrite mult_lrinv by exact a_nz.\n    apply mult_lcancel with b; [>exact b_nz|].\n    rewrite mult_rinv by exact b_nz.\n    rewrite mult_assoc, (mult_comm b).\n    rewrite mult_rinv; [>reflexivity|].\n    apply mult_nz; assumption.\nQed.\n\nTheorem div_one : /1 = 1.\nProof.\n    rewrite <- (mult_lid (/1)).\n    classic_case (0 = 1) as [triv|ntriv].\n    -   rewrite <- triv.\n        apply mult_lanni.\n    -   rewrite mult_rinv by exact ntriv.\n        reflexivity.\nQed.\n\n(* begin hide *)\nEnd Field.\n\nSection MultHomo.\n\nContext {U V} `{Field U, Field 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    @HomomorphismDiv U V UZ UD UD0 f\n}.\n\nGlobal Instance field_inj : Injective f.\nProof.\n    apply (homo_zero_inj _).\n    intros a eq.\n    classic_contradiction a_nz.\n    apply (lmult (f (/a))) in eq.\n    rewrite mult_ranni in eq.\n    rewrite <- homo_mult in eq.\n    rewrite mult_linv in eq by exact a_nz.\n    rewrite homo_one in eq.\n    contradiction (not_trivial_one eq).\nQed.\nLocal Remove Hints field_inj : typeclass_instances.\n\nGlobal Instance field_homo_div : HomomorphismDiv f.\nProof.\n    split.\n    intros a a_nz.\n    pose proof (inj_zero _ a_nz) as fa_nz.\n    apply (mult_lcancel (f a) fa_nz).\n    rewrite <- homo_mult.\n    do 2 rewrite mult_rinv by assumption.\n    apply homo_one.\nQed.\nLocal Remove Hints field_homo_div : typeclass_instances.\n\n(* begin hide *)\nEnd MultHomo.\n(* end hide *)\nTactic Notation \"mult_cancel_left\" constr(x) :=\n    mult_bring_left x;\n    apply lmult.\nTactic Notation \"mult_cancel_left\" constr(x) \"in\" ident(H) :=\n    mult_bring_left x in H;\n    apply mult_lcancel in H.\nTactic Notation \"mult_cancel_right\" constr(x) :=\n    mult_bring_right x;\n    apply rmult.\nTactic Notation \"mult_cancel_right\" constr(x) \"in\" ident(H) :=\n    mult_bring_right x in H;\n    apply mult_rcancel 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_field.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.7520125793176223, "lm_q1q2_score": 0.6533686751958607}}
{"text": "Require Export SpecSyntax.\nSet Implicit Arguments.\n\n(******************************************************************************)\n(* Shifting                                                                   *)\n(******************************************************************************)\n\nFixpoint shiftIndex (c : nat) (i : nat) : nat :=\n  match c with\n    | O   => S i\n    | S c =>\n      match i with\n        | O   => O\n        | S i => S (shiftIndex c i)\n      end\n  end.\n\nFixpoint tshiftTy (c : nat) (T : Ty) : Ty :=\n  match T with\n    | tvar X      => tvar (shiftIndex c X)\n    | top         => top\n    | tarr T1 T2  => tarr (tshiftTy c T1) (tshiftTy c T2)\n    | tall T1 T2  => tall (tshiftTy c T1) (tshiftTy (S c) T2)\n    | tprod T1 T2 => tprod (tshiftTy c T1) (tshiftTy c T2)\n  end.\n\nFixpoint tshiftTm (c : nat) (t : Tm) : Tm :=\n  match t with\n  | var x        => var x\n  | abs T1 t2    => abs (tshiftTy c T1) (tshiftTm c t2)\n  | app t1 t2    => app (tshiftTm c t1) (tshiftTm c t2)\n  | tabs T1 t2   => tabs (tshiftTy c T1) (tshiftTm (S c) t2)\n  | tapp t1 T2   => tapp (tshiftTm c t1) (tshiftTy c T2)\n  | prod t1 t2   => prod (tshiftTm c t1) (tshiftTm c t2)\n  | lett p t1 t2 => lett p (tshiftTm c t1) (tshiftTm c t2)\n  end.\n\nFixpoint shiftTm (c : nat) (t : Tm) : Tm :=\n  match t with\n  | var x        => var (shiftIndex c x)\n  | abs T1 t2    => abs T1 (shiftTm (S c) t2)\n  | app t1 t2    => app (shiftTm c t1) (shiftTm c t2)\n  | tabs T1 t2   => tabs T1 (shiftTm c t2)\n  | tapp t1 T2   => tapp (shiftTm c t1) T2\n  | prod t1 t2   => prod (shiftTm c t1) (shiftTm c t2)\n  | lett p t1 t2 => lett p (shiftTm c t1) (shiftTm (bindPat p + c) t2)\n  end.\n\nFixpoint weakenTm (t : Tm) (k : nat) : Tm :=\n  match k with\n    | O   => t\n    | S k => shiftTm O (weakenTm t k)\n  end.\n\nFixpoint tshiftExt (c : nat) (Δ : Ext) : Ext :=\n  match Δ with\n    | exempty    => exempty\n    | exvar Δ T  => exvar (tshiftExt c Δ) (tshiftTy c T)\n  end.\n\n(******************************************************************************)\n(* Type substitution.                                                         *)\n(******************************************************************************)\n\nFixpoint tsubstIndex (X : nat) (T' : Ty) (Y : nat) : Ty :=\n  match X , Y with\n    | O   , O   => T'\n    | O   , S Y => tvar Y\n    | S X , O   => tvar O\n    | S X , S Y => tshiftTy 0 (tsubstIndex X T' Y)\n  end.\n\nFixpoint tsubstTy (X : nat) (T' : Ty) (T : Ty) : Ty :=\n  match T with\n    | tvar Y      => tsubstIndex X T' Y\n    | top         => top\n    | tarr T1 T2  => tarr (tsubstTy X T' T1) (tsubstTy X T' T2)\n    | tall T1 T2  => tall (tsubstTy X T' T1) (tsubstTy (S X) T' T2)\n    | tprod T1 T2 => tprod (tsubstTy X T' T1) (tsubstTy X T' T2)\n  end.\n\nFixpoint tsubstTm (X : nat) (T' : Ty) (t : Tm) : Tm :=\n  match t with\n  | var x        => var x\n  | abs T1 t2    => abs  (tsubstTy X T' T1) (tsubstTm X T' t2)\n  | app t1 t2    => app  (tsubstTm X T' t1) (tsubstTm X T' t2)\n  | tabs T1 t2   => tabs (tsubstTy X T' T1) (tsubstTm (S X) T' t2)\n  | tapp t1 T2   => tapp (tsubstTm X T' t1) (tsubstTy X T' T2)\n  | prod t1 t2   => prod (tsubstTm X T' t1) (tsubstTm X T' t2)\n  | lett p t1 t2 => lett p (tsubstTm X T' t1) (tsubstTm X T' t2)\n  end.\n\nFixpoint tsubstExt (X : nat) (T' : Ty) (Δ : Ext) : Ext :=\n  match Δ with\n    | exempty    => exempty\n    | exvar Δ T  => exvar (tsubstExt X T' Δ) (tsubstTy X T' T)\n  end.\n\n(******************************************************************************)\n(* Term substitutions.                                                        *)\n(******************************************************************************)\n\nInductive Subst : Set :=\n  | sub_here  : Subst\n  | sub_var   : Subst → Subst\n  | sub_bound : Subst → Subst.\n\nFixpoint weaken_subst (sub : Subst) (k : nat) : Subst :=\n  match k with\n   | O   => sub\n   | S k => sub_var (weaken_subst sub k)\n  end.\n\nFixpoint substIndex (x : Subst) (t : Tm) (y : nat) : Tm :=\n  match x , y with\n    | sub_here    , O   => t\n    | sub_here    , S y => var y\n    | sub_var x   , O   => var O\n    | sub_var x   , S y => shiftTm O (substIndex x t y)\n    | sub_bound x , y   => tshiftTm O (substIndex x t y)\n  end.\n\nFixpoint substTm (x : Subst) (t' : Tm) (t : Tm) : Tm :=\n  match t with\n    | var y        => substIndex x t' y\n    | abs T1 t2    => abs T1 (substTm (sub_var x) t' t2)\n    | app t1 t2    => app (substTm x t' t1) (substTm x t' t2)\n    | tabs T1 t2   => tabs T1 (substTm (sub_bound x) t' t2)\n    | tapp t1 T2   => tapp (substTm x t' t1) T2\n    | prod t1 t2   => prod (substTm x t' t1) (substTm x t' t2)\n    | lett p t1 t2 => lett p (substTm x t' t1)\n                        (substTm (weaken_subst x (bindPat p)) t' t2)\n  end.\n\n(******************************************************************************)\n(* Context extension.                                                         *)\n(******************************************************************************)\n\nFixpoint extend (Γ : Env) (Δ : Ext) : Env :=\n  match Δ with\n    | exempty     => Γ\n    | exvar Δ T   => evar (extend Γ Δ) T\n  end.\n\nFixpoint append (Δ1 Δ2 : Ext) : Ext :=\n  match Δ2 with\n    | exempty    => Δ1\n    | exvar Δ2 T => exvar (append Δ1 Δ2) T\n  end.\n\nFixpoint lengthExt (Δ : Ext) : nat :=\n  match Δ with\n    | exempty   => 0\n    | exvar Δ _ => 1 + lengthExt Δ\n  end.\n\n(******************************************************************************)\n(* Context lookups.                                                           *)\n(******************************************************************************)\n\nInductive lookup_etvar : Env → nat → Ty → Prop :=\n  | gb_here {Γ T} :\n      lookup_etvar (etvar Γ T) O (tshiftTy O T)\n  | gb_var {Γ T T' X} :\n      lookup_etvar Γ X T →\n      lookup_etvar (evar Γ T') X T\n  | gb_bound {Γ T T' X} :\n      lookup_etvar Γ X T →\n      lookup_etvar (etvar Γ T') (S X) (tshiftTy O T).\nHint Constructors lookup_etvar.\n\nInductive lookup_evar : Env → nat → Ty → Prop :=\n  | gv_here {Γ T} :\n      lookup_evar (evar Γ T) O T\n  | gv_var {Γ T T' X} :\n      lookup_evar Γ X T →\n      lookup_evar (evar Γ T') (S X) T\n  | gv_bound {Γ T T' X} :\n      lookup_evar Γ X T →\n      lookup_evar (etvar Γ T') X (tshiftTy O T).\nHint Constructors lookup_evar.\n\n(******************************************************************************)\n(* Well-formedness.                                                           *)\n(******************************************************************************)\n\n(* These LoC shouldn't be counted here.. *)\nInductive wfTy (Γ: Env) : Ty → Prop :=\n  | wf_tvar {X T} :\n      lookup_etvar Γ X T → wfTy Γ (tvar X)\n  | wf_top :\n      wfTy Γ top\n  | wf_tarr {T1 T2}:\n      wfTy Γ T1 → wfTy Γ T2 → wfTy Γ (tarr T1 T2)\n  | wf_tall {T1 T2} :\n      wfTy Γ T1 → wfTy (etvar Γ T1) T2 →\n      wfTy Γ (tall T1 T2)\n  | wf_tprod {T1 T2}:\n      wfTy Γ T1 → wfTy Γ T2 → wfTy Γ (tprod T1 T2).\nHint Constructors wfTy.\n", "meta": {"author": "Blaisorblade", "repo": "knot-esop-2017-case-study", "sha": "cf541cb38a483a514474f4c948bf005bc49b1e6f", "save_path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study", "path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study/knot-esop-2017-case-study-cf541cb38a483a514474f4c948bf005bc49b1e6f/casestudy/manual/fsubprod/BoilerplateFunctions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6533686703670735}}
{"text": "Require Import Coq.Lists.List Coq.Bool.Bool Coq.Structures.OrderedType Coq.Classes.Morphisms Coq.Setoids.Setoid.\nRequire Export Fiat.Common.Coq__8_4__8_5__Compat.\n\nDefinition SetEq {A: Type} (seq1: list A) (seq2: list A) :=\n  forall x,\n    List.In x seq1 <-> List.In x seq2.\n\nLemma SetEq_rewrite :\n  forall {A: Type} (seq1 seq2: list A),\n    SetEq seq1 seq2 <-> forall a, List.In a seq1 <-> List.In a seq2.\n  unfold SetEq; tauto.\nQed.\n\nLtac autospecialize :=\n  repeat match goal with\n           | [ H: forall _, _ |- List.In ?x _ ] => try specialize (H x)\n         end.\n\nLemma SetEq_Reflexive :\n  forall {A: Type}, forall (x: list A), SetEq x x.\nProof.\n  unfold Reflexive, SetEq;\n  intuition;\n  autospecialize;\n  intuition.\nQed.\n\nLemma SetEq_Symmetric :\n  forall {A: Type}, forall (x y: list A), SetEq x y -> SetEq y x.\nProof.\n  unfold Symmetric, SetEq;\n  intuition; autospecialize; intuition.\nQed.\n\nLemma SetEq_Transitive :\n  forall {A: Type}, forall (x y z: list A), SetEq x y -> SetEq y z -> SetEq x z.\nProof.\n  unfold Transitive, SetEq;\n  intuition; autospecialize; intuition.\nQed.\n\nLtac seteq_equivalence :=\n  eauto using SetEq_Transitive, SetEq_Symmetric, SetEq_Reflexive.\n\nLemma SetEq_Equivalence:\n  forall {A: Type}, Equivalence (SetEq (A:=A)).\nProof.\n  intros; constructor; seteq_equivalence.\nQed.\n\nLemma SetEq_Symmetric_iff:\n  forall {A: Type}, forall (x y: list A), SetEq x y <-> SetEq y x.\nProof.\n  split; seteq_equivalence.\nQed.\n\nLemma SetEq_trans_iff:\n  forall {A: Type} (seq1 seq1' seq2: list A),\n    SetEq seq1 seq1' ->\n    (SetEq seq1 seq2 <-> SetEq seq1' seq2).\nProof.\n  intuition; seteq_equivalence.\nQed.\n\nLemma SetEq_trans_iff_2:\n  forall {A: Type} (seq1 seq2 seq2': list A),\n    SetEq seq2 seq2' ->\n    (SetEq seq1 seq2 <-> SetEq seq1 seq2').\nProof.\n  intuition; seteq_equivalence.\nQed.\n\n\nDefinition SetUnion {A: Type} (x y: list A) := (x ++ y)%list.\n\nLemma union_left :\n  forall {A: Type} (x: A) (seq1 seq2: list A),\n    SetEq (SetUnion (x::seq1) seq2) (x :: (SetUnion seq1 seq2)).\nProof.\n  intros; unfold SetEq, SetUnion; intuition.\nQed.\n\nLemma union_right :\n  forall {A: Type} (x: A) (seq1 seq2: list A),\n    SetEq (SetUnion seq1 (x::seq2)) (x :: (SetUnion seq1 seq2)).\nProof.\n  intros; unfold SetEq, SetUnion; intuition;\n  repeat (rewrite in_app_iff in *; simpl in *);\n  intuition.\nQed.\n\nLemma filter_union :\n  forall {A: Type} (seq1 seq2: list A),\n  forall (pred: A -> bool),\n    SetEq (List.filter pred (SetUnion seq1 seq2))\n          (SetUnion (List.filter pred seq1) (List.filter pred seq2)).\nProof.\n  unfold SetEq, SetUnion;\n  split;\n  intros;\n  rewrite filter_In, in_app_iff in *;\n  rewrite ! filter_In in *;\n  tauto.\nQed.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Common/SetEq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6533686629840939}}
{"text": "Require Import Coq.ZArith.ZArith Coq.ZArith.BinIntDef Coq.ZArith.BinInt coqutil.Z.Lia.\nRequire Import coqutil.sanity coqutil.Tactics.forward coqutil.Word.Interface. Import word.\nRequire Import Kami.Lib.Word.\nRequire riscv.Utility.Utility.\nFrom coqutil Require Import destr div_mod_to_equations.\n\nLocal Open Scope bool_scope.\nLocal Open Scope Z_scope.\n\nSection KamiWordFacts.\n\n  (* compatibility code for Coq 8.14 *)\n  Fact Znat_N2Z_inj_mod : forall n m : N, m <> 0%N -> Z.of_N (n mod m) = Z.of_N n mod Z.of_N m.\n  Proof. intros. now apply Znat.N2Z.inj_mod. Qed.\n\n  Lemma wordToN_split2 a b w :\n    wordToN (@split2 a b w) = BinNat.N.div (wordToN w) (NatLib.Npow2 a).\n  Proof.\n    pose proof wordToNat_split2 a b w as HH.\n    eapply Nnat.Nat2N.inj_iff in HH.\n    rewrite wordToN_nat, HH; f_equal; clear HH.\n    rewrite wordToN_nat, NatLib.pow2_N.\n    generalize (#w); intro.\n    specialize (NatLib.zero_lt_pow2 a).\n    generalize (NatLib.pow2 a); intros.\n    pose proof Zdiv.div_Zdiv n n0 ltac:(blia).\n    pose proof Znat.N2Z.inj_div (BinNat.N.of_nat n) (BinNat.N.of_nat n0).\n    rewrite Znat.nat_N_Z in *.\n    blia.\n  Qed.\n\n  Lemma wmsb_split2 a b w x y (H:b <> 0%nat)\n    : wmsb (split2 a b w) x = wmsb w y.\n  Proof.\n    intros.\n    rewrite <-(combine_split a b w) at 2.\n    erewrite wmsb_combine by trivial.\n    reflexivity.\n  Qed.\n\n  Lemma wordToZ_split2 a b w (H:b <> 0%nat)\n    : wordToZ (@split2 a b w) = Z.div (wordToZ w) (2^Z.of_nat a).\n  Proof.\n    rewrite 2wordToZ_wordToN.\n    rewrite wordToN_split2.\n    erewrite wmsb_split2; [instantiate (1:=false)|trivial].\n    case (wmsb w).\n    all: rewrite ?Znat.N2Z.inj_div.\n    all: rewrite <-?Znat.N_nat_Z, ?NatLib.Npow2_nat, ?N_Z_nat_conversions.Nat2Z.inj_pow.\n    2: setoid_rewrite Z.add_0_r; trivial.\n    rewrite ?Znat.Nat2Z.inj_add, ?Z.pow_add_r by blia.\n    rewrite Z.mul_comm.\n    symmetry.\n    rewrite <-Z.add_opp_r, Zopp_mult_distr_l.\n    rewrite Zdiv.Z_div_plus.\n    1: reflexivity.\n    eapply Z.lt_gt.\n    eapply Z.pow_pos_nonneg; blia.\n  Qed.\n\n  Lemma wordToN_wones_ones:\n    forall sz, wordToN (wones sz) = BinNat.N.ones (BinNat.N.of_nat sz).\n  Proof.\n    intros.\n    rewrite wordToN_nat.\n    rewrite wones_pow2_minus_one.\n    rewrite Nnat.Nat2N.inj_sub, BinNat.N.sub_1_r.\n    rewrite <-NatLib.pow2_N.\n    cbv [BinNat.N.ones]; rewrite BinNat.N.shiftl_1_l.\n    f_equal.\n    apply Znat.N2Z.inj.\n    rewrite NatLib.Z_of_N_Npow2, Znat.N2Z.inj_pow, Znat.nat_N_Z.\n    reflexivity.\n  Qed.\n\n  Lemma uwordToZ_wplus_distr:\n    forall sz (x y: Word.word sz),\n      Z.of_N (wordToN (x ^+ y)) = (Z.of_N (wordToN x) + Z.of_N (wordToN y)) mod 2 ^ (Z.of_nat sz).\n  Proof.\n    intros.\n    cbv [wplus wordBin].\n    rewrite wordToN_NToWord_eqn, Znat_N2Z_inj_mod, Znat.N2Z.inj_add, NatLib.Z_of_N_Npow2.\n    2: apply NatLib.Npow2_not_zero.\n    f_equal; f_equal; blia.\n  Qed.\n\n  Lemma wnot_idempotent:\n    forall {sz} (w: word sz),\n      wnot (wnot w) = w.\n  Proof.\n    induction w; cbn; rewrite ?IHw, ?Bool.negb_involutive; eauto.\n  Qed.\n\n  Lemma wordToN_eq_rect:\n    forall sz (w: Word.word sz) nsz Hsz,\n      wordToN (eq_rect _ Word.word w nsz Hsz) = wordToN w.\n  Proof.\n    intros; subst; simpl; reflexivity.\n  Qed.\n\n  Lemma Z_pow_add_lor:\n    forall n m p: Z,\n      0 <= n < 2 ^ p -> 0 <= m -> 0 <= p ->\n      (n + 2 ^ p * m)%Z = Z.lor n (2 ^ p * m).\n  Proof.\n    intros.\n    apply eq_sym, BitOps.or_to_plus.\n    rewrite Z.mul_comm, <-Z.shiftl_mul_pow2 by assumption.\n    replace n with (Z.land n (Z.ones p)).\n    - bitblast.Z.bitblast.\n      rewrite Z.testbit_neg_r with (n:= l) by blia.\n      apply Bool.andb_false_r.\n    - destruct (Z.eq_dec n 0); [subst; apply Z.land_0_l|].\n      assert (0 < n) by blia.\n      rewrite Z.land_ones_low; [reflexivity|blia|].\n      apply Z.log2_lt_pow2; blia.\n  Qed.\n\n  Lemma Z_of_wordToN_combine_alt:\n    forall sz1 (w1: Word.word sz1) sz2 (w2: Word.word sz2),\n      Z.of_N (wordToN (Word.combine w1 w2)) =\n      Z.lor (Z.of_N (wordToN w1)) (Z.shiftl (Z.of_N (wordToN w2)) (Z.of_N (BinNat.N.of_nat sz1))).\n  Proof.\n    intros.\n    rewrite wordToN_combine, N2Z.inj_add, N2Z.inj_mul.\n    assert (0 <= Z.of_N (wordToN w1) < 2 ^ (Z.of_N (N.of_nat sz1))).\n    { split; [apply N2Z.is_nonneg|].\n      clear.\n      induction w1; [simpl; blia|].\n      unfold wordToN; fold wordToN.\n      destruct b.\n      { rewrite N2Z.inj_succ, N2Z.inj_mul, Nnat.Nat2N.inj_succ.\n        rewrite N2Z.inj_succ.\n        rewrite Z.pow_succ_r by blia; blia.\n      }\n      { rewrite N2Z.inj_mul, Nnat.Nat2N.inj_succ.\n        rewrite N2Z.inj_succ.\n        rewrite Z.pow_succ_r by blia; blia.\n      }\n    }\n    assert (0 <= Z.of_N (wordToN w2)) by blia.\n    assert (0 <= Z.of_N (N.of_nat sz1)) by blia.\n\n    replace (Z.of_N (NatLib.Npow2 sz1)) with (Z.pow 2 (Z.of_N (N.of_nat sz1))).\n    - generalize dependent (Z.of_N (wordToN w1)).\n      generalize dependent (Z.of_N (wordToN w2)).\n      generalize dependent (Z.of_N (N.of_nat sz1)).\n      intros p ? z1 ? z2 ?.\n      rewrite Z.shiftl_mul_pow2 by assumption.\n      rewrite Z.mul_comm with (n:= z1).\n      apply Z_pow_add_lor; assumption.\n    - clear; induction sz1; [reflexivity|].\n      rewrite Nnat.Nat2N.inj_succ, N2Z.inj_succ.\n      unfold NatLib.Npow2; fold NatLib.Npow2.\n      rewrite Z.pow_succ_r by blia; blia.\n  Qed.\n\n  Lemma ZToWord_zero:\n    forall n, ZToWord n 0 = wzero n.\n  Proof.\n    destruct n; intros; [shatterer|].\n    apply wordToZ_inj.\n    rewrite wordToZ_ZToWord.\n    - rewrite wordToZ_wzero; reflexivity.\n    - split.\n      + blia.\n      + change 0 with (Z.of_nat 0).\n        apply Nat2Z.inj_lt.\n        apply NatLib.zero_lt_pow2.\n  Qed.\n\n  Lemma combine_wplus_wzero:\n    forall sz1 (wb: Word.word sz1) sz2 (w1 w2: Word.word sz2),\n      Word.combine wb w1 ^+ Word.combine (wzero sz1) w2 =\n      Word.combine wb (w1 ^+ w2).\n  Proof.\n    induction wb; intros; [reflexivity|].\n    simpl; rewrite <-wplus_WS_0.\n    rewrite IHwb; reflexivity.\n  Qed.\n\n  Lemma split1_wplus_silent:\n    forall sz1 sz2 (w1 w2: Word.word (sz1 + sz2)),\n      split1 sz1 sz2 w2 = wzero _ ->\n      split1 sz1 sz2 (w1 ^+ w2) = split1 sz1 sz2 w1.\n  Proof.\n    intros.\n    pose proof (word_combinable _ _ w1).\n    destruct H0 as [w11 [w12 ?]].\n    pose proof (word_combinable _ _ w2).\n    destruct H1 as [w21 [w22 ?]].\n    subst; rewrite split1_combine in H; subst.\n    rewrite combine_wplus_wzero.\n    do 2 rewrite split1_combine.\n    reflexivity.\n  Qed.\n\n  Lemma wordToN_split1 a b w :\n    wordToN (@split1 a b w) = BinNat.N.modulo (wordToN w) (NatLib.Npow2 a).\n  Proof.\n    pose proof wordToNat_split1 a b w as HH.\n    eapply Nnat.Nat2N.inj_iff in HH.\n    rewrite wordToN_nat, HH; f_equal; clear HH.\n    rewrite wordToN_nat, NatLib.pow2_N.\n    generalize (#w); intro.\n    remember (NatLib.pow2 a) as pa eqn:Ha.\n    pose proof NatLib.pow2_zero a.\n    pose proof mod_Zmod n pa ltac:(blia).\n    pose proof Znat_N2Z_inj_mod (BinNat.N.of_nat n) (BinNat.N.of_nat pa) ltac:(blia).\n    rewrite Znat.nat_N_Z in *.\n    blia.\n  Qed.\n\n  Lemma sumbool_rect_weq {T} a b n x y :\n    sumbool_rect (fun _ => T) (fun _ => a) (fun _ => b) (@weq n x y) = if weqb x y then a else b.\n  Proof.\n    cbv [sumbool_rect].\n    destruct (weq _ _), (weqb _ _) eqn:?;\n                                   try match goal with H : _ |- _ => eapply weqb_true_iff in H end;\n      trivial; congruence.\n  Qed.\n\n  Lemma sumbool_rect_bool_weq n x y :\n    sumbool_rect (fun _ => bool) (fun _ => true) (fun _ => false) (@weq n x y) = weqb x y.\n  Proof. rewrite sumbool_rect_weq; destruct (weqb x y); trivial. Qed.\n\n  Lemma unsigned_eqb n x y : Z.eqb (Z.of_N (wordToN x)) (Z.of_N (wordToN y)) = @weqb n x y.\n  Proof.\n    destruct (Z.eqb_spec (Z.of_N (wordToN x)) (Z.of_N (wordToN y))).\n    - apply N2Z.inj, wordToN_inj in e; subst.\n      apply eq_sym, weqb_eq; reflexivity.\n    - apply eq_sym, weqb_ne.\n      intro Hx; subst; auto.\n  Qed.\n\n  Lemma unsigned_split1_mod:\n    forall n m w,\n      Z.of_N (wordToN (split1 n m w)) = Z.of_N (wordToN w) mod (2 ^ (Z.of_nat n)).\n  Proof.\n    intros.\n    rewrite wordToN_split1.\n    rewrite N2Z.inj_mod by apply NatLib.Npow2_not_zero.\n    rewrite NatLib.Z_of_N_Npow2.\n    reflexivity.\n  Qed.\n\nEnd KamiWordFacts.\n\nSection WithWidth.\n  Context {width : Z}.\n  Context {width_nonneg : Z.lt 0 width}.\n  Local Notation sz := (Z.to_nat width).\n\n  Definition kword: Type := Kami.Lib.Word.word sz.\n  Definition kunsigned(x: kword): Z := Z.of_N (wordToN x).\n  Definition ksigned: kword -> Z := @wordToZ sz.\n  Definition kofZ: Z -> kword := ZToWord sz.\n\n  Definition riscvZdivu(x y: Z): Z :=\n    if y =? 0 then 2 ^ width - 1 else Z.div x y.\n\n  Definition riscvZdivs(x y: Z): Z :=\n    if (x =? - 2 ^ (width - 1)) && (y =? - 1) then x\n    else if y =? 0 then - 1 else Z.quot x y.\n\n  Definition riscvZmodu(x y: Z): Z :=\n    if y =? 0 then x else Z.modulo x y.\n\n  Definition riscvZmods(x y: Z): Z :=\n    if y =? 0 then x else Z.rem x y.\n\n  Instance word : word.word width := {|\n    rep := kword;\n    unsigned := kunsigned;\n    signed := ksigned;\n    of_Z := kofZ;\n\n    add := @wplus sz;\n    sub := @wminus sz;\n    opp := @wneg sz;\n\n    or  := @wor sz;\n    and := @wand sz;\n    xor := @wxor sz;\n    not := @wnot sz;\n\n    (* \"x and not y\" *)\n    ndn x y := kofZ (Z.ldiff (kunsigned x) (kunsigned y));\n\n    mul := @wmult sz;\n    mulhss x y := kofZ (Z.mul (ksigned x) (ksigned y) / 2^width);\n    mulhsu x y := kofZ (Z.mul (ksigned x) (kunsigned y) / 2^width);\n    mulhuu x y := kofZ (Z.mul (kunsigned x) (kunsigned y) / 2^width);\n\n    divu x y := kofZ (riscvZdivu (kunsigned x) (kunsigned y));\n    divs x y := kofZ (riscvZdivs (ksigned x) (ksigned y));\n    modu x y := kofZ (riscvZmodu (kunsigned x) (kunsigned y));\n    mods x y := kofZ (riscvZmods (ksigned x) (ksigned y));\n\n    (* shifts only look at the lowest 5-6 bits of the shift amount *)\n    slu x y := wlshift x (Z.to_nat ((kunsigned y) mod width));\n    sru x y := wrshift x (Z.to_nat ((kunsigned y) mod width));\n    srs x y := wrshifta x (Z.to_nat ((kunsigned y) mod width));\n\n    eqb := @weqb sz;\n    ltu x y := if wlt_dec x y then true else false;\n    lts x y := if wslt_dec x y then true else false;\n\n    sextend oldwidth z := kofZ ((kunsigned z + 2^(oldwidth-1)) mod 2^oldwidth - 2^(oldwidth-1));\n\n  |}.\n\n  Section __.\n    Import BinNat Word. Local Open Scope N_scope.\n\n    Lemma wordToN_WS b n w :\n      wordToN (@WS b n w) = 2*wordToN w + N.b2n b.\n    Proof.\n      case b; rewrite ?wordToN_WS_0, ?wordToN_WS_1; cbn [N.b2n].\n      all : blia.\n    Qed.\n\n    Lemma testbit_wordToN_oob n (a : word n) i (H: Logic.not (i < N.of_nat n)) :\n      N.testbit (wordToN a) i = false.\n    Proof.\n      pose proof wordToN_bound a.\n      case (wordToN a) in *; trivial; intros.\n      apply N.bits_above_log2, N.log2_lt_pow2; try blia.\n      eapply N.lt_le_trans; try apply H0; clear H0.\n      eapply Znat.N2Z.inj_le.\n      rewrite NatLib.Z_of_N_Npow2, Znat.N2Z.inj_pow; cbn.\n      eapply Z.pow_le_mono_r; blia.\n    Qed.\n\n    Lemma testbit_wordToN_bitwp_inbounds f n (a b : word n) i (H:i < N.of_nat n) :\n      N.testbit (wordToN (bitwp f a b)) i = f (N.testbit (wordToN a) i) (N.testbit (wordToN b) i).\n    Proof.\n      revert dependent i; revert b; revert a; induction n; intros.\n      { blia. }\n      case (shatter_word_S a) as (?&?&?) in *; subst a.\n      case (shatter_word_S b) as (?&?&?) in *; subst b.\n      cbn [bitwp whd].\n      rewrite 3wordToN_WS.\n      case (N.eq_dec 0 i); intros.\n      { subst. rewrite 3N.testbit_0_r; trivial. }\n      { rewrite <-(N.succ_pred i) by blia.\n        rewrite 3N.testbit_succ_r. eapply IHn. blia. }\n    Qed.\n  End __.\n\n  Lemma uwordToZ_bitwp f F (F_spec : forall x y i, Z.testbit (F x y) i = f (Z.testbit x i) (Z.testbit y i)) sz (x y : Word.word sz)\n    : uwordToZ (bitwp f x y) = (F (uwordToZ x) (uwordToZ y)) mod 2 ^ Z.of_nat sz.\n  Proof.\n    cbv [uwordToZ].\n    eapply Z.bits_inj_iff'; intros.\n    case (ZArith_dec.Z_lt_dec n (Z.of_nat sz)); intros.\n    2: {\n      rewrite Z.mod_pow2_bits_high by blia.\n      rewrite ?Z.testbit_of_N' by trivial.\n      rewrite testbit_wordToN_oob; trivial.\n      intro X.\n      eapply Znat.N2Z.inj_lt in X; blia.\n    }\n    rewrite Z.mod_pow2_bits_low by trivial.\n    rewrite F_spec.\n    rewrite ?Z.testbit_of_N' by trivial.\n    rewrite testbit_wordToN_bitwp_inbounds; trivial.\n    eapply Znat.N2Z.inj_lt; blia.\n  Qed.\n\n  Instance ok : word.ok word.\n  Proof using width_nonneg.\n    assert (AA: (0 < sz)%nat) by (eapply (Znat.Z2Nat.inj_lt 0); blia).\n    assert (BB: Z.of_nat sz = width) by (rewrite Znat.Z2Nat.id; blia).\n    split; trivial.\n    all: cbv [rep unsigned signed of_Z add sub opp or and xor not\n                  ndn mul mulhss mulhsu mulhuu divu divs modu mods slu sru srs\n                  eqb ltu lts sextend word wrap\n                  kword kunsigned ksigned kofZ]; intros.\n\n    { pose proof @uwordToZ_ZToWord_full (Z.to_nat width) ltac:(blia).\n      replace (Z.of_nat sz) with width in * by blia.\n      match goal with H : _ |- _ => eapply H end. }\n    { rewrite wordToZ_ZToWord_full; try blia. cbv [swrap].\n      replace (Z.of_nat sz) with width in * by blia; trivial. }\n    { rewrite ZToWord_Z_of_N, NToWord_wordToN; solve[trivial]. }\n    { rewrite uwordToZ_wplus_distr, BB; reflexivity. }\n    { cbv [wminus]; rewrite uwordToZ_wplus_distr, BB.\n      destruct (BinNat.N.eq_dec (wordToN y) N0).\n      { rewrite e.\n        rewrite <-wordToN_wzero with (sz:= sz) in e.\n        apply wordToN_inj in e; subst.\n        rewrite wzero_wneg, wordToN_wzero; reflexivity.\n      }\n      { rewrite wneg_wordToN by assumption.\n        rewrite Znat.N2Z.inj_sub by (pose proof (wordToN_bound y); blia).\n        rewrite NatLib.Z_of_N_Npow2, BB.\n        replace (Z.of_N (wordToN x) + (2 ^ width - Z.of_N (wordToN y)))\n          with (Z.of_N (wordToN x) - Z.of_N (wordToN y) + 1 * 2 ^ width) by blia.\n        rewrite Zdiv.Z_mod_plus_full.\n        reflexivity.\n      }\n    }\n\n    { destruct (BinNat.N.eq_dec (wordToN x) N0).\n      { rewrite e.\n        rewrite <-wordToN_wzero with (sz:= sz) in e.\n        apply wordToN_inj in e; subst.\n        rewrite wzero_wneg, wordToN_wzero; reflexivity.\n      }\n      { rewrite wneg_wordToN by assumption.\n        rewrite Znat.N2Z.inj_sub by (pose proof (wordToN_bound x); blia).\n        rewrite NatLib.Z_of_N_Npow2, BB.\n        assert (Hms: Z.of_N (wordToN x) mod 2 ^ (Z.of_nat sz) = Z.of_N (wordToN x)).\n        { apply Z.mod_small.\n          split; [blia|].\n          rewrite <-NatLib.Z_of_N_Npow2.\n          apply Znat.N2Z.inj_lt, wordToN_bound.\n        }\n        rewrite BB in Hms.\n        rewrite Zdiv.Z_mod_nz_opp_full by (rewrite Hms; blia).\n        rewrite Hms; reflexivity.\n      }\n    }\n    { setoid_rewrite (uwordToZ_bitwp _ _ Z.lor_spec); f_equal; congruence. }\n    { setoid_rewrite (uwordToZ_bitwp _ _ Z.land_spec); f_equal; congruence. }\n    { setoid_rewrite (uwordToZ_bitwp _ _ Z.lxor_spec); f_equal; congruence. }\n    { rewrite wnot_wnot'_equiv. cbv [wnot'].\n      setoid_rewrite (uwordToZ_bitwp _ _ Z.lxor_spec).\n      rewrite <-Z.lxor_m1_l.\n      pose proof uwordToZ_bound x.\n      change (Z.of_N (wordToN x)) with (uwordToZ x).\n      eapply Z.bits_inj_iff'; intros i Hi.\n      case (ZArith_dec.Z_lt_dec i width); intros.\n      2: rewrite !Z.mod_pow2_bits_high by blia; trivial.\n      rewrite !Z.mod_pow2_bits_low by blia.\n      rewrite 2Z.lxor_spec.\n      rewrite bitblast.Z.testbit_minus1 by trivial.\n      enough (Z.testbit (uwordToZ (wones sz)) i = true) by congruence.\n      cbv [uwordToZ].\n      rewrite ?Z.testbit_of_N' by trivial.\n      rewrite wordToN_wones_ones.\n      apply BinNat.N.ones_spec_low.\n      blia.\n    }\n\n    { setoid_rewrite uwordToZ_ZToWord_full; f_equal; trivial; congruence. }\n    { cbv [wmult wordBin].\n      rewrite wordToN_NToWord_eqn, Znat_N2Z_inj_mod, Znat.N2Z.inj_mul, NatLib.Z_of_N_Npow2.\n      2: apply NatLib.Npow2_not_zero.\n      f_equal; f_equal; blia. }\n\n    { rewrite wordToZ_ZToWord_full by blia;\n        cbv [swrap];  repeat (blia || f_equal). }\n    { rewrite wordToZ_ZToWord_full by blia;\n        cbv [swrap];  repeat (blia || f_equal). }\n    { repeat setoid_rewrite uwordToZ_ZToWord_full; try blia.\n      cbv [swrap];  repeat (blia || f_equal). }\n\n    { repeat setoid_rewrite uwordToZ_ZToWord_full; try blia.\n      f_equal.\n      2: repeat (blia || f_equal).\n      (* f_equal. (* WHY (COQBUG?) does this add hyps to the goal *) *)\n      cbv [riscvZdivu]; destr (Z.of_N (wordToN y) =? 0); blia. }\n    { rewrite wordToZ_ZToWord_full by blia.\n      cbv [swrap]; f_equal.\n      2 : repeat (blia || f_equal).\n      cbv [swrap]; f_equal.\n      2 : repeat (blia || f_equal).\n      cbv [riscvZdivs].\n      destr ((wordToZ x =? - 2 ^ (width - 1))); cbn [andb].\n      { destr (wordToZ y =? -1); try blia.\n        destr (wordToZ y =?  0); try blia.\n        f_equal; f_equal; blia. }\n      { destr (wordToZ y =?  0); try blia.\n        f_equal; f_equal; blia. } }\n    { repeat setoid_rewrite uwordToZ_ZToWord_full; try blia.\n      f_equal.\n      2: repeat (blia || f_equal).\n      cbv [riscvZmodu].\n      destr (Z.of_N (wordToN y) =? 0); blia. }\n    { rewrite wordToZ_ZToWord_full by blia.\n      cbv [swrap]; f_equal.\n      2 : repeat (blia || f_equal).\n      cbv [swrap]; f_equal.\n      2 : repeat (blia || f_equal).\n      cbv [riscvZmods].\n      destr (wordToZ y =? 0); try blia.\n      f_equal; f_equal; blia. }\n    { rewrite wlshift_mul_Zpow2 by (Z.div_mod_to_equations; blia).\n      cbv [wmult wordBin].\n      rewrite wordToN_NToWord_eqn, Znat_N2Z_inj_mod, Znat.N2Z.inj_mul, NatLib.Z_of_N_Npow2.\n      2:apply NatLib.Npow2_not_zero.\n      repeat setoid_rewrite uwordToZ_ZToWord_full; try blia.\n      rewrite Zdiv.Zmult_mod_idemp_r.\n      rewrite Z.shiftl_mul_pow2 by blia.\n      f_equal. 2: { f_equal; blia. }\n      f_equal.\n      f_equal.\n      apply Z.mod_small; blia. }\n\n    { cbv [wrshift].\n      rewrite wordToN_split2.\n      cbv [eq_rec_r eq_rec].\n      rewrite wordToN_nat, wordToNat_eq_rect, <-wordToN_nat, wordToN_combine, wordToN_wzero.\n      PreOmega.zify.\n      rewrite !NatLib.Z_of_N_Npow2.\n      rewrite Z.shiftr_div_pow2 by blia.\n      replace (Z.of_N (wordToN x) + 2 ^ Z.of_nat sz * 0)\n        with (Z.of_N (wordToN x)) by blia.\n      rewrite Z.mod_small by blia.\n      rewrite Z.mod_small.\n      2: {\n        pose proof uwordToZ_bound x; cbv [uwordToZ] in *.\n        replace (Z.of_nat sz) with width in * by blia.\n        match goal with\n        | H: _ \\/ _ |- _ => clear H; subst\n        end.\n        pose proof Z.pow_pos_nonneg 2 (Z.of_N (wordToN y)) eq_refl. auto_specialize.\n        replace 0 with (0/2 ^ Z.of_N (wordToN y)) by (apply Z.div_0_l; blia).\n        split; eauto using Z.div_le_mono.\n        eapply Z.div_lt_upper_bound; trivial.\n        Lia.nia. }\n      f_equal.\n      f_equal.\n      rewrite Znat.Z2Nat.id; blia. }\n\n    { cbv [wrshifta eq_rec_r eq_rec].\n      rewrite Z.mod_small, wordToZ_split2, wordToZ_eq_rect, sext_wordToZ, Znat.Z2Nat.id, Z.shiftr_div_pow2; try blia.\n      cbv [swrap]; rewrite Z.mod_small; try blia.\n      pose proof @wordToZ_size (pred sz).\n      rewrite PeanoNat.Nat.succ_pred in H0; [|blia].\n      specialize (H0 x).\n      pose proof (wordToZ_size'' AA x); rewrite BB in H1.\n      split.\n      { assert (0 < 2 ^ Z.of_N (wordToN y)) by (apply Z.pow_pos_nonneg; blia).\n        assert (0 < 2 ^ (width - 1)) by (apply Z.pow_pos_nonneg; blia).\n        assert (- 2 ^ (width - 1) <= wordToZ x / 2 ^ Z.of_N (wordToN y)).\n        { apply Z.div_le_lower_bound; [assumption|].\n          etransitivity; [|apply H1].\n          rewrite Z.mul_comm; apply Z.le_mul_diag_l; blia.\n        }\n        blia.\n      }\n      { apply Z.lt_add_lt_sub_r.\n        replace (2 ^ width) with (2 * 2 ^ (width - 1)).\n        2: { change 2 with (2 ^ 1) at 1.\n             rewrite <-Z.pow_add_r by blia.\n             f_equal; blia.\n        }\n        replace (2 * 2 ^ (width - 1) - 2 ^ (width - 1))\n          with (2 ^ (width - 1)) by blia.\n        apply Z.div_lt_upper_bound; [apply Z.pow_pos_nonneg; blia|].\n        eapply Z.lt_le_trans; [apply H1|].\n        rewrite Z.mul_comm; apply Z.le_mul_diag_r.\n        { apply Z.pow_pos_nonneg; blia. }\n        { pose proof (Z.pow_pos_nonneg 2 (Z.of_N (wordToN y))); blia. }\n      }\n    }\n    { specialize (weqb_true_iff x y); case (weqb x y); intros [].\n      { specialize (H eq_refl); subst; rewrite Z.eqb_refl; trivial. }\n      { case (weq x y); try solve [intuition congruence]; intros HH.\n        case (Z.eqb_spec (Z.of_N (wordToN x)) (Z.of_N (wordToN y))) as [X|X]; trivial.\n        eapply Znat.N2Z.inj_iff in X.\n        eapply wordToN_inj in X.\n        contradiction. } }\n    { case (wlt_dec x y) as [H|H]; cbv [wlt] in H;\n        case (Z.ltb_spec (Z.of_N (wordToN x)) (Z.of_N (wordToN y)));\n        trivial; blia. }\n    { case (wslt_dec x y) as [H|H]; cbv [wslt] in H;\n        case (Z.ltb_spec (wordToZ x) (wordToZ y)) as [G|G];\n        trivial; blia. }\n  Qed.\nEnd WithWidth.\nArguments word : clear implicits.\nArguments ok : clear implicits.\nArguments kword : clear implicits.\n\n#[global] Existing Instance word.\n#[global] Existing Instance ok.\n\n\nOpen Scope Z_scope.\n\nSection MkWords.\n  Context {width : Z}.\n  Context {width_cases : width = 32 \\/ width = 64}.\n\n  Lemma boundW: 0 < width.\n  Proof.\n    case width_cases; intro E; rewrite E; reflexivity.\n  Defined.\n  #[local] Instance wordW: word.word width := word width.\n  #[local] Instance wordWok: word.ok wordW := ok width boundW.\n\n  #[local] Instance word8: word.word 8 := word 8.\n  #[local] Instance word8ok: word.ok word8 := ok 8 eq_refl.\nEnd MkWords.\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/processor/src/processor/KamiWord.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6533686627044968}}
{"text": "Require Import ssreflect.\nFrom Tweetnacl.Libs Require Import Export.\nFrom Tweetnacl.Gen Require Import Get_abcdef.\n\nSection last_in.\n\nOpen Scope Z.\n\nContext (U:Type).\nContext (T:Type).\nContext (T':Type).\n\nFixpoint fun_rec (f_last: U -> T) (f_in: nat -> T' -> U -> U) (m : nat) (z : T') (x : U) : T :=\n  match m with\n  | 0%nat => f_last x\n  | S n => fun_rec f_last f_in n z (f_in n z x) \n    end.\n\nFixpoint fun_rec_0 (f_in: nat -> T' -> U -> U) (m : nat) (z : T') (x : U) : U :=\n  match m with\n  | 0%nat => x\n  | S n => fun_rec_0 f_in n z (f_in n z x)\n   end.\n\nLemma fun_rec_extract_last: forall f_in f_last n z x,\n  f_last (fun_rec_0 f_in n z x) = fun_rec f_last f_in  n z x.\nProof.\nintros f_in f_last n.\ninduction n as [|n IHn]; intros z x.\nreflexivity.\nsimpl.\nrewrite IHn.\nreflexivity.\nQed.\n\nClose Scope Z.\n\nEnd last_in.", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/proofs/spec/Gen/rec_f_extr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6533686601503044}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.setoid_ring.Ring.\nRequire Import Coq.setoid_ring.Ring_theory.\nRequire Import Field_theory.\nRequire Import Field_tac.\nRequire Import PeanoNat.\nRequire Import Arith.\nRequire Import Omega.\nRequire Import Matrix.\nRequire Import MyHelpers.\n\nSection MatrixInversion.\n  Variable E: MatrixElem.\n  Variable M: @Matrix E.\n  Add Field MatrixInversionEtField' : MEfield.\n  Variable n: nat.\n\n  Set Implicit Arguments.\n  Parameter is_eq_dec : forall x y: MEt, { eq x y } + { ~ eq x y }.\n  \n  Lemma non_trivial_ring:\n    e0 <> e1.\n  Proof.\n    Print field_theory.\n    intro.\n    symmetry in H.    \n    apply MEfield.(F_1_neq_0).\n    assumption.\n  Qed.\n\n  Lemma  normal_field_knowledge:\n    forall r, r <> e0 -> MEinv r <> e0.\n  Proof.\n    intros.\n    assert (MEinv r *e r = e1) by (field; assumption).\n    unfold not; intros.\n    rewrite H1 in H0.\n    assert (e0 *e r = e0) by field.\n    rewrite H2 in H0.\n    assert (e0 <> e1) by (apply non_trivial_ring). \n    contradiction.\n  Qed.\n\n  Definition I := @I n E M.\n  Definition e := @e n E M. \n  Definition row_mul := @row_mul n E M.\n  Definition row_add_to_row := @row_add_to_row n E M.\n  Definition swap := @swap n E M.\n  \n  Definition invertible (M : Mt n n) :=\n    exists M', M @* M' @= I /\\ M' @* M @= I. \n\n  Lemma I_is_invertible:\n    invertible I.\n  Proof.\n    exists I.\n    split; apply I_is_identity.\n  Qed.\n\n  Lemma AB_BA:\n    forall A B, invertible A -> A @* B @= I -> B @* A @= I. \n  Proof.\n    intros.\n    unfold invertible in H.\n    inversion H.\n    inversion H1.\n    rename x into B'.\n    assert (B' @* (A @* B) @= B' @* I).\n    {\n      setoid_rewrite H0.\n      reflexivity.\n    }\n\n    rewrite <- mult_assoc in H4.\n    rewrite H3 in H4.\n    rewrite I_is_left_identity in H4.\n    rewrite I_is_right_identity in H4.\n    rewrite H4.\n    assumption.\n  Qed.\n  \n  Fixpoint GE_elemdown (A: Mt n n) (x: nat) (cur: nat) :=\n    match cur with\n    | O => (I, A)\n    | S cur' =>\n      let ee := row_add_to_row (n - cur) x (MEopp (Mget A (n - cur) x)) in\n      let (E', EA') := GE_elemdown (ee @* A) x cur' in\n      (E' @* ee, EA')\n    end.\n\n  Fixpoint get_first_none_zero (A: Mt n n) (i: nat) (y: nat) :=\n    match i with\n    | O => n\n    | S i' =>\n      if (is_eq_dec (Mget A (n - i) y) MEzero) then\n        get_first_none_zero A i' y\n      else\n        n - i\n    end.\n  \n        \n  Fixpoint GE_stage1 (A: Mt n n) (i: nat) :=\n    match i with\n    | O => Some (I, A)\n    | S i' =>\n      let r := get_first_none_zero A i (n - i) in\n      if (r =? n) then\n        None\n      else\n        let A0 := (swap (n - i) r) @* A in \n        let ee := (row_mul (n - i) (MEinv (Mget A0 (n - i) (n - i)))) in\n        let (E', EA') := GE_elemdown (ee @* A0) (n - i) (i - 1) in\n        let ret := GE_stage1 EA' i' in\n        match ret with\n        | None => None\n        | Some (E'', EA'') => Some (E'' @* E' @* ee @* swap (n - i) r, EA'')\n        end\n    end.\n  \n  Fixpoint GE_elemup (A: Mt n n) (x: nat) (i: nat) :=\n    match i with\n    | O => (I, A)\n    | S i' =>\n      let ee := row_add_to_row i' x (MEopp (Mget A i' x)) in\n      let (E', EA') := GE_elemup (ee @* A) x i' in\n      (E' @* ee, EA')\n    end.\n  \n  Fixpoint GE_stage2 (A: Mt n n) (i: nat) :=\n    match i with\n    | O => (I, A)\n    | S i' =>\n        let (E', EA') := GE_elemup (A) i' i' in\n        let (E'', EA'') := GE_stage2 EA' i' in\n        (E'' @* E', EA'')\n    end.\n\n  Definition Inversion (A: Mt n n) := \n    match GE_stage1 A n with\n    | None => None\n    | Some (E, EA) => Some (fst (GE_stage2 EA n) @* E)\n    end.\n\n  Hint Rewrite @Mfill_correct @Melementwise_op_correct @get_element_e  @get_element_row_mul @get_element_row_add_to_row @get_element_swap: MMM. \n  Ltac urgh := \n    repeat match goal with\n    | _ => discriminate\n    | _ => progress subst\n    | _ => field\n    | _ => progress auto\n    | _ => omega\n    | _ => progress autorewrite with MMM\n    | [ |- context[let (_, _) := ?x in _]] => destruct x eqn: ?                                 \n    | _ => progress elim_bool\n                    \n    | [ |- context[?x <? ?y]] => destruct (x <? y) eqn: ?\n    | [ |- context[?x <=? ?y]] => destruct (x <=? y) eqn: ?\n                                                            \n    | [ |- context[match ?x with | _ => _ end]] => destruct (x) eqn: ?\n                                                                       \n    | [H: context[let (_, _) := ?x in _] |- _] => destruct x eqn: ?\n                                                                    \n    | [H: context[?x =? ?y] |- _] => destruct (x =? y) eqn: ?\n                                                              \n    | [H: context[?x <? ?y] |- _] => destruct (x <? y) eqn: ?\n    | [H: context[?x <=? ?y] |- _] => destruct (x <=? y) eqn: ?\n    | [H: context[match ?x with | _ => _ end] |- _] => destruct (x) eqn: ?                  \n    end.\n  \n  Lemma GE_elemdown_correct_1 :\n    forall A x cur,\n      x < n -> cur < n - x ->\n      (fst (GE_elemdown A x cur) @* A) @= snd (GE_elemdown A x cur).\n  Proof.\n    intros.\n    generalize dependent A. \n    induction cur.\n    - intros. simpl. apply I_is_identity.\n    - assert (cur < n - x) by omega. intros.\n      eapply IHcur in H1.\n      simpl.\n      destruct (GE_elemdown (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A) x cur) eqn: eq.\n      simpl.\n      rewrite eq in H1. simpl in H1.\n      rewrite <- mult_assoc in H1.\n      assumption.\n  Qed.\n\n  Lemma GE_elemdown_correct_keep :\n    forall A x cur,\n      x < n -> cur < n - x -> Mget A x x = e1 ->\n      forall i j, i < n - cur -> j < n -> Mget (snd (GE_elemdown A x cur)) i j = Mget A i j.\n  Proof.\n    intros.\n    generalize dependent A.\n    generalize dependent i.\n    generalize dependent j.\n    induction cur.\n    - intros.\n      simpl.\n      reflexivity.\n    - intros.\n      simpl.\n      destruct (GE_elemdown (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A) x cur) eqn: eq.\n      simpl.\n      assert (snd (GE_elemdown (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A) x cur)@[i, j] = (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A)@[i, j]).\n      {\n        apply IHcur; auto; try omega.\n        rewrite get_element_row_add_to_row; auto; try omega. \n        elim_bool; auto.\n        omega.\n      }\n      rewrite eq in H4. simpl in H4.\n      rewrite H4.\n      rewrite get_element_row_add_to_row; auto; try omega.\n      elim_bool; auto.\n      omega.\n  Qed.\n  \n  Lemma GE_elemdown_correct_2 :\n    forall A x cur,\n      x < n -> cur < n - x -> Mget A x x = e1 ->\n      forall y, y >= n - cur -> y < n -> Mget (snd (GE_elemdown A x cur)) y x = e0.\n  Proof.\n    intros.\n    generalize dependent A.\n    generalize dependent y.\n    induction cur. \n    - intros.\n      simpl. omega.\n    - intros.\n      destruct (beq_nat y (n - S cur)) eqn: eq; elim_bool.\n      + simpl.\n        destruct (GE_elemdown (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A) x cur) eqn: eq2. \n        simpl.\n        assert (m0@[y, x] = (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A)@[y, x]).\n        {\n          assert (m0 = snd (GE_elemdown (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A) x cur)) by (rewrite eq2; auto).\n          rewrite H4. \n          apply GE_elemdown_correct_keep; auto; try omega.\n          rewrite get_element_row_add_to_row; auto; try omega.\n          elim_bool; auto. omega.\n        }\n        rewrite H4.\n        rewrite get_element_row_add_to_row; auto; try omega.\n        elim_bool; auto; try omega.\n        rewrite <- eq0.\n        rewrite H1.\n        ring.\n      + simpl.\n        destruct (GE_elemdown (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A) x cur) eqn: eq2.\n        simpl.\n        assert (m0 = snd (GE_elemdown (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A) x cur)) by (rewrite eq2; auto).\n        rewrite H4.\n        apply IHcur; auto; try omega.\n        rewrite get_element_row_add_to_row; auto; try omega.\n        elim_bool; auto. omega.\n  Qed.\n\n  Definition lower_left_zeros (A: Mt n n) (L: nat) :=\n    forall i j,\n      i < n -> j < n -> j < L -> i > j -> Mget A i j = e0.\n  \n  Lemma GE_elemdown_correct_keep_0:\n    forall A x cur,\n      x < n -> cur < n - x -> Mget A x x = e1 -> lower_left_zeros A x -> \n      lower_left_zeros (snd (GE_elemdown A x cur)) x.\n  Proof.\n    intros.\n    generalize dependent A.\n    induction cur.\n    - intros.\n      simpl.\n      assumption.\n    - intros.\n      simpl.\n      destruct (GE_elemdown (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A)  x cur) eqn: eq.\n      simpl.\n      unfold lower_left_zeros in *.\n      intros.\n      destruct (i <? (n - S cur)) eqn: eq2.\n      + elim_bool.\n        replace (m0) with (snd (GE_elemdown (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A) x cur)) by (rewrite eq; auto).\n        assert (e0 = (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A)@[i, j]).\n        {\n          rewrite get_element_row_add_to_row; auto; try omega.\n          elim_bool; auto; try omega. \n          rewrite H2; auto.\n        }\n        rewrite H7. \n        apply GE_elemdown_correct_keep; auto; try omega.\n        rewrite get_element_row_add_to_row; auto; try omega.\n        elim_bool; auto; try omega.\n      + destruct (i =? (n - S cur)) eqn: eq3; elim_bool; auto; try omega.\n        * subst.\n          replace (m0) with (snd (GE_elemdown (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A) x cur)) by (rewrite eq; auto).\n          assert (e0 = (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A)@[n - S cur, j]).\n          {\n            rewrite get_element_row_add_to_row; auto; try omega.\n            elim_bool; auto; try omega.\n            rewrite H2; auto.\n            replace (A@[x, j]) with e0 by (rewrite H2; auto).\n            ring.\n          }\n          rewrite H7.\n          apply GE_elemdown_correct_keep; auto; try omega.\n          rewrite get_element_row_add_to_row; auto; try omega.\n          elim_bool; auto; try omega.\n        * replace (m0) with (snd (GE_elemdown (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A) x cur)) by (rewrite eq; auto).\n          apply IHcur; auto; try omega.\n          --- rewrite get_element_row_add_to_row; auto; try omega.\n              elim_bool; auto; try omega.\n          --- intros.\n              rewrite get_element_row_add_to_row; auto; try omega.\n              elim_bool; auto; try omega.\n              rewrite H2; auto.\n              replace (A@[x, j0]) with e0 by (rewrite H2; auto).\n              ring. \n  Qed.\n  \n  Lemma GE_elemdown_correct_extend_0:\n    forall A x,\n      x < n -> Mget A x x = e1 -> lower_left_zeros A x -> \n      lower_left_zeros (snd (GE_elemdown A x (n - x - 1))) (x + 1).\n  Proof.\n    intros.\n    unfold lower_left_zeros.\n    intros.\n    destruct (j =? x) eqn: eq; elim_bool.\n    - rewrite eq. apply GE_elemdown_correct_2; auto; omega. \n    - apply GE_elemdown_correct_keep_0; auto; omega.\n  Qed.\n\n  Lemma  get_first_none_zero_at_least:\n    forall A i j, get_first_none_zero A i j >= n - i.\n  Proof.\n    intros.\n    induction i.\n    - simpl. omega.\n    - simpl.\n      destruct (is_eq_dec (A@[n - S i, j]) e0); omega. \n  Qed.\n\n  Lemma  get_first_none_zero_at_most:\n    forall A i j, get_first_none_zero A i j <= n.\n  Proof.\n    intros.\n    induction i.\n    - simpl. omega.\n    - simpl.\n      destruct (is_eq_dec (A@[n - S i, j]) e0); omega. \n  Qed.\n\n  Lemma  get_first_none_zero_correct:\n    forall A i j, get_first_none_zero A i j < n -> A@[get_first_none_zero A i j, j] <> e0.\n  Proof.\n    intros.\n    induction i.\n    - simpl. simpl in H. omega.\n    - simpl; urgh.\n      simpl in H.\n      urgh.\n  Qed.\n  \n  Lemma GE_stage1_correct_1:\n    forall A i E EA,\n      i <= n -> GE_stage1 A i = Some (E, EA) -> \n      E @* A @= EA.\n  Proof.\n    intros.\n    generalize dependent A.\n    generalize dependent E0.\n    generalize dependent EA.\n    induction i; intros.\n    - simpl in H0. inversion H0; subst.\n      apply I_is_left_identity.\n    - unfold GE_stage1 in H0.\n      fold GE_stage1  in H0.\n      urgh.\n      remember (swap (n - S i) (get_first_none_zero A (S i) (n - S i)) @* A) as A0.\n        remember (row_mul (n - S i) (MEinv (A0@[n - S i, n - S i])) @* A0) as A1. \n        inversion H0.\n        replace ((if is_eq_dec (A@[n - S i, n - S i]) e0\n     then get_first_none_zero A i (n - S i)\n                  else n - S i)) with (get_first_none_zero A (S i) (n - S i)) by (auto).\n        rewrite mult_assoc. \n        rewrite <- HeqA0. \n        assert (m  @* A1 @= m0).\n        {\n          replace m with (fst (GE_elemdown A1 (n - S i) (S i - 1))) by (rewrite Heqp; auto).\n          replace m0 with (snd (GE_elemdown A1 (n - S i) (S i - 1))) by (rewrite Heqp; auto).\n          apply GE_elemdown_correct_1; urgh.\n        }\n      destruct (GE_stage1 m0 i) eqn: eq3.\n      * destruct p.\n        apply IHi in eq3; try omega. \n        \n        rewrite mult_assoc.\n        rewrite mult_assoc.\n        rewrite <- HeqA1. \n        rewrite H1.\n        rewrite <- H3.\n        inversion Heqo.\n        rewrite <- H5.\n        rewrite <- H6.\n        assumption.\n      * inversion Heqo.\n  Qed.\n\n  Lemma GE_stage1_correct_keep :\n    forall A i E EA,\n      i <= n -> GE_stage1 A i = Some (E, EA) -> \n      forall x y, x < n - i -> y < n -> Mget EA x y = Mget A x y. \n  Proof.\n    intros A i.\n    generalize dependent A.\n    induction i; intros.\n    - simpl in H0.\n      inversion H0; subst.\n      reflexivity.\n    - simpl in H0; urgh.\n      +\n        remember (swap (n - S i) (get_first_none_zero A i (n - S i)) @* A) as A0.\n        remember (row_mul (n - S i) (MEinv (A0@[n - S i, n - S i])) @* A0) as A1; try rewrite <- HeqA0 in *; try rewrite <- HeqA1 in *. \n        inversion H0. \n        rewrite <- H5. \n        rewrite IHi with (A := m0) (EA := m2) (E0 := m1); auto; try omega.\n        replace (m0) with (snd (GE_elemdown A1 (n - S i) (i - 0))) by (rewrite Heqp; auto).\n        rewrite GE_elemdown_correct_keep; auto; try omega.\n        *\n          apply transitivity with (y0 := A0@[x, y]).\n          --- rewrite HeqA1.\n              rewrite get_element_row_mul; urgh;\n              assert (get_first_none_zero A i (n - S i) <= n) by apply  get_first_none_zero_at_most;\n              omega. \n          --- rewrite HeqA0.\n              rewrite get_element_swap; urgh.\n              assert (get_first_none_zero A i (n - S i) >= n - i) by apply get_first_none_zero_at_least.\n              omega.\n              assert (get_first_none_zero A i (n - S i) <= n) by apply get_first_none_zero_at_most.\n              omega.\n        * rewrite HeqA1.\n          rewrite get_element_row_mul; urgh.\n          apply get_first_none_zero_correct.\n          assert (get_first_none_zero A i (n - S i) <= n) by apply  get_first_none_zero_at_most;\n            omega.\n\n          assert (get_first_none_zero A i (n - S i) <= n) by apply  get_first_none_zero_at_most;\n              omega. \n      + remember (swap (n - S i) (n - S i) @* A) as A0; remember (row_mul (n - S i) (MEinv (A0@[n - S i, n - S i])) @* A0) as A1; try rewrite <- HeqA0 in *; try rewrite <- HeqA1 in *. \n        inversion H0. \n        rewrite <- H5. \n        rewrite IHi with (A := m0) (EA := m2) (E0 := m1); auto; try omega.\n        replace (m0) with (snd (GE_elemdown A1 (n - S i) (i - 0))) by (rewrite Heqp; auto).\n        rewrite GE_elemdown_correct_keep; auto; try omega.\n        *\n          apply transitivity with (y0 := A0@[x, y]).\n          --- rewrite HeqA1.\n              rewrite get_element_row_mul; urgh.\n          --- rewrite HeqA0.\n              rewrite get_element_swap; urgh.\n        * rewrite HeqA1.\n          rewrite get_element_row_mul; urgh.\n  Qed.\n  \n  Definition Diag_ones (A: Mt n n) (L: nat) :=\n    forall i,\n      i < n -> i < L -> Mget A i i = e1.\n\n  Lemma GE_stage1_extend_ones :\n    forall A i E EA,\n      i <= n -> Diag_ones A (n - i) -> GE_stage1 A i = Some (E, EA) -> \n      Diag_ones EA n.\n  Proof.\n    intros.\n    generalize dependent A.\n    generalize dependent E0.\n    generalize dependent EA.\n    induction i; intros; urgh. \n    - simpl in H1. inversion H1; subst.\n      replace n with (n - 0) by omega.\n      assumption.\n    - unfold Diag_ones.\n      intros.\n      unfold GE_stage1 in H1; urgh. fold GE_stage1 in *.\n      remember (swap (n - S i) (get_first_none_zero A (S i) (n - S i)) @* A) as A0.\n      remember (row_mul (n - S i) (MEinv (A0@[n - S i, n - S i])) @* A0) as A1; try rewrite <- HeqA0 in *; try rewrite <- HeqA1 in *.\n\n      assert (get_first_none_zero A (S i) (n - S i) <= n) by apply get_first_none_zero_at_most.\n      assert (get_first_none_zero A (S i) (n - S i) >= n - S i) by apply get_first_none_zero_at_least.\n      \n      assert (Diag_ones m0 (n - i)).\n      {\n        unfold Diag_ones; intros.\n        replace (m0) with (snd (GE_elemdown A1 (n - S i) (S i - 1))) by (rewrite Heqp; auto). \n        rewrite GE_elemdown_correct_keep; auto; try omega.\n        + rewrite HeqA1.\n          rewrite get_element_row_mul; elim_bool; auto; try omega.\n          * rewrite eq; field. \n            rewrite HeqA0. rewrite get_element_swap; urgh.\n            --- apply get_first_none_zero_correct.\n                omega.\n          * rewrite HeqA0.\n            rewrite get_element_swap; urgh.\n            apply H0; urgh.\n        + rewrite HeqA1; urgh.\n          apply get_first_none_zero_correct.\n          omega. \n      }\n      apply IHi with (E0:=m1) (EA:=m2) in H6 ; auto; try omega.\n      inversion H1. \n      rewrite <- H9.\n      apply H6; auto.\n  Qed.\n\n  Lemma GE_stage1_extend_zeros :\n    forall A i E EA,\n      i <= n -> lower_left_zeros A (n - i) -> GE_stage1 A i = Some (E, EA) -> \n      lower_left_zeros EA n.\n  Proof.\n    intros A i.\n    generalize dependent A.\n    induction i; intros; urgh. \n    - replace n with (n - 0) by omega.\n      simpl in H1.\n      inversion H1.\n      rewrite <- H4. \n      assumption.\n    - unfold GE_stage1 in H1; urgh. fold GE_stage1 in *.\n      remember (swap (n - S i) (get_first_none_zero A (S i) (n - S i)) @* A) as A0.\n      remember (row_mul (n - S i) (MEinv (A0@[n - S i, n - S i])) @* A0) as A1; try rewrite <- HeqA0 in *; try rewrite <- HeqA1 in *.\n\n      assert (get_first_none_zero A (S i) (n - S i) <= n) by apply get_first_none_zero_at_most.\n      assert (get_first_none_zero A (S i) (n - S i) >= n - S i) by apply get_first_none_zero_at_least.\n      \n      assert (lower_left_zeros m0 (n - i)).\n      {\n        unfold lower_left_zeros.\n        intros. \n        replace (m0) with (snd (GE_elemdown A1 (n - S i) (S i - 1))) by (rewrite Heqp; auto).\n        replace (S i - 1) with (n - (n - S i) - 1) by omega. \n        apply GE_elemdown_correct_extend_0 with (x := n - S i); urgh.\n        + \n          apply get_first_none_zero_correct; urgh.\n        + unfold lower_left_zeros; intros.\n          rewrite get_element_row_mul; urgh.\n          * replace ( A@[get_first_none_zero A (S i) (n - S i), j0]) with e0 by (rewrite <- H0; auto; omega).\n            ring.\n          * rewrite <- H0; auto; omega.\n      }\n      apply IHi with (A := m0) (E0 := m1); auto; try omega.\n      inversion H1. \n      rewrite <- H7.\n      assumption.\n  Qed.\n\n  Definition normalized_upper_triangle (A: Mt n n) := \n    Diag_ones A n /\\ lower_left_zeros A n.\n  \n  Theorem GE_stage1_correct:\n    forall A E EA,\n      GE_stage1 A n = Some (E, EA) -> \n      E @* A @= EA /\\ normalized_upper_triangle EA.\n  Proof.\n    intros.\n    split.\n    - eapply GE_stage1_correct_1; eauto.\n    - unfold normalized_upper_triangle.\n      split.\n      + eapply GE_stage1_extend_ones; eauto.\n        unfold Diag_ones. intros. omega.\n      + eapply GE_stage1_extend_zeros; eauto.\n        unfold lower_left_zeros; intros. omega.\n  Qed.\n\n  Lemma GE_elemup_correct_1 :\n    forall A x i,\n      x < n -> i <= x ->\n      (fst (GE_elemup A x i) @* A) @= snd (GE_elemup A x i).\n  Proof.\n    intros.\n    generalize dependent A. \n    induction i.\n    - intros. simpl. apply I_is_identity.\n    - assert (i <= x) by omega. intros.\n      eapply IHi in H1.\n      simpl.\n      destruct (GE_elemup (row_add_to_row i x (MEopp (A@[i, x])) @* A) x i) eqn: eq.\n      simpl.\n      rewrite eq in H1. simpl in H1.\n      rewrite <- mult_assoc in H1.\n      assumption.\n  Qed.\n\n  Definition upper_right_zeros (A: Mt n n) (L: nat) :=\n    forall i j,\n      i < n -> j < n -> j >= n - L -> i < j -> Mget A i j = e0.\n\n  Lemma nut_preserve:\n    forall A x i',\n      x < n -> i' < x -> normalized_upper_triangle A -> \n      normalized_upper_triangle ((row_add_to_row i' x (MEopp (Mget A i' x))) @* A).\n  Proof.\n    intros.\n    unfold normalized_upper_triangle.\n    inversion H1.\n    unfold Diag_ones in H2. unfold lower_left_zeros in H3. \n    split.\n    + unfold Diag_ones; intros.\n      rewrite get_element_row_add_to_row; auto; try omega.\n      elim_bool; auto; try omega.\n      replace (A@[x, i]) with e0 by (rewrite H3; auto; omega).\n      replace (A@[i, i]) with e1 by (rewrite H2; auto; omega).\n      ring.\n    + unfold lower_left_zeros; intros. \n      rewrite get_element_row_add_to_row; auto; try omega.\n      elim_bool; auto; try omega.\n      replace (A@[i, j]) with e0 by (rewrite H3; auto; omega).\n      replace (A@[x, j]) with e0 by (rewrite H3; auto; omega).\n      ring.\n  Qed.\n  \n  Lemma GE_elemup_correct_2 :\n    forall A x i,\n      x < n -> i <= x -> normalized_upper_triangle A\n           -> normalized_upper_triangle (snd (GE_elemup A x i)). \n  Proof.\n    intros.\n    generalize dependent A.\n    generalize dependent x.\n    \n    induction i; intros.\n    - simpl. assumption.\n    - simpl.\n      destruct (GE_elemup (row_add_to_row i x (MEopp (A@[i, x])) @* A) x i) eqn: eq.\n      replace (snd (m @* row_add_to_row i x (MEopp (A@[i, x])), m0)) with (snd (GE_elemup (row_add_to_row i x (MEopp (A@[i, x])) @* A) x i)) by (rewrite eq; auto). \n      apply IHi; auto; try omega.\n      apply nut_preserve; auto.\n  Qed.\n\n  Lemma GE_elemup_correct_keep :\n    forall A x i,\n      x < n -> i <= x -> normalized_upper_triangle A ->\n      forall i' j, i' < n -> i' >= i -> j < n -> Mget (snd (GE_elemup A x i)) i' j = Mget A i' j.\n  Proof.\n    intros.\n    generalize dependent A.\n    generalize dependent i.\n    generalize dependent j.\n    generalize dependent i'.\n    generalize dependent x. \n    induction i.\n    - intros.\n      simpl.\n      reflexivity.\n    - intros.\n      simpl.\n      destruct (GE_elemup (row_add_to_row i x (MEopp (A@[i, x])) @* A) x i) eqn: eq.\n      simpl.\n      assert (snd (GE_elemup (row_add_to_row i x (MEopp (A@[i, x])) @* A) x i)@[i', j] = (row_add_to_row i x (MEopp (A@[i, x])) @* A)@[i', j]).\n      {\n        apply IHi; auto; try omega.\n        apply nut_preserve; auto; try omega.\n      } \n      rewrite eq in H5. simpl in H5.\n      rewrite H5.\n      rewrite get_element_row_add_to_row; auto; try omega.\n      elim_bool; auto.\n      omega.\n  Qed.\n  \n  Lemma GE_elemup_correct_3 :\n    forall A x i,\n      x < n -> i <= x -> normalized_upper_triangle A ->\n      (forall i0, i0 < i -> (snd (GE_elemup A x i))@[i0, x] = e0).  \n  Proof.\n    intros.\n    generalize dependent A.\n    generalize dependent x.\n    generalize dependent i.\n    generalize dependent i0. \n    induction i; intros.\n    - simpl. omega. \n    - simpl.\n      inversion H1.\n      unfold Diag_ones in H3.\n      unfold lower_left_zeros in H4. \n      destruct (GE_elemup (row_add_to_row i x (MEopp (A@[i, x])) @* A) x i) eqn: eq.\n      replace (snd (m @* row_add_to_row i x (MEopp (A@[i, x])), m0)) with (snd (GE_elemup (row_add_to_row i x (MEopp (A@[i, x])) @* A) x i)) by (rewrite eq; auto).\n      destruct (i0 =? i) eqn: eq2; elim_bool; auto.\n      + rewrite GE_elemup_correct_keep; auto; try omega.\n        * rewrite get_element_row_add_to_row; auto; try omega.\n          elim_bool; auto; try omega.\n          replace (A@[x, x]) with e1 by (rewrite H3; auto; omega).\n          rewrite eq0.\n          ring.\n        * apply nut_preserve; auto; try omega.\n      + rewrite IHi; auto; try omega.\n        apply nut_preserve; auto; try omega.\n  Qed.\n\n  Lemma GE_elemup_correct_4 :\n    forall A x i L ,\n      x < n -> i <= x -> L < n - x -> normalized_upper_triangle A -> upper_right_zeros A L ->  \n      upper_right_zeros (snd (GE_elemup A x i)) L. \n  Proof.\n    intros.\n    generalize dependent A.\n    generalize dependent x.\n    generalize dependent L.\n    induction i; intros; try assumption.\n    simpl.\n    destruct (GE_elemup (row_add_to_row i x (MEopp (A@[i, x])) @* A) x i) eqn: eq.\n    replace (snd (m @* row_add_to_row i x (MEopp (A@[i, x])), m0)) with (snd (GE_elemup (row_add_to_row i x (MEopp (A@[i, x])) @* A) x i)) by (rewrite eq; auto).\n    apply IHi; auto; try omega.\n    - apply nut_preserve; auto; omega.\n    - unfold upper_right_zeros.\n      intros.\n      rewrite get_element_row_add_to_row; auto; try omega.\n      elim_bool; auto; try omega.\n      rewrite eq0.\n      replace (A@[i, j]) with e0 by (rewrite H3; auto; omega).\n      replace (A@[x, j]) with e0 by (rewrite H3; auto; omega).\n      ring.\n  Qed.\n\n  Lemma GE_elemup_correct_5:\n    forall A x,\n      x < n -> normalized_upper_triangle A -> upper_right_zeros A (n - x - 1) ->  \n      upper_right_zeros (snd (GE_elemup A x x)) (n - x). \n  Proof.\n    intros.\n    unfold upper_right_zeros.\n    intros.\n    destruct (j =? x) eqn: eq; elim_bool; auto.\n    - rewrite eq. apply GE_elemup_correct_3; auto; try omega.\n    - rewrite GE_elemup_correct_4 with (L := n - x - 1);auto; try omega.\n  Qed.\n\n  Lemma GE_stage2_correct_1:\n    forall A i,\n      i <= n ->\n      fst (GE_stage2 A i) @* A @= snd (GE_stage2 A i).\n  Proof.\n    intros.\n    generalize dependent A.\n    induction i.\n    - intros; simpl.\n      apply I_is_identity.\n    - intros.\n      simpl.\n      destruct (GE_elemup A i i) eqn: eq1.\n      destruct (GE_stage2 m0 i) eqn: eq2.\n      simpl.\n      rewrite mult_assoc.\n      replace (m) with (fst (GE_elemup A i i)) by (rewrite eq1; auto). \n      rewrite GE_elemup_correct_1; auto; try omega.\n      replace (m1) with (fst (GE_stage2 m0 i)) by (rewrite eq2; auto).\n      replace (m2) with (snd (GE_stage2 m0 i)) by (rewrite eq2; auto).\n      replace (m0) with (snd (GE_elemup A i i)) by (rewrite eq1; auto).      \n      apply IHi; auto; try omega. \n  Qed.\n\n  Lemma GE_stage2_correct_2:\n    forall A i,\n      i <= n -> normalized_upper_triangle A -> \n      normalized_upper_triangle (snd (GE_stage2 A i)).\n  Proof.\n    intros.\n    generalize dependent A.\n    induction i.\n    - intros. simpl. assumption.\n    - intros; simpl.\n      destruct (GE_elemup A i i) eqn: eq1.\n      destruct (GE_stage2 m0 i) eqn: eq2.\n      simpl.\n      replace (m2) with (snd (GE_stage2 m0 i)) by (rewrite eq2; auto).\n      apply IHi; auto; try omega.\n      replace (m0) with (snd (GE_elemup A i i)) by (rewrite eq1; auto).\n      apply GE_elemup_correct_2; auto; try omega.\n  Qed.\n\n  Lemma GE_stage2_correct_3:\n    forall A i,\n      i <= n -> normalized_upper_triangle A -> upper_right_zeros A (n - i) -> \n      upper_right_zeros (snd (GE_stage2 A i)) n.\n  Proof.\n    intros.\n    generalize dependent A.\n    induction i.\n    - intros; simpl. replace (n) with (n - 0) by omega. assumption.\n    - intros; simpl.\n      destruct (GE_elemup A i i) eqn: eq1.\n      destruct (GE_stage2 m0 i) eqn: eq2.\n      simpl.\n      replace (m2) with (snd (GE_stage2 m0 i)) by (rewrite eq2; auto).\n      apply IHi; auto; try omega.\n      + replace (m0) with (snd (GE_elemup A i i)) by (rewrite eq1; auto).\n        apply GE_elemup_correct_2; auto; try omega.\n      + replace (m0) with (snd (GE_elemup A i i)) by (rewrite eq1; auto).\n        apply GE_elemup_correct_5; auto; try omega.\n        replace (n - i - 1) with (n - S i) by omega.\n        assumption.\n  Qed.\n\n  Theorem GE_stage2_correct:\n    forall A,\n      normalized_upper_triangle A ->\n      fst (GE_stage2 A n) @* A @= snd (GE_stage2 A n) /\\ snd (GE_stage2 A n) @= I.\n  Proof.\n    intros.\n    split.\n    - apply GE_stage2_correct_1. auto.\n    - unfold \"@=\".\n      intros.\n      destruct (j <=? i) eqn: eq; elim_bool; auto; try omega.\n      + destruct (j =? i) eqn: eq2; elim_bool; auto; try omega.\n        * subst.\n          unfold I. unfold Matrix.I. \n          rewrite Mfill_correct; elim_bool; auto; try omega.\n          apply GE_stage2_correct_2; auto.\n        * unfold I. unfold Matrix.I. \n          rewrite Mfill_correct; elim_bool; auto; try omega.\n          apply GE_stage2_correct_2; auto; omega.\n      + unfold I. unfold Matrix.I. \n        rewrite Mfill_correct; elim_bool; auto; try omega.\n        apply GE_stage2_correct_3; auto; try omega.\n        unfold upper_right_zeros; intros.\n        omega.\n  Qed.\n\n  Theorem Inversion_correct:\n    forall A E,\n      Inversion A = Some E -> E @* A @= I.\n  Proof.\n    intros.\n    unfold Inversion in H.\n    destruct (GE_stage1 A n) eqn: eq; try inversion H.\n    clear H1.\n    destruct p.\n    inversion H. clear H.\n    assert (m @* A @= m0 /\\ normalized_upper_triangle m0) by (apply GE_stage1_correct; assumption).\n    inversion H. clear H.\n    rewrite mult_assoc.\n    rewrite H0.\n    assert ((snd (GE_stage2 m0 n)) @= I) by (apply GE_stage2_correct; auto).\n    rewrite <- H.\n    apply GE_stage2_correct.\n    assumption.\n  Qed.\n\n  Lemma invertible_closed:\n    forall A B,\n      invertible A -> invertible B -> invertible (A @* B).\n  Proof.\n    intros.\n    unfold invertible in *.\n    inversion H.\n    inversion H0.\n    exists (x0 @* x).\n    split.\n    - rewrite mult_assoc.\n      assert (B @* (x0 @* x) @= ((B @* x0) @* x)) by (rewrite mult_assoc; reflexivity).\n      rewrite H3.\n      inversion H2.\n      rewrite H4.\n      rewrite I_is_left_identity.\n      apply H1.\n    - rewrite mult_assoc.\n      assert ((x @* (A @* B)) @= ((x @* A) @* B)) by (rewrite mult_assoc; reflexivity).\n      rewrite H3. \n      inversion H1.\n      rewrite H5.\n      rewrite I_is_left_identity.\n      apply H2.\n  Qed.\n\n  Lemma row_mul_invertible:\n    forall i x,\n      i < n -> x <> MEzero -> invertible (row_mul i x).\n  Proof.\n    intros.\n    unfold invertible.\n    exists (row_mul i (MEinv x)).\n    split.\n    - unfold Meq.\n      intros.\n      rewrite get_element_row_mul; auto; try omega.\n      destruct (i0 =? i) eqn: eq; elim_bool.\n      + unfold row_mul. unfold Matrix.row_mul. rewrite Mfill_correct; urgh.\n        * unfold I; unfold Matrix.I; urgh.\n        * unfold I; unfold Matrix.I; urgh.\n      + unfold row_mul; unfold Matrix.row_mul; urgh.\n        * unfold I; unfold Matrix.I; urgh.\n        * unfold I; unfold Matrix.I; urgh.\n    - unfold Meq; intros.\n      rewrite get_element_row_mul; urgh.\n      + unfold row_mul; unfold Matrix.row_mul; unfold I; unfold Matrix.I; urgh.\n      + unfold row_mul; unfold Matrix.row_mul; unfold I; unfold Matrix.I; urgh.\n  Qed.\n\n  Lemma row_add_to_row_invertible:\n    forall x y c,\n      x < n -> y < n -> x <> y -> invertible (row_add_to_row x y c).\n  Proof.\n    intros.\n    unfold invertible.\n    exists (row_add_to_row x y (MEopp c)).\n    split; unfold Meq; intros; rewrite get_element_row_add_to_row; urgh; unfold row_add_to_row; unfold Matrix.row_add_to_row; unfold I; unfold Matrix.I; unfold e; unfold Matrix.e; urgh; simpl in *; try inversion eq7; try inversion eq8;  try inversion eq4; try field.\n  Qed.\n\n  Lemma swap_invertible:\n    forall x y,\n      x < n -> y < n -> invertible (swap x y).\n  Proof.\n    intros.\n    unfold invertible.\n    exists (swap x y).\n    split; unfold Meq; intros; unfold I; unfold Matrix.I; unfold swap; unfold Matrix.swap; urgh; simpl; rewrite Mtimes_correct; auto; urgh. \n    - remember (if j =? x then y else if j =? y then x else j) as t.\n      apply sum_single with (x0 := t); intros; try rewrite Heqt; unfold I; unfold Matrix.I; unfold e; unfold Matrix.e; urgh. \n    - apply sum_e0';intros; unfold I; unfold Matrix.I; unfold e; unfold Matrix.e; urgh.\n    - remember (if j =? x then y else if j =? y then x else j) as t.\n      apply sum_single with (x0 := t); intros; try rewrite Heqt; unfold I; unfold Matrix.I; unfold e; unfold Matrix.e; urgh.\n    - apply sum_e0';intros; unfold I; unfold Matrix.I; unfold e; unfold Matrix.e; urgh.\n  Qed.\n  \n  Lemma GE_elemdown_preserve_invertibility:\n    forall A x cur,\n      x < n -> cur < n - x -> invertible A ->\n      invertible (snd (GE_elemdown A x cur)). \n  Proof.\n    intros.\n    generalize dependent A.\n    generalize dependent x.\n    induction cur; intros. \n    - simpl. assumption.\n    - simpl. \n      destruct (GE_elemdown (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A) x cur) eqn: eq.\n      simpl.\n      replace (m0) with (snd (GE_elemdown (row_add_to_row (n - S cur) x (MEopp (A@[n - S cur, x])) @* A) x cur)) by (rewrite eq; auto).\n      apply IHcur; try omega.\n      apply invertible_closed; try assumption.\n      apply row_add_to_row_invertible; omega.\n  Qed.\n        \n  Lemma kernal_span:\n    forall F: (nat -> nat -> MEt), forall i: nat,\n        (forall j k, j <= i -> k > j -> k < n -> F j k = e0) ->\n        (forall j, j < i -> F j j = e1) ->\n        F i i = e0 ->\n        (exists c: nat -> MEt, forall k, k < n -> F i k = sum i (fun j => (c j) *e (F j k))).\n  Proof.\n    intros.\n    generalize dependent F.\n    induction i.\n    - intros.\n      exists (fun x => e0).\n      intros.\n      simpl.\n      destruct (k =? 0) eqn: eq; urgh.\n      apply H; omega.\n    - intros.\n      assert (exists c: nat -> MEt, forall k: nat, k < n -> (if i <? i then F i k else F (S i) k -e F i k *e F (S i) i) = sum i (fun j => (c j) *e (if j <? i then F j k else F (S i) k -e F i k *e F (S i) i))).\n      {\n        apply IHi with (F := (fun x y => if x <? i  then F x y else (F (S i) y) -e (F i y *e F (S i) i))).\n        - intros.\n          urgh.\n          assert (i = j) by omega.\n          rewrite <- H5 in H3. \n          destruct (k =? i) eqn: eq2; urgh.\n          assert (F (S j) k = e0).\n          {\n            destruct (k =? S j) eqn: eq3; urgh.\n            rewrite H; try omega; reflexivity.\n          }\n          rewrite H5.\n          rewrite H; try omega.\n          ring.\n        - intros.\n          urgh.\n        - urgh.\n          rewrite H0; try omega. \n          ring.\n      }\n      inversion H2.\n      remember (x) as c'. \n      clear H2 Heqc' x. \n      exists (fun x => if x =? i then F (S i) i else c' x). \n      intros.\n      apply H3 in H2.\n      urgh.\n      rewrite sum_eq with (g := fun x => c' x *e F x k) in H2 .\n      + rewrite sum_split with (g := fun x => (if x =? i then e0 else c' x) *e F x k) (h := fun x => (if x =? i then F (S i) i else e0) *e F x k).\n        * assert (fold_nat (S i)\n                           (fun (acc : MEt) (x : nat) => acc +e (if x =? i then e0 else c' x) *e F x k) e0 = F (S i) k -e F i k *e F (S i) i).\n          {\n            simpl.\n            urgh.\n            rewrite sum_eq with (g := fun x => c' x *e F x k).\n            - rewrite <- H2.\n              ring.\n            - intros.\n              urgh.\n          }\n          rewrite H4.\n          rewrite sum_single with (x := i) (y := F (S i) i *e F i k); urgh; try ring.\n          intros.\n          urgh.\n        * intros.\n          urgh.\n      + intros.\n        urgh.\n  Qed.\n  \n  Lemma get_first_none_zero_invertibility_lemma:\n    forall A i,\n      i <= n -> 0 < i -> invertible A -> Diag_ones A (n - i) -> lower_left_zeros A (n - i + 1) -> Mget A (n - i) (n - i) = e0 -> False.\n  Proof.\n    intros.\n    inversion H1.\n    inversion H5.\n    remember x as B.\n    clear H5 H6 HeqB x.\n    assert ((exists c: nat -> MEt, forall k, k < n -> Mget A k (n - i) = sum (n - i) (fun j => (c j) *e (Mget A k j)))).\n    {\n      apply kernal_span with (F := fun i j => Mget A j i).\n      - intros. unfold lower_left_zeros in H2.\n        apply H3; try omega.\n      - intros.\n        apply H2; try omega.\n      - assumption. \n    }\n    inversion H5.\n    remember (x) as c.\n    clear H5 Heqc x.\n    assert (forall j, j < n - i -> sum n (fun k => Mget B (n - i) k *e Mget A k j) = e0). \n    {\n      intros.\n      unfold Meq in H7.\n      rewrite <- Mtimes_correct; try omega.\n      rewrite H7; try omega.\n      unfold I; unfold Matrix.I; urgh. \n    }\n    assert (sum n (fun k => Mget B (n - i) k *e Mget A k (n - i)) = e1). \n    {\n      intros.\n      unfold Meq in H7.\n      rewrite <- Mtimes_correct; try omega.\n      rewrite H7; try omega.\n      unfold I; unfold Matrix.I; urgh. \n    }\n    assert (sum n (fun k => Mget B (n - i) k *e Mget A k (n - i)) = e0).\n    {\n      rewrite sum_eq with (g := fun x => sum (n - i) (fun (y : nat) => B@[n - i, x] *e (c y *e A@[x, y]))).\n      - rewrite sum_swap with (n0 := n) (m := n - i).\n        apply sum_e0'.\n        intros.\n        rewrite sum_eq with (g := fun x => c i0 *e (B@[n - i, x] *e A@[x, i0])).\n        + rewrite <- sum_multiply_l.\n          rewrite H5; auto.\n          ring.\n        + intros.\n          ring.\n      - intros.\n        rewrite <- sum_multiply_l.\n        rewrite <- H6; auto.\n    }\n    remember (sum n (fun k : nat => B@[n - i, k] *e A@[k, n - i])) as x. \n    rewrite H9 in H8.\n    assert (e0 <> e1) by apply non_trivial_ring.\n    rewrite H8 in H10.\n    unfold not in H10.\n    apply H10.\n    reflexivity.\n  Qed.\n\n  Lemma get_first_none_zero_less_condition:\n    forall A i j,\n      i <= n -> (get_first_none_zero A i j = n -> (forall k, k >= n - i -> k < n -> Mget A k j = e0)).\n  Proof.\n    intros.\n      generalize dependent k.\n      induction i.\n      + intros.\n        omega.\n      + intros.\n        destruct (k =? n - S i) eqn: eq; urgh.\n        * simpl in H0.\n          rewrite eq. (* Needed in 8.6 *)\n          urgh.\n        * apply IHi; try omega.\n          simpl in H0.\n          urgh.\n  Qed.\n\n  Lemma get_first_none_zero_invertibility:\n          forall A i,\n            i <= n -> 0 < i -> invertible A -> Diag_ones A (n - i) -> lower_left_zeros A (n - i) -> get_first_none_zero A i (n - i) < n.\n  Proof.\n    intros.\n    assert (get_first_none_zero A i (n - i) <= n) by (apply get_first_none_zero_at_most). \n    assert (get_first_none_zero A i (n - i) < n <-> get_first_none_zero A i (n - i) <> n) by (split; omega).\n    apply H5.\n    clear H4 H5.\n    unfold not.\n    intros.\n    assert ((forall k, k >= n - i -> k < n -> Mget A k (n - i) = e0)) by (apply get_first_none_zero_less_condition; omega). \n    clear H4.\n    apply get_first_none_zero_invertibility_lemma with (A := A) (i := i); urgh.\n    - unfold lower_left_zeros.\n      intros.\n      destruct (j =? n - i) eqn: eq; urgh.\n      + apply H5; omega.\n      + apply H3; omega.\n    - apply H5; omega.\n  Qed.\n  \n  Lemma GE_stage1_preserve_invertibility:\n    forall A i,\n      i <= n -> lower_left_zeros A (n - i) -> invertible A -> Diag_ones A (n - i) ->\n      GE_stage1 A i <> None. \n  Proof.\n    intros.\n    generalize dependent A.\n    induction i.\n    - intros.\n      unfold not.\n      intros.\n      inversion H3.\n    - intros.\n      \n      remember (swap (n - S i) (get_first_none_zero A (S i) (n - S i)) @* A) as A0; remember (row_mul (n - S i) (MEinv (A0@[n - S i, n - S i])) @* A0) as A1.\n      assert (get_first_none_zero A (S i) (n - S i) <= n) by apply get_first_none_zero_at_most.\n        assert (get_first_none_zero A (S i) (n - S i) >= n - S i) by apply get_first_none_zero_at_least.\n      assert (forall m m0, get_first_none_zero A (S i) (n - S i) <> n -> GE_elemdown A1 (n - S i) (S i - 1) = (m, m0) -> GE_stage1 m0 i <> None). \n      {\n        intros.\n        apply IHi; try omega.\n        - try rewrite <- HeqA0 in *; try rewrite <- HeqA1 in *.\n            unfold lower_left_zeros.\n            intros. \n            replace (m0) with (snd (GE_elemdown A1 (n - S i) (S i - 1))) by (rewrite H6; auto).\n            replace (S i - 1) with (n - (n - S i) - 1) by omega. \n            apply GE_elemdown_correct_extend_0 with (x := n - S i); urgh.\n            + apply get_first_none_zero_correct; urgh.\n            + unfold lower_left_zeros; intros.\n              urgh. \n              * replace ( A@[get_first_none_zero A (S i) (n - S i), j0]) with e0 by (rewrite <- H0; auto; try omega).\n                ring. \n              *  rewrite <- H0; auto; omega.\n        - replace (m0) with (snd (GE_elemdown A1 (n - S i) (S i - 1))) by (rewrite H6; auto).\n          apply GE_elemdown_preserve_invertibility; urgh.\n          apply invertible_closed.\n          + apply row_mul_invertible; try omega.\n            urgh. \n            * assert (get_first_none_zero A (S i) (n - S i) <= n) by apply get_first_none_zero_at_most.\n              assert (A@[get_first_none_zero A (S i) (n - S i), n - S i] <> e0) by (apply get_first_none_zero_correct; omega).\n              remember (A@[get_first_none_zero A (S i) (n - S i), n - S i]) as r.\n              apply normal_field_knowledge.\n  \n              assumption.\n          + apply invertible_closed; try assumption.\n            apply swap_invertible; try omega. \n        - \n          unfold Diag_ones; intros.\n          replace (m0) with (snd (GE_elemdown A1 (n - S i) (S i - 1))) by (rewrite H6; auto).\n          rewrite GE_elemdown_correct_keep; auto; try omega.\n          + rewrite HeqA1.\n            rewrite get_element_row_mul; elim_bool; auto; try omega.\n            * rewrite eq; field.\n              rewrite HeqA0. rewrite get_element_swap; urgh.\n              --- apply get_first_none_zero_correct.\n                  omega.\n            * rewrite HeqA0.\n              rewrite get_element_swap; urgh.\n              apply H2; urgh.\n          + urgh. apply get_first_none_zero_correct.\n            omega.\n      }\n\n      Ltac urgh2 :=\n    repeat (try\n      ( let eq := fresh \"eq\" in \n        match goal with\n        | [ |- context[?x =? ?y]] => destruct (x =? y) eqn: eq\n        | [ |- context[?x <? ?y]] => destruct (x <? y) eqn: eq\n        | [ |- context[?x <=? ?y]] => destruct (x <=? y) eqn: eq\n        | [ |- context[Mfill _ ]] => rewrite Mfill_correct\n        | [ |- context [Melementwise_op _ _ _]] => rewrite Melementwise_op_correct\n        | [ |- context[let (_, _) := ?x in _]] => destruct x eqn: eq\n        | [ |- context[match ?x with | _ => _ end]] => destruct (x) eqn: eq  \n        | [H: context[let (_, _) := ?x in _] |- _] => destruct x eqn: eq\n        | [H: context[?x =? ?y] |- _] => destruct (x =? y) eqn: eq\n        | [H: context[?x <? ?y] |- _] => destruct (x <? y) eqn: eq\n        | [H: context[?x <=? ?y] |- _] => destruct (x <=? y) eqn: eq\n        | [H: context[match ?x with | _ => _ end] |- _] => destruct (x) eqn: eq               | [H: Some _ = None |- _] => inversion H\n        | [H: None = Some _|- _] => inversion H\n        | [H: true = false|- _] => inversion H\n        | [H: false = true|- _] => inversion H                                     \n        | [ |- context[((e _ _ _) @* _)@[_, _]]] => rewrite get_element_e\n        | [ |- context[((row_mul _ _) @* _)@[_, _]]] => rewrite get_element_row_mul\n        | [ |- context[((row_add_to_row _ _ _) @* _)@[_, _]]] => rewrite get_element_row_add_to_row\n        | [ |- context[((swap _ _) @* _)@[_, _]]] => rewrite get_element_swap                                                               \n      end); \n  try elim_bool;  \n  auto;\n  try omega).\n      \n                       \n        \n      unfold GE_stage1; urgh2; try rewrite HeqA1 in *; try rewrite HeqA0 in *. \n      + \n        assert (get_first_none_zero A (S i) (n - S i) < n) by (apply get_first_none_zero_invertibility; try assumption; omega).\n        omega.\n      +\n        unfold not.\n        intros.\n        inversion H6.\n      +\n        rewrite <- eq1 at 1.\n        fold GE_stage1 in *.\n        apply H5 with (m:= m); assumption.\n        \n  Qed.\n\n  Definition default_get {A: Type} (d: A) (c: option A) :=\n    match c with\n    | None => d\n    | Some c' => c'\n    end.\n\n  Theorem Inversion_very_correct:\n    forall A,\n      invertible A -> default_get I (Inversion A) @* A @= I.\n  Proof.\n    intros.\n    assert (GE_stage1 A n <> None).\n    {\n      apply GE_stage1_preserve_invertibility; urgh.\n      - unfold lower_left_zeros; intros; urgh.\n      - unfold Diag_ones; intros; urgh.\n    }\n    unfold default_get.\n    unfold Inversion.\n    urgh.\n    - apply Inversion_correct.\n      unfold Inversion.\n      urgh.\n      subst.\n      inversion Heqo0; subst.\n      assumption.\n    - unfold not in H0.\n      assert (False) by auto.\n      inversion H1.\n  Qed.\n        \nEnd MatrixInversion. ", "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/MatrixInversion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6533686553215172}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Omega.\n\nSet Implicit Arguments.\n\nTactic Notation \"eq\" \"goal\" \"with\" hyp(H) := \n  match goal with |- ?b => match type of H with ?t => replace b with t; auto end end.\n  \nTheorem nat_rev_ind (P : nat -> Prop) (HP : forall n, P (S n) -> P n) x y : x <= y -> P y -> P x.\nProof. induction 1; auto. Qed.\n\nReserved Notation \"f ↑ n\" (at level 1, left associativity).\n\nFixpoint iter X (f : X -> X) n x :=\n  match n with \n    | 0 => x\n    | S n => f (f↑n x)\n  end\nwhere \"f ↑ n\" := (@iter _ f n).\n\nFact iter_plus X f a b (x : X) : f↑(a+b) x = f↑a (f↑b x).\nProof. induction a; simpl; f_equal; auto. Qed.\n\nTactic Notation \"rew\" \"iter\" constr(f) :=\n  repeat match goal with \n    | |- context[f ?x]           => change (f x) with (f↑1 x)\n    | |- context[f↑?a (f↑?b ?x)] => rewrite <- (iter_plus f a b)\n  end.\n\nSection Tortoise_and_Hare_tail_recursive.\n\n  Variables (X : Type) (eqdec : forall x y : X, { x = y } + { x <> y }).\n  \n  Infix \"=?\" := eqdec (at level 70).\n\n  Variable (f : X -> X) (x0 : X) \n           (Hx0 : exists τ, 0 < τ /\\ f↑τ x0 = f↑(2*τ) x0).\n\n  Let R (c d : X*X) := match d with (x,y) => x<>y /\\ c = (f x, f (f y)) end.\n\n  Let tortoise_hare_tail_rec : \n    forall i x y, Acc R (x,y) -> { k | i <= k /\\ f↑(k-i) x = f↑(2*(k-i)) y }.\n  Proof.\n    refine (fix loop i x y H { struct H } := \n           match x =? y with\n             | left E  => exist _ i _\n             | right C => match loop (S i) (f x) (f (f y)) _ with\n                            | exist _ k Hk => exist _ k _\n                          end\n           end).\n    * split; f_equal; auto; omega.\n    * apply Acc_inv with (1 := H); constructor; trivial.\n    * destruct Hk; split; try omega.\n      revert H1; rew iter f; intros H1.\n      eq goal with H1; do 2 f_equal; omega.\n  Qed.\n\n  Let Acc_eq x y : x = y -> Acc R (x,y).\n  Proof.\n    intros; constructor 1.\n    intros [] (? & _); tauto.\n  Qed.\n\n  Let Acc_f0_ff0 : Acc R (f x0, f (f x0)).\n  Proof.\n    destruct Hx0 as (k & H1 & H2).\n    apply Acc_eq in H2.\n    revert k H1 H2; apply nat_rev_ind. \n    intros ? H.\n    constructor 1.\n    intros (u,v) (_ & Huv).\n    inversion Huv; subst.\n    rew iter f; eq goal with H; do 3 f_equal; omega.\n  Qed.\n\n  Definition tortoise_hare_tail : { τ | 0 < τ /\\ f↑τ x0 = f↑(2*τ) x0 }.\n  Proof.\n    refine (match tortoise_hare_tail_rec 1 Acc_f0_ff0 with\n      | exist _ k Hk => exist _ k _\n    end).\n    destruct Hk as (? & Hk); split; try omega.\n    revert Hk; rew iter f; intros Hk.\n    eq goal with Hk; do 2 f_equal; omega.\n  Defined.\n\nEnd Tortoise_and_Hare_tail_recursive.\n\nRecursive Extraction tortoise_hare_tail.\n", "meta": {"author": "DmxLarchey", "repo": "The-Tortoise-and-the-Hare", "sha": "8aa3a897271cf8f61c9d9530bf9efd363eb2a574", "save_path": "github-repos/coq/DmxLarchey-The-Tortoise-and-the-Hare", "path": "github-repos/coq/DmxLarchey-The-Tortoise-and-the-Hare/The-Tortoise-and-the-Hare-8aa3a897271cf8f61c9d9530bf9efd363eb2a574/th_acc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6533686524877272}}
{"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(** ** FRACTRAN termination is Diophantine *)\n\n(* Require Import dio_expr dio_logic dio_elem dio_poly. *)\n\nRequire Import List Arith Omega.\n\nRequire Import utils_tac utils_list sums rel_iter pos vec.\nRequire Import fractran_defs prime_seq.\nRequire Import dio_logic dio_bounded dio_rt_closure dio_single.\n\nSet Implicit Arguments.\n\nSection fractran_dio.\n\n  Notation \"l /F/ x → y\" := (fractran_step l x y) (at level 70, no associativity).\n\n  (* Fractran step is a diophantine relation *)\n\n  Lemma dio_rel_fractran_step l x y : 𝔻P x -> 𝔻P y -> 𝔻R (fun ν => l /F/ x ν → y ν).\n  Proof.\n    intros Hx Hy.\n    induction l as [ | (p,q) l IHl ].\n    + apply dio_rel_equiv with (fun _ => False); auto.\n      intros v; rewrite fractran_step_nil_inv; split; tauto.\n    + apply dio_rel_equiv with (1 := fun v => fractran_step_cons_inv p q l (x v) (y v)); auto.\n  Defined.\n\n  Hint Resolve dio_rel_fractran_step.\n\n  (* Hence Fractan step* (refl. trans. closure) is diophantine *)\n\n  Theorem dio_rel_fractran_rt l x y : \n                     𝔻P x -> 𝔻P y -> 𝔻R (fun ν => fractran_compute l (x ν) (y ν)).\n  Proof.\n    intros; apply dio_rel_exst, dio_rel_rel_iter; auto.\n  Defined.\n\n  (* Fractran stop is a diophantine relation *)\n\n  Theorem dio_rel_fractran_stop l x : 𝔻P x -> 𝔻R (fun ν => fractran_stop l (x ν)).\n  Proof.\n    intros Hx.\n    induction l as [ | (p,q) l IHl ].\n    + apply dio_rel_equiv with (fun _ => True); auto.\n      intro v; split; auto; intros _ ?.\n      rewrite fractran_step_nil_inv; auto.\n    + apply dio_rel_equiv with (1 := fun v => fractan_stop_cons_inv p q l (x v)); auto.\n  Defined.\n\n  Hint Resolve dio_rel_fractran_rt dio_rel_fractran_stop.\n\n  (* We start with the case of regular Fractran programs that do not\n     contain (_,0) \"fractions\" *)\n\n  (* Hence Halting from the value x is diophantine *)\n\n  Theorem FRACTRAN_HALTING_on_diophantine ll x :\n                      𝔻P x -> 𝔻R (fun ν => FRACTRAN_HALTING (ll,x ν)).\n  Proof.\n    intros; apply dio_rel_exst, dio_rel_conj; auto.\n  Defined.\n\n  Theorem FRACTRAN_HALTING_diophantine_0 ll : 𝔻R (fun ν => FRACTRAN_HALTING (ll,ν 0)).\n  Proof.\n    intros; apply FRACTRAN_HALTING_on_diophantine; auto.\n  Defined.\n\n  Theorem FRACTRAN_HALTING_diophantine l x : 𝔻R (fun _ => FRACTRAN_HALTING (l,x)).\n  Proof. apply FRACTRAN_HALTING_on_diophantine; auto. Defined.\n\nEnd fractran_dio.\n\nLocal Notation power := (mscal mult 1).\n\nFact power_expo x y : power x y = y^x.\nProof.\n  induction x as [ | x IHx ]; simpl.\n  + rewrite power_0; auto.\n  + rewrite power_S; f_equal; auto.\nQed.\n\nTheorem FRACTRAN_HALTING_dio_single l x : { e : dio_single nat Empty_set | l /F/ x ↓ <-> dio_single_pred e (fun _ => 0) }.\nProof.\n  generalize (@FRACTRAN_HALTING_on_diophantine l (fun _ => x)); intros H1.\n  spec in H1; auto.\n  destruct dio_rel_single with (1 := H1) as ((p,q) & He).\n  unfold FRACTRAN_HALTING in He.\n  exists (dp_inst_par (fun _ => 0) p, dp_inst_par (fun _ => 0) q).\n  rewrite He with (ν := fun _ => 0).\n  unfold dio_single_pred; simpl.\n  split; intros (phi & Hphi); exists phi; revert Hphi;\n    repeat rewrite dp_inst_par_eval; auto.\nQed.\n\nSection exp_diophantine.\n\n  (* for fixed n i j, the function v => exp i <v(j),...,v(n-1+j)> has a diophantine representation *)\n\n  Let exp_dio n i j y : 𝔻P y -> 𝔻R (fun v => y v = exp i (fun2vec j n v)).\n  Proof.\n    revert j i y; induction n as [ | n IHn ]; intros j i y Hy.\n    + simpl; dio_rel_auto.\n    + assert (H : forall v, y v = exp i (fun2vec j (S n) v)\n                        <-> exists q1 q2, y v = q1*q2 \n                                       /\\ q1 = power (v j) (qs i) \n                                       /\\ q2 = exp (S i) (fun2vec (S j) n v)).\n      { intros v; simpl fun2vec; rewrite exp_cons; split.\n        * exists (qs i^v j), (exp (S i) (fun2vec (S j) n v));\n            rewrite power_expo; auto.\n        * intros (q1 & q2 & H & ? & ?); subst.\n          rewrite H, power_expo; auto. }\n      apply dio_rel_equiv with (1 := H); clear H.\n      do 2 apply dio_rel_exst.\n      apply dio_rel_conj; auto.\n      apply dio_rel_conj; auto.\n      assert (H : dio_rel (fun v => v 0 = exp (S i) (fun2vec (3+j) n v))).\n      { apply IHn; auto. }\n      revert H; apply dio_rel_equiv.\n      intros v; rewrite fun2vec_lift with (f := fun i => v (S i)).\n      rewrite fun2vec_lift; simpl; tauto.\n  Qed.\n\n  (* for a fixed n, the relation \n  \n         ν 0 = ps 1 * (qs 1)^(ν 1) * ... * (qs n)^(ν n) \n\n     has a diophantine representation *)\n\n  Hint Resolve exp_dio.\n\n  Fact exp_diophantine n : 𝔻R (fun ν => ν 0 = ps 1 * exp 1 (fun2vec 0 n (fun x => ν (S x)))).\n  Proof.\n    apply dio_rel_equiv with (fun v => exists y, v 0 = ps 1 * y \n                                    /\\ y = exp 1 (fun2vec 0 n (fun x => v (S x)))).\n    + intro v; split.\n      * exists (exp 1 (fun2vec 0 n (fun x => v (S x)))); auto.\n      * intros (y & H1 & <-); auto.\n    + apply dio_rel_exst, dio_rel_conj; auto.\n      apply dio_rel_equiv with (fun v => v 0 = exp 1 (fun2vec 2 n v)); auto.\n      intro; repeat rewrite <- fun2vec_lift; tauto.\n  Qed.\n\nEnd exp_diophantine.\n\nHint Resolve exp_diophantine.\n\nTheorem FRACTRAN_HALTING_on_exp_diophantine n l :  \n                     𝔻R (fun ν => l /F/ ps 1 * exp 1 (fun2vec 0 n ν) ↓).\nProof.\n  apply dio_rel_compose with (R := fun x v => l /F/ x ↓); auto.\n  apply FRACTRAN_HALTING_on_diophantine; auto.\nQed.\n\nCheck FRACTRAN_HALTING_on_exp_diophantine.\nPrint Assumptions FRACTRAN_HALTING_on_exp_diophantine.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/coq-library-undecidability/H10/Fractran/fractran_dio.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6533686502131324}}
{"text": "Definition N := 16.\n\nInductive tree : Type :=\n| Leaf : tree\n| Node : nat -> tree -> tree -> tree.\n\nFixpoint binary_tree c n :=\n  match n with\n  | 0 => Leaf\n  | S n =>\n    let t := binary_tree c n in\n    Node c t t\n  end.\n\nDefinition t0 := Eval vm_compute in binary_tree 0 N.\nDefinition t1 := Eval vm_compute in binary_tree 1 N.\n", "meta": {"author": "eponier", "repo": "compare-eq", "sha": "cc2da184e747d0ad6ada8597e1ebf03377e413e2", "save_path": "github-repos/coq/eponier-compare-eq", "path": "github-repos/coq/eponier-compare-eq/compare-eq-cc2da184e747d0ad6ada8597e1ebf03377e413e2/equality_test/16/type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6533537571945344}}
{"text": "(** * IterFlip.v: An example of probabilistic termination *)\n\nRequire Export Prog.\nRequire ZArith.\nSet Implicit Arguments.\n\nModule IterFlip (Univ:Universe).\nModule RP := (Rules Univ).\n(* begin hide *)\nImport Univ.\nImport RP.\nImport RP.PP.\nImport RP.PP.MP.\nImport RP.PP.MP.UP.\n(* end hide *)\n(** ** Definition of a random walk \nWe interpret the probabilistic program \n<<\nlet rec iter x = if flip() then iter (x+1) else x \n>>*)\nImport ZArith.\n\nDefinition Fiter (f: Z -> (distr Z)) (x:Z) := Mif Flip (f (Zsucc x)) (Munit x).\n\nLemma Fiter_mon : forall f g : Z -> distr Z, \n  (forall n, le_distr (f n) (g n)) -> forall n, le_distr (Fiter f n) (Fiter g n).\nunfold Fiter; intros.\napply Mif_mon; auto.\nQed.\n\nDefinition iterflip : Z -> (distr Z) := Mfix Fiter Fiter_mon.\n\n(** ** Main result \n     Probability for [iter] to terminate is $1$ *)\n(** *** Auxiliary function $p_n$\n   Definition $ p_n = 1 - \\frac{1}{2^n} $ *)\n\nFixpoint p (n : nat) : U := match n with O => 0 | (S n) => [1/2] * p n + [1/2] end.\n\nLemma p_eq : forall n:nat, p n == [1-]([1/2]^n).\ninduction n; simpl; auto.\nsetoid_rewrite IHn.\napply Ueq_trans with ([1/2] * [1-]([1/2]^n) + [1-][1/2]);auto.\nQed.\nHint Resolve p_eq.\n\nLemma p_le : forall n:nat, [1-]([1/]1+n) <= p n.\nintro; setoid_rewrite (p_eq n).\napply Uinv_le_compat.\ninduction n; simpl; intros; auto.\napply Ule_trans with ([1/2] * ([1/]1+n)); auto.\nQed.\n\nHint Resolve p_le.\n\nLemma lim_p_one : 1 <= lub p.\napply Ule_lt_lim; intros.\nassert (exc (fun n : nat => t <= [1-] ([1/]1+n))).\nassert (~(0==[1-] t)).\nred; intro; apply H; auto.\napply Ule_trans with ([1-] 0); auto.\napply (archimedian H0); auto; intros m H1.\napply exc_intro with m; auto.\napply H0; auto; intros.\napply Ule_trans with (p x); auto.\napply Ule_trans with ([1-] ([1/]1+x)); auto.\nQed.\n\nHint Resolve lim_p_one.\n\n(** *** Proof of probabilistic termination  *)\nDefinition q1 (z1 z2:Z) := 1.\n\nLemma iterflip_term : okfun (fun k => 1) iterflip q1.\nunfold iterflip; intros.\napply okfun_le_compat with (fun (k:Z) => lub p) q1; auto.\napply fixrule with (p:= fun (x:Z) => p); auto; intros.\nred; simpl; intros.\nunfold Fiter.\nred.\nsetoid_rewrite (Mif_eq Flip (f (Zsucc x)) (Munit x) (q1 x)); simpl.\nunfold unit; simpl.\nsetoid_rewrite flip_ctrue.\nsetoid_rewrite flip_cfalse.\nunfold q1 at 2.\nsetoid_rewrite (Umult_one_left [1/2]).\napply Uplus_le_compat_left.\napply Ule_trans with (p i * [1/2]); auto.\napply Umult_le_compat_left; auto.\napply (H (Zsucc x)%Z).\nQed.\n\nEnd IterFlip.\n", "meta": {"author": "coq-contribs", "repo": "random", "sha": "e29ddb2860344bcaa750476ba26b786ee84afa4e", "save_path": "github-repos/coq/coq-contribs-random", "path": "github-repos/coq/coq-contribs-random/random-e29ddb2860344bcaa750476ba26b786ee84afa4e/IterFlip.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6533537571945344}}
{"text": "Require Import prosa.classic.util.all.\nRequire Import prosa.classic.model.arrival.basic.job prosa.classic.model.arrival.basic.task.\nRequire Import prosa.classic.model.schedule.global.basic.schedule.\nFrom mathcomp Require Import ssreflect eqtype ssrbool ssrnat seq bigop.\n\n(* Definitions of deadline miss. *)\nModule Schedulability.\n\n  Import Schedule SporadicTaskset Job.\n\n  Section SchedulableDefs.\n\n    Context {sporadic_task: eqType}.\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 -> sporadic_task.\n    \n    (* Consider any job arrival sequence... *)\n    Variable arr_seq: arrival_sequence Job.\n    \n    (* ...and any multiprocessor schedule of these jobs. *)\n    Context {num_cpus: nat}.\n    Variable sched: schedule Job num_cpus.\n\n    Section ScheduleOfJobs.\n\n      (* Let j be any job. *)\n      Variable j: Job.\n\n      (* We say that job j misses no deadline in sched if it completed by its absolute deadline. *)\n      Definition job_misses_no_deadline :=\n        completed job_cost sched j (job_arrival j + job_deadline j).\n\n    End ScheduleOfJobs.\n\n    Section ScheduleOfTasks.\n\n      (* Consider any task tsk. *)\n      Variable tsk: sporadic_task.\n\n      (* Task tsk doesn't miss its deadline iff all of its jobs don't miss their deadline. *)\n      Definition task_misses_no_deadline :=\n        forall j,\n          arrives_in arr_seq j ->\n          job_task j = tsk ->\n          job_misses_no_deadline j.\n\n      (* Task tsk doesn't miss its deadline before time t' iff all of its jobs don't miss\n         their deadline by that time. *)\n      Definition task_misses_no_deadline_before (t': time) :=\n        forall j,\n          arrives_in arr_seq j ->\n          job_task j = tsk ->\n          job_arrival j + job_deadline j < t' ->\n          job_misses_no_deadline j.\n\n    End ScheduleOfTasks.\n\n  End SchedulableDefs.\n\n  Section BasicLemmas.\n\n    Context {sporadic_task: eqType}.\n    Variable task_cost: sporadic_task -> time.\n    Variable task_period: sporadic_task -> time.\n    Variable task_deadline: sporadic_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 -> sporadic_task.\n\n    (* Consider any job arrival sequence... *)\n    Variable arr_seq: arrival_sequence Job.\n    \n    (* ...and any schedule of these jobs... *)\n    Context {num_cpus : nat}.\n    Variable sched: schedule Job num_cpus.\n\n    (* ... where jobs dont execute after completion. *)\n    Hypothesis H_completed_jobs_dont_execute:\n      completed_jobs_dont_execute job_cost sched.\n\n    Section SpecificJob.\n\n      (* Then, for any job j ...*)\n      Variable j: Job.\n      Hypothesis H_j_arrives: arrives_in arr_seq j.\n\n      (* ...that doesn't miss a deadline in this schedule, ... *)\n      Hypothesis no_deadline_miss:\n        job_misses_no_deadline job_arrival job_cost job_deadline sched j.\n\n      (* the service received by j at any time t' after its deadline is 0. *)\n      Lemma service_after_job_deadline_zero :\n        forall t',\n          t' >= job_arrival j + job_deadline j ->\n          service_at sched j t' = 0.\n      Proof.\n        intros t' LE.\n        rename no_deadline_miss into RT,\n               H_completed_jobs_dont_execute into EXEC.\n        unfold job_misses_no_deadline, completed, completed_jobs_dont_execute in *.\n        apply/eqP; rewrite -leqn0.\n        eapply completion_monotonic in RT; eauto 2.\n        apply completed_implies_not_scheduled in RT; eauto 2.\n          by move: RT; rewrite not_scheduled_no_service; move => /eqP RT; rewrite RT.\n      Qed.\n\n      (* The same applies for the cumulative service of job j. *)\n      Lemma cumulative_service_after_job_deadline_zero :\n        forall t' t'',\n          t' >= job_arrival j + job_deadline j ->\n          \\sum_(t' <= t < t'') service_at sched j t = 0.\n      Proof.\n        ins; apply/eqP; rewrite -leqn0.\n        rewrite big_nat_cond; rewrite -> eq_bigr with (F2 := fun i => 0);\n          first by rewrite big_const_seq iter_addn mul0n addn0 leqnn.\n        intro i; rewrite andbT; move => /andP [LE _].\n        by rewrite service_after_job_deadline_zero;\n          [by ins | by apply leq_trans with (n := t')].\n      Qed.\n      \n    End SpecificJob.\n    \n    Section AllJobs.\n\n      (* Consider any task tsk ...*)\n      Variable tsk: sporadic_task.\n\n      (* ... that doesn't miss any deadline. *)\n      Hypothesis no_deadline_misses:\n        task_misses_no_deadline job_arrival job_cost job_deadline job_task arr_seq sched tsk.\n\n      (* Then, for any valid job j of this task, ...*)\n      Variable j: Job.\n      Hypothesis H_j_arrives: arrives_in arr_seq j.\n      Hypothesis H_job_of_task: job_task j = tsk.\n      Hypothesis H_valid_job:\n        valid_sporadic_job task_cost task_deadline job_cost job_deadline job_task j.\n      \n      (* the service received by job j at any time t' after the deadline is 0. *)\n      Lemma service_after_task_deadline_zero :\n        forall t',\n          t' >= job_arrival j + task_deadline tsk ->\n          service_at sched j t' = 0.\n      Proof.\n        rename H_valid_job into PARAMS; unfold valid_sporadic_job in *; des; intros t'.\n        rewrite -H_job_of_task -PARAMS1.\n        by apply service_after_job_deadline_zero, no_deadline_misses.\n      Qed.\n\n      (* The same applies for the cumulative service of job j. *)\n      Lemma cumulative_service_after_task_deadline_zero :\n        forall t' t'',\n          t' >= job_arrival j + task_deadline tsk ->\n          \\sum_(t' <= t < t'') service_at sched j t = 0.\n      Proof.\n        rename H_valid_job into PARAMS; unfold valid_sporadic_job in *; des; intros t' t''.\n        rewrite -H_job_of_task -PARAMS1.\n        by apply cumulative_service_after_job_deadline_zero, no_deadline_misses.\n      Qed.\n      \n    End AllJobs.\n\n  End BasicLemmas.\n\nEnd Schedulability.", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/classic/model/schedule/global/schedulability.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102419, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6533537554303774}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\n(* -*- coding : utf-8 -*- *)\n\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp\nRequire Import ssrfun ssrbool eqtype ssrnat choice seq fintype.\n\n(*****************************************************************************)\n(* Provided a base type T, this files defines an interface for quotients Q   *)\n(* of the type T with explicit functions for canonical surjection (\\pi       *)\n(* : T -> Q) and for choosing a representative (repr : Q -> T).  It then     *)\n(* provide a helper to quotient T by a decidable equivalence relation (e     *)\n(* : rel T) if T is a choiceType (or encodable as a choiceType modulo e).    *)\n(*                                                                           *)\n(* See \"Pragamatic Quotient Types in Coq\", proceedings of ITP2013,           *)\n(* by Cyril Cohen.                                                           *)\n(*                                                                           *)\n(* *** Generic Quotienting ***                                               *)\n(*   QuotClass (reprK : cancel repr pi) == builds the quotient which         *)\n(*              canonical surjection function is pi and which                *)\n(*              representative selection function is repr.                   *)\n(*   QuotType Q class == packs the quotClass class to build a quotType       *)\n(*                       You may declare such elements as Canonical          *)\n(*            \\pi_Q x == the class in Q of the element x of T                *)\n(*              \\pi x == the class of x where Q is inferred from the context *)\n(*             repr c == canonical representative in T of the class c        *)\n(*    [quotType of Q] == clone of the canonical quotType structure of Q on T *)\n(*     x = y %[mod Q] := \\pi_Q x = \\pi_Q y                                   *)\n(*                    <-> x and y are equal modulo Q                         *)\n(*    x <> y %[mod Q] := \\pi_Q x <> \\pi_Q y                                  *)\n(*    x == y %[mod Q] := \\pi_Q x == \\pi_Q y                                  *)\n(*    x != y %[mod Q] := \\pi_Q x != \\pi_Q y                                  *)\n(*                                                                           *)\n(* The quotient_scope is delimited by %qT                                    *)\n(* The most useful lemmas are piE and reprK                                  *)\n(*                                                                           *)\n(* *** Morphisms ***                                                         *)\n(* One may declare existing functions and predicates as liftings of some     *)\n(* morphisms for a quotient.                                                 *)\n(*    PiMorph1 pi_f == where pi_f : {morph \\pi : x / f x >-> fq x}           *)\n(*                     declares fq : Q -> Q as the lifting of f : T -> T     *)\n(*    PiMorph2 pi_g == idem with pi_g : {morph \\pi : x y / g x y >-> gq x y} *)\n(*     PiMono1 pi_p == idem with pi_p : {mono \\pi : x / p x >-> pq x}        *)\n(*     PiMono2 pi_r == idem with pi_r : {morph \\pi : x y / r x y >-> rq x y} *)\n(*   PiMorph11 pi_f == idem with pi_f : {morph \\pi : x / f x >-> fq x}       *)\n(*                     where fq : Q -> Q' and f : T -> T'.                   *)\n(*       PiMorph eq == Most general declaration of compatibility,            *)\n(*                     /!\\ use with caution /!\\                              *)\n(* One can use the following helpers to build the liftings which may or      *)\n(* may not satisfy the above properties (but if they do not, it is           *)\n(* probably not a good idea to define them):                                 *)\n(*       lift_op1 Q f := lifts f : T -> T                                    *)\n(*       lift_op2 Q g := lifts g : T -> T -> T                               *)\n(*      lift_fun1 Q p := lifts p : T -> R                                    *)\n(*      lift_fun2 Q r := lifts r : T -> T -> R                               *)\n(*   lift_op11 Q Q' f := lifts f : T -> T'                                   *)\n(* There is also the special case of constants and embedding functions       *)\n(* that one may define and declare as compatible with Q using:               *)\n(*    lift_cst Q x := lifts x : T to Q                                       *)\n(*       PiConst c := declare the result c of the previous construction as   *)\n(*                    compatible with Q                                      *)\n(*  lift_embed Q e := lifts e : R -> T to R -> Q                             *)\n(*       PiEmbed f := declare the result f of the previous construction as   *)\n(*                    compatible with Q                                      *)\n(*                                                                           *)\n(* *** Quotients that have an eqType structure ***                           *)\n(* Having a canonical (eqQuotType e) structure enables piE to replace terms  *)\n(* of the form (x == y) by terms of the form (e x' y') if x and y are        *)\n(* canonical surjections of some x' and y'.                                  *)\n(*    EqQuotType e Q m == builds an (eqQuotType e) structure on Q from the   *)\n(*                        morphism property m                                *)\n(*                        where m : {mono \\pi : x y / e x y >-> x == y}      *)\n(*   [eqQuotType of Q] == clones the canonical eqQuotType structure of Q     *)\n(*                                                                           *)\n(* *** Equivalence and quotient by an equivalence ***                        *)\n(*  EquivRel r er es et == builds an equiv_rel structure based on the        *)\n(*                         reflexivity, symmetry and transitivity property   *)\n(*                         of a boolean relation.                            *)\n(*          {eq_quot e} == builds the quotType of T by equiv                 *)\n(*                         where e : rel T is an equiv_rel                   *)\n(*                         and T is a choiceType or a (choiceTypeMod e)      *)\n(*                         it is canonically an eqType, a choiceType,        *)\n(*                         a quotType and an eqQuotType.                     *)\n(*    x = y %[mod_eq e] := x = y %[mod {eq_quot e}]                          *)\n(*                      <-> x and y are equal modulo e                       *)\n(*    ...                                                                    *)\n(*****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nReserved Notation \"\\pi_ Q\" (at level 0, format \"\\pi_ Q\").\nReserved Notation \"\\pi\" (at level 0, format \"\\pi\").\nReserved Notation \"{pi_ Q a }\"\n         (at level 0, Q at next level, format \"{pi_ Q  a }\").\nReserved Notation \"{pi a }\" (at level 0, format \"{pi  a }\").\nReserved Notation \"x == y %[mod_eq e ]\" (at level 70, y at next level,\n  no associativity,   format \"'[hv ' x '/'  ==  y '/'  %[mod_eq  e ] ']'\").\nReserved Notation \"x = y %[mod_eq e ]\" (at level 70, y at next level,\n  no associativity,   format \"'[hv ' x '/'  =  y '/'  %[mod_eq  e ] ']'\").\nReserved Notation \"x != y %[mod_eq e ]\" (at level 70, y at next level,\n  no associativity,   format \"'[hv ' x '/'  !=  y '/'  %[mod_eq  e ] ']'\").\nReserved Notation \"x <> y %[mod_eq e ]\" (at level 70, y at next level,\n  no associativity,   format \"'[hv ' x '/'  <>  y '/'  %[mod_eq  e ] ']'\").\nReserved Notation \"{eq_quot e }\" (at level 0, e at level 0,\n  format \"{eq_quot  e }\", only parsing).\n\nDelimit Scope quotient_scope with qT.\nLocal Open Scope quotient_scope.\n\n(*****************************************)\n(* Definition of the quotient interface. *)\n(*****************************************)\n\nSection QuotientDef.\n\nVariable T : Type.\n\nRecord quot_mixin_of qT := QuotClass {\n  quot_repr : qT -> T;\n  quot_pi : T -> qT;\n  _ : cancel quot_repr quot_pi\n}.\n\nNotation quot_class_of := quot_mixin_of.\n\nRecord quotType := QuotTypePack {\n  quot_sort :> Type;\n  quot_class : quot_class_of quot_sort\n}.\n\nVariable qT : quotType.\nDefinition pi_phant of phant qT := quot_pi (quot_class qT).\nLocal Notation \"\\pi\" := (pi_phant (Phant qT)).\nDefinition repr_of := quot_repr (quot_class qT).\n\nLemma repr_ofK : cancel repr_of \\pi.\nProof. by rewrite /pi_phant /repr_of /=; case: qT=> [? []]. Qed.\n\nDefinition QuotType_clone (Q : Type) qT cT \n  of phant_id (quot_class qT) cT := @QuotTypePack Q cT.\n\nEnd QuotientDef.\n\nArguments repr_ofK {T qT}.\n\n(****************************)\n(* Protecting some symbols. *)\n(****************************)\n\nModule Type PiSig.\nParameter f : forall (T : Type) (qT : quotType T), phant qT -> T -> qT.\nAxiom E : f = pi_phant.\nEnd PiSig.\n\nModule Pi : PiSig.\nDefinition f := pi_phant.\nDefinition E := erefl f.\nEnd Pi.\n\nModule MPi : PiSig.\nDefinition f := pi_phant.\nDefinition E := erefl f.\nEnd MPi.\n\nModule Type ReprSig.\nParameter f : forall (T : Type) (qT : quotType T), qT -> T.\nAxiom E : f = repr_of.\nEnd ReprSig.\n\nModule Repr : ReprSig.\nDefinition f := repr_of.\nDefinition E := erefl f.\nEnd Repr.\n\n(*******************)\n(* Fancy Notations *)\n(*******************)\n\nNotation repr := Repr.f.\nNotation \"\\pi_ Q\" := (@Pi.f _ _ (Phant Q)) : quotient_scope.\nNotation \"\\pi\" := (@Pi.f _ _ (Phant _))  (only parsing) : quotient_scope.\nNotation \"x == y %[mod Q ]\" := (\\pi_Q x == \\pi_Q y) : quotient_scope.\nNotation \"x = y %[mod Q ]\" := (\\pi_Q x = \\pi_Q y) : quotient_scope.\nNotation \"x != y %[mod Q ]\" := (\\pi_Q x != \\pi_Q y) : quotient_scope.\nNotation \"x <> y %[mod Q ]\" := (\\pi_Q x <> \\pi_Q y) : quotient_scope.\n\nLocal Notation \"\\mpi\" := (@MPi.f _ _ (Phant _)).\nCanonical mpi_unlock := Unlockable MPi.E.\nCanonical pi_unlock := Unlockable Pi.E.\nCanonical repr_unlock := Unlockable Repr.E.\n\nNotation quot_class_of := quot_mixin_of.\nNotation QuotType Q m := (@QuotTypePack _ Q m).\nNotation \"[ 'quotType' 'of' Q ]\" := (@QuotType_clone _ Q _ _ id)\n (at level 0, format \"[ 'quotType'  'of'  Q ]\") : form_scope.\n\nArguments repr {T qT} x.\n\n(************************)\n(* Exporting the theory *)\n(************************)\n\nSection QuotTypeTheory.\n\nVariable T : Type.\nVariable qT : quotType T.\n\nLemma reprK : cancel repr \\pi_qT.\nProof. by move=> x; rewrite !unlock repr_ofK. Qed.\n\nVariant pi_spec (x : T) : T -> Type :=\n  PiSpec y of x = y %[mod qT] : pi_spec x y.\n\nLemma piP (x : T) : pi_spec x (repr (\\pi_qT x)).\nProof. by constructor; rewrite reprK. Qed.\n\nLemma mpiE : \\mpi =1 \\pi_qT.\nProof. by move=> x; rewrite !unlock. Qed.\n\nLemma quotW P : (forall y : T, P (\\pi_qT y)) -> forall x : qT, P x.\nProof. by move=> Py x; rewrite -[x]reprK; apply: Py. Qed.\n\nLemma quotP P : (forall y : T, repr (\\pi_qT y) = y -> P (\\pi_qT y))\n  -> forall x : qT, P x.\nProof. by move=> Py x; rewrite -[x]reprK; apply: Py; rewrite reprK. Qed.\n\nEnd QuotTypeTheory.\n\nArguments reprK {T qT} x.\n\n(*******************)\n(* About morphisms *)\n(*******************)\n\n(* This was pi_morph T (x : T) := PiMorph { pi_op : T; _ : x = pi_op }. *)\nStructure equal_to T (x : T) := EqualTo {\n   equal_val : T;\n   _         : x = equal_val\n}.\nLemma equal_toE (T : Type) (x : T) (m : equal_to x) : equal_val m = x.\nProof. by case: m. Qed.\n\nNotation piE := (@equal_toE _ _).\n\nCanonical equal_to_pi T (qT : quotType T) (x : T) :=\n  @EqualTo _ (\\pi_qT x) (\\pi x) (erefl _).\n\nArguments EqualTo {T x equal_val}.\n\nSection Morphism.\n\nVariables T U : Type.\nVariable (qT : quotType T).\nVariable (qU : quotType U).\n\nVariable (f : T -> T) (g : T -> T -> T) (p : T -> U) (r : T -> T -> U).\nVariable (fq : qT -> qT) (gq : qT -> qT -> qT) (pq : qT -> U) (rq : qT -> qT -> U).\nVariable (h : T -> U) (hq : qT -> qU).\nHypothesis pi_f : {morph \\pi : x / f x >-> fq x}.\nHypothesis pi_g : {morph \\pi : x y / g x y >-> gq x y}.\nHypothesis pi_p : {mono \\pi : x / p x >-> pq x}.\nHypothesis pi_r : {mono \\pi : x y / r x y >-> rq x y}.\nHypothesis pi_h : forall (x : T), \\pi_qU (h x) = hq (\\pi_qT x).\nVariables (a b : T) (x : equal_to (\\pi_qT a)) (y : equal_to (\\pi_qT b)).\n\n(* Internal Lemmmas : do not use directly *)\nLemma pi_morph1 : \\pi (f a) = fq (equal_val x). Proof. by rewrite !piE. Qed.\nLemma pi_morph2 : \\pi (g a b) = gq (equal_val x) (equal_val y). Proof. by rewrite !piE. Qed.\nLemma pi_mono1 : p a = pq (equal_val x). Proof. by rewrite !piE. Qed.\nLemma pi_mono2 : r a b = rq (equal_val x) (equal_val y). Proof. by rewrite !piE. Qed.\nLemma pi_morph11 : \\pi (h a) = hq (equal_val x). Proof. by rewrite !piE. Qed.\n\nEnd Morphism.\n\nArguments pi_morph1 {T qT f fq}.\nArguments pi_morph2 {T qT g gq}.\nArguments pi_mono1 {T U qT p pq}.\nArguments pi_mono2 {T U qT r rq}.\nArguments pi_morph11 {T U qT qU h hq}.\n\nNotation \"{pi_ Q a }\" := (equal_to (\\pi_Q a)) : quotient_scope.\nNotation \"{pi a }\" := (equal_to (\\pi a)) : quotient_scope.\n\n(* Declaration of morphisms *)\nNotation PiMorph pi_x := (EqualTo pi_x).\nNotation PiMorph1 pi_f :=\n  (fun a (x : {pi a}) => EqualTo (pi_morph1 pi_f a x)).\nNotation PiMorph2 pi_g :=\n  (fun a b (x : {pi a}) (y : {pi b}) => EqualTo (pi_morph2 pi_g a b x y)).\nNotation PiMono1 pi_p :=\n  (fun a (x : {pi a}) => EqualTo (pi_mono1 pi_p a x)).\nNotation PiMono2 pi_r :=\n  (fun a b (x : {pi a}) (y : {pi b}) => EqualTo (pi_mono2 pi_r a b x y)).\nNotation PiMorph11 pi_f :=\n  (fun a (x : {pi a}) => EqualTo (pi_morph11 pi_f a x)).\n\n(* lifiting helpers *)\nNotation lift_op1 Q f := (locked (fun x : Q => \\pi_Q (f (repr x)) : Q)).\nNotation lift_op2 Q g := \n  (locked (fun x y : Q => \\pi_Q (g (repr x) (repr y)) : Q)).\nNotation lift_fun1 Q f := (locked (fun x : Q => f (repr x))).\nNotation lift_fun2 Q g := (locked (fun x y : Q => g (repr x) (repr y))).\nNotation lift_op11 Q Q' f := (locked (fun x : Q => \\pi_Q' (f (repr x)) : Q')).\n\n(* constant declaration *)\nNotation lift_cst Q x := (locked (\\pi_Q x : Q)).\nNotation PiConst a := (@EqualTo _ _ a (lock _)).\n\n(* embedding declaration, please don't redefine \\pi *)\nNotation lift_embed qT e := (locked (fun x => \\pi_qT (e x) : qT)).\n\nLemma eq_lock T T' e : e =1 (@locked (T -> T') (fun x : T => e x)).\nProof. by rewrite -lock. Qed.\nPrenex Implicits eq_lock.\n\nNotation PiEmbed e := \n  (fun x => @EqualTo _ _ (e x) (eq_lock (fun _ => \\pi _) _)).\n\n(********************)\n(* About eqQuotType *)\n(********************)\n\nSection EqQuotTypeStructure.\n\nVariable T : Type.\nVariable eq_quot_op : rel T.\n\nDefinition eq_quot_mixin_of (Q : Type) (qc : quot_class_of T Q)\n  (ec : Equality.class_of Q) :=\n  {mono \\pi_(QuotTypePack qc) : x y /\n   eq_quot_op x y >-> @eq_op (Equality.Pack ec) x y}.\n\nRecord eq_quot_class_of (Q : Type) : Type := EqQuotClass {\n  eq_quot_quot_class :> quot_class_of T Q;\n  eq_quot_eq_mixin :> Equality.class_of Q;\n  pi_eq_quot_mixin :> eq_quot_mixin_of eq_quot_quot_class eq_quot_eq_mixin\n}.\n\nRecord eqQuotType : Type := EqQuotTypePack {\n  eq_quot_sort :> Type;\n  _ : eq_quot_class_of eq_quot_sort;\n \n}.\n\nImplicit Type eqT : eqQuotType.\n\nDefinition eq_quot_class eqT : eq_quot_class_of eqT :=\n  let: EqQuotTypePack _ cT as qT' := eqT return eq_quot_class_of qT' in cT.\n\nCanonical eqQuotType_eqType eqT := EqType eqT (eq_quot_class eqT).\nCanonical eqQuotType_quotType eqT := QuotType eqT (eq_quot_class eqT).\n\nCoercion eqQuotType_eqType : eqQuotType >-> eqType.\nCoercion eqQuotType_quotType : eqQuotType >-> quotType.\n\nDefinition EqQuotType_pack Q :=\n  fun (qT : quotType T) (eT : eqType) qc ec \n  of phant_id (quot_class qT) qc & phant_id (Equality.class eT) ec => \n    fun m => EqQuotTypePack (@EqQuotClass Q qc ec m).\n\nDefinition EqQuotType_clone (Q : Type) eqT cT \n  of phant_id (eq_quot_class eqT) cT := @EqQuotTypePack Q cT.\n\nLemma pi_eq_quot eqT : {mono \\pi_eqT : x y / eq_quot_op x y >-> x == y}.\nProof. by case: eqT => [] ? []. Qed.\n\nCanonical pi_eq_quot_mono eqT := PiMono2 (pi_eq_quot eqT).\n\nEnd EqQuotTypeStructure.\n\nNotation EqQuotType e Q m := (@EqQuotType_pack _ e Q _ _ _ _ id id m).\nNotation \"[ 'eqQuotType' e 'of' Q ]\" := (@EqQuotType_clone _ e Q _ _ id)\n (at level 0, format \"[ 'eqQuotType'  e  'of'  Q ]\") : form_scope.\n\n(**************************************************************************)\n(* Even if a quotType is a natural subType, we do not make this subType   *)\n(* canonical, to allow the user to define the subtyping he wants. However *)\n(* one can:                                                               *)\n(* - get the eqMixin and the choiceMixin by subtyping                     *)\n(* - get the subType structure and maybe declare it Canonical.            *)\n(**************************************************************************)\n\nModule QuotSubType.\nSection SubTypeMixin.\n\nVariable T : eqType.\nVariable qT : quotType T.\n\nDefinition Sub x (px : repr (\\pi_qT x) == x) := \\pi_qT x.\n\nLemma qreprK x Px : repr (@Sub x Px) = x.\nProof. by rewrite /Sub (eqP Px). Qed.\n\nLemma sortPx (x : qT) : repr (\\pi_qT (repr x)) == repr x.\nProof. by rewrite !reprK eqxx. Qed.\n\nLemma sort_Sub (x : qT) : x = Sub (sortPx x).\nProof. by rewrite /Sub reprK. Qed.\n\nLemma reprP K (PK : forall x Px, K (@Sub x Px)) u : K u.\nProof. by rewrite (sort_Sub u); apply: PK. Qed.\n\nCanonical subType  := SubType _ _ _ reprP qreprK.\nDefinition eqMixin := Eval hnf in [eqMixin of qT by <:].\n\nCanonical eqType := EqType qT eqMixin.\n\nEnd SubTypeMixin.\n\nDefinition choiceMixin (T : choiceType) (qT : quotType T) :=\n  Eval hnf in [choiceMixin of qT by <:].\nCanonical choiceType (T : choiceType) (qT : quotType T) :=\n  ChoiceType qT (@choiceMixin T qT).\n\nDefinition countMixin (T : countType) (qT : quotType T) :=\n  Eval hnf in [countMixin of qT by <:].\nCanonical countType (T : countType) (qT : quotType T) :=\n  CountType qT (@countMixin T qT).\n\nSection finType.\nVariables (T : finType) (qT : quotType T).\nCanonical subCountType := [subCountType of qT].\nDefinition finMixin := Eval hnf in [finMixin of qT by <:].\nEnd finType.\n\nEnd QuotSubType.\n\nNotation \"[ 'subType' Q 'of' T 'by' %/ ]\" :=\n(@SubType T _ Q _ _ (@QuotSubType.reprP _ _) (@QuotSubType.qreprK _ _))\n(at level 0, format \"[ 'subType'  Q  'of'  T  'by'  %/ ]\") : form_scope.\n\nNotation \"[ 'eqMixin' 'of' Q 'by' <:%/ ]\" := \n  (@QuotSubType.eqMixin _ _: Equality.class_of Q)\n  (at level 0, format \"[ 'eqMixin'  'of'  Q  'by'  <:%/ ]\") : form_scope.\n\nNotation \"[ 'choiceMixin' 'of' Q 'by' <:%/ ]\" := \n  (@QuotSubType.choiceMixin _ _: Choice.mixin_of Q)\n  (at level 0, format \"[ 'choiceMixin'  'of'  Q  'by'  <:%/ ]\") : form_scope.\n\nNotation \"[ 'countMixin' 'of' Q 'by' <:%/ ]\" := \n  (@QuotSubType.countMixin _ _: Countable.mixin_of Q)\n  (at level 0, format \"[ 'countMixin'  'of'  Q  'by'  <:%/ ]\") : form_scope.\n\nNotation \"[ 'finMixin' 'of' Q 'by' <:%/ ]\" := \n  (@QuotSubType.finMixin _ _: Finite.mixin_of Q)\n  (at level 0, format \"[ 'finMixin'  'of'  Q  'by'  <:%/ ]\") : form_scope.\n\n(****************************************************)\n(* Definition of a (decidable) equivalence relation *)\n(****************************************************)\n\nSection EquivRel.\n\nVariable T : Type.\n\nLemma left_trans (e : rel T) :\n  symmetric e -> transitive e -> left_transitive e.\nProof. by move=> s t ? * ?; apply/idP/idP; apply: t; rewrite // s. Qed.\n\nLemma right_trans (e : rel T) :\n  symmetric e -> transitive e -> right_transitive e.\nProof. by move=> s t ? * x; rewrite ![e x _]s; apply: left_trans. Qed.\n\nVariant equiv_class_of (equiv : rel T) :=\n  EquivClass of reflexive equiv & symmetric equiv & transitive equiv.\n\nRecord equiv_rel := EquivRelPack {\n  equiv :> rel T;\n  _ : equiv_class_of equiv\n}.\n\nVariable e : equiv_rel.\n\nDefinition equiv_class :=\n  let: EquivRelPack _ ce as e' := e return equiv_class_of e' in ce.\n\nDefinition equiv_pack (r : rel T) ce of phant_id ce equiv_class :=\n  @EquivRelPack r ce.\n\nLemma equiv_refl x : e x x. Proof. by case: e => [] ? []. Qed.\nLemma equiv_sym : symmetric e. Proof. by case: e => [] ? []. Qed.\nLemma equiv_trans : transitive e. Proof. by case: e => [] ? []. Qed.\n\nLemma eq_op_trans (T' : eqType) : transitive (@eq_op T').\nProof. by move=> x y z; move/eqP->; move/eqP->. Qed.\n\nLemma equiv_ltrans: left_transitive e.\nProof. by apply: left_trans; [apply: equiv_sym|apply: equiv_trans]. Qed.\n\nLemma equiv_rtrans: right_transitive e.\nProof. by apply: right_trans; [apply: equiv_sym|apply: equiv_trans]. Qed.\n\nEnd EquivRel.\n\nHint Resolve equiv_refl : core.\n\nNotation EquivRel r er es et := (@EquivRelPack _ r (EquivClass er es et)).\nNotation \"[ 'equiv_rel' 'of' e ]\" := (@equiv_pack _ _ e _ id)\n (at level 0, format \"[ 'equiv_rel'  'of'  e ]\") : form_scope.\n\n(**************************************************)\n(* Encoding to another type modulo an equivalence *)\n(**************************************************)\n\nSection EncodingModuloRel.\n\nVariables (D E : Type) (ED : E -> D) (DE : D -> E) (e : rel D).\n\nVariant encModRel_class_of (r : rel D) :=\n  EncModRelClassPack of (forall x, r x x -> r (ED (DE x)) x) & (r =2 e).\n\nRecord encModRel := EncModRelPack {\n  enc_mod_rel :> rel D;\n  _ : encModRel_class_of enc_mod_rel\n}.\n\nVariable r : encModRel.\n\nDefinition encModRelClass := \n  let: EncModRelPack _ c as r' := r return encModRel_class_of r' in c.\n\nDefinition encModRelP (x : D) : r x x -> r (ED (DE x)) x.\nProof. by case: r => [] ? [] /= he _ /he. Qed.\n\nDefinition encModRelE : r =2 e. Proof. by case: r => [] ? []. Qed.\n\nDefinition encoded_equiv : rel E := [rel x y | r (ED x) (ED y)].\n\nEnd EncodingModuloRel.\n\nNotation EncModRelClass m :=\n  (EncModRelClassPack (fun x _ => m x) (fun _ _ => erefl _)).\nNotation EncModRel r m := (@EncModRelPack _ _ _ _ _ r (EncModRelClass m)).\n\nSection EncodingModuloEquiv.\n\nVariables (D E : Type) (ED : E -> D) (DE : D -> E) (e : equiv_rel D).\nVariable (r : encModRel ED DE e).\n\nLemma enc_mod_rel_is_equiv : equiv_class_of (enc_mod_rel r).\nProof.\nsplit => [x|x y|y x z]; rewrite !encModRelE //; first by rewrite equiv_sym.\nby move=> exy /(equiv_trans exy).\nQed.\n\nDefinition enc_mod_rel_equiv_rel := EquivRelPack enc_mod_rel_is_equiv.\n\nDefinition encModEquivP (x : D) : r (ED (DE x)) x.\nProof. by rewrite encModRelP ?encModRelE. Qed.\n\nLocal Notation e' := (encoded_equiv r).\n\nLemma encoded_equivE : e' =2 [rel x y | e (ED x) (ED y)].\nProof. by move=> x y; rewrite /encoded_equiv /= encModRelE. Qed.\nLocal Notation e'E := encoded_equivE.\n\nLemma encoded_equiv_is_equiv : equiv_class_of e'.\nProof.\nsplit => [x|x y|y x z]; rewrite !e'E //=; first by rewrite equiv_sym.\nby move=> exy /(equiv_trans exy).\nQed.\n\nCanonical encoded_equiv_equiv_rel := EquivRelPack encoded_equiv_is_equiv.\n\nLemma encoded_equivP x : e' (DE (ED x)) x.\nProof. by rewrite /encoded_equiv /= encModEquivP. Qed.\n\nEnd EncodingModuloEquiv.\n\n(**************************************)\n(* Quotient by a equivalence relation *)\n(**************************************)\n\nModule EquivQuot.\nSection EquivQuot.\n\nVariables (D : Type) (C : choiceType) (CD : C -> D) (DC : D -> C).\nVariables (eD : equiv_rel D) (encD : encModRel CD DC eD).\nNotation eC := (encoded_equiv encD).\n\nDefinition canon x := choose (eC x) (x).\n\nRecord equivQuotient := EquivQuotient {\n  erepr : C;\n  _ : (frel canon) erepr erepr\n}.\n\nDefinition type_of of (phantom (rel _) encD) := equivQuotient.\n\nLemma canon_id : forall x, (invariant canon canon) x.\nProof.\nmove=> x /=; rewrite /canon (@eq_choose _ _ (eC x)).\n  by rewrite (@choose_id _ (eC x) _ x) ?chooseP ?equiv_refl.\nby move=> y; apply: equiv_ltrans; rewrite equiv_sym /= chooseP.\nQed.\n\nDefinition pi := locked (fun x => EquivQuotient (canon_id x)).\n\nLemma ereprK : cancel erepr pi.\nProof.\nunlock pi; case=> x hx; move/eqP:(hx)=> hx'.\nexact: (@val_inj _ _ [subType for erepr]).\nQed.\n\nLocal Notation encDE := (encModRelE encD).\nLocal Notation encDP := (encModEquivP encD).\nCanonical encD_equiv_rel := EquivRelPack (enc_mod_rel_is_equiv encD).\n\nLemma pi_CD (x y : C) : reflect (pi x = pi y) (eC x y).\nProof.\napply: (iffP idP) => hxy.\n  apply: (can_inj ereprK); unlock pi canon => /=.\n  rewrite -(@eq_choose _ (eC x) (eC y)); last first.\n    by move=> z; rewrite /eC /=; apply: equiv_ltrans.\n  by apply: choose_id; rewrite ?equiv_refl //.\nrewrite (equiv_trans (chooseP (equiv_refl _ _))) //=.\nmove: hxy => /(f_equal erepr) /=; unlock pi canon => /= ->.\nby rewrite equiv_sym /= chooseP.\nQed.\n\nLemma pi_DC (x y : D) :\n  reflect (pi (DC x) = pi (DC y)) (eD x y).\nProof.\napply: (iffP idP)=> hxy.\n  apply/pi_CD; rewrite /eC /=.\n  by rewrite (equiv_ltrans (encDP _)) (equiv_rtrans (encDP _)) /= encDE.\nrewrite -encDE -(equiv_ltrans (encDP _)) -(equiv_rtrans (encDP _)) /=.\nexact/pi_CD.\nQed.\n\nLemma equivQTP : cancel (CD \\o erepr) (pi \\o DC).\nProof.\nby move=> x; rewrite /= (pi_CD _ (erepr x) _) ?ereprK /eC /= ?encDP.\nQed.\n\nLocal Notation qT := (type_of (Phantom (rel D) encD)).\nDefinition quotClass := QuotClass equivQTP.\nCanonical quotType := QuotType qT quotClass.\n\nLemma eqmodP x y : reflect (x = y %[mod qT]) (eD x y).\nProof. by apply: (iffP (pi_DC _ _)); rewrite !unlock. Qed.\n\nFact eqMixin : Equality.mixin_of qT. Proof. exact: CanEqMixin ereprK. Qed.\nCanonical eqType := EqType qT eqMixin.\nDefinition choiceMixin := CanChoiceMixin ereprK.\nCanonical choiceType := ChoiceType qT choiceMixin.\n\nLemma eqmodE x y : x == y %[mod qT] = eD x y.\nProof. exact: sameP eqP (@eqmodP _ _). Qed.\n\nCanonical eqQuotType := EqQuotType eD qT eqmodE.\n\nEnd EquivQuot.\nEnd EquivQuot.\n\nCanonical EquivQuot.quotType.\nCanonical EquivQuot.eqType.\nCanonical EquivQuot.choiceType.\nCanonical EquivQuot.eqQuotType.\n\nArguments EquivQuot.ereprK {D C CD DC eD encD}.\n\nNotation \"{eq_quot e }\" :=\n(@EquivQuot.type_of _ _ _ _ _ _ (Phantom (rel _) e)) : quotient_scope.\nNotation \"x == y %[mod_eq r ]\" := (x == y %[mod {eq_quot r}]) : quotient_scope.\nNotation \"x = y %[mod_eq r ]\" := (x = y %[mod {eq_quot r}]) : quotient_scope.\nNotation \"x != y %[mod_eq r ]\" := (x != y %[mod {eq_quot r}]) : quotient_scope.\nNotation \"x <> y %[mod_eq r ]\" := (x <> y %[mod {eq_quot r}]) : quotient_scope.\n\n(***********************************************************)\n(* If the type is directly a choiceType, no need to encode *)\n(***********************************************************)\n\nSection DefaultEncodingModuloRel.\n\nVariables (D : choiceType) (r : rel D).\n\nDefinition defaultEncModRelClass :=\n  @EncModRelClassPack D D id id r r (fun _ rxx => rxx) (fun _ _ => erefl _).\n\nCanonical defaultEncModRel := EncModRelPack defaultEncModRelClass.\n\nEnd DefaultEncodingModuloRel.\n\n(***************************************************)\n(* Recovering a potential countable type structure *)\n(***************************************************)\n\nSection CountEncodingModuloRel.\n\nVariables (D : Type) (C : countType) (CD : C -> D) (DC : D -> C).\nVariables (eD : equiv_rel D) (encD : encModRel CD DC eD).\nNotation eC := (encoded_equiv encD).\n\nFact eq_quot_countMixin : Countable.mixin_of {eq_quot encD}.\nProof. exact: CanCountMixin EquivQuot.ereprK. Qed.\nCanonical eq_quot_countType := CountType {eq_quot encD} eq_quot_countMixin.\n\nEnd CountEncodingModuloRel.\n\nSection EquivQuotTheory.\n\nVariables (T : choiceType) (e : equiv_rel T) (Q : eqQuotType e).\n\nLemma eqmodE x y : x == y %[mod_eq e] = e x y.\nProof. by rewrite pi_eq_quot. Qed.\n\nLemma eqmodP x y : reflect (x = y %[mod_eq e]) (e x y).\nProof. by rewrite -eqmodE; apply/eqP. Qed.\n\nEnd EquivQuotTheory.\n\nPrenex Implicits eqmodE eqmodP.\n\nSection EqQuotTheory.\n\nVariables (T : Type) (e : rel T) (Q : eqQuotType e).\n\nLemma eqquotE x y : x == y %[mod Q] = e x y.\nProof. by rewrite pi_eq_quot. Qed.\n\nLemma eqquotP x y : reflect (x = y %[mod Q]) (e x y).\nProof. by rewrite -eqquotE; apply/eqP. Qed.\n\nEnd EqQuotTheory.\n\nPrenex Implicits eqquotE eqquotP.\n", "meta": {"author": "palmskog", "repo": "mathcomp-experiment", "sha": "67a6e83c025784b1e6f646a30dde38e0f33060eb", "save_path": "github-repos/coq/palmskog-mathcomp-experiment", "path": "github-repos/coq/palmskog-mathcomp-experiment/mathcomp-experiment-67a6e83c025784b1e6f646a30dde38e0f33060eb/ssreflect/generic_quotient.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199592797929, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6533376299168794}}
{"text": "Require Import List.\n\n(* Filter *)\n\nSection Filter.\n  Variable X : Type.\n  Implicit Types (x y: X) (A B C: list X) (p q: X -> bool).\n\n  Local Notation \"x 'el' L\" := (In x L) (at level 50).\n\n  Lemma in_filter_iff x p A :\n    x el filter p A <-> x el A /\\ p x = true.\n  Proof. \n    induction A as [|y A]; cbn.\n    - tauto.\n    - destruct (p y) eqn:E; cbn;\n      rewrite IHA; intuition; subst; auto. congruence.\n  Qed.\n\n  Local Notation \"A '<<=' B\" := (incl A B) (at level 50).\n\n  Lemma filter_incl p A :\n    filter p A <<= A.  \n  Proof.\n    intros x D. apply in_filter_iff in D. apply D.\n  Qed.\n\n  Lemma filter_mono p A B :\n    A <<= B -> filter p A <<= filter p B.\n  Proof.\n    intros D x E. apply in_filter_iff in E as [E E'].\n    apply in_filter_iff. auto.\n  Qed.\n\n  Lemma filter_id p A :\n    (forall x, x el A -> p x = true) -> filter p A = A.\n  Proof.\n    intros D.\n    induction A as [|x A]; cbn.\n    - reflexivity.\n    - destruct (p x) eqn:E.\n      + f_equal. eapply IHA. intros y H. apply D. cbn. eauto.\n      + exfalso. rewrite D in E. congruence. cbn. eauto.\n  Qed.\n\n  Lemma filter_app p A B :\n    filter p (A ++ B) = filter p A ++ filter p B.\n  Proof.\n    induction A as [|y A]; cbn.\n    - reflexivity.\n    - rewrite IHA. destruct (p y); reflexivity.  \n  Qed.\n\n  Lemma filter_fst p x A :\n    p x = true -> filter p (x::A) = x::filter p A.\n  Proof.\n    cbn. destruct (p x); auto. congruence.\n  Qed.\n\n  Lemma filter_fst' p x A :\n    p x = false -> filter p (x::A) = filter p A.\n  Proof.\n    cbn. destruct (p x); auto; congruence.\n  Qed.\n\n  Lemma filter_pq_mono p q A :\n    (forall x, x el A -> p x = true -> q x = true) -> filter p A <<= filter q A.\n  Proof. \n    intros D x E. apply in_filter_iff in E as [E E'].\n    apply in_filter_iff. auto.\n  Qed.\n\n  Lemma filter_pq_eq p q A :\n    (forall x, x el A -> p x = q x) -> filter p A = filter q A.\n  Proof. \n    intros C; induction A as [|x A]; cbn.\n    - reflexivity.\n    - destruct (p x) eqn:D, (q x) eqn:E.\n      + f_equal. eapply IHA. intros. eapply C. cbn. eauto.\n      + exfalso. enough (p x = q x) by congruence. firstorder.\n      + exfalso. enough (p x = q x) by congruence. firstorder.\n      + firstorder.\n  Qed.\n\n  Lemma filter_and p q A :\n    filter p (filter q A) = filter (fun x => andb (p x) (q x)) A.\n  Proof.\n    induction A as [|x A]; cbn. reflexivity.\n    destruct (p x) eqn:E, (q x); cbn;\n      try rewrite E; now rewrite IHA.\n  Qed.\n\n  Lemma filter_comm p q A :\n    filter p (filter q A) = filter q (filter p A).\n  Proof.\n    rewrite !filter_and. apply filter_pq_eq.\n    intros x _. now destruct (p x), (q x).\n  Qed.\n  \nEnd Filter.\n", "meta": {"author": "uds-psl", "repo": "constructive-and-synthetic-reducibility-in-coq", "sha": "3bd7c2e7c311d17bb93a9edcd55e39fc1ad9aa9d", "save_path": "github-repos/coq/uds-psl-constructive-and-synthetic-reducibility-in-coq", "path": "github-repos/coq/uds-psl-constructive-and-synthetic-reducibility-in-coq/constructive-and-synthetic-reducibility-in-coq-3bd7c2e7c311d17bb93a9edcd55e39fc1ad9aa9d/Shared/FilterFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6533376265507135}}
{"text": "Set Universe Polymorphism.\n\n(*\nWe show how to prove the induction principle of parametrized lists\nfrom the induction principle for indexed lists.\n*)\n\n(*\nWhen trying to prove the parametric induction principle for list T,\ngiven P : list T -> Type you can take as your predicate\nP' : forall T', list T' -> Type such that P T' l := forall e : T = T', (transp P e) l.\nThis way you always have an equality between T (which you know things about)\nand an arbitrary T' which you can use to specialize.\n*)\n\nInductive list_param@{i j | i <= j} (T : Type@{i}) : Type@{j} :=\n  | nilp : list_param T\n  | consp : T -> list_param T -> list_param T.\nCheck list_param_rect.\n(*\nlist_param_rect\n     : forall (T : Type) (P : list_param T -> Type),\n       P (nilp T) ->\n       (forall (t : T) (l : list_param T), P l -> P (consp T t l)) ->\n       forall l : list_param T, P l\n*)\n\nInductive list_index@{i j | i < j} : Type@{i} -> Type@{j} :=\n  | nili : forall (A : Type@{i}), list_index A\n  | consi : forall (A : Type@{i}), A -> list_index A -> list_index A\n  .\nCheck list_index_rect.\n(*\nlist_index_rect\n     : forall P : forall T : Type, list_index T -> Type,\n       (forall A : Type, P A (nili A)) ->\n       (forall (A : Type) (a : A) (l : list_index A), P A l -> P A (consi A a l)) ->\n       forall (T : Type) (l : list_index T), P T l\n*)\n\nDefinition list_param_rect_from_index_rect (T : Type) (P : list_index T -> Type)\n  (step_nil : P (nili T))\n  (step_cons : forall (t : T) (l : list_index T), P l -> P (consi T t l))\n  (l : list_index T)\n  : P l\n  := let P' T' (l : list_index T') : Type\n      := forall e : T = T',\n         (eq_rect T (fun T => list_index T -> Type) P T' e) l\n     in\n     list_index_rect P'\n     (* nil case *)\n     (fun A e =>\n      match e in _ = A\n      return\n        (eq_rect T (fun T => list_index T -> Type) P A e) (nili A)\n      with eq_refl => step_nil\n      end)\n     (* cons case *)\n     (fun A a l IH e =>\n      match e in _ = A\n      return\n        forall a l, P' A l ->\n        (eq_rect T (fun T => list_index T -> Type) P A e) (consi A a l)\n      with eq_refl => fun a l IH => step_cons a l (IH eq_refl)\n      end a l IH)\n     T\n     l\n     eq_refl.\n", "meta": {"author": "jashug", "repo": "MiscTypeTheory", "sha": "8f8995809c0d2bc8b1418bba793ce3766f013d8b", "save_path": "github-repos/coq/jashug-MiscTypeTheory", "path": "github-repos/coq/jashug-MiscTypeTheory/MiscTypeTheory-8f8995809c0d2bc8b1418bba793ce3766f013d8b/Transfer_Indexed_Parameter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6533376265507135}}
{"text": "From sflib Require Import sflib.\n\n\nLemma Forall2_refl\n      A (f: A -> A -> Prop) (a: list A)\n      (REFL: forall x, f x x):\n  List.Forall2 f a a.\nProof.\n  induction a; eauto.\nQed.\n\nLemma Forall2_symm\n      A (f: A -> A -> Prop) (a b: list A)\n      (SYMM: forall x y, f x y -> f y x)\n      (FORALL: List.Forall2 f a b):\n  List.Forall2 f b a.\nProof.\n  induction FORALL; eauto.\nQed.\n\nLemma Forall2_trans\n      A (f: A -> A -> Prop) (a b c: list A)\n      (TRANS: forall x y z, f x y -> f y z -> f x z)\n      (FORALL1: List.Forall2 f a b)\n      (FORALL2: List.Forall2 f b c):\n  List.Forall2 f a c.\nProof.\n  revert c FORALL2.\n  induction FORALL1; eauto. i.\n  inv FORALL2. econs; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/sequential/SeqLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6533376224714277}}
{"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(** Properties of decidable propositions *)\n\nDefinition decidable (P:Prop) := P \\/ ~ P.\n\nTheorem dec_not_not : forall P:Prop, decidable P -> (~ P -> False) -> P.\nProof.\nunfold decidable; tauto.\nQed.\n\nTheorem dec_True : decidable True.\nProof.\nunfold decidable; auto.\nQed.\n\nTheorem dec_False : decidable False.\nProof.\nunfold decidable, not; auto.\nQed.\n\nTheorem dec_or :\n forall A B:Prop, decidable A -> decidable B -> decidable (A \\/ B).\nProof.\nunfold decidable; tauto.\nQed.\n\nTheorem dec_and :\n forall A B:Prop, decidable A -> decidable B -> decidable (A /\\ B).\nProof.\nunfold decidable; tauto.\nQed.\n\nTheorem dec_not : forall A:Prop, decidable A -> decidable (~ A).\nProof.\nunfold decidable; tauto.\nQed.\n\nTheorem dec_imp :\n forall A B:Prop, decidable A -> decidable B -> decidable (A -> B).\nProof.\nunfold decidable; tauto.\nQed.\n\nTheorem dec_iff :\n forall A B:Prop, decidable A -> decidable B -> decidable (A<->B).\nProof.\nunfold decidable; tauto.\nQed.\n\nTheorem not_not : forall P:Prop, decidable P -> ~ ~ P -> P.\nProof.\nunfold decidable; tauto.\nQed.\n\nTheorem not_or : forall A B:Prop, ~ (A \\/ B) -> ~ A /\\ ~ B.\nProof.\ntauto.\nQed.\n\nTheorem not_and : forall A B:Prop, decidable A -> ~ (A /\\ B) -> ~ A \\/ ~ B.\nProof.\nunfold decidable; tauto.\nQed.\n\nTheorem not_imp : forall A B:Prop, decidable A -> ~ (A -> B) -> A /\\ ~ B.\nProof.\nunfold decidable; tauto.\nQed.\n\nTheorem imp_simp : forall A B:Prop, decidable A -> (A -> B) -> ~ A \\/ B.\nProof.\nunfold decidable; tauto.\nQed.\n\nTheorem not_iff :\n  forall A B:Prop, decidable A -> decidable B ->\n    ~ (A <-> B) -> (A /\\ ~ B) \\/ (~ A /\\ B).\nProof.\nunfold decidable; tauto.\nQed.\n\n(** Results formulated with iff, used in FSetDecide.\n    Negation are expanded since it is unclear whether setoid rewrite\n    will always perform conversion. *)\n\n(** We begin with lemmas that, when read from left to right,\n    can be understood as ways to eliminate uses of [not]. *)\n\nTheorem not_true_iff : (True -> False) <-> False.\nProof.\ntauto.\nQed.\n\nTheorem not_false_iff : (False -> False) <-> True.\nProof.\ntauto.\nQed.\n\nTheorem not_not_iff : forall A:Prop, decidable A ->\n  (((A -> False) -> False) <-> A).\nProof.\nunfold decidable; tauto.\nQed.\n\nTheorem contrapositive : forall A B:Prop, decidable A ->\n  (((A -> False) -> (B -> False)) <-> (B -> A)).\nProof.\nunfold decidable; tauto.\nQed.\n\nLemma or_not_l_iff_1 : forall A B: Prop, decidable A ->\n  ((A -> False) \\/ B <-> (A -> B)).\nProof.\nunfold decidable. tauto.\nQed.\n\nLemma or_not_l_iff_2 : forall A B: Prop, decidable B ->\n  ((A -> False) \\/ B <-> (A -> B)).\nProof.\nunfold decidable. tauto.\nQed.\n\nLemma or_not_r_iff_1 : forall A B: Prop, decidable A ->\n  (A \\/ (B -> False) <-> (B -> A)).\nProof.\nunfold decidable. tauto.\nQed.\n\nLemma or_not_r_iff_2 : forall A B: Prop, decidable B ->\n  (A \\/ (B -> False) <-> (B -> A)).\nProof.\nunfold decidable. tauto.\nQed.\n\nLemma imp_not_l : forall A B: Prop, decidable A ->\n  (((A -> False) -> B) <-> (A \\/ B)).\nProof.\nunfold decidable. tauto.\nQed.\n\n\n(** Moving Negations Around:\n    We have four lemmas that, when read from left to right,\n    describe how to push negations toward the leaves of a\n    proposition and, when read from right to left, describe\n    how to pull negations toward the top of a proposition. *)\n\nTheorem not_or_iff : forall A B:Prop,\n  (A \\/ B -> False) <-> (A -> False) /\\ (B -> False).\nProof.\ntauto.\nQed.\n\nLemma not_and_iff : forall A B:Prop,\n  (A /\\ B -> False) <-> (A -> B -> False).\nProof.\ntauto.\nQed.\n\nLemma not_imp_iff : forall A B:Prop, decidable A ->\n  (((A -> B) -> False) <-> A /\\ (B -> False)).\nProof.\nunfold decidable. tauto.\nQed.\n\nLemma not_imp_rev_iff : forall A B : Prop, decidable A ->\n  (((A -> B) -> False) <-> (B -> False) /\\ A).\nProof.\nunfold decidable. tauto.\nQed.\n\n\n\n(** With the following hint database, we can leverage [auto] to check\n    decidability of propositions. *)\n\nHint Resolve dec_True dec_False dec_or dec_and dec_imp dec_not dec_iff\n : decidable_prop.\n\n(** [solve_decidable using lib] will solve goals about the\n    decidability of a proposition, assisted by an auxiliary\n    database of lemmas.  The database is intended to contain\n    lemmas stating the decidability of base propositions,\n    (e.g., the decidability of equality on a particular\n    inductive type). *)\n\nTactic Notation \"solve_decidable\" \"using\" ident(db) :=\n  match goal with\n   | |- decidable _ =>\n     solve [ auto 100 with decidable_prop db ]\n  end.\n\nTactic Notation \"solve_decidable\" :=\n  solve_decidable using core.\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/Logic/Decidable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6533376181876743}}
{"text": "Require Export Ensemble.\n\n(* General topology *)\n\n(* topological spaces *)\nDefinition Topology X cT := cT ⊂ cP(X) ∧\n  X ∈ cT ∧ ∅ ∈ cT ∧ (∀ A B, A ∈ cT → B ∈ cT → A ∩ B ∈ cT) ∧\n  (∀ cT1, cT1 ⊂ cT → ∪cT1 ∈ cT).\n\nDefinition inDiscrete X := [X] ⋃ [∅].\nDefinition Discrete X := cP(X).\n\nExample inDiscreteT : ∀ X, Ensemble X → Topology X (inDiscrete X).\nProof.\n  intros. unfold inDiscrete. repeat split; intros.\n  intros x Hx; unH; sing H0; ens. AppCG; ens. apply EmptySub.\n  AppCG; ens. AppCG; ens. apply IntSinEm; auto. apply EleUSinEm; auto.\nQed.\n\nExample DiscreteT : ∀ X, Ensemble X → Topology X (Discrete X).\nProof.\n  intros. unfold Discrete; repeat split; ens; intros.\n  apply PowerI; auto; apply EmptySub. pow H0; pow H1. AppCG.\n  apply InterEns; eens. intros x Hx; inH; auto.\n  AppCG. eens. intros x Hx; eleU Hx; apply H0 in H2; pow H2.\nQed.\n\n(* neighborhood system *)\nDefinition Neigh x U X cT := Topology X cT ∧ x ∈ X ∧ U ⊂ X ∧\n  ∃ V, V ∈ cT ∧ x ∈ V ∧ V ⊂ U.\nDefinition NeighS x X cT := \\{λ U, Neigh x U X cT\\}.\n\nFact neighF : ∀ x U X cT, Topology X cT → x ∈ U → U ∈ cT → Neigh x U X cT.\nProof.\n  intros. assert (U ⊂ X). apply H in H1; pow H1.\n  red; andG; auto. exists U; andG; ens.\nQed.\n\nFact neigh_F1 : ∀ x U X cT,\n  Ensemble X → Neigh x U X cT ↔ U ∈ NeighS x X cT.\nProof. split; intros. AppCG. eapply SubAxP; eauto. apply H0. AppC H0. Qed.\n\nDefinition EleUx x U cT := ∪\\{λ V, x ∈ U ∧ V ∈ cT ∧ x ∈ V ∧ V ⊂ U \\}.\n\nLemma Le_NeFa : ∀ U, U = ∪(\\{λ t, ∃ x, x ∈ U ∧ t = [x]\\}).\nProof.\n  intro. AppE; AssE x. AppCG. exists [x]. andG; ens. AppCG; ens.\n  eleU H. AppC H1; destruct H1; andH. subst. sing H; Ens.\nQed.\n\nTheorem neigh_T : ∀ U X cT, Ensemble X → Topology X cT → U ⊂ X →\n  (U ∈ cT ↔ ∀ x, x ∈ U → U ∈ NeighS x X cT).\nProof.\n  intros * Hxe Ht Hs. split; intros Hp.\n  - intros. apply neigh_F1, neighF; auto.\n  - DC (U = ∅). subst; apply Ht. set (∪(\\{λ t, ∃ x, x ∈ U ∧\n      t = EleUx x U cT\\})) as Hmi.\n    assert (H1 : ∪(\\{λ t, ∃ x, x ∈ U ∧ t = [x]\\}) ⊂ Hmi).\n    { intros z Hz; eleU Hz. AppC H1; destruct H1; andH. subst.\n      sing H0; Ens. apply Hp in H1 as Hu. AppC Hu. AppCG; Ens.\n      exists (EleUx x0 U cT). andG. AppCG; Ens. destruct Hu as\n        [_ [_ [_ [V [Hv []]]]]]. exists V. andG; auto. AppCG; Ens. AppCG.\n      apply (SubAxP U); eens. intros z Hz. eleU Hz. AppC H2; andH; auto. }\n    rewrite <- Le_NeFa in H1. assert (H2 : Hmi ⊂ U).\n    { intros z Hz. eleU Hz. AppC H2; destruct H2; andH.\n      subst. eleU H0; AppC H3; andH; auto. } assert (U = Hmi). eens.\n    rewrite H0. apply Ht; intros V Hv. AppC Hv; destruct Hv; andH.\n    subst V. apply Ht. intros z Hz; AppC Hz; tauto.\nQed.\n\nTheorem neigh_T1a : ∀ x X cT, Ensemble X → Topology X cT → x ∈ X →\n  ∀ U V, U ∈ NeighS x X cT → V ∈ NeighS x X cT →\n  U ∩ V ∈ NeighS x X cT.\nProof.\n  intros * Hxe Ht Hx * Hu Hv.\n  apply neigh_F1 in Hu as [_ [_ [Hux [U0 [Ho1 []]]]]]; auto.\n  apply neigh_F1 in Hv as [_ [_ [Hvx [V0 [Ho2 []]]]]]; auto.\n  apply neigh_F1; auto. red; andG; auto. intros z Hz; inH; auto.\n  exists (U0 ∩ V0). andG; ens. apply Ht; auto. intros z Hz; inH; ens.\nQed.\n\nTheorem neigh_T1b : ∀ x X cT, Ensemble X → Topology X cT → x ∈ X →\n  ∀ U V, U ∈ NeighS x X cT → V ⊂ X → U ⊂ V → V ∈ NeighS x X cT.\nProof.\n  intros * Hxe Ht Hx * Hu Hv Huv.\n  apply neigh_F1 in Hu as [_ [_ [Hux [U0 [Ho1 []]]]]]; auto.\n  apply neigh_F1; auto. red; andG; auto. exists U0; andG; eens.\nQed.\n\nTheorem neigh_T1c : ∀ x X cT, Ensemble X → Topology X cT → x ∈ X →\n  ∀ U, U ∈ NeighS x X cT → ∃ V, V ∈ NeighS x X cT ∧ V ⊂ U ∧\n  (∀ y, y ∈ V → V ∈ NeighS y X cT).\nProof.\n  intros. apply neigh_F1 in H2 as [_[_[Hu [V [Ho []]]]]]; auto. exists V.\n  andG; auto. apply neigh_F1, neighF; auto. apply neigh_T; eens.\nQed.\n\n(* derived *)\nDefinition Cluster x A X cT := Topology X cT ∧ A ⊂ X ∧ x ∈ X ∧\n  ∀ U, Neigh x U X cT → U ∩ (A - [x]) ≠ ∅.\nDefinition Derived A X cT := \\{λ x, Cluster x A X cT\\}.\n\nFact DerivedP : ∀ A X cT, Derived A X cT ⊂ X.\nProof. intros * x Hx. AppC Hx. apply Hx. Qed.\n\nFact derived_F1 : ∀ x A X cT, Cluster x A X cT ↔ x ∈ Derived A X cT.\nProof. split; intros. AppCG; exists X; apply H. AppC H. Qed.\n\nFact derived_F2 : ∀ x A X cT, Topology X cT → A ⊂ X → x ∈ X →\n  x ∉ Derived A X cT → ∃ U, Neigh x U X cT ∧ U ∩ (A - [x]) = ∅.\nProof.\n  intros * Ht Hs Hx Hp. DC (∃ U, Neigh x U X cT ∧ U ∩ (A - [x]) = ∅).\n  auto. elim Hp; apply derived_F1; red; andG; eauto.\nQed.\n\nTheorem derived_Ta : ∀ A B X cT, B ⊂ X → A ⊂ B → Derived A X cT ⊂ Derived B X cT.\nProof.\n  intros * Hb Hs x Hx. apply derived_F1 in Hx. red in Hx; andH.\n  apply derived_F1. red; andG; auto. intros U Hu. apply H2 in Hu.\n  apply EmptyNE in Hu as [y]. inH; smH.\n  apply EmptyNE. exists y; inG; smG; auto.\nQed.\n\nTheorem derived_Tb : ∀ A B X cT, Ensemble X → A ⊂ X → B ⊂ X →\n  Derived (A ⋃ B) X cT = Derived A X cT ⋃ Derived B X cT.\nProof.\n  intros * Hxe Ha Hb. apply IncAsym.\n  - intros x Hx. pose proof Hx as Hx'. apply derived_F1 in Hx as\n      [Ht [_ [Hx _]]]. DC (x ∈ Derived A X cT ⋃ Derived B X cT); auto.\n    apply UnionNE in H; andH. apply derived_F2 in H as [U [Hun Hu]];\n    apply derived_F2 in H0 as [V [Hvn Hv]]; auto.\n    assert (x ∉ Derived (A ⋃ B) X cT).\n    { intro. apply derived_F1 in H as [_ [_ [_ Hp]]]. set (U ∩ V) as D.\n      assert (D ∈ NeighS x X cT). apply neigh_T1a; auto;\n      apply neigh_F1; auto. apply neigh_F1, Hp in H; auto.\n      assert (D ∩ (A ⋃ B) - [x] = ∅).\n      { assert ((A ⋃ B) - [x] = A - [x] ⋃ B - [x]). AppE. smH; unH; ens.\n        unH; smH; smG; ens. rewrite H0, DistribuLI. AppE; [|exfalso0].\n        rewrite <- Hu, <- (EmptyU (U ∩ A - [x])), <- Hv.\n        unH;inH;smH;AppC H1; andH; [unG|apply UnionI']; inG; smG; auto. }\n       auto. } tauto.\n  - assert (Derived A X cT ⊂ Derived (A ⋃ B) X cT ∧\n      Derived B X cT ⊂ Derived (A ⋃ B) X cT).\n    { andG; apply derived_Ta; intros x Hx; unH; ens. }\n    andH; intros x Hx; unH; auto.\nQed.\n\nTheorem derived_Tc : ∀ A X cT, Ensemble X → A ⊂ X →\n  Derived (Derived A X cT) X cT ⊂ A ⋃ Derived A X cT.\nProof.\n  intros * Hxe Ha x Hx. pose proof Hx as Hx'. apply derived_F1 in Hx as\n    [Ht [_ [Hx _]]]. DC (x ∈ A ⋃ Derived A X cT); auto. exfalso.\n  apply UnionNE in H as [Hxa Hxd]. apply derived_F2 in Hxd as\n    [U [Hun Hue]]; auto. apply neigh_F1 in Hun as Hun'; auto.\n  apply neigh_T1c in Hun' as [V [Hvn [Hvu Hp]]]; auto.\n  apply neigh_T in Hp as Hp'; auto; [|apply neigh_F1 in Hvn; auto;\n  eapply IncTran; eauto; apply Hun]. assert (V ∩ A - [x] = ∅).\n  { AppE; [|exfalso0]. rewrite <- Hue. inH; smH. inG; smG; auto. }\n  assert (V ∩ A = ∅). { eapply InterEqEmI; revgoals; eauto; Ens. }\n  assert (∀ y, y ∈ V → y ∉ A).\n  { intros * Hy H1. assert (y ∈ V ∩ A); ens. rewrite H0 in H2. exfalso0. }\n  assert (∀ y, y ∈ V → V ∩ A - [y] = ∅).\n  { intros. AppE; [|exfalso0]. inH; smH. apply H1 in H3; tauto. }\n  assert (∀ y, y ∈ V → y ∉ Derived A X cT).\n  { intros * Hy H3. apply H2 in Hy as Hyp. apply derived_F1 in H3.\n    apply Hp, neigh_F1, H3 in Hy; auto. }\n  assert (V ∩ Derived A X cT - [x] = ∅).\n  { AppE; [|exfalso0]. inH; smH. exfalso. apply H3 in H4; auto. }\n  apply derived_F1 in Hx' as [_ [_ [_ Hx']]].\n  AppC Hvn. apply Hx' in Hvn; auto.\nQed.\n\n(* Closed *)\nDefinition Closed A X cT := Topology X cT ∧ A ⊂ X ∧ Derived A X cT ⊂ A.\n\nTheorem closed_T : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Closed A X cT ↔ X - A ∈ cT.\nProof.\n  intros * Hxe Ht Hs. pose proof (SetminSubI A X). split; intros Hp.\n  - eapply neigh_T; eauto. intros. smH. assert (x ∉ Derived A X cT).\n    { intro. apply Hp in H2; tauto. } apply derived_F2 in H2 as\n      [U [Hun Hue]]; auto. apply InterEqEmI in Hue; Ens. \n    apply neigh_F1; auto. red; andG; auto. destruct Hun as\n      [_ [_ [Hu [V [Hv [Hxv Hvu]]]]]]. exists V. andG; auto.\n    eapply IncTran; eauto. intros z Hz. smG; auto. intro.\n    assert (z ∈ U ∩ A); ens. rewrite Hue in H3; exfalso0.\n  - red; andG; auto. intros x Hx. DC (x ∈ A); auto. exfalso.\n    assert (x ∈ X - A). { AppC Hx. smG; auto. apply Hx. }\n    eapply neigh_T, neigh_F1 in H1; eauto. pose proof Hx.\n    apply derived_F1 in Hx as [_ [_ [_ Hx]]]. apply Hx in H1.\n    assert (X-A ∩ A-[x] = ∅). AppE; [|exfalso0]; inH; smH; tauto. auto.\nQed.\n\nCorollary closed_C : ∀ A X cT,\n  Ensemble X → Topology X cT → A ⊂ X → A ∈ cT → Closed (X - A) X cT.\nProof.\n  intros. apply closed_T; auto.\n  apply SetminSubI. rewrite TwoCompl; auto.\nQed.\n\n(* closure *)\nDefinition Closure A X cT := A ⋃ Derived A X cT.\n\nFact closureP : ∀ A X cT, A ⊂ X → Closure A X cT ⊂ X.\nProof. intros * Ha x Hx. AppC Hx; orH; auto. apply DerivedP in H; auto. Qed.\n\nFact closure_F1 : ∀ A X cT, A ⊂ Closure A X cT .\nProof. intros * x Hx. AppCG; Ens. Qed.\n\nFact closure_F2 : ∀ A B X cT, B ⊂ X → A ⊂ B → Closure A X cT ⊂ Closure B X cT.\nProof.\n  unfold Closure; intros * Hb Hs x Hx. unH; ens.\n  apply UnionI'. eapply derived_Ta; eauto.\nQed.\n\nFact closure_F3 : ∀ A B X cT, Ensemble X → Topology X cT →\n  A ⊂ X → B ⊂ X → Closure (A ⋃ B) X cT = Closure A X cT ⋃ Closure B X cT.\nProof.\n  intros * Hxe Ht Ha Hb. unfold Closure. rewrite derived_Tb,\n    AssocU, (CommuU B), <- AssocU, <- AssocU, AssocU, (CommuU _ B); auto.\nQed.\n\nFact closure_F4 : ∀ A B X cT, Ensemble X → Topology X cT →\n  A ⊂ X → B ⊂ X → Closure (A ⋃ B) X cT = Closure A X cT ⋃ Closure B X cT.\nProof.\n  intros * Hxe Ht Ha Hb. unfold Closure. rewrite derived_Tb,\n    AssocU, (CommuU B), <- AssocU, <- AssocU, AssocU, (CommuU _ B); auto.\nQed.\n\nTheorem closure_T : ∀ A X cT, Topology X cT → A ⊂ X →\n  Closed A X cT ↔ A = Closure A X cT.\nProof.\n  intros * Ht Hs. split.\n  - intros [_ [_ Hp]]. unfold Closure. AppE; [|unH]; ens.\n  - intros. red; andG; auto. rewrite H at 2; intros z HZ; AppCG; Ens.\nQed.\n\nTheorem closure_T1 : ∀ X cT, Ensemble X → Topology X cT → Closure ∅ X cT = ∅.\nProof.\n  intros. pose proof (EmptySub X). symmetry; apply closure_T; auto.\n  apply closed_T; auto. rewrite SetminEm; apply H0.\nQed.\n\nTheorem closure_T2 : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Closure (Closure A X cT) X cT = Closure A X cT.\nProof.\n  intros * He Ht Hs. unfold Closure at 2. rewrite closure_F3; auto;\n  [|apply DerivedP]. unfold Closure. rewrite AssocU,\n    <- (AssocU (Derived A X cT) _ _), IdemU,\n    <- AssocU, CommuU, IncU; auto. apply derived_Tc; auto.\nQed.\n\nFact closure_F5 : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Closed (Closure A X cT) X cT.\nProof.\n  intros * Hxe Ht Hs. apply closure_T; auto.\n  apply closureP; auto. rewrite closure_T2; auto.\nQed.\n\n(* Interior *)\nDefinition Interiorp x A X cT := Neigh x A X cT.\nDefinition Interior A X cT := \\{λ x, Interiorp x A X cT \\}.\n\nFact interiorP : ∀ A X cT, Interior A X cT ⊂ X.\nProof.\n  unfold Interior, Interiorp, Neigh.\n  intros * z Hz. AppC Hz. andH. destruct H2; andH; auto.\nQed.\n\nFact interior_F1 : ∀ A X cT, Interior A X cT ⊂ A.\nProof.\n  intros * z Hz. AppC Hz; destruct Hz; andH. destruct H2; andH; auto.\nQed.\n\nFact interior_F2 : ∀ A X cT, Interior A X cT ⊂ Closure A X cT.\nProof. intros. eapply IncTran. apply interior_F1. apply closure_F1. Qed.\n\nTheorem interior_Ta : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Interior A X cT = X - (Closure (X - A) X cT).\nProof.\n  intros * Hxe Ht Hs. apply IncAsym; intros x Hx.\n  - AppC Hx. assert (Hx' := Hx).\n    destruct Hx as [_ [Hx [_ [V [Hv [Hxv Hva]]]]]]. apply Hva in Hxv.\n    AppCG; andG; Ens. intro. AppC H; orH. smH; auto. apply derived_F1 in H.\n    apply H in Hx'. elim Hx'. AppE. inH; smH; tauto. exfalso0.\n  - smH. apply UnionNE in H0 as [Hxi Hc]. apply derived_F2 in Hc as\n      [V [Hnv Hc]]; auto; [|apply SetminSubI]. apply InterEqEmI in Hc; Ens.\n    apply InterSetmin in Hc; [|apply Hnv]. AppCG; Ens.\n    eapply neigh_F1, neigh_T1b; eauto. apply neigh_F1; auto.\nQed.\n\nTheorem interior_Tb : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Closure A X cT = X - (Interior (X - A) X cT).\nProof.\n  intros * Hxe Ht Hs. pose proof (SetminSubI A X) as Hc.\n  eapply interior_Ta in Hc; eauto. erewrite TwoCompl in Hc; auto.\n  apply (SetminEq _ _ X) in Hc. erewrite TwoCompl in Hc; auto.\n  apply closureP; auto.\nQed.\n\nTheorem interior_T1 : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  A ∈ cT ↔ A = Interior A X cT.\nProof.\n  intros * Hxe Ht Ha. pose proof SetminSubI A X as Hc. split; intros Hp.\n  - eapply closed_C in Hp as Hp'; eauto.\n    apply closure_T, (SetminEq _ _ X) in Hp'; auto.\n    rewrite TwoCompl in Hp'; auto. rewrite interior_Ta; auto.\n  - rewrite interior_Ta in Hp; auto. apply (SetminEq _ _ X) in Hp.\n    rewrite TwoCompl in Hp; [|apply closureP]; auto.\n    apply closure_T, closed_T in Hp; auto.\n    rewrite TwoCompl in Hp; auto.\nQed.\n\nTheorem interior_T2a : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Interior (Interior A X cT) X cT = Interior A X cT.\nProof.\n  intros *Hxe Ht Ha. pose proof SetminSubI A X as Ha'.\n  rewrite interior_Ta, interior_Ta, TwoCompl, closure_T2;\n  auto. apply closureP; auto. apply interiorP.\nQed.\n\nTheorem interior_T2b : ∀ A X cT,\n  Ensemble X → Topology X cT → A ⊂ X → Interior A X cT ∈ cT.\nProof.\n  intros * Hxe Ht Ha. eapply interior_T1; eauto.\n  apply interiorP. symmetry; apply interior_T2a; auto.\nQed.\n\n(* boundary *)\nDefinition Boundp x A X cT := Topology X cT ∧ A ⊂ X ∧ x ∈ X ∧\n  ∀ U, Neigh x U X cT → U ∩ A ≠ ∅ ∧ U ∩ X - A ≠ ∅.\nDefinition Bound A X cT := \\{λ x, Boundp x A X cT\\}.\n\nFact boundP : ∀ A X cT, Bound A X cT ⊂ X.\nProof. intros * x Hx. AppC Hx; apply Hx. Qed.\n\nTheorem bound_T : ∀ A X cT, Interior A X cT ∩ Bound A X cT = ∅.\nProof.\n  intros. AppE; [exfalso|exfalso0]. inH. AppC H0. AppC H; apply H0 in H.\n  andH. apply H1. AppE; [exfalso|exfalso0]. inH; smH; auto.\nQed.\n\nTheorem Re1_ClInBo : ∀ A X cT, Topology X cT → A ⊂ X →\n  Bound A X cT = Closure A X cT ∩ Closure (X - A) X cT.\nProof.\n  intros * Ht Ha. pose proof SetminSubI A X as Ha'. AppE.\n  - AppC H. red in H; andH. AppCG; Ens. andG; AppCG; Ens;\n    [DC (x ∈ A); auto|DC (x ∈ X - A); auto]; right; apply derived_F1;\n    red; andG; auto; intros; [apply H2 in H4 as [Hl _]|\n    apply H2 in H4 as [_ Hl]]; intro; elim Hl; eapply InterEqEmI; Ens.\n  - inH. AppCG; Ens. red; andG; auto. eapply closureP; eauto. intros.\n    AppC H; AppC H0; orH; [smH; tauto|apply derived_F1 in H|\n    apply derived_F1 in H0|].\n    + andG. apply H in H1; intro; elim H1; apply InterEqEmE; auto.\n      destruct H1 as [_ [_ [_ [V [_ [Hv Hvu]]]]]]. intro.\n      assert (x ∈ U ∩ X - A); ens. rewrite H1 in H2; exfalso0.\n    + andG; [|apply H0 in H1; intro; elim H1; apply InterEqEmE; auto].\n      destruct H1 as [_ [_ [_ [V [_ [Hv Hvu]]]]]]. intro.\n      assert (x ∈ U ∩ A); ens. rewrite H1 in H2; exfalso0.\n    + apply derived_F1 in H; apply derived_F1 in H0. andG; [apply H in H1|\n      apply H0 in H1]; intro; elim H1; apply InterEqEmE; auto.\nQed.\n\nTheorem Re2_ClInBo : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Closure A X cT ∩ Closure (X - A) X cT =\n  X - (Interior A X cT ⋃ Interior (X - A) X cT).\nProof.\n  intros * Hxe Ht Ha. rewrite interior_Tb, interior_Tb,\n    TwoCompl, <- UnionCompl, CommuU;\n  try apply interiorP; auto. apply SetminSubI.\nQed.\n\nTheorem Re3_ClInBo : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  X - (Interior A X cT ⋃ Interior (X - A) X cT) = Bound (X - A) X cT.\nProof.\n  intros * Hxe Ht Ha. rewrite Re1_ClInBo, TwoCompl,\n    CommuI, Re2_ClInBo; auto. apply SetminSubI.\nQed.\n\nTheorem Re4_ClInBo : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  X - (Interior (X - A) X cT) = Interior A X cT ⋃ Bound A X cT.\nProof.\n  intros * Hxe Ht Ha. rewrite Re1_ClInBo, DistribuLU, CommuU, CommuU, IncU,\n    (interior_Tb (X - A) _ _), TwoCompl, ComUn, IncI, interior_Tb; auto.\n  apply closureP; auto. apply interiorP; auto. apply SetminSubI.\n  apply (IncTran _ A). intros * z Hz. AppC Hz; destruct Hz; andH.\n  destruct H2; andH; auto. intros * x Hx. AppCG; Ens.\nQed.\n\nTheorem Re5_ClInBo : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  X - (Closure (X - A) X cT) = Closure A X cT - Bound A X cT.\nProof.\n  intros * Hxe Ht Ha. rewrite Re1_ClInBo, TwoDMI, SetminId, CommuU, EmptyU,\n   (SetminInter (Closure A X cT) _ X), <- interior_Ta, CommuI, IncI; auto.\n  apply interior_F2. apply closureP; auto.\nQed.\n\nFact bound_F1 : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Bound A X cT = Bound (X - A) X cT.\nProof. intros. rewrite Re1_ClInBo, Re2_ClInBo, Re3_ClInBo; auto. Qed.\n\nFact bound_F2 : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Closure A X cT = Interior A X cT ⋃ Bound A X cT.\nProof. intros. rewrite interior_Tb, Re4_ClInBo; auto. Qed.\n\nFact bound_F3 : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Interior A X cT = Closure A X cT - Bound A X cT.\nProof. intros. rewrite interior_Ta, Re5_ClInBo; auto. Qed.\n\nCorollary Re_bou_C1 : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Closure A X cT = A ⋃ Bound A X cT.\nProof.\n  intros. assert (A ⋃ Closure (X - A) X cT = X).\n  { AppE. unH; auto. eapply closureP; revgoals; eauto. apply SetminSubI.\n    DC (x ∈ A); ens. apply UnionI'. AppCG; Ens. left; ens. }\n  rewrite Re1_ClInBo, DistribuLU, CommuU, CommuU, IncU, H2, IncI; auto.\n  apply closureP; auto. apply closure_F1.\nQed.\n\nCorollary Re_bou_C2 : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Interior A X cT = A - Bound A X cT.\nProof.\n  intros. pose proof (SetminSubI A X). assert (A ∩ X - Closure A X cT = ∅).\n  { rewrite Re_bou_C1, TwoDMU; auto. AppE; [|exfalso0]. inH; smH; tauto. }\n  erewrite Re1_ClInBo, SetminIE, InterCompl, DistribuLI, <- interior_Ta,\n    H3, CommuU, EmptyU, CommuI, IncI; eauto; try apply closureP; auto;\n  [|intros x Hx; inH; eapply closureP; eauto]. apply interior_F1.\nQed.\n\nCorollary Re_bou_C3 : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Bound (Interior A X cT) X cT ⊂ Bound A X cT.\nProof.\n  intros. pose proof (SetminSubI A X). assert (Hai: Interior A X cT ⊂ A).\n  apply interior_F1. rewrite Re1_ClInBo, Re1_ClInBo,\n    <- (closure_T2 (X - A)); eens. intros x Hx; inH; inG.\n  apply (closure_F2 (Interior A X cT)); auto.\n  apply (closure_F2 (X - Interior A X cT)); auto. apply closureP; auto.\n  rewrite Re_bou_C2, (SetminIE A (Bound A X cT) X), TwoDMI, TwoCompl,\n    Re_bou_C1, bound_F1; auto; try apply boundP. intros y Hy; unH; ens.\nQed.\n\nCorollary Re_bou_C4 : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Bound (Closure A X cT) X cT ⊂ Bound A X cT.\nProof.\n  intros. rewrite Re1_ClInBo, Re1_ClInBo, closure_T2; auto;\n  [|apply closureP; auto]. intros x Hx; inH. inG; ens.\n  apply (closure_F2 (X - Closure A X cT) (X - A)); auto.\n  apply SetminSubI. apply SetminSub2, closure_F1.\nQed.\n\n(* subSpace *)\nDefinition RestFamEns cA Y := \\{λ z, ∃ A, A ∈ cA ∧ z = A ∩ Y\\}.\nNotation \"cA | Y\" := (RestFamEns cA Y)(at level 30).\n\nLemma resFam : ∀ Y X cT, Ensemble X → Topology X cT → Y ⊂ X → Topology Y (cT|Y).\nProof.\n  intros * Hxe Ht Hsub. split; andG.\n  - intros z Hz. AppC Hz. destruct Hz as [A []].\n    subst. assert (A ∩ Y ⊂ Y). intros x Hx; AppC Hx; tauto. eens.\n  - AppCG; eens. exists X. andG. apply Ht. AppE; [|inH]; ens.\n  - AppCG; ens. exists ∅. andG. apply Ht. AppE; [|inH]; exfalso0.\n  - intros * Ha Hb. AppC Ha; AppC Hb.\n    destruct Ha as [A' []], Hb as [B' []].\n    subst. rewrite <- DisLII. AssE A'; AssE B'. AppCG.\n    apply InterEns; eens. exists (A' ∩ B'). andG; auto. apply Ht; auto.\n  - intros. assert (Hct: ∪cT1 ⊂ Y).\n    { intros x Hx. eleU Hx. apply H in H1. AppC H1.\n      destruct H1; andH. subst. inH; auto. } assert (Hp : ∀ A, A ∈ cT1 →\n       ∃ A', [A,A'] ∈ \\{\\λ m n, n ∈ cT ∧ m = n ∩ Y\\}\\).\n    { intros. AssE A. apply H in H0. AppC H0; destruct H0 as [A' []].\n      AssE A'. exists A'. AppCG. ens. }\n    assert (Hpe : Ensemble \\{\\λ m n, n ∈ cT ∧ m = n ∩ Y\\}\\).\n    { assert (Hpe : \\{\\λ m n, n ∈ cT ∧ m = n ∩ Y\\}\\ ⊂ cP(X) × cT).\n      { intros z Hz. PP Hz A B; andH. apply CProdI; auto.\n        assert (A ⊂ X). subst; intros z Hz; inH; auto. ens. }\n      eapply SubAxP; revgoals; eauto. apply CProdEns; ens.\n      destruct Ht as [Ht _]. eens. }\n    destruct (ChoAx1 _ _ Hpe Hp) as [f [Hf Hfp]].\n    set (\\{λ W, ∃ A, A ∈ cT1 ∧ W = f[A] ∩ Y\\}) as cW.\n    assert (Ht1: ∪cT1 = ∪cW).\n    { AppE; eleU H0.\n      - AppCG; andG; Ens. exists x0; andG; auto. AppCG; Ens.\n        exists x0; andG; auto. apply Hfp in H1. AppC' H1; tauto.\n      - AppC H1; destruct H1 as [A []]. apply Hfp in H1 as Ha.\n        AppC' Ha; andH. AppCG; Ens. rewrite H2, <- H4 in H0; eauto. }\n    set (\\{λ V, ∃ A, A ∈ cT1 ∧ V = f[A]\\}) as cV.\n    assert (Ht2: ∪cW = (∪cV) ∩ Y).\n    { AppE.\n      - eleU H0. AppC H1; destruct H1 as [A []]. rewrite H2 in H0; inH.\n        inG; auto. AppCG; Ens. exists f[A]; andG; auto. AppCG; eens.\n      - inH. eleU H0. AppC H2; destruct H2 as [A []]. subst. AppCG; Ens.\n        exists (f[A] ∩ Y). andG; ens. AppCG. apply InterEns; eens. }\n    AppCG. eapply SubAxP; revgoals; eens. exists (∪ cV).\n    rewrite Ht1, Ht2; andG; auto. apply Ht.\n    intros A Ha. AppC Ha. destruct Ha as [B []]; andH.\n    apply Hfp in H0. AppC' H0; andH. subst; auto.\nQed.\n\nDefinition SubTop Y X cT := Topology X cT ∧ Y ⊂ X.\n\nFact sTop_F1 : ∀ X Y cT, SubTop Y X cT →\n  ∀ U, U ∈ cT|Y ↔ ∃ V, V ∈ cT ∧ U = V ∩ Y.\nProof.\n  intros * [Ht Hs] *. split; intros. AppC H. destruct H as [V []].\n  AssE V; AppCG. eapply SubAxP; eauto. intros x Hx; subst; inH; auto.\nQed.\n\nFact sTop_F2 : ∀ X Y Z cT,\n  Ensemble X → SubTop Y X cT → SubTop Z Y (cT|Y) → SubTop Z X cT.\nProof. intros * Hxe [Hyt Hyx] [Hzt Hzy]. split; eens. Qed.\n\nTheorem subTop_T1 : ∀ Y X cT, Ensemble X → SubTop Y X cT →\n  Interior Y X cT ⋃ X - Closure Y X cT = X - Bound Y X cT.\nProof.\n  intros * Hxe []. assert (Hix: Interior Y X cT ⊂ X). apply interiorP.\n  rewrite bound_F2, UnionCompl, DistribuLU, ComUn, CommuI, IncI, IncU;\n  auto. rewrite bound_F3; auto. apply SetminSub1, closureP; auto.\n  intros x Hx; unH; ens. eapply SetminSubI; eauto. apply boundP.\nQed.\n\nTheorem subTop_T2a : ∀ X Y cT, Ensemble X → SubTop Y X cT →\n  ∀ y, y ∈ Y → NeighS y Y (cT|Y) = NeighS y X cT | Y.\nProof.\n  intros * Hxe [Hxm Hs] * Hy. apply ExtAx; intro U; split; intros Hu.\n  - AppCG; Ens. eapply neigh_F1 in Hu as [_ [_ [Hu [V [Hv [Hyv Hvu]]]]]];\n    eens. AppC Hv. destruct Hv as [V1 [Hv1 Hvv]]. exists (V1 ⋃ U); andG;\n    [|rewrite DistribuI, <- Hvv, IncI, IncU; auto].\n    AppCG. apply UnionAx. Ens. eens. split; andG; auto.\n    + intros x Hx. AppC Hx; orH; auto. apply Hxm in Hv1; pow Hv1.\n    + exists V1. andG; auto. rewrite Hvv in Hyv; inH; auto. intros x Hx; AppCG; Ens.\n  - AppCG; Ens. AppC Hu; destruct Hu as [A [Ha Hu]]. split; andG; auto.\n    eapply resFam; eauto. subst; intros x Hx; inH; auto.\n    eapply neigh_F1 in Ha as [_ [_ [Ha [V [Hv [Hyv Hva]]]]]]; eens.\n    exists (V ∩ Y). rewrite Hu. andG; ens; [|intros x Hx; inH; ens].\n    AppCG. apply InterEns; eens.\nQed.\n\nTheorem subTop_T2b : ∀ X Y cT, Ensemble X → SubTop Y X cT →\n  ∀ A, A ⊂ Y → Derived A Y (cT|Y) = Derived A X cT ∩ Y.\nProof.\n  intros * Hxe [Hxm Hs] * Ha. AppE.\n  - apply derived_F1 in H as [_ [_ [Hx Hxp]]]. inG; auto.\n    apply derived_F1. split; andG; eens. intros. apply neigh_F1 in H; auto.\n    assert (Neigh x (U ∩ Y) Y (cT | Y)).\n    { apply neigh_F1; eens. erewrite subTop_T2a; eauto; [|split; auto].\n      AppCG. eapply SubAxP; eauto. intros y Hy; inH; auto. }\n    apply Hxp in H0. apply EmptyNE in H0 as [y]; inH.\n    apply EmptyNE; exists y; ens.\n  - inH. apply derived_F1 in H as [_ [_ [_ Hxp]]]. apply derived_F1.\n    split; andG; auto. eapply resFam; eauto. intros V Hv.\n    apply neigh_F1 in Hv; eens. erewrite subTop_T2a in Hv; eauto;\n    [|split; auto]. AppC Hv; destruct Hv as [U [Hu Hvu]].\n    apply neigh_F1, Hxp in Hu; auto. subst. rewrite AssocI, (CommuI Y),\n      <- AssocI, IncI; auto. intros y Hy. inH; smH; auto.\nQed.\n\nTheorem subTop_T2c : ∀ X Y cT, Ensemble X → SubTop Y X cT →\n  ∀ A, A ⊂ Y → Closure A Y (cT|Y) = Closure A X cT ∩ Y.\nProof.\n  intros * Hxe Hst * Ha. unfold Closure. erewrite subTop_T2b; eauto.\n  rewrite <- (IncU A Y) at 2; auto. apply DistribuLU.\nQed.\n\n(* connectedness *)\nDefinition Separation A B X cT :=\n  A ⊂ X ∧ B ⊂ X ∧ (A ∩ Closure B X cT) ⋃ (B ∩ Closure A X cT) = ∅.\n\nFact sep_F1 : ∀ A B X cT, Separation A B X cT →\n  A ∩ Closure B X cT = ∅ ∧ B ∩ Closure A X cT = ∅.\nProof. intros. apply two_union_Empty, H. Qed.\n\nFact sep_F2 : ∀ A B X cT, A ⊂ X → B ⊂ X → A ∩ Closure B X cT = ∅ →\n  B ∩ Closure A X cT = ∅ → Separation A B X cT .\nProof. intros. split; andG; auto. apply two_union_Empty; auto. Qed.\n\nFact sep_F3 : ∀ A B X cT, Separation A B X cT →\n  A ∩ B = ∅ ∧ A ∩ Derived B X cT = ∅.\nProof.\n  intros. apply sep_F1 in H as [H _]. unfold Closure in H.\n  rewrite DistribuLI in H. apply two_union_Empty in H; auto.\nQed.\n\nTheorem separation_T : ∀ Y X cT, Ensemble X → SubTop Y X cT → ∀ A B,\n  A ⊂ Y → B ⊂ Y → Separation A B Y (cT|Y) ↔ Separation A B X cT.\nProof.\n  intros * Hxe Hst * Ha Hb.\n  assert (Hp1: A ∩ Closure B Y (cT|Y) = A ∩ Closure B X cT).\n  erewrite subTop_T2c, (CommuI _ Y), <- AssocI, (IncI A); eauto.\n  assert (Hp2: B ∩ Closure A Y (cT|Y) = B ∩ Closure A X cT).\n  erewrite subTop_T2c, (CommuI _ Y), <- AssocI, (IncI B); eauto.\n  assert (Y ⊂ X). apply Hst. unfold Separation; rewrite Hp1, Hp2.\n  split; intros; andH; andG; auto; eapply IncTran; eauto.\nQed.\n\nDefinition disConnected X cT :=\n  ∃ A B, ⦿ A ∧ ⦿ B ∧ Separation A B X cT ∧ X = A ⋃ B.\n\nDefinition Connected X cT := ~ (disConnected X cT).\n\nTheorem nConnect_Ta : ∀ X cT, Topology X cT → disConnected X cT →\n  ∃ A B, ⦿ A ∧ ⦿ B ∧ Closed A X cT ∧ Closed B X cT ∧\n  A ∩ B = ∅ ∧ A ⋃ B = X.\nProof.\n  intros * Ht [A [B [Hae [Hbe [Hp1 Hp2]]]]]. assert (Heq: A ∩ B = ∅).\n  { apply sep_F3 in Hp1; tauto. } pose proof Hp1.\n  apply sep_F1 in H as [Hab Hba]. assert (A ⊂ X ∧ B ⊂ X).\n  andG; apply Hp1. destruct H as [Has Hbs]. exists A, B. andG; auto;\n  apply closure_T; auto; [rewrite <- (IncI (Closure A X cT) X)|\n  rewrite <- (IncI (Closure B X cT) X)]; try apply closureP; auto;\n  rewrite Hp2 at 2; rewrite CommuI, DistribuI; [rewrite Hba|\n  rewrite Hab, CommuU]; rewrite EmptyU, IncI; auto; apply closure_F1.\nQed.\n\nTheorem nConnect_Tb : ∀ X cT, Ensemble X → Topology X cT → (∃ A B,\n  ⦿ A ∧ ⦿ B ∧ Closed A X cT ∧ Closed B X cT ∧ A ∩ B = ∅ ∧ A ⋃ B = X) →\n  (∃ A B, ⦿ A ∧ ⦿ B ∧ A ∈ cT ∧ B ∈ cT ∧ A ∩ B = ∅ ∧ A ⋃ B = X).\nProof.\n  intros * Hxe Ht [A [B [Hae [Hbe [Hba [Hbb [Hp1 Hp2]]]]]]].\n  assert (A ⊂ X ∧ B ⊂ X). andG; [apply Hba|apply Hbb].\n  destruct H as [Has Hbs]. apply closed_T in Hba; auto.\n  apply closed_T in Hbb; auto. assert (A = X - B ∧ B = X - A).\n  { andG; apply two_inter_Empty; auto; [rewrite CommuI|rewrite CommuU]; auto. }\n  andH. exists A, B; andG; auto; [rewrite H|rewrite H0]; auto.\nQed.\n\nTheorem nConnect_Tc : ∀ X cT, Ensemble X → Topology X cT →\n  (∃ A B, ⦿ A ∧ ⦿ B ∧ A ∈ cT ∧ B ∈ cT ∧ A ∩ B = ∅ ∧ A ⋃ B = X) →\n  (∃ C, ⦿ C ∧ C ⊊ X ∧ C ∈ cT ∧ Closed C X cT).\nProof.\n  intros * Hxe Ht [A [B [Hae [Hbe [Hao [Hbo [Hp1 Hp2]]]]]]].\n  apply Ht in Hao as Has; apply Ht in Hbo as Hbs. pow Has; pow Hbs.\n  eapply two_inter_Empty in Hp1 as Hab; eauto. exists A; andG; auto. split; auto.\n  { DC (A = X); auto. assert (B = ∅). rewrite (two_inter_Empty B A X); eauto;\n    [|rewrite CommuI|rewrite CommuU]; auto. rewrite H; apply SetminId.\n    destruct Hbe as [x]. subst B; exfalso0. }\n  rewrite Hab; apply closed_C; auto.\nQed.\n\nTheorem nConnect_Td : ∀ X cT, Ensemble X → Topology X cT →\n  (∃ C, ⦿ C ∧ C ⊊ X ∧ C ∈ cT ∧ Closed C X cT) → disConnected X cT.\nProof.\n  intros * Hxe Ht [A [Hae [[_ Hneq] [Hao Hac]]]]. set (B := X - A).\n  assert (Has: A ⊂ X). apply Hac. assert (Hab: A ∩ B = ∅). apply ComIn.\n  apply closed_T in Hac as Hbo; auto. eapply closed_C in Hao as Hbc; eauto.\n  assert (Hbs: B ⊂ X). apply SetminSubI. exists A, B. andG; auto;\n  [| |symmetry; apply ComUn; auto].\n  { DC (⦿ B); auto. exfalso. apply EmptyEq in H. assert (A = X).\n    { AppE; auto. DC (x ∈ A); auto. assert (x ∈ B).\n      AppCG; Ens.  rewrite H in H2; exfalso0. } auto. } split; andG; auto;\n  apply two_union_Empty; unfold Closure. repeat rewrite CommuU, IncU; andG; auto;\n  [|apply Hac|apply Hbc]. rewrite CommuI; auto.\nQed.\n\nDefinition subConnect Y cT := Connected Y (cT|Y).\nDefinition disSubConnect Y cT := disConnected Y (cT|Y).\n\nTheorem scon_T1 : ∀ Y Z X cT, Ensemble X → SubTop Z X cT →\n  SubTop Y Z (cT|Z) → subConnect Y cT ↔ subConnect Y (cT|Z).\nProof.\n  intros * Hxe Hzt Hyt. eapply sTop_F2 in Hyt as Hyx; eauto.\n  assert (Z ⊂ X ∧ Y ⊂ Z). { andG. apply Hzt. apply Hyt. }\n  destruct H as [Hzx Hyz]. assert (Ensemble Z ∧ Ensemble Y).\n  { andG; eapply SubAxP; eauto. eapply IncTran; eauto. }\n  destruct H as [Hze Hye]. split; intros Hsc;\n  intros [A [B [Hae [Hbe [H Heq]]]]]; assert (A ⊂ Y ∧ B ⊂ Y);\n  [subst; andG; intros x Hx; ens| |subst; andG; intros x Hx; ens|];\n  destruct H0 as [Hay Hby]; apply Hsc; exists A, B; andG; auto;\n  apply sep_F1 in H; [do 2 rewrite (subTop_T2c Z Y),\n    (subTop_T2c X Z), AssocI, (CommuI Z Y), (IncI Y Z) in H; eens|\n    do 2 rewrite (subTop_T2c X Y) in H; auto]; apply sep_F2; auto;\n  try (rewrite (subTop_T2c X Y); tauto); rewrite (subTop_T2c Z Y),\n    (subTop_T2c X Z), AssocI, (CommuI Z Y), (IncI Y Z); eens; tauto.\nQed.\n\nTheorem scon_T2 : ∀ Y X cT, Ensemble X → SubTop Y X cT →\n  disSubConnect Y cT ↔ ∃ A B, ⦿ A ∧ ⦿ B ∧ Separation A B X cT ∧ Y = A ⋃ B.\nProof.\n  intros * Hxe Hst. split; intros [A [B [Hae [Hbe []]]]]; exists A, B; andG;\n  auto; eapply separation_T; eauto; try apply H; subst; intros x Hx; ens.\nQed.\n\nTheorem scon_T3 : ∀ Y X cT, Ensemble X → SubTop Y X cT →\n  subConnect Y cT → ∀ A B, Separation A B X cT → Y ⊂ A ⋃ B → Y ⊂ A ∨ Y ⊂ B.\nProof.\n  intros * Hxe Hyx Hsy * Hs Hsub. assert (Heq: A ∩ Y ⋃ B ∩ Y = Y).\n  { rewrite <- DistribuI, CommuI; apply IncI; auto. }\n  assert (Hd: A ∩ Y = ∅ ∨ B ∩ Y = ∅).\n  { DC (A ∩ Y = ∅ ∨ B ∩ Y = ∅); auto. exfalso.\n    apply not_or_and in H as [Ha Hb]. apply EmptyNE in Ha.\n    apply EmptyNE in Hb. assert (disSubConnect Y cT).\n    { apply (scon_T2 Y X cT); auto. exists (A∩Y), (B∩Y); andG; auto.\n      split; andG; [intros x Hx|intros x Hx|]; inH; try apply Hyx; auto.\n      assert ((A∩Y) ∩ Closure (B∩Y) X cT ⋃ (B∩Y) ∩ Closure (A∩Y) X cT ⊂\n        (A∩Y) ∩ Closure B X cT ⋃ (B∩Y) ∩ Closure A X cT).\n      { intros y Hy. unH; inH; [unG| apply UnionI']; inG; auto;\n        eapply closure_F2; eauto; try apply Hs; intros z Hz; inH; auto. }\n      AppE; [|exfalso0]. apply H in H0. destruct Hs as [_ [_ Hs]].\n      rewrite (CommuI A Y), (CommuI B Y), AssocI, AssocI, <- DistribuLI, Hs,\n        EmptyI in H0; auto. } apply Hsy, H. }\n  orH; rewrite H in Heq; [rewrite CommuU in Heq|]; rewrite EmptyU in Heq;\n  rewrite <- Heq; [right|left]; intros x Hx; inH; auto.\nQed.\n\nCorollary scon_T3C1 : ∀ Y X cT, Ensemble X → SubTop Y X cT → subConnect Y cT →\n  ∀ Z, SubTop Z X cT → Y ⊂ Z → Z ⊂ Closure Y X cT → subConnect Z cT.\nProof.\n  intros * Hxe Hyx Hsy * HzX Hyz Hzc. DC (subConnect Z cT); auto.\n  assert (Hzn: disSubConnect Z cT). unfold disSubConnect; apply NNPP, H.\n  apply (scon_T2 Z X) in Hzn as [A [B [[x Ha] [[y Hb] [Hab Heq]]]]];\n  auto. assert (A⊂X ∧ B⊂X). andG; apply Hab. destruct H0 as [Hax Hbx].\n  assert (B = Z∩B ∧ A = Z∩A). { subst Z. andG; AppE; ens; inH; auto. }\n  destruct H0 as [Hbz Haz]. clear H; pose proof Hab.\n  apply sep_F1 in H as [Habc Hbac]. rewrite Heq in Hyz.\n  apply (scon_T3 Y X) in Hab as [H|H]; auto;\n  apply (closure_F2 Y _ X cT) in H; eauto.\n  - assert (Z ⊂ Closure A X cT); eens. apply (InterRSub _ _ B) in H0.\n    rewrite CommuI in Hbac. rewrite Hbac, <- Hbz in H0.\n    assert (B = ∅). AppE; exfalso0. subst B; exfalso0.\n  - assert (Z ⊂ Closure B X cT); eens. apply (InterRSub _ _ A) in H0.\n    rewrite CommuI in Habc. rewrite Habc, <- Haz in H0.\n    assert (A = ∅). AppE; exfalso0. subst A; exfalso0.\nQed.\n\nFact scon_T3C2 : ∀ A X cT, Ensemble X → SubTop A X cT →\n  subConnect A cT → subConnect (Closure A X cT) cT.\nProof.\n  intros * Hxe [Has Ht] Hac. assert (H: Closure A X cT ⊂ X).\n  apply closureP; auto. assert (SubTop (Closure A X cT) X cT).\n  split; andG; auto. eapply (scon_T3C1 A); eens. split; andG; auto.\n  intros x Hx; unfold Closure; ens.\nQed.\n\nTheorem scon_T4 : ∀ Y X cT, Ensemble X → SubTop Y X cT →\n  ⦿ Interior Y X cT → Closure Y X cT ≠ X → Separation (Interior Y X cT)\n  (X - (Closure Y X cT)) (X - (Bound Y X cT)) (cT|(X - (Bound Y X cT))).\nProof.\n  intros * Hxe [Ht Hyx] Hye Hyn. assert (X - (Closure Y X cT) ⊂ X ∧\n    X - (Closure Y X cT) ⊂ X - Bound Y X cT).\n  { andG. apply SetminSubI. rewrite bound_F2; auto.\n    apply SetminSub2; intros x Hx; ens. } destruct H as [Hbx Hby].\n  assert (Interior Y X cT ⊂ X ∧ Interior Y X cT ⊂ X - Bound Y X cT).\n  { andG. apply interiorP. rewrite bound_F3; auto. intros x Hx; smH; smG;\n    auto. eapply closureP; revgoals; eauto. } destruct H as [Hax Hay].\n  assert (Hst: SubTop (X - Bound Y X cT) X cT).\n  { assert (X - Bound Y X cT ⊂ X). apply SetminSubI. split; andG; auto. }\n  eapply separation_T, sep_F2; eauto.\n  - rewrite (Re_bou_C1 (X - Closure Y X cT)), DistribuLI, <- bound_F1;\n    try apply closureP; auto. apply two_union_Empty; andG.\n    + rewrite bound_F2, TwoDMU; auto.\n      AppE; [exfalso|exfalso0]. inH; smH; tauto.\n    + rewrite bound_F3; auto. AppE; [exfalso|exfalso0].\n      inH; smH. apply Re_bou_C4 in H0; auto.\n  - rewrite (bound_F2 Y), (Re_bou_C1 (Interior Y X cT)), TwoDMU, DistribuLI;\n    auto. apply two_union_Empty; andG; AppE; [exfalso|exfalso0|exfalso|exfalso0];\n    inH; smH; auto. apply Re_bou_C3 in H0; auto.\nQed.\n\nCorollary scon_T4C : ∀ Y X cT, Ensemble X → SubTop Y X cT →\n  ⦿ Interior Y X cT → Closure Y X cT ≠ X → disSubConnect (X - (Bound Y X cT)) cT.\nProof.\n  intros * Hxe [Ht Hyx] Hye Hyn. assert (Hbcx: X - Bound Y X cT ⊂ X).\n  { intros x Hx; smH; auto. } assert (Hbe: Ensemble (X - Bound Y X cT)).\n  { eapply SubAxP; eauto; intros x Hx; smH; auto. }\n  assert (Hbt: Topology (X - Bound Y X cT) (cT | (X - Bound Y X cT))).\n  { eapply resFam; revgoals; eauto. } apply nConnect_Td; auto.\n  apply nConnect_Tc; eauto. assert (Hcx: Closure Y X cT ⊂ X).\n  apply closureP; auto. assert (Hix: Interior Y X cT ⊂ X). apply interiorP.\n  assert (Hbx: Bound Y X cT ⊂ X). apply boundP.\n  exists (Interior Y X cT), (X - (Closure Y X cT)). andG; auto.\n  - pose proof ProperSubE as [x []]. split; revgoals; eauto. exists x; ens.\n  - assert (Interior Y X cT ∈ cT). apply interior_T2b; auto. AppCG; Ens.\n    exists (Interior Y X cT); andG; auto. AppE; [|inH; auto]. inG; auto.\n    smG; auto. rewrite bound_F3 in H0; auto. smH; auto.\n  - assert (X - Closure Y X cT ∈ cT). apply closed_T, closure_F5; auto.\n    AppCG; Ens. exists (X - Closure Y X cT). andG; auto. AppE; [|inH; auto].\n    inG; auto. smH; smG; auto.\n    rewrite interior_Tb, Re4_ClInBo in H1; auto. intro; ens.\n  - AppE; [exfalso|exfalso0]. inH; smH. pose proof (interior_F2 Y X cT); auto.\n  - apply subTop_T1; auto. split; auto.\nQed.", "meta": {"author": "BalanceYan", "repo": "GIS_topology", "sha": "23665bfda55c0d488925ee3507d4c49564d7cfbd", "save_path": "github-repos/coq/BalanceYan-GIS_topology", "path": "github-repos/coq/BalanceYan-GIS_topology/GIS_topology-23665bfda55c0d488925ee3507d4c49564d7cfbd/Topology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.653337615025976}}
{"text": "Require Export Ensembles.\nRequire Import EnsemblesImplicit.\nRequire Export Image.\nRequire Import ImageImplicit.\nRequire Export Finite_sets.\nRequire Export FunctionProperties.\nRequire Import DecidableDec.\nRequire Import ProofIrrelevance.\nRequire Import Description.\n\nInductive FiniteT : Type -> Prop :=\n  | empty_finite: FiniteT False\n  | add_finite: forall T:Type, FiniteT T -> FiniteT (option T)\n  | bij_finite: forall (X Y:Type) (f:X->Y), FiniteT X ->\n    invertible f -> FiniteT Y.\n\nLemma True_finite: FiniteT True.\nProof.\napply bij_finite with (option False)\n  (fun _ => I).\nconstructor; constructor.\nexists (True_rect None).\ndestruct x as [[]|].\nremember (True_rect (@None False) I) as LHS.\ndestruct LHS as [[]|].\nreflexivity.\n\nexact (fun y:True => match y with\n  | I => refl_equal I\n  end).\nQed.\n\nLemma finite_dec_exists: forall (X:Type) (P:X->Prop),\n  FiniteT X -> (forall x:X, {P x} + {~ P x}) ->\n  { exists x:X, P x } + { forall x:X, ~ P x }.\nProof.\nintros.\napply exclusive_dec.\nred; intro.\ndestruct H0.\ndestruct H0.\ncontradiction (H1 x).\n\nrevert P X0.\ninduction H.\nright.\ndestruct x.\nintros.\ncase (IHFiniteT (fun x:T => P (Some x))\n  (fun x:T => X0 (Some x))).\nleft.\ndestruct H0.\nexists (Some x).\nassumption.\nintro.\ncase (X0 None).\nleft.\nexists None.\nassumption.\nright.\ndestruct x.\napply H0.\nassumption.\ndestruct H0.\nintros.\ncase (IHFiniteT (fun x:X => P (f x))\n  (fun x:X => X0 (f x))).\nleft.\ndestruct H2.\nexists (f x).\nassumption.\nright.\nintro.\nrewrite <- H1 with x.\napply H2.\nQed.\n\nLemma finite_dec_forall: forall (X:Type) (P:X->Prop),\n  FiniteT X -> (forall x:X, { P x } + { ~ P x }) ->\n  { forall x:X, P x } + { exists x:X, ~ P x }.\nProof.\nintros.\napply exclusive_dec.\nintuition.\ndestruct H2.\ncontradiction (H1 x).\n\nrevert P X0.\ninduction H.\nleft.\ndestruct x.\nintros.\ncase (IHFiniteT (fun x:T => P (Some x))\n  (fun x:T => X0 (Some x))).\nintro.\ncase (X0 None).\nleft.\ndestruct x.\napply H0.\nassumption.\nright.\nexists None.\nassumption.\nright.\ndestruct H0.\nexists (Some x).\nassumption.\n\nintros.\ndestruct H0.\ncase (IHFiniteT (fun x:X => P (f x))\n  (fun x:X => X0 (f x))).\nleft.\nintro y.\nrewrite <- H1.\napply H2.\nright.\ndestruct H2.\nexists (f x).\nassumption.\nQed.\n\nLemma finite_eq_dec: forall X:Type, FiniteT X ->\n  forall x y:X, {x=y} + {x<>y}.\nProof.\nintros.\napply decidable_dec.\ninduction H.\ndestruct x.\ndecide equality.\n\ndestruct H0.\ncase (IHFiniteT (g x) (g y)).\nleft.\nrewrite <- H1.\nrewrite <- H1 with x.\nrewrite H2.\nreflexivity.\nright.\ncontradict H2.\nrewrite H2.\nreflexivity.\nQed.\n\nLemma finite_dep_choice: forall (A:Type) (B:forall x:A, Type)\n  (R:forall x:A, B x->Prop),\n  FiniteT A -> (forall x:A, exists y:B x, R x y) ->\n  exists f:(forall x:A, B x), forall x:A, R x (f x).\nProof.\nintros.\nrevert B R H0.\ninduction H.\nintros.\nexists (fun x:False => False_rect (B x) x).\ndestruct x.\nintros.\npose proof (IHFiniteT (fun x:T => B (Some x))\n  (fun x:T => R (Some x))\n  (fun x:T => H0 (Some x))).\ndestruct H1.\npose proof (H0 None).\ndestruct H2.\nexists (fun y:option T =>\n  match y return (B y) with\n  | Some y0 => x y0\n  | None => x0\n  end).\ndestruct x1.\napply H1.\nassumption.\n\nintros.\ndestruct H0.\npose proof (IHFiniteT (fun x:X => B (f x))\n  (fun x:X => R (f x))\n  (fun x:X => H1 (f x))).\ndestruct H3.\npose (f0 := fun y:Y => x (g y)).\npose (conv := fun (y:Y) (a:B (f (g y))) =>\n  eq_rect (f (g y)) B a y (H2 y)).\n\nexists (fun y:Y => conv y (x (g y))).\nintro.\nunfold conv; simpl.\ngeneralize (H2 x0).\npattern x0 at 2 3 6.\nrewrite <- H2.\nintro.\nrewrite <- eq_rect_eq.\napply H3.\nQed.\n\nLemma finite_choice : forall (A B:Type) (R:A->B->Prop),\n  FiniteT A -> (forall x:A, exists y:B, R x y) ->\n  exists f:A->B, forall x:A, R x (f x).\nProof.\nintros.\napply finite_dep_choice.\nassumption.\nassumption.\nQed.\n\nLemma Finite_ens_type: forall {X:Type} (S:Ensemble X),\n  Finite _ S -> FiniteT { x:X | In S x }.\nProof.\nintros.\ninduction H.\napply bij_finite with False (False_rect _).\nconstructor.\nassert (g:{x:X | In Empty_set x}->False).\nintro.\ndestruct X0.\ndestruct i.\nexists g.\ndestruct x.\ndestruct y.\ndestruct g.\n\nassert (Included A (Add A x)).\nauto with sets.\nassert (In (Add A x) x).\nauto with sets.\npose (g := fun (y: option {x:X | In A x}) =>\n  match y return {x0:X | In (Add A x) x0} with\n  | Some (exist y0 i) => exist (fun x2:X => In (Add A x) x2) y0 (H1 y0 i)\n  | None => exist (fun x2:X => In (Add A x) x2) x H2\n  end).\napply bij_finite with _ g.\napply add_finite.\nassumption.\n\nassert (h:forall x0:X, In (Add A x) x0 ->\n  { In A x0 } + { x0 = x }).\nintros; apply exclusive_dec.\nintuition.\ndestruct H6; auto.\ndestruct H3.\nleft; assumption.\nright; destruct H3; reflexivity.\n\npose (ginv := fun s:{x0:X | In (Add A x) x0} =>\n  match s return option {x:X | In A x} with\n  | exist x0 i => match (h x0 i) with\n                  | left iA => Some (exist _ x0 iA)\n                  | right _ => None\n                  end\n  end).\nexists ginv.\nintro; destruct x0.\ndestruct s.\nsimpl.\nremember (h x0 (H1 x0 i)) as sum; destruct sum.\ndestruct (proof_irrelevance _ i i0).\nreflexivity.\ncontradiction H0.\nrewrite <- e; assumption.\nsimpl.\nremember (h x H2) as sum; destruct sum.\ncontradiction H0.\nreflexivity.\n\nintro.\nunfold ginv.\ndestruct y.\ndestruct (h x0 i).\nsimpl.\ngeneralize (H1 x0 i0); intro.\ndestruct (proof_irrelevance _ i i1).\nreflexivity.\nsimpl.\ndestruct e.\ndestruct (proof_irrelevance _ H2 i).\nreflexivity.\nQed.\n\nLemma FiniteT_img: forall (X Y:Type) (f:X->Y),\n  FiniteT X -> (forall y1 y2:Y, y1=y2 \\/ y1<>y2) ->\n  Finite _ (Im Full_set f).\nProof.\nintros.\ninduction H.\nassert (Im Full_set f = Empty_set).\napply Extensionality_Ensembles.\nred; split.\nred; intros.\ndestruct H.\ndestruct x.\nauto with sets.\nrewrite H.\nconstructor.\n\nassert ({exists x:T, f (Some x) = f None} +\n        {forall x:T, f (Some x) <> f None}).\napply finite_dec_exists.\nassumption.\nintro.\napply decidable_dec.\napply H0.\ncase H1.\nintro.\npose (g := fun (x:T) => f (Some x)).\nassert (Im Full_set f =\n        Im Full_set g).\napply Extensionality_Ensembles.\nred; split.\nred; intros.\ndestruct H2.\ndestruct x.\nexists t.\nconstructor.\nassumption.\ndestruct e.\nexists x.\nconstructor.\ntransitivity (f None).\nassumption.\nsymmetry; assumption.\nred; intros.\ndestruct H2.\nexists (Some x).\nconstructor.\nassumption.\nrewrite H2.\napply IHFiniteT.\n\nintros.\npose (g := fun x:T => f (Some x)).\nassert (Im Full_set f =\n  Add (Im Full_set g) (f None)).\napply Extensionality_Ensembles.\nred; split.\nred; intros.\ndestruct H2.\ndestruct x.\nleft.\nexists t.\nconstructor.\nassumption.\nright.\nauto with sets.\nred; intros.\ndestruct H2.\ndestruct H2.\nexists (Some x).\nconstructor.\nassumption.\ndestruct H2.\nexists None.\nconstructor.\nreflexivity.\nrewrite H2.\nconstructor.\napply IHFiniteT.\nred; intro.\ndestruct H3.\ncontradiction (n x).\nsymmetry; assumption.\n\npose (g := fun (x:X) => f (f0 x)).\nassert (Im Full_set f = Im Full_set g).\napply Extensionality_Ensembles.\nred; split.\nred; intros.\ndestruct H2.\ndestruct H1.\nrewrite H3.\nrewrite <- H4 with x.\nexists (g0 x).\nconstructor.\nunfold g.\nreflexivity.\nred; intros.\ndestruct H2.\nexists (f0 x).\nconstructor.\nassumption.\n\nrewrite H2.\napply IHFiniteT.\nQed.\n\nLemma surj_finite: forall (X Y:Type) (f:X->Y),\n  FiniteT X -> surjective f ->\n  (forall y1 y2:Y, y1=y2 \\/ y1<>y2) ->\n  FiniteT Y.\nProof.\nintros.\napply bij_finite with {y:Y | In (Im Full_set f) y}\n  (@proj1_sig _ (fun y:Y => In (Im Full_set f) y)).\napply Finite_ens_type.\napply FiniteT_img.\nassumption.\nassumption.\nassert (forall y:Y, In (Im Full_set f) y).\nintro.\ndestruct (H0 y).\nexists x; auto with sets.\nconstructor.\n\npose (proj1_sig_inv := fun y:Y =>\n  exist (fun y0:Y => In (Im Full_set f) y0) y (H2 y)).\nexists proj1_sig_inv.\ndestruct x.\nsimpl.\nunfold proj1_sig_inv.\ndestruct (proof_irrelevance _ (H2 x) i); trivial.\nintros; simpl; reflexivity.\nQed.\n\nLemma finite_subtype: forall (X:Type) (P:X->Prop),\n  FiniteT X -> (forall x:X, P x \\/ ~ P x) ->\n  FiniteT {x:X | P x}.\nProof.\nintros.\ninduction H.\napply bij_finite with False (False_rect _).\nconstructor.\nexists (@proj1_sig _ _).\ndestruct x.\nintro s; destruct s; destruct x.\n\ndestruct (H0 None).\npose (g := fun (x:option {x:T | P (Some x)}) =>\n  match x return {x:option T | P x} with\n  | Some (exist x0 i) => exist (fun x:option T => P x) (Some x0) i\n  | None => exist (fun x:option T => P x) None H1\n  end).\napply bij_finite with _ g.\napply add_finite.\napply IHFiniteT.\nintro; apply H0.\npose (ginv := fun (s:{x0:option T | P x0}) =>\n  match s return option {x:T | P (Some x)} with\n  | exist (Some x0) i => Some (exist (fun y:T => P (Some y)) x0 i)\n  | exist None _ => None\n  end).\nexists ginv.\ndestruct x as [[x0]|].\nsimpl.\nreflexivity.\nsimpl.\nreflexivity.\ndestruct y as [[x0|]].\nsimpl.\nreflexivity.\nsimpl.\ndestruct (proof_irrelevance _ H1 p).\nreflexivity.\n\npose (g := fun (x:{x:T | P (Some x)}) =>\n  match x return {x:option T | P x} with\n    | exist x0 i => exist (fun x:option T => P x) (Some x0) i\n  end).\napply bij_finite with _ g.\napply IHFiniteT.\nintro; apply H0.\npose (ginv := fun s:{x0:option T | P x0} =>\n  match s return {x:T | P (Some x)} with\n    | exist (Some x0) i => exist (fun x:T => P (Some x)) x0 i\n    | exist None i => False_rect _ (H1 i)\n  end).\nexists ginv.\ndestruct x; simpl.\nreflexivity.\ndestruct y as [[x0|]].\nsimpl.\nreflexivity.\ncontradiction H1.\n\npose (g := fun (x:{x:X | P (f x)}) =>\n  match x with\n  | exist x0 i => exist (fun x:Y => P x) (f x0) i\n  end).\napply bij_finite with _ g.\napply IHFiniteT.\nintro; apply H0.\ndestruct H1.\nassert (forall y:Y, P y -> P (f (g0 y))).\nintros; rewrite H2; assumption.\npose (ginv := fun (y:{y:Y | P y}) =>\n  match y with\n  | exist y0 i => exist (fun x:X => P (f x)) (g0 y0) (H3 y0 i)\n  end).\nexists ginv.\ndestruct x; simpl.\ngeneralize (H3 (f x) p).\nrewrite H1.\nintro; destruct (proof_irrelevance _ p p0).\nreflexivity.\n\ndestruct y; simpl.\ngeneralize (H3 x p).\nrewrite H2.\nintro; destruct (proof_irrelevance _ p p0).\nreflexivity.\nQed.\n\nLemma inj_finite: forall (X Y:Type) (f:X->Y),\n  FiniteT Y -> FunctionProperties.injective f ->\n  (forall y:Y, (exists x:X, f x = y) \\/\n               (~ exists x:X, f x = y)) ->\n  FiniteT X.\nProof.\nintros.\nassert (forall y:{y:Y | exists x:X, f x = y}, {x:X | f x = proj1_sig y}).\nintro.\ndestruct y.\nsimpl.\n\napply constructive_definite_description.\ndestruct e.\nexists x0.\nred; split.\nassumption.\nintros.\napply H0.\ntransitivity x.\nassumption.\nsymmetry; assumption.\n\npose (g := fun y:{y:Y | exists x:X, f x = y} =>\n  proj1_sig (X0 y)).\napply bij_finite with _ g.\napply finite_subtype.\nassumption.\nassumption.\n\npose (ginv := fun (x:X) => exist (fun y:Y => exists x:X, f x = y)\n  (f x) (ex_intro _ x (refl_equal _))).\nexists ginv.\ndestruct x as [y [x e]].\nunfold g; simpl.\nmatch goal with |- context [X0 ?arg] => destruct (X0 arg) end.\nsimpl.\nunfold ginv; simpl.\nsimpl in e0.\nrepeat match goal with |- context [ex_intro ?f ?x ?e] =>\n  generalize (ex_intro f x e) end.\nrewrite <- e0.\nintros; destruct (proof_irrelevance _ e1 e2).\nreflexivity.\n\nintro; unfold ginv.\nunfold g; simpl.\nmatch goal with |- context [X0 ?arg] => destruct (X0 arg) end.\nsimpl.\nsimpl in e.\nauto.\nQed.\n\nLemma finite_inj_surj: forall (X:Type) (f:X->X),\n  FiniteT X -> injective f -> surjective f.\nProof.\nintros.\ninduction H.\nred.\ndestruct y.\n\nremember (f None) as f0; destruct f0 as [a|].\nassert (forall x:T, f (Some x) <> Some a).\nunfold not; intros.\nassert (Some x = None).\napply H0.\ncongruence.\ndiscriminate H2.\npose (g := fun x:T => match f (Some x) with\n  | Some y => y\n  | None => a\nend).\nassert (surjective g).\napply IHFiniteT.\nred; intros.\nremember (f (Some x1)) as fx1; destruct fx1;\nremember (f (Some x2)) as fx2; destruct fx2.\nunfold g in H2.\nrewrite <- Heqfx1 in H2; rewrite <- Heqfx2 in H2.\ndestruct H2; assert (f (Some x1) = f (Some x2)).\ncongruence.\napply H0 in H2.\ninjection H2; trivial.\n\nunfold g in H2; rewrite <- Heqfx1 in H2; rewrite <- Heqfx2 in H2.\ndestruct H2.\ncontradiction (H1 x1).\nsymmetry; assumption.\n\nunfold g in H2; rewrite <- Heqfx1 in H2; rewrite <- Heqfx2 in H2.\ndestruct H2.\ncontradiction (H1 x2).\nsymmetry; assumption.\n\nassert (Some x1 = Some x2).\napply H0.\ncongruence.\ninjection H3; trivial.\n\nred; intro.\ndestruct y.\ncase (finite_eq_dec _ H t a).\nexists None.\ncongruence.\ndestruct (H2 t).\nexists (Some x).\nunfold g in H3.\ndestruct (f (Some x)).\ncongruence.\ncontradiction n.\nsymmetry; assumption.\ndestruct (H2 a).\nexists (Some x).\nunfold g in H3.\nremember (f (Some x)) as fx; destruct fx.\ndestruct H3.\ncontradiction (H1 x).\nsymmetry; assumption.\nreflexivity.\n\nassert (forall x:T, { y:T | f (Some x) = Some y }).\nintros.\nremember (f (Some x)) as fx; destruct fx.\nexists t; reflexivity.\nassert (Some x = None).\napply H0.\ncongruence.\ndiscriminate H1.\npose (g := fun x:T => proj1_sig (X x)).\nassert (surjective g).\napply IHFiniteT.\nred; intros.\nunfold g in H1.\nrepeat destruct X in H1.\nsimpl in H1.\nassert (Some x1 = Some x2).\napply H0.\ncongruence.\ninjection H2; trivial.\n\nred; intro.\ndestruct y.\ndestruct (H1 t).\nunfold g in H2; destruct X in H2.\nsimpl in H2.\nexists (Some x).\ncongruence.\nexists None.\nsymmetry; assumption.\n\ndestruct H1.\n\npose (f' := fun (x:X) => g (f (f0 x))).\nassert (surjective f').\napply IHFiniteT.\nred; intros.\nunfold f' in H3.\nassert (f (f0 x1) = f (f0 x2)).\ncongruence.\napply H0 in H4.\ncongruence.\n\nred; intro.\ndestruct (H3 (g y)).\nunfold f' in H4.\nexists (f0 x).\ncongruence.\nQed.\n\nLemma finite_surj_inj: forall (X:Type) (f:X->X),\n  FiniteT X -> surjective f -> FunctionProperties.injective f.\nProof.\nintros.\nassert (exists g:X->X, forall x:X, f (g x) = x).\napply finite_choice with (R:=fun (x y:X) => f y = x).\nassumption.\nassumption.\ndestruct H1 as [g].\nassert (surjective g).\napply finite_inj_surj.\nassumption.\nred; intros.\nrewrite <- H1 with x1.\nrewrite <- H1 with x2.\nrewrite H2; reflexivity.\nred; intros.\ndestruct (H2 x1).\ndestruct (H2 x2).\nrewrite <- H4 in H3.\nrewrite <- H5 in H3.\nrepeat rewrite H1 in H3.\nrewrite <- H4.\nrewrite <- H5.\nrewrite H3.\nreflexivity.\nQed.\n\nLemma finite_sum: forall X Y:Type, FiniteT X -> FiniteT Y ->\n  FiniteT (X+Y).\nProof.\nintros.\ninduction H0.\napply bij_finite with _ inl.\nassumption.\npose (g := fun (x:X+False) => match x with\n  | inl x => x\n  | inr f => False_rect X f\nend).\nexists g.\nintro; simpl.\nreflexivity.\ndestruct y.\nsimpl.\nreflexivity.\ndestruct f.\n\npose (g := fun (x:option (X+T)) => match x with\n  | Some (inl x) => inl _ x\n  | Some (inr t) => inr _ (Some t)\n  | None => inr _ None\n  end).\napply bij_finite with _ g.\napply add_finite.\nassumption.\npose (ginv := fun (x:X + option T) => match x with\n  | inl x => Some (inl _ x)\n  | inr (Some t) => Some (inr _ t)\n  | inr None => None\n  end).\nexists ginv.\ndestruct x as [[x|t]|]; trivial.\ndestruct y as [x|[t|]]; trivial.\n\npose (g := fun (x:X+X0) => match x with\n  | inl x0 => inl _ x0\n  | inr x0 => inr _ (f x0)\n  end).\ndestruct H1.\npose (ginv := fun (x:X+Y) => match x with\n  | inl x0 => inl _ x0\n  | inr y0 => inr _ (g0 y0)\n  end).\napply bij_finite with _ g.\nassumption.\nexists ginv.\ndestruct x as [x0|x0]; trivial.\nsimpl.\nrewrite H1; reflexivity.\ndestruct y as [x|y0]; trivial.\nsimpl.\nrewrite H2; reflexivity.\nQed.\n\nLemma finite_prod: forall (X Y:Type), FiniteT X -> FiniteT Y ->\n  FiniteT (X*Y).\nProof.\nintros.\ninduction H0.\napply bij_finite with _ (False_rect _).\nconstructor.\nexists (@snd X False).\ndestruct x.\ndestruct y.\ndestruct f.\n\npose (g := fun (x:X*T + X) => match x with\n  | inl (pair x0 t) => pair x0 (Some t)\n  | inr x0 => pair x0 None\n  end).\npose (ginv := fun (x:X * option T) => match x with\n  | (x0, Some t) => inl _ (x0, t)\n  | (x0, None) => inr _ x0\n  end).\napply bij_finite with _ g.\napply finite_sum.\nassumption.\nassumption.\nexists ginv.\ndestruct x as [[x0 t]|x0]; trivial.\ndestruct y as [x0 [t|]]; trivial.\n\npose (g := fun (y:X*X0) => match y with\n  | pair x x0 => pair x (f x0)\n  end).\ndestruct H1.\npose (ginv := fun (y:X*Y) => let (x,y0) := y in\n  (x, g0 y0)).\napply bij_finite with _ g.\nassumption.\nexists ginv.\ndestruct x as [x x0]; unfold ginv, g; try rewrite H1; trivial.\ndestruct y as [x y]; unfold ginv, g; try rewrite H2; trivial.\nQed.\n\nRequire Import FunctionalExtensionality.\n\nLemma finite_exp: forall X Y:Type, FiniteT X -> FiniteT Y ->\n  FiniteT (X->Y).\nProof.\nintros.\ninduction H.\npose (g := fun (x:True) (f:False) => False_rect Y f).\npose (ginv := fun (_:False->Y) => I).\napply bij_finite with _ g.\napply True_finite.\nexists ginv.\ndestruct x as [].\ntrivial.\nintro; extensionality f.\ndestruct f.\n\npose (g := fun (p:(T->Y)*Y) (x:option T) =>\n  let (f,y0) := p in\n  match x with\n  | Some x0 => f x0\n  | None => y0\n  end).\npose (ginv := fun (f:option T->Y) =>\n  (fun x:T => f (Some x), f None)).\napply bij_finite with _ g.\napply finite_prod.\nassumption.\nassumption.\nexists ginv.\ndestruct x as [f y0]; try extensionality t;\ntry destruct t as [t0|]; trivial.\nintro.\nextensionality t; destruct t as [t0|]; trivial.\n\ndestruct H1.\npose (g0 := fun (h:X->Y) (y:Y0) => h (g y)).\napply bij_finite with _ g0.\nassumption.\npose (g0inv := fun (h:Y0->Y) (x:X) => h (f x)).\nexists g0inv.\nintro.\nextensionality x0; unfold g0; unfold g0inv; simpl.\nrewrite H1; reflexivity.\nintro.\nextensionality y0; unfold g0; unfold g0inv; simpl.\nrewrite H2; reflexivity.\nQed.\n\nLemma FiniteT_has_nat_cardinal: forall X:Type, FiniteT X ->\n  exists! n:nat, cardinal _ (@Full_set X) n.\nProof.\nintros.\napply -> unique_existence; split.\napply finite_cardinal.\npose (idX := fun x:X => x).\nassert (Im Full_set idX = Full_set).\napply Extensionality_Ensembles.\nred; split.\nred; intros; constructor.\nred; intros.\nexists x.\nconstructor.\ntrivial.\n\nrewrite <- H0.\napply FiniteT_img with (f:=fun x:X => x).\nassumption.\nintros.\ncase (finite_eq_dec X H y1 y2); tauto.\n\nred; intros.\napply cardinal_unicity with X Full_set; trivial.\nQed.\n\nDefinition FiniteT_nat_cardinal (X:Type) (H:FiniteT X) : nat :=\n  proj1_sig (constructive_definite_description _\n              (FiniteT_has_nat_cardinal X H)).\nLemma FiniteT_nat_cardinal_def: forall (X:Type) (H:FiniteT X),\n  cardinal _ (@Full_set X) (FiniteT_nat_cardinal X H).\nProof.\nintros; unfold FiniteT_nat_cardinal.\ndestruct constructive_definite_description.\nassumption.\nQed.\nLemma FiniteT_nat_cardinal_cond: forall (X:Type) (H:FiniteT X)\n  (n:nat),\n  cardinal _ (@Full_set X) n ->\n  FiniteT_nat_cardinal X H = n.\nProof.\nintros.\npose proof (FiniteT_has_nat_cardinal X H).\ndestruct H1.\nred in H1.\ndestruct H1.\ntransitivity x.\nsymmetry; apply H2.\napply FiniteT_nat_cardinal_def.\napply H2; trivial.\nQed.\n\nLemma FiniteT_nat_cardinal_False:\n  FiniteT_nat_cardinal False empty_finite = 0.\nProof.\napply FiniteT_nat_cardinal_cond.\nassert (@Full_set False = @Empty_set False).\napply Extensionality_Ensembles; red; split; auto with sets.\nred; intros.\ndestruct x.\nrewrite H.\nconstructor.\nQed.\n\nLemma injection_preserves_cardinal: forall (X Y:Type)\n  (f:X->Y) (n:nat) (S:Ensemble X), cardinal _ S n ->\n  injective f -> cardinal _ (Im S f) n.\nProof.\nintros.\ninduction H.\nassert (Im Empty_set f = Empty_set).\napply Extensionality_Ensembles; split; auto with sets.\nred; intros.\ndestruct H.\ndestruct H.\nrewrite H; constructor.\nassert (Im (Add A x) f = Add (Im A f) (f x)).\napply Extensionality_Ensembles; split.\nred; intros.\ndestruct H2.\nsymmetry in H3; destruct H3.\ndestruct H2.\nleft; exists x0; auto with sets.\ndestruct H2; right; auto with sets.\nred; intros.\ndestruct H2.\ndestruct H2.\nexists x0.\nleft; auto with sets.\nassumption.\ndestruct H2.\nexists x; trivial; right; auto with sets.\nrewrite H2.\nconstructor; trivial.\nred; intro H3; inversion H3.\napply H0 in H5; destruct H5.\ncontradiction H1.\nQed.\n\nLemma FiniteT_nat_cardinal_option:\n  forall (X:Type) (H:FiniteT X),\n  FiniteT_nat_cardinal (option X) (add_finite X H) =\n  S (FiniteT_nat_cardinal X H).\nProof.\nintros.\napply FiniteT_nat_cardinal_cond.\nassert (Full_set =\n        Add (Im Full_set (@Some X)) None).\napply Extensionality_Ensembles; split.\nred; intros.\ndestruct x.\nleft; exists x; constructor.\nright; constructor.\nred; intros; constructor.\nrewrite H0.\nconstructor.\napply injection_preserves_cardinal.\napply FiniteT_nat_cardinal_def.\nred; intros x1 x2 Heq; injection Heq; trivial.\nred; intro.\ninversion H1.\ndiscriminate H3.\nQed.\n\nLemma FiniteT_nat_cardinal_bijection:\n  forall (X Y:Type) (H:FiniteT X) (g:X->Y) (Hinv:invertible g),\n    FiniteT_nat_cardinal Y (bij_finite X Y g H Hinv) =\n    FiniteT_nat_cardinal X H.\nProof.\nintros.\napply FiniteT_nat_cardinal_cond.\napply invertible_impl_bijective in Hinv.\ndestruct Hinv as [g_inj g_surj].\nassert (Full_set = Im Full_set g).\napply Extensionality_Ensembles; split; red; intros;\n  try constructor.\ndestruct (g_surj x).\nexists x0; try constructor; auto.\nrewrite H0; apply injection_preserves_cardinal; trivial.\napply FiniteT_nat_cardinal_def.\nQed.\n\nLemma unique_FiniteT_nat_cardinal:\n  exists! f: (forall (X:Type), FiniteT X -> nat),\n  f False empty_finite = 0 /\\\n  (forall (X:Type) (H:FiniteT X),\n     f (option X) (add_finite X H) = S (f X H)) /\\\n  (forall (X Y:Type) (H:FiniteT X) (g:X->Y) (Hinv:invertible g),\n     f Y (bij_finite X Y g H Hinv) = f X H).\nProof.\nmatch goal with |- @ex ?T (@unique ?T ?f) =>\n  apply -> (@unique_existence T f) end.\nsplit.\nexists FiniteT_nat_cardinal.\nrepeat split.\nexact FiniteT_nat_cardinal_False.\nexact FiniteT_nat_cardinal_option.\nexact FiniteT_nat_cardinal_bijection.\nred; intros f g Hf Hg.\ndestruct Hf as [HFalse_f [Hoption_f Hbijection_f]].\ndestruct Hg as [HFalse_g [Hoption_g Hbijection_g]].\nextensionality X; extensionality HFinite.\ngeneralize HFinite.\ninduction HFinite.\nintro.\ndestruct (proof_irrelevance _ empty_finite HFinite).\ncongruence.\nintro.\ndestruct (proof_irrelevance _ (add_finite T HFinite) HFinite0).\ncongruence.\nintro.\ndestruct (proof_irrelevance _ (bij_finite _ _ f0 HFinite H) HFinite0).\ncongruence.\nQed.\n", "meta": {"author": "dschepler", "repo": "coq-zorns-lemma", "sha": "4ad354c50f73758c094f43da5fc0f2c6dd8e3da2", "save_path": "github-repos/coq/dschepler-coq-zorns-lemma", "path": "github-repos/coq/dschepler-coq-zorns-lemma/coq-zorns-lemma-4ad354c50f73758c094f43da5fc0f2c6dd8e3da2/FiniteTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.653337615025976}}
{"text": "Require Import List.  \nImport ListNotations.\n\nRequire Import Logic.Class.Eq.\n\nRequire Import Logic.List.In.\nRequire Import Logic.List.Include.\nRequire Import Logic.List.InjectiveOn.\nRequire Import Logic.List.Difference.\n\nFixpoint remove (v:Type) (e:Eq v) (x:v) (xs:list v) : list v :=\n    match xs with\n    | []            => []\n    | (cons y ys)   => \n        match (eqDec x y) with \n        | left _    => remove v e x ys\n        | right _   => cons y (remove v e x ys)\n        end\n    end.  \n\nArguments remove {v} {e}.\n\nLemma remove_still : forall (v:Type) (e:Eq v) (x y:v) (xs:list v),\n    x <> y -> y :: xs -> y :: (remove x xs).\nProof.\n    intros v e x y. induction xs as [|a xs IH].\n    - intros _ H. inversion H.\n    - intros Exy H. simpl. destruct (eqDec x a) eqn:Exa. \n        + apply IH.\n            { assumption. }\n            { destruct H as [H1|H2]. \n                { exfalso. apply Exy. rewrite <- H1. assumption. }\n                { assumption. }\n            }\n        + destruct H.  \n            { left. assumption. }\n            { right. apply IH; assumption. }\nQed.\n\n\nLemma remove_mon : forall (v:Type) (e:Eq v) (x:v) (xs ys:list v),\n    xs <= ys -> (remove x xs) <= (remove x ys).\nProof.\n    intros v e x. induction xs as [|a xs IH]; simpl; intros ys H.\n    - intros y Hy. inversion Hy.\n    - destruct (eqDec x a) eqn:E.\n        + apply IH. intros y Hy. apply H. right. assumption.\n        + intros y Hy. destruct (eqDec y a) as [H1|H2].\n            { apply remove_still. \n                { rewrite H1. assumption. }\n                { apply H. left. symmetry. assumption. }\n            }\n            { apply IH.\n                { intros z Hz. apply H. right. assumption. }\n                { destruct Hy as [G1|G2].\n                    { exfalso. apply H2. symmetry. assumption. }\n                    { assumption. }\n                 }\n            }\nQed.\n\nLemma remove_map_incl:forall(v w:Type)(e:Eq v)(e':Eq w)(f:v -> w)(x:v)(xs:list v),\n    remove (f x) (map f xs) <= map f (remove x xs).\nProof.\n    intros v w e e' f x xs. induction xs as [|a xs IH]; simpl.\n    - apply incl_refl.\n    - destruct (eqDec x a) as [P|P].\n        + destruct (eqDec (f x) (f a)) as [Q|Q].\n            { assumption. }\n            { exfalso. apply Q. rewrite P. reflexivity. }\n        + destruct (eqDec (f x) (f a)) as [Q|Q].\n            { apply incl_tl. assumption. }\n            { simpl. intros y Hy. destruct Hy.\n                { left. assumption. }\n                { right. apply IH. assumption. }}\nQed.\n\nLemma remove_x_gone: forall (v:Type) (e:Eq v) (x:v) (xs:list v),\n    ~ x :: remove x xs.\nProof.\n    intros v e x. induction xs as [|a xs IH]; simpl.\n    - intros H. assumption.\n    - destruct (eqDec x a) as [Hp|Hp].\n        + subst. assumption.\n        + intros [H'|H'].\n            { subst. apply Hp. reflexivity. }\n            { apply IH. assumption. }\nQed.\n\n\nLemma remove_x_not_in : forall (v:Type) (e:Eq v) (x:v) (xs:list v),\n    ~ x :: xs -> remove x xs = xs.\nProof.\n    intros v e x xs. induction xs as [|a xs IH]; simpl; intros H.\n    - reflexivity.\n    - destruct (eqDec x a) as [Hx|Hx].\n        + exfalso. apply H. left. symmetry. assumption.\n        + rewrite IH.\n            { reflexivity. }\n            { intros H'. apply H. right. assumption. }\nQed.\n\nLemma remove_map : forall (v w:Type)(e:Eq v)(e':Eq w)(f:v -> w)(x:v)(xs:list v),\n    (forall (y:v), x <> y -> y :: xs -> f x <> f y) ->\n    remove (f x) (map f xs) = map f (remove x xs).\nProof.\n   intros v w e e' f x xs H. \n   induction xs as [|a xs IH]; simpl. \n   - reflexivity.\n   - destruct (eqDec (f x) (f a)) as [Hq|Hq].\n        + subst. destruct (eqDec x a) as [Hp|Hp].\n            { subst. apply IH. intros y H1 H2. apply H.\n                { assumption. }\n                { right. assumption. }}\n            { exfalso. apply H with a. \n                { assumption. }\n                { left. reflexivity. }\n                { assumption. }}\n        + destruct (eqDec x a) as [Hp|Hp].\n            { subst. exfalso. apply Hq. reflexivity. }\n            { simpl. rewrite IH.\n                { reflexivity. }\n                { intros y H1 H2. apply H.\n                    { assumption. }\n                    { right. assumption. }}}\nQed.\n\n\nLemma remove_inj : forall (v w:Type)(e:Eq v)(e':Eq w)(f:v -> w)(x:v)(xs:list v),\n    x :: xs -> \n    injective_on xs f -> \n    remove (f x) (map f xs) = map f (remove x xs).\nProof.\n    intros v w e e' f x xs H1 H2. apply remove_map.\n    intros y H3 H4 H5. apply H3, H2; assumption.\nQed.\n\nLemma remove_inj2 : forall (v w:Type)(e:Eq v)(e':Eq w)(f:v -> w)(x:v)(xs:list v),\n    injective_on (x :: xs) f -> \n    remove (f x) (map f xs) = map f (remove x xs).\nProof.\n    intros v w e e' f x xs H1. apply remove_map.\n    intros y H2 H3 H4. apply H2, H1.\n    - left. reflexivity.\n    - right. assumption.\n    - assumption.\nQed.\n\nLemma remove_incl : forall (v:Type) (e:Eq v) (x:v) (xs:list v), \n    remove x xs <= xs. \nProof.\n    intros v e x xs. induction xs as [|a xs IH]; simpl.\n    - apply incl_refl.\n    - destruct (eqDec x a) as [H|H].\n        + apply incl_tl. assumption.\n        + apply incl_cons_compat. assumption.\nQed.\n\n\nLemma remove_charac : forall (v:Type) (e:Eq v) (x:v) (xs:list v),\n    forall (z:v), z :: remove x xs <-> z :: xs /\\ x <> z.\nProof.\n    intros v e x. induction xs as [|y ys IH]; simpl; intros z.\n    - split; intros H.\n        + exfalso. assumption.\n        + destruct H as [H _]. assumption.\n    - split; intros H; destruct (eqDec x y) as [E|E].\n        + subst. apply IH in H. split.\n            { right. destruct H as [H _]. assumption. }\n            { destruct H as [_ H]. assumption. }\n        + split; destruct H as [H|H].\n            { left. assumption. }\n            { apply IH in H. destruct H as [H1 H2]. right. assumption. }\n            { subst. assumption. }\n            { apply IH in H. destruct H as [_ H]. assumption. }\n        + subst. destruct H as [H1 H2]. destruct H1 as [H1|H1].\n            { exfalso. apply H2. assumption. }\n            { apply IH. split; assumption. }\n        + simpl. destruct H as [H1 H2]. destruct H1 as [H1|H1].\n            { subst. left. reflexivity. }\n            { right. apply IH. split; assumption. }\nQed.\n\nLemma remove_diff : forall (v:Type) (e:Eq v) (x:v) (xs:list v),\n    remove x xs = xs \\\\ [x].\nProof.\n    intros v e x. induction xs as [|y ys IH].\n    - reflexivity.\n    - simpl. destruct (eqDec x y) as [H|H].\n        + apply IH.\n        + rewrite IH. 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/Logic/List/Remove.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6531706169182825}}
{"text": "(* scratch.v  *)\n\nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun seq.\n\n\nInductive e : Type :=\n  | enil : e\n  | eC : e -> e\n  | eP : e ->e.\n\nInductive evol : e -> e -> Prop :=\n | er : forall j k, j = k ->  evol j k\n | ep : forall j k, evol j k -> evol j (eP k).\n\nLemma e_refl: forall e, evol e e.\nProof. by move=> H //; constructor. Qed.\n\nLemma evol_eP i j: evol (eP i) j -> evol i j.\nProof.\nmove=> H2; elim: j H2=>[|e IH| e IH]H2; inversion H2; try (by discriminate H).\n+ by rewrite -H; apply: ep; constructor.\nby apply: ep; apply: IH.\nQed.\n\nLemma e_trans: forall i j k, evol i j -> evol j k -> evol i k.\nProof. \nmove=> i; elim=>//=[||]k/=. case=>//.\n\nmove=>i j k H1; elim=>//. IH H1 H2.\napply: H1. \n\n\nelim=> i1 j1; first by move=>->.\n [|H IH H2].\n H1 H2.\nelim: H1. ", "meta": {"author": "germanD", "repo": "misc", "sha": "5702ba76b5ae6c1c70e5e8033ca2b28044d3876c", "save_path": "github-repos/coq/germanD-misc", "path": "github-repos/coq/germanD-misc/misc-5702ba76b5ae6c1c70e5e8033ca2b28044d3876c/scratch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6531706164420109}}
{"text": "Require Import init.\n\nRequire Export mult_ring.\n\n(** Alright, I lied, these are just records and not categories.  I'll make\ncategories later (maybe).\n*)\n\nRecord RngObj := make_rng {\n    rng_U : Type;\n    rng_plus : Plus rng_U;\n    rng_zero : Zero rng_U;\n    rng_neg : Neg rng_U;\n    rng_mult : Mult rng_U;\n    rng_plus_assoc : @PlusAssoc rng_U rng_plus;\n    rng_plus_comm : @PlusComm rng_U rng_plus;\n    rng_plus_lid : @PlusLid rng_U rng_plus rng_zero;\n    rng_plus_linv : @PlusLinv rng_U rng_plus rng_zero rng_neg;\n    rng_mult_assoc : @MultAssoc rng_U rng_mult;\n    rng_ldist : @Ldist rng_U rng_plus rng_mult;\n    rng_rdist : @Rdist rng_U rng_plus rng_mult;\n}.\n\nRecord RingObj := make_ring {\n    ring_rng : RngObj;\n    ring_one : One (rng_U ring_rng);\n    ring_mult_lid : @MultLid (rng_U ring_rng) (rng_mult ring_rng) ring_one;\n    ring_mult_rid : @MultRid (rng_U ring_rng) (rng_mult ring_rng) ring_one;\n}.\nDefinition ring_U R := rng_U (ring_rng R).\nDefinition ring_plus R := rng_plus (ring_rng R).\nDefinition ring_zero R := rng_zero (ring_rng R).\nDefinition ring_neg R := rng_neg (ring_rng R).\nDefinition ring_mult R := rng_mult (ring_rng R).\nDefinition ring_plus_assoc R := rng_plus_assoc (ring_rng R).\nDefinition ring_plus_comm R := rng_plus_comm (ring_rng R).\nDefinition ring_plus_lid R := rng_plus_lid (ring_rng R).\nDefinition ring_plus_linv R := rng_plus_linv (ring_rng R).\nDefinition ring_mult_assoc R := rng_mult_assoc (ring_rng R).\nDefinition ring_ldist R := rng_ldist (ring_rng R).\nDefinition ring_rdist R := rng_rdist (ring_rng R).\n\nRecord CRingObj := make_cring {\n    cring_ring : RingObj;\n    cring_mult_comm : @MultComm (ring_U cring_ring) (ring_mult cring_ring);\n}.\nDefinition cring_U R := ring_U (cring_ring R).\nDefinition cring_plus R := ring_plus (cring_ring R).\nDefinition cring_zero R := ring_zero (cring_ring R).\nDefinition cring_neg R := ring_neg (cring_ring R).\nDefinition cring_mult R := ring_mult (cring_ring R).\nDefinition cring_plus_assoc R := ring_plus_assoc (cring_ring R).\nDefinition cring_plus_comm R := ring_plus_comm (cring_ring R).\nDefinition cring_plus_lid R := ring_plus_lid (cring_ring R).\nDefinition cring_plus_linv R := ring_plus_linv (cring_ring R).\nDefinition cring_mult_assoc R := ring_mult_assoc (cring_ring R).\nDefinition cring_ldist R := ring_ldist (cring_ring R).\nDefinition cring_one R := ring_one (cring_ring R).\nDefinition cring_mult_lid R := ring_mult_lid (cring_ring R).\n\nGlobal Existing Instances cring_plus cring_zero cring_neg cring_mult\n    cring_plus_assoc cring_plus_comm cring_plus_lid cring_plus_linv\n    cring_mult_assoc cring_ldist cring_one cring_mult_lid cring_mult_comm.\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Algebra/Ring/ring_category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6531504899641692}}
{"text": "Require Import Bool Arith Omega List Coq.Program.Equality.\nRequire Import Maps Imp.\nRequire Import Sequences Semantics.\n\n(** This chapter defines a compiler from the Imp language to a virtual machine\n  (a small subset of the Java Virtual Machine) and proves that this\n  compiler preserves the semantics of the source programs. *)\n\n(** * 1. The virtual machine. *)\n\n(** The machine operates on a code [c] (a fixed list of instructions)\n  and three variable components:\n- a program counter, denoting a position in [c]\n- a state assigning integer values to variables\n- an evaluation stack, containing integers.\n*)\n\n(** The instruction set of the machine. *)\n\nInductive instruction: Type :=\n  | Iconst(n: nat)                 (**r push integer [n] on stack *)\n  | Ivar(x: id)                    (**r push the value of variable [x] *)\n  | Isetvar(x: id)                 (**r pop an integer, assign it to variable [x] *)\n  | Iadd                           (**r pop [n2], pop [n1], push back [n1+n2] *)\n  | Isub                           (**r pop [n2], pop [n1], push back [n1-n2] *)\n  | Imul                           (**r pop [n2], pop [n1], push back [n1*n2] *)\n  | Ibranch_forward(ofs: nat)      (**r skip [ofs] instructions forward *)\n  | Ibranch_backward(ofs: nat)     (**r skip [ofs] instructions backward *)\n  | Ibeq(ofs: nat)                 (**r pop [n2], pop [n1], skip [ofs] forward if [n1=n2] *)\n  | Ibne(ofs: nat)                 (**r pop [n2], pop [n1], skip [ofs] forward if [n1<>n2] *)\n  | Ible(ofs: nat)                 (**r pop [n2], pop [n1], skip [ofs] forward if [n1<=n2] *)\n  | Ibgt(ofs: nat)                 (**r pop [n2], pop [n1], skip [ofs] forward if [n1>n2] *)\n  | Ihalt.                         (**r terminate execution successfully *)\n\nDefinition code := list instruction.\n\n(** [code_at C pc = Some i] if [i] is the instruction at position [pc]\n  in the list of instructions [C]. *)\n\nFixpoint code_at (C: code) (pc: nat) : option instruction :=\n  match C, pc with\n  | nil, _ => None\n  | i :: C', O => Some i\n  | i :: C', S pc' => code_at C' pc'\n  end.\n\nDefinition stack := list nat.\n\n(** The semantics of the virtual machine is given in small-step style,\n  as a transition relation between machine configuration: triples\n  (program counter, evaluation stack, variable state).\n  The transition relation is parameterized by the code [c].\n  There is one transition rule for each kind of instruction,\n  except [Ihalt], which has no transition. *)\n\nDefinition configuration := (nat * stack * state)%type.\n\nInductive transition (C: code): configuration -> configuration -> Prop :=\n  | trans_const: forall pc stk s n,\n      code_at C pc = Some(Iconst n) ->\n      transition C (pc, stk, s) (pc + 1, n :: stk, s)\n  | trans_var: forall pc stk s x,\n      code_at C pc = Some(Ivar x) ->\n      transition C (pc, stk, s) (pc + 1, s x :: stk, s)\n  | trans_setvar: forall pc stk s x n,\n      code_at C pc = Some(Isetvar x) ->\n      transition C (pc, n :: stk, s) (pc + 1, stk, t_update s x n)\n  | trans_add: forall pc stk s n1 n2,\n      code_at C pc = Some(Iadd) ->\n      transition C (pc, n2 :: n1 :: stk, s) (pc + 1, (n1 + n2) :: stk, s)\n  | trans_sub: forall pc stk s n1 n2,\n      code_at C pc = Some(Isub) ->\n      transition C (pc, n2 :: n1 :: stk, s) (pc + 1, (n1 - n2) :: stk, s)\n  | trans_mul: forall pc stk s n1 n2,\n      code_at C pc = Some(Imul) ->\n      transition C (pc, n2 :: n1 :: stk, s) (pc + 1, (n1 * n2) :: stk, s)\n  | trans_branch_forward: forall pc stk s ofs pc',\n      code_at C pc = Some(Ibranch_forward ofs) ->\n      pc' = pc + 1 + ofs ->\n      transition C (pc, stk, s) (pc', stk, s)\n  | trans_branch_backward: forall pc stk s ofs pc',\n      code_at C pc = Some(Ibranch_backward ofs) ->\n      pc' = pc + 1 - ofs ->\n      transition C (pc, stk, s) (pc', stk, s)\n  | trans_beq: forall pc stk s ofs n1 n2 pc',\n      code_at C pc = Some(Ibeq ofs) ->\n      pc' = (if beq_nat n1 n2 then pc + 1 + ofs else pc + 1) ->\n      transition C (pc, n2 :: n1 :: stk, s) (pc', stk, s)\n  | trans_bne: forall pc stk s ofs n1 n2 pc',\n      code_at C pc = Some(Ibne ofs) ->\n      pc' = (if beq_nat n1 n2 then pc + 1 else pc + 1 + ofs) ->\n      transition C (pc, n2 :: n1 :: stk, s) (pc', stk, s)\n  | trans_ble: forall pc stk s ofs n1 n2 pc',\n      code_at C pc = Some(Ible ofs) ->\n      pc' = (if leb n1 n2 then pc + 1 + ofs else pc + 1) ->\n      transition C (pc, n2 :: n1 :: stk, s) (pc', stk, s)\n  | trans_bgt: forall pc stk s ofs n1 n2 pc',\n      code_at C pc = Some(Ibgt ofs) ->\n      pc' = (if leb n1 n2 then pc + 1 else pc + 1 + ofs) ->\n      transition C (pc, n2 :: n1 :: stk, s) (pc', stk, s).\n\n(** As usual with small-step semantics, we form sequences of machine transitions\n  to define the behavior of a code.  We always start with [pc = 0]\n  and an empty evaluation stack.  We stop successfully if [pc] points\n  to an [Ihalt] instruction and the evaluation stack is empty.\n\n  If [R] is a binary relation, [star R] is its reflexive transitive closure.\n  (See file [Sequences] for the definition.)  [star (transition C)]\n  therefore represents a sequence of  zero, one or several machine transitions.\n*)\n\nDefinition mach_terminates (C: code) (s_init s_fin: state) :=\n  exists pc,\n  code_at C pc = Some Ihalt /\\\n  star (transition C) (0, nil, s_init) (pc, nil, s_fin).\n\n(** Likewise, [infseq R] represents an infinite sequence of [R] transitions.\n  (Also defined in file [Sequences].) *)\n\nDefinition mach_diverges (C: code) (s_init: state) :=\n  infseq (transition C) (0, nil, s_init).\n\n(** A third case can occur: after a finite number of transitions,\n  the machine hits a configuration where it cannot make any transition,\n  and this state is not a final configuration ([Ihalt] instruction and empty stack).\n  In this case, we say that the machine \"goes wrong\", which is\n  a politically-correct way of saying that our program just crashed. *)\n\nDefinition mach_goes_wrong (C: code) (s_init: state) :=\n  exists pc, exists stk, exists s_fin,\n  star (transition C) (0, nil, s_init) (pc, stk, s_fin)\n  /\\ irred (transition C) (pc, stk, s_fin)\n  /\\ (code_at C pc <> Some Ihalt \\/ stk <> nil).\n\n(** An important property of the virtual machine is that it is deterministic:\n  from a given configuration, it can transition to at most one other configuration. *)\n\nLemma machine_deterministic:\n  forall C config config1 config2,\n  transition C config config1 -> transition C config config2 -> config1 = config2.\nProof.\n  intros. inversion H; subst; inversion H0; try congruence.\n  destruct (beq_nat n1 n2); congruence.\n  destruct (beq_nat n1 n2); congruence.\n  destruct (leb n1 n2); congruence.\n  destruct (leb n1 n2); congruence.\nQed.\n\n(** As a consequence of this determinism, it follows that\n  the final state of a terminating program is unique,\n  and that a program cannot both terminate and diverge,\n  or terminate and go wrong, or diverge and go wrong.\n  These results follow from the generic determinism properties \n  found at the end of module [Sequence]. *)\n\nRemark stop_irred:\n  forall C pc stk st,\n  code_at C pc = Some Ihalt -> irred (transition C) (pc, stk, st).\nProof.\n  unfold irred; intros. unfold not; intros. inversion H0; congruence.\nQed.\n\nLemma terminates_unique:\n  forall C st st1 st2, mach_terminates C st st1 -> mach_terminates C st st2 -> st1 = st2.\nProof.\n  unfold mach_terminates; intros. destruct H as (pc1 & A1 & B1), H0 as (pc2 & A2 & B2).\n  assert (((pc1, nil, st1) : configuration) = ((pc2, nil, st2) : configuration)).\n  { eapply finseq_unique; eauto using machine_deterministic, stop_irred. }\n  congruence. \nQed.\n\nLemma terminates_goeswrong_exclusive:\n  forall C st st', mach_terminates C st st' -> mach_goes_wrong C st -> False.\nProof.\n  unfold mach_terminates, mach_goes_wrong; intros.\n  destruct H as (pc1 & A1 & B1), H0 as (pc2 & stk2 & st2 & A2 & B2 & C2).\n  assert (((pc1, nil, st') : configuration) = ((pc2, stk2, st2) : configuration)).\n  { eapply finseq_unique; eauto using machine_deterministic, stop_irred. }\n  inversion H. subst pc2 stk2 st2. destruct C2; congruence.\nQed.\n\nLemma terminates_diverges_exclusive:\n  forall C st st', mach_terminates C st st' -> mach_diverges C st -> False.\nProof.\n  unfold mach_terminates, mach_diverges; intros.\n  destruct H as (pc1 & A1 & B1).\n  eapply infseq_finseq_excl with (R := transition C); eauto using machine_deterministic, stop_irred.\nQed.\n\nLemma goeswrong_diverges_exclusive:\n  forall C st, mach_goes_wrong C st -> mach_diverges C st -> False.\nProof.\n  unfold mach_terminates, mach_diverges; intros. \n  destruct H as (pc2 & stk2 & st2 & A2 & B2 & C2).\n  eapply infseq_finseq_excl with (R := transition C); eauto using machine_deterministic, stop_irred.\nQed.\n\n(** *** Exercise (2 stars, recommended). *)\n(** To quickly see how a machine program executes, it is convenient\n  to redefine the semantics of the machine as an executable function\n  instead of inductively-defined relations.  This is similar to the\n  [ceval_step] function from the [Imp] chapter of Software Foundations,\n  which provides an executable interpreter for the Imp language.\n\n  To ensure termination of the machine interpreter, we need to bound \n  the number of instructions it can execute.  The result of the\n  machine interpreter, therefore, is of the following type:\n*)\n\nInductive machine_result : Type :=\n  | Timeout : machine_result              (**r the interpreter ran out of fuel *)\n  | GoesWrong : machine_result            (**r the machine goes wrong on an impossible case *)\n  | Terminates : state -> machine_result. (**r the machine successfully stops with the given state *)\n\n(** Please fill in the blanks in the following definition for a machine interpreter: *)\n\nFixpoint mach_interp (C: code) (fuel: nat)\n                     (pc: nat) (stk: stack) (st: state) : machine_result :=\n  match fuel with\n  | O => Timeout\n  | S fuel' =>\n      match code_at C pc, stk with\n      | Some Ihalt, nil => Terminates st\n      | Some (Iconst n), stk => mach_interp C fuel' (pc + 1) (n :: stk) st\n      (* FILL IN HERE *)\n      | _, _ => GoesWrong\n      end\n  end.\n\n(** * 2. The compilation scheme *)\n\n(** The code for an arithmetic expression [a]\n- executes in sequence (no branches)\n- deposits the value of [a] at the top of the stack\n- preserves the variable state.\n\nThis is the familiar translation to \"reverse Polish notation\".\n*)\n\nFixpoint compile_aexp (a: aexp) : code :=\n  match a with\n  | ANum n => Iconst n :: nil\n  | AId v => Ivar v :: nil\n  | APlus a1 a2 => compile_aexp a1 ++ compile_aexp a2 ++ Iadd :: nil\n  | AMinus a1 a2 => compile_aexp a1 ++ compile_aexp a2 ++ Isub :: nil\n  | AMult a1 a2 => compile_aexp a1 ++ compile_aexp a2 ++ Imul :: nil\n  end.\n\n(** Some examples. *)\n\nNotation vx := (Id \"X\").\nNotation vy := (Id \"Y\").\n\nCompute (compile_aexp (APlus (AId vx) (ANum 1))).\n\n(** Result is: [ [Ivar vx, Iconst 1, Iadd] ] *)\n\nCompute (compile_aexp (AMult (AId vy) (APlus (AId vx) (ANum 1)))).\n\n(** Result is: [ [Ivar vy, Ivar vx, Iconst 1, Iadd, Imul] ] *)\n\n(** The code [compile_bexp b cond ofs] for a boolean expression [b]\n- skips forward the [ofs] following instructions if [b] evaluates to [cond] (a boolean)\n- executes in sequence if [b] evaluates to the negation of [cond]\n- leaves the stack and the variable state unchanged.\n\nSee slides for explanation of the mysterious branch offsets!\n*)\n\nFixpoint compile_bexp (b: bexp) (cond: bool) (ofs: nat) : code :=\n  match b with\n  | BTrue =>\n      if cond then Ibranch_forward ofs :: nil else nil\n  | BFalse =>\n      if cond then nil else Ibranch_forward ofs :: nil\n  | BEq a1 a2 =>\n      compile_aexp a1 ++ compile_aexp a2 ++\n      (if cond then Ibeq ofs :: nil else Ibne ofs :: nil)\n  | BLe a1 a2 =>\n      compile_aexp a1 ++ compile_aexp a2 ++\n      (if cond then Ible ofs :: nil else Ibgt ofs :: nil)\n  | BNot b1 =>\n      compile_bexp b1 (negb cond) ofs\n  | BAnd b1 b2 =>\n      let c2 := compile_bexp b2 cond ofs in\n      let c1 := compile_bexp b1 false (if cond then length c2 else ofs + length c2) in\n      c1 ++ c2\n  end.\n\n(** Examples. *)\n\nCompute (compile_bexp (BEq (AId vx) (ANum 1)) true 42).\n\n(** Result is: [ [Ivar vx, Iconst 1, Ibeq 42] ] *)\n\nCompute (compile_bexp (BAnd (BLe (ANum 1) (AId vx)) (BLe (AId vx) (ANum 10))) false 42).\n\n(** Result is: [ [Iconst 1, Ivar vx, Ibgt 45, Ivar vx, Iconst 10, Ibgt 42] ] *)\n\nCompute (compile_bexp (BNot (BAnd BTrue BFalse)) true 42).\n\n(** Result is: [ [Ibranch_forward 42] ] *)\n\n(** The code for a command [c]\n- updates the variable state as prescribed by [c]\n- preserves the stack\n- finishes on the next instruction immediately following the generated code.\n\nAgain, see slides for explanations of the generated branch offsets.\n*)\n\nFixpoint compile_com (c: com) : code :=\n  match c with\n  | SKIP =>\n      nil\n  | (id ::= a) =>\n      compile_aexp a ++ Isetvar id :: nil\n  | (c1 ;; c2) =>\n      compile_com c1 ++ compile_com c2\n  | IFB b THEN ifso ELSE ifnot FI =>\n      let code_ifso := compile_com ifso in\n      let code_ifnot := compile_com ifnot in\n      compile_bexp b false (length code_ifso + 1)\n      ++ code_ifso\n      ++ Ibranch_forward (length code_ifnot)\n      :: code_ifnot\n  | WHILE b DO body END =>\n      let code_body := compile_com body in\n      let code_test := compile_bexp b false (length code_body + 1) in\n      code_test\n      ++ code_body\n      ++ Ibranch_backward (length code_test + length code_body + 1)\n      :: nil\n  end.\n\n(** The code for a program [p] (a command) is similar, but terminates\n  cleanly on an [Ihalt] instruction. *)\n\nDefinition compile_program (p: com) : code :=\n  compile_com p ++ Ihalt :: nil.\n\n(** Examples of compilation: *)\n\nCompute (compile_program (vx ::= APlus (AId vx) (ANum 1))).\n\n(** Result is: [ [Ivar vx, Iconst 1, Iadd, Isetvar vx, Ihalt] ] *)\n\nCompute (compile_program (WHILE BTrue DO SKIP END)).\n\n(** Result is: [ [Ibranch_backward 1, Ihalt] ].  That's a tight loop indeed! *)\n\nCompute (compile_program (IFB BEq (AId vx) (ANum 1) THEN vx ::= ANum 0 ELSE SKIP FI)).\n\n(** Result is: [ [Ivar vx, Iconst 1, Ibne 3, Iconst 0, Isetvar vx, Ibranch_forward 0, Ihalt] ] *)\n\n(** *** Exercise (1 star, recommended) *)\n(** The last example shows a slight inefficiency in the code generated for\n  [IFB ... THEN ... ELSE SKIP FI].  How would you change [compile_com]\n  to generate better code?  Hint: ponder the following function. *)\n\nDefinition smart_Ibranch_forward (ofs: nat) : code :=\n  if beq_nat ofs 0 then nil else Ibranch_forward(ofs) :: nil.\n\n(** * 3. Semantic preservation *)\n\n(** ** Auxiliary results about code sequences. *)\n\n(** To reason about the execution of compiled code, we need to consider\n  code sequences [C2] that are at position [pc] in a bigger code\n  sequence [C = C1 ++ C2 ++ C3].  The following predicate\n  [codeseq_at C pc C2] does just this. *)\n\nInductive codeseq_at: code -> nat -> code -> Prop :=\n  | codeseq_at_intro: forall C1 C2 C3 pc,\n      pc = length C1 ->\n      codeseq_at (C1 ++ C2 ++ C3) pc C2.\n\n(** We show a number of no-brainer lemmas about [code_at] and [codeseq_at],\n  then populate a \"hint database\" so that Coq can use them automatically. *)\n\nLemma code_at_app:\n  forall i c2 c1 pc,\n  pc = length c1 ->\n  code_at (c1 ++ i :: c2) pc = Some i.\nProof.\n  induction c1; simpl; intros; subst pc; auto.\nQed.\n\nLemma codeseq_at_head:\n  forall C pc i C',\n  codeseq_at C pc (i :: C') ->\n  code_at C pc = Some i.\nProof.\n  intros. inversion H. simpl. apply code_at_app. auto.\nQed.\n\nLemma codeseq_at_tail:\n  forall C pc i C',\n  codeseq_at C pc (i :: C') ->\n  codeseq_at C (pc + 1) C'.\nProof.\n  intros. inversion H. \n  change (C1 ++ (i :: C') ++ C3)\n    with (C1 ++ (i :: nil) ++ C' ++ C3).\n  rewrite <- app_ass. constructor. rewrite app_length. auto.\nQed. \n\nLemma codeseq_at_app_left:\n  forall C pc C1 C2,\n  codeseq_at C pc (C1 ++ C2) ->\n  codeseq_at C pc C1.\nProof.\n  intros. inversion H. rewrite app_ass. constructor. auto.\nQed.\n\nLemma codeseq_at_app_right:\n  forall C pc C1 C2,\n  codeseq_at C pc (C1 ++ C2) ->\n  codeseq_at C (pc + length C1) C2.\nProof.\n  intros. inversion H. rewrite app_ass. rewrite <- app_ass. constructor. rewrite app_length. auto.\nQed.\n\nLemma codeseq_at_app_right2:\n  forall C pc C1 C2 C3,\n  codeseq_at C pc (C1 ++ C2 ++ C3) ->\n  codeseq_at C (pc + length C1) C2.\nProof.\n  intros. inversion H. repeat rewrite app_ass. rewrite <- app_ass. constructor. rewrite app_length. auto.\nQed.\n\nHint Resolve codeseq_at_head codeseq_at_tail codeseq_at_app_left codeseq_at_app_right codeseq_at_app_right2: codeseq.\n\nLtac normalize :=\n  repeat rewrite app_length in *;\n  repeat rewrite plus_assoc in *;\n  repeat rewrite plus_0_r in *;\n  simpl in *.\n\n(** ** Correctness of generated code for expressions. *)\n\n(** Remember the informal specification we gave for the code generated\n  for an arithmetic expression [a].  It should\n- execute in sequence (no branches)\n- deposit the value of [a] at the top of the stack\n- preserve the variable state.\n\nWe now prove that the code [compile_aexp a] fulfills this contract.\nThe proof is a nice induction on the structure of [a]. *)\n\nLemma compile_aexp_correct:\n  forall C st a pc stk,\n  codeseq_at C pc (compile_aexp a) ->\n  star (transition C)\n       (pc, stk, st)\n       (pc + length (compile_aexp a), aeval st a :: stk, st).\nProof.\n  induction a; simpl; intros.\n\n- (* ANum *)\n  apply star_one. apply trans_const. eauto with codeseq. \n\n- (* AId *)\n  apply star_one. apply trans_var. eauto with codeseq. \n\n- (* APlus *)\n  eapply star_trans.\n  apply IHa1. eauto with codeseq. \n  eapply star_trans.\n  apply IHa2. eauto with codeseq. \n  apply star_one. normalize. apply trans_add. eauto with codeseq. \n\n- (* AMinus *)\n  eapply star_trans.\n  apply IHa1. eauto with codeseq. \n  eapply star_trans.\n  apply IHa2. eauto with codeseq. \n  apply star_one. normalize. apply trans_sub. eauto with codeseq. \n\n- (* AMult *)\n  eapply star_trans.\n  apply IHa1. eauto with codeseq. \n  eapply star_trans.\n  apply IHa2. eauto with codeseq. \n  apply star_one. normalize. apply trans_mul. eauto with codeseq. \nQed.\n\n(** Here is a similar proof for the compilation of boolean expressions. *)\n\nLemma compile_bexp_correct:\n  forall C st b cond ofs pc stk,\n  codeseq_at C pc (compile_bexp b cond ofs) ->\n  star (transition C)\n       (pc, stk, st)\n       (pc + length (compile_bexp b cond ofs) + if eqb (beval st b) cond then ofs else 0, stk, st).\nProof.\n  induction b; simpl; intros.\n\n- (* BTrue *)\n  destruct cond; simpl.\n  + (* BTrue, true *)\n    apply star_one. apply trans_branch_forward with ofs. eauto with codeseq. auto.\n  + (* BTrue, false *)\n    repeat rewrite plus_0_r. apply star_refl.\n \n- (* BFalse *)\n  destruct cond; simpl.\n  + (* BFalse, true *)\n    repeat rewrite plus_0_r. apply star_refl.\n  + (* BFalse, false *)\n    apply star_one. apply trans_branch_forward with ofs. eauto with codeseq. auto.\n\n- (* BEq *)\n  eapply star_trans. \n  apply compile_aexp_correct with (a := a). eauto with codeseq. \n  eapply star_trans.\n  apply compile_aexp_correct with (a := a0). eauto with codeseq. \n  apply star_one. normalize.\n  destruct cond.\n  + (* BEq, true *)\n    apply trans_beq with ofs. eauto with codeseq.\n    destruct (beq_nat (aeval st a) (aeval st a0)); simpl; omega.\n  + (* BEq, false *)\n    apply trans_bne with ofs. eauto with codeseq. \n    destruct (beq_nat (aeval st a) (aeval st a0)); simpl; omega.\n\n- (* BLe *)\n  eapply star_trans. \n  apply compile_aexp_correct with (a := a). eauto with codeseq. \n  eapply star_trans.\n  apply compile_aexp_correct with (a := a0). eauto with codeseq. \n  apply star_one. normalize.\n  destruct cond.\n  + (* BLe, true *)\n    apply trans_ble with ofs. eauto with codeseq.\n    destruct (leb (aeval st a) (aeval st a0)); simpl; omega.\n  + (* BLe, false *)\n    apply trans_bgt with ofs. eauto with codeseq. \n    destruct (leb (aeval st a) (aeval st a0)); simpl; omega.\n\n- (* BNot *)\n  replace (eqb (negb (beval st b)) cond)\n     with (eqb (beval st b) (negb cond)).\n  apply IHb; auto. \n  destruct (beval st b); destruct cond; auto.\n\n- (* BAnd *)\n  set (code_b2 := compile_bexp b2 cond ofs) in *.\n  set (ofs' := if cond then length code_b2 else ofs + length code_b2) in *.\n  set (code_b1 := compile_bexp b1 false ofs') in *.\n  apply star_trans with (pc + length code_b1 + (if eqb (beval st b1) false then ofs' else 0), stk, st).\n  apply IHb1. eauto with codeseq.\n  destruct cond.\n  + (* BAnd, true *)\n    destruct (beval st b1); simpl.\n    * (* b1 evaluates to true *)\n      normalize. apply IHb2. eauto with codeseq. \n    * (* b1 evaluates to false *)\n      normalize. apply star_refl.\n  + (* BAnd, false *)\n    destruct (beval st b1); simpl.\n    * (* b1 evaluates to true *)\n      normalize. apply IHb2. eauto with codeseq. \n    * (* b1 evaluates to false *)\n      replace ofs' with (length code_b2 + ofs). normalize. apply star_refl.\n      unfold ofs'; omega.\nQed.\n\n(** ** Correctness of generated code for commands: terminating case. *)\n\nLemma compile_com_correct_terminating:\n  forall C st c st',\n  c / st \\\\ st' ->\n  forall stk pc,\n  codeseq_at C pc (compile_com c) ->\n  star (transition C)\n       (pc, stk, st)\n       (pc + length (compile_com c), stk, st').\nProof.\n  induction 1; intros stk pc AT.\n\n- (* SKIP *)\n  simpl in *. rewrite plus_0_r. apply star_refl.\n\n- (* := *)\n  simpl in *. subst n.\n  eapply star_trans. apply compile_aexp_correct. eauto with codeseq.\n  apply star_one. normalize. apply trans_setvar. eauto with codeseq. \n\n- (* sequence *)\n  simpl in *.\n  eapply star_trans. apply IHceval1. eauto with codeseq. \n  normalize. apply IHceval2. eauto with codeseq. \n\n- (* if true *)\n  simpl in *.\n  set (code1 := compile_com c1) in *.\n  set (codeb := compile_bexp b false (length code1 + 1)) in *.\n  set (code2 := compile_com c2) in *.\n  eapply star_trans. \n  apply compile_bexp_correct with (b := b) (cond := false) (ofs := length code1 + 1).\n  eauto with codeseq. \n  rewrite H. simpl. rewrite plus_0_r. fold codeb. normalize.\n  eapply star_trans. apply IHceval. eauto with codeseq. \n  apply star_one. eapply trans_branch_forward. eauto with codeseq. omega.\n\n- (* if false *)\n  simpl in *.\n  set (code1 := compile_com c1) in *.\n  set (codeb := compile_bexp b false (length code1 + 1)) in *.\n  set (code2 := compile_com c2) in *.\n  eapply star_trans. \n  apply compile_bexp_correct with (b := b) (cond := false) (ofs := length code1 + 1).\n  eauto with codeseq. \n  rewrite H. simpl. fold codeb. normalize.\n  replace (pc + length codeb + length code1 + S(length code2))\n     with (pc + length codeb + length code1 + 1 + length code2).\n  apply IHceval. eauto with codeseq. omega. \n\n- (* while false *)\n  simpl in *. \n  eapply star_trans.\n  apply compile_bexp_correct with (b := b) (cond := false) (ofs := length (compile_com c) + 1). \n  eauto with codeseq.\n  rewrite H. simpl. normalize. apply star_refl.\n\n- (* while true *)\n  apply star_trans with (pc, stk, st').\n  simpl in *.\n  eapply star_trans.\n  apply compile_bexp_correct with (b := b) (cond := false) (ofs := length (compile_com c) + 1). \n  eauto with codeseq. \n  rewrite H; simpl. rewrite plus_0_r.\n  eapply star_trans. apply IHceval1. eauto with codeseq. \n  apply star_one.\n  eapply trans_branch_backward. eauto with codeseq. omega.\n  apply IHceval2. auto.\nQed.\n\nTheorem compile_program_correct_terminating:\n  forall c st st',\n  c / st \\\\ st' ->\n  mach_terminates (compile_program c) st st'.\nProof.\n  intros. unfold compile_program. red.\n  exists (length (compile_com c)); split.\n  apply code_at_app. auto.\n  apply compile_com_correct_terminating with (pc := 0). auto. \n  apply codeseq_at_intro with (C1 := nil). auto.\nQed.\n\n\n(** *** Exercise (2 stars, recommended) *)\n(** The previous exercise in this chapter suggested to use\n  [smart_Ibranch_forward] to avoid generating useless \"branch forward\"\n  instructions when compiling [IFB ... THEN ... ELSE SKIP FI] commands.\n  Once you have modified [compile_com] to use [smart_Ibranch_forward],\n  adapt the proof of [compile_com_correct_terminating] accordingly.\n  The following lemma will come handy: *)\n\nLemma trans_smart_branch_forward:\n  forall C ofs pc stk st,\n  codeseq_at C pc (smart_Ibranch_forward ofs) ->\n  star (transition C) (pc, stk, st) (pc + length (smart_Ibranch_forward ofs) + ofs, stk, st).\nProof.\n  unfold smart_Ibranch_forward; intros.\n  (* FILL IN HERE *)\nAdmitted.\n\n(** *** Exercise (3 stars, optional) *)\n(** The manufacturer of our virtual machine offers a cheaper variant\n  that lacks the [Ibge] and [Ibgt] conditional branches.  The only\n  conditional branches available are [Ibeq] (branch if equal) and \n  [Ibne] (branch if different).  Modify the definition of [compile_bexp] and\n  its correctness proof to target this cheaper virtual machine.\n  Hint: study Coq's definition of subtraction between natural numbers\n  (do [Print Nat.sub]). *)\n\n(** ** Correctness of generated code for commands: general case. *)\n\n(** We would like to strengthen the correctness result above so that it\n  is not restricted to terminating source programs, but also applies to\n  source program that diverge.  To this end, we abandon the big-step\n  semantics for commands and switch to the small-step semantics with continuations.\n  We then show a simulation theorem, establishing that every transition\n  of the small-step semantics in the source program is simulated (in a sense\n  to be made precise below) by zero, one or several transitions of the\n  machine executing the compiled code for the source program. *)\n\n(** Our first task is to relate configurations [(c, k, st)] of the small-step\n  semantics with configurations [(C, pc, stk, st)] of the machine.\n  We already know how to relate a command [c] with the machine code,\n  using the [codeseq_at] predicate.  What needs to be defined is a relation\n  between the continuation [k] and the machine code.\n\n  Intuitively, when the machine finishes executing the generated code for\n  command [c], that is, when it reaches the program point\n  [pc + length(compile_com c)], the machine should continue by executing\n  instructions that perform the pending computations described by\n  continuation [k], then reach an [Ihalt] instruction to stop cleanly.\n\n  We formalize this intution by the following inductive predicate\n  [compile_cont C k pc], which states that, starting at program point [pc],\n  there are instructions that perform the computations described in [k]\n  and reach an [Ihalt] instruction. *)\n\nInductive compile_cont (C: code): cont -> nat -> Prop :=\n  | ccont_stop: forall pc,\n      code_at C pc = Some Ihalt ->\n      compile_cont C Kstop pc\n  | ccont_seq: forall c k pc pc',\n      codeseq_at C pc (compile_com c) ->\n      pc' = pc + length (compile_com c) ->\n      compile_cont C k pc' ->\n      compile_cont C (Kseq c k) pc\n  | ccont_while: forall b c k pc ofs pc' pc'',\n      code_at C pc = Some(Ibranch_backward ofs) ->\n      pc' = pc + 1 - ofs ->\n      codeseq_at C pc' (compile_com (WHILE b DO c END)) ->\n      pc'' = pc' + length (compile_com (WHILE b DO c END)) ->\n      compile_cont C k pc'' ->\n      compile_cont C (Kwhile b c k) pc\n  | ccont_branch: forall ofs k pc pc',\n      code_at C pc = Some(Ibranch_forward ofs) ->\n      pc' = pc + 1 + ofs ->\n      compile_cont C k pc' ->\n      compile_cont C k pc.\n\n(** Then, a configuration [(c,k,st)] of the small-step semantics matches\n  a configuration [(C, pc, stk, st')] of the machine if the following conditions hold:\n- The memory states are identical: [st' = st].\n- The machine stack is empty: [stk = nil].\n- The machine code at point [pc] is the compiled code for [c]:\n  [codeseq_at C pc (compile_com c)].\n- The machine code at point [pc + length (compile_com c)] matches continuation\n  [k], in the sense of [compile_cont] above.\n*)\n\nInductive match_config (C: code): com * cont * state -> configuration -> Prop :=\n  | match_config_intro: forall c k st pc,\n      codeseq_at C pc (compile_com c) ->\n      compile_cont C k (pc + length (compile_com c)) ->\n      match_config C (c, k, st) (pc, nil, st).\n\n(** We are now ready to prove the expected simulation property.  Our first\n  attempt is to show a diagram of the following form:\n<<\n                      match_config\n     c / k / st  ----------------------- machstate\n       |                                   |\n       |                                   | *\n       |                                   |\n       v                                   v\n    c' / k' / st' ----------------------- machstate'\n                      match_config \n>>\nHypotheses:\n- Left: one transition in the small-step continuation semantics for Imp.\n- Top: the [match_config] invariant.\n\nConclusions:\n- Bottom: the [match_config] invariant, which must be preserved.\n- Right: zero, one or several transitions of the virtual machine.\n\nWhy \"zero, one, or several\"?  Some transitions of the Imp semantics involve\nthe evaluation of a complex expression, which requires several machine instructions\nto be executed.  However, other transitions of the Imp semantics, such as\nthe [KS_Seq] and [KS_SkipSeq] rules, just change the focus on a sub-command,\nbut the machine need not execute any instruction to reflect this change of focus.\n*)\n\nLemma simulation_step_first_attempt:\n  forall C impstate1 impstate2 machstate1,\n  kstep impstate1 impstate2 ->\n  match_config C impstate1 machstate1 ->\n  exists machstate2,\n      star (transition C) machstate1 machstate2\n   /\\ match_config C impstate2 machstate2.\nProof.\nAbort.\n\n(** This simulation lemma is true and can be proved, but it is too weak to\n  imply the preservation of diverging behaviors: we have an issue with\n  \"infinite stuttering\".  Imagine a situation where the source program\n  takes infinitely many transitions, but every such transition is matched\n  by zero transitions of the virtual machine.  In this case, the source\n  program diverges, but the machine code can do anything: it can diverge,\n  as expected, but it can also terminate cleanly or go wrong. \n  The simulation lemma above is too weak to rule out the last two cases!\n\n  We therefore need a stronger simulation result that rules out stuttering.\n  To this end, we are going to require that if a source transition is\n  matched by zero machine transition, some nonnegative measure of the source\n  configuration must strictly decrease.  This ensures that only a finite\n  number of stuttering steps can be taken before the machine actually does\n  a transition.  Here is the revised simulation diagram:\n \n<<\n                      match_config\n     c / k / st  ----------------------- machconfig\n       |                                   |\n       |                                   | + or ( * and |c',k'| < |c,k} )\n       |                                   |\n       v                                   v\n    c' / k' / st' ----------------------- machconfig'\n                      match_config \n>>\nNote the stronger conclusion on the right:\n- either the virtual machine does one or several transitions\n- or it does zero, one or several transitions, but the size of the [c,k]\n  pair decreases strictly.\n\nIt would be equivalent to state:\n- either the virtual machine does one or several transitions\n- or it does zero transitions, but the size of the [c,k] pair decreases strictly.\n\nHowever, the formulation above, with the \"star\" case, is often more convenient.\n*)\n\n(** Finding an appropriate \"anti-stuttering\" measure is a bit of a black art.\nAfter trial and error, we find that the following measure works.  It is\nthe sum of the sizes of the command [c] under focus and all the commands\nappearing in the continuation [k]. *)\n\nFixpoint com_size (c: com) : nat :=\n  match c with\n  | SKIP => 1\n  | x ::= a => 1\n  | (c1 ;; c2) => com_size c1 + com_size c2 + 1\n  | IFB b THEN ifso ELSE ifnot FI => com_size ifso + com_size ifnot + 1\n  | WHILE b DO c1 END => com_size c1 + 1\n  end.\n\nRemark com_size_nonzero: forall c, com_size c > 0. \nProof.\n  induction c; simpl; omega.\nQed.\n\nFixpoint cont_size (k: cont) : nat :=\n  match k with\n  | Kstop => 0\n  | Kseq c k' => com_size c + cont_size k'\n  | Kwhile b c k' => cont_size k'\n  end.\n\nDefinition measure (impconf: com * cont * state) : nat :=\n  match impconf with (c, k, m) => com_size c + cont_size k end.\n\n(** A few technical lemmas to help with the simulation proof. *)\n\nLemma compile_cont_Kstop_inv:\n  forall C pc m,\n  compile_cont C Kstop pc ->\n  exists pc',\n  star (transition C) (pc, nil, m) (pc', nil, m)\n  /\\ code_at C pc' = Some Ihalt.\nProof.\n  intros. dependent induction H. \n- exists pc; split. apply star_refl. auto.\n- destruct IHcompile_cont as [pc'' [A B]]; auto.\n  exists pc''; split; auto. eapply star_step; eauto. eapply trans_branch_forward; eauto. \nQed.\n\nLemma compile_cont_Kseq_inv:\n  forall C c k pc m,\n  compile_cont C (Kseq c k) pc ->\n  exists pc',\n  star (transition C) (pc, nil, m) (pc', nil, m)\n  /\\ codeseq_at C pc' (compile_com c)\n  /\\ compile_cont C k (pc' + length(compile_com c)).\nProof.\n  intros. dependent induction H. \n  exists pc; split. apply star_refl. split; congruence. \n  destruct (IHcompile_cont _ _ eq_refl) as [pc'' [A [B D]]].\n  exists pc''; split; auto. eapply star_step; eauto. eapply trans_branch_forward; eauto. \nQed.\n\nLemma compile_cont_Kwhile_inv:\n  forall C b c k pc m,\n  compile_cont C (Kwhile b c k) pc ->\n  exists pc',\n  plus (transition C) (pc, nil, m) (pc', nil, m)\n  /\\ codeseq_at C pc' (compile_com (WHILE b DO c END))\n  /\\ compile_cont C k (pc' + length(compile_com (WHILE b DO c END))).\nProof.\n  intros. dependent induction H.\n- exists (pc + 1 - ofs); split.\n  apply plus_one. eapply trans_branch_backward; eauto. \n  split; congruence.\n- destruct (IHcompile_cont _ _ _ (refl_equal _)) as [pc'' [A [B D]]].\n  exists pc''; split; auto. eapply plus_left. eapply trans_branch_forward; eauto. apply plus_star; auto. \nQed.\n\nRemark code_at_inv:\n  forall C pc i, code_at C pc = Some i -> exists C1, exists C2, C = C1 ++ C2 /\\ length C1 = pc.\nProof.\n  induction C; simpl; intros.\n  inversion H.\n  destruct pc. inversion H. exists (@nil instruction); exists (i :: C); auto. \n  destruct (IHC _ _ H) as [C1 [C2 [A B]]].\n  exists (a :: C1); exists C2; split. simpl; congruence. simpl; congruence.\nQed.\n\nRemark code_at_codeseq:\n  forall C pc i, code_at C pc = Some i -> codeseq_at C pc nil.\nProof.\n  intros. destruct (code_at_inv _ _ _ H) as [C1 [C2 [A B]]]. \n  subst. change C2 with (nil ++ C2). constructor. auto.\nQed.\n\nLemma match_config_skip:\n  forall C k m pc,\n  compile_cont C k pc ->\n  match_config C (SKIP, k, m) (pc, nil, m).\nProof.\n  intros C.\n  assert (forall k pc, compile_cont C k pc -> codeseq_at C pc nil).\n    induction 1.\n    eapply code_at_codeseq; eauto.\n    change (compile_com c) with (nil ++ compile_com c) in H. eauto with codeseq.\n    eapply code_at_codeseq; eauto.\n    eapply code_at_codeseq; eauto.\n  intros. constructor. simpl. eauto. simpl. rewrite plus_0_r; auto.\nQed.\n\n(** At long last, we can state and prove the right simulation diagram. *)\n\nLemma simulation_step:\n  forall C impstate1 impstate2 machstate1,\n  kstep impstate1 impstate2 ->\n  match_config C impstate1 machstate1 ->\n  exists machstate2,\n      (plus (transition C) machstate1 machstate2\n       \\/ (star (transition C) machstate1 machstate2 /\\ measure impstate2 < measure impstate1))\n   /\\ match_config C impstate2 machstate2.\nProof.\n  intros until machstate1; intros KSTEP MATCH. \n  inversion KSTEP; clear KSTEP; subst; inversion MATCH; clear MATCH; subst; simpl in *.\n\n- (* assign *)\n  econstructor; split.\n  left. eapply plus_right. eapply compile_aexp_correct; eauto with codeseq. \n  eapply trans_setvar; eauto with codeseq. \n  normalize. apply match_config_skip. auto.\n\n- (* seq *)\n  econstructor; split.\n  right; split. apply star_refl. omega. \n  normalize. constructor. eauto with codeseq. eapply ccont_seq; eauto with codeseq. \n\n- (* if true *)\n  set (code1 := compile_com c1) in *.\n  set (codeb := compile_bexp b false (length code1 + 1)) in *.\n  set (code2 := compile_com c2) in *.\n  econstructor; split.\n  right; split.\n  apply compile_bexp_correct with (b := b) (cond := false) (ofs := length code1 + 1).\n  eauto with codeseq.\n  omega.\n  rewrite H; simpl. fold codeb. normalize. constructor; eauto with codeseq. \n  eapply ccont_branch; eauto with codeseq. \n  change (S (length code2)) with (1 + length code2) in H5. normalize. auto.\n\n- (* if false *)\n  set (code1 := compile_com c1) in *.\n  set (codeb := compile_bexp b false (length code1 + 1)) in *.\n  set (code2 := compile_com c2) in *.\n  econstructor; split.\n  right; split.\n  apply compile_bexp_correct with (b := b) (cond := false) (ofs := length code1 + 1).\n  eauto with codeseq.\n  omega.\n  rewrite H; simpl. fold codeb. normalize. constructor; eauto with codeseq. \n  change (S (length code2)) with (1 + length code2) in H5. normalize. auto.\n\n- (* while true *)\n  set (codec := compile_com c) in *.\n  set (codeb := compile_bexp b false (length codec + 1)) in *.\n  econstructor; split.\n  right; split.\n  apply compile_bexp_correct with (b := b) (cond := false) (ofs := length codec + 1).\n  eauto with codeseq.\n  omega.\n  rewrite H; simpl. fold codeb. normalize. constructor; eauto with codeseq.\n  fold codec.\n  assert (PC: pc + length codeb + length codec + 1 - (length codeb + length codec + 1) = pc)\n      by omega.\n  eapply ccont_while; eauto with codeseq. rewrite PC; auto. rewrite PC.\n  simpl. normalize. auto.\n\n- (* while false *)\n  set (codec := compile_com c) in *.\n  set (codeb := compile_bexp b false (length codec + 1)) in *.\n  econstructor; split.\n  right; split.\n  apply compile_bexp_correct with (b := b) (cond := false) (ofs := length codec + 1).\n  eauto with codeseq.\n  generalize (com_size_nonzero c). omega. \n  rewrite H; simpl. fold codeb. normalize. apply match_config_skip. auto. \n\n- (* skip seq *)\n  normalize.\n  destruct (compile_cont_Kseq_inv _ _ _ _ st H4) as [pc' [X [Y Z]]].\n  econstructor; split.\n  right; split. eexact X. omega.\n  constructor; auto. \n\n- (* skip while *)\n  normalize.\n  destruct (compile_cont_Kwhile_inv _ _ _ _ _ st H4) as [pc' [X [Y Z]]].\n  econstructor; split.\n  left. eexact X. \n  constructor; auto.\nQed.\n\n(** Simulation diagrams such as [simulation_step] above imply semantic preservation\n  for terminating programs and for diverging programs.  We now develop a generic\n  proof of this fact that we can reuse later for other program transformations. *)\n\nSection SIMULATION_DIAGRAM.\n\n(** The generic proof is parameterized over the small-step semantics for the\n  source and target languages, and over an invariant between their states. *)\n\nVariable state1: Type.\t     (**r the type of configurations for the source language *)\nVariable step1: state1 -> state1 -> Prop.   (**r the small-step semantics for the source language *)\n\nVariable state2: Type.\t     (**r the type of configurations for the target language *)\nVariable step2: state2 -> state2 -> Prop.   (**r the small-step semantics for the target language *)\n\nVariable match_states: state1 -> state2 -> Prop.  (**r the invariant *)\n\nVariable measure: state1 -> nat.                  (**r the anti-stuttering measure *)\n\nHypothesis simulation:\n  forall S1 S1' S2,\n  step1 S1 S1' -> match_states S1 S2 ->\n  exists S2',\n    (plus step2 S2 S2' \\/ (star step2 S2 S2' /\\ measure S1' < measure S1))\n  /\\ match_states S1' S2'.\n\n(** We first extend the simulation to finite sequences of source transitions.\n  This will show semantic preservation for terminating programs. *)\n\nLemma simulation_star:\n  forall S1 S1', star step1 S1 S1' ->\n  forall S2, match_states S1 S2 ->\n  exists S2', star step2 S2 S2' /\\ match_states S1' S2'.\nProof.\n  induction 1; intros.\n- (* zero transition *)\n  exists S2; split. apply star_refl. auto.\n- (* one or more transitions *)\n  destruct (simulation _ _ _ H H1) as [S2' [P Q]].\n  destruct (IHstar _ Q) as [S2'' [U V]].\n  exists S2''; split. \n  eapply star_trans; eauto. destruct P. apply plus_star; auto. destruct H2; auto.\n  auto.\nQed.\n\n(** Turning to infinite sequences, we first show that the target program\n  can always make progress, while preserving the [match_states] relation,\n  if the source diverges.  The proof is an induction on the maximal number\n  [N] of stutterings the target can make before performing at least one transition. *)\n\nLemma simulation_infseq_productive:\n  forall N S1 S2,\n  measure S1 < N ->\n  infseq step1 S1 ->\n  match_states S1 S2 ->\n  exists S1', exists S2',\n      plus step2 S2 S2'\n   /\\ infseq step1 S1'\n   /\\ match_states S1' S2'.\nProof.\n  induction N; intros. \n- (* N = 0 *)\n  exfalso. omega.\n- (* N > 0 *)\n  inversion H0; clear H0; subst.\n  destruct (simulation _ _ _ H2 H1) as [S2' [P Q]].\n  destruct P.\n  + (* one or several transitions *)\n    exists b; exists S2'; auto.\n  + (* zero, one or several transitions *)\n    destruct H0. inversion H0; clear H0; subst.\n    * (* zero transitions *)\n      eapply IHN; eauto. omega.\n    * (* one or several transitions *)\n      exists b; exists S2'; split. eapply plus_left; eauto. auto.\nQed.\n\n(** It follows that the target performs infinitely many transitions if\n  started in a configuration that matches a diverging source configuration. *)\n\nLemma simulation_infseq:\n  forall S1 S2,\n  infseq step1 S1 ->\n  match_states S1 S2 ->\n  infseq step2 S2.\nProof.\n  intros. \n  apply infseq_coinduction_principle_2 with\n    (X := fun S2 => exists S1, infseq step1 S1 /\\ match_states S1 S2).\n  intros. destruct H1 as [S [A B]]. \n  destruct (simulation_infseq_productive (measure S + 1) S a) \n  as [S1' [S2' [P [Q R]]]].\n  omega. auto. auto.\n  exists S2'; split. auto. exists S1'; auto. \n  exists S1; auto.\nQed.\n\nEnd SIMULATION_DIAGRAM.\n\n(** We now apply these results to the Imp compiler.  We first obtain\n  an alternate proof of semantic preservation for terminating Imp programs. *)\n\nLemma match_config_initial:\n  forall c st,\n  match_config (compile_program c) (c, Kstop, st) (0, nil, st).\nProof.\n  intros. constructor.\n  change (compile_program c) with (nil ++ compile_com c ++ Ihalt :: nil). constructor. auto.\n  simpl. unfold compile_program. constructor. apply code_at_app. auto.\nQed.\n\nTheorem compile_program_correct_terminating_2:\n  forall c st st',\n  kterminates c st st' ->\n  mach_terminates (compile_program c) st st'.\nProof.\n  intros.\n  assert (exists machconf2, \n           star (transition (compile_program c)) (0, nil, st) machconf2\n           /\\ match_config (compile_program c) (SKIP, Kstop, st') machconf2).\n  eapply simulation_star; eauto. eapply simulation_step. apply match_config_initial.\n  destruct H0 as [machconf2 [STAR MS]]. \n  inversion MS; subst. simpl in *. normalize. \n  destruct (compile_cont_Kstop_inv _ _ st' H5) as [pc' [A B]].\n  red. exists pc'; split. auto. eapply star_trans; eauto.\nQed.\n\n(** More interestingly, we also prove semantic preservation for diverging\n  Imp programs. *)\n\nTheorem compile_program_correct_diverging:\n  forall c st,\n  kdiverges c st ->\n  mach_diverges (compile_program c) st.\nProof.\n  intros; red; intros. \n  eapply simulation_infseq with (match_states := match_config (compile_program c)); eauto.\n  eapply simulation_step. apply match_config_initial.\nQed.\n\n(** *** Mini-project (4 stars) *)\n\n(** Our compiler for arithmetic expressions implements a left-to-right\n  evaluation order: in [a1 + a2], [a1] is evaluated first, and its value\n  left on the stack; then [a2] is evaluated; then an [Iadd] instruction\n  is performed.  For commutative operators like [+] and [*], we\n  could just as well evaluate [a2] first, then [a1], then combine\n  their results.  \n\n  This can help producing more efficient code in terms of how much\n  stack space is required by the evaluation.  Consider the expression\n  [1 + (2 + (3 + ... (N-1 + N)))].  With left-to-right evaluation,\n  it uses [N+1] stack entries.  With right-to-left evaluation,\n  it uses only 2 stack entries.  \n\n  In this exercise, we explore the effect of different evaluation orders\n  on stack usage.  Let us first parameterize [compile_aexp] with\n  a heuristic function [ord] that, given the two arguments of a [+]\n  or [*] operator, decides whether to evaluate them left-to-right\n  or right-to-left: *)\n\nInductive eval_order : Type := LtoR | RtoL.\n\nFixpoint compile_aexp_gen (ord: aexp -> aexp -> eval_order) (a: aexp) : code :=\n  match a with\n  | ANum n => Iconst n :: nil\n  | AId v => Ivar v :: nil\n  | APlus a1 a2 =>\n      match ord a1 a2 with\n      | LtoR => compile_aexp_gen ord a1 ++ compile_aexp_gen ord a2 ++ Iadd :: nil\n      | RtoL => compile_aexp_gen ord a2 ++ compile_aexp_gen ord a1 ++ Iadd :: nil\n      end\n  | AMinus a1 a2 =>\n      compile_aexp_gen ord a1 ++ compile_aexp_gen ord a2 ++ Isub :: nil\n  | AMult a1 a2 =>\n      match ord a1 a2 with\n      | LtoR => compile_aexp_gen ord a1 ++ compile_aexp_gen ord a2 ++ Imul :: nil\n      | RtoL => compile_aexp_gen ord a2 ++ compile_aexp_gen ord a1 ++ Imul :: nil\n      end\n  end.\n\n(** First show that, whatever the [ord] heuristic is, the code generated\nby [compile_aexp_gen ord] is correct.  This is a simple extension of\nthe proof of [compile_aexp_correct]. *)\n\nLemma compile_aexp_gen_correct:\n  forall ord C st a pc stk,\n  codeseq_at C pc (compile_aexp_gen ord a) ->\n  star (transition C)\n       (pc, stk, st)\n       (pc + length (compile_aexp_gen ord a), aeval st a :: stk, st).\nProof.\n  induction a; simpl; intros.\n  (* FILL IN HERE *)\nAdmitted.\n\n(** Now, let us try to compute the minimum number of stack entries\n  needed to evaluate an expression, regardless of the strategy used. *)\n\nRequire Import Min Max.     (**r Libraries of lemmas about min and max *)\n\nFixpoint stack_needs (a: aexp) : nat :=\n  match a with\n  | ANum n => 1\n  | AId v => 1\n  | APlus a1 a2 =>\n      let n1 := stack_needs a1 in\n      let n2 := stack_needs a2 in\n      min (max n1 (n2 + 1)) (max n2 (n1 + 1))\n  | AMinus a1 a2 =>\n      let n1 := stack_needs a1 in\n      let n2 := stack_needs a2 in\n      max n1 (n2 + 1)\n  | AMult a1 a2 =>\n      let n1 := stack_needs a1 in\n      let n2 := stack_needs a2 in\n      min (max n1 (n2 + 1)) (max n2 (n1 + 1))\n  end.\n\n(** This definition is a variation on the Strahler numbering of a tree.\n  Here are some intuitions.  Consider [APlus a1 a2].  If we\n  evaluate [a1] then [a2], we will need at least [stack_needs a1]\n  space for evaluating [a1], then [stack_needs a2 + 1] for [a2]:\n  plus one, because during the evaluation of [a2], the value of [a1]\n  sits in the stack.  So, our space usage is the max of these two\n  quantities.  But we can also choose the other evaluation order,\n  so our space usage is the min of the two max corresponding to the\n  two possible evaluation orders. *)\n\n(** To show that [stack_needs] is the minimal stack size required,\n  we can define the stack usage (number of stack entries needed) of\n  a given strategy [ord], the show that it is at least [stack_needs]. *)\n\nFixpoint stack_usage (ord: aexp -> aexp -> eval_order) (a: aexp) : nat :=\n  match a with\n  | ANum n => 1\n  | AId v => 1\n  | APlus a1 a2 =>\n      match ord a1 a2 with\n      | LtoR => max (stack_usage ord a1) (stack_usage ord a2 + 1)\n      | RtoL => max (stack_usage ord a2) (stack_usage ord a1 + 1)\n      end\n  | AMinus a1 a2 =>\n      max (stack_usage ord a1) (stack_usage ord a2 + 1)\n  | AMult a1 a2 =>\n      match ord a1 a2 with\n      | LtoR => max (stack_usage ord a1) (stack_usage ord a2 + 1)\n      | RtoL => max (stack_usage ord a2) (stack_usage ord a1 + 1)\n      end\n  end.\n\nLemma stack_needs_is_optimal:\n  forall ord a, stack_needs a <= stack_usage ord a.\nProof.\n  (* FILL IN HERE *)\nAdmitted.\n\n(** Useful tip: the tactic [zify; omega] works very well to prove\n    arithmetic properties involving min and max operators. *)\n\n(** An optimal strategy (with respect to stack usage) is to always\n  compute the biggest subexpression first: *)\n\nDefinition optimal_ord (a1 a2: aexp) :=\n  if leb (stack_needs a2) (stack_needs a1) then LtoR else RtoL.\n\nDefinition compile_aexp_optimal (a: aexp) : code :=\n  compile_aexp_gen optimal_ord a.\n\n(** The intuition is simple: if one of the arguments, say [a1], has\n  stack needs strictly less than the other, say [a2], evaluating [a1]\n  after [a2], with [a2]'s value as additional entry on the stack,\n  will use no more stack space than evaluating [a2].  So, evaluating\n  [a1 + a2] can be done with no extra space than evaluating just [a2].\n  This would not be the case if we started with [a1], then evaluated [a2]:\n  in this case, one more stack slot would be needed. \n\n  If both arguments have the same stack needs, the two evaluation\n  orders use exactly the same amount of space, so it does not matter\n  which one we choose. *)\n\n(** We can show the optimality of the strategy by observing that \n  its stack usage is the minimum predicted by [stack_needs]. *)\n\nLemma stack_usage_optimal_ord:\n  forall a, stack_usage optimal_ord a = stack_needs a.\nProof.\n  (* FILL IN HERE *)\nAdmitted.  \n\n(** So far, we've reasoned informally on the stack usage of a particular\n  evaluation strategy.  Now, let us formally connect this reasoning with the\n  execution of the compiled code.  First, we need to instrument the\n  virtual machine so that it monitors its stack usage and goes wrong\n  if the stack size goes over a given maximum [maxstack]. *)\n\nInductive checked_transition (C: code) (maxstack: nat) : configuration -> configuration -> Prop :=\n  | ctrans: forall pc stk s pc' stk' s',\n      transition C (pc, stk, s) (pc', stk', s') ->\n      length stk' <= maxstack ->\n      checked_transition C maxstack (pc, stk, s) (pc', stk', s').\n\n(** Now, we can state and prove the fact that the compiled code for\n  expression [a] with respect to a strategy [ord] execute safely\n  if at least [stack_usage ord a] stack entries are available. *)\n\nLemma compile_aexp_gen_safe:\n  forall ord C maxstack st a pc stk,\n  codeseq_at C pc (compile_aexp_gen ord a) ->\n  length stk + stack_usage ord a <= maxstack ->\n  star (checked_transition C maxstack)\n       (pc, stk, st)\n       (pc + length (compile_aexp_gen ord a), aeval st a :: stk, st).\nProof.\n  induction a; simpl; intros.\nAdmitted.\n\n(** Moreover, the size [stack_usage ord a] is tight, in that there exists\n  a point in the execution of the compiled code for [a] where the stack\n  is at least that big. *)\n\nLemma stack_usage_reached:\n  forall ord C st a pc stk,\n  codeseq_at C pc (compile_aexp_gen ord a) ->\n  exists pc', exists stk',\n  star (transition C) (pc, stk, st) (pc', stk', st)\n  /\\ length stk' >= length stk + stack_usage ord a.\nProof.\n  induction a; simpl; intros.\n  (* FILL IN HERE *)\nAdmitted.\n\n(** **** Full project (5 stars) *)\n\nModule StorelessMachine.\n\n(** The purpose of this project is to retarget the IMP compiler to a\n  different, simpler virtual machine that has no store, just a stack\n  that also supports direct accesses, i.e. reading or modifying the\n  N-th entry of the stack.  Here is the instruction set of the machine:\n*)\n\nInductive instruction: Type :=\n  | Iconst(n: nat)                 (**r push integer [n] on stack *)\n  | Iget(n: nat)                   (**r push the value of the [n]-th stack slot *)\n  | Iset(n: nat)                   (**r pop an integer, assign it to the [n]-th stack slot *)\n  | Iadd                           (**r pop [n2], pop [n1], push back [n1+n2] *)\n  | Isub                           (**r pop [n2], pop [n1], push back [n1-n2] *)\n  | Imul                           (**r pop [n2], pop [n1], push back [n1*n2] *)\n  | Ibranch_forward(ofs: nat)      (**r skip [ofs] instructions forward *)\n  | Ibranch_backward(ofs: nat)     (**r skip [ofs] instructions backward *)\n  | Ibeq(ofs: nat)                 (**r pop [n2], pop [n1], skip [ofs] forward if [n1=n2] *)\n  | Ibne(ofs: nat)                 (**r pop [n2], pop [n1], skip [ofs] forward if [n1<>n2] *)\n  | Ible(ofs: nat)                 (**r pop [n2], pop [n1], skip [ofs] forward if [n1<=n2] *)\n  | Ibgt(ofs: nat)                 (**r pop [n2], pop [n1], skip [ofs] forward if [n1>n2] *)\n  | Ihalt.                         (**r terminate execution successfully *)\n\n(** The only difference with the original virtual machine is that the\n  [Ivar] and [Isetvar] instructions (to access the store by\n  identifier) are gone and replaced by [Iget] and [Iset] instructions\n  (to access the stack by position). *)\n\nDefinition code := list instruction.\nDefinition stack := list nat.\nDefinition configuration := (nat * stack)%type.\n\nFixpoint code_at (C: code) (pc: nat) : option instruction :=\n  match C, pc with\n  | nil, _ => None\n  | i :: C', O => Some i\n  | i :: C', S pc' => code_at C' pc'\n  end.\n\n(** To give semantics to the [Iget] and [Iset] instructions, start by\n  defining two stack-manipulating functions, such that\n<<\n     get_nth_slot (v0 :: ... :: vN :: ...) N = Some vN\n     set_nth_slot (v0 :: ... :: vN :: ...) N v' = Some (v0 :: ... :: v' :: ...)\n>>\n*)\n\nDefinition get_nth_slot (s: stack) (n: nat) : option nat :=\n  None. (* FILL HERE *)\n\nFixpoint set_nth_slot (s: stack) (n: nat) (v: nat) : option stack :=\n  None. (* FILL HERE *)\n\n(** Then, the semantics of the machine is given by the following transition\n  relation.  Note that machine states are just pairs of a program counter\n  and a stack.  Note also that many transitions are exactly those of\n  the original machine after erasing the store component of the state. *)\n\nInductive transition (C: code): configuration -> configuration -> Prop :=\n  | trans_const: forall pc stk n,\n      code_at C pc = Some(Iconst n) ->\n      transition C (pc, stk) (pc + 1, n :: stk)\n  | trans_get: forall pc stk n v,\n      code_at C pc = Some(Iget n) ->\n      get_nth_slot stk n = Some v ->\n      transition C (pc, stk) (pc + 1, v :: stk)\n  | trans_set: forall pc stk n v stk',\n      code_at C pc = Some(Iset n) ->\n      set_nth_slot stk n v = Some stk' ->\n      transition C (pc, v :: stk) (pc + 1, stk')\n  | trans_add: forall pc stk n1 n2,\n      code_at C pc = Some(Iadd) ->\n      transition C (pc, n2 :: n1 :: stk) (pc + 1, (n1 + n2) :: stk)\n  | trans_sub: forall pc stk n1 n2,\n      code_at C pc = Some(Isub) ->\n      transition C (pc, n2 :: n1 :: stk) (pc + 1, (n1 - n2) :: stk)\n  | trans_mul: forall pc stk n1 n2,\n      code_at C pc = Some(Imul) ->\n      transition C (pc, n2 :: n1 :: stk) (pc + 1, (n1 * n2) :: stk)\n  | trans_branch_forward: forall pc stk ofs pc',\n      code_at C pc = Some(Ibranch_forward ofs) ->\n      pc' = pc + 1 + ofs ->\n      transition C (pc, stk) (pc', stk)\n  | trans_branch_backward: forall pc stk ofs pc',\n      code_at C pc = Some(Ibranch_backward ofs) ->\n      pc' = pc + 1 - ofs ->\n      transition C (pc, stk) (pc', stk)\n  | trans_beq: forall pc stk ofs n1 n2 pc',\n      code_at C pc = Some(Ibeq ofs) ->\n      pc' = (if beq_nat n1 n2 then pc + 1 + ofs else pc + 1) ->\n      transition C (pc, n2 :: n1 :: stk) (pc', stk)\n  | trans_bne: forall pc stk ofs n1 n2 pc',\n      code_at C pc = Some(Ibne ofs) ->\n      pc' = (if beq_nat n1 n2 then pc + 1 else pc + 1 + ofs) ->\n      transition C (pc, n2 :: n1 :: stk) (pc', stk)\n  | trans_ble: forall pc stk ofs n1 n2 pc',\n      code_at C pc = Some(Ible ofs) ->\n      pc' = (if leb n1 n2 then pc + 1 + ofs else pc + 1) ->\n      transition C (pc, n2 :: n1 :: stk) (pc', stk)\n  | trans_bgt: forall pc stk ofs n1 n2 pc',\n      code_at C pc = Some(Ibgt ofs) ->\n      pc' = (if leb n1 n2 then pc + 1 else pc + 1 + ofs) ->\n      transition C (pc, n2 :: n1 :: stk) (pc', stk).\n\nDefinition mach_terminates (C: code) (stk_init stk_fin: stack) :=\n  exists pc,\n  code_at C pc = Some Ihalt /\\\n  star (transition C) (0, stk_init) (pc, stk_fin).\n\n(** Now it's your turn: define a compilation scheme from IMP programs\n    to machine code and prove its correctness w.r.t. terminating executions,\n    as stated below. *)\n\nDefinition compile_program (c: com) : code := nil. (* FILL HERE *)\n\nTheorem compile_program_correct_terminating:\n  forall c st,\n  c / empty_state \\\\ st ->\n  exists stk,\n     mach_terminates (compile_program c) nil stk\n  /\\ True.\nProof.\n  (* Have fun! *)\nAdmitted.\n\n(** The [True] above is to be replaced by some informative relation between\n  the final stack [stk] and the final store [st]. *)\n\n(** Some hints to get you started.  Clearly, we need to use a portion of\n  the stack to hold the current values for the program variables.  It may\n  seem impossible to represent a store (a function from identifiers to values,\n  giving gives values to infinitely many variables) as a stack (a finite\n  list of values).  However, only the variables that are ever assigned to\n  within the program need to be associated with a stack slot: all\n  other variables keep their initial value of 0 throughout the program\n  execution. *)\n\n(**  Hence, the first order of business is to construct a list of\n  variables that are ever assigned in the program, and, from this\n  list, to assign a position in the stack for every such variable.\n  For example, if the list of assigned variables is [[\"x\";\"y\";\"z\"]]\n  we could say that the value of [\"x\"] is at the top of the stack,\n  the value of [\"y\"] one slot below, and that of [\"z\"] two slots below.\n  Those offsets need adjusting during the evaluation of expressions,\n  because intermediate results are pushed on the stack on top of the\n  values of variables. *)\n\n(**  Using this information, the compilation of an expression [AId id] is\n  either [Iconst 0] if the variable is not assigned in the program,\n  or, [Iget N] otherwise, for a stack distance [N] that reflects the\n  stack position of variable [id]. *)\n\n(** To state and prove semantic preservation for the compilation functions,\n  you will need a predicate [agree st stk] that relates an IMP store [st]\n  with a machine stack [stk].  Typically, it will say that\n- [st x = 0] for all non-assigned variables [x]\n- [get_nth_slot stk N = Some (st x)] if [N] is the stack offset for variable [x]\n\n  The predicate [agree st stk] acts both as a pre- and a post-condition, e.g.\n\n<<\nLemma compile_com_correct_terminating:\n  forall C st c st',\n  c / st \\\\ st' ->\n  forall stk pc,\n  codeseq_at C pc (compile_com c) ->\n  agree st stk ->\n  exists stk',\n     star (transition C) (pc, stk) (pc + length (compile_com c), stk')\n  /\\ agree st' stk'.\n>>\n*)\n\nEnd StorelessMachine.\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/compiler/Compiler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6531504835788359}}
{"text": "Require Import Coq.Classes.EquivDec.\nRequire Import RamifyCoq.lib.List_ext.\n\nSection FIND_NOT_IN.\nContext {V: Type}.\nContext {EDV: EqDec V eq}.\n \nFixpoint findNotIn (l1 l2 l3: list V) : (option V * (list V * list V)) :=\n  match l1 with\n    | nil => (None, (nil, nil))\n    | x :: l => if (in_dec equiv_dec x l2) then findNotIn l l2 (x :: l3) else (Some x, (rev l3, l))\n  end.\n \nLemma find_not_in_none: forall l1 l2 l3, fst (findNotIn l1 l2 l3) = None -> Forall (fun m => In m l2) l1.\nProof.\n  induction l1; intros. apply Forall_nil. simpl in H. destruct (in_dec equiv_dec a l2).\n  apply Forall_cons. auto. apply IHl1 with (a :: l3); auto. inversion H.\nQed.\n \nLemma find_not_in_some_explicit:\n  forall l1 l2 l3 x li1 li2,\n    findNotIn l1 l2 l3 = (Some x, (li1, li2)) -> (Forall (fun m => In m l2) l3) ->\n    (~ In x li1) /\\ (~ In x l2) /\\ exists l4, li1 = rev l3 ++ l4 /\\ Forall (fun m => In m l2) l4 /\\ l1 = l4 ++ x :: li2.\nProof.\n  induction l1; intros; simpl in H. inversion H. destruct (in_dec equiv_dec a l2).\n  assert (Forall (fun m : V => In m l2) (a :: l3)) by (apply Forall_cons; auto).\n  specialize (IHl1 l2 (a :: l3) x li1 li2 H H1). destruct IHl1 as [? [? [l4 [? [? ?]]]]]. split; auto. split; auto.\n  exists (a :: l4). repeat split; auto. simpl in H4. rewrite <- app_assoc in H4. rewrite <- app_comm_cons in H4.\n  rewrite app_nil_l in H4. auto. rewrite H6; apply app_comm_cons. inversion H. split. intro; apply n.\n  rewrite Forall_forall in H0. apply (H0 a). rewrite H2. rewrite in_rev. auto. split. rewrite <- H2. auto.\n  exists nil. repeat split; auto. rewrite app_nil_r. auto.\nQed.\n \nLemma find_not_in_some:\n  forall l1 l2 x li1 li2,\n    findNotIn l1 l2 nil = (Some x, (li1, li2)) ->\n    Forall (fun m => In m l2) li1 /\\ l1 = li1 ++ x :: li2 /\\ ~ In x li1 /\\ ~ In x l2.\nProof.\n  intros. assert (Forall (fun m : V => In m l2) nil) by apply Forall_nil.\n  destruct (find_not_in_some_explicit l1 l2 nil x li1 li2 H H0). destruct H2 as [? [l4 [? [? ?]]]].\n  simpl in H3. rewrite H3 in *. repeat split; auto.\nQed.\n \nEnd FIND_NOT_IN.\n\n", "meta": {"author": "johndoe20190406", "repo": "RamifyCoq", "sha": "72fb538b40ee8ea641e4bf5fe6cd232756d0929c", "save_path": "github-repos/coq/johndoe20190406-RamifyCoq", "path": "github-repos/coq/johndoe20190406-RamifyCoq/RamifyCoq-72fb538b40ee8ea641e4bf5fe6cd232756d0929c/graph/find_not_in.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388209992571, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6531467604727369}}
{"text": "Require Import Undecidability.Shared.Libs.PSL.Base.\nRequire Import Lia. \nFrom Undecidability.L Require Import L_facts.\nRequire Import Undecidability.Shared.ListAutomation.\nFrom Complexity.Libs.CookPrelim Require Export Tactics.\n\n(** * Various preliminaries for the TM -> SAT part of the Cook-Levin Theorem *)\n\n(** Results regarding lists *)\nSection tabulate.\n  Variable (A : Type).\n  Fixpoint tabulate (f : nat -> A) (n : nat): list A := match n with 0 => []\n                                                                      | S n => tabulate f n ++ [f n]\n                                                                end. \n\n  Lemma tabulate_length (f : nat -> A)  (n : nat) : |tabulate f n| = n. \n  Proof. \n    induction n; cbn.\n    - reflexivity. \n    - rewrite app_length, IHn. cbn;lia. \n  Qed. \n\n  Lemma tabulate_nth (f : nat -> A) (n : nat) : forall k, k < n -> nth_error (tabulate f n) k = Some (f k). \n  Proof.\n    intros. induction n. \n    - lia. \n    - destruct (Nat.eqb k n) eqn:H1; dec_bool.\n      + rewrite H1 in *; clear H1. cbn. rewrite nth_error_app2, tabulate_length. 2: specialize (tabulate_length f n); lia. \n        rewrite Nat.sub_diag; cbn; reflexivity.  \n      + assert (k < n) by lia. clear H1 H. cbn. rewrite nth_error_app1. 2: now rewrite tabulate_length. \n        now apply IHn. \n  Qed. \n\n  Lemma tabulate_In (f : nat -> A) (n : nat) : forall a, a el tabulate f n <-> exists k, k < n /\\ f k = a. \n  Proof.\n    specialize (@tabulate_nth f n) as H1. \n    intros a. split.\n    - intros (n0 & H2)%In_nth_error.\n      assert (n0 < n). { rewrite <- tabulate_length with (f := f). now apply nth_error_Some_lt with (x:=a). }\n      exists n0. split; [assumption|]. \n      specialize (H1 n0 H). congruence. \n    - intros (k & H2 & H3). specialize (H1 k H2).  \n      rewrite <- H3; eapply nth_error_In, H1. \n  Qed. \nEnd tabulate. \n\nSection subsequence.\n  Variable (X : Type).\n  Definition subsequence (A B : list X) := exists C D, B = C ++ A ++ D.\n  Notation \"A 'subs' B\" := (subsequence A B)(at level 70).\n\n  Lemma subsequence_incl (A B : list X) : A subs B -> incl A B.\n  Proof. \n    induction B. \n    - unfold subsequence. destruct A; cbn; try firstorder.\n      intros (C & D & H). destruct C; cbn in H; congruence.   \n    - intros (C & D & H). intros x xel. destruct C. \n      + cbn in H. rewrite H. firstorder. \n      + cbn in H. assert (x0 = a) as -> by congruence.  \n        right. apply IHB; [|assumption]. exists C,D. congruence. \n  Qed.\nEnd subsequence. \n\n(* Lemma dupfree_nthe (X : Type) (l : list X) : dupfree l <-> forall i j a b, nth_error l i = Some a -> nth_error l j = Some b -> i <> j -> a <> b. *)\n(* use NoDup_nth_error *)\n\nSection remove.\n  Variable (X : Type).\n  Context (eqdec : (forall x y: X, dec (x = y))).\n  Lemma in_remove_iff (l : list X) (a b : X) : a el remove eqdec b l <-> a el l /\\ a <> b.\n  Proof.\n    revert a. induction l; intros; cbn.\n    - tauto. \n    - destruct (eqdec b a).\n      + split; [firstorder | ]. intros [[-> | H1] H2]; [congruence|]. now apply IHl. \n      + split; [ firstorder; congruence | firstorder ].\n  Qed. \n\n  Lemma remove_length (l : list X) (a : X) : |remove eqdec a l| <= |l|.\n  Proof.\n    induction l; cbn.\n    - lia.\n    - destruct eqdec; cbn; lia. \n  Qed. \n\n  Lemma remove_length_el (l : list X) (a : X) : a el l -> |remove eqdec a l| < |l|.\n  Proof.\n    induction l.\n    - intros [].\n    - intros [-> | H1].\n      + cbn. destruct (eqdec a a); [specialize (remove_length l a); lia | congruence].\n      + cbn. destruct (eqdec a a0); [specialize (remove_length l a); lia | cbn; firstorder nia ].  \n  Qed. \nEnd remove.\n\nProposition map_dupfree (X Y : Type) (f : X -> Y) (A : list X) : dupfree (map f A) -> dupfree A.\nProof. \n  remember (map f A) as B. intros H1. revert A HeqB. induction H1; intros B HeqB.\n  - destruct B; cbn in HeqB; [constructor | congruence].\n  - destruct B; cbn in HeqB; [congruence | ].\n    inv HeqB. constructor. \n    + rewrite in_map_iff in H. contradict H. eauto.\n    + now apply IHNoDup. \nQed. \n\nRequire Import Lia.\n(*Require Template.utils.*)\nFrom Undecidability.Shared.Libs.PSL Require Export FiniteTypes.FinTypes FiniteTypes.BasicFinTypes FiniteTypes.CompoundFinTypes Retracts Inhabited Base Vectors.Vectors FiniteTypes. \nRequire Export smpl.Smpl.\nFrom Undecidability.Shared Require Import Prelim.\n\nFrom Undecidability.L Require Import Util.L_facts.\nFrom Undecidability.L.Tactics Require Import Lrewrite.\n\n\n(*option monad in order to ease notation *)\nDefinition optReturn := @Some.\nDefinition optBind {X Y : Type} (x : option X) (f : X -> option Y) :=\n  match x with\n  | None => None\n  | Some x => f x\n  end. \n\n(*notations from https://pdp7.org/blog/2011/01/the-maybe-monad-in-coq/ *)\nNotation \"A >>= F\" := (optBind A F) (at level 40, left associativity).\nNotation \"'do' X <- A ; B\" := (optBind A (fun X => B)) (at level 200, X name, A at level 100, B at level 200).\n\n\n(* involutions *)\nDefinition involution (X : Type) (f : X -> X) := forall (x : X), f (f x) = x. \n\nLemma map_involution (X : Type)(f : X -> X) : involution f -> involution (map f). \nProof. \n  intros. intros l. rewrite map_map. setoid_rewrite H. now rewrite map_id. \nQed. \n\nLemma involution_invert_eqn (X : Type) (f : X -> X) : involution f -> forall a b, f a = f b -> a = b. \nProof. \n  intros. enough (f (f a) = f(f b)). { now rewrite  !H in H1. } now rewrite H0. \nQed. \n\nLemma involution_invert_eqn2 (X : Type) (f : X -> X) : involution f -> forall a b, f a = b -> a = f b. \nProof. \n  intros. rewrite <- (H a). now apply involution_invert_eqn with (f := f). \nQed. \n\nSmpl Create involution.\nLtac involution_simpl := smpl involution; repeat (involution_simpl).\n\nSmpl Add (apply map_involution) : involution.\n\nLemma rev_involution (X : Type): involution (@rev X).  \nProof. \n  unfold involution. apply rev_involutive. \nQed. \n\nSmpl Add (apply rev_involution) : involution. \n\nDefinition prefix (X : Type) (a b : list X) := exists b', b = a ++ b'.\nDefinition substring (X : Type) (a b : list X) := exists b1 b2, b = b1 ++ a ++ b2. \n\nLemma map_skipn (A B : Type) (f : A -> B) (l : list A) (n : nat) : map f (skipn n l) = skipn n (map f l). \nProof. \n  induction n as [ | n] in l |-*; cbn; [reflexivity | destruct l as [ | x l]]; cbn; firstorder. \nQed.\n\nLemma skipn_add (X : Type) (xs vs: list X) (i j : nat) : length vs = j -> skipn (j + i) (vs ++ xs) = skipn i xs. \nProof. \n  revert vs; induction j; intros. \n  - inv_list. now cbn. \n  - inv_list. cbn. apply IHj. cbn in H; congruence.\nQed. \n\nLemma skipn_app2 (X : Type) i (a b c : list X): c <> [] -> skipn i a = c -> skipn i (a ++ b) = c ++ b. \nProof.\n  intros H; revert i; induction a; intros. \n  - destruct i; cbn in H0; congruence. \n  - destruct i; cbn in H0.\n    + cbn. now rewrite <- H0. \n    + cbn. now apply IHa. \nQed. \n\nLemma skipn_app3 (X : Type) i (a b : list X) : i <= |a| -> exists a', skipn i (a ++ b) = a' ++ b /\\ a = firstn i a ++ a'. \nProof. \n  intros. exists (skipn i a). split.\n  + destruct (nat_eq_dec i (|a|)). \n    - rewrite skipn_app. 2: apply e. rewrite skipn_all2. 2: lia. now cbn. \n    - apply skipn_app2.\n      * enough (|skipn i a| <> 0) by (destruct skipn; cbn in *; congruence). rewrite skipn_length. lia. \n      * reflexivity. \n  + now rewrite firstn_skipn. \nQed.\n\nLemma firstn_skipn_rev (X : Type) i (h : list X) : firstn i h = rev (skipn (|h| - i) (rev h)). \nProof. \n  rewrite <- (firstn_skipn i h) at 3. \n  rewrite rev_app_distr.\n  rewrite skipn_app. \n  - now rewrite rev_involution.\n  - rewrite rev_length. now rewrite skipn_length.\nQed. \n\nLemma skipn_firstn_rev (X : Type) i (h : list X) : skipn i h = rev (firstn (|h| - i) (rev h)). \nProof. \n  intros. \n  destruct (le_lt_dec i (|h|)). \n  - rewrite firstn_skipn_rev. \n    rewrite !rev_involution.\n    rewrite rev_length.\n    replace ((|h|) - (|h| - i)) with i by  lia. easy. \n  - specialize (skipn_length i h) as H1. assert (|skipn i h| = 0) by lia. \n    specialize (firstn_le_length (|h| - i) (rev h)) as H2. assert (|firstn (|h| - i) (rev h)| = 0)  as H3 by lia. \n    destruct skipn, firstn; cbn in *; try congruence. \nQed. \n\nLemma map_firstn (X Y : Type) i (h : list X) (f : X -> Y) : map f (firstn i h) = firstn i (map f h). \nProof.\n  revert i; induction h; intros; cbn. \n  - now rewrite !firstn_nil. \n  - destruct i; cbn; [reflexivity | now rewrite IHh].\nQed.\n\n\nLemma length_app_decompose (X : Type) (a : list X) i j : length a = i + j -> exists a1 a2, a = a1 ++ a2 /\\ length a1 = i /\\ length a2 = j. \nProof. \n  revert a. \n  induction i. \n  - cbn. intros. now exists [], a. \n  - cbn. intros. \ninv_list. assert (|a| = i + j) by lia. destruct (IHi a H0) as (a1 & a2 & H2 & H3). \n    exists (x :: a1), a2. rewrite H2; cbn. firstorder. \nQed. \n\n\nInductive relpowerRev (X : Type) (R : X -> X -> Prop) : nat -> X -> X -> Prop :=\n| relpowerRevB x : relpowerRev R 0 x x\n| relpowerRevS x y y' n: relpowerRev R n x y -> R y y' -> relpowerRev R (S n) x y'. \n#[export]\nHint Constructors relpowerRev : core. \n\nInductive relpower (A : Type) (R : A -> A -> Prop) : nat -> A -> A -> Prop :=\n| relpowerB (a : A) : relpower R 0 a a\n| relpowerS (a b c : A) n : R a b -> relpower R n b c -> relpower R (S n) a c. \n#[export]\nHint Constructors relpower : core. \n\nLemma relpower_trans A R n m (x y z : A) : relpower R n x y -> relpower R m y z -> relpower R (n + m) x z.\nProof. \n  induction 1. \n  - now cbn. \n  - intros. apply relpowerS with (b := b). assumption. now apply IHrelpower. \nQed. \n\nLemma relpower_monotonous (X : Type) (R1 R2 : X -> X -> Prop) : (forall a b, R1 a b -> R2 a b) -> forall n a b, relpower R1 n a b -> relpower R2 n a b.\nProof. \n  intros H1 n a b. induction 1. \n  - eauto. \n  - apply H1 in H. eauto. \nQed.\n\nLemma relpower_congruent (X : Type) (R R': X -> X -> Prop) :\n  (forall x y, R x y <-> R' x y) -> forall n x y, relpower R n x y <-> relpower R' n x y. \nProof. \n  intros H. induction n. \n  - split; intros H0; inv H0; eauto. \n  - split; intros H0; inv H0.\n    + apply H in H2. apply IHn in H3. eauto. \n    + apply H in H2. apply IHn in H3. eauto. \nQed. \n\nLemma relpowerRev_trans (X : Type) (R : X -> X -> Prop) n m x y z : relpowerRev R n x y -> relpowerRev R m y z -> relpowerRev R (n + m) x z.\nProof. \n  rewrite Nat.add_comm. induction 2; cbn; eauto. \nQed. \n\nLemma relpower_relpowerRev (X : Type) (R : X -> X -> Prop) n x y : relpower R n x y <-> relpowerRev R n x y.\nProof. \n  split; induction 1; eauto. \n  - replace (S n) with (1 + n) by lia. eauto using relpowerRev_trans. \n  - replace (S n) with (n + 1) by lia. eauto using relpower_trans. \nQed. \n\nLemma relpower_add_split (X : Type) (R : X -> X -> Prop) n m x y: relpower R (n + m) x y -> exists z, relpower R n x z /\\ relpower R m z y.\nProof. \n  revert x y. induction n; intros. \n  - cbn in H. eauto. \n  - inv H. apply IHn in H2 as (z & H3 & H4). exists z. eauto.\nQed. \n\nNotation injective := FinFun.Injective.\n\nLemma getPosition_map (X Y : eqType) (f : X -> Y) (l : list X) (x : X) : injective f -> getPosition (map f l) (f x) = getPosition l x. \nProof.\n  intros.\n  induction l; cbn. \n  - reflexivity. \n  - destruct Dec; destruct Dec; try congruence.\n    now apply H in e.\nQed. \n\nLemma getPosition_app1 (X : eqType) (A B : list X) x k : k < |A| -> getPosition A x = k -> getPosition (A ++ B) x = k.\nProof.\n  revert k. induction A; intros; cbn in *.\n  - lia. \n  - destruct Dec; [assumption | destruct k; [ lia | erewrite IHA]]. \n    + reflexivity. \n    + lia. \n    + easy. \nQed. \n\nLemma getPosition_app2 (X : eqType) (A B : list X) x k : k < |B| -> not (x el A) -> getPosition B x = k -> getPosition (A ++ B) x = |A| + k. \nProof. \n  revert k. induction A; intros; cbn in *. \n  - apply H1. \n  - destruct Dec; [ exfalso ; auto | ]. \n    erewrite IHA; eauto. \nQed.\n\nLemma getPosition_prodLists (X Y : eqType) (A : list X) (B : list Y) x1 x2 k1 k2 : getPosition A x1 = k1 -> k1 < |A| -> getPosition B x2 = k2 -> k2 < |B| -> getPosition (list_prod A B) (x1, x2) = (k1 * |B|) + k2. \nProof. \n  revert k1. induction A; intros; cbn in *. \n  - lia. \n  - destruct k1. \n    + destruct Dec; [ | congruence].\n      rewrite getPosition_app1 with (k := k2); [reflexivity | now rewrite map_length| ].\n      rewrite e; now rewrite getPosition_map. \n    + destruct Dec; [ congruence | ]. \n      rewrite getPosition_app2 with (k := (k1 * |B|) + k2). \n      * rewrite map_length. lia. \n      * setoid_rewrite prod_length. nia. \n      * intros (? & ? &?)%in_map_iff. congruence. \n      * apply IHA; eauto. now apply Nat.succ_lt_mono.  \nQed. \n\nFixpoint filterSome (X : Type) (l : list (option X)) := match l with\n                                                        | [] => []\n                                                        | (Some x :: l) => x :: filterSome l\n                                                        | None :: l => filterSome l\n                                                        end. \n\nLemma in_filterSome_iff (X : Type) (l : list (option X)) a:\n  a el filterSome l <-> Some a el l.\nProof.\n  induction l as [ | []]; cbn.  \n  - tauto.\n  - split.\n    + intros [-> | H]; [eauto | right; now apply IHl]. \n    + intros [H1 | H]; [eauto | ]. inv H1. \n      * eauto. \n      * right; now apply IHl. \n  - rewrite IHl. split; intros H; [ eauto | now destruct H]. \nQed. \n\n(*an actually usable version of the lemma without useless bool2Prop stuff *)\nLemma in_filter_iff (X : Type) (x : X) (p : X -> bool) (A : list X): x el filter p A <-> x el A /\\ p x = true. \nProof. \n  induction A; cbn. \n  - tauto. \n  - destruct (p a) eqn:H1.\n    + cbn. rewrite IHA. split; [intros [-> | [H2 H3]]; tauto | tauto ]. \n    + rewrite IHA. split; [tauto | intros [[-> | H2] H3]; [congruence | tauto] ]. \nQed.\n\n\nLemma nth_error_nth (X : Type) x (l : list X) n : nth_error l n = Some x -> nth n l x = x.  \nProof. \n  revert n; induction l; intros; cbn. \n  - now destruct n. \n  - destruct n; cbn in H.\n    * congruence. \n    * now apply IHl. \nQed.\n\nLemma nth_error_nth' (X : Type) x y (l : list X) n : nth_error l n = Some x -> nth n l y = x.\nProof. \n  revert n; induction l; intros; cbn. \n  - now destruct n. \n  - destruct n; cbn in H.\n    * congruence. \n    * now apply IHl. \nQed.\n\nLemma nth_error_map (A B : Type) (f : A -> B) (n : nat) (l : list A) : nth_error (map f l) n = option_map f (nth_error l n). \nProof. \n  induction n as [ | n] in l |-* ; destruct l as [ | x l]; cbn; congruence. \nQed.\n\nLemma nth_error_Some_length (A : Type) (l : list A) (n : nat) (v : A) : nth_error l n = Some v -> n < |l|.\nProof.\n  induction l as [ | x l IH] in n |-*; destruct n as [ | n]; cbn; try congruence. lia. intros H%IH; lia.\nQed.\n\nLemma In_explicit (X : Type) (x : X) (l : list X) :\n  x el l <-> exists s1 s2, l = s1 ++ [x] ++ s2. \nProof. \n  induction l; cbn. \n  - split; [tauto | intros (s1 & s2 & H)].\n    destruct s1; cbn in H; congruence. \n  - split. \n    + intros [-> | (s1 & s2 & ->)%IHl]. \n      * exists [], l. eauto. \n      * exists (a :: s1), s2; eauto. \n    + intros ([] & s2 & H). \n      * inv H. eauto. \n      * inv H. right; apply IHl.\n        exists l0, s2. eauto. \nQed. \n\nLemma list_length_split1 (X : Type) (s : list X) n : n <= |s| -> exists s1 s2, |s1| = n /\\ |s2| = |s| - n /\\ s = s1 ++ s2. \nProof. \n  revert s. induction n; intros. \n  - exists [], s. cbn; rewrite Nat.sub_0_r. eauto. \n  - destruct s; cbn in H; [lia | ]. assert (n <= |s|) as H' by lia. \n    apply IHn in H' as (s1 & s2 & H1 & H2 & ->). \n    exists (x::s1), s2. cbn. eauto. \nQed. \n\nLemma list_length_split2 (X : Type) (s : list X) n : n <= |s| -> exists s1 s2, |s1| = |s| - n /\\ |s2| = n /\\ s = s1 ++ s2. \nProof. \n  intros. assert (|s| - n <= |s|) as H' by lia. \n  specialize (list_length_split1 H') as (s1 & s2 & H1 & H2 & ->). \n  exists s1, s2. \n  rewrite app_length in *.\n  repeat split; [lia | lia].\nQed. \n\nLemma app_eq_length (X : Type) (s1 s2 w1 w2 : list X) : |s1| = |w1| -> s1 ++ s2 = w1 ++ w2 -> s1 = w1 /\\ s2 = w2. \nProof.\n  intros. revert w1 H H0. induction s1; cbn in *; intros. \n  - destruct w1; cbn in *; eauto. \n  - destruct w1; cbn in *; [congruence | ]. inv H0. inv H. \n    specialize (IHs1 w1 H1 H3) as (-> & ->). eauto. \nQed. \n\nLemma nth_error_step (X : Type) x s (l : list X) a y : x >= S s -> nth_error l (x - S s) = Some a <-> nth_error (y :: l) (x - s) = Some a.\nProof. \n  intros. replace (y :: l) with ([y] ++ l) by now cbn. \n  rewrite nth_error_app2; cbn; [ | lia].\n  replace (x - s - 1) with (x - S s) by lia. tauto.\nQed. \n\nLemma list_eq_nth_error (X : Type) (l1 l2 : list X) : \n  l1 = l2 <-> (|l1| = |l2| /\\ forall k, k < |l1| -> nth_error l1 k = nth_error l2 k). \nProof. \n  split; [intros -> | intros (H1 & H2)]. \n  - split; [easy | intros; easy ]. \n  - revert l2 H1 H2; induction l1; intros; destruct l2. \n    + easy. \n    + cbn in H1; congruence. \n    + cbn in H1; congruence. \n    + cbn in H1. apply Nat.succ_inj in H1. enough (a = x /\\ l1 = l2) by easy; split. \n      * specialize (H2 0 (Nat.lt_0_succ (|l1|))). now cbn in H2. \n      * apply IHl1; [ apply H1 | ]. \n        intros. apply Nat.succ_lt_mono in H. specialize (H2 (S k) H). now cbn in H2. \nQed. \n\nLemma nth_error_firstn (X : Type) k m (l : list X): k < m -> nth_error (firstn m l) k = nth_error l k. \nProof. \n  revert k l. induction m; intros. \n  - lia.\n  - destruct k; cbn; destruct l; cbn; firstorder. now apply IHm.\nQed. \n\nLemma nth_error_skipn (X : Type) k m (l : list X) : nth_error (skipn m l) k = nth_error l (m + k). \nProof. \n  revert k l. induction m; intros. \n  - easy. \n  - destruct l; cbn; [ now destruct k | apply IHm]. \nQed. \n\nLemma firstn_all_inv (X : Type) (m l : list X) : |l| = |m| -> firstn (|l|) m = l -> m = l.\nProof. \n  revert l; induction m; intros.\n  - destruct l; cbn; easy. \n  - destruct l; cbn in *; [easy | ]. inv H0. apply Nat.succ_inj in H. \n    rewrite H3. f_equal. now apply IHm. \nQed. \n\nLemma skipn_firstn_shift (X : Type) (m : list X) len l : skipn l (firstn len m) = firstn (len - l) (skipn l m). \nProof. \n  revert l len. induction m; cbn; intros. \n  - rewrite !firstn_nil, !skipn_nil, firstn_nil. easy. \n  - destruct len. \n    + cbn. now destruct l.\n    + cbn. destruct l; cbn; [ easy | ]. now rewrite IHm. \nQed. \n\nLemma skipn_skipn (X : Type) (m : list X) l1 l2 : skipn l1 (skipn l2 m) = skipn (l1 + l2) m. \nProof. \n  revert l1 l2. \n  induction m; intros; destruct l2; cbn; try now rewrite !skipn_nil. \n  - now rewrite Nat.add_0_r. \n  - rewrite IHm. rewrite Nat.add_succ_r. easy. \nQed. \n\nLemma skipn_firstn_skipn (X : Type) (m : list X) l1 l2 len2 : \n  skipn l1 (firstn len2 (skipn l2 m)) = firstn (len2 - l1) (skipn (l1 + l2) m). \nProof. \n  intros. \n  rewrite skipn_firstn_shift. now rewrite skipn_skipn. \nQed. \n\nLemma firstn_add (X : Type) (m : list X) l1 l2 : firstn (l1 + l2) m = firstn l1 m ++ firstn l2 (skipn l1 m). \nProof. \n  revert l1 l2. induction m; intros. \n  - now rewrite !skipn_nil, !firstn_nil.\n  - destruct l1; cbn; [ easy | ]. now rewrite IHm. \nQed. \n\nLemma dupfree_map_getPosition (X : eqType) (l : list X) : NoDup l -> seq 0 (|l|) = map (getPosition l) l. \nProof. \n  intros H. enough (forall n, seq n (|l|) = map (fun x => n + getPosition l x) l). \n  { specialize (H0 0). apply H0. }\n  induction H; intros; [ easy | ]. \n  cbn. destruct Dec; [ | congruence]. \n  rewrite Nat.add_0_r. f_equal. rewrite (IHNoDup (S n)).\n  clear IHNoDup e.\n  apply map_ext_in. \n  intros a H1. destruct (Dec (a = x)); [ congruence | lia ].  \nQed. \n\nLemma repEl_app_inv (X : Type) (a : X) s1 s2 n : repeat a n = s1 ++ s2 -> exists n1 n2, s1 = repeat a n1 /\\ s2 = repeat a n2 /\\ n1 + n2 = n. \nProof. \n  revert s1 s2.  induction n. \n  - cbn. destruct s1, s2; cbn; try congruence. intros _. exists 0, 0; now cbn.  \n  - cbn. destruct s1. \n    + cbn. destruct s2; cbn; [ congruence | ]. \n      intros H. inv H. exists 0, (S n); now cbn. \n    + intros. cbn in H. inv H. apply IHn in H2 as (n1 & n2 & -> & -> & <-). \n      exists (S n1), n2; now cbn. \nQed. \n\nLemma app_length_split (X : Type) (v u b c : list X) : v ++ b = u ++ c -> |v| <= |u| -> exists u', u = v ++ u'. \nProof. \n  intros. apply list_length_split1 in H0 as (s1 & s2 & H0 & _ & ->). \n  rewrite <- app_assoc in H. apply app_eq_length in H as (-> & ->); [ | easy]. \n  now exists s2. \nQed. \n\nLemma nth_nth_error (X : Type) (l : list X) n def a  : nth n l def = a -> n < |l| -> nth_error l n = Some a. \nProof. \n  intros. apply nth_error_Some in H0. destruct nth_error eqn:H1; [ | congruence].\n  clear H0. apply nth_error_nth' with (y := def) in H1. easy.\nQed. \n\nLemma in_concat_map_iff (X Y : Type) (f : X -> list Y) (l : list X) y : y el concat (map f l) <-> exists x, x el l /\\ y el f x. \nProof. \n  split; intros. \n  - apply in_concat_iff in H as (? & H1 & (? & <- & H3)%in_map_iff). eauto. \n  - apply in_concat_iff. destruct H as (x & H1 & H2). exists (f x). split.\n    + exact H2.\n    + apply in_map. exact H1.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-library-complexity", "sha": "5a996877f16fd6fe16dc5f0c3b933486957869df", "save_path": "github-repos/coq/uds-psl-coq-library-complexity", "path": "github-repos/coq/uds-psl-coq-library-complexity/coq-library-complexity-5a996877f16fd6fe16dc5f0c3b933486957869df/theories/Libs/CookPrelim/MorePrelim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.6531467479519392}}
{"text": "Require Import ZArith.\nRequire Import Coqlib.\nRequire Import Floats.\n\n(* This file defines the data types for defining syntax. *) \n\nLocal Open Scope nat_scope.\n\nModule Size.\n\nDefinition t := nat.\nDefinition dec : forall x y : t, {x=y} + {x<>y} := eq_nat_dec.\nDefinition Zero : t := 0.\nDefinition One : t := 1.\nDefinition Two : t := 2.\nDefinition Four : t := 4.\nDefinition Eight : t := 8.\nDefinition Sixteen : t := 16.\nDefinition ThirtyTwo : t := 32.\nDefinition SixtyFour : t := 64.\nDefinition from_nat (i:nat) : t := i.\nDefinition to_nat (i:t) : nat := i.\nDefinition to_Z (i:t) : Z := Z_of_nat i.\nDefinition from_Z (i:Z) : t := nat_of_Z i.\nDefinition add (a b:t) : t := (a + b).\nDefinition sub (a b:t) : t := (a - b).\nDefinition mul (a b:t) : t := (a * b).\nDefinition div (a b:t) : t := nat_of_Z ((Z_of_nat a) / (Z_of_nat b)).\nDefinition gt (a b:t) : Prop := (a > b).\nDefinition lt (a b:t) : Prop := (a < b).\n\nEnd Size.\n\nModule Align.\n\nDefinition t := nat.\nDefinition dec : forall x y : t, {x=y} + {x<>y} := eq_nat_dec.\nDefinition Zero : t := 0.\nDefinition One : t := 1.\nDefinition Two : t := 2.\nDefinition Four : t := 4.\nDefinition Eight : t := 8.\nDefinition Sixteen : t := 16.\nDefinition ThirtyTwo : t := 32.\nDefinition SixtyFour : t := 64.\nDefinition from_nat (i:nat) : t := i.\nDefinition to_nat (i:t) : nat := i.\nDefinition to_Z (i:t) : Z := Z_of_nat i.\nDefinition from_Z (i:Z) : t := nat_of_Z i.\nDefinition add (a b:t) : t := (a + b).\nDefinition sub (a b:t) : t := (a - b).\nDefinition mul (a b:t) : t := (a * b).\nDefinition div (a b:t) : t := nat_of_Z ((Z_of_nat a) / (Z_of_nat b)).\nDefinition gt (a b:t) : Prop := (a > b).\nDefinition lt (a b:t) : Prop := (a < b).\n\nEnd Align.\n\nModule INTEGER.\n\nDefinition t := Z.\nDefinition dec : forall x y : t, {x=y} + {x<>y} := zeq.\nDefinition to_nat (i:t) : nat := nat_of_Z i.\nDefinition to_Z (i:t) : Z := i.\nDefinition of_Z (bitwidth:Z) (v:Z) (is_signed:bool) : t := v.\n\nEnd INTEGER.\n\nModule FLOAT.\n\nDefinition t := float.\nDefinition dec : forall x y : t, {x=y} + {x<>y} := Float.eq_dec.\n(* Definition Zero : t := Float.zero. *)\n\nEnd FLOAT.\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/datatype_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6530615015952759}}
{"text": "Definition tsat (f:nat -> bool) : Prop := exists (n:nat), f n = true.\n\nLemma tsatOr : forall (f g:nat -> bool), \n    (tsat f \\/ tsat g) -> tsat (fun n => orb (f n) (g n)).\nProof.\n    intros f g [H1|H1]; destruct H1 as [n H1]; exists n; rewrite H1.\n    - destruct (g n); reflexivity.\n    - destruct (f n); 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/Logic/Axiom/Sat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6530615005139214}}
{"text": "\nTheorem Ex046 (A B : Prop): (A /\\ (A -> ~A)) -> (A /\\ (B -> ~A)).\nProof.\n  intro.\n  destruct H.\n  split.\n  + exact H.\n  + intro. intro.\n    apply H0.\n    - exact H.\n    - exact H.\nQed.", "meta": {"author": "SvenWille", "repo": "CoqLogicExercises", "sha": "b4c1aea30abb95dc7ba81fa42ccb914d534d65e5", "save_path": "github-repos/coq/SvenWille-CoqLogicExercises", "path": "github-repos/coq/SvenWille-CoqLogicExercises/CoqLogicExercises-b4c1aea30abb95dc7ba81fa42ccb914d534d65e5/src/propLogic/Ex046.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6530134423857831}}
{"text": "(* ********************************************** *)\n(* Types and Semantics for Programming Languages  *)\n(* ********************************************** *)\n\n(* Place an X in front of the appropriate statement *)\n(* [ ]  I have done Problems 1 and 2 *)\n(* [ ]  I have done Problems 1 and 3 *)\n\n\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 Export Maps.\nRequire Export SfLib.\n\n(* ********************************************** *)\n(* Problem 1 *)\n(* ********************************************** *)\n\nInductive last {X:Type} : list X -> X -> Prop:=\n  | last_end : forall x,\n      last (x :: nil) x\n  | last_step : forall x y xs,\n      last xs y ->\n      last (x::xs) y.\n\nTheorem last_app : forall (X:Type) (x:X) (xs:list X),\n  last xs x -> exists xs', xs = xs' ++ [x].\nProof.\n  intros.\n  induction H. \n  - exists nil.  simpl. reflexivity.\n  - destruct IHlast.\n    exists (x::x0). rewrite H0. simpl. reflexivity.\nQed.\n\n(* ********************************************** *)\n(* Problem 2 *)\n(* ********************************************** *)\n\n(* Arithmetic and boolean expressions *)\n\nDefinition state := total_map nat.\n\nDefinition ble_nat := leb.\t\t    \n\nInductive aexp : Type :=\n  | ANum : nat -> aexp\n  | AId : id -> aexp\n  | APlus : aexp -> aexp -> aexp\n  | AMinus : aexp -> aexp -> aexp\n  | AMult : aexp -> aexp -> aexp.\n\nInductive bexp : Type :=\n  | BTrue : bexp\n  | BFalse : bexp\n  | BEq : aexp -> aexp -> bexp\n  | BLe : aexp -> aexp -> bexp\n  | BNot : bexp -> bexp\n  | BAnd : bexp -> bexp -> bexp.\n\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\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  | CLoop : com -> 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 \"'IFB' c1 'THEN' c2 'ELSE' c3 'FI'\" :=\n  (CIf c1 c2 c3) (at level 80, right associativity).\nNotation \"'WHILE' b 'DO' c 'END'\" :=\n  (CWhile b c) (at level 80, right associativity).\nNotation \" 'LOOP' c1 'WHILE' b 'DO' c2 'END'\" :=\n  (CLoop c1 b c2) (at level 80, right associativity).\n\n\n(* Evaluation relation *)\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 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_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  | \n\n  where \"c1 '/' st '||' st'\" := (ceval c1 st st').\n\n(* Assertions *)\n\nDefinition Assertion := state -> Prop.\n\nDefinition assert_implies (P Q : Assertion) : Prop :=\n  forall st, P st -> Q st.\n\nNotation \"P ->> Q\" :=\n  (assert_implies P Q) (at level 80) : hoare_spec_scope.\nOpen Scope hoare_spec_scope.\n\nNotation \"P <<->> Q\" :=\n  (P ->> Q /\\ Q ->> P) (at level 80) : hoare_spec_scope.\n\n(* Hoare triples *)\n\nDefinition hoare_triple\n           (P:Assertion) (c:com) (Q:Assertion) : Prop :=\n  forall st st',\n       c / st || st'  ->\n       P st  ->\n       Q st'.\n\nNotation \"{{ P }}  c  {{ Q }}\" :=\n  (hoare_triple P c Q) (at level 90, c at next level)\n  : hoare_spec_scope.\n\n(* Assertions *)\n\nDefinition bassn b : Assertion :=\n  fun st => (beval st b = true).\n\nLemma bexp_eval_true : forall b st,\n  beval st b = true -> (bassn b) st.\nProof.\n  intros b st Hbe.\n  unfold bassn. assumption.  Qed.\n\nLemma bexp_eval_false : forall b st,\n  beval st b = false -> ~ ((bassn b) st).\nProof.\n  intros b st Hbe contra.\n  unfold bassn in contra.\n  rewrite -> contra in Hbe. inversion Hbe.  Qed.\n\n(* Assignment *)\n\n(*\n             ------------------------------ (hoare_asgn)\n             {{Q [X |-> a]}} X::=a {{Q}}\n*)\n\n\nDefinition assn_sub X a P : Assertion :=\n  fun (st : state) =>\n    P (t_update st X (aeval st a)).\n\nNotation \"P [ X |-> a ]\" := (assn_sub X a P) (at level 10).\n\nTheorem hoare_asgn : forall Q X a,\n  {{Q [X |-> a]}} (X ::= a) {{Q}}.\nProof.\n  unfold hoare_triple.\n  intros Q X a st st' HE HQ.\n  inversion HE. subst.\n  unfold assn_sub in HQ. assumption.  Qed.\n\n(* Consequence *)\n\n(*\n                {{P'}} c {{Q'}}\n                   P ->> P'\n                   Q' ->> Q\n         -----------------------------   (hoare_consequence)\n                {{P}} c {{Q}}\n*)\n\nTheorem hoare_consequence_pre : forall (P P' Q : Assertion) c,\n  {{P'}} c {{Q}} ->\n  P ->> P' ->\n  {{P}} c {{Q}}.\nProof.\n  intros P P' Q c Hhoare Himp.\n  intros st st' Hc HP. apply (Hhoare st st'). \n  assumption. apply Himp. assumption. Qed.\n\nTheorem hoare_consequence_post : forall (P Q Q' : Assertion) c,\n  {{P}} c {{Q'}} ->\n  Q' ->> Q ->\n  {{P}} c {{Q}}.\nProof.\n  intros P Q Q' c Hhoare Himp.\n  intros st st' Hc HP. \n  apply Himp.\n  apply (Hhoare st st'). \n  assumption. assumption. Qed.\n\nTheorem hoare_consequence : forall (P P' Q Q' : Assertion) c,\n  {{P'}} c {{Q'}} ->\n  P ->> P' ->\n  Q' ->> Q ->\n  {{P}} c {{Q}}.\nProof.\n  intros P P' Q Q' c Hht HPP' HQ'Q.\n  apply hoare_consequence_pre with (P' := P').\n  apply hoare_consequence_post with (Q' := Q').\n  assumption. assumption. assumption.  Qed.\n\n(* Skip *)\n\n(*\n             --------------------  (hoare_skip)\n             {{ P }} SKIP {{ P }}\n*)\n\nTheorem hoare_skip : forall P,\n     {{P}} SKIP {{P}}.\nProof.\n  intros P st st' H HP. inversion H. subst.\n  assumption.  Qed.\n\n(* Sequencing *)\n\n(*\n               {{ P }} c1 {{ Q }} \n               {{ Q }} c2 {{ R }}\n              ---------------------  (hoare_seq)\n              {{ P }} c1;;c2 {{ R }}\n*)\n\nTheorem hoare_seq : forall P Q R c1 c2,\n     {{Q}} c2 {{R}} ->\n     {{P}} c1 {{Q}} ->\n     {{P}} c1;;c2 {{R}}.\nProof.\n  intros P Q R c1 c2 H1 H2 st st' H12 Pre.\n  inversion H12; subst.\n  apply (H1 st'0 st'); try assumption.\n  apply (H2 st st'0); assumption. Qed.\n\n(* Conditional *)\n\n(*\n              {{P /\\  b}} c1 {{Q}}\n              {{P /\\ ~b}} c2 {{Q}}\n      ------------------------------------  (hoare_if)\n      {{P}} IFB b THEN c1 ELSE c2 FI {{Q}} \n*)\n\nTheorem hoare_if : forall P Q b c1 c2,\n  {{fun st => P st /\\ bassn b st}} c1 {{Q}} ->\n  {{fun st => P st /\\ ~(bassn b st)}} c2 {{Q}} ->\n  {{P}} (IFB b THEN c1 ELSE c2 FI) {{Q}}.\nProof.\n  intros P Q b c1 c2 HTrue HFalse st st' HE HP.\n  inversion HE; subst. \n  + (* \"b is true\" *)\n    apply (HTrue st st'). \n      assumption. \n      split. assumption. \n             apply bexp_eval_true. assumption.\n  + (* \"b is false\" *)\n    apply (HFalse st st'). \n      assumption. \n      split. assumption.\n             apply bexp_eval_false. assumption. Qed.\n\n(* While *)\n\n(*\n               {{P /\\ b}} c {{P}}\n        -----------------------------------  (hoare_while)\n        {{P}} WHILE b DO c END {{P /\\ ~b}}\n    The proposition [P] is called an _invariant_ of the loop.\n*)\n\nLemma hoare_while : forall P b c,\n  {{fun st => P st /\\ bassn b st}} c {{P}} ->\n  {{P}} WHILE b DO c END {{fun st => P st /\\ ~ (bassn b st)}}.\nProof.\n  intros P b c Hhoare st st' He HP.\n  (* Like we've seen before, we need to reason by induction \n     on [He], because, in the \"keep looping\" case, its hypotheses \n     talk about the whole loop instead of just [c]. *)\n  remember (WHILE b DO c END) as wcom eqn:Heqwcom.\n  induction He;\n    try (inversion Heqwcom); subst; clear Heqwcom.\n  + (* Case \"E_WhileEnd\" *)\n    split. assumption. apply bexp_eval_false. assumption.\n  + (* Case \"E_WhileLoop\" *)\n    apply IHHe2. reflexivity.\n    apply (Hhoare st st'). assumption.\n      split. assumption. apply bexp_eval_true. assumption.\nQed.\n\n(* ********************************************** *)\n(* Problem 3 *)\n(* ********************************************** *)\n\n(* Types *)\n\nInductive ty : Type := \n  | TBool  : ty \n  | TArrow : ty -> ty -> ty.\n\n(* Terms *)\n\nInductive tm : Type :=\n  | tvar : id -> tm\n  | tapp : tm -> tm -> tm\n  | tabs : id -> ty -> tm -> tm\n  | ttrue : tm\n  | tfalse : tm\n  | tif : tm -> tm -> tm -> tm.\n\n(* Values *)\n\nInductive value : tm -> Prop :=\n  | v_abs : forall x T t,\n      value (tabs x T t)\n  | v_true : \n      value ttrue\n  | v_false : \n      value tfalse.\n\nHint Constructors value.\n\n(* Substitution *)\n\nReserved Notation \"'[' x ':=' s ']' t\" (at level 20, right associativity).\n\nFixpoint subst (x:id) (s:tm) (t:tm) : tm :=\n  match t with\n  | tvar x' => \n      if beq_id x x' then s else t\n  | tabs x' T t1 => \n      tabs x' T (if beq_id x x' then t1 else ([x:=s] t1)) \n  | tapp t1 t2 => \n      tapp ([x:=s] t1) ([x:=s] t2)\n  | ttrue => \n      ttrue\n  | tfalse => \n      tfalse\n  | tif t1 t2 t3 => \n      tif ([x:=s] t1) ([x:=s] t2) ([x:=s] t3)\n  end\n\nwhere \"'[' x ':=' s ']' t\" := (subst x s t).\n\n(* Evaluation relation *)\n\nReserved Notation \"t1 '==>' t2\" (at level 40).\n\nInductive step : tm -> tm -> Prop :=\n  | ST_AppAbs : forall x T t12 v2,\n         value v2 ->\n         (tapp (tabs x T t12) v2) ==> [x:=v2]t12\n  | ST_App1 : forall t1 t1' t2,\n         t1 ==> t1' ->\n         tapp t1 t2 ==> tapp t1' t2\n  | ST_App2 : forall v1 t2 t2',\n         value v1 ->\n         t2 ==> t2' -> \n         tapp v1 t2 ==> tapp v1  t2'\n  | ST_IfTrue : forall t1 t2,\n      (tif ttrue t1 t2) ==> t1\n  | ST_IfFalse : forall t1 t2,\n      (tif tfalse t1 t2) ==> t2\n  | ST_If : forall t1 t1' t2 t3,\n      t1 ==> t1' ->\n      (tif t1 t2 t3) ==> (tif t1' t2 t3)\n\nwhere \"t1 '==>' t2\" := (step t1 t2).\n\nHint Constructors step.\n\nDefinition relation a := a -> a -> Prop.\n\nInductive multi {X:Type} (R: relation X) : relation X :=\n  | multi_refl : forall (x : X), multi R x x\n  | multi_step : forall (x y z : X),\n                    R x y ->\n                    multi R y z ->\n                    multi R x z.\n\nNotation \"t1 '==>*' t2\" := (multi step t1 t2) (at level 40).\n\n(* Contexts *)\n\nDefinition context := partial_map ty.\n\n(* Typing relation *)\n\nReserved Notation \"Gamma '|-' t '\\in' T\" (at level 40).\n    \nInductive has_type : context -> tm -> ty -> Prop :=\n  | T_Var : forall Gamma x T,\n      Gamma x = Some T ->\n      Gamma |- tvar x \\in T\n  | T_Abs : forall Gamma x T11 T12 t12,\n      update Gamma x T11 |- t12 \\in T12 -> \n      Gamma |- tabs x T11 t12 \\in TArrow T11 T12\n  | T_App : forall T11 T12 Gamma t1 t2,\n      Gamma |- t1 \\in TArrow T11 T12 -> \n      Gamma |- t2 \\in T11 -> \n      Gamma |- tapp t1 t2 \\in T12\n  | T_True : forall Gamma,\n       Gamma |- ttrue \\in TBool\n  | T_False : forall Gamma,\n       Gamma |- tfalse \\in TBool\n  | T_If : forall t1 t2 t3 T Gamma,\n       Gamma |- t1 \\in TBool ->\n       Gamma |- t2 \\in T ->\n       Gamma |- t3 \\in T ->\n       Gamma |- tif t1 t2 t3 \\in T\n\nwhere \"Gamma '|-' t '\\in' T\" := (has_type Gamma t T).\n\nHint Constructors has_type.\n\n(* Canonical Forms *)\n\nLemma cannonical_forms_bool : forall t,\n  empty |- t \\in TBool ->\n  value t ->\n  (t = ttrue) \\/ (t = tfalse).\nProof.\n  intros t HT HVal.\n  inversion HVal; intros; subst; try inversion HT; auto.\nQed.\n\nLemma cannonical_forms_fun : forall t T1 T2,\n  empty |- t \\in (TArrow T1 T2) ->\n  value t ->\n  exists x u, t = tabs x T1 u.\nProof.\n  intros t T1 T2 HT HVal.\n  inversion HVal; intros; subst; try inversion HT; subst; auto.\n  exists x. exists t0.  auto.\nQed.\n   \n(* Progress, by induction on type derivation *)\n\nTheorem progress : forall t T, \n     empty |- t \\in T ->\n     value t \\/ exists t', t ==> t'.\n\nProof with eauto.\n  intros t T Ht.\n  remember (@empty ty) as Gamma.\n  induction Ht; subst Gamma...\n  + (* Case \"T_Var\" *)\n    (* contradictory: variables cannot be typed in an \n       empty context *)\n    inversion H. \n\n  + (* Case \"T_App\" *) \n    (* [t] = [t1 t2].  Proceed by cases on whether [t1] is a \n       value or steps... *)\n    right. destruct IHHt1...\n    - (* t1 is a value *)\n      destruct IHHt2...\n      * (* t2 is also a value *)\n        assert (exists x0 t0, t1 = tabs x0 T11 t0).\n        eapply cannonical_forms_fun; eauto.\n        destruct H1 as [x0 [t0 Heq]]. subst.\n        exists ([x0:=t2]t0)...\n\n      * (* t2 steps *)\n        inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...\n\n    - (* t1 steps *)\n      inversion H as [t1' Hstp]. exists (tapp t1' t2)...\n\n  + (* Case \"T_If\" *)\n    right. destruct IHHt1...\n    \n    - (* t1 is a value *)\n      destruct (cannonical_forms_bool t1); subst; eauto.\n\n    - (* t1 also steps *)\n      inversion H as [t1' Hstp]. exists (tif t1' t2 t3)...\nQed.\n\n\n", "meta": {"author": "pierewoj", "repo": "tspl", "sha": "7b0f7edb08f04469bafdac804f22b347ea5574c4", "save_path": "github-repos/coq/pierewoj-tspl", "path": "github-repos/coq/pierewoj-tspl/tspl-7b0f7edb08f04469bafdac804f22b347ea5574c4/pract2/Exam.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749422, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.6529726197514113}}
{"text": "Require Export List Setoid Morphisms SetoidList Sorted.\nRequire Export Orders OrdersFacts.\nRequire Export Bool Arith Lia.\nImport ListNotations.\n\nLemma app_nil {A} (l l' : list A) : l ++ l' = [] <-> l = [] /\\ l' = [].\nProof.\nAdmitted.\n\n(** Cartesian product *)\n\nDefinition product {A B} (l : list A) (l' : list B) : list (A * B) :=\n List.flat_map (fun e => map (pair e) l') l.\n\nLemma product_ok {A B} (l : list A) (l' : list B) x y :\n  List.In (x, y) (product l l') <-> List.In x l /\\ List.In y l'.\nProof.\nAdmitted.\n\nLemma product_length {A B} (l:list A)(l':list B) :\n  length (product l l') = length l * length l'.\nProof.\nAdmitted.\n\n(** Equivalence of lists *)\n\nDefinition eqlist {A} (l l' : list A) := forall n,\n  List.In n l <-> List.In n l'.\n\n(** For rewriting with eqlist : *)\nGlobal Instance : forall A, Equivalence (@eqlist A).\nProof. firstorder. Qed.\nGlobal Instance : forall {A}, Proper (eq ==> eqlist ==> eqlist) (@cons A).\nProof. intros A a a' <-. firstorder. Qed.\nGlobal Instance : forall {A}, Proper (eqlist ==> eqlist ==> eqlist) (@app A).\nProof.\n intros A l1 l1' H1 l2 l2' H2 x.\n rewrite !in_app_iff. now rewrite (H1 x), (H2 x).\nQed.\nGlobal Instance : forall {A B}, Proper (eq ==> eqlist ==> eqlist) (@map A B).\nProof.\n intros A B f f' <- l l' H x. rewrite !in_map_iff.\n split; intros (y & E & IN); exists y; split; auto; now apply H.\nQed.\n\nLemma eqlist_nil {A} (l : list A) : eqlist l [] -> l = [].\nProof.\nAdmitted.\n\nLemma eqlist_comm {A} (l l' : list A) : eqlist l l' -> eqlist l' l.\nProof.\nAdmitted.\n\nLemma eqlist_undup {A} (a:A) l l' :\n eqlist (a::l) l' -> In a l -> eqlist l l'.\nProof.\nAdmitted.\n\nLemma eqlist_uncons {A} (a:A) l l' :\n eqlist (a::l) (a::l') -> ~In a l -> ~In a l' -> eqlist l l'.\nProof.\nAdmitted.\n\n(** [Incl] : inclusion of lists.\n\n    For this predicate, the positions are important : a list is included\n    in another if we can obtain the second one by putting some more\n    elements in the first one. *)\n\nInductive Incl {A} : list A -> list A -> Prop :=\n| InclNil : Incl [] []\n| InclSkip x l l' : Incl l l' -> Incl l (x::l')\n| InclSame x l l' : Incl l l' -> Incl (x::l) (x::l').\nGlobal Hint Constructors Incl : core.\n\nLemma Incl_nil {A} (l:list A) : Incl [] l.\nProof.\nAdmitted.\nGlobal Hint Resolve Incl_nil : core.\n\nLemma Incl_len {A} (l l' : list A) : Incl l l' -> length l <= length l'.\nProof.\nAdmitted.\n\nGlobal Instance Incl_PreOrder {A} : PreOrder (@Incl A).\nProof.\n split.\n - red. intro l. induction l; auto.\n - red. intros l1 l2 l3 H12 H23. revert l1 H12.\n   induction H23; intros; auto. inversion H12; subst; auto.\nQed.\n\nGlobal Instance Incl_Order {A} : PartialOrder eq (@Incl A).\nProof.\n intros l l'; split.\n - now intros <-.\n - intros (H,H'). red in H'.\n   induction H.\n   + inversion H'; subst; auto.\n   + apply Incl_len in H; apply Incl_len in H'. simpl in *. lia.\n   + f_equal. inversion H'; subst; auto.\n     apply Incl_len in H; apply Incl_len in H2. simpl in *. lia.\nQed.\n\nLemma Incl_Forall {A}(P:A->Prop) l l' :\n  Incl l l' -> Forall P l' -> Forall P l.\nProof.\n induction 1; auto; inversion 1; subst; auto.\nQed.\n\nLemma Incl_singleton {A} (a:A) l : In a l -> Incl [a] l.\nProof.\nAdmitted.\n\n(** [sublists] generates all lists included in a first one *)\n\nFixpoint sublists {A} (l : list A) :=\n  match l with\n  | [] => [[]]\n  | a :: l' =>\n    let s := sublists l' in\n    s ++ List.map (cons a) s\n  end.\n\nLemma sublists_spec {A} (l l' :list A) :\n In l' (sublists l) <-> Incl l' l.\nProof.\nAdmitted.\n\nLemma sublists_length {A} (l:list A) :\n length (sublists l) = 2^length l.\nProof.\nAdmitted.\n\n(** [Subset] : another inclusion predicate, but this time we ignore\n   the positions and the repetitions. It is enough for all elements\n   of the left list to appear at least somewhere in the right list. *)\n\nDefinition Subset {A} (l l' : list A) :=\n  forall n, List.In n l -> List.In n l'.\n\nLemma subset_notin {A} (l l' : list A) a :\n Subset l (a::l') -> ~In a l -> Subset l l'.\nProof.\nAdmitted.\n\nLemma subset_nil {A} (l : list A) : Subset l [] -> l = [].\nProof.\nAdmitted.\n\nLemma incl_subset {A} (l l':list A) : Incl l l' -> Subset l l'.\nProof.\nAdmitted.\n\n(** A tricky lemma : a subset without duplicates has a smaller length.\n    See Coq standard library for [NoDup]. This proof might be done\n    via [List.in_split]. *)\n\nLemma subset_nodup_length {A} (l l' : list A) :\n Subset l l' -> NoDup l -> length l <= length l'.\nProof.\nAdmitted.\n\n(** More on [Incl] and [Subset] in RegOrder.v, where we will be able to\n    test whether two list elements are equal or not. *)\n\nLemma existsb_forall {A} (f:A -> bool) l :\n existsb f l = false <-> forall x, In x l -> f x = false.\nProof.\nAdmitted.\n\n(** Being in a list, modulo an equivalence [R] *)\n\nSection SomeEquivalence.\nContext {A}(R:A->A->Prop){HR:Equivalence R}.\n\nDefinition InModulo a l := exists a', R a a' /\\ In a' l.\n\nGlobal Instance : Proper (R ==> eqlist ==> iff) InModulo.\nProof.\n intros x x' Hx l l' Hl. unfold InModulo; split;\n intros (a' & IN & E); exists a'; split; eauto; firstorder.\nQed.\n\n(** Equivalence with another such definition (from Coq stdlib) *)\n\nLemma InModulo_InA a l : InModulo a l <-> InA R a l.\nProof.\n symmetry. apply InA_alt.\nQed.\n\n(** Similar to [subset_nodup_length], but here elements are taken up\n    to the equivalence R. See Coq stdlib for [NoDupA]. *)\n\nLemma subset_nodupA_length l l' :\n (forall x, In x l -> InModulo x l') -> NoDupA R l ->\n length l <= length l'.\nProof using HR.\nAdmitted.\n\n(** Removing redundancy with respect to some decidable equivalence.\n    Quadratic complexity. *)\n\nVariable (f:A->A->bool).\nVariable (Hf:forall a b, f a b = true <-> R a b).\n\nFixpoint removedup l :=\n  match l with\n  | [] => []\n  | x::l =>\n    let l' := removedup l in\n    if existsb (f x) l' then l' else x::l'\n  end.\n\nLemma removedup_nodup l : NoDupA R (removedup l).\nProof using Hf.\nAdmitted.\n\nLemma removedup_incl l : Incl (removedup l) l.\nProof using f.\nAdmitted.\n\nLemma removedup_in l x : In x l -> InModulo x (removedup l).\nProof using Hf HR.\nAdmitted.\n\nEnd SomeEquivalence.\n", "meta": {"author": "herbelin", "repo": "cours-preuves-ordinateur", "sha": "c638a7591e40af35fce450b4282b6dd717935aed", "save_path": "github-repos/coq/herbelin-cours-preuves-ordinateur", "path": "github-repos/coq/herbelin-cours-preuves-ordinateur/cours-preuves-ordinateur-c638a7591e40af35fce450b4282b6dd717935aed/projet/ListUtils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749422, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.6529726178838955}}
{"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\nRequire Import BinPos BinNat.\n\nLocal Open Scope N_scope.\n\nDefinition NPgeb (a:N)(b:positive) :=\n  match a with\n   | 0 => false\n   | Npos na => match Pcompare na b Eq with Lt => false | _ => true end\n  end.\n\nLocal Notation \"a >=? b\" := (NPgeb a b) (at level 70).\n\nFixpoint Pdiv_eucl (a b:positive) : N * N :=\n  match a with\n    | xH =>\n       match b with xH => (1, 0) | _ => (0, 1) end\n    | xO a' =>\n       let (q, r) := Pdiv_eucl a' b in\n       let r' := 2 * r in\n        if r' >=? b then (2 * q + 1, r' - Npos b)\n        else (2 * q, r')\n    | xI a' =>\n       let (q, r) := Pdiv_eucl a' b in\n       let r' := 2 * r + 1 in\n        if r' >=? b then (2 * q + 1, r' - Npos b)\n        else  (2 * q, r')\n  end.\n\nDefinition Ndiv_eucl (a b:N) : N * N :=\n  match a, b with\n   | 0,  _ => (0, 0)\n   | _, 0  => (0, a)\n   | Npos na, Npos nb => Pdiv_eucl na nb\n  end.\n\nDefinition Ndiv a b := fst (Ndiv_eucl a b).\nDefinition Nmod a b := snd (Ndiv_eucl a b).\n\nInfix \"/\" := Ndiv : N_scope.\nInfix \"mod\" := Nmod (at level 40, no associativity) : N_scope.\n\n(** Auxiliary Results about [NPgeb] *)\n\nLemma NPgeb_ge : forall a b, NPgeb a b = true -> a >= Npos b.\nProof.\n destruct a; simpl; intros.\n discriminate.\n unfold Nge, Ncompare. now destruct Pcompare.\nQed.\n\nLemma NPgeb_lt : forall a b, NPgeb a b = false -> a < Npos b.\nProof.\n destruct a; simpl; intros. red; auto.\n unfold Nlt, Ncompare. now destruct Pcompare.\nQed.\n\nTheorem NPgeb_correct: forall (a:N)(b:positive),\n  if NPgeb a b then a = a - Npos b + Npos b else True.\nProof.\n  destruct a as [|a]; simpl; intros b; auto.\n  generalize (Pcompare_Eq_eq a b).\n  case_eq (Pcompare a b Eq); intros; auto.\n  rewrite H0; auto.\n  now rewrite Pminus_mask_diag.\n  destruct (Pminus_mask_Gt a b H) as [d [H2 [H3 _]]].\n  rewrite H2. rewrite <- H3.\n  simpl; f_equal; apply Pplus_comm.\nQed.\n\nLemma NPgeb_ineq0 : forall a p, a < Npos p -> NPgeb (2*a) p = true ->\n 2*a - Npos p < Npos p.\nProof.\nintros a p LT GE.\napply Nplus_lt_cancel_l with (Npos p).\nrewrite Nplus_comm.\ngeneralize (NPgeb_correct (2*a) p). rewrite GE. intros <-.\nrewrite <- (Nmult_1_l (Npos p)). rewrite <- Nmult_plus_distr_r.\ndestruct a; auto.\nQed.\n\nLemma NPgeb_ineq1 : forall a p, a < Npos p -> NPgeb (2*a+1) p = true ->\n  (2*a+1) - Npos p < Npos p.\nProof.\nintros a p LT GE.\napply Nplus_lt_cancel_l with (Npos p).\nrewrite Nplus_comm.\ngeneralize (NPgeb_correct (2*a+1) p). rewrite GE. intros <-.\nrewrite <- (Nmult_1_l (Npos p)). rewrite <- Nmult_plus_distr_r.\ndestruct a; auto.\nred; simpl. apply Pcompare_eq_Lt; auto.\nQed.\n\n(* Proofs of specifications for these euclidean divisions. *)\n\nTheorem Pdiv_eucl_correct: forall a b,\n  let (q,r) := Pdiv_eucl a b in Npos a = q * Npos b + r.\nProof.\n  induction a; cbv beta iota delta [Pdiv_eucl]; fold Pdiv_eucl; cbv zeta.\n  intros b; generalize (IHa b); case Pdiv_eucl.\n    intros q1 r1 Hq1.\n    assert (Npos a~1 = 2*q1*Npos b + (2*r1+1))\n     by now rewrite Nplus_assoc, <- Nmult_assoc, <- Nmult_plus_distr_l, <- Hq1.\n    generalize (NPgeb_correct (2 * r1 + 1) b); case NPgeb; intros H'; auto.\n    rewrite Nmult_plus_distr_r, Nmult_1_l.\n    rewrite <- Nplus_assoc, (Nplus_comm (Npos b)), <- H'; auto.\n  intros b; generalize (IHa b); case Pdiv_eucl.\n    intros q1 r1 Hq1.\n    assert (Npos a~0 = 2*q1*Npos b + 2*r1)\n     by now rewrite <- Nmult_assoc, <- Nmult_plus_distr_l, <- Hq1.\n    generalize (NPgeb_correct (2 * r1) b); case NPgeb; intros H'; auto.\n    rewrite Nmult_plus_distr_r, Nmult_1_l.\n    rewrite <- Nplus_assoc, (Nplus_comm (Npos b)), <- H'; auto.\n  destruct b; auto.\nQed.\n\nTheorem Ndiv_eucl_correct: forall a b,\n  let (q,r) := Ndiv_eucl a b in a = b * q + r.\nProof.\n  destruct a as [|a]; destruct b as [|b]; simpl; auto.\n  generalize (Pdiv_eucl_correct a b); case Pdiv_eucl; intros q r.\n  destruct q. simpl; auto. rewrite Nmult_comm. intro EQ; exact EQ.\nQed.\n\nTheorem Ndiv_mod_eq : forall a b,\n  a = b * (a/b) + (a mod b).\nProof.\n  intros; generalize (Ndiv_eucl_correct a b).\n  unfold Ndiv, Nmod; destruct Ndiv_eucl; simpl; auto.\nQed.\n\nTheorem Pdiv_eucl_remainder : forall a b:positive,\n  snd (Pdiv_eucl a b) < Npos b.\nProof.\n  induction a; cbv beta iota delta [Pdiv_eucl]; fold Pdiv_eucl; cbv zeta.\n  intros b; generalize (IHa b); case Pdiv_eucl.\n    intros q1 r1 Hr1; simpl in Hr1.\n    case_eq (NPgeb (2*r1+1) b); intros; unfold snd.\n    apply NPgeb_ineq1; auto.\n    apply NPgeb_lt; auto.\n  intros b; generalize (IHa b); case Pdiv_eucl.\n    intros q1 r1 Hr1; simpl in Hr1.\n    case_eq (NPgeb (2*r1) b); intros; unfold snd.\n    apply NPgeb_ineq0; auto.\n    apply NPgeb_lt; auto.\n  destruct b; simpl; reflexivity.\nQed.\n\nTheorem Nmod_lt : forall (a b:N), b<>0 -> a mod b < b.\nProof.\n  destruct b as [ |b]; intro H; try solve [elim H;auto].\n  destruct a as [ |a]; try solve [compute;auto]; unfold Nmod, Ndiv_eucl.\n  generalize (Pdiv_eucl_remainder a b); destruct Pdiv_eucl; simpl; auto.\nQed.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/NArith/Ndiv_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.6529479103645413}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. You may distribute   *)\n(* under the terms of either the CeCILL-B License or the CeCILL        *)\n(* version 2 License, as specified in the README file.                 *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq bigops fintype.\nRequire Import div prime choice.\n\n(****************************************************************************)\n(* This files contains the definition  of:                                  *)\n(*   bin m n        ==  binomial coeficients, i.e. m choose n               *)\n(*                                                                          *)\n(* In additions to the properties of this function, wilson and pascal are   *)\n(* two examples of how to manipulate expressions with bigops.               *)\n(****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(** Factorial lemma **)\nLemma fact0 : fact 0 = 1.\nProof. by done. Qed.\n\nLemma factS : forall n, fact n.+1  = n.+1 * fact n.\nProof. by done. Qed.\n\nLemma fact_prod n : fact n = \\prod_(1 <= i < n.+1) i.\nProof.\nelim=> [|n Hrec] //; first by rewrite big_nil.\nby apply sym_equal; rewrite factS Hrec // !big_add1 big_nat_recr /= mulnC.\nQed.\n\nTheorem wilson : forall p, p > 1 -> prime p = (p %| (fact p.-1).+1).\nProof.\nhave dFact: forall p, 0 < p -> fact p.-1 = \\prod_(0 <= i < p | i != 0) i.\n  move=> p Hp; rewrite -big_filter fact_prod; symmetry; apply: congr_big=> //.\n  rewrite /index_iota subn1 -[p]prednK //=; apply/all_filterP.\n  by rewrite all_predC has_pred1 mem_iota.\nmove=> p lt1p; have p_gt0 := ltnW lt1p.\napply/idP/idP=> [pr_p | dv_pF]; last first.\n  apply/primeP; split=> // d dv_dp; have: d <= p by exact: dvdn_leq.\n  rewrite orbC leq_eqVlt; case/orP=> [-> // | ltdp].\n  have:= dvdn_trans dv_dp dv_pF; rewrite dFact // big_mkord.\n  rewrite (bigD1 (Ordinal ltdp)) /=; last by rewrite -lt0n (dvdn_gt0 p_gt0).\n  by rewrite orbC -addn1 dvdn_addr ?dvdn_mulr // dvdn1 => ->.\npose Fp1 := Ordinal lt1p; pose Fp0 := Ordinal p_gt0.\nhave ltp1p: p.-1 < p by [rewrite prednK]; pose Fpn1 := Ordinal ltp1p.\ncase eqF1n1: (Fp1 == Fpn1); first by rewrite -{1}[p]prednK -1?((1 =P p.-1) _).\nhave toFpP: _ %% p < p by move=> m; rewrite ltn_mod.\npose toFp := Ordinal (toFpP _).\npose mFp (i j : 'I_p) := toFp (i * j).\nhave Fp_mod: forall i : 'I_p, i %% p = i by move=> i; exact: modn_small.\nhave mFpA: associative mFp.\n  by move=> i j k; apply: val_inj; rewrite /= modn_mulml modn_mulmr mulnA.\nhave mFpC: commutative mFp by move=> i j; apply: val_inj; rewrite /= mulnC.\nhave mFp1: left_id Fp1 mFp by move=> i; apply: val_inj; rewrite /= mul1n.\nhave mFp1r: right_id Fp1 mFp by move=> i; apply: val_inj; rewrite /= muln1.\npose mFpLaw := Monoid.Law mFpA mFp1 mFp1r.\npose mFpM := Monoid.operator (@Monoid.ComLaw _ _ mFpLaw mFpC).\npose vFp (i : 'I_p) := toFp (egcdn i p).1.\nhave vFpV: forall i, i != Fp0 -> mFp (vFp i) i = Fp1.\n  move=> i; rewrite -val_eqE /= -lt0n => i_gt0; apply: val_inj => /=.\n  rewrite modn_mulml; case: egcdnP => //= _ km -> _; rewrite {km}modn_addl_mul.\n  suff: coprime i p by move/eqnP->; rewrite modn_small.\n  rewrite coprime_sym prime_coprime //; apply/negP; move/(dvdn_leq i_gt0).\n  by rewrite leqNgt ltn_ord.\nhave vFp0: forall i, i != Fp0 -> vFp i != Fp0.\n  move=> i; move/vFpV=> inv_i; apply/eqP=> vFp0.\n  by have:= congr1 val inv_i; rewrite vFp0 /= mod0n.\nhave vFpK: {in predC1 Fp0, involutive vFp}.\n  by move=> i n0i; rewrite /= -[vFp _]mFp1r -(vFpV _ n0i) mFpA vFpV (vFp0, mFp1).\nhave le_pmFp: (_ : 'I_p) <= p + _.\n  by move=> *; apply: leq_trans (ltnW _) (leq_addr _ _).\nhave eqFp : forall i j : 'I_p, (i == j) = (p %| p + i - j).\n  by move=> i j; rewrite -eqn_mod_dvd ?(modn_addl, Fp_mod).\nhave vFpId: forall i, (vFp i == i :> nat) = xpred2 Fp1 Fpn1 i.\n  move=> i; symmetry; case: (i =P Fp0) => [->{i}|]; last move/eqP=> ni0.\n    by rewrite /= -!val_eqE /= -{2}[p]prednK //= modn_small //= -(subnKC lt1p).\n  rewrite 2!eqFp -euclid //= -[_ - p.-1]subSS prednK //.\n  have lt0i: 0 < i by rewrite lt0n.\n  rewrite -addnS addKn -addn_subA // muln_addl -{2}(addn1 i) -subn_sqr.\n  rewrite addn_subA ?leq_sqr // mulnS -addnA -mulnn -muln_addl.\n  rewrite -(subnK (le_pmFp (vFp i) i)) muln_addl addnCA.\n  rewrite -[1 ^ 2]/(Fp1 : nat) -addn_subA // dvdn_addl.\n    by rewrite euclid // -eqFp eq_sym orbC /dvdn Fp_mod eqn0Ngt lt0i.\n  by rewrite -eqn_mod_dvd // Fp_mod modn_addl -(vFpV _ ni0) eqxx.\nsuffices [mod_fact]: toFp (fact p.-1) = Fpn1.\n  by rewrite /dvdn -addn1 -modn_addml mod_fact addn1 prednK // modnn.\nrewrite dFact // (@big_morph _ _ _ Fp1 _ mFpM toFp) //; first last.\n- by apply: val_inj; rewrite /= modn_small.\n- by move=> i j; apply: val_inj; rewrite /= modn_mul2m.\nrewrite big_mkord (eq_bigr id) => [|i _]; last by apply: val_inj => /=.\npose ltv i := vFp i < i; rewrite (bigID ltv) -/mFpM [mFpM _ _]mFpC.\nrewrite (bigD1 Fp1) -/mFpM; last by rewrite [ltv _]ltn_neqAle vFpId.\nrewrite [mFpM _ _]mFp1 (bigD1 Fpn1) -?mFpA -/mFpM; last first.\n  rewrite -lt0n -ltnS prednK // lt1p.\n  by rewrite [ltv _]ltn_neqAle vFpId eqxx orbT eq_sym eqF1n1.\nrewrite (reindex_onto vFp vFp) -/mFpM => [|i]; last by do 3!case/andP; auto.\nrewrite (eq_bigl (xpredD1 ltv Fp0)) => [|i]; last first.\n  rewrite andbC -!andbA -2!negb_or -vFpId orbC -leq_eqVlt.\n  rewrite andbA -ltnNge; symmetry; case: eqP => [->|].\n    by case: eqP => // ->; rewrite !andbF.\n  by move/eqP=> ni0; rewrite vFpK //eqxx vFp0.\nrewrite -{2}[mFp]/mFpM -[mFpM _ _]big_split -/mFpM.\nby rewrite big1 ?mFp1r //= => i; case/andP; auto.\nQed.\n\n(** Binomial *)\n\nFixpoint bin_rec (m n : nat) {struct m} :=\n  match m, n with\n  | m'.+1, n'.+1 => bin_rec m' n + bin_rec m' n'\n  | _, 0 => 1\n  | 0, _.+1 => 0\n  end.\n\nDefinition bin := nosimpl bin_rec.\n\nLemma binE : bin = bin_rec. Proof. by []. Qed.\n\nLemma bin0 : forall n, bin n 0 = 1.\nProof. by elim. Qed.\n\nLemma binS : forall m n,  bin m.+1 n.+1 = bin m n.+1 + bin m n.\nProof. by []. Qed.\n\nLemma bin_small : forall m n, m < n -> bin m n = 0.\nProof. by elim=> [|m IHm] [|n] // lt_m_n; rewrite binS !IHm // ltnW. Qed.\n\nLemma binn : forall n, bin n n = 1.\nProof. by elim=> [|n IHn] //; rewrite binS bin_small. Qed.\n\nLemma bin_gt0 : forall m n, (0 < bin m n) = (n <= m).\nProof.\nby elim=> [|m IHm] [|n] //; rewrite binS addn_gt0 !IHm orbC ltn_neqAle andKb.\nQed.\n\nLemma bin_fact : forall m n,\n  n <= m -> bin m n * (fact n * fact (m - n)) = fact m.\nProof.\nmove=> m n Hm; rewrite -{1 3}(subnKC Hm) {Hm}.\nelim: n {m}(m - n) => [m | n IHn]; first by rewrite bin0 !mul1n.\nelim=> [|m IHm]; first by rewrite addn0 binn mul1n muln1.\nrewrite {1}addnS binS muln_addl -2!{1}(mulnCA m.+1) {}IHm addSnnS.\nby rewrite -(mulnA n.+1) mulnCA {}IHn addnC -muln_addl.\nQed.\n\nLemma bin_sub : forall n m, n <= m -> bin m n = bin m (m - n).\nProof.\nmove=> n m le_n_m.\napply/eqP; rewrite -(eqn_pmul2r (fact_gt0 (m - n))) -(eqn_pmul2r (fact_gt0 n)).\nby rewrite {1}mulnAC -!mulnA -{6}(subKn le_n_m) !bin_fact ?leq_subr.\nQed.\n\nTheorem pascal : forall a b n,\n  (a + b) ^ n = \\sum_(i < n.+1) (bin n i * (a ^ (n - i) * b ^ i)).\nProof.\nmove=> a b; elim=> [|n IHn]; first by rewrite big_ord_recl big_ord0.\nrewrite big_ord_recr big_ord_recl /= expnS {}IHn muln_addl !big_distrr.\nrewrite big_ord_recl big_ord_recr /= !bin0 !binn !subn0 !subnn !mul1n !muln1.\nrewrite -!expnS addnA; congr (_ + _); rewrite -addnA -big_split; congr (_ + _).\napply: eq_bigr => i _ /=; rewrite 2!(mulnCA b) (mulnCA a) (mulnA a) -!expnS.\nby rewrite -leq_subS ?ltn_ord // -muln_addl -binS.\nQed.\n", "meta": {"author": "Wassasin", "repo": "ssreflect", "sha": "45cf056aa48bec1e7e2bbb77cb4458d4bddf43e4", "save_path": "github-repos/coq/Wassasin-ssreflect", "path": "github-repos/coq/Wassasin-ssreflect/ssreflect-45cf056aa48bec1e7e2bbb77cb4458d4bddf43e4/theories/binomial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.6529479084734043}}
{"text": "\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool ssrint eqtype ssrnat seq choice fintype rat finfun.\nFrom mathcomp Require Import bigop ssralg div ssrnum ssrint.\nFrom mathcomp Require Import fingroup finset. \nFrom mathcomp Require Import cyclic zmodp.\n\n\n\n\nInductive Perm {A : Type} : list A -> list A -> Type :=\n| perm_nil: Perm nil nil\n| perm_skip x l l' : Perm l l' -> Perm (x::l) (x::l')\n| perm_swap x y l : Perm (y::x::l) (x::y::l)\n| perm_trans l l' l'' :\n    Perm l l' -> Perm l' l'' -> Perm l l''.\n\nLemma Perm_refl {A} (xs : list A) : Perm xs xs.\n  induction xs.\n  apply perm_nil.\n  apply perm_skip; done.\nDefined.\n\nHint Resolve Perm_refl.\n\nLemma Perm_sym {A} (xs ys : list A) : Perm xs ys -> Perm ys xs.\n  elim.\n  done.\n  intros; apply perm_skip.\n  apply X.\n  intros; apply perm_swap.\n  intros; eapply perm_trans.\n  apply X0.\n  done.\nDefined.\n\nLemma Perm_rcons {A} (xs : list A) x : Perm (x :: xs) (rcons xs x).\n  induction xs.\n  simpl.\n  done.\n  simpl.\n  eapply perm_trans.\n  apply perm_swap.\n  apply perm_skip.\n  done.\nDefined.\n\nLemma Perm_cats0 {A} (xs : list A) : Perm xs (xs ++ nil).\n  induction xs.\n  done.\n  simpl; apply perm_skip.\n  apply IHxs.\nDefined.\n\n\nLemma Perm_middle {A} (xs ys : list A) x : Perm (x :: xs ++ ys) (xs ++ (x :: ys)).\n  induction xs.\n  simpl.\n  done.\n  simpl.\n  eapply perm_trans.\n  apply perm_swap.\n  apply perm_skip.\n  apply IHxs.\nDefined.\n\nFixpoint rot_rcons {A} (n : nat) (xs : list A) :=\n  match n, xs with\n    | 0, _ => xs\n    | S n, (x :: xs) => rot_rcons n (rcons xs x)\n    | _, _ => xs\n                end.\n\nLemma Perm_rot {A} n (xs : list A) : Perm xs (rot_rcons n xs).\n  move: xs; induction n.\n  simpl.\n  done.\n  simpl.\n  induction xs.\n  done.\n  eapply perm_trans.\n  apply Perm_rcons.\n  apply IHn.\nDefined.\n\n\nLemma Perm_cat_sym {A} (xs ys : list A) : Perm (xs ++ ys) (ys ++ xs).\n  move: ys; induction xs.\n  simpl.\n  induction ys.\n  done.\n  simpl.\n  apply perm_skip.\n  apply IHys.\n  intro; apply Perm_sym.\n  move: (Perm_middle ys xs a) => h.\n  apply Perm_sym in h.\n  eapply perm_trans.\n  apply h.\n  have -> : (a :: xs) ++ ys = a :: xs ++ ys by done.\n  apply perm_skip.\n  apply Perm_sym; apply IHxs.\nDefined.\n\n\nFixpoint Perm_size {A} {xs ys : list A} (H : Perm xs ys) {struct H} :=\n  match H with\n    | perm_nil => 0\n    | perm_skip _ _ _ pf => S (Perm_size pf)\n    | perm_swap _ _ pf => 0\n    | perm_trans _ _ _ pf1 pf2 => S (Perm_size pf1 + Perm_size pf2)\n                                    end.\n\n\n(* split the sequence in two; the nth element will be the head of the second list *)\nFixpoint seq_split {A} (n : nat) (xs : seq A) : seq A * seq A :=\n  match n, xs with\n    | 0, xs => (nil, xs) \n    | (S n), (x :: xs) => let p := seq_split n xs in (x :: p.1, p.2)\n    | (S n), nil => (nil, nil)\n                      end.\n\nLemma seq_splitE  {A} n (xs : seq A) : (seq_split n xs).1 ++ (seq_split n xs).2 = xs.\n  move: xs; induction n.\n  done.\n  induction 0.\n  done.\n  simpl.\n  rewrite -{3}(IHn xs) //=.\nDefined.\n\nLemma Perm_cat2l {A} (l l0 l1 : list A) :\n  Perm l0 l1 -> Perm (l ++ l0) (l ++ l1).\n  intro; induction l.\n  simpl.\n  apply X.\n  simpl; apply perm_skip.\n  apply IHl.\nDefined.\n\n(*\nLemma perm_eq_swap {A : eqType} from to (xs : list A) : perm_eq xs (swap from to xs).\n  rewrite /swap.\n  remember (seq_split from xs) as p1; destruct p1.\n  destruct l0.\n  done.\n  move: (seq_splitE from xs) => <-. \n  rewrite -Heqp1 //=.\n  destruct (from <= to).\n  remember (seq_split (to - from) l0) as p2; destruct p2.\n  move: (seq_splitE (to - from) l0) => <-.\n  rewrite -Heqp2 //=.\n  rewrite perm_cat2l.\n  have -> : s :: l1 ++ l2 = [:: s] ++ l1 ++ l2 by done.\n  rewrite perm_catCA; done.\n\n  remember (seq_split to l) as p2; destruct p2.\n  move: (seq_splitE to l) => <-.\n  rewrite -Heqp2 //=.\n  rewrite -catA.\n  rewrite perm_cat2l.\n  have -> : l2 ++ s :: l0 = l2 ++ [:: s] ++ l0 by done.\n  rewrite perm_catCA; done.\nQed.\n*)\n\n\n\nDefinition swap {A} (from to : nat) (xs : list A) : list A :=\n  match (seq_split from xs) with\n  | (tl, (x :: hd)) =>\n    if from <= to then\n    match (seq_split (to - from) hd) with\n      | (hd0, hd1) => tl ++ hd0 ++ [:: x] ++ hd1\n                         end\n    else\n      match (seq_split to tl) with\n      | (tl0, tl1) => tl0 ++ [:: x] ++ tl1 ++ hd\n      end\n  | _ => xs\n           end.\n\n\n\nLemma Perm_swap {A} from to (xs : list A) : Perm xs (swap from to xs).\n  rewrite /swap.\n  remember (seq_split from xs) as p1; destruct p1.\n  destruct l0.\n  done.\n  move: (seq_splitE from xs) => <-. \n  rewrite -Heqp1 //=.\n  destruct (from <= to).\n  remember (seq_split (to - from) l0) as p2; destruct p2.\n  move: (seq_splitE (to - from) l0) => <-.\n  rewrite -Heqp2 //=.\n  apply Perm_cat2l.\n  apply Perm_middle.\n\n  remember (seq_split to l) as p2; destruct p2.\n  move: (seq_splitE to l) => <-.\n  rewrite -Heqp2 //=.\n  clear.\n  induction l1.\n  simpl.\n  apply Perm_sym.\n  apply Perm_middle.\n  simpl.\n  apply perm_skip.\n  apply IHl1.\nDefined.\n\n\nLemma Perm_swap_irrel {A} from to (xs : list A) : Perm xs (swap from to xs).\n  apply Perm_swap.\nQed.\n\n\nLemma Perm_map {A B} (f : A -> B) (xs ys : list A)  :\n  Perm xs ys -> Perm (map f xs) (map f ys).\n  elim.\n  simpl.\n  done.\n  simpl.\n  intros.\n  apply perm_skip.\n  apply X.\n  intros; simpl.\n  apply perm_swap.\n  intros; simpl in *.\n  eapply perm_trans.\n  apply X.\n  apply X0.\nDefined.\n\nLemma Perm_mem {A : eqType} (xs ys : seq A) :\n  Perm xs ys -> forall x, (x \\in xs) = (x \\in ys).\n  intro.\n  induction X.\n  done.\n  intro; rewrite !in_cons.\n  destruct (eqVneq x0 x).\n  subst.\n  rewrite eq_refl //=.\n  rewrite (negbTE i) //=.\n  intros; simpl; rewrite !in_cons //=.\n  destruct (x0 == y); destruct (x0 == x); destruct (x0 \\in l); done.\n  intros.\n  rewrite -IHX2 //=.\nQed.\n\nFixpoint ofind {A} (xs : seq A) (f : A -> bool) : option nat :=\n  match xs with\n    | nil => None\n    | x :: xs' =>\n      if f x then Some 0%N else\n        match ofind xs' f with\n          | Some n => Some (S n)\n          | None => None\n        end\n          end.\n\nFixpoint ofind_val {A} (xs : seq A) (f : A -> bool) : option A :=\n  match xs with\n    | nil => None\n    | x :: xs' =>\n      if f x then Some x else\n        match ofind_val xs' f with\n          | Some x => Some x\n          | None => None\n        end\n          end.\n\nFixpoint prefix {A : eqType} (xs ys : seq A) : bool :=\n  match xs with\n    | nil => true\n    | x :: xs' =>\n      match ys with\n      | nil => false\n      | y :: ys' =>\n        if x == y then prefix xs' ys' else false\n      end\n        end.\n                      \nLemma prefixP {A : eqType} (xs ys : seq A) : prefix xs ys -> {zs | ys = xs ++ zs}.\n  move: ys.\n  induction xs.\n  simpl.\n  intros; exists ys; done.\n  induction ys.\n  done.\n  simpl.\n  destruct (eqVneq a a0).\n  subst.\n  rewrite eq_refl.\n  intro h; destruct (IHxs _ h).\n  subst.\n  exists x.\n  done.\n  rewrite (negbTE i).\n  done.\nDefined.\n\nLemma prefix_cat {A : eqType} (xs ys : seq A) : prefix xs (xs ++ ys).\n  induction xs.\n  done.\n  simpl.\n  rewrite eq_refl.\n  done.\nDefined.\n\nFixpoint extract_right_cat {A : eqType} (xs ys : seq A) : option (seq A) :=\n  match xs, ys with\n  | nil, nil => Some nil\n  | (x :: xs), nil => None\n  | nil, y :: ys => Some (y :: ys)\n  | (x :: xs), (y :: ys) =>\n    if x == y then\n      extract_right_cat xs ys\n    else\n      None\n  end.\n\nLemma extract_right_catP {A : eqType} (xs ys : seq A) zs :\n  extract_right_cat xs ys = Some zs ->\n  ys = xs ++ zs.\n  move: ys; induction xs.\n  induction ys.\n  simpl.\n  intro H; injection H; done.\n  simpl.\n  intro H; injection H; done.\n  induction ys.\n  simpl.\n  done.\n  simpl.\n  destruct (eqVneq a a0).\n  subst.\n  rewrite eq_refl.\n  move/IHxs.\n  move => ->; done.\n  rewrite (negbTE i).\n  done.\nQed.\n\nDefinition extract_cons {A : eqType} (a : A) (xs : seq A) : option (seq A).\n  destruct xs.\n  apply None.\n  apply (if a == s then Some xs else None).\nDefined.\n\nLemma extract_consP {A : eqType} (a : A) xs ys :\n  extract_cons a xs = Some ys -> xs = a :: ys.\n  induction xs.\n  done.\n  simpl.\n  destruct (eqVneq a a0).\n  destruct e.\n  rewrite eq_refl.\n  intro h; injection h.\n  move => ->.\n  done.\n  rewrite (negbTE i); done.\nQed.\n\n\nDefinition extract_right_cons_cat {A : eqType} (h : A) (xs ys : seq A) : option (seq A) :=\n  match extract_cons h ys with\n    | None => None\n    | Some ys' =>\n      extract_right_cat xs ys'\n                        end.\n\nLemma extract_right_cons_catP {A : eqType} (h : A) xs ys zs :\n  extract_right_cons_cat h xs ys = Some zs ->\n  ys = h :: xs ++ zs.\n  rewrite /extract_right_cons_cat.\n  remember (extract_cons h ys) as o; destruct o; symmetry in Heqo.\n  apply extract_consP in Heqo.\n  rewrite Heqo.\n  move/extract_right_catP.\n  move => ->.\n  done.\n  done.\nQed.\n\nLemma orP_sumbool {b1 b2 : bool} : (b1 || b2) -> {b1} + {b2}.\n  destruct b1.\n  intro; apply left; apply is_true_true.\n  destruct b2.\n  intros; apply right; apply is_true_true.\n  done.\nQed.\n\nLemma Perm_rem_cat_l {A : eqType} (xs ys : seq A) x : x \\in ys ->\n                                                            Perm (xs ++ ys) ((x :: xs) ++ (rem x ys)).\n  move: x ys.\n  induction xs.\n  simpl.\n  induction ys.\n  done.\n  simpl.\n  destruct (eqVneq a x).\n  subst.\n  rewrite eq_refl.\n  intros; apply Perm_refl.\n  rewrite (negbTE i).\n  intros.\n  eapply perm_trans; last first.\n  apply Perm_sym.\n  apply perm_swap.\n  apply perm_skip.\n  apply IHys.\n  rewrite in_cons in H.\n  rewrite eq_sym (negbTE i) in H; done.\n  intros; simpl.\n  eapply perm_trans; last first.\n  apply perm_swap.\n  apply perm_skip.\n  apply IHxs.\n  done.\nQed.", "meta": {"author": "gancherj", "repo": "rellogic", "sha": "8b446184e86b8a97937ead07d07ab8f7ca1e5833", "save_path": "github-repos/coq/gancherj-rellogic", "path": "github-repos/coq/gancherj-rellogic/rellogic-8b446184e86b8a97937ead07d07ab8f7ca1e5833/SeqOps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321936479701, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.6529479066294244}}
{"text": "Require Import GeoCoq.Axioms.parallel_postulates.\nRequire Import GeoCoq.Meta_theory.Parallel_postulates.tarski_s_euclid_remove_degenerated_cases.\nRequire Import GeoCoq.Tarski_dev.Ch12_parallel.\n\nSection SPP_tarski.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma impossible_case_5 : forall P Q R S T U I,\n  BetS P T Q ->\n  BetS R T S ->\n  BetS Q U R ->\n  ~ Col P Q S ->\n  ~ Col P R U ->\n  Par P R Q S ->\n  Par P S Q R ->\n  Bet S Q I ->\n  Bet U I P ->\n  False.\nProof.\nintros P Q R S T U I HPTQ HRTS HQUR HNC HNC' HPar1 HPar2 HSQI HPUI.\napply BetSEq in HPTQ; apply BetSEq in HRTS; apply BetSEq in HQUR.\nassert (HTS : TS Q S P U) by (assert_diffs; spliter; assert_cols; repeat split;\n                                     Col; try (exists I; Col; Between); intro; apply HNC'; ColR).\napply l9_9 in HTS; apply HTS.\napply one_side_transitivity with R.\n\n  {\n  apply l12_6; apply par_not_col_strict with P; Col; Par.\n  }\n\n  {\n  assert (HQS : Q <> S) by (assert_diffs; assumption).\n  assert (HQSQ : Col Q S Q) by Col.\n  assert (HRUQ : Col R U Q) by (spliter; assert_cols; Col).\n  rewrite (l9_19 Q S R U Q HQSQ HRUQ).\n  split; spliter; try (intro; apply HNC; assert_cols; ColR); repeat split; Between.\n  }\nQed.\n\nLemma impossible_case_6 : forall P Q R S T U I,\n  BetS P T Q ->\n  BetS R T S ->\n  BetS Q U R ->\n  ~ Col P Q S ->\n  ~ Col P R U ->\n  Par P R Q S ->\n  Par P S Q R ->\n  Bet S Q I ->\n  Bet I P U ->\n  False.\nProof.\nintros P Q R S T U I HPTQ HRTS HQUR HNC HNC' HPar1 HPar2 HSQI HPUI.\napply BetSEq in HPTQ; apply BetSEq in HRTS; apply BetSEq in HQUR.\napply between_symmetry in HPUI.\ndestruct (inner_pasch S U I Q P HSQI HPUI) as [J [HBet1 HBet2]].\nassert (HParS : Par_strict P S Q U).\n  {\n  apply par_not_col_strict with R.\n\n    {\n    spliter; assert_cols.\n    apply par_col_par with R; Par.\n    ColR.\n    }\n\n    {\n    spliter; assert_cols; ColR.\n    }\n\n    {\n    intro; apply HNC.\n    spliter; assert_cols; ColR.\n    }\n  }\napply HParS; exists J; assert_cols; Col.\nQed.\n\nLemma impossible_case_7 : forall P Q R S T U I,\n  BetS P T Q ->\n  BetS R T S ->\n  BetS Q U R ->\n  ~ Col P Q S ->\n  ~ Col P R U ->\n  Par P R Q S ->\n  Par P S Q R ->\n  Col P U I ->\n  Bet Q I S ->\n  False.\nProof.\nintros P Q R S T U I HPTQ HRTS HQUR HNC HNC' HPar1 HPar2 HPUI HSQI.\napply BetSEq in HPTQ; apply BetSEq in HRTS; apply BetSEq in HQUR.\nelim (eq_dec_points I S); intro HIS; treat_equalities.\n\n  {\n  assert (HParS : Par_strict Q R P I) by (apply par_not_col_strict with P; Col; Par; unfold BetS in *;\n                                          spliter; assert_cols; intro; apply HNC'; ColR).\n  apply HParS; exists U; spliter; assert_cols; Col.\n  }\n\n  {\n  assert (HTS : TS P U Q S) by (assert_diffs; spliter; assert_cols; repeat split;\n                                       Col; try (exists I; Col; Between); intro; apply HNC; ColR).\n  apply l9_9 in HTS; apply HTS.\n  exists R; split.\n\n    {\n    spliter; assert_diffs; assert_cols.\n    split; try (intro; apply HNC; ColR).\n    split; try (intro; apply HNC; ColR).\n    exists U; Col; Between.\n    }\n\n    {\n    destruct HPTQ as [HPTQ HDiff1].\n    destruct HQUR as [HQUR HDiff2].\n    apply between_symmetry in HQUR.\n    destruct (inner_pasch R P Q U T HQUR HPTQ) as [J [HPJU HRJT]].\n    assert (HRJS : Bet R J S) by (spliter; eBetween).\n    spliter; assert_diffs; assert_cols.\n    split; try (intro; apply HNC; ColR).\n    split; try (intro; apply HNC; ColR).\n    exists J; split; Col; Between.\n    }\n  }\nQed.\n\nLemma impossible_case_8 : forall P Q R S T U I,\n  BetS P T Q ->\n  BetS R T S ->\n  BetS Q U R ->\n  ~ Col P Q S ->\n  ~ Col P R U ->\n  Par P R Q S ->\n  Par P S Q R ->\n  Col P U I ->\n  Bet I S Q ->\n  False.\nProof.\nintros P Q R S T U I HPTQ HRTS HQUR HNC HNC' HPar1 HPar2 HPUI HSQI.\napply BetSEq in HPTQ; apply BetSEq in HRTS; apply BetSEq in HQUR.\nelim HPUI; clear HPUI; intro HPUI.\n\n  {\n  assert (H : Par_strict P S Q R) by (apply par_not_col_strict with Q; Col; Par; unfold BetS in *;\n                                      spliter; assert_cols; intro; apply HNC'; ColR); apply H.\n  apply between_symmetry in HSQI.\n  destruct (inner_pasch P Q I U S HPUI HSQI) as [J [HQJU HPJS]]; exists J.\n  spliter; assert_diffs; assert_cols; split; Col; ColR.\n  }\n\n  {\n  elim HPUI; clear HPUI; intro HPUI.\n\n    {\n    assert (H : Par_strict P S Q R) by (apply par_not_col_strict with Q; Col; Par; unfold BetS in *;\n                                        spliter; assert_cols; intro; apply HNC'; ColR); apply H.\n    apply between_symmetry in HSQI.\n    destruct (outer_pasch U Q I P S HPUI HSQI) as [J [HQJU HPSJ]]; exists J.\n    spliter; assert_diffs; assert_cols; split; Col; ColR.\n    }\n\n    {\n    assert (H : Par_strict P R Q S) by (apply par_not_col_strict with Q; Col; Par; unfold BetS in *;\n                                        spliter; assert_cols; intro; apply HNC'; ColR); apply H.\n    destruct HQUR as [HQUR HDiff].\n    destruct (outer_pasch Q I U R P HQUR HPUI) as [J [HQJI HRPJ]]; exists J.\n    spliter; assert_diffs; assert_cols; split; Col.\n    elim (eq_dec_points Q I); intro HQI; treat_equalities; Col; ColR.\n    }\n  }\nQed.\n\nLemma strong_parallel_postulate_implies_tarski_s_euclid_aux :\n  strong_parallel_postulate ->\n  (forall A B C D T,\n   A <> B ->\n   A <> C ->\n   A <> D ->\n   A <> T ->\n   B <> C ->\n   B <> D ->\n   B <> T ->\n   C <> D ->\n   C <> T ->\n   D <> T ->\n   ~ Col A B C ->\n   Bet A D T ->\n   Bet B D C ->\n   exists B', exists B'', exists MB, exists X, Bet A B X /\\ Par_strict B C T X /\\\n   BetS B MB T /\\ BetS B' MB B'' /\\\n   Cong B MB T MB /\\ Cong B' MB B'' MB /\\\n   Col B B' D /\\ Bet B'' T X /\\\n   B <> B' /\\ B'' <> T).\nProof.\nintros HSPP A B C D T HAB HAC HAD HAT HBC HBD HBT HCD HCT HDT HABC HADT HBDC.\ndestruct (symmetric_point_construction D B) as [B' HB'].\ndestruct (midpoint_distinct_2 B D B' HBD HB') as [HB'D HBB'].\ndestruct HB' as [HBDB' HCong1].\napply between_symmetry in HADT.\napply between_symmetry in HBDB'.\ndestruct (outer_pasch T B' D A B HADT HBDB') as [B''' [HTB'''B' HABB''']].\ndestruct (midpoint_existence B T) as [MB HMB].\ndestruct (midpoint_distinct_1 MB B T HBT HMB) as [HBMB HMBT].\ndestruct HMB as [HBMBT HCong2].\ndestruct (symmetric_point_construction B' MB) as [B'' HB''].\nassert (HB'MB : MB <> B').\n  {\n  assert (H : ~ Col B' D MB) by (intro; apply HABC; assert_cols; ColR).\n  intro; treat_equalities; apply H; Col.\n  }\ndestruct (midpoint_distinct_2 MB B' B'' HB'MB HB'') as [HB'B'' HB''MB].\ndestruct HB'' as [HB'MBB'' HCong3].\nassert (H1 : BetS B MB T) by (repeat split; Between).\nassert (H2 : BetS B' MB B'') by (repeat split; Between).\nassert (HB'T : B' <> T).\n  {\n  assert (H : ~ Col B B' T) by (intro; apply HABC; assert_cols; ColR).\n  intro; treat_equalities; apply H; Col.\n  }\nassert (HB'B''' : B' <> B''').\n  {\n  assert (H : ~ Col A B B') by (intro; apply HABC; assert_cols; ColR).\n  intro; treat_equalities; apply H; Col.\n  }\nassert (HB'''T : B''' <> T).\n  {\n  assert (H : ~ Col A B T) by (intro; apply HABC; assert_cols; ColR).\n  intro; treat_equalities; apply H; Col.\n  }\nassert (H3 : BetS T B''' B') by (repeat split; Between).\nassert (H4 : ~ Col B T B'') by (intro; apply HABC; assert_cols; ColR).\nassert (H5 : Cong B MB T MB) by Cong.\nassert (H6 : Cong B' MB B'' MB) by Cong.\ndestruct (HSPP B T B' B'' MB B''') as [X [HBetS HX]];\nCol; Cop; try (intro; apply H4; assert_diffs; assert_cols; ColR).\nassert (HNC : ~ Col B B' B''') by (intro; assert_diffs; assert_cols; apply H4; ColR).\nassert (HPar1 : Par B B' T B'') by (unfold BetS in *; spliter; apply l12_17 with MB; try split; Col).\nassert (HPar2 : Par B B'' T B')\n  by (unfold BetS in *; spliter; assert_diffs; apply l12_17 with MB; try split; Between; Cong).\nelim HBetS; clear HBetS; intro HBetS.\n\n  {\n  elim HX; clear HX; intro HX.\n\n    {\n    assert (H : BetS B'' T X).\n      {\n      repeat split; try (intro; treat_equalities); Col.\n      apply H4; assert_diffs; assert_cols; ColR.\n      }\n    clear HBetS; rename H into HBetS.\n    assert (H : BetS B B''' X).\n      {\n      repeat split; try (intro; treat_equalities); Col; unfold BetS in *; spliter;\n      apply H4; assert_diffs; assert_cols; ColR.\n      }\n    clear HX; rename H into HX.\n    apply BetSEq in HBetS; destruct HBetS as [HB''TX [HB''T [HB''X HBTX]]].\n    exists B'; exists B''; exists MB; exists X.\n    split; unfold BetS in HX; spliter; eBetween.\n    assert (HPar : Par B' B B'' T) by (apply l12_17 with MB; try split; Between; Cong).\n    assert (HPar' : Par B C B'' T)\n      by (apply par_symmetry; apply par_col_par with B'; Par; assert_cols; ColR).\n    split.\n\n      {\n      apply par_not_col_strict with T; Col.\n\n        {\n        apply par_col_par with B''; Par.\n        assert_cols; ColR.\n        }\n\n        {\n        intro; apply HABC; assert_cols; ColR.\n        }\n      }\n\n      {\n      repeat (split; try assumption); unfold BetS in *; spliter; assert_cols; Col.\n      }\n    }\n\n    {\n    elim HX; clear HX; intro HX.\n\n      {\n      exfalso; apply impossible_case_5 with B T B' B'' MB B''' X; spliter; assumption.\n      }\n\n      {\n      exfalso; apply impossible_case_6 with B T B' B'' MB B''' X; spliter; assumption.\n      }\n    }\n  }\n\n  {\n  elim HBetS; clear HBetS; intro HBetS.\n\n    {\n    exfalso; apply impossible_case_7 with B T B' B'' MB B''' X; spliter; assumption.\n    }\n\n    {\n    exfalso; apply impossible_case_8 with B T B' B'' MB B''' X; spliter; assumption.\n    }\n  }\n\nQed.\n\nLemma strong_parallel_postulate_implies_tarski_s_euclid :\n  strong_parallel_postulate ->\n  tarski_s_parallel_postulate.\nProof.\nunfold tarski_s_parallel_postulate.\nintro HSPP; apply tarski_s_euclid_remove_degenerated_cases.\nintros A B C D T HAB HAC HAD HAT HBC HBD HBT HCD HCT HDT HABC HADT HBDC.\ndestruct (strong_parallel_postulate_implies_tarski_s_euclid_aux HSPP A B C D T)\nas [B' [B'' [MB [X [HABX [HPar' [HBet1 [HBet2 [HCong1 [HCong2 [HBB'D [HB''TX [HBB' HB''T]]]]]]]]]]]]];\ndestruct (strong_parallel_postulate_implies_tarski_s_euclid_aux HSPP A C B D T)\nas [C' [C'' [MC [Y [HACY [HPar [HBet3 [HBet4 [HCong3 [HCong4 [HCC'D [HC''TY [HCC' HC''T]]]]]]]]]]]]];\nBetween; Col.\nclear HBet3; clear HBet4; clear HCong3; clear HCong4;\nclear MC; clear HC''TY; clear HC''T; clear HPar'.\nexists X; exists Y; repeat split; try assumption.\nelim (col_dec X T Y); intro HXTY.\n\n  {\n  apply between_symmetry in HACY.\n  assert (HU := outer_pasch Y B C A D HACY HBDC); destruct HU as [U [HYUB HADU]].\n  apply between_symmetry in HABX.\n  assert (HV := outer_pasch X Y B A U HABX HYUB); destruct HV as [V [HXVY HAUV]].\n  assert (HAX : A <> X) by (intro; treat_equalities; Col).\n  assert (HAY : A <> Y) by (intro; treat_equalities; Col).\n  assert (HAXY : ~ Col A X Y) by (intro; assert_cols; apply HABC; ColR).\n  assert (HAU : A <> U) by (intro; treat_equalities; Col).\n  assert (HEq : T = V) by (assert_cols; apply l6_21 with X Y A D; Col; ColR); subst; assumption.\n  }\n\n  {\n  assert (HNC : ~ Col T B'' Y) by (intro; apply HXTY; unfold BetS in *; spliter; assert_cols; ColR).\n  assert (HCop : Coplanar T B B'' Y).\n    {\n    apply coplanar_pseudo_trans with A B C; assert_cols; Cop.\n\n      {\n      exists D; assert_cols; Col5.\n      }\n\n      {\n      assert (HABD : ~ Col D A B) by (intro; assert_cols; apply HABC; ColR).\n      apply coplanar_trans_1 with D; [Cop..|].\n      apply ts__coplanar.\n      apply l9_8_2 with X.\n\n        {\n        assert (HAX : A <> X) by (intro; treat_equalities; apply HABC; Col).\n        split; try (intro; assert_cols; apply HABC; ColR).\n        split; try (intro; assert_cols; apply HABC; ColR).\n        exists T; split; Col; Between.\n        }\n\n        {\n        apply invert_one_side.\n        assert (HADA : Col A D A) by Col.\n        assert (HXBA : Col X B A) by (assert_cols; Col).\n        rewrite (l9_19 A D X B A HADA HXBA).\n        assert (HAX : A <> X) by (intro; treat_equalities; apply HABC; Col).\n        split; try (intro; assert_cols; apply HABC; ColR); split; auto.\n        }\n      }\n    }\n  destruct (HSPP T B B'' B' MB Y) as [I [HCol1 HCol2]]; Cong;\n  try (unfold BetS in *; spliter; repeat (split; try Between)).\n  exfalso; apply HPar; exists I; split; Col.\n  elim (eq_dec_points I B); intro HBI; subst; Col.\n  unfold BetS in *; spliter; assert_cols; ColR.\n  }\nQed.\n\nEnd SPP_tarski.", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/GeoCoq/Meta_theory/Parallel_postulates/SPP_tarski.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478254, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.6529478879066828}}
{"text": "Require Import Lists.List.\nRequire Import Coq.Arith.PeanoNat.\n\nRequire Import Top.FinSet.Distinct.\nRequire Import Top.FinSet.Remove.\n\n(**\n\n  * Injections between lists\n\n *)\nSection lists.\n  Variables A B : Type.\n  Variable f : A -> B.\n  Variable aa : list A.\n\n  Definition inj_on_list : Prop :=\n    forall a a', In a aa -> In a' aa -> f a = f a' -> a = a'.\n\n  Variable bb : list B.\n\n  Definition is_list_map : Prop :=\n    forall a, In a aa -> In (f a) bb.\n\n  Definition surj_on_list : Prop :=\n    forall b, In b bb -> In b (map f aa).\n\nEnd lists.\n\nArguments inj_on_list {A B} f aa.\nArguments is_list_map {A B} f aa bb.\nArguments surj_on_list {A B} f aa bb.\n\nLemma inj_on_list_uncons {A B : Type} {f : A -> B} {a aa}\n  : inj_on_list f (a :: aa) -> inj_on_list f aa.\nProof.\n  unfold inj_on_list; auto with datatypes.\nQed.\n\nLemma is_list_map_uncons {A B : Type} {f : A -> B} {a aa bb}\n      (decB : forall x y : B, {x = y} + {x <> y})\n  : is_list_map f (a :: aa) bb ->\n    ~ In a aa ->\n    inj_on_list f (a :: aa) ->\n    is_list_map f aa (remove decB (f a) bb).\nProof.\n  unfold is_list_map.\n  intros lmH notH injH a' inH.\n  apply in_remove; auto with datatypes.\n  unfold inj_on_list in injH.\n  intro feqH.\n  rewrite (injH a' a (in_cons a a' aa inH) (in_eq a aa) feqH) in inH.\n  contradiction.\nQed.\n\nLemma list_map_cons_first_in_tgt {A B : Type} {f : A -> B} {a aa bb}\n  : is_list_map f (a :: aa) bb -> In (f a) bb.\nProof.\n  auto using (in_eq  a aa).\nQed.\n\nLemma distinct_inj_induct\n      {A B : Type} {f : A -> B} {aa bb}\n      (decB : forall x y : B, {x = y} + {x <> y})\n      P\n  : (forall bb, P nil bb) ->\n    (forall a aa bb, distinct aa ->\n                     distinct bb ->\n                     ~ In a aa ->\n                     is_list_map f (a :: aa) bb ->\n                     P aa (remove decB (f a) bb) ->\n                     P (a :: aa) bb) ->\n    distinct aa ->\n    distinct bb ->\n    is_list_map f aa bb ->\n    inj_on_list f aa ->\n    P aa bb.\nProof.\n  intros nilH stepH; revert bb.\n  induction aa as [ | a aa IH ]; auto.\n  intros bb distaH distbH lmH injH.\n  destruct distaH as [ norepaH distaH ].\n  specialize (IH (remove decB (f a) bb) distaH\n                 (distinct_remove decB (f a) distbH)\n                 (is_list_map_uncons decB lmH norepaH injH)\n                 (inj_on_list_uncons injH)).\n  auto.\nQed.\n\nLemma inj_on_list_length\n      {A B : Type} {f : A -> B} (aa : list A) (bb : list B)\n      (decB : forall x y : B, {x = y} + {x <> y})\n  : distinct aa ->\n    distinct bb ->\n    is_list_map f aa bb ->\n    inj_on_list f aa ->\n    length aa <= length bb.\nProof.\n  apply (distinct_inj_induct decB (fun aa bb => length aa <= length bb));\n    auto using le_0_n.\n  clear aa bb; intros a aa bb distaH distbH norepaH lmH lenH.\n  rewrite (length_distinct_remove_in\n             decB distbH (list_map_cons_first_in_tgt lmH)).\n  simpl; auto using le_n_S.\nQed.\n\nLemma surj_on_list_nil {A B : Type} (f : A -> B) (l : list A)\n  : surj_on_list f l nil.\nProof.\n  unfold surj_on_list; intros; contradiction.\nQed.\n\n(*\n\n  Now we want to show how to get a surjection from an injection. If I\n  have an injective map between two equal length lists (with no\n  duplicates) then it follows that the map is actually surjective.\n\n*)\nLemma inj_on_eql_list_is_surj\n      {A B : Type} {f : A -> B}\n      (aa : list A) (bb : list B)\n      (decB : forall x y : B, {x = y} + {x <> y})\n  : distinct aa -> distinct bb ->\n    is_list_map f aa bb ->\n    inj_on_list f aa ->\n    length aa = length bb ->\n    surj_on_list f aa bb.\nProof.\n  apply (distinct_inj_induct\n           decB\n           (fun aa bb => length aa = length bb -> surj_on_list f aa bb));\n    clear aa bb.\n  - intros bb lenH.\n    enough (bbH : bb = nil); try (rewrite bbH; auto using surj_on_list_nil).\n    apply length_zero_iff_nil; auto.\n  - intros a aa bb distaH distbH norepaH lmH stepH lenH.\n    rewrite (length_distinct_remove_in\n               decB distbH (list_map_cons_first_in_tgt lmH)) in lenH.\n    simpl in lenH.\n    specialize (stepH (eq_add_S _ _ lenH)); clear lenH.\n    intros b inH; unfold surj_on_list in stepH; specialize (stepH b).\n    rewrite map_cons.\n    destruct (decB b (f a)) as [ -> | neH ].\n    + apply in_eq.\n    + apply in_cons; apply stepH.\n      apply (in_remove decB inH neH).\nQed.\n", "meta": {"author": "rswarbrick", "repo": "eder84", "sha": "682fa4d81ba690a88ea9b6eedee655901c8189b6", "save_path": "github-repos/coq/rswarbrick-eder84", "path": "github-repos/coq/rswarbrick-eder84/eder84-682fa4d81ba690a88ea9b6eedee655901c8189b6/FinSet/InjList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603725, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6529351832158207}}
{"text": "(* Software Foundations *)\n(* Exercice 1 star, not_both_true_and_false *)\n\nTheorem not_both_true_and_false: forall P: Prop, ~(P /\\ ~ P).\nProof.\n    intros.\n    unfold not.\n    intros.\n    inversion H.\n    apply H1 in H0.\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/not_both_true_and_false.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6529351742224099}}
{"text": "Require Import Arith.Arith.\nRequire Import Bool.Bool.\nRequire Export Coq.Strings.String.\nRequire Import Logic.FunctionalExtensionality.\nRequire Import Lists.List.\nRequire Import Relations String.\nImport ListNotations.\n\nModule Maps.\n  Definition eqb_string (x y : string) : bool :=\n    if string_dec x y then true else false.\n\n  Theorem eqb_string_refl : forall s : string, true = eqb_string s s.\n  Proof.\n    intros s. unfold eqb_string.\n    destruct (string_dec s s) as [Hs_eq | Hs_not_eq].\n    - reflexivity.\n    - destruct Hs_not_eq. reflexivity.\n  Qed.\n\n  Theorem eqb_string_true_iff : forall x y : string,\n    eqb_string x y = true <-> x = y.\n  Proof.\n    intros x y.\n    unfold eqb_string.\n    destruct (string_dec x y) as [Hs_eq | Hs_not_eq].\n    - rewrite Hs_eq. split. reflexivity. reflexivity.\n    - split.\n      + intros contra. discriminate contra.\n      + intros H. exfalso. apply Hs_not_eq. apply H.\n  Qed.\n\n  Theorem eqb_string_false_iff : forall x y : string,\n    eqb_string x y = false <-> x <> y.\n  Proof.\n    intros x y. rewrite <- eqb_string_true_iff.\n    rewrite not_true_iff_false. reflexivity. Qed.\n\n  (** This corollary follows just by rewriting: *)\n\n  Theorem false_eqb_string : forall x y : string,\n    x <> y -> eqb_string x y = false.\n  Proof.\n    intros x y. rewrite eqb_string_false_iff.\n    intros H. apply H. Qed.\n  \n  Definition total_map (A : Type) := string -> A.\n\n  Definition t_empty {A : Type} (v : A) : total_map A :=\n  (fun _ => v).\n\n  Definition t_update {A : Type} (m : total_map A)\n                    (x : string) (v : A) :=\n  fun x' => if eqb_string x x' then v else m x'.\n\n  Notation \"'_' '!->' v\" := (t_empty v)\n  (at level 100, right associativity).\n\n  Notation \"x '!->' v ';' m\" := (t_update m x v)\n                                (at level 100, v at next level, right associativity).\n\n  Lemma t_apply_empty : forall (A : Type) (x : string) (v : A),\n    (_ !-> v) x = v.\n  Proof ltac:(reflexivity).\n\n  Lemma t_update_eq : forall (A : Type) (m : total_map A) x v,\n    (x !-> v ; m) x = v.\n  Proof.\n    intros. unfold t_update.\n    rewrite <- eqb_string_refl; auto.\n  Qed.\n\n  Theorem t_update_neq : forall (A : Type) (m : total_map A) x1 x2 v,\n    x1 <> x2 ->\n    (x1 !-> v ; m) x2 = m x2.\n  Proof with auto.\n    intros **. unfold t_update.\n    rewrite false_eqb_string...\n  Qed.\n\n  Lemma t_update_shadow : forall (A : Type) (m : total_map A) x v1 v2,\n  (x !-> v2 ; x !-> v1 ; m) = (x !-> v2 ; m).\n  Proof.\n    intros. unfold t_update.\n    extensionality y.\n    destruct (eqb_string x y); auto.\n  Qed.\n\n  Lemma eqb_stringP : forall x y : string,\n    reflect (x = y) (eqb_string x y).\n  Proof with auto.\n    intros. destruct (eqb_string x y) eqn:X;\n    constructor;\n    [ apply eqb_string_true_iff\n    | apply eqb_string_false_iff ]...\n  Qed.\n\n  Theorem t_update_same : forall (A : Type)\n      (m : total_map A) x,\n    (x !-> m x ; m) = m.\n  Proof.\n    intros. unfold t_update. extensionality y.\n    destruct (eqb_stringP x y) as [<- |]; auto.\n  Qed.\n\n  Theorem t_update_permute : forall (A : Type)\n      (m : total_map A) v1 v2 x1 x2,\n      x2 <> x1 ->\n    (x1 !-> v1 ; x2 !-> v2 ; m)\n    =\n    (x2 !-> v2 ; x1 !-> v1 ; m).\n  Proof with auto.\n    intros. unfold t_update. extensionality y.\n    destruct (eqb_stringP x1 y) as [<-|];\n    [rewrite false_eqb_string|]...\n  Qed.\n\n  Definition partial_map (A : Type) := total_map (option A).\n\n  Definition empty {A : Type} : partial_map A :=\n    t_empty None.\n\n  Definition update {A : Type} (m : partial_map A)\n            (x : string) (v : A) :=\n    (x !-> Some v ; m).\n\n  (** We introduce a similar notation for partial maps: *)\n  Notation \"x '|->' v ';' m\" := (update m x v)\n    (at level 100, v at next level, right associativity).\n\n  (** We can also hide the last case when it is empty. *)\n  Notation \"x '|->' v\" := (update empty x v)\n    (at level 100).\n\n  Lemma apply_empty : forall (A : Type) (x : string),\n    @empty A x = None.\n  Proof.\n    intros. unfold empty. rewrite t_apply_empty.\n    reflexivity.\n  Qed.\n\n  Lemma update_eq : forall (A : Type) (m : partial_map A) x v,\n    (x |-> v ; m) x = Some v.\n  Proof.\n    intros. unfold update. rewrite t_update_eq.\n    reflexivity.\n  Qed.\n\n  Theorem update_neq : forall (A : Type) (m : partial_map A) x1 x2 v,\n    x2 <> x1 ->\n    (x2 |-> v ; m) x1 = m x1.\n  Proof.\n    intros A m x1 x2 v H.\n    unfold update. rewrite t_update_neq. reflexivity.\n    apply H. Qed.\n\n  Lemma update_shadow : forall (A : Type) (m : partial_map A) x v1 v2,\n    (x |-> v2 ; x |-> v1 ; m) = (x |-> v2 ; m).\n  Proof.\n    intros A m x v1 v2. unfold update. rewrite t_update_shadow.\n    reflexivity.\n  Qed.\n\n  Theorem update_same : forall (A : Type) (m : partial_map A) x v,\n    m x = Some v ->\n    (x |-> v ; m) = m.\n  Proof.\n    intros A m x v H. unfold update. rewrite <- H.\n    apply t_update_same.\n  Qed.\n\n  Theorem update_permute : forall (A : Type) (m : partial_map A)\n                                  x1 x2 v1 v2,\n    x2 <> x1 ->\n    (x1 |-> v1 ; x2 |-> v2 ; m) = (x2 |-> v2 ; x1 |-> v1 ; m).\n  Proof.\n    intros A m x1 x2 v1 v2. unfold update.\n    apply t_update_permute.\n  Qed.\n\n  Definition inclusion {A : Type} (m m' : partial_map A) :=\n  forall x v, m x = Some v -> m' x = Some v.\n\n  (** We then show that map update preserves map inclusion, that is: *)\n\n  Lemma inclusion_update : forall (A : Type) (m m' : partial_map A)\n                                  (x : string) (vx : A),\n    inclusion m m' ->\n    inclusion (x |-> vx ; m) (x |-> vx ; m').\n  Proof.\n    unfold inclusion.\n    intros A m m' x vx H.\n    intros y vy.\n    destruct (eqb_stringP x y) as [Hxy | Hxy].\n    - rewrite Hxy.\n      rewrite update_eq. rewrite update_eq. intro H1. apply H1.\n    - rewrite update_neq. rewrite update_neq.\n      + apply H.\n      + apply Hxy.\n      + apply Hxy.\n  Qed.\n\n  Corollary inclusion_empty :\n      forall (X: Type) (m: partial_map X),\n    inclusion empty m.\n  Proof ltac:(inversion 1).\n\n  Hint Resolve inclusion_empty : core.\n\nEnd    Maps.\n\nImport Maps.\nLtac inv H := inversion H; subst; clear H.\nCreate HintDb stlcabDB.\n\nInductive multi {X : Type} (R : relation X) : relation X :=\n  | multi_refl : forall (x : X), multi R x x\n  | multi_step : forall (x y z : X),\n                    R x y ->\n                    multi R y z ->\n                    multi R x z.\n\nInductive ty : Type :=\n  | Ty_Bool  : ty\n  | Ty_Arrow : ty -> ty -> ty.\n\nInductive tm : Type :=\n  | tm_var   : string -> tm\n  | tm_app   : tm -> tm -> tm\n  | tm_abs   : string -> ty -> tm -> tm\n  | tm_true  : tm\n  | tm_false : tm\n  | tm_if    : tm -> tm -> tm -> tm.\n\nDeclare Custom Entry stlc.\nNotation \"<{ e }>\" := e (e custom stlc at level 99).\nNotation \"( x )\" := x (in custom stlc, x at level 99).\nNotation \"x\" := x (in custom stlc at level 0, x constr at level 0).\nNotation \"S -> T\" := (Ty_Arrow S T) (in custom stlc at level 50, right associativity).\nNotation \"x y\" := (tm_app x y) (in custom stlc at level 1, left associativity).\nNotation \"\\ x : t , y\" :=\n  (tm_abs x t y) (in custom stlc at level 90, x at level 99,\n                     t custom stlc at level 99,\n                     y custom stlc at level 99,\n                     left associativity).\nCoercion tm_var : string >-> tm.\n\nNotation \"'Bool'\" := Ty_Bool (in custom stlc at level 0).\nNotation \"'if' x 'then' y 'else' z\" :=\n  (tm_if x y z) (in custom stlc at level 89,\n                    x custom stlc at level 99,\n                    y custom stlc at level 99,\n                    z custom stlc at level 99,\n                    left associativity).\nNotation \"'true'\"  := true (at level 1).\nNotation \"'true'\"  := tm_true (in custom stlc at level 0).\nNotation \"'false'\"  := false (at level 1).\nNotation \"'false'\"  := tm_false (in custom stlc at level 0).\n\n(* ################################################################# *)\n(** * Operational Semantics *)\n\n(** To define the small-step semantics of STLC terms, we begin,\n    as always, by defining the set of values.  Next, we define the\n    critical notions of _free variables_ and _substitution_, which are\n    used in the reduction rule for application expressions.  And\n    finally we give the small-step relation itself. *)\n\n(* ================================================================= *)\n(** ** Values *)\n\n\nInductive value : tm -> Prop :=\n  | v_abs   : forall x T2 t1, value <{\\x:T2, t1}>\n  | v_true  : value <{true}>\n  | v_false : value <{false}>.\n\nHint Constructors value : core.\n\nReserved Notation \"'[' x ':=' s ']' t\" (in custom stlc at level 20, x constr).\n\n(* This is not capture avoiding!\n\n      (x := z) λz.x ==> λz.z\n\n   [TAPL]\n   we've turned the constant function λz.x into the identity function!\n   Again, this occurred only because we happened to choose z as the\n   name of the bound variable in the constant function, so something\n   is clearly still wrong. *)\n(* Fixpoint subst (x : string) (s : tm) (t : tm) : tm :=\n  match t with\n  | tm_var y                  => if eqb_string x y then s else t\n  | <{\\y:T, t1}>              => if eqb_string x y\n                                 then t else <{\\y:T, [x:=s] t1}>\n  | <{t1 t2}>                 => <{([x:=s] t1) ([x:=s] t2)}>\n  | <{true}>                  => <{true}>\n  | <{false}>                 => <{false}>\n  | <{if t1 then t2 else t3}> => <{if ([x:=s] t1) then ([x:=s] t2) else ([x:=s] t3)}>\n  end\n\nwhere \"'[' x ':=' s ']' t\" := (subst x s t) (in custom stlc). *)\n\nInductive appears_free_in (x : string) : tm -> Prop :=\n  | afi_var : appears_free_in x <{x}>\n  | afi_app1 : forall t1 t2,\n      appears_free_in x t1 ->\n      appears_free_in x <{t1 t2}>\n  | afi_app2 : forall t1 t2,\n      appears_free_in x t2 ->\n      appears_free_in x <{t1 t2}>\n  | afi_abs : forall y T1 t1,\n      y <> x ->\n      appears_free_in x t1 ->\n      appears_free_in x <{\\y:T1, t1}>\n  | afi_if1 : forall t1 t2 t3,\n      appears_free_in x t1 ->\n      appears_free_in x <{if t1 then t2 else t3}>\n  | afi_if2 : forall t1 t2 t3,\n      appears_free_in x t2 ->\n      appears_free_in x <{if t1 then t2 else t3}>\n  | afi_if3 : forall t1 t2 t3,\n      appears_free_in x t3 ->\n      appears_free_in x <{if t1 then t2 else t3}>.\nHint Constructors appears_free_in : core.\n\n\n\n\nReserved Notation \"t '-->' t'\" (at level 40).\n\nInductive step : tm -> tm -> Prop :=\n  | ST_AppAbs : forall x T2 t1 v2,\n         value v2 ->\n         <{(\\x:T2, t1) v2}> --> <{ [x:=v2]t1 }>\n  | ST_App1 : forall t1 t1' t2,\n         t1 --> t1' ->\n         <{t1 t2}> --> <{t1' t2}>\n  | ST_App2 : forall v1 t2 t2',\n         value v1 ->\n         t2 --> t2' ->\n         <{v1 t2}> --> <{v1  t2'}>\n  | ST_IfTrue : forall t1 t2,\n      <{if true then t1 else t2}> --> t1\n  | ST_IfFalse : forall t1 t2,\n      <{if false then t1 else t2}> --> t2\n  | ST_If : forall t1 t1' t2 t3,\n      t1 --> t1' ->\n      <{if t1 then t2 else t3}> --> <{if t1' then t2 else t3}>\n\nwhere \"t '-->' t'\" := (step t t').\n\nHint Constructors step : core.\n\nNotation multistep := (multi step).\nNotation \"t1 '-->*' t2\" := (multistep t1 t2) (at level 40).\n(* ################################################################# *)\n(** * Typing *)\n\n(** Next we consider the typing relation of the STLC. *)\n\n(* ================================================================= *)\n(** ** Contexts *)\n\n(** _Question_: What is the type of the term \"[x y]\"?\n\n    _Answer_: It depends on the types of [x] and [y]!\n\n    I.e., in order to assign a type to a term, we need to know\n    what assumptions we should make about the types of its free\n    variables.\n\n    This leads us to a three-place _typing judgment_, informally\n    written [Gamma |- t \\in T], where [Gamma] is a\n    \"typing context\" -- a mapping from variables to their types. *)\n\n(** Following the usual notation for partial maps, we write [(X |->\n    T, Gamma)] for \"update the partial function [Gamma] so that it\n    maps [x] to [T].\" *)\n\nDefinition context := partial_map ty.\n\n(* ================================================================= *)\n(** ** Typing Relation *)\n\n\nReserved Notation \"Gamma '|-' t '\\in' T\"\n            (at level 101,\n             t custom stlc, T custom stlc at level 0).\n\nInductive has_type : context -> tm -> ty -> Prop :=\n  | T_Var : forall G x T1\n      (IH: G x = Some T1),\n      G |- x \\in T1\n  | T_Abs : forall G x T1 T2 t1\n      (IH: x |-> T2 ; G |- t1 \\in T1),\n      G |- \\x:T2, t1 \\in (T2 -> T1)\n  | T_App : forall T1 T2 G t1 t2\n      (IH1: G |- t1 \\in (T2 -> T1))\n      (IH2: G |- t2 \\in T2),\n      G |- t1 t2 \\in T1\n  | T_True : forall G,\n       G |- true \\in Bool\n  | T_False : forall G,\n       G |- false \\in Bool\n  | T_If : forall t1 t2 t3 T1 G\n       (IH1: G |- t1 \\in Bool)\n       (IH2: G |- t2 \\in T1)\n       (IH3: G |- t3 \\in T1),\n       G |- if t1 then t2 else t3 \\in T1\n\nwhere \"G '|-' t '\\in' T\" := (has_type G t T).\n\nHint Constructors has_type : core.\n\nTheorem t__unique_typ : forall t G T T'\n    (tT: G |- t \\in T) (tT': G |- t \\in T'),\n  T = T'.\nProof with eauto.\n  induction t; intros.\n  all: inv tT; inv tT'...\n  - rewrite IH0 in IH. injection IH...\n  - rewrite (IHt2 _ _ _ IH3 IH2) in IH0.\n    pose proof (IHt1 _ _ _ IH1 IH0). inv H...\n  - rewrite (IHt _ _ _ IH IH0)...\nQed.\n\nTheorem v_val_Bool__tof : forall v G\n    (valv: value v)\n    (vBool: G |- v \\in Bool),\n  v = <{true}> \\/ v = <{false}>.\nProof with eauto.\n  intros. inv valv...\n  inv vBool.\nQed.\n\n\n\n(* Theorem value__closed : forall v G T\n    (valv: value v)\n    (vT: G |- v \\in T),\n  empty |- v \\in T.\nProof with eauto.\n  induction 2;\n  try solve [inv valv]...\n\n  econstructor. clear - vT.\n  inv vT...\n  + econstructor. erewrite <- update_shadow ...\n  update_shadow\n  inv vT.\n  - inv valv.\n  -\nQed. *)\n\nTheorem progress : forall t T\n    (twt: empty |- t \\in T),\n  value t \\/ exists t', t --> t'.\nProof with eauto.\n  remember empty as G.\n  induction 1...\n  - rewrite HeqG in IH. inv IH.\n  - rename IHtwt1 into IH1, IHtwt2 into IH2.\n    specialize (IH1 HeqG). specialize (IH2 HeqG).\n    right. destruct IH1; [destruct IH2 |].\n    + inv H; [ eexists; econstructor| |]...\n      all: inv twt1.\n    + destruct H0. eexists; eapply ST_App2...\n    + destruct H.  eexists; eapply ST_App1...\n  - rename IHtwt1 into IH1, IHtwt2 into IH2,\n           IHtwt3 into IH3. specialize (IH1 HeqG).\n    specialize (IH2 HeqG). specialize (IH3 HeqG).\n    right. destruct IH1;\n    [ inv H; [inv twt1| |]\n    | destruct H]; eexists; econstructor ...\nQed.\n\nLemma weakening : forall G G' t T\n    (INCL: inclusion G G')\n    (H: G |- t \\in T),\n  G' |- t \\in T.\nProof with eauto.\n  intros **. generalize dependent G'.\n  induction H;\n  try solve [econstructor; try apply INCL; auto];\n  intros.\n\n  econstructor. eapply IHhas_type. intros ? **.\n  destruct (eqb_stringP x x0) as [<-|].\n  - now rewrite update_eq in *.\n  - rewrite update_neq in *...\nQed.\n\nLemma weakening_empty : forall G t T,\n    empty |- t \\in T  ->\n  G |- t \\in T.\nProof with auto.\n  intros. eapply weakening...\nQed.\n\nLemma substitution_preserves_typing : forall G x U t v T,\n    x |-> U ; G |- t \\in T ->\n    empty |- v \\in U ->\n  G |- [x:=v]t \\in T.\nProof with eauto.\n  intros *; revert G x U v T.\n  induction t; intros **; simpl; inv H...\n  - destruct (eqb_stringP x s) as [<-|].\n    + rewrite update_eq in IH.\n      injection IH as ->.\n      apply weakening_empty...\n    + econstructor. rewrite update_neq in IH...\n  - destruct (eqb_stringP x s) as [<-|]; econstructor.\n    + rewrite update_shadow in IH...\n    + eapply IHt... rewrite update_permute...\nQed.\n\nLemma substitution_of_open_tm_preserves_typing :\n    forall G x U t v T,\n    x |-> U ; G |- t \\in T ->\n    G |- v \\in U ->\n  G |- [x:=v]t \\in T.\nProof with eauto.\n  intros *; revert G x U v T.\n  induction t; intros **; simpl; inv H...\n  - destruct (eqb_stringP x s) as [<-|].\n    + rewrite update_eq in IH.\n      injection IH as ->...\n    + econstructor. rewrite update_neq in IH...\n  - destruct (eqb_stringP x s) as [<-|]; econstructor.\n    + rewrite update_shadow in IH...\n    + eapply IHt... rewrite update_permute...\n    admit.\nAdmitted.\n\nLtac niceIH :=\n  try rename IHhas_type into IH;\n  try rename IHhas_type1 into IH1;\n  try rename IHhas_type2 into IH2;\n  try rename IHhas_type3 into IH3.\n(* Goal forall G x U t v T,\n    x |-> U ; G |- t \\in T ->\n    empty |- v \\in U ->\n  G |- [x:=v]t \\in T.\nProof with eauto.\n  intros.\n  remember (x |-> U; G) as G'.\n  revert dependent v. revert dependent G.\n  revert x U.\n  induction H... all: intros * -> **;\n  try rename IHhas_type into IH;\n  try rename IHhas_type1 into IH1;\n  try rename IHhas_type2 into IH2;\n  try rename IHhas_type3 into IH3.\n  - destruct (eqb_stringP x x0) as [<-|]; simpl;\n    [ rewrite <- eqb_string_refl\n    | rewrite false_eqb_string ]...\n    + rewrite update_eq in IH.\n      injection IH as <-. apply weakening_empty...\n    + rewrite update_neq in IH...\n  - specialize (IH _ eq_refl).\n\nQed. *)\n\n\nTheorem preservation : forall t t' T,\n    empty |- t \\in T  ->\n    t --> t'  ->\n  empty |- t' \\in T.\nProof with eauto.\n  remember empty as G.\n  intros * ?; revert t'. induction H; intros;\n  try solve [inv H| inv H0|inv H2;eauto]; niceIH.\n  inv HeqG. specialize (IH2 eq_refl).\n  specialize (IH1 eq_refl).\n\n  inv H1; try solve [econstructor;eauto].\n  inv H. eapply substitution_preserves_typing...\nQed.\n\n\nTheorem preservation_strong : forall t t' T G,\n    G |- t \\in T  ->\n    t --> t'  ->\n  G |- t' \\in T.\nProof with eauto.\n  intros * ?; revert t'. induction H; intros;\n  try solve [inv H| inv H0|inv H2;eauto]; niceIH.  \n\n  inv H1; try solve [econstructor;eauto].\n  inv H. eapply substitution_of_open_tm_preserves_typing...\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\nRequire Import List Nat.\nDefinition ident := nat.\n\n(* deBruijn index *)\nDefinition dbi := nat.\n\nInductive ty : Type :=\n  | Bool\n  | Arrow : ty -> ty -> ty.\n\n(* Inductive binding : Type := VarBind : ty -> binding. *)\nDefinition context := list (ident * ty).\nDefinition add_binding ctx x bind : context := (x,bind)::ctx.\n\nFixpoint get_binding (ctx:context) i :=\n  match ctx with\n  | (x,T) :: tl => if Nat.eqb x i\n                   then Some T\n                   else get_binding tl i\n  | _ => None\n  end.\n\nDefinition getTypeFromContext ctx i :=\n  match get_binding ctx i with\n  | Some ty => ty\n  | _ => Bool\n  end.\n\nNotation \"x ;; T ∈ G\" := (get_binding G x = Some T) (at level 1, T at next level).\n\nInductive tm : Type :=\n  | ttrue\n  | tfalse\n  | ITE : tm -> tm -> tm -> tm\n  | var : nat -> tm\n  | abs : ident -> ty -> tm -> tm\n  | app : tm -> tm -> tm.\n\nFixpoint size t :=\n  match t with\n  | ttrue | tfalse | var _ => 1\n  | abs _ _ t => 1 + size t\n  | app t1 t2 => 1 + size t1 + size t2\n  | ITE t1 t2 t3 => 1 + size t1 + size t2 + size t3\n  end.\n\nFixpoint binders acc t : Prop :=\n  match t with\n  | var k => if <\n  end\n\nNotation \"'If' c 'Then' u 'Else' v\" :=\n  (ITE c u v)\n  (at level 200).\n\nInductive val : tm -> Prop :=\n  | vtrue : val ttrue\n  | vfalse : val tfalse\n  | vabs : forall x T body,\n    val (abs x T body).\n\nInductive type_of : context -> tm -> ty -> Prop :=\n  | tttrue : forall G, type_of G ttrue Bool\n  | ttfalse : forall G, type_of G tfalse Bool\n  | tif : forall G t1 t2 t3 T\n      (t1ht: type_of G t1 Bool)\n      (t2ht: type_of G t2 T)\n      (t3ht: type_of G t3 T),\n    type_of G (ITE t1 t2 t3) T\n  | tvar : forall G x T,\n      (x ;; T ∈ G) ->\n    type_of G (var x) T\n  | tabs : forall G x body Tx Tb\n      (H: type_of (add_binding G x Tx) body Tb),\n    type_of G (abs x Tx body) (Arrow Tx Tb)\n  | tapp : forall G t1 t2 T2 T\n      (t1ht: type_of G t1 (Arrow T2 T))\n      (t2ht: type_of G t2 T2),\n    type_of G (app t1 t2) T.\n\nNotation \"G |- t ;; T\" := (type_of G t T) (at level 1, t at next level).\n\n#[export] Hint Resolve vtrue vfalse vabs\ntttrue ttfalse tif tvar tabs tapp : stlcabDB.\n\nFixpoint shift d c t :=\n  match t with\n  | var k => if k <? c then t else var (k + d)\n  | abs x T body => abs x T (shift d (S c) body)\n  | app t1 t2 => app (shift d c t1) (shift d c t2)\n  | ITE t1 t2 t3 => ITE (shift d c t1) (shift d c t2) (shift d c t3)\n  | _ => t\n  end.\n\nDefinition dshift d t := shift d 0 t.\n\nFixpoint subst_by_in (j: dbi) (s t: tm) : tm :=\n  match t with\n  | var k => if k =? j then s else t\n  | abs x T body => abs x T (subst_by_in (S j) (dshift 1 s) body)\n  | app t1 t2 => app (subst_by_in j s t1) (subst_by_in j s t2)\n  | ITE t1 t2 t3 => ITE (subst_by_in j s t1) (subst_by_in j s t2) (subst_by_in j s t3)\n  | _ => t\n  end.\n\nInductive step : tm -> tm -> Prop :=\n  | eiftrue : forall t2 t3,\n      step (If ttrue Then t2 Else t3) t2\n  | eiffalse : forall t2 t3,\n      step (If tfalse Then t2 Else t3) t3\n  | eif : forall t t' t2 t3\n        (IH: step t t'),\n      step (If t Then t2 Else t3) (If t' Then t2 Else t3)\n  | eapp1 : forall t t' targ\n        (IH: step t t'),\n      step (app t targ) (app t' targ)\n  | eapp2 : forall v t t'\n        (IHv: val v)\n        (IH: step t t'),\n      step (app v t) (app v t')\n  | eappabs : forall x T body v,\n      step (app (abs x T body) v) (subst_by_in 0 v body).\n\nNotation \"a --> b\" := (step a b) (at level 5).\n\nInductive stepstar : tm -> tm -> Prop :=\n  | zerosteps : forall t, stepstar t t\n  | oneormoresteps : forall t1 t2 t3,\n      step t1 t2 -> stepstar t2 t3 -> stepstar t1 t3.\nNotation \"a -->* b\" := (stepstar a b) (at level 5).\n#[export] Hint Resolve zerosteps\neiftrue eiffalse: stlcabDB.\n\nTheorem t__unique_typ : forall t G T T'\n  (tT: G |- t ;; T) (tT': G |- t ;; T'), T = T'.\nProof with eauto.\n  induction t; intros.\n  all: inv tT; inv tT'...\n  - rewrite H1 in H2. injection H2...\n  - rewrite (IHt _ _ _ H4 H5)...\n  - rewrite (IHt2 _ _ _ t2ht t2ht0) in t1ht.\n    pose proof (IHt1 _ _ _ t1ht t1ht0).\n    inversion H...\nQed.\n\nTheorem v_val_Bool__tof : forall v G\n    (valv: val v)\n    (vBool: G |- v ;; Bool),\n  v = ttrue \\/ v = tfalse.\nProof with eauto.\n  intros. inv valv...\n  inv vBool.\nQed.\n\nTheorem Progress : forall G t\n    (twt: exists T, G |- t ;; T),\n  val t \\/ exists t', t --> t'.\nProof with eauto with stlcabDB.\n  intros * [T tWT].\n  induction tWT...\n  - admit.\n  - \nQed.\n\n  Theorem Preservation\n\nDefinition in_ctx (x:nat) (T:typ) ctx := \n  nth_error ctx x  = Some T.\n\nInductive has_typ : tcontext -> tm -> typ -> Prop :=\n  | \n", "meta": {"author": "CESally", "repo": "CS578Spring", "sha": "a36cc6b37d9c5e80e6fd762c6501334d15b331dd", "save_path": "github-repos/coq/CESally-CS578Spring", "path": "github-repos/coq/CESally-CS578Spring/CS578Spring-a36cc6b37d9c5e80e6fd762c6501334d15b331dd/coq/STLCappB.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.7718435030872967, "lm_q1q2_score": 0.6529351652289982}}
{"text": "(** Formal Reasoning About Programs <http://adam.chlipala.net/frap/>\n  * Chapter 4: Semantics via Interpreters\n  * Author: Adam Chlipala\n  * License: https://creativecommons.org/licenses/by-nc-nd/4.0/ *)\n\nRequire Import Frap.\n\n\n(* We begin with a return to our arithmetic language from BasicSyntax,\n * adding subtraction*, which will come in handy later.\n * *: good pun, right? *)\nInductive arith : Set :=\n| Const (n : nat)\n| Var (x : var)\n| Plus (e1 e2 : arith)\n| Minus (e1 e2 : arith)\n| Times (e1 e2 : arith).\n\nExample ex1 := Const 42.\nExample ex2 := Plus (Var \"y\") (Times (Var \"x\") (Const 3)).\n\n(* The above definition only explains what programs *look like*.\n * We also care about what they *mean*.\n * The natural meaning of an expression is the number it evaluates to.\n * Actually, it's not quite that simple.\n * We need to consider the meaning to be a function over a valuation\n * to the variables, which in turn is itself a finite map from variable\n * names to numbers.  We use the book library's [fmap] type family. *)\nDefinition valuation := fmap var nat.\n(* That is, the domain is [var] (a synonym for [string]) and the codomain/range\n * is [nat]. *)\n\n(* The interpreter is a fairly innocuous-looking recursive function. *)\nFixpoint interp (e : arith) (v : valuation) : nat :=\n  match e with\n  | Const n => n\n  | Var x =>\n    (* Note use of infix operator to look up a key in a finite map. *)\n    match v $? x with\n    | None => 0 (* goofy default value! *)\n    | Some n => n\n    end\n  | Plus e1 e2 => interp e1 v + interp e2 v\n  | Minus e1 e2 => interp e1 v - interp e2 v\n                   (* For anyone who's wondering: this [-] sticks at 0,\n                    * if we would otherwise underflow. *)\n  | Times e1 e2 => interp e1 v * interp e2 v\n  end.\n\n(* Here's an example valuation, using an infix operator for map extension. *)\nDefinition valuation0 : valuation :=\n  $0 $+ (\"x\", 17) $+ (\"y\", 3).\n\n(* Unfortunately, we can't execute code based on finite maps, since, for\n * convenience, they use uncomputable features.  The reason is that we need a\n * comparison function, a hash function, etc., to do computable finite-map\n * implementation, and such things are impossible to compute automatically for\n * all types in Coq.  However, we can still prove theorems about execution of\n * finite-map programs, and the [simplify] tactic knows how to reduce the\n * key constructions. *)\nTheorem interp_ex1 : interp ex1 valuation0 = 42.\nProof.\n  simplify.\n  equality.\nQed.\n\nTheorem interp_ex2 : interp ex2 valuation0 = 54.\nProof.\n  unfold valuation0.\n  simplify.\n  equality.\nQed.\n\n(* Here's the silly transformation we defined last time. *)\nFixpoint commuter (e : arith) : arith :=\n  match e with\n  | Const _ => e\n  | Var _ => e\n  | Plus e1 e2 => Plus (commuter e2) (commuter e1)\n  | Minus e1 e2 => Minus (commuter e1) (commuter e2)\n                   (* ^-- NB: didn't change the operand order here! *)\n  | Times e1 e2 => Times (commuter e2) (commuter e1)\n  end.\n\n(* Instead of proving various odds-and-ends properties about it,\n * let's show what we *really* care about: it preserves the\n * *meanings* of expressions! *)\nTheorem commuter_ok : forall v e, interp (commuter e) v = interp e v.\nProof.\n  induct e; simplify.\n\n  equality.\n\n  equality.\n\n  linear_arithmetic.\n\n  equality.\n\n  rewrite IHe1, IHe2.\n  ring.\nQed.\n(* Well, that's a relief! ;-) *)\n\n(* Let's also revisit substitution. *)\nFixpoint substitute (inThis : arith) (replaceThis : var) (withThis : arith) : arith :=\n  match inThis with\n  | Const _ => inThis\n  | Var x => if x ==v replaceThis then withThis else inThis\n  | Plus e1 e2 => Plus (substitute e1 replaceThis withThis) (substitute e2 replaceThis withThis)\n  | Minus e1 e2 => Minus (substitute e1 replaceThis withThis) (substitute e2 replaceThis withThis)\n  | Times e1 e2 => Times (substitute e1 replaceThis withThis) (substitute e2 replaceThis withThis)\n  end.\n\nTheorem substitute_ok : forall v replaceThis withThis inThis,\n  interp (substitute inThis replaceThis withThis) v\n  = interp inThis (v $+ (replaceThis, interp withThis v)).\nProof.\n  induct inThis; simplify; try equality.\n\n  (* One case left after our basic heuristic:\n   * the variable case, naturally! *)\n  cases (x ==v replaceThis); simplify; equality.\nQed.\n(* Great; we seem to have gotten that one right, too. *)\n\n(* Let's also define a pared-down version of the expression-simplification\n * functions from last chapter. *)\nFixpoint doSomeArithmetic (e : arith) : arith :=\n  match e with\n  | Const _ => e\n  | Var _ => e\n  | Plus (Const n1) (Const n2) => Const (n1 + n2)\n  | Plus e1 e2 => Plus (doSomeArithmetic e1) (doSomeArithmetic e2)\n  | Minus e1 e2 => Minus (doSomeArithmetic e1) (doSomeArithmetic e2)\n  | Times (Const n1) (Const n2) => Const (n1 * n2)\n  | Times e1 e2 => Times (doSomeArithmetic e1) (doSomeArithmetic e2)\n  end.\n\nTheorem doSomeArithmetic_ok : forall e v, interp (doSomeArithmetic e) v = interp e v.\nProof.\n  induct e; simplify; try equality.\n\n  cases e1; simplify; try equality.\n  cases e2; simplify; equality.\n\n  cases e1; simplify; try equality.\n  cases e2; simplify; equality.\nQed.\n\n(* Of course, we're going to get bored if we confine ourselves to arithmetic\n * expressions for the rest of our journey.  Let's get a bit fancier and define\n * a *stack machine*, related to postfix calculators that some of you may have\n * experienced. *)\nInductive instruction :=\n| PushConst (n : nat)\n| PushVar (x : var)\n| Add\n| Subtract\n| Multiply.\n\n(* What does it all mean?  An interpreter tells us unambiguously! *)\nDefinition run1 (i : instruction) (v : valuation) (stack : list nat) : list nat :=\n  match i with\n  | PushConst n => n :: stack\n  | PushVar x => (match v $? x with\n                  | None => 0\n                  | Some n => n\n                  end) :: stack\n  | Add =>\n    match stack with\n    | arg2 :: arg1 :: stack' => arg1 + arg2 :: stack'\n    | _ => stack (* arbitrary behavior in erroneous case (stack underflow) *)\n    end\n  | Subtract =>\n    match stack with\n    | arg2 :: arg1 :: stack' => arg1 - arg2 :: stack'\n    | _ => stack (* arbitrary behavior in erroneous case *)\n    end\n  | Multiply =>\n    match stack with\n    | arg2 :: arg1 :: stack' => arg1 * arg2 :: stack'\n    | _ => stack (* arbitrary behavior in erroneous case *)\n    end\n  end.\n\n(* That function explained how to run one instruction.\n * Here's how to run several of them. *)\nFixpoint run (is : list instruction) (v : valuation) (stack : list nat) : list nat :=\n  match is with\n  | nil => stack\n  | i :: is' => run is' v (run1 i v stack)\n  end.\n\n(* Instead of writing fiddly stack programs ourselves, let's *compile*\n * arithmetic expressions into equivalent stack programs. *)\nFixpoint compile (e : arith) : list instruction :=\n  match e with\n  | Const n => PushConst n :: nil\n  | Var x => PushVar x :: nil\n  | Plus e1 e2 => compile e1 ++ compile e2 ++ Add :: nil\n  | Minus e1 e2 => compile e1 ++ compile e2 ++ Subtract :: nil\n  | Times e1 e2 => compile e1 ++ compile e2 ++ Multiply :: nil\n  end.\n\n(* Now, of course, we should prove our compiler correct.\n * Skip down to the next theorem to see the overall correctness statement.\n * It turns out that we need to strengthen the induction hypothesis with a\n * lemma, to push the proof through. *)\nLemma compile_ok' : forall e v is stack,\n    run (compile e ++ is) v stack = run is v (interp e v :: stack).\nProof.\n  induct e; simplify.\n\n  equality.\n\n  equality.\n\n  (* Here we want to use associativity of [++], to get the conclusion to match\n   * an induction hypothesis.  Let's ask Coq to search its library for lemmas\n   * that would justify such a rewrite, giving a pattern with wildcards, to\n   * specify the essential structure that the rewrite should match. *)\n  Search ((_ ++ _) ++ _).\n  (* Ah, we see just the one! *)\n  rewrite app_assoc_reverse.\n  rewrite IHe1.\n  rewrite app_assoc_reverse.\n  rewrite IHe2.\n  simplify.\n  equality.\n\n  rewrite app_assoc_reverse.\n  rewrite IHe1.\n  rewrite app_assoc_reverse.\n  rewrite IHe2.\n  simplify.\n  equality.\n\n  rewrite app_assoc_reverse.\n  rewrite IHe1.\n  rewrite app_assoc_reverse.\n  rewrite IHe2.\n  simplify.\n  equality.\nQed.\n\n(* The overall theorem follows as a simple corollary. *)\nTheorem compile_ok : forall e v, run (compile e) v nil = interp e v :: nil.\nProof.\n  simplify.\n\n  (* To match the form of our lemma, we need to replace [compile e] with\n   * [compile e ++ nil], adding a \"pointless\" concatenation of the empty list.\n   * [Search] again helps us find a library lemma. *)\n  Search (_ ++ nil).\n  rewrite (app_nil_end (compile e)).\n  (* Note that we can use [rewrite] with explicit values of the first few\n   * quantified variables of a lemma.  Otherwise, [rewrite] picks an\n   * unhelpful place to rewrite.  (Try it and see!) *)\n\n  apply compile_ok'.\n  (* Direct appeal to a previously proved lemma *)\nQed.\n\n\n(* Let's get a bit fancier, moving toward the level of general-purpose\n * imperative languages.  Here's a language of commands, building on the\n * language of expressions we have defined. *)\nInductive cmd :=\n| Skip\n| Assign (x : var) (e : arith)\n| Sequence (c1 c2 : cmd)\n| Repeat (e : arith) (body : cmd).\n\n(* That last constructor is for repeating a body command some number of\n * times.  Note that we sneakily avoid constructs that could introduce\n * nontermination, since Coq only accepts terminating programs, and we want to\n * write an interpreter for commands.\n * In contrast to our last one, this interpreter *transforms valuations*.\n * We use a helper function for self-composing a function some number of\n * times. *)\n\nFixpoint selfCompose {A} (f : A -> A) (n : nat) : A -> A :=\n  match n with\n  | O => fun x => x\n  | S n' => fun x => selfCompose f n' (f x)\n  end.\n\nFixpoint exec (c : cmd) (v : valuation) : valuation :=\n  match c with\n  | Skip => v\n  | Assign x e => v $+ (x, interp e v)\n  | Sequence c1 c2 => exec c2 (exec c1 v)\n  | Repeat e body => selfCompose (exec body) (interp e v) v\n  end.\n\n(* Let's define some programs and prove that they operate in certain ways. *)\n\nExample factorial_ugly :=\n  Sequence\n    (Assign \"output\" (Const 1))\n    (Repeat (Var \"input\")\n            (Sequence\n               (Assign \"output\" (Times (Var \"output\") (Var \"input\")))\n               (Assign \"input\" (Minus (Var \"input\") (Const 1))))).\n\n(* Ouch; that code is hard to read.  Let's introduce some notations to make the\n * concrete syntax more palatable.  We won't explain the general mechanisms on\n * display here, but see the Coq manual for details, or try to reverse-engineer\n * them from our examples. *)\nCoercion Const : nat >-> arith.\nCoercion Var : var >-> arith.\n(*Declare Scope arith_scope.*)\nInfix \"+\" := Plus : arith_scope.\nInfix \"-\" := Minus : arith_scope.\nInfix \"*\" := Times : arith_scope.\nDelimit Scope arith_scope with arith.\nNotation \"x <- e\" := (Assign x e%arith) (at level 75).\nInfix \";\" := Sequence (at level 76).\nNotation \"'repeat' e 'doing' body 'done'\" := (Repeat e%arith body) (at level 75).\n\n(* OK, let's try that program again. *)\nExample factorial :=\n  \"output\" <- 1;\n  repeat \"input\" doing\n    \"output\" <- \"output\" * \"input\";\n    \"input\" <- \"input\" - 1\n  done.\n\n(* Now we prove that it really computes factorial.\n * First, a reference implementation as a functional program. *)\nFixpoint fact (n : nat) : nat :=\n  match n with\n  | O => 1\n  | S n' => n * fact n'\n  end.\n\n(* To prove that [factorial] is correct, the real action is in a lemma, to be\n * proved by induction, showing that the loop works correctly.  So, let's first\n * assign a name to the loop body alone. *)\nDefinition factorial_body :=\n  \"output\" <- \"output\" * \"input\";\n  \"input\" <- \"input\" - 1.\n\n(* Now for that lemma: self-composition of the body's semantics produces the\n * expected changes in the valuation.\n * Note that here we're careful to put the quantified variable [input] *first*,\n * because the variables coming after it will need to *change* in the course of\n * the induction.  Try switching the order to see what goes wrong if we put\n * [input] later. *)\nLemma factorial_ok' : forall input output v,\n  v $? \"input\" = Some input\n  -> v $? \"output\" = Some output\n  -> selfCompose (exec factorial_body) input v\n     = v $+ (\"input\", 0) $+ (\"output\", output * fact input).\nProof.\n  induct input; simplify.\n\n  maps_equal.\n  (* [maps_equal]: prove that two finite maps are equal by considering all\n   *   the relevant cases for mappings of different keys. *)\n\n  rewrite H0.\n  f_equal.\n  linear_arithmetic.\n\n  trivial.\n  (* [trivial]: Coq maintains a database of simple proof steps, such as proving\n   *   a fact by direct appeal to a matching hypothesis.  [trivial] asks to try\n   *   all such simple steps. *)\n\n  rewrite H, H0.\n  (* Note the two arguments to one [rewrite]! *)\n  rewrite (IHinput (output * S input)).\n  (* Note the careful choice of a quantifier instantiation for the IH! *)\n  maps_equal.\n  f_equal; ring.\n  simplify; f_equal; linear_arithmetic.\n  simplify; equality.\nQed.\n\n(* Finally, we have the natural correctness condition for factorial as a whole\n * program. *)\nTheorem factorial_ok : forall v input,\n  v $? \"input\" = Some input\n  -> exec factorial v $? \"output\" = Some (fact input).\nProof.\n  simplify.\n  rewrite H.\n  rewrite (factorial_ok' input 1); simplify.\n  f_equal; linear_arithmetic.\n  trivial.\n  trivial.\nQed.\n\n\n(* One last example: let's try to do loop unrolling, for constant iteration\n * counts.  That is, we can duplicate the loop body instead of using an explicit\n * loop. *)\n\nFixpoint seqself (c : cmd) (n : nat) : cmd :=\n  match n with\n  | O => Skip\n  | S n' => Sequence c (seqself c n')\n  end.\n\nFixpoint unroll (c : cmd) : cmd :=\n  match c with\n  | Skip => c\n  | Assign _ _ => c\n  | Sequence c1 c2 => Sequence (unroll c1) (unroll c2)\n  | Repeat (Const n) c1 => seqself (unroll c1) n\n  (* ^-- the crucial case! *)\n  | Repeat e c1 => Repeat e (unroll c1)\n  end.\n\n(* This obvious-sounding fact will come in handy: self-composition gives the\n * same result, when passed two functions that map equal inputs to equal\n * outputs. *)\nLemma selfCompose_extensional : forall {A} (f g : A -> A) n x,\n  (forall y, f y = g y)\n  -> selfCompose f n x = selfCompose g n x.\nProof.\n  induct n; simplify; try equality.\n\n  rewrite H.\n  apply IHn.\n  trivial.\nQed.\n\n(* Crucial lemma: [seqself] is acting just like [selfCompose], in a suitable\n * sense. *)\nLemma seqself_ok : forall c n v,\n  exec (seqself c n) v = selfCompose (exec c) n v.\nProof.\n  induct n; simplify; equality.\nQed.\n\n(* The two lemmas we just proved are the main ingredients to prove the natural\n * correctness condition for [unroll]. *)\nTheorem unroll_ok : forall c v, exec (unroll c) v = exec c v.\nProof.\n  induct c; simplify; try equality.\n\n  cases e; simplify; try equality.\n\n  rewrite seqself_ok.\n  apply selfCompose_extensional.\n  trivial.\n\n  apply selfCompose_extensional.\n  trivial.\n\n  apply selfCompose_extensional.\n  trivial.\n\n  apply selfCompose_extensional.\n  trivial.\n\n  apply selfCompose_extensional.\n  trivial.\nQed.\n", "meta": {"author": "achlipala", "repo": "frap", "sha": "ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb", "save_path": "github-repos/coq/achlipala-frap", "path": "github-repos/coq/achlipala-frap/frap-ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb/Interpreters.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6529351609033283}}
{"text": "(** * The calculus of (co)inductive constructions *)\n\n(** ** Abstraction *)\n\n(** The calculus used in Coq is based on the calculus of constructions (CoC)\n    %[%#[#Coquand, Huet, '88#]#%]% with the addition of several later extensions\n    such as an infinite hierarchy of types %[%#[#Luo, '89#]#%]%, inductively\n    defined data types %[%#[#Pfenning, Paulin-Morhing, '88#]#%]% and\n    co-inductively defined data types %[%#[#Giménez, 95#]#%]%.\n\n    The CoC is a higher-order typed lambda calculus. It sits at the\n    top of the \"Lambda cube\", as it allows all 4 forms of abstraction.\n\n    The first type of abstraction is simply lambda-abstraction,\n    i.e. values depending on values.*)\n\nDefinition add_two := fun (x : nat) => x + 2.\n\nCheck add_two.\n\n(** Another type of abstraction is polymorphism, with which we can\n    define values depending on types. *)\n\nDefinition id := fun (A : Type) (x : A) => x.\n\nCheck id.\n\n(** Type operators offer a third form of abstraction, which allows\n    defining types that depend on types. *)\n\nDefinition arrow := fun (A B : Type) => A -> B.\n\nCheck arrow.\n\n(** The last form of abstraction is dependent types, or types whose\n    definition depends on values. *)\n\nDefinition arrow_n :=\n  fun (A : Type) =>\n    fix F (n : nat) :=\n    match n with\n    | 0 => A\n    | S n' => arrow A (F n')\n    end.\n\nCompute (arrow_n bool 3).\n\nCheck arrow_n.\n\n(* begin hide *)\nImport Nat.\n(* end hide *)\n\n(** ** Terms and types *)\n\n(** In fact, in the CoC there is no real distinction between values and\n    types.\n\n    - At the lowest level, there are concrete values (e.g. [O], [true]...)\n      and programs ([add], [negb]...)\n\n    - The types of these terms ([nat], [bool], [nat -> nat -> nat], [bool -> bool]...) are\n      also terms themselves. This means that they can be passed as\n      arguments to functions and be used in the definition of a type. It\n      also means that they have a type themselves. *)\n\n(** We can keep checking the types upward. *)\n\nCheck 0.\n\nCheck nat.\n\nCheck Set.\n\nCheck Type.\n\n(** This last answer should be surprising. It is known that this kind\n    of typing results in an inconsistent system, for reasons similar\n    to Russell's paradox in naive set theory (this is called Girard's\n    paradox and is not quite as easy to exhibit as Russell's).\n\n    Coq actually hides some technical details when it comes to printing\n    [Type]. These can be reactivated. *)\n\nSet Printing Universes.\n\nCheck Set.\n\nCheck Type.\n\n(** We now see that [Type] actually stands for an infinite hierarchy of\n    types, thus preventing Girard's paradox. Each occurrence of [Type] is\n    called a universe. Conveniently, any universe of rank <<i>> also has\n    rank <<j>> for any <<j > i>> (so, for example, [Set] has the type [Type@{i}] for\n    any <<i>>). *)\n\nUnset Printing Universes.\n\n(** ** Terms in the CoC *)\n\n(** Let us take a look at the different ways to form terms. *)\n\n(** First we fix some constants. *)\nAxiom A : Set.\n\nAxiom B : Set.\n\n(** We can form terms by lambda abstraction. *)\nDefinition lambda := fun (x : A) => B.\n\n(** This next construct is called product. This becomes a bit\n    confusing later when we'll add inductively defined data types and\n    the more common notion of product type. *)\nDefinition product := forall (x : A), B.\n\n(** We fix another constant of the proper type to form a term by\n    application. *)\nAxiom a : A.\n\nDefinition application := lambda a.\n\n(** Note that [A -> B] is actually equivalent to [forall (_ : A), B]. *)\n\n(** In this definition, the second lambda is dependent on [P]. Observe\n    the type. *)\n\nCheck fun (P : Set) (x : P) => x.\n\n(** In this second definition, [P] is not used in the second\n    lambda. This results in a simpler type, using [->] instead of\n    [forall]. *)\n\nCheck fun (P : Set) (x : A) => x.\n\n(** These rules (constant, abstraction, product, application) are the\n    only ones on which to build terms in the original calculus of\n    constructions. *)\n\n(** ** Inductively defined types *)\n\n(** While it is possible to define a higher-order logic with only\n    these rules, the addition of inductively defined data types is a\n    useful feature. *)\n\n(** Here is an example of an inductive data type. *)\n\nInductive vector (T : Type) : nat -> Type :=\n| vnil : vector T 0\n| vcons : forall n, T -> vector T n -> vector T (S n).\n\n(** There is a slight difference between the two arguments of the type\n    [vector A n]: The argument [A] has the same value in the return type\n    of all the constructors. This is sometimes called an \"inductive\n    parameter\". The value of the second argument varies across\n    different constructors: [O] for [vnil], [S n] for [vcons]. This is\n    sometimes called a \"real argument\".\n\n    An inductive parameter can be turned into a real argument:\n\n[[\nInductive vector : Type -> nat -> Type :=\n| vnil : forall T, vector T 0\n| vcons : forall n T, T -> vector T n -> vector T (S n).\n]]\n\n    But a real argument cannot in general be replaced by an inductive\n    parameter. *)\n\n(** Values from inductively defined data types can be manipulated by\n    pattern matching. *)\n\nFixpoint vapp (A : Type) (n m : nat) (v1 : vector A n) (v2 : vector A m) : vector A (n + m) :=\n  match v1 with\n  | vnil _ => v2\n  | vcons _ _ x v' => vcons _ _ x (vapp _ _ _ v' v2)\n  end.\n\n(** ** Programs and proofs *)\n\n(** For a more eloquent presentation of the Curry-Howard\n    correspondence, see %[%#[#Wadler, 15%]%#]#. *)\n\n(** [x : T] is usually understood as \"[x] has type [T]\", but it can also be\n    understood as \"[x] is a proof of [T]\". *)\n\n(** [A -> B] is the type of functions from [A] to [B] but also reads as \"[A]\n    implies [B]\". Indeed, a proof of [A -> B] must be a program that takes\n    a proof of [A] as input and produce a proof of [B] as output. *)\n\n(** Logical connectives (other than [forall]/[->]) can be defined\n    inductively. *)\n\n(** Conjunction corresponds to product type (using the usual\n    definition of product here). *)\nInductive and (A B : Prop) : Prop :=\n| conj : A -> B -> and A B.\n\nArguments conj {_ _} _ _.\n\n(** Disjunction corresponds to sum. *)\nInductive or (A B : Prop) : Prop :=\n| disj_l : A -> or A B\n| disj_r : B -> or A B.\n\nArguments disj_l {_ _} _.\nArguments disj_r {_ _} _.\n\n(** [False] is the empty type, the type for which there exists no\n    inhabitant/proof. *)\nInductive False :=.\n\n(** For [True], any inhabited type will do, so the unit type is as good as any. *)\nInductive True :=\n| unit : True.\n\n(** ** Tactics and proof terms *)\n\n(** So far we have written terms only when we needed functions, and\n    used tactics to build proofs. But tactics are just a convenient\n    mechanism to build terms. We can write proof terms directly (or\n    more unusually, use tactics to build a function over small\n    types).*)\n\nLemma and_comm (A B : Prop) : and A B -> and B A.\nProof.\n  (* We must provide a term of type [A /\\ B -> B /\\ A], it seems that\n     this term should be a function with one argument of type [A /\\ B],\n     although we don't really know what the body the function is going\n     to look like. The tactic [intro] builds that lambda-abstraction for\n     us, leaving a hole where the body of the function is. *)\n  intros.\n  Show Proof.\n  (* We now have an element of type [A /\\ B] in the context (the\n     argument of the lambda abstraction, and we must build a term of\n     type [B /\\ A]. One way to construct this term is to pattern-match\n     something in context, and later provide a term of type [A /\\ B] for\n     every match. [destruct H] creates this pattern matching over [H],\n     leaving a hole in each branch. *)\n  destruct H.\n  (* The type [and A B] of [H] has only one constructor with two\n     arguments of type [A] and [B]. Therefore, we are now in a context with\n     two terms [H : A] and [H0 : B]. *)\n  Show Proof.\n  (* There is only one constructor for the type [and B A], so we apply\n     it. After that we have to fill two holes, corresponding to the\n     two arguments of the constructor. *)\n  apply conj.\n  Show Proof.\n  (* For the next two holes, we have terms of the needed type in\n     context, so we can use them directly using [exact]. *)\n  - exact H0.\n  - exact H.\nQed.\n\nPrint and_comm.\n\n(** The tactic [refine] is a more general version of [exact]. Instead of a\n    fully-formed term, it lets us put a term with holes (of course the\n    type of this term must unify with the expected type of the\n    hole). We can fill each hole later.\n\n    This script emulates the action of the previous tactics, using\n    only refine. *)\nLemma and_comm' (A B : Prop) : and A B -> and B A.\nProof.\n  refine (fun H => _).\n  refine (match H with conj H H0 => _ end).\n  refine (conj _ _).\n  - refine H0. (* without holes, this is identical to 'exact H0'*)\n  - refine H.\nQed.\n\n(** ** Equality *)\n\n(** Here is the definition of the equality [Prop].\n\n[[\nInductive eq (T : Type) (x : T) : T -> Prop :=\n| eq_refl : eq T x x.\n]]\n\n    This definition says that [eq T x y] holds only if [x] and [y] are\n    equivalent terms. On the meta-level, two terms are considered\n    equivalent if they have identical normal forms.\n\n    For example [0 + (0 + (0 + n))] is equivalent to [n]. However [n + 0] does\n    not normalize to [n], so it is not considered equivalent. *)\n\n(** ** Inductive proofs *)\n\n(** Proofs by induction correspond naturally to recursive functions. *)\n\n(** Let us write an induction proof, separating the two steps. *)\nDefinition base_case : forall (n m : nat), 0 + n + m = 0 + (n + m) :=\n  fun (n m : nat) => eq_refl.\n\n(** Proofs involving equational reasoning are not fun to write by\n    hand, let's use tactics for now. *)\nLemma ind_step : forall (n m p : nat), n + m + p = n + (m + p) -> S n + m + p = S n + (m + p).\nProof.\n  intros. simpl. rewrite <- H. apply eq_refl.\nQed.\n\nLemma add_assoc : forall (n m p : nat), n + m + p = n + (m + p).\nProof.\n  intros. induction n as [| n'].\n  - exact (base_case m p).\n  - exact (ind_step n' m p IHn').\nQed.\n\nDefinition add_assoc' : forall (n m p : nat), n + m + p = n + (m + p) :=\n  fix F (n m p : nat) :=\n    match n with\n    | O => base_case m p\n    | S n' => ind_step n' m p (F n' m p)\n    end.\n\n(** If you print the proof term created by the script, you will see\n    that [induction] actually applies [nat_ind], the induction principle\n    generated at the same time as [nat] was declared, rather than\n    building a recursive function from the ground up. *)\n\nPrint add_assoc.\n\n(** But it is important to note that [nat_ind] is not an axiom, just a\n    simple function that we could define ourselves, if Coq didn't do\n    it automatically (actually, [nat_ind] is defined with [nat_rect], so\n    let us print that instead). *)\n\nPrint nat_rect.\n\n(** Every inductively defined type has its associated induction\n    principle. *)\n\n(** We mentioned equality reasoning earlier. Equality reasoning is\n    based on the induction generated from the [eq] type. *)\n\nPrint eq_rect.\n\n(** Here are some useful lemmas/functions if you want to write\n    equational proofs. *)\nPrint eq_ind.\nPrint eq_sym.\nPrint eq_ind_r.\n\n(** However, be advised that the resulting proof terms are not particularly\n    pretty. *)\nPrint ind_step.\n\n(** ** Prop vs Set *)\n\n(** We found the lowest universe by checking the type of [Set]. There is\n    another native sort which lives in [Type@{0}], named [Prop]. Although\n    [Prop] and [Set] share the same universe, there are some important\n    differences between the two.\n\n    Prop is often described as the type of proof-irrelevant\n    propositions. What this means is that for a given proposition of\n    type [Prop] (e.g. [forall (P Q : Prop), P /\\ Q -> Q /\\ P]), we don't\n    really care about specific elements of this type (different\n    proofs). The existence or non-existence of a proof matters, but\n    the specifics of a given proof can usually be ignored.\n\n    In contrast, for types in [Set] (so-called small types, such as\n    [bool], [nat -> nat -> nat]...), we tend to care about the specifics of\n    the elements that implement the type: [true] is different from\n    [false], [mult] from [add]....\n\n    This distinction is useful when using the code extraction feature\n    of Coq: Objects in [Set] can be extracted to OCaml/Haskell/Scheme\n    while elements of [Prop] are left aside.\n\n    One important difference is that [Prop] is impredicative. Concretely,\n    this means that a term formed by quantification over [Prop] can\n    itself be in [Prop]. *)\n\nCheck forall (P Q : Prop), ((P -> Q) -> P) -> P.\n\n(** On the other hand, a term quantifying over [Set] has to live in the\n    next universe. *)\n\nCheck forall (P Q : Set), ((P -> Q) -> P) -> P.\n\n(** ** Elimination and impredicativity *)\n\n(** An impredicative universe seems more expressive, but it comes with\n    its own risks. Unrestricted impredicativity leads to\n    inconsistency, therefore Coq must put some restrictions on\n    elimination (pattern matching) over [Prop]. *)\n\nInductive ex {T : Type} (P : T -> Prop) : Prop :=\n  ex_intro : forall (t : T), P t -> ex P.\n\n(** [exists (x : T), P]      [ex T (fun x => P x)] *)\n\n(** The following definition is forbidden because it attempts to\n    eliminate a term whose type is [Prop] in the higher context [Type].\n\n[[\nDefinition witness_prop {T : Type} {P : T -> Prop} (H : ex P) : T :=\n  match H with\n  | ex_intro _ t _ => t\n  end.\n]]\n\n    However, it is possible to eliminate a proof to produce a proof.\n\n    The next [Prop] describes types that are inhabited (have at least\n    one element). *)\n\nInductive inhabited (T : Type) : Prop :=\n  inhabits : T -> inhabited T.\n\n(** The next lemma indicates that if we have a proof of some\n    existentially quantified property over a type [T], this type must be\n    inhabited. *)\n\n(** The proof can be constructed by elimination on the proof [destruct\n    H]. *)\n\nLemma exists_inhabited : forall (T : Type) (P : T -> Prop),\n    ex P -> inhabited T.\nProof.\n  intros. destruct H. apply inhabits. exact t.\nQed.\n\n(** Or equivalently, here is the proof term, which pattern-matches the\n    proof. *)\n\nDefinition exists_inhabited' : forall (T : Type) (P : T -> Prop), ex P -> inhabited T :=\n  fun (T : Type) (P : T -> Prop) (H : ex P) =>\n    match H with\n    | ex_intro _ t _ => inhabits _ t\n    end.\n\n(** Let us now define a type that is very similar to [ex], except that\n    it doesn't live in [Prop].\n\n    Instead of being a proof that some element verifies a property [P],\n    an element of type [sig P] is usually understood as being the set\n    of elements that verifies [P]. *)\n\nInductive sig {T : Type} (P : T -> Prop) : Type :=\n  sig_intro : forall (t : T), P t -> sig P.\n\n(** The following function, similar to [witness], extracts a member from\n    a type [sig P]. The definition can pattern-match [S] without\n    restriction since [sig P] is not in [Prop]. *)\n\nDefinition member {T : Type} {P : T -> Prop} (S : sig P) : T :=\n  match S with\n  | sig_intro _ t _ => t\n  end.\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/presentations/3/Presentation_week3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6529351593474146}}
{"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.\n  Proof.\n  Admitted.\n\n  Fact perm_length l1 l2 : l1 ~p l2 -> length l1 = length l2.\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  Admitted.\n\n  Fact perm_sym l1 l2 : l1 ~p l2 -> l2 ~p l1.\n  Proof.\n  Admitted.\n\n  Fact perm_middle x l r : x::l++r ~p l++x::r.\n  Proof.\n    induction l as [ | y l IHl ]; simpl.\n  Admitted.\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; simpl.\n  Admitted.\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; revert H r1 r2.\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  Admitted.\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                   ]; simpl; auto.\n  Admitted.\n\nEnd list_perm.\n\nInfix \"~p\" := (perm _) (at level 70, no associativity).\n", "meta": {"author": "DmxLarchey", "repo": "PHP-etudiants", "sha": "5d9f86703a0070a55600a68bfda9cf1384a5ff72", "save_path": "github-repos/coq/DmxLarchey-PHP-etudiants", "path": "github-repos/coq/DmxLarchey-PHP-etudiants/PHP-etudiants-5d9f86703a0070a55600a68bfda9cf1384a5ff72/perm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.6528737353465723}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Examples for other tactics provided by TLC                              *\n**************************************************************************)\n\nSet Implicit Arguments.\nFrom TLC Require Import LibTactics.\nFrom TLC Require Import LibLogic LibEqual LibList LibRelation LibWf LibList LibLN.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Demo of extens tactics *)\n\nLemma test_extensionality_1 : forall A1 (P Q :  A1->Prop),\n  (forall x1, P x1 <-> Q x1) ->\n  P = Q.\nProof using.\n  intros. applys extensionality. hnf.\nAbort.\n\nLemma test_extensionality_2 : forall A1 (A2: A1->Type) (P Q : forall (x1:A1) (x2:A2 x1), Prop),\n  (forall x1 x2, P x1 x2 <-> Q x1 x2) ->\n  P = Q.\n  intros. applys extensionality. hnf.\nAbort.\n\nSection FuncExtDepTest.\nVariables (A1 : Type).\nVariables (A2 : forall (x1 : A1), Type).\nVariables (A3 : forall (x1 : A1) (x2 : A2 x1), Type).\nVariables (A4 : forall (x1 : A1) (x2 : A2 x1) (x3 : A3 x2), Type).\n\nLemma test_fun_ext_3 : forall (f g : forall (x1:A1) (x2:A2 x1) (x3:A3 x2), A4 x3),\n  (forall x1 x2 x3, f x1 x2 x3 = g x1 x2 x3) ->\n  f = g.\nProof using. intros. applys extensionality. hnf. Abort.\n\nEnd FuncExtDepTest.\n\nLemma prop_ext_1_test : forall (P Q : Prop),\n  (P <-> Q) ->\n  P = Q.\nProof using.\n  intros. applys extensionality. simpl extensionality_hyp.\nAbort.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Demo of LibLogic tactics *)\nLemma absurds_demo : forall (P Q : Prop),\n  P /\\ (~ P) /\\ (Q \\/ ~ P).\nProof using.\n  intros. splits.\n  { absurds ;=> H. admit. }\n  { absurds ;=> H. admit. }\n  { absurds ;=> (H1&H2). admit. }\nAbort.\n\n\n(* ********************************************************************** *)\n(** * How to do recursion/induction on terms with list of subterms *)\n\nModule SubtermIndDemos.\n\nImport 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\n#[global]\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\nImport 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\n#[global]\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.\nImport 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\n(* ---------------------------------------------------------------------- *)\n(** ** Demo of LibSet tactics *)\n\nFrom TLC Require Import LibSet.\n\nLemma inter_union_disjoint_right:\n  forall A (E F G : set A),\n  F \\# G ->\n  (E \\u F) \\n G = (E \\n G).\nProof using.\n  set_prove.\n  (* intros. set_norm. set_specialize. set_norm. tauto. *)\nQed. (* demo *)\n\nLemma inter_union_subset_right:\n  forall A (E F G : set A),\n  F \\c G ->\n  (E \\u F) \\n G = (E \\n G) \\u F.\nProof using.\n  set_prove.\nQed. (* demo *)\n\nLemma inter_covariant:\n  forall A (E E' F F' : set A),\n  E \\c E' ->\n  F \\c F' ->\n  (E \\n F) \\c (E' \\n F').\nProof using.\n  set_prove.\nQed. (* demo *)\n\nLemma set_decompose_inter_right :\n  forall A (E F : set A),\n  E = (E \\n F) \\u (E \\- F).\nProof using.\n  set_prove_classic.\nQed. (* demo *)\n\nLemma set_decompose_union_right :\n  forall A (E F : set A),\n  (E \\u F) = E \\u (F \\- E).\nProof using.\n  set_prove_classic.\nQed. (* demo *)\n", "meta": {"author": "charguer", "repo": "tlc", "sha": "590c8c8d80442376b8ac19198b7ed446cebc6934", "save_path": "github-repos/coq/charguer-tlc", "path": "github-repos/coq/charguer-tlc/tlc-590c8c8d80442376b8ac19198b7ed446cebc6934/src/LibOtherDemos.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.6528737314225905}}
{"text": "(** * 논리: 콕에서 다루는 논리 *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Tactics.\n\n(** 이전 장들에서 사실에 기반을 둔 주장(_명제_)의 많은 예들과 그것들이\n    사실이라는 주장을 펴는 방법들(_증명_)을 보았다. 특히 [e1 = e2]\n    형태의 _등식에 관한 명제_, 함축([P -> Q]), 한정사를 사용한\n    명제([forall x, P])를 광범위하게 다루었다. 이 장에서 다른 익숙한\n    형태들의 논리 추론을 하기 위해 어떻게 콕을 사용할 수 있는지를 보게\n    될 것이다.\n\n    상세한 내용을 살펴보기 전에, 콕으로 작성하는 수학적 문장의 상태에\n    대해 조금 이야기하자. 콕은 _타입을 매기는_ 언어인데, 이는 콕의\n    세계에 있는 모든 의미 있는 식은 연관된 타입을 갖는다는 것을 뜻한다.\n    논리적 주장도 예외가 아니다. 왜냐하면 콕으로 증명하고자 시도하는\n    어떤 문장도 타입을 가지고 있기 때문이다. _명제_의 타입인\n    [Prop]이다. [Check] 명령어로 이것을 볼 수 있다.\n*)\n\nCheck 3 = 3.\n(* ===> Prop *)\n\nCheck forall n m : nat, n + m = m + n.\n(* ===> Prop *)\n\n(** _모든_ 구문 규칙을 준수하는 명제들은 콕에서 [Prop] 타입을 갖는\n    것에 주목하자.  이 명제들이 참이든 거짓이든 상관없이 이 타입을\n    갖는다. *)\n\n(** 단순히 명제의 _자격을 갖추는 것_과 명제가 참임을 _증명할 수 있는 것_은 \n    별개의 문제다! *)\n\nCheck 2 = 2.\n(* ===> Prop *)\n\nCheck forall n : nat, n = 2.\n(* ===> Prop *)\n\nCheck 3 = 4.\n(* ===> Prop *)\n\n(** 정말로 명제는 단지 타입만 가지고 있는 것이 아니다. 콕의 세계의 다른 것들처럼\n    똑같은 방식으로 다룰 수 있는 _일 등급 객체_이다. \n *)\n\n(** 지금까지 명제를 작성할 수 있는 한 가지 주된 위치 [Theorem] (\n    [Lemma]와 [Example]) 선언들만 보아왔다.  *)\n\nTheorem plus_2_2_is_4 :\n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** 하지만 명제는 다른 많은 방법으로 사용할 수 있다. 예를 들어,\n    [Definition]을 사용하여 명제에 다른 이름을 줄 수 있다. 마치 다른\n    종류의 식에 이름을 붙이는 것처럼 말이다.  *)\n\nDefinition plus_fact : Prop := 2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** 나중에 명제를 기대하는 어떤 상황에서 이 이름을 사용할 수\n    있다. 예를 들어, [Theorem] 선언의 주장으로 사용할 수 있다. *)\n\nTheorem plus_fact_is_true :\n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** _매개 변수를 갖는_ 명제도 작성할 수 있다. 즉, 어떤 타입의 인자들을\n    받아 명제를 리턴하는 함수들을 작성할 수 있다. *)\n\n(** 예를 들어, 다음 함수는 숫자를 받아 이 숫자가 3과 같다고 주장하는\n    명제를 리턴한다. *)\n\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\nCheck is_three.\n(* ===> nat -> Prop *)\n\n(** 콕에서 명제를 리턴하는 함수는 그 함수 인자의 _성질_을 정의한다라고 한다.\n\n    예를 들어, _단사 함수_라는 익숙한 개념을 다음과 같이 정의한다.\n *)\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\nLemma succ_inj : injective S.\nProof.\n  intros n m H. inversion H. reflexivity.\nQed.\n\n(** 동치 연산자 [=]는 [Prop]을 리턴하는 함수이기도 하다.\n\n    식 [n = m]은 [eq n m]을 보기 좋게 표현한 것인데, 콕의 [Notation]\n    방법을 사용하여 정의한 것이다. [eq]은 어떠한 타입의 원소들과 함께 사용할 수 있기\n    때문에 이 함수도 다형성을 갖는다. *)\n\nCheck @eq.\n(* ===> forall A : Type, A -> A -> Prop *)\n\n(** ([eq] 대신 [@eq]라고 작성했음을 주목하시오. [eq]에 대한 타입 인자\n    [A]는 묵시적으로 선언되어서 [eq]의 전체 타입을 보려면 묵시적 인자\n    기능을 중지시킬 필요가 있다.) *)\n\n(* ################################################################# *)\n(** * 논리적 연결자 *)\n\n(* ================================================================= *)\n(** ** 논리곱 *)\n\n(** 명제 [A]와 [B]의 _논리곱_은 [A /\\ B]라고 작성하고, [A]와 [B]가\n    둘 다 참이라는 주장을 표현한다. \n *)\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\n\n(** 논리곱을 증명하기 위해 [split] 전술을 사용한다. 이 전술로 이 문장의 각 부분에 대해\n    하나씩 두 개의 부분 목적들을 설정할 것이다. *)\n\nProof.\n  (* 수업에서 다루었음 *)\n  split.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\n(** 어떤 명제 [A]와 [B]에 대해 [A]가 참이라고 가정하고 [B]가 참이라고\n    가정하면 [A /\\ 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(** 가정들과 함께 정리를 어떤 목적에 적용하면 이 정리를 위해 필요한\n    가정들의 수만큼의 부분 목적들을 새로 만들어내는 효과가 있기\n    때문에 [and_intro]를 적용해서 [split]와 동일한 효과를 얻을 수\n    있다.\n     *)\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(** **** 연습문제: 별 두 개 (and_exercise)  *)\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** 논리곱 문장을 증명하는 것에 대해서는 이쯤 해두자. 나머지 다른\n    방향에 대해서 즉, 그 밖에 무엇인가를 증명하기 위해 논리곱 가정을\n    _사용_하려면 [destruct] 전술을 사용한다.\n\n    증명 문맥에 [A /\\ B] 형태의 가정 [H]를 포함하는 경우 [destruct H\n    as [HA HB]]라고 명령을 내리면 [H]를 이 문맥에서 없애고 두 개의\n    새로운 가정들: [A]가 참이라는 [HA]와 [B]가 참이라는 [HB]을 새로\n    추가한다.\n  *)\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  (* 수업에서 다루었음 *)\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** 대개 그러하듯이 [H]를 도입한 다음 분해하지 않고 도입하자마자\n    분해도 할 수 있다.\n *)\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(** 두 가정들 [n = 0]과 [m = 0]을 하나의 논리곱으로 묶는 것을 왜\n    꺼려했는지 궁금할 수도 있다. 왜냐하면 두 개의 분리된 전제들을\n    가지고 이 정리를 작성할 수 있었기 때문입니다.\n *)\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(** 이 정리를 작성하기 위해서라면 두 가지 작성 방법 모두\n    좋습니다. 하지만 논리곱 가정들을 어떻게 다루는지 이해하는 것이\n    중요합니다. 왜냐하면 논리곱은 증명 중간 단계에 빈번하게 발생할 수\n    있기 때문입니다. 특히 매우 큰 증명 과정 중에. 여기 간단한 예가\n    있습니다.\n *)\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  intros n m H.\n  assert (H' : n = 0 /\\ m = 0).\n  { apply and_exercise. apply H. }\n  destruct H' as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\n(** 논리곱에 대한 다른 흔하게 발생하는 상황은 [A /\\ B]가 참이지만 어떤\n    경우에는 단지 [A]만 (또는 [B]만) 필요한 상황이다. 다음 보조\n    정리들은 그러한 경우에 유용하다.\n *)\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP.  Qed.\n\n(** **** 연습문제: 별 한 개, 선택 사항 (proj2)  *)\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** 마지막으로 논리곱의 순서나 여러 피연산자들을 갖는 논리곱의 그룹을\n    재배치할 필요가 있다.  다음 교환 법칙과 결합 법칙 정리들은 그런\n    경우에 편리하다.\n *)\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  (* 수업에서 다루었음 *)\n  intros P Q [HP HQ].\n  split.\n    - (* 왼쪽 *) apply HQ.\n    - (* 오른쪽 *) apply HP.  Qed.\n  \n(** **** 연습문제: 별 두 개 (and_assoc)  *)\n(** (결합성에 대한 다음 증명에서 _내포된_ intro 패턴이 가정 [H : P /\\\n    (Q /\\ R)]을 [HP : P], [HQ : Q], [HR : R]로 분해하는 과정을\n    주목하시오. 거기에서부터 증명을 완료하시오.) *)\n\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R [HP [HQ HR]].\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** 그런데 중위 연산자 [/\\]는 사실 [and A B]를 구문상으로 직관적으로\n    보이도록 만든 표기법일 뿐이다. 즉, [and]는 두 개의 명제들을 인자로\n    받아 하나의 명제를 내는 콕 연산자이다.\n *)\n\nCheck and.\n(* ===> and : Prop -> Prop -> Prop *)\n\n(* ================================================================= *)\n(** ** 논리합 *)\n\n(** 다른 중요한 논리 연결자는 두 명제의 _논리합_이다. [A] 또는 [B]가\n    참이면 [A \\/ B]가 참이다. ([or : Prop -> Prop -> Prop]를 사용하여\n    [or A B]로 논리합을 작성할 수 있다.) *)\n\n(** 증명에서 논리합 가정을 사용하려면 [nat]이나 다른 데이터 타입에\n    대해 진행한 것과 같이 경우 별 분석으로 진행한다. 경우 별 분석은\n    [destruct]나 [intros]를 가지고 진행할 수 있다.  여기 예가 있다. *)\n\nLemma or_example :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  (* 이 패턴은 [n = 0 \\/ m = 0]에 대해 묵시적으로 경우 별로 분석한다. *)\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\n(** 역으로 논리합이 성립하는 것을 보이려면 둘 중 하나만 성립하는 것을\n    보이면 된다.  이때 [left]와 [right] 두 가지 전술을\n    사용한다. 전술의 이름에서 알 수 있듯이 첫 번째 전술은 논리합의\n    왼편을 증명하면 되고, 두 번째 전술은 오른편을 증명한다.  여기 매우\n    단순한 사용 예가 있다... *)\n\nLemma or_intro : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\n(** ... 그리고 [left]와 [right]를 둘 다 사용해야 하는 조금 더 흥미로운\n    예가 있다.  *)\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(** **** 연습문제: 별 한 개 (mult_eq_0)  *)\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 한 개 (or_commut)  *)\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** 거짓과 부정 *)\n\n(** 이제까지 주로 어떤 것이 _참_이라는 것을 증명하는 것에\n    관여해왔다. 덧셈의 교환 법칙이 성립하고, 두 리스트를 붙이는 연산은\n    결합 법칙이 성립하며, 등등. 물론 어떤 명제들이 참이 _아니다_라는\n    _부정적인_ 결과에도 관심이 있을 수 있다. 그러한 부정적인 문장들을\n    콕에서는 부정 연산자 [~]로 표현한다. *)\n\n(** 부정이 어떻게 동작하는지 보기 위해서 [Tactics] 장에서 _부정의 함축\n    원리(principle of explosion)_에 관해 논의한 것을 기억하자.  이\n    원리가 얘기하는 바는, 만일 우리가 모순을 가정하면 어떤 명제도\n    유도할 수 있다는 것이다. 이 직관을 따르면 [~ P] (\"not [P]\")를\n    [forall Q, P -> Q]로 정의할 수 있을 것이다. 콕에서는 사실 [~ P]를\n    [P -> False]로 약간 다르게 정의한다. 이때 [False]는 표준\n    라이브러리에서 정의한 모순된 명제이다.\n *)\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(** [False]는 모순된 명제이기 때문에 부정의 함축 원리를 이것에도\n    적용한다.  만일 [False]를 증명 문맥에 추가한다면 [destruct] (또는\n    [inversion]) 전술을 이 모순 명제에 적용하여 어떠한 목적도 달성할\n    수 있다.\n *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* 수업에서 다루었음 *)\n  intros P contra.\n  destruct contra.  Qed.\n\n(** 라틴어 _ex falso quodlibet_는 문자 그대로 \"네가 바라는 것\n    무엇이든지 거짓으로부터 끌어낼 수 있다\"를 의미한다. 이 것은 부정의\n    함축 원리에 대한 또 다른 흔한 이름이다.\n *)\n\n(** **** 연습문제: 별 두 개, 선택 사항 (not_implies_our_not)  *)\n(** 부정에 대한 콕의 정의로부터 바로 위에서 언급한 직관적인 명제를\n    유도할 수 있음을 보이시오. *)\n\nFact not_implies_our_not : forall (P:Prop),\n  ~ P -> (forall (Q:Prop), P -> Q).\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** 다음은 [0]과 [1]은 [nat]의 다른 원소들이라는 것을 서술하기 위해\n    [not]을 사용하는 방법이다.\n *)\n\nTheorem zero_not_one : ~(0 = 1).\nProof.\n  intros contra. inversion contra.\nQed.\n\n(** 이러한 등식에 대한 부정 형태의 문장은 충분히 자주 나타나므로\n    특별한 표기법 [x <> y]을 도입할 필요가 있다.  *)\n\nCheck (0 <> 1).\n(* ===> Prop *)\n\nTheorem zero_not_one' : 0 <> 1.\nProof.\n  intros H. inversion H.\nQed.\n\n(** 콕에서 부정을 가지고 작업하는 것에 익숙해지기 위해서 약간 연습이\n    필요하다.  비록 부정을 포함하는 문장이 왜 참인지 완벽하게 잘\n    이해할 수 있지만 콕이 그것을 이해할 수 있도록 적절한 설정을 만드는\n    것은 처음에 약간 복잡할 수 있다.  여기 몇 가지 익숙한 사실들을\n    증명해봄으로써 조금씩 익숙해지도록 하자.\n*)\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. destruct H. Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  (* 수업에서 다루었음 *)\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(** **** 연습문제: 별 두 개, 고급, 추천 (double_neg_inf)  *)\n(**  [double_neg]의 비형식적인 증명을 작성해보시오:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P]. *)\n\n(* 여기를 채우시오 *)\n(** [] *)\n\n(** **** 연습문제: 별 두 개, 추천 (contrapositive)  *)\nTheorem contrapositive : forall (P Q : Prop),\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 한 개 (not_both_true_and_false)  *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 한 개, 고급 (informal_not_PNP)  *)\n(** 명제 [forall P : Prop, ~(P /\\ ~P)]를 영어로 비형식적인 증명을\n    작성하시오. *)\n\n(* 여기를 채우시오 *)\n(** [] *)\n\n(** 비슷하게 부등식은 부정을 사용하기 때문에 부등식을 가지고 능숙하게\n    증명할 수 있으려면 약간 연습을 요구한다. 여기 유용한 요령이 있다.\n    성립하지 않는 목적 (예를 들어 [false = true]와 같은 목적)을\n    증명하려 한다면 [ex_falso_quodlibet]을 적용해서 이 목적을\n    [False]로 변경하라. 어쩌면 문맥에 있는 [~P] 형태의 가정을 사용하기\n    더 쉬울 것이다. 특히 [x<>y] 형태의 가정도 사용하기 더 쉬울 것이다.\n    *)\n\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = true *)\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  - (* b = false *)\n    reflexivity.\nQed.\n\n(** [ex_falso_quodlibet]로 추론하는 것이 상당히 흔해서 콕에서 미리\n    준비된 전술 [exfalso]을 제공하므로 이 것을 적용하자.  *)\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(** ** 참 *)\n\n(** [False] 이외에도 콕은 표준 라이브러리에 [True]도 정의한다. 말\n    그대로 참인 명제이다.  이 것을 증명하려면 미리 정의된 상수 [I :\n    True]를 사용한다.  *)\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\n(** [False]는 널리 사용되는 반면에 [True]는 매우 드물게\n    사용된다. 왜냐하면 목적으로 증명하는 것이 매우 사소해서 그다지\n    흥미롭지 않기 때문이다. 그리고 가정으로 유용한 정보를 제공하지\n    않는다. 하지만 조건부 또는 고차원 [Prop]에 대한 매개변수로서\n    복잡한 [Prop]를 정의할 때 상당히 유용할 수 있다. [True]를 그러한\n    용도로 사용하는 예제들을 나중에 보게 될 것이다.\n  *)\n\n(* ================================================================= *)\n(** ** 논리적 동치 *)\n\n(** 편리한 \"if and only if\" 연결자는 두 명제가 동일한 진리 값을\n    갖는다고 서술한다.  이 것은 함축 연결자 두 개를 논리곱으로 표현한\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  (* 수업에서 다루었음 *)\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  (* 수업에서 다루었음 *)\n  intros b. split.\n  - (* -> *) apply not_true_is_false.\n  - (* <- *)\n    intros H. rewrite H. intros H'. inversion H'.\nQed.\n\n(** **** 연습문제: 별 한 개, 선택 사항 (iff_properties)  *)\n(** [<->]이 대칭 [iff_sym] 임을 보이는 위의 증명을 가이드로 사용하여\n    이 연결자가 반사적이고 추이적인 성질도 가지고 있음을\n    증명하시오. *)\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 세 개 (or_distributes_over_and)  *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** 어떤 콕 전술을 사용하면 [iff] 문장을 특별하게 취급해서 증명 상태를\n    상세하게 다루지 않아도 됩니다. 특히 [rewrite]와 [reflexivity]\n    전술은 단지 등식뿐만 아니라 [iff] 문장을 가지고 사용할 수 있다.\n    이 동작을 사용하려면 등식뿐만 아니라 다른 공식들을 가지고 다시\n    작성하도록 하는 특별한 콕 라이브러리를 불러들일 필요가 있다. *)\n\nRequire Import Coq.Setoids.Setoid.\n\n(** 이 전술들이 [iff]를 어떻게 다루는지 보여주는 간단한 예가 있다.\n    우선 기본적인 iff 동치 한 두 가지를 증명해보자... *)\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(** [rewrite]와 [reflexivity] 전술들을 가지고 이 사실들을 이제\n    사용하여 동치 형태의 문장을 매끄럽게 증명할 수 있다. 다음은 이전에\n    증명한 바 있는 [mult_0] 결과에서 3개의 피연산자를 포함하는\n    버전이다. *)\n\nLemma mult_0_3 :\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p.\n  rewrite mult_0. rewrite mult_0. rewrite or_assoc.\n  reflexivity.\nQed.\n\n(** [apply] 전술도 [<->]과 함께 사용할 수 있다. 인자로 동치 형태가\n    주어지면 [apply]는 그 동치의 어떤 편을 사용할지 추측한다. *)\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(** ** 존재 한정 *)\n\n(** 다른 중요한 논리 연결자는 _존재 한정_이다. 타입 [T]의 어떤 [x]가\n    존재하여 [x]에 대한 어떤 성질 [P]가 성립한다는 것을 [exists x : T,\n    P]라고 작성하여 표현한다.  만일 콕이 현재 문맥으로부터 [x]의\n    타입을 유추할 수 있다면 [forall]의 경우처럼 [: T] 타입 주석을\n    생략할 수 있다. *)\n\n(** [exists x, P] 형태의 문장을 증명하려면 [x]를 위해 특별히 선택한\n    값에 대해 [P]가 성립함을 보여야 한다. 이 증명은 두 단계로\n    이루어진다. 첫째, [exists t] 전술로 우리가 아는 목격자 [t]를\n    콕에게 명시적으로 알려준다. 그런 다음 [x]가 나타난 자리를 모두\n    [x]로 바꾼 다음 [P]가 성립함을 증명한다. *)\n\nLemma four_is_even : exists n : nat, 4 = n + n.\nProof.\n  exists 2. reflexivity.\nQed.\n\n(** 역으로 만일 존재 한정 [exists x, P] 명제를 현재 문맥에서 가지고\n    있다면 이 것을 분해해서 어떤 목격자 [x]와 [x]에 대해 [P]가\n    성립한다는 가정을 얻어 낼 수 있다. *)\n\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  (* 수업에서 다루었음 *)\n  intros n [m Hm]. (* 여기 묵시적으로 [destruct]를 적용함을 주목하시오 *)\n  exists (2 + m).\n  apply Hm.  Qed.\n\n(** **** 연습문제: 별 한 개 (dist_not_exists)  *)\n(** 모든 [x]에 대해 [P]가 성립하면 [P]가 성립하지 않는 [x]가 없음을\n    증명하시오. *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 두 개 (dist_exists_or)  *)\n(** 논리합에 대한 존재 한정 분배를 증명하시오. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n  (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n   (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * 명제를 다루는 프로그래밍 *)\n\n(** 이제까지 살펴본 논리 연결자들은 간단한 명제에서부터 복잡한 것들을\n    정의하는데 풍성한 어휘를 제공한다. 예를 들어 원소 [x]가 리스트\n    [l]에 나타난다는 주장을 표현하는 법을 살펴보자. 이 성질은 간단한\n    재귀적 구조를 가지고 있음을 주목하시오.  *)\n(**    - 만일 [l]이 비어있는 리스트이면 [x]는 그 리스트에 나타날 \n         수 없다. 그래서 [x]는 [l]에 나타난다는 성질은 간단히 \n         거짓이다. *)\n(**    - 그렇지 않다면 [l]은 [x' :: l'] 형태이다. 이 경우 [x]가 \n         [x']가 일치하거나 [l']에 나타나면 [x]가 [l]에 나타난다. *)\n\n(** 이 성질을 원소와 리스트를 받아 명제를 리턴하는 간단한 재귀 함수로\n    바로 변환할 수 있다. *)\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x' = x \\/ In x l'\n  end.\n\n(** [In]을 구체적인 리스트에 적용하면 내포된 논리합들이 쭉 나열된\n    형태로 펼쳐진다. *)\n\nExample In_example_1 : In 4 [1; 2; 3; 4; 5].\nProof.\n  (* 수업에서 다루었음 *)\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  (* 수업에서 다루었음 *)\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\nQed.\n(** (_덧붙여서_ 마지막 경우를 이행하기 위해서 비어있는 패턴을 사용함을\n    주목하시오.) *)\n\n(** [In]에 대한 더 일반적 형태이고 고차원인 보조 정리들도 증명할 수\n    있다.\n\n    다음 보조 정리 증명에서 [In]을 변수에 적용하여 시작하고 그 변수에\n    대한 경우 별 분석을 하는 경우만 펼쳐지는 것을 주목하시오. *)\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, 모순 *)\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(** 이렇게 재귀적으로 명제를 정의하는 방법은 어떤 경우에는 편리하지만\n    약간의 단점도 있다. 특히 콕에서 재귀 함수를 정의할 때 반드시\n    종료해야하는 조건에 관한 제약에 관한 것이다. 다음 장에서 명제들을\n    _귀납적으로_ 정의하는 법을 살펴볼 것이다. 이 방법은 나름의 장점과\n    한계를 갖는 다른 기법이다. *)\n\n(** **** 연습문제: 별 두 개 (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  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 두 개 (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  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 세 개, 추천 (All)  *)\n(** 명제를 리턴하는 함수를 그 함수 인자들의 _성질_로 볼 수 있다고 한\n    점을 다시 기억하시오. 예를 들어 [P]가 [nat -> Prop] 타입을\n    갖는다면 [P n]은 [n]에 대해 성질 [P]가 성립함을 서술한다.\n\n    [In]으로부터 영감을 받아 리스트 [l]의 모든 원소들에 대해 성립하는\n    어떤 성질 [P]를 기술하는 재귀 함수 [All]을 작성하시오. 당신이\n    작성한 정의가 정확함을 확신하기 위해 [All_In] 보조 정리를 아래에서\n    증명하시오. (물론 단순히 [All_In]의 왼편을 기술하지는 않도록\n    한다.) *)\n\nFixpoint All {T : Type} (P : T -> Prop) (l : list T) : Prop\n  (* 이 줄을 \":= _여러분의 정의_\"로 다시 작성하시오 *). 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  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 세 개 (combine_odd_even)  *)\n(** 아래 [combine_odd_even] 함수의 정의를 완성하시오.  인자로 숫자들의\n    두 가지 성질들, [Podd]와 [Peven]을 받아 [n]이 홀수 일 때 [P n]이\n    [Podd n]과 동치이고 [n]이 짝수 일 때 [P n]이 [Peven n]과 동치인\n    성질 [P]를 리턴해야 한다. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop\n  (* 이 줄을 \":= _여러분의 정의_\"로 다시 작성하시오 *). Admitted.\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  (* 여기를 채우시오 *) 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  (* 여기를 채우시오 *) 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  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * 정리를 인자에 적용하기 *)\n\n(** 콕이 많은 다른 증명 보조기와 구분되는 한 가지 특징은 _증명_을 일\n    등급 객체로 다룬다는 것이다.\n\n    이것에 대해 이야기할 것이 많이 있지만 콕을 사용하기 위해서 이것을\n    상세히 이해할 필요는 없다. 이 절은 단지 맛보기만 제공하고 더 깊은\n    탐구는 선택 사항으로 분류된 장 [ProofObjects]와\n    [IndPrinciples]에서 다룬다. *)\n\n(** [Check] 명령어를 사용하여 콕으로 하여금 식의 타입을 출력하도록\n    요청하는 것을 보아왔다. [Check] 명령어를 사용하여 특정 식별자가\n    가리키는 정리가 무엇인지 콕에게 물어볼 수도 있다. *)\n\nCheck plus_comm.\n(* ===> forall n m : nat, n + m = m + n *)\n\n(** 콕은 [Check]으로 어떤 식의 _타입_을 출력하는 것과 동일한 방법으로\n    [plus_comm] 정리의 _문장_을 출력한다. 왜 그럴까? *)\n\n(** 그 이유는 [plus_comm] 식별자는 사실 _증명 객체_를 가리키고 있기\n    때문이다.  증명 객체는 [forall n m: nat, n + m = m + n] 문장이\n    참임을 증명하는 논리적 유도과정을 표현하는 자료 구조이다. 이\n    객체의 타입이 _바로_ 이 객체가 증명하는 정리의 문장이다.  *)\n\n(** 직관적으로 정리의 문장은 그 정리를 사용할 목적이기 때문에 정리\n    식별자를 [Check]로 확인하면 그 문장이 타입으로 출력되는 것이\n    일리가 있다. 이것은 마치 계산을 담고 있는 객체의 타입이 그 객체를\n    가지고 우리가 할 수 있는 것을 말해주는 것과 비슷하다. 예를 들어,\n    [nat -> nat -> nat] 타입의 식을 가지고 있다면 그 식에 두 개의\n    [nat]들을 인자로 주어 다시 [nat]을 돌려받을 수 있다. 비슷하게 [n =\n    m -> n + n = m + m] 타입의 객체를 가지고 있고 타입 [n = m]의 어떤\n    \"인자\"를 주면 [n + n = m + m]을 유도할 수 있다. *)\n\n(** 그 과정을 생각하면 이러한 유사점은 한 걸음 더 나아갈 수\n    있다. 정리를 마치 함수인 것처럼 타입이 매칭 되는 가정에 적용하여\n    중간 단계의 주장들을 거치지 않고 정리의 결과를 그 가정에 맞추어\n    특화시킬 수 있다. 예를 들어 다음 결과를 증명하기를 원했다고\n    가정하자. *)\n\nLemma plus_comm3 :\n  forall n m p, n + (m + p) = (p + m) + n.\n\n(** 처음 보기에는 [plus_comm]을 두 번 적용하여 양 편을 일치하도록\n    작성하여 이 정리를 증명할 수 있어야 할 것처럼 보인다. 하지만 두\n    번째 [rewrite]는 첫 번째 적용한 결과를 되돌려 놓는 문제가 있다.\n    *)\n\nProof.\n  intros n m p.\n  rewrite plus_comm.\n  rewrite plus_comm.\n  (* 처음 시작했던 곳으로 돌아왔다... *)\nAbort.\n\n(** 이 문제를 해결하는 한 가지 간단한 방법은 (우리가 이미 아는\n    방법만을 사용한다면) 우리가 원하는 정확한 그 곳에 다시 작성 전술을\n    적용할 수 있도록 [plus_comm]의 특화 버전을 유도하기 위해서\n    [assert]를 사용하는 것이다. *)\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(** 더 우아한 방법은 [plus_comm]을 적용하기를 원하는 인자에 직접\n    적용하는 것이다.  마치 다형성 함수에 타입 인자를 적용하는 것과\n    매우 흡사한 방법이다. *)\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(** 정리 이름을 인자로 받는 거의 모든 전술들을 이런 방식으로 \"정리를\n    함수처럼 사용\"할 수 있다. 정리를 적용할 때 함수를 적용하는 것과\n    동일한 추론 방법을 사용하는 점을 또한 주목하시오. 이렇게, 예를\n    들어 인자로 와일드카드를 주어 추론되도록 하거나 정리의 어떤\n    가정들을 묵시적으로 주어지도록 선언하는 것이 가능하다. 이 특징들을\n    아래 증명에서 예시로 보여준다. *)\n\nExample lemma_application_ex :\n  forall {n : nat} {ns : list nat},\n    In n (map (fun m => m * 0) ns) ->\n    n = 0.\nProof.\n  intros n ns H.\n  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H)\n           as [m [Hm _]].\n  rewrite mult_0_r in Hm. rewrite <- Hm. reflexivity.\nQed.\n\n(** 이 절에서 보여준 관용 표현들의 더 많은 예들을 나중에 볼 것이다. *)\n\n(* ################################################################# *)\n(** * 콕 vs. 집합론 *)\n\n(** 콕의 핵심 논리 부분, _Calculus of Inductive Constructions_,은\n    정확하고 엄밀하게 증명을 쓰기 위해 수학자들이 사용한 다른 정형\n    시스템과 비교할 때 몇 가지 중요한 측면에서 다르다. 예를 들어,\n    종이와 연필로 증명하는 수학을 위한 가장 잘 알려진 기초는\n    Zermelo-Fraenkel 집합론(ZFC)이다. 이 이론에서 수학적 객체는\n    잠재적으로 많은 다른 집합들의 원소가 될 수 있다. 반면에 콕의\n    논리에서 식은 기껏해야 한 가지 타입의 원소이다. 이 차이점은\n    비형식적인 수학적 개념들을 표현하는 약간의 다른 방법들로 귀결되곤\n    한다. 하지만 다른 방법이긴 하지만 대체로 꽤 자연스럽고 쉽게 작업할\n    수 있다. 예를 들어 자연수 [n]은 짝수 집합에 속한다고 말하는 대신\n    콕에서는 [ev : nat -> Prop]는 짝수를 기술하는 성질로 [ev n]이\n    성립한다고 이야기 할 것이다.\n    \n    하지만 표준 수학적 추론으로 콕으로 변환하기 귀찮을 수 있고 때로는\n    콕의 핵심 논리에 새로운 공리를 추가하지 않으면 심지어 그러한\n    변환이 불가능한 경우 조차 있다. 이 두 세계들 사이의 가장 중요한\n    차이점들 일부를 간략하게 논의하면서 이 장을 마친다. *)\n\n(* ================================================================= *)\n(** ** 함수 외연성 *)\n\n(** 지금까지 살펴본 동치 주장은 대부분 귀납적 타입 ([nat], [bool],\n    등등)의 원소들에 관한 것이었다. 하지만 콕의 동치 연산자는 다형성이\n    있기 때문에 이 타입들의 원소들에 대해서만 가능한 것은 아니다. 특히\n    두 _함수_가 서로 동일하다고 주장하는 명제를 작성할 수 있다. *)\n\nExample function_equality_ex1 : plus 3 = plus (pred 4).\nProof. reflexivity. Qed.\n\n(** 동일한 수학적 사례에서 두 함수 [f]와 [g]는 동일한 출력을 내면\n    동일한 것으로 간주한다.\n\n    (forall x, f x = g x) -> f = g\n\n    이것을 _함수 외연성_ 원리라고 부른다.\n\n    쉽게 설명하자면, \"외연성 성질\"은 객체의 관찰 가능한 동작에\n    속한다. 마찬가지로 함수 외연성은 간단히 함수로부터 관찰할 수 있는\n    것(예를 들어, 콕 식에서 함수를 적용한 다음 얻는 결과)으로 함수를\n    구분하는 것을 의미한다.\n\n    함수 외연성은 콕의 기본 공리가 아니다. 어떤 \"합리적인\" 명제들을\n    증명할 수 없을 수도 있다는 것을 뜻한다. *)\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n   (* Stuck *)\nAbort.\n\n(** 하지만 [Axiom] 명령어를 사용하여 콕의 논리 핵심에 함수 외연성을\n    추가할 수 있다. *)\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(** [Axiom]은 정리를 기술하고 [Admitted]를 사용하여 그 증명을 생략한\n    것과 똑같은 효과를 낸다. 이 명령어를 사용하면 하지만 나중에 다시\n    돌아와서 채우는 그런 것은 아니라는 것을 경고한다! *)\n\n(** 이제 증명에서 함수 외연성을 사용할 수 있다. *)\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n  apply functional_extensionality. intros x.\n  apply plus_comm.\nQed.\n\n(** 콕 논리에 새로운 공리를 추가할 때 당연히 주의해야 한다. 왜냐하면\n    새로운 공리는 콕을 _일관성을 잃게_ 만들 수 있기 때문이다. 즉,\n    [False]를 포함한 모든 명제를 증명하도록 만들 수도 있다!\n\n    불행히도 이 공리가 더해도 안전한지 판단할 수 있는 간단한 방법은\n    없다.  일반적으로 특정 공리 조합의 일관성을 확인할 때 힘든 작업이\n    필요하다.\n\n    하지만 함수 외연성을 추가해도 _일관성을 유지한다고_ 알려져\n    있다. *)\n\n(** 특정 증명이 추가된 공리에 의존하는지 검사하기 위해서 [Print\n    Assumptions] 명령어를 사용한다.  *)\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(** **** 연습문제: 별 네 개 (tr_rev)  *)\n(** 리스트를 뒤집는 함수 [rev] 정의는 각 단계에서 [app]를 호출하는\n    문제가 있다.  [app]를 리스트 길이에 비례해서 실행 시간이 걸리므로\n    [rev]는 그 길이의 제곱에 해당하는 실행 시간이 걸린다. 다음 정의로\n    이러한 문제를 개선할 수 있다.  *)\n\nFixpoint rev_append {X} (l1 l2 : list X) : list X :=\n  match l1 with\n  | [] => l2\n  | x :: l1' => rev_append l1' (x :: l2)\n  end.\n\nDefinition tr_rev {X} (l : list X) : list X :=\n  rev_append l [].\n\n(** 이 버전을 _꼬리에서 재귀 함수를 호출_한다고 부른다. 왜냐하면 재귀\n    함수 호출이 맨 마지막에서 수행하기 때문이다. 즉, 재귀 함수 호출\n    다음에 [++]를 실행할 필요가 없다. 좋은 컴파일러는 이런 경우에 매우\n    효율적인 코드를 생성할 것이다. 두 정의가 정말로 동일하다는 것을\n    증명하시오. *)\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\n(* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** 명제와 부울 *)\n\n(** 콕에서 논리적 사실을 표현하는 두 가지 다른 방법을 보았다. ([bool]\n    타입의) _부울_을 사용하는 방법과 ([Prop] 타입의) _명제_를 사용하는\n    방법이다.\n\n    예를 들어, [n]이 짝수라고 주장하기 위해서 (1) [evenb n]은 [true]를\n    리턴한다라고 말하거나 (2) [n = double k]인 어떤 [k]가 존재한다고\n    얘기할 수 있다. 정말로 짝수에 대한 이 두 가지 개념들은\n    동일하다. 이를 몇 가지 보조 정리들로 쉽게 보일 수 있다.\n\n    부울 [evenb n]은 명제 [exists k, n = double k]를 _반영한다고_ 종종\n    얘기한다. *)\n\nTheorem evenb_double : forall k, evenb (double k) = true.\nProof.\n  intros k. induction k as [|k' IHk'].\n  - reflexivity.\n  - simpl. apply IHk'.\nQed.\n\n(** **** 연습문제: 별 세 개 (evenb_double_conv)  *)\nTheorem evenb_double_conv : forall n,\n  exists k, n = if evenb n then double k\n                else S (double k).\nProof.\n  (* 힌트: [Induction.v]의 [evenb_S] 보조 정리를 사용하시오. *)\n  (* 여기를 채우시오 *) 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(** 비슷하게 두 숫자 [n]과 [m]이 같다고 말하기 위해서 (1) [beq_nat n\n    m]이 [true]를 리턴한다고 말하거나 (2) [n = m]이라고 말할 수\n    있다. 이 두 개념들은 동일하다. *)\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(** 순수한 논리적 관점에서 어떤 주장을 부울과 명제로 동일하게 작성할\n    수 있다고 하더라도 _증명 과정_에서 동일할 필요는 없다. 동등성은 한\n    가지 극단적인 예를 제공한다.  [beq_nat n m = true]를 알고 있다고\n    해도 [n]과 [m]이 관여한 증명에 일반적으로 직접적인 도움이 되지\n    못한다. 하지만 이 문장을 동등한 [n = m] 형태로 바꾸면 이 것을\n    가지고 다시 작성 전술에 활용할 수 있다.\n\n    짝수의 경우에도 흥미롭다. [even_bool_prop] (즉, [evenb_double],\n    명제에서 부울식 주장으로 향하는)의 역 방향을 증명할 때 [k]에 대한\n    귀납법을 간단히 사용했다.  반면에 역 ([evenb_double_conv]\n    연습문제)은 현명한 일반화가 필요했다.  왜냐하면 [(exists k, n =\n    double k) -> evenb n = true]를 직접 증명할 수 없기 때문이다.\n\n    이 예제들에서 명제로 주장하는 것은 부울 주장보다 더\n    유용하다. 하지만 항상 그러한 것은 아니다. 예를 들어, 함수 정의에서\n    일반적인 명제가 참인지 거짓인지 테스트할 수 없다.  그 결과 다음\n    코드를 콕이 거절한다. *)\n\nFail Definition is_even_prime n :=\n  if n = 2 then true\n  else false.\n\n(** 콕은 [bool] (또는 두 원소를 갖는 어떤 다른 귀납적 타입) 원소를\n    기대했지만 [n = 2]가 [Prop] 타입이라고 불평할 것이다.  이 에러\n    메시지를 내는 이유는 콕의 핵심 언어의 _계산적인_ 성질과 관련이\n    있다. 콕이 표현할 수 있는 모든 함수는 계산 가능하고 항상\n    종료하도록 핵심 언어를 설계하였다. 이렇게 설계한 한 가지 이유는 콕\n    증명으로부터 실행 가능한 프로그램을 추출하기 위한 것이다. 그 결과\n    콕에서 [Prop]은 어떤 주어진 명제가 참인지 거짓인지 판단하는\n    보편적인 경우 별 분석 연산을 _가지고 있지 않다_. 왜냐하면 그러한\n    연산을 허용하면 계산할 수 없는 함수를 작성할 수 있기 때문이다.\n\n    비록 일반적인 계산 가능하지 않는 성질들을 부울 계산으로 나타낼 수\n    없지만 많은 _계산 가능한_ 성질들조차 [bool]보다 [Prop]을 사용해서\n    표현하는 것이 더 쉽다는 것을 주목할만하다. 왜냐하면 콕에서 재귀\n    함수를 정의하는데 큰 제약이 있기 때문이다. 예를 들어 다음 장에서\n    [Prop]을 사용하여 정규식과 문자열을 매칭 하는 성질을 어떻게\n    정의하는지 보여준다. [bool]을 가지고 똑같은 것을 한다면 정규식\n    매치 함수를 작성하는 것과 다름이 없을 것인데, 더 복잡하고 이해하기\n    어렵고, 추론에 활용하는 것이 더 어려울 것이다.\n\n    역으로 부울을 가지고 사실을 기술하는 것의 중요한 부수적인 이점은\n    콕 식의 계산을 통해 어떤 증명을 자동화할 수 있다는 것이다.  이\n    기법은 _반사에 의한 증명_이라 알려져 있다. 다음 문장을\n    고려해보자. *)\n\nExample even_1000 : exists k, 1000 = double k.\n\n(** 이 사실을 가장 직접적으로 증명하는 것은 [k]의 값을 명확히 주는 것이다. *)\n\nProof. exists 500. reflexivity. Qed.\n\n(** 반면에 해당하는 부울 기반 문장에 대한 증명은 한층 더 간단하다. *)\n\nExample even_1000' : evenb 1000 = true.\nProof. reflexivity. Qed.\n\n(** 흥미로운 점은, 두 개념이 동일하기 때문에 500을 명시적으로 언급하지\n    않고 부울 기반 문장을 사용하여 앞의 명제를 증명할 수 있다는\n    점이다. *)\n\nExample even_1000'' : exists k, 1000 = double k.\nProof. apply even_bool_prop. reflexivity. Qed.\n\n(** 이 경우 증명 크기에 관하여 얻은 것이 비록 없지만 더 큰 증명의 경우\n    반사를 사용하면 훨씬 더 간단하게 증명할 수 있곤 한다. 극단적인\n    예로써 유명한 _4색 정리_에 대한 콕 증명에서 반사를 사용하여 부울\n    계산의 수백 가지 다른 경우들을 분석하는 것을 줄였다. 반사에 대해\n    매우 깊이 설명하지 않지만 부울과 일반적인 명제의 보완적인 장점들을\n    보여주는 좋은 예이다.\n *)\n\n(** **** 연습문제: 별 두 개 (logical_connectives)  *)\n(** 다음 보조 정리들은 이 장에서 공부한 명제의 연결자들을 해당하는\n    부울 연산과 연관시킨다. *)\n\nLemma andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 한 개 (beq_nat_false_iff)  *)\n(** 다음 정리는 [beq_nat_true_iff]의 또 다른 \"부정\" 형식이다. 이것은\n    어떤 상황에서 더 편리하다 (나중에 예제를 살펴 볼 것이다). *)\n\nTheorem beq_nat_false_iff : forall x y : nat,\n  beq_nat x y = false <-> x <> y.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 세 개 (beq_list)  *)\n(** 어떤 타입 [A]의 원소들이 동일한지 비교하는 부울 연산자 [beq]에\n    대해 [A] 타입 원소를 갖는 리스트가 동일한지 비교하는 함수\n    [beq_list beq]를 정의할 수 있다. 아래의 [beq_list] 함수 정의를\n    완성하시오. 그 정의가 올바른지 확인하기 위해 [beq_list_true_iff]\n    보조 정리를 증명하시오. *)\n\nFixpoint beq_list {A : Type} (beq : A -> A -> bool)\n                  (l1 l2 : list A) : bool\n  (* 이 줄을 \":= _여러분의 정의_\"로 다시 작성하시오 *). 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(* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 두 개, 추천 (All_forallb)  *)\n(** [Tactics] 장의 연습문제 [forall_exists_challenge]에서 [forallb]\n    함수를 기억해보자. *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => true\n  | x :: l' => andb (test x) (forallb test l')\n  end.\n\n(** 위 연습문제의 [forallb]를 [All]를 연관짓는 아래의 정리를\n    증명하시오. *)\n\nTheorem forallb_true_iff : forall X test (l : list X),\n   forallb test l = true <-> All (fun x => test x = true) l.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n\n(** 함수 [forallb]의 중요한 성질들 중에 이 명세로 표현되지 않는 것이\n    있는가?  *)\n\n(* 여기를 채우시오 *)\n(** [] *)\n\n(* ================================================================= *)\n(** ** 고전적 vs. 건설적 논리 *)\n\n(** 명제 [P]가 성립하는지 검사하는 것은 가능하지 않다고\n    하였다. _증명_!에도 유사한 제약이 적용된다는 것에 놀랄 수도\n    있다. 달리 설명하면 다음의 직관적인 유추 원리를 콕에서 유도할 수\n    없다. *)\n\nDefinition excluded_middle := forall P : Prop,\n  P \\/ ~ P.\n\n(** 왜 그러한지 과정 측면에서 이해하자면 [P \\/ Q] 형태의 문장을\n    증명하기 위해 [left]와 [right] 전술을 사용하였음을 기억하자. 각각\n    논리합의 해당하는 편이 성립하는 증명을 가지고 있다는\n    요구한다. 하지만 [excluded_middle]에서 전칭 한정 [P]의 경우\n    _임의의_ 명제이고 그 것에 대해 아무것도 알지 못한다.  [left]와\n    [right] 중에 어느 것을 적용할 지 선택할 충분한 정보가 없다.\n    왜냐하면 콕은 함수 안에서 [P]가 성립하는지 여부를 기계적으로\n    결정하기 위해서 충분한 정보를 갖고 있지 않는 것이기 때문이다. *)\n\n(** 하지만 [P]를 어떤 부울 식 [b]로 투영할 수 있다면 [P]가 성립하는지\n    여부를 아는 것은 매우 쉽다. [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(** 특히, 자연수 [n]과 [m]에 대한 [n = m] 식에 대해서 excluded_middle\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.\n  apply beq_nat_true_iff.\nQed.\n\n(** 콕에 일반적인 excluded_middle이 성립하지 않는 것에 대해 이상하게\n    생각할 수도 있다. 왜냐하면 결국 모든 주장은 참 또는 거짓이어야\n    하기 때문이다.  그럼에도 불구하고 이 것을 가정하지 않는 장점이\n    있다. 콕의 문장은 표준 수학에서 유사한 문장보다 더 강한 주장을\n    만들 수 있기 때문이다. 좋은 예로 [exists x. P x]를 콕에서 증명하면\n    [P x]를 증명하는 [x]의 값을 명시적으로 보여줄 수 있다.  다르게\n    설명하면 존재에 대한 모든 증명은 반드시 _건설적_이다. *)\n\n(** excluded_middle을 가정하지 않는 콕과 같은 논리를 _건설적 논리_라고\n    부른다.\n\n    임의의 명제에 대해 excluded_middle이 성립하는 ZFC와 같은 더 자주\n    사용하는 논리 시스템을 _고전적_이라고 부른다. *)\n\n(** 다음 예는 exlcluded_middle을 가정하면 왜 비 건설적인 증명이 될\n    수도 있는지를 보여준다.\n\n    _주장_: [a ^ b]가 유리수인 무리수 [a]와 [b]가 존재한다.\n\n    _증명_: [sqrt 2]가 무리수라는 것을 증명하는 것은 어렵지 않다. 만일\n    [sqrt 2 ^ sqrt 2]가 유리수라면 [a = b = sqrt 2]를 취하는 것으로\n    증명할 수 있다. 만일 유리수가 아니라면 [a = sqrt 2 ^ sqrt 2]라\n    하고 [b = sqrt 2]로 놓자. [a ^ b = sqrt 2 ^ (sqrt 2 * sqrt 2) =\n    sqrt 2 ^ 2 = 2]. []\n    \n    여기서 무슨 일이 벌어졌는지 이해하는가? [sqrt 2 ^ sqrt 2]가\n    유리수인 경우와 그렇지 않은 경우를 excluded_middle을 사용하여\n    분리해서 고려하였다. 하지만 어느 것이 성립하는지 알지 못한다! 바로\n    그 것 때문에 그러한 [a]와 [b]가 존재하는 것을 아는 문제를 우회해서\n    매듭지었지만 실제 값이 무엇인지 결정할 수 없다 (적어도 이 논법을\n    사용하여).\n\n    건설적 논리만큼 유용하지만 한계를 가지고 있다. 고전적 논리에서\n    쉽게 증명할 수 있지만 훨씬 복잡한 건설적 증명을 필요로 하는 많은\n    문장들이 있다. 그리고 건설적 방법으로 전혀 증명할 수 없다고 알려진\n    것도 있다! 운 좋게도 함수 외연성 처럼 excluded_middle은 콕의\n    논리와 호환 가능하다고 알려져 있어서 공리로 안전하게 추가할 수\n    있다. 하지만 이 책에서는 그것을 필요로 하지 않을 것이다. 왜냐하면\n    우리가 다루는 결과들은 건설적 논리로 무시할만한 추가 비용으로 모두\n    증명할 수 있기 때문이다.\n\n    건설적 추론에서 어떤 증명 기법들을 피해야 하는지 이해하는데 약간의\n    연습이 필요하다. 하지만 모순에 의한 주장은 특히 비건설적 증명을\n    초래하는 것으로 악명이 높다. 전형적인 예를 살펴보자. 어떤 성질\n    [P]를 갖는 [x]가 존재한다는 것(즉, [P x])를 증명하기를 원한다고\n    가정하자.  우리의 결론이 거짓이라고 가정하면서 시작한다. 즉\n    [~exists x, P x].  이 가설로부터 [forall x, ~ P x]를 유도하는 것은\n    어렵지 않다. 이 중간 단계의 사실이 모순을 일으킨다는 것을 보일 수\n    있다면 [P x]를 만족하는 [x]의 값을 결코 보이지 않고도 존재 증명에\n    도달한다!\n\n    여기에서 건설적 관점에서 바라볼 때 기술적 결함은 [~ ~(exists x, P\n    x)] 증명을 사용하여 [exists x, P x]를 증명하였다고 주장한\n    것이다. 임의의 문장에서 이중 부정을 제거하는 것을 허용하는 것은\n    excluded_middle을 가정하는 것과 동일하다.  아래의 연습문제에서\n    보여준다. 이렇게 이러한 논법은 새로운 공리를 추가하지 않고 콕에서\n    표현할 수 없다. *)\n\n(** **** 연습문제: 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  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 세 개, 고급 (not_exists_dist)  *)\n(** 다음 두 주장이 동일하다는 것은 바로 고전적 논리의 정리이다:\n\n    ~ (exists x, ~ P x) forall x, P x\n\n    위의 [dist_not_exists] 정리는 이 등식의 한쪽만\n    증명한다. 흥미롭게도 다른 방향은 건설적 논리에서 증명할 수\n    없다. 이 연습문제에서 당신이 할 일은 그 다른 방향이\n    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  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 다섯 개, 선택사항 (classical_axioms)  *)\n(** 도전적인 사람은 Bertot와 Casteran이 작성한 책 (p. 123)에서 가져온\n    연습문제를 풀어보자. 다음 네 개의 문장들 각각은\n    [excluded_middle]와 함께 고전적 논리를 특징짓는 문장이라고 간주할\n    수 있다. 콕으로는 어떤 것도 증명할 수 없다. 하지만 고전적 논리로\n    증명하기를 원한다면 네 개 중 어떠한 것 하나를 일관성 있게 추가할\n    수 있다.\n\n    모든 다섯 개 명제 (아래 네 개와 [excluded_middle])가 동등함을\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(* 여기를 채우시오 *)\n(** [] *)\n\n(** $Date: 2017-08-22 17:13:32 -0400 (Tue, 22 Aug 2017) $ *)\n", "meta": {"author": "kwanghoon", "repo": "sf", "sha": "6937265f0ba88524af8a5e0da1cb19d49c079875", "save_path": "github-repos/coq/kwanghoon-sf", "path": "github-repos/coq/kwanghoon-sf/sf-6937265f0ba88524af8a5e0da1cb19d49c079875/Logic_ko_utf8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.652873729602056}}
{"text": "(* Copyright 2012-2015 by Adam Petcher.\t\t\t\t*\n * Use of this source code is governed by the license described\t*\n * in the LICENSE file at the root of the source tree.\t\t*)\nSet Implicit Arguments.\n\nRequire Import List.\nRequire Import FCF.Fold.\n\nSection In_gen.\n  Variable A : Type.\n  Variable ea : A -> A -> Prop.\n\n  Hypothesis ea_symm : \n    forall a1 a2, ea a1 a2 -> ea a2 a1.\n\n  Hypothesis ea_trans : \n    forall a1 a2 a3,\n      ea a1 a2 ->\n      ea a2 a3 ->\n      ea a1 a3.\n\n  Fixpoint In_gen(a : A)(ls : list A) : Prop :=\n    match ls with\n      | nil => False\n      | a' :: ls' =>\n        ea a a' \\/ In_gen a ls'\n    end.\n\n  Theorem In_gen_equiv_compat : \n    forall (ls : list A)(a1 a2 : A),\n      ea a1 a2 ->\n      In_gen a1 ls ->\n      In_gen a2 ls.\n    \n    induction ls; intuition; simpl in *.\n    intuition.\n    left.\n    eapply ea_trans.\n    eapply ea_symm.\n    eauto.\n    trivial.\n\n    right.\n    eauto.\n    \n  Qed.\n\nEnd In_gen.\n\nTheorem In_gen_eq : \n  forall (A : Type)(a : A)(ls : list A),\n    In a ls <-> In_gen eq a ls.\n  \n  induction ls; intuition; simpl in *.\n  intuition.\n  intuition.\n  \nQed.\n\nSection NoDup_gen.\n\n  Variable A : Type.\n  Variable ea : A -> A -> Prop.\n\n  Inductive NoDup_gen : list A -> Prop :=\n  | NoDup_gen_nil : NoDup_gen nil\n  | NoDup_gen_cons : \n      forall (a : A)(ls : list A),\n        (~In_gen ea a ls) -> \n        NoDup_gen ls ->\n        NoDup_gen (a :: ls).\n\nEnd NoDup_gen.\n\n  \nTheorem NoDup_gen_eq : \n  forall (A : Type)(ls : list A),\n    NoDup ls <-> NoDup_gen eq ls.\n  \n  induction ls; intuition; simpl in *.\n  econstructor.\n  econstructor.\n  \n  inversion H1; clear H1; subst.\n  econstructor.\n  intuition.\n  eapply H4.\n  eapply  In_gen_eq.\n  trivial.\n  intuition.\n  \n  inversion H1; clear H1; subst.\n  econstructor.\n  intuition.\n  eapply H4.\n  eapply In_gen_eq.\n  trivial.\n  intuition.\n  \nQed.\n\nSection NoDup_gen_map.\n\n  Variable A B : Type.\n  Variable ea : A -> A -> Prop.\n  Variable eb : B -> B -> Prop.\n  Variable f : A -> B.\n\n  Hypothesis ea_symm : \n    forall a1 a2,\n      ea a1 a2 -> ea a2 a1.\n\n  Hypothesis ea_trans : \n    forall a1 a2 a3,\n      ea a1 a2 ->\n      ea a2 a3 ->\n      ea a1 a3.\n\n  Hypothesis ea_func : \n    forall a1 a2, ea a1 a2 -> eb (f a1) (f a2).\n\n  Hypothesis eb_symm : \n    forall b1 b2,\n      eb b1 b2 -> eb b2 b1.\n\n  Hypothesis eb_trans : \n    forall b1 b2 b3,\n      eb b1 b2 ->\n      eb b2 b3 ->\n      eb b1 b3.\n\n  Hypothesis ea_refl : \n    forall a y,\n      eb (f a) y ->\n      ea a a .\n\n  Hypothesis eb_func : \n    forall a1 a2,\n      eb (f a1) (f a2) -> ea a1 a2.\n\n  Theorem In_gen_map_iff\n  : forall (l : list A) (y : B),\n      (In_gen eb y (map f l) <-> (exists x : A, eb (f x) y /\\ In_gen ea x l)).\n    \n    induction l; intuition; simpl in *.\n    intuition.\n    destruct H.\n    intuition.\n    intuition.\n    econstructor.\n    intuition.\n    eapply eb_symm.\n    eauto.\n\n    left.\n    eapply ea_refl.\n    eapply eb_symm.\n    eauto.\n    \n    specialize (IHl y).\n    intuition.\n    destruct H2.\n    intuition.\n    econstructor.\n    split.\n    eauto.\n    intuition.\n    \n    destruct H.\n    intuition.\n    left.\n    eapply eb_trans.\n    eapply eb_symm.\n    eauto.\n    eapply ea_func.\n    trivial.\n    \n    right.       \n    specialize (IHl y).\n    intuition.\n    eapply H2.\n    econstructor.\n    intuition.\n    eauto.\n    trivial.\n  Qed.\n\n  Theorem map_NoDup_gen : \n    forall (ls : list A),\n      NoDup_gen ea ls ->\n      NoDup_gen eb (map f ls).\n    \n    induction ls; intuition; simpl in *.\n    econstructor.\n    \n    inversion H; clear H; subst.\n    econstructor.\n    intuition.\n    eapply H2.\n    eapply In_gen_map_iff in H.\n    destruct H.\n    intuition.\n    eapply In_gen_equiv_compat; [ eauto | eauto | idtac | idtac].\n    eapply eb_func.\n    eauto.\n    trivial.\n\n    eauto.\n    \n  Qed.\n  \nEnd NoDup_gen_map.\n\nRequire Import FCF.RepeatCore.\n \nTheorem In_gen_weaken : \n  forall (A : Type)(e1 e2 : A -> A -> Prop) ls a,\n    In_gen e1 a ls ->\n    (forall a', e1 a a' -> e2 a a') ->\n    In_gen e2 a ls.\n  \n  induction ls; intuition; simpl in *.\n  intuition.\n  \nQed.\n\nLemma flatten_NoDup_gen : \n  forall (A : Set)(ls : list (list A)),\n    NoDup_gen (fun a b => a <> nil /\\ a = b) ls ->\n    (forall x, In x ls -> NoDup x) ->\n    (forall x1 x2, In x1 ls -> In x2 ls -> x1 <> x2 -> NoDup (x1 ++ x2)) ->\n    NoDup (flatten ls).\n  \n  induction ls; intuition; simpl in *.\n  econstructor.\n  \n  inversion H; clear H; subst.\n  eapply app_NoDup; intuition.\n  \n  eapply in_flatten in H3.\n  destruct H3.\n  intuition.\n  eapply app_NoDup_inv.\n  eapply H1.\n  right.\n  eapply H6.\n  left.\n  reflexivity.\n  intuition.\n  subst.\n  \n  eapply H4.\n  eapply In_gen_weaken.\n  exact H6.\n  intuition.\n  subst.\n  subst.\n  simpl in *.\n  intuition.\n  eauto.\n  eauto.\n       \n  eapply in_flatten in H2.\n  destruct H2.\n  intuition.\n  eapply app_NoDup_inv.\n  eapply H1.\n  right.\n  eapply H6.\n  left.\n  reflexivity.\n  intuition.\n  subst.\n  eapply H4.\n  eapply In_gen_weaken.\n  exact H6.\n  intuition.\n  subst.\n  subst.\n  simpl in *.\n  intuition.\n  eauto.\n  eauto.\n  \nQed.\n\nTheorem NoDup_gen_weaken : \n  forall (A : Type)(e1 e2 : A -> A -> Prop) ls,\n    NoDup_gen e1 ls ->\n    (forall a1 a2, e2 a1 a2 -> e1 a1 a2) ->\n    NoDup_gen e2 ls.\n  \n  induction ls; intuition; simpl in *.\n  econstructor.\n  \n  inversion H; clear H; subst.\n  econstructor.\n  intuition.\n  eapply H3.\n  eapply In_gen_weaken; eauto.\n  \n  eauto.\n  \nQed.\n\nTheorem In_gen_zip_fst : \n  forall (A B : Set)(ea : A -> A -> Prop)(lsa : list A)(lsb : list B) a b,   \n    In_gen (fun a b => ea (fst a) (fst b)) (a, b) (zip lsa lsb) ->\n    In_gen ea a lsa.\n  \n  induction lsa; intuition; simpl in *.\n  destruct lsb;\n    simpl in *;\n    intuition.\n  \n  right.\n  eauto.\nQed.\n\n\nTheorem NoDup_gen_zip_fst : \n  forall (A B : Set)(ea : A -> A -> Prop)(lsa : list A)(lsb : list B),\n    NoDup_gen ea lsa ->\n    NoDup_gen (fun a b => ea (fst a) (fst b)) (zip lsa lsb).\n  \n  induction lsa; intuition; simpl in *.\n  econstructor.\n  \n  inversion H; clear H; subst.\n  destruct lsb; intuition; simpl in *.\n  econstructor.\n  \n  econstructor.\n  intuition.\n  eapply H2.\n  eapply In_gen_zip_fst.\n  eauto.\n  eauto.\n\nQed.\n\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/NoDup_gen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.6528737280644334}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Order relations                                                         *\n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibTactics LibLogic LibReflect LibOperation LibRelation.\nGeneralizable Variables A.\n\n(**************************************************************************)\n(* * Preorder *)\n\n(** Definition *)\n\nRecord preorder (A:Type) (R:binary A) : Prop := {\n   preorder_refl : refl R;\n   preorder_trans : trans R }.\n\nImplicit Arguments preorder_trans [A R p x z].\n\n(** Transformations *)\n\nLemma preorder_flip : forall A (R:binary A),\n  preorder R -> preorder (flip R).\nProof using. introv [Re Tr]. constructor; autos~ flip_trans. Qed.\n\nLemma preorder_large : forall A (R:binary A),\n  preorder R -> preorder (large R).\nProof using. introv [Re Tr]. constructor; autos~ large_refl large_trans. Qed.\n\n\n(**************************************************************************)\n(* * Total preorder *)\n\n(** Definition of total preorder relations *)\n\nRecord total_preorder (A:Type) (R:binary A) : Prop := {\n   total_preorder_trans : trans R;\n   total_preorder_total : total R }.\n\nImplicit Arguments total_preorder_trans [A R x z].\n\n(** Conversion to preorder *)\n\nLemma total_preorder_refl : forall A (le:binary A),\n  total_preorder le -> 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_flip : forall A (R:binary A),\n  total_preorder R -> total_preorder (flip R).\nProof using. introv [Tr To]. constructor; autos~ flip_trans flip_total. Qed.\n\nLemma total_preorder_large : forall A (R:binary A),\n  total_preorder R -> total_preorder (large R).\nProof using. introv [Re Tr]. constructor; autos~ large_trans large_total. Qed.\n\n(** Properties *)\n\nLemma flip_from_not : forall A (R:binary A) x y,\n  total R -> ~ R x y -> flip R x y.\nProof using. introv T H. destruct (T x y); auto_false~. Qed.\n\nLemma flip_strict_from_not : forall A (R:binary A) x y,\n  total R -> ~ R x y -> flip (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:Type) (R:binary A) : Prop := {\n   order_refl : refl R;\n   order_trans : trans R;\n   order_antisym : antisym R }.\n\nImplicit Arguments order_trans [A R o x z].\nImplicit Arguments order_antisym [A R o x y].\n\n(** Conversion to preorder *)\n\nCoercion order_to_preorder (A:Type) (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_flip : forall A (R:binary A),\n  order R -> order (flip R).\nProof using.\n  introv [Re Tr An]. constructor;\n  autos~ flip_trans flip_antisym.\nQed.\n\nLemma order_large : forall A (R:binary A),\n  order R -> order (large R).\nProof using.\n  introv [Re Tr An]. constructor;\n  autos~ large_refl large_trans large_antisym.\nQed.\n\n(** Properties *)\n\n\n(**************************************************************************)\n(* * Total Order *)\n\n(** Definition *)\n\nRecord total_order (A:Type) (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\nImplicit Arguments total_order_trans [A R o x z].\nImplicit Arguments total_order_antisym [A R o x y].\n\n(** Construction *)\n\nLemma total_order_intro : forall A (R:binary A),\n   trans R -> antisym R -> total R -> 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:Type) (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_flip : forall A (R:binary A),\n  total_order R -> total_order (flip R).\nProof using.\n  introv [Or To]. constructor;\n  autos~ flip_total order_flip.\nQed.\n\nLemma total_order_large : forall A (R:binary A),\n  total_order R -> total_order (large R).\nProof using.\n  introv [Or To]. constructor;\n  autos~ large_total order_large.\nQed.\n\n(** Properties *)\n\nSection TotalOrderProp.\nVariables (A:Type) (R:binary A).\nNotation \"'le'\" := (R).\nNotation \"'ge'\" := (flip R).\nNotation \"'lt'\" := (strict R).\nNotation \"'gt'\" := (flip lt).\n\nHint Unfold strict flip.\n\nLemma total_order_le_is_large_lt :\n  forall (To:total_order R),\n  le = large lt.\nProof using.\n  extens. intros. unfold large, strict. iff M.\n  tests~: (x = y).\n  destruct M. autos*. subst*. dintuition eauto.\nQed.\n\nLemma total_order_lt_is_strict_le :\n  forall (To:total_order R),\n  lt = strict le.\nProof using.\n  auto.\nQed.\n\nLemma total_order_ge_is_large_gt :\n  forall (To:total_order R),\n  ge = large gt.\nProof using.\n  extens. intros. unfold large, flip, strict. iff M.\n  tests~: (x = y).\n  destruct M. autos*. subst*. dintuition eauto.\nQed.\n\nLemma total_order_gt_is_strict_ge :\n  forall (To:total_order R),\n  gt = strict ge.\nProof using.\n  extens. intros. unfold flip, large, strict. iff M.\n  tests~: (x = y).\n  destruct M. autos*.\n  destruct M. autos*.\nQed.\n\nLemma total_order_lt_or_eq_or_gt :\n  forall (To:total_order R), forall x y,\n  lt x y \\/ x = y \\/ gt x y.\nProof using.\n  introv H. intros. 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 :\n  forall (To:total_order R), forall 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_large_gt. hnfs~.\nQed.\n\nLemma total_order_le_or_gt : forall x y,\n  forall (To:total_order R),\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_large_lt. 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:Type) (R:binary A) : Prop := {\n   strict_order_irrefl : irrefl R;\n   strict_order_asym : asym R;\n   strict_order_trans : trans R }.\n\nImplicit Arguments strict_order_trans [A R s x z].\n\n(** Transformations *)\n\nLemma strict_order_flip : forall A (R:binary A),\n  strict_order R -> strict_order (flip R).\nProof using.\n  introv [Ir As Tr]. constructor;\n  autos~ flip_antisym flip_trans flip_asym.\nQed.\n\nLemma strict_order_strict : forall (A:Type) (R:binary A),\n  order R -> strict_order (strict R).\nProof using.\n  introv [Re As Tr]. unfold strict. constructor; intros_all; simpls.\n  destruct* H.\n  applys* antisym_elim x y.\n  split. applys* As. intros E. subst. applys* antisym_elim y z.\nQed.\n\nLemma order_from_strict : forall (A:Type) (R:binary A),\n  strict_order R -> order (large R).\nProof using.\n  introv [Re As Tr]. unfold large. constructor; simpl.\n  intros_all~.\n  introv [H1|E1] [H2|E2]; subst; auto.\n    left. apply* trans_elim.\n  introv [H1|E1] [H2|E2]; try subst; auto.\n    false. apply* As.\nQed.\n\n\n(**************************************************************************)\n(* * Total strict order *)\n\n(** Trichotomy *)\n(* todo: move *)\n\nInductive trichotomy (A:Type) (R:binary A) : binary A :=\n  | trichotomy_left: forall x y,\n      R x y -> x <> y -> ~ R y x -> trichotomy R x y\n  | trichotomy_eq : forall x,\n      ~ R x x -> trichotomy R x x\n  | trichotomy_right : forall x y,\n      ~ R x y -> x <> y -> R y x -> trichotomy R x y.\n\nDefinition trichotomous (A:Type) (R:binary A) :=\n  forall x y, trichotomy R x y.\n\nLemma flip_trichotomous : forall (A:Type) (R:binary A),\n  trichotomous R -> trichotomous (flip R).\nProof using.\n  introv H. intros x y. destruct (H x y).\n  apply~ trichotomy_right.\n  apply~ trichotomy_eq.\n  apply~ trichotomy_left.\nQed.\n\n(** Definition *)\n\nRecord strict_total_order (A:Type) (R:binary A) : Prop := {\n   strict_total_order_trans : trans R;\n   strict_total_order_trichotomous : trichotomous R }.\n\nImplicit Arguments strict_total_order_trans [A R s 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 -> 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 -> 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_flip : forall A (R:binary A),\n  strict_total_order R -> strict_total_order (flip R).\nProof using.\n  introv [Tr Tk]. constructor. apply~ flip_trans.\n  apply~ flip_trichotomous.\nQed.\n(** From total order *)\n\nLemma strict_total_order_from_total_order : forall (A:Type) (R:binary A),\n  total_order R -> 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(** ** 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_from_le : forall `{Le A}, Ge A.\n  constructor. apply (flip le). Defined.\nInstance lt_from_le : forall `{Le A}, Lt A.\n  constructor. apply (strict le). Defined.\nInstance gt_from_le : forall `{Le A}, Gt A.\n  constructor. apply (flip lt). Defined.\n\nLemma ge_is_flip_le : forall `{Le A}, ge = flip le.\nProof using. intros. apply* prop_ext_2. Qed.\nLemma lt_is_strict_le : forall `{Le A}, lt = strict le.\nProof using. intros. apply* prop_ext_2. Qed.\nLemma gt_is_flip_lt : forall `{Le A}, gt = flip lt.\nProof using. intros. apply* prop_ext_2. Qed.\nLemma gt_is_flip_strict_le : forall `{Le A}, gt = flip (strict le).\nProof using. intros. rewrite gt_is_flip_lt. rewrite~ lt_is_strict_le. Qed.\n\nGlobal Opaque ge_from_le lt_from_le gt_from_le.\nHint Rewrite @gt_is_flip_strict_le @ge_is_flip_le @lt_is_strict_le : rew_to_le_def.\nTactic Notation \"rew_to_le\" :=\n  autorewrite with rew_to_le_def in *.\n\nHint Rewrite @ge_is_flip_le @gt_is_flip_lt : rew_to_le_lt_def.\nTactic Notation \"rew_to_le_lt\" :=\n  autorewrite with rew_to_le_lt_def in *.\n\nLemma gt_is_strict_flip_le : forall `{Le A}, gt = strict (flip le).\nProof using. intros. rew_to_le. apply flip_strict. Qed.\nLemma le_is_large_lt : forall `{Le A},\n  refl le -> le = large lt.\nProof using. intros. rew_to_le. rewrite~ large_strict. Qed.\nLemma le_is_flip_ge : forall `{Le A}, le = flip ge.\nProof using. intros. rew_to_le. rewrite~ flip_flip. Qed.\nLemma lt_is_flip_gt : forall `{Le A}, lt = flip gt.\nProof using. intros. rew_to_le. rewrite~ flip_flip. Qed.\nLemma gt_is_strict_ge : forall `{Le A}, gt = strict ge.\nProof using. intros. rew_to_le. apply flip_strict. Qed.\nLemma ge_is_large_gt : forall `{Le A},\n  refl le -> ge = large gt.\nProof using. intros. rewrite gt_is_strict_ge. rewrite~ large_strict. Qed.\n\n\n(* ********************************************************************** *)\n(** * Classes for comparison properties *)\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\nImplicit Arguments lt_irrefl [A H Lt_irrefl].\nImplicit Arguments le_trans [[A] [H] [Le_trans] x z].\nImplicit Arguments ge_trans [[A] [H] [Ge_trans] x z].\nImplicit Arguments lt_trans [[A] [H] [Lt_trans] x z].\nImplicit Arguments gt_trans [[A] [H] [Gt_trans] 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_from_le_order :\n  Le_order -> Le_preorder.\nProof using. constructor. intros. apply* order_to_preorder. Qed.\n\nGlobal Instance le_total_preorder_from_le_total_order :\n  Le_total_order -> Le_total_preorder.\nProof using. constructor. intros. apply* total_order_to_total_preorder. Qed.\n\nGlobal Instance le_preorder_from_total_preorder :\n  Le_total_preorder -> Le_preorder.\nProof using. constructor. intros. apply* total_preorder_to_preorder. Qed.\n\nGlobal Instance le_order_from_le_total_order :\n  Le_total_order -> Le_order.\nProof using. constructor. intros. apply* total_order_to_order. Qed.\n\nGlobal Instance lt_strict_order_from_lt_strict_total_order :\n  Lt_strict_total_order -> Lt_strict_order.\nProof using. constructor. intros. apply* strict_total_order_to_strict_order. Qed.\n\nGlobal Instance lt_strict_order_from_le_order :\n  Le_order -> Lt_strict_order.\nProof using. constructor. intros. rew_to_le. apply* strict_order_strict. Qed.\n\nGlobal Instance lt_strict_total_order_from_le_total_order :\n  Le_total_order -> Lt_strict_total_order.\nProof using. constructor. intros. rew_to_le. apply* strict_total_order_from_total_order. Qed.\n\n(** symmetric structures *)\n\nGlobal Instance ge_preorder_from_le_order :\n  Le_order -> Ge_preorder.\nProof using. constructor. rew_to_le. apply preorder_flip. apply le_preorder. Qed.\n\nGlobal Instance ge_total_preorder_from_le_total_order :\n  Le_total_order -> Ge_total_preorder.\nProof using. constructor. rew_to_le. apply total_preorder_flip. apply le_total_preorder. Qed.\n\nGlobal Instance ge_preorder_from_total_preorder :\n  Le_total_preorder -> Ge_preorder.\nProof using. constructor. rew_to_le. apply preorder_flip. apply le_preorder. Qed.\n\nGlobal Instance ge_order_from_le_total_order :\n  Le_total_order -> Ge_order.\nProof using. constructor. rew_to_le. apply order_flip. apply le_order. Qed.\n\nGlobal Instance gt_strict_order_from_lt_strict_total_order :\n  Lt_strict_total_order -> Gt_strict_order.\nProof using. constructor. rewrite gt_is_flip_lt. apply strict_order_flip. apply lt_strict_order. Qed.\n\nGlobal Instance gt_strict_order_from_le_order :\n  Le_order -> Gt_strict_order.\nProof using. constructor. rewrite gt_is_flip_lt. apply strict_order_flip. apply lt_strict_order. Qed.\n\nGlobal Instance gt_strict_total_order_from_le_total_order :\n  Le_total_order -> Gt_strict_total_order.\nProof using. constructor. rewrite gt_is_flip_lt. apply strict_total_order_flip. apply lt_strict_total_order. Qed.\n\n(** properties of le *)\n\nGlobal Instance le_refl_from_le_preorder :\n  Le_preorder -> Le_refl.\nProof using. intros [[Re Tr]]. constructor~. Qed.\n\nGlobal Instance le_trans_from_le_preorder :\n  Le_preorder -> Le_trans.\nProof using. intros [[Re Tr]]. constructor~. Qed.\n\nGlobal Instance le_antisym_from_le_order :\n  Le_order -> Le_antisym.\nProof using. constructor. intros. apply* order_antisym. Qed.\n\nGlobal Instance le_total_from_le_total_order :\n  Le_total_order -> Le_total.\nProof using. constructor. intros. apply* total_order_total. Qed.\n\n(** properties of ge *)\n\nGlobal Instance ge_refl_from_le_preorder :\n  Le_preorder -> Ge_refl.\nProof using. constructor. rew_to_le. apply flip_refl. apply le_refl. Qed.\n\nGlobal Instance ge_trans_from_le_preorder :\n  Le_preorder -> Ge_trans.\nProof using. constructor. rew_to_le. apply flip_trans. apply le_trans. Qed.\n\nGlobal Instance ge_antisym_from_le_order :\n  Le_order -> Ge_antisym.\nProof using. constructor. rew_to_le. apply flip_antisym. apply le_antisym. Qed.\n\nGlobal Instance ge_total_from_le_total_order :\n  Le_total_order -> Ge_total.\nProof using. constructor. rew_to_le. apply flip_total. apply le_total. Qed.\n\n(** properties of lt *)\n\nGlobal Instance lt_irrefl_from_le_order :\n  Le_order -> Lt_irrefl.\nProof using. constructor. apply strict_order_irrefl. apply lt_strict_order. Qed.\n\nGlobal Instance lt_trans_from_le_order :\n  Le_order -> Lt_trans.\nProof using. constructor. apply strict_order_trans. apply lt_strict_order. Qed.\n\n(** properties of gt *)\n\nGlobal Instance gt_irrefl_from_le_order :\n  Le_order -> Gt_irrefl.\nProof using. constructor. apply strict_order_irrefl. apply gt_strict_order. Qed.\n\nGlobal Instance gt_trans_from_le_order :\n  Le_order -> 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_from : Le_order -> 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_le_trans_from : Le_order -> 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_from : Le_order -> 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_from : Le_order -> 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_from : Ge_As_SLe.\nProof using. constructor. intros. rew_to_le. auto. Qed.\n\nGlobal Instance gt_as_slt_from : Gt_As_SLt.\nProof using. constructor. intros. rew_to_le. auto. Qed.\n\nGlobal Instance ngt_as_sle_from : Le_total_order -> NGt_As_SLe.\nProof using.\n  constructor. intros. rew_to_le. unfold strict. rew_logic. iff M.\n  destruct M.\n    forwards K:(flip_strict_from_not (R:=le)); eauto.\n      apply le_total. apply (proj1 K).\n    subst. apply le_refl.\n  apply classic_left. intros P Q. apply P. apply* le_antisym.\nQed.\n\nGlobal Instance nlt_as_ge_from : Le_total_order -> NLt_As_Ge.\nProof using. constructor. intros. rew_to_le_lt. unfold flip. apply ngt_as_sle. Qed.\n\nGlobal Instance ngt_as_le_from : Le_total_order -> NGt_As_Le.\nProof using. constructor. intros. rew_to_le_lt. unfold flip. apply ngt_as_sle. Qed.\n\nGlobal Instance nle_as_gt_from : Le_total_order -> NLe_As_Gt.\nProof using.\n  constructor. intros. rew_to_le_lt. unfold flip.\n  rewrite <- ngt_as_sle. rewrite~ not_not.\nQed.\n\nGlobal Instance nge_as_lt_from : Le_total_order -> NGe_As_Lt.\nProof using.\n  constructor. intros. rew_to_le_lt. unfold flip.\n  rewrite nle_as_gt. rewrite~ gt_is_flip_lt.\nQed.\n\n(** inclusion between operators *)\n\nGlobal Instance lt_to_le_from : Lt_to_Le.\nProof using. constructor. intros. rew_to_le. unfolds* strict. Qed.\n\nGlobal Instance gt_to_ge_from : Gt_to_Ge.\nProof using. constructor. intros. rew_to_le. unfolds* flip, strict. Qed.\n\nGlobal Instance nle_to_sle_from : Le_total_order -> NLe_to_SLe.\nProof using.\n  constructor. introv K. rewrite nle_as_gt in K.\n  rew_to_le. unfolds* flip, strict.\nQed.\n\nGlobal Instance nle_to_slt_from : Le_total_order -> NLe_to_SLt.\nProof using.\n  constructor. introv K. rewrite nle_as_gt in K.\n  rew_to_le. unfolds* flip, strict.\nQed.\n\n(** case analysis under no assumption *)\n\nGlobal Instance case_eq_lt_gt_from : Le_total_order -> 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_large_lt in M1 by applys* total_order_refl. destruct* M1.\n    autos*.\n    rewrite le_is_large_lt in M1 by applys* total_order_refl. destruct* M1.\nQed.\n\nGlobal Instance case_eq_lt_slt_from : Le_total_order -> Case_Eq_Lt_SLt.\nProof using.\n  constructor. intros. pattern lt at 2. rewrite lt_is_flip_gt.\n  apply case_eq_lt_gt.\nQed.\n\nGlobal Instance case_le_gt_from : Le_total_order -> Case_Le_Gt.\nProof using.\n  constructor. intros.\n  rewrite le_is_large_lt by applys* total_order_refl. unfold large.\n  branches (total_order_lt_or_eq_or_gt le_total_order x y); eauto.\nQed.\n\nGlobal Instance case_eq_lt_ge_from : Le_total_order -> Case_Lt_Ge.\nProof using.\n  constructor. intros.\n  rewrite ge_is_large_gt by applys* total_order_refl. unfold large.\n  branches (total_order_lt_or_eq_or_gt le_total_order x y); eauto.\nQed.\n\nGlobal Instance case_le_slt_from : Le_total_order -> Case_Le_SLt.\nProof using. constructor. intros. rewrite lt_is_flip_gt. apply case_le_gt. Qed.\n\nGlobal Instance case_eq_lt_sle_from : Le_total_order -> Case_Lt_SLe.\nProof using. constructor. intros. rewrite le_is_flip_ge. apply case_lt_ge. Qed.\n\n\n(** case analysis under one assumption *)\n\nGlobal Instance neq_case_lt_gt_from : Le_total_order -> Neq_Case_Lt_Gt.\nProof using. constructor. intros. destruct* (case_eq_lt_gt x y). Qed.\n\nGlobal Instance neq_case_lt_slt_from : Le_total_order -> Neq_Case_Lt_SLt.\nProof using. constructor. intros. destruct* (case_eq_lt_gt x y). Qed.\n\nGlobal Instance le_case_eq_lt_from : Le_total_order -> Le_Case_Eq_Lt.\nProof using. constructor. intros. rew_to_le. unfold strict. tests*: (x = y). Qed.\n\nGlobal Instance ge_case_eq_gt_from : Le_total_order -> Ge_Case_Eq_Gt.\nProof using. constructor. intros. rew_to_le. unfold flip, strict. tests*: (x = y). Qed.\n\n(** case analysis under two assumptions *)\n\nGlobal Instance le_neq_to_lt_from : Le_total_order -> Le_NEq_To_Lt.\nProof using. constructor. intros. rew_to_le. hnfs*. Qed.\n\nGlobal Instance ge_neq_to_gt_from : Le_total_order -> Ge_NEq_To_Gt.\nProof using. constructor. intros. rew_to_le. hnfs*. Qed.\n\nGlobal Instance nlt_nslt_to_eq_from : Le_total_order -> NLt_NSLt_To_Eq.\nProof using. constructor. intros. branches* (case_eq_lt_gt x y). Qed.\n\n\n(** contradiction from case analysis *)\n\nGlobal Instance lt_ge_false_from : Le_total_order -> Lt_Ge_false.\nProof using. constructor. introv H1 H2. rewrite~ <- nlt_as_ge in H2. Qed.\n\nGlobal Instance lt_gt_false_from : Le_total_order -> 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_from_le_order :\n  Le_total_order -> 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\nImplicit Arguments nle_to_sle [[A] [H] [NLe_to_SLe] x y].\n\n\n\n(* ********************************************************************** *)\n(* * Order modulo -- todo: move *)\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\n\n(* ********************************************************************** *)\n(** * Boolean comparison *)\n\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\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/LibOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.6528737259609867}}
{"text": "Load Functor.\n\nDefinition hom_pairing {C D : Category} a b :=\n  prod (Hom C (fst a) (fst b)) (Hom D (snd a) (snd b)).\n\nDefinition id_pairing {C D : Category} (a : Ob C * Ob D) :=\n  (@Id _ (fst a), @Id _ (snd a)).\n\nDefinition comp_pairing\n           {C D : Category}\n           (a b c: Ob C * Ob D) \n           (f : hom_pairing a b)\n           (g : hom_pairing b c) :=\n  (Comp _ (fst f) (fst g), Comp _ (snd f) (snd g)).\n  \nVariable C D : Category.\nVariable a : Ob C.\nVariable b : Ob D.\nCheck @Id _ a.\nCheck hom_pairing (a, b) (a, b).\nCheck Build_Category ((Ob C) * (Ob D)) (hom_pairing).\nCheck hom_pairing.\nCheck id_pairing.\nCheck snd.\n\n\nDefinition Product (C D : Category) : Category.\n  apply (Build_Category\n           ((Ob C) * (Ob D))\n           (hom_pairing)\n           (fun a => id_pairing a)\n           (fun a b c f g => comp_pairing a b c f g)\n        ).\n  \n  unfold comp_pairing, id_pairing, hom_pairing.\n  intros.\n  simpl.\n  rewrite (idl C), (idl D).\n  simpl.\n  symmetry.\n  apply surjective_pairing.\n\n  unfold comp_pairing, id_pairing, hom_pairing.\n  intros.\n  simpl.\n  rewrite (idr C), (idr D).\n  symmetry.\n  apply surjective_pairing.\n\n  unfold comp_pairing, id_pairing, hom_pairing.\n  intros.\n  simpl.\n  rewrite <- (assoc C (fst f) (fst g) (fst h)),\n             (assoc D (snd f) (snd g) (snd h)).\n  trivial.\nDefined.\n\nDefinition PiFst : Functor (Product C D) C.\n  apply (Build_Functor _ _ _\n                       (fun a b (f: Hom (Product C D) a b) => fst f)).\n  simpl.\n  trivial.\n\n  simpl.\n  trivial.\nDefined.\n\nDefinition PiSnd : Functor (Product C D) D.\n  apply (Build_Functor _ _ _\n                       (fun a b (f: Hom (Product C D) a b) => snd f)).\n  simpl.\n  trivial.\n\n  simpl.\n  trivial.\nDefined.", "meta": {"author": "vtols", "repo": "Categories", "sha": "e0b2a3e7cbae5fd311608f021f00394bdd1366e5", "save_path": "github-repos/coq/vtols-Categories", "path": "github-repos/coq/vtols-Categories/Categories-e0b2a3e7cbae5fd311608f021f00394bdd1366e5/Product.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.65286882325222}}
{"text": "Require Import\n  HoTT.Classes.interfaces.abstract_algebra\n  HoTT.TruncType.\n\n(** Demonstrate the [HProp] is a (bounded) lattice w.r.t. the logical\noperations. This requires Univalence. *)\nGlobal Instance join_hor : Join HProp := hor.\nDefinition hand (X Y : HProp) : HProp := Build_HProp (X * Y).\nGlobal Instance meet_hprop : Meet HProp := hand.\nGlobal Instance bottom_hprop : Bottom HProp := False_hp.\nGlobal Instance top_hprop : Top HProp := Unit_hp.\n\nSection contents.\n  Context `{Univalence}.\n\n  (* We use this notation because [hor] can accept arguments of type [Type], which leads to minor confusion in the instances below *)\n  Notation lor := (hor : HProp -> HProp -> HProp).\n\n  (* This tactic attempts to destruct a truncated sum (disjunction) *)\n  Local Ltac hor_intros :=\n    let x := fresh in\n    intro x; repeat (strip_truncations; destruct x as [x | x]).\n\n  Instance commutative_hor : Commutative lor.\n  Proof.\n    intros ??.\n    apply path_iff_hprop; hor_intros; apply tr; auto.\n  Defined.\n\n  Instance commutative_hand : Commutative hand.\n  Proof.\n    intros ??.\n    apply path_hprop.\n    apply equiv_prod_symm.\n  Defined.\n\n  Instance associative_hor : Associative lor.\n  Proof.\n    intros ???.\n    apply path_iff_hprop;\n    hor_intros; apply tr;\n    ((by auto) || (left; apply tr) || (right; apply tr));\n    auto.\n  Defined.\n\n  Instance associative_hand : Associative hand.\n  Proof.\n    intros ???.\n    apply path_hprop.\n    apply equiv_prod_assoc.\n  Defined.\n\n  Instance idempotent_hor : BinaryIdempotent lor.\n  Proof.\n    intros ?. compute.\n    apply path_iff_hprop; hor_intros; auto.\n    by apply tr, inl.\n  Defined.\n\n  Instance idempotent_hand : BinaryIdempotent hand.\n  Proof.\n    intros ?.\n    apply path_iff_hprop.\n    - intros [a _] ; apply a.\n    - intros a; apply (pair a a).\n  Defined.\n\n  Instance leftidentity_hor : LeftIdentity lor False_hp.\n  Proof.\n    intros ?.\n    apply path_iff_hprop; hor_intros; try contradiction || assumption.\n    by apply tr, inr.\n  Defined.\n\n  Instance rightidentity_hor : RightIdentity lor False_hp.\n  Proof.\n    intros ?.\n    apply path_iff_hprop; hor_intros; try contradiction || assumption.\n    by apply tr, inl.\n  Defined.\n\n  Instance leftidentity_hand : LeftIdentity hand Unit_hp.\n  Proof.\n    intros ?.\n    apply path_trunctype, prod_unit_l.\n  Defined.\n\n  Instance rightidentity_hand : RightIdentity hand Unit_hp.\n  Proof.\n    intros ?.\n    apply path_trunctype, prod_unit_r.\n  Defined.\n\n  Instance absorption_hor_hand : Absorption lor hand.\n  Proof.\n    intros ??.\n    apply path_iff_hprop.\n    - intros X; strip_truncations.\n      destruct X as [? | [? _]]; assumption.\n    - intros ?. by apply tr, inl.\n  Defined.\n\n  Instance absorption_hand_hor : Absorption hand lor.\n  Proof.\n    intros ??.\n    apply path_iff_hprop.\n    - intros [? _]; assumption.\n    - intros ?.\n      split.\n      * assumption.\n      * by apply tr, inl.\n  Defined.\n\n  Global Instance boundedlattice_hprop : IsBoundedLattice HProp.\n  Proof. repeat split; apply _. Defined.\nEnd contents.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Classes/implementations/hprop_lattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6528504751199197}}
{"text": "\nRequire Export Iron.SimplePCFa.Value.\n\n\n(******************************************************************************)\n(* Primitive reduction step. *)\nInductive STEPP : exp -> exp -> Prop := \n (* Application *)\n | SpAppLam\n   : forall t11 x12 v2\n   , STEPP (XApp (VLam t11 x12) v2)\n           (substVX 0 v2 x12)\n\n | SpAppFix \n   : forall t1 v2 v3\n   , STEPP (XApp (VFix t1 v2) v3)\n           (XApp (substVV 0 (VFix t1 v2) v2) v3)\n\n (* Naturals *)\n | SpSucc \n   : forall n\n   , STEPP (XOp1 OSucc (VConst (CNat n)))\n           (XVal (VConst (CNat (S n))))\n\n | SpPredZero\n   : STEPP (XOp1 OPred (VConst (CNat O)))\n           (XVal (VConst (CNat O)))\n\n | SpPredSucc\n   : forall n\n   , STEPP (XOp1 OPred (VConst (CNat (S n))))\n           (XVal (VConst (CNat n)))\n\n (* Booleans *)\n | SpIsZeroTrue\n   : STEPP (XOp1 OIsZero (VConst (CNat O)))\n           (XVal (VConst (CBool true)))\n\n | SpIsZeroFalse\n   : forall n\n   , STEPP (XOp1 OIsZero (VConst (CNat (S n))))\n           (XVal (VConst (CBool false)))\n\n (* Branching *)\n | SpIfThen\n   : forall x1 x2\n   , STEPP (XIf (VConst (CBool true)) x1 x2) x1\n\n | SpIfElse\n   : forall x1 x2\n   , STEPP (XIf (VConst (CBool false)) x1 x2) x2.\nHint Constructors STEPP.\n\n\n(* Single step reduction. \n   This judgement contains the rule for 'let', which is the only form\n   that holds a context while it reduces an expression. *)\nInductive STEP : exp -> exp -> Prop :=\n | SPrim \n   :  forall x1 x2\n   ,  STEPP x1 x2\n   -> STEP  x1 x2\n\n | SLetStep\n   :  forall t1 x1 x1' x2\n   ,  STEP x1 x1'\n   -> STEP (XLet t1 x1  x2)\n           (XLet t1 x1' x2)\n\n | SLetSub\n   : forall t1 v1 x2 \n   , STEP (XLet t1 (XVal v1) x2)\n          (substVX 0 v1 x2).\nHint Constructors STEP.\n\n\n(********************************************************************)\n(** Multi-step evaluation. *)\nInductive STEPS : exp -> exp -> Prop :=\n | SsNone\n   :  forall x1\n   ,  STEPS x1 x1\n\n (* Take a single step. *)\n | SsStep\n   :  forall x1 x2\n   ,  STEP  x1 x2\n   -> STEPS x1 x2\n\n (* Combine two evaluations into a third. *)\n | SsAppend\n   :  forall x1 x2 x3\n   ,  STEPS x1 x2 -> STEPS x2 x3\n   -> STEPS x1 x3.\n\nHint Constructors STEPS.\n\n\n(* TODO *)\nLemma steps_context_let1\n :  forall t1 x1 x1' x2\n ,  STEPS x1 x1' \n -> STEPS (XLet t1 x1 x2) (XLet t1 x1' x2).\nProof.\n admit.\nQed.\n\n\n", "meta": {"author": "Warbo", "repo": "iron", "sha": "69997b162a52e07456562d00908ef4791b47a15a", "save_path": "github-repos/coq/Warbo-iron", "path": "github-repos/coq/Warbo-iron/iron-69997b162a52e07456562d00908ef4791b47a15a/devel/Iron/SimplePCFa/Step/Prim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451416, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6528460295460192}}
{"text": "Require Import Coq.Classes.Equivalence.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Unicode.Utf8.\n\nGeneralizable All Variables.\n\nReserved Notation \"x ⊔ y\" (at level 36, left associativity).\nReserved Notation \"x ⊓ y\" (at level 40, left associativity).\nReserved Notation \"⊥\" (at level 0).\nReserved Notation \"⊤\" (at level 0).\n\nDefinition equiv `{Equivalence A} := Equivalence.equiv.\n\nLocal Open Scope equiv_scope.\n\nClass Lattice (A : Type) `{Equivalence A} : Type := {\n  meet : A → A → A where \"x ⊓ y\" := (meet x y);\n  join : A → A → A where \"x ⊔ y\" := (join x y);\n  top : A;\n  bot : A;\n\n  (* These exact axioms are taken from the nlab page on lattices *)\n  meet_commutative : ∀ a b, a ⊓ b === b ⊓ a;\n  meet_idempotent : ∀ a, a ⊓ a === a;\n  meet_associative : ∀ a b c, a ⊓ (b ⊓ c) === (a ⊓ b) ⊓ c;\n\n  join_commutative : ∀ a b, a ⊔ b === b ⊔ a;\n  join_idempotent : ∀ a, a ⊔ a === a;\n  join_associative : ∀ a b c, a ⊔ (b ⊔ c) === (a ⊔ b) ⊔ c;\n\n  join_meet_absorptive : ∀ a b, a ⊔ (a ⊓ b) === a;\n  meet_join_absorptive : ∀ a b, a ⊓ (a ⊔ b) === a;\n\n  meet_id : ∀ a, a ⊓ top === a;\n  join_id : ∀ a, a ⊔ bot === a;\n\n  (* Welcome to \"Setoid-Hell\" *)\n  meet_respectful :> Proper (equiv ==> equiv ==> equiv) meet;\n  join_respectful :> Proper (equiv ==> equiv ==> equiv) join;\n}.\n\nNotation \"x ⊓ y\" := (meet x y).\nNotation \"x ⊔ y\" := (join x y).\nNotation \"⊤\" := top.\nNotation \"⊥\" := bot.\n\nModule Lattice.\nSection Lattice.\n\n  Context {A : Type} {equ : A → A → Prop}.\n  Context {E : Equivalence equ}.\n  Context {L : Lattice A}.\n\n  Definition le_meet a b := a ⊓ b === a.\n\n  Instance Reflexive_le_meet : Reflexive le_meet := meet_idempotent.\n\n  Instance Transitive_le_meet : Transitive le_meet.\n  Proof.\n    intros x y z P Q.\n    unfold le_meet in *.\n    rewrite <- P.\n    rewrite <- Q.\n    rewrite meet_associative.\n    rewrite <- meet_associative.\n    rewrite meet_idempotent.\n    reflexivity.\n  Qed.\n\n  Instance PreOrder_le_meet : PreOrder le_meet := {|\n    PreOrder_Reflexive := Reflexive_le_meet;\n    PreOrder_Transitive := Transitive_le_meet;\n  |}.\n\n  Instance PartialOrder_le_meet : PartialOrder equ le_meet.\n  Proof.\n    intros x y.\n    split; intros H.\n    - split.\n      + unfold le_meet.\n        rewrite <- (meet_respectful x x (reflexivity x) x y H).\n        apply meet_idempotent.\n      + unfold le_meet, Basics.flip.\n        rewrite (meet_respectful y y (reflexivity y) x y H).\n        apply meet_idempotent.\n    - destruct H as [H1 H2].\n      unfold le_meet, Basics.flip in *.\n      rewrite <- H1 in *.\n      rewrite (meet_commutative x y) in H2.\n      rewrite meet_associative in H2.\n      rewrite meet_idempotent in H2.\n      rewrite meet_commutative in H2.\n      apply H2.\n  Qed.\n\n  Definition le_join a b := a ⊔ b === b.\n\n  Lemma le_meet_join : ∀ a b, le_meet a b ↔ le_join a b.\n  Proof.\n    intros a b.\n    unfold le_meet, le_join in *.\n    split.\n    - intros H.\n      rewrite <- H.\n      rewrite meet_commutative.\n      rewrite join_commutative.\n      apply join_meet_absorptive.\n    - intros H.\n      rewrite <- H.\n      apply meet_join_absorptive.\n  Qed.\n\n  Instance Reflexive_le_join : Reflexive le_join := join_idempotent.\n  Instance Transitive_le_join : Transitive le_join.\n  Proof.\n    intros x y z.\n    do 3 rewrite <- le_meet_join.\n    apply Transitive_le_meet.\n  Qed.\n  Instance PreOrder_le_join : PreOrder le_join := {|\n    PreOrder_Reflexive := Reflexive_le_join;\n    PreOrder_Transitive := Transitive_le_join;\n  |}.\n  Instance PartialOrder_le_join : PartialOrder equ le_join.\n  Proof.\n    intros x y.\n    unfold pointwise_lifting, relation_conjunction, Basics.flip, predicate_intersection, pointwise_extension.\n    do 2 rewrite <- le_meet_join.\n    apply PartialOrder_le_meet.\n  Qed.\n\nEnd Lattice.\nEnd Lattice.\n\n", "meta": {"author": "Skyb0rg007", "repo": "Policy-Iteration-Coq", "sha": "687dcdc869f3c51f430d4adeaa9fcc7a8da86115", "save_path": "github-repos/coq/Skyb0rg007-Policy-Iteration-Coq", "path": "github-repos/coq/Skyb0rg007-Policy-Iteration-Coq/Policy-Iteration-Coq-687dcdc869f3c51f430d4adeaa9fcc7a8da86115/theories/Lattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6528460266655648}}
{"text": "Require Import Coq.Setoids.Setoid.\n\nLemma drop_antecedent:\n  forall P Q: Prop, P -> (P -> Q) <-> Q.\nProof.\n  tauto.\nQed.\n\nLemma drop_antecedent_3:\n  forall (A B C D : Prop),\n  A ->\n  B ->\n  C ->\n  (A -> B -> C -> D) <-> D.\nProof.\n  intros.\n  do 3 (erewrite drop_antecedent; eauto).\n  eapply iff_refl.\nQed.\n", "meta": {"author": "verified-network-toolchain", "repo": "leapfrog", "sha": "fe8c4e60c9d1c2660ca2a199909bef04c81e5634", "save_path": "github-repos/coq/verified-network-toolchain-leapfrog", "path": "github-repos/coq/verified-network-toolchain-leapfrog/leapfrog-fe8c4e60c9d1c2660ca2a199909bef04c81e5634/lib/Utils/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.652846023332339}}
{"text": "From Coq Require Import List Arith Lia Permutation Wf_nat.\nImport ListNotations.\n\nFrom Undecidability.Shared.Libs.DLW Require Import gcd prime.\nFrom Undecidability.FRACTRAN Require Import FRACTRAN fractran_utils.\n\nSet Default Goal Selector \"!\".\n\n(* necessary facts on prime factorization *)\nModule Prime_factors.\n\n#[local] Notation lprod := (fold_right mult 1).\n\nLemma prime_divides_lt {lc ld} :\n  ~ (divides (lprod ld) (lprod lc)) ->\n  Forall prime lc -> Forall prime ld ->\n  exists (p : nat), prime p /\\ count_occ Nat.eq_dec lc p < count_occ Nat.eq_dec ld p.\nProof.\n  revert lc. induction ld as [|a ld IHld].\n  - intros lc H. exfalso. apply H.\n    exists (lprod lc). cbn. lia.\n  - intros lc H Hlc Hld'.\n    pose proof (Ha := Forall_inv Hld').\n    pose proof (Hld := Forall_inv_tail Hld').\n    destruct (in_dec Nat.eq_dec a lc) as [Halc|Halc].\n    + apply in_split in Halc as [l1c [l2c ?]]. subst lc.\n      assert (H' : not (divides (lprod (ld)) (lprod (l1c ++ l2c)))).\n      { intros [p Hp]. rewrite !lprod_app in *.\n        apply H. exists p. cbn. nia. }\n      assert (H'lc : Forall prime (l1c ++ l2c)).\n      { revert Hlc. rewrite !Forall_app.\n        now intros [? ? %Forall_inv_tail]. }\n      specialize (IHld _ H' H'lc Hld).\n      destruct IHld as [p [? Hp]].\n      exists p. split; [assumption|].\n      revert Hp. rewrite !count_occ_app. cbn.\n      destruct (Nat.eq_dec); lia.\n    + exists a. split; [assumption|].\n      apply (count_occ_not_In Nat.eq_dec) in Halc.\n      rewrite count_occ_cons_eq, Halc; lia.\nQed.\n\nDefinition count_pow (p n : nat) : nat :=\n  let (l, _) := (@prime_decomp (S n) (Nat.neq_succ_0 n))\n    in count_occ Nat.eq_dec l p.\n\nLemma prime_divides_lt' {c d} (Hc : c <> 0) (Hd : d <> 0):\n  ~ (divides d c) ->\n  exists p,\n    (forall x y, (S x) * c = (S y) * d -> count_pow p y < count_pow p x).\nProof.\n  pose proof (@prime_decomp c Hc) as [lc [Hclc Hlc]].\n  pose proof (@prime_decomp d Hd) as [ld [Hdld Hld]].\n  subst. intros H. apply prime_divides_lt in H as [p [? Hp]]; [|assumption ..].\n  exists p. intros x y. unfold count_pow.\n  destruct (@prime_decomp (S x) _) as [lx [Hxlx Hlx]].\n  destruct (@prime_decomp (S y) _) as [ly [Hyly Hly]].\n  rewrite Hxlx, Hyly, <- !lprod_app.\n  intros E. apply prime_decomp_uniq in E; [|now rewrite Forall_app ..].\n  assert (iffLR : forall P Q, (P <-> Q) -> P -> Q) by tauto.\n  assert (H' := iffLR _ _ (Permutation_count_occ Nat.eq_dec _ _) E p).\n  rewrite !count_occ_app in H'. lia.\nQed.\n\nLemma rel_prime_intro {p q} : (p <> 0 \\/ q <> 0) ->\n  { a & { b & { g | p = a*g /\\ q = b*g /\\ is_gcd a b 1 } } }.\nProof.\n  intros ?. assert (Hg := gcd_spec p q).\n  assert (gcd p q <> 0).\n  { intros H'g. rewrite H'g in Hg. apply is_gcd_0 in Hg. tauto. }\n  destruct (divides_dec p (gcd p q)) as [[a Ha]|].\n  2: { unfold is_gcd in Hg. tauto. }\n  destruct (divides_dec q (gcd p q)) as [[b Hb]|].\n  2: { unfold is_gcd in Hg. tauto. }\n  exists a, b, (gcd p q). split; [easy|split;[easy|]].\n  split; [apply divides_1|]. split; [apply divides_1|].\n  intros [|[|k]].\n  - intros [??] [??]. nia.\n  - intros _ _. now exists 1.\n  - intros [ka ?] [kb ?]. subst a b. exfalso.\n    destruct Hg as [[??] [[??] Hpq]].\n    destruct (Hpq (S (S k) * (gcd p q))) as [k' ?].\n    + exists ka. nia.\n    + exists kb. nia.\n    + destruct k' as [|?]; nia.\nQed.\n\nEnd Prime_factors.\n\nImport Prime_factors.\n\nModule Argument.\n\nLemma fractran_nstop_cons a b l s :\n  (forall t, ~ l /F/ t ↓) -> ~ (a,b) :: l /F/ s ↓.\nProof.\n  intros H [u [[n Hsu] Hu]].\n  destruct (divides_dec (a*u) b) as [[t Ht]|?].\n  - apply (Hu t), in_fractran_0. lia.\n  - apply (H u). exists u.\n    split; [now exists 0|].\n    intros t Hut. now apply (Hu t), in_fractran_1.\nQed.\n\nLemma fractran_nstop_zero_num_1 d l s : ~ (0,d) :: l /F/ s ↓.\nProof.\n  destruct d as [|d]; simpl; intros [y [_ Hs]]; apply (Hs 0); now constructor.\nQed.\n\nLemma fractran_stop_zero_den_1 c s (Hc : c <> 0) : [(c, 0)] /F/ s ↓.\nProof.\n  destruct s as [|s]; simpl.\n  - exists 1. constructor.\n    + exists 1. exists 1. constructor; [|reflexivity].\n      now constructor.\n    + intros z [?|[? Hz]]%fractran_step_cons_inv; [lia|inversion Hz].\n  - exists (S s). constructor.\n    + now exists 0.\n    + intros z [?|[? Hz]]%fractran_step_cons_inv; [lia|inversion Hz].\nQed.\n\nLemma fractran_stop_ndiv_singleton x c d (Hc : c <> 0) (Hd : d <> 0) :\n  ~ divides d c -> [(c,d)] /F/ (S x) ↓.\nProof.\n  intros [p H]%(prime_divides_lt' Hc Hd).\n  induction x as [x IH] using (induction_ltof1 _ (fun x => (count_pow p x))); unfold ltof in IH.\n  destruct (fractran_step_dec [(c,d)] (S x)) as [[y Hxy]|Hs].\n  - revert Hxy. intros [|[? Hxy]]%fractran_step_cons_inv.\n    + destruct y as [|y]; [lia|].\n      specialize (H x y ltac:(lia)).\n      apply IH in H as [y' [[n Hyy'] Hs']].\n      exists y'. split; [|exact Hs'].\n      exists (1+n), (S y). now split; [constructor|].\n    + inversion Hxy.\n  - exists (S x). now split; [exists 0|].\nQed.\n\n(* if the second fraction is not redundant, then the program is not reversible *)\nLemma fractran_step_contradict_reversible a b c d l :\n  is_gcd b a 1 -> ~ divides b d ->\n  exists (s t u : nat),\n    (a,b) :: (c,d) :: l /F/ s ≻ u /\\ (a,b) :: (c,d) :: l /F/ t ≻ u /\\ s <> t.\nProof.\n  intros Hba Hbd. exists (c*b), (a*d), (a*c).\n  constructor; [constructor; lia|].\n  constructor.\n  - apply in_fractran_1.\n    + intros Hb. now do 2 apply (is_rel_prime_div _ Hba) in Hb.\n    + constructor. lia.\n  - intros E. apply Hbd. apply (is_rel_prime_div _ Hba). now exists c.\nQed.\n\nLemma fractran_step_iff_halt l1 l2 :\n  (forall s t, l1 /F/ s ≻ t <-> l2 /F/ s ≻ t) -> (forall x, l1 /F/ x ↓ -> l2 /F/ x ↓).\nProof.\n  intros H x. intros [y [[n Hn] Hs]]. exists y. constructor.\n  - exists n. revert x Hn. induction n as [|n IHn]; simpl; auto.\n    intros x [y' [Hy' Hs']]. exists y'. constructor; [now apply H|now apply IHn].\n  - intros z Hs'. now apply (Hs z), H.\nQed.\n\nLemma fractran_step_iff_decide {l1 l2 n} :\n  (forall s t, l1 /F/ s ≻ t <-> l2 /F/ s ≻ t) ->\n  ((l1 /F/ n ↓) + (not (l1 /F/ n ↓))) ->\n  ((l2 /F/ n ↓) + (not (l2 /F/ n ↓))).\nProof.\n  intros H [|Hn]; [left|right].\n  - eapply fractran_step_iff_halt; eassumption.\n  - intros ?. apply Hn. eapply fractran_step_iff_halt; [|eassumption].\n    firstorder easy.\nQed.\n\n(* in a reversible FRACTRAN program the second fraction is shadowed by the first *)\nLemma fractran_reversible_shadow {a b c d P x y} : x <> 0 -> y <> 0 ->\n  fractran_reversible ((a * x, b * x) :: (c * y, d * y) :: P) ->\n  is_gcd b a 1 -> is_gcd d c 1 ->\n  forall s t, (c * y) * s = t * (d * y) -> exists u, (a * x) * s = u * (b * x).\nProof.\n  intros ?? HP Hba Hdc.\n  destruct (divides_dec d b) as [[u Hu]|Hb].\n  - subst d. intros s t Hst.\n    assert (Hubcs : divides (u * b) (c * s)) by (exists t; nia).\n    destruct (is_rel_prime_div s Hdc Hubcs) as [k ?].\n    subst s. exists (a*k*u). nia.\n  - exfalso.\n    destruct (fractran_step_contradict_reversible a b c d P Hba Hb) as [s [t [u [? [? Hst]]]]].\n    apply Hst.\n    enough (H_extend : forall s' t', (a, b) :: (c, d) :: P /F/ s' ≻ t' ->\n      (a * x, b * x) :: (c * y, d * y) :: P /F/ s' ≻ t').\n    { apply (HP s t u); now apply H_extend. }\n    intros s' t' [|[H'b Hs't']]%fractran_step_cons_inv.\n    + apply in_fractran_0. nia.\n    + revert Hs't'. intros [|[H'd Hs't']]%fractran_step_cons_inv.\n      * apply in_fractran_1.\n        { intros [k ?]. apply H'b. exists k. nia. }\n        apply in_fractran_0. nia.\n      * apply in_fractran_1.\n        { intros [k1 ?]. apply H'b. exists k1. nia. }\n        apply in_fractran_1.\n        { intros [k2 ?]. apply H'd. exists k2. nia. }\n        exact Hs't'.\nQed.\n\nLemma fractran_reversible_shorten {a b c d P s t} :\n  fractran_reversible ((S a, b) :: (S c, d) :: P) ->\n  ((S a, b) :: P /F/ s ≻ t) <-> ((S a, b) :: (S c, d) :: P /F/ s ≻ t).\nProof.\n  intros HP.\n  assert (Hba : b <> 0 \\/ S a <> 0) by lia.\n  destruct (rel_prime_intro Hba) as [b' [a' [gab [H'b [H'a Hb'a']]]]].\n  rewrite H'b, H'a in *.\n  assert (Hdc : d <> 0 \\/ S c <> 0) by lia.\n  destruct (rel_prime_intro Hdc) as [d' [c' [gcd [H'd [H'c Hd'c']]]]].\n  rewrite H'd, H'c in *.\n  assert (Hgab : gab <> 0) by lia.\n  assert (Hgcd : gcd <> 0) by lia.\n  split.\n  + intros [?|[Hb ?]]%fractran_step_cons_inv.\n    * now apply in_fractran_0.\n    * apply in_fractran_1; [easy|].\n      apply in_fractran_1; [|easy].\n      intros [m Hm]. apply Hb.\n      eapply (fractran_reversible_shadow Hgab Hgcd HP Hb'a' Hd'c').\n      eassumption.\n  + intros [?|[Hb H']]%fractran_step_cons_inv.\n    * now apply in_fractran_0.\n    * revert H'. intros [H'|[Hd ?]]%fractran_step_cons_inv.\n      ** exfalso. apply Hb. eapply (fractran_reversible_shadow Hgab Hgcd HP Hb'a' Hd'c' s t). lia.\n      ** now apply in_fractran_1.\nQed.\n\n(* informative decision statement for empty FRACTRAN halting *)\nLemma fractran_empty_decision (n: nat) : ([] /F/ n ↓).\nProof.\n  exists n. split; [now exists 0|].\n  intros z H. now inversion H.\nQed.\n\n(* informative decision statement for singleton FRACTRAN halting *)\nLemma fractran_singleton_decision c d n : ([(c,d)] /F/ n ↓) + (not ([(c,d)] /F/ n ↓)).\nProof.\n  destruct (divides_dec c d) as [[k Hk] | Hndiv].\n  { right. intros [y [[m Hm] Hstop]]. apply (Hstop (k*y)). constructor. nia. }\n  destruct c as [|c].\n  { right. now intros H%fractran_nstop_zero_num_1. }\n  destruct d as [|d].\n  { left. now apply fractran_stop_zero_den_1. }\n  destruct n as [|n].\n  { right. intros [y [[n Hn] Hy]].\n    apply fractran_rt_no_zero_den in Hn.\n    - apply (Hy 0). apply in_fractran_0. lia.\n    - now repeat constructor. }\n  left. now apply fractran_stop_ndiv_singleton.\nQed.\n\n(* informative decision statement for reversible FRACTRAN halting *)\nTheorem decision (P : list (nat * nat)) (n: nat) : fractran_reversible P -> (P /F/ n ↓) + (not (P /F/ n ↓)).\nProof.\n  induction P as [P IH] using (induction_ltof1 _ (fun P => length P)); unfold ltof in IH.\n  destruct P as [|(a,b) [|(c,d) P]].\n  - (* empty program *)\n    intros _. left. now apply fractran_empty_decision.\n  - (* singleton program *)\n    intros _. now apply fractran_singleton_decision.\n  - (* at least two fractions, remove the second *)\n    destruct a as [|a]; simpl.\n    { intros _. right. now intros H%fractran_nstop_zero_num_1. }\n    destruct c as [|c]; simpl.\n    { intros _. right. now apply fractran_nstop_cons, fractran_nstop_zero_num_1. }\n    intros HP.\n    enough (H'P : forall s t, ((S a, b) :: P) /F/ s ≻ t <-> ((S a, b) :: (S c, d) :: P) /F/ s ≻ t).\n    { apply (fractran_step_iff_decide H'P).\n      apply IH; simpl; [lia|].\n      intros n1 n2 m Hn1%H'P Hn2%H'P. eapply HP; eassumption. }\n    intros s t. now apply fractran_reversible_shorten.\nQed.\n\nEnd Argument.\n\nRequire Import Undecidability.Synthetic.Definitions.\n\n(* decision procedure for the halting problem for reversible FRACTRAN *)\nDefinition decide : { P : list (nat * nat) | fractran_reversible P } * nat -> bool :=\n  fun '(exist _ P HP, x) =>\n    match Argument.decision P x HP with\n    | inl _ => true\n    | inr _ => false\n    end.\n\n(* decision procedure correctness *)\nLemma decide_spec : decider decide Halt_REV_FRACTRAN.\nProof.\n  intros [[P HP] x]. unfold reflects. simpl.\n  destruct (Argument.decision P x HP) as [[y Hy%eval_iff]|HPx].\n  - firstorder easy.\n  - split; [|easy]. intros [y ?%eval_iff]. firstorder easy.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/FRACTRAN/Deciders/Halt_REV_FRACTRAN_dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6528460221184973}}
{"text": "(** attempted 4 and completed 4 out of 4 optional exercises *)\n(** attempted 3 and completed 3 out of 3 advanced exercises *)\n(** Exercise 1 (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intros p. destruct p as (n, m). reflexivity.  Qed.\n\n\n(** Exercise 2 (optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  intros p. destruct p as (n, m). reflexivity.  Qed.\n  \n\n(** Exercise 3 (list_funs) *)\nixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | O :: t => nonzeros t\n  | h :: t => h :: (nonzeros t)\n  end.\nExample test_nonzeros:          nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity.  Qed.\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\n(** Exercise 4 (advanced (alternate)) *)\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n  | nil, l2' => l2'\n  | l1', nil => l1'\n  | h1 :: t1, h2 :: t2 => h1 :: h2 :: (alternate t1 t2)\n  end.\n\nExample test_alternate1:        alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. 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(** Exercise 5 (bag_functions) *)\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.\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(** Exercise 6 (bag functions) *)\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.\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\n(** Exercise 7 (optional (bag_more_functions)) *)\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  (* When remove_one is applied to a bag without the number to remove,\n     it should return the same bag unchanged. *)\n  match s with\n  | nil => nil\n  | h :: t => match beq_nat h v with\n              | true => t\n              | false => h :: (remove_one v t)\n              end\n  end.\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.\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  | nil => true\n  | h :: t => match member h s2 with\n              | true => subset t (remove_one h s2)\n              | false => false\n              end\n  end.\n\nExample test_subset1:              subset [1;2] [2;1;4;1] = true.\nProof. reflexivity.  Qed.\nExample test_subset2:              subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity.  Qed.\n\n\n(** Exercise 8 (bag_theorem) *)\nTheorem beq_nat_refl: forall n : nat,\n  beq_nat n n = true.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n\nTheorem add_count: forall (n : nat) (s : bag),\n  count n (add n s) = S (count n s).\nProof.\n  intros n s. destruct s as [| m l'].\n  Case \"s = nil\".\n    simpl. rewrite -> beq_nat_refl. reflexivity.\n  Case \"s = cons\".\n    simpl. rewrite -> beq_nat_refl. reflexivity.  Qed.\n\n\n(** Exercise 9 (list_exercises) *)\nTheorem app_nil_end : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons\".\n    simpl. rewrite -> IHl'. reflexivity.  Qed.\n\nTheorem rev_snoc: forall n : nat, forall l : natlist,\n  rev (snoc l n) = n :: rev l.\nProof.\n  intros n l. induction l as [| m l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons\".\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 = nil\".\n    reflexivity.\n  Case \"l = cons\".\n    simpl. rewrite -> rev_snoc. rewrite -> IHl'. reflexivity.  Qed.\nTheorem app_ass4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros l1 l2 l3 l4.\n  rewrite -> app_ass. rewrite -> app_ass. reflexivity.  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\".\n    reflexivity.\n  Case \"l = cons\".\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 as [| n1 l1'].\n  Case \"l1 = nil\".\n    simpl. rewrite -> app_nil_end. reflexivity.\n  Case \"l1 = cons\".\n    simpl. rewrite -> snoc_append. rewrite -> snoc_append.\n    rewrite -> IHl1'. rewrite -> app_ass. reflexivity.  Qed.\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2. induction l1 as [| n1 l1'].\n  Case \"l1 = nil\".\n    reflexivity.\n  Case \"l1 = cons\".\n    simpl. rewrite -> IHl1'.\n    destruct n1 as [| n1'].\n    SCase \"n1 = O\".\n      reflexivity.\n    SCase \"n1 = S n1'\".\n      reflexivity.  Qed.\n\n\n(** Exercise 10 (beq_natlist) *)\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1 with\n  | h1 :: t1 => match l2 with\n                | h2 :: t2 => andb (beq_nat h1 h2) (beq_natlist t1 t2)\n                | nil => false\n                end\n  | nil      => match l2 with\n                | h2 :: t2 => false\n                | nil => true\n                end\n  end.\n\nExample test_beq_natlist1 :   (beq_natlist nil nil = true).\n  Proof. reflexivity.  Qed.\nExample test_beq_natlist2 :   beq_natlist [1;2;3] [1;2;3] = true.\n  Proof. reflexivity.  Qed.\nExample test_beq_natlist3 :   beq_natlist [1;2;3] [1;2;4] = false.\n  Proof. reflexivity.  Qed.\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  intros l. induction l as [| l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons\".\n    simpl. rewrite <- IHl. rewrite <- beq_nat_refl. simpl. reflexivity.\n  Qed.\n\n\n(** Exercise 11 (list_design) *)\nTheorem cons_snoc_append: forall (n1 n2 : nat), forall l : natlist,\n  [n1] ++ (snoc l n2) = (cons n1 l) ++ [n2].\nProof.\n  intros n1 n2 l. simpl. rewrite -> snoc_append. reflexivity.  Qed.\n\n\n(** Exercise 12 (advanced (bag_proofs)) *)\nTheorem count_member_nonzero : forall (s : bag),\n  ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n  intros s.\n  simpl. reflexivity. Qed.\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\".\n    simpl. reflexivity.\n  Case \"s = cons\".\n    simpl. destruct n.\n    SCase \"n = 0\".\n      simpl. rewrite ble_n_Sn. reflexivity.\n    SCase \"n = S n'\".\n      simpl. rewrite IHs'. reflexivity.\n  Qed.\n\n\n(** Exercise 13 (optional (bag_count_sum)) *)\nTheorem bag_count_sum: forall n : nat, forall s1 s2 : bag,\n  count n (sum s1 s2) = (count n s1) + (count n s2).\nProof.\n  intros n s1 s2. induction s1 as [| m s1'].\n  Case \"s1 = nil\".\n    reflexivity.\n  Case \"s1 = cons\".\n    simpl. rewrite -> IHs1'.\n    remember (beq_nat m n) as eq.\n    destruct eq.\n    SCase \"eq = true\".\n      reflexivity.\n    SCase \"eq = false\".\n      reflexivity.  Qed.\n\n\n(** Exercise 14 (advanced (rev_injective)) *)\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(** Exercise 15 (hd_opt) *)\nDefinition hd_opt (l : natlist) : natoption :=\n  match l with\n  | h :: t => Some h\n  | nil => None\n  end.\n\nExample test_hd_opt1 : hd_opt [] = None.\n Proof. reflexivity.  Qed.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\n Proof. reflexivity.  Qed.\n\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\n Proof. reflexivity.  Qed.\n\n\n(** Exercise 16 (optional (option_elim_hd)) *)\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_opt l).\nProof.\n  intros l default. destruct l as [| n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons\".\n    reflexivity.  Qed.\n    \n\n(** Exercise 17 (dictionary_invariant1) *)\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.\n  Qed.\n  \n\n(** Exercise 18 (dictionary_invariant2) *)\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. Qed.\n  \n\n\n", "meta": {"author": "surenz20", "repo": "CS6463", "sha": "2325abfb1d5c18104c05d4d29bf9fe1bd7de0558", "save_path": "github-repos/coq/surenz20-CS6463", "path": "github-repos/coq/surenz20-CS6463/CS6463-2325abfb1d5c18104c05d4d29bf9fe1bd7de0558/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.6528460120369057}}
{"text": "Require Import BinInt.\nFrom mathcomp Require Import all_ssreflect all_algebra.\nRequire Import tactics binomialz rat_of_Z seq_defs.\nRequire harmonic_numbers.\n\nLocal Open Scope ring_scope.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* We state the equalities and prove evaluations of the main sequences \n   a and b, to be used as initial conditions. Proofs are done by\n   (internal) computation, using the field tactic so that computations\n   are performed using a rather efficient binary arithmetic instead of\n   type rat which is awful for 'large' scale computations.*)\n\n(* A tactic to unroll the definition of a and preprocess the term in order *)\n(* for rat_field to be able to process the equality correctly. *)\nLtac expand_a :=\n(* unfolding the definition of a, c, binomials and unlocking the constant *)\n(* defining the sigma, so that sums can be unrolled: *)\nrewrite /a /c /binomialz unlock /=.\n\n(* A tactic to unroll the definition of b and preprocess the term in order *)\n(* for rat_field to be able to process the equality correctly. *)\nLtac expand_b :=\n(* unfolding the definition of b: *)\nrewrite /b; \n(* unfolding the definition of auxiliary sequence and unlocking the constant*)\n(* defining the sigma, so that sums can be unrolled: *)\nrewrite unlock /= /v /c /u /ghn3 /harmonic_numbers.ghn;\nrewrite unlock /= /s unlock /= /d /binomialz /=;\n(* normalizing the exponents (that are natural numbers) *)\nrewrite ?(=^~ PoszD, addnE) /=.\n\n\n(* Tactic proving an evaluation for the sequence a (fails otherwise) *)\nLtac solve_a_evaluation := by expand_a; field.\n\n(* Tactic proving an evaluation for the sequence b (fails otherwise) *)\nLtac solve_b_evaluation := by expand_b; field.\n\n\n\n(* Evaluations for the sequence b. With our definition we have:\n        b_n = 0, 6, 351/4, 62531/36, ... *)\n\nLemma b0_eq : b 0 = 0.\nProof. solve_b_evaluation. Qed.\n\nLemma b1_eq : b 1 = 6%:Q.\nProof. solve_b_evaluation. Qed.\n\nLemma b2_eq : b 2 = rat_of_Z 351 / rat_of_Z 4.\nProof. solve_b_evaluation. Qed.\n\nLemma b3_eq : b 3 = rat_of_Z 62531 / rat_of_Z 36.\nProof. solve_b_evaluation. Qed.\n\n\n(* Evaluations for the sequence b. With our definition we have:\n     a_n = 1, 5, 73, 1445, 33001 ... *)\n\nLemma a0_eq : a 0 = 1.\nProof. solve_a_evaluation. Qed.\n\nLemma a1_eq : a 1 = rat_of_Z 5.\nProof. solve_a_evaluation. Qed.\n\nLemma a2_eq : a 2 = rat_of_Z 73.\nProof. solve_a_evaluation. Qed.\n\nLemma a3_eq : a 3 = rat_of_Z 1445.\nProof. solve_a_evaluation. Qed.\n", "meta": {"author": "coq-community", "repo": "apery", "sha": "305046d98025d75ca426cc44283302963389f1dc", "save_path": "github-repos/coq/coq-community-apery", "path": "github-repos/coq/coq-community-apery/apery-305046d98025d75ca426cc44283302963389f1dc/theories/initial_conds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6528460118105204}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Correctness of instruction selection for integer division *)\n\nRequire Import Zquot Coqlib.\nRequire Import AST Integers Floats Values Memory Globalenvs Events.\nRequire Import Cminor Op CminorSel.\nRequire Import SelectOp SelectOpproof SplitLong SplitLongproof SelectLong SelectLongproof SelectDiv.\n\nLocal Open Scope cminorsel_scope.\n\n(** * Main approximation theorems *)\n\nSection Z_DIV_MUL.\n\nVariable N: Z.      (**r number of relevant bits *)\nHypothesis N_pos: N >= 0.\nVariable d: Z.      (**r divisor *)\nHypothesis d_pos: d > 0.\n\n(** This is theorem 4.2 from Granlund and Montgomery, PLDI 1994. *)\n\nLemma Zdiv_mul_pos:\n  forall m l,\n  l >= 0 ->\n  two_p (N+l) <= m * d <= two_p (N+l) + two_p l ->\n  forall n,\n  0 <= n < two_p N ->\n  Zdiv n d = Zdiv (m * n) (two_p (N + l)).\nProof.\n  intros m l l_pos [LO HI] n RANGE.\n  exploit (Z_div_mod_eq n d). auto.\n  set (q := n / d).\n  set (r := n mod d).\n  intro EUCL.\n  assert (0 <= r <= d - 1).\n    unfold r. generalize (Z_mod_lt n d d_pos). omega.\n  assert (0 <= m).\n    apply Zmult_le_0_reg_r with d. auto.\n    exploit (two_p_gt_ZERO (N + l)). omega. omega.\n  set (k := m * d - two_p (N + l)).\n  assert (0 <= k <= two_p l).\n    unfold k; omega.\n  assert ((m * n - two_p (N + l) * q) * d = k * n + two_p (N + l) * r).\n    unfold k. rewrite EUCL. ring.\n  assert (0 <= k * n).\n    apply Zmult_le_0_compat; omega.\n  assert (k * n <= two_p (N + l) - two_p l).\n    apply Zle_trans with (two_p l * n).\n    apply Zmult_le_compat_r. omega. omega.\n    replace (N + l) with (l + N) by omega.\n    rewrite two_p_is_exp.\n    replace (two_p l * two_p N - two_p l)\n       with (two_p l * (two_p N - 1))\n         by ring.\n    apply Zmult_le_compat_l. omega. exploit (two_p_gt_ZERO l). omega. omega.\n    omega. omega.\n  assert (0 <= two_p (N + l) * r).\n    apply Zmult_le_0_compat.\n    exploit (two_p_gt_ZERO (N + l)). omega. omega.\n    omega.\n  assert (two_p (N + l) * r <= two_p (N + l) * d - two_p (N + l)).\n    replace (two_p (N + l) * d - two_p (N + l))\n       with (two_p (N + l) * (d - 1)) by ring.\n    apply Zmult_le_compat_l.\n    omega.\n    exploit (two_p_gt_ZERO (N + l)). omega. omega.\n  assert (0 <= m * n - two_p (N + l) * q).\n    apply Zmult_le_reg_r with d. auto.\n    replace (0 * d) with 0 by ring.  rewrite H2. omega.\n  assert (m * n - two_p (N + l) * q < two_p (N + l)).\n    apply Zmult_lt_reg_r with d. omega.\n    rewrite H2.\n    apply Zle_lt_trans with (two_p (N + l) * d - two_p l).\n    omega.\n    exploit (two_p_gt_ZERO l). omega. omega.\n  symmetry. apply Zdiv_unique with (m * n - two_p (N + l) * q).\n  ring. omega.\nQed.\n\nLemma Zdiv_unique_2:\n  forall x y q, y > 0 -> 0 < y * q - x <= y -> Zdiv x y = q - 1.\nProof.\n  intros. apply Zdiv_unique with (x - (q - 1) * y). ring.\n  replace ((q - 1) * y) with (y * q - y) by ring. omega.\nQed.\n\nLemma Zdiv_mul_opp:\n  forall m l,\n  l >= 0 ->\n  two_p (N+l) < m * d <= two_p (N+l) + two_p l ->\n  forall n,\n  0 < n <= two_p N ->\n  Zdiv n d = - Zdiv (m * (-n)) (two_p (N + l)) - 1.\nProof.\n  intros m l l_pos [LO HI] n RANGE.\n  replace (m * (-n)) with (- (m * n)) by ring.\n  exploit (Z_div_mod_eq n d). auto.\n  set (q := n / d).\n  set (r := n mod d).\n  intro EUCL.\n  assert (0 <= r <= d - 1).\n    unfold r. generalize (Z_mod_lt n d d_pos). omega.\n  assert (0 <= m).\n    apply Zmult_le_0_reg_r with d. auto.\n    exploit (two_p_gt_ZERO (N + l)). omega. omega.\n  cut (Zdiv (- (m * n)) (two_p (N + l)) = -q - 1).\n    omega.\n  apply Zdiv_unique_2.\n  apply two_p_gt_ZERO. omega.\n  replace (two_p (N + l) * - q - - (m * n))\n     with (m * n - two_p (N + l) * q)\n       by ring.\n  set (k := m * d - two_p (N + l)).\n  assert (0 < k <= two_p l).\n    unfold k; omega.\n  assert ((m * n - two_p (N + l) * q) * d = k * n + two_p (N + l) * r).\n    unfold k. rewrite EUCL. ring.\n  split.\n  apply Zmult_lt_reg_r with d. omega.\n  replace (0 * d) with 0 by omega.\n  rewrite H2.\n  assert (0 < k * n). apply Zmult_lt_0_compat; omega.\n  assert (0 <= two_p (N + l) * r).\n    apply Zmult_le_0_compat. exploit (two_p_gt_ZERO (N + l)); omega. omega.\n  omega.\n  apply Zmult_le_reg_r with d. omega.\n  rewrite H2.\n  assert (k * n <= two_p (N + l)).\n    rewrite Zplus_comm. rewrite two_p_is_exp; try omega.\n    apply Zle_trans with (two_p l * n). apply Zmult_le_compat_r. omega. omega.\n    apply Zmult_le_compat_l. omega. exploit (two_p_gt_ZERO l). omega. omega.\n  assert (two_p (N + l) * r <= two_p (N + l) * d - two_p (N + l)).\n    replace (two_p (N + l) * d - two_p (N + l))\n       with (two_p (N + l) * (d - 1))\n         by ring.\n    apply Zmult_le_compat_l. omega. exploit (two_p_gt_ZERO (N + l)). omega. omega.\n  omega.\nQed.\n\n(** This is theorem 5.1 from Granlund and Montgomery, PLDI 1994. *)\n\nLemma Zquot_mul:\n  forall m l,\n  l >= 0 ->\n  two_p (N+l) < m * d <= two_p (N+l) + two_p l ->\n  forall n,\n  - two_p N <= n < two_p N ->\n  Z.quot n d = Zdiv (m * n) (two_p (N + l)) + (if zlt n 0 then 1 else 0).\nProof.\n  intros. destruct (zlt n 0).\n  exploit (Zdiv_mul_opp m l H H0 (-n)). omega.\n  replace (- - n) with n by ring.\n  replace (Z.quot n d) with (- Z.quot (-n) d).\n  rewrite Zquot_Zdiv_pos by omega. omega.\n  rewrite Z.quot_opp_l by omega. ring.\n  rewrite Zplus_0_r. rewrite Zquot_Zdiv_pos by omega.\n  apply Zdiv_mul_pos; omega.\nQed.\n\nEnd Z_DIV_MUL.\n\n(** * Correctness of the division parameters *)\n\nLemma divs_mul_params_sound:\n  forall d m p,\n  divs_mul_params d = Some(p, m) ->\n  0 <= m < Int.modulus /\\ 0 <= p < 32 /\\\n  forall n,\n  Int.min_signed <= n <= Int.max_signed ->\n  Z.quot n d = Zdiv (m * n) (two_p (32 + p)) + (if zlt n 0 then 1 else 0).\nProof with (try discriminate).\n  unfold divs_mul_params; intros d m' p'.\n  destruct (find_div_mul_params Int.wordsize\n               (Int.half_modulus - Int.half_modulus mod d - 1) d 32)\n  as [[p m] | ]...\n  generalize (p - 32). intro p1.\n  destruct (zlt 0 d)...\n  destruct (zlt (two_p (32 + p1)) (m * d))...\n  destruct (zle (m * d) (two_p (32 + p1) + two_p (p1 + 1)))...\n  destruct (zle 0 m)...\n  destruct (zlt m Int.modulus)...\n  destruct (zle 0 p1)...\n  destruct (zlt p1 32)...\n  intros EQ; inv EQ.\n  split. auto. split. auto. intros.\n  replace (32 + p') with (31 + (p' + 1)) by omega.\n  apply Zquot_mul; try omega.\n  replace (31 + (p' + 1)) with (32 + p') by omega. omega.\n  change (Int.min_signed <= n < Int.half_modulus).\n  unfold Int.max_signed in H. omega.\nQed.\n\nLemma divu_mul_params_sound:\n  forall d m p,\n  divu_mul_params d = Some(p, m) ->\n  0 <= m < Int.modulus /\\ 0 <= p < 32 /\\\n  forall n,\n  0 <= n < Int.modulus ->\n  Zdiv n d = Zdiv (m * n) (two_p (32 + p)).\nProof with (try discriminate).\n  unfold divu_mul_params; intros d m' p'.\n  destruct (find_div_mul_params Int.wordsize\n               (Int.modulus - Int.modulus mod d - 1) d 32)\n  as [[p m] | ]...\n  generalize (p - 32); intro p1.\n  destruct (zlt 0 d)...\n  destruct (zle (two_p (32 + p1)) (m * d))...\n  destruct (zle (m * d) (two_p (32 + p1) + two_p p1))...\n  destruct (zle 0 m)...\n  destruct (zlt m Int.modulus)...\n  destruct (zle 0 p1)...\n  destruct (zlt p1 32)...\n  intros EQ; inv EQ.\n  split. auto. split. auto. intros.\n  apply Zdiv_mul_pos; try omega. assumption.\nQed.\n\nLemma divs_mul_shift_gen:\n  forall x y m p,\n  divs_mul_params (Int.signed y) = Some(p, m) ->\n  0 <= m < Int.modulus /\\ 0 <= p < 32 /\\\n  Int.divs x y = Int.add (Int.shr (Int.repr ((Int.signed x * m) / Int.modulus)) (Int.repr p))\n                         (Int.shru x (Int.repr 31)).\nProof.\n  intros. set (n := Int.signed x). set (d := Int.signed y) in *.\n  exploit divs_mul_params_sound; eauto. intros (A & B & C).\n  split. auto. split. auto.\n  unfold Int.divs. fold n; fold d. rewrite C by (apply Int.signed_range).\n  rewrite two_p_is_exp by omega. rewrite <- Zdiv_Zdiv.\n  rewrite Int.shru_lt_zero. unfold Int.add. apply Int.eqm_samerepr. apply Int.eqm_add.\n  rewrite Int.shr_div_two_p. apply Int.eqm_unsigned_repr_r. apply Int.eqm_refl2.\n  rewrite Int.unsigned_repr. f_equal.\n  rewrite Int.signed_repr. rewrite Int.modulus_power. f_equal. ring.\n  cut (Int.min_signed <= n * m / Int.modulus < Int.half_modulus).\n  unfold Int.max_signed; omega.\n  apply Zdiv_interval_1. generalize Int.min_signed_neg; omega. apply Int.half_modulus_pos.\n  apply Int.modulus_pos.\n  split. apply Zle_trans with (Int.min_signed * m). apply Zmult_le_compat_l_neg. omega. generalize Int.min_signed_neg; omega.\n  apply Zmult_le_compat_r. unfold n; generalize (Int.signed_range x); tauto. tauto.\n  apply Zle_lt_trans with (Int.half_modulus * m).\n  apply Zmult_le_compat_r. generalize (Int.signed_range x); unfold n, Int.max_signed; omega. tauto.\n  apply Zmult_lt_compat_l. generalize Int.half_modulus_pos; omega. tauto.\n  assert (32 < Int.max_unsigned) by (compute; auto). omega.\n  unfold Int.lt; fold n. rewrite Int.signed_zero. destruct (zlt n 0); apply Int.eqm_unsigned_repr.\n  apply two_p_gt_ZERO. omega.\n  apply two_p_gt_ZERO. omega.\nQed.\n\nTheorem divs_mul_shift_1:\n  forall x y m p,\n  divs_mul_params (Int.signed y) = Some(p, m) ->\n  m < Int.half_modulus ->\n  0 <= p < 32 /\\\n  Int.divs x y = Int.add (Int.shr (Int.mulhs x (Int.repr m)) (Int.repr p))\n                         (Int.shru x (Int.repr 31)).\nProof.\n  intros. exploit divs_mul_shift_gen; eauto. instantiate (1 := x).\n  intros (A & B & C). split. auto. rewrite C.\n  unfold Int.mulhs. rewrite Int.signed_repr. auto.\n  generalize Int.min_signed_neg; unfold Int.max_signed; omega.\nQed.\n\nTheorem divs_mul_shift_2:\n  forall x y m p,\n  divs_mul_params (Int.signed y) = Some(p, m) ->\n  m >= Int.half_modulus ->\n  0 <= p < 32 /\\\n  Int.divs x y = Int.add (Int.shr (Int.add (Int.mulhs x (Int.repr m)) x) (Int.repr p))\n                         (Int.shru x (Int.repr 31)).\nProof.\n  intros. exploit divs_mul_shift_gen; eauto. instantiate (1 := x).\n  intros (A & B & C). split. auto. rewrite C. f_equal. f_equal.\n  rewrite Int.add_signed. unfold Int.mulhs. set (n := Int.signed x).\n  transitivity (Int.repr (n * (m - Int.modulus) / Int.modulus + n)).\n  f_equal.\n  replace (n * (m - Int.modulus)) with (n * m +  (-n) * Int.modulus) by ring.\n  rewrite Z_div_plus. ring. apply Int.modulus_pos.\n  apply Int.eqm_samerepr. apply Int.eqm_add; auto with ints.\n  apply Int.eqm_sym. eapply Int.eqm_trans. apply Int.eqm_signed_unsigned.\n  apply Int.eqm_unsigned_repr_l. apply Int.eqm_refl2. f_equal. f_equal.\n  rewrite Int.signed_repr_eq. rewrite Zmod_small by assumption.\n  apply zlt_false. omega.\nQed.\n\nTheorem divu_mul_shift:\n  forall x y m p,\n  divu_mul_params (Int.unsigned y) = Some(p, m) ->\n  0 <= p < 32 /\\\n  Int.divu x y = Int.shru (Int.mulhu x (Int.repr m)) (Int.repr p).\nProof.\n  intros. exploit divu_mul_params_sound; eauto. intros (A & B & C).\n  split. auto.\n  rewrite Int.shru_div_two_p. rewrite Int.unsigned_repr.\n  unfold Int.divu, Int.mulhu. f_equal. rewrite C by apply Int.unsigned_range.\n  rewrite two_p_is_exp by omega. rewrite <- Zdiv_Zdiv by (apply two_p_gt_ZERO; omega).\n  f_equal. rewrite (Int.unsigned_repr m).\n  rewrite Int.unsigned_repr. f_equal. ring.\n  cut (0 <= Int.unsigned x * m / Int.modulus < Int.modulus).\n  unfold Int.max_unsigned; omega.\n  apply Zdiv_interval_1. omega. compute; auto. compute; auto.\n  split. simpl. apply Z.mul_nonneg_nonneg. generalize (Int.unsigned_range x); omega. omega.\n  apply Zle_lt_trans with (Int.modulus * m).\n  apply Zmult_le_compat_r. generalize (Int.unsigned_range x); omega. omega.\n  apply Zmult_lt_compat_l. compute; auto. omega.\n  unfold Int.max_unsigned; omega.\n  assert (32 < Int.max_unsigned) by (compute; auto). omega.\nQed.\n\n(** Same, for 64-bit integers *)\n\nLemma divls_mul_params_sound:\n  forall d m p,\n  divls_mul_params d = Some(p, m) ->\n  0 <= m < Int64.modulus /\\ 0 <= p < 64 /\\\n  forall n,\n  Int64.min_signed <= n <= Int64.max_signed ->\n  Z.quot n d = Zdiv (m * n) (two_p (64 + p)) + (if zlt n 0 then 1 else 0).\nProof with (try discriminate).\n  unfold divls_mul_params; intros d m' p'.\n  destruct (find_div_mul_params Int64.wordsize\n               (Int64.half_modulus - Int64.half_modulus mod d - 1) d 64)\n  as [[p m] | ]...\n  generalize (p - 64). intro p1.\n  destruct (zlt 0 d)...\n  destruct (zlt (two_p (64 + p1)) (m * d))...\n  destruct (zle (m * d) (two_p (64 + p1) + two_p (p1 + 1)))...\n  destruct (zle 0 m)...\n  destruct (zlt m Int64.modulus)...\n  destruct (zle 0 p1)...\n  destruct (zlt p1 64)...\n  intros EQ; inv EQ.\n  split. auto. split. auto. intros.\n  replace (64 + p') with (63 + (p' + 1)) by omega.\n  apply Zquot_mul; try omega.\n  replace (63 + (p' + 1)) with (64 + p') by omega. omega.\n  change (Int64.min_signed <= n < Int64.half_modulus).\n  unfold Int64.max_signed in H. omega.\nQed.\n\nLemma divlu_mul_params_sound:\n  forall d m p,\n  divlu_mul_params d = Some(p, m) ->\n  0 <= m < Int64.modulus /\\ 0 <= p < 64 /\\\n  forall n,\n  0 <= n < Int64.modulus ->\n  Zdiv n d = Zdiv (m * n) (two_p (64 + p)).\nProof with (try discriminate).\n  unfold divlu_mul_params; intros d m' p'.\n  destruct (find_div_mul_params Int64.wordsize\n               (Int64.modulus - Int64.modulus mod d - 1) d 64)\n  as [[p m] | ]...\n  generalize (p - 64); intro p1.\n  destruct (zlt 0 d)...\n  destruct (zle (two_p (64 + p1)) (m * d))...\n  destruct (zle (m * d) (two_p (64 + p1) + two_p p1))...\n  destruct (zle 0 m)...\n  destruct (zlt m Int64.modulus)...\n  destruct (zle 0 p1)...\n  destruct (zlt p1 64)...\n  intros EQ; inv EQ.\n  split. auto. split. auto. intros.\n  apply Zdiv_mul_pos; try omega. assumption.\nQed.\n\nRemark int64_shr'_div_two_p:\n  forall x y, Int64.shr' x y = Int64.repr (Int64.signed x / two_p (Int.unsigned y)).\nProof.\n  intros; unfold Int64.shr'. rewrite Int64.Zshiftr_div_two_p; auto. generalize (Int.unsigned_range y); omega.\nQed.\n\nLemma divls_mul_shift_gen:\n  forall x y m p,\n  divls_mul_params (Int64.signed y) = Some(p, m) ->\n  0 <= m < Int64.modulus /\\ 0 <= p < 64 /\\\n  Int64.divs x y = Int64.add (Int64.shr' (Int64.repr ((Int64.signed x * m) / Int64.modulus)) (Int.repr p))\n                             (Int64.shru x (Int64.repr 63)).\nProof.\n  intros. set (n := Int64.signed x). set (d := Int64.signed y) in *.\n  exploit divls_mul_params_sound; eauto. intros (A & B & C).\n  split. auto. split. auto.\n  unfold Int64.divs. fold n; fold d. rewrite C by (apply Int64.signed_range).\n  rewrite two_p_is_exp by omega. rewrite <- Zdiv_Zdiv.\n  rewrite Int64.shru_lt_zero. unfold Int64.add. apply Int64.eqm_samerepr. apply Int64.eqm_add.\n  rewrite int64_shr'_div_two_p. apply Int64.eqm_unsigned_repr_r. apply Int64.eqm_refl2.\n  rewrite Int.unsigned_repr. f_equal.\n  rewrite Int64.signed_repr. rewrite Int64.modulus_power. f_equal. ring.\n  cut (Int64.min_signed <= n * m / Int64.modulus < Int64.half_modulus).\n  unfold Int64.max_signed; omega.\n  apply Zdiv_interval_1. generalize Int64.min_signed_neg; omega. apply Int64.half_modulus_pos.\n  apply Int64.modulus_pos.\n  split. apply Zle_trans with (Int64.min_signed * m). apply Zmult_le_compat_l_neg. omega. generalize Int64.min_signed_neg; omega.\n  apply Zmult_le_compat_r. unfold n; generalize (Int64.signed_range x); tauto. tauto.\n  apply Zle_lt_trans with (Int64.half_modulus * m).\n  apply Zmult_le_compat_r. generalize (Int64.signed_range x); unfold n, Int64.max_signed; omega. tauto.\n  apply Zmult_lt_compat_l. generalize Int64.half_modulus_pos; omega. tauto.\n  assert (64 < Int.max_unsigned) by (compute; auto). omega.\n  unfold Int64.lt; fold n. rewrite Int64.signed_zero. destruct (zlt n 0); apply Int64.eqm_unsigned_repr.\n  apply two_p_gt_ZERO. omega.\n  apply two_p_gt_ZERO. omega.\nQed.\n\nTheorem divls_mul_shift_1:\n  forall x y m p,\n  divls_mul_params (Int64.signed y) = Some(p, m) ->\n  m < Int64.half_modulus ->\n  0 <= p < 64 /\\\n  Int64.divs x y = Int64.add (Int64.shr' (Int64.mulhs x (Int64.repr m)) (Int.repr p))\n                             (Int64.shru' x (Int.repr 63)).\nProof.\n  intros. exploit divls_mul_shift_gen; eauto. instantiate (1 := x).\n  intros (A & B & C). split. auto. rewrite C.\n  unfold Int64.mulhs. rewrite Int64.signed_repr. auto.\n  generalize Int64.min_signed_neg; unfold Int64.max_signed; omega.\nQed.\n\nTheorem divls_mul_shift_2:\n  forall x y m p,\n  divls_mul_params (Int64.signed y) = Some(p, m) ->\n  m >= Int64.half_modulus ->\n  0 <= p < 64 /\\\n  Int64.divs x y = Int64.add (Int64.shr' (Int64.add (Int64.mulhs x (Int64.repr m)) x) (Int.repr p))\n                             (Int64.shru' x (Int.repr 63)).\nProof.\n  intros. exploit divls_mul_shift_gen; eauto. instantiate (1 := x).\n  intros (A & B & C). split. auto. rewrite C. f_equal. f_equal.\n  rewrite Int64.add_signed. unfold Int64.mulhs. set (n := Int64.signed x).\n  transitivity (Int64.repr (n * (m - Int64.modulus) / Int64.modulus + n)).\n  f_equal.\n  replace (n * (m - Int64.modulus)) with (n * m +  (-n) * Int64.modulus) by ring.\n  rewrite Z_div_plus. ring. apply Int64.modulus_pos.\n  apply Int64.eqm_samerepr. apply Int64.eqm_add; auto with ints.\n  apply Int64.eqm_sym. eapply Int64.eqm_trans. apply Int64.eqm_signed_unsigned.\n  apply Int64.eqm_unsigned_repr_l. apply Int64.eqm_refl2. f_equal. f_equal.\n  rewrite Int64.signed_repr_eq. rewrite Zmod_small by assumption.\n  apply zlt_false. omega.\nQed.\n\nRemark int64_shru'_div_two_p:\n  forall x y, Int64.shru' x y = Int64.repr (Int64.unsigned x / two_p (Int.unsigned y)).\nProof.\n  intros; unfold Int64.shru'. rewrite Int64.Zshiftr_div_two_p; auto. generalize (Int.unsigned_range y); omega.\nQed.\n\nTheorem divlu_mul_shift:\n  forall x y m p,\n  divlu_mul_params (Int64.unsigned y) = Some(p, m) ->\n  0 <= p < 64 /\\\n  Int64.divu x y = Int64.shru' (Int64.mulhu x (Int64.repr m)) (Int.repr p).\nProof.\n  intros. exploit divlu_mul_params_sound; eauto. intros (A & B & C).\n  split. auto.\n  rewrite int64_shru'_div_two_p. rewrite Int.unsigned_repr.\n  unfold Int64.divu, Int64.mulhu. f_equal. rewrite C by apply Int64.unsigned_range.\n  rewrite two_p_is_exp by omega. rewrite <- Zdiv_Zdiv by (apply two_p_gt_ZERO; omega).\n  f_equal. rewrite (Int64.unsigned_repr m).\n  rewrite Int64.unsigned_repr. f_equal. ring.\n  cut (0 <= Int64.unsigned x * m / Int64.modulus < Int64.modulus).\n  unfold Int64.max_unsigned; omega.\n  apply Zdiv_interval_1. omega. compute; auto. compute; auto.\n  split. simpl. apply Z.mul_nonneg_nonneg. generalize (Int64.unsigned_range x); omega. omega.\n  apply Zle_lt_trans with (Int64.modulus * m).\n  apply Zmult_le_compat_r. generalize (Int64.unsigned_range x); omega. omega.\n  apply Zmult_lt_compat_l. compute; auto. omega.\n  unfold Int64.max_unsigned; omega.\n  assert (64 < Int.max_unsigned) by (compute; auto). omega.\nQed.\n\n(** * Correctness of the smart constructors for division and modulus *)\n\nSection CMCONSTRS.\nContext mem `{external_calls: ExternalCalls mem} `{!I64HelpersCorrect mem}.\n\nVariable prog: program.\nVariable hf: helper_functions.\nHypothesis HELPERS: helper_functions_declared prog hf.\nLet ge := Genv.globalenv prog.\nVariable sp: val.\nVariable e: env.\nVariable m: mem.\n\nLemma is_intconst_sound:\n  forall v a n le,\n  is_intconst a = Some n -> eval_expr ge sp e m le a v -> v = Vint n.\nProof with (try discriminate).\n  intros. unfold is_intconst in *.\n  destruct a... destruct o... inv H. inv H0. destruct vl; inv H5. auto.\nQed.\n\nLemma eval_divu_mul:\n  forall le x y p M,\n  divu_mul_params (Int.unsigned y) = Some(p, M) ->\n  nth_error le O = Some (Vint x) ->\n  eval_expr ge sp e m le (divu_mul p M) (Vint (Int.divu x y)).\nProof.\n  intros. unfold divu_mul. exploit (divu_mul_shift x); eauto. intros [A B].\n  assert (C: eval_expr ge sp e m le (Eletvar 0) (Vint x)) by (apply eval_Eletvar; eauto).\n  assert (D: eval_expr ge sp e m le (Eop (Ointconst (Int.repr M)) Enil) (Vint (Int.repr M))) by EvalOp.\n  exploit eval_mulhu. eexact C. eexact D. intros (v & E & F). simpl in F. inv F. \n  exploit eval_shruimm. eexact E. instantiate (1 := Int.repr p).\n  intros [v [P Q]]. simpl in Q.\n  replace (Int.ltu (Int.repr p) Int.iwordsize) with true in Q.\n  inv Q. rewrite B. auto.\n  unfold Int.ltu. rewrite Int.unsigned_repr. rewrite zlt_true; auto. tauto.\n  assert (32 < Int.max_unsigned) by (compute; auto). omega.\nQed.\n\nTheorem eval_divuimm:\n  forall le e1 x n2 z,\n  eval_expr ge sp e m le e1 x ->\n  Val.divu x (Vint n2) = Some z ->\n  exists v, eval_expr ge sp e m le (divuimm e1 n2) v /\\ Val.lessdef z v.\nProof.\n  unfold divuimm; intros. generalize H0; intros DIV.\n  destruct x; simpl in DIV; try discriminate.\n  destruct (Int.eq n2 Int.zero) eqn:Z2; inv DIV.\n  destruct (Int.is_power2 n2) as [l | ] eqn:P2.\n- erewrite Int.divu_pow2 by eauto.\n  replace (Vint (Int.shru i l)) with (Val.shru (Vint i) (Vint l)).\n  apply eval_shruimm; auto.\n  simpl. erewrite Int.is_power2_range; eauto.\n- destruct (Compopts.optim_for_size tt).\n  + eapply eval_divu_base; eauto. EvalOp.\n  + destruct (divu_mul_params (Int.unsigned n2)) as [[p M] | ] eqn:PARAMS.\n    * exists (Vint (Int.divu i n2)); split; auto.\n      econstructor; eauto. eapply eval_divu_mul; eauto.\n    * eapply eval_divu_base; eauto. EvalOp.\nQed.\n\nTheorem eval_divu:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.divu x y = Some z ->\n  exists v, eval_expr ge sp e m le (divu a b) v /\\ Val.lessdef z v.\nProof.\n  unfold divu; intros.\n  destruct (is_intconst b) as [n2|] eqn:B.\n- exploit is_intconst_sound; eauto. intros EB; clear B.\n  destruct (is_intconst a) as [n1|] eqn:A.\n+ exploit is_intconst_sound; eauto. intros EA; clear A.\n  destruct (Int.eq n2 Int.zero) eqn:Z. eapply eval_divu_base; eauto. \n  subst. simpl in H1. rewrite Z in H1; inv H1.\n  TrivialExists.\n+ subst. eapply eval_divuimm; eauto.\n- eapply eval_divu_base; eauto.\nQed.\n\nLemma eval_mod_from_div:\n  forall le a n x y,\n  eval_expr ge sp e m le a (Vint y) ->\n  nth_error le O = Some (Vint x) ->\n  eval_expr ge sp e m le (mod_from_div a n) (Vint (Int.sub x (Int.mul y n))).\nProof.\n  unfold mod_from_div; intros.\n  exploit eval_mulimm; eauto. instantiate (1 := n). intros [v [A B]].\n  simpl in B. inv B. EvalOp.\nQed.\n\nTheorem eval_moduimm:\n  forall le e1 x n2 z,\n  eval_expr ge sp e m le e1 x ->\n  Val.modu x (Vint n2) = Some z ->\n  exists v, eval_expr ge sp e m le (moduimm e1 n2) v /\\ Val.lessdef z v.\nProof.\n  unfold moduimm; intros. generalize H0; intros MOD.\n  destruct x; simpl in MOD; try discriminate.\n  destruct (Int.eq n2 Int.zero) eqn:Z2; inv MOD.\n  destruct (Int.is_power2 n2) as [l | ] eqn:P2.\n- erewrite Int.modu_and by eauto.\n  change (Vint (Int.and i (Int.sub n2 Int.one)))\n    with (Val.and (Vint i) (Vint (Int.sub n2 Int.one))).\n  apply eval_andimm. auto.\n- destruct (Compopts.optim_for_size tt).\n  + eapply eval_modu_base; eauto. EvalOp.\n  + destruct (divu_mul_params (Int.unsigned n2)) as [[p M] | ] eqn:PARAMS.\n    * econstructor; split.\n      econstructor; eauto. eapply eval_mod_from_div.\n      eapply eval_divu_mul; eauto. simpl; eauto. simpl; eauto.\n      rewrite Int.modu_divu. auto.\n      red; intros; subst n2; discriminate.\n    * eapply eval_modu_base; eauto. EvalOp.\nQed.\n\nTheorem eval_modu:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.modu x y = Some z ->\n  exists v, eval_expr ge sp e m le (modu a b) v /\\ Val.lessdef z v.\nProof.\n  unfold modu; intros.\n  destruct (is_intconst b) as [n2|] eqn:B.\n- exploit is_intconst_sound; eauto. intros EB; clear B.\n  destruct (is_intconst a) as [n1|] eqn:A.\n+ exploit is_intconst_sound; eauto. intros EA; clear A.\n  destruct (Int.eq n2 Int.zero) eqn:Z. eapply eval_modu_base; eauto. \n  subst. simpl in H1. rewrite Z in H1; inv H1.\n  TrivialExists.\n+ subst. eapply eval_moduimm; eauto.\n- eapply eval_modu_base; eauto.\nQed.\n\nLemma eval_divs_mul:\n  forall le x y p M,\n  divs_mul_params (Int.signed y) = Some(p, M) ->\n  nth_error le O = Some (Vint x) ->\n  eval_expr ge sp e m le (divs_mul p M) (Vint (Int.divs x y)).\nProof.\n  intros. unfold divs_mul.\n  assert (C: eval_expr ge sp e m le (Eletvar 0) (Vint x)) by (apply eval_Eletvar; eauto).\n  assert (D: eval_expr ge sp e m le (Eop (Ointconst (Int.repr M)) Enil) (Vint (Int.repr M))) by EvalOp.\n  exploit eval_mulhs. eexact C. eexact D. intros (v & X & F). simpl in F; inv F.\n  exploit eval_shruimm. eexact C. instantiate (1 := Int.repr (Int.zwordsize - 1)).\n  intros [v1 [Y LD]]. simpl in LD.\n  change (Int.ltu (Int.repr 31) Int.iwordsize) with true in LD.\n  simpl in LD. inv LD.\n  assert (RANGE: 0 <= p < 32 -> Int.ltu (Int.repr p) Int.iwordsize = true).\n  { intros. unfold Int.ltu. rewrite Int.unsigned_repr. rewrite zlt_true by tauto. auto.\n    assert (32 < Int.max_unsigned) by (compute; auto). omega. }\n  destruct (zlt M Int.half_modulus).\n- exploit (divs_mul_shift_1 x); eauto. intros [A B].\n  exploit eval_shrimm. eexact X. instantiate (1 := Int.repr p). intros [v1 [Z LD]].\n  simpl in LD. rewrite RANGE in LD by auto. inv LD.\n  exploit eval_add. eexact Z. eexact Y. intros [v1 [W LD]].\n  simpl in LD. inv LD.\n  rewrite B. exact W.\n- exploit (divs_mul_shift_2 x); eauto. intros [A B].\n  exploit eval_add. eexact X. eexact C. intros [v1 [Z LD]].\n  simpl in LD. inv LD.\n  exploit eval_shrimm. eexact Z. instantiate (1 := Int.repr p). intros [v1 [U LD]].\n  simpl in LD. rewrite RANGE in LD by auto. inv LD.\n  exploit eval_add. eexact U. eexact Y. intros [v1 [W LD]].\n  simpl in LD. inv LD.\n  rewrite B. exact W.\nQed.\n\nTheorem eval_divsimm:\n  forall le e1 x n2 z,\n  eval_expr ge sp e m le e1 x ->\n  Val.divs x (Vint n2) = Some z ->\n  exists v, eval_expr ge sp e m le (divsimm e1 n2) v /\\ Val.lessdef z v.\nProof.\n  unfold divsimm; intros. generalize H0; intros DIV.\n  destruct x; simpl in DIV; try discriminate.\n  destruct (Int.eq n2 Int.zero\n            || Int.eq i (Int.repr Int.min_signed) && Int.eq n2 Int.mone) eqn:Z2; inv DIV.\n  destruct (Int.is_power2 n2) as [l | ] eqn:P2.\n- destruct (Int.ltu l (Int.repr 31)) eqn:LT31.\n  + eapply eval_shrximm; eauto. eapply Val.divs_pow2; eauto.\n  + eapply eval_divs_base; eauto. EvalOp.\n- destruct (Compopts.optim_for_size tt).\n  + eapply eval_divs_base; eauto. EvalOp.\n  + destruct (divs_mul_params (Int.signed n2)) as [[p M] | ] eqn:PARAMS.\n    * exists (Vint (Int.divs i n2)); split; auto.\n      econstructor; eauto. eapply eval_divs_mul; eauto.\n    * eapply eval_divs_base; eauto. EvalOp.\nQed.\n\nTheorem eval_divs:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.divs x y = Some z ->\n  exists v, eval_expr ge sp e m le (divs a b) v /\\ Val.lessdef z v.\nProof.\n  unfold divs; intros.\n  destruct (is_intconst b) as [n2|] eqn:B.\n- exploit is_intconst_sound; eauto. intros EB; clear B.\n  destruct (is_intconst a) as [n1|] eqn:A.\n+ exploit is_intconst_sound; eauto. intros EA; clear A.\n  destruct (Int.eq n2 Int.zero) eqn:Z. eapply eval_divs_base; eauto.\n  subst. simpl in H1. \n  destruct (Int.eq n2 Int.zero || Int.eq n1 (Int.repr Int.min_signed) && Int.eq n2 Int.mone); inv H1.\n  TrivialExists.\n+ subst. eapply eval_divsimm; eauto.\n- eapply eval_divs_base; eauto.\nQed.\n\nTheorem eval_modsimm:\n  forall le e1 x n2 z,\n  eval_expr ge sp e m le e1 x ->\n  Val.mods x (Vint n2) = Some z ->\n  exists v, eval_expr ge sp e m le (modsimm e1 n2) v /\\ Val.lessdef z v.\nProof.\n  unfold modsimm; intros.\n  exploit Val.mods_divs; eauto. intros [y [A B]].\n  generalize A; intros DIV.\n  destruct x; simpl in DIV; try discriminate.\n  destruct (Int.eq n2 Int.zero\n            || Int.eq i (Int.repr Int.min_signed) && Int.eq n2 Int.mone) eqn:Z2; inv DIV.\n  destruct (Int.is_power2 n2) as [l | ] eqn:P2.\n- destruct (Int.ltu l (Int.repr 31)) eqn:LT31.\n  + exploit (eval_shrximm ge sp e m (Vint i :: le) (Eletvar O)).\n    constructor. simpl; eauto. eapply Val.divs_pow2; eauto.\n    intros [v1 [X LD]]. inv LD.\n    econstructor; split. econstructor. eauto.\n    apply eval_mod_from_div. eexact X. simpl; eauto.\n    simpl. auto.\n  + eapply eval_mods_base; eauto. EvalOp.\n- destruct (Compopts.optim_for_size tt).\n  + eapply eval_mods_base; eauto. EvalOp.\n  + destruct (divs_mul_params (Int.signed n2)) as [[p M] | ] eqn:PARAMS.\n    * econstructor; split.\n      econstructor. eauto. apply eval_mod_from_div with (x := i); auto.\n      eapply eval_divs_mul with (x := i); eauto.\n      simpl. auto.\n    * eapply eval_mods_base; eauto. EvalOp.\nQed.\n\nTheorem eval_mods:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.mods x y = Some z ->\n  exists v, eval_expr ge sp e m le (mods a b) v /\\ Val.lessdef z v.\nProof.\n  unfold mods; intros.\n  destruct (is_intconst b) as [n2|] eqn:B.\n- exploit is_intconst_sound; eauto. intros EB; clear B.\n  destruct (is_intconst a) as [n1|] eqn:A.\n+ exploit is_intconst_sound; eauto. intros EA; clear A.\n  destruct (Int.eq n2 Int.zero) eqn:Z. eapply eval_mods_base; eauto.\n  subst. simpl in H1. \n  destruct (Int.eq n2 Int.zero || Int.eq n1 (Int.repr Int.min_signed) && Int.eq n2 Int.mone); inv H1.\n  TrivialExists.\n+ subst. eapply eval_modsimm; eauto.\n- eapply eval_mods_base; eauto.\nQed.\n\nLemma eval_modl_from_divl:\n  forall le a n x y,\n  eval_expr ge sp e m le a (Vlong y) ->\n  nth_error le O = Some (Vlong x) ->\n  eval_expr ge sp e m le (modl_from_divl a n) (Vlong (Int64.sub x (Int64.mul y n))).\nProof.\n  unfold modl_from_divl; intros.\n  exploit eval_mullimm; eauto. eauto. instantiate (1 := n). intros (v1 & A1 & B1).\n  assert (A0: eval_expr ge sp e m le (Eletvar O) (Vlong x)) by (constructor; auto).\n  exploit eval_subl ; auto ; try apply HELPERS. exact A0. exact A1.\n  intros (v2 & A2 & B2).\n  simpl in B1; inv B1. simpl in B2; inv B2. exact A2.\nQed.\n\nLemma eval_divlu_mull:\n  forall le x y p M,\n  divlu_mul_params (Int64.unsigned y) = Some(p, M) ->\n  nth_error le O = Some (Vlong x) ->\n  eval_expr ge sp e m le (divlu_mull p M) (Vlong (Int64.divu x y)).\nProof.\n  intros. unfold divlu_mull. exploit (divlu_mul_shift x); eauto. intros [A B].\n  assert (A0: eval_expr ge sp e m le (Eletvar O) (Vlong x)) by (constructor; auto).\n  exploit eval_mullhu. eauto. eexact A0. instantiate (1 := Int64.repr M). intros (v1 & A1 & B1).\n  exploit eval_shrluimm. eauto. eexact A1. instantiate (1 := Int.repr p). intros (v2 & A2 & B2).\n  simpl in B1; inv B1. simpl in B2. replace (Int.ltu (Int.repr p) Int64.iwordsize') with true in B2. inv B2.\n  rewrite B. assumption.\n  unfold Int.ltu. rewrite Int.unsigned_repr. rewrite zlt_true; auto. tauto.\n  assert (64 < Int.max_unsigned) by (compute; auto). omega.\nQed.\n\nTheorem eval_divlu:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.divlu x y = Some z ->\n  exists v, eval_expr ge sp e m le (divlu a b) v /\\ Val.lessdef z v.\nProof.\n  unfold divlu; intros.\n  destruct (is_longconst b) as [n2|] eqn:N2.\n- assert (y = Vlong n2) by (eapply is_longconst_sound; eauto). subst y.\n  destruct (is_longconst a) as [n1|] eqn:N1.\n+ assert (x = Vlong n1) by (eapply is_longconst_sound; eauto). subst x.\n  simpl in H1. destruct (Int64.eq n2 Int64.zero); inv H1.\n  econstructor; split. apply eval_longconst. constructor.\n+ destruct (Int64.is_power2' n2) as [l|] eqn:POW.\n* exploit Val.divlu_pow2; eauto. intros EQ; subst z. apply eval_shrluimm; auto.\n* destruct (Compopts.optim_for_size tt). eapply eval_divlu_base; eauto.\n  destruct (divlu_mul_params (Int64.unsigned n2)) as [[p M]|] eqn:PARAMS.\n** destruct x; simpl in H1; try discriminate.\n   destruct (Int64.eq n2 Int64.zero); inv H1.\n   econstructor; split; eauto. econstructor. eauto. eapply eval_divlu_mull; eauto.\n** eapply eval_divlu_base; eauto.\n- eapply eval_divlu_base; eauto.\nQed.\n\nTheorem eval_modlu:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.modlu x y = Some z ->\n  exists v, eval_expr ge sp e m le (modlu a b) v /\\ Val.lessdef z v.\nProof.\n  unfold modlu; intros.\n  destruct (is_longconst b) as [n2|] eqn:N2.\n- assert (y = Vlong n2) by (eapply is_longconst_sound; eauto). subst y.\n  destruct (is_longconst a) as [n1|] eqn:N1.\n+ assert (x = Vlong n1) by (eapply is_longconst_sound; eauto). subst x.\n  simpl in H1. destruct (Int64.eq n2 Int64.zero); inv H1.\n  econstructor; split. apply eval_longconst. constructor.\n+ destruct (Int64.is_power2 n2) as [l|] eqn:POW.\n* exploit Val.modlu_pow2; eauto. intros EQ; subst z. eapply eval_andl; eauto. apply eval_longconst.\n* destruct (Compopts.optim_for_size tt). eapply eval_modlu_base; eauto.\n  destruct (divlu_mul_params (Int64.unsigned n2)) as [[p M]|] eqn:PARAMS.\n** destruct x; simpl in H1; try discriminate.\n   destruct (Int64.eq n2 Int64.zero) eqn:Z; inv H1.\n   rewrite Int64.modu_divu.\n    econstructor; split; eauto. econstructor. eauto.\n    eapply eval_modl_from_divl; eauto.\n    eapply eval_divlu_mull; eauto.\n    red; intros; subst n2; discriminate Z.\n** eapply eval_modlu_base; eauto.\n- eapply eval_modlu_base; eauto.\nQed.\n\nLemma eval_divls_mull:\n  forall le x y p M,\n  divls_mul_params (Int64.signed y) = Some(p, M) ->\n  nth_error le O = Some (Vlong x) ->\n  eval_expr ge sp e m le (divls_mull p M) (Vlong (Int64.divs x y)).\nProof.\n  intros. unfold divls_mull.\n  assert (A0: eval_expr ge sp e m le (Eletvar O) (Vlong x)).\n  { constructor; auto. }\n  exploit eval_mullhs. eauto. eexact A0. instantiate (1 := Int64.repr M).  intros (v1 & A1 & B1).\n  exploit eval_addl; auto; try apply HELPERS. eexact A1. eexact A0. intros (v2 & A2 & B2).\n  exploit eval_shrluimm. eauto. eexact A0. instantiate (1 := Int.repr 63). intros (v3 & A3 & B3).\n  set (a4 := if zlt M Int64.half_modulus\n             then mullhs (Eletvar 0) (Int64.repr M)\n             else addl (mullhs (Eletvar 0) (Int64.repr M)) (Eletvar 0)).\n  set (v4 := if zlt M Int64.half_modulus then v1 else v2).\n  assert (A4: eval_expr ge sp e m le a4 v4).\n  { unfold a4, v4; destruct (zlt M Int64.half_modulus); auto. }\n  exploit eval_shrlimm. eauto. eexact A4. instantiate (1 := Int.repr p). intros (v5 & A5 & B5).\n  exploit eval_addl; auto; try apply HELPERS. eexact A5. eexact A3. intros (v6 & A6 & B6).\n  assert (RANGE: forall x, 0 <= x < 64 -> Int.ltu (Int.repr x) Int64.iwordsize' = true).\n  { intros. unfold Int.ltu. rewrite Int.unsigned_repr. rewrite zlt_true by tauto. auto.\n    assert (64 < Int.max_unsigned) by (compute; auto). omega. }\n  simpl in B1; inv B1.\n  simpl in B2; inv B2.\n  simpl in B3; rewrite RANGE in B3 by omega; inv B3.\n  destruct (zlt M Int64.half_modulus).\n- exploit (divls_mul_shift_1 x); eauto. intros [A B].\n  simpl in B5; rewrite RANGE in B5 by auto; inv B5.\n  simpl in B6; inv B6.\n  rewrite B; exact A6.\n- exploit (divls_mul_shift_2 x); eauto. intros [A B].\n  simpl in B5; rewrite RANGE in B5 by auto; inv B5.\n  simpl in B6; inv B6.\n  rewrite B; exact A6.\nQed.\n\nTheorem eval_divls:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.divls x y = Some z ->\n  exists v, eval_expr ge sp e m le (divls a b) v /\\ Val.lessdef z v.\nProof.\n  unfold divls; intros.\n  destruct (is_longconst b) as [n2|] eqn:N2.\n- assert (y = Vlong n2) by (eapply is_longconst_sound; eauto). subst y.\n  destruct (is_longconst a) as [n1|] eqn:N1.\n+ assert (x = Vlong n1) by (eapply is_longconst_sound; eauto). subst x.\n  simpl in H1.\n  destruct (Int64.eq n2 Int64.zero\n         || Int64.eq n1 (Int64.repr Int64.min_signed) && Int64.eq n2 Int64.mone); inv H1.\n  econstructor; split. apply eval_longconst. constructor.\n+ destruct (Int64.is_power2' n2) as [l|] eqn:POW.\n* destruct (Int.ltu l (Int.repr 63)) eqn:LT.\n** exploit Val.divls_pow2; eauto. intros EQ. eapply eval_shrxlimm; eauto.\n** eapply eval_divls_base; eauto.\n* destruct (Compopts.optim_for_size tt). eapply eval_divls_base; eauto.\n  destruct (divls_mul_params (Int64.signed n2)) as [[p M]|] eqn:PARAMS.\n** destruct x; simpl in H1; try discriminate.\n   destruct (Int64.eq n2 Int64.zero\n             || Int64.eq i (Int64.repr Int64.min_signed) && Int64.eq n2 Int64.mone); inv H1.\n   econstructor; split; eauto. econstructor. eauto.\n   eapply eval_divls_mull; eauto.\n** eapply eval_divls_base; eauto.\n- eapply eval_divls_base; eauto.\nQed.\n\nTheorem eval_modls:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.modls x y = Some z ->\n  exists v, eval_expr ge sp e m le (modls a b) v /\\ Val.lessdef z v.\nProof.\n  unfold modls; intros.\n  destruct (is_longconst b) as [n2|] eqn:N2.\n- assert (y = Vlong n2) by (eapply is_longconst_sound; eauto). subst y.\n  destruct (is_longconst a) as [n1|] eqn:N1.\n+ assert (x = Vlong n1) by (eapply is_longconst_sound; eauto). subst x.\n  simpl in H1.\n  destruct (Int64.eq n2 Int64.zero\n         || Int64.eq n1 (Int64.repr Int64.min_signed) && Int64.eq n2 Int64.mone); inv H1.\n  econstructor; split. apply eval_longconst. constructor.\n+ destruct (Int64.is_power2' n2) as [l|] eqn:POW.\n* destruct (Int.ltu l (Int.repr 63)) eqn:LT.\n**destruct x; simpl in H1; try discriminate.\n  destruct (Int64.eq n2 Int64.zero\n         || Int64.eq i (Int64.repr Int64.min_signed) && Int64.eq n2 Int64.mone) eqn:D; inv H1.\n  assert (Val.divls (Vlong i) (Vlong n2) = Some (Vlong (Int64.divs i n2))).\n  { simpl; rewrite D; auto. }\n  exploit Val.divls_pow2; eauto. intros EQ.\n  set (le' := Vlong i :: le).\n  assert (A: eval_expr ge sp e m le' (Eletvar O) (Vlong i)) by (constructor; auto).\n  exploit eval_shrxlimm; eauto. intros (v1 & A1 & B1). inv B1.\n  econstructor; split.\n  econstructor. eauto. eapply eval_modl_from_divl. eexact A1. reflexivity.\n  rewrite Int64.mods_divs. auto.\n**eapply eval_modls_base; eauto.\n* destruct (Compopts.optim_for_size tt). eapply eval_modls_base; eauto.\n  destruct (divls_mul_params (Int64.signed n2)) as [[p M]|] eqn:PARAMS.\n** destruct x; simpl in H1; try discriminate.\n   destruct (Int64.eq n2 Int64.zero\n             || Int64.eq i (Int64.repr Int64.min_signed) && Int64.eq n2 Int64.mone); inv H1.\n   econstructor; split; eauto. econstructor. eauto.\n   rewrite Int64.mods_divs.\n   eapply eval_modl_from_divl; auto.\n   eapply eval_divls_mull; eauto.\n** eapply eval_modls_base; eauto.\n- eapply eval_modls_base; eauto.\nQed.\n\n(** * Floating-point division *)\n\nTheorem eval_divf:\n  forall le a b x y,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  exists v, eval_expr ge sp e m le (divf a b) v /\\ Val.lessdef (Val.divf x y) v.\nProof.\n  intros until y. unfold divf. destruct (divf_match b); intros.\n- unfold divfimm. destruct (Float.exact_inverse n2) as [n2' | ] eqn:EINV.\n  + inv H0. inv H4. simpl in H6. inv H6. econstructor; split.\n    EvalOp. constructor. eauto. constructor. EvalOp. simpl; eauto. constructor.\n    simpl; eauto.\n    destruct x; simpl; auto. erewrite Float.div_mul_inverse; eauto.\n  + TrivialExists.\n- TrivialExists.\nQed.\n\nTheorem eval_divfs:\n  forall le a b x y,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  exists v, eval_expr ge sp e m le (divfs a b) v /\\ Val.lessdef (Val.divfs x y) v.\nProof.\n  intros until y. unfold divfs. destruct (divfs_match b); intros.\n- unfold divfsimm. destruct (Float32.exact_inverse n2) as [n2' | ] eqn:EINV.\n  + inv H0. inv H4. simpl in H6. inv H6. econstructor; split.\n    EvalOp. constructor. eauto. constructor. EvalOp. simpl; eauto. constructor.\n    simpl; eauto.\n    destruct x; simpl; auto. erewrite Float32.div_mul_inverse; eauto.\n  + TrivialExists.\n- TrivialExists.\nQed.\n\nEnd CMCONSTRS.\n", "meta": {"author": "CertiKOS", "repo": "compcert.old", "sha": "1fbd4e9beeb9e58b15f7f20ab1c949f6381a4105", "save_path": "github-repos/coq/CertiKOS-compcert.old", "path": "github-repos/coq/CertiKOS-compcert.old/compcert.old-1fbd4e9beeb9e58b15f7f20ab1c949f6381a4105/backend/SelectDivproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6528460118105204}}
{"text": "Require Export B9_Inegalite_Triang.\n\nSection METRIC_BASICS.\n\nDefinition LS0 := Distance Oo Oo.\n\nLemma NullDist : forall A, \n\tDistance A A = LS0.\nProof.\n\tintro; unfold LS0 in |- *; apply DistAA.\nQed.\n\nLemma NullLSlt : forall A B : Point, \n\tA <> B -> LSlt LS0 (Distance A B).\nProof.\n\tintros; rewrite <- (NullDist A).\n\tapply OrderLSlt; auto.\n\tcanonize.\n\telim (NotClockwiseAAB _ _ H0).\nQed.\n\nLemma EquiOrientedNotEquiOriented : forall A B C D : Point,\n\tA <> B ->\n\tEquiOriented A B C D ->\n\t~EquiOriented A B D C.\nProof.\n\tcanonize.\n\tdestruct (ClockwiseExists A B H) as (E, H2).\n\telim (ClockwiseNotClockwise C D E); auto.\nQed.\n\nLemma LSltDistinct : forall A B C D, \n\tLSlt (Distance A B) (Distance C D) -> C <> D.\nProof.\n\tred in |- *; intros; subst.\n\trewrite (DistAA D A) in H.\n\tdestruct (LSltOrder A B A).\n\t right; canonize.\n\t   elim (NotClockwiseAAB A x); auto.\n\t trivial.\n\t elim (EquiOrientedNotEquiOriented A B B A (sym_not_eq H1) H0).\n\t   canonize.\nQed.\n\nLemma LSltNull : forall A B, \n\tLSlt LS0 (Distance A B) -> A <> B.\nProof.\n\tred in |- *; intros; subst.\n\trewrite <- (NullDist B) in H.\n\tdestruct (LSltOrder B B B).\n\t canonize.\n\t trivial.\n\t auto.\nQed.\n\nLemma NotLSltNullNull : ~LSlt LS0 LS0.\nProof.\n\tchange (~ LSlt LS0 (Distance Oo Oo)) in |- *.\n\tintro.\n\telim (LSltNull _ _ H).\n\ttrivial.\nQed.\n\nLemma LS0NeutralRight : forall A B : Point,\n\tLSplus (Distance A B) LS0 = Distance A B.\nProof.\n\tintros.\n\trewrite <- (NullDist B); rewrite Chasles; canonize.\n\telim (NotClockwiseAAB B x); trivial.\nQed.\n\nLemma LS0NeutralLeft : forall A B : Point,\n\tLSplus LS0 (Distance A B) = Distance A B.\nProof.\n\tintros.\n\trewrite <- (NullDist A); rewrite Chasles; canonize.\n\telim (NotClockwiseAAB A x); trivial.\nQed.\n\nLemma EquiOrientedNotEquiOrientedABC : forall A B C : Point,\n\tA <> B ->\n\tEquiOriented A B B C ->\n\t~EquiOriented A C C B.\nProof.\n\tcanonize.\n\tdestruct (ClockwiseExists A B H) as (E, H2).\n\tdecompose [or] (FourCases A B C).\n\t elim (NotClockwiseBAA C B); auto.\n\t elim (NotClockwiseBAA B C); apply H1; apply ClockwiseBCA; trivial.\n\t canonize.\n\t   elim (ClockwiseNotClockwise B C E); auto.\n\t generalizeChangeSense.\n\t   elim (ClockwiseNotClockwise B C E); auto.\nQed.\n\nLemma HalfLineAntisymLSlt  : forall A B C : Point,\n\tA <> B ->\n\tHalfLine A B C ->\n\tLSlt (Distance A B) (Distance A C) ->\n\t~LSlt (Distance A C) (Distance A B).\nProof.\n\tred in |- *; intros.\n\tassert (H3 : HalfLine A B C \\/ HalfLine A C B).\n\t intuition.\n\t destruct (LSltOrder _ _ _ H3 H1).\n\t   elim (EquiOrientedNotEquiOrientedABC _ _ _ H H4).\n\t   assert (EquiOriented A C C B /\\ C <> B).\n\t  apply LSltOrder.\n\t   generalizeChange.\n\t   trivial.\n\t  intuition.\nQed.\n\nLemma AntisymLSlt  : forall A B C : Point,\n\tA <> B ->\n\tLSlt (Distance A B) (Distance A C) ->\n\t~LSlt (Distance A C) (Distance A B).\nProof.\n\tintros.\n\tassert (H1 := LSltDistinct _ _ _ _ H0).\n\tdestruct (ExistsHalfLineEquidistant A B A C H H1) as (D, (H2, H3)).\n\trewrite <- H3; rewrite <- H3 in H0.\n\tapply HalfLineAntisymLSlt; auto.\nQed.\n\nLemma ClockwiseNotNullSide : forall A B C : Point,\n\tClockwise A B C ->\n\t~Distance B C = LS0.\nProof.\n\tred in |- *; intros.\n\tassert (H1 := TriangularIneq _ _ _ H).\n\trewrite H0 in H1; rewrite LS0NeutralRight in H1.\n\telim (AntisymLSlt A C B).\n\t apply sym_not_eq; apply (ClockwiseDistinctCA _ _ _ H).\n\t trivial.\n\t assert (H2 := TriangularIneq _ _ _ (ClockwiseBCA _ _ _ H)).\n\t   rewrite H0 in H2; rewrite LS0NeutralLeft in H2.\n\t   rewrite (DistSym A B); rewrite (DistSym A C); trivial.\nQed.\n\nLemma DistDistinctNull : forall A B D : Point, \n\tDistance A B = LS0 -> \n\tD <> A ->\n\tA = B.\nProof.\n\tintros.\n\tdecompose [or] (FourCases D A B).\n\t elim (ClockwiseNotNullSide _ _ _ H1); trivial.\n\t elim (ClockwiseNotNullSide _ _ _ (ClockwiseBCA _ _ _ H2)); rewrite DistSym;\n\t  trivial.\n\t decompose [or] (FourCases B A D).\n\t  elim (ClockwiseNotNullSide _ _ _ (ClockwiseCAB _ _ _ H2)); rewrite DistSym;\n\t   trivial.\n\t  elim (ClockwiseNotNullSide _ _ _ (ClockwiseCAB _ _ _ H3)); trivial.\n\t  apply (HalfLineEquidistantEqual D A B H0 H1).\n\t    rewrite <- (Chasles D A B H1 H2).\n\t    rewrite H; rewrite LS0NeutralRight; trivial.\n\t  assert (H3 : HalfLine D B A).\n\t   generalizeChange.\n\t   assert (H4 : D <> B).\n\t    canonize; subst.\n\t      destruct (ClockwiseExists B A H0) as (C, H4).\n\t      elim (NotClockwiseAAB B C); auto.\n\t    apply sym_eq; apply (HalfLineEquidistantEqual D B A H4 H3).\n\t      rewrite <- (Chasles D B A H3 H2).\n\t      rewrite (DistSym B A); rewrite H; rewrite LS0NeutralRight; trivial.\n\t assert (H2 : A <> B).\n\t  intro; subst; canonize.\n\t    destruct (ClockwiseExists B D (sym_not_eq H0)) as (C, H2).\n\t    elim (NotClockwiseAAB B C); auto.\n\t  elim NotLSltNullNull.\n\t    pattern LS0 at 2 in |- *; rewrite <- H.\n\t    apply NullLSlt; trivial.\nQed.\n\nLemma DistNull : forall A B, \n\tDistance A B = LS0 -> A = B.\nProof.\n\tintros; destruct (Apart Oo Uu A DistinctOoUu).\n\t apply (DistDistinctNull A B Oo); auto.\n\t apply (DistDistinctNull A B Uu); auto.\nQed.\n\nLemma EquiDistantDistinct : forall A B C D : Point,\n\tA <> B ->\n\tDistance A B = Distance C D ->\n\tC <> D.\nProof.\n\tintuition; subst.\n\telim H; apply DistNull.\n\trewrite H0; apply NullDist.\nQed.\n\nLemma BetweenLSlt : forall A B C, \n\t(Between A B C) -> \n\tLSlt (Distance A B) (Distance A C).\nProof.\n\tintros.\n\tapply OrderLSlt; canonize.\n\tdestruct (ClockwiseExists A B H1) as (D, H3).\n\telim (ClockwiseDistinctAB B C D); auto.\nQed.\n\nLemma LSltBetween : forall A B C, \n\tA <> B ->\n\tHalfLine A B C ->\n\tLSlt (Distance A B) (Distance A C) ->\n\t(Between A B C).\nProof.\n\tintros.\n\tassert (H2 : EquiOriented A B B C /\\ B <> C).\n\t apply (LSltOrder A B C); intuition.\n\t canonize.\nQed.\n\nLemma DistDistinct : forall A B, \n\tDistance A B <> LS0 -> A <> B.\nProof.\n\tintuition.\n\tsubst; elim H; apply NullDist.\nQed.\n\nLemma DistinctDist : forall A B, \n\tA <> B -> Distance A B <> LS0.\nProof.\n\tintuition.\n\telim H; apply DistNull; auto.\nQed.\n\nEnd METRIC_BASICS.\n\nSection METRIC_PROPERTIES.\n\nLemma ChaslesComm : forall A B C : Point,\n\tHalfLine A B C ->\n\tHalfLine C B A -> \n\tLSplus (Distance A B) (Distance B C) = LSplus (Distance B C) (Distance A B).\nProof.\n\tintros A B C H H0.\n\trewrite (Chasles A B C H H0).\n\trewrite (DistSym B C); rewrite (DistSym A B); rewrite (Chasles C B A H0 H).\n\tapply DistSym.\nQed.\n\nLemma ChaslesAssoc : forall A B C D : Point,\n\tHalfLine A B C ->\n\tHalfLine C B A -> \n\tHalfLine A B D ->\n\tHalfLine D B A -> \n\tHalfLine B C D ->\n\tHalfLine D C B -> \n\tHalfLine A C D ->\n\tHalfLine D C A -> \n\tLSplus (Distance A B) (LSplus (Distance B C) (Distance C D)) = \n\t\tLSplus (LSplus (Distance A B) (Distance B C)) (Distance C D).\nProof.\n\tintros.\n\trepeat (rewrite Chasles; auto).\nQed.\n\nLemma SSSEqualBD : forall A B C D : Point,\n\tClockwise A B C ->\n\tClockwise A D C ->\n\tDistance A B = Distance A D ->\n\tDistance B C = Distance D C ->\n\tB = D.\nProof.\n\tintros.\n\tassert (Hab := ClockwiseDistinctAB A B C H).\n\tassert (Hbc := ClockwiseDistinctBC A B C H).\n\tsetCircle A A B Hab ipattern:(G1) ipattern:(Aab).\n\tsetCircle C B C Hbc ipattern:(G2) ipattern:(Cbc).\n\tsetCinterantiC G1 G2 Aab Cbc ipattern:(E) ipattern:(H3) ipattern:(H4) ipattern:(H5)\n\t ipattern:(H6).\n\t rewrite (DistSym A C); apply ClockwiseTriangleSpec; apply ClockwiseCAB; auto.\n\t rewrite <- (H6 B).\n\t  apply H6.\n\t    intuition.\n\t   rewrite (DistSym C D); auto.\n\t   apply ClockwiseCAB; auto.\n\t  intuition.\n\t   rewrite (DistSym C B); auto.\n\t   apply ClockwiseCAB; auto.\nQed.\n\nLemma SSSEqualCD : forall A B C D : Point,\n\tClockwise A B C ->\n\tClockwise A B D ->\n\tDistance A C = Distance A D ->\n\tDistance B C = Distance B D ->\n\tC = D.\nProof.\n\tintros.\n\tassert (Hac := sym_not_eq (ClockwiseDistinctCA A B C H)).\n\tassert (Hbc := ClockwiseDistinctBC A B C H).\n\tsetCircle A A C Hac ipattern:(G1) ipattern:(Aac).\n\tsetCircle B B C Hbc ipattern:(G2) ipattern:(Bbc).\n\tsetCinterantiC G2 G1 Bbc Aac ipattern:(E) ipattern:(H3) ipattern:(H4) ipattern:(H5)\n\t ipattern:(H6).\n\t rewrite (DistSym B A); rewrite (DistSym A C); apply ClockwiseTriangleSpec;\n\t  auto.\n\t rewrite <- (H6 C).\n\t  apply H6.\n\t    intuition.\n\t  intuition.\nQed.\n\nEnd METRIC_PROPERTIES.\n", "meta": {"author": "coq-contribs", "repo": "ruler-compass-geometry", "sha": "ee36f5cd523abaa2e0b676c4100c02ec496c0bfd", "save_path": "github-repos/coq/coq-contribs-ruler-compass-geometry", "path": "github-repos/coq/coq-contribs-ruler-compass-geometry/ruler-compass-geometry-ee36f5cd523abaa2e0b676c4100c02ec496c0bfd/B10_Longueur_Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6528460048357683}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nFrom compcert Require Import Coqlib.\nRequire Import Zwf.\nRequire Coq.Program.Wf.\nRequire Import Recdef.\n\nDefinition interv : Type := (Z * Z)%type.\n\n\n\nDefinition In (x: Z) (i: interv) : Prop := fst i <= x < snd i.\n\nLemma In_dec:\nforall x i, {In x i} + {~In x i}.\nProof. hammer_hook \"Intv\" \"Intv.In_dec\".\nunfold In; intros.\ncase (zle (fst i) x); intros.\ncase (zlt x (snd i)); intros.\nleft; auto.\nright; intuition.\nright; intuition.\nQed.\n\nLemma notin_range:\nforall x i,\nx < fst i \\/ x >= snd i -> ~In x i.\nProof. hammer_hook \"Intv\" \"Intv.notin_range\".\nunfold In; intros; omega.\nQed.\n\nLemma range_notin:\nforall x i,\n~In x i -> fst i < snd i -> x < fst i \\/ x >= snd i.\nProof. hammer_hook \"Intv\" \"Intv.range_notin\".\nunfold In; intros; omega.\nQed.\n\n\n\nDefinition empty (i: interv) : Prop := fst i >= snd i.\n\nLemma empty_dec:\nforall i, {empty i} + {~empty i}.\nProof. hammer_hook \"Intv\" \"Intv.empty_dec\".\nunfold empty; intros.\ncase (zle (snd i) (fst i)); intros.\nleft; omega.\nright; omega.\nQed.\n\nLemma is_notempty:\nforall i, fst i < snd i -> ~empty i.\nProof. hammer_hook \"Intv\" \"Intv.is_notempty\".\nunfold empty; intros; omega.\nQed.\n\nLemma empty_notin:\nforall x i, empty i -> ~In x i.\nProof. hammer_hook \"Intv\" \"Intv.empty_notin\".\nunfold empty, In; intros. omega.\nQed.\n\nLemma in_notempty:\nforall x i, In x i -> ~empty i.\nProof. hammer_hook \"Intv\" \"Intv.in_notempty\".\nunfold empty, In; intros. omega.\nQed.\n\n\n\nDefinition disjoint (i j: interv) : Prop :=\nforall x, In x i -> ~In x j.\n\nLemma disjoint_sym:\nforall i j, disjoint i j -> disjoint j i.\nProof. hammer_hook \"Intv\" \"Intv.disjoint_sym\".\nunfold disjoint; intros; red; intros. elim (H x); auto.\nQed.\n\nLemma empty_disjoint_r:\nforall i j, empty j -> disjoint i j.\nProof. hammer_hook \"Intv\" \"Intv.empty_disjoint_r\".\nunfold disjoint; intros. apply empty_notin; auto.\nQed.\n\nLemma empty_disjoint_l:\nforall i j, empty i -> disjoint i j.\nProof. hammer_hook \"Intv\" \"Intv.empty_disjoint_l\".\nintros. apply disjoint_sym. apply empty_disjoint_r; auto.\nQed.\n\nLemma disjoint_range:\nforall i j,\nsnd i <= fst j \\/ snd j <= fst i -> disjoint i j.\nProof. hammer_hook \"Intv\" \"Intv.disjoint_range\".\nunfold disjoint, In; intros. omega.\nQed.\n\nLemma range_disjoint:\nforall i j,\ndisjoint i j ->\nempty i \\/ empty j \\/ snd i <= fst j \\/ snd j <= fst i.\nProof. hammer_hook \"Intv\" \"Intv.range_disjoint\".\nunfold disjoint, empty; intros.\ndestruct (zlt (fst i) (snd i)); auto.\ndestruct (zlt (fst j) (snd j)); auto.\nright; right.\ndestruct (zlt (fst i) (fst j)).\n\ndestruct (zle (snd i) (fst j)).\n\nauto.\n\nelim (H (fst j)). red; omega. red; omega.\n\ndestruct (zle (snd j) (fst i)).\n\nauto.\n\nelim (H (fst i)). red; omega. red; omega.\nQed.\n\nLemma range_disjoint':\nforall i j,\ndisjoint i j -> fst i < snd i -> fst j < snd j ->\nsnd i <= fst j \\/ snd j <= fst i.\nProof. hammer_hook \"Intv\" \"Intv.range_disjoint'\".\nintros. exploit range_disjoint; eauto. unfold empty; intuition omega.\nQed.\n\nLemma disjoint_dec:\nforall i j, {disjoint i j} + {~disjoint i j}.\nProof. hammer_hook \"Intv\" \"Intv.disjoint_dec\".\nintros.\ndestruct (empty_dec i). left; apply empty_disjoint_l; auto.\ndestruct (empty_dec j). left; apply empty_disjoint_r; auto.\ndestruct (zle (snd i) (fst j)). left; apply disjoint_range; auto.\ndestruct (zle (snd j) (fst i)). left; apply disjoint_range; auto.\nright; red; intro. exploit range_disjoint; eauto. intuition.\nQed.\n\n\n\nDefinition shift (i: interv) (delta: Z) : interv := (fst i + delta, snd i + delta).\n\nLemma in_shift:\nforall x i delta,\nIn x i -> In (x + delta) (shift i delta).\nProof. hammer_hook \"Intv\" \"Intv.in_shift\".\nunfold shift, In; intros. simpl. omega.\nQed.\n\nLemma in_shift_inv:\nforall x i delta,\nIn x (shift i delta) -> In (x - delta) i.\nProof. hammer_hook \"Intv\" \"Intv.in_shift_inv\".\nunfold shift, In; simpl; intros. omega.\nQed.\n\n\n\nSection ELEMENTS.\n\nVariable lo: Z.\n\nFunction elements_rec (hi: Z) {wf (Zwf lo) hi} : list Z :=\nif zlt lo hi then (hi-1) :: elements_rec (hi-1) else nil.\nProof.\nintros. red. omega.\napply Zwf_well_founded.\nQed.\n\nLemma In_elements_rec:\nforall hi x,\nList.In x (elements_rec hi) <-> lo <= x < hi.\nProof. hammer_hook \"Intv\" \"Intv.In_elements_rec\".\nintros. functional induction (elements_rec hi).\nsimpl; split; intros.\ndestruct H. clear IHl. omega. rewrite IHl in H. clear IHl. omega.\ndestruct (zeq (hi - 1) x); auto. right. rewrite IHl. clear IHl. omega.\nsimpl; intuition.\nQed.\n\nEnd ELEMENTS.\n\nDefinition elements (i: interv) : list Z :=\nelements_rec (fst i) (snd i).\n\nLemma in_elements:\nforall x i,\nIn x i -> List.In x (elements i).\nProof. hammer_hook \"Intv\" \"Intv.in_elements\".\nintros. unfold elements. rewrite In_elements_rec. auto.\nQed.\n\nLemma elements_in:\nforall x i,\nList.In x (elements i) -> In x i.\nProof. hammer_hook \"Intv\" \"Intv.elements_in\".\nunfold elements; intros.\nrewrite In_elements_rec in H. auto.\nQed.\n\n\n\nSection FORALL.\n\nVariables P Q: Z -> Prop.\nVariable f: forall (x: Z), {P x} + {Q x}.\nVariable lo: Z.\n\nProgram Fixpoint forall_rec (hi: Z) {wf (Zwf lo) hi}:\n{forall x, lo <= x < hi -> P x}\n+ {exists x, lo <= x < hi /\\ Q x} :=\nif zlt lo hi then\nmatch f (hi - 1) with\n| left _ =>\nmatch forall_rec (hi - 1) with\n| left _ => left _ _\n| right _ => right _ _\nend\n| right _ => right _ _\nend\nelse\nleft _ _\n.\nNext Obligation.\nred. omega.\nQed.\nNext Obligation.\nassert (x = hi - 1 \\/ x < hi - 1) by omega.\ndestruct H2. congruence. auto.\nQed.\nNext Obligation.\nexists wildcard'; split; auto. omega.\nQed.\nNext Obligation.\nexists (hi - 1); split; auto. omega.\nQed.\nNext Obligation.\nomegaContradiction.\nDefined.\n\nEnd FORALL.\n\nDefinition forall_dec\n(P Q: Z -> Prop) (f: forall (x: Z), {P x} + {Q x}) (i: interv) :\n{forall x, In x i -> P x} + {exists x, In x i /\\ Q x} :=\nforall_rec P Q f (fst i) (snd i).\n\n\n\nSection FOLD.\n\nVariable A: Type.\nVariable f: Z -> A -> A.\nVariable lo: Z.\nVariable a: A.\n\nFunction fold_rec (hi: Z) {wf (Zwf lo) hi} : A :=\nif zlt lo hi then f (hi - 1) (fold_rec (hi - 1)) else a.\nProof. hammer_hook \"Intv\" \"Intv.forall_dec\".\nintros. red. omega.\napply Zwf_well_founded.\nQed.\n\nLemma fold_rec_elements:\nforall hi, fold_rec hi = List.fold_right f a (elements_rec lo hi).\nProof. hammer_hook \"Intv\" \"Intv.fold_rec_elements\".\nintros. functional induction (fold_rec hi).\nrewrite elements_rec_equation. rewrite zlt_true; auto.\nsimpl. congruence.\nrewrite elements_rec_equation. rewrite zlt_false; auto.\nQed.\n\nEnd FOLD.\n\nDefinition fold {A: Type} (f: Z -> A -> A) (a: A) (i: interv) : A :=\nfold_rec A f (fst i) a (snd i).\n\nLemma fold_elements:\nforall (A: Type) (f: Z -> A -> A) a i,\nfold f a i = List.fold_right f a (elements i).\nProof. hammer_hook \"Intv\" \"Intv.fold_elements\".\nintros. unfold fold, elements. apply fold_rec_elements.\nQed.\n\n\n\nHint Resolve\nnotin_range range_notin\nis_notempty empty_notin in_notempty\ndisjoint_sym empty_disjoint_r empty_disjoint_l\ndisjoint_range\nin_shift in_shift_inv\nin_elements elements_in : intv.\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/compcert/Intv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6527501268841831}}
{"text": "\n(* La librairie strandard est décrite ici\n\n   https://coq.inria.fr/distrib/current/stdlib/\n\n*)\n\nRequire Import List.  (* https://coq.inria.fr/distrib/current/stdlib/Coq.Lists.List.html *)\nRequire Import Arith. (* https://coq.inria.fr/distrib/current/stdlib/Coq.Arith.Arith_base.html *)\n\nLoad perm.\n\nSection list_incl.\n\n  Variable (X : Type).\n  \n  Implicit Types (l m : list X).\n\n  Print In.\n  Print incl.\n  \n  Fact incl_left_cons l m x : incl (x::m) l -> In x l /\\ incl m l.\n  Proof.\n    intros H.\n    split.\n    apply H.\n    left.\n    reflexivity.\n    intros ? ?.\n    apply H.\n    right.\n    assumption.\n  Qed.\n \n  Fact incl_left_app l m k : incl (l++m) k <-> incl l k /\\ incl m k.\n  Proof.\n    split. (* Divise en deux sous buts *)\n    intro H.\n    split. (* Divise en deux sous buts *)\n    intros H2 H3.\n    apply H. (* Permet de remplacer k par (l ++ m *)\n    apply in_or_app.\n    left.\n    apply H3. (* Premier sous but résolu *)\n    intros H4 H5.\n    apply H. (*Permet de remplacer k par (l ++m) *)\n    apply in_or_app.\n    right. (* Permet d'appliquer H5 par la suite *)\n    apply H5.\n    intro H1.\n    destruct H1. (* Dans le but de trouver une forme pour appliquer incl_app *)\n    revert H0.\n    revert H.\n    apply incl_app.\n  Qed.\n  \n  Fact incl_right_nil l : incl l nil -> l = nil.\n  Proof.\n    intros H.\n    destruct l as [ | x l ].\n    reflexivity. (* Pour enlever le premier sous but *)\n    apply incl_left_cons in H.\n    destruct H as (H1 & H2).\n    destruct H1. (*Afin de résoudre la preuve *)\n  Qed.\n\n  Let incl_nil_x l : incl nil l.\n  Proof.\n    intros ? [].\n  Qed.\n \n\n  Fact incl_right_app l m p : incl m (l++p) -> exists m1 m2, m ~p m1++m2 /\\ incl m1 l /\\ incl m2 p.\n  Proof.\n    \n    induction m as [ | x m IHm ].\n\n    exists nil, nil; simpl; repeat split.\n    apply perm_nil.\n    apply incl_nil_x.\n    apply incl_nil_x.\n\n\n    intros H.\n    apply incl_left_cons in H. \n    destruct H as (H1 & H2).    \n    apply IHm in H2.\n    destruct H2 as (m1 & m2 & H3 & H4 & H5).\n    destruct IHm.\n\n\n    apply perm_incl in H3.\n    apply incl_appl with(m:=p) in H4.\n    apply incl_appr with(m:=l) in H5.\n    apply incl_app with(l:=m1) (m:=m2) (n:=l++p) in H4.\n    apply incl_tran with(l:=m) in H4.\n    apply H4.\n    apply H3.\n    apply H5.\n\n    destruct H.\n    destruct H.\n    destruct H0.\n\n    apply in_app_or in H1.\n    destruct H1.\n    \n    exists (x::x0).\n    exists (x1).\n    split.\n    apply perm_cons with(x:=x) in H.\n    apply H.\n    split.\n\n  apply incl_cons with(a:=x) in H0.\n    apply H0.\n    apply H1.\n    apply H2.\n    \n\n    exists (x0).\n    exists (x::x1).\n    split.\n    apply perm_cons with(x:=x) in H.\n    apply perm_trans with(l2:=(x::x0++x1)) (l3:= (x0++x::x1)) in H.\n    apply H.\n    apply perm_middle.\n    split.\n    apply H0.\n    apply incl_cons with(a:=x) in H2.\n    apply H2.\n    apply H1.\nQed. \n  \n  Fact incl_right_cons_split x l m : incl m (x::l) -> exists m1 m2, m ~p m1 ++ m2 /\\ (forall a, In a m1 -> a = x) /\\ incl m2 l.\n  Proof.\n    intros H.\n    apply (incl_right_app (x::nil) _ l) in H.\n    destruct H.\n    destruct H.\n    destruct H.\n    destruct H0.\n    \n    exists x0.\n    exists x1.\n    split.\n    apply H.\n    split.\n  \n    Focus 2.\n    apply H1.\n\n    intros.\n\n    apply perm_incl in H.\n    apply incl_cons with(l:=nil) in H2.\n    apply incl_tran with(l:=a::nil) in H0.\n\n    Focus 2.\n    apply H2.\n\n    Focus 2.\n    apply incl_nil_x.\n\n    apply incl_left_cons in H0.\n    destruct H0.\n    induction H0.\n    subst.\n    trivial.\n    exfalso.\n    apply H0.\nQed.\n  \n\n  Fact incl_right_cons_choose x l m : incl m (x::l) -> In x m \\/ incl m l.\n  Proof.\n    intros H.\n    apply incl_right_cons_split in H.\n    destruct H as ( m1 & m2 & H1 & H2 & H3 ); simpl in H1.\n    destruct m1 as [ | y m1 ].\n    \n    right.\n    simpl in H1.\n    apply perm_incl in H1.    \n    revert H1 H3.\n    apply incl_tran.\n    apply Forall_forall in H2.\n    apply Forall_inv in H2.\n    subst.\n    apply perm_sym in H1.\n    apply perm_incl in H1.\n    apply incl_left_cons in H1.\n    destruct H1.\n    left.\n    apply H.\nQed.\n\n\n  Fact list_remove (x : X) l : In x l -> exists m, incl l (x::m) /\\ length m < length l.\n  Proof.\n    induction l as [ | y l IHl ].\n    intros [].\n    intros [ ? | H ].\n\n    subst.\n\n    exists l.\n    split.\n    apply incl_refl.\n    simpl; apply lt_n_Sn.\n    \n    specialize (IHl H).\n    destruct IHl as (m & H1 & H2).\n    exists (y::m); split.\n    intros u [ Hu | Hu ].\n    subst; right; left; auto.\n    apply H1 in Hu.\n    destruct Hu; [ left | right; right ]; auto.\n    simpl; apply lt_n_S; auto.\n  Qed.\n\n\nEnd list_incl.\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/list_incl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800691997339971, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.6527501248041356}}
{"text": "Require Export ProjectiveGeometry.Dev.fano_matroid_tactics.\n\n(** Fano's plane **)\n(** also known as Pg(2,2). **)\n\n(** To show that our axiom system is consistent we build a finite model. **)\n\n\n(*****************************************************************************)\n\n\nSection s_fanoPlaneModelRk.\n\nParameter A B C D E F G : Point.\n\nParameter is_only_7_pts : forall P, {P=A}+{P=B}+{P=C}+{P=D}+{P=E}+{P=F}+{P=G}.\n\nParameter rk_points : rk(A :: nil) = 1 /\\ rk(B :: nil) = 1 /\\ rk(C :: nil) = 1 /\\ rk(D :: nil) = 1 /\\\nrk(E :: nil) = 1 /\\ rk(F :: nil) = 1 /\\ rk(G :: nil) = 1.\n\nParameter rk_distinct_points : \nrk(A :: B :: nil) = 2 /\\ rk(A :: C :: nil) = 2 /\\ rk(A :: D :: nil) = 2 /\\ rk(A :: E :: nil) = 2 /\\rk(A :: F :: nil) = 2 /\\ rk(A :: G :: nil) = 2 /\\\nrk(B :: C :: nil) = 2 /\\ rk(B :: D :: nil) = 2 /\\ rk(B :: E :: nil) = 2 /\\ rk(B :: F :: nil) = 2 /\\ rk(B :: G :: nil) = 2 /\\\nrk(C :: D :: nil) = 2 /\\ rk(C :: E :: nil) = 2 /\\ rk(C :: F :: nil) = 2 /\\ rk(C :: G :: nil) = 2 /\\\nrk(D :: E :: nil) = 2 /\\ rk(D :: F :: nil) = 2 /\\ rk(D :: G :: nil) = 2 /\\\nrk(E :: F :: nil) = 2 /\\ rk(E :: G :: nil) = 2 /\\\nrk(F :: G :: nil) = 2.\n\nParameter rk_lines : rk (A :: B :: F :: nil) = 2 /\\ rk (B :: C :: D :: nil) = 2 /\\ \nrk (C :: A :: E :: nil) = 2 /\\ rk (A :: D :: G :: nil) = 2 /\\ rk (B :: E :: G :: nil) = 2 /\\\nrk (C :: F :: G :: nil) = 2 /\\ rk (D :: E :: F :: nil) = 2.\n\nParameter rk_planes : \nrk(A :: B :: C :: nil) = 3 /\\ rk(A :: B :: D :: nil) = 3 /\\ rk(A :: B :: E :: nil) = 3 /\\ rk(A :: B :: G :: nil) = 3 /\\\nrk(A :: C :: D :: nil) = 3 /\\ rk(A :: C :: F :: nil) = 3 /\\ rk(A :: C :: G :: nil) = 3 /\\ rk(A :: D :: E :: nil) = 3 /\\\nrk(A :: D :: F :: nil) = 3 /\\ rk(A :: E :: F :: nil) = 3 /\\ rk(A :: E :: G :: nil) = 3 /\\ rk(A :: F :: G :: nil) = 3 /\\\nrk(B :: C :: E :: nil) = 3 /\\ rk(B :: C :: F :: nil) = 3 /\\ rk(B :: C :: G :: nil) = 3 /\\ rk(B :: D :: E :: nil) = 3 /\\\nrk(B :: D :: F :: nil) = 3 /\\ rk(B :: D :: G :: nil) = 3 /\\ rk(B :: E :: F :: nil) = 3 /\\ rk(B :: F :: G :: nil) = 3 /\\\nrk(C :: D :: E :: nil) = 3 /\\ rk(C :: D :: F :: nil) = 3 /\\ rk(C :: D :: G :: nil) = 3 /\\ rk(C :: E :: F :: nil) = 3 /\\\nrk(C :: E :: G :: nil) = 3 /\\ rk(D :: E :: G :: nil) = 3 /\\ rk(D :: F :: G :: nil) = 3 /\\ rk(E :: F :: G :: nil) = 3.\n\n\n(*****************************************************************************)\n\nLtac case_clear P := let HA:= fresh in let HB:=fresh in let HC:=fresh in let HD:=fresh in let HE:=fresh in let HF:=fresh in let HG:=fresh in \ndestruct (is_only_7_pts P) as [[[[[[HA | HB] | HC] | HD] | HE ] | HF ] | HG]; subst P.\n\n(** rk-singleton : The rank of a point is always greater than one  **) \nLemma rk_singleton_ge : forall P, rk (P :: nil) >= 1.\nProof.\nintros.\nassert(HH := rk_points);use HH.\ncase_clear P;intuition.\nQed.\n\nLemma rk_couple_ge_alt : forall P Q, rk(P :: Q :: nil) = 2 -> rk(P :: Q :: nil) >=2.\nProof.\nintuition.\nQed.\n\n(** rk-couple : The rank of a two distinct points is always greater than one  **)\nLemma rk_couple_ge : forall P Q, ~ P = Q -> rk(P :: Q :: nil) >= 2.\nProof.\nintros.\nassert(HH := rk_distinct_points);use HH.\napply rk_couple_ge_alt.\ncase_clear P;case_clear Q;try equal_degens;try assumption;rewrite couple_equal;assumption.\nQed.\n\nLemma triple_rk2_1 : forall P R, rk(P :: R :: nil) = 2 -> rk(P :: P :: R :: nil) = 2.\nProof.\nintros.\nassert(HH : equivlist (P :: P :: R :: nil) (P :: R :: nil));[my_inO|];rewrite HH;intuition.\nQed.\n\nLemma triple_rk2_2 : forall P R, rk(P :: R :: nil) = 2 -> rk(P :: R :: P :: nil) = 2.\nProof.\nintros.\nassert(HH : equivlist (P :: R :: P :: nil) (P :: R :: nil));[my_inO|];rewrite HH;intuition.\nQed.\n\nLemma triple_rk2_3 : forall P R, rk(P :: R :: nil) = 2 -> rk(R :: P :: P :: nil) = 2.\nProof.\nintros.\nassert(HH : equivlist (R :: P :: P :: nil) (P :: R :: nil));[my_inO|];rewrite HH;intuition.\nQed.\n\nLtac degens_rk2' :=\n  solve[ first [apply triple_rk2_1 | apply triple_rk2_2 | apply triple_rk2_3];rk_couple_triple].\n\nLtac solve_ex_1 L := solve[exists L;repeat split;[try degens_rk2';assumption|rk_couple_triple|rk_couple_triple]].\n\nLtac solve_ex_p_1 := first [\n        solve_ex_1 A\n     |  solve_ex_1 B\n     |  solve_ex_1 C\n     |  solve_ex_1 D\n     |  solve_ex_1 E\n     |  solve_ex_1 F\n     |  solve_ex_1 G\n ].\n\nLtac rk_three_points_simplify P Q :=\nmatch goal with\n| H : rk(P :: Q :: ?X :: nil) = 2 |- _ => solve_ex_1 X\n| H : rk(P :: ?X :: Q :: nil) = 2 |- _ => rewrite <-triple_equal_1 in H;solve_ex_1 X\n| H : rk(Q :: P :: ?X :: nil) = 2 |- _ => rewrite <-triple_equal_2 in H;solve_ex_1 X\n| H : rk(Q :: ?X :: P :: nil) = 2 |- _ => rewrite <-triple_equal_3 in H;solve_ex_1 X\n| H : rk(?X :: P :: Q :: nil) = 2 |- _ => rewrite <-triple_equal_4 in H;solve_ex_1 X\n| H : rk(?X :: Q :: P :: nil) = 2 |- _ => rewrite <-triple_equal_5 in H;solve_ex_1 X\nend.\n\nLtac rk_three_points_simplify_bis :=\nmatch goal with\n| H : _ |- exists R, rk (?P :: ?P :: _ :: nil) = 2 /\\ _ /\\ _ => solve_ex_p_1\n| H : _ |- exists R, rk (?P :: ?Q :: _ :: nil) = 2 /\\ _ /\\ _ => rk_three_points_simplify P Q\nend.\n\n(** rk-three_point_on_lines : Each lines contains at least three points **)\nLemma rk_three_points_on_lines : forall P Q, exists R, \nrk (P :: Q :: R :: nil) = 2 /\\ rk (Q :: R :: nil) = 2 /\\ rk (P :: R :: nil) = 2.\nProof.\nintros.\nassert(HH := rk_distinct_points);assert(HH0 := rk_lines);use HH;use HH0.\ncase_clear P;case_clear Q;rk_three_points_simplify_bis.\nQed.\n\nLtac solve_ex_2 L := solve [exists L;repeat split;try degens_rk2';rk_couple_triple].\n\nLtac solve_ex_p_2 := first [\n        solve_ex_2 A\n     |  solve_ex_2 B\n     |  solve_ex_2 C\n     |  solve_ex_2 D\n     |  solve_ex_2 E\n     |  solve_ex_2 F\n     |  solve_ex_2 G\n ].\n\nLtac rk_inter_simplify X Y :=\nmatch goal with\n| H : _ |- exists J, rk (_ :: Y :: _ :: nil) = 2 /\\ rk (_ :: _ :: _ :: nil) = 2 => try solve_ex_2 Y\n| H : _ |- exists J, rk (Y :: _ :: _ :: nil) = 2 /\\ rk (_ :: _ :: _ :: nil) = 2 => try solve_ex_2 Y\n| H : _ |- exists J, rk (_ :: _ :: _ :: nil) = 2 /\\ rk (_ :: X :: _ :: nil) = 2 => try solve_ex_2 X\n| H : _ |- exists J, rk (_ :: _ :: _ :: nil) = 2 /\\ rk (X :: _ :: _ :: nil) = 2 => try solve_ex_2 X\n| H : _ |- exists J, rk (_ :: _ :: _ :: nil) = 2 /\\ rk (_ :: _ :: _ :: nil) = 2 => try solve_ex_2 X\nend.\n\nLtac rk_inter_simplify_bis P Q R S X :=\nmatch goal with\n| H : rk(R :: S :: ?Y :: nil) = 2 |- _ => rk_inter_simplify X Y \n| H : rk(R :: ?Y :: S :: nil) = 2 |- _ => rk_inter_simplify X Y\n| H : rk(S :: R :: ?Y :: nil) = 2 |- _ => rk_inter_simplify X Y\n| H : rk(S :: ?Y :: R :: nil) = 2 |- _ => rk_inter_simplify X Y\n| H : rk(?Y :: R :: S :: nil) = 2 |- _ => rk_inter_simplify X Y\n| H : rk(?Y :: S :: R :: nil) = 2 |- _ => rk_inter_simplify X Y\nend.\n\nLtac rk_inter_simplify_bis_bis :=\nmatch goal with\n| H : _ |- exists J, rk (?P :: ?P :: _ :: nil) = 2 /\\ rk (?P :: ?P :: _ :: nil) = 2 => solve_ex_p_2\n| H : _ |- exists J, rk (?P :: ?P :: _ :: nil) = 2 /\\ rk (?Q :: ?Q :: _ :: nil) = 2 => solve_ex_p_2\n\n| H : _ |- exists J, rk (?P :: ?Q :: _ :: nil) = 2 /\\ rk (?P :: ?P :: _ :: nil) = 2 => solve_ex_2 P\n| H : _ |- exists J, rk (?Q :: ?P :: _ :: nil) = 2 /\\ rk (?Q :: ?Q :: _ :: nil) = 2 => solve_ex_2 P\n| H : _ |- exists J, rk (?Q :: ?Q :: _ :: nil) = 2 /\\ rk (?P :: ?Q :: _ :: nil) = 2 => solve_ex_2 P\n| H : _ |- exists J, rk (?Q :: ?Q :: _ :: nil) = 2 /\\ rk (?Q :: ?P :: _ :: nil) = 2 => solve_ex_2 P\n\n| H : _ |- exists J, rk (?P :: ?Q :: _ :: nil) = 2 /\\ rk (?R :: ?R :: _ :: nil) = 2 => solve_ex_2 P\n| H : _ |- exists J, rk (?R :: ?R :: _ :: nil) = 2 /\\ rk (?P :: ?Q :: _ :: nil) = 2 => solve_ex_2 P\n\n| H : _ |- exists J, rk (?P :: ?Q :: _ :: nil) = 2 /\\ rk (?R :: ?P :: _ :: nil) = 2 => solve_ex_2 P\n| H : _ |- exists J, rk (?P :: ?Q :: _ :: nil) = 2 /\\ rk (?P :: ?R :: _ :: nil) = 2 => solve_ex_2 P\n| H : _ |- exists J, rk (?Q :: ?P :: _ :: nil) = 2 /\\ rk (?R :: ?P :: _ :: nil) = 2 => solve_ex_2 P\n| H : _ |- exists J, rk (?Q :: ?P :: _ :: nil) = 2 /\\ rk (?P :: ?R :: _ :: nil) = 2 => solve_ex_2 P\n\n| H : rk(?P :: ?Q :: ?X :: nil) = 2 |- exists J, rk (?P :: ?Q :: _ :: nil) = 2 /\\ rk (?R :: ?S :: _ :: nil) = 2 => rk_inter_simplify_bis P Q R S X\n| H : rk(?P :: ?X :: ?Q :: nil) = 2 |- exists J, rk (?P :: ?Q :: _ :: nil) = 2 /\\ rk (?R :: ?S :: _ :: nil) = 2 => rk_inter_simplify_bis P Q R S X\n| H : rk(?Q :: ?P :: ?X :: nil) = 2 |- exists J, rk (?P :: ?Q :: _ :: nil) = 2 /\\ rk (?R :: ?S :: _ :: nil) = 2 => rk_inter_simplify_bis P Q R S X\n| H : rk(?Q :: ?X :: ?P :: nil) = 2 |- exists J, rk (?P :: ?Q :: _ :: nil) = 2 /\\ rk (?R :: ?S :: _ :: nil) = 2 => rk_inter_simplify_bis P Q R S X\n| H : rk(?X :: ?P :: ?Q :: nil) = 2 |- exists J, rk (?P :: ?Q :: _ :: nil) = 2 /\\ rk (?R :: ?S :: _ :: nil) = 2 => rk_inter_simplify_bis P Q R S X\n| H : rk(?X :: ?Q :: ?P :: nil) = 2 |- exists J, rk (?P :: ?Q :: _ :: nil) = 2 /\\ rk (?R :: ?S :: _ :: nil) = 2 => rk_inter_simplify_bis P Q R S X\nend.\n\n\n(** rk-inter : Two lines always intersect in the plane **)\nLemma rk_inter : forall P Q R S, exists J, rk (P :: Q :: J :: nil) = 2 /\\ rk (R :: S :: J :: nil) = 2.\nProof.\nintros.\nassert(HH := rk_distinct_points);assert(HH0 := rk_lines);use HH;use HH0.\ncase_clear P;case_clear Q;\nabstract(case_clear R;case_clear S;rk_inter_simplify_bis_bis).\nQed.\n\n(** rk-lower_dim : There exist three points which are not collinear **)\nLemma rk_lower_dim : exists P0 P1 P2, rk( P0 :: P1 :: P2 :: nil) >=3.\nProof.\nintros.\nassert(HH := rk_planes);use HH.\nexists A;exists B;exists C;intuition.\nQed.\n\nEnd s_fanoPlaneModelRk.", "meta": {"author": "ProjectiveGeometry", "repo": "ProjectiveGeometry", "sha": "4f7f4e6c14580833c91fdef38d048259fb454b88", "save_path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry", "path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry/ProjectiveGeometry-4f7f4e6c14580833c91fdef38d048259fb454b88/Dev/fano_plane_model_rk.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629215, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.652750122724088}}
{"text": "Inductive Boole : Set :=\n  | igaz : Boole\n  | hamis : Boole.\n\nPrint Boole_ind.\n\nDefinition Boole_Or (b1:Boole) (b2:Boole) : Boole :=\n  match b1 with\n    | igaz => match b2 with\n                | igaz => igaz\n                | hamis => igaz\n              end\n    | hamis => match b2 with\n                | igaz => igaz\n                | hamis => hamis\n              end\n  end.\n\nNotation \"x 'vagy' y\" := (Boole_Or x y) (at level 20) : type_scope.\n\nCheck igaz vagy hamis.\n\nEval compute in (igaz vagy hamis).\n\n\nDefinition Boole_And (b1 : Boole) (b2: Boole) : Boole :=\n  match b1 with\n    | igaz => match b2 with | igaz => igaz | hamis => hamis end\n    | hamis => match b2 with | igaz => hamis | hamis => hamis end end.\n\n\nNotation \"x 'es' y\" := (Boole_And x y) (at level 20) : type_scope.\n\n\nDefinition Boole_Not (b : Boole) : Boole :=\n  match b with\n    | igaz => hamis\n    | hamis => igaz\n  end.\n\nNotation \"'nem' x\" := (Boole_Not x) (at level 20) : type_scope.\n\nTheorem DM_2 : (forall x y : Boole, (nem x) es (nem y) = nem (x vagy y)).\nProof.\n  intros.\n  Print Boole_ind.\n  apply Boole_ind with (P:=fun x => (nem x) es (nem y) = nem (x vagy y)).\n  apply Boole_ind with (P:=fun y => (nem igaz) es (nem y) = nem (igaz vagy y)).\n  unfold Boole_And.\n  unfold Boole_Or.\n  unfold Boole_Not.\n  reflexivity.\n  auto.\n  apply Boole_ind with (P:=fun y=> (nem hamis) es (nem y) = nem (hamis vagy y)).\n  unfold Boole_And.\n  unfold Boole_Or.\n  unfold Boole_Not.\n  reflexivity.\n  auto.\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/benedekt/DM_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.652725108965747}}
{"text": "Require Import Verse.Word.\nRequire Import Verse.Types.Internal.\nRequire Import Verse.Types.\nRequire Import Verse.Language.\nRequire Import Verse.Syntax.\n\nRequire Import PeanoNat.\nRequire Import Eqdep_dec.\nRequire Import Bool.\nRequire Import Equality.\nRequire Import Vector.\nImport VectorNotations.\nRequire Import VectorEq.\n\nSet Implicit Arguments.\nGeneralizable All Variables.\n\n\nNotation decidable P := ({P} + {~ P}) (only parsing).\n\nTheorem dec_not_not : forall P:Prop, decidable P -> (~ P -> False) -> P.\nProof.\ntauto.\nDefined.\n\nTheorem dec_True : decidable True.\nProof.\nauto.\nDefined.\n\nTheorem dec_False : decidable False.\nProof.\nunfold not; auto.\nDefined.\n\nTheorem dec_or :\n forall A B:Prop, decidable A -> decidable B -> decidable (A \\/ B).\nProof.\ntauto.\nDefined.\n\nTheorem dec_and :\n forall A B:Prop, decidable A -> decidable B -> decidable (A /\\ B).\nProof.\ntauto.\nDefined.\n\nTheorem dec_not : forall A:Prop, decidable A -> decidable (~ A).\nProof.\ntauto.\nDefined.\n\nTheorem dec_imp :\n forall A B:Prop, decidable A -> decidable B -> decidable (A -> B).\nProof.\ntauto.\nDefined.\n\nTheorem dec_iff :\n forall A B:Prop, decidable A -> decidable B -> decidable (A<->B).\nProof.\ntauto.\nDefined.\n\nTheorem iff_dec :\n  forall A B:Prop, A <-> B -> decidable A -> decidable B.\nProof.\n  intros A B H AOR.\n  destruct AOR as [a | na].\n  left; apply H; easy.\n  right; intro; contradict na; apply H; easy.\nDefined.\n\nNotation eq_dec A := (forall A1 A2 : A, {A1 = A2} + {A1 <> A2}) (only parsing).\nNotation eq_dec_P A := (forall A1 A2 : A, A1 = A2 \\/ A1 <> A2) (only parsing).\n\nDefinition eq_dec_eq_dec_P A : eq_dec A -> eq_dec_P A :=\n  fun A_eq_dec a1 a2 => match A_eq_dec a1 a2 with\n                        | left p => or_introl p\n                        | right p => or_intror p\n                        end.\n\nDefinition nat_eq_dec : eq_dec nat := Nat.eq_dec.\nDefinition bool_eq_dec : eq_dec bool := bool_dec.\n\nHint Resolve dec_True dec_False dec_or dec_and dec_imp dec_not dec_iff nat_eq_dec bool_eq_dec\n : decidable_prop.\n\nLtac solve_decidable :=\n  match goal with\n  | |- decidable _ => solve [ auto 100 with decidable_prop core ]\n  end.\n\nLemma eq_dec_refl {T} (T_eq_dec : eq_dec T) (t : T)\n  : {p : t = t | T_eq_dec t t = left p}.\n  pose (T_eq_dec t t).\n  change (T_eq_dec t t) with s.\n  destruct s.\n  destruct e. exists eq_refl; trivial.\n  destruct n; trivial.\nQed.\n\nLemma eq_dec_neq {T} (T_eq_dec : eq_dec T) (t1 t2 : T)\n  : t1 <> t2 -> { p : t1 <> t2 | T_eq_dec t1 t2 = right p}.\n  intros.\n  pose (T_eq_dec t1 t2).\n  change (T_eq_dec t1 t2) with s.\n  destruct s;\n    [contradiction | ].\n  exists n; trivial.\nQed.\n\n(* undep_eq not actually used any more *)\n(*\nLtac undep_eq :=\n  match goal with\n  | [ H : existT _ _ ?a = existT _ _ ?b |- _ ]\n    => let He := fresh H in\n       assert (He : a = b) by (refine (inj_pair2_eq_dec _ _ _ _ _ _ H);\n                             auto with decidable_prop);\n       rewrite He in *; clear H\n  end.\n*)\nLtac crush_eq_dec := repeat aux_match; aux_solve\n  with aux_match :=  (intros;\n                     match goal with\n                     | [ H1 : ?T, H2 : ?T, _ : _ <> _ |- _ ] => idtac\n                     | [ H1 : ?T, H2 : ?T, H3 : ?T |- _ ]    => aux_cases2 H1 H3 T\n                     | [ H1 : ?T, H2 : ?T |- _ ]             => aux_cases H1 H2 T\n                     end)\n  with aux_cases H1 H2 T :=\n                       let T_eq_dec := fresh \"T\" in assert (T_eq_dec : eq_dec T) by (intros; solve_decidable);\n                                                    destruct (T_eq_dec H1 H2) as [ eq | ];\n                                                    [ subst | ..]; clear T_eq_dec\n  (* Heuristic for pairing up four hypothesis of the same type by alternation *)\n  with aux_cases2 H1 H2 T :=\n                       let T_eq_dec := fresh \"T\" in assert (T_eq_dec : eq_dec T) by (intros; solve_decidable);\n                                                    destruct (T_eq_dec H1 H2) as [ eq | ];\n                                                    [ symmetry in eq; subst | ..]; clear T_eq_dec\n  with aux_solve := try solve [left; constructor; trivial |\n                               right; inversion 1; try congruence; easy ].\n\nLtac crush_eqb_eq :=\n  repeat (match goal with\n          | [ |- _ <-> _ ] => constructor\n          | |- context [?H ?x ?x] => destruct (eq_dec_refl H x) as [eq deceq]; rewrite deceq; trivial\n          | H : ?a = ?a -> False |- _ => contradict H; trivial\n          | H : ?a = ?b -> False |- context [?Heq_dec ?a ?b] => destruct (Heq_dec a b)\n          | |- _ -> _ => intros\n          | H : _ = _ |- _ => dependent destruction H\n          | _ => try contradiction\n          end; autounfold in *).\n\nSection DecFacts.\n\n  Variable T : Type.\n  Variable T_dec : forall (a b : T), decidable (a = b).\n\n  (* Boolean equality for decidable Types *)\n  Definition eqdec_eqb := fun a b => if T_dec a b then true else false.\n\n  Definition eqdec_eqb_eq : forall a b, eqdec_eqb a b = true <-> a = b.\n    unfold eqdec_eqb. intros.\n    destruct (T_dec a b);\n      unfold iff; split; first [discriminate | contradiction | trivial].\n  Defined.\n\n  (* Vector equality is decidable *)\n  Definition vec_eq_dec n : eq_dec (Vector.t T n).\n    apply (Vector.eq_dec T eqdec_eqb eqdec_eqb_eq).\n  Defined.\n\nEnd DecFacts.\n\n(** Decidable equality for Verse constructs *)\n\nLemma kind_eq_dec : eq_dec kind.\n  refine (\n  fun k1 k2 => match k1, k2 with\n               | direct, direct => left eq_refl\n               | memory, memory => left eq_refl\n               | _, _           => right _\n               end); intro; exact (match H with end).\nDefined.\n\nLemma endian_eq_dec : eq_dec endian.\n  refine (fun e1 e2 => match e1, e2 with\n                       | hostE, hostE\n                       | bigE, bigE\n                       | littleE, littleE => left eq_refl\n                       | _, _ => right _\n                       end); inversion 1.\nDefined.\n\nHint Resolve vec_eq_dec kind_eq_dec endian_eq_dec : decidable_prop.\n\nLemma directTy_eq_dec : eq_dec (type direct).\n  refine (fun ty => match ty as ty0 in type direct return\n                          forall ty' : type direct, {ty0 = ty'} + {ty0 <> ty'} with\n                    | word n => fun ty' => match ty' as ty0' in type direct\n                                                 return\n                                                 {word n = ty0'} + {word n <> ty0'}\n                                           with\n                                           | word n' => _\n                                           | multiword _ _ => _\n                                           end\n                    | multiword m n => fun ty' => match ty' as ty0' in type direct\n                                                        return\n                                                        {multiword m n = ty0'} + {multiword m n <> ty0'}\n                                                  with\n                                                  | word _ => _\n                                                  | multiword m' n' => _\n                                                  end\n                    end).\n  all: crush_eq_dec.\n(*\n  refine (fun (ty ty' : type direct) => match ty in type direct, ty' as ty0' in type direct return {ty = ty0'} + {ty <> ty'} with\n                        | word n, word n' => if nat_eq_dec n n'\n                                             then _\n                                             else _\n                        | multiword n m, multiword n' m' => if nat_eq_dec n n'\n                                                            then if nat_eq_dec m m'\n                                                                 then left _\n                                                                 else right _\n                                                            else right _\n                        | _, _ => right _\n                        end).\n *)\n(*\n  dependent destruction A1; dependent destruction A2; crush_eq_dec.\n *)\nDefined.\n\nHint Resolve directTy_eq_dec.\n\nLemma ty_eq_dec : forall {k}, eq_dec (type k).\n  induction k.\n  apply directTy_eq_dec.\n  intros ty ty'.\n  refine (match ty, ty' with\n          | array n e t, array n' e' t' => _\n          end).\n  crush_eq_dec.\nDefined.\n\nLemma bytes_eq_dec : forall (n : nat), eq_dec (bytes n).\n  destruct A1. destruct A2.\n  unfold Bvector.Bvector in b, b0.\n  crush_eq_dec.\nDefined.\n\nHint Resolve ty_eq_dec bytes_eq_dec : decidable_prop.\n\nLemma op_eq_dec {ar} : eq_dec (op ar).\n  refine (\n  fun o1 o2 => match o1 as o1' in op ar'\n                     return forall o : op ar', {o1' = o} + {o1' <> o}\n               with\n               | plus    => fun o => match o as o' in op binary\n                                           return {plus = o'} + {plus <> o'}\n                                     with\n                                     | plus => _\n                                     | _    => _\n                                     end\n               | minus   => fun o => match o as o' in op binary\n                                           return {minus = o'} + {minus <> o'}\n                                     with\n                                     | minus => _\n                                     | _     => _\n                                     end\n               | mul     => fun o => match o as o' in op binary\n                                           return {mul = o'} + {mul <> o'}\n                                     with\n                                     | mul   => _\n                                     | _     => _\n                                     end\n               | quot     => fun o => match o as o' in op binary\n                                           return {quot = o'} + {quot <> o'}\n                                     with\n                                     | quot  => _\n                                     | _    => _\n                                      end\n               | rem      => fun o => match o as o' in op binary\n                                            return {rem = o'} + {rem <> o'}\n                                      with\n                                      | rem  => _\n                                      | _    => _\n                                      end\n               | bitOr    => fun o => match o as o' in op binary\n                                            return {bitOr = o'} + {bitOr <> o'}\n                                      with\n                                      | bitOr  => _\n                                      | _    => _\n                                      end\n               | bitAnd   => fun o => match o as o' in op binary\n                                            return {bitAnd = o'} + {bitAnd <> o'}\n                                      with\n                                      | bitAnd  => _\n                                      | _    => _\n                                      end\n               | bitXor   => fun o => match o as o' in op binary\n                                            return {bitXor = o'} + {bitXor <> o'}\n                                      with\n                                      | bitXor  => _\n                                      | _    => _\n                                      end\n               | bitComp  => fun o => match o as o' in op unary\n                                            return {bitComp = o'} + {bitComp <> o'}\n                                      with\n                                      | bitComp => _\n                                      | _       => _\n                                      end\n               | rotL n   => fun o => match o as o' in op unary\n                                            return {rotL n = o'} + {rotL n <> o'}\n                                      with\n                                      | rotL n' => _\n                                      | _       => _\n                                      end\n               | rotR n   => fun o => match o as o' in op unary\n                                            return {rotR n = o'} + {rotR n <> o'}\n                                      with\n                                      | rotR n' => _\n                                      | _       => _\n                                      end\n               | shiftL n   => fun o => match o as o' in op unary\n                                            return {shiftL n = o'} + {shiftL n <> o'}\n                                      with\n                                      | shiftL n' => _\n                                      | _       => _\n                                      end\n               | shiftR n   => fun o => match o as o' in op unary\n                                            return {shiftR n = o'} + {shiftR n <> o'}\n                                      with\n                                      | shiftR n' => _\n                                      | _         => _\n                                        end\n               | nop        => fun o => match o as o' in op unary\n                                              return {nop = o'} + {nop <> o'}\n                                        with\n                                        | nop  => _\n                                        | _    => _\n                                        end\n               end o2); solve [exact idProp | crush_eq_dec].\nDefined.\n\nHint Resolve vec_eq_dec kind_eq_dec endian_eq_dec ty_eq_dec bytes_eq_dec op_eq_dec\n  : decidable_prop.\n\n(* Equality is decidable for scopeVar *)\n\nFixpoint idxInScope n (vT : Vector.t (some type) n)\n         k (ty : type k) (x : scopeVar vT ty) : nat  :=\n  match x with\n  | headVar    => 0\n  | restVar x' => S (idxInScope x')\n  end.\n\nDefinition scopeVar_eqb n (vT : Vector.t (some type) n)\n           k (ty : type k) (x y : scopeVar vT ty) : bool :=\n  if Nat.eq_dec (idxInScope x) (idxInScope y)\n  then true else false.\n\nDefinition scopeVar_eqb_eq n (vT : Vector.t (some type) n)\n           k (ty : type k) (x y : scopeVar vT ty) : scopeVar_eqb x y = true <-> x = y.\n  constructor.\n  * intro eqb_x_y.\n    unfold scopeVar_eqb in eqb_x_y.\n    simpl in eqb_x_y.\n    destruct (Nat.eq_dec (idxInScope x) (idxInScope y));\n      [idtac | discriminate].\n\n    dependent induction x; dependent induction y.\n  - trivial.\n  - contradict e; discriminate.\n  - contradict e; discriminate.\n  - f_equal.\n    apply IHx. apply (eq_add_S e).\n    all: trivial.\n  * intro.\n    unfold scopeVar_eqb.\n    rewrite H.\n    destruct (Nat.eq_dec (idxInScope y) (idxInScope y));\n      congruence.\nQed.\n(*\nDefinition scopeVar_eq_dec n (vT : Vector.t (some type) n)\n  : forall {k} {ty : type k}, eq_dec (scopeVar vT ty).\n  dependent induction A1; dependent induction A2;\n    [left | right .. | idtac]; try congruence.\n  destruct (IHA1 A2);\n    [left; congruence | right].\n  contradict n;\n  apply (f_equal ((fun (y : scopeVar (tl v) ty) (x : scopeVar v ty) =>\n                    (match x in @scopeVar (S n0) v0 _ ty0\n                          return scopeVar (tl v0) ty0 -> scopeVar (tl v0) ty0 with\n                    | headVar => fun y => y\n                    | restVar x' => fun _ => x'\n                    end y)) A1)\n                 n).\nDefined.\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/DecFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430520409023, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6527037748891574}}
{"text": "Require Export D.\n\n\n\n(** **** Problem #13 : 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\nLemma rev_involutive : forall l : list nat,\n  rev (rev l) = l.\nProof.\n  intros. induction l. reflexivity.\n  Lemma rev_snoc_lemma : forall n:nat, forall l:list nat,\n    rev (n :: l) = snoc (rev l) n.\n  Proof. intros. reflexivity. Qed.\n  rewrite -> rev_snoc_lemma. simpl.\n  Lemma rev_snoc_lemma2 : forall n:nat, forall l:list nat,\n    rev (snoc l n) = n :: rev l.\n  Proof. intros. induction l. reflexivity.\n  simpl. rewrite -> IHl. simpl. reflexivity. Qed.\n  rewrite -> rev_snoc_lemma2. rewrite -> IHl. reflexivity.\n  \nQed.\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     rev l = l'.\nProof.\n intros.\n   rewrite -> H.  apply rev_involutive.\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/P14.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931457, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6527037608591001}}
{"text": "(*|\n###############################################\nHow could I make example for sigma type in Coq?\n###############################################\n\n:Link: https://stackoverflow.com/q/56365504\n|*)\n\n(*|\nQuestion\n********\n\nFor that type:\n|*)\n\nRecord Version :=\n  mkVersion {\n      major  : nat;\n      minor  : nat;\n      branch : {b : nat | b > 0 /\\ b <= 9};\n      hotfix : {h : nat | h > 0 /\\ h < 8}\n    }.\n\n(*| I'm trying to make an example, and it failed with: |*)\n\nFail Example ex1 := mkVersion 3 2 (exist _ 5) (exist _ 5). (* .unfold .fails *)\n\n(*| What am I missing? |*)\n\n(*|\nAnswer\n******\n\nThe reason it fails is that you need not only provide a witness (``b``\nand ``h`` in this case) but also a proof that the corresponding\ncondition holds for the provided witness.\n\nI would switch to booleans to make my life easier, because this allows\nproof by computation, which is basically what ``eq_refl`` does in the\nsnippet below:\n|*)\n\nReset Initial. (* .none *)\nFrom Coq Require Import Bool Arith.\n\nCoercion is_true : bool >-> Sortclass.\n\nRecord Version :=\n  mkVersion {\n      major  : nat;\n      minor  : nat;\n      branch : {b : nat | (0 <? b) && (b <=? 9)};\n      hotfix : {h : nat | (0 <? h) && (h <? 8)}\n    }.\n\nExample ex1 := mkVersion 3 2 (exist _ 5 eq_refl) (exist _ 5 eq_refl).\n\n(*|\nWe could introduce a notation allowing a nicer representation of literals:\n|*)\n\nNotation \"<| M ',' m ',' b '~' h |>\" :=\n  (mkVersion M m (exist _ b eq_refl) (exist _ h eq_refl)).\n\nExample ex2 := <| 3,2,5~5 |>.\n\n(*|\nIf there is a need to add manual proofs then I'd suggest to use\n``Program`` mechanism:\n|*)\n\nFrom Coq Require Import Program.\n\nProgram Definition ex3 b h (condb : b =? 5) (condh : h =? 1) :=\n  mkVersion 3 2 (exist _ b _) (exist _ h _).\nNext Obligation.\n  now unfold is_true in * |-; rewrite Nat.eqb_eq in * |-; subst. Qed.\nNext Obligation.\n  now unfold is_true in * |-; rewrite Nat.eqb_eq in * |-; subst. Qed.\n\n(*| or ``refine`` tactic: |*)\n\nDefinition ex3' b h (condb : b =? 5) (condh : h =? 1) : Version.\nProof.\n  now refine (mkVersion 3 2 (exist _ b _) (exist _ h _));\n    unfold is_true in * |-; rewrite Nat.eqb_eq in * |-; subst.\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-could-i-make-example-for-sigma-type-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.65257712531744}}
{"text": "(* infotheo (c) AIST. R. Affeldt, M. Hagiwara, J. Senizergues. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq path div fintype.\nFrom mathcomp Require Import tuple finfun bigop.\nRequire Import Reals Fourier.\nRequire Import Reals_ext Ranalysis_ext Rssr log2.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope Rb_scope.\n\nSection ln_id_sect.\n\nDefinition ln_id x := ln x - (x - 1).\n\nLemma pderivable_ln_id_xle1 : pderivable ln_id (fun x => 0 < x <= 1).\nProof.\nrewrite /pderivable => x Hx.\nrewrite /ln_id.\napply derivable_pt_plus.\n- apply derivable_pt_ln, Hx.\n- apply derivable_pt_opp, derivable_pt_minus ; [apply derivable_pt_id | apply derivable_pt_cst].\nDefined.\n\nDefinition ln_id' x (H : 0 < x <= 1) := derive_pt ln_id x (pderivable_ln_id_xle1 H).\n\nLemma derive_pt_ln_id_xle1 : forall x (Hx : 0 < x <= 1), (/ x) - 1 = ln_id' Hx.\nProof.\nmove=> y Hy.\nrewrite /ln_id' /pderivable_ln_id_xle1 /ln_id.\nrewrite derive_pt_plus derive_pt_opp derive_pt_ln derive_pt_minus derive_pt_id derive_pt_cst.\nrewrite Rminus_0_r /Rminus.\nreflexivity.\nDefined.\n\nLemma derive_pt_ln_id_xle1_ge0 x (Hx : 0 < x <= 1) : 0 < if x==1 then 1 else ln_id' Hx.\nProof.\ncase/orP : (orbN (x == 1)) => Hcase ; first by rewrite Hcase; fourier.\nmove/negbTE in Hcase ; rewrite Hcase.\nrewrite -derive_pt_ln_id_xle1.\napply Rgt_lt, Rgt_minus, Rlt_gt.\nrewrite -Rinv_1 ; apply Rinv_lt_contravar; first by [rewrite mulR1; apply Hx].\ncase (Rle_lt_or_eq_dec x 1) ; [apply Hx | done | ].\nmove/eqP in Hcase ; move => Habs.\nrewrite Habs in Hcase ; by contradict Hcase.\nDefined.\n\nLemma ln_idlt0_xlt1 : forall x, 0 < x < 1 -> ln_id x < 0.\nProof.\nrewrite {2}(_ : 0 = ln_id 1); last by rewrite /ln_id ln_1 /Rminus Rplus_opp_r Ropp_0 addR0.\nmove=> x Hx.\nhave lt01 : 0 < 1 by fourier.\napply (derive_increasing_ad_hoc lt01 derive_pt_ln_id_xle1_ge0).\n- by split; [apply Hx | apply Rlt_le, Hx].\n- split; by fourier.\n- by apply Hx.\nQed.\n\nLemma ln_idlt0_xgt1 x : 0 < x -> 1 < x -> ln_id x < 0.\nProof.\nmove=> Hx Hx2.\nrewrite /ln_id; apply Rlt_minus, exp_lt_inv.\nrewrite exp_ln; last exact Hx.\nrewrite -{1}(addR0 x) -(Rplus_opp_l 1) addRA addRC.\napply exp_ineq1, Rgt_minus, Rgt_lt, Hx2.\nQed.\n\nLemma ln_idgt0 x : 0 < x -> ln_id x <= 0.\nProof.\nmove=> Hx.\ncase (total_order_T x 1).\n- case => Hx2.\n  + by apply Rlt_le, ln_idlt0_xlt1.\n  + subst x; rewrite /ln_id ln_1 /Rminus 2!Rplus_opp_r; by apply Rle_refl.\n- move=> Hx2; apply Rlt_le, ln_idlt0_xgt1; by [apply Hx | apply Rgt_lt, Hx2].\nQed.\n\nLemma ln_id_cmp x : 0 < x -> ln x <= x - 1.\nProof. move=> Hx ; apply Rminus_le ; apply ln_idgt0 ; exact Hx. Qed.\n\nLemma log_id_cmp x : 0 < x -> log x <= (x - 1) * log (exp 1).\nProof.\nmove=> Hx ; rewrite /log ln_exp /Rdiv mul1R.\napply Rmult_le_compat_r; by\n  [apply Rlt_le, Rinv_0_lt_compat, ln_2_pos | apply ln_id_cmp].\nQed.\n\nLemma ln_id_eq x : 0 < x -> ln x = x - 1 -> x = 1.\nProof.\nmove=> Hx' Hx.\ncase (total_order_T x 1) => [ [] // Hx2 | Hx2]; contradict Hx.\n- apply Rlt_not_eq, (Rplus_lt_reg_r (- (x - 1))); rewrite (addRC (x - 1)) Rplus_opp_l.\n  apply ln_idlt0_xlt1; split; [exact Hx' | exact Hx2].\n- apply Rlt_not_eq, (Rplus_lt_reg_r (- (x - 1))); rewrite (addRC (x - 1)) Rplus_opp_l.\n  by apply ln_idlt0_xgt1.\nQed.\n\nLemma log_id_eq x : 0 < x -> log x = (x - 1) * log (exp 1) -> x = 1.\nProof.\nmove=> Hx' Hx ; rewrite /log ln_exp /Rdiv mul1R in Hx.\napply Rmult_eq_reg_r in Hx; last by apply not_eq_sym, Rlt_not_eq, Rinv_0_lt_compat, ln_2_pos.\napply ln_id_eq; by [apply Hx' | apply Hx].\nQed.\n\nEnd ln_id_sect.\n\nSection xlnx_sect.\n\nSection xlnx.\n\nDefinition xlnx := fun x => if 0 <b x then x * ln x else 0.\n\nLemma xlnx_0 : xlnx 0 = 0.\nProof. rewrite /xlnx mul0R; by case : ifP. Qed.\n\nLemma xlnx_1 : xlnx 1 = 0.\nProof. rewrite /xlnx ln_1 mulR0 ; by case : ifP. Qed.\n\nLemma xlnx_neg x : 0 < x < 1 -> xlnx x < 0.\nProof.\ncase => lt0x ltx1.\nrewrite /xlnx.\nhave -> : 0 <b x ; first by apply/RltP.\napply Ropp_lt_cancel.\nrewrite Ropp_0 -Ropp_mult_distr_r_reverse.\napply Rmult_lt_0_compat => //.\napply Ropp_lt_cancel; rewrite Ropp_involutive Ropp_0.\napply exp_lt_inv.\nby rewrite exp_ln // exp_0.\nQed.\n\nLemma continue_xlnx : continuity xlnx.\nProof.\nrewrite /continuity => r.\nrewrite /continuity_pt /continue_in /limit1_in /limit_in => eps eps_pos /=.\ncase (total_order_T 0 r) ; first case ; move=> Hcase.\n- have : continuity_pt (fun x => x * ln x) r.\n    apply continuity_pt_mult.\n      by apply derivable_continuous_pt, derivable_id.\n    by apply derivable_continuous_pt, derivable_pt_ln.\n  rewrite /continuity_pt /continue_in /limit1_in /limit_in => /(_ eps eps_pos); case => /= k [k_pos Hk].\n  exists (Rmin k r); split; first by apply Rlt_gt, Rmin_pos.\n  - move=> x ; rewrite /D_x ; move => [[_ Hx1] Hx2].\n    rewrite /xlnx.\n    have -> : 0 <b x.\n      apply/RltP.\n      rewrite -(addR0 x) -{2}(Rplus_opp_l r) addRA.\n      apply (Rle_lt_trans _ ((x + - r) + Rabs (x + - r))).\n        rewrite -(Rplus_opp_r (x + -r)); apply Rplus_le_compat_l.\n        rewrite -Rabs_Ropp; by apply Rle_abs.\n      apply Rplus_lt_compat_l.\n      rewrite /R_dist /Rminus in Hx2.\n      apply (Rlt_le_trans _ (Rmin k r)) => //; by apply Rmin_r.\n    have -> : 0 <b r by apply/RltP.\n    apply Hk.\n    split => //.\n    by apply (@Rlt_le_trans _ _ _ Hx2), Rmin_l.\n- subst r.\n  exists (exp (- 2 * / eps)).\n  split ; first by apply exp_pos.\n  move=> x; rewrite /R_dist /Rminus Ropp_0 addR0; case=> Hx1 Hx2.\n  rewrite /xlnx.\n  have -> : Rlt_bool 0 0 = false by apply/RltP/Rlt_irrefl.\n  case (Rlt_le_dec 0 x) => Hcase.\n  + rewrite Rabs_pos_eq in Hx2 ; last by apply Rlt_le.\n    have -> : 0 <b x by apply/RltP.\n    rewrite /Rminus Ropp_0 addR0 -{1}(exp_ln _ Hcase).\n    set X := ln x.\n    have X_neg : X < 0.\n      apply (Rlt_trans _ (-2 * / eps)).\n      by apply exp_lt_inv ; subst X ; rewrite exp_ln.\n      rewrite Ropp_mult_distr_l_reverse.\n      apply Ropp_0_lt_gt_contravar, Rlt_mult_inv_pos => // ; by apply Rlt_R0_R2.\n    apply: (Rlt_le_trans _ (2 * / (- X)) _).\n    * rewrite Rabs_left ; last first.\n        rewrite -(mulR0 (exp X)).\n        apply Rmult_lt_compat_l => // ; by apply exp_pos.\n       rewrite -Ropp_mult_distr_r_reverse.\n      apply (Rmult_lt_reg_r (/ - X)); first by apply Rinv_0_lt_compat, Ropp_0_gt_lt_contravar.\n      rewrite -mulRA Rinv_r; last by apply not_eq_sym, Rlt_not_eq, Ropp_0_gt_lt_contravar.\n      rewrite mulR1 -(Rinv_involutive 2); last by apply not_eq_sym, Rlt_not_eq, Rlt_R0_R2.\n      rewrite -mulRA ( _ : forall r, r * r = r ^ 2); last by move=> ?; rewrite /pow mulR1.\n      rewrite pow_inv; last by apply not_eq_sym, Rlt_not_eq, Ropp_0_gt_lt_contravar.\n      rewrite -Rinv_mult_distr; last 2 first.\n        by apply Rinv_neq_0_compat, not_eq_sym, Rlt_not_eq, Rlt_R0_R2.\n        by apply pow_nonzero, Ropp_neq_0_compat, Rlt_not_eq.\n      rewrite -(Rinv_involutive (exp X)); last by apply not_eq_sym, Rlt_not_eq, exp_pos.\n      apply Rinv_lt_contravar.\n        rewrite -mulRA mulRC; apply Rlt_mult_inv_pos; last fourier.\n        apply Rlt_mult_inv_pos; last by apply exp_pos.\n        apply pow_gt0; by fourier.\n        rewrite -exp_Ropp mulRC (_ : 2 = INR 2`!) //.\n        by apply exp_strict_lb, Ropp_0_gt_lt_contravar.\n    * apply (Rmult_le_reg_r (/ 2)); first by apply Rinv_0_lt_compat, Rlt_R0_R2.\n      rewrite mulRC mulRA Rinv_l; last by apply not_eq_sym, Rlt_not_eq, Rlt_R0_R2.\n      rewrite mul1R -(Rinv_involutive eps); last by apply not_eq_sym, Rlt_not_eq.\n      rewrite -Rinv_mult_distr ; last 2 first.\n        by apply not_eq_sym, Rlt_not_eq, Rinv_0_lt_compat.\n        by apply not_eq_sym, Rlt_not_eq, Rlt_R0_R2.\n      apply Rle_Rinv.\n      - apply Rmult_lt_0_compat; by [apply Rinv_0_lt_compat | apply Rlt_R0_R2].\n      - by apply Ropp_0_gt_lt_contravar.\n      - rewrite -(Ropp_involutive (/ eps * 2)); apply Ropp_le_contravar.\n        rewrite mulRC -Ropp_mult_distr_l_reverse.\n        apply exp_le_inv, Rlt_le; subst X; by rewrite exp_ln.\n  + have -> : 0 <b x = false by apply/RltP; apply RIneq.Rle_not_lt.\n    by rewrite /Rminus Ropp_0 addR0 Rabs_R0.\n- exists (- r); split; first by apply Ropp_0_gt_lt_contravar.\n  move=> x [[_ Hx1] Hx2].\n  rewrite /R_dist /xlnx.\n  have -> : 0 <b x = false.\n    apply/RltP ; apply Rge_not_lt, Rle_ge.\n    rewrite -(addR0 x) -{1}(Rplus_opp_l r) addRA.\n    apply (Rle_trans _ ((x + - r) - Rabs (x + - r))).\n      apply Rplus_le_compat_l, Rlt_le.\n      rewrite -{1}(Ropp_involutive r).\n      by apply Ropp_lt_contravar.\n    rewrite -(Rplus_opp_r (x + -r)); apply Rplus_le_compat_l.\n    by apply Ropp_le_contravar, Rle_abs.\n  have -> : Rlt_bool 0 r = false.\n    by apply/RltP; apply Rge_not_lt, Rle_ge, Rlt_le.\n  rewrite /Rminus Ropp_0 addR0 Rabs_R0; by apply Rgt_lt.\nQed.\n\n(* NB: not used *)\nLemma uniformly_continue_xlnx : uniform_continuity xlnx (fun x => 0 <= x <= 1).\nProof.\napply Heine ; first by apply compact_P3.\nmove=> x _ ; by apply continue_xlnx.\nQed.\n\nLet xlnx_total := fun y => y * ln y.\n\nLemma derivable_xlnx_total x : 0 < x -> derivable_pt xlnx_total x.\nProof.\nmove=> x_pos.\napply derivable_pt_mult.\n  by apply derivable_id.\nby apply derivable_pt_ln.\nDefined.\n\nLemma xlnx_total_xlnx x : 0 < x -> xlnx x = xlnx_total x.\nProof. by rewrite /xlnx /f => /RltP ->. Qed.\n\nLemma derivable_pt_xlnx x (x_pos : 0 < x) : derivable_pt xlnx x.\nProof. apply (@derivable_f_eq_g _ _ x 0 xlnx_total_xlnx x_pos (derivable_xlnx_total x_pos)). Defined.\n\nLemma derive_xlnx_aux1 x (x_pos : 0 < x) :\n  derive_pt xlnx x (derivable_pt_xlnx x_pos) =\n  derive_pt xlnx_total x (derivable_xlnx_total x_pos).\nProof. by rewrite -derive_pt_f_eq_g. Qed.\n\nLemma derive_xlnx_aux2 x (x_pos : 0 < x) : derive_pt xlnx x (derivable_pt_xlnx x_pos) = ln x + 1.\nProof.\nrewrite derive_xlnx_aux1 /f derive_pt_mult derive_pt_ln.\nrewrite Rinv_r; last by apply not_eq_sym, Rlt_not_eq.\nrewrite (_ : derive_pt ssrfun.id x (derivable_id x) = 1) ; first by rewrite mul1R.\nrewrite -(derive_pt_id x).\nby apply proof_derive_irrelevance.\nQed.\n\nLemma derive_pt_xlnx x (x_pos : 0 < x) (pr : derivable_pt xlnx x) : derive_pt xlnx x pr = ln x + 1.\nProof. rewrite -derive_xlnx_aux2 ; by apply proof_derive_irrelevance. Qed.\n\nLemma pderivable_Ropp_xlnx : pderivable (fun y => - xlnx y) (fun x => 0 < x <= exp (- 1)).\nProof.\nmove=> x /= Hx.\napply derivable_pt_opp.\napply derivable_pt_xlnx.\napply Hx.\nDefined.\n\nLemma xlnx_sdecreasing_0_Rinv_e_helper : forall (t : R) (Ht : 0 < t <= exp (-1)),\n  0 < (if t == exp (-1) then 1 else derive_pt (fun x => - xlnx x) t (pderivable_Ropp_xlnx Ht)).\nProof.\nmove=> t [Ht1 Ht2].\ncase : ifP => [|/negbT] Hcase ; first apply Rlt_0_1.\nrewrite derive_pt_opp derive_pt_xlnx //.\napply Ropp_lt_cancel ; rewrite Ropp_involutive Ropp_0.\napply (Rplus_lt_reg_r (- 1)).\nrewrite -addRA Rplus_opp_r addR0 add0R.\napply exp_lt_inv.\nrewrite exp_ln //.\napply Rlt_le_neq => //.\nmove/eqP; by apply/negP.\nQed.\n\nLemma xlnx_sdecreasing_0_Rinv_e x y :\n  0 <= x <= exp (-1) -> 0 <= y <= exp (-1) -> x < y -> xlnx x > xlnx y.\nProof.\nmove=> [Hx1 Hx2] [Hy1 Hy2] xlty.\ncase/orP : (orbN ( x == 0)).\n- move/eqP => -> ; rewrite xlnx_0 ; apply xlnx_neg.\n  split ; first by apply (Rle_lt_trans _ x).\n  apply (Rle_lt_trans _ (exp (-1)))=> //.\n  apply exp_opp_1_lt_1.\nmove => xnot0.\napply Ropp_lt_cancel.\nhave x_pos : 0 < x.\n  apply Rlt_le_neq => // /eqP.\n  rewrite eq_sym ; by apply/negP.\nhave y_pos : 0 < y by apply (Rlt_trans _ x).\nmove=> {Hx1 Hy1}.\nhave aux : 0 < exp(-1) by apply exp_pos.\nby apply (derive_increasing_ad_hoc aux xlnx_sdecreasing_0_Rinv_e_helper).\nQed.\n\nLemma xlnx_decreasing_0_Rinv_e x y :\n  0 <= x <= exp (-1) -> 0 <= y <= exp (-1) -> x <= y -> xlnx y <= xlnx x.\nProof.\nmove=> Hx Hy Hxy.\ncase/orP : (orbN (x == y)).\n- move=> /eqP -> ; by apply Rle_refl.\n- move=> H.\n  apply Rlt_le, xlnx_sdecreasing_0_Rinv_e => //.\n  apply Rlt_le_neq => //.\n  move=> /eqP ; by apply/negP.\nQed.\n\nEnd xlnx.\n\nSection diff_xlnx.\n\nDefinition diff_xlnx := fun x => xlnx (1 - x) - xlnx x.\n\nLemma derivable_pt_diff_xlnx x (Hx : 0 < x < 1) : derivable_pt diff_xlnx x.\nProof.\nrewrite /diff_xlnx /Rminus.\napply derivable_pt_plus ; last by apply derivable_pt_opp, derivable_pt_xlnx, Hx.\napply (derivable_pt_comp (fun x => 1 + - x) xlnx).\n  apply derivable_pt_plus ; first by apply derivable_pt_const.\n  apply derivable_pt_Ropp.\napply derivable_pt_xlnx.\napply (Rplus_lt_reg_r x); rewrite addRC -addRA Rplus_opp_l 2!addR0; by apply Hx.\nDefined.\n\nLemma derive_pt_diff_xlnx x (Hx : 0 < x < 1) :\n  derive_pt diff_xlnx x (derivable_pt_diff_xlnx Hx) = -(2 + ln (x * (1-x))).\nProof.\nrewrite derive_pt_plus derive_pt_opp derive_pt_xlnx; last by apply Hx.\nrewrite derive_pt_comp derive_pt_plus derive_pt_const.\nrewrite derive_pt_xlnx /=; last first.\n  apply (Rplus_lt_reg_r x); rewrite addRC -addRA Rplus_opp_l 2!addR0; by apply Hx.\nrewrite add0R ln_mult; first field.\n- by apply Hx.\n- apply (Rplus_lt_reg_r x); rewrite addRC -addRA Rplus_opp_l 2!addR0; by apply Hx.\nQed.\n\nLemma diff_xlnx_0 : diff_xlnx 0 = 0.\nProof. by rewrite /diff_xlnx Rminus_0_r xlnx_0 xlnx_1 Rminus_0_r. Qed.\n\nLemma diff_xlnx_1 : diff_xlnx 1 = 0.\nProof. by rewrite /diff_xlnx /Rminus Rplus_opp_r xlnx_0 xlnx_1 Rplus_opp_r. Qed.\n\nLemma derive_diff_xlnx_neg_aux x (Hx : 0 < x < 1) : x < exp (-2) -> 0 < derive_pt diff_xlnx x (derivable_pt_diff_xlnx Hx).\nProof.\nrewrite derive_pt_diff_xlnx; case: Hx => Hx1 Hx2 xltexp2.\napply Ropp_lt_cancel; rewrite Ropp_0 Ropp_involutive.\napply (Rplus_lt_reg_r (-2)); rewrite addRC addRA Rplus_opp_l 2!add0R.\napply exp_lt_inv.\nrewrite exp_ln ; last first.\n  apply Rmult_lt_0_compat => //.\n  apply (Rplus_lt_reg_r x); by rewrite addRC -addRA Rplus_opp_l 2!addR0.\napply (Rlt_trans _ ( (exp (-2)) * (1 - x))).\n  apply Rmult_lt_compat_r => //.\n  apply (Rplus_lt_reg_r x); by rewrite addRC -addRA Rplus_opp_l 2!addR0.\nrewrite -{2}(mulR1 (exp (-2))).\napply Rmult_lt_compat_l; first by apply exp_pos.\napply (Rplus_lt_reg_r (-1)).\nrewrite /Rminus addRC addRA Rplus_opp_l add0R Rplus_opp_r.\napply Ropp_lt_cancel; by rewrite Ropp_involutive Ropp_0.\nQed.\n\nLemma derive_diff_xlnx_pos x (Hx : 0 < x < 1) (pr : derivable_pt diff_xlnx x) : x < exp (-2) -> 0 < derive_pt diff_xlnx x pr.\nProof.\nrewrite (proof_derive_irrelevance _ (derivable_pt_diff_xlnx Hx)).\napply derive_diff_xlnx_neg_aux.\nQed.\n\nLemma MVT_cor1_pderivable_new f a b : forall (prd : pderivable f (fun x => a < x < b)) (prc : forall x (Hx : a <= x <= b), continuity_pt f x),\n  a < b ->\n  exists c (Hc : a < c < b),\n    f b - f a = derive_pt f c (prd c Hc) * (b - a) /\\ a < c < b.\nProof.\nintros prd prc ab.\nhave H0 : forall c : R, a < c < b -> derivable_pt f c.\n  move=> c Hc.\n  apply prd.\n  case: Hc => ? ?; split; fourier.\nhave H1 : forall c : R, a < c < b -> derivable_pt id c.\n  move=> c _; by apply derivable_pt_id.\nhave H2 : forall c, a <= c <= b -> continuity_pt f c.\n  move=> x Hc.\n  by apply prc.\nhave H3 : forall c, a <= c <= b -> continuity_pt id c.\n  move=> x Hc; by apply derivable_continuous_pt, derivable_pt_id.\ncase: (MVT f id a b H0 H1 ab H2 H3) => c [Hc H'].\nexists c.\nexists Hc.\nsplit => //.\ncut (derive_pt id c (H1 c Hc) = derive_pt id c (derivable_pt_id c));\n    [ intro | apply pr_nu ].\nrewrite H (derive_pt_id c) mulR1 in H'.\nrewrite -H' /= /id mulRC.\nf_equal.\nby apply pr_nu.\nQed.\n\nLemma MVT_cor1_pderivable_new_var f a b : forall (prd : pderivable f (fun x => a < x < b)) (prca : continuity_pt f a) (prcb : continuity_pt f b),\n  a < b ->\n  exists c (Hc : a < c < b),\n    f b - f a = derive_pt f c (prd c Hc) * (b - a) /\\ a < c < b.\nProof.\nintros prd prca prcb ab.\nhave prc : forall x (Hx : a <= x <= b), continuity_pt f x.\n  move=> x Hx.\n  case/orP : (orbN (x == a)) ; first by move/eqP => ->.\n  move=> xnota.\n  case/orP : (orbN (x == b)) ; first by move/eqP => ->.\n  move=> xnotb.\n  apply derivable_continuous_pt, prd.\n  split.\n  - apply Rlt_le_neq ; by [apply Hx | move=> /eqP ; apply/negP ; rewrite eq_sym].\n  - apply Rlt_le_neq ; by [apply Hx | move=> /eqP ; apply/negP].\nhave H0 : forall c : R, a < c < b -> derivable_pt f c.\n  move=> c Hc.\n  apply prd.\n  case: Hc => ? ?; split; fourier.\nhave H1 : forall c : R, a < c < b -> derivable_pt id c.\n  move=> c _; by apply derivable_pt_id.\nhave H2 : forall c, a <= c <= b -> continuity_pt f c.\n  move=> x Hc.\n  by apply prc.\nhave H3 : forall c, a <= c <= b -> continuity_pt id c.\n  move=> x Hc; by apply derivable_continuous_pt, derivable_pt_id.\ncase: (MVT f id a b H0 H1 ab H2 H3) => c [Hc H'].\nexists c.\nexists Hc.\nsplit => //.\ncut (derive_pt id c (H1 c Hc) = derive_pt id c (derivable_pt_id c));\n    [ intro | apply pr_nu ].\nrewrite H (derive_pt_id c) mulR1 in H'.\nrewrite -H' /= /id mulRC.\nf_equal.\nby apply pr_nu.\nQed.\n\nLemma derive_sincreasing_interv a b (f:R -> R) (pr: pderivable f (fun x => a < x < b)) (prc : forall x (Hx : a <= x <= b), continuity_pt f x) :\n    a < b ->\n    ((forall t:R, forall (prt : derivable_pt f t), a < t < b -> 0 < derive_pt f t prt) ->\n      forall x y:R, a <= x <= b -> a <= y <= b -> x < y -> f x < f y).\nProof.\nintros H H0 x y H1 H2 H3.\n- apply Rplus_lt_reg_r with (- f x).\n  rewrite Rplus_opp_r.\n  have prd' : pderivable f (fun z => x < z < y).\n    move=> z /= [Hz1 Hz2] ; apply pr.\n    split.\n    - apply (Rle_lt_trans _ x) => // ; by apply H1.\n    - apply (Rlt_le_trans _ y) => // ; by apply H2.\n  have H0' : forall t (Ht : x < t < y), 0 < derive_pt f t (prd' t Ht).\n    move=> z /= [Hz0 Hz1].\n    apply H0.\n    split.\n    - apply (Rle_lt_trans _ x) => // ; by apply H1.\n    - apply (Rlt_le_trans _ y) => // ; by apply H2.\n  have prcx : continuity_pt f x.\n    apply prc ; split ; by apply H1.\n  have prcy : continuity_pt f y.\n    apply prc ; split ; by apply H2.\n  have aux : a < b.\n    apply (Rle_lt_trans _ x) ; first by apply H1.\n    apply (Rlt_le_trans _ y) => // ; by apply H2.\n  case: (MVT_cor1_pderivable_new_var prd' prcx prcy H3); intros x0 [x1 [H7 H8]].\n  unfold Rminus in H7.\n  rewrite H7.\n  apply Rmult_lt_0_compat.\n  by apply H0'.\napply (Rplus_lt_reg_r x).\nby rewrite addRC -addRA Rplus_opp_l 2!addR0.\nQed.\n\nLemma diff_xlnx_sincreasing_0_Rinv_e2 : forall x y : R, 0 <= x <= exp (-2) -> 0 <= y <= exp (-2) -> x < y -> diff_xlnx x < diff_xlnx y.\nProof.\napply derive_sincreasing_interv.\n- move=> x /= [Hx1 Hx2].\n  apply derivable_pt_diff_xlnx.\n  split => //.\n  apply: (@Rlt_trans _ _ _ Hx2 _).\n  by apply exp_opp_2_lt_1.\n- move=> x /= Hx.\n  rewrite /diff_xlnx.\n  apply continuity_pt_minus ; last by apply continue_xlnx.\n  apply (continuity_pt_comp (fun x => 1 - x) xlnx); last by apply continue_xlnx.\n  rewrite /Rminus.\n  apply continuity_pt_plus ; first by apply continuity_pt_const.\n  apply continuity_pt_opp.\n  apply derivable_continuous_pt.\n  by apply derivable_pt_id.\n- by apply exp_pos.\n- move => t prt [Ht1 Ht2].\n  apply derive_diff_xlnx_pos => //.\n  split => // ; apply (Rlt_trans _ (exp (-2))) => //.\n  by apply exp_opp_2_lt_1.\nQed.\n\nLemma xlnx_ineq x : 0 <= x <= exp (-2) -> xlnx x <= xlnx (1-x).\nProof.\nmove=> [Hx1 Hx2].\napply Rge_le, Rminus_ge, Rle_ge.\nrewrite -diff_xlnx_0 -/(diff_xlnx x).\ncase/orP : (orbN (0 == x)) ; last move=> xnot0 ; first by [move=> /eqP <- ; apply Rle_refl].\napply Rlt_le, diff_xlnx_sincreasing_0_Rinv_e2.\n- split ; by [apply Rle_refl | apply Rlt_le, exp_pos].\n- by split.\napply Rlt_le_neq => // /eqP ; by apply/negP.\nQed.\n\nEnd diff_xlnx.\n\nDefinition xlnx_delta a := fun x => xlnx (x + a) - xlnx x.\n\nLemma derivable_xlnx_delta eps (Heps : 0 < eps < 1) x (Hx : 0 < x < 1 - eps) :\n  derivable_pt (xlnx_delta eps) x.\nProof.\nrewrite /xlnx_delta.\napply derivable_pt_minus.\n- apply (derivable_pt_comp (fun x => x + eps) xlnx).\n    apply derivable_pt_plus ; first by apply derivable_pt_id.\n    by apply derivable_pt_const.\n  apply derivable_pt_xlnx.\n  apply Rplus_le_lt_0_compat ; by [apply Heps | apply Rlt_le, Hx].\n- by apply derivable_pt_xlnx, Hx.\nDefined.\n\nLemma derive_pt_xlnx_delta eps (Heps : 0 < eps < 1) x (Hx : 0 < x < 1 - eps) :\n  derive_pt (xlnx_delta eps) x (derivable_xlnx_delta Heps Hx) = ln (x + eps) - ln x.\nProof.\nrewrite derive_pt_minus derive_pt_comp derive_pt_plus derive_pt_id derive_pt_const derive_pt_xlnx ; last first.\n  apply Rplus_lt_0_compat ; by [apply Hx | apply Heps].\nrewrite derive_pt_xlnx ; last by apply Hx.\nfield.\nQed.\n\nLemma increasing_xlnx_delta eps (Heps : 0< eps < 1) :\n  forall x y : R, 0 <= x <= 1 - eps -> 0 <= y <= 1 - eps -> x < y ->\n                  xlnx_delta eps x < xlnx_delta eps y.\nProof.\napply derive_sincreasing_interv.\n- move=> x /= [Hx1 Hx2] ; rewrite /xlnx_delta.\n  apply derivable_pt_minus.\n  - apply (derivable_pt_comp (fun x => x + eps) xlnx).\n      apply derivable_pt_plus ; first by apply derivable_pt_id.\n      by apply derivable_pt_const.\n    apply derivable_pt_xlnx.\n    apply Rplus_lt_0_compat => // ; by apply Heps.\n  - by apply derivable_pt_xlnx.\n- move=> x /= [Hx1 Hx2] ; rewrite /xlnx_delta.\n  apply continuity_pt_minus.\n  - apply (continuity_pt_comp (fun x => x + eps) xlnx); last by apply continue_xlnx.\n      apply continuity_pt_plus ; first by apply derivable_continuous_pt, derivable_pt_id.\n      by apply continuity_pt_const.\n  - by apply continue_xlnx.\n- by apply Rgt_lt, Rgt_minus, Rlt_gt, Heps.\n- move=> t prd Ht.\n  rewrite (proof_derive_irrelevance _ (derivable_xlnx_delta Heps Ht)) derive_pt_xlnx_delta.\n  apply Rgt_lt, Rgt_minus, Rlt_gt, ln_increasing ; first by apply Ht.\n  rewrite -{1}(addR0 t).\n  by apply Rplus_lt_compat_l, Heps.\nQed.\n\nLemma xlnx_delta_bound eps : 0 < eps <= exp (-2) ->\n  forall x, 0 <= x <= 1 - eps -> Rabs (xlnx_delta eps x) <= - xlnx eps.\nProof.\nmove=> [Heps1 Heps2] x [Hx1 Hx2].\napply Rabs_Rle.\n- apply (Rle_trans _ (xlnx_delta eps (1 - eps))).\n    case/orP : (orbN (x == 1 - eps)) ; last move=> xnot0 ; first by [move=> /eqP -> ; apply Rle_refl].\n    apply Rlt_le, increasing_xlnx_delta => //.\n    - split => //.\n      apply (Rle_lt_trans _ (exp (-2))) => //.\n      by apply exp_opp_2_lt_1.\n    - split ; by [apply (Rle_trans _ x) | apply Rle_refl].\n    - apply Rlt_le_neq => // /eqP ; by apply/negP.\n  rewrite /xlnx_delta /Rminus -addRA Rplus_opp_l addR0 xlnx_1 add0R.\n  apply Ropp_le_cancel ; rewrite 2!Ropp_involutive.\n  apply xlnx_ineq.\n  split => // ; by apply Rlt_le.\nrewrite Ropp_involutive.\nrewrite (_ : xlnx eps = xlnx_delta eps 0) ; last first.\n  rewrite /xlnx_delta.\n  by rewrite add0R xlnx_0 Rminus_0_r.\ncase/orP : (orbN (0 == x)) ; last move=> xnot0 ; first by [move=> /eqP <- ; apply Rle_refl].\napply Rlt_le, increasing_xlnx_delta => //.\n- split => //.\n  apply (Rle_lt_trans _ (exp (-2))) => //.\n  by apply exp_opp_2_lt_1.\n- split ; by [apply (Rle_trans _ x) | apply Rle_refl].\n- apply Rlt_le_neq => // /eqP ; by apply/negP.\nQed.\n\nLemma Rabs_xlnx a (Ha : 0 <= a <= exp(-2)) x y :\n  0 <= x <= 1 -> 0 <= y <= 1 -> Rabs (x - y) <= a ->\n  Rabs (xlnx x - xlnx y) <= - xlnx a.\nProof.\nmove=> [Hx1 Hx2] [Hy1 Hy2] H.\ncase : (Rtotal_order x y) ; last case ; move => Hcase.\n- have Haux : y = x + Rabs (x - y).\n    rewrite /R_dist -Rabs_Ropp Rabs_pos_eq.\n      by rewrite Ropp_plus_distr Ropp_involutive addRA Rplus_opp_r add0R.\n    apply Ropp_le_cancel; rewrite Ropp_0 Ropp_involutive.\n    by apply Rle_minus, Rlt_le.\n  rewrite Haux -Rabs_Ropp Ropp_plus_distr Ropp_involutive addRC.\n  apply (Rle_trans _ (- xlnx (Rabs (x - y)))).\n    apply xlnx_delta_bound.\n    - split.\n      - by apply Rabs_pos_lt, Rlt_not_eq, Rlt_minus.\n      - apply (Rle_trans _ a) => //; by apply Ha.\n    - split => //.\n      apply (Rplus_le_reg_r (Rabs (x - y))); by rewrite /Rminus -addRA Rplus_opp_l addR0 -Haux.\n  apply Ropp_le_cancel ; rewrite 2!Ropp_involutive.\n  apply xlnx_decreasing_0_Rinv_e => //.\n  - split; first by apply Rabs_pos.\n    apply (Rle_trans _ a) => //.\n    apply (Rle_trans _ (exp (- 2))); first by apply Ha.\n    apply Rlt_le, exp_increasing, Ropp_lt_contravar; fourier.\n  - split; first by apply Ha.\n    apply (Rle_trans _ (exp (-2))); first by apply Ha.\n    apply Rlt_le, exp_increasing, Ropp_lt_contravar; fourier.\n- subst x ; rewrite /Rminus Rplus_opp_r Rabs_R0.\n  apply Ropp_le_cancel ; rewrite Ropp_involutive Ropp_0.\n  case/orP : (orbN (0 == a)); last move=> anot0.\n    by [move=> /eqP <- ; rewrite xlnx_0 ; apply Rle_refl].\n  apply Rlt_le, xlnx_neg.\n  split.\n  - apply Rlt_le_neq; first by apply Ha.\n    move/eqP; by apply/negP.\n  - apply (Rle_lt_trans _ (exp (-2))); first by apply Ha.\n    by apply exp_opp_2_lt_1.\n- apply Rgt_lt in Hcase.\n  have Haux : x = y + Rabs (x - y).\n    rewrite Rabs_pos_eq.\n      by rewrite addRC /Rminus -addRA Rplus_opp_l addR0.\n    by apply Rge_le, Rge_minus, Rle_ge, Rlt_le.\n  rewrite Rabs_minus_sym in H Haux.\n  rewrite Haux.\n  apply (Rle_trans _ (- xlnx (Rabs (y - x)))).\n    apply xlnx_delta_bound.\n    - split.\n      - by apply Rabs_pos_lt, Rlt_not_eq, Rlt_minus.\n      - apply (Rle_trans _ a) => //; by apply Ha.\n    - split => //.\n      apply (Rplus_le_reg_r (Rabs (y - x))); by rewrite /Rminus -addRA Rplus_opp_l addR0 -Haux.\n  apply Ropp_le_cancel ; rewrite 2!Ropp_involutive.\n  apply xlnx_decreasing_0_Rinv_e => //.\n  + split; first by apply Rabs_pos.\n    apply (Rle_trans _ a) => //.\n    apply (Rle_trans _ (exp (-2))); first by apply Ha.\n    apply Rlt_le, exp_increasing, Ropp_lt_contravar; fourier.\n  - split; first by apply Ha.\n    apply (Rle_trans _ (exp (-2))); first by apply Ha.\n    apply Rlt_le, exp_increasing, Ropp_lt_contravar; fourier.\nQed.\n\nEnd xlnx_sect.\n", "meta": {"author": "johnbender", "repo": "shannon", "sha": "552c66f7c76ad687430f4fb8122a2a2b94b741ee", "save_path": "github-repos/coq/johnbender-shannon", "path": "github-repos/coq/johnbender-shannon/shannon-552c66f7c76ad687430f4fb8122a2a2b94b741ee/ln_facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6524618680292381}}
{"text": "From Categories Require Import Essentials.Notations.\nFrom Categories Require Import Essentials.Types.\nFrom Categories Require Import Essentials.Facts_Tactics.\nFrom Categories Require Import Category.Main.\nFrom Categories Require Import Functor.Functor Functor.Functor_Ops.\nFrom Categories Require Import Cat.Cat.\nFrom Categories Require Import NatTrans.NatTrans NatTrans.Func_Cat.\n\nLocal Open Scope nattrans_scope.\n\n(** If all components of a natural transformation are monic then\nso is that natural transformation. *)\nSection is_Monic_components_is_Monic.\n  Context\n    {C D : Category}\n    {F G : (C –≻ D)%functor}\n    (N : F –≻ G)\n    (H : ∀ c, is_Monic (Trans N c))\n  .\n\n  Definition is_Monic_components_is_Monic :\n    @is_Monic (Func_Cat _ _) _ _ N.\n  Proof.\n    intros I g h H2.\n    apply NatTrans_eq_simplify.\n    extensionality x.\n    apply H.\n    apply (fun x => f_equal (fun w => Trans w x) H2).\n  Qed.\n\nEnd is_Monic_components_is_Monic.\n\n(** If all components of a natural transformation are epic then\nso is that natural transformation. *)\nSection is_Epic_components_is_Epic.\n  Context\n    {C D : Category}\n    {F G : (C –≻ D)%functor}\n    (N : F –≻ G)\n    (H : ∀ c, is_Epic (Trans N c))\n  .\n\n  Definition is_Epic_components_is_Epic :\n    @is_Epic (Func_Cat _ _) _ _ N.\n  Proof.\n    intros I g h H2.\n    apply NatTrans_eq_simplify.\n    extensionality x.\n    apply H.\n    apply (fun x => f_equal (fun w => Trans w x) H2).\n  Qed.\n\nEnd is_Epic_components_is_Epic.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/Categories/NatTrans/Morphisms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6524618651296086}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.lemma_betweennotequal.\nRequire Import ProofCheckingEuclid.lemma_congruencesymmetric.\nRequire Import ProofCheckingEuclid.lemma_extensionunique.\nRequire Import ProofCheckingEuclid.lemma_localextension.\nRequire Import ProofCheckingEuclid.lemma_orderofpoints_ABC_ACD_BCD.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\n(* Originally known as lemma_3_7a *)\nLemma lemma_orderofpoints_ABC_BCD_ACD :\n\tforall A B C D,\n\tBetS A B C -> BetS B C D ->\n\tBetS A C D.\nProof.\n\tintros A B C D.\n\tintros BetS_A_B_C.\n\tintros BetS_B_C_D.\n\tpose proof (lemma_betweennotequal _ _ _ BetS_A_B_C) as (neq_B_C & neq_A_B & neq_A_C).\n\tpose proof (lemma_betweennotequal _ _ _ BetS_B_C_D) as (neq_C_D & _ & neq_B_D).\n\tpose proof (lemma_localextension _ _ _ neq_A_C neq_C_D) as (E & BetS_A_C_E & Cong_CE_CD).\n\tapply lemma_congruencesymmetric in Cong_CE_CD as Cong_CD_CE.\n\tpose proof (lemma_orderofpoints_ABC_ACD_BCD _ _ _ _ BetS_A_B_C BetS_A_C_E) as BetS_B_C_E.\n\tpose proof (lemma_extensionunique _ _ _ _ BetS_B_C_D BetS_B_C_E Cong_CD_CE) as eq_D_E.\n\tassert (BetS A C D) as BetS_A_C_D by (rewrite eq_D_E; exact BetS_A_C_E).\n\texact BetS_A_C_D.\nQed.\n\nEnd Euclid.\n\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_orderofpoints_ABC_BCD_ACD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6524618642523641}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_collinearorder.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_ray4.\n\nSection Euclid.\n\nContext `{Ax1:euclidean_neutral_ruler_compass}.\n\nLemma lemma_ABCequalsCBA : \n   forall A B C, \n   nCol A B C ->\n   CongA A B C C B A.\nProof.\nintros.\nassert (~ eq B A).\n {\n intro.\n assert (eq A B) by (conclude lemma_equalitysymmetric).\n assert (Col A B C) by (conclude_def Col ).\n contradict.\n }\nassert (~ eq C B).\n {\n intro.\n assert (Col C B A) by (conclude_def Col ).\n assert (Col A B C) by (forward_using lemma_collinearorder).\n contradict.\n }\nlet Tf:=fresh in\nassert (Tf:exists E, (BetS B A E /\\ Cong A E C B)) by (conclude lemma_extension);destruct Tf as [E];spliter.\nassert (~ eq B C).\n {\n intro.\n assert (Col A B C) by (conclude_def Col ).\n contradict.\n }\nassert (neq A B) by (conclude lemma_inequalitysymmetric).\nlet Tf:=fresh in\nassert (Tf:exists F, (BetS B C F /\\ Cong C F A B)) by (conclude lemma_extension);destruct Tf as [F];spliter.\nassert (Cong B A F C) by (forward_using lemma_doublereverse).\nassert (BetS F C B) by (conclude axiom_betweennesssymmetry).\nassert (Cong B E F B) by (conclude cn_sumofparts).\nassert (Cong F B B F) by (conclude cn_equalityreverse).\nassert (Cong B E B F) by (conclude lemma_congruencetransitive).\nassert (Cong B F B E) by (conclude lemma_congruencesymmetric).\nassert (Cong E F F E) by (conclude cn_equalityreverse).\nassert (Out B A E) by (conclude lemma_ray4).\nassert (Out B C F) by (conclude lemma_ray4).\nassert (CongA A B C C B A) by (conclude_def CongA ).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_ABCequalsCBA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.652461858721}}
{"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(*****************************************************************************)\n(*                                                                           *)\n(*          Buchberger : ordering: lexi and total                            *)\n(*                                                                           *)\n(*          Laurent Thery \t                                             *)\n(*                                                                           *)\n(*****************************************************************************)\n\nRequire Import Eqdep.\nSection lexi_order.\nRequire Import Monomials.\n\nInductive orderc : forall n : nat, mon n -> mon n -> Prop :=\n  | lo1 :\n      forall (n a b : nat) (p : mon n),\n      b < a -> orderc (S n) (c_n n a p) (c_n n b p)\n  | lo2 :\n      forall (n a b : nat) (p q : mon n),\n      orderc n p q -> orderc (S n) (c_n n a p) (c_n n b q).\nHint Resolve lo1 lo2.\nRequire Import Arith.\nRequire Import Compare_dec.\n\nTheorem orderc_dec :\n forall (n : nat) (a b : mon n), {orderc n a b} + {orderc n b a} + {a = b}.\nintros n a; elim a; auto.\nintro b.\nrewrite <- (mon_0 b); auto.\nintros d n0 m H' b; try assumption.\nrewrite <- (proj_ok d b).\ncase (H' (pmon2 (S d) b)).\nintro H'0; case H'0.\nintro H'1.\nleft; left; auto.\nintro H'1; left; right; auto.\nintro H'0.\nelim (lt_eq_lt_dec n0 (pmon1 (S d) b)); [ intro H'1; elim H'1 | idtac ];\n intro H'2; auto.\nleft; right; auto.\nrewrite H'0; auto.\nright; rewrite H'0; rewrite H'2; auto.\nleft; left; rewrite H'0; auto.\nQed.\n\nDefinition degc : forall n : nat, mon n -> nat.\nintros n H'; elim H'.\nexact 0.\nintros d n1 M n2; exact (n1 + n2).\nDefined.\n\nInductive total_orderc : forall n : nat, mon n -> mon n -> Prop :=\n  | total_orderc0 :\n      forall (n : nat) (p q : mon n),\n      degc n p < degc n q -> total_orderc n p q\n  | total_orderc1 :\n      forall (n : nat) (p q : mon n),\n      degc n p = degc n q -> orderc n p q -> total_orderc n p q.\nHint Resolve total_orderc0 total_orderc1.\nRequire Import LetP.\n\nTheorem total_orderc_dec :\n forall (n : nat) (a b : mon n),\n {total_orderc n a b} + {total_orderc n b a} + {a = b}.\nintros n a b.\napply LetP with (A := nat) (h := degc n a).\nintros u H'; apply LetP with (A := nat) (h := degc n b).\nintros u0 H'0.\ncase (le_lt_dec u u0); auto.\nintro H'1; case (le_lt_eq_dec u u0); auto.\nrewrite H'0; rewrite H'; auto.\nrewrite H'0; rewrite H'; intro H'2; case (orderc_dec n a b); auto.\nintro H'3; case H'3; auto.\nrewrite H'0; rewrite H'; auto.\nQed.\nEnd lexi_order.", "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/buchberger/LexiOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.652461858721}}
{"text": "(* fmformulas library for yalla *)\n\n\n\n(* output in Type *)\n\n\n(** * Order structure and finite multiset structure on formulas *)\n\nRequire Import Injective.\nRequire Import nattree.\nRequire Import fmsetlist_Type.\n\nRequire Export formulas.\n\n(** ** Encoding of [formula] into [nat]-labelled trees for ordering *)\n\n(** Embedding of [Atom] into [nat] *)\nDefinition a2n := yalla_ax.a2n.\nDefinition n2a := yalla_ax.n2a.\nDefinition a2a_n := yalla_ax.a2a_n.\n\n(** Embedding of [formula] into [nattree] *)\nFixpoint form2nattree A :=\nmatch A with\n| var X => Bnt 1 (Bnt (a2n X) Lnt Lnt) Lnt\n| covar X => Bnt 2 (Bnt (a2n X) Lnt Lnt) Lnt\n| one => Bnt 3 Lnt Lnt\n| bot => Bnt 4 Lnt Lnt\n| tens A B => Bnt 5 (form2nattree A) (form2nattree B)\n| parr A B => Bnt 6 (form2nattree A) (form2nattree B)\n| zero => Bnt 7 Lnt Lnt\n| top => Bnt 8 Lnt Lnt\n| aplus A B => Bnt 9 (form2nattree A) (form2nattree B)\n| awith A B => Bnt 10 (form2nattree A) (form2nattree B)\n| oc A => Bnt 11 (form2nattree A) Lnt\n| wn A => Bnt 12 (form2nattree A) Lnt\nend.\n\nFixpoint nattree2form t :=\nmatch t with\n| Bnt 1 (Bnt k Lnt Lnt) Lnt => var (n2a k)\n| Bnt 2 (Bnt k Lnt Lnt) Lnt => covar (n2a k)\n| Bnt 3 Lnt Lnt => one\n| Bnt 4 Lnt Lnt => bot\n| Bnt 5 t1 t2 => tens (nattree2form t1) (nattree2form t2)\n| Bnt 6 t1 t2 => parr (nattree2form t1) (nattree2form t2)\n| Bnt 7 Lnt Lnt => zero\n| Bnt 8 Lnt Lnt => top\n| Bnt 9 t1 t2 => aplus (nattree2form t1) (nattree2form t2)\n| Bnt 10 t1 t2 => awith (nattree2form t1) (nattree2form t2)\n| Bnt 11 t1 Lnt => oc (nattree2form t1)\n| Bnt 12 t1 Lnt => wn (nattree2form t1)\n| _ => one\nend.\n\nLemma form_nattree_section : forall A, nattree2form (form2nattree A) = A.\nProof.\ninduction A ; simpl ;\n  try rewrite IHA1 ; try rewrite IHA2 ;\n  try rewrite IHA ;\n  try rewrite a2a_n ; try reflexivity.\nQed.\n\n\n(** ** [BOrder] structure (total order with value into [bool]) *)\n\nInstance border_formula : BOrder.\nProof.\neapply border_inj.\neapply comp_inj.\n- apply nattree2nat_inj.\n- eapply section_inj.\n  apply form_nattree_section.\nDefined.\n\n\n(** ** Finite multi-sets over [formula] *)\n\nInstance fmset_formula : FinMultiset (SortedList _) formula :=\n  FMConstr_slist border_formula.\n\n\n", "meta": {"author": "olaure01", "repo": "yalla", "sha": "9c6a66fa3a3d68b5a21ce7fa695402a0f2dda4d7", "save_path": "github-repos/coq/olaure01-yalla", "path": "github-repos/coq/olaure01-yalla/yalla-9c6a66fa3a3d68b5a21ce7fa695402a0f2dda4d7/yalla/fmformulas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.6524618540668807}}
{"text": "(**********************************************************************)\n(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the 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 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, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n(**********************************************************************)\n\n(**********************************************************************)\n(*                     not_church_numerals                            *)\n(*                                                                    *)\n(*                          Barry Jay                                 *)\n(*                                                                    *)\n(**********************************************************************)\n\n\nRequire Import List Omega Closure_calculus.\n\n\n(* primitive recursion \n      https://en.wikipedia.org/wiki/Lambda_calculus#Arithmetic_in_lambda_calculus\n *)\n\n(* \nThe Church numeral n is an iterator, that maps f and x to f^n (x). \nChurch numerals don't work in closure calculus, at least with the traditinal account of \npredecessor, since pred zero reduces to a normal form which, unlike zero, \nhas a non-empty environment.  \n*) \n\nDefinition zero_c:= ff. (* \\fx. x *) \nDefinition succ_c := \nAbs Iop 2 (Abs (Add Iop 2 (Ref 2)) 1 (Abs (Add (Add Iop 2 (Ref 2)) 1 (Ref 1)) 0 \n    (Tag (Ref 1) (Tag (Tag (Ref 2) (Ref 1)) (Ref 0))))). \n(* \\nfx.f(nfx) *) \n\nFixpoint church n :=\nmatch n with\n  | 0 => ff\n  | S n => Abs (Add Iop 2 (church n)) 1 (Abs (Add (Add Iop 2 (Ref 2)) 1 (Ref 1)) 0 \n               (Tag (Ref 1) (Tag (Tag (Ref 2) (Ref 1)) (Ref 0))))\nend.\n\nLemma church_numerals_are_normal: forall n, normal (church n). \nProof.  \ninduction n; unfold church; fold church; unfold zero, value; split_all. unfold ff; auto.\nrepeat eapply2 nf_abs.  \nQed. \n\nHint Resolve church_numerals_are_normal. \n\nLemma succ_church: forall n, seq_red (App succ_c (church n)) (church (S n)).\nProof. intro; unfold succ_c. repeat eapply2 succ_red.  Qed. \n\n\nDefinition is_zero_c := Abs Iop 0 (Tag (Tag (Ref 0) (Abs Iop 0 ff)) tt).\n\nLemma is_zero_c_zero_c: seq_red (App is_zero_c zero_c) tt .\nProof. unfold is_zero_c, zero_c, ff, tt; split_all. repeat eapply2 succ_red. Qed.\n\nLemma is_zero_c_succ_c: forall n, seq_red (App is_zero_c (church (S n))) ff .\nProof. intros. unfold church, is_zero_c, tt, ff, church. repeat eapply2 succ_red. Qed. \n\n\nDefinition my_pred_c :=\nAbs Iop 2 (Abs (Add Iop 2 (Ref 2)) 1 (Abs (Add (Add Iop 2 (Ref 2)) 1 (Ref 1)) 0 \n    (Tag (Tag (Tag (Ref 2) (Abs (Add (Add Iop 1 (Ref 1)) 0 (Ref 0)) 4\n     (Abs (Add (Add (Add Iop 1 (Ref 1)) 0 (Ref 0)) 4 (Ref 4)) 3 \n        (Tag (Ref 3) (Tag (Ref 4) (Ref 1))))))\n              (Abs Iop 5 (Ref 0)))\n         Iop)))\n  (* λnfx. n (\\gh. h(gf))(\\u.x)(\\u.u) *) \n.\n\nDefinition pred_0_nf := \nAbs (Add Iop 2 (Abs Iop 1 (Abs Iop 0 (Ref 0)))) 1\n     (Abs (Add (Add Iop 2 (Ref 2)) 1 (Ref 1)) 0\n        (Tag\n           (Tag\n              (Tag (Ref 2)\n                 (Abs (Add (Add Iop 1 (Ref 1)) 0 (Ref 0)) 4\n                    (Abs (Add (Add (Add Iop 1 (Ref 1)) 0 (Ref 0)) 4 (Ref 4)) 3 (Tag (Ref 3) (Tag (Ref 4) (Ref 1))))))\n              (Abs Iop 5 (Ref 0))) Iop)).\n\n \nLemma pred_0_val : seq_red (App my_pred_c zero_c) pred_0_nf. \nProof. unfold my_pred_c, zero_c, ff, tt. repeat eapply2 succ_red.  Qed. \n\n\nLemma pred_zero_fails: ~(seq_red (App my_pred_c zero_c) zero_c).\nProof.\nintro. \nassert (exists n, seq_red zero_c n /\\ seq_red pred_0_nf n).\neapply2 closure_confluence.  eapply2 pred_0_val. split_all.  \nassert(irreducible zero_c seq_red1). \neapply2 irreducible_iff_normal. \nreplace zero_c with (church 0) by auto. eapply2 church_numerals_are_normal. \nassert(x = zero_c). \ninversion H0; auto. \nassert False by eapply2 H1. contradiction. subst. \nassert(irreducible pred_0_nf seq_red1). \neapply2 irreducible_iff_normal. \nunfold pred_0_nf;  auto 20. \nassert(zero_c = pred_0_nf). \ninversion H2; auto. \nassert False by eapply2 H3. contradiction.  discriminate. \nQed. \n\n", "meta": {"author": "Barry-Jay", "repo": "Intensional-computation", "sha": "de09d3e646c1ea50127c5033b46576d8b4773259", "save_path": "github-repos/coq/Barry-Jay-Intensional-computation", "path": "github-repos/coq/Barry-Jay-Intensional-computation/Intensional-computation-de09d3e646c1ea50127c5033b46576d8b4773259/Closure_calculus/not_church_numerals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6524618513011988}}
{"text": "\nRequire Import core.\n\nInductive HomotopyCalculus :=\n | Id                 | Refl\n | Inh                | Inc\n | Squash             | InhRec\n | TransU             | TransInvU\n | TransURef          | Singl\n | MapOnPath          | AppOnPath\n | HExt               | EquivEq\n | EquivEqRef         | TransUEquivEq\n | IdP                | MapOnPathD\n | IdS                | MapOnPathS\n | AppOnPathD         | Circle\n | Base               | HLoop\n | CircleRec          | I\n | I0                 | I1\n | Line               | IntRec\n | Undef: Loc -> HomotopyCalculus.\n\n(*\n   prop : U -> U\n   prop A = (a b : A) -> Id A a b\n   Sigma : (A : U) (B : A -> U) -> U\n   Sigma A B = (x : A) * B x\n   fiber : (A B : U) (f : A -> B) (y : B) -> U\n   fiber A B f y = Sigma A (\\x -> Id B (f x) y)\n   id : (A : U) -> A -> A\n   id A a = a\n   singl : (A : U) -> A -> U\n   singl A a = Sigma A (Id A a)\n   pathTo : (A:U) -> A -> U\n   pathTo A = fiber A A (id A)\n   sId : (A : U) (a : A) -> pathTo A a\n   sId A a = (a, refl A a)\n   IdS : (A : U) (F : A -> U) (a0 a1 : A) (p : Id A a0 a1) -> F a0 -> F a1 -> U\n   IdS A F a0 a1 p = IdP (F a0) (F a1) (mapOnPath A U F a0 a1 p)\n\n   Primitives\n\n   Id : (A : U) (a b : A) -> U\n   refl : (A : U) (a : A) -> Id A a a\n   inh : U -> U\n   inc : (A : U) -> A -> inh A\n   squash : (A : U) -> prop (inh A)\n   inhrec : (A : U) (B : U) (p : prop B) (f : A -> B) (a : inh A) -> B\n   contrSingl : (A : U) (a b : A) (p : Id A a b) -> Id (singl A a) (a, refl A a) (b, p)\n\n   equivEq : (A B : U) (f : A -> B) (s : (y : B) -> fiber A B f y)\n             (t : (y : B) -> (v : fiber A B f y) ->\n             Id (fiber A B f y) (s y) v) -> Id U A B\n\n   transport : (A B : U) -> Id U A B -> A -> B\n   transpInv : (A B : U) -> Id U A B -> B -> A\n\n   transportRef : (A : U) (a : A) -> Id A a (transport A A (refl U A) a)\n\n   equivEqRef : (A : U) -> (s : (y : A) -> pathTo A y) ->\n                (t : (y : A) -> (v : pathTo A y) ->\n                Id (pathTo A y) (s y) v) ->\n                Id (Id U A A) (refl U A) (equivEq A A (id A) s t)\n\n   transpEquivEq : (A B : U) -> (f : A -> B) (s : (y : B) -> fiber A B f y) ->\n                   (t : (y : B) -> (v : fiber A B f y) -> Id (fiber A B f y) (s y) v) ->\n                   (a : A) -> Id B (f a) (transport A B (equivEq A B f s t) a)\n\n   appOnPathD :  (A : U) (F : A -> U) (f g : (x : A) -> F x) -> Id ((x : A) -> F x) f g ->\n                 (a0 a1 : A) (p : Id A a0 a1) -> IdS A F a0 a1 p  (f a0) (g a1)\n\n\n   mapOnPath : (A B : U) (f : A -> B) (a b : A) (p : Id A a b) -> Id B (f a) (f b)\n   appOnPath : (A B : U) (f g : A -> B) (a b : A) (q : Id (A -> B) f g) (p : Id A a b) -> Id B (f a) (g b)\n\n   IdP : (A B : U) -> Id U A B -> A -> B -> U\n\n   mapOnPathD : (A:U) (F: A -> U) (f: (x:A) -> F x) (a0 a1: A) (p: Id A a0 a1) -> IdS A F a0 a1 p  (f a0) (f a1)\n   mapOnPathS : (A:U) (F: A -> U) (C: U) (f: (x:A) -> F x -> C)\n                (a0 a1 : A) (p : Id A a0 a1) (b0 : F a0) (b1 : F a1)\n                (q : IdS A F a0 a1 p b0 b1) -> Id C (f a0 b0) (f a1 b1)\n\n   funHExt : (A : U) (B : A -> U) (f g : (a : A) -> B a) ->\n             ((x y : A) -> (p : Id A x y) -> IdS A B x y p (f x) (g y)) ->\n             Id ((y : A) -> B y) f g\n\n   S1 : U\n   base : S1\n   loop : Id S1 base base\n   S1rec : (F : S1 -> U) (b : F base) (l : IdS S1 F base base loop b b) (x : S1) -> F x\n   I : U\n   I0 : I\n   I1 : I\n   line : Id I I0 I1\n   intrec : (F : I -> U) (s : F I0) (e : F I1) (l : IdS I F I0 I1 line s e) (x : I) -> F x\n\n*)\n", "meta": {"author": "nponeccop", "repo": "infinity", "sha": "7600ac735a48517021e46a477ec143f0b78dc5e6", "save_path": "github-repos/coq/nponeccop-infinity", "path": "github-repos/coq/nponeccop-infinity/infinity-7600ac735a48517021e46a477ec143f0b78dc5e6/src/homotopy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6524551914962088}}
{"text": "Require Import Coq.Init.Specif.\n\nTheorem proj_left : forall (A B : Type), A * B -> A.\nProof.\n  intros A B H.\n  destruct H.\n  apply a.\nQed.\n\nTheorem proj_right : forall (A B : Type), A * B -> B.\nProof.\n  intros A B H.\n  destruct H.\n  apply b.\nQed.\n\nTheorem inj_left : forall (A B : Type), A -> A + B.\nProof.\n  intros A B H.\n  left. apply H.\nQed.\n\nTheorem inj_right : forall (A B : Type), B -> A + B.\nProof.\n  intros A B H.\n  right. apply H.\nQed.\n\nInductive Sigma (A : Type) (B : A -> Type) :=\n  | element (a : A) (b : (B a)).\n\nCheck nat = bool.\n\nCheck existT.\n\nCheck sigT.\n\nDefinition homotopy (A : Type) (P : A -> Type) (f g: forall (a : A), P a): Type\n  := forall (a : A), (f a) = (g a).\n\nDefinition homotopy_ind (A B : Type) (f g: A -> B): Type\n  := homotopy A (fun (a : A) => B) f g.\n  \nDefinition id (A : Type) (a : A) := a.\n\nCheck id.\n\nCheck forall (a : nat), (fun (a: nat) => bool) a.\nCheck forall (a : nat), (fun (a: nat) => bool) a.\n\nDefinition Pi (A : Type) (P : A -> Type) : Type := forall (a : A), P a.\n\nCheck Pi.\n\nCheck existT.\n\n(* TODO use existT f such that isequiv f *)\nDefinition type_equiv (A B : Type) : Type :=\n  sigT (fun (f : A -> B) => (\n    prod\n    (sigT (fun (h : B -> A) => (homotopy_ind A A (fun (a : A) => (h (f a))) (id A))))\n    (sigT (fun (g : B -> A) => (homotopy_ind B B (fun (b : B) => (f (g b))) (id B))))\n  )).\n\n(*\nTODO (more specific things)\n    - research Sigma and Pi types (use sig_t in the documentation page\n    - try to prove split_prob_general\n    - convert theorems at the bottom into levelled versions\n*)\n\n(*\nNext steps (general)\n  - make sure that the axioms are consistent\n  - are there any contradictions?\n    - step 1: prove that all of the non-induction rules are consistent\n    - step 2: prove that adding the induction rules keeps the system consistent\n*)", "meta": {"author": "Jonathan-Ackerman", "repo": "aresty-research-probability", "sha": "8b7acdc87b90fca845e19d34070977f2b507da1f", "save_path": "github-repos/coq/Jonathan-Ackerman-aresty-research-probability", "path": "github-repos/coq/Jonathan-Ackerman-aresty-research-probability/aresty-research-probability-8b7acdc87b90fca845e19d34070977f2b507da1f/Utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6524551798370993}}
{"text": "(* Exercise 77 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_077 : (exists x : D, forall y : D, P x \\/ P y) -> exists x : D, P x.\nProof.\nimp_i a1.\nexi_e (exists x:D, forall y:D, P x \\/ P y) a a2.\nhyp a1.\ndis_e (P a \\/ P a) a3 a3.\nall_e (forall y:D, P a \\/ P y) a.\nhyp a2.\nexi_i a.\nhyp a3.\nexi_i a.\nhyp a3.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred077.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.6522454487008987}}
{"text": "Require Import ssreflect Arith.\nRequire Import Arith.EqNat.\nRequire Import Arith.Compare_dec.\nRequire Import List.\nRequire Import Omega.\nRequire Import untypedLambda.\n\n(*Question 1.4.2*)\nTheorem no_index_sub: forall (t u: term) (i: nat), (C i t) -> substitution i t u = t.\nProof.\n  induction t.\n  simpl.\n  intros.\n  Search _ (_ < _).\n  have:(beq_nat i v = false).\n  apply beq_nat_false_iff.\n  intro.\n  rewrite H0 in H.\n  apply Lt.lt_irrefl in H.\n  done.\n  move => h0.\n  rewrite h0.\n  done.\n  simpl.\n  intros.\n  rewrite -lambda_equivalence.\n  apply IHt.\n  done.\n  simpl.\n  intros.\n  rewrite app_equivalence.\n  split.\n  apply IHt1.\n  apply H.\n  apply IHt2.\n  apply H.\nQed.\n\nLemma substitution_invariance: forall (t u: term) (i: nat), (C 0 t) -> substitution i t u = t.\nProof.\n  induction t.\n  move => u i.\n  simpl.\n  move => h0.\n  Search \"0\".\n  apply Lt.lt_n_0 in h0.\n  done.\n  simpl.\n  move => u i h0.  \n  rewrite -lambda_equivalence.\n  apply no_index_sub.\n  induction i.\n  simpl.\n  done.\n  apply ind_C_pred.\n  rewrite Plus.plus_comm in IHi.\n  done.\n  intros.\n  simpl.\n  rewrite app_equivalence.\n  simpl in H.\n  move:H.\n  move => [h0 h1].\n  split.\n  apply IHt1.\n  done.\n  apply IHt2.\n  done.\nQed.\n\n(*Used for case analysis in if's*)\nLemma dic: forall b : bool, (b = false) \\/ (b = true).\nProof.\n  move => b.\n  case b.\n  right.\n  done.\n  left.\n  done.\nQed.\n\n(*Question 1.4.1*)\nTheorem id_substitution: forall t: term, forall i: nat, multiple_substitution i t nil = t.\nProof.\n  induction t.\n  move => i.\n  simpl.\n  elim (dic (leb i v && leb v (i + 0 - 1))%bool).\n  move => h0.\n  rewrite h0.\n  done.\n  move => h0.\n  rewrite h0.\n  have:(beq_nat v v = true).\n  Search \"beq\".\n  apply beq_nat_true_iff.\n  done.\n  move => h1.\n  rewrite h1.\n  move: h0.\n  case v.\n  intro.\n  Search \"andb\".\n  apply Bool.andb_true_iff in h0.\n  Search \"leb_iff\".\n  destruct h0 as [h0 h01].\n  apply leb_iff in h0.\n  apply leb_iff in h01.\n  simpl.\n  done.\n  case i.\n  intros.\n  apply Bool.andb_true_iff in h0.\n  destruct h0 as [h0 h01].\n  apply leb_iff in h0.\n  apply leb_iff in h01.\n  omega.\n  intros.\n  simpl.\n  apply Bool.andb_true_iff in h0.\n  destruct h0 as [h0 h01].\n  apply leb_iff in h0.\n  apply leb_iff in h01.\n  omega.\n  intro.\n  simpl.\n  rewrite IHt.\n  done.\n  intro.\n  simpl.\n  rewrite IHt1.\n  rewrite IHt2.\n  done.\nQed.\n\n(*Lifting and arithmetic resuts*)\n(*-----------------------------*)\n\nLemma lift_free: forall (t: term) (i k: nat), C i t -> C (i+1) (lifting 1 k t).\nProof.\n  induction t.\n  simpl.\n  intros.\n  case (leb k v).\n  simpl.\n  Search \"plus\".\n  apply Plus.plus_lt_compat_r.\n  done.\n  simpl.\n  Search \"plus\".\n  apply Plus.lt_plus_trans.\n  done.\n  simpl.\n  intros.\n  apply IHt.\n  done.\n  simpl.\n  intros.\n  split.\n  apply IHt1.\n  apply H.\n  apply IHt2.\n  apply H.\nQed.\n\nLemma extract_lifting: forall (lu: list term) (j: nat) (u: term), (j < length lu) -> (nth j (lift_all 1 0 lu) u) = lifting 1 0 (nth j lu u).\nProof.\n  induction lu.\n  simpl.\n  intros.\n  Search _ (_<_).\n  apply Lt.lt_n_0 in H.\n  done.\n  simpl.\n  intros.\n  induction j.\n  done.\n  apply IHlu.\n  Search _ (_<_).\n  apply (Plus.plus_lt_reg_l j (length lu) 1).\n  apply H.\nQed.\n\nLemma lt_plus_l: forall (n m p: nat), n + p < m -> n < m.\nProof.\n  induction n.\n  induction m.\n  simpl.\n  intros.\n  apply lt_n_0 in H.\n  done.\n  simpl.\n  intros.\n  Search _ (_<_).\n  apply lt_0_Sn.\n  intros.\n  omega.\nQed.\n\nLemma le_plus_l: forall (n m p: nat), n + p <= m -> n <= m.\nProof.\n  intros.\n  omega.\nQed.\n\nLemma minus_dist: forall (n m p: nat), n - (m+p) = (n-m) - p.\nProof.\n  intros.\n  omega.\nQed.\n\nLemma lift_inv: forall (lu:list term), length lu = length (lift_all 1 0 lu).\nProof.\n  induction lu.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite IHlu.\n  reflexivity.  \nQed.\n\n(*-----------------------------*)\n\n(*Question 1.4.3*)\n(*Case when lu is non empty*)\nLemma mult_sub_inv_bis: forall (t u:term) (lu:list term) (i: nat),\n (0 < length lu) -> (forall (j:nat), (j < length lu) -> C i (nth j lu (Var 0))) -> multiple_substitution i t (u :: lu) = substitution i (multiple_substitution (i+1) t lu) (u).\nProof.\n  induction t.\n  intros.\n  simpl.\n  have:(true = beq_nat v v).\n  Search \"beq\".\n  apply ( beq_nat_refl v).\n  intro.\n  rewrite -x.\n  have:((leb (i+1) v = false) \\/ (leb (i+1) v = true)).\n  apply (dic (leb (i+1) v)).\n  intro.\n  case:x0.\n  move => h0.\n  rewrite h0.\n  simpl.\n  apply leb_iff_conv in h0.\n  have:(v < i)\\/(v=i).\n  Search _ (_<_).\n  apply le_lt_or_eq.\n  rewrite ->plus_comm in h0.\n  apply lt_n_Sm_le in h0.\n  done.\n  intro h1.\n  apply or_comm in h1.\n  case:h1.\n  intro h1.\n  rewrite h1.\n  rewrite minus_diag.\n  Search \"leb\".\n  have:(leb i i = true).\n  apply leb_iff.\n  apply le_refl.\n  intro h2.\n  rewrite h2.\n  simpl.\n  have:(beq_nat i i = true).\n  apply beq_nat_true_iff.\n  reflexivity.\n  intro h3.\n  rewrite h3.\n  have:(leb i (i + (length lu+1) -1) = true).\n  apply leb_iff.\n  omega.\n  intro h4.\n  have:i + S (length lu) - 1 = i + (length lu + 1) - 1.\n  omega.\n  intro.\n  rewrite x0.\n  rewrite h4.\n  done.\n  intro.\n  have:leb i v = false.\n  apply leb_iff_conv.\n  done.\n  intro.\n  rewrite x0.\n  simpl.\n  have:beq_nat i v = false.\n  rewrite beq_nat_false_iff.\n  intro.\n  rewrite H1 in b.\n  apply lt_irrefl in b.\n  done.\n  intro h1.\n  rewrite h1.\n  done.\n  intro.\n  rewrite b.\n  simpl.\n  apply leb_iff in b.\n  apply le_lt_or_eq_iff in b.\n  have:i + 1 + length lu - 1 = i + (1 + length lu) - 1.\n  omega.\n  intro h2.\n  rewrite -h2.\n  have:(leb v (i + 1 + length lu - 1) = false) \\/ leb v (i + 1 + length lu - 1) = true.\n  apply dic.\n  intro h0.\n  case:h0.\n  intro h1.\n  rewrite h1.\n  Search _ (_&&_)%bool \"comm\".\n  rewrite Bool.andb_comm.\n  simpl.\n  have:(beq_nat i v = false). \n  rewrite beq_nat_false_iff.\n  intro.\n  rewrite H1 in b.\n  case b.\n  intro.\n  omega.\n  omega.\n  intro h3.\n  rewrite h3.\n  done.\n  intro h1.\n  rewrite h1.\n  rewrite Bool.andb_comm.\n  simpl.\n  have:leb i v = true.\n  have:(i+1) <= v.\n  Search _ (_<=_) \"or\".\n  apply le_lt_or_eq_iff.\n  done.\n  intro h3.\n  apply leb_iff.\n  apply (le_plus_l i v 1).\n  done.\n  intro h3.\n  rewrite h3.\n  rewrite NPeano.Nat.sub_add_distr.\n  destruct (v - i) eqn:h4.\n  apply NPeano.Nat.sub_0_le in h4.\n  omega.\n  simpl.\n  rewrite -minus_n_O.\n  symmetry.\n  apply no_index_sub.\n  apply H0.\n  apply leb_iff in h1.\n  apply leb_iff in h3.\n  omega.\n  intros.\n  simpl.\n  rewrite -lambda_equivalence.\n  (*Find a way to deal with the lifting operation*)\n  apply (IHt (lifting 1 0 u) (lift_all 1 0 lu) (i+1)).\n  rewrite -lift_inv.\n  done.\n  intros.\n  rewrite -lift_inv in H1.\n  rewrite (extract_lifting).\n  apply lift_free.\n  apply H0.\n  done.\n  done.\n  intros.\n  simpl.\n  rewrite app_equivalence.\n  split.\n  apply (IHt1 u lu i).\n  done.\n  done.\n  apply (IHt2 u lu i).\n  done.\n  done.\nQed.\n\n(*General case*)\nLemma mult_sub_inv: forall (t u:term) (lu:list term) (i: nat),\n (forall (j:nat), (j < length lu) -> C i (nth j lu (Var 0))) -> multiple_substitution i t (u :: lu) = substitution i (multiple_substitution (i+1) t (lu)) (u).\nProof.\n  induction lu.\n  move:u.\n  induction t.\n  intros.\n  rewrite id_substitution.\n  unfold multiple_substitution.\n  have:i + 1 - 1 = i.\n  omega.\n  intro h0.\n  rewrite h0.\n  have: ((leb i v && leb v i)%bool = false) \\/ (leb i v && leb v i)%bool = true. \n  apply dic.\n  intro h1.\n  case:h1.\n  intro h1.\n  rewrite h1.\n  simpl.\n  apply Bool.andb_false_iff in h1.\n  case:h1.\n  intro h1.\n  apply leb_iff_conv in h1.\n  have: beq_nat i v = false.\n  apply beq_nat_false_iff.\n  omega.\n  intro h2.\n  rewrite h2.\n  trivial.\n  intro h1.\n  apply leb_iff_conv in h1.\n  have: beq_nat v i = false.\n  apply beq_nat_false_iff.\n  omega.\n  intro h2.\n  apply beq_nat_false_iff in h2.\n  apply not_eq_sym in h2.\n  apply beq_nat_false_iff in h2.\n  rewrite h2.\n  trivial.\n  intro h1.\n  rewrite h1.\n  apply Bool.andb_true_iff in h1.\n  have: i = v.\n  destruct h1 as [h1 h2].\n  apply leb_iff in h1.\n  apply leb_iff in h2.\n  omega.\n  intro h2.\n  have : v - i = 0.\n  omega.\n  intro h3.\n  rewrite h3.\n  simpl.\n  rewrite h2.\n  trivial.\n  intros.\n  simpl.\n  rewrite -lambda_equivalence.\n  apply IHt.\n  intros.\n  apply ind_C_pred.\n  apply H.\n  trivial.\n  intros.\n  simpl.\n  rewrite app_equivalence.\n  split.\n  apply IHt1.\n  done.\n  apply IHt2.\n  done.\n  intros.\n  apply (mult_sub_inv_bis t u (a::lu) i).\n  simpl.\n  omega.\n  intros.\n  apply H.\n  done.\nQed.\n\n", "meta": {"author": "pedrohaa", "repo": "untypedCoq", "sha": "89ba50c6c306a4e8b2a9d2114ccf1e944bacf8cf", "save_path": "github-repos/coq/pedrohaa-untypedCoq", "path": "github-repos/coq/pedrohaa-untypedCoq/untypedCoq-89ba50c6c306a4e8b2a9d2114ccf1e944bacf8cf/substitution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246077301781, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6522119117075508}}
{"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.\nRequire list.List.\nRequire list.Length.\nRequire list.Nth.\nRequire option.Option.\n\n(* Why3 goal *)\nLemma nth_none_1 :\nforall {a:Type} {a_WT:WhyType a},\nforall (l:(list a)) (i:Z),\n (i < 0%Z)%Z -> ((list.Nth.nth i l) = Init.Datatypes.None).\nProof.\nintros a a_WT l.\ninduction l as [|h q].\neasy.\nintros i H.\nsimpl.\ngeneralize (Zeq_bool_if i 0).\ncase Zeq_bool.\nintros H'.\nnow rewrite H' in H.\nintros _.\napply IHq.\nomega.\nQed.\n\n(* Why3 goal *)\nLemma nth_none_2 :\nforall {a:Type} {a_WT:WhyType a},\nforall (l:(list a)) (i:Z),\n ((list.Length.length l) <= i)%Z ->\n ((list.Nth.nth i l) = Init.Datatypes.None).\nProof.\nintros a a_WT l.\ninduction l as [|h q].\neasy.\nintros i H.\nunfold Length.length in H.\nfold Length.length in H.\nsimpl.\ngeneralize (Zeq_bool_if i 0).\ncase Zeq_bool.\nintros H'.\nrewrite H' in H.\nexfalso.\ngeneralize (Length.Length_nonnegative q).\nomega.\nintros _.\napply IHq.\nomega.\nQed.\n\n(* Why3 goal *)\nLemma nth_none_3 :\nforall {a:Type} {a_WT:WhyType a},\nforall (l:(list a)) (i:Z),\n ((list.Nth.nth i l) = Init.Datatypes.None) ->\n ((i < 0%Z)%Z \\/ ((list.Length.length l) <= i)%Z).\nProof.\nintros a a_WT l.\ninduction l as [|h q].\nintros i _.\nsimpl.\nomega.\nintros i.\nsimpl (Nth.nth i (h :: q)).\nchange (Length.length (h :: q)) with (1 + Length.length q)%Z.\ngeneralize (Zeq_bool_if i 0).\ncase Zeq_bool.\neasy.\nintros Hi H.\nspecialize (IHq _ H).\nomega.\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/list/NthLength.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7826624890918021, "lm_q1q2_score": 0.6522119019883269}}
{"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 Export NumPrelude NZAxioms.\nRequire Import NZBase NZOrder NZAddOrder Plus Minus.\n\n(** In this file, we investigate the shape of domains satisfying\n    the [NZDomainSig] interface. In particular, we define a\n    translation from Peano numbers [nat] into NZ.\n*)\n\n(** First, a section about iterating a function. *)\n\nSection Iter.\nVariable A : Type.\nFixpoint iter (f:A->A)(n:nat) : A -> A := fun a =>\n  match n with\n    | O => a\n    | S n => f (iter f n a)\n  end.\nInfix \"^\" := iter.\n\nLemma iter_alt : forall f n m, (f^(Datatypes.S n)) m = (f^n) (f m).\nProof.\ninduction n; simpl; auto.\nintros; rewrite <- IHn; auto.\nQed.\n\nLemma iter_plus : forall f n n' m, (f^(n+n')) m = (f^n) ((f^n') m).\nProof.\ninduction n; simpl; auto.\nintros; rewrite IHn; auto.\nQed.\n\nLemma iter_plus_bis : forall f n n' m, (f^(n+n')) m = (f^n') ((f^n) m).\nProof.\ninduction n; simpl; auto.\nintros. rewrite <- iter_alt, IHn; auto.\nQed.\n\nGlobal Instance iter_wd (R:relation A) : Proper ((R==>R)==>eq==>R==>R) iter.\nProof.\nintros f f' Hf n n' Hn; subst n'. induction n; simpl; red; auto.\nQed.\n\nEnd Iter.\nImplicit Arguments iter [A].\nLocal Infix \"^\" := iter.\n\n\nModule NZDomainProp (Import NZ:NZDomainSig').\n\n(** * Relationship between points thanks to [succ] and [pred]. *)\n\n(** We prove that any points in NZ have a common descendant by [succ] *)\n\nDefinition common_descendant n m := exists k l, (S^k) n == (S^l) m.\n\nInstance common_descendant_wd : Proper (eq==>eq==>iff) common_descendant.\nProof.\nunfold common_descendant. intros n n' Hn m m' Hm.\nsetoid_rewrite Hn. setoid_rewrite Hm. auto with *.\nQed.\n\nInstance common_descendant_equiv : Equivalence common_descendant.\nProof.\nsplit; red.\nintros x. exists O; exists O. simpl; auto with *.\nintros x y (p & q & H); exists q; exists p; auto with *.\nintros x y z (p & q & Hpq) (r & s & Hrs).\nexists (r+p)%nat. exists (q+s)%nat.\nrewrite !iter_plus. rewrite Hpq, <-Hrs, <-iter_plus, <- iter_plus_bis.\nauto with *.\nQed.\n\nLemma common_descendant_with_0 : forall n, common_descendant n 0.\nProof.\napply bi_induction.\nintros n n' Hn. rewrite Hn; auto with *.\nreflexivity.\nsplit; intros (p & q & H).\nexists p; exists (Datatypes.S q). rewrite <- iter_alt; simpl.\n now f_equiv.\nexists (Datatypes.S p); exists q. rewrite iter_alt; auto.\nQed.\n\nLemma common_descendant_always : forall n m, common_descendant n m.\nProof.\nintros. transitivity 0; [|symmetry]; apply common_descendant_with_0.\nQed.\n\n(** Thanks to [succ] being injective, we can then deduce that for any two\n    points, one is an iterated successor of the other. *)\n\nLemma itersucc_or_itersucc : forall n m, exists k, n == (S^k) m \\/ m == (S^k) n.\nProof.\nintros n m. destruct (common_descendant_always n m) as (k & l & H).\nrevert l H. induction k.\nsimpl. intros; exists l; left; auto with *.\nintros. destruct l.\nsimpl in *. exists (Datatypes.S k); right; auto with *.\nsimpl in *. apply pred_wd in H; rewrite !pred_succ in H. eauto.\nQed.\n\n(** Generalized version of [pred_succ] when iterating *)\n\nLemma succ_swap_pred : forall k n m, n == (S^k) m -> m == (P^k) n.\nProof.\ninduction k.\nsimpl; auto with *.\nsimpl; intros. apply pred_wd in H. rewrite pred_succ in H. apply IHk in H; auto.\nrewrite <- iter_alt in H; auto.\nQed.\n\n(** From a given point, all others are iterated successors\n    or iterated predecessors. *)\n\nLemma itersucc_or_iterpred : forall n m, exists k, n == (S^k) m \\/ n == (P^k) m.\nProof.\nintros n m. destruct (itersucc_or_itersucc n m) as (k,[H|H]).\nexists k; left; auto.\nexists k; right. apply succ_swap_pred; auto.\nQed.\n\n(** In particular, all points are either iterated successors of [0]\n    or iterated predecessors of [0] (or both). *)\n\nLemma itersucc0_or_iterpred0 :\n forall n, exists p:nat, n == (S^p) 0 \\/ n == (P^p) 0.\nProof.\n intros n. exact (itersucc_or_iterpred n 0).\nQed.\n\n(** * Study of initial point w.r.t. [succ] (if any). *)\n\nDefinition initial n := forall m, n ~= S m.\n\nLemma initial_alt : forall n, initial n <-> S (P n) ~= n.\nProof.\nsplit. intros Bn EQ. symmetry in EQ. destruct (Bn _ EQ).\nintros NEQ m EQ. apply NEQ. rewrite EQ, pred_succ; auto with *.\nQed.\n\nLemma initial_alt2 : forall n, initial n <-> ~exists m, n == S m.\nProof. firstorder. Qed.\n\n(** First case: let's assume such an initial point exists\n    (i.e. [S] isn't surjective)... *)\n\nSection InitialExists.\nHypothesis init : t.\nHypothesis Initial : initial init.\n\n(** ... then we have unicity of this initial point. *)\n\nLemma initial_unique : forall m, initial m -> m == init.\nProof.\nintros m Im. destruct (itersucc_or_itersucc init m) as (p,[H|H]).\ndestruct p. now simpl in *. destruct (Initial _ H).\ndestruct p. now simpl in *. destruct (Im _ H).\nQed.\n\n(** ... then all other points are descendant of it. *)\n\nLemma initial_ancestor : forall m, exists p, m == (S^p) init.\nProof.\nintros m. destruct (itersucc_or_itersucc init m) as (p,[H|H]).\ndestruct p; simpl in *; auto. exists O; auto with *. destruct (Initial _ H).\nexists p; auto.\nQed.\n\n(** NB : We would like to have [pred n == n] for the initial element,\n    but nothing forces that. For instance we can have -3 as initial point,\n    and P(-3) = 2. A bit odd indeed, but legal according to [NZDomainSig].\n    We can hence have [n == (P^k) m] without [exists k', m == (S^k') n].\n*)\n\n(** We need decidability of [eq] (or classical reasoning) for this: *)\n\nSection SuccPred.\nHypothesis eq_decidable : forall n m, n==m \\/ n~=m.\nLemma succ_pred_approx : forall n, ~initial n -> S (P n) == n.\nProof.\nintros n NB. rewrite initial_alt in NB.\ndestruct (eq_decidable (S (P n)) n); auto.\nelim NB; auto.\nQed.\nEnd SuccPred.\nEnd InitialExists.\n\n(** Second case : let's suppose now [S] surjective, i.e. no initial point. *)\n\nSection InitialDontExists.\n\nHypothesis succ_onto : forall n, exists m, n == S m.\n\nLemma succ_onto_gives_succ_pred : forall n, S (P n) == n.\nProof.\nintros n. destruct (succ_onto n) as (m,H). rewrite H, pred_succ; auto with *.\nQed.\n\nLemma succ_onto_pred_injective : forall n m, P n == P m -> n == m.\nProof.\nintros n m. intros H; apply succ_wd in H.\nrewrite !succ_onto_gives_succ_pred in H; auto.\nQed.\n\nEnd InitialDontExists.\n\n\n(** To summarize:\n\n  S is always injective, P is always surjective  (thanks to [pred_succ]).\n\n  I) If S is not surjective, we have an initial point, which is unique.\n     This bottom is below zero: we have N shifted (or not) to the left.\n     P cannot be injective: P init = P (S (P init)).\n     (P init) can be arbitrary.\n\n  II) If S is surjective, we have [forall n, S (P n) = n], S and P are\n     bijective and reciprocal.\n\n     IIa) if [exists k<>O, 0 == S^k 0], then we have a cyclic structure Z/nZ\n     IIb) otherwise, we have Z\n*)\n\n\n(** * An alternative induction principle using [S] and [P]. *)\n\n(** It is weaker than [bi_induction]. For instance it cannot prove that\n    we can go from one point by many [S] _or_ many [P], but only by many\n    [S] mixed with many [P]. Think of a model with two copies of N:\n\n    0,  1=S 0,   2=S 1, ...\n    0', 1'=S 0', 2'=S 1', ...\n\n    and P 0 = 0' and P 0' = 0.\n*)\n\nLemma bi_induction_pred :\n  forall A : t -> Prop, Proper (eq==>iff) A ->\n    A 0 -> (forall n, A n -> A (S n)) -> (forall n, A n -> A (P n)) ->\n    forall n, A n.\nProof.\nintros. apply bi_induction; auto.\nclear n. intros n; split; auto.\nintros G; apply H2 in G. rewrite pred_succ in G; auto.\nQed.\n\nLemma central_induction_pred :\n  forall A : t -> Prop, Proper (eq==>iff) A -> forall n0,\n    A n0 -> (forall n, A n -> A (S n)) -> (forall n, A n -> A (P n)) ->\n    forall n, A n.\nProof.\nintros.\nassert (A 0).\ndestruct (itersucc_or_iterpred 0 n0) as (k,[Hk|Hk]); rewrite Hk; clear Hk.\n clear H2. induction k; simpl in *; auto.\n clear H1. induction k; simpl in *; auto.\napply bi_induction_pred; auto.\nQed.\n\nEnd NZDomainProp.\n\n(** We now focus on the translation from [nat] into [NZ].\n    First, relationship with [0], [succ], [pred].\n*)\n\nModule NZOfNat (Import NZ:NZDomainSig').\n\nDefinition ofnat (n : nat) : t := (S^n) 0.\nNotation \"[ n ]\" := (ofnat n) (at level 7) : ofnat.\nLocal Open Scope ofnat.\n\nLemma ofnat_zero : [O] == 0.\nProof.\nreflexivity.\nQed.\n\nLemma ofnat_succ : forall n, [Datatypes.S n] == succ [n].\nProof.\n now unfold ofnat.\nQed.\n\nLemma ofnat_pred : forall n, n<>O -> [Peano.pred n] == P [n].\nProof.\n unfold ofnat. destruct n. destruct 1; auto.\n intros _. simpl. symmetry. apply pred_succ.\nQed.\n\n(** Since [P 0] can be anything in NZ (either [-1], [0], or even other\n    numbers, we cannot state previous lemma for [n=O]. *)\n\nEnd NZOfNat.\n\n\n(** If we require in addition a strict order on NZ, we can prove that\n    [ofnat] is injective, and hence that NZ is infinite\n    (i.e. we ban Z/nZ models) *)\n\nModule NZOfNatOrd (Import NZ:NZOrdSig').\nInclude NZOfNat NZ.\nInclude NZBaseProp NZ <+ NZOrderProp NZ.\nLocal Open Scope ofnat.\n\nTheorem ofnat_S_gt_0 :\n  forall n : nat, 0 < [Datatypes.S n].\nProof.\nunfold ofnat.\nintros n; induction n as [| n IH]; simpl in *.\napply lt_succ_diag_r.\napply lt_trans with (S 0). apply lt_succ_diag_r. now rewrite <- succ_lt_mono.\nQed.\n\nTheorem ofnat_S_neq_0 :\n  forall n : nat, 0 ~= [Datatypes.S n].\nProof.\nintros. apply lt_neq, ofnat_S_gt_0.\nQed.\n\nLemma ofnat_injective : forall n m, [n]==[m] -> n = m.\nProof.\ninduction n as [|n IH]; destruct m; auto.\nintros H; elim (ofnat_S_neq_0 _ H).\nintros H; symmetry in H; elim (ofnat_S_neq_0 _ H).\nintros. f_equal. apply IH. now rewrite <- succ_inj_wd.\nQed.\n\nLemma ofnat_eq : forall n m, [n]==[m] <-> n = m.\nProof.\nsplit. apply ofnat_injective. intros; now subst.\nQed.\n\n(* In addition, we can prove that [ofnat] preserves order. *)\n\nLemma ofnat_lt : forall n m : nat, [n]<[m] <-> (n<m)%nat.\nProof.\ninduction n as [|n IH]; destruct m; repeat rewrite ofnat_zero; split.\nintro H; elim (lt_irrefl _ H).\ninversion 1.\nauto with arith.\nintros; apply ofnat_S_gt_0.\nintro H; elim (lt_asymm _ _ H); apply ofnat_S_gt_0.\ninversion 1.\nrewrite !ofnat_succ, <- succ_lt_mono, IH; auto with arith.\nrewrite !ofnat_succ, <- succ_lt_mono, IH; auto with arith.\nQed.\n\nLemma ofnat_le : forall n m : nat, [n]<=[m] <-> (n<=m)%nat.\nProof.\nintros. rewrite lt_eq_cases, ofnat_lt, ofnat_eq.\nsplit.\ndestruct 1; subst; auto with arith.\napply Lt.le_lt_or_eq.\nQed.\n\nEnd NZOfNatOrd.\n\n\n(** For basic operations, we can prove correspondance with\n    their counterpart in [nat]. *)\n\nModule NZOfNatOps (Import NZ:NZAxiomsSig').\nInclude NZOfNat NZ.\nLocal Open Scope ofnat.\n\nLemma ofnat_add_l : forall n m, [n]+m == (S^n) m.\nProof.\n induction n; intros.\n apply add_0_l.\n rewrite ofnat_succ, add_succ_l. simpl. now f_equiv.\nQed.\n\nLemma ofnat_add : forall n m, [n+m] == [n]+[m].\nProof.\n intros. rewrite ofnat_add_l.\n induction n; simpl. reflexivity.\n rewrite ofnat_succ. now f_equiv.\nQed.\n\nLemma ofnat_mul : forall n m, [n*m] == [n]*[m].\nProof.\n induction n; simpl; intros.\n symmetry. apply mul_0_l.\n rewrite plus_comm.\n rewrite ofnat_succ, ofnat_add, mul_succ_l.\n now f_equiv.\nQed.\n\nLemma ofnat_sub_r : forall n m, n-[m] == (P^m) n.\nProof.\n induction m; simpl; intros.\n rewrite ofnat_zero. apply sub_0_r.\n rewrite ofnat_succ, sub_succ_r. now f_equiv.\nQed.\n\nLemma ofnat_sub : forall n m, m<=n -> [n-m] == [n]-[m].\nProof.\n intros n m H. rewrite ofnat_sub_r.\n revert n H. induction m. intros.\n rewrite <- minus_n_O. now simpl.\n intros.\n destruct n.\n inversion H.\n rewrite iter_alt.\n simpl.\n rewrite ofnat_succ, pred_succ; auto with arith.\nQed.\n\nEnd NZOfNatOps.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/Numbers/NatInt/NZDomain.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7826624840223699, "lm_q1q2_score": 0.6522118977638444}}
{"text": "Require Import List.\n\nLemma fold_right_map: forall {A1 B1 A2 B2} (f1: A1 -> B1 -> B1) (f2: A2 -> B2 -> B2) gA gB,\n  (forall a b, gB (f1 a b) = f2 (gA a) (gB b)) ->\n  (forall l b, gB (fold_right f1 b l) = fold_right f2 (gB b) (map gA l)).\nProof.\n  intros.\n  induction l; auto.\n  simpl.\n  rewrite H.\n  rewrite IHl.\n  auto.\nQed.\n\nLemma fold_left_map: forall {A1 B1 A2 B2} (f1: A1 -> B1 -> A1) (f2: A2 -> B2 -> A2) gA gB,\n  (forall a b, gA (f1 a b) = f2 (gA a) (gB b)) ->\n  (forall l a, gA (fold_left f1 l a) = fold_left f2 (map gB l) (gA a)).\nProof.\n  intros.\n  revert a; induction l; auto; intros.\n  simpl.\n  rewrite <- H.\n  rewrite IHl.\n  auto.\nQed.\n\nLemma NoDup_app_iff {A}: forall l1 l2 : list A,\n  NoDup (l1 ++ l2) <->\n  NoDup l1 /\\ NoDup l2 /\\ (forall a, In a l1 /\\ In a l2 <-> False).\nProof.\n  induction l1; intros.\n  + simpl.\n    split; intros.\n    - split; [constructor |].\n      split; auto.\n      intros; tauto.\n    - tauto.\n  + split; intros.\n    - simpl in H.\n      inversion H; subst.\n      rewrite IHl1 in H3; destruct H3 as [? [? ?]].\n      split; [constructor | split]; auto.\n      * rewrite in_app_iff in H2; tauto.\n      * intros; specialize (H3 a0).\n        simpl.\n        split; [| tauto].\n        intros [[? | ?] ?]; [| tauto].\n        subst a0.\n        rewrite in_app_iff in H2; tauto.\n    - destruct H as [? [? ?]].\n      simpl; constructor.\n      * inversion H; subst.\n        specialize (H1 a); simpl in H1.\n        rewrite in_app_iff; tauto.\n      * rewrite IHl1.\n        split; [inversion H | split]; auto.\n        intros; specialize (H1 a0); simpl in H1; tauto.\nQed.\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/Coqlib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.6522118886797496}}
{"text": "Require Import Coq.Sets.Ensembles.\nRequire Import Coq.Logic.Classical_Prop.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Logic.ChoiceFacts.\nRequire Import Coq.Logic.ClassicalChoice.\nRequire Import Logic.lib.RelationPairs_ext.\nRequire Import Logic.GeneralLogic.KripkeModel.\nRequire Import Logic.SeparationLogic.Model.SeparationAlgebra.\nRequire Import Logic.SeparationLogic.Model.OrderedSA.\n\n(***********************************)\n(* Separation Algebra Generators   *)\n(***********************************)\n\nSection trivialSA.\n  Context {worlds: Type}.\n  \n  Definition trivial_Join: Join worlds:=  (fun a b c => False).\n\n  Definition trivial_SA: @SeparationAlgebra worlds trivial_Join.\n  Proof.\n    constructor; intuition.\n    inversion H.\n  Qed.\n\n  (* Trivial algebra is upwards closed *)\n  (* Trivial is NOT downwards closed *)\n  Definition trivial_uSA {R: Relation worlds}:\n    @UpwardsClosedSeparationAlgebra worlds R (trivial_Join).\n  Proof.\n    intros until m2; intros.\n    inversion H.\n  Qed.\n\n  (*Increasing*)\n  Definition trivial_incrSA: @IncreasingSeparationAlgebra\n                           worlds eq trivial_Join.\n  Proof.\n    constructor; intros.\n    hnf; intros.\n    inversion H.\n  Qed.\n\n  (*Trivial is NOT necessarily unital*)\n\n  (*Trivial is NOT necessarily residual*)\n  \nEnd trivialSA.\n\nSection unitSA.\n  Definition unit_Join: Join unit:=  (fun _ _ _ => True).\n\n  Definition unit_SA: @SeparationAlgebra unit unit_Join.\n  Proof.\n    constructor.\n    + intros. constructor.\n    + intros; exists tt; split; constructor.\n  Qed.\n\n  (* Unit algebra is upwards closed *)\n  Definition unit_uSA:\n    @UpwardsClosedSeparationAlgebra unit eq unit_Join.\n  Proof.\n    intros; exists tt, tt; intuition.\n    + destruct m1; reflexivity.\n    + destruct m2; reflexivity.\n  Qed.\n\n  (* Unit algebra is downwards closed *)\n  Definition unit_dSA:\n    @DownwardsClosedSeparationAlgebra unit eq unit_Join.\n  Proof.\n    intros; exists tt; intuition.\n    destruct m; reflexivity.\n  Qed.\n\n  (*Increasing*)\n  Instance unit_incrSA:\n    @IncreasingSeparationAlgebra unit eq unit_Join.\n  Proof.\n    constructor; intros; hnf; intros.\n    destruct n, n'; reflexivity.\n  Qed.\n\n  Instance unit_residual:\n    @ResidualSeparationAlgebra unit eq unit_Join.\n  Proof.\n    constructor; intros.\n    exists tt; exists tt; split.\n    + constructor.\n    + destruct n; reflexivity.\n  Qed.\n\n  Definition unit_unital:\n    @UnitalSeparationAlgebra unit eq unit_Join.\n  Proof.\n    apply <- (@incr_unital_iff_residual unit eq (eq_preorder unit) unit_Join); auto.\n    + apply unit_residual.\n    + apply unit_incrSA.\n  Qed.\n\nEnd unitSA.\n\n\nSection equivSA.\n  Context {worlds: Type}.\n  \n  Definition equiv_Join: Join worlds:=  (fun a b c => a = c /\\ b = c).\n\n  Definition equiv_SA: @SeparationAlgebra worlds equiv_Join.\n  Proof.\n    constructor.\n    + intros.\n      inversion H.\n      split; tauto.\n    + intros.\n      simpl in *.\n      destruct H, H0.\n      subst mx my mxy mz.\n      exists mxyz; do 2 split; auto.\n  Qed.\n\n  (* Identity algebra is upwards closed *)\n  (* Identity is NOT downwards closed *)\n  Definition identity_uSA {R: Relation worlds}:\n    @UpwardsClosedSeparationAlgebra worlds R equiv_Join.\n  Proof.\n    intros until m2; intros.\n    destruct H; subst m1 m2.\n    exists n, n; do 2 split; auto.\n  Qed.\n\n  Definition equiv_incrSA: @IncreasingSeparationAlgebra\n                           worlds eq equiv_Join.\n  Proof.\n    constructor; intros.\n    hnf; intros.\n    inversion H; subst.\n    constructor.\n  Qed.\n\n  Definition ikiM_uSA {R: Relation worlds} {po_R: PreOrder Krelation} {ikiM: IdentityKripkeIntuitionisticModel worlds} {J: Join worlds}: UpwardsClosedSeparationAlgebra worlds.\n  Proof.\n    intros until m2; intros.\n    apply Korder_identity in H0.\n    subst n.\n    exists m1, m2.\n    split; [| split]; auto; reflexivity.\n  Qed.\n\n  Definition ikiM_dSA {R: Relation worlds} {po_R: PreOrder Krelation} {ikiM: IdentityKripkeIntuitionisticModel worlds} {J: Join worlds}: DownwardsClosedSeparationAlgebra worlds.\n  Proof.\n    intros until n2; intros.\n    apply Korder_identity in H0.\n    apply Korder_identity in H1.\n    subst n1 n2.\n    exists m.\n    split; auto; reflexivity.\n  Qed.\n\n  (*Identity is NOT necessarily increasing*)\n\n  (*Identity is NOT necessarily unital*)\n\n  (*Identity is NOT necessarily residual*)\n  \nEnd equivSA.\n\nSection optionSA.\n  Context (worlds: Type).\n  \n  Inductive option_join {J: Join worlds}: option worlds -> option worlds -> option worlds -> Prop :=\n  | None_None_join: option_join None None None\n  | None_Some_join: forall a, option_join None (Some a) (Some a)\n  | Some_None_join: forall a, option_join (Some a) None (Some a)\n  | Some_Some_join: forall a b c, join a b c -> option_join (Some a) (Some b) (Some c).\n\n  Definition option_Join {SA: Join worlds}: Join (option worlds):=\n    (@option_join SA).\n  \n  Definition option_SA\n             {J: Join worlds}\n             {SA: SeparationAlgebra worlds}:\n    @SeparationAlgebra (option worlds) (option_Join).\n  Proof.\n    constructor.\n    + intros.\n      simpl in *.\n      destruct H.\n    - apply None_None_join.\n    - apply Some_None_join.\n    - apply None_Some_join.\n    - apply Some_Some_join.\n      apply join_comm; auto.\n      + intros.\n        simpl in *.\n        inversion H; inversion H0; clear H H0; subst;\n        try inversion H4; try inversion H5; try inversion H6; subst;\n        try congruence;\n        [.. | destruct (join_assoc _ _ _ _ _ H1 H5) as [? [? ?]];\n           eexists; split; apply Some_Some_join; eassumption];\n        eexists; split;\n        try solve [ apply None_None_join | apply Some_None_join\n                    | apply None_Some_join | apply Some_Some_join; eauto].\n  Qed.\n\n  (* Ordered option Upwards closed *)\n  Lemma option_ord_uSA\n        {R: Relation worlds}\n        {J: Join worlds}\n        (uSA: UpwardsClosedSeparationAlgebra worlds):\n    @UpwardsClosedSeparationAlgebra (option worlds) (option01_relation Krelation) option_Join.\n  Proof.\n    hnf; intros.\n    inversion H; subst.\n    - inversion H0; subst.\n      + exists None, None; repeat split; try constructor.\n      + exists (Some a), None; repeat split; try constructor.\n    - inversion H0; subst.\n      exists None, (Some b); repeat split; try constructor; auto.\n    - inversion H0; subst.\n      exists (Some b), None; repeat split; try constructor; auto.\n    - inversion H0; subst.\n      destruct\n        (uSA  _ _ _ _ H1 H3) as [n1 [n2 [HH1 [HH2 HH3]]]].\n      exists (Some n1), (Some n2); repeat split; try constructor; auto.\n  Qed.\n\n  (* Downwards closed IF the algebra is increasing*)\n  Lemma option_ord_dSA\n        {R: Relation worlds}\n        {po_R: PreOrder Krelation}\n        {J: Join worlds}\n        {SA: SeparationAlgebra worlds}\n        (dSA: DownwardsClosedSeparationAlgebra worlds)\n        {incrSA: IncreasingSeparationAlgebra worlds}:\n    @DownwardsClosedSeparationAlgebra (option worlds) (option01_relation Krelation) option_Join.\n  Proof.\n    hnf; intros.\n    inversion H0; [ | | inversion H1]; subst.\n    - exists n2; inversion H; subst; split; auto;\n      destruct n2; constructor.\n    - exists n2; inversion H; subst; split; auto;\n      destruct n2; constructor.\n      + inversion H1.\n      + inversion H; subst.\n        apply all_increasing in H6.\n        inversion H1; subst.\n        transitivity b; auto.\n    - exists (Some a); split; try constructor.\n      inversion H; subst; auto.\n    - exists (Some a); split; try constructor.\n      transitivity (Some b); auto.\n      inversion H; subst.\n      constructor. eapply all_increasing. apply join_comm; eassumption.\n    - inversion H; subst.\n      destruct (dSA _ _ _ _ _ H6 H2 H5) as [n [HH1 HH2]].\n      exists (Some n); split; constructor; auto.\n  Qed.\n\n  Lemma option_ord_incr_None\n        {R: Relation worlds}\n        {po_R: PreOrder Krelation}\n        {J: Join worlds}\n        {SA: SeparationAlgebra worlds}:\n    @increasing (option worlds) (option01_relation Krelation) option_Join None.\n  Proof.\n    hnf; intros.\n    inversion H; subst.\n    + constructor.\n    + constructor.\n      reflexivity.\n  Qed.\n\n  Lemma option_ord_res_None\n        {R: Relation worlds}\n        {po_R: PreOrder Krelation}\n        {J: Join worlds}\n        {SA: SeparationAlgebra worlds}:\n    forall n, @residue (option worlds) (option01_relation Krelation) option_Join n None.\n  Proof.\n    hnf; intros.\n    exists n.\n    split.\n    + destruct n; constructor.\n    + destruct n; constructor.\n      reflexivity.\n  Qed.\n\n  Lemma option_ord_USA\n        {R: Relation worlds}\n        {po_R: PreOrder Krelation}\n        {J: Join worlds}\n        {SA: SeparationAlgebra worlds}:\n    @UnitalSeparationAlgebra (option worlds) (option01_relation Krelation) option_Join.\n  Proof.\n    constructor.\n    intros.\n    exists None.\n    split.\n    + apply option_ord_res_None.\n    + apply option_ord_incr_None.\n  Qed.\n\n  (* Disjoint option Upwards closed*)\n  Lemma option_disj_uSA\n        {R: Relation worlds}\n        {J: Join worlds}\n        (uSA: UpwardsClosedSeparationAlgebra worlds):\n    @UpwardsClosedSeparationAlgebra (option worlds) (option00_relation Krelation) option_Join.\n  Proof.\n    hnf; intros.\n    inversion H; subst.\n    - inversion H0; subst.\n      exists None, None; repeat split; try constructor.\n    - inversion H0; subst.\n      exists None, (Some b); repeat split; try constructor; auto.\n    - inversion H0; subst.\n      exists (Some b), None; repeat split; try constructor; auto.\n    - inversion H0; subst.\n      destruct\n        (uSA  _ _ _ _ H1 H3) as [n1 [n2 [HH1 [HH2 HH3]]]].\n      exists (Some n1), (Some n2); repeat split; try constructor; auto.\n  Qed.\n\n  (* Disjointed option Downwards *)\n  Lemma option_disj_dSA\n        {R: Relation worlds}\n        {J: Join worlds}\n        {SA: SeparationAlgebra worlds}\n        (dSA: DownwardsClosedSeparationAlgebra worlds):\n    @DownwardsClosedSeparationAlgebra (option worlds) (option00_relation Krelation) option_Join.\n  Proof.\n    hnf; intros.\n    inversion H0; [ | inversion H1]; subst.\n    - exists n2; inversion H; subst; split; auto;\n      destruct n2; constructor.\n    - exists (Some a); split; try constructor.\n      inversion H; subst; auto.\n    - inversion H; subst.\n      destruct (dSA _ _ _ _ _ H6 H2 H5) as [n [HH1 HH2]].\n      exists (Some n); split; constructor; auto.\n  Qed.\n\n  Lemma option_disj_incr_None\n        {R: Relation worlds}\n        {po_R: PreOrder Krelation}\n        {J: Join worlds}\n        {SA: SeparationAlgebra worlds}:\n    @increasing (option worlds) (option00_relation Krelation) option_Join None.\n  Proof.\n    hnf; intros.\n    inversion H; subst.\n    + constructor.\n    + constructor.\n      reflexivity.\n  Qed.\n\n  Lemma option_disj_res_None\n        {R: Relation worlds}\n        {po_R: PreOrder Krelation}\n        {J: Join worlds}\n        {SA: SeparationAlgebra worlds}:\n    forall n, @residue (option worlds) (option00_relation Krelation) option_Join n None.\n  Proof.\n    hnf; intros.\n    exists n.\n    split.\n    + destruct n; constructor.\n    + destruct n; constructor.\n      reflexivity.\n  Qed.\n\n  Lemma option_disj_USA\n        {R: Relation worlds}\n        {po_R: PreOrder Krelation}\n        {J: Join worlds}\n        {SA: SeparationAlgebra worlds}:\n    @UnitalSeparationAlgebra (option worlds) (option00_relation Krelation) option_Join.\n  Proof.\n    constructor.\n    intros.\n    exists None.\n    split.\n    + apply option_disj_res_None.\n    + apply option_disj_incr_None.\n  Qed.\n\n  Lemma option_disj_USA'\n        {R: Relation worlds}\n        {po_R: PreOrder Krelation}\n        {J: Join worlds}\n        {SA: SeparationAlgebra worlds}:\n    @UnitalSeparationAlgebra' (option worlds) (option00_relation Krelation) option_Join.\n  Proof.\n    constructor.\n    intros.\n    exists None.\n    split.\n    + apply option_disj_res_None.\n    + hnf; intros.\n      inversion H; subst.\n      apply option_disj_incr_None.\n  Qed.\n\nEnd optionSA.\n\nSection exponentialSA.\n  Definition fun_Join (A B: Type) {J_B: Join B}: Join (A -> B) :=\n    (fun a b c => forall x, join (a x) (b x) (c x)).\n\n  Definition fun_SA\n             (A B: Type)\n             {Join_B: Join B}\n             {SA_B: SeparationAlgebra B}: @SeparationAlgebra (A -> B) (fun_Join A B).\n  Proof.\n    constructor.\n    + intros.\n      simpl in *.\n      intros x; specialize (H x).\n      apply join_comm; auto.\n    + intros.\n      simpl in *.\n      destruct (choice (fun x fx => join (my x) (mz x) fx /\\ join (mx x) fx (mxyz x) )) as [myz ?].\n    - intros x; specialize (H x); specialize (H0 x).\n      apply (join_assoc _ _ _ _ _ H H0); auto.\n    - exists myz; firstorder.\n  Qed.\n\n  (* Exponential is upwards closed *)\n  Lemma fun_uSA \n        (A B: Type)\n        {R_B: Relation B}\n        {J_B: Join B}\n        (uSA_B: UpwardsClosedSeparationAlgebra B):\n    @UpwardsClosedSeparationAlgebra (A -> B) (pointwise_relation A R_B) (fun_Join A B).\n  Proof.\n    hnf; intros.\n    unfold join, fun_Join in H.\n    unfold Krelation, pointwise_relation in H0.\n    destruct (choice (fun x nn => join (fst nn) (snd nn) (n x) /\\\n                               Krelation (m1 x) (fst nn) /\\\n                               Krelation (m2 x) (snd nn)))\n      as [nn H1].\n    intros x.\n    destruct (uSA_B (m x) (n x) (m1 x) (m2 x) (H x) (H0 x)) as [x1 [x2 ?]];\n      exists (x1, x2); auto.\n    exists (fun x => fst (nn x)), (fun x => snd (nn x)).\n    simpl; repeat split; intros x; specialize (H1 x); destruct H1 as [H1 [H2 H3]];\n    assumption.\n  Qed.\n\n  \n  (* Exponential is downwards closed *)\n  Lemma fun_dSA \n        (A B: Type)\n        {R_B: Relation B}\n        {J_B: Join B}\n        (dSA_B: DownwardsClosedSeparationAlgebra B):\n    @DownwardsClosedSeparationAlgebra (A -> B) (pointwise_relation A R_B) (fun_Join A B).\n  Proof.\n    hnf; intros.\n    unfold join, fun_Join in H.\n    unfold Krelation, pointwise_relation in H0.\n    destruct (choice (fun x n => join (n1 x) (n2 x) (n) /\\\n                               Krelation (n) (m x)))\n      as [n H2].\n    intros x.\n    destruct (dSA_B (m1 x) (m2 x) (m x) (n1 x) (n2 x) (H x) (H0 x)) as [x1 [x2 ?]]; auto.\n    + apply H1.\n    + exists x1; auto.\n    + exists n; split; hnf; intros x; specialize (H2 x); destruct H2; auto.\n  Qed.\n\n  (* Exponential is increasing *)\n  Lemma fun_incrSA \n        (A B: Type)\n        {R_B: Relation B}\n        {J_B: Join B}\n        (incr_B: IncreasingSeparationAlgebra B):\n    @IncreasingSeparationAlgebra (A -> B) (pointwise_relation A R_B) (fun_Join A B).\n  Proof.\n    constructor; intros.\n    hnf; intros.\n    hnf; intros.\n    specialize (H a).\n    eapply all_increasing; eauto.\n  Qed.\n\n  (* Exponential is Unital*)\n  Lemma fun_unitSA \n        (A B: Type)\n        {R_B: Relation B}\n        {J_B: Join B}\n        (USA_B: UnitalSeparationAlgebra B):\n    @UnitalSeparationAlgebra (A -> B) (pointwise_relation A R_B) (fun_Join A B).\n  Proof.\n    constructor; intros.\n    destruct (choice (fun x mx => residue (n x) mx /\\ increasing mx)) as [M HH].\n    { intros;\n      specialize (incr_exists (n x)); intros [y HH];\n      exists y; auto. }\n    exists M; split.\n    + cut (forall x, residue (n x) (M x)).\n      - clear; unfold residue; intros.\n        apply choice in H; destruct H as [n' H].\n        exists n'; split; hnf; intros x;\n        specialize (H x); destruct H; auto.\n      - intros x; specialize (HH x); destruct HH; auto.\n    + unfold increasing; intros.\n      unfold join, fun_Join in H.\n      hnf; intros x.\n      specialize (HH x); destruct HH as [ _ HH].\n      apply HH.\n      auto.\n  Qed.\n\n  (* Exponential is Unital' *)\n  Lemma fun_unitSA' \n        (A B: Type)\n        {R_B: Relation B}\n        {J_B: Join B}\n        (USA'_B: UnitalSeparationAlgebra' B):\n    @UnitalSeparationAlgebra' (A -> B) (pointwise_relation A R_B) (fun_Join A B).\n  Proof.\n    constructor; intros.\n    destruct (choice (fun x mx => residue (n x) mx /\\ increasing' mx)) as [M HH].\n    { intros;\n      specialize (incr'_exists (n x)); intros [y HH];\n      exists y; auto. }\n    exists M; split.\n    + cut (forall x, residue (n x) (M x)).\n      - clear; unfold residue; intros.\n        apply choice in H; destruct H as [n' H].\n        exists n'; split; hnf; intros x;\n        specialize (H x); destruct H; auto.\n      - intros x; specialize (HH x); destruct HH; auto.\n    + unfold increasing', increasing; intros.\n      unfold join, fun_Join in H.\n      hnf; intros x.\n      specialize (HH x); destruct HH as [ _ HH].\n      eapply (HH _); eauto.\n      apply H.\n  Qed.\n\nEnd exponentialSA.\n\nSection sumSA.\n\n  Inductive sum_worlds {worlds1 worlds2}: Type:\n    Type:=\n  | lw (w:worlds1): sum_worlds\n  | rw (w:worlds2): sum_worlds.\n\n  Inductive sum_join {A B: Type} {J1: Join A} {J2: Join B}:\n    @sum_worlds A B ->\n    @sum_worlds A B ->\n    @sum_worlds A B-> Prop :=\n  | left_join a b c:\n      join a b c ->\n      sum_join (lw a) (lw b) (lw c)\n  | right_join a b c:\n      join a b c ->\n      sum_join (rw a) (rw b) (rw c).\n\n  Definition sum_Join (A B: Type) {Join_A: Join A} {Join_B: Join B}: Join (@sum_worlds A B) :=\n    (@sum_join A B Join_A Join_B).\n\n  Definition sum_SA (A B: Type) {Join_A: Join A} {Join_B: Join B} {SA_A: SeparationAlgebra A} {SA_B: SeparationAlgebra B}: @SeparationAlgebra (@sum_worlds A B) (sum_Join A B).\n  Proof.\n    constructor.\n    - intros; inversion H;\n      constructor; apply join_comm; auto.\n    - intros.\n      inversion H; subst;\n      inversion H0;\n      destruct (join_assoc _ _ _ _ _ H1 H3) as [myz [HH1 HH2]].\n      + exists (lw myz); split; constructor; auto.\n      + exists (rw myz); split; constructor; auto.\n  Qed.\n\nEnd sumSA.\n\nSection productSA.\n\n  Definition prod_Join (A B: Type) {Join_A: Join A} {Join_B: Join B}: Join (A * B) :=\n    (fun a b c => join (fst a) (fst b) (fst c) /\\ join (snd a) (snd b) (snd c)).\n\n  Definition prod_SA (A B: Type) {Join_A: Join A} {Join_B: Join B} {SA_A: SeparationAlgebra A} {SA_B: SeparationAlgebra B}: @SeparationAlgebra (A * B) (prod_Join A B).\n  Proof.\n    constructor.\n    + intros.\n      simpl in *.\n      destruct H; split;\n      apply join_comm; auto.\n    + intros.\n      simpl in *.\n      destruct H, H0.\n      destruct (join_assoc _ _ _ _ _ H H0) as [myz1 [? ?]].\n      destruct (join_assoc _ _ _ _ _ H1 H2) as [myz2 [? ?]].\n      exists (myz1, myz2).\n      do 2 split; auto.\n  Qed.\n\n  Lemma prod_uSA\n        (A B: Type)\n        {R_A: Relation A}\n        {R_B: Relation B}\n        {Join_A: Join A}\n        {Join_B: Join B}\n        {dSA_A: UpwardsClosedSeparationAlgebra A}\n        {dSA_B: UpwardsClosedSeparationAlgebra B}:\n    @UpwardsClosedSeparationAlgebra (A * B) (RelProd R_A R_B) (@prod_Join _ _ Join_A Join_B).\n  Proof.\n    intros until m2; intros.\n    destruct H, H0.\n    destruct (join_Korder_up _ _ _ _ H H0) as [fst_n1 [fst_n2 [? [? ?]]]].\n    destruct (join_Korder_up _ _ _ _ H1 H2) as [snd_n1 [snd_n2 [? [? ?]]]].\n    exists (fst_n1, snd_n1), (fst_n2, snd_n2).\n    do 2 split; simpl; auto;\n    constructor; auto.\n  Qed.\n\n  Lemma prod_dSA\n        (A B: Type)\n        {R_A: Relation A}\n        {R_B: Relation B}\n        {Join_A: Join A}\n        {Join_B: Join B}\n        {uSA_A: DownwardsClosedSeparationAlgebra A}\n        {uSA_B: DownwardsClosedSeparationAlgebra B}:\n    @DownwardsClosedSeparationAlgebra (A * B) (RelProd R_A R_B) (@prod_Join _ _ Join_A Join_B).\n  Proof.\n    intros until n2; intros.\n    destruct H, H0, H1.\n    destruct (join_Korder_down _ _ _ _ _ H H0 H1) as [fst_n [? ?]].\n    destruct (join_Korder_down _ _ _ _ _ H2 H3 H4) as [snd_n [? ?]].\n    exists (fst_n, snd_n).\n    do 2 split; simpl; auto.\n  Qed.\n\n  Lemma prod_incr\n        (A B: Type)\n        {R_A: Relation A}\n        {R_B: Relation B}\n        {Join_A: Join A}\n        {Join_B: Join B}:\n    forall (a: A) (b: B),\n      increasing a -> increasing b ->\n      @increasing _\n                   (RelProd R_A R_B)\n                   (@prod_Join _ _ Join_A Join_B) (a,b).\n  Proof.\n    intros. hnf; intros.\n    destruct n, n'.\n    inversion H1; simpl in *.\n    hnf; intros; split.\n    apply H; auto.\n    apply H0; auto.\n  Qed.\n\n  Lemma prod_incrSA\n        (A B: Type)\n        {R_A: Relation A}\n        {R_B: Relation B}\n        {Join_A: Join A}\n        {Join_B: Join B}\n        {incrSA_A: IncreasingSeparationAlgebra A}\n        {incrSA_B: IncreasingSeparationAlgebra B}:\n    @IncreasingSeparationAlgebra (A * B) (RelProd R_A R_B) (@prod_Join _ _ Join_A Join_B).\n  Proof.\n    constructor; intros.\n    destruct x; apply prod_incr; auto.\n    + apply incrSA_A.\n    + apply incrSA_B.\n  Qed.\n\n  Lemma prod_residualSA\n        (A B: Type)\n        {R_A: Relation A}\n        {R_B: Relation B}\n        {Join_A: Join A}\n        {Join_B: Join B}\n        {residualSA_A: ResidualSeparationAlgebra A}\n        {residualSA_B: ResidualSeparationAlgebra B}:\n    @ResidualSeparationAlgebra (A * B) (RelProd R_A R_B) (@prod_Join _ _ Join_A Join_B).\n  Proof.\n    constructor; intros.\n    destruct n as [a b].\n    inversion residualSA_A;\n      inversion residualSA_B.\n    destruct (residue_exists a) as [a' [a'' [Ha1 Ha2]]].\n    destruct (residue_exists0 b) as [b' [b'' [Hb1 Hb2]]].\n    exists (a', b'); hnf; intros.\n    exists (a'', b''); hnf; intros;\n    split; hnf; intros;\n    split; simpl; auto.\n  Qed.\n\n  Lemma prod_unitalSA\n        (A B: Type)\n        {R_A: Relation A}\n        {R_B: Relation B}\n        {Join_A: Join A}\n        {Join_B: Join B}\n        {unitalSA_A: UnitalSeparationAlgebra A}\n        {unitalSA_B: UnitalSeparationAlgebra B}:\n    @UnitalSeparationAlgebra (A * B) (RelProd R_A R_B) (@prod_Join _ _ Join_A Join_B).\n  Proof.\n    inversion unitalSA_A.\n    inversion unitalSA_B.\n    constructor; intros.\n    - destruct n as [a b].\n      destruct (incr_exists a) as [a' [Ha1 Ha2]].\n      destruct (incr_exists0 b) as [b' [Hb1 Hb2]].\n      exists (a', b'); split; hnf; intros.\n      + destruct Ha1 as [a'' [Ha1 Ha3]].\n        destruct Hb1 as [b'' [Hb1 Hb3]].\n        exists (a'',b''); split; hnf; hnf; intros; try constructor; simpl; auto.\n      + destruct n, n'.\n        inversion H; simpl in *.\n        apply Ha2 in H0.\n        apply Hb2 in H1.\n        split; auto.\n  Qed.\n\nEnd productSA.\n\nClass SeparationAlgebra_unit (worlds: Type) {J: Join worlds} := {\n                                                                 unit: worlds;\n                                                                 unit_join: forall n, join n unit n;\n                                                                 unit_spec: forall n m, join n unit m -> n = m\n                                                               }.\n\n(***********************************)\n(* Preorder examples               *)\n(***********************************)\n\n\n(***********************************)\n(* dSA uSA examples                *)\n(***********************************)\n\n\n(***********************************)\n(* More examples                   *)\n(***********************************)\n\n(*\nProgram Definition nat_le_kiM: KripkeIntuitionisticModel nat := \n  Build_KripkeIntuitionisticModel nat (fun a b => a <= b) _.\nNext Obligation.\n  constructor; hnf; intros.\n  + apply le_n.\n  + eapply NPeano.Nat.le_trans; eauto.\nQed.\n\n(* TODO: Probably don't need this one. *)\nProgram Definition SAu_kiM (worlds: Type) {J: Join worlds} {SA: SeparationAlgebra worlds} {SAu: SeparationAlgebra_unit worlds} : KripkeIntuitionisticModel worlds :=\n  Build_KripkeIntuitionisticModel worlds (fun a b => exists b', join b b' a) _.\nNext Obligation.\n  constructor; hnf; intros.\n  + exists unit; apply unit_join.\n  + destruct H as [? ?], H0 as [? ?].\n    destruct (join_assoc _ _ _ _ _ H0 H) as [? [? ?]].\n    exists x2; auto.\nQed.\n\nDefinition Heap (addr val: Type): Type := addr -> option val.\n\nInstance Heap_Join (addr val: Type): Join (Heap addr val) :=\n  @fun_Join _ _ (@option_Join _ (equiv_Join _)).\n\nInstance Heap_SA (addr val: Type): SeparationAlgebra (Heap addr val) :=\n  @fun_SA _ _ _ (@option_SA _ _ (equiv_SA _)).\n\nInstance mfHeap_kiM (addr val: Type): KripkeIntuitionisticModel (Heap addr val) :=\n  identity_kiM _.\n\nInstance gcHeap_kiM (addr val: Type): KripkeIntuitionisticModel (Heap addr val) :=\n  @fun_kiM _ _ (@option_ord_kiM _ (identity_kiM _)).\n\nDefinition Stack (LV val: Type): Type := LV -> val.\n\nDefinition StepIndex_kiM (worlds: Type) {po_R: PreOrder Krelation}: KripkeIntuitionisticModel (nat * worlds) := @prod_kiM _ _ nat_le_kiM kiM.\n\nDefinition StepIndex_Join (worlds: Type) {J: Join worlds}: Join (nat * worlds) :=\n  @prod_Join _ _ (equiv_Join _) J.\n\nDefinition StepIndex_SA (worlds: Type) {J: Join worlds} {SA: SeparationAlgebra worlds}:\n  @SeparationAlgebra (nat * worlds) (StepIndex_Join worlds) := @prod_SA _ _ _ _ (equiv_SA _) SA.\n\nDefinition StepIndex_dSA (worlds: Type) {po_R: PreOrder Krelation}\n           {J: Join worlds} {dSA: UpwardsClosedSeparationAlgebra worlds}:\n  @UpwardsClosedSeparationAlgebra (nat * worlds) (StepIndex_Join worlds) (StepIndex_kiM worlds):= @prod_dSA _ _ _ _ _ _ (@identity_dSA _ nat_le_kiM) dSA.\n\n *)", "meta": {"author": "QinxiangCao", "repo": "UnifySL", "sha": "cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d", "save_path": "github-repos/coq/QinxiangCao-UnifySL", "path": "github-repos/coq/QinxiangCao-UnifySL/UnifySL-cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d/SeparationLogic/Model/OSAGenerators.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6521831203537252}}
{"text": "Require Import Coq.Bool.Bool.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import Crypto.Util.ZUtil.Notations.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Testbit.\n\nLocal Open Scope bool_scope. Local Open Scope Z_scope.\n\nModule Z.\n  Lemma lor_m1'_r x : Z.lor x (-1) = -1.\n  Proof. apply Z.lor_m1_r. Qed.\n#[global]\n  Hint Rewrite lor_m1'_r : zsimplify_const zsimplify zsimplify_fast.\n\n  Lemma lor_m1'_l x : Z.lor (-1) x = -1.\n  Proof. apply Z.lor_m1_l. Qed.\n#[global]\n  Hint Rewrite lor_m1'_l : zsimplify_const zsimplify zsimplify_fast.\n\n  Lemma lor_add a b (Hand : a &' b = 0) : a |' b = a + b.\n  Proof. rewrite <- Z.lxor_lor, Z.add_nocarry_lxor by assumption; reflexivity. Qed.\n\n  Lemma lor_small_neg a b\n        (Ha : - 2^b <= a < 0)\n        (Hb : 0 < b) :\n    2^b |' a = a.\n  Proof.\n    apply Z.bits_inj_iff; red; intros; rewrite Z.lor_spec.\n    destruct (Z.eqb_spec b n); subst.\n    - now rewrite (Testbit.Z.testbit_small_neg a), orb_true_r.\n    - now rewrite Z.pow2_bits_false, orb_false_l. 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/Lor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6521831080378433}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat seq path order eqtype. \nFrom okasaki Require Import ssrlia.\nRequire Import Psatz.\nImport Order.TTheory.\nNotation ordType := (orderType tt).\nImport Order.NatOrder.\nFrom Equations Require Import Equations.\n\nOpen Scope order_scope.\n\nLemma snd_true3 a b : a || true || b.\nProof. by case: a. Qed.\n\nLemma trd_true3 a b : b || a || true.\nProof. by case: a; case b. Qed.\n\nLemma snd_true2 a : a || true.\nProof. by case: a. Qed.\n\nLemma add_lt_le a b c d: (a < c)%N -> (b <= d)%N -> (a + b < c + d)%N.\nProof. by move=> *; rewrite [a + b]addnC -ltn_subRL -addnBA // ltn_addr. Qed.\n\nLemma add_le_lt a b c d: (a <= c)%N -> (b < d)%N -> (a + b < c + d)%N.\nProof. move=> *; rewrite [a + b]addnC [c + d]addnC. by apply: add_lt_le. Qed.\n\n\nHint Resolve trd_true3 snd_true3 snd_true2 lexx ltxx : core.\n\nModule leftistheap.\n(* Leftist heaps are heap-ordered binary trees that satisfy the                         *)\n(* leftist property: the rank of any left child is at least as large as the rank of its *)\n(* right sibling. The rank of a node is defined to be the length of its right spine     *)\n(* (i.e., the rightmost path from the node in question to an empty node).               *)\nSection LeftistDef.\nVariables (T: ordType).\n\nInductive heap :=\n| Emp : heap\n| Node : nat -> T-> heap -> heap -> heap.\n\nEnd LeftistDef.\nArguments Node {T}.\nArguments Emp {T}.\nNotation \"[ tl | n , x | tr ]\" := (Node n x tl tr) (at level 0).\nNotation \"'[||]'\" := Emp.\n\n(* Definition of arbitrary measure on Heaps *)\nModule Measure.\nStructure mixin_of {T : ordType} (measure : heap T -> nat) :=\n  Mixin {\n    measure1            : nat;\n    f                   : nat -> nat -> nat;\n    measureNode         : forall tl tr n x, measure [tl| x, n |tr] = f (measure tl) (measure tr);\n    measure_NodexEE     : f (measure [||]) (measure [||]) = measure1;\n    measure_Node_E      : forall h1 h2 n x, (measure [||] < measure [h1 | n, x | h2])%N\n  }.\n\nNotation class_of := mixin_of (only parsing).\n\nSection classdef.\n\nStructure type T := Pack { sort; _ : @class_of T sort }.\n\nLocal Coercion sort : type >-> Funclass.\n\nVariables (T : ordType) (cT : (type T)).\n\n(** Projection out of [type] *)\nDefinition class :=\n  let: Pack _ c := cT return class_of cT in c.\n\nEnd classdef.\nModule Exports.\n\nCoercion sort : type >-> Funclass.\n(** Some shorthands *)\nNotation measureType := type.\n\nNotation MeasureMixin := Mixin.\n\nEnd Exports.\nEnd Measure.\n\nSection Specifications.\nExport Measure.Exports.\nVariables (T : ordType).\nImplicit Type h : heap T.\n\nDefinition empty h :=\nif h is Emp then true else false.\n\nTheorem emptyP h : reflect (h = Emp) (empty h).\nProof. case h; by constructor. Qed.\n\n\n(* Definition of decidable equality on Heaps  *)\nFixpoint eqheap h1 h2 :=\n  match h1, h2 with\n  | Emp, Emp => true\n  | Node n1 x1 tl1 tr1, Node n2 x2 tl2 tr2 => [&& (n1 == n2), (x1 == x2), eqheap tl1 tl2 & eqheap tr1 tr2]\n  | _, _ => false\n  end.\n\nLemma eqheapP : Equality.axiom eqheap.\nProof.\nelim=> [|??? IHh1 ? IHh2] [|*] /=; try by constructor.\nby apply: (iffP and4P); case=> [/eqP-> /eqP-> /IHh1-> /IHh2->].\nQed.\n\nCanonical heap_eqMixin := EqMixin eqheapP.\nCanonical heap_eqType := Eval hnf in EqType (heap T) heap_eqMixin.\n\nLemma eqheapE : eqheap = eq_op. Proof. by []. Qed.\n\nFixpoint mem_heap h :=\n  if h is Node _ y tl tr then xpredU1 y (xpredU (mem_heap tl) (mem_heap tr)) else xpred0.\n\nDefinition heap_eqclass := heap T.\nIdentity Coercion heap_of_eqclass : heap_eqclass >-> heap.\nCoercion pred_of_heap (h : heap_eqclass) : {pred T} := mem_heap h.\n\nCanonical heap_predType := PredType pred_of_heap.\n(* The line below makes mem_heap a canonical instance of topred. *)\nCanonical mem_heap_predType := PredType mem_heap.\n\nLemma in_node x y n tl tr: \n  x \\in [tl | n, y | tr] = [|| x == y, x \\in tl | x \\in tr].\nProof. by []. Qed.\n\n(* Definition of rank and size and simple properties *)\nSection Mesures.\n\nFixpoint rank h : nat := if h is Node _ _ _ b then (rank b).+1 else O.\n\nDefinition f1 (x y : nat) := y.+1.\n\nLemma rank__NodexEE : f1 (rank [||]) (rank  [||]) = 1%N.\nProof. by []. Qed.\n\nLemma rankNode tl tr n x : rank [tl| x, n |tr] = f1 (rank tl) (rank tr).\nProof. by []. Qed.\n\nLemma rank_Node_E h1 h2 n x : (rank  [||] < rank [h1 | n, x | h2])%N.\nProof. by []. Qed.\n\nFixpoint size h : nat :=\nif h is Node _ _ a b then (size a) + (size b) + 1 else O.\n\nDefinition f2 (x y : nat) := x + y + 1.\n\nLemma sizeNode tl tr n x : size [tl| x, n |tr] = f2 (size tl) (size tr).\nProof. by []. Qed.\n\nLemma size__NodexEE : f2 (size  [||]) (size  [||]) = 1%N.\nProof. by []. Qed.\nLemma size_Node_E h1 h2 n x : (size  [||] < size [h1 | n, x | h2])%N.\nProof. by rewrite addn_gt0 leqnn. Qed.\n\nEnd Mesures.\n\n(* Definition of count, all and simple properties *)\nSection HeapCount.\nVariables a : pred T.\n\nFixpoint count h : nat := if h is [tl| _, x |tr] then a x + count\n tl + count tr else 0.\n\nLemma count_Node tl tr y n: count [tl| n, y |tr] = a y + count tl + count tr.\nProof. by []. Qed.\n\nLemma count_E : count [||] = 0.\nProof. by []. Qed.\n\nLemma count_NodexEE n y : count [[||]| n, y | [||]] = a y.\nProof. by rewrite /= !addn0. Qed.\n\nFixpoint all h := \nif h is [tl| _, x |tr] then [&& a x, (all tl) & all tr] else true.\n\nEnd HeapCount.\n\nLemma count_a_predT a h : (count a h <= count predT h)%N.\nProof. elim: h=> //= n s *; case: (a s); by repeat apply: leq_add. Qed.\nHint Resolve count_a_predT: core.\n\nLemma size_count h : size =1 count predT.\nProof. by elim=> //= n x h1 -> h2->; ssrnatlia. Qed.\n\nLemma allE h a : reflect (count a h = size h) (all a h).\nProof.\nrewrite size_count //.\nelim: h => /= [| _ s h1 /(sameP eqP) <- h2 /(sameP eqP) <-]; first by constructor.\napply/introP => [/and3P[-> /eqP-> /eqP->]|] // H.\nsuffices: ((a s) + count a h1 + count a h2 < 1 + count predT h1 + count predT h2)%N.\n- by move=> LE EQ; move: EQ LE=>->; rewrite ltnn.\nmove: H=> /nandP[/negPf->|/nandP[] H] //=.\n- apply: add_lt_le=> //; apply : add_lt_le=> //.\n1: have: (count a h1 < count predT h1)%N=>*.\n3: have: (count a h2 < count predT h2)%N=>*.\n1,3: rewrite ltn_neqAle; apply/andP; by split.\n- apply: add_lt_le=> //; apply add_le_lt=> //; by case (a s).\n- apply: add_le_lt=> //. apply leq_add=> //; by case (a s).\nQed.\n\nLemma in_count x h: x \\in h = (0 < count (xpred1 x) h)%N.\nProof.\nelim h=> // ??? IHh1 ? IHh2; by rewrite in_node /= !addn_gt0 IHh1 IHh2 eq_sym lt0b orbA.\nQed.\n\n(* if h is heap oredered (see below) LE x h is same as   *)\n(* x is less or equal then all elements in heaps         *)\nDefinition LE x h : bool := \nif h is Node n y a b then (x <= y) else true.\n\nLemma LE_trans y x h: LE y h -> (x <= y) -> LE x h.\nProof. by case: h=> //= ???? H /le_trans/(_ H). Qed.\n\n(* Definition of heap ordered heaps and simpl properties *)\nFixpoint heap_ordered h : bool :=\nif h is Node n x tl tr then\n  [&& (LE x tl), (LE x tr), (heap_ordered tl) & (heap_ordered tr)]\nelse true.\n\nLemma LE_correct h x y: heap_ordered h -> x \\in h -> LE y h -> y <= x.\nProof.\nby elim: h x y=> [| n x h1 IHh1 h2 IHh2 x' y' /= /and4P[L1 L2 H1 H2]] //\n/or3P[/eqP ->|/(IHh1 _ _ H1)/(_ L1)|/(IHh2 _ _ H2)/(_ L2)] // H /le_trans/(_ H).\nQed.\n\nLemma LE_spec x h : heap_ordered h -> LE x h -> all (>= x) h.\nProof.\nelim h=> // n y h1 IHh1 h2 IHh2 /= /and4P[???? XY].\nby rewrite XY IHh1 // ?IHh2 // ?(LE_trans y).\nQed.\n\nFact heap_ordered_NodexEE n x : heap_ordered [ [||]| n, x |  [||]].\nProof. by []. Qed.\nHint Resolve heap_ordered_NodexEE: core.\nFact heap_ordered_E : heap_ordered [||]. Proof. by []. Qed.\n\n(* Some basic definitions for reasoning about spines in heaps *)\nVariant side := R | L.\n\nDefinition spine := seq side.\n\nFixpoint spine_in p h : bool :=\nmatch p, h with\n| R :: p, Node _ _ _ tr => spine_in p tr\n| L :: p, Node _ _ tl _ => spine_in p tl\n| [::],   Emp          => true\n| _,      _          => false\nend.\n\nFixpoint right p : bool :=\nmatch p with\n| R :: p' => right p'\n| L :: _  => false\n| [::]    => true\nend.\n\nLemma rigth_correct x s: right (x :: s) -> ((x = R) * right s).\nProof. by case: s; case x. Qed.\n\nLemma right_spine_ex h: exists s, right s && spine_in s h.\nProof.\nelim: h=> [|n s hl _ hr [] s']; by [exists nil| exists (R :: s')].\nQed.\n\nLemma spine_in_E s : spine_in s Emp -> s = [::].\nProof. by case: s=> [|[]] //=. Qed.\n\n(* Theory for heaps with leftist measure *)\n\nSection Measure.\nVariables measure : measureType T.\nDefinition measure1 : nat := Measure.measure1 _ (Measure.class T measure).\nDefinition measure_NodexEE := Measure.measure_NodexEE _ (Measure.class T measure).\nDefinition measureNode := Measure.measureNode _ (Measure.class T measure).\nDefinition measure_Node_E := Measure.measure_Node_E _ (Measure.class T measure).\nDefinition f := Measure.f _ (Measure.class T measure).\nHint Resolve measure_Node_E : core.\n\nFixpoint measure_inv h : bool :=\nmatch h with\n| [tl| n, x |tr] => [&& (n == measure h), (measure_inv tl) & (measure_inv tr)]\n| [||]           => true\nend.\n\nLemma measure_inv_NodexEE x : measure_inv [ [||]| measure1, x | [||]].\nProof. by rewrite /= measureNode measure_NodexEE eq_refl. Qed.\nHint Resolve measure_inv_NodexEE : core.\n\nFact measure_E : measure_inv [||]. Proof. by []. Qed.\n\n(* leftist invariant for arbitrary mesure and defonition of leftist heap *)\nFixpoint leftist_inv h : bool :=\nif h is Node n x tl tr then\n  [&& (measure tr <= measure tl)%N, (leftist_inv tl) & (leftist_inv tr)]\nelse true.\n\nFact leftist_inv_NodexEE n x : leftist_inv [[||]| n, x |  [||]].\nProof. move=> /=; by rewrite leqnn. Qed.\nHint Resolve leftist_inv_NodexEE : core.\n\nFact leftist_inv_E : leftist_inv [||]. Proof. by []. Qed.\n\nDefinition leftist_measure_inv h := leftist_inv h && measure_inv h.\n\nLemma case_leftist_measure_inv_r n x tl tr :\nleftist_measure_inv (Node n x tl tr) -> leftist_measure_inv tr.\nProof.\nby rewrite /leftist_measure_inv /= => /and3P[/and3P[_ _ -> _ /andP[]]].\nQed.\n\nLemma case_leftist_measure_inv_rl n x tl tr:\nleftist_measure_inv (Node n x tl tr) -> \n[&& leftist_measure_inv tr, leftist_measure_inv tl & (measure tr <= measure tl)%N].\nProof.\nby rewrite /leftist_measure_inv => /andP[] /= => /and3P[->->-> /and3P[_ ->->]].\nQed.\n\nLemma case_leftist_measure_inv n x tl tr: \nleftist_measure_inv (Node n x tl tr) -> (n == f (measure tl) (measure tr)) &&\n[&& leftist_measure_inv tr, leftist_measure_inv tl & (measure tr <= measure tl)%N].\nProof.\nmove=> LI. move: LI (LI)=> /case_leftist_measure_inv_rl -> /andP[_] /= /and3P[]; \nby rewrite measureNode=>->.\nQed. \n\nDefinition leftistheap h :=\n[&& leftist_inv h, measure_inv h & heap_ordered h].\n\nFact leftistheap_NodexEE x : leftistheap [[||]| measure1, x |[||]].\nProof. by rewrite /leftistheap measure_inv_NodexEE heap_ordered_NodexEE leftist_inv_NodexEE. Qed.\nHint Resolve leftistheap_NodexEE : core.\n\nFact leftistheap_E : leftistheap  [||].\nProof. by rewrite /leftistheap. Qed.\nHint Resolve leftistheap_E : core.\n\n(* makeT takes two heaps and element and make heap from them *)\n(* with correct mesure                                       *)\nDefinition makeT (x : T) h1 h2 :=\nlet m1 := measure h1 in\n  let m2 := measure h2 in\n      if (m2 <= m1)%N then [h1| f m1 m2, x |h2] else [h2| f m2 m1, x |h1] .\n\nLemma makeT_LI_inv x tl tr : leftist_inv tl -> leftist_inv tr ->\nleftist_inv (makeT x tl tr).\nProof. \nrewrite /makeT; case: ifP=> H /=->->; first by rewrite H.\n- suffices: (measure tl <= measure tr)%N => [->|] //; move: H.\nmove=> /neq0_lt0n; by ssrnatlia.\nQed.\n\nLemma makeT_rk_inv x tl tr : measure_inv tl -> measure_inv tr ->\nmeasure_inv (makeT x tl tr).\nProof.\nby rewrite /makeT; case: ifP=> /= _ ->->; rewrite measureNode eq_refl. \nQed.\n\nLemma makeT_peserve_HO_inv x tl tr :\nheap_ordered tl -> heap_ordered tr -> LE x tl -> LE x tr ->\n heap_ordered (makeT x tl tr).\nProof. rewrite /makeT; by case: ifP => _ /=->->->->. Qed.\n\nLemma makeT_spec h1 h2 x a:\ncount a (makeT x h1 h2) = a x + count a h1 + count a h2.\nProof. rewrite /makeT; case: ifP=> /=; ssrnatlia. Qed.\n\nLemma makeT_in_spec h1 h2 x y :\nx \\in (makeT y h1 h2) = ((x == y) || (x \\in h1) || (x \\in h2)).\nProof.\nby rewrite !in_count makeT_spec eq_sym; case : (x == y)=> /=; rewrite !addn_gt0.\nQed.\n\n(* fuction merge makes from two heaps nwe one that contains *)\n(* same elements (see merge_spec)                           *)\n(* Here your can see special total realization of merge     *)\nFixpoint merge' a :=\nif a is Node n x a1 b1 then\nlet fix merge_a b :=\n  if b is Node m y a2 b2 then\n    if x <= y then \n      makeT x a1 (merge' b1 b)\n    else\n      makeT y a2 (merge_a b2)\n  else a in\nmerge_a\nelse id.\n\nArguments merge' !tl !tr : rename.\nDefinition merge := nosimpl merge'.\n\nLtac merge_cases := match goal with \n| H : (?x <= ?y) = true |- _ => move: (H); rewrite /merge /= =>->; rewrite ?H\n| H : (?x <= ?y) = false |- _ => move: (H)=> /merge_a /= ->; rewrite ?H\nend. \n\nLtac merge_casesxy x y := case H : (x <= y); merge_cases.\n\nLemma merge_E_h h: merge Emp h = h.\nProof. by []. Qed.\n\nLemma merge_h_E h: merge h Emp = h.\nProof. by case: h. Qed.\n\nLemma merge_a nl nr x y tll tlr trr trl : (x <= y) = false -> \nmerge (Node nl x tll tlr) (Node nr y trl trr) = \nmakeT y trl (merge  (Node nl x tll tlr) trr).\nProof. rewrite /merge /= => ->. by elim: trr. Qed.\n\nLemma merge_measure_inv h1 h2:\nmeasure_inv h1 -> measure_inv h2 -> measure_inv (merge h1 h2) .\nProof.\nelim: h1 h2=> // ? x ??? IHhr. elim=> // ? y ??? IH'hr.\nmerge_casesxy x y => /and3P[E M M' /and3P[EQ M1 M2]];\nby rewrite makeT_rk_inv // (IHhr, IH'hr) //= (EQ, E) (M1, M) (M2, M').\nQed.\n\nLemma merge_LE h1 h2 x: LE x h1 -> LE x h2 -> LE x (merge h1 h2).\nProof.\nelim: h1 h2 x => // ? x ????. elim=> // ? y *. \nby merge_casesxy x y; rewrite /makeT; case: ifP.\nQed.\n\nLemma merge_HO_inv h1 h2:\nheap_ordered h1 -> heap_ordered h2 -> heap_ordered (merge h1 h2).\nProof.\nelim: h1 h2=> // ? x ??? IHhr. elim=> // ? y ??? IH'hr H1 H2.\nmove : (H1) (H2)=> /and4P[???? /and4P[????]]. by merge_casesxy x y;\nrewrite makeT_peserve_HO_inv ?IHhr ?IH'hr ?merge_LE //=; move: H; case: ltgtP.\nQed.\n\nLemma merge_LI_inv h1 h2:\n leftist_inv h1 -> leftist_inv h2 -> leftist_inv (merge h1 h2).\nProof.\nelim: h1 h2=> // ? x ??? IHhr. elim=> // ? y ??? IH'hr H1 H2.\nmove : (H1) (H2) => /and3P[??? /and3P[*]]. merge_casesxy x y; \nby rewrite makeT_LI_inv ?IHhr ?IH'hr.\nQed.\n\nTheorem merge_LH h1 h2 :\nleftistheap h1 -> leftistheap h2 -> leftistheap (merge h1 h2).\nProof.\nmove=> /and3P[???/and3P[*]].\nby rewrite /leftistheap merge_LI_inv ?merge_measure_inv ?merge_HO_inv.\nQed.\n\nTheorem merge_spec h1 h2 a:  count a (merge h1 h2) = count a h1 + count a h2.\nProof.\nelim: h1 h2=> [?|? x ??? IHh2] //. elim=> [/=|? y ??? IHh22]; first by ssrnatlia.\nby merge_casesxy x y; rewrite makeT_spec ?IHh2 ?IHh22 /=; ssrnatlia.\nQed.\n\nLemma merge_size h1 h2 : size (merge h1 h2) = size h1 + size h2.\nProof. by rewrite !size_count ?merge_spec. Qed.\n\nTheorem merge_in_spec  h1 h2 x : x \\in (merge h1 h2) = ((x \\in h1) || (x \\in h2)).\nProof. by rewrite !in_count merge_spec !addn_gt0. Qed.\n\n(* Two defenition of insert, their equality and some properties *)\nDefinition insert (x : T) h :=  merge [[||]| measure1, x | [||]] h.\n\nFixpoint insert' (x : T) h :=\nif h is Node n y a b then\nlet h' := Node n y a b in \n  if x <= y then\n    Node (f (measure h') (measure [||])) x h' Emp\n  else makeT y a (insert' x b)\nelse Node measure1 x Emp Emp.\n\nLemma insert_measure_inv h x: measure_inv h -> measure_inv (insert x h).\nProof. by move=> *; apply: merge_measure_inv. Qed.\n\nLemma insert_HO_inv h x: heap_ordered h -> heap_ordered (insert x h).\nProof. by move=> *; apply: merge_HO_inv. Qed.\n\nLemma insert_LI_inv h x: leftist_inv h -> leftist_inv (insert x h).\nProof. by move=> *; apply: merge_LI_inv. Qed.\n\nTheorem insert_LH h x: leftistheap h -> leftistheap (insert x h).\nProof. by move=> *; apply: merge_LH. Qed.\n\nTheorem insert_spec h x a : count a (insert x h) = a x + count a h.\nProof. by rewrite merge_spec /=; ssrnatlia. Qed.\n\nLemma insert_size h x: size (insert x h) = (size h).+1.\nProof. by rewrite !size_count ?merge_spec. Qed.\n\nTheorem insertE x h : measure_inv h -> leftist_inv h -> insert' x h = insert x h.\nProof.\nrewrite /insert. elim h=> // n y h1 IHh1 h2 IHh2 /= /and3P[??? /and3P[*]].\nmerge_casesxy x y=> //; rewrite ?IHh2 // /makeT.\nhave: (measure [h1 | n, y | h2] <= measure [||] = false)%N=> [|->] //.\nby apply/negbTE; rewrite -ltnNge. \nQed.\n\nTheorem insert_in_spec h x y : x \\in (insert y h) = ((x == y) || (x \\in h)).\nProof. \nrewrite merge_in_spec /= !in_node; case (x == y); by case (x \\in h).\nQed.\n\n\n(* Properties of findmin function *)\nDefinition findmin h := \nif h is Node _ x _ _ then Some x else None.\n\nTheorem findmin_None h: None = findmin h <-> h = [||].\nProof. split=> [|-> //]. by case : h. Qed.\n\nTheorem findmin_Some h z: heap_ordered h ->\nSome z = findmin h -> all (>= z) h.\nProof. \ncase: h=> //= _ ??? /and3P[?? /andP[?? [->]]]; by rewrite lexx ?LE_spec. \nQed.\n\nLemma findmin_cases h: (exists x, Some x = findmin h) \\/ (h = Emp).\nProof. case: h=> [|n z h1 h2 /=]; first by right. by left; exists z. Qed.\n\nTheorem findmin_spec x h: heap_ordered h -> \n((x \\in h) && LE x h) <-> (Some x = findmin h).\nProof.\nsplit=> [/andP[]|]; move: h H=> [] //.\n- move=> n y h1 h2 /= /and4P[L1 L2 H1 H2]\n  /or3P[/eqP-> //|/(LE_correct _ _ _ H1)/(_ L1)|/(LE_correct _ _ _ H2)/(_ L2)] XY YX;\nsuffices: x = y=> [-> //|]; apply: le_anti; rewrite XY YX //.\nmove=> ????? [->]. by rewrite in_node eq_refl /=.\nQed.\n\n(* Properties of findmin function *)\nDefinition deletemin h := if h is Node _ _ a b then merge a b else Emp.\n\nLemma case_leftistheap n x h1 h2 :\nleftistheap (Node n x h1 h2) -> leftistheap h1 && leftistheap h2.\nProof.\nby rewrite/leftistheap=>/and3P[/=/and3P[_->->/=/and3P[_->->/and4P[_ _->->]]]].\nQed.\n\nLemma deletemin_rk_inv h: measure_inv h -> measure_inv (deletemin h).\nProof. case: h=> //= ???? /and3P[*]; by rewrite merge_measure_inv. Qed.\n\nLemma deletemin_ho_inv h: heap_ordered h -> heap_ordered (deletemin h).\nProof. case: h=> //= ???? /and4P[*]. by rewrite merge_HO_inv. Qed.\n\n\nLemma deletemin_LI_inv h: leftist_inv h -> leftist_inv (deletemin h).\nProof. case: h=> //= ???? /and3P[*]. by rewrite merge_LI_inv. Qed.\n\nLemma deletemin_correct h:\nleftistheap h -> leftistheap (deletemin h).\nProof.\nby case: h=> //=???? H; apply merge_LH; move: H=> /case_leftistheap/andP[].\nQed.\n\nTheorem deletemin_spec h x: \n  Some x = findmin h <-> (count^~ (insert x (deletemin h)) =1 count^~ h).\nProof.\n\ncase: h=> /=; first (split=> // /(_ (pred1 x)) /=; by rewrite eq_refl).\nmove=> _ s??; split=> [[-> a]|/(_ (pred1 x))]; \nrewrite insert_spec merge_spec addnA // -2?addnA=> /eqP; \nrewrite eqn_add2r/= eq_refl=> /eqP/esym. case E: (s == x)=> //. by rewrite (eqP E).\nQed.\n\nLemma deletemin_size h : size (deletemin h) = (size h).-1.\nProof. case: h=> // n x tl tr; by rewrite ?size_count //= merge_spec. Qed.\n\nTheorem deletemin_in_spec h x y:\nSome x = findmin h -> (y \\in (insert x (deletemin h))) = (y \\in h).\nProof.\ncase: h=> // ???? [->]. \nby rewrite insert_in_spec /deletemin merge_in_spec // orbA.\nQed.\n\n(* In this section we define heapsort and prove it's properties *)\n(* heapsort fist translates sequense of elements into heap and  *)\n(* than takes the minimal element of the heap while it is not   *)\n(* empty                                                        *)\nSection Heapsort.\nImplicit Type hh : seq (option (heap T)).\n\nFixpoint seq_to_seqheap (st : seq T) :=\nif st is h :: t then cons [ [||]| measure1, h | [||]] (seq_to_seqheap t)\nelse [::].\n\nFixpoint count_sseq a hh := \n  if hh is sh :: hh' then \n    if sh is some h then count a h + count_sseq a hh' \n    else count_sseq a hh'\n  else 0.\n\nFixpoint count_seq a (sh : seq (heap T)) := \n  if sh is h :: sh' then count a h + count_seq a sh' else 0.\n\nTheorem seq_to_seqheap_spec s: count_seq^~ (seq_to_seqheap s) =1 seq.count^~ s.\nProof. move=> a; elim: s=> //= ??->; ssrnatlia. Qed.\n\n(* Now we want to define fromseq function that will translate  *)\n(* sequense of elements into heap in O(n) time                 *)\n(* Our implementation is based on divide and conqure principle *)\n(* adapted to total languages                                  *)\nFixpoint fromseqheap_push h1 hh :=\n  match hh with\n  | None :: hh' | [::] as hh' => (some h1) :: hh'\n  | (some h2) :: hh' => None :: fromseqheap_push (merge h2 h1) hh'\n  end.\n\nFixpoint fromseqheap_pop h1 hh :=\n  if hh is sh2 :: hh' then\n    let h2 := if sh2 is some h then h else [||] in\n   fromseqheap_pop (merge h2 h1) hh' else h1.\n\nFixpoint fromseqheap_rec hh sh  :=\n  match sh with\n  | [:: x1, x2 & h'] => let h1 := merge x1 x2 in\n    fromseqheap_rec (fromseqheap_push h1 hh) h'\n  | [:: h] => fromseqheap_pop h hh\n  | [::] => fromseqheap_pop [||] hh\n  end.\n\nDefinition fromseqheap := (fromseqheap_rec [::]).\n\nFixpoint fromseqheap_rec1 hh sh :=\n  if sh is x :: h then fromseqheap_rec1 (fromseqheap_push x hh) h else fromseqheap_pop (  [||]) hh.\n\nLemma fromseqheapE sh : fromseqheap sh = fromseqheap_rec1 [::] sh.\nProof.\ntransitivity (fromseqheap_rec1 [:: None] sh); last by case: sh.\nrewrite /fromseqheap; move: [::] {2}_.+1 (ltnSn (seq.size sh)./2) => hh n.\nelim: n => // n IHn in hh sh *. case: sh => [|x [|y s]] //=; by rewrite ?merge_h_E=> //= /IHn->.\nQed.\n\nDefinition fromseq := fromseqheap \\o seq_to_seqheap.\n\nLemma fromseqheap_pop_spec a h hh : \n  count a (fromseqheap_pop h hh) = count_sseq a hh + count a h.\nProof.\nelim: hh => [|[?|]? IHhh] //= in h *; by rewrite IHhh merge_spec; ssrnatlia.\nQed.\n\nLemma fromseqheap_push_spec h hh a: \n  count_sseq a (fromseqheap_push h hh )= count a h + count_sseq a hh.\nProof.\nelim: hh=> [|[?|]? IHhh] //= in h *. by rewrite IHhh merge_spec; ssrnatlia.\nQed.\n\nLemma fromseqheap_rec1_spec sh hh a: \n  count a (fromseqheap_rec1 hh sh) = count_sseq a hh + count_seq a sh.\nProof.\nelim: sh => [|?? IHsh] /= in hh *;\nby rewrite ?fromseqheap_pop_spec // IHsh fromseqheap_push_spec; ssrnatlia.\nQed.\n\nLemma fromseqheap_spec sh : \n count^~ (fromseqheap sh) =1 count_seq^~ sh.\nProof. move=> a; by rewrite fromseqheapE fromseqheap_rec1_spec. Qed.\n\nTheorem fromseq_cspec (s : seq T): \n  seq.count^~ s =1 count^~ (fromseq s).\nProof.\nmove=> a; by rewrite /fromseq /= fromseqheap_spec seq_to_seqheap_spec.\nQed.\n\n(* In this section we prove that fromseq s statisfy any invariant *)\n(* with spesial properties                                        *)\nSection Invariant.\nDefinition invariant := heap T -> bool.\n\nVariables inv : invariant.\n\nHypothesis merge_invariat : forall h1 h2, inv h1 -> inv h2 -> inv (merge h1 h2).\nHypothesis inv_E : inv [||].\nHypothesis inv_NodexEE : forall x, inv [[||]| measure1, x |  [||]].\nHint Resolve inv_E : core.\n\nDefinition some_inv sh := if sh is some h then inv h else true.\n\nLemma inv_fromseqheap_pop h sh: \n  (seq.all some_inv sh) -> inv h -> inv (fromseqheap_pop h sh).\nProof.\nelim: sh=> [|[?|]? IHhh] //= in h *=> /andP[*]; by rewrite IHhh ?merge_invariat. \nQed.\n\nLemma all_inv_fromseqheap_push h hh: inv h -> (seq.all some_inv hh) ->\nseq.all some_inv (fromseqheap_push h hh) = (inv h) && (seq.all some_inv hh).\nProof.\nby elim: hh=> [|[?|]? IHhh] //= in h *=> HH /andP[SH ?]; \nrewrite IHhh ?merge_invariat // HH SH.\nQed.\n\nLemma inv_fromseqheap_rec1 hh sh : \n(seq.all some_inv  hh) -> (seq.all inv sh) -> (inv (fromseqheap_rec1 hh sh)).\nProof.\nelim: sh => [|h sh IHsh] /= in hh *=> ?; rewrite ?inv_fromseqheap_pop //.\nmove => /andP[HH ?]. by rewrite IHsh ?all_inv_fromseqheap_push // HH.\nQed.\n\nLemma inv_fromseqheap sh : seq.all inv sh -> inv (fromseqheap sh).\nProof. move=> ASH; by rewrite fromseqheapE inv_fromseqheap_rec1. Qed.\n\nLemma all_inv_seq_toseqheap s : seq.all inv (seq_to_seqheap s).\nProof. elim: s=> //= a h->; by rewrite inv_NodexEE. Qed.\n\nLemma inv_fromseq s : inv (fromseq s).\nProof. by rewrite /fromseq /= inv_fromseqheap // all_inv_seq_toseqheap. Qed.\nEnd Invariant.\n\nLemma measure_inv_E : measure_inv [||].\nProof. by []. Qed.\n\nDefinition rank_rk_fromseq : forall s, measure_inv (fromseq s) := \n  inv_fromseq measure_inv merge_measure_inv measure_inv_E measure_inv_NodexEE.\n\nDefinition heap_ordered_fromseq : forall s, heap_ordered (fromseq s) := \n  inv_fromseq heap_ordered merge_HO_inv heap_ordered_E (heap_ordered_NodexEE measure1).\n\nDefinition leftist_inv_fromseq : forall s, leftist_inv (fromseq s) := \n  inv_fromseq leftist_inv merge_LI_inv leftist_inv_E (leftist_inv_NodexEE measure1).\n\nDefinition leftistheap_fromseq : forall s, leftistheap (fromseq s) := \n  inv_fromseq leftistheap merge_LH leftistheap_E leftistheap_NodexEE.\n\n\nEquations fromheap h : seq T by wf (size h) lt:=\nfromheap [||] := [::];\nfromheap [tl| n, x |tr] := x :: (fromheap (deletemin [tl| n, x |tr])).\n\nNext Obligation. rewrite merge_size; ssrnatlia. Qed.\n\nLemma fromheap_spec1 h: count^~ h =1 seq.count^~ (fromheap h).\nProof.\nmove=> p. apply_funelim (fromheap h)=> // ???? /= <-. by rewrite merge_spec; ssrnatlia.\nQed.\n\nLemma fromheap_srec1_in x h: (x \\in h) = (x \\in (fromheap h)).\nProof. by rewrite !in_count -has_pred1 has_count -fromheap_spec1. Qed.\n\nLemma fromheap_spec2 h: (heap_ordered h) -> sorted <=%O (fromheap h).\nProof.\napply_funelim (fromheap h)=> //= _ x h1 h2 IHh /and4P[L1 L2 H1 H2];\nrewrite path_sortedE ?IHh ?all_count -?count_predT -?fromheap_spec1 ?merge_spec ?merge_HO_inv //.\n- by rewrite (allE _ _ (LE_spec _ _ H1 L1)) (allE _ _ (LE_spec _ _ H2 L2)) !size_count // eq_refl.\nby exact le_trans.\nQed.\n\nDefinition heapsort s := fromheap (fromseq s).\n\nTheorem sorted_heapsort s : (sorted <=%O (heapsort s)).\nProof. by rewrite fromheap_spec2 // heap_ordered_fromseq. Qed.\n\nLemma count_heapsort s : seq.count^~ (heapsort s) =1 seq.count^~ s.\nProof. move=> p. by rewrite /heapsort -fromheap_spec1 fromseq_cspec. Qed.\n\nTheorem perm_heapsort s : perm_eql (heapsort s) s.\nProof. apply/permPl/permP; by apply: count_heapsort. Qed.\nEnd Heapsort.\nEnd Measure.\n\nDefinition rank_measureMixin : Measure.mixin_of rank := Measure.Mixin T rank 1%N f1 rankNode rank__NodexEE rank_Node_E.\nCanonical rank_measureType : measureType T := Measure.Pack T rank rank_measureMixin.\n\nDefinition size_measureMixin : Measure.mixin_of size := Measure.Mixin T size 1%N f2 sizeNode size__NodexEE size_Node_E.\nCanonical size_measureType : measureType T := Measure.Pack T size size_measureMixin.\n\nDefinition leftist_rank_inv := (leftist_measure_inv rank_measureType).\nDefinition case_leftist_rank_inv := (case_leftist_measure_inv rank_measureType).\nDefinition case_leftist_rank_inv_r := (case_leftist_measure_inv_r rank_measureType).\nDefinition case_leftist_rank_inv_rl := (case_leftist_measure_inv_rl rank_measureType).\n\nSection Grank.\n\n(** The (general) rank of a tree is the length of the shortest path from the root to leaves *)\nFixpoint grank h : nat :=\n  if h is Node _ _ tl tr then\n    (minn (grank tl) (grank tr)).+1\n  else 0.\n\nTheorem grank_rk h : leftist_rank_inv  h -> grank h = rank h.\nProof.\nelim: h=> // ??? IHh1 ? IHh2 /case_leftist_rank_inv/andP[].\nrewrite /f/=/f1=>_ /and3P[??].\nby rewrite IHh1 // IHh2 // minnC ?Order.NatOrder.minnE=> ->.\nQed.\n\nEnd Grank.\n\n(* We can obtain that right spine is the shoterst for heaps with *)\n(* rank measure                                                  *)\nSection Spine.\n\nLemma length_right_spine h s:\nleftist_rank_inv h -> right s -> spine_in s h -> length s = rank h.\nProof.\nmove=> /andP[_ RC]. elim: h s RC=>[[|[]]|????? IHtr [_ _|[?/=/and3P[_ *]|]]] //.\napply/eqnP=> /=; apply/eqP. by apply: IHtr.\nQed.\n\nTheorem rigth_spine_shortest H s1 s2:\n right s1 -> leftist_rank_inv H -> spine_in s1 H -> spine_in s2 H ->\n(length s1 <= length s2)%nat.\nProof. \nelim: H s1 s2=> [????/spine_in_E->|?? tl IHtl tr IHtr [//|a s1 [??? \n|[] s2 /rigth_correct [] ->]]] //= => [? /case_leftist_rank_inv_r ?|\n? /case_leftist_rank_inv_rl /and3P[??/=?]]=>*.\n- rewrite -addn1 -[(length s2).+1]addn1 leq_add2r IHtr //.\nrewrite (length_right_spine tr s1) //. case: (right_spine_ex tl)=> s /andP[*].\nsuffices: (rank tl <= length s2)%N; first by ssrnatlia.\nby rewrite -(length_right_spine tl s) // IHtl.\nQed.\nEnd Spine.\nEnd Specifications.\nEnd leftistheap.", "meta": {"author": "volodeyka", "repo": "okasaki", "sha": "c35da84a82d7e45c2d858047079745f44e0e2ad1", "save_path": "github-repos/coq/volodeyka-okasaki", "path": "github-repos/coq/volodeyka-okasaki/okasaki-c35da84a82d7e45c2d858047079745f44e0e2ad1/LeftistHeap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6521831080378433}}
{"text": "Require Export Vector VectorDef.\n\nDelimit Scope vector_scope with vector_scope.\n\nNotation \"[||]\" := (nil _) : vector_scope.\nNotation \"h ':::' t\" := (cons _ h _ t) (at level 60, right associativity) : vector_scope.\n                        \nNotation \" [| x |] \" := ((x ::: [||])%vector_scope) : vector_scope.\nNotation \" [| x ; y ; .. ; z |] \" := (cons _ x _ (cons _ y _ .. (cons _ z _ (nil _)) ..)) : vector_scope.\nNotation \"v [@ p ]\" := (nth v p) (at level 1, format \"v [@ p ]\").\n\nLemma Vector_replace_nth X n (v : Vector.t X n) i (x : X) :\n  (Vector.replace v i x) [@i] = x.\nProof.\n  induction i.\n  - cbn. revert x. pattern v. revert n v. eapply Vector.caseS.\n    cbn. reflexivity.\n  - cbn. revert x i  IHi. pattern v. revert n v. eapply Vector.caseS.\n    intros. cbn. eapply IHi.\nQed.\n\nLemma Vector_replace_nth2 X n (v : Vector.t X n) i j (x : X) :\n  i <> j -> (Vector.replace v i x) [@j] = v[@j].\nProof.\n  revert v. pattern i, j. revert n i j.\n  eapply Fin.rect2; intros; try congruence.\n  - revert f H. pattern v. revert n v.\n    eapply Vector.caseS. \n    cbn. reflexivity.\n  - revert f H. pattern v. revert n v.\n    eapply Vector.caseS. \n    cbn. reflexivity.\n  - revert g f H H0. pattern v. revert n v.\n    eapply Vector.caseS. firstorder congruence.\nQed.\n", "meta": {"author": "uds-psl", "repo": "cbv-lambda-calculus-reasonable", "sha": "4f12b7c8ce2816cdd771d22d04943e0fa81c63fd", "save_path": "github-repos/coq/uds-psl-cbv-lambda-calculus-reasonable", "path": "github-repos/coq/uds-psl-cbv-lambda-calculus-reasonable/cbv-lambda-calculus-reasonable-4f12b7c8ce2816cdd771d22d04943e0fa81c63fd/Base/Extra/Vectors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6521552505512705}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq             *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later            *)\nFrom mathcomp Require Import all_ssreflect ssralg fingroup finalg perm zmodp.\nFrom mathcomp Require Import matrix.\nFrom mathcomp Require boolp.\nFrom mathcomp Require Import Rstruct.\nRequire Import Reals.\nRequire Import ssrR Reals_ext ssr_ext ssralg_ext logb Rbigop.\nRequire Import fdist proba entropy num_occ channel_code channel typ_seq.\n\n(******************************************************************************)\n(*          Elements of the theory of types (in information theory)           *)\n(*                                                                            *)\n(* P_n(A)                  == type                                            *)\n(* type_counting           == Upper-bound of the number of types              *)\n(* T_{P}                   == typed tuples, tuples that are representative of *)\n(*                            a type                                          *)\n(* tuple_dist_type_entropy == probability of tuples representative of a type  *)\n(*                            using the entropy                               *)\n(* card_typed_tuples       == Upper-bound of the number of tuples             *)\n(*                            representative of a type using the entropy      *)\n(*                                                                            *)\n(******************************************************************************)\n\nReserved Notation \"'P_' n '(' A ')'\" (at level 9, n, A at next level).\nReserved Notation \"'T_{' P '}'\" (at level 9).\nReserved Notation \"P '.-typed_code' c\" (at level 50, c at next level).\n\nDeclare Scope types_scope.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope entropy_scope.\nLocal Open Scope num_occ_scope.\nLocal Open Scope R_scope.\n\nModule type.\n\nSection type_def.\n\nVariable A : finType.\nVariable n : nat.\n\nRecord type : predArgType := mkType {\n  d :> fdist A ;\n  f : {ffun A -> 'I_n.+1} ;\n  d_f : forall a, d a = INR (f a) / INR n }.\n\nEnd type_def.\n\nEnd type.\n\nCoercion type_coercion := type.d.\n\nNotation \"'P_' n '(' A ')'\" := (type.type A n) : types_scope.\n\nLocal Open Scope types_scope.\n\nDefinition ffun_of_type A n (P : P_ n ( A )) := let: type.mkType _ f _ := P in f.\n\nLemma type_fun_type A n (_ : n != O) (P : P_ n ( A )) a :\n  ((type.f P) a)%:R = n%:R * P a.\nProof.\ncase: P => /= d f d_f; by rewrite d_f mulRCA mulRV ?INR_eq0' // mulR1.\nQed.\n\nLemma INR_type_fun A n (P : P_ n ( A )) a : ((type.f P) a)%:R / n%:R = P a.\nProof. destruct P as [d f d_f] => /=. by rewrite d_f. Qed.\n\nLemma no_0_type A (d : fdist A) (t : {ffun A -> 'I_1}) :\n  (forall a, d a = (t a)%:R / 0%:R) -> False.\nProof.\nmove=> H; apply R1_neq_R0.\nrewrite -(FDist.f1 d).\ntransitivity (\\sum_(a | a \\in A) INR (t a) / 0); first exact/eq_bigr.\nrewrite -big_distrl /= -big_morph_natRD.\nrewrite (_ : (\\sum_(a in A) _)%nat = O) ?mul0R //.\ntransitivity (\\sum_(a in A) 0)%nat; first by apply eq_bigr => a _; rewrite (ord1 (t a)).\nby rewrite big_const iter_addn.\nQed.\n\nDefinition type_of_tuple (A : finType) n (ta : n.+1.-tuple A) : P_ n.+1 ( A ).\nset f := [ffun a => N(a | ta)%:R / n.+1%:R].\nassert (H1 : forall a, (0 <= f a)%R).\n  move=> a; rewrite ffunE; apply divR_ge0; by [apply leR0n | apply ltR0n].\nhave H2 : \\sum_(a in A) f a = 1%R.\n  under eq_bigr do rewrite ffunE /=.\n  by rewrite -big_distrl /= -big_morph_natRD sum_num_occ_alt mulRV // INR_eq0'.\nhave H : forall a, (N(a | ta) < n.+2)%nat.\n  move=> a; rewrite ltnS; by apply num_occ_leq_n.\nrefine (@type.mkType _ n.+1 (FDist.make H1 H2)\n  [ffun a => @Ordinal n.+2 (N(a | ta)) (H a)] _).\nby move=> a /=; rewrite !ffunE.\nDefined.\n\nLemma type_ext A n (t1 t2 : P_ n ( A )) : type.f t1 = type.f t2 -> t1 = t2.\nProof.\ncase: t1 t2 => d1 f1 H1 /= [] d2 f2 H2 /= f1f2.\nsubst f2.\nsuff ? : d1 = d2 by subst d2; congr type.mkType; exact: boolp.Prop_irrelevance.\napply fdist_ext => /= a; by rewrite H1 H2.\nQed.\n\nDefinition type_eq A n (t1 t2 : P_ n ( A )) :=\n  match t1, t2 with\n    | type.mkType _ f1 _, type.mkType _ f2 _ => f1 == f2\n  end.\n\nLemma type_eqP A n : Equality.axiom (@type_eq A n).\nProof.\ncase=> d1 f1 H1 [] d2 f2 H2 /=.\napply: (iffP idP) => [/eqP H|[] _ -> //].\nsubst f2.\nsuff ? : d1 = d2 by subst d2; congr type.mkType; exact: boolp.Prop_irrelevance.\napply fdist_ext => /= a; by rewrite H1 H2.\nQed.\n\nDefinition type_eqMixin A n := EqMixin (@type_eqP A n).\nCanonical type_eqType A n := Eval hnf in EqType _ (@type_eqMixin A n).\n\nLemma type_ffunP A n (P Q : P_ n.+1 ( A )) :\n  (forall c, P c = Q c) -> P = Q.\nProof.\nmove=> H.\ndestruct P as [d1 f1 H1].\ndestruct Q as [d2 f2 H2].\nrewrite /= in H.\napply/type_eqP => /=.\napply/eqP/ffunP => a.\napply/val_inj/INR_eq.\nmove: {H}(H a); rewrite H1 H2 eqR_mul2r //.\napply/invR_neq0; by rewrite INR_eq0.\nQed.\n\nDefinition nneg_fun_of_ffun (A : finType) n (f : {ffun A -> 'I_n.+2}) : nneg_finfun A.\nset d := [ffun a : A => INR (f a) / INR n.+1].\nrefine (@mkNNFinfun _ d _); apply/forallP_leRP => a.\nby rewrite ffunE; apply divR_ge0; [apply leR0n | apply ltR0n].\nDefined.\n\nDefinition fdist_of_ffun (A : finType) n (f : {ffun A -> 'I_n.+2})\n  (Hf : (\\sum_(a in A) f a)%nat == n.+1) : fdist A.\nset pf := nneg_fun_of_ffun f.\nhave H : \\sum_(a in A) pf a == 1 :> R.\n  rewrite /pf; under eq_bigr do rewrite ffunE /=.\n  rewrite /Rdiv -big_distrl /= -big_morph_natRD.\n  by move/eqP : Hf => ->; rewrite mulRV // INR_eq0'.\nexact:(FDist.mk H).\nDefined.\n\nLemma fdist_of_ffun_prop (A : finType) n (f : {ffun A -> 'I_n.+2})\n  (Hf : (\\sum_(a in A) f a)%nat == n.+1) :\nforall a : A, (fdist_of_ffun Hf) a = INR (f a) / INR n.+1.\nProof. by move=> a; rewrite ffunE. Qed.\n\nDefinition type_choice_f (A : finType) n (f : {ffun A -> 'I_n.+1}) : option (P_ n ( A )).\ndestruct n; first by exact None.\nrefine (match Sumbool.sumbool_of_bool (\\sum_(a in A) f a == n.+1)%nat with\n          | left H => Some (@type.mkType _ _ (fdist_of_ffun H) f (fdist_of_ffun_prop H))\n          | right _ => None\n        end).\nDefined.\n\nLemma ffun_of_fdist A n (d : fdist A) (t : {ffun A -> 'I_n.+2})\n  (H : forall a : A, d a = INR (t a) / INR n.+1) : (\\sum_(a in A) t a)%nat == n.+1.\nProof.\nsuff : INR (\\sum_(a in A) t a) == INR n.+1 * \\sum_(a | a \\in A) d a.\n  by move/eqP; rewrite (FDist.f1 d) mulR1 => /INR_eq/eqP.\napply/eqP.\ntransitivity (INR n.+1 * (\\sum_(a|a \\in A) INR (t a) / INR n.+1)).\n  by rewrite -big_distrl -big_morph_natRD mulRCA mulRV ?mulR1 // INR_eq0'.\ncongr (_ * _); exact/eq_bigr.\nQed.\n\nLemma type_choice_pcancel A n : pcancel (@type.f A n) (@type_choice_f A n).\nProof.\ncase=> d t H /=.\ndestruct n.\n  by move: (no_0_type H).\nrewrite /type_choice_f /=; f_equal.\nmove: (ffun_of_fdist H) => H'.\ndestruct Sumbool.sumbool_of_bool as [e|e]; last first.\n  by rewrite H' in e.\ncongr Some.\nset d1 := fdist_of_ffun _.\nsuff ? : d1 = d by subst d; congr type.mkType; apply boolp.Prop_irrelevance.\napply fdist_ext => /= a; by rewrite ffunE H.\nQed.\n\nLemma type_choiceMixin A n : choiceMixin (P_ n ( A )).\nProof. apply (PcanChoiceMixin (@type_choice_pcancel A n)). Qed.\n\nCanonical type_choiceType A n := Eval hnf in ChoiceType _ (type_choiceMixin A n).\n\nDefinition type_pickle A n (P : P_ n (A)) : nat.\ndestruct P as [d f H].\nexact: (pickle f).\n(*destruct (finfun_countMixin A [finType of 'I_n.+1]) as [pi unpi Hcan].\napply (pi f).*)\nDefined.\n\nDefinition type_unpickle A n (m : nat) : option (P_ n ( A )).\ndestruct n.\n  exact None.\npose unpi : option {ffun A -> 'I_n.+2} := unpickle m.\ncase: unpi; last first.\n  exact None.\nmove=> f.\nrefine (match Sumbool.sumbool_of_bool ((\\sum_(a in A) f a)%nat == n.+1) with\n          | left H => Some (@type.mkType _ _ (fdist_of_ffun H) f (fdist_of_ffun_prop H))\n          | right _ => None\n        end).\nDefined.\n\nLemma type_count_pcancel A n : pcancel (@type_pickle A n) (@type_unpickle A n).\nProof.\ndestruct n.\n  case=> d t H /=; by move: (no_0_type H).\ncase=> d t H /=.\nrewrite pickleK.\nmove: (ffun_of_fdist H) => H'.\ndestruct Sumbool.sumbool_of_bool as [e|e]; last first.\n  by rewrite H' in e.\ncongr Some.\nset d1 := fdist_of_ffun _.\nsuff ? : d1 = d by subst d; congr type.mkType; apply boolp.Prop_irrelevance.\napply/fdist_ext => a; by rewrite ffunE H.\nQed.\n\nDefinition type_countMixin A n := CountMixin (@type_count_pcancel A n).\nCanonical type_countType A n :=\n  Eval hnf in CountType (P_ n ( A )) (@type_countMixin A n).\n\nDefinition type_enum_f (A : finType) n (f : { f : {ffun A -> 'I_n.+1} | (\\sum_(a in A) f a)%nat == n} ) : option (P_ n ( A )).\ndestruct n.\n  apply None.\nrefine (Some (@type.mkType _ _ (fdist_of_ffun (proj2_sig f)) (sval f) (fdist_of_ffun_prop (proj2_sig f)))).\nDefined.\n\nDefinition type_enum A n := pmap (@type_enum_f A n)\n  (enum [finType of {f : {ffun A -> 'I_n.+1} | (\\sum_(a in A) f a)%nat == n}]).\n\nLemma type_enumP A n : Finite.axiom (@type_enum A n).\nProof.\ndestruct n.\n  case=> d t H /=; by move: (no_0_type H).\ncase=> d t H /=.\nmove: (ffun_of_fdist H) => H'.\nhave : Finite.axiom (enum [finType of { f : {ffun A -> 'I_n.+2} | (\\sum_(a in A) f a)%nat == n.+1}]).\n  rewrite enumT; by apply enumP.\nmove/(_ (@exist {ffun A -> 'I_n.+2} (fun f => \\sum_(a in A) f a == n.+1)%nat t H')) => <-.\nrewrite /type_enum /= /type_enum_f /= count_map.\nby apply eq_count.\nQed.\n\nDefinition type_finMixin A n := Eval hnf in FinMixin (@type_enumP A n).\nCanonical type_finType A n := Eval hnf in FinType _ (@type_finMixin A n).\n\nSection type_facts.\nVariable A : finType.\nLocal Open Scope nat_scope.\n\nLemma type_counting n : #| P_ n ( A ) | <= expn (n.+1) #|A|.\nProof.\nrewrite -(card_ord n.+1) -card_ffun /=.\nrewrite cardE /enum_mem.\napply (@leq_trans (size (map (@ffun_of_type A n) (Finite.enum (type_finType A n))))).\n  by rewrite 2!size_map.\nrewrite cardE.\napply: uniq_leq_size.\n  rewrite map_inj_uniq //.\n    move: (enum_uniq (type_finType A n)).\n    by rewrite enumT.\n  case=> d f Hd [] d2 f2 Hd2 /= ?; subst f2.\n  have ? : d = d2 by apply/fdist_ext => a; rewrite Hd Hd2.\n  subst d2; congr type.mkType; exact: boolp.Prop_irrelevance.\nmove=> /= f Hf; by rewrite mem_enum.\nQed.\n\nLemma type_card_neq0 n : 0 < #|A| -> 0 < #|P_ n.+1(A)|.\nProof.\ncase/card_gt0P => a _.\napply/card_gt0P.\nhave [f Hf] : [finType of {f : {ffun A -> 'I_n.+2} | \\sum_(a in A) f a == n.+1}].\n  exists [ffun a1 => if pred1 a a1 then Ordinal (ltnSn n.+1) else Ordinal (ltn0Sn n.+1)].\n  rewrite (bigD1 a) //= big1; first by rewrite ffunE eqxx addn0.\n  move=> p /negbTE Hp; by rewrite ffunE Hp.\nexists (@type.mkType _ _ (fdist_of_ffun Hf) _ (fdist_of_ffun_prop Hf)).\nby rewrite inE.\nQed.\n\nLemma type_empty1 n : #|A| = 0 -> #|P_ n(A)| = 0.\nProof.\nmove=> A0; apply eq_card0; case=> d ? ?.\nmove: (fdist_card_neq0 d); by rewrite A0.\nQed.\n\nLemma type_empty2 : #|P_ 0(A)| = 0.\nProof.\napply eq_card0; case=> d f Hf.\nexfalso.\nby move/no_0_type in Hf.\nQed.\n\nEnd type_facts.\n\nSection typed_tuples.\nVariables (A : finType) (n : nat) (P : P_ n ( A )).\n\nLocal Open Scope nat_scope.\n\nDefinition typed_tuples :=\n  [set t : n.-tuple A | [forall a, P a == (INR N(a | t) / INR n)%R] ].\n\nEnd typed_tuples.\n\nNotation \"'T_{' P '}'\" := (typed_tuples P) : types_scope.\n\nSection typed_tuples_facts.\nVariables (A : finType) (n' : nat).\nLet n := n'.+1.\nVariable P : P_ n ( A ).\n\nLemma type_numocc ta (Hta : ta \\in T_{P}) a : N(a | ta) = type.f P a.\nProof.\nmove: Hta.\nrewrite in_set.\nmove/forallP/(_ a)/eqP.\ndestruct P as [d f H] => /= Htmp.\napply/INR_eq/esym; move: Htmp.\nrewrite H eqR_mul2r //.\nby apply/invR_neq0; rewrite INR_eq0.\nQed.\n\nLemma typed_tuples_not_empty' : exists x : seq A,\n  exists Hx : size x == n, Tuple Hx \\in T_{P}.\nProof.\nexists (flatten (map (fun x0 => nseq (type.f P x0) x0) (enum A))).\nhave Hx : size (flatten [seq nseq (type.f P x0) x0 | x0 <- enum A]) == n.\n  rewrite size_flatten /shape -map_comp sumn_big_addn big_map.\n  case: (P) => P' f HP' /=.\n  apply/eqP.\n  transitivity (\\sum_(a in A) f a)%nat; last first.\n     apply/eqP; by apply ffun_of_fdist with P'.\n  apply congr_big => //.\n  by rewrite enumT.\n  move=> a /= _.\n  by rewrite size_nseq.\nexists Hx.\nrewrite inE.\napply/forallP => a.\nrewrite /num_occ /= -size_filter.\nrewrite filter_flatten size_flatten /shape -!map_comp sumn_big_addn big_map.\nrewrite (bigD1 a) // big1 /= => [|a' Ha'].\n- rewrite addn0 -(INR_type_fun P).\n  apply/eqP.\n  do 2 f_equal.\n  rewrite -{1}(_ : size (nseq (type.f P a) a) = type.f P a); last by rewrite size_nseq.\n  congr (size _).\n  apply/esym/all_filterP/all_pred1P.\n  by rewrite size_nseq.\n- transitivity (size (@List.nil A)) => //.\n  congr (size _).\n  apply/eqP/negPn; rewrite -has_filter; apply/hasPn => l Hl.\n  by case/nseqP : Hl => ->.\nQed.\n\nLemma typed_tuples_not_empty : { t | t \\in T_{P} }.\nProof.\napply sigW.\ncase: typed_tuples_not_empty' => x [Hx H].\nby exists (Tuple Hx).\nQed.\n\nEnd typed_tuples_facts.\n\nSection typed_tuples_facts_continued.\nVariables (A : finType) (n : nat).\nHypothesis Hn : n != O.\nVariable P : P_ n ( A ).\n\nLemma typed_tuples_not_empty_alt : {t : n.-tuple A | t \\in T_{P}}.\nProof. destruct n => //. apply typed_tuples_not_empty. Qed.\n\nLocal Open Scope fdist_scope.\nLocal Open Scope tuple_ext_scope.\nLocal Open Scope vec_ext_scope.\n\nLemma tuple_dist_type t : tuple_of_row t \\in T_{P} ->\n  P `^ n t = \\prod_(a : A) P a ^ (type.f P a).\nProof.\nmove=> Hx.\nrewrite fdist_rVE.\nrewrite (_ : \\prod_(i < n) P (t ``_ i) =\n  \\prod_(a : A) (\\prod_(i < n) (if a == t ``_ i then P t ``_ i else 1))); last first.\n  rewrite exchange_big; apply eq_big ; first by [].\n  move=> i _.\n  rewrite (bigID (fun y => y == t ``_ i)) /=.\n  rewrite -/(INR n.+1) big_pred1_eq eqxx big1 ?mulR1 //.\n  by move=> i0 /negbTE ->.\napply eq_bigr => a _.\nrewrite -big_mkcond /= -/(INR n.+1).\ntransitivity (\\prod_(i < n | t ``_ i == a) (INR (type.f P a) / INR n)).\n  apply eq_big => // i.\n  move/eqP => ->.\n  by rewrite INR_type_fun.\nrewrite big_const iter_mulR INR_type_fun.\ncongr (_ ^ _).\nrewrite /typed_tuples inE in Hx.\nmove/forallP/(_ a)/eqP : Hx.\nrewrite -INR_type_fun eqR_mul2r; last by apply/invR_neq0; rewrite INR_eq0; exact/eqP.\nmove/INR_eq => ->.\nrewrite num_occ_alt cardsE /=.\napply eq_card => /= n0.\nby rewrite /in_mem /= tnth_mktuple.\nQed.\n\nLocal Close Scope tuple_ext_scope.\n\nLemma tuple_dist_type_entropy t : tuple_of_row t \\in T_{P} ->\n  P `^ n t = exp2 (- INR n * `H P).\nProof.\nmove/(@tuple_dist_type t) => ->.\nrewrite (_ : \\prod_(a : A) P a ^ (type.f P) a =\n             \\prod_(a : A) exp2 (P a * log (P a) * INR n)); last first.\n  apply eq_bigr => a _.\n  case/boolP : (0 == P a) => H; last first.\n    have {}H : 0 < P a.\n      have := FDist.ge0 P a.\n      case/Rle_lt_or_eq_dec => // abs.\n      by rewrite abs eqxx in H.\n    rewrite -{1}(logK H) -exp2_pow.\n    congr exp2.\n    rewrite -mulRA [X in _ = X]mulRC -mulRA mulRC.\n    congr (_ * _).\n    by rewrite type_fun_type.\n  - move/eqP : (H) => <-.\n    rewrite -(_ : O = type.f P a); first by rewrite !mul0R exp2_0 /pow.\n    apply INR_eq.\n    rewrite {1}/INR.\n    rewrite -(@eqR_mul2r ( / INR n)); last by apply/invR_neq0; rewrite INR_eq0; exact/eqP.\n    by rewrite type_fun_type // -(eqP H) mulR0.\nrewrite -(big_morph _ morph_exp2_plus exp2_0) -(big_morph _ (morph_mulRDl _) (mul0R _)).\nby rewrite /entropy Rmult_opp_opp mulRC.\nQed.\n\nLocal Open Scope typ_seq_scope.\n\nLemma typed_tuples_are_typ_seq : (@row_of_tuple A n @: T_{ P }) \\subset `TS P n 0.\nProof.\napply/subsetP => t Ht.\nrewrite /set_typ_seq inE /typ_seq tuple_dist_type_entropy; last first.\n  case/imsetP : Ht => x Hx ->.\n  by rewrite row_of_tupleK.\nby rewrite addR0 subR0 !leRR'.\nQed.\n\nLemma card_typed_tuples : INR #| T_{ P } | <= exp2 (INR n * `H P).\nProof.\nrewrite -(invRK (exp2 (INR n * `H P))%R); last exact/eqP.\nrewrite -exp2_Ropp -mulNR.\nset aux := - INR n * `H P.\nrewrite -div1R leR_pdivl_mulr // {}/aux.\ncase/boolP : [exists x, x \\in T_{P}] => x_T_P.\n- case/existsP : x_T_P => ta Hta.\n  rewrite -(row_of_tupleK ta) in Hta.\n  rewrite -(tuple_dist_type_entropy Hta).\n  rewrite [X in X <= _](_ : _ = Pr P `^ n (@row_of_tuple A n @: T_{P})).\n    by apply Pr_1.\n  symmetry.\n  rewrite /Pr.\n  transitivity (\\sum_(a| (a \\in [finType of 'rV[A]_n]) && [pred x in (@row_of_tuple A n @: T_{P})] a)\n      exp2 (- INR n * `H P)).\n    apply eq_big => // ta'/= Hta'.\n    rewrite -(@tuple_dist_type_entropy ta') //.\n    case/imsetP : Hta' => x Hx ->. by rewrite row_of_tupleK.\n  rewrite big_const iter_addR tuple_dist_type_entropy //.\n  do 2 f_equal.\n  by rewrite card_imset //; exact: row_of_tuple_inj.\n- rewrite (_ : (INR #| T_{P} | = 0)%R); first by rewrite mul0R; exact/Rle_0_1.\n  rewrite (_ : 0%R = INR 0) //; congr INR; apply/eqP.\n  rewrite cards_eq0; apply/negPn.\n  by move: x_T_P; apply contra => /set0Pn/existsP.\nQed.\n\nLemma card_typed_tuples_alt : INR #| T_{P} | <= exp2 (INR n * `H P).\nProof.\napply (@leR_trans (INR #| `TS P n 0 |)).\n  apply/le_INR/leP.\n  apply: leq_trans; last first.\n    by apply subset_leq_card; exact: typed_tuples_are_typ_seq.\n  by rewrite card_imset //; exact: row_of_tuple_inj.\nby apply: (leR_trans (TS_sup _ _ _)); rewrite addR0; exact/leRR.\nQed.\n\nLemma perm_tuple_in_Ttuples ta (s : 'S_n) :\n  perm_tuple s ta \\in T_{P} <-> ta \\in T_{P}.\nProof.\nrewrite 2!in_set.\nsplit => /forallP H; apply/forallP => a; move: H => /(_ a)/eqP => ->; by rewrite num_occ_perm.\nQed.\n\nEnd typed_tuples_facts_continued.\n\nSection enc_pre_img_partition.\nVariables (A B M : finType) (n' : nat).\nLet n := n'.+1.\nVariable c : code A B M n.\n\nDefinition enc_pre_img (P : P_ n ( A )) := [set m | tuple_of_row (enc c m) \\in T_{P}].\n\nLemma enc_pre_img_injective (P Q : P_ n ( A )) :\n  enc_pre_img P != set0 -> enc_pre_img P = enc_pre_img Q ->\n  forall a, P a = Q a.\nProof.\nrewrite /enc_pre_img.\ncase/set0Pn => m.\nrewrite in_set => HmP /setP HPQ.\nhave HmQ : tuple_of_row (enc c m) \\in T_{Q} by move:(HPQ m) ; rewrite 2!in_set => <-.\nmove=> a {HPQ}.\nmove: HmP ; rewrite in_set => /forallP/(_ a)/eqP => ->.\nmove: HmQ ; rewrite in_set => /forallP/(_ a)/eqP => <-.\nreflexivity.\nQed.\n\nDefinition enc_pre_img_partition :=\n  enc_pre_img @: [set P in P_ n ( A ) | enc_pre_img P != set0].\n\nLemma cover_enc_pre_img : cover enc_pre_img_partition = [set: M].\nProof.\nrewrite /cover /enc_pre_img_partition.\napply/setP => m.\nrewrite in_set.\napply/bigcupP.\nexists (enc_pre_img (type_of_tuple (tuple_of_row (enc c m)))).\n- apply/imsetP; exists (type_of_tuple (tuple_of_row (enc c m))) => //.\n  rewrite in_set.\n  apply/andP; split => //.\n  apply/set0Pn.\n  exists m.\n  rewrite 2!in_set.\n  by apply/forallP => a; rewrite ffunE.\n- rewrite 2!in_set.\n  by apply/forallP => a; rewrite ffunE.\nQed.\n\nLemma trivIset_enc_pre_img : trivIset enc_pre_img_partition.\nProof.\napply/trivIsetP => S1 S2 /imsetP ; case => P1 _ HP1. case/imsetP => P2 _ HP2 HP12.\nsubst S1 S2.\nrewrite /disjoint.\napply/pred0P => m /=.\napply/negP/negP.\nmove: m.\napply/forallP; rewrite -negb_exists; apply/negP; case/existsP => m /andP [H1 H2]; contradict HP12.\napply/negP/negPn/eqP/setP => m'.\ncase/boolP : (m' \\in enc_pre_img P2) => [|/negbTE] Hcase.\n- apply/negPn/negPn.\n  rewrite 2!in_set; apply/forallP => a.\n  move: H1; rewrite 2!in_set => /forallP/(_ a)/eqP ->.\n  move: Hcase; rewrite 2!in_set => /forallP/(_ a)/eqP <-.\n  move: H2; rewrite 2!in_set => /forallP/(_ a)/eqP <-.\n  by rewrite eqxx.\n- apply/negP/negPn; move: Hcase => /negP/negPn; apply contra => Hcase.\n  rewrite 2!in_set; apply/forallP => a.\n  move: H2; rewrite 2!in_set => /forallP/(_ a)/eqP ->.\n  move: Hcase; rewrite 2!in_set => /forallP/(_ a)/eqP <-.\n  move: H1; rewrite 2!in_set => /forallP/(_ a)/eqP <-.\n  by rewrite eqxx.\nQed.\n\nEnd enc_pre_img_partition.\n\nSection sum_messages_types.\nVariables (A B M : finType) (n' : nat).\nLet n := n'.+1.\nVariable c : code A B M n.\n\nLemma sum_messages_types' f :\n  \\sum_(P : P_ n ( A )) (\\sum_(m |m \\in enc_pre_img c P) f m) =\n  \\sum_ (S | S \\in enc_pre_img_partition c) \\sum_(m in S) f m.\nProof.\nrewrite (bigID (fun P => [exists m, m \\in enc_pre_img c P] )).\nrewrite (_ : forall a b, addR_comoid a b = a + b) //.\nrewrite Rplus_comm big1 ; last first.\n  move=> P ; rewrite andTb negb_exists => HP.\n  apply big_pred0 => m /=.\n  apply/negP/negPn; by move:HP => /forallP/(_ m) ->.\nrewrite /= add0R big_imset.\n  apply eq_big => [P|P _] //=.\n  rewrite in_set.\n  case: set0Pn => [/existsP //| ?]; exact/existsP.\nmove=> P Q; rewrite 2!in_set => HP HQ HPQ /=.\nmove: (enc_pre_img_injective HP HPQ) => {HP HQ} {}HPQ.\ncase: P HPQ => /= Pd Pf HP HPQ.\ncase: Q HPQ => /= Qd Qf HQ HPQ.\napply/type_eqP => /=.\napply/eqP.\napply ffunP => a.\napply/val_inj/INR_eq.\nmove: {HPQ}(HPQ a); rewrite HP HQ eqR_mul2r //.\napply/invR_neq0; by rewrite INR_eq0.\nQed.\n\nLemma sum_messages_types f :\n  \\sum_(P : P_ n ( A )) (\\sum_(m |m \\in enc_pre_img c P) f m) = \\sum_ (m : M) (f m).\nProof.\ntransitivity (\\sum_ (m in [set: M]) (f m)); last by apply eq_bigl => b; rewrite in_set.\nrewrite -(cover_enc_pre_img c) /enc_pre_img_partition sum_messages_types'.\nsymmetry.\nby apply big_trivIset, trivIset_enc_pre_img.\nQed.\n\nEnd sum_messages_types.\n\nSection typed_code_def.\nVariables (A B M : finType) (n : nat).\nVariable P : P_ n ( A ).\n\nRecord typed_code := mkTypedCode {\n  untyped_code :> code A B M n ;\n  typed_prop : forall m, tuple_of_row (enc untyped_code m) \\in T_{P} }.\n\nEnd typed_code_def.\n\nSection typed_code_of_code.\nVariables (A B M : finType) (n' : nat).\nLet n := n'.+1.\nVariable P : P_ n ( A ).\nVariable c : code A B M n.\n\nDefinition def := row_of_tuple (sval (typed_tuples_not_empty P)).\nDefinition Hdef := proj2_sig (typed_tuples_not_empty P).\n\nDefinition tcode_untyped_code := mkCode\n  [ffun m => if tuple_of_row (enc c m) \\in T_{P} then enc c m else def] (dec c).\n\nLemma tcode_typed_prop (m : M) : tuple_of_row ((enc tcode_untyped_code) m) \\in T_{P}.\nProof.\nrewrite /= ffunE; case: ifP => [//| _]; rewrite /def row_of_tupleK; exact Hdef.\nQed.\n\nDefinition tcode : typed_code B M P := mkTypedCode tcode_typed_prop.\n\nEnd typed_code_of_code.\n\nNotation \"P '.-typed_code' c\" := (tcode P c) : types_scope.\n", "meta": {"author": "affeldt-aist", "repo": "infotheo", "sha": "5f9efb859dbadcbcae2330e2e21e76f9b632d879", "save_path": "github-repos/coq/affeldt-aist-infotheo", "path": "github-repos/coq/affeldt-aist-infotheo/infotheo-5f9efb859dbadcbcae2330e2e21e76f9b632d879/information_theory/types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6521552460631738}}
{"text": "Require Import AutoSep WordLemmas.\n\n(* ============================================================================\n * specification with overflow safeguard\n * - the result is correct and not overflowing if the input is 12 or less\n * ========================================================================= *)\n\nFixpoint fact (n : nat) :=\n  match n with\n    | 0 => 1\n    | S n' => n * fact n'\n  end.\n\nDefinition factS : spec := SPEC(\"n\") reserving 1\n  PRE[V]  [| (wordToNat (V \"n\") <= 12)%nat |]\n  POST[R] [| wordToNat R = fact (wordToNat (V \"n\")) |].\n\n\n(* ============================================================================\n * implementation\n * ========================================================================= *)\n\nDefinition m := bmodule \"factorial\" {{\n  bfunction \"fact\" (\"n\", \"r\" ) [factS]\n    \"r\" <- 1;;\n    [ PRE[V]  [| goodSize (wordToNat (V \"r\") * fact (wordToNat (V \"n\"))) |]\n      POST[R] [| wordToNat R\n                 = (wordToNat (V \"r\") * fact (wordToNat (V \"n\")))%nat |] ]\n    While (\"n\" > 1) {\n      \"r\" <- \"r\" * \"n\";;\n      \"n\" <- \"n\" - 1\n    };;\n    Return \"r\"\n  end\n  }}.\n\n\n(* ============================================================================\n * factorial up to 12 is not overflowing\n * - fact12 is too big to calculate, instead we calcuate factN 12 and deduce\n * ========================================================================= *)\n\nRequire Import NArith.\n\nFixpoint factN (n : nat) :=\n  match n with\n    | 0 => N.of_nat 1\n    | S n' => Nmult (N.of_nat n) (factN n')\n  end.\n\nLemma factN_12_lt_pow2_32 : (factN 12 < Npow2 32)%N.\n  red; simpl; unfold Pos.compare; simpl; auto.\nQed.\n\nTheorem factN_fact : forall n, N.to_nat (factN n) = fact n.\n  induction n; simpl; auto.\n  destruct (factN n) eqn:?; simpl in *.\n  rewrite <- IHn; simpl; auto.\n  rewrite <- IHn.\n  rewrite Pnat.Pos2Nat.inj_mul, Pnat.SuccNat2Pos.id_succ; simpl; auto.\nQed.\n\nLemma fact_non_decreasing : forall x y, (x <= y)%nat -> (fact x <= fact y)%nat.\n  induction 1; auto; simpl.\n  destruct m0, x; simpl in *; auto;\n  eapply Le.le_trans; try eassumption; apply Plus.le_plus_l.\nQed.\nLocal Hint Resolve fact_non_decreasing.\n  \nLemma goodSize_def : forall x, (N.of_nat x < Npow2 32)%N -> goodSize x.\n  auto.\nQed.\n\nLemma fact_bound : forall n, (n <= 12)%nat -> goodSize (fact n).\n  intros.\n  assert (goodSize (fact 12)).\n  {\n    apply goodSize_def.\n    rewrite <- factN_fact, N2Nat.id.\n    apply factN_12_lt_pow2_32.\n  }\n  eapply goodSize_weaken; eassumption || auto.\nQed.\n\n\n(* ============================================================================\n * lemmas\n * ========================================================================= *)\n\nLemma fact_le_1 : forall r n : W, n <= natToW 1\n          -> wordToNat r = (wordToNat r * fact (wordToNat n))%nat.\n  intros; destruct_words; roundtrip.\n  repeat (destruct w0; simpl; try omega).\nQed.\nHint Resolve fact_le_1.\n\nLemma fact_gt_0 : forall x, (0 < fact x)%nat.\n  induction x; simpl; auto.\n  rewrite Mult.mult_comm; simpl.\n  generalize (fact x * x); intros; omega.\nQed.\n\nLemma fact_ge_1 : forall x, (1 <= fact x)%nat.\n  induction x; simpl; auto.\n  rewrite Mult.mult_comm; simpl.\n  generalize (fact x * x); intros; omega.\nQed.\nLocal Hint Resolve fact_ge_1.\n\nLemma fact_ge : forall x, (x <= fact x)%nat.\n  destruct x; simpl; auto.\n  change (S x <= S x * fact x)%nat.\n  rewrite <- Mult.mult_1_l at 1.\n  rewrite Mult.mult_comm at 1.\n  apply Mult.mult_le_compat_l; auto.\nQed.\nLocal Hint Resolve fact_ge.\n\nLemma rw1 : forall r n, natToW 1 < n\n                 -> goodSize (wordToNat r * fact (wordToNat n))\n                 -> wordToNat (r ^* n) * fact (wordToNat (n ^- natToW 1))\n                    = wordToNat r * fact (wordToNat n).\n  intros; destruct_words; roundtrip.\n  destruct w0; simpl; try omega.\n  replace (w0 - 0) with w0 by omega.\n  assert (w * S w0 <= w * fact (S w0))%nat by (apply Mult.mult_le_compat_l; auto).\n  rewrite wordToNat_wmult by (roundtrip; goodsize).\n  roundtrip.\n  rewrite <- Mult.mult_assoc; f_equal.\nQed.\n\nLemma rw2 : forall n : W, wordToNat (natToW 1) * fact (wordToNat n)\n                          = fact (wordToNat n).\n  intros; roundtrip; omega.\nQed.\n\n\n(* ===========================================================================\n * Proof\n * ========================================================================= *)\n\nLtac finish :=\n  match goal with\n    | _ => solve [auto]\n    | H: Regs _ Rv = _ |- _ => rewrite H\n  end.\n\nHint Rewrite rw1 : sepFormula.\nHint Rewrite rw2 : sepFormula.\nHint Resolve fact_bound.\n\nTheorem ok : moduleOk m.\n  vcgen; sep_auto; repeat finish.\nQed.\n", "meta": {"author": "duckki", "repo": "bedrock-examples", "sha": "4086a4f63e57c98ace308bdbe75033afb9e11044", "save_path": "github-repos/coq/duckki-bedrock-examples", "path": "github-repos/coq/duckki-bedrock-examples/bedrock-examples-4086a4f63e57c98ace308bdbe75033afb9e11044/myfactorial-safe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6521552356653587}}
{"text": "(** Formalization of generic properties of complex\n  numbers, complex vectors and complex matrices *)\n\nRequire Import Reals Psatz R_sqrt R_sqr.\nFrom mathcomp Require Import all_algebra all_ssreflect ssrnum bigop.\nFrom mathcomp.analysis Require Import boolp Rstruct classical_sets posnum\n     topology normedtype landau sequences.\nRequire Import Coquelicot.Lim_seq.\nRequire Import Coquelicot.Rbar.\nRequire Import Coquelicot.Hierarchy Coquelicot.Lub.\nFrom mathcomp Require Import mxalgebra matrix all_field.\nFrom canonical_forms Require Import jordan similar closed_poly frobenius_form.\nFrom CoqEAL Require Import mxstructure ssrcomplements.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nOpen Scope R_scope.\nOpen Scope ring_scope.\n\nDelimit Scope ring_scope with Ri.\nDelimit Scope R_scope with Re.\n\nImport Order.TTheory GRing.Theory Num.Def Num.Theory.\n\nOpen Scope classical_set_scope.\n\nFrom mathcomp Require Import complex.\nImport ComplexField.\n\n(** Define the modulus of a complex number **)\nDefinition C_mod (x: R[i]):=\n   sqrt ( (Re x)^+2 + (Im x)^+2).\n\n(** Properties of the modulus of a complex number **)\nLemma C_mod_0: C_mod 0 = 0%Re.\nProof.\nby rewrite /C_mod /= expr2 mul0r Rplus_0_r sqrt_0.\nQed.\n\nLemma C_mod_ge_0: \n  forall (x: complex R), (0<= C_mod x)%Re.\nProof.\nintros. unfold C_mod. apply sqrt_pos.\nQed.\n\nLemma Re_complex_prod: forall (x y: complex R), \n  Re (x * y) = Re x * Re y - Im x * Im y.\nProof.\nintros. destruct x. destruct y. simpl. by [].\nQed.\n\nLemma Im_complex_prod: forall (x y:complex R),\n  Im (x * y) = Re x * Im y + Im x * Re y.\nProof.\nintros. destruct x. destruct y. simpl. by [].\nQed.\n\nLemma C_mod_prod: forall (x y: complex R), \n  C_mod (x * y) = C_mod x * C_mod y.\nProof.\nintros. rewrite /C_mod -[RHS]RmultE -sqrt_mult.\n+ assert ( Re (x * y) ^+ 2 + Im (x * y) ^+ 2 = \n            ((Re x ^+ 2 + Im x ^+ 2) * (Re y ^+ 2 + Im y ^+ 2))).\n  { rewrite Re_complex_prod Im_complex_prod. \n    rewrite -!RpowE -!RmultE -!RplusE -!RoppE. nra.\n  } by rewrite !RplusE H.\n+ apply Rplus_le_le_0_compat;rewrite -RpowE; nra.\n+ apply Rplus_le_le_0_compat;rewrite -RpowE; nra.\nQed.\n\n\nLemma Re_complex_div: forall (x y: complex R),\n  Re (x / y) = (Re x * Re y + Im x * Im y) / ((Re y)^+2 + (Im y)^+2).\nProof.\nintros. destruct x, y. \nby rewrite /= mulrDl mulrN opprK !mulrA.\nQed.\n\n\nLemma Im_complex_div: forall (x y: complex R),\n  Im (x / y) = ( - (Re x * Im y) + Im x * Re y) / ((Re y)^+2 + (Im y)^+2).\nProof.\nintros. destruct x, y.  \nby rewrite /= mulrDl mulrN mulNr !mulrA.\nQed.\n\n\nLemma complex_not_0 (x: complex R) : \n  (Re x +i* Im x)%C != 0 -> Re x != 0 \\/ Im x != 0.\nProof.\nrewrite eq_complex /=. intros. by apply /nandP.\nQed.\n\n\nLemma sqr_complex_not_zero: forall (x: complex R),\n  x <> 0 -> (Re x)^+2 + (Im x)^+2 <> 0.\nProof.\nintros.\nassert ( x !=0). { by apply /eqP. }\nrewrite -!RpowE -RplusE.\nassert ( ( 0< Re x ^ 2 + Im x ^ 2)%Re -> \n          (Re x ^ 2 + Im x ^ 2)%Re <> 0%Re).\n{ nra. } apply H1.\nassert ( (Re x <> 0)%Re \\/ ( Im x <> 0)%Re -> \n          (0 < Re x ^ 2 + Im x ^ 2)%Re). { nra. }\napply H2.\nassert ( (Re x <> 0)  <-> (Re x !=0)). \n{ split.\n  + intros. by apply /eqP.\n  + intros. by apply /eqP.\n} rewrite H3.\nassert ( (Im x <> 0)  <-> (Im x !=0)). \n{ split.\n  + intros. by apply /eqP.\n  + intros. by apply /eqP.\n} rewrite H4.\napply complex_not_0. clear H H1 H2 H3 H4.\nmove : H0. destruct x. by [].\nQed.\n\nLemma div_prod: forall (x:R),\n  x <> 0 -> x / (x * x) = x^-1.\nProof.\nintros. rewrite -RdivE. \nassert ( (x / (x * x)%Ri)%Re  = (x * (/ (x*x)))%Re).\n{ by []. } rewrite H0.\n+ rewrite Rinv_mult_distr. \n  - rewrite -Rmult_assoc. rewrite Rinv_r.\n    * assert ( (1 * / x)%Re = (1/x)%Re). { nra. }\n      rewrite H1. rewrite RdivE. \n      { apply div1r. }\n      { by apply /eqP. }\n    * exact H.\n  - exact H.\n  - exact H.\n+ apply /eqP. auto.\nQed.\n\nLemma C_mod_div: forall (x y: complex R),\n  y <> 0 -> C_mod (x / y) = (C_mod x) / (C_mod y).\nProof.\nintros. rewrite /C_mod -[RHS]RdivE.\n+ rewrite -sqrt_div.\n  - assert ( (Re (x / y) ^+ 2 + Im (x / y) ^+ 2) =\n      ((Re x ^+ 2 + Im x ^+ 2) / (Re y ^+ 2 + Im y ^+ 2))).\n    { rewrite Re_complex_div Im_complex_div !expr_div_n -mulrDl sqrrD. \n      assert ( (- (Re x * Im y) + Im x * Re y) = \n                Im x * Re y - (Re x * Im y)).\n      { by rewrite addrC. } rewrite H0. clear H0.\n      rewrite sqrrB //= !addrA !mulrA. \n      assert ( ((Re x * Re y) ^+ 2 + Re x * Re y * Im x * Im y +\n             Re x * Re y * Im x * Im y + (Im x * Im y) ^+ 2 +\n             (Im x * Re y) ^+ 2 - Im x * Re y * Re x * Im y *+ 2 +\n             (Re x * Im y) ^+ 2) = \n              (Re x ^+ 2 + Im x ^+ 2) * (Re y ^+ 2 + Im y ^+ 2)).\n      { rewrite !expr2 mulr2n !mulrA. \n        rewrite -!RmultE -!RplusE -!RoppE Rmult_comm. nra. \n      } rewrite H0. clear H0. rewrite -mulrA.\n      assert ( ((Re y ^+ 2 + Im y ^+ 2) / (Re y ^+ 2 + Im y ^+ 2) ^+ 2)=\n                (Re y ^+ 2 + Im y ^+ 2)^-1).\n      { assert ( (Re y ^+ 2 + Im y ^+ 2) ^+ 2 = \n                (Re y ^+ 2 + Im y ^+ 2) * (Re y ^+ 2 + Im y ^+ 2)).\n        { by rewrite expr2. }\n        rewrite H0. clear H0. apply div_prod. \n        by apply sqr_complex_not_zero.\n      } by rewrite H0. \n    } rewrite !RplusE. \n    rewrite RdivE.\n    * by rewrite H0. \n    * apply /eqP. by apply sqr_complex_not_zero. \n  - apply Rplus_le_le_0_compat;rewrite -RpowE; nra. \n  - assert ( (Re y ^ 2 + Im y ^ 2)%Re <> 0%Re ->\n            (0 < Re y ^ 2 + Im y ^ 2)%Re). { nra. }\n    rewrite -!RpowE. apply H0. rewrite !RpowE.\n    by apply sqr_complex_not_zero.\n+ apply /eqP. rewrite -!RpowE.\n  assert ( (0< sqrt (Re y ^ 2 + Im y ^ 2))%Re -> \n          sqrt (Re y ^ 2 + Im y ^ 2) <> 0%Re).  { nra. }\n  apply H0. apply sqrt_lt_R0.\n  assert ( (Re y ^ 2 + Im y ^ 2)%Re <> 0%Re ->\n            (0 < Re y ^ 2 + Im y ^ 2)%Re). { nra. }\n  apply H1. rewrite !RpowE.\n  by apply sqr_complex_not_zero.  \nQed.\n\n\nLemma C_mod_not_zero: forall (x: complex R), \n  x <> 0 -> C_mod x <> 0.\nProof.\nintros. rewrite /C_mod.\nhave H1: forall x:R, (0 < x)%Re -> sqrt x <> 0%Re.\n  move => a Ha. \n  assert ( (0< sqrt a)%Re ->  sqrt a <> 0%Re). { nra. }\n  apply H0. apply sqrt_lt_R0; nra.\napply H1. rewrite -!RpowE.\nassert ( (Re x ^ 2 + Im x ^ 2)%Re <> 0%Re ->\n            (0 < Re x ^ 2 + Im x ^ 2)%Re). { nra. }\napply H0. rewrite !RpowE.\nby apply sqr_complex_not_zero.\nQed. \n\nLemma C_mod_1: C_mod 1 = 1.\nProof.\nby rewrite /C_mod /= !expr2 mul1r mul0r Rplus_0_r sqrt_1.\nQed.\n\n\nLemma C_mod_pow: forall (x: complex R) (n:nat), \n  C_mod (x^+ n) = (C_mod x)^+n.\nProof.\nintros. induction n.\n+ by rewrite !expr0 C_mod_1. \n+ by rewrite !exprS C_mod_prod IHn.\nQed.\n\nLemma C_destruct: forall (x: complex R), x = (Re x +i* Im x)%C.\nProof.\nby move => [a b]. \nQed.\n\nLemma C_mod_minus_x: forall (x: complex R),\n  C_mod (-x) = C_mod x.\nProof.\nintros. rewrite /C_mod //=. \nassert (x = (Re x +i* Im x)%C).\n{ by rewrite -C_destruct. } rewrite H //=.\nrewrite !expr2. by rewrite !mulrNN.\nQed.\n\nLemma complex_not_0_sym: forall (x : complex R),\n  Re x != 0 \\/ Im x != 0 -> (Re x +i* Im x)%C != 0.\nProof.\nintros. rewrite eq_complex /=. by apply /nandP.\nQed.\n\n(** Define a coercion from real to complex **)\nDefinition RtoC (x:R):= (x +i* 0)%C.\n\n\n\n(** Compatibilty between C_mod and normc in the mathcomp/complex\n  libary **)\nLemma C_modE y : C_mod y = normc y.\nProof.\nrewrite /C_mod RsqrtE /normc; case: y => [ry iy] //=.\nby rewrite RplusE addr_ge0 // sqr_ge0.\nQed.\n\nLemma normcV (y : complex R) : y != 0 -> normc (y^-1) = (normc y)^-1.\nProof.\nmove=> yn0.\nhave normyn0 : normc y != 0 by apply/eqP=> /eq0_normc /eqP; apply/negP.\napply: (mulfI normyn0); rewrite mulfV // -normcM mulfV //.\nby rewrite /normc /= expr0n /= addr0 expr1n sqrtr1.\nQed.\n\nLemma C_mod_invE (y : complex R) : C_mod (y ^-1) = (C_mod y) ^-1.\nProof.\nhave [/eqP y0 | yn0] := boolP (y == 0); last by rewrite !C_modE normcV.\nrewrite y0 /C_mod /= !mul0r oppr0 expr0n /= RplusE mulr0n add0r RsqrtE //.\nby rewrite sqrtr0 invr0.\nQed.\n\nLemma C_mod_eq_0: forall (x: complex R), \n  C_mod x = 0 -> x = 0.\nProof.\nintros. rewrite /C_mod in H.\nassert ((Re x ^+ 2 + Im x ^+ 2) = 0).\n{ apply sqrt_eq_0. \n  + rewrite -!RpowE -RplusE. nra.\n  + apply H.\n} clear H.\nassert ((Re x ^+ 2 =0) /\\ (Im x ^+ 2 = 0)).\n{ apply Rplus_eq_R0. \n  + rewrite -RpowE. nra.\n  + rewrite -RpowE. nra.\n  + apply H0.\n} destruct H.\nassert (Re x = 0 /\\ Im x = 0). \n{ rewrite -RpowE in H. rewrite -RpowE in H1.\n  split. \n  + apply Rsqr_0_uniq. rewrite /Rsqr. \n    assert ((Re x ^ 2)%Re = (Re x * Re x)%Re). { nra. }\n    by rewrite -H2.\n  + apply Rsqr_0_uniq. rewrite /Rsqr. \n    assert ((Im x ^ 2)%Re = (Im x * Im x)%Re). { nra. }\n    by rewrite -H2.\n} destruct H2. \nassert (x = (Re x +i* Im x)%C). { apply C_destruct. }\nrewrite H4. apply /eqP. rewrite eq_complex //=.\napply /andP. by split; apply /eqP. \nQed.\n\nLemma C_mod_gt_0: forall (x: complex R),\n  x <> 0  <->  0 < C_mod x.\nProof.\nintros x ; split => Hx.\ndestruct (C_mod_ge_0 x) => //.\nby apply /RltbP. \ncontradict Hx. by apply C_mod_eq_0.\nassert ((0 < C_mod x)%Re). { by apply /RltbP. }\ncontradict H.\napply Rle_not_lt, Req_le.\nby rewrite H C_mod_0.\nQed.\n\nLemma C_mod_inv : forall x : complex R, \n  x <> 0 -> C_mod (invc x) = Rinv (C_mod x).\nProof.\nintros x Zx.\napply Rmult_eq_reg_l with (C_mod x).\nrewrite -[LHS]C_mod_prod.\nrewrite Rinv_r. rewrite mulrC.\nassert (invc x * x = 1). \n{ rewrite [LHS]mulVc. by rewrite /RtoC.  by apply /eqP. }\nby rewrite H C_mod_1.\nassert ( (0 < C_mod x)%Re -> C_mod x <> 0%Re). { nra. }\napply H. apply /RltbP. by apply C_mod_gt_0.\nassert ( (0 < C_mod x)%Re -> C_mod x <> 0%Re). { nra. }\napply H. apply /RltbP. by apply C_mod_gt_0.\nQed.\n\n\nLemma C_mod_gt_not_zero: forall x: complex R,\n  C_mod x <> 0 -> 0 < C_mod x.\nProof.\nintros. rewrite /C_mod. rewrite /C_mod in H. apply /RltP.\napply sqrt_lt_R0. \nassert (Re x = 0%Re \\/ (Re x <> 0)%Re).\n{ nra. }\nassert (Im x = 0%Re \\/ (Im x <> 0)%Re).\n{ nra. } destruct H0.\n+ destruct H1.\n  - rewrite H0 H1 in H.\n    by rewrite expr2 mulr0 Rplus_0_r sqrt_0 in H.\n  - rewrite H0 expr2 mulr0 Rplus_0_l -RpowE.\n    assert ((Im x ^ 2)%Re = Rsqr (Im x)). { rewrite /Rsqr. nra. }\n    rewrite H2. by apply Rsqr_pos_lt.\n+ destruct H1.\n  - rewrite H1. assert ( (0 ^+ 2)%Re = 0%Re). { by rewrite expr2 mulr0. }\n    rewrite H2 Rplus_0_r -RpowE.\n    assert ((Re x ^ 2)%Re = Rsqr (Re x)). { rewrite /Rsqr. nra. }\n    rewrite H3. by apply Rsqr_pos_lt.\n  - apply Rplus_lt_0_compat.\n    * rewrite -RpowE.\n      assert ((Re x ^ 2)%Re = Rsqr (Re x)). { rewrite /Rsqr. nra. }\n      rewrite H2. by apply Rsqr_pos_lt.\n    * rewrite -RpowE.\n      assert ((Im x ^ 2)%Re = Rsqr (Im x)). { rewrite /Rsqr. nra. }\n      rewrite H2. by apply Rsqr_pos_lt.\nQed.\n\nLemma Cinv_not_0: \n  forall x:complex R, x <> 0 -> (invc x)%C <> 0.\nProof.\nintros. apply C_mod_gt_0.\nrewrite C_mod_inv. apply /RltbP. apply Rinv_0_lt_compat. \napply /RltbP. apply C_mod_gt_0. apply H. apply H.\nQed.\n\nLemma Im_add: forall (x y: complex R), \n  Im (x+y)%C = Im x + Im y.\nProof.\nmove => [a b] [c d] //=.\nQed.\n\nLemma Re_add: forall (x y: complex R), \n  Re (x+y)%C = Re x + Re y.\nProof.\nmove => [a b] [c d] //=.\nQed.\n\n(** Some trivial proprties of the reals **)\nLemma posreal_cond: forall (x:posreal), (0< x)%Re.\nProof.\nintros. destruct x. auto.\nQed.\n\nLemma real_sub_0r : forall (x: R), (x-0)%Re = x.\nProof.\nintros. by rewrite RminusE subr0.\nQed.\n\nLemma Rsqr_ge_0: forall (x:R), (0<=x)%Re -> (0<= Rsqr x)%Re.\nProof.\nintros. unfold Rsqr. assert (0%Re = (0*0)%Re). { nra. }\nrewrite H0. apply Rmult_le_compat;nra. \nQed.\n\nLemma x_pow_n_not_0: forall (x:R) (n:nat), x <> 0 -> x^+n <> 0.\nProof.\nmove => x n H. induction n.\n+ rewrite expr0. by apply /eqP.\n+ rewrite exprS. by apply Rmult_integral_contrapositive.\nQed.\n\nLemma Rmult_le_compat_0: forall (x y :R), \n  (0 <= x)%Re -> (0<=y)%Re  -> (0 <= x*y)%Re.\nProof.\nintros. assert (0%Re = (0 * 0)%Re). { nra. } rewrite H1.\napply Rmult_le_compat; nra.\nQed.\n\n\n(** define a complex matrix **)\nDefinition RtoC_mat (n:nat) (A: 'M[R]_n): 'M[complex R]_n := \n  \\matrix_(i<n, j<n) ((A i j) +i* 0)%C.\n\n(** Define L2 norm of a vector **)\nDefinition vec_norm (n:nat) (x: 'cV[R]_n.+1)  := \n  sqrt (\\big[+%R/0]_l (Rsqr (x l 0))).\n\n(** Define vector norm for a complex vector **)\nDefinition vec_norm_C (n:nat) (x: 'cV[complex R]_n.+1):=\n  sqrt (\\big[+%R/0]_l (Rsqr (C_mod (x l 0)))).\n\n(** Define a non-zero vector **)\nDefinition vec_not_zero (n:nat) (x: 'cV[complex R]_n.+1):=\n  exists i:'I_n.+1,  x i 0 <> 0.\n\n(** Define a coercion from the real vector to a complex vector **)\nDefinition RtoC_vec (n:nat) (v: 'cV[R]_n.+1) : 'cV[complex R]_n.+1:=\n  \\col_i ((v i 0) +i* 0)%C.\n\n(** Define vector norm for a complex vector **)\nDefinition vec_norm_rowv (n:nat) (x: 'rV[complex R]_n.+1):=\n  sqrt (\\big[+%R/0]_l (Rsqr (C_mod (x 0 l)))).\n\n(** Define a non-zero row vector **)\nDefinition vec_not_zero_row (n:nat) (x: 'rV[complex R]_n.+1):=\n  exists i:'I_n.+1,  x 0 i <> 0.\n\nLemma vec_norm_R_C: forall (n:nat) (v: 'cV[R]_n.+1),\n  vec_norm_C (RtoC_vec  v) = vec_norm v.\nProof.\nintros. rewrite /vec_norm_C /vec_norm.\nhave H1: \\big[+%R/0]_l (C_mod (RtoC_vec v l 0))² = \\big[+%R/0]_l (v l 0)².\n{ apply eq_big. by []. intros. rewrite mxE /C_mod /=.\n  assert (0^+2 = 0%Re). { by rewrite expr2 mul0r. } rewrite H0 Rplus_0_r.\n  rewrite Rsqr_sqrt.\n  + rewrite -RpowE /Rsqr. nra.\n  + assert (((v i 0) ^+ 2) = Rsqr (v i 0)).\n    { rewrite -RpowE /Rsqr. nra. } rewrite H1.\n    apply Rle_0_sqr.\n} by rewrite H1.\nQed.\n\n\n(** \\sum_j (Re ((u j) * (v j)) = Re (\\sum_j ((u j) * (v j))) **)\nLemma eq_big_Re_C: forall (n:nat) (u v: 'I_n.+1 -> complex R),\n   (\\big[+%R/0]_(j<n.+1) Re ((u j) * (v j))%C) = Re (\\big[+%R/0]_(j<n.+1) ((u j)* (v j))).\nProof.\nintros.\ninduction n.\n+ by rewrite !big_ord_recr //= !big_ord0 !add0r. \n+ rewrite big_ord_recr //=. rewrite IHn -Re_add.\n  rewrite [in RHS]big_ord_recr //=.\nQed.\n\n(** \\sum_j (Im ((u j) * (v j)) = Im (\\sum_j ((u j) * (v j))) **)\nLemma eq_big_Im_C: forall (n:nat) (u v: 'I_n.+1 -> complex R),\n   (\\big[+%R/0]_(j<n.+1) Im ((u j) * (v j))%C) = Im (\\big[+%R/0]_(j<n.+1) ((u j)* (v j))).\nProof.\nintros.\ninduction n.\n+ by rewrite !big_ord_recr //= !big_ord0 !add0r. \n+ rewrite big_ord_recr //=. rewrite IHn -Im_add.\n  rewrite [in RHS]big_ord_recr //=.\nQed.\n\n(** \\sum_j 0 = 0 **)\nLemma big_0_sum: forall (n:nat),\n  \\big[+%R/0]_(j<n.+1) 0%Re = 0%Re.\nProof.\nintros. induction n.\n+ by rewrite !big_ord_recr //= big_ord0 add0r.\n+ rewrite big_ord_recr //=. rewrite IHn. apply add0r.\nQed. \n\nLemma mat_vec_unfold: forall (n:nat) (A: 'M[R]_n.+1 ) (v: 'cV[R]_n.+1),\n    RtoC_vec (mulmx A v) = mulmx (RtoC_mat A) (RtoC_vec v).\nProof.\nintros. apply matrixP. unfold eqrel. intros. rewrite !mxE.\nrewrite [RHS]C_destruct. apply /eqP. rewrite eq_complex /=.\napply /andP. split.\n+ apply /eqP. rewrite -eq_big_Re_C. apply eq_big. by [].\n  intros. by rewrite /RtoC_mat /RtoC_vec !mxE /= mul0r subr0.\n+ apply /eqP. rewrite -eq_big_Im_C. rewrite -[LHS](big_0_sum n).\n  apply eq_big. by []. intros. \n  by rewrite /RtoC_mat /RtoC_vec !mxE //= mul0r mulr0 add0r.\nQed.\n\n\nLemma sum_n_ge_0: forall (n:nat) (u: 'I_n.+1 ->R), \n    (forall i:'I_n.+1, 0<= (u i)) -> \n    0 <= \\big[+%R/0]_i (u i).\nProof.\nintros. induction n.\n+ by rewrite big_ord_recr //= big_ord0 add0r. \n+ rewrite big_ord_recr //=. apply /RleP. \n  apply Rplus_le_le_0_compat. apply /RleP. apply IHn. \n  intros. apply H. apply /RleP. apply H.\nQed.\n\n(** 0 <= ||v|| **)\nLemma vec_norm_C_ge_0: forall (n:nat) (v: 'cV[complex R]_n.+1), \n  (0<= vec_norm_C v)%Re.\nProof.\nintros.\nunfold vec_norm_C.\napply sqrt_positivity. apply /RleP.\napply sum_n_ge_0. intros.\nassert (0 = Rsqr 0). { symmetry. apply Rsqr_0. } rewrite H. apply /RleP.\napply Rsqr_incr_1. apply C_mod_ge_0.\nnra. apply C_mod_ge_0.\nQed.\n\nLemma vec_norm_rowv_ge_0: forall (n:nat) (v: 'rV[complex R]_n.+1), \n  (0<= vec_norm_rowv v)%Re.\nProof.\nintros.\nunfold vec_norm_rowv.\napply sqrt_positivity. apply /RleP.\napply sum_n_ge_0. intros.\nassert (0 = Rsqr 0). { symmetry. apply Rsqr_0. } rewrite H. apply /RleP.\napply Rsqr_incr_1. apply C_mod_ge_0.\nnra. apply C_mod_ge_0.\nQed.\n\nLemma sum_gt_0: forall (n:nat) (u: 'I_n.+1 -> R),   \n   (forall l:'I_n.+1, 0 < (u l) )-> \n      \\big[+%R/0]_l (u l) >0.\nProof.\nintros. induction  n.\n+ simpl. rewrite big_ord_recr //=. rewrite !big_ord0.\n  rewrite add0r. apply H. \n+ simpl. rewrite big_ord_recr //=.  \n  apply /RltbP. apply Rplus_lt_0_compat.\n  apply /RltbP. apply IHn. \n  intros. apply H. apply /RltbP. apply H. \nQed. \n\n(** Generic property of big operator for reals. Missing \n  in the mathcomp. **)\nLemma big_ge_0_ex_abstract I r (P: pred I) (E : I -> R):\n  (forall i, P i -> (0 <= E i)) ->\n  (0 <= \\big[+%R/0]_(i <-r | P i) E i).\nProof.\nmove => leE. apply big_ind.\n+ apply /RleP. apply Rle_refl.\n+ intros. apply /RleP.\n  rewrite -RplusE. apply Rplus_le_le_0_compat.  \n  - by apply /RleP.\n  - by apply /RleP.\n+ apply leE.\nQed.\n \n(** v <> 0 --> 0 < ||v|| **) \nLemma non_zero_vec_norm: forall (n:nat) (v: 'cV[complex R]_n.+1),\n  vec_not_zero v -> (vec_norm_C v <> 0)%Re.\nProof.\nintros.\nunfold vec_not_zero in H. \nassert ((0< vec_norm_C v)%Re -> (vec_norm_C v <> 0)%Re).\n{ nra. } apply H0. unfold vec_norm_C. \napply sqrt_lt_R0. destruct H as [i H].\nrewrite (bigD1 i) //=.  \nrewrite -RplusE.\napply Rplus_lt_le_0_compat.\n+ assert (0%Re = Rsqr 0). { by rewrite Rsqr_0. }\n  rewrite H1. apply Rsqr_incrst_1.\n  - apply /RltP. by apply C_mod_gt_0.\n  - nra.\n  - apply C_mod_ge_0.\n+ apply /RleP. apply big_ge_0_ex_abstract.\n  intros. apply /RleP. apply Rle_0_sqr.\nQed.\n\n\nLemma non_zero_vec_norm_row: forall (n:nat) (v: 'rV[complex R]_n.+1),\n v != 0 -> (vec_norm_rowv v <> 0)%Re.\nProof.\nintros.\nassert (exists i, v 0 i != 0). { by apply /rV0Pn. } \nassert ((0< vec_norm_rowv v)%Re -> (vec_norm_rowv v <> 0)%Re).\n{ nra. } apply H1. unfold vec_norm_rowv. \napply sqrt_lt_R0. destruct H0 as [i H0].\nrewrite (bigD1 i) //=.  \nrewrite -RplusE.\napply Rplus_lt_le_0_compat.\n+ assert (0%Re = Rsqr 0). { by rewrite Rsqr_0. }\n  rewrite H2. apply Rsqr_incrst_1.\n  - apply /RltP. apply C_mod_gt_0. by apply /eqP.\n  - nra.\n  - apply C_mod_ge_0.\n+ apply /RleP. apply big_ge_0_ex_abstract.\n  intros. apply /RleP. apply Rle_0_sqr.\nQed.\n\nLemma vec_norm_eq: forall (n:nat) (x y: 'cV[R]_n.+1), \n   x=y -> vec_norm x = vec_norm y.\nProof.\nintros.\nrewrite H. reflexivity.\nQed.\n\n\nLemma RtoC_Mone: forall n:nat, @RtoC_mat n 1%:M = 1%:M.\nProof.\nintros. rewrite /RtoC_mat. apply matrixP. unfold eqrel.\nintros. rewrite !mxE.\ncase: (x == y); simpl;apply /eqP;rewrite eq_complex /=;by apply /andP.\nQed. \n\nLemma C_equals: forall (x y: complex R),\n  (Re x = Re y) /\\ (Im x = Im y) -> x = y.\nProof.\nmove =>[a b] [c d] //= H. destruct H. rewrite H H0 //=.\nQed.\n\nLemma RtoC_mat_prod: forall (n:nat) (A B: 'M[R]_n.+1),\n  mulmx (RtoC_mat A) (RtoC_mat B) = RtoC_mat (mulmx A B).\nProof.\nintros. apply matrixP. unfold eqrel. intros.\nrewrite !mxE. apply C_equals. split.\n+ simpl. rewrite -eq_big_Re_C. apply eq_big. by [].\n  intros. by rewrite /RtoC_mat !mxE //= mul0r subr0.\n+ rewrite //= -eq_big_Im_C -[RHS](big_0_sum n). apply eq_big.\n  by []. intros. by rewrite /RtoC_mat !mxE //= mul0r mulr0 add0r.\nQed.\n\nLemma RtoC_mat_add: forall (n:nat) (A B: 'M[R]_n.+1),\n  RtoC_mat (addmx A B) = addmx (RtoC_mat A) (RtoC_mat B).\nProof.\nintros. apply matrixP. unfold eqrel. intros. rewrite !mxE.\napply /eqP. rewrite eq_complex //= add0r. apply /andP.\nsplit; by apply /eqP.\nQed.\n\n\n(** Properties of scale operation of vectors and matrices **)\n\n\n(** define the scale operation for a complex vector **)\nDefinition scal_vec_C (n:nat) (l:complex R) (v: 'cV[complex R]_n.+1):=\n  \\col_(i<n.+1) (l * (v i 0))%C.\n\n(** define the scale operation for a complex vector **)\nDefinition scal_vec_rowC (n:nat) (l:complex R) (v: 'rV[complex R]_n.+1):=\n  \\row_(i<n.+1) (l * (v 0 i))%C.\n\n(** ||scale c v|| = |c| * ||v|| **)\nLemma ei_vec_ei_compat: forall (n:nat) (x:complex R) (v: 'cV[complex R]_n.+1), \n  vec_norm_C (scal_vec_C x v) = C_mod x * vec_norm_C v.\nProof.\nintros. unfold vec_norm_C. \nhave H1: sqrt (Rsqr (C_mod x)) = C_mod x. \n  { apply sqrt_Rsqr. apply C_mod_ge_0. }\nrewrite -H1 -RmultE -sqrt_mult_alt.\nhave H2: (\\big[+%R/0]_l (C_mod (scal_vec_C x v l 0))²) = \n           ((C_mod x)² *  \\big[+%R/0]_l (C_mod (v l 0))²).\n{ rewrite mulr_sumr. apply eq_big. by []. intros. \n  rewrite mxE C_mod_prod -RmultE. apply Rsqr_mult.\n} by rewrite H2. \nassert (0%Re = Rsqr 0). { symmetry. apply Rsqr_0. } rewrite H.\napply Rsqr_incr_1. apply C_mod_ge_0. nra. apply C_mod_ge_0.\nQed.\n\n(** ||scale c v|| = |c| * ||v|| **)\nLemma ei_vec_ei_compat_row: forall (n:nat) (x:complex R) (v: 'rV[complex R]_n.+1), \n  vec_norm_rowv (scal_vec_rowC x v) = C_mod x * vec_norm_rowv v.\nProof.\nintros. unfold vec_norm_rowv. \nhave H1: sqrt (Rsqr (C_mod x)) = C_mod x. \n  { apply sqrt_Rsqr. apply C_mod_ge_0. }\nrewrite -H1 -RmultE -sqrt_mult_alt.\nhave H2: (\\big[+%R/0]_l (C_mod (scal_vec_rowC x v 0 l))²) = \n           ((C_mod x)² *  \\big[+%R/0]_l (C_mod (v 0 l))²).\n{ rewrite mulr_sumr. apply eq_big. by []. intros. \n  rewrite mxE C_mod_prod -RmultE. apply Rsqr_mult.\n} by rewrite H2. \nassert (0%Re = Rsqr 0). { symmetry. apply Rsqr_0. } rewrite H.\napply Rsqr_incr_1. apply C_mod_ge_0. nra. apply C_mod_ge_0.\nQed.\n\n\n(** v = scale 1 v **)\nLemma scal_vec_1: forall (n:nat) (v: 'cV[complex R]_n.+1), \n  v= scal_vec_C (1%C) v.\nProof.\nintros. apply matrixP. unfold eqrel. intros. rewrite mxE.\nsymmetry. assert (y=0).  { apply ord1. } by rewrite H mul1r. \nQed.\n\nLemma scal_vec_1_row: forall (n:nat) (v: 'rV[complex R]_n.+1), \n  v= scal_vec_rowC (1%C) v.\nProof.\nintros. apply matrixP. unfold eqrel. intros. rewrite mxE.\nsymmetry. assert (x=0).  { apply ord1. } by rewrite H mul1r. \nQed.\n\n\n(** scale x (scale l v) = scale (l*v) v **)\nLemma scal_of_scal_vec : \n forall (n:nat) (x l:complex R) (v: 'cV[complex R]_n.+1),\n  scal_vec_C x (scal_vec_C l v) = scal_vec_C (x* l)%C v.\nProof.\nintros. unfold scal_vec_C. apply matrixP. unfold eqrel. intros.\nby rewrite !mxE /= mulrA.\nQed.\n\nLemma scal_of_scal_vec_row : \n forall (n:nat) (x l:complex R) (v: 'rV[complex R]_n.+1),\n  scal_vec_rowC x (scal_vec_rowC l v) = scal_vec_rowC (x* l)%C v.\nProof.\nintros. unfold scal_vec_rowC. apply matrixP. unfold eqrel. intros.\nby rewrite !mxE /= mulrA.\nQed.\n\n\n(** scale x (scale l v) = scale l (scale x v) **)\nLemma scal_vec_C_comm : \nforall (n:nat) (x l:complex R) (v: 'cV[complex R]_n.+1),\n  scal_vec_C x (scal_vec_C l v) = scal_vec_C l (scal_vec_C x v).\nProof.\nintros.\nunfold scal_vec_C. apply matrixP. unfold eqrel. intros.\nrewrite !mxE /=.\nhave H1: (x * (l * v x0 0))%C  = ((x* l) * (v x0 0))%C.\n{ apply mulrA. } rewrite H1. \nhave H2: (l * (x * v x0 0))%C = ((l* x) * (v x0 0))%C.\n{ apply mulrA. } rewrite H2. \nassert ((x* l)%C = (l* x)%C). { apply mulrC. } by rewrite H.\nQed.\n\n\nLemma scal_vec_C_row_comm : \nforall (n:nat) (x l:complex R) (v: 'rV[complex R]_n.+1),\n  scal_vec_rowC x (scal_vec_rowC l v) = scal_vec_rowC l (scal_vec_rowC x v).\nProof.\nintros.\nunfold scal_vec_rowC. apply matrixP. unfold eqrel. intros.\nrewrite !mxE /=.\nhave H1: (x * (l * v 0 y))%C  = ((x* l) * (v 0 y))%C.\n{ apply mulrA. } rewrite H1. \nhave H2: (l * (x * v 0 y))%C = ((l* x) * (v 0 y))%C.\n{ apply mulrA. } rewrite H2. \nassert ((x* l)%C = (l* x)%C). { apply mulrC. } by rewrite H.\nQed.\n\nLemma scale_vec_mat_conv_C:\n  forall (n:nat) (l:complex R) (v: 'cV[complex R]_n.+1) (A: 'M[complex R]_n.+1),\n  scal_vec_C l (A *m v) =  A *m (scal_vec_C l v).\nProof.\nintros. apply matrixP. unfold eqrel. intros.\nrewrite !mxE. \nassert (y = 0). { by apply ord1. } rewrite H.\nrewrite /scal_vec_C //=. \nassert (\\big[+%R/0]_(j < n.+1) (A x j *(\\col_i (l * v i 0)) j 0)= \n      \\big[+%R/0]_(j < n.+1) ((l * v j 0) * A x j)).\n{ apply eq_big. by []. intros. rewrite !mxE. by rewrite mulrC -mulrA. }\nrewrite H0. rewrite big_distrr //=. apply eq_big.\nby []. intros. rewrite -mulrA. \nassert ((A x i * v i 0) = (v i 0 * A x i)).\n{ by rewrite mulrC. } by rewrite H2.\nQed.\n\n\nLemma scale_vec_mat_conv:\n  forall (n:nat) (l:complex R) (v: 'rV[complex R]_n.+1) (A: 'M[complex R]_n.+1),\n  scal_vec_rowC l (v *m A) = (scal_vec_rowC l v) *m A.\nProof.\nintros. apply matrixP. unfold eqrel. intros.\nrewrite !mxE. \nassert (x = 0). { by apply ord1. } rewrite H.\nrewrite /scal_vec_rowC //=. \nassert (\\big[+%R/0]_(j < n.+1) ((\\row_i (l * v 0 i)) 0\n                          j * A j y)= \n      \\big[+%R/0]_(j < n.+1) ((l * v 0 j) * A j y)).\n{ apply eq_big. by []. intros. by rewrite !mxE. }\nrewrite H0. rewrite big_distrr //=. apply eq_big.\nby []. intros. by rewrite mulrA.\nQed.\n\nLemma scal_vec_mathcomp_compat_col:\n  forall (n:nat) (l: complex R) (v: 'cV[complex R]_n.+1),\n  l *: v = (scal_vec_C l v).\nProof.\nintros. apply matrixP. unfold eqrel. intros.\nrewrite !mxE. \nassert (y = 0). { by apply ord1. } by rewrite H.\nQed.\n\nLemma scal_vec_mathcomp_compat:\n  forall (n:nat) (l: complex R) (v: 'rV[complex R]_n.+1),\n  l *: v = (scal_vec_rowC l v).\nProof.\nintros. apply matrixP. unfold eqrel. intros.\nrewrite !mxE. \nassert (x = 0). { by apply ord1. } by rewrite H.\nQed.\n\n\n(** x * \\sum_j (u j) = \\sum_j (x * (u j)) **)\nLemma big_scal: forall (n:nat) (u: 'I_n.+1 -> complex R) (x:complex R),\n  (x* \\big[+%R/0]_j (u j))%C = \\big[+%R/0]_j (x* (u j))%C.\nProof.\nintros. induction n.\n+ by rewrite !big_ord_recr //= !big_ord0 !add0r. \n+ rewrite big_ord_recr //= mulrDr IHn [RHS]big_ord_recr //=.\nQed.\n\n(** Define scale operation for a complex matrix **)\nDefinition scal_mat_C (m n :nat) (l:complex R) (x: 'M[complex R]_(m,n)):= \n    \\matrix_(i<m,j<n) (l* (x i j))%C.\n\n\nLemma big_scal_com: \n  forall (n:nat) (x: complex R) (u : 'I_n.+1 -> complex R),\n  x * (\\big[+%R/0]_j (u j)) = \\big[+%R/0]_j (x * (u j)).\nProof.\nintros. induction n.\n+ by rewrite !big_ord_recr //= !big_ord0 //= !add0r.\n+ rewrite big_ord_recr //= [RHS]big_ord_recr //=.\n  by rewrite -IHn mulrDr.\nQed. \n\n\nLemma scal_mat_to_vec: \n  forall (m : nat) (l:complex R) (v: 'cV[complex R]_m.+1),\n  scal_mat_C l v = scal_vec_C l v.\nProof.\nintros. apply matrixP. unfold eqrel. intros. rewrite !mxE. \nassert (y=0). { apply ord1. } by rewrite H.\nQed.\n\n(** scale x v + scale y v = scale (x+y) v **)\nLemma scal_vec_add_xy: \n  forall (n:nat) (x y:complex R) (v: 'cV[complex R]_n.+1),\n  addmx (scal_vec_C x v) (scal_vec_C y v) = scal_vec_C (x+y)%C v.\nProof.\nintros. unfold addmx. unfold scal_vec_C. apply matrixP. unfold eqrel.\nintros. by rewrite !mxE /= mulrDl.\nQed.\n\nLemma scal_vec_eq: \n  forall (n:nat) (x:complex R) (v1 v2: 'cV[complex R]_n.+1),\n   x <> 0 -> scal_vec_C x v1 = scal_vec_C x v2 -> v1 = v2.\nProof.\nintros. apply colP. unfold eqfun.\nintros. unfold scal_vec_C in H0. apply matrixP in H0. \nunfold eqrel in H0. specialize (H0 x0 0).\nrewrite !mxE in H0. rewrite <- mul1r.\nhave H1: v1 x0 0 = (1 * v1 x0 0)%C. \n{ by rewrite mul1r. } \nhave H2: (invc x * x)%C = 1. { apply mulVc. by apply /eqP. }\nrewrite <-H2. rewrite -!mulrA.\nrewrite H0. by rewrite mulrA mulrC H2 mulr1.\nQed.\n\n(** scale x v1 + scale x v2 = scale x (v1 + v2) **)\nLemma scal_vec_add: \n  forall (n:nat) (x: complex R) (v1 v2: 'cV[complex R]_n.+1),\n  addmx (scal_vec_C x v1) (scal_vec_C x v2) =  scal_vec_C x (addmx v1 v2).\nProof.\nintros. rewrite /addmx /scal_vec_C. apply matrixP. unfold eqrel.\nintros. rewrite !mxE/=. by rewrite mulrDr. \nQed.\n\n(** -(scale x v)  =  scale (-x) v **)\nLemma scal_vec_C_Mopp: forall (n:nat) (x:complex R) (v: 'cV[complex R]_n.+1), \n  oppmx (scal_vec_C x v) = scal_vec_C (-x)%C v.\nProof.\nintros. rewrite /scal_vec_C /oppmx. apply matrixP. unfold eqrel.\nintros. by rewrite !mxE /= mulNr. \nQed.\n\nDefinition scal_of_mat0 (A: 'cV[complex R]_1):= A 0 0.\n\n\nLemma scal_conv_scal_vec: forall (x:complex R) (v: 'M[complex R]_1),\n  scal_of_mat0 (scal_vec_C x v) = (x* (scal_of_mat0 v))%C.\nProof.\nintros. by rewrite /scal_of_mat0 /scal_vec_C !mxE.\nQed.\n\n\n(** Define transpose of a complex matrix  **)\nDefinition transpose_C (m n:nat) (A: 'M[complex R]_(m,n)):=\n  \\matrix_(i<n,j<m) A j i.\n\n\n(** Define conjugate of a complex matrix **)\nDefinition conjugate (m n:nat) (A: 'M[complex R]_(m,n)):=\n  \\matrix_(i<m,j<n) conjc (A i j).\n\n(** Define conjugate tranpose of a complex matrix **)\nDefinition conjugate_transpose (m n:nat) (A: 'M[complex R]_(m,n)):=\n  transpose_C (conjugate A).\n\n(** Generic properties of complex conjugates **)\n\n(** x* conj x = ||x||^2 :> complex **)\nLemma conj_mag: \n  forall x:complex R, (x* conjc x)%C = RtoC (Rsqr (C_mod x)).\nProof.\nintros. rewrite /conjc /RtoC /C_mod.\nassert ( x = (Re x +i* Im x)%C). { apply C_destruct. }\nrewrite H //=. apply /eqP. rewrite eq_complex //=.\napply /andP. split.\n+ apply /eqP. rewrite -mulN1r mulrN mulrNN mul1r.\n  rewrite Rsqr_sqrt.\n  - rewrite -!RpowE -RplusE -!RmultE. nra.\n  - rewrite -!RpowE. nra.\n+ apply /eqP. rewrite mulrN mulrC //=. \n  rewrite -!RmultE -RplusE. apply Rplus_opp_l. \nQed.  \n\nLemma Cconj_prod: forall (x y: complex R),\n  conjc (x*y)%C = (conjc x * conjc y)%C.\nProof.\nmove => [a b] [c d]. apply /eqP. rewrite eq_complex //=.\napply /andP. split.\n+ apply /eqP. by rewrite mulrNN.\n+ apply /eqP. by rewrite mulrN mulNr opprD. \nQed.\n\n\nLemma conj_mag_re: \n  forall x:complex R, Re (x* conjc x)%C = Rsqr (C_mod x).\nProof.\nintros.\nassert ( (x* conjc x)%C = RtoC (Rsqr (C_mod x))).\n{ by rewrite conj_mag. } by rewrite H.\nQed.\n\nLemma C_mod_sqr: forall (x y : complex R),\n  Rsqr (C_mod (x * y)) = (Rsqr (C_mod x)) * (Rsqr (C_mod y)).\nProof.\nintros. rewrite -!conj_mag_re. rewrite Cconj_prod.\nassert ((x * y * ((x^*)%C * (y^*)%C))%C = \n        ((x * (x^*)%C) * (y * (y^*)%C))%C).\n{ rewrite mulrC.\n  assert ((x * y)%C = (y * x)%C). { by rewrite mulrC. } \n  rewrite H. \n  assert (((x^*)%C * (y^*)%C * (y * x))%C = \n            ((x^*)%C *( (y^*)%C * (y * x)))%C).\n  { by rewrite -mulrA. } rewrite H0.\n  assert (((y^*)%C * (y * x))%C = ( x * (y * (y^*)%C))%C).\n  { rewrite mulrA. rewrite mulrC.\n    assert (((y^*)%C * y)%C = (y * (y^*)%C)%C).\n    { by rewrite mulrC. } by rewrite H1.\n  } rewrite H1. rewrite mulrA.\n  rewrite mulrC.\n  assert (((x^*)%C * x)%C = (x * (x^*)%C)%C).\n  { by rewrite mulrC. } rewrite H2. by rewrite mulrC.\n} rewrite H. rewrite Re_complex_prod.\nassert (Im (x * (x^*)%C) * Im (y * (y^*)%C) = 0).\n{ rewrite !conj_mag //=. by rewrite mulr0. } rewrite H0.\nby rewrite subr0.\nQed.\n\n\n(** conj (scale l x) = scale (conj l) x^* **)\nLemma conj_scal_mat_mul: \n  forall (m n : nat) (l:complex R) (x: 'M[complex R]_(m,n)),\n  conjugate_transpose (scal_mat_C l x) = scal_mat_C (conjc l) (conjugate_transpose x).\nProof.\nintros.\nrewrite /conjugate_transpose /transpose_C /scal_mat_C /conjugate. \napply matrixP. unfold eqrel. intros.\nrewrite !mxE /=. apply Cconj_prod.\nQed.\n\nLemma Ceq_dec: forall (x: complex R),\n  (x==0) || (x != 0).\nProof.\nmove => [a b]. rewrite eq_complex //=.\nassert ( a = 0 \\/ a <> 0). { by apply Req_dec. }\nassert ( b = 0 \\/ b <> 0). { by apply Req_dec. } \ndestruct H.\n+ rewrite H //=.\n  destruct H0.\n  - rewrite H0 //=. apply /orP. left. \n    apply /andP. by split; apply /eqP.\n  - apply /orP. right. apply /nandP. by right; apply /eqP.\n+ apply /orP. right. apply /nandP. left. by apply /eqP.\nQed. \n\n \nLemma Cmult_neq_0 (z1 z2 : complex R) : \n  z1 <> 0 -> z2 <> 0 -> z1 * z2 <> 0.\nProof.\n  intros Hz1 Hz2 => Hz.\n  assert (C_mod (z1 * z2) = 0).\n  by rewrite Hz C_mod_0.\n  rewrite C_mod_prod in H.\n  apply Rmult_integral in H ; destruct H.\n  now apply Hz1, C_mod_eq_0.\n  now apply Hz2, C_mod_eq_0.\nQed.\n\nLemma prod_not_zero: forall (x y: complex R) , \n  (x*y)%C <>0 <-> (x <> 0) /\\ (y <> 0).\nProof.\nintros.\nsplit.\n+ intros.\n  split. \n  - assert ( (x==0) \\/ (x!=0)). \n    { have H1: (x==0) || (x != 0). apply Ceq_dec. \n      intros. by apply /orP.\n    } destruct H0. \n    * assert (x=0). { by apply /eqP. } rewrite H1 in H. \n      by rewrite mul0r in H. \n    * by apply /eqP.\n  - assert ( (y==0) \\/ (y!=0)). \n    { have H1: (y==0) || (y != 0). apply Ceq_dec. \n      intros. by apply /orP.\n    } destruct H0. \n    * assert (y=0). { by apply /eqP. } rewrite H1 in H. \n      by rewrite mulr0 in H. \n    * by apply /eqP.\n+ intros. destruct H. \n  apply Cmult_neq_0. apply H. apply H0.\nQed.\n\nLemma Cconj_add: forall (x y: complex R), \n  conjc (x+y) = conjc x + conjc y.\nProof.\nmove => [a b] [c d]. rewrite /conjc //=. apply /eqP.\nrewrite eq_complex //=. apply /andP. split.\n+ by apply /eqP.\n+ apply /eqP. by rewrite opprD.\nQed.\n\nLemma conj_prod: \n  forall (x:complex R), ((conjc x)*x)%C = RtoC (Rsqr (C_mod x)).\nProof.\nmove => [a b]. rewrite /conjc /C_mod //= /RtoC.\napply /eqP. rewrite eq_complex //=. apply /andP.\nsplit.\n+ apply /eqP. rewrite Rsqr_sqrt.\n  - rewrite -!RpowE -!RmultE -!RoppE -RplusE. nra.\n  - rewrite -!RpowE. nra.\n+ apply /eqP. by rewrite mulNr mulrC addrN.\nQed.\n\n(** conj (\\sum_j (x j)) = \\sum_j (conj (x j)) **)\nLemma Cconj_sum: forall (p:nat) (x: 'I_p -> complex R),\n  conjc (\\big[+%R/0]_(j < p) x j)= \\big[+%R/0]_(j < p) conjc (x j).\nProof.\nintros.\ninduction p.\n+ by rewrite !big_ord0 conjc0 //=.\n+ rewrite !big_ord_recl. \n  rewrite <-IHp. apply Cconj_add.\nQed.\n\n\nLemma conj_of_conj_C: forall (x: complex R), \n  x = conjc (conjc x).\nProof.\nintros.\nassert (x = (Re x +i* Im x)%C).\n{ by rewrite -C_destruct. } rewrite H.\nrewrite /conjc //=. apply /eqP. rewrite eq_complex //=.\napply /andP. split.\n+ by [].\n+ by rewrite opprK.\nQed.\n\nLemma double_r: forall (x:R),\n  (2 * x)%Re = (x + x)%Re.\nProof.\nintros. nra.\nQed.\n\nLemma Re_conjc_add: forall (x: complex R),\n  Re x + Re (conjc x) = 2 * (Re x).\nProof.\nintros. \nassert (x = (Re x +i* Im x)%C).\n{ by rewrite -C_destruct. } rewrite H //=. \nrewrite -RmultE -RplusE. \nby rewrite double_r.\nQed.\n\n\nLemma Cconjc_mod: forall (a: complex R),\n  C_mod a = C_mod (conjc a).\nProof.\nintros. \nassert (a = (Re a +i* Im a)%C).\n{ by rewrite -C_destruct. } rewrite H.\nrewrite /C_mod //=. by rewrite sqrrN.\nQed.\n\nLemma Re_C_le_C_mod: forall (x : complex R),\n  Re x <= C_mod x.\nProof.\nintros. apply /RleP. rewrite /C_mod.\nassert ((Re x < 0)%Re \\/ (0 <= Re x)%Re). { nra. }\ndestruct H.\n+ apply Rle_trans with 0%Re.\n  - by apply Rlt_le.\n  - apply sqrt_pos.\n+ apply Rsqr_incr_0.\n  - rewrite Rsqr_sqrt.\n    * unfold Rsqr. rewrite !expr2 -!RmultE. nra.\n    * apply Rplus_le_le_0_compat;rewrite -RpowE;nra.\n    * nra.\n    * apply sqrt_pos.\nQed.\n\n\nLemma C_mod_add_leq : forall (a b: complex R),\n  C_mod (a + b) <= C_mod a + C_mod b.\nProof.\nintros. apply /RleP. rewrite -!RplusE. apply Rsqr_incr_0.\n+ rewrite -conj_mag_re. rewrite Cconj_add.\n  rewrite !mulrDr !mulrDl. rewrite !Re_add.\n  rewrite -!RplusE. rewrite !conj_mag_re. \n  rewrite Rsqr_plus.\n  assert (((C_mod a)² + Re (b * (a^*)%C)%Ri +\n              (Re (a * (b^*)%C)%Ri + (C_mod b)²))%Re = \n          (((C_mod a)² + (C_mod b)²) +\n            ( Re (b * (a^*)%C)%Ri + Re (a * (b^*)%C)%Ri))%Re).\n  { nra. } rewrite H.\n  apply Rplus_le_compat.\n  - nra.\n  - assert ((a * (b^*)%C) = conjc (b * conjc a)).\n    { rewrite Cconj_prod. rewrite -conj_of_conj_C. by rewrite mulrC. }\n    rewrite H0. apply /RleP. rewrite RplusE. rewrite Re_conjc_add.\n    apply /RleP. rewrite -RmultE.\n    assert (C_mod a = C_mod (conjc a)).\n    { by rewrite Cconjc_mod. } rewrite H1.\n    assert ((2 * C_mod (conjc a) * C_mod b)%Re = (2 * (C_mod b * C_mod (conjc a)))%Re).\n    { nra. } rewrite H2. apply /RleP. rewrite !RmultE. rewrite -C_mod_prod.\n    apply /RleP. rewrite -!RmultE. apply Rmult_le_compat_l.\n    * nra.\n    * remember ((b * (a^*)%C)%Ri) as c.\n      apply /RleP. apply Re_C_le_C_mod.\n  - apply C_mod_ge_0.\n  - apply Rplus_le_le_0_compat; apply C_mod_ge_0.\nQed.\n\n\nLemma C_mod_sum_rel: forall (n:nat) (u : 'I_n.+1 -> (complex R)),\n  (C_mod (\\big[+%R/0]_j (u j))) <= \\big[+%R/0]_j ((C_mod (u j))).\nProof.\nintros. induction n.\n+ simpl. rewrite !big_ord_recl //= !big_ord0.\n  by rewrite !addr0.\n+ simpl. rewrite big_ord_recr //=.\n  assert ( \\big[+%R/0]_(j < n.+2) (C_mod (u j)) = \n            \\big[+%R/0]_(j < n.+1) (C_mod (u (widen_ord (leqnSn n.+1) j))) +\n              (C_mod (u ord_max))).\n  { by rewrite big_ord_recr //=. } rewrite H.\n  apply /RleP.\n  apply Rle_trans with \n    (C_mod (\\big[+%R/0]_(i < n.+1) u (widen_ord (leqnSn n.+1) i)) +   \n      C_mod (u ord_max)).\n  - apply /RleP. apply C_mod_add_leq.\n  - rewrite -!RplusE. apply Rplus_le_compat.\n    * apply /RleP. apply IHn.\n    * nra.\nQed.\n\n\n\n(** (A B)^* = B^* A^* **)\nLemma conj_matrix_mul : \n  forall (m n p:nat) (A: 'M[complex R]_(m,p)) (B: 'M[complex R]_(p,n)),\n    conjugate_transpose (mulmx A B) = mulmx\n      (conjugate_transpose B) (conjugate_transpose A).\nProof.\nintros.\nrewrite /conjugate_transpose /transpose_C /conjugate.\napply matrixP. unfold eqrel. intros.\nrewrite !mxE /=. \nhave H: conjc (\\big[+%R/0]_(j < p) (A y j * B j x)) = \n            \\big[+%R/0]_(j < p) conjc (A y j * B j x).\n{ apply Cconj_sum. }\nrewrite H. apply eq_big. by [].\nintros. by rewrite !mxE Cconj_prod //= mulrC.\nQed.\n\n(** x^* ^* = x**)\nLemma conj_of_conj: forall (m n:nat) (x: 'M[complex R]_(m,n)),\n  conjugate_transpose (conjugate_transpose x) = x.\nProof.\nintros. rewrite /conjugate_transpose /transpose_C /conjugate.\napply matrixP. unfold eqrel. intros. rewrite !mxE.\nassert ( x x0 y = (Re (x x0 y) +i* Im (x x0 y))%C).\n{ apply C_destruct. } rewrite H /conjc //=. apply /eqP.\nrewrite eq_complex //=. apply /andP. split.\n+ by apply /eqP.\n+ apply /eqP. by rewrite opprK.\nQed.\n\n(** conjugate transpose of a real matrix is the matrix itself **)\nLemma conj_transpose_A: forall (n:nat) (A : 'M[R]_n.+1),\n  (forall i j:'I_n.+1,   A i j = A j i) -> \n  conjugate_transpose (RtoC_mat A) = RtoC_mat A.\nProof.\nintros. \nrewrite /conjugate_transpose /RtoC_mat /transpose_C /conjugate.\napply matrixP. unfold eqrel. intros. rewrite !mxE.\nrewrite /conjc. apply /eqP. rewrite eq_complex //=. apply /andP.\nsplit.\n+ apply /eqP. apply H.\n+ apply /eqP. apply oppr0.\nQed.\n\n\nLemma Re_eq: forall (x y:complex R), x= y -> Re x = Re y.\nProof.\nintros. by rewrite /Re H. \nQed.\n\nLemma Re_prod: \n  forall (x:R) (y:complex R), Re (RtoC x * y)%C = Re (RtoC x) * Re y.\nProof.\nby move => x [a b]; rewrite /RtoC //= mul0r subr0.\nQed.\n\n\nLemma Rsqr_le_add: forall (x y:R),\n  (0 <= y)%Re ->\n  (Rsqr x <= Rsqr x + y)%Re.\nProof.\nintros.\nassert (Rsqr x = (Rsqr x + 0)%Re). { nra. } rewrite H0.\nassert ( (x² + 0 + y)%Re = (Rsqr x + y)%Re). { nra. } rewrite H1.\napply Rplus_le_compat; nra.\nQed.\n\nLemma big_sum_1_const: forall (n:nat),\n  \\big[+%R/0]_(l < n.+1) 1 = n.+1%:R :> R.\nProof.\nintros. induction n.\n+ by rewrite big_ord_recl //= big_ord0 addr0.\n+ rewrite big_ord_recr //=. rewrite IHn. rewrite -addn2. \n  rewrite natrD. rewrite -addn1. rewrite natrD. rewrite -addrA.\n  by rewrite -natrD.\nQed.\n\nLemma n_plus_1_gt_0: forall n:nat,\n  (0 < n.+1%:R)%Re.\nProof.\nintros. induction n.\n+ apply Rlt_0_1.\n+ assert (n.+2%:R = n.+1%:R + 1%:R :> R).\n  { rewrite -addn2. \n    rewrite natrD. rewrite -addn1. rewrite natrD.\n    assert (n.+1%:R = n%:R + 1%R :> R).\n    { by rewrite -addn1 natrD. } rewrite H. \n    by rewrite -addrA.\n  } rewrite H. rewrite -RplusE. \n  apply Rplus_lt_0_compat.\n  - by [].\n  - apply Rlt_0_1.\nQed.\n\nLemma sqrt_n_neq_0: forall n:nat,\n  sqrt n.+1%:R != 0.\nProof.\nintros. apply /eqP.\napply Rgt_not_eq. apply Rlt_gt.\napply sqrt_lt_R0. apply n_plus_1_gt_0.\nQed.\n\n(*** existence of right eigen vector **)\nLemma matrix_vec_transpose (n:nat) (A: 'M[complex R]_n.+1) (v: 'rV[complex R]_n.+1):\n  A^T *m v^T = (v *m A)^T.\nProof.\napply matrixP. unfold eqrel. intros.\nrewrite !mxE. apply eq_big. by [].\nintros. rewrite !mxE. by rewrite mulrC.\nQed.\n\nLemma scal_vec_transpose (n:nat) (l : complex R) (v: 'rV[complex R]_n.+1):\n  l *: v^T = (l *: v)^T.\nProof.\napply matrixP. unfold eqrel. intros. by rewrite !mxE.\nQed.\n\n\nLemma char_poly_A_A_tr:\n  forall (n:nat) (A: 'M[complex R]_n.+1),\n  char_poly A = char_poly A^T.\nProof.\nintros. rewrite /char_poly /char_poly_mx.\nrewrite -det_tr.\nrewrite /determinant //=. apply eq_big.\n+ by [].\n+ intros. \n  assert (\\big[ *%R/1]_(i0 < succn n) ('X%:M - map_mx polyC A)^T\n                              i0\n                              (perm.PermDef.fun_of_perm\n                                 i i0) = \n          \\big[ *%R/1]_(i0 < succn n) ('X%:M - map_mx polyC A^T)\n                              i0\n                              (perm.PermDef.fun_of_perm\n                                 i i0)).\n  { apply eq_big. by []. intros. \n    rewrite !mxE. \n    by rewrite eq_sym.\n  } by rewrite H0.\nQed. \n\n\nLemma eigen_val_mat_transpose:\n  forall (n:nat) (l: complex R) (A: 'M[complex R]_n.+1),\n  @eigenvalue (complex_fieldType _) n.+1 A l = \n  @eigenvalue (complex_fieldType _) n.+1 A^T l.\nProof.\nintros. rewrite !eigenvalue_root_char.\nassert ((char_poly A) = (char_poly A^T)).\n{ apply char_poly_A_A_tr. } by rewrite H.\nQed.\n\nLemma A_tr_tr: forall (n:nat) (A: 'M[complex R]_n.+1),\n  A = (A^T)^T.\nProof.\nintros. apply matrixP. unfold eqrel. intros.\nby rewrite !mxE.\nQed.\n\n\nLemma A_v_tr:\n  forall (n:nat) (A: 'M[complex R]_n.+1) (v: 'rV[complex R]_n.+1),\n  A *m v^T = (v *m A^T)^T.\nProof.\nintros. apply matrixP. unfold eqrel. intros. rewrite !mxE.\napply eq_big. by [].\nintros. rewrite !mxE. by rewrite mulrC.\nQed.\n\nLemma v_l_tr:\n  forall (n:nat) (l: complex R) (v: 'rV[complex R]_n.+1),\n  l *: v^T = (l *: v)^T.\nProof.\nintros. apply matrixP. unfold eqrel. intros.\nby rewrite !mxE.\nQed.\n\n\nLemma right_eigen_vector_exists:\n  forall (n:nat) (i: 'I_n.+1) (A: 'M[complex R]_n.+1) (l : complex R),\n  @eigenvalue (complex_fieldType _) n.+1 A l ->  \n   exists v: 'cV_n.+1, (mulmx A v = l *: v) /\\ (v !=0).\nProof.\nintros.\nassert ( @eigenvalue (complex_fieldType _) n.+1 A^T l).\n{ by rewrite -eigen_val_mat_transpose. }\nassert (exists v : 'rV_(succn n),\n           v *m A^T = l *: v /\\ v != 0).\n{ assert (exists2 v : 'rV_n.+1, v *m A^T = l *: v & v != 0).\n  { by apply /eigenvalueP. } destruct H1. exists x. by split.\n} destruct H1 as [v H1].\nexists v^T. destruct H1.\nsplit.\n+ rewrite [in LHS]A_v_tr. rewrite v_l_tr. by rewrite H1.\n+ apply /cV0Pn.\n  assert (exists i, v 0 i != 0).\n  { by apply /rV0Pn. } destruct H3 as [k H3].\n  exists k. by rewrite mxE.\nQed.\n\n\n\n", "meta": {"author": "mohittkr", "repo": "iterative_convergence", "sha": "f60db20242e30236b3979bfda23248de4b9158d0", "save_path": "github-repos/coq/mohittkr-iterative_convergence", "path": "github-repos/coq/mohittkr-iterative_convergence/iterative_convergence-f60db20242e30236b3979bfda23248de4b9158d0/complex_mat_vec_prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6521552342437369}}
{"text": "Require Import prosa.util.epsilon.\nRequire Import prosa.util.tactics.\nRequire Import prosa.model.task.concept.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq path fintype bigop.\n\n(** * Reduction of the search space for Abstract RTA *)\n(** In this file, we prove that in order to calculate the worst-case response time \n    it is sufficient to consider only values of [A] that lie in the search space defined below. *)  \n\nSection AbstractRTAReduction. \n\n  (** The response-time analysis we are presenting in this series of documents is based on searching \n     over all possible values of [A], the relative arrival time of the job respective to the beginning \n     of the busy interval. However, to obtain a practically useful response-time bound, we need to \n     constrain the search space of values of [A]. In this section, we define an approach to \n     reduce the search space. *)\n  \n  Context {Task : TaskType}.\n  \n  (** First, we provide a constructive notion of equivalent functions. *)\n  Section EquivalentFunctions.\n    \n    (** Consider an arbitrary type [T]... *)\n    Context {T : eqType}.\n\n    (**  ...and two function from [nat] to [T]. *)\n    Variables f1 f2 : nat -> T.\n\n    (** Let [B] be an arbitrary constant. *) \n    Variable B : nat.\n    \n    (** Then we say that [f1] and [f2] are equivalent at values less than [B] iff\n       for any natural number [x] less than [B] [f1 x] is equal to [f2 x].  *)\n    Definition are_equivalent_at_values_less_than :=\n      forall x, x < B -> f1 x = f2 x.\n\n    (** And vice versa, we say that [f1] and [f2] are not equivalent at values \n       less than [B] iff there exists a natural number [x] less than [B] such\n       that [f1 x] is not equal to [f2 x].  *)\n    Definition are_not_equivalent_at_values_less_than :=\n      exists x, x < B /\\ f1 x <> f2 x.\n\n  End EquivalentFunctions. \n\n  (** Let [tsk] be any task that is to be analyzed *)\n  Variable tsk : Task.\n  \n  (** To ensure that the analysis procedure terminates, we assume an upper bound [B] on \n     the values of [A] that must be checked. The existence of [B] follows from the assumption \n     that the system is not overloaded (i.e., it has bounded utilization). *)\n  Variable B : duration.\n\n  (** Instead of searching for the maximum interference of each individual job, we \n     assume a per-task interference bound function [IBF(tsk, A, x)] that is parameterized \n     by the relative arrival time [A] of a potential job (see abstract_RTA.definitions.v file). *)\n  Variable interference_bound_function : Task -> duration -> duration -> duration.\n\n  (** Recall the definition of [ε], which defines the neighborhood of a point in the timeline.\n     Note that [ε = 1] under discrete time. *)\n  (** To ensure that the search converges more quickly, we only check values of [A] in the interval \n     <<[0, B)>> for which the interference bound function changes, i.e., every point [x] in which \n     [interference_bound_function (A - ε, x)] is not equal to [interference_bound_function (A, x)]. *)\n  Definition is_in_search_space A :=\n    A = 0 \\/\n    0 < A < B /\\ are_not_equivalent_at_values_less_than\n                  (interference_bound_function tsk (A - ε)) (interference_bound_function tsk A) B.\n  \n  (** In this section we prove that for every [A] there exists a smaller [A_sp] \n     in the search space such that [interference_bound_function(A_sp,x)] is \n     equal to [interference_bound_function(A, x)]. *)\n  Section ExistenceOfRepresentative.\n\n    (** Let [A] be any constant less than [B]. *) \n    Variable A : duration.\n    Hypothesis H_A_less_than_B : A < B.\n    \n    (** We prove that there exists a constant [A_sp] such that:\n       (a) [A_sp] is no greater than [A], (b) [interference_bound_function(A_sp, x)] is \n       equal to [interference_bound_function(A, x)] and (c) [A_sp] is in the search space.\n       In other words, either [A] is already inside the search space, or we can go \n       to the \"left\" until we reach [A_sp], which will be inside the search space. *)\n    Lemma representative_exists:\n      exists A_sp, \n        A_sp <= A /\\\n        are_equivalent_at_values_less_than (interference_bound_function tsk A)\n                                           (interference_bound_function tsk A_sp) B /\\\n        is_in_search_space A_sp.\n    Proof.\n      induction A as [|n].\n      - exists 0; repeat split.\n          by rewrite /is_in_search_space; left.\n      - have ALT:\n          all (fun t => interference_bound_function tsk n t == interference_bound_function tsk n.+1 t) (iota 0 B)\n          \\/ has (fun t => interference_bound_function tsk n t != interference_bound_function tsk n.+1 t) (iota 0 B).\n        { apply/orP.\n          rewrite -[_ || _]Bool.negb_involutive Bool.negb_orb.\n          apply/negP; intros CONTR.\n          move: CONTR => /andP [NALL /negP NHAS]; apply: NHAS.\n            by rewrite -has_predC /predC in NALL.\n        }\n        feed IHn; first by apply ltn_trans with n.+1. \n        move: IHn => [ASP [NEQ [EQ SP]]].\n        move: ALT => [/allP ALT| /hasP ALT].\n        { exists ASP; repeat split; try done.\n          { by apply leq_trans with n. }\n          { intros x LT.\n            move: (ALT x) => T. feed T; first by rewrite mem_iota; apply/andP; split. \n            move: T => /eqP T.\n              by rewrite -T EQ.\n          }\n        }\n        { exists n.+1; repeat split; try done.\n          rewrite /is_in_search_space; right.\n          split; first by  apply/andP; split.\n          move: ALT => [y IN N].\n          exists y.\n          move: IN; rewrite mem_iota add0n. move => /andP [_ LT]. \n          split; first by done.\n          rewrite subn1 -pred_Sn.\n          intros CONTR; move: N => /negP N; apply: N.\n            by rewrite CONTR.\n        }\n    Qed.\n\n  End ExistenceOfRepresentative.\n\n  (** In this section we prove that any solution of the response-time recurrence for\n     a given point [A_sp] in the search space also gives a solution for any point \n     A that shares the same interference bound. *)\n  Section FixpointSolutionForAnotherA.\n\n    (** Suppose [A_sp + F_sp] is a \"small\" solution (i.e. less than [B]) of the response-time recurrence. *)\n    Variables A_sp F_sp : duration.\n    Hypothesis H_less_than : A_sp + F_sp < B.\n    Hypothesis H_fixpoint : A_sp + F_sp = interference_bound_function tsk A_sp (A_sp + F_sp).\n\n    (** Next, let [A] be any point such that: (a) [A_sp <= A <= A_sp + F_sp] and \n       (b) [interference_bound_function(A, x)] is equal to \n       [interference_bound_function(A_sp, x)] for all [x] less than [B]. *)\n    Variable A : duration.\n    Hypothesis H_bounds_for_A : A_sp <= A <= A_sp + F_sp.\n    Hypothesis H_equivalent :\n      are_equivalent_at_values_less_than\n        (interference_bound_function tsk A)\n        (interference_bound_function tsk A_sp) B.\n\n    (** We prove that there exists a constant [F] such that [A + F] is equal to [A_sp + F_sp]\n       and [A + F] is a solution for the response-time recurrence for [A]. *)\n    Lemma solution_for_A_exists:\n      exists F,\n        A_sp + F_sp = A + F /\\\n        F <= F_sp /\\\n        A + F = interference_bound_function tsk A (A + F).\n    Proof.  \n      move: H_bounds_for_A => /andP [NEQ1 NEQ2].\n      set (X := A_sp + F_sp) in *.\n      exists (X - A); split; last split.\n      - by rewrite subnKC.\n      - by rewrite leq_subLR /X leq_add2r.\n      - by rewrite subnKC // H_equivalent.\n    Qed.\n\n  End FixpointSolutionForAnotherA.\n  \nEnd AbstractRTAReduction. ", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/analysis/abstract/search_space.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6521532864139747}}
{"text": "Require Import Relations.\nRequire Import Ensembles.\nRequire Import ClassicalFacts.\nRequire Import Classical_Prop.\nRequire Import Classical_Pred_Type.\nRequire Import ClassicalChoice.\n\nDefinition choice_cond :\n    forall (A B : Type) (R : A->B->Prop) (P : A -> Prop),\n   inhabited B ->\n   (forall x : A, P x -> exists y : B, R x y) ->\n    exists f : A->B, (forall x : A, P x -> R x (f x)).\nProof.\nintro.\nintro.\nintro.\nintro.\nintro Bin.\nintro.\napply (choice (fun (a : A) (b : B) => P a -> R a b)).\nintro.\nassert (H0 := H x).\ncase (classic (P x)).\nintro.\ndestruct (H0 H1).\nexists x0.\nintro.\ntrivial.\nintro.\ndestruct Bin.\nexists X.\nintro.\napply False_ind.\napply H1.\ntrivial.\nQed.\n\n(* connexity *)\nDefinition connex (A : Type) (R : relation A) (sub : Ensemble A) :=\n  (forall x y : A, sub x -> sub y -> R x y \\/ R y x).\n\n(* every nonempty subset has least element *)\nDefinition wellord (A : Type) (R : relation A) :=\n  forall e : Ensemble A, (exists a, e a) ->\n  (exists x, e x /\\ forall y, e y -> R x y).\n\nDefinition wellord_ens (A : Type) (R : relation A) (E : Ensemble A) :=\n  forall e : Ensemble A, Included _ e E -> (exists a, e a) ->\n  (exists x, e x /\\ forall y, e y -> R x y).\n\nDefinition transfinite_induction : forall\n  (A : Type)\n  (R : relation A)\n  (anti : antisymmetric A R)\n  (well : wellord A R)\n  (P : A -> Prop),\n  (forall (a : A), (forall (b : A), (R b a /\\ b <> a) -> P b) -> P a)\n  -> (forall c : A, P(c)).\nProof.\nintros.\nunfold antisymmetric in anti.\nassert (~ (exists t, ~(P t))).\nintro.\ndestruct H0.\nrename x into t.\nassert (well0 := well (fun x => ~(P x))).\nsimpl in well0.\nassert (exists x : A, ~ P x /\\ (forall y : A, ~ P y -> R x y)).\napply well0.\nexists t.\ntrivial.\ndestruct H1.\ndestruct H1.\napply H1.\napply H.\nintros.\ndestruct H3.\napply NNPP.\nintro.\nassert (H6 := H2 b H5).\napply H4.\napply anti.\ntrivial.\ntrivial.\nassert (H1 := not_ex_all_not _ _ H0).\napply NNPP.\napply H1.\nQed.\n\nDefinition Small (A : Type) (R : relation A)\n  (f : Ensemble A -> A) (sub : Ensemble A) :=\n    connex A R sub /\\\n    wellord_ens A R sub /\\\n    (forall x, sub x -> x = f (fun t => sub t /\\ R t x /\\ t <> x)).\n\nDefinition Big (A : Type) (R : relation A) (f : Ensemble A -> A) :=\n  (fun s => exists sub : Ensemble A, Small _ R f sub /\\ sub s).\n\nDefinition Seg (A : Type) (R : relation A)\n  (sub : Ensemble A) (x : A) :=\n    (fun t => sub t /\\ R t x /\\ t <> x).\n\nDefinition StrictUpperBoundFunc (A : Type) (R : relation A) (f : Ensemble A -> A) := \n  forall sub : Ensemble A,\n       connex A R sub ->\n       forall z : A, sub z -> R z (f sub) /\\ z <> f sub.\n\nDefinition small_combine : forall\n  (A : Type)\n  (R : relation A)\n  (Ord : order A R)\n  (f : Ensemble A -> A)\n  (bound : StrictUpperBoundFunc A R f)\n  (sub1 : Ensemble A)\n  (sub2 : Ensemble A)\n  (noteq : sub1 <> sub2)\n  (Hsub1 : Small A R f sub1)\n  (Hsub2 : Small A R f sub2),\n    (Included _ sub1 sub2 /\\ exists x, sub1 = Seg A R sub2 x) \\/ \n    (Included _ sub2 sub1 /\\ exists x, sub2 = Seg A R sub1 x).\nProof.\nintros.\nunfold Seg.\nunfold StrictUpperBoundFunc in bound.\nassert (refl := ord_refl A R Ord).\nassert (trans := ord_trans A R Ord).\nassert (anti := ord_antisym A R Ord).\nunfold reflexive in refl.\nunfold transitive in trans.\nunfold antisymmetric in anti.\ndestruct Hsub1.\ndestruct H0.\ndestruct Hsub2.\ndestruct H3.\nunfold connex in H, H2.\nunfold wellord_ens in H0, H3.\nrename H into Hcon1.\nrename H0 into Hweo1.\nrename H1 into Hboa1.\nrename H2 into Hcon2.\nrename H3 into Hweo2.\nrename H4 into Hboa2.\nassert (Hbob1 := bound _ Hcon1).\nassert (Hbob2 := bound _ Hcon2).\n\ncase (classic (Included A sub1 sub2)).\nintro.\n\nleft.\nsplit.\ntrivial.\nunfold Included in *.\nunfold In in *.\nassert (let e := (fun t => (~ sub1 t) /\\ sub2 t)\n  in exists x : A, e x /\\\n  (forall y : A, e y -> R x y)).\napply Hweo2.\nintros.\ndestruct H0.\ntrivial.\napply NNPP.\nintro.\nassert (H1 := not_ex_all_not _ _ H0).\nsimpl in H1.\nassert (sub1 = sub2).\napply Extensionality_Ensembles.\nsplit.\nintro.\nintro.\napply H.\ntrivial.\nintro.\nintro.\nassert (H3 := not_and_or _ _ (H1 x)).\ncase H3.\nintro.\napply NNPP.\ntrivial.\nintro.\ncontradiction.\ncontradiction.\n\nsimpl in H0.\ndestruct H0.\ndestruct H0.\ndestruct H0.\n\nrename x into rem.\nrename H0 into Hrem0.\nrename H2 into Hrem2.\nrename H1 into Hrem1.\n\nassert (forall x y,\n  sub1 x ->\n  ~ sub1 y ->\n  sub2 y ->\n  R x y).\nintros.\nassert (H3 := H _ H0).\nassert (R x rem).\n\nAdmitted.\n\nDefinition small_big : forall\n  (A : Type)\n  (R : relation A)\n  (Ord : order A R)\n  (f : Ensemble A -> A)\n  (bound : StrictUpperBoundFunc A R f),\n    Small A R f (Big A R f).\nAdmitted.\n\n(*\nassert (connex A R (Big A R f)).\nunfold connex.\nunfold Big.\nintros.\ndestruct H.\ndestruct H0.\ndestruct H.\ndestruct H0.\nrename x0 into subx.\nrename x1 into suby.\nassert (SC := small_combine A R Ord f Hfun subx suby H H0).\ncase SC.\nintro.\ndestruct H3.\ndestruct H4.\ndestruct H0.\napply H0.\napply H3.\ntrivial.\ntrivial.\nintro.\ndestruct H3.\ndestruct H4.\ndestruct H.\napply H.\ntrivial.\napply H3.\ntrivial.\n*)\n\nDefinition zorn : forall\n  (A : Type)\n  (R : relation A)\n  (Ord : order A R),\n    (forall sub : Ensemble A,\n      (connex A R sub ->\n       (exists x, forall y, sub y -> R y x)))\n    -> exists x, ~ (exists y, R x y /\\ x <> y).\nProof.\nintro.\nintro.\nintro.\nassert (refl := ord_refl A R Ord).\nassert (trans := ord_trans A R Ord).\nassert (anti := ord_antisym A R Ord).\nunfold reflexive in refl.\nunfold transitive in trans.\nunfold antisymmetric in anti.\nintro.\n\n(* proof of inhabited A *)\nunfold connex in H.\nassert (exists x : A, forall y : A, False -> R y x).\napply H.\nintros.\napply False_ind.\ntrivial.\ndestruct H0.\nclear H0.\nrename x into inh.\nrename H into Hsub.\n\n(* change goal and hypothesis *)\napply NNPP.\nintro.\nassert (H0 := not_ex_all_not _ _ H).\nsimpl in H0.\nassert (forall n : A, exists y : A, R n y /\\ n <> y).\nintro.\napply NNPP.\napply (H0 n).\nclear H.\nclear H0.\nrename H1 into Hex.\n\n(* find some excluded and larger element for all subsets *)\nassert (forall sub : Ensemble A,\n  connex A R sub ->\n  exists g : A, forall z : A, sub z -> R z g /\\ z <> g).\nintros.\nassert (H1 := Hsub sub H).\ndestruct H1.\nassert (H1 := Hex x).\ndestruct H1.\ndestruct H1.\nexists x0.\nintros.\nsplit.\napply (trans _ x _).\napply H0.\ntrivial.\ntrivial.\nintro.\napply H2.\napply anti.\ntrivial.\napply H0.\nrewrite <- H4.\ntrivial.\nrename H into Hgre.\nclear Hsub.\n\n(* apply axiom of choice *)\nassert (exists f : (Ensemble A)->A, StrictUpperBoundFunc A R f).\napply (choice_cond (Ensemble A) A (fun (sub : Ensemble A) (x : A) =>\n  forall z : A, sub z -> R z x /\\ z <> x)).\nexists.\ntrivial.\nintros.\nrename H into Hchn.\napply (Hgre x).\ntrivial.\ndestruct H.\nrename H into Hfun.\nrename x into f.\nclear Hgre.\nclear Hex.\n\n(* create some big ensemble and use\n   it to get a contradiction *)\n\n(* First, prove Big is connex. *)\nassert (H := small_big A R Ord f Hfun).\ndestruct H.\ndestruct H0.\nrename H into Hcon.\nrename H0 into Hwel.\nrename H1 into Hbon.\nassert (Hdec := Hfun (Big A R f) Hcon).\n\n(* Second, proof Big (f Big) *)\n\n(* connex *)\nassert (Big A R f (f (Big A R f))).\nunfold Big.\nexists (fun t => Big A R f t \\/ t = f (Big A R f)).\nsplit.\nsplit.\nintro.\nintros.\ncase H.\ncase H0.\nintros.\napply Hcon.\ntrivial.\ntrivial.\nintros.\nleft.\nrewrite H1.\nassert (H3 := Hdec x H2).\ndestruct H3.\ntrivial.\nintro.\ncase H0.\nintro.\nright.\nrewrite H1.\nassert (H3 := Hdec y H2).\ndestruct H3.\ntrivial.\nintro.\nleft.\nrewrite H1.\nrewrite H2.\napply refl.\n\n(* wellord *)\nsplit.\nintro.\nintros.\nunfold Included in H.\nunfold In in H.\ncase (classic (exists t, e t /\\ Big A R f t)).\nintro.\nassert (exists x : A, (e x /\\ Big A R f x) /\\\n  (forall y : A, e y /\\ Big A R f y -> R x y)).\napply (Hwel).\nintro.\nintro.\ndestruct H2.\ntrivial.\ntrivial.\ndestruct H2.\ndestruct H2.\ndestruct H2.\nexists x.\nsplit.\ntrivial.\nintros.\nassert (H6 := H y H5).\ncase H6.\nintro.\napply H3.\nsplit.\ntrivial.\ntrivial.\nintro.\nassert (H8 := Hdec _ H4).\ndestruct H8.\nrewrite H7.\ntrivial.\n\nintro.\nassert (forall t, e t -> t = f (Big A R f)).\nintros.\nassert (H3 := not_ex_all_not _ _ H1).\nassert (H4 := not_and_or _ _ (H3 t)).\ncase H4.\nintro.\ncontradiction.\nintro.\nassert (H6 := H t H2).\ncase H6.\nintro.\ncontradiction.\nintro.\nauto.\ndestruct H0.\nexists x.\nsplit.\ntrivial.\nintros.\nrewrite (H2 _ H0).\nrewrite (H2 _ H3).\nauto.\n\n(* bound condition *)\nintros.\ncase H.\nintro.\nassert (H1 := Hbon x H0).\nrewrite H1 at 1.\napply f_equal.\napply Extensionality_Ensembles.\nsplit.\nintro.\nintro.\ndestruct H2.\ndestruct H3.\nsplit.\nleft.\ntrivial.\nsplit.\ntrivial.\ntrivial.\n\nintro.\nintro.\ndestruct H2.\ndestruct H3.\nsplit.\nassert (H5 := Hdec _ H0).\ndestruct H5.\nassert (x0 <> f (Big A R f)).\nintro.\nrewrite H7 in H4.\nrewrite H7 in H3.\napply H6.\napply anti.\ntrivial.\ntrivial.\ncase H2.\nintro.\ntrivial.\nintro.\ncontradiction.\nsplit.\ntrivial.\ntrivial.\n\nintros.\nrewrite H0.\napply f_equal.\napply Extensionality_Ensembles.\nsplit.\nintro.\nintro.\nsplit.\nleft.\ntrivial.\napply Hdec.\ntrivial.\nintro.\nintro.\ndestruct H1.\ndestruct H2.\ncase H1.\nintro.\ntrivial.\nintro.\ncontradiction.\nright.\nreflexivity.\n\n(* make a contradiction *)\nassert (H0 := Hdec _ H).\ndestruct H0.\ncontradiction.\nQed.", "meta": {"author": "aidatorajiro", "repo": "WorksOfProof", "sha": "e65dd026f5e700ce37ca5ffab86e863616af8641", "save_path": "github-repos/coq/aidatorajiro-WorksOfProof", "path": "github-repos/coq/aidatorajiro-WorksOfProof/WorksOfProof-e65dd026f5e700ce37ca5ffab86e863616af8641/zorn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6521532791756827}}
{"text": "Module NinetyNine.\n\n  (*\n   *  H-99: Ninety-Nine Haskell Problems\n   *\n   *  An Attempt in Coq\n   *  Pascal Sommer, Feb. 2018\n   *\n   *  https://wiki.haskell.org/H-99:_Ninety-Nine_Haskell_Problems\n   *)\n\n\n  Require Import Coq.Arith.Plus.\n  Require Import Coq.Arith.Arith.\n  Require Import Coq.Arith.EqNat.\n\n  \n  (* \n   *  Some datatypes, because we're cool like that\n   *  and don't just use the standard library for\n   *  everything. (this might be a big mistake)\n   *)\n  \n  Inductive maybe (X : Type) :=\n  | nothing : maybe X\n  | just : X -> maybe X.\n\n  Arguments nothing {X}.\n  Arguments just {X} _.\n  \n  Inductive list (X : Type) :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\n  Arguments nil {X}.\n  Arguments cons {X} _ _.\n\n  Notation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) .. ).\n  Notation \"[ ]\" := nil.\n  Notation \"x :: xs\" := (cons x xs).\n\n  Fixpoint beq_natlist (a b : list nat) : bool :=\n    match a, b with\n    | nil, nil => true\n    | x::xs, y::ys => andb (beq_nat x y) (beq_natlist xs ys)\n    | _, _ => false\n    end.\n\n  Theorem beq_natlist_refl :\n    forall l : list nat,\n      beq_natlist l l = true.\n  Proof.\n    induction l.\n    - reflexivity.\n    - simpl.\n      rewrite <- beq_nat_refl.\n      rewrite -> IHl.\n      reflexivity.\n  Qed.\n  \n                          \n  (*\n   *  ######## Problem 1\n   *)\n  \n  Fixpoint myLast {X : Type} (l : list X) : maybe X :=\n    match l with\n    | [] => nothing\n    | [x] => just x\n    | x::xs => myLast xs\n    end.\n\n  Example ex_myLast_1 :\n    myLast [1;2;3;4] = just 4.\n  Proof. reflexivity. Qed.\n\n  Example ex_myLast_2 :\n    myLast [] = @nothing nat.\n  Proof. reflexivity. Qed.\n\n\n  (*\n   *  ######## Problem 2\n   *)\n\n  Fixpoint myButLast {X : Type} (l : list X) : maybe X :=\n    match l with\n    | [] => nothing\n    | [x] => nothing\n    | [x;y] => just x\n    | x::xs => myButLast xs\n    end.\n\n  Example ex_myButLast_1 :\n    myButLast [1;2;3;4] = just 3.\n  Proof. reflexivity. Qed.\n\n  Example ex_myButLast_2 :\n    myButLast [1] = nothing.\n  Proof. reflexivity. Qed.\n\n\n  (*\n   *  ######## Problem 3\n   *)\n\n  Fixpoint elementAt {X : Type} (l : list X) (n : nat) : maybe X :=\n    match n, l with\n    | _, [] => nothing\n    | 0, x::_ => just x\n    | S n', _::xs => elementAt xs n'\n    end.\n\n  Example ex_elementAt_1 :\n    elementAt [1;2;3;4] 2 = just 3.\n  Proof. reflexivity. Qed.\n\n  Example ex_elementAt_2 :\n    elementAt [1;2;3] 3 = nothing.\n  Proof. reflexivity. Qed.\n\n\n  (*\n   *  Problem 4\n   *)\n\n  Fixpoint myLength {X : Type} (l : list X) : nat :=\n    match l with\n    | nil => 0\n    | x::xs => S (myLength xs)\n    end.\n\n  Example ex_myLength_1 :\n    myLength [1;2;3] = 3.\n  Proof. reflexivity. Qed.\n\n  Example ex_myLength_2 :\n    myLength (@nil nat) = 0.\n  Proof. reflexivity. Qed.\n\n  Theorem cons_increases_length :\n    forall (l : list nat) (n : nat),\n      myLength (n :: l) = S (myLength l).\n  Proof. reflexivity. Qed.\n\n  Print myLength.\n  \n\n  (*\n   *  ######## Problem 5\n   *\n   *  It would be possible to define list reversion without\n   *  append in linear time, but then it's a lot harder to\n   *  prove that the length is preserved.\n   *)\n  \n  Fixpoint append {X : Type} (a b : list X) : list X :=\n    match a with\n    | nil => b\n    | x::xs => x :: (append xs b)\n    end.\n\n  Notation \"a ++ b\" := (append a b).\n\n  Theorem append_preserves_length :\n    forall (a b : list nat),\n      myLength (a ++ b) = myLength a + myLength b.\n  Proof.\n    induction a.\n    - reflexivity.\n    - simpl. intros b.\n      rewrite IHa.\n      reflexivity.\n  Qed.\n\n  Theorem append_neutral_l :\n    forall (X : Type) (a : list X),\n      a = [] ++ a.\n  Proof. reflexivity. Qed.\n\n  Theorem append_neutral_r :\n    forall (X : Type) (a : list X),\n      a = a ++ [].\n  Proof.\n    induction a.\n    - reflexivity.\n    - simpl. rewrite <- IHa.\n      reflexivity.\n  Qed.\n\n  Theorem append_assoc :\n    forall (X : Type) (a b c : list X),\n      a ++ (b ++ c) = (a ++ b) ++ c.\n  Proof.\n    intros X a b c.\n    induction a.\n    - reflexivity.\n    - simpl. rewrite <- IHa.\n      reflexivity.\n  Qed.\n\n  \n  Fixpoint myReverse {X : Type} (l : list X) : list X :=\n    match l with\n    | nil => nil\n    | x :: xs => (myReverse xs) ++ [x]\n    end.\n\n  Example ex_myReverse_1 :\n    myReverse [] = @nil nat.\n  Proof. reflexivity. Qed.\n\n  Theorem reverse_preserves_length :\n    forall (l : list nat),\n      myLength l = myLength (myReverse l).\n  Proof.\n    induction l.\n    - reflexivity.\n    - simpl.\n      rewrite -> append_preserves_length.\n      rewrite <- IHl.      \n      rewrite plus_comm.\n      reflexivity.\n  Qed.\n\n  Theorem reverse_append :\n    forall (X : Type) (a b : list X),\n      myReverse (a ++ b) = myReverse b ++ myReverse a.\n  Proof.\n    induction a.\n    - simpl. intros b. rewrite <- append_neutral_r.\n      reflexivity.\n    - simpl. intros b. rewrite IHa, append_assoc.\n      reflexivity.\n  Qed.\n\n  Theorem reverse_involution :\n    forall (X : Type) (l : list X),\n      myReverse (myReverse l) = l.\n  Proof.\n    induction l.\n    - reflexivity.\n    - simpl. rewrite reverse_append, IHl.\n      reflexivity.\n  Qed.\n  \n\n  (*\n   *  ######## Problem 6\n   *)\n  \n  Definition isPalindrome (l : list nat) : bool :=\n    beq_natlist (myReverse l) l.\n\n  Example ex_isPalindrome_1 :\n    isPalindrome [1;2;3;2;1] = true.\n  Proof. reflexivity. Qed.\n\n  Theorem rev_append_is_palindrome :\n    forall l : list nat,\n      isPalindrome (l ++ myReverse l) = true.\n  Proof.\n    induction l.\n    - reflexivity.\n    - simpl.\n      \n  \nEnd NinetyNine.", "meta": {"author": "Pascal-So", "repo": "h-99-coq", "sha": "c24bad82fe726aa1c2bdf85a73acae3658b9d863", "save_path": "github-repos/coq/Pascal-So-h-99-coq", "path": "github-repos/coq/Pascal-So-h-99-coq/h-99-coq-c24bad82fe726aa1c2bdf85a73acae3658b9d863/99.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.8705972650509008, "lm_q1q2_score": 0.6521532790222831}}
{"text": "Require Import A1_Plan A2_Orientation A4_Droite A5_Cercle A7_Tactics .\nRequire Import C1_Distance.\n\nSection CIRCLE_AND_DISTANCE.\n\nDefinition Radius := fun c : Circle => let (_, A, B) := c in Distance A B.\n\nDefinition OnCircle (c : Circle) := let (C, A, B) := c in (fun M : Point => Distance C M = Distance A B).\n\nLemma OnCircle1OnCircle : forall c : Circle, forall M : Point,\n\tOnCircle1 c M -> OnCircle c M.\nProof.\n\tunfold OnCircle1, OnCircle in |- *; destruct c; simpl in |- *; intros.\n\tapply DistanceEq; trivial.\nQed.\n\nLemma OnCircleOnCircle1 : forall c : Circle, forall M : Point,\n\tOnCircle c M -> OnCircle1 c M.\nProof.\n\tunfold OnCircle1, OnCircle in |- *; destruct c; simpl in |- *; intros.\n\tapply EqDistance; trivial.\nQed.\n\nLemma InterDiameterPointDef : forall (l : Line) (c : Circle),\n\tDiameter l c ->\n\tlet f := (fun M : Point => OnCircle c M /\\ EquiOriented (Center c) M (LineA l) (LineB l)) in\n\t{M : Point |  f M /\\ Unicity M f}.\nProof.\n\tintros.\n\tsetInterDiameter1 l c ipattern:(P).\n\t exists P; unfold f in |- *; simpl in |- *; intuition.\n\t  apply OnCircle1OnCircle; trivial.\n\t  unfold Unicity in *; intuition.\n\t    apply Hun; intuition.\n\t    apply OnCircleOnCircle1; trivial.\nDefined.\n\nEnd CIRCLE_AND_DISTANCE.\n", "meta": {"author": "coq-contribs", "repo": "euclidean-geometry", "sha": "06838851a5924918d98e5a9c07ffa84021e13af7", "save_path": "github-repos/coq/coq-contribs-euclidean-geometry", "path": "github-repos/coq/coq-contribs-euclidean-geometry/euclidean-geometry-06838851a5924918d98e5a9c07ffa84021e13af7/C2_CircleAndDistance.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6521126841291252}}
{"text": "Require Import QuickSort.\nRequire Import Prelude.\nRequire Import HsToCoq.DeferredFix.\n\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nInductive AlreadySorted {a} `{Ord a} : list a -> Prop :=\n | ASNil: AlreadySorted []\n | ASCons: forall x xs,\n     AlreadySorted xs -> \n     Forall (fun y => (op_zl__ y x) = false) xs ->\n     AlreadySorted (x::xs).\n\nAxiom unroll_deferred_fix: forall a r `{Default r} (f : (a -> r) -> (a -> r)),\n  deferredFix1 f = f (deferredFix1 f).\n\n\nLemma Forall_partition:\n  forall a p (xs : list a),\n  Forall (fun y => (p y) = false) xs ->\n  OldList.partition p xs = ([], xs).\nProof.\n  intros.\n  induction H.\n  * reflexivity.\n  * unfold OldList.partition in *.\n    simpl in *. rewrite IHForall.\n    unfold OldList.select.\n    rewrite H. reflexivity.\nQed.\n\n\nTheorem quicksort_already_sorted:\n  forall a `(Ord a) (xs : list a),\n  AlreadySorted xs -> quicksort xs = xs.\nProof.\n  intros.\n  induction H1.\n  * unfold quicksort.\n    rewrite unroll_deferred_fix. reflexivity.\n  * change (quicksort (x :: xs) = [] ++ [x] ++ xs).\n    unfold quicksort.\n    rewrite unroll_deferred_fix.\n    rewrite Forall_partition by assumption.\n    f_equal;[|f_equal].\n    + rewrite unroll_deferred_fix. reflexivity.\n    + apply IHAlreadySorted.\nQed.\n\nRequire Import Coq.Sorting.Permutation.\n\nLemma partition_permutation:\n  forall a p (xs ys zs : list a),\n  OldList.partition p xs = (ys, zs) ->\n  Permutation xs (ys ++ zs).\nProof.\n  induction xs; intros.\n  * simpl in *. inversion_clear H. constructor.\n  * simpl in *. unfold OldList.select in *.\n    destruct (p a0).\n    - destruct (OldList.partition p xs) eqn:?.\n      inversion H.\n      apply Permutation_cons; [reflexivity|].\n      apply IHxs.\n      congruence.\n    - destruct (OldList.partition p xs) eqn:?.\n      inversion H.\n      apply Permutation_cons_app.\n      apply IHxs.\n      congruence.\nQed.\n\n\nLemma Forall_partition_l:\n  forall a p (xs ys zs : list a),\n  OldList.partition p xs = (ys, zs) ->\n  Forall (fun y => (p y) = true) ys.\nProof.\n  induction xs; intros.\n  * simpl in H. inversion H. auto.\n  * simpl in *. unfold OldList.select in *.\n    destruct (p a0) eqn:?.\n    - destruct (OldList.partition p xs) eqn:?.\n      inversion H. simpl.\n      constructor; try assumption.\n      apply (IHxs l zs).\n      congruence.\n    - destruct (OldList.partition p xs) eqn:?.\n      inversion H. simpl.\n      destruct zs. try congruence.\n      apply (IHxs ys zs).\n      congruence.\nQed.\n\n\nLemma Forall_partition_r:\n  forall a p (xs ys zs : list a),\n  OldList.partition p xs = (ys, zs) ->\n  Forall (fun y => (p y) = false) zs.\nProof.\n  induction xs; intros.\n  * simpl in H. inversion H. auto.\n  * simpl in *. unfold OldList.select in *.\n    destruct (p a0) eqn:?.\n    - destruct (OldList.partition p xs) eqn:?.\n      inversion H. simpl.\n      destruct ys. try congruence.\n      apply (IHxs ys zs).\n      congruence.\n    - destruct (OldList.partition p xs) eqn:?.\n      inversion H. simpl.\n      constructor; try assumption.\n      apply (IHxs ys l0).\n      congruence.\nQed.\n\nLemma partition_length_l:\n  forall a p (xs ys zs : list a),\n  OldList.partition p xs = (ys, zs) ->\n  Peano.le (length ys) (length xs).\nProof.\n  induction xs; intros.\n  * simpl in *. inversion_clear H. constructor.\n  * simpl in *. unfold OldList.select in *.\n    destruct (p a0).\n    - destruct (OldList.partition p xs) eqn:?.\n      inversion H.\n      simpl.\n      apply le_n_S.\n      apply (IHxs l zs).\n      congruence.\n    - destruct (OldList.partition p xs) eqn:?.\n      inversion H.\n      destruct zs. try congruence.\n      inversion H2.\n      simpl.\n      rewrite (IHxs ys zs).\n      omega.\n      congruence.\nQed.\n\n\nLemma partition_length_r:\n  forall a p (xs ys zs : list a),\n  OldList.partition p xs = (ys, zs) ->\n  Peano.le (length zs) (length xs).\nProof.\n  induction xs; intros.\n  * simpl in *. inversion_clear H. constructor.\n  * simpl in *. unfold OldList.select in *.\n    destruct (p a0).\n    - destruct (OldList.partition p xs) eqn:?.\n      inversion H.\n      destruct ys. try congruence.\n      inversion H2.\n      simpl.\n      rewrite (IHxs ys zs).\n      omega.\n      congruence.\n    - destruct (OldList.partition p xs) eqn:?.\n      inversion H.\n      simpl.\n      apply le_n_S.\n      apply (IHxs ys l0).\n      congruence.\nQed.\n\n\nTheorem quicksort_permutation:\n  forall a `(Ord a) (xs : list a),\n  Permutation  (quicksort xs) xs.\nProof.\n  intros.\n  remember (length xs) as n.\n  generalize dependent xs.\n  induction n using lt_wf_ind.\n  intros.\n  unfold quicksort.\n  rewrite unroll_deferred_fix.\n  destruct xs.\n  * apply perm_nil.\n  * destruct (OldList.partition (fun arg_1__ : a => _<_ arg_1__ a0) xs) eqn:?.\n    simpl app.\n    rewrite <- Permutation_middle.\n    apply Permutation_cons; [reflexivity|].\n    rewrite (partition_permutation _ _ _ _ _ Heqp).\n    apply Permutation_app.\n    - apply (H1 (length l)).\n      + pose (partition_length_l _ _ _ _ _  Heqp).\n        subst n. simpl.\n        omega.\n      + reflexivity.\n    - apply (H1 (length l0)).\n      + pose (partition_length_r _ _ _ _ _  Heqp).\n        subst n. simpl.\n        omega.\n      + reflexivity.\nQed.\n\nRequire Import Coq.Sorting.Sorted.\nRequire Import Coq.Sets.Relations_1.\nRequire Import Coq.Lists.List.\n\nLemma Forall_app:\n  forall a P (xs ys : list a),\n  Forall P xs -> Forall P ys ->\n  Forall P (xs ++ ys).\nProof.\n  intros. induction xs; try assumption. constructor.\n  inversion H; assumption.\n  apply IHxs. inversion H; assumption.\nQed.\n\nLemma Forall_Permutation:\n  forall a P (xs ys : list a),\n  Forall P ys -> Permutation xs ys ->\n  Forall P xs.\nProof.\n  intros.\n  induction H0.\n  * auto.\n  * constructor.\n    + inversion_clear H. assumption.\n    + apply IHPermutation. inversion_clear H. assumption.\n  * inversion_clear H. inversion_clear H1.\n    repeat (constructor; try assumption).\n  * auto.\nQed.\n\nSection sorted.\n Variable a : Type.\n Variable eq : Eq_ a.\n Variable ord : Ord a.\n \n Definition R x y := x < y = true.\n\n Variable trans : Transitive R.\n Variable total : forall a b, R a b \\/ R b a.\n\nLemma StronglySorted_app_cons:\n  forall (xs ys : list a) p,\n  StronglySorted R xs ->\n  StronglySorted R ys ->\n  Forall (fun x => R x p) xs ->\n  Forall (fun y => R p y) ys ->\n  StronglySorted R (xs ++ p :: ys).\nProof.\n  intros.\n  induction xs.\n  * simpl.\n    apply SSorted_cons.\n    - assumption.\n    - assumption.\n  * simpl. apply SSorted_cons.\n    - apply IHxs.\n      + inversion H; assumption.\n      + inversion H1; assumption.\n    - apply Forall_app.\n      inversion_clear H; assumption.\n      constructor.\n      inversion_clear H1; assumption.\n      refine (Forall_impl _ _ H2). intros.\n      refine (trans _ _ _ _ H3).\n      inversion_clear H1; assumption.\nQed.\n\nTheorem quicksort_sorted:\n  forall (xs : list a), StronglySorted R (quicksort xs).\nProof.\n  intros.\n  remember (length xs) as n.\n  generalize dependent xs.\n  induction n using lt_wf_ind.\n  intros.\n  unfold quicksort.\n  rewrite unroll_deferred_fix.\n  destruct xs.\n  * apply SSorted_nil.\n  * destruct (OldList.partition (fun arg_1__ : a => _<_ arg_1__ a0) xs) eqn:?.\n    simpl app.\n    apply StronglySorted_app_cons.\n    - apply (H (length l)).\n      + pose (partition_length_l _ _ _ _ _  Heqp).\n        subst n. simpl.\n        omega.\n      + reflexivity.\n    - apply (H (length l0)).\n      + pose (partition_length_r _ _ _ _ _  Heqp).\n        subst n. simpl.\n        omega.\n      + reflexivity.\n    - refine (Forall_Permutation _ _ _ _ _ (quicksort_permutation _ _ _)).\n      apply (Forall_partition_l _ _ _ _ _  Heqp).\n    - refine (Forall_Permutation _ _ _ _ _ (quicksort_permutation _ _ _)).\n      specialize (Forall_partition_r _ _ _ _ _  Heqp).\n      apply Forall_impl.\n      intros.\n      destruct (total a0 a1); [assumption|congruence].\nQed.\nEnd sorted.\n\nPrint Assumptions quicksort_sorted.\n", "meta": {"author": "plclub", "repo": "hs-to-coq", "sha": "e6401f6f054a2c1ff5e63a17ab8af2bcd5861c9c", "save_path": "github-repos/coq/plclub-hs-to-coq", "path": "github-repos/coq/plclub-hs-to-coq/hs-to-coq-e6401f6f054a2c1ff5e63a17ab8af2bcd5861c9c/examples/quicksort/Proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6521126722232548}}
{"text": "Require Import Classical.\n\nParameters P Q R S: Prop.\n\nSection example0.\n\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\n\n", "meta": {"author": "bodri5", "repo": "logic22", "sha": "b627d281715c0b947b48d91fc61d01e238720e00", "save_path": "github-repos/coq/bodri5-logic22", "path": "github-repos/coq/bodri5-logic22/logic22-b627d281715c0b947b48d91fc61d01e238720e00/example0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6521126717651626}}
{"text": "subset_transitive < Undo 2.\n1 subgoal\n  \n  ============================\n   forall x y z : set, subset x y -> subset y z -> subset x z\n\nsubset_transitive < unfold subset at 2.\n1 subgoal\n  \n  ============================\n   forall x y z : set,\n   subset x y -> (forall x0 : U, element x0 y -> element x0 z) -> subset x z\n\nsubset_transitive < intros.\n1 subgoal\n  \n  x : set\n  y : set\n  z : set\n  H : subset x y\n  H0 : forall x0 : U, element x0 y -> element x0 z\n  ============================\n   subset x z\n\nsubset_transitive < unfold subset in H.\n1 subgoal\n  \n  x : set\n  y : set\n  z : set\n  H : forall x0 : U, element x0 x -> element x0 y\n  H0 : forall x0 : U, element x0 y -> element x0 z\n  ============================\n   subset x z\n\nsubset_transitive < red.\n1 subgoal\n  \n  x : set\n  y : set\n  z : set\n  H : forall x0 : U, element x0 x -> element x0 y\n  H0 : forall x0 : U, element x0 y -> element x0 z\n  ============================\n   forall x0 : U, element x0 x -> element x0 z\n\nsubset_transitive < auto.\nNo more subgoals.\n\nsubset_transitive < Qed.\nunfold transitive.\nunfold subset at 2.\nintros.\nunfold subset in H.\nred.\nauto.\n\nsubset_transitive is defined\n\nCoq < \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/001chapt/proof12.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6520830984468907}}
{"text": "Require Export ZArith.\n(*Require Export Bmc.Logic.*)\n\nOpen Scope nat_scope.\n\nSet Implicit Arguments.\n\n(**)\n\nDefinition state : Type := Z.\nDefinition sseq : Type := nat -> state.\n\nDefinition nth (n : nat) (ss : sseq) : state :=\n  ss n.\n\nNotation \"ss .[ n ] \" := (nth n ss)\n                         (at level 0).\n\nDefinition skipn (n : nat) (ss : sseq) : sseq :=\n  fun i => ss (i+n).\n\nLemma skipn_nth: forall (ss : sseq) (n m : nat),\n  (skipn n ss).[m] = ss.[n+m].\nProof.\n  intros.\n  unfold skipn.\n  rewrite plus_comm.\n  reflexivity.\nQed.\n\nLemma state_sseq :\n  forall (s:state), (fun _ => s).[0] = s.\nProof.\n  intros. unfold nth. reflexivity.\nQed.\n\nLemma prop_state_sseq :\n  forall (p : state -> Prop),\n    (forall (ss:sseq), p ss.[0]) ->\n    (forall (s:state), p s).\nProof.\n  intros.\n  rewrite <- state_sseq. apply H.\nQed.\n\n(**)\n\nDefinition trans : Type := state -> state -> Prop.\nDefinition prop : Type := state -> Prop.\n\nFixpoint path (T : trans) (ss : sseq) (o len : nat) : Prop :=\n  match len with\n  | O => True\n  | S len' => path T ss o len' /\\ T ss.[o+len'] ss.[o+len]\n  end.\n\nFixpoint invariance (P : prop) (ss : sseq) (len : nat) : Prop :=\n  match len with\n  | O => P ss.[0]\n  | S len' => invariance P ss len' /\\ P ss.[len]\n  end.\n\nFixpoint no_loop' (ss : sseq) (o m n : nat) : Prop :=\n  match n with\n  | O => ss.[o+m] <> ss.[o]\n  | S n' => no_loop' ss o m n' /\\ ss.[o+m] <> ss.[o+n]\n  end.\n\nFixpoint no_loop (ss : sseq) (o k : nat) : Prop :=\n  match k with\n  | O => True\n  | S k' => no_loop' ss o k k' /\\ no_loop ss o k'\n  end.\n\nDefinition loop (ss : sseq) (o m n : nat) : Prop :=\n  exists i, i <= n /\\ ss.[o+m] = ss.[o+i].\n\nDefinition loop_free (T : trans) (ss : sseq) (o k: nat) : Prop :=\n  path T ss o k /\\ no_loop ss o k.\n\nDefinition lasso_fwd (I : prop) (T : trans) (k : nat) : Prop :=\n  forall ss : sseq,\n  I ss.[0] -> ~loop_free T ss 0 k.\n\nDefinition lasso_bwd (T : trans) (P : prop) (k: nat) : Prop :=\n  forall ss : sseq,\n  loop_free T ss 0 k -> P ss.[k].\n\nDefinition lasso_bwd' (T : trans) (P : prop) (k: nat) : Prop :=\n  forall ss : sseq,\n  ~P ss.[k] -> ~loop_free T ss 0 k.\n\nDefinition prop_nth_init (I : prop) (T : trans) (P : prop) (n : nat) : Prop :=\n  forall ss : sseq,\n  I ss.[0] -> path T ss 0 n -> P ss.[n].\n\nFixpoint safety_nth (I : prop) (T : trans) (P : prop) (n : nat) : Prop :=\n  match n with\n  | O => prop_nth_init I T P n\n  | S n' => safety_nth I T P n' /\\ prop_nth_init I T P n\n  end.\n\nDefinition prop_nth_init_lf  (I : prop) (T : trans) (P : prop) (n : nat) : Prop :=\n  forall ss : sseq,\n  I ss.[0] -> loop_free T ss 0 n -> P ss.[n].\n\nFixpoint safety_nth_offset (P : prop) (ss : sseq) (o n: nat) : Prop :=\n  match n with\n  | O => True\n  | S n' => safety_nth_offset P ss o n' /\\ P ss.[o+n']\n  end.\n\n(**)\n\nLemma safety_path_lf :\n  forall (I:prop) (T:trans) (P:prop),\n  forall (i:nat),\n    prop_nth_init I T P i ->\n    prop_nth_init_lf I T P i.\nProof.\n  intros.\n  unfold prop_nth_init in H.\n  unfold prop_nth_init_lf.\n  unfold loop_free.\n  intros.\n  destruct H1.\n  apply H.\n  apply H0.\n  apply H1.\nQed.\n\nLemma bounded_safety : \n  forall (i k : nat) (I : prop) (T : trans) (P : prop),\n  i <= k -> safety_nth I T P k -> prop_nth_init I T P i.\nProof.\n  intros.\n  apply Nat.lt_eq_cases in H. \n  destruct H.\n  - induction k.\n    + easy.\n    + destruct (Nat.lt_ge_cases i k).\n      * assert (H2 : safety_nth I T P k /\\ prop_nth_init I T P k).\n        destruct k; firstorder; now rewrite <- plus_n_O in H0.\n        apply IHk.\n        auto.\n        tauto.\n      * apply gt_S_le in H.\n        assert (H2 : i = k) by omega.\n        destruct k ;rewrite H2; firstorder.\n  - subst.\n    destruct k; firstorder.\nQed.\n\n(**)\n\nLemma skipn_path : forall (T : trans) (i j : nat),\n  forall ss : sseq,\n  path T ss j i  -> path T (skipn j ss) 0 i.\nProof.\n  intros.\n  induction i.\n  - auto.\n  - assert ( path T (skipn j ss) 0 (S i) <->\n      path T (skipn j ss) 0 i /\\\n        T (skipn j ss).[i] (skipn j ss).[S i] ).\n    {\n      destruct i. firstorder.\n      unfold path; fold path.\n      simpl.\n      (*rewrite <- plus_n_O.*)\n      tauto.\n    }\n    apply H0.\n    clear H0.\n\n    split.\n    apply IHi.\n    destruct i; firstorder.\n    + clear IHi.\n      rewrite skipn_nth.\n      rewrite skipn_nth.\n      simpl in *.\n      decompose [and] H. clear H.\n      destruct i.\n      * simpl in *.\n        auto.\n      * auto.\nQed.\n\nLemma skipn_no_loop' : forall (i j k : nat),\n  forall ss : sseq,\n  no_loop' ss j k i ->\n  no_loop' (skipn j ss) 0 k i.\nProof.\n  intros.\n  destruct i.\n  - simpl in *.\n    do 2 rewrite skipn_nth.\n    rewrite -> Nat.add_0_r.\n    apply H.\n  - induction i.\n    + simpl in *.\n      do 3 rewrite skipn_nth.\n      rewrite -> Nat.add_0_r.\n      apply H.\n    + simpl.\n      split.\n      * do 2 rewrite skipn_nth.\n        firstorder.\n      * simpl in H.\n        do 2 rewrite skipn_nth.\n        tauto.\nQed.\n\nLemma skipn_no_loop : forall (i j : nat),\n  forall ss : sseq,\n  no_loop ss j i -> no_loop (skipn j ss) 0 i.\nProof.\n  intros.\n  induction i.\n  - auto.\n\n  - assert (H1 : no_loop ss j i /\\ no_loop' ss j (S i) i)\n      by ( destruct i; firstorder; rewrite <- plus_n_O in *).\n    clear H.\n\n    assert ( H :no_loop (skipn j ss) 0 i /\\\n      no_loop' (skipn j ss) 0 (S i) i -> \n      no_loop (skipn j ss) 0 (S i) ).\n    intros.\n    destruct i; firstorder; rewrite <- plus_n_O in *.\n    apply H.\n    clear H.\n    split.\n    apply IHi.\n    tauto.\n    destruct H1.\n    clear H.\n    apply skipn_no_loop' in H0.\n    tauto.\nQed.\n\nLemma skipn_prop : forall (P : prop) (i k : nat),\n  forall ss : sseq,\n  i >= k -> ~ P ss.[i] -> ~ P (skipn (i - k) ss).[k].\nProof.\n  intros.\n  rewrite skipn_nth.\n  replace (i - k + k) with i.\n  auto.\n  omega.\nQed.\n\n(**)\n\nLemma cons_path : forall (ss : sseq) (T : trans) (i j : nat),\n  T ss.[i] ss.[S i] /\\ path T ss (S i) j <->\n  path T ss i (S j).\nProof.\n  destruct j.\n  - unfold path.\n    rewrite Nat.add_0_r.\n    rewrite Nat.add_1_r.\n    tauto.\n  - induction j. \n    + simpl.\n      rewrite Nat.add_1_r.\n      do 2 rewrite Nat.add_succ_r.\n      rewrite Nat.add_0_r.\n      tauto.\n    + simpl.\n      split; firstorder;\n      now do 5 rewrite Nat.add_succ_r in *.\nQed.\n\nLemma snoc_path : forall (ss : sseq) (T : trans) (i j: nat),\n  path T ss i (S j) <->\n  path T ss i j /\\ T ss.[i+j] ss.[S (i+j)].\nProof.\n  intros.\n  simpl.\n  replace (i + S j) with (S (i + j)).\n  tauto.\n  auto.\nQed.\n\nLemma skip1_path : forall (T : trans) (i j : nat),\n  forall ss : sseq,\n  path T ss (S i) j -> path T (skipn 1 ss) i j.\nProof.\n  intros.\n  induction j.\n  - simpl. intuition.\n  - rewrite -> snoc_path in H.\n    destruct H.\n    rewrite -> snoc_path.\n    split.\n    * apply IHj.\n      apply H.\n    * do 2 rewrite skipn_nth.\n      replace (1+(i+j)) with (S i + j).\n      replace (1+S (i+j)) with (S (S i + j)).\n      apply H0.\n      auto. \n      auto.\nQed.\n\nLemma shift_path : forall (ss : sseq) (T : trans) (i j : nat), \n  path T ss 0 i /\\ path T ss i (S j) <-> \n  path T ss 0 (S i) /\\ path T ss (S i) j .\nProof.\n  intros.\n  rewrite snoc_path with (i:=0).\n  rewrite and_assoc.\n  rewrite cons_path.\n  reflexivity.\nQed.\n\nLemma split_path : forall (ss : sseq) (T : trans) (i j: nat),\n  path T ss 0 (i+j) <-> path T ss 0 i /\\ path T ss i j.\nProof.\n  induction i.\n  - simpl.\n    tauto.\n  - split.\n    + intros.\n      rewrite -> Nat.add_succ_comm in H.\n      apply IHi in H.\n      apply shift_path.\n      apply H.\n    + intros.\n      apply shift_path in H.\n      apply IHi in H.\n      rewrite <- Nat.add_succ_comm in H.\n      apply H.\nQed.\n\n\nLemma split_no_loop' : forall (ss:sseq) (o i k j:nat),\n  no_loop' ss o i (j+k) -> no_loop' ss o i j.\nProof.\n  induction k.\n  - intros.\n    rewrite -> plus_0_r in H.\n    apply H.\n  - intros.\n    rewrite <- Nat.add_succ_comm in H.\n    apply IHk in H.\n    simpl in H.\n    destruct H.\n    apply H.\nQed.\n\nLemma split_no_loop_former : forall (ss : sseq) (j i : nat),\n  no_loop ss 0 (i+j) -> no_loop ss 0 i.\nProof.\n  induction j.\n  - intros.\n    now rewrite <- plus_n_O in H.\n  - intros.\n    rewrite <- Nat.add_succ_comm in H.\n    apply IHj in H.\n    simpl in H.\n    destruct H.\n    apply H0.\nQed.\n\n\nLocal Lemma split_no_loop_latter'' : \n  forall (ss : sseq) (i j k : nat),\n  no_loop' ss i (S k) (S j) <->\n    ss.[(i + (S k))] <> ss.[i] /\\\n    no_loop' ss (S i) k j.\nProof.\n  destruct j.\n  - simpl. \n    intros.\n    now rewrite <- Nat.add_succ_l;\n      rewrite Nat.add_succ_comm; rewrite Nat.add_1_r.\n  - induction j.\n    + simpl.\n      intros.\n      do 2 rewrite <- Nat.add_succ_r.\n      do 1 rewrite ->  Nat.add_1_r.\n      tauto.\n    + intros.\n      simpl in *.\n      assert (forall (p1 p2 p3 p4 p5:Prop),\n        (p1 <-> (p2 /\\ p3 /\\ p4) /\\ p5) <->\n        (p1 <-> p2 /\\ (p3 /\\ p4) /\\ p5)) by tauto.\n      rewrite <- H.\n      rewrite <- IHj.\n      do 2 rewrite <- Nat.add_succ_r.\n      tauto.\nQed.\n\nLocal Lemma split_no_loop_latter' : forall (ss : sseq) (j i : nat),\n  no_loop ss i (S j) -> no_loop ss (S i) j.\nProof.\n  induction j.\n  intros.\n  - destruct i; firstorder.\n  - intros.\n    assert (no_loop ss (S i) (S j) <->\n      no_loop' ss (S i) (S j) j /\\ no_loop ss (S i) j)\n      by (destruct j; firstorder).\n    apply H0.\n    assert (no_loop ss i (S (S j)) <->\n      no_loop' ss i (S (S j)) (S j) /\\ \n      no_loop ss i (S j))\n      by (destruct j; firstorder).\n    apply -> H1 in H.\n    destruct H.\n    split.\n    now apply split_no_loop_latter'' in H.\n    now apply IHj in H2.\nQed.\n\nLemma split_no_loop_latter : forall (ss : sseq) (i j : nat),\n  no_loop ss 0 (i+j) -> no_loop ss i j.\nProof.\n  induction i.\n  - easy.\n  - intros.\n    rewrite Nat.add_succ_comm in H.\n    apply IHi in H.\n    now apply split_no_loop_latter' in H.\nQed.\n\nLemma split_no_loop : forall (ss : sseq) (i j: nat),\n    no_loop ss 0 (i+j) ->\n    no_loop ss 0 i /\\ no_loop ss i j.\nProof.\n  intros.\n  split.\n  - now apply split_no_loop_former in H.\n  - now apply split_no_loop_latter in H.\nQed.\n\nLemma split_loop_free : forall  (ss : sseq) (T : trans) (i j : nat),\n  loop_free T ss 0 (i+j) -> \n  loop_free T ss 0 i /\\ loop_free T ss i j.\nProof.\n  unfold loop_free.\n  intros.\n  destruct H.\n  apply split_path in H.\n  apply split_no_loop in H0.\n  tauto.\nQed.\n\nLemma split_path_lf :\n  forall (T:trans) (ss:sseq) (m n:nat),\n    loop_free T ss 0 m /\\ path T ss m n ->\n    path T ss 0 (m+n).\nProof.\n  induction m.\n  - intros.\n    unfold loop_free in H.\n    decompose [and] H; clear H.\n    tauto.\n  - intros.\n    unfold loop_free in H.\n    decompose [and] H; clear H.\n    assert (path T ss 0 (S m) /\\ path T ss (S m) n) by auto.\n    clear H1 H2.\n    apply shift_path in H.\n    destruct H.\n    rewrite <- Nat.add_1_r in H3.\n    apply split_no_loop_former in H3.\n    assert (loop_free T ss 0 m /\\ path T ss m (S n)) by (unfold loop_free; tauto).\n    clear H3 H H0.\n    apply IHm in H1.\n    rewrite <- Nat.add_succ_comm in H1.\n    apply H1.\nQed.\n\nLemma split_lf_path :\n  forall (T:trans) (ss:sseq) (n:nat),\n    path T ss 0 (n+1) -> \n    ss.[n+1] <> ss.[n] ->\n    path T ss 0 n /\\ loop_free T ss n 1.\nProof.\n  induction n.\n  - intros.\n    unfold path.\n    unfold loop_free.\n    unfold no_loop.\n    unfold no_loop'.\n    rewrite -> Nat.add_0_l in *.\n    tauto.\n  - intros.\n    split.\n    + rewrite -> Nat.add_1_r in H.\n      rewrite -> snoc_path in H.\n      destruct H.\n      apply H.\n    + unfold loop_free.\n      split.\n      * rewrite -> split_path in H.\n        destruct H.\n        apply H1.\n      * unfold no_loop.\n        unfold no_loop'.\n        (*rewrite -> Nat.add_0_r.*)\n        tauto.\nQed.\n\n(**)\n\nLemma lf_path :\n  forall (T:trans) (ss:sseq) (i:nat),\n  loop_free T ss 0 i ->\n  path T ss 0 i.\nProof.\n  intros.\n  induction i.\n  - simpl. intuition.\n  - simpl.\n    rewrite <- Nat.add_1_r in H.\n    apply split_loop_free in H.\n    destruct H.\n    split.\n    + apply IHi in H.\n      apply H.\n    + unfold loop_free in H0.\n      destruct H0.\n      unfold path in H0.\n      destruct H0.\n      rewrite -> Nat.add_0_r in H2.\n      rewrite -> Nat.add_1_r in H2.\n      apply H2.\nQed.\n\nLemma no_loop'_neq' :\n  forall (ss:sseq) (o i j:nat),\n  i >= j -> no_loop' ss o (S i) (i-j) ->\n  ss.[o + S i] <> ss.[o+(i-j)].\nProof.\n  intros.\n  destruct j.\n  - destruct i.\n    + rewrite -> Nat.sub_0_r in *.\n      rewrite -> Nat.add_0_r.\n      simpl in H0.\n      apply H0.\n    + rewrite -> Nat.sub_0_r in *.\n      simpl in H0.\n      destruct H0.\n      apply H1.\n  - remember (i - S j) as k.\n    destruct k.\n    + simpl in H0.\n      rewrite -> Nat.add_0_r.\n      apply H0.\n    + simpl in H0.\n      destruct H0.\n      apply H1.\nQed.\n\nLemma no_loop'_neq :\n  forall (ss:sseq) (o i j:nat),\n  no_loop' ss o (S i) i ->\n  i > j -> ss.[o + S i] <> ss.[o+j].\nProof.\n  intros.\n  remember (i-j) as k.\n  replace j with (i-k).\n  apply no_loop'_neq'.\n  omega.\n  assert (j = i - k) by omega.\n  rewrite <- H1.\n  assert (i = j + k) by omega.\n  rewrite -> H2 in H.\n  apply split_no_loop' in H.\n  rewrite <- H2 in H.\n  apply H.\n  omega.\nQed.\n\nLemma neq_states_no_loop' :\n  forall (ss:sseq) (o i j:nat),\n  i > j -> \n  no_loop' ss o (S i) j -> ss.[o + S i] <> ss.[o+(S j)] ->\n  no_loop' ss o (S i) (S j).\nProof.\n  intros.\n  destruct j.\n  - simpl.\n    split.\n    + simpl in H0.\n      apply H0.\n    + apply H1.\n  - simpl.\n    split.\n    + simpl in H0.\n      apply H0.\n    + apply H1.\nQed.\n\nLemma eq_states_not_no_loop' :\n  forall (ss:sseq) (o i j:nat),\n  i > j -> ss.[o + S i] = ss.[o+j] ->\n  ~ no_loop' ss o (S i) i.\nProof.\n  intros.\n  assert (~(ss.[o + S i] <> ss.[o+j])) by tauto.\n  contradict H1.\n  apply no_loop'_neq.\n  apply H1.\n  apply H.\nQed.\n\nLemma lf_loop_path :\n  forall (T:trans) (i j:nat) (ss:sseq),\n  loop_free T ss 0 i -> \n  path T ss 0 j -> ~ no_loop ss 0 j -> \n  (* i <= j *) ~ i > j.\nProof.\n  intros.\n  contradict H1.\n\n  unfold loop_free in H.\n  destruct H.\n\n  remember (i-j) as k.\n  assert (i = j+k) by omega.\n\n  rewrite -> H3 in H2.\n  apply split_no_loop in H2.\n  destruct H2.\n  apply H2.\nQed.\n\nLemma lf_loop_path' :\n  forall (T:trans) (i j:nat) (ss:sseq),\n  loop_free T ss 0 i -> \n  i > j -> \n  ~no_loop ss 0 j -> ~path T ss 0 j.\nProof.\n  intros.\n  assert (~~(i > j)) by omega.\n  contradict H2.\n  revert H H2 H1.\n  apply lf_loop_path.\nQed.\n\n(*\nLemma lf_loop_path'' :\n  forall (T:trans) (i j:nat) (ss:sseq),\n  loop_free T ss 0 i -> \n  path T ss 0 j -> i > j -> \n  no_loop ss 0 j.\nProof.\n  intros.\n  apply NNPP.\n  contradict H1.\n  revert H H0 H1.\n  apply lf_loop_path.\nQed.\n*)\n\nLemma split_skipn :\n  forall (m n i : nat) (ss : sseq),\n  (skipn (m+n) ss).[i] = (skipn m (skipn n ss)).[i].\nProof.\n  intros.\n  do 3 rewrite -> skipn_nth.\n  assert (m + n + i = n + (m + i)) by omega.\n  rewrite -> H.\n  reflexivity.\nQed.\n\n(* eof *)", "meta": {"author": "dsksh", "repo": "coq-smc", "sha": "60e63dc612eeffe7ed5ad4a658fdacf30709b19a", "save_path": "github-repos/coq/dsksh-coq-smc", "path": "github-repos/coq/dsksh-coq-smc/coq-smc-60e63dc612eeffe7ed5ad4a658fdacf30709b19a/src/Core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.6520830912854678}}
{"text": "(** * Ternary logic exercise *)\n\nModule ternary_unknown.\n\nInductive bool3 : Set :=\n| true : bool3\n| false : bool3\n| unknown : bool3.\n\nDefinition andb3 (b1 b2 : bool3) : bool3 :=\nmatch b1, b2 with\n| true, true => true\n| false, _ => false\n| _, false => false\n| _, _ => unknown\nend.\n\nDefinition orb3 (b1 b2 : bool3) : bool3 :=\nmatch b1, b2 with\n| false, false => false\n| true, _ => true\n| _, true => true\n| _, _ => unknown\nend.\n\nDefinition negb3 (b : bool3) : bool3 :=\nmatch b with\n| true => false\n| false => true\n| unknown => unknown\nend.\n\nLtac solve_bool3 := intros;\nmatch reverse goal with\n| b : bool3 |- _ => destruct b; solve_bool3\n| _ => cbn; reflexivity\nend.\n\nNotation \"b1 & b2\" := (andb3 b1 b2) (at level 40).\nNotation \"b1 | b2\" := (orb3 b1 b2) (at level 40).\n\nLemma andb3_comm :\n  forall b1 b2 : bool3, b1 & b2 = b2 & b1.\nProof. solve_bool3. Qed.\n\nLemma orb3_comm :\n  forall b1 b2 : bool3, b1 | b2 = b2 | b1.\nProof. solve_bool3. Qed.\n\nLemma andb3_dist_orb3 :\n  forall b1 b2 b3 : bool3,\n    b1 & (b2 | b3) = (b1 & b2) | (b1 & b3).\nProof. solve_bool3. Qed.\n\nLemma orb3_dist_andb3 :\n  forall b1 b2 b3 : bool3,\n    b1 | (b2 & b3) = (b1 | b2) & (b1 | b3).\nProof. solve_bool3. Qed.\n\nLemma andb3_true_neutral_l :\n  forall b : bool3, andb3 true b = b.\nProof. solve_bool3. Qed.\n\nLemma andb3_true_neutral_r :\n  forall b : bool3, andb3 b true = b.\nProof. solve_bool3. Qed.\n\nEnd ternary_unknown.", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/code/IndRec/TernaryLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.6520830806041814}}
{"text": "From Coq Require Import Nat.\nFrom Coq Require Import Program.Equality.\n\nSet Maximal Implicit Insertion.\n\nModule Stlc.\n\n  (** Use the same reified type for the whole development *)\n  Inductive type : Type :=\n  | TNum: type\n  | TArrow : type -> type -> type.\n\n  Declare Custom Entry stlc_ty.\n  Notation \"<{{ e }}>\" := e (e custom stlc_ty at level 99).\n  Notation \"( x )\" := x (in custom stlc_ty, x at level 99).\n  Notation \"x\" := x (in custom stlc_ty at level 0, x constr at level 0).\n  Notation \"S -> T\" := (TArrow S T) (in custom stlc_ty at level 2, right associativity).\n  Notation \"'Num'\" := TNum (in custom stlc_ty at level 0).\n\n  (* begin typeDenote *)\n  Fixpoint typeDenote (t : type) : Set :=\n    match t with\n    | <{{ Num }}> => nat\n    | <{{ t1 -> t2 }}> => typeDenote t1 -> typeDenote t2\n    end.\n  (* end typeDenote *)\n  \n  (* begin syntax *)\n  Section vars.\n    Variable var : type -> Type.\n\n    Inductive Term: type -> Type :=\n    | NUM: nat -> Term <{{ Num }}>\n    | ADD: Term <{{ Num }}> -> Term <{{ Num }}> -> Term <{{ Num }}>\n    | APP: forall a b, Term <{{ a -> b }}> -> Term a -> Term b\n    | RET: forall a, var a -> Term a\n    | LAM: forall a b, (var a -> Term b) -> Term <{{ a ->  b }}>.\n  End vars.\n  (* end syntax *)\n  \n  Arguments RET {var a}.\n  Arguments NUM {var}.\n  Arguments ADD {var}.\n  Arguments APP {var a b}.\n  Arguments LAM {var a b}.\n\n  (* Syntax *)\n  Declare Custom Entry stlc.\n  Notation \"<{ e }>\" := e (e custom stlc at level 99).\n  Notation \"( x )\" := x (in custom stlc, x at level 99).\n  Notation \"x\" := x (in custom stlc at level 0, x constr at level 0).\n  Notation \"x y\" := (APP x y) (in custom stlc at level 2, left associativity).\n  Notation \"x + y\" := (ADD x y) (in custom stlc at level 2, left associativity).\n  Notation \"\\ x , y\" :=\n    (LAM (fun x => y)) (in custom stlc at level 90,\n                        x constr,\n                        y custom stlc at level 80,\n                        left associativity).\n  Notation \"\\_ , y\" :=\n    (LAM (fun _ => y)) (in custom stlc at level 90,\n                        y custom stlc at level 80,\n                        left associativity).\n\n  Notation \"# n\" := (NUM n) (in custom stlc at level 0).\n  Notation \"@ n\" := (RET n) (in custom stlc at level 0, n custom stlc at level 1).\n  Notation \"{ x }\" := x (in custom stlc at level 1, x constr).\n\n  Class Denotation (v: type -> Type) := {\n      denote{t}(e: Term v t): v t;\n                                      }.\n\n  (* begin termDenote *)\n  Fixpoint termDenote {t: type} (e : Term typeDenote t) : typeDenote t :=\n    match e in (Term _ t) return (typeDenote t) with\n    | RET v => v\n    | ADD l r => (termDenote l) + (termDenote r)                                   \n    | NUM f => f\n    | APP e1 e2 => (termDenote e1) (termDenote e2)\n    | LAM e' => fun x => termDenote (e' x)\n    end.\n  (* end termDenote *)\n  \n  Fixpoint termFlatten {t: type} {v: type -> Type} (e: Term (Term v) t): Term v t :=\n    match e with\n    | RET v => v\n    | NUM f => NUM f\n    | ADD l r => ADD (termFlatten l) (termFlatten r)\n    | APP e1 e2 => APP (termFlatten e1) (termFlatten e2)\n    | LAM e' => LAM (fun x => termFlatten (e' (RET x)))\n    end.\n\n  Instance baseDenotation: Denotation typeDenote := {\n      denote t e := termDenote e\n    }.\n  \n  Instance stepDenotation v `{Denotation v}: Denotation (Term v) := {\n      denote t e := termFlatten e\n    }.\n\n\n  (** Demo *)\n  Fixpoint add1 {t: type} {v: type -> Type} (e: Term v t): Term v t :=\n    match e with\n    | NUM f => NUM (f+1)\n    | APP e1 e2 => APP (add1 e1) (add1 e2)\n    | ADD e1 e2 => ADD (add1 e1) (add1 e2)\n    | LAM e' => LAM (fun x => add1 (e' x))\n    | RET v => RET v\n    end.\n  \n  Tactic Notation \"meta\" uconstr(x) := refine x; exact typeDenote.\n  \n  Definition l3 :=\n    ltac:(meta <{ \\x, @x + #1 + (@ (#3 + (@( #1)))) }>).\n\n  Check l3.\n\n  Compute add1 l3.          (* = <{ \\ x, @ x + #2 + @ (#3) + @ (#1) }> *)\n  Compute denote (add1 l3). (* = <{ \\ x, @ x + #2 + (#3 + @ (#1)) }> *)\n  Compute denote (add1 (denote (add1 l3))).\n                            (* = <{ \\ x, @ x + #3 + #4 + #1 }> *)\n  Compute denote (denote (add1 (denote (add1 l3)))).\n                            (* = <{ \\x, 5 }> *)\n  Compute denote (denote (add1 l3)).\n  Compute denote (denote (denote (add1 l3))).\n\n  (* Normalization via reify/reflect Danvy et al. *)\n  (* begin nbe *)\n  Class Nbe (t: type) := {\n    reify: typeDenote t -> Term typeDenote t;\n    reflect: Term typeDenote t -> typeDenote t\n    }.\n  \n  Instance Nbe_lam {a b: type} `{Nbe a} `{Nbe b}: Nbe <{{ a -> b }}> := {\n    reify v :=\n      LAM (fun x => reify (v (reflect (RET x))));\n    reflect e :=\n      fun x => reflect (APP e (reify x))\n    }.\n  \n  Instance Nbe_int : Nbe <{{ Num }}> := {\n    reify v := NUM v;\n    reflect v := termDenote v;\n    }.\n  (* end nbe *)\n  \n  Fixpoint resolver(t: type): Nbe t :=\n    match t with\n    | <{{ Num }}> => Nbe_int\n    | <{{ a -> b }}> => Nbe_lam\n    end.\n\n  Arguments Nbe {t}.\n  Arguments Nbe_lam [a b].\n\n  Definition normalize {t: type} (e: Term typeDenote t): Term typeDenote t :=\n    @reify t (resolver t) (@reflect t (resolver t) e).\n\n  Compute normalize <{ ((\\x, @x + #1) #2) + #1 }>.\n\n  (* begin fof *)\n  Inductive fof: type -> Prop :=\n  | fo_num: fof <{{ Num }}>\n  | fof_num: forall a,\n      fof <{{ a }}> ->\n      fof <{{ Num -> a }}>.\n\n  Hint Constructors fof: core.\n  (* end fof *)\n  \n  Inductive value: forall {t: type}, Term typeDenote t -> Prop :=\n  | Value_var: forall x, @value <{{ Num }}> (@RET typeDenote <{{ Num }}> x)\n  | Value_const: forall (x: nat), @value <{{ Num }}> (NUM x).\n\n  Hint Constructors value: core.\n\n  (* begin hnff *)\n  Inductive hnff: forall (t: type), Term typeDenote t -> Prop :=\n  | HNF_num_ar: forall a f,\n      (forall (arg: typeDenote <{{ Num }}>), hnff <{{ a }}> (f arg)) ->\n      hnff <{{ Num -> a }}> (LAM f)\n  | HNF_num: forall e,\n      value e ->\n      hnff <{{ Num }}> e.\n  \n  Hint Constructors hnff: core.\n  (* end hnff *)\n\n  (* begin correct *)\n  Theorem normalize_correct: forall (t: type) (e: Term typeDenote t),\n      fof t  ->\n      hnff t (normalize e).\n  Proof with eauto.\n    induction t; dependent destruction e; inversion 1; subst; cbn...\n  Defined.\n  (* end correct *)\n  \nEnd Stlc.\n", "meta": {"author": "elefthei", "repo": "phoas-experiments", "sha": "03bbae98a594e77f38ac129bdc477f0f567da492", "save_path": "github-repos/coq/elefthei-phoas-experiments", "path": "github-repos/coq/elefthei-phoas-experiments/phoas-experiments-03bbae98a594e77f38ac129bdc477f0f567da492/Quoting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6520641661792801}}
{"text": "Require Import Arith List Omega.\nRequire Import Max.\n\nSet Implicit Arguments.\n\n\n(** * Recursion on proofs *)\n\nPrint positive.\n\nFixpoint div2 (n : nat) : nat :=\n  match n with\n    | S (S n') => S (div2 n')\n    | _ => O\n  end.\n\nInductive ntb_pred : nat -> Prop :=\n  | ntb_1 : ntb_pred 1\n  | ntb_div2 : forall n,\n    ntb_pred (div2 n)\n    -> ntb_pred n.\n\nFixpoint bin_to_nat (b : positive) : nat :=\n  match b with\n    | xH => 1\n    | xO b' => 2 * bin_to_nat b'\n    | xI b' => 1 + 2 * bin_to_nat b'\n  end.\n\nLemma ntb_pred_positive : forall n,\n  ntb_pred n\n  -> n = 0\n  -> False.\n  induction 1; intuition; subst; auto.\nQed.\n\nHint Resolve ntb_pred_positive.\n\nHint Extern 5 False => omega.\n\nFixpoint isEven (n : nat) : bool :=\n  match n with\n    | 0 => true\n    | 1 => false\n    | S (S n') => isEven n'\n  end.\n\nDefinition nat_to_bin (n : nat) (pf : ntb_pred n) : positive.\n  refine (fix nat_to_bin (n : nat) (pf : ntb_pred n) {struct pf} : positive :=\n    match n as n' return (n = n' -> _) with\n      | 0 => fun Heq => False_rec _ _\n      | 1 => fun Heq => xH\n      | S (S n') => fun Heq =>\n\tmatch nat_to_bin (div2 n)\n\t  (match pf in (ntb_pred n') return (n = n' -> ntb_pred (div2 n')) with\n\t     | ntb_1 => fun Heq => False_ind _ _\n\t     | ntb_div2 _ pf' => fun _ => pf'\n\t   end (refl_equal _)) with\n\t  | b =>\n\t    if isEven n\n\t      then xO b\n\t      else xI b\n\tend\n    end (refl_equal _)); clear nat_to_bin; eauto.\nDefined.\n\nEval compute in nat_to_bin ntb_1.\nEval compute in nat_to_bin (ntb_div2 2 ntb_1).\nEval compute in nat_to_bin (ntb_div2 3 ntb_1).\nEval compute in nat_to_bin (ntb_div2 4 (ntb_div2 2 ntb_1)).\nEval compute in nat_to_bin (ntb_div2 5 (ntb_div2 2 ntb_1)).\n\nExtraction nat_to_bin.\n\n\n(** * Well-founded recursion: merge sort example *)\n\nSection mergeSort.\n  Variable A : Set.\n  Variable le : A -> A -> Prop.\n\n  Variable le_dec : forall x y, {le x y} + {~le x y}.\n\n  Fixpoint insert (x : A) (ls : list A) {struct ls} : list A :=\n    match ls with\n      | nil => x :: nil\n      | h :: ls' =>\n\tif le_dec x h\n\t  then x :: ls\n\t  else h :: insert x ls'\n    end.\n\n  Fixpoint merge (ls1 ls2 : list A) {struct ls1} : 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\tlet (ls1, ls2) := split ls' in\n\t  (h1 :: ls1, h2 :: ls2)\n    end.\n\n  Definition lengthOrder (ls1 ls2 : list A) :=\n    length ls1 < length ls2.\n\n  Theorem lengthOrder_wf : well_founded lengthOrder.\n    red.\n\n    cut (forall len : nat, forall a : list A, length a <= len -> Acc lengthOrder a); eauto.\n    \n    induction len; intuition.\n\n    destruct a; simpl in H.\n\n    constructor; intros.\n    inversion H0.\n\n    inversion H.\n\n    constructor; intros.\n    red in H0.\n    apply IHlen.\n    omega.\n  Qed.\n\n  Ltac arith_contra :=\n    assert False; [omega | tauto].\n\n  Lemma split_lengthOrder1' : forall len ls,\n    2 <= length ls <= len\n    -> lengthOrder (fst (split ls)) ls.\n    induction len; simpl; intuition; try arith_contra.\n\n    destruct ls; simpl in *; try arith_contra.\n    destruct ls; simpl in *; try arith_contra.\n\n    red; simpl.\n\n    destruct (le_lt_dec 2 (length ls)).\n\n    generalize (IHlen ls).\n    destruct (split ls); simpl.\n    unfold lengthOrder; simpl.\n    omega.\n    \n    destruct ls; simpl in *; try omega.\n    destruct ls; simpl in *; omega.\n  Qed.\n\n  Lemma split_lengthOrder2' : forall len ls,\n    2 <= length ls <= len\n    -> lengthOrder (snd (split ls)) ls.\n    induction len; simpl; intuition; try arith_contra.\n\n    destruct ls; simpl in *; try arith_contra.\n    destruct ls; simpl in *; try arith_contra.\n\n    red; simpl.\n\n    destruct (le_lt_dec 2 (length ls)).\n\n    generalize (IHlen ls).\n    destruct (split ls); simpl.\n    unfold lengthOrder; simpl.\n    omega.\n    \n    destruct ls; simpl in *; try omega.\n    destruct ls; simpl in *; omega.\n  Qed.\n\n  Theorem split_lengthOrder1 : forall ls,\n    2 <= length ls\n    -> forall ls1 ls2, split ls = (ls1, ls2)\n      -> lengthOrder ls1 ls.\n    intros.\n    replace ls1 with (fst (split ls)).\n    eapply split_lengthOrder1'; eauto.\n    rewrite H0; trivial.\n  Qed.\n\n  Theorem split_lengthOrder2 : forall ls,\n    2 <= length ls\n    -> forall ls1 ls2, split ls = (ls1, ls2)\n      -> lengthOrder ls2 ls.\n    intros.\n    replace ls2 with (snd (split ls)).\n    eapply split_lengthOrder2'; eauto.\n    rewrite H0; trivial.\n  Qed.\n\n  Hint Resolve split_lengthOrder1 split_lengthOrder2.\n\n  Definition mergeSort (ls : list A) : list A.\n    refine (Fix lengthOrder_wf (fun _ => list A)\n      (fun (ls : list A)\n\t(mergeSort : forall ls' : list A, lengthOrder ls' ls -> list A) =>\n\tif le_lt_dec 2 (length ls)\n\t  then match split ls as lss return (split ls = lss -> _) with\n\t\t | (ls1, ls2) => fun Heq => merge (mergeSort ls1 _) (mergeSort ls2 _)\n\t       end (refl_equal _)\n\t  else ls)); eauto.\n  Defined.\n\n  Theorem mergeSort_rec : forall x y ls,\n    mergeSort (x :: y :: ls) =\n    match split (x :: y :: ls) as lss return (split (x :: y :: ls) = lss -> _) with\n      | (ls1, ls2) => fun Heq => merge (mergeSort ls1) (mergeSort ls2)\n    end (refl_equal _).\n    intros.\n    unfold mergeSort at 1.\n    rewrite Fix_eq; intuition.\n\n    destruct (le_lt_dec 2 (length x0)); intuition.\n    generalize (split_lengthOrder1 x0 l).\n    generalize (split_lengthOrder2 x0 l).\n    destruct (split x0); intuition.\n    repeat rewrite H.\n    reflexivity.\n  Qed.\nEnd mergeSort.\n\nRecursive Extraction mergeSort.\n\n\n(** * Domain theory approach to general recursive programs *)\n\n(** ** Foundational definitions *)\n\nSet Implicit Arguments.\n\nSection computation.\n  Variable A : Set.\n\n  Definition computation :=\n    {f : nat -> option A\n      | forall (n : nat) (v : A),\n\tf n = Some v\n\t-> forall (n' : nat), n' >= n\n\t  -> f n' = Some v}.\n\n  Definition runTo (m : computation) (n : nat) (v : A) :=\n    proj1_sig m n = Some v.\n\n  Definition run (m : computation) (v : A) :=\n    exists n, runTo m n v.\nEnd computation.\n\nHint Unfold runTo.\n\nSection Bottom.\n  Variable A : Set.\n\n  Definition Bottom : computation A.\n    exists (fun _ : nat => @None A); intuition.\n  Defined.\nEnd Bottom.\n\nSection Return.\n  Variable A : Set.\n  Variable v : A.\n\n  Definition Return : computation A.\n    intros.\n    exists (fun _ : nat => Some v); intuition.\n  Defined.\n\n  Theorem run_Return : run Return v.\n    red.\n    unfold runTo, Return.\n    exists 0; auto.\n  Qed.\nEnd Return.\n\nHint Resolve run_Return.\n\nLtac caseEq e := generalize (refl_equal e); pattern e at -1; case e.\n\nSection Bind.\n  Variables A B : Set.\n  Variable m1 : computation A.\n  Variable m2 : A -> computation B.\n\n  Definition Bind : computation B.\n    destruct m1 as [f1 Hf1].\n    exists (fun n =>\n      match f1 n with\n\t| None => None\n\t| Some v =>\n\t  let (f2, Hf2) := m2 v in\n\t    f2 n\n      end); intuition.\n    generalize (Hf1 n).\n    destruct (f1 n); intuition; try discriminate.\n    rewrite (H1 a (refl_equal _) _ H0); trivial.\n    destruct (m2 a); eauto.\n  Defined.\n\n  Theorem run_Bind : forall (v1 : A) (v2 : B),\n    run m1 v1\n    -> run (m2 v1) v2\n    -> run Bind v2.\n    unfold Bind, run, runTo; intros v1 v2 H1 H2.\n\n    destruct m1 as [f1 Hf1]; simpl in *; idtac.\n    caseEq (m2 v1); intros f2 Hf2 Heq.\n    rewrite Heq in H2.\n    destruct H1 as [n1 Hn1].\n    destruct H2 as [n2 Hn2].\n\n    exists (max n1 n2).\n    rewrite (Hf1 _ _ Hn1); auto with arith.\n    rewrite Heq.\n    rewrite (Hf2 _ _ Hn2); auto with arith.\n  Qed.\n\n  Theorem run_Bind' : forall (v2 : B),\n    run Bind v2\n    -> exists v1 : A,\n      run m1 v1\n      /\\ run (m2 v1) v2.\n    unfold Bind, run, runTo; intros v2 H1.\n\n    destruct m1 as [f1 Hf1]; simpl in *; idtac.\n    destruct H1 as [n1 Hn1].\n    caseEq (f1 n1);\n    [intros v1 Heq\n      | intros Heq]; rewrite Heq in Hn1; try discriminate.\n    exists v1; intuition eauto.\n    destruct (m2 v1); simpl; eauto.\n  Qed.\nEnd Bind.\n\nHint Resolve run_Bind.\n\nNotation \"x <- m1 ; m2\" :=\n  (Bind m1 (fun x => m2)) (right associativity, at level 70).\n\nSection monotone_runTo.\n  Variable A : Set.\n  Variable c : computation A.\n  Variable v : A.\n\n  Theorem monotone_runTo : forall (n1 : nat),\n    runTo c n1 v\n    -> forall n2, n2 >= n1\n      -> runTo c n2 v.\n    unfold runTo; intuition.\n    destruct c; simpl in *; intuition eauto.\n  Qed.\nEnd monotone_runTo.\n\nHint Resolve monotone_runTo.\n\nSection rewrite.\n  Variable A : Set.\n  Variable c : computation A.\n  Variable n : nat.\n  Variable v : A.\n\n  Theorem fold_runTo :\n    (proj1_sig c n = Some v)\n    = runTo c n v.\n    trivial.\n  Qed.\nEnd rewrite.\n\nSection lattice.\n  Variable A : Set.\n\n  Definition leq (x y : option A) :=\n    forall v, x = Some v -> y = Some v.\nEnd lattice.\n\nHint Unfold leq.\n\nSection Fix.\n  Variables A B : Set.\n  Variable f : (A -> computation B) -> (A -> computation B).\n\n  Hypothesis f_continuous : forall n v v1 x,\n    runTo (f v1 x) n v\n    -> forall (v2 : A -> computation B), (forall x, leq (proj1_sig (v1 x) n) (proj1_sig (v2 x) n))\n      -> runTo (f v2 x) n v.\n\n  Fixpoint Fix' (n : nat) (x : A) {struct n} : computation B :=\n    match n with\n      | O => Bottom _\n      | S n' => f (Fix' n') x\n    end.\n\n  Definition Fix : A -> computation B.\n    intro x.\n    exists (fun n => proj1_sig (Fix' n x) n).\n\n    cut (forall (steps : nat) (n : nat) (v : B),\n      proj1_sig (Fix' n x) steps = Some v ->\n      forall (n' : nat), n' >= n\n\t-> proj1_sig (Fix' n' x) steps = Some v).\n\n    intuition.\n    eapply H; eauto.\n    rewrite fold_runTo; eauto.\n\n    intros steps n.\n    generalize dependent x.\n    induction n; simpl; intuition.\n\n    discriminate.\n\n    destruct n'.\n    inversion H0.\n\n    simpl.\n    apply f_continuous with (Fix' n); clear f_continuous; auto.\n\n    red; intros.\n    eauto with arith.\n  Defined.\n\n  Definition extensional (f : (A -> computation B) -> (A -> computation B)) := \n    forall g1 g2 n,\n      (forall x, proj1_sig (g1 x) n = proj1_sig (g2 x) n)\n      -> forall x, proj1_sig (f g1 x) n = proj1_sig (f g2 x) n.\n\n  Hypothesis f_extensional : extensional f.\n\n  Theorem run_Fix : forall x v,\n    run (f Fix x) v\n    -> run (Fix x) v.\n    intros.\n\n    red; unfold runTo; simpl.\n    red in H; unfold runTo in H; simpl in H.\n\n    destruct H as [n Hn].\n    exists (S n).\n    simpl.\n\n    rewrite fold_runTo.\n    apply monotone_runTo with n; auto.\n\n    red.\n    rewrite (f_extensional (Fix' n) Fix n); intuition.\n  Qed.\nEnd Fix.\n\nHint Resolve run_Fix.\n\nNotation \"'dfix' f [ x ::: dom ] ::: ran := e\" :=\n  (Fix (A := dom) (B := ran) (fun f x => e) _) (at level 80).\nNotation \"'dfix' f [ '__' ::: dom ] ::: ran := e\" :=\n  (Fix (A := dom) (B := ran) (fun f _ => e) _) (at level 80).\nNotation \"'dfix' '__' [ x ::: dom ] ::: ran := e\" :=\n  (Fix (A := dom) (B := ran) (fun _ x => e) _) (at level 80).\nNotation \"'dfix' '__' [ '__' ::: dom ] ::: ran := e\" :=\n  (Fix (A := dom) (B := ran) (fun _ _ => e) _) (at level 80).\n\n\n(** ** Examples *)\n\n(** *** The constant-0 function *)\n\nDefinition const : nat -> computation nat.\n  refine (dfix const [ x ::: nat ] ::: nat := Return 0); intuition.\nDefined.\n\nEval compute in proj1_sig (const 0) 0.\nEval compute in proj1_sig (const 0) 1.\nEval compute in proj1_sig (const 8) 2.\n\nHint Unfold extensional.\n\nTheorem const_correct : forall n, run (const n) 0.\n  intros.\n  unfold const.\n  apply run_Fix; auto.\nQed.\n\nRecursive Extraction const.\n\n\n(** *** Natural number addition *)\n\nDefinition add : nat * nat -> computation nat.\n  refine (Fix (fun (add : nat * nat -> computation nat) (ns : nat * nat) =>\n    let (n1, n2) := ns in\n      match n1 with\n\t| O => Return (snd ns)\n\t| S n1' => res <- add (n1', n2); Return (S res)\n      end) _); intuition.\n\n  destruct x; simpl in *; idtac.\n  destruct n0; intuition.\n\n  unfold runTo, Bind; simpl.\n  unfold runTo, Bind in H; simpl in H.\n  caseEq (v1 (n0, n1)); intros f1 Hf1 Heq.\n  rewrite Heq in H; simpl in H.\n\n  caseEq (f1 n); [intros V1 Heq' | intros Heq']; rewrite Heq' in H; try discriminate.\n\n  generalize (H0 (n0, n1)); intro Hleq.\n  red in Hleq.\n  rewrite Heq in Hleq; simpl in Hleq.\n  destruct (v2 (n0, n1)) as [f2 Hf2]; simpl in *; idtac.\n  rewrite (Hleq V1); intuition.\nDefined.\n\nEval compute in proj1_sig (add (0, 0)) 0.\nEval compute in proj1_sig (add (0, 0)) 1.\nEval compute in proj1_sig (add (1, 0)) 1.\n\nEval compute in proj1_sig (add (8, 13)) 9.\n\nTheorem add_extensional : extensional\n  (fun add (ns : nat * nat) => let (n1, n2) := ns in\n    match n1 with\n      | O => Return (snd ns)\n      | S n1' => res <- add (n1', n2); Return (S res)\n    end).\n  red; intuition.\n  destruct a; intuition.\n  unfold Bind.\n  generalize (H (a, b)).\n  destruct (g1 (a, b)); simpl.\n  destruct (g2 (a, b)); simpl.\n  intro Heq.\n  rewrite Heq.\n  trivial.\nQed.\n\nHint Immediate add_extensional.\n\nTheorem add_correct : forall n1 n2, run (add (n1, n2)) (n1 + n2).\n  induction n1; unfold add; eauto.\nQed.\n\nRecursive Extraction add.\n\n\n(** *** Guarded infinite loop *)\n\nDefinition looper : bool -> computation unit.\n  refine (dfix looper [b ::: bool] ::: unit :=\n    if b\n      then Return tt\n      else looper b); intuition.\n\n  destruct x; intuition.\n  unfold leq in H0.\n  eauto.\nDefined.\n\nEval compute in proj1_sig (looper true) 0.\nEval compute in proj1_sig (looper true) 1.\n\nEval compute in proj1_sig (looper false) 0.\nEval compute in proj1_sig (looper false) 1.\nEval compute in proj1_sig (looper false) 10.\n\nTheorem looper_extensional : extensional (fun looper (b : bool) =>\n  if b\n    then Return tt\n    else looper b).\n  red; intuition.\n  destruct x; intuition.\nQed.\n\nHint Immediate looper_extensional.\n\nTheorem looper_correct : run (looper true) tt.\n  unfold looper; auto.\nQed.\n\nRecursive Extraction looper.\n", "meta": {"author": "SatyendraBanjare", "repo": "itp", "sha": "80831ac497c7e000e964587eb0233adb7382ee88", "save_path": "github-repos/coq/SatyendraBanjare-itp", "path": "github-repos/coq/SatyendraBanjare-itp/itp-80831ac497c7e000e964587eb0233adb7382ee88/lecture_codes/Lect9/lecture9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6520641569578608}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n\n(****************************************************************************)\n(* This contribution was updated for Coq V5.10 by the COQ workgroup.        *)\n(* January 1995                                                             *)\n(****************************************************************************)\n(*                                                                          *)\n(*      Coq V5.8                                                            *)\n(*                                                                          *)\n(*                                                                          *)\n(*      First-order Unification                                             *)\n(*                                                                          *)\n(*      Joseph Rouyer                                                       *)\n(*                                                                          *)\n(*      November 1992                                                       *)\n(*                                                                          *)\n(*               New theorems and lemmas on naturals.                       *)\n(*                                                                          *)\n(****************************************************************************)\n(*                            nat_complements.v                             *)\n(****************************************************************************)\n\nRequire Import Arith.\n\n(*********************************************************************)\n(************* Lemmas on naturals proved in Nat.v and *****************)\n(******************** used with the command \"auto\". *******************)\n(*********************************************************************)\n(*O_S      :(n:nat)(~O=(S n))*)\n(*eq_S     :(n:nat)(m:nat)(n=m)->((S n)=(S m))*)\n(*eq_add_S :(n:nat)(m:nat)((S n)=(S m))->(n=m)*)\n(*le_pred_n:(n:nat)(le (pred n) n)*)\n(*le_n_Sn  :(n:nat)(le n (S n))*)\n(*le_S_n   :(n:nat)(m:nat)(le (S n) (S m))->(le n m)*)\n(*le_Sn_O  :(n:nat)(~(le (S n) O))*)\n(*le_n     :(n:nat)(le n n)*)\n(*le_n_S   :(n:nat)(m:nat)(le n m)->(le (S n) (S m))*)\n(*********************************************************************)\n\n(*********************************************************************)\n(********** Logic tools : To translate P:Prop into Q:Set : ****************)\n(*********************************************************************)\n\nDefinition P_S (A : Set) (P : A -> Prop) (x : A) : Set :=\n  {a : A | a = x &  P a}.\n\nLemma P_S_proof1 : forall (A : Set) (a : A) (P : A -> Prop), P a -> P_S A P a.\nintros; unfold P_S in |- *; exists a; auto with arith.\nQed.\n\nLemma P_S_proof2 : forall (A : Set) (a : A) (P : A -> Prop), P_S A P a -> P a.\nunfold P_S in |- *; intros A a P h; elim h; intros x h0; elim h0;\n auto with arith.\nQed.\n\n(*********************************************************************)\n(***************** Logic tools  To negate an equality : ******************)\n(*********************************************************************)\n\nLemma Diff :\n forall (A : Set) (f : A -> Prop) (a b : A), f a -> ~ f b -> a <> b.\nunfold not in |- *; intros A f a b H H0 H1; elim H0; elim H1; auto with arith.\nQed.\n\n(*** Replace \"apply h;auto with arith\" by \"auto\" when the Type of h is False : ***)\n\nLemma n_False : ~ False.\nauto with arith.\nQed.\n\n(*********************************************************************)\n\n(*********************************************************************)\n(********************** Section complement_nat. *********************)\n(*********************************************************************)\n\n(*Section complement_nat.*)\n\n(*********************************************************************)\n(**************** Decidability of the equality in the Set nat : *************)\n(*********************************************************************)\n\nLemma nat_eq_decS : forall x y : nat, {x = y} + {x <> y}.\nsimple induction x.           \n(*case x=O*)\nsimple induction y; auto with arith.\n(*case x=(S y)*)\nsimple induction y.\n(*... case y0=O*)\nright; discriminate.\n(*... case y0=(S y1)*)\nintros y1 h; elim (H y1); intros.\n(*... ... case y=y1*)\nauto with arith. (*apply eq_S*)\n(*case not y=y1*)\nright; simplify_eq; auto with arith.\nQed.\n\nLemma nat_eq_decP : forall x y : nat, x = y \\/ x <> y.\nintros x y; elim (nat_eq_decS x y); auto with arith.\nQed.\n\n(*********************************************************************)\n(************** General induction (with le) : ****************************)\n(*********************************************************************)\n\nLemma ind_leS :\n forall (n : nat) (P : nat -> Set),\n P 0 -> (forall p : nat, (forall q : nat, q <= p -> P q) -> P (S p)) -> P n.\nintros n P; cut ((forall m : nat, m <= n -> P m) -> P n).\n2: auto with arith. (*apply le_n*)\nintros h h0 h1; apply h.\nelim n.\n(*case n=O*)\n(*... case m=O*)\nsimple induction m.\nintros; auto with arith.\n(*... case m=(S y)*)    \nintros y Hyp1 Hyp2; absurd (S y <= 0); auto with arith. (*le_Sn_O*)\n(*case n=(S y)*)\nsimple induction m.\n(*... case m=O*)\nauto with arith.\n(*... case m=(S y0)*)    \nintros y0 hyp1 hyp2; apply (h1 y0).\neauto with arith.\nQed.\n\nLemma ind_leP :\n forall (n : nat) (P : nat -> Prop),\n P 0 -> (forall p : nat, (forall q : nat, q <= p -> P q) -> P (S p)) -> P n.\nintros; apply (P_S_proof2 nat n P).\napply (ind_leS n (P_S nat P));\n [ apply P_S_proof1; assumption | intros; apply P_S_proof1 ].\napply H0; intros; elim (H1 q); [ intros x eg_x_q | auto with arith ].\nrewrite eg_x_q; auto with arith.\nQed.\n\n(*********************************************************************)\n(********** Reasoning by cases with the natural constructors : ************)\n(*********************************************************************)\n\nLemma pred_or : forall m : nat, 0 = m \\/ m = S (pred m).\nintro; elim m; auto with arith.\nQed.\n\nLemma nat_caseS :\n forall (x : nat) (P : nat -> Set), P 0 -> (forall n : nat, P (S n)) -> P x.\nintros; elim x; auto with arith.\nQed.\n\n(*********************************************************************)\n(************** Decidability of le : ************************************)\n(*********************************************************************)\n\nLemma le_decS : forall n p : nat, {n <= p} + {~ n <= p}.\nsimple induction n.\n(*case n=O*)\nauto with arith.\n(*case n=(S y)*)\nsimple induction p.\nauto with arith.           (*apply le_Sn_O*)\nintros y0 le_or_not_le; elim (H y0).\nauto with arith.             (*apply le_n_S*)\nintro not_le_n0_y0; right; unfold not in |- *.\nintros; elim not_le_n0_y0; auto with arith.        (*apply le_S_n*)\nQed.\n\nLemma le_decP : forall n p : nat, n <= p \\/ ~ n <= p.\nintros; elim (le_decS n p); auto with arith.\nQed.\n\nLemma le_S_eqS : forall n p : nat, n <= p -> {S n <= p} + {n = p :>nat}.\nsimple induction n.\nsimple induction p; auto with arith.\nintros n0 H p; elim p.\nintros; absurd (S n0 <= 0); auto with arith.\nintros n1 H1 H2; elim (H n1); auto with arith. (*le_n_S*)\nQed.\n\nLemma le_S_eqP : forall n p : nat, n <= p -> S n <= p \\/ n = p :>nat.\nintros; elim (le_S_eqS n p); auto with arith.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "continuations", "sha": "52115376f182175321b0d9fac9ad7d61db51ddb0", "save_path": "github-repos/coq/coq-contribs-continuations", "path": "github-repos/coq/coq-contribs-continuations/continuations-52115376f182175321b0d9fac9ad7d61db51ddb0/FOUnify_cps/nat_complements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6520641556511404}}
{"text": "Require Import ssreflect Arith.\nRequire Import Arith.EqNat.\nRequire Import Arith.Compare_dec.\nRequire Import List.\nRequire Import Omega.\n\nInductive typ :=\n  | Tnat : typ\n  | Tarrow : typ -> typ -> typ.\n\nInductive term :=\n  | Var : nat -> term\n  | ConstNat : nat -> term\n  | App : term -> term -> term\n  | Lambda : typ -> term -> term.\n\nCheck nth.\nCheck (list).\nDefinition context (t: Set) := list (option t).\n\n\nLemma lambda_equivalence: forall (t u: term) (ty: typ), t = u <-> (Lambda ty t = Lambda ty u).\nProof.\n  move => t u.\n  split;(move => h0).\n  rewrite h0.\n  done.\n  inversion h0.\n  trivial.\nQed.\n\nLemma app_equivalence: forall t u v w: term, App t u = App v w <-> (t = v) /\\ (u = w).\nProof.\n  move => t u v w.\n  split.\n  move => h0.\n  split.\n  inversion h0.\n  done.\n  inversion h0.\n  done.\n  move => [h0 h1].\n  rewrite h0.\n  rewrite h1.\n  done.\nQed.\n\n\nFixpoint omap (oty: option typ)  (ty: typ) : option typ:=\n  match oty with\n    | None => None\n    | Some t => Some (Tarrow (ty) (t)) \n  end.\n\nFixpoint type (ctx: list typ) (t: term) : option typ :=\n  match t with\n    | Var n => nth_error ctx n\n    | ConstNat _ => Some Tnat \n    | App t1 t2 => if type ctx t1 is Some (Tarrow t1l t1r) then\n                     if type ctx t2 is Some t1l then Some t1r\n                     else None\n                   else None\n    | Lambda ty t => omap (type (ty :: ctx) t) ty\n  end.\n\n\nFixpoint C (i: nat) (t: term): Prop :=\n  match t with\n    | Var v => (v < i)\n    | ConstNat v => True\n    | App t1 t2 => (C i t1) /\\ (C i t2)\n    | Lambda ty t1 => C (i+1) t1\n  end.\n\n(*Question 1.2*)\nLemma ind_C_pred: forall t: term, forall n: nat, C n t -> C (n+1) t.\nProof.\n  induction t; simpl; intros.\n  omega; trivial.\n  trivial.\n  split.\n  apply IHt1.\n  by destruct H.\n  apply IHt2. by destruct H.\n  by apply IHt.\nQed.\n\n\nFixpoint lifting (n: nat) (k: nat) (t: term): term :=\n  match t with\n    | Var i => if leb k i then Var (i+n) else Var i\n    | ConstNat i => ConstNat i\n    | App t1 t2 => App (lifting n k t1) (lifting n k t2)\n    | Lambda ty t1 => Lambda ty (lifting n (k+1) t1)\n  end.\n\nFixpoint substitution (i: nat) (t1: term) (t2: term): term :=\n  match t1 with\n    | Var v => if beq_nat i v then t2 else Var v\n    | ConstNat i => ConstNat i\n    | App t3 t4 => App (substitution i t3 t2) (substitution i t4 t2)\n    | Lambda ty t3 => Lambda ty (substitution (i+1) t3 (lifting 1 0 t2))\n  end.\n\n\n(*Question 1.4.2*)\nTheorem no_index_sub: forall (t u: term) (i: nat), (C i t) -> substitution i t u = t.\nProof.\n  induction t; simpl; intros.\n  have:(beq_nat i n = false).\n  apply beq_nat_false_iff.\n  omega.\n  move => h0.\n  by rewrite h0.\n  trivial.\n  rewrite app_equivalence; split.\n  apply IHt1.\n  apply H.\n  apply IHt2.\n  apply H.\n  apply lambda_equivalence.\n  by apply IHt.\nQed.\n\nDefinition has_type (ctx: list typ) (t: term) := exists ty: typ, type ctx t = Some ty.\n\nLemma nth_of_list: forall (A: Type) (l: list A) (n: nat), n < length l <-> exists a: A, nth_error l n = Some a. \nProof.\n  intros A l.\n  split.\n  move: n.\n  induction l; simpl.\n  intros; omega.\n  intro; case n; simpl.\n  intros.\n  exists a.\n  done.\n  intros.\n  apply IHl.\n  omega.\n  intro h0.\n  case:h0.\n  move: n.\n  induction l; simpl.\n  intros.\n  have:nth_error nil n = None.\n  intros.\n  induction n.\n  by simpl.\n  by simpl.\n  intro.\n  by rewrite x0 in p.\n  intro.\n  case:n; simpl.\n  intros.\n  omega.\n  intros.\n  have: n < (length l) -> S n < S (length l).\n  omega.\n  intro h0; apply h0.\n  by apply (IHl _ x).\nQed.\n\nLemma app_is_typed: forall (t1 t2: term) (ctx: list typ), has_type ctx (App t1 t2) -> has_type ctx t1 /\\ has_type ctx t2.\nProof.\n  unfold has_type.\n  intros.\n  split.\n  case H.\n  intro.\n  simpl.\n  case (type ctx t1).\n  intros.  \n    by exists t.\n  intros.            \n  by exists x.\n  case H.\n  simpl.\n  case (type ctx t2).\n  case (type ctx t1).\n  intro.\n  case t.\n  intros.\n  done.\n  intros.\n  by exists t4.\n  intros.\n  done.\n  case (type ctx t1).\n  intro.\n  case t.\n  done.\n  done.\n  done.\nQed.  \n\nLemma omap_eq: forall (oty: option typ) (ty: typ), (exists t0:typ, omap oty ty = Some t0) -> (exists t1:typ, oty = Some t1).\nProof.\n  intros.\n  case:H.\n  intro.\n  unfold omap.\n  case oty.\n  intros.\n  by exists t.\n  done.\nQed.\n\n\n(*The converse is not true*)\nLemma typable_implies_closed: forall (t: term) (ctx: list typ), has_type ctx t -> C (length ctx) t.\nProof.\n  induction t; simpl.\n  unfold has_type.\n  simpl.\n  intros.\n  case H.\n  intros.\n  induction ctx; simpl.\n  have:nth_error nil n = None.\n  intros.\n  induction n.\n  by simpl.  simpl.\n  by simpl.\n  intro h0.\n  by rewrite h0 in H0.  \n  apply nth_of_list in H.\n  done.\n  intro.\n  done.\n  unfold has_type.\n  intros.\n  case H.\n  intros.\n  split.\n  apply IHt1.\n  apply (app_is_typed t1 t2 ctx).\n  done.\n  apply IHt2.\n  by apply (app_is_typed t1 t2 ctx).\n  intro.\n  unfold has_type.\n  simpl.\n  intros.\n  case:H.\n  intros x H0.\n  rewrite plus_comm.\n  apply (IHt (t::ctx)).\n  unfold has_type.\n  apply (omap_eq _ t).\n  by exists x.\nQed.\n", "meta": {"author": "pedrohaa", "repo": "untypedCoq", "sha": "89ba50c6c306a4e8b2a9d2114ccf1e944bacf8cf", "save_path": "github-repos/coq/pedrohaa-untypedCoq", "path": "github-repos/coq/pedrohaa-untypedCoq/untypedCoq-89ba50c6c306a4e8b2a9d2114ccf1e944bacf8cf/typedLambda.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6520641468900862}}
{"text": "(******************************************************************************)\n(* Dr Daniel Kirk (c) 2021                                                    *)\n(******************************************************************************)\n(* Let R : ringType and M : lmodType R                                        *)\n(******************************************************************************)\n(* lmodSetType M == a record consisting of a type 'sort' a function           *)\n(*                'elem' : sort -> M, and proofs of (injective elem)          *)\n(*                and (non_degenerate elem).                                  *)\n(*                injective elem == forall x y : T, elem x = elem y -> x = y  *)\n(*                non_degenerate elem == forall x : T, elem x != 0            *)\n(*                S : lmodSetType M coerces to its type T and function elem   *)\n(*                so b : S is shorthand for b : (sort S)                      *)\n(*                and S b for (elem S) b.                                     *)\n(******************************************************************************)\n(* Let S : lmodSetType M                                                      *)\n(******************************************************************************)\n(* typeIsNonDegenerate S == the proof that S is non_degenerate                *)\n(* typeIsInjective S == the proof that S  is injective                        *)\n(******************************************************************************)\n(*        li B     ==  forall C : lmodLCType B, lmodLC.li C.                  *)\n(*      span B     ==  forall m : M, {C : lmodLCType B |lmodLC.sumsTo C m}    *)\n(* lmodBasisType M == a record consisting of an lmodSetType sort and proofs   *)\n(*                    of li sort and span sort                                *)\n(******************************************************************************)\n(* Let B : lmodBasisType M                                                    *)\n(******************************************************************************)\n(*    basisLI B    ==  given (C : lmodLC B) and a proof of (lmodLCSumsTo C 0) *)\n(*                       returns proof of (C = nullFSType B)                  *)\n(*  basisSpanLC B  ==  given m : M, returns (C : lmodLC B) such that          *)\n(*                      (lmodLCSumsTo C m) is true                            *)\n(*  basisSpanEq B  ==  given m : M returns a proof of                         *)\n(*                          (lmodLCSumsTo (hasSpanLC B m) m)                  *)\n(******************************************************************************)\n(* lmodFinSetType M == a record consisting of a finType 'sort' and the        *)\n(*                     mixin of an lmodSetType for type sort.                 *)\n(*                     F : lmodBasisType M coerces to an lmodSetType          *)\n(*                     so f : F and F f work as for lmodSetType               *)\n(*                     However lmodFinSetType does not coerce to a finType    *)\n(*                     There is an explicit function for this                 *)\n(******************************************************************************)\n(* Let F : lmodFinSetType M                                                   *)\n(******************************************************************************)\n(* typeIsNonDegenerate F == the proof that F is non_degenerate                *)\n(* typeIsInjective F == the proof that F  is injective                        *)\n(* to_FinType F == the underlying finType of F                                *)\n(******************************************************************************)\n(* Note that all F : lmodFinSetType M are bijective to some ordinal type,     *)\n(* to establish the bijection we require:                                     *)\n(*  1) n : nat                                                                *)\n(*  2) and a proof K : n = size (enum (to_FinType F))                         *)\n(*  finBasis_to_ord K f == ordinal of 'I_n corresponding to f : F             *)\n(*  ord_to_finBasis K i == element of F corresponding to i : 'I_n             *)\n(******************************************************************************)\n(* lmodFinBasisType M == a record consisting of a lmodFinSetType sort and     *)\n(*                       a mixin of lmodBasisType for sort (which coerces to  *)\n(*                       lmodSetType M)                                       *)\n(******************************************************************************)\n(* Let B : lmodFinBasisType M                                                 *)\n(******************************************************************************)\n(* lmodFinBasis_to_lmodBasis B == the underlying lmodBasisType M              *)\n(******************************************************************************)\n\n\n\nRequire Import Coq.Program.Tactics.\nFrom Coq.Logic Require Import FunctionalExtensionality ProofIrrelevance.\nFrom mathcomp Require Import ssreflect ssrfun eqtype fintype seq bigop.\n\nRequire Import Modules Linears FiniteSupport lmodLC.\n\nSet Warnings \"-parsing\". (* Some weird bug in ssrbool throws out parsing warnings*)\n  From mathcomp Require Import ssrbool.\nSet Warnings \"parsing\".\n\nSet Warnings \"-ambiguous-paths\". (* Some weird bug in ssralg throws out coercion warnings*)\n    From mathcomp Require Import ssralg.\nSet Warnings \"ambiguous-paths\".\n\nOpen Scope ring_scope.\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n\nReserved Notation \"\\basisProj_ b ^( B )\"\n  (at level 36, B at level 36, b at level 0,\n    right associativity,\n          format \"'[' \\basisProj_ b '^(' B ) ']'\").\n\n\n\nModule lmodBasis.\n  Section Def.\n    Variable (R : ringType) (M : lmodType R).\n\n    Definition li (B : lmodSetType M)\n    := forall (C : lmodLCType B), lmodLC.li C.\n\n    Definition isnonzero (B : lmodSetType M) (T : seq (B*R)) := ~~has (eq_op^~0) (map snd T).\n    Lemma nonzero_cons (B : lmodSetType M) (T : lmodLCType B) (a : B*R) c : isnonzero (a::c) -> isnonzero c.\n    Proof. by rewrite/isnonzero/= negb_or -(rwP andP)=>U; rewrite (proj2 U). Qed.\n\n    Definition span (B : lmodSetType M)\n    := forall (m : M),\n        {C : lmodLCType B | (lmodLC.sumsTo C m)}.\n\n    Record mixin (B : lmodSetType M) := Mixin {\n      is_li : li B;\n      spans : span B;\n    }.\n\n    Record type := Pack { sort : _; class_of : mixin sort; }.\n\n    Definition hasLI (B : type) (C : lmodLCType (sort B)) := @is_li _ (class_of B) C.\n    Definition hasSpanLC (B : type) (m : M) := sval (@spans _ (class_of B) m).\n\n    Lemma hasSpanEq (B : type) (m : M) : lmodLC.sumsTo (hasSpanLC B m) m.\n    Proof. move: (proj2_sig (@spans _ (class_of B) m))=>P.\n      destruct P as [s [S Eq]].\n      refine(ex_intro _ s _); refine(ex_intro _ S _)=>//.\n    Qed.\n\n    Definition Build (T : eqType) (elem : T -> M)\n      (I : injective elem) (ND : non_degenerate elem)\n      (LI : li (lmodSet.Build I ND))\n      (Sp : span (lmodSet.Build I ND))\n    : type := Pack (Mixin LI Sp).\n\n    Local Coercion sort : type >-> lmodSetType.\n    Local Coercion class_of : type >-> mixin.\n  End Def.\n\n  Module Exports.\n    Notation lmodBasisType := type.\n    Notation basisLI := hasLI.\n    Notation basisSpanLC := hasSpanLC.\n    Notation basisSpanEq := hasSpanEq.\n    Coercion sort : type >-> lmodSetType.\n    Coercion class_of : type >-> mixin.\n  End Exports.\n  Export Exports.\n  \n  Section Results.\n    Export lmodBasis.Exports GRing.\n    Variable (R : ringType) (M : lmodType R) (B : type M).\n\n    Lemma sumsToZero_null (C : lmodLCType B) : lmodLC.sumsTo C 0 -> C = nullFSType R B.\n    Proof. move=>H; by apply (hasLI H). Qed.\n\n    Definition is_add_ind_fn (xy x y : M) := (fun i : B => (sval (spans B xy)) i - (sval (spans B x) i + sval (spans B y) i)).\n \n    Lemma is_additive (x y : M) : (hasSpanLC B x) <+> (hasSpanLC B y) = (hasSpanLC B (x + y)).\n    Proof.\n      move:(hasSpanEq B x) (hasSpanEq B y) (hasSpanEq B (x + y)).\n      rewrite/hasSpanLC lmodLC.eqFSFun/=/lmodLCSumsTo/==>Ex Ey Exy.\n      destruct Ex as [c [Uc [Fc Ex]]],  Ey as [d [Ud [Fd Ey]]], Exy as [cd [Ucd [Fcd Exy]]].\n\n      move:(fsFun.hasSupport_catl d Fc)=>Fc'; move/fsFun.hasSupport_undup\n        /(fsFun.hasSupport_catl cd)/fsFun.hasSupport_undup in Fc'.\n      move:(fsFun.hasSupport_catr c Fd)=>Fd'; move /fsFun.hasSupport_undup\n        /(fsFun.hasSupport_catl cd)/fsFun.hasSupport_undup in Fd'.\n\n      move:(fsFun.hasSupport_undup (fsFun.hasSupport_catr (undup (c ++ d)) Fcd))=>Fcd'.\n      rewrite (eqLCSumsTo Fc Fc' Uc (undup_uniq _)) in Ex; move/eqP in Ex.\n      rewrite (eqLCSumsTo Fd Fd' Ud (undup_uniq _)) in Ey; move/eqP in Ey.\n      rewrite (eqLCSumsTo Fcd Fcd' Ucd (undup_uniq _)) in Exy.\n      move: Exy; rewrite -{3}Ex-{3}Ey -big_split/= -subr_eq0 -sumrB.\n      under eq_bigr do rewrite -scalerDl -scalerBl; move=>Exy.\n\n      have FS: fsFun.hasSupport (is_add_ind_fn (x + y) x y)\n        (undup (undup (c ++ d) ++ cd)).\n      rewrite/is_add_ind_fn=>b C.\n      case(~~(sval (spans B x) b == 0)) as []eqn:Ec.\n      by apply (Fc' b Ec).\n      case(~~(sval (spans B y) b == 0)) as []eqn:Ed.\n      by apply (Fd' b Ed).\n      move/negbFE/eqP in Ec.\n      move/negbFE/eqP in Ed.\n      rewrite Ec Ed addr0 subr0 in C.\n      by apply (Fcd' b C).\n\n      have E: fsFun.finSuppE (is_add_ind_fn (x + y) x y).\n      refine(ex_intro _ (undup (undup (c ++ d) ++ cd)) _); split=>//; apply (undup_uniq _).\n\n      have S:lmodLCSumsTo (fsFun.Pack E) 0.\n      refine(ex_intro _ (undup (undup (c ++ d) ++ cd)) (ex_intro _ (undup_uniq _) _)).\n      apply(ex_intro _ FS Exy).\n\n      clear FS; move:(@hasLI _ _ B (fsFun.Pack E) S)=>/=K.\n      apply lmodLC.eqFSFun in K;simpl in K.\n      apply functional_extensionality=>b.\n      move:(equal_f K b)=>T.\n      move/eqP in T.\n      rewrite subr_eq0 eq_sym in T.\n      by move/eqP in T.\n    Qed.\n\n    Definition is_sca_ind_fn r (x : M) := (fun i => (sval (spans B (r *: x)) i) - r * (sval (spans B (x)) i)).\n \n    Lemma is_scalar (r : R) (x : M) : r <*:> (hasSpanLC B x) = (hasSpanLC B (r *: x)).\n    Proof.\n      move:(hasSpanEq B x) (hasSpanEq B (r *: x)).\n      rewrite/hasSpanLC lmodLC.eqFSFun/=/lmodLCSumsTo/==>Ex Erx.\n      destruct Ex as [c [Uc [Fc Ex]]], Erx as [d [Ud [Fd Erx]]].\n\n      move:(fsFun.hasSupport_undup (fsFun.hasSupport_catl d Fc))=>Fc'.\n      move:(fsFun.hasSupport_undup (fsFun.hasSupport_catr c Fd))=>Fd'.\n      \n      rewrite (eqLCSumsTo Fc Fc' Uc (undup_uniq _)) in Ex; move/eqP in Ex.\n      rewrite (eqLCSumsTo Fd Fd' Ud (undup_uniq _)) in Erx.\n      move: Erx; rewrite -{3}Ex -subr_eq0 scaler_sumr -sumrB.\n      under eq_bigr do rewrite scalerA -scalerBl; move=>Erx.\n\n      have FS: fsFun.hasSupport (is_sca_ind_fn r x)\n        (undup (c ++ d)).\n      rewrite /is_sca_ind_fn/fsFun.hasSupport=>b C.\n      case(~~(sval (spans B x) b == 0)) as []eqn:Ec.\n      by apply (Fc' b Ec).\n      move/negbFE/eqP in Ec.\n      rewrite Ec mulr0 subr0 in C.\n      apply (Fd' b C).\n\n      have E: finSuppE (is_sca_ind_fn r x).\n      refine(ex_intro _ (undup (c ++ d)) _); split=>//; apply (undup_uniq _).\n\n      have S:lmodLCSumsTo (fsFun.Pack E) 0.\n      refine(ex_intro _ (undup (c ++ d)) _);\n      apply (ex_intro _ (undup_uniq _) (ex_intro _ FS Erx)).\n\n      clear FS; move:(@hasLI _ _ B (fsFun.Pack E) S)=>/=K.\n      apply lmodLC.eqFSFun in K;simpl in K.\n      apply functional_extensionality=>b.\n      move:(equal_f K b)=>T.\n      move/eqP in T.\n      rewrite subr_eq0 eq_sym in T.\n      by move/eqP in T.\n    Qed.\n  End Results.\n\n  Section Coef.\n    Variable (R : ringType) (M : lmodType R) (B : type M).\n\n    Definition coef_raw (b : B) (m : M) : R\n      := (hasSpanLC B m) b.\n\n    Lemma coef_sca (b : B) : scalar (coef_raw b).\n    Proof. rewrite/coef_raw=>r x y.\n      by rewrite -is_additive -is_scalar/=.\n    Qed.\n\n    Definition coef b := Linear (coef_sca b).\n  End Coef.\n\n  Section Results.\n    Export lmodBasis.Exports GRing.\n    Variable (R : ringType) (M : lmodType R) (B : type M).\n\n    Lemma BasisElem_hasSupport (b : B) : hasSupport (hasSpanLC B (B b)) [:: b].\n    Proof.\n      move:(hasLI (lmodLC.sumToElem_sumToZero (hasSpanEq B (B b)))).\n      rewrite fsFun.eqFSFun/==>Z.\n      move=>c X.\n      move:(equal_f Z c)=>Y.\n      case(c == b) as []eqn:E.\n      by move/eqP in E; rewrite E in_cons eq_refl orTb.\n      rewrite addr0 in Y.\n      by rewrite Y eq_refl in X.\n    Qed.\n\n    Lemma orthonormP (b1 b2 : B) : coef b1 (B b2) = if b1 == b2 then 1 else 0.\n    Proof. rewrite/= /coef_raw.\n      move:(hasLI (lmodLC.sumToElem_sumToZero (hasSpanEq B (B b2)))).\n      rewrite fsFun.eqFSFun/==>S.\n      case(b1 == b2) as []eqn:E.\n        move/eqP in E; rewrite -E.\n        move:(equal_f S b1)=>Y.\n        by move/eqP in Y; rewrite -E eq_refl subr_eq0 in Y; move/eqP in Y.\n\n        move:(equal_f S b1)=>Y.\n        by rewrite E addr0 in Y.\n    Qed.\n\n    Lemma sum_trivialises (S : seq B) (U : uniq S) (b1 : B) (x : M) : (hasSupport (lmodBasis.hasSpanLC B x) S) ->\n      \\sum_(b2 <- S) (coef b1 (lmodBasis.hasSpanLC B x b2 *: B b2)) *: B b1\n      = (coef b1 x) *: B b1.\n    Proof. move=>H.\n      move:(lmodBasis.hasSpanEq B x)=>Z.\n      destruct Z as [s [U' [H' Z]]]; move/eqP in Z.\n      by rewrite -scaler_suml -linear_sum (eqLCSumsTo H H' U U')-{2}Z.\n    Qed.\n  End Results.\n\n  Section Isomorphism.\n    Export lmodBasis.Exports GRing.\n    Variable (R : ringType) (M1 M2 : lmodType R) (f : linIsomType M1 M2)\n    (B : type M1).\n    Lemma inj_ : injective (f \\o B).\n    Proof. rewrite/comp=>x y H.\n      move: (congr1 (inv(f)) H).\n      rewrite !isomlK=>H2.\n      apply (typeIsInjective H2).\n    Qed.\n    Lemma nondeg_ : non_degenerate (f \\o B).\n    Proof. move=>b.\n      rewrite -(rwP negP) -(rwP eqP)=>H.\n      move: (congr1 (inv(f)) H).\n      rewrite !isomlK linear0 (rwP eqP)=>H2.\n      move: (@typeIsNonDegenerate _ _ _ b).\n      by rewrite H2.\n    Qed.\n    Definition bset := lmodSet.Build inj_ nondeg_.\n\n    Lemma li_ : li bset.\n    Proof. rewrite/bset=> C H.\n      destruct C as [coef [c [U E]]].\n      destruct H as [s [Us [H S]]].\n      move:coef s Us E H S.\n      rewrite /lmodSet.to_Type/=.\n      move=>coef s Us E H S.\n      rewrite fsFun.eqFSFun/=; clear c U E.\n\n      move/eqP/(congr1 (isom_linmapI f)) in S; move:S.\n      rewrite /comp linear_sum linear0.\n      under eq_bigr do rewrite linearZ_LR/=(linIsom.isomfK f).\n      rewrite(rwP eqP)=>/=S.\n\n      have J : finSuppE coef.\n      refine (ex_intro _ s _); split=>//.\n\n      have K : lmodLCSumsTo (fsFun.Pack J) 0 by\n      apply (ex_intro _ s (ex_intro _ Us (ex_intro _ H S))).\n\n      move:(hasLI K); by rewrite eqFSFun.\n    Qed.\n\n    Lemma span_ : lmodBasis.span bset.\n    Proof. move=>m; move: (hasSpanEq B (inv(f) m))=>X.\n      destruct (hasSpanLC B (inv(f) m)) as [coef E].\n      have FS: fsFun.finSuppE (B:=bset) coef by\n      destruct E as [e [U F]];\n      refine(ex_intro _ e _); split=>//.\n      refine (exist _ (fsFun.Pack FS) _).\n      destruct X as [c [U [D S]]].\n      refine (ex_intro _ c (ex_intro _ U (ex_intro _ D _))).\n      move/eqP/(congr1 f)/eqP in S; move:S.\n      rewrite isomKl linear_sum.\n      by under eq_bigr do rewrite linearZ.\n    Qed.\n\n    Definition isomorphicBasis : type M2\n      := Build li_ span_.\n  End Isomorphism.\nEnd lmodBasis.\nExport lmodBasis.Exports.\n\nNotation \"\\basisProj_ b ^( B )\" := (@lmodBasis.coef _ _ B b) : lmod_scope.\n\n\n\n\n\nModule lmodFinSet.\n  Section Def.\n    Variable (R : ringType) (M : lmodType R).\n    Record class (T : finType) := Class {\n      base : lmodSet.mixin M T;\n    }.\n\n    Record type := Pack { sort : _; class_of : class sort; }.\n\n    Definition Build {T : finType} (elem : T -> M) (I : injective elem) (ND : non_degenerate elem)\n    := Pack (Class (lmodSet.Build I ND)).\n\n    Section Seq.\n      Variable (s : seq M) (H : all (fun m => m != 0) s).\n      Definition elem_seq (t : seq_sub s) : M := ssval t.\n      Lemma inj_seq : injective elem_seq.\n        rewrite /elem_seq/==>x y W.\n        by rewrite (rwP eqP)/eq_op/= W.\n      Qed.\n      Lemma nondeg_seq : non_degenerate elem_seq.\n      Proof. rewrite/elem_seq/==>x.\n        move:H=>H2; move/allP in H2.\n        by move:(H2 (ssval x) (ssvalP x)).\n      Qed.\n      Definition seq := Build inj_seq nondeg_seq.\n    End Seq.\n\n    Section Lemmas.\n      Variable (T : type).\n      Definition to_set\n      := lmodSet.Pack (base (class_of T)).\n\n      Variable (n : nat) (K : n = size (enum (sort T))).\n      Definition to_ord : sort T -> 'I_n :=\n      eq_rect_r (fun n : nat => sort T -> 'I_n) \n        (eq_rect #|sort T| (fun n : nat => sort T -> 'I_n)\n          enum_rank (size (enum (sort T))) (cardT (sort T))) K.\n\n      Definition from_ord : 'I_n -> sort T :=\n      eq_rect_r (fun n : nat => 'I_n -> sort T) \n        (eq_rect #|sort T| (fun n : nat => 'I_n -> sort T)\n          enum_val (size (enum (sort T))) (cardT (sort T))) K.\n\n      Lemma from_ordK : cancel to_ord from_ord.\n      Proof. rewrite/to_ord/from_ord/eq_rect_r/eq_rect.\n        destruct (cardT (sort T)), (Logic.eq_sym K)=>x.\n        by rewrite enum_rankK.\n      Qed.\n\n      Lemma to_ordK : cancel from_ord to_ord.\n      Proof. rewrite/to_ord/from_ord/eq_rect_r/eq_rect.\n        destruct (cardT (sort T)), (Logic.eq_sym K)=>x.\n        by rewrite enum_valK.\n      Qed.\n    End Lemmas.\n  End Def.\n\n  Module Exports.\n    Notation lmodFinSetType := type.\n    Notation to_FinType := sort.\n    Coercion to_set : type >-> lmodSetType.\n    Notation finBasis_to_ord := to_ord.\n    Notation ord_to_finBasis := from_ord.\n    Notation finBasis_to_ordK := to_ordK.\n    Notation ord_to_finBasisK := from_ordK.\n  End Exports.\nEnd lmodFinSet.\nExport lmodFinSet.Exports.\n\nModule lmodFinBasis.\n  Section Def.\n    Variable (R : ringType) (M : lmodType R).\n    Record mixin (T : lmodFinSetType M) := Mixin {\n      base : lmodBasis.mixin T;\n    }.\n\n    Record type := Pack { sort : _; class_of : mixin sort; }.\n\n    Definition Build (T : finType) (elem : T -> M)\n    (I : injective elem) (ND : non_degenerate elem)\n    (LI : lmodBasis.li (lmodFinSet.Build I ND))\n    (Sp : lmodBasis.span (lmodFinSet.Build I ND))\n    : type := Pack (Mixin (lmodBasis.Mixin LI Sp)).\n\n    Definition basis_number (B : type) := #|(to_FinType (sort B))|.\n\n    Lemma typeSpanning (T : type) : lmodBasis.span (sort T).\n    Proof. destruct T as [t B], B as [B], B; apply spans. Qed.\n\n    Lemma typeLI (T : type) : lmodBasis.li (sort T).\n    Proof. destruct T as [t B], B as [B], B; apply is_li. Qed.\n  End Def.\n\n  Section To.\n    Variable (R : ringType) (M : lmodType R).\n    Definition to_lmodBasis (B : type M)\n    := lmodBasis.Pack (base (class_of B)).\n  End To.\n  Section From.\n    Variable (R : ringType) (M : lmodType R) (T : lmodBasisType M) (finClass : Finite.class_of T).\n\n    Definition bset := @lmodFinSet.Build _ M (Finite.Pack finClass) T (@typeIsInjective _ _ T) (@typeIsNonDegenerate _ _ T).\n    Lemma hasFinSuppP coef s : fsFun.hasSupport (B:=T) coef s <-> fsFun.hasSupport (R:=R) (B:=bset) coef s.\n    Proof. split=>H b W; move:(H b W);\n        [rewrite -(mem_map (f:=fun b : T => b : bset))| rewrite -(mem_map (f:=fun b : bset => b : T))];\n        by [rewrite map_id | |rewrite map_id |].\n    Qed.\n    Lemma finSupp_uniqP s : @uniq (lmodSet.sort T) s <-> @uniq (lmodSet.sort bset) s. \n    Proof. split=>U.\n      by rewrite -(map_inj_in_uniq (f:=fun b : T => b : bset)) in U; [rewrite map_id in U|].\n      by rewrite -(map_inj_in_uniq (f:=fun b : bset => b : T)) in U; [rewrite map_id in U|].\n    Qed.\n\n    Lemma finSuppP coef : fsFun.finSuppE (B:=T) coef <-> fsFun.finSuppE (R:=R) (B:=bset) coef.\n    Proof. split=>H; destruct H as [s [U F]]; refine(ex_intro _ s _).\n      move/finSupp_uniqP in U; split=>//.\n      by move/hasFinSuppP in F.\n\n      move/finSupp_uniqP in U; split=>//.\n      by move/hasFinSuppP in F.\n    Qed.\n\n    Lemma lmodLCSumsToP (C : lmodLCType bset) (E : fsFun.finSuppE (B:=T) C) m\n    : lmodLCSumsTo (B:=bset) C m <-> lmodLCSumsTo (fsFun.Pack E) m.\n    rewrite/bset/=/lmodFinSet.to_set/=/lmodLCSumsTo/=.\n    split=>H; destruct H as [s [U [H S]]];\n    move/finSupp_uniqP in U;\n    move/hasFinSuppP in H;\n    apply (ex_intro _ s (ex_intro _ U (ex_intro _ H S))).\n    Qed.\n\n    Lemma li_ : lmodBasis.li bset.\n    Proof.\n      move=>/=C S.\n      have E: fsFun.finSuppE (B := T) C.\n      rewrite finSuppP.\n      destruct C as [coef C].\n      by apply C.\n      move/(lmodLCSumsToP E) in S.\n      move:(lmodBasis.hasLI S).\n      by rewrite !lmodLC.eqFSFun.\n    Qed.\n\n    Lemma span_ : lmodBasis.span bset.\n    Proof. move=>m.\n      move: (lmodBasis.hasSpanEq T m)=>X.\n\n      have E: fsFun.finSuppE (B := bset) (lmodBasis.hasSpanLC T m) by\n      clear X;destruct (lmodBasis.hasSpanLC T m) as [coef C]=>/=;\n      move/finSuppP in C.\n\n      refine (exist _ (fsFun.Pack E) _).\n      destruct X as [s [U [H S]]].\n      move/finSupp_uniqP in U;\n      move/hasFinSuppP in H;\n      apply(ex_intro _ s (ex_intro _ U (ex_intro _ H S))).\n    Qed.\n    \n    Definition from_lmodBasis : type M\n    := Build li_ span_.\n  End From.\n\n  Module Exports.\n    Notation basis_number := basis_number.\n    Notation lmodFinBasisType := type.\n    Coercion class_of : type >-> mixin.\n    Coercion sort : type >-> lmodFinSetType.\n    Coercion to_lmodBasis : type >-> lmodBasisType.\n    Notation lmodBasis_to_finLmodBasis := from_lmodBasis.\n    Notation lmodFinBasis_to_lmodBasis := to_lmodBasis.\n  End Exports.\n\n  Section Results.\n    Export Exports GRing.\n    Variable (R : ringType) (M : lmodType R) (B : type M) (x : M).\n    Lemma hasSupport_enum: hasSupport (lmodBasis.hasSpanLC B x) (enum B).\n    Proof. move=>b B'; by rewrite mem_enum. Qed.\n\n    End Results.\nEnd lmodFinBasis.\nExport lmodFinBasis.Exports.\n\nClose Scope ring_scope.\n", "meta": {"author": "Modularius", "repo": "MathcompFreeModules", "sha": "5731747c5bcbafe914687d44e74f112632f07ec7", "save_path": "github-repos/coq/Modularius-MathcompFreeModules", "path": "github-repos/coq/Modularius-MathcompFreeModules/MathcompFreeModules-5731747c5bcbafe914687d44e74f112632f07ec7/theories/Modules/Basis.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6520218032569041}}
{"text": "(* ---------------------------------------------------------------------\n   This file contains definitions and proof scripts related to \n   (i) closure operations for context-free grammars, \n   (ii) context-free grammars simplification \n   (iii) context-free grammar Chomsky normalization and \n   (iv) pumping lemma for context-free languages.\n   \n   More information can be found in the paper \"Formalization of the\n   Pumping Lemma for Context-Free Languages\", submitted to JFR.\n   \n   Marcus Vinícius Midena Ramos\n   mvmramos@gmail.com\n   --------------------------------------------------------------------- *)\n   \n(* --------------------------------------------------------------------- *)\n(* SIMPLIFICATION - UNIT RULES                                           *)\n(* --------------------------------------------------------------------- *)\n\nRequire Import List.\nRequire Import Ring.\nRequire Import Omega.\n\nRequire Import misc_arith.\nRequire Import misc_list.\nRequire Import cfg.\nRequire Import useless.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport ListNotations.\nOpen Scope list_scope.\n\n(* --------------------------------------------------------------------- *)\n(* SIMPLIFICATION - UNIT RULES - DEFINITIONS                             *)\n(* --------------------------------------------------------------------- *)\n\nSection UnitRules.\n\nVariables terminal non_terminal: Type.\nNotation sf := (list (non_terminal + terminal)).\nNotation sentence := (list terminal).\nNotation term_lift:= ((terminal_lift non_terminal) terminal).\nNotation nlist:= (list non_terminal).\nNotation tlist:= (list terminal).\n\nInductive unit (g: cfg non_terminal terminal) (a: non_terminal): non_terminal -> Prop:=\n| unit_rule: forall (b: non_terminal),\n             rules g a [inl b] -> unit g a b\n| unit_trans: forall b c: non_terminal,\n              unit g a b ->\n              unit g b c ->\n              unit g a c.\n\nInductive g_unit_rules (g: cfg _ _): non_terminal -> sf -> Prop :=\n| Lift_direct' : \n       forall left: non_terminal,\n       forall right: sf,\n       (forall r: non_terminal,\n       right <> [inl r]) -> rules g left right ->\n       g_unit_rules g left right\n| Lift_indirect':\n       forall a b: non_terminal,\n       unit g a b ->\n       forall right: sf,\n       rules g b right ->  \n       (forall c: non_terminal,\n       right <> [inl c]) -> \n       g_unit_rules g a right.\n\nLemma unit_exists_right:\nforall g: cfg _ _,\nforall a b: non_terminal,\nunit g a b ->\nexists c : sf, rules g a c.\nProof.\nintros g a b H.\ninduction H.\n- exists [inl b].\n  exact H.\n- exact IHunit1.\nQed.\n\nLemma unit_exists_left:\nforall g: cfg _ _,\nforall a c: non_terminal,\nunit g a c ->\nexists b : non_terminal, rules g a [inl b].\nProof.\nintros g a c H.\ninduction H.\n- exists b.\n  exact H.\n- exact IHunit1. \nQed.\n\nLemma g_unit_finite:\nforall g: cfg _ _,\nexists n: nat,\nexists ntl: nlist,\nexists tl: tlist,\nIn (start_symbol g) ntl /\\\nforall left: non_terminal,\nforall right: sf,\ng_unit_rules g left right ->\n(length right <= n) /\\\n(In left ntl) /\\\n(forall s: non_terminal, In (inl s) right -> In s ntl) /\\\n(forall s: terminal, In (inr s) right -> In s tl).\nProof.\nintros g.\ndestruct (rules_finite g) as [n [ntl [tl H1]]].\nexists n, ntl, tl.\nsplit.\n- destruct H1 as [H1 _].\n  exact H1.\n- destruct H1 as [_ H1].\n  intros left right H2.\n  inversion H2.\n  + subst.\n    specialize (H1 left right H0).\n    destruct H1 as [H4 [H5 H6]].\n    split.\n    * exact H4.\n    * {\n      split.\n      - exact H5.\n      - exact H6.\n      }\n  + subst.\n    apply unit_exists_right in H.\n    destruct H as [c H4].\n    split.\n    * specialize (H1 b right H0).\n      destruct H1 as [H1 _].\n      exact H1.\n    * {\n      split.\n      - specialize (H1 left c H4).\n        destruct H1 as [_ [H1 _]].\n        exact H1.\n      - specialize (H1 b right H0).\n        destruct H1 as [_ [_ H1]].\n        exact H1.\n      }  \nQed.\n\nDefinition g_unit (g: cfg _ _): cfg _ _ := {|\nstart_symbol:= start_symbol g;\nrules:= g_unit_rules g;\nt_eqdec:= t_eqdec g;\nnt_eqdec:= nt_eqdec g;\nrules_finite:= g_unit_finite g\n|}.\n\n(* --------------------------------------------------------------------- *)\n(* SIMPLIFICATION - UNIT RULES - LEMMAS AND THEOREMS                     *)\n(* --------------------------------------------------------------------- *)\n\nLemma unit_not_unit:\nforall g: cfg _ _,\nforall a b: non_terminal,\n~ unit (g_unit g) a b.\nProof.\nintros g a0 b0 H.\ninduction H.\n- inversion H.\n  + specialize (H0 b).\n    destruct H0.\n    reflexivity.\n  + specialize (H2 b).\n    destruct H2.\n    reflexivity.\n- exact IHunit1.\nQed.\n\nLemma unit_derives:\nforall g: cfg _ _,\nforall a b: non_terminal,\nunit g a b ->\nderives g [inl a] [inl b].\nProof.\nintros g a b H.\ninduction H.\n- apply derives_start.\n  exact H.\n- apply derives_trans with (s2:=[inl b]).\n  + exact IHunit1.\n  + exact IHunit2.\nQed.\n\nLemma rules_g_unit_g:\nforall g: cfg _ _,\nforall left: non_terminal,\nforall right: sf,\nrules (g_unit g) left right ->\nrules g left right \\/ derives g [inl left] right.\nProof.\nintros g left right H.\nsimpl in H.\ninversion H.\n- left.\n  exact H1.\n- right.\n  subst.\n  replace right with ([] ++ right ++ []).\n  + apply derives_step with (left:=b).\n    * apply unit_derives in H0.\n      exact H0.\n    * exact H1.\n  + rewrite app_nil_l. \n    rewrite app_nil_r.\n    reflexivity.\nQed.\n\nLemma rules_g_unit_g':\nforall g: cfg _ _,\nforall left: non_terminal,\nforall right: sf,\nrules (g_unit g) left right ->\nrules g left right \\/ \nexists left': non_terminal, unit g left left' /\\ rules g left' right.\nProof.\nintros g left right H.\ninversion H.\n- left.\n  exact H1.\n- right. \n  exists b.\n  split.\n  + exact H0.\n  + exact H1.\nQed.\n\nLemma rules_g_unit_not_unit:\nforall g: cfg _ _,\nforall left: non_terminal,\nforall right: sf,\n(rules (g_unit g) left right) ->\n(~ exists n: non_terminal, right = [inl n]).\nProof.\nintros g left right H1 H2.\ninversion H1.\n- subst.\n  destruct H2 as [n H2]. \n  specialize (H n).\n  contradiction.\n- subst.\n  destruct H2 as [n H2]. \n  specialize (H3 n).\n  contradiction.\nQed.\n\nLemma generates_g_unit_g:\nforall g: cfg _ _,\nforall s: sf,\ngenerates (g_unit g) s -> generates g s.\nProof.\nunfold generates.\nintros g s H.\nsimpl in H.\nremember [inl (start_symbol g)] as w1. \ninduction H.\n- apply derives_refl.\n- apply rules_g_unit_g in H0.\n  destruct H0 as [H0 | H0].\n  + apply derives_step with (left:=left).\n    * apply IHderives.\n      exact Heqw1.\n    * exact H0.\n  + apply derives_subs with (s3:=[inl left]).\n    * apply IHderives.\n      exact Heqw1.\n    * exact H0.\nQed.\n\nLemma rules_g_g_unit:\nforall g: cfg _ _,\nforall left: non_terminal,\nforall right: sf,\nrules g left right ->\n(forall n: non_terminal, right <> [inl n]) ->\nrules (g_unit g) left right.\nProof.\nintros g left right H1 H2.\nsimpl. \napply Lift_direct'.\n- exact H2.\n- exact H1.\nQed.\n\nLemma derives3_g_g_unit:\nforall g: cfg _ _,\nforall n: non_terminal,\nforall s: sentence, \nderives3 g n s -> derives3 (g_unit g) n s. \nProof.\nintros g.\nintros n s H.\napply derives3_ind_2 with (g:=g) (P:=derives3 (g_unit g)) (P0:=derives3_aux (g_unit g)).\n- intros n0 lt H1.\n  apply derives3_rule.\n  apply rules_g_g_unit in H1.\n  + exact H1. \n  + destruct lt; discriminate.\n- intros n0 ltnt lt H1 H2 H3.\n  destruct ltnt.\n  + apply rules_g_g_unit in H1.\n    * inversion H2. \n      subst. \n      apply derives3_rule.\n      exact H1. \n    * discriminate.\n  + destruct ltnt.\n    * {\n      destruct s0. \n      - apply exists_rule_derives3_aux in H2.\n        destruct H2 as [H2 | H2].\n        + assert (H10: rules (g_unit g) n0 (map term_lift lt)).\n            {\n            apply Lift_indirect' with (b:=n1).\n            * apply unit_rule.\n              exact H1.\n            * exact H2. \n            * destruct lt; discriminate.\n            }\n          apply derives3_rule.\n          exact H10.\n        + destruct H2 as [right [H4 H5]].\n          apply exists_rule_derives3_aux in H3.\n          destruct H3 as [H3 | H3].\n          * apply rules_g_unit_g' in H3.\n            {\n            destruct H3 as [H3 | H3].\n            - assert (H10: rules (g_unit g) n0 (map term_lift lt)).\n                {\n                apply Lift_indirect' with (b:=n1).\n                - apply unit_rule.\n                  exact H1.\n                - exact H3.\n                - intros c0.\n                  destruct lt. \n                  + discriminate.\n                  + discriminate.\n                }  \n              apply derives3_rule.\n              exact H10.\n            - destruct H3 as [left' [H6 H7]].\n              assert (H10: rules (g_unit g) n0 (map term_lift lt)).\n                {\n                apply Lift_indirect' with (b:=left').\n                - apply unit_trans with (b:=n1).\n                  + apply unit_rule.\n                    exact H1.\n                  + exact H6.\n                - exact H7.\n                - intros c0.\n                  destruct lt; discriminate.\n                }\n              apply derives3_rule.\n              exact H10.\n            }\n          * destruct H3 as [right0 [H6 H7]].\n            assert (H6':=H6).\n            apply rules_g_unit_not_unit in H6'.\n            apply rules_g_unit_g' in H6.\n            {\n            destruct H6 as [H6 | H6].\n            - apply derives3_step with (ltnt:=right0).\n              + apply Lift_indirect' with (b:=n1).\n                * apply unit_rule.\n                  exact H1.\n                * exact H6.\n                * apply not_exists_forall_not.\n                  exact H6'.\n              + exact H7.\n            - apply derives3_step with (ltnt:=right0).\n              + destruct H6 as [left' [H8 H9]].\n                apply Lift_indirect' with (b:=left').\n                * {\n                  apply unit_trans with (b:=n1).\n                  - apply unit_rule.\n                    exact H1.\n                  - exact H8.\n                  }\n                * exact H9.\n                * apply not_exists_forall_not.\n                  exact H6'.\n              + exact H7.\n            }  \n      - apply rules_g_g_unit in H1.\n        + apply derives3_step with (ltnt:=[inr t]).\n          * exact H1.\n          * exact H3.\n        + discriminate.\n      }\n    * {\n      apply rules_g_g_unit in H1.\n      - apply derives3_step with (ltnt:=(s0 :: s1 :: ltnt)).\n        + exact H1.\n        + exact H3.\n      - discriminate.\n      }\n- apply derives3_aux_empty.\n- intros t ltnt lt H1 H2.\n  apply derives3_aux_t.\n  exact H2.\n- intros n0 lt lt' ltnt H1 H2 H3 H4.\n  apply derives3_aux_nt.\n  + exact H2.\n  + exact H4.\n- exact H.\nQed.\n\nLemma derives_g_g_unit:\nforall g: cfg _ _,\nforall s: sentence,\nforall n: non_terminal,\nderives g [inl n] (map term_lift s) -> derives (g_unit g) [inl n] (map term_lift s).\nProof.\nintros g s n.\nrepeat rewrite derives_equiv_derives3.\napply derives3_g_g_unit.\nQed.\n\nTheorem g_equiv_unit:\nforall g: cfg _ _,\ng_equiv (g_unit g) g.\nProof.\nunfold g_equiv.\nunfold produces.\nintros g s.\nsplit.\n- apply generates_g_unit_g.\n- apply derives_g_g_unit.\nQed.\n\nDefinition has_no_unit_rules (g: cfg _ _): Prop:=\nforall left n: non_terminal,\nforall right: sf,\nrules g left right -> right <> [inl n].\n\nLemma g_unit_has_no_unit_rules:\nforall g: cfg _ _,\nhas_no_unit_rules (g_unit g).\nProof.\nunfold has_no_unit_rules.\nintros g left n right H.\ndestruct right.\n- apply nil_cons.\n- inversion_clear H.\n  + specialize (H0 n). \n    exact H0.\n  + specialize (H2 n). \n    exact H2.\nQed.\n\nTheorem g_unit_correct: \nforall g: cfg _ _,\ng_equiv (g_unit g) g /\\\nhas_no_unit_rules (g_unit g).\nProof.\nintros g.\nsplit.\n- apply g_equiv_unit.\n- apply g_unit_has_no_unit_rules.\nQed.\n\nEnd UnitRules.\n", "meta": {"author": "mvmramos", "repo": "pumping", "sha": "d8e2db890a4eb2c25bb0ef8efffa1d83031619f9", "save_path": "github-repos/coq/mvmramos-pumping", "path": "github-repos/coq/mvmramos-pumping/pumping-d8e2db890a4eb2c25bb0ef8efffa1d83031619f9/unitrules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.6520217977408181}}
{"text": "Require Import Sets.\n\nDefinition Monotonic {L:Set} (rel:L->L->Prop) (f:L->L) := forall x y, rel x y -> rel (f x) (f y).\n\nDefinition Compatible {L:Set} (f:L->L) (S: Pow L) := forall x, x ∈ S -> (f x) ∈ S.\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/Functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6519894691128155}}
{"text": "Require Export ifTf.\n\n(** This library defines a theorem [IFIDEMP] and its proof. Notice that we use [#] (resp. [##]) for [message] (resp. [Bool]) in lieu of [=].\n\n [if b then (if b then x1 else y1) else (if b then x2 else y2) # if b then x1 else y2] *)\n\nTheorem IFIDEMP_B : forall (n: nat)(b1 b2 b3 b4 : Bool), (IF (Bvar n) then (IF (Bvar n) then b1 else b2) else (IF (Bvar n) then b3 else b4)) ## (IF (Bvar n) then b1 else b4).\nProof.\nintros n b1 b2 b3 b4.\nrewrite IFEVAL_B with (b1:= IF (Bvar n) then b1 else b2)(b2 := (IF (Bvar n) then b3 else b4)) .\nsimpl.\nrewrite <-beq_nat_refl.\nrewrite IFTRUE_B.\nrewrite IFFALSE_B.\nrewrite IFEVAL_B with(b2:=b4).\nreflexivity.               \nQed.\n \nTheorem IFIDEMP_M : forall (n: nat)(x1 x2 y1 y2 : message),  (If (Bvar n) then (If (Bvar n) then x1 else y1) else (If (Bvar n) then x2 else y2)) # (If (Bvar n) then x1 else y2).\nProof.\nintros n x1 x2 y1 y2 .\nrewrite IFEVAL_M with (t1:= If (Bvar n) then x1 else y1)(t2 := (If (Bvar n) then x2 else y2)) .\nsimpl.\nrewrite <-beq_nat_refl.\nrewrite IFTRUE_M.\nrewrite IFFALSE_M. \nrewrite IFEVAL_M with (t2:=y2).\nreflexivity.\nQed.\n ", "meta": {"author": "ajayeeralla", "repo": "vote_privacy_proofs", "sha": "87a689040f7c4f4cb8bb0434efcef0fa0bb01a96", "save_path": "github-repos/coq/ajayeeralla-vote_privacy_proofs", "path": "github-repos/coq/ajayeeralla-vote_privacy_proofs/vote_privacy_proofs-87a689040f7c4f4cb8bb0434efcef0fa0bb01a96/src/voteprivacy/ifIdemp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6519661205099514}}
{"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.\n\n(* Hack so that Why3 does not override the notation below.\n\n(* Why3 assumption *)\nDefinition divides (d:Z) (n:Z): Prop := exists q:Z, (n = (q * d)%Z).\n\n*)\n\nRequire Import Znumtheory.\nNotation divides := Zdivide (only parsing).\n\n(* Why3 goal *)\nLemma divides_refl : forall (n:Z), (divides n n).\nProof.\nexact Zdivide_refl.\nQed.\n\n(* Why3 goal *)\nLemma divides_1_n : forall (n:Z), (divides 1%Z n).\nProof.\nexact Zone_divide.\nQed.\n\n(* Why3 goal *)\nLemma divides_0 : forall (n:Z), (divides n 0%Z).\nProof.\nexact Zdivide_0.\nQed.\n\n(* Why3 goal *)\nLemma divides_left : forall (a:Z) (b:Z) (c:Z), (divides a b) -> (divides\n  (c * a)%Z (c * b)%Z).\nProof.\nexact Zmult_divide_compat_l.\nQed.\n\n(* Why3 goal *)\nLemma divides_right : forall (a:Z) (b:Z) (c:Z), (divides a b) -> (divides\n  (a * c)%Z (b * c)%Z).\nProof.\nexact Zmult_divide_compat_r.\nQed.\n\n(* Why3 goal *)\nLemma divides_oppr : forall (a:Z) (b:Z), (divides a b) -> (divides a (-b)%Z).\nProof.\nexact Zdivide_opp_r.\nQed.\n\n(* Why3 goal *)\nLemma divides_oppl : forall (a:Z) (b:Z), (divides a b) -> (divides (-a)%Z b).\nProof.\nexact Zdivide_opp_l.\nQed.\n\n(* Why3 goal *)\nLemma divides_oppr_rev : forall (a:Z) (b:Z), (divides (-a)%Z b) -> (divides a\n  b).\nProof.\nexact Zdivide_opp_l_rev.\nQed.\n\n(* Why3 goal *)\nLemma divides_oppl_rev : forall (a:Z) (b:Z), (divides a (-b)%Z) -> (divides a\n  b).\nProof.\nexact Zdivide_opp_r_rev.\nQed.\n\n(* Why3 goal *)\nLemma divides_plusr : forall (a:Z) (b:Z) (c:Z), (divides a b) -> ((divides a\n  c) -> (divides a (b + c)%Z)).\nProof.\nexact Zdivide_plus_r.\nQed.\n\n(* Why3 goal *)\nLemma divides_minusr : forall (a:Z) (b:Z) (c:Z), (divides a b) -> ((divides a\n  c) -> (divides a (b - c)%Z)).\nProof.\nexact Zdivide_minus_l.\nQed.\n\n(* Why3 goal *)\nLemma divides_multl : forall (a:Z) (b:Z) (c:Z), (divides a b) -> (divides a\n  (c * b)%Z).\nProof.\nintros a b c.\napply Zdivide_mult_r.\nQed.\n\n(* Why3 goal *)\nLemma divides_multr : forall (a:Z) (b:Z) (c:Z), (divides a b) -> (divides a\n  (b * c)%Z).\nProof.\nexact Zdivide_mult_l.\nQed.\n\n(* Why3 goal *)\nLemma divides_factorl : forall (a:Z) (b:Z), (divides a (b * a)%Z).\nProof.\nexact Zdivide_factor_l.\nQed.\n\n(* Why3 goal *)\nLemma divides_factorr : forall (a:Z) (b:Z), (divides a (a * b)%Z).\nProof.\nexact Zdivide_factor_r.\nQed.\n\n(* Why3 goal *)\nLemma divides_n_1 : forall (n:Z), (divides n 1%Z) -> ((n = 1%Z) \\/\n  (n = (-1%Z)%Z)).\nProof.\nexact Zdivide_1.\nQed.\n\n(* Why3 goal *)\nLemma divides_antisym : forall (a:Z) (b:Z), (divides a b) -> ((divides b\n  a) -> ((a = b) \\/ (a = (-b)%Z))).\nProof.\nexact Zdivide_antisym.\nQed.\n\n(* Why3 goal *)\nLemma divides_trans : forall (a:Z) (b:Z) (c:Z), (divides a b) -> ((divides b\n  c) -> (divides a c)).\nProof.\nexact Zdivide_trans.\nQed.\n\n(* Why3 goal *)\nLemma divides_bounds : forall (a:Z) (b:Z), (divides a b) -> ((~ (b = 0%Z)) ->\n  ((ZArith.BinInt.Z.abs a) <= (ZArith.BinInt.Z.abs b))%Z).\nProof.\nexact Zdivide_bounds.\nQed.\n\nImport EuclideanDivision.\n\n(* Why3 goal *)\nLemma mod_divides_euclidean : forall (a:Z) (b:Z), (~ (b = 0%Z)) ->\n  (((int.EuclideanDivision.mod1 a b) = 0%Z) -> (divides b a)).\nProof.\nintros a b Zb H.\nexists (div a b).\nrewrite (Div_mod a b Zb) at 1.\nrewrite H.\nring.\nQed.\n\n(* Why3 goal *)\nLemma divides_mod_euclidean : forall (a:Z) (b:Z), (~ (b = 0%Z)) -> ((divides\n  b a) -> ((int.EuclideanDivision.mod1 a b) = 0%Z)).\nProof.\nintros a b Zb H.\nassert (Zmod a b = Z0).\nnow apply Zdivide_mod.\nunfold mod1, div.\nrewrite H0.\ncase Z_le_dec ; intros H1.\nrewrite (Z_div_exact_full_2 a b Zb H0) at 1.\napply Zminus_diag.\nnow elim H1.\nQed.\n\n(* Why3 goal *)\nLemma mod_divides_computer : forall (a:Z) (b:Z), (~ (b = 0%Z)) ->\n  (((ZArith.BinInt.Z.rem a b) = 0%Z) -> (divides b a)).\nProof.\nintros a b Zb H.\nexists (Z.quot a b).\nrewrite Zmult_comm.\nnow apply Zquot.Z_quot_exact_full.\nQed.\n\n(* Why3 goal *)\nLemma divides_mod_computer : forall (a:Z) (b:Z), (~ (b = 0%Z)) -> ((divides b\n  a) -> ((ZArith.BinInt.Z.rem a b) = 0%Z)).\nProof.\nintros a b Zb (q,H).\nrewrite H.\napply Zquot.Z_rem_mult.\nQed.\n\n(* Why3 goal *)\nLemma even_divides : forall (a:Z), (number.Parity.even a) <-> (divides 2%Z\n  a).\nProof.\nsplit ;\n  intros (q,H) ; exists q ; now rewrite Zmult_comm.\nQed.\n\n(* Why3 goal *)\nLemma odd_divides : forall (a:Z), (number.Parity.odd a) <-> ~ (divides 2%Z\n  a).\nProof.\nsplit.\nintros H.\ncontradict H.\napply Parity.even_not_odd.\nnow apply <- even_divides.\nintros H.\ndestruct (Parity.even_or_odd a).\nelim H.\nnow apply -> even_divides.\nexact H0.\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/Divisibility.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6519485149367489}}
{"text": "Require Export Eqdep.\n \nSection update_def.\nVariables (A : Type) (A_eq_dec : forall (x y : A),  { x = y } + { x <> y }).\nVariables (B : A ->  Type) (a : A) (v : B a) (f : forall (x : A),  B x).\n \nDefinition update (x : A) : B x :=\n   match A_eq_dec a x with\n    | left h => eq_rect a B v x h   \n    | right h' => f x\n   end.\n \nEnd update_def.\n \nTheorem update_eq:\n forall (A : Type) (eq_dec : forall (x y : A),  { x = y } + { x <> y })\n        (B : A ->  Type) (a : A) (v : B a) (f : forall (x : A),  B x),\n  update A eq_dec B a v f a = v.\nProof.\nintros A eq_dec B a v f.\nunfold update;case (eq_dec a a).\n- intros e; rewrite <- eq_rect_eq;auto.\n- intros Hneq; elim Hneq; trivial.\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/ch14_fundations_of_inductive_types/SRC/update_eq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6519464698986855}}
{"text": "(* Every Isabelle constant has prefix I *)\n(* just from IFOL.thy *)\n(* Q : What's class \"term\"? *)\n\n(* Should A be set or type or sth else? *)\nNotation tip := Set.\n\n(* TODO: Define \"Pointed set\" type...\nInductive PSet :=\n| C (S:Set) (s:S) : PSet *)\n\nInductive o :=\n(* Equality *)\n| Ieq (A:tip) : A -> A -> o\n(* Propositional logic *)\n| IFalse : o\n| Iconj : o -> o -> o\n| Iimp : o -> o -> o\n(*| IAll (A:tip) : A -> A -> o*)\n.\n\nInductive prop :=\n| ITrueprop : o -> prop \n| Iimpl : prop -> prop -> prop\n| Iall (A:tip) : (A->prop) -> prop\n.\n\n(* Isabelle's judgement == Coq's Coercion? *)\nCoercion tp := ITrueprop.\n\n(* TODO: add context! *)\nInductive Prf : prop -> Type :=\n(* Metalogic *)\n| A1 A B :  Prf (Iimpl A (Iimpl B A))\n| A2 A B C :  Prf (\nIimpl (Iimpl A (Iimpl B C)) (Iimpl (Iimpl A B) (Iimpl A C))\n)\n| MP A B : Prf (Iimpl A B) -> Prf A -> Prf B\n(* |  assu P : Prf (Iimpl P P) *)\n(* Object logic *)\n(* Equality *)\n| Irefl : forall (A:tip) (a:A),\n   Prf (Ieq A a a)\n| Isubst : forall (A:tip) (a b:A) (P:A -> o),\n   Prf (Ieq A a b) -> Prf (P a) -> Prf (P b)\n(* Propositional logic *)\n| IimpI : forall (P Q : o),\n   Prf (Iimpl P Q) -> Prf (Iimp P Q)\n| Imp : forall (P Q : o),\n   Prf (Iimp P Q) -> Prf P -> Prf Q\n.\n\nInductive PrfCtx (G : prop -> Type): prop -> Type :=\n| ctx p : PrfCtx G p\n| ax p : Prf p -> PrfCtx G p\n.\n\n(*\nInductive WithMP (G : prop -> Type): prop -> Type :=\n| Imp : forall (P Q : o),\n   WithMP (Iimp P Q) -> WithMP P -> WithMP Q\n*)\n\n\n\n\nTheorem Deduction (P Q:prop) (H : Prf P -> Prf Q)\n:  Prf (Iimpl P Q).\nProof.\nAbort.\n(*\nContext (P:prop).\nCheck A2 P P P.*)\n\n(* The following is useful when one does not use context:\n(as it possibly done in Isabelle) *)\nTheorem assu P : Prf (Iimpl P P).\nProof.\nrefine (MP _ _ _ _).\nrefine (MP _ _ _ _).\nrefine (A2 P (Iimpl P P) P).\nrefine (A1 _ _).\nrefine (A1 _ _).\nDefined.\n\nTheorem dropL P Q : Prf Q -> Prf (Iimpl P Q).\nProof.\nintro H.\nrefine (MP _ _ _ _).\nrefine (A1 _ _).\nassumption.\nDefined.\n\nTheorem dropR P Q R : Prf (Iimpl P R) \n -> Prf (Iimpl P (Iimpl Q R)).\nProof.\nrefine (MP _ _ _).\nrefine (MP _ _ _ _).\nrefine (A2 _ _ _).\nrefine (dropL _ _ _).\nrefine (A1 _ _).\nDefined.\n\n(* Simple theorems: *)\nDefinition ITrue : o := Iimp IFalse IFalse. \nTheorem TrueI: Prf ITrue.\nProof.\nunfold ITrue.\napply IimpI.\napply assu.\nDefined.\n(*--------------------------*)\n(* What if \"inductive extension\"? *)\n(*\nAxiom elems : forall A:Type, A -> Type.\n*)\n\n\nInductive bigunion {A} (f:A -> Type) : Type :=\n| c : forall n : A, f n -> bigunion f\n. (* exists *)\n\n(*| z : f 0 -> bigunion\n| s : forall n : nat,  *)\n\nFixpoint q (n:nat) :=\n", "meta": {"author": "georgydunaev", "repo": "FirstOrderTheory", "sha": "d54cc5041508345745853ca5da388920e196b696", "save_path": "github-repos/coq/georgydunaev-FirstOrderTheory", "path": "github-repos/coq/georgydunaev-FirstOrderTheory/FirstOrderTheory-d54cc5041508345745853ca5da388920e196b696/IsabelleAlt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6519464640313991}}
{"text": "Require Import BenB.\n\nVariable X: R -> Prop.\nVariable Y: R -> Prop.\n\nTheorem getallen_003 :\n  (Y 0)\n->\n    (forall t:R, Y t -> (forall u:R, u>=t+2 -> X u))\n  ->\n    (forall t:R, t>=3 -> X t).\nProof.\nimp_i a1.\nimp_i a2.\nall_i a.\nimp_i a3.\nimp_e (a >= 0+2).\nall_e (forall u:R, u >= 0 + 2 -> X u) a.\nimp_e (Y 0).\nall_e (forall t : R, Y t -> forall u : R, u >= t + 2 -> X u) 0.\nhyp a2.\nhyp a1.\nlin_solve.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak12/Taak12_real003.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6519464515701069}}
{"text": "(* Rule Evaluator Helper Functions *)\n\nRequire Import Nat.\nRequire Import QArith.\n\n(* Q type less than -> bool *)\n\nDefinition Qlt (a b : Q) : bool := (Qle_bool a b) &&  negb (Qeq_bool a b).\n\n(* Q type greater than -> bool *) \n\nDefinition Qgt (a b : Q) : bool := negb (Qle_bool a b) &&  negb (Qeq_bool a b).\n\n(* nat type greater than -> bool *) \n\nDefinition gtr_nat (a b : nat) : bool := negb (Nat.leb a b) && negb (beq_nat a b). ", "meta": {"author": "JamesEngelmann", "repo": "IMDS_Coq", "sha": "22f653c5175541350ca0590dbde9bfa03979cc19", "save_path": "github-repos/coq/JamesEngelmann-IMDS_Coq", "path": "github-repos/coq/JamesEngelmann-IMDS_Coq/IMDS_Coq-22f653c5175541350ca0590dbde9bfa03979cc19/Helper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6519464515701069}}
{"text": "Require Import Psatz.\nRequire Import Reals.\n\nRequire Export Prelim.\nRequire Export Complex.\nRequire Export Matrix.\n\n(* Using our (complex, unbounded) matrices, their complex numbers *)\n\nOpen Scope R_scope.\nOpen Scope C_scope.\nOpen Scope matrix_scope.\n\n(*******************************************)\n(* Quantum basis states *)\n(*******************************************)\n\n(* Maybe change to IF statements? *)\nDefinition qubit0 : Vector 2 := \n  fun x y => match x, y with \n          | 0, 0 => C1\n          | 1, 0 => C0\n          | _, _ => C0\n          end.\nDefinition qubit1 : Vector 2 := \n  fun x y => match x, y with \n          | 0, 0 => C0\n          | 1, 0 => C1\n          | _, _ => C0\n          end.\n\n(* Ket notation: \\mid 0 \\rangle *)\nNotation \"∣0⟩\" := qubit0.\nNotation \"∣1⟩\" := qubit1.\nNotation \"⟨0∣\" := qubit0†.\nNotation \"⟨1∣\" := qubit1†.\nNotation \"∣0⟩⟨0∣\" := (∣0⟩×⟨0∣).\nNotation \"∣1⟩⟨1∣\" := (∣1⟩×⟨1∣).\nNotation \"∣1⟩⟨0∣\" := (∣1⟩×⟨0∣).\nNotation \"∣0⟩⟨1∣\" := (∣0⟩×⟨1∣).\n\nDefinition bra (x : nat) : Matrix 2 1 := if x =? 0 then ⟨0∣ else ⟨1∣.\nDefinition ket (x : nat) : Matrix 2 1 := if x =? 0 then ∣0⟩ else ∣1⟩.\n\n(* Note the 'mid' symbol for these *)\nNotation \"'∣' x '⟩'\" := (ket x).\nNotation \"'⟨' x '∣'\" := (bra x). (* This gives the Coq parser headaches *)\n\nNotation \"∣ x , y , .. , z ⟩\" := (kron .. (kron ∣x⟩ ∣y⟩) .. ∣z⟩) (at level 0).\n                                                           \nTransparent bra.\nTransparent ket.\nTransparent qubit0.\nTransparent qubit1.\n\nDefinition bool_to_ket (b : bool) : Matrix 2 1 := if b then ∣1⟩ else ∣0⟩.\n                                                                     \nDefinition bool_to_matrix (b : bool) : Matrix 2 2 := if b then ∣1⟩⟨1∣ else ∣0⟩⟨0∣.\n\nDefinition bool_to_matrix' (b : bool) : Matrix 2 2 := fun x y =>\n  match x, y with\n  | 0, 0 => if b then 0 else 1\n  | 1, 1 => if b then 1 else 0\n  | _, _ => 0\n  end.  \n  \nLemma bool_to_matrix_eq : forall b, bool_to_matrix b = bool_to_matrix' b.\nProof. intros. destruct b; simpl; solve_matrix. Qed.\n\nLemma bool_to_ket_matrix_eq : forall b,\n    outer_product (bool_to_ket b) (bool_to_ket b) = bool_to_matrix b.\nProof. unfold outer_product. destruct b; simpl; reflexivity. Qed.\n\nDefinition bools_to_matrix (l : list bool) : Square (2^(length l)) := \n  big_kron (map bool_to_matrix l).\n\n\n(*************)\n(* Unitaries *)\n(*************)\n\nDefinition hadamard : Matrix 2 2 := \n  (fun x y => match x, y with\n          | 0, 0 => (1 / √2)\n          | 0, 1 => (1 / √2)\n          | 1, 0 => (1 / √2)\n          | 1, 1 => -(1 / √2)\n          | _, _ => 0\n          end).\n\nFixpoint hadamard_k (k : nat) : Matrix (2^k) (2^k):= \n  match k with\n  | 0 => I 1\n  | S k' => hadamard ⊗ hadamard_k k'\n  end. \n\nLemma hadamard_1 : hadamard_k 1 = hadamard.\nProof. apply kron_1_r. Qed.\n\n(* Alternative definitions:\nDefinition pauli_x : Matrix 2 2 := fun x y => if x + y =? 1 then 1 else 0.\nDefinition pauli_y : Matrix 2 2 := fun x y => if x + y =? 1 then (-1) ^ x * Ci else 0.\nDefinition pauli_z : Matrix 2 2 := fun x y => if (x =? y) && (x <? 2) \n                                           then (-1) ^ x * Ci else 0.\n*)\n\nDefinition σx : Matrix 2 2 := \n  fun x y => match x, y with\n          | 0, 1 => C1\n          | 1, 0 => C1\n          | _, _ => C0\n          end.\n\nDefinition σy : Matrix 2 2 := \n  fun x y => match x, y with\n          | 0, 1 => -Ci\n          | 1, 0 => Ci\n          | _, _ => C0\n          end.\n\nDefinition σz : Matrix 2 2 := \n  fun x y => match x, y with\n          | 0, 0 => C1\n          | 1, 1 => -C1\n          | _, _ => C0\n          end.\n\nDefinition phase_shift (ϕ : R) : Matrix 2 2 :=\n  fun x y => match x, y with\n          | 0, 0 => C1\n          | 1, 1 => Cexp ϕ\n          | _, _ => C0\n          end.\n  \nDefinition control {n : nat} (A : Matrix n n) : Matrix (2*n) (2*n) :=\n  fun x y => if (x <? n) && (y =? x) then 1 else \n          if (n <=? x) && (n <=? y) then A (x-n)%nat (y-n)%nat else 0.\n\n(* Definition cnot := control pauli_x. *)\n(* Direct definition makes our lives easier *)\nDefinition cnot : Matrix 4 4 :=\n  fun x y => match x, y with \n          | 0, 0 => C1\n          | 1, 1 => C1\n          | 2, 3 => C1\n          | 3, 2 => C1\n          | _, _ => C0\n          end.          \n\nLemma cnot_eq : cnot = control σx.\nProof.\n  unfold cnot, control, σx.\n  solve_matrix.\nQed.\n\n(* Swap Matrices *)\n\nDefinition swap : Matrix 4 4 :=\n  fun x y => match x, y with\n          | 0, 0 => C1\n          | 1, 2 => C1\n          | 2, 1 => C1\n          | 3, 3 => C1\n          | _, _ => C0\n          end.\n\n(* Does this overwrite the other Hint DB M? *)\nHint Unfold qubit0 qubit1 hadamard σx σy σz control cnot swap bra ket : M_db.\n\n(* Lemmas *)\nLemma MmultX1 : σx × ∣1⟩ = ∣0⟩. Proof. solve_matrix. Qed.\nLemma Mmult1X : ⟨1∣ × σx = ⟨0∣. Proof. solve_matrix. Qed.\nLemma MmultX0 : σx × ∣0⟩ = ∣1⟩. Proof. solve_matrix. Qed.\nLemma Mmult0X : ⟨0∣ × σx = ⟨1∣. Proof. solve_matrix. Qed.\nHint Rewrite Mmult0X Mmult1X MmultX0 MmultX1 : M_db.\n\nLemma swap_swap : swap × swap = I 4. Proof. solve_matrix. Qed.\n\nLemma swap_swap_r : forall n A, WF_Matrix n 4 A ->\n      A × swap × swap = A.\nProof.\n  intros.\n  rewrite Mmult_assoc.\n  rewrite swap_swap. \n  apply Mmult_1_r.\n  auto.\nQed.\n\nHint Rewrite swap_swap swap_swap_r using (auto 100 with wf_db): M_db.\n\n\n\n(* The input k is really k+1, to appease to Coq termination gods *)\n(* NOTE: Check that the offsets are right *)\n(* Requires: i + 1 < n *)\nFixpoint swap_to_0_aux (n i : nat) {struct i} : Matrix (2^n) (2^n) := \n  match i with\n  | O => swap ⊗ I (2^(n-2))\n  | S i' =>  (I (2^i) ⊗ swap ⊗ I (2^(n-i-2))) × (* swap i-1 with i *)\n            swap_to_0_aux n i' × \n            (I (2^i) ⊗ swap ⊗ I (2^(n-i-2))) (* swap i-1 with 0 *)\n  end.\n\n(* Requires: i < n *)\nDefinition swap_to_0 (n i : nat) : Matrix (2^n) (2^n) := \n  match i with \n  | O => I (2^n) \n  | S i' => swap_to_0_aux n i'\n  end.\n  \n(* Swapping qubits i and j in an n-qubit system, where i < j *) \n(* Requires i < j, j < n *)\nFixpoint swap_two_aux (n i j : nat) : Matrix (2^n) (2^n) := \n  match i with \n  | O => swap_to_0 n j \n  | S i' => I 2 ⊗ swap_two_aux (n-1) (i') (j-1)\n  end.\n\n(* Swapping qubits i and j in an n-qubit system *)\n(* Requires i < n, j < n *)\nDefinition swap_two (n i j : nat) : Matrix (2^n) (2^n) :=\n  if i =? j then I (2^n) \n  else if i <? j then swap_two_aux n i j\n  else swap_two_aux n j i.\n\n(* Simpler version of swap_to_0 that shifts other elements *)\n(* Requires: i+1 < n *)\nFixpoint move_to_0_aux (n i : nat) {struct i}: Matrix (2^n) (2^n) := \n  match i with\n  | O => swap ⊗ I (2^(n-2))\n  | S i' => (move_to_0_aux n i') × (I (2^i) ⊗ swap ⊗ I (2^(n-i-2))) \n                  \n  end.\n             \n(* Requires: i < n *)\nDefinition move_to_0 (n i : nat) : Matrix (2^n) (2^n) := \n  match i with \n  | O => I (2^n) \n  | S i' => move_to_0_aux n i'\n  end.\n \n(* Always moves up in the matrix from i to k *)\n(* Requires: k < i < n *)\nFixpoint move_to (n i k : nat) : Matrix (2^n) (2^n) := \n  match k with \n  | O => move_to_0 n i \n  | S k' => I 2 ⊗ move_to (n-1) (i-1) (k')\n  end.\n\n(*\nEval compute in ((swap_two 1 0 1) 0 0)%nat.\nEval compute in (print_matrix (swap_two 1 0 2)).\n*)\n\n(** Well Formedness of Quantum States and Unitaries **)\n\nLemma WF_bra0 : WF_Matrix 1 2 ⟨0∣. Proof. show_wf. Qed. \nLemma WF_bra1 : WF_Matrix 1 2 ⟨1∣. Proof. show_wf. Qed.\nLemma WF_qubit0 : WF_Matrix 2 1 ∣0⟩. Proof. show_wf. Qed.\nLemma WF_qubit1 : WF_Matrix 2 1 ∣1⟩. Proof. show_wf. Qed.\nLemma WF_braqubit0 : WF_Matrix 2 2 ∣0⟩⟨0∣. Proof. show_wf. Qed.\nLemma WF_braqubit1 : WF_Matrix 2 2 ∣1⟩⟨1∣. Proof. show_wf. Qed.\nLemma WF_bool_to_ket : forall b, WF_Matrix 2 1 (bool_to_ket b). \nProof. destruct b; show_wf. Qed.\nLemma WF_bool_to_matrix : forall b, WF_Matrix 2 2 (bool_to_matrix b).\nProof. destruct b; show_wf. Qed.\nLemma WF_bool_to_matrix' : forall b, WF_Matrix 2 2 (bool_to_matrix' b).\nProof. destruct b; show_wf. Qed.\n\nLemma WF_bools_to_matrix : forall l, \n  WF_Matrix (2^(length l)) (2^(length l))  (bools_to_matrix l).\nProof. \n  induction l; auto with wf_db.\n  unfold bools_to_matrix in *; simpl.\n  apply WF_kron; try rewrite map_length; try omega.\n  apply WF_bool_to_matrix.\n  apply IHl.\nQed.\n\nHint Resolve WF_bra0 WF_bra1 WF_qubit0 WF_qubit1 WF_braqubit0 WF_braqubit1 : wf_db.\nHint Resolve WF_bool_to_ket WF_bool_to_matrix WF_bool_to_matrix' : wf_db.\nHint Resolve WF_bools_to_matrix : wf_db.\n\nLemma WF_hadamard : WF_Matrix 2 2 hadamard. Proof. show_wf. Qed.\nLemma WF_σx : WF_Matrix 2 2 σx. Proof. show_wf. Qed.\nLemma WF_σy : WF_Matrix 2 2 σy. Proof. show_wf. Qed.\nLemma WF_σz : WF_Matrix 2 2 σz. Proof. show_wf. Qed.\nLemma WF_cnot : WF_Matrix 4 4 cnot. Proof. show_wf. Qed.\nLemma WF_swap : WF_Matrix 4 4 swap. Proof. show_wf. Qed.\nLemma WF_phase : forall ϕ, WF_Matrix 2 2 (phase_shift ϕ). Proof. intros. show_wf. Qed.\n\nLemma WF_control : forall (n m : nat) (U : Matrix n n), \n      (m = 2 * n)%nat ->\n      WF_Matrix n n U -> WF_Matrix m m (control U).\nProof.\n  intros n m U E WFU. subst.\n  unfold control, WF_Matrix in *.\n  intros x y [Hx | Hy];\n  bdestruct (x <? n); bdestruct (y =? x); bdestruct (n <=? x); bdestruct (n <=? y);\n    simpl; try reflexivity; try omega. \n  all: rewrite WFU; [reflexivity|omega].\nQed.\n\nHint Resolve WF_hadamard WF_σx WF_σy WF_σz WF_cnot WF_swap WF_phase WF_control : wf_db.\n\nHint Extern 2 (WF_Matrix 2 2 (phase_shift _)) => apply WF_phase : wf_db.\nHint Extern 2 (WF_Matrix 2 2 (control _)) => apply WF_control : wf_db.\n\n(***************************)\n(** Unitaries are unitary **)\n(***************************)\n\nDefinition WF_Unitary {n: nat} (U : Matrix n n): Prop :=\n  WF_Matrix n n U /\\ U † × U = I n.\n\nHint Unfold WF_Unitary : M_db.\n\n(* More precise *)\n(* Definition unitary_matrix' {n: nat} (A : Matrix n n): Prop := Minv A A†. *)\n\nLemma H_unitary : WF_Unitary hadamard.\nProof.\n  split.\n  show_wf.\n  unfold Mmult, I.\n  prep_matrix_equality.\n  autounfold with M_db.\n  destruct x as [| [|x]]; destruct y as [|[|y]]; simpl; autorewrite with C_db; \n    try reflexivity.\n  replace ((S (S x) <? 2)) with false by reflexivity.\n  rewrite andb_false_r.\n  reflexivity.\nQed.\n\nLemma σx_unitary : WF_Unitary σx.\nProof. \n  split.\n  show_wf.\n  unfold Mmult, I.\n  prep_matrix_equality.\n  destruct x as [| [|x]]; destruct y as [|[|y]]; try clra.\n  simpl.\n  replace ((S (S x) <? 2)) with false by reflexivity.\n  rewrite andb_false_r.\n  clra.\nQed.\n\nLemma σy_unitary : WF_Unitary σy.\nProof.\n  split.\n  show_wf.\n  unfold Mmult, I.\n  prep_matrix_equality.\n  destruct x as [| [|x]]; destruct y as [|[|y]]; try clra.\n  simpl.\n  replace ((S (S x) <? 2)) with false by reflexivity.\n  rewrite andb_false_r.\n  clra.\nQed.\n\nLemma σz_unitary : WF_Unitary σz.\nProof.\n  split.\n  show_wf.\n  unfold Mmult, I.\n  prep_matrix_equality.\n  destruct x as [| [|x]]; destruct y as [|[|y]]; try clra.\n  simpl.\n  replace ((S (S x) <? 2)) with false by reflexivity.\n  rewrite andb_false_r.\n  clra.\nQed.\n\nLemma phase_unitary : forall ϕ, @WF_Unitary 2 (phase_shift ϕ).\nProof.\n  intros ϕ.\n  split; [show_wf|].\n  unfold Mmult, I, phase_shift, adjoint, Cexp.\n  prep_matrix_equality.\n  destruct x as [| [|x]]; destruct y as [|[|y]]; try clra.\n  - simpl.\n    Csimpl.\n    unfold Cconj, Cmult.\n    simpl.\n    unfold Rminus.\n    rewrite Ropp_mult_distr_l.\n    rewrite Ropp_involutive.\n    replace (cos ϕ * cos ϕ)%R with ((cos ϕ)²) by easy.\n    replace (sin ϕ * sin ϕ)%R with ((sin ϕ)²) by easy. \n    rewrite Rplus_comm.\n    rewrite sin2_cos2.\n    clra.\n  - simpl. Csimpl.\n    replace ((S (S x) <? 2)) with false by reflexivity.\n    rewrite andb_false_r.\n    clra.\nQed.\n\nLemma control_unitary : forall n (A : Matrix n n), \n                          WF_Unitary A -> WF_Unitary (control A). \nProof.\n  intros n A H.\n  destruct H as [WF U].\n  split; auto with wf_db.\n  unfold control, adjoint, Mmult, I.\n  prep_matrix_equality.\n  simpl.\n  bdestructΩ (x =? y).\n  - subst; simpl.\n    rewrite Csum_sum.\n    bdestructΩ (y <? n + (n + 0)).\n    + bdestructΩ (n <=? y).\n      * rewrite Csum_0_bounded. Csimpl.\n        rewrite (Csum_eq _ (fun x => A x (y - n)%nat ^* * A x (y - n)%nat)).\n        ++ unfold control, adjoint, Mmult, I in U.\n           rewrite Nat.add_0_r.\n           eapply (equal_f) in U. \n           eapply (equal_f) in U. \n           rewrite U.\n           rewrite Nat.eqb_refl. simpl.\n           bdestructΩ (y - n <? n).\n           easy.\n        ++ apply functional_extensionality. intros x.\n           bdestructΩ (n + x <? n).\n           bdestructΩ (n <=? n + x).\n           rewrite minus_plus.\n           easy.\n        ++ intros x L.\n           bdestructΩ (y =? x).\n           rewrite andb_false_r.\n           bdestructΩ (n <=? x).\n           simpl. clra.\n      * rewrite (Csum_unique 1). \n        rewrite Csum_0_bounded.\n        ++ clra.\n        ++ intros.\n           rewrite andb_false_r.\n           bdestructΩ (n + x <? n).\n           simpl.\n           clra.\n        ++ exists y.\n           repeat rewrite andb_false_r.\n           split. easy.\n           split. \n           rewrite Nat.eqb_refl.\n           bdestructΩ (y <? n).\n           simpl. clra.\n           intros x Ne.\n           bdestructΩ (y =? x ).\n           repeat rewrite andb_false_r.\n           clra.\n    + rewrite 2 Csum_0_bounded; [clra| |].\n      * intros x L.\n        rewrite WF by (right; omega).\n        bdestructΩ (n + x <? n).\n        bdestructΩ (n <=? n + x).\n        bdestructΩ (n <=? y).\n        clra.\n      * intros x L.\n        bdestructΩ (y =? x).\n        rewrite andb_false_r.\n        bdestructΩ (n <=? x).\n        simpl. clra.\n  - simpl.\n    rewrite Csum_sum.\n    bdestructΩ (y <? n + (n + 0)).\n    + bdestructΩ (n <=? y).\n      * rewrite Csum_0_bounded. Csimpl.\n        bdestructΩ (n <=? x).\n        rewrite (Csum_eq _ (fun z => A z (x - n)%nat ^* * A z (y - n)%nat)).\n        ++ unfold control, adjoint, Mmult, I in U.\n           rewrite Nat.add_0_r.\n           eapply (equal_f) in U. \n           eapply (equal_f) in U. \n           rewrite U.\n           bdestructΩ (x - n =? y - n).\n           simpl.\n           easy.\n        ++ apply functional_extensionality. intros z.\n           bdestructΩ (n + z <? n).\n           bdestructΩ (n <=? n + z).\n           rewrite minus_plus.\n           easy.\n        ++ rewrite Csum_0. easy.\n           intros z.\n           bdestructΩ (n + z <? n).\n           rewrite andb_false_r.\n           Csimpl. easy. \n        ++ intros z L.\n           bdestructΩ (z <? n).\n           bdestructΩ (n <=? z).\n           bdestructΩ (x =? z); bdestructΩ (y =? z); try clra. \n      * bdestructΩ (n <=? x).        \n        ++ rewrite Csum_0_bounded.\n           rewrite Csum_0_bounded. clra.\n           ** intros z L.\n              bdestructΩ (n + z <? n).\n              rewrite andb_false_r.\n              clra.\n           ** intros z L.\n              bdestructΩ (z <? n).\n              rewrite andb_false_r.\n              bdestructΩ (x =? z); bdestructΩ (y =? z); try clra.\n              bdestructΩ (n <=? z).\n              clra.\n        ++ rewrite 2 Csum_0_bounded; [clra| |].\n           ** intros z L.\n              rewrite andb_false_r.\n              bdestructΩ (x =? n + z); bdestructΩ (y =? n + z); rewrite andb_false_r; clra.\n           ** intros z L.\n              rewrite andb_false_r.\n              bdestructΩ (x =? z); bdestructΩ (y =? z); rewrite andb_false_r; clra.\n    + rewrite 2 Csum_0_bounded; [clra| |].\n      * intros z L.\n        bdestructΩ (n + z <? n). \n        bdestructΩ (n <=? n + z). \n        bdestructΩ (n <=? y).\n        rewrite (WF _ (y-n)%nat) by (right; omega).\n        clra.\n      * intros z L.\n        bdestructΩ (y =? z).\n        rewrite andb_false_r.\n        rewrite (WF _ (y-n)%nat) by (right; omega).\n        destruct ((n <=? z) && (n <=? y)); clra.\nQed.\n\nLemma transpose_unitary : forall n (A : Matrix n n), WF_Unitary A -> WF_Unitary (A†).\nProof.\n  intros. \n  simpl.\n  split.\n  + destruct H; auto with wf_db.\n  + unfold WF_Unitary in *.\n    rewrite adjoint_involutive.\n    destruct H as [_ H].\n    apply Minv_left in H as [_ S]. (* NB: admitted lemma *)\n    assumption.\nQed.\n\nLemma cnot_unitary : WF_Unitary cnot.\nProof.\n  split. \n  apply WF_cnot.\n  unfold Mmult, I.\n  prep_matrix_equality.\n  do 4 (try destruct x; try destruct y; try clra).\n  replace ((S (S (S (S x))) <? 4)) with (false) by reflexivity.\n  rewrite andb_false_r.\n  clra.\nQed.\n\nLemma id_unitary : forall n, WF_Unitary (I n). \nProof.\n  split.\n  apply WF_I.\n  unfold WF_Unitary.\n  rewrite id_adjoint_eq.\n  apply Mmult_1_l.\n  apply WF_I.\nQed.\n\nLemma swap_unitary : WF_Unitary swap.\nProof. \n  split.\n  apply WF_swap.\n  unfold WF_Unitary, Mmult, I.\n  prep_matrix_equality.\n  do 4 (try destruct x; try destruct y; try clra).\n  replace ((S (S (S (S x))) <? 4)) with (false) by reflexivity.\n  rewrite andb_false_r.\n  clra.\nQed.\n\n\nLemma kron_unitary : forall {m n} (A : Matrix m m) (B : Matrix n n),\n  WF_Unitary A -> WF_Unitary B -> WF_Unitary (A ⊗ B).\nProof.\n  intros m n A B [WFA UA] [WFB UB].\n  unfold WF_Unitary in *.\n  split.\n  auto with wf_db.\n  rewrite kron_adjoint.\n  rewrite kron_mixed_product.\n  rewrite UA, UB.\n  rewrite id_kron. \n  easy.\nQed.\n\nLemma Mmult_unitary : forall (n : nat) (A : Square n) (B : Square n),\n  WF_Unitary A ->\n  WF_Unitary B ->\n  WF_Unitary (A × B).  \nProof.\n  intros n A B [WFA UA] [WFB UB].\n  split.\n  auto with wf_db.\n  autorewrite with M_db.\n  rewrite Mmult_assoc.\n  rewrite <- (Mmult_assoc _ _ _ _ (A†)).\n  rewrite UA.\n  autorewrite with M_db.\n  apply UB.\nQed.\n\n\n(********************)\n(* Self-adjointness *)\n(********************)\n\nDefinition id_sa := id_adjoint_eq.\n\nLemma hadamard_sa : hadamard† = hadamard.\nProof.\n  prep_matrix_equality.\n  repeat (try destruct x; try destruct y; try clra; trivial).\nQed.\n\nLemma σx_sa : σx† = σx.\nProof. \n  prep_matrix_equality. \n  repeat (try destruct x; try destruct y; try clra; trivial).\nQed.\n\nLemma σy_sa : σy† = σy.\nProof.\n  prep_matrix_equality. \n  repeat (try destruct x; try destruct y; try clra; trivial).\nQed.\n\nLemma σz_sa : σz† = σz.\nProof.\n  prep_matrix_equality. \n  repeat (try destruct x; try destruct y; try clra; trivial).\nQed.\n\nLemma cnot_sa : cnot† = cnot.\nProof.\n  prep_matrix_equality. \n  repeat (try destruct x; try destruct y; try clra; trivial).\nQed.\n\nLemma swap_sa : swap† = swap.\nProof.\n  prep_matrix_equality. \n  repeat (try destruct x; try destruct y; try clra; trivial).\nQed.\n\nLemma control_adjoint : forall n (U : Square n), (control U)† = control (U†).\nProof.\n  intros n U.\n  unfold control, adjoint.\n  prep_matrix_equality.\n  rewrite Nat.eqb_sym.\n  bdestruct (y =? x). \n  - subst.\n    bdestruct (x <? n); bdestruct (n <=? x); try omega; simpl; clra.\n  - rewrite 2 andb_false_r.\n    rewrite andb_comm.\n    rewrite (if_dist _ _ _ Cconj).\n    rewrite Cconj_0.\n    reflexivity.\nQed.\n\nLemma control_sa : forall (n : nat) (A : Square n), \n    A† = A -> (control A)† = (control A).\nProof.\n  intros n A H.\n  rewrite control_adjoint.\n  rewrite H.\n  easy.\nQed.  \n\nLemma phase_adjoint : forall ϕ, (phase_shift ϕ)† = phase_shift (-ϕ). \nProof.\n  intros ϕ.\n  unfold phase_shift, adjoint.\n  prep_matrix_equality.\n  destruct_m_eq; try clra.\n  unfold Cexp, Cconj. \n  rewrite cos_neg, sin_neg.\n  easy.\nQed.\n\nLemma braqubit0_sa : ∣0⟩⟨0∣† = ∣0⟩⟨0∣. Proof. mlra. Qed.\nLemma braqubit1_sa : ∣1⟩⟨1∣† = ∣1⟩⟨1∣. Proof. mlra. Qed.\n\nHint Rewrite hadamard_sa σx_sa σy_sa σz_sa cnot_sa swap_sa \n             braqubit1_sa braqubit0_sa control_adjoint phase_adjoint : M_db.\n\n(* Rather use control_adjoint :\nHint Rewrite control_sa using (autorewrite with M_db; reflexivity) : M_db. *)\n\n(************************************)\n(* Unitary Properties on Basis Kets *)\n(************************************)\n\n(*\nDefinition plus_state := 1/√2 .* ∣0⟩ .+ 1/√2 .* ∣1⟩.\nDefinition minus_state := 1/√2 .* ∣0⟩ .+ (-1/√2) .* ∣1⟩.\n\nTransparent plus_state.\nTransparent minus_state.\n                                                       \nNotation \"∣+⟩\" := plus_state.\nNotation \"∣-⟩\" := minus_state.\n*)\n\nNotation \"∣+⟩\" := (/√2 .* ∣0⟩ .+ /√2 .* ∣1⟩).\nNotation \"∣-⟩\" := (/√2 .* ∣0⟩ .+ (-/√2) .* ∣1⟩).\n\n(* Hadamard properties *)\nLemma H0_spec : hadamard × ∣0⟩ = ∣+⟩.\nProof. solve_matrix. Qed.\n\nLemma H1_spec : hadamard × ∣1⟩ = ∣-⟩.\nProof. solve_matrix. Qed.\n\nLemma Hplus_spec : hadamard × ∣+⟩ = ∣0⟩.\nProof. solve_matrix. Qed.\n\nLemma Hminus_spec : hadamard × ∣-⟩ = ∣1⟩.\nProof. solve_matrix.  Qed.\n\n(* X properties *)\nLemma X0_spec : σx × ∣0⟩ = ∣1⟩.\nProof. solve_matrix. Qed.\n\nLemma X1_spec : σx × ∣1⟩ = ∣0⟩.\nProof. solve_matrix. Qed.\n\n(* Y properties *)\nLemma Y0_spec : σy × ∣0⟩ = Ci .* ∣1⟩.\nProof. solve_matrix. Qed.\n\nLemma Y1_spec : σy × ∣1⟩ = -Ci .* ∣0⟩.\nProof. solve_matrix. Qed.\n\n(* Z properties *)\nLemma Z0_spec : σz × ∣0⟩ = ∣0⟩.\nProof. solve_matrix. Qed.\n\nLemma Z1_spec : σz × ∣1⟩ = -C1 .* ∣1⟩.\nProof. solve_matrix. Qed.\n\n(* CNOT properties *)\n\nLemma CNOT_spec : forall (x y : nat), (x < 2)%nat -> (y < 2)%nat -> cnot × ∣x,y⟩ = ∣x, (x + y) mod 2⟩.\nProof.\n  intros.\n  destruct x as [| [|x]], y as [| [|y]]; try omega; solve_matrix.\nQed.\n\nLemma CNOT00_spec : cnot × ∣0,0⟩ = ∣0,0⟩.\nProof. solve_matrix. Qed.\n\nLemma CNOT01_spec : cnot × ∣0,1⟩ = ∣0,1⟩.\nProof. crunch_matrix. Qed.\n\nLemma CNOT10_spec : cnot × ∣1,0⟩ = ∣1,1⟩.\nProof. solve_matrix. Qed.\n                                        \nLemma CNOT11_spec : cnot × ∣1,1⟩ = ∣1,0⟩.\nProof. solve_matrix. Qed.\n\n(* SWAP properties *)\n\nLemma SWAP_spec : forall x y, swap × ∣x,y⟩ = ∣y,x⟩.\nProof. intros. destruct x,y; solve_matrix. Qed.\n\n(* Automation *)\n\nHint Rewrite Mmult_plus_distr_l Mscale_plus_distr Mscale_mult_dist_r Mscale_mult_dist_l : ket_db.\nHint Rewrite Mscale_assoc Mmult_assoc: ket_db.\nHint Rewrite Mscale_0_l Mscale_1_l : ket_db.\nHint Rewrite H0_spec H1_spec Hplus_spec Hminus_spec X0_spec X1_spec Y0_spec Y1_spec\n     Z0_spec Z1_spec : ket_db.\n\nLtac ket_eq_solver :=\n  intros; autorewrite with ket_db C_db;\n  try match goal with\n  | [|- ?a .* ∣0⟩ .+ ?b .* ∣1⟩ = ?a' .* ∣0⟩ .+ ?b' .* ∣1⟩ ] =>\n    replace a with a'; try clra; replace b with b'; try clra; trivial\n  end.                                                           \n\nLemma XYZ0 : -Ci .* σx × σy × σz × ∣0⟩ = ∣0⟩.\nProof. autorewrite with ket_db C_db; easy. Qed.\n                                            \nLemma XYZ1 : -Ci .* σx × σy × σz × ∣1⟩ = ∣1⟩.\nProof. autorewrite with ket_db C_db; easy. Qed.\n\nLemma XYZ : forall α β, -Ci .* σx × σy × σz × (α .* ∣0⟩ .+ β .* ∣1⟩) = α .* ∣0⟩ .+ β .* ∣1⟩.\nProof.\n  ket_eq_solver.\nQed.\n\nProposition HZH : forall α β,\n  hadamard × σz × hadamard × (α .* ∣0⟩ .+ β .* ∣1⟩) = σx × (α .* ∣0⟩ .+ β .* ∣1⟩).\nProof.\n  ket_eq_solver.\nAbort.\n\n(* Next up:\n   Multiqubit systems.\n   Have ket_eq_solver group ∣0⟩s and ∣1⟩s.\n*)\n\n(**************)\n(* Automation *)\n(**************)\n\n(* For when autorewrite needs some extra help *)\n\nLtac Msimpl := \n  repeat match goal with \n  | [ |- context[(?A ⊗ ?B)†]]    => let H := fresh \"H\" in \n                                  specialize (kron_adjoint _ _ _ _ A B) as H;\n                                  simpl in H; rewrite H; clear H\n  | [ |- context[(control ?U)†]] => let H := fresh \"H\" in \n                                  specialize (control_sa _ U) as H;\n                                  simpl in H; rewrite H; \n                                  [clear H | Msimpl; reflexivity]\n  | [|- context[(?A ⊗ ?B) × (?C ⊗ ?D)]] => \n                                  let H := fresh \"H\" in \n                                  specialize (kron_mixed_product _ _ _ _ _ _ A B C D);\n                                  intros H; simpl in H; rewrite H; clear H\n  | _                           => autorewrite with M_db\n  end.\n\n\n(*****************************)\n(* Positive Semidefiniteness *)\n(*****************************)\n\nDefinition positive_semidefinite {n} (A : Square n) : Prop :=\n  forall (z : Matrix n 1), WF_Matrix 2 1 z -> fst ((z† × A × z) O O) >= 0.  \n\nLemma braqubit0_psd : positive_semidefinite ∣0⟩⟨0∣.\nProof. \n  intros z WFz. \n  do 3 reduce_matrices. \n  simpl.\n  rewrite <- Ropp_mult_distr_l.\n  unfold Rminus.\n  rewrite Ropp_involutive.\n  replace (fst (z 0%nat 0%nat) * fst (z 0%nat 0%nat))%R with ((fst (z 0%nat 0%nat))²) by easy. \n  replace (snd (z 0%nat 0%nat) * snd (z 0%nat 0%nat))%R with ((snd (z 0%nat 0%nat))²) by easy. \n  apply Rle_ge.\n  apply Rplus_le_le_0_compat; apply Rle_0_sqr.\nQed.\n\nLemma braqubit1_psd : positive_semidefinite ∣1⟩⟨1∣.\nProof. \n  intros z WFz. \n  do 3 reduce_matrices. \n  simpl.\n  rewrite <- Ropp_mult_distr_l.\n  unfold Rminus.\n  rewrite Ropp_involutive.\n  replace (fst (z 1%nat 0%nat) * fst (z 1%nat 0%nat))%R with ((fst (z 1%nat 0%nat))²) by easy. \n  replace (snd (z 1%nat 0%nat) * snd (z 1%nat 0%nat))%R with ((snd (z 1%nat 0%nat))²) by easy. \n  apply Rle_ge.\n  apply Rplus_le_le_0_compat; apply Rle_0_sqr.\nQed.\n\nLemma H0_psd : positive_semidefinite (hadamard × ∣0⟩⟨0∣ × hadamard).\nProof.\n  intros z WFz.\n  do 5 reduce_matrices.  \n  simpl.\n  autorewrite with R_db.\n  replace (√ 2 * / 2 * (√ 2 * / 2))%R with ((√ 2 / 2)²) by reflexivity.\n  rewrite Rsqr_div by lra.\n  rewrite Rsqr_sqrt by lra.\n  Search (_ * ?x + _ * ?x).\n  rewrite <- Rmult_plus_distr_r.\n  Search (- _ + - _).\n  rewrite <- Ropp_plus_distr.\n  repeat rewrite <- Ropp_mult_distr_l.\n  repeat rewrite Ropp_involutive.\n  rewrite <- Rmult_plus_distr_r.\n  rewrite (Rmult_comm _ (2/2²)).\n  rewrite (Rmult_comm _ (2/2²)).\n  repeat rewrite Rmult_assoc.\n  repeat rewrite <- Rmult_plus_distr_l.\n  apply Rle_ge.\n  apply Rmult_le_pos. \n  left. \n  apply Rmult_lt_0_compat. \n  lra.\n  apply Rinv_0_lt_compat.\n  apply Rmult_lt_0_compat; lra.\n  Search ((_ + _) * _)%R.\n  repeat rewrite Rmult_plus_distr_r.\n  remember (fst (z 0 0)%nat) as a.\n  remember (snd (z 0 0)%nat) as b.\n  remember (fst (z 1 0)%nat) as c.\n  remember (snd (z 1 0)%nat) as d.\n  (* This is (a + b)² + (b + c)². *)\n  clear.\n  rewrite <- Rplus_assoc.\n  remember (a * a + c * a)%R as ac1. \n  remember (b * b + d * b)%R as bd1. \n  remember (a * c + c * c)%R as ac2. \n  remember (b * d + d * d)%R as bd2.\n  rewrite (Rplus_assoc ac1).\n  rewrite (Rplus_comm bd1).\n  repeat rewrite <- Rplus_assoc.\n  rewrite (Rplus_assoc _ bd1).\n  apply Rplus_le_le_0_compat.\n  replace (ac1 + ac2)%R with ((a + c)²).\n  apply Rle_0_sqr.\n  unfold Rsqr. lra.\n  replace (bd1 + bd2)%R with ((b + d)²).\n  apply Rle_0_sqr.\n  unfold Rsqr. lra.\nQed.\n    \n(*************************)\n(* Pure and Mixed States *)\n(*************************)\n\nNotation Density n := (Matrix n n) (only parsing). \n\nDefinition Classical {n} (ρ : Density n) := forall i j, i <> j -> ρ i j = 0.\n\nDefinition Pure_State_Vector {n} (φ : Matrix n 1): Prop := \n  WF_Matrix n 1 φ /\\ φ† × φ = I  1.\n\nDefinition Pure_State {n} (ρ : Density n) : Prop := \n  exists φ, Pure_State_Vector φ /\\ ρ = φ × φ†.\n\nInductive Mixed_State {n} : Matrix n n -> Prop :=\n| Pure_S : forall ρ, Pure_State ρ -> Mixed_State ρ\n| Mix_S : forall (p : R) ρ1 ρ2, 0 < p < 1 -> Mixed_State ρ1 -> Mixed_State ρ2 ->\n                                       Mixed_State (p .* ρ1 .+ (1-p)%R .* ρ2).  \n\nLemma WF_Pure : forall {n} (ρ : Density n), Pure_State ρ -> WF_Matrix n n ρ.\nProof. intros. destruct H as [φ [[WFφ IP1] Eρ]]. rewrite Eρ. auto with wf_db. Qed.\nHint Resolve WF_Pure : wf_db.\n\nLemma WF_Mixed : forall {n} (ρ : Density n), Mixed_State ρ -> WF_Matrix n n ρ.\nProof. induction 1; auto with wf_db. Qed.\nHint Resolve WF_Mixed : wf_db.\n\nLemma pure0 : Pure_State ∣0⟩⟨0∣. \nProof. exists ∣0⟩. intuition. split. auto with wf_db. solve_matrix. Qed.\n\nLemma pure1 : Pure_State ∣1⟩⟨1∣. \nProof. exists ∣1⟩. intuition. split. auto with wf_db. solve_matrix. Qed.\n\nLemma pure_id1 : Pure_State (I  1).\nProof. exists (I  1). split. split. auto with wf_db. solve_matrix. solve_matrix. Qed.\n\nLemma pure_dim1 : forall (ρ : Square 1), Pure_State ρ -> ρ = I  1.\nProof.\n  intros ρ [φ [[WFφ IP1] Eρ]]. \n  apply Minv_flip in IP1.\n  rewrite Eρ; easy.\nQed.    \n                              \nLemma pure_state_kron : forall m n (ρ : Square m) (φ : Square n),\n  Pure_State ρ -> Pure_State φ -> Pure_State (ρ ⊗ φ).\nProof.\n  intros m n ρ φ [u [[WFu Pu] Eρ]] [v [[WFv Pv] Eφ]].\n  exists (u ⊗ v).\n  split; [split |].\n  - auto with wf_db.\n  - Msimpl. rewrite Pv, Pu. Msimpl. easy.\n  - Msimpl. subst. easy.\nQed.\n\nLemma mixed_state_kron : forall m n (ρ : Square m) (φ : Square n),\n  Mixed_State ρ -> Mixed_State φ -> Mixed_State (ρ ⊗ φ).\nProof.\n  intros m n ρ φ Mρ Mφ.\n  induction Mρ.\n  induction Mφ.\n  - apply Pure_S. apply pure_state_kron; easy.\n  - rewrite kron_plus_distr_l.\n    rewrite 2 Mscale_kron_dist_r.\n    apply Mix_S; easy.\n  - rewrite kron_plus_distr_r.\n    rewrite 2 Mscale_kron_dist_l.\n    apply Mix_S; easy.\nQed.\n\nLemma pure_state_trace_1 : forall {n} (ρ : Density n), Pure_State ρ -> trace ρ = 1.\nProof.\n  intros n ρ [u [[WFu Uu] E]]. \n  subst.\n  clear -Uu.\n  unfold trace.\n  unfold Mmult, adjoint in *.\n  simpl in *.\n  match goal with\n    [H : ?f = ?g |- _] => assert (f O O = g O O) by (rewrite <- H; easy)\n  end. \n  unfold I in H; simpl in H.\n  rewrite <- H.\n  apply Csum_eq.\n  apply functional_extensionality.\n  intros x.\n  rewrite Cplus_0_l, Cmult_comm.\n  easy.\nQed.\n\nLemma mixed_state_trace_1 : forall {n} (ρ : Density n), Mixed_State ρ -> trace ρ = 1.\nProof.\n  intros n ρ H. \n  induction H. \n  - apply pure_state_trace_1. easy.\n  - rewrite trace_plus_dist.\n    rewrite 2 trace_mult_dist.\n    rewrite IHMixed_State1, IHMixed_State2.\n    clra.\nQed.\n\n(* The following two lemmas say that for any mixed states, the elements along the \n   diagonal are real numbers in the [0,1] interval. *)\n\nLemma mixed_state_diag_in01 : forall {n} (ρ : Density n) i , Mixed_State ρ -> \n                                                        0 <= fst (ρ i i) <= 1.\nProof.\n  intros.\n  induction H.\n  - destruct H as [φ [[WFφ IP1] Eρ]].\n    destruct (lt_dec i n). \n    2: {\n      rewrite Eρ. unfold Mmult, adjoint. simpl. rewrite WFφ. simpl. lra.\n      omega. }\n    rewrite Eρ.\n    unfold Mmult, adjoint in *.\n    simpl in *.\n    rewrite Rplus_0_l.\n    match goal with\n    [H : ?f = ?g |- _] => assert (f O O = g O O) by (rewrite <- H; easy)\n    end. \n    unfold I in H. simpl in H. clear IP1.\n    match goal with\n    [ H : ?x = ?y |- _] => assert (H': fst x = fst y) by (rewrite H; easy); clear H\n    end.\n    simpl in H'.\n    rewrite <- H'.    \n    split.\n    + unfold Rminus. rewrite <- Ropp_mult_distr_r. rewrite Ropp_involutive.\n      rewrite <- Rplus_0_r at 1.\n      apply Rplus_le_compat; apply Rle_0_sqr.    \n    + match goal with \n      [ |- ?x <= fst (Csum ?f ?m)] => specialize (Csum_member_le f n) as res\n      end.\n      simpl in *.\n      unfold Rminus in *.\n      Search (_ * - _)%R.\n      rewrite <- Ropp_mult_distr_r.\n      rewrite Ropp_mult_distr_l.\n      apply res with (x := i); trivial. \n      intros x.\n      unfold Rminus. rewrite <- Ropp_mult_distr_l. rewrite Ropp_involutive.\n      rewrite <- Rplus_0_r at 1.\n      apply Rplus_le_compat; apply Rle_0_sqr.    \n  - simpl.\n    repeat rewrite Rmult_0_l.\n    repeat rewrite Rminus_0_r.\n    split.\n    assert (0 <= p * fst (ρ1 i i)).\n      apply Rmult_le_pos; lra.\n    assert (0 <= (1 - p) * fst (ρ2 i i)).\n      apply Rmult_le_pos; lra.\n    lra.\n    assert (p * fst (ρ1 i i) <= p)%R. \n      rewrite <- Rmult_1_r.\n      apply Rmult_le_compat_l; lra.\n    assert ((1 - p) * fst (ρ2 i i) <= (1-p))%R. \n      rewrite <- Rmult_1_r.\n      apply Rmult_le_compat_l; lra.\n    lra.\nQed.\n\nLemma mixed_state_diag_real : forall {n} (ρ : Density n) i , Mixed_State ρ -> \n                                                        snd (ρ i i) = 0.\nProof.\n  intros.\n  induction H.\n  + unfold Pure_State in H. \n  - destruct H as [φ [[WFφ IP1] Eρ]].\n    rewrite Eρ.\n    simpl. \n    lra.\n  + simpl.\n    rewrite IHMixed_State1, IHMixed_State2.\n    repeat rewrite Rmult_0_r, Rmult_0_l.\n    lra.\nQed.\n\nLemma mixed_dim1 : forall (ρ : Square 1), Mixed_State ρ -> ρ = I  1.\nProof.\n  intros.  \n  induction H.\n  + apply pure_dim1; trivial.\n  + rewrite IHMixed_State1, IHMixed_State2.\n    prep_matrix_equality.\n    clra.\nQed.  \n\n\n(** Density matrices and superoperators **)\n\nDefinition Superoperator m n := Density m -> Density n.\n\nDefinition WF_Superoperator {m n} (f : Superoperator m n) := \n  (forall ρ, Mixed_State ρ -> Mixed_State (f ρ)).   \n\nDefinition super {m n} (M : Matrix m n) : Superoperator n m := fun ρ => \n  M × ρ × M†.\n\nLemma super_I : forall n ρ,\n      WF_Matrix n n ρ ->\n      super (I n) ρ = ρ.\nProof.\n  intros.\n  unfold super.\n  autorewrite with M_db.\n  reflexivity.\nQed.\n\nLemma WF_super : forall  m n (U : Matrix m n) (ρ : Square n), \n  WF_Matrix m n U -> WF_Matrix n n ρ -> WF_Matrix m m (super U ρ).\nProof.\n  unfold super.\n  auto with wf_db.\nQed.\n\nHint Resolve WF_super : wf_db.\n\nLemma super_outer_product : forall m (φ : Matrix m 1) (U : Matrix m m), \n    super U (outer_product φ φ) = outer_product (U × φ) (U × φ).\nProof.\n  intros. unfold super, outer_product.\n  autorewrite with M_db.\n  repeat rewrite Mmult_assoc. reflexivity.\nQed.\n\nDefinition compose_super {m n p} (g : Superoperator n p) (f : Superoperator m n)\n                      : Superoperator m p := fun ρ => g (f ρ).\n\nLemma WF_compose_super : forall m n p (g : Superoperator n p) (f : Superoperator m n) \n  (ρ : Square m), \n  WF_Matrix m m ρ ->\n  (forall A, WF_Matrix m m A -> WF_Matrix n n (f A)) ->\n  (forall A, WF_Matrix n n A -> WF_Matrix p p (g A)) ->\n  WF_Matrix p p (compose_super g f ρ).\nProof.\n  unfold compose_super.\n  auto.\nQed.\n\nHint Resolve WF_compose_super : wf_db.\n\n\nLemma compose_super_correct : forall {m n p} \n                              (g : Superoperator n p) (f : Superoperator m n),\n      WF_Superoperator g -> \n      WF_Superoperator f ->\n      WF_Superoperator (compose_super g f).\nProof.\n  intros m n p g f pf_g pf_f.\n  unfold WF_Superoperator.\n  intros ρ mixed.\n  unfold compose_super.\n  apply pf_g. apply pf_f. auto.\nQed.\n\nDefinition sum_super {m n} (f g : Superoperator m n) : Superoperator m n :=\n  fun ρ => (1/2)%R .* f ρ .+ (1 - 1/2)%R .* g ρ.\n\nLemma sum_super_correct : forall m n (f g : Superoperator m n),\n      WF_Superoperator f -> WF_Superoperator g -> WF_Superoperator (sum_super f g).\nProof.\n  intros m n f g wf_f wf_g ρ pf_ρ.\n  unfold sum_super. \n  set (wf_f' := wf_f _ pf_ρ).\n  set (wf_g' := wf_g _ pf_ρ).\n  apply (Mix_S (1/2) (f ρ) (g ρ)); auto. \n  lra.\nQed.\n\n(* Maybe we shouldn't call these superoperators? Neither is trace-preserving *)\nDefinition SZero {m n} : Superoperator m n := fun ρ => Zero.\nDefinition Splus {m n} (S T : Superoperator m n) : Superoperator m n :=\n  fun ρ => S ρ .+ T ρ.\n\n(* These are *)\nDefinition new0_op : Superoperator 1 2 := super ∣0⟩.\nDefinition new1_op : Superoperator 1 2 := super ∣1⟩.\nDefinition meas_op : Superoperator 2 2 := Splus (super ∣0⟩⟨0∣) (super ∣1⟩⟨1∣).\nDefinition discard_op : Superoperator 2 1 := Splus (super ⟨0∣) (super ⟨1∣).\n\nLemma pure_unitary : forall {n} (U ρ : Matrix n n), \n  WF_Unitary U -> Pure_State ρ -> Pure_State (super U ρ).\nProof.\n  intros n U ρ [WFU H] [φ [[WFφ IP1] Eρ]].\n  rewrite Eρ.\n  exists (U × φ).\n  split.\n  - split; auto with wf_db.\n    rewrite (Mmult_adjoint _ _ _ U φ).\n    rewrite Mmult_assoc.\n    rewrite <- (Mmult_assoc _ _ _ _ (U†)).\n    rewrite H, Mmult_1_l, IP1; easy.\n  - unfold super.\n    rewrite (Mmult_adjoint _ _ _ U φ).\n    repeat rewrite Mmult_assoc.\n    reflexivity.\nQed.    \n\nLemma mixed_unitary : forall {n} (U ρ : Matrix n n), \n  WF_Unitary U -> Mixed_State ρ -> Mixed_State (super U ρ).\nProof.\n  intros n U ρ H M.\n  induction M.\n  + apply Pure_S.\n    apply pure_unitary; trivial.\n  + unfold WF_Unitary, super in *.\n    rewrite Mmult_plus_distr_l.\n    rewrite Mmult_plus_distr_r.\n    rewrite 2 Mscale_mult_dist_r.\n    rewrite 2 Mscale_mult_dist_l.\n    apply Mix_S; trivial.\nQed.\n\nLemma super_unitary_correct : forall {n} (U : Matrix n n), \n  WF_Unitary U -> WF_Superoperator (super U).\nProof.\n  intros n U H ρ Mρ.\n  apply mixed_unitary; easy.\nQed.\n\nLemma compose_super_assoc : forall {m n p q}\n      (f : Superoperator m n) (g : Superoperator n p) (h : Superoperator p q), \n      compose_super (compose_super f g) h\n    = compose_super f (compose_super g h).\nProof. easy. Qed.\n\n\n(* This is compose_super_correct \nLemma WF_Superoperator_compose : forall m n p (s : Superoperator n p) (s' : Superoperator m n),\n    WF_Superoperator s ->\n    WF_Superoperator s' ->\n    WF_Superoperator (compose_super s s').\nProof.\n  unfold WF_Superoperator.\n  intros m n p s s' H H0 ρ H1.\n  unfold compose_super.\n  apply H.\n  apply H0.\n  easy.\nQed.\n*)\n\n(****************************************)\n(* Tests and Lemmas about swap matrices *)\n(****************************************)\n\nLemma swap_spec : forall (q q' : Matrix 2 1), WF_Matrix 2 1 q -> \n                                         WF_Matrix 2 1 q' ->\n                                         swap × (q ⊗ q') = q' ⊗ q.\nProof.\n  intros q q' WF WF'.\n  solve_matrix.\n  - destruct y. clra. \n    rewrite WF by omega. \n    rewrite (WF' O (S y)) by omega.\n    clra.\n  - destruct y. clra. \n    rewrite WF by omega. \n    rewrite (WF' O (S y)) by omega.\n    clra.\n  - destruct y. clra. \n    rewrite WF by omega. \n    rewrite (WF' 1%nat (S y)) by omega.\n    clra.\n  - destruct y. clra. \n    rewrite WF by omega. \n    rewrite (WF' 1%nat (S y)) by omega.\n    clra.\nQed.  \n\nExample swap_to_0_test_24 : forall (q0 q1 q2 q3 : Matrix 2 1), \n  WF_Matrix 2 1 q0 -> WF_Matrix 2 1 q1 -> WF_Matrix 2 1 q2 -> WF_Matrix 2 1 q3 ->\n  swap_to_0 4 2 × (q0 ⊗ q1 ⊗ q2 ⊗ q3) = (q2 ⊗ q1 ⊗ q0 ⊗ q3). \nProof.\n  intros q0 q1 q2 q3 WF0 WF1 WF2 WF3.\n  unfold swap_to_0, swap_to_0_aux.\n  repeat rewrite Mmult_assoc.\n  rewrite (kron_assoc _ _ _ _ _ _ q0 q1).\n  rewrite kron_mixed_product.\n  rewrite (kron_mixed_product _ _ _ _ _ _ (I  (2^1)) swap).\n  rewrite swap_spec by assumption.\n  Msimpl.\n  rewrite (kron_assoc _ _ _ _ _ _ q0).\n  rewrite (kron_assoc _ _ _ _ _ _ q2 q1).\n  setoid_rewrite <- (kron_assoc _ _ _ _ _ _ q0 q2 (q1 ⊗ q3)).\n  simpl.\n  setoid_rewrite (kron_mixed_product _ _ _ _ _ _ swap (I 4) (q0 ⊗ q2) (q1 ⊗ q3)).\n  rewrite swap_spec by assumption.\n  Msimpl.\n  rewrite (kron_assoc _ _ _ _ _ _ q2 q0).\n  setoid_rewrite <- (kron_assoc _ _ _ _ _ _ q0 q1 q3).\n  setoid_rewrite (kron_assoc _ _ _ _ _ _ (I 2)).  \n  setoid_rewrite (kron_mixed_product _ _ _ _ _ _ (I 2) (swap ⊗ I 2) q2 _).\n  setoid_rewrite (kron_mixed_product _ _ _ _ _ _ swap (I 2) _ _).\n  Msimpl.\n  rewrite swap_spec by assumption.\n  repeat setoid_rewrite kron_assoc.\n  reflexivity.\nQed.\n\nLemma swap_two_base : swap_two 2 1 0 = swap.\nProof. unfold swap_two. simpl. apply kron_1_r. Qed.\n\nLemma swap_second_two : swap_two 3 1 2 = I 2 ⊗ swap.\nProof. unfold swap_two.\n       simpl.\n       rewrite kron_1_r.\n       reflexivity.\nQed.\n\nLemma swap_0_2 : swap_two 3 0 2 = (I 2 ⊗ swap) × (swap ⊗ I 2) × (I 2 ⊗ swap).\nProof.\n  unfold swap_two.\n  simpl.\n  Msimpl.\n  reflexivity.\nQed.\n\n(*\nProposition swap_to_0_spec : forall (q q0 : Matrix 2 1) (n k : nat) (l1 l2 : list (Matrix 2 1)), \n   length l1 = (k - 1)%nat ->\n   length l2 = (n - k - 2)%nat ->   \n   @Mmult (2^n) (2^n) 1 (swap_to_0 n k) (⨂ ([q0] ++ l1 ++ [q] ++ l2)) = \n     ⨂ ([q] ++ l1 ++ [q0] ++ l2).\n\nProposition swap_two_spec : forall (q q0 : Matrix 2 1) (n0 n1 n2 n k : nat) (l0 l1 l2 : list (Matrix 2 1)), \n   length l0 = n0 ->\n   length l1 = n1 ->\n   length l2 = n2 ->   \n   n = (n0 + n1 + n2 + 2)%nat ->\n   @Mmult (2^n) (2^n) 1 \n     (swap_two n n0 (n0+n1+1)) (⨂ (l0 ++ [q0] ++ l1 ++ [q] ++ l2)) = \n     ⨂ (l0 ++ [q] ++ l1 ++ [q0] ++ l2).\n*)\n\nExample move_to_0_test_24 : forall (q0 q1 q2 q3 : Matrix 2 1), \n  WF_Matrix 2 1 q0 -> WF_Matrix 2 1 q1 -> WF_Matrix 2 1 q2 -> WF_Matrix 2 1 q3 ->\n  move_to_0 4 2 × (q0 ⊗ q1 ⊗ q2 ⊗ q3) = (q2 ⊗ q0 ⊗ q1 ⊗ q3). \nProof.\n  intros q0 q1 q2 q3 WF0 WF1 WF2 WF3.\n  unfold move_to_0, move_to_0_aux.\n  repeat rewrite Mmult_assoc.\n  rewrite (kron_assoc _ _ _ _ _ _ q0 q1).\n  simpl.\n  setoid_rewrite (kron_mixed_product _ _ _ _ _ _ ((I 2) ⊗ swap) (I 2) \n                                     (q0 ⊗ (q1 ⊗ q2)) q3).\n  setoid_rewrite (kron_mixed_product _ _ _ _ _ _ (I 2) swap q0 (q1 ⊗ q2)).\n  Msimpl.\n  rewrite swap_spec by assumption.\n  setoid_rewrite <- (kron_assoc _ _ _ _ _ _ q0 q2 q1).\n  setoid_rewrite (kron_assoc _ _ _ _ _ _ (q0 ⊗ q2) q1 q3).\n  setoid_rewrite (kron_mixed_product _ _ _ _ _ _ swap (I 4) (q0 ⊗ q2) (q1 ⊗ q3)).\n  rewrite swap_spec by assumption.\n  Msimpl.\n  repeat setoid_rewrite kron_assoc.\n  reflexivity.\nQed.\n\n(* *)\n", "meta": {"author": "k4rtik", "repo": "rp1", "sha": "b50914211c6aaf30170c775c0d70708249977cad", "save_path": "github-repos/coq/k4rtik-rp1", "path": "github-repos/coq/k4rtik-rp1/rp1-b50914211c6aaf30170c775c0d70708249977cad/Quantum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.651943415278109}}
{"text": "Set Primitive Projections.\n\nFrom HB Require Import structures.\n\nHB.mixin Record proset_op T := { Pleq : T -> T -> Prop }.\nHB.structure Definition proset_raw := { T of proset_op T }.\nNotation \"x <= y\" := (@Pleq _ x y) (at level 70).\n\nHB.mixin Record monoid_op T of proset_raw T := { Mzero : T ; Madd : T -> T -> T }.\nHB.structure Definition monoid_raw := { T of proset_raw T & monoid_op T }.\nNotation \"0\" := (@Mzero _).\nNotation \"x + y\" := (@Madd _ x y).\n\nHB.mixin Record semiring_op T of monoid_raw T := { SRone : T ; SRmul : T -> T -> T }.\nHB.structure Definition semiring_raw := { T of monoid_raw T & semiring_op T}.\nNotation \"1\" := (@SRone _).\nNotation \"x * y\" := (@SRmul _ x y).\n\nHB.mixin Record proset_ax T of proset_raw T :=\n  { Pleq_refl : forall x : T, x <= x ;\n    Pleq_trans : forall {x y z : T}, x <= y -> y <= z -> x <= z }.\nHB.structure Definition proset := {T of proset_raw T & proset_ax T }.\n\nHB.mixin Record monoid_ax T of proset T & monoid_raw T :=\n  { Madd_mono : forall a b c d : T, a <= b -> c <= d -> a + c <= b + d ;\n    Madd_0_l : forall a : T, 0 + a <= a ;\n    Madd_0_r : forall a : T, a <= a + 0 ;\n    Madd_assoc : forall a b c : T, (a + b) + c <= a + (b + c) }.\nHB.structure Definition monoid := { T of proset T & monoid_raw T & monoid_ax T }.\n\nHB.mixin Record semiring_ax T of monoid T & semiring_raw T := {\n  SRadd_comm : forall a b : T, a + b <= b + a ;\n  SRmul_0_l : forall a : T, 0 * a <= 0 ;\n  SRmul_0_r : forall a : T, 0 <= 0 * a ;\n  SRaddmul_l : forall a b c : T, (a + b) * c <= a * c + b * c ;\n  SRaddmul_r : forall a b c : T, a * b + a * c <= a * (b + c) ;\n}.\nHB.structure Definition semiring := { T of monoid T & semiring_raw T & semiring_ax T }.\n\n(* /!\\ upstream bug in hierarchical structures\n\nHB.mixin Record semimodule_op (S : semiring.type) (T : Type) :=\n  { SMact : S -> T -> T }.\nHB.structure Definition semimodule_raw (S : semiring.type) :=\n  { T of monoid_raw T & semimodule_op S T }.\n\nPrint semimodule_raw.axioms.\nNotation \"x # y\" := (@SMact _ _ x y) (at level 50).\n\nHB.mixin Record semimodule_ax (S : semiring.type) (T : Type) of semimodule_raw S T := {\n  SMadd_comm : forall a : T, a <= a ;\n}.\n  SMmul_mono : forall (a b : SR) (c d : SM), a <= b -> c <= d -> a # c <= b # d ;\n  SMmul_1_l : forall a : SM, 1 # a <= a ;\n  SMmulact : forall (a b : SR) (c : SM), (a * b) # c <= a # (b # c) ;\n  SMact_0_l : forall a : SM, 0 # a <= 0 ;\n  SMact_0_r : forall a : SR, 0 <= a # (0 : SM) ;\n  SMaddact_l : forall (a b : SR) (c : SM), (a + b) # c <= (a # c) + (b # c) ;\n  SMaddact_r : forall (a : SR) (b c : SM), (a # b) + (a # c) <= a # (b + c) ;\n}\n*)", "meta": {"author": "Lapin0t", "repo": "linear", "sha": "5dc897199f523375e06419afd41e37eebc04c5f4", "save_path": "github-repos/coq/Lapin0t-linear", "path": "github-repos/coq/Lapin0t-linear/linear-5dc897199f523375e06419afd41e37eebc04c5f4/coq-src/skew.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6519434102298453}}
{"text": "Require Import GeoCoq.Axioms.parallel_postulates.\nRequire Import GeoCoq.Tarski_dev.Annexes.saccheri.\n\nSection thales_existence_rah.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\n\nLemma thales_existence__rah : existential_thales_postulate -> postulate_of_right_saccheri_quadrilaterals.\nProof.\n  intro thales.\n  destruct thales as [A [B [C [M]]]].\n  spliter.\n  apply (t22_17__rah A B C M); assumption.\nQed.\n\nEnd thales_existence_rah.", "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/thales_existence_rah.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6518798252104331}}
{"text": "Require Import Bool Arith List.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nDefinition table_T (tuple_T: Type) := list tuple_T.\nDefinition non_empty {tuple_T: Type} (l: table_T tuple_T) :=\n  match l with\n   | nil => False\n   | h :: t => True\n  end.\n\nFixpoint row_transform {tuple_T1 tuple_T2: Type} \n(op : tuple_T1 -> tuple_T2) (l : table_T tuple_T1) : table_T tuple_T2:=\n  match l with\n  | nil => nil\n  | h :: t => (op h) :: (row_transform op t)\n  end.\n\nFixpoint filter {tuple_T: Type} \n(f : tuple_T -> bool) (l : table_T tuple_T) : table_T tuple_T:=\n  match l with\n  | nil => nil\n  | h :: t => if f h then h :: (filter f t) else (filter f t)\n  end.\n\nDefinition row_transform_sz {tuple_T1 tuple_T2: Type} \n(op : tuple_T1 -> tuple_T2) (f : tuple_T2 -> bool) (g : tuple_T1 -> bool) \n(len : nat) :=\nforall (t : table_T tuple_T1), \n(length t <= len) -> (filter f (row_transform op t) = row_transform op (filter g t)).\n\n\nLemma filter_split {tuple_T: Type} : \nforall (t : table_T tuple_T) (tup : tuple_T) (f: tuple_T -> bool),\nfilter f (tup::t) = ((filter f (tup::nil)) ++ filter f t).\nProof.\nintros.\nsimpl. destruct (f tup). simpl. reflexivity.\nsimpl. reflexivity.\nQed.\n\nLemma filter_split2 {tuple_T: Type} : \nforall (t1 t2: table_T tuple_T) (f: tuple_T -> bool),\nfilter f (t1++t2) = (filter f t1) ++ (filter f t2).\nProof.\nintros.\ninduction t1. \n+ simpl. reflexivity.\n+ rewrite filter_split. simpl.\n  destruct (f a). simpl. rewrite IHt1. reflexivity.\n  rewrite IHt1. simpl. reflexivity.\nQed.\n\nLemma transform_split {tuple_T1 tuple_T2: Type} : \nforall (t : table_T tuple_T1) (tup : tuple_T1) (op: tuple_T1 -> tuple_T2),\nrow_transform op (tup::t) = (row_transform op (tup::nil)) ++ (row_transform op t).\nProof.\nintros.\nsimpl. reflexivity.\nQed.\n\nLemma transform_split2 {tuple_T1 tuple_T2: Type} :\nforall (t1 t2 : table_T tuple_T1) (op: tuple_T1 -> tuple_T2),\nrow_transform op (t1++t2) = (row_transform op t1) ++ (row_transform op t2).\nProof.\nintros. induction t1. \n + simpl.  reflexivity.\n + rewrite transform_split. simpl. rewrite IHt1. reflexivity.\nQed.\n\n\n\n(* SMP proof *)\nTheorem row_transform_smp : \nforall (tuple_T1 tuple_T2 : Type)\n(op : tuple_T1 -> tuple_T2) (f : tuple_T2 -> bool) (g : tuple_T1 -> bool)\n(len : nat),\n(row_transform_sz op f g 1) -> (row_transform_sz op f g len).\nProof.\nintros.\ninduction len.\n(* empty table *)\n{ unfold row_transform_sz. intros. induction t. simpl. reflexivity. \n  simpl in H0. apply Nat.nle_succ_0 in H0. contradiction. }\ninduction len.\napply H.\n{ unfold row_transform_sz. intros.\n  induction t. simpl. reflexivity.\n  rewrite transform_split. rewrite filter_split. \n  rewrite transform_split2. rewrite filter_split2.\n  simpl in H0. apply le_S_n in H0. \n  assert (Hlen: length t <= S (S len)). \n    { rewrite Nat.le_succ_diag_r. apply le_n_S. apply H0. }\n  assert (part1: filter f (row_transform op t) = row_transform op (filter g t)).\n    { apply IHt. apply Hlen. }\n  assert (part2: filter f (row_transform op (a :: nil)) = row_transform op (filter g (a :: nil))).\n    { unfold row_transform_sz in H. apply H. simpl. reflexivity. }\n  rewrite part1. rewrite part2. reflexivity.\n}\nQed.\n  \n \n\n\n", "meta": {"author": "predicate-udf", "repo": "pushdown-smp-proof", "sha": "ffeca05301a23e9277a7e357ebbfb91b821a9f0e", "save_path": "github-repos/coq/predicate-udf-pushdown-smp-proof", "path": "github-repos/coq/predicate-udf-pushdown-smp-proof/pushdown-smp-proof-ffeca05301a23e9277a7e357ebbfb91b821a9f0e/row-transform.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6517872860407673}}
{"text": "(** * Tactics: More Basic Tactics *)\n\n(** This chapter introduces several additional proof strategies\n    and tactics that allow us to begin proving more interesting\n    properties of functional programs.\n\n    We will see:\n    - how to use auxiliary lemmas in both \"forward-\" and\n      \"backward-style\" proofs;\n    - how to reason about data constructors -- in particular, how to\n      use the fact that they are injective and disjoint;\n    - how to strengthen an induction hypothesis, and when such\n      strengthening is required; and\n    - more details on how to reason by case analysis. *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Poly.\n\n(* ################################################################# *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    _exactly_ the same as some hypothesis in the context or some\n    previously proved lemma. *)\nDefinition mon_type := forall x : nat , nat.\nPrint mon_type.\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n\n(** Here, we could finish with \"[rewrite -> eq2.  reflexivity.]\" as we\n    have done several times before.  We can finish this proof in\n    a single step by using the [apply] tactic instead: *)\n\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n    n = m ->\n    (n = m -> [n;o] = [m;p]) ->\n    [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] that introduces some _universally quantified\n    variables_.  When Coq matches the current goal against the\n    conclusion of [H], it will try to find appropriate values for\n    these variables.  For example, when we do [apply eq2] in the\n    following proof, the universal variable [q] in [eq2] gets\n    instantiated with [n], and [r] gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, standard, optional (silly_ex) \n\n    Complete the following proof using only [intros] and [apply]. *)\n\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 2 = true ->\n     oddb 3 = true.\nProof.\n  intros H Eq.\n  apply H.\n  apply Eq.\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 = (n =? 5)  ->\n     (S (S n)) =? 7 = true.\nProof.\n  intros n H.\n\n(** Here we cannot use [apply] directly, but we can use the [symmetry]\n    tactic, which switches the left and right sides of an equality in\n    the goal. *)\n\n  symmetry.\n  simpl. (** (This [simpl] is optional, since [apply] will perform\n             simplification first, if needed.) *)\n  apply H.  Qed.\n\n(** **** Exercise: 3 stars, standard (apply_exercise1) \n\n    _Hint_: You can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  You may find earlier lemmas like\n    [app_nil_r], [app_assoc], [rev_app_distr], [rev_involutive],\n    etc. helpful.  Also, remember that [Search] is your friend\n    (though it may not find earlier lemmas if they were posed as\n    optional problems and you chose not to finish the proofs). *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  intros l l' Eq.\n  rewrite Eq.\n  Search (rev(rev _ )).\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\n\n\n(* apply est une tactique qui permet d'utiliser la conclusion d'une hypothèse ou\nd'un théorème pour démontrer le but. Pour que la tactique fonctionne, il faut\nque le but soit une instance de cette hypothèse ou de ce théorème. Il reste\nalors à démontrer les hypothèses qui permette d'utiliser la propriété utilisée\npar apply.\n\nrewrite permet de remplacer dans le but les occurrences d'un terme apparaissant\ndans une égalité (présente en hypothèse ou issue d'un théorème) par l'autre\nterme impliqué dans cette égalité.\n\n    [] *)\n\n(* ################################################################# *)\n(** * The [apply with] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a;b]] to [[e;f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might like to pull it out as a\n    lemma that records, once and for all, the fact that equality is\n    transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to prove the above\n    example.  However, to do this we need a slight refinement of the\n    [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n\n(** If we simply tell Coq [apply trans_eq] at this point, it can\n    tell (by matching the goal against the conclusion of the lemma)\n    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and\n    [o] with [[e,f]].  However, the matching process doesn't determine\n    an instantiation for [m]: we have to supply one explicitly by\n    adding \"[with (m:=[c,d])]\" to the invocation of [apply]. *)\n\n  apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2.   Qed.\n\n(** (Actually, we usually don't have to include the name [m] in\n    the [with] clause; Coq is often smart enough to figure out which\n    variable we are instantiating. We could instead write [apply\n    trans_eq with [c;d]].) *)\n\n(** Coq also has a tactic [transitivity] that accomplishes the\n    same purpose as applying [trans_eq]. The tactic requires us to\n    state the instantiation we want, just like [apply with] does. *)\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  transitivity [c;d].\n  apply eq1. apply eq2.   Qed.\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 eq1 eq2.\n  transitivity m.\n  - apply eq2.\n  - apply eq1.\nQed.\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    It is obvious from this definition that every number has one of\n    two forms: either it is the constructor [O] or it is built by\n    applying the constructor [S] to another number.  But there is more\n    here than meets the eye: implicit in the definition are two more\n    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  assert (H2: n = pred (S n)). { reflexivity. }\n  rewrite H2. rewrite H1. reflexivity.\nQed.\n\n(** This technique can be generalized to any constructor by\n    writing the equivalent of [pred] -- 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\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\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  intros n m o H.\n  injection H.\n  (* WORKED IN CLASS *)\n  intros H1 H2. rewrite H1. rewrite H2. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, standard (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 eq1 eq2.\n  injection eq1 as eq_x_z eq_yl_j.\n  rewrite eq2 in eq_yl_j.\n  injection eq_yl_j as eq_y_z.\n  transitivity z.\n  - apply eq_x_z.\n  - rewrite eq_y_z. reflexivity.\nQed.\n  (** [] *)\nTheorem eq_aux_lemma : forall (X : Type) (x y : X) (l : list X),\n  x :: l = y :: l -> x = y.\n  Proof.\n  intros.\n  injection H. intros. apply H0. Qed.\nExample injection_ex4 : 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. rewrite H0.\n  intros Eq1 Eq2.\n  apply eq_aux_lemma in  Eq1.\n  transitivity z.\n  - apply Eq2.\n  - symmetry. apply Eq1.\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   0 =? n = true -> n = 0.\nProof.\n  intros n.\n\n(** We can proceed by case analysis on [n]. The first case is\n    trivial. *)\n\n  destruct n as [| n'] eqn:E.\n  - (* n = 0 *)\n    intros H. reflexivity.\n\n(** However, the second one doesn't look so simple: assuming [0\n    =? (S n') = true], we must show [S n' = 0]!  The way forward is to\n    observe that the assumption itself is nonsensical: *)\n\n  - (* n = S n' *)\n    simpl.\n\n(** If we use [discriminate] on this hypothesis, Coq confirms\n    that the subgoal we are working on is impossible and removes it\n    from further consideration. *)\n\n    intros H. discriminate H.\nQed.\n\n(** This is an instance of a logical principle known as the _principle\n    of explosion_, which asserts that a contradictory hypothesis\n    entails anything (even false things!). *)\n\nTheorem discriminate_ex1 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. discriminate contra. Qed.\n\nTheorem discriminate_ex2 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. discriminate contra. Qed.\n\n(** If you find the principle of explosion confusing, remember\n    that these proofs are _not_ showing that the conclusion of the\n    statement holds.  Rather, they are showing that, _if_ the\n    nonsensical situation described by the premise did somehow arise,\n    _then_ the nonsensical conclusion would 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. *)\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 eq.\n  discriminate eq.\nQed.\n\n\n(** The injectivity of constructors allows us to reason that\n    [forall (n m : nat), S n = S m -> n = m].  The converse of this\n    implication is an instance of a more general fact about both\n    constructors and functions, which we will find convenient in a few\n    places below: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.\n\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(** There is also a tactic named `f_equal` that can prove such\n    theorems.  Given a goal of the form [f a1 ... an = g b1 ... bn],\n    the tactic [f_equal] will produce subgoals of the form [f = g],\n    [a1 = b1], ..., [an = bn]. At the same time, any of these subgoals\n    that are simple enough (e.g., immediately provable by\n    [reflexivity]) will be automatically discharged by [f_equal]. *)\n\nTheorem eq_implies_succ_equal' : forall (n m : nat),\n    n = m -> S n = S m.\nProof. intros n m H. f_equal. apply H. Qed.\n\n(* ################################################################# *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic \"[simpl in H]\" performs simplification on\n    the hypothesis [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     (S n) =? (S m) = b  ->\n     n =? m = b.\nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, [apply L in H] matches some conditional statement\n    [L] (of the form [X -> Y], say) against a hypothesis [H] in the\n    context.  However, unlike ordinary [apply] (which rewrites a goal\n    matching [Y] into a subgoal [X]), [apply L in H] matches [H]\n    against [X] and, if successful, replaces it with [Y].\n\n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\": from [X -> Y] and a hypothesis matching [X], it\n    produces a hypothesis matching [Y].  By contrast, [apply L] is\n    \"backward reasoning\": it says that if we know [X -> Y] and we\n    are trying to prove [Y], it suffices to prove [X].\n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\nTheorem silly3' : forall (n : nat),\n  (n =? 5 = true -> (S (S n)) =? 7 = true) ->\n  true = (n =? 5)  ->\n  true = ((S (S n)) =? 7).\nProof.\n  intros n eq H.\n  symmetry in H. apply eq in H. symmetry in H.\n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_ and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n\n    The informal proofs that you've seen in math or computer science\n    classes probably tended to use forward reasoning.  In general,\n    idiomatic use of Coq favors backward reasoning, but in some\n    situations the forward style can be easier to think about. *)\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 sometimes need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose\n    we want to show that [double] is injective -- i.e., that it maps\n    different arguments to different results:\n\n       Theorem double_injective: forall n m,\n         double n = double m -> n = m.\n\n    The way we start this proof is a bit delicate: if we begin it with\n\n       intros n. induction n.\n\n    all is well.  But if we begin it with\n\n       intros n m. induction n.\n\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n' 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.\n\n(** At this point, the induction hypothesis ([IHn']) does _not_ give us\n    [n' = m'] -- there is an extra [S] in the way -- so the goal is\n    not provable. *)\n\nAbort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context --\n    intuitively, we have told Coq, \"Let's consider some particular [n]\n    and [m]...\" and we now have to prove that, if [double n = double\n    m] for _those particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove, for\n    _all_ [n], that the proposition\n\n      - [P n] = \"if [double n = double m], then [n = m]\"\n\n    holds, by showing\n\n      - [P O]\n\n         (i.e., \"if [double O = double m] then [O = m]\") and\n\n      - [P n -> P (S n)]\n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: 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 (arbitrary,\n    but fixed) [m] -- say, [5].  The statement is then saying that,\n    if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help at all with proving\n    [R]!  If we tried to prove [R] from [Q], we would start with\n    something like \"Suppose [double (S n) = 10]...\" but then we'd be\n    stuck: knowing that [double (S n)] is [10] tells us nothing\n    helpful about whether [double n] is [10] (indeed, it strongly\n    suggests that [double n] is _not_ [10]!!), so [Q] is useless. *)\n\n(** Trying to carry out this proof by induction on [n] when [m] is\n    already in the context doesn't work because we are then trying to\n    prove a statement involving _every_ [n] but just a _single_ [m]. *)\n\n(** A successful proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = O *) simpl. intros m eq. destruct m as [| m'] eqn:E.\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) discriminate eq.\n\n  - (* n = S n' *) simpl.\n\n(** Notice that both the goal and the induction hypothesis are\n    different this time: the goal asks us to prove something more\n    general (i.e., to prove the statement for _every_ [m]), but the IH\n    is correspondingly more flexible, allowing us to choose whichever\n    [m] we like when we apply the IH. *)\n\n    intros m eq.\n\n(** Now we've chosen a particular [m] and introduced the assumption\n    that [double n = double m].  Since we are doing a case analysis on\n    [n], we also need a case analysis on [m] to keep the two \"in sync.\" *)\n\n    destruct m as [| m'] eqn:E.\n    + (* m = O *)\n\n(** The 0 case is trivial: *)\n\n    discriminate eq.\n    + (* m = S m' *)\n      apply f_equal.\n\n(** At this point, since we are in the second branch of the [destruct\n    m], the [m'] mentioned in the context is the predecessor of the\n    [m] we started out talking about.  Since we are also in the [S]\n    branch of the induction, this is perfect: if we instantiate the\n    generic [m] in the IH with the current [m'] (this instantiation is\n    performed automatically by the [apply] in the next step), then\n    [IHn'] gives us exactly what we need to finish the proof. *)\n\n      apply IHn'. simpl in eq. injection eq as goal. apply goal. Qed.\n\n(** What you should take away from all this is that we need to be\n    careful, when using induction, that we are not trying to prove\n    something too specific: When proving a property involving two\n    variables [n] and [m] by induction on [n], it is sometimes\n    crucial to leave [m] generic. *)\n\n(** The following exercise follows the same pattern. *)\n\n(** **** Exercise: 2 stars, standard (eqb_true)  *)\nTheorem eqb_true : forall n m,\n    n =? m = true -> n = m.\nProof.\n  intros n.\n  (*\n    On démontre par récurrence sur n que pour tout m\n    n =? m = true -> n  = m\n  *)\n  induction n as  [| n' IHn'].\n  - (*  Si n = 0, on prend un entier m et on suppose que 0 =? m = true. *)\n    intros m Eq.\n    (* On poursuit par une analyse de cas sur m : *)\n    destruct m as [| m'].\n    + (*  si m = 0, alors la conclusion est vérifiée *)\n      reflexivity.\n    + (*  si m = S m', alors  0 =? S m' s'évalue à false, *)\n      simpl in Eq.\n      (* contredisant l'hypothèse que 0 =? m = true.*)\n      discriminate Eq.\n  - (* Si n = S n', prend un entier m et on suppose que S n' =? m = true. *)\n    intros m Eq.\n    (* On fait une analyse de cas sur m : *)\n    destruct m as [|m'].\n    + (*  si m = 0 , alors S n' =? m s'évalue à false. *)\n      simpl in Eq.\n      (* Ce qui contredit les hypothèses. *)\n      discriminate Eq.\n    + (* si m = S m', alors S n' =? S m' s'évalue à n' =? m' *)\n      (*  Par hypothèse, cela implique que n'=? m' = true. *)\n      simpl in Eq.\n      (* Par récurence il s'ensuit que  n' = m'. *)\n      apply IHn' in Eq.\n      (*  Ainsi S n' = S m' et n = m. *)\n      rewrite Eq.\n      reflexivity.\nQed.\n  (** [] *)\n\n(** **** Exercise: 2 stars, advanced (eqb_true_informal) \n\n    On démontre par récurrence sur n que pour tout m\n    n =? m = true -> n  = m\n\n   Si n = 0, on prend un entier m et on suppose que 0 =? m = true.\n   On poursuit par une analyse de cas sur m :\n   - si m = 0, alors la conclusion est vérifiée\n   - si m = S m', alors  0 =? S m' s'évalue à false, contredisant l'hypothèse que\n     0 =? m = true.\n\n  Si n = S n', prend un entier m et on suppose que S n' =? m = true.\n  On fait une analyse de cas sur m :\n  - si m = 0 , alors S n' =? m s'évalue à false. Ce qui contredit les hypothèses.\n  - si m = S m', alors S n' =? S m' s'évalue à n' =? m'. Par hypothèse, cela implique que\n    n'=? m' = true. Par récurence il s'ensuit que  n' = m'. Ainsi S n' = S m' et n = m.\n\n\n\n    Give a careful informal proof of [eqb_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_proof : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, especially useful (plus_n_n_injective) \n\n    In addition to being careful about how you use [intros], practice\n    using \"in\" variants 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 n.\n  induction n as [| n' IHn'].\n  - simpl. intros m eq. destruct m as [| m'].\n    + reflexivity.\n    + simpl in eq. discriminate eq.\n  -  simpl.\n     intros m eq.\n     destruct m as [|m'].\n     + simpl in eq.\n       discriminate eq.\n     + simpl in eq.\n       Search (_ + S _).\n       rewrite <- plus_n_Sm in eq.\n       rewrite <- plus_n_Sm in eq.\n       injection eq as eq.\n       rewrite IHn' with (m:=m').\n       * reflexivity.\n       * apply eq.\nQed.\n\n\n(** [] *)\n\n(** The strategy of doing fewer [intros] before an [induction] to\n    obtain a more general IH doesn't always work by itself; sometimes\n    some _rearrangement_ of quantified variables is needed.  Suppose,\n    for example, that we wanted to prove [double_injective] by\n    induction on [m] instead of [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m' IHm'].\n  - (* m = O *) simpl. intros eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) discriminate eq.\n  - (* m = S m' *) intros eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) discriminate eq.\n    + (* n = S n' *) apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (And if we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce [n]\n    for us!)  *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    works, but it's not nice: We don't want to have to twist the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them!  Rather we want to state them in the clearest and\n    most natural way. *)\n\n(** What we can do instead is to first introduce all the quantified\n    variables and then _re-generalize_ one or more of them,\n    selectively taking variables out of the context and putting them\n    back at the beginning of the goal.  The [generalize dependent]\n    tactic does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m.\n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m' IHm'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) discriminate eq.\n  - (* m = S m' *) intros n eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) discriminate eq.\n    + (* n = S n' *) apply f_equal.\n      apply IHm'. injection eq as goal. apply goal. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n    _Theorem_: For any nats [n] and [m], if [double n = double m], then\n      [n = m].\n\n    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n      any [n], if [double n = double m] then [n = m].\n\n      - First, suppose [m = 0], and suppose [n] is a number such\n        that [double n = double m].  We must show that [n = 0].\n\n        Since [m = 0], by the definition of [double] we have [double n =\n        0].  There are two cases to consider for [n].  If [n = 0] we are\n        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']\n        for some [n'], we derive a contradiction: by the definition of\n        [double], we can calculate [double n = S (S (double n'))], but\n        this contradicts the assumption that [double n = 0].\n\n      - Second, suppose [m = S m'] and that [n] is again a number such\n        that [double n = double m].  We must show that [n = S m'], with\n        the induction hypothesis that for every number [s], if [double s =\n        double m'] then [s = m'].\n\n        By the fact that [m = S m'] and the definition of [double], we\n        have [double n = S (S (double m'))].  There are two cases to\n        consider for [n].\n\n        If [n = 0], then by definition [double n = 0], a contradiction.\n\n        Thus, we may assume that [n = S n'] for some [n'], and again by\n        the definition of [double] we have [S (S (double n')) =\n        S (S (double m'))], which implies by injectivity that [double n' =\n        double m'].  Instantiating the induction hypothesis with [n'] thus\n        allows us to conclude that [n' = m'], and it follows immediately\n        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just\n        what we wanted to show. [] *)\n\n(** **** Exercise: 3 stars, standard, especially useful (gen_dep_practice) \n\n    Prove this by induction on [l]. *)\n\nTheorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     nth_error l n = None.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Unfolding Definitions *)\n\n(** It sometimes happens that we need to manually unfold a name that\n    has been introduced by a [Definition] so that we can manipulate\n    the expression it denotes.  For example, if we define... *)\n\nDefinition square n := n * n.\n\n(** ... and try to prove a simple fact about [square]... *)\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\n  simpl.\n\n(** ... we appear to be stuck: [simpl] doesn't simplify anything, and\n    since we haven't proved any other facts about [square], there is\n    nothing we can [apply] or [rewrite] with. *)\n\n(**  To make progress, we can manually [unfold] the definition of\n    [square]: *)\n\n  unfold square.\n\n(** Now we have plenty to work with: both sides of the equality are\n    expressions involving multiplication, and we have lots of facts\n    about multiplication at our disposal.  In particular, we know that\n    it is commutative and associative, and from these it is not hard\n    to finish the proof. *)\n\n  rewrite mult_assoc.\n  assert (H : n * m * n = n * n * m).\n    { rewrite mult_comm. apply mult_assoc. }\n  rewrite H. rewrite mult_assoc. reflexivity.\nQed.\n\n(** At this point, some discussion of unfolding and simplification is\n    in order.\n\n    We already have observed that tactics like [simpl], [reflexivity],\n    and [apply] will often unfold the definitions of functions\n    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\n    [reflexivity], if we omit the [simpl]) will unfold [foo m] to\n    [(fun x => 5) m] and then further simplify this expression to just\n    [5]. *)\n\nFact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.\nProof.\n  intros m.\n  simpl.\n  reflexivity.\nQed.\n\n(** However, this automatic unfolding is somewhat conservative.  For\n    example, if we define a slightly more complicated function\n    involving a pattern match... *)\n\nDefinition bar x :=\n  match x with\n  | O => 5\n  | S _ => 5\n  end.\n\n(** ...then the analogous proof will get stuck: *)\n\nFact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  simpl. (* Does nothing! *)\nAbort.\n\n(** The reason that [simpl] doesn't make progress here is that it\n    notices that, after tentatively unfolding [bar m], it is left with\n    a match whose scrutinee, [m], is a variable, so the [match] cannot\n    be simplified further.  It is not smart enough to notice that the\n    two branches of the [match] are identical, so it gives up on\n    unfolding [bar m] and leaves it alone.  Similarly, tentatively\n    unfolding [bar (m+1)] leaves a [match] whose scrutinee is a\n    function application (that cannot itself be simplified, even\n    after unfolding the definition of [+]), so [simpl] leaves it\n    alone. *)\n\n(** At this point, there are two ways to make progress.  One is to use\n    [destruct m] to break the proof into two cases, each focusing on a\n    more concrete choice of [m] ([O] vs [S _]).  In each case, the\n    [match] inside of [bar] can now make progress, and the proof is\n    easy to complete. *)\n\nFact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  destruct m eqn:E.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(** This approach works, but it depends on our recognizing that the\n    [match] hidden inside [bar] is what was preventing us from making\n    progress. *)\n\n(** A more straightforward way forward is to explicitly tell Coq to\n    unfold [bar]. *)\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n\n(** Now it is apparent that we are stuck on the [match] expressions on\n    both sides of the [=], and we can use [destruct] to finish the\n    proof without thinking too hard. *)\n\n  destruct m eqn:E.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where [destruct] is used to\n    perform case analysis of the value of some variable.  Sometimes we\n    need to reason by cases on the result of some _expression_.  We\n    can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if n =? 3 then false\n  else if n =? 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (n =? 3) eqn:E1.\n    - (* n =? 3 = true *) reflexivity.\n    - (* n =? 3 = false *) destruct (n =? 5) eqn:E2.\n      + (* n =? 5 = true *) reflexivity.\n      + (* n =? 5 = false *) reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (n =? 3) then ... else ...].  But either\n    [n] is equal to [3] or it isn't, so we can use [destruct (eqb\n    n 3)] to let us reason about the two cases.\n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c]. *)\n\n(** **** Exercise: 3 stars, standard (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' IHl'].\n  - intros l1 l2 H. simpl in H.\n    injection H as H1 H2.\n    rewrite <- H1.\n    rewrite <- H2.\n    reflexivity.\n  - intros l1' l2' H'.\n    simpl in H'.  destruct x as [x1 x2].\ndestruct (split l') as [l1'' l2''].\n     injection  H' as H1 H2.\n     rewrite <- H1. rewrite <- H2.\n     simpl. rewrite -> IHl'.\n    reflexivity. reflexivity.\nQed.\n\n(** [] *)\n\n(** The [eqn:] part of the [destruct] tactic is optional: So far,\n    we've chosen to include it most of the time, just for the sake of\n    documentation.\n\n    However, when [destruct]ing compound expressions, the information\n    recorded by the [eqn:] can actually be critical: if we leave it\n    out, then [destruct] can erase information we need to complete a\n    proof.\n\n    For example, suppose we define a function [sillyfun1] like\n    this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if n =? 3 then true\n  else if n =? 5 then true\n  else false.\n\n(** Now suppose that we want to convince Coq that [sillyfun1 n]\n    yields [true] only when [n] is odd.  If we start the proof like\n    this (with no [eqn:] on the [destruct])... *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3).\n  (* stuck... *)\nAbort.\n\n(** ... then we are stuck at this point because the context does\n    not contain enough information to prove the goal!  The problem is\n    that the substitution performed by [destruct] is quite brutal --\n    in this case, it throws away every occurrence of [n =? 3], but we\n    need to keep some memory of this expression and how it was\n    destructed, because we need to be able to reason that, since [n =?\n    3 = true] in this branch of the case analysis, it must be that [n\n    = 3], from which it follows that [n] is odd.\n\n    What we want here is to substitute away all existing occurences of\n    [n =? 3], but at the same time add an equation to the context that\n    records which case we are in.  This is precisely what the [eqn:]\n    qualifier does. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got\n     stuck above, except that the context contains an extra\n     equality assumption, which is exactly what we need to\n     make progress. *)\n    - (* e3 = true *) apply eqb_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    - (* e3 = false *)\n     (* When we come to the second equality test in the body\n        of the function we are reasoning about, we can use\n        [eqn:] again in the same way, allowing us to finish the\n        proof. *)\n      destruct (n =? 5) eqn:Heqe5.\n        + (* e5 = true *)\n          apply eqb_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + (* e5 = false *) discriminate eq.  Qed.\n\n(** **** Exercise: 2 stars, standard (destruct_eqn_practice)  *)\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  intros. destruct b.\n  - destruct (f true) eqn:fTrue.\n    + rewrite -> fTrue.\n      apply fTrue.\n    + destruct (f false) eqn:fFalse.\n      * apply fTrue. * apply fFalse.\n - destruct (f false) eqn: fFalse.\n   + destruct (f true) eqn:fTrue.\n     * apply fTrue. * apply fFalse.\n   + rewrite -> fFalse.\n     apply fFalse.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Review *)\n\n(** We've now seen many of Coq's most fundamental tactics.  We'll\n    introduce a few more in the coming chapters, and later on we'll\n    see some more powerful _automation_ tactics that make Coq help us\n    with low-level details.  But basically we've got what we need to\n    get work done.\n\n    Here are the ones we've seen:\n\n      - [intros]: move hypotheses/variables from goal to context\n\n      - [reflexivity]: finish the proof (when the goal looks like [e =\n        e])\n\n      - [apply]: prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: apply a hypothesis, lemma, or constructor to\n        a hypothesis in the context (forward reasoning)\n\n      - [apply... with...]: explicitly specify values for variables\n        that cannot be determined by pattern matching\n\n      - [simpl]: simplify computations in the goal\n\n      - [simpl in H]: ... or a hypothesis\n\n      - [rewrite]: use an equality hypothesis (or lemma) to rewrite\n        the goal\n\n      - [rewrite ... in H]: ... or a hypothesis\n\n      - [symmetry]: changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]: changes a hypothesis of the form [t=u] into\n        [u=t]\n\n      - [transitivity y]: prove a goal [x=z] by proving two new subgoals,\n        [x=y] and [y=z]\n\n      - [unfold]: replace a defined constant by its right-hand side in\n        the goal\n\n      - [unfold... in H]: ... or a hypothesis\n\n      - [destruct... as...]: case analysis on values of inductively\n        defined types\n\n      - [destruct... eqn:...]: specify the name of an equation to be\n        added to the context, recording the result of the case\n        analysis\n\n      - [induction... as...]: induction on values of inductively\n        defined types\n\n      - [injection]: reason by injectivity on equalities\n        between values of inductively defined types\n\n      - [discriminate]: reason by disjointness of constructors on\n        equalities between values of inductively defined types\n\n      - [assert (H: e)] (or [assert (e) as H]): introduce a \"local\n        lemma\" [e] and call it [H]\n\n      - [generalize dependent x]: move the variable [x] (and anything\n        else that depends on it) from the context back to an explicit\n        hypothesis in the goal formula\n\n      - [f_equal]: change a goal of the form [f x = f y] into [x = y] *)\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. induction n as [| n' IH].\n  - intros m.\n    destruct m as [| m'].\n    + reflexivity.\n    + reflexivity.\n  - intros m. destruct m as [| m'].\n    + reflexivity.\n    + simpl. apply IH.\nQed.\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   (* THéorème : Pour tous n et m de type nat , (n =? m) = (m =? n)\n\n  preuve  : Par induction sur [n].\n\n  - premièrement, on suppose que [l = []]. Et on doit montre que\n       (0 =? m) = (m =? 0)\n       Par induction sur m ,\n       si m = 0, \n         On aura (0 =? 0) = (0 =? 0),\n         Ce qui est vrai est verifé par la definition eqb_true\n       si m = S m',\n         On \n  \n  - Secondement, on suppose que [l = n::l'], avec )\n\n    [] *)\n\n(** **** Exercise: 3 stars, standard, optional (eqb_trans)  *)\nTheorem eqb_trans : forall n m p,\n  n =? m = true ->\n  m =? p = true ->\n  n =? p = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine) \n\n    We proved, in an exercise above, that for all lists of pairs,\n    [combine] is the inverse of [split].  How would you formalize the\n    statement that [split] is the inverse of [combine]?  When is this\n    property true?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split (combine l1 l2) = (l1,l2)] to be true?) *)\n\nDefinition split_combine_statement : Prop\n  (* (\"[: Prop]\" means that we are giving a name to a\n     logical proposition here.) *)\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nTheorem split_combine : split_combine_statement.\nProof.\n(* FILL IN HERE *) Admitted.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_split_combine : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise) \n\n    This one is a bit challenging.  Pay attention to the form of your\n    induction hypothesis. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, especially useful (forall_exists_challenge) \n\n    Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n\n      forallb evenb [0;2;4;5] = false\n\n      forallb (eqb 5) [] = true\n\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n\n      existsb (eqb 5) [0;2;3;6] = false\n\n      existsb (andb true) [true;true;false] = true\n\n      existsb oddb [1;0;0;0;0;3] = true\n\n      existsb evenb [] = false\n\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n\n    Finally, prove a theorem [existsb_existsb'] stating that\n    [existsb'] and [existsb] have the same behavior.\n*)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_forallb_1 : forallb oddb [1;3;5;7;9] = true.\nProof. (* FILL IN HERE *) Admitted.\n\nExample test_forallb_2 : forallb negb [false;false] = true.\nProof. (* FILL IN HERE *) Admitted.\n\nExample test_forallb_3 : forallb evenb [0;2;4;5] = false.\nProof. (* FILL IN HERE *) Admitted.\n\nExample test_forallb_4 : forallb (eqb 5) [] = true.\nProof. (* FILL IN HERE *) Admitted.\n\nFixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_existsb_1 : existsb (eqb 5) [0;2;3;6] = false.\nProof. (* FILL IN HERE *) Admitted.\n\nExample test_existsb_2 : existsb (andb true) [true;true;false] = true.\nProof. (* FILL IN HERE *) Admitted.\n\nExample test_existsb_3 : existsb oddb [1;0;0;0;0;3] = true.\nProof. (* FILL IN HERE *) Admitted.\n\nExample test_existsb_4 : existsb evenb [] = false.\nProof. (* FILL IN HERE *) Admitted.\n\nDefinition existsb' {X : Type} (test : X -> bool) (l : list X) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nTheorem existsb_existsb' : forall (X : Type) (test : X -> bool) (l : list X),\n  existsb test l = existsb' test l.\nProof. (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* 2020-09-09 20:51 *)\n", "meta": {"author": "JeanDeboutGat", "repo": "Logique-Plus", "sha": "f27e260848b281cb46845d9f5352c18440706d8d", "save_path": "github-repos/coq/JeanDeboutGat-Logique-Plus", "path": "github-repos/coq/JeanDeboutGat-Logique-Plus/Logique-Plus-f27e260848b281cb46845d9f5352c18440706d8d/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.6517872698853576}}
{"text": "(***\n  Lowenheim's Formula Implementation\n\n  Authors:\n    Joseph St. Pierre\n    Spyridon Antonatos\n***)\n\n(*** Required Libraries ***)\n\nRequire Export terms.\n\n\nRequire Import List.\nImport ListNotations.\n\n\n\n(** * Introduction *)\n\n(** In this section we formulate Lowenheim's algorithm using the data\n    structures and functions defined in the [terms] library. The final occuring\n    main function, [Lowenheim_Main], takes as input a term and produces a\n    substitution that unifies the given term. The resulting substitution is said\n    to be a most general unifier and not a mere substitution, but that statement\n    is proven in the [lowenheim_proof] file. In this section we focus on the\n    formulation of the algorithm itself, without any proofs about the properties\n    of the formula or the algorithm. *)\n\n\n(** * Lowenheim's Builder *)\n\n(** In this subsection we are implementing the main component of Lowenheim's\n    algorithm, which is the \"builder\" of Lowenheim's substitution for a given\n    term. This implementation strictly follows as close as possible the formal,\n    mathematical format of Lowenheim's algorithm. *)\n\n(** Here is a skeleton function for building a substition on the format\n    $\\sigma(x) := (s + 1) \\ast \\sigma_{1}(x) + s \\ast \\sigma_{2}(x)$, each\n    variable of a given list of variables, a given term [s] and subtitutions\n    $\\sigma_{1}$ and $\\sigma_{2}$. This skeleton function is a more general\n    format of Lowenheim's builder. *)\n\nFixpoint build_on_list_of_vars (list_var : var_set) (s : term) (sig1 : subst)\n                               (sig2 : subst) : subst :=\n  match list_var with\n  | [] => []\n  | v' :: v => (v', (s + T1) * apply_subst (VAR v') sig1 +\n                    s * apply_subst (VAR v') sig2)\n               :: build_on_list_of_vars v s sig1 sig2\n  end.\n\n\n(** This is the function to build a Lowenheim subsitution for a term _t_,\n    given the term _t_ and a unifier of _t_, using the previously defined\n    skeleton function. The list of variables is the variables within _t_ and the\n    substitions are the identical subtitution and the unifer of the term. This\n    fuction will often be referred in the rest of the document as our\n    \"Lowenheim builder\" or the \"Lowenheim substitution builder\", etc. *)\n\nDefinition build_lowenheim_subst (t : term) (tau : subst) : subst :=\n  build_on_list_of_vars (term_unique_vars t) t\n                        (build_id_subst (term_unique_vars t)) tau.\n\n\n\n(** * Lowenheim's Algorithm *)\n\n(** In this subsection we enhance Lowenheim's builder to the level of a\n    complete algorithm that is able to find ground substitutions before feeding\n    them to the main formula to generate a most general unifier *)\n\n(** ** Auxillary Functions and Definitions *)\n\n(** This is a function to update a term, after it applies to it a given\n    substitution and simplifies it. *)\n\nDefinition update_term (t : term) (s' : subst) : term :=\n  simplify (apply_subst t s').\n\n(** Here is a function to determine if a term is the ground term [T0]. *)\n\nDefinition term_is_T0 (t : term) : bool :=\n  identical t T0.\n\n(** In this development we have the need to be able to represent both the\n    presence and the absence of a substitution. In case for example our\n    [find_unifier] function cannot find a unifier for an input term, we need to\n    be able to return a [subst nil] type, like a substitution option that states\n    no substition was found. We are using the built-in [Some] and [None]\n    inductive options (that are used as [Some] $\\sigma$ and [None]) to represent\n    some substitution and no substition repsectively. The type of the two above\n    is the inductive [option {A:type}] that can be attached to any type; in our\n    case it is [option subst]. *)\n\n(** Our Lowenheim builder works when we provide an already existing unifier of\n    the input term _t_. For our implementation to be complete we need to be able\n    to generate that initial unifier ourselves. That is why we first need to\n    define a function to find all possible \"01\" substitutions (substitutions\n    where each variable gets mapped to [T0] or [T1]. *)\n\nFixpoint all_01_substs (vars : var_set) : list subst :=\n  match vars with\n  | [] => [[]]\n  | v :: v' => (map (fun s => (v, T0) :: s) (all_01_substs v')) ++\n               (map (fun s => (v, T1) :: s) (all_01_substs v'))\n  end.\n\n\n(** Next is a function to find an initial \"ground unifier\" for our Lowenheim\n    builder function. It finds a substitution with ground terms that makes the\n    given input term equivalent to [T0]. *)\n\nFixpoint find_unifier (t : term) : option subst :=\n  find (fun s => match update_term t s with\n                 | T0 => true\n                 | _ => false\n                 end) (all_01_substs (term_unique_vars t)).\n\n(** ** Lowenheim's Main Function *)\n\n(** Here is the main Lowenheim's formula; given a term, produce an MGU (a most\n    general substitution that when applied on the input term, it makes it\n    equivalent to [T0]), if there is one. Otherwise, return [None]. This\n    function is often referred in the rest of the document as \"Lowenheim Main\"\n    function or \"Main Lowenheim\" function, etc. *)\n\nDefinition Lowenheim_Main (t : term) : option subst :=\n  match find_unifier t with\n  | Some s => Some (build_lowenheim_subst t s)\n  | None => None\n  end.\n\n\n(** * Lowenheim's Functions Testing *)\n\n(** In this subsection we explore ways to test the correctness of our Lowenheim's\n    functions on specific inputs. *)\n\n(** Here is a function to test the correctness of the output of the\n    [find_unifier] helper function defined above. True means expected output was\n    produced, false otherwise. *)\n\nDefinition Test_find_unifier (t : term) : bool :=\n  match find_unifier t with\n  | Some s => term_is_T0 (update_term t s)\n  | None => true\n  end.\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/lowenheim_formula.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.651762162311913}}
{"text": "(* Since Coq allows us to manipulate proofs as first class objects,\n   it is very common to design types which not only encapsulate data,\n   but also proofs that the data satisfies some required property.\n   These proofs are usually deemed irrelevant, and two objects whose\n   data coincide are often deemed equal, regardless of the specifics\n   of the proofs attributes they contain. However, even with proof\n   irrelevance, the actual mechanics of coq tactics and rewrites may \n   not be so obvious to handle, and some subtle tricks need to be \n   applied. Let us consider an example: *) \n\n(* Some predicate on nat *)\nParameter P : nat -> Prop.\n\n(* Some type which encapsulate a natural number, together with a proof *)\nInductive Obj : Type :=\n| make : forall n, P n -> Obj\n.\n\n(* We assume proof irrelevance *)\nAxiom proof_irrelevance : forall (P:Prop) (p q:P), p = q.\n\n(* Now let us consider the following result *)\nExample obvious : forall (n m:nat) (p:P n) (q: P m),\n    n = m -> make n p = make m q.\nProof.\n    intros n m p q Enm. \n    Fail rewrite Enm.\n    (*\n    Error: Abstracting over the term \"n\" leads to a term\n    fun n0 : nat => make n0 p = make m q\n    which is ill-typed.\n        Reason is: Illegal application: \n        The term \"make\" of type \"forall n : nat, P n -> Obj\"\n        cannot be applied to the terms\n         \"n0\" : \"nat\"\n          \"p\" : \"P n\"\n          The 2nd term has type \"P n\" which should be coercible to \n          \"P n0\".\n   *)\n\n   (* We simply rewrite the equality 'n = m' in the goal because the type\n      of p is dependent on n. We need to abstract over p. *)\n   revert p. (* same as generalize p. clear p. *)\n   (* We can now successfully rewrite Enm, then re-introduce p *)\n   rewrite Enm. intros p.\n   (* Now both p and q are of type P m, and we simply need to use irrelevance *)\n   rewrite (proof_irrelevance _ p q).\n   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/cat/Rewrite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.651762155492601}}
{"text": "Require Export Basics.\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(* some helpful arithmetic Proofs *)\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 plus_n_Sm : forall n m : nat, \n  S (n + m) = n + (S m).\nProof. \n  intros n m.  induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    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    rewrite plus_0_r. reflexivity.\n  Case \"n = S n'\".\n    simpl. \n    rewrite IHn'. \n    rewrite -> plus_n_Sm. reflexivity.\nQed.\n\nDefinition neq_0_b (n :nat) : bool := \n  match n with \n    |0 => false \n    |S _ => true \nend.\n\nTheorem neq_0_dist :\n  forall (n m : nat),\n  neq_0_b (n + m) = orb (neq_0_b n) (neq_0_b m).\nProof.\n  intros. destruct n. reflexivity. reflexivity.\nQed.  \n\n(* bin is defined here *)\n\nInductive bin : Type :=\n| Zero : bin\n| D : bin -> bin\n| P : bin -> bin.\n\nFixpoint inc (n : bin) : bin :=\n  match n with\n   | Zero => P Zero\n   | D n' => P n'\n   | P n' => D (inc n')\n  end.\n\nFixpoint gt_Zero (n : bin) : bool :=\n  match n with\n    |Zero => false\n    |D n' => gt_Zero n'\n    |P n' => true\n  end.\n\nFixpoint toUnary (n : bin) : nat :=\n  match n with\n    |Zero => O\n    |D n' => 2 * toUnary n'\n    |P n' => S (2 * toUnary n')\n  end.\n\nFixpoint fromUnary (n : nat) : bin :=\n  match n with\n    |O => Zero\n    |S n' => inc (fromUnary n')\nend.\n\nTheorem comm_inc_binunary :\n  forall (n : bin),\n  toUnary (inc n) = S (toUnary n).\nProof.\n  induction n. reflexivity.\n  reflexivity.\n  simpl. rewrite IHn.\n  simpl. rewrite <- plus_n_Sm.\n  reflexivity.\nQed.\n\nTheorem leftInv : \n  forall (x : nat),\n  toUnary (fromUnary x) = x.\nProof.\n  induction x. Case \"base\". reflexivity.\n  simpl. rewrite comm_inc_binunary.\n  rewrite IHx.\n  reflexivity.\nQed.\n\n(* Here is the definition of normalize *)\n\nFixpoint dropZeros (n: bin) :bin :=\n  match n with\n    | Zero => Zero\n    | D n' => dropZeros n'\n    | P n' => P n'\nend.\n\nFixpoint conj (n: bin) (con: bin -> bin) : bin :=\n  match n with\n    | Zero => con Zero\n    | D n' => D (conj n' con)\n    | P n' => P (conj n' con)\n  end.\n\n(* this is slower than reverse with an accumulator, but easier to reason about *)\nFixpoint reverse (n : bin) : bin :=\n  match n with\n    | Zero => Zero\n    | D n' => conj (reverse n') D\n    | P n' => conj (reverse n') P\nend.\n\nFixpoint normalize (n : bin) :bin :=\n  reverse ( dropZeros ( reverse n)).\n\n\nLemma conj_revD : \n  forall (b : bin),\n  reverse (conj b D) = D (reverse b).\nProof.\n  intros. induction b. reflexivity.\n  simpl.  rewrite IHb. reflexivity.\n  simpl.  rewrite IHb. reflexivity.\nQed.\n\nLemma conj_revP : \n  forall (b : bin),\n  reverse (conj b P) = P (reverse b).\nProof.\n  intros. induction b. reflexivity.\n  simpl.  rewrite IHb. reflexivity.\n  simpl.  rewrite IHb. reflexivity.\nQed.\n\nTheorem rev_inv_rev:\n  forall (x : bin),\n  reverse (reverse x) = x.\nProof.\n  intros. induction x. reflexivity.\n  simpl. rewrite conj_revD. rewrite IHx. reflexivity.\n  simpl. rewrite conj_revP. rewrite IHx. reflexivity.\nQed.\n\nTheorem toUnary_distD:\n  forall (x : bin),\n  toUnary (D x) = (toUnary x) + (toUnary x) .\nProof.    \n  intros. induction x. simpl. reflexivity.\n  simpl. rewrite plus_0_r. rewrite plus_0_r. reflexivity.\n  simpl. rewrite plus_0_r. rewrite plus_0_r. reflexivity.\nQed.  \n\nTheorem toUnary_distP:\n  forall (x : bin),\n  toUnary (P x) = S (toUnary x + toUnary x).\nProof.\n  induction x. simpl. reflexivity.\n  simpl. rewrite plus_0_r. rewrite plus_0_r. reflexivity.\n  simpl. rewrite plus_0_r. rewrite plus_0_r. reflexivity.\nQed.\n\n(* Here I used inversion. Basically if you have an absurd \npremise you can derive an absurd conclusion. *)\nTheorem fromUnary_distD:\n  forall (n : nat),\n  neq_0_b n = true -> D (fromUnary n) = fromUnary(n + n).  \nProof.\n  intros. induction n. inversion H.\n  simpl. rewrite <- plus_n_Sm. simpl. destruct n. reflexivity. \n  rewrite <- IHn. simpl. reflexivity. reflexivity.\nQed.\n\nTheorem fromUnary_distP:\n  forall (n : nat),\n  P (fromUnary n) = inc (fromUnary(n + n)).\nProof.\n  induction n. reflexivity.\n  simpl. rewrite <- plus_comm. simpl. rewrite <- IHn. simpl. reflexivity.\nQed.\n\nTheorem has_P_not_zero:\n  forall (x : bin),\n  neq_0_b (toUnary (conj x P)) = true.\nProof.\n  induction x. reflexivity.\n  simpl. rewrite plus_0_r. rewrite neq_0_dist. rewrite IHx. reflexivity.\n  reflexivity.\nQed.\n\nTheorem trailing_P_is_normal:\n  forall (y : bin),\n  fromUnary (toUnary (conj y P)) = conj y P.\nProof.\n  induction y. reflexivity.\n  simpl. rewrite plus_0_r. rewrite <- fromUnary_distD. rewrite IHy. reflexivity.\n  rewrite has_P_not_zero. reflexivity.\n  simpl. rewrite plus_0_r. rewrite <- fromUnary_distP. rewrite IHy. reflexivity.\nQed.\n\nTheorem toUnary_drop_trailing_D :\n  forall (y : bin),\n  toUnary (conj y D) = toUnary y.\nProof.\n  intros. induction y. reflexivity.\n  simpl. rewrite IHy. reflexivity.\n  simpl. rewrite IHy. reflexivity.\nQed.\n\nTheorem dropFront :\n  forall (x : bin),\n  reverse (dropZeros x) = (fromUnary (toUnary (reverse x))).\nProof.\n induction x. reflexivity.\n simpl. rewrite toUnary_drop_trailing_D. rewrite IHx. reflexivity.\n simpl. rewrite trailing_P_is_normal. reflexivity.\nQed.\n\nTheorem rightInv:\n  forall (z : bin),\n  fromUnary (toUnary z) = normalize z.\nProof.\n  destruct z. reflexivity.\n  simpl. rewrite plus_0_r.\n  rewrite dropFront. rewrite conj_revD. rewrite rev_inv_rev. rewrite toUnary_distD. reflexivity.\n  simpl. rewrite plus_0_r.\n  rewrite dropFront. rewrite conj_revP. rewrite rev_inv_rev. rewrite toUnary_distP. reflexivity.\nQed.\n\n\n(* Things I didn't end up needing *)\n \nTheorem fromUnary_inj :\n  forall (x y: nat),\n  fromUnary x = fromUnary y -> x = y.\nProof.\n  intros. rewrite <- leftInv. rewrite <- H. rewrite leftInv. reflexivity.\nQed.  \n\n\nFixpoint rev (n: bin) (acc : bin) : bin :=\n  match n with\n    | Zero => acc\n    | D n' => rev n' (D acc)\n    | P n' => rev n' (P acc)\nend.\n\n(* this reverse uses an accumulator and is O(n) instead of O(n^2) *)\nDefinition reverse_fast (n : bin) : bin :=\n  rev n Zero.\n\n(* never got around to proving this *)\nTheorem rev_eq_rev_fast :\n  forall (n : bin), reverse n = reverse_fast n.\nProof.\nAbort.\n\n(* this is another normalize function I defined I belive it should be a bit faster, \n but looks hard to reason about. *)\n\nFixpoint revpend (n: bin) (m: bin) : bin :=\n  match n with\n    |Zero => m\n    |D n' => D (revpend n' m)\n    |P n' => P (revpend n' m)\n  end.\n\nFixpoint nml (n : bin) (acc : bin) : bin :=\n  match n with\n    |Zero => Zero\n    |D n' => nml n' (D acc)\n    |P n' => revpend (D acc) (nml n' Zero)\n  end.\n\nDefinition normalize' (n : bin) : bin := \n  nml n Zero.\n\n\n", "meta": {"author": "sftypes", "repo": "software-foundations", "sha": "6d3754608420aeb5dfe8abfe2275a623f0083459", "save_path": "github-repos/coq/sftypes-software-foundations", "path": "github-repos/coq/sftypes-software-foundations/software-foundations-6d3754608420aeb5dfe8abfe2275a623f0083459/stump_smith_normalize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.6517621527991403}}
{"text": "Require Import STLCdbj.syntax.\nRequire Import STLCdbj.bindings.\nRequire Import Utf8.\n\n\nImplicit Types V: Set.\n\n\n\n\n\nDefinition Ctx V := V → ty.\n\nDefinition DV_extend {V} {K:Type} (f: V -> K) (T : K) : inc V -> K :=\n  fun t =>\n    match t with\n    | VZ => T\n    | VS k => f k\n    end.\n\nNotation ctx_append Γ T := (DV_extend Γ T).\n\n(* \nInductive val (V: Set) : Set :=\n  | v_var  : V -> val V\n  | v_true : val V\n  | v_false : val V \n  | v_abs  : exp (inc V) -> val V\nwith exp (V : Set) : Set :=\n  | e_val  : val V -> exp V\n  | e_if   : exp V -> exp V -> exp V -> exp V\n  | e_app  : exp V -> exp V -> exp V.\n   *)\n\nInductive val_has_type {V} : Ctx V -> val V -> ty -> Prop :=\n  | htv_var : forall Γ x T,\n    Γ x = T ->\n    val_has_type Γ (v_var x) T\n  | htv_true : forall Γ,\n    val_has_type Γ v_true ty_bool\n  | htv_false : forall Γ,\n    val_has_type Γ v_false ty_bool\n  | htv_abs : forall Γ exp_body Ti To,\n    exp_has_type (ctx_append Γ Ti) exp_body To ->\n    val_has_type Γ (v_abs Ti exp_body) (ty_arrow Ti To)\nwith exp_has_type {V} : Ctx V -> exp V -> ty -> Prop :=\n  | hte_val : forall Γ x T,\n    val_has_type Γ x T ->\n    exp_has_type Γ (e_val x) T\n  | hte_if : forall Γ cond a b T,\n    exp_has_type Γ cond ty_bool ->\n    exp_has_type Γ a T ->\n    exp_has_type Γ b T ->\n    exp_has_type Γ (e_if cond a b) T\n  | hte_app : forall Γ a b Ti To,\n    exp_has_type Γ a (ty_arrow Ti To) ->\n    exp_has_type Γ b Ti ->\n    exp_has_type Γ (e_app a b) To.\n\n\nNotation \"Gamma '⊢ᵛ' t '∈' T\" := (val_has_type Gamma t T) \n(at level 101).\n\nNotation \"Gamma '⊢ᵉ' t '∈' T\" := (exp_has_type Gamma t T) \n(at level 101).\n\n", "meta": {"author": "DKXXXL", "repo": "Redstone", "sha": "02873ec15605ed90a2f43b6e7132be72bb20b8cc", "save_path": "github-repos/coq/DKXXXL-Redstone", "path": "github-repos/coq/DKXXXL-Redstone/Redstone-02873ec15605ed90a2f43b6e7132be72bb20b8cc/STLCdbj/syn_typing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6517621453207398}}
{"text": "Require Export Omega.\nRequire Export matroid_axioms.\n\n(*****************************************************************************)\n(** Proof of matroid' to matroid **)\n\n\nSection s_matroid'ToMatroid.\n\nContext `{M : Matroid'}.\n\nLemma rk_compat:\n  forall x x', Equal x x' ->\n     rk x = rk x'.\nProof.\nintros;apply rk_compat;assumption.\nQed.\n\n(*\nGlobal Add Morphism rk : rk_mor.\nProof.\n exact rk_compat.\nQed.\n*)\n\nGlobal Instance rk_mor : Proper (Equal ==> Logic.eq) rk.\nProof.\n exact rk_compat.\nQed.\n\nLemma matroid1_a : forall X, rk X >= 0.\nProof.\napply set_induction.\nintros.\nsetoid_replace s with empty.\ngeneralize matroid1';omega.\nfsetdecide.\nintros.\nassert (rk s <= rk (add x s) <= rk s + 1).\napply matroid2'.\nomega.\nQed.\n\nLemma matroid1_b : forall X, rk X <= cardinal X.\nProof.\napply set_induction.\nintros.\nsetoid_replace s with empty by fsetdecide.\nrewrite matroid1';auto.\nomega.\n\nintros.\nassert (rk s <= rk (add x s) <= rk s + 1).\napply matroid2'.\nassert (cardinal s' = S (cardinal s)).\neapply cardinal_2;eauto.\nrewrite H4.\nsetoid_replace s' with (add x s).\nomega.\nrewrite <- Add_Equal;auto.\nQed.\n\nLemma singleton_eq : forall x y, In y (singleton x) -> x [==] y.\nProof.\nintros.\nfsetdecide.\nQed.\n\nHint Resolve singleton_eq.\n\nLemma set_fact_1 : forall x E A E' , ~ In x A -> ~ In x E -> \nEqual (union E (add x A)) E' ->\nEqual (union E A) (diff E' (singleton x)).\nProof.\nintros.\nassert(HH : ~ (In x (A ++ E))).\nfsetdec.\nrewrite <-H2.\nclear H0 H1 H2.\nfsetdecide.\nQed.\n\nLemma set_fact_2 : forall E E' x, \n Subset E E' -> \n ~ In x E -> \n Subset E (diff E' (singleton x)).\nProof.\nintros.\nfsetdecide.\nQed.\n\nLemma set_fact_3: forall e', forall x : Point, \nIn x e'  -> Equal (add x (diff e' (singleton x))) e'.\nProof.\nintros.\nassert(HH := add_remove H0).\nfsetdecide.\nQed.\n\nLemma matroid2:\n   forall e e',Subset e e' -> rk(e)<=rk(e').\nProof.\nintros.\nelim (subset_exists e e' H0).\nintros e'' He.\n\ngeneralize H0; clear H0.\ngeneralize He; clear He.\ngeneralize e; clear e.\ngeneralize e'; clear e'.\ngeneralize e''; clear e''.\n \napply (set_induction (P:= fun e'' => forall (e' e : Set_of_points),\nEqual (union e e'') e' -> Subset e e' -> rk e <= rk e')).\nintros.\nassert (Equal e e').\nfsetdecide.\nrewrite H3;auto.\n\nintros.\n\nelim (In_dec x e);intro.\napply (H0 e' e).\nsetoid_replace (union e s') with (union e s) in H3.\nauto.\nsetoid_replace s' with (add x s) in H3 by (apply -> Add_Equal;auto).\nsetoid_replace s' with (add x s) by (apply -> Add_Equal;auto).\nclear H0 H1 H2 H3 H4.\nfsetdecide.\nauto.\n\nassert (Equal (union e s) (diff e' (singleton x))).\napply set_fact_1;auto.\nsetoid_replace s' with (add x s) in H3 by (apply -> Add_Equal;auto).\nauto.\n\nassert (Subset e (diff e' (singleton x))).\napply set_fact_2;auto.\nassert (T:= H0 (diff e' (singleton x)) e H5 H6).\n\nassert (rk (diff e' (singleton x)) <= rk (add x (diff e' (singleton x))))\nby (generalize (matroid2' (diff e' (singleton x)) x); intros;intuition).\nassert (Equal (add x (diff e' (singleton x))) e').\napply set_fact_3.\nsetoid_replace s' with (add x s) in H3 by (apply -> Add_Equal;auto).\nrewrite <- H3.\nclear H0 H1 H2 H3 H4 H5 H6 H7.\nfsetdecide.\n\nrewrite H8 in H7.\nomega.\nQed.\n\n\nLemma matroid3:\nforall e e', rk(union e e') + rk(inter e e') <= rk(e) + rk(e'). \nProof.\napply (set_induction (P:= fun e => forall e' : set Point, \nrk (e ++ e')%set + rk (inter e e') <= rk e + rk e')).\n\nintros.\nassert(HH : Equal (s ++ e') e').\nfsetdecide.\nassert(HH0 : Equal (inter s e') s).\nfsetdecide.\nrewrite HH.\nrewrite HH0.\nomega.\n\nintros.\nassert(HH := Add_Equal x s s').\nassert(HH0 : Equal s' {x; s}).\nintuition.\nrewrite HH0.\n\ncase_eq(In_dec x e').\nintros.\nassert(HH1 : Equal ({x;s} ++ e') (s ++ e')).\nclear H1 H2 HH HH0.\nfsetdecide.\nassert(HH2 : Equal ({x;inter s e'}) (inter {x;s} e')).\nclear H1 H2 HH HH0 H3 HH1.\nfsetdecide.\nrewrite HH1.\nrewrite <-HH2.\nassert(HH3 := matroid2' s x).\nassert(HH4 := matroid2' (inter s e') x).\n\n\n(*\n\napply le_trans with(m:= rk s + rk e').\n2:omega.\napply le_trans with (m:= rk (union s e') + rk ((inter s e') + 1)).\nadmit.\nomega.\n\nintros.\nassert(HH2 : Equal (inter {x;s} e') (inter s e')).\nclear H0 H2 HH HH0.\napply inter_add_2.\nassumption.\nrewrite HH2.\n*)\n\n(*\napply le_trans with (m:= rk ( union s e') + rk (inter s e')).\nfsetdec.\n*)\n\n(*\ngeneralize s'.\napply (set_induction (P:= fun e' => forall s'0: set Point, \nrk (s'0 ++ e')%set + rk (inter s'0 e') <= rk s'0 + rk e')).\n\nintros.\nassert(HH : Equal (s'0 ++ s0) s'0).\nfsetdecide.\nassert(HH0 : Equal (inter s'0 s0) s0).\nfsetdecide.\nrewrite HH.\nrewrite HH0.\nomega.\n\nintros.\nassert(HH := matroid3').\n\n\nintros.\napply (set_induction (P:= fun e' => \nrk (s' ++ e')%set + rk (inter s' e') <= rk s' + rk e')).\n\nintros.\nassert(HH : Equal (s' ++ s0) s').\nfsetdecide.\nassert(HH0 : Equal (inter s' s0) s0).\nfsetdecide.\nrewrite HH.\nrewrite HH0.\nomega.\n\nintros.\n\n*)\n\nAdmitted.\n\nEnd s_matroid'ToMatroid.\n", "meta": {"author": "ProjectiveGeometry", "repo": "ProjectiveGeometry", "sha": "4f7f4e6c14580833c91fdef38d048259fb454b88", "save_path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry", "path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry/ProjectiveGeometry-4f7f4e6c14580833c91fdef38d048259fb454b88/SandBox/matroid_p_to_matroid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.6517621432863675}}
{"text": "Require Import init.\n\nRequire Import zorn.\n\nRequire Export set.\n\nSection ZornSet.\n\nContext {U : Type}.\n\nLocal Instance subset_order : Order (U → Prop) := {le := subset}.\n\nVariable SS : (U → Prop) → Prop.\nHypothesis SS_union : ∀ F : (set_type SS) → Prop, is_chain le F →\n    SS (⋃ (image_under (λ S, [S|]) F)).\n\nTheorem set_zorn : ∃ S : set_type SS, ∀ A : set_type SS, ¬([S|] ⊂ [A|]).\nProof.\n    pose proof (zorn (le (U := set_type SS))) as S_ex.\n    prove_parts S_ex.\n    {\n        intros F F_chain.\n        specialize (SS_union F F_chain).\n        exists [_|SS_union].\n        intros A FA.\n        unfold le; cbn.\n        apply union_sub.\n        exact (image_under_in FA).\n    }\n    destruct S_ex as [S S_max].\n    exists S.\n    intros A.\n    specialize (S_max A).\n    setoid_rewrite <- set_type_lt in S_max.\n    exact S_max.\nQed.\n\nEnd ZornSet.\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Set/zorn_set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6517463688958366}}
{"text": "Require Import Bignums.BigZ.BigZ CRArith model.totalorder.QposMinMax\n        ARbigD ARbigQ ARQ ARtrans ARsign.\n\nDefinition myAR := ARbigD.\n\nDefinition answer (n : positive) (r : ARbigD) : bigZ :=\n let m := iter_pos _ (Pmult 10) 1%positive n in \n let (a, b) := (approximate r (Qpos2QposInf (1#m)) : bigD) * 'Zpos m in \n BigZ.shiftl a b.\n\n(* To avoid timing the printing mechanism *)\nDefinition no_answer (n : positive) (r : myAR) :=\n  let m := iter_pos _ (Pmult 10) 1%positive n in\n  let _ := approximate r (Qpos2QposInf (1#m)) in\n  tt.\n\n(* xkcd.org/217 *)\nDefinition xkcd : myAR := (ARexp ARpi)-ARpi.\n\nTime Eval vm_compute in (answer 10 xkcd).\n\nExample xkcd217A : ARltT xkcd ('20%Z).\nProof. Time AR_solve_ltT (-8)%Z. Defined.\n\n(* Many of the following expressions are taken from the \"Many Digits friendly competition\" problem set *)\n\n(* Instance resolution takes 3s *)\nTime Definition P01 : myAR := ARsin (ARsin (AQsin 1)).\n\nTime Eval vm_compute in (answer 500 P01).\nTime Eval vm_compute in (no_answer 500 P01).\nDefinition P02 : myAR := ARsqrt (ARcompress ARpi).\nTime Eval vm_compute in (answer 500 P02).\n\nDefinition P03 : myAR := ARsin (AQexp 1).\nTime Eval vm_compute in (answer 500 P03).\n\nDefinition P04 : myAR := ARexp (ARcompress (ARpi * AQsqrt ('163%Z))).\nTime Eval vm_compute in (answer 500 P04).\n\nDefinition P05 : myAR := ARexp (ARexp (AQexp 1)).\nTime Eval vm_compute in (answer 500 P05).\n\nDefinition P07 : myAR := AQexp ('1000%Z).\nTime Eval vm_compute in (answer 2000 P07).\n\nDefinition P08 : myAR := AQcos ('(10^50)%Z).\nTime Eval vm_compute in (answer 2000 P08).\n\nDefinition C02_prf : ARapartT (ARpi : myAR) (0 : myAR).\nProof. AR_solve_apartT (-8)%Z. Defined.\n\nDefinition C02 : myAR := ARsqrt (AQexp 1 * ARinvT ARpi C02_prf).\nTime Eval vm_compute in (answer 250 C02).\n\nDefinition C03 : myAR := ARsin (ARcompress ((AQexp 1 + 1) ^ (3:N))).\nTime Eval vm_compute in (answer 500 C03).\n\nDefinition C04 : myAR := ARexp (ARcompress (ARpi * AQsqrt ('2011%Z))).\nTime Eval vm_compute in (answer 500 C04).\n\nDefinition C05 : myAR := ARexp (ARexp (ARsqrt (AQexp 1))).\nTime Eval vm_compute in (answer 500 C05).\n\n(* slow *) (*\nDefinition C07 : myAR := ARpi ^ 1000%N.\nTime Eval vm_compute in (answer 50 C07).\n*)\nDefinition ARtest1 : myAR := ARpi.\nTime Eval vm_compute in (answer 1500 ARtest1).\n\nDefinition ARtest2 : myAR := ARarctan (ARcompress ARpi).\nTime Eval vm_compute in (answer 100 ARtest2).\n\nDefinition ARtest3 : myAR := ARsqrt 2.\nTime Eval vm_compute in (answer 1000 ARtest3).\n\nDefinition ARtest4 : myAR := ARsin ARpi.\nTime Eval vm_compute in (answer 500 ARtest4).\n", "meta": {"author": "coq-community", "repo": "corn", "sha": "cfbf6b297643935f0fe7e22d2b14b462bf7e3095", "save_path": "github-repos/coq/coq-community-corn", "path": "github-repos/coq/coq-community-corn/corn-cfbf6b297643935f0fe7e22d2b14b462bf7e3095/examples/RealFaster.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6517463624833053}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\nRequire Import Coq.micromega.Lia.\nRequire Import List.\nImport ListNotations.\n\nDefinition surjective (X Y : Type) (f : X -> Y) : Prop :=\n  forall y, exists x, f x = y.\n\nTheorem Cantor X : ~ exists f : X -> X -> Prop,\n  surjective f.\nProof.\n  intros [f A].\n  pose (g := fun x => ~ f x x).\n  destruct (A g) as [x B].\n  assert (C : g x <-> f x x).\n  { rewrite B. intuition. }\n  unfold g in C.\n  intuition.\nQed.\n", "meta": {"author": "Kraks", "repo": "playground", "sha": "677da3823615d4e241f7d1de05ee9b79ddabb118", "save_path": "github-repos/coq/Kraks-playground", "path": "github-repos/coq/Kraks-playground/playground-677da3823615d4e241f7d1de05ee9b79ddabb118/coq/Cantor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213880824789, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6517463582078415}}
{"text": "(*\nI hereby assign copyright in my past and future contributions \nto the Software Foundations project to the Author of Record of \neach volume or component, to be licensed under the same terms \nas the rest of Software Foundations. I understand that, at present, \nthe Authors of Record are as follows: For Volumes 1 and 2, known \nuntil 2016 as \"Software Foundations\" and from 2016 as (respectively) \n\"Logical Foundations\" and \"Programming Foundations,\" and for Volume 4, \n\"QuickChick: Property-Based Testing in Coq,\" the Author of Record is \nBenjamin C. Pierce. For Volume 3, \"Verified Functional Algorithms\", \nthe Author of Record is Andrew W. Appel. For components outside of \ndesignated volumes (e.g., typesetting and grading tools and other \nsoftware infrastructure), the Author of Record is Benjamin Pierce.\n*)\n\n\nFrom LF Require Export Poly.\n\n(*Exercise 1*)\n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n\n      forallb evenb [0;2;4;5] = false\n\n      forallb (beq_nat 5) [] = true\n\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n\n      existsb (beq_nat 5) [0;2;3;6] = false\n\n      existsb (andb true) [true;true;false] = true\n\n      existsb oddb [1;0;0;0;0;3] = true\n\n      existsb evenb [] = false\n\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n\n    Finally, prove a theorem [existsb_existsb'] stating that\n    [existsb'] and [existsb] have the same behavior. *)\n\n(* FILL IN HERE *)\n\n\nRequire Export Tactics.\n\n\nCheck 3 = 3.\nCheck forall n m : nat, n + m = m + n.\nCheck 2 = 2.\nCheck forall n : nat, n = 2.\nCheck 3 = 4.\n\nTheorem plus_2_2_is_4 :\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 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. inversion H. reflexivity.\nQed.\n\nCheck @eq.\n\n\n\nCheck and.\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\n\nProof.\n  (* WORKED IN CLASS *)\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\n(*Exercise 2*)\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    + inversion H.\n  - destruct m.\n    + reflexivity.\n    + rewrite plus_comm in H.\n      * inversion H.\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\nLemma and_example2' :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example2'' :\n  forall n m : nat, n = 0 -> m = 0 -> n + m = 0.\nProof.\n  intros n m Hn Hm.\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros n m H.\n  assert (H' : n = 0 /\\ m = 0).\n  { apply and_exercise. apply H. }\n  destruct H' as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP.  Qed.\n\n(*Exercise 3*)\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros. destruct H.\n  - assumption.\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\n(*Exercise 4*)\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      * assumption.\n      * assumption.\n    + assumption.\nQed.\n\n\n\nCheck or.\n\nLemma or_example :\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\n\nLemma or_intro : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  (* WORKED IN CLASS *)\n  intros [|n].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\n(*Exercise 5*)\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros [].\n  - left. reflexivity.\n  - right. destruct m.\n    + reflexivity.\n    + inversion H.\nQed.\n  \n\n(*Exercise 6*)\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros. destruct H.\n  - right. apply H.\n  - left. apply H.\nQed.\n\n\nModule MyNot.\n\nDefinition not (P:Prop) := P -> False.\n\n\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n\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(*Exercise 7*)\nFact not_implies_our_not : forall (P:Prop),\n  ~ P -> (forall (Q:Prop), P -> Q).\nProof.\n  intros . destruct H.\n  apply H0.\nQed. \n\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\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 8*)\nTheorem contrapositive : forall (P Q : Prop),\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros. unfold not. unfold not in H0. intros. apply H0 in H. assumption. assumption.\nQed.\n\n(*Exercise 9*)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros. unfold not. intros. destruct H.\n  - apply H0 in H. assumption.\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    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 = false *)\n    unfold not in H.\n    exfalso.\n    apply H. reflexivity.\n  - (* b = true *) reflexivity.\nQed.\n\n\n(*Exercise 10*)\nTheorem xxx:\n  forall (P Q R: Prop),\n  (P -> Q -> R) -> (P /\\ Q -> R).\n\nProof.\n  intros. destruct H0.\n  - apply H.\n    + apply H0.\n    + apply H1.\nQed.\n\n(*Exercise 11*)\nTheorem yyy:\n  forall (P Q R: Prop),\n  (P /\\ Q -> R) -> (P -> Q -> R).\nProof.\n  intros. apply H. split.\n  - apply H0.\n  - apply H1.\nQed.\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/CA11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.8991213684847577, "lm_q1q2_score": 0.6517463440020362}}
{"text": "Require Import GHC.DeferredFix.\nRequire Import Data.Graph.Inductive.Query.BFS.\nRequire Import Coq.Lists.List.\nRequire Import Data.Graph.Inductive.Internal.Queue.\nRequire Import NicerQueue.\nRequire Import Equations.Equations.\nRequire Import Data.Graph.Inductive.Graph.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Lists.SetoidList.\nRequire Import Omega.\nRequire Import Wellfounded.\n\nRequire Import Path.\nRequire Import Helper.\nRequire Import Coq.FSets.FMapFacts.\n\nRequire Import Coq.FSets.FMapList.\nRequire Import Coq.FSets.FMapInterface.\nRequire Import Coq.Structures.OrderedTypeEx.\n\nModule M := FMapList.Make(N_as_OT).\nModule P := WProperties_fun N_as_OT M.\nModule F := P.F.\n\nRequire Import Coq.Relations.Relation_Operators.\nRequire Import Lex.\n\n(* Inductive relation*)\nSection Ind.\n\n\nContext {a : Type} {b : Type} { gr : Type -> Type -> Type} {Hgraph : Graph.Graph gr} {Hlaw : Graph.LawfulGraph gr}.\n\n(*Well formed lexicographic measure*)\nDefinition natNodes := (@Path.natNodes a b gr Hgraph).\n\nDefinition natNodes_lt (x y : gr a b) := natNodes x < natNodes y.\n\nDefinition natNodes_eq (x y : gr a b) := natNodes x = natNodes y.\nDefinition list_length_lt {a} (x y : list a) := length x < length y.\nDefinition queue_length_lt  {a} (x y : Queue a) := list_length_lt (toList _ x) (toList _ y).\n\nDefinition bf_measure_list (a: Type) := \n  lex _ _ (natNodes_lt) natNodes_eq ((@list_length_lt a)).\n\n\nDefinition bf_measure_queue (a: Type) :=\n  lex _ _ (natNodes_lt) natNodes_eq (@queue_length_lt a).\n\nLemma well_founded_bf_measure_list : forall a,  well_founded (bf_measure_list a).\nProof.\n  intros. eapply WF_lex.\n  - apply f_nat_lt_wf.\n  - apply f_nat_lt_wf.\n  - unfold Transitive. intros. unfold natNodes_eq in *; omega.\n  - intros. unfold natNodes_eq in *. unfold natNodes_lt in *. destruct H. destruct H.\n    omega.\n  - unfold Symmetric. intros. unfold natNodes_eq in *. omega.\nQed. \n\nLemma well_founded_bf_measure_queue : forall a,  well_founded (bf_measure_queue a).\nProof.\n  intros. eapply WF_lex.\n  - apply f_nat_lt_wf.\n  - apply f_nat_lt_wf.\n  - unfold Transitive. intros. unfold natNodes_eq in *; omega.\n  - intros. unfold natNodes_eq in *. unfold natNodes_lt in *. destruct H. destruct H.\n    omega.\n  - unfold Symmetric. intros. unfold natNodes_eq in *. omega.\nQed. \n\n(*A few properties of this relation*)\nLemma measure_trans: forall {a} x y z,\n  bf_measure_list a x y ->\n  bf_measure_list a y z ->\n  bf_measure_list a x z.\nProof.\n  intros. unfold bf_measure_list in *.\n  inversion H; subst.\n  - inversion H0; subst.\n    + apply lex1. unfold natNodes_lt in *. omega.\n    + apply lex1. unfold natNodes_lt in *. unfold natNodes_eq in H4. omega.\n  - inversion H0; subst.\n    + apply lex1. unfold natNodes_lt in *. unfold natNodes_eq in H1. omega.\n    + apply lex2. unfold natNodes_eq in *. omega. unfold list_length_lt in *. omega.\nQed. \n\nLemma measure_antisym: forall {a} x y,\n  bf_measure_list a x y ->\n  ~bf_measure_list a y x.\nProof.\n  intros. intro. unfold bf_measure_list in *. \n  inversion H; inversion H0; subst; unfold natNodes_lt in *; unfold natNodes_eq in *.\n  - inversion H5; subst. inversion H6; subst. omega.\n  - inversion H6; subst. inversion H7; subst. omega.\n  - inversion H6; subst. inversion H7; subst. omega.\n  - inversion H7; subst. inversion H8; subst.\n    unfold list_length_lt in *. omega.\nQed.\n\nLemma measure_antirefl: forall {a} x,\n  ~bf_measure_list a x x.\nProof.\n  intros. intro. inversion H; subst; unfold natNodes_lt in *; unfold list_length_lt in *; try(omega).\nQed.\n\n\n(*We define an equivalent version of BFS that is tail recursive and consists of a series of states\n  that step to each other. This way, we can reason about the specific states of the algorithm. A state\n  consists of the current graph, the current queue, and the current output*)\nDefinition state : Type := (gr a b) * (list (Node * Num.Int)) * (list (Node * Num.Int)) .\n\n\nDefinition get_graph (s: state) :=\n  match s with\n  | (g, _, _) => g\n  end.\n\nDefinition get_queue (s: state) :=\n  match s with\n  | (_, q, _) => q\nend.\n\nDefinition get_dists (s: state) :=\n  match s with\n  | (_, _, d) => d\n  end.\n\n(*How to step from 1 state to another. The inductive definiction makes it easier to use as\n  an assumption in proofs*)\nInductive bfs_step : state -> state -> Prop :=\n  | bfs_find: forall g d v j vs c g',\n      isEmpty g = false ->\n      match_ v g = (Some c, g') ->\n      bfs_step (g, (v, j) :: vs, d) (g', (vs ++ suci c (Num.op_zp__ j (Num.fromInteger 1))),\n        d ++ (v,j) :: nil)\n  | bfs_skip: forall g d v j vs g',\n      isEmpty g = false ->\n      match_ v g = (None, g') ->\n      bfs_step (g, (v, j) :: vs, d) (g', vs, d).\n\nDefinition start (g : gr a b) (v: Graph.Node) : state := (g, ((v, Num.fromInteger 0) :: nil), nil).\n\n(*A valid state is any state that can be reached from the start state.*)\nInductive valid : state -> (gr a b) -> Node -> Prop :=\n  | v_start : forall g v, vIn g v = true -> valid (start g v) g v\n  | v_step : forall s s' v g, valid s' g v -> bfs_step s' s -> valid s g v.\n\n(*From Software Foundations*)\nDefinition relation (X : Type) := X -> X -> Prop.\n\nInductive multi {X : Type} (R : relation X) : relation X :=\n  | multi_refl : forall (x : X), multi R x x\n  | multi_step : forall (x y z : X),\n                    R x y ->\n                    multi R y z ->\n                    multi R x z.\n\nTheorem multi_R : forall (X : Type) (R : relation X) (x y : X),\n    R x y -> (multi R) x y.\nProof.\n  intros X R x y H.\n  apply multi_step with y. apply H. apply multi_refl.\nQed.\n\nTheorem multi_trans :\n  forall (X : Type) (R : relation X) (x y z : X),\n      multi R x y ->\n      multi R y z ->\n      multi R x z.\nProof.\n  intros X R x y z G H.\n  induction G.\n    - (* multi_refl *) assumption.\n    - (* multi_step *)\n      apply multi_step with y. assumption.\n      apply IHG. assumption.\nQed.\n\nDefinition bfs_multi (s1 s2 : state):= multi (bfs_step) s1 s2.\n\nLemma multi_valid: forall s1 s2 g v,\n  valid s1 g v ->\n  bfs_multi s1 s2 ->\n  valid s2 g v.\nProof.\n  intros. induction H0. assumption. apply IHmulti. eapply v_step. apply H. assumption.\nQed.\n\nDefinition done (s: state) := null (get_queue s) || isEmpty (get_graph s).\n\n(*The executable, tail recursive version of this, which we will prove equivalent to the hs-to-coq version*)\nSection Exec.\n\nLemma match_none_size: forall g v g',\n  match_ v g = (None, g') -> natNodes g = natNodes g'.\nProof.\n  intros. pose proof (match_remain_none g). erewrite H0. reflexivity. apply H.\nQed.  \n\nInstance need_this_for_equations : WellFounded (bf_measure_list (Node * Num.Int)).\nProof.\n  unfold WellFounded. apply well_founded_bf_measure_list.\nDefined.\n\nEquations bfs_tail (s: state) : state by wf (get_queue s, get_graph s) (bf_measure_list (Node * Num.Int)) :=\n  bfs_tail (g, nil, x) => (g, nil, x);\n  bfs_tail (g, (v, j) :: vs, d) => if (isEmpty g) then  (g, (v, j) :: vs, d) else\n      match (match_ v g) as y return ((match_ v g = y) -> _) with\n      | (Some c, g') => fun H: (match_ v g) = (Some c, g') => \n        bfs_tail (g', (vs ++ suci c (Num.op_zp__ j (Num.fromInteger 1))), d ++ (v,j) :: nil)\n      | (None, g') => fun H: (match_ v g) = (None, g') => bfs_tail (g', vs, d)\n      end (eq_refl).\nNext Obligation.\nunfold bf_measure_list. apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply H.\nDefined.\nNext Obligation.\nunfold bf_measure_list. apply lex2. unfold natNodes_eq. symmetry. eapply match_none_size. apply H. unfold list_length_lt.\nsimpl. omega.\nDefined.\n\nDefinition expand_bfs_tail := \nfun s : gr a b * list (Node * Num.Int) * list (Node * Num.Int) =>\nlet (p, l) := s in\n(let (g, l0) := p in\n fun l1 : list (Node * Num.Int) =>\n match l0 with\n | nil => fun l2 : list (Node * Num.Int) => (g, nil, l2)\n | p0 :: l2 =>\n     fun l3 : list (Node * Num.Int) =>\n     (let (n, i) := p0 in\n      fun l4 l5 : list (Node * Num.Int) =>\n      if isEmpty g\n      then (g, (n, i) :: l4, l5)\n      else\n       (let (m, g') as y return (match_ n g = y -> gr a b * list (Node * Num.Int) * list (Node * Num.Int)) :=\n          match_ n g in\n        match\n          m as m0 return (match_ n g = (m0, g') -> gr a b * list (Node * Num.Int) * list (Node * Num.Int))\n        with\n        | Some c =>\n            fun _ : match_ n g = (Some c, g') =>\n            bfs_tail (g', l4 ++ suci c (Num.op_zp__ i (Num.fromInteger 1)), l5 ++ (n, i) :: nil)\n        | None => fun _ : match_ n g = (None, g') => bfs_tail (g', l4, l5)\n        end) eq_refl) l2 l3\n end l1) l.\n\nLemma unfold_bfs_tail: forall s,\n  bfs_tail s = expand_bfs_tail s.\nProof.\n  intros. unfold expand_bfs_tail. apply bfs_tail_elim; intros; reflexivity.\nQed.\n\n(*This is equivalent to repeatedly stepping with the bfs_step inductive relation. We prove this by proving that\n  bfs_tail represents a multistep to a done state. So when we start with the start state, we get a valid\n  done state. We will later prove that all valid done states are equivalent, so we can prove claims about bfs_tail\n  by considering valid done states in general*)\n\nLemma bfs_tail_multi: forall s,\n  bfs_multi s (bfs_tail s).\nProof.\n  intros. destruct s as[r d].\n  remember (snd r, fst r) as r'. generalize dependent r. revert d. \n  induction (r') using (well_founded_induction (well_founded_bf_measure_list (Node * Num.Int))).\n  intros. destruct r' as [q g]. inversion Heqr'; subst. clear Heqr'. destruct r as [g q].\n  rewrite unfold_bfs_tail. simpl. destruct q eqn : Q.\n  - apply multi_refl.\n  - destruct p as [v j]. destruct (isEmpty g) eqn : E.\n    + apply multi_refl.\n    + destruct (match_ v g) eqn : M.  destruct m eqn : M'.\n      *  eapply multi_step. apply bfs_find. assumption. apply M. eapply H. unfold bf_measure_list.\n         apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply M. simpl. reflexivity.\n      * eapply multi_step. apply bfs_skip. assumption. apply M. eapply H. unfold bf_measure_list.\n        apply lex2. unfold natNodes_eq. assert (g = g0) by (eapply match_remain_none; apply M).\n        subst. eapply match_none_size. simpl.  apply M. \n        unfold list_length_lt. simpl. assert (length l < S(length l)) by omega. apply H0. simpl. \n        assert (g = g0) by (eapply match_remain_none; apply M). subst. reflexivity.\nQed.\n\nLemma bfs_tail_done: forall s,\n  done (bfs_tail s) = true.\nProof.\n  intros. unfold done. destruct s as [r d].\n  remember (snd r, fst r) as r'. generalize dependent r. revert d. \n  induction (r') using (well_founded_induction (well_founded_bf_measure_list (Node * Num.Int))).\n  intros. destruct r'. inversion Heqr'. subst. clear Heqr'.\n  destruct r as [g q]. rewrite unfold_bfs_tail. simpl. destruct q eqn : Q.\n  - simpl. reflexivity.\n  - destruct p. simpl. destruct (isEmpty g) eqn : G. simpl. assumption.\n    destruct (match_ n g) eqn : M. destruct m; simpl.\n    eapply H. unfold bf_measure_list. apply lex1. unfold natNodes_lt. eapply match_decr_size;\n    symmetry; apply M. simpl. reflexivity. assert (g = g0) by (eapply match_remain_none; apply M). subst.\n    eapply H. unfold bf_measure_list. apply lex2.\n    unfold natNodes_eq. eapply match_none_size. simpl. apply M.  unfold list_length_lt. simpl.\n    assert (length l < S(length l)) by omega. apply H0. simpl. reflexivity.\nQed. \n\nEnd Exec.\n\n(*Results about multistepping and measure. In particular, we will prove that any two done states\n  are equivalent, that any valid state multisteps to a done state, and several other needed results*)\nSection Multi.\n\n(*if we step from s to s', s' < s*)\nLemma measure_step: forall s s',\n  bfs_step s s' ->\n  bf_measure_list (Node * Num.Int) (get_queue s', get_graph s') (get_queue s, get_graph s) .\nProof.\n  intros. unfold bf_measure_list. unfold transp. inversion H; subst; simpl in *.\n  - apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply H1.\n  - apply lex2. unfold natNodes_eq. symmetry. eapply match_none_size. apply H1.  unfold list_length_lt.\nsimpl. omega.\nQed.\n\n(*The same for multistep*)\nLemma measure_multi: forall s s',\n  bfs_multi s s' ->\n  s = s' \\/ bf_measure_list (Node * Num.Int) (get_queue s', get_graph s') (get_queue s, get_graph s) .\nProof.\n  intros. induction H.\n  - left. reflexivity.\n  - destruct IHmulti. subst. right. apply measure_step. assumption.\n    right. eapply measure_trans. apply H1. apply measure_step. assumption.\nQed.\n\n(*If s multisteps to s', s and s' are equal exactly when s < s' and s' < s are both false*)\nLemma multistep_eq_measure: forall s s',\n  bfs_multi s s' ->\n  (s = s') <-> (~bf_measure_list _ (get_queue s', get_graph s') (get_queue s, get_graph s) /\\\n  ~bf_measure_list (Node * Num.Int) (get_queue s, get_graph s) (get_queue s', get_graph s')). \nProof.\n  intros. split. intros. subst. split; intro;\n  pose proof (measure_antirefl (get_queue s', get_graph s')); contradiction. intros.\n  destruct H0. apply measure_multi in H. destruct H. subst. reflexivity. contradiction.\nQed. \n\nLemma bfs_step_deterministic : forall s1 s2 s,\n  bfs_step s s1 -> bfs_step s s2 -> s1 = s2.\nProof.\n  intros. inversion H; subst; simpl in *.\n  - inversion H0; subst; simpl in *.\n    + rewrite H10 in H2. inversion H2; subst. reflexivity.\n    + rewrite H10 in H2. inversion H2.\n  - inversion H0; subst; simpl in *.\n    + rewrite H10 in H2. inversion H2.\n    + rewrite H10 in H2. inversion H2; subst. reflexivity.\nQed.\n\nLemma multi_from_start: forall s s' s'',\n  bfs_multi s s'' ->\n  bfs_multi s s' ->\n  (bfs_multi s' s'' \\/ bfs_multi s'' s').\nProof.\n  intros. generalize dependent s'. induction H; intros.\n  - right. apply H0.\n  - inversion H1; subst.\n    + left. eapply multi_step. apply H. apply H0.\n    + assert (y=y0). eapply bfs_step_deterministic.\n      apply H. apply H2. subst. apply IHmulti. apply H3.\nQed.\n\nLemma valid_begins_with_start: forall s g v,\n  valid s g v ->\n  bfs_multi (start g v) s.\nProof.\n  intros. induction H.\n  - constructor.\n  - eapply multi_trans. apply IHvalid.  eapply multi_step. apply H0. apply multi_refl.\nQed.\n\n(*For any two valid states, one multisteps to the other*)\nLemma valid_multi: forall s s' g v,\n  valid s g v ->\n  valid s' g v ->\n  bfs_multi s s' \\/ bfs_multi s' s.\nProof.\n  intros. eapply multi_from_start. apply valid_begins_with_start. apply H0.\n  apply valid_begins_with_start. assumption.\nQed.\n\n(*A valid state is not done iff it can step*)\nLemma not_done_step: forall s g v,\n  valid s g v ->\n  (done s = false <-> exists s', bfs_step s s').\nProof.\n  intros. split; intros.\n  - destruct s as [p d]. destruct p as [g' q].\n    unfold done in H0. simpl in H0.\n    rewrite orb_false_iff in H0. destruct H0.\n    destruct q. simpl in H0. inversion H0.\n    destruct p as [v' d'].\n    destruct (match_ v' g') eqn : M. destruct m.\n    + exists ((g0, q ++ suci c (Num.op_zp__ d' (Num.fromInteger 1)), d ++ (v', d') :: nil)).\n      constructor; assumption.\n    + exists (g0, q, d). constructor; assumption.\n  - destruct H0. unfold done in *; inversion H0; subst; simpl in *; assumption.\nQed.\n\n(*If a state is done, it cannot step*)\nLemma done_cannot_step: forall s g v,\n  valid s g v ->\n  done s = true ->\n  ~(exists s', bfs_step s s').\nProof.\n  intros. intro. pose proof (not_done_step _ _ _ H).\n  destruct H2. apply contrapositive in H3. contradiction. \n  rewrite H0. intro. inversion H4.\nQed.\n\n(*A state is done if for every valid state s', s' < s is false*)\nLemma measure_done: forall s g v,\n  valid s g v ->\n  done s = true <-> \n  (forall s', valid s' g v -> ~bf_measure_list _(get_queue s', get_graph s') (get_queue s, get_graph s)).\nProof.\n  intros. split; intros.\n  - intro. pose proof (valid_multi _ _ _ _ H H1). destruct H3.\n    + inversion H3. subst. pose proof (measure_antirefl (get_queue s', get_graph s')).\n      contradiction. subst. pose proof (done_cannot_step _ _ _ H H0).\n      apply H6. exists y. assumption.\n    + apply measure_multi in H3. destruct H3. subst.\n      pose proof (measure_antirefl (get_queue s, get_graph s)).\n      contradiction. pose proof (measure_antisym _ _ H2). contradiction.\n  - destruct (done s) eqn : D.\n    + reflexivity.\n    + pose proof (not_done_step _ _ _ H). apply H1 in D.\n      destruct D. assert (valid x g v). eapply v_step. apply H. apply H2.\n      apply H0 in H3. apply measure_step in H2. contradiction.\nQed.  \n\n(*two valid states are equal if neither is less than the other*)\nLemma measure_unique: forall s g v s',\n  valid s g v ->\n  valid s' g v ->\n  ~bf_measure_list _(get_queue s', get_graph s') (get_queue s, get_graph s) ->\n  ~bf_measure_list _(get_queue s, get_graph s) (get_queue s', get_graph s') ->\n  s = s'.\nProof.\n  intros. pose proof (valid_multi _ _ _ _ H H0). destruct H3.\n  - apply measure_multi in H3. destruct H3. assumption. contradiction.\n  - apply measure_multi in H3. destruct H3. subst. reflexivity. contradiction.\nQed. \n\n(*An important lemma: any two done states that are valid are unique. This allows us to use a tail\n  recursive function and still prove claims about generic done states*)\nLemma done_unique: forall s g v s',\n  valid s g v ->\n  valid s' g v ->\n  done s = true ->\n  done s' = true ->\n  s = s'.\nProof.\n  intros. assert (forall s', valid s' g v -> ~bf_measure_list _(get_queue s', get_graph s') (get_queue s, get_graph s)).\n  eapply measure_done. assumption. assumption.\n  assert (forall s'', valid s'' g v -> ~bf_measure_list _(get_queue s'', get_graph s'') (get_queue s', get_graph s')).\n  eapply measure_done. assumption. assumption.\n  eapply measure_unique. apply H. apply H0. apply H3. apply H0.\n  apply H4. apply H.\nQed.\n\n(*This enables us to talk about any prior valid state, with the assurance that we will multistep to the\n  current, done state*)\nLemma multi_done: forall s s' g v,\n  valid s g v ->\n  valid s' g v ->\n  done s = false ->\n  done s' = true ->\n  bfs_multi s s'.\nProof.\n  intros. assert (exists s'', bfs_multi s s'' /\\ done s'' = true).\n  exists (bfs_tail s). split. apply bfs_tail_multi. apply bfs_tail_done.\n  destruct H3 as [s'']. destruct H3. assert (valid s'' g v). eapply multi_valid.\n  apply H. apply H3. assert (s' = s''). eapply done_unique; try(assumption).\n  apply H0. apply H5. subst. assumption.\nQed.\n\n(*A lemma that says that 2 states that step to each other are the closest valid states according to the well founded\n  relation*)\nLemma bfs_step_measure_exact: forall s s' g v,\n  valid s g v ->\n  bfs_step s s' ->\n  (forall x, valid x g v -> ~ (bf_measure_list _ (get_queue x, get_graph x) (get_queue s, get_graph s) /\\\n  bf_measure_list _ (get_queue s', get_graph s') (get_queue x, get_graph x))).\nProof.\n  intros. intro. destruct H2.\n  assert (valid s' g v). eapply v_step. apply H. assumption.\n  pose proof (valid_multi _ _ _ _ H H1). destruct H5.\n  inversion H5. subst. pose proof (measure_antirefl (get_queue x, get_graph x)). contradiction.\n  subst. assert (y = s'). eapply bfs_step_deterministic. apply H6. assumption. subst.\n  eapply measure_multi in H7. destruct H7. subst. \n  pose proof (measure_antirefl (get_queue x, get_graph x)). contradiction.\n  pose proof (measure_antisym (get_queue x, get_graph x) (get_queue s', get_graph s')).\n  apply H8 in H7. contradiction.\n  apply measure_multi in H5. destruct H5. subst.\n  pose proof (measure_antirefl (get_queue s, get_graph s)). contradiction.\n  pose proof (measure_antisym (get_queue x, get_graph x) (get_queue s, get_graph s)).\n  apply H6 in H2. contradiction.\nQed.\n\n(*Why we needed that lemma: if s -> x and s' -> x, then s = s'*)\nLemma valid_determ: forall s g v s' x,\n  valid s g v ->\n  valid s' g v ->\n  bfs_step s x ->\n  bfs_step s' x ->\n  s = s'.\nProof.\n  intros. pose proof (valid_multi _ _ _ _ H H0).\n  destruct H3.\n  - apply multistep_eq_measure. apply H3.\n    apply measure_multi in H3. destruct H3. subst.\n    split; intro; pose proof (measure_antirefl (get_queue s', get_graph s')); contradiction.\n    assert (S1 := H1). assert (S2 := H2).\n    apply measure_step in H1. apply measure_step in H2. split.\n    exfalso. pose proof (bfs_step_measure_exact _ _ _ _ H S1).\n    specialize (H4 s' H0). apply H4. split; assumption.\n    intro.\n    pose proof (measure_antisym (get_queue s, get_graph s) (get_queue s', get_graph s')).\n    apply H5 in H4. contradiction.\n  - symmetry. apply multistep_eq_measure. apply H3.\n    apply measure_multi in H3. destruct H3. subst.\n    split; intro; pose proof (measure_antirefl (get_queue s, get_graph s)); contradiction.\n    assert (S1 := H1). assert (S2 := H2).\n    apply measure_step in H1. apply measure_step in H2. split.\n    exfalso. pose proof (bfs_step_measure_exact _ _ _ _ H0 S2).\n    specialize (H4 s H). apply H4. split; assumption.\n    intro.\n    pose proof (measure_antisym (get_queue s, get_graph s) (get_queue s', get_graph s')).\n    apply H5 in H3. contradiction.\nQed.\n\n(*Every state that is not the start state has a previous state*)\nLemma prior_state: forall s g v,\n  valid s g v ->\n  s <> (start g v) ->\n  (exists s', valid s' g v /\\ bfs_step s' s).\nProof.\n  intros. inversion H; subst.\n  - contradiction.\n  - exists s'. split; assumption.\nQed.\n\n(*The start state is not done*)\nLemma done_not_start: forall g v,\n  vIn g v = true ->\n  done (start g v) = false.\nProof.\n  intros. unfold start. unfold done. simpl. destruct (isEmpty g) eqn : E.\n  rewrite isEmpty_def in E. rewrite E in H. inversion H. apply v. reflexivity.\nQed.  \n\n\nEnd Multi.\n\n(*This section contains various results about some Haskell functions used, inlcuding List.zip,\n  repeat (used in place of List.repeat), and suci*)\nSection HaskellFunctions.\n\n(*Replicate is trivially sorted*)\nLemma replicate_sorted: forall c n,\n  Sorted Z.le (repeat c (Z.to_nat n)). \nProof.\n  intros. \n  induction (Z.to_nat n); simpl; try(constructor).\n  - assumption.\n  - apply In_InfA. intros. apply repeat_spec in H. subst. omega. \nQed. \n\n(*List.filter equivalence with Coq*)\nLemma filter_equiv: forall {a} (l: list a) p,\n  List.filter p l = filter p l.\nProof.\n  intros. induction l; simpl. reflexivity. rewrite IHl. reflexivity.\nQed.\n\n(*Tuple.snd quivalence with Coq*)\nLemma snd_equiv: @Tuple.snd = @snd.\nProof.\n  unfold Tuple.snd. unfold snd. reflexivity.\nQed.\n\n(*Prove that List.length is equivalent (up to Z -> nat conversion) with Coq list length *)\nLemma len_acc_def: forall {a} (l : list a ) n,\n  List.lenAcc l n = (n + Z.of_nat (length l))%Z.\nProof.\n  intros. revert n. induction l; intros; simpl.\n  - omega.\n  - rewrite IHl. rewrite Zpos_P_of_succ_nat. omega.\nQed. \n\nLemma length_equiv: forall {a} (l: list a),\n  length l = Z.to_nat (List.length l).\nProof.\n  intros. induction l; simpl.\n  - reflexivity.\n  - unfold List.length. simpl. unfold List.length in IHl. rewrite len_acc_def. \n    rewrite len_acc_def in IHl. simpl in IHl.\n    rewrite Z2Nat.inj_add. simpl. omega. omega. omega.\nQed.\n\n(*List.zip results*)\nLemma zip_in: forall {a} {b} (l1 : list a) (l2: list b),\n  (forall x y, In (x,y) (List.zip l1 l2) -> In x l1 /\\ In y l2).\nProof.\n  intros. generalize dependent l2. induction l1; intros.\n  - simpl in H. destruct H.\n  - simpl in H. destruct l2. destruct H.\n    simpl in H.  destruct H. inversion H; subst.\n    split; simpl; left; reflexivity. simpl. apply IHl1 in H. destruct H.\n    split; right; assumption. \nQed. \n\nLemma map_snd_zip: forall {a b} (l1: list a) (l2: list b),\n  length l1 = length l2 ->\n  map snd (List.zip l1 l2) = l2.\nProof.\n  intros. generalize dependent l2. induction l1; intros; simpl.\n  - simpl in H. destruct l2; try(reflexivity). simpl in H. omega.\n  - simpl in H. destruct l2. simpl in H. omega. simpl in H. inversion H.\n    simpl. rewrite IHl1. reflexivity. assumption.\nQed.\n\nLemma map_fst_zip: forall {a b} (l1: list a) (l2: list b),\n  length l1 = length l2 ->\n  map fst (List.zip l1 l2) = l1.\nProof.\n  intros. generalize dependent l2. induction l1; intros. simpl. reflexivity.\n  simpl. destruct l2. simpl in H. omega. simpl in *. inversion H. apply IHl1 in H1. rewrite H1. reflexivity.\nQed.\n\n(*Need specialized lemma for zip with replicate*)\nLemma zip_replicate: forall {a} {b} (l : list a) (m : b) x (n: b) ,\n  In (x,n) (List.zip l (repeat m (Z.to_nat (List.length l)))) <-> In x l /\\ n = m.\nProof.\n  intros. rewrite <- length_equiv. induction l; simpl; split; intros.\n  - destruct H.\n  - destruct_all. destruct H.\n  - destruct H. inversion H; subst. split; try(left); reflexivity.\n    apply IHl in H. destruct H. subst. split. right. assumption. reflexivity.\n  - destruct H. subst. destruct H. inversion H. left. reflexivity.\n    right. apply IHl. split; try(assumption); reflexivity.\nQed.\n\n(*Definition about context4l' (a custom function in Data.Graph*)\nLemma context4l'_def: forall (g: gr a b) v i x l o g' y,\n  match_ v g = (Some (i, x, l, o), g') ->\n  In y (map snd (context4l' (i, x, l, o))) <-> eIn g v y = true.\nProof.\n  intros. unfold context4l'. split; intros.\n  - rewrite in_map_iff in H0. destruct H0. destruct x0. simpl in *. destruct H0. subst.\n    apply in_app_or in H1. destruct H1. apply match_context in H.\n    destruct_all. subst. apply H2. rewrite in_map_iff. exists (b0, y). split; auto.\n    unfold Base.op_z2218U__ in H0. unfold Base.op_zeze__ in H0. unfold Base.Eq_Char___ in H0.\n    unfold Base.op_zeze____  in H0. rewrite filter_equiv in H0. apply filter_In in H0.\n    destruct H0. apply match_context in H. destruct_all. subst. \n    simpl in H1. rewrite N.eqb_eq in H1. subst. apply H2. rewrite in_map_iff. exists (b0, x).\n    split. reflexivity. assumption.\n  - apply match_context in H. destruct_all. subst.\n    apply H2 in H0. rewrite in_map_iff in H0. destruct H0. rewrite in_map_iff. exists x0.\n    split. apply H. destruct H. solve_in.\nQed.\n\n(*Characterizing suci, which is the function uesd by BFS*)\nLemma suci_def: forall x y n (c: Context a b) v g g',\n  match_ v g = (Some c, g') ->\n  In (x,y) (suci c n) <-> y = n /\\ eIn g v x = true. \nProof. \n  intros. split. intros. split. unfold suci in H0. apply zip_in in H0. destruct H0. eapply repeat_spec.\n  apply H1. \n  unfold suci in H0. apply zip_in in H0. destruct H0. unfold suc' in H0.\n  unfold Base.op_z2218U__ in H0. unfold Base.map in H0. rewrite snd_equiv in H0. \n  destruct c. destruct p. destruct p.\n  eapply context4l'_def. apply H. apply H0.\n  intros. unfold suci. destruct H0. subst.\n  epose proof (zip_replicate (suc' c) n x n). apply H0. split.\n  unfold suc'. unfold Base.op_z2218U__. rewrite snd_equiv. unfold Base.map.\n  destruct c. destruct p. destruct p. rewrite context4l'_def. apply H1. apply H. reflexivity.\nQed.\n\nEnd HaskellFunctions.\n\n(*We only need to prove correctness for any valid done state, as explained above.*)\nSection Correctness.\n\nDefinition distance := (@Path.distance a b gr Hgraph).\n\n(*We use a None distance to represent infinity (as in CLRS).*)\nDefinition lt_distance (o1: option nat) (o2: option nat) :=\n  match o1, o2 with\n  | _, None => true\n  | None, _ => false\n  | Some x, Some y => leb x y\n  end.\n\nDefinition plus_distance (o1: option nat) (n: nat) :=\n  match o1 with\n  | None => None\n  | Some x => Some (x + n)\n  end.\n\n(*Lemma 22.1 of CLRS: if (u,v) in E, then v.d <= u.d + 1 (distance from s)*)\nLemma distance_triangle: forall g s u v,\n  eIn g u v = true ->\n  vIn g s = true ->\n  lt_distance (distance g s v) (plus_distance (distance g s u) 1) = true.\nProof.\n  intros. destruct (path_dec g s u).\n  - destruct e as [l]. apply shortest_path_exists in H1. clear l. destruct H1 as [l]. \n    assert (path' g s v (v ::  l)). { eapply p_multi. apply H1. assumption. }\n    destruct (distance g s v) eqn : D.\n    + destruct (distance g s u) eqn : D'.\n      * simpl. rewrite Nat.leb_le.\n        assert (length l = n0). eapply shortest_path_distance. apply D'. assumption. subst.\n        apply distance_some in D. destruct_all. subst.\n        unfold shortest_path in H3. destruct_all.\n        assert (forall n m, n <= m \\/ m < n) by (intros; omega).\n        specialize (H5 (length x) (length l + 1)). destruct H5. assumption.\n        assert (length l + 1 = length (v :: l)). simpl. omega.\n        rewrite H6 in H5. apply H4 in H5. contradiction.\n      * unfold distance in D'. rewrite distance_none in D'. unfold shortest_path in H1. destruct_all.\n        exfalso. apply (D' l). assumption.\n    + unfold distance in D. rewrite distance_none in D. unfold shortest_path in H1. destruct_all.\n      exfalso. apply (D (v :: l)). assumption.\n  - destruct (distance g s u) eqn : D.\n    + apply distance_some in D. destruct_all. unfold shortest_path in H1. destruct_all. exfalso.\n      apply n. exists x. assumption.\n    + simpl. destruct (distance g s v); reflexivity.\nQed.\n\n(*Any vertex or edge in the graph at any point during BFS was in the original graph*)\nLemma graph_subset: forall s v g,\n  valid s g v ->\n  (forall v, vIn (get_graph s) v = true -> vIn g v = true) /\\\n  (forall u v, eIn (get_graph s) u v = true -> eIn g u v = true).\nProof.\n  intros. induction H; simpl.\n  - split; intros; assumption.\n  - inversion H0; subst; simpl in *. assert (M:=H2). apply match_remain_some in H2.\n    destruct H2. split. intros. rewrite H2 in H4. apply IHvalid. apply H4.\n    intros. rewrite H3 in H4. apply IHvalid. apply H4. apply match_remain_none in H2.\n    subst. apply IHvalid.\nQed.\n\n(*A vertex that is in the original graph is in the graph in a given state iff\n  it is not already finished*)\nLemma graph_iff_not_output: forall s g v v',\n  valid s g v ->\n  vIn g v' = true ->\n  In v' (map fst (get_dists s)) <-> (vIn (get_graph s) v' = false).\nProof.\n  intros. induction H; split; intros; simpl in *.\n  - destruct H1.\n  - rewrite H1 in H0. inversion H0.\n  - inversion H1; subst; simpl in *.\n    + rewrite map_app in H2. apply in_app_or in H2.\n      destruct H2. assert (vIn g0 v' = false). apply IHvalid.\n      assumption. assumption. apply match_remain_some in H4.\n      destruct H4. specialize (H4 v'). destruct H4. apply contrapositive in H4.\n      destruct (vIn g' v'). contradiction. reflexivity. intro. \n      destruct H8. rewrite H8 in H5. inversion H5.\n      simpl in H2. destruct H2. subst. apply match_remain_some in H4.\n      destruct H4. specialize (H2 v'). destruct H2. apply contrapositive in H2.\n      destruct (vIn g' v'). contradiction. reflexivity. intro. destruct H6. contradiction.\n      destruct H2.\n    + apply match_remain_none in H4. subst. apply IHvalid. assumption. assumption.\n  - inversion H1; subst; simpl in *.\n    + destruct (N.eq_dec v' v0). subst.\n      rewrite map_app. apply in_or_app. right. simpl. left. reflexivity.\n      apply match_remain_some in H4. destruct H4. specialize (H4 v').\n      destruct H4. apply contrapositive in H6. destruct (vIn g0 v') eqn : V.\n      exfalso. apply H6. split. reflexivity. assumption. rewrite map_app.\n      apply in_or_app. left. rewrite IHvalid. reflexivity. assumption. \n      destruct (vIn g' v'). inversion H2. auto.\n    + apply IHvalid. assumption. apply match_remain_none in H4. subst. assumption.\nQed.\n\n(*Every vertex in the queue is in the graph*)\nLemma queue_in_graph: forall s v g v',\n  valid s g v ->\n  In v' (map fst (get_queue s)) -> \n  vIn g v' = true.\nProof.\n  intros. induction H.\n  - unfold start in *. simpl in *. destruct H0. subst. assumption. destruct H0.\n  - inversion H1; subst; simpl in *.\n    + rewrite map_app in H0. apply in_app_or in H0. destruct H0.\n      apply IHvalid. right. assumption. rewrite in_map_iff in H0.\n      destruct H0. destruct x. destruct H0; subst. apply (suci_def n i (j + 1)%Z) in H3.\n      rewrite H3 in H4. destruct H4. subst. simpl. \n      apply edges_valid in H4. destruct H4.\n      pose proof (graph_subset _ _ _ H). destruct H5. apply H5. simpl. assumption.\n    + apply IHvalid. right. assumption.\nQed.\n\n(*Each vertex appears at most once in the output*)\nLemma no_dups_output: forall s g v,\n  valid s g v ->\n  NoDup (map fst (get_dists s)).\nProof.\n  intros. induction H; simpl.\n  - constructor.\n  - inversion H0; subst; simpl in *.\n    rewrite map_app. simpl. assert (map fst d ++ v0 :: nil = rev (v0 :: rev ((map fst d)))).\n    simpl. rewrite rev_involutive. reflexivity.\n    rewrite H3. rewrite NoDup_NoDupA. apply NoDupA_rev. apply eq_equivalence.\n    constructor. intro. rewrite <- In_InA_equiv in H4. rewrite <- in_rev in H4.\n    assert (vIn g v0 = true). eapply queue_in_graph. apply H. simpl. left. reflexivity. \n    pose proof (graph_iff_not_output _ _ _ _ H H5) as D; simpl in *.\n    apply D in H4. \n    assert (vIn g0 v0 = true). apply match_in. exists c. exists g'. assumption.\n    rewrite H6 in H4. inversion H4. apply NoDupA_rev. apply eq_equivalence. rewrite <- NoDup_NoDupA.\n    assumption. assumption.\nQed.\n\n(*Every distance on the queue is >= 0*)\nLemma dist_geq_0: forall s g v v' d,\n  valid s g v ->\n  In (v', d) (get_queue s) ->\n  (d >= 0)%Z.\nProof.\n  intros. generalize dependent v'. generalize dependent d. induction H; intros.\n  - unfold start in H0; simpl in *. destruct H0. inversion H0; subst. omega. destruct H0.\n  - inversion H0; subst; simpl in *.\n    +  apply in_app_or in H1. destruct H1. eapply IHvalid. right. apply H1.\n      eapply (suci_def _ _ _ _ _ _ _ H3) in H1. destruct H1. \n       assert ((j >=0)%Z). eapply IHvalid. left. reflexivity. omega.\n     + eapply IHvalid. right. apply H1.\nQed. \n\n(*Likewise for the output*)\nLemma dists_geq_0: forall s g v v' d,\n  valid s g v ->\n  In (v', d) (get_dists s) ->\n  (0 <= d)%Z.\nProof.\n  intros. induction H.\n  - unfold start in *. simpl in *. destruct H0.\n  - inversion H1; subst; simpl in *.\n    + apply in_app_or in H0. destruct H0. apply IHvalid; assumption. simpl in H0. destruct H0.\n      inversion H0; subst.\n      pose proof (dist_geq_0 (g0, (v', d) :: vs, d0) g v v' d H). simpl in H4.\n      assert (d >= 0)%Z. apply H4. left. reflexivity. omega. destruct H0.\n    + apply IHvalid; assumption.\nQed.\n\nLemma valid_in: forall s g v,\n  valid s g v ->\n  vIn g v = true.\nProof.\n  intros. induction H. assumption. assumption.\nQed.\n\n(** ** Lemma 22.2 of CLRS **)\n\n(*TODO (or something): The BFS implementation does not count the first vertex, so we have that\n  [distance u v] (length of shortest path) = 1 + (computed distance)*)\n\n(*First, the necessary statement for queues: if (v', d) is in the queue, then d(v') <= d + 1*)\nLemma queue_upper_bound: forall s g v v' d,\n  valid s g v ->\n  In (v', d) (get_queue s) ->\n  lt_distance (distance g v v')  (Some ((Z.to_nat d) + 1)) = true.\nProof.\n  intros. generalize dependent v'. generalize dependent d. induction H; intros.\n  - unfold start in *; simpl in *. destruct H0. inversion H0; subst.\n    simpl. assert (distance g v' v' = Some 1). apply distance_refl in H.\n    apply distance_of_shortest_path in H. simpl in H. assumption.\n    rewrite H1. reflexivity. destruct H0.\n  - inversion H0; subst; simpl in *.\n    + apply in_app_or in H1. destruct H1.\n      * apply IHvalid. right. assumption.\n      * apply (suci_def _ _ _ _ _ _ _ H3) in H1. destruct H1. subst.\n        pose proof (valid_in (g0, (v0, j) :: vs, d0) g v H). simpl in H1.\n        pose proof (graph_subset (g0, (v0, j) :: vs, d0) v g H). simpl in H5.\n        destruct H5. apply H6 in H4. \n        pose proof (distance_triangle _ _ _ _ H4 H1).\n        assert (lt_distance (distance g v v0) (Some (Z.to_nat j + 1)) = true). apply IHvalid. left.\n        reflexivity. destruct (distance g v v0) eqn : ?; simpl in *.\n        destruct (distance g v v') eqn : ?. simpl in *. rewrite Nat.leb_le in *.\n        assert ((j >= 0)%Z). eapply dist_geq_0. apply H. simpl. left. reflexivity.\n        assert (Z.to_nat j + 1 = Z.to_nat (j + 1)). assert (Z.to_nat j + Z.to_nat (1%Z) = Z.to_nat (j + 1)).\n        rewrite <- Z2Nat.inj_add. reflexivity. omega. omega. \n        assert (Z.to_nat 1 = 1). unfold Z.to_nat. unfold Pos.to_nat. simpl. reflexivity.\n        rewrite H11 in H10. omega. omega. simpl. simpl in H7. inversion H7.\n        inversion H8.\n    + apply IHvalid. right. assumption.\nQed. \n\n(*Lemma 22.2 of CLRS*)\nLemma dist_upper_bound: forall s g v v' d,\n  valid s g v ->\n  In (v', d) (get_dists s) ->\n  lt_distance (distance g v v') (Some (Z.to_nat d + 1))  = true.\nProof.\n  intros. induction H; simpl.\n  - unfold start in H0; simpl in H0. destruct H0.\n  - inversion H1; subst; simpl in *.\n    + apply in_app_or in H0. destruct H0. specialize (IHvalid H0).\n      apply IHvalid. simpl in H0. destruct H0. inversion H0; subst.\n      pose proof (queue_upper_bound _ _ _ v' d H). simpl in H4.\n      unfold lt_distance in H4. apply H4. left. reflexivity. destruct H0.\n    + apply IHvalid. assumption.\nQed.\n\n(** Lemma 22.3 of CLRS **)\n(*I believe we only ever use the first part (sortedness of the queue), but the second is necessary for the IH*)\nLemma queue_structure: forall s g v v' d tl,\n  valid s g v ->\n  get_queue s = (v', d) :: tl ->\n  (Sorted Z.le (map snd (get_queue s))) /\\ (forall v' d', In (v', d') (get_queue s) -> (d' <= d + 1)%Z).\nProof.\n  intros. generalize dependent v'. revert d. revert tl. induction H; intros; simpl.\n  - unfold start; simpl in *. inversion H0; subst. split. constructor. constructor. constructor.\n    intros. destruct H1. inversion H1. subst. omega. destruct H1.\n  - inversion H0; subst; simpl in *.\n    + split. rewrite map_app. eapply SortA_app. apply eq_equivalence.\n      assert (Sorted Z.le (j :: map snd vs)). { specialize (IHvalid vs j v0).\n      apply IHvalid. reflexivity. } inversion H4; subst. assumption.\n      unfold suci. rewrite map_snd_zip.  apply replicate_sorted.\n      rewrite repeat_length. apply length_equiv.\n      intros.\n      unfold suci in H5. rewrite map_snd_zip in H5. \n      rewrite <- In_InA_equiv in H5. apply repeat_spec in H5.  subst.\n      rewrite <- In_InA_equiv in H4. rewrite in_map_iff in H4.\n      destruct H4. destruct H4. destruct x0; subst.\n      simpl. specialize (IHvalid vs j v0). destruct IHvalid. reflexivity.\n      specialize (H6 n i). apply H6. right. assumption.\n      rewrite repeat_length. apply length_equiv.\n      intros. apply in_app_or in H4.\n      (*d is in vs or suci *)\n      destruct vs. simpl in H1. destruct H4. simpl in H4. destruct H4.\n      unfold suci in H4. apply zip_in in H4. destruct H4.\n      apply repeat_spec in H5. subst.\n      assert (In (v', d) (suci c (j+1)%Z)). rewrite H1. solve_in.\n      unfold suci in H5. apply zip_in in H5. destruct H5.\n      apply repeat_spec in H6. subst. omega.\n      (*other case*)\n      simpl in H1. inversion H1. subst.\n      specialize (IHvalid ((v', d) :: vs) j v0). destruct IHvalid.\n      reflexivity. inversion H5. subst.\n      inversion H10. subst. \n      destruct H4.\n      simpl in H4. destruct H4. inversion H4. subst. omega.\n      assert (d' <= j + 1)%Z. eapply H6. right. right. apply H4.\n      omega.\n      unfold suci in H4. apply zip_in in H4. destruct H4.\n      apply repeat_spec in H7. subst. omega.\n    + specialize (IHvalid vs j v0). destruct IHvalid. reflexivity.\n      split. inversion H4. assumption. intros. rewrite H1 in H6.\n      destruct H6. inversion H6; subst. omega.\n      inversion H4; subst. inversion H10; subst.\n      assert (d' <= j + 1)%Z. eapply H5. right. right. apply H6. omega.\nQed. \n\n(** Reachability **)\n\n(*First, everything on the queue is reachable fron v*)\nLemma queue_reachable: forall s g v v',\n  valid s g v ->\n  In v' (map fst (get_queue s)) ->\n  exists l, path' g v v' l.\nProof.\n  intros. generalize dependent v'. induction H; intros; subst.\n  - unfold start in *; simpl in *. destruct H0. subst. exists (v' :: nil). constructor. assumption. destruct H0.\n  - inversion H0; subst; simpl in *.\n    + rewrite map_app in H1. apply in_app_or in H1. destruct H1.\n      apply IHvalid. right. assumption. rewrite in_map_iff in H1.\n      destruct H1. destruct x. simpl in H1. destruct H1; subst.\n      apply (suci_def _ _ _ _ _  _ _ H3) in H4. destruct H4; subst.\n      specialize (IHvalid v0). destruct IHvalid. left. reflexivity. subst.\n      exists (v' :: x). econstructor. apply H1. pose proof (graph_subset _ _ _ H).\n      destruct H5. apply H6. simpl. assumption.\n    + apply IHvalid. right. assumption.\nQed. \n\n(*Thus, everything in the output is reachable from v*)\nTheorem output_is_reachable: forall s g v v',\n  valid s g v ->\n  In v' (map fst (get_dists s)) ->\n  exists l, path' g v v' l.\nProof.\n  intros. induction H; subst.\n  - unfold start in *; simpl in *. destruct H0.\n  - inversion H1; subst; simpl in *.\n    + rewrite map_app in H0. apply in_app_or in H0. destruct H0.\n      apply IHvalid. assumption. eapply queue_reachable. apply H. simpl.\n      simpl in H0. destruct H0; subst. left. reflexivity. destruct H0.\n    + apply IHvalid. assumption.\nQed. \n\n(*Now the harder side: everything that is reachable is in the output*)\n\n(*Everything in the output at one state is there in all future states*)\nLemma output_preserved_strong: forall s v g v' s' (d : Num.Int),\n  valid s g v ->\n  bfs_multi s s' ->\n  In (v' d) (get_dists s) ->\n  In (v' d) (get_dists s').\nProof.\n  intros. induction H0. assumption. assert (valid y g v). eapply v_step. apply H. assumption.\n  specialize (IHmulti H3). clear H3. inversion H0; subst; simpl in *; apply IHmulti; solve_in.\nQed.\n\nLemma output_preserved: forall s v g v' s',\n  valid s g v ->\n  bfs_multi s s' ->\n  In v' (map fst (get_dists s)) ->\n  In v' (map fst (get_dists s')).\nProof.\n  intros. rewrite in_map_iff in *. destruct H1. exists x. destruct H1.\n  split. assumption. destruct x; simpl. subst. eapply output_preserved_strong.\n  apply H. apply H0. assumption.\nQed.\n\n(*A stronger version of [graph_subset]: if a vertex or edge is in the graph at a later point,\n  then it was in the graph in an earlier state that steps to the current state *)\nLemma graph_subset': forall s v g s',\n  valid s g v ->\n  bfs_multi s s' ->\n  (forall v, vIn (get_graph s') v = true -> vIn (get_graph s) v = true) /\\\n  (forall u v, eIn (get_graph s') u v = true -> eIn (get_graph s) u v = true).\nProof.\n  intros. induction H0; simpl.\n  - split; intros; assumption.\n  - assert (valid y g v). eapply v_step. apply H. assumption.\n    specialize (IHmulti H2). clear H2. inversion H0; subst; simpl in *.\n    assert (M:=H3). apply match_remain_some in H3.\n    destruct H3. split. intros. destruct IHmulti. apply H6 in H5.\n    rewrite H3 in H5. destruct H5. assumption.\n    intros. destruct IHmulti. apply H7 in H5.\n    rewrite H4 in H5. destruct H5. assumption. apply match_remain_none in H3. subst. apply IHmulti.\nQed.\n\n(*Everything in the queue at one point that is not in the queue at a future point must be in the output*)\nLemma queue_added_to_output: forall s v g v' s',\n  valid s g v ->\n  bfs_multi s s' ->\n  In v' (map fst (get_queue s)) ->\n  ~In v' (map fst (get_queue s')) ->\n  In v' (map fst (get_dists s')).\nProof.\n  intros. induction H0.\n  - contradiction.\n  - inversion H0; subst; simpl in *.\n    + destruct H1. subst. eapply output_preserved.\n      eapply v_step. apply H. apply H0. assumption. simpl. rewrite map_app.\n      apply in_or_app. right. simpl. left. reflexivity.\n      apply IHmulti. eapply v_step. apply H. assumption.\n      rewrite map_app. apply in_or_app. left. apply H1. assumption.\n    + destruct H1. subst. rewrite graph_iff_not_output. pose proof (graph_subset' _ _ _ z H).\n      destruct H1. eapply multi_step. apply H0. assumption. simpl in *. \n      specialize (H1 v'). apply contrapositive in H1. destruct (vIn (get_graph z) v').\n      contradiction. reflexivity. \n      destruct (vIn g0 v') eqn : M. rewrite <- match_in in M.\n      destruct M. destruct H7. rewrite H7 in H5. inversion H5. auto. \n      eapply multi_valid. apply H. eapply multi_step. apply H0. assumption.\n      eapply queue_in_graph. apply H. simpl. left. reflexivity. \n      apply IHmulti. eapply v_step. apply H. assumption. assumption. assumption.\nQed.\n     \n(*An important lemma: If a vertex is on the queue at any point, when we multistep to the end, it is in\n  the list of distances*)\nLemma queue_ends_in_output: forall s v g s' v',\n  valid s g v ->\n  bfs_multi s s' ->\n  done s' = true ->\n  In v' (map fst (get_queue s)) ->\n  In v' (map fst (get_dists s')).\nProof.\n  intros. unfold done in H1. rewrite orb_true_iff in H1.\n  destruct H1. destruct (get_queue s') eqn : E. \n  eapply queue_added_to_output. apply H. assumption. assumption. rewrite E. simpl. auto.\n  simpl in H1. inversion H1. rewrite graph_iff_not_output. \n  rewrite isEmpty_def in H1. apply H1. apply v'. \n  eapply multi_valid. apply H. assumption. eapply queue_in_graph. apply H. assumption.\nQed.\n\n(*If a vertex is in the distances at any point, there must be a step when it was added to the distances. The rest\n  of the lemma gives a bunch of information about that state and the queue/distances*)\nLemma output_is_added: forall s v g v' d,\n  valid s g v ->\n  In (v', d) (get_dists s) ->\n  (exists s' c g', valid s' g v /\\ bfs_multi s' s  /\\ (exists l1,\n    get_queue s' = l1 ++ suci c (Num.op_zp__ d (Num.fromInteger 1)) /\\ (forall s'', valid s'' g v ->\n     bfs_step s'' s' ->\n    ~In v' (map fst (get_dists s'')) /\\ (match_ v' (get_graph s'') = (Some c, g')) /\\ \n      get_queue s'' = (v', d) :: l1)) /\\ s' <> start g v /\\ (exists l2, get_dists s' = l2 ++ (v', d) :: nil) ).\nProof.\n  intros. induction H.\n  - unfold start in H0. simpl in *. destruct H0.\n  - inversion H1; subst; simpl in *.\n    + assert (~In v0 (map fst d0)). assert (valid ( (g', vs ++ suci c (j + 1)%Z, d0 ++ (v0, j) :: nil)) g v).\n      eapply v_step. apply H. assumption. apply no_dups_output in H4. simpl in H4. rewrite NoDup_NoDupA in H4.\n      rewrite map_app in H4. simpl in H4. apply NoDupA_swap in H4. inversion H4; subst.\n      intro. rewrite In_InA_equiv in H5. rewrite app_nil_r in H7. contradiction.\n      apply eq_equivalence. destruct (N.eq_dec v' v0). subst. apply in_app_or in H0. destruct H0.\n      rewrite in_map_iff in H4. exfalso. apply H4. exists (v0, d). split; simpl. reflexivity. assumption.\n      simpl in H0. destruct H0. inversion H0; subst. \n      exists (g', vs ++ suci c (d + 1)%Z, d0 ++ (v0, d) :: nil). exists c. exists g'.\n      split. eapply v_step. apply H. assumption.\n      split. apply multi_refl.\n      split. exists vs. split. reflexivity. intros.\n      assert (s'' = (g0, (v0, d) :: vs, d0)). eapply valid_determ. apply H5.\n      assumption. apply H6. assumption. subst. simpl in *. split. assumption. split.  assumption.\n      reflexivity. split.\n      unfold start. simpl. intro. inversion H5; subst. destruct d0; inversion H9.\n      exists d0. simpl. reflexivity.\n      destruct H0. apply in_app_or in H0. destruct H0.\n      apply IHvalid in H0. clear IHvalid. destruct H0 as [s']. destruct H0 as [c'].\n      destruct H0 as [g'']. destruct_all. exists s'. exists c'. exists g''. split.\n      assumption. split. eapply multi_trans. apply H5. apply multi_R. assumption.\n      split. exists x. split. assumption. split. apply H9. assumption. assumption. apply H9.\n      assumption. assumption. split. apply H7. exists x0. assumption.\n      destruct H0. inversion H0; subst.\n      contradiction. destruct H0.\n    + apply IHvalid in H0. clear IHvalid. destruct H0 as [s']. destruct H0 as [c'].\n      destruct H0 as [g'']. destruct_all. exists s'. exists c'. exists g''.\n      repeat(split; try(assumption)). eapply multi_trans. apply H4. apply multi_R. assumption.\n      exists x. split. assumption. apply H8. exists x0. assumption.\nQed.\n\n(*Last lemma before reachability - an edge is in the graph in a given state exactly when both ot its\n  vertices are in the graph*)\nLemma edge_in_state: forall s g v u' v',\n  valid s g v ->  \n  eIn g u' v' = true ->\n  eIn (get_graph s) u' v' = true <-> (vIn (get_graph s) u' = true /\\ vIn (get_graph s) v' = true).\nProof.\n  intros. induction H.\n  - unfold start; simpl. split; intros.\n    + apply edges_valid. assumption.\n    + assumption.\n  - specialize (IHvalid H0). inversion H1; subst; simpl in *.\n    + split; intros.\n      * apply edges_valid. assumption.\n      * destruct H4. apply match_remain_some in H3. destruct H3. apply H3 in H4.\n        apply H3 in H5. rewrite H6. split. rewrite IHvalid. destruct_all. split; assumption.\n        destruct_all; split; assumption.\n    + apply match_remain_none in H3. subst. apply IHvalid.\nQed.\n\n(*First, prove everything reachable is in queue at some point*)\nLemma reachable_in_queue: forall g v v',\n  (exists l, path' g v v' l) ->\n  (exists s, valid s g v /\\ In v' (map fst (get_queue s))).\nProof.\n  intros. destruct H as [l]. generalize dependent v'.\n  induction l using (well_founded_induction\n                     (wf_inverse_image _ nat _ (@length _)\n                        PeanoNat.Nat.lt_wf_0)).\n  intros. inversion H0; subst.\n  - exists (start g v'). split. constructor. assumption. simpl. left. reflexivity. \n  - rename v'0 into n. \n    assert (exists s : state, valid s g v /\\ In n (map fst (get_queue s))). eapply H.\n    assert (length l0 < S(length l0)) by omega. simpl. apply H3. assumption.\n    destruct H3 as [s]. destruct H3. \n    assert (exists sd, done sd = true /\\ bfs_multi s sd). exists (bfs_tail s).\n    split. apply bfs_tail_done. apply bfs_tail_multi. destruct H5 as [sd]. destruct H5.\n    pose proof (queue_ends_in_output _ _ _ _ _ H3 H6 H5 H4).\n    assert (valid sd g v). eapply multi_valid. apply H3. assumption.\n    rewrite in_map_iff in H7. destruct H7. destruct x as [n' d]. simpl in H7. destruct H7; subst.\n    pose proof (output_is_added _ _ _ _ _ H8 H9). destruct H7 as [sp]. destruct H7 as [c].\n    destruct H7 as [g']. destruct H7. destruct H10. destruct H11. destruct H11 as [l1].\n    (*need prior state*)\n    destruct H12. destruct H13. pose proof (prior_state _ _ _ H7 H12). destruct H14 as [sb]. destruct H14.\n    pose proof (edge_in_state _ _ _ _ _ H14 H2). destruct H11 as [A H11].\n    specialize (H11 _ H14 H15). destruct H11. destruct H17. destruct (vIn (get_graph sb) v') eqn : M.\n    + assert (vIn (get_graph sb) n = true). erewrite <- match_in. exists c. exists g'. assumption.\n      rewrite H19 in H16. assert (eIn (get_graph sb) n v' = true). rewrite H16. split; reflexivity.\n      exists sp. split; try(assumption). rewrite A.  rewrite map_app. apply in_or_app. right.\n      pose proof (suci_def v' (Num.op_zp__ d (Num.fromInteger 1)) (Num.op_zp__ d (Num.fromInteger 1))\n      c n (get_graph sb) g' H17). simpl in H21. destruct H21.\n      rewrite H20 in H21. rewrite in_map_iff. exists (v', (d+1)%Z). split. reflexivity.\n      simpl. apply H22. rewrite H20. split; reflexivity.\n    + rewrite <- graph_iff_not_output in M. rewrite in_map_iff in M. destruct M. destruct x0. simpl in H19; destruct H19; subst.\n      pose proof (output_is_added _ _ _ _ _ H14 H20). destruct_all.\n      pose proof (prior_state _ _ _ H19 H23). destruct H26. exists x5. destruct H26. \n      specialize (H25 _ H26 H27). destruct_all. split. assumption. rewrite H29. simpl.\n      left. reflexivity. apply H14. apply edges_valid in H2. destruct H2; assumption.\nQed.\n\n(*Now, everything reachable is in the ouptut*)\nLemma reachable_in_output: forall g v v' s,\n  valid s g v ->\n  done s = true ->\n  (exists l, path' g v v' l) ->\n  In v' (map fst (get_dists s)).\nProof.\n  intros. eapply reachable_in_queue in H1. destruct H1 as [s']. destruct H1.\n  eapply queue_ends_in_output. apply H1. destruct (done s') eqn : D.\n  assert (s = s'). eapply done_unique. apply H. apply H1. assumption. assumption.\n  subst. apply multi_refl. eapply multi_done. apply H1. apply H. assumption. assumption.\n  assumption. assumption.\nQed.\n(*\n(*The start vertex is in the output*)\nLemma v_in_output: forall s g v,\n  valid s g v ->\n  s = start g v \\/ In v (map fst (get_dists s)).\nProof.\n  intros. induction H.\n  - left. reflexivity.\n  - inversion H0; subst; simpl in *.\n    + right. destruct (N.eq_dec v v0). subst.\n      rewrite map_app. simpl. solve_in.\n      unfold start in IHvalid. simpl in IHvalid.\n      rewrite map_app. destruct IHvalid. inversion H3; subst. contradiction.\n      solve_in.\n    + destruct IHvalid. unfold start in H3. inversion H3. subst.\n      assert (vIn g v = false). destruct (vIn g v) eqn : V.\n      rewrite <- match_in in V. destruct_all. rewrite H4 in H2. inversion H2. reflexivity.\n      assert (vIn g v = true). eapply valid_in. apply H. rewrite H5 in H4. inversion H4.\n      right. assumption.\nQed.\n*)\n(** Proof the BFS finds all reachable vertices and only reachable vertices **)\nTheorem output_iff_reachable: forall s g v v',\n  valid s g v ->\n  done s = true ->\n  In v' (map fst (get_dists s)) <-> exists l, path' g v v' l.\nProof.\n  intros. split; intros.\n  - eapply output_is_reachable. apply H. apply H1.\n  - eapply reachable_in_output. apply H. assumption. assumption.\nQed.\n\n(** Correctness of BFS **)\n\n(*Now we will prove that every (v',d) pair in the output has the property that (d'+1) is the distance from v\n  to v'. This requires several lemmas first.*)\n\n(*Find distance from state*)\nDefinition find_dist_list l v :=\n  fold_right (fun x acc => if N.eq_dec (fst x) v then Some (Z.to_nat (snd x)) else acc) None l.\n\nDefinition find_dist s := find_dist_list (get_dists s).\n\nLemma find_dist_in: forall s g v v' n,\n  valid s g v ->\n  find_dist s v' = Some n <-> In (v',(Z.of_nat n)) (get_dists s).\nProof.\n  intros. pose proof no_dups_output _ _ _ H. unfold find_dist.\n  assert (forall l, NoDup (map fst l) ->\n   (forall n, In n (map snd l) -> (0 <= n)%Z) ->\n   fold_right (fun (x : N * Z) (acc : option nat) => if N.eq_dec (fst x) v' then Some (Z.to_nat (snd x)) else acc)\n  None l = Some n <-> In (v', Z.of_nat n) l). { intros; induction l; split; intros; simpl in *.\n  - inversion H3.\n  - destruct H3.\n  - destruct a0. simpl in *. destruct (N.eq_dec n0 v') eqn : ?. subst. inversion H3; subst.\n    left. rewrite Z2Nat.id. reflexivity. apply H2. left. reflexivity. \n    right. apply IHl. inversion H1; assumption. intros. apply H2. right. assumption. assumption.\n  - destruct a0; simpl in *. destruct H3. inversion H3; subst. destruct (N.eq_dec v' v').\n    rewrite Nat2Z.id. reflexivity. contradiction. destruct (N.eq_dec n0 v'). subst.\n    inversion H1. subst. assert (In v' (map fst l)). rewrite in_map_iff. exists (v', Z.of_nat n).\n    split; try(reflexivity); assumption. contradiction. rewrite IHl. assumption. inversion H1; assumption.\n    intros. apply H2. right. assumption. } apply H1.\n    assumption. intros. rewrite in_map_iff in H2. destruct H2.\n    destruct x. destruct H2. simpl in H2; subst. eapply dists_geq_0. apply H.  apply H3.\nQed.\n\nLemma find_dist_not: forall s v,\n  find_dist s v = None <-> (forall y, ~In (v, y) (get_dists s)).\nProof.\n  intros. unfold find_dist. assert (forall l, \n  fold_right (fun (x : N * Z) (acc : option nat) => if N.eq_dec (fst x) v then Some (Z.to_nat (snd x)) else acc) None\n  l = None <-> (forall y : Num.Int, ~ In (v, y) l)). { intros.\n  induction l; split; intros; simpl in *.\n  - auto.\n  - reflexivity.\n  - destruct a0. simpl in *. destruct (N.eq_dec n v). inversion H.\n    intro. rewrite IHl in H. destruct H0. inversion H0; subst. contradiction.\n    apply (H y); assumption.\n  - destruct a0. simpl. destruct (N.eq_dec n v). subst. exfalso. apply (H z).\n    left. reflexivity. rewrite IHl. intros. intro. apply (H y). right. assumption. }\n    apply H.\nQed.\n\n(*The start vertex appears with distance 0 in the output*)\nLemma second_state: forall s g v,\n  vIn g v = true ->\n  bfs_step (start g v) s ->\n  get_dists s = (v, 0%Z) :: nil.\nProof.\n  intros. unfold start in H0. inversion H0; subst; simpl. reflexivity.\n  rewrite <- match_in in H. destruct H. destruct H. rewrite H in H8. inversion H8.\nQed.\n\nLemma dists_nil_iff_start: forall s g v,\n  valid s g v ->\n  get_dists s = nil <-> s = start g v.\nProof.\n  intros. induction H.\n  - split; intros; try(reflexivity).\n  - split; intros.\n    + inversion H0; subst; simpl in *.\n      * destruct d; inversion H1.\n      * subst. unfold start in IHvalid. destruct IHvalid.\n        specialize (H1 eq_refl). inversion H1; subst.\n        pose proof (valid_in _ _ _ H). rewrite <- match_in in H5.\n        destruct_all. rewrite H5 in H3. inversion H3.\n    + subst. inversion H0; subst; simpl in *.\n      * destruct d; inversion H5.\n      * unfold start in IHvalid. destruct IHvalid. \n        specialize (H1 eq_refl). inversion H1; subst.\nQed.\n\nLemma multi_from_second: forall s g v s',\n  valid s g v  ->\n  bfs_step (start g v) s' ->\n  s = start g v \\/ bfs_multi s' s.\nProof.\n  intros. induction H.\n  - left. reflexivity.\n  - specialize (IHvalid H0). destruct IHvalid. subst.\n    assert (s = s'). eapply bfs_step_deterministic. apply H1. apply H0. subst.\n    right. apply multi_refl. right. eapply multi_trans. apply H2. eapply multi_step.\n    apply H1. apply multi_refl.\nQed. \n\nLemma start_0_dist: forall s g v,\n  valid s g v ->\n  (get_dists s) <> nil ->\n  In (v, 0%Z) (get_dists s).\nProof.\n  intros. assert (exists s', bfs_step (start g v) s').\n  assert (vIn g v = true) by (eapply valid_in; apply H).\n  pose proof (done_not_start g v H1). rewrite not_done_step in H2.\n  apply H2. apply v_start. apply H1. destruct H1 as [s'].\n  pose proof (multi_from_second _ _ _ _ H H1). destruct H2. subst.\n  rewrite dists_nil_iff_start in H0. contradiction. apply H. \n  eapply output_preserved_strong. eapply v_step. apply v_start.\n  apply valid_in in H. apply H. apply H1. assumption.\n  erewrite second_state. simpl. left. reflexivity. \n  apply valid_in in H. apply H. apply H1.\nQed.\n\n(*A key characterization of distances: If (v', d) is the first instance of v' on the queue and v' has not\n  yet been discovered, when we step, either (v', d) is in the output, or the same condition holds*)\nLemma first_queue_constant: forall s g v v' d' l1 l2 s',\n  valid s g v ->\n  get_queue s = l1 ++ (v', d') :: l2 ->\n  (forall x, In x (map fst l1) -> x <> v') ->\n  ~In v' (map fst (get_dists s)) ->\n  bfs_step s s' ->\n  (In (v', d') (get_dists s') \\/ \n  (~In v' (map fst (get_dists s')) /\\\n  exists l1 l2, get_queue s' = l1 ++ (v', d') :: l2  /\\\n  (forall x, In x (map fst l1) -> x <> v'))).\nProof.\n  intros. inversion H3; subst; simpl in *.\n  - destruct (N.eq_dec v0 v'). subst. left.\n    destruct l1. simpl in H0. inversion H0. subst. solve_in.\n    simpl in H0. inversion H0; subst. \n    specialize (H1 v'). simpl in H1. \n    assert (v' <> v') by (apply H1; left; reflexivity); contradiction.\n    destruct l1. simpl in H0. inversion H0; subst. contradiction.\n    destruct p. inversion H0; subst. right. split. intro.\n    rewrite map_app in H6. apply in_app_or in H6. destruct H6. contradiction.\n    simpl in H6. destruct H6; subst. contradiction. destruct H6.\n    exists l1. exists (l2 ++ suci c (i + 1)%Z). split. rewrite <- app_assoc.\n    simpl. reflexivity. intros. apply H1. simpl. right. assumption.\n  - assert (vIn g0 v' = true). destruct (vIn g0 v') eqn : E. reflexivity.\n     replace g0 with (get_graph (g0, (v0, j) :: vs, d)) in E by reflexivity.\n    rewrite <- graph_iff_not_output in E. simpl in E. contradiction.\n    apply H. \n    eapply queue_in_graph. apply H. rewrite H0. simpl.\n    rewrite map_app. apply in_or_app. right. simpl. left. reflexivity.\n    right. split. assumption. destruct l1. simpl in H0. inversion H0; subst.\n    rewrite <- match_in in H6. destruct_all. rewrite H6 in H5. inversion H5.\n    inversion H0; subst. exists l1. exists l2. split. reflexivity. intros. apply H1.\n    simpl. right. assumption.\nQed.\n\n(*Multistep version of the above*)\nLemma first_queue_contant_multi: forall s g v v' d' l1 l2 s',\n  valid s g v ->\n  get_queue s = l1 ++ (v', d') :: l2 ->\n  (forall x, In x (map fst l1) -> x <> v') ->\n  ~In v' (map fst (get_dists s)) ->\n  bfs_multi s s' ->\n  (In (v', d') (get_dists s') \\/ \n  (~In v' (map fst (get_dists s')) /\\\n  exists l1 l2, get_queue s' = l1 ++ (v', d') :: l2  /\\\n  (forall x, In x (map fst l1) -> x <> v'))).\nProof.\n  intros. generalize dependent l1. revert l2. induction H3; intros.\n  - right. split; try(assumption). exists l1. exists l2. split; try(assumption).\n  - pose proof (first_queue_constant _ _ _ _ _ _ _ _ H H1 H4 H2 H0). destruct H5.\n    left. eapply output_preserved_strong. eapply v_step. apply H. apply H0.\n    assumption. apply H5. destruct_all. assert (valid y g v). eapply v_step.\n    apply H. assumption. specialize (IHmulti H8 H5 _ _ H6 H7). apply IHmulti.\nQed.\n\n(*Now we know that if (v', d') is the first instance of v' on the queue at some point, v', g') is in\n  the distances when we finish (since the other condition cannot happen)*)\nLemma first_queue_in_dists: forall s g v v' d' l1 l2 s',\n  valid s g v ->\n  valid s' g v ->\n  get_queue s = l1 ++ (v', d') :: l2 ->\n  (forall x, In x (map fst l1) -> x <> v') ->\n  ~In v' (map fst (get_dists s)) ->\n  done s' = true ->\n  In (v', d') (get_dists s').\nProof.\n  intros. destruct (done s) eqn : D.\n  - assert (s = s'). eapply done_unique. apply H. \n    assumption. assumption. assumption. subst.\n    unfold done in D. rewrite H1 in D. rewrite orb_true_iff in D.\n    destruct D. destruct l1; simpl in H5; inversion H5.\n    rewrite isEmpty_def in H5. \n    assert (vIn (get_graph s') v' = true). destruct (vIn (get_graph s') v') eqn : V.\n    reflexivity. eapply graph_iff_not_output in V. contradiction. apply H.\n    eapply queue_in_graph. apply H. rewrite H1. rewrite map_app. simpl. solve_in.\n    rewrite H5 in H6. inversion H6. assumption.\n  - pose proof (multi_done _ _ _ _ H H0 D H4).\n    pose proof (first_queue_contant_multi _ _ _ _ _ _ _ _ H H1 H2 H3 H5). destruct H6. assumption.\n    destruct_all. unfold done in H4. rewrite H7 in H4.\n    rewrite orb_true_iff in H4. destruct H4. destruct x; simpl in H4; inversion H4.\n    rewrite isEmpty_def in H4. destruct (vIn (get_graph s') v') eqn : V.\n    rewrite H4 in V. inversion V. eapply graph_iff_not_output in V. \n    contradiction. apply H0. eapply queue_in_graph. apply H. rewrite H1. rewrite map_app; simpl; solve_in.\n    assumption.\nQed.\n\nLemma queue_smaller_than_dists: forall s g v,\n  valid s g v ->\n  (forall n, In n (map snd (get_queue s)) ->\n  (forall m, In m (map snd (get_dists s)) ->\n  (m <= n)%Z)).\nProof.\n  intros. generalize dependent n. generalize dependent m. induction H; intros. unfold start in *; simpl in *. destruct H1.\n  inversion H0; subst; simpl in *.\n  - rewrite map_app in *. apply in_app_or in H1. apply in_app_or in H2. destruct H2.\n    destruct H1. apply IHvalid.  assumption. right. assumption. simpl in H1.\n    destruct H1. subst. pose proof (queue_structure _ _ _ v0 m vs H) .\n    assert (get_queue (g0, (v0, m) :: vs, d) = (v0, m) :: vs) by reflexivity. specialize (H1 H5); clear H5.\n    destruct H1. simpl in H1. apply Sorted_StronglySorted in H1. inversion H1; subst.\n    rewrite Forall_forall in H9. apply H9. assumption. unfold Relations_1.Transitive. intros. omega. \n    destruct H1.  \n    rewrite in_map_iff in H2. destruct H2. destruct x. simpl in *. destruct H2. subst.  \n    rewrite (suci_def n0 n _ c v0 g0 g' H4) in H5. destruct H5. subst.\n    destruct H1. assert ( (m<=j)%Z). apply IHvalid. assumption. left. reflexivity. omega.\n    destruct H1. subst. omega. destruct H1.\n  - apply IHvalid. assumption. right. assumption.\nQed.\n\n(*Another key property of BFS: the distances are sorted*)\nTheorem dists_sorted: forall s g v,\n  valid s g v ->\n  Sorted Z.le (map snd (get_dists s)).\nProof.\n  intros. induction H.\n  - simpl. constructor.\n  - inversion H0; subst; simpl in *.\n    + rewrite map_app. eapply SortA_app. apply eq_equivalence. apply IHvalid.\n      simpl. constructor. constructor. constructor. intros.\n      simpl in H4. rewrite <- In_InA_equiv in H4. rewrite <- In_InA_equiv in H3. \n      eapply queue_smaller_than_dists. apply H.\n      simpl. simpl in H4. destruct H4. subst. left. reflexivity. destruct H4.\n      simpl. assumption.\n    + assumption.\nQed.\n\nDefinition dist_plus_one s v :=\n  match find_dist s v with\n  | Some n => Some (n + 1)\n  | None => None\n  end.\n\n(** The big result: Every (v', d) pair that appears in the output is actually the shortest\n  distance from v to v'. This also implies reachability, although that was already proved separately\n  (and is needed for this proof) **)\n\nTheorem bfs_tail_correct: forall s g v,\n  valid s g v ->\n  done s = true ->\n  (forall v',\n  vIn g v' = true ->\n  dist_plus_one s v' = distance g v v').\nProof.\n  intros. destruct (distance g v v') eqn : D.\n  - generalize dependent v'. induction n as [ n IHn ] using (well_founded_induction lt_wf).\n    intros. unfold dist_plus_one. destruct (find_dist s v') as [n'|] eqn : D' .\n    rewrite find_dist_in in D'.\n    pose proof (dist_upper_bound _ _ _ _ _ H D'). rewrite D in H2.\n    rewrite Nat2Z.id in H2. simpl in H2.\n    rewrite Nat.leb_le in H2. assert (n = n' + 1 \\/ n < n' + 1) by omega.\n    destruct H3. subst. reflexivity. clear H2.\n    (*It cannot be the start node*)\n    destruct (N.eq_dec v v'). subst. unfold distance in D. apply distance_some in D. destruct D as [l].\n    destruct H2. subst. assert (shortest_path g v' v' (v' ::  nil)) by (apply distance_refl; assumption).\n    apply distance_of_shortest_path in H4. simpl in H4. eapply shortest_path_distance in H4.\n    rewrite H4. \n    pose proof (start_0_dist _ _ _ H).\n    assert (In (v', 0%Z) (get_dists s)). apply H5. intro. rewrite H6 in D'. destruct D'.\n    assert (Z.of_nat n' = 0%Z). eapply NoDup_pairs. apply   (no_dups_output _ _ _ H).\n    apply D'. assumption. assert (n' = 0) by omega. subst. omega. assumption. \n    (*Get predecessor on shortest path*)\n    assert (P := D). unfold distance in P. apply distance_some in P. destruct P as [l].\n    destruct_all. assert (S:=H2). unfold shortest_path in H2. destruct_all.\n    inversion H2; subst. contradiction.\n    rename v'0 into w. simpl in H3.\n    assert (vIn g v = true). eapply valid_in. apply H.\n    destruct (distance g v w) as [nw|] eqn : DW . unfold distance in DW. assert (E := DW).\n    apply distance_some in DW. destruct DW as [lw]. destruct H8.\n    assert (nw + 1 = length (v' :: l0)). { (*idea, since lw is sp from v -> w, we know that\n    length l0 >= length lw, if greater, then can have shorter path to v, so must be equal, this proves claim*)\n    assert (length lw <= length l0). { unfold shortest_path in H8. destruct_all.\n    assert (length lw <= length l0 \\/ length l0 < length lw) by omega. destruct H11. assumption.\n    apply H10 in H11. contradiction. } assert (length lw < length l0 \\/ length lw = length l0) by omega.\n    destruct H11. assert (path' g v v' (v' :: lw)). eapply p_multi. unfold shortest_path in H8.\n    apply H8. assumption. exfalso. apply (H5 (v' :: lw)). simpl. omega. assumption. subst. \n    simpl. rewrite H11. omega. } rewrite <- H10. \n    assert (dist_plus_one s w = Some nw). apply IHn. omega. apply edges_valid in H7. destruct H7. assumption.\n    assumption. unfold dist_plus_one in H11. destruct (find_dist s w) eqn : F. 2 : { inversion H11. }\n    inversion H11; subst. rewrite find_dist_in in F.\n    (*we know that the predecessor has distance 1 less and is thus in the distances correctly. We now\n    look at the state at which this vertex is added to the distances*)\n    pose proof (output_is_added _ _ _ _ _ H F). destruct H9 as [sw]. destruct H9 as [c].\n    destruct H9 as [g']. destruct H9. destruct H12. destruct H14. destruct H15. \n    destruct H16 as [l2]. destruct H14. destruct H14. \n    (*first case, v' is already finished *)\n    assert (L: n < n'). { assert (length l0 = length lw). simpl in H10; inversion H10. omega.\n    rewrite H18 in H3. rewrite <- H18 in H3. omega. }\n    destruct (In_dec N.eq_dec v' (map fst (get_dists sw))).\n    rewrite H16 in i. rewrite map_app in i. apply in_app_or in i. destruct i.\n    rewrite in_map_iff in H18. destruct H18. destruct x0. simpl in H18. destruct H18; subst.\n    pose proof (dists_sorted _ _ _ H9). rewrite H16 in H18. rewrite map_app in H18. \n    simpl in H18. epose proof (sort_app (map snd l2) (Z.of_nat n :: nil) Z.le H18).\n    assert (Relations_1.Transitive Z.le). unfold Relations_1.Transitive. intros; omega.\n    specialize (H20 H21); clear H21. specialize (H20 i (Z.of_nat n)).\n    assert (i <= Z.of_nat n)%Z.  apply H20. rewrite in_map_iff. exists (v', i).\n    split. reflexivity. assumption. simpl. left. reflexivity. clear H20.\n    pose proof (no_dups_output _ _ _ H). epose proof (NoDup_pairs _ v' i (Z.of_nat n') H20).\n    assert (i = Z.of_nat n'). apply H22. eapply output_preserved_strong.\n    apply H9. assumption. rewrite H16. solve_in. assumption. subst.\n     omega. \n    simpl in H18. destruct H18. subst. exfalso. apply (H5 l0). simpl. omega. assumption. destruct H18.\n    (* Now we know that v' has not been finished already. Now we need to see if it was already in\n        the queue or not*)\n    (*Next case: v' not already done, but it is already on the queue*)\n    (*Hmm do we need that - just look at 1st position on the queue, it is <= nw + 1 by sorted, already a contradiction*)\n    simpl in H14. assert (In v' (map fst (suci c (Z.of_nat n + 1)%Z))). { assert (vIn (get_graph sw) v' = true). \n    destruct (vIn (get_graph sw) v') eqn : ?. reflexivity. rewrite <- graph_iff_not_output in Heqb0.\n    contradiction. apply H9. assumption.\n    pose proof suci_def. pose proof (prior_state _ _ _ H9 H15). destruct H20 as [sp]. destruct H20.\n    specialize (H17 _ H20 H21). destruct H17. destruct H22. simpl in H14. \n    specialize (H19 v' ((Z.of_nat n + 1)%Z) ((Z.of_nat n + 1)%Z) c w (get_graph sp) g' H22).\n    destruct H19. rewrite in_map_iff. exists (v', (Z.of_nat n + 1)%Z). simpl. split. reflexivity.\n    apply H24. split. reflexivity. rewrite edge_in_state. (*solve_assume.*) split; try(assumption).\n    rewrite <- match_in. exists c. exists g'. assumption. \n    destruct (vIn (get_graph sp) v') eqn : V. reflexivity. rewrite <- graph_iff_not_output in V.\n    assert (In v' (map fst (get_dists sw))). eapply output_preserved. apply H20.\n    eapply multi_step. apply H21. constructor. assumption. contradiction. apply H20. assumption.\n    apply H20. assumption. }\n    assert (In v' (map fst (get_queue sw))). rewrite H14. rewrite map_app. solve_in.\n    epose proof (@in_split_app_special _ _ N.eq_dec _ _ H19). destruct H20 as [i]. \n    destruct H20 as [l']. destruct H20 as [l'']. clear H19. assert (H19 := H20). clear H20. destruct H19.\n    assert (suci c (Z.of_nat n + 1)%Z <> nil). {\n    destruct (suci c (Z.of_nat n + 1)%Z) eqn : S'. destruct H18. intro. inversion H21. }\n    pose proof (exists_last H21). destruct H22. destruct s0. rewrite e in H14.\n    assert (Sorted Z.le (map snd (get_queue sw))). { \n    destruct l'. simpl in H19.\n    pose proof (queue_structure _ _ _ _ _ _ H9 H19). apply H22. simpl in H19. destruct p.\n    pose proof (queue_structure _ _ _ _ _ _ H9 H19). apply H22. }\n    assert (i <= (Z.of_nat  n + 1))%Z. { destruct x1.\n    assert (In (n2, i0) (suci c (Z.of_nat n + 1)%Z )) by (rewrite e; solve_in).\n    pose proof suci_def. pose proof (prior_state _ _ _ H9 H15). destruct H25 as [sp]. destruct H25.\n    specialize (H17 _ H25 H26). destruct H17. destruct H27. \n    specialize (H24 n2 i0 ((Z.of_nat n + 1)%Z) c w (get_graph sp) g' H27).\n    rewrite H24 in H23. destruct H23. subst.\n    clear H26. clear H25. clear H24. destruct l''. rewrite H14 in H19.\n    pose proof ( app_inj_tail  (x ++ x0) l' (n2, (Z.of_nat n + 1)%Z) (v', i)).\n    assert (x ++ x0 = l' /\\ (n2, (Z.of_nat n + 1)%Z) = (v', i)). apply H23. rewrite <- app_assoc.\n    apply H19. clear H23. destruct H24. inversion H24; subst. omega.\n    remember (p :: l'') as l'''. assert (l''' <> nil). subst. intro. inversion H23.\n    pose proof (exists_last H23). destruct H24. destruct s0. rewrite e0 in H19.\n    rewrite H14 in H19. destruct x2.\n    pose proof  ( app_inj_tail  (x ++ x0) ( l' ++ (v', i) :: x1) (n2, (Z.of_nat n + 1)%Z) (n3, i0)).\n    assert (x ++ x0 = l' ++ (v', i) :: x1 /\\ (n2, (Z.of_nat n + 1)%Z) = (n3, i0)). apply H24.\n    rewrite <- app_assoc. rewrite H19. rewrite <- app_assoc. simpl. reflexivity. clear H24.\n    destruct H25. inversion H25; subst. rewrite app_assoc in H14. rewrite H24 in H14.\n    rewrite H14 in H22. rewrite map_app in H22. eapply sort_app in H22.\n    apply H22. unfold Relations_1.Transitive. intros. omega. rewrite map_app.\n    simpl. solve_in. simpl. left. reflexivity. }\n    pose proof (first_queue_in_dists _ _ _ _ _ _ _ _ H9 H H19 H20 n1 H0).\n    assert (i = Z.of_nat n'). eapply NoDup_pairs. eapply no_dups_output.\n    apply H. apply H24. assumption. subst.\n    assert (n' <= n + 1). omega. assert (n' < n + 1 \\/ n' = n + 1) by omega.\n    destruct H26. omega. subst. reflexivity. apply H.\n    (*The hard part is over! The rest of the cases are basically just showing that None cases give contradictions*)\n    unfold distance in DW. rewrite distance_none in DW. exfalso.\n    apply (DW l0). assumption. apply H. rewrite find_dist_not in D'.\n    pose proof (output_iff_reachable _ _ _ v' H H0). assert (In v' (map fst (get_dists s))).\n    apply H2. apply distance_some in D. destruct_all. exists x. apply H3.\n    rewrite in_map_iff in H3. destruct_all. destruct x; subst. exfalso. apply (D' i).\n    simpl; assumption.\n  - pose proof (output_iff_reachable _ _ _ v' H H0).\n    unfold distance in D. rewrite distance_none in D.\n    unfold dist_plus_one. destruct (find_dist s v') eqn : F.\n    rewrite find_dist_in in F. assert ((exists l : list Node, path' g v v' l)).\n    apply H2. rewrite in_map_iff. exists (v', Z.of_nat n). simpl. solve_assume.\n    destruct_all. exfalso. apply (D x). assumption. apply H. reflexivity.\nQed.\n\nEnd Correctness.\n\n(** ** Equivalence and Correctness of [level] (bfs with distances) **)\n\nSection Level.\n\nInstance need_this_for_equations' : WellFounded (bf_measure_list (Node * Num.Int)).\nProof.\n  unfold WellFounded. apply well_founded_bf_measure_list.\nDefined.\n\nEquations leveln' (x: (list (Node * Num.Int) * (gr a b))) : list (Node * Num.Int) by wf x (bf_measure_list (Node * Num.Int)) :=\n  leveln' (nil, g) := nil;\n  leveln' ((v,j) :: vs, g) := if (isEmpty g) then nil else\n                                match (match_ v g) as y return ((match_ v g = y) -> _ ) with\n                                | (Some c, g') => fun H : (match_ v g) = (Some c, g') => (v,j) :: leveln' ( (vs ++ suci c (Num.op_zp__ j (Num.fromInteger 1))), g')\n                                | (None, g') => fun H: (match_ v g) = (None, g') => leveln' (vs, g')\n                                 end (eq_refl).\nNext Obligation.\nunfold bf_measure_list. apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply H.\nDefined.\nNext Obligation.\nunfold bf_measure_list. apply lex2. symmetry. unfold natNodes_eq. eapply match_none_size. apply H. unfold list_length_lt.\nsimpl. omega.\nDefined.\n\n\nDefinition expand_leveln' := \nfun x : list (Node * Num.Int) * gr a b =>\nlet (l, g) := x in\nmatch l with\n| nil => fun _ : gr a b => nil\n| p :: l0 =>\n    fun g0 : gr a b =>\n    (let (n, i) := p in\n     fun (l1 : list (Node * Num.Int)) (g1 : gr a b) =>\n     if isEmpty g1\n     then nil\n     else\n      (let (m, g') as y return (match_ n g1 = y -> list (Node * Num.Int)) := match_ n g1 in\n       match m as m0 return (match_ n g1 = (m0, g') -> list (Node * Num.Int)) with\n       | Some c =>\n           fun _ : match_ n g1 = (Some c, g') =>\n           (n, i) :: leveln' (l1 ++ suci c (Num.op_zp__ i (Num.fromInteger 1)), g')\n       | None => fun _ : match_ n g1 = (None, g') => leveln' (l1, g')\n       end) eq_refl) l0 g0\nend g.\n\nLemma unfold_leveln': forall x,\n  leveln' x = expand_leveln' x.\nProof.\n  intros. unfold expand_leveln'. apply leveln'_elim. reflexivity. reflexivity.\nQed.\n\nLemma leveln_leveln'_equiv: forall g q,\n  leveln' (q, g) = leveln q g.\nProof.\n  intros. remember (q, g) as x. generalize dependent q. revert g. \n  induction (x) as [y IH] using (well_founded_induction (well_founded_bf_measure_list (Node * Num.Int))).\n  intros. destruct y. inversion Heqx; subst. clear Heqx. unfold leveln.\n  rewrite unfold_leveln'. simpl. \n   unfold deferredFix2 in *. unfold curry in *.\n  rewrite (deferredFix_eq_on _ (fun x => True) ( (bf_measure_list (_)) )).\n  - simpl. destruct q eqn : Q.  \n    + reflexivity.\n    + simpl. destruct p. \n      destruct (isEmpty g) eqn : GE. reflexivity. \n      destruct (match_ n g) eqn : M. unfold leveln in IH. unfold deferredFix2 in IH. unfold curry in IH. destruct m.\n      *  erewrite IH.\n        reflexivity. unfold bf_measure_list. apply lex1. unfold natNodes_lt. eapply match_decr_size.\n        symmetry. apply M. reflexivity.\n      * erewrite IH. reflexivity. unfold bf_measure_list. apply lex2. unfold natNodes_eq.\n        symmetry. eapply match_none_size. apply M. unfold list_length_lt. simpl. omega. reflexivity.\n  - eapply well_founded_bf_measure_list.\n  - unfold recurses_on. intros. unfold uncurry. destruct x. destruct l eqn : ?. reflexivity. \n    destruct (isEmpty g1) eqn : ?. reflexivity. simpl. destruct p. \n    destruct (match_ n g1) eqn : ?. destruct m. rewrite H0. reflexivity. apply I.\n    unfold bf_measure_list. apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply Heqd.\n    rewrite H0. reflexivity. apply I. apply lex2. unfold natNodes_eq. symmetry. eapply match_none_size.\n    apply Heqd. unfold list_length_lt. simpl. omega.\n  - apply I.\nQed. \n\nLemma leveln_tail_equiv: forall x l,\n  get_dists (bfs_tail (x, l)) = l ++ leveln' (snd x, fst x).\nProof.\n  intros x. remember (snd x, fst x) as x'. generalize dependent x.\n  induction (x') using (well_founded_induction (well_founded_bf_measure_list (Node * Num.Int))).\n  intros. destruct x'; inversion Heqx'; subst; clear Heqx'.\n  rewrite unfold_leveln'. rewrite unfold_bfs_tail. simpl.  (* unfold expand_leveln'. *)\n  destruct x as [g q]. simpl. destruct q eqn : Q.\n  - simpl. rewrite app_nil_r. reflexivity.\n  - destruct p as [v j]. destruct (isEmpty g) eqn : G. \n    + simpl. rewrite app_nil_r. reflexivity.\n    + destruct (match_ v g) eqn : M. destruct m.\n      * remember (g0, l0 ++ suci c (j + 1)%Z) as x. erewrite H. rewrite <- app_assoc. simpl.\n        reflexivity. unfold bf_measure_list. simpl. destruct x. apply lex1.\n        unfold natNodes_lt. eapply match_decr_size. symmetry. inversion Heqx; subst. apply M.\n        destruct x. inversion Heqx; subst. simpl. reflexivity.\n      * erewrite H. reflexivity. unfold bf_measure_list.  apply lex2.\n        unfold natNodes_eq. symmetry. eapply match_none_size. apply M. unfold list_length_lt. simpl. omega.\n        simpl. reflexivity.\nQed. \n\n(** Correctness of [level] **)\n\n\n(*The Haskell level function (the actual BFS function) is equivalent to running bfs_tail from the start\n  state and getting the distances. Now we get correctness from the previous proven results*)\nTheorem level_tail_equiv: forall v g,\n  get_dists (bfs_tail (start g v)) = level v g.\nProof.\n  intros. unfold level. rewrite <- leveln_leveln'_equiv.\n  rewrite leveln_tail_equiv. simpl. reflexivity.\nQed.\n\nLemma level_invalid: forall v (g: gr a b),\n  vIn g v = false ->\n  level v g = nil.\nProof.\n  intros. unfold level. rewrite <- leveln_leveln'_equiv. simpl. rewrite unfold_leveln'. simpl.\n  destruct (isEmpty g). reflexivity. destruct (match_ v g) eqn : M. destruct m.\n  - assert (vIn g v = true). rewrite <- match_in. exists c. exists g0. assumption. rewrite H0 in H. inversion H.\n  - rewrite unfold_leveln'. simpl. reflexivity.\nQed. \n\n(*[level], when run from a vertex v (not necessarily in the graph), produces a list of the shortest distances from v to v' for\n  each v' that is reachable from v. Note that this also implies that a vertex is in this list iff it is\n  reachable from v.*)\nTheorem level_finds_shortest_path: forall v g v',\n  match (find_dist_list (level v g) v') with\n  | Some n => Some (n+1)\n  | None => None\n  end = distance g v v'.\nProof.\n  intros.\n  destruct (vIn g v) eqn : H.\n  assert (V: valid (bfs_tail (start g v)) g v). eapply multi_valid. apply v_start. assumption.\n  eapply bfs_tail_multi. assert (D': done (bfs_tail (start g v)) = true). eapply bfs_tail_done.\n  rewrite <- level_tail_equiv.\n  destruct (vIn g v') eqn : D.\n  - pose proof bfs_tail_correct. unfold dist_plus_one in H0. unfold find_dist in H0.\n    specialize (H0 (bfs_tail (start g v)) g v).\n    specialize (H0 V D' v' D). rewrite <- H0. reflexivity.\n  - replace (find_dist_list (get_dists (bfs_tail (start g v))) v') with (find_dist (bfs_tail (start g v)) v') by\n    (unfold find_dist; reflexivity).\n    destruct (find_dist (bfs_tail (start g v)) v') eqn : F.\n    + rewrite find_dist_in in F. pose proof output_iff_reachable.\n      assert (exists l, path' g v v' l). rewrite <- H0. rewrite in_map_iff. exists (v', Z.of_nat n).\n      solve_assume. apply F. assumption. assumption. destruct_all. apply path_implies_in_graph in H1.\n      destruct_all. rewrite H2 in D. inversion D. apply V.\n    + destruct (distance g v v') eqn : DI.\n      * apply distance_some in DI. destruct_all. unfold shortest_path in H0.\n        destruct_all. apply path_implies_in_graph in H0. destruct_all. rewrite H3 in D. inversion D.\n      * reflexivity.\n  - assert (A:= H). apply level_invalid in H. rewrite H. simpl. destruct (distance g v v') eqn : D.\n    + apply distance_some in D. destruct_all. unfold shortest_path in H0. destruct_all.\n      apply path_implies_in_graph in H0. destruct_all. rewrite H0 in A. inversion A.\n    + reflexivity.\nQed. \n\n(*The resulting list is sorted by shortest path distance*)\nTheorem level_sorted_by_dist: forall v (g: gr a b),\n  Sorted Z.le (map snd (level v g)).\nProof.\n  intros. destruct (vIn g v) eqn : ?.  rewrite <- level_tail_equiv.\n  eapply dists_sorted. eapply multi_valid. \n  apply v_start. apply Heqb0. apply bfs_tail_multi. rewrite level_invalid. simpl. constructor.\n  assumption.\nQed.\n\nTheorem no_dup_level: forall v (g: gr a b),\n  NoDup (map fst (level v g)).\nProof.\n  intros. destruct (vIn g v) eqn : ?. rewrite <- level_tail_equiv.\n  eapply no_dups_output. eapply multi_valid. apply v_start. apply Heqb0. apply bfs_tail_multi.\n  rewrite level_invalid. simpl. constructor. assumption.\nQed.\n \nEnd Level.\n\n(** ** Equivalence and Correctness of [bfsnInternal] (just returns vertices) **)\n\nSection Bfsn.\n\n(*TODO: see if there is a better specification. I'm not sure how to make a general specification, since\n  the function can be arbitrary: ex: f x => 1 or f x => (number of outgoing edges), and the function depends\n  on the context, which we don't really know anything about. But I can prove the general case for when the\n  function depends only on the vertex , which includes [bfs].\n  Relatedly, not sure what to say for [bfsn], since the list could be anything. The resulting output is not\n  really bfs at all, and we really dont know much about the resulting output*)\n\n\nInstance need_this_for_equations'' : WellFounded (bf_measure_list (Node)).\nProof.\n  unfold WellFounded. apply well_founded_bf_measure_list.\nDefined.\nSection Func.\nContext {c: Type}.\n\n\nEquations bfsnInternal' (x :  (list Node) * (gr a b)) (f: Context a b -> c)  : (list c) by wf x (bf_measure_list Node) :=\n  bfsnInternal' (nil, g) f := nil;\n  bfsnInternal' ((v :: q'), g) f := if (isEmpty g) then nil else\n      match (match_ v g) as y return ((match_ v g = y) -> _) with\n                        | (Some c, g') => fun H : (match_ v g) = (Some c, g') => \n                          (f c) :: (bfsnInternal' (q' ++ (suc' c), g') f)\n                        | (None, g') => fun H : (match_ v g) = (None, g') => ( bfsnInternal' (q', g') f)\n                        end (eq_refl).\nNext Obligation.\nunfold bf_measure_list. apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply H.\nDefined.\nNext Obligation.\nunfold bf_measure_list. apply lex2. symmetry. unfold natNodes_eq. eapply match_none_size. apply H. unfold list_length_lt.\nsimpl. omega.\nDefined.\n\nDefinition expand_bfsnInternal' := \nfun (x : list Node * gr a b) (f : Context a b -> c) =>\n(let (l, g) := x in\n fun f0 : Context a b -> c =>\n match l with\n | nil => fun (_ : gr a b) (_ : Context a b -> c) => nil\n | n :: l0 =>\n     fun (g0 : gr a b) (f1 : Context a b -> c) =>\n     if isEmpty g0\n     then nil\n     else\n      (let (m, g') as y return (match_ n g0 = y -> list c) := match_ n g0 in\n       match m as m0 return (match_ n g0 = (m0, g') -> list c) with\n       | Some c0 => fun _ : match_ n g0 = (Some c0, g') => f1 c0 :: bfsnInternal' (l0 ++ suc' c0, g') f1\n       | None => fun _ : match_ n g0 = (None, g') => bfsnInternal' (l0, g') f1\n       end) eq_refl\n end g f0) f.\n\nLemma unfold_bfsnInternal' : forall x f, bfsnInternal' x f = expand_bfsnInternal' x f.\nProof.\n  intros. unfold expand_bfsnInternal'. apply bfsnInternal'_elim. reflexivity. reflexivity.\nQed.\n\n(*Unfortunately, [bfsnInternal] contains a function parameter, so we need yet another well_founded relation\n  to enable unrolling [deferredFix]. This one is made up a compound lexicographic order, where we ignore\n  the function argument, so it ends up being effectively equivalent to [bf_measure_queue]*)\n\nDefinition bfs_two {C} := (lex _ C (@queue_length_lt Node) (fun x y => length (toList _ x) = length (toList _ y)) (fun x y => False)).\n\nDefinition bfs_three {C} := lex _ _ (natNodes_lt) (natNodes_eq)  (@bfs_two C).\n\nLemma wf_bfs_three: forall C, well_founded (@bfs_three C).\nProof.\n  intros. unfold bfs_three. apply WF_lex.\n  - apply f_nat_lt_wf.\n  - unfold bfs_two. apply WF_lex.\n    + apply f_nat_lt_wf.\n    + unfold well_founded. intros. apply Acc_intro. intros. destruct H.\n    + unfold Transitive. intros. omega.\n    + intros. unfold queue_length_lt in *. destruct_all. unfold list_length_lt in *. omega.\n    + unfold Symmetric. intros. omega.\n  - unfold Transitive. unfold natNodes_eq. intros. omega.\n  - intros. unfold natNodes_eq in *. unfold natNodes_lt in *. destruct_all. omega.\n  - unfold Symmetric. intros. unfold natNodes_eq in *. omega.\nQed.\n\nLemma bfsnInternal_equiv: forall q g f,\n  bfsnInternal f q g = bfsnInternal' ((toList _ q),g) f.\nProof.\n  intros. remember (toList Node q) as l. remember (l, g) as x. \n  generalize dependent l. revert g. revert q.\n  induction (x) as [y IH] using (well_founded_induction (well_founded_bf_measure_list _)).\n  intros. destruct y. inversion Heqx. subst. clear Heqx. unfold bfsnInternal.\n  rewrite unfold_bfsnInternal'. simpl. \n  unfold deferredFix3. unfold curry. unfold deferredFix2. unfold curry.\n  rewrite (deferredFix_eq_on _ (fun x => True) ( (bfs_three ) )).\n  simpl. destruct (queueGet q) eqn : Q.\n  destruct (queueEmpty q) eqn : QE.\n  - simpl. rewrite toList_queueEmpty in QE. rewrite QE. reflexivity.\n  - simpl. destruct (toList _ q) eqn : L.\n    + rewrite <- toList_queueEmpty in L. rewrite L in QE. inversion QE.\n    + pose proof (toList_queueGet _ _ _ _ L). rewrite Q in H. destruct H. simpl in *. subst.\n      destruct (isEmpty g) eqn : G. reflexivity.\n      destruct (match_ n0 g) eqn : M. destruct m.\n      * unfold bfsnInternal in IH. unfold deferredFix3 in IH. unfold curry in IH. unfold deferredFix2 in IH.\n        unfold curry in IH. erewrite IH. reflexivity. unfold bf_measure_list. apply lex1. \n        unfold natNodes_lt. eapply match_decr_size. symmetry. apply M. reflexivity.\n        rewrite toList_queuePutList . reflexivity.\n      * unfold bfsnInternal in IH. unfold deferredFix3 in IH. unfold curry in IH. unfold deferredFix2 in IH.\n        unfold curry in IH. erewrite IH. reflexivity. apply lex2. unfold natNodes_eq. symmetry. \n        eapply match_none_size. apply M. unfold list_length_lt. simpl. omega. reflexivity.\n        reflexivity.\n  - apply wf_bfs_three.\n  - unfold recurses_on. intros. unfold uncurry. destruct x. destruct p. destruct (queueGet q0) eqn : Q'.\n    destruct (queueEmpty q0) eqn : QE'. simpl. reflexivity.\n    destruct (isEmpty g1) eqn : G'; try(reflexivity). simpl. destruct (match_ n g1) eqn : M'.\n    destruct m. rewrite H0. reflexivity. apply I. unfold bfs_three.\n    apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply M'. rewrite H0. reflexivity.\n    apply I. apply lex2. unfold natNodes_eq. symmetry. eapply match_none_size. apply M'.\n    apply lex1. unfold queue_length_lt. destruct (toList _ q0) eqn : L'.\n    rewrite <- toList_queueEmpty in L'. rewrite L' in QE'. inversion QE'.\n    pose proof (toList_queueGet _ _ _ _ L'). rewrite Q' in H1. simpl in H1. destruct H1. subst.\n    unfold list_length_lt. simpl. omega.\n  - apply I.\nQed.\n\n(*Not sure what we can say about the general bfsnInternal function, but we can prove that if the function\n  given depends only on the vertices, it is the same as applying that function to each vertex in the output\n  of [leveln']*)\nLemma bfsInternal_on_vertex_equiv: forall q q' (g: gr a b) (f: Context a b -> c) (default : a),\n  (forall c c', node' c = node' c' -> f c = f c') ->\n  map fst q' = q ->\n  bfsnInternal' (q, g) f = map (fun (x: Node * Num.Int) => let (v, d) := x in f (nil, v, default, nil)) (leveln' (q', g)).\nProof.\n  intros. remember (q, g) as p. generalize dependent q. generalize dependent g. generalize dependent q'.\n  induction p using (well_founded_induction (well_founded_bf_measure_list _)). intros.\n  rewrite unfold_bfsnInternal'. rewrite unfold_leveln'. simpl. destruct p. inversion Heqp. rewrite H3 in H0. rewrite H4 in H0. clear Heqp. clear H3. clear l. clear H4. clear g0.\n  simpl. destruct q eqn : Q.\n  - destruct q'. simpl. reflexivity. simpl in H1. inversion H1.\n  - destruct q' eqn : Q'. simpl in H1. inversion H1. simpl in H1. inversion H1. subst. destruct p.\n    simpl. destruct (isEmpty g) eqn : E. simpl. reflexivity.\n    destruct (match_ n g) eqn : M. destruct m.\n    + simpl. specialize (H c0 (nil, n, default, nil)). simpl in H. rewrite H. erewrite H0.  reflexivity.\n      apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply M. reflexivity.\n      rewrite map_app. unfold suci. rewrite map_fst_zip. reflexivity. rewrite repeat_length.\n      apply length_equiv . destruct c0. destruct p. destruct p. simpl. apply match_context in M.\n      destruct_all. subst. reflexivity.\n    + erewrite H0. reflexivity. apply lex2. unfold natNodes_eq. symmetry. eapply match_none_size.\n      apply M. unfold list_length_lt. simpl. omega. reflexivity. reflexivity.\nQed.\nEnd Func.\n\n(** ** Correctness of [bfs] **)\n(*This states that running bfs is the same as taking the first element from [level]. Note that this immediately\n  implies that bfs contains all reachable vertices and they are sorted by distance*)\n(*Need an instance of type [a] for the proof to go through. TODO: see if I can eliminate this assumption*)\nTheorem bfs_def: forall v (g: gr a b) (x: a),\n  bfs v g = map fst (level v g).\nProof.\n  intros. unfold bfs. unfold bfsWith. unfold level. \n  pose proof (@bfsnInternal_equiv Node). rewrite H.\n  clear H. rewrite <- leveln_leveln'_equiv.\n  pose proof (@bfsInternal_on_vertex_equiv Node (toList Node (queuePut v mkQueue)) \n  ((v, Num.fromInteger 0) :: nil) g node' x). simpl in H. unfold fst. apply H. intros.\n  assumption. reflexivity.\nQed. \n\nEnd Bfsn.\n\n\n(** ** Equivalence and Correctness of [bft] (returns whole path) **)\nSection Bft.\n\nInstance need_this_for_equations''' : WellFounded (bf_measure_list (Path)).\nProof.\n  unfold WellFounded. apply well_founded_bf_measure_list.\nDefined.\n\nEquations bf' (x :  (list Path) * (gr a b)) : RootPath.RTree by wf x (bf_measure_list Path) :=\n  bf' (nil, g) := nil;\n  bf' ((nil :: q'), g) := if (isEmpty g) then nil else GHC.Err.patternFailure;\n  bf' (((v :: t) :: q'), g) := let p:= v :: t in  if (isEmpty g) then nil else\n      match (match_ v g) as y return ((match_ v g = y) -> _) with\n                        | (Some c, g') => fun H : (match_ v g) = (Some c, g') => p :: (bf' ((q' ++ map (fun x => x :: p)  (suc' c)), g'))\n                        | (None, g') => fun H : (match_ v g) = (None, g') => ( bf' (q', g'))\n                        end (eq_refl).\nNext Obligation.\nunfold bf_measure_list. apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply H.\nDefined.\nNext Obligation.\nunfold bf_measure_list. apply lex2. symmetry. unfold natNodes_eq. eapply match_none_size. apply H. unfold list_length_lt.\nsimpl. omega.\nDefined.\n\nDefinition expand_bf' := \nfun x : list Path * gr a b =>\nlet (l, g) := x in\nmatch l with\n| nil => fun _ : gr a b => nil\n| p :: l0 =>\n    fun g0 : gr a b =>\n    match p with\n    | nil => fun (_ : list Path) (g1 : gr a b) =>  if (isEmpty g) then nil else patternFailure\n    | n :: l1 =>\n        fun (l2 : list Path) (g1 : gr a b) =>\n        if isEmpty g1\n        then nil\n        else\n         (let (m, g') as y return (match_ n g1 = y -> list (list Node)) := match_ n g1 in\n          match m as m0 return (match_ n g1 = (m0, g') -> list (list Node)) with\n          | Some c =>\n              fun _ : match_ n g1 = (Some c, g') =>\n              (n :: l1) :: bf' (l2 ++ map (fun x0 : Node => x0 :: n :: l1) (suc' c), g')\n          | None => fun _ : match_ n g1 = (None, g') => bf' (l2, g')\n          end) eq_refl\n    end l0 g0\nend g.\n\nLemma unfold_bf' : forall x, bf' x = expand_bf' x.\nProof.\n  intros. unfold expand_bf'. apply bf'_elim. reflexivity. reflexivity. reflexivity.\nQed.\n\n(*Need assumption that q is nonempty, or else queueGet is undefined (and this is OK, bft is called on nonempty queue*)\nLemma bf_bf'_equiv: forall g q,\n  bf' ((toList _ q), g) = bf q g.\nProof.\n  intros. remember (toList Path q) as l. remember (l, g) as x. generalize dependent q.\n  generalize dependent g. revert l.\n  induction (x) as [y IH] using (well_founded_induction (well_founded_bf_measure_list _)).\n  intros. destruct y. inversion Heqx; subst. clear Heqx. unfold bf.\n  rewrite unfold_bf'. simpl. \n   unfold deferredFix2 in *. unfold curry in *.\n  rewrite (deferredFix_eq_on _ (fun x => True) ( (bf_measure_queue (_)) )).\n  - simpl.  destruct (toList _ q) eqn : Q'. rewrite <- toList_queueEmpty in Q'. rewrite Q'. simpl.\n    reflexivity. assert (queueEmpty q = false). destruct (queueEmpty q) eqn : ?.\n    rewrite toList_queueEmpty in Heqb0. rewrite Heqb0 in Q'. inversion Q'.\n    reflexivity. rewrite H. simpl. destruct (isEmpty g) eqn : E.\n    destruct p. reflexivity. rewrite E. reflexivity. \n    destruct (queueGet q) eqn : G.\n    pose proof (toList_queueGet _ _ _ _ Q'). rewrite G in H0. simpl in H0. destruct H0. subst.\n    destruct p.\n    reflexivity. rewrite E. destruct (match_ n g) eqn : M. destruct m.\n    + unfold bf in IH. unfold deferredFix2 in IH. unfold curry in IH. erewrite IH. reflexivity.\n      apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply M. reflexivity.\n      rewrite toList_queuePutList . reflexivity.\n    + unfold bf in IH. unfold deferredFix2 in IH. unfold curry in IH. erewrite IH. reflexivity.\n      apply lex2. unfold natNodes_eq. symmetry. eapply match_none_size. apply M. unfold list_length_lt.\n      simpl. omega. reflexivity. reflexivity.\n  - apply well_founded_bf_measure_queue.\n  - unfold recurses_on. intros. unfold uncurry. destruct x. destruct (queueEmpty q0) eqn : QE. simpl.\n    reflexivity. simpl. destruct (isEmpty g1); simpl; try(reflexivity). destruct (queueGet q0) eqn : Q''.\n    destruct p; try(reflexivity). destruct (match_ n g1) eqn : M'. destruct m. rewrite H0.\n    reflexivity. auto. apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply M'.\n    rewrite H0. reflexivity. auto. apply lex2. unfold natNodes_eq. symmetry. eapply match_none_size.\n    apply M'. unfold queue_length_lt. destruct (toList _ q0) eqn : L. rewrite <- toList_queueEmpty in L.\n    rewrite L in QE. inversion QE.\n    pose proof (toList_queueGet _ _ _ _ L). rewrite Q'' in H1; simpl in H1; destruct H1; subst.\n    unfold list_length_lt. simpl. omega.\n  - auto.\nQed.\n\n(** ** Correctness of [bf] **)\n(*We want to prove that each is a shortest path. We need to know that the returned paths are valid and that\n  their length equals the result of [distance]*)\n\n\n(*Valid paths. Because we defined a path as the list between vertex u and v, we simply pull out the last\n  vertex from the list, verify that it is v, and the rest should be a path according to our previous definition*)\n(*Fixpoint valid_path (g: gr a b) (v u : Node) (l: list Node) : Prop :=\n  match l with\n  | \n*)\n(*\nDefinition valid_path (g: gr a b) (v u : Node) (l: list Node) : Prop :=\n  (u = v /\\ l = (v :: nil)) \\/ exists l', l = u :: l' ++ (v :: nil) /\\ path g v u l'.\n\nDefinition head {a} (l: list a) : option a :=\n  match l with\n  | nil => None\n  | x :: l => Some x\n  end.\n\nLemma valid_path_head: forall g u v l,\n  valid_path g v u l ->\n  head l = Some u.\nProof.\n  intros. unfold valid_path in H. destruct H; destruct_all. subst. reflexivity.\n  rewrite H. reflexivity.\nQed.\n\nDefinition All {A} (f: A -> Prop) (l: list A) :=\n  fold_right (fun x acc => f x /\\ acc) True l.\n\nLemma All_app: forall {A} (l1 l2: list A) f,\n  All f (l1 ++ l2) <-> All f l1 /\\ All f l2.\nProof.\n  intros. generalize dependent l2. induction l1; intros; simpl.\n  - split; intros. split. auto. assumption. destruct H. assumption.\n  - split; intros. split. destruct_all. split. assumption. apply IHl1 in H0. apply H0.\n    destruct_all. rewrite IHl1 in H0. apply H0. destruct_all. split. assumption.\n    rewrite IHl1. split; assumption.\nQed.\n\nLemma All_in: forall {A} (l: list A) f,\n  All f l <-> (forall x, In x l -> f x).\nProof.\n  intros. induction l; intros; split; intros.\n  - inversion H0.\n  - simpl. auto.\n  - simpl in *. destruct H. destruct H0. subst. auto. apply IHl; assumption.\n  - simpl. split. apply H. simpl. left. reflexivity. apply IHl. intros. apply H. right. assumption.\nQed.\n*)\nDefinition bf_state : Type := gr a b * list Path * list Path.\n\nDefinition bf_queue (s: bf_state) :=\n  match s with\n  | (_, q, _) => q\n  end.\n\nDefinition bf_graph (s: bf_state) :=\n  match s with\n  |(g, _ ,_) => g\n  end.\n\nDefinition bf_out (s: bf_state) :=\n  match s with\n  |(_, _, o) => o\n  end.\n\nInductive bf_step : bf_state -> bf_state -> Prop :=\n  | bf_find: forall g d v t vs c g',\n    isEmpty g = false ->\n    match_ v g = (Some c, g') ->\n    bf_step (g, (v :: t) :: vs, d) (g', (vs ++ map (fun x => x :: v :: t)  (suc' c)), d ++ ((v :: t) :: nil))\n  | bf_skip: forall g d v t vs g',\n    isEmpty g = false ->\n    match_ v g = (None, g') ->\n    bf_step (g, (v :: t) :: vs, d) (g', vs, d).\n\nDefinition bf_start (g : gr a b) (v: Graph.Node) : bf_state := (g, ((v :: nil) :: nil), nil).\n\n(*A valid state is any state that can be reached from the start state.*)\nInductive bf_valid : bf_state -> (gr a b) -> Node -> Prop :=\n  | v_bf_start : forall g v, vIn g v = true -> bf_valid (bf_start g v) g v\n  | v_bf_step : forall s s' v g, bf_valid s' g v -> bf_step s' s -> bf_valid s g v.\n\n(*It is much easier to reason about the valid paths by stepping through the function, since the\n  graph changes at every step, and we need to show that the paths are still valid in terms of the original grpah*)\nLemma bf_graph_subset: forall s v g,\n  bf_valid s g v ->\n  (forall v, vIn (bf_graph s) v = true -> vIn g v = true) /\\\n  (forall u v, eIn (bf_graph s) u v = true -> eIn g u v = true).\nProof.\n  intros. induction H; simpl.\n  - split; intros; assumption.\n  - inversion H0; subst; simpl in *. assert (M:=H2). apply match_remain_some in H2.\n    destruct H2. split. intros. rewrite H2 in H4. apply IHbf_valid. apply H4.\n    intros. rewrite H3 in H4. apply IHbf_valid. apply H4. apply match_remain_none in H2.\n    subst. apply IHbf_valid.\nQed.\n\nLemma queue_valid_paths: forall s v g v' l,\n  bf_valid s g v ->\n  In (v' :: l) (bf_queue s) ->\n  path' g v v' (v' :: l).\nProof.\n  intros. generalize dependent v'. revert l. induction H; intros.\n  - simpl in H0. destruct H0. inversion H0; subst. constructor. assumption. destruct H0.  \n  - inversion H0; subst; simpl in *.\n    apply in_app_or in H1. destruct H1. apply IHbf_valid. right. assumption.\n    rewrite in_map_iff in H1. destruct_all. inversion H1; subst.\n    eapply p_multi. apply IHbf_valid. left. reflexivity. unfold suc' in H4.\n    unfold Base.op_z2218U__ in H4. unfold Base.map in H4. rewrite snd_equiv in H4.\n    destruct c. destruct p. destruct p. rewrite context4l'_def in H4. \n    assert (eIn g0 v0 v' = true). apply H4. eapply bf_graph_subset. apply H.\n    simpl. assumption. apply H3. apply IHbf_valid. right. assumption.\nQed.\n\n\nLemma output_valid_paths: forall s v g v' l,\n  bf_valid s g v ->\n  In (v' :: l) (bf_out s) ->\n  path' g v v' (v' :: l).\nProof.\n  intros. induction H.\n  - simpl in H0. destruct H0.\n  - inversion H1; subst; simpl in *.\n    + apply in_app_or in H0. destruct H0. apply IHbf_valid. assumption.\n      pose proof (queue_valid_paths _ _ _ v' l H). apply H4. simpl. left. simpl in H0.\n      destruct H0; inversion H0. subst. reflexivity.\n    + apply IHbf_valid; assumption.\nQed.\n\n(*Now need to prove equivalence with the translated version**)\nEquations bf_tail (s: bf_state) : bf_state by wf (bf_queue s, bf_graph s) (bf_measure_list _) :=\n  bf_tail (g, nil, x) => (g, nil, x);\n  bf_tail (g, (nil :: q'), x) =>  (g, (nil :: q'), x);\n  bf_tail (g, (v :: t) :: vs, d) => if (isEmpty g) then  (g, (v :: t) :: vs, d) else\n      match (match_ v g) as y return ((match_ v g = y) -> _) with\n      | (Some c, g') => fun H: (match_ v g) = (Some c, g') => \n        bf_tail (g', (vs ++ map (fun x => x :: (v :: t))  (suc' c)), d ++ (v :: t) :: nil)\n      | (None, g') => fun H: (match_ v g) = (None, g') => bf_tail (g', vs, d)\n      end (eq_refl).\nNext Obligation.\nunfold bf_measure_list. apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply H.\nDefined.\nNext Obligation.\nunfold bf_measure_list. apply lex2. unfold natNodes_eq. symmetry. eapply match_none_size. apply H. unfold list_length_lt.\nsimpl. omega.\nDefined.\n\nDefinition expand_bf_tail := \nfun s : gr a b * list Path * list Path =>\nlet (p, l) := s in\n(let (g, l0) := p in\n fun l1 : list Path =>\n match l0 with\n | nil => fun l2 : list Path => (g, nil, l2)\n | p0 :: l2 =>\n     fun l3 : list Path =>\n     match p0 with\n     | nil => fun l4 l5 : list Path => (g, nil :: l4, l5)\n     | n :: l4 =>\n         fun l5 l6 : list Path =>\n         if isEmpty g\n         then (g, (n :: l4) :: l5, l6)\n         else\n          (let (m, g') as y return (match_ n g = y -> gr a b * list Path * list Path) := match_ n g in\n           match m as m0 return (match_ n g = (m0, g') -> gr a b * list Path * list Path) with\n           | Some c =>\n               fun _ : match_ n g = (Some c, g') =>\n               bf_tail (g', l5 ++ map (fun x : Node => x :: n :: l4) (suc' c), l6 ++ (n :: l4) :: nil)\n           | None => fun _ : match_ n g = (None, g') => bf_tail (g', l5, l6)\n           end) eq_refl\n     end l2 l3\n end l1) l.\n\nLemma unfold_bf_tail: forall s,\n  bf_tail s = expand_bf_tail s.\nProof.\n  intros. unfold expand_bf_tail. apply bf_tail_elim; intros; reflexivity.\nQed.\n\nLemma bf_multi_valid: forall s1 s2 g v,\n  bf_valid s1 g v ->\n  multi (bf_step) s1 s2 ->\n  bf_valid s2 g v.\nProof.\n  intros. induction H0. assumption. apply IHmulti. eapply v_bf_step. apply H. assumption.\nQed.\n\nLemma bf_tail_multi: forall s,\n  multi (bf_step) s (bf_tail s).\nProof.\n  intros. destruct s as[r d].\n  remember (snd r, fst r) as r'. generalize dependent r. revert d. \n  induction (r') using (well_founded_induction (well_founded_bf_measure_list (_))).\n  intros. destruct r' as [q g]. inversion Heqr'; subst. clear Heqr'. destruct r as [g q].\n  rewrite unfold_bf_tail. simpl. destruct q eqn : Q.\n  - apply multi_refl.\n  - destruct p as [|v j]. apply multi_refl. destruct (isEmpty g) eqn : E.\n    + apply multi_refl.\n    + destruct (match_ v g) eqn : M.  destruct m eqn : M'.\n      *  eapply multi_step. apply bf_find. assumption. apply M. eapply H. unfold bf_measure_list.\n         apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply M. simpl. reflexivity.\n      * eapply multi_step. apply bf_skip. assumption. apply M. eapply H. unfold bf_measure_list.\n        apply lex2. unfold natNodes_eq. assert (g = g0) by (eapply match_remain_none; apply M).\n        subst. eapply match_none_size. simpl.  apply M. \n        unfold list_length_lt. simpl. assert (length l < S(length l)) by omega. apply H0. simpl. \n        assert (g = g0) by (eapply match_remain_none; apply M). subst. reflexivity.\nQed.\n\nLemma bf_tail_equiv: forall x l,\n  (~In nil (snd x)) ->\n  bf_out (bf_tail (x, l)) = l ++ bf' (snd x, fst x).\nProof.\n  intros x. remember (snd x, fst x) as x'. generalize dependent x.\n  induction (x') using (well_founded_induction (well_founded_bf_measure_list _)).\n  intros. destruct x'; inversion Heqx'; subst; clear Heqx'.\n  rewrite unfold_bf'. rewrite unfold_bf_tail. simpl.  (* unfold expand_leveln'. *)\n  destruct x as [g q]. simpl. destruct q eqn : Q.\n  - simpl. rewrite app_nil_r. reflexivity.\n  - destruct l0 as [|v j]. simpl in H0. exfalso. apply H0. left. reflexivity. destruct (isEmpty g) eqn : G. \n    + simpl. rewrite app_nil_r. reflexivity.\n    + simpl.  destruct (match_ v g) eqn : M. destruct m.\n      * erewrite H. rewrite <- app_assoc. simpl. reflexivity. \n        unfold bf_measure_list. simpl. apply lex1.\n        unfold natNodes_lt. eapply match_decr_size. symmetry.  apply M. simpl. reflexivity.\n        intro. simpl in H1. apply in_app_or in H1. destruct H1. apply H0. right. assumption.\n        rewrite in_map_iff in H1. destruct_all. inversion H1.\n      * erewrite H. reflexivity. unfold bf_measure_list.  apply lex2.\n        unfold natNodes_eq. symmetry. eapply match_none_size. apply M. unfold list_length_lt. simpl. omega.\n        simpl. reflexivity. simpl in *. intro. apply H0. right. assumption.\nQed.\n\nLemma bft_tail_equiv: forall v g,\n  bf_out (bf_tail (bf_start g v)) = bft v g.\nProof.\n  intros. unfold bft. rewrite <- bf_bf'_equiv. rewrite bf_tail_equiv. simpl. reflexivity.\n  intro. simpl in H. destruct H. inversion H. auto.\nQed.\n\n(** ** Correctness of [bf] **)\n\n(*Need this as a helper: If v is not in the graph, this returns nil*)\nLemma bf_invalid_v: forall v (g: gr a b),\n  vIn g v = false ->\n  bft v g = nil.\nProof.\n  intros. unfold bft. rewrite <- bf_bf'_equiv. simpl. rewrite unfold_bf'. simpl.\n  destruct (isEmpty g). reflexivity. destruct (match_ v g) eqn : M. destruct m.\n  assert (vIn g v = true). eapply match_in. exists c. exists g0. assumption. rewrite H0 in H.\n  inversion H. rewrite unfold_bf'. simpl. reflexivity.\nQed. \n\n(*1. All paths in the output are valid*)\nTheorem bft_paths_valid: forall v (g: gr a b) v' l,\n  In (v' :: l) (bft v g) ->\n  path' g v v' (v' :: l).\nProof.\n  intros. destruct (vIn g v) eqn : V. rewrite <- bft_tail_equiv in H. eapply output_valid_paths in H.\n  apply H. eapply bf_multi_valid.\n  apply v_bf_start. assumption. apply bf_tail_multi. rewrite bf_invalid_v in H. simpl in H. inversion H.\n  assumption. \nQed.\n\n\nLemma zip_fst_map: forall {A B} (l: list A) (l' : list B) l'',\n   length l = length l' ->\n   map (fun x => Some (fst x)) (List.zip l l') = map (fun x => head x) (map (fun x => x :: l'') l). \nProof. \n  intros. generalize dependent l'. revert l''. induction l. intros.\n  simpl. reflexivity. intros.\n  simpl. destruct l'. simpl in H. omega. simpl in H. inversion H. eapply IHl in H1.\n  simpl. rewrite H1. reflexivity.\nQed. \n  \n(*Each path starts/ends with the corresponding vertex from [leveln]*)\n(*More specifically, if we find the head of each list from [bf], this gives us Some of the first element \n  of [leveln] (as long as we start with equivalent queues)*)\nLemma bf_vertex_order: forall (g: gr a b) q q',\n  map (fun x => Some (fst x)) q = map (fun x => head x) q' ->\n  map (fun x => Some (fst x)) (leveln' (q, g)) = map (fun x => head x) (bf' (q', g)).\nProof.\n  intros. remember (q, g) as x. generalize dependent q. revert g. revert q'. \n  induction (x) as [y IH] using (well_founded_induction (well_founded_bf_measure_list _)).\n  intros. destruct y. inversion Heqx. subst. clear Heqx. rewrite unfold_leveln'.\n  rewrite unfold_bf'. simpl. destruct q; simpl. simpl in H.\n  destruct q'. simpl. reflexivity. simpl in H. inversion H. destruct p.\n  destruct q'. simpl in H. inversion H. simpl in H. inversion H. \n  destruct (isEmpty g) eqn : E. simpl. destruct l. simpl. reflexivity.\n  rewrite E. simpl. reflexivity. destruct l. simpl in H1. inversion H1.\n  rewrite E. simpl in H1. symmetry in H1. inversion H1; subst. destruct (match_ n g) eqn : M. destruct m.\n  - simpl. erewrite IH. reflexivity. apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry.\n    apply M. 2 : { reflexivity. } rewrite map_app. rewrite map_app. rewrite H2.\n    assert (map (fun x : Node * Num.Int => Some (fst x)) (suci c (i + 1)%Z) =\n     map (fun x : list Node => head x) (map (fun x0 : Node => x0 :: n :: l) (suc' c))).\n    unfold suci. apply zip_fst_map.\n     rewrite repeat_length. rewrite length_equiv. reflexivity.\n    rewrite H0. reflexivity.\n  - erewrite IH. reflexivity. apply lex2. unfold natNodes_eq. symmetry. eapply match_none_size. apply M.\n    unfold list_length_lt. simpl. omega. apply H2. reflexivity.\nQed.\n\nLemma bft_vertex_order: forall (g: gr a b) v,\n  map (fun x => Some (fst x)) (level v g) = map (fun x => head x) (bft v g).\nProof.\n  intros. unfold level. unfold bft. rewrite <- leveln_leveln'_equiv.\n  rewrite <- bf_bf'_equiv. apply bf_vertex_order. simpl. reflexivity.\nQed. \n\n(*The length of each path is the value in leveln - 1*)\n(*We need the hypothesis from before (about the fst elements) so that we know that the queues actually\n  have the same vertices in the same order*)\nLemma bf_length: forall (g: gr a b) q q',\n  (~In nil q') ->\n  map (fun x => Some (fst x)) q = map (fun x => head x) q' ->\n  map snd q = map (fun x => (List.length x - 1)%Z) q' ->\n  map snd (leveln' (q, g)) = map (fun x => (List.length x - 1)%Z) (bf' (q', g)).\nProof.\n  intros. remember (q, g) as x. generalize dependent q. revert g. generalize dependent q'. \n  induction (x) as [y IH] using (well_founded_induction (well_founded_bf_measure_list _)).\n  intros. destruct y. inversion Heqx. subst. clear Heqx. rewrite unfold_leveln'.\n  rewrite unfold_bf'. simpl. destruct q; simpl. simpl in H0. destruct q'. reflexivity.\n  simpl in H1. inversion H1. destruct q'. inversion H1. simpl in H1. inversion H1.\n  destruct p. simpl in *. subst. destruct l. exfalso. apply H. left. reflexivity.\n  destruct (isEmpty g) eqn : E. reflexivity.\n  destruct (match_ n g) eqn : M. simpl in H0.  inversion H0. symmetry in H3. subst. \n  destruct m.\n  - rewrite M. simpl. erewrite IH. reflexivity. apply lex1. unfold natNodes_lt. eapply match_decr_size.\n    symmetry. apply M. intro. apply in_app_or in H2. destruct H2. apply H. right. assumption.\n    rewrite in_map_iff in H2. destruct_all. inversion H2. 3 : { reflexivity. } rewrite map_app.\n    rewrite map_app. unfold suci. rewrite (zip_fst_map _ _ (n :: l)). rewrite H5. reflexivity.\n    rewrite repeat_length. apply length_equiv. rewrite map_app. rewrite map_app. rewrite H4.\n    assert ( map snd (suci c (List.length (n :: l) - 1 + 1)%Z) = \n    map (fun x : list Node => (List.length x - 1)%Z) (map (fun x0 : Node => x0 :: n :: l) (suc' c))). {\n    unfold suci. assert ((List.length (n :: l) - 1 + 1)%Z = (List.length (n :: l))) by omega. rewrite H2. clear H2.\n    simpl. rewrite <- length_equiv. assert (forall {A} (l: list A) l' ,\n    map snd (List.zip l (repeat (List.length l') (length l))) =\n    map (fun x => ((List.length x - 1)%Z)) (map (fun x => x :: l') l)). { intros. generalize dependent l'.\n    induction l0; intros. simpl. reflexivity. simpl. rewrite IHl0.\n    assert (forall {B} (x : B) l, List.length (x :: l) = (List.length l + 1)%Z). { intros.\n    assert (Z.to_nat (List.length (x :: l1)) = Z.to_nat (List.length l1 + 1)). rewrite <- length_equiv.\n    rewrite Z2Nat.inj_add. rewrite <- length_equiv.  assert (Z.to_nat 1%Z = 1). unfold Z.to_nat. unfold Pos.to_nat.\n    unfold Pos.iter_op. reflexivity. rewrite H2. simpl. omega. unfold List.length. \n    rewrite len_acc_def. simpl. omega. omega. \n    apply Z2Nat.inj. unfold List.length. rewrite len_acc_def. simpl. apply Zle_0_pos .\n    assert (0 <= List.length l1)%Z. unfold List.length. rewrite len_acc_def. simpl. omega.\n    omega. apply H2. } rewrite H2. assert ((List.length l' + 1 - 1)%Z = List.length l') by omega. rewrite H3.\n    reflexivity. } apply H2. } rewrite H2. reflexivity. \n  - rewrite M. erewrite IH. reflexivity. apply lex2. unfold natNodes_eq. symmetry. eapply match_none_size.\n    apply M. unfold list_length_lt. simpl. omega. intro. apply H. right. assumption.\n    apply H5. apply H4. reflexivity.\nQed.\n\nLemma bft_length: forall (g: gr a b) v,\n  map snd (level v g) = map (fun x => (List.length x - 1)%Z) (bft v g).\nProof.\n  intros. unfold level. unfold bft. rewrite <- leveln_leveln'_equiv.\n  rewrite <- bf_bf'_equiv. apply bf_length. \n  - intro. simpl in H. destruct H. inversion H. auto.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(*The big result: that [bft] finds shortest paths. We use List.zip to preserve order*)\nTheorem bft_shortest_paths: forall (g: gr a b) v p d u,\n  In (p, (u, d)) (List.zip (bft v g) (level v g)) ->\n  shortest_path g v u p /\\ length p = Z.to_nat d + 1.\nProof.\n  intros. pose proof (bft_length g v).\n  pose proof (bft_vertex_order g v). symmetry in H0. symmetry in H1.\n  pose proof (in_zip_map (bft v g) (level v g) p (u,d) _ _ H H0).\n  pose proof (in_zip_map (bft v g) (level v g) p (u,d) _ _ H H1).\n  simpl in H2. simpl in H3. unfold hd_error in H3. destruct p. inversion H3.\n  inversion H3; subst. \n  assert ((List.length (u :: p) -1)%Z = Z.of_nat (length p)). {\n  unfold List.length at 1. rewrite len_acc_def.\n  assert (forall n, (Num.fromInteger 0 + Z.of_nat n)%Z = Z.of_nat n). intros.\n  simpl. reflexivity. rewrite H2. clear H2.\n  assert (length (u :: p) = (1 + length p)). simpl. reflexivity. rewrite H2. clear H2.\n  rewrite Nat2Z.inj_add. assert (Z.of_nat 1 = 1%Z). simpl. reflexivity. rewrite H2.\n  assert (forall z1 z2, (z1 + z2 - z1)%Z = z2%Z). intros. omega. rewrite H4. reflexivity. }\n  assert (V': valid (bfs_tail (start g v)) g v). destruct (vIn g v) eqn : V.\n  eapply multi_valid. apply v_start. apply V. apply bfs_tail_multi. \n  apply bf_invalid_v in V. rewrite V in H. inversion H.\n  split.\n  - apply zip_in in H. destruct_all. pose proof (level_finds_shortest_path v g u).\n    rewrite <- level_tail_equiv in H5. rewrite <- level_tail_equiv in H4. \n      replace (find_dist_list (get_dists (bfs_tail (start g v)))) with\n      (find_dist (bfs_tail (start g v))) in H5 by (unfold find_dist_list; reflexivity).\n    destruct (find_dist (bfs_tail (start g v)) u) eqn : F.\n    + rewrite find_dist_in in F.\n      pose proof (no_dup_level v g). rewrite <- level_tail_equiv in H6.\n      assert ((List.length (u :: p) -1)%Z = Z.of_nat n).\n      eapply NoDup_pairs in H6. apply H6. apply H4. apply F.\n      symmetry in H5. apply distance_some in H5. destruct H5 as [l].\n      destruct_all.\n      eapply shortest_path_of_length. apply H5. apply bft_paths_valid.\n      assumption. rewrite H8.\n      assert (forall z1 z2 z3, (z1 - z2)%Z = z3%Z -> z1 = (z3 + z2)%Z). intros. omega.\n      assert (List.length (u :: p) = (Z.of_nat n + 1)%Z). apply H9. assumption.\n      rewrite length_equiv. rewrite H10. rewrite Z2Nat.inj_add. rewrite Nat2Z.id.\n      simpl. unfold Pos.to_nat. simpl. reflexivity. omega. omega. apply V'.\n    + symmetry in H5. pose proof (output_iff_reachable (bfs_tail (start g v)) g v u).\n      unfold distance in H5. assert (exists l, path' g v u l). apply H6.\n      assumption. apply bfs_tail_done. rewrite in_map_iff. exists (u, (List.length (u :: p) - 1)%Z).\n      simpl. solve_assume. rewrite distance_none in H5. destruct_all. exfalso; apply (H5 x); assumption.\n  - rewrite H2. rewrite Nat2Z.id. simpl. omega.\nQed. \n\nEnd Bft. \n\n(** Labelled Paths (lbf) **)\nSection Lbft.\n\nInstance need_this_for_equations'''' : WellFounded (bf_measure_list (LPath b)).\nProof.\n  unfold WellFounded. apply well_founded_bf_measure_list.\nDefined.\n\n\nEquations lbf' (x :  (list (LPath b)) * (gr a b)) : (RootPath.LRTree b) by wf x (bf_measure_list (LPath b)) :=\n  lbf' (nil, g) := nil;\n  lbf' ((LP nil :: q'), g) := if (isEmpty g) then nil else GHC.Err.patternFailure;\n  lbf' ((LP ((v, l) :: t) :: q'), g) := let p:= (v, l) :: t in  if (isEmpty g) then nil else\n      match (match_ v g) as y return ((match_ v g = y) -> _) with\n                        | (Some c, g') => fun H : (match_ v g) = (Some c, g') => LP p :: (lbf' ((q' ++ map (fun v' => LP (v' :: p))  (lsuc' c)), g'))\n                        | (None, g') => fun H : (match_ v g) = (None, g') => (lbf' (q', g'))\n                        end (eq_refl).\nNext Obligation.\nunfold bf_measure_list. apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply H.\nDefined.\nNext Obligation.\nunfold bf_measure_list. apply lex2. symmetry. unfold natNodes_eq. eapply match_none_size. apply H. unfold list_length_lt.\nsimpl. omega.\nDefined.\n\nDefinition expand_lbf' :=\nfun x : list (LPath b) * gr a b =>\nlet (l, g) := x in\nmatch l with\n| nil => fun _ : gr a b => nil\n| l0 :: l1 =>\n    fun g0 : gr a b =>\n    match l0 with\n    | LP unLPath =>\n        fun (l2 : list (LPath b)) (g1 : gr a b) =>\n        match unLPath with\n        | nil => fun (_ : list (LPath b)) (g2 : gr a b) => if isEmpty g2 then nil else patternFailure\n        | l3 :: l4 =>\n            fun (l5 : list (LPath b)) (g2 : gr a b) =>\n            (let (n, b0) := l3 in\n             fun (l6 : list (LNode b)) (l7 : list (LPath b)) (g3 : gr a b) =>\n             if isEmpty g3\n             then nil\n             else\n              (let (m, g') as y return (match_ n g3 = y -> list (LPath b)) := match_ n g3 in\n               match m as m0 return (match_ n g3 = (m0, g') -> list (LPath b)) with\n               | Some c =>\n                   fun _ : match_ n g3 = (Some c, g') =>\n                   LP ((n, b0) :: l6)\n                   :: lbf' (l7 ++ map (fun v' : Node * b => LP (v' :: (n, b0) :: l6)) (lsuc' c), g')\n               | None => fun _ : match_ n g3 = (None, g') => lbf' (l7, g')\n               end) eq_refl) l4 l5 g2\n        end l2 g1\n    end l1 g0\nend g. \n\n\nLemma unfold_lbf' : forall x, lbf' x = expand_lbf' x.\nProof.\n  intros. unfold expand_lbf'. apply lbf'_elim. reflexivity. reflexivity. reflexivity.\nQed.\n\n(*Need assumption that q is nonempty, or else queueGet is undefined (and this is OK, bft is called on nonempty queue*)\nLemma lbf_lbf'_equiv: forall g q,\n  lbf' ((toList _ q), g) = lbf q g.\nProof.\n  intros. remember (toList _ q) as l. remember (l, g) as x. generalize dependent q.\n  generalize dependent g. revert l.\n  induction (x) as [y IH] using (well_founded_induction (well_founded_bf_measure_list _)).\n  intros. destruct y. inversion Heqx; subst. clear Heqx. unfold lbf.\n  rewrite unfold_lbf'. simpl. \n   unfold deferredFix2 in *. unfold curry in *.\n  rewrite (deferredFix_eq_on _ (fun x => True) ( (bf_measure_queue (_)) )).\n  - simpl.  destruct (toList _ q) eqn : Q'. rewrite <- toList_queueEmpty in Q'. rewrite Q'. simpl.\n    reflexivity. assert (queueEmpty q = false). destruct (queueEmpty q) eqn : ?.\n    rewrite toList_queueEmpty in Heqb0. rewrite Heqb0 in Q'. inversion Q'.\n    reflexivity. rewrite H. simpl. destruct (isEmpty g) eqn : E.\n    destruct l. destruct unLPath. rewrite E. reflexivity. destruct l. rewrite E. reflexivity. \n    destruct (queueGet q) eqn : G.\n    pose proof (toList_queueGet _ _ _ _ Q'). rewrite G in H0. simpl in H0. destruct H0. subst.\n    destruct l. destruct unLPath. rewrite E. reflexivity. destruct l. rewrite E.\n    destruct (match_ n g) eqn : M. destruct m.\n    + unfold lbf in IH. unfold deferredFix2 in IH. unfold curry in IH. erewrite IH. reflexivity.\n      apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply M. reflexivity.\n      rewrite toList_queuePutList . reflexivity.\n    + unfold lbf in IH. unfold deferredFix2 in IH. unfold curry in IH. erewrite IH. reflexivity.\n      apply lex2. unfold natNodes_eq. symmetry. eapply match_none_size. apply M. unfold list_length_lt.\n      simpl. omega. reflexivity. reflexivity.\n  - apply well_founded_bf_measure_queue.\n  - unfold recurses_on. intros. unfold uncurry. destruct x. destruct (queueEmpty q0) eqn : QE. simpl.\n    reflexivity. simpl. destruct (isEmpty g1); simpl; try(reflexivity). destruct (queueGet q0) eqn : Q''.\n    destruct l; try(reflexivity). destruct unLPath; try reflexivity. destruct l.\n    destruct (match_ n g1) eqn : M'. destruct m. rewrite H0.\n    reflexivity. auto. apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply M'.\n    rewrite H0. reflexivity. auto. apply lex2. unfold natNodes_eq. symmetry. eapply match_none_size.\n    apply M'. unfold queue_length_lt. destruct (toList _ q0) eqn : L. rewrite <- toList_queueEmpty in L.\n    rewrite L in QE. inversion QE.\n    pose proof (toList_queueGet _ _ _ _ L). rewrite Q'' in H1; simpl in H1; destruct H1; subst.\n    unfold list_length_lt. simpl. omega.\n  - auto.\nQed.\n\n(** ** Correctness of [lbf] **)\n\n(*The correctness property is simple: [lb] is the same as [bf] when we remove the labels*)\n\nDefinition unlabel_path (l : LPath b) : Path := \n  match l with\n  | LP l' => map fst l'\n  end.\n\nDefinition unlabel_tree (l : list (LPath b)) : list (Path) :=\n  map unlabel_path l.\n\nLemma unlabel_app: forall l1 l2, unlabel_tree (l1 ++ l2) = unlabel_tree l1 ++ unlabel_tree l2.\nProof.\n  intros. unfold unlabel_tree. rewrite map_app. reflexivity.\nQed. \n\nLemma lbf_unlabel: forall g q q',\n  ~In nil q' ->\n  unlabel_tree q = q' ->\n  unlabel_tree (lbf' (q, g)) = bf' (q', g).\nProof.\n  intros. remember (q, g) as x. generalize dependent q. generalize dependent q'. revert g.\n  induction (x) as [y IH] using (well_founded_induction (well_founded_bf_measure_list _)).\n  intros. destruct y. inversion Heqx. subst. clear Heqx. rewrite unfold_lbf'.\n  rewrite unfold_bf'. simpl. destruct q. simpl. reflexivity.\n  simpl. destruct l. simpl. destruct unLPath. simpl. simpl in H. exfalso. apply H.\n  left. reflexivity. destruct l. simpl. destruct (isEmpty g) eqn : E. reflexivity.\n  destruct (match_ n g) eqn : M. destruct m.\n  - simpl. erewrite IH. reflexivity. apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry.\n    apply M. intro. simpl in H. apply in_app_or in H0. destruct H0.\n    apply H. right. assumption. rewrite in_map_iff in H0. destruct_all. inversion H0.\n    2: { reflexivity. } simpl. rewrite unlabel_app. \n    assert (unlabel_tree (map (fun v' : Node * b => LP (v' :: (n, b0) :: unLPath)) (lsuc' c)) = \n    map (fun x0 : Node => x0 :: n :: map fst unLPath) (suc' c)). unfold unlabel_tree.\n    rewrite map_map. simpl. unfold lsuc'. unfold suc'. unfold Base.op_z2218U__.\n    unfold Base.map. unfold Graph.flip2. unfold Tuple.snd. induction (context4l' c).\n    simpl. reflexivity. simpl. rewrite IHa0. destruct a0. simpl. reflexivity. rewrite H0. reflexivity.\n  - erewrite IH. reflexivity. apply lex2. unfold natNodes_eq. symmetry. eapply match_none_size.\n    apply M. unfold list_length_lt. simpl. omega. intro. apply H. simpl. right. assumption.\n    reflexivity. reflexivity.\nQed.\n\n(*For some reason, if the vertex v has no edges, [lbft] returns a list of nil instead of nil, so\n  the property we want only holds if v has at least one outgoing edge*)\n\nLemma out_fst: forall (g: gr a b) v n m b l,\n  out g v = (n, m, b) :: l -> v = n.\nProof.\n  intros. unfold out in H. unfold Base.map in H. \n  destruct (context4l g v). simpl in H. inversion H. simpl in H. destruct p. inversion H. subst.\n  reflexivity.\nQed.\n\nTheorem lbft_label: forall (g: gr a b) v,\n  out g v <> nil ->\n  unlabel_tree (lbft v g) = bft v g.\nProof.\n  intros. unfold lbft. unfold bft. destruct (out g v) eqn : O. contradiction. destruct l.\n  destruct p. rewrite <- lbf_lbf'_equiv. rewrite <- bf_bf'_equiv. apply lbf_unlabel.\n  intro. simpl in H0. destruct H0. inversion H0. auto. simpl. apply out_fst in O. subst. reflexivity.\nQed. \n\nEnd Lbft.\n\n(** Correctness of [bfen] (BFS with predecessors **)\nSection Bfen.\n\nInstance need_this_for_equations''''' : WellFounded (bf_measure_list (Node * Node)).\nProof.\n  unfold WellFounded. apply well_founded_bf_measure_list.\nDefined.\n\nEquations bfenInternal' (x: (list (Node * Node) * (gr a b))) : list (Node * Node) by wf x (bf_measure_list (Node * Node)) :=\n  bfenInternal' (nil, g) := nil;\n  bfenInternal' ((u,v) :: vs, g) := if (isEmpty g) then nil else\n                                match (match_ v g) as y return ((match_ v g = y) -> _ ) with\n                                | (Some c, g') => fun H : (match_ v g) = (Some c, g') => (u,v) :: bfenInternal' (vs ++ (outU c), g')\n                                | (None, g') => fun H: (match_ v g) = (None, g') => bfenInternal' (vs, g')\n                                 end (eq_refl).\nNext Obligation.\nunfold bf_measure_list. apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply H.\nDefined.\nNext Obligation.\nunfold bf_measure_list. apply lex2. symmetry. unfold natNodes_eq. eapply match_none_size. apply H. unfold list_length_lt.\nsimpl. omega.\nDefined.\n\nDefinition expand_bfenInternal' := \nfun x : list (Node * Node) * gr a b =>\nlet (l, g) := x in\nmatch l with\n| nil => fun _ : gr a b => nil\n| p :: l0 =>\n    fun g0 : gr a b =>\n    (let (n, n0) := p in\n     fun (l1 : list (Node * Node)) (g1 : gr a b) =>\n     if isEmpty g1\n     then nil\n     else\n      (let (m, g') as y return (match_ n0 g1 = y -> list (Node * Node)) := match_ n0 g1 in\n       match m as m0 return (match_ n0 g1 = (m0, g') -> list (Node * Node)) with\n       | Some c => fun _ : match_ n0 g1 = (Some c, g') => (n, n0) :: bfenInternal' (l1 ++ outU c, g')\n       | None => fun _ : match_ n0 g1 = (None, g') => bfenInternal' (l1, g')\n       end) eq_refl) l0 g0\nend g.\n\nLemma unfold_bfenInternal': forall x,\n  bfenInternal' x = expand_bfenInternal' x.\nProof.\n  intros. unfold expand_bfenInternal'. apply bfenInternal'_elim. reflexivity. reflexivity.\nQed.\n\nLemma bfenInternal_bfenInternal'_equiv: forall g q,\n  bfenInternal' (toList _ q, g) = bfenInternal q g.\nProof.\n  intros. remember (q, g) as x. generalize dependent q. revert g. \n  induction (x) as [y IH] using (well_founded_induction (well_founded_bf_measure_queue _)).\n  intros. destruct y. inversion Heqx; subst. clear Heqx. unfold bfenInternal.\n  rewrite unfold_bfenInternal'. simpl. \n   unfold deferredFix2 in *. unfold curry in *.\n  rewrite (deferredFix_eq_on _ (fun x => True) ( (bf_measure_queue (_)) )).\n  - simpl. destruct (toList _ q) eqn : Q. rewrite <- toList_queueEmpty in Q. rewrite Q. simpl.\n    destruct (queueGet q) eqn : G. rewrite G. destruct p. reflexivity. destruct p.\n    destruct (queueGet q) eqn : QG. rewrite QG. pose proof (toList_queueGet _ _ _ _ Q).\n    rewrite QG in H. simpl in H. destruct H. subst.\n    destruct (queueEmpty q) eqn : E. rewrite toList_queueEmpty in E. rewrite E in Q. inversion Q.\n    rewrite E. clear E. destruct (isEmpty g) eqn : E. simpl. reflexivity.\n    simpl. destruct (match_ n0 g) eqn : M. destruct m.\n    + unfold bfenInternal in IH. unfold deferredFix2 in IH. unfold curry in IH. erewrite <- IH.\n      rewrite toList_queuePutList. reflexivity. 2: { reflexivity. } apply lex1.\n      unfold natNodes_lt. eapply match_decr_size. symmetry. apply M.\n    + unfold bfenInternal in IH. unfold deferredFix2 in IH. unfold curry in IH. erewrite IH. reflexivity.\n      2: { reflexivity. } apply lex2. unfold natNodes_eq. symmetry. eapply match_none_size. apply M.\n      unfold queue_length_lt. rewrite Q. unfold list_length_lt. simpl. omega.\n  - apply well_founded_bf_measure_queue.\n  - unfold recurses_on. intros. unfold uncurry. destruct x. destruct (queueGet q0) eqn : Q.\n    destruct e. destruct (queueEmpty q0) eqn : E. simpl. reflexivity. destruct (isEmpty g1) eqn : G.\n    simpl. reflexivity. simpl. destruct (match_ n0 g1) eqn : M'. destruct m.\n    rewrite H0. reflexivity. auto. apply lex1. unfold natNodes_lt. eapply match_decr_size.\n    symmetry. apply M'. apply H0. auto. apply lex2. unfold natNodes_eq. symmetry.\n    eapply match_none_size. apply M'. unfold queue_length_lt. unfold list_length_lt.\n    destruct (toList _ q0) eqn : L. rewrite <- toList_queueEmpty in L. rewrite L in E. inversion E.\n    pose proof (toList_queueGet _ _ _ _ L). rewrite Q in H1. simpl in H1. destruct H1. destruct e. inversion H1; subst. simpl. omega.\n  - auto.\nQed.\n\nDefinition first_two (l: list Node) : option (Node * Node) :=\n  match l with\n  | x :: y :: t => Some (y,x)\n  | _ => None\n  end.\n\n(*Maybe - prove this claim for suitably long queues, manually go through 1 iteration in other, prove that\n  if we take 1st off of bf' then get (v,v) cons that*)\n\nLemma bfenInternal_pred: forall g q q',\n  (forall x, In x q -> first_two x <> None) ->\n  map first_two q = map Some q' ->\n  map first_two (bf' (q, g)) = map Some (bfenInternal' (q', g)).\nProof.\n  intros. remember (q, g) as x. generalize dependent q. revert q'. revert g. \n  induction (x) as [y IH] using (well_founded_induction (well_founded_bf_measure_list _)).\n  intros. destruct y. inversion Heqx. subst. clear Heqx.\n  rewrite unfold_bfenInternal'. rewrite unfold_bf'. simpl. destruct q; destruct q'.\n  reflexivity. simpl in H0. inversion H0. simpl in H0. inversion H0. simpl in H0. inversion H0.\n  destruct l. inversion H2. simpl in H2. destruct l. inversion H2. simpl in H2. inversion H2.\n  destruct p. inversion H4; subst. clear H4. \n  destruct (isEmpty g) eqn : E. reflexivity. destruct (match_ n2 g) eqn : M.\n  destruct m.\n  - simpl. erewrite IH. reflexivity. apply lex1. unfold natNodes_lt. eapply match_decr_size. symmetry. apply M.\n    3: { reflexivity. } intros. intro. apply in_app_or in H1. destruct H1.\n    apply (H x). right. assumption. assumption. apply in_map_iff in H1. destruct H1. destruct H1. subst.\n    simpl in H4. inversion H4. rewrite map_app. rewrite map_app.\n    rewrite H3. unfold outU. unfold out'. unfold suc'. destruct c.\n    destruct p. destruct p. unfold Base.map. unfold Base.op_z2218U__.\n    rewrite snd_equiv. rewrite map_map. rewrite map_map. rewrite map_map. rewrite map_map.\n    simpl. rewrite filter_equiv. unfold Base.op_z2218U__ . rewrite snd_equiv.\n    assert (map (fun x : b * Node => Some (n2, snd x)) (a0 ++ filter (fun x : b * Node => Base.op_zeze__ (snd x) n) a2) =\n    map (fun x : b * Node => Some (toEdge (let '(l0, w) := x in (n, w, l0))))\n  (a0 ++ filter (fun x : b * Node => Base.op_zeze__ (snd x) n) a2)).\n    induction (a0 ++ filter (fun x : b * Node => Base.op_zeze__ (snd x) n) a2); simpl.\n    reflexivity. rewrite IHl0. destruct a3. simpl. eapply match_context in M. destruct M. subst. reflexivity.\n    rewrite H1. reflexivity.\n  - erewrite IH. reflexivity. apply lex2. unfold natNodes_eq. symmetry. eapply match_none_size. apply M.\n    unfold list_length_lt. simpl. omega. 3: { reflexivity. } intros. apply H. right. assumption.\n    assumption.\nQed.\n\n(*The first element in the list is (v,v), but the rest are the first two elements in the path\n  returned by [bft]*)\nTheorem bfe_pred: forall v (g: gr a b) h t,\n  vIn g v = true ->\n  bft v g = h :: t ->\n  map Some (bfe v g) = Some (v,v) :: map first_two t.\nProof.\n  intros. unfold bfe. unfold bft in H0. unfold bfen.\n  rewrite <- bf_bf'_equiv in H0. rewrite <- bfenInternal_bfenInternal'_equiv.\n  simpl. rewrite unfold_bfenInternal'. rewrite unfold_bf' in H0. simpl in *.\n  destruct (isEmpty g) eqn : E. inversion H0. destruct (match_ v g) eqn : M.\n  destruct m.\n  - simpl in *. inversion H0; subst. erewrite bfenInternal_pred. reflexivity.\n    intros. rewrite in_map_iff in H1. destruct_all. intro. subst. simpl in H3. inversion H3.\n    unfold suc'. unfold outU. unfold out'. destruct c. destruct p. destruct p.\n    unfold Base.map. rewrite snd_equiv. rewrite map_map. rewrite map_map. rewrite map_map.\n    unfold Base.op_z2218U__ . eapply match_context in M. destruct M. subst.\n    induction (context4l' (a2, n, a1, a0)). simpl. reflexivity. simpl. rewrite IHa3. simpl.\n    destruct a3. simpl. reflexivity.\n  - epose proof (match_in g v). destruct H1. apply H2 in H. destruct_all. rewrite M in H.  inversion H.\nQed.\n\nEnd Bfen.\n\nEnd Ind. ", "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/graph/theories/BFSProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6516767816320022}}
{"text": "Require Import Coq.Arith.EqNat.\nRequire Import Coq.Relations.Relations.\nRequire Import Coq.Sorting.Permutation.\n\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Integers.\n\nRequire Import VST.msl.Coqlib2.\nRequire Export VST.msl.eq_dec.\nRequire Export Lia.\n\nLemma max_two_power_nat: forall n1 n2, Z.max (two_power_nat n1) (two_power_nat n2) = two_power_nat (Nat.max n1 n2).\nProof.\n  intros.\n  rewrite !two_power_nat_two_p.\n  pose proof Zle_0_nat n1; pose proof Zle_0_nat n2.\n  rewrite Nat2Z.inj_max.\n  forget (Z.of_nat n1) as m1; forget (Z.of_nat n2) as m2.\n  destruct (Z_le_dec m1 m2).\n  + rewrite (Z.max_r m1 m2) by lia.\n    apply Z.max_r.\n    apply two_p_monotone; lia.\n  + rewrite (Z.max_l m1 m2) by lia.\n    apply Z.max_l.\n    apply two_p_monotone; lia.\nQed.\n\nLemma Z_max_two_p: forall m1 m2, (exists n, m1 = two_power_nat n) -> (exists n, m2 = two_power_nat n) -> (exists n, Z.max m1 m2 = two_power_nat n).\nProof.\n  intros ? ? [? ?] [? ?].\n  subst.\n  rewrite max_two_power_nat.\n  eexists; reflexivity.\nQed.\n\nLemma power_nat_divide: forall n m, two_power_nat n <= two_power_nat m -> Z.divide (two_power_nat n) (two_power_nat m).\nProof.\n  intros.\n  repeat rewrite two_power_nat_two_p in *.\n  unfold Z.divide.\n  exists (two_p (Z.of_nat m - Z.of_nat n)).\n  assert ((Z.of_nat m) = (Z.of_nat m - Z.of_nat n) + Z.of_nat n) by lia.\n  rewrite H0 at 1.\n  assert (Z.of_nat m >= 0) by lia.\n  assert (Z.of_nat n >= 0) by lia.\n  assert (Z.of_nat n <= Z.of_nat m).\n    destruct (Z_le_gt_dec (Z.of_nat n) (Z.of_nat m)).\n    exact l.\n    assert (Z.of_nat m < Z.of_nat n) by lia.\n    assert (two_p (Z.of_nat m) < two_p (Z.of_nat n)) by (apply two_p_monotone_strict; lia).\n    lia.\n  apply (two_p_is_exp (Z.of_nat m - Z.of_nat n) (Z.of_nat n)); lia.\nQed.\n\nLemma power_nat_divide_ge: forall n m: Z,\n  (exists N, n = two_power_nat N) ->\n  (exists M, m = two_power_nat M) ->\n  (n >= m <-> (m | n)).\nProof.\n  intros.\n  destruct H, H0.\n  split; intros.\n  + subst.\n    apply power_nat_divide.\n    lia.\n  + destruct H1 as [k ?].\n    rewrite H1.\n    pose proof two_power_nat_pos x0.\n    pose proof two_power_nat_pos x.\n    assert (k > 0).\n    {\n      eapply Zmult_gt_0_reg_l.\n      + exact H2.\n      + rewrite <- H0, Z.mul_comm; lia.\n    } \n    rewrite <- (Z.mul_1_l m) at 2.\n    apply Zmult_ge_compat_r; lia.\nQed.\n\nLemma power_nat_divide_le: forall n m: Z,\n  (exists N, n = two_power_nat N) ->\n  (exists M, m = two_power_nat M) ->\n  (m <= n <-> (m | n)).\nProof.\n  intros.\n  rewrite <- power_nat_divide_ge; auto.\n  lia.\nQed.\n\nLemma two_p_max_divide: forall m1 m2 m, (exists n, m1 = two_power_nat n) -> (exists n, m2 = two_power_nat n) -> ((Z.max m1 m2 | m) <-> (m1 | m) /\\ (m2 | m)).\nProof.\n  intros.\n  destruct (Z_le_dec m1 m2).\n  + rewrite Z.max_r by lia.\n    rewrite power_nat_divide_le in l by auto.\n    pose proof Z.divide_trans m1 m2 m.\n    tauto.\n  + rewrite Z.max_l by lia.\n    assert (m2 <= m1) by lia.\n    rewrite power_nat_divide_le in H1 by auto.\n    pose proof Z.divide_trans m2 m1 m.\n    tauto.\nQed.\n\nLemma two_p_max_1: forall m1 m2, (exists n, m1 = two_power_nat n) -> (exists n, m2 = two_power_nat n) -> (Z.max m1 m2 = 1 <-> m1 = 1 /\\ m2 = 1).\nProof.\n  assert (forall x, (exists n : nat, x = two_power_nat n) -> (x = 1 <-> (x | 1))).\n  + intros.\n    split; intros.\n    - subst.\n      exists 1; auto.\n    - rewrite <- power_nat_divide_le in H0 by (auto; exists 0%nat; auto).\n      destruct H as [n ?]; subst x.\n      pose proof two_power_nat_pos n.\n      lia.\n  + intros m1 m2 Hm1 Hm2.\n    pose proof Z_max_two_p _ _ Hm1 Hm2 as Hmax.\n    rewrite (H _ Hm1), (H _ Hm2), (H _ Hmax).\n    apply two_p_max_divide; auto.\nQed.\n\nLemma two_power_nat_0: forall x, (exists n, x = two_power_nat n) -> x <> 0.\nProof.\n  intros.\n  destruct H.\n  pose proof two_power_nat_pos x0.\n  lia.\nQed.\n\nHint Rewrite andb_true_iff: align.\nHint Rewrite <- Zle_is_le_bool: align.\nHint Rewrite Z.eqb_eq: align.\nHint Rewrite power_nat_divide_le using (auto with align): align.\nHint Rewrite Z.mod_divide using (apply two_power_nat_0; auto with align): align.\nHint Rewrite two_p_max_divide using (auto with align): align.\nHint Rewrite two_p_max_1 using (auto with align): align.\n#[export] Hint Resolve Z_max_two_p: align.\n\nLemma Z_of_nat_ge_O: forall n, Z.of_nat n >= 0.\nProof. intros.\nchange 0 with (Z.of_nat O).\napply inj_ge. clear; lia.\nQed.\n\nLemma nth_error_nth:\n  forall A (al: list A) (z: A) i, (i < length al)%nat -> nth_error al i = Some (nth i al z).\nProof.\nintros. revert al H; induction i; destruct al; simpl; intros; auto; try lia.\napply IHi. lia.\nQed.\n\nLemma nat_of_Z_eq: forall i, Z.to_nat (Z_of_nat i) = i.\nProof.\nintros.\napply inj_eq_rev.\nrewrite Nat2Z.id; auto.\nQed.\n\nLemma nth_error_length:\n  forall {A} i (l: list A), nth_error l i = None <-> (i >= length l)%nat.\nProof.\ninduction i; destruct l; simpl; intuition.\ninv H.\ninv H.\nrewrite IHi in H. lia.\nrewrite IHi. lia.\nQed.\n\nLemma prop_unext: forall P Q: Prop, P=Q -> (P<->Q).\nProof. intros. subst; split; auto. Qed.\n\nLemma list_norepet_In_In: forall {K X} a x y (l:list (K*X)),\n  list_norepet (map (@fst K X) l) -> In (a, x) l -> In (a, y) l -> x = y.\nProof.\n  induction l; intros N Ix Iy.\n   - inv Ix.\n   - simpl in N; inv N.\n     destruct Ix.\n     + subst.\n       simpl in Iy; destruct Iy as [|Iy]; [congruence|].\n       exfalso; apply (in_map (@fst K X)) in Iy; tauto.\n     + simpl in Iy; destruct Iy as [|Iy].\n       subst. exfalso; apply (in_map (@fst K X)) in H; tauto.\n       apply IHl; auto.\nQed.\n\nInductive sublist {A} : list A -> list A -> Prop :=\n| sublist_nil : sublist nil nil\n| sublist_cons a l1 l2 : sublist l1 l2 -> sublist (a :: l1) (a :: l2)\n| sublist_drop a l1 l2 : sublist l1 l2 -> sublist l1 (a :: l2).\n\nLemma sublist_In {A} (a : A) l1 l2 : sublist l1 l2 -> In a l1 -> In a l2.\nProof.\n  intros S; induction S; intros I.\n  - inversion I.\n  - simpl in I; destruct I.\n    subst; left; auto.\n    right; auto.\n  - right; auto.\nQed.\n\nLemma sublist_norepet {A} (l1 l2 : list A) : sublist l1 l2 -> list_norepet l2 -> list_norepet l1.\nProof.\n  intros S; induction S; intros N; auto.\n  - inversion N; subst; constructor; auto.\n    pose proof sublist_In a l1 l2; auto.\n  - inversion N; auto.\nQed.\n\nRequire Import Coq.Sets.Ensembles.\n\nDefinition Ensemble_join {A} (X Y Z: Ensemble A): Prop :=\n  (forall a, Z a <-> X a \\/ Y a) /\\ (forall a, X a -> Y a -> False).\n\nRequire Coq.Logic.ConstructiveEpsilon.\n\nLemma decidable_countable_ex_sig {A} (f : nat -> A)\n      (Hf : forall a, exists n, a = f n)\n      (P : A -> Prop)\n      (Pdec : forall x, {P x} + {~ P x}) :\n  (exists x : A, P x) -> {x : A | P x}.\nProof.\n  intros E.\n  cut ({n | P (f n)}). intros [n Hn]; eauto.\n  apply ConstructiveEpsilon.constructive_indefinite_ground_description_nat.\n  intro; apply Pdec.\n  destruct E as [x Hx].\n  destruct (Hf x) as [n ->].\n  eauto.\nQed.\n\n(** Additions to [if_tac]: when mature, move these upstream *)\n\nTactic Notation \"if_tac\" \"eq:\" simple_intropattern(E) :=\n  match goal with\n    |- context [if ?a then _ else _] =>\n    destruct a as [?H | ?H] eqn:E\n  end.\n\nTactic Notation \"if_tac\" simple_intropattern(H) \"eq:\" simple_intropattern(E):=\n  match goal with\n    |- context [if ?a then _ else _] =>\n    destruct a as H eqn:E\n  end.\n\nTactic Notation \"if_tac\" \"in\" hyp(H0) \"eq:\" simple_intropattern(E) :=\n  match type of H0 with\n    context [if ?a then _ else _] =>\n    destruct a as [?H  | ?H] eqn:E\n  end.\n\nTactic Notation \"if_tac\" simple_intropattern(H) \"in\" hyp(H1) \"eq:\" simple_intropattern(E) :=\n  match type of H1 with\n    context [if ?a then _ else _] =>\n    destruct a as H eqn:E\n  end.\n\n(** Specializing a hypothesis with a newly created goal *)\n\nTactic Notation \"assert_specialize\" hyp(H) :=\n  match type of H with\n    forall x : ?P, _ =>\n    let Htemp := fresh \"Htemp\" in\n    assert P as Htemp; [ | specialize (H Htemp); try clear Htemp ]\n  end.\n\nTactic Notation \"assert_specialize\" hyp(H) \"by\" tactic1(tac) :=\n  match type of H with\n    forall x : ?P, _ =>\n    let Htemp := fresh \"Htemp\" in\n    assert P as Htemp by tac; specialize (H Htemp); try clear Htemp\n  end.\n\nTactic Notation \"assert_specialize\" hyp(H) \"as\" simple_intropattern(Hnew) :=\n  match type of H with\n    forall x : ?P, _ =>\n    assert P as Hnew; [ | specialize (H Hnew) ]\n  end.\n\nTactic Notation \"assert_specialize\" hyp(H) \"as\" simple_intropattern(Hnew) \"by\" tactic1(tac) :=\n  match type of H with\n    forall x : ?P, _ =>\n    assert P as Hnew by tac;\n    specialize (H Hnew)\n  end.\n\n(** Auto-specializing a hypothesis *)\n\nLtac autospec H := specialize (H ltac:(solve [eauto])).\n\n(** When a hypothesis/term is provably equal, but not convertible, to\n    your goal *)\n\nLtac exact_eq H :=\n  revert H;\n  match goal with\n    |- ?p -> ?q => cut (p = q); [intros ->; auto | ]\n  end.\n\n(** Auto rewriting of a term *)\n\nTactic Notation \"rewr\" :=\n  match goal with\n  | H : ?f = _ |- context [?f] => rewrite H\n  | H : ?f _ = ?f _ |- _ => try (injection H; repeat intros ->)\n  end.\n\nTactic Notation \"rewr\" constr(e) :=\n  match goal with\n    E : e = _ |- _ => rewrite E\n  | E : _ = e |- _ => rewrite <-E\n  end.\n\nTactic Notation \"rewr\" constr(e) \"in\" \"*\" :=\n  match goal with\n    E : e = _ |- _ => rewrite E in *\n  | E : _ = e |- _ => rewrite <-E in *\n  end.\n\nTactic Notation \"rewr\" constr(e) \"in\" hyp(H) :=\n  match goal with\n    E : e = _ |- _ => rewrite E in H\n  | E : _ = e |- _ => rewrite <-E in H\n  end.\n\nLemma perm_search:\n  forall {A} (a b: A) r s t,\n     Permutation (a::t) s ->\n     Permutation (b::t) r ->\n     Permutation (a::r) (b::s).\nProof.\nintros.\neapply perm_trans.\napply perm_skip.\napply Permutation_sym.\napply H0.\neapply perm_trans.\napply perm_swap.\napply perm_skip.\napply H.\nQed.\n\nLemma Permutation_concat: forall {A} (P Q: list (list A)),\n  Permutation P Q ->\n  Permutation (concat P) (concat Q).\nProof.\n  intros.\n  induction H.\n  + apply Permutation_refl.\n  + simpl.\n    apply Permutation_app_head; auto.\n  + simpl.\n    rewrite !app_assoc.\n    apply Permutation_app_tail.\n    apply Permutation_app_comm.\n  + eapply Permutation_trans; eauto.\nQed.    \n\nLemma Permutation_app_comm_trans:\n forall (A: Type) (a b c : list A),\n   Permutation (b++a) c ->\n   Permutation (a++b) c.\nProof.\nintros.\neapply Permutation_trans.\napply Permutation_app_comm.\nauto.\nQed.\n\nLtac solve_perm :=\n    (* solves goals of the form (R ++ ?i = S)\n          where R and S are lists, and ?i is a unification variable *)\n  try match goal with\n       | |-  Permutation (?A ++ ?B) _ =>\n            is_evar A; first [is_evar B; fail 1| idtac];\n            apply Permutation_app_comm_trans\n       end;\n  repeat first [ apply Permutation_refl\n       | apply perm_skip\n       | eapply perm_search\n       ].\n\nGoal exists e, Permutation ((1::2::nil)++e) (3::2::1::5::nil).\neexists.\nsolve_perm.\nQed.\n\nLemma range_pred_dec: forall (P: nat -> Prop),\n  (forall n, {P n} + {~ P n}) ->\n  forall m,\n    {forall n, (n < m)%nat -> P n} + {~ forall n, (n < m)%nat -> P n}.\nProof.\n  intros.\n  induction m.\n  + left.\n    intros; lia.\n  + destruct (H m); [destruct IHm |].\n    - left.\n      intros.\n      destruct (eq_dec n m).\n      * subst; auto.\n      * apply p0; lia.\n    - right.\n      intro.\n      apply n; clear n.\n      intros; apply H0; lia.\n    - right.\n      intro.\n      apply n; clear n.\n      apply H0.\n      lia.\nQed.\n\nLemma Z2Nat_neg: forall i, i < 0 -> Z.to_nat i = 0%nat.\nProof.\n  intros.\n  destruct i; try reflexivity.\n  pose proof Zgt_pos_0 p; lia.\nQed.\n\nLemma Zrange_pred_dec: forall (P: Z -> Prop),\n  (forall z, {P z} + {~ P z}) ->\n  forall l r,  \n    {forall z, l <= z < r -> P z} + {~ forall z, l <= z < r -> P z}.\nProof.\n  intros.\n  assert ((forall n: nat, (n < Z.to_nat (r - l))%nat -> P (l + Z.of_nat n)) <-> (forall z : Z, l <= z < r -> P z)).\n  {\n    split; intros.\n    + specialize (H0 (Z.to_nat (z - l))).\n      rewrite <- Z2Nat.inj_lt in H0 by lia.\n      spec H0; [lia |].\n      rewrite Z2Nat.id in H0 by lia.\n      replace (l + (z - l)) with z in H0 by lia.\n      auto.\n    + apply H0.\n      rewrite Nat2Z.inj_lt in H1.\n      destruct (zlt (r - l) 0).\n      - rewrite Z2Nat_neg in H1 by lia.\n        simpl in H1.\n        lia.\n      - rewrite Z2Nat.id in H1 by lia.\n        lia.\n  }\n  eapply sumbool_dec_iff; [clear H0 | eassumption].\n  apply range_pred_dec.\n  intros.\n  apply H.\nQed.\n\nDefinition eqb_list {A: Type} (eqb_A: A -> A -> bool): list A -> list A -> bool :=\n  fix eqb_list (l1 l2: list A): bool :=\n    match l1, l2 with\n    | nil, nil => true\n    | a1 :: l1, a2 :: l2 => eqb_A a1 a2 && eqb_list l1 l2\n    | _, _ => false\n    end.\n\nLemma eqb_list_spec: forall {A: Type} (eqb_A: A -> A -> bool),\n  (forall a1 a2, eqb_A a1 a2 = true <-> a1 = a2) ->\n  (forall l1 l2, eqb_list eqb_A l1 l2 = true <-> l1 = l2).\nProof.\n  intros.\n  revert l2; induction l1 as [| a1 l1]; intros; destruct l2 as [| a2 l2].\n  + simpl.\n    tauto.\n  + simpl.\n    split; intros; congruence.\n  + simpl.\n    split; intros; congruence.\n  + simpl.\n    rewrite andb_true_iff.\n    rewrite  H.\n    rewrite IHl1.\n    split; intros.\n    - destruct H0; subst; auto.\n    - inv H0; auto.\nQed.\n\n\nLemma nat_ind2_Type:\nforall P : nat -> Type,\n((forall n, (forall j:nat, (j<n )%nat -> P j) ->  P n):Type) ->\n(forall n, P n).\nProof.\nintros.\nassert (forall j , (j <= n)%nat -> P j).\ninduction n.\nintros.\nreplace j with 0%nat ; try lia.\napply X; intros.\nelimtype False; lia.\nintros.  apply X. intros.\napply IHn.\nlia.\napply X0.\nlia.\nQed.\n\nLemma nat_ind2:\nforall P : nat -> Prop,\n(forall n, (forall j:nat, (j<n )%nat -> P j) ->  P n) ->\n(forall n, P n).\nProof.\nintros; apply Wf_nat.lt_wf_ind. auto.\nQed.\n\nLemma equiv_e2 : forall A B: Prop, A=B -> B -> A.\nProof.\nintros.\nrewrite H; auto.\nQed.\nArguments equiv_e2 [A B] _ _.\n\nDefinition opt2list (A: Type) (x: option A) :=\n  match x with Some a => a::nil | None => nil end.\nArguments opt2list [A] _.\n\nDefinition isSome {A} (o: option A) := match o with Some _ => True | None => False end.\n\nDefinition isSome_dec: forall {A} (P: option A), isSome P + ~ isSome P.\nProof.\n  intros.\n  destruct P; simpl; auto.\nDefined.\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/veric/coqlib4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.651676757909673}}
{"text": "Require Import ssreflect.\nRequire Import Coq.Classes.EquivDec.\nRequire Import Metalib.Metatheory.\n\nRequire Import Coq.Structures.Orders.\nRequire Import Coq.Bool.Sumbool.\nRequire Import Coq.Program.Equality.\n\nRequire Export usage_sig.\n\n(* ----------------------------------------------------------------- *)\n(* Lemmas about the usage pre-order / semi-ring.                     *)\n(* ----------------------------------------------------------------- *)\n\nOpen Scope usage_scope. \n\n(* --------------- Derived lemmas below here. -------------------- *)\n\nLemma usage_dec : forall x y, x =? y = true -> x = y.\nProof. intros. rewrite -> eqb_eq in H. auto. Qed.\n\n(* --------------------------- *)\n\nLemma qplus_0_r : forall x, x + 0 = x.\nProof. \n  intros. rewrite qplus_comm. rewrite qplus_0_l. auto.\nQed.\n\n(* --------------------------- *)\n\nLemma qplus_sub_r : forall u2 u u1, u1 <= u2 -> u1 + u <= u2 + u.\nProof.\n  intros; eapply po_semiring1; auto.\nQed.  \n\nLemma qplus_sub_l : forall u2 u u1, u1 <= u2 -> u + u1 <= u + u2.\nProof.\n  intros; repeat rewrite (qplus_comm u).\n  apply po_semiring1. auto.\nQed.  \n\n   \nLemma qplus_sub q1 q2 : 0 <= q2 -> q1 <= q1 + q2.\nProof.\n  intros.\n  move: (po_semiring1 _ _ q1 H) => h.\n  rewrite qplus_0_l in h.\n  rewrite qplus_comm.\n  auto.\nQed.\n\nLemma qmul_sub2 q1 q2 : 1 <= q2 -> q1 <= q1 * q2.\nProof.\n  move: (po_semiring3 1 q2 q1) => h.\n  rewrite qmul_1_r in h.\n  auto.\nQed.\n\nLemma qmul_sub_disposable : forall r q, 0 <= r -> 0 <= q * r.\nProof.\n  intros.\n  move: (po_semiring3 _ _ q H) => h.\n  rewrite qmul_0_r in h.\n  auto.\nQed. \n\n(* ----------------------------------------------------------------- *)\n(* Tactics and Hints *)\n(* ----------------------------------------------------------------- *)\n\n(*\nAdd Ring usage_semi_ring : usage_semi_ring (decidable usage_dec).\nHint Resolve usage_semi_ring : usage.\n*)\n\nHint Rewrite qplus_0_l qplus_0_r qmul_0_l qmul_0_r qmul_1_l qmul_1_r qplus_assoc qmul_assoc distr_l distr_r : usage.\n\nLtac ring_simpl := \n  repeat autorewrite with usage.\n\nTactic Notation \"ring_simpl\" \"in\" hyp(H) := \n  repeat autorewrite with usage in H.\n\nLtac ring_equal :=\n  repeat (ring_simpl; f_equal).\n\nLtac asimpl := repeat (simpl; ring_simpl; simpl_env).\n\nTactic Notation \"asimpl\" \"in\" hyp(H) :=\n  repeat (simpl in H; ring_simpl in H; simpl_env in H).\n\n\n(* ---------------------------------------------------------------- *)\n\n", "meta": {"author": "sweirich", "repo": "graded-haskell", "sha": "97eee95dfb6aedef81c81e8a64b9ad2b718c2815", "save_path": "github-repos/coq/sweirich-graded-haskell", "path": "github-repos/coq/sweirich-graded-haskell/graded-haskell-97eee95dfb6aedef81c81e8a64b9ad2b718c2815/GraD/src-def/usage.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924953, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6516712368052477}}
{"text": "(** * Algebra 1 . Part A .  Generalities. Vladimir Voevodsky. Aug. 2011 - . \n\n*)\n\n\n\n(** ** Preambule *)\n\n(** Settings *)\n\nUnset Automatic Introduction. (** This line has to be removed for the file to compile with Coq8.2 *)\n\n\n(** Imports *)\n\nAdd LoadPath \"../hlevel1\" .\nAdd LoadPath \"../Generalities\".\n\nRequire Export hSet .\n\n\n(** To upstream files *)\n\n\n\n(** ** Sets with one and two binary operations *)\n\n(** *** Binary operations *)\n\n(** **** General definitions *)\n\nDefinition binop ( X : UU ) := X -> X -> X .\n\nDefinition islcancelable { X : UU } ( opp : binop X ) ( x : X ) := isincl ( fun x0 : X => opp x x0 ) .\n\nDefinition isrcancelable { X : UU } ( opp : binop X ) ( x : X ) := isincl ( fun x0 : X => opp x0 x ) .\n\nDefinition iscancelable { X : UU } ( opp : binop X ) ( x : X )  := dirprod ( islcancelable opp x ) ( isrcancelable opp x ) . \n\nDefinition islinvertible { X : UU } ( opp : binop X ) ( x : X ) := isweq ( fun x0 : X => opp x x0 ) .\n\nDefinition isrinvertible { X : UU } ( opp : binop X ) ( x : X ) := isweq ( fun x0 : X => opp x0 x ) .\n\nDefinition isinvertible { X : UU } ( opp : binop X ) ( x : X ) := dirprod ( islinvertible opp x ) ( isrinvertible opp x ) . \n\n\n\n(** **** Standard conditions on one binary operation on a set *)\n\n(** *)\n\nDefinition isassoc { X : hSet} ( opp : binop X ) := forall x x' x'' , paths ( opp ( opp x x' ) x'' ) ( opp x ( opp x' x'' ) ) .\n\nLemma isapropisassoc { X : hSet } ( opp : binop X ) : isaprop ( isassoc opp ) .\nProof . intros . apply impred . intro x . apply impred . intro x' . apply impred . intro x'' . simpl . apply ( setproperty X ) . Defined .\n\n(** *)\n\nDefinition islunit { X : hSet} ( opp : binop X ) ( un0 : X ) := forall x : X , paths ( opp un0 x ) x .\n\nLemma isapropislunit { X : hSet} ( opp : binop X ) ( un0 : X ) : isaprop ( islunit opp un0 ) . \nProof . intros . apply impred . intro x . simpl . apply ( setproperty X ) .  Defined .  \n\nDefinition isrunit { X : hSet} ( opp : binop X ) ( un0 : X ) := forall x : X , paths ( opp x un0 ) x  .\n\nLemma isapropisrunit { X : hSet} ( opp : binop X ) ( un0 : X ) : isaprop ( isrunit opp un0 ) .\nProof . intros . apply impred . intro x . simpl . apply ( setproperty X ) .  Defined .  \n\nDefinition isunit { X : hSet} ( opp : binop X ) ( un0 : X ) := dirprod ( islunit opp un0 ) ( isrunit opp un0 ) .\n\nDefinition isunital { X : hSet} ( opp : binop X ) := total2 ( fun un0 : X => isunit opp un0 ) .\nDefinition isunitalpair { X : hSet } { opp : binop X } ( un0 : X ) ( is : isunit opp un0 ) : isunital opp := tpair _ un0 is .  \n\nLemma isapropisunital { X : hSet} ( opp : binop X )  : isaprop ( isunital opp ) .\nProof . intros .  apply ( @isapropsubtype X ( fun un0 : _ => hconj ( hProppair _ ( isapropislunit opp un0 ) ) ( hProppair _ ( isapropisrunit opp un0 ) ) ) )  .  intros u1 u2 .  intros ua1 ua2 .  apply ( pathscomp0 ( pathsinv0 ( pr2 ua2 u1 ) ) ( pr1 ua1 u2 ) ) .  Defined . \n\n\n(** *)\n\nDefinition ismonoidop { X : hSet } ( opp : binop X ) := dirprod ( isassoc opp ) ( isunital opp ) .\nDefinition assocax_is { X : hSet } { opp : binop X } : ismonoidop opp -> isassoc opp := @pr1 _ _ .  \nDefinition unel_is { X : hSet } { opp : binop X } ( is : ismonoidop opp ) : X := pr1 ( pr2 is ) .\nDefinition lunax_is { X : hSet } { opp : binop X } ( is : ismonoidop opp ) := pr1 ( pr2 ( pr2 is ) ) . \nDefinition runax_is { X : hSet } { opp : binop X } ( is : ismonoidop opp ) := pr2 ( pr2 ( pr2 is ) ) . \n\n\nLemma isapropismonoidop { X : hSet } ( opp : binop X ) : isaprop ( ismonoidop opp ) .\nProof . intros . apply ( isofhleveldirprod 1 ) . apply ( isapropisassoc ) .  apply ( isapropisunital ) .  Defined .  \n\n\n\n(** *)\n\nDefinition islinv { X : hSet } ( opp : binop X ) ( un0 : X ) ( inv0 : X -> X ) := forall x : X , paths ( opp ( inv0 x ) x ) un0 .\n\nLemma isapropislinv { X : hSet } ( opp : binop X ) ( un0 : X ) ( inv0 : X -> X ) : isaprop ( islinv opp un0 inv0 ) .\nProof . intros . apply impred . intro x .  apply ( setproperty X (opp (inv0 x) x) un0 ) . Defined .\n\nDefinition isrinv { X : hSet } ( opp : binop X ) ( un0 : X ) ( inv0 : X -> X ) := forall x : X , paths ( opp x ( inv0 x ) ) un0 .\n\nLemma isapropisrinv { X : hSet } ( opp : binop X ) ( un0 : X ) ( inv0 : X -> X ) : isaprop ( isrinv opp un0 inv0 ) .\nProof . intros . apply impred . intro x .  apply ( setproperty X ) . Defined .\n\nDefinition isinv { X : hSet } ( opp : binop X ) ( un0 : X ) ( inv0 : X -> X ) := dirprod ( islinv opp un0 inv0 ) ( isrinv opp un0 inv0 ) . \n\nLemma isapropisinv { X : hSet } ( opp : binop X ) ( un0 : X ) ( inv0 : X -> X ) : isaprop ( isinv opp un0 inv0 ) .\nProof . intros . apply ( isofhleveldirprod 1 ) . apply isapropislinv .  apply isapropisrinv . Defined .  \n\nDefinition invstruct { X : hSet } ( opp : binop X ) ( is : ismonoidop opp  ) := total2 ( fun inv0 : X -> X =>  isinv opp ( unel_is is ) inv0 ) .\n\nDefinition isgrop { X : hSet } ( opp : binop X ) := total2 ( fun is : ismonoidop opp => invstruct opp is ) .\nDefinition isgroppair { X : hSet } { opp : binop X } ( is1 : ismonoidop opp ) ( is2 : invstruct opp is1 ) : isgrop opp := tpair ( fun is : ismonoidop opp => invstruct opp is ) is1 is2 . \nDefinition pr1isgrop ( X : hSet ) ( opp : binop X ) : isgrop opp -> ismonoidop opp := @pr1 _ _ .\nCoercion pr1isgrop : isgrop >-> ismonoidop . \n\nDefinition grinv_is { X : hSet } { opp : binop X } ( is : isgrop opp ) : X -> X := pr1 ( pr2 is ) . \n\nDefinition grlinvax_is { X : hSet } { opp : binop X } ( is : isgrop opp ) := pr1 ( pr2 ( pr2 is ) ) . \n\nDefinition grrinvax_is { X : hSet } { opp : binop X } ( is : isgrop opp ) := pr2 ( pr2 ( pr2 is ) ) . \n\n\nLemma isweqrmultingr_is { X : hSet } { opp : binop X } ( is : isgrop opp ) ( x0 : X ) : isrinvertible opp x0 .\nProof . intros .  destruct is as [ is istr ] . set ( f := fun x : X => opp x x0 ) . set ( g := fun x : X , opp x ( ( pr1 istr ) x0 ) ) .  destruct is as [ assoc isun0 ] . destruct istr as [ inv0 axs ] .   destruct isun0 as [ un0 unaxs ] .  simpl in * |-  . \nassert ( egf : forall x : _ , paths ( g ( f x ) ) x ) . intro x . unfold f . unfold g . destruct ( pathsinv0 ( assoc x x0 ( inv0 x0 ) ) ) .  assert ( e := pr2 axs x0 ) .   simpl in e . rewrite e . apply ( pr2 unaxs x ) .  \nassert ( efg : forall x : _ , paths ( f ( g x ) ) x ) . intro x .  unfold f . unfold g . destruct ( pathsinv0 ( assoc x ( inv0 x0 ) x0 ) ) . assert ( e := pr1 axs x0 ) . simpl in e . rewrite e . apply ( pr2 unaxs x ) .  \napply ( gradth _ _ egf efg ) . Defined .  \n\nLemma isweqlmultingr_is { X : hSet } { opp : binop X } ( is : isgrop opp )  ( x0 : X ) : islinvertible opp x0 .\nProof . intros .   destruct is as [ is istr ] .  set ( f := fun x : X => opp x0 x ) . set ( g := fun x : X , opp ( ( pr1 istr ) x0 ) x ) .  destruct is as [ assoc isun0 ] . destruct istr as [ inv0 axs ] .  destruct isun0 as [ un0 unaxs ] .  simpl in * |-  . \nassert ( egf : forall x : _ , paths ( g ( f x ) ) x ) . intro x . unfold f . unfold g . destruct ( assoc ( inv0 x0 ) x0 x  ) . assert ( e := pr1 axs x0 ) . simpl in e . rewrite e . apply ( pr1 unaxs x ) .  \nassert ( efg : forall x : _ , paths ( f ( g x ) ) x ) . intro x . unfold f . unfold g . destruct ( assoc x0 ( inv0 x0 ) x  ) . assert ( e := pr2 axs x0 ) . simpl in e . rewrite e . apply ( pr1 unaxs x ) .  \napply ( gradth _ _ egf efg ) . Defined .  \n\n\nLemma isapropinvstruct { X : hSet } { opp : binop X } ( is : ismonoidop opp ) : isaprop ( invstruct opp is ) . \nProof . intros . apply isofhlevelsn . intro is0 . set ( un0 := pr1 ( pr2 is ) ) . assert ( int : forall i : X -> X , isaprop ( dirprod ( forall x : X , paths ( opp ( i x ) x ) un0 ) ( forall x : X , paths ( opp x ( i x ) ) un0 ) ) ) . intro i . apply ( isofhleveldirprod 1 ) .  apply impred . intro x .  simpl . apply ( setproperty X  ) . apply impred . intro x .   simpl .  apply ( setproperty X ) . apply ( isapropsubtype ( fun i : _ => hProppair _ ( int i ) ) ) .  intros inv1 inv2 .  simpl . intro ax1 .  intro ax2 .  apply funextfun . intro x0 . apply ( invmaponpathsweq ( weqpair _ ( isweqrmultingr_is ( tpair _ is is0 ) x0 ) ) ) .    simpl . rewrite ( pr1 ax1 x0 ) .   rewrite ( pr1 ax2 x0 ) .  apply idpath .  Defined . \n\nLemma isapropisgrop { X : hSet } ( opp : binop X ) : isaprop ( isgrop opp ) .\nProof . intros . apply ( isofhleveltotal2 1 ) . apply isapropismonoidop . apply isapropinvstruct . Defined .  \n\n(* (** Unitary monoid where all elements are invertible is a group *)\n\nDefinition allinvvertibleinv { X : hSet } { opp : binop X } ( is : ismonoidop opp ) ( allinv : forall x : X , islinvertible opp x ) : X -> X := fun x : X => invmap ( weqpair _ ( allinv x ) ) ( unel_is is ) .   \n\n*)\n\n\n(** The following lemma is an analog of [ Bourbaki , Alg. 1 , ex. 2 , p. 132 ] *)\n\nLemma isgropif { X : hSet } { opp : binop X } ( is0 : ismonoidop opp ) ( is : forall x : X, hexists ( fun x0 : X => eqset ( opp x x0 ) ( unel_is is0 ) ) ) : isgrop opp . \nProof . intros . split with is0 .  destruct is0 as [ assoc isun0 ] . destruct isun0 as [ un0 unaxs0 ] . simpl in is .  simpl in unaxs0 . simpl in un0 . simpl in assoc . simpl in unaxs0 .  \n\nassert ( l1 : forall x' : X , isincl ( fun x0 : X => opp x0 x' ) ) . intro x' . apply ( @hinhuniv ( total2 ( fun x0 : X => paths ( opp x' x0 ) un0 ) ) ( hProppair _ ( isapropisincl ( fun x0 : X => opp x0 x' ) ) ) ) .  intro int1 . simpl . apply isinclbetweensets .  apply ( pr2 X ) .  apply ( pr2 X ) .   intros a b .  intro e .  rewrite ( pathsinv0 ( pr2 unaxs0 a ) ) . rewrite ( pathsinv0 ( pr2 unaxs0 b ) ) .  destruct int1 as [ invx' eq ] .  rewrite ( pathsinv0 eq ) . destruct ( assoc a x' invx' ) .  destruct ( assoc b x' invx' ) .  rewrite e . apply idpath .  apply ( is x' ) .  \n\nassert ( is' :  forall x : X, hexists ( fun x0 : X => eqset ( opp x0 x ) un0 ) ) . intro x . apply ( fun f : _  => hinhuniv f ( is x ) ) .  intro s1 .  destruct s1 as [ x' eq ] .  apply hinhpr . split with x' . simpl . apply ( invmaponpathsincl _ ( l1 x' ) ) .   rewrite ( assoc x' x x' ) . rewrite eq .  rewrite ( pr1 unaxs0 x' ) . unfold unel_is.   simpl . rewrite ( pr2 unaxs0 x' ) .  apply idpath . \n\nassert ( l1' :  forall x' : X , isincl ( fun x0 : X => opp x' x0 ) ) . intro x' . apply ( @hinhuniv ( total2 ( fun x0 : X => paths ( opp x0 x' ) un0 ) ) ( hProppair _ ( isapropisincl ( fun x0 : X => opp x' x0 ) ) ) ) .  intro int1 . simpl . apply isinclbetweensets .  apply ( pr2 X ) .  apply ( pr2 X ) .   intros a b .  intro e .  rewrite ( pathsinv0 ( pr1 unaxs0 a ) ) . rewrite ( pathsinv0 ( pr1 unaxs0 b ) ) .  destruct int1 as [ invx' eq ] .  rewrite ( pathsinv0 eq ) . destruct ( pathsinv0 ( assoc invx' x' a )  ) .  destruct ( pathsinv0 ( assoc invx' x' b ) ) .  rewrite e . apply idpath .  apply ( is' x' ) .  \n\nassert ( int : forall x : X , isaprop ( total2 ( fun x0 : X => eqset ( opp x0 x ) un0 ) ) ) . intro x .   apply isapropsubtype .  intros x1 x2 .  intros eq1 eq2 .  apply ( invmaponpathsincl _ ( l1 x ) ) . rewrite eq1 .   rewrite eq2 .  apply idpath . \n\nsimpl . set ( linv0 := fun x : X => hinhunivcor1 ( hProppair _ ( int x ) ) ( is' x ) ) .  simpl in linv0 .  set ( inv0 := fun x : X => pr1 ( linv0 x ) ) .  split with inv0 . simpl . split with ( fun x : _ => pr2 ( linv0 x ) ) .  intro x .  apply ( invmaponpathsincl _ ( l1 x ) ) . rewrite ( assoc x ( inv0 x ) x ) . change ( inv0 x ) with ( pr1 ( linv0 x ) ) . rewrite ( pr2 ( linv0 x ) ) . unfold unel_is . simpl . rewrite ( pr1 unaxs0 x ) . rewrite ( pr2 unaxs0 x ) . apply idpath .  Defined . \n\n\n\n(** *)\n\nDefinition iscomm { X : hSet} ( opp : binop X ) := forall x x' : X , paths ( opp x x' ) ( opp x' x ) . \n\nLemma isapropiscomm { X : hSet } ( opp : binop X ) : isaprop ( iscomm opp ) .\nProof . intros . apply impred . intros x . apply impred . intro x' . simpl . apply ( setproperty X ) . Defined . \n\nDefinition isabmonoidop { X : hSet } ( opp : binop X ) := dirprod ( ismonoidop opp ) ( iscomm opp ) . \nDefinition pr1isabmonoidop ( X : hSet ) ( opp : binop X ) : isabmonoidop opp -> ismonoidop opp := @pr1 _ _ .\nCoercion pr1isabmonoidop : isabmonoidop >-> ismonoidop .\n\nDefinition commax_is { X : hSet} { opp : binop X } ( is : isabmonoidop opp ) : iscomm opp := pr2 is . \n\nLemma isapropisabmonoidop { X : hSet } ( opp : binop X ) : isaprop ( isabmonoidop opp ) .\nProof . intros . apply ( isofhleveldirprod 1 ) . apply isapropismonoidop . apply isapropiscomm . Defined . \n\nLemma abmonoidoprer { X : hSet } { opp : binop X } ( is : isabmonoidop opp ) ( a b c d : X ) : paths ( opp ( opp a b ) ( opp c d ) ) ( opp ( opp a c ) ( opp b d ) ) .\nProof . intros . destruct is as [ is comm ] . destruct is as [ assoc unital0 ] .  simpl in * .  destruct ( assoc ( opp a b ) c d ) .  destruct ( assoc ( opp a c ) b d ) . destruct ( pathsinv0 ( assoc a b c ) ) . destruct ( pathsinv0 ( assoc a c b ) ) .   destruct ( comm b c ) . apply idpath .  Defined . \n\n\n\n\n(** *)\n\n\nLemma weqlcancelablercancelable { X : hSet } ( opp : binop X ) ( is : iscomm opp ) ( x : X ) : weq ( islcancelable opp x ) ( isrcancelable opp x ) .\nProof . intros . \n\nassert ( f : ( islcancelable opp x ) -> ( isrcancelable opp x ) ) . unfold islcancelable . unfold isrcancelable .  intro isl . apply ( fun h : _ => isinclhomot _ _ h isl ) .  intro x0 . apply is .  \nassert ( g : ( isrcancelable opp x ) -> ( islcancelable opp x ) ) . unfold islcancelable . unfold isrcancelable .  intro isr . apply ( fun h : _ => isinclhomot _ _ h isr ) .  intro x0 . apply is . \n\nsplit with f . apply ( isweqimplimpl f g ( isapropisincl ( fun x0 : X => opp x x0 ) )  ( isapropisincl ( fun x0 : X => opp x0 x ) ) ) .  Defined .  \n\n\n\nLemma weqlinvertiblerinvertible { X : hSet } ( opp : binop X ) ( is : iscomm opp ) ( x : X ) : weq ( islinvertible opp x ) ( isrinvertible opp x ) .\nProof . intros . \n\nassert ( f : ( islinvertible opp x ) -> ( isrinvertible opp x ) ) . unfold islinvertible . unfold isrinvertible .  intro isl . apply ( fun h : _ => isweqhomot _ _ h isl ) .  apply is .  \nassert ( g : ( isrinvertible opp x ) -> ( islinvertible opp x ) ) . unfold islinvertible . unfold isrinvertible .  intro isr . apply ( fun h : _ => isweqhomot _ _ h isr ) .  intro x0 . apply is . \n\nsplit with f . apply ( isweqimplimpl f g ( isapropisweq ( fun x0 : X => opp x x0 ) )  ( isapropisweq ( fun x0 : X => opp x0 x ) ) ) .  Defined .  \n\n\nLemma weqlunitrunit { X : hSet } ( opp : binop X ) ( is : iscomm opp ) ( un0 : X ) : weq ( islunit opp un0 ) ( isrunit opp un0 ) .\nProof . intros . \n\nassert ( f : ( islunit opp un0 ) -> ( isrunit opp un0 ) ) . unfold islunit . unfold isrunit .  intro isl .  intro x .  destruct ( is un0 x ) .  apply ( isl x ) .  \nassert ( g : ( isrunit opp un0 ) -> ( islunit opp un0 ) ) . unfold islunit . unfold isrunit .  intro isr . intro x .  destruct ( is x un0 ) .  apply ( isr x ) .  \n\nsplit with f . apply ( isweqimplimpl f g ( isapropislunit opp un0 )  ( isapropisrunit opp un0 ) ) .  Defined .  \n\n\nLemma weqlinvrinv { X : hSet } ( opp : binop X ) ( is : iscomm opp ) ( un0 : X ) ( inv0 : X -> X ) : weq ( islinv opp un0 inv0 ) ( isrinv opp un0 inv0 ) .\nProof . intros . \n\nassert ( f : ( islinv opp un0 inv0 ) -> ( isrinv opp un0 inv0 ) ) . unfold islinv . unfold isrinv .  intro isl .  intro x .  destruct ( is ( inv0 x ) x ) .  apply ( isl x ) .  \nassert ( g : ( isrinv opp un0 inv0 ) -> ( islinv opp un0 inv0 ) ) . unfold islinv . unfold isrinv .  intro isr . intro x .  destruct ( is x ( inv0 x ) ) .  apply ( isr x ) .  \n\nsplit with f . apply ( isweqimplimpl f g ( isapropislinv opp un0 inv0 )  ( isapropisrinv opp un0 inv0 ) ) .  Defined .  \n\n\nOpaque abmonoidoprer .\n\n\n(** *)\n\nDefinition isabgrop { X : hSet } ( opp : binop X ) := dirprod ( isgrop opp ) ( iscomm opp ) .\nDefinition pr1isabgrop ( X : hSet ) ( opp : binop X ) : isabgrop opp -> isgrop opp := @pr1 _ _ .\nCoercion pr1isabgrop : isabgrop >-> isgrop .\n\nDefinition isabgroptoisabmonoidop ( X : hSet ) ( opp : binop X ) : isabgrop opp -> isabmonoidop opp := fun is : _ => dirprodpair ( pr1 ( pr1 is ) ) ( pr2 is ) .\nCoercion isabgroptoisabmonoidop : isabgrop >-> isabmonoidop .\n\nLemma isapropisabgrop { X : hSet } ( opp : binop X ) : isaprop ( isabgrop opp ) .\nProof . intros . apply ( isofhleveldirprod 1 ) . apply isapropisgrop . apply isapropiscomm . Defined .  \n\n\n\n\n\n\n\n\n(** **** Standard conditions on a pair of binary operations on a set *)\n\n(** *)\n\nDefinition isldistr { X : hSet} ( opp1 opp2 : binop X ) := forall x x' x'' : X , paths ( opp2 x'' ( opp1 x x' ) ) ( opp1 ( opp2 x'' x ) ( opp2 x'' x' ) ) .\n\nLemma isapropisldistr { X : hSet} ( opp1 opp2 : binop X ) : isaprop ( isldistr opp1 opp2 ) .\nProof . intros . apply impred . intro x . apply impred . intro x' . apply impred . intro x'' . simpl . apply ( setproperty X ) . Defined .   \n\nDefinition isrdistr { X : hSet} ( opp1 opp2 : binop X ) := forall x x' x'' : X , paths ( opp2 ( opp1 x x' ) x'' ) ( opp1 ( opp2 x x'' ) ( opp2 x' x'' ) ) .\n\nLemma isapropisrdistr { X : hSet} ( opp1 opp2 : binop X ) : isaprop ( isrdistr opp1 opp2 ) .\nProof . intros . apply impred . intro x . apply impred . intro x' . apply impred . intro x'' . simpl . apply ( setproperty X ) . Defined .   \n\nDefinition isdistr { X : hSet } ( opp1 opp2 : binop X ) := dirprod ( isldistr opp1 opp2 ) ( isrdistr opp1 opp2 ) .\n\nLemma isapropisdistr { X : hSet } ( opp1 opp2 : binop X ) : isaprop ( isdistr opp1 opp2  ) .\nProof . intros . apply ( isofhleveldirprod 1 _ _ ( isapropisldistr _ _ ) ( isapropisrdistr _ _ ) ) . Defined .  \n\n(** *)\n\nLemma weqldistrrdistr { X : hSet} ( opp1 opp2 : binop X ) ( is : iscomm opp2 ) : weq ( isldistr opp1 opp2 ) ( isrdistr opp1 opp2 ) .\nProof .  intros . \n\nassert ( f : ( isldistr opp1 opp2 ) -> ( isrdistr opp1 opp2 ) ) . unfold isldistr . unfold isrdistr .  intro isl .  intros x x' x'' .  destruct ( is x'' ( opp1 x x' ) ) . destruct ( is x'' x ) . destruct ( is x'' x' ) .  apply ( isl x x' x'' ) .  \nassert ( g : ( isrdistr opp1 opp2 ) -> ( isldistr opp1 opp2 ) ) . unfold isldistr . unfold isrdistr .  intro isr .  intros x x' x'' .  destruct ( is ( opp1 x x' ) x'' ) . destruct ( is x x'' ) . destruct ( is x' x'' ) .  apply ( isr x x' x'' ) .   \n\nsplit with f . apply ( isweqimplimpl f g ( isapropisldistr opp1 opp2 )  ( isapropisrdistr opp1 opp2 ) ) .  Defined . \n\n\n(** *)\n\n\nDefinition isrigops { X : hSet } ( opp1 opp2 : binop X ) :=  dirprod ( total2 ( fun axs : dirprod ( isabmonoidop opp1 ) ( ismonoidop opp2 ) => ( dirprod ( forall x : X , paths ( opp2 ( unel_is ( pr1 axs ) ) x ) ( unel_is ( pr1 axs ) ) ) ) ( forall x : X , paths ( opp2 x ( unel_is ( pr1 axs ) ) ) ( unel_is ( pr1 axs ) ) ) ) ) ( isdistr opp1 opp2 ) .\n    \nDefinition rigop1axs_is { X : hSet } { opp1 opp2 : binop X } : isrigops opp1 opp2 -> isabmonoidop opp1 := fun is : _ => pr1 ( pr1 ( pr1 is ) ) .\nDefinition rigop2axs_is { X : hSet } { opp1 opp2 : binop X } : isrigops opp1 opp2 -> ismonoidop opp2 := fun is : _ => pr2 ( pr1 ( pr1 is ) ) .\nDefinition rigdistraxs_is { X : hSet } { opp1 opp2 : binop X } : isrigops opp1 opp2 -> isdistr opp1 opp2 := fun is : _ =>  pr2 is .\nDefinition rigldistrax_is { X : hSet } { opp1 opp2 : binop X } : isrigops opp1 opp2 -> isldistr opp1 opp2 := fun is : _ => pr1 ( pr2 is ) .\nDefinition rigrdistrax_is { X : hSet } { opp1 opp2 : binop X } : isrigops opp1 opp2 -> isrdistr opp1 opp2 := fun is : _ => pr2 ( pr2 is ) .\nDefinition rigunel1_is { X : hSet } { opp1 opp2 : binop X } ( is : isrigops opp1 opp2 ) : X := pr1 (pr2 (pr1 (rigop1axs_is is))) .\nDefinition rigunel2_is { X : hSet } { opp1 opp2 : binop X } ( is : isrigops opp1 opp2 ) : X := (pr1 (pr2 (rigop2axs_is is))) .\nDefinition rigmult0x_is { X : hSet } { opp1 opp2 : binop X } ( is : isrigops opp1 opp2 ) ( x : X ) : paths ( opp2 ( rigunel1_is is ) x ) ( rigunel1_is is )  := pr1 ( pr2 ( pr1 is ) ) x .\nDefinition rigmultx0_is { X : hSet } { opp1 opp2 : binop X } ( is : isrigops opp1 opp2 ) ( x : X ) : paths ( opp2 x ( rigunel1_is is ) ) ( rigunel1_is is ) := pr2 ( pr2 ( pr1 is ) ) x .\n\n\nLemma isapropisrigops { X : hSet } ( opp1 opp2 : binop X ) : isaprop ( isrigops opp1 opp2 ) .\nProof . intros . apply ( isofhleveldirprod 1 ) . apply ( isofhleveltotal2 1 ) . apply ( isofhleveldirprod 1 ) . apply isapropisabmonoidop . apply isapropismonoidop. intro x . apply ( isofhleveldirprod 1 ) . apply impred. intro x' . apply ( setproperty X ) . apply impred . intro x' . apply ( setproperty X ) . apply isapropisdistr . Defined . \n\n\n\n\n(** *)\n\n\nDefinition isrngops { X : hSet } ( opp1 opp2 : binop X ) := dirprod ( dirprod ( isabgrop opp1 ) ( ismonoidop opp2 ) ) ( isdistr opp1 opp2 ) . \n\nDefinition rngop1axs_is { X : hSet } { opp1 opp2 : binop X } : isrngops opp1 opp2 -> isabgrop opp1 := fun is : _ => pr1 ( pr1 is ) .\nDefinition rngop2axs_is { X : hSet } { opp1 opp2 : binop X } : isrngops opp1 opp2 -> ismonoidop opp2 := fun is : _ => pr2 ( pr1 is ) .\nDefinition rngdistraxs_is { X : hSet } { opp1 opp2 : binop X } : isrngops opp1 opp2 -> isdistr opp1 opp2 := fun is : _ =>  pr2 is .\nDefinition rngldistrax_is { X : hSet } { opp1 opp2 : binop X } : isrngops opp1 opp2 -> isldistr opp1 opp2 := fun is : _ => pr1 ( pr2 is ) .\nDefinition rngrdistrax_is { X : hSet } { opp1 opp2 : binop X } : isrngops opp1 opp2 -> isrdistr opp1 opp2 := fun is : _ => pr2 ( pr2 is ) .\nDefinition rngunel1_is { X : hSet } { opp1 opp2 : binop X } ( is : isrngops opp1 opp2 ) : X := unel_is ( pr1 ( pr1 is ) ) .\nDefinition rngunel2_is { X : hSet } { opp1 opp2 : binop X } ( is : isrngops opp1 opp2 ) : X := unel_is ( pr2 ( pr1 is ) ) .\n\n\nLemma isapropisrngops { X : hSet } ( opp1 opp2 : binop X ) : isaprop ( isrngops opp1 opp2 ) .\nProof . intros . apply ( isofhleveldirprod 1 ) . apply ( isofhleveldirprod 1 ) . apply isapropisabgrop . apply isapropismonoidop. apply isapropisdistr . Defined . \n\nLemma multx0_is_l { X : hSet } { opp1 opp2 : binop X } ( is1 : isgrop opp1 ) ( is2 : ismonoidop opp2 ) ( is12 : isdistr opp1 opp2 ) : forall x : X , paths ( opp2 x ( unel_is ( pr1 is1 ) ) ) ( unel_is ( pr1 is1 ) )  .\nProof . intros .  destruct is12 as [ ldistr0 rdistr0 ] . destruct is2 as [ assoc2 [ un2 [ lun2 run2 ] ] ] . simpl in * . apply ( invmaponpathsweq ( weqpair _ ( isweqrmultingr_is is1 ( opp2 x un2 ) ) ) ) .  simpl .  destruct is1 as [ [ assoc1 [ un1 [ lun1 run1 ] ] ] [ inv0 [ linv0 rinv0 ] ] ] .  unfold unel_is .  simpl in * . rewrite ( lun1 ( opp2 x un2 ) ) . destruct ( ldistr0 un1 un2 x ) .    rewrite ( run2 x ) .  rewrite ( lun1 un2 ) .  rewrite ( run2 x ) . apply idpath .  Defined .\n\nOpaque multx0_is_l .\n\nLemma mult0x_is_l { X : hSet } { opp1 opp2 : binop X } ( is1 : isgrop opp1 ) ( is2 : ismonoidop opp2 ) ( is12 : isdistr opp1 opp2 ) : forall x : X , paths ( opp2 ( unel_is ( pr1 is1 ) ) x ) ( unel_is ( pr1 is1 ) ) .\nProof . intros .  destruct is12 as [ ldistr0 rdistr0 ] . destruct is2 as [ assoc2 [ un2 [ lun2 run2 ] ] ] . simpl in * . apply ( invmaponpathsweq ( weqpair _ ( isweqrmultingr_is is1 ( opp2 un2 x ) ) ) ) .  simpl .  destruct is1 as [ [ assoc1 [ un1 [ lun1 run1 ] ] ] [ inv0 [ linv0 rinv0 ] ] ] .  unfold unel_is .  simpl in * . rewrite ( lun1 ( opp2 un2 x ) ) . destruct ( rdistr0 un1 un2 x ) .  rewrite ( lun2 x ) .  rewrite ( lun1 un2 ) .  rewrite ( lun2 x ) . apply idpath .  Defined .\n\nOpaque mult0x_is_l .\n\n\n\nDefinition minus1_is_l { X : hSet } { opp1 opp2 : binop X } ( is1 : isgrop opp1 ) ( is2 : ismonoidop opp2 ) := ( grinv_is is1 ) ( unel_is is2 ) . \n\nLemma islinvmultwithminus1_is_l { X : hSet } { opp1 opp2 : binop X } ( is1 : isgrop opp1 ) ( is2 : ismonoidop opp2 ) ( is12 : isdistr opp1 opp2 ) ( x : X ) : paths ( opp1 ( opp2 ( minus1_is_l is1 is2 ) x ) x ) ( unel_is ( pr1 is1 ) ) .\nProof . intros . set ( xinv := opp2 (minus1_is_l is1 is2) x ) . rewrite ( pathsinv0 ( lunax_is is2 x ) ) . unfold xinv .  rewrite ( pathsinv0 ( pr2 is12 _ _ x ) ) . unfold minus1_is_l . unfold grinv_is . rewrite ( grlinvax_is is1 _ ) .  apply mult0x_is_l .   apply is2 . apply is12 .  Defined . \n\nOpaque islinvmultwithminus1_is_l .\n\nLemma isrinvmultwithminus1_is_l { X : hSet } { opp1 opp2 : binop X } ( is1 : isgrop opp1 ) ( is2 : ismonoidop opp2 ) ( is12 : isdistr opp1 opp2 ) ( x : X ) : paths ( opp1 x ( opp2 ( minus1_is_l is1 is2 ) x ) ) ( unel_is ( pr1 is1 ) ) .\nProof . intros . set ( xinv := opp2 (minus1_is_l is1 is2) x ) . rewrite ( pathsinv0 ( lunax_is is2 x ) ) . unfold xinv .  rewrite ( pathsinv0 ( pr2 is12 _ _ x ) ) . unfold minus1_is_l . unfold grinv_is . rewrite ( grrinvax_is is1 _ ) .  apply mult0x_is_l .   apply is2 . apply is12 .  Defined . \n\nOpaque isrinvmultwithminus1_is_l . \n\n\nLemma isminusmultwithminus1_is_l { X : hSet } { opp1 opp2 : binop X } ( is1 : isgrop opp1 ) ( is2 : ismonoidop opp2 ) ( is12 : isdistr opp1 opp2 ) ( x : X ) : paths ( opp2 ( minus1_is_l is1 is2 ) x ) ( grinv_is is1 x ) .\nProof . intros . apply ( invmaponpathsweq ( weqpair _ ( isweqrmultingr_is is1 x ) ) ) .    simpl . rewrite ( islinvmultwithminus1_is_l is1 is2 is12 x ) . unfold grinv_is . rewrite ( grlinvax_is is1 x ) .  apply idpath . Defined . \n\nOpaque isminusmultwithminus1_is_l . \n\nLemma isrngopsif { X : hSet } { opp1 opp2 : binop X } ( is1 : isgrop opp1 ) ( is2 : ismonoidop opp2 ) ( is12 : isdistr opp1 opp2 ) : isrngops opp1 opp2 .\nProof . intros .  set ( assoc1 := pr1 ( pr1 is1 ) ) . split . split .  split with is1 . \nintros x y .    apply ( invmaponpathsweq ( weqpair _ ( isweqrmultingr_is is1 ( opp2 ( minus1_is_l is1 is2 ) ( opp1 x y ) ) ) ) ) . simpl . rewrite ( isrinvmultwithminus1_is_l is1 is2 is12 ( opp1 x y ) ) . rewrite ( pr1 is12 x y _ ) .  destruct ( assoc1 ( opp1 y x ) (opp2 (minus1_is_l is1 is2) x) (opp2 (minus1_is_l is1 is2) y)) . rewrite ( assoc1 y x _ ) . destruct ( pathsinv0 ( isrinvmultwithminus1_is_l is1 is2 is12 x ) ) . unfold unel_is .  rewrite ( runax_is ( pr1 is1 ) y ) . rewrite ( isrinvmultwithminus1_is_l is1 is2 is12 y ) .  apply idpath . apply is2 . apply is12 .  Defined .\n\nDefinition rngmultx0_is { X : hSet } { opp1 opp2 : binop X } ( is : isrngops opp1 opp2 ) := multx0_is_l ( rngop1axs_is is ) ( rngop2axs_is is ) ( rngdistraxs_is is )  .\n\nDefinition rngmult0x_is { X : hSet } { opp1 opp2 : binop X } ( is : isrngops opp1 opp2 ) := mult0x_is_l ( rngop1axs_is is ) ( rngop2axs_is is ) ( rngdistraxs_is is )  .\n\nDefinition rngminus1_is { X : hSet } { opp1 opp2 : binop X } ( is : isrngops opp1 opp2 ) := minus1_is_l ( rngop1axs_is is ) ( rngop2axs_is is ) .\n\nDefinition rngmultwithminus1_is { X : hSet } { opp1 opp2 : binop X } ( is : isrngops opp1 opp2 ) := isminusmultwithminus1_is_l ( rngop1axs_is is ) ( rngop2axs_is is ) ( rngdistraxs_is is ) .\n \nDefinition isrngopstoisrigops ( X : hSet ) ( opp1 opp2 : binop X ) ( is : isrngops opp1 opp2 ) : isrigops opp1 opp2 .\nProof. intros . split . split with ( dirprodpair ( isabgroptoisabmonoidop _ _ ( rngop1axs_is is ) ) ( rngop2axs_is is ) ) . split . simpl .  apply ( rngmult0x_is )  . simpl . apply ( rngmultx0_is ) .  apply ( rngdistraxs_is is ) . Defined . \n\nCoercion isrngopstoisrigops : isrngops >-> isrigops . \n\n\n\n(** *)\n\nDefinition iscommrigops { X : hSet } ( opp1 opp2 : binop X )  :=  dirprod ( isrigops opp1 opp2 ) ( iscomm opp2 ) .\nDefinition pr1iscommrigops ( X : hSet ) ( opp1 opp2 : binop X ) : iscommrigops opp1 opp2 -> isrigops opp1 opp2 := @pr1 _ _ .\nCoercion pr1iscommrigops : iscommrigops >-> isrigops .  \n\nDefinition rigiscommop2_is { X : hSet } { opp1 opp2 : binop X } ( is : iscommrigops opp1 opp2 ) : iscomm opp2 := pr2 is . \n\nLemma isapropiscommrig  { X : hSet } ( opp1 opp2 : binop X ) : isaprop ( iscommrigops opp1 opp2 ) .\nProof . intros . apply ( isofhleveldirprod 1 ) . apply isapropisrigops . apply isapropiscomm . Defined .\n\n\n\n\n\n\n(** *) \n\nDefinition iscommrngops { X : hSet } ( opp1 opp2 : binop X )  :=  dirprod ( isrngops opp1 opp2 ) ( iscomm opp2 ) . \nDefinition pr1iscommrngops ( X : hSet ) ( opp1 opp2 : binop X ) : iscommrngops opp1 opp2 -> isrngops opp1 opp2 := @pr1 _ _ .\nCoercion pr1iscommrngops : iscommrngops >-> isrngops .  \n\nDefinition rngiscommop2_is { X : hSet } { opp1 opp2 : binop X } ( is : iscommrngops opp1 opp2 ) : iscomm opp2 := pr2 is . \n\nLemma isapropiscommrng  { X : hSet } ( opp1 opp2 : binop X ) : isaprop ( iscommrngops opp1 opp2 ) .\nProof . intros . apply ( isofhleveldirprod 1 ) . apply isapropisrngops . apply isapropiscomm . Defined . \n\nDefinition iscommrngopstoiscommrigops ( X : hSet ) ( opp1 opp2 : binop X ) ( is : iscommrngops opp1 opp2 ) : iscommrigops opp1 opp2 := dirprodpair ( isrngopstoisrigops _ _ _ ( pr1 is ) ) ( pr2 is ) .\nCoercion iscommrngopstoiscommrigops : iscommrngops >-> iscommrigops . \n\n\n\n\n(** *** Sets with one binary operation *)\n\n(** **** General definitions *)\n\n\nDefinition setwithbinop := total2 ( fun X : hSet => binop X ) . \nDefinition setwithbinoppair ( X : hSet ) ( opp : binop X ) : setwithbinop := tpair ( fun X : hSet => binop X ) X opp .\nDefinition pr1setwithbinop : setwithbinop -> hSet := @pr1 _ ( fun X : hSet => binop X ) .\nCoercion pr1setwithbinop : setwithbinop >-> hSet .\n\n\nDefinition op { X : setwithbinop } : binop X := pr2 X . \n\nNotation \"x + y\" := ( op x y ) : addoperation_scope .\nNotation \"x * y\" := ( op x y ) : multoperation_scope .  \n\n\n\n(** **** Functions compatible with a binary operation ( homomorphisms ) and their properties *)\n\nDefinition isbinopfun { X Y : setwithbinop } ( f : X -> Y ) := forall x x' : X , paths ( f ( op x x' ) ) ( op ( f x ) ( f x' ) ) . \n\nLemma isapropisbinopfun { X Y : setwithbinop } ( f : X -> Y ) : isaprop ( isbinopfun f ) .\nProof . intros . apply impred . intro x . apply impred . intro x' . apply ( setproperty Y ) . Defined .\n\nDefinition binopfun ( X Y : setwithbinop ) : UU := total2 ( fun f : X -> Y => isbinopfun f ) .\nDefinition binopfunpair { X Y : setwithbinop } ( f : X -> Y ) ( is : isbinopfun f ) : binopfun X Y := tpair _ f is . \nDefinition pr1binopfun ( X Y : setwithbinop ) : binopfun X Y -> ( X -> Y ) := @pr1 _ _ . \nCoercion pr1binopfun : binopfun >-> Funclass . \n\nLemma isasetbinopfun  ( X Y : setwithbinop ) : isaset ( binopfun X Y ) .\nProof . intros . apply ( isasetsubset ( pr1binopfun X Y  ) ) . change ( isofhlevel 2 ( X -> Y ) ) . apply impred .  intro . apply ( setproperty Y ) . apply isinclpr1 .  intro .  apply isapropisbinopfun . Defined .  \n\nLemma isbinopfuncomp { X Y Z : setwithbinop } ( f : binopfun X Y ) ( g : binopfun Y Z ) : isbinopfun ( funcomp ( pr1 f ) ( pr1 g ) ) .\nProof . intros . set ( axf := pr2 f ) . set ( axg := pr2 g ) .  intros a b . unfold funcomp .  rewrite ( axf a b ) . rewrite ( axg ( pr1 f a ) ( pr1 f b ) ) .  apply idpath . Defined .  \n\nOpaque isbinopfuncomp . \n\nDefinition binopfuncomp { X Y Z : setwithbinop } ( f : binopfun X Y ) ( g : binopfun Y Z ) : binopfun X Z := binopfunpair ( funcomp ( pr1 f ) ( pr1 g ) ) ( isbinopfuncomp f g ) . \n\n\nDefinition binopmono ( X Y : setwithbinop ) : UU := total2 ( fun f : incl X Y => isbinopfun ( pr1 f ) ) .\nDefinition binopmonopair { X Y : setwithbinop } ( f : incl X Y ) ( is : isbinopfun f ) : binopmono X Y := tpair _  f is .\nDefinition pr1binopmono ( X Y : setwithbinop ) : binopmono X Y -> incl X Y := @pr1 _ _ .\nCoercion pr1binopmono : binopmono >-> incl .\n\nDefinition binopincltobinopfun ( X Y : setwithbinop ) : binopmono X Y -> binopfun X Y := fun f => binopfunpair ( pr1 ( pr1 f ) ) ( pr2 f ) .\nCoercion binopincltobinopfun : binopmono >-> binopfun . \n\n\nDefinition binopmonocomp { X Y Z : setwithbinop } ( f : binopmono X Y ) ( g : binopmono Y Z ) : binopmono X Z := binopmonopair ( inclcomp ( pr1 f ) ( pr1 g ) ) ( isbinopfuncomp f g ) . \n\nDefinition binopiso ( X Y : setwithbinop ) : UU := total2 ( fun f : weq X Y => isbinopfun f ) .   \nDefinition binopisopair { X Y : setwithbinop } ( f : weq X Y ) ( is : isbinopfun f ) : binopiso X Y := tpair _  f is .\nDefinition pr1binopiso ( X Y : setwithbinop ) : binopiso X Y -> weq X Y := @pr1 _ _ .\nCoercion pr1binopiso : binopiso >-> weq .\n\nDefinition binopisotobinopmono ( X Y : setwithbinop ) : binopiso X Y -> binopmono X Y := fun f => binopmonopair ( pr1 f ) ( pr2 f ) .\nCoercion binopisotobinopmono : binopiso >-> binopmono . \n\nDefinition binopisocomp { X Y Z : setwithbinop } ( f : binopiso X Y ) ( g : binopiso Y Z ) : binopiso X Z := binopisopair ( weqcomp ( pr1 f ) ( pr1 g ) ) ( isbinopfuncomp f g ) .\n\nLemma isbinopfuninvmap { X Y : setwithbinop } ( f : binopiso X Y ) : isbinopfun ( invmap ( pr1 f ) ) . \nProof . intros . set ( axf := pr2 f ) . intros a b .  apply ( invmaponpathsweq ( pr1 f ) ) .  rewrite ( homotweqinvweq ( pr1 f ) ( op a b ) ) . rewrite ( axf (invmap (pr1 f) a) (invmap (pr1 f) b) ) .  rewrite ( homotweqinvweq ( pr1 f ) a ) .   rewrite ( homotweqinvweq ( pr1 f ) b ) .   apply idpath . Defined .\n\nOpaque isbinopfuninvmap .  \n\nDefinition invbinopiso { X Y : setwithbinop } ( f : binopiso X Y ) : binopiso Y X := binopisopair ( invweq ( pr1 f ) ) ( isbinopfuninvmap f ) .\n\n\n\n(** **** Transport of properties of a binary operation  *)\n\n\nLemma isincltwooutof3a { X Y Z : UU } ( f : X -> Y ) ( g : Y -> Z ) ( isg : isincl g ) ( isgf : isincl ( funcomp f g ) ) : isincl f .\nProof . intros . apply ( isofhlevelff 1 f g isgf ) .  apply ( isofhlevelfsnincl 1 g isg ) . Defined .\n\n\nLemma islcancelablemonob { X Y : setwithbinop } ( f : binopmono X Y ) ( x : X ) ( is : islcancelable ( @op Y ) ( f x ) ) : islcancelable ( @op X ) x .\nProof . intros .  unfold islcancelable . apply ( isincltwooutof3a (fun x0 : X => op x x0) f ( pr2 ( pr1 f ) ) ) .    \n\nassert ( h : homot ( funcomp f ( fun y0 : Y => op ( f x ) y0 ) ) (funcomp (fun x0 : X => op x x0) f) ) .  intro x0 .  unfold funcomp .  apply ( pathsinv0 ( ( pr2 f ) x x0 ) ) . \n\napply ( isinclhomot _ _ h ) . apply ( isinclcomp f ( inclpair _ is ) ) .  Defined .\n\n\nLemma isrcancelablemonob { X Y : setwithbinop } ( f : binopmono X Y ) ( x : X ) ( is : isrcancelable ( @op Y ) ( f x ) ) : isrcancelable ( @op X ) x .\nProof . intros .  unfold islcancelable . apply ( isincltwooutof3a (fun x0 : X => op x0 x) f ( pr2 ( pr1 f ) ) ) .    \n\nassert ( h : homot ( funcomp f ( fun y0 : Y => op y0 ( f x ) ) ) (funcomp (fun x0 : X => op x0 x ) f) ) .  intro x0 .  unfold funcomp .  apply ( pathsinv0 ( ( pr2 f ) x0 x ) ) . \n\napply ( isinclhomot _ _ h ) . apply ( isinclcomp f ( inclpair _ is ) ) .  Defined .\n\n\nLemma iscancelablemonob { X Y : setwithbinop } ( f : binopmono X Y ) ( x : X ) ( is : iscancelable ( @op Y ) ( f x ) ) : iscancelable ( @op X ) x . \nProof . intros . apply ( dirprodpair ( islcancelablemonob f x ( pr1 is ) ) ( isrcancelablemonob f x ( pr2 is ) ) ) . Defined .\n\nNotation islcancelableisob := islcancelablemonob . \nNotation isrcancelableisob := isrcancelablemonob . \nNotation iscancelableisob := iscancelablemonob .\n\n\nLemma islinvertibleisob  { X Y : setwithbinop } ( f : binopiso X Y ) ( x : X ) ( is : islinvertible ( @op Y ) ( f x ) ) : islinvertible ( @op X ) x .\nProof . intros .  unfold islinvertible . apply ( twooutof3a (fun x0 : X => op x x0) f ) .     \n\nassert ( h : homot ( funcomp f ( fun y0 : Y => op ( f x ) y0 ) ) (funcomp (fun x0 : X => op x x0) f) ) .  intro x0 .  unfold funcomp .  apply ( pathsinv0 ( ( pr2 f ) x x0 ) ) . \n\napply ( isweqhomot _ _ h ) . apply ( pr2 ( weqcomp f ( weqpair _ is ) ) ) . apply ( pr2 ( pr1 f ) ) . Defined .  \n\nLemma isrinvertibleisob { X Y : setwithbinop } ( f : binopiso X Y ) ( x : X ) ( is : isrinvertible ( @op Y ) ( f x ) ) : isrinvertible ( @op X ) x .\nProof . intros .  unfold islinvertible . apply ( twooutof3a (fun x0 : X => op x0 x) f ) .    \n\nassert ( h : homot ( funcomp f ( fun y0 : Y => op y0 ( f x ) ) ) (funcomp (fun x0 : X => op x0 x ) f) ) .  intro x0 .  unfold funcomp .  apply ( pathsinv0 ( ( pr2 f ) x0 x ) ) . \n\napply ( isweqhomot _ _ h ) . apply ( pr2 ( weqcomp f ( weqpair _ is ) ) ) . apply ( pr2 ( pr1 f ) ) . Defined .\n\n\nLemma isinvertiblemonob { X Y : setwithbinop } ( f : binopiso X Y ) ( x : X ) ( is : isinvertible ( @op Y ) ( f x ) ) : isinvertible ( @op X ) x . \nProof . intros . apply ( dirprodpair ( islinvertibleisob f x ( pr1 is ) ) ( isrinvertibleisob f x ( pr2 is ) ) ) . Defined .\n\n\nDefinition islinvertibleisof  { X Y : setwithbinop } ( f : binopiso X Y ) ( x : X ) ( is : islinvertible ( @op X ) x ) : islinvertible ( @op Y ) ( f x ) .\nProof . intros . unfold islinvertible . apply ( twooutof3b f ) .  apply ( pr2 ( pr1 f ) ) .    \n\nassert ( h : homot ( funcomp ( fun x0 : X => op x x0 ) f ) (fun x0 : X => op (f x) (f x0))  ) .  intro x0 .  unfold funcomp .   apply ( pr2 f x x0 ) .\n\napply ( isweqhomot _ _ h ) . apply ( pr2 ( weqcomp ( weqpair _ is ) f ) ) . Defined .  \n\nDefinition isrinvertibleisof  { X Y : setwithbinop } ( f : binopiso X Y ) ( x : X ) ( is : isrinvertible ( @op X ) x ) : isrinvertible ( @op Y ) ( f x ) .\nProof . intros . unfold isrinvertible . apply ( twooutof3b f ) .  apply ( pr2 ( pr1 f ) ) .    \n\nassert ( h : homot ( funcomp ( fun x0 : X => op x0 x ) f ) (fun x0 : X => op (f x0) (f x) )  ) .  intro x0 .  unfold funcomp .   apply ( pr2 f x0 x ) .\n\napply ( isweqhomot _ _ h ) . apply ( pr2 ( weqcomp ( weqpair _ is ) f ) ) . Defined . \n\nLemma isinvertiblemonof { X Y : setwithbinop } ( f : binopiso X Y ) ( x : X ) ( is : isinvertible ( @op X ) x ) : isinvertible ( @op Y ) ( f x ) . \nProof . intros . apply ( dirprodpair ( islinvertibleisof f x ( pr1 is ) ) ( isrinvertibleisof f x ( pr2 is ) ) ) . Defined .\n\n\nLemma isassocmonob { X Y : setwithbinop } ( f : binopmono X Y ) ( is : isassoc ( @op Y ) ) : isassoc ( @op X ) .\nProof . intros . set ( axf := pr2 f ) .  simpl in axf .  intros a b c . apply ( invmaponpathsincl _ ( pr2 ( pr1 f ) ) ) . rewrite ( axf ( op a b ) c ) .  rewrite ( axf a b ) . rewrite ( axf a ( op b c ) ) . rewrite ( axf b c ) . apply is . Defined .   \n\nOpaque isassocmonob .\n\nLemma iscommmonob { X Y : setwithbinop } ( f : binopmono X Y ) ( is : iscomm ( @op Y ) ) : iscomm ( @op X ) .\nProof . intros . set ( axf := pr2 f ) .  simpl in axf .  intros a b . apply ( invmaponpathsincl _ ( pr2 ( pr1 f ) ) ) . rewrite ( axf a b ) .  rewrite ( axf b a  ) . apply is . Defined .  \n\nOpaque iscommmonob .\n\nNotation isassocisob := isassocmonob .\nNotation iscommisob := iscommmonob . \n\nLemma isassocisof  { X Y : setwithbinop } ( f : binopiso X Y ) ( is : isassoc ( @op X ) ) : isassoc ( @op Y ) .\nProof . intros . apply ( isassocmonob ( invbinopiso f ) is ) . Defined .  \n\nOpaque isassocisof .\n\nLemma iscommisof { X Y : setwithbinop } ( f : binopiso X Y ) ( is : iscomm ( @op X ) ) : iscomm ( @op Y ) .\nProof . intros .  apply ( iscommmonob ( invbinopiso f ) is ) . Defined . \n\nOpaque iscommisof . \n\nLemma isunitisof { X Y : setwithbinop } ( f : binopiso X Y ) ( unx : X ) ( is : isunit ( @op X ) unx ) : isunit ( @op Y ) ( f unx ) .\nProof . intros . set ( axf := pr2 f ) .  split . \n\nintro a . change ( f unx ) with ( pr1 f unx ) . apply ( invmaponpathsweq ( pr1 ( invbinopiso f ) ) ) .  rewrite ( pr2 ( invbinopiso f ) ( pr1 f unx ) a ) . simpl . rewrite ( homotinvweqweq ( pr1 f ) unx ) .  apply ( pr1 is ) .  \n\nintro a . change ( f unx ) with ( pr1 f unx ) . apply ( invmaponpathsweq ( pr1 ( invbinopiso f ) ) ) .  rewrite ( pr2 ( invbinopiso f ) a ( pr1 f unx ) ) . simpl . rewrite ( homotinvweqweq ( pr1 f ) unx ) .  apply ( pr2 is ) . Defined .   \n\nOpaque isunitisof . \n\nDefinition isunitalisof { X Y : setwithbinop } ( f : binopiso X Y ) ( is : isunital ( @op X ) ) : isunital ( @op Y ) := isunitalpair ( f ( pr1 is ) ) ( isunitisof f ( pr1 is ) ( pr2 is ) ) .\n\nLemma isunitisob { X Y : setwithbinop } ( f : binopiso X Y ) ( uny : Y ) ( is : isunit ( @op Y ) uny ) : isunit ( @op X ) ( ( invmap f ) uny ) .\nProof . intros . set ( int := isunitisof ( invbinopiso f ) ) .  simpl . simpl in int . apply int .  apply is .  Defined .\n\nOpaque isunitisob .\n\nDefinition isunitalisob  { X Y : setwithbinop } ( f : binopiso X Y ) ( is : isunital ( @op Y ) ) : isunital ( @op X ) := isunitalpair ( ( invmap f ) ( pr1 is ) ) ( isunitisob f ( pr1 is ) ( pr2 is ) ) .\n\n\nDefinition ismonoidopisof { X Y : setwithbinop } ( f : binopiso X Y ) ( is : ismonoidop ( @op X ) ) : ismonoidop ( @op Y ) := dirprodpair ( isassocisof f ( pr1 is ) ) ( isunitalisof f ( pr2 is ) ) . \n\nDefinition ismonoidopisob { X Y : setwithbinop } ( f : binopiso X Y ) ( is : ismonoidop ( @op Y ) ) : ismonoidop ( @op X ) := dirprodpair ( isassocisob f ( pr1 is ) ) ( isunitalisob f ( pr2 is ) ) . \n\nLemma isinvisof { X Y : setwithbinop } ( f : binopiso X Y ) ( unx : X ) ( invx : X -> X ) ( is : isinv ( @op X ) unx invx ) : isinv ( @op Y ) ( pr1 f unx ) ( funcomp ( invmap ( pr1 f ) ) ( funcomp invx ( pr1 f ) ) ) .\nProof . intros . set ( axf := pr2 f ) . set ( axinvf := pr2 ( invbinopiso f ) ) .  simpl in axf . simpl in axinvf . unfold funcomp . split .\n\nintro a .  apply ( invmaponpathsweq ( pr1 ( invbinopiso f ) ) ) .  simpl . rewrite ( axinvf ( ( pr1 f ) (invx (invmap ( pr1 f ) a))) a ) . rewrite ( homotinvweqweq ( pr1 f ) unx ) .  rewrite ( homotinvweqweq ( pr1 f ) (invx (invmap ( pr1 f ) a)) ) . apply ( pr1 is ) .   \n\nintro a .  apply ( invmaponpathsweq ( pr1 ( invbinopiso f ) ) ) .  simpl . rewrite ( axinvf a ( ( pr1 f ) (invx (invmap ( pr1 f ) a))) ) . rewrite ( homotinvweqweq ( pr1 f ) unx ) .  rewrite ( homotinvweqweq ( pr1 f ) (invx (invmap ( pr1 f ) a)) ) . apply ( pr2 is ) . Defined .      \n\nOpaque isinvisof .\n\nDefinition isgropisof  { X Y : setwithbinop } ( f : binopiso X Y ) ( is : isgrop ( @op X ) ) : isgrop ( @op Y ) :=  tpair _ ( ismonoidopisof f is ) ( tpair _ ( funcomp ( invmap ( pr1 f ) ) ( funcomp ( grinv_is is ) ( pr1 f ) ) ) ( isinvisof f ( unel_is is ) ( grinv_is is ) ( pr2 ( pr2 is ) ) ) ) .  \n\nLemma isinvisob { X Y : setwithbinop } ( f : binopiso X Y ) ( uny : Y ) ( invy : Y -> Y ) ( is : isinv ( @op Y ) uny invy ) : isinv ( @op X ) ( invmap (  pr1 f ) uny ) ( funcomp ( pr1 f ) ( funcomp invy ( invmap ( pr1 f ) ) ) ) .\nProof . intros . apply ( isinvisof ( invbinopiso f ) uny invy is ) . Defined .  \n\nOpaque isinvisob .\n\nDefinition isgropisob  { X Y : setwithbinop } ( f : binopiso X Y ) ( is : isgrop ( @op Y ) ) : isgrop ( @op X ) :=  tpair _ ( ismonoidopisob f is ) ( tpair _  ( funcomp ( pr1 f ) ( funcomp ( grinv_is is ) ( invmap ( pr1 f ) ) ) ) ( isinvisob f ( unel_is is ) ( grinv_is is ) ( pr2 ( pr2 is ) ) ) ) .\n\nDefinition isabmonoidopisof { X Y : setwithbinop } ( f : binopiso X Y ) ( is : isabmonoidop ( @op X ) ) : isabmonoidop ( @op Y ) := tpair _ ( ismonoidopisof f is ) ( iscommisof f ( commax_is is ) )  . \n\nDefinition isabmonoidopisob { X Y : setwithbinop } ( f : binopiso X Y ) ( is : isabmonoidop ( @op Y ) ) : isabmonoidop ( @op X ) := tpair _ ( ismonoidopisob f is ) ( iscommisob f ( commax_is is ) )  .\n\n\nDefinition isabgropisof { X Y : setwithbinop } ( f : binopiso X Y ) ( is : isabgrop ( @op X ) ) : isabgrop ( @op Y ) := tpair _ ( isgropisof f is ) ( iscommisof f ( commax_is is ) )  . \n\nDefinition isabgropisob { X Y : setwithbinop } ( f : binopiso X Y ) ( is : isabgrop ( @op Y ) ) : isabgrop ( @op X ) := tpair _ ( isgropisob f is ) ( iscommisob f ( commax_is is ) )  .\n\n \n\n\n   \n\n\n(** **** Subobjects *)\n\nDefinition issubsetwithbinop { X : hSet } ( opp : binop X ) ( A : hsubtypes X ) := forall a a' : A , A ( opp ( pr1 a ) ( pr1 a' ) ) .\n\nLemma isapropissubsetwithbinop { X : hSet } ( opp : binop X ) ( A : hsubtypes X ) : isaprop ( issubsetwithbinop opp A ) .\nProof .  intros .  apply impred .  intro a . apply impred . intros a' . apply ( pr2 ( A ( opp (pr1 a) (pr1 a')) ) ) . Defined .\n\nDefinition subsetswithbinop { X : setwithbinop } := total2 ( fun A : hsubtypes X => issubsetwithbinop ( @op X ) A ) .\nDefinition subsetswithbinoppair { X : setwithbinop } := tpair ( fun A : hsubtypes X => issubsetwithbinop ( @op X ) A ) . \nDefinition subsetswithbinopconstr { X : setwithbinop } := @subsetswithbinoppair X .  \nDefinition pr1subsetswithbinop ( X : setwithbinop ) : @subsetswithbinop X -> hsubtypes X := @pr1 _ ( fun A : hsubtypes X => issubsetwithbinop ( @op X ) A ) . \nCoercion pr1subsetswithbinop : subsetswithbinop >-> hsubtypes .\n\nDefinition totalsubsetwithbinop ( X : setwithbinop ) : @subsetswithbinop X .\nProof . intros .  split with ( fun x : X => htrue ) . intros x x' .  apply tt . Defined .  \n\n\nDefinition carrierofasubsetwithbinop { X : setwithbinop } ( A : @subsetswithbinop X ) : setwithbinop .\nProof . intros . set ( aset := ( hSetpair ( carrier A ) ( isasetsubset ( pr1carrier A ) ( setproperty X ) ( isinclpr1carrier A ) ) ) : hSet ) . split with aset . \nset ( subopp := ( fun a a' : A => carrierpair A ( op ( pr1carrier _ a ) ( pr1carrier _ a' ) ) ( pr2 A a a' ) ) : ( A -> A -> A ) ) .  simpl . unfold binop . apply subopp .  Defined . \n\nCoercion carrierofasubsetwithbinop : subsetswithbinop >-> setwithbinop . \n\n\n\n\n\n\n(** **** Relations compatible with a binary operation and quotient objects *)\n\nDefinition isbinophrel { X : setwithbinop } ( R : hrel X ) := dirprod ( forall a b c : X , R a b -> R ( op c a ) ( op c b ) ) ( forall a b c : X , R a b -> R ( op a c ) ( op b c ) ) .\n\nDefinition isbinophrellogeqf { X : setwithbinop } { L R : hrel X } ( lg : hrellogeq L R ) ( isl : isbinophrel L ) : isbinophrel R .\nProof . intros . split . intros a b c rab . apply ( ( pr1 ( lg _ _ ) ( ( pr1 isl ) _ _ _ ( pr2 ( lg  _ _ ) rab ) ) ) ) . intros a b c rab .  apply ( ( pr1 ( lg _ _ ) ( ( pr2 isl ) _ _ _ ( pr2 ( lg  _ _ ) rab ) ) ) ) . Defined .     \n\nLemma isapropisbinophrel { X : setwithbinop } ( R : hrel X ) : isaprop ( isbinophrel R ) . \nProof . intros . apply isapropdirprod . apply impred . intro a . apply impred . intro b . apply impred . intro c . apply impred . intro r . apply ( pr2 ( R _ _ ) ) .  apply impred . intro a . apply impred . intro b . apply impred . intro c . apply impred . intro r . apply ( pr2 ( R _ _ ) ) .  Defined .\n  \nLemma isbinophrelif { X : setwithbinop } ( R : hrel X ) ( is : iscomm ( @op X ) ) ( isl : forall a b c : X , R a b -> R ( op c a ) ( op c b ) ) : isbinophrel R . \nProof . intros . split with isl .  intros a b c rab .  destruct ( is c a ) . destruct ( is c b ) . apply ( isl _ _ _ rab ) . Defined .  \n \nLemma iscompbinoptransrel { X : setwithbinop } ( R : hrel X ) ( ist : istrans R )  ( isb : isbinophrel R ) : iscomprelrelfun2 R R ( @op X ) . \nProof . intros . intros a b c d .  intros rab rcd . set ( racbc := pr2 isb a b c rab ) .  set ( rbcbd := pr1 isb c d b rcd ) .  apply ( ist _ _ _ racbc rbcbd ) .  Defined .  \n\nLemma isbinopreflrel { X : setwithbinop } ( R : hrel X ) ( isr : isrefl R )  ( isb : iscomprelrelfun2 R R ( @op X ) ) : isbinophrel R .\nProof . intros . split .   intros a b c rab .  apply ( isb c c a b ( isr c ) rab ) .  intros a b c rab . apply ( isb a b c c rab ( isr c ) ) .  Defined . \n\n\nDefinition binophrel { X : setwithbinop } := total2 ( fun R : hrel X => isbinophrel R ) .\nDefinition binophrelpair { X : setwithbinop } := tpair ( fun R : hrel X => isbinophrel R ) .\nDefinition pr1binophrel ( X : setwithbinop ) : @binophrel X -> hrel X := @pr1 _ ( fun R : hrel X => isbinophrel R ) .\nCoercion pr1binophrel : binophrel >-> hrel . \n\nDefinition binoppo { X : setwithbinop } := total2 ( fun R : po X => isbinophrel R ) .\nDefinition binoppopair { X : setwithbinop } := tpair ( fun R : po X => isbinophrel R ) .\nDefinition pr1binoppo ( X : setwithbinop ) : @binoppo X -> po X := @pr1 _ ( fun R : po X => isbinophrel R ) .\nCoercion pr1binoppo : binoppo >-> po . \n\nDefinition binopeqrel { X : setwithbinop } := total2 ( fun R : eqrel X => isbinophrel R ) .\nDefinition binopeqrelpair { X : setwithbinop } := tpair ( fun R : eqrel X => isbinophrel R ) .\nDefinition pr1binopeqrel ( X : setwithbinop ) : @binopeqrel X -> eqrel X := @pr1 _ ( fun R : eqrel X => isbinophrel R ) .\nCoercion pr1binopeqrel : binopeqrel >-> eqrel . \n\nDefinition setwithbinopquot { X : setwithbinop } ( R : @binopeqrel X ) : setwithbinop .\nProof . intros . split with ( setquotinset R )  .  set ( qt  := setquot R ) . set ( qtset := setquotinset R ) .  \nassert ( iscomp : iscomprelrelfun2 R R op ) . apply ( iscompbinoptransrel R ( eqreltrans R ) ( pr2 R ) ) .\nset ( qtmlt := setquotfun2 R R op iscomp ) .   simpl . unfold binop . apply qtmlt . Defined . \n\n\nDefinition ispartbinophrel { X : setwithbinop } ( S : hsubtypes X ) ( R : hrel X ) := dirprod ( forall a b c : X , S c -> R a b -> R ( op c a ) ( op c b ) ) ( forall a b c : X , S c -> R a b -> R ( op a c ) ( op b c ) ) .\n\nDefinition isbinoptoispartbinop { X : setwithbinop } ( S : hsubtypes X ) ( L : hrel X ) ( is : isbinophrel L ) : ispartbinophrel S L .\nProof . intros X S L .  unfold isbinophrel . unfold ispartbinophrel . intro d2 .  split .  intros a b c is .  apply ( pr1 d2 a b c ) . intros a b c is . apply ( pr2 d2 a b c ) . Defined .  \n\nDefinition ispartbinophrellogeqf { X : setwithbinop } ( S : hsubtypes X ) { L R : hrel X } ( lg : hrellogeq L R ) ( isl : ispartbinophrel S L ) : ispartbinophrel S R .\nProof . intros . split . intros a b c is rab .  apply ( ( pr1 ( lg _ _ ) ( ( pr1 isl ) _ _ _ is ( pr2 ( lg _ _ ) rab ) ) ) ) . intros a b c is rab .  apply ( ( pr1 ( lg _ _ ) ( ( pr2 isl ) _ _ _ is ( pr2 ( lg  _ _ ) rab ) ) ) ) . Defined .    \n\nLemma ispartbinophrelif { X : setwithbinop } ( S : hsubtypes X ) ( R : hrel X ) ( is : iscomm ( @op X ) ) ( isl : forall a b c : X , S c -> R a b -> R ( op c a ) ( op c b ) ) : ispartbinophrel S R .\nProof . intros .  split with isl .  intros a b c s rab .  destruct ( is c a ) . destruct ( is c b ) . apply ( isl _ _ _ s rab ) . Defined .  \n  \n\n\n(** **** Relations inversely compatible with a binary operation *)\n\nDefinition isinvbinophrel { X : setwithbinop } ( R : hrel X ) := dirprod ( forall a b c : X , R ( op c a ) ( op c b ) ->  R a b ) ( forall a b c : X , R ( op a c ) ( op b c ) -> R a b ) .\n\nDefinition isinvbinophrellogeqf { X : setwithbinop } { L R : hrel X } ( lg : hrellogeq L R ) ( isl : isinvbinophrel L ) : isinvbinophrel R .\nProof . intros . split . intros a b c rab . apply ( ( pr1 ( lg _ _ ) ( ( pr1 isl ) _ _ _ ( pr2 ( lg  _ _ ) rab ) ) ) ) . intros a b c rab .  apply ( ( pr1 ( lg _ _ ) ( ( pr2 isl ) _ _ _ ( pr2 ( lg  _ _ ) rab ) ) ) ) . Defined .  \n\nLemma isapropisinvbinophrel { X : setwithbinop } ( R : hrel X ) : isaprop ( isinvbinophrel R ) . \nProof . intros . apply isapropdirprod . apply impred . intro a . apply impred . intro b . apply impred . intro c . apply impred . intro r . apply ( pr2 ( R _ _ ) ) .  apply impred . intro a . apply impred . intro b . apply impred . intro c . apply impred . intro r . apply ( pr2 ( R _ _ ) ) .  Defined .     \n\nLemma isinvbinophrelif { X : setwithbinop } ( R : hrel X ) ( is : iscomm ( @op X ) ) ( isl : forall a b c : X ,  R ( op c a ) ( op c b ) -> R a b ) : isinvbinophrel R . \nProof . intros . split with isl .  intros a b c rab .  destruct ( is c a ) . destruct ( is c b ) . apply ( isl _ _ _ rab ) . Defined . \n\n\n\n \n \nDefinition ispartinvbinophrel { X : setwithbinop } ( S : hsubtypes X ) ( R : hrel X ) := dirprod ( forall a b c : X , S c -> R ( op c a ) ( op c b ) -> R a b ) ( forall  a b c : X  , S c -> R ( op a c ) ( op b c ) -> R a b ) .\n\nDefinition isinvbinoptoispartinvbinop { X : setwithbinop } ( S : hsubtypes X ) ( L : hrel X ) ( is : isinvbinophrel L ) : ispartinvbinophrel S L .\nProof . intros X S L .  unfold isinvbinophrel . unfold ispartinvbinophrel . intro d2 .  split .  intros a b c s .  apply ( pr1 d2 a b c ) . intros a b c s . apply ( pr2 d2 a b c ) . Defined .  \n\nDefinition ispartinvbinophrellogeqf { X : setwithbinop } ( S : hsubtypes X ) { L R : hrel X } ( lg : hrellogeq L R ) ( isl : ispartinvbinophrel S L ) : ispartinvbinophrel S R .\nProof . intros . split . intros a b c s rab . apply ( ( pr1 ( lg _ _ ) ( ( pr1 isl ) _ _ _ s ( pr2 ( lg  _ _ ) rab ) ) ) ) . intros a b c s rab .  apply ( ( pr1 ( lg _ _ ) ( ( pr2 isl ) _ _ _ s ( pr2 ( lg  _ _ ) rab ) ) ) ) . Defined .  \n\nLemma ispartinvbinophrelif { X : setwithbinop } ( S : hsubtypes X ) ( R : hrel X ) ( is : iscomm ( @op X ) ) ( isl : forall a b c : X , S c -> R ( op c a ) ( op c b ) -> R a b ) : ispartinvbinophrel S R .\nProof . intros .  split with isl .  intros a b c s rab .  destruct ( is c a ) . destruct ( is c b ) . apply ( isl _ _ _ s rab ) . Defined .   \n\n\n(** **** Homomorphisms and relations *)\n\nLemma binophrelandfun { X Y : setwithbinop } ( f : binopfun X Y ) ( R : hrel Y ) ( is : @isbinophrel Y R ) : @isbinophrel X ( fun x x' => R ( f x ) ( f x' ) ) . \nProof . intros . set ( ish := ( pr2 f ) : forall a0 b0 , paths ( f ( op a0 b0 ) ) ( op ( f a0 ) ( f b0 ) ) ) . split . \n\nintros a b c r . rewrite ( ish _ _ ) .   rewrite ( ish _ _ ) .  apply ( pr1 is ) . apply r . \n\nintros a b c r . rewrite ( ish _ _ ) .   rewrite ( ish _ _ ) .  apply ( pr2 is ) . apply r . Defined . \n\n\nLemma ispartbinophrelandfun { X Y : setwithbinop } ( f : binopfun X Y ) ( SX : hsubtypes X ) ( SY : hsubtypes Y ) ( iss : forall x : X , ( SX x ) -> ( SY ( f x ) ) ) ( R : hrel Y ) ( is : @ispartbinophrel Y SY R ) : @ispartbinophrel X SX ( fun x x' => R ( f x ) ( f x' ) ) . \nProof . intros . set ( ish := ( pr2 f ) : forall a0 b0 , paths ( f ( op a0 b0 ) ) ( op ( f a0 ) ( f b0 ) ) ) . split . \n\nintros a b c s r . rewrite ( ish _ _ ) .   rewrite ( ish _ _ ) .  apply ( ( pr1 is ) _ _ _ ( iss _ s ) r ) .  \n\nintros a b c s r . rewrite ( ish _ _ ) .   rewrite ( ish _ _ ) .  apply ( ( pr2 is ) _ _ _ ( iss _ s ) r ) . Defined .  \n\nLemma invbinophrelandfun { X Y : setwithbinop } ( f : binopfun X Y ) ( R : hrel Y ) ( is : @isinvbinophrel Y R ) : @isinvbinophrel X ( fun x x' => R ( f x ) ( f x' ) ) .\nProof . intros .  set ( ish := ( pr2 f ) : forall a0 b0 , paths ( f ( op a0 b0 ) ) ( op ( f a0 ) ( f b0 ) ) ) . split . \n\nintros a b c r . rewrite ( ish _ _ ) in r .   rewrite ( ish _ _ ) in r .  apply ( ( pr1 is ) _ _ _ r ) .  \n\nintros a b c r . rewrite ( ish _ _ ) in r .   rewrite ( ish _ _ ) in r .  apply ( ( pr2 is ) _ _ _ r ) . Defined . \n \n\nLemma ispartinvbinophrelandfun { X Y : setwithbinop } ( f : binopfun X Y ) ( SX : hsubtypes X ) ( SY : hsubtypes Y ) ( iss : forall x : X , ( SX x ) -> ( SY ( f x ) ) ) ( R : hrel Y ) ( is : @ispartinvbinophrel Y SY R ) : @ispartinvbinophrel X SX ( fun x x' => R ( f x ) ( f x' ) ) . \nProof . intros .  set ( ish := ( pr2 f ) : forall a0 b0 , paths ( f ( op a0 b0 ) ) ( op ( f a0 ) ( f b0 ) ) ) . split . \n\nintros a b c s r . rewrite ( ish _ _ ) in r .   rewrite ( ish _ _ ) in r .  apply ( ( pr1 is ) _ _ _ ( iss _ s ) r ) .  \n\nintros a b c s r . rewrite ( ish _ _ ) in r .   rewrite ( ish _ _ ) in r .  apply ( ( pr2 is ) _ _ _ ( iss _ s ) r ) . Defined . \n\n\n(** **** Quotient relations *)\n\nLemma isbinopquotrel { X : setwithbinop } ( R : @binopeqrel X ) { L : hrel X } ( is : iscomprelrel R L ) ( isl : isbinophrel L ) : @isbinophrel ( setwithbinopquot R ) ( quotrel is ) . \nProof .  intros .  unfold isbinophrel .   split . assert ( int : forall a b c :  setwithbinopquot R , isaprop ( quotrel is a b -> quotrel is (op c a ) (op c b ) ) ) . intros a b c .  apply impred . intro .  apply ( pr2 ( quotrel is _ _ ) ) .  apply ( setquotuniv3prop R ( fun a b c => hProppair _ ( int a b c ) ) ) . exact ( pr1 isl )  . \n assert ( int : forall a b c :  setwithbinopquot R , isaprop ( quotrel is a b -> quotrel is (op a c ) (op b c ) ) ) . intros a b c .  apply impred . intro .  apply ( pr2 ( quotrel is _ _ ) ) .  apply ( setquotuniv3prop R ( fun a b c => hProppair _ ( int a b c ) ) ) . exact ( pr2 isl )  . Defined .  \n\n\n\n(** **** Direct products *)\n\nDefinition setwithbinopdirprod ( X Y : setwithbinop ) : setwithbinop .\nProof . intros . split with ( setdirprod X Y ) . unfold binop .  simpl . apply ( fun xy xy' : _ => dirprodpair ( op ( pr1 xy ) ( pr1 xy' ) ) ( op ( pr2 xy ) ( pr2 xy' ) ) ) . Defined .  \n\n\n\n\n\n\n(** *** Sets with two binary operations *)\n\n(** **** General definitions *)\n\n\nDefinition setwith2binop := total2 ( fun X : hSet => dirprod ( binop X ) ( binop X ) ) . \nDefinition setwith2binoppair ( X : hSet ) ( opps : dirprod ( binop X ) ( binop X ) ) : setwith2binop := tpair ( fun X : hSet => dirprod ( binop X ) ( binop X ) ) X opps .\nDefinition pr1setwith2binop : setwith2binop -> hSet := @pr1 _ ( fun X : hSet => dirprod ( binop X ) ( binop X ) ) .\nCoercion pr1setwith2binop : setwith2binop >-> hSet . \n\nDefinition op1 { X : setwith2binop } : binop X := pr1 ( pr2 X ) .\nDefinition op2 { X : setwith2binop } : binop X := pr2 ( pr2 X ) .\n\nDefinition setwithbinop1 ( X : setwith2binop ) : setwithbinop := setwithbinoppair ( pr1 X ) ( @op1 X ) . \nDefinition setwithbinop2 ( X : setwith2binop ) : setwithbinop := setwithbinoppair ( pr1 X ) ( @op2 X ) . \n\nNotation \"x + y\" := ( op1 x y ) : twobinops_scope .\nNotation \"x * y\" := ( op2 x y ) : twobinops_scope .   \n\n\n(** **** Functions compatible with a pair of binary operation ( homomorphisms ) and their properties *)\n\nDefinition istwobinopfun { X Y : setwith2binop } ( f : X -> Y ) := dirprod ( forall x x' : X , paths ( f ( op1 x x' ) ) ( op1 ( f x ) ( f x' ) ) ) ( forall x x' : X , paths ( f ( op2 x x' ) ) ( op2 ( f x ) ( f x' ) ) )  . \n\nLemma isapropistwobinopfun { X Y : setwith2binop } ( f : X -> Y ) : isaprop ( istwobinopfun f ) .\nProof . intros . apply isofhleveldirprod . apply impred . intro x . apply impred . intro x' . apply ( setproperty Y ) . apply impred . intro x . apply impred . intro x' . apply ( setproperty Y ) . Defined .\n\nDefinition twobinopfun ( X Y : setwith2binop ) : UU := total2 ( fun f : X -> Y => istwobinopfun f ) .\nDefinition twobinopfunpair { X Y : setwith2binop } ( f : X -> Y ) ( is : istwobinopfun f ) : twobinopfun X Y := tpair _ f is . \nDefinition pr1twobinopfun ( X Y : setwith2binop ) : twobinopfun X Y -> ( X -> Y ) := @pr1 _ _ . \nCoercion pr1twobinopfun : twobinopfun >-> Funclass .\n\nDefinition binop1fun { X Y : setwith2binop } ( f : twobinopfun X Y ) : binopfun ( setwithbinop1 X ) ( setwithbinop1 Y ) := @binopfunpair ( setwithbinop1 X ) ( setwithbinop1 Y ) ( pr1 f ) ( pr1 ( pr2 f ) ) .\n\nDefinition binop2fun { X Y : setwith2binop } ( f : twobinopfun X Y ) : binopfun ( setwithbinop2 X ) ( setwithbinop2 Y ) := @binopfunpair ( setwithbinop2 X ) ( setwithbinop2 Y ) ( pr1 f ) ( pr2 ( pr2 f ) ) .  \nLemma isasettwobinopfun  ( X Y : setwith2binop ) : isaset ( twobinopfun X Y ) .\nProof . intros . apply ( isasetsubset ( pr1twobinopfun X Y  ) ) . change ( isofhlevel 2 ( X -> Y ) ) . apply impred .  intro . apply ( setproperty Y ) . apply isinclpr1 .  intro .  apply isapropistwobinopfun . Defined . \n \n\nLemma istwobinopfuncomp { X Y Z : setwith2binop } ( f : twobinopfun X Y ) ( g : twobinopfun Y Z ) : istwobinopfun ( funcomp ( pr1 f ) ( pr1 g ) ) .\nProof . intros . set ( ax1f := pr1 ( pr2 f ) ) . set ( ax2f := pr2 ( pr2 f ) ) . set ( ax1g := pr1 ( pr2 g ) ) . set ( ax2g := pr2 ( pr2 g ) ) .  split.\n\nintros a b . unfold funcomp .  rewrite ( ax1f a b ) . rewrite ( ax1g ( pr1 f a ) ( pr1 f b ) ) .  apply idpath .\nintros a b . unfold funcomp .  rewrite ( ax2f a b ) . rewrite ( ax2g ( pr1 f a ) ( pr1 f b ) ) .  apply idpath . Defined . \n \nOpaque istwobinopfuncomp . \n\nDefinition twobinopfuncomp { X Y Z : setwith2binop } ( f : twobinopfun X Y ) ( g : twobinopfun Y Z ) : twobinopfun X Z := twobinopfunpair ( funcomp ( pr1 f ) ( pr1 g ) ) ( istwobinopfuncomp f g ) . \n\n\nDefinition twobinopmono ( X Y : setwith2binop ) : UU := total2 ( fun f : incl X Y => istwobinopfun f ) .\nDefinition twobinopmonopair { X Y : setwith2binop } ( f : incl X Y ) ( is : istwobinopfun f ) : twobinopmono X Y := tpair _  f is .\nDefinition pr1twobinopmono ( X Y : setwith2binop ) : twobinopmono X Y -> incl X Y := @pr1 _ _ .\nCoercion pr1twobinopmono : twobinopmono >-> incl .\n\nDefinition twobinopincltotwobinopfun ( X Y : setwith2binop ) : twobinopmono X Y -> twobinopfun X Y := fun f => twobinopfunpair ( pr1 ( pr1 f ) ) ( pr2 f ) .\nCoercion twobinopincltotwobinopfun : twobinopmono >-> twobinopfun . \n\nDefinition binop1mono { X Y : setwith2binop } ( f : twobinopmono X Y ) : binopmono ( setwithbinop1 X ) ( setwithbinop1 Y ) := @binopmonopair ( setwithbinop1 X ) ( setwithbinop1 Y ) ( pr1 f ) ( pr1 ( pr2 f ) ) .\n\nDefinition binop2mono { X Y : setwith2binop } ( f : twobinopmono X Y ) : binopmono ( setwithbinop2 X ) ( setwithbinop2 Y ) := @binopmonopair ( setwithbinop2 X ) ( setwithbinop2 Y ) ( pr1 f ) ( pr2 ( pr2 f ) ) .  \n\nDefinition twobinopmonocomp { X Y Z : setwith2binop } ( f : twobinopmono X Y ) ( g : twobinopmono Y Z ) : twobinopmono X Z := twobinopmonopair ( inclcomp ( pr1 f ) ( pr1 g ) ) ( istwobinopfuncomp f g ) . \n\nDefinition twobinopiso ( X Y : setwith2binop ) : UU := total2 ( fun f : weq X Y => istwobinopfun f ) .   \nDefinition twobinopisopair { X Y : setwith2binop } ( f : weq X Y ) ( is : istwobinopfun f ) : twobinopiso X Y := tpair _  f is .\nDefinition pr1twobinopiso ( X Y : setwith2binop ) : twobinopiso X Y -> weq X Y := @pr1 _ _ .\nCoercion pr1twobinopiso : twobinopiso >-> weq .\n\nDefinition twobinopisototwobinopmono ( X Y : setwith2binop ) : twobinopiso X Y -> twobinopmono X Y := fun f => twobinopmonopair ( pr1 f ) ( pr2 f ) .\nCoercion twobinopisototwobinopmono : twobinopiso >-> twobinopmono . \n\nDefinition binop1iso { X Y : setwith2binop } ( f : twobinopiso X Y ) : binopiso ( setwithbinop1 X ) ( setwithbinop1 Y ) := @binopisopair ( setwithbinop1 X ) ( setwithbinop1 Y ) ( pr1 f ) ( pr1 ( pr2 f ) ) .\n\nDefinition binop2iso { X Y : setwith2binop } ( f : twobinopiso X Y ) : binopiso ( setwithbinop2 X ) ( setwithbinop2 Y ) := @binopisopair ( setwithbinop2 X ) ( setwithbinop2 Y ) ( pr1 f ) ( pr2 ( pr2 f ) ) .  \nDefinition twobinopisocomp { X Y Z : setwith2binop } ( f : twobinopiso X Y ) ( g : twobinopiso Y Z ) : twobinopiso X Z := twobinopisopair ( weqcomp ( pr1 f ) ( pr1 g ) ) ( istwobinopfuncomp f g ) .\n\nLemma istwobinopfuninvmap { X Y : setwith2binop } ( f : twobinopiso X Y ) : istwobinopfun ( invmap ( pr1 f ) ) . \nProof . intros . set ( ax1f := pr1 ( pr2 f ) ) . set ( ax2f := pr2 ( pr2 f ) ) . split .\n\n\nintros a b .  apply ( invmaponpathsweq ( pr1 f ) ) .  rewrite ( homotweqinvweq ( pr1 f ) ( op1 a b ) ) .   rewrite ( ax1f (invmap (pr1 f) a) (invmap (pr1 f) b) ) .  rewrite ( homotweqinvweq ( pr1 f ) a ) .   rewrite ( homotweqinvweq ( pr1 f ) b ) .   apply idpath .\nintros a b .  apply ( invmaponpathsweq ( pr1 f ) ) .  rewrite ( homotweqinvweq ( pr1 f ) ( op2 a b ) ) . rewrite ( ax2f (invmap (pr1 f) a) (invmap (pr1 f) b) ) .  rewrite ( homotweqinvweq ( pr1 f ) a ) .   rewrite ( homotweqinvweq ( pr1 f ) b ) .   apply idpath . Defined .\n\nOpaque istwobinopfuninvmap .  \n\nDefinition invtwobinopiso { X Y : setwith2binop } ( f : twobinopiso X Y ) : twobinopiso Y X := twobinopisopair ( invweq ( pr1 f ) ) ( istwobinopfuninvmap f ) .\n\n\n\n\n\n(** **** Transport of properties of a pair binary operations *)\n\nLemma isldistrmonob { X Y : setwith2binop } ( f : twobinopmono X Y ) ( is : isldistr ( @op1 Y ) ( @op2 Y ) ) : isldistr ( @op1 X ) ( @op2 X ) .\nProof . intros .   set ( ax1f := pr1 ( pr2 f ) ) .   set ( ax2f := pr2 ( pr2 f )  ) .   intros a b c . apply ( invmaponpathsincl _ ( pr2 ( pr1 f ) ) ) .  change ( paths ( (pr1 f) (op2 c (op1 a b)))\n     ( (pr1 f) (op1 (op2 c a) (op2 c b))) ) . rewrite ( ax2f c ( op1 a b ) ) . rewrite ( ax1f a b ) .   rewrite ( ax1f ( op2 c a ) ( op2 c b ) ) . rewrite ( ax2f c a ) . rewrite ( ax2f c b ) .  apply is .  Defined . \n\nOpaque isldistrmonob .\n\n\nLemma isrdistrmonob { X Y : setwith2binop } ( f : twobinopmono X Y ) ( is : isrdistr ( @op1 Y ) ( @op2 Y ) ) : isrdistr ( @op1 X ) ( @op2 X ) .\nProof . intros .  set ( ax1f := pr1 ( pr2 f ) ) .   set ( ax2f := pr2 ( pr2 f ) ) .  intros a b c . apply ( invmaponpathsincl _ ( pr2 ( pr1 f ) ) ) . change ( paths ( (pr1 f) (op2 (op1 a b) c))\n     ( (pr1 f) (op1 (op2 a c) (op2 b c))) ) .  rewrite ( ax2f ( op1 a b ) c ) . rewrite ( ax1f a b ) .   rewrite ( ax1f ( op2 a c ) ( op2 b c ) ) . rewrite ( ax2f a c ) . rewrite ( ax2f b c ) .  apply is .  Defined . \n\nOpaque isrdistrmonob .\n\nDefinition isdistrmonob { X Y : setwith2binop } ( f : twobinopmono X Y ) ( is : isdistr ( @op1 Y ) ( @op2 Y ) ) : isdistr ( @op1 X ) ( @op2 X ) := dirprodpair ( isldistrmonob f ( pr1 is ) ) ( isrdistrmonob f ( pr2 is ) ) .\n\nNotation isldistrisob := isldistrmonob .\nNotation isrdistrisob := isrdistrmonob .\nNotation isdistrisob := isdistrmonob .\n\nLemma isldistrisof  { X Y : setwith2binop } ( f : twobinopiso X Y ) ( is : isldistr ( @op1 X ) ( @op2 X ) ) : isldistr ( @op1 Y ) ( @op2 Y ) .\nProof . intros . apply ( isldistrisob ( invtwobinopiso f ) is ) . Defined .   \n\nLemma isrdistrisof  { X Y : setwith2binop } ( f : twobinopiso X Y ) ( is : isrdistr ( @op1 X ) ( @op2 X ) ) : isrdistr ( @op1 Y ) ( @op2 Y ) .\nProof . intros . apply ( isrdistrisob ( invtwobinopiso f ) is ) . Defined . \n\nLemma isdistrisof  { X Y : setwith2binop } ( f : twobinopiso X Y ) ( is : isdistr ( @op1 X ) ( @op2 X ) ) : isdistr ( @op1 Y ) ( @op2 Y ) .\nProof . intros . apply ( isdistrisob ( invtwobinopiso f ) is ) . Defined . \n\n\nDefinition isrigopsisof { X Y : setwith2binop } ( f : twobinopiso X Y ) ( is : isrigops ( @op1 X ) ( @op2 X ) ) : isrigops ( @op1 Y ) ( @op2 Y ) .\nProof . intros. split . split with ( dirprodpair ( isabmonoidopisof ( binop1iso f ) ( rigop1axs_is is ) ) ( ismonoidopisof ( binop2iso f ) ( rigop2axs_is is ) ) ) . simpl .   change (unel_is (ismonoidopisof (binop1iso f) (rigop1axs_is is))) with ( (pr1 f ) ( rigunel1_is is ) ) .  split .  intro y . rewrite ( pathsinv0 ( homotweqinvweq f y ) ) . rewrite ( pathsinv0 ( ( pr2 ( pr2 f ) ) _ _ ) ) . apply ( maponpaths ( pr1 f ) ) .  apply ( rigmult0x_is is ) .    intro y . rewrite ( pathsinv0 ( homotweqinvweq f y ) ) . rewrite ( pathsinv0 ( ( pr2 ( pr2 f ) ) _ _ ) ) . apply ( maponpaths ( pr1 f ) ) .  apply ( rigmultx0_is is ) . apply ( isdistrisof f ) .  apply ( rigdistraxs_is is ) .  Defined . \n\nDefinition isrigopsisob { X Y : setwith2binop } ( f : twobinopiso X Y ) ( is : isrigops ( @op1 Y ) ( @op2 Y ) ) : isrigops ( @op1 X ) ( @op2 X ) .\nProof. intros . apply ( isrigopsisof ( invtwobinopiso f ) is ) . Defined . \n\n\nDefinition isrngopsisof { X Y : setwith2binop } ( f : twobinopiso X Y ) ( is : isrngops ( @op1 X ) ( @op2 X ) ) : isrngops ( @op1 Y ) ( @op2 Y ) := dirprodpair ( dirprodpair ( isabgropisof ( binop1iso f ) ( rngop1axs_is is ) ) ( ismonoidopisof ( binop2iso f ) ( rngop2axs_is is ) ) ) ( isdistrisof f ( pr2 is ) ) .\n\nDefinition isrngopsisob { X Y : setwith2binop } ( f : twobinopiso X Y ) ( is : isrngops ( @op1 Y ) ( @op2 Y ) ) : isrngops ( @op1 X ) ( @op2 X ) := dirprodpair ( dirprodpair ( isabgropisob ( binop1iso f ) ( rngop1axs_is is ) ) ( ismonoidopisob ( binop2iso f ) ( rngop2axs_is is ) ) ) ( isdistrisob f ( pr2 is ) ) .\n\n\nDefinition iscommrngopsisof { X Y : setwith2binop } ( f : twobinopiso X Y ) ( is : iscommrngops ( @op1 X ) ( @op2 X ) ) : iscommrngops ( @op1 Y ) ( @op2 Y ) := dirprodpair ( isrngopsisof f is ) ( iscommisof ( binop2iso f ) ( pr2 is ) ) .\n\nDefinition iscommrngopsisob { X Y : setwith2binop } ( f : twobinopiso X Y ) ( is : iscommrngops ( @op1 Y ) ( @op2 Y ) ) : iscommrngops ( @op1 X ) ( @op2 X ) := dirprodpair ( isrngopsisob f is ) ( iscommisob ( binop2iso f ) ( pr2 is ) ) .\n\n\n\n\n(** **** Subobjects *)\n\nDefinition issubsetwith2binop { X : setwith2binop } ( A : hsubtypes X ) := dirprod ( forall a a' : A , A ( op1 ( pr1 a ) ( pr1 a' ) ) ) ( forall a a' : A , A ( op2 ( pr1 a ) ( pr1 a' ) ) ) .\n\nLemma isapropissubsetwith2binop { X : setwith2binop } ( A : hsubtypes X ) : isaprop ( issubsetwith2binop A ) .\nProof . intros . apply ( isofhleveldirprod 1 ) .\n apply impred .  intro a . apply impred . intros a' . apply ( pr2 ( A ( op1 (pr1 a) (pr1 a')) ) ) .  apply impred .  intro a . apply impred . intros a' . apply ( pr2 ( A ( op2 (pr1 a) (pr1 a')) ) ) .  Defined .\n\nDefinition subsetswith2binop { X : setwith2binop } := total2 ( fun A : hsubtypes X => issubsetwith2binop A ) .\nDefinition subsetswith2binoppair { X : setwith2binop } := tpair ( fun A : hsubtypes X => issubsetwith2binop A ) . \nDefinition subsetswith2binopconstr { X : setwith2binop } := @subsetswith2binoppair X .  \nDefinition pr1subsetswith2binop ( X : setwith2binop ) : @subsetswith2binop X -> hsubtypes X := @pr1 _ ( fun A : hsubtypes X => issubsetwith2binop A ) . \nCoercion pr1subsetswith2binop : subsetswith2binop >-> hsubtypes .\n\nDefinition totalsubsetwith2binop ( X : setwith2binop ) : @subsetswith2binop X .\nProof . intros .  split with ( fun x : X => htrue ) . split . intros x x' .  apply tt .  intros . apply tt . Defined .  \n\n\nDefinition carrierofsubsetwith2binop { X : setwith2binop } ( A : @subsetswith2binop X ) : setwith2binop .\nProof . intros . set ( aset := ( hSetpair ( carrier A ) ( isasetsubset ( pr1carrier A ) ( setproperty X ) ( isinclpr1carrier A ) ) ) : hSet ) . split with aset . \nset ( subopp1 := ( fun a a' : A => carrierpair A ( op1 ( pr1carrier _ a ) ( pr1carrier _ a' ) ) ( pr1 ( pr2 A ) a a' ) ) : ( A -> A -> A ) ) . \nset ( subopp2 := ( fun a a' : A => carrierpair A ( op2 ( pr1carrier _ a ) ( pr1carrier _ a' ) ) ( pr2 ( pr2 A ) a a' ) ) : ( A -> A -> A ) ) .\nsimpl .  apply ( dirprodpair subopp1 subopp2 ) .  Defined . \n\nCoercion carrierofsubsetwith2binop : subsetswith2binop >-> setwith2binop . \n\n\n(** **** Quotient objects *)\n\nDefinition is2binophrel { X : setwith2binop } ( R : hrel X ) := dirprod ( @isbinophrel ( setwithbinop1 X ) R ) ( @isbinophrel ( setwithbinop2 X ) R ) . \n\nLemma isapropis2binophrel { X : setwith2binop } ( R : hrel X ) : isaprop ( is2binophrel R ) . \nProof . intros . apply ( isofhleveldirprod 1 ) .  apply isapropisbinophrel . apply isapropisbinophrel .  \nDefined .    \n\nLemma iscomp2binoptransrel { X : setwith2binop } ( R : hrel X ) ( is : istrans R ) ( isb : is2binophrel R ) : dirprod ( iscomprelrelfun2 R R ( @op1 X ) ) ( iscomprelrelfun2 R R ( @op2 X ) ) .\nProof . intros . split . apply ( @iscompbinoptransrel ( setwithbinop1 X ) R is ( pr1 isb ) ) . apply ( @iscompbinoptransrel ( setwithbinop2 X ) R is ( pr2 isb ) ) .  Defined .\n\n\nDefinition twobinophrel { X : setwith2binop } := total2 ( fun R : hrel X => is2binophrel R ) .\nDefinition twobinophrelpair { X : setwith2binop } := tpair ( fun R : hrel X => is2binophrel R ) .\nDefinition pr1twobinophrel ( X : setwith2binop ) : @twobinophrel X -> hrel X := @pr1 _ ( fun R : hrel X => is2binophrel R ) .\nCoercion pr1twobinophrel : twobinophrel >-> hrel . \n\nDefinition twobinoppo { X : setwith2binop } := total2 ( fun R : po X => is2binophrel R ) .\nDefinition twobinoppopair { X : setwith2binop } := tpair ( fun R : po X => is2binophrel R ) .\nDefinition pr1twobinoppo ( X : setwith2binop ) : @twobinoppo X -> po X := @pr1 _ ( fun R : po X => is2binophrel R ) .\nCoercion pr1twobinoppo : twobinoppo >-> po . \n\nDefinition twobinopeqrel { X : setwith2binop } := total2 ( fun R : eqrel X => is2binophrel R ) .\nDefinition twobinopeqrelpair { X : setwith2binop } := tpair ( fun R : eqrel X => is2binophrel R ) .\nDefinition pr1twobinopeqrel ( X : setwith2binop ) : @twobinopeqrel X -> eqrel X := @pr1 _ ( fun R : eqrel X => is2binophrel R ) .\nCoercion pr1twobinopeqrel : twobinopeqrel >-> eqrel . \n\nDefinition setwith2binopquot { X : setwith2binop } ( R : @twobinopeqrel X ) : setwith2binop .\nProof . intros . split with ( setquotinset R )  .  set ( qt  := setquot R ) . set ( qtset := setquotinset R ) .  \nassert ( iscomp1 : iscomprelrelfun2 R R ( @op1 X ) ) . apply ( pr1 ( iscomp2binoptransrel ( pr1 R ) ( eqreltrans _ ) ( pr2 R ) ) ) .  set ( qtop1 := setquotfun2 R R ( @op1 X ) iscomp1 ) .   \nassert ( iscomp2 : iscomprelrelfun2 R R ( @op2 X ) ) . apply ( pr2 ( iscomp2binoptransrel ( pr1 R ) ( eqreltrans _ ) ( pr2 R ) ) ) .  set ( qtop2 := setquotfun2 R R ( @op2 X ) iscomp2 ) .  \nsimpl . apply ( dirprodpair qtop1 qtop2 )  . Defined . \n\n\n(** **** Direct products *)\n\nDefinition setwith2binopdirprod ( X Y : setwith2binop ) : setwith2binop .\nProof . intros . split with ( setdirprod X Y ) . simpl . apply ( dirprodpair ( fun xy xy' : _ => dirprodpair ( op1 ( pr1 xy ) ( pr1 xy' ) ) ( op1 ( pr2 xy ) ( pr2 xy' ) ) ) ( fun xy xy' : _ => dirprodpair ( op2 ( pr1 xy ) ( pr1 xy' ) ) ( op2 ( pr2 xy ) ( pr2 xy' ) ) ) ) . Defined .  \n\n\n\n\n\n\n\n(* End of the file algebra1a.v *)\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/arxiv/Foundations/hlevel2/algebra1a.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143777, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6516712261801451}}
{"text": "Set Implicit Arguments.\nRequire Export Notations.\nNotation \"A -> B\" := (forall (_ : A), B) : type_scope.\nInductive True: Prop :=\nI: True.\n\nInductive False : Prop := .\n\nDefinition not (A:Prop) := A -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nHint Unfold not: core.\n\nInductive and (A B:Prop) :Prop :=\n  conj : A-> B -> A /\\B\n\nwhere \"A /\\ B\" := (and A B) : type_scope.\n\nSection Conjunction.\n  Variables A B :Prop.\n  Theorem proj1 : A/\\B -> A.\n  Proof.\n  (*destruct 1.\n  trivial.  \n  *)  \n  intro H1.\n  destruct H1.\n  exact H.\n  Qed.\n  Theorem proj2 : A /\\ B -> B.\n  Proof.\n  intro H1.\n  induction H1.\n  exact H0.\nQed.\nEnd Conjunction.\n\nInductive or (A B: Prop):Prop :=\n|or_introl : A -> A \\/ B\n|or_intror : B -> A \\/ B\nwhere \"A \\/ B\" := (or A B) : type_scope.\n\nDefinition iff (A B:Prop) := (A -> B) /\\ (B->A).\nNotation \"A <-> B\" := (iff A B) : type_scope.\nSection Equivalence.\nVariables A B C:Prop.\nTheorem iff_refl : forall A, A <->A.\nProof.\nintro H1.\nsplit.\ntrivial.\ntrivial.\nQed.\nTheorem iff_trans : forall A B C: Prop, (A <-> B) -> (B <-> C) -> (A <-> C).\nProof.\nsplit.\ninduction H.\ninduction H0.\nintros until 1.\napply H0; apply H; exact H3.\nintro P2.\napply H; apply H0; exact P2.\nQed.\nTheorem iff_sym: forall A B: Prop, (A<->B) -> (B <->A).\nProof.\nsplit.\napply H.\napply H.\nQed.\nEnd Equivalence.\n\nHint Unfold iff: extcore.\n\nTheorem and_iff_compat_l : forall A B C : Prop, (B <-> C) -> (A /\\ B <-> A /\\ C).\nProof.\nconstructor.\nexists.\napply H0.\napply H; apply H0.\nexists.\napply H0.\napply H; apply H0.\nQed.\n\nTheorem and_iff_compat_r : forall A B C : Prop, (B<->C) -> (B/\\A <-> C/\\A).\nProof.\nsplit.\nsplit.\napply H; apply H0.\napply H0.\nsplit.\napply H; apply H0.\napply H0.\nQed.\n\nTheorem or_iff_compat_l : forall A B C: Prop, (B <-> C) -> (A \\/ B <-> A \\/ C).\nProof.\nsplit.\nintro P.\ndestruct P.\nleft.\nexact H0.\nright.\napply H; exact H0.\nintro P.\ndestruct P.\nleft.\nexact H0.\nright.\napply H.\nexact H0.\nQed.\n\nTheorem or_iff_compat_r : forall A B C :Prop, (B <-> C) -> (B \\/ A <-> C \\/ A).\nProof.\nsplit.\nintro Q.\ndestruct Q.\nleft; apply H; exact H0.\nright; exact H0.\nintro Q.\ndestruct Q.\nleft; apply H; exact H0.\nright; exact H0.\nQed.\n\nTheorem imp_iff_compat_l : forall A B C : Prop, (B <-> C) -> ((A -> B) <-> (A -> C)).\nProof.\nsplit.\nintro Q.\nintro Q2.\napply H; apply Q; exact Q2.\nintros P P2.\napply H.\napply P.\nexact P2.\nQed.\n\nTheorem imp_iff_compat_r : forall A B C : Prop, (B <-> C) -> ((B -> A) <-> (C -> A)).\nProof.\n  split.\n  intro P.\n  intro Q.\n  apply P.\n  apply H; exact Q.\n  intro P2.\n  intro Q.\n  apply P2.\n  apply H; exact Q.\nQed.\n\nTheorem not_iff_compat : forall A B : Prop, (A <-> B) -> (~ A <-> ~B).\nProof.\n  split.\n  intro P1.\n  unfold not.\n  intro Q1.\n  elim P1.\n  apply H.\n  exact Q1.\n  intro P2.\n  unfold not.\n  intro Q2.\n  elim P2.\n  apply H; exact Q2.\nQed.\n\nTheorem neg_false : forall A : Prop, ~A <-> (A <-> False).\nProof.\n  split.\n  split.\n  intro P2.\n  \n  contradict H.\n  unfold not.\n  intro Q2.\n  elim Q2.\n  exact P2.\n  intro P3.\n  elim P3.\n  intro Q3.\n  unfold not.\n  destruct Q3.\n  exact H.\nQed.\n\nTheorem and_cancel_l : forall A B C : Prop, (B->A) -> (C -> A) -> ((A /\\B <-> A /\\ C) <-> (B <-> C)).\nProof.\n  exists.\n  constructor.\n  intro P1.\n  apply H1.\n  split.\n  apply H.\n  exact P1.\n  exact P1.\n  intro P2.\n  apply H1.\n  split.\n  apply H0.\n  exact P2.\n  exact P2.\n  exists.\n  constructor.\n  destruct H2.\n  exact H2.\n  apply H1; apply H2.\n  split.\n  apply H2.\n  apply H1; apply H2.\nQed.\n\nTheorem and_cancel_r : forall A B C :Prop, (B->A) -> (C -> A) -> ((B /\\ A <-> C /\\ A) <-> (B <->C)).\nProof.\n  split.\n  split.\n  intro P1.\n  destruct H1.\n  destruct H1.\n  split.\n  exact P1.\n  apply H.\n  exact P1.\n  exact H1.\n  destruct H1.\n  intro P2.\n  \n  destruct H1.\n  split.\n  \n  destruct H2.\n  split.\n  exact P2.\n  apply H0.\n  exact P2.\n  exact H1.\n  destruct H2.\n  split.\n  exact P2.\n  apply H0.\n  exact P2.\n  exact H2.\n  destruct H2.\n  split.\n  exact P2.\n  exact H3.\n  exact H2.\n  split.\n  split.\n  destruct H2.\n  apply H1.\n  exact H2.\n  destruct H2.\n  exact H3.\n  split.\n  destruct H2.\n  Focus 2.\n  destruct H2.\n  exact H3.\n  apply H1.\n  exact H2.\n  Qed.\n\nTheorem and_comm: forall A B : Prop, A /\\ B <-> B /\\ A.\nProof.\n  split.\n  split.\n  destruct H.\n  exact H0.\n  destruct H.\n  exact H.\n  split.\n  destruct H.\n  exact H0.\n  destruct H.\n  exact H.\nQed.\n\nTheorem and_assoc : forall A B : Prop, A /\\ B <-> B /\\ A.\nProof.\n  split.\n  split.\n  destruct H.\n  exact H0.\n  destruct H.\n  exact H.\n  split.\n  destruct H.\n  exact H0.\n  destruct H.\n  exact H.\nQed.\n\nTheorem or_cancel_l : forall A B C : Prop,\n  (B -> ~ A) -> (C -> ~ A) -> ((A \\/ B <-> A \\/ C) <-> (B <-> C)).\nProof.\n  intros ? ? ? Fl Fr; split; [ | apply or_iff_compat_l]; intros [Hl Hr]; split; intros.\n  { destruct Hl; [ right | destruct Fl | ]; assumption. }\n  \n  { destruct Hr; [ right | destruct Fr | ]; assumption. }\nQed.\n(* Goal forall A B: Prop, A/\\B.\nProof.\n  intro P0.\n  intro P1.\n  \n  exists.\n  intro H.\n[H1 H2].\nCheck {.\n   *)\n  \n\n  (*\nhttp://www.inf.ed.ac.uk/teaching/courses/tspl/cheatsheet.pdf\nhttps://www.cs.princeton.edu/courses/archive/fall07/cos595/stdlib/html/Coq.Init.Logic.html\nhttps://coq.inria.fr/distrib/current/stdlib/Coq.Init.Logic.html\nhttps://www.cs.cornell.edu/courses/cs3110/2018sp/a5/coq-tactics-cheatsheet.html#simplegoals\n*)\n\nTheorem or_cancel_r : forall A B C: Prop, (B-> not A) -> (C -> not A) -> ((B \\/ A <-> C \\/ A) <-> (B <-> C)).\nProof.\n  intros ? ? ? Fl Fr; split; [ | apply or_iff_compat_r]; intros [Hl Hr]; split; intros.\n  { destruct Hl; [ left | | destruct Fl ]; assumption. }\n  { destruct Hr; [ left | | destruct Fr ]; assumption. }\nQed.\nTheorem or_cancel_r2 : forall A B C: Prop, (B-> not A) -> (C -> not A) -> ((B \\/ A <-> C \\/ A) <-> (B <-> C)).\nProof.\n  intros *.\n  intros Fl Fr.\n  split.\n  intro P1.\n  Focus 2.\n  apply or_iff_compat_r.\n  split.\n  intro Hl.\n  Focus 2.\n  intro Hr.\n  Unfocus.\n  intros.\n  Admitted.\n(*   Focus 2.\n  (* exists. *)\n  induction 1.\n  induction H1.\n  induction H2.\n  split.\n  intro P1.\n  exact H1.\n  intro P2.\n  exact H2.\n  split.\n  intro P3.\n  exact H1.\n  intro P4.\n  induction H.\n  Focus 2.\n  exact H2.\n  Focus 2.\n  left; exact H1.\n  Focus 3.\n  destruct H2.\n  Unfocus.\n  Focus 2.\n  induction H2.\n  split.\n  intro P1.\n  Focus 2.\n  intro P2.\n  exact H2.\n  Focus 3.\n  right; apply H1.\n  Focus 2.\n  split.\n  intro P1.\n  Focus 2.\n  intro P1.\n  Unfocus.\n  Unfocus.\n  induction H.\n  Focus 2.\n  exact H1.\n  exact H2.\n  destruct H.\n  exact P1.\n  exact H1.\n  Unfocus.\n  Focus 4.\n  left; exact H1.\n  Focus 5.\n  destruct 1.\n\n  split.\n  induction 1.\n  Focus 2.\n  right; exact H3.\n  Focus 2.\n  induction 1.\n  Unfocus.\n  Focus 3.\n  right; exact H3.\n  Unfocus.\n  Focus 4.\n  right; exact H1.\n  Focus 3.\n  induction H.\n  induction H0.\n  Unfocus.\n  induction H0.\n  exact P4.\n  exact H2.\n  Focus 3.\n  Unfocus.\n  Focus 6.\n  left; apply H2; exact H3.\n  Focus 5.\n  left; apply H1; exact H3.\n  Focus 4.\n  induction H0.\n  Unfocus.\n  auto.\n  Admitted. *)\n\n\nTheorem or_comm: forall A B : Prop, (A\\/B) <-> (B\\/A).\nProof.\n  constructor.\n  induction 1.\n  right; exact H.\n  left; exact H.\n  induction 1.\n  right; exact H.\n  left; exact H.\nQed.\n\nTheorem or_assoc : forall A B C :Prop, (A\\/B) \\/ C <-> A \\/ B \\/ C.\nProof.\n  intros; split; [ intros [[?|?]|?] | intros [?|[?|?]]].\n  + left; assumption.\n  + right; left; assumption.\n  + right; right; assumption.\n  + left; left; assumption.\n  + left; right; assumption.\n  + right; assumption.\nQed.\n\n\n(*   intros A B C.\n  split.\n  right.\n  induction H.\n  left.\n  induction H.\n  Focus 2.\n  exact H.\n  Focus 2.\n  right; exact H.\n  Focus 2.\n  destruct 1.\n  left; left; exact H.\n  induction H.\n  left; right; exact H.\n  right; exact H.\n  Admitted. *)\n\nTheorem iff_and : forall A B: Prop, ( A <-> B) -> (A -> B) /\\ (B -> A).\nProof.\n  constructor.\n  destruct H.\n  exact H.\n  destruct H.\n  exact H0.\nQed.\n\nTheorem iff_to_and : forall A B : Prop, (A<-> B) <-> (A -> B) /\\ (B -> A).\nProof.\n  constructor.\n  induction 1.\n  split.\n  exact H.\n  exact H0.\n  split.\n  destruct H.\n  exact H.\n  destruct H.\n  exact H0.\nQed.\n\nDefinition IF_the_else ( P Q R: Prop) := P /\\ Q \\/ ~P/\\R.\n\nNotation \"'IF' c1 'then' c2 'else' c3\" := (IF_then_else c1 c2 c3) ( at level 200, right associativity): type_scope.\n\nInductive ex (A:Type) (P: A -> Prop) : Prop := ex_intro : forall x: A, P x -> ex (A:=A) P.\n\nSection Projections.\nVariables (A:Prop) (P:A-> Prop).\n  Definition ex_proj1 (x:ex P) : A := match x with ex_intro _ a _ => a end.\n  Definition ex_proj2 (x:ex P) : P (ex_proj1 x) := match x with ex_intro _ _ b => b end.\nEnd Projections.\n\nInductive ex2 (A:Type) (P Q: A -> Prop) : Prop := ex_intro2 : forall x:A, P x -> Q x -> ex2 (A:=A) P Q.\nDefinition all (A:Type) (P:A -> Prop) := forall x:A, P x.\nNotation \"'exists' x .. y , p\" := (ex (fun x => .. ( ex (fun y => p)) ..)) (at level 200, x binder, right associativity, format \"'[' 'exists' '/' x .. y , '/ ' p ']'\") : type_scope.\nNotation \"'exists2' x , p & q\" := (ex2 (fun x => p) (fun x => q))\n  (at level 200, x ident, p at level 200, right associativity) : type_scope.\nNotation \"'exists2' x : A , p & q\" := (ex2 (A:=A) (fun x => p) (fun x => q))\n  (at level 200, x ident, A at level 200, p at level 200, right associativity,\n    format \"'[' 'exists2' '/ ' x : A , '/ ' '[' p & '/' q ']' ']'\")\n  : type_scope.\n\nNotation \"'exists2' ' x , p & q\" := (ex2 (fun x => p) (fun x => q))\n  (at level 200, x strict pattern, p at level 200, right associativity) : type_scope.\nNotation \"'exists2' ' x : A , p & q\" := (ex2 (A:=A) (fun x => p) (fun x => q))\n  (at level 200, x strict pattern, A at level 200, p at level 200, right associativity,\n    format \"'[' 'exists2' '/ ' ' x : A , '/ ' '[' p & '/' q ']' ']'\")\n  : type_scope.\n\nSection universal_quantification.\nVariable A:Type.\nVariable P: A->Prop.\n\nTheorem inst : forall x:A, all (fun x => P x) -> P x.\nProof.\n  intros *.\n  intro Q1.\n  apply Q1.\nQed.\n\nTheorem gen : forall (B:Prop) (f:forall y:A, B -> P y), B -> all P.\nProof.\n  intros *.\n  intro Q1.\n  intro Q2.\n  intro Q3.\n  apply Q1.\n  exact Q2.\nQed.\n\nEnd universal_quantification.\n\n\nInductive eq (A:Type) (x:A) : A -> Prop := eq_refl : x = x :> A where \"x = y :> A\" := (@eq A x y): type_scope.\n\nNotation \"x = y\" := (x = y :>_) : type_scope.\nNotation \"x <> y :> T\" := (~x = y :> T) :type_scope.\nNotation \"x <> y\" := (x <> y :>_) : type_scope.\n\nHint Resolve I conj or_introl or_intror : core.\nHint Resolve eq_refl: core.\nHint Resolve ex_intro ex_intro2: core.\n\nSection Logic_lemmas.\n  Theorem absurd: forall A C: Prop, A -> ~A -> C.\n  Proof.\n    intros *.\n    intro P1.\n    intro P2.\n    contradict P2.\n    unfold not.\n    intro Q1.\n    contradiction.\n  Qed.\n\n    Section equality.\n      Variables A B : Type.\n      Variables f : A->B.\n      Variables x y z : A.\n      Theorem eq_sym : x = y -> y = x.\n      Proof.\n        intro H0.\n        replace x with y.\n        reflexivity.\n        destruct H0.\n        reflexivity.\n      Qed.\n      \n      Theorem eq_trans : x = y -> y = z -> x = z.\n      Proof.\n        induction 1.\n        induction 1.\n        reflexivity.\n      Qed.\n      \n      Theorem eq_trans_r : x = y -> z = y -> x = z.\n      Proof.\n        induction 1.\n        induction 1.\n        reflexivity.\n      Qed.\n      \n      Theorem f_equal : x = y -> f x = f y.\n      Proof.\n        induction 1.\n        reflexivity.\n      Qed.\n\n      Theorem not_eq_sym : x <> y -> y <> x.\n      Proof.\n        intro P1.\n        intro P2.\n        induction P1.\n        induction P2.\n        reflexivity.\n      Qed.\n\n    End equality.\n\n  Definition eq_sind_r : forall (A:Type) (x:A) (P:A -> SProp),  P x -> forall y : A, y = x -> P y.\n  Proof.\n    intros x y P.\n    intro H0.\n    intro M0.\n    intro M1.\n    induction M1.\n    exact H0.\n  Qed.\n\nEnd Logic_lemmas.\n\n\nModule EqNotations.\n  Notation \"'rew' H 'in' H'\" := (eq_rect _ _ H' _ H)\n    (at level 10, H' at level 10,\n     format \"'[' 'rew' H in '/' H' ']'\").\n  Notation \"'rew' [ P ] H 'in' H'\" := (eq_rect _ P H' _ H)\n    (at level 10, H' at level 10,\n     format \"'[' 'rew' [ P ] '/ ' H in '/' H' ']'\").\n  Notation \"'rew' <- H 'in' H'\" := (eq_rect_r _ H' H)\n    (at level 10, H' at level 10,\n     format \"'[' 'rew' <- H in '/' H' ']'\").\n  Notation \"'rew' <- [ P ] H 'in' H'\" := (eq_rect_r P H' H)\n    (at level 10, H' at level 10,\n     format \"'[' 'rew' <- [ P ] '/ ' H in '/' H' ']'\").\n  Notation \"'rew' -> H 'in' H'\" := (eq_rect _ _ H' _ H)\n    (at level 10, H' at level 10, only parsing).\n  Notation \"'rew' -> [ P ] H 'in' H'\" := (eq_rect _ P H' _ H)\n    (at level 10, H' at level 10, only parsing).\n\nEnd EqNotations.\n\nImport EqNotation\n", "meta": {"author": "luntan-maker", "repo": "Coq-Walkthrough", "sha": "c66737d41a16bbd8a23434d815af181788696c38", "save_path": "github-repos/coq/luntan-maker-Coq-Walkthrough", "path": "github-repos/coq/luntan-maker-Coq-Walkthrough/Coq-Walkthrough-c66737d41a16bbd8a23434d815af181788696c38/StandardLibrary/COQ_LOGIC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6516712187121912}}
{"text": "Require Export D.\n\n\n\nCheck optimize_1mult.\n(*\n[optimize_1mult] is defined as follows:\n\nFixpoint optimize_1mult (a:aexp) : aexp :=\n  match a with\n  | ANum n =>\n      ANum n\n  | APlus e1 e2 =>\n      APlus (optimize_1mult e1) (optimize_1mult e2)\n  | AMinus e1 e2 =>\n      AMinus (optimize_1mult e1) (optimize_1mult e2)\n  | AMult (ANum 1) e2 =>\n      optimize_1mult e2\n  | AMult e1 (ANum 1) =>\n      optimize_1mult e1\n  | AMult e1 e2 =>\n      AMult (optimize_1mult e1) (optimize_1mult e2)\n  end.\n*)\n\n(** Hint:\n    If you use the tacticals [;], [try] and [omega] well,\n    you can prove the following theorem in 5 lines.\n **)\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 Tactic Notation \"inductive_cases\" tactic(first) ident(c) :=\n   first;\n   [ Case_aux c \"O\" | Case_aux c \"S n\"].\n\nTheorem optimize_1mult_sound: forall a,\n  aeval (optimize_1mult a) = aeval a.\nProof.\n  intros. aexp_cases (induction a) Case; try reflexivity; try (simpl; omega).\n   aexp_cases (destruct a1) SCase. \n  (* SCase = \"ANum\" *)\n  destruct n.\n  SSCase \"n = 0\".\n      aexp_cases (destruct a2) SSSCase; try reflexivity. destruct n. reflexivity. destruct n; try reflexivity.\n  SSCase \"n = S n\".\n    aexp_cases (destruct a2) SSSCase. destruct n. destruct n0; try reflexivity. simpl in *. omega. simpl in *. destruct n0; try reflexivity. simpl. destruct n0; try reflexivity. simpl. omega.\n  destruct n; simpl in *; rewrite IHa2; [try omega|reflexivity]. \n  destruct n; simpl in *; rewrite IHa2; [try omega|reflexivity]. \n  destruct n; simpl in *; rewrite IHa2; [try omega|reflexivity]. \n \n  (* SCase = \"APlus\" *)\n   aexp_cases (destruct a2) SSSCase.  destruct n. simpl in *. rewrite IHa1. omega. destruct n.  simpl in *. rewrite IHa1. omega. simpl in *. rewrite IHa1. omega.\n  simpl in *. rewrite IHa1. rewrite IHa2. omega.\n  simpl in *. rewrite IHa1. rewrite IHa2. omega.\n  simpl in *. rewrite IHa1. rewrite IHa2. omega.\n\n  (* SCase = \"AMinus\" *)\n   aexp_cases (destruct a2) SSSCase.  destruct n. simpl in *. rewrite IHa1. omega. destruct n.  simpl in *. rewrite IHa1. omega. simpl in *. rewrite IHa1. omega.\n  simpl in *. rewrite IHa1. rewrite IHa2. omega.\n  simpl in *. rewrite IHa1. rewrite IHa2. omega.\n  simpl in *. rewrite IHa1. rewrite IHa2. omega.\n\n  (* SCase = \"AMult\" *)\n   aexp_cases (destruct a2) SSSCase.  destruct n. simpl in *. rewrite IHa1. omega. destruct n.  simpl in *. rewrite IHa1. omega. simpl in *. rewrite IHa1. omega.\n  simpl in *. rewrite IHa1. rewrite IHa2. omega.\n  simpl in *. rewrite IHa1. rewrite IHa2. omega.\n  simpl in *. rewrite IHa1. rewrite IHa2. omega.\n\nQed.\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/07/P02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.651671214439364}}
{"text": "From LADR Require Import VectorSpace.\nInclude DEFINITIONS.\nRequire Import Ensembles.\nRequire Import Vector.\nRequire Import Logic.FunctionalExtensionality.\nRequire Import Logic.PropExtensionality.\nFixpoint zipwith {A B C : Type} {n : nat}\n         (f : A -> B -> C) (v1 : t A n) (v2 : t B n) : t C n\n  := match v1 in t _ n return t B n -> t C n with\n     | nil _ => fun _ => nil C\n     | cons _ x1 _ v1' =>\n       fun v2 =>\n         cons _ (f x1 (hd v2)) _ (zipwith f v1' (tl v2))\n     end v2.\nDefinition zip {A B C : Type} {n : nat} := @zipwith A B (A*B) n pair.\nLemma nil_unique {A : Type} : forall (xs : t A 0), xs = nil A.\nProof. apply case0. reflexivity. Qed.\n\n\n(*2.5*)\nDefinition span {n : nat} (xs : t V n) : V -> Prop\n  :=\n    fun x => exists ys, x = fold_left vadd 0 (zipwith vsmult ys xs).\n\n(*2.8*)\nDefinition spans {n : nat} (xs : t V n) : Prop\n  :=\n    span xs = Full_set V.\n\n\n(*2.5*)\nTheorem span_empty_zero : span (@nil V) = fun x => x = 0.\nProof.\n  apply (functional_extensionality (span (@nil V)) (fun x => x = 0)).\n  intros x.\n  unfold span.\n  apply propositional_extensionality.\n  split.\n  - intros.\n    destruct H as [ys H].\n    rewrite (nil_unique ys) in H; simpl in H.\n    apply H.\n  - simpl.\n    intros.\n    exists (@nil F).\n    simpl.\n    apply H.\n  Qed.\n(*\n(*2.10*)\nDefinition finite_dimensional (V : Type) (H__vectorspace : )\n*)\n(*Linear Independence*)\n\n(*2.17*)\nDefinition linearly_independent {n : nat} (xs : t V n) : Prop :=\n  forall (ys : t F n),\n    fold_left vadd 0 (zipwith vsmult ys xs) = 0 ->\n    Forall (fun y => y = 0%fieldsc) ys.\n\n(*2.17 b*)\nTheorem empty_independent : linearly_independent (@nil V).\nProof.\n  unfold linearly_independent; intros.\n  specialize (nil_unique ys); intros.\n  rewrite H0.\n  apply Forall_nil.\nQed.\n\n(*2.19*)\nDefinition linearly_dependent {n : nat} (xs : t V n) : Prop :=\n  exists (ys : t F n),\n    Exists (fun y => y <> 0%fieldsc) ys -> fold_left vadd 0 (zipwith vsmult ys xs) = 0.\n\n\nDefinition three_zeros : t V 3 :=\n  (cons V 0 2 (cons V 0 1 (cons V 0 0 (nil V)))).\n(*)\n  Definition coprojection {A : Type} {n : nat} (v : t A n) (j : nat) (H : j < n) : t A (n-1) :=\n    (*[x for i, x in enumerate(xs) if i != j]*)\n    take (n-1) v.\n*)\nCheck nth_order (cons V 0 2 (cons V 0 1 (cons V 0 0 (nil V)))).\nDefinition a_leq_prop := 5 <= 7.\n\n(*2.21*)\nTheorem linear_dependence_lemma1 {n : nat} (xs : t V n) (H : linearly_dependent xs) :\n  exists (j : nat),\n  forall (H0 : j <= n) (H1 : j < n),\n    (span (take j H0 xs) (nth_order xs H1)).\nProof.\n  exists 1%nat.\n  intros.\n  induction xs.\n  - inversion H0.\n  - simpl.\n    unfold linearly_dependent in H.\n    destruct H as [ys H].\n    unfold span.\n\n\nAdmitted.\n\n(*2.23*)\nTheorem length_linearly_independent_list_leq_length_spanning_list {n m : nat} :\n  forall (xs : t V n) (xs' : t V m),\n    linearly_independent xs -> spans F V vadd vsmult 0 veq xs' -> n <= m.\nProof.\n  intros.\n  unfold linearly_independent in H.\n  unfold spans, span in H0.\nAdmitted.\n\nLemma fold_commute {n : nat} {a__k : t F n} {xs : t V n} {l : F} :\n  fold_left vadd 0 (map (vsmult l) (zipwith vsmult a__k xs)) = vsmult l (fold_left vadd 0 (zipwith vsmult a__k xs)).\nProof.\n  generalize dependent a__k.\n  induction xs; intros a__k.\n  - specialize (nil_unique a__k); intros.\n    rewrite H.\n    simpl.\n    symmetry.\n    apply number_times_zero with (r0 := r0) (r1 := r1) (radd := radd) (rmul := rmul)\n                                 (rsub := rsub) (ropp := ropp) (req := req) (rdiv := rdiv)\n                                 (rinv := rinv) (vadd := vadd) (veq := veq); give_up.\n  - simpl.\nAdmitted.\n\nLemma factor_out_scalar {n : nat} {a__k : t F n} {xs : t V n} : forall (l : F) (H__l : l <> 0%fieldsc),\n    fold_left vadd 0 (map (vsmult l) (zipwith vsmult a__k xs)) = 0 ->\n    fold_left vadd 0 (zipwith vsmult a__k xs) = 0.\nProof.\n  intros l H__l H__xsl.\n  rewrite fold_commute in H__xsl.\n  Admitted.\n\n(*exercise 2.A.8*)\nTheorem scalar_ind {n : nat} :\n  forall (l : F) (H__l : l <> 0%fieldsc) (xs : t V n) (H__xs : linearly_independent xs),\n    linearly_independent (map (vsmult l) xs).\nProof.\n  intros l H__l xs H__xs.\n  unfold linearly_independent in *.\n  intros b__k H__lx.\n  specialize (H__xs b__k).\nAdmitted.\n\n\n(*exercise 2.A.9*)\n(*This is actually false, counterexample is v = [2,0], [0,1] and w = [1, 2], [3, 1]*)\nTheorem sum_ind {n : nat} : forall (xs ys : t V n) (H__xs : linearly_independent xs) (H__ys : linearly_independent ys),\n    linearly_independent (zipwith vadd xs ys).\nProof.\n  intros xs ys H__xs H__ys.\n  unfold linearly_independent in *.\n  intros b__k H__xys.\n  specialize (H__xs b__k).\n  apply H__xs.\n", "meta": {"author": "quinn-dougherty", "repo": "ladr", "sha": "a3137394831791ad29c5bbfe6241d1fb233d67cb", "save_path": "github-repos/coq/quinn-dougherty-ladr", "path": "github-repos/coq/quinn-dougherty-ladr/ladr-a3137394831791ad29c5bbfe6241d1fb233d67cb/src/SpanIndependenceBasis.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6516712101665367}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_betweennotequal.\n\nSection Euclid.\n\nContext `{Ax1:euclidean_neutral}.\n\nLemma lemma_lessthannotequal : \n   forall A B C D, \n   Lt A B C D ->\n   neq A B /\\ neq C D.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists E, (BetS C E D /\\ Cong C E A B)) by (conclude_def Lt );destruct Tf as [E];spliter.\nassert (neq C E) by (forward_using lemma_betweennotequal).\nassert (neq A B) by (conclude axiom_nocollapse).\nassert (neq C D) by (forward_using lemma_betweennotequal).\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_lessthannotequal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6514483567744267}}
{"text": "From Categories Require Import Essentials.Notations.\nFrom Categories Require Import Essentials.Types.\nFrom Categories Require Import Essentials.Facts_Tactics.\nFrom Categories Require Import Category.Main.\nFrom Categories Require Import Functor.Functor.\nFrom Categories Require Import Functor.Functor_Ops.\n\nLocal Open Scope functor_scope.\n\nSection Functor_Properties.\n  Context {C C' : Category} (F : C –≻ C').\n\n  Local Open Scope object_scope.\n  Local Open Scope isomorphism_scope.\n  Local Open Scope morphism_scope.\n    \n  (** A functor is said to be injective if its object map is. *)\n  Definition Injective_Func := ∀ (c c' : Obj), F _o c = F _o c' → c = c'.\n\n  (** A functor is said to be essentially injective if its object map maps\nequal objects to isomorphic objects in the codomain category. *)\n  Definition Essentially_Injective_Func :=\n    ∀ (c c' : Obj), F _o c = F _o c' → c ≃ c'.\n  \n  (** A functor is said to be surjective if its object map is. *)\n  Definition Surjective_Func := ∀ (c : Obj), {c' : Obj | F _o c' = c}.\n\n  (** A functor is said to be essentially surjective if for each object in the\ncodomain category there is an aobject in the domain category that is mapped\nto an aobject isomorphic to it. *)\n  Definition Essentially_Surjective_Func :=\n    ∀ (c : Obj), {c' : Obj & F _o c' ≃ c}.\n\n  (** A functor is said to be faithful if its arrow map is injective. *)\n  Definition Faithful_Func := ∀ (c c' : Obj) (h h' : (c –≻ c')%morphism),\n      F _a h = F _a h' → h = h'.\n\n  (** A functor is said to be full if its arrow map is surjective. *)\n  Definition Full_Func :=\n    ∀ (c1 c2 : Obj) (h' : ((F _o c1) –≻ (F _o c2))%morphism),\n      {h : (c1 –≻ c2)%morphism | F _a h = h'}\n  .\n\n  Local Ltac Inv_FTH :=\n    match goal with\n      [fl : Full_Func |- _] =>\n      progress (\n          repeat\n            match goal with\n              [|- context [(F _a (proj1_sig (fl _ _ ?x)))]] =>\n              rewrite (proj2_sig (fl _ _ x))\n            end\n        )\n    end\n  .\n\n  Local Hint Extern 1 => Inv_FTH.\n\n  Local Hint Extern 1 => rewrite F_compose.\n\n  Local Hint Extern 1 =>\n  match goal with\n    [fth : Faithful_Func |- _ = _ ] => apply fth\n  end\n  .\n\n  Local Obligation Tactic := basic_simpl; auto 6.\n  \n  (** Any fully-faithful functor is essentially surjective. *)\n  Program Definition Fully_Faithful_Essentially_Injective\n          (fth : Faithful_Func) (fl : Full_Func) : Essentially_Injective_Func\n    :=\n      fun c c' eq =>\n        {|\n          iso_morphism :=\n            proj1_sig (\n                fl\n                  _\n                  _\n                  match eq in _ = y return\n                        (_ –≻ y)%morphism\n                  with\n                    eq_refl => id (F _o c)\n                  end\n              );\n          inverse_morphism :=\n            proj1_sig (\n                fl\n                  _\n                  _\n                  match eq in _ = y return\n                        (y –≻ _)%morphism\n                  with\n                    eq_refl => id (F _o c)\n                  end\n              )\n        |}\n  .\n\n  (** Any fully-faithful functor is conservative.\n      A conservative functor is one for which we have to objects of the domain\n      category are isomorphic if their images are ismorphic. *)\n  Program Definition Fully_Faithful_Conservative\n          (fth : Faithful_Func) (fl : Full_Func)\n    : ∀ (c c' : Obj), F _o c ≃ F _o c' → c ≃ c' :=\n    fun c c' I =>\n      {|\n        iso_morphism := proj1_sig (fl _ _ I);\n        inverse_morphism := proj1_sig (fl _ _ (I⁻¹))\n      |}\n  .\n\nEnd Functor_Properties.\n\n(** Functors Preserve Isomorphisms. *)\nSection Functors_Preserve_Isos.\n  Context {C C' : Category} (F : C –≻ C')\n          {a b : C} (I : (a ≃≃ b ::> C)%isomorphism).\n\n  Program Definition Functors_Preserve_Isos : (F _o a ≃ F _o b)%isomorphism :=\n    {|\n      iso_morphism := (F _a I)%morphism;\n      inverse_morphism := (F _a (I⁻¹))%morphism\n    |}.\n\nEnd Functors_Preserve_Isos.\n  \nSection Embedding.\n  Context (C C' : Category).\n\n  (**\n    An embedding is a functor that is fully-faithful. Such a functor is\n    necessarily essentially injective and conservative, i.e.,\n    if F _O c ≃ F _O c' then c ≃ c'.\n   *)\n\n  Record Embedding : Type :=\n    {\n      Emb_Func : C –≻ C';\n\n      Emb_Faithful : Faithful_Func Emb_Func;\n      \n      Emb_Full : Full_Func Emb_Func\n    }.\n\n  Coercion Emb_Func : Embedding >-> Functor.\n\n  Definition Emb_Essent_Inj (E : Embedding) :=\n    Fully_Faithful_Essentially_Injective\n      (Emb_Func E) (Emb_Faithful E) (Emb_Full E).\n  \n  Definition Emb_Conservative (E : Embedding) :=\n    Fully_Faithful_Conservative\n      (Emb_Func E) (Emb_Faithful E) (Emb_Full E).\n\nEnd Embedding.\n\nArguments Emb_Func {_ _} _.\nArguments Emb_Faithful {_ _} _ {_ _} _ _ _.\nArguments Emb_Full {_ _} _ {_ _} _.\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/Functor/Functor_Properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6514483560276051}}
{"text": "(************************************************************************)\n(* Copyright 2006 Milad Niqui                                           *)\n(* This file is distributed under the terms of the                      *)\n(* GNU Lesser General Public License Version 2.1                        *)\n(* A copy of the license can be found at                                *)\n(*                  <http://www.gnu.org/licenses>                       *)\n(************************************************************************)\n\n\nRequire Import digits.\nRequire Import Refining_T.\nRequire Import quadratic.\nRequire Import Streams_addenda.\nRequire Import rep.\nRequire Import RIneq.\nFrom QArithSternBrocot Require Import R_addenda.\n\n(** * Coinductive correctness of the quadratic algorithm. *)\n\n(** Calculating the left and right products of [xi] and the first [n] elements of [alpha] and [beta]. *)\n\nFixpoint product_init_zip (xi:Tensor) (alpha beta:Reals) (n:nat) {struct n}: Tensor := \n match n with\n | O => xi\n | S n' => right_product (left_product (product_init_zip xi alpha beta n') (Str_nth n' alpha)) (Str_nth n' beta) \n end.\n\n\nLemma product_init_zip_S:forall xi alpha beta n, \n   product_init_zip xi alpha beta (S n) = \n        right_product (left_product (product_init_zip xi alpha beta n) (Str_nth n alpha)) (Str_nth n beta).\nProof.\n intros xi alpha beta [|n]; trivial.\nQed.\n\nLemma product_init_zip_folds:forall xi alpha beta n, \n   product_init_zip xi alpha beta (S n) =\n       product_init_zip (right_product (left_product xi (Streams.hd alpha)) (Streams.hd beta)) (Streams.tl alpha) (Streams.tl beta) n.\nProof.\n intros xi alpha beta n; generalize xi alpha beta; clear xi alpha beta; induction n; intros xi alpha beta; simpl; trivial;\n rewrite <- IHn; rewrite product_init_zip_S; apply (f_equal2 right_product); trivial.\nDefined.\n\nLemma product_init_zip_init_rev_id: forall xi alpha beta n, \n    xi = \n   (right_product (left_product (product_init_zip xi alpha beta n) (product_init_rev alpha n)) (product_init_rev beta n)).\nProof.\n intros xi alpha beta n; generalize xi alpha beta; clear xi alpha beta; induction n; intros xi alpha beta.\n\n  unfold product_init_zip, product_init_rev; simpl; rewrite right_left_product_idM_identity_right; reflexivity.\n   \n  unfold product_init_rev; repeat rewrite rev_take_S_Str_nth; repeat rewrite fold_right_cons;\n  replace (fold_right product idM (rev (take n (Streams.map inv_digit alpha)))) with (product_init_rev alpha n); trivial;\n  replace (fold_right product idM (rev (take n (Streams.map inv_digit beta)))) with (product_init_rev beta n); trivial;\n  repeat rewrite <- Str_nth_map_pointwise;\n  rewrite product_init_zip_S; rewrite product_left_right_product_associative;\n  rewrite (product_associative (map_digits (Str_nth n alpha))); rewrite product_digit_inv_digit_identity_right;\n  rewrite (product_associative (map_digits (Str_nth n beta))); rewrite product_digit_inv_digit_identity_right;\n  rewrite <- product_left_right_product_associative; rewrite right_left_product_idM_identity_right; apply IHn.\nQed.  \n\nLemma product_init_zip_product_init_pure:forall xi alpha beta n,  \n product_init_zip xi alpha beta n = right_product (left_product xi (product_init_pure alpha n)) (product_init_pure beta n).\nProof.\n intros xi alpha beta n; revert xi alpha beta; induction n; intros xi alpha beta; unfold product_init_pure.\n  (* O *)\n  simpl; rewrite right_left_product_idM_identity_right; trivial.\n  (* S n *)\n  repeat rewrite Streams_addenda.take_S_n;\n  repeat rewrite (Streams_addenda.fold_right_cons product);\n  rewrite <- product_left_right_product_associative;\n  rewrite product_init_zip_folds;\n  rewrite (IHn (right_product (left_product xi (Streams.hd alpha)) (Streams.hd beta)) (Streams.tl alpha) (Streams.tl beta)); trivial.\nQed.\n\n\nSection depth_of_modulus_q.\n\nFixpoint depth_q (xi:Tensor) (alpha beta:Reals) (H1:emits_q xi alpha beta) {struct H1}:nat:=\n   match Incl_T_dec_D xi LL with\n   | left _ => 0\n   | right H_emission_L =>\n       match Incl_T_dec_D xi RR with\n       | left _ => 0\n       | right H_emission_R =>\n           match Incl_T_dec_D xi MM with\n           | left _ => 0\n           | right H_emission_M =>\n               S(depth_q (right_product (left_product xi (Streams.hd alpha)) (Streams.hd beta)) (Streams.tl alpha) (Streams.tl beta)\n                 (emits_q_absorbs_inv xi alpha beta H_emission_L H_emission_R H_emission_M H1))\n           end\n       end\n   end.\n\n\nLemma depth_q_PI:forall xi alpha beta H1 H2,  depth_q xi alpha beta H1 = depth_q xi alpha beta H2.\nProof.\n intros xi alpha beta H1.\n pattern alpha, beta, H1.\n elim H1 using emits_q_ind_dep;\n clear H1 xi;\n   [ intros xi alpha0 beta0 i H2; generalize i\n   | intros xi alpha0 beta0 i H2; generalize i \n   | intros xi alpha0 beta0 i H2; generalize i\n   | intros xi alpha0 beta0 f H H2; generalize f H\n   ];\n   pattern alpha0, beta0, H2;\n   elim H2 using emits_q_ind_dep;\n   first \n    [ intros xi0 alpha' beta' H_primity H_primity'; simpl; case (Incl_T_dec_D xi0 LL); intro; trivial; contradiction\n    | intros xi0 alpha' beta' H_primity H_primity'; simpl; case (Incl_T_dec_D xi0 RR); intro; trivial; contradiction\n    | intros xi0 alpha' beta' H_primity H_primity'; simpl; case (Incl_T_dec_D xi0 MM); intro; trivial; contradiction\n    | intros; contradiction]  || \n    (intro xi0; intros; simpl;\n      case (Incl_T_dec_D xi0 LL); intro; contradiction || \n\tcase (Incl_T_dec_D xi0 RR); intro; contradiction ||\n\t  case (Incl_T_dec_D xi0 MM); intro; contradiction ||\n\t    trivial;apply eq_S; trivial).\nDefined.\n\nLemma depth_q_PI_strong:forall xi xi' alpha beta alpha' beta' H1 H2, xi=xi'->alpha=alpha' -> beta = beta' ->\n   depth_q xi alpha beta H1 = depth_q xi' alpha' beta' H2.\nProof.\n intros; subst; apply depth_q_PI.\nDefined.\n\nLemma depth_q_L:forall (xi:Tensor) (alpha beta:Reals) (t: emits_q xi alpha beta),(Incl_T xi LL) ->\n                 depth_q xi alpha beta t=0.\nProof.\n intros xi alpha beta t t_l.\n transitivity (depth_q xi alpha beta (emits_q_L _ _ _ t_l)).\n apply depth_q_PI.\n simpl;\n  case (Incl_T_dec_D xi LL); try contradiction;\n   intros; reflexivity.\nDefined.\n\nLemma depth_q_R:forall (xi:Tensor) (alpha beta:Reals) (t: emits_q xi alpha beta), ~(Incl_T xi LL) ->  (Incl_T xi RR) ->\n                 depth_q xi alpha beta t=0.\nProof.\n intros xi alpha beta t t_l t_r.\n transitivity (depth_q xi alpha beta (emits_q_R _ _ _ t_r)).\n apply depth_q_PI.\n simpl;\n   case (Incl_T_dec_D xi LL); try contradiction;\n     case (Incl_T_dec_D xi RR); try contradiction;\n      intros; reflexivity.\nDefined.\n\nLemma depth_q_M:forall (xi:Tensor) (alpha beta:Reals) (t: emits_q xi alpha beta),~(Incl_T xi LL)->~(Incl_T xi RR)->(Incl_T xi MM)->\n                 depth_q xi alpha beta t=0.\nProof.\n intros xi alpha beta t t_l t_r t_m.\n transitivity (depth_q xi alpha beta (emits_q_M _ _ _ t_m)).\n apply depth_q_PI.\n simpl;\n case (Incl_T_dec_D xi LL); try contradiction;\n  case (Incl_T_dec_D xi RR); try contradiction;\n   case (Incl_T_dec_D xi MM); try contradiction;\n    intros; reflexivity.\nDefined.\n\nLemma depth_q_absorbs:forall (xi:Tensor) (alpha beta:Reals) (t: emits_q xi alpha beta),~(Incl_T xi LL)->~(Incl_T xi RR)->~(Incl_T xi MM)->\n  forall t', depth_q xi alpha beta t = S(depth_q (right_product (left_product xi (Streams.hd alpha)) (Streams.hd beta)) (Streams.tl alpha) (Streams.tl beta) t').\nProof.\n intros xi alpha beta t t_l t_r t_m t'.\n transitivity (depth_q xi alpha beta (emits_q_absorbs _ _ _ t')).\n apply depth_q_PI.\n simpl.\n case (Incl_T_dec_D xi LL); try contradiction;\n  case (Incl_T_dec_D xi RR); try contradiction;\n   case (Incl_T_dec_D xi MM); try contradiction;\n    intros _; reflexivity.\nDefined.\n\nLemma depth_q_modulus_q:forall (xi:Tensor) (alpha beta:Reals) (t: emits_q xi alpha beta) n,depth_q xi alpha beta t=n->\n       exists d:Digit, modulus_q xi alpha beta t = \n                                     pairT d (pairT (m_product (inv_digit d) (product_init_zip xi alpha beta n))\n                                                    (pairT (drop n alpha) (drop n beta))).\nProof.\n intros xi alpha beta t n H_eq.\n generalize xi alpha beta t H_eq; clear xi alpha beta t H_eq; induction n; intros xi alpha beta t H_eq.\n  (* n=0 *)\n  simpl.\n  case (Incl_T_dec_D xi LL); intro t_l.\n   exists LL; rewrite (modulus_q_L _ _ _ t t_l); trivial.\n   case (Incl_T_dec_D xi RR); intro t_r.\n    exists RR; rewrite (modulus_q_R _ _ _ t t_l t_r); trivial.\n    case (Incl_T_dec_D xi MM); intro t_m.\n     exists MM; rewrite (modulus_q_M _ _ _ t t_l t_r t_m); trivial.\n       \n     apply False_ind;\n     rewrite (depth_q_absorbs xi alpha beta t t_l t_r t_m (emits_q_absorbs_inv xi alpha beta t_l t_r t_m t)) in H_eq;\n     discriminate.\n  (* n=S n *)\n  case (Incl_T_dec_D xi LL); intro t_l.\n   apply False_ind; rewrite (depth_q_L xi alpha beta t t_l) in H_eq; discriminate.\n   case (Incl_T_dec_D xi RR); intro t_r.\n    apply False_ind; rewrite (depth_q_R xi alpha beta t t_l t_r) in H_eq; discriminate.\n    case (Incl_T_dec_D xi MM); intro t_m.\n     apply False_ind; rewrite (depth_q_M xi alpha beta t t_l t_r t_m) in H_eq; discriminate.\n\n     rewrite (depth_q_absorbs xi alpha beta t t_l t_r t_m (emits_q_absorbs_inv xi alpha beta t_l t_r t_m t)) in H_eq.\n     destruct (IHn _ _ _ _ (eq_add_S _ _ H_eq)) as [d H_ind]; exists d.\n     rewrite (modulus_q_absorbs xi alpha beta t t_l t_r t_m (emits_q_absorbs_inv xi alpha beta t_l t_r t_m t)). \n     rewrite H_ind.\n     apply (@f_equal2 _ _ _ (@pairT Digit (@prodT Tensor (@prodT Reals Reals)))); trivial;\n     apply (@f_equal2 _ _ _ (@pairT Tensor (@prodT Reals Reals))); trivial.\n     rewrite product_init_zip_folds; trivial.\n     destruct alpha; destruct beta; reflexivity.\nDefined.\n\nLemma depth_q_Incl_T_inf_strong : forall xi alpha beta (t: emits_q xi alpha beta) n, depth_q xi alpha beta t = n -> \n        {Incl_T (product_init_zip xi alpha beta n) LL/\\ fst (modulus_q xi alpha beta t)=LL}+\n        {Incl_T (product_init_zip xi alpha beta n) RR/\\ fst (modulus_q xi alpha beta t)=RR}+\n        {Incl_T (product_init_zip xi alpha beta n) MM/\\ fst (modulus_q xi alpha beta t)=MM}.\nProof.\n intros xi alpha beta t n H_eq.\n generalize xi alpha beta t H_eq.\n clear xi alpha beta t H_eq.\n induction n; intros xi alpha beta t H_eq.\n  case (Incl_T_dec_D xi LL); intro t_l.\n   left; left; split; trivial; rewrite (modulus_q_L _ _ _ t t_l); trivial.\n   case (Incl_T_dec_D xi RR); intro t_r.\n    left; right; split; trivial; rewrite (modulus_q_R _ _ _ t t_l t_r); trivial.\n    case (Incl_T_dec_D xi MM); intro t_m. \n    right; split; trivial; rewrite (modulus_q_M _ _ _ t t_l t_r t_m); trivial...   \n\n    apply False_rec;\n    rewrite (depth_q_absorbs xi alpha beta t t_l t_r t_m (emits_q_absorbs_inv xi alpha beta t_l t_r t_m t)) in H_eq;\n    discriminate...\n\n  case (Incl_T_dec_D xi LL); intro t_l.\n   apply False_rec; rewrite (depth_q_L xi alpha beta t t_l) in H_eq; discriminate.\n   case (Incl_T_dec_D xi RR); intro t_r.\n    apply False_rec; rewrite (depth_q_R xi alpha beta t t_l t_r) in H_eq; discriminate.\n     case (Incl_T_dec_D xi MM); intro t_m.\n     apply False_rec; rewrite (depth_q_M xi alpha beta t t_l t_r t_m) in H_eq; discriminate. \n\n     rewrite (depth_q_absorbs xi alpha beta t t_l t_r t_m (emits_q_absorbs_inv xi alpha beta t_l t_r t_m t)) in H_eq.\n     rewrite product_init_zip_folds.\n     destruct (IHn _ _ _ _ (eq_add_S _ _ H_eq)) as  [[[H_Incl H_modulus]|[H_Incl H_modulus]]|[H_Incl H_modulus]];\n     [ left; left\n     | left; right\n     | right\n     ]; split; trivial;\n     rewrite <- H_modulus;\n     apply (f_equal (@fst Digit (Tensor*(Reals*Reals))));\n     rewrite (modulus_q_absorbs _ _ _ t t_l t_r t_m (emits_q_absorbs_inv xi alpha beta t_l t_r t_m t)); trivial.\nDefined.\n\nLemma depth_q_Incl_T_inf_strong_general\n     : forall (xi : Tensor) (alpha beta: Reals) (t : emits_q xi alpha beta) (n : nat),\n       depth_q xi alpha beta t = n -> \n           exists d,Incl_T (product_init_zip xi alpha beta n) d /\\ fst (modulus_q xi alpha beta t) = d. \nProof.\n intros xi alpha beta t n H_depth.\n destruct (depth_q_Incl_T_inf_strong _ _ _ t n H_depth) as [[Hd|Hd]|Hd];\n  [ exists LL\n  | exists RR\n  | exists MM\n  ]; assumption.\nQed.\n\nEnd depth_of_modulus_q.\n\n\nLemma quadratic_emits_strong: forall xi alpha beta (p:productive_q xi alpha beta), \n      exists n, \n       (exists d:Digit, \n               productive_q (m_product (inv_digit d) (product_init_zip xi alpha beta n)) (drop n alpha) (drop n beta) /\\\n\t       Incl_T (product_init_zip xi alpha beta n) d/\\\n\t       forall p', bisim (quadratic xi alpha beta p)  \n       (Cons d (quadratic (m_product (inv_digit d) (product_init_zip xi alpha beta n)) (drop n alpha) (drop n beta) p'))).\nProof.\n intros xi alpha beta H_productive.\n generalize (productive_q_emits_q xi alpha beta H_productive); intro H_emits.\n\n exists (depth_q xi alpha beta H_emits).\n destruct (depth_q_modulus_q xi alpha beta H_emits (depth_q xi alpha beta H_emits) (refl_equal _)) as [d H_modulus].\n exists d; split.\n  generalize (modulus_q_productive_q xi alpha beta H_emits H_productive); rewrite H_modulus; trivial.\n  split. \n   \n   destruct (depth_q_Incl_T_inf_strong _ _ _ H_emits (depth_q xi alpha beta H_emits) (refl_equal _)) as\n         [[[H_Incl H_modulus']|[H_Incl H_modulus']]|[H_Incl H_modulus']];\n    rewrite H_modulus in H_modulus'; simpl in H_modulus'; rewrite H_modulus'; assumption...\n\n   intros H_productive'.\n   rewrite (quadratic_unfolded xi alpha beta H_productive);\n   constructor; simpl;\n   [ idtac \n   | apply quadratic_EPI_strong\n   ];\n   rewrite <- (modulus_q_PI _ _ _ H_emits (productive_q_emits_q xi alpha beta H_productive));\n   rewrite H_modulus;\n   trivial.\nDefined.\n\n\nTheorem quadratic_correctness : forall (xi:Tensor) (alpha beta:Reals) (H:productive_q xi alpha beta) (r1 r2:Rdefinitions.R),\n     rep alpha r1 ->  rep beta r2-> rep (quadratic xi alpha beta H) (as_Tensor xi r1 r2).\nProof.\n cofix.\n intros xi alpha beta H_productive r1 r2 Hr1_alpha Hr2_beta;\n destruct (quadratic_emits_strong xi alpha beta H_productive) as [n [[ | | ] [H_productive_dropped [H_Incl H_bis]]]];\n unfold inv_digit in H_bis; unfold inv_digit;\n generalize (H_bis H_productive_dropped); clear H_bis; intro H_bis.\n  (* L *)\n  replace (as_Tensor xi r1 r2) with (as_Tensor (m_product LL (m_product inv_LL xi)) r1 r2);\n  [ idtac | rewrite <- m_product_inv_L;  reflexivity];\n  replace (m_product inv_LL xi) with (m_product inv_LL\n  (right_product (left_product (product_init_zip xi alpha beta n) (product_init_rev alpha n)) (product_init_rev beta n)));\n  [ idtac | rewrite <- product_init_zip_init_rev_id; trivial].\n\n  assert (H_base: (-1<=as_Tensor (m_product inv_LL (right_product (left_product (product_init_zip xi alpha beta n)\n                                 (product_init_rev alpha n)) (product_init_rev beta n))) r1 r2 <= 1)%R).\n   rewrite m_product_left_right_product_associative.\n   rewrite as_Tensor_right_left_product_as_Moebius.\n    apply Is_refining_T_property;\n     try (apply rep_drop_in_range; assumption).\n     replace inv_LL with (inv_digit LL); trivial; apply Incl_T_absorbs_Is_refining_T; assumption.\n    apply denom_nonvanishing_product_init; assumption.\n    apply denom_nonvanishing_product_init; assumption.\n    apply rep_drop_in_range; assumption.\n    apply rep_drop_in_range; assumption.\n    replace inv_LL with (inv_digit LL); trivial; apply Incl_T_absorbs_Is_refining_T; assumption.\n\n  rewrite as_Tensor_L; try exact H_base.\n   refine\n     (rep_L \n       (quadratic (m_product inv_LL (product_init_zip xi alpha beta n)) (drop n alpha) (drop n beta) H_productive_dropped)\n       _ _ _ _ H_bis).\n\n    exact H_base.\n\n    rewrite m_product_left_right_product_associative;\n    rewrite as_Tensor_right_left_product_as_Moebius.\n     apply quadratic_correctness;\n     [ apply (rep_drop _ _ n Hr1_alpha)\n     | apply (rep_drop _ _ n Hr2_beta)\n     ]. \n     apply denom_nonvanishing_product_init; assumption.\n     apply denom_nonvanishing_product_init; assumption.\n     apply rep_drop_in_range; assumption.\n     apply rep_drop_in_range; assumption.\n     replace inv_LL with (inv_digit LL); trivial; apply Incl_T_absorbs_Is_refining_T; assumption.\n   rewrite m_product_left_right_product_associative; apply denom_nonvanishing_T_left_right_product.\n    apply denom_nonvanishing_product_init; assumption.\n    apply denom_nonvanishing_product_init; assumption.\n    apply rep_drop_in_range; assumption.\n    apply rep_drop_in_range; assumption.\n    replace inv_LL with (inv_digit LL); trivial; apply Incl_T_absorbs_Is_refining_T; assumption.\n  (* R *)\n  replace (as_Tensor xi r1 r2) with (as_Tensor (m_product RR (m_product inv_RR xi)) r1 r2);\n  [ idtac | rewrite <- m_product_inv_R;  reflexivity];\n  replace (m_product inv_RR xi) with (m_product inv_RR\n  (right_product (left_product (product_init_zip xi alpha beta n) (product_init_rev alpha n)) (product_init_rev beta n)));\n  [ idtac | rewrite <- product_init_zip_init_rev_id; trivial].\n\n  assert (H_base: (-1<=as_Tensor (m_product inv_RR (right_product (left_product (product_init_zip xi alpha beta n)\n                                 (product_init_rev alpha n)) (product_init_rev beta n))) r1 r2 <= 1)%R).\n   rewrite m_product_left_right_product_associative.\n   rewrite as_Tensor_right_left_product_as_Moebius.\n    apply Is_refining_T_property;\n     try (apply rep_drop_in_range; assumption).\n     replace inv_RR with (inv_digit RR); trivial; apply Incl_T_absorbs_Is_refining_T; assumption.\n    apply denom_nonvanishing_product_init; assumption.\n    apply denom_nonvanishing_product_init; assumption.\n    apply rep_drop_in_range; assumption.\n    apply rep_drop_in_range; assumption.\n    replace inv_RR with (inv_digit RR); trivial; apply Incl_T_absorbs_Is_refining_T; assumption.\n\n  rewrite as_Tensor_R; try exact H_base.\n   refine\n     (rep_R \n       (quadratic (m_product inv_RR (product_init_zip xi alpha beta n)) (drop n alpha) (drop n beta) H_productive_dropped)\n       _ _ _ _ H_bis).\n\n    exact H_base.\n\n    rewrite m_product_left_right_product_associative;\n    rewrite as_Tensor_right_left_product_as_Moebius.\n     apply quadratic_correctness;\n     [ apply (rep_drop _ _ n Hr1_alpha)\n     | apply (rep_drop _ _ n Hr2_beta)\n     ]. \n     apply denom_nonvanishing_product_init; assumption.\n     apply denom_nonvanishing_product_init; assumption.\n     apply rep_drop_in_range; assumption.\n     apply rep_drop_in_range; assumption.\n     replace inv_RR with (inv_digit RR); trivial; apply Incl_T_absorbs_Is_refining_T; assumption.\n   rewrite m_product_left_right_product_associative; apply denom_nonvanishing_T_left_right_product.\n    apply denom_nonvanishing_product_init; assumption.\n    apply denom_nonvanishing_product_init; assumption.\n    apply rep_drop_in_range; assumption.\n    apply rep_drop_in_range; assumption.\n    replace inv_RR with (inv_digit RR); trivial; apply Incl_T_absorbs_Is_refining_T; assumption.\n  (* M *)\n  replace (as_Tensor xi r1 r2) with (as_Tensor (m_product MM (m_product inv_MM xi)) r1 r2);\n  [ idtac | rewrite <- m_product_inv_M;  reflexivity];\n  replace (m_product inv_MM xi) with (m_product inv_MM\n  (right_product (left_product (product_init_zip xi alpha beta n) (product_init_rev alpha n)) (product_init_rev beta n)));\n  [ idtac | rewrite <- product_init_zip_init_rev_id; trivial].\n\n  assert (H_base: (-1<=as_Tensor (m_product inv_MM (right_product (left_product (product_init_zip xi alpha beta n)\n                                 (product_init_rev alpha n)) (product_init_rev beta n))) r1 r2 <= 1)%R).\n   rewrite m_product_left_right_product_associative.\n   rewrite as_Tensor_right_left_product_as_Moebius.\n    apply Is_refining_T_property;\n     try (apply rep_drop_in_range; assumption).\n     replace inv_MM with (inv_digit MM); trivial; apply Incl_T_absorbs_Is_refining_T; assumption.\n    apply denom_nonvanishing_product_init; assumption.\n    apply denom_nonvanishing_product_init; assumption.\n    apply rep_drop_in_range; assumption.\n    apply rep_drop_in_range; assumption.\n    replace inv_MM with (inv_digit MM); trivial; apply Incl_T_absorbs_Is_refining_T; assumption.\n\n  rewrite as_Tensor_M; try exact H_base.\n   refine\n     (rep_M \n       (quadratic (m_product inv_MM (product_init_zip xi alpha beta n)) (drop n alpha) (drop n beta) H_productive_dropped)\n       _ _ _ _ H_bis).\n\n    exact H_base.\n\n    rewrite m_product_left_right_product_associative;\n    rewrite as_Tensor_right_left_product_as_Moebius.\n     apply quadratic_correctness;\n     [ apply (rep_drop _ _ n Hr1_alpha)\n     | apply (rep_drop _ _ n Hr2_beta)\n     ]. \n     apply denom_nonvanishing_product_init; assumption.\n     apply denom_nonvanishing_product_init; assumption.\n     apply rep_drop_in_range; assumption.\n     apply rep_drop_in_range; assumption.\n     replace inv_MM with (inv_digit MM); trivial; apply Incl_T_absorbs_Is_refining_T; assumption.\n   rewrite m_product_left_right_product_associative; apply denom_nonvanishing_T_left_right_product.\n    apply denom_nonvanishing_product_init; assumption.\n    apply denom_nonvanishing_product_init; assumption.\n    apply rep_drop_in_range; assumption.\n    apply rep_drop_in_range; assumption.\n    replace inv_MM with (inv_digit MM); trivial; apply Incl_T_absorbs_Is_refining_T; assumption.\nDefined.\n\n", "meta": {"author": "coq-contribs", "repo": "coinductive-reals", "sha": "e1b67f1c3a4d23b2819e9977492728d3743abeec", "save_path": "github-repos/coq/coq-contribs-coinductive-reals", "path": "github-repos/coq/coq-contribs-coinductive-reals/coinductive-reals-e1b67f1c3a4d23b2819e9977492728d3743abeec/qcorrectness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.7577943712746407, "lm_q1q2_score": 0.6514483404269314}}
{"text": "Require Import init.\n\nRequire Export analysis_base.\nRequire Import analysis_topology.\nRequire Import order_minmax.\n\nDefinition cauchy_seq {U} `{Metric U} (f : sequence U) :=\n    ∀ ε, 0 < ε → ∃ N, ∀ i j, N ≤ i → N ≤ j → d (f i) (f j) < ε.\n\nDefinition complete U `{Metric U} := ∀ f, cauchy_seq f → seq_converges f.\n\nDefinition seq_bounded {U} `{Metric U} (f : nat → U)\n    := ∃ M, ∀ m n, d (f m) (f n) ≤ M.\n(* begin hide *)\n\nSection AnalysisSequence.\n\nContext {U} `{Metric U}.\n(* end hide *)\n\nTheorem metric_seq_lim : ∀ f x, seq_lim f x ↔\n    ∀ ε, 0 < ε → ∃ N, ∀ n, N ≤ n → d x (f n) < ε.\nProof.\n    intros f x.\n    rewrite basis_seq_lim.\n    split.\n    -   intros lim ε ε_pos.\n        pose proof (open_ball_basis x [ε|ε_pos]) as x_basis.\n        pose proof (open_ball_self x [ε|ε_pos]) as x_in.\n        exact (lim _ x_basis x_in).\n    -   intros lim S S_basis Sx.\n        destruct S_basis as [z [ε eq]]; subst S.\n        pose proof (open_ball_ex _ _ _ Sx) as [δ sub].\n        specialize (lim [δ|] [|δ]) as [N lim].\n        exists N.\n        intros n n_gt.\n        apply sub.\n        apply lim.\n        exact n_gt.\nQed.\n\nTheorem metric_seq_closure : ∀ (A : U → Prop) x,\n    (∃ f, (∀ n, A (f n)) ∧ seq_lim f x) ↔ closure A x.\nProof.\n    intros A x.\n    split.\n    -   intros [f [Af lim]].\n        exact (seq_closure A x f Af lim).\n    -   intros Ax.\n        assert (∀ n, 0 < / from_nat (nat_suc n)) as n_pos.\n        {\n            intros n.\n            apply div_pos.\n            rewrite <- homo_zero.\n            rewrite <- homo_lt2.\n            apply nat_pos2.\n        }\n        pose (B n := open_ball x [_|n_pos n]).\n        assert (∀ n, ∃ a, B n a ∧ A a) as f_ex.\n        {\n            intros n.\n            rewrite in_closure in Ax.\n            assert (open (B n)) as B_open.\n            {\n                unfold B.\n                apply open_ball_open.\n            }\n            assert (B n x) as Bnx by apply open_ball_self.\n            specialize (Ax (B n) B_open Bnx).\n            apply empty_neq in Ax as [a a_in].\n            rewrite inter_comm in a_in.\n            exists a.\n            exact a_in.\n        }\n        exists (λ n, ex_val (f_ex n)).\n        split.\n        +   intros n.\n            rewrite_ex_val a a_in.\n            apply a_in.\n        +   rewrite metric_seq_lim.\n            intros ε ε_pos.\n            pose proof (archimedean2 _ ε_pos) as [N N_lt].\n            exists N.\n            intros n n_gt.\n            rewrite_ex_val a a_in.\n            destruct a_in as [Bna Aa].\n            unfold B in Bna.\n            apply (trans2 N_lt).\n            rewrite <- nat_sucs_le in n_gt.\n            rewrite (homo_le2 (f := from_nat)) in n_gt.\n            apply le_div_pos in n_gt.\n            2: apply from_nat_pos.\n            apply (lt_le_trans2 n_gt).\n            exact Bna.\nQed.\n\nTheorem metric_seq_closed :\n    ∀ A, closed A ↔ (∀ f x, (∀ n, A (f n)) → seq_lim f x → A x).\nProof.\n    intros A.\n    split.\n    -   intros A_closed f x Af fx.\n        apply closed_if_closure in A_closed.\n        rewrite A_closed.\n        exact (seq_closure A x f Af fx).\n    -   intros all_f.\n        apply closed_if_closure.\n        apply antisym; try apply closure_sub.\n        intros x Ax.\n        apply metric_seq_closure in Ax.\n        destruct Ax as [f [all_n f_seq]].\n        exact (all_f f x all_n f_seq).\nQed.\n\nTheorem converges_cauchy : ∀ f, seq_converges f → cauchy_seq f.\nProof.\n    intros f [x fx] ε ε_pos.\n    pose proof (half_pos ε_pos) as ε2_pos.\n    rewrite metric_seq_lim in fx.\n    specialize (fx _ ε2_pos) as [N fx].\n    exists N.\n    intros i j i_gt j_gt.\n    pose proof (lt_lrplus (fx i i_gt) (fx j j_gt)) as ltq.\n    rewrite plus_half in ltq.\n    apply (le_lt_trans2 ltq).\n    rewrite (d_sym x).\n    apply d_tri.\nQed.\n\nTheorem limit_point_seq_ex :\n    ∀ X x, limit_point X x → ∃ f, (∀ n, X (f n) ∧ x ≠ f n) ∧ seq_lim f x.\nProof.\n    intros X x x_lim.\n    assert (∀ n, ∃ a, open_ball x [_|real_n_div_pos n] a ∧ X a ∧ x ≠ a) as f_ex.\n    {\n        intros n.\n        unfold limit_point in x_lim.\n        specialize (x_lim (open_ball x [_|real_n_div_pos n])).\n        specialize (x_lim (open_ball_open _ _) (open_ball_self _ _)).\n        apply empty_neq in x_lim.\n        destruct x_lim as [a [[Xa nxa] a_in]].\n        exists a.\n        rewrite singleton_eq in nxa.\n        split; [>|split]; assumption.\n    }\n    exists (λ n, ex_val (f_ex n)).\n    split.\n    -   intros n.\n        rewrite_ex_val a a_H.\n        split; apply a_H.\n    -   rewrite metric_seq_lim.\n        intros ε ε_pos.\n        pose proof (archimedean2 ε ε_pos) as [N N_lt].\n        exists N.\n        intros m m_geq.\n        rewrite_ex_val b b_H.\n        destruct b_H as [b_in [Xb xb]].\n        unfold open_ball in b_in; cbn in b_in.\n        apply (trans b_in).\n        apply (le_lt_trans2 N_lt).\n        apply le_div_pos.\n        1: apply from_nat_pos.\n        change (1 + from_nat m) with (from_nat (U := real) (nat_suc m)).\n        rewrite <- homo_le2.\n        rewrite nat_sucs_le.\n        exact m_geq.\nQed.\n\nTheorem cauchy_subseq_converge :\n    ∀ a b x, cauchy_seq a → subsequence a b → seq_lim b x → seq_lim a x.\nProof.\n    intros a b x a_cauchy [f [f_sub ab_eq]] b_lim.\n    rewrite metric_seq_lim in *.\n    intros ε ε_pos.\n    pose proof (half_pos ε_pos) as ε2_pos.\n    specialize (b_lim (ε / 2) ε2_pos) as [N1 b_lim].\n    specialize (a_cauchy (ε / 2) ε2_pos) as [N2 a_cauchy].\n    exists (max N1 N2).\n    intros n n_geq.\n    specialize (b_lim n (trans (lmax N1 N2) n_geq)).\n    rewrite <- ab_eq in b_lim.\n    pose proof (subsequence_seq_leq f f_sub n) as fn_leq.\n    apply (trans n_geq) in fn_leq.\n    apply (trans (rmax N1 N2)) in n_geq, fn_leq.\n    specialize (a_cauchy (f n) n fn_leq n_geq).\n    pose proof (lt_lrplus b_lim a_cauchy) as ltq.\n    rewrite plus_half in ltq.\n    apply (le_lt_trans2 ltq).\n    apply d_tri.\nQed.\n\n(* begin hide *)\nOpen Scope card_scope.\n(* end hide *)\nTheorem cauchy_bounded : ∀ a, cauchy_seq a → seq_bounded a.\nProof.\n    intros a a_cauchy.\n    specialize (a_cauchy 1 one_pos) as [N a_cauchy].\n    classic_case (0 = N) as [N_z|N_nz].\n    {\n        exists 1.\n        intros i j.\n        subst N.\n        apply a_cauchy; apply nat_pos.\n    }\n    pose (S m := ∃ i j, i < 1 + N ∧ j < 1 + N ∧ m = d (a i) (a j)).\n    assert (finite (|set_type S|)) as S_fin.\n    {\n        unfold finite.\n        apply (le_lt_trans2 (nat_is_finite ((1 + N)*(1 + N)))).\n        rewrite <- nat_to_card_mult.\n        unfold mult, le, nat_to_card; equiv_simpl.\n        pose (to_i (x : set_type S) := ex_val [|x]).\n        pose (to_j (x : set_type S) := ex_val (ex_proof [|x])).\n        pose (to_i_lt (x : set_type S)\n            := land (ex_proof (ex_proof [|x]))).\n        pose (to_j_lt (x : set_type S)\n            := land (rand (ex_proof (ex_proof [|x])))).\n        exists (λ x : set_type S, ([to_i x|to_i_lt x], [to_j x|to_j_lt x])).\n        split.\n        intros x y eq.\n        inversion eq as [[eq1 eq2]].\n        clear eq to_i_lt to_j_lt.\n        unfold to_i, to_j in *.\n        unfold ex_val in eq1 at 1; unfold ex_proof in eq2 at 1.\n        destruct (ex_to_type _) as [i C0]; cbn in *.\n        rewrite_ex_val j [i_lt [j_lt x_eq]]; clear C0.\n        unfold ex_val in eq1; unfold ex_proof in eq2.\n        destruct (ex_to_type _) as [i' C0]; cbn in *.\n        rewrite_ex_val j' [i'_lt [j'_lt y_eq]]; clear C0.\n        subst i' j'.\n        apply set_type_eq.\n        rewrite x_eq, y_eq.\n        reflexivity.\n    }\n    assert (∃ x, S x) as S_ex.\n    {\n        exists (d (a 0) (a 0)). (* Really just zero, but this is simpler. *)\n        exists 0, 0.\n        split.\n        2: split.\n        1, 2: split; try apply nat_pos.\n        1, 2: intros contr; inversion contr.\n        reflexivity.\n    }\n    pose proof (finite_well_ordered_set_max S S_fin S_ex) as [M[Sm M_greatest]].\n    assert (∀ i j, i < 1 + N → j < 1 + N → d (a i) (a j) < M + 1) as lem1.\n    {\n        intros i j i_lt j_lt.\n        pose proof one_pos as ltq.\n        apply lt_lplus with M in ltq.\n        rewrite plus_rid in ltq.\n        apply (le_lt_trans2 ltq).\n        apply M_greatest.\n        exists i, j.\n        split.\n        2: split.\n        -   exact i_lt.\n        -   exact j_lt.\n        -   reflexivity.\n    }\n    assert (∀ i j, 1 + N ≤ i → j < 1 + N → d (a i) (a j) < M + 1) as lem2.\n    {\n        intros i j i_ge j_lt.\n        pose proof (trans (nat_le_suc N) i_ge) as i_ge2.\n        specialize (a_cauchy _ _ i_ge2 (refl N)).\n        assert (d (a N) (a j) ≤ M) as leq.\n        {\n            apply M_greatest.\n            exists N, j.\n            split.\n            2: split.\n            -   apply nat_lt_suc.\n            -   exact j_lt.\n            -   reflexivity.\n        }\n        pose proof (le_lt_lrplus leq a_cauchy) as ltq.\n        clear - ltq.\n        apply (le_lt_trans2 ltq).\n        rewrite plus_comm.\n        apply d_tri.\n    }\n    assert (∀ i j, 1 + N ≤ i → 1 + N ≤ j → d (a i) (a j) < M + 1) as lem3.\n    {\n        intros i j i_ge j_ge.\n        assert (N ≤ i) as i_ge2.\n        {\n            apply (trans2 i_ge).\n            apply nat_le_suc.\n        }\n        assert (N ≤ j) as j_ge2.\n        {\n            apply (trans2 j_ge).\n            apply nat_le_suc.\n        }\n        specialize (a_cauchy i j i_ge2 j_ge2).\n        apply (lt_le_trans a_cauchy).\n        rewrite <- (plus_lid 1) at 1.\n        apply le_rplus.\n        apply M_greatest.\n        exists 0, 0.\n        split.\n        2: split.\n        1, 2: apply nat_pos2.\n        rewrite d_zero.\n        reflexivity.\n    }\n    exists (M + 1).\n    intros i j.\n    classic_case (i < 1 + N) as [i_lt|i_ge];\n    classic_case (j < 1 + N) as [j_lt|j_ge].\n    -   apply lem1; assumption.\n    -   rewrite nlt_le in j_ge.\n        rewrite d_sym.\n        apply lem2; assumption.\n    -   rewrite nlt_le in i_ge.\n        apply lem2; assumption.\n    -   rewrite nlt_le in i_ge, j_ge.\n        apply lem3; assumption.\nQed.\n(* begin hide *)\n\nClose Scope card_scope.\n\nEnd AnalysisSequence.\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/Analysis/analysis_sequence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6514483357245882}}
{"text": "(* \n  Author(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\nRequire Import List Lia.\nImport ListNotations.\nRequire Import Undecidability.SystemF.SysF Undecidability.SystemF.Autosubst.syntax Undecidability.SystemF.Autosubst.unscoped.\nImport UnscopedNotations.\nRequire Import Undecidability.SystemF.Util.Facts Undecidability.SystemF.Util.poly_type_facts.\n\nRequire Import ssreflect ssrbool ssrfun.\n\nSet Default Goal Selector \"!\".\n\n(* evaluates predicate p on all free variables *)\nFixpoint allfv_pure_term (p: nat -> Prop) (M: pure_term) :=\n  match M with\n  | pure_var x => p x\n  | pure_app M N => allfv_pure_term p M /\\ allfv_pure_term p N\n  | pure_abs M => allfv_pure_term (scons True p) M\n  end.\n  \nLemma allfv_pure_term_impl {p1 p2: nat -> Prop} {M}: \n  (forall x, p1 x -> p2 x) -> allfv_pure_term p1 M -> allfv_pure_term p2 M.\nProof.\n  elim: M p1 p2.\n  - move=> >. by apply.\n  - by move=> ? IH1 ? IH2 > /= /copy [/IH1 {}IH1 /IH2 {}IH2] [/IH1 ? /IH2 ?].\n  - move=> > IH > H /=. apply: IH. by case.\nQed.\n\nLemma allfv_pure_term_ren_pure_term {p ξ M} : \n  allfv_pure_term p (ren_pure_term ξ M) <-> allfv_pure_term (ξ >> p) M.\nProof.\n  elim: M ξ p.\n  - done.\n  - move=> ? IH1 ? IH2 > /=. by rewrite IH1 IH2.\n  - move=> ? IH > /=. rewrite IH. constructor; apply: allfv_pure_term_impl; by case.\nQed.\n\nLemma allfv_pure_term_TrueI {p: nat -> Prop} {M} : (forall x, p x) -> allfv_pure_term p M.\nProof.\n  move=> Hp. elim: M.\n  - move=> > /=. by apply: Hp.\n  - by move=> ? + ? + /=.\n  - move=> ? /=. apply: allfv_pure_term_impl. case; first done.\n    move=> *. by apply: Hp.\nQed.\n\nLemma ren_pure_term_id {M} : ren_pure_term id M = M.\nProof.\n  elim: M.\n  - done.\n  - move=> /=. congruence.\n  - move=> /=. rewrite /upRen_pure_term_pure_term.\n    move=> > ?. under extRen_pure_term => ? do rewrite up_ren_id. by congruence.\nQed.\n\nLemma ren_pure_term_id' {ξ M} : (forall x, ξ x = x) -> ren_pure_term ξ M = M.\nProof. move=> ?. rewrite -[RHS]ren_pure_term_id. by apply: extRen_pure_term. Qed.\n\nFixpoint pure_var_bound (M: pure_term) :=\n  match M with\n  | pure_var x => 1 + x\n  | pure_app M N => 1 + pure_var_bound M + pure_var_bound N\n  | pure_abs M => 1 + pure_var_bound M\n  end.\n\nLemma pure_var_boundP M : allfv_pure_term (gt (pure_var_bound M)) M.\nProof.\n  elim: M.\n  - move=> /=. by lia.\n  - move=> ? IH1 ? IH2 /=. constructor; [move: IH1 | move: IH2]; apply: allfv_pure_term_impl; by lia.\n  - move=> ? /=. apply: allfv_pure_term_impl. case; first done. move=> /=. by lia.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/SystemF/Util/pure_term_facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7879312006227323, "lm_q1q2_score": 0.6513920097429925}}
{"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(* ** Bitwise operations on nat as list bool *)\n\nRequire Import List Lia Bool Setoid.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac.\n\nSet Implicit Arguments.\n\n(* Section lb. *)\n\n  Local Reserved Notation \"x ⪯ y\" (at level 70, no associativity).\n  Local Reserved Notation \"x ⟂ y\" (at level 70, no associativity).\n  Local Reserved Notation \"x ↓ y\" (at level 40, left associativity).\n  Local Reserved Notation \"x ↑ y\" (at level 41, left associativity).\n\n  Local Notation lb := (list bool).\n  Local Notation \"⟘\" := false.\n  Local Notation \"⟙\" := true.\n  Local Infix \"⪦\" := Bool.le (at level 70, no associativity).\n\n  Fact leb_refl : forall x, x ⪦ x.\n  Proof. intros []; simpl; auto. Qed.\n\n  Fact leb_trans : forall x y z, x ⪦ y -> y ⪦ z -> x ⪦ z.\n  Proof. intros [] [] []; simpl; auto. Qed.\n\n  Fact leb_strict : ⟘ ⪦ ⟙.\n  Proof. exact I. Qed. \n\n  #[export] Hint Resolve leb_refl leb_trans leb_strict : core.\n\n  (* We develop the Boolean algebra of lists of Booleans *)\n\n  (* The masking relation *)\n\n  Inductive lb_mask : lb -> lb -> Prop :=\n    | in_lb_mask_0 : forall l,                            nil ⪯ l\n    | in_lb_mask_1 : forall l,                l ⪯ nil -> ⟘::l ⪯  nil \n    | in_lb_mask_2 : forall x y l m, x ⪦ y -> l ⪯ m   -> x::l ⪯  y::m\n  where \"l ⪯ m\" := (lb_mask l m).\n\n  Fact lb_mask_inv_nil l : ⟘::l ⪯  nil -> l ⪯  nil.\n  Proof. inversion 1; auto. Qed. \n\n  Fact lb_mask_inv_left x l : x::l ⪯  nil -> x = ⟘ /\\ l ⪯  nil.\n  Proof. inversion 1; auto. Qed. \n\n  Fact lb_mask_inv_cons x y l m : x::l ⪯ y::m -> Bool.le x y /\\ l ⪯  m.\n  Proof. inversion 1; tauto. Qed.\n\n  Fact lb_mask_inv_cons_nil l : ⟙::l ⪯ nil -> False.\n  Proof. inversion 1. Qed.\n\n  Fact lb_mask_inv_cons_cons l m : ⟙::l ⪯ ⟘::m -> False.\n  Proof.\n    intros H; apply lb_mask_inv_cons, proj1 in H; discriminate.\n  Qed.\n \n  Definition lb_mask_leb := in_lb_mask_2.\n\n  Fact lb_mask_refl l : l ⪯ l.\n  Proof. induction l as [ | [] ]; constructor; simpl; auto. Qed.\n\n  Fact lb_mask_trans l m k : l ⪯ m -> m ⪯ k -> l ⪯ k.\n  Proof.\n    intros H1; revert H1 k.\n    induction 1 as [ l | l H1 IH1 | x y l m H1 IH1 ].\n    + intros; constructor.\n    + intros [ | z k ] Hk.\n      * constructor; auto.\n      * constructor; simpl; auto; apply IH1; constructor.\n    + intros [ | z k ] Hk.\n      * apply lb_mask_inv_left in Hk; destruct Hk as (? & Hk); subst y.\n        destruct x; simpl in H1; try discriminate.\n        constructor; auto.\n      * apply lb_mask_inv_cons in Hk. \n        destruct Hk as (H2 & Hk).\n        constructor; auto.\n        revert x y z H1 H2.\n        intros [] [] []; simpl; auto.\n  Qed.\n\n  #[export] Hint Resolve lb_mask_refl lb_mask_trans : core.\n\n  Definition lb_mask_equiv l m := l ⪯ m /\\ m ⪯ l.\n\n  Local Infix \"≂\" := lb_mask_equiv (at level 70, no associativity).\n\n  Fact lb_mask_equiv_refl l : l ≂ l.\n  Proof. split; auto. Qed.\n\n  Fact lb_mask_equiv_sym l m : l ≂ m -> m ≂ l.\n  Proof. intros []; split; auto. Qed.\n\n  Fact lb_mask_equiv_trans l m k : l ≂ m -> m ≂ k -> l ≂ k.\n  Proof. intros [] []; split; eauto. Qed.\n\n  #[export] Hint Resolve in_lb_mask_0 lb_mask_refl lb_mask_equiv_refl : core.\n\n  Add Parametric Relation: (lb) (lb_mask_equiv)\n      reflexivity proved by  lb_mask_equiv_refl\n      symmetry proved by     lb_mask_equiv_sym\n      transitivity proved by lb_mask_equiv_trans\n    as lb_mask_equiv_rst.\n\n  Local Notation lbeq := lb_mask_equiv (only parsing).\n\n  Add Parametric Morphism: (lb_mask) with signature (lbeq) ==> (lbeq) ==> (iff) as lb_mask_le_iff.\n  Proof. \n    intros x1 y1 (H1 & H2) x2 y2 (H3 & H4); split; intros H5.\n    + apply lb_mask_trans with (1 := H2), lb_mask_trans with (1 := H5); auto.\n    + apply lb_mask_trans with (1 := H1), lb_mask_trans with (1 := H5); auto.\n  Qed.\n\n  Add Parametric Morphism: (@cons bool) with signature (eq) ==> (lbeq) ==> (lbeq) as lb_mask_equiv_cons.\n  Proof.\n    intros [] ? ? []; split; apply lb_mask_leb; simpl; auto.\n  Qed.\n\n  Fact lb_mask_app l m a b : length l = length m -> l ⪯ m -> a ⪯ b -> l++a ⪯ m++b.\n  Proof.\n    revert m; induction l as [ | x l IHl ]; intros [ | y m ]; try discriminate; auto;\n      simpl; intros H H1 H2.\n    apply lb_mask_inv_cons in H1; destruct H1 as (H1 & H3).\n    constructor 3; auto.\n  Qed.\n\n  Fact lb_mask_equiv_app l m a b : length l = length m -> l ≂ m -> a ≂ b -> l++a ≂ m++b.\n  Proof.\n    intros H (? & ?) (? & ?); split; apply lb_mask_app; auto.\n  Qed.\n\n  Inductive lb_ortho : lb -> lb -> Prop :=\n    | in_lb_ortho_0 : forall l, nil ⟂ l\n    | in_lb_ortho_1 : forall l, l ⟂ nil\n    | in_lb_ortho_2 : forall x y l m, (x = ⟘ \\/ y = ⟘) -> l ⟂ m -> x::l ⟂ y::m\n  where \"x ⟂ y\" := (lb_ortho x y).\n\n  #[export] Hint Constructors lb_ortho : core.\n\n  Fact lb_ortho_cons_inv x y l m : x::l ⟂ y::m -> (x = ⟘ \\/ y = ⟘) /\\ l ⟂ m.\n  Proof. inversion 1; auto. Qed.\n\n  Fact lb_ortho_anti_left a b x : a ⪯ b -> b ⟂ x -> a ⟂ x.\n  Proof.\n    intros H; revert H x.\n    induction 1 as [ l | m H1 IH1 | x y l m H1 H2 IH2  ]; intros z H3; try (constructor; fail);\n      destruct z as [ | v z ]; try (constructor; fail).\n    + constructor; auto; apply IH1; constructor.\n    + apply lb_ortho_cons_inv in H3.\n      destruct H3 as (H3 & H4).\n      constructor; auto. \n      revert x y v H1 H3.\n      intros [] [] []; simpl; auto.\n  Qed.\n\n  Fact lb_ortho_sym a b : a ⟂ b -> b ⟂ a.\n  Proof. induction 1; constructor; tauto. Qed.\n\n  Fact lb_ortho_anti a b x y : a ⪯ b -> x ⪯ y -> b ⟂ y -> a ⟂ x.\n  Proof. \n    intros H1 H2 H3.\n    apply lb_ortho_anti_left with (1 := H1), lb_ortho_sym,\n          lb_ortho_anti_left with (1 := H2), lb_ortho_sym.\n    trivial.\n  Qed.\n\n  Add Parametric Morphism: (lb_ortho) with signature (lbeq) ==> (lbeq) ==> (iff) as lb_ortho_iff.\n  Proof. intros ? ? [] ? ? []; split; apply lb_ortho_anti; auto. Qed.\n\n  Section lb_pointwise.\n\n    Variable (f : bool -> bool -> bool).\n\n    Fixpoint lb_pointwise l m := \n      match l, m with\n        | nil,   nil  => nil\n        |  _,    nil  => map (fun x => f x ⟘) l\n        | nil,     _  => map (f ⟘) m\n        | x::l, y::m  => f x y :: lb_pointwise l m\n      end.\n\n    Fact lb_pointwise_nil : lb_pointwise nil nil = nil.\n    Proof. trivial. Qed.\n\n    Fact lb_pointwise_left l : lb_pointwise l nil = map (fun x => f x ⟘) l.\n    Proof. destruct l; trivial. Qed.\n\n    Fact lb_pointwise_right l : lb_pointwise nil l = map (f ⟘) l.\n    Proof. destruct l; trivial. Qed.\n \n    Fact lb_pointwise_cons x l y m : lb_pointwise (x::l) (y::m) = f x y :: lb_pointwise l m.\n    Proof. trivial. Qed.\n\n    Fact lb_pointwise_length n l m : length l <= n -> length m <= n -> length (lb_pointwise l m) <= n.\n    Proof.\n      revert l m; induction n as [ | n IHn ].\n      + intros [] []; simpl; lia.\n      + intros [ | x l ] [ | y m ]; simpl; try rewrite map_length; auto.\n        intros; apply le_n_S, IHn; lia.\n    Qed.\n\n    Fact lb_pointwise_sym l m : (forall x y, f x y = f y x) -> lb_pointwise l m = lb_pointwise m l.\n    Proof.\n      intros H; revert l m; induction l as [ | x l IHl ]; intros m.\n      + rewrite lb_pointwise_left, lb_pointwise_right.\n        apply map_ext; intro; auto.\n      + destruct m as [ | y m ].\n        * rewrite lb_pointwise_left, lb_pointwise_right.\n          apply map_ext; intro; auto.\n        * do 2 rewrite lb_pointwise_cons; f_equal; auto.\n    Qed.\n\n    Variable (Hf1 : forall x a b, Bool.le a b -> Bool.le (f x a) (f x b)) \n             (Hf2 : f ⟘ ⟘ = ⟘).\n\n    Let lbpw_mono_1 l m :  lb_pointwise l nil ⪯   lb_pointwise l m.\n    Proof.\n      rewrite lb_pointwise_left.\n      revert m; induction l as [ | x l IHl ]; intros m.\n      + simpl; constructor.\n      + destruct m as [ | y m ]; simpl.\n        * apply lb_mask_refl.\n        * apply lb_mask_leb; auto.\n    Qed.\n\n    Let lbpw_mono_f_0 g l m : g ⟘ = ⟘ -> Bool.le (g ⟘) (g ⟙) -> l ⪯ m -> map g l ⪯  map g m.\n    Proof.\n      intros H1 H2.\n      assert (Hg : forall x y, x ⪦ y -> g x ⪦ g y).\n      { intros [] []; simpl; auto; discriminate. }\n      induction 1; simpl; try rewrite H1; constructor; auto.\n    Qed.\n\n    Let lbpw_mono_2 l m : m ⪯ nil -> lb_pointwise l m ⪯   lb_pointwise l nil.\n    Proof.\n      revert m; induction l as [ | x l IHl ]; intros [ | y m ] H.\n      + constructor.\n      + rewrite lb_pointwise_right.\n        apply lbpw_mono_f_0 with (g := f ⟘) in H; auto.\n      + apply lb_mask_refl.\n      + rewrite lb_pointwise_cons, lb_pointwise_left.\n        apply lb_mask_inv_left in H.\n        destruct H as (E & H); subst y.\n        simpl.\n        apply lb_mask_leb.\n        1: destruct (f x ⟘); simpl; auto.\n        apply lb_mask_trans with (1 := IHl _ H).\n        rewrite lb_pointwise_left.\n        apply lb_mask_refl.\n    Qed.\n\n    Fact lb_pointwise_mono_left l m k : l ⪯  m -> lb_pointwise k l ⪯   lb_pointwise k m.\n    Proof using Hf1 Hf2.\n      intros H; revert m H k.\n      induction l as [ | x l IHl ]; intros m H k; auto.\n      destruct m as [ | y m ].\n      * apply lbpw_mono_2; auto.\n      * destruct k as [ | u k ].\n        - apply lbpw_mono_f_0; auto.\n        - do 2 rewrite lb_pointwise_cons.\n          apply lb_mask_inv_cons in H; destruct H.\n          apply lb_mask_leb; auto.\n    Qed.\n  \n  End lb_pointwise.\n\n  Definition lb_meet := (lb_pointwise andb).\n  Definition lb_join := (lb_pointwise orb).\n\n  Local Infix \"↓\" := lb_meet.\n  Local Infix \"↑\" := lb_join.\n\n  Fact lb_meet_left x : x↓nil ≂ nil.\n  Proof.\n    unfold lb_meet.\n    split; try (constructor; fail).\n    rewrite lb_pointwise_left.\n    induction x as [ | [] x ]; simpl; constructor; auto.\n  Qed.\n\n  Fact lb_meet_comm l m : l↓m = m↓l.\n  Proof.\n    apply lb_pointwise_sym.\n    destruct x; destruct y; auto.\n  Qed.\n\n  Fact lb_meet_right x : nil↓x ≂ nil.\n  Proof.\n    rewrite lb_meet_comm; apply lb_meet_left.\n  Qed.\n\n  Fact lb_meet_cons x y l m : (x::l) ↓ (y::m) = x && y :: l↓m.\n  Proof. auto. Qed.\n\n  Fact lb_meet_mono l m a b : l ⪯ m -> a ⪯ b -> l↓a ⪯  m↓b.\n  Proof.\n    intros H1 H2.\n    apply lb_mask_trans with (l↓b).\n    + apply lb_pointwise_mono_left;auto.\n      intros [] [] []; simpl; auto; discriminate.\n    + do 2 rewrite (lb_meet_comm _ b).\n      apply lb_pointwise_mono_left;auto.\n      intros [] [] []; simpl; auto; discriminate.\n  Qed.\n\n  Add Parametric Morphism: (lb_meet) with signature (lbeq) ==> (lbeq) ==> (lbeq) as lb_meet_eq.\n  Proof. intros ? ? [] ? ? []; split; apply lb_meet_mono; auto. Qed.\n\n  Fact lb_meet_length_le n l m : length l <= n -> length m <= n -> length (l↓m) <= n.\n  Proof. apply lb_pointwise_length. Qed.\n\n  Fact lb_meet_length a b : length a = length b -> length (a↓b) = length a.\n  Proof.\n    revert b; induction a as [ | x a IHa ]; intros [ | y b ]; try discriminate; auto;\n      intros H.\n    rewrite lb_meet_cons; simpl; f_equal; auto.\n  Qed.\n\n  Fact lb_meet_app l m a b : length l = length m -> (l++a)↓(m++b) = l↓m++a↓b.   \n  Proof.\n    revert m; induction l as [ | x l IHl ]; intros [ | y m ]; try discriminate; intros H.\n    + simpl; auto.\n    + simpl app.\n      rewrite lb_meet_cons; f_equal.\n      apply IHl.\n      simpl in H; inversion H; auto.\n  Qed.\n\n  Fact lb_join_left x : x↑nil = x.\n  Proof.\n    unfold lb_join.\n    rewrite lb_pointwise_left.\n    induction x as [ | [] ]; simpl; f_equal; auto.\n  Qed.\n\n  Fact lb_join_comm l m : l↑m = m↑l.\n  Proof.\n    apply lb_pointwise_sym.\n    destruct x; destruct y; auto.\n  Qed.\n\n  Fact lb_join_right x : nil↑x = x.\n  Proof.\n    rewrite lb_join_comm; apply lb_join_left.\n  Qed.\n \n  Fact lb_join_cons x y l m : (x::l) ↑ (y::m) = x || y :: l↑m.\n  Proof. auto. Qed.\n\n  Fact lb_join_length_le n l m : length l <= n -> length m <= n -> length (l↑m) <= n.\n  Proof. apply lb_pointwise_length. Qed.\n\n  Fact lb_join_mono l m a b : l ⪯ m -> a ⪯ b -> l↑a ⪯  m↑b.\n  Proof.\n    intros H1 H2.\n    apply lb_mask_trans with (l↑b).\n    + apply lb_pointwise_mono_left;auto.\n      intros [] [] []; simpl; auto; discriminate.\n    + do 2 rewrite (lb_join_comm _ b).\n      apply lb_pointwise_mono_left;auto.\n      intros [] [] []; simpl; auto; discriminate.\n  Qed.\n\n  Add Parametric Morphism: (lb_join) with signature (lbeq) ==> (lbeq) ==> (lbeq) as lb_join_eq.\n  Proof. intros ? ? [] ? ? []; split; apply lb_join_mono; auto. Qed.\n\n  Fact lb_ortho_meet_nil x y : x ⟂ y <-> x↓y ≂ nil.\n  Proof.\n    split.\n    + intros H; split; try constructor; revert H.\n      induction 1 as [ m | l | x y l m ].\n      - rewrite lb_meet_right; constructor.\n      - rewrite lb_meet_left; constructor.\n      - rewrite lb_meet_cons.\n        simpl; destruct H; [ destruct y | destruct x ]; try discriminate; subst; simpl; constructor; auto.\n    + intros [ H1 _ ]; revert H1.\n      revert y; induction x as [ | x l IHl ]; intros [ | y m ]; simpl; intros H; try (constructor; fail).\n      destruct x; destruct y; simpl in H |- *; try (inversion H; fail);\n        apply lb_mask_inv_nil in H; constructor; auto.\n  Qed.\n\n  #[export] Hint Resolve lb_mask_equiv_refl : core.\n\n  Fact lb_join_inc_left a b : a ⪯  a↑b.\n  Proof.\n    revert b; induction a as [ | x a IHa ]; intros b.\n    + constructor.\n    + destruct b as [ | y b ].\n      * rewrite lb_join_left; auto.\n      * rewrite lb_join_cons.\n        apply lb_mask_leb; auto.\n        destruct x; destruct y; simpl; auto.\n  Qed.\n\n  Fact lb_meet_dec_left a b : a↓b ⪯  a.\n  Proof.\n    revert b; induction a as [ | x a IHa ]; intros b.\n    + rewrite lb_meet_right; constructor.\n    + destruct b as [ | y b ].\n      * rewrite lb_meet_left; constructor. \n      * rewrite lb_meet_cons.\n        apply lb_mask_leb; auto.\n        destruct x; destruct y; simpl; auto.\n  Qed.\n\n  Fact lb_join_inc_right a b : b ⪯  a↑b.\n  Proof. rewrite lb_join_comm; apply lb_join_inc_left. Qed.\n\n  Fact lb_meet_dec_right a b : a↓b ⪯  b.\n  Proof. rewrite lb_meet_comm; apply lb_meet_dec_left. Qed.\n  \n  #[export] Hint Resolve lb_join_inc_left lb_join_inc_right lb_meet_dec_left lb_meet_dec_right : core.\n\n  Fact lb_mask_join a b : a ⪯  b <-> a↑b ≂ b.\n  Proof.\n    split.\n    + intros H; split.\n      2: rewrite lb_join_comm; auto.\n      induction H as [ | | x y ? ? H ].\n      * rewrite lb_join_right; auto.\n      * rewrite lb_join_left; constructor; auto.\n      * rewrite lb_join_cons; constructor; auto.\n        revert x y H; intros [] []; simpl; auto.\n    + intros (H1 & _).\n      apply lb_mask_trans with (2 := H1); auto.\n  Qed.\n\n  Fact lb_mask_meet a b : a ⪯  b <-> a↓b ≂ a.\n  Proof.\n    split.\n    + intros H; split; auto.\n      induction H as [ | | x y ? ? H ].\n      * constructor.\n      * rewrite lb_meet_left; constructor; auto.\n      * rewrite lb_meet_cons; constructor; auto.\n        revert x y H; intros [] []; simpl; auto.\n    + intros (H1 & H2).\n      apply lb_mask_trans with (1 := H2).\n      rewrite lb_meet_comm; auto.\n  Qed.\n\n  Fact lb_meet_idem a : a↓a = a.\n  Proof.\n    induction a as [ | x a ]; auto.\n    rewrite lb_meet_cons; f_equal; auto.\n    destruct x; simpl; auto.\n  Qed.\n\n  Fact lb_join_idem a : a↑a = a.\n  Proof.\n    induction a as [ | x a ]; auto.\n    rewrite lb_join_cons; f_equal; auto.\n    destruct x; simpl; auto.\n  Qed.\n\n  Tactic Notation \"rew\" \"lb\"  :=\n       repeat (  rewrite lb_meet_left || rewrite lb_meet_right\n              || rewrite lb_join_left || rewrite lb_join_right); auto.\n\n  Fact lb_join_meet_distr a b c : a↑(b↓c) ≂ (a↑b)↓(a↑c).\n  Proof.\n    revert b c; induction a as [ | x a IHa ]; intros b c.\n    + rew lb.\n    + destruct b as [ | y b ].\n      * rew lb.\n        rewrite (proj1 (lb_mask_meet _ _)); auto.\n      * destruct c as [ | z c ].\n        - rew lb.\n          rewrite lb_meet_comm. \n          rewrite (proj1 (lb_mask_meet _ _)); auto.\n        - repeat rewrite lb_meet_cons.\n          repeat rewrite lb_join_cons.\n          repeat rewrite lb_meet_cons.\n          apply lb_mask_equiv_cons; auto.\n          destruct x; destruct y; destruct z; simpl; auto.\n  Qed.\n\n  Fact lb_meet_join_distr a b c : a↓(b↑c) ≂ (a↓b)↑(a↓c).\n  Proof.\n    revert b c; induction a as [ | x a IHa ]; intros b c.\n    + rew lb.\n    + destruct b as [ | y b ].\n      * rew lb.\n      * destruct c as [ | z c ].\n        - rew lb.\n        - repeat rewrite lb_meet_cons.\n          repeat rewrite lb_join_cons.\n          repeat rewrite lb_meet_cons.\n          apply lb_mask_equiv_cons; auto.\n          destruct x; destruct y; destruct z; simpl; auto.\n  Qed.\n\n  Fact lb_meet_assoc a b c : a↓(b↓c) ≂ a↓b↓c.\n  Proof.\n    revert b c; induction a as [ | x a IHa ]; intros b c.\n    + rew lb.\n    + destruct b as [ | y b ].\n      * rew lb.\n      * destruct c as [ | z c ].\n        - rew lb.\n        - repeat rewrite lb_meet_cons.\n          apply lb_mask_equiv_cons; auto.\n          destruct x; destruct y; destruct z; simpl; auto.\n  Qed.\n\n  Fact lb_join_assoc a b c : a↑(b↑c) ≂ a↑b↑c.\n  Proof.\n    revert b c; induction a as [ | x a IHa ]; intros b c.\n    + rew lb.\n    + destruct b as [ | y b ].\n      * rew lb.\n      * destruct c as [ | z c ].\n        - rew lb.\n        - repeat rewrite lb_join_cons.\n          apply lb_mask_equiv_cons; auto.\n          destruct x; destruct y; destruct z; simpl; auto.\n  Qed.\n\n  #[export] Hint Resolve lb_meet_mono lb_join_mono : core.\n  \n  Fact lb_join_spec a b c : a ⪯  c -> b ⪯  c -> a↑b ⪯  c.\n  Proof. intros; rewrite <- (lb_join_idem c); auto. Qed.\n\n  Fact lb_meet_spec a b c : c ⪯  a -> c ⪯  b -> c ⪯  a↓b.\n  Proof. intros; rewrite <- (lb_meet_idem c); auto. Qed.\n\n  Fact lb_meet_join_idem a b : a↓(a↑b) ≂ a.\n  Proof. rewrite <- lb_mask_meet; auto. Qed.\n\n  Fact lb_join_meet_idem a b : a↑(a↓b) ≂ a.\n  Proof. rewrite lb_join_comm, <- lb_mask_join; auto. Qed.\n\n  Fact lb_join_nil_eq a b : a↑b ≂ nil -> a ≂ nil /\\ b ≂ nil.\n  Proof.\n    intros H; split.\n    rewrite <- (lb_meet_left a), <- H, lb_meet_join_idem; auto.\n    rewrite <- (lb_meet_left b), <- H, lb_join_comm, lb_meet_join_idem; auto.\n  Qed.\n\n  Fact lb_ortho_join a x y : a ⟂ x↑y <-> a ⟂ x /\\ a ⟂ y.\n  Proof.\n    do 3 rewrite lb_ortho_meet_nil; split.\n    + intros H; apply lb_join_nil_eq.\n      rewrite <- lb_meet_join_distr, H; auto.\n    + intros (H1 & H2).\n      rewrite lb_meet_join_distr, H1, H2; auto.\n  Qed.\n\n  Fact lb_ortho_mask_nil a x : a ⟂ x -> x ⪯  a -> x ≂ nil.\n  Proof. \n    induction 1 as [ | | x y l m H1 H2 IH2 ]; auto.\n    + split; auto.\n    + intros H.\n      apply lb_mask_inv_cons in H; destruct H as (H3 & H4).\n      rewrite IH2; auto; split; auto.\n      revert x y H1 H3.\n      intros [] []; simpl; intros [] ?; try discriminate; constructor; auto.\n  Qed.\n\n  (* c = a - b *)\n\n  Section lb_complement.\n\n    Let bin_comp a b :=\n      match a, b with\n        | ⟘, ⟘  => ⟘ \n        | ⟘, ⟙  => ⟘\n        | ⟙, ⟘  => ⟙\n        | ⟙, ⟙  => ⟘ \n    end.\n\n    Definition lb_complement a b : { c | b ⟂ c /\\ a↑b ≂ c↑b }.\n    Proof.\n       revert b; induction a as [ | x a IHa ]; intros b.\n       + exists nil; split; auto.\n       + destruct b as [ | y b ].\n         - exists (x :: a); split; auto.\n         - destruct (IHa b) as (c & H1 & H2).\n           exists (bin_comp x y::c).\n           revert x y; intros [] []; simpl; split; auto; \n             rewrite H2; simpl; auto.\n    Qed.\n\n  End lb_complement.\n\n  Definition lb_minus a b : a ⪯ b -> { c | a ⟂ c /\\ b ≂ a↑c }.\n  Proof.\n    intros H.\n    destruct (lb_complement b a) as (c & H1 & H2).\n    exists c; split; auto.\n    rewrite lb_mask_join in H.\n    rewrite <- H, (lb_join_comm a), (lb_join_comm a); auto.\n  Qed.\n\n(* End lb.\n\n#[export] Hint Resolve leb_refl leb_trans leb_strict.\n#[export] Hint Resolve lb_mask_refl lb_mask_trans.\n#[export] Hint Resolve in_lb_mask_0 lb_mask_refl lb_mask_equiv_refl.\nLocal Hint Constructors lb_mask lb_ortho.\n#[export] Hint Resolve lb_mask_equiv_refl.\n#[export] Hint Resolve lb_join_inc lb_meet_dec_left lb_meet_dec_right.\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/bool_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012105, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.6513920048732547}}
{"text": "(** * Ordered types, suprema/infima, continuity, etc. *)\n\n(** See cpo.v and aCPO.v for more order-theoretic definitions that\n  build upon those here. *)\n\nFrom Coq Require Import\n  Basics\n  Morphisms\n  PeanoNat\n  Relation_Definitions\n  Lia\n  Equivalence\n  ZArith\n.\n\nLocal Open Scope program_scope.\nLocal Open Scope equiv_scope.\n\nFrom algco Require Import\n  axioms\n  misc\n  tactics\n.\n\nCreate HintDb order.\n\n(** Ordered types. *)\nClass OType (A : Type) : Type :=\n  { leq : relation A\n  ; leq_preorder : PreOrder leq\n  }.\n\n#[global]\n  Instance OType_Reflexive A `{o : OType A} : Reflexive leq.\nProof. destruct o; typeclasses eauto. Qed.\n\n#[global]\n  Instance OType_Transitive A `{o : OType A} : Transitive leq.\nProof. destruct o; typeclasses eauto. Qed.\n\nDefinition gt {A : Type} `{OType A} : relation A := fun x y => not (leq x y).\n\nDefinition lt {A : Type} `{OType A} : relation A := fun x y => leq x y /\\ not (leq y x).\n\n#[global]\n  Instance Transitive_lt A `{o : OType A} : Transitive lt.\nProof.\n  destruct o as [R [Hrefl Htrans]].\n  intros x y z [H0 H1] [H2 H3].\n  unfold lt; simpl in *; split.\n  - eapply Htrans; eauto.\n  - intro HC; apply H3.\n    eapply Htrans; eauto.\nQed.\n\nDeclare Scope order_scope.\nNotation \"x '⊑' y\" := (leq x y) (at level 70, no associativity) : order_scope.\nNotation \"x '⊏' y\" := (lt x y) (at level 70, no associativity) : order_scope.\nLocal Open Scope order_scope.\n\n(** Pointed ordered types *)\nClass PType (A : Type) `{o : OType A} : Type :=\n  { bot : A\n  ; bot_le : forall x, bot ⊑ x }.\n\n#[global] Hint Resolve bot_le : order.\n\nNotation \"⊥\" := bot.\n\nLemma bot_leq {A} `{PType A} :\n  forall a : A, ⊥ ⊑ a.\nProof. intro; apply bot_le. Qed.\n#[global] Hint Resolve bot_leq : order.\n\n(** Ordered types with a top element *)\nClass TType (A : Type) `{o : OType A} : Type :=\n  { top : A\n  ; le_top : forall x, x ⊑ top }.\n\nNotation \"⊤\" := top.\n\nLemma leq_top {A} `{TType A} :\n  forall a : A, a ⊑ ⊤.\nProof. intro; apply le_top. Qed.\n#[global] Hint Resolve leq_top : order.\n\n(* [a] is an upper bound of [f] *)\nDefinition upper_bound {I A : Type} `{OType A} (a : A) (f : I -> A) :=\n  forall i, f i ⊑ a.\n\n(* [a] is a lower bound of [f] *)\nDefinition lower_bound {I A : Type} `{OType A} (a : A) (f : I -> A) :=\n  forall i, a ⊑ f i.\n\n(* [a] is the least upper bound of [f]. *)\nDefinition supremum {I A : Type} `{OType A} (a : A) (f : I -> A) :=\n  upper_bound a f /\\ forall x, upper_bound x f -> a ⊑ x.\n\n(* [a] is the greatest lower bound of [f]. *)\nDefinition infimum {I A : Type} `{OType A} (a : A) (f : I -> A) :=\n  lower_bound a f /\\ forall x, lower_bound x f -> x ⊑ a.\n\n(* f is an ascending ω-chain *)\nDefinition chain {A : Type} `{o : OType A} (f : nat -> A) : Prop :=\n  forall i, f i ⊑ f (S i).\n\n(* f is a descending ω-chain *)\nDefinition dec_chain {A : Type} `{o : OType A} (f : nat -> A) : Prop :=\n  forall i, f (S i) ⊑ f i.\n\n(* f is upward-directed. *)\n(* When the order relation is interpreted as an approximation\nrelation, we can think of directed sets as sets of elements that are\nall ultimately approximating the same thing. *)\nDefinition directed {I A : Type} `{OType A} (f : I -> A) : Prop :=\n  forall i j : I, exists k : I, f i ⊑ f k /\\ f j ⊑ f k.\n\n(* f is downward-directed. *)\nDefinition downward_directed {I A : Type} `{OType A} (f : I -> A) : Prop :=\n  forall i j : I, exists k : I, f k ⊑ f i /\\ f k ⊑ f j.\n\n#[global]\n  Program Instance OType_Prop : OType Prop := {| leq := impl |}.\nNext Obligation. constructor; intuition. Qed.\n\n#[global]\n  Program\n  Instance PType_Prop : PType Prop := {| bot := False |}.\nNext Obligation. intros []. Qed.\n#[global] Hint Resolve PType_Prop : order.\n\n#[global]\n  Program\n  Instance TType_Prop : TType Prop := {| top := True |}.\nNext Obligation. intro; apply I. Qed.\n\nDefinition bool_le (a b : bool) : Prop :=\n  match a, b with\n  | false, _ => True\n  | _, true => True\n  | _, _ => False\n  end.\n\n#[global]\n  Instance Reflexive_bool_le : Reflexive bool_le.\nProof. intros []; apply I. Qed.\n\n#[global]\n  Instance Transitive_bool_le : Transitive bool_le.\nProof. intros [] [] [] [] []; constructor; etransitivity; eauto. Qed.\n\n#[global]\n  Instance PreOrder_bool_le : PreOrder bool_le.\nProof. constructor; typeclasses eauto. Qed.\n\n#[global]\n  Instance OType_bool : OType bool :=\n  {| leq := bool_le |}.\n\n#[global]\n  Program\n  Instance PType_bool : PType bool :=\n  {| bot := false |}.\n\n#[global]\n  Program\n  Instance TType_bool : TType bool :=\n  {| top := true |}.\nNext Obligation. destruct x; apply I. Qed.\n\n#[global]\n  Program Instance OType_arrow A B {oB : OType B} : OType (A -> B) :=\n  {| leq := fun f g => forall x, leq (f x) (g x) |}.\nNext Obligation.\n  constructor.\n  - intros f x; reflexivity.\n  - intros ?; etransitivity; eauto.\nQed.\n\n#[global]\n  Program Instance PType_arrow A B `{PType B} : PType (A -> B) :=\n  {| bot := const bot |}.\nNext Obligation. apply bot_le. Qed.\n\n#[global]\n  Program Instance TType_arrow A B `{TType B} : TType (A -> B) :=\n  {| top := const top |}.\nNext Obligation. apply le_top. Qed.\n\n#[global]\n  Instance OType_nat : OType nat := {| leq := Nat.le |}.\n\n#[global]\n  Instance OType_Z : OType Z := {| leq := Z.le |}.\n\nDefinition prod_le {A B} `{OType A} `{OType B} (x y : A * B) : Prop :=\n  fst x ⊑ fst y /\\ snd x ⊑ snd y.\n\n#[global]\n  Instance Reflexive_prod_le {A B} `{OType A} `{OType B} : Reflexive (@prod_le A B _ _).\nProof. constructor; reflexivity. Qed.\n\n#[global]\n  Instance Transitive_prod_le {A B} `{OType A} `{OType B} : Transitive (@prod_le A B _ _).\nProof. intros [] [] [] [] []; constructor; etransitivity; eauto. Qed.\n\n#[global]\n  Instance PreOrder_prod_le {A B} `{OType A} `{OType B} : PreOrder (@prod_le A B _ _).\nProof. constructor; typeclasses eauto. Qed.\n\n#[global]\n  Instance OType_prod {A B} `{OType A} `{OType B} : OType (A * B) :=\n  {| leq := prod_le |}.\n\nDefinition sum_le {A B} `{OType A} `{OType B} (x y : A + B) : Prop :=\n  match (x, y) with\n  | (inl a, inl a') => a ⊑ a'\n  | (inr b, inr b') => b ⊑ b'\n  | _ => False\n  end.\n\n#[global]\n  Instance Reflexive_sum_le {A B} `{OType A} `{OType B} : Reflexive (@sum_le A B _ _).\nProof. unfold sum_le; intros []; reflexivity. Qed.\n\n#[global]\n  Instance Transitive_sum_le {A B} `{OType A} `{OType B} : Transitive (@sum_le A B _ _).\nProof. unfold sum_le; intros [a1|b1] [a2|b2] [a3|b3]; firstorder; etransitivity; eauto. Qed.\n\n#[global]\n  Instance PreOrder_sum_le {A B} `{OType A} `{OType B} : PreOrder (@sum_le A B _ _).\nProof. constructor; typeclasses eauto. Qed.\n\n#[global]\n  Instance OType_sum {A B} `{OType A} `{OType B} : OType (A + B) :=\n  {| leq := sum_le |}.\n\nDefinition equ {A : Type} `{OType A} (x y : A) := x ⊑ y /\\ y ⊑ x.\n\n#[global]\n  Instance Reflexive_equ A `{o : OType A} : Reflexive equ.\nProof. destruct o as [? [Hrefl ?]]; split; apply Hrefl. Qed.\n\n#[global]\n  Instance Transitive_equ A `{o : OType A} : Transitive equ.\nProof.\n  intros x y z Hxy Hyz.\n  destruct o as [? [? Htrans]]; split.\n  - etransitivity. apply Hxy. apply Hyz.\n  - etransitivity. apply Hyz. apply Hxy.\nQed.\n\n#[global]\n  Instance Symmetric_equ A `{OType A} : Symmetric equ.\nProof. unfold Symmetric, equ; intuition. Qed.\n\n#[global]\n  Program\n  Instance Equivalence_equ A `{OType A} : Equivalence equ.\n\nLemma le_bot {A} `{PType A} (a : A) :\n  a ⊑ ⊥ ->\n  a === ⊥.\nProof. intro Hle; split; auto; apply bot_le. Qed.\n\n#[global]\n  Instance Proper_leq {A} `{OType A} : Proper (equ ==> equ ==> flip impl) leq.\nProof.\n  intros x y [Hxy Hyx] a b [Hab Hba] Hle.\n  etransitivity; eauto.\n  etransitivity; eauto.\nQed.\n\n#[global]\n  Instance Proper_monotone_equ {A B} `{OType A} `{OType B} (f : A -> B)\n  {pf: Proper (leq ==> leq) f} : Proper (equ ==> equ) f.\nProof. intros a b Hab; split; apply pf, Hab. Qed.\n\n#[global]\n  Instance Proper_monotone_equ2 {A B C} `{OType A} `{OType B} `{OType C} (f : A -> B -> C)\n  {pf: Proper (leq ==> leq ==> leq) f} : Proper (equ ==> equ ==> equ) f.\nProof. intros a b Hab c d Hcd; split; apply pf; firstorder. Qed.\n\n#[global]\n  Instance Proper_monotone_eq_equ {A B C} `{OType A} `{OType B} `{OType C} (f : A -> B -> C)\n  {pf: Proper (leq ==> eq ==> leq) f} : Proper (equ ==> eq ==> equ) f.\nProof. intros a b Hab c d Hcd; split; apply pf; firstorder. Qed.\n\n#[global]\n  Instance Proper_antimonotone_equ {A B} `{OType A} `{OType B} (f : A -> B)\n  {pf: Proper (leq ==> flip leq) f} : Proper (equ ==> equ) f.\nProof. intros a b Hab; split; apply pf, Hab. Qed.\n\nDefinition incomparable {A} `{OType A} (x y : A) : Prop :=\n  ~ (x ⊑ y \\/ y ⊑ x).\n\nDefinition bounded_above {A B : Type} `{OType B} (f : A -> B) :=\n  exists b, upper_bound b f.\n\nDefinition eventually_constant_at {A} `{OType A} (f : nat -> A) (x : A) : Prop :=\n  exists n0, forall n, (n0 <= n)%nat -> f n === x.\n\nLemma infimum_unique {A B : Type} `{o : OType B} (x y : B) (f : A -> B) :\n  infimum x f -> infimum y f -> x === y.\nProof.\n  intros [H0 H1] [H2 H3]; split.\n  - apply H3; auto.\n  - apply H1; auto.\nQed.\n\nLemma supremum_unique {A B : Type} `{o : OType B} (x y : B) (f : A -> B) :\n  supremum x f -> supremum y f -> x === y.\nProof.\n  intros [H0 H1] [H2 H3]; split.\n  - apply H1; auto.\n  - apply H3; auto.\nQed.\n\n(* [f] is monotone whenever it is order-preserving. *)\nDefinition monotone {A B : Type} `{OType A} `{OType B} (f : A -> B) :=\n  Proper (leq ==> leq) f.\n#[global] Hint Unfold monotone : order.\n\n(* [f] is antimonotone whenever it is order-reversing. *)\nDefinition antimonotone {A B : Type} `{OType A} `{OType B} (f : A -> B) :=\n  Proper (leq ==> flip leq) f.\n#[global] Hint Unfold antimonotone : order.\n\nLemma monotone_chain {A B : Type} `{OType A} `{OType B} (f : A -> B) (g : nat -> A) :\n  monotone f ->\n  chain g ->\n  chain (f ∘ g).\nProof. intros Hmono Hg i; apply Hmono, Hg. Qed.\n\nLemma monotone_directed {I A B : Type} `{OType A} `{OType B} (f : A -> B) (g : I -> A) :\n  monotone f ->\n  directed g ->\n  directed (f ∘ g).\nProof.\n  intros Hf Hg i j.\n  specialize (Hg i j); destruct Hg as [k [Hk Hk']].\n  exists k; split; eauto.\nQed.\n#[global] Hint Resolve monotone_directed : order.\n\nLemma antimonotone_directed {I A B : Type} `{OType A} `{OType B} (f : A -> B) (g : I -> A) :\n  antimonotone f ->\n  downward_directed g ->\n  directed (f ∘ g).\nProof.\n  intros Hf Hg i j.\n  specialize (Hg i j); destruct Hg as [k [Hk Hk']].\n  exists k; split; apply Hf; auto.\nQed.\n#[global] Hint Resolve antimonotone_directed : order.\n\nLemma monotone_downward_directed {I A B : Type} `{OType A} `{OType B}\n  (f : A -> B) (g : I -> A) :\n  monotone f ->\n  downward_directed g ->\n  downward_directed (f ∘ g).\nProof.\n  intros Hf Hg i j.\n  specialize (Hg i j); destruct Hg as [k [Hk Hk']].\n  exists k; split; apply Hf; auto.\nQed.\n#[global] Hint Resolve monotone_downward_directed : order.\n\nLemma antimonotone_downward_directed {I A B : Type} `{OType A} `{OType B}\n  (f : A -> B) (g : I -> A) :\n  antimonotone f ->\n  directed g ->\n  downward_directed (f ∘ g).\nProof.\n  intros Hf Hg i j.\n  specialize (Hg i j); destruct Hg as [k [Hk Hk']].\n  exists k; split; apply Hf; auto.\nQed.\n#[global] Hint Resolve antimonotone_downward_directed : order.\n\nLemma monotone_dec_chain {A B : Type} `{OType A} `{OType B} (f : A -> B) (g : nat -> A) :\n  monotone f ->\n  dec_chain g ->\n  dec_chain (f ∘ g).\nProof. intros Hmono Hg i; apply Hmono, Hg. Qed.\n\nLemma antimonotone_dec_chain {A B : Type} `{OType A} `{OType B} (f : A -> B) (g : nat -> A) :\n  antimonotone f ->\n  chain g ->\n  dec_chain (f ∘ g).\nProof. intros Hmono Hg i; apply Hmono, Hg. Qed.\n\nLemma antimonotone_chain {A B : Type} `{OType A} `{OType B} (f : A -> B) (g : nat -> A) :\n  antimonotone f ->\n  dec_chain g ->\n  chain (f ∘ g).\nProof. intros Hmono Hg i; apply Hmono, Hg. Qed.\n\nLemma monotone_compose {A B C : Type} `{OType A} `{OType B} `{OType C}\n  (f : A -> B) (g : B -> C) :\n  monotone f ->\n  monotone g ->\n  monotone (g ∘ f).\nProof. intros Hf Hg x y Hleq; apply Hg, Hf; auto. Qed.\n#[global] Hint Resolve monotone_compose : order.\n\nLemma monotone_compose' {A B C : Type} `{OType A} `{OType B} `{OType C}\n  (f : A -> B) (g : B -> C) :\n  monotone f ->\n  monotone g ->\n  monotone (fun x => g (f x)).\nProof. intros Hf Hg x y Hleq; apply Hg, Hf; auto. Qed.\n#[global] Hint Resolve monotone_compose' : order.\n\nLemma monotone_antimonotone_compose {A B C : Type} `{OType A} `{OType B} `{OType C}\n  (f : A -> B) (g : B -> C) :\n  monotone f ->\n  antimonotone g ->\n  antimonotone (g ∘ f).\nProof. intros Hf Hg x y Hleq; apply Hg, Hf; auto. Qed.\n\nLemma antimonotone_monotone_compose {A B C : Type} `{OType A} `{OType B} `{OType C}\n  (f : A -> B) (g : B -> C) :\n  antimonotone f ->\n  monotone g ->\n  antimonotone (g ∘ f).\nProof. intros Hf Hg x y Hleq; apply Hg, Hf; auto. Qed.\n\nLemma antimonotone_compose {A B C : Type}\n  `{OType A} `{OType B} `{OType C} (f : A -> B) (g : B -> C) :\n  antimonotone f ->\n  antimonotone g ->\n  monotone (g ∘ f).\nProof. intros Hf Hg x y Hleq; apply Hg, Hf; auto. Qed.\n#[global] Hint Resolve antimonotone_compose : order.\n\nLemma chain_leq {A : Type} `{o : OType A} (f : nat -> A) (n m : nat) :\n  chain f ->\n  (n <= m)%nat ->\n  leq (f n) (f m).\nProof.\n  intros Hchain Hle; induction m.\n  - assert (n = O). lia. subst; reflexivity.\n  - destruct (Nat.eqb_spec n (S m)); subst.\n    + reflexivity.\n    + assert (H': (n <= m)%nat). lia.\n      etransitivity. apply IHm; auto.\n      apply Hchain.\nQed.\n\nLemma dec_chain_leq {A : Type} `{o : OType A} (f : nat -> A) (n m : nat) :\n  dec_chain f ->\n  (n <= m)%nat ->\n  leq (f m) (f n).\nProof.\n  intros Hchain Hle; induction m.\n  - assert (n = O). lia. subst; reflexivity.\n  - destruct (Nat.eqb_spec n (S m)); subst.\n    + reflexivity.\n    + assert (H': (n <= m)%nat). lia.\n      etransitivity. apply Hchain. apply IHm; auto.\nQed.\n\nLemma const_infimum {A : Type} {o : OType A} (ch : nat -> A) (c : A) :\n  (forall i, ch i === c) -> infimum c ch.\nProof.\n  intros Hequ; split.\n  - intro; apply Hequ.\n  - intros lb Hlb.\n    specialize (Hlb O); specialize (Hequ O).\n    etransitivity; eauto; apply Hequ.\nQed.\n\nLemma const_supremum {A : Type} {o : OType A} (f : nat -> A) (x : A) :\n  (forall i, f i === x) -> supremum x f.\nProof.\n  intros Hequ; split.\n  - intro; apply Hequ.\n  - intros ub Hub.\n    specialize (Hub O); specialize (Hequ O).\n    etransitivity; eauto; apply Hequ.\nQed.\n\nLemma const_supremum'' {A : Type} `{o : OType A} (f : nat -> A) (x : A) :\n  upper_bound x f ->\n  (exists n, f n === x) ->\n  supremum x f.\nProof.\n  intros Hx [n0 Hequ].\n  split; auto.\n  - intros ub Hub.\n    transitivity (f n0).\n    apply Hequ; auto.\n    apply Hub.\nQed.\n\n#[global]\n  Instance Proper_infimum {A B : Type} {oB : OType B}\n  : Proper (equ ==> equ ==> iff) (@infimum A B oB).\nProof.\n  intros x y [Hequ0 Hequ1] f g [Hequ0' Hequ1'].\n  split; intros [Hlb Hglb].\n  - split.\n    + intro z.\n      transitivity x; auto.\n      transitivity (f z); auto.\n    + intros lb Hlb'.\n      transitivity x; auto.\n      apply Hglb.\n      intro z; transitivity (g z); auto.\n  - split.\n    + intro z.\n      transitivity y; auto.\n      transitivity (g z); auto.\n    + intros lb Hlb'.\n      transitivity y; auto.\n      apply Hglb.\n      intro z; transitivity (f z); auto.\nQed.\n\n#[global]\n  Instance Proper_supremum {A B : Type} {oB : OType B}\n  : Proper (equ ==> equ ==> iff) (@supremum A B oB).\nProof.\n  intros x y [Hequ0 Hequ1] f g [Hequ0' Hequ1'].\n  split; intros [Hub Hlub].\n  - split.\n    + intro z.\n      transitivity x; auto.\n      transitivity (f z); auto.\n    + intros ub Hub'.\n      transitivity x; auto.\n      apply Hlub.\n      intro z; transitivity (g z); auto.\n  - split.\n    + intro z.\n      transitivity y; auto.\n      transitivity (g z); auto.\n    + intros lb Hub'.\n      transitivity y; auto.\n      apply Hlub.\n      intro z; transitivity (f z); auto.\nQed.\n\nDefinition continuous {A B : Type} `{OType A} `{OType B} (f : A -> B) :=\n  forall g : nat -> A,\n    directed g ->\n    forall a : A,\n      supremum a g ->\n      supremum (f a) (f ∘ g).\n\n(* A function is cocontinuous when it is continuous wrt the opposite\n   order relation. *)\nDefinition cocontinuous {A B : Type} `{OType A} `{OType B} (f : A -> B) :=\n  forall g : nat -> A,\n    directed g ->\n    forall a : A,\n      supremum a g ->\n      infimum (f a) (f ∘ g).\n\n(* ω-continuity is a weaker notion in general than directed-continuity\n   (e.g., in the CPO of reals). In general, a function that is\n   d-continuous is also ω-continuous, but the converse may not\n   hold. *)\nDefinition wcontinuous {A B : Type} `{OType A} `{OType B} (f : A -> B) :=\n  forall g : nat -> A,\n    chain g ->\n    forall a : A,\n      supremum a g ->\n      supremum (f a) (f ∘ g).\n\n(* Definition wcontinuous2 {A B C : Type} `{OType A} `{OType B} `{OType C} (f : A -> B -> C) := *)\n(*   forall (g : nat -> A) (h : nat -> B), *)\n(*     chain g -> *)\n(*     chain h -> *)\n(*     forall (a : A) (b : B), *)\n(*       supremum a g -> *)\n(*       supremum b h -> *)\n(*       supremum (f a b) (fun i => f (g i) (h i)). *)\n\nDefinition wcocontinuous {A B : Type} `{OType A} `{OType B} (f : A -> B) :=\n  forall g : nat -> A,\n    chain g ->\n    forall a : A,\n      supremum a g ->\n      infimum (f a) (f ∘ g).\n\nDefinition dec_continuous {A B : Type} `{OType A} `{OType B} (f : A -> B) :=\n  forall g : nat -> A,\n    downward_directed g ->\n    forall a : A,\n      infimum a g ->\n      infimum (f a) (f ∘ g).\n\nDefinition dec_cocontinuous {A B : Type} `{OType A} `{OType B} (f : A -> B) :=\n  forall g : nat -> A,\n    downward_directed g ->\n    forall a : A,\n      infimum a g ->\n      supremum (f a) (f ∘ g).\n\nDefinition dec_wcontinuous {A B : Type} `{OType A} `{OType B} (f : A -> B) :=\n  forall g : nat -> A,\n    dec_chain g ->\n    forall inf : A,\n      infimum inf g ->\n      infimum (f inf) (f ∘ g).\n\nLemma chain_directed {A} `{OType A} (f : nat -> A) :\n  chain f ->\n  directed f.\nProof.\n  intros Hch i j.\n  exists (max i j); split; apply chain_leq; auto.\n  - apply Nat.le_max_l.\n  - apply Nat.le_max_r.\nQed.\n#[global] Hint Resolve chain_directed : order.\n\nLemma dec_chain_downward_directed {A} `{OType A} (f : nat -> A) :\n  dec_chain f ->\n  downward_directed f.\nProof.\n  intros Hch i j.\n  exists (max i j); split; apply dec_chain_leq; auto.\n  - apply Nat.le_max_l.\n  - apply Nat.le_max_r.\nQed.\n#[global] Hint Resolve dec_chain_downward_directed : order.\n\nLemma continuous_wcontinuous {A B} `{OType A} `{OType B} (f : A -> B) :\n  continuous f ->\n  wcontinuous f.\nProof.\n  intros Hf ch Hch s Hs; apply Hf; auto; apply chain_directed; auto.\nQed.\n#[global] Hint Resolve continuous_wcontinuous : order.\n\nLemma dec_continuous_dec_wcontinuous {A B} `{OType A} `{OType B} (f : A -> B) :\n  dec_continuous f ->\n  dec_wcontinuous f.\nProof.\n  intros Hf ch Hch s Hs; apply Hf; auto; apply dec_chain_downward_directed; auto.\nQed.\n#[global] Hint Resolve continuous_wcontinuous : order.\n\nLemma upper_bound_const {A B} `{OType A} (a : A) :\n  upper_bound a (@const A B a).\nProof. intro b; reflexivity. Qed.\n\nLemma lower_bound_const {A B} `{OType A} (a : A) :\n  lower_bound a (@const A B a).\nProof. intro b; reflexivity. Qed.\n\nLemma supremum_const {A B} `{OType A} `{Inhabited B} (a : A) :\n  supremum a (fun _ : B => a).\nProof.\n  split.\n  - apply upper_bound_const.\n  - unfold upper_bound.\n    unfold const. intros x H1.\n    destruct H0; apply H1; auto.\nQed.\n#[global] Hint Resolve supremum_const : order.\n\nLemma supremum_const' {A B} `{OType A} `{Inhabited B} (a : A) (f : nat -> A) :\n  f === const a ->\n  supremum a f.\nProof. intros ->; apply supremum_const. Qed.\n\nLemma infimum_const {A B} `{OType A} `{Inhabited B} (a : A) :\n  infimum a (fun _ : B => a).\nProof.\n  split.\n  - apply lower_bound_const.\n  - unfold const; intros x H1.\n    destruct H0; apply H1; auto.\nQed.\n#[global] Hint Resolve infimum_const : order.\n\nLemma infimum_const' {A B} `{OType A} `{Inhabited B} (a : A) (f : nat -> A) :\n  f === const a ->\n  infimum a f.\nProof. intros ->; apply infimum_const. Qed.\n\nLemma leq_arrow {A B} `{OType B} (f g : A -> B) :\n  f ⊑ g -> forall x, f x ⊑ g x.\nProof. auto. Qed.\n\nLemma equ_arrow {A B} `{OType B} (f g : A -> B) :\n  f === g <-> forall x, f x === g x.\nProof.\n  split.\n  - intros [Hfg Hgf] x; split; auto.\n  - intros Hfg; split; intro x; apply Hfg.\nQed.\n\nLemma directed_const {I A} `{OType A} (x : A) :\n  directed (fun _ : I => x).\nProof. intros _ j; exists j; split; reflexivity. Qed.\n#[global] Hint Resolve directed_const : order.\n\nLemma downward_directed_const {I A} `{OType A} (x : A) :\n  downward_directed (fun _ : I => x).\nProof. intros _ j; exists j; split; reflexivity. Qed.\n#[global] Hint Resolve downward_directed_const : order.\n\nLemma eq_equ {A} `{OType A} x y :\n  x = y -> x === y.\nProof. intro; subst; reflexivity. Qed.\n\nLemma pointwise_le_supremum_le {A} `{OType A} (f g : nat -> A) (a b : A) :\n  (forall i, f i ⊑ g i) ->\n  supremum a f ->\n  supremum b g ->\n  a ⊑ b.\nProof.\n  intros Hle [Ha Ha'] [Hb Hb'].\n  eapply Ha'; intro i; etransitivity; eauto.\nQed.\n\nLemma pointwise_le_infimum_le {A} `{OType A} (f g : nat -> A) (a b : A) :\n  (forall i, f i ⊑ g i) ->\n  infimum a f ->\n  infimum b g ->\n  a ⊑ b.\nProof.\n  intros Hle [Ha Ha'] [Hb Hb'].\n  eapply Hb'; intro i; etransitivity; eauto.\nQed.\n\nLemma apply_supremum {I A B} `{OType B}\n  (f : A -> B) (ch : I -> A -> B) (x : A) :\n  supremum f ch -> supremum (f x) (fun i => ch i x).\nProof.\n  intros [Hub Hlub]; split.\n  - intro i; apply Hub.\n  - intros y Hy.\n    simpl in Hlub.\n    unfold upper_bound in Hy.\n    simpl in *.\n    destruct (classicT (f x ⊑ y)); auto.\n    set (f' := fun a => if classicT (a = x) then y else f a).\n    assert (Hf': upper_bound f' ch).\n    { intros i a; unfold f'; simpl.\n      destruct_classic; subst; auto; apply Hub. }\n    specialize (Hlub f' Hf' x); unfold f' in Hlub.\n    destruct_classic; auto; congruence.\nQed.\n\nCorollary wcontinuous_apply {A B} `{OType B} (x : A) :\n  wcontinuous (fun f : A -> B => f x).\nProof. intros ch Hch s Hs; apply apply_supremum; auto. Qed.\n\nLemma supremum_apply {I A B} `{Inhabited I} `{OType B} (f : A -> B) (ch : I -> A -> B) :\n  (forall x, supremum (f x) (fun i => ch i x)) -> supremum f ch.\nProof.\n  intro Hsup; split.\n  - intros i x; apply Hsup.\n  - intros g Hg x; apply Hsup; intro i; apply Hg.\nQed.\n\nLemma infimum_apply {I A B} `{Inhabited I} `{OType B} (f : A -> B) (ch : I -> A -> B) :\n  (forall x, infimum (f x) (fun i => ch i x)) -> infimum f ch.\nProof.\n  intro Hsup; split.\n  - intros i x; apply Hsup.\n  - intros g Hg x; apply Hsup; intro i; apply Hg.\nQed.\n\nLemma apply_infimum {I A B} `{Inhabited I} `{OType B}\n  (f : A -> B) (ch : I -> A -> B) (x : A) :\n  infimum f ch -> infimum (f x) (fun i => ch i x).\nProof.\n  intros [Hlb Hglb]; split.\n  - intro i; apply Hlb.\n  - intros y Hy.\n    simpl in Hglb.\n    unfold lower_bound in Hy.\n    simpl in *.\n    destruct (classicT (y ⊑ f x)); auto.\n    set (f' := fun a => if classicT (a = x) then y else f a).\n    assert (Hf': lower_bound f' ch).\n    { intros i a; unfold f'; simpl.\n      destruct_classic; subst; auto; apply Hlb. }\n    specialize (Hglb f' Hf' x); unfold f' in Hglb.\n    destruct_classic; auto; congruence.\nQed.\n\nLemma continuous_monotone {A B} `{OType A} `{OType B} (f : A -> B) :\n  continuous f ->\n  Proper (leq ==> leq) f.\nProof.\n  unfold continuous, monotone, Proper, respectful.\n  intros Hf x y Hxy.\n  set (ch := fun i => match i with\n                   | O => x\n                   | _ => y\n                   end).\n  assert (Hch: directed ch).\n  { intros i j; unfold ch; exists (max i j); split;\n      destruct i, j; simpl; auto; reflexivity. }\n  assert (supremum y ch).\n  { split.\n    - intro i; unfold ch; destruct i; auto; reflexivity.\n    - intros z Hz; specialize (Hz (S O)); auto. }\n  apply Hf in H1; auto.\n  destruct H1 as [Hub Hlub]; apply (Hub O).\nQed.\n#[global] Hint Resolve continuous_monotone : order.\n\nLemma cocontinuous_antimonotone {A B} `{OType A} `{OType B} (f : A -> B) :\n  cocontinuous f ->\n  Proper (leq ==> flip leq) f.\nProof.\n  unfold cocontinuous, antimonotone, Proper, respectful.\n  intros Hf x y Hxy.\n  set (ch := fun i => match i with\n                   | O => x\n                   | _ => y\n                   end).\n  assert (Hch: directed ch).\n  { intros i j; unfold ch; exists (max i j); split;\n      destruct i, j; simpl; auto; reflexivity. }\n  assert (supremum y ch).\n  { split.\n    - intro i; unfold ch; destruct i; auto; reflexivity.\n    - intros z Hz; specialize (Hz (S O)); auto. }\n  apply Hf in H1; auto.\n  destruct H1 as [Hub Hlub]; apply (Hub O).\nQed.\n#[global] Hint Resolve cocontinuous_antimonotone : order.\n\nLemma wcontinuous_monotone {A B} `{OType A} `{OType B} (f : A -> B) :\n  wcontinuous f ->\n  Proper (leq ==> leq) f.\nProof.\n  unfold wcontinuous, monotone, Proper, respectful.\n  intros Hf x y Hxy.\n  set (ch := fun i => match i with\n                      | O => x\n                      | _ => y\n                      end).\n  assert (Hch: chain ch).\n  { intros []; auto; reflexivity. }\n  assert (supremum y ch).\n  { split.\n    - intro i; unfold ch; destruct i; auto; reflexivity.\n    - intros z Hz; specialize (Hz (S O)); auto. }\n  apply Hf in H1; auto.\n  destruct H1 as [Hub Hlub]; apply (Hub O).\nQed.\n#[global] Hint Resolve wcontinuous_monotone : order.\n\nLemma dec_continuous_monotone {A B} `{OType A} `{OType B} (f : A -> B) :\n  dec_continuous f ->\n  Proper (leq ==> leq) f.\nProof.\n  unfold dec_continuous, monotone, Proper, respectful.\n  intros Hf x y Hxy.\n  set (ch := fun i => match i with\n                   | O => y\n                   | _ => x\n                   end).\n  assert (Hch: downward_directed ch).\n  { intros i j; unfold ch; exists (max i j); split;\n      destruct i, j; simpl; auto; reflexivity. }\n  assert (infimum x ch).\n  { split.\n    - intro i; unfold ch; destruct i; auto; reflexivity.\n    - intros z Hz; specialize (Hz (S O)); auto. }\n  apply Hf in H1; auto.\n  destruct H1 as [Hlb Hglb]; apply (Hlb O).\nQed.\n#[global] Hint Resolve dec_continuous_monotone : order.\n\nLemma dec_wcontinuous_monotone {A B} `{OType A} `{OType B} (f : A -> B) :\n  dec_wcontinuous f ->\n  Proper (leq ==> leq) f.\nProof.\n  unfold dec_continuous, monotone, Proper, respectful.\n  intros Hf x y Hxy.\n  set (ch := fun i => match i with\n                   | O => y\n                   | _ => x\n                   end).\n  assert (Hch: dec_chain ch).\n  { intros []; auto; reflexivity. }\n  assert (infimum x ch).\n  { split.\n    - intro i; unfold ch; destruct i; auto; reflexivity.\n    - intros z Hz; specialize (Hz (S O)); auto. }\n  apply Hf in H1; auto.\n  destruct H1 as [Hlb Hglb]; apply (Hlb O).\nQed.\n#[global] Hint Resolve dec_wcontinuous_monotone : order.\n\nLemma continuous_compose {A B C} `{OType A} `{OType B} `{OType C}\n  (f : A -> B) (g : B -> C) :\n  continuous f ->\n  continuous g ->\n  continuous (g ∘ f).\nProof.\n  unfold continuous.\n  intros Hf Hg ch Hch x Hx; unfold compose in *.\n  apply Hg.\n  - apply monotone_directed; auto.\n    apply continuous_monotone; auto.\n  - apply Hf; auto.\nQed.\n#[global] Hint Resolve continuous_compose : order.\n\nLemma supremum_eventually_constant_at {A} `{OType A} (f : nat -> A) (x : A) :\n  chain f ->\n  eventually_constant_at f x ->\n  supremum x f.\nProof.\n  intros Hch [n0 Hn0]; split.\n  - intro i.\n    destruct (Nat.leb_spec n0 i).\n    + specialize (Hn0 i H0); apply Hn0.\n    + specialize (Hn0 n0 (le_n n0)).\n      rewrite <- Hn0.\n      apply chain_leq; auto; lia.\n  - intros ub Hub.\n    specialize (Hub n0).\n    specialize (Hn0 n0 (le_n n0)); rewrite <- Hn0; auto.\nQed.\n\nLemma infimum_eventually_constant_at {A} `{OType A} (f : nat -> A) (x : A) :\n  dec_chain f ->\n  eventually_constant_at f x ->\n  infimum x f.\nProof.\n  intros Hch [n0 Hn0]; split.\n  - intro i.\n    destruct (Nat.leb_spec n0 i).\n    + specialize (Hn0 i H0); apply Hn0.\n    + specialize (Hn0 n0 (le_n n0)).\n      rewrite <- Hn0.\n      apply dec_chain_leq; auto; lia.\n  - intros ub Hub.\n    specialize (Hub n0).\n    specialize (Hn0 n0 (le_n n0)); rewrite <- Hn0; auto.\nQed.\n\nLemma supremum_shift {A} `{OType A} (f : nat -> A) (a : A) :\n  chain f ->\n  supremum a f ->\n  supremum a (shift f).\nProof.\n  intros Hf [Hub Hlub]; split.\n  - intro i; apply Hub.\n  - intros x Hx; apply Hlub; intro i; etransitivity; eauto.\nQed.\n\nLemma Proper_compose_l {A B C} `{OType A} `{OType B} `{OType C}\n  (f f' : A -> B) (g g' : B -> C) :\n  Proper (equ ==> equ) g ->\n  f === f' ->\n  g === g' ->\n  g ∘ f === g' ∘ f'.\nProof.\n  intros Hg Hf' Hg'.\n  unfold compose; apply equ_arrow; intro x.\n  rewrite equ_arrow in Hf'.\n  rewrite Hf'.\n  rewrite equ_arrow in Hg'.\n  apply Hg'.\nQed.\n\nLemma infimum_shift {A} `{OType A} (a : A) (f : nat -> A) :\n  dec_chain f ->\n  infimum a f ->\n  infimum a (shift f).\nProof.\n  unfold shift; intros Hch [Hlb Hglb]; split.\n  - intro i; apply Hlb.\n  - intros x Hx; apply Hglb; intro i; etransitivity; eauto.\nQed.\n\nLemma shift_supremum {A} `{OType A} (a : A) (f : nat -> A) :\n  f 0 ⊑ a ->\n  supremum a (shift f) ->\n  supremum a f.\nProof.\n  unfold shift; intros Hf0 [Hub Hlub]; split.\n  - intros []; auto.\n  - intros x Hx; apply Hlub; intro i; apply Hx.\nQed.\n\nLemma shift_supremum' {A} `{OType A} (a : A) (f g : nat -> A) :\n  (exists i, g 0 ⊑ g (S i)) ->\n  supremum a f ->\n  shift g === f ->\n  supremum a g.\nProof.\n  intros Hg01 Ha Hgf.\n  rewrite <- Hgf in Ha.\n  apply shift_supremum; auto.\n  destruct Hg01 as [i Hi].\n  etransitivity; eauto.\n  apply Ha.\nQed.\n\nCorollary shift_supremum'' {A} `{OType A} (a : A) (f g : nat -> A) :\n  g 0 ⊑ g 1 ->\n  supremum a f ->\n  shift g === f ->\n  supremum a g.\nProof. intros Hg01 Ha Hgf; eapply shift_supremum'; eauto. Qed.\n\nLemma shift_infimum {A} `{OType A} (a : A) (f : nat -> A) :\n  a ⊑ f 0 ->\n  infimum a (shift f) ->\n  infimum a f.\nProof.\n  unfold shift; intros Hf0 [Hub Hlub]; split.\n  - intros []; auto.\n  - intros x Hx; apply Hlub; intro i; apply Hx.\nQed.\n\nLemma shift_infimum' {A} `{OType A} (a : A) (f g : nat -> A) :\n  (exists i, g (S i) ⊑ g O) ->\n  infimum a f ->\n  shift g === f ->\n  infimum a g.\nProof.\n  intros Hg01 Ha Hgf.\n  rewrite <- Hgf in Ha.\n  apply shift_infimum; auto.\n  destruct Hg01 as [i Hi].\n  etransitivity; eauto.\n  apply Ha.\nQed.\n\nCorollary shift_infimum'' {A} `{OType A} (a : A) (f g : nat -> A) :\n  g 1 ⊑ g 0 ->\n  infimum a f ->\n  shift g === f ->\n  infimum a g.\nProof. intros Hg01 Ha Hgf; eapply shift_infimum'; eauto. Qed.\n\n#[global]\n  Instance monotone_id {A} `{OType A} : Proper (leq ==> leq) id.\nProof. intros ? ? Hle; apply Hle. Qed.\n#[global] Hint Resolve monotone_id : order.\n\nLemma continuous_id {A} `{OType A} : continuous id.\nProof. intros ch Hch s Hs; apply Hs. Qed.\n#[global] Hint Resolve continuous_id : order.\n\nLemma dec_continuous_id {A} `{OType A} : dec_continuous id.\nProof. intros ch Hch s Hs; apply Hs. Qed.\n#[global] Hint Resolve dec_continuous_id : order.\n\nFixpoint iter_n {A} (F : A -> A) (z : A) (n : nat) : A :=\n  match n with\n  | O => z\n  | S n' => F (iter_n F z n')\n  end.\n\nLemma chain_iter_n' {A} `{OType A} (f : A -> A) (z : A) :\n  z ⊑ f z ->\n  monotone f ->\n  chain (iter_n f z).\nProof. intros Hz Hf i; induction i; simpl; auto. Qed.\n\nLemma dec_chain_iter_n' {A} `{OType A} (f : A -> A) (z : A) :\n  f z ⊑ z ->\n  monotone f ->\n  dec_chain (iter_n f z).\nProof. intros Hz Hf i; induction i; simpl; auto. Qed.\n\nLemma monotone_iter_n {A} `{OType A} (f g : A -> A) (x y : A) (i : nat) :\n  (forall x y, x ⊑ y -> f x ⊑ g y) ->\n  x ⊑ y ->\n  iter_n f x i ⊑ iter_n g y i.\nProof. revert f g x y; induction i; intros f g x y; simpl; auto. Qed.\n\nLemma leq_impl (P Q : Prop) :\n  P ⊑ Q ->\n  P -> Q.\nProof. intro H; apply H. Qed.\n\nLemma equ_iff (P Q : Prop) :\n  P === Q ->\n  P <-> Q.\nProof. firstorder. Qed.\n\nLemma iter_n_eq {A} `{OType A} (F G : A -> A) (a b : A) (i : nat) :\n  (forall x y, x === y -> F x === G y) ->\n  a === b ->\n  iter_n F a i === iter_n G b i.\nProof. revert F G a b; induction i; intros F G a b HFG Hab; simpl; auto. Qed.\n\nLemma chain_id : chain (fun i : nat => i).\nProof. intro i; simpl; lia. Qed.\n#[global] Hint Resolve chain_id : order.\n\nLemma supremum_cond {A} `{OType A} (b : bool) (x y : A) (f g : nat -> A) :\n  supremum x f ->\n  supremum y g ->\n  supremum (if b then x else y) (fun i => if b then f i else g i).\nProof. intros Hf Hg; destruct b; auto. Qed.\n\nLemma infimum_cond {A} `{OType A} (b : bool) (x y : A) (f g : nat -> A) :\n  infimum x f ->\n  infimum y g ->\n  infimum (if b then x else y) (fun i => if b then f i else g i).\nProof. intros Hf Hg; destruct b; auto. Qed.\n\nLemma iter_n_const {A} `{OType A} (F : A -> A) (z : A) (n : nat) :\n  Proper (leq ==> leq) F ->  \n  F z === z ->\n  iter_n F z n === z.\nProof.\n  intros Hmono HFz.\n  induction n; simpl; try reflexivity.\n  rewrite IHn; auto.\nQed.\n\n(* Pointwise variant for function spaces. *)\nCorollary iter_n_const' {A B} `{OType B}\n  (F : (A -> B) -> A -> B) (z : A -> B) (n : nat) (x : A) :\n  Proper (leq ==> leq) F ->\n  F z === z ->\n  iter_n F z n x === z x.\nProof. intros Hmono HFz; apply equ_arrow; apply iter_n_const; auto. Qed.\n\nLemma iter_n_bounded {A} `{OType A} (F : A -> A) (z ub : A) (n : nat) :\n  z ⊑ ub ->\n  (forall x, x ⊑ ub -> F x ⊑ ub) ->\n  iter_n F z n ⊑ ub.\nProof. revert z ub; induction n; intros z ub Hz HF; simpl; auto. Qed.\n\n(** Types for which the symmetric closure of the order relation\n    coincides with propositional equality. Obviously, depends on the\n    choice of order relation. *)\nClass ExtType (A : Type) `{OType A} : Type :=\n  { ext : forall (a b : A), a === b -> a = b }.\n\n#[global]\n  Instance ExtType_Proper {A B} `{ExtType A} `{OType B} (f : A -> B)\n  : Proper (equ ==> equ) f.\nProof. intros x y Hxy; eapply ext in Hxy; subst; reflexivity. Qed.\n\n#[global]\n  Instance ExtType_bool : ExtType bool.\nProof. constructor. intros [] [] []; auto; destruct H. Qed.\n\n#[global]\n  Instance ExtType_arrow {A B} `{ExtType B} : ExtType (A -> B).\nProof.\n  constructor; intros f g Hfg.\n  ext x; rewrite equ_arrow in Hfg; specialize (Hfg x); apply ext; auto.\nQed.\n\n(* #[global] *)\n(*   Instance ExtType_Prop : ExtType Prop. *)\n(* Proof. constructor; apply propositional_extensionality. Qed. *)\n\n#[global]\n  Instance ExtType_nat : ExtType nat.\nProof.\n  constructor; intros a b Hab.\n  unfold equiv, equ in Hab; simpl in Hab; lia.\nQed.\n\nLemma continuous_cocontinuous_compose {A B C} `{OType A} `{OType B} `{OType C}\n  (f : A -> B) (g : B -> C) :\n  continuous f ->\n  cocontinuous g ->\n  cocontinuous (g ∘ f).\nProof.\n  unfold continuous, cocontinuous.\n  intros Hf Hg ch Hch x Hx; unfold compose in *.\n  apply Hg.\n  - apply monotone_directed; auto.\n    apply continuous_monotone; auto.\n  - apply Hf; auto.\nQed.\n\nLemma supremum_Prop (P : Prop) (f : nat -> Prop) :\n  (P <-> exists i, f i) ->\n  supremum P f.\nProof.\n  intros [H0 H1]; split.\n  - intros i Hfi; apply H1; exists i; auto.\n  - intros Q HQ HP.\n    apply H0 in HP.\n    destruct HP as [i Hfi].\n    eapply HQ; eauto.\nQed.\n\nLemma supremum_Prop' (P : Prop) (f : nat -> Prop) :\n  supremum P f ->\n  (P <-> exists i, f i).\nProof.\n  intros [Hub Hlub]; split.\n  - intro pf.\n    contra H.\n    assert (Hf: forall i, ~ f i).\n    { intros i HC; apply H; exists i; auto. }\n    clear H.\n    eapply Hlub; auto.\n  - intros [i Hi].\n    eapply Hub; eauto.\nQed.\n\nLemma infimum_Prop (P : Prop) (f : nat -> Prop) :\n  (P <-> forall i, f i) ->\n  infimum P f.\nProof.\n  intros [H0 H1]; split.\n  - intros i Hfi; apply H0; auto.\n  - intros Q HQ HP; apply H1; intro i; apply HQ; auto.\nQed.\n\n(* Lemma equ_list {A} (l1 l2 : list A) : *)\n(*   l1 === l2 -> l1 = l2. *)\n(* Proof. intros []; apply is_prefix_antisym; auto. Qed. *)\n\nLemma continuous_ite {A B} `{OType A} `{OType B} (b : bool) (f g : A -> B) :\n  continuous f ->\n  continuous g ->\n  continuous (fun x => if b then f x else g x).\nProof.\n  intros Hf Hg ch Hch a Hsup; unfold compose; destruct b.\n  - apply Hf; auto.\n  - apply Hg; auto.\nQed.\n#[global] Hint Resolve continuous_ite : order.\n\nLemma leq_refl {A} `{OType A} (x : A) :\n  x ⊑ x.\nProof. reflexivity. Qed.\n#[global] Hint Resolve leq_refl : order.\n\nLemma continuous_disj (P : Prop) :\n  continuous (fun x : Prop => P \\/ x).\nProof.\n  intros ch Hch Q Hsup; unfold compose.\n  split.\n  - intros i [H|H]; auto.\n    destruct Hsup as [Hub Hlub].\n    right; apply (Hub i); auto.\n  - intros R HR [HP|HQ].\n    + apply (HR O); auto.\n    + destruct Hsup as [Hub Hlub]; eapply Hlub; auto.\n      intros i y; eapply HR; right; eauto.\nQed.\n\nLemma dec_continuous_conj (P : Prop) :\n  dec_continuous (fun x : Prop => P /\\ x).\nProof.\n  intros ch Hch Q Hinf; unfold compose.\n  split.\n  - intros i [H0 H1]; split; auto; apply Hinf; auto.\n  - intros R HR x; split.\n    + apply (HR O); auto.\n    + destruct Hinf as [Hlb Hglb].\n      eapply Hglb.\n      2: { apply x. }\n      intros i y; apply HR; auto.\nQed.\n\nLemma continuous_exists {I} :\n  continuous (fun f : I -> Prop => exists i : I, f i).\nProof.\n  intros ch Hch f [Hub Hlub]; unfold compose; split.\n  - intros i [j Hj]; exists j; eapply Hub; eauto.\n  - intros x Hx [j Hj]; eapply Hlub; eauto.\n    intros k l Hkl; eapply Hx; exists l; eauto.\nQed.\n\nLemma dec_continuous_forall {I} :\n  dec_continuous (fun f : I -> Prop => forall i : I, f i).\nProof.\n  intros ch Hch f [Hlb Hglb]; unfold compose; split.\n  - intros n H i; apply Hlb; auto.\n  - intros P HP H i.\n    unfold lower_bound in HP; simpl in HP; unfold impl in HP.\n    eapply Hglb.\n    + intros m j Hj.\n      apply HP; auto.\n    + apply (HP O); auto.\nQed.\n\nLemma continuous_const {A B} `{OType A} `{OType B} (b : B) :\n  continuous (fun _ : A => b).\nProof. intros ? ? ? ?; apply supremum_const. Qed.\n#[global] Hint Resolve continuous_const : order.\n\nLemma cocontinuous_const {A B} `{OType A} `{OType B} (b : B) :\n  cocontinuous (fun _ : A => b).\nProof. intros ? ? ? ?; apply infimum_const. Qed.\n\n#[global]\n  Instance monotone_fst {A B} `{OType A} `{OType B}\n  : Proper (leq ==> leq) (@fst A B).\nProof. intros [] [] []; auto. Qed.\n#[global] Hint Resolve monotone_fst : order.\n\n#[global]\n  Instance monotone_snd {A B} `{OType A} `{OType B}\n  : Proper (leq ==> leq) (@snd A B).\nProof. intros [] [] []; auto. Qed.\n#[global] Hint Resolve monotone_snd : order.\n\nLemma supremum_fst {A B} `{OType A} `{OType B} (a : A) (b : B) (f : nat -> A * B) :\n  supremum (a, b) f ->\n  supremum a (fst ∘ f).\nProof.\n  intros [Hub Hlub]; split.\n  - intro i; specialize (Hub i); inv Hub; auto.\n  - unfold compose; intros x Hx.\n    specialize (Hlub (x, b)).\n    apply Hlub.\n    intro i; specialize (Hx i); simpl in Hx.\n    specialize (Hub i).\n    inv Hub.\n    destruct (f i); constructor; auto.\nQed.\n\nLemma infimum_fst {A B} `{OType A} `{OType B} (a : A) (b : B) (f : nat -> A * B) :\n  infimum (a, b) f ->\n  infimum a (fst ∘ f).\nProof.\n  intros [Hub Hlub]; split.\n  - intro i; specialize (Hub i); inv Hub; auto.\n  - unfold compose; intros x Hx.\n    specialize (Hlub (x, b)).\n    apply Hlub.\n    intro i; specialize (Hx i); simpl in Hx.\n    specialize (Hub i).\n    inv Hub.\n    destruct (f i); constructor; auto.\nQed.\n\nLemma supremum_snd {A B} `{OType A} `{OType B} (a : A) (b : B) (f : nat -> A * B) :\n  supremum (a, b) f ->\n  supremum b (snd ∘ f).\nProof.\n  intros [Hub Hlub]; split.\n  - intro i; specialize (Hub i); inv Hub; auto.\n  - unfold compose; intros x Hx.\n    specialize (Hlub (a, x)).\n    apply Hlub.\n    intro i; specialize (Hx i); simpl in Hx.\n    specialize (Hub i).\n    inv Hub.\n    destruct (f i); constructor; auto.\nQed.\n\nLemma infimum_snd {A B} `{OType A} `{OType B} (a : A) (b : B) (f : nat -> A * B) :\n  infimum (a, b) f ->\n  infimum b (snd ∘ f).\nProof.\n  intros [Hub Hlub]; split.\n  - intro i; specialize (Hub i); inv Hub; auto.\n  - unfold compose; intros x Hx.\n    specialize (Hlub (a, x)).\n    apply Hlub.\n    intro i; specialize (Hx i); simpl in Hx.\n    specialize (Hub i).\n    inv Hub.\n    destruct (f i); constructor; auto.\nQed.\n\nLemma chain_fst {A B} `{OType A} `{OType B} (f : nat -> A * B) :\n  chain f ->\n  chain (fst ∘ f).\nProof. firstorder. Qed.\n\nLemma directed_fst {A B} `{OType A} `{OType B} (f : nat -> A * B) :\n  directed f ->\n  directed (fst ∘ f).\nProof.\n  intros Hf i j; specialize (Hf i j); destruct Hf as [k [Hk Hk']].\n  exists k; split; apply monotone_fst; auto.\nQed.\n\nLemma chain_snd {A B} `{OType A} `{OType B} (f : nat -> A * B) :\n  chain f ->\n  chain (snd ∘ f).\nProof. firstorder. Qed.\n\nLemma directed_snd {A B} `{OType A} `{OType B} (f : nat -> A * B) :\n  directed f ->\n  directed (snd ∘ f).\nProof.\n  intros Hf i j; specialize (Hf i j); destruct Hf as [k [Hk Hk']].\n  exists k; split; apply monotone_snd; auto.\nQed.\n\nLemma supremum_prod {A B} `{OType A} `{OType B} (a : A) (b : B) (f : nat -> A * B) :\n  supremum a (fst ∘ f) ->\n  supremum b (snd ∘ f) ->\n  supremum (a, b) f.\nProof.\n  intros [Ha Ha'] [Hb Hb']; split.\n  - intro i; specialize (Ha i); specialize (Hb i).\n    unfold compose in *; destruct (f i); split; auto.\n  - intros [x y] Hxy; split; simpl.\n    + apply Ha'; intro i; specialize (Hxy i); unfold compose;\n        destruct (f i); destruct Hxy; auto.\n    + apply Hb'; intro i; specialize (Hxy i); unfold compose;\n        destruct (f i); destruct Hxy; auto.\nQed.\n\nLemma infimum_prod {A B} `{OType A} `{OType B} (a : A) (b : B) (f : nat -> A * B) :\n  infimum a (fst ∘ f) ->\n  infimum b (snd ∘ f) ->\n  infimum (a, b) f.\nProof.\n  intros [Ha Ha'] [Hb Hb']; split.\n  - intro i; specialize (Ha i); specialize (Hb i).\n    unfold compose in *; destruct (f i); split; auto.\n  - intros [x y] Hxy; split; simpl.\n    + apply Ha'; intro i; specialize (Hxy i); unfold compose;\n        destruct (f i); destruct Hxy; auto.\n    + apply Hb'; intro i; specialize (Hxy i); unfold compose;\n        destruct (f i); destruct Hxy; auto.\nQed.\n\nLemma infimum_conj (f g : nat -> Prop) (P Q : Prop) :\n  infimum P f ->\n  infimum Q g ->\n  infimum (P /\\ Q) (fun i => f i /\\ g i).\nProof.\n  intros [HP HP'] [HQ HQ']; split.\n  - intro i; intros [a b]; split.\n    + apply HP; auto.\n    + apply HQ; auto.\n  - intros R HR z; split.\n    + eapply HP'.\n      2: { apply z. }\n      intros i r; apply HR; auto.\n    + eapply HQ'.\n      2: { apply z. }\n      intros i r; apply HR; auto.\nQed.\n\nLemma inl_supremum {A B} `{OType A} `{OType B} (a : A) (f : nat -> A + B) :\n  supremum (inl a) f ->\n  supremum a (fun i : nat => match f i with\n                        | inl x => x\n                        | inr _ => a\n                        end).\nProof.\n  intros [Hub Hlub]; split.\n  - intro i; destruct (f i) eqn:Hfi.\n    + specialize (Hub i); rewrite Hfi in Hub; apply Hub.\n    + reflexivity.\n  - intros x Hx.\n    assert (Hxf: upper_bound (inl x) f).\n    { intro i; specialize (Hx i); simpl in *.\n      unfold sum_le.\n      destruct (f i) eqn:Hfi; auto.\n      assert (HC: inr b ⊑ inl a).\n      { rewrite <- Hfi; apply Hub. }\n      inv HC. }\n    apply Hlub in Hxf; apply Hxf.\nQed.\n\nLemma inr_supremum {A B} `{OType A} `{OType B} (b : B) (f : nat -> A + B) :\n  supremum (inr b) f ->\n  supremum b (fun i : nat => match f i with\n                        | inl _ => b\n                        | inr y => y\n                        end).\n  intros [Hub Hlub]; split.\n  - intro i; destruct (f i) eqn:Hfi.\n    + reflexivity.\n    + specialize (Hub i); rewrite Hfi in Hub; apply Hub.\n  - intros x Hx.\n    assert (Hxf: upper_bound (inr x) f).\n    { intro i; specialize (Hx i); simpl in *.\n      unfold sum_le.\n      destruct (f i) eqn:Hfi; auto.\n      assert (HC: inl a ⊑ inr b).\n      { rewrite <- Hfi; apply Hub. }\n      inv HC. }\n    apply Hlub in Hxf; apply Hxf.\nQed.\n\nLemma supremum_inl {A B} `{OType A} `{OType B} (ch : nat -> A) (a : A) :\n  supremum a ch ->\n  supremum (inl a) (fun i : nat => inl (ch i)).\nProof.\n  intros [Hub Hlub]; split.\n  - intro i; apply Hub.\n  - intros [a'|b] Ha'.\n    + eapply Hlub; auto.\n    + destruct (Ha' O).\nQed.\n\nLemma supremum_inr {A B} `{OType A} `{OType B} (ch : nat -> B) (b : B) :\n  supremum b ch ->\n  supremum (@inr A B b) (fun i : nat => inr (ch i)).\nProof.\n  intros [Hub Hlub]; split.\n  - intro i; apply Hub.\n  - intros [a|b'] Hb'.\n    + destruct (Hb' O).\n    + eapply Hlub; auto.\nQed.\n\n(* (** Hmm.. need the fancier OType on function spaces for this to work.. *) *)\n(* Lemma monotone_2 {A B C} `{OType A} `{OType B} `{OType C} (f : A -> B -> C) (a : A) : *)\n(*   Proper (leq ==> leq) f -> *)\n(*   Proper (leq ==> leq) (f a). *)\n(* Proof. *)\n(*   intros Hf x y Hxy. *)\n(*   specialize (Hf a a (leq_refl a)). *)\n(*   simpl in Hf. *)\n  \n(*   intros Hf ch Hch b [Hub Hlub]. *)\n(*   unfold compose. *)\n(*   split. *)\n(*   - intro i. *)\n(*     apply  *)\n\n(* Lemma continuous_2 {A B C} `{OType A} `{OType B} `{OType C} (f : A -> B -> C) (a : A) : *)\n(*   continuous f -> *)\n(*   continuous (f a). *)\n(* Proof. *)\n(*   intros Hf ch Hch b [Hub Hlub]. *)\n(*   unfold compose. *)\n(*   split. *)\n(*   - intro i. *)\n(*     apply  *)\n\n(* Definition ofun (A B : Type) `{OType A} `{OType B} : Type := *)\n(*   { f : A -> B | Proper (leq ==> leq) f }. *)\n\n(* Program *)\n(*   Instance OType_arrow' {A B} `{OType A} `{OType B} : OType (ofun A B) := *)\n(*   {| leq := fun f g => forall x y, x ⊑ y -> f x ⊑ g y |}. *)\n(* Next Obligation. *)\n(*   constructor. *)\n(*   - intros f x y Hxy; destruct f; auto. *)\n(*   - intros [f] [g] [h] Hfg Hgh x y Hxy; simpl in *. *)\n(*     etransitivity. *)\n(*     apply Hfg; eauto. *)\n(*     apply Hgh; reflexivity. *)\n(* Qed. *)\n\n(* Definition ocontinuous {A B : Type} `{OType A} `{OType B} (f : ofun A B) := *)\n(*   forall g : nat -> A, *)\n(*     directed g -> *)\n(*     forall a : A, *)\n(*       supremum a g -> *)\n(*       supremum (proj1_sig f a) (proj1_sig f ∘ g). *)\n\n(* Lemma continuous_2 {A B C} `{OType A} `{OType B} `{OType C} (f : ofun A (ofun B C)) (a : A) : *)\n(*   ocontinuous f -> *)\n(*   ocontinuous (proj1_sig f a). *)\n(* Proof. *)\n(*   intros Hf ch Hch b Hsup. *)\n(*   specialize (Hf (const a) (directed_const a) a (supremum_const a)). *)\n(*   destruct Hf as [Hub Hlub]. *)\n(*   unfold compose, const in *. *)\n(*   simpl in *. *)\n(*   destruct Hsup as [Hub' Hlub']. *)\n(*   destruct f as [f]; simpl in *. *)\n(*   destruct (f a) as [g]; simpl in *. *)\n(*   split. *)\n(*   - intro i; apply p0; auto. *)\n(*   - intros x Hx. *)\n(*     clear Hub. *)\n(*     specialize (Hlub (exist _ g p0)). *)\n(*     simpl in Hlub. *)\n\n(*   intros Hf ch Hch b [Hub Hlub]. *)\n(*   destruct f as [f]. *)\n(*   unfold compose. *)\n(*   split. *)\n(*   - intro i. *)\n(*     simpl. *)\n(*     destruct (f a) as [g]; simpl. *)\n(*     apply p0. *)\n(*     apply Hub. *)\n(*   - intros x Hx; simpl in *. *)\n(*     destruct (f a) as [g]; simpl.     *)\n(*     simpl in *. *)\n(*     specialize (Hf (const a)). *)\n(*     simpl in Hf. *)\n", "meta": {"author": "bagnalla", "repo": "algco", "sha": "433836e4a0743c0443d530913769a00549b6993a", "save_path": "github-repos/coq/bagnalla-algco", "path": "github-repos/coq/bagnalla-algco/algco-433836e4a0743c0443d530913769a00549b6993a/order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7879311881731379, "lm_q1q2_score": 0.6513919994507661}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq             *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later            *)\nFrom mathcomp Require Import all_ssreflect ssralg fingroup finalg matrix.\nRequire Import Reals Lra.\nFrom mathcomp Require Import Rstruct.\nRequire Import ssrR Reals_ext Ranalysis_ext logb ln_facts Rbigop fdist entropy.\nRequire Import channel_code channel divergence conditional_divergence.\nRequire Import variation_dist pinsker.\n\n(******************************************************************************)\n(*                         Error exponent bound                               *)\n(*                                                                            *)\n(* Lemmas:                                                                    *)\n(*   out_entropy_dist_ub == Distance from the output entropy of one channel   *)\n(*                          to another                                        *)\n(* joint_entropy_dist_ub == Distance from the joint entropy of one channel    *)\n(*                          to another                                        *)\n(*      mut_info_dist_ub == Distance from the mutual information of one       *)\n(*                          channel to another                                *)\n(*  error_exponent_bound == intermediate step in the proof of the converse of *)\n(*                          the channel coding theorem                        *)\n(*                                                                            *)\n(* For details, see Reynald Affeldt, Manabu Hagiwara, and Jonas Sénizergues.  *)\n(* Formalization of Shannon's theorems. Journal of Automated Reasoning,       *)\n(* 53(1):63--103, 2014                                                        *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope divergence_scope.\nLocal Open Scope fdist_scope.\nLocal Open Scope entropy_scope.\nLocal Open Scope channel_scope.\nLocal Open Scope reals_ext_scope.\nLocal Open Scope R_scope.\n\nSection mutinfo_distance_bound.\n\nVariables (A B : finType) (V W : `Ch(A, B)) (P : fdist A).\nHypothesis V_dom_by_W : P |- V << W.\nHypothesis cdiv_ub : D(V || W | P) <= (exp(-2)) ^ 2 * / 2.\n\nLet cdiv_bounds : 0 <= sqrt (2 * D(V || W | P)) <= exp (-2).\nProof.\nsplit; first exact: sqrt_pos.\napply pow2_Rle_inv; [ exact: sqrt_pos | exact/ltRW/exp_pos | ].\nrewrite [in X in X <= _]/= mulR1 sqrt_sqrt; last first.\n  apply mulR_ge0; [lra | exact: cdiv_ge0].\napply/leRP; rewrite -(leR_pmul2r' (/ 2)); last exact/ltRP/invR_gt0.\nby rewrite -mulRA mulRCA mulRV ?mulR1; [exact/leRP | exact/gtR_eqF].\nQed.\n\nLocal Open Scope variation_distance_scope.\n\nLemma out_entropy_dist_ub : `| `H(P `o V) - `H(P `o W) | <=\n  / ln 2 * #|B|%:R * - xlnx (sqrt (2 * D(V || W | P))).\nProof.\nrewrite 2!xlnx_entropy.\nrewrite -addR_opp -mulRN -mulRDr normRM gtR0_norm; last exact/invR_gt0/ln2_gt0.\nrewrite -mulRA; apply leR_pmul2l; first exact/invR_gt0/ln2_gt0.\nrewrite oppRK big_morph_oppR -big_split /=.\napply: leR_trans; first exact: leR_sumR_Rabs.\nrewrite -iter_addR -big_const; apply leR_sumR => b _; rewrite addRC.\napply: Rabs_xlnx => //.\nrewrite 2!fdist_outE -addR_opp big_morph_oppR -big_split /=.\napply: leR_trans; first exact: leR_sumR_Rabs.\napply: (@leR_trans (d((P `X V), (P `X W)))).\n- rewrite /var_dist /=.\n  apply (@leR_trans (\\sum_a \\sum_b `| ((P `X V)) (a, b) - ((P `X W)) (a, b) | )); last first.\n    by apply Req_le; rewrite pair_bigA /=; apply eq_bigr => -[].\n  apply: leR_sumR => a _.\n  rewrite (bigD1 b) //= distRC -[X in X <= _]addR0.\n  rewrite 2!fdist_prodE /= !(mulRC (P a)) addR_opp.\n  by apply/leR_add2l/sumR_ge0 => ? _; exact/normR_ge0.\n- rewrite cdiv_is_div_joint_dist => //.\n  exact/Pinsker_inequality_weak/joint_dominates.\nQed.\n\nLemma joint_entropy_dist_ub : `| `H(P , V) - `H(P , W) | <=\n  / ln 2 * #|A|%:R * #|B|%:R * - xlnx (sqrt (2 * D(V || W | P))).\nProof.\nrewrite 2!xlnx_entropy.\nrewrite -addR_opp -mulRN -mulRDr normRM gtR0_norm; last exact/invR_gt0/ln2_gt0.\nrewrite -2!mulRA; apply leR_pmul2l; first exact/invR_gt0/ln2_gt0.\nrewrite oppRK big_morph_oppR -big_split /=.\napply: leR_trans; first exact: leR_sumR_Rabs.\nrewrite -2!iter_addR -2!big_const pair_bigA /=.\napply: leR_sumR; case => a b _; rewrite addRC /=.\napply Rabs_xlnx => //.\napply (@leR_trans (d(P `X V, P `X W))).\n- rewrite /var_dist /R_dist (bigD1 (a, b)) //= distRC.\n  rewrite -[X in X <= _]addR0.\n  by apply/leR_add2l/sumR_ge0 => ? _; exact/normR_ge0.\n- rewrite cdiv_is_div_joint_dist => //.\n  exact/Pinsker_inequality_weak/joint_dominates.\nQed.\n\nLemma mut_info_dist_ub : `| `I(P, V) - `I(P, W) | <=\n  / ln 2 * (#|B|%:R + #|A|%:R * #|B|%:R) * - xlnx (sqrt (2 * D(V || W | P))).\nProof.\nrewrite /mutual_info_chan.\nrewrite (_ : _ - _ = `H(P `o V) - `H(P `o W) + (`H(P, W) - `H(P, V))); last by field.\napply: leR_trans; first exact: Rabs_triang.\nrewrite -mulRA mulRDl mulRDr.\napply leR_add.\n- by rewrite mulRA; apply out_entropy_dist_ub.\n- by rewrite distRC 2!mulRA; apply joint_entropy_dist_ub.\nQed.\n\nEnd mutinfo_distance_bound.\n\nSection error_exponent_lower_bound.\nVariables A B : finType.\nHypothesis Bnot0 : (0 < #|B|)%nat.\nVariables (W : `Ch(A, B)) (minRate : R).\nHypothesis minRate_cap : minRate > capacity W.\nHypothesis set_of_I_has_ubound :\n  classical_sets.has_ubound (fun y => exists P, `I(P, W) = y).\n\nLemma error_exponent_bound : exists Delta, 0 < Delta /\\\n  forall P : fdist A, forall V : `Ch(A, B),\n    P |- V << W ->\n    Delta <= D(V || W | P) +  +| minRate - `I(P, V) |.\nProof.\nset gamma := / (#|B|%:R + #|A|%:R * #|B|%:R) * (ln 2 * ((minRate - capacity W) / 2)).\nhave : min(exp (-2), gamma) > 0.\n  apply Rmin_Rgt_r; split; apply Rlt_gt; first exact: exp_pos.\n  apply mulR_gt0.\n  - by apply/invR_gt0/addR_gt0wl; [exact/ltR0n | apply/mulR_ge0; exact/leR0n].\n  - by apply mulR_gt0 => //; apply mulR_gt0; [rewrite subR_gt0|exact:invR_gt0].\nmove/(continue_xlnx 0) => [] /= mu [mu_gt0 mu_cond].\nset x := min(mu / 2, exp (-2)).\nhave x_gt0 : 0 < x.\n  by apply: Rmin_pos; [apply: mulR_gt0 => //; exact: invR_gt0|exact: exp_pos].\nhave /mu_cond : D_x no_cond 0 x /\\ R_dist x 0 < mu.\n  split.\n  - by split => //; exact/eqP/ltR_eqF.\n  - rewrite /R_dist subR0 gtR0_norm // /x.\n    apply (@leR_ltR_trans (mu * / 2)); first exact/geR_minl.\n    by rewrite ltR_pdivr_mulr //; lra.\nrewrite /R_dist {2}/xlnx ltRR' subR0 ltR0_norm; last first.\n  apply xlnx_neg; split => //; rewrite /x.\n  exact: leR_ltR_trans (geR_minr _ _) ltRinve21.\nmove=> Hx.\nset Delta := min((minRate - capacity W) / 2, x ^ 2 / 2).\nexists Delta; split.\n  apply Rmin_case.\n  - by apply mulR_gt0; [exact/subR_gt0 | exact/invR_gt0].\n  - by apply mulR_gt0; [exact: expR_gt0 | exact: invR_gt0].\nmove=> P V v_dom_by_w.\ncase/boolP : (Delta <b= D(V || W | P)) => [/leRP| /leRP/ltRNge] Hcase.\n  apply (@leR_trans (D(V || W | P))) => //.\n  by rewrite -{1}(addR0 (D(V || W | P))); exact/leR_add2l/leR_maxl.\nsuff HminRate : (minRate - capacity W) / 2 <= minRate - (`I(P, V)).\n  clear -Hcase v_dom_by_w HminRate.\n  apply (@leR_trans +| minRate - `I(P, V) |); last first.\n    by rewrite -[X in X <= _]add0R; exact/leR_add2r/cdiv_ge0.\n  apply: leR_trans; last exact: leR_maxr.\n  by apply: (leR_trans _ HminRate); exact: geR_minl.\nhave : `I(P, V) <= capacity W + / ln 2 * (#|B|%:R + #|A|%:R * #|B|%:R) *\n                               (- xlnx (sqrt (2 * D(V || W | P)))).\n  apply (@leR_trans (`I(P, W) + / ln 2 * (#|B|%:R + #|A|%:R * #|B|%:R) *\n                               - xlnx (sqrt (2 * D(V || W | P))))); last first.\n    apply/leR_add2r/Rstruct.RleP/Rstruct.Rsup_ub; last by exists P.\n    split; first by exists (`I(P, W)), P.\n    case: set_of_I_has_ubound => y Hy.\n    by exists y => _ [Q _ <-]; apply Hy; exists Q.\n  rewrite addRC -leR_subl_addr.\n  apply (@leR_trans `| `I(P, V) + - `I(P, W) |); first exact: Rle_abs.\n  suff : D(V || W | P) <= exp (-2) ^ 2 * / 2 by apply mut_info_dist_ub.\n  clear -Hcase x_gt0.\n  apply/ltRW/(ltR_leR_trans Hcase).\n  apply (@leR_trans (x ^ 2 * / 2)); first exact: geR_minr.\n  apply leR_wpmul2r; first exact/invR_ge0.\n  by apply pow_incr; split; [exact: ltRW | exact: geR_minr].\nrewrite -[X in _ <= X]oppRK => /leR_oppr/(@leR_add2l minRate).\nmove/(leR_trans _); apply.\nsuff x_gamma : - xlnx (sqrt (2 * (D(V || W | P)))) <= gamma.\n  rewrite oppRD addRA addRC -leR_subl_addr.\n  rewrite [X in X <= _](_ : _ = - ((minRate + - capacity W) / 2)); last by field.\n  rewrite leR_oppr oppRK -mulRA mulRC.\n  rewrite leR_pdivr_mulr // mulRC -leR_pdivl_mulr; last first.\n    by apply addR_gt0wl; [exact/ltR0n|rewrite -natRM; exact/leR0n].\n  by rewrite [in X in _ <= X]mulRC /Rdiv (mulRC _ (/ (_ + _))).\nsuff x_D : xlnx x <= xlnx (sqrt (2 * (D(V || W | P)))).\n  clear -Hx x_D.\n  rewrite leR_oppl; apply (@leR_trans (xlnx x)) => //.\n  rewrite leR_oppl; apply/ltRW/(ltR_leR_trans Hx).\n  by rewrite /gamma; exact: geR_minr.\napply/ltRW/Rgt_lt.\nhave ? : sqrt (2 * D(V || W | P)) < x.\n  apply pow2_Rlt_inv; [exact: sqrt_pos | exact: ltRW | ].\n  rewrite [in X in X < _]/= mulR1 sqrt_sqrt; last first.\n    by apply mulR_ge0; [exact/ltRW | exact/cdiv_ge0].\n  by rewrite mulRC -ltR_pdivl_mulr //; exact/(ltR_leR_trans Hcase)/geR_minr.\nhave ? : x <= exp (- 1).\n  apply (@leR_trans (exp (-2))); first exact: geR_minr.\n  by apply/ltRW/exp_increasing; lra.\napply xlnx_sdecreasing_0_Rinv_e => //.\n- by split; [exact/sqrt_pos|exact: (@leR_trans x _ _ (ltRW _))].\n- by split => //; exact: ltRW.\nQed.\n\nEnd error_exponent_lower_bound.\n", "meta": {"author": "affeldt-aist", "repo": "infotheo", "sha": "5f9efb859dbadcbcae2330e2e21e76f9b632d879", "save_path": "github-repos/coq/affeldt-aist-infotheo", "path": "github-repos/coq/affeldt-aist-infotheo/infotheo-5f9efb859dbadcbcae2330e2e21e76f9b632d879/information_theory/error_exponent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894604912849, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.651384764458233}}
{"text": "Require Import Coq.Init.Peano.\nRequire Import HoTT.Basics HoTT.Truncations HoTT.HProp HoTT.Types HoTT.Spaces.Nat HoTT.DProp.\n\nSection bounded_search.\n\n  Context `{Funext}.\n  Context (P : nat -> Type)\n          {P_hprop : forall n, IsHProp (P n)}\n          (P_dec : forall n, Decidable (P n))\n          (P_inhab : hexists (fun n => P n)).\n  (** We reopen these scopes so they take precedence over nat_scope; otherwise, now that we have [Coq.Init.Peano], we'd get [* : nat -> nat -> nat] rather than [* : Type -> Type -> Type]. *)\n  Global Open Scope type_scope.\n  Global Open Scope core_scope.\n\n  (** But in this file, we want to be able to use the usual symbols for natural number arithmetic. *)\n  Local Open Scope nat_scope.\n\n  Local Definition minimal (n : nat) : Type := forall m : nat, P m -> n <= m.\n  Local Definition ishprop_minimal (n : nat) : IsHProp (minimal n).\n  Proof.\n    apply _.\n  Qed.\n  Local Definition min_n_Type : Type := { n : nat & ((P n) * (minimal n))%type}.\n\n  Local Definition ishpropmin_n : IsHProp min_n_Type.\n  Proof.\n    apply ishprop_sigma_disjoint.\n    intros n n' [p m] [p' m'].\n    apply leq_antisym.\n    - exact (m n' p').\n    - exact (m' n p).\n  Qed.\n\n  (* Local Definition min_n : hProp := hProppair min_n_UU isapropmin_n. *)\n\n  Local Definition smaller (n : nat) := { l : nat & (P l * minimal l * (l <= n))%type}.\n\n  Local Definition smaller_S (n : nat) (k : smaller n) : smaller (S n).\n  Proof.\n    induction k as [l [[p m] z]].\n    exists l.\n    repeat split; try assumption.\n    refine (leq_trans _ _ _ _ _).\n    - exact z.\n    - apply leqnSn.\n  Qed.\n\n  Local Definition bounded_search (n : nat) : smaller n + forall l : nat, (l <= n) -> not (P l).\n  Proof.\n    induction n as [|n IHn].\n    - assert (P 0 + not (P 0)) as X; [apply P_dec |].\n      induction X as [h|].\n      + left.\n        refine (0;(h,_,_)).\n        * intros ? ?. apply leq0n.\n        * reflexivity.\n      + right.\n        intros l lleq0.\n        assert (l0 : l = 0).\n        {\n          apply leq_antisym; try assumption.\n          apply leq0n.\n        }\n        rewrite l0; assumption.\n    - induction IHn as [|n0].\n      + left. apply smaller_S. assumption.\n      + assert (P (n.+1) + not (P (n.+1))) as X by apply P_dec.\n        induction X as [h|].\n        * left.\n          refine (n.+1;(h,_,_)).\n          -- intros m pm.\n             assert ((n.+1 <= m)+(n.+1>m))%type as X by apply leqdichot.\n             destruct X as [leqSnm|ltmSn].\n             ++ assumption.\n             ++ unfold lt in ltmSn.\n                assert (m <= n) as X by assumption.\n                destruct (n0 m X pm).\n          -- apply leq_refl.\n        * right. intros l q.\n          assert ((l <= n) + (l > n)) as X by apply leqdichot.\n          induction X as [h|h].\n          -- exact (n0 l h).\n          -- unfold lt in h.\n             assert (eqlSn : l = n.+1).\n             {\n               apply leq_antisym; assumption.\n             }\n             rewrite eqlSn; assumption.\n  Qed.\n\n  Local Definition n_to_min_n (n : nat) (Pn : P n) : min_n_Type.\n  Proof.\n    assert (smaller n + forall l, (l <= n) -> not (P l)) as X by apply bounded_search.\n    induction X as [[l [[Pl ml] leqln]]|none].\n    - exact (l;(Pl,ml)).\n    - destruct (none n (leq_refl n) Pn).\n  Defined.\n\n  Local Definition prop_n_to_min_n : min_n_Type.\n  Proof.\n    refine (Trunc_rec _ P_inhab).\n    - exact ishpropmin_n.\n    - induction 1 as [n Pn]. exact (n_to_min_n n Pn).\n  Defined.\n\n  Definition minimal_n : { n : nat & P n }.\n  Proof.\n    induction prop_n_to_min_n as [n pl]. induction pl as [p _].\n    exact (n;p).\n  Defined.\n\nEnd bounded_search.\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/BoundedSearch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6513847620664432}}
{"text": "(* Check forward dependencies *)\n\nCheck\n  (fun (P : nat -> Prop) Q (A : P 0 -> Q) (B : forall n : nat, P (S n) -> Q)\n     x =>\n   match x return Q with\n   | exist O H => A H\n   | exist (S n) H => B n H\n   end).\n\n(* Check dependencies in anonymous arguments (from FTA/listn.v) *)\n\nInductive listn (A : Set) : nat -> Set :=\n  | niln : listn A 0\n  | consn : forall (a : A) (n : nat), listn A n -> listn A (S n).\n\nSection Folding.\nVariable B C : Set.\nVariable g : B -> C -> C.\nVariable c : C.\n\nFixpoint foldrn (n : nat) (bs : listn B n) {struct bs} : C :=\n  match bs with\n  | niln => c\n  | consn b _ tl => g b (foldrn _ tl)\n  end.\nEnd Folding.\n\n(* -------------------------------------------------------------------- *)\n(*   Example to test patterns matching on dependent families            *)\n(* This exemple extracted from the developement done by Nacira Chabane  *)\n(* (equipe Paris 6)                                                     *)\n(* -------------------------------------------------------------------- *)\n\n\nRequire Import Prelude.\nRequire Import Logic_Type.\n\nSection Orderings.\n   Variable U : Type.\n\n   Definition Relation := U -> U -> Prop.\n\n   Variable R : Relation.\n\n   Definition Reflexive : Prop := forall x : U, R x x.\n\n   Definition Transitive : Prop := forall x y z : U, R x y -> R y z -> R x z.\n\n   Definition Symmetric : Prop := forall x y : U, R x y -> R y x.\n\n   Definition Antisymmetric : Prop := forall x y : U, R x y -> R y x -> x = y.\n\n   Definition contains (R R' : Relation) : Prop :=\n     forall x y : U, R' x y -> R x y.\n  Definition same_relation (R R' : Relation) : Prop :=\n    contains R R' /\\ contains R' R.\nInductive Equivalence : Prop :=\n    Build_Equivalence : Reflexive -> Transitive -> Symmetric -> Equivalence.\n\n   Inductive PER : Prop :=\n       Build_PER : Symmetric -> Transitive -> PER.\n\nEnd Orderings.\n\n(***** Setoid  *******)\n\nInductive Setoid : Type :=\n    Build_Setoid :\n      forall (S : Type) (R : Relation S), Equivalence _ R -> Setoid.\n\nDefinition elem (A : Setoid) := let (S, R, e) := A in S.\n\nDefinition equal (A : Setoid) :=\n  let (S, R, e) as s return (Relation (elem s)) := A in R.\n\n\nAxiom prf_equiv : forall A : Setoid, Equivalence (elem A) (equal A).\nAxiom prf_refl : forall A : Setoid, Reflexive (elem A) (equal A).\nAxiom prf_sym : forall A : Setoid, Symmetric (elem A) (equal A).\nAxiom prf_trans : forall A : Setoid, Transitive (elem A) (equal A).\n\nSection Maps.\nVariable A B : Setoid.\n\nDefinition Map_law (f : elem A -> elem B) :=\n  forall x y : elem A, equal _ x y -> equal _ (f x) (f y).\n\nInductive Map : Type :=\n    Build_Map : forall (f : elem A -> elem B) (p : Map_law f), Map.\n\nDefinition explicit_ap (m : Map) :=\n  match m return (elem A -> elem B) with\n  | Build_Map f p => f\n  end.\n\nAxiom pres : forall m : Map, Map_law (explicit_ap m).\n\nDefinition ext (f g : Map) :=\n  forall x : elem A, equal _ (explicit_ap f x) (explicit_ap g x).\n\nAxiom Equiv_map_eq : Equivalence Map ext.\n\nDefinition Map_setoid := Build_Setoid Map ext Equiv_map_eq.\n\nEnd Maps.\n\nNotation ap := (explicit_ap _ _).\n\n(* <Warning> : Grammar is replaced by Notation *)\n\n\nDefinition ap2 (A B C : Setoid) (f : elem (Map_setoid A (Map_setoid B C)))\n  (a : elem A) := ap (ap f a).\n\n\n(*****    posint     ******)\n\nInductive posint : Type :=\n  | Z : posint\n  | Suc : posint -> posint.\n\nAxiom\n  f_equal : forall (A B : Type) (f : A -> B) (x y : A), x = y -> f x = f y.\nAxiom eq_Suc : forall n m : posint, n = m -> Suc n = Suc m.\n\n(* The predecessor function *)\n\nDefinition pred (n : posint) : posint :=\n  match n return posint with\n  | Z => (* Z *)  Z\n      (* Suc u *)\n  | Suc u => u\n  end.\n\nAxiom pred_Sucn : forall m : posint, m = pred (Suc m).\nAxiom eq_add_Suc : forall n m : posint, Suc n = Suc m -> n = m.\nAxiom not_eq_Suc : forall n m : posint, n <> m -> Suc n <> Suc m.\n\n\nDefinition IsSuc (n : posint) : Prop :=\n  match n return Prop with\n  | Z => (* Z *)  False\n      (* Suc p *)\n  | Suc p => True\n  end.\nDefinition IsZero (n : posint) : Prop :=\n  match n with\n  | Z => True\n  | Suc _ => False\n  end.\n\nAxiom Z_Suc : forall n : posint, Z <> Suc n.\nAxiom Suc_Z : forall n : posint, Suc n <> Z.\nAxiom n_Sucn : forall n : posint, n <> Suc n.\nAxiom Sucn_n : forall n : posint, Suc n <> n.\nAxiom eqT_symt : forall a b : posint, a <> b -> b <> a.\n\n\n(*******  Dsetoid *****)\n\nDefinition Decidable (A : Type) (R : Relation A) :=\n  forall x y : A, R x y \\/ ~ R x y.\n\n\nRecord DSetoid : Type :=\n  {Set_of : Setoid; prf_decid : Decidable (elem Set_of) (equal Set_of)}.\n\n(* example de Dsetoide d'entiers *)\n\n\nAxiom eqT_equiv : Equivalence posint (eq (A:=posint)).\nAxiom Eq_posint_deci : Decidable posint (eq (A:=posint)).\n\n(* Dsetoide des posint*)\n\nDefinition Set_of_posint := Build_Setoid posint (eq (A:=posint)) eqT_equiv.\n\nDefinition Dposint := Build_DSetoid Set_of_posint Eq_posint_deci.\n\n\n\n(**************************************)\n\n\n(* Definition des signatures *)\n(* une signature est un ensemble d'operateurs muni\n de l'arite de chaque operateur *)\n\n\nSection Sig.\n\nRecord Signature : Type :=\n  {Sigma : DSetoid; Arity : Map (Set_of Sigma) (Set_of Dposint)}.\n\nVariable S : Signature.\n\n\n\nVariable Var : DSetoid.\n\nInductive TERM : Type :=\n  | var : elem (Set_of Var) -> TERM\n  | oper :\n      forall op : elem (Set_of (Sigma S)), LTERM (ap (Arity S) op) -> TERM\nwith LTERM : posint -> Type :=\n  | nil : LTERM Z\n  | cons : TERM -> forall n : posint, LTERM n -> LTERM (Suc n).\n\n\n\n(* -------------------------------------------------------------------- *)\n(*                  Examples                                            *)\n(* -------------------------------------------------------------------- *)\n\n\nParameter t1 t2 : TERM.\n\nType\n  match t1, t2 with\n  | var v1, var v2 => True\n  | oper op1 l1, oper op2 l2 => False\n  | _, _ => False\n  end.\n\n\n\nParameter n2 : posint.\nParameter l1 l2 : LTERM n2.\n\nType\n  match l1, l2 with\n  | nil, nil => True\n  | cons v m y, nil => False\n  | _, _ => False\n  end.\n\n\nType\n  match l1, l2 with\n  | nil, nil => True\n  | cons u n x, cons v m y => False\n  | _, _ => False\n  end.\n\n\n\nDefinition equalT (t1 t2 : TERM) : Prop :=\n  match t1, t2 with\n  | var v1, var v2 => True\n  | oper op1 l1, oper op2 l2 => False\n  | _, _ => False\n  end.\n\nDefinition EqListT (n1 : posint) (l1 : LTERM n1) (n2 : posint)\n  (l2 : LTERM n2) : Prop :=\n  match l1, l2 with\n  | nil, nil => True\n  | cons t1 n1' l1', cons t2 n2' l2' => False\n  | _, _ => False\n  end.\n\n\nReset equalT.\n(* ------------------------------------------------------------------*)\n(*          Initial exemple (without patterns)                       *)\n(*-------------------------------------------------------------------*)\n\nFixpoint equalT (t1 : TERM) : TERM -> Prop :=\n  match t1 return (TERM -> Prop) with\n  | var v1 =>\n      (*var*)\n      fun t2 : TERM =>\n      match t2 return Prop with\n      | var v2 =>\n          (*var*) equal _ v1 v2\n          (*oper*)\n      | oper op2 _ => False\n      end\n      (*oper*)\n  | oper op1 l1 =>\n      fun t2 : TERM =>\n      match t2 return Prop with\n      | var v2 =>\n          (*var*) False\n          (*oper*)\n      | oper op2 l2 =>\n          equal _ op1 op2 /\\\n          EqListT (ap (Arity S) op1) l1 (ap (Arity S) op2) l2\n      end\n  end\n\n with EqListT (n1 : posint) (l1 : LTERM n1) {struct l1} :\n forall n2 : posint, LTERM n2 -> Prop :=\n  match l1 in (LTERM _) return (forall n2 : posint, LTERM n2 -> Prop) with\n  | nil =>\n      (*nil*)\n      fun (n2 : posint) (l2 : LTERM n2) =>\n      match l2 in (LTERM _) return Prop with\n      | nil =>\n          (*nil*) True\n          (*cons*)\n      | cons t2 n2' l2' => False\n      end\n      (*cons*)\n  | cons t1 n1' l1' =>\n      fun (n2 : posint) (l2 : LTERM n2) =>\n      match l2 in (LTERM _) return Prop with\n      | nil =>\n          (*nil*)  False\n          (*cons*)\n      | cons t2 n2' l2' => equalT t1 t2 /\\ EqListT n1' l1' n2' l2'\n      end\n  end.\n\n\n(* ---------------------------------------------------------------- *)\n(*                Version with simple patterns                      *)\n(* ---------------------------------------------------------------- *)\nReset equalT.\n\nFixpoint equalT (t1 : TERM) : TERM -> Prop :=\n  match t1 with\n  | var v1 =>\n      fun t2 : TERM =>\n      match t2 with\n      | var v2 => equal _ v1 v2\n      | oper op2 _ => False\n      end\n  | oper op1 l1 =>\n      fun t2 : TERM =>\n      match t2 with\n      | var _ => False\n      | oper op2 l2 =>\n          equal _ op1 op2 /\\\n          EqListT (ap (Arity S) op1) l1 (ap (Arity S) op2) l2\n      end\n  end\n\n with EqListT (n1 : posint) (l1 : LTERM n1) {struct l1} :\n forall n2 : posint, LTERM n2 -> Prop :=\n  match l1 return (forall n2 : posint, LTERM n2 -> Prop) with\n  | nil =>\n      fun (n2 : posint) (l2 : LTERM n2) =>\n      match l2 with\n      | nil => True\n      | _ => False\n      end\n  | cons t1 n1' l1' =>\n      fun (n2 : posint) (l2 : LTERM n2) =>\n      match l2 with\n      | nil => False\n      | cons t2 n2' l2' => equalT t1 t2 /\\ EqListT n1' l1' n2' l2'\n      end\n  end.\n\n\nReset equalT.\n\nFixpoint equalT (t1 : TERM) : TERM -> Prop :=\n  match t1 with\n  | var v1 =>\n      fun t2 : TERM =>\n      match t2 with\n      | var v2 => equal _ v1 v2\n      | oper op2 _ => False\n      end\n  | oper op1 l1 =>\n      fun t2 : TERM =>\n      match t2 with\n      | var _ => False\n      | oper op2 l2 =>\n          equal _ op1 op2 /\\\n          EqListT (ap (Arity S) op1) l1 (ap (Arity S) op2) l2\n      end\n  end\n\n with EqListT (n1 : posint) (l1 : LTERM n1) (n2 : posint)\n (l2 : LTERM n2) {struct l1} : Prop :=\n  match l1 with\n  | nil => match l2 with\n           | nil => True\n           | _ => False\n           end\n  | cons t1 n1' l1' =>\n      match l2 with\n      | nil => False\n      | cons t2 n2' l2' => equalT t1 t2 /\\ EqListT n1' l1' n2' l2'\n      end\n  end.\n\n(* ---------------------------------------------------------------- *)\n(*                  Version with multiple patterns                  *)\n(* ---------------------------------------------------------------- *)\nReset equalT.\n\nFixpoint equalT (t1 t2 : TERM) {struct t1} : Prop :=\n  match t1, t2 with\n  | var v1, var v2 => equal _ v1 v2\n  | oper op1 l1, oper op2 l2 =>\n      equal _ op1 op2 /\\ EqListT (ap (Arity S) op1) l1 (ap (Arity S) op2) l2\n  | _, _ => False\n  end\n\n with EqListT (n1 : posint) (l1 : LTERM n1) (n2 : posint)\n (l2 : LTERM n2) {struct l1} : Prop :=\n  match l1, l2 with\n  | nil, nil => True\n  | cons t1 n1' l1', cons t2 n2' l2' =>\n      equalT t1 t2 /\\ EqListT n1' l1' n2' l2'\n  | _, _ => False\n  end.\n\n\n(* ------------------------------------------------------------------ *)\n\nEnd Sig.\n\n(* Exemple soumis par Bruno *)\n\nDefinition bProp (b : bool) : Prop := if b then True else False.\n\nDefinition f0 (F : False) (ty : bool) : bProp ty :=\n  match ty as _, ty return (bProp ty) with\n  | true, true => I\n  | _, false => F\n  | _, true => I\n  end.\n\n(* Simplification of bug/wish #1671 *)\n\nInductive I : unit -> Type :=\n| C : forall a, I a -> I tt.\n\n(*\nDefinition F (l:I tt) : l = l :=\nmatch l return l = l with\n| C tt (C _ l')  => refl_equal (C tt (C _ l'))\nend.\n\none would expect that the compilation of F (this involves\nsome kind of pattern-unification) would produce:\n*)\n\nDefinition F (l:I tt) : l = l :=\nmatch l return l = l with\n| C tt l' => match l' return C _ l' = C _ l' with C _ l''  => refl_equal (C tt (C _ l'')) end\nend.\n\nInductive J : nat -> Type :=\n| D : forall a, J (S a) -> J a.\n\n(*\nDefinition G (l:J O) : l = l :=\nmatch l return l = l with\n| D O (D 1 l')  => refl_equal (D O (D 1 l'))\n| D _ _  => refl_equal _\nend.\n\none would expect that the compilation of G (this involves inversion)\nwould produce:\n*)\n\nDefinition G (l:J O) : l = l :=\nmatch l return l = l with\n| D 0 l'' =>\n    match l'' as _l'' in J n return\n      match n return forall l:J n, Prop with\n      | O => fun _ => l = l\n      | S p => fun l'' => D p l'' = D p l''\n      end _l'' with\n    | D 1 l'  => refl_equal (D O (D 1 l'))\n    | _ => refl_equal _\n    end\n| _ => refl_equal _\nend.\n\nFixpoint app {A} {n m} (v : listn A n) (w : listn A m) : listn A (n + m) :=\n  match v with\n    | niln => w\n    | consn a n' v' => consn _ a _ (app v' w)\n  end.\n\n(* Testing regression of bug 2106 *)\n\nSet Implicit Arguments.\nRequire Import List.\n\nInductive nt := E.\nDefinition root := E.\nInductive ctor : list nt -> nt -> Type :=\n Plus : ctor (cons E (cons E nil)) E.\n\nInductive term : nt -> Type :=\n| Term : forall s n, ctor s n -> spine s -> term n\nwith spine : list nt -> Type :=\n| EmptySpine : spine nil\n| ConsSpine : forall n s, term n -> spine s -> spine (n :: s).\n\nInductive step : nt -> nt -> Type :=\n  | Step : forall l n r n' (c:ctor (l++n::r) n'), spine l -> spine r -> step n\nn'.\n\nDefinition test (s:step E E) :=\n  match s with\n    | Step nil _ (cons E nil) _ Plus l l' => true\n    | _ => false\n  end.\n\n(* Testing regression of bug 2454 (\"get\" used not be type-checkable when\n   defined with its type constraint) *)\n\nInductive K : nat -> Type := KC : forall (p q:nat), K p.\n\nDefinition get : K O -> nat := fun x => match x with KC p q => q end.\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/CasesDep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6513549552242028}}
{"text": "\n(*begin hide*)\nRequire Import String. Open Scope string_scope.\nRequire Import Program.\n\nFrom mathcomp Require Import ssreflect ssrnat ssrbool eqtype fintype.\nImport ssreflect ssrnat ssrbool ssrfun eqtype fintype.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nAdd LoadPath \"./\" as Top.\nRequire Import Top.CaseTactic.\nRequire Import Top.Syntax.\n\nRequire Import Vector.\nRequire Import ZArith.\n          \n(*end hide*)\n\n(*\n  No es suficiente con utilizar el tipo bool de Coq, ya que necesitamos\n  dar semántica al \"para todo\" y el \"existe\", por lo tanto utilizamos Prop y\n  lo renombramos para seguir la notación de la materia.\n*)\nNotation bool := Prop.\n\n(** *)\n(*** Semántica del lenguaje ***)\n(** *)\n\n(** *Semántica de los operadores de orden *)\nDefinition SemOrdOp (op : OrdOp) : Z -> Z -> bool :=\n  match op with\n  | EqOP => Zeq_bool\n  | LeOP => Z.leb\n  end\n.\n\n(** *Semántica de los operadores booleanos *)\nDefinition SemBoolOp (op : BoolOp) : bool -> bool -> bool :=\n  match op with\n  | AndOP => fun a b => a /\\ b\n  | OrOP =>  fun a b => a \\/ b\n  end\n.\n\n(** *Semántica de los cuantificadores *)\nDefinition SemQuant (op : QOp) : (Z -> bool) -> bool :=\n  match op with\n  | ForallOP => fun f => forall (z : Z), f z\n  | ExistOP => fun f => exists (z : Z), f z\n  end\n.\n\n(** *Semántica de los operadores aritmeticos *)\nDefinition SemZOp (op : ZOp) : Z -> Z -> Z :=\n  match op with\n  | PlusOP  => Z.add\n  | MinusOP => Z.sub\n  end\n.\n\nInfix \"⦃ op '⦄≤'\" := (SemOrdOp op) (at level 1).\nInfix \"⦃ op '⦄∧'\" := (SemBoolOp op) (at level 1).\nInfix \"⦃ op '⦄+'\" := (SemZOp op) (at level 1).\nNotation \"⦃ op '⦄∀'\" := (SemQuant op) (at level 1).\n\n(** *Semántica de los entornos *)\n(* Dado un entorno E, su semántica será un vector de enteros tamaño E *)\nDefinition SemEnv (E : Env) := Vector.t Z E.\n\n(* \n   Utilizando la notación de la materia la semántica de un entorno E\n   será un subconjunto de Σ tal que los estados están definidos solo\n   para las variables de 0 a E; lo denotamos entonces como Σ(E)\n*)\nNotation \"'Σ(' E )\" := (SemEnv E) (at level 1, no associativity).\n\n(* Diferentes formas de escribir los estados *)\nNotation \"[ ]\" := (nil _) (format \"[ ]\").\nNotation \"z :: σ\" := (cons _ z _ σ) (at level 60, right associativity).\nNotation \"[ x , .. , y ]\" := (cons _ x _ .. (cons _ y _ (nil _)) ..).\n\n(** *Semántica de las variables *)\nDefinition SemVar (E : Env) (v : Var E) : Σ(E) -> Z.\n  intros σ.\n  apply (@nth_order _ _ σ (var_to_nat v)).\n  apply var_to_nat_prop.\nDefined.\n  \n(** *Notation *)\nNotation \"σ ! v\" := (@SemVar _ v σ) (at level 1, no associativity).\n\n(** *Propiedades de los estados *)\n(* Utilizando variables con nombre y la notación de la materia este lema es\n   equivalente a: \n   [σ | x : z] x = z\n*)\nLemma State_Prop_ZVAR : forall (E : Env) (v : Var E) (z : Z) (σ : Σ(E)),\n    (z :: σ) ! (ZVAR E) = z.\nProof. auto. Qed.\n\n(* Utilizando variables con nombre y la notación de la materia este lema es\n   equivalente a: \n   [σ | x : z] w = σ w\n*)\nLemma State_Prop_SVAR : forall (E : Env) (z : Z) (σ : Σ(E)) (w : Var E),\n    (z :: σ) ! (SVAR w) = σ ! w.\nProof.\n  intros E z σ w.\n  dependent destruction w; unfold \"_ ! _\", nth_order in *; simpl. by auto.\n  erewrite -> Fin.of_nat_ext. reflexivity.\nQed.\n\n(* Utilizando variables con nombre y la notación de la materia este lema es\n   equivalente a:\n   Dado algún conjunto de variables V,\n   si para toda w ∈ V, σ w = σ' w\n   entonces      \n   para toda w ∈ V, [σ | x : z] w = [σ' | x : z] w\n*)\nLemma State_Prop_Extension : forall (E : Env) (z : Z) (σ σ' : Σ(E)),\n    (forall w : Var E, σ ! w = σ' ! w) ->\n    (forall w : Var (succn E), (z :: σ) ! w = (z :: σ') ! w).\nProof.\n  intros E z σ σ' H w.\n  dependent destruction w.\n  + Case \"w = ZVAR\". by cbn.\n  + Case \"w = SVAR w\".\n    unfold \"_ ! _\", nth_order in *. simpl.\n    erewrite -> Fin.of_nat_ext. by apply H.\nQed.\n\n(** *Notation *)\nReserved Notation \"⟦ ie '⟧ᵢ'\" (at level 1, no associativity).\nReserved Notation \"⟦ ae '⟧ₐ'\" (at level 1, no associativity).\n\n(** *Semántica de las expresiones enteras *)\nFixpoint SemI E (ie : IntExp E) : Σ(E) -> Z :=\n  match ie with\n  | VAR v           => fun σ => σ ! v\n  | NAT n           => fun _ => Z.of_nat n\n  | Neg ie          => fun σ => (- ⟦ ie ⟧ᵢ σ )%Z\n  | BNOp zop ie ie' => fun σ => (⟦ ie ⟧ᵢ σ) ⦃zop⦄+ (⟦ ie' ⟧ᵢ σ)\n  end\nwhere \"⟦ ie '⟧ᵢ'\" := (SemI ie).\n\n(** *Semántica de las expresiones booleanas *)\nFixpoint SemA E (ae : Assert E) : Σ(E) -> bool :=\n  match ae with\n  | BOOL b          => fun σ => b\n  | Not ae          => fun σ => ~ (⟦ ae ⟧ₐ σ)\n  | OOp oop ie ie'  => fun σ => (⟦ ie ⟧ᵢ σ) ⦃oop⦄≤ (⟦ ie' ⟧ᵢ σ)\n  | BBOp bop ae ae' => fun σ => (⟦ ae ⟧ₐ σ) ⦃bop⦄∧ (⟦ ae' ⟧ₐ σ)\n  | Quant qop ae    => fun σ => ⦃qop⦄∀ (fun z => ⟦ ae ⟧ₐ (z :: σ))\n  end\nwhere \"⟦ ae '⟧ₐ'\" := (SemA ae).\n\n(** *Propiedades de la semántica denotacional *)\n(* \n   Si denotamos a la substitución que substituye cualquier índice i por su\n   su sucesor (i+1) como (n ↦ n+1) entonces vale:\n\n             ⟦ ie / (n ↦ n+1) ⟧ᵢ (z :: σ) = ⟦ ie ⟧ᵢ σ\n\n   Notar que la expresión entera \"ie / (n ↦ n+1)\" que es el resultado de\n   aplicarle la substitución a \"ie\" no tiene índice \"0\" como variable libre, por\n   lo tanto su semántica en un estado extendido que asigna el valor z al índice\n   0 es la misma que evaluarla en el estado sin extender.\n*)\nLemma Lift_Prop : forall (E : Env) (ie : IntExp E) (z : Z) (σ : Σ(E)),\n    ⟦ renI [eta SVAR (E:=E)] ie ⟧ᵢ (z :: σ)\n    =\n    ⟦ ie ⟧ᵢ σ.\nProof.\n  dependent induction ie; intros z' σ.\n  + Case \"Var\".\n    simpl. by apply State_Prop_SVAR.\n  + Case \"Nat\". by simpl.\n  + Case \"Neg\". simpl. by rewrite -> IHie.\n  + Case \"BNOp\".\n    simpl. rewrite -> IHie1. by rewrite -> IHie2.\nQed.\n", "meta": {"author": "alexgadea", "repo": "coqlab", "sha": "573b93c9ab6502812ae603f208898c9d72d5676f", "save_path": "github-repos/coq/alexgadea-coqlab", "path": "github-repos/coq/alexgadea-coqlab/coqlab-573b93c9ab6502812ae603f208898c9d72d5676f/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6513549524268868}}
{"text": "(* Exercise 21 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_021 : ~((forall x : D, P x) /\\ (exists x : D, ~ P x)).\nProof.\nneg_i (1=1) a1.\nexi_e (exists x:D, ~P x) a a2.\ncon_e2 (forall x:D, P x).\nhyp a1.\nneg_e (P a).\nhyp a2.\nall_e (forall x:D, P x) a.\ncon_e1 (exists x:D, ~P x).\nhyp a1.\nlin_solve.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred021.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.6513292696937942}}
{"text": "Require Import UniMath.Combinatorics.Lists.\nRequire Import UniMath.Foundations.Sets.\nRequire Import UniMath.Algebra.Monoids_and_Groups.\n\n\nInfix \"::\" := cons (at level 60, right associativity) : lists_scope.\nDelimit Scope lists_scope with lists.\nBind Scope lists_scope with list.\n\nInfix \"++\" := concatenate (right associativity, at level 60) : lists_scope.\n\nLocal Open Scope lists_scope.\n\nModule ListsNotations.\nNotation \" [ ] \" := nil (format \"[ ]\") : lists_scope.\nNotation \" [ x ] \" := (cons x nil) : lists_scope.\nNotation \" [ x ; .. ; y ] \" := (cons x .. (cons y nil) ..) : lists_scope.\nEnd ListsNotations.\n\nImport ListsNotations.\nOpen Scope lists_scope.\n\nSection ListFacts.\n  Context (A : hSet).\n\n  Fact list_preserve_hset : isaset (list A).\n  Proof.\n    unfold list.\n    eapply (@isofhleveltotal2 2).\n    - pose isasetnat.\n      exact i.\n    - intros.\n      induction x.\n      + apply (isasetunit).\n      + apply isofhleveldirprod.\n        * exact (setproperty A).\n        * exact IHx.\n  Qed.\n\n  Definition setlist : hSet.\n    use hSetpair.\n    - exact (list A).\n    - apply list_preserve_hset.\n  Defined.\n\n\n\n\n\n  Definition concatenate_nil_runit (l : list A) : concatenate l [ ] = l.\n    use (list_ind (λ l, concatenate l nil = l)).\n    - reflexivity.\n    - intros.\n      simpl.\n      simpl in X.\n      rewrite (concatenateStep).\n      rewrite X.\n      reflexivity.\n  Defined.\n\n\n  Definition concatenate_nil_lunit {X : UU} : forall (l : list X), concatenate nil l = l.\n  Proof.\n    reflexivity.\n  Defined.\n\n\n  Definition concatenate_assoc (l1 l2 l3 : list A) :\n    concatenate (concatenate l1 l2) l3 = concatenate l1 (concatenate l2 l3).\n  Proof.\n    revert l1.\n    use list_ind.\n    - simpl.\n      rewrite !concatenate_nil_lunit.\n      reflexivity.\n    - simpl ; intros x xs IH.\n      rewrite !concatenateStep.\n      rewrite IH.\n      reflexivity.\n  Defined.\n\n\n  Definition reverse {X : UU} : list X -> list X.\n  Proof.\n    use list_ind.\n    - apply nil.\n    - intros x ? rev.\n      exact (rev ++ (cons x nil)).\n  Defined.\n\n  Definition reverse_cons {X : UU} (x : X) (l : list X)\n    : reverse (x :: l) = (reverse l) ++ [x].\n  Proof.\n    reflexivity.\n  Defined.\n\n\n  Definition list_ind_on (xs : list A) :\n    ∏ (P : list A → UU), P nil → (∏ (x : A) (xs : list A), P xs → P (x :: xs)) → P xs.\n    intros P X X0.\n    exact (list_ind P X X0 xs).\n  Defined.\n\n  Lemma reverse_concatenate_distr : forall x y:list A, reverse (x ++ y) = reverse y ++ reverse x.\n  Proof.\n    intros x.\n    apply (list_ind_on x).\n    - simpl. intros y.\n      apply (list_ind_on y).\n      + apply idpath.\n      + intros x0 xs X.\n        now rewrite concatenate_nil_runit.\n    - intros x0 xs IHl.\n      simpl in *.\n      intros y.\n      clear x. rename x0 into a. rename xs into l.\n      simpl.\n      replace ((a :: l) ++ y) with (a :: (l ++ y)) by reflexivity.\n      repeat rewrite reverse_cons.\n      rewrite (IHl y).\n      rewrite concatenate_assoc.\n      apply idpath.\n  Defined.\n\n  Definition reverse_involutive (l : list A) : reverse (reverse l) = l.\n  Proof.\n    revert l.\n    apply list_ind.\n    - cbn. reflexivity.\n    - intros x xs IH.\n      replace (reverse (x :: xs)) with (reverse xs ++ [x]) by easy.\n      rewrite (reverse_concatenate_distr (reverse xs) [x]).\n      now rewrite IH.\n  Defined.\n\nEnd ListFacts.\n\nArguments reverse {_} _.\nArguments concatenate_assoc {_} _ _ _.\n", "meta": {"author": "bham-nominal", "repo": "UniNominalSets", "sha": "46f20b07ed48b1b0e30060c0cb412fe90b05e18d", "save_path": "github-repos/coq/bham-nominal-UniNominalSets", "path": "github-repos/coq/bham-nominal-UniNominalSets/UniNominalSets-46f20b07ed48b1b0e30060c0cb412fe90b05e18d/MoreLists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6513275119612403}}
{"text": "Set Warnings \"-notation-overridden, -parsing\".\n\nFrom mathcomp Require Import ssreflect ssrbool eqtype.\nRequire Import Arith List String Lia.\nFrom QuickChick Require Import QuickChick.\nImport ListNotations.\n\n(* Types *)\n\nInductive type : Type :=\n| N : type\n| Arrow : type -> type -> type.\n\nDerive (Arbitrary, Show, EnumSized) for type.\n#[local] Instance dec_type (t1 t2 : type) : Dec (t1 = t2).\nProof. dec_eq. Defined.\n\n(* Terms *)\n\nDefinition var := nat.\n\nInductive term : Type :=\n| Const : nat -> term\n| Id : var -> term\n| App : term -> term -> term\n| Abs : type -> term -> term.\n\nDerive Arbitrary for term.\n\n(* Environments *)\n\nDefinition env := list type.\n\nInductive bind : env -> nat -> type -> Prop :=\n| BindNow   : forall t G, bind (t :: G) 0 t\n| BindLater : forall t t' x G,\n    bind G x t -> bind (t' :: G) (S x) t.\n\n(* Generate variables of a specific type in an env. *)\nDerive ArbitrarySizedSuchThat for (fun x => bind G x t).\n(* Get the type of a given variable in an env. *)\nDerive EnumSizedSuchThat for (fun t => bind G x t).\n(* Check whether a variable has a given type in an env. *)\nDerive DecOpt for (bind G e t).\n\n(* Typing *)\n\nInductive typing (G : env) : term -> type -> Prop :=\n| TId :\n    forall x t,\n      bind G x t ->\n      typing G (Id x) t\n| TConst :\n    forall n,\n      typing G (Const n) N\n| TAbs :\n    forall e t1 t2,\n      typing (t1 :: G) e t2 ->\n      typing G (Abs t1 e) (Arrow t1 t2)\n| TApp :\n    forall e1 e2 t1 t2,\n      typing G e2 t1 ->\n      typing G e1 (Arrow t1 t2) ->\n      typing G (App e1 e2) t2.\n\nFixpoint typeOf G e : option type :=\n  match e with\n  | Id x => nth_error G x\n  | Const n => Some N\n  | Abs t e' =>\n    match typeOf (t::G) e' with\n    | Some t' => Some (Arrow t t')\n    | None => None\n    end\n  | App e1 e2 =>\n    match typeOf G e1, typeOf G e2 with\n    | Some (Arrow t1 t2), Some t1' =>\n      if t1 = t1'? then Some t2 else None\n    | _, _ => None\n    end\n  end.\n\nDefinition vars (Γ : env) (t : type) (g : G term) : G term :=\n  let vs :=\n    map (fun p => Id (snd p))\n        (filter (fun p => t = fst p?)\n                (combine Γ (seq 0 (List.length Γ))))\n  in \n  match vs with\n  | [] => g\n  | _ => oneOf_ (ret (Const 0)) [elems_ (Const 0) vs; g]\n  end.\n\nFixpoint gen_base (Γ : env) (t : type) : G term :=\n  match t with\n  | N => vars Γ t (bindGen (choose (0,10)) (fun n => returnGen (Const n)))\n  | Arrow t1 t2 =>\n      bindGen (gen_base (t1::Γ) t2) (fun e =>\n      returnGen (Abs t1 e))                                       \n  end.\n\nFixpoint gen_typed (sz : nat) (Γ : env) (t : type) : G term :=\n  match sz with\n  | O => gen_base Γ t\n  | S sz' =>\n      let app :=\n        bindGen (@arbitrarySized type _ 3) (fun t' =>\n        bindGen (gen_typed sz' Γ (Arrow t' t)) (fun e1 =>\n        bindGen (gen_typed sz' Γ t') (fun e2 =>\n        returnGen (App e1 e2)))) in\n      match t with\n      | N => vars Γ t (oneOf_ app [app; liftGen Const arbitrary])\n      | Arrow t1 t2 => vars Γ t (oneOf_ app [app; liftGen (Abs t1) (gen_typed sz' Γ t2)])\n      end\n  end.\n\n(* Generate terms of a specific type in an env. *)\nDerive ArbitrarySizedSuchThat for (fun e => typing G e t).\nDerive EnumSizedSuchThat for (fun t => typing G e t).\n\n(* Check whether a variable has a given type in an env. *)\nDerive DecOpt for (typing G e t).\n\n(* Small step CBV semantics *)\nInductive value : term -> Prop :=\n| VConst : forall n, value (Const n)\n| VAbs   : forall t e, value (Abs t e).\n\nDerive DecOpt for (value e).\n\nDefinition is_value (e : term) : bool :=\n  match e with\n  | Const _ | Abs _ _ => true\n  | _ => false\n  end.\n\nFixpoint subst (y : var) (e1 : term) (e2 : term) : term :=\n  match e2 with\n  | Const n => Const n\n  | Id x =>\n      (*! *)\n      if eq_nat_dec x y then e1 else e2\n      (*!! SUBST-swap *)\n      (*! if eq_nat_dec x y then e2 else e1 *)\n  | App e e' =>\n      App (subst y e1 e) (subst y e1 e')\n  | Abs t e =>\n      (*! *)\n      Abs t (subst (S y) e1 e)\n      (*!! SUBST-no-lift *)\n      (*! Abs t (subst y e1 e) *)\n  end.\n\nFixpoint step (e : term) : option term :=\n  match e with\n    | Const _ | Id _ => None | Abs _ x => None\n    | App (Abs t e1) e2 =>\n      if is_value e2 then Some (subst 0 e2 e1)\n      else\n        match step e2 with\n        | Some e2' => Some (App (Abs t e1) e2')\n        | None => None\n        end\n    | App e1 e2 =>\n      match step e1 with\n      | Some e1' => Some (App e1' e2)\n      | None => None\n      end\n  end.\n\n(*\nEval compute in (step (App (Abs N (Id 0)) (Const 42))).\nEval compute in (step (App (Abs N (Abs N (Id 0))) (Const 42))).\nEval compute in (subst 0 (Const 42) (Abs N (Id 0))).\n*)\n\n(* Printing *)\n\nOpen Scope string.\n\nFixpoint show_type (tau : type) :=\n  match tau with\n    | N => \"N\"\n    | Arrow tau1 tau2 =>\n      \"(Arrow \" ++ show_type tau1 ++ \" -> \" ++ show_type tau2 ++ \")\"\n  end.\n\n#[local] Instance showType : Show type := { show := show_type }.\n\nFixpoint show_term (e : term) :=\n  match e with\n    | Const n => \"(Const \" ++ show n ++ \")\"\n    | Id x => \"(Id \" ++ show x ++ \")\"\n    | App e1 e2 => \"(App \" ++ show_term e1 ++ \" \" ++ show_term e2 ++ \")\"\n    | Abs t e => \"(Abs \" ++ show t ++ \" \" ++ show_term e ++ \")\"\n  end.\n\nClose Scope string.\n\n#[local] Instance showTerm : Show term := { show := show_term }.\n\n#[local] Instance dec_eq_opt_type : Dec_Eq (option type).\nProof. dec_eq. Defined.\n\nDefinition preservation (e : term) (t: type) : Checker :=\n  match step e with\n  | Some e' => checker ((typeOf nil e' = Some t)?)\n  | None => checker true\n  end.\n\nDefinition preservation_derived (e : term) (t: type) : Checker :=\n  match step e with\n  | Some e' => checker (typing nil e' t ?? 10)\n  | None => checker true\n  end.\n\nDefinition preservation_check (e : term) : Checker :=\n  match typeOf nil e, step e with\n  | Some t, Some e' => checker ((typeOf nil e' = Some t)?)\n  | None, _ => checker tt\n  | _, _ => checker true\n  end.\n\nExtract Constant defNumTests => \"100000\".\n\n(*! Section base *)\n\nDefinition prop_preservation :=\n  forAll (@arbitrary type _) (fun t =>\n  forAll (gen_typed 5 nil t) (fun e =>\n  preservation e t)).\n\n(*! QuickChick prop_preservation. *)\n\n(*! Section derived-dec *)\n\nDefinition prop_preservation_derived_checker :=\n  forAll (@arbitrary type _) (fun t =>\n  forAll (gen_typed 5 nil t) (fun e =>\n  preservation_derived e t)).\n\n(*! QuickChick prop_preservation_derived_checker. *)\n\n(*! Section derived-gen *)\n\nDefinition prop_preservation_derived_gen :=\n  forAll (@arbitrary type _) (fun t =>\n  forAllMaybe (@arbitrarySizeST _ (fun e => typing nil e t) _ 5) (fun e =>\n  preservation e t)).\n\n(*! QuickChick prop_preservation_derived_gen. *)\n\n(*! Section naive-gen *)\n\nDefinition prop_preservation_naive_gen :=\n  forAll (@arbitrary term _) (fun e =>\n  preservation_check e).\n\n(*! QuickChick prop_preservation_naive_gen. *)\n\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": "QuickChick", "repo": "QuickChick", "sha": "ca56cc21ecc76bc0e1443e917ce26c010980ae2f", "save_path": "github-repos/coq/QuickChick-QuickChick", "path": "github-repos/coq/QuickChick-QuickChick/QuickChick-ca56cc21ecc76bc0e1443e917ce26c010980ae2f/benchmarks/stlc/stlc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6513275119612403}}
{"text": "(** * Poly: Polymorphism and Higher-Order Functions *)\n\nRequire Export Lists.\n\n(* ###################################################### *)\n(** * Polymorphism *)\n\n(** In this chapter we continue our development of basic \n    concepts of functional programming.  The critical new ideas are\n    _polymorphism_ (abstracting functions over the types of the data\n    they manipulate) and _higher-order functions_ (treating functions\n    as data).  We begin with polymorphism.\n*)\n\n(* ###################################################### *)\n(** ** Polymorphic Lists *)\n\n(** For the last couple of chapters, we've been working just\n    with lists of numbers.  Obviously, interesting programs also need\n    to be able to manipulate lists with elements from other types --\n    lists of strings, lists of booleans, lists of lists, etc.  We\n    _could_ just define a new inductive datatype for each of these,\n    for example... *)\n\nInductive boollist : Type :=\n  | bool_nil : boollist\n  | bool_cons : bool -> boollist -> boollist.\n\n(** ... but this would quickly become tedious, partly because we\n    have to make up different constructor names for each datatype, but\n    mostly because we would also need to define new versions of all\n    our list manipulating functions ([length], [rev], etc.)  for each\n    new datatype definition. *)\n\n(** To avoid all this repetition, Coq supports _polymorphic_\n    inductive type definitions.  For example, here is a _polymorphic\n    list_ datatype. *)\n\nInductive list (X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\n(** This is exactly like the definition of [natlist] from the\n    previous chapter, except that the [nat] argument to the [cons]\n    constructor has been replaced by an arbitrary type [X], a binding\n    for [X] has been added to the header, and the occurrences of\n    [natlist] in the types of the constructors have been replaced by\n    [list X].  (We can re-use the constructor names [nil] and [cons]\n    because the earlier definition of [natlist] was inside of a\n    [Module] definition that is now out of scope.) *)\n\n(** What sort of thing is [list] itself?  One good way to think\n    about it is that [list] is a _function_ from [Type]s to\n    [Inductive] definitions; or, to put it another way, [list] is a\n    function from [Type]s to [Type]s.  For any particular type [X],\n    the type [list X] is an [Inductive]ly defined set of lists whose\n    elements are things of type [X]. *)\n\n(** With this definition, when we use the constructors [nil] and\n    [cons] to build lists, we need to tell Coq the type of the\n    elements in the lists we are building -- that is, [nil] and [cons]\n    are now _polymorphic constructors_.  Observe the types of these\n    constructors: *)\n\nCheck nil.\n(* ===> nil : forall X : Type, list X *)\nCheck cons.\n(* ===> cons : forall X : Type, X -> list X -> list X *)\n\n(** (Side note on notation: In .v files, the \"forall\" quantifier is\n    spelled out in letters.  In the generated HTML files, [forall] is\n    usually typeset as the usual mathematical \"upside down A,\" but\n    you'll see the spelled-out \"forall\" in a few places, as in the\n    above comments.  This is just a quirk of typesetting: there is no\n    difference in meaning. *)\n\n(** The \"[forall X]\" in these types can be read as an additional\n    argument to the constructors that determines the expected types of\n    the arguments that follow.  When [nil] and [cons] are used, these\n    arguments are supplied in the same way as the others.  For\n    example, the list containing [2] and [1] is written like this: *)\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\n(** (We've gone back to writing [nil] and [cons] explicitly here\n    because we haven't yet defined the [ [] ] and [::] notations for\n    the new version of lists.  We'll do that in a bit.) *)\n\n(** We can now go back and make polymorphic (or \"generic\")\n    versions of all the list-processing functions that we wrote\n    before.  Here is [length], for example: *)\n\n\nFixpoint length (X:Type) (l:list X) : nat :=\n  match l with\n  | nil      => 0\n  | cons h t => S (length X t)\n  end.\n\n(** Note that the uses of [nil] and [cons] in [match] patterns\n    do not require any type annotations: Coq already knows that the list\n    [l] contains elements of type [X], so there's no reason to include\n    [X] in the pattern.  (More precisely, the type [X] is a parameter\n    of the whole definition of [list], not of the individual\n    constructors.  We'll come back to this point later.)\n\n    As with [nil] and [cons], we can use [length] by applying it first\n    to a type and then to its list argument: *)\n\nExample test_length1 :\n    length nat (cons nat 1 (cons nat 2 (nil nat))) = 2.\nProof. reflexivity.  Qed.\n\n(** To use our length with other kinds of lists, we simply\n    instantiate it with an appropriate type parameter: *)\n\nExample test_length2 :\n    length bool (cons bool true (nil bool)) = 1.\nProof. reflexivity.  Qed.\n\n\n(** Let's close this subsection by re-implementing a few other\n    standard list functions on our new polymorphic lists: *)\n\nFixpoint app (X : Type) (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons X h (app X t l2)\n  end.\n\nFixpoint rev (X:Type) (l:list X) : list X :=\n  match l with\n  | nil      => nil X\n  | cons h t => app X (rev X t) (cons X h (nil X))\n  end.\n\n\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 MumbleGrumble.\n(** **** Exercise: 2 stars (mumble_grumble)  *)\n(** Consider the following two inductively defined types. *)\n\nInductive mumble : Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\nInductive grumble (X:Type) : Type :=\n  | d : mumble -> grumble X\n  | e : X -> grumble X.\n\n(** Which of the following are well-typed elements of [grumble X] for\n    some type [X]?\n      - [d (b a 5)]\n      - [d mumble (b a 5)]\n      - [d bool (b a 5)]\n      - [e bool true]\n      - [e mumble (b c 0)]\n      - [e bool (b c 0)]\n      - [c] \n(* FILL IN HERE *)\n*)\n(** [] *)\n\nEnd MumbleGrumble.\n\n(* ###################################################### *)\n(** *** Type Annotation Inference *)\n\n(** Let's write the definition of [app] again, but this time we won't\n    specify the types of any of the arguments. Will Coq still accept\n    it? *)\n\nFixpoint app' X l1 l2 : list X :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons X h (app' X t l2)\n  end.\n\n(** Indeed it will.  Let's see what type Coq has assigned to [app']: *)\n\nCheck app'.\n(* ===> forall X : Type, list X -> list X -> list X *)\nCheck app.\n(* ===> forall X : Type, list X -> list X -> list X *)\n\n(** It has exactly the same type type as [app].  Coq was able to\n    use _type inference_ to deduce what the types of [X], [l1], and\n    [l2] must be, based on how they are used.  For example, since [X]\n    is used as an argument to [cons], it must be a [Type], since\n    [cons] expects a [Type] as its first argument; matching [l1] with\n    [nil] and [cons] means it must be a [list]; and so on.\n\n    This powerful facility means we don't always have to write\n    explicit type annotations everywhere, although explicit type\n    annotations are still quite useful as documentation and sanity\n    checks, so we will continue to use them most of the time.  You\n    should try to find a balance in your own code between too many\n    type annotations (which can clutter and distract) and too\n    few (which forces readers to perform type inference in their heads\n    in order to understand your code). *)\n\n(* ###################################################### *)\n(** *** Type Argument Synthesis *)\n\n(** Whenever we use a polymorphic function, we need to pass it\n    one or more types in addition to its other arguments.  For\n    example, the recursive call in the body of the [length] function\n    above must pass along the type [X].  But just like providing\n    explicit type annotations everywhere, this is heavy and verbose.\n    Since the second argument to [length] is a list of [X]s, it seems\n    entirely obvious that the first argument can only be [X] -- why\n    should we have to write it explicitly?\n\n    Fortunately, Coq permits us to avoid this kind of redundancy.  In\n    place of any type argument we can write the \"implicit argument\"\n    [_], which can be read as \"Please figure out for yourself what\n    type belongs here.\"  More precisely, when Coq encounters a [_], it\n    will attempt to _unify_ all locally available information -- the\n    type of the function being applied, the types of the other\n    arguments, and the type expected by the context in which the\n    application appears -- to determine what concrete type should\n    replace the [_].\n\n    This may sound similar to type annotation inference -- and,\n    indeed, the two procedures rely on the same underlying mechanisms.\n    Instead of simply omitting the types of some arguments to a\n    function, like\n      app' X l1 l2 : list X :=\n    we can also replace the types with [_], like\n      app' (X : _) (l1 l2 : _) : list X :=\n    which tells Coq to attempt to infer the missing information, just\n    as with argument synthesis.\n\n    Using implicit arguments, the [length] function can be written\n    like this: *)\n\nFixpoint length' (X:Type) (l:list X) : nat :=\n  match l with\n  | nil      => 0\n  | cons h t => S (length' _ t)\n  end.\n\n(** In this instance, we don't save much by writing [_] instead of\n    [X].  But in many cases the difference can be significant.  For\n    example, suppose we want to write down a list containing the\n    numbers [1], [2], and [3].  Instead of writing this... *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...we can use argument synthesis to write this: *)\n\nDefinition list123' := cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ###################################################### *)\n(** *** Implicit Arguments *)\n\n(** In fact, we can go further.  To avoid having to sprinkle [_]'s\n    throughout our programs, we can tell Coq _always_ to infer the\n    type argument(s) of a given function. The [Arguments] directive\n    specifies the name of the function or constructor, and then lists\n    its argument names, with curly braces around any arguments to be\n    treated as implicit. If some arguments of a definition don't have\n    a name, as it is often the case for constructors, they can be\n    marked with a wildcard pattern [_]. *)\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments length {X} l.\nArguments app {X} l1 l2.\nArguments rev {X} l. \n\n(** Now, we don't have to supply type arguments for these functions: *)\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\nCheck (length list123'').\n\n(** Alternatively, we can declare an argument to be implicit while\n    defining the function itself, by surrounding the argument in curly\n    braces.  For example: *)\n\nFixpoint length'' {X:Type} (l:list X) : nat :=\n  match l with\n  | nil      => 0\n  | cons h t => S (length'' t)\n  end.\n\n(** (Note that we didn't even have to provide a type argument to the\n    recursive call to [length'']; indeed, it is invalid to provide\n    one.)  We will use this style whenever possible, although we will\n    continue to use use explicit [Argument] declarations for\n    [Inductive] constructors. The reason for that is that marking the\n    parameter of an inductive type as implicit causes it to become\n    implicit for the type itself, not just its constructors.  For\n    instance, consider the following alternative definition of the\n    [list] type: *)\n\nInductive list' {X:Type} : Type :=\n  | nil' : list'\n  | cons' : X -> list' -> list'.\n\n(** Because [X] is declared as implicit for the _entire_ inductive\n    definition, we can't write an expression such as [list' nat],\n    which is almost never what we want. *)\n\n(** One small problem with declaring arguments [Implicit] is\n    that, occasionally, Coq does not have enough local information to\n    determine a type argument; in such cases, we need to tell Coq that\n    we want to give the argument explicitly this time, even though\n    we've globally declared it to be [Implicit].  For example, suppose we\n    write this: *)\n\nFail Definition mynil := nil.\n\n(** The [Fail] qualifier that appears before [Definition] can be\n    used with _any_ command, and is used to ensure that that command\n    indeed fails when executed. If the command does fail, Coq prints\n    the corresponding error message, but continues processing the rest\n    of the file.  Here, Coq gives us an error because it doesn't know\n    what type argument to supply to [nil].  We can help it by\n    providing an explicit type declaration (so that Coq has more\n    information available when it gets to the \"application\" of [nil]):\n    *)\n\nDefinition mynil : list nat := nil.\n\n(** Alternatively, we can force the implicit arguments to be explicit by\n   prefixing the function name with [@]. *)\n\nCheck @nil.\n\nDefinition mynil' := @nil nat.\n\n(** Using argument synthesis and implicit arguments, we can\n    define convenient notation for lists, as before.  Since we have\n    made the constructor type arguments implicit, Coq will know to\n    automatically infer these when we use the notations. *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** Now lists can be written just the way we'd hope: *)\n\nDefinition list123''' := [1; 2; 3].\n\n\n\n\n\n(* ###################################################### *)\n(** *** Exercises: Polymorphic Lists *)\n\n(** **** Exercise: 2 stars, optional (poly_exercises)  *)\n(** Here are a few simple exercises, just like ones in the [Lists]\n    chapter, for practice with polymorphism.  Fill in the definitions\n    and complete the proofs below. *)\n\nFixpoint repeat {X : Type} (n : X) (count : nat) : list X :=\n match count with\n  | O => []\n  | S count' => n :: repeat n count'\nend.\n\n\nExample test_repeat1:\n  repeat true 2 = cons true (cons true nil).\n (* FILL IN HERE *) Admitted.\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  (* FILL IN HERE *) Admitted.\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(** [] *)\n\n(** **** Exercise: 2 stars, optional (more_poly_exercises)  *)\n(** Here are some slightly more interesting ones... *)\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Polymorphic Pairs *)\n\n(** Following the same pattern, the type definition we gave in\n    the last chapter for pairs of numbers can be generalized to\n    _polymorphic pairs_ (or _products_): *)\n\nInductive prod (X Y : Type) : Type :=\n| pair : X -> Y -> prod X Y.\n\nArguments pair {X} {Y} _ _.\n\n(** As with lists, we make the type arguments implicit and define the\n    familiar concrete notation. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** We can also use the [Notation] mechanism to define the standard\n    notation for pair _types_: *)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** (The annotation [: type_scope] tells Coq that this abbreviation\n    should be used when parsing types.  This avoids a clash with the\n    multiplication symbol.) *)\n\n(** A note of caution: it is easy at first to get [(x,y)] and\n    [X*Y] confused.  Remember that [(x,y)] is a _value_ built from two\n    other values; [X*Y] is a _type_ built from two other types.  If\n    [x] has type [X] and [y] has type [Y], then [(x,y)] has type\n    [X*Y]. *)\n\n(** The first and second projection functions now look pretty\n    much as they would in any functional programming language. *)\n\n(** Note that the pair notation can also be used in patterns... *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with \n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with \n  | (x, y) => y\n  end.\n\n(** The following function takes two lists and combines them\n    into a list of pairs.  In many functional programming languages,\n    it is called [zip].  We call it [combine] for consistency with\n    Coq's standard library. *)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\nEval compute in combine [1;2] [3;4].\n\n\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        Compute (combine [1;2] [false;false;true;true]).\n      print?   []\n*)\n\n(** **** Exercise: 2 stars (split)  *)\n(** The function [split] is the right inverse of combine: it takes a\n    list of pairs and returns a pair of lists.  In many functional\n    programing languages, this function is called [unzip].\n\n    Uncomment the material below and fill in the definition of\n    [split].  Make sure it passes the given unit tests. *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) :=\n(* FILL IN HERE *) admit.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Polymorphic Options *)\n\n(** One last polymorphic type for now: _polymorphic options_.\n    The type declaration generalizes the one for [natoption] in the\n    previous chapter: *)\n\nInductive option (X:Type) : Type :=\n  | Some : X -> option X\n  | None : option X.\n\nArguments Some {X} _. \nArguments None {X}. \n\n(** We can now rewrite the [nth_error] function so that it works\n    with any type of lists. *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity.  Qed.\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\nProof. reflexivity.  Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 1 star, optional (hd_error_poly)  *)\n(** Complete the definition of a polymorphic version of the\n    [hd_error] function from the last chapter. Be sure that it\n    passes the unit tests below. *)\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  (* FILL IN HERE *) admit.\n\n(** Once again, to force the implicit arguments to be explicit,\n    we can use [@] before the name of the function. *)\n\nCheck @hd_error.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\n (* FILL IN HERE *) Admitted.\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Functions as Data *)\n\n(** Like many other modern programming languages -- including\n    all _functional languages_ (ML, Haskell, Scheme, etc.) -- Coq\n    treats functions as first-class citizens, allowing functions to be\n    passed as arguments to other functions, returned as results,\n    stored in data structures, etc.*)\n\n(* ###################################################### *)\n(** ** Higher-Order Functions *)\n\n(** Functions that manipulate other functions are often called\n    _higher-order_ functions.  Here's a simple one: *)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\n(** The argument [f] here is itself a function (from [X] to\n    [X]); the body of [doit3times] applies [f] three times to some\n    value [n]. *)\n\nCheck @doit3times.\n(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity.  Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity.  Qed.\n\n(* ###################################################### *)\n(** ** Filter *)\n\n(** Here is a useful higher-order function, which takes a list\n    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])\n    and \"filters\" the list, returning a new list containing just those\n    elements for which the predicate returns [true]. *)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | []     => []\n  | h :: t => if test h then h :: (filter test t)\n                        else       filter test t\n  end.\n\n(** For example, if we apply [filter] to the predicate [evenb]\n    and a list of numbers [l], it returns a list containing just the\n    even members of [l]. *)\n\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity.  Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  beq_nat (length l) 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n\n(** We can use [filter] to give a concise version of the\n    [countoddmembers] function from the [Lists] chapter. *)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity.  Qed.\n\n(* ###################################################### *)\n(** ** Anonymous Functions *)\n\n(** It is a little annoying to be forced to define the function\n    [length_is_1] and give it a name just to be able to pass it as an\n    argument to [filter], since we will probably never use it again.\n    Moreover, this is not an isolated example.  When using\n    higher-order functions, we often want to pass as arguments\n    \"one-off\" functions that we will never use again; having to give\n    each of these functions a name would be tedious.\n\n    Fortunately, there is a better way. It is also possible to\n    construct a function \"on the fly\" without declaring it at the top\n    level or giving it a name; this is analogous to the notation we've\n    been using for writing down constant lists, natural numbers, and\n    so on. *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity.  Qed.\n\n(** Here is the motivating example from before, rewritten to use\n    an anonymous function. *)\n\nExample test_filter2':\n    filter (fun l => beq_nat (length l) 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 2 stars (filter_even_gt7)  *)\n\n(** Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  (* FILL IN HERE *) admit.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\n (* FILL IN HERE *) Admitted.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\n (* FILL IN HERE *) Admitted.\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(* FILL IN HERE *) admit.\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\n(* FILL IN HERE *) Admitted.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Map *)\n\n(** Another handy higher-order function is called [map]. *)\n\nFixpoint map {X Y:Type} (f:X->Y) (l:list X)\n             : (list Y) :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]\n    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has\n    been applied to each element of [l] in turn.  For example: *)\n\nExample test_map1: map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** The element types of the input and output lists need not be\n    the same ([map] takes _two_ type arguments, [X] and [Y]).  This\n    version of [map] can thus be applied to a list of numbers and a\n    function from numbers to booleans to yield a list of booleans: *)\n\nExample test_map2: map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity.  Qed.\n\n(** It can even be applied to a list of numbers and\n    a function from numbers to _lists_ of booleans to\n    yield a list of lists of booleans: *)\n\nExample test_map3:\n    map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity.  Qed.\n\n\n\n(** ** Map for options *)\n(** **** Exercise: 3 stars (map_rev)  *)\n(** Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (flat_map)  *)\n(** The function [map] maps a [list X] to a [list Y] using a function\n    of type [X -> Y].  We can define a similar function, [flat_map],\n    which maps a [list X] to a [list Y] using a function [f] of type\n    [X -> list Y].  Your definition should work by 'flattening' the\n    results of [f], like so:\n        flat_map (fun n => [n;n+1;n+2]) [1;5;10]\n      = [1; 2; 3; 5; 6; 7; 10; 11; 12].\n*)\n\nFixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X)\n                   : (list Y) :=\n  (* FILL IN HERE *) admit.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Lists are not the only inductive type that we can write a\n    [map] function for.  Here is the definition of [map] for the\n    [option] type: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\n(** **** Exercise: 2 stars, optional (implicit_args)  *)\n(** The definitions and uses of [filter] and [map] use implicit\n    arguments in many places.  Replace the curly braces around the\n    implicit arguments with parentheses, and then fill in explicit\n    type parameters where necessary and use Coq to check that you've\n    done so correctly.  (This exercise is not to be turned in; it is\n    probably easiest to do it on a _copy_ of this file that you can\n    throw away afterwards.)  [] *)\n\n(* ###################################################### *)\n(** ** Fold *)\n\n(** An even more powerful higher-order function is called\n    [fold].  This function is the inspiration for the \"[reduce]\"\n    operation that lies at the heart of Google's map/reduce\n    distributed programming framework. *)\n\nFixpoint fold {X Y:Type} (f: X->Y->Y) (l:list X) (b:Y) : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(** Intuitively, the behavior of the [fold] operation is to\n    insert a given binary operator [f] between every pair of elements\n    in a given list.  For example, [ fold plus [1;2;3;4] ] intuitively\n    means [1+2+3+4].  To make this precise, we also need a \"starting\n    element\" that serves as the initial second input to [f].  So, for\n    example,\n   fold plus [1;2;3;4] 0\n    yields\n   1 + (2 + (3 + (4 + 0))).\n    Here are some more examples:\n*)\n\nCheck (fold andb).\n(* ===> fold andb : list bool -> bool -> bool *)\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n\n(** **** Exercise: 1 star, advanced (fold_types_different)  *)\n(** Observe that the type of [fold] is parameterized by _two_ type\n    variables, [X] and [Y], and the parameter [f] is a binary operator\n    that takes an [X] and a [Y] and returns a [Y].  Can you think of a\n    situation where it would be useful for [X] and [Y] to be\n    different? *)\n\n(* ###################################################### *)\n(** ** Functions That Construct Functions *)\n\n(** Most of the higher-order functions we have talked about so\n    far take functions as _arguments_.  Now let's look at some\n    examples involving _returning_ functions as the results of other\n    functions.\n\n    To begin, here is a function that takes a value [x] (drawn from\n    some type [X]) and returns a function from [nat] to [X] that\n    yields [x] whenever it is called, ignoring its [nat] argument. *)\n\nDefinition constfun {X: Type} (x: X) : nat->X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** In fact, the multiple-argument functions we have already\n    seen are also examples of passing functions as data.  To see why,\n    recall the type of [plus]. *)\n\nCheck plus.\n(* ==> nat -> nat -> nat *)\n\n(** Each [->] in this expression is actually a _binary_ operator\n    on types.  (This is the same as saying that Coq primitively\n    supports only one-argument functions -- do you see why?)  This\n    operator is _right-associative_, so the type of [plus] is really a\n    shorthand for [nat -> (nat -> nat)] -- i.e., it can be read as\n    saying that \"[plus] is a one-argument function that takes a [nat]\n    and returns a one-argument function that takes another [nat] and\n    returns a [nat].\"  In the examples above, we have always applied\n    [plus] to both of its arguments at once, but if we like we can\n    supply just the first.  This is called _partial application_. *)\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity.  Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity.  Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity.  Qed.\n\n(* ##################################################### *)\n(** * Additional Exercises *)\n\nModule Exercises.\n(** **** Exercise: 2 stars (fold_length)  *)\n(** Many common functions on lists can be implemented in terms of\n   [fold].  For example, here is an alternative definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length]. *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\n(* FILL IN HERE *) Admitted.\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(* FILL IN HERE *) admit.\n\n(** Write down a theorem [fold_map_correct] in Coq stating that\n   [fold_map] is correct, and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (currying)  *)\n(** In Coq, a function [f : A -> B -> C] really has the type [A\n    -> (B -> C)].  That is, if you give [f] a value of type [A], it\n    will give you function [f' : B -> C].  If you then give [f'] a\n    value of type [B], it will return a value of type [C].  This\n    allows for partial application, as in [plus3].  Processing a list\n    of arguments with functions that return functions is called\n    _currying_, in honor of the logician Haskell Curry.\n\n    Conversely, we can reinterpret the type [A -> B -> C] as [(A *\n    B) -> C].  This is called _uncurrying_.  With an uncurried binary\n    function, both arguments must be given at once as a pair; there is\n    no partial application. *)\n\n(** We can define currying as follows: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** As an exercise, define its inverse, [prod_uncurry].  Then prove\n    the theorems below to show that the two are inverses. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z :=\n  (* FILL IN HERE *) admit.\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  (* FILL IN HERE *) Admitted.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                               (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (nth_error_informal)  *)\n(** Recall the definition of the [nth_error] function:\n   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n     match l with\n     | [] => None \n     | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\n     end.\n   Write an informal proof of the following theorem:\n   forall X n l, length l = n -> @nth_error X l n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (church_numerals)  *)\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\nModule Church.\nDefinition nat := forall X : Type, (X -> X) -> X -> X.\n\n(** Let's see how to write some numbers with this notation. Iterating\n    a function once should be the same as just applying it. Thus, *)\n\nDefinition one : nat := \n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** Similarly, [two] should apply [f] twice to its argument: *)\n\nDefinition two : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** Defining [zero] is somewhat trickier: how can we apply a function zero\n    times? The answer is simple: just return the argument untouched. *)\n\nDefinition zero : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(** More generally, a number [n] can be written as [fun X f x => f (f\n    ... (f x) ...)], with [n] occurrences of [f]. Notice in particular\n    how the [doit3times] function we've defined previously is actually\n    just the representation of [3]. *)\n\nDefinition three : nat := @doit3times.\n\n(** Complete the definitions of the following functions. Make sure\n    that the corresponding unit tests pass by proving them with\n    [reflexivity]. *)    \n\n(** Successor of a natural number: *)\n\nDefinition succ (n : nat) : nat :=\n  (* FILL IN HERE *) admit.\n\nExample succ_1 : succ zero = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample succ_2 : succ one = two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample succ_3 : succ two = three.\nProof. (* FILL IN HERE *) Admitted.\n\n(** Addition of two natural numbers: *)\n\nDefinition plus (n m : nat) : nat :=\n  (* FILL IN HERE *) admit.\n\nExample plus_1 : plus zero one = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample plus_2 : plus two three = plus three two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. (* FILL IN HERE *) Admitted.\n\n(** Multiplication: *)\n\nDefinition mult (n m : nat) : nat := \n  (* FILL IN HERE *) admit.\n\nExample mult_1 : mult one one = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample mult_2 : mult zero (plus three three) = zero.\nProof. (* FILL IN HERE *) Admitted.\n\nExample mult_3 : mult two three = plus three three.\nProof. (* FILL IN HERE *) Admitted.\n\n(** Exponentiation: *)\n\n(** _Hint_: Polymorphism plays a crucial role here. However, 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  (* FILL IN HERE *) admit.\n\nExample exp_1 : exp two two = plus two two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample exp_2 : exp three two = plus (mult two (mult two two)) one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample exp_3 : exp three zero = one.\nProof. (* FILL IN HERE *) Admitted.\n\nEnd Church.\n(** [] *)\n\nEnd Exercises.\n\n(** $Date: 2016-01-11 13:15:02 -0500 (Mon, 11 Jan 2016) $ *)\n\n", "meta": {"author": "YuduDu", "repo": "Formal-Engineering-Method---coq", "sha": "8285e24c727b8becb5eee8bfb6d08b7ee059361d", "save_path": "github-repos/coq/YuduDu-Formal-Engineering-Method---coq", "path": "github-repos/coq/YuduDu-Formal-Engineering-Method---coq/Formal-Engineering-Method---coq-8285e24c727b8becb5eee8bfb6d08b7ee059361d/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.6513275087126993}}
{"text": "From Equations Require Import Equations.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Lists.List.\n\nRequire Import MirrorSolve.FirstOrder.\nRequire Import MirrorSolve.HLists.\n\nImport ListNotations.\nImport HListNotations.\n\nRequire Import Coq.ZArith.BinInt.\n\nSection ZFOL.\n  Inductive sorts: Set :=\n  | ZS\n  | BS.\n\n  Scheme Equality for sorts.\n\n  Inductive funs: arity sorts -> sorts -> Type :=\n  | ZLit: forall (z: Z), funs [] ZS\n  | BLit: forall (b: bool), funs [] BS\n  | Neg: funs [ZS] ZS\n  | Sub: funs [ZS; ZS] ZS\n  | Plus: funs [ZS; ZS] ZS\n  | Mul: funs [ZS; ZS] ZS\n  | Div: funs [ZS; ZS] ZS\n  | Mod: funs [ZS; ZS] ZS\n  | Abs: funs [ZS] ZS\n  | Lte: funs [ZS; ZS] BS\n  | Lt: funs [ZS; ZS] BS\n  | Gte: funs [ZS; ZS] BS\n  | Gt: funs [ZS; ZS] BS.\n\n\n  Inductive rels: arity sorts -> Type :=.\n\n  Definition sig: signature :=\n    {| sig_sorts := sorts;\n      sig_funs := funs;\n      sig_rels := rels |}.\n\n  Definition fm ctx := FirstOrder.fm sig ctx.\n  Definition tm ctx := FirstOrder.tm sig ctx.\n\n  Definition mod_sorts (s: sig_sorts sig) : Type :=\n    match s with\n    | ZS => Z\n    | BS => bool\n    end.\n\n  Obligation Tactic := idtac.\n  Equations \n    mod_fns params ret (f: sig_funs sig params ret) (args: HList.t mod_sorts params) \n    : mod_sorts ret :=\n    { mod_fns _ _ (BLit b) _ := b;\n      mod_fns _ _ (ZLit z) _ := z;\n      mod_fns _ _ Neg (x ::: _) := Z.opp x;\n      mod_fns _ _ Sub (l ::: r ::: _) := Z.sub l r;\n      mod_fns _ _ Plus (l ::: r ::: _) := Z.add l r;\n      mod_fns _ _ Mul (l ::: r ::: _) := Z.mul l r;\n      mod_fns _ _ Div (l ::: r ::: _) := Z.div l r;\n      mod_fns _ _ Mod (l ::: r ::: _) := Z.modulo l r;\n      mod_fns _ _ Abs (x ::: _) := Z.abs x;\n      mod_fns _ _ Lte (l ::: r ::: _) := Z.leb l r;\n      mod_fns _ _ Lt (l ::: r ::: _) := Z.ltb l r;\n      mod_fns _ _ Gte (l ::: r ::: _) := Z.geb l r;\n      mod_fns _ _ Gt (l ::: r ::: _) := Z.gtb l r;\n    }.\n\n  Definition mod_rels params\n    (args: sig_rels sig params)\n    (env: HList.t mod_sorts params) : Prop :=\n    match args with\n    end.\n\n  Definition fm_model : model sig := {|\n    FirstOrder.mod_sorts := mod_sorts;\n    FirstOrder.mod_fns := mod_fns;\n    FirstOrder.mod_rels := mod_rels;\n  |}.\n\n\nEnd ZFOL.", "meta": {"author": "jsarracino", "repo": "mirrorsolve", "sha": "74fc7790b21952d4f27ea70545b0038f298915b0", "save_path": "github-repos/coq/jsarracino-mirrorsolve", "path": "github-repos/coq/jsarracino-mirrorsolve/mirrorsolve-74fc7790b21952d4f27ea70545b0038f298915b0/src/theories/Z.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6513142203568053}}
{"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(* ** Iteration of binary relations *)\n\nRequire Import Arith Nat Lia.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac gcd prime binomial sums.\n\nSet Implicit Arguments.\n\nSection rel_iter.\n\n  Variable (X : Type) (R : X -> X -> Prop).\n\n  Fixpoint rel_iter n :=\n    match n with\n      | 0   => eq\n      | S n => fun x z => exists y, R x y /\\ rel_iter n y z\n    end.\n\n  Fact rel_iter_plus n m x y : rel_iter (n+m) x y <-> exists a, rel_iter n x a /\\ rel_iter m a y.\n  Proof.\n    revert x y; induction n as [ | n IHn ]; intros x y; simpl.\n    + split.\n      * exists x; split; auto.\n      * intros (? & ? & ?); subst; auto.\n    + split.\n      * intros (a & H1 & H2).\n        apply IHn in H2.\n        destruct H2 as (b & H2 & H3).\n        exists b; split; auto; exists a; auto.\n      * intros (a & (b & H1 & H2) & H3).\n        exists b; split; auto.\n        apply IHn; exists a; auto.\n  Qed.\n\n  Fact rel_iter_1 x y : rel_iter 1 x y <-> R x y.\n  Proof. \n    simpl; split.\n    * intros (? & ? & ?); subst; auto.\n    * exists y; auto.\n  Qed. \n\n  Fact rel_iter_S n x y : rel_iter (S n) x y <-> exists a, rel_iter n x a /\\ R a y.\n  Proof.\n    replace (S n) with (n+1) by lia.\n    rewrite rel_iter_plus. \n    split; intros (a & H1 & H2); exists a; revert H1 H2;\n      rewrite rel_iter_1; auto.\n  Qed.\n\n  Fact rel_iter_sequence n x y : rel_iter n x y <-> exists f, f 0 = x /\\ f n = y /\\ forall i, i < n -> R (f i) (f (S i)).\n  Proof.\n    split.\n    * revert x y; induction n as [ | n IHn ]; simpl; intros x y.\n      + intros; subst y; exists (fun _ => x); repeat split; auto; intros; lia.\n      + intros (a & H1 & H2).\n        destruct IHn with (1 := H2) as (f & H3 & H4 & H5).\n        exists (fun i => match i with 0 => x | S i => f i end); repeat split; auto.\n        intros [ | i ] Hi; subst; auto.\n        apply H5; lia.\n    * intros (f & H1 & H2 & H3); subst x y.\n      induction n as [ | n IHn ].\n      + simpl; auto.\n      + rewrite rel_iter_S.\n        exists (f n); split; auto.\n  Qed.\n\nEnd rel_iter.\n\nLocal Notation power := (mscal mult 1).\n\nDefinition is_digit c q i y := y < q /\\ exists a b, c = (a*q+y)*power i q+b /\\ b < power i q.\n\nFact is_digit_fun c q i x y : is_digit c q i x -> is_digit c q i y -> x = y.\nProof.\n   intros (H1 & a1 & b1 & H3 & H4) (H2 & a2 & b2 & H5 & H6).\n   rewrite H3 in H5.\n   apply div_rem_uniq, proj1 in H5; auto; try lia.\n   apply div_rem_uniq, proj2 in H5; auto; lia.\nQed.\n\nDefinition is_seq (R : nat -> nat -> Prop) c q n := forall i, i < n -> exists y y', is_digit c q i y /\\ is_digit c q (1+i) y' /\\ R y y'.\n\nSection rel_iter_bound.\n\n  Variable (R : nat -> nat -> Prop) (k : nat) (Hk1 : forall x y, R x y -> y <= k*x).\n\n  Let Hk' : forall x y, R x y -> y <= (S k)*x.\n  Proof. intros x y H; apply le_trans with (1 := Hk1 H), mult_le_compat_r; lia. Qed.\n\n  (* q represents a basis big enough so that all the sequence x=x0 R x1 R ... R xn = y can be\n      encoded as the digits of c in base q \n\n      Since the growth of R is controlled by k, we can find a simple diophantine constraint\n      on x n q such that q is big enough. *)\n\n  Definition rel_iter_bound n x y := exists q c, x*power n (S k) < q /\\ is_seq R c q n /\\ is_digit c q 0 x /\\ is_digit c q n y.\n\n  Lemma rel_iter_bound_iter n x y : rel_iter_bound n x y -> rel_iter R n x y.\n  Proof.\n    revert y; induction n as [ | n IHn ]; intros y.\n    * intros (q & c & H1 & H2 & H3 & H4).\n      red in H2.\n      rewrite power_0 in H1; auto.\n      revert H3 H4; apply is_digit_fun.\n    * rewrite rel_iter_S.\n      intros (q & c & H1 & H2 & H3 & H4).\n      assert (0 < q) as Hq.\n      { revert H1; generalize (x*power (S n) (S k)); intros; lia. }\n      assert (exists z, is_digit c q n z) as H6.\n      { exists (rem (div c (power n q)) q).\n        split.\n        + apply div_rem_spec2; lia.\n        + exists (div (div c (power n q)) q), (rem c (power n q)); split.\n          2: apply div_rem_spec2; red; rewrite power_0_inv; lia.\n          rewrite <- div_rem_spec1 with (p := q).\n          apply div_rem_spec1. }\n      destruct H6 as (z & H6); exists z; split.\n      + apply IHn.\n        exists q, c; repeat (split; auto).\n        - apply le_lt_trans with (2 := H1), mult_le_compat; auto.\n          simpl.\n          replace (power n (S k)) with (1*power n (S k)) at 1 by lia.\n          apply mult_le_compat; auto; lia.\n        - intros i Hi; apply H2; lia.\n      + destruct (H2 n) as (u & v & G1 & G2 & G3); auto.\n        rewrite is_digit_fun with (1 := H4) (2 := G2),\n                is_digit_fun with (1 := H6) (2 := G1); auto.\n  Qed.\n\n  Notation power := (mscal mult 1).\n  Notation \"∑\" := (msum plus 0).\n\n  Lemma rel_iter_iter_bound n x y : rel_iter R n x y -> rel_iter_bound n x y.\n  Proof.\n    intros H.\n    apply rel_iter_sequence in H.\n    destruct H as (f & H1 & H2 & H3).\n    assert (forall i, i <= n -> f i <= power i (S k) * x) as Hf.\n    { induction i as [ | i IHi ]; intros Hi; simpl; try lia.\n      specialize (H3 _ Hi).\n      apply Hk' in H3.\n      apply le_trans with (1 := H3).\n      rewrite power_S, <- mult_assoc.\n      apply mult_le_compat; auto.\n      apply IHi; lia. }\n    set (q := S (x * power n (S k))).\n    assert (q <> 0) as Hq by discriminate.\n    assert (forall i, i <= n -> f i < q) as Hfq.\n    { unfold q; intros i Hi.\n      apply le_n_S, le_trans with (1 := Hf _ Hi).\n      rewrite mult_comm; apply mult_le_compat; auto.\n      apply power_mono; auto; lia. } \n    set (c := ∑ (S n) (fun i => f i * power i q)).\n    assert (forall i, i <= n -> is_digit c q i (f i)) as Hc.\n    { intros i Hi; split; auto.\n      + exists (∑ (n-i) (fun j => f (1+i+j) * power j q)),\n               (∑  i    (fun i => f i * power i q)); split.\n        2: apply sum_power_lt; auto; intros; apply Hfq; lia.\n        unfold c; replace (S n) with (i+S (n - i)) by lia.\n        rewrite msum_plus, plus_comm; f_equal; auto. \n        rewrite msum_ext with (g := fun k => power i q*(f (i+k)*power k q)).\n        * rewrite sum_0n_scal_l, mult_comm; f_equal.\n          rewrite msum_S, plus_comm; f_equal.\n          2: simpl; rewrite Nat.mul_1_r; f_equal; lia.\n          rewrite (mult_comm _ q), <- sum_0n_scal_l.\n          apply msum_ext.\n          intros j _.\n          replace (i+S j) with (1+i+j) by lia.\n          rewrite power_S; ring.\n        * intros j _; rewrite power_plus; ring. }\n    exists q, c; split; [ | split; [ | split ] ].\n    + unfold q; auto.\n    + intros i Hi; exists (f i), (f (S i)).\n      split; [ | split ].\n      * apply Hc; lia.\n      * apply Hc; lia.\n      * apply H3; auto.\n    + rewrite <- H1; apply Hc; lia.\n    + rewrite <- H2; apply Hc; lia.\n  Qed.\n\n  Hint Resolve rel_iter_bound_iter rel_iter_iter_bound : core.\n\n  (* A characterization of fun n x y => rel_iter R n x y with a diophantine formula\n     (to be proved in dio_expo.v) when the relation R does not grow more that linearly *)\n\n  Theorem rel_iter_bound_equiv n x y : rel_iter R n x y <-> rel_iter_bound n x y.\n  Proof. split; auto. Qed.\n\nEnd rel_iter_bound.\n\nSection rel_iter_seq.\n\n  Variable (R : nat -> nat -> Prop).\n\n  (* q represents a basis big enough so that all the sequence x=x0 R x1 R ... R xn = y can be\n      encoded as the digits of c in base q *)\n\n  Definition rel_iter_seq n x y := exists q c, is_seq R c q n /\\ is_digit c q 0 x /\\ is_digit c q n y.\n\n  Lemma rel_iter_seq_iter n x y : rel_iter_seq n x y -> rel_iter R n x y.\n  Proof.\n    revert y; induction n as [ | n IHn ]; intros y.\n    * intros (q & c & H2 & H3 & H4).\n      red in H2.\n      simpl; revert H3 H4; apply is_digit_fun.\n    * rewrite rel_iter_S.\n      intros (q & c & H2 & H3 & H4).\n      red in H2.\n      assert (0 < q) as Hq.\n      { destruct H3; lia. }\n      assert (exists z, is_digit c q n z) as H6.\n      { exists (rem (div c (power n q)) q).\n        split.\n        + apply div_rem_spec2; lia.\n        + exists (div (div c (power n q)) q), (rem c (power n q)); split.\n          2: apply div_rem_spec2; red; rewrite power_0_inv; lia.\n          rewrite <- div_rem_spec1 with (p := q).\n          apply div_rem_spec1. }\n      destruct H6 as (z & H6); exists z; split.\n      + apply IHn.\n        exists q, c; msplit 2; auto.\n        intros i Hi; apply H2; lia.\n      + destruct (H2 n) as (u & v & G1 & G2 & G3); auto.\n        rewrite is_digit_fun with (1 := H4) (2 := G2),\n                is_digit_fun with (1 := H6) (2 := G1); auto.\n  Qed.\n\n  Notation power := (mscal mult 1).\n  Notation \"∑\" := (msum plus 0).\n\n  Lemma rel_iter_iter_seq n x y : rel_iter R n x y -> rel_iter_seq n x y.\n  Proof.\n    intros H.\n    apply rel_iter_sequence in H.\n    destruct H as (f & H1 & H2 & H3).\n    assert (exists q, forall i, i <= n -> f i < q) as Hq.\n    { clear H1 H2 H3.\n      revert f; induction n as [ | n IHn ]; intros f.\n      + exists (S (f 0)); intros [ | ] ?; lia.\n      + destruct IHn with (f := fun i => (f (S i))) as (q & Hq).\n        exists (1+f 0+q); intros [ | i ] Hi; try lia.\n        generalize (Hq i); intros; lia. }\n    destruct Hq as (q & Hfq).\n    assert (q <> 0) as Hq. \n    { generalize (Hfq 0); intros; lia. }\n    set (c := ∑ (S n) (fun i => f i * power i q)).\n    assert (forall i, i <= n -> is_digit c q i (f i)) as Hc.\n    { intros i Hi; split; auto.\n      + exists (∑ (n-i) (fun j => f (1+i+j) * power j q)),\n               (∑  i    (fun i => f i * power i q)); split.\n        2: apply sum_power_lt; auto; intros; apply Hfq; lia.\n        unfold c; replace (S n) with (i+S (n - i)) by lia.\n        rewrite msum_plus, plus_comm; f_equal; auto. \n        rewrite msum_ext with (g := fun k => power i q*(f (i+k)*power k q)).\n        * rewrite sum_0n_scal_l, mult_comm; f_equal.\n          rewrite msum_S, plus_comm; f_equal.\n          2: simpl; rewrite Nat.mul_1_r; f_equal; lia.\n          rewrite (mult_comm _ q), <- sum_0n_scal_l.\n          apply msum_ext.\n          intros j _.\n          replace (i+S j) with (1+i+j) by lia.\n          rewrite power_S; ring.\n        * intros j _; rewrite power_plus; ring. }\n    exists q, c; msplit 2.\n    + intros i Hi; exists (f i), (f (S i)).\n      split; [ | split ].\n      * apply Hc; lia.\n      * apply Hc; lia.\n      * apply H3; auto.\n    + rewrite <- H1; apply Hc; lia.\n    + rewrite <- H2; apply Hc; lia.\n  Qed.\n\n  Hint Resolve rel_iter_seq_iter rel_iter_iter_seq : core.\n\n  (* A characterization of fun n x y => rel_iter R n x y with a diophantine formula *)\n\n  Theorem rel_iter_seq_equiv n x y : rel_iter R n x y <-> rel_iter_seq n x y.\n  Proof. split; auto. Qed.\n\nEnd rel_iter_seq.\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/rel_iter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6513142166032715}}
{"text": "(*********************************************************************************\n\n Biadjunctions of bicategories\n\n We define the notion of biadjunction. To do so, we use the formulation with units\n and counits. We don't require the biadjunctions to be coherent: the swallowtail\n equations do not have to be satisfied.\n\n Contents\n 1. Definition\n 2. Equivalence on hom-categories\n\n *********************************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.CategoryTheory.Adjunctions.Core.\nRequire Import UniMath.CategoryTheory.Equivalences.Core.\nRequire Import UniMath.Bicategories.Core.Bicat. Import Bicat.Notations.\nRequire Import UniMath.Bicategories.Core.Invertible_2cells.\nRequire Import UniMath.Bicategories.Core.Univalence.\nRequire Import UniMath.Bicategories.Core.BicategoryLaws.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.PseudoFunctorBicat.\nRequire Import UniMath.Bicategories.PseudoFunctors.PseudoFunctor.\nImport PseudoFunctor.Notations.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Identity.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Composition.\nRequire Import UniMath.Bicategories.Transformations.PseudoTransformation.\nRequire Import UniMath.Bicategories.Transformations.Examples.Whiskering.\nRequire Import UniMath.Bicategories.Transformations.Examples.Unitality.\nRequire Import UniMath.Bicategories.Transformations.Examples.Associativity.\nRequire Import UniMath.Bicategories.Modifications.Modification.\n\nLocal Open Scope cat.\n\n(**\n 1. Definition\n *)\nDefinition left_biadj_unit_counit\n           {B₁ B₂ : bicat}\n           (L : psfunctor B₁ B₂)\n  := ∑ (R : psfunctor B₂ B₁),\n     (pstrans\n       (id_psfunctor B₁)\n       (comp_psfunctor R L))\n     ×\n     (pstrans\n        (comp_psfunctor L R)\n        (id_psfunctor B₂)).\n\nSection BiadjunctionProjections.\n  Context {B₁ B₂ : bicat}\n          {L : psfunctor B₁ B₂}\n          (R : left_biadj_unit_counit L).\n\n  Definition biadj_right_adjoint\n    : psfunctor B₂ B₁\n    := pr1 R.\n\n  Definition biadj_unit\n    : pstrans\n        (id_psfunctor B₁)\n        (comp_psfunctor biadj_right_adjoint L)\n    := pr12 R.\n\n  Definition biadj_counit\n    : pstrans\n        (comp_psfunctor L biadj_right_adjoint)\n        (id_psfunctor B₂)\n    := pr22 R.\nEnd BiadjunctionProjections.\n\nCoercion biadj_right_adjoint : left_biadj_unit_counit >-> psfunctor.\n\nSection BiadjunctionTriangleLaws.\n  Context {B₁ B₂ : bicat}\n          {L : psfunctor B₁ B₂}\n          (R : left_biadj_unit_counit L).\n\n  Let η : pstrans (id_psfunctor B₁) (comp_psfunctor R L)\n    := biadj_unit R.\n  Let ε : pstrans (comp_psfunctor L R) (id_psfunctor B₂)\n    := biadj_counit R.\n\n  Definition biadj_triangle_l_lhs\n    : pstrans L L\n    := comp_pstrans\n         (rinvunitor_pstrans L)\n         (comp_pstrans\n            (L ◅ η)\n            (comp_pstrans\n               (lassociator_pstrans L R L)\n               (comp_pstrans\n                  (ε ▻ L)\n                  (lunitor_pstrans L)))).\n\n  Definition biadj_triangle_l_law\n    : UU\n    := invertible_modification\n         biadj_triangle_l_lhs\n         (id_pstrans L).\n\n  Definition biadj_triangle_r_lhs\n    : pstrans R R\n    := comp_pstrans\n         (linvunitor_pstrans R)\n         (comp_pstrans\n            (η ▻ R)\n            (comp_pstrans\n               (rassociator_pstrans R L R)\n                    (comp_pstrans\n                       (R ◅ ε)\n                       (runitor_pstrans R)))).\n\n  Definition biadj_triangle_r_law\n    : UU\n    := invertible_modification\n         biadj_triangle_r_lhs\n         (id_pstrans R).\nEnd BiadjunctionTriangleLaws.\n\nDefinition left_biadj_data\n           {B₁ B₂ : bicat}\n           (L : psfunctor B₁ B₂)\n  : UU\n  := ∑ (R : left_biadj_unit_counit L),\n     biadj_triangle_l_law R × biadj_triangle_r_law R.\n\nSection BiadjunctionDataProjections.\n  Context {B₁ B₂ : bicat}\n          {L : psfunctor B₁ B₂}\n          (R : left_biadj_data L).\n\n  Definition left_biadj_data_to_left_biadj_unit_counit\n    : left_biadj_unit_counit L\n    := pr1 R.\n\n  Definition biadj_triangle_l\n    : invertible_modification\n        (biadj_triangle_l_lhs (pr1 R))\n        (id_pstrans L)\n    := pr12 R.\n\n  Definition biadj_triangle_r\n    : invertible_modification\n        (biadj_triangle_r_lhs (pr1 R))\n        (id_pstrans (pr1 R))\n    := pr22 R.\nEnd BiadjunctionDataProjections.\n\nCoercion left_biadj_data_to_left_biadj_unit_counit\n  : left_biadj_data >-> left_biadj_unit_counit.\n\nDefinition make_biadj_unit_counit\n           {B₁ B₂ : bicat}\n           {L : psfunctor B₁ B₂}\n           (R : psfunctor B₂ B₁)\n           (η : pstrans\n                  (id_psfunctor B₁)\n                  (comp_psfunctor R L))\n           (ε : pstrans\n                  (comp_psfunctor L R)\n                  (id_psfunctor B₂))\n  : left_biadj_unit_counit L\n  := R ,, η ,, ε.\n\nDefinition make_biadj_data\n           {B₁ B₂ : bicat}\n           {L : psfunctor B₁ B₂}\n           (R : left_biadj_unit_counit L)\n           (tl : biadj_triangle_l_law R)\n           (tr : biadj_triangle_r_law R)\n  : left_biadj_data L\n  := R ,, tl ,, tr.\n\n(**\n 2. Equivalence on hom-categories\n *)\nSection BiadjunctionHom.\n  Context {B₁ B₂ : bicat}\n          {L : psfunctor B₁ B₂}\n          (R : left_biadj_data L)\n          (X : B₁) (Y : B₂).\n\n  Let η : pstrans (id_psfunctor B₁) (comp_psfunctor R L)\n    := biadj_unit R.\n  Let ε : pstrans (comp_psfunctor L R) (id_psfunctor B₂)\n    := biadj_counit R.\n\n  Local Definition biadj_left_hom_data\n    : functor_data (hom X (R Y)) (hom (L X) Y).\n  Proof.\n    use make_functor_data.\n    - exact (λ f, #L f · ε Y).\n    - exact (λ f g α, (##L α) ▹ ε Y).\n  Defined.\n\n  Local Definition biadj_left_hom_is_functor\n    : is_functor biadj_left_hom_data.\n  Proof.\n    split.\n    - intros f.\n      cbn in f ; cbn.\n      rewrite psfunctor_id2, id2_rwhisker.\n      apply idpath.\n    - intros f g h α β.\n      cbn in f, g, h, α, β ; cbn.\n      rewrite rwhisker_vcomp, psfunctor_vcomp.\n      apply idpath.\n  Qed.\n\n  Definition biadj_left_hom\n    : hom X (R Y) ⟶ hom (L X) Y.\n  Proof.\n    use make_functor.\n    - exact biadj_left_hom_data.\n    - exact biadj_left_hom_is_functor.\n  Defined.\n\n  Definition biadj_right_hom_data\n    : functor_data (hom (L X) Y) (hom X (R Y)).\n  Proof.\n    use make_functor_data.\n    - exact (λ f, η X · #R f).\n    - exact (λ f g α, η X ◃ ##R α).\n  Defined.\n\n  Definition biadj_right_hom_is_functor\n    : is_functor biadj_right_hom_data.\n  Proof.\n    split.\n    - intros f.\n      cbn in f ; cbn.\n      rewrite psfunctor_id2, lwhisker_id2.\n      apply idpath.\n    - intros f g h α β.\n      cbn in f, g, h, α, β ; cbn.\n      rewrite psfunctor_vcomp, lwhisker_vcomp.\n      apply idpath.\n  Qed.\n\n  Definition biadj_right_hom\n    : hom (L X) Y ⟶ hom X (R Y).\n  Proof.\n    use make_functor.\n    - exact biadj_right_hom_data.\n    - exact biadj_right_hom_is_functor.\n  Defined.\n\n  Definition biadj_hom_left_right_data\n    : nat_trans_data\n        (functor_identity (hom X (R Y)))\n        (biadj_left_hom ∙ biadj_right_hom).\n  Proof.\n    intros f.\n    exact ((rinvunitor f)\n             • (f ◃ (((invertible_modcomponent_of (biadj_triangle_r R) Y)^-1)\n                       • lunitor _\n                       • (_ ◃ (lunitor _ • runitor _))))\n             • lassociator _ _ _\n             • ((psnaturality_of η f)^-1 ▹ _)\n             • rassociator _ _ _\n             • (_ ◃ psfunctor_comp R (#L f) (ε Y))).\n  Defined.\n\n  Definition biadj_hom_left_right_is_nat_trans\n    : is_nat_trans _ _ biadj_hom_left_right_data.\n  Proof.\n    intros f g α.\n    cbn in f, g, α ; cbn.\n    unfold biadj_hom_left_right_data ; simpl.\n    etrans.\n    {\n      rewrite !vassocr.\n      rewrite rinvunitor_natural.\n      rewrite <- rwhisker_hcomp.\n      rewrite !vassocl.\n      apply maponpaths.\n      rewrite !vassocr.\n      rewrite vcomp_whisker.\n      apply idpath.\n    }\n    rewrite !vassocl.\n    do 2 apply maponpaths.\n    etrans.\n    {\n      rewrite !vassocr.\n      rewrite <- rwhisker_rwhisker.\n      rewrite !vassocl.\n      apply idpath.\n    }\n    apply maponpaths.\n    rewrite lwhisker_vcomp.\n    rewrite psfunctor_rwhisker.\n    rewrite <- lwhisker_vcomp.\n    rewrite !vassocr.\n    apply maponpaths_2.\n    rewrite !vassocl.\n    rewrite rwhisker_lwhisker_rassociator.\n    rewrite !vassocr.\n    apply maponpaths_2.\n    use vcomp_move_L_pM.\n    { is_iso. }\n    simpl.\n    rewrite !vassocr.\n    use vcomp_move_R_Mp.\n    { is_iso. }\n    simpl.\n    rewrite !rwhisker_vcomp.\n    apply maponpaths.\n    exact (!(psnaturality_natural η _ _ f g α)).\n  Qed.\n\n  Definition biadj_hom_left_right\n    : (functor_identity (hom X (R Y)))\n        ⟹\n        biadj_left_hom ∙ biadj_right_hom.\n  Proof.\n    use make_nat_trans.\n    - exact biadj_hom_left_right_data.\n    - exact biadj_hom_left_right_is_nat_trans.\n  Defined.\n\n  Definition biadj_hom_right_left_data\n    : nat_trans_data\n        (biadj_right_hom ∙ biadj_left_hom)\n        (functor_identity (hom (L X) Y)).\n  Proof.\n    intros f.\n    exact (((psfunctor_comp L (η X) (#R f))^-1 ▹ (ε Y))\n             • rassociator _ _ _\n             • (#L (η X) ◃ (psnaturality_of ε f)^-1)\n             • lassociator _ _ _\n             • (((_ ◃ (rinvunitor _ • linvunitor _))\n                   • linvunitor _\n                   • (invertible_modcomponent_of (biadj_triangle_l R) X)) ▹ f)\n             • lunitor f).\n  Defined.\n\n  Definition biadj_hom_right_left_is_nat_trans\n    : is_nat_trans _ _ biadj_hom_right_left_data.\n  Proof.\n    intros f g α.\n    cbn in f, g, α ; cbn.\n    unfold biadj_hom_right_left_data.\n    simpl.\n    refine (!_).\n    etrans.\n    {\n      rewrite !vassocl.\n      do 4 apply maponpaths.\n      etrans.\n      {\n        apply maponpaths.\n        refine (!(vcomp_lunitor f _ α)).\n      }\n      rewrite !vassocr.\n      rewrite vcomp_whisker.\n      apply idpath.\n    }\n    rewrite !vassocr.\n    do 2 apply maponpaths_2.\n    rewrite !vassocl.\n    rewrite <- lwhisker_lwhisker.\n    rewrite !vassocr.\n    apply maponpaths_2.\n    use vcomp_move_L_Mp.\n    { is_iso. }\n    simpl.\n    rewrite !vassocl.\n    use vcomp_move_R_pM.\n    { is_iso. }\n    simpl.\n    rewrite !lwhisker_vcomp.\n    etrans.\n    {\n      do 2 apply maponpaths.\n      etrans.\n      {\n        apply maponpaths.\n        exact (psnaturality_natural ε _ _ _ _ α).\n      }\n      rewrite !vassocr.\n      rewrite vcomp_linv, id2_left.\n      apply idpath.\n    }\n    rewrite rwhisker_lwhisker_rassociator.\n    rewrite !vassocr.\n    apply maponpaths_2.\n    rewrite !rwhisker_vcomp.\n    apply maponpaths.\n    refine (!_).\n    rewrite psfunctor_lwhisker.\n    rewrite !vassocl.\n    rewrite vcomp_rinv, id2_right.\n    apply idpath.\n  Qed.\n\n  Definition biadj_hom_right_left\n    : (biadj_right_hom ∙ biadj_left_hom)\n        ⟹\n        (functor_identity (hom (L X) Y)).\n  Proof.\n    use make_nat_trans.\n    - exact biadj_hom_right_left_data.\n    - exact biadj_hom_right_left_is_nat_trans.\n  Defined.\n\n  Definition biadj_hom_equivalence\n    : equivalence_of_cats (hom X (R Y)) (hom (L X) Y).\n  Proof.\n    use tpair.\n    - use tpair.\n      + exact biadj_left_hom.\n      + use tpair.\n        * exact biadj_right_hom.\n        * split.\n          ** exact biadj_hom_left_right.\n          ** exact biadj_hom_right_left.\n    - split ; simpl.\n      + intro a.\n        apply is_inv2cell_to_is_z_iso.\n        unfold biadj_hom_left_right_data.\n        is_iso.\n        apply property_from_invertible_2cell.\n      + intro a.\n        apply is_inv2cell_to_is_z_iso.\n        unfold biadj_hom_right_left_data.\n        is_iso.\n        apply property_from_invertible_2cell.\n  Defined.\n\n  Definition biadj_hom_equiv\n    : adj_equivalence_of_cats biadj_left_hom.\n  Proof.\n    exact (adjointificiation biadj_hom_equivalence).\n  Defined.\nEnd BiadjunctionHom.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/Bicategories/PseudoFunctors/Biadjunction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6513142078455307}}
{"text": "(** A datatype to coerce from [Type] to [Prop]. The essence is that\n    [squash {x:A|P x}] is equivalent to [exists x:A, P x], however,\n    for instance, [squash (forall x:A, {y:B|P x y})] isn't equivalent\n    to [forall x:A, exists y:B, P x y] (the former is stronger than\n    the latter). In fact [(forall x:A, squash P x) -> squash (forall\n    x:A,P x)] is an equivalent for of the axiom of choice [(forall\n    x:A, exists y:B, P x y) -> (exists f:A->B, forall x:A, P x (f x))]. *)\n\n\nInductive squash (A:Type) : Prop :=\n| squash_intro (a:A) : squash A\n.\n\nLemma squash_map {A B} : (A->B) -> squash A -> squash B.\nProof.\n  intros ? [?]; constructor; eauto.\nQed.\n\nLemma squash_unit {A} : A -> squash A.\nProof.\n  intros ?; constructor; assumption.\nQed.\n\nLemma squash_join {A} : squash (squash A) -> squash A.\nProof.\n  intros [?]; assumption.\nQed.\n\nLemma squash_counit {P:Prop} : squash P -> P.\nProof.\n  intros [?]; assumption.\nQed.\n\nLemma squash_and {A B} : squash (A*B) -> (squash A) /\\ (squash B).\nProof.\n  intros [[h₁ h₂]].\n  split; constructor; assumption.\nQed.\n\n(** The binary case of finite choice. *)\nLemma and_squash {A B} : (squash A) /\\ (squash B) -> squash (A*B).\nProof.\n  intros [[h₁][h₂]].\n  constructor;split;assumption.\nQed.\n\n(** The zero-ary case of finite choice. *)\nLemma squash_top : squash unit.\nProof. do 2 constructor. Qed.\n\n(** In the general case, of dependent product, only this direction is available. *)\nLemma squash_forall {A B} : squash (forall x:A, B x) -> forall x, squash (B x).\nProof.\n  intros h x.\n  destruct h as [h].\n  constructor; eauto.\nQed.\n\n(** Index types [A] where the converse of [squash_forall] is true are\n    said to support choice. The property can be read in a familiar\n    way: products over A of inhabited types is inhabited. Types\n    supporting choice consist essentially of types for which a list of\n    the element exist. It cannot be proved though, as some forms of\n    choice are consistent. *)\nDefinition has_choice A :=\n  forall B:A->Type, (forall x,squash (B x)) -> squash (forall x:A, B x)\n.\n\n(** Types supporting choice can hoist existentials out. *)\nLemma choice_exists A : has_choice A ->\n  forall (B:A->Type) (P:forall x:A, B x -> Prop),\n  (forall x:A, exists y:B x, P x y) ->\n  exists f:(forall x:A,B x), forall x:A, P x (f x).\nProof.\n  intros choice * h.\n  assert (forall x:A, squash { y:B x & P x y }) as h'.\n  { intros x; specialize (h x).\n    destruct h as [ y h ].\n    repeat econstructor; eauto. }\n  apply choice in h'.\n  destruct h' as [h'].\n  exists (fun x => projT1 (h' x)).\n  intros x.\n  apply (projT2 (h' x)).\nQed.\n\n(** A few type supporting choice from the standard library. *)\n(** Equivalent to Lemma [squash_top]. *)\nLemma empty_has_choice : has_choice Empty_set.\nProof.\n  unfold has_choice.\n  intros B f.\n  constructor; intros [].\nQed.\n\nLemma unit_has_choice : has_choice unit.\nProof.\n  unfold has_choice.\n  intros B f.\n  specialize (f tt); destruct f as [f].\n  constructor; intros [].\n  assumption.\nQed.\n\n(** Equivalent to Lemma [and_squash] *)\nLemma bool_has_choice : has_choice bool.\nProof.\n  unfold has_choice.\n  intros B f.\n  generalize (f true); intros [h₁].\n  generalize (f false); intros [h₂].\n  constructor; intros [|]; assumption.\nQed.", "meta": {"author": "aspiwack", "repo": "cosa", "sha": "2d808236e71f2289033dff6b74a3f57311df9a14", "save_path": "github-repos/coq/aspiwack-cosa", "path": "github-repos/coq/aspiwack-cosa/cosa-2d808236e71f2289033dff6b74a3f57311df9a14/Lib/Bracket.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199754937772, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6510818949896795}}
{"text": "\nRequire Import List.\nParameter A : Set.\nParameter B : Set.\nDefinition assoc_list := list (A * B)%type.\nParameter eq_dec : forall (x:A) (y:A),{x=y}+{x<>y}.\n\nDefinition spec (x:A) (l:list (A*B)) r :=\n  match r with\n    | Some y => In (x,y) l\n    | None => forall y:B, ~In (x,y) l\n  end.\n\nFixpoint assoc (x:A) (l:list (A*B)) {struct l}  : option B :=\n  match l with\n    | nil => None\n    | ((x',y)::t) =>\n      match eq_dec x x' with\n\t| left p => Some y\n\t| right p => assoc x t\n      end\n  end.\n\nLemma assoc' : forall (x:A) (l:list (A*B)), option B.\nProof.\n  intros x l.\n  induction l.\n  apply None. \n  case_eq (eq_dec x (fst a)).\n  intros. \n  apply (Some (snd a)).\n  intros ; apply IHl.\nDefined.\n\nExtraction assoc'.    \n\n(* prints out: \nassoc' = \nfun (x : A) (l : list (A * B)) =>\nlist_rec (fun _ : list (A * B) => option B) None\n  (fun (a : A * B) (_ : list (A * B)) (IHl : option B) =>\n   match eq_dec x (fst a) as s return (eq_dec x (fst a) = s -> option B) with\n   | left e => fun _ : eq_dec x (fst a) = left (x <> fst a) e => Some (snd a)\n   | right n => fun _ : eq_dec x (fst a) = right (x = fst a) n => IHl\n   end (eq_refl (eq_dec x (fst a)))) l\n     : A -> list (A * B) -> option B\n\n(** val assoc' : a -> (a, b) prod list -> b option **)\n\nlet rec assoc' x = function\n| Nil -> None\n| Cons (y, l0) ->\n  (match eq_dec x (fst y) with\n   | Left -> Some (snd y)\n   | Right -> assoc' x l0)\n\n*)\n\n(* \nAnd then solve the obligations with:\n\nSolve Obligations using intros; clear H0; subst; try (destruct (assoc x t); compute in *; destruct x0); firstorder; congruence.\n\n*) ", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/assoc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6510818875176794}}
{"text": "Require Import ct00.\n(* ct00 contains the original conjecture. *)\n\nRequire Import ct22.\n(* ct16 contains all necessary divide-and-conquer tactics *)\n\nRequire Import ct02 ct15 ct18 ct25.\n(* ct02 ct15 ct18 ct25 contains the following proven lemmas:\n * - sort_prog_base\n * - permutation_merge_concat\n * - merge_sorted\n * - permutation_split_pivot\n *)\n\nFixpoint merge l1 l2 :=\n  let fix merge_aux l2 :=\n  match l1, l2 with\n  | [], _ => l2\n  | _, [] => l1\n  | a1::l1', a2::l2' =>\n      if (le_lt_dec a1 a2) then a1 :: merge l1' l2 else a2 :: merge_aux l2'\n  end\n  in merge_aux l2.\n\nLemma sort_prog_pivot : forall (a : nat) (l l' l'0: list nat),\n     sorted l' -> permutation l' (snd (split_pivot nat le le_dec a l))\n  -> sorted l'0 -> permutation l'0 (fst (split_pivot nat le le_dec a l))\n  -> {l'1 : list nat | sorted l'1 /\\ permutation l'1 (a :: l)}.\nProof.\nintros; exists (merge l'0 (a :: l')); split.\n+ apply merge_sorted; auto; constructor; auto.\n  assert (Forall (le a) l').\n  eapply Permutation_Forall. apply Permutation_sym; apply H0.\n  apply Forall_snd_split_pivot; intros; \n  apply not_le, gt_le_S,le_Sn_le in H3; auto.\n  inversion H3; auto.\n+ rewrite permutation_merge_concat, <- Permutation_middle; constructor;\n  rewrite H0, H2; apply permutation_split_pivot.\nDefined.\n\nLemma qsort_prog : \n  forall (l : list nat), {l' : list nat | sorted l' /\\ permutation l' l}.\nProof.\nunshelve div_conq_pivot. exact le. exact le_dec. \n- apply sort_prog_base.\n- intros; destruct H,H0,a0,a1; eapply sort_prog_pivot.\n  exact H1. assumption. exact H. assumption.\nDefined.\n\n(*---------------------------------Extraction---------------------------------*)\n\nRequire Extraction.\nRequire Import ExtrOcamlBasic.\nRequire Import ExtrOcamlNatInt.\n(* Suppose all the packages above are embedded in some trans *)\n\nExtraction Language OCaml.\nSet Extraction AccessOpaque.\n\nExtraction \"extraction/qsort.ml\" qsort_prog.\n\n(*----------------------------------------------------------------------------*)", "meta": {"author": "jinxinglim", "repo": "coq-chain", "sha": "e237c6b5f797f2af43237b68ff599d6cc0a8d60e", "save_path": "github-repos/coq/jinxinglim-coq-chain", "path": "github-repos/coq/jinxinglim-coq-chain/coq-chain-e237c6b5f797f2af43237b68ff599d6cc0a8d60e/contributions/ct26.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6510818760849876}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type :=  Nil : lst |  Cons : natural -> lst -> lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint 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. lfind.  simpl.  reflexivity. \nAdmitted.\n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal81_theorem0_48_append_assoc/goal81.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.651081864291769}}
{"text": "Require Import init.\n\nRequire Import nat.\nRequire Export mult.\nRequire Import set.\n\nRequire Import int_plus.\n\nNotation \"a ⊗ b\" :=\n    (fst a * fst b + snd a * snd b, fst a * snd b + snd a * fst b)\n    (at level 40, left associativity) : int_scope.\n\n(* begin hide *)\nOpen Scope int_scope.\n\nLemma int_mult_wd : ∀ a b c d, a ~ b → c ~ d → a ⊗ c ~ b ⊗ d.\nProof.\n    intros [a1 a2] [b1 b2] [c1 c2] [d1 d2] ab cd.\n    simpl in *.\n    pose proof (rmult c1 ab) as eq1.\n    pose proof (rmult c2 ab) as eq2.\n    pose proof (lmult b1 cd) as eq3.\n    pose proof (lmult b2 cd) as eq4.\n    symmetry in eq2.\n    symmetry in eq4.\n    pose proof (lrplus eq1 eq2) as eq5.\n    pose proof (lrplus eq3 eq4) as eq6.\n    pose proof (lrplus eq5 eq6) as eq.\n    clear ab cd eq1 eq2 eq3 eq4 eq5 eq6.\n    repeat rewrite ldist in eq.\n    repeat rewrite rdist in eq.\n    plus_cancel_right (b2 * c1) in eq.\n    plus_cancel_right (b1 * c2) in eq.\n    plus_cancel_right (b1 * c1) in eq.\n    plus_cancel_right (b2 * c2) in eq.\n    plus_bring_left (a1 * c2).\n    plus_bring_left (a2 * c1).\n    repeat rewrite plus_assoc.\n    exact eq.\nQed.\n\nGlobal Instance int_mult : Mult int := {\n    mult := binary_op (binary_self_wd int_mult_wd);\n}.\n\nLemma int_mult_comm : ∀ a b, a * b = b * a.\nProof.\n    intros a b.\n    equiv_get_value a b.\n    unfold mult; simpl; equiv_simpl.\n    destruct a as [a1 a2], b as [b1 b2].\n    simpl.\n    do 2 rewrite (mult_comm b1 _).\n    do 2 rewrite (mult_comm b2 _).\n    rewrite (plus_comm (a2 * b1)).\n    reflexivity.\nQed.\n\nGlobal Instance int_mult_comm_class : MultComm int := {\n    mult_comm := int_mult_comm;\n}.\n\nLemma int_mult_assoc : ∀ a b c, a * (b * c) = (a * b) * c.\nProof.\n    intros a b c.\n    equiv_get_value a b c.\n    unfold mult; simpl; equiv_simpl.\n    destruct a as [a1 a2], b as [b1 b2], c as [c1 c2]; simpl.\n    repeat rewrite ldist, rdist.\n    repeat rewrite mult_assoc.\n    plus_cancel_left (a1 * b1 * c1)%nat.\n    plus_cancel_left (a1 * b1 * c2)%nat.\n    plus_cancel_left (a1 * b2 * c1)%nat.\n    plus_cancel_left (a1 * b2 * c2)%nat.\n    plus_cancel_left (a2 * b1 * c1)%nat.\n    plus_cancel_left (a2 * b1 * c2)%nat.\n    reflexivity.\nQed.\n\nGlobal Instance int_mult_assoc_class : MultAssoc int := {\n    mult_assoc := int_mult_assoc;\n}.\n\nLemma int_ldist : ∀ a b c, a * (b + c) = a * b + a * c.\nProof.\n    intros a b c.\n    equiv_get_value a b c.\n    unfold plus, mult; simpl; equiv_simpl.\n    destruct a as [a1 a2], b as [b1 b2], c as [c1 c2]; simpl.\n    do 4 rewrite ldist.\n    plus_cancel_left (a1 * b1)%nat.\n    plus_cancel_left (a1 * c1)%nat.\n    plus_cancel_left (a2 * b2)%nat.\n    plus_cancel_left (a2 * c2)%nat.\n    plus_cancel_left (a2 * b1)%nat.\n    plus_cancel_left (a1 * c2)%nat.\n    reflexivity.\nQed.\n\nGlobal Instance int_ldist_class : Ldist int := {\n    ldist := int_ldist;\n}.\n\nGlobal Instance int_one : One int := {\n    one := to_equiv int_equiv (1, 0);\n}.\n\nLemma int_mult_lid : ∀ a, 1 * a = a.\nProof.\n    intros a.\n    equiv_get_value a.\n    unfold mult, one; simpl; equiv_simpl.\n    destruct a as [a1 a2]; simpl.\n    repeat rewrite mult_lanni.\n    repeat rewrite plus_rid.\n    do 2 rewrite mult_lid.\n    reflexivity.\nQed.\n\nGlobal Instance int_mult_lid_class : MultLid int := {\n    mult_lid := int_mult_lid;\n}.\n(* end hide *)\nTheorem int_mult_0 : ∀ {a b}, 0 = a * b → 0 = a ∨ 0 = b.\nProof.\n    intros a b eq.\n    equiv_get_value a b.\n    unfold mult, zero in *; simpl in *.\n    equiv_simpl in eq.\n    equiv_simpl.\n    destruct a as [a1 a2], b as [b1 b2]; simpl in *.\n    repeat rewrite plus_rid in *.\n    repeat rewrite plus_lid in *.\n    pose proof (trichotomy a1 a2) as comps.\n    destruct comps as [comps|comp].\n    destruct comps as [comp|comp].\n    { (* a1 < a2 *)\n        apply nat_lt_ex in comp as [c c_eq].\n        rewrite <- c_eq in eq.\n        do 2 rewrite rdist in eq.\n        do 2 rewrite plus_assoc in eq.\n        rewrite (plus_comm (a1 * b2)) in eq.\n        apply plus_lcancel in eq.\n        apply mult_lcancel in eq; [>|apply nat_zero_suc].\n        right; symmetry; exact eq.\n    }\n    { (* a1 = a2 *)\n        left; symmetry; exact comp.\n    }\n    { (* a1 > a2 *)\n        apply nat_lt_ex in comp as [c c_eq].\n        rewrite <- c_eq in eq.\n        do 2 rewrite rdist in eq.\n        rewrite plus_comm in eq.\n        rewrite (plus_comm _ (a2 * b2)) in eq.\n        do 2 rewrite plus_assoc in eq.\n        rewrite (plus_comm (a2 * b1)) in eq.\n        apply plus_lcancel in eq.\n        apply mult_lcancel in eq; [>|apply nat_zero_suc].\n        right; exact eq.\n    }\nQed.\n\n(* begin hide *)\nLemma int_mult_lcancel : ∀ a b c, 0 ≠ c → c * a = c * b → a = b.\nProof.\n    intros a b c c_neq_0 eq.\n    apply plus_0_anb_a_b in eq.\n    rewrite <- mult_rneg in eq.\n    rewrite <- ldist in eq.\n    destruct (int_mult_0 eq) as [eq2|eq2]; try contradiction.\n    rewrite plus_0_anb_a_b in eq2.\n    exact eq2.\nQed.\n\nGlobal Instance int_mult_lcancel_class : MultLcancel int := {\n    mult_lcancel := int_mult_lcancel;\n}.\n\nLemma int_not_trivial : 0 ≠ 1.\nProof.\n    unfold zero, one; simpl.\n    equiv_simpl.\n    intro eq.\n    inversion eq.\nQed.\n\nGlobal Instance int_not_trivial_class : NotTrivial int := {\n    not_trivial := int_not_trivial;\n}.\n\nClose Scope int_scope.\n(* end hide *)\nTheorem nat_to_int_mult : ∀ a b,\n        nat_to_int (a * b) = nat_to_int a * nat_to_int b.\nProof.\n    intros a b.\n    unfold mult at 2, nat_to_int; simpl; equiv_simpl; simpl.\n    do 2 rewrite mult_lanni.\n    rewrite mult_ranni.\n    do 3 rewrite plus_rid.\n    reflexivity.\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_mult.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6510392028297776}}
{"text": "\nRequire Import Undecidability.Synthetic.Definitions.\nFrom Undecidability.L Require Import L Functions.Eval Util.L_facts.\nImport L_Notations.\n\n(* Halting problem for call-by-value lambda-calculus *)\nDefinition HaltLclosed (s : {s : term | closed s}) := exists t, eval (proj1_sig s) t.\n\nLemma reduction : HaltL ⪯ HaltLclosed.\nProof.\n  unshelve eexists.\n  - intros s. exists (Eval (enc s)). unfold Eval. Lproc. \n  - cbn. intros s. unfold HaltL. split; intros (t & Ht).\n    + eapply eval_converges. edestruct Eval_converges. eapply H.\n      eapply eval_iff in Ht. eauto.\n    + setoid_rewrite eval_iff. eapply eval_converges.\n      eapply Eval_converges. eapply Seval.eval_converges. eauto.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/L/Reductions/HaltL_to_HaltLclosed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.6510391900858133}}
{"text": "From Undecidability.L Require Import L .\nFrom Undecidability.L.Tactics Require Import LTactics GenEncode.\nFrom Undecidability.L.Datatypes Require Import Lists LNat. \nFrom Complexity.NP.SAT Require Export SharedSAT.\nRequire Import Lia Nat. \n\n(** * Formula Satisfiability: the satisfiability problem on arbitrary Boolean formulas *)\n\nInductive formula : Type := \n  | Ftrue : formula\n  | Fvar : var -> formula\n  | Fand : formula -> formula -> formula\n  | For : formula -> formula -> formula\n  | Fneg : formula -> formula. \n\nNotation \"a ∧ b\" := (Fand a b) (at level 40).  \nNotation \"a ∨ b\" := (For a b) (at level 40). \nNotation \"¬ a\" := (Fneg a) (at level 10). \nCoercion Fvar : var >-> formula. \n\nNotation \"⋁ [ x , .. , z , y ]\" := (For x .. (For z y) ..). \nNotation \"⋀ [ x , .. , z , y ]\" := (Fand x .. (Fand z y) ..). \n\n(** assignments: we list the variables which are assigned the value true; all other variables are assigned the value false *)\nImplicit Types (a : assgn) (f : formula) (v : var). \n\nFixpoint evalFormula a f := \n  match f with \n  | Ftrue => true\n  | Fvar v => evalVar a v\n  | Fand f1 f2 => evalFormula a f1 && evalFormula a f2\n  | For f1 f2 => evalFormula a f1 || evalFormula a f2\n  | Fneg f => negb (evalFormula a f)\n  end. \n\nLemma evalFormula_and_iff a f1 f2 : evalFormula a (f1 ∧ f2) = true <-> evalFormula a f1 = true /\\ evalFormula a f2 = true. \nProof. cbn. now rewrite andb_true_iff. Qed. \n\nLemma evalFormula_and_iff' f1 f2 a: evalFormula a (f1 ∧ f2) = false <-> evalFormula a f1 = false \\/ evalFormula a f2 = false. \nProof. \n  cbn.  destruct (evalFormula a f1), (evalFormula a f2); cbn; tauto.\nQed. \n\nLemma evalFormula_or_iff a f1 f2 : evalFormula a (f1 ∨ f2) = true <-> evalFormula a f1 = true \\/ evalFormula a f2 = true. \nProof. cbn. now rewrite orb_true_iff. Qed. \n\nLemma evalFormula_not_iff a f : evalFormula a (¬ f) = true <-> not (evalFormula a f = true).\nProof.\n  cbn. rewrite negb_true_iff. split; intro H.\n  - rewrite H. discriminate.\n  - destruct (evalFormula a f).\n    + now contradiction H.\n    + reflexivity.\nQed. \n\nLemma evalFormula_prim_iff a v : evalFormula a v = true <-> v el a. \nProof. cbn. unfold evalVar. rewrite list_in_decb_iff; [easy | intros ]. now rewrite Nat.eqb_eq. Qed. \n\n(** satisfaction of formulas *)\nDefinition satisfies a f := evalFormula a f = true. \nDefinition FSAT f := exists a, satisfies a f. \n\n(** bounds on the number of used variables *)\nInductive varInFormula (v : var) : formula -> Prop := \n  | varInFormulaV : varInFormula v v\n  | varInFormuAndL f1 f2: varInFormula v f1 -> varInFormula v (f1 ∧ f2)\n  | varInFormulaAndR f1 f2 : varInFormula v f2 -> varInFormula v (f1 ∧ f2)\n  | varInFormulaOrL f1 f2 : varInFormula v f1 -> varInFormula v (f1 ∨ f2)\n  | varInFormulaOrR f1 f2 : varInFormula v f2 -> varInFormula v (f1 ∨ f2)\n  | varInFormulaNot f : varInFormula v f -> varInFormula v (¬ f).\n#[export]\n  Hint Constructors varInFormula : core.\n\nDefinition formula_varsIn (p : nat -> Prop) f := forall v, varInFormula v f -> p v. \n\n(** A computable notion of boundedness *)\nFixpoint formula_maxVar (f : formula) := match f with\n  | Ftrue => 0\n  | Fvar v => v\n  | Fand f1 f2 => Nat.max (formula_maxVar f1) (formula_maxVar f2)\n  | For f1 f2 => Nat.max (formula_maxVar f1) (formula_maxVar f2)\n  | Fneg f => formula_maxVar f\nend. \n\nLemma formula_maxVar_varsIn f : formula_varsIn (fun n => n < S (formula_maxVar f)) f. \nProof. \n  unfold formula_varsIn. \n  induction f. \n  - intros v H. inv H. \n  - intros v H. inv H. now cbn. \n  - intros v H. inv H. \n    + apply IHf1 in H1. cbn. lia. \n    + apply IHf2 in H1. cbn. lia. \n  - intros v H. inv H. \n    + apply IHf1 in H1. cbn. lia. \n    + apply IHf2 in H1. cbn. lia. \n  - intros v H. inv H. apply IHf in H1. cbn. lia. \nQed.\n\nLemma formula_varsIn_bound f c : formula_varsIn (fun n => n <= c) f -> formula_maxVar f <= c. \nProof. \n  unfold formula_varsIn. intros H. induction f; cbn. \n  - lia. \n  - now apply H. \n  - apply Nat.max_lub; [apply IHf1 | apply IHf2]; eauto.\n  - apply Nat.max_lub; [apply IHf1 | apply IHf2]; eauto. \n  - apply IHf; eauto.\nQed. \n\n(** size of formulas *)\nFixpoint formula_size (f : formula) := match f with \n  | Ftrue => 1\n  | Fvar _ => 1\n  | For f1 f2 => formula_size f1 + formula_size f2 + 1\n  | Fand f1 f2 => formula_size f1 + formula_size f2 + 1\n  | Fneg f => formula_size f + 1\nend. \n\n(** ** extraction *)\nFrom Undecidability.L.Datatypes Require Import LNat.\nFrom Undecidability.L.Tactics Require Import LTactics GenEncode.\nFrom Undecidability.L.Datatypes Require Import  LProd LOptions LBool LUnit.\nFrom Complexity.Libs.CookPrelim Require Import PolyBounds. \n\nMetaCoq Run (tmGenEncode \"formula_enc\" formula).\n#[export]\nHint Resolve formula_enc_correct : Lrewrite.\n\nLemma formula_enc_size f: size (enc f) = match f with \n  | Ftrue => 10\n  | Fvar v => 10 + size (enc v )\n  | Fand f1 f2 => 10 + size (enc f1) + size (enc f2) \n  | For f1 f2 => 9 + size (enc f1) + size (enc f2) \n  | Fneg f => 7 + size (enc f) \n  end. \nProof.\n  set (g:=enc (X:= formula)). unfold enc in g;cbn in g.\n  destruct f; cbn; try lia. \nQed. \n\n#[export]\nInstance term_Fvar : computableTime' Fvar (fun v _ => (1, tt)). \nProof. \n  extract constructor. solverec. \nQed. \n\n#[export]\nInstance term_Fand : computableTime' Fand (fun f1 _ => (1, fun f2 _ => (1, tt))).\nProof. \n  extract constructor. solverec. \nQed. \n\n#[export]\nInstance term_For : computableTime' For (fun f1 _ => (1, fun f2 _ => (1, tt))). \nProof. \n  extract constructor. solverec. \nQed. \n\n#[export]\nInstance term_Fneg : computableTime' Fneg (fun f _ => (1, tt)). \nProof. \n  extract constructor. solverec. \nQed. \n\n(** the encoding size of a formula is bounded linearly by formula_size f * formula_maxVar f *)\nDefinition c__formulaBound1 := c__natsizeS. \nDefinition c__formulaBound2 := size (enc Ftrue) + 10 + c__natsizeO.\nLemma formula_enc_size_bound : forall f, size (enc f) <= c__formulaBound1 * formula_size f * formula_maxVar f + c__formulaBound2 * formula_size f.\nProof. \n  induction f; rewrite formula_enc_size. \n  - unfold c__formulaBound2. cbn. nia.\n  - rewrite size_nat_enc. unfold c__formulaBound1, c__formulaBound2. cbn -[Nat.add Nat.mul]. lia. \n  - cbn -[Nat.mul Nat.add].\n    rewrite IHf1, IHf2. unfold c__formulaBound2. cbn. nia.\n  - cbn -[Nat.mul Nat.add].\n    rewrite IHf1, IHf2. unfold c__formulaBound2. cbn. nia.\n  - cbn -[Nat.mul Nat.add]. \n    rewrite IHf. unfold c__formulaBound2. nia. \nQed. \n\n(** conversely, we can only obtain a quadratic bound due to the overapproximation provided by maxVar *)\n\nLemma formula_size_enc_bound f : formula_size f <= size (enc f). \nProof. \n  induction f; rewrite formula_enc_size; cbn -[Nat.add Nat.mul]; try lia.\nQed.  \n\nLemma formula_maxVar_enc_bound f : formula_maxVar f <= size (enc f).\nProof. \n  induction f; rewrite formula_enc_size; cbn -[Nat.add Nat.mul]; try lia. \n  rewrite (size_nat_enc_r n) at 1. unfold enc. cbn. nia. \nQed. \n\nLemma formula_total_size_enc_bound f : formula_size f * formula_maxVar f <= size (enc f) * size (enc f). \nProof. \n  rewrite formula_size_enc_bound, formula_maxVar_enc_bound. lia. \nQed. \n\n\n(**extraction of formula_maxVar *)\n\nDefinition c__formulaMaxVar := 13 + c__max1. \nFixpoint formula_maxVar_time (f : formula) := match f with \n  | Ftrue => 0\n  | Fvar _ => 0\n  | Fand f1 f2 => formula_maxVar_time f1 + formula_maxVar_time f2 + max_time (formula_maxVar f1) (formula_maxVar f2)  \n  | For f1 f2 => formula_maxVar_time f1 + formula_maxVar_time f2 + max_time (formula_maxVar f1) (formula_maxVar f2)\n  | Fneg f => formula_maxVar_time f \n  end + c__formulaMaxVar. \n#[export]\nInstance term_formula_maxVar : computableTime' formula_maxVar (fun f _ => (formula_maxVar_time f, tt)). \nProof. \n  extract. solverec. \n  - now unfold c__formulaMaxVar. \n  - now unfold c__formulaMaxVar. \n  - fold formula_maxVar. unfold c__formulaMaxVar; solverec. \n  - fold formula_maxVar. unfold c__formulaMaxVar; solverec. \n  - unfold c__formulaMaxVar; solverec. \nQed. \n\nDefinition c__formulaMaxVarBound1 := c__formulaMaxVar + c__max2.\nDefinition poly__formulaMaxVar n := (n+1) * (n + 1) * c__formulaMaxVarBound1.\nLemma formula_maxVar_time_bound (f : formula) : formula_maxVar_time f <= poly__formulaMaxVar (size (enc f)). \nProof. \n  induction f; cbn -[Nat.add Nat.mul].\n  - unfold poly__formulaMaxVar, c__formulaMaxVarBound1; nia.\n  - unfold poly__formulaMaxVar, c__formulaMaxVarBound1; nia. \n  - rewrite IHf1, IHf2. unfold max_time. rewrite Nat.le_min_l. \n    rewrite formula_maxVar_enc_bound. setoid_rewrite formula_enc_size at 4. \n    unfold poly__formulaMaxVar, c__formulaMaxVarBound1. leq_crossout. \n  - rewrite IHf1, IHf2. unfold max_time. rewrite Nat.le_min_l. \n    rewrite formula_maxVar_enc_bound. setoid_rewrite formula_enc_size at 4. \n    unfold poly__formulaMaxVar, c__formulaMaxVarBound1. leq_crossout. \n  - rewrite IHf. setoid_rewrite formula_enc_size at 2. unfold poly__formulaMaxVar, c__formulaMaxVarBound1. leq_crossout. \nQed. \nLemma formula_maxVar_poly : monotonic poly__formulaMaxVar /\\ inOPoly poly__formulaMaxVar. \nProof. \n  split; unfold poly__formulaMaxVar; smpl_inO. \nQed. \n\n", "meta": {"author": "uds-psl", "repo": "coq-library-complexity", "sha": "5a996877f16fd6fe16dc5f0c3b933486957869df", "save_path": "github-repos/coq/uds-psl-coq-library-complexity", "path": "github-repos/coq/uds-psl-coq-library-complexity/coq-library-complexity-5a996877f16fd6fe16dc5f0c3b933486957869df/theories/NP/SAT/FSAT/FSAT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749422, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6510049599367627}}
{"text": "(* In this file we explain how to do prove the counter specifications from\n   Section 7.7 of the notes. This involves construction and manipulation of\n   resource algebras, the explanation of which is the focus of this file. We\n   assume the reader has experimented with coq-intro-example-1.v example, and\n   thus we do not explain the features we have explained therein already. *)\n\nFrom iris.program_logic Require Export weakestpre.\nFrom iris.base_logic.lib Require Export invariants.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.heap_lang Require Import proofmode.\nFrom iris.heap_lang Require Import notation lang.\nFrom iris.algebra Require Import numbers.\nFrom iris.prelude Require Import options.\n\nFrom iris.heap_lang.lib Require Import par.\n\n(* The counter module definition. *)\nDefinition read : val := λ: \"c\", !\"c\".\nDefinition incr : val := rec: \"incr\" \"c\" := let: \"n\" := !\"c\" in\n                                            let: \"m\" := #1 + \"n\" in\n                                            if: CAS \"c\" \"n\" \"m\" then #() else \"incr\" \"c\".\n\nDefinition newCounter : val := λ: <>, ref #0.\n\nSection monotone_counter.\n  (* For the first example we will only give the weaker specification, as we did\n     in the notes. In this specification we only know the lower bound on the\n     counter value, since the isCounter predicate is freely duplicable.\n\n     Before we start with the actual verification we will define the resource\n     algebra we shall be using. The Iris library contains all the ingredients\n     needed to compose this particular resource algebra from simpler components,\n     however to illustrate how to define our own we will define it from scratch.\n\n     In the subsequent section we show how to obtain an equivalent resource\n     algebra from the building blocks provided by the Iris Coq library. \n  *)\n\n  (* The carrier of our resource algebra is the set ℕ_{⊥,⊤} × ℕ. NBT (Natural\n     numbers with Top and Bottom) is the first component of this product. We\n     wrap the project into a record to avoid ambiguous type class search. *)\n  Inductive NBT :=\n    Bot : NBT (* Bottom *)\n  | Top : NBT (* Top *)\n  | NBT_incl : nat → NBT. (* Inclusion of natural numbers into our new type. *)\n\n  (* The carrier of our RA. *)\n  Record mcounterRAT := MCounter { mcounter_auth : NBT; mcounter_flag : nat }.\n\n  (* The notion of a resource algebra as used in Iris is more general than the one\n     currently described. It is called a cmra (standing roughly for complete\n     metric resource algebra). For most verification purposes it is not\n     important what that is. It is a step-indexed generalization of the resource\n     algebra we have described in Section 7. The main difference is that the\n     carrier is not simply a set, but comes equipped with a set of equivalence\n     relations indexed by natural numbers (the \"step-indices\").\n\n     The notion we have defined in Section 7 is that of a \"discrete\" CMRA. There\n     is special support in the library for such CMRAs, and that is why in the\n     remainder of this file we will often use, e.g., special lemmas for discrete\n     CMRAs. \n   *)\n\n  (* \n     To tell Coq we wish to use such a discrete CMRA we use the constructor leibnizO.\n     This takes a Coq type and makes it an instance of an OFE (a step-indexed generalization of sets).\n     This is not the place do describe Canonical Structures.\n     A very good introduction is available at https://hal.inria.fr/hal-00816703v1/document \n  *)\n  Canonical Structure mcounterRAC := leibnizO mcounterRAT.\n\n  (* To make the type mcounterRAT into an RA we need an operation. This is\n     defined in the standard way, except we use the typeclass Op so we can reuse\n     a lot of the notation mechanism (we can write x ⋅ y for the operation), and\n     some other infrastucture and generic lemmas. *)\n  Instance mcounterRAop : Op mcounterRAT :=\n    λ '(MCounter x n) '(MCounter y m),\n    match x with\n      Bot => MCounter y (max n m)\n    | _ => match y with\n             Bot => MCounter x (max n m)\n           | _ => MCounter Top (max n m)\n           end\n    end.\n\n  (* The set of valid elements. Valid A is simply abbreviation for A → Prop,\n     i.e., for the set of subsets of A. Importantly Valid is a typeclass, and\n     thus we make our definition an instance of it. This will enable the Coq\n     typeclass search and various interactive proof mode tactics automatically\n     deal with many boring use cases. *)\n  Instance mcounterRAValid : Valid mcounterRAT :=\n    λ x, match x with\n           MCounter Bot _ => True\n         | MCounter (NBT_incl x) m => x ≥ m\n         | _ => False\n         end.\n\n  (* The core of the RA. PCore stands for \"partial core\", and is an abbreviation\n     for a partial function, which in Coq is encoded as a function from A →\n     option A. Again, PCore is a typeclass for better automation support, and\n     thus our definition is an instance. *)\n  Instance mcounterRACore : PCore mcounterRAT :=\n    λ '(MCounter _ n), Some (MCounter Bot n).\n\n  (* We can then package these definitions up into an RA structure, used by the\n     Iris library. *)\n\n  (* We need these auxiliary lemmas in the proof below. \n     We need the type  annotation to guide the type inference. *)\n  Lemma mcounterRA_op_second (x y : NBT) n m :\n    ∃ z, MCounter x n ⋅ MCounter y m = MCounter z (max n m).\n  Proof.\n    destruct x as [], y as []; eexists; unfold op, mcounterRAop; simpl; auto.\n  Qed.\n\n  Lemma mcounterRA_included_aux x y (n m : nat) :\n    MCounter x n ≼ MCounter y m → (n ≤ m)%nat.\n  Proof.\n    intros [[z k] [=H]].\n    revert H.\n    destruct (mcounterRA_op_second x z n k) as [? ->].\n    inversion 1; subst; auto with arith.\n  Qed.\n\n  Lemma mcounterRA_included_frag (n m : nat) :\n    MCounter Bot n ≼ MCounter Bot m ↔ (n ≤ m)%nat.\n  Proof.\n    split.\n    - apply mcounterRA_included_aux.\n    - intros H%Max.max_r; exists (MCounter Bot m); unfold op, mcounterRAop; rewrite H; auto.\n  Qed.\n\n  Lemma mcounterRA_valid x (n : nat): ✓ (MCounter (NBT_incl x) n) ↔ (n ≤ x)%nat.\n  Proof.\n    split; auto.\n  Qed.\n\n  (* An RAMixin is a structure which combines all the parts of an RA into one\n     Coq structure, together with all the properties that the operations and\n     functions satisfy. *)\n  Definition mcounterRA_mixin : RAMixin mcounterRAT.\n  Proof.\n    split; try apply _; try done.\n    - unfold valid, op, mcounterRAop, mcounterRAValid. intros ? ? cx -> ?; exists cx. done.\n    (* The operation is associative. *)\n    - unfold op, mcounterRAop. intros [[]] [[]] [[]]; rewrite !Nat.max_assoc; reflexivity.\n    (* The operation is commutative. *)\n    - unfold op, mcounterRAop. intros [[]] [[]]; rewrite Nat.max_comm; reflexivity.\n    (* Core axioms. *)\n    - unfold pcore, mcounterRACore, op, mcounterRAop; intros [[]] [[]] [=->]; rewrite Max.max_idempotent; auto.\n    - unfold pcore, mcounterRACore, op, mcounterRAop; intros [[]] [[]] [=->]; auto.\n    - unfold pcore, mcounterRACore, op, mcounterRAop. \n      intros [x n] [y m] cx Hleq%mcounterRA_included_aux [=<-].\n      exists (MCounter Bot m); split; first auto.\n      by apply mcounterRA_included_frag.\n    - (* Validity axiom: validity is down-closed with respect to the extension order. *)\n      intros [[]].\n      + reflexivity.\n      + unfold op, mcounterRAop; intros [[]] [].\n      + unfold op, mcounterRAop; intros [[]].\n        * rewrite !mcounterRA_valid. eauto with arith.\n        * intros [].\n        * intros [].\n  Qed.\n\n  (* We finally wrap the type and the above mixin and make the structure\n  available for typeclass search. The discreteR is a wrapper for when our CMRA is\n  \"discrete\" as described above. *)\n  Canonical Structure mcounterRA := discreteR mcounterRAT mcounterRA_mixin.\n\n  (* Some tactics and lemmas only apply for discrete CMRAs (what we called RAs).\n     To be able to use these we need to register our CMRA as a discrete one, to\n     make this information available to typeclass search. *) \n  Instance mcounterRA_cmra_discrete : CmraDiscrete mcounterRA.\n  Proof. apply discrete_cmra_discrete. Qed.\n\n  (* A total CMRA (or RA) is the one where the core operation is a total\n     function, i.e., the core of every element is defined. Some properties and\n     lemmas only apply for such CMRAs, and so we register the fact that our CMRA\n     is of this form.\n   *)\n  Instance mcounterRA_cmra_total : CmraTotal mcounterRA.\n  Proof. intros [[]]; eauto. Qed.\n\n  (* We define some abbreviation. We only define it as notation in this section\n     since the same notation is already defined for the general authoritative RA\n     construction in the Iris Coq library. \n   *)\n  Local Notation \"◯ n\" := (MCounter Bot n%nat) (at level 20).\n  Local Notation \"● m\" := (MCounter (NBT_incl m%nat) 0%nat) (at level 20).\n\n  (* We now prove the three properties we claim were required from the resource\n     algebra in Section 7.7. \n   *)\n  (* CoreId x states that the core of x is x, which is one of the properties we claimed for the\n     fragments. CoreId is a typeclass. *)\n  Instance mcounterRA_frag_core (n : nat): CoreId (◯ n).\n  Proof.\n    rewrite /CoreId; reflexivity.\n  Qed.\n\n  Lemma mcounterRA_valid_auth_frag m n: ✓ (● m ⋅ ◯ n) ↔ (n ≤ m)%nat.\n  Proof.\n    apply mcounterRA_valid.\n  Qed.\n\n  Lemma mcounterRA_update m n: ((● m ⋅ ◯ n) : mcounterRA) ~~> (● (1 + m) ⋅ ◯ (1 + n)).\n  Proof.\n    (* Use the specialized definition of update, since our RA is a nice one. *)\n    apply cmra_discrete_update.\n    intros [[] k].\n    - rewrite /op /cmra_op !mcounterRA_valid; lia.\n    - intros [].\n    - intros [].\n  Qed.\n\n  (* We now need to tell Coq to use our RA as one of the RA's in the instantiation of Iris. *)\n  (* This is achieved via the subG constructor. All of this is boilerplate, so\n     the proofs are trivial, with the tactics provided by the library. *)\n  Class mcounterG Σ := MCounterG { mcounter_inG :> inG Σ mcounterRA }.\n  Definition mcounterΣ : gFunctors := #[GFunctor mcounterRA].\n  \n  Instance subG_mcounterΣ {Σ} : subG mcounterΣ Σ → mcounterG Σ.\n  Proof. solve_inG. Qed.\n\n  (* We can now verify the programs. *)\n  (* We start off as in the previous example, with some boilerplate code. *)\n  Context `{!heapGS Σ, !mcounterG Σ} (N : namespace).\n  Notation iProp := (iProp Σ).\n\n  (* The counter invariant as defined in the notes. The only difference is that\n     we are using the namespace N for the invariant, instead of existentially\n     quantifying the invariant name. *)\n  Definition counter_inv (ℓ : loc) (γ : gname) : iProp := (∃ (m : nat), ℓ ↦ #m ∗ own γ (● m))%I.\n\n  (* the isCounter predicate as in the notes. *)\n  Definition isCounter (ℓ : loc) (n : nat) : iProp :=\n    (∃ γ, own γ (◯ n) ∗ inv N (counter_inv ℓ γ))%I.\n\n  (* isCounter is a persistent predicate. This is needed so we can share it among threads. *)\n  (* We first need an auxiliary lemma, which tells Coq that ownership of fragments is persistent.\n     This follows from the persistently-core axiom of the logic.\n     Instead of proving this as a lemma we make it an instance of the Persistent class.\n     This way Coq will be able to infer automatically whenever it needs the fact\n     that ownership of fragments is persistent.\n   *)\n  Instance ownFrac_persistent γ n: Persistent (own γ (◯ n)).\n  Proof.\n   apply own_core_persistent, _.\n  Qed.\n\n  (* Now the proof of the main counter predicate is simple: Coq's typeclass\n     search can automatically deduce that isCounter is persistent. It knows the\n     closure properties of persistent propositions, e.g., existential\n     quantification over a persistent predicate is persistent, and it knows that\n     invariants are persistent. The final part it needs is that own γ (◯ n) is\n     persistent, and we have just taught it that in the preceding lemma. *)\n  Instance isCounter_persistent ℓ n: Persistent (isCounter ℓ n).\n  Proof.\n    apply _.\n  Qed.\n\n  (* We can now perform the main proofs. They are not very different from the\n     proofs we have done previously. *) \n  Lemma newCounter_spec: {{{ True }}} newCounter #() {{{ v, RET #v; isCounter v 0 }}}.\n  Proof.\n    iIntros (Φ) \"_ HCont\".\n    rewrite /newCounter.\n    wp_lam.\n    (* We allocate ghost state using the rule/lemma own_alloc. Since the\n       conclusion of the rule is under a modality we wrap the application of\n       this lemma with the call to the iMod tactic, which takes care of the\n       bookkeeping, using the primitive rules of the modality. \n       In this case the tactic knows that |==> WP ... implies WP ... and thus removes it from the goal.\n     *)\n    iMod (own_alloc (● 0 ⋅ ◯ 0)) as (γ) \"[HAuth HFrac]\".\n    - apply mcounterRA_valid_auth_frag; auto. (* NOTE: We use the validity property of the RA we have constructed. *)\n    - wp_alloc ℓ as \"Hpt\".\n      (* We now allocate an invariant. *)\n      iMod (inv_alloc N _ (counter_inv ℓ γ) with \"[Hpt HAuth]\") as \"HInv\".\n      + iExists 0%nat; iFrame.\n      + iApply (\"HCont\" with \"[HFrac HInv]\").\n        iExists γ; iFrame.\n  Qed.\n  \n  (* The read method specification. *)\n  Lemma read_spec ℓ n: {{{ isCounter ℓ n }}} read #ℓ {{{ m, RET #m; ⌜n ≤ m⌝%nat }}}.\n  Proof.\n    iIntros (Φ) \"HCounter HCont\".\n    iDestruct \"HCounter\" as (γ) \"[HOwnFrag HInv]\".\n    rewrite /read.\n    wp_lam.\n    iInv N as (m) \">[Hpt HOwnAuth]\" \"HClose\".\n    wp_load.\n    (* NOTE: We use the validity property of the RA we have constructed. From the fact that we own \n             ◯ n and ● m to conclude that n ≤ m. *)\n    iDestruct (own_valid_2 with \"HOwnAuth HOwnFrag\") as %H%mcounterRA_valid_auth_frag. \n    iMod (\"HClose\" with \"[Hpt HOwnAuth]\") as \"_\".\n    { iNext; iExists m; iFrame. }\n    iModIntro.\n    iApply \"HCont\"; done.\n  Qed.\n\n  (* The read method specification. *)\n  Lemma incr_spec ℓ n: {{{ isCounter ℓ n }}} incr #ℓ {{{ RET #(); isCounter ℓ (1 + n)%nat }}}.\n  Proof.\n    iIntros (Φ) \"HCounter HCont\".\n    iDestruct \"HCounter\" as (γ) \"[HOwnFrag #HInv]\".\n    iLöb as \"IH\".\n    rewrite /incr.\n    wp_lam.\n    wp_bind (! _)%E.\n    iInv N as (m) \">[Hpt HOwnAuth]\" \"HClose\".\n    wp_load.\n    iDestruct (@own_valid_2 _ _ _ γ with \"HOwnAuth HOwnFrag\") as %H%mcounterRA_valid_auth_frag.\n    iMod (\"HClose\" with \"[Hpt HOwnAuth]\") as \"_\".\n    { iNext; iExists m; iFrame. }\n    iModIntro.\n    wp_let; wp_op; wp_let.\n    wp_bind (CmpXchg _ _ _)%E.\n    iInv N as (k) \">[Hpt HOwnAuth]\" \"HClose\".\n    destruct (decide (k = m)); subst.\n    + wp_cmpxchg_suc.\n      (* If the CAS succeeds we need to update our ghost state. This is achieved using the own_update rule/lemma.\n         The arguments are the ghost name and the ghost resources x from which and to which we are updating.\n         Finally we need to give up own γ x to get ownership of the new resources.\n         We do this using the \"with ...\" syntax.\n         Again, the conclusion of the update rule is under the update modality,\n         and thus we wrap the application of the lemma with the iMod tactic. *)\n      iMod (own_update γ ((● m ⋅ ◯ n) : mcounterRA) (● (1 + m) ⋅ ◯ (1 + n)) with \"[HOwnFrag HOwnAuth]\") as \"[HOwnAuth HOwnFrag]\".\n      { apply mcounterRA_update. } (* We need the final property of the RA we proved above: the frame preserving update from (● m ⋅ ◯ n) to (● (1 + m) ⋅ ◯ (1 + n)). *)\n      { rewrite own_op; iFrame. }\n      iMod (\"HClose\" with \"[Hpt HOwnAuth]\") as \"_\".\n      { iNext; iExists (1 + m)%nat.\n        rewrite Nat2Z.inj_succ Z.add_1_l; iFrame. }\n      iModIntro; wp_pures; iApply (\"HCont\" with \"[HInv HOwnFrag]\").\n      iExists γ; iFrame \"#\"; iFrame.\n    + wp_cmpxchg_fail; first intros ?; simplify_eq.\n      iMod (\"HClose\" with \"[Hpt HOwnAuth]\") as \"_\".\n      - iExists k; iFrame.\n      - iModIntro. wp_proj. wp_if.\n        iApply (\"IH\" with \"HOwnFrag HCont\"); iFrame.\n  Qed.\nEnd monotone_counter.\n\n(* In the preceding section we spent a lot of time defining our own resource\n   algebra and proving it satisfies all the needed properties. The same patterns\n   appear often in proof development, and thus the iris Coq library provides\n   several building blocks for constructing resource algebras.\n\n   In the following section we repeat the above specification, but with a\n   resource algebra constructed using these building blocks. We will see that\n   this will save us quite a bit of work.\n\n   As we stated in an exercise in the counter modules section of the lecture\n   notes, the resource algebra we constructed above is nothing but Auth(N_max).\n   Auth and N_max are both part of the iris Coq library. They are called authR\n   and max_natUR (standing for authoritative Resource algebra and max nat Unital\n   Resource algebra). *)\n\n(* Auth is defined in iris.algebra.auth. *)\nFrom iris.algebra Require Import auth.\n\n(* The following section is a generic update property of the authoritative construction.\n   In the Iris Coq library there are several update lemmas, using the concept of local updates\n   (notation x ~l~> y, and the definition is called local_update).\n   \n   The two updates in the following section are the same as stated in the exercise in the notes.\n*)\nSection auth_update.\n  Context {U : ucmra}.\n\n  Lemma auth_update_add (x y z : U): ✓ (x ⋅ z) → ● x ⋅ ◯ y ~~> ● (x ⋅ z) ⋅ ◯ (y ⋅ z).\n  Proof.\n    intros ?.\n    (* auth_update is the generic update rule for the auth RA. It reduces a\n       frame preserving update to that of a local update. *)\n    apply auth_update.\n    intros ? mz ? Heq.\n    split.\n    - apply cmra_valid_validN; auto.\n    - simpl in *.\n      rewrite Heq.\n      destruct mz; simpl; auto.\n      rewrite -assoc (comm _ _ z) assoc //.\n  Qed.\n\n  Lemma auth_update_add' (x y z w : U): ✓ (x ⋅ z) → w ≼ z → ● x ⋅ ◯ y ~~> ● (x ⋅ z) ⋅ ◯ (y ⋅ w).\n  Proof.\n    (* The proof of this lemma uses the previous lemma, together with the fact\n       that ~~> is transitive, and the fact that we always have the frame\n       preserving update from a ⋅ b to a. This is proved in cmra_update_op_l in\n       the Coq library.\n    *)\n    intros Hv [? He].\n    etransitivity.\n    { apply (auth_update_add x y z Hv). }\n    rewrite {2}He assoc auth_frag_op assoc.\n    apply cmra_update_op_l.\n  Qed.\nEnd auth_update.\n\nSection monotone_counter'.\n  (* We tell Coq that our Iris instantiation has the following resource\n     algebras. Note that the only diffference from above is that we use authR\n     max_natUR in place of the resource algebra mcounterRA we constructed above. *)\n  Class mcounterG' Σ := MCounterG' { mcounter_inG' :> inG Σ (authR max_natUR)}.\n  Definition mcounterΣ' : gFunctors := #[GFunctor (authR max_natUR)].\n\n  Instance subG_mcounterΣ' {Σ} : subG mcounterΣ' Σ → mcounterG' Σ.\n  Proof. solve_inG. Qed.\n\n  (* We now prove the same three properties we claim were required from the resource\n     algebra in Section 7.7.  *)\n  Instance mcounterRA_frag_core' (n : max_natUR): CoreId (◯ n).\n  Proof.\n    apply _.\n    (* CoreID is a typeclass, so typeclass search can automatically deduce what\n       we want. Concretely, the proof follows by lemmas auth_frag_core_id and\n       max_nat_core_id proved in the Iris Coq library. *)\n  Qed.\n\n  Lemma mcounterRA_valid_auth_frag' (m n : max_natUR): ✓ (● m ⋅ ◯ n) ↔ (max_nat_car n ≤ max_nat_car m)%nat.\n  Proof.\n    (* Use a simplified definition of validity for when the underlying CMRA is discrete, i.e., an RA.\n       The general definition also involves the use of step-indices, which is not needed in our case. *)\n    rewrite auth_both_valid_discrete.\n    split.\n    - intros [? _]; by apply max_nat_included.\n    - intros ?%max_nat_included; done.\n  Qed.\n\n  Lemma max_nat_op_succ m : MaxNat (S m) = MaxNat m ⋅ MaxNat (S m).\n  Proof. rewrite max_nat_op. apply f_equal. lia. Qed.\n\n  Lemma mcounterRA_update' (m n : max_natUR) :\n    ● m ⋅ ◯ n ~~> ● MaxNat (S (max_nat_car m)) ⋅ ◯ MaxNat (S (max_nat_car n)).\n  Proof.\n    destruct m as [m], n as [n]. simpl.\n    rewrite (max_nat_op_succ m) (max_nat_op_succ n).\n    apply cmra_update_valid0. intros ?%cmra_discrete_valid%mcounterRA_valid_auth_frag'.\n    simpl in *. apply auth_update_add'; first reflexivity.\n    exists (MaxNat (S m)). rewrite max_nat_op. apply f_equal. lia.\n  Qed.\n\n  (* We can now verify the programs. *)\n  (* We start off as in the previous example, with some boilerplate code. *)\n  Context `{!heapGS Σ, !mcounterG' Σ} (N : namespace).\n  Notation iProp := (iProp Σ).\n\n  (* The rest of this section is exactly the same as the preceding one. We use\n     the properties of the RA we have proved above. *)\n  Definition counter_inv' (ℓ : loc) (γ : gname) : iProp := (∃ (m : nat), ℓ ↦ #m ∗ own γ (● MaxNat m))%I.\n\n  Definition isCounter' (ℓ : loc) (n : max_natUR) : iProp :=\n    (∃ γ, own γ (◯ n) ∗ inv N (counter_inv' ℓ γ))%I.\n\n  Global Instance isCounter_persistent' ℓ n: Persistent (isCounter' ℓ n).\n  Proof.\n    apply _.\n  Qed.\n\n  Lemma newCounter_spec': {{{ True }}} newCounter #() {{{ v, RET #v; isCounter' v (MaxNat 0) }}}.\n  Proof.\n    iIntros (Φ) \"_ HCont\".\n    rewrite /newCounter.\n    wp_lam.\n    iMod (own_alloc (● MaxNat 0 ⋅ ◯ MaxNat 0)) as (γ) \"[HAuth HFrac]\".\n    - apply mcounterRA_valid_auth_frag'; auto.\n    - wp_alloc ℓ as \"Hpt\".\n      iMod (inv_alloc N _ (counter_inv' ℓ γ) with \"[Hpt HAuth]\") as \"HInv\".\n      + iExists 0%nat; iFrame.\n      + iApply (\"HCont\" with \"[HFrac HInv]\").\n        iExists γ; iFrame.\n  Qed.\n\n  (* The read method specification. *)\n  Lemma read_spec' ℓ n : {{{ isCounter' ℓ (MaxNat n) }}} read #ℓ {{{ m, RET #m; ⌜n ≤ m⌝%nat }}}.\n  Proof.\n    iIntros (Φ) \"HCounter HCont\".\n    iDestruct \"HCounter\" as (γ) \"[HOwnFrag HInv]\".\n    rewrite /read.\n    wp_lam.\n    iInv N as (m) \">[Hpt HOwnAuth]\" \"HClose\".\n    wp_load.\n    iDestruct (@own_valid_2 _ _ _ γ with \"HOwnAuth HOwnFrag\") as %H%mcounterRA_valid_auth_frag'.\n    iMod (\"HClose\" with \"[Hpt HOwnAuth]\") as \"_\".\n    { iNext; iExists m; iFrame. }\n    iModIntro.\n    iApply \"HCont\"; done.\n  Qed.\n\n  (* The read method specification. *)\n  Lemma incr_spec' ℓ n : {{{ isCounter' ℓ (MaxNat n) }}} incr #ℓ {{{ RET #(); isCounter' ℓ (MaxNat (1 + n)) }}}.\n  Proof.\n    iIntros (Φ) \"HCounter HCont\".\n    iDestruct \"HCounter\" as (γ) \"[HOwnFrag #HInv]\".\n    iLöb as \"IH\".\n    rewrite /incr.\n    wp_lam.\n    wp_bind (! _)%E.\n    iInv N as (m) \">[Hpt HOwnAuth]\" \"HClose\".\n    wp_load.\n    iDestruct (@own_valid_2 _ _ _ γ with \"HOwnAuth HOwnFrag\") as %H%mcounterRA_valid_auth_frag'.\n    iMod (\"HClose\" with \"[Hpt HOwnAuth]\") as \"_\".\n    { iNext; iExists m; iFrame. }\n    iModIntro.\n    wp_let; wp_op; wp_let.\n    wp_bind (CmpXchg _ _ _)%E.\n    iInv N as (k) \">[Hpt HOwnAuth]\" \"HClose\".\n    destruct (decide (k = m)); subst.\n    + wp_cmpxchg_suc.\n      iMod (own_update γ (● (MaxNat m) ⋅ ◯ (MaxNat n)) (● (MaxNat (S m)) ⋅ (◯ (MaxNat (S n)))) with \"[HOwnFrag HOwnAuth]\") as \"[HOwnAuth HOwnFrag]\".\n      { apply mcounterRA_update'. }\n      { rewrite own_op; iFrame. }\n      iMod (\"HClose\" with \"[Hpt HOwnAuth]\") as \"_\".\n      { iNext; iExists (1 + m)%nat.\n        rewrite Nat2Z.inj_succ Z.add_1_l; iFrame. }\n      iModIntro; wp_pures; iApply (\"HCont\" with \"[HInv HOwnFrag]\").\n      iExists γ; iFrame \"#\"; iFrame.\n    + wp_cmpxchg_fail; first intros ?; simplify_eq.\n      iMod (\"HClose\" with \"[Hpt HOwnAuth]\") as \"_\".\n      - iExists k; iFrame.\n      - iModIntro. wp_proj. wp_if.\n        iApply (\"IH\" with \"HOwnFrag HCont\"); iFrame.\n  Qed.\nEnd monotone_counter'.\n\n(* Counter with contributions. *)\n(* As a final example in this example file we give the more precise specification to the counter. *) \n(* As explained in the lecture notes we need a different resource algebra: the\n   authoritative resource algebra on the product of the RA of fractions and the\n   RA of natural numbers, with an added unit.\n\n   The combination of the RA of fractions and the authoritative RA in this way\n   is fairly common, and so the Iris Coq library provides frac_authR (CM)RA. *)\n\nFrom iris.algebra Require Import frac_auth.\n\nSection ccounter.\n  (* We start as we did before, telling Coq what we assume from the Iris instantiation. *)\n  (* Note that now we use natR as the underlying resource algebra. This is the\n     RA of natural numbers with addition as the operation. *)\n  Class ccounterG Σ := CCounterG { ccounter_inG :> inG Σ (frac_authR natR) }.\n  Definition ccounterΣ : gFunctors := #[GFunctor (frac_authR natR)].\n\n  Instance subG_ccounterΣ {Σ} : subG ccounterΣ Σ → ccounterG Σ.\n  Proof. solve_inG. Qed.\n\n\n  (* The first thing we are going to prove are the properties of the resource\n     algebra, specialized to our use case. These are listed in the exercise in\n     the relevant section of the lecture notes. *)\n  (* We are using some new notation. The frac_auth library defines the notation\n     ◯F{q} n to mean ◯ (q, n) as we used in the lecture notes. Further, ●F m\n     means ● (1, m) and ◯F n means ◯ (1, n). *)\n  Lemma ccounterRA_valid (m n : natR) (q : frac): ✓ (●F m ⋅ ◯F{q} n) → (n ≤ m)%nat.\n  Proof.\n    intros ?.\n    (* This property follows directly from the generic properties of the relevant RAs. *)\n    apply nat_included. by apply: (frac_auth_included_total q).\n  Qed.\n\n  Lemma ccounterRA_valid_full (m n : natR): ✓ (●F m ⋅ ◯F n) → (n = m)%nat.\n  Proof.\n    by intros ?%frac_auth_agree.\n  Qed.\n\n  Lemma ccounterRA_update (m n : natR) (q : frac): (●F m ⋅ ◯F{q} n) ~~> (●F (S m) ⋅ ◯F{q} (S n)).\n  Proof.\n    apply frac_auth_update, (nat_local_update _ _ (S _) (S _)).\n    lia.\n  Qed.\n\n  (* We have all the properties of the RAs needed and thus we can proceed with\n     the proof, which proceeds largely as before, modulo the changes in\n     invariants.\n\n     There is one important difference in the definition of is_ccounter. The\n     ghost name γ is not hidden. This is because now is_ccounter is not\n     persistent, and to share it we have the is_ccounter_op lemma, which would\n     not hold if we were to existentially quantify γ as we did in the previous\n     examples.\n  *)\n  Context `{!heapGS Σ, !ccounterG Σ} (N : namespace).\n\n  Definition ccounter_inv (γ : gname) (l : loc) : iProp Σ :=\n    (∃ n, own γ (●F n) ∗ l ↦ #n)%I.\n\n  Definition is_ccounter (γ : gname) (l : loc) (q : frac) (n : natR) : iProp Σ :=\n    (own γ (◯F{q} n) ∗ inv N (ccounter_inv γ l))%I.\n\n  (** The main proofs. *)\n\n  (* As explained in the notes the is_ccounter predicate for this specificatin is not persistent.\n     However it is still shareable in the following restricted way.\n   *)\n  Lemma is_ccounter_op γ ℓ q1 q2 (n1 n2 : nat) :\n    is_ccounter γ ℓ (q1 + q2) (n1 + n2)%nat ⊣⊢ is_ccounter γ ℓ q1 n1 ∗ is_ccounter γ ℓ q2 n2.\n  Proof.\n    apply bi.equiv_entails; split; rewrite /is_ccounter frac_auth_frag_op own_op.\n    - iIntros \"[? #?]\".\n      iFrame \"#\"; iFrame.\n    - iIntros \"[[? #?] [? _]]\".\n      iFrame \"#\"; iFrame.\n  Qed.\n\n  Lemma newcounter_contrib_spec (R : iProp Σ) :\n    {{{ True }}}\n        newCounter #()\n    {{{ γ ℓ, RET #ℓ; is_ccounter γ ℓ 1 0%nat }}}.\n  Proof.\n    iIntros (Φ) \"_ HΦ\". rewrite /newCounter /=. wp_lam. wp_alloc ℓ as \"Hpt\".\n    iMod (own_alloc (●F O%nat ⋅ ◯F 0%nat)) as (γ) \"[Hγ Hγ']\"; first by apply auth_both_valid_discrete.\n    iMod (inv_alloc N _ (ccounter_inv γ ℓ) with \"[Hpt Hγ]\").\n    { iNext. iExists 0%nat. by iFrame. }\n    iModIntro. iApply \"HΦ\". rewrite /is_ccounter; eauto.\n  Qed.\n\n  Lemma incr_contrib_spec γ ℓ q n :\n    {{{ is_ccounter γ ℓ q n  }}}\n        incr #ℓ\n    {{{ RET #(); is_ccounter γ ℓ q (S n) }}}.\n  Proof.\n    iIntros (Φ) \"[Hown #Hinv] HΦ\". iLöb as \"IH\". wp_rec.\n    wp_bind (! _)%E. iInv N as (c) \">[Hγ Hpt]\" \"Hclose\".\n    wp_load. iMod (\"Hclose\" with \"[Hpt Hγ]\") as \"_\"; [iNext; iExists c; by iFrame|].\n    iModIntro. wp_let. wp_op. wp_let.\n    wp_bind (CmpXchg _ _ _). iInv N as (c') \">[Hγ Hpt]\" \"Hclose\".\n    destruct (decide (c' = c)) as [->|].\n    - iMod (own_update_2 with \"Hγ Hown\") as \"[Hγ Hown]\".\n      { apply ccounterRA_update. } (* We use the update lemma for our RA. *)\n      wp_cmpxchg_suc. iMod (\"Hclose\" with \"[Hpt Hγ]\") as \"_\".\n      { iNext. iExists (S c). rewrite Nat2Z.inj_succ Z.add_1_l. by iFrame. }\n      iModIntro. wp_pures. iApply \"HΦ\". by iFrame \"Hinv\".\n    - wp_cmpxchg_fail; first (by intros [= ?%Nat2Z.inj]).\n      iMod (\"Hclose\" with \"[Hpt Hγ]\") as \"_\"; [iNext; iExists c'; by iFrame|].\n      iModIntro. wp_pures. by iApply (\"IH\" with \"[Hown] [HΦ]\"); auto.\n  Qed.\n\n  Lemma read_contrib_spec γ ℓ q n :\n    {{{ is_ccounter γ ℓ q n }}}\n        read #ℓ\n    {{{ c, RET #c; ⌜n ≤ c⌝%nat ∧ is_ccounter γ ℓ q n }}}.\n  Proof.\n    iIntros (Φ) \"[Hown #Hinv] HΦ\".\n    rewrite /read /=. wp_lam. iInv N as (c) \">[Hγ Hpt]\" \"Hclose\". wp_load.\n    iDestruct (own_valid_2 with \"Hγ Hown\") as % ?%ccounterRA_valid. (* We use the validity property of our RA. *)\n    iMod (\"Hclose\" with \"[Hpt Hγ]\") as \"_\"; [iNext; iExists c; by iFrame|].\n    iApply (\"HΦ\" with \"[-]\"); rewrite /is_ccounter; eauto.\n  Qed.\n\n  Lemma read_contrib_spec_1 γ ℓ n :\n    {{{ is_ccounter γ ℓ 1 n }}} read #ℓ\n    {{{ m, RET #m; ⌜m = n⌝ ∗ is_ccounter γ ℓ 1 m }}}.\n  Proof.\n    iIntros (Φ) \"[Hown #Hinv] HΦ\".\n    rewrite /read /=. wp_lam. iInv N as (c) \">[Hγ Hpt]\" \"Hclose\". wp_load.\n    iDestruct (own_valid_2 with \"Hγ Hown\") as % <-%ccounterRA_valid_full. (* We use the validity property of our RA. *)\n    iMod (\"Hclose\" with \"[Hpt Hγ]\") as \"_\"; [iNext; iExists n; by iFrame|].\n    iApply \"HΦ\"; iModIntro. iFrame \"Hown #\"; done.\n  Qed.\nEnd ccounter.\n", "meta": {"author": "pavel-ivanov-rnd", "repo": "iris-heaplang-experiments", "sha": "a283a53fe994672f7a6dbdaefa0d4eedd044b733", "save_path": "github-repos/coq/pavel-ivanov-rnd-iris-heaplang-experiments", "path": "github-repos/coq/pavel-ivanov-rnd-iris-heaplang-experiments/iris-heaplang-experiments-a283a53fe994672f7a6dbdaefa0d4eedd044b733/theories/lecture_notes/coq_intro_example_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439707, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6510037409756625}}
{"text": "(*File containing lists and poly examples*)\n\n(** Before getting started, we need to import all of our\n    definitions from the previous chapter: *)\n\nFrom LF Require Export Basics.\nModule MyLists.\n\nInductive natprod : Type :=\n| pair (n1 n2 : nat). \n\nNotation \"( x , y )\" := (pair x y).\n\nDefinition minus'' (p: natprod) : nat :=\n  match p with\n  | (x, y) => x-y\n  end.\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 length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(*Definition bag := natlist.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | h::t => match (h =? v) with\n                | true => 1+(count v t)\n                | false => (count v t)\n                end\n  end. \n*)\n\nInductive id : Type :=\n  | Id (n : nat).\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 nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42  (* arbitrary! *)\n  | a :: l' => match n =? O with\n               | true => a\n               | false => nth_bad l' (pred n)\n               end\n  end.\n\nInductive natoption : Type :=\n  | Some (n : nat)\n  | None.\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match n =? O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\n(*Examples for reasoning about lists*)\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\n(*Example 1: simpl*)\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. simpl. reflexivity. Qed.\n\n(*Example 2: destruct*)\nDefinition pred (n : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => n'\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\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    simpl. reflexivity.\n  - (* l = cons n l' *)\n    simpl. reflexivity.  Qed.\n\n(*Example 3: induction*)\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    simpl. reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\nEnd MyLists.\n(**********************Polymorphism******************************)\n\nModule MyPoly.\nExport MyLists.\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\n(*Check list.\n(* ===> list : Type -> Type *)*)\n\nCheck nil.\n\n(*Type Annotation Inference*)\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\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(* ===> forall X : Type, X -> nat -> list X *)\nCheck repeat.\n(* ===> forall X : Type, X -> nat -> list X *)\n\n(*Type Argument Inference*)\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n(*Implict Arguments*)\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\nCheck nil.\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\n(** Now lists can be written just the way we'd hope: *)\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\n\nDefinition list123''' := [1; 2; 3].\n\n(*Polymorphism Pairs*)\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\n\n(*Note: Module MyPoly is need, as constructor [pair] has used in natprod*)\n\nArguments pair {X} {Y} _ _.\n\nNotation \"( x , y )\" := (pair x y).\nNotation \"X * Y\" := (prod X Y) : type_scope.\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\nFail Definition mynil : list := nil.\n\nCheck nil.\n\nDefinition mynil : list nat := nil.\nCheck mynil.\nDefinition mynil' := @nil nat.\nCheck mynil'.\n\n(*Polymorphic Options*)\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\n\nArguments Some {X} _.\nArguments None {X}.\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l  with\n  | nil => None\n  | a::l' => Some a\n  end.\n\n(*High-order functions*)\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\n(*Anonymous Functions*)\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  (length l) =? 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\nExample test_filter2':\n    filter (fun l => (length l) =? 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(*Functions That Construct Functions*)\nDefinition constfun {X: Type} x : nat->X :=\n  fun (k:nat) => x.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n\n(*************************Example: Map*****************************)\n\n(*Input f, l=[n1,n2......]   output: [f n1, f n2, ......]*)\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. simpl. 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 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\n(**)\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n(**)\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.\n  induction l as [| h t Ht].\n  - (* l = [] *)\n    simpl. reflexivity.\n  - (* l = h t *)\n    simpl. rewrite <- Ht. simpl. reflexivity.\nQed.\n(**)\n\nTheorem map_app_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 as [| h1 t1 IHt1].\n  - (* l1 = [] *)\n    simpl. reflexivity.\n  - (* l1 = h1 t1 *)\n    simpl. rewrite -> IHt1. reflexivity.\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros X Y f.\n  induction l as [| h t Ht].\n  - (* l = [] *)\n    simpl. reflexivity.\n  - (* l = h t *)\n    simpl.  rewrite <- Ht. rewrite -> map_app_distr. simpl. reflexivity.\nQed.\n\nEnd MyPoly.", "meta": {"author": "hengxin", "repo": "coq-rock", "sha": "e28ae5e40317ffea434c8f3d84cd371c1c38afe6", "save_path": "github-repos/coq/hengxin-coq-rock", "path": "github-repos/coq/hengxin-coq-rock/coq-rock-e28ae5e40317ffea434c8f3d84cd371c1c38afe6/seminar/reports/1-20190516-Lists&Poly-XueJiang/ListPoly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.6510037349335982}}
{"text": "Require Export RTopology.\nRequire Export SeparatednessAxioms.\n\nLocal Unset Standard Proposition Elimination Names.\n\n(* This proof of the Tietze extension theorem is heavily based on\n   the proof described on planetmath.org. *)\n\nSection Tietze_extension_construction.\n\nVariable X:TopologicalSpace.\nVariable F:Ensemble (point_set X).\nHypothesis F_closed: closed F.\nVariable f:point_set (SubspaceTopology F) -> point_set RTop.\nHypothesis f_continuous: continuous f.\nHypothesis f_bound: forall x:point_set (SubspaceTopology F), -1 <= f x <= 1.\nHypothesis X_nonempty: inhabited (point_set X).\n\n\nVariable Urysohns_lemma_function: forall F G:Ensemble (point_set X),\n  closed F -> closed G -> Intersection F G = Empty_set ->\n  { f:point_set X -> point_set RTop |\n    continuous f /\\ (forall x:point_set X, 0 <= f x <= 1) /\\\n    (forall x:point_set X, In F x -> f x = 0) /\\\n    (forall x:point_set X, In G x -> f x = 1)\n  }.\n\n\nLemma subspace_inc_takes_closed_to_closed:\n  forall G:Ensemble (point_set (SubspaceTopology F)),\n  closed G -> closed (Im G (subspace_inc F)).\nProof.\nintros.\ndestruct (subspace_topology_topology _ _ _ H) as [U []].\nreplace (Im G (subspace_inc F)) with (Intersection F (Complement U)).\napply closed_intersection2; trivial.\nred; rewrite Complement_Complement; trivial.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H2.\nexists (exist _ x H2); trivial.\napply NNPP; intro.\nchange (In (Complement G) (exist (In F) x H2)) in H4.\nrewrite H1 in H4.\ndestruct H4.\nsimpl in H4.\ncontradiction H3.\n\ndestruct H2 as [[y]].\nrewrite H3; clear y0 H3.\nconstructor.\ntrivial.\nintro.\nabsurd (In (Complement G) (exist (fun x => In F x) y i)).\nintro.\ncontradiction H4.\nrewrite H1.\nconstructor.\ntrivial.\nQed.\n\nLemma Rle_order: order Rle.\nProof.\nconstructor.\nred; intros; apply Rle_refl.\nred; intros; eapply Rle_trans; [ apply H | apply H0 ].\nred; intros; apply Rle_antisym; trivial.\nQed.\n\nSection extension_approximation.\n\nVariable f0:point_set (SubspaceTopology F) -> point_set RTop.\nHypothesis f0_cont: continuous f0.\nHypothesis f0_bound: forall x:point_set (SubspaceTopology F), -1 <= f0 x <= 1.\n\nDefinition extension_approximation: point_set X -> point_set RTop.\nrefine (\n  let F0:=Im [ x:point_set (SubspaceTopology F) | f0 x <= -1/3 ] (subspace_inc F) in\n  let G0:=Im [ x:point_set (SubspaceTopology F) | f0 x >= 1/3 ] (subspace_inc F) in\n  let g:=proj1_sig (Urysohns_lemma_function F0 G0 _ _ _) in\n  fun x:point_set X => -1/3 + 2/3 * g x).\napply subspace_inc_takes_closed_to_closed.\nreplace ([ x:point_set (SubspaceTopology F) | f0 x <= -1/3 ]) with\n  (inverse_image f0 [ y:point_set RTop | y <= -1/3 ]).\nred.\nrewrite <- inverse_image_complement.\napply f0_cont.\napply lower_closed_interval_closed.\napply Rle_order.\nintros.\ndestruct (total_order_T x y) as [[|]|]; auto with real.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H as [[]]; constructor; trivial.\ndestruct H; constructor; constructor; trivial.\napply subspace_inc_takes_closed_to_closed.\nreplace ([ x:point_set (SubspaceTopology F) | f0 x >= 1/3 ]) with\n  (inverse_image f0 [ y:point_set RTop | 1/3 <= y ]).\nred.\nrewrite <- inverse_image_complement.\napply f0_cont.\napply upper_closed_interval_closed.\napply Rle_order.\nintros; destruct (total_order_T x y) as [[|]|]; auto with real.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H as [[]]; constructor; auto with real.\ndestruct H; constructor; constructor; auto with real.\napply Extensionality_Ensembles; split; auto with sets; red; intros.\ndestruct H.\ndestruct H as [[y] []].\nsimpl in H1.\ndestruct H0 as [[z] []].\nsimpl in H2.\ndestruct H1; destruct H2.\ndestruct (proof_irrelevance _ i i0).\nRequire Import Fourier.\nfourier.\nDefined.\n\nLemma extension_approximation_bound: forall x:point_set X,\n  -1/3 <= extension_approximation x <= 1/3.\nProof.\nintros.\nunfold extension_approximation.\ndestruct Urysohns_lemma_function as [g].\nsimpl.\ndestruct a as [? [? []]].\ndestruct (H0 x).\nsplit; fourier.\nQed.\n\nLemma extension_approximation_diff_bound:\n  forall x:point_set (SubspaceTopology F),\n  -2/3 <= f0 x - extension_approximation (subspace_inc F x) <= 2/3.\nProof.\nintros.\nunfold extension_approximation; destruct Urysohns_lemma_function as\n  [g [? [? []]]]; simpl.\ndestruct (f0_bound x).\ndestruct (Rle_or_lt (f0 x) (-1/3)).\nreplace (g (subspace_inc F x)) with 0.\nsplit; fourier.\nsymmetry; apply e.\neconstructor; trivial.\nconstructor; trivial.\n\ndestruct (Rle_or_lt (1/3) (f0 x)).\nreplace (g (subspace_inc F x)) with 1.\nsplit; fourier.\nsymmetry; apply e0.\neconstructor; trivial.\nconstructor; auto with real.\n\ndestruct (a (subspace_inc F x)).\nsplit; fourier.\nQed.\n\nLemma extension_approximation_continuous:\n  continuous extension_approximation.\nProof.\nunfold extension_approximation; destruct Urysohns_lemma_function as\n  [g [? [? []]]]; simpl.\napply pointwise_continuity; intros.\nRequire Import RFuncContinuity.\napply sum_continuous.\napply continuous_func_continuous_everywhere; apply continuous_constant.\napply const_multiple_continuous.\napply continuous_func_continuous_everywhere; trivial.\nQed.\n\nEnd extension_approximation.\n\nLemma missing_pow_mult: forall (x y:R) (n:nat),\n  (x*y)^n = x^n * y^n.\nProof.\ninduction n.\nsimpl; ring.\nsimpl.\nrewrite IHn; ring.\nQed.\n\nDefinition extension_approximation_seq: forall n:nat,\n  { g0:point_set X -> point_set RTop |\n    continuous g0 /\\\n    (forall x:point_set X, -1 + (2/3)^n <= g0 x <= 1 - (2/3)^n) /\\\n    (forall x:point_set (SubspaceTopology F),\n      -(2/3)^n <= f x - g0 (subspace_inc F x) <= (2/3)^n) }.\nsimple refine (fix g (n:nat) {struct n} := match n return\n  { g0:point_set X -> point_set RTop |\n    continuous g0 /\\\n    (forall x:point_set X, -1 + (2/3)^n <= g0 x <= 1 - (2/3)^n) /\\\n    (forall x:point_set (SubspaceTopology F),\n      -(2/3)^n <= f x - g0 (subspace_inc F x) <= (2/3)^n) } with\n| O => exist _ (fun _ => 0) _\n| S m => match g m with\n         | exist gm y =>\n         let H := _ in\n         let approx := extension_approximation\n                       (fun x:point_set (SubspaceTopology F) =>\n                       (3/2)^m * (f x - gm (subspace_inc F x))) H in\n         exist _ (fun x:point_set X => gm x + (2/3)^m * approx x) _\n         end\nend); clear g; [ | | clearbody H ].\nsimpl.\nsplit.\napply continuous_constant.\nsplit.\nintros; split; ring_simplify; auto with real.\nintros.\ndestruct (f_bound x).\nsplit; fourier.\napply pointwise_continuity; intros.\napply const_multiple_continuous.\napply diff_continuous.\napply continuous_func_continuous_everywhere; trivial.\napply continuous_composition_at.\ndestruct y.\napply continuous_func_continuous_everywhere; trivial.\napply continuous_func_continuous_everywhere; apply subspace_inc_continuous.\n\nassert (forall x:point_set (SubspaceTopology F),\n  -1 <= (3/2)^m * (f x - gm (subspace_inc F x)) <= 1).\nintros.\ndestruct y.\ndestruct H1.\ndestruct (H2 x).\nassert ((3/2)^m * (2/3)^m = 1).\nrewrite <- missing_pow_mult.\nreplace (3/2*(2/3)) with 1 by field.\napply pow1.\nreplace (-1) with ((3/2)^m * (- (2/3)^m)).\npattern 1 at 21; replace 1 with ((3/2)^m * (2/3)^m).\nassert (0 <= (3/2)^m).\napply pow_le.\nfourier.\nsplit; apply Rmult_le_compat_l; trivial.\nreplace ((3/2)^m * -(2/3)^m) with (- ((3/2)^m * (2/3)^m)) by ring.\nf_equal; trivial.\n\nassert (forall x:point_set X, -1/3 <= approx x <= 1/3).\napply extension_approximation_bound.\nassert (forall x:point_set (SubspaceTopology F),\n  -2/3 <= (3/2)^m * (f x - gm (subspace_inc F x)) -\n          approx (subspace_inc F x) <= 2/3).\napply extension_approximation_diff_bound; trivial.\ndestruct y as [? []].\nsplit.\napply pointwise_continuity; intros.\napply sum_continuous.\napply continuous_func_continuous_everywhere; trivial.\napply const_multiple_continuous.\napply continuous_func_continuous_everywhere.\napply extension_approximation_continuous.\n\nsplit; intros.\ndestruct (H4 x).\nsimpl.\ndestruct (H1 x).\nassert (0 <= (2/3)^m).\napply pow_le; fourier.\nassert ((2/3)^m * (-1/3) <= (2/3)^m * approx x <= (2/3)^m * (1/3)).\nsplit; apply Rmult_le_compat_l; trivial.\ndestruct H11.\nsplit; fourier.\n\nsimpl.\nreplace (-(2/3*(2/3)^m)) with ((2/3)^m * (-2/3)) by field.\nreplace (2/3*(2/3)^m) with ((2/3)^m * (2/3)) by ring.\nreplace (f x - (gm (subspace_inc F x) + (2/3)^m * approx (subspace_inc F x)))\n  with ((2/3)^m * ((3/2)^m * (f x - gm (subspace_inc F x)) -\n                   approx (subspace_inc F x))).\nassert (0 <= (2/3)^m).\napply pow_le; fourier.\ndestruct (H2 x).\nsplit; apply Rmult_le_compat_l; trivial.\nring_simplify.\nreplace ((2/3)^m*(3/2)^m) with 1.\nring.\nrewrite <- missing_pow_mult.\nreplace (2/3*(3/2)) with 1 by field.\nsymmetry; apply pow1.\nDefined.\n\nLemma extension_approximation_seq_diff: forall (n:nat) (x:point_set X),\n  -(1/3 * (2/3)^n) <= proj1_sig (extension_approximation_seq (S n)) x -\n                      proj1_sig (extension_approximation_seq n) x\n                   <= 1/3*(2/3)^n.\nProof.\nintros.\nsimpl extension_approximation_seq.\ndestruct extension_approximation_seq; simpl.\nmatch goal with |- context [extension_approximation ?A ?B x] =>\n  cut (-1/3 <= extension_approximation A B x <= 1/3);\n  [ generalize (extension_approximation A B x) |\n    apply extension_approximation_bound ] end.\nintros.\nassert (0 <= (2/3)^n).\napply pow_le; fourier.\nreplace (-(1/3*(2/3)^n)) with ((2/3)^n*(-1/3)) by field.\nreplace (1/3*(2/3)^n) with ((2/3)^n*(1/3)) by ring.\nreplace (x0 x + (2/3)^n*p - x0 x) with ((2/3)^n*p) by ring.\ndestruct H.\nsplit; apply Rmult_le_compat_l; trivial.\nQed.\n\n(* now we've gotten what we need from the concrete definition, make\n   it opaque so it doesn't slow down searches in the future *)\nGlobal Opaque extension_approximation_seq.\nOpaque extension_approximation_seq.\n\nLemma Rle_R1_pow: forall (x:R) (m n:nat), 0 <= x <= 1 -> (m <= n)%nat ->\n  x^n <= x^m.\nProof.\ninduction 2.\nauto with real.\nsimpl.\nreplace (x^m) with (1*x^m) by auto with real.\ndestruct H.\napply Rmult_le_compat; trivial.\napply pow_le; trivial.\nQed.\n\nLemma extension_approximation_seq_cauchy_aux:\n  forall (m n:nat) (x:point_set X),\n  Rabs (proj1_sig (extension_approximation_seq m) x -\n        proj1_sig (extension_approximation_seq n) x) <=\n  Rabs ((2/3)^m - (2/3)^n).\nProof.\ncut (forall (m n:nat) (x:point_set X), (m <= n)%nat ->\n  Rabs (proj1_sig (extension_approximation_seq m) x -\n        proj1_sig (extension_approximation_seq n) x) <=\n  (2/3)^m - (2/3)^n).\nintros.\ndestruct (le_or_lt m n).\nrewrite (Rabs_right ((2/3)^m - (2/3)^n)).\napply H; trivial.\napply Rge_minus.\ncut ((2/3)^n <= (2/3)^m); auto with real.\napply Rle_R1_pow; trivial.\nsplit; fourier.\napply lt_le_weak in H0.\nrewrite (Rabs_left1 ((2/3)^m - (2/3)^n)).\nreplace (- ((2/3)^m - (2/3)^n)) with ((2/3)^n - (2/3)^m) by ring.\nrewrite Rabs_minus_sym.\napply H; trivial.\napply Rle_minus.\napply Rle_R1_pow; trivial.\nsplit; fourier.\n\ninduction 1.\nrepeat match goal with |- context [ ?y - ?y ] =>\n  replace (y-y) with 0 by ring end.\nrewrite Rabs_R0; apply Rle_refl.\n\nsimpl pow.\napply Rle_trans with\n  (Rabs (proj1_sig (extension_approximation_seq m) x -\n         proj1_sig (extension_approximation_seq m0) x) +\n   Rabs (proj1_sig (extension_approximation_seq m0) x -\n         proj1_sig (extension_approximation_seq (S m0)) x)).\nrewrite Rplus_comm.\napply R_metric_is_metric.\npose proof (extension_approximation_seq_diff m0 x).\nassert (Rabs (proj1_sig (extension_approximation_seq m0) x -\n              proj1_sig (extension_approximation_seq (S m0)) x) <=\n        1/3 * (2/3)^m0).\ndestruct H0.\nunfold Rabs.\ndestruct Rcase_abs; fourier.\nfourier.\nQed.\n\nRequire Import UniformTopology.\n\nDefinition convert_approx_to_uniform_space:\n  nat -> uniform_space R_metric (fun _:point_set X => 0).\nrefine (fun n:nat => exist _ (proj1_sig (extension_approximation_seq n)) _).\ndestruct extension_approximation_seq as [g [? []]].\nsimpl.\nunfold R_metric.\nexists (1 - (2/3)^n).\nred; intros.\ndestruct H.\nrewrite H0; clear y H0.\ndestruct (a x).\nunfold Rabs; destruct Rcase_abs; fourier.\nDefined.\n\nLemma extension_approximation_seq_cauchy:\n  cauchy (uniform_metric R_metric (fun _:point_set X => 0)\n          R_metric_is_metric X_nonempty)\n    convert_approx_to_uniform_space.\nProof.\nred; intros.\nassert (Rabs (2/3) < 1).\nrewrite Rabs_right; fourier.\nassert (0 < eps/2) by fourier.\ndestruct (pow_lt_1_zero (2/3) H0 (eps/2) H1) as [N].\nexists N.\nintros.\napply Rle_lt_trans with (Rabs ((2/3)^m - (2/3)^n)).\nunfold uniform_metric; unfold convert_approx_to_uniform_space;\n  destruct sup; simpl.\napply i.\nred; intros.\ndestruct H5.\nrewrite H6; clear y H6.\nrewrite metric_sym.\napply extension_approximation_seq_cauchy_aux.\nexact R_metric_is_metric.\napply Rle_lt_trans with (Rabs ((2/3)^m) + Rabs((2/3)^n)).\nrewrite <- (Rabs_Ropp ((2/3)^n)).\nunfold Rminus.\napply Rabs_triang.\nreplace eps with (eps/2 + eps/2) by field.\napply Rplus_lt_compat; apply H2; trivial.\nQed.\n\nDefinition Tietze_extension_func : point_set X -> point_set RTop.\nRequire Import Description.\nrefine (proj1_sig (proj1_sig (constructive_definite_description\n  (fun f:point_set (UniformTopology R_metric (fun _:point_set X => 0)\n                    R_metric_is_metric X_nonempty) =>\n  net_limit convert_approx_to_uniform_space f\n    (I:=nat_DS) (X:=UniformTopology R_metric (fun _:point_set X => 0)\n                    R_metric_is_metric X_nonempty)) _))).\napply -> unique_existence; split.\nassert (complete (uniform_metric R_metric (fun _:point_set X => 0)\n                    R_metric_is_metric X_nonempty)\n          (uniform_metric_is_metric _ _ _ _ _ _)).\napply uniform_metric_complete.\nexact R_metric_complete.\napply H.\nexact extension_approximation_seq_cauchy.\napply Hausdorff_impl_net_limit_unique.\napply T3_sep_impl_Hausdorff.\napply normal_sep_impl_T3_sep.\napply metrizable_impl_normal_sep.\nexists (uniform_metric R_metric (fun _:point_set X => 0)\n          R_metric_is_metric X_nonempty).\napply (uniform_metric_is_metric _ _ R_metric (fun _:point_set X => 0)\n          R_metric_is_metric X_nonempty).\napply MetricTopology_metrizable.\nDefined.\n\nLemma Tietze_extension_func_bound: forall x:point_set X,\n  -1 <= Tietze_extension_func x <= 1.\nProof.\nintros.\ncut (Rabs (Tietze_extension_func x) <= 1).\nintros.\nunfold Rabs in H; destruct Rcase_abs in H;\n  split; fourier.\n\nunfold Tietze_extension_func;\n  destruct constructive_definite_description as [[g]].\nsimpl.\nassert (bound (Im Full_set (fun x:point_set X => R_metric 0 0))).\nexists 0.\nred; intros.\ndestruct H.\nright.\nrewrite H0; apply R_metric_is_metric.\napply Rle_trans with (uniform_metric _ _ R_metric_is_metric X_nonempty\n                    (exist _ (fun _:point_set X => 0) H)\n                    (exist _ g b)).\nunfold uniform_metric; simpl; destruct sup; simpl.\napply i.\nexists x.\nconstructor.\nunfold R_metric; f_equal; auto with real.\n\napply lt_plus_epsilon_le; intros.\nunshelve refine (let H1:=metric_space_net_limit_converse _ _ _ _ _ _ n eps H0 in _); [ | | clearbody H1 ]; shelve_unifiable.\napply MetricTopology_metrizable.\ndestruct H1 as [N].\nrefine (Rle_lt_trans _ _ _\n  (triangle_inequality _ _ _ _ (convert_approx_to_uniform_space N) _) _).\napply uniform_metric_is_metric.\napply Rplus_lt_compat.\napply Rle_lt_trans with (1 - (2/3)^N).\nunfold uniform_metric; simpl; destruct sup; simpl.\napply i.\nred; intros.\ndestruct H2.\nrewrite H3; clear y H3.\nunfold R_metric.\ndestruct extension_approximation_seq as [h [? []]].\ndestruct (a x1).\nsimpl.\nunfold Rabs; destruct Rcase_abs; fourier.\nassert ((2/3)^N > 0).\napply pow_lt; fourier.\nfourier.\nrewrite metric_sym; try apply uniform_metric_is_metric.\napply H1.\nunfold DS_ord; constructor.\nQed.\n\nLemma Tietze_extension_func_is_extension:\n  forall x:point_set (SubspaceTopology F),\n  Tietze_extension_func (subspace_inc F x) = f x.\nProof.\nintros.\napply R_metric_is_metric.\napply Rle_antisym; try (apply Rge_le; apply R_metric_is_metric).\napply lt_plus_epsilon_le; intros.\nunfold Tietze_extension_func;\n  destruct constructive_definite_description as [[g]]; simpl.\nassert (eps/2 > 0) by fourier.\nunshelve refine (let H1:=metric_space_net_limit_converse _ _ _ _ _ _ n (eps/2) H0\n          in _); [ | | clearbody H1 ]; shelve_unifiable.\napply MetricTopology_metrizable.\ndestruct H1 as [N1].\nassert (Rabs (2/3) < 1).\nrewrite Rabs_right; fourier.\n\ndestruct (pow_lt_1_zero (2/3) H2 (eps/2) H0) as [N2].\nRequire Import Max.\npose (N := max N1 N2).\napply Rle_lt_trans with (R_metric (g (subspace_inc F x))\n          (proj1_sig (extension_approximation_seq N) (subspace_inc F x)) +\n  R_metric (proj1_sig (extension_approximation_seq N) (subspace_inc F x))\n    (f x)).\napply triangle_inequality; apply R_metric_is_metric.\nreplace (0+eps) with (eps/2+eps/2) by field.\napply Rplus_lt_compat.\nrewrite metric_sym; try apply R_metric_is_metric.\nassert (DS_ord N1 N) by apply le_max_l.\napply Rle_lt_trans with (2:=H1 N H4).\nunfold uniform_metric; simpl; destruct sup; simpl.\napply i.\nexists (subspace_inc F x).\nconstructor.\napply R_metric_is_metric.\n\nassert ((N >= N2)%nat) by apply le_max_r.\napply Rle_lt_trans with (2:=H3 N H4).\nrewrite Rabs_right.\ndestruct extension_approximation_seq as [h [? []]]; simpl.\nunfold R_metric.\ndestruct (a0 x).\nunfold Rabs; destruct Rcase_abs; fourier.\napply Rle_ge.\napply pow_le; fourier.\nQed.\n\nLet convert_continuity: forall h:point_set X -> R,\n  continuous h (Y:=RTop) <-> continuous h (Y:=MetricTopology R_metric\n                                           R_metric_is_metric).\nProof.\nassert (continuous (fun x:R => x)\n  (X:=RTop) (Y:=MetricTopology R_metric R_metric_is_metric)).\napply pointwise_continuity; intros.\napply metric_space_fun_continuity with R_metric R_metric; intros.\napply RTop_metrization.\napply MetricTopology_metrizable.\nexists eps; split; trivial.\nassert (continuous (fun x:R => x)\n  (X:=MetricTopology R_metric R_metric_is_metric) (Y:=RTop)).\napply pointwise_continuity; intros.\napply metric_space_fun_continuity with R_metric R_metric; intros.\napply MetricTopology_metrizable.\napply RTop_metrization.\nexists eps; split; trivial.\n\nintros; split; intros.\napply continuous_composition with (1:=H) (2:=H1).\napply continuous_composition with (1:=H0) (2:=H1).\nQed.\n\nLemma Tietze_extension_func_continuous: continuous Tietze_extension_func.\nProof.\nunfold Tietze_extension_func;\n  destruct constructive_definite_description as [g];\n  simpl.\napply net_limit_in_closure with\n  (S:=fun h:point_set (UniformTopology R_metric (fun _:point_set X => 0)\n                           R_metric_is_metric X_nonempty) =>\n     continuous (proj1_sig h)\n     (Y:=MetricTopology R_metric R_metric_is_metric)) in n.\nrewrite closure_fixes_closed in n.\nunfold In in n.\napply <- convert_continuity; trivial.\napply continuous_functions_closed_in_uniform_metric.\nred; intros.\nexists i; split.\nsimpl; constructor.\nred.\nunfold convert_approx_to_uniform_space; simpl.\ndestruct extension_approximation_seq as [h [? []]]; simpl.\napply -> convert_continuity; trivial.\nQed.\n\nEnd Tietze_extension_construction.\n\nLemma bounded_Tietze_extension_theorem: forall (X:TopologicalSpace)\n  (F:Ensemble (point_set X)) (f:point_set (SubspaceTopology F) ->\n                                point_set RTop),\n  normal_sep X -> closed F -> continuous f ->\n  (forall x:point_set (SubspaceTopology F), -1 <= f x <= 1) ->\n  exists g:point_set X -> point_set RTop,\n    continuous g /\\ (forall x:point_set (SubspaceTopology F),\n                     g (subspace_inc F x) = f x) /\\\n    (forall x:point_set X, -1 <= g x <= 1).\nProof.\nintros.\ndestruct (classic (inhabited (point_set X))) as [Hinh|Hempty].\nRequire Import ClassicalChoice.\ndestruct (choice (fun \n  (FG:{FG:Ensemble (point_set X) * Ensemble (point_set X) | let (F,G):=FG in\n                    closed F /\\ closed G /\\ Intersection F G = Empty_set})\n  (phi:point_set X -> point_set RTop) =>\n   let (F,G):=proj1_sig FG in\n   continuous phi /\\ (forall x:point_set X, 0 <= phi x <= 1) /\\\n   (forall x:point_set X, In F x -> phi x = 0) /\\\n   (forall x:point_set X, In G x -> phi x = 1))) as [choice_fun].\nintros.\ndestruct x as [[F' G] [? []]].\nsimpl.\nRequire Import UrysohnsLemma.\napply UrysohnsLemma; trivial.\npose (Urysohns_lemma_function := fun (F G:Ensemble (point_set X))\n  (HF:closed F) (HG:closed G) (Hdisj:Intersection F G = Empty_set) =>\n  exist (fun (f:point_set X -> point_set RTop) =>\n           continuous f /\\ (forall x:point_set X, 0 <= f x <= 1) /\\\n           (forall x:point_set X, In F x -> f x = 0) /\\\n           (forall x:point_set X, In G x -> f x = 1))\n    (choice_fun (exist _ (F,G) (conj HF (conj HG Hdisj))))\n    (H3 (exist _ (F,G) (conj HF (conj HG Hdisj))))).\nclearbody Urysohns_lemma_function; clear choice_fun H3.\nexists (Tietze_extension_func X F H0 f H1 H2 Hinh\n  Urysohns_lemma_function).\nsplit.\napply Tietze_extension_func_continuous.\nsplit; intros.\napply Tietze_extension_func_is_extension.\napply Tietze_extension_func_bound.\n\nexists (fun x:point_set X => False_rect _ (Hempty (inhabits x))).\nsplit.\napply pointwise_continuity.\nintros.\ndestruct (Hempty (inhabits x)).\nsplit.\nintros.\ndestruct x.\ndestruct (Hempty (inhabits x)).\nintros.\ndestruct (Hempty (inhabits x)).\nQed.\n\nLemma open_bounded_Tietze_extension_theorem: forall (X:TopologicalSpace)\n  (F:Ensemble (point_set X)) (f:point_set (SubspaceTopology F) ->\n                                point_set RTop),\n  normal_sep X -> closed F -> continuous f ->\n  (forall x:point_set (SubspaceTopology F), -1 < f x < 1) ->\n  exists g:point_set X -> point_set RTop,\n    continuous g /\\ (forall x:point_set (SubspaceTopology F),\n                     g (subspace_inc F x) = f x) /\\\n    (forall x:point_set X, -1 < g x < 1).\nProof.\nintros.\ndestruct (bounded_Tietze_extension_theorem _ F f) as [g0 [? []]]; trivial.\nintros; split; left; apply H2.\n\npose (G := characteristic_function_to_ensemble (fun x:point_set X =>\n  g0 x = 1 \\/ g0 x = -1)).\ndestruct (UrysohnsLemma _ H G F) as [phi [? [? []]]]; trivial.\nreplace G with (inverse_image g0 (Union (Singleton 1) (Singleton (-1)))).\nred; rewrite <- inverse_image_complement.\napply H3.\napply (closed_union2 (X:=RTop)); apply Hausdorff_impl_T1_sep;\n  apply T3_sep_impl_Hausdorff; apply normal_sep_impl_T3_sep;\n  apply metrizable_impl_normal_sep; exists R_metric;\n  (apply R_metric_is_metric || apply RTop_metrization).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H6.\nconstructor.\ndestruct H6.\nleft; destruct H6; trivial.\nright; destruct H6; trivial.\ndestruct H6.\nconstructor.\ndestruct H6; [ left | right ]; rewrite H6; constructor.\n\napply Extensionality_Ensembles; split; auto with sets; red; intros.\ndestruct H6.\ndestruct H6.\nassert (-1 < g0 x < 1).\nreplace x with (subspace_inc F (exist _ x H7)) by reflexivity.\nrewrite H4.\napply H2.\ndestruct H8.\ndestruct H6.\nabsurd (1 < 1); [ apply Rlt_irrefl | congruence ].\nabsurd (-1 < -1); [ apply Rlt_irrefl | congruence ].\n\nexists (fun x:point_set X => phi x * g0 x).\nsplit.\napply pointwise_continuity; intros.\napply product_continuous; apply continuous_func_continuous_everywhere;\n  trivial.\nsplit.\nintros.\nrewrite H9.\nreplace (1*g0 (subspace_inc F x)) with (g0 (subspace_inc F x)) by\n  auto with real.\napply H4.\ndestruct x; trivial.\n\nintros.\napply and_comm; apply Rabs_def2.\nrewrite Rabs_mult.\nrewrite (Rabs_right (phi x)); try (apply Rle_ge; apply H7).\ndestruct (classic (In G x)).\nrewrite H8; trivial.\nreplace (0*Rabs (g0 x)) with 0; auto with real.\nassert (Rabs (g0 x) < 1).\nassert (Rabs (g0 x) <= 1).\ndestruct (H5 x).\nunfold Rabs; destruct Rcase_abs; fourier.\ndestruct H11; trivial.\ncontradiction H10.\nunfold Rabs in H11; destruct Rcase_abs in H11.\nconstructor; right.\nreplace (g0 x) with (- -(g0 x)) by auto with real.\nf_equal; trivial.\nconstructor; left; trivial.\ndestruct (H7 x).\napply Rle_lt_trans with (Rabs (g0 x)); trivial.\npattern (Rabs (g0 x)) at 2; replace (Rabs (g0 x)) with (1*Rabs (g0 x)) by\n  auto with real.\napply Rmult_le_compat_r; trivial.\napply Rabs_pos.\nQed.\n\nTheorem Tietze_extension_theorem: forall (X:TopologicalSpace)\n  (F:Ensemble (point_set X)) (f:point_set (SubspaceTopology F) ->\n                                point_set RTop),\n  normal_sep X -> closed F -> continuous f ->\n  exists g:point_set X -> point_set RTop,\n    continuous g /\\ (forall x:point_set (SubspaceTopology F),\n                     g (subspace_inc F x) = f x).\nProof.\nintros.\npose (U := characteristic_function_to_ensemble\n      (fun x:point_set RTop => -1 < x < 1)).\npose proof (open_interval_homeomorphic_to_real_line).\nfold U in H2.\nsimpl in H2.\ndestruct H2 as [a [b]].\npose (f0 := fun x:point_set (SubspaceTopology F) => subspace_inc U (a (f x))).\ndestruct (open_bounded_Tietze_extension_theorem X F f0) as [g0 [? []]];\n  trivial. unfold f0.\napply continuous_composition.\napply subspace_inc_continuous.\napply continuous_composition; trivial.\n\nintros.\nunfold f0.\ndestruct (a (f x)).\ndestruct i; trivial.\n\nassert (forall x:point_set X, In U (g0 x)).\nintros.\nconstructor; apply H8.\nRequire Import ContinuousFactorization.\npose (g0_U := continuous_factorization g0 U H9).\nassert (continuous g0_U).\napply factorization_is_continuous; trivial.\n\nexists (fun x:point_set X => b (g0_U x)).\nsplit.\napply continuous_composition; trivial.\nintros.\nunfold g0_U; unfold continuous_factorization.\ngeneralize (H9 (subspace_inc F x)).\nrewrite H7.\nintros.\nreplace (exist _ (f0 x) i) with (a (f x)).\napply H4.\nRequire Import Proj1SigInjective.\napply (proj1_sig_injective (In U)).\nsimpl.\nreflexivity.\nQed.\n", "meta": {"author": "verimath", "repo": "topology", "sha": "9405aaf18d99c718769f1d2af8e030a902687837", "save_path": "github-repos/coq/verimath-topology", "path": "github-repos/coq/verimath-topology/topology-9405aaf18d99c718769f1d2af8e030a902687837/src/top/TietzeExtension.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6510037344849193}}
{"text": "Require Import bnat.\nRequire Import FCF.\nRequire Import EqDec.\nSet Implicit Arguments.\nCheck 0.\n\n\nDefinition vec_dotmod {n : nat} (q : nat) (a b : Vector.t nat n) :=\nVector.fold_left2 (fun acc v w => acc + (v * w) mod q)%nat 0%nat a b.\n\nCheck Vector.map2.\n\nDefinition vec_addmod {n : nat} (q : nat) (a b : Vector.t nat n) :=\nVector.map2 (fun x y => x + y mod q)%nat a b.\n\nDefinition ratRound01 (r : Rat) :=\nif bleRat (ratDistance r 0) (ratDistance r 1) then false else true.\n\nFixpoint Sample_N {A : Set} {eqa : EqDec A} {eqva : forall n, EqDec (Vector.t A n)} (c : Comp A) (n : nat) : Comp (Vector.t A n) :=\nmatch n with\n| 0 => ret (Vector.nil A)\n| S m => x <-$ c;\n         tl <-$ Sample_N c m;\n         ret (Vector.cons _ x _ tl)\nend.\n\nDefinition Uniform_nat (N : nat) :=\nx <-$ [0..N);\nret x.\n\nSection LWE_Defs.\nContext (q n : nat).\nContext (posq : nz q).\nLocate nz.\nDefinition LWEVec := Vector.t nat n.\n\nCheck Vector.fold_left2.\n\n\n\nDefinition Uniform_LWEVec := Sample_N (Uniform_nat q) n. (* computes x <-$ Z_q^n *)\nDefinition Uniform_q := Uniform_nat q. (* computes x <-$ Z_q *)\nContext (chi : Comp (bnat q)).\n\nDefinition LWE_UniformDist (st input : unit) :=\na <-$ Uniform_LWEVec;\nb <-$ Uniform_q;\nret ((a, b), tt).\n\nDefinition LWE_RealDist (s : LWEVec) (st input : unit) :=\na <-$ Uniform_LWEVec;\ne <-$ chi;\nret ((a, (to_nat e) + (vec_dotmod q a s))%nat, tt).\n\n\nCheck LWE_RealDist.\n\nVariable D : OracleComp unit (Vector.t nat n * nat) bool.\n\nDefinition LWE_Fake :=\n[b, _] <-$2 D _ _ LWE_UniformDist tt;\nret b.\n\nDefinition LWE_Real (s : LWEVec) :=\n[b, _] <-$2 D _ _ (LWE_RealDist s) tt;\nret b.\n\nDefinition LWE_Advantage (s : LWEVec) := |Pr[LWE_Fake] - Pr[LWE_Real s]|. (* this is a concrete rational number *)\nEnd LWE_Defs.\n\n(* should be able to say IND-CPA experiment for Regev LWE PKE is such that for all s,\n|Regev_Advantage - LWE_Advantage| < negl(n) *)\n\nSection Regev_PKE.\nContext (q n m : nat).\nContext (posq : nz q).\nContext (chi : Comp (bnat q)).\nCheck Uniform_LWEVec.\nDefinition Sample_SK := Uniform_LWEVec q n.\nCheck Sample_SK.\nDefinition Regev_SecretKey := (Vector.t nat n).\n\nCheck LWEVec.\n\nCheck LWE_RealDist.\n\nDefinition Sample_PK (s : LWEVec n) := Sample_N\n([a, b, _] <-$3 LWE_RealDist chi s tt tt;\n ret (a, b)) \nm.\n\nCheck Sample_PK.\nDefinition Regev_PublicKey := (Vector.t (Vector.t nat n * nat) m).\n\nDefinition Generate_SelectVector := Sample_N ({0,1}) m.\nDefinition SelectVector := Vector.t bool m.\n\nCheck Vector.const.\n\nCheck vec_addmod.\n\nDefinition SubsetSum (pk: Regev_PublicKey) (sel : SelectVector) :=\nVector.fold_left2 (fun acc p (b : bool) => if b then \n                   match p, acc with\n                   | (a, b), (aa, ab) => (vec_addmod q a aa, b + ab mod q)%nat \n                   end\n                    else acc)\n                   (Vector.const 0%nat n, 0%nat) pk sel.\n\nCheck SubsetSum.\n\nCheck div.\n\nCheck bnat_mod_nat.\n\nDefinition Regev_PKEnc (pk: Regev_PublicKey) (m : bool) :=\nsel <-$ Generate_SelectVector;\n[a, b] <-2 SubsetSum pk sel;\nb <- if m then\n      (b + (div q 2) mod q)%nat\n      else b;\nret (a, b).\n\n\n\nDefinition Regev_Ciphertext := (Vector.t nat n * nat)%type.\n\n\nDefinition Regev_PKDec (s : Regev_SecretKey) (c : Regev_Ciphertext) := match c with\n| (a, b) => let r := (b - (vec_dotmod q a s)) in\n            ratRound01 ( (r/1) * (2 / 1) * (1 / q))%rat\nend.\n\nCheck Vector.fold_left.\n\nDefinition admissible_chi (k : nat) :=\nes <-$ Sample_N chi k;\nsum <- Vector.fold_left (fun a b => a + (to_nat b))%nat (0%nat) es;\nret (leb sum (div q 4)).\n\nLemma correct_decrypt (delta : Rat) (s : Regev_SecretKey) (pk: Regev_PublicKey) (c : Regev_Ciphertext) (msg : bool) :\nIn pk (getSupport (Sample_PK s)) ->\nIn c (getSupport (Regev_PKEnc pk msg)) ->\n(forall k : nat, k < m -> Pr[admissible_chi k] <= delta) ->\nRegev_PKDec s c = msg.\nAbort.\n\n            \n\n", "meta": {"author": "gancherj", "repo": "whp", "sha": "6c7f5766b7260d6a00d048d3aa5c3c9a91dec2f6", "save_path": "github-repos/coq/gancherj-whp", "path": "github-repos/coq/gancherj-whp/whp-6c7f5766b7260d6a00d048d3aa5c3c9a91dec2f6/old/lwedefs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6509693060511174}}
{"text": "(*\n        #####################################################\n        ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n        #####################################################\n*)\nRequire Import Turing.Turing.\nRequire Import Turing.LangRed.\nRequire Import Turing.LangDec.\n\n(* ---------------------------------------------------------------------------*)\n\n(* ------------------------ BEGIN UTILITY RESULTS ---------------------- *)\n(** See Example 5.26 (pp 237):\n    Let <M> = p.\n\n    Function F3 (defined below) maps the input <M> to the output <M, M1>,\n    where M1 is the machine that rejects all inputs.\n*)\n\nDefinition F3 p :=\n    encode_pair (p , [[ Build (fun _ => REJECT) ]]).\n\nLemma false_equiv_reject:\n    PRecognizes (fun _ => REJECT) (fun _ => False).\nProof.\n    intros.\n    apply p_recognizes_def; intros; run_simpl_all.\nQed.\n\nLemma E_tm_inv:\n    forall w,\n    E_tm w ->\n    exists m, m = decode_machine w /\\\n    forall i, run m i <> Accept.\nProof.\n    intros.\n    unfold E_tm in *.\n    rewrite is_empty_never_accept_rw in H.\n    unfold NeverAccept in *.\n    eauto.\nQed.\n\nLemma EQ_tm_inv:\n    forall w,\n    EQ_tm w ->\n    exists m1 m2, w = encode_pair (encode_machine m1, encode_machine m2) /\\\n    forall i, run m1 i = Accept <-> run m2 i = Accept.\nProof.\n    intros.\n    unfold EQ_tm in *.\n    destruct (decode_pair w) as (w1, w2) eqn:Hr.\n    exists (decode_machine w1).\n    exists (decode_machine w2).\n    split. {\n    run_simpl_all.\n    rewrite <- Hr.\n    run_simpl_all.\n    reflexivity.\n    }\n    intros.\n    unfold Lang, Equiv in *.\n    auto.\nQed.\n\n\n(* Given two machines m1 m2 you will need to show:\n    1. Whenever m1 accepts, m2 accepts.\n    2. Whenever m2 accepts, m1 accepts.\n    Then EQ_tm (m1, m2) holds.\n*)\nLemma EQ_tm_def:\n    forall m1 m2 w,\n    w = encode_pair (encode_machine m1, encode_machine m2) ->\n    (forall i, run m1 i = Accept -> run m2 i = Accept) ->\n    (forall i, run m2 i = Accept -> run m1 i = Accept) ->\n    EQ_tm w.\nProof.\n    intros.\n    unfold EQ_tm in *.\n    destruct (decode_pair w) as (w1, w2) eqn:Hr.\n    rewrite H in *.\n    run_simpl_all.\n    inversion Hr; subst; clear Hr.\n    unfold Equiv.\n    unfold Lang.\n    run_simpl_all.\n    split; intros; auto.\nQed.\n\n(**\n  To construct a term of E_tm we must show that the machine\n  does _not_ accept any input.\n  *)\nLemma E_tm_def:\n    forall m w,\n    w = encode_machine m ->\n    (forall i, run m i <> Accept) ->\n    E_tm w.\nProof.\n    intros.\n    unfold E_tm.\n    unfold IsEmpty, Empty, Recognizes.\n    subst.\n    run_simpl_all.\n    split; intros. {\n    assert (Hx := H0 i).\n    contradiction.\n    }\n    contradiction.\nQed.\n\nLemma f3_rw:\n    forall w,\n    F3 w = encode_pair ([[decode_machine w]], [[Build (fun _ => REJECT)]]).\nProof.\n    intros.\n    run_simpl_all.\n    unfold F3.\n    reflexivity.\nQed.\n\nLemma f3_inv:\n    forall w m1 m2,\n    F3 w = encode_pair ([[m1]], [[m2]]) ->\n    w = [[m1]] /\\ m2 = Build (fun _ => REJECT).\nProof.\n    unfold F3; intros.\n    apply encode_pair_ext in H.\n    inversion H; subst; clear H.\n    apply encode_machine_ext in H2.\n    auto.\nQed.\n(* -------------------------- END OF UTILITY RESULTS ---------------------- *)\n\n\n\n(**\n\nMedium.\n* Use E_def, EQ_tm_def to construct an EQ_tm/E_tm.\n* Use E_tm_inv, EQ_tm_inv to destruct an EQ/E assumption.\n* Use run_simpl_all to simplify assumptions `run (Build _)`.\n *)\nTheorem E_tm_red_EQ_tm_1:\n  forall w, E_tm w -> EQ_tm (F3 w).\nProof.\n\nAdmitted.\n\n(**\n\nMedium.\n\n* Use E_def, EQ_tm_def to construct an EQ_tm/E_tm.\n* Use E_tm_inv, EQ_tm_inv to destruct an EQ/E assumption.\n* Use run_simpl_all to simplify assumptions `run (Build _)`.\n\n\n *)\nTheorem E_tm_red_EQ_tm_2:\n  forall w, EQ_tm (F3 w) -> E_tm w.\nProof.\n\nAdmitted.\n\n(**\n\nEasy. Solve Exercise 5.26 of the book (pp 237).\n\n *)\nTheorem E_tm_red_EQ_tm:\n  E_tm <=m EQ_tm.\nProof.\n\nAdmitted.\n\n(**\n\nEasy. Prove Theorem 5.4 (pp 220) using map-reducibility (Exercise 5.26).\n\n *)\nTheorem thm_5_4:\n  ~ Decidable EQ_tm.\nProof.\n\nAdmitted.\n\n(**\n\nEasy. Solve Exercise 5.6 (pp 239; solution in pp 242). You should use `reducible_def` and then unfold Reduction.\n\n\n *)\nTheorem ex_5_6:\n  forall A B C, A <=m B -> B <=m C -> A <=m C.\nProof.\nintros A B C (f, Hab) (g, Hbc).\n\nAdmitted.\n\n(**\n\nSolve Exercise 5.7 (pp 239; solution in pp 242).\n\n\n *)\nTheorem ex_5_7:\n  forall A, Recognizable A -> A <=m compl A -> Decidable A.\nProof.\n\nAdmitted.\n\n(**\n\nEasy. Show that every recognizable language is map-reducible to A_tm.\n\n\n *)\nTheorem ex_5_22_a:\n  forall A, Recognizable A -> A <=m A_tm.\nProof.\nintros A (M, Hd). apply reducible_def with (f:= fun w => <[ M, w ]> ).\n\nAdmitted.\n\n(**\n\nEasy. Show that every language map-reducible to A_tm is recognizable.\n\n *)\nTheorem ex_5_22_b:\n  forall A, A <=m A_tm -> Recognizable A.\nProof.\n\nAdmitted.\n\n(**\n\nEasy. Show that A is Turing-recognizable iff A <=m ATM (Exercise 5.22, pp 240).\n\n\n *)\nTheorem ex_5_22:\n  forall A, Recognizable A <-> A <=m A_tm.\nProof.\n\nAdmitted.\n\n(**\n\nEasy. One theorem can help you solve this result.\n\n *)\nTheorem not_dec_to_not_rec:\n  forall L, ~ Decidable L -> Recognizable (compl L) -> ~ Recognizable L.\nProof.\n\nAdmitted.\n\n(**\n\nHard. Easy to solve if done in pen-and-paper first.\nSome results needed to prove Exercise 5.22 are helpful here.\n\n\n *)\nTheorem a_red_not_a_tm:\n  forall A B, compl A <=m B -> Recognizable B -> A <=m compl A_tm.\nProof.\n\nAdmitted.\n", "meta": {"author": "mansi0312", "repo": "CS420", "sha": "d949dc7ba204b990a4bfe3b616916437f50b0230", "save_path": "github-repos/coq/mansi0312-CS420", "path": "github-repos/coq/mansi0312-CS420/CS420-d949dc7ba204b990a4bfe3b616916437f50b0230/hw8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6509554200347287}}
{"text": "Require Export Reals.\nRequire Import ComhCoq.GenTacs.\nRequire Import ComhCoq.Extras.LibTactics.\nOpen Scope R_scope.\n\nLtac Rmult_le_zero :=\n  match goal with\n  | [ |- 0 <= ?y1 * ?y2] => \n    replace 0 with (0 * 0);[ | ring];\n    apply Rmult_le_compat;[apply Rle_refl | apply Rle_refl | ..]\n  end.\n\n(** Splits the goal into 2 subgoals based on d <= t or t < d*)\nLtac Rleltcases d t U :=  let H := fresh in lets H : Rle_or_lt d t;\n                                            let U1 := fresh U in elim_intro H U1 U1.\n\nLemma not_Rle_lt : forall (r1 r2 : R),\n  ~r1 <= r2 -> r2 < r1. intros. addHyp (Rlt_or_le r1 r2). invertClear H0.\n  apply False_ind. apply H. apply Rlt_le. assumption.\n  apply Rle_lt_or_eq_dec in H1. invertClear H1. assumption.\n  rewrite H0 in H. apply False_ind. apply H. apply Rle_refl. Qed.\n\nLemma RltMinusBothSides : forall (r1 r2 : R),\n  r2 < r1 -> 0 < (r1 - r2).\n  intros. apply Rnot_le_lt. unfold not. intros.\n  apply Rplus_le_compat_l with (r := r2) in H0. rewrite Rplus_minus in H0.\n  rewrite Rplus_0_r in H0. eapply Rle_not_lt. apply H0. apply H.\n  Qed.\n\n(**** Rle ****)\n\nLtac Rle_trans_red := \n  match goal with\n  | [H1 : ?r1 <= ?r2, H2 : ?r2 <= ?r3 |- ?r1 <= ?r3] =>\n    eapply Rle_trans;[apply H1 | apply H2]\n  | [H1 : ?r1 <= ?r2 |- ?r1 <= ?r3] =>\n    eapply Rle_trans;[apply H1 | ]\n  | [H2 : ?r2 <= ?r3 |- ?r1 <= ?r3] =>\n    eapply Rle_trans;[ | apply H2]\n  end.\n\nLtac Rle_trans_rev_red := \n  match reverse goal with\n  | [H1 : ?r1 <= ?r2, H2 : ?r2 <= ?r3 |- ?r1 <= ?r3] =>\n    eapply Rle_trans;[apply H1 | apply H2]\n  | [H1 : ?r1 <= ?r2 |- ?r1 <= ?r3] =>\n    eapply Rle_trans;[apply H1 | ]\n  | [H2 : ?r2 <= ?r3 |- ?r1 <= ?r3] =>\n    eapply Rle_trans;[ | apply H2]\n  end.\n\nLtac Rplus_le_cancel_middle :=\n  match goal with\n  | [ |- ?x1 + ?r + ?x2 <= ?y1 + ?r + ?y2] =>\n    replace (x1 + r + x2) with (x1 + x2 + r);[ | ring];\n    replace (y1 + r + y2) with (y1 + y2 + r);[ | ring];\n    apply Rplus_le_compat_r\n  | [ |- ?x1 + ?r <= ?y1 + ?r + ?y2] =>\n    replace (y1 + r + y2) with (y1 + y2 + r);[ | ring];\n    apply Rplus_le_compat_r\n  end.\n\nLtac Rle_ring_solve := apply Req_le; simpl; ring.\n\nLtac Rle_refl_solve := apply Rle_refl.\n\nLemma Rle_plus_r : forall (x y : R),\n  0 <= y -> x <= x + y. intros. apply Rle_trans with (r2 := x + 0).\n  replace (x + 0) with x. apply Rle_refl. ring.\n  apply Rplus_le_compat. apply Rle_refl. assumption. Qed.\n\nLemma Rle_plus_l : forall (x y : R),\n  0 <= y -> x <= y + x. intros. rewrite Rplus_comm.\n  apply Rle_plus_r. assumption. Qed.\n\nLemma RleMinusBothSides : forall (r1 r2 : R),\n  r2 <= r1 -> 0 <= (r1 - r2). intros. apply Rle_lt_or_eq_dec in H.\n  inversion H. apply RltMinusBothSides in H0. apply Rlt_le. assumption.\n  rewrite H0. rewrite Rminus_diag_eq. apply Rle_refl. reflexivity. Qed.\n\nLemma Rmult_le_0_compat : forall r1 r2 : R,\n  0 <= r1 -> 0 <= r2 -> 0 <= r1 * r2.\n  intros. simpl. rewrite <- (Rmult_0_r 0). apply Rmult_le_compat;\n  try assumption; try apply Rle_refl. Qed.\n\nLemma Rle_zero_plus : forall r1 r2 : R,\n  0 <= r1 -> 0 <= r2 -> 0 <= r1 + r2.\n  intros. rewrite <- Rplus_0_r at 1. apply Rplus_le_compat; assumption. Qed.\n\nLemma Rle_zero_mult : forall r1 r2 : R,\n  0 <= r1 -> 0 <= r2 -> 0 <= r1 * r2. intros. rewrite <- (Rmult_0_l r2)at 1.\n  apply Rmult_le_compat_r; assumption. Qed.\n\nLemma RlePlusExistsR : forall (r1 r2 : R),\n  r1 <= r2 -> exists r3, r2 = r1 + r3 /\\ 0 <= r3. intros.\n  exists (r2 - r1). split. ring. apply (Rplus_le_reg_r r1).\n  replace (r2 - r1 + r1) with r2; try ring. rewrite Rplus_0_l.\n  assumption. Qed.\n\nLemma RlePlusExistsL : forall (r1 r2 : R),\n  r1 <= r2 -> exists r3, r2 = r3 + r1 /\\ 0 <= r3. intros.\n  apply RlePlusExistsR in H. invertClear H.\n  exists x. rewrite Rplus_comm. assumption. Qed.\n\nLemma Rle_or_le : forall (r1 r2 : R), r1 <= r2 \\/ r2 <= r1.\n  intros. addHyp (Rlt_or_le r1 r2). invertClear H. left.\n  apply Rlt_le. assumption. right. assumption. Qed.\n\nLemma Rplus_le_swap_rr : forall (x y z : R),\n  x <= y + z -> x - z <= y. intros. eapply Rplus_le_reg_r.\n  eapply Rle_trans;[ | apply H ].\n  apply Req_le. ring. Qed.\n\nLemma Rplus_le_swap_rl : forall (x y z : R),\n  x <= y + z -> x - y <= z. intros. rewrite Rplus_comm in H.\n  apply Rplus_le_swap_rr. assumption. Qed.\n\nLemma Rplus_le_swap_lr : forall (x y z : R),\n  x + y <= z -> x <= z - y. intros. eapply Rplus_le_reg_r.\n  eapply Rle_trans. apply H. apply Req_le. ring. Qed.\n\nLemma Rplus_le_swap_ll : forall (x y z : R),\n  x + y <= z -> y <= z - x. intros. rewrite Rplus_comm in H.\n  apply Rplus_le_swap_lr. assumption. Qed.\n\nLemma Rminus_le_swap_rr : forall (x y z : R),\n  x <= y - z -> x + z <= y. intros. eapply Rplus_le_reg_r.\n  eapply Rle_trans;[ | apply H]. apply Req_le. ring. Qed.\n\nLemma Rminus_le_swap_lr : forall (x y z : R),\n  x - y <= z -> x <= z + y. intros. eapply Rplus_le_reg_r.\n  eapply Rle_trans. apply H. apply Req_le. ring. Qed.\n\nLemma Rplus_le_weaken_lr : forall (x y z : R), x + y <= z -> 0 <= y -> x <= z.\n  intros. eapply Rle_trans;[ |apply H]. apply Rle_plus_r. assumption. Qed.\n\nLemma Rplus_le_weaken_ll : forall (x y z : R), x + y <= z -> 0 <= x -> y <= z.\n  intros. rewrite Rplus_comm in H. eapply Rplus_le_weaken_lr. apply H. assumption.\n  Qed.\n\nLemma Rplus_le_weaken_rr : forall (x y z : R), 0 <= z -> x <= y -> x <= y + z.\n  intros. replace x with (x + 0). eapply Rplus_le_compat; assumption.\n  ring. Qed.\n\nLemma Rplus_le_weaken_rl : forall (x y z : R), 0 <= y -> x <= z -> x <= y + z.\n  intros. rewrite Rplus_comm. apply Rplus_le_weaken_rr;assumption. Qed.\n\nLemma Rminus_le_weaken_lr : forall (x y z : R), 0 <= y -> x <= z -> x - y <= z.\n  intros. replace z with (z - 0);[ | ring]. eapply Rplus_le_compat.\n  assumption. apply Ropp_le_contravar. assumption. Qed.\n\n(** Tries to solve an inequality on real numbers.*)\nLtac Rplus_le_tac := \n  match goal with\n  | [ H1 : ?r1 <= ?r3, H2 : ?r2 <= ?r4 |- ?r1 + ?r2 <= ?r3 + ?r4] =>\n    apply Rplus_le_compat;[apply H1 | apply H2]\n  | [ H1 : ?r1 <= ?r3, H2 : ?r2 <= ?r4 |- ?r2 + ?r1 <= ?r3 + ?r4] =>\n    rewrite Rplus_comm; apply Rplus_le_compat;[apply H1 | apply H2]\n  | [ H1 : ?r1 <= ?r2|- ?r + ?r1 <= ?r + ?r2] =>\n    apply Rplus_le_compat_l;apply H1\n  | [ H1 : ?r1 <= ?r2|- ?r1 + ?r <= ?r2 + ?r] =>\n    apply Rplus_le_compat_r;apply H1\n  | [ |- ?r + ?r1 <= ?r + ?r2] =>\n    apply Rplus_le_compat_l\n  | [ |- ?r1 + ?r <= ?r2 + ?r] =>\n    apply Rplus_le_compat_r\n  | [ H : ?r1 + ?r <= ?r2 + ?r |- ?r1 <= ?r2] =>\n    apply Rplus_le_reg_l in H; assumption\n  | [ H : ?r + ?r1 <= ?r + ?r2 |- ?r1 <= ?r2] =>\n    apply Rplus_le_reg_r in H; assumption\n  | [ H : ?x <= ?y + ?z |- ?x - ?z <= ?y] =>\n    apply Rplus_le_swap_rr; assumption\n  | [ H : ?x + ?y <= ?z |- ?y <= ?z - ?x] =>\n    apply Rplus_le_swap_ll; assumption\n  | [ H : ?x + ?y <= ?z |- ?x <= ?z - ?y] =>\n    apply Rplus_le_swap_lr; assumption\n  | [ H : ?x <= ?y + ?z |- ?x - ?y <= ?z] =>\n    apply Rplus_le_swap_rl; assumption\n  | [ |- ?r1 <= ?r1 + _] => apply Rle_plus_r\n  | [ |- ?r1 <= _ + ?r1] => apply Rle_plus_l\n  | [ H : ?x + ?y <= ?z |- ?x <= ?z] =>\n    eapply Rplus_le_weaken_lr; apply H\n  | [ H : ?x + ?y <= ?z |- ?y <= ?z] =>\n    eapply Rplus_le_weaken_ll; apply H\n  end.\n\n\n(**** Rlt ****)\n\nLtac Rlt_trans_red := \n  match goal with\n  | [H1 : ?r1 < ?r2, H2 : ?r2 < ?r3 |- ?r1 < ?r3] =>\n    eapply Rlt_trans;[apply H1 | apply H2]\n  | [H1 : ?r1 < ?r2 |- ?r1 < ?r3] =>\n    eapply Rlt_trans;[apply H1 | ]\n  | [H2 : ?r2 < ?r3 |- ?r1 < ?r3] =>\n    eapply Rlt_trans;[ | apply H2]\n  end.\n\nLtac Rlt_trans_rev_red := \n  match reverse goal with\n  | [H1 : ?r1 < ?r2, H2 : ?r2 < ?r3 |- ?r1 < ?r3] =>\n    eapply Rlt_trans;[apply H1 | apply H2]\n  | [H1 : ?r1 < ?r2 |- ?r1 < ?r3] =>\n    eapply Rlt_trans;[apply H1 | ]\n  | [H2 : ?r2 < ?r3 |- ?r1 < ?r3] =>\n    eapply Rlt_trans;[ | apply H2]\n  end.\n\nLtac Rplus_lt_cancel_middle :=\n  match goal with\n  | [ |- ?x1 + ?r + ?x2 < ?y1 + ?r + ?y2] =>\n    replace (x1 + r + x2) with (x1 + x2 + r);[ | ring];\n    replace (y1 + r + y2) with (y1 + y2 + r);[ | ring];\n    apply Rplus_lt_compat_r\n  | [ |- ?x1 + ?r < ?y1 + ?r + ?y2] =>\n    replace (y1 + r + y2) with (y1 + y2 + r);[ | ring];\n    apply Rplus_lt_compat_r\n  end.\n\nLemma Rlt_plus_r : forall (x y : R),\n  0 < y -> x < x + y. intros. apply Rle_lt_trans with (r2 := x + 0).\n  replace (x + 0) with x. apply Rle_refl. ring.\n  apply Rplus_le_lt_compat. apply Rle_refl. assumption. Qed.\n\nLemma Rlt_plus_l : forall (x y : R),\n  0 < y -> x < y + x. intros. rewrite Rplus_comm.\n  apply Rlt_plus_r. assumption. Qed.\n\nLemma Rlt_zero_plus : forall r1 r2 : R,\n  0 < r1 -> 0 < r2 -> 0 < r1 + r2.\n  intros. rewrite <- Rplus_0_r at 1. apply Rplus_lt_compat; assumption. Qed.\n\nLemma RltPlusExistsR : forall (r1 r2 : R),\n  r1 < r2 -> exists r3, r2 = r1 + r3 /\\ 0 < r3. intros.\n  exists (r2 - r1). split. ring. apply (Rplus_lt_reg_r r1).\n  replace (r2 - r1 + r1) with r2; try ring. rewrite Rplus_0_l.\n  assumption. Qed.\n\nLemma RltPlusExistsL : forall (r1 r2 : R),\n  r1 < r2 -> exists r3, r2 = r3 + r1 /\\ 0 < r3. intros.\n  apply RltPlusExistsR in H. invertClear H.\n  exists x. rewrite Rplus_comm. assumption. Qed.\n\nLemma RltExistsBetween (r1 r2 : R) : r1 < r2 -> exists r3,\n  r1 < r3 < r2. intros. addHyp (RltPlusExistsL r1 r2 H). invertClear H0.\n  invertClear H1. exists (r1 + x/2). assert (0 < x/2). rewrite double_var in H2.\n  addHyp (Rlt_or_le 0 (x/2)). invertClear H1. assumption.\n  assert (x / 2 + x / 2 <= 0 + 0). apply Rplus_le_compat;\n  assumption. replace (0 + 0) with 0 in H1; [|ring].\n  apply False_ind. eapply Rlt_not_le. apply H2. assumption.\n  assert (x / 2 < x). rewrite double_var. apply Rlt_plus_l.\n  assumption. split. apply Rlt_plus_r. assumption. rewrite H0.\n  rewrite Rplus_comm. apply Rplus_lt_le_compat. assumption.\n  apply Rle_refl. Qed. \n\nLemma Rplus_lt_swap_rl : forall (x y z : R),\n  x < y + z -> x - y < z. intros. eapply Rplus_lt_compat_r in H.\n  eapply Rlt_le_trans. unfold Rminus. apply H. apply Req_le.\n  ring. Qed.\n\nLemma Rplus_lt_swap_rr : forall (x y z : R),\n  x < y + z -> x - z < y. intros. rewrite Rplus_comm in H.\n  apply Rplus_lt_swap_rl. assumption. Qed.\n\nLemma Rplus_lt_swap_ll : forall (x y z : R),\n  x + y < z -> y < z - x. intros. eapply Rplus_lt_compat_r in H.\n  unfold Rminus. eapply Rle_lt_trans;[| apply H]. apply Req_le.\n  ring. Qed.  \n\nLemma Rplus_lt_swap_lr : forall (x y z : R),\n  x + y < z -> x < z - y. intros. rewrite Rplus_comm in H.\n  apply Rplus_lt_swap_ll. assumption. Qed.\n\nLemma Rminus_lt_swap_rr : forall (x y z : R),\n  x < y - z -> x + z < y. intros. rewrite <- (Ropp_involutive z).\n  apply Rplus_lt_swap_rr. apply H. Qed.\n\nLemma Rminus_lt_swap_lr : forall (x y z : R),\n  x - y < z -> x < z + y. intros. rewrite <- (Ropp_involutive y).\n  apply Rplus_lt_swap_lr. apply H. Qed.\n\nLemma Rplus_lt_reg_l: forall r r1 r2 : R, r1 + r < r2 + r -> r1 < r2.\n  intros. replace r2 with (r2 + r - r);[ | ring]. apply Rplus_lt_swap_lr.\n  assumption. Qed.\n\nLemma Rplus_lt_reg_r: forall r r1 r2 : R, r + r1 < r + r2 -> r1 < r2.\n  intros. apply (Rplus_lt_reg_l r). my_applys_eq H;ring. Qed.\n\nLemma Rplus_lt_weaken_lr : forall (x y z : R), x + y < z -> 0 <= y -> x < z.\n  intros. eapply Rle_lt_trans;[ |apply H]. apply Rle_plus_r. assumption. Qed.\n\nLemma Rplus_lt_weaken_ll : forall (x y z : R), x + y < z -> 0 <= x -> y < z.\n  intros. rewrite Rplus_comm in H. eapply Rplus_lt_weaken_lr. apply H. assumption.\n  Qed.\n\nLemma Rplus_lt_weaken_rr : forall (x y z : R), 0 <= z -> x < y -> x < y + z.\n  intros. replace x with (x + 0). eapply Rplus_lt_le_compat; assumption.\n  ring. Qed.\n\nLemma Rplus_lt_weaken_rl : forall (x y z : R), 0 <= y -> x < z -> x < y + z.\n  intros. rewrite Rplus_comm. apply Rplus_lt_weaken_rr;assumption. Qed.\n\nLemma Rminus_lt_weaken_lr : forall (x y z : R), 0 <= y -> x < z -> x - y < z.\n  intros. replace z with (z - 0);[ | ring]. eapply Rplus_lt_le_compat.\n  assumption. apply Ropp_le_contravar. assumption. Qed.\n\n(** Tries to solve an inequality on real numbers.*) \nLtac Rplus_lt_tac := \n  match goal with\n  | [ H1 : ?r1 < ?r3, H2 : ?r2 < ?r4 |- ?r1 + ?r2 < ?r3 + ?r4] =>\n    apply Rplus_lt_compat;[apply H1 | apply H2]\n  | [ H1 : ?r1 <= ?r3, H2 : ?r2 < ?r4 |- ?r1 + ?r2 < ?r3 + ?r4] =>\n    apply Rplus_le_lt_compat;[apply H1 | apply H2]\n  | [ H1 : ?r1 < ?r3, H2 : ?r2 <= ?r4 |- ?r1 + ?r2 < ?r3 + ?r4] =>\n    apply Rplus_lt_le_compat;[apply H1 | apply H2]\n  | [ H1 : ?r1 < ?r3, H2 : ?r2 < ?r4 |- ?r2 + ?r1 < ?r3 + ?r4] =>\n    rewrite Rplus_comm; apply Rplus_lt_compat;[apply H1 | apply H2]\n  | [ H1 : ?r1 < ?r2|- ?r + ?r1 < ?r + ?r2] =>\n    apply Rplus_lt_compat_l;apply H1\n  | [ H1 : ?r1 < ?r2|- ?r1 + ?r < ?r2 + ?r] =>\n    apply Rplus_lt_compat_r;apply H1\n  | [ H : ?r1 + ?r < ?r2 + ?r |- ?r1 < ?r2] =>\n    apply Rplus_lt_reg_l in H; assumption\n  | [ H : ?r + ?r1 < ?r + ?r2 |- ?r1 < ?r2] =>\n    apply Rplus_lt_reg_r in H; assumption\n  | [ H : ?x < ?y + ?z |- ?x - ?z < ?y] =>\n    apply Rplus_lt_swap_rr; assumption\n  | [ H : ?x + ?y < ?z |- ?y < ?z - ?x] =>\n    apply Rplus_lt_swap_ll; assumption\n  | [ H : ?x < ?y + ?z |- ?x - ?y < ?z] =>\n    apply Rplus_lt_swap_rl; assumption\n  | [ H : ?x + ?y < ?z |- ?x < ?z - ?y] =>\n    apply Rplus_lt_swap_lr; assumption\n  | [ |- ?r1 < ?r1 + _] => apply Rlt_plus_r\n  | [ |- ?r1 < _ + ?r1] => apply Rlt_plus_l\n  | [ H : ?x + ?y < ?z |- ?x < ?z] =>\n    eapply Rplus_lt_weaken_lr; apply H\n  | [ H : ?x + ?y < ?z |- ?y < ?z] =>\n    eapply Rplus_lt_weaken_ll; apply H\n  end.\n\n(** Takes a hypothesis H of type r1 < r2 and gives a hypothesis U of type\nr2 = r1 + d'*)\nLtac Rlttoplus H d' U := let Q1 := fresh in lets Q1 : RltPlusExistsL H;\n  let U1 := fresh U in let U2 := fresh U in decompExAnd Q1 d' U1 U2.\n", "meta": {"author": "ColmBhandal", "repo": "PhD-Formalilsing-Comhordu", "sha": "7f31dbc4a9a205b3b722cff30e79442922e0f9c9", "save_path": "github-repos/coq/ColmBhandal-PhD-Formalilsing-Comhordu", "path": "github-repos/coq/ColmBhandal-PhD-Formalilsing-Comhordu/PhD-Formalilsing-Comhordu-7f31dbc4a9a205b3b722cff30e79442922e0f9c9/src/RInequalities.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6509554164997416}}
{"text": "Require Import QFacts QArith Qcanon.\n\nRequire Import FunctionalExtensionality.\n\n(** Non-negative rational numbers *)\n(** Nothing here should be too surprising.\n    Non-negative rationals, [Qnn] are represented by rational numbers\n    in reduced form together with proofs that the rational numbers\n    are non-negative. Using functional extensionality, these numbers\n    are Leibniz equal whenever the rational numbers they represent are equal.\n\n    There is a subtraction operation, [Qnnminus], which implements\n    a truncated subtraction; if the result should have been negative, it will\n    instead be zero. Lemmas show that it behaves nicely when we indeed\n    subtracted a smaller number from a larger one.\n\n    Division in [Qnn] is handled as in [Qc]: we arbitrarily have 0 / 0 = 0.\n\n    We prove [Qnn] forms a semiring.\n\n    Many definitions and lemmas from [Qc] are essentially reproduced, perhaps\n    in an alterned form for the modified settings where all numbers are \n    non-negative.\n\n    Axioms required:\n    - functional extensionality: the proof of less-than-or-equal\n      for [Z] is a negation, and to prove that any two negations are equal,\n      we require functional extensionality.  *)\n\nRecord Qnn :=\n  { qnn :> Qc\n  ; nonneg : 0 <= qnn\n  }.\n\nLocal Open Scope Z.\n\n(** Proof irrelevance for <= on [Z], assuming\n    functional extensionality. *)\nTheorem Zle_irrel {x y : Z} (prf1 prf2 : x <= y) :\n  prf1 = prf2. \nProof. unfold Z.le in *.\nextensionality z; contradiction.\nQed.\n\nLocal Close Scope Z.\nLocal Close Scope Qc.\n\nDefinition Qle_irrel {x y : Q} (prf1 prf2 : x <= y)\n  : prf1 = prf2 := Zle_irrel prf1 prf2.\n\nLocal Open Scope Qc.\nDefinition Qcle_irrel {x y : Qc} (prf1 prf2 : x <= y)\n  : prf1 = prf2 := Qle_irrel prf1 prf2.\n\n(** Comparison operators for [Qnn] simply reduce to those for\n    [Qc]. *)\nDefinition Qnnle (x y : Qnn) : Prop := x <= y.\nDefinition Qnnge (x y : Qnn) : Prop := Qnnle y x.\nDefinition Qnnlt (x y : Qnn) : Prop := x < y.\nDefinition Qnngt (x y : Qnn) : Prop := Qnnlt y x.\n\nDefinition Qnneq (x y : Qnn) : Prop := qnn x = qnn y.\n\nDefinition Qnnplus (x y : Qnn) : Qnn.\nProof.\nrefine ({| qnn := x + y |}).\nabstract (replace 0 with (0 + 0) by field;\napply Qcplus_le_compat; destruct x, y; assumption).\nDefined.\n\nDefinition Qnnmult (x y : Qnn) : Qnn.\nProof.\nrefine ({| qnn := x * y |}).\nabstract (\nreplace 0 with (0 * y) by field;\napply Qcmult_le_compat_r; apply nonneg).\nDefined.\n\nDefinition Qnnzero : Qnn := Build_Qnn 0%Qc (Qcle_refl 0%Qc).\n\nLtac makeQnn q := apply (Build_Qnn q); \n  abstract (unfold Qcle, Qle, Z.le; simpl; congruence).\n\nDefinition Qnnone : Qnn.\nProof. makeQnn 1.\nDefined.\n\nDefinition Qnnonehalf : Qnn.\nProof. makeQnn (Qcmake (1 # 2) eq_refl).\nDefined.\n\n(** If two [Qnn]s have the same [Qc] values, they are\n    Leibniz equal. *)\nTheorem Qnneq_prop {x y : Qnn} :\n  Qnneq x y -> x = y.\nProof. intros. destruct x, y. unfold Qnneq in H. simpl in H.\ninduction H. replace nonneg0 with nonneg1 by (apply Qcle_irrel).\nreflexivity.\nQed.\n\nInfix \"<=\" := Qnnle   : Qnn_scope.\nInfix \">=\" := Qnnge   : Qnn_scope.\nInfix \"<\"  := Qnnlt   : Qnn_scope.\nInfix \">\"  := Qnngt   : Qnn_scope.\nInfix \"+\"  := Qnnplus : Qnn_scope.\nInfix \"*\"  := Qnnmult : Qnn_scope.\nInfix \"==\" := Qnneq   : Qnn_scope.\n\nNotation \"'0'\" := Qnnzero : Qnn_scope.\nNotation \"'1'\" := Qnnone  : Qnn_scope.\n\nRequire Import Ring.\n\nLocal Close Scope Q.\nLocal Close Scope Qc.\n\nDelimit Scope Qnn_scope with Qnn.\n\nLocal Open Scope Qnn.\n\nRequire Import QArith.Qminmax.\n\nDefinition Qnn_truncate (q : Q) : Qnn.\nProof.\nrefine {| qnn := !! (Qmax 0 q) |}.\nunfold Qcle. simpl. rewrite Qred_correct.\napply Q.le_max_l.\nDefined.\n\n(** Non-negative rational numbers form a semiring *)\nTheorem Qnnsrt : semi_ring_theory 0 1\n  Qnnplus Qnnmult eq.\nProof.\nconstructor; intros;\n  match goal with\n  | [  |- _ = _ ] => apply Qnneq_prop; unfold Qnneq\n  end;\n  try solve[simpl; field].\nQed.\n\nAdd Ring Qnn_Ring : Qnnsrt.\n\nTheorem Qnn_zero_prop {x : Qnn} :\n  x <= 0 -> x = Qnnzero.\nProof.\nintros. apply Qnneq_prop. unfold Qnneq.\nunfold Qnnzero. simpl. apply Qcle_antisym.\nassumption. apply nonneg.\nQed.\n\nLemma Qnnle_refl (x : Qnn) : x <= x.\nProof. apply Qcle_refl. Qed.\n\nLemma Qnnle_trans {x y z : Qnn}\n  : x <= y -> y <= z -> x <= z.\nProof. intros. eapply Qcle_trans; eassumption. Qed.\n\nInstance Qnnle_preorder : PreOrder Qnnle.\nProof.\nconstructor.\n- unfold Reflexive. apply Qnnle_refl.\n- unfold Transitive. apply @Qnnle_trans.\nQed.\n\nLemma Qnnle_antisym {x y : Qnn}\n  : x <= y -> y <= x -> x = y.\nProof. intros. apply Qnneq_prop. eapply Qcle_antisym; eassumption. Qed.\n\nDefinition Qnnle_irrel {x y : Qnn} (prf1 prf2 : x <= y)\n  : prf1 = prf2 := Qcle_irrel prf1 prf2.\n\nLemma Qnnle_lt_trans : forall x y z : Qnn\n  , x <= y -> y < z -> x < z.\nProof. intros. eapply Qcle_lt_trans; eassumption. Qed.\n\nLemma Qnnlt_le_trans: forall x y z : Qnn\n  , x < y -> y <= z -> x < z.\nProof. intros. eapply Qclt_le_trans; eassumption. Qed.\n\nDefinition Qnncompare (x y : Qnn) := (x ?= y)%Qc.\n\nInfix \"?=\" := Qnncompare : Qnn_scope.\n\nLemma Qnnlt_alt {x y : Qnn} : (x ?= y) = Lt <-> x < y.\nsplit; intros; apply Qclt_alt; assumption.\nQed. \n\nLemma Qnngt_alt {x y : Qnn} : (x ?= y) = Gt <-> x > y.\nsplit; intros; unfold Qnngt; apply Qcgt_alt; assumption.\nQed. \n\nLemma Qnneq_alt {x y : Qnn} : (x ?= y) = Eq <-> x = y.\nsplit; intros. apply Qnneq_prop. apply Qceq_alt; assumption.\napply Qceq_alt. induction H. reflexivity.\nQed. \n\nLemma Qnnmult_le_compat {x y x' y' : Qnn}\n  : x <= x' -> y <= y' -> x * y <= x' * y'.\nProof. intros.\nassert (x * y <= x' * y).\napply Qcmult_le_compat_r. assumption. apply nonneg.\nrewrite H1.\nreplace (x' * y) with (y * x') by ring.\nreplace (x' * y') with (y' * x') by ring.\napply Qcmult_le_compat_r. assumption. apply nonneg.\nQed.\n\nInstance Qnnmult_le_compatI : Proper (Qnnle ==> Qnnle ==> Qnnle) Qnnmult.\nProof.\nunfold Proper, respectful. intros. apply Qnnmult_le_compat; assumption.\nQed.\n\nLemma Qnnlt_zero_prop {q : Qnn} : ~(q < 0).\nProof. unfold not; intros contra.\nassert (q = 0). apply Qnnle_antisym.\napply Qclt_le_weak. assumption.\napply nonneg.\neapply Qclt_not_eq. eassumption.\nrewrite H. reflexivity.\nQed.\n\nDefinition Qnnmax (x y : Qnn) : Qnn := match x ?= y with \n   | Lt => y\n   | Eq => x\n   | Gt => x\n   end.\n\nLemma Qnnmax_induction {x y} (P : Qnn -> Qnn -> Qnn -> Prop) :\n  (y <= x -> P x y x) -> (x <= y -> P x y y) -> P x y (Qnnmax x y).\nProof.\nintros. unfold Qnnmax. destruct (x ?= y) eqn:ceqn. \n  apply H. apply Qnneq_alt in ceqn. rewrite ceqn. apply Qnnle_refl.\n  apply H0. apply Qclt_le_weak. apply Qnnlt_alt. assumption.\n  apply H. apply Qnngt_alt in ceqn. apply Qclt_le_weak. assumption.\nQed.\n\nLemma Qnnmax_mult {x y z} : x * Qnnmax y z = Qnnmax (x * y) (x * z).\nProof. \npattern y, z, (Qnnmax y z). apply Qnnmax_induction; intros.\n- pattern (x * y), (x * z), (Qnnmax (x * y) (x * z)). \n  apply Qnnmax_induction; intros. reflexivity.\n  apply Qnnle_antisym. assumption. apply Qnnmult_le_compat.\n  reflexivity. assumption.\n- pattern (x * y), (x * z), (Qnnmax (x * y) (x * z)). \n  apply Qnnmax_induction; intros.\n  apply Qnnle_antisym. assumption. apply Qnnmult_le_compat.\n  reflexivity. assumption. reflexivity.\nQed.\n\nLemma Qnnmax_l {x y} : x <= Qnnmax x y.\nProof. unfold Qnnmax; simpl. destruct (x ?= y) eqn:compare; simpl. \n- reflexivity.\n- apply Qclt_le_weak. apply Qnnlt_alt. assumption.\n- reflexivity.\nQed.\n\nLemma Qnnmax_r {x y} : y <= Qnnmax x y.\nProof. unfold Qnnmax; simpl. destruct (x ?= y) eqn:compare; simpl. \n- apply Qnneq_alt in compare. induction compare. reflexivity.\n- reflexivity. \n- apply Qclt_le_weak. apply Qnngt_alt. assumption.\nQed.\n\nLemma Qnninv_nonneg (x : Qnn) : (0 <= / x)%Qc.\nProof.\ndestruct (x ?= 0) eqn:comp. apply Qnneq_alt in comp.\nsubst. simpl. apply Qle_refl.\napply Qnnlt_alt in comp. apply Qnnlt_zero_prop in comp.\ncontradiction.\nunfold Qcle. \nsetoid_replace (this (/ x)%Qc) with (/ x)%Q by apply Qred_correct.\napply Qinv_le_0_compat. apply nonneg.\nQed.\n\nDefinition Qnninv (x : Qnn) : Qnn :=\n  {| qnn := (/ x)%Qc\n   ; nonneg := Qnninv_nonneg x\n  |}.\n\nNotation \"/ x\" := (Qnninv x) : Qnn_scope.\n\nLemma Qnn_dec (x y : Qnn) : {x < y} + {y < x} + {x = y}.\nProof. destruct (Qc_dec x y).\nleft. destruct s. left. assumption. right. assumption.\nright. apply Qnneq_prop. assumption.\nQed. \n\nLemma Qnnzero_prop2 (x : Qnn) : x > 0 <-> x <> 0.\nProof.\nsplit; intros. unfold not. intros contra. subst. \napply Qnnlt_zero_prop in H. assumption.\ndestruct (Qnn_dec x 0). destruct s.\napply Qnnlt_zero_prop in q. contradiction. assumption.\nsubst. unfold not in H. pose proof (H eq_refl). contradiction.\nQed.\n\nLemma Qnnmult_inv_r (x : Qnn) :\n  x > 0 -> x * Qnninv x = 1.\nProof. intros. \napply Qnneq_prop. apply Qcmult_inv_r. apply Qnnzero_prop2 in H.\nunfold not. intros contra. assert (x = 0). apply Qnneq_prop. assumption.\ncontradiction. \nQed.\n\n\nLemma Qnninv_zero1 {x : Qnn} : / x = 0 -> x = 0.\nProof. intros. destruct (x ?= 0) eqn:comp.\napply Qnneq_alt in comp. assumption.\napply Qnnle_antisym. apply Qclt_le_weak. assumption. apply nonneg.\napply Qnngt_alt in comp. replace x with (x * 1) by ring.\nreplace 1 with (Qnninv x * x). rewrite H. ring.\nrewrite (SRmul_comm Qnnsrt).\napply Qnnmult_inv_r. assumption.\nQed. \n\nLemma Qnninv_zero2 {x : Qnn} : 0 < x -> 0 < / x.\nProof. intros. apply Qnnzero_prop2. unfold not. intros contra.\napply Qnninv_zero1 in contra. subst. apply Qnnzero_prop2 in H. \nunfold not in H. apply H. reflexivity. \nQed.\n\nDefinition Qnndiv (x y : Qnn) : Qnn := x * / y.\n\nInfix \"/\" := Qnndiv : Qnn_scope.\n\nLemma Qnndiv_lt (num denom : Qnn) : num < denom -> num / denom < 1.\nProof. intros. unfold Qnndiv.\ndestruct (num ?= 0) eqn:comp. apply Qnneq_alt in comp.\nsubst. replace (0 * / denom) with 0 by ring. unfold Qnnlt. \napply Qclt_alt. reflexivity.\n\napply Qnnlt_alt in comp. apply Qnnlt_zero_prop in comp. contradiction.\n\napply Qnngt_alt in comp. replace 1 with (denom * / denom).\napply Qcmult_lt_compat_r.\napply Qnninv_zero2. eapply Qnnle_lt_trans. apply (nonneg num). assumption.\nassumption. \napply Qnnmult_inv_r. eapply Qnnle_lt_trans. apply (nonneg num). assumption.\nQed. \n\nLtac reduceQ := repeat (unfold Qcplus, Qcdiv, Qcinv, Qcmult; \nmatch goal with\n| [ |- context[this (Q2Qc ?x)%Qc] ] => \n     setoid_replace (this (Q2Qc x)%Qc) with x by (apply Qred_correct)\nend).\n\n\nDefinition Qcaverage (x z : Qc) : (x < z)%Qc\n  -> (let avg := ((x + z) / (1 + 1)) in x < avg /\\ avg < z)%Qc.\nProof. intros. destruct (Qaverage x z H).\nassert ((this avg == (x + z) / (1 + 1))%Q). \nunfold avg. reduceQ. reflexivity.\nunfold Qclt. split; setoid_rewrite H2; assumption.\nQed. \n\nDefinition Qnnaverage (x z : Qnn) : (x < z)\n  -> (let avg := ((x + z) * Qnnonehalf) in x < avg /\\ avg < z).\nProof. intros.\npose proof (Qcaverage x z H).\nassert (qnn avg = ((x + z) / (1 + 1))%Qc).\nunfold avg. unfold Qcdiv. unfold Qnnmult. simpl. reflexivity.\nunfold Qnnlt; rewrite H1. assumption.\nQed.\n\nDefinition Qcbetween (x z : Qc) : (x < z)%Qc\n  -> { y | (x < y /\\ y < z)%Qc }.\nProof. intros. eexists. apply Qcaverage. assumption.\nQed.\n\nDefinition Qnnbetween (x z : Qnn) : (x < z)\n  -> { y | x < y /\\ y < z }.\nProof. intros. eexists. apply Qnnaverage. assumption.\nQed.\n\nDefinition Qnnplus_le_lt_compat {x x' y y' : Qnn}\n  : x <= x' -> y < y' -> x + y < x' + y'.\nProof.\nintros.\napply Qclt_minus_iff. simpl.\neapply Qclt_le_trans.\napply Qclt_minus_iff in H0. eassumption.\nreplace (x' + y' + - (x + y))%Qc with (y' + - y + (x' + - x))%Qc by ring.\nreplace (y' + -y)%Qc with (y' + -y + 0)%Qc at 1 by ring.\napply Qcplus_le_compat. apply Qcle_refl.\napply -> Qcle_minus_iff. assumption.\nQed.\n\nLemma Qnnlt_le_weak {x y : Qnn}\n  : x < y -> x <= y.\nProof. apply Qclt_le_weak. Qed.\n\nInstance Qnnlt_le_subrelation : subrelation Qnnlt Qnnle.\nProof.\nunfold subrelation, predicate_implication, pointwise_lifting,\n  Basics.impl.\napply @Qnnlt_le_weak.\nQed.\n\nLemma Qnnmult_lt_compat_r {x y z : Qnn}\n  : 0 < z -> x < y -> x * z < y * z.\nProof. apply Qcmult_lt_compat_r. Qed.\n\nLemma Qnnlt_not_le {x y : Qnn}\n  : x < y -> ~ y <= x.\nProof. apply Qclt_not_le. Qed.\n\nLemma Qnnplus_le_compat {x x' y y' : Qnn}\n  : x <= x' -> y <= y' -> x + y <= x' + y'.\nProof. apply Qcplus_le_compat. Qed.\n\nInstance Qnnplus_le_compatI : Proper (Qnnle ==> Qnnle ==> Qnnle) Qnnplus.\nProof.\nunfold Proper, respectful.\nintros. apply Qnnplus_le_compat; assumption.\nQed.\n\nDefinition Qnnmin (x y : Qnn) : Qnn := match (x ?= y) with \n   | Lt => x\n   | Eq => x\n   | Gt => y\n   end.\n\nLemma Qnnmin_l {x y} : (Qnnmin x y <= x)%Qnn.\nProof. unfold Qnnmin; simpl. destruct (x ?= y) eqn:compare; simpl. \n- reflexivity.\n- reflexivity. \n- apply Qclt_le_weak. apply Qnngt_alt. assumption.\nQed.\n\nLemma Qnnmin_r {x y} : Qnnmin x y <= y.\nProof. unfold Qnnmin; simpl. destruct (x ?= y) eqn:compare; simpl. \n- apply Qnneq_alt in compare. induction compare. reflexivity.\n- apply Qclt_le_weak. apply Qnnlt_alt. assumption.\n- reflexivity.\nQed.\n\nLemma Qnnmin_le_both {z x y} : \n  z <= x -> z <= y -> z <= Qnnmin x y.\nProof. intros. unfold Qnnmin; simpl. destruct (x ?= y) eqn:compare;\nunfold Qnnle; simpl; assumption.\nQed.\n\nLemma Qnnmin_lt_both {z x y} : \n  z < x -> z < y -> z < Qnnmin x y.\nProof. intros. unfold Qnnmin; simpl. destruct (x ?= y) eqn:compare;\nunfold Qnnle; simpl; assumption.\nQed.\n\nLemma Qnnminus_nonneg (x y : Qnn) : (0 <=  match (x ?= y)%Qnn with\n   | Lt => 0%Qnn\n   | Eq => 0%Qnn\n   | Gt => (x - y)%Qc\n   end)%Qc.\nProof.\ndestruct (x ?= y)%Qnn eqn:destr.\n- apply nonneg.\n- apply nonneg.\n- apply -> Qcle_minus_iff.\n  apply Qnnlt_le_weak. apply Qnngt_alt.\n  assumption.\nQed.\n\nDefinition Qnnminus (x y : Qnn) : Qnn :=\n  {| qnn := match (x ?= y)%Qnn with\n   | Lt => 0%Qnn\n   | Eq => 0%Qnn\n   | Gt => (x - y)%Qc\n   end\n   ;  nonneg := Qnnminus_nonneg x y\n  |}.\n\nInfix \"-\" := Qnnminus : Qnn_scope.\n\nLemma Qnnminus_Qc {x y : Qnn} : y <= x ->\n  qnn (x - y) = (qnn x - qnn y)%Qc.\nProof.\nintros ylex. simpl.\ndestruct (x ?= y) eqn:destr; simpl.\n- apply Qnneq_alt in destr. subst. ring.\n- apply Qnnlt_alt in destr.\n  apply Qnnlt_not_le in destr.\n  specialize (destr ylex). contradiction.\n- reflexivity.\nQed.\n\nDefinition Qnnminusp (x y : Qnn) (prf : y <= x) : Qnn.\nProof. refine (\n  {| qnn := x - y |}\n). abstract (apply -> Qcle_minus_iff; assumption).\nDefined. \n\nDefinition Qnnminusp_irrel {x y : Qnn} {p q : y <= x}\n  : Qnnminusp x y p = Qnnminusp x y q.\nProof.\napply Qnneq_prop. unfold Qnneq. simpl. reflexivity.\nQed.\n\nLemma Qnnminus_equiv {x y : Qnn} {ylex : y <= x}\n  : Qnnminusp x y ylex = Qnnminus x y.\nProof.\napply Qnneq_prop. unfold Qnneq. symmetry. apply Qnnminus_Qc.\nassumption.\nQed.\n\nFixpoint Qnnpow (b : Qnn) (e : nat) := match e with\n  | 0 => 1\n  | S e' => b * Qnnpow b e'\n  end.\n\nInfix \"^\"  := Qnnpow : Qnn_scope.\n\nLemma Qnnpow_Qc : forall (b : Qnn) (e : nat),\n  qnn (b ^ e) = ((qnn b) ^ e)%Qc.\nProof.\nintros. induction e; simpl.\n- reflexivity. \n- rewrite IHe. reflexivity.\nQed.\n\nLemma Qnnpow_le {x : Qnn} {n : nat} :\n  x <= 1 -> x ^ n <= 1.\nProof.\nintros. induction n; simpl. reflexivity.\nreplace 1 with (1 * 1) by ring.\napply Qnnmult_le_compat; assumption.\nQed.\n\nLemma Qnnminus_le {x y z : Qnn} : y <= x \n  -> (x - y <= z <-> x <= y + z).\nProof.\nsplit; intros. \n- unfold Qnnle. apply Qcle_minus_iff. simpl.\n  replace (y + z + - x)%Qc with (z - (x - y))%Qc by ring.\n  apply -> Qcle_minus_iff. rewrite <- Qnnminus_Qc by assumption. \n  apply H0.\n- unfold Qnnle. rewrite Qnnminus_Qc by assumption. \n  apply Qcle_minus_iff. simpl.\n  replace (z + - (x - y))%Qc with (y + z - x)%Qc by ring.\n  apply -> Qcle_minus_iff. apply H0. \nQed.\n\nLemma Qnnminus_lt_l {x y z : Qnn} : (y <= x)\n  -> (x - y < z <-> x < y + z).\nProof.\nsplit; intros. \n- unfold Qnnle. apply Qclt_minus_iff. simpl.\n  replace (y + z + - x)%Qc with (z - (x - y))%Qc by ring.\n  apply -> Qclt_minus_iff. \n  rewrite <- Qnnminus_Qc by assumption.\n  apply H0.\n- apply Qclt_minus_iff. rewrite Qnnminus_Qc by assumption.\n  replace (z + - (x - y))%Qc with (y + z - x)%Qc by ring.\n  apply -> Qclt_minus_iff. apply H0. \nQed.\n\nLemma Qnnminus_lt_r {x y z : Qnn} : y <= x\n  -> (z < x - y <-> y + z < x).\nProof.\nsplit; intros. \n- unfold Qnnlt. apply Qclt_minus_iff. simpl.\n  replace (x + - (y + z))%Qc with ((x - y) - z)%Qc by ring.\n  apply -> Qclt_minus_iff. \n  rewrite <- Qnnminus_Qc by assumption.\n  apply H0.\n- unfold Qnnlt. apply Qclt_minus_iff. \n  rewrite Qnnminus_Qc by assumption. \n  replace (x - y + - z)%Qc with (x - (y + z))%Qc by ring.\n  apply -> Qclt_minus_iff. apply H0. \nQed.\n\n\nLemma Qnnminus_plus {x y : Qnn}\n  : x <= y -> (x + (y - x)) = y.\nProof.\n  intros. apply Qnneq_prop. unfold Qnneq.\n  replace (qnn (x + (y - x))) \n  with (qnn x + qnn (y - x)%Qnn)%Qc by reflexivity. \n  rewrite Qnnminus_Qc by assumption. ring.\nQed.\n\nLemma Qnnminus_mult_distr {c x y : Qnn}\n  : (y <= x) -> c * (x - y) = c * x - c * y.\nProof.\nintros. apply Qnneq_prop. unfold Qnneq. simpl.\ndestruct (x ?= y)%Qnn eqn:xy;\ndestruct (c * x ?= c * y)%Qnn eqn:cxcy;\ntry ring.\nrewrite Qnneq_alt in xy. subst. rewrite Qnngt_alt in cxcy.\napply Qnnlt_not_le in cxcy. apply False_rect. apply cxcy.\nreflexivity.\napply Qnnlt_alt in xy. apply Qnnlt_not_le in xy.\nspecialize (xy H). contradiction.\napply Qnneq_alt in cxcy.\ndestruct (Qnn_dec c 0). destruct s. apply Qnnlt_zero_prop in q.\ncontradiction.\nrewrite Qnngt_alt in xy.\nassert (y * c < x * c).\napply Qnnmult_lt_compat_r. assumption. \nunfold Qnngt in xy. assumption.\napply Qnnlt_not_le in H0. apply False_rect. apply H0.\nreplace (x * c) with (c * x) by ring.\nreplace (y * c) with (c * y) by ring.\nrewrite cxcy. reflexivity.\nsubst. simpl. ring. apply Qnnlt_alt in cxcy. \nassert (x < y)%Qnn. replace x with (x * 1) by ring.\nreplace y with (y * 1)%Qnn by ring.\nrewrite <- (Qnnmult_inv_r c).\nrepeat rewrite (SRmul_assoc Qnnsrt).\napply Qnnmult_lt_compat_r.\napply Qnnlt_alt in cxcy. \napply Qnninv_zero2.\ndestruct (Qnn_dec c 0). destruct s.\napply Qnnlt_not_le in q. apply False_rect. apply q. apply nonneg.\nassumption. subst. apply Qnnlt_not_le in cxcy.\napply False_rect. apply cxcy. ring_simplify. reflexivity.\nrewrite (SRmul_comm Qnnsrt x). \nrewrite (SRmul_comm Qnnsrt y). \napply Qnnlt_alt in cxcy. apply cxcy.\ndestruct (Qnn_dec c 0).\ndestruct s. apply Qnnlt_zero_prop in q. contradiction.\nassumption. subst. apply Qnnlt_not_le in cxcy.\napply False_rect. apply cxcy. ring_simplify. reflexivity.\napply Qnnlt_not_le in H0. specialize (H0 H). contradiction.\nQed.\n\nLemma Qnnminus_plus2 {x y : Qnn}\n  : ((x + y) - y = x)%Qnn .\nProof.\napply Qnneq_prop. unfold Qnneq.\nrewrite Qnnminus_Qc. simpl. ring.\nreplace y with (0 + y)%Qnn at 1 by ring.\napply Qnnplus_le_compat. apply nonneg. reflexivity.\nQed.\n\n\nLemma Qnnminus_eq {x y : Qnn}\n  : (y <= x)%Qnn -> forall z, ((x - y = z)%Qnn <-> (x = y + z)%Qnn).\nProof.\nintros. split; intros.\n- rewrite <- H0. rewrite Qnnminus_plus. reflexivity. assumption. \n- rewrite H0 in *. rewrite (SRadd_comm Qnnsrt). \n  apply Qnnminus_plus2.\nQed.\n\nLemma Qnnminus_plus_distr {x y a b : Qnn}\n  : (a <= x -> b <= y -> \n    x - a + (y - b)\n  = (x + y) - (a + b))%Qnn.\nProof.\nintros.\nsymmetry. rewrite Qnnminus_eq.\nreplace (a + b + (x - a + (y - b)))%Qnn\nwith ((a + (x - a)) + (b + (y - b)))%Qnn by ring.\ndo 2 rewrite Qnnminus_plus by assumption. reflexivity. \napply Qnnplus_le_compat; assumption.\nQed.\n\nLemma Qnnonehalf_split {x : Qnn}\n  : (x = (x + x) * Qnnonehalf)%Qnn.\nProof. \nunfold Qnnonehalf. apply Qnneq_prop. unfold Qnnmult, Qnnplus.\nsimpl. unfold Qnneq. simpl. apply Qc_is_canon. reduceQ.\nsimpl. field.\nQed.\n\nLemma redistribute_onehalf : forall q x y,\n (   (q + (x + y)) * Qnnonehalf\n  = (q * Qnnonehalf + x) * Qnnonehalf + (q * Qnnonehalf + y) * Qnnonehalf\n  )%Qnn.\nProof.\nintros. rewrite (@Qnnonehalf_split q) at 1. ring. \nQed.\n\nFixpoint Qnnnat (n : nat) : Qnn := match n with \n  | 0 => 0%Qnn\n  | S n' => (1 + Qnnnat n')%Qnn\n  end.\n\nDefinition Qnnfrac (n : nat) := / (Qnnnat n).\n\nLemma Qnnnatfrac {n : nat} : (Qnnnat (S n) * Qnnfrac (S n) = 1)%Qnn.\nProof. unfold Qnnfrac. apply Qnnmult_inv_r. simpl.\nreplace 0%Qnn with (0 + 0)%Qnn by ring.\nreplace (1 + Qnnnat n)%Qnn with (Qnnnat n + 1)%Qnn by ring.\napply Qnnplus_le_lt_compat. apply nonneg.\napply Qnnlt_alt. reflexivity.\nQed.\n\nLemma Qnnnat_plus {x y : nat} : (Qnnnat (x + y) = Qnnnat x + Qnnnat y)%Qnn.\nProof.\ninduction x.\n- simpl; ring.\n- simpl. rewrite IHx. ring.\nQed.\n\nRequire Import clement.SmallPowers.\nLocal Close Scope Qc.\nLocal Close Scope Q.\n\nLemma smallPowers {p : Qnn} : p < 1\n  -> forall (q : Qnn), (q > 0)\n  -> exists (n : nat), (p ^ n < q).\nProof.\nintros.\ndestruct (power_small p q (nonneg p) H H0).\nexists x. unfold Qnnlt. rewrite Qnnpow_Qc. assumption.\nQed.\n\nLemma Qnnplus_open {q x y : Qnn} : q < x + y\n  -> 0 < x -> 0 < y\n  -> exists x' y', x' < x /\\ y' < y /\\ (q <= x' + y').\nProof.\nintros. \npose (((x + y) - q) * Qnnonehalf)%Qnn as eps.\npose (Qnnmin eps (Qnnmin x y)) as eps'.\nexists (x - eps'). exists (y - eps').\nassert (0 < eps)%Qnn. unfold eps.\nreplace 0%Qnn with (0 * Qnnonehalf)%Qnn by ring.\napply Qnnmult_lt_compat_r. rewrite <- Qnnlt_alt.\nreflexivity. apply Qnnminus_lt_r. apply Qnnlt_le_weak.\nassumption. ring_simplify. assumption.\nassert (0 < eps')%Qnn.\napply Qnnmin_lt_both. assumption. apply Qnnmin_lt_both; assumption.\nassert (eps' <= x)%Qnn. unfold eps'. rewrite Qnnmin_r. apply Qnnmin_l.\nassert (eps' <= y)%Qnn. unfold eps'. rewrite Qnnmin_r. apply Qnnmin_r. \nsplit.\n  simpl. apply Qnnminus_lt_l. assumption.\n  replace x with (x + 0)%Qnn at 1 by ring.\n  replace (eps' + x)%Qnn with (x + eps')%Qnn by ring.\n  apply Qnnplus_le_lt_compat. reflexivity.\n  assumption.\nsplit. \n  simpl. apply Qnnminus_lt_l. assumption.\n  replace y with (y + 0)%Qnn at 1 by ring.\n  replace (eps' + y)%Qnn with (y + eps')%Qnn by ring.\n  apply Qnnplus_le_lt_compat. reflexivity.\n  assumption.\nrewrite (@Qnnonehalf_split q).\nreplace ((q + q) * Qnnonehalf)%Qnn\n  with (q * Qnnonehalf + q * Qnnonehalf)%Qnn by ring.\napply Qnnplus_le_compat.\nadmit. admit.\nAdmitted.\n\nLemma Qnnmult_open {q x y : Qnn} : q < x * y\n  -> exists x' y', x' < x /\\ y' < y /\\ (q <= x' * y').\nProof.\nAdmitted.\n\n", "meta": {"author": "bmsherman", "repo": "numbers", "sha": "412568157cfc9c3be0c6212a7c6692a8bfc802c1", "save_path": "github-repos/coq/bmsherman-numbers", "path": "github-repos/coq/bmsherman-numbers/numbers-412568157cfc9c3be0c6212a7c6692a8bfc802c1/Qnn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.6509554164288822}}
{"text": "Module Turing.\n\nRequire Import List.\nRequire Import EqNat.\n\n\nInductive Direction :=\n\tLeft | Right.\n\n(* A single step in each evaluation of a machine. *)\nInductive Step (State : Set) :=\n\t| StepDo : nat -> State -> Direction -> Step State\n\t| StepHalt : Step State.\n\n(* a total mapping from State*Symbol to a Step. *)\nDefinition Stepper (State : Set) :=\n\tState -> nat -> Step State.\n\n\n(* Our infinitely long tape, and its read head.\nThere are symbols to the left and symbols to the right.\nIt also has a default symbol that the whole thing is initialised to. *)\nInductive Tape : Set :=\n\tTTape : nat -> list nat -> list nat -> Tape.\n\n(* Get the value at the tapehead *)\nDefinition get (t : Tape) :=\n\tmatch t with\n\t| TTape default nil _ => default\n\t| TTape _ (x::_) _ => x\n\tend.\n\n(* Replace value at tapehead, producing new tape *)\nDefinition write (t : Tape) (s : nat) :=\n\tmatch t with\n\t| TTape d nil rs => TTape d (s::nil) rs\n\t| TTape d (_::ls) rs => TTape d (s::ls) rs\n\tend.\n\n(* Move tapehead to left *)\nDefinition move_left (t : Tape) :=\n\tmatch t with\n\t| TTape default nil rs => TTape default nil (default :: rs)\n\t| TTape default (l::ls) rs => TTape default ls (l::rs)\n\tend.\n\nDefinition move_right (t : Tape) :=\n\tmatch t with\n\t| TTape default ls nil => TTape default (default :: ls) nil\n\t| TTape default ls (r::rs) => TTape default (r::ls) rs\n\tend.\n\nDefinition move (t : Tape) (d : Direction) :=\n\tmatch d with\n\t| Left => move_left t\n\t| Right => move_right t\n\tend.\n\nDefinition empty (default : nat) :=\n\tTTape default nil nil.\n\n(* What do we know about our infinite tape? *)\n\n(* How do we say that two tapes are equivalent?\nChop any defaults off the ends and then compare? *)\n\nDefinition chopList (d : nat) (l : list nat) :=\n\tlet fix go l' :=\n\t\tmatch l' with\n\t\t| nil => nil\n\t\t| x::xs =>\n\t\t\tmatch beq_nat x d with\n\t\t\t| true => go xs\n\t\t\t| false => x::xs\n\t\t\tend\n\t\tend\n\tin rev (go (rev l)).\n\nDefinition chop (t : Tape) :=\n\tmatch t with\n\t| TTape d ls rs => TTape d (chopList d ls) (chopList d rs)\n\tend.\n\nDefinition equiv (l r : Tape) :=\n\tchop l = chop r.\n\nNotation \"l ~= r\" := (equiv l r) (at level 70).\n\nTheorem chopList_one (d : nat) :\n\tchopList d (d::nil) = nil.\nProof.\n  intros. unfold chopList. simpl.\n  rewrite <- beq_nat_refl.\n  reflexivity.\nQed.\n\n(* left.right = id *)\nTheorem tape_lr_id (t : Tape) :\n\tmove_left (move_right t) ~= t.\nProof.\n  intros. unfold equiv.\n  destruct t; destruct l0; simpl.\n    rewrite chopList_one. reflexivity.\n    reflexivity.\nQed.\n\nTheorem tape_rl_id (t : Tape) :\n\tmove_right (move_left t) ~= t.\nProof.\n  intros. unfold equiv.\n  destruct t; destruct l; simpl.\n    rewrite chopList_one. reflexivity.\n    reflexivity.\nQed.\n\n(* write.write = write *)\nTheorem tape_ww (t : Tape) (s1 s2 : nat) :\n\twrite (write t s2) s1 ~= write t s1.\nProof.\n  intros. unfold equiv.\n  destruct t; destruct l; auto.\nQed.\n\n(* The whole thing, with current state, tape and a stepper function *)\nInductive Machine (State : Set) : Set :=\n\tMMachine : State\n\t\t\t-> Tape\n\t\t\t-> Stepper State\n\t\t\t-> Machine State.\n\nDefinition step {State : Set}\n\t(m : Machine State) :=\n\tmatch m with\n\t| MMachine state tape stepper =>\n\t\tmatch stepper state (get tape) with\n\t\t| StepDo sy st' dir  =>\n\t\t\tSome (MMachine _ st' (move (write tape sy) dir) stepper)\n\t\t| StepHalt => None\n\t\tend\n\tend.\n\n\n(* fill *)\nModule Fill.\n  Inductive FState := FLeft | FRight.\n  \n  Definition stepper : Stepper FState :=\n    fun st => fun sym =>\n      match st with\n      | FLeft =>\n        match sym with\n        | 0 => StepDo _ 0 FRight Right\n        | 1 => StepDo _ 1 FLeft Left\n        | _ => StepHalt _\n        end\n      | FRight =>\n        match sym with\n        | 0 => StepDo _ 1 FLeft Left\n        | 1 => StepDo _ 1 FRight Right\n        | _ => StepHalt _\n        end\n      end.\n  \n  Definition machine := MMachine _ FRight (empty 0) stepper.\n\n  Eval compute in step machine.\nEnd Fill.\n", "meta": {"author": "amosr", "repo": "coq", "sha": "7e8c28e2222d897884880c21ff71d29799e5b1f5", "save_path": "github-repos/coq/amosr-coq", "path": "github-repos/coq/amosr-coq/coq-7e8c28e2222d897884880c21ff71d29799e5b1f5/turing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6508924089929201}}
{"text": "Inductive Dir : Type :=\n| L\n| R.\n\nInductive Connective : Type :=\n| Impl\n| Or\n| And\n| Iff\n| Xor\n| Nimpl\n| Nor\n| Nand.\n\nDefinition con (c : Connective) (P Q : Prop) : Prop :=\nmatch c with\n| Impl  => P -> Q\n| Or    => P \\/ Q\n| And   => P /\\ Q\n| Iff   => P <-> Q\n| Xor   => (P /\\ ~ Q) \\/ (~ P /\\ Q)\n| Nimpl => ~ (P -> Q)\n| Nor   => ~ (P \\/ Q)\n| Nand  => ~ (P /\\ Q)\nend.\n\nInductive Constant : Type :=\n| Top\n| Bot.\n\nDefinition const (c : Constant) : Prop :=\nmatch c with\n| Top => True\n| Bot => False\nend.\n\nInductive Law1 : Type :=\n| IsC (c : Prop)\n| IsArg\n| IsNeg.\n\nDefinition law1 (l : Law1) (C : Prop -> Prop) : Prop :=\nmatch l with\n| IsC c => forall P : Prop, C P <-> c\n| IsArg => forall P : Prop, C P <-> P\n| IsNeg => forall P : Prop, C P <-> ~ P\nend.\n\nInductive ReflIdem : Type :=\n| Refl\n| Irrefl\n| Idempotent\n| Antiidempotent.\n\nDefinition reflIdem (ri : ReflIdem) (C : Prop -> Prop -> Prop) : Prop :=\nmatch ri with\n| Refl => law1 (IsC True) (fun P => C P P)\n| Irrefl => law1 (IsC False) (fun P => C P P)\n| Idempotent => law1 IsArg (fun P => C P P)\n| Antiidempotent => law1 IsNeg (fun P => C P P)\nend.\n\nEval simpl in reflIdem Irrefl (con Xor).\nCheck ltac:(cbn; tauto) : reflIdem Irrefl (con Xor).\n\nDefinition neutr (d : Dir) (N : Prop) (C : Prop -> Prop -> Prop) : Prop :=\nmatch d with\n| L => law1 IsArg (C N)\n| R => law1 IsArg (fun P => C P N)\nend.\n\nDefinition antineutr (d : Dir) (N : Prop) (C : Prop -> Prop -> Prop) : Prop :=\nmatch d with\n| L => law1 IsNeg (C N)\n| R => law1 IsNeg (fun P => C P N)\nend.\n\nDefinition absorb (d : Dir) (A : Prop) (C : Prop -> Prop -> Prop) : Prop :=\nmatch d with\n| L => law1 (IsC A) (C A)\n| R => law1 (IsC A) (fun P => C P A)\nend.\n\nEval simpl in absorb L False (con Xor).\n\nInductive DistrLaw : Type :=\n| DistrLaw' (d : Dir) (c1 c2 : Connective).\n\nDefinition distrLaw (d : DistrLaw) : Prop :=\nmatch d with\n| DistrLaw' L c1 c2 =>\n    forall P Q R : Prop, con c1 P (con c2 Q R) <-> con c2 (con c1 P Q) (con c1 P R)\n| _ => False\nend.\n\nEval simpl in distrLaw (DistrLaw' L Or And).\nCheck ltac:(cbn; tauto) : distrLaw (DistrLaw' L Or And).\n\nDefinition distrL (C D : Prop -> Prop -> Prop) : Prop :=\n  forall P Q R : Prop, C P (D Q R) <-> D (C P Q) (C P R).\n\nDefinition distrR (C D : Prop -> Prop -> Prop) : Prop :=\n  forall P Q R : Prop, C (D P Q) R <-> D (C P R) (C Q R).\n\nCheck ltac:(compute; tauto) : distrL or and.\nCheck ltac:(compute; tauto) : distrR and or.\nEval compute in distrL or and.\n\nInductive Law2 : Type :=\n| Comm.\n\nDefinition law2 (l : Law2) (Con : Prop -> Prop -> Prop) : Prop :=\nmatch l with\n| Comm => forall P Q : Prop, Con P Q <-> Con Q P\nend.\n\nInductive Law3 : Type :=\n| Assoc.\n\nDefinition law3 (l : Law3) (Con : Prop -> Prop -> Prop) : Prop :=\nmatch l with\n| Assoc => forall P Q R : Prop, Con (Con P Q) R <-> Con P (Con Q R)\nend.\n\nModule wut.\n\nInductive LAW : Type :=\n| Neutr (d : Dir) (c : Constant) (naive : bool)\n| Antineutr (d : Dir) (c : Constant) (naive : bool)\n| Absorb (d : Dir) (c : Constant) (naive : bool)\n| Reflexive\n| Irreflexive\n| Idempotent\n| Antiidempotent\n| Commutative\n| Associative\n| Monotone (d : Dir)\n| Distributive (d : Dir) (Con : Connective).\n\nDefinition unconst (c : Constant) (P : Prop) : Prop :=\nmatch c with\n| Top => P\n| Bot => ~ P\nend.\n\nDefinition law (l : LAW) (Con : Connective) : Prop :=\nmatch l with\n| Neutr L c true => forall P : Prop, con Con (const c) P <-> P\n| Neutr R c true => forall P : Prop, con Con P (const c) <-> P\n| Neutr L c false => forall P Q : Prop, unconst c P -> con Con P Q <-> Q\n| Neutr R c false => forall P Q : Prop, unconst c Q -> con Con P Q <-> P\n| Antineutr L c true => forall P : Prop, con Con (const c) P <-> ~ P\n| Antineutr R c true => forall P : Prop, con Con P (const c) <-> ~ P\n| Antineutr L c false => forall P Q : Prop, unconst c P -> con Con P Q <-> ~ Q\n| Antineutr R c false => forall P Q : Prop, unconst c Q -> con Con P Q <-> ~ P\n| Absorb L c true => forall P : Prop, con Con (const c) P <-> const c\n| Absorb R c true => forall P : Prop, con Con P (const c) <-> const c\n| Absorb L c false => forall P Q : Prop, unconst c P -> con Con P Q <-> True\n| Absorb R c false => forall P Q : Prop, unconst c Q -> con Con P Q <-> True\n| _ => False\nend.\n\n(* | Antineutr (d : Dir) (c : Constant) (naive : bool)\n| Absorb (d : Dir) (c : Constant) (naive : bool)\n| Reflexive\n| Irreflexive\n| Idempotent\n| Antiidempotent\n| Commutative\n| Associative\n| Monotone (d : Dir)\n| Distributive (d : Dir) (Con : Connective). *)\n\nEval simpl in law (Neutr L Top true) Impl.\nEval simpl in law (Absorb L Top true) Or.\nEval simpl in law (Absorb L Top false) Or.\nEval simpl in law (Neutr L Bot false) Or.\n\nEnd wut.", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/code/Logika/GenerycznePrawaLogiki.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6508924040404822}}
{"text": "(** * Indu\\u00e7\\u00e3o em Coq *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nAdd LoadPath \"/Users/marcosmonteiro/desktop/coq\".\nRequire Export aula07_poli.\n\n(* ############################################### *)\n(** * Fun\\u00e7\\u00f5es de alta ordem *)\n\n(** Assim como outras linguagens funcionais,\n    \\u00e9 poss\\u00edvel passar fun\\u00e7\\u00f5es como argumentos,\n    retornar fun\\u00e7\\u00f5es e armazenar fun\\u00e7\\u00f5es em\n    estruturas de dados. *)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\nCheck @doit3times.\n(* ===> doit3times :\n        forall X : Type, (X -> X) -> X -> X *)\n\nExample test_doit3times:\n  doit3times minustwo 9 = 3.\nProof. reflexivity.  Qed.\n\nExample test_doit3times':\n  doit3times negb true = false.\nProof. reflexivity.  Qed.\n\n(** Uma fun\\u00e7\\u00e3o mais \\u00fatil \\u00e9 [filter]. *)\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:\n  filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity.  Qed.\n\nDefinition length_is_1 {X : Type} (l : list X)\n                       : 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(** \\u00c9 poss\\u00edvel definir fun\\u00e7\\u00f5es \"on the fly\"\n    (an\\u00f4nimas); ou seja, sem dar um nome a elas.\n\n    O exemplo a seguir n\\u00e3o precisa da defini\\u00e7\\u00e3o\n    de [length_is]. *)\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: (partition)  *)\n(** Use [filter] para escrever a fun\\u00e7\\u00e3o [partition]:\n\n      partition : forall X : Type,\n                  (X -> bool) -> list X\n                  -> list X * list X\n\n    Dado um conjunto [X], uma fun\\u00e7\\u00e3o teste [X -> bool],\n    e uma [list X], a fun\\u00e7\\u00e3o [partition] retorna um\n    par de listas: o primeiro \\u00e9 uma sublista com\n    os elementos que satisfazem o teste; o segundo,\n    com aqueles que n\\u00e3o satisfazem o teste. *)\n\nDefinition partition {X : Type} (test : X -> bool)\n                     (l : list X) : list X * list X\n(* SUBSTITUA COM \":= _sua_defini\\u00e7\\u00e3o_ .\" *). Admitted.\n\nExample test_partition1:\n  partition oddb [1;2;3;4;5]\n  = ([1;3;5], [2;4]).\nProof.\n (* COMPLETE AQUI *) Admitted.\n\nExample test_partition2:\n  partition (fun x => false) [5;9;0]\n  = ([], [5;9;0]).\nProof.\n (* COMPLETE AQUI *) Admitted.\n\n(** Outra fun\\u00e7\\u00e3o \\u00fatil \\u00e9 [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\nExample test_map1:\n  map (fun x => plus 3 x) [2;0;2]\n  = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** Observe que as listas de entrada e sa\\u00edda\n    podem ter tipos diferentes. *)\n\nExample test_map2:\n  map oddb [2;1;2;5]\n  = [false;true;false;true].\nProof. reflexivity.  Qed.\n\nExample test_map3:\n  map length [ [2;3] ; [] ; [3] ]\n  = [2;0;1].\nProof. reflexivity. Qed. \n\n(** **** Exercise: (map_rev)  *)\n(** Prove que [map] e [rev] comutam. Talvez\n    voc\\u00ea precise definir um lemma auxiliar. *)\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 (* COMPLETE AQUI *) Admitted.\n\n(** Outra fun\\u00e7\\u00e3o \\u00fatil \\u00e9 [fold]. Esta fun\\u00e7\\u00e3o insere\n    um operador bin\\u00e1rio [f] entre cada par de elementos\n    de uma certa lista. \\u00c9 preciso definir um elemento\n    base / inicial. Por exemplo, fold plus [1;2;3;4] 0\n    retorna 1 + (2 + (3 + (4 + 0))). *)\n\nFixpoint fold {X Y:Type} (f: X->Y->Y) (l:list X)\n              (b:Y) : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true\n  = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app [[1];[];[2;3];[4]] []\n  = [1;2;3;4].\nProof. reflexivity. Qed.\n\n(** \\u00c9 poss\\u00edvel definir fun\\u00e7\\u00f5es que retornam fun\\u00e7\\u00f5es. *)\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. reflexivity. Qed.\n\nExample constfun_example2 :\n  (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** A fun\\u00e7\\u00e3o [plus] \\u00e9 um exemplo disto. *)\n\nCheck plus.\n(* ==> nat -> nat -> nat *)\n\n(** O operador [->] \\u00e9 bin\\u00e1rio. Logo, [nat -> nat -> nat]\n    significa [nat -> (nat -> nat)]. Isto permite\n    aplica\\u00e7\\u00e3o parcial de [plus]. Al\\u00e9m disto, processar\n    uma lista de argumentos com fun\\u00e7\\u00f5es que retornam\n    fun\\u00e7\\u00f5es \\u00e9 conhecido como \"currying\". *)\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 :\n  plus3 4 = 7.\nProof. reflexivity.  Qed.\nExample test_plus3' :\n  doit3times plus3 0 = 9.\nProof. reflexivity.  Qed.\nExample test_plus3'' :\n  doit3times (plus 3) 0 = 9.\nProof. reflexivity.  Qed.\n\nModule Exercises.\n\n(** **** Exercise: (fold_length)  *)\n(** Muitas fun\\u00e7\\u00f5es podem ser implementadas em termos\n    de [fold]. Por exemplo, a seguir uma defini\\u00e7\\u00e3o\n    alternativa para [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 a corretude de [fold_length]. *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n   (* COMPLETE AQUI *) Admitted.\n\n(** **** Exercise: (fold_map)  *)\n(** Tamb\\u00e9m podemos definir [map] em termos de [fold].\n    Complete a defini\\u00e7\\u00e3o [fold_map] e prove sua corretude. *)\n\nDefinition fold_map {X Y:Type} (f : X -> Y)\n                    (l : list X) : list Y\n(* SUBSTITUA COM \":= _sua_defini\\u00e7\\u00e3o_ .\" *). Admitted.\n\nTheorem fold_map_correct :\n  forall (X Y : Type) (f : X -> Y) (l : list X),\n    fold_map f l = map f l.\nProof.\n   (* COMPLETE AQUI *) Admitted.\n\nEnd Exercises.\n\n(* ############################################### *)\n(** * Leitura sugerida *)\n\n(** Software Foundations: volume 1\n  - Functions as Data\n  https://softwarefoundations.cis.upenn.edu/lf-current/Poly.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/aula08_ordem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.8723473763375643, "lm_q1q2_score": 0.650892392953528}}
{"text": "Print bool.\nGoal false <> true.\nProof.\n  intros A.\n  change (if false then True else False).\n  rewrite A.\n  exact I.\nQed.\n\nLemma disjoint_O_S n:\n  O <> S n.\nProof.\n  intro A.\n  change (match O with O => False | _ => True end).\n  rewrite A.\n  exact I.\nQed.\n\nGoal false <> true.\nProof.\n  intros A.\n  change (match true with false => True | true => False end).\n  rewrite <- A.\n  exact I.\nQed.\n\nLemma injective_S x y:\n  S x = S y -> x = y.\nProof.\n  intro A.\n  change (pred (S x) = pred (S y)).\n  rewrite A.\n  reflexivity.\nQed.\n\nPrint pred.\nPrint Nat.pred.\n\nGoal forall x, S x <> O.\nProof. intros x A. discriminate A. Qed.\n\nGoal forall x y, S x = S y -> x = y.\nProof. intros x y A. injection A. auto. Qed.\n\nGoal forall x, S x <> O.\nProof.\n  intros x A.\n  congruence.\nQed.\n\nGoal forall x y, S x = S y -> x = y.\nProof. intros x y A. congruence. Qed.\n", "meta": {"author": "s9yumeng", "repo": "Theorem", "sha": "e2d142014aefa6f5a82136662d1feb78ea3a9348", "save_path": "github-repos/coq/s9yumeng-Theorem", "path": "github-repos/coq/s9yumeng-Theorem/Theorem-e2d142014aefa6f5a82136662d1feb78ea3a9348/discrimination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033684, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6508923916593866}}
{"text": "(** * Tactics: More Basic Tactics *)\n\n(** This chapter introduces several additional proof strategies\n    and tactics that allow us to begin proving more interesting\n    properties of functional programs.  We will see:\n\n    - how to use auxiliary lemmas in both \"forward-style\" and\n      \"backward-style\" proofs;\n    - how to reason about data constructors (in particular, how to use\n      the fact that they are injective and disjoint);\n    - how to strengthen an induction hypothesis (and when such\n      strengthening is required); and\n    - more details on how to reason by case analysis. *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Export Poly.\n\n(* ################################################################# *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    _exactly_ the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n\n(** Here, we could finish with \"[rewrite -> eq2.  reflexivity.]\" as we\n    have done several times before.  We can achieve the same effect in\n    a single step by using the [apply] tactic instead: *)\n\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] that binds some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex)  *)\n(** Complete the following proof without using [simpl]. *)\n\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 3 = true ->\n     oddb 4 = true.\nProof.\n  intros C1 C2. apply C1. apply C2. Qed.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal exactly -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n\n(** Here we cannot use [apply] directly, but we can use the [symmetry]\n    tactic, which switches the left and right sides of an equality in\n    the goal. *)\n\n  symmetry.\n  simpl. (* (This [simpl] is optional, since [apply] will perform\n            simplification first, if needed.) *)\n  apply H.  Qed.\n\n(** **** Exercise: 3 stars (apply_exercise1)  *)\n(** (_Hint_: You can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [Search] is\n    your friend.) *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  intros l l' H.\n  symmetry. rewrite -> H. apply rev_involutive. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (apply_rewrite)  *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  What are the situations where both can usefully be\n    applied?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(* ################################################################# *)\n(** * The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might like to pull it out\n    as a lemma recording, once and for all, the fact that equality is\n    transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to prove the above\n    example.  However, to do this we need a slight refinement of the\n    [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n\n(** If we simply tell Coq [apply trans_eq] at this point, it can\n    tell (by matching the goal against the conclusion of the lemma)\n    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and\n    [o] with [[e,f]].  However, the matching process doesn't determine\n    an instantiation for [m]: we have to supply one explicitly by\n    adding [with (m:=[c,d])] to the invocation of [apply]. *)\n\n  apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2.   Qed.\n\n(** Actually, we usually don't have to include the name [m] in\n    the [with] clause; Coq is often smart enough to figure out which\n    instantiation we're giving. We could instead write: [apply\n    trans_eq with [c;d]]. *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o).\nProof.\n  intros m n o p Eq1 Eq2.\n  apply trans_eq with (m := n).\n  apply Eq2. apply Eq1. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * The [inversion] Tactic *)\n\n(** Recall the definition of natural numbers:\n\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n\n    It is obvious from this definition that every number has one of\n    two forms: either it is the constructor [O] or it is built by\n    applying the constructor [S] to another number.  But there is more\n    here than meets the eye: implicit in the definition (and in our\n    informal understanding of how datatype declarations work in other\n    programming languages) are two more facts:\n\n    - The constructor [S] is _injective_.  That is, if [S n = S m], it\n      must be the case that [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n].\n\n    Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor\n    is injective and [nil] is different from every non-empty list.\n    For booleans, [true] and [false] are different.  (Since neither\n    [true] nor [false] take any arguments, their injectivity is not\n    interesting.)  And so on. *)\n\n(** Coq provides a tactic called [inversion] that allows us to\n    exploit these principles in proofs. To see how to use it, let's\n    show explicitly that the [S] constructor is injective: *)\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n\n(** By writing [inversion H] at this point, we are asking Coq to\n    generate all equations that it can infer from [H] as additional\n    hypotheses, replacing variables in the goal as it goes. In the\n    present example, this amounts to adding a new hypothesis [H1 : n =\n    m] and replacing [n] by [m] in the goal. *)\n\n  inversion H.\n  reflexivity.\nQed.\n\n(** Here's a more interesting example that shows how multiple\n    equations can be derived at once. *)\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity. Qed.\n\n(** We can name the equations that [inversion] generates with an\n    [as ...] clause: *)\n\nTheorem inversion_ex2 : forall (n m : nat),\n  [n] = [m] ->\n  n = m.\nProof.\n  intros n m H. inversion H as [Hnm]. reflexivity.  Qed.\n\n(** **** Exercise: 1 star (inversion_ex3)  *)\nExample inversion_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  intros X x y z l j H0 H1.\n  inversion H0.\n  inversion H1.\n  symmetry. apply H2. Qed.\n(** [] *)\n\n(** When used on a hypothesis involving an equality between\n    _different_ constructors (e.g., [S n = O]), [inversion] solves the\n    goal immediately.  Consider the following proof: *)\n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  intros n.\n\n(** We can proceed by case analysis on [n]. The first case is\n    trivial. *)\n\n  destruct n as [| n'].\n  - (* n = 0 *)\n    intros H. reflexivity.\n\n(** However, the second one doesn't look so simple: assuming\n    [beq_nat 0 (S n') = true], we must show [S n' = 0], but the latter\n    clearly contradictory!  The way forward lies in the assumption.\n    After simplifying the goal state, we see that [beq_nat 0 (S n') =\n    true] has become [false = true]: *)\n\n  - (* n = S n' *)\n    simpl.\n\n(** If we use [inversion] on this hypothesis, Coq notices that\n    the subgoal we are working on is impossible, and therefore removes\n    it from further consideration. *)\n\n    intros H. inversion H. Qed.\n\n(** This is an instance of a logical principle known as the _principle\n    of explosion_, which asserts that a contradictory hypothesis\n    entails anything, even false things! *)\n\nTheorem inversion_ex4 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem inversion_ex5 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. inversion contra. Qed.\n\n(** If you find the principle of explosion confusing, remember\n    that these proofs are not actually showing that the conclusion of\n    the statement holds.  Rather, they are arguing that, if the\n    nonsensical situation described by the premise did somehow arise,\n    then the nonsensical conclusion would follow.  We'll explore the\n    principle of explosion of more detail in the next chapter. *)\n\n(** **** Exercise: 1 star (inversion_ex6)  *)\nExample inversion_ex6 : forall (X : Type)\n                          (x y z : X) (l j : list X),\n  x :: y :: l = [] ->\n  y :: l = z :: j ->\n  x = z.\nProof.\n  intros X x y z l j H0 H1.\n  inversion H1. inversion H0. Qed.\n(** [] *)\n\n(** To summarize this discussion, suppose [H] is a hypothesis in the\n    context or a previously proven lemma of the form\n\n        c a1 a2 ... an = d b1 b2 ... bm\n\n    for some constructors [c] and [d] and arguments [a1 ... an] and\n    [b1 ... bm].  Then [inversion H] has the following effect:\n\n    - If [c] and [d] are the same constructor, then, by the\n      injectivity of this constructor, we know that [a1 = b1], [a2 =\n      b2], etc.  The [inversion H] adds these facts to the context and\n      tries to use them to rewrite the goal.\n\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory, and the current goal doesn't have to be\n      considered at all.  In this case, [inversion H] marks the\n      current goal as completed and pops it off the goal stack. *)\n\n(** The injectivity of constructors allows us to reason that\n    [forall (n m : nat), S n = S m -> n = m].  The converse of this\n    implication is an instance of a more general fact about both\n    constructors and functions, which we will find convenient in a few\n    places below: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic [simpl in H] performs simplification in\n    the hypothesis named [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     beq_nat (S n) (S m) = b  ->\n     beq_nat n m = b.\nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, [apply L in H] matches some conditional statement\n    [L] (of the form [L1 -> L2], say) against a hypothesis [H] in the\n    context.  However, unlike ordinary [apply] (which rewrites a goal\n    matching [L2] into a subgoal [L1]), [apply L in H] matches [H]\n    against [L1] and, if successful, replaces it with [L2].\n\n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\": from [L1 -> L2] and a hypothesis matching [L1], it\n    produces a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\": it says that if we know [L1->L2] and we are\n    trying to prove [L2], it suffices to prove [L1].\n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\nTheorem silly3' : forall (n : nat),\n  (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->\n  true = beq_nat n 5  ->\n  true = beq_nat (S (S n)) 7.\nProof.\n  intros n eq H.\n  symmetry in H. apply eq in H. symmetry in H.\n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, idiomatic use of Coq tends to favor backward reasoning,\n    but in some situations the forward style can be easier to think\n    about.  *)\n\n(** **** Exercise: 3 stars, recommended (plus_n_n_injective)  *)\n(** Practice using \"in\" variants in this proof.  (Hint: use\n    [plus_n_Sm].) *)\n\nTheorem plus_n_n_injective : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  - simpl. intros [] H.\n    + reflexivity.\n    + inversion H.\n  - simpl. intros [] H.\n    { simpl in H. inversion H. }\n    { symmetry in H. inversion H.\n      rewrite <- plus_n_Sm in H1.\n      rewrite <- plus_n_Sm in H1.\n      inversion H1. symmetry in H2.\n      apply IHn' in H2. apply f_equal. apply H2. } Qed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Varying the Induction Hypothesis *)\n\n(** Sometimes it is important to control the exact form of the\n    induction hypothesis when carrying out inductive proofs in Coq.\n    In particular, we need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose\n    we want to show that the [double] function is injective -- i.e.,\n    that it maps different arguments to different results:\n\n    Theorem double_injective: forall n m,\n      double n = double m -> n = m.\n\n    The way we _start_ this proof is a bit delicate: if we begin with\n\n      intros n. induction n.\n\n    all is well.  But if we begin it with\n\n      intros n m. induction n.\n\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  - (* n = O *) simpl. intros eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n  - (* n = S n' *) intros eq. destruct m as [| m'].\n    + (* m = O *) inversion eq.\n    + (* m = S m' *) apply f_equal.\n\n(** At this point, the induction hypothesis, [IHn'], does _not_ give us\n    [n' = m'] -- there is an extra [S] in the way -- so the goal is\n    not provable. *)\n\n      Abort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context --\n    intuitively, we have told Coq, \"Let's consider some particular [n]\n    and [m]...\" and we now have to prove that, if [double n = double\n    m] for _these particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove, for\n    _all_ [n], that the proposition\n\n      - [P n] = \"if [double n = double m], then [n = m]\"\n\n    holds, by showing\n\n      - [P O]\n\n         (i.e., \"if [double O = double m] then [O = m]\") and\n\n      - [P n -> P (S n)]\n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: it says that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help at all with proving\n    [R]!  (If we tried to prove [R] from [Q], we would start with\n    something like \"Suppose [double (S n) = 10]...\" but then we'd be\n    stuck: knowing that [double (S n)] is [10] tells us nothing about\n    whether [double n] is [10], so [Q] is useless.) *)\n\n(** Trying to carry out this proof by induction on [n] when [m] is\n    already in the context doesn't work because we are then trying to\n    prove a relation involving _every_ [n] but just a _single_ [m]. *)\n\n(** The successful proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  - (* n = O *) simpl. intros m eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n\n  - (* n = S n' *) simpl.\n\n(** Notice that both the goal and the induction hypothesis are\n    different this time: the goal asks us to prove something more\n    general (i.e., to prove the statement for _every_ [m]), but the IH\n    is correspondingly more flexible, allowing us to choose any [m] we\n    like when we apply the IH. *)\n\n    intros m eq.\n\n(** Now we've chosen a particular [m] and introduced the assumption\n    that [double n = double m].  Since we are doing a case analysis on\n    [n], we also need a case analysis on [m] to keep the two \"in sync.\" *)\n\n    destruct m as [| m'].\n    + (* m = O *) simpl.\n\n(** The 0 case is trivial: *)\n\n      inversion eq.\n\n    + (* m = S m' *)\n      apply f_equal.\n\n(** At this point, since we are in the second branch of the [destruct\n    m], the [m'] mentioned in the context is the predecessor of the\n    [m] we started out talking about.  Since we are also in the [S]\n    branch of the induction, this is perfect: if we instantiate the\n    generic [m] in the IH with the current [m'] (this instantiation is\n    performed automatically by the [apply] in the next step), then\n    [IHn'] gives us exactly what we need to finish the proof. *)\n\n      apply IHn'. inversion eq. reflexivity. Qed.\n\n(** What you should take away from all this is that we need to be\n    careful about using induction to try to prove something too\n    specific: To prove a property of [n] and [m] by induction on [n],\n    it is sometimes important to leave [m] generic. *)\n\n(** The following exercise requires the same pattern. *)\n\n(** **** Exercise: 2 stars (beq_nat_true)  *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  intros n. induction n as [ | n' IH0 ].\n  - simpl. intros [] Ht.\n    + reflexivity.\n    + inversion Ht.\n  - simpl. intros [] Ht.\n    + inversion Ht.\n    + apply f_equal. apply IH0. apply Ht. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (beq_nat_true_informal)  *)\n(** Give a careful informal proof of [beq_nat_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** The strategy of doing fewer [intros] before an [induction] to\n    obtain a more general IH doesn't always work by itself; sometimes\n    some _rearrangement_ of quantified variables is needed.  Suppose,\n    for example, that we wanted to prove [double_injective] by\n    induction on [m] instead of [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  - (* m = O *) simpl. intros eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *) apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (If we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce [n]\n    for us!)  *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    works, but it's not nice: We don't want to have to twist the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them!  Rather we want to state them in the clearest and\n    most natural way. *)\n\n(** What we can do instead is to first introduce all the quantified\n    variables and then _re-generalize_ one or more of them,\n    selectively taking variables out of the context and putting them\n    back at the beginning of the goal.  The [generalize dependent]\n    tactic does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m.\n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros n eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *) apply f_equal.\n      apply IHm'. inversion eq. reflexivity. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n    _Theorem_: For any nats [n] and [m], if [double n = double m], then\n      [n = m].\n\n    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n      any [n], if [double n = double m] then [n = m].\n\n      - First, suppose [m = 0], and suppose [n] is a number such\n        that [double n = double m].  We must show that [n = 0].\n\n        Since [m = 0], by the definition of [double] we have [double n =\n        0].  There are two cases to consider for [n].  If [n = 0] we are\n        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']\n        for some [n'], we derive a contradiction: by the definition of\n        [double], we can calculate [double n = S (S (double n'))], but\n        this contradicts the assumption that [double n = 0].\n\n      - Second, suppose [m = S m'] and that [n] is again a number such\n        that [double n = double m].  We must show that [n = S m'], with\n        the induction hypothesis that for every number [s], if [double s =\n        double m'] then [s = m'].\n\n        By the fact that [m = S m'] and the definition of [double], we\n        have [double n = S (S (double m'))].  There are two cases to\n        consider for [n].\n\n        If [n = 0], then by definition [double n = 0], a contradiction.\n\n        Thus, we may assume that [n = S n'] for some [n'], and again by\n        the definition of [double] we have [S (S (double n')) =\n        S (S (double m'))], which implies by inversion that [double n' =\n        double m'].  Instantiating the induction hypothesis with [n'] thus\n        allows us to conclude that [n' = m'], and it follows immediately\n        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just\n        what we wanted to show. [] *)\n\n(** Before we close this section and move on to some exercises,\n    let's digress briefly and use [beq_nat_true] to prove a similar\n    property of identifiers that we'll need in later chapters: *)\n\nTheorem beq_id_true : forall x y,\n  beq_id x y = true -> x = y.\nProof.\n  intros [m] [n]. simpl. intros H.\n  assert (H' : m = n). { apply beq_nat_true. apply H. }\n  rewrite H'. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, recommended (gen_dep_practice)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     nth_error l n = None.\nProof.\n  intros n X l.\n  generalize dependent n.\n  induction l as [ | t l0 IH0 ].\n  - simpl. intros n eq. reflexivity.\n  - intros n eq. destruct n as [ | n' ].\n    + inversion eq.\n    + apply IH0. inversion eq. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Unfolding Definitions *)\n\n(** It sometimes happens that we need to manually unfold a Definition\n    so that we can manipulate its right-hand side.  For example, if we\n    define... *)\n\nDefinition square n := n * n.\n\n(** ... and try to prove a simple fact about [square]... *)\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\n  simpl.\n\n(** ... we get stuck: [simpl] doesn't simplify anything at this point,\n    and since we haven't proved any other facts about [square], there\n    is nothing we can [apply] or [rewrite] with.\n\n    To make progress, we can manually [unfold] the definition of\n    [square]: *)\n\n  unfold square.\n\n(** Now we have plenty to work with: both sides of the equality are\n    expressions involving multiplication, and we have lots of facts\n    about multiplication at our disposal.  In particular, we know that\n    it is commutative and associative, and from these facts it is not\n    hard to finish the proof. *)\n\n  rewrite mult_assoc.\n  assert (H : n * m * n = n * n * m).\n  { rewrite mult_comm. apply mult_assoc. }\n  rewrite H. rewrite mult_assoc. reflexivity.\nQed.\n\n(** At this point, a deeper discussion of unfolding and simplification\n    is in order.\n\n    You may already have observed that tactics like [simpl],\n    [reflexivity], and [apply] will often unfold the definitions of\n    functions automatically when this allows them to make progress.  For\n    example, if we define [foo m] to be the constant [5]... *)\n\nDefinition foo (x: nat) := 5.\n\n(** then the [simpl] in the following proof (or the [reflexivity], if\n    we omit the [simpl]) will unfold [foo m] to [(fun x => 5) m] and\n    then further simplify this expression to just [5]. *)\n\nFact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.\nProof.\n  intros m.\n  simpl.\n  reflexivity.\nQed.\n\n(** However, this automatic unfolding is rather conservative.  For\n    example, if we define a slightly more complicated function\n    involving a pattern match... *)\n\nDefinition bar x :=\n  match x with\n  | O => 5\n  | S _ => 5\n  end.\n\n(** ...then the analogous proof will get stuck: *)\n\nFact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  simpl. (* Does nothing! *)\nAbort.\n\n(** The reason that [simpl] doesn't make progress here is that it\n    notices that, after tentatively unfolding [bar m], it is left with\n    a match whose scrutinee, [m], is a variable, so the [match] cannot\n    be simplified further.  (It is not smart enough to notice that the\n    two branches of the [match] are identical.)  So it gives up on\n    unfolding [bar m] and leaves it alone.  Similarly, tentatively\n    unfolding [bar (m+1)] leaves a [match] whose scrutinee is a\n    function application (that, itself, cannot be simplified, even\n    after unfolding the definition of [+]), so [simpl] leaves it\n    alone. *)\n\n(** At this point, there are two ways to make progress.  One is to use\n    [destruct m] to break the proof into two cases, each focusing on a\n    more concrete choice of [m] ([O] vs [S _]).  In each case, the\n    [match] inside of [bar] can now make progress, and the proof is\n    easy to complete. *)\n\nFact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  destruct m.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(** This approach works, but it depends on our recognizing that the\n    [match] hidden inside [bar] is what was preventing us from making\n    progress. *)\n\n(** A more straightforward way to make progress is to explicitly tell\n    Coq to unfold [bar]. *)\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n\n(** Now it is apparent that we are stuck on the [match] expressions on\n    both sides of the [=], and we can use [destruct] to finish the\n    proof without thinking too hard. *)\n\n  destruct m.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where [destruct] is used to\n    perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (beq_nat n 3).\n    - (* beq_nat n 3 = true *) reflexivity.\n    - (* beq_nat n 3 = false *) destruct (beq_nat n 5).\n      + (* beq_nat n 5 = true *) reflexivity.\n      + (* beq_nat n 5 = false *) reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (beq_nat n 3) then ... else ...].  But either\n    [n] is equal to [3] or it isn't, so we can use [destruct (beq_nat\n    n 3)] to let us reason about the two cases.\n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c]. *)\n\n(** **** Exercise: 3 stars, optional (combine_split)  *)\n(** Here is an implementation of the [split] function mentioned in\n    chapter [Poly]: *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) :=\n  match l with\n  | [] => ([], [])\n  | (x, y) :: t =>\n      match split t with\n      | (lx, ly) => (x :: lx, y :: ly)\n      end\n  end.\n\n(** Prove that [split] and [combine] are inverses in the following\n    sense: *)\n\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  intros X Y l.\n  induction l as [ | (x, y) l0 IH0 ].\n  - intros l1 l2 H. simpl in H. inversion H. reflexivity.\n  - simpl. destruct (split l0). intros l2 l3 H. inversion H.\n    simpl. assert (combine l l1 = l0) as AH. { apply IH0. reflexivity. }\n    rewrite AH. reflexivity. Qed.\n(** [] *)\n\n(** However, [destruct]ing compound expressions requires a bit of\n    care, as such [destruct]s can sometimes erase information we need\n    to complete a proof. *)\n(** For example, suppose we define a function [sillyfun1] like\n    this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** Now suppose that we want to convince Coq of the (rather\n    obvious) fact that [sillyfun1 n] yields [true] only when [n] is\n    odd.  By analogy with the proofs we did with [sillyfun] above, it\n    is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAbort.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution performed by [destruct] is too brutal -- it threw\n    away every occurrence of [beq_nat n 3], but we need to keep some\n    memory of this expression and how it was destructed, because we\n    need to be able to reason that, since [beq_nat n 3 = true] in this\n    branch of the case analysis, it must be that [n = 3], from which\n    it follows that [n] is odd.\n\n    What we would really like is to substitute away all existing\n    occurences of [beq_nat n 3], but at the same time add an equation\n    to the context that records which case we are in.  The [eqn:]\n    qualifier allows us to introduce such an equation, giving it a\n    name that we choose. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got\n     stuck above, except that the context contains an extra\n     equality assumption, which is exactly what we need to\n     make progress. *)\n    - (* e3 = true *) apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    - (* e3 = false *)\n     (* When we come to the second equality test in the body\n        of the function we are reasoning about, we can use\n        [eqn:] again in the same way, allow us to finish the\n        proof. *)\n      destruct (beq_nat n 5) eqn:Heqe5.\n        + (* e5 = true *)\n          apply beq_nat_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + (* e5 = false *) inversion eq.  Qed.\n\n(** **** Exercise: 2 stars (destruct_eqn_practice)  *)\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  intros f b.\n  destruct (f b) eqn : H0.\n  - destruct b.\n    + rewrite -> H0. rewrite -> H0. reflexivity.\n    + destruct (f true) eqn : H1.\n      { apply H1. }\n      { apply H0. }\n  - destruct b.\n    + destruct (f false) eqn : H1.\n      { apply H0. }\n      { apply H1. }\n    + rewrite -> H0. rewrite -> H0. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Review *)\n\n(** We've now seen many of Coq's most fundamental tactics.  We'll\n    introduce a few more in the coming chapters, and later on we'll\n    see some more powerful _automation_ tactics that make Coq help us\n    with low-level details.  But basically we've got what we need to\n    get work done.\n\n    Here are the ones we've seen:\n\n      - [intros]: move hypotheses/variables from goal to context\n\n      - [reflexivity]: finish the proof (when the goal looks like [e =\n        e])\n\n      - [apply]: prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: apply a hypothesis, lemma, or constructor to\n        a hypothesis in the context (forward reasoning)\n\n      - [apply... with...]: explicitly specify values for variables\n        that cannot be determined by pattern matching\n\n      - [simpl]: simplify computations in the goal\n\n      - [simpl in H]: ... or a hypothesis\n\n      - [rewrite]: use an equality hypothesis (or lemma) to rewrite\n        the goal\n\n      - [rewrite ... in H]: ... or a hypothesis\n\n      - [symmetry]: changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]: changes a hypothesis of the form [t=u] into\n        [u=t]\n\n      - [unfold]: replace a defined constant by its right-hand side in\n        the goal\n\n      - [unfold... in H]: ... or a hypothesis\n\n      - [destruct... as...]: case analysis on values of inductively\n        defined types\n\n      - [destruct... eqn:...]: specify the name of an equation to be\n        added to the context, recording the result of the case\n        analysis\n\n      - [induction... as...]: induction on values of inductively\n        defined types\n\n      - [inversion]: reason by injectivity and distinctness of\n        constructors\n\n      - [assert (H: e)] (or [assert (e) as H]): introduce a \"local\n        lemma\" [e] and call it [H]\n\n      - [generalize dependent x]: move the variable [x] (and anything\n        else that depends on it) from the context back to an explicit\n        hypothesis in the goal formula *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (beq_nat_sym)  *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  intros n. induction n as [ | n' IH0 ].\n  - intros m. destruct m.\n    + reflexivity.\n    + simpl. reflexivity.\n  - intros m. destruct m eqn : Hm0.\n    + reflexivity.\n    + simpl. apply IH0. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Proof:\n   (* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof.\n  intros n m p H0 H1.\n  apply beq_nat_true in H0.\n  apply beq_nat_true in H1.\n  rewrite H0. rewrite H1. symmetry. apply beq_nat_refl. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine)  *)\n(** We proved, in an exercise above, that for all lists of pairs,\n    [combine] is the inverse of [split].  How would you formalize the\n    statement that [split] is the inverse of [combine]?  When is this\n    property true?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?) *)\n\nDefinition split_combine_statement : Prop := forall (X Y : Type) (l : list (X * Y)) (l1 : list X) (l2 : list Y),\n    length l1 = length l2 -> split l = (l1, l2) -> combine l1 l2 = l.\n  (* (\"[: Prop]\" means that we are giving a name to a\n     logical proposition here.) *)\n\nTheorem split_combine : split_combine_statement.\nProof.\n  intros X Y l.\n  induction l as [ | h' l' IH0 ].\n  - simpl. intros l2 l1 H0 H1. inversion H1. reflexivity.\n  - intros l1 l2 H0 H1. destruct l2 as [ | h2 lt2 ].\n    + inversion H1. destruct l1 as [ | h1 lt1 ].\n      { apply combine_split. apply H1. }\n      { apply combine_split. apply H1. }\n    + destruct l1 as [ | h1 lt1 ].\n      { apply combine_split. apply H1. }\n      { apply combine_split. apply H1. } Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise)  *)\n(** This one is a bit challenging.  Pay attention to the form of your\n    induction hypothesis. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  intros X test x l lf H0.\n  generalize dependent x.\n  generalize dependent test.\n  generalize dependent lf.\n  generalize dependent l.\n  induction l as [ | h t IH0 ].\n  - intros. inversion H0.\n  - simpl. intros. destruct (test h) eqn : test_H.\n    + inversion H0. rewrite <- H1. apply test_H.\n    + apply IH0 in H0. apply H0. Qed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge)  *) \n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n\n      forallb evenb [0;2;4;5] = false\n\n      forallb (beq_nat 5) [] = true\n\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n\n      existsb (beq_nat 5) [0;2;3;6] = false\n\n      existsb (andb true) [true;true;false] = true\n\n      existsb oddb [1;0;0;0;0;3] = true\n\n      existsb evenb [] = false\n\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n\n    Finally, prove a theorem [existsb_existsb'] stating that\n    [existsb'] and [existsb] have the same behavior. *)\n\nFixpoint forallb { X : Type } ( f : X -> bool ) ( l : list X ) : bool :=\n  match l with\n  | [] => true\n  | x :: xs => f x && forallb f xs\n  end.\n\nFixpoint existsb { X : Type } ( f : X -> bool ) ( l : list X ) : bool :=\n  match l with\n  | [] => false\n  | x :: xs => f x || existsb f xs\n  end.\n\nDefinition existsb' { X : Type } ( f : X -> bool ) ( l : list X ) : bool := negb (forallb (fun x => negb (f x)) l).\n\nTheorem existsb_existsb' : forall ( X : Type ) ( f : X -> bool ) ( l : list X ), existsb f l = existsb' f l.\nProof.\n  intros. induction l as [ | h t IH0 ].\n  - simpl. unfold existsb'. simpl. reflexivity.\n  - simpl. unfold existsb'. unfold existsb' in IH0. simpl.\n    destruct (f h).\n    + simpl. reflexivity.\n    + simpl. apply IH0. Qed.\n(** [] *)\n\n\n\n", "meta": {"author": "tonyfloatersu", "repo": "SF-solution", "sha": "63d116cca62f4d8d4515b6ec7cffe8b88adf5a77", "save_path": "github-repos/coq/tonyfloatersu-SF-solution", "path": "github-repos/coq/tonyfloatersu-SF-solution/SF-solution-63d116cca62f4d8d4515b6ec7cffe8b88adf5a77/LogicFoundationSolution/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389873857265, "lm_q2_score": 0.8723473746782093, "lm_q1q2_score": 0.650892386790996}}
{"text": "Require Import EnsemblesEx.\nRequire Import Denotation.\nRequire Import Basics.\n\nExport EnsemblesEx.\nExport Denotation.\n\nOpen Scope program_scope.\n\nClass Basic := {\n  Space : Type -> Type;\n  denotationSpace {A} :> Denotation (Space A) (Ensemble A);\n\n  empty {A} : Space A;\n  single {A} : A -> Space A;\n  union {A} : Space A -> Space A -> Space A;\n  bind {A B} : Space A -> (A -> Space B) -> Space B;\n  \n  denoteEmptyOk {A} : ⟦ empty ⟧ = Empty_set A;\n  denoteSingleOk {A a} : ⟦ single a ⟧ = Singleton A a;\n  denoteUnionOk {A s t} : ⟦ union s t ⟧ = Union A ⟦ s ⟧ ⟦ t ⟧;\n  denoteBindOk {A B s f} : ⟦ bind s f ⟧ = BigUnion A B ⟦ s ⟧ (fun a => ⟦ f a ⟧);\n}.\n\nDefinition map `{S:Basic} {A B} (f:A->B) s := bind s (single ∘ f).\n", "meta": {"author": "konne88", "repo": "SpaceSearch", "sha": "524040a1f60a629c4f71c233341ad39a43d44eff", "save_path": "github-repos/coq/konne88-SpaceSearch", "path": "github-repos/coq/konne88-SpaceSearch/SpaceSearch-524040a1f60a629c4f71c233341ad39a43d44eff/src/coq/Space/Basic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544448, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6508572378951782}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import ZArith.\n\nRequire Import Pseudorandom.SplitMix.\nRequire Pseudorandom.SplitMix2.\n\nFixpoint split_many (n : N) g :=\n  N.iter n\n         (fun g => fst (split g))\n         g.\n\nModule SM1.\nImport SplitMix.\n\nDefinition iter (n : N) :=\n  next_int64 (split_many n (of_seed 33)).\n\nEnd SM1.\n\nModule SM2.\nImport SplitMix2.\n\nDefinition iter (n : N) :=\n  binary_to_N (to_binary\n    (N.iter n\n            (fun g => snd (split g))\n            (of_seed 33))).\n\nEnd SM2.\n\nTime Compute SM1.iter 3000.\nTime Compute SM2.iter 3000.\n\nDefinition test_run :=\n  let g0 := of_seed 33 in\n  let (x0, g0) := next_int64 g0 in\n  let (x1, g0) := next_int64 g0 in\n  let (g1, g0) := split g0 in\n  let (x2, g1) := next_int64 g1 in\n  let (g2, g1) := split g1 in\n  let (x3, g1) := next_int64 g1 in\n  let (g3, g2) := split g2 in\n  let (x4, g2) := next_int64 g2 in\n  let (x5, g2) := next_int64 g2 in\n  let (x6, g3) := next_int64 g3 in\n  let (x7, g3) := next_int64 g3 in\n  let (x8, g3) := next_int64 g3 in\n  let (x9, _) := next_int64 (split_many 300 g3) in\n  map two's [x0;x1;x2;x3;x4;x5;x6;x7;x8;x9].\n\nExample ex :\n  test_run =\n  [ 3174492301114349736;  1387786489429541378;\n    2612135949649290519; -6594435460564017959;\n    6114845654480584590; -3434961282303982149;\n   -4710980162942128616; -5883331640739962744;\n    7437753320184232638; -2875907909505887564]%Z.\nProof. Time native_compute. reflexivity. Qed.\n", "meta": {"author": "Lysxia", "repo": "coq-pseudorandom", "sha": "9c5d111199db228e9ab9d8a14ed7777506017674", "save_path": "github-repos/coq/Lysxia-coq-pseudorandom", "path": "github-repos/coq/Lysxia-coq-pseudorandom/coq-pseudorandom-9c5d111199db228e9ab9d8a14ed7777506017674/test/test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6508572378951781}}
{"text": "Require Export NFA.\n\nSection Reversing.\n\nContext {State Symbol : Type}.\nDefinition Word := @Word Symbol.\nHypothesis State_eq_dec : forall (x1 x2:State), { x1 = x2 } + { x1 <> x2 }.\nHypothesis Symbol_eq_dec : forall (x1 x2:Symbol), { x1 = x2 } + { x1 <> x2 }.\nDefinition NFA := @NFA State Symbol.\nDefinition ext_transitionf := ext_transitionf State_eq_dec Symbol_eq_dec.\nDefinition nfa_accepts := nfa_accepts State_eq_dec Symbol_eq_dec.\n\n(* Reverses word *)\nFixpoint rev (w:Word) :=\n  match w with\n  | a::w => rev w ++ [a]\n  | nil => nil\n  end.\n\n(* Reverses NFA *)\nFixpoint rev_nfa (g:NFA) :=\n  match g with\n  | start q::g => accept q::rev_nfa g\n  | accept q::g => start q::rev_nfa g\n  | transition q1 a q2::g => transition q2 a q1::rev_nfa g\n  | x::g => x::rev_nfa g\n  | nil => nil\n  end.\n\n(* Distribution of word reversion *)\nLemma rev_distr w1 w2 :\n  rev (w1 ++ w2) = rev w2 ++ rev w1.\nProof.\n  induction w1 as [|a w1 IH].\n  symmetry; apply app_nil_r.\n  simpl.\n  rewrite IH, app_assoc_reverse.\n  intuition.\nQed.\n\n(* A word reversed twice is equal to itself *)\nLemma rev_twice w :\n  rev (rev w) = w.\nProof.\n  induction w as [|a w IH].\n  intuition.\n  simpl.\n  rewrite rev_distr, IH.\n  intuition.\nQed.\n\n(* The resulting states are the same *)\nLemma rev_states g q :\n  In q (states (rev_nfa g)) -> In q (states g).\nProof.\n  intro H.\n  induction g as [|c g IH].\n  contradiction.\n  destruct c.\n  1-4: try destruct H; subst.\n  1,4,6: left; intuition.\n  1-4: try right; intuition.\n  destruct H as [H|[H|H]].\n  1,3: right.\n  1,3: subst; left; intuition.\n  right; intuition.\nQed.\n\n(* The resulting accept states are the original start states *)\nLemma rev_start_states g :\n  accept_states (rev_nfa g) = start_states g.\nProof.\n  induction g as [|c g IH].\n  intuition.\n  destruct c;\n  simpl; rewrite IH; intuition.\nQed.\n\n(* The resulting start states are the original accept states *)\nLemma rev_accept_states g :\n  start_states (rev_nfa g) = accept_states g.\nProof.\n  induction g as [|c g IH].\n  intuition.\n  destruct c;\n  simpl; rewrite IH; intuition.\nQed.\n\n(* The transitions go reversed *)\nLemma rev_transition g q1 a q2 :\n  In (transition q1 a q2) g <->\n  In (transition q2 a q1) (rev_nfa g).\nProof.\n  induction g as [|c g IH].\n  intuition.\n  destruct c; simpl.\n  1-4: split; intros [H|H]; try discriminate; intuition.\n  split; intros [H|H].\n  1,3: inversion H; subst; intuition.\n  1,2: intuition.\nQed.\n\n(* Same for paths *)\nLemma rev_path g q1 q2 w :\n  path g q1 q2 w <-> path (rev_nfa g) q2 q1 (rev w).\nProof.\n  split; intro H.\n  - induction H.\n    constructor.\n    simpl.\n    pose proof (path_trans_inv1 (rev_nfa g) q3 q2 q1 (rev w) a).\n    apply H1.\n    2: apply rev_transition in H.\n    1,2: intuition.\n  - rewrite <- rev_twice;\n    remember (rev w) as w'; clear Heqw' w.\n    induction H.\n    constructor.\n    simpl.\n    pose proof (path_trans_inv1 g q3 q2 q1 (rev w) a).\n    apply H1.\n    2: apply rev_transition.\n    1,2: intuition.\nQed.\n\n(* And for the extended transition function *)\nLemma rev_ext_transitionf g q1 q2 w :\n  In q1 (ext_transitionf g [q2] w) <->\n  In q2 (ext_transitionf (rev_nfa g) [q1] (rev w)).\nProof.\n  split; intro H.\n  - apply path_ext_transitionf;\n    apply path_ext_transitionf, rev_path in H;\n    intuition.\n  - apply path_ext_transitionf;\n    apply path_ext_transitionf, rev_path in H;\n    intuition.\nQed.\n\n(* The reversed language *)\nLemma rev_language g w :\n  nfa_accepts g w <-> nfa_accepts (rev_nfa g) (rev w).\nProof.\n  unfold nfa_accepts, NFA.nfa_accepts, has_accept_state; split; intros [q [H H0]].\n  - apply ext_transitionf_singleton in H; destruct H as [q0 [H H1]].\n    apply path_ext_transitionf in H1.\n    apply rev_path in H1.\n    pose proof (path_ext_transitionf State_eq_dec Symbol_eq_dec (rev_nfa g) q q0 (rev w)) as H2.\n    apply H2 in H1.\n    exists q0; split.\n    2: rewrite rev_start_states.\n    apply ext_transitionf_generalize with q.\n    rewrite rev_accept_states.\n    1-3: intuition.\n  - apply ext_transitionf_singleton in H; destruct H as [q0 [H H1]].\n    apply path_ext_transitionf in H1.\n    apply rev_path in H1.\n    pose proof (path_ext_transitionf State_eq_dec Symbol_eq_dec g q q0 w) as H2.\n    apply H2 in H1.\n    exists q0; split.\n    2: rewrite <- rev_accept_states.\n    apply ext_transitionf_generalize with q.\n    rewrite <- rev_start_states.\n    1-3: intuition.\nQed.\n\nEnd Reversing.", "meta": {"author": "fil1pe", "repo": "brzozowski-algorithm", "sha": "66bdff98c14c203d9f88cb6fe2b5c81612a81439", "save_path": "github-repos/coq/fil1pe-brzozowski-algorithm", "path": "github-repos/coq/fil1pe-brzozowski-algorithm/brzozowski-algorithm-66bdff98c14c203d9f88cb6fe2b5c81612a81439/Reversing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6508572324720046}}
{"text": "Require Import Coq.Program.Program.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Arith.Bool_nat.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Relations.Relations.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Wellfounded.Lexicographic_Product.\n\nGeneralizable All Variables.\n\nReserved Infix \"⊓\" (at level 40, left associativity).\nReserved Infix \"⊔\" (at level 36, left associativity).\n\nClass Lattice (A : Type) := {\n  meet : A -> A -> A where \"x ⊓ y\" := (meet x y);\n  join : A -> A -> A where \"x ⊔ y\" := (join x y);\n\n  meet_commutative : forall a b, a ⊓ b = b ⊓ a;\n  meet_associative : forall a b c, (a ⊓ b) ⊓ c = a ⊓ (b ⊓ c);\n  meet_absorptive  : forall a b, a ⊓ (a ⊔ b) = a;\n  meet_idempotent  : forall a, a ⊓ a = a;\n\n  join_commutative : forall a b, a ⊔ b = b ⊔ a;\n  join_associative : forall a b c, (a ⊔ b) ⊔ c = a ⊔ (b ⊔ c);\n  join_absorptive  : forall a b, a ⊔ (a ⊓ b) = a;\n  join_idempotent  : forall a, a ⊔ a = a\n}.\n\nInfix \"⊓\" := meet (at level 40, left associativity).\nInfix \"⊔\" := join (at level 36, left associativity).\n\nClass Order (A : Set) := {\n  ord : relation A;\n\n  reflexive :> Reflexive ord;\n  antisymmetric : forall {x y}, ord x y -> ord y x -> x = y;\n  transitive :> Transitive ord\n}.\n\nInfix \"≤\" := ord (at level 50).\n\nClass LOSet {A : Set} `(@Order A) `(@Lattice A) := {\n  meet_consistent : forall a b, a ≤ b <-> a = a ⊓ b;\n  join_consistent : forall a b, a ≤ b <-> b = a ⊔ b\n}.\n\nSection Lattice.\n\nContext `{O : Order A}.\nContext `{L : Lattice A}.\nContext `{@LOSet A O L}.\n\nTheorem meet_is_glb : forall a b : A,\n  forall x, x ≤ a /\\ x ≤ b <-> x ≤ a ⊓ b.\nProof.\n  split; intros.\n    intuition.\n    apply meet_consistent in H1.\n    apply meet_consistent in H2.\n    apply meet_consistent.\n    rewrite <- meet_associative, <- H1.\n    assumption.\n  apply meet_consistent in H0.\n  rewrite H0; clear H0.\n  split; apply meet_consistent.\n    rewrite meet_associative.\n    rewrite (meet_commutative (a ⊓ b) a).\n    rewrite <- (meet_associative a).\n    rewrite meet_idempotent.\n    reflexivity.\n  rewrite meet_associative.\n  rewrite meet_associative.\n  rewrite meet_idempotent.\n  reflexivity.\nQed.\n\nTheorem meet_prime : forall a b : A,\n  forall x, a ≤ x \\/ b ≤ x -> a ⊓ b ≤ x.\nProof.\n  intros.\n  destruct H0;\n  apply meet_consistent in H0;\n  apply meet_consistent; [rewrite meet_commutative|];\n  rewrite meet_associative;\n  rewrite <- H0; reflexivity.\nQed.\n\nTheorem join_is_lub : forall a b : A,\n  forall x, a ≤ x /\\ b ≤ x <-> a ⊔ b ≤ x.\nProof.\n  split; intros.\n    intuition.\n    apply join_consistent in H1.\n    apply join_consistent in H2.\n    apply join_consistent.\n    rewrite join_associative, <- H2.\n    assumption.\n  apply join_consistent in H0.\n  rewrite H0; clear H0.\n  split; apply join_consistent.\n    rewrite <- join_associative.\n    rewrite <- join_associative.\n    rewrite join_idempotent.\n    reflexivity.\n  rewrite (join_commutative a b).\n  rewrite <- join_associative.\n  rewrite <- join_associative.\n  rewrite join_idempotent.\n  reflexivity.\nQed.\n\nTheorem join_prime : forall a b : A,\n  forall x, x ≤ a \\/ x ≤ b -> x ≤ a ⊔ b.\nProof.\n  intros.\n  destruct H0;\n  apply join_consistent in H0;\n  apply join_consistent; [|rewrite join_commutative];\n  rewrite <- join_associative;\n  rewrite <- H0; reflexivity.\nQed.\n\nSet Decidable Equality Schemes.\n\nInductive Term : Set :=\n  | Var  : nat  -> Term\n  | Meet : Term -> Term -> Term\n  | Join : Term -> Term -> Term.\n\nLemma Meet_acc_l x y : Meet x y <> x.\nProof.\n  induction x;\n  unfold not; intros;\n  try discriminate.\n  inversion H0; subst.\n  contradiction.\nQed.\n\nLemma Meet_acc_r x y : Meet x y <> y.\nProof.\n  induction y;\n  unfold not; intros;\n  try discriminate.\n  inversion H0; subst.\n  contradiction.\nQed.\n\nLemma Join_acc_l x y : Join x y <> x.\nProof.\n  induction x;\n  unfold not; intros;\n  try discriminate.\n  inversion H0; subst.\n  contradiction.\nQed.\n\nLemma Join_acc_r x y : Join x y <> y.\nProof.\n  induction y;\n  unfold not; intros;\n  try discriminate.\n  inversion H0; subst.\n  contradiction.\nQed.\n\nFixpoint length (t : Term) : nat :=\n  match t with\n  | Var n => 1\n  | Meet t1 t2 => 1 + length t1 + length t2\n  | Join t1 t2 => 1 + length t1 + length t2\n  end.\n\nFixpoint depth (t : Term) : nat :=\n  match t with\n  | Var n => 0\n  | Meet t1 t2 => 1 + max (depth t1) (depth t2)\n  | Join t1 t2 => 1 + max (depth t1) (depth t2)\n  end.\n\nInductive Subterm : Term -> Term -> Prop :=\n  | Meet1 : forall t1 t2, Subterm t1 (Meet t1 t2)\n  | Meet2 : forall t1 t2, Subterm t2 (Meet t1 t2)\n  | Join1 : forall t1 t2, Subterm t1 (Join t1 t2)\n  | Join2 : forall t1 t2, Subterm t2 (Join t1 t2).\n\nDefinition Subterm_inv_t : forall x y, Subterm x y -> Prop.\nProof.\n  intros [] [] f;\n  match goal with\n  | [ H : Subterm ?X (Meet ?Y ?Z) |- Prop ] =>\n    destruct (Term_eq_dec X Y); subst;\n    [ destruct (Term_eq_dec X Z); subst;\n      [ exact (f = Meet1 _ _ \\/ f = Meet2 _ _)\n      | exact (f = Meet1 _ _) ]\n    | destruct (Term_eq_dec X Z); subst;\n      [ exact (f = Meet2 _ _)\n      | exact False ] ]\n  | [ H : Subterm ?X (Join ?Y ?Z) |- Prop ] =>\n    destruct (Term_eq_dec X Y); subst;\n    [ destruct (Term_eq_dec X Z); subst;\n      [ exact (f = Join1 _ _ \\/ f = Join2 _ _)\n      | exact (f = Join1 _ _) ]\n    | destruct (Term_eq_dec X Z); subst;\n      [ exact (f = Join2 _ _)\n      | exact False ] ]\n  | _ => exact False\n  end.\nDefined.\n\nCorollary Subterm_inv x y f : Subterm_inv_t x y f.\nProof.\n  pose proof Term_eq_dec.\n  destruct f, t1, t2; simpl;\n  destruct (Term_eq_dec _ _); subst;\n  try destruct (Term_eq_dec _ _); subst;\n  try (rewrite e || rewrite <- e; clear e);\n  try (rewrite e0 || rewrite <- e0; clear e0);\n  try congruence;\n  try rewrite <- Eqdep_dec.eq_rect_eq_dec; eauto; simpl; intuition;\n  try rewrite <- Eqdep_dec.eq_rect_eq_dec; eauto; simpl; intuition;\n  try (unfold eq_rect; destruct e0; intuition);\n  try (unfold eq_rect; destruct e; intuition).\nQed.\n\nProgram Instance Subterm_Irreflexive : Irreflexive Subterm.\nNext Obligation.\n  repeat intro.\n  pose proof (Subterm_inv _ _ H0).\n  inversion H0; subst; simpl in *.\n  - now apply (Meet_acc_l x t2).\n  - now apply (Meet_acc_r t1 x).\n  - now apply (Join_acc_l x t2).\n  - now apply (Join_acc_r t1 x).\nQed.\n\nLemma Subterm_wf : well_founded Subterm.\nProof.\n  constructor; intros.\n  inversion H0; subst; simpl in *;\n  induction y;\n  induction t1 || induction t2;\n  simpl in *;\n  constructor; intros;\n  inversion H1; subst; clear H1;\n  try (apply IHy1; constructor);\n  try (apply IHy2; constructor).\nDefined.\n\nReserved Notation \"〚 t 〛 env\" (at level 9).\n\nFixpoint eval (t : Term) (env : nat -> A) : A :=\n  match t with\n  | Var n => env n\n  | Meet t1 t2 => 〚t1〛env ⊓ 〚t2〛env\n  | Join t1 t2 => 〚t1〛env ⊔ 〚t2〛env\n  end where \"〚 t 〛 env\" := (eval t env).\n\nDefinition Leq   (s t : Term) : Prop := forall env, 〚s〛env ≤ 〚t〛env.\nArguments Leq _ _ /.\n\n(* Note that Equiv can be computed from Leq. *)\nDefinition Equiv (s t : Term) : Prop := forall env, 〚s〛env = 〚t〛env.\nArguments Equiv _ _ /.\n\nReserved Infix \"≲\" (at level 30).\n\nDefinition R := symprod Term Term Subterm Subterm.\nArguments R /.\n\nOpen Scope lazy_bool_scope.\n\nLtac meets_and_joins leq :=\n  repeat destruct (leq (_, _) _);\n  simpl in *;\n  subst;\n  repeat match goal with\n  | [ H : (_, _) = (_, _) |- _ ] => progress (inversion H; subst)\n  | [ H : bool |- _ ] => destruct H\n  end;\n  try discriminate;\n  simpl in *;\n  repeat match goal with\n  | [ |- _ ⊔ _ ≤ _ ] => apply join_is_lub; split; firstorder idtac\n  | [ |- _ ≤ _ ⊔ _ ] => apply join_prime; firstorder idtac\n  | [ |- _ ≤ _ ⊓ _ ] => apply meet_is_glb; split; firstorder idtac\n  | [ |- _ ⊓ _ ≤ _ ] => apply meet_prime; firstorder idtac\n  end.\n\nLocal Obligation Tactic :=\n  program_simpl; try (constructor; constructor).\n\nSet Transparent Obligations.\n\n(* Whitman's decision procedure. *)\nProgram Fixpoint leq (p : Term * Term) {wf R p} :\n  { b : bool | b = true -> Leq (fst p) (snd p) } :=\n  match p with\n  (* 1. If s = Var i and t = Var j, then s ≲ t holds iff i = j. *)\n  | (Var i, Var j) => nat_eq_bool i j\n\n  (* 2. If s = Join s1 s2, then s ≲ t holds iff s1 ≲ t and s2 ≲ t. *)\n  | (Join s1 s2, t) =>\n    exist _ (proj1_sig (leq (s1, t)) &&& proj1_sig (leq (s2, t))) _\n\n  (* 3. If t = Meet t1 t2, then s ≲ t holds iff s ≲ t1 and s ≲ t2. *)\n  | (s, Meet t1 t2) =>\n    exist _ (proj1_sig (leq (s, t1)) &&& proj1_sig (leq (s, t2))) _\n\n  (* 4. If s = Var i and t = Join t1 t2, then s ≲ t holds iff s ≲ t1 or s ≲ t2. *)\n  | (Var i, Join t1 t2) =>\n    exist _ (proj1_sig (leq (Var i, t1)) ||| proj1_sig (leq (Var i, t2))) _\n\n  (* 5. If s = Meet s1 s2 and t = Var i, then s ≲ t holds iff s1 ≲ t or s2 ≲ t. *)\n  | (Meet s1 s2, Var i) =>\n    exist _ (proj1_sig (leq (s1, Var i)) ||| proj1_sig (leq (s2, Var i))) _\n\n  (* 6. If s = Meet s1 s2 and t = Join t1 t2, then s ≲ t holds iff s1 ≲ t or\n        s2 ≲ t or s ≲ t1 or s ≲ t2. *)\n  | (Meet s1 s2, Join t1 t2) =>\n    exist _ (proj1_sig (leq (s1, Join t1 t2)) |||\n             proj1_sig (leq (s2, Join t1 t2)) |||\n             proj1_sig (leq (Meet s1 s2, t1)) |||\n             proj1_sig (leq (Meet s1 s2, t2))) _\n  end.\nNext Obligation.\n  destruct (nat_eq_bool i j); simpl in *; subst.\n  rewrite y; reflexivity.\nDefined.\nNext Obligation. meets_and_joins leq. Defined.\nNext Obligation. meets_and_joins leq. Defined.\nNext Obligation. meets_and_joins leq. Defined.\nNext Obligation. meets_and_joins leq. Defined.\nNext Obligation.\n  repeat destruct (leq (_, _)); simpl in *.\n  destruct x.  apply meet_prime; left;  apply o;  reflexivity.\n  destruct x0. apply meet_prime; right; apply o0; reflexivity.\n  destruct x1. apply join_prime; left;  apply o1; reflexivity.\n  destruct x2. apply join_prime; right; apply o2; reflexivity.\n  discriminate.\nDefined.\nNext Obligation.\n  apply wf_symprod;\n  apply Subterm_wf.\nDefined.\n\nNotation \"s ≲ t\" := (leq (s, t)) (at level 30).\n\nDefinition leq_correct {t u : Term} (Heq : ` (t ≲ u) = true) :\n  forall env, 〚t〛env ≤ 〚u〛env := proj2_sig (t ≲ u) Heq.\n\nInductive Logic : Set :=\n  | LLe   : Term  -> Term  -> Logic\n  | LAnd  : Logic -> Logic -> Logic\n  | LOr   : Logic -> Logic -> Logic\n  | LImpl : Logic -> Logic -> Logic.\n\nFixpoint logicDenote (t : Logic) (env : nat -> A) : Prop :=\n  match t with\n  | LLe   x y => 〚x〛env ≤ 〚y〛env\n  | LAnd  x y => logicDenote x env /\\ logicDenote y env\n  | LOr   x y => logicDenote x env \\/ logicDenote y env\n  | LImpl x y => logicDenote x env -> logicDenote y env\n  end.\n\nInductive AndOr {A B : Type} : Type :=\n  | AO_Terms : A -> B    -> AndOr\n  | AO_And   : AndOr -> AndOr -> AndOr\n  | AO_Or    : AndOr -> AndOr -> AndOr.\n\nProgram Fixpoint normLe (p : Term * Term) {wf (R) p} : @AndOr Term Term :=\n  match p with\n  | (Meet a b, c) => AO_Or  (normLe (a, c)) (normLe (b, c))\n  | (Join a b, c) => AO_And (normLe (a, c)) (normLe (b, c))\n  | (c, Meet a b) => AO_And (normLe (c, a)) (normLe (c, b))\n  | (c, Join a b) => AO_Or  (normLe (c, a)) (normLe (c, b))\n  | (a, b) => AO_Terms a b\n  end.\nNext Obligation.\n  intuition; match goal with [ H : _ = _ |- _ ] => inversion H end.\nDefined.\nNext Obligation.\n  intuition; match goal with [ H : _ = _ |- _ ] => inversion H end.\nDefined.\nNext Obligation.\n  intuition; match goal with [ H : _ = _ |- _ ] => inversion H end.\nDefined.\nNext Obligation.\n  apply measure_wf.\n  apply wf_symprod;\n  apply Subterm_wf.\nDefined.\n\nFixpoint denoteAndOr (t : @AndOr Term Term) : Logic :=\n  match t with\n  | AO_Terms x y => LLe x y\n  | AO_And   x y => LAnd (denoteAndOr x) (denoteAndOr y)\n  | AO_Or    x y => LOr (denoteAndOr x) (denoteAndOr y)\n  end.\n\nProgram Fixpoint logicNorm (t : Logic) : Logic :=\n  match t with\n  | LLe a b => denoteAndOr (normLe (a, b))\n\n  | LAnd  x y => LAnd (logicNorm x) (logicNorm y)\n  | LOr   x y => LOr  (logicNorm x) (logicNorm y)\n\n  | LImpl x y =>\n    match logicNorm y with\n    | LImpl y z => LImpl (LAnd (logicNorm x) y) z\n    | y => LImpl (logicNorm x) y\n    end\n  end.\n\nTheorem logicNorm_sound : forall x env,\n  logicDenote x env <->\n  logicDenote (logicNorm x) env.\nProof.\nAdmitted.\n\n(*\nDefinition markVars (t : Term) (env : nat -> A) (f : nat -> bool) :\n  nat -> bool :=\n  let fix go t f :=\n      match t with\n      | Var x    => fun n => (x =? n) ||| f n\n      | Meet x y => go x (go y f) (* jww (2017-06-18): correct? *)\n      | Join x y => go x (go y f)\n      end in\n  go t (fun _ => false).\n\nFixpoint markLogic (t : Logic) (env : nat -> A) : Prop :=\n  match t with\n  | LLe   x y => 〚x〛env ≤ 〚y〛env\n  | LAnd  x y => logicDenote x env /\\ logicDenote y env\n  | LOr   x y => logicDenote x env \\/ logicDenote y env\n  | LImpl x y => logicDenote x env -> logicDenote y env\n  end.\n\nFixpoint logicCheck (t : Logic) (env : nat -> A) : Prop :=\n  match t with\n  | LLe   x y => 〚x〛env ≤ 〚y〛env\n  | LAnd  x y => logicDenote x env /\\ logicDenote y env\n  | LOr   x y => logicDenote x env \\/ logicDenote y env\n  | LImpl x y => logicDenote x env -> logicDenote y env\n  end.\n\nProgram Fixpoint determine_truth (t : Logic) {struct t} :\n  { b : bool | b = true -> forall env, logicDenote t env } :=\n  match t with\n  | LLe   x y => leq (x, y)\n  | LAnd  x y => exist _ (` (determine_truth x) &&& ` (determine_truth y)) _\n  | LOr   x y => exist _ (` (determine_truth x) ||| ` (determine_truth y)) _\n  | LImpl x y => exist _ (if ` (determine_truth x)\n                          then ` (determine_truth y)\n                          else false) _\n  end.\nNext Obligation. destruct x0; intuition. Defined.\nNext Obligation. destruct x0; intuition. Defined.\nNext Obligation. destruct x0; intuition. Defined.\n*)\n\nEnd Lattice.\n\nNotation \"〚 t 〛 env\" := (@eval _ _ t env) (at level 9).\nNotation \"s ≲ t\" := (@leq _ _ _ _ (s, t)) (at level 30).\n\nImport ListNotations.\n\nLtac inList x xs :=\n  match xs with\n  | tt => false\n  | (x, _) => true\n  | (_, ?xs') => inList x xs'\n  end.\n\nLtac addToList x xs :=\n  let b := inList x xs in\n  match b with\n  | true => xs\n  | false => constr:((x, xs))\n  end.\n\nLtac allVars xs e :=\n  match e with\n  | ?e1 ⊓ ?e2 =>\n    let xs := allVars xs e1 in\n    allVars xs e2\n  | ?e1 ⊔ ?e2 =>\n    let xs := allVars xs e1 in\n    allVars xs e2\n  | _ => addToList e xs\n  end.\n\nLtac lookup x xs :=\n  match xs with\n  | (x, _) => O\n  | (_, ?xs') =>\n    let n := lookup x xs' in\n    constr:(S n)\n  end.\n\nLtac reifyTerm env t :=\n  match t with\n  | ?X1 ⊓ ?X2 =>\n    let r1 := reifyTerm env X1 in\n    let r2 := reifyTerm env X2 in\n    constr:(Meet r1 r2)\n  | ?X1 ⊔ ?X2 =>\n    let r1 := reifyTerm env X1 in\n    let r2 := reifyTerm env X2 in\n    constr:(Join r1 r2)\n  | ?X =>\n    let n := lookup X env in\n    constr:(Var n)\n  end.\n\nLtac functionalize xs :=\n  let rec loop n xs' :=\n    match xs' with\n    | (?x, tt) => constr:(fun _ : nat => x)\n    | (?x, ?xs'') =>\n      let f := loop (S n) xs'' in\n      constr:(fun m : nat => if m =? n then x else f m)\n    end in\n  loop 0 xs.\n\nLtac reify :=\n  match goal with\n  | [ |- ?S ≤ ?T ] =>\n    let xs  := allVars tt S in\n    let xs' := allVars xs T in\n    let r1  := reifyTerm xs' S in\n    let r2  := reifyTerm xs' T in\n    let env := functionalize xs' in\n    (* pose xs'; *)\n    (* pose env; *)\n    (* pose r1; *)\n    (* pose r2; *)\n    change (〚r1〛env ≤ 〚r2〛env)\n  end.\n\nLtac lattice := reify; apply leq_correct; vm_compute; auto.\n\nExample sample_1 `{LOSet A} : forall a b : A,\n  a ≤ a ⊔ b.\nProof. intros; lattice. Qed.\n\nLemma running_example `{LOSet A} : forall a b : A,\n  a ⊓ b ≤ a ⊔ b.\nProof.\n  intros a b.\n  rewrite meet_consistent.\n  rewrite meet_associative.\n  rewrite join_commutative.\n  rewrite meet_absorptive.\n  reflexivity.\nQed.\n\nLemma running_example' `{LOSet A} : forall a b : A,\n  a ⊓ b ≤ a ⊔ b.\nProof. intros; lattice. Qed.\n\nLemma median_inequality `{LOSet A} : forall x y z : A,\n  (x ⊓ y) ⊔ (y ⊓ z) ⊔ (z ⊓ x) ≤ (x ⊔ y) ⊓ (y ⊔ z) ⊓ (z ⊔ x).\nProof. intros; lattice. Qed.\n\nLtac allVarsLogic xs e :=\n  match e with\n  | ?X1 ≤ ?X2 =>\n    let xs := allVars xs X1 in\n    allVars xs X2\n  | ?X1 /\\ ?X2 =>\n    let xs := allVarsLogic xs X1 in\n    allVarsLogic xs X2\n  | ?X1 \\/ ?X2 =>\n    let xs := allVarsLogic xs X1 in\n    allVarsLogic xs X2\n  | ~ ?X1 =>\n    allVarsLogic xs X1\n  | ?X1 -> ?X2 =>\n    let xs := allVarsLogic xs X1 in\n    allVarsLogic xs X2\n  end.\n\nLtac reifyLogic env t :=\n  match t with\n  | ?X1 ≤ ?X2 =>\n    let r1 := reifyTerm env X1 in\n    let r2 := reifyTerm env X2 in\n    constr:(LLe r1 r2)\n  | ?X1 /\\ ?X2 =>\n    let r1 := reifyLogic env X1 in\n    let r2 := reifyLogic env X2 in\n    constr:(LAnd r1 r2)\n  | ?X1 \\/ ?X2 =>\n    let r1 := reifyLogic env X1 in\n    let r2 := reifyLogic env X2 in\n    constr:(LOr r1 r2)\n  | ?X1 -> ?X2 =>\n    let r1 := reifyLogic env X1 in\n    let r2 := reifyLogic env X2 in\n    constr:(LImpl r1 r2)\n  end.\n\nLtac lattice' :=\n  match goal with\n  | [ |- ?P ] =>\n    let xs := allVarsLogic tt P in\n    let r1 := reifyLogic xs P in\n    let env := functionalize xs in\n    (* pose xs; *)\n    (* pose r1; *)\n    (* pose env; *)\n    change (logicDenote r1 env);\n    apply logicNorm_sound;\n    let p := fresh \"p\" in\n    let Heqp := fresh \"Heqp\" in\n    remember (logicNorm _) as p eqn:Heqp;\n    vm_compute in Heqp;\n    rewrite Heqp; clear Heqp p\n    (* vm_compute; *)\n    (* intuition idtac *)\n  end.\n\nLemma example_3 `{LOSet A} : forall a b c : A,\n  b ≤ a ⊔ b ->\n  a ⊓ c ≤ a ->\n  a ⊓ b ≤ c ->\n  a ⊓ c ≤ b.\nProof.\n  intros a b c.\n  lattice'.\n  simpl.\n  intuition.\nAdmitted.\n\nLemma median_inequality' `{LOSet A} : forall x y z : A,\n  (x ⊓ y) ⊔ (y ⊓ z) ⊔ (z ⊓ x) ≤ (x ⊔ y) ⊓ (y ⊔ z) ⊓ (z ⊔ x).\nProof.\n  intros.\n  lattice.\nQed.\n", "meta": {"author": "jwiegley", "repo": "coq-lattice", "sha": "87b292b7926569a0826efae7d95341c555ea44c3", "save_path": "github-repos/coq/jwiegley-coq-lattice", "path": "github-repos/coq/jwiegley-coq-lattice/coq-lattice-87b292b7926569a0826efae7d95341c555ea44c3/Lattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6508572229993939}}
{"text": "Require Export D1_DistanceProp.\n\nSection AXIS.\n\nRequire Export Arith.\n\nVariables A B : Point.\n\nHypothesis Hab : A <> B.\n\nDefinition StrongGraduation : forall n : nat,\n\t{N : Point | HalfLine A N B /\\ Distance A N = DistTimesn n A B /\\ (n > 0 -> A <> N)}.\nProof.\n\tintro n.\n\t case n.\n\t  exists A; repeat split.\n\t   canonize.\n\t     elim (NotClockwiseAAB A x H).\n\t   intro H; inversion H.\n\t  induction n0.\n\t   exists B; repeat split.\n\t    canonize.\n\t    simpl in |- *.\n\t      rewrite NullDist; rewrite LS0NeutralRight; trivial.\n\t    intuition.\n\t   destruct IHn0 as (N, (H1, (H2, H3))).\n\t     assert (H : A <> N).\n\t    intuition.\n\t    destruct (ExistsBetweenEquidistant N A A B) as (P, (H4, H5)).\n\t     auto.\n\t     trivial.\n\t     exists P; repeat split.\n\t      assert (H6 := BetweenSymHalfLine _ _ _ H4).\n\t        assert (H7 := HalfLineSym A N P H H6).\n\t        canonize.\n\t      change\n\t        (DistTimesn (S (S n0)) A B) with (LSplus (Distance A B)\n\t                                            (DistTimesn (S n0) A B)) in |- *.\n\t        rewrite <- H2; rewrite <- H5; rewrite LSplusComm.\n\t       rewrite ChaslesBetween.\n\t        trivial.\n\t        apply BetweenSym; trivial.\n\t       apply (EquiDistantDistinct A B); trivial.\n\t         autoDistance.\n\t       trivial.\n\t      intros _; exact (BetweenDistinctCA _ _ _ H4).\nDefined.\n\nDefinition Graduation : forall n : nat,\n\t{N : Point | HalfLine A N B /\\ Distance A N = DistTimesn n A B}.\nProof.\n\tintro n; destruct (StrongGraduation n) as (P, H0); exists P; intuition.\nDefined.\n\nEnd AXIS.\n", "meta": {"author": "coq-contribs", "repo": "ruler-compass-geometry", "sha": "ee36f5cd523abaa2e0b676c4100c02ec496c0bfd", "save_path": "github-repos/coq/coq-contribs-ruler-compass-geometry", "path": "github-repos/coq/coq-contribs-ruler-compass-geometry/ruler-compass-geometry-ee36f5cd523abaa2e0b676c4100c02ec496c0bfd/D2_Axe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6508568769610855}}
{"text": "Require Import SecOrder.\nRequire Import P_occurs_in_alpha.\nRequire Import ST_setup.\nRequire Import Correctness_ST.\nRequire Import Arith.EqNat.\nRequire Import List_machinery_impl My_List_Map my_arith__my_leb_nat.\nRequire Import Unary_Predless nList_egs Rep_Pred_FOv Indicies Unary_Predless_l List.\n(* \n  Uniform_Mod_Lemmas8a\n*)\n\n(* ---------------------------------------------------------  *)\n\nDefinition num_occ (alpha : SecOrder) (Q : predicate) : nat :=\n  length (indicies alpha Q).\n\nLemma num_occ_conjSO2 : forall (alpha1 alpha2 : SecOrder) (Q : predicate),\n  num_occ (conjSO alpha1 alpha2) Q =  (length (indicies alpha1 Q)) +\n                                       (length (indicies alpha2 Q)).\nProof.\n  intros.\n  unfold num_occ.\n  rewrite indicies_conjSO.\n  rewrite app_length.\n  unfold indicies.\n  do 3 rewrite list_map_length.\n  reflexivity.\nQed.\n\nLemma num_occ_disjSO2 : forall (alpha1 alpha2 : SecOrder) (Q : predicate),\n  num_occ (disjSO alpha1 alpha2) Q =  (length (indicies alpha1 Q)) +\n                                       (length (indicies alpha2 Q)).\nProof.\n  intros.\n  unfold num_occ.\n  rewrite indicies_disjSO.\n  rewrite app_length.\n  unfold indicies.\n  do 3 rewrite list_map_length.\n  reflexivity.\nQed.\n\nLemma num_occ_predSO : forall (P Q : predicate) (x : FOvariable),\n  num_occ (predSO P x) Q = match P, Q with\n                           | Pred Pn, Pred Qm =>\n                          if beq_nat Pn Qm then 1 else 0\n                          end.\nProof.\n  intros.\n  destruct P as [Pn]; destruct Q as [Qm]; destruct x as [xn].\n  unfold num_occ.\n  unfold indicies.\n  simpl.\n  rewrite list_map_length.\n  case (beq_nat Pn Qm); simpl; reflexivity.\nQed.\n  \n\nLemma num_occ_allSO : forall (alpha : SecOrder) (P Q : predicate),\n  num_occ (allSO P alpha) Q = match P, Q with\n                           | Pred Pn, Pred Qm =>\n                          if beq_nat Pn Qm then 1 + num_occ alpha Q else num_occ alpha Q\n                          end.\nProof.\n  intros.\n  destruct P as [Pn]; destruct Q as [Qm].\n  unfold num_occ.\n  unfold indicies.\n  simpl.\n  do 2 rewrite list_map_length.\n  case (beq_nat Pn Qm); simpl; reflexivity.\nQed.\n\n(* ---------------------------------------------------------  *)\n\nFixpoint is_in_l (l : list nat) (i : nat) : bool :=\n  match l with\n  | nil => false\n  | cons n l' => if beq_nat i n then true else is_in_l l' i\n  end.\n\nLemma is_in_l_app : forall (l1 l2 : list nat) (i : nat),\n  is_in_l (l1 ++ l2) i = if is_in_l l1 i \n                          then true\n                          else is_in_l l2 i.\nProof.\n  intros.\n  induction l1.\n    simpl; reflexivity.\n\n    simpl.\n    rewrite IHl1.\n    case (beq_nat i a);\n      reflexivity.\nQed.\n\n(* ---------------------------------------------------------  *)\n\nFixpoint num_occ_diff_l (l : list nat) (i : nat) : nat :=\n  if is_in_l l i then 0 else\n  match l with\n  | nil => 0\n  | cons n l' => if Nat.leb n i \n                    then 1 + num_occ_diff_l l' i\n                    else num_occ_diff_l l' i\n  end.\n\nLemma num_occ_diff_l_defn : forall (l : list nat) (i : nat),\n  num_occ_diff_l l i =\n  if is_in_l l i then 0 else\n  match l with\n  | nil => 0\n  | cons n l' => if Nat.leb n i \n                    then 1 + num_occ_diff_l l' i\n                    else num_occ_diff_l l' i\n  end.\nProof.\n  intros.\n  unfold num_occ_diff_l.\n  induction l; simpl; reflexivity.\nQed.\n\nLemma num_occ_diff_l_cons : forall (l : list nat) (a i : nat),\n  num_occ_diff_l (cons a l) i =\n    if is_in_l (cons a l) i \n       then 0 \n       else if Nat.leb a i \n               then 1 + num_occ_diff_l l i\n               else num_occ_diff_l l i.\nProof.\n  intros; simpl.\n  reflexivity.\nQed.\n\nLemma num_occ_diff_l_app : forall (l1 l2 : list nat) (i : nat),\n  is_in_l l1 i = false ->\n    is_in_l l2 i = false ->\n      num_occ_diff_l (app l1 l2) i =\n        (num_occ_diff_l l1 i) + (num_occ_diff_l l2 i).\nProof.\n  induction l1.\n    intros.\n    simpl; reflexivity.\n\n    intros l2 i H1 H2.\n    rewrite num_occ_diff_l_cons.\n    rewrite H1.\n    simpl in *.\n    case_eq (beq_nat i a); intros Hbeq; rewrite Hbeq in *.\n      discriminate.\n\n      rewrite is_in_l_app.\n      rewrite IHl1.\n      rewrite H1.\n      rewrite H2.\n      case (Nat.leb a i).\n        simpl; reflexivity.\n\n        reflexivity.\n\n      assumption.\n\n      assumption.\nQed.\n\nDefinition num_occ_diff (alpha : SecOrder) (Q : predicate) (i : nat)\n                                              : nat :=\n  num_occ_diff_l (indicies alpha Q) i.\n\n\nLemma num_occ_diff_relatSO : forall ( x y : FOvariable)\n                                   (Q : predicate) (i : nat),\n  num_occ_diff (relatSO x y) Q i = 0.\nProof.\n  intros x y Q i.\n  unfold num_occ_diff.\n  unfold indicies.\n  destruct x; destruct y.\n  simpl.\n  reflexivity.\nQed.\n\nLemma num_occ_diff_eqFO : forall ( x y : FOvariable)\n                                   (Q : predicate) (i : nat),\n  num_occ_diff (eqFO x y) Q i = 0.\nProof.\n  intros x y Q i.\n  unfold num_occ_diff.\n  unfold indicies.\n  destruct x; destruct y.\n  simpl.\n  reflexivity.\nQed.\n\n\nLemma num_occ_diff_allFO : forall (alpha : SecOrder) (x : FOvariable)\n                                  (Q : predicate) (i : nat),\n  num_occ_diff (allFO x alpha) Q i = \n    num_occ_diff alpha Q i.\nProof.\n  intros.\n  unfold num_occ_diff.\n  unfold num_occ_diff_l.\n  reflexivity.\nQed.\n\nLemma num_occ_diff_exFO : forall (alpha : SecOrder) (x : FOvariable)\n                                  (Q : predicate) (i : nat),\n  num_occ_diff (exFO x alpha) Q i = \n    num_occ_diff alpha Q i.\nProof.\n  intros.\n  unfold num_occ_diff.\n  unfold num_occ_diff_l.\n  unfold indicies.\n  simpl.\n  destruct x.\n  reflexivity.\nQed.\n\nLemma num_occ_diff_negSO : forall (alpha : SecOrder)\n                                  (Q : predicate) (i : nat),\n  num_occ_diff (negSO alpha) Q i = \n    num_occ_diff alpha Q i.\nProof.\n  intros.\n  unfold num_occ_diff.\n  unfold num_occ_diff_l.\n  unfold indicies.\n  simpl.\n  reflexivity.\nQed.\n\n(* ------------------------------------------------------------- *)\n\n\n\nLemma num_occ_diff_l_nil : forall (l : list nat),\n  (num_occ_diff_l l 0) = 0.\nProof.\n  induction l.\n    simpl; reflexivity.\n\n    destruct a.\n      reflexivity.\n\n      simpl.\n      rewrite IHl.\n      case (is_in_l l 0); reflexivity.\nQed.\n\nLemma num_occ_diff_nil : forall (alpha : SecOrder) (P : predicate),\n  (num_occ_diff alpha P 0) = 0.\nProof.\n  intros.\n  unfold num_occ_diff.\n  apply num_occ_diff_l_nil.\nQed.\n\n\n(* ------------------------------------------------------------- *)\n\n\nLemma num_occ_relatSO : forall (x y : FOvariable) (Q : predicate),\n   num_occ (relatSO x y) Q = 0.\nProof.\n  intros.\n  destruct x; destruct y; destruct Q.\n  unfold num_occ.\n  unfold indicies.\n  simpl.\n  reflexivity.\nQed.\n\n\nLemma num_occ_eqFO : forall (x y : FOvariable) (Q : predicate),\n   num_occ (eqFO x y) Q = 0.\nProof.\n  intros.\n  destruct x; destruct y; destruct Q.\n  unfold num_occ.\n  unfold indicies.\n  simpl.\n  reflexivity.\nQed.\n\n\n\nLemma num_occ_negSO : forall (alpha : SecOrder) (P : predicate),\n  num_occ (negSO alpha) P = num_occ alpha P.\nProof.\n   intros.\n  unfold num_occ.\n  unfold indicies.\n  simpl.\n  reflexivity.\nQed.\n\nLemma num_occ_allFO : forall (alpha : SecOrder) (x : FOvariable)\n                             (P : predicate),\n  num_occ (allFO x alpha) P = num_occ alpha P.\nProof.\n   intros.\n  unfold num_occ.\n  unfold indicies.\n  simpl.\n  reflexivity.\nQed.\n\nLemma num_occ_exFO : forall (alpha : SecOrder) (x : FOvariable)\n                             (P : predicate),\n  num_occ (exFO x alpha) P = num_occ alpha P.\nProof.\n   intros.\n  unfold num_occ.\n  unfold indicies.\n  simpl.\n  destruct x.\n  reflexivity.\nQed.\n\nLemma num_occ_conjSO : forall (alpha1 alpha2 : SecOrder)\n                             (P : predicate),\n  num_occ (conjSO alpha1 alpha2) P = num_occ alpha1 P + num_occ alpha2 P.\nProof.\n   intros.\n  unfold num_occ.\n  unfold indicies.\n  simpl.\n  rewrite app_length.\n  rewrite list_map_length.\n  rewrite list_map_length.\n  rewrite list_map_length.\n  rewrite indicies_l_rev_app.\n  rewrite app_length.\n  rewrite list_map_length.\n  reflexivity.\nQed.\n\nLemma num_occ_disjSO : forall (alpha1 alpha2 : SecOrder)\n                             (P : predicate),\n  num_occ (disjSO alpha1 alpha2) P = num_occ alpha1 P + num_occ alpha2 P.\nProof.\n   intros.\n  unfold num_occ.\n  unfold indicies.\n  simpl.\n  rewrite app_length.\n  rewrite list_map_length.\n  rewrite list_map_length.\n  rewrite list_map_length.\n  rewrite indicies_l_rev_app.\n  rewrite app_length.\n  rewrite list_map_length.\n  reflexivity.\nQed.\n\nLemma num_occ_implSO : forall (alpha1 alpha2 : SecOrder)\n                             (P : predicate),\n  num_occ (implSO alpha1 alpha2) P = num_occ alpha1 P + num_occ alpha2 P.\nProof.\n   intros.\n  unfold num_occ.\n  unfold indicies.\n  simpl.\n  rewrite app_length.\n  rewrite list_map_length.\n  rewrite list_map_length.\n  rewrite list_map_length.\n  rewrite indicies_l_rev_app.\n  rewrite app_length.\n  rewrite list_map_length.\n  reflexivity.\nQed.\n\nLemma num_occ_preds_in : forall (alpha : SecOrder) (P : predicate),\n  Nat.leb (num_occ alpha P) (length (preds_in alpha)) = true.\nProof.\n  intros.\n  induction alpha;\n    try destruct p as [Qm]; try destruct f as [xn];\n    try destruct P as [Pn]; try destruct f0 as [xm];\n    try (unfold num_occ in *; unfold indicies in *; simpl);\n    try reflexivity; try  rewrite list_map_length in *;\n    try rewrite list_map_length in IHalpha;\n    try rewrite list_map_length in IHalpha1;\n    try rewrite list_map_length in IHalpha2;\n    try (case (beq_nat Qm Pn); simpl; reflexivity);\n    try assumption;\n    try (rewrite indicies_l_rev_app;\n    do 2 rewrite app_length;\n    rewrite list_map_length;\n    apply leb_plus_gen; assumption);\n    (case_eq (beq_nat Qm Pn); intros Hbeq; [simpl | apply leb_suc_r];\n      assumption).\nQed.\n\n\nLemma  num_occ_ind_l_rev : forall (alpha : SecOrder) (P : predicate),\n  num_occ alpha P = length (indicies_l_rev (preds_in alpha) P).\nProof.\n  intros alpha P.\n  unfold num_occ.\n  unfold indicies.\n  rewrite list_map_length.\n  reflexivity.\nQed.\n\n\nLemma num_occ_rep_pred : forall alpha cond P x,\nis_unary_predless cond = true ->\nnum_occ (replace_pred alpha P x cond) P = 0.\nProof.\n  intros alpha cond P x Hcond.\n  unfold num_occ.\n  rewrite length_ind.\n  induction alpha;\n    try destruct p as [Pn]; try destruct P as [Qm];\n    try destruct f; try destruct f0;\n    simpl in *; try reflexivity;\n    try assumption;\n    try (rewrite indicies_l_rev_app; rewrite app_length;\n    rewrite list_map_length;\n    rewrite IHalpha1; rewrite IHalpha2;\n    reflexivity).\n    case_eq (beq_nat Qm Pn); intros Hbeq.\n      rewrite preds_in_rep_FOv.\n      rewrite un_predless_preds_in; try assumption.\n      reflexivity.\n\n      simpl.\n      rewrite beq_nat_comm.\n      rewrite Hbeq.\n      reflexivity.\n\n    case_eq (beq_nat Qm Pn); intros Hbeq.\n      assumption.\n\n      simpl.\n      rewrite beq_nat_comm.\n      rewrite Hbeq.\n      assumption.\n\n    case_eq (beq_nat Qm Pn); intros Hbeq.\n      assumption.\n\n      simpl.\n      rewrite beq_nat_comm.\n      rewrite Hbeq.\n      assumption.\nQed.\n\nLemma num_occ_rep_pred_0 : forall (alpha cond : SecOrder) (P Q : predicate)\n                                  (x : FOvariable),\nis_unary_predless cond = true ->\nnum_occ alpha P = 0 ->\nnum_occ (replace_pred alpha Q x cond) P = 0.\nProof.\n  induction alpha; intros cond P Q x Hcond Hnum;\n  unfold num_occ in *; rewrite length_ind in *;\n  simpl in *;\n    try destruct Q as [Qm]; try destruct p as [Pn];\n    try destruct f as [xn]; try destruct f0; try destruct P as [Rn];\n    try destruct x as [ym];\n    try reflexivity;\n    try (simpl in *;\n    specialize (IHalpha cond (Pred Rn) (Pred Qm) (Var ym) Hcond);\n    do 2 rewrite length_ind in *;\n    apply IHalpha; assumption);\n\n    try (simpl;\n    rewrite indicies_l_rev_app in *;\n    rewrite app_length in *;\n    rewrite list_map_length;\n    rewrite list_map_length in Hnum;\n    specialize (IHalpha1 cond (Pred Rn) (Pred Qm) (Var ym) Hcond);\n    specialize (IHalpha2 cond (Pred Rn) (Pred Qm) (Var ym) Hcond);\n    do 2 rewrite length_ind in *;\n    rewrite IHalpha1; [rewrite IHalpha2 | ];\n      [reflexivity |\n      rewrite arith_plus_comm in Hnum;\n      apply eq_nat_zero in Hnum; assumption |\n      apply eq_nat_zero in Hnum; assumption]);\n\n   try (    simpl in *;\n    specialize (IHalpha cond (Pred Rn) (Pred Qm) (Var ym) Hcond);\n    do 2 rewrite length_ind in IHalpha;\n    case_eq (beq_nat Pn Rn); intros Hbeq2; rewrite Hbeq2 in *;\n      [simpl in *; discriminate |];\n\n      case (beq_nat Qm Pn);\n        [|simpl; rewrite Hbeq2];\n        apply IHalpha; assumption).\n\n    simpl in *; \n    case_eq (beq_nat Qm Pn); intros Hbeq.\n      apply rep_FOv_is_unary_predless with (x := (Var ym)) (y := (Var xn)) in Hcond.\n      apply un_predless_preds_in in Hcond.\n      rewrite Hcond.\n      reflexivity.\n\n      simpl.\n      case_eq (beq_nat Pn Rn); intros Hbeq2; rewrite Hbeq2 in *.\n        simpl in *; discriminate.\n\n        reflexivity.\nQed.\n\nLemma num_occ_rep_pred__l_0 : forall (alpha : SecOrder) l l1 l2 P Q x cond,\nis_unary_predless_l l2 = true ->\nis_unary_predless cond = true ->\nnum_occ (replace_pred_l alpha l l1 l2) P = 0 ->\nnum_occ (replace_pred (replace_pred_l alpha l l1 l2) Q x cond) P = 0.\nProof.\n  intros alpha l l1 l2 P Q x cond Hun1 Hun2 Hnum.\n  apply num_occ_rep_pred_0; assumption.\nQed.\n\n\nLemma num_occ_rep_pred2 : forall (alpha cond : SecOrder) \n                                 (P Q : predicate) (x : FOvariable),\nis_unary_predless cond = true ->\nmatch P, Q with\n| Pred Pn, Pred Qm =>\nbeq_nat Pn Qm = false\nend ->\nnum_occ (replace_pred alpha P x cond) Q =\nnum_occ alpha Q.\nProof.\n  intros alpha cond P Q x Hcond Hbeq.\n  destruct P as [Pn]; destruct Q as [Qm].\n  unfold num_occ.\n  do 2 rewrite length_ind.\n  induction alpha;\n    try destruct p as [Rn]; try destruct f;\n    try destruct f0;\n    try reflexivity;\n    try (    simpl; assumption);\n    try (simpl; do 2 rewrite indicies_l_rev_app;\n    do 2 rewrite app_length;\n    do 2 rewrite list_map_length;\n    rewrite IHalpha1;\n    rewrite IHalpha2;\n    reflexivity);\n\n    simpl;\n    case_eq (beq_nat Rn Qm); intros Hbeq2;\n      case_eq (beq_nat Pn Rn); intros Hbeq3.\n        rewrite <- (beq_nat_true _ _ Hbeq2) in *;\n        rewrite <- (beq_nat_true _ _ Hbeq3) in Hbeq;\n        rewrite <- beq_nat_refl in Hbeq;\n        discriminate.\n\n        simpl; rewrite Hbeq2; reflexivity.\n\n        simpl.\n        apply rep_FOv_is_unary_predless with (x := x)\n              (y := (Var n)) in Hcond.\n        apply un_predless_preds_in in Hcond.\n        rewrite Hcond.\n        reflexivity.\n\n        simpl.\n        rewrite Hbeq2.\n        reflexivity.\n(* allSO *)\n        rewrite <- (beq_nat_true _ _ Hbeq2) in *;\n        rewrite <- (beq_nat_true _ _ Hbeq3) in Hbeq;\n        rewrite <- beq_nat_refl in Hbeq;\n        discriminate.\n\n        simpl; rewrite Hbeq2; simpl;  rewrite IHalpha ; reflexivity.\n\n        assumption.\n\n        simpl; rewrite Hbeq2; assumption.\n(* exSO *)\n        rewrite <- (beq_nat_true _ _ Hbeq2) in *;\n        rewrite <- (beq_nat_true _ _ Hbeq3) in Hbeq;\n        rewrite <- beq_nat_refl in Hbeq;\n        discriminate.\n\n        simpl; rewrite Hbeq2; simpl;  rewrite IHalpha ; reflexivity.\n\n        assumption.\n\n        simpl; rewrite Hbeq2; assumption.\nQed.\n\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/Num_Occ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6508568721423545}}
{"text": "(*|\n######################################\nProving Termination of Function in Coq\n######################################\n\n:Link: https://stackoverflow.com/q/46928911\n|*)\n\n(*|\nQuestion\n********\n\nI am having trouble proving termination of the following function:\n\n.. coq:: none\n|*)\n\nRequire Import Arith Ascii.\n\nInductive regex : Set :=\n| Empty   : regex\n| Epsilon : regex\n| Symbol  : ascii -> regex\n| Union   : regex -> regex -> regex\n| Concat  : regex -> regex -> regex\n| Star    : regex -> regex.\n\nLemma eq_regex_dec : forall u v : regex, {u = v} + {u <> v}.\nProof. decide equality. apply ascii_dec. Defined.\n\nFixpoint le_regex u v : bool :=\n  match u, v with\n  | Empty       , _            => true\n  | _           , Empty        => false\n  | Epsilon     , _            => true\n  | _           , Epsilon      => false\n  | Symbol a    , Symbol b     => nat_of_ascii a <=? nat_of_ascii b\n  | Symbol _    , _            => true\n  | _           , Symbol _     => false\n  | Star u      , Star v       => le_regex u v\n  | Star u      , _            => true\n  | _           , Star v       => false\n  | Union u1 u2 , Union v1 v2  => if eq_regex_dec u1 v1\n                                  then le_regex u2 v2\n                                  else le_regex u1 v1\n  | Union _ _   , _            => true\n  | _           , Union _ _    => false\n  | Concat u1 u2, Concat v1 v2 => if eq_regex_dec u1 v1\n                                  then le_regex u2 v2\n                                  else le_regex u1 v1\n  end.\n\n(*||*)\n\nFail Fixpoint norm_union u v : regex :=\n  match u, v with\n  | Empty    , v         => v\n  | u        , Empty     => u\n  | Union u v, w         => norm_union u (norm_union v w)\n  | u        , Union v w => if eq_regex_dec u v\n                            then Union v w\n                            else if le_regex u v\n                                 then Union u (Union v w)\n                                 else Union v (norm_union u w)\n  | u        , v         => if eq_regex_dec u v\n                            then u\n                            else if le_regex u v\n                                 then Union u v\n                                 else Union v u\n  end. (* .fails *)\n\n(*|\nwhere ``regex`` is the type of regular expressions and ``le_regex``\nimplements a total ordering on regular expressions. The source is page\nfive of `this <http://www21.in.tum.de/~krauss/papers/rexp.pdf>`__\ndocument. The function occurs as part of a normalization function for\nregular expressions (formalized in Isabelle/HOL). The ``le_regex``\nfunction is adapted from the same paper. I am using ``ascii`` to avoid\nparameterizing ``regex`` by a decidable total ordering (and want to\nextract the program).\n|*)\n\nReset Initial. (* .none *)\nRequire Import Arith Ascii. (* .none *)\nInductive regex : Set :=\n| Empty   : regex\n| Epsilon : regex\n| Symbol  : ascii -> regex\n| Union   : regex -> regex -> regex\n| Concat  : regex -> regex -> regex\n| Star    : regex -> regex.\n\nLemma eq_regex_dec : forall u v : regex, {u = v} + {u <> v}.\nProof. decide equality. apply ascii_dec. Defined.\n\nFixpoint le_regex u v : bool :=\n  match u, v with\n  | Empty       , _            => true\n  | _           , Empty        => false\n  | Epsilon     , _            => true\n  | _           , Epsilon      => false\n  | Symbol a    , Symbol b     => nat_of_ascii a <=? nat_of_ascii b\n  | Symbol _    , _            => true\n  | _           , Symbol _     => false\n  | Star u      , Star v       => le_regex u v\n  | Star u      , _            => true\n  | _           , Star v       => false\n  | Union u1 u2 , Union v1 v2  => if eq_regex_dec u1 v1\n                                  then le_regex u2 v2\n                                  else le_regex u1 v1\n  | Union _ _   , _            => true\n  | _           , Union _ _    => false\n  | Concat u1 u2, Concat v1 v2 => if eq_regex_dec u1 v1\n                                  then le_regex u2 v2\n                                  else le_regex u1 v1\n  end.\n\n(*|\nI think the correct approach is to define a decreasing measure and use\n``Program Fixpoint`` to prove termination. However, I'm having trouble\ncoming up with the correct measure (attempts based on the number of\noperators have been unsuccessful). I have tried factoring the work\ninto separate functions, but ran into similar problems. Any help would\nbe appreciated, or hints pointing in the right direction.\n|*)\n\n(*|\nAnswer (Yves)\n*************\n\nYour code is more complex than what is usually handled with a measure\nfunction, because you have a nested recursive call in the following\nline:\n\n.. code-block:: coq\n\n    Union u v, w         => norm_union u (norm_union v w)  (* line 5 *)\n\nI suggest that you should not return a value in type ``regex``, but in\ntype ``{r : regex | size r < combined_size u v}`` for suitable notions\nof ``size`` and ``combined_size``.\n\nAfter several hours of study on your problem, it also turns out that\nyour recursion relies on lexical ordering of the arguments.\n``norm_union v w`` may well return ``Union v w``, so you need that the\nargument pair ``(u, Union v w)`` is smaller than ``(Union u v, w)``.\nSo if you really want to use a measure, you need the weight of the\nleft-hand side to be larger than the weight of the right-hand side,\nand you need the measure of a component of a ``Union`` to be less than\nthe measure of the whole.\n\nBecause of the lexical ordering nature, I chose to not use a measure\nbut a well-founded order. Also, I don't know ``Program Fixpoint`` well\nenough, so I developed a solution to your problem using another tool.\nThe solution I came up with can be seen `here on github\n<https://github.com/ybertot/norm_union_example>`__. At least this\nshows all the decrease conditions that need to be proved.\n|*)\n\n(*|\nAnswer (Yves)\n*************\n\nAfter an extra day of work, I now have a more complete answer to this\nquestion. It is still visible at `this link\n<https://github.com/ybertot/norm_union_example>`__. This solution\ndeserves a few comments.\n\nFirst, I am using a function constructor called ``Fix`` (the long name\nis ``Coq.Init.Wf.Fix``). This is a higher order function that can be\nused to define functions by well-founded recursion. I need a well\nfounded order for this, this order is called ``order``. Well founded\norders were studied intensively in the early 2000s and they are still\nat the foundation of the ``Program Fixpoint`` command.\n\nSecond, the code you wrote performs case analyses on two values of\ntype ``regex`` simultaneously, so this leads to 36 cases (a bit less,\nbecause there is no case analysis on the second argument when the\nfirst one is ``Empty``). You don't see the 36 cases in your code,\nbecause several constructors are covered by the same rule where the\npattern is just a variable. To avoid this multiplication of cases, I\ndevised a specific inductive type for the case analyses. I called this\nspecific type ``arT``. Then I define a function ``ar`` that maps any\nelement of type ``regex`` to the corresponding element of ``arT``. The\ntype ``arT`` has three constructors instead of six, so pattern\nmatching expressions will contain much less code and proofs will be\nless verbose.\n\nThen I proceeded to define ``norm_union`` using ``Fix``. As usual in\nCoq (and in most theorem provers, including Isabelle), the language of\nrecursive definitions ensures that recursive functions always\nterminate. In this case, this is done by imposing that recursive calls\nonly happen on arguments that are *smaller* than the function's input.\nIn this case, this is done by describing the body of the recursive\nfunction by a function that takes as first argument the initial input\nand as second argument the function that will be used to represent the\nrecursive calls. The name of this function is ``norm_union_F`` and its\ntype is as follows:\n\n.. code-block:: coq\n\n    forall p : regex * regex,\n      forall g : (forall p', order p' p ->\n                             {r : regex | size_regex r <= size_2regex p'}),\n        {r : regex | size_regex r <= size_2regex p}\n\nIn this type description, the name of the function used to represent\nrecursive calls is ``g`` and we see that the type of ``g`` imposes\nthat it can only be used on pairs of ``regex`` terms that are smaller\nthan the initial argument ``p`` for the order named ``order``. In this\ntype description, we also see I chose to express that the returned\ntype of the recursive calls is not ``regex`` but ``{r : regex |\nsize_regex r <= size_2regex p'}``. This is because we have to handle\n*nested* recursion, where outputs of recursive calls will be used as\ninputs of other recursive calls. **This is the main trick of this\nanswer.**\n\nThen we have the body of the ``norm_union_F`` function:\n\n.. coq:: none\n|*)\n\nRequire Import Psatz Relation_Operators.\n\nFixpoint size_regex u :=\n  match u with\n  | Union u v => size_regex u + size_regex v + 1\n  | _ => 0\n  end.\n\nDefinition size_2regex (p : regex * regex) :=\n  let (u, v) := p in\n  size_regex u + size_regex v + 1.\n\nInductive arT (u : regex) : Type :=\n| arE : u = Empty -> arT u\n| arU : forall v w, u = Union v w -> arT u\n| arO : u <> Empty -> (forall v w, u <> Union v w) -> arT u.\n\nDefinition ar u : arT u.\nProof.\n  destruct u as [| |s|u v| |];\n    [apply arE; auto | apply arO| apply arO | apply (arU _ u v); auto |\n      apply arO | apply arO ]; discriminate.\nDefined.\n\nLemma th1 p : size_regex (snd p) <= size_2regex p.\nProof.\n  destruct p. unfold size_2regex. simpl. lia.\nQed.\n\nLemma th2' p u v (h : fst p = Union u v) :\n  size_regex (Union u v) <= size_2regex p.\nProof.\n  destruct p. rewrite <- h. unfold size_2regex. simpl. lia.\nQed.\n\nDefinition order : regex * regex -> regex * regex -> Prop :=\n  fun p1 p2 =>\n    lexprod nat (fun _ =>  nat)\n            lt (fun _ => lt)\n            (existT _ (size_2regex p1) (size_regex (fst p1)))\n            (existT _ (size_2regex p2) (size_regex (fst p2))).\n\nLemma th3' p u v (h : fst p = Union u v) :\n  order (v, snd p) p.\nProof.\n  destruct p. unfold order. apply left_lex. simpl.\n  simpl in h. rewrite h. simpl. lia.\nQed.\n\nLemma th4' p u v (eq1 : fst p = Union u v) (h : order (v, snd p) p)\n      r (rs : size_regex r <= size_2regex (v, snd p)) :\n  order (u, r) p.\nProof.\n  destruct p as [p1 p2]. simpl in eq1. rewrite eq1.\n  simpl in rs |- *.\n  apply le_lt_or_eq in rs. destruct rs as [rlt | req].\n  - now apply left_lex; simpl; lia.\n  - unfold order. simpl.\n    replace (size_regex u + size_regex r + 1) with\n      (size_regex u + size_regex v + 1 + size_regex p2 + 1) by\n      ring [req].\n    apply right_lex. lia.\nQed.\n\nLemma th5' p u v (eq1 : (fst p) = Union u v)\n      r1 (r1s : size_regex r1 <= size_2regex (v, snd p))\n      r2 (r2s : size_regex r2 <= size_2regex (u, r1)) :\n  size_regex r2 <= size_2regex p.\nProof.\n  destruct p as [p1 p2]. simpl in eq1, r1s, r2s |- *.\n  rewrite eq1. simpl. lia.\nQed.\n\nLemma th7' p v w (eq2 : snd p = Union v w) :\n  size_regex (Union v w) <= size_2regex p.\nProof. destruct p. rewrite <- eq2. simpl. lia. Qed.\n\nLemma th8' p v w (eq1 : snd p = Union v w) :\n  size_regex (Union (fst p) (Union v w)) <= size_2regex p.\nProof.\n  destruct p. rewrite <- eq1. simpl. lia.\nQed.\n\nLemma th9' p v w (eq2 : snd p = Union v w) :\n  order (fst p, w) p.\nProof.\n  destruct p as [p1 p2]. simpl in eq2 |- *.\n  rewrite eq2. apply left_lex. simpl. lia.\nQed.\n\nLemma th10' p v w (eq2 : snd p = Union v w)\n      r (rs : size_regex r <= size_2regex (fst p, w)) :\n  size_regex (Union v r) <= size_2regex p.\nProof.\n  destruct p as [p1 p2]. simpl in eq2, rs |- *.\n  rewrite eq2. simpl. lia.\nQed.\n\nLemma th11' p : size_regex (fst p) <= size_2regex p.\nProof.\n  destruct p as [p1 p2]. simpl. lia.\nQed.\n\nLemma th12' p : size_regex (Union (fst p) (snd p)) <= size_2regex p.\nProof.\n  destruct p. simpl. lia.\nQed.\n\nLemma th13' p : size_regex (Union (snd p) (fst p)) <= size_2regex p.\nProof.\n  destruct p. simpl. lia.\nQed.\n\n(*||*)\n\nDefinition norm_union_F : forall p : regex * regex,\n  forall g : (forall p', order p' p ->\n                         {r : regex | size_regex r <= size_2regex p'}),\n    {r : regex | size_regex r <= size_2regex p} :=\n  fun p norm_union =>\n    match ar (fst p) with\n    | arE _ eq1 => exist _ (snd p) (th1 p)\n    | arU _ u v eq1 =>\n        match ar (snd p) with\n        | arE _ eq2 => exist _ (Union u v) (th2' _ _ _ eq1)\n        | _ => exist _ (proj1_sig\n                          (norm_union (u,\n                                        proj1_sig (norm_union (v, snd p)\n                                                              (th3' _ _ _ eq1)))\n                                      (th4' _ _ _ eq1 (th3' _ _ _ eq1)\n                                            (proj1_sig (norm_union (v, snd p)\n                                                                   (th3' _ _ _ eq1)))\n                                            _)))\n                     (th5' _ _ _ eq1\n                           (proj1_sig (norm_union (v, snd p)\n                                                  (th3' _ _ _ eq1)))\n                           (proj2_sig (norm_union (v, snd p)\n                                                  (th3' _ _ _ eq1)))\n                           (proj1_sig\n                              (norm_union\n                                 (u, proj1_sig (norm_union (v, snd p)\n                                                           (th3' _ _ _ eq1)))\n                                 (th4' _ _ _ eq1 (th3' _ _ _ eq1)\n                                       (proj1_sig (norm_union (v, snd p)\n                                                              (th3' _ _ _ eq1)))\n                                       (proj2_sig (norm_union (v, snd p)\n                                                              (th3' _ _ _ eq1))))))\n                           (proj2_sig\n                              (norm_union\n                                 (u, proj1_sig (norm_union (v, snd p)\n                                                           (th3' _ _ _ eq1)))\n                                 (th4' _ _ _ eq1 (th3' _ _ _ eq1)\n                                       (proj1_sig (norm_union (v, snd p)\n                                                              (th3' _ _ _ eq1)))\n                                       (proj2_sig (norm_union (v, snd p)\n                                                              (th3' _ _ _ eq1)))))))\n        end\n    | arO _ d1 d2 =>\n        match ar (snd p) with\n        | arE _ eq2 => exist _ (fst p) (th11' _)\n        | arU _ v w eq2 =>\n            if eq_regex_dec (fst p) v then\n              exist _ (Union v w) (th7' _ _ _ eq2)\n            else if le_regex (fst p) v then\n                   exist _ (Union (fst p) (Union v w)) (th8' _ _ _ eq2)\n                 else exist _ (Union v (proj1_sig (norm_union (fst p, w)\n                                                              (th9' _ _ _ eq2))))\n                            (th10' _ _ _ eq2\n                                   (proj1_sig (norm_union (fst p, w)\n                                                          (th9' _ _ _ eq2)))\n                                   (proj2_sig (norm_union (fst p, w)\n                                                          (th9' _ _ _ eq2))))\n        | arO _ d1 d2 =>\n            if eq_regex_dec (fst p) (snd p) then\n              exist _ (fst p) (th11' _)\n            else if le_regex (fst p) (snd p) then\n                   exist _ (Union (fst p) (snd p)) (th12' _)\n                 else exist _ (Union (snd p) (fst p)) (th13' _)\n        end\n    end.\n\n(*|\nIn this code, all output values are within an ``exist _`` context: not\nonly do we produce the output value, but we also show that the size of\nthis value is smaller than the combined size of the input pair of\nvalues. More over, all recursive calls are within a ``proj1_sig``\ncontext, so that we forget the size information at the moment of\nconstructing the output value. But also, all recursive calls, here\nrepresented by calls to the function named ``norm_union`` also have a\nproof that the input to the recursive call is indeed smaller than the\ninitial input. All the proofs are in `the complete development\n<https://github.com/ybertot/norm_union_example>`__.\n\nIt would probably be possible to use tactics like ``refine`` to define\n``norm_union_F``, you are invited to explore.\n\nThen we define the truly recursive function ``norm_union_1``:\n\n.. coq:: none\n|*)\n\nRequire Import Wellfounded.\n\nLemma well_founded_order : well_founded order.\nProof.\n  unfold order.\n  apply (wf_inverse_image\n           (regex * regex) {x : nat & nat}\n           (lexprod nat (fun _ => nat) lt (fun _ => lt))\n           (fun p => (existT _ (size_2regex p) (size_regex (fst p))))).\n  apply wf_lexprod; intros; apply Nat.lt_wf_0.\nQed.\n\n(*||*)\n\nDefinition norm_union_1 : forall p : regex * regex,\n    {x | size_regex x <= size_2regex p} :=\n  Fix well_founded_order (fun p => {x | size_regex x <= size_2regex p})\n      norm_union_F.\n\n(*|\nNote that the output of ``norm_union_1`` has type ``{x | size_regex x\n<= size_2regex p}``. This is not the type you asked for. So we define\na new function, which is really the one you want, simply by forgetting\nthe logical information that the output has a size smaller than the\ninput.\n|*)\n\nDefinition norm_union u v : regex := proj1_sig (norm_union_1 (u, v)).\n\n(*|\nYou might still doubt that this is the right function, the one you\nasked for. To convince ourselves, we are going to prove a lemma that\nexpresses exactly what you would have said in a definition.\n\nWe first prove the corresponding lemma for ``norm_union_1``. This\nrelies on a theorem associated to the ``Fix`` function, name\n``Fix_eq``. The proof that needs to be done is fairly routine (it\nalways is, it could be done automatically, but I never came around to\ndeveloping the automatic tool for that).\n\nThen we finish with most interesting lemma, the one for\n``norm_union``. Here is the statement:\n|*)\n\nLemma norm_union_eqn u v :\n  norm_union u v =\n    match u, v with\n    | Empty    , v         => v\n    | u        , Empty     => u\n    | Union u v, w         => norm_union u (norm_union v w)\n    | u        , Union v w => if eq_regex_dec u v\n                              then Union v w\n                              else if le_regex u v\n                                   then Union u (Union v w)\n                                   else Union v (norm_union u w)\n    | u        , v         => if eq_regex_dec u v\n                              then u\n                              else if le_regex u v\n                                   then Union u v\n                                   else Union v u\n    end.\n\n(*|\nPlease note that the right-hand-side of this equation is exactly the\ncode that you gave in your initial question (I simply copy-pasted it).\nThe proof of this final theorem is also fairly systematic.\n\nNow, I made the effort of following exactly your request, but after\nthe fact I discovered that there is a simple implementation of the\nsame functionality, using three recursive functions. The first one\nflattens binary trees of ``Union`` to make then look like list, and\nthe other two sort these union with respect to the order ``le_regex``\nwhile removing duplicates as soon as they are uncovered. Such an\nimplementation would workaround the need for nested recursion.\n\nIf you still want to stick to nested recursion and need to refer to\nthe technique described here, it was first published in a paper by\nBalaa and Bertot at TPHOLs2000. That paper is difficult to read\nbecause it was written at a time when Coq was using a different\nsyntax.\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/proving-termination-of-function-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673223709251, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.6508563695865286}}
{"text": "(*|\n####################################################\nJust a universally quantified hypotesis in Coq proof\n####################################################\n\n:Link: https://stackoverflow.com/q/19053778\n|*)\n\n(*|\nQuestion\n********\n\nAnother hard goal (for me, of course) is the following:\n|*)\n\nGoal ~(forall P Q : nat -> Prop,\n          (exists x, P x) /\\ (exists x, Q x) -> (exists x, P x /\\ Q x)).\nProof.\nAbort. (* .none *)\n\n(*|\nI absolutely have no idea of what could I do. If I introduce\nsomething, I get a universal quantifier in the hypotesis, and then I\ncan't do anything with it.\n\nI suppose that it exists a standard way for managing such kind of\nsituations, but I was not able to find it out.\n|*)\n\n(*|\nAnswer (Ptival)\n***************\n\nTo progress in that proof, you will have to exhibit an instance of\n``P`` and an instance of ``Q`` such that your hypothesis produces a\ncontradiction.\n\nA simple way to go is to use:\n\n.. code-block:: coq\n\n    P : fun x => x = 0\n    Q : fun x => x = 1\n\nIn order to work with the hypothesis introduced, you might want to use\nthe tactic ``specialize``:\n|*)\n\nGoal ~(forall P Q : nat -> Prop,\n          (exists x, P x) /\\ (exists x, Q x) -> (exists x, P x /\\ Q x)).\nProof.\n  intro H.\n  specialize (H (fun x => x = 0) (fun x => x = 1)).\n\n(*|\nIt allows you to apply one of your hypothesis on some input (when the\nhypothesis is a function). From now on, you should be able to derive a\ncontradiction easily.\n\nAlternatively to ``specialize``, you can also do:\n|*)\n\n  Undo. (* .none *)\n  pose proof (H (fun x => x = 0) (fun x => x = 1)) as Happlied.\nAbort. (* .none *)\n\n(*|\nWhich will conserve ``H`` and give you another term ``Happlied`` (you\nchoose the name) for the application.\n|*)\n\n(*|\nAnswer (Matteo Zanchi)\n**********************\n\nThe answer of Ptival did the trick. Here is the code of the complete\nproof:\n|*)\n\nGoal ~(forall P Q : nat -> Prop,\n          (exists x, P x) /\\ (exists x, Q x) -> (exists x, P x /\\ Q x)).\nProof.\n  unfold not. intros.\n  destruct (H (fun x => x = 0) (fun x => x = 1)).\n  - split.\n    + exists 0. reflexivity.\n    + exists 1. reflexivity.\n  - destruct H0. rewrite H0 in H1. inversion H1.\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/just-a-universally-quantified-hypotesis-in-coq-proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6508563567640815}}
{"text": "(** Formal Reasoning About Programs <http://adam.chlipala.net/frap/>\n  * Chapter 8: Abstract Interpretation and Dataflow Analysis\n  * Author: Adam Chlipala\n  * License: https://creativecommons.org/licenses/by-nc-nd/4.0/ *)\n\nRequire Import Frap Imp.\nExport Imp.\n\nSet Implicit Arguments.\n\n\n(* Reduced version of code from AbstractInterpretation.v *)\n\nRecord absint := {\n  Domain :> Set;\n  Top : Domain;\n  Constant : nat -> Domain;\n  Add : Domain -> Domain -> Domain;\n  Subtract : Domain -> Domain -> Domain;\n  Multiply : Domain -> Domain -> Domain;\n  Join : Domain -> Domain -> Domain;\n  Represents : nat -> Domain -> Prop\n}.\n\nRecord absint_sound (a : absint) : Prop := {\n  TopSound : forall n, a.(Represents) n a.(Top);\n\n  ConstSound : forall n, a.(Represents) n (a.(Constant) n);\n\n  AddSound : forall n na m ma, a.(Represents) n na\n                               -> a.(Represents) m ma\n                               -> a.(Represents) (n + m) (a.(Add) na ma);\n  SubtractSound: forall n na m ma, a.(Represents) n na\n                                   -> a.(Represents) m ma\n                                   -> a.(Represents) (n - m) (a.(Subtract) na ma);\n  MultiplySound : forall n na m ma, a.(Represents) n na\n                                    -> a.(Represents) m ma\n                                    -> a.(Represents) (n * m) (a.(Multiply) na ma);\n\n  AddMonotone : forall na na' ma ma', (forall n, a.(Represents) n na -> a.(Represents) n na')\n                                      -> (forall n, a.(Represents) n ma -> a.(Represents) n ma')\n                                      -> (forall n, a.(Represents) n (a.(Add) na ma)\n                                                    -> a.(Represents) n (a.(Add) na' ma'));\n  SubtractMonotone : forall na na' ma ma', (forall n, a.(Represents) n na -> a.(Represents) n na')\n                                           -> (forall n, a.(Represents) n ma -> a.(Represents) n ma')\n                                           -> (forall n, a.(Represents) n (a.(Subtract) na ma)\n                                                         -> a.(Represents) n (a.(Subtract) na' ma'));\n  MultiplyMonotone : forall na na' ma ma', (forall n, a.(Represents) n na -> a.(Represents) n na')\n                                           -> (forall n, a.(Represents) n ma -> a.(Represents) n ma')\n                                           -> (forall n, a.(Represents) n (a.(Multiply) na ma)\n                                                         -> a.(Represents) n (a.(Multiply) na' ma'));\n\n  JoinSoundLeft : forall x y n, a.(Represents) n x\n                                -> a.(Represents) n (a.(Join) x y);\n  JoinSoundRight : forall x y n, a.(Represents) n y\n                                 -> a.(Represents) n (a.(Join) x y)\n}.\n\nGlobal Hint Resolve TopSound ConstSound AddSound SubtractSound MultiplySound\n     AddMonotone SubtractMonotone MultiplyMonotone\n     JoinSoundLeft JoinSoundRight : core.\n\n\n\nDefinition astate (a : absint) := fmap var a.\n\nFixpoint absint_interp (e : arith) a (s : astate a) : a :=\n  match e with\n  | Const n => a.(Constant) n\n  | Var x => match s $? x with\n             | None => a.(Top)\n             | Some xa => xa\n             end\n  | Plus e1 e2 => a.(Add) (absint_interp e1 s) (absint_interp e2 s)\n  | Minus e1 e2 => a.(Subtract) (absint_interp e1 s) (absint_interp e2 s)\n  | Times e1 e2 => a.(Multiply) (absint_interp e1 s) (absint_interp e2 s)\n  end.\n\nDefinition merge_astate a : astate a -> astate a -> astate a :=\n  merge (fun x y =>\n           match x with\n           | None => None\n           | Some x' =>\n             match y with\n             | None => None\n             | Some y' => Some (a.(Join) x' y')\n             end\n           end).\n\nDefinition subsumed a (s1 s2 : astate a) :=\n  forall x, match s1 $? x with\n            | None => s2 $? x = None\n            | Some xa1 =>\n              forall xa2, s2 $? x = Some xa2\n                          -> forall n, a.(Represents) n xa1\n                                       -> a.(Represents) n xa2\n            end.\n\nTheorem subsumed_refl : forall a (s : astate a),\n  subsumed s s.\nProof.\n  unfold subsumed; simplify.\n  cases (s $? x); equality.\nQed.\n\nGlobal Hint Resolve subsumed_refl : core.\n\nLemma subsumed_use : forall a (s s' : astate a) x n t0 t,\n  s $? x = Some t0\n  -> subsumed s s'\n  -> s' $? x = Some t\n  -> Represents a n t0\n  -> Represents a n t.\nProof.\n  unfold subsumed; simplify.\n  specialize (H0 x).\n  rewrite H in H0.\n  eauto.\nQed.\n\nLemma subsumed_use_empty : forall a (s s' : astate a) x n t0 t,\n  s $? x = None\n  -> subsumed s s'\n  -> s' $? x = Some t\n  -> Represents a n t0\n  -> Represents a n t.\nProof.\n  unfold subsumed; simplify.\n  specialize (H0 x).\n  rewrite H in H0.\n  equality.\nQed.\n\nGlobal Hint Resolve subsumed_use subsumed_use_empty : core.\n\nLemma subsumed_trans : forall a (s1 s2 s3 : astate a),\n  subsumed s1 s2\n  -> subsumed s2 s3\n  -> subsumed s1 s3.\nProof.\n  unfold subsumed; simplify.\n  specialize (H x); specialize (H0 x).\n  cases (s1 $? x); simplify.\n  cases (s2 $? x); eauto.\n  cases (s2 $? x); eauto.\n  equality.\nQed.\n\nLemma subsumed_merge_left : forall a, absint_sound a\n  -> forall s1 s2 : astate a,\n    subsumed s1 (merge_astate s1 s2).\nProof.\n  unfold subsumed, merge_astate; simplify.\n  cases (s1 $? x); trivial.\n  cases (s2 $? x); simplify; try equality.\n  invert H0; eauto.\nQed.\n\nGlobal Hint Resolve subsumed_merge_left : core.\n\nLemma subsumed_add : forall a, absint_sound a\n  -> forall (s1 s2 : astate a) x v1 v2,\n  subsumed s1 s2\n  -> (forall n, a.(Represents) n v1 -> a.(Represents) n v2)\n  -> subsumed (s1 $+ (x, v1)) (s2 $+ (x, v2)).\nProof.\n  unfold subsumed; simplify.\n  cases (x ==v x0); subst; simplify; eauto.\n  invert H2; eauto.\n  specialize (H0 x0); eauto.\nQed.\n\nGlobal Hint Resolve subsumed_add : core.\n\n\n(** * Flow-sensitive analysis *)\n\nDefinition compatible a (s : astate a) (v : valuation) : Prop :=\n  forall x xa, s $? x = Some xa\n               -> exists n, v $? x = Some n\n                            /\\ a.(Represents) n xa.\n\nLemma compatible_add : forall a (s : astate a) v x na n,\n  compatible s v\n  -> a.(Represents) n na\n  -> compatible (s $+ (x, na)) (v $+ (x, n)).\nProof.\n  unfold compatible; simplify.\n  cases (x ==v x0); simplify; eauto.\n  invert H1; eauto.\nQed.\n\nGlobal Hint Resolve compatible_add : core.\n\n(* A similar result follows about soundness of expression interpretation. *)\nTheorem absint_interp_ok : forall a, absint_sound a\n  -> forall (s : astate a) v e,\n    compatible s v\n    -> a.(Represents) (interp e v) (absint_interp e s).\nProof.\n  induct e; simplify; eauto.\n  cases (s $? x); auto.\n  unfold compatible in H0.\n  apply H0 in Heq.\n  invert Heq.\n  propositional.\n  rewrite H2.\n  assumption.\nQed.\n\nGlobal Hint Resolve absint_interp_ok : core.\n\nDefinition astates (a : absint) := fmap cmd (astate a).\n\nFixpoint absint_step a (s : astate a) (c : cmd) (wrap : cmd -> cmd) : option (astates a) :=\n  match c with\n  | Skip => None\n  | Assign x e => Some ($0 $+ (wrap Skip, s $+ (x, absint_interp e s)))\n  | Sequence c1 c2 =>\n    match absint_step s c1 (fun c => wrap (Sequence c c2)) with\n    | None => Some ($0 $+ (wrap c2, s))\n    | v => v\n    end\n  | If _ then_ else_ => Some ($0 $+ (wrap then_, s) $+ (wrap else_, s))\n  | While e body => Some ($0 $+ (wrap Skip, s) $+ (wrap (Sequence body (While e body)), s))\n  end.\n\nLemma command_equal : forall c1 c2 : cmd, sumbool (c1 = c2) (c1 <> c2).\nProof.\n  repeat decide equality.\nQed.\n\nTheorem absint_step_ok : forall a, absint_sound a\n  -> forall (s : astate a) v, compatible s v\n  -> forall c v' c', step (v, c) (v', c')\n                     -> forall wrap, exists ss s', absint_step s c wrap = Some ss\n                                                   /\\ ss $? wrap c' = Some s'\n                                                   /\\ compatible s' v'.\nProof.\n  induct 2; simplify.\n\n  do 2 eexists; propositional.\n  simplify; equality.\n  eauto.\n\n  eapply IHstep in H0; auto.\n  invert H0.\n  invert H2.\n  propositional.\n  rewrite H2.\n  eauto.\n\n  do 2 eexists; propositional.\n  simplify; equality.\n  assumption.\n\n  do 2 eexists; propositional.\n  cases (command_equal (wrap c') (wrap else_)).\n  simplify; equality.\n  simplify; equality.\n  assumption.\n\n  do 2 eexists; propositional.\n  simplify; equality.\n  assumption.\n\n  do 2 eexists; propositional.\n  simplify; equality.\n  assumption.\n\n  do 2 eexists; propositional.\n  cases (command_equal (wrap Skip) (wrap (body;; while e loop body done))).\n  simplify; equality.\n  simplify; equality.\n  assumption.\nQed.\n\nInductive abs_step a : astate a * cmd -> astate a * cmd -> Prop :=\n| AbsStep : forall s c ss s' c',\n  absint_step s c (fun x => x) = Some ss\n  -> ss $? c' = Some s'\n  -> abs_step (s, c) (s', c').\n\nGlobal Hint Constructors abs_step : core.\n\nDefinition absint_trsys a (c : cmd) := {|\n  Initial := {($0, c)};\n  Step := abs_step (a := a)\n|}.\n\nInductive Rabsint a : valuation * cmd -> astate a * cmd -> Prop :=\n| RAbsint : forall v s c,\n  compatible s v\n  -> Rabsint (v, c) (s, c).\n\nGlobal Hint Constructors abs_step Rabsint : core.\n\nTheorem absint_simulates : forall a v c,\n  absint_sound a\n  -> simulates (Rabsint (a := a)) (trsys_of v c) (absint_trsys a c).\nProof.\n  simplify.\n  constructor; simplify.\n\n  exists ($0, c); propositional.\n  subst.\n  constructor.\n  unfold compatible.\n  simplify.\n  equality.\n\n  invert H0.\n  cases st1'.\n  eapply absint_step_ok in H1; eauto.\n  invert H1.\n  invert H0.\n  propositional.\n  eauto.\nQed.\n\nDefinition merge_astates a : astates a -> astates a -> astates a :=\n  merge (fun x y =>\n           match x with\n           | None => y\n           | Some x' =>\n             match y with\n             | None => Some x'\n             | Some y' => Some (merge_astate x' y')\n             end\n           end).\n\nInductive oneStepClosure a : astates a -> astates a -> Prop :=\n| OscNil :\n  oneStepClosure $0 $0\n| OscCons : forall ss c s ss' ss'',\n  oneStepClosure ss ss'\n  -> match absint_step s c (fun x => x) with\n     | None => ss'\n     | Some ss'' => merge_astates ss'' ss'\n     end = ss''\n  -> oneStepClosure (ss $+ (c, s)) ss''.\n\nDefinition subsumeds a (ss1 ss2 : astates a) :=\n  forall c s1, ss1 $? c = Some s1\n               -> exists s2, ss2 $? c = Some s2\n                             /\\ subsumed s1 s2.\n\nTheorem subsumeds_refl : forall a (ss : astates a),\n  subsumeds ss ss.\nProof.\n  unfold subsumeds; simplify; eauto.\nQed.\n\nGlobal Hint Resolve subsumeds_refl : core.\n\nLemma subsumeds_add : forall a (ss1 ss2 : astates a) c s1 s2,\n  subsumeds ss1 ss2\n  -> subsumed s1 s2\n  -> subsumeds (ss1 $+ (c, s1)) (ss2 $+ (c, s2)).\nProof.\n  unfold subsumeds; simplify.\n  cases (command_equal c c0); subst; simplify; eauto.\n  invert H1; eauto.\nQed.\n\nGlobal Hint Resolve subsumeds_add : core.\n\nLemma subsumeds_empty : forall a (ss : astates a),\n  subsumeds $0 ss.\nProof.\n  unfold subsumeds; simplify.\n  equality.\nQed.\n\nLemma subsumeds_add_left : forall a (ss1 ss2 : astates a) c s,\n  ss2 $? c = Some s\n  -> subsumeds ss1 ss2\n  -> subsumeds (ss1 $+ (c, s)) ss2.\nProof.\n  unfold subsumeds; simplify.\n  cases (command_equal c c0); subst; simplify; eauto.\n  invert H1; eauto.\nQed.\n\nInductive interpret a : astates a -> astates a -> astates a -> Prop :=\n| InterpretDone : forall ss1 any ss2,\n  oneStepClosure ss1 ss2\n  -> subsumeds ss2 ss1\n  -> interpret ss1 any ss1\n| InterpretStep : forall ss worklist ss' ss'',\n  oneStepClosure worklist ss'\n  -> interpret (merge_astates ss ss') ss' ss''\n  -> interpret ss worklist ss''.\n\nLemma oneStepClosure_sound : forall a, absint_sound a\n  -> forall ss ss' : astates a, oneStepClosure ss ss'\n  -> forall c s s' c', ss $? c = Some s\n                       -> abs_step (s, c) (s', c')\n                          -> exists s'', ss' $? c' = Some s''\n                                         /\\ subsumed s' s''.\nProof.\n  induct 2; simplify.\n\n  equality.\n\n  cases (command_equal c c0); subst; simplify.\n\n  invert H2.\n  invert H3.\n  rewrite H5.\n  unfold merge_astates; simplify.\n  rewrite H7.\n  cases (ss' $? c').\n  eexists; propositional.\n  unfold subsumed; simplify.\n  unfold merge_astate; simplify.\n  cases (s' $? x); try equality.\n  cases (a0 $? x); simplify; try equality.\n  invert H1; eauto.\n  eauto.\n\n  apply IHoneStepClosure in H3; auto.\n  invert H3; propositional.\n  cases (absint_step s c (fun x => x)); eauto.\n  unfold merge_astates; simplify.\n  rewrite H3.\n  cases (a0 $? c'); eauto.\n  eexists; propositional.\n  unfold subsumed; simplify.\n  unfold merge_astate; simplify.\n  specialize (H4 x0).\n  cases (s' $? x0).\n  cases (a1 $? x0); try equality.\n  cases (x $? x0); try equality.\n  invert 1.\n  eauto.\n\n  rewrite H4.\n  cases (a1 $? x0); equality.\nQed.\n\nLemma absint_step_monotone_None : forall a (s : astate a) c wrap,\n    absint_step s c wrap = None\n    -> forall s' : astate a, absint_step s' c wrap = None.\nProof.\n  induct c; simplify; try equality.\n  cases (absint_step s c1 (fun c => wrap (c;; c2))); equality.\nQed.\n\nLemma absint_interp_monotone : forall a, absint_sound a\n  -> forall (s : astate a) e s' n,\n    a.(Represents) n (absint_interp e s)\n    -> subsumed s s'\n    -> a.(Represents) n (absint_interp e s').\nProof.\n  induct e; simplify; eauto.\n\n  cases (s' $? x); eauto.\n  cases (s $? x); eauto.\nQed.\n\nGlobal Hint Resolve absint_interp_monotone : core.\n\nLemma absint_step_monotone : forall a, absint_sound a\n    -> forall (s : astate a) c wrap ss,\n      absint_step s c wrap = Some ss\n      -> forall s', subsumed s s'\n                    -> exists ss', absint_step s' c wrap = Some ss'\n                                   /\\ subsumeds ss ss'.\nProof.\n  induct c; simplify.\n\n  equality.\n\n  invert H0.\n  eexists; propositional.\n  eauto.\n  apply subsumeds_add; eauto.\n\n  cases (absint_step s c1 (fun c => wrap (c;; c2))).\n\n  invert H0.\n  eapply IHc1 in Heq; eauto.\n  invert Heq; propositional.\n  rewrite H2; eauto.\n\n  invert H0.\n  eapply absint_step_monotone_None in Heq; eauto.\n  rewrite Heq; eauto.\n\n  invert H0; eauto.\n\n  invert H0; eauto.\nQed.\n\nLemma abs_step_monotone : forall a, absint_sound a\n  -> forall (s : astate a) c s' c',\n    abs_step (s, c) (s', c')\n    -> forall s1, subsumed s s1\n                  -> exists s1', abs_step (s1, c) (s1', c')\n                                 /\\ subsumed s' s1'.\nProof.\n  invert 2; simplify.\n  eapply absint_step_monotone in H4; eauto.\n  invert H4; propositional.\n  apply H3 in H6.\n  invert H6; propositional; eauto.\nQed.\n\nLemma interpret_sound' : forall c a, absint_sound a\n  -> forall ss worklist ss' : astates a, interpret ss worklist ss'\n    -> ss $? c = Some $0\n    -> invariantFor (absint_trsys a c) (fun p => exists s, ss' $? snd p = Some s\n                                                           /\\ subsumed (fst p) s).\nProof.\n  induct 2; simplify; subst.\n\n  apply invariant_induction; simplify; propositional; subst; simplify; eauto.\n\n  invert H3; propositional.\n  cases s.\n  cases s'.\n  simplify.\n  eapply abs_step_monotone in H4; eauto.\n  invert H4; propositional.\n  eapply oneStepClosure_sound in H4; eauto.\n  invert H4; propositional.\n  eapply H1 in H4.\n  invert H4; propositional.\n  eauto using subsumed_trans.\n\n  apply IHinterpret.\n  unfold merge_astates; simplify.\n  rewrite H2.\n  cases (ss' $? c); trivial.\n  unfold merge_astate; simplify; equality.\nQed.\n\nTheorem interpret_sound : forall c a (ss : astates a),\n  absint_sound a\n  -> interpret ($0 $+ (c, $0)) ($0 $+ (c, $0)) ss\n  -> invariantFor (absint_trsys a c) (fun p => exists s, ss $? snd p = Some s\n                                                         /\\ subsumed (fst p) s).\nProof.\n  simplify.\n  eapply interpret_sound'; eauto.\n  simplify; equality.\nQed.\n\nLtac interpret_simpl := unfold merge_astates, merge_astate;\n                       simplify; repeat simplify_map.\nLtac oneStepClosure := apply OscNil\n                       || (eapply OscCons; [ oneStepClosure\n                                           | interpret_simpl; reflexivity ]).\nLtac interpret1 := eapply InterpretStep; [ oneStepClosure | interpret_simpl ].\nLtac interpret_done := eapply InterpretDone; [ oneStepClosure\n  | repeat (apply subsumeds_add_left || apply subsumeds_empty); (simplify; equality) ].\n", "meta": {"author": "achlipala", "repo": "frap", "sha": "ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb", "save_path": "github-repos/coq/achlipala-frap", "path": "github-repos/coq/achlipala-frap/frap-ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb/AbstractInterpret.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6508270386687398}}
{"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(*                      Evgeny Makarov, INRIA, 2007                     *)\n(************************************************************************)\n\nRequire Import NZAxioms NZBase NZAdd.\n\nModule Type NZMulProp (Import NZ : NZAxiomsSig')(Import NZBase : NZBaseProp NZ).\nInclude NZAddProp NZ NZBase.\n\nTheorem mul_0_r : forall n, n * 0 == 0.\nProof.\nnzinduct n; intros; now nzsimpl.\nQed.\n\nTheorem mul_succ_r : forall n m, n * (S m) == n * m + n.\nProof.\nintros n m; nzinduct n. now nzsimpl.\nintro n. nzsimpl. rewrite succ_inj_wd, <- add_assoc, (add_comm m n), add_assoc.\nnow rewrite add_cancel_r.\nQed.\n\nHint Rewrite mul_0_r mul_succ_r : nz.\n\nTheorem mul_comm : forall n m, n * m == m * n.\nProof.\nintros n m; nzinduct n. now nzsimpl.\nintro. nzsimpl. now rewrite add_cancel_r.\nQed.\n\nTheorem mul_add_distr_r : forall n m p, (n + m) * p == n * p + m * p.\nProof.\nintros n m p; nzinduct n. now nzsimpl.\nintro n. nzsimpl. rewrite <- add_assoc, (add_comm p (m*p)), add_assoc.\nnow rewrite add_cancel_r.\nQed.\n\nTheorem mul_add_distr_l : forall n m p, n * (m + p) == n * m + n * p.\nProof.\nintros n m p.\nrewrite (mul_comm n (m + p)), (mul_comm n m), (mul_comm n p).\napply mul_add_distr_r.\nQed.\n\nTheorem mul_assoc : forall n m p, n * (m * p) == (n * m) * p.\nProof.\nintros n m p; nzinduct n. now nzsimpl.\nintro n. nzsimpl. rewrite mul_add_distr_r.\nnow rewrite add_cancel_r.\nQed.\n\nTheorem mul_1_l : forall n, 1 * n == n.\nProof.\nintro n. now nzsimpl'.\nQed.\n\nTheorem mul_1_r : forall n, n * 1 == n.\nProof.\nintro n. now nzsimpl'.\nQed.\n\nHint Rewrite mul_1_l mul_1_r : nz.\n\nTheorem mul_shuffle0 : forall n m p, n*m*p == n*p*m.\nProof.\nintros n m p. now rewrite <- 2 mul_assoc, (mul_comm m).\nQed.\n\nTheorem mul_shuffle1 : forall n m p q, (n * m) * (p * q) == (n * p) * (m * q).\nProof.\nintros n m p q. now rewrite 2 mul_assoc, (mul_shuffle0 n).\nQed.\n\nTheorem mul_shuffle2 : forall n m p q, (n * m) * (p * q) == (n * q) * (m * p).\nProof.\nintros n m p q. rewrite (mul_comm p). apply mul_shuffle1.\nQed.\n\nTheorem mul_shuffle3 : forall n m p, n * (m * p) == m * (n * p).\nProof.\nintros n m p. now rewrite mul_assoc, (mul_comm n), mul_assoc.\nQed.\n\nEnd NZMulProp.\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/NatInt/NZMul.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6508270333584583}}
{"text": "Require Import Program.Basics.\nRequire Import Category.\nRequire Import Std.prod.\n\nHint Resolve prod_proj.\n\nOpen Scope program_scope.\n\n(** Polymorphic lens: views the current part [A] from the whole [S] and updates \n    the part [A] with a new version of it [B], which is reflected in the whole \n    [T]. *)\nRecord pLens (S T A B : Type) := mkPLens\n{ view : S -> A\n; update : S -> B -> T\n}.\nArguments mkPLens [S T A B].\nArguments view [S T A B].\nArguments update [S T A B].\n\n(** Monomorphic lens *)\nDefinition lens S A : Type := pLens S S A A.\n\n(** Very well-behaved lens. *)\nRecord lensDec {S A} (ln : lens S A) := mkLensDec\n{ view_update : forall s, update ln s (view ln s) = s\n; update_view : forall s a, view ln (update ln s a) = a\n; update_update : forall s a1 a2, update ln (update ln s a1) a2 = update ln s a2\n}.\n\nInstance Category_lens : Category lens :=\n{ identity A := mkPLens id (fun _ => id) \n; compose A B C ln1 ln2 := mkPLens \n    (view ln2 ∘ view ln1)\n    (fun s => update ln1 s ∘ update ln2 (view ln1 s))\n}.\n\nInstance CategoryDec_lens : CategoryDec lens.\nProof.\n  split; simpl; intros; destruct cab; auto.\nQed.\n\nLemma lensDec_identity : forall A, lensDec (@identity lens _ A).\nProof. split; auto. Qed.\n\nLemma lensDec_compose :\n  forall {A B C} (ln1 : lens A B) (ln2 : lens B C), \n    lensDec ln1 -> lensDec ln2 -> lensDec (compose ln1 ln2).\nProof.\n  intros.\n  destruct H.\n  destruct H0.\n  split; simpl; unfold Basics.compose; intros.\n\n  - (* view_update *)\n    rewrite view_update1.\n    now rewrite view_update0.\n\n  - (* update_view *)\n    rewrite update_view0.\n    now rewrite update_view1.\n\n  - (* update_update *)\n    rewrite update_update0.\n    rewrite update_view0.\n    now rewrite update_update1.\nQed.\n\n(** Provides access to the first component of a product. *)\nDefinition first {A B} : lens (A * B) A :=\n  mkPLens fst (fun s a' => (a', snd s)).\n\nDefinition firstDec {A B} : lensDec (@first A B).\nProof.\n  split; simpl; auto.\nQed.\n\n(** Provides access to the second component of a product. *)\nDefinition second {A B} : lens (A * B) B :=\n  mkPLens snd (fun s b' => (fst s, b')).\n\nDefinition secondDec {A B} : lensDec (@second A B).\nProof.\n  split; simpl; auto.\nQed.\n\n(** Profunctor lens *)\n\nRequire Import Profunctor.\n\nDefinition LensP (S T A B : Type) : Type := forall p `{Cartesian p}, p A B -> p S T.\n\nDefinition LensP' (S A : Type) : Type := LensP S S A A.\n\n(** Monadic lens *)\n\nRequire Import Monad.\n\nRecord mLens (S A : Type) (m : Type -> Type) `{Monad m} := mkMLens\n{ mview   : S -> A\n; mupdate : S -> A -> m S \n}.\n\nArguments mkMLens [S A m _ _ _].\nArguments mview [S A m _ _ _].\nArguments mupdate [S A m _ _ _].\n\n(** Well-behaved monadic lens *)\n\nRecord mLensLaws {S A m} `{Monad m} (mln : mLens S A m) := mkMLensLaws\n{ mview_mupdate : forall s, mupdate mln s (mview mln s) = ret s\n; mupdate_mview : forall B (k : S -> A -> m B) s a,\n    mupdate mln s a >>= (fun s' => k s' (mview mln s')) =\n    mupdate mln s a >>= (fun s' => k s' a)\n}.\n", "meta": {"author": "hablapps", "repo": "koky", "sha": "7dc9141fafabeb0b381cfbda0cd6e856394cc9d4", "save_path": "github-repos/coq/hablapps-koky", "path": "github-repos/coq/hablapps-koky/koky-7dc9141fafabeb0b381cfbda0cd6e856394cc9d4/Core/lens.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417088, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6508270259474581}}
{"text": "From mathcomp Require Import all_ssreflect perm algebra.zmodp.\nFrom mathcomp Require Import zify.\nRequire Import more_tuple nsort.\n\nImport Order POrderTheory TotalTheory.\n\n(******************************************************************************)\n(*  Definition of the Batcher odd-even merge sorting algorithm                *)\n(*                                                                            *)\n(*      batcher_merge == the connector that links i to i.+1 for i odd         *)\n(*  batcher_merge_rec == the recursive network that calls itself on           *)\n(*                       the even and odd parts and then apply batcher_merge  *)\n(*                    == the network that calls itself on the top and bottom  *)\n(*                       parts and then apply batcher_merge_rec               *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Batcher.\n\nVariable d : unit.\nVariable A : orderType d.\n\nDefinition batcher_merge {m} : connector m := codd_jump 1.\n\nLemma cfun_batcher_merge n (t : n.-tuple A) : \n  cfun batcher_merge t = \n  [tuple\n    if odd i then min (tnth t i) (tnth t (inext i))\n    else max (tnth t i) (tnth t (ipred i)) | i < n].\nProof.\nrewrite [LHS]cfun_odd_jump //.\napply/val_eqP/eqP=> /=; apply/eq_map => i;\n      congr (if _ then min (tnth _ _) (tnth _ _) \n             else max _ _).\n  case: (n) i => //= n1 i; rewrite add1n.\n  by have := ltn_ord i; rewrite ltnS; case: (ltngtP i n1).\ncongr (tnth _ _); apply/val_eqP/eqP=> /=.\nrewrite /isub /ipred.\nby case: (n) i => //= n1 i; case: (i : nat) => [|i1]; rewrite ?addn1 ?subn1.\nQed.\n\nFixpoint batcher_merge_rec_aux m : network (`2^ m.+1) :=\n  if m is m1.+1 then rcons (neodup (batcher_merge_rec_aux m1)) batcher_merge\n  else [:: cswap ord0 ord_max].\n\nLemma size_batcher_merge_rec_aux m : size (batcher_merge_rec_aux m) = m.+1.\nProof.\nelim: m => [//| m IH] /=.\nby rewrite size_rcons size_map size_zip minnn IH.\nQed.\n\nDefinition batcher_merge_rec m := \n  if m is m1.+1 then batcher_merge_rec_aux m1 else [::].\n\nLemma size_batcher_merge_rec m : size (batcher_merge_rec m) = m.\nProof. by case: m => //= m; rewrite size_batcher_merge_rec_aux. Qed.\n\nFixpoint batcher m : network (`2^ m) :=\n  if m is m1.+1 then ndup (batcher m1) ++ batcher_merge_rec m1.+1\n  else [::].\n\nLemma size_batcher m : size (batcher m) = (m * m.+1)./2.\nProof. \nelim: m => [//|m IH].\nrewrite [in LHS]/= size_cat size_map size_zip minnn.\nrewrite size_batcher_merge_rec_aux IH.\nby rewrite -addn2 mulnDr -!divn2 divnDMl // mulnC.\nQed.\n\nEnd Batcher.\n\n\nLemma sorted_batcher_merge  (m : nat) (t : (m + m).-tuple bool) :\n noF (totake t) <= noF (tetake t) <= (noF (totake t)).+2 ->\n sorted <=%O (tetake t) -> sorted <=%O (totake t) ->\n sorted <=%O (cfun batcher_merge t).\nProof.\nmove=> /andP[FotLFet FotLFet2] eS oS.\npose i := noF (tetake t) - noF (totake t).\nhave i_le2 : i <= 2 by rewrite leq_subLR addn2.\nhave nFE : noF (tetake t) = noF (totake t) + i by rewrite addnC subnK.\nhave [ceS coF ncFE] := sorted_odd_jump (isT : odd 1) i_le2 eS oS nFE.\napply: sorted_tetake_totake => //.\nrewrite ncFE leq_addr -[X in _ <= X]addn1 leq_add2l /=.\nby rewrite leq_subLR addnC -leq_subLR -addnn leq_addr.\nQed.\n \n(* This is the big proof could be improved : lots of repetitions *)\nLemma sorted_nfun_batcher_merge_rec m (t : (`2^ m.+1).-tuple bool) :\n  sorted <=%O (ttake t) -> sorted <=%O (tdrop t) ->\n  sorted <=%O (nfun (batcher_merge_rec_aux m) t).\nProof.\nelim: m t => [t tS dS|m IH t tS dS /=].\n  rewrite [batcher_merge_rec_aux 0]/= tsorted2 /=.\n  by rewrite cswapE_min // cswapE_max // le_minl le_maxr lexx.\nrewrite nfun_rcons nfun_eodup.\nset n1 := nfun _ _; set n2 := nfun _ _.\nhave n1P : perm_eq n1 (tetake t) by apply: perm_nfun.\nhave n1S : sorted <=%O n1.\n  apply: IH.\n    by rewrite ttake_etakeE; apply: etake_sorted => // [] [] [] [].\n  by rewrite tdrop_etakeE; apply: etake_sorted => // [] [] [] [].\nhave n2P : perm_eq n2 (totake t) by apply: perm_nfun.\nhave n2S : sorted <=%O n2.\n  apply: IH.\n  - by rewrite ttake_otakeE; apply: otake_sorted => // [] [] [] [].\n  - by rewrite tdrop_otakeE; apply: otake_sorted => // [] [] [] [].\napply: sorted_batcher_merge; rewrite ?(tetakeK, totakeK) //.\nhave /isorted_boolP[[a1 b1] n1E] := n1S.\nhave /isorted_boolP[[a2 b2] n2E] := n2S.\nrewrite !n1E !n2E !noE.\nhave /isorted_boolP[[a3 b3] tSE] := tS.\nhave /isorted_boolP[[a4 b4] dSE] := dS.\nhave /val_eqP tE := cat_ttake_tdrop t; rewrite /= tSE dSE in tE.\nhave /val_eqP eotE := eocat_tetake_totake t.\nrewrite /= (eqP tE) !(etake_cat, otake_cat, etake_cat_nseq, otake_nseq, \n                      etake_nseq, size_cat, size_nseq, otake_cat_nseq) in eotE.\nhave : ~~ odd (size (ttake t)) by rewrite size_tuple addnn odd_double.\nrewrite tSE size_cat !size_nseq => /negPf b3O. \nrewrite b3O in eotE; rewrite oddD in b3O.\nhave : ~~ odd (size (tdrop t)) by rewrite size_tuple addnn odd_double.\nrewrite dSE size_cat !size_nseq oddD => /negPf b4O.\nrewrite tetakeE totakeE (eqP tE) !(etake_cat, otake_cat, otake_nseq, \n                                    etake_nseq, size_cat, size_nseq, \n                                    uphalf_half)\n         oddD n1E n2E in n1P n2P.\ncase: (boolP (odd a3)) b3O => [a3O /negP/negP b3O |/negPf a3E b3E].\n  case: (boolP (odd a4)) b4O => [a4O /negP/negP b4O|/negPf a4E b4E].\n(* First case *)\n    rewrite a3O a4O b3O b4O [if true (+) true then _ else _]/= !add1n in n1P.\n    rewrite a3O a4O b3O b4O [if true (+) true then _ else _]/= !add1n in n2P.\n    have [/eqP Ea1 /eqP Eb1] : a1 == (a3./2 + a4./2).+2 /\\\n                               b1 == b3./2 + b4./2.\n      move/allP/(_ false) : (n1P); move/allP/(_ true) : n1P.\n      rewrite /= !(count_cat, count_nseq) /= !(count_cat, count_nseq) /=.\n      rewrite !mul1n !mul0n !(addn0, add0n) !add1n !(addSn, addnS).\n      rewrite !(mem_cat, inE, mem_nseq, eqxx, orbT, orTb, orFb, orbF, \n                andbF, andbT) => Hb1 -> //; split=> //.\n      by case: (b1) Hb1 => [|x] //; (do 2 case (_./2) => [|?]) => // ->.\n    have [/eqP Ea2 /eqP Eb2] : a2 == a3./2 + a4./2 /\\ b2 == (b3./2 + b4./2).+2.\n      move/allP/(_ false) : (n2P); move/allP/(_ true) : n2P.\n      rewrite /= !(count_cat, count_nseq) /= !(count_cat, count_nseq) /=.\n      rewrite !mul1n !mul0n !(addn0, add0n, add1n, addSn, addnS).\n      rewrite !(mem_cat, mem_nseq, inE, eqxx, orTb, andTb, andbT, orbT,\n                andbF, orFb, orbF) => -> //.\n      by case: (a2) => [|?]//; (do 2 (case: (_./2) => [|?]//)) => ->.\n    by move=> {a3O b3O a4O b4O n1P n2P}//; lia.\n(* Second case *)\n  rewrite /= in b4E.\n  rewrite a3O b3O a4E b4E [if true (+) true then _ else _]/= \n          !add0n !add1n in n1P. \n  rewrite a3O a4E b3O b4E [if true (+) true then _ else _]/= in n2P.\n  have [/eqP Ea1 /eqP Eb1] : a1 == (a3./2 + a4./2).+1 /\\ b1 == b3./2 + b4./2.\n    move/allP/(_ false) : (n1P); move/allP/(_ true) : n1P.\n    rewrite /= !(count_cat, count_nseq) /= .\n    rewrite !mul1n !mul0n !(addn0, add0n) !add1n /=.\n    rewrite !(mem_cat, inE, mem_nseq, eqxx, orbT, orTb, orFb, orbF, \n              andbF, andbT) /= => Hb1 ->; split=> //.\n    by case: (b1) Hb1 => [|x]; (do 2 case (_./2) => [|?]) => // ->.\n  have [/eqP Ea2 /eqP Eb2] : a2 == a3./2 + a4./2 /\\ b2 == (b3./2 + b4./2).+1.\n    move/allP/(_ false) : (n2P); move/allP/(_ true) : n2P.\n    rewrite /= !(count_cat, count_nseq) /= !(count_cat, count_nseq) /=.\n    rewrite !mul1n !mul0n !(addn0, add0n, add1n, addSn, addnS).\n    rewrite !(mem_cat, mem_nseq, inE, eqxx, orTb, andTb, andbT, orbT,\n              andbF, orFb, orbF) => -> //.\n    by case: (a2) => [|?]//; (do 2 (case: (_./2) => [|?]//)) => ->.\n  by move=> {a3O b3O a4E b4E n1P n2P}//; lia.  \ncase: (boolP (odd a4)) b4O => [a4O /negP/negP b4O|/negPf a4E b4E].\n(* Third case *)\n  rewrite /= in b3E.\n  rewrite a3E b3E a4O [if false (+) false then _ else _]/= !add0n in n1P.\n  rewrite a3E b3E a4O b4O [if false (+) false then _ else _]/= in n2P. \n  have [/eqP Ea1 /eqP Eb1] : a1 == (a3./2 + a4./2).+1 /\\ b1 == b3./2 + b4./2.\n    move/allP/(_ false) : (n1P); move/allP/(_ true) : n1P.\n    rewrite /= !(count_cat, count_nseq) /= !(count_cat, count_nseq) /=.\n    rewrite !mul1n !mul0n !(addn0, add0n) !add1n !(addSn, addnS).\n    rewrite !(mem_cat, inE, mem_nseq, eqxx, orbT, orTb, orFb, orbF, \n              andbF, andbT) => Hb1 -> //; split => //.\n    by case: (b1) Hb1 => // => [|x]; (do 2 case (_./2) => [|?]) => // ->.\n  have [/eqP Ea2 /eqP Eb2] : a2 == a3./2 + a4./2 /\\ b2 == (b3./2 + b4./2).+1.\n    move/allP/(_ false) : (n2P); move/allP/(_ true) : n2P.\n    rewrite /= !(count_cat, count_nseq) /= !(count_cat, count_nseq) /=.\n    rewrite !mul1n !mul0n !(addn0, add0n, add1n, addSn, addnS).\n    rewrite !(mem_cat, mem_nseq, inE, eqxx, orTb, andTb, andbT, orbT,\n               andbF, orFb, orbF) => -> // Hb1; split => //.\n    by case: (a2) Hb1 => [|?]//; (do 2 (case: (_./2) => [|?]//)) => ->.\n  by move=> {a3E b3E a4O b4O n1P n2P}//; lia.\n(* Fourth case *)\nrewrite /= in a3E b3E b4E.\nrewrite a3E b3E a4E b4E [if false (+) false then _ else _]/= !add0n in n1P.\nrewrite a3E b3E a4E b4E [if false (+) false then _ else _]/= in n2P.\nhave [/eqP Ea1 /eqP Eb1] : a1 == a3./2 + a4./2 /\\ b1 == b3./2 + b4./2.\n  move/allP/(_ false) : (n1P); move/allP/(_ true) : n1P.\n  rewrite /= !(count_cat, count_nseq) /=.\n  rewrite !mul1n !mul0n !(addn0, add0n).\n  rewrite !(mem_cat, inE, mem_nseq, eqxx, orbT, orTb, orFb, orbF, \n            andbF, andbT) => Hb1 Ha1 //; split.\n    by case: (a1) Ha1 => [|x]; (do 2 case (_./2) => [|?]) => // ->.\n  by  case: (b1) Hb1 => [|x]; (do 2 case (_./2) => [|?]) => // ->.\nhave [/eqP Ea2 /eqP Eb2] : a2 == a3./2 + a4./2 /\\ b2 == b3./2 + b4./2.\n  move/allP/(_ false) : (n2P); move/allP/(_ true) : n2P.\n  rewrite /= !(count_cat, count_nseq) /=.\n  rewrite !mul1n !mul0n !(addn0, add0n, add1n, addSn, addnS).\n  rewrite !(mem_cat, mem_nseq, inE, eqxx, orTb, andTb, andbT, orbT,\n            andbF, orFb, orbF) => Hb2 Ha2; split.\n    by case: (a2) Ha2 => [|?]//; (do 2 (case: (_./2) => [|?]//)) => ->.\n  by case: (b2) Hb2 => [|?]//; (do 2 (case: (_./2) => [|?]//)) => ->.\nby move=> {a3E b3E a4E b4E n1P n2P}//; lia.\nQed.\n\nLemma sorted_nfun_batcher_merge m (t : (`2^ m.+1).-tuple bool) :\n  sorted <=%O (ttake t) -> sorted <=%O (tdrop t) ->\n  sorted <=%O (nfun (batcher_merge_rec m.+1) t).\nProof. exact: sorted_nfun_batcher_merge_rec. Qed.\n\nLemma sorted_nfun_batcher m (t : (`2^ m).-tuple bool) :\n  sorted <=%O (nfun (batcher m) t).\nProof.\nelim: m t => [t|m IH t] /=; first by apply: tsorted01.\nrewrite nfun_cat.\napply: sorted_nfun_batcher_merge_rec.\n  by rewrite nfun_dup ttakeK; apply: IH.\nby rewrite nfun_dup; rewrite tdropK; apply: IH.\nQed.\n\nLemma sorting_batcher m : batcher m \\is sorting.\nProof. apply/forallP => x; apply: sorted_nfun_batcher. Qed.\n\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/batcher.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6508270236249707}}
{"text": "(** * Indução em Coq *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Export aula05_listas.\n\n\n(* ############################################### *)\n(** * Listas polimórficas *)\n\n(** Polimorfismo permite criar definições abstraindo\n    os tipos de dados que serão manipulados. *)\n\nInductive list (X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\n(** Agora, [list] é uma função de [Type]s para\n    [Type]s. Dado um tipo [X], [list X] é o conjunto\n    de listas indutivamente definidas cujos elementos\n    possuem tipo [X]. *)\n\nCheck list.\n(* ===> list : Type -> Type *)\nCheck (nil nat).\n(* ===> nil nat : list nat *)\nCheck (cons nat 3 (nil nat)).\n(* ===> cons nat 3 (nil nat) : list nat *)\nCheck nil.\n(* ===> nil : forall X : Type, list X *)\nCheck cons.\n(* ===> cons : forall X : Type, X -> list X -> list X *)\n\n(** Funções sobre listas polimórficas. *)\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 =\n  cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity.  Qed.\n\nExample test_repeat2 :\n  repeat bool false 1 =\n  cons bool false (nil bool).\nProof. reflexivity.  Qed.\n\n(** Coq possui um mecanismo de inferência. *)\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(* ===> forall X : Type, X -> nat -> list X *)\nCheck repeat.\n(* ===> forall X : Type, X -> nat -> list X *)\n\n(** É importante ter um equilíbrio entre o\n    que é inferido e o que é informado:\n    - inferido: + prática, dificultar entendimento\n    - informado: - prático, facilitar entendimento. *)\n\n(** É possível indicar argumentos implícitos: [_]. *)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n(** É possível omitir até o [_]. A diretiva\n    [Arguments] especifica o nome de uma função\n    (ou construtor) e, em seguida, lista os nomes\n    dos seus argumentos, com chaves limitando\n    os argumentos que serão implícitos. Se a\n    função tiver argumentos sem nome, usar [_]. *)\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\n(** Agora é possível escrever o seguinte. *)\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\n(** Também é possível usar chaves na própria\n    definição da função. *)\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0        => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n(** Sugestão: usar a última opção para funções\n    e a anterior para construtores indutivos.\n    Em construtores, torna o tipo implícito\n    até para o tipo sendo definido pelo construtor.\n\n    Em alguns casos, será necessário informar\n    explicitamente o tipo implícito: [@]. *)\n\nFail Definition mynil := nil.\n\n(** Alternativas:\n    - Declarar o tipo explicitamente\n    - Tornar explícito o tipo implícito. *)\n\nDefinition mynil : list nat := nil.\n\nCheck @nil.\nDefinition mynil' := @nil nat.\n\n(** Outras funções para listas polimórficas. *)\n\nFixpoint app {X : Type} (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) =\n  (cons 2 (cons 1 nil)).\nProof. reflexivity.  Qed.\n\nExample test_rev2:\n  rev (cons true nil) =\n  cons true nil.\nProof. reflexivity.  Qed.\n\nExample test_length1:\n  length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity.  Qed.\n\n(** Definindo uma sintaxe conveniente para listas. *)\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(** Agora, podemos escrever listas da seguinte forma. *)\n\nDefinition list123''' := [1; 2; 3].\nCheck (list123''').\n\n(** **** Exercise: (poly_exercises)  *)\n(** Complete as provas a seguir. *)\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  (* COMPLETE AQUI *) Admitted.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  (* COMPLETE AQUI *) Admitted.\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  (* COMPLETE AQUI *) Admitted.\n\n(* ############################################### *)\n(** * Pares polimórficos *)\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\n(** A anotação [: type_scope] diz para Coq\n    só usar esta abreviação ao processar tipos.\n    Isto impede conflitos com o símbolo da\n    multiplicação. *)\n\n(** Algumas funções úteis. *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\n(** A função a seguir combina lista de pares. *)\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\nExample combine_test1 :\n  combine [1;2;3] [0;10]\n  = [(1,0);(2,10)].\nProof. reflexivity. Qed.\n\n(** **** Exercise: (split)  *)\n(** A função [split] é a inversa direita de [combine]:\n    dada uma lista de pares, retorna um par de listas. *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y)\n(* SUBSTITUA COM \":= _sua_definição_ .\" *). Admitted.\n\nExample test_split:\n  split [(1,false);(2,false)] =\n  ([1;2],[false;false]).\nProof.\n  (* COMPLETE AQUI *) Admitted.\n\n(* ############################################### *)\n(** * Option polimórfico *)\n\nInductive option (X:Type) : Type :=\n  | Some : X -> option X\n  | None : option X.\n\nArguments Some {X} _.\nArguments None {X}.\n\n(** Reescrevendo [nth_error]. *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if beq_nat n O then Some a\n               else nth_error l' (pred n)\n  end.\n\nExample test_nth_error1 :\n  nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 :\n  nth_error [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 :\n  nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\n(** **** Exercise: (hd_error_poly)  *)\n(** Complete a definição polimórfica\n    da função [hd_error]. *)\n\nDefinition hd_error {X : Type} (l : list X)\n           : option X\n(* SUBSTITUA COM \":= _sua_definição_ .\" *). Admitted.\n\nExample test_hd_error1 :\n  hd_error [1;2] = Some 1.\nProof. (* COMPLETE AQUI *) Admitted.\n\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\nProof. (* COMPLETE AQUI *) Admitted.\n\n(* ############################################### *)\n(** * Leitura sugerida *)\n\n(** Software Foundations: volume 1\n  - Polymorphism\n  https://softwarefoundations.cis.upenn.edu/lf-current/Poly.html\n*)\n", "meta": {"author": "gabritto", "repo": "TAES", "sha": "68512767bd3658beae20196f34ba785d001cca9a", "save_path": "github-repos/coq/gabritto-TAES", "path": "github-repos/coq/gabritto-TAES/TAES-68512767bd3658beae20196f34ba785d001cca9a/aula06_poli.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.8688267796346599, "lm_q1q2_score": 0.6508270213024832}}
{"text": "Set Implicit Arguments.\n\n(* A set of propositional variables. *)\nVariable ap: Set.\n\n(* Formulae in intuitionistic and classical propositinal logic. *)\nInductive fml: Set :=\n  | fml_var: ap -> fml\n  | fml_and: fml -> fml -> fml\n  | fml_or: fml -> fml -> fml\n  | fml_imp: fml -> fml -> fml\n  | fml_bot: fml.\n\n(* Notations.\n * We define level(and) := level( * ) == level(&&), level(or) := level(+) == level(||) and level(==>) slightly lower than +.\n * Since these formulae can't contain arithmetic expressions, there will be no clash.\n *)\nNotation \"s 'and' t\" := (fml_and s t) (at level 40, left associativity).\nNotation \"s 'or' t\" := (fml_or s t) (at level 50, left associativity).\nNotation \"s ==> t\" := (fml_imp s t) (at level 55, right associativity).\n\nDefinition fml_not x := x ==> fml_bot.\nDefinition fml_top := fml_not fml_bot.\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/prop_logic/fml.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.7490872019117029, "lm_q1q2_score": 0.6508270136697137}}
{"text": "Require Import Ensembles.\n\nSection KnasterTarski.\n  Variable U : Type.\n  Variable f : Ensemble U -> Ensemble U.\n  Hypotheses monotone : forall X Y, Included _ X Y -> Included _ (f X) (f Y).\n\n  Definition lfp : Ensemble U := fun x => forall X, Included _ (f X) X -> In _ X x.\n\n  Lemma lfp_lower_bound X : Included _ (f X) X -> Included _ lfp X.\n  Proof. intros HIncl ? HIn. apply HIn, HIncl. Qed.\n\n  Lemma lfp_f_closed : Included _ (f lfp) lfp.\n  Proof.\n    intros ? Hf ? HIncl.\n    eapply HIncl, monotone.\n    - apply lfp_lower_bound, HIncl.\n    - apply Hf.\n  Qed.\n\n  Lemma lfp_f_consistent : Included _ lfp (f lfp).\n  Proof. intros ? HIn. apply HIn, monotone, lfp_f_closed. Qed.\n\n  Definition gfp : Ensemble U := fun x => exists X, Included _ X (f X) /\\ In _ X x.\n\n  Lemma gfp_upper_bound X : Included _ X (f X) -> Included _ X gfp.\n  Proof. intros HIncl ? HIn. exists X. eauto. Qed.\n\n  Lemma gfp_f_consistent : Included _ gfp (f gfp).\n  Proof.\n    intros ? [? [HIncl HIn]].\n    eapply monotone.\n    - apply gfp_upper_bound, HIncl.\n    - eapply HIncl, HIn.\n  Qed.\n\n  Lemma gfp_f_closed : Included _ (f gfp) gfp.\n  Proof.\n    intros ? HIn.\n    exists (f gfp). split.\n    - apply monotone, gfp_f_consistent.\n    - apply HIn.\n  Qed.\nEnd KnasterTarski.", "meta": {"author": "fetburner", "repo": "metatheories", "sha": "68e1c0bc74e9dee5f081b76cba59b7f9ed30ae18", "save_path": "github-repos/coq/fetburner-metatheories", "path": "github-repos/coq/fetburner-metatheories/metatheories-68e1c0bc74e9dee5f081b76cba59b7f9ed30ae18/KnasterTarski.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6507498404689532}}
{"text": "Definition N := 14.\n\nInductive tree : Type :=\n| Leaf : tree\n| Node : nat -> tree -> tree -> tree.\n\nFixpoint binary_tree c n :=\n  match n with\n  | 0 => Leaf\n  | S n =>\n    let t := binary_tree c n in\n    Node c t t\n  end.\n\nDefinition t0 := Eval vm_compute in binary_tree 0 N.\nDefinition t1 := Eval vm_compute in binary_tree 1 N.\n", "meta": {"author": "eponier", "repo": "compare-eq", "sha": "cc2da184e747d0ad6ada8597e1ebf03377e413e2", "save_path": "github-repos/coq/eponier-compare-eq", "path": "github-repos/coq/eponier-compare-eq/compare-eq-cc2da184e747d0ad6ada8597e1ebf03377e413e2/equality_test/14/type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6507218970772575}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\nLemma lem : forall (x : lst) (y : natural), eq (rev (append x (Cons y Nil))) (Cons y (rev x)).\nProof.\ninduction x.\n- intros. simpl. rewrite IHx. reflexivity.\n- intros. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : lst) (y : lst) (z : natural), eq (rev (append x (append y (Cons z Nil)))) (Cons z (rev (append x y))).\nProof.\ninduction x.\n- intros. simpl. rewrite IHx. reflexivity.\n- intros.  simpl. lfind. \nAdmitted.\n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal59_theorem0_33_lem/goal59.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6507218927412245}}
{"text": "Require Coq.Lists.List.\nRequire Coq.Lists.SetoidList.\n\nTheorem InA_In : forall (A : Type) (x : A) (xs : list A),\n  SetoidList.InA (@eq _) x xs -> List.In x xs.\nProof.\n  induction xs as [|y ys]. {\n    intros H_in.\n    inversion H_in.\n  } {\n    intros H_in.\n    inversion H_in.\n    subst; simpl in *; auto.\n    subst; simpl in *; auto.\n  }\nQed.\n\nLemma InMapPair : forall (A B : Type) (x : A) (y : B) es,\n  List.In (x, y) es ->\n    List.In x (List.map fst es) /\\ List.In y (List.map snd es).\nProof.\n  induction es as [|f fs]. {\n    intros H_f0.\n    inversion H_f0.\n  } {\n    intros H_in0.\n    destruct H_in0 as [H_inL|H_inR]. {\n      constructor; (left; destruct f as [f0 f1]; rewrite H_inL; reflexivity).\n    } {\n      constructor; (right; destruct (IHfs H_inR) as [H0 H1]; auto).\n    }\n  }\nQed.\n", "meta": {"author": "io7m", "repo": "genevan", "sha": "3a4baf90ecbc72b86f435352623a18ea3755a7cf", "save_path": "github-repos/coq/io7m-genevan", "path": "github-repos/coq/io7m-genevan/genevan-3a4baf90ecbc72b86f435352623a18ea3755a7cf/com.io7m.genevan.core/src/main/coq/Genevan/ListExts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6507218877024195}}
{"text": "(********************)\n(********************)\n(****            ****)\n(****   Syntax   ****)\n(****            ****)\n(********************)\n(********************)\n\nRequire Import Main.SystemF.Name.\n\nInductive term :=\n| eFreeVar : name -> term\n| eBoundVar : nat -> term\n| eAbs : type -> term -> term\n| eApp : term -> term -> term\n| eTAbs : term -> term\n| eTApp : term -> type -> term\n\nwith type :=\n| tFreeVar : name -> type\n| tBoundVar : nat -> type\n| tArrow : type -> type -> type\n| tForAll : type -> type.\n", "meta": {"author": "stepchowfun", "repo": "proofs", "sha": "00da33f63a56080227d06d37fd0f28b560f24624", "save_path": "github-repos/coq/stepchowfun-proofs", "path": "github-repos/coq/stepchowfun-proofs/proofs-00da33f63a56080227d06d37fd0f28b560f24624/proofs/SystemF/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467643431001, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6507218853587099}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq             *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later            *)\nFrom mathcomp Require Import all_ssreflect ssralg finalg poly polydiv cyclic.\nFrom mathcomp Require Import perm matrix mxpoly vector mxalgebra zmodp.\nRequire Import ssr_ext ssralg_ext poly_ext channel_code decoding linearcode.\nRequire Import hamming dft poly_decoding euclid grs cyclic_code.\n\n(******************************************************************************)\n(*                        Reed-Solomon codes                                  *)\n(*                                                                            *)\n(* The main result of this file is the proof that Reed-Solomon codes          *)\n(* implement bounded-distance decoding (Lemma RS_repair_is_correct).          *)\n(*                                                                            *)\n(* Main references:                                                           *)\n(* - Robert McEliece, The Theory of Information and Coding,  Cambridge        *)\n(*   University Press, 2002                                                   *)\n(* - Manabu Hagiwara, Coding Theory: Mathematics for Digital Communication,   *)\n(*   Nippon Hyoron Sha, 2012 (in Japanese)                                    *)\n(******************************************************************************)\n\n(** OUTLINE\n- Section reed_solomon_min_dist_errors.\n- Module RS.\n  + Section reed_solomon_def.\n  + Section reed_solomon_prop.\n- Section RS_generator_def.\n- Section RS_is_GRS.\n- Section reed_solomon_key_equation.\n- Section RS_decoding_procedure.\n- Section RS_generator_prop0.\n- Section RS_generator_prop1.\n- Section RS_generator_prop.\n- Section RS_decoding_using_euclid0.\n- Section RS_decoding_using_euclid.\n- Module RS_encoder.\n- Section RS_cyclic.\n*)\n\nReserved Notation \"'\\RSsynp_(' a , y , t )\" (at level 3).\nReserved Notation \"'\\RSomega_(' a , e )\" (at level 3).\nReserved Notation \"'\\gen_(' a , d )\" (at level 3).\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory.\nLocal Open Scope ring_scope.\nLocal Open Scope dft_scope.\n\nModule RS.\n\nLocal Notation \"'\\RSsynp_(' a , y , t )\" := (syndromep a y t).\nLocal Notation \"'\\RSomega_(' a , e )\" := (erreval a a e).\n\nLocal Open Scope vec_ext_scope.\n\nSection reed_solomon_min_dist_errors.\n\nVariables (t d n : nat).\n\nDefinition redundancy_ub := d < n. (* definition of RS *)\nDefinition errors_ub := t <= d./2. (* necessary condition to decode t errors *)\n\nEnd reed_solomon_min_dist_errors.\n\nSection reed_solomon_def.\n\nVariables (F : finFieldType) (a : F) (n d : nat).\n\nDefinition PCM : 'M[F]_(d, n) := \\matrix_(i, j) (a ^+ i.+1) ^+ j.\n\nDefinition code : {vspace _} := kernel PCM.\n\nEnd reed_solomon_def.\n\nSection reed_solomon_prop.\n\nVariables (F : finFieldType) (a : F) (n' : nat).\nLet n := n'.+1.\nVariable d : nat.\nHypothesis dn : redundancy_ub d n.\nHypothesis a_neq0 : a != 0.\nHypothesis a_not_uroot_on : not_uroot_on a n.\n\nLemma uniq_roots_exp : uniq_roots [seq a ^+ i | i <- iota 1 d].\nProof.\nrewrite uniq_rootsE map_inj_in_uniq; first by rewrite iota_uniq.\nmove=> i j.\nrewrite !mem_iota addnC addn1 => H1.\nmove: H1 => // /andP[_ Hid] /andP [_ Hjd] /eqP aij.\napply/eqP.\nby rewrite (val_eqE (Ordinal (leq_trans _ dn)) (Ordinal (leq_trans _ dn))) -(exp_inj a_neq0).\nQed.\n\nLocal Notation \"v ^`_ i\" := (v ^`_(rVexp a n, i)) (at level 9).\n\nDefinition codebook :=\n  [set c : 'rV_n | [forall i : 'I_d.+1, (0 < i) ==> (c ^`_ (inord i) == 0)] ].\n\nLemma all_root_codeword c : c \\in codebook ->\n  all (root (rVpoly c)) [seq a ^+ i | i <- iota 1 d].\nProof.\nrewrite inE => /forallP H.\napply/allP => x /mapP[i].\nrewrite mem_iota addnC addn1 => H1.\nmove: H1 => // id ->.\napply/rootP.\ncase/andP : id => i0 id.\nmove: (H (Ordinal id)); rewrite i0 implyTb => /eqP.\nby rewrite /fdcoor mxE inordK // (leq_trans id).\nQed.\n\nLemma deg_lb c : c \\in codebook -> (c == 0) || (d.+1 <= size (rVpoly c)).\nProof.\nmove=> H.\ncase/boolP : (c == 0) => //=.\nrewrite -rVpoly0 => c0.\nmove: (uniq_roots_exp); rewrite uniq_rootsE.\nmove/(max_poly_roots c0 (all_root_codeword H)).\nby rewrite size_map size_iota -ltnS.\nQed.\n\nLemma O_in_codebook : 0 \\in codebook.\nProof.\nrewrite inE; apply/forallP => i; apply/implyP => i0; by rewrite fdcoor0.\nQed.\n\nLemma oppr_closed : oppr_closed codebook.\nProof.\nmove=> /= c; rewrite inE => /forallP H.\nrewrite inE; apply/forallP => i; apply/implyP => i0.\nrewrite fdcoorN eqr_oppLR oppr0; move: (H i); by rewrite i0 implyTb.\nQed.\n\nLemma addr_closed : addr_closed codebook.\nProof.\nsplit; [exact: O_in_codebook | move=> x y].\nhave [xy|xy] := boolP (x + y == 0); first by rewrite /= (eqP xy) O_in_codebook.\nrewrite inE => /forallP H1; rewrite inE => /forallP H2.\nrewrite inE; apply/forallP => i; apply/implyP => i0.\nrewrite fdcoorD.\nmove: (H1 i) (H2 i); by rewrite i0 2!implyTb => /eqP-> /eqP->; rewrite addr0.\nQed.\n\nLemma scaler_closed : GRing.scaler_closed codebook.\nProof.\nmove=> k x; rewrite !inE => /forallP xC.\napply/forallP => /= i; apply/implyP => i0.\nrewrite tdcoorZ; move: (xC i); rewrite i0 implyTb => /eqP ->; by rewrite mulr0.\nQed.\n\nLemma submod_closed : submod_closed codebook.\nProof.\nsplit=> [|k x y xC yCby]; first exact: O_in_codebook.\nby rewrite (proj2 addr_closed) // scaler_closed.\nQed.\n\nLemma syndrome_syndromep y :\n  syndrome (PCM a n d) y = poly_rV \\RSsynp_(rVexp a n, y, d).\nProof.\napply/rowP => i; rewrite !mxE /syndromep poly_def coef_sum.\nevar (tmp : 'I_d -> F); transitivity (\\sum_j (tmp j)); last first.\n  apply eq_bigr => /= j _.\n  apply/esym; rewrite /fdcoor coefZ horner_poly big_distrl /= /tmp; reflexivity.\nrewrite {}/tmp (exchange_big_dep xpredT) //=; apply eq_bigr => j _; rewrite !mxE.\nhave @i' :  'I_d.\n  by apply (@Ordinal _ i); rewrite (leq_trans (ltn_ord i)).\nrewrite (bigD1 i') //= coefXn insubT //= => Hj.\nrewrite eqxx mulr1 (_ : Ordinal Hj = j); last by apply val_inj.\nrewrite mxE inordK; last by rewrite ltnS (leq_trans (ltn_ord i)).\nrewrite mulrC; apply/eqP.\nrewrite addrC -subr_eq subrr; apply/eqP/esym.\nrewrite big1 // => k ki'; rewrite coefXn (_ : (_ == _) = false) ?mulr0 //.\nby apply: contraNF ki'; rewrite -val_eqE /= eq_sym.\nQed.\n\nLemma codebook_syndrome (c : 'rV_n) :\n  (c \\in codebook) = (syndrome (PCM a n d) c == 0).\nProof.\nrewrite syndrome_syndromep inE; apply/idP/idP.\n- move/forallP => H; apply/eqP/rowP => i; rewrite !mxE.\n  rewrite /syndromep /poly_decoding.syndromep poly_def coef_sum.\n  rewrite (eq_bigr (fun=> 0)) ?big_const ?iter_addr0 // => j _.\n  rewrite coefZ; apply/eqP; rewrite mulf_eq0.\n  have @j' : 'I_d.+1.\n    by apply (@Ordinal _ j.+1); move: (ltn_ord j); rewrite -ltnS.\n  move: (H j'); by rewrite lt0n /= => ->.\n- move/eqP/rowP => H.\n  apply/forallP => /= i; apply/implyP => i0.\n  have @i' : 'I_d.\n    apply (@Ordinal _ i.-1).\n    by rewrite prednK // -ltnS.\n  move: (H i'); rewrite !mxE.\n  rewrite /syndromep /poly_decoding.syndromep.\n  rewrite coef_poly ltn_ord => /eqP /=.\n  by rewrite prednK.\nQed.\n\nLemma lcode0_codebook : [set cw in code a n d] = codebook.\nProof.\nby apply/setP => /= x; rewrite inE mem_kernel_syndrome0 codebook_syndrome.\nQed.\n\nLemma RS_syndromep_codeword' t (tr : t < d.+1) (c : 'rV[F]_n) :\n  c \\in codebook -> \\RSsynp_(rVexp a n, c, t) = 0.\nProof.\nrewrite inE // => /forallP H.\nrewrite /syndromep /poly_decoding.syndromep poly_def (eq_bigr \\0) ?big1 //.\nmove=> i _.\nhave [:tmp] @j : 'I_d.+1.\n  apply/(Sub i.+1)/(leq_ltn_trans (ltn_ord _)).\n  abstract: tmp.\n  exact tr.\nby move: (H j) => /= /eqP ->; rewrite scale0r.\nQed.\n\nLemma RS_syndromep_codeword (c : 'rV[F]_n) :\n  (\\RSsynp_(rVexp a n, c, d) == 0) = (c \\in codebook).\nProof.\napply/idP/idP => [/eqP | ]; last first.\n  by move/(@RS_syndromep_codeword' d) => /(_ (ltnSn _)) ->.\nrewrite codebook_syndrome syndrome_syndromep => /eqP ?.\nby rewrite poly_rV_0.\nQed.\n\nEnd reed_solomon_prop.\nEnd RS.\n\nNotation \"'\\RSsynp_(' a , e , t )\" := (syndromep a e t).\nNotation \"'\\RSomega_(' a , e )\" := (erreval a a e).\n\nLocal Open Scope vec_ext_scope.\n\nSection RS_generator_def.\n\nVariables (F : finFieldType) (a : F) (d : nat).\n\nDefinition rs_gen := \\prod_(1 <= i < d.+1) ('X - (a ^+ i)%:P).\n\nEnd RS_generator_def.\n\nNotation \"'\\gen_(' a , d )\" := (rs_gen a d).\n\n(** Reed-Solomon codes are an instance of GRS codes. Take a and b to\nbe \\alpha^j to get conventional RS codes. *)\nSection RS_is_GRS.\n\nVariables (F : finFieldType) (n' : nat).\nLet n := n'.+1.\nVariables (a : F) (d : nat).\n\nLet b : 'rV[F]_n := rVexp a n.\n\nLemma RS_GRS_PCM : GRS.PCM b b d = RS.PCM a n d.\nProof.\napply/matrixP => i j.\nrewrite !mxE (bigD1 j) //= !mxE eqxx mulr1n -exprSr -exprM mulnC exprM.\nrewrite (eq_bigr (fun=> 0)) ?big_const ?iter_addr0 ?addr0 // => k kj.\nby rewrite !mxE (negbTE kj) mulr0n mulr0.\nQed.\n\nLemma fdcoor_GRS_syndrome_coor y l : l < n' -> l < d ->\n  fdcoor b y (inord l.+1) = GRS.syndrome_coord b b l y.\nProof.\nmove=> ln id1.\nrewrite /fdcoor /GRS.syndrome_coord horner_poly; apply/eq_bigr => /= j _.\nrewrite insubT // => jn.\nrewrite 2!mxE -mulrA; congr (y ord0 _ * _); first by apply val_inj.\nby rewrite -exprS -exprM mulnC exprM inordK.\nQed.\n\nLemma RS_GRS_syndromep y : RS.redundancy_ub d n ->\n  \\RSsynp_(b, y, d) = (GRS.syndromep b b d) y.\nProof.\nmove=> dn; rewrite /GRS.syndromep /poly_decoding.syndromep.\napply/polyP => i.\nrewrite 2!coef_poly; case: ifP => // id1.\nby rewrite fdcoor_GRS_syndrome_coor // (leq_trans id1).\nQed.\n\nEnd RS_is_GRS.\n\nSection reed_solomon_key_equation.\n\nVariables (F : finFieldType) (a : F) (n' : nat).\nLet n := n'.+1.\nVariable t : nat.\n\nHypothesis tn : t < n.\n\nDefinition RS_mod (y : 'rV[F]_n) t := - \\sum_(i in supp y) y ``_ i *:\n  (\\prod_(j in supp y :\\ i) (1 - a ^+ j *: 'X) * - (a ^+ (t.+1 * i))%:P).\n\nLemma RS_mod_is_GRS_mod y : RS_mod y t = - GRS_mod y (rVexp a n) (rVexp a n) t.\nProof.\nrewrite /RS_mod /GRS_mod; congr (- _); apply/eq_bigr => /= i iy.\nrewrite !mulrN scalerN; congr (- _).\nrewrite -!scalerAl; congr (_ *: _ ).\nrewrite -mulrA; congr (_ * _).\n  apply eq_big.\n    by move=> j; rewrite in_setD1 andbC.\n  by move=> j; rewrite mxE.\nby rewrite mxE -polyCM -exprSr -exprM mulnC.\nQed.\n\nLemma RS_key_equation y :\n  \\sigma_(rVexp a n, y) * \\RSsynp_(rVexp a n, y, t) =\n  \\RSomega_(rVexp a n, y) + - RS_mod y t * 'X^t.\nProof.\nmove: (@RS_GRS_syndromep F n' a t y tn) => H0.\nmove: (GRS_key_equation y (rVexp a n) (rVexp a n) t).\nrewrite -{}H0 => ->; by rewrite RS_mod_is_GRS_mod opprK.\nQed.\n\nEnd reed_solomon_key_equation.\n\nSection RS_decoding_procedure.\n\nVariables (F : finFieldType) (a : F) (n' : nat).\nLet n := n'.+1.\nVariable d : nat.\nLet t := d./2.\nHypothesis dn : RS.redundancy_ub d n.\n\nLet td : t <= d. Proof. by rewrite /t -divn2 leq_div. Qed.\n\nLocal Notation \"'v'\" := (Euclid.v).\nLocal Notation \"'r'\" := (Euclid.r).\n\nDefinition RS_err y : {poly F} :=\n  let r0 : {poly F} := 'X^d in\n  let r1 := \\RSsynp_(rVexp a n, y, d) in\n  let vstop := v r0 r1 (stop (odd d + t) r0 r1) in\n  let rstop := r r0 r1 (stop (odd d + t) r0 r1) in\n  let s := vstop.[0]^-1 *: vstop in\n  let w := vstop.[0]^-1 *: rstop in\n  \\poly_(i < n) (if s.[a^- i] == 0 then - w.[a ^- i] / s^`().[a ^- i] else 0).\n\nDefinition RS_repair : repairT F F n := [ffun y =>\n  if \\RSsynp_(rVexp a n, y, d) == 0 then\n    Some y\n  else\n    let ret := y - poly_rV (RS_err y) in\n    if \\RSsynp_(rVexp a n, ret, d) == 0 then Some ret else None].\n\nEnd RS_decoding_procedure.\n\n(* TODO: move? *)\nLemma leqnmul2 k : k <= k.*2.\nProof. by rewrite -addnn leq_addr. Qed.\n\nSection RS_generator_prop0.\n\nVariables (F : finFieldType) (a : F) (n' : nat) (d : nat).\nLet n := n'.+1.\n\nLemma size_rs_gen : size \\gen_(a, d) = d.+1.\nProof. by rewrite size_prod_XsubC size_iota subn1 prednK. Qed.\n\nLemma wH_rs_gen : wH (poly_rV \\gen_(a, d) : 'rV[F]_n) <= d.+1.\nProof.\nby rewrite (leq_trans (wH_poly_rV _ _)) // size_rs_gen.\nQed.\n\nLemma gen_neq0 : \\gen_(a, d) != 0.\nProof. by rewrite -size_poly_gt0 size_rs_gen. Qed.\n\nLemma fdcoor_codeword (n0 : 'I_d.+1) (Hn0 : 0 < n0 < n) (m : {poly F}) :\n  size (m * \\gen_(a, d)) <= n ->\n  (poly_rV (m * \\gen_(a, d)) : 'rV_n)^`_(rVexp a n, inord n0) == 0.\nProof.\nmove=> mn.\nrewrite /fdcoor poly_rV_K // !hornerE.\nrewrite mxE inordK; last first.\n  by case/andP : Hn0.\ncase Hm : (m.[a ^+ n0] == 0); first by rewrite (eqP Hm) mul0r.\napply negbT in Hm.\nrewrite mulrI_eq0; last by move : Hm => /lregP.\nrewrite -rootE.\npose rs := [seq (a ^+ i) | i <- iota 1 d].\nrewrite /rs_gen.\nhave -> : \\prod_(1 <= n1 < d.+1) ('X - (a ^+ n1)%:P) = \\prod_(a <- rs) ('X - a%:P)\n  by rewrite /rs big_map /index_iota subn1.\nrewrite root_prod_XsubC /rs.\napply/mapP; exists (val n0) => //.\nrewrite mem_iota.\ncase/andP : Hn0 => -> _.\nrewrite addnC addn1 /=; by apply ltn_ord.\nQed.\n\nHypothesis dn : RS.redundancy_ub d n.\n\nLemma mem_rs_gen_RS : poly_rV \\gen_(a, d) \\in RS.code a n d.\nProof.\nrewrite mem_kernel_syndrome0 -RS.codebook_syndrome // inE.\napply/forallP => /= i; apply/implyP => i0.\nrewrite -(mul1r \\gen_(a, d)) fdcoor_codeword //.\n  by rewrite i0 /= (leq_trans (ltn_ord i)) //.\nrewrite mul1r size_rs_gen; exact: dn.\nQed.\n\nLemma RS_not_trivial : not_trivial (RS.code a n d).\nProof.\nrewrite /not_trivial.\nexists (poly_rV (rs_gen a d)); apply/andP; split.\n- by rewrite mem_rs_gen_RS.\n- apply/negP => /poly_rV_0_inv.\n  rewrite size_rs_gen => /(_ dn).\n  apply/negP; by rewrite gen_neq0.\nQed.\n\nLemma RS_message_size (p : 'rV_n) x : rVpoly p = x * \\gen_(a, d) ->\n  (size x).-1 <= n - d.+1.\nProof.\nmove=> Hx.\ncase/boolP : (x == 0) => [/eqP ->|x0]; first by rewrite size_poly0.\nhave : size (rVpoly p) <= n by rewrite size_poly.\nrewrite Hx size_mul // ?gen_neq0 // => H.\nrewrite -(leq_add2r d.+1) (subnK dn) (leq_trans _ H) //.\nrewrite -subn1 addnC addnBA; last by rewrite lt0n size_poly_eq0.\nby rewrite -subn1 addnC leq_sub2r // leq_add2l size_rs_gen.\nQed.\n\nEnd RS_generator_prop0.\n\nSection RS_generator_prop1.\n\nVariables q m' : nat.\nHypothesis primeq : prime q.\nLet F := GF m' primeq.\nVariables (a : F) (n' : nat) (d : nat).\nLet n := n'.+1.\n\nHypothesis dn : RS.redundancy_ub d n.\nHypothesis qn : ~~ (q %| n)%nat.\n\nLemma RS_Hchar : ([char F]^').-nat n.\nProof. by rewrite -natf_neq0 -(@dvdn_charf _ q) ?char_GFqm. Qed.\n\nLemma RS_min_dist1 c : n.-primitive_root a -> c != 0 ->\n  c \\in RS.code a n d -> d.+1 <= wH c.\nProof.\nmove=> an c0 Hc.\nhave a_neq0 := primitive_uroot_neq0 an.\nrewrite -(wH_phase_shift a_neq0 _ d).\napply: (@BCH_argument_lemma _ _ (@GRing.idfun_rmorphism F) _ RS_Hchar _ an\n  (phase_shift a c d.+1) _ dn).\n  by rewrite -wH_eq0 wH_phase_shift // wH_eq0.\nrewrite (_ : \\row_i0 (GRing.idfun_rmorphism F) ((phase_shift a c d.+1) ``_ i0) =\n  phase_shift a c d.+1); last by apply/rowP => i; rewrite !mxE.\napply (dft_shifting a_neq0 (prim_expr_order an) dn) => i /andP[ir1 ir2].\nhave {Hc} : c \\in RS.codebook a n' d by rewrite -(RS.lcode0_codebook a dn) inE.\nrewrite inE => /forallP/(_ (Ordinal ir2)) /=.\nby rewrite ir1 implyTb !mxE => /eqP.\nQed.\n\nLemma RS_min_dist : n.-primitive_root a ->\n  min_dist (RS_not_trivial a dn) = d.+1.\nProof.\nmove=> na.\napply min_distP; split; first by move=> *; apply RS_min_dist1.\nexists (poly_rV \\gen_(a, d)); split; first by rewrite mem_rs_gen_RS.\napply/andP; rewrite wH_rs_gen andbT.\napply: contra (gen_neq0 a d).\nmove/poly_rV_0_inv; apply; by rewrite size_rs_gen.\nQed.\n\nLemma PCM_lin1_mx :\n  RS.PCM a n d = (lin1_mx (linfun (lin_syndrome (RS.PCM a n d))))^T.\nProof.\napply/matrixP => i j.\nrewrite !(mxE,lfunE) (bigD1 j) //= !mxE !eqxx mulr1 (eq_bigr (fun=> 0)).\n- by rewrite big_const iter_addr0 addr0.\n- move=> k kj; by rewrite !mxE eqxx (negbTE kj) mulr0.\nQed.\n\nLemma dim_RS_code (a0 : a != 0) (auroot : not_uroot_on a n) :\n  \\dim (RS.code a n d) = (n - d)%N.\nProof.\napply dim_kernel; last by rewrite ltnW.\nrewrite -RS_GRS_PCM rank_GRS_PCM //.\n- by apply (@rVexp_inj _ _ _ a0 auroot).\n- by rewrite ltnW.\n- move=> i; by rewrite mxE expf_neq0.\nQed.\n\nLemma RS_MDS : n.-primitive_root a ->\n  maximum_distance_separable (RS_not_trivial a dn).\nProof.\nmove=> an.\nrewrite /maximum_distance_separable RS_min_dist // addn1 dim_RS_code //.\n- by rewrite subKn // ltnW.\n- exact: primitive_uroot_neq0 an.\n- by apply prim_root_not_uroot_on.\nQed.\n\nEnd RS_generator_prop1.\n\nSection RS_generator_prop.\n\nVariable (F : finFieldType) (a : F).\nVariables (d : nat) (n' : nat).\nLet n := n'.+1.\nHypothesis dn : RS.redundancy_ub d n.\nHypothesis a_neq0 : a != 0.\nHypothesis a_not_uroot_on : not_uroot_on a n.\n\nLemma rs_genP (c : 'rV[F]_n) : c \\in RS.codebook a n' d\n  <-> exists m : {poly F}, (size m).-1 <= n - d.+1 /\\ rVpoly c = m * \\gen_(a, d).\nProof.\nsplit => [c_in_RS| [m [H0 H1]] ]; last first.\n  rewrite /RS.codebook inE.\n  apply/forallP => n0; apply/implyP => Hn0.\n  rewrite -(rVpolyK c) H1 fdcoor_codeword //.\n    rewrite Hn0 /= (leq_trans (ltn_ord n0)) //.\n    by rewrite -H1 size_poly.\ncase/boolP : (c == 0) => [/eqP ->|Hc].\n  exists 0; by rewrite size_poly0 -subn1 sub0n leq0n mul0r linear0.\nhave Hc' : 0 < size (rVpoly c) by rewrite size_poly_gt0 rVpoly0.\nhave H1 : forall i, 1 <= i < d.+1 -> (rVpoly c).[a ^+ i] = 0.\n  move=> i /andP[i0 id].\n  move: c_in_RS; rewrite inE => /forallP/(_ (Ordinal id)); rewrite i0 implyTb /fdcoor // => /eqP.\n  by rewrite mxE /= inordK // (leq_trans id).\nhave H2 : forall n0, 1 <= n0 < d.+1 -> 'X - (a ^+ n0)%:P %| rVpoly c.\n  move=> n0 /H1 /eqP /factor_theorem [x ->].\n  by rewrite dvdp_mull.\npose rs := [seq (a ^+ i) | i <- iota 1 d].\nhave K1 : all (root (rVpoly c)) rs by apply RS.all_root_codeword.\nhave K2 : uniq_roots rs by apply: (@RS.uniq_roots_exp _ _ n').\ncase: (uniq_roots_prod_XsubC K1 K2) => m.\nhave -> : \\prod_(z <- rs) ('X - z%:P) = \\gen_(a, d).\n  by rewrite /rs_gen /rs big_map /index_iota subn1.\nhave Hg := size_rs_gen a d.\nhave Hg' : 0 < size \\gen_(a, d) by rewrite Hg.\nhave Hg'' := gen_neq0 a d.\nmove => Hm.\nhave Hm' : m != 0.\n  move : Hm => /eqP.\n  apply contraLR => /negPn/eqP ->; by rewrite mul0r rVpoly0.\nhave Hm'' : 0 < size m by rewrite size_poly_gt0.\nexists m; split; [| by rewrite Hm].\nhave : size (rVpoly c) <= n by apply size_poly.\nrewrite Hm.\nmove : (size_mul_leq m \\gen_(a, d)) => Hmg.\nrewrite size_mul // -!subn1 addnC -addnBA // addnC.\nmove /(leq_sub2r d.+1).\nrewrite Hg.\nby move : (addnK d.+1 (size m - 1)%N) => ->.\nQed.\n\nLocal Open Scope cyclic_code_scope.\n\nLemma rs_gen_is_pgen : \\gen_(a, d) \\in 'pgen[RS.codebook a n' d].\nProof.\napply/forallP => cw; apply/eqP; apply/idP/idP.\n  case/rs_genP => x [sz_x ->]; by rewrite dvdp_mulIr.\nrewrite dvdp_eq => /eqP H; apply/rs_genP.\nexists (rVpoly cw %/ \\gen_(a, d)); split => //.\nrewrite size_divp ?gen_neq0 // size_rs_gen.\nby rewrite -subnS /= leq_sub2r // size_poly.\nQed.\n\nEnd RS_generator_prop.\n\nSection RS_decoding_using_euclid0.\n\nVariables (F : finFieldType) (a : F) (n' : nat).\nLet n := n'.+1.\nVariable d : nat.\nLet t := d./2.\n\nHypothesis dn : RS.redundancy_ub d n.\n\nHypothesis a_neq0 : a != 0.\nHypothesis a_not_uroot_on : not_uroot_on a n.\n\nLet tn : t.*2 < n.\nProof.\nby rewrite /t (leq_trans _ dn) // ltnS -{2}(odd_double_half d) leq_addl.\nQed.\n\n(* TODO: clean *)\nLemma td : RS.errors_ub t d.+1.\nProof.\nby rewrite /RS.errors_ub /t half_leq.\nQed.\n\nLemma RS_err_is_correct l (e y : 'rV_n) :\n  distinct_non_zero (rVexp a n) ->\n  let r0 := 'X^d : {poly F} in\n  let r1 := \\RSsynp_(rVexp a n, y, d) in\n  let vj := Euclid.v r0 r1 (stop (odd d + t) r0 r1) in\n  let rj := Euclid.r r0 r1 (stop (odd d + t) r0 r1) in\n  l <> 0 ->\n  vj = l *: \\sigma_(rVexp a n, e) ->\n  rj = l *: \\RSomega_(rVexp a n, e) ->\n  e = poly_rV (RS_err a d y).\nProof.\nmove=> H1 r0 r1 vj rj /eqP l0 Hvj Hrj; apply/rowP => i.\nrewrite mxE coef_poly ltn_ord -/r0 -/r1 -/vj -/rj; case: ifPn => H.\n  apply: (@mulIf _ ((rVexp a n) ``_ i)).\n    by rewrite mxE expf_eq0 negb_and a_neq0 orbT.\n  rewrite (erreval_vecE H1 (rVexp a n)) //; last first.\n    rewrite -(errloc_zero _ _ H1) mxE.\n    move: H; rewrite Hvj !hornerZ !mulrA mulf_eq0 => /orP[|//].\n    rewrite mulf_eq0 (negbTE l0) orbF invr_eq0 mulf_eq0 (negbTE l0) orFb.\n    by rewrite horner_errloc_0 oner_eq0.\n  rewrite 2![in RHS]mulNr -[in RHS]mulrN [in RHS]mulrC -mulrA; congr (_ * _).\n  rewrite Hvj Hrj -/(\\RSomega_(rVexp a n, e)) mxE !scalerA !(hornerZ,derivZ).\n  set x := (_^-1 * _).\n  rewrite -mulf_div divrr ?mul1r // unitfE mulf_neq0 //.\n  by rewrite invr_neq0 // mulf_neq0 // horner_errloc_0 oner_neq0.\napply/eqP; apply: contraNT H.\nrewrite -insupp -(errloc_zero _ _ H1) mxE Hvj !hornerZ => /eqP ->.\nby rewrite !mulr0.\nQed.\n\nEnd RS_decoding_using_euclid0.\n\nSection RS_decoding_using_euclid.\n\nVariables q m' : nat.\nHypothesis primeq : prime q.\nLet F := GF m' primeq.\nVariables (a : F) (n' : nat) (d : nat).\nLet n := n'.+1.\n\nHypothesis dn : RS.redundancy_ub d n.\nHypothesis qn : ~~ (q %| n)%nat.\n\nLet t := d./2.\n\nLocal Open Scope ecc_scope.\n\nLemma RS_repair_is_correct : n.-primitive_root a ->\n  t.-BDD (RS.code a n d, RS_repair a n.-1 d).\nProof.\nmove=> an; rewrite /BD_decoding /=.\nmove=> c e.\nset y := c + e.\nset r0 : {poly F} := 'X^d.\nset r1 := \\RSsynp_(rVexp a n, y, d).\nset vj := Euclid.v r0 r1 (stop (odd d + t) r0 r1).\nset rj := Euclid.r r0 r1 (stop (odd d + t) r0 r1).\nmove=> Hc et.\nset r_ : {poly F} := \\RSomega_(rVexp a n, e).\nrewrite /= /RS_repair.\nhave same_syndrome : \\RSsynp_(rVexp a n, y, d) = \\RSsynp_(rVexp a n, e, d).\n  rewrite syndromepD.\n  move: Hc => /=.\n  rewrite mem_kernel_syndrome0 -RS.codebook_syndrome //.\n  rewrite -RS.RS_syndromep_codeword // => /eqP ->; by rewrite add0r.\nrewrite ffunE.\ncase: ifPn => syndrome0.\n  suff e0 : e = 0 by rewrite /y e0 addr0.\n  suff yc : y = c.\n    move/eqP : yc; by rewrite -subr_eq0 /y addrAC subrr add0r => /eqP.\n  apply/eqP/negPn/negP => abs.\n  suff : dH y c < min_dist (RS_not_trivial a dn).\n    apply/negP; rewrite -leqNgt min_dist_prop //.\n    move: syndrome0; by rewrite RS.RS_syndromep_codeword // -RS.lcode0_codebook // inE.\n  rewrite (RS_min_dist dn _ an) // dH_sym dH_wH (@leq_ltn_trans t) //.\n  move: (td d).\n  rewrite /RS.errors_ub ltnS => /leq_trans; apply.\n  by rewrite -{2}(half_bit_double d true) add1n half_leq // ltnS -addnn leq_addr.\nhave H1 : distinct_non_zero (rVexp a n).\n  apply distinct_non_zero_rVexp.\n  by apply (primitive_uroot_neq0 an).\n  by move/prim_root_not_uroot_on: an.\nhave H2 := rVexp_neq0 _ (primitive_uroot_neq0 an).\nhave r1_neq0 : \\RSsynp_(rVexp a n, e, d) != 0.\n  apply: contra syndrome0.\n  rewrite syndromepD => /eqP ->.\n  by rewrite addr0 RS.RS_syndromep_codeword // -RS.lcode0_codebook // inE.\nhave K1 : size r1 <= size ('X^d : {poly F}).\n  by rewrite /r1 size_polyXn (leq_trans (size_syndromep _ _ _)).\nhave K2 : \\RSsynp_(rVexp a n, y, d) != 0 by rewrite same_syndrome.\nhave K3 : \\sigma_(rVexp a n, e) * r1 = r_ + - RS_mod a e d * 'X^d.\n  by rewrite /r1 same_syndrome RS_key_equation.\nhave K4 : size \\sigma_(rVexp a n, e) <= t.+1.\n  rewrite (leq_trans (size_errloc _ _)) => //; by rewrite -wH_card_supp.\nhave K5 : size r_ <= odd d + t.\n  rewrite wH_card_supp in et.\n  by rewrite (leq_trans (size_erreval (rVexp a n) (Errvec et) _)) // leq_addl.\nhave K6 : (t.+1 + (odd d + t))%N = size ('X^d : {poly F}).\n  rewrite size_polyXn addnCA addSn addnn addnS; congr S.\n  by rewrite -[RHS](odd_double_half d).\nmove: (@solve_key_equation_coprimep F 'X^d r1 K1 \\sigma_(rVexp a n, e) r_ _ (errloc_neq0 (rVexp a n) (supp e)) K2 t.+1 _ K3 K4 K5 K6 (coprime_errloc_erreval H1 (@H2 n) _)).\ncase=> l [l0 [Hvj Hrj]].\nby rewrite -(@RS_err_is_correct _ _ _ _ (primitive_uroot_neq0 an) l e) // /y addrK ifT // RS.RS_syndromep_codeword // -RS.lcode0_codebook // inE.\nQed.\n\nEnd RS_decoding_using_euclid.\n\nModule RS_encoder.\n\nSection RS_encoder_sect.\n\nVariable (F : finFieldType) (a : F).\nVariables (d : nat) (n' : nat).\nLet n := n'.+1.\nHypothesis dn : RS.redundancy_ub d n.\n\nDefinition encoder : encT F [finType of 'rV[F]_(n - d.+1).+1] n :=\n  let g := \\gen_(a, d) in\n [ffun m => let mxd := rVpoly m * 'X^d in poly_rV (mxd - mxd %% g)].\n\n(* TODO(rei) *)\nLemma tmp : (d + (n - d.+1).+1 = n)%nat.\nProof.\nmove: dn; rewrite /RS.redundancy_ub => ?.\nrewrite subnS prednK //; last by rewrite subn_gt0.\nby rewrite subnKC // ltnW.\nQed.\n\nDefinition RS_discard' (x : 'rV[F]_n) : 'rV[F]_(n - d.+1).+1 :=\n  rsubmx (castmx (erefl, esym tmp) x).\n\nDefinition RS_discard (x : 'rV[F]_n) : 'rV[F]_(n - d.+1).+1 :=\n  poly_rV ((rVpoly x) %/ 'X^d).\n\nDefinition decoder : decT F [finType of 'rV[F]_(n - d.+1).+1] n :=\n  [ffun y => omap RS_discard (RS_repair a _ d y)].\n\nDefinition RS_code := mkCode encoder decoder.\n\n(* NB: first part of lemma 10.60 *)\nLemma RS_enc_injective : injective (enc RS_code).\nProof.\nmove=> x1 x2 /=.\nrewrite /encoder 2!ffunE => x1x2.\nsuff H : rVpoly x1 * 'X^d.+1 = rVpoly x2 * 'X^d.+1.\n  rewrite -(rVpolyK x1) -(rVpolyK x2).\n  have : (rVpoly x1 * 'X^d.+1) %/ 'X^d.+1 = (rVpoly x2 * 'X^d.+1) %/ 'X^d.+1 by rewrite H.\n  rewrite mulpK; last by rewrite -size_poly_gt0 size_polyXn.\n  rewrite mulpK; last by rewrite -size_poly_gt0 size_polyXn.\n  by move=> ->.\napply/eqP.\nrewrite -subr_eq0 -mulrBl.\nsuff : ((rVpoly x1 - rVpoly x2) == 0) &&\n  ((rVpoly x2 * 'X^d) %% \\gen_(a, d) -\n   (rVpoly x1 * 'X^d) %% \\gen_(a, d) == 0).\n  case/andP => /eqP ->; by rewrite mul0r.\nhave H1 : size ((rVpoly x2 * 'X^d) %% \\gen_(a, d)) < d.+1.\n  by rewrite -[in X in _ < X](size_rs_gen a d) ltn_modp gen_neq0.\nhave H2 : size ((rVpoly x1 * 'X^d) %% \\gen_(a, d)) < d.+1.\n  by rewrite -[in X in _ < X](size_rs_gen a d) ltn_modp gen_neq0.\nrewrite -(@rreg_div0 _ _ _ 'X^d).\n- rewrite mulrBl -(opprB (_ %% _)).\n  rewrite (_ : forall a b c d, a - b - (c - d) = (a - c) + (d - b)); last first.\n    move=> *.\n    rewrite -2!addrA; congr (_ + _).\n    rewrite addrA addrC opprD; congr (_ - _).\n    by rewrite opprK.\n  rewrite addr_eq0 opprB -subr_eq0.\n  move/eqP : x1x2.\n  rewrite -[in X in X -> _]subr_eq0 -linearB /= => /poly_rV_0_inv; apply.\n  rewrite (leq_trans (size_add _ _)) // size_opp geq_max.\n  have H : forall x : 'rV[F]_(n - d.+1).+1, size (rVpoly x * 'X^d) <= n.\n    move=> x.\n    apply (leq_trans (size_mul_leq _ _)).\n    rewrite size_polyXn addnS /=.\n    rewrite (@leq_trans ((n - d.+1).+1 + d)) //.\n      by rewrite leq_add2r size_poly.\n    move: dn; rewrite /RS.redundancy_ub => ?.\n    by rewrite subnS prednK // ?subn_gt0 // subnK // ltnW.\n  apply/andP; split; rewrite (leq_trans (size_add _ _)) // geq_max size_opp H /=.\n    by rewrite (leq_trans _ dn) // ltnW.\n    by rewrite (leq_trans _ dn) // ltnW.\n- rewrite lead_coefXn; exact: GRing.rreg1.\n- rewrite size_polyXn ltnS (leq_trans (size_add _ _)) //.\n  rewrite geq_max size_opp /=; apply/andP; split; by rewrite -ltnS.\nQed.\n\nHypothesis a_neq0 : a != 0.\nHypothesis a_not_uroot_on : not_uroot_on a n.\n\n(* NB: corresponds to lemma 10.59? *)\nLemma RS_enc_img :\n  (enc RS_code) @: [finType of 'rV[F]_(n - d.+1).+1] \\subset RS.code a n d.\nProof.\napply/subsetP => /= c /imsetP[/= m _] ->{c}.\nrewrite /encoder ffunE.\nhave Htmp : size (rVpoly m * 'X^d) <= n.\n  eapply leq_trans; first by apply size_mul_leq.\n  rewrite size_polyXn addnS /=.\n  suff : size (rVpoly m) <= (n - d.+1).+1.\n    rewrite -(leq_add2r d) => /leq_trans -> //.\n    by rewrite subnS prednK ?subn_gt0 // subnK // ltnW.\n  by apply size_poly.\nsuff : poly_rV (rVpoly m * 'X^d - (rVpoly m * 'X^d) %% \\gen_(a, d))\n    \\in [set cw in RS.code a n d].\n  by rewrite !inE.\nrewrite (@RS.lcode0_codebook _ a n' d); last by exact dn.\napply/(rs_genP dn a_neq0 a_not_uroot_on).\nexists ((rVpoly m * 'X^d) %/ \\gen_(a, d)).\nsplit.\n  rewrite size_divp; last apply: gen_neq0.\n  rewrite -subnS prednK; last by rewrite size_poly_gt0; exact: gen_neq0.\n  apply (@leq_trans (n - size \\gen_(a, d))).\n  apply leq_sub => //.\n  apply leq_sub2l => //.\n  rewrite size_rs_gen //; exact: d_pos.\nrewrite {1}(divp_eq (rVpoly m * 'X^d) \\gen_(a, d)) addrK poly_rV_K //.\nby eapply leq_trans; first by apply leq_trunc_divp.\nQed.\n\nLemma RS_repair_output_is_in_the_code (x y : 'rV_n) (an1 : a ^+ n = 1) :\n  RS_repair a _ d x = Some y -> y \\in RS.code a n d.\nProof.\nrewrite /RS_repair ffunE.\ncase: ifPn => [|_].\n  rewrite RS.RS_syndromep_codeword // -RS.lcode0_codebook // inE.\n  by move=> ? [<-].\ncase: ifPn => [|//].\nrewrite RS.RS_syndromep_codeword // -RS.lcode0_codebook // inE => ?.\nby case=> <-.\nQed.\n\nLemma RS_repair_img (an1 : a ^+ n = 1) (Hchar : ([char F]^').-nat n'.+1) :\n  oimg (RS_repair a _ d) \\subset RS.code a n d.\nProof.\napply/subsetP => /= y.\nrewrite inE => /existsP[/= x /eqP].\nby apply RS_repair_output_is_in_the_code.\nQed.\n\nDefinition low (c : 'rV[F]_n) : 'rV[F]_d := poly_rV (rVpoly c %% 'X^d).\nDefinition high (c : 'rV[F]_n) : 'rV[F]_(n - d.+1).+1 := poly_rV (rVpoly c %/ 'X^d).\n\nLemma decomp_codeword (c : 'rV[F]_n) : rVpoly c = rVpoly (low c) + rVpoly (high c) * 'X^d.\nProof.\nrewrite poly_rV_K; last first.\n  move: (@ltn_modp _ (rVpoly c) 'X^d).\n  by rewrite size_polyXn -size_poly_eq0 size_polyXn.\nrewrite poly_rV_K; last first.\n  rewrite size_divp; last by rewrite -size_poly_eq0 size_polyXn.\n  rewrite size_polyXn /= -(subSn dn) (@leq_trans (n - d)) //.\n  by rewrite leq_sub2r // size_poly.\nby rewrite addrC -divp_eq.\nQed.\n\nLemma RS_enc_surjective (c : 'rV[F]_n) : c \\in RS.codebook a n' d ->\n  encoder (high c) = c.\nProof.\nmove=> c_RS; apply/eqP; rewrite -subr_eq0 -rVpoly0.\nset m := high c.\nsuff H : size (rVpoly (encoder m - c)) <= d.\n  have : encoder m - c \\in RS.codebook a n' d.\n    have Hencm : encoder m \\in RS.codebook a n' d.\n      move: RS_enc_img.\n      rewrite -RS.lcode0_codebook //.\n      move/subsetP/(_ (encoder m)) => K.\n      have : encoder m \\in [set encoder x | x : 'rV_(n - d.+1).+1].\n        by apply/imsetP; exists m.\n      move/K => {K}.\n      by rewrite inE.\n    case: (RS.addr_closed a n' d) => _.\n    move/(_ _ (- c) Hencm); apply.\n    by rewrite RS.oppr_closed.\n  case/(@RS.deg_lb _ a _ _ dn a_neq0 a_not_uroot_on)/orP => [/eqP ->|].\n    apply/eqP/polyP => i.\n    rewrite coef_poly coef0.\n    case: ifP => // _.\n    by case: (insub i) => // ?; rewrite mxE.\n  by move=> /leq_trans/(_ H); rewrite ltnn.\nrewrite /encoder ffunE linearB /= poly_rV_K; last first.\n  rewrite (leq_trans (size_add _ _)) // geq_max.\n  apply/andP; split.\n    rewrite (leq_trans (size_mul_leq _ _)) // size_polyXn addnS /=.\n    apply (@leq_trans ((n - d.+1).+1 + d)).\n      by rewrite leq_add2r size_poly.\n    by rewrite subnS prednK ?subn_gt0 // subnK // ltnW.\n  rewrite size_opp (@leq_trans d) //; last exact/ltnW.\n  by rewrite -ltnS -[in X in _ <= X](size_rs_gen a d) ltn_modp gen_neq0.\npose c1 := low c.\nrewrite (_ : _ - _ = - rVpoly c1 - (rVpoly m * 'X^d) %% \\gen_(a, d)); last first.\n  rewrite addrC addrA; congr (_ - _).\n  by rewrite (decomp_codeword c) opprD subrK.\nrewrite (leq_trans (size_add _ _)) // geq_max.\napply/andP; split.\n  by rewrite size_opp /rVpoly size_poly.\nby rewrite size_opp -ltnS -[in X in _ <= X](size_rs_gen a d) ltn_modp gen_neq0.\nQed.\n\nLemma RS_enc_discard_is_id : cancel_on (RS.code a n d) encoder RS_discard.\nProof.\nmove=> /= c Hc.\nrewrite /RS_discard -/(high c); apply RS_enc_surjective.\nby rewrite -RS.lcode0_codebook // ?inE.\nQed.\n\nDefinition RS_as_lcode (an1 : a ^+ n = 1) (Hchar : ([char F]^').-nat n) :\n  Lcode.t _ _ _ [finType of 'rV_(n - d.+1).+1] :=\n    @Lcode.mk _ _ _ _ _\n      (Encoder.mk RS_enc_injective RS_enc_img)\n      (Decoder.mk (RS_repair_img an1 Hchar) RS_discard)\n      RS_enc_discard_is_id.\n\nEnd RS_encoder_sect.\n\nEnd RS_encoder.\n\nSection RS_cyclic.\n\nVariable (F : finFieldType) (a : F).\nVariables (d : nat) (n' : nat).\nLet n := n'.+1.\nHypothesis dn : RS.redundancy_ub d n.\nHypothesis an : n.-primitive_root a.\nLet a0 : a != 0 := primitive_uroot_neq0 an.\nLet an1 : a ^+ n = 1 := prim_expr_order an.\n\nLemma RS_cyclic : rcsP [set cw in RS.code a n d].\nProof.\nrewrite (_ : [set cw in _] = [set cw in RS.codebook a n' d]); last first.\n  apply/setP => i; by rewrite -RS.lcode0_codebook // inE 2![in RHS]inE.\nmove=> /= y.\nrewrite !inE => /forallP x_RS.\napply/forallP => /= i; apply/implyP => i0; apply/eqP.\nmove: x_RS => /(_ i); rewrite i0 implyTb => /eqP x_RS.\nmove/(congr1 (fun x => a^+i * x)) : x_RS.\nrewrite mulr0 => H.\napply fdcoor_rcs; first exact: prim_expr_order.\nmove/eqP: H.\nby rewrite mulf_eq0 expf_eq0 i0 (negbTE a0) /= => /eqP.\nQed.\n\nLocal Open Scope cyclic_code_scope.\n\nLemma rs_gen_is_gen : poly_rV \\gen_(a, d) \\in 'cgen[Ccode.mk RS_cyclic].\nProof.\napply pgen_is_cgen => /=; first exact: RS_not_trivial.\napply/forallP => /= p; apply/eqP; apply/idP/idP.\n  move=> Hp.\n  move: (proj1 (rs_genP dn a0 (prim_root_not_uroot_on an) p)).\n  rewrite RS.codebook_syndrome //.\n  rewrite inE mem_kernel_syndrome0 /syndrome in Hp.\n  rewrite Hp => /(_ erefl); case=> m [H1 H2].\n  rewrite poly_rV_K // ?size_rs_gen //.\n  by rewrite H2 dvdp_mull // modpp.\nmove=> Hp.\nrewrite inE mem_kernel_syndrome0 /linearcode.syndrome.\nrewrite -(@RS.codebook_syndrome _ a n' d) //.\napply: (proj2 (rs_genP dn a0 (prim_root_not_uroot_on an) p)).\nrewrite poly_rV_K // ?size_rs_gen // in Hp.\ncase/dvdpP : Hp => x Hx.\nby exists x; split => //; exact: RS_message_size Hx.\nQed.\n\nEnd RS_cyclic.\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/ecc_classic/reed_solomon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6507126336961008}}
{"text": "(* Surjective Library *)\n(* v0   Olivier Laurent *)\n\n\n(** * Some properties of surjective functions *)\n\nRequire Import List.\n\nDefinition surjective {A B} (f : A -> B) := forall y, exists x, y = f x.\n\nDefinition surjective2 {A B C} (f : A -> B -> C) := forall z, exists x y, z = f x y.\n\n(** * Basic properties of surjective functions *)\n\nLemma comp_surj {A B C} : forall (f : B -> C) (g : A -> B),\n  surjective f -> surjective g -> surjective (fun x => f (g x)).\nProof.\nintros f g Hf Hg z.\ndestruct (Hf z) as [y Heq] ; subst.\ndestruct (Hg y) as [x Heq] ; subst.\nexists x ; reflexivity.\nQed.\n\nLemma retract_surj {A B} : forall (f : A -> B) g,\n  (forall x, f (g x) = x) -> surjective f.\nProof.\nintros f g Hret y.\nexists (g y).\nrewrite Hret.\nreflexivity.\nQed.\n\nLemma map_surj {A B} : forall f : A -> B, surjective f -> surjective (map f).\nProof.\nintros f Hf l1.\ninduction l1.\n- exists nil.\n  reflexivity.\n- destruct (Hf a) as [b Heq] ; subst.\n  destruct IHl1 as [l Heq] ; subst.\n  exists (b :: l).\n  reflexivity.\nQed.\n\n\n\n", "meta": {"author": "olaure01", "repo": "yalla", "sha": "9c6a66fa3a3d68b5a21ce7fa695402a0f2dda4d7", "save_path": "github-repos/coq/olaure01-yalla", "path": "github-repos/coq/olaure01-yalla/yalla-9c6a66fa3a3d68b5a21ce7fa695402a0f2dda4d7/ollibs/Surjective.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6507126250090278}}
{"text": "Require Import HoTT.\nRequire Import Functors.\n\nOpen Scope list_scope.\n\nGeneralizable Variables A B X Y f g x y z w T F.\n\nSection List_is_monad.\n  Notation T := list.\n  Local Fixpoint bind (A B: Type) (X: T A) (f: A -> list B): list B\n    := match X with\n       | nil => nil\n       | x :: xs => (f x) ++ (bind A B xs f)\n       end.\n\n  Local Definition ret (A: Type) (X: A): T A := X :: nil.\n  \n  Local Definition ret_unit_left : forall (A B : Type) (k : A -> T B) (a : A),\n                    bind A B (ret A a) k = k a.\n    intros; unfold bind, ret.\n    SearchAbout \"++\".\n  \n  Local Definition ret_unit_right : forall (A : Type) (m : T A), \n                    bind A A m (ret A) = m.\n  \n  Local Definition bind_assoc : forall (A B C : Type) (m : T A) (k : A -> T B)\n                   (h : B -> T C), bind A C m (fun x : A => \n                   bind B C (k x) h) = bind B C (bind A B m k) h.\n  \n  Global Instance list_is_monad : TMonad list\n    := {|  |}\n\nEnd List_is_monad.\n\nDefinition merge {X: Type} : list (list X) -> list X :=\n  fix merge lists :=\n  match lists with\n  | nil => nil\n  | xs :: lists => xs ++ (merge lists)\n  end.\n\nFixpoint list_map {X Y: Type} (f: X -> Y) (xs: list X) : list Y := \n  match xs with\n  | nil => nil\n  | x :: xs' => (f x) :: (list_map f xs')\n  end.\n\nSection Assoc_Algebra.\n  Notation Ends X := (list X -> X).\n\n  Variable A : Type.\n\n  Definition VirtualCompose (is_op : Ends A -> Type) := \n    let V := (exists f, is_op f) in\n    forall (f g: V), exists (h: V), (g.1 o (list_map f.1) = h.1 o merge).\n  \n  Record Associative := \n  {\n    is_op: Ends A -> Type;\n    comp: VirtualCompose is_op;\n    unique_operation: Contr (exists f, is_op f)\n    }.\n  \nEnd Assoc_Algebra.\n\nArguments comp [_] _ _ _.\nArguments is_op [_] _ _.\nArguments unique_operation [_] _ .\nArguments VirtualCompose [A] _.\n\n(* Note: we can reduce the structures in definition of A_00 algebras and\ntheir maps from maps of type families to maps of elemets, i.e. a composition\nin A_00 structure is a path p: m m = m concat, where m is some virtual \noperation. A functor is a map f: X -> Y with p: f m_X = m_Y f and preserving \ncomposition p. *)\n\nDefinition VirtualOp {X: Type} (A: Associative X) := \n  exists (f: list X -> X), A.(is_op) f.\n\nRecord Assoc_map {X Y: Type} (A: Associative X) (B: Associative Y) :=\n  {\n    base_map: X -> Y;\n    operation_map: forall (f: VirtualOp A), exists (g: VirtualOp B),\n                      g.1 o base_map = base_map o f.1;\n    compose_map: \n  (** Simplicial objects: to associate simplicial object to monoid M, consider Hom( F_n , M), where F_n is a free monoid on n generators. Free monoid form a simplicial object, thus Hom(..) is cosimplicial. **)\n  (** Simplicial category maps to FinSet (forget the ordering) and FinSet maps to Monoid via free monoid functor. Thus free monoids are cosimplicial.**)", "meta": {"author": "afetisov", "repo": "HottCat", "sha": "b22c6298fa0b97c868760199ca09a1a5eacd73c0", "save_path": "github-repos/coq/afetisov-HottCat", "path": "github-repos/coq/afetisov-HottCat/HottCat-b22c6298fa0b97c868760199ca09a1a5eacd73c0/Associative.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6507126236414453}}
{"text": "Require Export Coq.Bool.Bool CoqRecon.Util.ListLib.\n\nDeclare Scope set_scope.\nDelimit Scope set_scope with set.\n\nReserved Notation \"l ∪ r\" (at level 45, left associativity).\nReserved Notation \"l ∩ r\" (at level 44, left associativity).\nReserved Notation \"l ∖ r\" (at level 43, left associativity).\n\nNotation \"e ∈ s\"\n  := (In e s)\n       (at level 80, no associativity) : set_scope.\n\nNotation \"e ∉ s\"\n  := (~ In e s)\n       (at level 80, no associativity) : set_scope.\n\n(** [l ⊆ r] *)\nDefinition Subset {A : Set} (l r : list A) : Prop :=\n  forall a, (a ∈ l -> a ∈ r)%set.\n\nNotation \"l ⊆ r\"\n  := (Subset l r)\n       (at level 80, no associativity) : set_scope.\n\nDefinition set_equiv {A : Set} (l r : list A) : Prop :=\n  (l ⊆ r /\\ r ⊆ l)%set.\n\nNotation \"l ≡ r\"\n  := (set_equiv l r)\n       (at level 80, no associativity) : set_scope.\n\nSection SetEquiv.\n  Open Scope set_scope.\n\n  Context {A : Set}.\n\n  Local Hint Unfold set_equiv : core.\n  Local Hint Unfold Subset : core.\n  Local Hint Unfold Reflexive : core.\n  \n  Lemma set_equiv_Reflexive :\n    Reflexive (@set_equiv A).\n  Proof.\n    autounfold with core; auto.\n  Qed.\n\n  Local Hint Unfold Symmetric : core.\n  \n  Lemma set_equiv_Symmetric :\n    Symmetric (@set_equiv A).\n  Proof.\n    autounfold with core; intuition.\n  Qed.\n\n  Local Hint Unfold Transitive : core.\n\n  Lemma set_equiv_Transitive :\n    Transitive (@set_equiv A).\n  Proof.\n    autounfold with core; intuition.\n  Qed.\n\n  Local Hint Resolve set_equiv_Reflexive : core.\n  Local Hint Resolve set_equiv_Symmetric : core.\n  Local Hint Resolve set_equiv_Transitive : core.\n  Local Hint Constructors Equivalence : core.\n  \n  Global Instance SetEquiv : Equivalence (@set_equiv A).\n  Proof.\n    auto.\n  Qed.\nEnd SetEquiv.\n\nSection SubsetPO.\n  Context {A : Set}.\n\n  Open Scope set_scope.\n\n  Local Hint Unfold Subset : core.\n  Local Hint Unfold Reflexive : core.\n  \n  Lemma Subset_reflexive : Reflexive (@Subset A).\n  Proof.\n    autounfold with *; auto.\n  Qed.\n\n  Local Hint Unfold Transitive : core.\n  \n  Lemma Subset_transitive : Transitive (@Subset A).\n  Proof.\n    autounfold with *; firstorder.\n  Qed.\n\n  Local Hint Unfold set_equiv : core.\n\n  Lemma Subset_antisymmetric : forall l r : list A,\n      l ⊆ r -> r ⊆ l -> l ≡ r.\n  Proof.\n    autounfold with *; firstorder.\n  Qed.\n\n  Lemma Subset_refl : forall l : list A, l ⊆ l.\n  Proof.\n    auto using Subset_reflexive.\n  Qed.\n\n  Lemma Subset_trans : forall l l' l'' : list A,\n      l ⊆ l' -> l' ⊆ l'' -> l ⊆ l''.\n  Proof.\n    auto using Subset_transitive.\n  Qed.\n\n  Lemma Subset_nil : forall l : list A, [] ⊆ l.\n  Proof.\n    intuition.\n  Qed.\nEnd SubsetPO.\n\nSection SetDefs.\n  Context {A : Set}.\n\n  Open Scope set_scope.\n  \n  Local Hint Unfold Subset : core.\n  Local Hint Resolve Permutation_in : core.\n  Local Hint Resolve Permutation_sym : core.\n\n  Lemma Subset_perm_l : forall l l' : list A,\n      Permutation l l' ->\n      forall r, l ⊆ r -> l' ⊆ r.\n  Proof. eauto. Qed.\n\n  Lemma Subset_perm_r : forall r r' : list A,\n      Permutation r r' ->\n      forall l, l ⊆ r -> l ⊆ r'.\n  Proof. eauto. Qed.\n\n  Lemma Subset_perm : forall l l' r r' : list A,\n      Permutation l l' -> Permutation r r' -> l ⊆ r -> l' ⊆ r'.\n  Proof.\n    intros l l' r r' Hl Hr; autounfold with *; eauto.\n  Qed.\n  \n  (** [u] is the union of [l] & [r]. *)\n  Definition Union (l r u : list A) : Prop :=\n    forall a, a ∈ u <-> a ∈ l \\/ a ∈ r.\n\n  Local Hint Unfold Union : core.\n\n  Lemma Union_Subset_l : forall l r u,\n      Union l r u -> l ⊆ u.\n  Proof. firstorder. Qed.\n\n  Lemma Union_Subset_r : forall l r u,\n      Union l r u -> r ⊆ u.\n  Proof. firstorder. Qed.\n\n  Lemma Union_perm_l : forall l l',\n      Permutation l l' ->\n      forall r u, Union l r u -> Union l' r u.\n  Proof. firstorder eauto. Qed.\n\n  Lemma Union_perm_r : forall r r',\n      Permutation r r' ->\n      forall l u, Union l r u -> Union l r' u.\n  Proof. firstorder eauto. Qed.\n\n  Lemma Union_perm_u : forall u u',\n      Permutation u u' ->\n      forall l r, Union l r u -> Union l r u'.\n  Proof. firstorder eauto. Qed.\n      \n  (** [i] is the intersection of [l] & [r]. *)\n  Definition Intersection (l r i : list A) : Prop :=\n    forall a, a ∈ i <-> a ∈ l /\\ a ∈ r.\n\n  Definition Disjoint (l r : list A) : Prop := Intersection l r [].\n\n  Local Hint Unfold Intersection : core.\n\n  Lemma Inter_Subset_l : forall l r i,\n      Intersection l r i -> i ⊆ l.\n  Proof.\n    firstorder.\n  Qed.\n\n  Lemma Inter_Subset_r : forall l r i,\n      Intersection l r i -> i ⊆ r.\n  Proof.\n    firstorder.\n  Qed.\n\n  Lemma Inter_perm_l : forall l l',\n      Permutation l l' ->\n      forall r i, Intersection l r i -> Intersection l' r i.\n  Proof. firstorder eauto. Qed.\n\n  Lemma Inter_perm_r : forall r r',\n      Permutation r r' ->\n      forall l i, Intersection l r i -> Intersection l r' i.\n  Proof. firstorder eauto. Qed.\n\n  Lemma Intersection_perm_i : forall i i',\n      Permutation i i' ->\n      forall l r, Intersection l r i -> Intersection l r i'.\n  Proof.\n    autounfold with core.\n    intros i i' HP l r H a;\n      pose proof H a as [Hai  Halr];\n      split; eauto.\n  Qed.\n  \n  (** [d] is the diff of [l] & [r]. *)\n  Definition Difference (l r d : list A) : Prop :=\n    forall a, a ∈ d <-> a ∈ l /\\ a ∉ r.\n\n  Local Hint Unfold Difference : core.\n  \n  Lemma Diff_Subset : forall l r d,\n      Difference l r d -> d ⊆ l.\n  Proof.\n    firstorder.\n  Qed.\n\n  Lemma Diff_perm_l : forall l l',\n      Permutation l l' ->\n      forall r d, Difference l r d -> Difference l' r d.\n  Proof. firstorder eauto. Qed.\n\n  Lemma Diff_perm_r : forall r r',\n      Permutation r r' ->\n      forall l d, Difference l r d -> Difference l r' d.\n  Proof. firstorder eauto. Qed.\n\n  Lemma Diff_perm_u : forall d d',\n      Permutation d d' ->\n      forall l r, Difference l r d -> Difference l r d'.\n  Proof.\n    autounfold with core.\n    intros d d' HP l r HD a;\n      pose proof HD a as [Had Halr]; split; eauto.\n  Qed.\n\n  Lemma Subset_Diff : forall l r,\n      l ⊆ r ->\n      Difference l r [].\n  Proof.\n    unfold Subset, Difference.\n    intros l r Hs a; simpl; intuition.\n  Qed.\n\n  Lemma Subset_cons : forall l r : list A,\n      l ⊆ r -> forall a : A, a :: l ⊆ a :: r.\n  Proof.\n    unfold Subset; intros;\n      simpl in *; intuition.\n  Qed.\nEnd SetDefs.\n\nSection ComputeSets.\n  Context {A : Set} {HEA: EqDec A eq}.\n  \n  Fixpoint member (a : A) (l : list A) : bool :=\n    match l with\n    | []    => false\n    | h :: t => if a == h then true else member a t\n    end.\n  \n  Fixpoint intersect (l r : list A) : list A :=\n    match l with\n    | []    => []\n    | h :: t =>\n      (if member h r then [h] else []) ++ intersect t r\n    end.\n\n  Fixpoint difference (l r : list A) : list A :=\n    match l with\n    | []    => []\n    | h :: t =>\n      (if member h r then [] else [h]) ++ difference t r\n    end.\nEnd ComputeSets.\n\nNotation \"l ∪ r\" := (l ++ r) : set_scope.\nNotation \"l ∩ r\" := (intersect l r) : set_scope.\nNotation \"l ∖ r\" := (difference l r) : set_scope.\n\nSection Sets.\n  Open Scope set_scope.\n  \n  Context {A : Set} {HEA: EqDec A eq}.\n\n  Local Hint Unfold Subset : core.\n  Local Hint Unfold Union : core.\n  Local Hint Unfold Intersection : core.\n  Local Hint Unfold Difference : core.\n  \n  Lemma append_Union : forall l r : list A, Union l r (l ∪ r).\n  Proof.\n    auto using in_app_iff.\n  Qed.\n\n  Lemma In_member : forall a l, a ∈ l -> member a l = true.\n  Proof.\n    intros a l; induction l as [| h t IHt];\n      intro H; simpl in *;\n        [ contradiction | destruct H as [H | H]]; subst;\n          dispatch_eqdec; auto.\n  Qed.\n\n  Local Hint Resolve In_member : core.\n  \n  Lemma member_In : forall a l, member a l = true -> a ∈ l.\n  Proof.\n    intros a l; induction l as [| h t IHt];\n      intro H; simpl in *; try discriminate;\n        dispatch_eqdec; auto.\n  Qed.\n\n  Local Hint Resolve member_In : core.\n\n  Lemma In_member_iff : forall a l,\n      member a l = true <-> In a l.\n  Proof.\n    intuition.\n  Qed.\n  \n  Lemma In_member_reflects : reflects (@In A) member.\n  Proof.\n    Local Hint Constructors reflect : core.\n    unfold reflects.\n    intros a l; destruct (member a l) eqn:Hmem; auto.\n    constructor. intros H. apply In_member in H.\n    rewrite H in Hmem. discriminate.\n  Defined.\n\n  Lemma Not_In_member_iff : forall a l,\n      member a l = false <-> a ∉ l.\n  Proof.\n    intros a l.\n    pose proof In_member_reflects a l as H.\n    inv H; intuition.\n  Qed.\n\n  Lemma member_app_or : forall a l r,\n      member a (l ∪ r) = member a l || member a r.\n  Proof.\n    intros a l r.\n    pose proof In_member_reflects a l as Hal; inv Hal; simpl.\n    - assert (HIn : In a (l ++ r)).\n      { rewrite in_app_iff; auto. }\n      auto using In_member.\n    - pose proof In_member_reflects a r as Har; inv Har.\n      + assert (HIn : In a (l ++ r)).\n        { rewrite in_app_iff; auto. }\n        auto using In_member.\n      + rewrite Not_In_member_iff.\n        rewrite in_app_iff. intuition.\n  Qed.\n\n  Lemma member_repeat : forall n a,\n      member a (repeat a n) =\n      match n with\n      | O => false\n      | S _ => true\n      end.\n  Proof.\n    intros [| n] a; simpl; auto. dispatch_eqdec; auto.\n  Qed.\n\n  Lemma intersect_Intersection : forall l r,\n      Intersection l r (l ∩ r).\n  Proof.\n    unfold Intersection; intro l;\n      induction l as [| h t IHt];\n      intros r a; simpl in *.\n    - intuition.\n    - split.\n      + pose proof (In_member_reflects h r) as H; inv H; simpl.\n        * intros [H | H]; subst; firstorder.\n        * firstorder.\n      + intros [[Hha | Hat] Har]; subst.\n        * rewrite In_member by auto; simpl; auto.\n        * rewrite in_app_iff. firstorder.\n  Qed.\n\n  Lemma difference_Difference : forall l r,\n      Difference l r (l ∖ r).\n  Proof.\n    unfold Difference; intro l;\n      induction l as [| h t IHt];\n      intros r a; simpl in *.\n    - intuition.\n    - split.\n      + pose proof In_member_reflects h r as H; inv H; simpl.\n        * intros H; apply IHt in H as [IH IHr]. intuition.\n        * intros [H | H]; subst; intuition;\n            apply IHt in H; intuition.\n      + intros [[Hha | Hat] Har]; subst.\n        * assert (member a r = false).\n          { pose proof In_member_reflects a r as H; inv H;\n              auto; contradiction. }\n          rewrite H. rewrite in_app_iff. intuition.\n        * rewrite in_app_iff. right.\n          apply IHt. intuition.\n  Qed.\n\n  Lemma diff_empty_r : forall l : list A,\n      l ∖ [] = l.\n  Proof.\n    intro l; induction l as [| h l]; simpl; auto.\n    rewrite IHl. reflexivity.\n  Qed.\n\n  Lemma remove_diff_cons : forall l r a,\n      l ∖ (a :: r) = remove a (l ∖ r).\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intros r a; simpl; auto.\n    destruct (member h r) eqn:Hmemhr;\n      repeat dispatch_eqdec; try rewrite IHl; reflexivity.\n  Qed.\n  \n  Lemma remove_diff : forall l r : list A,\n      fold_right remove l r = l ∖ r.\n  Proof.\n    intro l; induction l as [| a l IHl];\n      intro r; induction r as [| x r IHr]; simpl in *; auto.\n    - rewrite IHr. reflexivity.\n    - f_equal. rewrite diff_empty_r. reflexivity.\n    - dispatch_eqdec.\n      + rewrite IHr. rewrite remove_app.\n        destruct (member x r); simpl.\n        * rewrite remove_diff_cons. reflexivity.\n        * dispatch_eqdec.\n          rewrite remove_diff_cons. reflexivity.\n      + destruct (member a r) eqn:Hmemar; simpl in *.\n        * rewrite IHr. rewrite remove_diff_cons. reflexivity.\n        * rewrite IHr; simpl.\n          dispatch_eqdec; f_equal.\n          rewrite remove_diff_cons. reflexivity.\n  Qed.\n\n  Lemma Subset_difference : forall l r,\n      l ⊆ r -> l ∖ r = [].\n  Proof.\n    intros l r Hlr. apply Subset_Diff in Hlr.\n    unfold Difference in Hlr.\n    induction l as [| h l IHl]; simpl; auto.\n    pose proof In_member_reflects h r as Hhr; inv Hhr; simpl; firstorder.\n  Qed.\n\n  Corollary difference_same : forall l : list A,\n      l ∖ l = [].\n  Proof.\n    intros l. apply Subset_difference.\n    intuition.\n  Qed.\n\n  Corollary uniques_app_diff : forall l r: list A,\n      uniques (l ++ r) = uniques l ++ difference (uniques r) l.\n  Proof.\n    intros l r. rewrite uniques_app2.\n    f_equal. rewrite remove_diff. reflexivity.\n  Qed.\n\n  Corollary uniques_app_same : forall l : list A,\n      uniques (l ++ l) = uniques l.\n  Proof.\n    intros l. rewrite uniques_app_diff.\n    rewrite Subset_difference by auto using uniques_sound.\n    apply app_nil_r.\n  Qed.\n\n  Lemma difference_app_l : forall l1 l2 r : list A,\n      difference (l1 ∪ l2) r = difference l1 r ∪ difference l2 r.\n  Proof.\n    intro l1; induction l1 as [| h1 l1 IHl1];\n      intros l2 r; simpl; auto.\n    rewrite IHl1. apply app_assoc.\n  Qed.\n\n  Lemma difference_app_r_comm : forall l r1 r2 : list A,\n      difference l (r1 ∪ r2) = difference l (r2 ∪ r1).\n  Proof.\n    intro l; induction l as [| h l IHl]; intros r1 r2; simpl; auto.\n    repeat rewrite member_app_or.\n    rewrite orb_comm. rewrite IHl. reflexivity.\n  Qed.\n\n  Lemma difference_app_r_assoc : forall l r1 r2 : list A,\n      l ∖ r1 ∖ r2 = l ∖ (r1 ∪ r2).\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intros r1 r2; simpl; auto.\n    rewrite member_app_or.\n    destruct (member h r1) eqn:Hmemhr1; simpl; auto.\n    rewrite IHl. reflexivity.\n  Qed.\n\n  Lemma diff_uniques : forall l r : list A, l ∖ uniques r = l ∖ r.\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intro r; simpl in *; auto.\n    pose proof In_member_reflects h r as Hhr;\n      inversion Hhr as [Hin Hmem | Hin Hmem]; clear Hhr; simpl.\n    - rewrite <- uniques_iff in Hin.\n      rewrite <- In_member_iff in Hin.\n      rewrite Hin; simpl; auto.\n    - rewrite <- uniques_iff in Hin.\n      rewrite <- Not_In_member_iff in Hin.\n      rewrite Hin; simpl; f_equal; auto.\n  Qed.\n  \n  Local Hint Resolve Permutation_app_comm : core.\n  \n  Lemma length_uniques_app : forall l r : list A,\n      length (uniques (l ++ r)) = length (uniques (r ++ l)).\n  Proof.\n    intros l r.\n    assert (Permutation (uniques (l ++ r)) (uniques (r ++ l)))\n      by eauto using uniques_perm.\n    auto using Permutation_length.\n  Qed.\n  \n  Local Hint Resolve Union_Subset_l : core.\n  Local Hint Resolve Union_Subset_r : core.\n  Local Hint Resolve Inter_Subset_l : core.\n  Local Hint Resolve Inter_Subset_r : core.\n  Local Hint Resolve Diff_Subset : core.\n  Local Hint Resolve append_Union : core.\n  Local Hint Resolve intersect_Intersection : core.\n  Local Hint Resolve difference_Difference : core.\n  \n  Lemma Subset_union_l : forall l r : list A, l ⊆ l ∪ r.\n  Proof.\n    eauto.\n  Qed.\n\n  Lemma Subset_union_r : forall l r : list A, r ⊆ l ∪ r.\n  Proof.\n    eauto.\n  Qed.\n\n  Lemma Subset_inter_l : forall l r, l ∩ r ⊆ l.\n  Proof.\n    eauto.\n  Qed.\n\n  Lemma Subset_inter_r : forall l r, l ∩ r ⊆ r.\n  Proof.\n    eauto.\n  Qed.\n\n  Lemma Subset_diff : forall l r, l ∖ r ⊆ l.\n  Proof.\n    eauto.\n  Qed.\n\n  Hint Rewrite in_app_iff : core.\n\n  Lemma Subset_l_union : forall l r : list A,\n      l ⊆ r -> forall s, l ⊆ r ∪ s.\n  Proof.\n    unfold Subset; intros.\n    autorewrite with core in *; intuition.\n  Qed.\n\n  Lemma Subset_r_union : forall l r : list A,\n      l ⊆ r -> forall s, l ⊆ s ∪ r.\n  Proof.\n    unfold Subset; intros.\n    autorewrite with core in *; intuition.\n  Qed.\n  \n  Lemma Subset_union_distr_l : forall l r : list A,\n      l ⊆ r -> forall s, s ∪ l ⊆ s ∪ r.\n  Proof.\n    unfold Subset; intros.\n    autorewrite with core in *; intuition.\n  Qed.\n\n  Lemma Subset_union_distr_r : forall l r : list A,\n      l ⊆ r -> forall s, l ∪ s ⊆ r ∪ s.\n  Proof.\n    unfold Subset; intros.\n    autorewrite with core in *; intuition.\n  Qed.\n\n  Lemma Subset_union : forall l1 l2 r1 r2 : list A,\n      l1 ⊆ r1 -> l2 ⊆ r2 -> l1 ∪ l2 ⊆ r1 ∪ r2.\n  Proof.\n    unfold \"⊆\"; intros l1 l2 r1 r2 H1 H2 a.\n    autorewrite with core; firstorder.\n  Qed.\n\n  Lemma Subset_extra_l : forall l r : list A,\n      l ∪ l ⊆ r <-> l ⊆ r.\n  Proof.\n    unfold Subset; intros l r; split;\n      intros H a; specialize H with a;\n        autorewrite with core in *; firstorder.\n  Qed.\n\n  Lemma Subset_extra_r : forall l r : list A,\n      l ⊆ r ∪ r <-> l ⊆ r.\n  Proof.\n    unfold Subset; intros l r; split;\n      intros H a; specialize H with a;\n        autorewrite with core in *; firstorder.\n  Qed.\n  \n  Lemma union_perm : forall l r : list A,\n      Permutation (l ∪ r) (r ∪ l).\n  Proof.\n    auto using Permutation_app_comm.\n  Qed.\n  \n  Lemma Inter_nil : forall l r : list A,\n      Intersection l r [] -> l ∩ r = [].\n  Proof.\n    unfold Intersection.\n    intro l; induction l as [| a l IHl];\n      intros r H; simpl in *; eauto.\n    pose proof (In_member_reflects a r) as Har;\n      inv Har; simpl in *; firstorder.\n  Qed.\n\n  Lemma inter_union_distr : forall l r s,\n      l ∩ (r ∪ s) = l ∩ r ∪ l ∩ s.\n  Proof.\n    intros l;\n      induction l as [| h l IHl];\n      intros r s; simpl; auto.\n    rewrite member_app_or.\n    pose proof In_member_reflects h r as Hhr;\n      pose proof In_member_reflects h s as Hhs;\n      inv Hhr; inv Hhs; simpl; f_equal; auto.\n  Abort.\n\n  Lemma uniques_perm_app : forall l l' s,\n      Permutation l (l' ++ s) ->\n      forall r r',\n        Permutation r (r' ++ s) ->\n        Permutation (uniques (l ++ r)) (uniques (l' ++ r' ++ s)).\n  Proof.\n    intros l l' s Hll' r r' Hrr'.\n    assert (Happ : Permutation (l ++ r) ((l' ++ s) ++ (r' ++ s)))\n      by auto using Permutation_app.\n    rewrite <- app_assoc in Happ.\n    assert (Happ': Permutation (l ++ r) (l' ++ r' ++ s ++ s)).\n    { apply perm_trans with (l' ++ s ++ r' ++ s); auto.\n      apply Permutation_app_head.\n      apply Permutation_app_swap_app. }\n    apply uniques_perm in Happ'.\n    rewrite (uniques_app l') in Happ'.\n    rewrite (uniques_app r') in Happ'.\n    rewrite uniques_app_same in Happ'.\n    rewrite <- (uniques_app r') in Happ'.\n    rewrite <- (uniques_app l') in Happ'.\n    assumption.\n  Qed.\n\n  Lemma uniques_uniques_perm_app : forall l l' s,\n      Permutation (uniques l) (uniques (l' ++ s)) ->\n      forall r r',\n        Permutation (uniques r) (uniques (r' ++ s)) ->\n        Permutation (uniques (l ++ r)) (uniques (l' ++ r' ++ s)).\n  Proof.\n    intros l l' s Hll' r r' Hrr'.\n    assert (Happ : Permutation\n                     (uniques l ++ uniques r)\n                     (uniques (l' ++ s) ++ uniques (r' ++ s)))\n      by auto using Permutation_app.\n    apply uniques_perm in Happ.\n    repeat rewrite <- uniques_app in Happ.\n    rewrite <- app_assoc in Happ.\n    assert (Happ' : Permutation\n                      (uniques (l ++ r))\n                      (uniques (l' ++ r' ++ s ++ s))).\n    { apply perm_trans with (uniques (l' ++ s ++ r' ++ s)); auto.\n      apply uniques_perm. apply Permutation_app_head.\n      apply Permutation_app_swap_app. }\n    rewrite (uniques_app l') in Happ'.\n    rewrite (uniques_app r') in Happ'.\n    rewrite uniques_app_same in Happ'.\n    rewrite <- (uniques_app r') in Happ'.\n    rewrite <- (uniques_app l') in Happ'.\n    assumption.\n  Qed.\n\n  Lemma uniques_uniques_perm_app3 : forall l l' m m' n n' o,\n      Permutation (uniques l) (uniques (l' ++ o)) ->\n      Permutation (uniques m) (uniques (m' ++ o)) ->\n      Permutation (uniques n) (uniques (n' ++ o)) ->\n      Permutation (uniques (l ++ m ++ n)) (uniques (l' ++ m' ++ n' ++ o)).\n  Proof.\n    intros l l' m m' n n' o Hl Hm Hn.\n    pose proof uniques_uniques_perm_app _ _ _ Hm _ _ Hn  as Hmn.\n    rewrite app_assoc in Hmn.\n    pose proof uniques_uniques_perm_app _ _ _ Hl _ _ Hmn as Hml.\n    repeat rewrite <- app_assoc in Hml.\n    assumption.\n  Qed.\nEnd Sets.\n\nSection NatSet.\n  Open Scope set_scope.\n  Local Hint Constructors Forall : core.\n\n  Lemma list_max_ge : forall l : list nat,\n      Forall (fun n => n <= list_max l) l.\n  Proof.\n    intro l; induction l as [| h t IHt];\n      simpl; constructor; try lia.\n    apply Forall_forall.\n    intros n HIn.\n    apply Forall_forall\n      with (x:=n) in IHt; try assumption. lia.\n  Qed.\n\n  Lemma list_max_ge_in : forall l n,\n      n ∈ l -> n <= list_max l.\n  Proof.\n    intro l. rewrite <- Forall_forall.\n    exact (list_max_ge l).\n  Qed.\n  \n  Lemma list_max_succ : forall l : list nat,\n    Forall (fun n => n < 1 + list_max l) l.\n  Proof.\n    intros l. apply Forall_forall.\n    pose proof list_max_ge l as H.\n    intros n HIn.\n    apply Forall_forall\n      with (x:=n) in H; try assumption. lia.\n  Qed.\n\n  Lemma list_max_succ_not_in : forall l : list nat,\n      1 + list_max l ∉ l.\n  Proof.\n    intros l HIn.\n    pose proof list_max_succ l as H.\n    pose proof Forall_forall\n         (fun n => n < 1 + list_max l) l as [HFF _].\n    pose proof HFF H as H'.\n    apply H' in HIn. lia.\n  Qed.\n\n  Lemma Subset_list_max : forall l r,\n      l ⊆ r -> list_max l <= list_max r.\n  Proof.\n    unfold \"⊆\".\n    intro l; induction l as [| a l IHl];\n      intros r HS; simpl in *; try lia.\n    destruct (le_gt_dec a (list_max l)) as [Hal | Hal].\n    - rewrite max_r by lia; eauto.\n    - rewrite max_l by lia.\n      assert (Har: In a r) by eauto.\n      auto using list_max_ge_in.\n  Qed.\nEnd NatSet.\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/Sets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.650707797367646}}
{"text": "Require Import Spreadable.\nRequire Import Tuple.\nRequire Import Lia.\n\nOpen Scope list_scope.\n\n(** * The specification for Linked Nested Data Types **)\nInductive LNDT (F : TT) (A : Type) : Type :=\n | empty : LNDT F A\n | nest : A -> LNDT F (F A) -> LNDT F A.\n\n(** * Some examples *)\n\nEval compute in (LNDT list).\n\nLemma ex1 : LNDT list nat.\nProof.\napply (nest list nat 1).\napply (nest list (list nat) (cons 1 (cons 2 (cons 3 nil)))).\nconstructor.\nDefined.\n\nDefinition nested1 : LNDT list nat :=\nnest list nat 1\n  (nest list (list nat)\n     (1 :: 2 :: 3 :: nil)\n     (empty list\n        (list (list nat)))).\n(* Proof. \napply (nest list nat 1).\napply \n  (nest list (list nat)\n     (1 :: 2 :: 3 :: nil)).\nconstructor.\nDefined.\n*)\n\n\nDefinition nested2 : LNDT list nat.\nProof. \napply (nest list nat 1).\napply \n  (nest list (list nat)\n     (1 :: 2 :: 3 :: nil)).\napply (nest list (list (list nat))\n     ((1::2::nil)::(2::nil) :: nil)).\napply empty.\nDefined.\n(*\nnest list nat 1\n  (nesOpen Scope list_scope.t list (list nat)\n     (1 :: 2 :: 3 :: nil)\n     (nest list\n        (list (list nat))\n        ((1 :: 2 :: nil)\n         :: (2 :: nil)\n            :: nil)\n        (empty list\n           (list\n              (list\n                 (list nat))))))\n                 \nou plus lisiblement sans les infos de type\n(nest 1\n  (nest [1 ; 2; 3]\n    (nest [[1;2] ; [2]]\n      empty)))\n*)\n\nDefinition nested3 : LNDT (Tuple 2) nat.\nProof.\napply (nest (Tuple 2) nat\n      1).\napply \n  (nest (Tuple 2) (Tuple 2 nat)\n     (1, (2, 3))).\napply (nest (Tuple 2) (Tuple 2 (Tuple 2 nat))\n     ( (1, (1, 1)), ( (2, (2, 2)), (3, (3, 3))))).\napply empty.\nDefined.\n\nPrint nested3.\n\n(** * Induction principle over nested data types *)\nCheck LNDT_ind.\n\n(** * A very simple property on equality *)\nLemma eq_nest : forall {F : TT} {A : Type} {x y} {l m : LNDT F (F A)},\n    x = y -> l = m -> (nest F A x l) = (nest F A y m).\nProof.\n  intros F A x y l m Heq_A Heq_Nested.\n  rewrite Heq_A, Heq_Nested. reflexivity.\nDefined.\n\n(** * All spread-able elements can indeed be spread from F to (LNDT F) *)\n\n(** ** Map function *)\nFixpoint lndt_map {F : TT} (map : Map F) (A B : Type) (f : A -> B) (t : LNDT F A) : LNDT F B :=\n match t with\n  |empty _ _     => empty _ _\n  |nest  _ _ x e => nest F B (f x) (lndt_map map (F A) (F B) (map A B f) e)\n end.\n\nDefinition ff (n : nat) := match n with\n  0 => false\n| _ => true\nend.\n\nLemma map_lndt_id : forall {F : TT} (map : Map F) (p : MapId map), MapId(lndt_map map).\nProof.\nunfold MapId, Map. intros.  \ngeneralize dependent f. revert x.\ninduction x; simpl; intros; auto.\nrewrite H. rewrite IHx with (f := map A A f).\n+ reflexivity.\n+ intros. rewrite p. reflexivity. exact H.\nQed.\n\n\n(** ** Congruence function *)\nRequire Import FunInd.\nFunctional Scheme lndt_map_ind := Induction for lndt_map Sort Prop.\n\nLemma lndt_cng_map : forall {F : TT} {map : Map F}\n  (cgMap : MapCongruence map), MapCongruence (lndt_map map).\nProof.\n  unfold MapCongruence, Map. intros.\n  functional induction (lndt_map map A B f x).\n  + auto.\n  + simpl; rewrite H. rewrite IHl with (g:= map A B g). reflexivity. intro ; apply cgMap; assumption. \nDefined.\n\n(** ** Composition function *)\nLemma lndt_cmp_map : forall {F : TT} {map : Map F} (cgMap : MapCongruence map)\n  (cpMap : MapComposition map), MapComposition (lndt_map map).\nProof.\nunfold MapComposition, MapCongruence. \nintros until x. revert f g. revert B C. revert x.\ninduction x.\n+ reflexivity.\n+ intros; simpl.\n  rewrite <- (IHx _ _ (map A B f) (map B C g)).\n  rewrite lndt_cng_map with \n    (f := (map A C (fun x0 : A => g (f x0))))\n    (g:= (fun x0 => map B C g (map A B f x0))) ; auto.\nQed.\n\nDefinition lndt_mapable {F : TT} (mp : MapAble F) : MapAble (LNDT F) :=\n  mkMap (LNDT F)\n        (lndt_map (map F mp))\n        (lndt_cng_map (map_congru F mp))\n        (lndt_cmp_map (map_congru F mp) (map_compo F mp)).\n\n(** ** Fold functions *)\nFixpoint lndt_foldr (F : TT) (foldr : Fold F) A B (f : B -> A -> B) (b0 : B) (t : LNDT F A) :=\nmatch t with\n |empty _ _ => b0\n |nest _ _ x v  => f (lndt_foldr _ foldr _ _ (foldr _ _ f) b0 v) x\nend.\n\nDefinition foldlist  : Fold list  := fun A B f b l => @List.fold_left B A f l b.\n\nEval compute in (lndt_foldr _ foldlist nat nat Nat.add 0 nested1).\n(* = 7 : nat *)\n\nEval compute in (lndt_foldr _ foldlist nat nat Nat.add 0 nested2).\n(* = 12 : nat *)\n\nEval compute in (lndt_foldr _ (tuple_foldr 2) nat nat Nat.add 0 nested3).\n(* = 25 : nat *)\n\nDefinition lndt_sum F (foldr : Fold F) (t : LNDT F nat) :=\nlndt_foldr _ foldr nat nat Nat.add 0 t.\n\nEval compute in (lndt_sum (Tuple 2) (tuple_foldr 2) nested3).\n(* = 25 : nat *)\n\nFixpoint lndt_foldl {F : TT} (foldl : Fold F) A B (f : B -> A -> B) (b0 : B) (t : LNDT F A) :=\nmatch t with\n |empty _ _     => b0\n |nest  _ _ x e => lndt_foldl foldl _ _ (foldl _ _ f) (f b0 x) e\nend.\n\nDefinition lndt_foldable {F : TT} (fp : FoldAble F) : FoldAble (LNDT F) :=\n  mkFold (LNDT F)\n        (lndt_foldl (foldl F fp))\n        (lndt_foldr F (foldr F fp)).\n\n(** ** Size function *)\nDefinition lndt_size F fold A := lndt_foldr F fold A nat (fun x => fun y => S x) 0.\n\nEval compute in (lndt_size list foldlist nat nested2).\n(* = 7 : nat *)\n\nEval compute in (lndt_size (Tuple 2) (tuple_foldr 2) nat nested3).\n(* = 13 : nat *)\n\n(** ** Any predicate transformer *)\nFixpoint lndt_any {F : TT} (T : TransPred F) A (P : A -> Prop) (t : LNDT F A) :=\nmatch t with\n |empty _ _ => False\n |nest _ _ x e  => (P x) \\/ (lndt_any T _ (T _ P) e)\nend.\n\nLemma lndt_any_ex1 : lndt_any (tuple_any 2) nat (fun x => x > 2) nested3.\nProof. compute. lia. Qed.\n\nLemma lndt_any_ex2 : not(lndt_any (tuple_any 2) nat (fun x => x > 3) nested3).\nProof. compute. lia. Qed.\n\nLemma lndt_dec_any : forall {F : TT} (T : TransPred F),\n    TransDec T -> TransDec (lndt_any T).\nProof.\nunfold TransDec, Dec, TransPred. intros F T Hyp A P HdecA x.\ninduction x.\n  + intuition.\n  + simpl. specialize (Hyp A P).\n    specialize (IHx (T A P) (Hyp HdecA)). destruct IHx.\n     { tauto. }\n     { destruct (HdecA a).\n        - tauto.\n        - right. intro Hfalse. destruct Hfalse; contradiction. }\nDefined.\n\n(** ** All predicate transformer *)\nFixpoint lndt_all {F : TT} (T : TransPred F) A (P : A -> Prop) (t : LNDT F A) :=\nmatch t with\n |empty _ _ => True\n |nest _ _ x e  => (P x) /\\ (lndt_all T _ (T _ P) e)\nend.\n\nLemma lndt_all_ex1:\n not(lndt_all (tuple_all 2) nat (fun x => x > 2) nested3).\nProof. compute. lia. Qed.\n\nLemma lndt_all_ex2:\n lndt_any (tuple_any 2) nat (fun x => x < 4) nested3.\nProof. compute. lia. Qed.\n\nLemma lndt_dec_all : forall {F : TT} (T : TransPred F),\n    TransDec T -> TransDec (lndt_all T).\nProof.\nunfold TransDec, Dec, TransPred. intros F T Hyp A P HdecA x.\ninduction x.\n  + simpl. tauto.\n  + simpl. specialize (Hyp A P).\n    specialize (IHx (T A P) (Hyp HdecA)). destruct IHx.\n     { destruct (HdecA a).\n        - tauto.\n        - right. intro Hfalse. tauto. }\n     { right. intro Hfalse. tauto.    }\nDefined.\n\nDefinition lndt_any_all_able {F : TT} (aa : AnyAllAble F) : AnyAllAble (LNDT F) :=\n  mkAnyAll (LNDT F)\n           (lndt_any (any F aa))\n           (lndt_dec_any _ (dec_any F aa))\n           (lndt_all (all F aa))\n           (lndt_dec_all _ (dec_all F aa)).\n\n(** ** Decidability of equality *)\nLemma lndt_dec_eq {F : TT} : DecEq F -> DecEq (LNDT F).\nProof.\nunfold DecEq, Decidable. intros Hyp A HdecA.\ninduction x ; destruct y.\n + intuition.\n + right ; intro H ; inversion H.\n + right ; intro H ; inversion H.\n + specialize (Hyp A HdecA).\n   specialize (IHx Hyp).  elim (HdecA a a0) ; intro HypeqA.\n    - subst.  elim (IHx y) ; intro Hypeqy.\n       * left; subst; auto.\n       * right ; intro Hpb. inversion Hpb; contradiction.\n    - right; intro Hpb ; inversion Hpb; contradiction.\nDefined.\n\nDefinition lndt_eq_able {F : TT} (eq : EqAble F) : EqAble (LNDT F) :=\n  mkEq (LNDT F) (lndt_dec_eq (dec_eq F eq)).\n\n(** * Nested is spreadable. *)\nDefinition lndt_spreadable {F : TT} (sp : SpreadAble F) : SpreadAble (LNDT F) :=\n  mkSpread (LNDT F)\n    (lndt_foldable (fold_able F sp))\n    (lndt_mapable (map_able F sp))\n    (lndt_any_all_able (any_all_able F sp))\n    (lndt_eq_able (eq_able F sp)).\n\nDefinition size_lndt {F : TT} (sp : SpreadAble F) A : LNDT F A -> nat :=\n (lndt_foldr _ (foldr _ (fold_able _ sp)) A nat (fun (x : nat) (_ : A) => x + 1) 0).\n \nEval compute in (size_lndt (tuple_spreadable 2) _ nested3).\n(* = 13 : nat *)\n\n(* Random generation / PBT *)\n\nFrom QuickChick Require Import QuickChick Tactics.\n\nModule DoNotation.\nNotation \"'do!' X <- A ; B\" :=\n  (bindGen A (fun X => B))\n    (at level 200, X ident, A at level 100, B at level 200).\nEnd DoNotation.\n\nImport DoNotation.\n\nFixpoint lndt_gen_sized {F : TT} (gen_F : Gensized F )\n ( A : Type) (g: nat -> G A) (size : nat) : G (LNDT F A):=\nmatch size with\n| 0 => returnGen (empty F _)\n| S size' => \n freq_ (returnGen (empty F _ ))\n  ((1,returnGen (empty F _)) ::\n   (1,do! p0 <- g size' ;\n      do! p1 <- lndt_gen_sized gen_F (F A) (gen_F _  g) size';\n      returnGen (nest _ _ p0 p1)):: nil)\n end.\n \n \nOpen Scope string.\n\n\nFixpoint lndt_print {F : TT} {show_F : Printable F}\n{ A : Type} `{sh : Show A} ( t : LNDT F A):=\n  match t with\n    | empty _ _ => \"empty\"\n    | nest _ _ x e => \"(\" ++ show x ++ \", \" ++ (@lndt_print F show_F (F A) (show_F A sh)  e) ++ \")\"\n  end.\n\n", "meta": {"author": "mmontin", "repo": "libndt", "sha": "b16c7916640cbbeb6e3d4653386753925d29118d", "save_path": "github-repos/coq/mmontin-libndt", "path": "github-repos/coq/mmontin-libndt/libndt-b16c7916640cbbeb6e3d4653386753925d29118d/Coq_lib/LNDT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.6507077955760845}}
{"text": "Require Import Setoid.\nRequire Import Morphisms.\nRequire Import Coq.Program.Basics.\nRequire Import NArith.\nRequire Import List.\nImport ListNotations.\nOpen Scope list.\nRequire Import Lia.\n\nUnset Printing Records.\n\nFrom Ordinal Require Import Defs.\nFrom Ordinal Require Import Operators.\nFrom Ordinal Require Import Arith.\nFrom Ordinal Require Import Cantor.\nFrom Ordinal Require Import Fixpoints.\nFrom Ordinal Require Import Reflection.\nFrom Ordinal Require Import VeblenDefs.\nFrom Ordinal Require Import VeblenCon.\n\nOpen Scope ord_scope.\n\nLemma onePlus_complete x : complete x -> complete (1 + x).\nProof.\n  intros; apply addOrd_complete; auto.\n  apply succ_complete; apply zero_complete.\nQed.\n\n\nLemma onePlus_normal : normal_function (addOrd 1).\nProof.\n  constructor.\n  - intros; apply addOrd_monotone; auto with ord.\n  - intros; apply addOrd_increasing; auto.\n  - red; intros; apply addOrd_continuous; auto.\n  - intros; apply addOrd_complete; auto.\n    apply succ_complete. apply zero_complete.\n  - intros.\n    rewrite <- addOrd_le1.\n    apply succ_lt.\nQed.\n\nLemma veblen_onePlus_complete a x :\n  complete a -> complete x -> complete (veblen (addOrd 1) a x).\nProof.\n  intros; apply veblen_complete; auto.\n  apply onePlus_normal.\n  apply onePlus_complete.\nQed.\n\nLemma onePlus_nonzero : forall x, 0 < 1+x.\nProof.\n  intros.\n  rewrite <- addOrd_le1. apply succ_lt.\nQed.\n\nTheorem onePlus_least f :\n  (forall x y, x < y -> f x < f y) ->\n  (forall x, 0 < f x) ->\n  forall x, 1+x <= f x.\nProof.\n  intros.\n  induction x using ordinal_induction.\n  rewrite addOrd_unfold.\n  apply lub_least.\n  apply succ_least; auto.\n  apply sup_least. intro i.\n  apply succ_least.\n  rewrite (H1 (x i)).\n  apply H; auto.\n  apply index_lt.\n  apply index_lt.\nQed.\n\nTheorem onePlus_least_normal f :\n    normal_function f ->\n    forall x, complete x -> 1+x <= f x.\nProof.\n  intros.\n  induction x using ordinal_induction.\n  rewrite addOrd_unfold.\n  apply lub_least.\n  apply succ_least.\n  apply normal_nonzero; auto.\n  apply sup_least. intro i.\n  apply succ_least.\n  rewrite (H1 (x i)).\n  apply normal_increasing; auto.\n  apply index_lt.\n  apply index_lt.\n  apply complete_subord. auto.\nQed.\n\nLemma onePlus_finite : forall n, natOrdSize n < 1 + natOrdSize n.\nProof.\n  induction n; simpl.\n  rewrite addOrd_zero_r.\n  apply succ_lt.\n  rewrite addOrd_succ.\n  apply succ_trans.\n  apply succ_least.\n  auto.\nQed.\n\nLemma onePlus_veblen f x y :\n  normal_function f ->\n  x > 0 ->\n  complete x ->\n  complete y ->\n  1 + veblen f x y ≈ veblen f x y.\nProof.\n  split; intros.\n  - rewrite <- (veblen_fixpoints f H 0 x y) at 2; auto.\n    rewrite veblen_zero.\n    apply onePlus_least_normal; auto.\n    apply veblen_complete; auto.\n    apply normal_complete; auto.\n    apply zero_complete.\n  - apply addOrd_le2.\nQed.\n\nLemma finite_veblen f x y n :\n  normal_function f ->\n  x > 0 ->\n  complete x ->\n  complete y ->\n  natOrdSize n + veblen f x y ≈ veblen f x y.\nProof.\n  intros. induction n; simpl.\n  - rewrite addOrd_zero_l. reflexivity.\n  - transitivity\n      ((natOrdSize (1+n)%nat + veblen f x y)).\n    rewrite natOrdSize_add.\n    simpl.\n    rewrite addOrd_succ. rewrite addOrd_zero_r.\n    reflexivity.\n    rewrite natOrdSize_add.\n    rewrite <- addOrd_assoc.\n    simpl.\n    rewrite onePlus_veblen; auto.\nQed.\n\nLemma finite_veblen_lt f x y n :\n  normal_function f ->\n  x > 0 ->\n  complete x ->\n  complete y ->\n  natOrdSize n < veblen f x y.\nProof.\n  intros.\n  apply ord_lt_le_trans with (natOrdSize n + 1).\n  rewrite addOrd_succ.\n  apply succ_trans. apply addOrd_zero_r.\n  rewrite <- (finite_veblen f x y n); auto.\n  apply addOrd_monotone; auto with ord.\n  apply succ_least. apply veblen_nonzero; auto.\nQed.\n\nLemma finite_veblen_le f x y n :\n  normal_function f ->\n  x > 0 ->\n  complete x ->\n  complete y ->\n  natOrdSize n <= veblen f x y.\nProof.\n  intros.\n  rewrite <- (finite_veblen f x y n); auto.\n  apply addOrd_le1.\nQed.\n\n\nTheorem veblen_onePlus :\n  forall a x, complete a -> complete x -> veblen (addOrd 1) a x ≈ expOrd ω a + x.\nProof.\n  induction a as [A f Ha]. induction x as [X g Hx].\n  split.\n  - rewrite veblen_unroll.\n    apply lub_least.\n    + apply addOrd_monotone; auto with ord.\n      apply succ_least.\n      apply expOrd_nonzero.\n    + unfold boundedSup.\n      apply sup_least; intro i.\n      apply fixOrd_least.\n      * intros; apply veblen_monotone; auto.\n        intros; apply addOrd_monotone; auto with ord.\n      * rewrite ord_le_unfold. simpl ordSize. intro a.\n        simpl in a. rewrite Hx; auto.\n        apply addOrd_increasing.\n        apply (index_lt (ord X g) a).\n        apply H0.\n      * rewrite (Ha i).\n        rewrite addOrd_assoc.\n        apply addOrd_monotone; auto with ord.\n        apply expOrd_add_collapse; auto.\n        apply (index_lt (ord A f)).\n        apply H.\n        apply addOrd_complete; auto.\n        apply expOrd_complete; auto.\n        apply (index_lt _ 0%nat).\n        apply omega_complete.\n\n  - unfold addOrd at 1.\n    rewrite foldOrd_unfold.\n    apply lub_least.\n    + rewrite expOrd_unfold.\n      apply lub_least.\n      { apply succ_least.\n        apply veblen_nonzero.\n        apply onePlus_normal. }\n      apply sup_least; intro i.\n      rewrite veblen_unroll.\n      rewrite <- lub_le2.\n      unfold boundedSup.\n      rewrite <- (sup_le _ _ i).\n      unfold fixOrd.\n      rewrite mulOrd_unfold.\n      apply sup_least; intro n.\n      rewrite <- (sup_le _ _ (S n)).\n      transitivity (expOrd ω (f i) * (S n : ω)).\n      simpl.\n      rewrite mulOrd_succ.\n      reflexivity.\n      generalize (S n). clear n.\n      induction n.\n      * simpl. rewrite mulOrd_zero_r. auto with ord.\n      * simpl.\n        rewrite mulOrd_succ.\n        etransitivity.\n        2: { apply veblen_monotone.\n             intros; apply addOrd_monotone; auto with ord.\n             apply IHn. }\n        rewrite Ha.\n        ** clear.\n           unfold sz. simpl ordSize.\n           induction n; simpl natOrdSize.\n           rewrite mulOrd_zero_r.\n           rewrite addOrd_zero_l.\n           rewrite addOrd_zero_r.\n           reflexivity.\n           rewrite mulOrd_succ.\n           rewrite addOrd_assoc.\n           rewrite IHn.\n           reflexivity.\n        ** apply H.\n        ** apply mulOrd_complete.\n           apply expOrd_complete.\n           apply (index_lt _ 0%nat).\n           apply omega_complete.\n           apply H.\n           apply natOrdSize_complete.\n\n    + apply sup_least; intro i. simpl ordSize.\n      transitivity (succOrd (expOrd ω (ord A f) + g i)).\n      reflexivity.\n      rewrite <- Hx; auto.\n      apply succ_least.\n      destruct (complete_zeroDec (ord A f)); auto.\n      * eapply ord_le_lt_trans.\n        apply veblen_monotone_first.\n        intros; apply addOrd_monotone; auto with ord.\n        apply H1.\n        eapply ord_lt_le_trans.\n        apply veblen_increasing0.\n        apply onePlus_normal. apply H0.\n        apply (index_lt (ord X g) i).\n        apply veblen_monotone_first; auto with ord.\n        intros; apply addOrd_monotone; auto with ord.\n      * apply veblen_increasing_nonzero; auto.\n        apply onePlus_normal.\n        apply (index_lt (ord X g) i).\n      * apply H0.\nQed.\n\nLemma veblen_fixpoint_zero f a x :\n  normal_function f ->\n  0 < a ->\n  complete a ->\n  complete x ->\n  f (veblen f a x) <= veblen f a x.\nProof.\n  intros.\n  transitivity (veblen f 0 (veblen f a x)).\n  rewrite veblen_zero. reflexivity.\n  apply veblen_fixpoints; auto.\n  apply zero_complete.\nQed.\n\nLemma veblen_monotone_full f g a x b y :\n  (forall x y, x <= y -> g x <= g y) ->\n  (forall x, f x <= g x) ->\n  a <= b ->\n  x <= y ->\n  veblen f a x <= veblen g b y.\nProof.\n  revert y a x.\n  induction b as [b Hb] using ordinal_induction.\n  induction y as [y Hy] using ordinal_induction.\n\n  intros.\n  rewrite (veblen_unroll f a x).\n  rewrite (veblen_unroll g b y).\n  apply lub_least.\n  - rewrite <- lub_le1.\n    transitivity (g x); auto.\n  - destruct a as [A r]. simpl.\n    apply sup_least; intro ai.\n    rewrite <- lub_le2.\n    destruct b as [B s]; simpl.\n    destruct (ord_le_subord (ord A r) (ord B s) H1 ai) as [bi ?].\n    rewrite <- (sup_le _ _ bi).\n    unfold fixOrd. apply sup_ord_le_morphism.\n    intro m.\n    induction m; simpl.\n    + rewrite ord_le_unfold; simpl; intro xi.\n      destruct (ord_le_subord x y H2 xi) as [yi ?].\n      rewrite ord_lt_unfold. simpl. exists yi.\n      apply Hy; auto with ord.\n    + apply Hb; auto with ord.\nQed.\n\n\nLemma veblen_monotone_func f g :\n  normal_function f ->\n  normal_function g ->\n  (forall i, complete i -> f i <= g i) ->\n  forall a x, complete a -> complete x ->\n    veblen f a x <= veblen g a x.\nProof.\n  intros Hf Hg H.\n  induction a as [A h Ha].\n  induction x as [X k Hx].\n  intros.\n  do 2 rewrite veblen_unroll.\n  apply lub_least.\n  - rewrite <- lub_le1. apply H; auto.\n  - simpl.\n    apply sup_least; intro i.\n    rewrite <- lub_le2.\n    rewrite <- (sup_le _ _ i).\n    unfold fixOrd.\n    apply sup_least; intro n.\n    rewrite <- (sup_le _ _ n).\n    transitivity (iter_f (veblen g (h i)) (limOrd (fun x0 : X => veblen f (ord A h) (k x0))) n).\n    { induction n; simpl iter_f.\n      reflexivity.\n      transitivity\n        (veblen g (h i)\n                (iter_f (veblen f (h i)) (limOrd (fun x : X => veblen f (ord A h) (k x))) n)).\n      apply (Ha i). apply H0.\n      apply iter_f_complete.\n      apply lim_complete; auto.\n      intros; apply veblen_complete; auto.\n      apply normal_complete; auto.\n      apply H1.\n      { red; intros. destruct (complete_directed (ord X k) H1 a1 a2) as [a' [??]].\n        exists a'; split.\n        apply veblen_monotone; auto.\n        apply normal_monotone; auto.\n        apply veblen_monotone; auto.\n        apply normal_monotone; auto. }\n      apply H1.\n      intros; apply veblen_complete; auto.\n      apply normal_complete; auto.\n      apply H0.\n      apply veblen_monotone; auto.\n      apply normal_monotone; auto. }\n\n    apply iter_f_monotone.\n    intros; apply veblen_monotone; auto.\n    apply normal_monotone; auto.\n    rewrite ord_le_unfold; intro q. simpl.\n    rewrite ord_lt_unfold; exists q; simpl.\n    apply Hx; auto.\n    apply H1.\nQed.\n\nAdd Parametric Morphism : (veblen (addOrd 1))\n    with signature ord_le ==> ord_le ==> ord_le\n      as veblen_onePlus_le_mor.\nProof.\n  intros.\n  apply veblen_le_mor; auto.\n  intros; apply addOrd_monotone; auto with ord.\nQed.\n\nAdd Parametric Morphism : (veblen (addOrd 1))\n    with signature ord_eq ==> ord_eq ==> ord_eq\n      as veblen_onePlus_eq_mor.\nProof.\n  intros.\n  apply veblen_eq_mor; auto.\n  intros; apply addOrd_monotone; auto with ord.\nQed.\n\nAdd Parametric Morphism : (veblen (expOrd ω))\n    with signature ord_le ==> ord_le ==> ord_le\n      as veblen_expOmega_le_mor.\nProof.\n  intros.\n  apply veblen_le_mor; auto.\n  apply expOrd_monotone; auto.\nQed.\n\nAdd Parametric Morphism : (veblen (expOrd ω))\n    with signature ord_eq ==> ord_eq ==> ord_eq\n      as veblen_expOmega_eq_mor.\nProof.\n  intros.\n  apply veblen_eq_mor; auto.\n  apply expOrd_monotone; auto.\nQed.\n\n\nLocal Hint Unfold powOmega : core.\nLocal Hint Resolve veblen_complete\n        onePlus_normal powOmega_normal expOrd_complete addOrd_complete\n        omega_complete succ_complete zero_complete\n        normal_monotone normal_complete omega_gt0 omega_gt1 : core.\n\n\nLemma veblen_additively_closed a b :\n  complete a -> complete b ->\n  additively_closed (veblen (expOrd ω) a b).\nProof.\n  intros. red. intros x y Hx Hy.\n  destruct (complete_zeroDec a) as [Ha|Ha]; auto.\n  - assert (veblen (expOrd ω) a b ≈ expOrd ω b).\n    { split.\n      transitivity (veblen (expOrd ω) 0 b).\n      apply veblen_monotone_first; auto.\n      rewrite veblen_zero. reflexivity.\n      rewrite veblen_unroll.\n      apply lub_le1. }\n    rewrite H1 in Hx, Hy.\n    rewrite H1.\n    apply expOmega_additively_closed; auto.\n  - assert (veblen (expOrd ω) a b ≈ expOrd ω (veblen (expOrd ω) a b)).\n    { rewrite <- (veblen_fixpoints _ powOmega_normal 0) at 1; auto.\n      rewrite veblen_zero.  reflexivity. }\n    rewrite H1 in Hx, Hy.\n    rewrite H1.\n    apply expOmega_additively_closed; auto.\nQed.\n\nLemma Γ_additively_closed a :\n  complete a -> additively_closed (Γ a).\nProof.\n  red; intros.\n  rewrite Γ_fixpoints; auto.\n  rewrite Γ_fixpoints in H0, H1; auto.\n  apply veblen_additively_closed; auto.\n  apply normal_complete; auto.\n  apply Γ_normal.\nQed.\n\nLemma veblen_collapse f (Hf:normal_function f) :\n  forall a b c,\n    complete a ->\n    complete b ->\n    complete c ->\n    a < c ->\n    b <= c ->\n    veblen f c 0 <= c ->\n    veblen f a b <= c.\nProof.\n  intros.\n  transitivity (veblen f c 0); auto.\n  rewrite <- (veblen_fixpoints f Hf a c 0); auto.\n  apply veblen_monotone; auto.\n  rewrite H3.\n  apply (normal_inflationary (fun i => veblen f i 0)); auto.\n  apply veblen_first_normal; auto.\nQed.\n\nLemma veblen_collapse' f (Hf:normal_function f) :\n  forall a b c,\n    complete a ->\n    complete b ->\n    complete c ->\n    a < c ->\n    b < c ->\n    veblen f c 0 <= c ->\n    veblen f a b < c.\nProof.\n  intros.\n  apply ord_lt_le_trans with (veblen f c 0); auto.\n  rewrite <- (veblen_fixpoints f Hf a c 0); auto.\n  apply veblen_increasing; auto.\n  apply ord_lt_le_trans with c; auto.\n  apply (normal_inflationary (fun i => veblen f i 0)); auto.\n  apply veblen_first_normal; auto.\nQed.\n\nLemma veblen_subterm1 f (Hf:normal_function f) :\n  forall a a' b,\n    complete a ->\n    complete a' ->\n    complete b ->\n    0 < b ->\n    a <= a' ->\n    a < veblen f a' b.\nProof.\n  intros.\n  apply ord_le_lt_trans with (veblen f a' 0).\n  transitivity (veblen f a 0).\n  apply (normal_inflationary (fun i => veblen f i 0)); auto.\n  apply veblen_first_normal; auto.\n  apply veblen_monotone_first; auto.\n  apply veblen_increasing; auto.\nQed.\n\nLemma veblen_shrink_lemma f (Hf:normal_function f) :\n  forall a b,\n    complete a ->\n    complete b ->\n    a < veblen f a 0 ->\n    b < veblen f b 0 ->\n    veblen f a b < veblen f (veblen f a b) 0.\nProof.\n  intros.\n  apply ord_lt_le_trans with\n      (veblen f a (veblen f (veblen f a b) 0)).\n  - apply veblen_increasing; auto.\n    apply ord_lt_le_trans with (veblen f b 0); auto.\n    apply veblen_monotone_first; auto.\n    apply veblen_inflationary; auto.\n  - apply veblen_fixpoints; auto.\n    apply ord_lt_le_trans with (veblen f a 0); auto.\n    apply veblen_monotone; auto with ord.\nQed.\n\nLemma veblen_subterm_zero f (Hf:normal_function f) :\n  forall a b c,\n    complete a ->\n    complete b ->\n    complete c ->\n    a < c ->\n    b < veblen f c 0 ->\n    veblen f a b < veblen f c 0.\nProof.\n  intros.\n  apply ord_lt_le_trans with (veblen f a (veblen f c 0)).\n  apply veblen_increasing; auto.\n  apply veblen_fixpoints; auto.\nQed.\n\nLemma veblen_subterm1_zero_nest f (Hf:normal_function f) :\n  forall a b c,\n    complete a ->\n    complete b ->\n    complete c ->\n    a < c ->\n    b < c ->\n    veblen f a b < veblen f c 0.\nProof.\n  intros.\n  apply veblen_subterm_zero; auto.\n  apply ord_lt_le_trans with c; auto.\n  apply (normal_inflationary (fun i => veblen f i 0)); auto.\n  apply veblen_first_normal; auto.\nQed.\n\nLemma veblen_increasing' f (Hf:normal_function f) :\n  forall a b c d,\n    complete a ->\n    complete d ->\n    a <= b ->\n    c < d ->\n    veblen f a c < veblen f b d.\nProof.\n  intros.\n  apply ord_lt_le_trans with (veblen f a d).\n  apply veblen_increasing; auto.\n  apply veblen_monotone_first; auto.\nQed.\n\nLemma ordering_correct_normal:\n  forall f x y o,\n    normal_function f ->\n    complete x ->\n    complete y ->\n    ordering_correct o x y ->\n    ordering_correct o (f x) (f y).\nProof.\n  intros. destruct o; simpl in *.\n  apply normal_increasing; auto.\n  destruct H2; split; apply normal_monotone; auto with ord.\n  apply normal_increasing; auto.\nQed.\n\nLemma veblen_compare_correct f (Hf:normal_function f) :\n  forall oab oxy oxVby oVaxy a b x y,\n    complete a ->\n    complete b ->\n    complete x ->\n    complete y ->\n    ordering_correct oab a b ->\n    ordering_correct oxy x y ->\n    ordering_correct oxVby x (veblen f b y) ->\n    ordering_correct oVaxy (veblen f a x) y ->\n    ordering_correct\n      (match oab with\n      | LT => oxVby\n      | EQ => oxy\n      | GT => oVaxy\n      end) (veblen f a x) (veblen f b y) .\nProof.\n  do 8 intro. intros Ha Hb Hx Hy Hoab Hoxy HoxVby HVaxy.\n  destruct oab; simpl in *.\n  - destruct oxVby; simpl in *.\n    + apply ord_lt_le_trans with (veblen f a (veblen f b y)).\n      apply veblen_increasing; auto.\n      apply veblen_fixpoints; auto.\n    + transitivity (veblen f a (veblen f b y)).\n      { split; (apply veblen_monotone; [ intros; apply normal_monotone; auto with ord | apply HoxVby ]). }\n      apply veblen_fixpoints; auto.\n    + apply ord_lt_le_trans with x; auto.\n      apply veblen_inflationary; auto.\n  - destruct oxy; simpl in *.\n    + apply ord_lt_le_trans with (veblen f a y).\n      apply veblen_increasing; auto.\n      apply veblen_monotone_first; auto.\n      apply Hoab.\n    + transitivity (veblen f a y).\n      split; apply veblen_monotone; auto; apply Hoxy.\n      split; apply veblen_monotone_first; auto; apply Hoab.\n    + apply ord_le_lt_trans with (veblen f a y).\n      apply veblen_monotone_first; auto. apply Hoab.\n      apply veblen_increasing; auto.\n  - destruct oVaxy; simpl in *.\n    + apply ord_lt_le_trans with y; auto.\n      apply veblen_inflationary; auto.\n    + symmetry.\n      transitivity (veblen f b (veblen f a x)).\n      split; apply veblen_monotone; auto; apply HVaxy.\n      apply veblen_fixpoints; auto.\n    + apply ord_lt_le_trans with (veblen f b (veblen f a x)).\n      apply veblen_increasing; auto.\n      apply veblen_fixpoints; auto.\nQed.\n\n\n\nLemma compose_normal f g :\n  normal_function f ->\n  normal_function g ->\n  normal_function (fun x => f (g x)).\nProof.\n  intros. constructor.\n  - intros; do 2 (apply normal_monotone; auto).\n  - intros. apply normal_increasing; auto.\n    apply normal_increasing; auto.\n  - hnf; intros A h a Hd Hc.\n    transitivity (f (supOrd (fun i => g (h i)))).\n    apply normal_monotone; auto.\n    apply normal_continuous; auto.\n    apply normal_continuous; auto.\n    hnf; intros.\n    destruct (Hd a1 a2) as [a' [??]].\n    exists a'.\n    split; apply normal_monotone; auto.\n  - intros. apply normal_complete; auto.\n  - intros; apply normal_nonzero; auto.\nQed.\n\nLemma veblen_first_onePlus_normal f :\n  normal_function f ->\n  normal_function (fun i => veblen f (1+i) 0).\nProof.\n  intros.\n  apply (compose_normal (fun i => veblen f i 0) (fun i => 1+i)).\n  apply veblen_first_normal; auto.\n  apply onePlus_normal; auto.\nQed.\n\nLemma veblen_func_onePlus_lemma f :\n  normal_function f ->\n  forall a x b y,\n    complete a ->\n    complete x ->\n    complete b ->\n    complete y ->\n    0 < b ->\n    a <= b -> x <= y ->\n    veblen (fun i => f (1+i)) a x <= veblen f b y.\nProof.\n  intros Hf.\n  induction a as [a Hind_a] using ordinal_induction.\n  induction x as [x Hind_x] using ordinal_induction.\n  intros b y Ha Hx Hb Hy Hb0 Hab Hxy.\n  rewrite veblen_unroll at 1.\n  apply lub_least.\n  - rewrite <- (veblen_fixpoints _ Hf 0); auto.\n    rewrite veblen_zero.\n    apply normal_monotone; auto.\n    rewrite <- onePlus_veblen; auto.\n    apply addOrd_monotone; auto with ord.\n    rewrite Hxy. apply veblen_inflationary; auto.\n  - destruct a as [A fa]; simpl; apply sup_least; intros i.\n    apply fixOrd_least; auto with ord.\n    + intros; apply veblen_monotone; auto.\n    + rewrite ord_le_unfold; simpl; intro ix.\n      rewrite (Hind_x (x ix) (index_lt x ix) b (x ix)); auto with ord.\n      apply veblen_increasing; auto.\n      apply ord_lt_le_trans with x; auto with ord.\n      apply complete_subord; auto.\n      apply complete_subord; auto.\n    + destruct (complete_zeroDec (fa i)); auto.\n      * apply Ha.\n      * transitivity (veblen (fun i0 : Ord => f (1 + i0)) 0 (veblen f b y)).\n        apply veblen_monotone_first; auto with ord.\n        rewrite <- (veblen_fixpoints _ Hf 0 b y) at 2; auto.\n        rewrite veblen_zero.\n        rewrite veblen_zero.\n        apply normal_monotone; auto.\n        apply onePlus_veblen; auto.\n      * rewrite <- (veblen_fixpoints _ Hf (fa i) b y) at 2; auto.\n        apply (Hind_a (fa i) (index_lt (ord A fa) i) (veblen f b y) (fa i) (veblen f b y)); auto with ord.\n        apply Ha.\n        apply Ha.\n        apply Ha.\n        apply ord_lt_le_trans with (ord A fa); auto with ord.\nQed.\n\nLemma veblen_func_onePlus f :\n  normal_function f ->\n  forall a x,\n    complete a ->\n    complete x ->\n    0 < a ->\n    veblen (fun i => f (1+i)) a x ≈ veblen f a x.\nProof.\n  intros; split.\n  apply veblen_func_onePlus_lemma; auto with ord.\n  apply veblen_monotone_func; auto.\n  apply (compose_normal f (fun i => 1+i)); auto.\n  intros; apply normal_monotone; auto.\n  apply addOrd_le2.\nQed.\n\n\nRequire Import ClassicalFacts.\nFrom Ordinal Require Import Classical.\n\nLemma veblen_decompose (EM:excluded_middle) f (Hf:normal_function f) :\n  forall x\n    (Hlim : limitOrdinal x),\n    x < veblen f x 0 ->\n    f x ≤ x ->\n    exists a b, x ≈ veblen f a b /\\ 0 < a /\\ a < x /\\ b < x.\nProof.\n  intros x Hlim Hx1 Hx2.\n\n  set (P a := a > 0 /\\ exists b, b < x /\\ x <= veblen f a b).\n  destruct (classical.ord_well_ordered EM P x) as [a [[Ha0 Ha] Hleast]]; auto.\n  { red. split. rewrite <- Hx2. apply normal_nonzero; auto.\n    exists 0. split; auto with ord. rewrite <- Hx2. apply normal_nonzero; auto. }\n  destruct Ha as [b0 Hb0].\n\n  set (Q b := b < x /\\ x <= veblen f a b).\n  destruct (classical.ord_well_ordered EM Q b0) as [b [[Hb Hab] Hbleast]]; auto.\n  unfold P in *.\n  unfold Q in *.\n\n  assert (Hle : veblen f a b ≤ x).\n  { rewrite veblen_unroll.\n    apply lub_least.\n    - rewrite <- Hx2.\n      apply normal_monotone; auto with ord.\n    - apply boundedSup_least. intros i Hi.\n      apply normal_fix_least; auto.\n      + apply veblen_normal; auto.\n        apply classical.ord_complete; auto.\n      + apply classical.ord_complete; auto.\n      + rewrite ord_le_unfold; simpl; intros.\n        destruct (classical.order_total EM x (veblen f a (b a0))) as [H|H]; auto.\n        elim (ord_lt_irreflexive b).\n        apply ord_le_lt_trans with (b a0); auto with ord.\n        apply Hbleast; split; auto with ord.\n        apply ord_lt_trans with b; auto with ord.\n      + destruct (classical.order_total EM i 0) as [Hi0|Hi0].\n        { apply ord_le_trans with (veblen f 0 x).\n          apply veblen_monotone_first; auto.\n          rewrite veblen_zero. auto. }\n        transitivity (veblen f i (boundedSup x (fun i => i))).\n        { apply veblen_monotone; auto.\n          apply limit_boundedSup; auto. }\n        transitivity (supOrd (fun q => veblen f i (x q))).\n        { destruct x as [X g]; simpl.\n          rewrite ord_lt_unfold in Hb. destruct Hb.\n          apply veblen_continuous; auto.\n          apply classical.ord_complete; auto.\n          apply classical.ord_directed; auto.\n          intros; apply classical.ord_complete; auto. }\n        apply sup_least; intro q.\n        destruct (classical.order_total EM (veblen f i (x q)) x) as [H|H]; auto.\n        elim (ord_lt_irreflexive a).\n        apply ord_le_lt_trans with i; auto.\n        apply Hleast; split; eauto with ord.\n  }\n\n  assert (Hax : a < x).\n  { destruct (classical.order_total EM x a); auto. exfalso.\n    elim (ord_lt_irreflexive x).\n    apply ord_lt_le_trans with (veblen f x 0); [ exact Hx1 | ].\n    transitivity (veblen f a 0).\n    apply veblen_monotone_first; auto.\n    rewrite <- Hle.\n    apply veblen_monotone; auto with ord.\n  }\n\n  exists a, b; intuition.\n  split; auto.\nQed.\n", "meta": {"author": "robdockins", "repo": "ordinals", "sha": "063164521baddfc99ab8c2d222cb01637e8833e1", "save_path": "github-repos/coq/robdockins-ordinals", "path": "github-repos/coq/robdockins-ordinals/ordinals-063164521baddfc99ab8c2d222cb01637e8833e1/Ordinal/VeblenFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6506786324189322}}
{"text": "Require Import Coq.Sets.Partial_Order.\nRequire Import Coq.Sets.Cpo.\nRequire Import Coq.Logic.Classical_Prop.\n\nSection Poset_Properties.\n\n  Variable U : Type.\n  Variable P : PO U.\n\n  Eval compute in (Carrier_of U P).\n\n  Definition C := @Carrier_of U P.\n  Definition R := @Rel_of U P.\n  \n  Definition Above (A:Ensemble U) : Ensemble U := fun x:U => In _ C x /\\ (forall y:U, In _ A y -> R y x).\n  \n  Definition Below (A:Ensemble U) : Ensemble U := fun x:U => In _ C x /\\ (forall y:U, In _ A y -> R x y).\n\n  Definition Upper_Bounded_Subset (A : Ensemble U) := Inhabited _ (Above A).\n\n  Definition Lower_Bounded_Subset (A : Ensemble U) := Inhabited _ (Below A).\n\n\n  Ltac crush_generic :=\n    repeat match goal with\n           | [ H : ?T |- ?T    ] => exact T\n           | [ |- ?T = ?T ] => reflexivity\n           | [ |- True         ] => constructor\n           | [ |- _ /\\ _       ] => constructor\n           | [ |- _ /\\ _ -> _  ] => intro\n           | [ H : _ /\\ _ |- _ ] => destruct H\n           | [ |- nat -> _     ] => intro\n           | [ H : Lower_Bounded_Subset _ |- _ ] => unfold Lower_Bounded_Subset in H\n           | [ H : Upper_Bounded_Subset _ |- _ ] => unfold Upper_Bounded_Subset in H\n           | [ H : In _ _ _ |- _ ] => unfold In in H\n           | [ H : Included _ _ _ |- _ ] => unfold Included in H\n           | _ => tauto\n           end.\n\n  Ltac unfold_all := try unfold Included;\n                     try unfold Above;\n                     try unfold Below;\n                     try unfold In;\n                     try unfold Lower_Bounded_Subset;\n                     try unfold Upper_Bounded_Subset.\n  \n  Ltac crush :=\n    repeat (crush_generic;\n            unfold_all;\n            match goal with\n            | [ |- ?T -> False  ]  => assert T\n            | _ => try trivial\n            end).\n\n  Lemma Below_In_Carrier : forall  (A : Ensemble U), Included _ A C -> Included _ (Below A) C.\n  Proof.\n    crush.\n  Qed.\n\n  Lemma Above_In_Carrier : forall  (A : Ensemble U), Included _ A C -> Included _ (Above A) C.\n  Proof.\n    crush.\n  Qed.\n\n  (** Lower Bound (Set) of a nonempty subset is Upper Bounded *)\n  Lemma Bound_Invert : forall  (A : Ensemble U), Included _ A C /\\ Inhabited _ A /\\ Lower_Bounded_Subset A -> Upper_Bounded_Subset (Below A).\n  Proof.\n    crush.\n    intros.\n\n    crush. inversion H0. inversion H1.\n    \n    apply Inhabited_intro with (x := x).\n    crush. apply H. tauto.\n    \n    intros. crush.\n    specialize H6 with x. tauto.\n  Qed.\n\n  (** If every nonempty upper-bounded subset has a least upper bound, then\nevery nonempty lower-bounded subset has a greatest lower bound. *)\n  Theorem Th : (forall A : Ensemble U, Included _ A C /\\ Inhabited _ A /\\ Upper_Bounded_Subset A -> exists lub, Lub _ P A lub) -> (forall B : Ensemble U, Included _ B C /\\ Inhabited _ B /\\ Lower_Bounded_Subset B -> exists glb, Glb _ P B glb).\n  Proof.\n    intros.\n    specialize H with (Below B).\n    pose proof Bound_Invert B H0 as R.\n\n    crush.\n    pose proof Below_In_Carrier B H0 as T.\n    pose proof H (conj T (conj H2 R)) as S.\n    destruct S.\n    exists x.\n\n    apply Glb_definition.\n\n    inversion H3. apply Lower_Bound_definition.\n    inversion H4. assumption.\n\n    intros. specialize H5 with y. apply H5.\n    apply Upper_Bound_definition.\n    specialize H0 with y. tauto.\n\n    intros. crush. unfold Below in H7.\n    apply H7. tauto.\n\n    intros. inversion H3. inversion H5.\n    specialize H8 with y. apply H8.\n\n    crush; inversion H4; assumption.\n  Qed.\n  ", "meta": {"author": "ankitku", "repo": "awotap", "sha": "1354a1f0e2f77c0157398553e666b6ff0be6d1ee", "save_path": "github-repos/coq/ankitku-awotap", "path": "github-repos/coq/ankitku-awotap/awotap-1354a1f0e2f77c0157398553e666b6ff0be6d1ee/Poset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6506593844089574}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_extension.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_layoff : \n   forall A B C D, \n   neq A B -> neq C D ->\n   exists X, Out A B X /\\ Cong A X C D.\nProof.\nintros.\nassert (~ eq B A).\n {\n intro.\n assert (eq A B) by (conclude lemma_equalitysymmetric).\n contradict.\n }\nlet Tf:=fresh in\nassert (Tf:exists E, (BetS B A E /\\ Cong A E C D)) by (conclude lemma_extension);destruct Tf as [E];spliter.\nassert (BetS E A B) by (conclude axiom_betweennesssymmetry).\nassert (neq E A) by (forward_using lemma_betweennotequal).\nassert (BetS E A B) by (conclude axiom_betweennesssymmetry).\nlet Tf:=fresh in\nassert (Tf:exists P, (BetS E A P /\\ Cong A P C D)) by (conclude lemma_extension);destruct Tf as [P];spliter.\nassert (Out A B P) by (conclude_def Out ).\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_layoff.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6505976206849418}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n\nSection Subsets.\n\nVariable X: Type.\nArguments X : default implicits.\n\nLet SX := X -> Prop.\n\nDefinition Has {X} (s: X->Prop) (x:X) := s x.\nNotation \"s `has` x\" := (Has s x) (at level 50).\n\nDefinition Includes (s:SX) (t:SX) := forall x:X, t x -> s x.\nNotation \"s `includes` t\" := (Includes s t) (at level 50).\n\nDefinition Complement (s:SX) := fun x:X => ~ s x.\nNotation \"s ^c\" := (Complement s) (at level 10).\n\nInductive Empty : SX :=.\n\nInductive Total : SX :=\n  Total_intro: forall x:X, Total  x.\n\nInductive Singleton (x: X) : SX :=\n  Singleton_intro : Singleton x `has` x.\n\nInductive Intersection (A B: SX) : SX :=\n  Intersection_intro : forall x: X, A `has` x -> B `has` x -> Intersection A  B `has` x.\nNotation \"a `and` b\" := (Intersection a b) (at level 0).\n\nInductive Union (A B: SX) : SX :=\n  | Union_introl : forall x: X, A `has` x -> Union A B `has` x\n  | Union_intror : forall x: X, B `has` x -> Union A B `has` x.\nNotation \"a `or` b\" := (Union a b) (at level 20).\n\n\nDefinition Equiv (A: SX) (B: SX) : Prop :=\n  A `includes` B /\\ B `includes` A.\nNotation \"a `equiv` b\" := (Equiv a b) (at level 20).\n\n\nTheorem intersection_left_includes (A B: SX) : A `includes` (A `and` B).\nProof.\n  move=> x AB_has_x.\n  by case: AB_has_x => A_has_x B_has_x.\nQed.\n\nTheorem intersection_right_includes (A B: SX) : B `includes` (A `and` B).\nProof.\n  move=> x AB_has_x.\n  by case: AB_has_x => A_has_x B_has_x.\nQed.\n\nTheorem includsion_intersection (A B: SX) : A `includes` B -> (A `and` B) `equiv` B.\nProof.\n  move => a_includes_b.\n  constructor.\n  - move => x ab_has_x.\n    constructor.\n    + by apply: a_includes_b.\n    + by apply: ab_has_x.\n  - by apply: intersection_right_includes.\nQed.\n\nTheorem total_includes (A: SX) : Total `includes` A.\nProof.\n  move=> x A_has_x.\n  by apply: Total_intro.\nQed.\nEnd Subsets.\n\nNotation \"s `has` x\" := (Has s x) (at level 50).\nNotation \"s `includes` t\" := (Includes s t) (at level 50).\nNotation \"a `and` b\" := (Intersection a b) (at level 0).\nNotation \"a `or` b\" := (Union a b) (at level 20).\nNotation \"a `equiv` b\" := (Equiv a b) (at level 20).\n\nSection Pretopologies.\nVariable X : Type.\nLet SX := (X -> Prop).\nLet SSX := (X -> Prop) -> Prop.\nLet TX := Total (X:=X).\n\nClass Upperset (u: SSX) := {\n  upperset_nonempty : exists s : SX, u `has` s;\n  upperset: forall (s t: SX), s `includes` t -> u `has` t -> u `has` s;\n}.\n\nTheorem upperset_has_total (u: SSX) : Upperset u -> u `has` TX.\nProof.\n  case => nonempty upper.\n  case: nonempty => s u_has_s.\n  apply: (upper TX s).\n  - by apply: total_includes.\n  - by apply: u_has_s.\nQed.\n\nClass Downward (d: SSX) := {\n  downward: True;\n}.\n\nClass Filter (f: SSX) := {\n  filter_upperset :> Upperset f;\n  filter_downward :> Downward f;\n}.\n\n\nClass Neighborhood v := {\n  neighborhood_filter :> forall x: X, Filter (v x);\n  neighborhood_has_point : forall (x: X) (s: SX), v x `has` s -> s `has` x;\n}.\n\nClass Interior (i: SX->SX) := {\n  interior_preserve_total : TX `equiv` i TX;\n  interior_intensive_law : forall (s: SX), s `includes` i s;\n  interior_functor_law: forall s t: SX, (s `includes` t) -> (i s) `includes` (i t); \n}.\n\n\nDefinition n2i (v: X -> SSX) := fun s:SX => fun x:X => (v x) `has` s.\nDefinition i2n i := fun x:X => fun s:SX => (i s) `has` x.\n\nTheorem neighborhood_derives_interior (v: X->SSX): Neighborhood v -> Interior (n2i v).\nProof.\n  case => filters has_point.\n  constructor.\n  - constructor.\n    + by apply: total_includes.\n    + move => x total_has_x.\n      move: (filters x) => filter.\n      case: filter => upper downward.\n      by apply: (upperset_has_total (u:=(v x)) upper).\n  - move => s x interior_has_s.\n    case: (filters x) => upper downward.\n    apply: has_point.\n    by apply: interior_has_s.\n  - move => s t s_includes_t x vx_has_t.\n    case: (filters x) => upper downward.\n    case: upper => nonempty upper.\n    by apply: (upper s t s_includes_t).\nQed.\n\nTheorem interior_derives_neighborhood (i: SX->SX): Interior i -> Neighborhood (i2n i).\nProof.\n  move => interior.\n  case: interior => preserve_total intensive functor.\n  constructor.\n  - move => x.\n    constructor.\n    + constructor.\n      exists (TX).\n      apply: (proj2 preserve_total).\n      by constructor.\n    + move => s t s_includes_t ti_has_x.\n      by apply: (functor s t s_includes_t).\n    + by constructor.\n  - move => x s si_has_x.\n    by apply: intensive.\nQed.\n\nClass Filter2 (f: SSX) := {\n  filter2_upperset :> Upperset f;\n  filter2_intersection_law : forall s t : SX, f `has` s -> f `has` t -> f `has` s `and` t;\n}.\n\nTheorem ext_multiply (f: SSX) : (forall (s t : SX), f `has` s -> f `has` t -> f `has` s `and` t) -> (forall (s t: SX), f `has` s -> f `has` t -> exists u, (s `includes` u) /\\ (t `includes` u))  .\nProof.\n  - move => mul s t fs ft.\n    apply: (ex_intro (fun u => s `includes` u /\\ t `includes` u) (s `and` t)).\n    constructor.\n    \n  - move => alpo s t f_has_s f_has_t.\n    move: (alpo s t f_has_s f_has_t) => asdf.\n    case: asdf => s_and_t P.\n    case: P => l r.\n    move: (Intersection_intro (X:=X) (A:=s) (B:=t)) => g.\n    compute in g.\n    compute in l.\n    compute in r.\n    compute.\n\nClass Neighborhood2 v := {\n  neighborhood2_filter :> forall x: X, Filter2 (v x);\n  neighborhood2_has_point : forall (x: X) (s: SX), v x `has` s -> s `has` x; \n}.\n\nTheorem neighborhood2_derives_interior (v: X->SSX): Neighborhood2 v -> Interior (n2i v).\nProof.\ncase => filters has_point.\nconstructor.\n- constructor.\n  + by apply: total_includes.\n  + move => x total_has_x.\n    case: (filters x) => upper intersection.\n    by apply: upperset_has_total.\n- move => s x interior_has_s.\n  case: (filters x) => upper intersection.\n  apply: has_point.\n  by apply: interior_has_s.\n- move => s t s_includes_t x vx_has_t.\n  case: (filters x) => upper intersection.\n  case: upper => nonempty upper.\n  by apply: (upper s t s_includes_t).\nQed.\n\nHypothesis extensionality : forall (s t: SX), s `equiv` t -> s = t.\n\nClass Interior2 (i: SX->SX) := {\n  interior2_preserve_total : TX `equiv` i TX;\n  interior2_intensive_law : forall (s: SX), s `includes` i s;\n  interior2_intersection_law: forall s t: SX, i (s `and` t) `equiv` (i s) `and` (i t); \n}.\n\nTheorem neighborhood2_derives_interior2 (v: X->SSX): Neighborhood2 v -> Interior2 (n2i v).\nProof.\nmove => neighborhood.\ncase: neighborhood => filters has_point.\nconstructor.\n- constructor.\n  + by apply: total_includes.\n  + move => x total_has_x.\n    case: (filters x) => upper intersection.\n    by apply: upperset_has_total.\n- move => s x interior_has_s.\n  case: (filters x) => upper intersection.\n  apply: has_point.\n  by apply: interior_has_s.\n- move => s t.\n  constructor.\n  + move => x si_and_ti_has_x.\n    case: (filters x) => upper intersection.\n    apply: intersection.\n    * by case: si_and_ti_has_x.\n    * by case: si_and_ti_has_x.\n  + move => x st_has_x.\n    constructor.\n    * case: (filters x) => upper intersecion.\n      case: upper => nonempty upper.\n      apply: (upper s (s `and` t) _ st_has_x).\n      by apply: intersection_left_includes.\n    * case: (filters x) => upper intersection.\n      case: upper => nonempty upper.\n      apply: (upper t (s `and` t) _ st_has_x).\n      by apply: intersection_right_includes.\nQed.\n\nTheorem interior2_derives_neighborhood2 (i: SX->SX): Interior2 i -> Neighborhood2 (i2n i).\nProof.\nmove => interior.\ncase: interior => preserve_total intensive intersection.\nconstructor.\n- move => x.\n  constructor.\n  + constructor.\n    exists (TX).\n    apply: (proj2 preserve_total).\n    by constructor.\n  + move => s t s_includes_t ti_has_x.\n    apply: (intersection_left_includes (A:=(i s)) (B:=(i t)) (x:=x)).\n    apply: ((proj2 (intersection s t)) x).\n    move: (extensionality (includsion_intersection s_includes_t)) => st_eq_t. (* use extensionality *)\n    by rewrite st_eq_t.\n  + move => s t si_has_x ti_has_x.\n    apply: ((proj1 (intersection s t)) x).\n    constructor.\n    * by apply si_has_x.\n    * by apply ti_has_x.\n- move => x s si_has_x.\n  by apply: intensive.\nQed.\n\nEnd Pretopologies.\n", "meta": {"author": "moritayasuaki", "repo": "pretopology", "sha": "54bf34d6329825a1f90887aff65c792cdccfdd82", "save_path": "github-repos/coq/moritayasuaki-pretopology", "path": "github-repos/coq/moritayasuaki-pretopology/pretopology-54bf34d6329825a1f90887aff65c792cdccfdd82/topology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6505976087366562}}
{"text": "Require Import Coq.Program.Basics LibTactics decision tactics.\n\nDefinition left_inverse {A B : Type} (f : A -> option B) (g : B -> option A) :=\n  forall (x : A) (y : B),\n    f x = Some y ->\n    g y = Some x.\nHint Unfold left_inverse.\n\nDefinition right_inverse {A B : Type} (f : A -> option B) (g : B -> option A) :=\n  forall (x : A) (y : B),\n    g y = Some x ->\n    f x = Some y.\nHint Unfold right_inverse.\n\nDefinition is_inverse {A B: Type} (f: A -> option B) (g: B -> option A) :=\n  left_inverse f g /\\ right_inverse f g.\nHint Unfold is_inverse.\n\nInductive bijection (A B: Type) :=\n| Bijection:\n    forall (f: A -> option B) (g: B -> option A),\n      left_inverse f g ->\n      right_inverse f g ->\n      @bijection A B.\nHint Constructors bijection.\n\nLemma inverse {A B: Type}:\n  bijection A B ->\n  bijection B A.\nProof.\n  intros.\n  inverts X.\n  eapply Bijection; eauto.\nDefined.\n\nLemma inverse_is_involutive {A B: Type} :\n  forall φ: bijection A B,\n    φ = inverse (inverse φ).\nProof.\n  intros.\n  unfold inverse.\n  destruct φ.\n  reflexivity.\nQed.\n\nDefinition fun_compose {A B C: Type} (f: B -> option C) (g: A -> option B) :=\n  fun (x : A) =>\n    match g x with\n    | Some y => f y\n    | None => None\n    end.\nHint Unfold fun_compose.\n\nLemma left_inverse_compose {A B C: Type}:\n  forall (f1: A -> option B)\n         (g1: B -> option A)\n         (f2: B -> option C)\n         (g2: C -> option B),\n    left_inverse f1 g1 ->\n    left_inverse f2 g2 ->\n    left_inverse (fun_compose f2 f1) (fun_compose g1 g2).\nProof.\n  intros.\n  unfold left_inverse in *.\n  intros.\n  unfold fun_compose in *.\n  destruct (f1 x) eqn:H2.\n  - erewrite -> H0; try eauto.\n  - discriminate.\nDefined.\n\n\nLemma right_inverse_compose {A B C: Type}:\n  forall (f1: A -> option B)\n         (g1: B -> option A)\n         (f2: B -> option C)\n         (g2: C -> option B),\n    right_inverse f1 g1 ->\n    right_inverse f2 g2 ->\n    right_inverse (fun_compose f2 f1) (fun_compose g1 g2).\nProof.\n  intros.\n  unfold right_inverse in *.\n  intros.\n  unfold fun_compose in *.\n  destruct (g2 y) eqn:H2.\n  - erewrite -> H; try eauto.\n  - discriminate.\nDefined.\n\nLemma bijection_compose {A B C: Type}:\n  bijection A B -> bijection B C -> bijection A C.\n  intros.\n  do 2 match goal with\n       | [H: bijection ?A ?B |- _] => inversion H; clear H\n       end.\n  apply (Bijection A C (fun_compose f f0) (fun_compose g0 g)).\n  apply left_inverse_compose; auto.\n  apply right_inverse_compose; auto.\nDefined.\n\nDefinition left {A B: Type} (f: bijection A B) : A -> option B :=\n  match f with\n    Bijection _ _ f _ _ _ => f\n  end.\n\nDefinition right {A B: Type} (f: bijection A B) : B -> option A :=\n  match f with\n    Bijection _ _ _ f _ _ => f\n  end.\n\nLemma inverse_compose {A B C: Type}:\n  forall (f : bijection A B)\n    (g : bijection B C),\n    inverse (bijection_compose f g) = bijection_compose (inverse g) (inverse f).\nProof.\n  intros.\n  unfold inverse.\n  unfold compose.\n  destruct f.\n  destruct g.\n  reflexivity.\nQed.    \n    \nLemma bijection_is_left_inverse {A B : Type}:\n  forall f : bijection A B,\n    left_inverse (left f) (right f).\nProof.\n  intros.\n  unfold left, right.\n  destruct f.\n  assumption.\nDefined.\n\nLemma bijection_is_right_inverse {A B : Type}:\n  forall f : bijection A B,\n    right_inverse (left f) (right f).\nProof.\n  intros.\n  unfold left, right.\n  destruct f.\n  assumption.\nDefined.\n\nLemma right_inverse_is_left {A B: Type}:\n  forall (f: bijection A B),\n    right (inverse f) = left f.\nProof.\n  unfold inverse.\n  destruct f.\n  unfold left.\n  unfold right.\n  reflexivity.\nDefined.\n\nLemma left_inverse_is_right {A B: Type}:\n  forall (f: bijection A B),\n    left (inverse f) = right f.\nProof.\n  unfold inverse.\n  destruct f.\n  unfold right.\n  unfold left.\n  reflexivity.\nDefined.\n\nLemma left_right {A B: Type}:\n  forall (f: bijection A B)\n         (x : B)\n         (y : A),\n    right f x = Some y ->\n    left f y = Some x.\nProof.\n  intros.\n  unfold left.\n  destruct f.\n  auto.\nQed.\n\nLemma right_left {A B: Type}:\n  forall (f: bijection A B)\n         (x: A)\n         (y: B),\n    left f x = Some y ->\n    right f y = Some x.\nProof.\n  intro.\n  unfold right.\n  destruct f.\n  auto.\nQed.\n\nLemma left_compose {A B C: Type}:\n  forall (φ : bijection A B)\n         (ψ: bijection B C)\n         (x : A)\n         (mz : option C),\n    left (bijection_compose φ ψ) x = mz ->\n    exists (my : option B),\n      left φ x = my /\\\n      (forall y, my = Some y -> left ψ y = mz) /\\\n      (my = None -> mz = None).\nProof.\n  intros.\n  exists (left φ x).\n  splits*.\n  - intros.\n    unfolds in H.\n    unfold bijection_compose in H.\n    destruct ψ.\n    destruct φ.\n    unfolds in H.\n    unfold left in *.\n    rewrite -> H0 in *.\n    assumption.\n  - intro.\n    unfold left in *.\n    unfold bijection_compose in *.\n    destruct ψ.\n    destruct φ.\n    unfolds in H.\n    rewrite -> H0 in H.\n    auto.\nQed.\n\nLemma right_bijection_compose {A B C: Type}:\n  forall (φ : bijection A B)\n         (ψ: bijection B C)\n         (z : C)\n         (mx : option A),\n    right (bijection_compose φ ψ) z = mx ->\n    exists (my : option B),\n      right ψ z = my /\\\n      (forall y, my = Some y -> right φ y = mx) /\\\n      (my = None -> mx = None).\nProof.\n  intros.\n  exists (right ψ z).\n  splits*.\n  - intros.\n    unfolds in H.\n    unfold bijection_compose in H.\n    unfolds in H0.\n    destruct ψ.\n    destruct φ.\n    unfolds.\n    unfolds in H.\n    rewrite -> H0 in *.\n    assumption.\n  - intro.\n    unfolds in H.\n    unfolds in H0.\n    unfold bijection_compose in H.\n    destruct ψ.\n    destruct φ.\n    unfolds in H.\n    rewrite -> H0 in *.\n    subst.\n    reflexivity.\nQed.\n\nLemma bijection_is_injective_left {A B : Type}:\n  forall (φ : bijection A B)\n         (x y : A)\n         (z : B),\n    x <> y -> left φ x = Some z -> Some z <> left φ y.\nProof.\n  intros.\n  intro H_absurd.\n  contradiction H.\n  unfolds in H_absurd.\n  destruct φ.\n  unfold left in *.\n  unfolds in l r.\n  symmetry in H_absurd.\n  remember (l x z H0).\n  remember (l y z H_absurd).\n  clear Heqe Heqe0.\n  rewrite e in *.\n  injects e0.\n  reflexivity.\nQed.\n\nLemma bijection_is_injective_right {A B : Type}:\n  forall (φ: bijection A B)\n         (x y : B)\n         (z : A),\n    x <> y -> right φ x = Some z -> Some z <> right φ y.\nProof.\n  intros.\n  intro H_absurd.\n  contradiction H.\n  unfolds in H_absurd.\n  destruct φ.\n  unfold right in *.\n  unfolds in l r.\n  symmetry in H_absurd.\n  remember (r z x H0).\n  remember (r z y H_absurd).\n  clear Heqe Heqe0.\n  rewrite e in *.\n  injects e0.\n  reflexivity.\nQed.\n\nLemma left_inverse_extend {A B: Type}\n      {DecA: forall a1 a2 : A, Decision (a1 = a2)}\n      {DecB: forall b1 b2: B, Decision (b1 = b2)}:\n  forall (f: A -> option B)\n    (g: B -> option A)\n    (l1: A)\n    (l2: B),\n    left_inverse f g ->\n    g l2 = None ->\n    left_inverse (fun l => if decide (l = l1)\n                        then Some l2\n                        else f l)\n                 (fun l => if decide (l = l2)\n                        then Some l1\n                        else g l).\n  Proof.\n    intros f g l1 l2 H1 H2.\n    unfolds.\n    intros.\n    destruct (decide (x = l1)); subst.\n    - injects.\n      destruct (decide (y = y)); subst.\n      + reflexivity.\n      + exfalso; eauto.\n    - destruct (decide (y = l2)); subst.\n      + exfalso.\n        match goal with\n          [H: left_inverse _ _ |- _] =>\n          erewrite H in *; eauto\n        end.\n        discriminate.\n      + eauto.\n  Defined.\n  Hint Resolve left_inverse_extend.\n\n  Lemma right_inverse_extend {A B : Type}\n        {DecA: forall a1 a2 : A, Decision (a1 = a2)}\n        {DecB: forall b1 b2: B, Decision (b1 = b2)}:\n    forall (f : A -> option B)\n      (g : B -> option A)\n      (l1 : A)\n      (l2 : B),\n    right_inverse f g ->\n    f l1 = None ->\n    right_inverse (fun l => if decide (l = l1)\n                            then Some l2\n                            else f l)\n                  (fun l => if decide (l = l2)\n                            then Some l1\n                            else g l).\nProof.\n  intros f g l1 l2 H1 H2.\n  unfolds.\n  intros.\n  destruct (decide (y = l2)); subst.\n  - rewrite_inj.\n    destruct (decide (x = x)); subst.\n    + reflexivity.\n    + exfalso; eauto.\n  - destruct (decide (x = l1)); subst.\n    + match goal with\n        [H: right_inverse _ _ |- _] =>\n        erewrite -> H1 in *; eauto\n      end.\n      discriminate.\n    + eauto.\nDefined.\nHint Resolve right_inverse_extend.\n\nDefinition extend_bijection {A B: Type}\n           {DecA: forall a1 a2 : A, Decision (a1 = a2)}\n           {DecB: forall b1 b2 : B, Decision (b1 = b2)}\n           (φ: bijection A B) (l3 : A) (l4 : B)\n           (H1: left φ l3 = None) (H2: right φ l4 = None) :=\n  Bijection A B\n            (fun l : A => if decide (l = l3) then Some l4 else left φ l)\n            (fun l : B => if decide (l = l4) then Some l3 else right φ l)\n            (@left_inverse_extend A B DecA DecB (left φ) (right φ)\n                                  l3 l4 (bijection_is_left_inverse φ) H2)\n            (@right_inverse_extend A B DecA DecB (left φ) (right φ)\n                                   l3 l4 (bijection_is_right_inverse φ) H1).\nHint Unfold extend_bijection.\n\nLemma left_inverse_reduce {A B : Type}\n      {DecA: forall a1 a2 : A, Decision (a1 = a2)}\n      {DecB: forall b1 b2 : B, Decision (b1 = b2)}:\n  forall (φ : bijection A B) l3 l4,\n    left φ l3 = Some l4 ->\n    left_inverse\n      (fun l : A => if decide (l = l3) then None else left φ l)\n      (fun l : B => if decide (l = l4) then None else right φ l).\nProof.\n  intros.\n  unfolds.\n  intros.\n  destruct (decide (x = l3)); subst; try discriminate.\n  assert (right φ y = Some x) by (destruct φ; eauto 2).\n  destruct (decide (y = l4)); subst; try assumption.\n  assert (Some l4 <> left φ l3)\n    by eauto using bijection_is_injective_left.\n  exfalso; eauto 2.\nQed.\n\nLemma right_inverse_reduce {A B : Type}\n      {DecA: forall a1 a2 : A, Decision (a1 = a2)}\n      {DecB: forall b1 b2 : B, Decision (b1 = b2)}:\n  forall φ l4 l3,\n    left φ l3 = Some l4 ->\n    right_inverse\n      (fun l : A => if decide (l = l3) then None else left φ l)\n      (fun l : B => if decide (l = l4) then None else right φ l).\nProof.\n  intros.\n  assert (right φ l4 = Some l3) by (destruct φ; eauto).\n  unfolds.\n  intros.\n  destruct (decide (y = l4)); subst; try discriminate.\n  assert (left φ x = Some y) by (destruct φ; eauto 2).\n  destruct (decide (x = l3)); subst; try assumption.\n  assert (Some l3 <> right φ l4)\n    by eauto using bijection_is_injective_right.\n  exfalso; eauto 2.\nQed.  \n\nDefinition reduce_bijection {A B : Type}\n           {DecA: forall a1 a2 : A, Decision (a1 = a2)}\n           {DecB: forall b1 b2 : B, Decision (b1 = b2)}\n           (φ: bijection A B) (l3 : A) (l4 : B) (H : left φ l3 = Some l4) :=\n  Bijection A B\n            (fun l : A => if decide (l = l3) then None\n                       else left φ l)\n            (fun l : B => if decide (l = l4) then None\n                       else right φ l)\n            (left_inverse_reduce φ l3 l4 H)\n            (right_inverse_reduce φ l4 l3 H).\n\nLemma reduce_bijection_lookup_eq_left {A B : Type}\n      {DecA: forall a1 a2 : A, Decision (a1 = a2)}\n      {DecB: forall b1 b2 : B, Decision (b1 = b2)}:\n  forall f (a : A) (b : B) H,\n    left (reduce_bijection f a b H) a = None.\nProof.\n  intros.\n  unfold left.\n  unfold reduce_bijection.\n  destruct (decide (a = a)); subst.\n  - reflexivity.\n  - exfalso; eauto.\nQed.\n\nLemma reduce_bijection_lookup_eq_right {A B : Type}\n      {DecA: forall a1 a2 : A, Decision (a1 = a2)}\n      {DecB: forall b1 b2 : B, Decision (b1 = b2)}:\n  forall f (a : A) (b : B) H,\n    right (reduce_bijection f a b H) b = None.\nProof.\n  intros.\n  unfold right.\n  unfold reduce_bijection.\n  destruct (decide (b = b)); subst.\n  - reflexivity.\n  - exfalso; eauto.\nQed.\n\nLemma reduce_bijection_lookup_neq_left {A B : Type}\n      {DecA: forall a1 a2 : A, Decision (a1 = a2)}\n      {DecB: forall b1 b2 : B, Decision (b1 = b2)}:\n  forall f (a1 a2 : A) (b : B) H,\n    a1 <> a2 ->\n    left (reduce_bijection f a1 b H) a2 = left f a2.\nProof.\n  intros.\n  unfold left.\n  unfold reduce_bijection.\n  destruct (decide (a2 = a1)); subst.\n  - exfalso; eauto.\n  - destruct f.\n    unfold left.\n    reflexivity.\nQed.\n\nLemma reduce_bijection_lookup_neq_right {A B : Type}\n      {DecA: forall a1 a2 : A, Decision (a1 = a2)}\n      {DecB: forall b1 b2 : B, Decision (b1 = b2)}:\n  forall f (a : A) (b1 b2 : B) H,\n    b1 <> b2 ->\n    right (reduce_bijection f a b1 H) b2 = right f b2.\nProof.\n  intros.\n  unfold right.\n  unfold reduce_bijection.\n  destruct (decide (b2 = b1)); subst.\n  - exfalso; eauto.\n  - destruct f.\n    unfold right.\n    reflexivity.\nQed.\n\nNotation \"φ '[' H1 ',' H2 '⊢' a '<->' b ']'\" :=\n  (extend_bijection φ a b H1 H2) (at level 10, no associativity).\n\nLemma left_extend_bijection_eq {A B: Type}\n           {DecA: forall a1 a2 : A, Decision (a1 = a2)}\n           {DecB: forall b1 b2 : B, Decision (b1 = b2)}:\n  forall (φ : bijection A B) loc1 loc2 H1 H2,\n    left (extend_bijection φ loc1 loc2 H1 H2) loc1 = Some loc2.\nProof.\n  intros.\n  unfold extend_bijection in *.\n  unfold left.\n  destruct (decide (loc1 = loc1)); subst.\n  - reflexivity.\n  - exfalso; eauto.\nQed.\nHint Resolve left_extend_bijection_eq.\n\nLemma right_extend_bijection_eq {A B: Type}\n           {DecA: forall a1 a2 : A, Decision (a1 = a2)}\n           {DecB: forall b1 b2 : B, Decision (b1 = b2)}:\n  forall (φ : bijection A B) loc1 loc2 H1 H2,\n    right (extend_bijection φ loc1 loc2 H1 H2) loc2 = Some loc1.\nProof.\n  intros.\n  unfold extend_bijection in *.\n  unfold right.\n  destruct (decide (loc2 = loc2)); subst.\n  - reflexivity.\n  - exfalso; eauto.\nQed.\nHint Resolve left_extend_bijection_eq.\n\nLemma left_extend_bijection_neq {A B: Type}\n           {DecA: forall a1 a2 : A, Decision (a1 = a2)}\n           {DecB: forall b1 b2 : B, Decision (b1 = b2)}:\n  forall (φ : bijection A B) loc1 loc2 loc3 H1 H2,\n    loc1 <> loc3 ->\n    left (extend_bijection φ loc1 loc2 H1 H2) loc3 = left φ loc3.\nProof.\n  intros.\n  unfold extend_bijection in *.\n  unfold left in *.\n  destruct (decide (loc3 = loc1)); subst.\n  - exfalso; eauto.\n  - destruct φ.\n    reflexivity.\nQed.\nHint Resolve left_extend_bijection_neq.\n\nLemma right_extend_bijection_neq {A B: Type}\n      {DecA: forall a1 a2 : A, Decision (a1 = a2)}\n      {DecB: forall b1 b2 : B, Decision (b1 = b2)}:\n  forall (φ : bijection A B) loc1 loc2 loc3 H1 H2,\n    loc2 <> loc3 ->\n    right (extend_bijection φ loc1 loc2 H1 H2) loc3 = right φ loc3.\nProof.\n  intros.\n  unfold extend_bijection in *.\n  unfold right in *.\n  destruct φ in *.\n  unfold left in *.\n  destruct (decide (loc3 = loc2)); subst.\n  - exfalso; eauto.\n  - reflexivity.\nQed.\nHint Resolve right_extend_bijection_neq.\n\nLemma identity_bijection:\n  forall A,\n    bijection A A.\nProof.\n  intros.\n  apply (Bijection A A (fun x => Some x) (fun y => Some y)).\n  - unfold left_inverse; eauto.\n  - unfold right_inverse; eauto.\nDefined.\n\nLemma identity_bijection_is_identity_left:\n  forall A B (φ : bijection A B) x,\n    left (bijection_compose (identity_bijection A) φ) x = left φ x.\nProof.\n  intros.\n  unfold left.\n  unfold bijection_compose.\n  destruct φ.\n  unfold identity_bijection.\n  unfold fun_compose.\n  reflexivity.\nQed.\n\nLemma identity_bijection_is_identity_right:\n  forall A B (φ : bijection A B) x,\n    right (bijection_compose (identity_bijection A) φ) x = right φ x.\nProof.\n  intros.\n  unfold right.\n  unfold bijection_compose.\n  destruct φ.\n  unfold identity_bijection.\n  unfold fun_compose.\n  destruct (g x); reflexivity.\nQed.\n\nLemma inverse_identity_is_identity {A: Type}:\n  inverse (identity_bijection A) = identity_bijection A.\nProof.\n  reflexivity.\nQed.\n\nDefinition pred_func {A : Type} (P: A -> Prop)\n           (DecP: forall a : A, {P a} + {~ P a}) :=\n  fun a : A => if DecP a then Some a else None.\n\nLemma left_inverse_pred_func:\n  forall {A : Type}\n    (P : A -> Prop)\n    (DecP: forall a : A, {P a} + {~ P a}),\n    left_inverse (pred_func P DecP) (pred_func P DecP).\nProof.\n  intros.\n  unfolds.\n  intros.\n  unfold pred_func in *.\n  destruct (DecP x).\n  - rewrite_inj.\n    destruct (DecP y); try contradiction.\n    reflexivity.\n  - discriminate.\nQed.\n\nLemma right_inverse_pred_func:\n  forall {A : Type}\n    (P : A -> Prop)\n    (DecP: forall a : A, {P a} + {~ P a}),\n    right_inverse (pred_func P DecP) (pred_func P DecP).\nProof.\n  intros.\n  unfolds.\n  intros.\n  unfold pred_func in *.\n  destruct (DecP y).\n  - rewrite_inj.\n    destruct (DecP x); try contradiction.\n    reflexivity.\n  - discriminate.\nQed.\n\nDefinition pred_bijection {A : Type} (P : A -> Prop)\n           (DecP: forall a : A, {P a} + {~ P a}) : bijection A A :=\n  Bijection A A (pred_func P DecP) (pred_func P DecP)\n            (left_inverse_pred_func P DecP)\n            (right_inverse_pred_func P DecP).\n\nDefinition filtered {A B : Type} (P: A -> Prop) (φ: bijection A B) (ψ: bijection A B) :=\n  (forall a, (~ P a -> left ψ a = None) /\\\n        (P a -> left ψ a = left φ a)).\nHint Unfold filtered.\n\nDefinition filtered' {A B : Type} (P: B -> Prop) (φ: bijection A B) (ψ: bijection A B) :=\n  (forall b, (~ P b -> right ψ b = None) /\\\n        (P b -> right ψ b = right φ b)).\nHint Unfold filtered'.\n\nLemma pred_compose_left_some {A B : Type}:\n  forall (P : A -> Prop) (DecP: forall a, {P a} + {~ P a}) (φ : bijection A B) a b,\n    left (bijection_compose (pred_bijection P DecP) φ) a = Some b ->\n    P a.\nProof.\n  intros.\n  unfold left, bijection_compose in *.\n  destruct φ.\n  unfold pred_bijection, fun_compose, pred_func in *.\n  destruct (DecP a); [assumption | discriminate].\nQed.\n\nLemma pred_compose_left_some' {A B : Type}:\n  forall (P : B -> Prop) (DecP: forall b, {P b} + {~ P b}) (φ : bijection A B) a b,\n    left (bijection_compose φ (pred_bijection P DecP)) a = Some b ->\n    P b.\nProof.\n  intros.\n  unfold left, bijection_compose in *.\n  destruct φ.\n  unfold pred_bijection, fun_compose, pred_func in *.\n  assert (f a = Some b).\n  {\n    destruct (f a).\n    - destruct (DecP b0); congruence.\n    - congruence.\n  }\n  decide_exist in *.\n  destruct (DecP b); [assumption | discriminate].\nQed.\n\nLemma not_pred_compose_left_implies_none {A B : Type}:\n  forall (P : A -> Prop) (DecP: forall a, {P a} + {~ P a}) (φ : bijection A B) a,\n    ~ P a ->\n    left (bijection_compose (pred_bijection P DecP) φ) a = None.\nProof.\n  intros.\n  unfold left, bijection_compose in *.\n  destruct φ.\n  unfold pred_bijection, fun_compose, pred_func in *.\n  destruct (DecP a).\n  - contradiction.\n  - reflexivity.\nQed.\nHint Resolve not_pred_compose_left_implies_none.\n\nLemma not_pred_compose_left_implies_none' {A B : Type}:\n  forall (P : B -> Prop) (DecP: forall b, {P b} + {~ P b}) (φ : bijection A B) b,\n    ~ P b ->\n    right (bijection_compose φ (pred_bijection P DecP)) b = None.\nProof.\n  intros.\n  unfold right, bijection_compose in *.\n  destruct φ.\n  unfold pred_bijection, fun_compose, pred_func in *.\n  destruct (DecP b).\n  - contradiction.\n  - reflexivity.\nQed.\nHint Resolve not_pred_compose_left_implies_none'.\n\nLemma pred_compose_left_implies_same {A B : Type}:\n  forall (P : A -> Prop) (DecP: forall a, {P a} + {~ P a}) (φ : bijection A B) a,\n    P a ->\n    left (bijection_compose (pred_bijection P DecP) φ) a = left φ a.\nProof.\n  intros.\n  unfold left, bijection_compose in *.\n  destruct φ.\n  unfold pred_bijection, fun_compose, pred_func in *.\n  destruct (DecP a).\n  - reflexivity.\n  - contradiction.\nQed.\nHint Resolve pred_compose_left_implies_same.\n\nLemma pred_compose_left_implies_same' {A B : Type}:\n  forall (P : B -> Prop) (DecP: forall b, {P b} + {~ P b}) (φ : bijection A B) b,\n    P b ->\n    right (bijection_compose φ (pred_bijection P DecP)) b = right φ b.\nProof.\n  intros.\n  unfold right, bijection_compose in *.\n  destruct φ.\n  unfold pred_bijection, fun_compose, pred_func in *.\n  destruct (DecP b).\n  - reflexivity.\n  - contradiction.\nQed.\nHint Resolve pred_compose_left_implies_same'.\n\nLemma filter_bijection {A B : Type}:\n  forall (P: A -> Prop)\n    (DecP : forall a, {P a} + {~ P a})\n    (φ : bijection A B),\n    { ψ : bijection A B | filtered P φ ψ }.\nProof.\n  intros.\n  exists (bijection_compose (pred_bijection P DecP) φ).\n  unfolds.\n  intros.\n  splits; intros; eauto.\nQed.\n\nLemma filter_bijection' {A B : Type}:\n  forall (P: B -> Prop)\n    (DecP : forall b, {P b} + {~ P b})\n    (φ : bijection A B),\n    { ψ : bijection A B | filtered' P φ ψ }.\nProof.\n  intros.\n  exists (bijection_compose φ (pred_bijection P DecP)).\n  unfolds.\n  intros.\n  splits; intros; eauto.\nQed.\n\nLemma filtered_eq_if {A B : Type}:\n  forall a b (P : A -> Prop) (DecP: forall a, {P a} + {~ P a})\n    (ψ : bijection A B) (φ : bijection A B),\n    left ψ a = Some b ->\n    filtered P φ ψ ->\n    left φ a = Some b.\nProof.\n  intros.\n  destruct (DecP a).\n  - assert (left ψ a = left φ a) by (eapply H0; eauto).\n    congruence.\n  - assert (left ψ a = None) by (eapply H0; eauto).\n    congruence.\nQed.\nHint Resolve filtered_eq_if.\n\nLemma filtered_eq_if' {A B : Type}:\n  forall a b (P : B -> Prop) (DecP: forall b, {P b} + {~ P b})\n    (ψ : bijection A B) (φ : bijection A B),\n    right ψ b = Some a ->\n    filtered' P φ ψ ->\n    right φ b = Some a.\nProof.\n  intros.\n  destruct (DecP b).\n  - assert (right ψ b = right φ b) by (eapply H0; eauto).\n    congruence.\n  - assert (right ψ b = None) by (eapply H0; eauto).\n    congruence.\nQed.\nHint Resolve filtered_eq_if'.\n\nLemma filtered_bijection_is_subset {A B : Type}:\n  forall (P : A -> Prop) (DecP: forall a, {P a} + {~ P a}) (φ ψ: bijection A B) a b,\n    filtered P φ ψ ->\n    left ψ a = Some b ->\n    left φ a = Some b.\nProof.\n  intros.\n  eauto.\nQed.\nHint Resolve filtered_bijection_is_subset.\n\nLemma filtered_bijection_is_subset' {A B : Type}:\n  forall (P : B -> Prop) (DecP: forall b, {P b} + {~ P b}) (φ ψ: bijection A B) a b,\n    filtered' P φ ψ ->\n    right ψ b = Some a ->\n    right φ b = Some a.\nProof.\n  intros.\n  eauto.\nQed.\nHint Resolve filtered_bijection_is_subset'.\n\nLemma filtered_bijection_is_subset_transpose_left {A B : Type}:\n  forall (P : A -> Prop)\n    (DecP: forall a, {P a} + {~ P a})\n    (φ ψ : bijection A B) a,\n    filtered P φ ψ ->\n    left φ a = None ->\n    left ψ a = None.\nProof.\n  intros.\n  destruct (left ψ a) eqn:H'.\n  -assert (left φ a = Some b) by eauto.\n   congruence.\n  - reflexivity.\nQed.\nHint Resolve filtered_bijection_is_subset_transpose_left.\n\nLemma filtered_bijection_is_subset_transpose_right {A B : Type}:\n  forall (P : B -> Prop)\n    (DecP: forall b, {P b} + {~ P b})\n    (φ ψ : bijection A B) b,\n    filtered' P φ ψ ->\n    right φ b = None ->\n    right ψ b = None.\nProof.\n  intros.\n  destruct (right ψ b) eqn:H'.\n  - assert (right φ b = Some a) by eauto.\n    congruence.\n  - reflexivity.\nQed.\nHint Resolve filtered_bijection_is_subset_transpose_right.\n\nLemma filter_true {A B : Type}:\n  forall (P : A -> Prop)\n    (φ ψ : bijection A B)\n    a b,\n    P a ->\n    filtered P φ ψ ->\n    left φ a = Some b ->\n    left ψ a = Some b.\nProof.\n  intros.\n  unfold filtered in *.\n  destruct (H0 a).\n  assert (left ψ a = left φ a) by eauto.\n  congruence.\nQed.\nHint Resolve filter_true.\n\nLemma filter_true' {A B : Type}:\n  forall (P : B -> Prop)\n    (φ ψ : bijection A B)\n    a b,\n    P b ->\n    filtered' P φ ψ ->\n    right φ b = Some a ->\n    right ψ b = Some a.\nProof.\n  intros.\n  unfold filtered in *.\n  destruct (H0 b).\n  assert (right ψ b = right φ b) by eauto.\n  congruence.\nQed.\nHint Resolve filter_true'.\n\nLemma filtered_bijection_some_implies_predicate {A B : Type}:\n  forall (P : A -> Prop) (DecP : forall a, {P a} + {~ P a})\n    (φ ψ : bijection A B) a b,\n    filtered P φ ψ ->\n    left ψ a = Some b ->\n    P a.\nProof.\n  intros.\n  unfold filtered in *.\n  destruct (H a).\n  destruct (DecP a); eauto 2.\n  assert (left ψ a = None) by eauto.\n  congruence.\nQed.\n\nLemma filtered_bijection_some_implies_predicate' {A B : Type}:\n  forall (P : B -> Prop) (DecP : forall b, {P b} + {~ P b})\n    (φ ψ : bijection A B) a b,\n    filtered' P φ ψ ->\n    right ψ b = Some a ->\n    P b.\nProof.\n  intros.\n  unfold filtered in *.\n  destruct (H b).\n  destruct (DecP b); eauto 2.\n  assert (right ψ b = None) by eauto.\n  congruence.\nQed.\n\nLemma implies_left_compose {A B C : Type}:\n  forall (f : bijection A B) (g : bijection B C)\n    x y z,\n    left f x = Some y ->\n    left g y = Some z ->\n    left (bijection_compose f g) x = Some z.\nProof.\n  intros.\n  unfold left, bijection_compose.\n  destruct g, f.\n  unfold left, fun_compose in *.\n  break_match; congruence.\nQed.\nHint Resolve implies_left_compose.\n\nLemma implies_right_compose {A B C : Type}:\n  forall (f : bijection A B) (g : bijection B C)\n    x y z,\n    right f y = Some x ->\n    right g z = Some y ->\n    right (bijection_compose f g) z = Some x.\nProof.\n  intros.\n  unfold right, bijection_compose.\n  destruct g, f.\n  unfold right, fun_compose in *.\n  break_match; congruence.\nQed.\nHint Resolve implies_right_compose.\n\nSection BijectionProofIrrelevance.\n\n  Require Import FunctionalExtensionality.\n  \n  Axiom bijection_proof_irrelevance:\n    forall (A B : Type) (f g : bijection A B),\n      left f = left g ->\n      right f = right g ->\n      f = g.\n  \n  Lemma compose_id_left {A B: Type}:\n    forall φ: bijection A B,\n      bijection_compose (identity_bijection A) φ = φ.\n  Proof.\n    intros.\n    unfold bijection_compose.\n    unfold identity_bijection.\n    destruct φ.\n    apply bijection_proof_irrelevance.\n    - reflexivity.\n    - unfold right.\n      unfold fun_compose.\n      extensionality x.\n      destruct (g x); eauto.\n  Qed.\n  \n  Lemma compose_id_right {A B: Type}:\n    forall φ: bijection A B,\n      bijection_compose φ (identity_bijection B) = φ.\n  Proof.\n    intros.\n    unfold bijection_compose.\n    unfold identity_bijection.\n    destruct φ.\n    apply bijection_proof_irrelevance.\n    - unfold left.\n      unfold fun_compose.\n      extensionality x.\n      destruct (f x); eauto.\n    - reflexivity.\n  Qed.\n\nEnd BijectionProofIrrelevance.", "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/bijection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924674, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.650597604265739}}
{"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(* A theory of constructed rational numbers *)\n\nSet Implicit Arguments.\n\nRequire Import Arith.\nRequire Import Omega.\nRequire Import List.\nRequire Import fcf.StdNat.\nRequire Import Lia.\n\nInductive Rat :=\n    RatIntro : nat -> posnat -> Rat.\n\nDefinition ratCD(r1 r2 : Rat) : (nat * nat * posnat) :=\n  match (r1, r2) with\n    | (RatIntro n1 d1, RatIntro n2 d2) =>\n      ((n1 * d2), (n2 * d1), (posnatMult d1 d2))\n  end.\n\nDefinition ratMult(r1 r2 : Rat) : Rat :=\n  match (r1, r2) with\n    | (RatIntro n1 d1, RatIntro n2 d2) =>\n      RatIntro (n1 * n2) (posnatMult d1 d2)\n  end.\n\nDefinition rat1 := (RatIntro 1 (pos 1)).\nDefinition rat0 := (RatIntro 0 (pos 1)).\n\n\nDefinition ratAdd(r1 r2 : Rat) : Rat :=\n  match ratCD r1 r2 with\n    | (n1, n2, d) => \n      RatIntro (n1 + n2) d\n  end.\n\nDefinition ratSubtract(r1 r2: Rat) : Rat :=\n  match ratCD r1 r2 with\n    | (n1, n2, d) =>\n      RatIntro (n1 - n2) d\n  end.\n\nDefinition beqRat(r1 r2 : Rat) :=\n  match (ratCD r1 r2) with\n    | (n1, n2, _) => \n      if (eq_nat_dec n1 n2) then true else false\n  end.\n\nDefinition bleRat(r1 r2 : Rat) :=\n  match (ratCD r1 r2) with\n    | (n1, n2, _) => \n      if (le_gt_dec n1 n2) then true else false\n  end.\n\nDefinition eqRat(r1 r2 : Rat) :=\n  beqRat r1 r2 = true.\n\nDefinition leRat(r1 r2 : Rat) := \n  bleRat r1 r2 = true.\n\nDefinition maxRat(r1 r2 : Rat) :=\n  if (bleRat r1 r2) then r2 else r1.\n\nDefinition minRat(r1 r2 : Rat) :=\n  if (bleRat r1 r2) then r1 else r2.\n\nDefinition ratDistance(r1 r2 : Rat) :=\n  ratSubtract (maxRat r1 r2) (minRat r1 r2).\n\nLtac rattac_one := \n  match goal with \n    (* rules that solve goals *)\n    | [|- posnatMult ?x1 ?x2 = posnatMult ?x2 ?x1] => apply posnatMult_comm\n    | [|- posnatToNat (posnatMult ?x1 ?x2) = posnatToNat (posnatMult ?x2 ?x1)] => rewrite posnatMult_comm; trivial\n    | [|- ?x1 * ?x2 = ?x2 * ?x1 ] => apply mult_comm\n    | [|- (mult (?x1 + ?x2) _)  = (mult (?x2 + ?x1) _ )] => f_equal\n    | [|- ?x1 * ?x2 * _ = ?x2 * ?x1 * _ ] => f_equal\n    | [ |- posnatToNat ?p > 0 ] => destruct p; unfold posnatToNat; omega\n      (* inversion on hypotheses *)\n    | [H1 : ?n * ?x = ?n0 * ?x1, H2: ?n1 * ?x1 = ?n * ?x0 |- ?n1 * ?x = ?n0 * ?x0 ] => eapply (@mult_same_l x1)(* ;\n      [idtac | rewrite mult_assoc ;\n        rewrite (mult_comm x1 n1);\n          rewrite H2;\n            rewrite <- mult_assoc ;\n              rewrite (mult_comm x x0) ;\n                repeat rewrite mult_assoc;\n                  f_equal] *) \n    | [H : ?x = ?n * (posnatToNat ?p) |- ?x = (posnatToNat ?p) * ?n ] => rewrite H\n    | [H : RatIntro _ _ = RatIntro _ _ |- _ ] => inversion H; clear H; subst\n    | [H : (eqRat _ _) |- _ ] => unfold eqRat, beqRat in H\n    | [H : (leRat _ _) |- _ ] => unfold leRat, bleRat in H\n    | [H : ?r = RatIntro _ _ |- context[match ?r with | RatIntro _ _ => _ end] ] => rewrite r\n    \n    | [|- context[match ?r with | RatIntro _ _ => _ end] ] => case_eq r; intuition\n    | [H : (_ , _) = (_ , _) |- _ ] => inversion H; clear H; subst\n    | [|- (_, _) = (_, _) ] => f_equal\n    | [H: context[ratCD _ _] |- _ ] => unfold ratCD in *\n    | [H : context[match rat0 with | RatIntro _ _ => _ end ] |- _ ] => unfold rat0 in H\n    | [H1 : context[match ?r with | RatIntro _ _ => _ end], H2 : ?r = RatIntro _ _ |- _ ] => rewrite H2 in H1\n    | [H : context[match ?r with | RatIntro _ _ => _ end ] |- _ ] => case_eq r; intuition\n    | [|- context[let (_, _) := ?x in _] ] => case_eq x; intuition\n    | [H : context[ratAdd _ _] |- _ ] => unfold ratAdd in H    \n    | [H : context[ratMult _ _] |- _ ] => unfold ratMult in H   \n    | [H: context [eq_nat_dec ?x ?y] |- _] => destruct (eq_nat_dec x y)\n    | [H: context [le_gt_dec ?x ?y] |- _] => destruct (le_gt_dec x y)\n    | [|- (if (eq_nat_dec ?x ?y) then true else false) = true ] => assert (x = y); destruct (eq_nat_dec x y); trivial\n     | [|- (if (le_gt_dec ?x ?y) then true else false) = true ] => assert (x <= y); [idtac | destruct (le_gt_dec x y); trivial]\n    | [|- context[posnatMult _ _ ] ] => unfold posnatMult\n    | [|- (eqRat _ _) ] => unfold eqRat, beqRat\n    | [|- (leRat _ _) ] => unfold leRat, bleRat\n    | [|- (posnatEq _ _ ) ] => econstructor\n    | [|- context[(posnatToNat _)] ] => unfold posnatToNat in *\n    | [H : context[let (_, _) := ?p in _] |- _] => destruct p\n    end.\nLtac rattac :=\n  intuition; unfold ratCD in *; \n    repeat (rattac_one; subst); repeat rewrite mult_1_r; repeat rewrite plus_0_r; trivial; try congruence; try omega.\n\nLemma ratCD_comm : forall r1 r2 n1 n2 d n1' n2' d',\n  ratCD r1 r2 = (n1, n2, d) ->\n  ratCD r2 r1 = (n1', n2', d') ->\n  n1 = n2' /\\ n1' = n2 /\\ (posnatEq d d').\n\n  rattac.\nQed.\n\nInfix \"*\" := ratMult : rat_scope.\nLocal Open Scope rat_scope.\n\n\nNotation \"n / d\" := (RatIntro n (pos d)) : rat_scope.\n\nNotation \"0\" := rat0 : rat_scope.\nNotation \"1\" := rat1 : rat_scope.\n\nInfix \"+\" := ratAdd : rat_scope.\n\nDelimit Scope rat_scope with rat.\n\nNotation \" |  a - b |\" := (ratDistance a%rat b%rat) (at level 30, a at next level, b at next level) : rat_scope.\n\nInfix \"<=\" := leRat : rat_scope.\nInfix \"==\" := eqRat (at level 70) : rat_scope.\n\n\nTheorem le_Rat_dec : forall r1 r2,\n  {r1 <= r2} + {~r1 <= r2}.\n\n  intuition.\n  case_eq (bleRat r1 r2); intuition.\n  right.\n  intuition.\n  congruence.\nQed.\n\nTheorem eq_Rat_dec : forall r1 r2,\n  {r1 == r2} + {~r1 == r2}.\n\n  intuition.\n  case_eq (beqRat r1 r2); intuition.\n  right.\n  intuition.\n  congruence.\nQed.\n\nTheorem eqRat_refl : forall r,\n  eqRat r r.\n\n  rattac.\nQed.\n\nTheorem eqRat_symm : forall r1 r2,\n  eqRat r1 r2 ->\n  eqRat r2 r1.\n\n  rattac.\nQed.\n\nTheorem eqRat_trans : forall r1 r2 r3,\n  eqRat r1 r2 ->\n  eqRat r2 r3 ->\n  eqRat r1 r3.\n\n  rattac.\n  match goal with H:_, G:_ |- _ => ring [H G] end.\nQed.\n\nTheorem leRat_refl : forall r,\n  leRat r r.\n\n  rattac.\nQed.\n\nLemma mult_le_compat_r_iff_h : forall n2 n3 n1,\n    n1 > O ->\n    (n2 * n1 <= n3 * n1)%nat ->\n    (n2 <= n3)%nat.\n  \n  induction n2; destruct n3; intuition; simpl in *; try omega.\n  \n  exfalso.\n  remember (n2 * n1)%nat as x.\n  omega.\n\n  eapply le_n_S.\n  eapply IHn2; eauto.\n  omega.\nQed.\n\nLemma mult_le_compat_r_iff : forall n1 n2 n3,\n    n1 > O ->\n    (n2 * n1 <= n3 * n1)%nat ->\n    (n2 <= n3)%nat.\n  \n  intuition.\n  eapply mult_le_compat_r_iff_h; eauto.\nQed.\n\nTheorem leRat_trans : forall r1 r2 r3,\n  leRat r1 r2 ->\n  leRat r2 r3 ->\n  leRat r1 r3.\n\n  rattac.\n\n  eapply (@mult_le_compat_r_iff x1); trivial.\n  rewrite <- mult_assoc.\n  rewrite (mult_comm x).\n  rewrite mult_assoc.\n  eapply le_trans.\n  eapply mult_le_compat.\n  eapply l.\n  eauto.\n\n  repeat rewrite <- mult_assoc.\n  repeat rewrite (mult_comm x0).\n  repeat rewrite mult_assoc.\n  eapply mult_le_compat; eauto.\nQed.\n\nTheorem eqRat_impl_leRat : forall r1 r2,\n  eqRat r1 r2 ->\n  leRat r1 r2.\n\n  rattac.\nQed.\n\nTheorem leRat_impl_eqRat : forall r1 r2,\n  leRat r1 r2 ->\n  leRat r2 r1 ->\n  eqRat r1 r2.\n\n  rattac.\nQed.\n\n\nRequire Import Setoid.\n\n(*\nDefinition eqRat_setoid : Setoid_Theory Rat eqRat.\neconstructor; red.\neapply eqRat_refl.\neapply eqRat_symm.\neapply eqRat_trans.\nDefined.\n*)\n\nAdd Parametric Relation : Rat leRat\n  reflexivity proved by leRat_refl\n  transitivity proved by leRat_trans\n    as leRat_rel.\n\nAdd Parametric Relation : Rat eqRat \n  reflexivity proved by eqRat_refl\n  symmetry proved by eqRat_symm\n  transitivity proved by eqRat_trans\n  as eqRat_rel.\n\nRequire Import RelationClasses.\nRequire Import Coq.Classes.Morphisms.\n\nGlobal Instance Subrelation_eq_le : subrelation eqRat leRat.\nrepeat red.\nintuition.\neapply eqRat_impl_leRat.\ntrivial.\nQed.\n\nGlobal Instance eqRat_resp_leRat : \n  forall x,\n    Proper (eqRat ==> Basics.flip Basics.impl)\n                                  (leRat x).\n\nintuition.\nrepeat red; intuition.\nsimpl.\nunfold respectful.\nintuition.\neapply leRat_trans.\neapply H0.\neapply eqRat_impl_leRat.\nsymmetry.\ntrivial.\n\nQed.\n\nLocal Open Scope rat_scope.\nTheorem rat0_le_all : forall r,\n  0 <= r.\n\n  rattac.\nQed.\n\nTheorem rat1_ne_rat0 : ~ (eqRat 1 0).\n  intuition.\nQed.\n\nTheorem rat0_ne_rat1 : ~ (eqRat 0 1).\n  intuition.\nQed.\n\nTheorem ratAdd_comm : forall r1 r2,\n  r1 + r2 == r2 + r1.\n \n  rattac.\nQed.\n\nTheorem ratAdd_0_r : forall r,\n  r == r + 0.\n\n  rattac;\n  inversion H;\n  subst;\n  rewrite mult_1_r;\n  trivial.\nQed.\n\nTheorem ratAdd_0_l : forall r,\n  r == 0 + r.\n\n  intuition.\n  rewrite ratAdd_comm.\n  apply ratAdd_0_r.\nQed.\n\nTheorem ratMult_comm : forall (r1 r2 : Rat),\n  eqRat (ratMult r1 r2) (ratMult r2 r1).\n\n  rattac.\nQed.\n\nTheorem ratAdd_assoc : forall r1 r2 r3,\n  r1 + r2 + r3 == r1 + (r2 + r3).\n\n  rattac. \n  inversion H; clear H; subst.\n\n  Local Open Scope nat_scope.\n\n  Ltac arithNormalize_step :=\n    repeat rewrite mult_succ_r in *;\n      repeat rewrite mult_plus_distr_r in *;\n        repeat rewrite mult_plus_distr_l in *;\n          repeat rewrite mult_minus_distr_r in *;\n            repeat rewrite mult_minus_distr_l in *;\n              repeat rewrite plus_assoc in *;\n                repeat rewrite mult_assoc in *.\n\n  Ltac arithNormalize := repeat arithNormalize_step.\n\n  Ltac arithSimplify :=\n    match goal with\n      | [|- _ + ?x = _ + ?x] => f_equal\n      | [|- _ + (?x1 * ?x2) = _ + (?x2 * ?x1) ] => f_equal\n      | [|- _ + (?x1 * ?x2 * ?x3) = _ + (?x1 * ?x3 * ?x2) ] => f_equal\n      | [|- _ + (?x1 * ?x2 * ?x3 * ?x4 * ?x5 * ?x6) = _ + (?x1 * ?x3 * ?x2 * ?x4 * ?x5 * ?x6) ] => f_equal\n      | [|- _ * ?x1 = _ * ?x1] => f_equal\n      | [|- _ * ?x = _ ] => rewrite mult_comm; repeat rewrite mult_assoc; arithSimplify\n      | [|- _ + ?x = _ ] => rewrite plus_comm; repeat rewrite plus_assoc; arithSimplify\n      | [|- _ * ?x1 <= _ * ?x1] => apply mult_le_compat; auto\n      | [|- _ * ?x1 <= _ * ?x1] => apply plus_le_compat; auto\n      | [|- _ * ?x <= _ ] => rewrite mult_comm; repeat rewrite mult_assoc; arithSimplify\n      | [|- _ + ?x <= _ ] => rewrite plus_comm; repeat rewrite plus_assoc; arithSimplify\n      \n    end.\n\n  arithNormalize.\n  arithSimplify.\n  arithSimplify.\n  do 5 arithSimplify.\n  do 5 arithSimplify.\nQed.\n\nLocal Open Scope rat_scope.\nTheorem ratMult_assoc : forall r1 r2 r3,\n  r1 * r2 * r3 == r1 * (r2 * r3).\n\n  rattac;\n\n  inversion H0; clear H0; subst;\n  inversion H; clear H; subst;\n  arithNormalize;\n  arithSimplify.\n  \nQed.\n\nLemma ratAdd_eqRat_compat_l : forall r1 r2 r3,\n  eqRat r1 r2 ->\n  r1 + r3 == r2 + r3.\n\n  rattac.\n  arithNormalize.\n  f_equal.\n  f_equal.\n  rewrite mult_comm.\n  rewrite (mult_comm _ x1).\n  repeat rewrite mult_assoc.\n  f_equal.\n  rewrite mult_comm.\n  rewrite e.\n  apply mult_comm.\n  do 3 arithSimplify.\nQed.\n\nTheorem ratAdd_eqRat_compat : forall r1 r2 r3 r4,\n  eqRat r1 r2 ->\n  eqRat r3 r4 ->\n  r1 + r3 == r2 + r4.\n\n  intuition.\n  eapply eqRat_trans.\n  eapply ratAdd_eqRat_compat_l; eauto.\n  repeat rewrite (ratAdd_comm r2).\n  eapply ratAdd_eqRat_compat_l; eauto.\nQed.\n\nLemma ratAdd_leRat_compat_l : forall r1 r2 r3,\n  leRat r1 r2 ->\n  r1 + r3 <= r2 + r3.\n\n  rattac.\n  \n  unfold leRat, bleRat in *.\n  rattac.\n  arithNormalize.  \n  apply plus_le_compat.\n\n  apply mult_le_compat; trivial.\n  repeat rewrite <- mult_assoc.\n  repeat rewrite (mult_comm x0).\n  repeat rewrite mult_assoc.\n  apply mult_le_compat; trivial.\n  \n  apply mult_le_compat; trivial.\n  rewrite <- mult_assoc.\n  rewrite (mult_comm x1).\n  rewrite mult_assoc.\n  apply mult_le_compat; trivial.  \nQed.\n\nTheorem ratAdd_leRat_compat : forall r1 r2 r3 r4,\n  leRat r1 r2 ->\n  leRat r3 r4 ->\n  r1 + r3 <= r2 + r4.\n\n  intuition.\n  eapply leRat_trans.\n\n  eapply ratAdd_leRat_compat_l; eauto.\n  rewrite ratAdd_comm.\n\n  eapply leRat_trans.\n  apply ratAdd_leRat_compat_l; eauto.\n  rewrite ratAdd_comm.\n  intuition.\nQed.\n\nTheorem ratMult_leRat_compat : forall (r1 r2 r3 r4 : Rat),\n  leRat r1 r2 ->\n  leRat r3 r4 ->\n  leRat (ratMult r1 r3) (ratMult r2 r4).\n\n  rattac.\n  nia.\nQed.\n\nAdd Parametric Morphism : ratAdd\n  with signature (leRat ==> leRat ==> leRat)\n  as ratAdd_leRat_mor.\n\n  intuition.\n  eapply ratAdd_leRat_compat; trivial.\nQed.\n\nAdd Parametric Morphism : ratAdd\n  with signature (eqRat ==> eqRat ==> eqRat)\n  as ratAdd_eqRat_mor.\n\n  intuition.\n  eapply ratAdd_eqRat_compat; trivial.\nQed.\n\nTheorem ratMult_eqRat_compat : forall (r1 r2 r3 r4 : Rat),\n  eqRat r1 r2 ->\n  eqRat r3 r4 ->\n  eqRat (ratMult r1 r3) (ratMult r2 r4).\n\n  rattac.\n  \n  repeat rewrite mult_assoc.\n  rewrite <- (mult_assoc n1).\n  rewrite (mult_comm n).\n  rewrite mult_assoc.\n  rewrite <- mult_assoc.\n  rewrite e.\n  rewrite e0.\n  rewrite mult_assoc.\n  do 3 arithSimplify.\n\nQed.\n\nAdd Parametric Morphism : ratMult\n  with signature (leRat ==> leRat ==> leRat)\n  as ratMult_leRat_mor.\n\n  intuition.\n  eapply ratMult_leRat_compat; trivial.\nQed.\n\nAdd Parametric Morphism : ratMult\n  with signature (eqRat ==> eqRat ==> eqRat)\n  as ratMult_eqRat_mor.\n\n  intuition.\n  eapply ratMult_eqRat_compat; trivial.\nQed.\n\n\nTheorem ratAdd_0 : forall r1 r2,\n  r1 + r2 == 0 <->\n  r1 == 0 /\\ r2 == 0.\n\n  intuition.\n  rattac.\n  rewrite mult_0_l in e.\n  unfold posnatToNat in *.\n  simpl in *.\n  destruct p1.\n  destruct p0.\n  rewrite mult_1_r in e.\n  apply plus_is_O in e.\n  intuition.\n  eapply mult_is_O in H0.\n  intuition.\n  \n  rattac.\n  rewrite mult_0_l in e.\n  unfold posnatToNat in *.\n  simpl in *.\n  destruct p1.\n  destruct p0.\n  rewrite mult_1_r in e.\n  apply plus_is_O in e.\n  intuition.\n  eapply mult_is_O in H1.\n  intuition.\n\n  rewrite (ratAdd_0_r 0).\n  eapply ratAdd_eqRat_compat; eauto.\nQed.\n\nTheorem ratAdd_nz : forall r1 r2,\n  ~(r1 + r2 == 0) <->\n  (~r1 == 0) \\/ (~r2 == 0).\n\n\n  intuition.\n  destruct (eq_Rat_dec r1 0); intuition.\n  destruct (eq_Rat_dec r2 0); intuition.\n  exfalso.\n  eapply H.\n  apply ratAdd_0; eauto.\n \n  apply H1.\n  specialize (ratAdd_0 r1 r2); intuition.\n\n  apply H1.\n  specialize (ratAdd_0 r1 r2); intuition.\nQed.\n\nTheorem rat_num_0 : forall d,\n  (RatIntro O d) == 0.\n\n  rattac.\nQed.\n\nLemma ratMult_0_l : forall r,\n  0 * r == 0.\n  \n  intuition; destruct r.\n  unfold ratMult.\n  simpl.\n  unfold natToPosnat, posnatMult; simpl.\n  destruct p.\n  apply rat_num_0.\nQed.\n\nLemma ratMult_0_r : forall r,\n  r * 0 == 0.\n  \n  rattac.\nQed.\n\nLemma ratMult_1_l : forall r,\n  1 * r == r.\n  \n  rattac.\n  inversion H; clear H; subst.\n  repeat rewrite mult_1_l in *.\n  trivial.\nQed.\n\nTheorem ratMult_0 : forall r1 r2,\n  r1 * r2 == 0 <-> \n  r1 == 0 \\/ r2 == 0.\n\n  intuition.\n  rattac.\n  rewrite mult_0_l in e.\n  unfold posnatToNat in *.\n  simpl in *.\n  rewrite mult_1_r in e.\n  apply mult_is_O in e.\n  intuition; subst.\n  left.\n  apply rat_num_0.\n  \n  right.\n  apply rat_num_0.\n\n  rewrite <- (ratMult_0_l r2).\n  eapply ratMult_eqRat_compat; intuition.\n\n  rewrite <- (ratMult_0_r r1).\n  eapply ratMult_eqRat_compat; intuition.\nQed.\n\nTheorem ratMult_nz : forall r1 r2,\n  (~r1 * r2 == 0) <->\n  (~r1 == 0) /\\ (~r2 == 0).\n\n  intuition.\n  \n  eapply H.\n  specialize (ratMult_0 r1 r2); intuition.\n\n  eapply H.\n  specialize (ratMult_0 r1 r2); intuition.\n\n  apply ratMult_0 in H0.\n  intuition.\n\nQed.\n\nTheorem leRat_num : forall n1 n2 d,\n  le n1 n2 ->\n  leRat (RatIntro n1 d) (RatIntro n2 d).\n\n  rattac.\n  eapply mult_le_compat; eauto.\nQed.\n\n\nTheorem eqRat_terms : forall n1 d1 n2 d2,\n  n1 = n2 ->\n  posnatToNat d1 = posnatToNat d2 ->\n  eqRat (RatIntro n1 d1) (RatIntro n2 d2).\n\n  rattac.\nQed.\n\nLemma leRat_mult : forall n1 n2 d1 d2 (pf1 : d1 > 0) (pf2 : d2 > 0),\n                     RatIntro n1 (exist (fun d => d > 0) _ pf1) <= RatIntro n2 (exist (fun d => d > 0) _ pf2) ->\n                     (n1 * d2 <= n2 * d1)%nat.\n  \n  rattac.\nQed.\n\nLemma nat_minus_eq : forall (n1 n2 : nat),\n                       (n1 <= n2)%nat ->\n                       n2 - n1 = O ->\n                       n1 = n2.\n\n  intuition. \nQed.\n\n\nLemma bleRat_total : forall r1 r2,\n                       bleRat r1 r2 = false -> bleRat r2 r1 = true.\n  \n  intuition.\n  unfold bleRat in *.\n  rattac.\nQed.\n\nTheorem ratIdentityIndiscernables : forall r1 r2,\n  r1 == r2 <->\n  ratDistance r1 r2 == rat0.\n\n  rattac;\n  unfold ratDistance, ratSubtract in *;\n  rattac;\n  unfold minRat, maxRat in *;\n  rattac.\n  case_eq (bleRat (RatIntro n (exist (fun n : nat => n > 0) x2 g2))\n             (RatIntro n0 (exist (fun n : nat => n > 0) x1 g1))); intuition.\n  rewrite H1 in H2.\n  rewrite H1 in H0.\n  rattac.\n\n  rewrite H1 in H2.\n  rewrite H1 in H0.\n  rattac.\n\n  case_eq (bleRat (RatIntro n0 (exist (fun n : nat => n > 0) x0 g0))\n             (RatIntro n1 (exist (fun n : nat => n > 0) x g))); intuition.\n  rewrite H0 in H1.\n  rewrite H0 in H2.\n  rattac.\n  inversion e; clear e; subst.\n  apply mult_is_O in H2; intuition.\n  unfold posnatMult in *.\n  inversion H5; clear H5; subst.\n  assert ((RatIntro n4 (exist (fun n : nat => n > 0) x0 g0)) <= (RatIntro n3 (exist (fun n : nat => n > 0) x g))).\n  unfold leRat.\n  trivial.\n  \n  eapply nat_minus_eq.\n  apply (leRat_mult H2).\n  trivial.\n\n  rewrite H0 in H1.\n  rewrite H0 in H2.\n  rattac.\n  unfold posnatMult in *.\n  simpl in *.\n  inversion H5; clear H5; subst.\n  apply mult_is_O in e. intuition.\n  symmetry.\n  eapply nat_minus_eq; trivial.\n\n  apply bleRat_total in H0.\n  assert (leRat (RatIntro n4 (exist (fun n : nat => n > 0) x g))\n         (RatIntro n3 (exist (fun n : nat => n > 0) x0 g0))).\n  apply H0.\n  apply (leRat_mult H2).\nQed.\n\n(* is this even true ? \nLemma ratDistance_comm_2 : forall r1 r2 r3 r4,\n    ratDistance (ratDistance r1 r2) (ratDistance r3 r4) ==\n    ratDistance (ratDistance r1 r3) (ratDistance r2 r4).\n\n    intuition.\n    \n    unfold ratDistance, ratSubtract.\n    rattac.\n    arithNormalize.\n\n    Lemma minus_eq_compat : forall n1 n2 n3 n4,\n      n1 = n2 ->\n      n3 = n4 ->\n      n1 - n3 = n2 - n4.\n\n      intuition.\n    Qed.\n\n    apply minus_eq_compat.\n    arithSimplify.\n    rewrite (mult_comm _ x).\n    arithNormalize.\n    arithSimplify.\n    unfold minRat, maxRat in *.\n    case_eq (bleRat (RatIntro (n7 * p8 - n8 * p7) (posnatMult p7 p8))\n            (RatIntro (n9 * p10 - n10 * p9) (posnatMult p9 p10))); intuition;\n    case_eq ( bleRat (RatIntro (n3 * p4 - n4 * p3) (posnatMult p3 p4))\n             (RatIntro (n5 * p6 - n6 * p5) (posnatMult p5 p6))); intuition.\n    case_eq (bleRat (RatIntro (n7 * p8 - n8 * p7) (posnatMult p7 p8))\n             (RatIntro (n9 * p10 - n10 * p9) (posnatMult p9 p10))); intuition.\n    case_eq (bleRat (RatIntro (n3 * p4 - n4 * p3) (posnatMult p3 p4))\n             (RatIntro (n5 * p6 - n6 * p5) (posnatMult p5 p6))); intuition.\n    rewrite H11 in H.\n    rewrite H12 in H1.\n    rewrite H13 in H0.\n    rewrite H14 in H2.\n\n    inversion H; clear H; subst.\n    inversion H0; clear H0; subst.\n    inversion H1; clear H1; subst.\n    inversion H2; clear H2; subst.\n\n    unfold posnatMult in *.\n    destruct p9; destruct p10.\n    destruct p5; destruct p6.\n    destruct p7; destruct p8.\n    destruct p3; destruct p4.\n    simpl in *.\n    inversion H1; clear H1; subst.\n    inversion H15; clear H15; subst.\n    inversion H16; clear H16; subst.\n    inversion H17; clear H17; subst.\n\n    unfold minRat in *.\n\n    destruct p7.\n\n    SearchAbout minus.\n    rattac_one.\n    rattac_one.\n  Abort.\n*)\n\nLemma ratSubtract_partition : forall r1 r2 r3,\n  r1 <= r2 ->\n  r2 <= r3 ->\n  (ratSubtract r3 r1) == (ratSubtract r2 r1) + (ratSubtract r3 r2).\n\n  rattac.\n  unfold ratSubtract in *.\n  rattac.\n  arithNormalize.\n  rewrite <- NPeano.Nat.add_sub_swap.\n  eapply minus_eq_compat.\n  rewrite minus_add_assoc.\n  rewrite plus_comm.\n  rewrite <- minus_add_assoc.\n  rewrite <- plus_0_r at 1.\n  apply plus_eq_compat.\n  do 4 arithSimplify.\n  symmetry.\n  eapply minus_diag_eq.\n  do 4 arithSimplify.\n  apply le_eq.\n  do 5 arithSimplify.\n  do 4 (apply mult_le_compat; trivial).\n  do 4 arithSimplify.\n  do 4 (apply mult_le_compat; trivial).\n\nQed.\n\nLemma ratAdd_any_leRat_l : forall r1 r2 r3,\n  r1 <= r3 ->\n  r1 <= r3 + r2.\n  \n  rattac.\n  arithNormalize.\n  assert (n * x * x0 <= n0 * x0 * x1)%nat.\n  rewrite (mult_comm (n0 * x0) x1).\n  rewrite mult_assoc.\n  apply mult_le_compat; trivial.\n  rewrite (mult_comm x1).\n  trivial.\n  rewrite <- plus_0_r at 1.\n  apply plus_le_compat; eauto.\n  apply le_0_n.\nQed.\n\nLemma ratAdd_any_leRat_r : forall r1 r2 r3,\n  r1 <= r2 ->\n  r1 <= r3 + r2.\n  \n  intuition.\n  eapply leRat_trans.\n  Focus 2.\n  eapply eqRat_impl_leRat.\n  apply ratAdd_comm.\n  apply ratAdd_any_leRat_l; eauto.\nQed.\n\nLemma ratAdd_eq_impl_leRat_l : forall r1 r2 r3,\n  r1 == r2 + r3 ->\n  r2 <= r1.\n  \n  intuition.\n  eapply leRat_trans.\n  Focus 2.\n  eapply eqRat_impl_leRat.\n  eapply eqRat_symm.\n  eapply H.\n  apply ratAdd_any_leRat_l.\n  apply leRat_refl.\nQed.\n\nLemma ratAdd_eq_impl_leRat_r : forall r1 r2 r3,\n  r1 == r2 + r3 ->\n  r3 <= r1.\n  \n  intuition.\n  eapply leRat_trans.\n  Focus 2.\n  eapply eqRat_impl_leRat.\n  eapply eqRat_symm.\n  eapply H.\n  apply ratAdd_any_leRat_r.\n  apply leRat_refl.\nQed.\n\nLemma ratSubtract_leRat_r : forall r1 r2 r3,\n  r1 <= r2 ->\n  ratSubtract r3 r2 <= ratSubtract r3 r1.\n  \n  rattac.\n  unfold ratSubtract in *.\n  rattac.\n  unfold posnatMult in *.\n  inversion H4; clear H4; subst.\n  inversion H3; clear H3; subst.\n  arithNormalize.\n  assert (n * x3 * x3 * x1 <= n0 * x3 * x3 * x2)%nat.\n  rewrite <- mult_comm.\n  rewrite <- (mult_comm x2).\n  repeat rewrite mult_assoc.\n  eapply mult_le_compat; trivial.\n  eapply mult_le_compat; trivial.\n  rewrite mult_comm.\n  rewrite l.\n  rewrite mult_comm.\n  trivial.\n  assert (n3 * x1 * x3 * x2 = n3 * x2 * x3 * x1)%nat.\n  do 3 arithSimplify.\n  omega.\n  \nQed.\n\nLemma ratSubtract_leRat_l:\n  forall r1 r2 r3 : Rat, r1 <= r2 -> ratSubtract r1 r3 <= ratSubtract r2 r3.\n  \n  rattac.\n  unfold ratSubtract in *.\n  rattac.\n  unfold posnatMult in *.\n  inversion H4; clear H4; subst.\n  inversion H3; clear H3; subst.\n  arithNormalize.\n  \n  assert (n * x3 * x1 * x3 <= n0 * x3 * x2 * x3)%nat.\n  apply mult_le_compat; trivial.\n  rewrite <- (mult_comm x1).\n  rewrite <- (mult_comm x2).\n  repeat rewrite mult_assoc.\n  apply mult_le_compat; trivial.\n  rewrite mult_comm.\n  rewrite l.\n  rewrite mult_comm.\n  trivial.\n  \n  assert (n3 * x2 * x1 * x3 = n3 * x1 * x2 * x3)%nat.\n  do 3 arithSimplify.\n  omega.\nQed.\n\nLemma ratSubtract_leRat : forall r1 r2 r3 r4,\n  r1 <= r2 ->\n  r3 <= r4 ->\n  ratSubtract r1 r4 <= ratSubtract r2 r3.\n  \n  intuition.\n  eapply leRat_trans.\n  eapply ratSubtract_leRat_l; eauto.\n  eapply ratSubtract_leRat_r; eauto.\nQed.\n\nLemma ratSubtract_0 : forall r1 r2,\n  r1 <= r2 ->\n  ratSubtract r1 r2 == 0.\n  \n  intuition.\n  unfold ratSubtract.\n  rattac.\n  inversion l; clear l; subst.\n  omega.\n  rewrite H0.\n  unfold posnatToNat in *.\n  \n  omega.\nQed.\n\nLemma ratSubtract_partition_leRat : forall r3 r1 r2 d1 d2,\n  ratSubtract r1 r3 <= d1 ->\n  ratSubtract r3 r2 <= d2 -> \n  ratSubtract r1 r2 <= d1 + d2.\n  \n  intuition.\n  case_eq (bleRat r3 r1); intuition.\n  case_eq (bleRat r2 r3); intuition.\n  rewrite ratSubtract_partition; eauto.\n  rewrite ratAdd_comm.\n  eapply ratAdd_leRat_compat;\n    intuition.\n  eapply bleRat_total in H2.\n  rewrite ratAdd_0_r.\n  eapply ratAdd_leRat_compat.\n  eapply leRat_trans; eauto.\n  eapply ratSubtract_leRat;\n    intuition.\n  eapply rat0_le_all.\n  \n  apply bleRat_total in H1.\n  case_eq (bleRat r2 r3); intuition.\n  rewrite ratAdd_0_l.\n  eapply ratAdd_leRat_compat.\n  eapply rat0_le_all.\n  eapply leRat_trans; eauto.\n  eapply ratSubtract_leRat;\n    intuition.\n  \n  apply bleRat_total in H2.\n  rewrite ratSubtract_0.\n  eapply rat0_le_all.\n  eapply leRat_trans; eauto.\n  \nQed.\n\nTheorem ratTriangleInequality : forall r1 r2 r3,\n  (ratDistance r1 r2) <= (ratDistance r1 r3) + (ratDistance r3 r2).\n\n  intuition.\n  unfold ratDistance, maxRat, minRat in *.\n  case_eq (bleRat r1 r3); intuition.\n  case_eq (bleRat r3 r2); intuition.\n  assert (bleRat r1 r2 = true).\n  eapply leRat_trans; eauto.\n  rewrite H1.\n\n  eapply leRat_trans.\n  Focus 2.\n  eapply eqRat_impl_leRat.\n  eapply ratAdd_comm.\n  eapply ratSubtract_partition_leRat; eapply leRat_refl.\n\n  case_eq (bleRat r1 r2); intuition.  \n  apply bleRat_total in H0.\n  eapply leRat_trans.\n  Focus 2.\n  eapply eqRat_impl_leRat.\n  eapply ratAdd_comm.\n  eapply ratSubtract_partition_leRat.\n  eapply ratSubtract_leRat; eauto.\n  intuition.\n\n  apply bleRat_total in H1.\n  apply bleRat_total in H0.\n  eapply ratSubtract_partition_leRat.\n  rewrite ratSubtract_0.\n  eapply rat0_le_all.\n  eapply leRat_refl.\n  eapply ratSubtract_leRat; intuition.\n\n  apply bleRat_total in H.\n  case_eq (bleRat r1 r2); intuition.\n  assert (bleRat r3 r2 = true).\n  eapply leRat_trans; eauto.\n  rewrite H1.\n  apply ratAdd_any_leRat_r.\n  eapply ratAdd_eq_impl_leRat_r.\n  eapply ratSubtract_partition; eauto.\n\n  apply bleRat_total in H0.\n  case_eq (bleRat r3 r2); intuition.\n  apply ratAdd_any_leRat_l.\n  eapply ratAdd_eq_impl_leRat_r.\n  eapply ratSubtract_partition; eauto.\n\n  apply bleRat_total in H1.\n  eapply eqRat_impl_leRat.\n  rewrite ratAdd_comm.\n  eapply ratSubtract_partition; eauto.\nQed.\n\nTheorem ratMult_1_r : forall r,\n  r * 1 == r.\n\n  intuition.\n  rewrite ratMult_comm.\n  apply ratMult_1_l.\n  \nQed.\n\nLemma minus_le : forall n1 n2 n3,\n    (n1 <= n3 ->\n     n1 - n2 <= n3)%nat.\n  \n  intuition.\nQed.\n\nTheorem ratSubtract_le : forall r1 r2 d,\n  r1 <= d ->\n  ratSubtract r1 r2 <= d.\n\n  intuition.\n\n  unfold ratSubtract.\n  rattac.\n  arithNormalize.\n\n  apply minus_le.\n  rewrite <- (mult_assoc n).\n  rewrite (mult_comm x0).\n  rewrite mult_assoc.\n  apply mult_le_compat; trivial.\n\nQed.\n\n\nTheorem ratDistance_le_trans : forall r1 r2 r3 d1 d2,\n  ratDistance r1 r2 <= d1 ->\n  ratDistance r2 r3 <= d2 ->\n  ratDistance r1 r3 <= d1 + d2.\n\n  intuition.\n\n  eapply leRat_trans.\n  eapply ratTriangleInequality.\n  eapply ratAdd_leRat_compat; eauto.\nQed.\n\n\nTheorem ratDistance_le : forall r1 r2 d,\n  r1 <= d ->\n  r2 <= d ->\n  (ratDistance r1 r2) <= d.\n\n  intuition.\n  unfold ratDistance, maxRat, minRat.\n  case_eq (bleRat r1 r2); intuition;\n  apply ratSubtract_le; eauto.\nQed.\n\nLemma ratSubtract_eqRat_compat : forall r1 r2 r3 r4,\n  r1 == r3 ->\n  r2 == r4 ->\n  ratSubtract r1 r2 == ratSubtract r3 r4.\n\n  intuition.\n  unfold ratSubtract.\n  rattac.\n  inversion e0; clear e0; subst.\n  inversion e; clear e; subst.\n  arithNormalize.\n  apply minus_eq_compat.\n  arithSimplify.\n  rewrite <- (mult_assoc n1).\n  rewrite (mult_comm x2).\n  rewrite mult_assoc.\n  arithSimplify.\n  trivial.\n\n  rewrite <- (mult_assoc (n2 * x1)).\n  rewrite (mult_comm x).\n  rewrite mult_assoc.\n  arithSimplify.\n  rewrite <- (mult_assoc n2).\n  rewrite (mult_comm x1 x0).\n  rewrite mult_assoc.\n  arithSimplify.\n  rewrite mult_comm.\n  trivial.\nQed.\n\nAdd Parametric Morphism : ratSubtract\n  with signature (eqRat ==> eqRat ==> eqRat)\n  as ratSubtract_eqRat_mor.\n\n  intuition.\n  eapply ratSubtract_eqRat_compat; trivial.\nQed.\n\nTheorem leRat_antisymm : forall r1 r2,\n  r1 <= r2 ->\n  r2 <= r1 ->\n  r1 == r2.\n\n  rattac.\nQed.\n\nLemma maxRat_eqRat_compat : forall r1 r2 r3 r4,\n  r1 == r3 ->\n  r2 == r4 ->\n  maxRat r1 r2 == maxRat r3 r4.\n\n  intuition.\n  unfold maxRat.\n  case_eq (bleRat r1 r2); intuition;\n  case_eq (bleRat r3 r4); intuition.\n  apply bleRat_total in H2.\n  eapply leRat_impl_eqRat;\n  eauto using leRat_trans, eqRat_impl_leRat, eqRat_symm.\n  \n  apply bleRat_total in H1.\n  eapply leRat_impl_eqRat;\n  eauto using leRat_trans, eqRat_impl_leRat, eqRat_symm.\nQed.\n\nAdd Parametric Morphism : maxRat\n  with signature (eqRat ==> eqRat ==> eqRat)\n  as maxRat_eqRat_mor.\n\n  intuition.\n  eapply maxRat_eqRat_compat; trivial.\nQed.\n\n\nLemma minRat_eqRat_compat : forall r1 r2 r3 r4,\n  r1 == r3 ->\n  r2 == r4 ->\n  minRat r1 r2 == minRat r3 r4.\n\n  intuition.\n  unfold minRat.\n  case_eq (bleRat r1 r2); intuition;\n  case_eq (bleRat r3 r4); intuition.\n  apply bleRat_total in H2.\n  eapply leRat_impl_eqRat;\n  eauto using leRat_trans, eqRat_impl_leRat, eqRat_symm.\n  \n  apply bleRat_total in H1.\n  eapply leRat_impl_eqRat;\n  eauto using leRat_trans, eqRat_impl_leRat, eqRat_symm.\nQed.\n\nAdd Parametric Morphism : minRat\n  with signature (eqRat ==> eqRat ==> eqRat)\n  as minRat_eqRat_mor.\n\n  intuition.\n  eapply minRat_eqRat_compat; trivial.\nQed.\n\nTheorem ratDistance_eqRat_compat : forall r1 r2 r3 r4,\n  r1 == r3 ->\n  r2 == r4 ->\n  ratDistance r1 r2 == ratDistance r3 r4.\n\n  intuition.\n  unfold ratDistance.\n  eauto using ratSubtract_eqRat_compat, maxRat_eqRat_compat, minRat_eqRat_compat.\nQed.\n\nAdd Parametric Morphism : ratDistance\n  with signature (eqRat ==> eqRat ==> eqRat)\n  as ratDistance_eqRat_mor.\n\n  intuition.\n  eapply ratDistance_eqRat_compat; trivial.\nQed.\n\nLemma ratSubtract_add_same_r : forall r1 r2 r3,\n  r1 <= r3 ->\n  ratSubtract (r3 + r2) (r1 + r2) == ratSubtract r3 r1.\n  \n  intuition.\n  unfold ratSubtract.\n  rattac.\n  arithNormalize.\n  rewrite (plus_comm (n2 * x0 * x1 * x0 * x1 * x)).\n  rewrite NPeano.Nat.sub_add_distr.\n  apply minus_eq_compat.\n  rewrite <- NPeano.Nat.add_sub_assoc.\n  rewrite minus_diag_eq.\n  rewrite plus_0_r.\n  do 5 arithSimplify.\n  do 5 arithSimplify.\n  eapply le_eq.\n  do 5 arithSimplify.\n  do 5 arithSimplify.\nQed.\n\nLemma ratSubtract_add_same_l : forall r1 r2 r3,\n  r1 <= r3 ->\n  ratSubtract (r2 + r3) (r2 + r1) == ratSubtract r3 r1.\n  \n  intuition.\n  unfold ratSubtract.\n  rattac.\n  arithNormalize.\n  rewrite NPeano.Nat.sub_add_distr.\n  apply minus_eq_compat.\n  rewrite plus_comm.\n  rewrite <- NPeano.Nat.add_sub_assoc.\n  rewrite minus_diag_eq.\n  rewrite plus_0_r.\n  do 5 arithSimplify.\n  do 5 arithSimplify.\n  eapply le_eq.\n  do 5 arithSimplify.\n  do 5 arithSimplify.\nQed.\n\nLemma minus_plus_assoc : forall n1 n2 n3,\n  (n3 <= n2 ->\n    (n1 + n2) - n3 = n1 + (n2 - n3))%nat.\n  \n  intuition.\nQed.\n\nLemma ratSubtract_ratAdd_assoc: forall r1 r2 r3,\n  r3 <= r2 ->\n  ratSubtract (r1 + r2) r3 == r1 + (ratSubtract r2 r3).\n  \n  intuition.\n  unfold ratSubtract.\n  rattac.\n  arithNormalize.\n  rewrite  minus_plus_assoc.\n  f_equal.\n  f_equal.\n  do 5 arithSimplify.\n  do 5 arithSimplify.\n  do 3 (eapply mult_le_compat; trivial).\n  repeat rewrite <- mult_assoc.\n  repeat rewrite (mult_comm x).\n  repeat rewrite mult_assoc.\n  apply mult_le_compat; trivial.\nQed.\n\nLemma ratAdd_add_same_r : forall r1 r2 r3,\n  r1 + r2 == r3 + r2 ->\n  r1 == r3.\n  \n  intuition.\n  assert (ratSubtract (r1 + r2) r2 == ratSubtract (r3 + r2) r2).\n  eapply ratSubtract_eqRat_compat; intuition.\n  \n  rewrite ratSubtract_ratAdd_assoc in H0.\n  setoid_rewrite ratAdd_0_r.\n  eapply eqRat_trans.\n  eapply ratAdd_eqRat_compat.\n  eapply eqRat_refl.\n  eapply eqRat_symm.\n  apply (@ratSubtract_0 r2 r2).\n  eapply leRat_refl.\n  rewrite H0.\n  rewrite ratSubtract_ratAdd_assoc.\n  eapply ratAdd_eqRat_compat.\n  intuition.\n  apply ratSubtract_0.\n  eapply leRat_refl.\n  apply leRat_refl.\n  apply leRat_refl.\nQed.\n\nLemma ratAdd_add_same_l : forall r1 r2 r3,\n  r2 + r1 == r2 + r3 ->\n  r1 == r3.\n\n  intuition.\n  eapply ratAdd_add_same_r.\n  eapply eqRat_trans.\n  apply ratAdd_comm.\n  rewrite H.\n  apply ratAdd_comm.\nQed.\n\nLemma ratDistance_add_same_r : forall r1 r2 r3,\n  (ratDistance (r1 + r2) (r3 + r2)) == (ratDistance r1 r3).\n  \n  intuition.\n  unfold ratDistance, maxRat, minRat.\n  case_eq (bleRat r1 r3); intuition.\n  assert (r1 + r2 <= r3 + r2).\n  eapply ratAdd_leRat_compat; trivial.\n  eapply leRat_refl.\n  rewrite H0.\n  \n  apply ratSubtract_add_same_r; eauto.\n  \n  apply bleRat_total in H.\n  assert (r3 + r2 <= r1 + r2).\n  eapply ratAdd_leRat_compat; trivial.\n  apply leRat_refl.\n  \n  case_eq (bleRat (r1 + r2) (r3 + r2)); intuition.\n  assert (r1 + r2 == r3 + r2).\n  eapply leRat_antisymm; eauto.\n  repeat rewrite ratSubtract_0.\n  intuition.\n  eapply eqRat_impl_leRat.\n  \n  eapply ratAdd_add_same_r.\n  eauto.\n  eapply eqRat_impl_leRat.\n  eapply eqRat_symm.\n  trivial.\n  \n  apply ratSubtract_add_same_r; eauto.\nQed.\n\nLemma ratDistance_add_same_l : forall r1 r2 r3,\n  (ratDistance (r2 + r3) (r2 + r1)) == (ratDistance r3 r1).\n  \n  intuition.\n  unfold ratDistance, maxRat, minRat.\n  case_eq (bleRat r3 r1); intuition.\n  assert (r2 + r3 <= r2 + r1).\n  eapply ratAdd_leRat_compat; trivial.\n  eapply leRat_refl.\n  rewrite H0.\n  \n  apply ratSubtract_add_same_l; eauto.\n  \n  apply bleRat_total in H.\n  assert (r2 + r1 <= r2 + r3).\n  eapply ratAdd_leRat_compat; trivial.\n  apply leRat_refl.\n\n  case_eq (bleRat (r2 + r3) (r2 + r1)); intuition.\n  assert (r2 + r3 == r2 + r1).\n  eapply leRat_antisymm; eauto.\n  repeat rewrite ratSubtract_0.\n  intuition.\n  eapply eqRat_impl_leRat.\n\n  eapply ratAdd_add_same_l.\n  eauto.\n  eapply eqRat_impl_leRat.\n  eapply eqRat_symm.\n  trivial.\n  \n  apply ratSubtract_add_same_l; eauto.\n\nQed.\n\nTheorem rat_distance_of_sum : forall r1 r2 r3 r4,\n  ratDistance (r1 + r2) (r3 + r4) <= (ratDistance r1 r3) + (ratDistance r2 r4).\n\n  intuition.\n  eapply leRat_trans.\n  eapply (ratTriangleInequality _ _ (r3 + r2)).\n  eapply ratAdd_leRat_compat.\n  \n  eapply eqRat_impl_leRat.\n  eapply ratDistance_add_same_r.\n\n  eapply eqRat_impl_leRat.\n  eapply ratDistance_add_same_l.\n  \nQed.\n\nTheorem ratMult_distrib : forall r1 r2 r3,\n  r1 * (r2 + r3) == r1 * r2 + r1 * r3.\n\n  rattac.\n  inversion H1; clear H1; subst.\n  inversion H0; clear H0; subst.\n  inversion H; clear H; subst.\n  arithNormalize.\n  f_equal.\n  do 5 arithSimplify.\n  do 5 arithSimplify.\nQed.\n\n\nTheorem num_dem_same_rat1 : forall n d,\n  n = posnatToNat d ->\n  RatIntro n  d == rat1.\n\n  rattac.\n  inversion H0; clear H0; subst.\n  omega.\nQed.\n\nLemma ratAdd_num : forall n1 n2 d,\n  RatIntro (n1 + n2) d == (ratAdd (RatIntro n1 d) (RatIntro n2 d)).\n  \n  rattac.\n  arithNormalize.\n  trivial.\nQed.\n\nLemma ratMult_denom : forall n d1 d2,\n  (RatIntro n (posnatMult d1 d2)) == (ratMult (RatIntro 1 d1) (RatIntro n d2)).\n\n  rattac.\nQed.\n\nLemma ratMult_num_den : forall n1 n2 d1 d2,\n  (RatIntro (n1 * n2)%nat (posnatMult d1 d2)) == (RatIntro n1 d1) * (RatIntro n2 d2).\n  \n  intuition.\n  \n  unfold ratMult, natToPosnat, posnatMult.\n  eapply eqRat_refl.\nQed.\n\nTheorem ratAdd_den_same : forall n1 n2 d,\n  RatIntro (n1 + n2)%nat d == (RatIntro n1 d) + (RatIntro n2 d).\n  \n  rattac.\n  arithNormalize.\n  arithSimplify.\nQed.\n\nLemma rat_mult_den : forall n d1 d2,\n  (RatIntro n (posnatMult d1 d2)) == (RatIntro 1 d1) * (RatIntro n d2).\n  \n  intuition.\n  assert (n = 1 * n)%nat.\n  omega.\n  rewrite H at 1.\n  apply ratMult_num_den; omega.\nQed.\n\nLemma ratOneHalf_add: \n  1 / 2 + 1 / 2 == 1.\n  \n  unfold ratAdd.\n  simpl.\n  unfold posnatMult.\n  simpl.\n  apply (@num_dem_same_rat1 4 _).\n  simpl.\n  trivial.\nQed.\n\n\nTheorem ratS_num : forall n,\n  (S n) / (S O) == 1 + (n / (S O)).\n\n  rattac.\n  unfold natToPosnat in *.\n  inversion H0; clear H0; subst.\n  repeat rewrite mult_1_r.\n  inversion H; clear H; subst.\n  trivial.\nQed.\n\nTheorem ratDistance_comm : forall r1 r2,\n  eqRat (ratDistance r1 r2) (ratDistance r2 r1).\n\n  intuition.\n  unfold ratDistance, maxRat, minRat.\n  case_eq (bleRat r1 r2); case_eq (bleRat r2 r1); intuition.\n  apply ratSubtract_eqRat_compat;\n  eapply leRat_antisymm; eauto.\n\n  apply bleRat_total in H.\n  apply bleRat_total in H0.\n  apply ratSubtract_eqRat_compat;\n  eapply leRat_antisymm; eauto.\nQed.\n\nTheorem ratMult_distrib_r : forall r1 r2 r3,\n  ratMult (ratAdd r2 r3) r1  == ratAdd (ratMult r2 r1) (ratMult r3 r1).\n  \n  intuition.\n  rewrite ratMult_comm.\n  rewrite ratMult_distrib.\n  eapply ratAdd_eqRat_compat; eapply ratMult_comm.\nQed.\n\nLemma ratSubtract_ratAdd_inverse : forall r1 r2,\n  ratSubtract (r1 + r2) r1 == r2.\n  \n  intuition.\n  unfold ratSubtract.\n  rattac.\n  arithNormalize.\n  rewrite <- (mult_assoc (n1 * x)).\n  rewrite (mult_comm x x0).\n  rewrite mult_assoc.\n  remember (n1 * x * x0 * x)%nat as a.\n  repeat rewrite <- (mult_assoc n0).\n  rewrite (mult_comm x).\n  omega.\nQed.\n\nLemma ratSubtract_ratAdd_inverse_2 : forall r1 r2,\n  r2 <= r1 ->\n  r2 + ratSubtract r1 r2 == r1.\n  \n  intuition.\n  apply eqRat_symm.\n  eapply eqRat_trans.\n  Focus 2.\n  apply ratSubtract_ratAdd_assoc.\n  trivial.\n  apply eqRat_symm.\n  apply ratSubtract_ratAdd_inverse.\nQed.\n\nLemma leRat_difference_exists : forall r1 r2,\n  r2 <= r1 ->\n  exists r3, r1 == r2 + r3.\n  \n  intuition.\n  exists (ratSubtract r1 r2).\n  apply eqRat_symm.\n  apply ratSubtract_ratAdd_inverse_2.\n  trivial.\nQed.\n\nLemma ratSubtract_ratMult_le : forall r1 r2 r3 r4,\n  r1 <= r2 ->\n  r3 <= r4 ->\n  ratSubtract (r2 * r4) (r1 * r3) == (ratSubtract r2 r1) * r3 + (ratSubtract r4 r3) * r1 + (ratSubtract r2 r1) * (ratSubtract r4 r3).\n  \n  intuition.\n  destruct (leRat_difference_exists H).\n  destruct (leRat_difference_exists H0).\n  eapply eqRat_trans.\n  apply ratSubtract_eqRat_compat.\n  eapply eqRat_trans.\n  apply ratMult_eqRat_compat.\n  apply H1.\n  apply H2.\n  eapply eqRat_trans.\n  apply ratMult_distrib_r.\n  eapply eqRat_trans.\n  eapply ratAdd_eqRat_compat.\n  apply ratMult_comm.\n  apply ratMult_comm.\n  apply ratAdd_eqRat_compat.\n  apply ratMult_distrib_r.\n  apply ratMult_distrib_r.\n  apply eqRat_refl.\n  eapply eqRat_trans.\n  eapply ratSubtract_eqRat_compat.\n  apply ratAdd_assoc.\n  apply ratMult_comm.\n  eapply eqRat_trans.\n  apply ratSubtract_ratAdd_inverse.\n  rewrite <- ratAdd_assoc.\n  apply ratAdd_eqRat_compat.\n  rewrite ratAdd_comm.\n  apply ratAdd_eqRat_compat.\n  rewrite ratMult_comm.\n  apply ratMult_eqRat_compat.\n  eapply eqRat_symm.\n  eapply eqRat_trans.\n  eapply ratSubtract_eqRat_compat.\n  apply H1.\n  apply eqRat_refl.\n  apply ratSubtract_ratAdd_inverse.\n  intuition.\n  apply ratMult_eqRat_compat.\n  apply eqRat_symm.\n  eapply eqRat_trans.\n  apply ratSubtract_eqRat_compat.\n  apply H2.\n  apply eqRat_refl.\n  apply ratSubtract_ratAdd_inverse.\n  intuition.\n\n  rewrite ratMult_comm.\n  apply ratMult_eqRat_compat.\n  apply eqRat_symm.\n  eapply eqRat_trans.\n  apply ratSubtract_eqRat_compat.\n  apply H1.\n  apply eqRat_refl.\n  apply ratSubtract_ratAdd_inverse.\n  \n  apply eqRat_symm.\n  eapply eqRat_trans.\n  apply ratSubtract_eqRat_compat.\n  apply H2.\n  apply eqRat_refl.\n  apply ratSubtract_ratAdd_inverse.\n\nQed.\n\n\n\nLemma ratSubtract_eq_r : forall r1 r2 r3,\n  r2 <= r1 ->\n  r3 <= r1 ->\n  (ratSubtract r1 r2) == (ratSubtract r1 r3) ->\n  r2 == r3.\n  \n  rattac.\n  unfold ratSubtract in *.\n  rattac.\n  match goal with\n    H: (_ * (?x*_) = _ * (?x*_))%nat |- _\n    => eapply (@mult_same_l (x * x)); nia\n  end.\nQed.\n\nLemma ratDistance_le_max : forall r1 r2 r3 v,\n  r1 <= r2 ->\n  r2 <= r3 ->\n  (ratDistance r2 v) <= (maxRat (ratDistance r1 v) (ratDistance r3 v)).\n  \n  intuition.\n  unfold ratDistance, maxRat, minRat.\n  case_eq (bleRat r3 v); intuition.\n  assert (r2 <= v).\n  rewrite H0.\n  eauto.\n  rewrite H2.\n  assert (r1 <= v).\n  rewrite H.\n  eauto.\n  rewrite H3.\n  \n  assert ((ratSubtract v r3) <= (ratSubtract v r1)).\n  eapply ratSubtract_leRat_r.\n  eauto using leRat_trans.\n  \n  case_eq (bleRat (ratSubtract v r1) (ratSubtract v r3)); intuition.\n  assert (r1 == r3).\n  assert ((ratSubtract v r1) == (ratSubtract v r3)).\n  eapply leRat_antisymm; eauto.\n  \n  eapply ratSubtract_eq_r; eauto.\n  \n  eapply ratSubtract_leRat_r.\n  rewrite <- H6.\n  trivial.\n  \n  eapply ratSubtract_leRat_r.\n  trivial.\n  \n  eapply bleRat_total in H1.\n  case_eq (bleRat r2 v); intuition.\n  assert (r1 <= v).\n  eauto using leRat_trans.\n  rewrite H3.\n  case_eq (bleRat (ratSubtract v r1) (ratSubtract r3 v)); intuition.\n  eapply leRat_trans.\n  eapply ratSubtract_leRat_r.\n  eapply H.\n  eapply H4.\n      \n  eapply ratSubtract_leRat_r; trivial.\n\n  apply bleRat_total in H2.\n  case_eq (bleRat r1 v); intuition.\n  case_eq (bleRat (ratSubtract v r1) (ratSubtract r3 v)); intuition.\n  \n  assert (r1 <= v).\n  eauto using leRat_trans.\n  eapply ratSubtract_leRat_l; trivial.\n  \n  apply bleRat_total in H4.\n  eapply leRat_trans.\n  eapply ratSubtract_leRat_l.\n  eapply H0.\n  trivial.\n  \n  assert (bleRat (ratSubtract r1 v) (ratSubtract r3 v) = true).\n  eapply ratSubtract_leRat_l.\n  eauto using leRat_trans.\n  rewrite H4.\n  \n  eapply ratSubtract_leRat_l; trivial.\nQed.\n\nLemma maxRat_leRat_same : forall r1 r2 r3,\n  r1 <= r3 ->\n  r2 <= r3 ->\n  maxRat r1 r2 <= r3.\n  \n  rattac.\n  unfold maxRat in *.\n  match goal with\n    [H:(if ?C then _ else _) = _ |- _ ] =>\n    destruct C eqn:?; inversion H; subst; nia\n  end.\nQed.\n\nLemma ratMult_3_ratAdd : forall r,\n  (3 / 1) * r == r + r + r.\n  \n  rattac.\n  inversion H; clear H; subst.\n  inversion H0; clear H0; subst.\n  simpl.\n  arithNormalize.\n  repeat rewrite mult_0_r.\n  repeat rewrite plus_0_r.\n  trivial.\nQed.\n\nLemma ratMult_small_le : forall r1 r2,\n  r2 <= 1 ->\n  r1 * r2 <= r1.\n  \n  rattac.\n  inversion H0; clear H0; subst.\n  rewrite mult_1_r in l.\n  rewrite mult_1_l in l.\n  rewrite mult_assoc.\n  rewrite <- (mult_assoc n2).\n  rewrite (mult_comm n).\n  rewrite mult_assoc.\n  apply mult_le_compat;\n    auto.\n  \nQed.\n\nLemma ratDistance_ratMult_le : forall r1 r2 r3 r4 d,\n  (ratDistance r1 r3) <= d ->\n  (ratDistance r2 r4) <= d ->\n  r1 <= 1 ->\n  r2 <= 1 ->\n  r3 <= 1 ->\n  r4 <= 1 ->\n  (ratDistance (r1 * r2) (r3 * r4)) <= (3 / 1) * d.\n  \n  intuition.\n  \n  unfold ratDistance, maxRat, minRat in *.\n  case_eq (bleRat r1 r3); intuition;\n    rewrite H5 in H.\n  case_eq (bleRat r2 r4); intuition;\n    rewrite H6 in H0.\n  \n  assert (r1 * r2 <= r3 * r4).\n  apply ratMult_leRat_compat; eauto.\n  rewrite H7.\n  \n  rewrite ratSubtract_ratMult_le; eauto.\n  repeat rewrite ratMult_small_le.\n  rewrite H.\n  rewrite H0.\n  eapply eqRat_impl_leRat.\n  symmetry.\n  eapply ratMult_3_ratAdd.\n  eapply ratSubtract_le.\n  trivial.\n  trivial.\n  trivial.\n  \n  apply bleRat_total in H6.\n  case_eq (bleRat (r1 * r2) (r3 * r4)); intuition.\n  \n  rewrite ratSubtract_leRat.\n  Focus 2.\n  eapply ratMult_leRat_compat.\n  eapply leRat_refl.\n  eapply H6.\n  Focus 2.\n  eapply ratMult_leRat_compat.\n  eapply leRat_refl.\n  eapply H6.\n  \n  rewrite ratSubtract_ratMult_le; eauto.\n  repeat rewrite ratMult_small_le.\n  rewrite H.\n  rewrite H0.\n  eapply eqRat_impl_leRat.\n  symmetry.\n  eapply ratMult_3_ratAdd.\n  eapply ratSubtract_le.\n  trivial.\n  trivial.\n  trivial.\n  \n  apply bleRat_total in H7.\n  eapply leRat_trans.\n  eapply ratSubtract_leRat.\n  eapply ratMult_leRat_compat.\n  eapply H5.\n  eapply leRat_refl.\n  eapply ratMult_leRat_compat.\n  eapply H5.\n  eapply leRat_refl.\n  rewrite ratSubtract_ratMult_le; eauto.\n  repeat rewrite ratMult_small_le.\n  rewrite H.\n  rewrite H0.\n  eapply eqRat_impl_leRat.\n  symmetry.\n  eapply ratMult_3_ratAdd.\n  eapply ratSubtract_le.\n  trivial.\n  trivial.\n  trivial.\n  \n  apply bleRat_total in H5.\n  case_eq (bleRat r2 r4); intuition.\n  rewrite H6 in H0.\n  case_eq (bleRat (r1 * r2) (r3 * r4)); intuition.\n  eapply leRat_trans.\n  eapply ratSubtract_leRat.\n  eapply ratMult_leRat_compat.\n  eapply H5.\n  eapply leRat_refl.\n  eapply ratMult_leRat_compat.\n  eapply H5.\n  eapply leRat_refl.\n  rewrite ratSubtract_ratMult_le; eauto.\n  repeat rewrite ratMult_small_le.\n  rewrite H.\n  rewrite H0.\n  eapply eqRat_impl_leRat.\n  symmetry.\n  eapply ratMult_3_ratAdd.\n  eapply ratSubtract_le.\n  trivial.\n  trivial.\n  trivial.\n  \n  apply bleRat_total in H7.\n  eapply leRat_trans.\n  eapply ratSubtract_leRat.\n  eapply ratMult_leRat_compat.\n  eapply leRat_refl.\n  eapply H6.\n  eapply ratMult_leRat_compat.\n  eapply leRat_refl.\n  eapply H6.\n  rewrite ratSubtract_ratMult_le; eauto.\n  repeat rewrite ratMult_small_le.\n  rewrite H.\n  rewrite H0.\n  eapply eqRat_impl_leRat.\n  symmetry.\n  eapply ratMult_3_ratAdd.\n  eapply ratSubtract_le.\n  trivial.\n  trivial.\n  trivial.\n  \n  rewrite H6 in H0.\n  \n  apply bleRat_total in H6.\n  assert (r3 * r4 <= r1 * r2).\n  eapply ratMult_leRat_compat; eauto.\n  case_eq (bleRat (r1 * r2) (r3 * r4)); intuition.\n  \n  rewrite ratSubtract_0; eauto.\n  eapply rat0_le_all.\n  apply bleRat_total in H8.\n  \n  rewrite ratSubtract_ratMult_le; eauto.\n  repeat rewrite ratMult_small_le.\n  rewrite H.\n  rewrite H0.\n  eapply eqRat_impl_leRat.\n  symmetry.\n  eapply ratMult_3_ratAdd.\n  eapply ratSubtract_le.\n  trivial.\n  trivial.\n  trivial.\n  \nQed.\n\nLemma ratAdd_any_le : forall r1 r2 r3,\n  r1 + r2 <= r3 ->\n  r1 <= r3.\n  \n  intuition.\n  eapply leRat_trans.\n  eapply eqRat_impl_leRat.\n  apply ratAdd_0_r.\n  eapply leRat_trans.\n  eapply ratAdd_leRat_compat.\n  apply leRat_refl.\n  apply rat0_le_all.\n  eauto.\nQed.\n\nLemma posnatMult_1_r : forall p,\n  posnatToNat (posnatMult p (pos 1)) = posnatToNat p.\n  \n  intuition.\n  unfold posnatMult.\n  destruct p.\n  remember (pos 1) as p2.\n  destruct p2.\n  unfold posnatToNat.\n  inversion Heqp2; subst.\n  apply mult_1_r.\n  \nQed.\n\nLemma rat_num_nz : forall n d,\n  n > 0 ->\n  RatIntro n d == 0 ->\n  False.\n  \n  rattac.\n  unfold posnatToNat, natToPosnat in *.\n  destruct d.\n  simpl in *.\n  omega.\nQed.\n\n\nLemma ratMult_inverse : forall r1 r2 (p1 p2 : posnat),\n  r1 == r2 * (RatIntro p1 p2) ->\n  r1 * (RatIntro p2 p1) == r2.\n  \n  intuition.\n  rewrite H.\n  rewrite <- (ratMult_1_r r2) at 2.\n  rewrite ratMult_assoc.\n  eapply ratMult_eqRat_compat.\n  intuition.\n  rewrite <- ratMult_num_den.\n  eapply num_dem_same_rat1.\n  rattac.\nQed.\n\nLemma ratMult_inverse_nat : forall r1 r2 n d (nzn : nz n), \n  r1 == r2 * (RatIntro n d) ->\n  r1 * (RatIntro d (natToPosnat nzn)) == r2.\n  \n  intuition.\n  eapply ratMult_inverse.\n  rewrite H.\n  eapply ratMult_eqRat_compat.\n  intuition.\n  eapply eqRat_terms; eauto.\nQed.\n\nLemma ratMult_same_r_inv : forall r1 r2 r3,\n  r1 * r2 == r3 * r2 ->\n  ~ r2 == 0 ->\n  r1 == r3.\n  \n  intuition.\n  unfold ratMult in *.\n  destruct r1.\n  destruct r2.\n  destruct r3.\n  unfold eqRat, beqRat in *.\n  simpl in *.\n  unfold posnatMult, posnatToNat, natToPosnat in *.\n  destruct p1.\n  destruct p0.\n  destruct p.\n  destruct (eq_nat_dec (n * n0 * (x * x0)) (n1 * n0 * (x1 * x0))); try congruence.\n  destruct (eq_nat_dec (n * x) (n1 * x1)).\n  trivial.\n  exfalso.\n  eapply n2.\n  clear n2.\n  arithNormalize.\n  rewrite <- (mult_assoc n) in e.\n  rewrite (mult_comm n0) in e.\n  arithNormalize.\n  rewrite <- mult_assoc in e.\n  rewrite <- (mult_assoc n1) in e.\n  rewrite <- (mult_comm x1) in e.\n  rewrite (mult_assoc n1) in e.\n  rewrite <- (mult_assoc (n1 * x1)) in e.\n  eapply mult_same_r.\n  Focus 2.\n  eapply e.\n  rewrite mult_0_r in H0.\n  rewrite plus_0_l in H0.\n  destruct (eq_nat_dec n0 0); intuition.\n  assert (~n0 * x0 = O)%nat.\n  intuition.\n  eapply mult_is_O in H1.\n  intuition.\n  remember (n0 * x0)%nat as a.\n  omega.\nQed.\n\nLemma rat_le_1 : forall n (d : posnat),\n  (n <= d)%nat -> (RatIntro n d) <= 1.\n  \n  rattac.\n  inversion H1; clear H1; subst.\n  rewrite mult_1_r.\n  rewrite mult_1_l.\n  trivial.\nQed.\n\nLemma rat_remove_common_factor : forall (n num : nat)(nzn : nz n) den,\n  RatIntro (n * num) (posnatMult (natToPosnat nzn) den) == RatIntro num den.\n  \n  rattac.\n  inversion H; clear H; subst.\n  arithNormalize.\n  do 2 arithSimplify.\nQed.\n\nLemma ratMult_2 : forall r,\n  r + r == r * (2/1).\n  \n  rattac.\n  inversion H; clear H; subst.\n  arithNormalize.\n  rewrite mult_0_r.\n  rewrite plus_0_r.\n  f_equal.\n  f_equal.\n  rewrite <- mult_assoc.\n  rewrite <- mult_assoc.\n  rewrite mult_comm.\n  simpl.\n  trivial.\nQed.\n\n\n(* ratInverse only works correctly when the number is positive *)\nDefinition ratInverse (r : Rat) :=\n  match r with\n    | RatIntro n d =>\n      match n with\n        | O => RatIntro d (pos (S O))\n        | S n' => RatIntro d (pos (S n'))\n      end\n  end.\n\nLemma ratInverse_prod_1 : forall r,\n  ~ r == 0 ->\n  (ratInverse r) * r == 1.\n  \n  intuition.\n  unfold ratInverse.\n  destruct r.\n  destruct n.\n  \n  exfalso.\n  eapply H.\n  eapply rat_num_0.\n  \n  rewrite <- ratMult_num_den.\n  eapply num_dem_same_rat1.\n  unfold posnatMult, natToPosnat, posnatToNat.\n  destruct p.\n  apply mult_comm.\nQed.\n\nFixpoint expRat r n :=\n  match n with\n    | O => rat1 \n    | S n' => r * (expRat r n')\n  end.\n\nLemma ratInverse_nz : forall (r : Rat),\n  ratInverse r == 0 ->\n  False.\n\n  intuition.\n  unfold ratInverse in *.\n  rattac.\n  destruct n0.\n  unfold posnatToNat, natToPosnat in *.\n  destruct p.\n  destruct p0.\n  inversion H0; clear H0; subst.\n  rewrite mult_1_r in e.\n  rewrite mult_1_r in e.\n  omega.\n\n  unfold posnatToNat, natToPosnat in *.\n  destruct p.\n  destruct p0.\n  inversion H0; clear H0; subst.\n  rewrite mult_1_r in e.\n  rewrite mult_0_l in e.\n  omega.  \n\nQed.\n\nLemma ratInverse_1_swap : forall r,\n  ~ r == 0 ->\n  r <= 1 ->\n  1 <= ratInverse r.\n  \n  intuition.\n  unfold ratInverse.\n  destruct r.\n  destruct n.\n  exfalso.\n  eapply H.\n  eapply rat_num_0.\n  \n  rattac.\n  inversion H1; clear H1; subst.\n  omega.\n  \nQed.\n\nLemma ratInverse_1 : \n  ratInverse 1 == 1.\n  \n  unfold ratInverse.\n  case_eq rat1; intuition.\n  inversion H; clear H; subst.\n  eapply eqRat_terms;\n    trivial.\n  \nQed.\n\nLemma ratInverse_leRat : forall r1 r2,\n  ~ r2 == 0 ->\n  r2 <= r1 ->\n  ratInverse r1 <= ratInverse r2.\n  \n  intuition.\n  unfold ratInverse.\n  rattac.\n  destruct n0.\n  exfalso.\n  eapply H.\n  eapply rat_num_0.\n  destruct n.\n  exfalso.\n  rewrite mult_0_l in l.\n  simpl in *.\n  remember (n0 * x1)%nat as a.\n  nia.\n  \n  inversion H3; clear H3; subst.\n  inversion H2; clear H2; subst.\n  nia.\nQed.\n\nLemma ratAdd_not_leRat : forall r1 r2,\n  r1 + r2 <= r1 ->\n  (~r2 == 0) ->\n  False.\n  \n  rattac.\n  eapply H0.\n  unfold posnatMult, natToPosnat, posnatToNat in *.\n  destruct p1.\n  destruct p0.\n  rewrite mult_plus_distr_r in l.\n  rewrite <- mult_assoc in l.\n  rewrite (mult_comm x) in l.\n  assert ((n1 * x0 * x0) = O)%nat.\n  remember (n0 * (x0 * x))%nat as a.\n  remember (n1 * x0 * x0)%nat as b.\n  omega.\n  apply mult_is_O in H1;\n    intuition; \n      subst.\n  apply mult_is_O in H2;\n    intuition;\n      subst.\n  apply rat_num_0.\n  omega.\n  omega.\nQed.\n\n\n(* relational versions of arithmetic operations. *)\nDefinition ratSubtract_rel (r1 r2 : Rat -> Prop) d :=\n  forall r1' r2', r1 r1' -> r2 r2' -> d == ratSubtract r1' r2'.\n  \nDefinition ratAdd_rel(r1 r2 : Rat -> Prop) r :=\n  forall r1' r2', r1 r1' -> r2 r2' -> r == r1' + r2'.\n\nDefinition ratMult_rel (r1 r2 : Rat -> Prop)(r : Rat) :=\n  forall r1' r2', r1 r1' -> r2 r2' -> r == r1' * r2'.\n\nDefinition expRat_rel (r1 : Rat -> Prop) n r :=\n  forall r1', r1 r1' -> r == expRat r1' n.\n\nDefinition ratInverse_rel (r : Rat -> Prop) v :=\n  forall r',\n    r r' -> v == ratInverse r'.\n\nLemma eqRat_flip : forall (p1 p2 p3 p4 : posnat),\n  RatIntro p1 p2 == RatIntro p3 p4 ->\n  RatIntro p2 p1 == RatIntro p4 p3.\n\n  rattac.\n  rewrite mult_comm.\n  rewrite <- e.\n  apply mult_comm.\n\nQed.\n\nLemma ratInverse_eqRat_compat : forall r1 r2,\n  ~ r1 == 0 ->\n  r1 == r2 ->\n  ratInverse r1 == ratInverse r2.\n\n  intuition.\n  unfold ratInverse.\n  destruct r1. destruct r2.\n  destruct n.\n  exfalso.\n  eapply H.\n  eapply rat_num_0.\n  destruct n0.\n  exfalso.\n  \n  eapply rat_num_nz.\n  Focus 2.\n  rewrite rat_num_0 in H0.\n  eauto.\n  omega.\n\n  eapply eqRat_flip.\n  eapply H0.\n\nQed.\n\nLemma ratSubtract_ratAdd_distr : forall r1 r2 r3,\n  ratSubtract r1 (r2 + r3) == ratSubtract (ratSubtract r1 r2) r3.\n  \n  intuition.\n  unfold ratSubtract, ratAdd.\n  rattac.\n  arithNormalize.\n  rewrite NPeano.Nat.sub_add_distr.\n  f_equal.\n  f_equal.\n  do 5 arithSimplify.\n  do 5 arithSimplify.\nQed.\n\nLemma ratSubtract_ratAdd_assoc_1 : forall r1 r2 r3,\n  r3 <= r2 ->\n  ratSubtract (r1 + r2) r3 == r1 + (ratSubtract r2 r3).\n  \n  intuition.\n  unfold ratSubtract, ratAdd.\n  rattac.\n  arithNormalize.\n  rewrite minus_plus_assoc.\n  f_equal.\n  f_equal.\n  do 5 arithSimplify.\n  do 5 arithSimplify.\n  unfold natToPosnat, posnatToNat in *.\n  eapply mult_le_compat; trivial.\n  eapply mult_le_compat; trivial.\n  eapply mult_le_compat; trivial.\n  \n  rewrite <- (mult_assoc).\n  rewrite (mult_comm x).\n  rewrite mult_assoc.\n  rewrite <- (mult_assoc n3).\n  rewrite (mult_comm x).\n  rewrite mult_assoc.\n  eapply mult_le_compat; trivial.\n  \nQed.\n\n\nLemma eqRat_ratMult_same_r : forall r1 r2 r3,\n  ~r1 == 0 ->\n  r2 * r1 == r3 * r1 ->\n  r2 == r3.\n\n  intuition.\n  destruct r1.\n  destruct r2.\n  destruct r3.\n  unfold ratMult in *.\n  unfold eqRat in *.\n  unfold beqRat in *.\n  unfold ratCD in *.\n  case_eq (0); intuition.\n  rewrite H1 in H.\n  destruct (eq_nat_dec (n * p2) (n2 * p)).\n  intuition.\n  destruct (eq_nat_dec (n0 * n * (posnatMult p1 p)) (n1 * n * (posnatMult p0 p))); intuition.\n  inversion H1; clear H1; subst.\n  unfold posnatMult, natToPosnat, posnatToNat in *.\n  destruct p1.\n  destruct p.\n  destruct p0.\n  destruct (eq_nat_dec (n0 * x) (n1 * x1)); trivial.\n  exfalso.\n  eapply n2.\n  eapply (@mult_same_l (n * x0)).\n  eapply mult_gt_0.\n  rewrite mult_1_r in n3.\n  rewrite mult_0_l in n3.\n  omega.\n  trivial.\n  rewrite (mult_comm).\n  rewrite mult_assoc.\n  rewrite <- (mult_assoc n0).\n  rewrite (mult_comm x).\n  arithNormalize.\n  rewrite e.\n  do 3 arithSimplify.\nQed.\n\nLemma expRat_le_1 : forall n x,\n  x <= 1 ->\n  expRat x n <= 1.\n  \n  induction n; intuition; simpl in *.\n  intuition.\n  \n  eapply leRat_trans.\n  eapply ratMult_leRat_compat.\n  eapply H.\n  eapply IHn.\n  trivial.\n  rewrite ratMult_1_l.\n  intuition.\n  \nQed.\n\nLemma expRat_le : forall n1 n2 x,\n  x <= 1 ->\n  n2 >= n1 ->\n  expRat x n2 <= expRat x n1.\n  \n  induction n1; intuition; simpl in *.\n  eapply expRat_le_1; trivial.\n  \n  destruct n2;\n    simpl.\n  omega.\n  eapply ratMult_leRat_compat.\n  intuition.\n  eapply IHn1.\n  trivial.\n  omega.\nQed.\n\nLemma expRat_leRat_compat : forall n r1 r2,\n  r1 <= r2 ->\n  expRat r1 n <= expRat r2 n.\n\n  induction n; intuition; simpl in *.\n  intuition.\n\n  eapply ratMult_leRat_compat; eauto.\n\nQed.\n\n\nLemma expRat_le' : forall n1 n2 r v,\n  expRat r n1 <= v ->\n  ~ (1 <= r) ->\n  n2 >= n1 ->\n  expRat r n2 <= v.\n\n  intuition.\n  eapply leRat_trans.\n  eapply expRat_le.\n  case_eq (bleRat r 1); intuition.\n  exfalso.\n  eapply H0.\n  eapply bleRat_total.\n  trivial.\n  eauto.\n  trivial.\nQed.\n\n\nLemma ratSubtract_sum_1 : forall r1 r2,\n  ~ r1 <= r2 ->\n  r2 + (ratSubtract r1 r2) == r1.\n\n  intuition.\n  \n  rewrite <- ratSubtract_ratAdd_assoc.\n  eapply ratSubtract_ratAdd_inverse.\n  apply bleRat_total.\n  case_eq (bleRat r1 r2); intuition.\n\nQed.\n\nLemma rat_ge_1 : forall n (d : posnat),\n  n >= d ->\n  1 <= RatIntro n d.\n  \n  intuition.\n  rattac.\n  inversion H1; clear H1; subst.\n  omega.\n  \nQed.\n\nLemma leRat_ratAdd_same_r : forall r1 r2 r3,\n  r2 + r1 <= r3 + r1 ->\n  r2 <= r3.\n\n  intuition.\n  \n  apply (@ratSubtract_leRat_l (r2 + r1) (r3 + r1) r1) in H.\n  rewrite <- (@ratSubtract_ratAdd_inverse r1 r2).\n  rewrite ratAdd_comm.\n  rewrite H.\n  rewrite ratAdd_comm.\n  rewrite ratSubtract_ratAdd_inverse.\n  intuition.\n  \nQed.\n\nLemma leRat_ratMult_same_r : forall r1 r2 r3,\n  (~r1 == 0) ->\n  r2 * r1 <= r3 * r1 ->\n  r2 <= r3.\n  \n  intuition.\n  rewrite <- ratMult_1_r.\n  erewrite <- (ratInverse_prod_1 H).\n  rewrite (ratMult_comm (ratInverse r1)).\n  rewrite <- ratMult_assoc.\n  eapply leRat_trans.\n  eapply ratMult_leRat_compat.\n  eapply H0.\n  eapply leRat_refl.\n  rewrite ratMult_assoc.\n  rewrite (ratMult_comm r1).\n  rewrite ratInverse_prod_1.\n  rewrite ratMult_1_r.\n  intuition.\n  intuition.\n  \nQed.\n\nLemma ratMult_eq_rat1 : forall n1 n2 (nz1 : nz n1)(nz2 : nz n2),\n  (n1 / n2) * (n2 / n1) == 1.\n  \n  intuition.\n  rewrite <- ratMult_num_den.\n  eapply num_dem_same_rat1.\n  unfold posnatMult, natToPosnat, posnatToNat.\n  eapply mult_comm.\n  \nQed.\n\n\nLemma half_distance_1_le : forall r,\n  ~ 1 <= r ->\n  ~ 1 <= r + (1 / 2) * (ratSubtract 1 r).\n  \n  intuition.\n  eapply H.\n  eapply (leRat_ratAdd_same_r 1).\n  rewrite <- (@ratSubtract_sum_1 1 r) at 3; trivial.\n  eapply leRat_trans.\n  Focus 2.\n  eapply eqRat_impl_leRat.\n  eapply ratAdd_assoc.\n  \n  repeat rewrite ratMult_2.\n  rewrite ratMult_comm.\n  rewrite (ratMult_comm (2/1)).\n  eapply (@leRat_ratMult_same_r (1/2)).\n  intuition.\n  rewrite ratMult_1_l.\n  rewrite ratMult_eq_rat1.\n  \n  eapply leRat_trans.\n  Focus 2.\n  eapply eqRat_impl_leRat.\n  symmetry.\n  eapply ratMult_distrib_r.\n  \n  rewrite ratMult_assoc.\n  rewrite ratMult_eq_rat1.\n  rewrite ratMult_1_r.\n  rewrite ratMult_comm.\n  trivial.\nQed.\n\nLemma leRat_terms : forall n1 n2 (d1 d2 : posnat),\n  (n1 <= n2)%nat ->\n  (d2 <= d1)%nat ->\n  RatIntro n1 d1 <= RatIntro n2 d2.\n\n  rattac.\n  eapply mult_le_compat; trivial.\n\nQed.\n\nLemma posnatMult_eq : forall p1 p2,\n  posnatToNat (posnatMult p1 p2) = (p1 * p2)%nat.\n\n  intuition.\n  unfold posnatMult.\n  destruct p1.\n  destruct p2.\n  unfold posnatToNat, natToPosnat.\n  trivial.\nQed.\n\nTheorem mult_gt_zero_if : \n  forall (a b : nat),\n    a * b > 0 -> (a > 0  /\\ b > 0).\n\n  induction a; induction b; intuition.\n\nQed.\n\nLemma expRat_terms : forall k n (d : posnat)(p : nz (expnat d k)),\n  expRat (RatIntro n d) k == (expnat n k) / (expnat d k).\n\n  induction k; intuition; simpl in *.\n  symmetry.\n  eapply num_dem_same_rat1.\n  trivial.\n  rewrite IHk.\n  rewrite <- ratMult_num_den.\n  eapply eqRat_terms.\n  intuition.\n  eapply posnatMult_eq.\n\n  Grab Existential Variables.\n  destruct p.\n  econstructor.\n  eapply mult_gt_zero_if; eauto.\n  \nQed.\n  \n\nLemma expRat_le_half_exists : forall r,\n  ~ 1 <= r ->\n  exists n, expRat r n <= (1/2).\n\n  intuition.\n  destruct r.\n  destruct (le_dec n (pred p)).\n\n  exists (p)%nat.\n  \n  eapply leRat_trans.\n  eapply expRat_leRat_compat.\n  eapply leRat_terms.\n  eapply l.\n  eapply le_refl.\n\n  rewrite expRat_terms.\n\n  destruct p.\n  destruct x.\n  omega.\n  simpl.\n  destruct (eq_nat_dec x O); subst.\n  rewrite mult_0_l.\n  rewrite rat_num_0.\n  eapply rat0_le_all.\n\n  assert (nz (2 * (x * expnat x x))).\n  econstructor.\n  eapply mult_gt_0.\n  omega.\n  eapply mult_gt_0. omega.\n  edestruct (@expnat_nz x x).\n  econstructor.\n  omega.\n  eauto.\n\n  assert (nz ((expnat (S x) x + x * expnat (S x) x))).\n  econstructor.\n  assert (expnat (S x) x > O).\n  edestruct (expnat_nz).\n  econstructor.\n  eapply g.\n  eauto.\n  remember (x * expnat (S x) x)%nat as a.\n  omega.\n\n  assert (posnatToNat (pos (2 * (x * expnat x x))) <= posnatToNat (pos (expnat (S x) x + x * expnat (S x) x)))%nat.\n  unfold natToPosnat, posnatToNat.\n  rewrite mult_assoc.\n  rewrite (mult_comm 2 x).\n  rewrite <- mult_assoc.\n  rewrite <- (plus_0_l (x * (2 * expnat x x))).\n  eapply plus_le_compat.\n  intuition.\n  eapply mult_le_compat.\n  intuition.\n  eapply expnat_base_S_same.\n  omega.\n\n  eapply leRat_trans.\n  eapply leRat_terms.\n  rewrite <- (mult_1_l (x * expnat x x)).\n  eapply le_refl.\n  unfold natToPosnat, posnatToNat.\n  eapply H2.\n  assert (nz (x * expnat x x)).\n  econstructor.\n  eapply mult_gt_0.\n  omega.\n  edestruct (@expnat_nz x x).\n  econstructor.\n  omega.\n  eauto.\n  assert (posnatToNat (pos (2 * (x * expnat x x))) = posnatToNat (posnatMult (pos 2) (pos (x * expnat x x)))).\n  unfold posnatMult, posnatToNat, natToPosnat.\n  trivial.\n  eapply leRat_trans.\n  eapply eqRat_impl_leRat.\n  eapply eqRat_trans.\n  eapply eqRat_terms.\n  eapply eq_refl.\n  eapply H4.\n  eapply ratMult_num_den.\n  eapply leRat_trans.\n  Focus 2.\n  eapply eqRat_impl_leRat.\n  rewrite <- (ratMult_1_r (1/2)).\n  eapply eqRat_refl.\n  eapply ratMult_leRat_compat.\n  intuition.\n  eapply eqRat_impl_leRat.\n  eapply num_dem_same_rat1.\n  unfold posnatToNat, natToPosnat.\n  trivial.\n\n  exfalso.\n  eapply H.\n\n  eapply rat_ge_1.\n  omega.\n\n  Grab Existential Variables.\n  \n  eapply expnat_nz.\n  destruct p.\n  econstructor.\n  simpl.\n  trivial.\nQed.\n\nLemma expRat_half_le_exp_exists : forall d,\n  ~ d == 0 ->\n  exists n,\n    expRat (1/2) n <= d.\n\n  intuition.\n  destruct d.\n  assert (1 <= n)%nat.\n  destruct n.\n  exfalso.\n  eapply H.\n  eapply rat_num_0.\n  omega.\n  exists p.\n  rewrite expRat_terms.\n  eapply leRat_trans.\n  Focus 2.\n  eapply leRat_terms.\n  eapply H0.\n  eapply le_refl.\n  erewrite expnat_1.\n  eapply leRat_terms.\n  intuition.\n  edestruct p.\n  unfold natToPosnat, posnatToNat.\n  eapply le_expnat_2.\n\n  Grab Existential Variables.\n  eapply expnat_nz.\n  econstructor.\n  destruct p.\n  econstructor.\n  intuition.\n\nQed.\n\nLemma expRat_1 : forall n,\n  expRat 1 n == 1.\n\n  induction n; intuition; simpl in *.\n  intuition.\n  rewrite ratMult_1_l.\n  trivial.\n\nQed.\n\nLemma expRat_exp_sum  : forall n1 n2 r,\n  expRat r (n1 + n2)%nat == (expRat r n1) * (expRat r n2).\n\n  induction n1; intuition; simpl in *.\n  symmetry.\n  eapply ratMult_1_l.\n\n  rewrite IHn1.\n  rewrite ratMult_assoc.\n  intuition.\n\nQed.\n\nLemma expRat_base_prod : forall n r1 r2,\n  expRat (r1 * r2) n == (expRat r1 n) * (expRat r2 n).\n\n  induction n; intuition; simpl in *.\n  symmetry.\n  eapply ratMult_1_l.\n\n  rewrite IHn.\n  repeat rewrite <- ratMult_assoc.\n  eapply ratMult_eqRat_compat; intuition.\n  repeat rewrite ratMult_assoc.\n  eapply ratMult_eqRat_compat; intuition.\n  eapply ratMult_comm.\nQed.\n\nLemma expRat_exp_prod : forall n1 n2 r,\n  expRat r (n1 * n2)%nat == expRat (expRat r n1) n2.\n\n  induction n1; intuition; simpl in *.\n  symmetry.\n  eapply expRat_1.\n\n  rewrite expRat_exp_sum.\n  rewrite IHn1.\n  rewrite expRat_base_prod.\n  intuition.\n\nQed.\n\nLemma expRat_le_exp_exists : forall r d, \n  ~ 1 <= r ->\n  ~ d == 0 ->\n  exists n,\n    expRat r n <= d.\n\n  intuition.\n  destruct (expRat_half_le_exp_exists H0).\n  destruct (expRat_le_half_exists H).\n  exists (x0 * x)%nat.\n  rewrite expRat_exp_prod.\n  eapply leRat_trans.\n  eapply expRat_leRat_compat.\n  eapply H2.\n  intuition.\nQed.\n\nLemma eqRat_ratAdd_same_r : forall r1 r2 r3,\n  r2 + r1 == r3 + r1 ->\n  r2 == r3.\n  \n  intuition.\n  eapply leRat_impl_eqRat.\n  eapply leRat_ratAdd_same_r;\n    eapply eqRat_impl_leRat; eauto.\n  symmetry in H.\n  eapply leRat_ratAdd_same_r;\n    eapply eqRat_impl_leRat; eauto.\nQed.\n\nLemma ratAdd_arg_0 : forall a b,\n  a + b == a ->\n  b == 0.\n  \n  intuition.\n  eapply eqRat_ratAdd_same_r.\n  rewrite ratAdd_comm.\n  rewrite H.\n  rewrite <- ratAdd_0_l.\n  intuition.\nQed.\n\nDefinition ratHalf(r : Rat) :=\n  r * (1 / 2).\n\nTheorem ratHalf_ne_0 : forall r,\n  ~ r == 0 ->\n  ~ (ratHalf r) == 0.\n\n  intuition.\n  unfold ratHalf in *.\n  apply ratMult_0 in H0.\n\n  destruct H0; intuition.\nQed.\n\nTheorem ratHalf_add : forall r,\n  ratHalf r + ratHalf r == r.\n\n  intuition.\n  unfold ratHalf.\n  eapply eqRat_trans.\n  apply eqRat_symm.\n  apply ratMult_distrib.\n  eapply eqRat_trans.\n  apply ratMult_eqRat_compat.\n  apply eqRat_refl.\n  apply ratOneHalf_add.\n  rewrite ratMult_1_r.\n  intuition.\nQed.\n\nTheorem le_ratHalf_0 : forall r,\n  r <= (ratHalf r) -> r == 0.\n\n  intuition.\n  unfold ratHalf in *.\n  rattac.\n  unfold posnatMult in *.\n  destruct p.\n  unfold natToPosnat in *.\n  unfold posnatToNat in *.\n  rewrite mult_1_r in *.\n  rewrite (mult_comm x) in l.\n  rewrite mult_assoc in *.\n  assert (n * 2 <= n)%nat.\n  eapply mult_le_compat_r_iff; eauto.\n  omega.\nQed.\n\nLemma ratSubtract_0_r : forall r,\n  ratSubtract r 0 == r.\n\n  unfold ratSubtract in *.\n  rattac.\n  arithNormalize.\n  inversion H; clear H; subst.\n  simpl.\n  rewrite <- minus_n_O.\n  do 2 arithSimplify.\n  \nQed.\n\nLemma ratDistance_0_r_le : forall r d,\n  r <= d ->\n  ratDistance r 0 <= d.\n\n  intuition.\n  unfold ratDistance, maxRat, minRat.\n  case_eq (bleRat r 0); intuition.\n  rewrite ratSubtract_0;\n  eapply rat0_le_all.\n  apply bleRat_total in H0.\n  rewrite ratSubtract_0_r.\n  trivial.\n  \nQed.\n\nLemma ratSubtract_0_inv : forall r1 r2,\n  ratSubtract r1 r2 == 0 ->\n  r1 <= r2.\n\n  intuition.\n  unfold ratSubtract in *.\n  rattac.\n  rewrite mult_0_l in e.\n  apply mult_is_O in e.\n  intuition.\nQed.\n\nLemma ratSubtract_le_sum : forall r1 r2 d,\n  r2 <= r1 ->\n  ratSubtract r1 r2 <= d ->\n  r1 <= r2 + d.\n  \n  intuition.\n  \n  rewrite <- (ratSubtract_ratAdd_inverse r2).\n  rewrite ratSubtract_ratAdd_assoc.\n  eapply ratAdd_leRat_compat; eauto.\n  intuition.\n  trivial.\nQed.\n\nLemma ratDistance_le_sum : forall r1 r2 d,\n  ratDistance r1 r2 <= d ->\n  r1 <= r2 + d.\n\n  unfold ratDistance, maxRat, minRat in *.\n  intuition.\n  case_eq (bleRat r1 r2); intuition;\n  rewrite H0 in H.\n  rewrite ratAdd_0_r.\n  eapply ratAdd_leRat_compat.\n  trivial.\n  eapply rat0_le_all.\n\n  eapply ratSubtract_le_sum.\n  eapply bleRat_total.\n  trivial.\n  trivial.\nQed.\n\nLemma ratSubtract_ratDistance_le : forall r1 r2,\n  ratSubtract r1 r2 <= ratDistance r1 r2.\n  \n  unfold ratDistance, maxRat, minRat in *.\n  intuition.\n  case_eq (bleRat r1 r2); intuition.\n  rewrite ratSubtract_0.\n  eapply rat0_le_all.\n  trivial.\nQed.\n\nLemma minRat_le_r : forall r1 r2,\n  minRat r1 r2 <= r2.\n  \n  unfold minRat in *.\n  intuition.\n  case_eq (bleRat r1 r2); intuition.\nQed.\n\nLemma minRat_le_l : forall r1 r2,\n  minRat r1 r2 <= r1.\n  \n  unfold minRat in *.\n  intuition.\n  case_eq (bleRat r1 r2); intuition.\n  eapply bleRat_total.\n  trivial.\nQed.\n\nLemma ratDistance_ge_difference: forall r1 r2 d,\n  ratDistance r1 r2 <= d ->\n  ratSubtract r1 d <= r2.\n  \n  intuition.\n  eapply (leRat_ratAdd_same_r d).\n  case_eq (bleRat r1 d); intuition.\n  rewrite ratSubtract_0; trivial.\n  eapply ratAdd_leRat_compat; intuition.\n  eapply rat0_le_all.\n  apply bleRat_total in H0.\n  rewrite ratAdd_comm.\n  rewrite ratSubtract_ratAdd_inverse_2; trivial.\n  eapply ratDistance_le_sum; trivial.\n  \nQed.\n\nLemma ratSubtract_ratAdd_assoc_le : forall r1 r2 r3,\n  ratSubtract (r1 + r2) r3 <= r1 + (ratSubtract r2 r3).\n  \n  unfold ratSubtract, ratAdd.\n  rattac.\n  arithNormalize.\n  generalize (n1 * x0 * x1 * x * x0 * x1)%nat; intuition.\n  assert (n3 * x * x1 * x * x0 * x1 = n3 * x1 * x * x * x0 * x1)%nat.\n  do 5 arithSimplify.\n  rewrite H.\n  generalize (n3 * x1 * x * x * x0 * x1)%nat; intuition.\n  assert (n0 * x * x0 * x * x0 * x1 = n0 * x0 * x * x * x0 * x1)%nat.\n  do 5 arithSimplify.\n  rewrite H0.\n  generalize ( n0 * x0 * x * x * x0 * x1)%nat; intuition.\nQed.\n\nLemma ratSubtract_assoc_le : forall r1 r2 r3,\n  ratSubtract r1 (ratSubtract r2 r3) <= (ratSubtract r1 r2) + r3.\n  \n  unfold ratSubtract.\n  rattac.\n  arithNormalize.\n  remember (n * x * x0 * x1 * x * x0)%nat as a.\n  assert (n1 * x0 * x1 * x1 * x * x0 = n1 * x1 * x0 * x1 * x * x0)%nat.\n  do 5 arithSimplify.\n  rewrite H.\n  assert (n2 * x * x1 * x1 * x * x0 = n2 * x1 * x * x1 * x * x0)%nat.\n  do 5 arithSimplify.\n  rewrite H0.\n  remember (n1 * x1 * x0 * x1 * x * x0)%nat as b.\n  remember (n2 * x1 * x * x1 * x * x0)%nat as c.\n  omega.\n  \nQed.\n\nLemma ratDistance_leRat_both : forall r1 r2 d,\n  ratSubtract r1 r2 <= d ->\n  ratSubtract r2 r1 <= d ->\n  ratDistance r1 r2 <= d.\n  \n  intuition.\n  \n  unfold ratDistance, maxRat, minRat.\n  destruct (bleRat r1 r2); trivial.\n  \nQed.\n\nLemma rat_distance_of_difference : forall r1 r2 r3 r4 d1 d2,\n  r2 <= r1 ->\n  r4 <= r3 ->\n  ratDistance r1 r3 <= d1 ->\n  ratDistance r2 r4 <= d2 ->\n  ratDistance (ratSubtract r1 r2) (ratSubtract r3 r4) <= (d1 + d2).\n  \n  intuition.\n  eapply ratDistance_leRat_both.\n  eapply leRat_trans.\n  eapply ratSubtract_leRat.\n  eapply ratSubtract_leRat.\n  eapply ratDistance_le_sum.\n  eauto.\n  \n  eapply ratDistance_ge_difference.\n  rewrite ratDistance_comm.\n  eauto.\n  \n  eapply leRat_refl.\n  \n  eapply leRat_trans.\n  eapply ratSubtract_leRat.\n  rewrite ratAdd_comm.\n  eapply ratSubtract_ratAdd_assoc_le.\n  eapply leRat_refl.\n  rewrite ratSubtract_ratAdd_assoc_le.\n  eapply ratAdd_leRat_compat.\n  intuition.\n  eapply leRat_trans.\n  eapply ratSubtract_leRat.\n  \n  eapply ratSubtract_assoc_le.\n  eapply leRat_refl.\n  rewrite ratAdd_comm.\n  rewrite ratSubtract_ratAdd_assoc_le.\n  rewrite ratSubtract_0.\n  rewrite <- ratAdd_0_r.\n  intuition.\n  intuition.\n  \n  eapply leRat_trans.\n  eapply ratSubtract_leRat.\n  eapply ratSubtract_leRat.\n  eapply ratDistance_le_sum.\n  rewrite ratDistance_comm.\n  eauto.\n  eapply ratDistance_ge_difference.\n  eauto.\n  eapply leRat_refl.\n  \n  eapply leRat_trans.\n  eapply ratSubtract_leRat.\n  rewrite ratAdd_comm.\n  eapply ratSubtract_ratAdd_assoc_le.\n  eapply leRat_refl.\n  rewrite ratSubtract_ratAdd_assoc_le.\n  eapply ratAdd_leRat_compat.\n  intuition.\n  eapply leRat_trans.\n  eapply ratSubtract_leRat.\n  \n  eapply ratSubtract_assoc_le.\n  eapply leRat_refl.\n  rewrite ratAdd_comm.\n  rewrite ratSubtract_ratAdd_assoc_le.\n  rewrite ratSubtract_0.\n  rewrite <- ratAdd_0_r.\n  intuition.\n  intuition.    \n  \nQed.\n\nLemma ratMult_ratSubtract_distrib_r : forall f r1 r2,\n  (ratSubtract r1 r2) * f  == ratSubtract (r1 * f) (r2 * f).\n  \n  intuition.\n  unfold ratMult, ratSubtract.\n  rattac.\n  inversion H; clear H; subst.\n  \n  arithNormalize.\n  f_equal.\n  do 6 arithSimplify.\n  do 6 arithSimplify.\nQed.\n\nLemma ratMult_ratDistance_factor_r : forall r1 r2 r3,\n  ratDistance (r1 * r3) (r2 * r3) == (ratDistance r1 r2) * r3.\n  \n  intuition.\n  destruct (eq_Rat_dec r3 0).\n  repeat rewrite e.\n  repeat rewrite ratMult_0_r.\n  rewrite <- ratIdentityIndiscernables.\n  intuition.\n  unfold ratDistance, maxRat, minRat.\n  case_eq (bleRat r1 r2); intuition.\n  assert (bleRat (r1 * r3) ( r2 * r3) = true).\n  eapply ratMult_leRat_compat; \n    intuition.\n  rewrite H0.\n  rewrite ratMult_ratSubtract_distrib_r.\n  intuition.\n\n  case_eq (bleRat (r1 * r3) (r2 * r3)); intuition.\n  eapply leRat_ratMult_same_r in H0.\n  congruence.\n  intuition.\n  \n  rewrite ratMult_ratSubtract_distrib_r.\n  intuition.\n\nQed.\n\nLemma ratMult_ratDistance_factor_l : forall r1 r2 r3,\n  ratDistance (r3 * r1) (r3 * r2) == r3 * (ratDistance r1 r2).\n  \n  intuition.\n  repeat rewrite (ratMult_comm r3).\n  eapply ratMult_ratDistance_factor_r.\nQed.\n\nLemma ratAdd_rel_left_total : forall (r1 r2: Rat -> Prop),\n  (exists r1', r1 r1') ->\n  (exists r2', r2 r2') ->\n  (forall x1 x2, r1 x1 -> r1 x2 -> x1 == x2) ->\n  (forall x1 x2, r2 x1 -> r2 x2 -> x1 == x2) ->\n  exists r3, ratAdd_rel r1 r2 r3.\n  \n  unfold ratAdd_rel in *.\n  intuition.\n  destruct H.\n  destruct H0.\n  exists (x + x0).\n  intuition.\n  eapply ratAdd_eqRat_compat; eauto.\nQed.\n\nLemma expRat_eqRat_compat : forall n r1 r2,\n  r1 == r2 ->\n  expRat r1 n == expRat r2 n.\n\n  induction n; intuition; simpl in *; intuition.\n\n  eapply ratMult_eqRat_compat; eauto.\n\nQed.\n\nLemma expRat_rel_left_total : forall (r1 : Rat -> Prop) n,\n  (exists r1', r1 r1') ->\n  (forall x1 x2, r1 x1 -> r1 x2 -> x1 == x2) ->\n  exists r3, expRat_rel r1 n r3.\n  \n  unfold expRat_rel in *.\n  intuition.\n  destruct H.\n  exists (expRat x n).\n  intuition.\n  eapply expRat_eqRat_compat; eauto.\n  \nQed.\n\nLemma expRat_rel_func : forall (r : Rat -> Prop) v1 v2 n,\n  expRat_rel r n v1 ->\n  expRat_rel r n v2 ->\n  (forall x1 x2, r x1 -> r x2 -> x1 == x2) ->\n  (exists r', r r') ->\n  v1 == v2.\n  \n  unfold expRat_rel in *.\n  intuition.\n  destruct H2.\n  rewrite H; eauto.\n  rewrite H0; eauto.\n  intuition.\nQed.\n\nLemma ratInverse_involutive : forall r,\n  ~ r == 0 ->\n  ratInverse (ratInverse r) == r.\n  \n  intuition.\n  unfold ratInverse.\n  destruct r.\n  destruct n.\n  exfalso.\n  eapply H.\n  eapply rat_num_0.\n  \n  destruct p.\n  unfold posnatToNat, natToPosnat.\n  destruct x.\n  omega.\n  eapply eqRat_terms; intuition.\nQed.\n\nLemma ratInverse_ratMult : forall r1 r2,\n  ~ r1 == 0 ->\n  ~ r2 == 0 ->\n  ratInverse (r1 * r2) == ratInverse r1 * ratInverse r2.\n\n  intuition.\n  unfold ratInverse.\n  destruct r1.\n  destruct n.\n  exfalso.\n  eapply H.\n  eapply rat_num_0.\n  destruct r2.\n  destruct n0.\n  exfalso.\n  eapply H0.\n  eapply rat_num_0.\n  case_eq (RatIntro (S n) p * RatIntro (S n0) p0); intuition.\n  inversion H1; clear H1; subst.\n  unfold ratMult.\n  unfold natToPosnat, posnatToNat, posnatMult.\n  simpl.\n  eapply eqRat_terms.\n  destruct p.\n  destruct p0.\n  trivial.\n  simpl.\n  trivial.\n\nQed.\n\nLemma ratDistance_ratInverse : forall r1 r2,\n  ~ r1 == 0 ->\n  ~ r2 == 0 -> \n  ratDistance (ratInverse r1) (ratInverse r2) == (ratDistance r1 r2) * ratInverse (r1 * r2).\n\n  intuition.\n  rewrite ratInverse_ratMult; intuition.\n  rewrite <- ratMult_ratDistance_factor_r.\n  rewrite (ratMult_comm (ratInverse r1)) at 2.\n  repeat rewrite <- ratMult_assoc.\n  rewrite (ratMult_comm r1).\n  rewrite ratInverse_prod_1; intuition.\n  rewrite ratMult_1_l.\n  rewrite (ratMult_comm r2).\n  rewrite ratInverse_prod_1; intuition.\n  rewrite ratMult_1_l.\n  intuition.\n  eapply ratDistance_comm.\nQed.\n\nLemma ratSubtract_half : forall x,\n  ratSubtract x (x * (1/2)) == x * (1/2).\n  \n  intuition.\n  unfold ratSubtract.\n  rattac.\n  arithNormalize.\n  inversion H; clear H; subst.\n  rewrite <- (mult_assoc (n * x * 2)).\n  rewrite (mult_comm (n * x)).\n  repeat rewrite mult_assoc.\n  simpl.\n  rewrite (plus_0_r).\n  repeat rewrite mult_plus_distr_r.\n  remember (n * x * x * 2)%nat as a.\n  omega.\nQed.\n\nLemma ratMult_ratAdd_cd : forall r n (d : posnat),\n  r + r * (RatIntro n d) == r * (RatIntro (d + n)%nat d).\n  \n  intuition.\n  unfold ratAdd, ratMult.\n  rattac.\n  arithNormalize.\n  arithSimplify.\n  do 4 arithSimplify.\nQed.\n\nDefinition numerator r :=\n  match r with\n    | RatIntro n d => n\n  end.\n\nLemma ratDistance_add_same_l_gen : forall r1 r2 r3 r4,\n  r1 == r3 ->\n  ratDistance (r1 + r2) (r3 + r4) == ratDistance r2 r4.\n  \n  intuition.\n  rewrite H.\n  eapply ratDistance_add_same_l.\nQed.\n\nLemma ratDistance_add_same_r_gen : forall r1 r2 r3 r4,\n  r2 == r4 ->\n  ratDistance (r1 + r2) (r3 + r4) == ratDistance r1 r3.\n  \n  intuition.\n  rewrite H.\n  eapply ratDistance_add_same_r.\nQed.\n\nLemma ratDistance_from_0 : forall r,\n  ratDistance 0 r == r.\n  \n  intuition.\n  unfold ratDistance, maxRat, minRat.\n  rewrite rat0_le_all.\n  eapply ratSubtract_0_r.\nQed.\n\nLemma maxRat_comm : forall r1 r2,\n  maxRat r1 r2 == maxRat r2 r1.\n  \n  intuition.\n  unfold maxRat.\n  case_eq (bleRat r1 r2); intuition.\n  case_eq (bleRat r2 r1); intuition.\n  eapply leRat_impl_eqRat; trivial.\n  apply bleRat_total in H.\n  rewrite H.\n  intuition.\nQed.\n\nLemma ratDistance_le_max_triv : forall r1 r2,\n  ratDistance r1 r2 <= maxRat r1 r2.\n  \n  intuition.\n  eapply leRat_trans.\n  eapply ratDistance_le_max.\n  eapply rat0_le_all.\n  eapply (@ratAdd_any_leRat_l r1 r2).\n  eapply leRat_refl.\n  eapply leRat_trans.\n  eapply eqRat_impl_leRat.\n  eapply maxRat_eqRat_compat.\n  eapply ratDistance_from_0.\n  \n  eapply eqRat_trans.\n  eapply ratDistance_eqRat_compat.\n  eapply eqRat_refl.\n  eapply ratAdd_0_l.\n  rewrite ratDistance_add_same_r.\n  rewrite ratDistance_comm.\n  eapply ratDistance_from_0.\n  \n  rewrite maxRat_comm.\n  intuition.\nQed.\n\nLemma ratAdd_2_ratMax : \n  forall r1 r2,\n    (r1 + r2 <= 2 / 1 * (maxRat r1 r2))%rat.\n  \n  intuition.\n  \n  unfold maxRat.\n  case_eq (bleRat r1 r2); intuition.\n  eapply leRat_trans.\n  eapply ratAdd_leRat_compat.\n  eapply H.\n  eapply leRat_refl.\n  rewrite ratMult_2.\n  rewrite ratMult_comm.\n  intuition.\n  \n  apply bleRat_total in H.\n  eapply leRat_trans.\n  eapply ratAdd_leRat_compat.\n  eapply leRat_refl.\n  eapply H.     \n  rewrite ratMult_2.\n  rewrite ratMult_comm.\n  intuition.\nQed.\n\nTheorem rat_num_not_le : \n  forall (d1 d2 : posnat),\n    (RatIntro 1 d1 <= RatIntro 1 d2)%rat ->\n    d1 < d2 ->\n    False.\n  \n  intuition.\n  rattac.\n  \nQed.\n\nLemma leRat_0_eq : \n  forall r, \n    (r <= 0 ->\n      r == 0)%rat.\n  \n  intuition.\n  rattac.\n  symmetry.\n  eapply le_n_0_eq.\n  unfold natToPosnat, posnatToNat in *.\n  rewrite mult_1_r in l.\n  rewrite l.\n  destruct p.\n  rewrite mult_0_l.\n  intuition.\nQed.\n\nLemma rat_le_1_if : \n  forall n d,\n    RatIntro n d <= 1 ->\n    (n <= d)%nat.\n  \n  intuition.\n  \n  unfold leRat, bleRat, ratCD, rat1 in *.\n  unfold natToPosnat, posnatToNat in *.\n  destruct d.\n  rewrite mult_1_r in H.\n  rewrite mult_1_l in H.\n  destruct (le_gt_dec n x); intuition.\n  discriminate.\n  \nQed.\n\n\nTheorem ratFraction_le_1 : \n  forall r1 r2,\n    r1 <= r2 ->\n    r1 * (ratInverse r2) <= 1.\n  \n  intuition.\n  unfold ratInverse.\n  destruct r2.\n  destruct n.\n  rewrite H.\n  rewrite rat_num_0.\n  rewrite ratMult_0_l.\n  eapply rat0_le_all.\n  rewrite H.\n  rewrite <- ratMult_num_den.\n  eapply rat_le_1.\n  \n  unfold posnatMult, natToPosnat, posnatToNat.\n  destruct p.\n  rewrite mult_comm.\n  intuition.\nQed.\n\nTheorem ratFraction_ge_1_inv : \n  forall r1 r2,\n    1 <= r1 * (ratInverse r2) ->\n    r2 <= r1.\n  \n  intuition.\n  \n  destruct (eq_Rat_dec r2 0).\n  rewrite e.\n  eapply rat0_le_all.\n  \n  eapply (@leRat_ratMult_same_r (ratInverse r2)).\n  intuition.\n  eapply ratInverse_nz.\n  eauto.\n  rewrite ratMult_comm.\n  rewrite ratInverse_prod_1.\n  intuition.\n  intuition.\n\nQed.\n\nTheorem eqRat_refl_eq : \n  forall x y,\n    x = y ->\n    x == y.\n  \n  intuition; subst.\n  intuition.\n  \nQed.\n\nTheorem rat_num_S : \n  forall n d,\n    (RatIntro (S n) d == (RatIntro 1 d) + RatIntro n d)%rat.\n  \n  intuition.\n  rattac.\n  rewrite mult_plus_distr_r.\n  f_equal.\n  eapply mult_assoc.\nQed.\n\nTheorem distance_le_prod_f :\n  forall (f : nat -> Rat) k,\n    (forall i, | (f i) - (f (S i)) | <= k) ->\n    forall q0,\n| (f 0%nat) - (f q0) | <= q0/1 * k.\n  \n  induction q0; intuition.\n  assert (| f 0%nat - f 0%nat | == 0).\n  rewrite <- ratIdentityIndiscernables.\n  reflexivity.\n  rewrite H0.\n  eapply rat0_le_all.\n  \n  eapply leRat_trans.\n  eapply ratTriangleInequality.\n  rewrite IHq0.\n  rewrite H.\n  \n  rewrite rat_num_S.\n  rewrite ratMult_distrib_r.\n  rewrite ratAdd_comm.\n  eapply ratAdd_leRat_compat.\n  rewrite ratMult_1_l.\n  reflexivity.\n  reflexivity.\nQed.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/fcf/Rat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.7690802264851918, "lm_q1q2_score": 0.6505975923174534}}
{"text": "From Coq Require Export List.\nImport ListNotations.\nLocal Open Scope list_scope.\nRequire Import Nat.\nRequire Import Psatz.\nRequire Import ZArith.\n\nRequire Import Common.\nRequire Import Basic.\nRequire Import Lt.\n\nImport Common.\n\nLocal Open Scope nat_scope.\n\n\nFixpoint plus (b b' : bilist) : bilist :=\n  match b with\n  | [] => b' \n  | h :: t => let l := plus t b' in\n              let (p, r) := split (length l - (length t)) l in\n              match h with\n              | E1 => (incr1 p) ++ r\n              | E2 => (incr2 p) ++ r\n              end\n  end.     \n\n\nExample test_plus_1 :  plus [E1] [E1] = [E2].\nProof.\nauto. Qed.\n\nExample test_plus_2 :  plus [E1] [E2] = [E1;E1].\nProof.\n    auto. Qed.\n    \nExample test_plus_3 :  plus [E2] [E2] = [E1;E2].\nProof.\nauto. Qed.\n\nExample test_plus_4 :  plus [E1] [E1;E1] = [E1;E2].\nProof.\nauto. Qed.\n\nExample test_plus_5 :  plus [E1] [E2;E2] = [E1;E1;E1].\nProof.\nauto. Qed.\n\nExample test_plus_6 :  plus [E2;E2] [E2;E2] = [E2;E1;E2].\nProof.\n    auto. Qed.\n  \n  \nExample test_plus_7:  plus [E1;E1] [E1] = [E1;E2].\nProof.\nauto. Qed.\n\nExample test_plus_8 :  plus [E2;E2] [E1] = [E1;E1;E1].\nProof.\nauto. Qed.\n\nExample test_plus_9 :  plus [E1;E2] [E2;E2] = [E1;E2;E2].\nProof.\n    auto. Qed.\n  \nExample test_plus_10 :  plus [E1; E1] [E1; E1; E1] = [E1;E2;E2].\nProof.\n    auto. \nQed.\n\nExample test_plus_11 :  plus [E1; E2] [E1; E2; E1] = [E2;E2;E1].\nProof.\n    auto. \nQed.\n\nExample test_plus_12 :  plus [E2;E2] [E1;E2] = [E1;E2;E2].\nProof.\n    auto. Qed.\n\nExample test_plus_13 :  plus [E1; E1;E1] [ E1; E1] = [E1;E2;E2].\nProof.\n    auto. \nQed.\n\nExample test_plus_14 :  plus [E1; E2;E1] [E1; E2] = [E2;E2;E1].\nProof.\n    auto. \nQed.\n\n\nLemma incr_plus_r: forall b : bilist,\n  incr1 b = plus [E1] b.\nProof.\n  induction b.\n  auto.\n  simpl.\n  simpl in IHb.\n  rewrite skipn_n in IHb.\n  rewrite PeanoNat.Nat.sub_0_r  with (length b) in IHb.\n  simpl in IHb.\n  rewrite firstn_n. rewrite <- PeanoNat.Nat.sub_0_r with (length b).\n  rewrite skipn_n.\n  rewrite app_nil_r. auto.\nQed.\n\nLemma incr_plus_l: forall b : bilist, incr1 b = plus b [E1].\nProof.\n  induction b using list_ind_length.\n  auto.\n  destruct b. auto.\n  simpl.\n  remember (length (incr1 b0) =? length b0).\n  destruct b1; destruct b.\n  -\n  rewrite <- H.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_eq in Heqb1.\n  rewrite Heqb1.\n  rewrite PeanoNat.Nat.sub_diag.\n  rewrite firstn_O.\n  rewrite skipn_O.\n  simpl. auto.\n  auto.\n  -\n  rewrite <- H.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_eq in Heqb1.\n  rewrite Heqb1.\n  rewrite PeanoNat.Nat.sub_diag.\n  rewrite firstn_O.\n  rewrite skipn_O.\n  simpl. auto.\n  auto.\n  - rewrite <- H.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  enough (S (length b0) = length (incr1 b0)).\n  rewrite <- H0.\n  replace (S (length b0) - length b0) with 1.\n  replace ((firstn 1 (incr1 b0))) with [E1].\n  replace (skipn 1 (incr1 b0)) with (tl ((incr1 b0))).\n  simpl. auto.\n  rewrite skipn_1. auto.\n  destruct b0.\n  simpl. auto.\n  simpl. destruct b; destruct (length (incr1 b0) =? length b0); simpl; try lia; auto.\n  apply forall_head.\n  destruct b0.\n  simpl. auto.\n  simpl. destruct b; destruct (length (incr1 b0) =? length b0); simpl; try lia; auto.\n  apply incr1_cons1.\n  lia. lia.\n  apply incr1_length_plus.\n  enough (length b0 <= length (incr1 b0)). lia.\n  apply incr1_length.\n  auto.\n  - rewrite <- H.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  enough (S (length b0) = length (incr1 b0)).\n  rewrite <- H0.\n  replace (S (length b0) - length b0) with 1.\n  replace ((firstn 1 (incr1 b0))) with [E1].\n  replace (skipn 1 (incr1 b0)) with (tl ((incr1 b0))).\n  simpl.\n  rewrite head_tail with (l:=incr1 b0) at 1.\n  replace (firstn 1 (incr1 b0)) with [E1]. auto.\n  apply forall_head.\n  lia.  apply incr1_cons1.\n  lia. lia.\n  apply skipn_1. lia.\n  apply forall_head.\n  lia. apply incr1_cons1. lia. lia.\n  apply incr1_length_plus.\n  enough (length b0 <= length (incr1 b0)). lia.\n  apply incr1_length.\n  auto.\n  \nQed.\n\n\nLemma plus_nil: forall b, plus b [] = b.\nProof.\n  induction b.\n  auto.\n  simpl.\n  destruct a.\n  rewrite ?IHb.\n  rewrite ?PeanoNat.Nat.sub_diag. \n  simpl. auto.\n  rewrite ?IHb.\n  rewrite ?PeanoNat.Nat.sub_diag.\n  simpl.\n  auto.\nQed.\n\nLemma plus_len: forall b b', \n  length b <= length (plus b b').\nProof.\n  intros.\n  generalize dependent b'.\n  induction b using list_ind_length; intros.\n  simpl. lia.\n  destruct b.\n  simpl. lia.\n  simpl.\n  destruct b.\n  -\n  rewrite app_length.\n  rewrite skipn_length.\n  replace (length (plus b0 b') - (length (plus b0 b') - length b0)) with (length b0).\n  remember (firstn (length (plus b0 b') - length b0) (plus b0 b')).\n  destruct l.\n  simpl.  lia.\n  simpl.\n  destruct b; destruct (length (incr1 l) =? length l); simpl; lia.\n  enough (length b0 <= length (plus b0 b')).\n  lia.\n  apply H.\n  simpl. lia.\n  -\n  rewrite app_length.\n  rewrite skipn_length.\n  replace (length (plus b0 b') - (length (plus b0 b') - length b0)) with (length b0).\n  remember (firstn (length (plus b0 b') - length b0) (plus b0 b')).\n  destruct l.\n  simpl.  lia.\n  simpl.\n  destruct b; destruct (length (incr2 l) =? length l); simpl; destruct l; simpl length; lia.\n  enough (length b0 <= length (plus b0 b')).\n  lia.\n  apply H.\n  simpl. lia.\nQed.\n\n\nLemma lt_plus: forall b b',\n0 < length b' -> \nbinary_lt b (plus b b').\nProof.\n  intros.\n  generalize dependent b'.\n  induction b using list_ind_length; intros.\n  simpl. \n  destruct b'. inversion H.\n\n  constructor. simpl. lia.\n  destruct b.\n  simpl.\n  destruct b'. inversion H0.\n  constructor. simpl. lia.\n  simpl.\n  destruct b.\n  -\n  remember (length (plus b0 b') - length b0) as n.\n  remember (plus b0 b') as x.\n  remember (iter_incr1_tail x (length b0)).\n  assert (iter (2 ^ length b0) incr1 x = incr1 (firstn (length x - length b0) x) ++ skipn (length x - length b0) x).\n  apply a.\n  rewrite Heqx.\n  apply binary_lt_length.\n  apply H.\n  simpl. lia.\n  destruct b'. inversion H0.\n  simpl. lia.\n  rewrite <- Heqn in H1.\n  rewrite <- H1.\n  clear a Heqa.\n  assert (E1 :: b0  = iter (2 ^ length b0) incr1 b0).\n  rewrite iter_incr1_tail1.\n  auto.\n  rewrite H2.\n  apply binary_lt_incr1_iter_hom.\n  rewrite Heqx.\n  apply H.\n  simpl. lia.\n  destruct b'. inversion H0.\n  simpl. lia.\n  -\n  remember (length (plus b0 b') - length b0) as n.\n  remember (plus b0 b') as x.\n  remember (iter_incr1_tail x (length b0)).\n  assert (iter (2 ^ length b0 + 2 ^ length b0) incr1 x =\n  incr2 (firstn (length x - length b0) x) ++ skipn (length x - length b0) x).\n  apply a.\n  rewrite Heqx.\n  apply binary_lt_length.\n  apply H.\n  simpl. lia.\n  destruct b'. inversion H0.\n  simpl. lia.\n  rewrite <- Heqn in H1.\n  rewrite <- H1.\n  clear a Heqa.\n  assert (E2 :: b0  = iter (2 ^ length b0 + 2 ^ length b0) incr1 b0).\n  rewrite iter_incr1_tail2.\n  auto.\n  rewrite H2.\n  apply binary_lt_incr1_iter_hom.\n  rewrite Heqx.\n  apply H.\n  simpl. lia.\n  destruct b'. inversion H0.\n  simpl. lia.\nQed.\n\n\n\nLemma plus_incr1_left: forall b b', plus (incr1 b) b' = incr1 (plus b  b') .\nProof.\n  intros.\n  generalize dependent b'.\n  induction b using bilist_lt_ind.\n  intros.\n  simpl.\n  replace (length b' - 0) with (length b').\n  rewrite firstn_all.\n  rewrite skipn_all.\n  rewrite ?app_nil_r.\n  auto.\n  lia.\n  intros.\n\n  destruct b.\n  simpl.\n  replace (length b' - 0) with (length b').\n  rewrite firstn_all.\n  rewrite skipn_all.\n  rewrite ?app_nil_r.\n  auto.\n  lia.\n  simpl.\n  remember (length (incr1 b0) =? length b0).\n  remember (length (plus b0 b') - length b0).\n  remember (plus b0 b') as x.\n  destruct b; destruct b1.\n  -\n  simpl.\n  rewrite H.\n  rewrite <- Heqx.\n  remember ((length (incr1 x) - length (incr1 b0))) as m.\n  remember (iter_incr1_tail x (length b0)).\n  clear Heqa.\n  rewrite <- Heqn in a.\n  assert (iter (2 ^ length b0) incr1 x = incr1 (firstn n x) ++ skipn n x).\n  apply a.\n  rewrite Heqx.\n  apply plus_len.\n  rewrite <- H0.\n  remember (iter_incr1_tail (incr1 x) (length (incr1 b0))).\n  clear Heqa0.\n  rewrite <- Heqm in a0.\n  assert (iter (2 ^ length (incr1 b0)) incr1 (incr1 x) =\n  incr1 (firstn m (incr1 x)) ++ skipn m (incr1 x)).\n  apply a0.\n  rewrite Heqx.\n  destruct b'.\n  rewrite plus_nil. lia.\n  apply incr1_length_hom.\n  apply lt_plus.\n  simpl. lia.\n  clear a H0 a0 H1.\n  remember (iter_incr1_tail (incr1 x) (length (incr1 b0))).\n  assert (iter (2 ^ length (incr1 b0)) incr1 (incr1 x) =\n  incr1 (firstn (length (incr1 x) - length (incr1 b0)) (incr1 x)) ++\n  skipn (length (incr1 x) - length (incr1 b0)) (incr1 x)).\n  apply a.\n  rewrite Heqx.\n  destruct b'.\n  rewrite plus_nil. lia.\n  apply incr1_length_hom.\n  apply lt_plus. simpl. lia.\n  rewrite <- Heqm in H0.\n  rewrite <- H0.\n  replace (length (incr1 b0)) with (length b0).\n  rewrite <- iterS.\n  simpl. auto.\n  apply PeanoNat.Nat.eqb_eq.\n  rewrite Heqb1.\n  apply PeanoNat.Nat.eqb_sym.\n  constructor. lia.\n  - simpl.\n  remember (length (plus (tl (incr1 b0)) b') - length (tl (incr1 b0))) as m.\n  remember ((plus (tl (incr1 b0)) b')).\n  destruct b0.\n  +\n  simpl in Heqb.\n  simpl in Heqm.\n  simpl in Heqx.\n  simpl in Heqn.\n  rewrite Heqx.\n  rewrite Heqb.\n  replace m with n.\n  subst.\n  replace (length b' - 0) with (length b') by lia.\n  rewrite firstn_all2.\n  rewrite skipn_all2.\n  rewrite ?app_nil_r.\n  rewrite incr2_incr1.\n  auto.\n  lia. lia.\n  subst.\n  auto.\n  +\n  rewrite <- incr1_tl_comm_E2 in Heqb.\n  rewrite H in Heqb.\n  rewrite <- incr1_tl_comm_E2 in Heqm.\n  simpl in Heqm.\n  simpl in Heqb.\n  remember  (iter_incr1_tail b (length (incr1 b1))).\n  assert (iter (2 ^ length (incr1 b1) + 2 ^ length (incr1 b1)) incr1 b =\n  incr2 (firstn (length b - length (incr1 b1)) b) ++ skipn (length b - length (incr1 b1)) b).\n  apply a.\n  rewrite Heqb.\n  destruct b'.\n  rewrite plus_nil. lia.\n  apply incr1_length_hom.\n  apply lt_plus. simpl. lia.\n  rewrite <- Heqm in H0.\n  rewrite <- H0.\n  clear a Heqa H0.\n  remember  (iter_incr1_tail x (length (b0 :: b1))).\n  assert (iter (2 ^ length (b0 :: b1)) incr1 x =\n  incr1 (firstn (length x - length (b0 :: b1)) x) ++ skipn (length x - length (b0 :: b1)) x).\n  apply a.\n  rewrite Heqx.\n  apply plus_len.\n  rewrite <- Heqn in H0.\n  rewrite <- H0.\n  simpl.\n  simpl in Heqx.\n  replace b0 with E2 in Heqx.\n  clear a Heqa H0.\n  remember (plus b1 b') as y.\n  remember  (iter_incr1_tail y (length b1)).\n  assert (iter (2 ^ length b1 + 2 ^ length b1) incr1 y =\n  incr2 (firstn (length y - length b1) y) ++ skipn (length y - length b1) y).\n  apply a.\n  rewrite Heqy.\n  apply plus_len.\n  rewrite <- H0 in Heqx.\n  clear a Heqa H0.\n  rewrite Heqx.\n  rewrite Heqb.\n  replace (2 ^ length b1 + (2 ^ length b1 + 0)) with (2 ^ length b1 + 2 ^ length b1 ).\n  replace (length (incr1 b1)) with (S (length b1)).\n  simpl.\n  replace  (2 ^ length b1 + 0) with (2 ^ length b1 ).\n  rewrite iter_plus.\n  rewrite <- iterS.\n  simpl.\n  rewrite <- iterS.\n  simpl. auto.\n  lia.\n  apply incr1_length_plus.\n  apply incr1_cons2_inv.\n  enough (length (b0 :: b1) < length (incr1 (b0 :: b1))).\n  apply incr1_cons2 in H0.\n  inversion H0. auto.\n  enough (length (b0 :: b1) <= length (incr1 (b0 :: b1))).\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  lia.\n  apply incr1_length.\n  lia.\n  enough (Forall (eq E2) (b0 :: b1)).\n  inversion H1. auto.\n  apply incr1_cons2.\n  enough (length (b0 :: b1) <= length (incr1 (b0 :: b1))).\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  lia. apply incr1_length.\n  simpl. lia.\n  apply incr1_cons2.\n  enough (length (b0 :: b1) <= length (incr1 (b0 :: b1))).\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  lia. apply incr1_length.\n  simpl.\n  constructor 1. simpl. lia.\n  simpl. lia.\n  apply incr1_cons2.\n  enough (length (b0 :: b1) <= length (incr1 (b0 :: b1))).\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  lia. apply incr1_length.\n  -\n  simpl.\n  remember (length (plus (incr1 b0) b') - length (incr1 b0)) as m.\n  rewrite H.\n  rewrite <- Heqx.\n  remember  (iter_incr1_tail x (length b0)).\n  assert (iter (2 ^ length b0 + 2 ^ length b0) incr1 x =\n  incr2 (firstn (length x - length b0) x) ++ skipn (length x - length b0) x).\n  apply a.\n  rewrite Heqx.\n  apply plus_len.\n  rewrite <- Heqn in H0.\n  rewrite <- H0.\n  clear a Heqa H0.\n  rewrite H in Heqm.\n  rewrite <- Heqx in Heqm.\n  remember  (iter_incr1_tail (incr1 x) (length (incr1 b0))).\n  assert (iter (2 ^ length (incr1 b0) + 2 ^ length (incr1 b0)) incr1 (incr1 x) =\n  incr2 (firstn (length (incr1 x) - length (incr1 b0)) (incr1 x)) ++\n  skipn (length (incr1 x) - length (incr1 b0)) (incr1 x)).\n  apply a.\n  rewrite Heqx.\n  destruct b'.\n  rewrite plus_nil.\n  lia.\n  apply incr1_length_hom.\n  apply lt_plus. simpl. lia.\n  rewrite <- Heqm in H0.\n  rewrite <- H0.\n  rewrite <- iterS.\n  simpl.\n  replace (length (incr1 b0)) with (length b0).\n  auto.\n  apply PeanoNat.Nat.eqb_eq.\n  rewrite Heqb1.\n  apply PeanoNat.Nat.eqb_sym.\n  constructor. lia.\n  constructor. lia.\n  -\n  simpl.\n  rewrite H.\n  rewrite <- Heqx.\n  remember (length (incr1 x) - length (incr1 b0)) as m.\n  remember  (iter_incr1_tail x (length b0)).\n  assert (iter (2 ^ length b0 + 2 ^ length b0) incr1 x =\n  incr2 (firstn (length x - length b0) x) ++ skipn (length x - length b0) x).\n  apply a.\n  rewrite Heqx.\n  apply plus_len.\n  rewrite <- Heqn in H0.\n  rewrite <- H0.\n  clear a Heqa H0.\n  remember  (iter_incr1_tail (incr1 x) (length (incr1 b0))).\n  assert (iter (2 ^ length (incr1 b0)) incr1 (incr1 x) =\n  incr1 (firstn (length (incr1 x) - length (incr1 b0)) (incr1 x)) ++\n  skipn (length (incr1 x) - length (incr1 b0)) (incr1 x)).\n  apply a.\n  rewrite Heqx.\n  destruct b'.\n  rewrite plus_nil.\n  lia.\n  apply incr1_length_hom.\n  apply lt_plus. simpl. lia.\n  rewrite <- Heqm in H0.\n  rewrite <- H0.\n  replace (length (incr1 b0)) with (S (length b0)).\n  simpl.\n  replace (2 ^ length b0 + (2 ^ length b0 + 0)) with (2 ^ length b0 + 2 ^ length b0 ).\n  rewrite <- iterS.\n  simpl. auto.\n  lia.\n  apply incr1_length_plus.\n  enough (length b0 <= length (incr1 b0)).\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  lia.\n  apply incr1_length.\n  constructor. lia.\nQed.\n\n\nLemma plus_incr1_right: forall b b', plus b (incr1 b') = incr1 (plus b b') .\nProof.\n  intros.\n  generalize dependent b'.\n  induction b using bilist_lt_ind.\n  intros.\n  simpl. auto.\n\n  intros.\n  destruct b.\n  simpl. auto.\n  simpl.\n  rewrite H.\n  remember  (plus b0 b') as x.\n  destruct b.\n  -\n  remember ((length (incr1 x) - length b0)) as m.\n  remember (length x - length b0) as n.\n  remember (iter_incr1_tail x (length b0)).\n  clear Heqa.\n  assert (iter (2 ^ length b0) incr1 x =\n  incr1 (firstn (length x - length b0) x) ++ skipn (length x - length b0) x).\n  apply a.\n  rewrite Heqx.\n  apply plus_len.\n  rewrite <- Heqn in H0.\n  rewrite <- H0.\n  clear a H0.\n  remember (iter_incr1_tail (incr1 x) (length  b0)).\n  assert (iter (2 ^ length b0) incr1 (incr1 x) =\n  incr1 (firstn (length (incr1 x) - length b0) (incr1 x)) ++\n  skipn (length (incr1 x) - length b0) (incr1 x)).\n  apply a.\n  rewrite Heqx.\n  destruct b'.\n  rewrite plus_nil. \n  apply incr1_length.\n  apply binary_lt_length.\n  apply binary_lt_trans with (b:=(plus b0 (b :: b'))).\n  apply lt_plus.\n  simpl. lia.\n  apply lt_incr1.\n  rewrite <- Heqm in H0.\n  rewrite <- H0.\n  clear a Heqa H0.\n  rewrite <- iterS. simpl. auto.\n- \n  remember ((length (incr1 x) - length b0)) as m.\n  remember (length x - length b0) as n.\n  remember (iter_incr1_tail x (length b0)).\n  clear Heqa.\n  assert (iter (2 ^ length b0 + 2 ^ length b0) incr1 x =\n  incr2 (firstn (length x - length b0) x) ++ skipn (length x - length b0) x).\n  apply a.\n  rewrite Heqx.\n  apply plus_len.\n  rewrite <- Heqn in H0.\n  rewrite <- H0.\n  clear a H0.\n  remember (iter_incr1_tail (incr1 x) (length  b0)).\n  assert (iter (2 ^ length b0 + 2 ^ length b0) incr1 (incr1 x) =\n  incr2 (firstn (length (incr1 x) - length b0) (incr1 x)) ++\n  skipn (length (incr1 x) - length b0) (incr1 x)).\n  apply a.\n  rewrite Heqx.\n  destruct b'.\n  rewrite plus_nil. \n  apply incr1_length.\n  apply binary_lt_length.\n  apply binary_lt_trans with (b:=(plus b0 (b :: b'))).\n  apply lt_plus.\n  simpl. lia.\n  apply lt_incr1.\n  rewrite <- Heqm in H0.\n  rewrite <- H0.\n  clear a Heqa H0.\n  rewrite <- iterS. simpl. auto.\n-\n  constructor.\n  lia.\nQed.    \n\nTheorem plus_comm: forall b b' : bilist,\n  plus b b' = plus b' b.\nProof.\n  intros.\n  generalize dependent b'.\n  induction b using bilist_incr_ind.\n  intros.\n  rewrite plus_nil. simpl. auto.\n  intros.\n  enough (forall b b', plus (incr1 b) b' = incr1 (plus b b')).\n  enough (forall b b', plus b (incr1 b') = incr1 (plus b b')).\n  rewrite H.\n  rewrite IHb.\n  rewrite H0.\n  auto.\n  intros. apply plus_incr1_right.\n  intros. apply plus_incr1_left.\nQed.  \n\n\nFixpoint plus' (b b' : bilist) :  bilist := \nmatch b with\n| [] => b'\n| E1 :: t => iter (pow 2 (length t)) incr1 (plus' t b')\n| E2 :: t => iter (pow 2 (length t) + pow 2 (length t)) incr1 (plus' t b')\nend.\n\nLemma plus'_0_l: forall b, plus' [] b = b .\nProof.\n  simpl.\n  auto.\nQed.\n\nLemma iter_incr1_next_digit: forall b,\niter (2 ^ length b) incr1 b = E1 :: b /\\\niter (2 ^ length b + 2 ^ length b) incr1 b = E2 :: b.\nProof.\n  intros.\n  remember (iter_incr1_tail b (length b)).\n  assert (iter (2 ^ length b) incr1 b =\n  incr1 (firstn (length b - length b) b) ++ skipn (length b - length b) b /\\\n  iter (2 ^ length b + 2 ^ length b) incr1 b =\n  incr2 (firstn (length b - length b) b) ++ skipn (length b - length b) b).\n  apply a.\n  lia.\n  clear Heqa a.\n  inversion_clear H.\n  rewrite H0. rewrite H1.\n  replace (length b - length b) with 0 by lia.\n  simpl.\n  auto.\nQed.\n\n\nLemma plus'_0_r: forall b, plus' b [] = b .\nProof.\n  induction b using list_ind_length.\n  auto.\n  destruct b; auto.\n  simpl.\n\n  destruct b.\n  -\n  rewrite H; [| simpl; lia].\n  apply iter_incr1_next_digit.\n  -\n  rewrite H; [| simpl; lia].\n  apply iter_incr1_next_digit.\nQed.\n\n\nLemma plus_plus': forall b b', plus b b' = plus' b b'.\nProof.\n  intros.\n  generalize dependent b'.\n  induction b using list_ind_length; intros.\n  simpl. auto.\n  destruct b; auto.\n  simpl.\n  rewrite <- H.\n  remember (plus b0 b').\n  remember (iter_incr1_tail b1 (length b0)).\n  enough (length b0 <= length b1).\n  apply a in H0.\n  inversion_clear H0.\n  rewrite H1, H2.\n  auto.\n  rewrite Heqb1.\n  apply plus_len.\n  simpl. lia.\nQed.\n", "meta": {"author": "Pruvendo", "repo": "dyadic-arith", "sha": "e3f4927ff49cf46e9e3b26edead241b47a4f6951", "save_path": "github-repos/coq/Pruvendo-dyadic-arith", "path": "github-repos/coq/Pruvendo-dyadic-arith/dyadic-arith-e3f4927ff49cf46e9e3b26edead241b47a4f6951/src/Diadic/Plus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.6505097484460898}}
{"text": "(***********************************************************)\n(*      This file contains a direct implementation with no *)\n(*      optimisation of Fourier-Mozkin algorithm. We use   *)\n(*      it to show that a system is unsolvable             *)\n(***********************************************************)\n\nRequire Import ZArith Znumtheory List.\nRequire Import FourierConcTerm.\n\n(***********************************************************)\n(* We first describe the algorithm then its partial        *)\n(* correctness proof                                       *)\n(***********************************************************)\n\n(***********************************************************)\n(* The implementation is naive. The set of inequations is  *)\n(* as a matrices (i.e a list of list of integers), the     *)\n(* constant part of the equation is separated in order to  *)\n(* make variable elimination only for the variables part   *)\n(* A sparse representation should be more sensible but     *)\n(* anyway Fourier is not a good choice for large problems  *)\n(*                                                         *)\n(* A line of the inequation contains the list of the       *)\n(* coefficients of the variable and a constant.            *)\n(* For example                                             *)\n(* 3x + z >= 4 is encoded as line (3::0::1::nil) -4 lLe    *)\n(*  x + y >  2 is encoded as line (1::1::0::nil) -2 lLt    *)\n(*  x = y      is encoded as line (1::-1::0::nil) 0 lEq    *)\n(***********************************************************)\nInductive ltype : Type := lEq | lLt | lLe.\nInductive line : Type := Line (_: list Z) (_: Z) (_:ltype).\n\n(* A system is a list of line *)\nDefinition dt := list line.\n\n(* An example\n      3x + y - z >= 0\n      2x     + z >= 2\n      -x + y + z >= 0\n*)\nDefinition ex1 :=    Line (3::1::-1::nil)%Z 0 lLe::\n                     Line (2::0::1::nil)%Z (-2) lLe :: \n                     Line (-1::1::1::nil)%Z 0 lLe ::nil.\n\n(* How line types combine *)\n\nDefinition lmerge t1 t2 :=\n  match t1 with\n    lEq => t2\n  | lLt => t1\n  | lLe => match t2 with lLt => t2 | _ => t1 end\n  end.\n\n(* Some check *)\nLemma lmerge_id: forall t, lmerge t t = t.\nProof. intro t; destruct t; auto. Qed.\n\nLemma lmerge_sym: forall t1 t2, lmerge t1 t2 = lmerge t2 t1.\nProof. intros t1 t2; destruct t1; destruct t2; auto. Qed.\n\n\n(***********************************************************)\n(*  Splitting the system in 3 depending of the top coef    *)\n(*    the positive part, the negative one, the zero one    *)\n(***********************************************************)\n\n(* The split datastructure *)\nInductive op_eq : Type :=\n  | Some_eq (_: positive) (_: list Z) (_: Z)\n  | No_eq.\n\nInductive dt4 :Type := DT4 (_: op_eq) (_ _ _: dt). \n(* Empty split *)\nDefinition nil_dt4 := DT4 No_eq nil nil nil.\n\n(* Add an element in the zero part *)\nDefinition add4z l (v: dt4) : dt4 :=\n  let (e,lp,ln,lz) := v in DT4 e lp ln (l::lz). \n(* Add an element in the positive part *)\nDefinition add4p l (v: dt4) : dt4 :=\n  let (e,lp,ln,lz) := v in DT4  e (l::lp) ln lz.\n(* Add an element in the negative part *)\nDefinition add4n l (v: dt4) : dt4 :=\n  let (e,lp,ln,lz) := v in DT4  e lp (l::ln) lz.\n(* Add an element in the equation part *)\nDefinition add4e p l c (v: dt4) : dt4 :=\n  let (e,lp,ln,lz) := v in \n  match e with \n    No_eq => DT4 (Some_eq p l c) lp ln lz\n  | Some_eq p1 l1 c1 =>\n     match (p ?= p1)%positive with\n       Lt => DT4 (Some_eq p l c) (Line (Zpos p1::l1) c1 lEq::lp) ln lz\n    |  _  => DT4 e (Line (Zpos p::l) c lEq::lp) ln lz\n    end\n  end.\n\nFixpoint oppsm (l: list Z): list Z :=\n  match l with nil => nil | v :: l1 => -v :: oppsm l1 end.\n\n(* Splitting in a tail recursive way *)\nFixpoint split_aux (v: dt) (r: dt4) {struct v}: dt4 :=\n  match v with \n    nil => r\n  | Line nil _ _ as l::v1 => split_aux v1 r\n  | Line (0%Z::l1) c t as l::v1 => \n      split_aux v1 (add4z (Line l1 c t) r)\n  | Line (Zpos p::l1) c1 lEq :: v1 => \n      split_aux v1 (add4e p l1 c1 r)\n  | Line (Zneg p::l1) c1 lEq :: v1 => \n      split_aux v1 (add4e p (oppsm l1) (-c1) r) \n  | Line (Zpos _::_) _ _  as l ::v1 => \n      split_aux v1 (add4p l r)\n  | Line (Zneg x::l1) c e as l ::v1 => \n      split_aux v1 (add4n (Line (Zpos x :: l1) c e) r)\n  end.\n\nDefinition split v := split_aux v nil_dt4.\n\n(*\nEval vm_compute in split ex1.\n*)\n\n(***********************************************************)\n(*  Adding the product of the positive and negative parts  *)\n(*  to the zero part removing the top variable             *)\n(***********************************************************)\n\nFixpoint mapsm (v: Z) (l: list Z) {struct l}: list Z :=\n  match l with nil => nil | v1 :: l1 => (v * v1) :: mapsm v l1 end.\n\nFixpoint merge (v1 v2: Z) (l1 l2: list Z) {struct l1}: list Z :=\n  match l1 with\n    nil => mapsm v2 l2\n  | v3:: l3 => match l2 with\n                 nil => mapsm v1 l1\n               | v4:: l4 => (v1*v3 + v2*v4) :: merge v1 v2 l3 l4\n               end\n  end.\n\nFixpoint app_one (v c: Z) (op: ltype) (l: list Z) (l1: dt) (r: dt) \n     {struct l1} :=\n  match l1 with\n    nil => r\n  | (Line nil _  _  as a)::l2 => app_one v c op l l2 (a :: r)\n  | (Line (v1::ll2) c1 op1)::l2 =>\n        let v2 := Z.gcd v v1 in\n        let k1 := v1/v2 in\n        let k2 := v/v2 in\n           app_one v c op l l2 \n              (Line (merge k1 k2 l ll2) (k1 * c + k2 * c1)\n                        (lmerge op op1) :: r)\n  end.\n\nFixpoint product (l1 l2: dt) (r: dt) {struct l1} : dt :=\n  match l1 with \n    nil => r\n  | (Line (v::l) c lLt)::l3 => product l3 l2 (app_one v c lLt l l2 r)\n  | (Line (v::l) c lLe)::l3 => product l3 l2 (app_one v c lLe l l2 r)\n  | _ ::l3 => product l3 l2 r\n  end.\n\n\n(***********************************************************)\n(*  Refuting by eliminating variables one by one           *)\n(***********************************************************)\n\n(* elim one variable *)\nDefinition elim_one v : dt :=\n  match split v with\n    DT4 No_eq x y z => product x y z\n  | DT4 (Some_eq p l c) x y z => \n     app_one (Zpos p) (-c) lEq (oppsm l) x\n       (app_one (Zpos p) c lEq l y z)\n  end.\n\n(* a system is unsolvable if there one constant negative element *)\nFixpoint unsolvable d :=\n  match d with \n    nil => false\n  | Line nil (Zneg _) lLe::_ => true\n  | Line nil (0%Z) lLt::_ => true\n  | Line nil (Zneg _) lLt::_ => true\n  | Line nil (Zpos _) lEq::_ => true\n  | Line nil (Zneg _) lEq::_ => true\n  | _::d1 => unsolvable d1\n  end.\n\n(* we use a clause to count how many variable to eliminate *)\nFixpoint refute_l (a: list Z) (v: dt) :=\n  match a with \n  | nil => unsolvable v \n  | _::b  => refute_l b (elim_one v)\n  end.\n\n(* extract the first clause *)\nDefinition first_clause (v: dt) :=\n  match v with nil => nil | Line a _ _::_ => a end.\n\nDefinition refute (v: dt) := refute_l (first_clause v) v.\n\n(*\nEval vm_compute in refute   (Line (1::nil) 0 lLe::\n                             Line (-1::nil) (-0) lLt ::nil).\n*)\n\n(*\nEval vm_compute in refute ex1.\n*)\n\n(*\n(* x >=0 and -x -1 <= 0 *)\nEval vm_compute in refute (Line (1::nil) 0 lLe::\n                           Line (-1::nil) (-1) lLe ::nil).\n*)\n\n(***********************************************************)\n(*                                                         *)\n(*                   Proving Part                          *)\n(*                                                         *)\n(***********************************************************)\n\nSection Proof.\n\nVariable FT : Fmodule.\nVariable FA : Faxiom FT.\n\nLet injT1 := (injT FT).\nCoercion injT1 : Z >-> T.\n\nOpen Scope F_scope.\n\n(* Change the top coefficient of the line *)\nDefinition swap_top l := match l with\n  |  Line nil _ _ => l\n  |  Line (p::l1) c eq  => Line ((-p)::l1) c eq\nend.\n\n(* Change the top coefficient of the line *)\nDefinition op_line l := match l with\n  |  Line l1 c t  => Line (oppsm l1) (-c) t\nend.\n\n(************************************************************)\n(*          Line interpretation                             *)\n(************************************************************)\n\nFixpoint list_to_T (l1: list Z) (l2: list (T _)) {struct l1} : T _ :=\n  match l1, l2 with\n    a::l3, x::l4 => a * x  + (list_to_T l3 l4)\n  | _, _ => 0\n  end.\n\nLemma list_to_T_nil: forall l1, list_to_T l1 nil = 0.\nProof.\nintros l1; destruct l1; simpl; auto.\nQed.\n\nDefinition line_to_T (l: line) (env: list (T _)) :=\n  match l with\n    Line ll c lEq => (0:T _) = (list_to_T ll env) + c\n  | Line ll c lLe => 0 <= (list_to_T ll env) + c\n  | Line ll c lLt => 0 < (list_to_T ll env) + c\n  end.\n\n(* Dealing with opposite *)\n\nLemma opp_opp: forall (a: Z), -(-a) = a.\nProof. intros a; case a; auto. Qed.\n\nLemma opp_oppsm: forall l, oppsm (oppsm l) = l.\nProof.\nintro l; induction l as [|a l Hrec]; simpl; auto.\nrewrite Hrec; rewrite opp_opp; auto.\nQed.\n\n\nLemma list_to_T_opp: forall l env,\n  list_to_T (oppsm l) env = (-1) * (list_to_T l env).\nProof.\nintros l; induction l as [|v l Hrec]; simpl.\nunfold injT1; rewrite scalT_inj0; auto.\nintros [|e env].\nunfold injT1; rewrite scalT_inj0; auto.\nrewrite Hrec; rewrite scalT_plus_r; auto.\nrewrite <-scalT_mul; auto.\nQed.\n\nLemma line_to_T_opp: forall l c env,\n  line_to_T (Line l c lEq) env ->\n  line_to_T (Line (oppsm l) (- c) lEq) env.\nProof.\nunfold line_to_T; intros l c env H1.\nrewrite list_to_T_opp.\nchange (Z.opp c) with (-1 * c)%Z.\nunfold injT1; rewrite injT_mul; auto.\nrewrite <- scalT_plus_r; auto.\nfold injT1; rewrite <- H1.\nunfold injT1; rewrite scalT_inj0; auto.\nQed.\n\n(* All the elements of the dt are verified *)\nDefinition Pdt d env := forall a, In a d -> line_to_T a env.\n\n(* All the element of the dt are verified with the flip of\n   the first element  *)\nDefinition Pdot d env := forall a, In a d -> line_to_T (swap_top a) env.\n\n(* Length of the variable part of a line *)\nDefinition llength l :=\n  match l with Line w _ _ => length w end.\n\n(************************************************************)\n(*          Split correctness                               *)\n(************************************************************)\n\n\n(* the split only shuffle things around but we restrict\n   ourself to prove inclusion *)\n\n(* Special inclusion to handle the fact that\n   we store only positive equation \n*)\nInductive InE: line -> dt -> Prop :=\n  InE_base: forall i b, In i b -> InE i b\n| InE_eq: forall l c b, \n     In (Line l c lEq) b -> InE (Line (oppsm l) (-c) lEq) b.\n\n(* Absolute value like lemma for InE *)\nLemma InE_opp: forall l c b,\n   InE (Line l c lEq) b -> InE (Line (oppsm l) (-c) lEq) b.\nProof.\nintros l c b HH; inversion_clear HH.\napply InE_eq; auto.\nrewrite opp_opp; rewrite opp_oppsm; auto.\napply InE_base; auto.\nQed.\n\nLemma InE_line_to_T: forall i d env,\n  InE i d -> Pdt d env -> line_to_T i env.\nProof.\nintros i d env HH; inversion_clear HH; auto.\nintros H1; apply line_to_T_opp; auto.\nQed.\n\nDefinition dincl (a b: dt) (f: line -> line) := \n  forall i, In i a -> InE (f i) b.\n(* identity filter *)\nDefinition id_elt (l: line) := l.\n(* removing filter *)\nDefinition rm_elt l :=\n  match l with Line l1 c eq => Line (0::l1) c eq end.\n\n(* Inclusion behave well with correctness *)\nLemma Pdt_incl_id: forall d1 d2 env,\n  dincl d1 d2 id_elt -> Pdt d2 env -> Pdt d1 env.\nProof.\nintros d1 d2 env Hinc Hd2 i Hi.\napply InE_line_to_T with (2 := Hd2); auto.\napply (Hinc i Hi).\nQed.\n\nLemma Pdt_incl_op: forall d1 d2 env,\n  dincl d1 d2 swap_top -> Pdt d2 env -> Pdot d1 env.\nProof.\nintros d1 d2 env Hinc Hd2 i Hi.\napply InE_line_to_T with (2 := Hd2); auto.\nQed.\n\nLemma line_to_T_tail: forall i env,\n  line_to_T (rm_elt i) env -> line_to_T i (tail env).\nProof.\nintros [l c t] [| e env]; simpl; \n  try (rewrite scalT_0; auto; rewrite injT_0_l; auto);\n  rewrite list_to_T_nil; auto.\nQed.\n\nLemma InE_tail_line_to_T: forall i d env,\n  InE (rm_elt i) d -> Pdt d env ->  line_to_T i (tail env).\nProof.\nintros i d env HI Hp; apply line_to_T_tail.\napply InE_line_to_T with (2 := Hp); auto.\nQed.\n\nLemma Pdt_incl_rm: forall d1 d2 env,\n  dincl d1 d2 rm_elt -> Pdt d2 env -> Pdt d1 (tail env).\nProof.\nintros d1 d2 env Hinc Hd2 i Hi.\napply InE_tail_line_to_T with (2 := Hd2); auto.\nQed.\n\nDefinition d4incl (a: dt4) (b: dt) := \n  match a with \n    DT4 No_eq d1 d2 d3 =>\n      (dincl d1 b id_elt) \n   /\\ (dincl d2 b swap_top) \n   /\\ (dincl d3 b rm_elt)\n  | DT4 (Some_eq p l c) d1 d2 d3 =>\n      InE (Line (Zpos p::l) c lEq) b \n   /\\ (dincl d1 b id_elt) \n   /\\ (dincl d2 b swap_top) \n   /\\ (dincl d3 b rm_elt)\n      \n  end. \n\n(* Horrible copy and paste proof, as we have to split  *)\n(* similar cases (lLt lLe) we get similar subproofs    *)\n(* This could be abstract away                         *)\nLemma split_aux_cor: forall v v1 (r: dt4),\n  dincl v v1 id_elt -> d4incl r v1 -> d4incl (split_aux v r) v1.\nProof.\nintro v; induction v as [| a v Hrec]; intros v1 r; simpl; auto.\ndestruct a as [x c t]; destruct x as [| x xs].\nintros H1 H2; apply Hrec; auto with datatypes.\nintros u Hu; apply H1; auto with datatypes.\ndestruct x as [|x|x]; intros H1 H2.\n apply Hrec; auto with datatypes;\n  try (intros u Hu; apply H1; auto with datatypes).\ndestruct r as [e w1 w2 w3]; destruct e; simpl.\ncase H2; clear H2; intros H2 (H3,(H4,H5));\n  repeat split; auto.\nintros i Hi; case Hi; auto; intros; subst.\nsimpl; apply (H1 (Line (0 :: xs) c t)); auto with datatypes.\ncase H2; clear H2; intros H2 (H3,H4);\n  repeat split; auto.\nintros i Hi; case Hi; auto; intros; subst.\nsimpl; apply (H1 (Line (0 :: xs) c t)); auto with datatypes.\ndestruct t; auto; apply Hrec;\n  try (intros u Hu; apply H1; auto with datatypes).\ndestruct r as [e w1 w2 w3]; destruct e; simpl.\ncase H2; clear H2; intros H2 (H3,(H4,H5)).\ncase Pos.compare_spec; repeat split; simpl; auto with datatypes.\nintros i Hi; case Hi; auto; intros; subst; simpl; auto with datatypes.\nrefine (H1 _ _); auto with datatypes.\nintros i Hi; case Hi; auto; intros; subst; simpl; auto with datatypes.\nintros i Hi; case Hi; auto; intros; subst; simpl; auto with datatypes.\ncase H2; clear H2; intros H2 (H3,H4); repeat split; auto.\nrefine (H1 _ _); auto with datatypes.\ndestruct r as [e w1 w2 w3]; destruct e; simpl.\ncase H2; clear H2; intros H2 (H3,(H4,H5)).\nrepeat split; auto.\nintros i Hi; case Hi; auto; intros; subst; simpl; auto with datatypes.\ncase H2; clear H2; intros H2 (H3,H4);\n  repeat split; auto.\nintros i Hi; case Hi; auto; intros; subst; simpl; auto with datatypes.\ndestruct r as [e w1 w2 w3]; destruct e; simpl.\ncase H2; clear H2; intros H2 (H3,(H4,H5)).\nrepeat split; auto.\nintros i Hi; case Hi; auto; intros; subst; simpl; auto with datatypes.\ncase H2; clear H2; intros H2 (H3,H4); repeat split; auto.\nintros i Hi; case Hi; auto; intros; subst; simpl; auto with datatypes.\ndestruct t; auto; apply Hrec;\n  try (intros u Hu; apply H1; auto with datatypes).\ndestruct r as [e w1 w2 w3]; destruct e; simpl.\ncase H2; clear H2; intros H2 (H3,(H4,H5)).\ncase Pos.compare_spec; repeat split; simpl; auto with datatypes.\nintros i Hi; case Hi; auto; intros; subst; simpl; auto with datatypes.\nchange (Zpos p :: oppsm xs) with (oppsm (Zneg p:: xs)); unfold id_elt.\napply InE_opp; refine (H1 _ _); auto with datatypes.\nchange (Zpos x :: oppsm xs) with (oppsm (Zneg x:: xs)); unfold id_elt.\napply InE_opp; refine (H1 _ _); auto with datatypes.\nintros i Hi; case Hi; auto; intros; subst; simpl; auto with datatypes.\nintros i Hi; case Hi; auto; intros; subst; simpl; auto with datatypes.\nchange (Zpos x :: oppsm xs) with (oppsm (Zneg x:: xs)); unfold id_elt.\napply InE_opp; refine (H1 _ _); auto with datatypes.\ncase H2; clear H2; intros H2 (H3,H4); repeat split; auto.\nchange (Zpos x :: oppsm xs) with (oppsm (Zneg x:: xs)); unfold id_elt.\napply InE_opp; refine (H1 _ _); auto with datatypes.\ndestruct r as [e w1 w2 w3]; destruct e; simpl.\ncase H2; clear H2; intros H2 (H3,(H4,H5)).\nrepeat split; auto.\nintros i Hi; case Hi; auto; intros; subst; simpl; auto with datatypes.\nrefine (H1 _ _); auto with datatypes.\ncase H2; clear H2; intros H2 (H3,H4); repeat split; auto.\nintros i Hi; case Hi; auto; intros; subst; simpl; auto with datatypes.\nrefine (H1 _ _); auto with datatypes.\ndestruct r as [e w1 w2 w3]; destruct e; simpl.\ncase H2; clear H2; intros H2 (H3,(H4,H5)).\nrepeat split; auto.\nintros i Hi; case Hi; auto; intros; subst; simpl; auto with datatypes.\nrefine (H1 _ _); auto with datatypes.\ncase H2; clear H2; intros H2 (H3,H4); repeat split; auto.\nintros i Hi; case Hi; auto; intros; subst; simpl; auto with datatypes.\nrefine (H1 _ _); auto with datatypes.\nQed.\n\nLemma split_cor: forall v, d4incl (split v) v.\nProof.\nintros v; unfold split; apply split_aux_cor.\nintros i Hi; apply InE_base; auto.\nrepeat split; intros i Hi; inversion Hi.\nQed.\n\nDefinition d4pos (a: dt4) := \n  match a with DT4 _ dp dn _ =>\n      (forall x l c t, In (Line (x::l) c t) dp -> (0 < x)%Z)\n   /\\ (forall x l c t, In (Line (x::l) c t) dn -> (0 < x)%Z)\n  end.\n\n(* Another copy and paste proof *)\nLemma split_aux_pos: forall v r, \n  d4pos r -> d4pos (split_aux v r).\nProof.\nintro v; induction v as [| a v Hrec];\n  intros (w1,w2,w3,w4) (H1,H2); repeat split; auto.\ndestruct a as [[|[|x|x] l] c t]; simpl.\n apply Hrec; repeat split; auto with datatypes.\n apply Hrec; repeat split; auto with datatypes.\ndestruct t; simpl; apply Hrec.\ndestruct w1.\ncase Pos.compare_spec.\nrepeat split; simpl; auto with datatypes.\nintros x1 l1 c1 t1 Hx1; case Hx1; auto; intros H3.\ninjection H3; intros; subst; red; simpl; auto.\napply H1 with (1 := H3).\nrepeat split; simpl; auto with datatypes.\nintros x1 l1 c1 t1 Hx1; case Hx1; auto; intros H3.\ninjection H3; intros; subst; red; simpl; auto.\napply H1 with (1 := H3).\nrepeat split; simpl; auto with datatypes.\nintros x1 l1 c1 t1 Hx1; case Hx1; auto; intros H3.\ninjection H3; intros; subst; red; simpl; auto.\napply H1 with (1 := H3).\nrepeat split; simpl; auto with datatypes.\nrepeat split; simpl; auto with datatypes.\nintros x1 l1 c1 t1 Hx1; case Hx1; auto; intros H3.\ninjection H3; intros; subst; red; simpl; auto.\napply H1 with (1 := H3).\nrepeat split; simpl; auto with datatypes.\nintros x1 l1 c1 t1 Hx1; case Hx1; auto; intros H3.\ninjection H3; intros; subst; red; simpl; auto.\napply H1 with (1 := H3).\ndestruct t; simpl; apply Hrec.\ndestruct w1.\ncase Pos.compare_spec.\nrepeat split; simpl; auto with datatypes.\nintros x1 l1 c1 t1 Hx1; case Hx1; auto; intros H3.\ninjection H3; intros; subst; red; simpl; auto.\napply H1 with (1 := H3).\nrepeat split; simpl; auto with datatypes.\nintros x1 l1 c1 t1 Hx1; case Hx1; auto; intros H3.\ninjection H3; intros; subst; red; simpl; auto.\napply H1 with (1 := H3).\nrepeat split; simpl; auto with datatypes.\nintros x1 l1 c1 t1 Hx1; case Hx1; auto; intros H3.\ninjection H3; intros; subst; red; simpl; auto.\napply H1 with (1 := H3).\nrepeat split; simpl; auto with datatypes.\nrepeat split; simpl; auto with datatypes.\nintros x1 l1 c1 t1 Hx1; case Hx1; auto; intros H3.\ninjection H3; intros; subst; red; simpl; auto.\napply H2 with (1 := H3).\nrepeat split; simpl; auto with datatypes.\nintros x1 l1 c1 t1 Hx1; case Hx1; auto; intros H3.\ninjection H3; intros; subst; red; simpl; auto.\napply H2 with (1 := H3).\nQed.\n\nLemma split_pos: forall v, d4pos (split v).\nProof.\nintros v; unfold split; apply split_aux_pos.\nrepeat split; intros i l c t Hi; inversion Hi.\nQed.\n\n(************************************************************)\n(*          Product correctness                             *)\n(************************************************************)\n\nLemma mapsm_cor: forall v l env,\n  list_to_T (mapsm v l) env = v * list_to_T l env.\nProof.\nintros v l; induction l as [| v1 l2 Hrec]; intros env; simpl; auto.\nunfold injT1; rewrite scalT_inj0; auto.\ndestruct env as [| y env].\nunfold injT1; rewrite scalT_inj0; auto.\nrewrite scalT_plus_r; auto; rewrite Hrec; rewrite scalT_mul; auto.\nQed.\n\nLemma merge_cor: forall v1 v2 l1 l2 env,\n  list_to_T (merge v1 v2 l1 l2) env = \n   v1 * list_to_T l1 env + v2 * list_to_T l2 env.\nProof.\nintros v1 v2 l1; induction l1 as [| w1 l1 Hrec]; intros l2 env; simpl; auto.\nrewrite mapsm_cor; unfold injT1; rewrite scalT_inj0; auto; rewrite injT_0_l; auto.\ndestruct l2 as [| w2 l2]; destruct env as [| x env]; simpl;\n  unfold injT1; repeat rewrite scalT_inj0; repeat rewrite injT_0_r; auto.\nrewrite mapsm_cor; rewrite scalT_plus_r; auto; rewrite scalT_mul; auto.\nrewrite Hrec.\nrepeat rewrite scalT_plus_r; repeat rewrite scalT_plus_l; auto.\nrewrite scalT_mul; repeat rewrite plusT_A; auto; \n  apply f_equal2 with (f := plusT FT); auto.\nrewrite plusT_C; repeat rewrite plusT_A; auto;\n  apply f_equal2 with (f := plusT FT); auto.\nrewrite plusT_C; repeat rewrite scalT_mul; auto.\nQed.\n\nLemma dt_dot_nil: forall l, Pdt l nil -> Pdot l nil.\nProof.\nintros l H i Hi; simpl.\ngeneralize (H _ Hi); destruct i as [[|x w] c]; auto.\nQed.\n \nLemma Zgcd_spos: forall x y, (0 < x -> 0 < y -> 0 < Z.gcd x y)%Z.\nProof.\nintros x y; case x; case y; auto with zarith.\nQed.\n\nLemma Zgcd_div_spos_l: forall x y, (0 < x -> 0 < y -> 0 < x/Z.gcd x y)%Z.\nProof.\nintros x y Hx Hy; destruct (Zgcd_is_gcd x y) as [[z Hz] _ _].\npattern x at 1; rewrite Hz; rewrite Z_div_mult.\ngeneralize Hx (Zgcd_spos _ _ Hx Hy); pattern x at 1; rewrite Hz.\ncase z; case Z.gcd; intros; auto with zarith; discriminate.\napply Z.lt_gt; apply Zgcd_spos; auto with zarith.\nQed.\n\nLemma Zgcd_div_spos_r: forall x y, (0 < x -> 0 < y -> 0 < y/ Z.gcd x y)%Z.\nProof.\nintros x y Hx Hy; destruct (Zgcd_is_gcd x y) as [_ [z Hz] _].\npattern y at 1; rewrite Hz; rewrite Z_div_mult.\ngeneralize Hy (Zgcd_spos _ _ Hx Hy); pattern y at 1; rewrite Hz.\ncase z; case Z.gcd; intros; auto with zarith; discriminate.\napply Z.lt_gt; apply Zgcd_spos; auto with zarith.\nQed.\n\nLemma app_one_cor: forall v c t l l1 r env,\n  (0 < v)%Z -> (forall x ll c t, In (Line (x::ll) c t) l1 -> (0 < x)%Z) ->\n  Pdt r (tail env) -> line_to_T (Line (v::l) c t) env ->\n  Pdot l1 env ->\n   Pdt (app_one v c t l l1 r) (tail env).\nProof.\nintros v c t l l1; induction l1 as [| (li,c1,t1) l1 Hrec]; intros r env;\n  destruct env as [| e env]; simpl; auto; destruct li as [|x li]; simpl; auto.\nintros Hv Hl1 H1 H2 H3; apply (fun x => Hrec x nil); simpl; auto.\nintros x ll cc tt Hx; apply (fun x => Hl1 x ll cc tt); auto.\nintros i; simpl; intros [Hi | Hi]; subst; auto.\napply (H3 (Line nil c1 t1)); auto with datatypes.\nintros i Hi; apply H3; auto with datatypes.\nintros Hv Hl1 H1 H2 H3.\nassert (Hxp: (0 < x)%Z).\n  apply (fun x => Hl1 x li c1 t1); auto.\nassert (Hzx:= Zgcd_div_spos_r _ _ Hv Hxp).\nassert (Hzv:= Zgcd_div_spos_l _ _ Hv Hxp).\napply (fun x => Hrec x nil); simpl; auto.\nintros x1 ll cc tt Hx; apply (fun x => Hl1 x ll cc tt); auto.\nintros i; simpl; intros [Hi | Hi]; subst; simpl; auto.\nrewrite merge_cor; repeat rewrite list_to_T_nil.\nunfold injT1; repeat rewrite scalT_inj0; repeat (rewrite injT_0_l in H2,H3 |- *);\n  repeat rewrite injT_0_l; auto.\nrewrite injT_plus; repeat rewrite injT_mul; auto.\ncut (line_to_T (swap_top (Line (x :: li) c1 t1)) nil); auto with datatypes.\ndestruct t; destruct t1; simpl; auto; unfold injT1 in H2 |- *; \n  rewrite injT_0_l in H2; auto; try rewrite <- H2; auto;\n  repeat rewrite scalT_inj0; repeat rewrite injT_0_l; auto; intros H4.\nrewrite <- H4; rewrite scalT_inj0; auto.\napply scalT_spos; auto.\napply scalT_pos; auto with zarith.\nrewrite <- H4; rewrite scalT_inj0; auto.\nrewrite injT_0_r; auto.\napply scalT_spos; auto.\napply plusTss_pos; auto; apply scalT_spos; auto.\napply plusTs1_pos; auto; try apply scalT_spos; auto;\n  apply scalT_pos; auto with zarith.\nrewrite <- H4; rewrite scalT_inj0; auto.\nrewrite injT_0_r; auto.\napply scalT_pos; auto with zarith.\napply plusT1s_pos; auto; try apply scalT_spos; auto;\n  apply scalT_pos; auto with zarith.\napply plusT_pos; auto; apply scalT_pos; auto with zarith.\nintros i Hi; auto with datatypes.\nintros Hv Hl1 H1 H2 H3.\napply (fun x => Hrec x (e::env)); simpl; auto.\nintros x ll cc tt Hcc; apply (Hl1 x ll cc tt); auto.\nintros i; simpl; intros [Hi | Hi]; subst; simpl; auto.\napply (H3 (Line nil c1 t1)); auto with datatypes.\nintros i Hi; apply (H3 i); auto with datatypes.\nintros Hv Hl1 H1 H2 H3.\nassert (Hxp: (0 < x)%Z).\n  apply (fun x => Hl1 x li c1 t1); auto.\nassert (Hzx:= Zgcd_div_spos_r _ _ Hv Hxp).\nassert (Hzv:= Zgcd_div_spos_l _ _ Hv Hxp).\napply (fun x => Hrec x (e::env)); simpl; auto.\nintros xx ll cc tt Hcc; apply (Hl1 xx ll cc tt); auto.\nintros i; simpl; intros [Hi|Hi]; subst; simpl; auto.\nrewrite merge_cor.\nmatch goal with |- context[?X + ?Y] =>\n  replace (X + Y) with \n    ((x / Z.gcd v x) * (v * e + list_to_T l env + c) +\n     (v / Z.gcd v x) * (- x * e + list_to_T li env + c1))\nend.\ncut (line_to_T (swap_top (Line (x :: li) c1 t1)) (e::env)); auto with datatypes.\ndestruct t; destruct t1; simpl; auto; unfold injT1 in H2 |- *; \n  auto; try rewrite <- H2; auto;\n  repeat rewrite scalT_inj0; repeat rewrite injT_0_l; auto; intros H4.\nrewrite <- H4; rewrite scalT_inj0; auto.\napply scalT_spos; auto.\napply scalT_pos; auto with zarith.\nrewrite <- H4; rewrite scalT_inj0; auto.\nrewrite injT_0_r; auto.\napply scalT_spos; auto.\napply plusTss_pos; auto; apply scalT_spos; auto.\napply plusTs1_pos; auto; try apply scalT_spos; auto;\n  apply scalT_pos; auto with zarith.\nrewrite <- H4; rewrite scalT_inj0; auto.\nrewrite injT_0_r; auto.\napply scalT_pos; auto with zarith.\napply plusT1s_pos; auto; try apply scalT_spos; auto;\n  apply scalT_pos; auto with zarith.\napply plusT_pos; auto; apply scalT_pos; auto with zarith.\nrepeat rewrite scalT_plus_r; auto.\nrepeat rewrite plusT_A; auto; rewrite plusT_C; repeat rewrite plusT_A; auto.\napply f_equal2 with (f := plusT FT); auto.\nrewrite plusT_C; repeat rewrite plusT_A; auto.\nrewrite plusT_C; repeat rewrite plusT_A; auto.\napply f_equal2 with (f := plusT FT); auto.\nrewrite plusT_C; repeat rewrite plusT_A; auto.\nrewrite plusT_C; repeat rewrite plusT_A; auto.\nunfold injT1; rewrite injT_plus; repeat rewrite injT_mul; auto.\napply f_equal2 with (f := plusT FT); auto.\nrewrite plusT_C; repeat rewrite plusT_A; auto.\nrewrite <- (injT_0_r); auto.\napply f_equal2 with (f := plusT FT); auto.\nrepeat rewrite <- scalT_mul; auto.\nreplace (x / Z.gcd v x * v)%Z with (v / Z.gcd v x * x)%Z.\nreplace (v / Z.gcd v x * - x)%Z with ((-1) * (v / Z.gcd v x * x))%Z; try ring.\nrewrite (scalT_mul _ FA (-1)%Z); rewrite plusT_0; auto.\nassert (Hdv: ((Z.gcd v x) | v)%Z).\nassert (Hz:= (Zgcd_is_gcd v x)); inversion Hz; auto.\ncase Hdv; intros q Hq; pattern v at 1 4; rewrite Hq.\nrewrite Z_div_mult.\nassert (Hdx: ((Z.gcd v x) | x)%Z).\nassert (Hz:= (Zgcd_is_gcd v x)); inversion Hz; auto.\ncase Hdx; intros q1 Hq1; pattern x at 1 2; rewrite Hq1.\nrewrite Z_div_mult; try ring.\napply Z.lt_gt; apply Zgcd_spos; auto.\napply Z.lt_gt; apply Zgcd_spos; auto.\nintros i Hi; apply (H3 i); auto with datatypes.\nQed.\n\n(* Special case for elimination of the positive part with an equation *)\nLemma app_one_cor_eq: forall v c l l1 r env,\n  (0 < v)%Z -> (forall x ll c t, In (Line (x::ll) c t) l1 -> (0 < x)%Z) ->\n  Pdt r (tail env) -> line_to_T (Line (-v::l) c lEq) env ->\n  Pdt l1 env ->\n   Pdt (app_one v c lEq l l1 r) (tail env).\nProof.\nintros v c l l1; induction l1 as [| (li,c1,t1) l1 Hrec]; intros r env;\n  destruct env as [| e env]; simpl; auto; destruct li as [|x li]; simpl; auto.\nintros Hv Hl1 H1 H2 H3; apply (fun x => Hrec x nil); simpl; auto.\nintros x ll cc tt Hx; apply (fun x => Hl1 x ll cc tt); auto.\nintros i; simpl; intros [Hi | Hi]; subst; auto.\napply (H3 (Line nil c1 t1)); auto with datatypes.\nintros i Hi; apply H3; auto with datatypes.\nintros Hv Hl1 H1 H2 H3.\nunfold injT1 in H2; rewrite injT_0_l in H2; auto.\nassert (Hxp: (0 < x)%Z).\n  apply (fun x => Hl1 x li c1 t1); auto.\nassert (Hzx:= Zgcd_div_spos_r _ _ Hv Hxp).\nassert (Hzv:= Zgcd_div_spos_l _ _ Hv Hxp).\napply (fun x => Hrec x nil); simpl; auto.\nintros x1 ll cc tt Hx; apply (fun x => Hl1 x ll cc tt); auto.\nintros i; simpl; intros [Hi | Hi]; subst; simpl; auto.\nrewrite merge_cor; repeat rewrite list_to_T_nil.\ncut (line_to_T (Line (x :: li) c1 t1) nil); auto with datatypes; simpl.\nunfold injT1; repeat rewrite scalT_inj0; repeat (rewrite injT_0_l in H2,H3 |- *);\n  auto.\nrepeat rewrite injT_0_l; auto.\nrewrite injT_plus; repeat rewrite injT_mul; auto.\ndestruct t1; simpl; intros H4;\n  try (rewrite <- H2); try (rewrite <-H4); \n  repeat rewrite scalT_inj0; auto;\n  try (rewrite injT_0_r); try (rewrite injT_0_l); auto.\napply scalT_spos; auto.\napply scalT_pos; auto with zarith.\nunfold injT1; rewrite <- H2; rewrite injT_0_r; auto.\nintros i Hi; auto with datatypes.\nintros Hv Hl1 H1 H2 H3.\napply (fun x => Hrec x (e::env)); simpl; auto.\nintros x ll cc tt Hcc; apply (Hl1 x ll cc tt); auto.\nintros i; simpl; intros [Hi | Hi]; subst; simpl; auto.\napply (H3 (Line nil c1 t1)); auto with datatypes.\nintros i Hi; apply (H3 i); auto with datatypes.\nintros Hv Hl1 H1 H2 H3.\napply (fun x => Hrec x (e::env)); simpl; auto.\nintros xx ll cc tt Hcc; apply (Hl1 xx ll cc tt); auto.\nintros i; simpl; intros [Hi|Hi]; subst; simpl; auto.\nrewrite merge_cor.\nassert (Hxp: (0 < x)%Z).\n  apply (fun x => Hl1 x li c1 t1); auto.\nassert (Hzx:= Zgcd_div_spos_r _ _ Hv Hxp).\nassert (Hzv:= Zgcd_div_spos_l _ _ Hv Hxp).\nmatch goal with |- context[?X + ?Y] =>\n  replace (X + Y) with \n    ((x / Z.gcd v x) * (-v * e + list_to_T l env + c) +\n     (v / Z.gcd v x) * (x * e + list_to_T li env + c1))\nend.\ncut (line_to_T (Line (x :: li) c1 t1) (e::env)); auto with datatypes.\ndestruct t1; simpl; auto; unfold injT1 in H2 |- *; \n  auto; try rewrite <- H2; auto;\n  repeat rewrite scalT_inj0; repeat rewrite injT_0_l; auto; intros H4.\nrewrite <- H4; rewrite scalT_inj0; auto.\napply scalT_spos; auto.\napply scalT_pos; auto with zarith.\nrepeat rewrite scalT_plus_r; auto.\nrepeat rewrite plusT_A; auto; rewrite plusT_C; repeat rewrite plusT_A; auto.\napply f_equal2 with (f := plusT FT); auto.\nrewrite plusT_C; repeat rewrite plusT_A; auto.\nrewrite plusT_C; repeat rewrite plusT_A; auto.\napply f_equal2 with (f := plusT FT); auto.\nrewrite plusT_C; repeat rewrite plusT_A; auto.\nrewrite plusT_C; repeat rewrite plusT_A; auto.\nunfold injT1; rewrite injT_plus; repeat rewrite injT_mul; auto.\napply f_equal2 with (f := plusT FT); auto.\nrewrite plusT_C; repeat rewrite plusT_A; auto.\nrewrite <- (injT_0_r); auto.\napply f_equal2 with (f := plusT FT); auto.\nrepeat rewrite <- scalT_mul; auto.\nrewrite plusT_C; auto.\nreplace (v / Z.gcd v x * x)%Z with (x / Z.gcd v x * v)%Z.\nreplace (x / Z.gcd v x * - v)%Z with ((-1) * (x / Z.gcd v x * v))%Z; try ring.\nrewrite (scalT_mul _ FA (-1)%Z); rewrite plusT_0; auto.\nassert (Hdv: ((Z.gcd v x) | x)%Z).\nassert (Hz:= (Zgcd_is_gcd v x)); inversion Hz; auto.\ncase Hdv; intros q Hq; pattern x at 1 4; rewrite Hq.\nrewrite Z_div_mult; auto.\nassert (Hdx: ((Z.gcd v x) | v)%Z).\nassert (Hz:= (Zgcd_is_gcd v x)); inversion Hz; auto.\ncase Hdx; intros q1 Hq1; pattern v at 1 2; rewrite Hq1.\nrewrite Z_div_mult; try ring.\napply Z.lt_gt; apply Zgcd_spos; auto.\napply Z.lt_gt; apply Zgcd_spos; auto.\nintros i Hi; apply (H3 i); auto with datatypes.\nQed.\n\nLemma product_cor: forall l1 l2 r env,\n  (forall x ll c t, In (Line (x::ll) c t) l1 -> (0 < x)%Z) ->\n  (forall x ll c t, In (Line (x::ll) c t) l2 -> (0 < x)%Z) ->\n  Pdt r (tail env) -> Pdt l1 env ->\n  Pdot l2 env -> Pdt (product l1 l2 r) (tail env).\nProof.\nintros l1; elim l1; simpl; auto; clear l1.\nintros ([|x w],c,t) l1 Hrec l2 r env Hp1 Hp2 H2 H3 H4; auto.\napply Hrec; auto with datatypes.\nintros x ll c1 t1 Hx.\napply (Hp1 x ll c1 t1); auto.\nintros i Hi; apply (H3 i); auto with datatypes.\ndestruct t.\napply Hrec; auto with datatypes.\nintros x1 ll c1 t1 Hx.\napply (Hp1 x1 ll c1 t1); auto with datatypes.\nintros i Hiu; apply H3; auto with datatypes.\napply Hrec; auto with datatypes.\nintros x1 ll c1 t1 Hx.\napply (Hp1 x1 ll c1 t1); auto.\napply app_one_cor; auto with datatypes.\napply (Hp1 x w c lLt); auto.\nintros i Hiu; apply H3; auto with datatypes.\napply Hrec; auto with datatypes.\nintros x1 ll c1 t1 Hx.\napply (Hp1 x1 ll c1 t1); auto.\napply app_one_cor; auto with datatypes.\napply (Hp1 x w c lLe); auto.\nintros i Hiu; apply H3; auto with datatypes.\nQed.\n\n(************************************************************)\n(*          Refute correctness                              *)\n(************************************************************)\n\nLemma elim_one_cor: forall v env,\n  Pdt v env -> Pdt (elim_one v) (tail env).\nProof.\nintros v env Hv; unfold elim_one.\ngeneralize (split_cor v) (split_pos v); \n  case split; intros [p l c|] w1 w2 w3.\nintros (Hd1, (Hd2, (Hd3, Hd4))) (Hp1, Hp2).\napply app_one_cor_eq; auto with zarith.\nred; auto.\napply app_one_cor; auto with zarith.\nred; auto.\napply Pdt_incl_rm with (1 := Hd4); auto.\napply InE_line_to_T with (2 := Hv); auto.\napply Pdt_incl_op with (1 := Hd3); auto.\napply (line_to_T_opp (Zpos p::l)).\napply InE_line_to_T with (2 := Hv); auto.\napply Pdt_incl_id with (1 := Hd2); auto.\nintros (Hd1, (Hd2, Hd3)) (Hp1, Hp2).\napply product_cor; auto.\napply Pdt_incl_rm with (1 := Hd3); auto.\napply Pdt_incl_id with (1 := Hd1); auto.\napply Pdt_incl_op with (1 := Hd2); auto.\nQed.\n\nLemma unsolvable_cor: forall d env,\n  unsolvable d = true -> ~ Pdt d env.\nProof.\nintros d env; induction d as [| [[| x w] c t] d Hrec]; simpl.\nintros HH; discriminate HH.\ndestruct c; simpl; auto.\ndestruct t; simpl.\nintros H H1; case (Hrec H).\nintros i Hi; auto with datatypes.\nintros _ H; case (ltT_neg _ FA (0%Z)); auto with zarith.\ngeneralize (H (Line nil (0%Z) lLt)); simpl; auto.\nunfold injT1; rewrite injT_0_r; auto with datatypes.\nintros H H1; case (Hrec H).\nintros i Hi; auto with datatypes.\ndestruct t; simpl.\nintros _ H; case (leT_neg _ FA (Zneg p)).\nred; simpl; auto.\nchange (Zneg p) with ((-1) * (Zpos p))%Z.\nrewrite injT_mul; auto.\ngeneralize (H (Line nil (Zpos p) lEq)); simpl.\nunfold injT1; rewrite injT_0_l; auto.\nintros HH; rewrite <-HH; auto; rewrite scalT_inj0; auto.\napply leT_refl; auto.\nintros H H1; case (Hrec H); intros i Hi; auto with datatypes.\nintros H H1; case (Hrec H); intros i Hi; auto with datatypes.\ndestruct t; simpl.\nintros _ H; case (leT_neg _ FA (Zneg p)).\nred; simpl; auto.\ngeneralize (H (Line nil (Zneg p) lEq)); simpl.\nunfold injT1; rewrite injT_0_l; auto.\nintros HH; rewrite <-HH; auto.\napply leT_refl; auto.\nintros _ H; case (ltT_neg _ FA (Zneg p)); try discriminate.\ngeneralize (H (Line nil (Zneg p) lLt)); simpl.\nunfold injT1; rewrite injT_0_l; auto.\nintros _ H; case (leT_neg _ FA (Zneg p)).\nred; simpl; auto.\ngeneralize (H (Line nil (Zneg p) lLe)); simpl.\nunfold injT1; rewrite injT_0_l; auto.\nintros H H1; case (Hrec H); intros i Hi; auto with datatypes.\nQed.\n\nLemma refute_l_cor: forall a v env,\n  length a = length env ->\n  refute_l a v = true -> ~ Pdt v env.\nintros a; induction a as [|x a Hrec].\nintros; apply unsolvable_cor; auto.\nintros v [|e env]; try (intros HH; discriminate).\nintros HH Hr Hd; apply (Hrec (elim_one v) env); auto.\ninjection HH; auto.\nintros HH1; apply (elim_one_cor v (e::env)); auto.\nQed.\n\nLemma refute_cor: forall v env,\n  length (first_clause v) = length env ->\n  refute v = true -> ~ Pdt v env.\nProof.\nintros v env Hl Hr; apply (refute_l_cor (first_clause v)); auto.\nQed.\n\nEnd Proof.", "meta": {"author": "thery", "repo": "Fourier", "sha": "6fa6a74940c5c8289f770910a6eea5f40cc0ab4c", "save_path": "github-repos/coq/thery-Fourier", "path": "github-repos/coq/thery-Fourier/Fourier-6fa6a74940c5c8289f770910a6eea5f40cc0ab4c/Fourier.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6505044805349721}}
{"text": "(**\n正規表現の言語を定義して、次の文献にある例を実行してみた。\n文献[1]：Tukuba Coq Users' Grup 「Coqによる定理証明」\n坂口さん著「反復定理で遊ぼう」\n\n実装にあたっては、\n文献[2]: https://www.ps.uni-saarland.de/~doczkal/regular/\nを参考にしているが、そのパッケージは使用しない。\n *)\n\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq fintype finset.\n\n(** 定義 1.1\n語は文字のseqで表す。\n *)\nVariable char : finType.                    (* アルファベットΣ *)\nVariables a b c : char.                     (* 文字 *)\nVariables w : seq char.                     (* 語 *)\n\n(** 定義 1.2\n正規表現\n *)\nInductive regexp :=\n | Void              : regexp\n | Eps               : regexp\n | Atom (a : char)   : regexp\n | Plus (e1 e2 : regexp) : regexp\n | Conc (e1 e2 : regexp) : regexp\n | Star (e : regexp) : regexp.\n\nCheck Void.\nCheck Eps.\n\n(* 例 1.3\n正規表現\n*)\nCheck (Conc (Conc (Star (Atom a))\n                  (Plus (Atom b) (Atom c)))\n            (Star (Star (Atom a)))).\n\n(** 定義 1.5\n正規表現の言語\n*)\n(**\n決定性言語を「与えられた語が、その言語に含まれるか」を示す述語として定義する。\n*)\nDefinition dlang := pred (seq char).        (* 決定性言語の集合 *)\nVariables L1 L2 : dlang.                    (* ひとつの言語 *)\n\n(**\n言語の演算\n *)\nDefinition void : dlang := pred0.           (* 語を含まない言語 *)\nDefinition eps : dlang := pred1 [::].       (* 空の語だけを含む言語 *)\nDefinition atom x : dlang := pred1 [:: x].  (* 一文字の語だけを含む言語 *)\nDefinition plus (L1 L2 : dlang) :=          (* 言語の和 *)\n  [pred w | L1 w || L2 w].\nDefinition conc (L1 L2: dlang) : dlang :=   (* 言語の積、語の畳込 *)\n  fun v => [exists i : 'I_(size v).+1, L1 (take i v) && L2 (drop i v)].\nDefinition residual (x : char) (L : dlang) := [pred w | L (x :: w)].\nDefinition star (L : dlang) : dlang :=      (* クリーネ閉包 *)\n  fix star v := if v is x :: v' then conc (residual x L) star v' else true.\n\n(* 以下は、正規表現の言語の定義には不要だが *)\nDefinition compl L : dlang := predC L.      (* 言語の補集合 *)\nDefinition prod (L1 L2 : dlang) :=          (* 言語の積、語の積 *)\n  [pred w in L1 | L2 w].\n\n(**\n正規表現の言語\n与えられた正規表現に対して、それに対応する語を含む言語\n（その語に対してtrueを返す論理式）を返す。\n *)\nFixpoint re_lang (e : regexp) : dlang :=\n  match e with\n  | Void => void\n  | Eps => eps\n  | Atom x => atom x\n  | Star e1 => star (re_lang e1)\n  | Plus e1 e2 => plus (re_lang e1) (re_lang e2)\n  | Conc e1 e2 => conc (re_lang e1) (re_lang e2)\n  end.\n\nLemma re_void__lang_none (w : seq char) :\n  ~~ (re_lang Void w).\nProof.\n  rewrite /re_lang /void.\n  by [].\nQed.\n\nLemma re_eps__lang_null : re_lang Eps [::].\nProof.\n  rewrite /re_lang /eps.\n  by [].\nQed.\n\nLemma re_atom__lang_atom (a : char) :\n  re_lang (Atom a) [:: a].\nProof.\n  rewrite /re_lang /atom /=.\n  by [].\nQed.\n\nLemma re_plus__lang_or (e1 e2 : regexp) (w : seq char) :\n    re_lang e1 w || re_lang e2 w ->\n    re_lang (Plus e1 e2) w.\nProof.\n  rewrite /re_lang /=.\n  case/orP => H.\n    by apply/orP; left.\n    by apply/orP; right.\nQed.\n\nLemma take_drop (L1 L2 : dlang) (w : seq char) (i : 'I_(size w).+1) :\n    L1 (take i w) -> L2 (drop i w) -> (conc L1 L2) w.\nProof.\n  move=> H1 H2.\n  rewrite /conc.\n  apply/existsP.\n  exists i.\n  by apply/andP; split.\nQed.  \n    \nLemma re_cons__lang_take_drop (e1 e2 : regexp) (w : seq char) (i : 'I_(size w).+1) :\n    re_lang e1 (take i w) ->\n    re_lang e2 (drop i w) ->\n    re_lang (Conc e1 e2) w.\nProof.\n  move=> L1 L2.\n  rewrite /re_lang /conc.\n  apply/existsP.\n  exists i.\n  apply/andP; split.\n  by apply L1.\n  by apply L2.\nQed.\n\n(**\n文献[2]で証明されている補題たち。一部を修正した。\n*)\nLemma plusP {L1 L2 : dlang} {w : seq char} :\n  reflect (L1 w \\/ L2 w) (plus L1 L2 w).\nProof.\n    by apply/orP.\nQed.\n\nLemma concP {L1 L2 : dlang} {w : seq char} :\n  reflect (exists w1 w2, w = w1 ++ w2 /\\ L1 w1  /\\ L2 w2) (conc L1 L2 w).\nProof.\n  apply: (iffP existsP) => [[n] /andP [H1 H2] | [w1] [w2] [e [H1 H2]]].\n  - exists (take n w). exists (drop n w).\n             by rewrite cat_take_drop.\n  - have lt_w1: size w1 < (size w).+1 by rewrite e size_cat ltnS leq_addr.\n    exists (Ordinal lt_w1); subst.\n    rewrite take_size_cat // drop_size_cat //. exact/andP.\nQed.\n\nLemma conc_cat {L1 L2 : dlang} {w1 w2 : seq char} :\n  L1 w1 -> L2 w2 -> conc L1 L2 (w1 ++ w2).\nProof.\n  move => H1 H2.\n  apply/concP.\n  by exists w1, w2.\nQed.\n\nLemma conc_eq (L1 L2 L3 L4: dlang) :\n  L1 =i L2 ->\n  L3 =i L4 ->\n  conc L1 L3 =i conc L2 L4.\nProof.\n  move=> H1 H2.\n  move=> w.\n  apply: eq_existsb => n.\n  (* by rewrite (_ : L1 =1 L2) // (_ : L3 =1 L4). *)\n  rewrite (H1 : L1 =1 L2).                  (* rewrite (_ : L1 =1 L2) *)\n  rewrite (H2 : L3 =1 L4).                  (* rewrite (_ : L3 =1 L4) *)\n    by [].\nQed.\n\nLemma starP {L : dlang} {v : seq char} :\n  reflect (exists2 vv, all [predD L & eps] vv & v = flatten vv) (star L v).\nProof.\n  elim: {v}_.+1 {-2}v (ltnSn (size v)) => // n IHn [|x v] /= le_v_n.\n  - by left; exists [::].\n  - apply: (iffP concP) => [[u] [v'] [def_v [Lxu starLv']] | [[|[|y u] vv] //=]].\n    case/IHn: starLv' => [|vv Lvv def_v'].\n    + by rewrite -ltnS (leq_trans _ le_v_n) // def_v size_cat !ltnS leq_addl.\n    + by exists ((x :: u) :: vv); [exact/andP | rewrite def_v def_v'].\n    + case/andP=> Lyu Lvv [def_x def_v]; exists u. exists (flatten vv).\n      subst. split => //; split => //. apply/IHn; last by exists vv.\n      by rewrite -ltnS (leq_trans _ le_v_n) // size_cat !ltnS leq_addl.\nQed.\n\nLemma star_eq (L1 L2 : dlang) :\n  L1 =i L2 -> star L1 =i star L2.\nProof.\n  move => H1 w.\n  apply/starP/starP; move => [] vv H3 H4; exists vv => //;\n  erewrite eq_all; try eexact H3; move => x /=; by rewrite ?H1 // -?H1.\nQed.\n\nLemma star_cat (w1 w2 : seq char) (L : dlang) :\n  L w1 -> star L w2 -> star L (w1 ++ w2).\nProof.\n  case: w1 => [|a w1] // H1 /starP [vv Ha Hf].\n  apply/starP.\n  exists ((a::w1) :: vv).\n  - rewrite /=.\n    apply/andP; split.\n    + by apply H1.\n    + by apply Ha.\n  - by rewrite Hf //= H1.\nQed.\n\n(**\nrep とその補題\n *)\nFixpoint rep (s : seq char) n : seq char :=\n  if n is n'.+1 then\n    s ++ rep s n'\n  else\n    [::].\n\nLemma rep_nil n : rep [::] n = [::].\nProof.\n  by elim: n => //=.\nQed.\n\nLemma star_rep (L1 : dlang) (w : seq char) (n : nat) :\n       L1 w -> (star L1) (rep w n).\nProof.\n  move=> H1.\n  elim: n.\n  - move=> /=.                              (* n = 0 *)\n    by [].\n  - move=> n IHn /=.                        (* n = n + 1 *)\n    apply star_cat.\n    + by [].\n    + by apply IHn.\nQed.\n\nLemma re_star__lang_star (e : regexp)  (w : seq char) (n : nat) :\n    re_lang e w ->\n    re_lang (Star e) (rep w n).\nProof.\n  elim: n.\n  - by [].\n  - move=> n /= IHn => H.\n    apply star_cat.\n    + by [].\n    + by apply IHn.\nQed.\n\n(** 例 1.6\n正規表現の言語\n*)\n\n(** 正規表現 a* b a* の言語は、{a^n b a^m : n,m ∈ Nat} である。 *)\nGoal forall (n m : nat),\n       re_lang\n         (Conc (Conc (Star (Atom a)) (Atom b)) (Star (Atom a)))\n         ((rep [:: a] n ++ [:: b]) ++ rep [:: a] m).\nProof.\n  move=> n m.\n  rewrite /conc.\n  apply conc_cat.\n  apply conc_cat.\n  - apply star_rep.\n    + by rewrite /atom /=.\n    + by rewrite /atom /=.\n  - apply star_rep.\n    + by rewrite /atom /=.\nQed.\n\n(** すごく遠回りして解いた例 *)\nLemma size_rep_one a n :\n  size (rep [:: a] n) = n.\nProof.\n  elim: n => /=.\n  - by [].\n  - move=> n IHn.\n    by rewrite IHn.\nQed.\n\nLemma size_cons (a :char)  l n :\n  size l = n -> size (a :: l) = n.+1.\nProof.\n  move=> H /=.\n  by rewrite H.\nQed.\n\nLemma size_rep a :\n  forall n m, size (rep [:: a] n ++ b :: rep [:: a] m) = n + m + 1.\nProof.\n  move=> n m.\n  rewrite size_cat.\n  Check (size_cons b (rep [::a] m)).\n  rewrite (size_cons b (rep [::a] m) m).\n  rewrite size_rep_one.\n  by nat_norm.\n  rewrite size_rep_one.\n  by [].\nQed.\n\nLemma take_take_1 (a : char) (n : nat) (ln lm : seq char) :\n  size ln = n ->\n  take (n + 1) ((ln ++ [:: a]) ++ lm) = ln ++ [:: a].\nProof.\n  move=> Hn.\n  have Hsize :  n + 1 <= size (ln ++ [:: a]).\n  - by rewrite size_cat Hn //=.\n  have Hsize2 : n + 1 = size (ln ++ [:: a]).\n  - by rewrite size_cat Hn //=.\n  Check @takel_cat (n + 1) char (ln ++ [:: a]) Hsize lm.\n  rewrite (@takel_cat (n + 1) char (ln ++ [:: a]) Hsize lm).\n  rewrite Hsize2.\n  Check @take_size char (ln ++ [:: a]).\n  rewrite (@take_size char (ln ++ [:: a])).\n  by [].\nQed.\n  \nLemma take_take' (a : char) (n : nat) (ln lm : seq char) :\n  size ln = n ->\n  take n (take (n + 1) ((ln ++ [:: a]) ++ lm)) = ln.\nProof.\n  move=> Hn.\n  rewrite (take_take_1 a n ln lm).\n  have Hsize : n <= size ln.\n  - by rewrite Hn.\n  Check @takel_cat n char ln Hsize [:: a].\n  rewrite (@takel_cat n char ln Hsize [:: a]).\n  rewrite -Hn.\n  Check @take_size char ln.\n  rewrite (@take_size char ln).\n  by [].\n  by apply Hn.\nQed.\n\nLemma subnnn n : n - n = 0.\nProof.\n  elim: n.\n  - by [].\n  - move=> n IHn.\n    by rewrite subSS.\nQed.\n\nLemma drop_take' (a : char) (n : nat) (ln lm : seq char) :\n  size ln = n ->\n  drop n (take (n + 1) ((ln ++ [:: a]) ++ lm)) = [:: a].\nProof.\n  move=> Hn.\n  rewrite (take_take_1 a n ln lm).\n  Check @drop_cat n char ln [:: a].\n  rewrite (@drop_cat n char ln [:: a]).\n  rewrite Hn.\n  case: (n < n).\n  - rewrite -Hn.\n    rewrite (drop_size ln).\n    by [].\n  - have Hzero : n - n = 0 by rewrite subnnn.\n    rewrite Hzero //=.\n    by [].\nQed.\n\nLemma take_take n m (a b : char) :\n  take n (take (n + 1) (rep [:: a] n ++ b :: rep [:: a] m)) = rep [:: a] n.\nProof.\n  Check take_take' b n (rep [:: a] n) (rep [:: a] m).\n  have H : take n (take (n + 1) ((rep [:: a] n ++ [:: b]) ++ rep [:: a] m)) = rep [:: a] n.\n  - rewrite (take_take' b n (rep [:: a] n) (rep [:: a] m)).\n    + by [].\n    + apply size_rep_one.\n  - Check catA.\n    rewrite -catA /= in H.\n      by apply H.\nQed.\n\nLemma drop_take n m (a b : char) :\n  (drop n (take (n + 1) (rep [:: a] n ++ b :: rep [:: a] m))) = [:: b].\nProof.\n  have H : drop n (take (n + 1) ((rep [:: a] n ++ [:: b]) ++ rep [:: a] m)) = [:: b].\n  - Check drop_take' b n (rep [:: a] n) (rep [:: a] m).\n    apply (drop_take' b n (rep [:: a] n) (rep [:: a] m)).\n    by apply size_rep_one.\n  - rewrite -catA /= in H.\n    by apply H.\nQed.\n\nLemma take_rep n :\n  forall (a : char) (l : seq char), take n (rep [:: a] n ++ l) = rep [:: a] n.\nProof.\n  move=> a l.\n  have Hsize : n <= size (rep [:: a] n) by rewrite size_rep_one.\n  Check @takel_cat n char (rep [:: a] n) Hsize l.\n  rewrite (@takel_cat n char (rep [:: a] n) Hsize l).\n\n  have Hsize2 : size (rep [:: a] n) = n by rewrite size_rep_one.\n  rewrite -{1}Hsize2.\n  Check @take_size char (rep [:: a] n).\n  rewrite (@take_size char (rep [:: a] n)).\n  by [].\nQed.\n\nLemma drop_rep n :\n  forall (a b : char) (l : seq char),\n    drop (n + 1) (rep [:: a] n ++ b :: l) = l.\nProof.\n  move=> a b l.\n  have Hsize2 : n + 1 = size (rep [:: a] n ++ [:: b]).\n  - by rewrite size_cat //= size_rep_one.\n  have H : drop (n + 1) ((rep [:: a] n ++ [:: b]) ++ l) = l.\n  - Check @drop_cat (n + 1) char ((rep [:: a] n) ++ [:: b]) l.\n    rewrite (@drop_cat (n + 1) char ((rep [:: a] n) ++ [:: b]) l).\n    rewrite -Hsize2.\n    case (n + 1 < n + 1).\n    + Check (drop_size (rep [:: a] n ++ [:: b])).\n      rewrite {1}Hsize2.\n      rewrite (drop_size (rep [:: a] n ++ [:: b])).\n      by [].\n    + have Hzero : (n + 1 - (n + 1)) = 0.\n      * nat_norm => //=.\n                      by rewrite subnnn.\n      rewrite Hzero.\n      by apply drop0.\n  - Search ((_ ++ _) ++ _).\n    Check @catA char.\n      by rewrite -catA //= in H.\nQed.\n\nGoal forall (n m : nat),\n       re_lang\n         (Conc (Conc (Star (Atom a)) (Atom b)) (Star (Atom a)))\n         (rep [:: a] n ++ [:: b] ++ rep [:: a] m).\nProof.\n  move=> n m.\n  rewrite /re_lang /conc /=.\n  apply/existsP => /=.\n  rewrite (size_rep a n m).\n  rewrite -addn1.\n  have lt_n__n_m_1 : n + 1 < n + m + 1 + 1.\n  - apply/ltP.\n    rewrite 2!addn1.\n    apply Lt.lt_n_S.\n    rewrite -addnA.\n    rewrite [m + 1]addnC.\n    rewrite addnA.\n    apply/ltP.\n    apply (@ltn_addr n (n + 1) m).\n    rewrite addn1.\n    apply ltnSn.\n    \n  exists (Ordinal lt_n__n_m_1).\n\n  apply/andP.\n  split.\n  - apply/existsP => /=.\n    Check size_takel.\n    rewrite size_takel.\n    rewrite -addn1.\n    have lt_n__n_1 : n < n + 1 + 1.\n      apply (@ltn_addr n (n + 1) 1).\n      rewrite addn1.\n      apply ltnSn.\n\n    exists (Ordinal lt_n__n_1).\n    apply/andP.\n    split.\n    + simpl.\n      rewrite take_take.\n      apply star_rep.\n      by rewrite /atom /=.\n    + simpl.\n      * rewrite drop_take.\n          by rewrite /atom /=.\n      * rewrite size_cat size_rep_one.\n          rewrite (size_cons b (rep [:: a] m) m).\n          - rewrite -[m.+1]addn1 [m + 1]addnC addnA.\n              by apply leq_addr.\n          - by rewrite size_rep_one.\n    + simpl.\n      rewrite drop_rep.\n      apply star_rep.\n      by rewrite /atom /=.\nQed.\n(** すごく遠回りして解いた例、終わり。 *)\n\n(** 正規表現 (aaa)* の言語は、{a^3n : n ∈ Nat} である。 *)\nGoal forall (n : nat), re_lang\n                         (Star (Conc (Conc (Atom a) (Atom a)) (Atom a)))\n                         (rep [:: a; a; a] n).\nProof.\n  move=> n.\n  rewrite /re_lang /conc /=.\n  apply star_rep.\n\n  Compute (take 1 (take 2 [:: a; a; a])).\n  Compute (drop 1 (take 2 [:: a; a; a])).\n  Compute (drop 2 [:: a; a; a]).\n\n  apply/existsP.                            (* exists 2 をする。 *)\n  have lt_2_size : 2 < (size [:: a; a; a]).+1 by [].\n  exists (Ordinal lt_2_size).\n\n  apply/andP; split.\n  - apply/existsP.                          (* exists 1 をする。 *)\n    have lt_1_size : 1 <  (size (take 2 [:: a; a; a])).+1 by [].\n    exists (Ordinal lt_1_size).\n    apply/andP.\n    split.\n    + simpl.\n        by rewrite /atom /=.                  (* atom a [:: a] *)\n    + simpl.\n        by rewrite /atom /=.                  (* atom a [:: a] *)\n  - simpl.\n        by rewrite /atom /=.                  (* atom a [:: a] *)\nQed.\n\n(** 正規表現 0* の言語は、{ε} である。  *)\nGoal re_lang (Star Eps) [::].\nProof.\n  rewrite /re_lang /eps.\n  by [].\nQed.\n\n(** 定理 1.10 （クリーネの定理）\n言語Lが正規言語なら、かつそのときに限り、言語がLであるような正規表現が存在する。\n\n文献[2]より：\nWe now call a general language regular if it is equivalent to the language of some\nregular expression.\nTheorem 3.1 The matching problem for regular expressions is decidable.\nProof This is an immediate consequence of defining the semantics of regular\nexpressions in terms of decidable languages.\n\n文献[2]ではこの証明は書かれていないで、次が定義されている。\n *)\nDefinition regular (L : dlang) :=\n  exists e : regexp, forall w, L w <-> re_lang e w.\n\n(** 例 *)\nGoal regular (re_lang Void).\nProof.\n  by exists Void.\nQed.\n\n(** 補足：言語が等しいということ。 *)\nGoal L1 = L2 -> L1 =i L2.\nProof.\n  move=> H.\n  (* Goal : L1 =i L2 *)\n  move=> w.\n  (* Goal : L1 w = L2 w *)\n  apply/(f_equal (fun L => w \\in L)).\n  (* Goal : L1 = L2 *)\n  by [].\nQed.\n\n(* w \\in L は、「rewrite /in_mem /mem /=」 で、L w になる。\n   実際は、直接 apply できる。\n*)\nGoal forall (L : dlang), (L w <-> w \\in L).\nProof.\n  rewrite /in_mem /mem /=.                  (* 不要 *)\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/regexp/ssr_simple_regexp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757313, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6505044749277374}}
{"text": "(*********************************************************************\n\n Zig-zags in categories\n\n A zig-zag in a category is a finite chain of morphisms like this\n\n x1 --> x2 <-- x3 --> x4 <-- x5\n\n In this file, we define the notion of zig-zags and a number of\n operations on them.\n\n Contents:\n 1. Definition of zig-zags\n 2. Constructors for zig-zags\n 3. Action of functors on zig-zags\n 4. Appending zig-zags\n 5. Reversing zig-zags\n 6. Zig-zags in groupoids give morphisms\n 7. Examples of zig-zag notation\n\n *********************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Groupoids.\n\nLocal Open Scope cat.\n\n(**\n 1. Definition of zig-zags\n *)\nDefinition zig_zag_of_length\n           {C : category}\n           (n : ℕ)\n  : ∏ (x y : C), UU.\nProof.\n  induction n as [ | n IHn ].\n  - exact (λ x y, z_iso x y).\n  - exact (λ x y, ∑ (z : C), ((x --> z) ⨿ (z --> x)) × IHn z y).\nDefined.\n\nDefinition zig_zag\n           {C : category}\n           (x y : C)\n  : UU\n  := ∑ (n : ℕ), zig_zag_of_length n x y.\n\nDefinition length_of_zig_zag\n           {C : category}\n           {x y : C}\n           (gs : zig_zag x y)\n  : ℕ\n  := pr1 gs.\n\n(**\n 2. Constructors for zig-zags\n *)\nDefinition empty_zig_zag\n           {C : category}\n           (x : C)\n  : zig_zag x x\n  := 0 ,, identity_z_iso x.\n\nNotation \"x ■\" := (empty_zig_zag x) (at level 40) : cat.\n\nDefinition left_cons_zig_zag\n           {C : category}\n           {x z y : C}\n           (f : x --> z)\n           (gs : zig_zag z y)\n  : zig_zag x y\n  := 1 + length_of_zig_zag gs ,, (z ,, (inl f ,, pr2 gs)).\n\nNotation \"x -[ f ]-> gs\" := (@left_cons_zig_zag _ x _ _ f gs)\n                              (at level 41, right associativity) : cat.\n\nDefinition right_cons_zig_zag\n           {C : category}\n           {x z y : C}\n           (f : z --> x)\n           (gs : zig_zag z y)\n  : zig_zag x y\n  := 1 + length_of_zig_zag gs ,, (z ,, (inr f ,, pr2 gs)).\n\nNotation \"x <-[ f ]- gs\" := (@right_cons_zig_zag _ x _ _ f gs)\n                              (at level 41, right associativity) : cat.\n\n(**\n 3. Action of functors on zig-zags\n *)\nDefinition functor_on_zig_zag_of_length\n           {C₁ C₂ : category}\n           (F : C₁ ⟶ C₂)\n           {x y : C₁}\n           {n : ℕ}\n           (gs : zig_zag_of_length n x y)\n  : zig_zag_of_length n (F x) (F y).\nProof.\n  revert x y gs.\n  induction n as [ | n IHn ].\n  - intros x y gs.\n    exact (functor_on_z_iso F gs).\n  - intros x y gs.\n    induction gs as [ z gs ].\n    induction gs as [ g gs ].\n    induction g as [ g | g ].\n    + exact (F z ,, inl (#F g) ,, IHn _ _ gs).\n    + exact (F z ,, inr (#F g) ,, IHn _ _ gs).\nDefined.\n\nDefinition functor_on_zig_zag\n           {C₁ C₂ : category}\n           (F : C₁ ⟶ C₂)\n           {x y : C₁}\n           (gs : zig_zag x y)\n  : zig_zag (F x) (F y)\n  := length_of_zig_zag gs ,, functor_on_zig_zag_of_length F (pr2 gs).\n\n(**\n 4. Appending zig-zags\n *)\nDefinition precomp_z_iso_zig_zag_of_length\n           {C : category}\n           {n : ℕ}\n           {x y z : C}\n           (fs : zig_zag_of_length n y z)\n           (i : z_iso x y)\n  : zig_zag_of_length n x z.\nProof.\n  revert x y z fs i.\n  induction n as [ | n IHn ].\n  - intros x y z fs i.\n    exact (z_iso_comp i fs).\n  - intros x y z fs i.\n    induction fs as [ w fs ].\n    induction fs as [ f fs ].\n    induction f as [ f | f ].\n    + exact (w ,, inl (i · f) ,, fs).\n    + exact (w ,, inr (f · inv_from_z_iso i) ,, fs).\nDefined.\n\nDefinition append_zig_zag_of_length\n           {C : category}\n           {n m : ℕ}\n           {x y z : C}\n           (fs : zig_zag_of_length n x y)\n           (gs : zig_zag_of_length m y z)\n  : zig_zag_of_length (n + m) x z.\nProof.\n  revert x y z fs gs.\n  induction n as [ | n IHn ].\n  - intros x y z fs gs.\n    exact (precomp_z_iso_zig_zag_of_length gs fs).\n  - intros x y z fs gs.\n    induction fs as [ w fs ].\n    induction fs as [ f fs ].\n    induction f as [ f | f ].\n    + exact (w ,, inl f ,, IHn w y z fs gs).\n    + exact (w ,, inr f ,, IHn w y z fs gs).\nDefined.\n\nDefinition append_zig_zag\n           {C : category}\n           {x y z : C}\n           (fs : zig_zag x y)\n           (gs : zig_zag y z)\n  : zig_zag x z\n  := length_of_zig_zag fs + length_of_zig_zag gs\n     ,,\n     append_zig_zag_of_length (pr2 fs) (pr2 gs).\n\n(**\n 5. Reversing zig-zags\n *)\nDefinition post_cons_left_zig_zag_of_length\n           {C : category}\n           {n : ℕ}\n           {x y z : C}\n           (gs : zig_zag_of_length n x y)\n           (f : y --> z)\n  : zig_zag_of_length (S n) x z.\nProof.\n  revert x y z gs f.\n  induction n as [ | n IHn ].\n  - intros x y z gs f.\n    exact (z ,, inl (pr1 gs · f) ,, identity_z_iso z).\n  - intros x y z gs f.\n    induction gs as [ w gs ].\n    induction gs as [ g gs ].\n    induction g as [ g | g ].\n    + exact (w ,, inl g ,, IHn _ _ _ gs f).\n    + exact (w ,, inr g ,, IHn _ _ _ gs f).\nDefined.\n\nDefinition post_cons_right_zig_zag_of_length\n           {C : category}\n           {n : ℕ}\n           {x y z : C}\n           (gs : zig_zag_of_length n x y)\n           (f : z --> y)\n  : zig_zag_of_length (S n) x z.\nProof.\n  revert x y z gs f.\n  induction n as [ | n IHn ].\n  - intros x y z gs f.\n    exact (z ,, inr (f · inv_from_z_iso gs) ,, identity_z_iso z).\n  - intros x y z gs f.\n    induction gs as [ w gs ].\n    induction gs as [ g gs ].\n    induction g as [ g | g ].\n    + exact (w ,, inl g ,, IHn _ _ _ gs f).\n    + exact (w ,, inr g ,, IHn _ _ _ gs f).\nDefined.\n\nDefinition reverse_zig_zag_of_length\n           {C : category}\n           {n : ℕ}\n           {x y : C}\n           (gs : zig_zag_of_length n x y)\n  : zig_zag_of_length n y x.\nProof.\n  revert x y gs.\n  induction n as [ | n IHn ].\n  - intros x y gs.\n    exact (z_iso_inv gs).\n  - intros x y gs.\n    induction gs as [ z gs ].\n    induction gs as [ g gs ].\n    induction g as [ g | g ].\n    + exact (post_cons_right_zig_zag_of_length (IHn _ _ gs) g).\n    + exact (post_cons_left_zig_zag_of_length (IHn _ _ gs) g).\nDefined.\n\nDefinition reverse_zig_zag\n           {C : category}\n           {x y : C}\n           (gs : zig_zag x y)\n  : zig_zag y x\n  := length_of_zig_zag gs ,, reverse_zig_zag_of_length (pr2 gs).\n\n(**\n 6. Zig-zags in groupoids give morphisms\n *)\nDefinition zig_zag_of_length_in_grpd_to_mor\n           {G : groupoid}\n           {n : ℕ}\n           {x y : G}\n           (gs : zig_zag_of_length n x y)\n  : x --> y.\nProof.\n  revert x y gs.\n  induction n as [ | n IHn ].\n  - intros x y gs.\n    exact (pr1 gs).\n  - intros x y gs.\n    induction gs as [ z gs ].\n    induction gs as [ g gs ].\n    induction g as [ g | g ].\n    + exact (g · IHn _ _ gs).\n    + exact (inv_from_z_iso (g ,, pr2 G _ _ _) · IHn _ _ gs).\nDefined.\n\nDefinition zig_zag_in_grpd_to_mor\n           {G : groupoid}\n           {x y : G}\n           (gs : zig_zag x y)\n  : x --> y\n  := zig_zag_of_length_in_grpd_to_mor (pr2 gs).\n\n(**\n 7. Examples of zig-zag notation\n *)\nLocal Example zig_zag_notation_1\n              {C : category}\n              {w x y z : C}\n              (f : w --> x)\n              (g : y --> x)\n              (h : y --> z)\n  : zig_zag w z\n  := w -[ f ]-> x <-[ g ]- y -[ h ]-> z ■.\n\nLocal Example zig_zag_notation_2\n              {C : category}\n              {w x y z : C}\n              (f : w --> x)\n              (g : x --> y)\n              (h : z --> y)\n  : zig_zag w z\n  := w -[ f ]-> x -[ g ]-> y <-[ h ]- z ■.\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/ZigZag.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6504889166212029}}
{"text": "Require Import Coq.Arith.PeanoNat.\nRequire Import Coq.ZArith.ZArith.\nRequire Import riscv.util.Tactics.\n\nLocal Open Scope nat_scope.\n\n\nLemma rewrite_div_mod: forall (a b: nat),\n    b <> 0 ->\n    exists q r, a mod b = r /\\ a / b = q /\\ a = b * q + r /\\ r < b.\nProof.\n  intros.\n  exists (a / b). exists (a mod b).\n  rewrite <- (Nat.div_mod a b) by assumption.\n  pose proof (Nat.mod_upper_bound a b).\n  auto.\nQed.\n\nLtac nat_div_mod_to_quot_rem_step :=\n  so fun hyporgoal => match hyporgoal with\n  | context [?a mod ?b] =>\n      let Ne := fresh \"Ne\" in\n      let P := fresh \"P\" in\n      assert (b <> 0) as Ne by omega;\n      pose proof (rewrite_div_mod a b Ne) as P;\n      clear Ne;\n      let q := fresh \"q\" in\n      let r := fresh \"r\" in\n      let Er := fresh \"Er\" in\n      let Eq := fresh \"Eq\" in\n      let E := fresh \"E\" in\n      let B := fresh \"B\" in\n      destruct P as [ q [ r [ Er [ Eq [ E B ] ] ] ] ];\n      rewrite? Er in *;\n      rewrite? Eq in *;\n      clear Er Eq\n  end.\n\nLtac nat_div_mod_to_quot_rem := repeat nat_div_mod_to_quot_rem_step.\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/nat_div_mod_to_quot_rem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6504889041509945}}
{"text": "(********************************)\n(********************************)\n(****                        ****)\n(****   Product categories   ****)\n(****                        ****)\n(********************************)\n(********************************)\n\nRequire Import Main.CategoryTheory.Category.\nRequire Import Main.CategoryTheory.Functor.\nRequire Import Main.Tactics.\n\n#[local] Set Universe Polymorphism.\n\n#[local] Open Scope type. (* Parse `*` as `prod` rather than `mul`. *)\n\n#[local] Theorem productCategoryCAssoc\n  {C D}\n  (w x y z : object C * object D)\n  (f : arrow (fst w) (fst x) * arrow (snd w) (snd x))\n  (g : arrow (fst x) (fst y) * arrow (snd x) (snd y))\n  (h : arrow (fst y) (fst z) * arrow (snd y) (snd z))\n: (\n    compose\n      (fst h)\n      (fst (compose (fst g) (fst f), compose (snd g) (snd f))),\n    compose\n      (snd h)\n      (snd (compose (fst g) (fst f), compose (snd g) (snd f)))\n  ) = (\n    compose\n      (fst (compose (fst h) (fst g), compose (snd h) (snd g)))\n      (fst f),\n    compose\n      (snd (compose (fst h) (fst g), compose (snd h) (snd g)))\n      (snd f)\n  ).\nProof.\n  search.\nQed.\n\n#[local] Theorem productCategoryCIdentLeft\n  {C D}\n  (x y : object C * object D)\n  (f : arrow (fst x) (fst y) * arrow (snd x) (snd y))\n: (\n    compose (fst (@id C (fst y), @id D (snd y))) (fst f),\n    compose (snd (@id C (fst y), @id D (snd y))) (snd f)\n  ) = f.\nProof.\n  search.\nQed.\n\n#[local] Theorem productCategoryCIdentRight\n  {C D : category}\n  (x y : object C * object D)\n  (f : arrow (fst x) (fst y) * arrow (snd x) (snd y))\n: (\n    compose (fst f) (fst (@id C (fst x), @id D (snd x))),\n    compose (snd f) (snd (@id C (fst x), @id D (snd x)))\n  ) = f.\nProof.\n  search.\nQed.\n\nDefinition productCategory C D : category := newCategory\n  (object C * object D)\n  (fun x y => arrow (fst x) (fst y) * arrow (snd x) (snd y))\n  (fun _ _ _ f g => (compose (fst f) (fst g), compose (snd f) (snd g)))\n  (fun _ => (id, id))\n  productCategoryCAssoc\n  productCategoryCIdentLeft\n  productCategoryCIdentRight.\n\n#[local] Theorem productCategoryProj1FIdent\n  {C D}\n  (x : object (productCategory C D))\n: fst (@id (productCategory C D) x) = id.\nProof.\n  search.\nQed.\n\n#[local] Theorem productCategoryProj1FComp\n  {C D}\n  (x y z : object (productCategory C D))\n  (f : arrow x y)\n  (g : arrow y z)\n: compose (fst g) (fst f) = fst (compose g f).\nProof.\n  search.\nQed.\n\nDefinition productCategoryProj1 C D :\n  functor (productCategory C D) C := newFunctor\n    (productCategory C D)\n    C\n    fst\n    (fun _ _ => fst) productCategoryProj1FIdent productCategoryProj1FComp.\n\n#[local] Theorem productCategoryProj2FIdent\n  {C D}\n  (x : object (productCategory C D))\n: snd (@id (productCategory C D) x) = id.\nProof.\n  search.\nQed.\n\n#[local] Theorem productCategoryProj2FComp\n  {C D}\n  (x y z : object (productCategory C D))\n  (f : arrow x y)\n  (g : arrow y z)\n: compose (snd g) (snd f) = snd (compose g f).\nProof.\n  search.\nQed.\n\nDefinition productCategoryProj2 C D :\n  functor (productCategory C D) D := newFunctor\n    (productCategory C D)\n    D\n    snd\n    (fun _ _ => snd) productCategoryProj2FIdent productCategoryProj2FComp.\n", "meta": {"author": "stepchowfun", "repo": "proofs", "sha": "00da33f63a56080227d06d37fd0f28b560f24624", "save_path": "github-repos/coq/stepchowfun-proofs", "path": "github-repos/coq/stepchowfun-proofs/proofs-00da33f63a56080227d06d37fd0f28b560f24624/proofs/CategoryTheory/ProductCategory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6504521304624686}}
{"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 Omega.\n\n(* Require Import tacs. *)\n\nRequire Import list_nat list_in list_forall list_prefix.\n\nSet Implicit Arguments.\n\nSection decide.\n\n  Variables X : Type.\n\n  Implicit Type (ll : list X).\n\n  Definition list_choose (P Q : X -> Prop) ll : (forall a, In a ll -> P a \\/ Q a)\n                                             -> (exists a, In a ll /\\ P a)\n                                             \\/ (forall a, In a ll -> Q a).\n  Proof.\n    induction ll as [ | x ll IH ]; intros HP. \n    right; intros ? [].\n    destruct IH as [ (z & H1 & H2) | IH ].\n    intros z Hz; apply HP; right; auto.\n    left; exists z; split; auto; right; auto.\n    destruct (HP x) as [ H3 | H3 ].\n    left; auto.\n    left; exists x; split; auto; left; auto.\n    right; intros q [ | Hq]; auto; intros; subst; auto.\n  Qed.\n\n  (* for an heterogeneous list [P x1 + Q x1;...;Pxn + Q xn], either find i s.t. P xi or\n     a proof that for any j, Q xj *)\n\n  Definition list_dep_choice_rect ll (P Q : forall x, In_t x ll -> Type) : \n       (forall x Hx, P x Hx + Q x Hx) \n    -> { x : _ & { Hx : In_t x ll & P x Hx } } \n     + (forall x Hx, Q x Hx).\n  Proof.\n    revert P Q.\n    induction ll as [ | x ll IH ]; intros P Q HP. \n    right; intros ? [].\n    specialize (IH (fun x Hx => P _ (inr Hx)) (fun x Hx => Q _ (inr Hx))).\n    destruct IH as [ (z & H1 & H2) | IH ].\n    intros z Hz; apply HP; right; auto.\n    left; exists z, (inr H1); auto.\n    destruct (HP _ (inl eq_refl)) as [ H3 | H3 ].\n    left; exists x, (inl eq_refl); auto. \n    right; intros q [ | Hq]; auto; intros; subst; auto.\n  Qed.\n  \n  Definition list_dep_choice_ind ll (P Q : forall x : X, In_t x ll -> Prop) : \n    (forall x Hx, P x Hx \\/ Q x Hx) -> (exists x Hx, P x Hx) \\/ forall x Hx, Q x Hx.\n  Proof.\n    revert P Q.\n    induction ll as [ | x ll IH ]; intros P Q HPQ. \n    right; intros ? [].\n    destruct (IH (fun x Hx => P _ (inr Hx)) (fun x Hx => Q _ (inr _ Hx))) as [ (z & H1 & H2) | IH' ].\n    intros z Hz; apply HPQ; right; auto.\n    left; exists z, (inr H1); auto.\n    destruct (HPQ x (inl eq_refl)) as [ H3 | H3 ].\n    left; exists x, (inl eq_refl); auto.\n    right; intros q [ Hq | Hq]; subst; auto.\n  Qed.\n\n  Definition list_choose_rect (P Q : X -> Type) ll : \n       (forall x, In_t x ll -> P x + Q x) \n    -> { z : _ & (In_t z ll * P z)%type } \n     + (forall z, In_t z ll -> Q z).\n  Proof.\n    intros H.\n    destruct (list_dep_choice_rect ll (fun x _ => P x) (fun x _ => Q x) H) as [ (x & H1 & H2) | H1 ].\n    left; exists x; auto.\n    right; auto.\n  Qed.\n  \n  Definition list_choose_ind (P Q : X -> Prop) ll : \n       (forall x, In x ll -> P x \\/ Q x) \n    -> (exists z, In z ll /\\ P z) \\/ forall z, In z ll -> Q z.\n  Proof.\n    intros H.\n    rewrite <- In_In_t in H.\n    destruct (list_dep_choice_ind ll (fun x _ => P x) (fun x _ => Q x) H) as [ (x & H1 & H2) | H1 ].\n    left; exists x; split; auto; apply In_t_In; auto.\n    right; apply In_In_t; auto.\n  Qed.\n\n  Definition list_choose_rec (P Q : X -> Prop) ll : \n    (forall x, In x ll -> {P x} + {Q x}) -> { z | In z ll /\\ P z } + { forall z, In z ll -> Q z }.\n  Proof.\n    intros H.\n    destruct (list_choose_rect P Q ll) as [ (z & H1 & H2) | H1 ].\n    intros x Hx; destruct (H x); try tauto; apply In_t_In; auto.\n    left; exists z; split; auto; apply In_t_In; auto. \n    right; apply In_In_t; auto. \n  Qed.\n\n  Variable P : X -> Prop.\n\n  Definition list_dec_rec ll : \n    (forall x, In x ll -> {P x} + {~ P x}) -> { z | In z ll /\\ P z } + { forall z, In z ll -> ~ P z }.\n  Proof.\n    apply list_choose_rec.\n  Qed.\n  \n  Corollary list_reif_dec ll : \n    (forall x, In x ll -> {P x} + {~ P x}) -> (exists x, P x /\\ In x ll) -> { x | P x /\\ In x ll }.\n  Proof.\n    intros Pdec H. \n    destruct list_dec_rec with (ll := ll) as [ (x & ? & ?) | H0 ]; auto.\n    exists x; auto.\n    contradict H.\n    intros (x & ? & ?); apply (H0 x); auto.\n  Qed.\n\n  Definition list_dec_ind ll : \n    (forall x, In x ll -> P x \\/ ~ P x) -> (exists z, In z ll /\\ P z ) \\/ forall z, In z ll -> ~ P z.\n  Proof.\n    apply list_choose_ind.\n  Qed.\n\nEnd decide.\n\nSection list_eq_dec.\n\n  Variable (X : Type).\n  \n  Fact list_eq_dect ll mm :  (forall x y : X, In_t x ll -> In_t y mm -> { x = y } + { x <> y })\n                         -> { ll = mm } + { ll <> mm }.\n  Proof.\n    revert mm; induction ll as [ | x ll ]; intros [ | y mm ] H.\n    left; auto.\n    right; discriminate.\n    right; discriminate.\n    destruct (H x y) as [ H1 | H1 ]; try (left; auto; fail).\n    subst y.\n    destruct (IHll mm) as [ H2 | H2 ].\n    intros; apply H; right; auto.\n    subst mm; left; auto.\n    right; contradict H2; injection H2; auto.\n    right; contradict H1; injection H1; auto.\n  Qed.\n  \n  Fact list_eq_dec ll mm :  (forall x y : X, In x ll -> In y mm -> { x = y } + { x <> y })\n                         -> { ll = mm } + { ll <> mm }.\n  Proof.\n    intros H; apply list_eq_dect.\n    intros; apply H; apply In_t_In; auto.\n  Qed.\n\nEnd list_eq_dec.\n\nSection finite_decision.\n\n  Variables (X : Type) (P : X -> Prop).\n\n  (* Given x in ll s.t. P x, finds the first among them, i.e. y in ll s.t. P y \n     and ~ P z for any z before y *)\n\n  Fact In_first ll : (forall x, In x ll -> P x \\/ ~ P x) \n                   -> forall x, In x ll -> P x -> exists l y r, ll = l++y::r\n                                                    /\\ P y \n                                                    /\\ forall z, In z l -> ~ P z.\n  Proof.\n    induction ll as [ | y ll IH ]; simpl; intros Hll x H1 H2; destruct H1.\n    subst; exists nil, x, ll; repeat split; auto.\n    destruct (Hll y) as [ Hy | Hy ]; auto.\n    exists nil, y, ll; repeat split; auto.\n    destruct IH with (3 := H2) as (l & z & r & H3 & H4 & H5); auto.\n    subst; exists (y::l), z, r; repeat split; auto.\n    intros k [ ? | ? ].\n    subst k; auto.\n    apply H5; auto.\n  Qed.\n\n  Variable Q : list X -> list X -> Prop.\n\n  (* if Q is decidable over the splits l++r of ll and Q nil ll holds then\n     there is prefix l s.t Q l' r' holds whenever l' <= l\n     and Q l' r' does not hold for the successor prefix of l' \n     (if it exists).\n\n  *)\n\n  Definition largest_list_prefix ll : (forall l r, ll = l++r -> { Q l r } + { ~ Q l r })\n                                   -> Q nil ll\n                                   -> { l : _ & { r | ll = l++r \n                                                   /\\ Q l r \n                                                   /\\ (forall l' r', ll = l'++r' -> length l' = S (length l) -> ~ Q l' r')\n                                                   /\\ (forall l' r', ll = l'++r' -> length l' <= length l    ->   Q l' r') } }.\n  Proof.\n    intros HQ H0.\n    set (K n := forall l r, ll = l++r -> length l = n -> Q l r).\n    destruct (@largest_nat_prefix (length ll) K) as (i & H1 & H2 & H3 & H3').\n    intros i Hi; unfold K.    \n    destruct (list_prefix _ Hi) as (l & r & H1 & H2).\n    destruct (HQ _ _ H1) as [ H5 | H5 ].\n    left.\n    intros l' r' H3 H4; subst.\n    destruct list_prefix_eq with (1 := H3); try omega; subst; auto.\n    right; contradict H5; apply H5; auto.\n    red.\n    intros l r H1 H2 .\n    destruct (list_prefix_eq l r nil ll); auto.\n    subst l r; auto.\n    destruct (list_prefix _ H1) as (l & r & H4 & H5).\n    exists l, r.\n    repeat split; auto.\n    \n    intros l' r' H6 H7.\n    intros H8.\n    assert (K (S i)) as C.\n      red.\n      intros l'' r'' H9 H10.\n      rewrite <- H5, <- H7 in H10.\n      rewrite H6 in H9.\n      destruct list_prefix_eq with (1 := H9); auto.\n      subst l'' r''; auto.\n    apply H3 in C.\n    apply f_equal with (f := @length X) in H6.\n    rewrite app_length in H6.\n    omega.\n    \n    intros l' r' H6 H7.\n    rewrite H5 in H7.\n    apply H3' in H7.\n    apply H7; auto.\n  Defined.\n\n  Variables (R : list X -> X -> list X -> Prop).\n\n  Definition list_find_split ll : (forall l x r, ll = l++x::r -> { R l x r } + { ~ R l x r })\n                               -> { l : _ & { x : _ & { r | ll = l++x::r /\\ R l x r } } } \n                                + { forall l x r, ll = l++x::r -> ~ R l x r }.\n  Proof.\n    revert R.\n    induction ll as [ | x ll IH ]; intros R HR.\n    right; intros [ | ] ? ?; discriminate 1.\n    destruct (HR nil x ll) as [ H0 | H0 ]; auto.\n    left; exists nil, x, ll; auto.\n    destruct (IH (fun l y r => R (x::l) y r)) as [ (l & y & r & H1 & H2) | H1 ].\n    intros; apply HR; simpl; f_equal; auto.\n    left; exists (x::l), y, r; split; simpl; auto; f_equal; auto.\n    right.\n    intros l y r H2.\n    destruct l as [ | k l ];\n    injection H2; intros; subst; auto.\n  Defined.\n\nEnd finite_decision.\n\nFact Forall_dec X (P : X -> Prop) ll : \n       (forall x, In x ll -> { P x } + { ~ P x })\n   -> { Forall P ll } + { ~ Forall P ll }.\nProof.\n  intros H.\n  destruct (list_choose_rec (fun x => ~ P x) P ll) as [ (x & H1 & H2) | H1 ].\n  intros x Hx; specialize (H _ Hx); tauto.\n  right; contradict H2; rewrite Forall_forall in H2; apply H2; auto.\n  rewrite <- Forall_forall in H1; tauto.\nQed.  \n\nFact finite_fall_disj U (P : U -> Prop) (Q : Prop) l : (forall u, In u l -> P u) \\/ Q <-> forall u, In u l -> P u \\/ Q.\nProof.\n  split.\n  intros [ H | H ] u Hu.\n  left; auto.\n  right; auto.\n  intros H.\n  destruct (list_choose (fun _ => Q) P l) as [ (u & H1 & H2) | H1 ].\n  intros a; specialize (H a); tauto.\n  right; auto.\n  left; auto.\nQed.\n\nSection combi_principle.\n\n  Let seq (l : list Type) := forall X, In_t X l -> X.\n\n  Let empseq : seq nil.\n  Proof. intros ? []. Defined.\n\n  Let consseq X (l : list Type) (a : X) : seq l -> seq (X::l).\n  Proof.\n    intros H Y [ HY | HY ].\n    subst; apply a.\n    apply (H _ HY).\n  Defined.\n\n(*\n  Let hd X l : seq (X::l) -> X.\n  Proof. intros H; apply (H _ (inl eq_refl)). Defined.\n  \n  Definition tl X l : seq (X::l) -> seq l.\n  Proof. intros H Y HY; apply (H _ (inr HY)). Defined.\n*)\n\n  (* the combinatorial principle of page 241 \n     in a purely intuitionistic way \n\n     Beware than universal quantification should be finite here otherwise\n     we cannot replace (forall u, P u \\/ Q) with (forall u, Pu) \\/ Q\n\n  *)\n\n  Fact combi_principle (l : list Type) (A : forall X, In_t X l -> list X) \n                                       (P : seq l -> Prop)\n                                       (B : forall X, In_t X l -> X -> Prop) :\n        (forall a : seq l, (forall X HX, In (a X HX) (A X HX)) -> P a \\/ exists X HX, B X HX (a X HX))\n     -> (exists a, P a /\\ forall X HX, In (a X HX) (A X HX)) \\/ exists X HX, forall x, In x (A X HX) -> B X HX x.\n  Proof.\n    revert A P B; induction l as [ | X l IH ]; intros A P B H.\n\n    destruct (H empseq) as [ H1 | (? & [] & _) ].\n    intros ? [].\n    left; exists empseq; split; auto.\n    intros ? [].\n\n    set (P' s := forall a, In a (A _ (inl eq_refl)) -> P (consseq a s)\\/ B _ (inl eq_refl) a).\n    set (A' X HX := A X (inr HX)).\n    set (B' X HX := B X (inr HX)).\n\n    destruct (IH A' P' B') as [ (a & Ha & Ha') | (Y & HY1 & HY2) ].\n\n    intros s Hs.\n    unfold P'.\n    apply finite_fall_disj.\n    intros a Ha.\n    destruct (H (consseq a s)) as [ H1 | (Y & HY & H1) ].\n    intros Y [ HY | HY ]; subst; auto; apply Hs.\n    left; left; auto.\n    destruct HY as [ HY | HY ].\n    subst Y.\n    left; right; apply H1.\n    right.\n    exists Y, HY; apply H1.\n    \n    red in Ha.\n    apply list_choose in Ha.\n    destruct Ha as [ (Y & H1 & H2) | H1 ].\n    left; exists (consseq Y a); split; auto.\n    intros ? [ ? | ? ]; subst; auto; apply Ha'.\n    right; exists X, (inl eq_refl); auto.\n    \n    unfold A', B' in HY2.\n    right; exists Y, (inr HY1); auto.\n  Qed. \n\nEnd combi_principle.\n\nSection list_fan_combi_principle.\n\n  Variable X : Type.\n\n  Fact list_fan_combi_principle ll P :\n               (forall p, Forall2 (@In X) p (map (@fst _ _) ll) \n                       -> P p \\/ Exists2 (fun x B => B x) p (map (@snd _ _) ll))\n            -> (exists p, Forall2 (@In _) p (map (@fst _ _) ll) /\\ P p)\n            \\/ (exists A B, In (A,B) ll/\\ forall x, In x A -> B x).\n  Proof.\n    revert P.\n    induction ll as [ | (A,B) ll IH ]; intros P Hll.\n    \n    destruct (Hll nil) as [ H0 | H0 ]; simpl; auto.\n    left; exists nil; simpl; auto.\n    apply Exists2_nil_inv in H0; destruct H0.\n    \n    set (P' l := forall a, In a A -> P (a::l) \\/ B a).\n    destruct (IH P') as [ (p & H1 & H2) | (A1 & B1 & H1 & H2) ].\n    \n    intros l Hl.\n    unfold P'.\n    apply finite_fall_disj.\n    intros a Ha.\n    destruct (Hll (a::l)) as [ H1 | H1 ]. \n    simpl; constructor; auto.\n    tauto.\n    simpl in H1.\n    apply Exists2_cons_inv in H1; tauto.\n    \n    apply list_choose in H2.\n    destruct H2 as [ (a & H2 & H3) | H2 ].\n    left; exists (a::p); simpl; split; auto.\n    right; exists A, B; simpl; split; auto.\n    \n    right; exists A1, B1; simpl; split; auto.\n  Qed.\n    \nEnd list_fan_combi_principle.    \n\nSection hig_combi_principle.\n\n  Variable X : Type.\n  Variable ll : list (list X).\n  Variable P : list X -> Prop.\n  Variable B : X -> Prop.\n\n  Fact hig_combi_principle :\n               (forall p, Forall2 (@In X) p ll -> P p \\/ exists x, In x p /\\ B x)\n            -> (exists p, Forall2 (@In _) p ll /\\ P p)\n            \\/ (exists A, In A ll/\\ forall x, In x A -> B x).\n  Proof.\n    intros H.\n    set (ll' := map (fun x => (x,B)) ll).\n    destruct (list_fan_combi_principle ll' P) as [ (p & H1 & H2) | (A & B' & H1 & H2) ].\n    \n    intros p Hp.\n    unfold ll' in Hp.\n    rewrite map_map, map_id in Hp.\n    destruct (H p) as [ H1 | (x & H1 & H2) ]; auto.\n    right.\n    unfold ll'; rewrite map_map; simpl.\n\n    clear H ll'.\n    induction Hp.\n    destruct H1.\n    destruct H1 as [ H1 | H1 ].\n    subst; simpl.\n    constructor 1; auto.\n    rewrite map_length.\n    revert Hp; apply Forall2_length.\n    constructor 2; auto.\n    \n    left; exists p; split; auto.\n    unfold ll' in H1; rewrite map_map, map_id in H1; auto.\n    \n    unfold ll' in H1.\n    rewrite in_map_iff in H1.\n    destruct H1 as (A' & H1 & H3).\n    injection H1; intros; subst A' B'.\n    right; exists A; auto.\n  Qed.\n\nEnd hig_combi_principle.                                                       \n\nSection list_decide_special.\n\n  Section one.\n\n    Variable (X Y : Type) (Q R S : X -> Y -> Prop).\n    \n    Hypothesis HQ : forall x y, Q x y -> R x y \\/ S x y.\n    \n    Fact one_list_decide ll : (forall x, In x ll -> exists y, Q x y)\n                           -> (forall x, In x ll -> exists y, R x y)\n                           \\/ (exists x y, In x ll /\\ S x y).\n    Proof.\n      intros H.\n      destruct (list_choose_ind (fun x => exists y, S x y) (fun x => exists y, R x y) ll) as [ (x & H1 & y & H2) | H1 ].\n      intros x Hx; destruct (H _ Hx) as (y & Hy).\n      apply HQ in Hy.\n      destruct Hy; [ right | left ]; exists y; auto.\n      right; exists x, y; split; auto; apply In_t_In; auto.\n      left; auto.\n    Qed.\n\n  End one.\n\n  Section two_prop.\n  \n    Variable (X Y : Type) (P S : X -> Y -> Prop) (Q : X -> Prop) (R : Y -> Prop).\n    \n    Hypothesis HQ : forall x y, P x y -> Q x \\/ R y \\/ S x y.\n\n    Variables (ll : list X) (mm : list Y).\n\n    Let A : forall T, In_t T (X::Y::nil) -> list T.\n    Proof.\n      intros T [ ? | [ ? | [] ] ]; subst T.\n      exact ll.\n      exact mm.\n    Defined.\n\n    Let PA : (forall T, In_t T (X::Y::nil) -> T) -> Prop.\n    Proof.\n      intros H.\n      apply S; apply H.\n      left; auto.\n      right; left; auto.\n    Defined.\n\n    Let PB : forall T, In_t T (X::Y::nil) -> T -> Prop.\n    Proof.\n      intros T [ ? | [ ? | [] ] ]; subst T.\n      apply Q.\n      apply R.\n    Defined.\n    \n    Fact two_list_decide_prop       : (forall x y, In x ll -> In y mm -> P x y)\n                                   -> (forall x, In x ll -> Q x)\n                                   \\/ (forall y, In y mm -> R y)\n                                   \\/ (exists x y, In x ll /\\ In y mm /\\ S x y).\n    Proof.\n      intros HP.\n      destruct (@combi_principle (X::Y::nil) A PA PB) as [ (a & H1 & H2) | (X0 & HX0 & H1) ] .\n      \n      intros f Hf.\n      generalize (Hf _ (inl eq_refl)) (Hf _ (inr (inl eq_refl))).\n      simpl; unfold eq_rect_r; simpl.\n      clear Hf; intros HX HY.\n      destruct (HQ (HP _ _ HX HY)) as [ H | [ H | H ] ].\n      right; exists X, (inl eq_refl); cbv; auto.\n      right; exists Y, (inr (inl eq_refl)); cbv; auto.\n      left; cbv; auto.\n      \n      cbv in H1.\n      right; right.\n      exists (a X (inl eq_refl)), (a Y (inr (inl eq_refl))); repeat split; auto; apply H2.\n      \n      destruct HX0 as [ ? | [ ? | [] ] ]; subst.\n      \n      left; apply H1.\n      right; left; apply H1.\n    Qed.\n\n  End two_prop.\n\n  Section two.\n  \n    Variable (X Y Z : Type) (P S : X -> Y -> Z -> Prop) (Q : X -> Z -> Prop) (R : Y -> Z -> Prop).\n    \n    Hypothesis HP : forall x y z, P x y z -> Q x z \\/ R y z \\/ S x y z.\n    \n    Fact two_list_decide ll mm : (forall x y, In x ll -> In y mm -> exists z, P x y z)\n                              -> (forall x, In x ll -> exists z, Q x z)\n                              \\/ (forall y, In y mm -> exists z, R y z)\n                              \\/ (exists x y z, In x ll /\\ In y mm /\\ S x y z).\n    Proof.\n      intros H.\n      destruct (two_list_decide_prop (fun x y => exists z, P x y z)\n                                     (fun x y => exists z, S x y z)\n                                     (fun x   => exists z, Q x z)\n                                     (fun   y => exists z, R y z)\n            ) with (2 := H) as [ HQ | [ HR | HS ] ]; try tauto.\n            \n      intros x y (z & Hz); apply HP in Hz; destruct Hz as [ | [|] ].\n      left; exists z; auto.\n      right; left; exists z; auto.\n      right; right; exists z; auto.\n      \n      destruct HS as (x & y & ? & ? & z & ?).\n      right; right; exists x, y, z; auto.\n    Qed.\n\n  End two.\n\nEnd list_decide_special.\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_decide.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733979704703, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6504439921675906}}
{"text": "Require Import Basics.\nRequire Import Types.\nRequire Import HProp.\nRequire Import HSet.\nRequire Import TruncType.\nRequire Import UnivalenceImpliesFunext.\nRequire Import Colimits.Pushout Truncations HIT.SetCone.\n\nLocal Open Scope path_scope.\n\nSection AssumingUA.\nContext `{ua:Univalence}.\n\n(** We will now prove that for sets, epis and surjections are equivalent.*)\nDefinition isepi {X Y} `(f:X->Y) := forall Z: hSet,\n  forall g h: Y -> Z, g o f = h o f -> g = h.\n\nDefinition isepi' {X Y} `(f : X -> Y) :=\n  forall (Z : hSet) (g : Y -> Z), Contr { h : Y -> Z | g o f = h o f }.\n\nLemma equiv_isepi_isepi' {X Y} f : @isepi X Y f <~> @isepi' X Y f.\nProof.\n  unfold isepi, isepi'.\n  apply (@equiv_functor_forall' _ _ _ _ _ (equiv_idmap _)); intro Z.\n  apply (@equiv_functor_forall' _ _ _ _ _ (equiv_idmap _)); intro g.\n  unfold equiv_idmap; simpl.\n  refine (transitivity (@equiv_sigT_ind _ (fun h : Y -> Z => g o f = h o f) (fun h => g = h.1)) _).\n  (** TODO(JasonGross): Can we do this entirely by chaining equivalences? *)\n  apply equiv_iff_hprop.\n  { intro hepi.\n    refine {| center := (g; idpath) |}.\n    intro xy; specialize (hepi xy).\n    apply path_sigma_uncurried.\n    exists hepi.\n    apply path_ishprop. }\n  { intros hepi xy.\n    exact (ap pr1 ((contr (g; 1))^ @ contr xy)). }\nDefined.\n\nSection cones.\n  Lemma isepi'_contr_cone `{Funext} {A B : hSet} (f : A -> B) : isepi' f -> Contr (setcone f).\n  Proof.\n    intros hepi.\n    exists (setcone_point _).\n    pose (alpha1 := @pglue A B Unit f (const tt)).\n    pose (tot:= { h : B -> setcone f & tr o push o inl o f = h o f }).\n    transparent assert (l : tot).\n    { simple refine (tr o _ o inl; _).\n      { refine push. }\n      { refine idpath. } }\n    pose (r := (@const B (setcone f) (setcone_point _); (ap (fun f => @tr 0 _ o f) (path_forall _ _ alpha1))) : tot).\n    subst tot.\n    assert (X : l = r).\n      { let lem := constr:(fun X push' => hepi (BuildhSet (setcone f)) (tr o push' o @inl _ X)) in\n        pose (lem _ push).\n        refine (path_contr l r). }\n    subst l r.\n\n    pose (I0 b := ap10 (X ..1) b).\n    refine (Trunc_ind _ _).\n    pose (fun a : B + Unit => (match a as a return setcone_point _ = tr (push a) with\n                                 | inl a' => (I0 a')^\n                                 | inr tt => idpath\n                               end)) as I0f.\n    refine (Pushout_ind _ (fun a' => I0f (inl a')) (fun u => (I0f (inr u))) _).\n\n    simpl. subst alpha1. intros.\n    unfold setcone_point.\n    subst I0. simpl.\n    pose (X..2) as p. simpl in p.\n    rewrite (transport_precompose f _ _ X..1) in p.\n    assert (H':=concat (ap (fun x => ap10 x a) p) (ap10_ap_postcompose tr (path_arrow (pushl o f) (pushr o const tt) pglue) _)).\n    rewrite ap10_path_arrow in H'.\n    clear p.\n    (** Apparently [pose; clearbody] is only ~.8 seconds, while [pose proof] is ~4 seconds? *)\n    pose (concat (ap10_ap_precompose f (X ..1) a)^ H') as p.\n    clearbody p.\n    simpl in p.\n    rewrite p.\n    rewrite transport_paths_Fr.\n    apply concat_Vp.\n  Qed.\nEnd cones.\n\nLemma issurj_isepi {X Y} (f:X->Y): IsSurjection f -> isepi f.\nProof.\nintros sur ? ? ? ep. apply path_forall. intro y.\nspecialize (sur y). pose (center (merely (hfiber f y))).\napply (Trunc_rec (n:=-1) (A:=(sigT (fun x : X => f x = y))));\n  try assumption.\nintros [x p]. set (p0:=apD10 ep x).\ntransitivity (g (f x)).\n- by apply ap.\n- transitivity (h (f x));auto with path_hints. by apply ap.\nQed.\n\n(** Old-style proof using polymorphic Omega. Needs resizing for the isepi proof to live in the\n same universe as X and Y (the Z quantifier is instantiated with an hSet at a level higher)\n<<\nLemma isepi_issurj {X Y} (f:X->Y): isepi f -> issurj f.\nProof.\n  intros epif y.\n  set (g :=fun _:Y => Unit_hp).\n  set (h:=(fun y:Y => (hp (hexists (fun _ : Unit => {x:X & y = (f x)})) _ ))).\n  assert (X1: g o f = h o f ).\n  - apply path_forall. intro x. apply path_equiv_biimp_rec;[|done].\n    intros _ . apply min1. exists tt. by (exists x).\n  - specialize (epif _ g h).\n    specialize (epif X1). clear X1.\n    set (p:=apD10 epif y).\n    apply (@minus1Trunc_map (sigT (fun _ : Unit => sigT (fun x : X => y = f x)))).\n    + intros [ _ [x eq]].\n      exists x.\n        by symmetry.\n    + apply (transport hproptype p tt).\nDefined.\n>> *)\n\nSection isepi_issurj.\n  Context {X Y : hSet} (f : X -> Y) (Hisepi : isepi f).\n  Definition epif := equiv_isepi_isepi' _ Hisepi.\n  Definition fam (c : setcone f) : hProp.\n  Proof.\n    pose (fib y := hexists (fun x : X => f x = y)).\n    apply (fun f => @Trunc_rec _ _ hProp _ f c).\n    refine (Pushout_rec hProp fib (fun _ => Unit_hp) (fun x => _)).\n    (** Prove that the truncated sigma is equivalent to Unit *)\n    pose (contr_inhabited_hprop (fib (f x)) (tr (x; idpath))) as i.\n    apply path_hprop. simpl. simpl in i.\n    apply (equiv_contr_unit).\n  Defined.\n\n  Lemma isepi_issurj : IsSurjection f.\n  Proof.\n    intros y.\n    pose (i := isepi'_contr_cone _ epif).\n\n    assert (X0 : forall x : setcone f, fam x = fam (setcone_point f)).\n    { intros. apply contr_dom_equiv. apply i. }\n    specialize (X0 (tr (push (inl y)))). simpl in X0.\n    exact (transport Contr (ap trunctype_type X0)^ _).\n  Defined.\nEnd isepi_issurj.\n\nLemma isepi_isequiv X Y (f : X -> Y) `{IsEquiv _ _ f}\n: isepi f.\nProof.\n  intros ? g h H'.\n  apply ap10 in H'.\n  apply path_forall.\n  intro x.\n  transitivity (g (f (f^-1 x))).\n  - by rewrite eisretr.\n  - transitivity (h (f (f^-1 x))).\n    * apply H'.\n    * by rewrite eisretr.\nQed.\nEnd AssumingUA.\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/HIT/epi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830606, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.6504439772148742}}
{"text": "Require Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Basics.\n\nRequire Import Coq.Bool.Bool.\n\nRequire Import Coq.Relations.Relation_Definitions.\n\nRequire Import Graph.\nRequire Import ReducedHomo.\n\nOpen Scope program_scope.\n\n(* Remove the empty leaves around an operator *)\nDefinition kSimpl {A: Type} (c : Graph A -> Graph A -> Graph A) (x y:Graph A) :=\n  if isEmpty x\n  then if isEmpty y\n    then Empty\n    else y\n  else if isEmpty y\n    then x\n    else c x y.\n\nDefinition dropEmpty {A:Type} (g:Graph A) := foldg Empty Vertex (kSimpl Overlay) (kSimpl Connect) g.\n\nDefinition induce {A:Type} (pred : A -> bool) (g:Graph A) :=\n  foldg Empty (fun x => if pred x then Vertex x else Empty) (kSimpl Overlay) (kSimpl Connect) g.\n\n(* A smart homomorphism is a graph morphism where you have removed empty leaves *)\nDefinition Smart_hom {A B} (f : Graph A -> Graph B) : Prop :=\n  f = dropEmpty ∘ (bind (compose f Vertex)).\n\nLemma smart_hom_empty {A B}  {f : Graph A -> Graph B}: Smart_hom f -> f Empty = Empty.\nProof.\n  intros H.\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma smart_hom_overlay {A B} {f : Graph A -> Graph B} (a b: Graph A):\n  Smart_hom f -> f (Overlay a b) = kSimpl Overlay (f a) (f b).\nProof.\n  intros H.\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma smart_hom_connect {A B} {f : Graph A -> Graph B} (a b: Graph A) :\n  Smart_hom f -> f (Connect a b) = kSimpl Connect (f a) (f b).\nProof.\n  intros H.\n  rewrite H.\n  reflexivity.\nQed.\n\n(* A smart homomorphism is a foldg-function *)\nTheorem smart_hom_single {A B} {f : Graph A -> Graph B} :\n  Smart_hom f -> f = foldg Empty (fun v => f (Vertex v)) (kSimpl Overlay) (kSimpl Connect).\nProof.\n  intros S.\n  apply FunctionalExtensionality.functional_extensionality.\n  intros g.\n  induction g.\n  - rewrite (smart_hom_empty S). auto.\n  - reflexivity.\n  - rewrite foldg_overlay.\n    rewrite (eq_sym IHg1).\n    rewrite (eq_sym IHg2).\n    rewrite (smart_hom_overlay g1 g2 S).\n    reflexivity.\n  - rewrite foldg_connect.\n    rewrite (eq_sym IHg1).\n    rewrite (eq_sym IHg2).\n    rewrite (smart_hom_connect g1 g2 S).\n    reflexivity.\nQed.\n\nLemma f_inside_if {A B} (f : A -> B) (x:bool) (a1 a2:A) : f (if x then a1 else a2) = if x then f a1 else f a2.\nProof.\n  induction x.\n  - auto.\n  - auto.\nQed.\n\nTheorem induce_smart_hom (A:Type) (pred : A -> bool) : Smart_hom (induce pred).\nProof.\n  unfold Smart_hom.\n  apply FunctionalExtensionality.functional_extensionality.\n  intro x.\n  induction x.\n  - auto.\n  - unfold compose; unfold bind; unfold induce; unfold foldg.\n    rewrite (f_inside_if dropEmpty (pred a)).\n    unfold dropEmpty; unfold foldg.\n    reflexivity.\n  - unfold induce; unfold compose; unfold dropEmpty.\n    rewrite foldg_overlay.\n    fold (induce pred x1); rewrite IHx1.\n    fold (induce pred x2); rewrite IHx2.\n    auto.\n  - unfold induce; unfold compose; unfold dropEmpty.\n    rewrite foldg_connect.\n    fold (induce pred x1); rewrite IHx1.\n    fold (induce pred x2); rewrite IHx2.\n    auto.\nQed.\n\nLemma r_ov_empty {A} {R: relation (Graph A)} {a b: Graph A} `{EqG A R} :\n   R a Empty -> R b Empty -> R (Overlay a b) Empty.\nProof.\n  intros ra rb.\n  rewrite rb.\n  rewrite (id_Plus a).\n  exact ra.\nQed.\n\nLemma r_co_empty {A} {R: relation (Graph A)} {a b: Graph A} `{EqG A R} :\n  R a Empty -> R b Empty -> R (Connect a b) Empty.\nProof.\n  intros ra rb.\n  rewrite rb.\n  rewrite EqG_TimesRightId.\n  exact ra.\nQed.\n\nLemma is_empty_R A (R: relation (Graph A)) (g:Graph A): EqG A R -> isEmpty g = true -> R g Empty.\nProof.\n  intros E i.\n  induction g.\n  - reflexivity.\n  - discriminate.\n  - unfold isEmpty in i.\n    rewrite foldg_overlay in i.\n    rewrite andb_true_iff in i.\n    fold (isEmpty g1) in i; fold (isEmpty g2) in i.\n    destruct i.\n    apply IHg1 in H; apply IHg2 in H0.\n    rewrite H0.\n    rewrite (id_Plus g1).\n    exact H.\n  - unfold isEmpty in i.\n    rewrite foldg_connect in i.\n    rewrite andb_true_iff in i.\n    fold (isEmpty g1) in i; fold (isEmpty g2) in i.\n    destruct i.\n    apply IHg1 in H; apply IHg2 in H0.\n    rewrite H0.\n    rewrite EqG_TimesRightId.\n    exact H.\nQed.\n\n(* A smart homomorphism is a reduced homomorphism *)\nTheorem smart_hom_is_reduced_hom A B (R: relation (Graph B)) (f : Graph A -> Graph B) :\n  EqG B R -> Smart_hom f -> Reduced_hom R f.\nProof.\n  intros H S.\n  split.\n  - exact H.\n  - rewrite (smart_hom_empty S).\n    reflexivity.\n  - intros a b.\n    rewrite (smart_hom_overlay a b S).\n    unfold kSimpl.\n    destruct (bool_dec (isEmpty (f a)) true); destruct (bool_dec (isEmpty (f b)) true).\n   -- rewrite e; rewrite e0.\n      symmetry.\n      apply r_ov_empty.\n      apply (is_empty_R B R (f a) H). exact e.\n      apply (is_empty_R B R (f b) H). exact e0.\n   -- rewrite e; rewrite (not_true_is_false (isEmpty (f b)) n).\n      rewrite (is_empty_R B R (f a) H e).\n      rewrite EqG_PlusCommut.\n      rewrite (id_Plus (f b)).\n      reflexivity.\n   -- rewrite (not_true_is_false (isEmpty (f a)) n); rewrite e.\n      rewrite (is_empty_R B R (f b) H e).\n      rewrite (id_Plus (f a)).\n      reflexivity.\n   -- rewrite (not_true_is_false (isEmpty (f a)) n).\n      rewrite (not_true_is_false (isEmpty (f b)) n0).\n      reflexivity.\n  - intros a b.\n    rewrite (smart_hom_connect a b S).\n    unfold kSimpl.\n    destruct (bool_dec (isEmpty (f a)) true); destruct (bool_dec (isEmpty (f b)) true).\n   -- rewrite e; rewrite e0.\n      symmetry.\n      apply r_co_empty.\n      apply (is_empty_R B R (f a) H); exact e.\n      apply (is_empty_R B R (f b) H); exact e0.\n   -- rewrite e; rewrite (not_true_is_false (isEmpty (f b)) n).\n      rewrite (is_empty_R B R (f a) H e).\n      rewrite (timesLeftId (f b)). reflexivity.\n   -- rewrite (not_true_is_false (isEmpty (f a)) n); rewrite e.\n      rewrite (is_empty_R B R (f b) H e).\n      rewrite EqG_TimesRightId.\n      reflexivity.\n   -- rewrite (not_true_is_false (isEmpty (f a)) n).\n      rewrite (not_true_is_false (isEmpty (f b)) n0).\n      reflexivity.\nQed.\n\nLemma smart_hom_e A B (f : Graph A -> Graph B) (x : Graph A) :\n  Smart_hom f -> isEmpty x = true -> f x = Empty.\nProof.\n  intros S i.\n  rewrite (smart_hom_single S).\n  induction x.\n  - auto.\n  - compute in i.\n    discriminate i.\n  - rewrite foldg_overlay.\n    unfold isEmpty in i.\n    rewrite foldg_overlay in i.\n    fold (isEmpty x1) in i.\n    fold (isEmpty x2) in i.\n    rewrite andb_true_iff in i.\n    destruct i as (i1,i2).\n    apply IHx1 in i1; rewrite i1.\n    apply IHx2 in i2; rewrite i2.\n    auto.\n  - rewrite foldg_connect.\n    unfold isEmpty in i.\n    rewrite foldg_connect in i.\n    fold (isEmpty x1) in i.\n    fold (isEmpty x2) in i.\n    rewrite andb_true_iff in i.\n    destruct i as (i1,i2).\n    apply IHx1 in i1; rewrite i1.\n    apply IHx2 in i2; rewrite i2.\n    auto.\nQed.\n\nLemma smart_hom_isE A B (f : Graph A -> Graph B) (x : Graph A) :\n  Smart_hom f -> isEmpty x = true -> isEmpty (f x) = true.\nProof.\n  intros S i.\n  rewrite (smart_hom_e A B f x S i).\n  auto.\nQed.\n\nLemma isEmpty_kSimpl A c (x y : Graph A) :\n   c = Overlay \\/ c = Connect -> isEmpty (kSimpl c x y) = true -> isEmpty x = true /\\ isEmpty y = true.\nProof.\n  intros H i.\n  unfold kSimpl in i.\n  destruct (bool_dec (isEmpty x) true); destruct (bool_dec (isEmpty y) true).\n  - rewrite e. rewrite e0. auto.\n  - rewrite e.\n    split. auto.\n    rewrite e in i.\n    rewrite (not_true_is_false (isEmpty y) n) in i.\n    exact i.\n  - rewrite e.\n    split. auto.\n    rewrite e in i.\n    rewrite (not_true_is_false (isEmpty x) n) in i.\n    exact i. auto.\n  - rewrite (not_true_is_false (isEmpty x) n) in i.\n    rewrite (not_true_is_false (isEmpty y) n0) in i.\n    destruct H.\n -- rewrite H in i.\n    unfold isEmpty in i.\n    rewrite foldg_overlay in i.\n    fold (isEmpty x) in i. fold (isEmpty y) in i.\n    rewrite andb_true_iff in i.\n    exact i.\n -- rewrite H in i.\n    unfold isEmpty in i.\n    rewrite foldg_connect in i.\n    fold (isEmpty x) in i. fold (isEmpty y) in i.\n    rewrite andb_true_iff in i.\n    exact i.\nQed.\n\nLemma ovov A : Overlay (A:=A) = Overlay. Proof. auto. Qed.\nLemma coco A : Connect (A:=A) = Connect. Proof. auto. Qed.\n\nLemma isEmpty_drope_e A (x : Graph A) :\n isEmpty (dropEmpty x) = true -> dropEmpty x = Empty.\nProof.\n  intros H.\n  induction x.\n  - auto.\n  - compute in H. discriminate H.\n  - unfold dropEmpty.\n    rewrite foldg_overlay.\n    fold (dropEmpty x1).\n    fold (dropEmpty x2).\n    unfold dropEmpty in H.\n    rewrite foldg_overlay in H.\n    fold (dropEmpty x1) in H.\n    fold (dropEmpty x2) in H.\n    destruct (isEmpty_kSimpl A Overlay (dropEmpty x1) (dropEmpty x2) (or_introl (ovov A)) H) as (H1,H2).\n    apply IHx1 in H1. rewrite H1.\n    apply IHx2 in H2. rewrite H2.\n    auto.\n  - unfold dropEmpty.\n    rewrite foldg_connect.\n    fold (dropEmpty x1).\n    fold (dropEmpty x2).\n    unfold dropEmpty in H.\n    rewrite foldg_connect in H.\n    fold (dropEmpty x1) in H.\n    fold (dropEmpty x2) in H.\n    destruct (isEmpty_kSimpl A Connect (dropEmpty x1) (dropEmpty x2) (or_intror (coco A)) H) as (H1,H2).\n    apply IHx1 in H1. rewrite H1.\n    apply IHx2 in H2. rewrite H2.\n    auto.\nQed.\n\n(* You can compose two smart homomorphisms *)\nTheorem smart_hom_compo A B C (s1 : Graph A -> Graph B) (s2 : Graph B -> Graph C):\n (Smart_hom s1) /\\ (Smart_hom s2) ->\n  s2 ∘ s1 = foldg Empty (s2 ∘ s1 ∘ Vertex) (kSimpl Overlay) (kSimpl Connect).\nProof.\n  intros H.\n  destruct H as (H1,H2).\n  rewrite (smart_hom_single H1).\n  rewrite (smart_hom_single H1) in H1.\n  remember (foldg Empty (fun v : A => s1 (Vertex v)) (kSimpl Overlay) (kSimpl Connect)) as f1.\n  rewrite (smart_hom_single H2).\n  rewrite (smart_hom_single H2) in H2.\n  remember (foldg Empty (fun v : B => s2 (Vertex v)) (kSimpl Overlay) (kSimpl Connect)) as f2.\n  apply FunctionalExtensionality.functional_extensionality.\n  intros g.\n  unfold compose.\n  induction g.\n  - rewrite Heqf1. rewrite Heqf2. auto.\n  - rewrite Heqf1. rewrite Heqf2. auto.\n  - rewrite Heqf1.\n    repeat rewrite foldg_overlay.\n    rewrite (eq_sym Heqf1).\n    rewrite (eq_sym IHg1). rewrite (eq_sym IHg2).\n    unfold kSimpl.\n    destruct (bool_dec (isEmpty (f1 g1)) true) ; destruct (bool_dec (isEmpty (f1 g2)) true).\n -- rewrite e. rewrite (smart_hom_e B C f2 (f1 g1) H2 e). simpl.\n    rewrite e0.\n    rewrite (smart_hom_isE B C f2 (f1 g2) H2 e0).\n    rewrite (smart_hom_empty H2). reflexivity.\n -- rewrite e. rewrite (not_true_is_false (isEmpty (f1 g2)) n).\n    rewrite (smart_hom_e B C f2 (f1 g1) H2 e). simpl.\n    destruct (bool_dec (isEmpty (f2 (f1 g2))) true).\n  + rewrite e0.\n    rewrite H2.\n    unfold compose.\n    apply (isEmpty_drope_e C).\n    fold (f2 ∘ Vertex).\n    fold (compose dropEmpty (bind (f2 ∘ Vertex)) (f1 g2)).\n    rewrite (eq_sym H2). exact e0.\n  + rewrite (not_true_is_false (isEmpty (f2 (f1 g2))) n0). reflexivity.\n -- rewrite e. rewrite (not_true_is_false (isEmpty (f1 g1)) n).\n    rewrite (smart_hom_e B C f2 (f1 g2) H2 e). simpl.\n    destruct (bool_dec (isEmpty (f2 (f1 g1))) true).\n  + rewrite e0.\n    rewrite H2.\n    unfold compose.\n    apply (isEmpty_drope_e C).\n    fold (f2 ∘ Vertex).\n    fold (compose dropEmpty (bind (f2 ∘ Vertex)) (f1 g1)).\n    rewrite (eq_sym H2). exact e0.\n  + rewrite (not_true_is_false (isEmpty (f2 (f1 g1))) n0). reflexivity.\n -- rewrite (not_true_is_false (isEmpty (f1 g1)) n).\n    rewrite (not_true_is_false (isEmpty (f1 g2)) n0).\n    rewrite (smart_hom_overlay (f1 g1) (f1 g2) H2). auto.\n  - rewrite Heqf1.\n    repeat rewrite foldg_connect.\n    rewrite (eq_sym Heqf1).\n    rewrite (eq_sym IHg1). rewrite (eq_sym IHg2).\n    unfold kSimpl.\n    destruct (bool_dec (isEmpty (f1 g1)) true) ; destruct (bool_dec (isEmpty (f1 g2)) true).\n -- rewrite e. rewrite (smart_hom_e B C f2 (f1 g1) H2 e). simpl.\n    rewrite e0.\n    rewrite (smart_hom_isE B C f2 (f1 g2) H2 e0).\n    rewrite (smart_hom_empty H2). reflexivity.\n -- rewrite e. rewrite (not_true_is_false (isEmpty (f1 g2)) n).\n    rewrite (smart_hom_e B C f2 (f1 g1) H2 e). simpl.\n    destruct (bool_dec (isEmpty (f2 (f1 g2))) true).\n  + rewrite e0.\n    rewrite H2.\n    unfold compose.\n    apply (isEmpty_drope_e C).\n    fold (f2 ∘ Vertex).\n    fold (compose dropEmpty (bind (f2 ∘ Vertex)) (f1 g2)).\n    rewrite (eq_sym H2). exact e0.\n  + rewrite (not_true_is_false (isEmpty (f2 (f1 g2))) n0). reflexivity.\n -- rewrite e. rewrite (not_true_is_false (isEmpty (f1 g1)) n).\n    rewrite (smart_hom_e B C f2 (f1 g2) H2 e). simpl.\n    destruct (bool_dec (isEmpty (f2 (f1 g1))) true).\n  + rewrite e0.\n    rewrite H2.\n    unfold compose.\n    apply (isEmpty_drope_e C).\n    fold (f2 ∘ Vertex).\n    fold (compose dropEmpty (bind (f2 ∘ Vertex)) (f1 g1)).\n    rewrite (eq_sym H2). exact e0.\n  + rewrite (not_true_is_false (isEmpty (f2 (f1 g1))) n0). reflexivity.\n -- rewrite (not_true_is_false (isEmpty (f1 g1)) n).\n    rewrite (not_true_is_false (isEmpty (f1 g2)) n0).\n    rewrite (smart_hom_connect (f1 g1) (f1 g2) H2). auto.\nQed.\n\nLemma dropEmpty_idempotence A (x:Graph A) : dropEmpty (dropEmpty x) = dropEmpty x.\nProof.\n  induction x.\n  - auto.\n  - auto.\n  - unfold dropEmpty.\n    rewrite foldg_overlay.\n    fold (dropEmpty x1).\n    fold (dropEmpty x2).\n    unfold kSimpl at 3 4.\n    destruct (bool_dec (isEmpty (dropEmpty x1)) true) ; destruct (bool_dec (isEmpty (dropEmpty x2)) true).\n -- rewrite e. rewrite e0. auto.\n -- rewrite e. rewrite (not_true_is_false (isEmpty (dropEmpty x2)) n). auto.\n -- rewrite e. rewrite (not_true_is_false (isEmpty (dropEmpty x1)) n). auto.\n -- rewrite (not_true_is_false (isEmpty (dropEmpty x1)) n).\n    rewrite (not_true_is_false (isEmpty (dropEmpty x2)) n0).\n    rewrite foldg_overlay.\n    fold (dropEmpty (dropEmpty x1)).\n    fold (dropEmpty (dropEmpty x2)).\n    rewrite IHx1.\n    rewrite IHx2.\n    unfold kSimpl.\n    rewrite (not_true_is_false (isEmpty (dropEmpty x1)) n).\n    rewrite (not_true_is_false (isEmpty (dropEmpty x2)) n0).\n    reflexivity.\n  - unfold dropEmpty.\n    rewrite foldg_connect.\n    fold (dropEmpty x1).\n    fold (dropEmpty x2).\n    unfold kSimpl at 3 4.\n    destruct (bool_dec (isEmpty (dropEmpty x1)) true) ; destruct (bool_dec (isEmpty (dropEmpty x2)) true).\n -- rewrite e; rewrite e0; auto.\n -- rewrite e; rewrite (not_true_is_false (isEmpty (dropEmpty x2)) n); auto.\n -- rewrite e; rewrite (not_true_is_false (isEmpty (dropEmpty x1)) n); auto.\n -- rewrite (not_true_is_false (isEmpty (dropEmpty x1)) n).\n    rewrite (not_true_is_false (isEmpty (dropEmpty x2)) n0).\n    rewrite foldg_connect.\n    fold (dropEmpty (dropEmpty x1)).\n    fold (dropEmpty (dropEmpty x2)).\n    rewrite IHx1.\n    rewrite IHx2.\n    unfold kSimpl.\n    rewrite (not_true_is_false (isEmpty (dropEmpty x1)) n).\n    rewrite (not_true_is_false (isEmpty (dropEmpty x2)) n0).\n    reflexivity.\nQed.\n\n(* And the composition of two smart homomorphisms is a smart homomorphism *)\nTheorem smart_hom_compo_is_smart A B C (s1 : Graph A -> Graph B) (s2 : Graph B -> Graph C):\n (Smart_hom s1) /\\ (Smart_hom s2) -> Smart_hom (s2 ∘ s1).\nProof.\n  intros H.\n  rewrite (smart_hom_compo A B C s1 s2 H).\n  destruct H as (H1,H2).\n  unfold Smart_hom.\n  apply FunctionalExtensionality.functional_extensionality.\n  intro g.\n  unfold compose.\n  induction g.\n  - auto.\n  - unfold bind. unfold foldg.\n    rewrite H2.\n    unfold compose.\n    rewrite (dropEmpty_idempotence C (bind (fun x : B => s2 (Vertex x)) (s1 (Vertex a)))).\n    reflexivity.\n  - rewrite foldg_overlay.\n    rewrite IHg1.\n    rewrite IHg2.\n    auto.\n  - rewrite foldg_connect.\n    rewrite IHg1.\n    rewrite IHg2.\n    auto.\nQed.", "meta": {"author": "nobrakal", "repo": "coq-alga", "sha": "a8d45e3b96d39b8cf79f259540ec29204ede7e5c", "save_path": "github-repos/coq/nobrakal-coq-alga", "path": "github-repos/coq/nobrakal-coq-alga/coq-alga-a8d45e3b96d39b8cf79f259540ec29204ede7e5c/src/SmartHomo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339556397749, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6504439691576545}}
{"text": "Require Import Coq.Program.Tactics.\n\n\n(** * Introduction *)\n\n(** The models we formalize all provide the structure of a category:\n\n  - A set of objects, representing interfaces,\n  - Morphisms between objects, representing components,\n  - Identities for trivial components,\n  - Composition of morphisms along a common interface.\n\n  By using Coq's module system, we can ensure a uniform interface\n  across different model and maximize code reuse, without paying for\n  the additional complexity what would come with a first-class\n  treatment of the underlying categorical concepts. *)\n\n\n(** * Categories *)\n\n(** ** Definition *)\n\n(** The following interface gives the basic definition of a category. *)\n\nModule Type CategoryDefinition.\n\n  (** Objects and morphisms *)\n\n  Parameter t : Type.\n  Parameter m : t -> t -> Type.\n\n  (** Identity and composition *)\n\n  Parameter id : forall A, m A A.\n  Parameter compose : forall {A B C}, m B C -> m A B -> m A C.\n\n  (** Properties *)\n\n  Axiom compose_id_left :\n    forall {A B} (f : m A B), compose (id B) f = f.\n\n  Axiom compose_id_right :\n    forall {A B} (f : m A B), compose f (id A) = f.\n\n  Axiom compose_assoc :\n    forall {A B C D} (f : m A B) (g : m B C) (h : m C D),\n      compose (compose h g) f = compose h (compose g f).\n\nEnd CategoryDefinition.\n\n(** ** Theory *)\n\n(** Once the fields enumerated in [CategoryDefinition] have been\n  defined, the user should include the following module, which works\n  out some basic category theory. *)\n\nModule CategoryTheory (C : CategoryDefinition).\n\n  (** ** Notations *)\n\n  Delimit Scope obj_scope with obj.\n  Bind Scope obj_scope with C.t.\n  Open Scope obj_scope.\n\n  Delimit Scope hom_scope with hom.\n  Bind Scope hom_scope with C.m.\n  Open Scope hom_scope.\n\n  Infix \"@\" := C.compose (at level 45, right associativity) : hom_scope.\n\n  (** ** Isomorphisms *)\n\n  Structure iso {A B : C.t} :=\n    {\n      fw :> C.m A B;\n      bw : C.m B A;\n      bw_fw : bw @ fw = C.id A;\n      fw_bw : fw @ bw = C.id B;\n    }.\n\n  Arguments iso : clear implicits.\n\n  (** The following versions help rewriting modulo associativity. *)\n\n  Lemma bw_fw_rewrite {A B X} (f : iso A B) (x : C.m X A) :\n    bw f @ fw f @ x = x.\n  Proof.\n    rewrite <- C.compose_assoc, bw_fw.\n    apply C.compose_id_left.\n  Qed.\n\n  Lemma fw_bw_rewrite {A B X} (f : iso A B) (x : C.m X B) :\n    fw f @ bw f @ x = x.\n  Proof.\n    rewrite <- C.compose_assoc, fw_bw.\n    apply C.compose_id_left.\n  Qed.\n\n  (** We can define some basic instances. *)\n\n  Program Canonical Structure id_iso {A} :=\n    {|\n      fw := C.id A;\n      bw := C.id A;\n    |}.\n  Solve All Obligations with\n    auto using C.compose_id_left.\n\n  Canonical Structure bw_iso {A B} (f : iso A B) :=\n    {|\n      fw := bw f;\n      bw := fw f;\n      bw_fw := fw_bw f;\n      fw_bw := bw_fw f;\n    |}.\n\n  Program Canonical Structure compose_iso {A B C} (g : iso B C) (f : iso A B) :=\n    {|\n      fw := fw g @ fw f;\n      bw := bw f @ bw g;\n    |}.\n  Solve All Obligations with\n    intros;\n    rewrite ?C.compose_assoc, ?bw_fw_rewrite, ?fw_bw_rewrite, ?fw_bw, ?bw_fw;\n    auto.\n\nEnd CategoryTheory.\n\n(** ** Overall interface *)\n\n(** A module defining a specific category is expected to provide the\n  basic definitions and include the theory. *)\n\nModule Type Category.\n  Include CategoryDefinition.\n  Include CategoryTheory.\nEnd Category.\n\n\n\n\n\n\n\n(** ** Basic instances *)\n\n(** *** Product category *)\n\n(** This is used in particular to give bifunctors a functor interface. *)\n\nModule Prod (C D : CategoryDefinition) <: Category.\n\n  (** Objects and morphisms *)\n\n  Definition t : Type := C.t * D.t.\n  Definition m (A B : t) : Type := C.m (fst A) (fst B) * D.m (snd A) (snd B).\n\n  (** Composition *)\n\n  Definition id A : m A A :=\n    (C.id (fst A), D.id (snd A)).\n\n  Definition compose {A B C} (g : m B C) (f : m A B) : m A C :=\n    (C.compose (fst g) (fst f), D.compose (snd g) (snd f)).\n\n  (** Proofs *)\n\n  Lemma compose_id_left {A B} (f : m A B) :\n    compose (id B) f = f.\n  Proof.\n    destruct f; unfold id, compose; cbn; f_equal.\n    - apply C.compose_id_left.\n    - apply D.compose_id_left.\n  Qed. \n\n  Lemma compose_id_right {A B} (f : m A B) :\n    compose f (id A) = f.\n  Proof.\n    destruct f; unfold id, compose; cbn; f_equal.\n    - apply C.compose_id_right.\n    - apply D.compose_id_right.\n  Qed.\n\n  Lemma compose_assoc {A B C D} (f : m A B) (g : m B C) (h : m C D) :\n    compose (compose h g) f = compose h (compose g f).\n  Proof.\n    destruct f, g, h; unfold id, compose; cbn; f_equal.\n    - apply C.compose_assoc.\n    - apply D.compose_assoc.\n  Qed.\n\n  Include CategoryTheory.\n\nEnd Prod.\n\n\n\n\n\n", "meta": {"author": "CertiKOS", "repo": "rbgs", "sha": "2802704c2ee0068a78874b7424aad09d69ce34b0", "save_path": "github-repos/coq/CertiKOS-rbgs", "path": "github-repos/coq/CertiKOS-rbgs/rbgs-2802704c2ee0068a78874b7424aad09d69ce34b0/interfaces/Category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.650388121544353}}
{"text": "(** Instance of identity on propositions *)\n\nTheorem not_False : ~ False.\nProof.  unfold not; trivial.  Qed.\n\nDefinition  not_False' : ~ False :=\n fun H => H.\n\nTheorem triple_neg : forall P:Prop, ~ ~ ~ P -> ~ P.\nProof.  auto. Qed.\n\nTheorem P3PQ : forall P Q:Prop, ~ ~ ~ P -> P -> Q.\nProof. tauto. Qed.\n\n(** instance of the transivity of -> \n*)\nTheorem contrap : forall P Q:Prop, (P -> Q) -> ~ Q -> ~ P.\nProof. auto. Qed.\n\nTheorem imp_absurd : forall P Q R:Prop, (P -> Q) -> (P -> ~ Q) -> P -> R.\nProof.  tauto. Qed.\n\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch5_everydays_logic/SRC/on_negation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6503881167938514}}
{"text": "Require Import Coq.ZArith.BinInt.\nRequire Import riscv.Encode.\nRequire Import riscv.util.ZBitOps.\nRequire Import riscv.util.prove_Zeq_bitwise.\n\nLemma invert_encode_I_shift_57: forall {opcode rd rs1 shamt5 funct3 funct7},\n  verify_I_shift_57 opcode rd rs1 shamt5 funct3 funct7 ->\n  forall inst,\n  encode_I_shift_57 opcode rd rs1 shamt5 funct3 funct7 = inst ->\n  opcode = bitSlice inst 0 7 /\\\n  funct3 = bitSlice inst 12 15 /\\\n  funct7 = bitSlice inst 25 32 /\\\n  rd = bitSlice inst 7 12 /\\\n  rs1 = bitSlice inst 15 20 /\\\n  shamt5 = bitSlice inst 20 25.\nProof. intros. unfold encode_I_shift_57, verify_I_shift_57 in *. prove_Zeq_bitwise. Qed.\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/proofs/invert_encode_I_shift_57.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.650388115559593}}
{"text": "Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq div.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nTheorem well_founded_lt : well_founded (fun n m => n < m).\nProof.\n  move => x.\n  elim: x {1 3}x (leqnn x) => [| n IHn] x H; constructor => y H0.\n  - by case: x H H0.\n  - exact: (IHn _ (leq_trans H0 H)).\nDefined.\n\nLemma problem1 a : a ^ 2 %% 3 != 2.\nProof.\n  by rewrite /expn /= -modnMm;\n    case: (a %% 3) (@ltn_pmod a 3 erefl) => [| [| []]].\nQed.\n\nLemma problem2 a b c :\n  a ^ 2 + b ^ 2 = 3 * c ^ 2 -> [&& 3 %| a, 3 %| b & 3 %| c].\nProof.\n  move => H.\n  have/andP [H0 H1]: (3 %| a) && (3 %| b).\n    move/(f_equal (modn ^~ 3)):\n      H (problem1 a) (problem1 b) (@ltn_pmod a 3 erefl) (@ltn_pmod b 3 erefl).\n    rewrite /dvdn /expn /= -modnMml modnn mul0n mod0n -modnDm\n            -(modnMm a) -(modnMm b).\n    by move: (a %% 3) (b %% 3) => [| [| [| a']]] [| [| []]].\n  rewrite H0 H1 /=; move/(f_equal (modn ^~ (3 ^ 2))): H.\n  have/eqP {H0} -> : 3 ^ 2 %| a ^ 2 + b ^ 2 by\n    rewrite /expn /=; apply dvdn_add; apply dvdn_mul.\n  move/esym/eqP; rewrite -/(dvdn _ _) dvdn_pmul2l // /dvdn /expn /= -modnMm.\n  by case: (c %% 3) (@ltn_pmod c 3 erefl) => [| [| []]].\nQed.\n\nLemma divn_expAC d m n : d %| m -> (m %/ d) ^ n = (m ^ n) %/ (d ^ n).\nProof.\n  by move => H; elim: n => //= n IH;\n    rewrite !expnS IH divn_mulAC // muln_divA ?dvdn_exp2r // -divnMA (mulnC d).\nQed.\n\nLemma problem3 a b c :\n  a ^ 2 + b ^ 2 = 3 * c ^ 2 -> [&& a == 0, b == 0 & c == 0].\nProof.\n  move => H.\n  suff H0: c = 0 by move: H; rewrite H0; move: a b => [] // [].\n  move: c (well_founded_lt c) a b H; refine (Acc_ind _ _).\n  case => [] // c _ IH a b H.\n  case/problem2/and3P: (H) (IH (c.+1 %/ 3)) => H0 H1 H2.\n  rewrite ltn_Pdiv // => /(_ erefl (a %/ 3) (b %/ 3)).\n  rewrite -{3}(divnK H2) => -> //.\n  by rewrite !divn_expAC // -divnDl ?dvdn_mul // H /expn /= muln_divA ?dvdn_mul.\nQed.\n", "meta": {"author": "pi8027", "repo": "tppmark", "sha": "5e10960e55570da6e73ee12dbe116873778b310b", "save_path": "github-repos/coq/pi8027-tppmark", "path": "github-repos/coq/pi8027-tppmark/tppmark-5e10960e55570da6e73ee12dbe116873778b310b/2014/solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861582, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6503880992414025}}
{"text": "(**************************************************************************)\n(*           *                                                            *)\n(*     _     *   The Coccinelle Library / Evelyne Contejean               *)\n(*    <o>    *          CNRS-LRI-Universite Paris Sud                     *)\n(*  -/@|@\\-  *                   A3PAT Project                            *)\n(*  -@ | @-  *                                                            *)\n(*  -\\@|@/-  *      This file is distributed under the terms of the       *)\n(*    -v-    *      CeCILL-C licence                                      *)\n(*           *                                                            *)\n(**************************************************************************)\n\nRequire Import Bool.\nRequire Import List.\nRequire Import closure.\nRequire Import more_list.\nRequire Import equiv_list.\nRequire Import list_permut.\nRequire Import dickson.\nRequire Import Relations.\nRequire Import Wellfounded.\nRequire Import Arith.\nRequire Import Wf_nat.\nRequire Import term_spec.\nRequire Import term.\nRequire Import decidable_set.\nRequire Import ordered_set.\nRequire Import Recdef.\nRequire Import Program.\n\n\nSet Implicit Arguments.\n\n(** A non-dependant version of lexicographic extension. *)\nDefinition lex (A B : Type) \n     (eq_bool : A -> A -> bool) \n     (o1 : relation A) (o2 : relation B) (s t : _ * _) :=\n  match s with\n  | (s1,s2) =>\n    match t with\n    | (t1,t2) => \n       if eq_bool s1 t1\n       then o2 s2 t2\n       else o1 s1 t1\n     end\n   end.\n\n(** Transitivity of  lexicographic extension. *)\nLemma lex_trans :\n forall (A B : Type) (eq_bool : A -> A -> bool) o1 o2\n (eq_bool_ok : forall a1 a2, if eq_bool a1 a2 then a1 = a2 else a1 <> a2), \n antisymmetric A o1 -> transitive A o1 -> transitive B o2 ->\n transitive _ (lex eq_bool o1 o2).\nProof.\nunfold transitive, lex; \nintros A B eq_bool o1 o2 eq_bool_ok A1 T1 T2 p1 p2 p3; \ndestruct p1 as [a1 b1]; destruct p2 as [a2 b2]; destruct p3 as [a3 b3].\ngeneralize (eq_bool_ok a1 a2); case (eq_bool a1 a2); [intro a1_eq_a2; subst a1 | intro a1_diff_a2].\ngeneralize (eq_bool_ok a2 a3); case (eq_bool a2 a3); [intro a2_eq_a3; subst a2 | intro a2_diff_a3].\napply T2.\nintros _ a2_t_a3; assumption.\ngeneralize (eq_bool_ok a2 a3); case (eq_bool a2 a3); [intro a2_eq_a3; subst a2 | intro a2_diff_a3].\ngeneralize (eq_bool_ok a1 a3); case (eq_bool a1 a3); [intro a1_eq_a3; subst a1 | intro a1_diff_a3].\napply False_rec; apply a1_diff_a2; reflexivity.\nintros a1_lt_a3 _; assumption.\ngeneralize (eq_bool_ok a1 a3); case (eq_bool a1 a3); [intro a1_eq_a3; subst a1 | intro a1_diff_a3].\nintros a3_lt_a2 a2_lt_a3; absurd (a3 = a2).\nassumption.\nexact ( A1 a3 a2 a3_lt_a2 a2_lt_a3).\nintros a1_lt_a2 a2_lt_a3; exact (T1 _ _ _ a1_lt_a2 a2_lt_a3).\nQed.\n\n(** Well-foundedness of  lexicographic extension. *)\nLemma wf_lex :\n  forall A B (eq_bool : A -> A -> bool) o1 o2 \n  (eq_bool_ok : forall a1 a2, if eq_bool a1 a2 then a1 = a2 else a1 <> a2), \n  well_founded o1 -> well_founded o2 ->\n  well_founded (@lex A B eq_bool o1 o2).\nProof.\nintros A B eq_bool o1 o2 eq_bool_ok W1 W2.\nintros [a1 a2]; revert a2; generalize (W1 a1); intros Wa1 a2; generalize (W2 a2).\nrevert a2; induction Wa1 as [a1 Wa1 wf_lex].\nintros a2 Wa2.\nrevert a1 Wa1 wf_lex.\nrevert a2 Wa2; fix wf_lex2 2.\nintros a2 Wa2 a1 Wa1 wf_lex.\napply Acc_intro; intros [b1 b2]; simpl.\ngeneralize (eq_bool_ok b1 a1); case (eq_bool b1 a1); [intro b1_eq_a1 | intro b1_diff_a1].\nintros b2_lt_a2; rewrite b1_eq_a1.\napply (wf_lex2 b2 (Acc_inv Wa2 b2_lt_a2) a1 Wa1 wf_lex).\nintro b1_lt_a1; exact (wf_lex b1 b1_lt_a1 _ (W2 b2)).\nDefined.\n\n\n(** ** Module Type Precedence, \n** Definition of a precedence. *)\n\nInductive status_type : Set :=\n  | Lex : status_type\n  | Mul : status_type.\n(*\nModule Type Precedence.\nParameter A : Type.\nParameter status : A -> status_type.\n\nParameter prec : relation A.\nParameter prec_bool : A -> A -> bool.\n\nParameter prec_bool_ok : forall a1 a2, match prec_bool a1 a2 with true => prec a1 a2 | false => ~prec a1 a2 end.\nParameter prec_antisym : forall s, prec s s -> False.\nParameter prec_transitive : transitive A prec.\n\nEnd Precedence.\n*)\n\nRecord Precedence (A : Type) : Type := {\n  status : A -> status_type;\n  prec : relation A;\n  prec_bool : A -> A -> bool;\n  prec_bool_ok : forall a1 a2, match prec_bool a1 a2 with true => prec a1 a2 | false => ~prec a1 a2 end;\n  prec_antisym : forall s, prec s s -> False;\n  prec_transitive : transitive A prec;\n\n  prec_eq : relation A;\n  prec_eq_bool : A -> A -> bool;\n  prec_eq_transitive : transitive A prec_eq;\n  prec_eq_refl : forall s, prec_eq s s;\n  prec_eq_bool_ok: forall a1 a2, match prec_eq_bool a1 a2 with true => prec_eq  a1 a2 | false => ~prec_eq a1 a2 end;\n  prec_eq_prec1: forall a1 a2 a3, prec a1 a2 -> prec_eq a2 a3 -> prec a1 a3;\n  prec_eq_prec2: forall a1 a2 a3, prec a1 a2 -> prec_eq a1 a3 -> prec a3 a2;\n  prec_eq_sym : forall s t, prec_eq s t -> prec_eq t s;\n  prec_not_prec_eq: forall f g, prec f g -> prec_eq f g -> False;\n  prec_eq_status: forall f g, prec_eq f g -> status f = status g\n}.\n\n\n(** ** Module Type RPO, \n** Definition of RPO from a precedence on symbols. *)\n\nModule Type RPO.\n\n  Declare Module Import T : Term.\n(*Declare Module Import P : Precedence with Definition A:= T.symbol.*)\n  Section S.\n    Variable P : Precedence T.symbol.\n(** ** Definition of rpo.*)\n    Inductive equiv : term -> term -> Prop :=\n    | Eq : forall t, equiv t t\n    | Eq_lex : \n      forall f g l1 l2, status P f = Lex -> status P g = Lex -> prec_eq P f g -> equiv_list_lex l1 l2 -> \n        equiv (Term f  l1) (Term g l2) \n    | Eq_mul :\n      forall f g l1 l2,  status P f = Mul -> status P g = Mul -> prec_eq P f g -> permut0 equiv l1 l2 ->\n        equiv (Term f l1) (Term g l2)\n\n    with equiv_list_lex : list term -> list term -> Prop :=\n    | Eq_list_nil : equiv_list_lex nil nil\n    | Eq_list_cons : \n      forall t1 t2 l1 l2, equiv t1 t2 -> equiv_list_lex l1 l2 ->\n        equiv_list_lex (t1 :: l1) (t2 :: l2).\n\n    Parameter equiv_in_list : \n      forall f g (f_stat : status  P f= Lex) (g_stat: status P g = Lex) l1 l2, length l1 = length l2 -> prec_eq P f g ->\n        (forall t1 t2, In (t1, t2) (combine l1 l2) -> equiv  t1  t2) -> \n        equiv (Term f l1) (Term g l2).\n\n(* equiv is actually an equivalence *)\n    Parameter equiv_equiv  : equivalence term equiv.\n\n    Parameter equiv_dec : forall t1 t2, {equiv t1 t2}+{~equiv t1 t2}.\n(*\nDeclare Module Import LP : \n    list_permut.S with Definition EDS.A:=term \n                        with Definition EDS.eq_A := equiv.\n*)\n\n    Inductive rpo (bb : nat) : term -> term -> Prop :=\n    | Subterm : forall f l t s, mem equiv s l -> rpo_eq bb t s -> rpo bb t (Term f l)\n    | Top_gt : \n      forall f g l l', prec P g f -> (forall s', mem equiv s' l' -> rpo bb s' (Term f l)) -> \n        rpo bb (Term g l') (Term f l)\n    | Top_eq_lex : \n      forall f g l l', status P f = Lex -> status P g = Lex -> prec_eq P f g -> (length l = length l' \\/ (length l' <= bb /\\ length l <= bb)) -> rpo_lex bb l' l -> \n        (forall s', mem equiv s' l' -> rpo bb s' (Term g l)) ->\n        rpo bb (Term f l') (Term g l)\n    | Top_eq_mul : \n      forall f g l l', status P f = Mul  -> status P g = Mul -> prec_eq P f g -> rpo_mul bb l' l -> \n        rpo bb (Term f l') (Term g l)\n\n    with rpo_eq (bb : nat) : term -> term -> Prop :=\n    | Equiv : forall t t', equiv t t' -> rpo_eq bb t t'\n    | Lt : forall s t, rpo bb s t -> rpo_eq bb s t\n\n    with rpo_lex (bb : nat) : list term -> list term -> Prop :=\n    | List_gt : forall s t l l', rpo bb s t -> rpo_lex bb (s :: l) (t :: l')\n    | List_eq : forall s s' l l', equiv s s' -> rpo_lex bb l l' -> rpo_lex bb (s :: l) (s' :: l')\n    | List_nil : forall s l, rpo_lex bb nil (s :: l)\n\n    with rpo_mul ( bb : nat) : list term -> list term -> Prop :=\n    | List_mul : forall a lg ls lc l l', \n      permut0 equiv l' (ls ++ lc) -> permut0 equiv l (a :: lg ++ lc) ->\n      (forall b, mem equiv b ls -> exists a', mem equiv a' (a :: lg) /\\ rpo bb b a') ->\n      rpo_mul bb l' l.\n\n(* Two equivalent terms have the same behaviour for rpo *)\n    Parameter equiv_rpo_equiv_1 :\n      forall bb t t', equiv t t' -> (forall s, rpo bb s t <-> rpo bb s t').\n\n    Parameter equiv_rpo_equiv_2 :\n      forall bb t t', equiv t t' -> (forall s, rpo bb t s <-> rpo bb t' s).\n\n    Parameter equiv_rpo_equiv_3 :\n      forall bb t t', equiv t t' -> (forall s, rpo_eq bb s t <-> rpo_eq bb s t').\n\n    Parameter equiv_rpo_equiv_4 :\n      forall bb t t', equiv t t' -> (forall s, rpo_eq bb t s <-> rpo_eq bb t' s).\n\n(** ** rpo is a preorder, and its reflexive closure is an ordering. *)\n    Parameter rpo_closure :\n      forall bb s t u, \n        (rpo bb t s -> rpo bb u t -> rpo bb u s) /\\\n        (rpo bb s t -> rpo bb t s -> False) /\\\n        (rpo bb s s -> False) /\\\n        (rpo_eq bb s t -> rpo_eq bb t s -> equiv s  t).\n\n    Parameter rpo_trans : forall bb s t u, rpo bb s t -> rpo bb t u -> rpo bb s u.\n\n(** ** Main theorem: when the precedence is well-founded, so is the rpo. *)\n    Parameter wf_rpo :  well_founded (prec P) -> forall bb, well_founded (rpo bb).\n\n(** ** RPO is compatible with the instanciation by a substitution. *)\n    Parameter equiv_subst :\n      forall s t, equiv s t -> \n        forall sigma, equiv (apply_subst sigma s) (apply_subst sigma t).\n\n    Parameter rpo_subst :\n      forall bb s t, rpo bb s t -> \n        forall sigma, rpo bb (apply_subst sigma s) (apply_subst sigma t).\n\n    Parameter rpo_eq_subst :\n      forall bb s t, rpo_eq bb s t -> \n        forall sigma, rpo_eq bb (apply_subst sigma s) (apply_subst sigma t).\n\n(** ** RPO is compatible with adding context. *)\n    Parameter equiv_add_context :\n      forall p ctx s t, equiv s t -> is_a_pos ctx p = true -> \n        equiv (replace_at_pos ctx s p) (replace_at_pos ctx t p).\n\n    Parameter rpo_add_context :\n      forall bb p ctx s t, rpo bb s t -> is_a_pos ctx p = true -> \n        rpo bb (replace_at_pos ctx s p) (replace_at_pos ctx t p).\n\n    Parameter rpo_eq_add_context :\n      forall bb p ctx s t, rpo_eq bb s t -> is_a_pos ctx p = true -> \n        rpo_eq bb (replace_at_pos ctx s p) (replace_at_pos ctx t p).\n\n    Parameter rpo_dec : forall bb t1 t2, {rpo bb t1 t2}+{~rpo bb t1 t2}.\n\nEnd S.\nEnd RPO.\n\nModule Make (T1: Term) \n(*                     (P1 : Precedence with Definition A := T1.symbol) *)\n<: RPO with Module T := T1(*  with Module P:=P1 *). \n\nModule T := T1.\nImport T1.\n\n(* Module P := P1. *)\n(* Import P. *)\n\n(** ** Definition of size-based well-founded orderings for induction.*)\nDefinition o_size s t := size s < size t.\n\nLemma wf_size :  well_founded o_size.\nProof.\ngeneralize (well_founded_ltof _ size); unfold ltof; trivial.\nDefined.\n\nDefinition size2 s := match s with (s1,s2) => (size s1, size s2) end.\nDefinition o_size2 s t := lex beq_nat lt lt (size2 s) (size2 t).\n\nLemma wf_size2 : well_founded o_size2.\nProof.\nrefine (wf_inverse_image _ _ (lex  beq_nat lt lt) size2 _);\napply wf_lex.\nexact beq_nat_ok.\napply lt_wf.\napply lt_wf.\nDefined.\n\nLemma size2_lex1 : \n forall s f l t1 t2, In s l -> o_size2 (s,t1) (Term f l,t2).\nProof.\nintros s f l t1 t2 s_in_l; unfold o_size2, size2, lex.\ngeneralize (beq_nat_ok (size s) (size (Term f l))); case (beq_nat (size s) (size (Term f l))); [intro s_eq_t | intro s_lt_t].\nabsurd (size (Term f l) < size (Term f l)); auto with arith;\ngeneralize (size_direct_subterm s (Term f l) s_in_l); rewrite s_eq_t; trivial.\napply (size_direct_subterm s (Term f l) s_in_l).\nDefined.\n\nLemma size2_lex1_bis : \n forall a f l t1 t2, o_size2 (Term f l, t1) (Term f (a::l), t2).\nProof.\nintros a f l t1 t2; unfold o_size2, size2, lex;\ngeneralize (beq_nat_ok (size (Term f l)) (size (Term f (a :: l)))); \ncase (beq_nat (size (Term f l)) (size (Term f (a :: l)))); [intro s_eq_t | intro s_lt_t].\ndo 2 rewrite size_unfold in s_eq_t; injection s_eq_t; clear s_eq_t; intro s_eq_t;\nabsurd (list_size size l < list_size size l); auto with arith;\ngeneralize (plus_le_compat_r _ _ (list_size size l) (size_ge_one a));\nrewrite <- s_eq_t; trivial.\ndo 2 rewrite size_unfold;\nsimpl; apply lt_n_S; apply lt_le_trans with (1 + list_size size l);\nauto with arith; \napply plus_le_compat_r; apply size_ge_one.\nDefined.\n\n(* Lemma size2_lex1_bis_prec_eq :  *)\n(*  forall a f g l t1 t2, prec_eq P f g -> o_size2 (Term f l, t1) (Term g (a::l), t2). *)\n(* Proof. *)\n(* intros a f g l t1 t2 f_eq_g; unfold o_size2, size2, lex. *)\n(* generalize (beq_nat_ok (size (Term f l)) (size (Term g (a :: l)))); *)\n(* case (beq_nat (size (Term f l)) (size (Term g (a :: l)))); [intro s_eq_t | intro s_lt_t]. *)\n(* do 2 rewrite size_unfold in s_eq_t; injection s_eq_t; clear s_eq_t; intro s_eq_t; *)\n(* absurd (list_size size l < list_size size l); auto with arith; *)\n(* generalize (plus_le_compat_r _ _ (list_size size l) (size_ge_one a)); *)\n(* rewrite <- s_eq_t; trivial. *)\n(* do 2 rewrite size_unfold; *)\n(* simpl; apply lt_n_S; apply lt_le_trans with (1 + list_size size l); *)\n(* auto with arith;  *)\n(* apply plus_le_compat_r; apply size_ge_one. *)\n(* Defined. *)\n\n\nLemma size2_lex2 :\n  forall t f l s, In t l -> o_size2 (s,t) (s, Term f l).\nProof.\nintros t f l s t_in_l;\nunfold o_size2, size2, lex;\ngeneralize (beq_nat_ok (size s) (size s)); case (beq_nat (size s) (size s)); [intros _ | intro s_diff_s].\napply size_direct_subterm; trivial.\napply False_rec; apply s_diff_s; reflexivity.\nDefined.\n\nLemma size2_lex2_bis :\n  forall t f l s, o_size2 (s,Term f l) (s, Term f (t :: l)).\nProof.\nintros a f l s;\nunfold o_size2, size2, lex;\ngeneralize (beq_nat_ok (size s) (size s)); case (beq_nat (size s) (size s)); [intros _ | intro s_diff_s].\ndo 2 rewrite size_unfold; apply plus_lt_compat_l; simpl.\nexact (plus_le_compat_r _ _ (list_size size l) (size_ge_one a)).\napply False_rec; apply s_diff_s; reflexivity.\nDefined.\n\nLemma o_size2_trans : transitive _ o_size2.\nProof.\nintros [x1 x2] [y1 y2] [z1 z2].\napply (lex_trans beq_nat beq_nat_ok).\nintros n m n_lt_m m_lt_n;\ngeneralize (lt_asym n m n_lt_m m_lt_n); contradiction.\nintros n1 n2 n3; apply lt_trans.\nintros n1 n2 n3; apply lt_trans.\nQed.\n\nDefinition size3 s := match s with (s1,s2) => (size s1, size2 s2) end.\nDefinition o_size3 s t := \n  lex beq_nat lt (lex beq_nat lt lt) (size3 s) (size3 t).\n\nLemma wf_size3 : well_founded o_size3.\nProof.\nrefine (wf_inverse_image _ _ \n  (lex  beq_nat lt (lex  beq_nat lt lt)) size3 _).\napply wf_lex; \n[ exact beq_nat_ok \n| apply lt_wf \n| apply wf_lex; [ exact beq_nat_ok | apply lt_wf | apply lt_wf ]].\nDefined.\n\nLemma size3_lex1 : \n forall s f l t1 u1 t2 u2, In s l -> o_size3 (s,(t1,u1)) (Term f l,(t2,u2)).\nProof.\nintros s f l t1 u1 t2 u2 s_in_l; unfold o_size3, size3, size2, lex.\ngeneralize (beq_nat_ok (size s) (size (Term f l))); case (beq_nat (size s) (size (Term f l))); [intro s_eq_t | intro s_lt_t].\nabsurd (size (Term f l) < size (Term f l)); auto with arith;\ngeneralize (size_direct_subterm s (Term f l) s_in_l); rewrite s_eq_t; trivial.\napply (size_direct_subterm s (Term f l) s_in_l).\nDefined.\n\nLemma size3_lex1_bis : \n forall a f l t1 u1 t2 u2, o_size3 (Term f l,(t1,u1)) (Term f (a::l),(t2,u2)).\nProof.\nintros a f l t1 u1 t2 u2; unfold o_size3, size3, lex;\ngeneralize (beq_nat_ok (size (Term f l)) (size (Term f (a :: l)))); \ncase (beq_nat (size (Term f l)) (size (Term f (a :: l)))); [intro s_eq_t | intro s_lt_t].\ndo 2 rewrite size_unfold in s_eq_t; injection s_eq_t; clear s_eq_t; intro s_eq_t;\nabsurd (list_size size l < list_size size l); auto with arith;\ngeneralize (plus_le_compat_r _ _ (list_size size l) (size_ge_one a));\nrewrite <- s_eq_t; trivial.\ndo 2 rewrite size_unfold;\nsimpl; apply lt_n_S; apply lt_le_trans with (1 + list_size size l);\nauto with arith; \napply plus_le_compat_r; apply size_ge_one.\nDefined.\n\nLemma size3_lex2 :\n  forall t f l s u1 u2, In t l -> o_size3 (s,(t,u1)) (s,(Term f l, u2)).\nProof.\nintros t f l s u1 u2 t_in_l;\nunfold o_size3, size3, size2, lex.\ngeneralize (beq_nat_ok (size s) (size s)); case (beq_nat (size s) (size s)); [intros _ | intro s_diff_s].\ngeneralize (beq_nat_ok (size t) (size (Term f l))); case (beq_nat (size t) (size (Term f l))); [intro t_eq_fl | intro t_lt_fl].\nabsurd (size (Term f l) < size (Term f l)); auto with arith;\ngeneralize (size_direct_subterm t (Term f l) t_in_l); rewrite t_eq_fl; trivial.\napply (size_direct_subterm t (Term f l) t_in_l).\napply False_rec; apply s_diff_s; reflexivity.\nDefined.\n\nLemma size3_lex3 :\n  forall u f l s t, In u l -> o_size3 (s,(t,u)) (s,(t,Term f l)).\nProof.\nintros u f l s t u_in_l;\nunfold o_size3, size3, size2, lex;\ngeneralize (beq_nat_ok (size s) (size s)); case (beq_nat (size s) (size s)); [intros _ | intro s_diff_s].\ngeneralize (beq_nat_ok (size t) (size t)); case (beq_nat (size t) (size t)); [intros _ | intro t_diff_t].\napply (size_direct_subterm u (Term f l) u_in_l).\napply False_rec; apply t_diff_t; reflexivity.\napply False_rec; apply s_diff_s; reflexivity.\nDefined.\n\nLemma o_size3_trans : transitive _ o_size3.\nProof.\nintros [x1 x2] [y1 y2] [z1 z2].\napply (@lex_trans _ _ beq_nat lt (lex beq_nat lt lt) beq_nat_ok).\nintros n m n_lt_m m_lt_n;\ngeneralize (lt_asym n m n_lt_m m_lt_n); contradiction.\nintros n1 n2 n3; apply lt_trans.\napply lex_trans.\nexact beq_nat_ok.\nintros n m n_lt_m m_lt_n;\ngeneralize (lt_asym n m n_lt_m m_lt_n); contradiction.\nintros n1 n2 n3; apply lt_trans.\nintros n1 n2 n3; apply lt_trans.\nQed.\n\n(** ** Definition of rpo.*)\n(** *** Equivalence modulo rpo *)\nSection S.\nVariable Prec: Precedence T1.symbol.\n(* Parameter prec_eq_transitive: transitive T1.symbol (prec_eq Prec). *)\n(* Parameter prec_bool : T1.symbol -> T1.symbol -> bool. *)\n(* Parameter prec_bool_ok : forall a1 a2, match prec_bool Prec a1 a2 with true => prec Prec a1 a2 | false => ~prec Prec a1 a2 end. *)\n(* Parameter prec_antisym : forall s, prec Prec s s -> False. *)\n(* Parameter prec_transitive : transitive T1.symbol (prec Prec). *)\n\nInductive equiv : term -> term -> Prop :=\n  | Eq : forall t, equiv t t\n  | Eq_lex : \n     forall f g l1 l2, status Prec f = Lex -> status Prec g = Lex -> prec_eq Prec f g -> equiv_list_lex l1 l2 -> \n     equiv (Term f  l1) (Term g l2) \n  | Eq_mul :\n     forall f g l1 l2,  status Prec f = Mul -> status Prec g = Mul -> prec_eq Prec f g -> permut0 equiv l1 l2 ->\n     equiv (Term f l1) (Term g l2)\n\nwith equiv_list_lex : list term -> list term -> Prop :=\n   | Eq_list_nil : equiv_list_lex nil nil\n   | Eq_list_cons : \n       forall t1 t2 l1 l2, equiv t1 t2 -> equiv_list_lex l1 l2 ->\n       equiv_list_lex (t1 :: l1) (t2 :: l2).\n\nLemma equiv_same_top :\n  forall f g l l', equiv (Term f l) (Term g l') -> prec_eq Prec f g.\nProof.\nintros f g l l' H; inversion H; subst; trivial.\napply prec_eq_refl.\nQed.\n\nLemma equiv_list_lex_same_length :\n  forall l1 l2, equiv_list_lex l1 l2 -> length l1 = length l2.\nProof.\nintros l1; induction l1 as [ | t1 l1]; intros l2 l1_eq_l2; \ninversion l1_eq_l2 as [ | s1 s2 l1' l2' _ l1'_eq_l2']; subst; trivial.\nsimpl; rewrite (IHl1 l2'); trivial.\nQed.\n\nLemma equiv_same_length :\n  forall f1 f2 l1 l2, equiv (Term f1 l1) (Term f2 l2) -> length l1 = length l2.\nProof.\nintros f1 f2 l1 l2 t1_eq_t2. \ninversion t1_eq_t2.  \ntrivial.  \napply equiv_list_lex_same_length; assumption.  \napply (@permut_length _ equiv); trivial.\nQed.\n\nLemma equiv_same_size :\n  forall t t', equiv t t' -> size t = size t'.\nProof.\nintros t; pattern t; apply term_rec2; clear t.\nintro n; induction n as [ | n]; intros t1 St1 t2 t1_eq_t2.\nabsurd (1 <= 0); auto with arith; apply le_trans with (size t1); trivial;\napply size_ge_one.\ninversion t1_eq_t2 as [ | f g l1' l2' Sf Sg prec_eq_f_g l1_eq_l2 | f g l1' l2' Sf Sg prec_eq_f_g P];  \nsubst.\ntrivial.\n(* Lex case *)\ndo 2 rewrite size_unfold; apply (f_equal (fun n => 1 + n)).\ngeneralize l2' l1_eq_l2; clear l2' l1_eq_l2 t1_eq_t2.\ninduction l1' as [ | t1 l1]; intros l2 l1_eq_l2; \ninversion l1_eq_l2 as [ | s1 s2 l1' l2' s1_eq_s2 l1'_eq_l2']; subst; trivial.\nsimpl.\nassert (St1' : size t1 <= n).\napply le_S_n; apply le_trans with (size (Term f (t1 :: l1))); trivial.\napply size_direct_subterm; left; trivial.\nrewrite (IHn t1 St1' s2); trivial. \nassert (Sl1 : size (Term f l1) <= S n).\napply le_trans with (size (Term f (t1 :: l1))); trivial.\ndo 2 rewrite size_unfold.\nsimpl; apply le_n_S.\napply (plus_le_compat_r 0 (size t1) (list_size size l1)).\napply lt_le_weak; apply (size_ge_one t1).\nrewrite (IHl1 Sl1 l2'); trivial.\n(* Mul case *)\nsubst; do 2 rewrite size_unfold; apply (f_equal (fun n => 1 + n)).\napply (@permut_size _ _ equiv); trivial.\nintros a a' a_in_l1 _ a_eq_a'; apply IHn; trivial.\napply le_S_n.\napply le_trans with (size (Term f l1')); trivial.\napply size_direct_subterm; trivial.\nQed.\n\nLemma equiv_in_list : \n    forall f g (f_stat : status Prec f = Lex) (g_stat: status Prec g = Lex) l1 l2, length l1 = length l2 -> prec_eq Prec f g ->\n      (forall t1 t2, In (t1, t2) (combine l1 l2) -> equiv  t1  t2) -> \n      equiv (Term f l1) (Term g l2).\nProof.\nintros f g f_stat g_stat l1 l2 L prec_eq_f_g E.  apply (Eq_lex _ _ f_stat g_stat prec_eq_f_g).\nclear f f_stat prec_eq_f_g; revert l1 l2 L E; fix equiv_in_list 1; intro l1; case l1; clear l1. intros l2; case l2; clear l2.\nintros _ _; apply Eq_list_nil.\nintros a2 l2 L _; discriminate.\nintros a1 l1 l2; case l2; clear l2.\nintro L; discriminate.\nintros a2 l2 L E; apply Eq_list_cons.\napply E; left; apply refl_equal.\napply (equiv_in_list l1 l2).\ninjection L; intros; assumption.\nintros t1 t2 H; apply E; right; assumption.\nQed.\n\n(* equiv is actually an equivalence *)\nLemma equiv_equiv  : equivalence term equiv.\nProof.\nsplit.\n(* Reflexivity *)\nintro t; apply Eq.\n(* Transitivity *)\nintros t1; pattern t1; apply term_rec3.\n(* 1/3 variable case *)\nintros v t2 t3 t1_eq_t2 t2_eq_t3; inversion t1_eq_t2; subst; trivial.\n(* 1/2 compound case *)\nintros f l1 E_l1 t2 t3 t1_eq_t2 t2_eq_t3; \ninversion t1_eq_t2 as [ | f' g' l1' l2 Sf Sg eq_f_g l1_eq_l2 H2 H' | f' g' l1' l2 Sf Sg eq_f_g P]; subst; trivial;\ninversion t2_eq_t3 as [ | f' g'' l2' l3 Sf' Sg' eq_f_g' l2_eq_l3 H2 H'' | f' g'' l2' l3 Sf' Sg' eq_f_g' P' ]; subst; trivial.\n(* 1/5 Lex case *)\napply Eq_lex; trivial.\napply prec_eq_transitive with g'; trivial.\ngeneralize l2 l3 l1_eq_l2 l2_eq_l3;\nclear t1_eq_t2 t2_eq_t3 l2 l3 l1_eq_l2 l2_eq_l3;\ninduction l1 as [ |s1 l1]; intros l2 l3 l1_eq_l2 l2_eq_l3.\ninversion l1_eq_l2; subst; trivial.\ninversion l1_eq_l2 as [ | s1' s2 l1' l2' s1_eq_s2 l1'_eq_l2']; subst.\ninversion l2_eq_l3 as [ | s2' s3 l2'' l3' s2_eq_s3 l2''_eq_l3']; subst.\napply Eq_list_cons.\napply E_l1 with s2; trivial; left; trivial.\napply IHl1 with l2'; trivial.\nintros t t_in_l1; apply E_l1; right; trivial.\n(* 1/4 absurd case *)\nrewrite Sg in Sf'; discriminate.\n(* 1/3 absurd case *)\nrewrite Sg in Sf'; discriminate.\n(* 1/2 Mul case *)\napply Eq_mul; trivial.\napply prec_eq_transitive with g'; trivial.\napply permut_trans with l2; trivial.\nintros a b c a_in_l1 _ _; apply E_l1; trivial.\n(* Symmetry *)\nintros t1; pattern t1; apply term_rec3; clear t1.\nintros v t2 t1_eq_t2; inversion t1_eq_t2; subst; trivial.\nintros f l1 IHl t2 t1_eq_t2; \ninversion t1_eq_t2 as \n  [ \n  | f' g' l1' l2 Sf Sg preceq_f_g l1_eq_l2 \n  | f' g' l1' l2 Sf Sg preceq_f_g P]; clear t1_eq_t2; subst.\napply Eq.\napply Eq_lex; trivial.\napply prec_eq_sym. trivial.\ngeneralize l2 l1_eq_l2; clear l2 l1_eq_l2; \ninduction l1 as [ | t1 l1]; intros l2 l1_eq_l2;\ninversion l1_eq_l2 as [ | s1 s2 l1' l2' s1_eq_s2 l1'_eq_l2']; subst; trivial.\napply Eq_list_cons.\napply IHl; trivial; left; trivial.\napply IHl1; trivial.\nintros t t_in_l1; apply IHl; right; trivial.\napply Eq_mul; trivial.\napply prec_eq_sym. trivial.\napply permut_sym; trivial.\nintros a b a_in_l1 _; apply IHl; trivial.\nQed.\n\n  Add Relation term equiv \n  reflexivity proved by (Relation_Definitions.equiv_refl _ _ equiv_equiv)\n    symmetry proved by (Relation_Definitions.equiv_sym _ _ equiv_equiv)\n      transitivity proved by (Relation_Definitions.equiv_trans _ _ equiv_equiv) as EQUIV_RPO.\n\n\nDefinition equiv_bool_F := \n(fun (equiv_bool : term -> term -> bool) (t1 t2 : term) =>\nmatch t1, t2 with\n| Var v1, Var v2 => X.eq_bool v1 v2\n| Var _, Term _ _ => false\n| Term _ _, Var _ => false\n| Term f1 l1, Term f2 l2 =>\n    if prec_eq_bool Prec f1 f2\n    then\n    match status Prec f1 with\n    | Lex => \n         let equiv_lex_bool :=\n              fix equiv_lex_bool (kk1 kk2 : list term) {struct kk1} :  bool :=  \n               match kk1 with\n               | nil => match kk2 with | nil => true | _ :: _=> false end\n               | t1 :: k1 => \n                     match kk2 with \n                       |  nil => false \n                       | t2 :: k2=> (equiv_bool t1 t2) && (equiv_lex_bool k1 k2)\n                       end\n                 end in\n              (equiv_lex_bool l1 l2)\n    | Mul => \n       let equiv_mult_bool :=\n              (fix equiv_mult_bool (kk1 kk2 : list term) {struct kk1} :  bool :=  \n               (match kk1 with\n               | nil => match kk2 with nil => true | _ :: _=> false end\n               | t1 :: k1 => \n                     match remove equiv_bool t1 kk2 with \n                           None => false \n                         | Some k2 => equiv_mult_bool k1 k2 end\n                         end)) in\n              (equiv_mult_bool l1 l2)\n    end\n    else false\nend) : (term -> term -> bool) -> term -> term -> bool.\n\n\nDefinition equiv_bool_terminate :\nforall t1 t2 : term,\n       {v : bool |  forall k : nat, (size t1) <= k ->\n         forall def : term -> term -> bool,\n         iter (term -> term -> bool) k equiv_bool_F def t1 t2 = v}.\nProof.\nintro t1.\nassert (Acc_t1 := well_founded_ltof term size t1).\ninduction Acc_t1 as [t1 Acc_t1 IHAcc].\nrevert Acc_t1 IHAcc; case t1; clear t1; [intro v1 | intros f1 l1]; \n(intros Acc_t1 IHAcc t2; case t2; clear t2; [intro v2 | intros f2 l2]).\n\nexists (X.eq_bool v1 v2); intros [ | p] p_lt_k def.\napply False_ind; exact (gt_irrefl 0 p_lt_k).\nexact (refl_equal ).\n\nexists false; intros [ | p] p_lt_k def.\napply False_ind; exact (gt_irrefl 0 p_lt_k).\nexact refl_equal.\n\nexists false; intros [ | p] p_lt_k def.\napply False_ind; exact (le_Sn_O _ p_lt_k).\nexact refl_equal.\n\nrewrite size_unfold.\nassert ({v : bool |\n  forall k : nat,\n  list_size size l1 <= k ->\n  forall def : term -> term -> bool,\n  iter (term -> term -> bool) (S k) equiv_bool_F def (Term f1 l1) (Term f2 l2) = v}).\nunfold iter; simpl.\ncase (prec_eq_bool Prec f1 f2).\nassert (IH : forall t1 : term, In t1 l1 ->\n     forall t2 : term,\n     {v : bool |\n       forall k : nat,\n       size t1 <= k ->\n       forall def : term -> term -> bool,\n       iter (term -> term -> bool) k equiv_bool_F def t1 t2 = v}).\nintros t1 t1_in_l1; exact (IHAcc t1 (size_direct_subterm t1 (Term f1 l1) t1_in_l1)).\ncase (status Prec f1).\nclear IHAcc Acc_t1 f2; revert l1 IH l2; fix equiv_lex_bool 1.\nintros l1; case l1.\nintros _ l2; case l2.\nexists true; intros k p_lt_k def; exact refl_equal.\nexists false; intros k p_lt_k def; exact refl_equal.\nintros a1 k1 IHl1 l2; case l2.\nexists false; intros k p_lt_k def; exact refl_equal.\nintros a2 k2; case (equiv_lex_bool k1 (tail_set _ IHl1) k2); intros bl IH'.\ncase (IHl1 a1 (or_introl _ refl_equal) a2); intros ba IH''.\nexists (ba && bl); intros k p_le_k def.\nassert (pa_lt_k : size a1 <= k).\napply le_trans with (list_size size (a1 :: k1)); [apply le_plus_l | exact p_le_k].\nrewrite (IH'' k pa_lt_k).\nassert (pl_le_k : list_size size k1 <= k).\napply le_trans with (list_size size (a1 :: k1)); [apply le_plus_r | exact p_le_k].\nrewrite (IH' k pl_le_k def).\nreflexivity.\n\nclear IHAcc Acc_t1 f2.\nrevert l1 IH l2; fix IHl1 1.\nintro l1; case l1; clear l1.\nintros _ l2; case l2.\nexists true; intros k p_lt_k def; exact refl_equal.\nexists false; intros k p_lt_k def; exact refl_equal.\nintros a1 l1 IH l2.\nassert (Hrem : {ok : option (list term) |\n                             forall k : nat, list_size size (a1 :: l1) <= k ->\n                             forall def : term -> term -> bool,\n                             remove (iter _ k equiv_bool_F def) a1 l2 = ok}).\nrevert l2; fix IHl2 1.\nintro l2; case l2; clear l2.\nexists (@None (list term)); intro k; case k; clear k.\nintro L; apply False_rec.\napply (le_Sn_O _ (le_trans 1 _ 0 (size_ge_one a1) (le_trans (size a1) _ 0 (le_plus_l _ _) L))).\nintros k _ def; reflexivity.\nintros a2 l2;\ncase (IH a1 (or_introl _ refl_equal) a2); intro v; case v; intro Ha1.\nexists (Some l2); intros k L def; simpl; rewrite Ha1.\nreflexivity.\napply le_trans with (list_size size (a1 :: l1)); [apply le_plus_l | apply L].\ncase (IHl2 l2); clear IHl2; intro ok; case ok; clear ok.\nintros k2 IHl2; exists (Some (a2 :: k2)); intros k L def; simpl.\nrewrite Ha1.\nrewrite IHl2.\nreflexivity.\napply L.\napply le_trans with (list_size size (a1 :: l1)); [apply le_plus_l | apply L].\nintro IHl2; exists (@None (list term)); intros k L def; simpl.\nrewrite Ha1.\nrewrite IHl2.\nreflexivity.\napply L.\napply le_trans with (list_size size (a1 :: l1)); [apply le_plus_l | apply L].\ncase Hrem; clear Hrem; intro ok; case ok; clear ok.\nintros k2 Hrem.\ncase (IHl1 _ (tail_set _ IH) k2); intros v Hl1; exists v; intros k L def.\nrewrite (Hrem k L).\nassert (l1_le_k : list_size size l1 <= k).\nrefine (le_trans _ _ _ _ L); apply le_plus_r.\nrewrite (Hl1 k l1_le_k def).\nreflexivity.\nintro Hrem; exists false; intros k L def.\nrewrite (Hrem k L).\nreflexivity.\n\nexists false; intros _ _ _; exact refl_equal.\n\ncase H; clear H; intros v H; exists v; intro k; case k; clear k.\nintro L; apply False_rec.\napply (le_Sn_O _ (le_trans 1 _ 0 (le_plus_l _ _) L)).\nintros k L def; rewrite (H k).\nreflexivity.\napply (le_S_n  _ _ L).\nDefined.\n\nDefinition equiv_bool := fun t1 t2 => let (v,_) := equiv_bool_terminate t1 t2 in v.\n\nLemma equiv_bool_equation :\n  forall t1 t2, equiv_bool t1 t2 = \nmatch t1, t2 with\n| Var v1, Var v2 => X.eq_bool v1 v2\n| Var _, Term _ _ => false\n| Term _ _, Var _ => false\n| Term f1 l1, Term f2 l2 =>\n    if prec_eq_bool Prec f1 f2\n    then\n    match status Prec f1 with\n    | Lex => \n         let equiv_lex_bool :=\n              (fix equiv_lex_bool (kk1 kk2 : list term) {struct kk1} :  bool :=  \n               (match kk1 with\n               | nil => match kk2 with nil => true | _ :: _=> false end\n               | t1 :: k1 => \n                     match kk2 with \n                         nil => false \n                       | t2 :: k2=> (equiv_bool t1 t2) && (equiv_lex_bool k1 k2)\n                       end\n                 end)) in\n              (equiv_lex_bool l1 l2)\n    | Mul => \n       let equiv_mult_bool :=\n              (fix equiv_mult_bool (kk1 kk2 : list term) {struct kk1} :  bool :=  \n               (match kk1 with\n               | nil => match kk2 with nil => true | _ :: _=> false end\n               | t1 :: k1 => \n                     match remove equiv_bool t1 kk2 with \n                           None => false \n                         | Some k2 => equiv_mult_bool k1 k2 end\n                         end)) in\n              (equiv_mult_bool l1 l2)\n    end\n    else false\nend.\nProof.\nassert (H : forall t1 t2 k, size t1 <= k -> iter (term -> term -> bool) k equiv_bool_F equiv_bool t1 t2 = equiv_bool t1 t2).\nintros t1 t2 k L; unfold equiv_bool at 2; generalize (equiv_bool_terminate t1 t2).\nintro H; case H; clear H; intros v H; apply H; apply L.\nintro t1; pattern t1; apply term_rec3; clear t1.\nintros v1 [v2 | f2 l2]; reflexivity.\nintros f1 l1 IH [v2 | f2 l2].\nreflexivity.\nrewrite <- (H (Term f1 l1) (Term f2 l2) _ (le_n _)). rewrite size_unfold. simpl.\ncase (prec_eq_bool Prec f1 f2); [idtac | reflexivity].\ncase (status Prec f1); clear f1.\nassert (H' : forall l1 f1 f2, (forall t1, In t1 l1 -> forall t2, f1 t1 t2 = f2 t1 t2) -> forall l2,\n                 (fix equiv_lex_bool (kk1 kk2 : list term) : bool :=\n                 match kk1 with\n                 | nil => match kk2 with\n                 | nil => true\n                 | _ :: _ => false\n                 end\n                 | t1 :: k1 =>\n                 match kk2 with\n                 | nil => false\n                 | t2 :: k2 => f1 t1 t2 && equiv_lex_bool k1 k2\n       end\n   end) l1 l2 =\n(fix equiv_lex_bool (kk1 kk2 : list term) : bool :=\n                 match kk1 with\n                 | nil => match kk2 with\n                 | nil => true\n                 | _ :: _ => false\n                 end\n                 | t1 :: k1 =>\n                 match kk2 with\n                 | nil => false\n                 | t2 :: k2 => f2 t1 t2 && equiv_lex_bool k1 k2\n       end\n   end) l1 l2).\nclear l1 l2 IH; intro l1; induction l1 as [ | a1 l1]; intros g1 g2 IH [ | a2 l2].\nreflexivity.\nreflexivity.\nreflexivity.\napply f_equal2.\napply IH; left; reflexivity.\napply (IHl1 g1 g2 (tail_prop _ IH) l2).\nrefine (H' l1 _ _ _ l2); clear H'.\nintros t1 t1_in_l1 t2; apply H.\ngeneralize (size_direct_subterm t1 (Term f2 l1) t1_in_l1).\nrewrite (size_unfold (Term f2 l1)).\nsimpl; intro L; apply (le_S_n _ _ L).\nassert (H' : forall l1 f1 f2, (forall t1, In t1 l1 -> forall t2, f1 t1 t2 = f2 t1 t2) -> forall l2,\n                 (fix equiv_mult_bool (kk1 kk2 : list term) : bool :=\n   match kk1 with\n   | nil => match kk2 with\n           | nil => true\n           | _ :: _ => false\n           end\n   | t1 :: k1 =>\n       match\n         remove f1 t1 kk2\n       with\n       | Some k2 => equiv_mult_bool k1 k2\n       | None => false\n       end\n   end) l1 l2 =\n(fix equiv_mult_bool (kk1 kk2 : list term) : bool :=\n   match kk1 with\n   | nil => match kk2 with\n           | nil => true\n           | _ :: _ => false\n           end\n   | t1 :: k1 =>\n       match remove f2 t1 kk2 with\n       | Some k2 => equiv_mult_bool k1 k2\n       | None => false\n       end\n   end) l1 l2).\nclear l1 l2 IH; intro l1; induction l1 as [ | a1 l1]; intros g1 g2 IH l2.\nreflexivity.\nassert (H' : forall f1 f2, (forall t2, f1 a1 t2 = f2 a1 t2) -> forall l2, remove f1 a1 l2 = remove f2 a1 l2).\nclear l1 l2 g1 g2 IH IHl1; intros g1 g2 IH; induction l2 as [ | a2 l2].\nreflexivity.\nsimpl; rewrite (IH a2); rewrite IHl2; reflexivity.\nrewrite (H' g1 g2 (IH a1 (or_introl _ refl_equal))).\ncase (remove g2 a1 l2).\nintro k2; apply (IHl1 g1 g2 (tail_prop _ IH)).\nreflexivity.\nrefine (H' l1 _ _ _ l2).\nintros t1 t1_in_l1 t2; apply H.\ngeneralize (size_direct_subterm t1 (Term f2 l1) t1_in_l1).\nrewrite (size_unfold (Term f2 l1)).\nsimpl; intro L; apply (le_S_n _ _ L).\nDefined.\n\nLemma equiv_bool_ok : forall t1 t2, match equiv_bool t1 t2 with true => equiv t1 t2 | false => ~equiv t1 t2 end.\nProof.\nintros t1; pattern t1; apply term_rec3; clear t1.\nintros v1 t2; case t2; clear t2.\nintro v2; rewrite equiv_bool_equation; generalize (X.eq_bool_ok v1 v2); case (X.eq_bool v1 v2).\nintro v1_eq_v2; rewrite v1_eq_v2; apply Eq.\nintros v1_diff_v2 v1_eq_v2; apply v1_diff_v2; inversion v1_eq_v2; reflexivity.\nintros f2 l2; rewrite equiv_bool_equation; intro t1_eq_t2; inversion t1_eq_t2.\nintros f1 l1 IH t2; case t2; clear t2.\nintros v2; rewrite equiv_bool_equation; intro t1_eq_t2; inversion t1_eq_t2.\nintros f2 l2; rewrite equiv_bool_equation.\ncase_eq (prec_eq_bool Prec f1 f2).\nintro f1_eq_f2; case_eq (status Prec f1).\nintro Lex_f1; simpl.\nassert (H : if (fix equiv_lex_bool (kk1 kk2 : list term) : bool :=\n      match kk1 with\n      | nil => match kk2 with\n              | nil => true\n              | _ :: _ => false\n              end\n      | t1 :: k1 =>\n          match kk2 with\n          | nil => false\n          | t2 :: k2 => equiv_bool t1 t2 && equiv_lex_bool k1 k2\n          end\n      end) l1 l2\n   then equiv_list_lex l1 l2 else ~equiv_list_lex l1 l2).\nrevert l2; induction l1 as [ | a1 l1]; intro l2; case l2; clear l2.\napply Eq_list_nil.\nintros a2 l2; simpl; intro l1_eq_l2; inversion l1_eq_l2.\nsimpl; intro l1_eq_l2; inversion l1_eq_l2.\nintros a2 l2; simpl; generalize (IH a1 (or_introl _ (refl_equal _)) a2).\ncase (equiv_bool a1 a2).\nintro a1_eq_a2; generalize (IHl1 (tail_prop _ IH) l2).\nsimpl.\ncase ((fix equiv_lex_bool (kk1 kk2 : list term) : bool :=\n       match kk1 with\n       | nil => match kk2 with\n               | nil => true\n               | _ :: _ => false\n               end\n       | t1 :: k1 =>\n           match kk2 with\n           | nil => false\n           | t3 :: k2 => equiv_bool t1 t3 && equiv_lex_bool k1 k2\n           end\n       end) l1 l2).\nintro l1_eq_l2; apply Eq_list_cons; assumption.\nintros l1_diff_l2 l1_eq_l2; apply l1_diff_l2; inversion l1_eq_l2; assumption.\nintros a1_diff_a2 l1_eq_l2; apply a1_diff_a2; inversion l1_eq_l2; assumption.\nrevert H; simpl.\ncase ((fix equiv_lex_bool (kk1 kk2 : list term) : bool :=\n       match kk1 with\n       | nil => match kk2 with\n               | nil => true\n               | _ :: _ => false\n               end\n       | t1 :: k1 =>\n           match kk2 with\n           | nil => false\n           | t3 :: k2 => equiv_bool t1 t3 && equiv_lex_bool k1 k2\n           end\n       end) l1 l2).\nintro l1_eq_l2.  apply Eq_lex; trivial. assert (H2:= prec_eq_bool_ok Prec). assert (H2':= H2 f1 f2). rewrite f1_eq_f2 in H2'.  assert (H5:= prec_eq_status Prec f1 f2). assert (H6: status Prec f1 = status Prec f2). apply H5; trivial. rewrite <- H6. trivial.\nassert (H2:= prec_eq_bool_ok Prec). assert (H2':= (H2 f1 f2)). rewrite f1_eq_f2 in H2'. trivial.\nintros l1_diff_l2 t1_eq_t2; inversion t1_eq_t2; subst l2.\napply l1_diff_l2; generalize l1; intro l; induction l as [ | a l].\napply Eq_list_nil.\napply Eq_list_cons; [apply Eq | assumption].\napply l1_diff_l2; assumption.\nsubst f2; rewrite Lex_f1 in H3. discriminate.\nintro Mul_f1; simpl.\nassert (H : if (fix equiv_mult_bool (kk1 kk2 : list term) : bool :=\n      match kk1 with\n      | nil => match kk2 with\n              | nil => true\n              | _ :: _ => false\n              end\n      | t1 :: k1 =>\n          match remove equiv_bool t1 kk2 with\n          | Some k2 => equiv_mult_bool k1 k2\n          | None => false\n          end\n      end) l1 l2\n    then permut0 equiv l1 l2 else ~permut0 equiv l1 l2).\nrevert l2; induction l1 as [ | a1 l1].\nintro l2; case l2; clear l2.\nsimpl; apply Pnil.\nintros a2 l2; simpl; intro t1_eq_t2; inversion t1_eq_t2.\nassert (R : forall l2, match remove equiv_bool a1 l2 with\n | Some _ =>\n     {a2 : term & \n     {l2' : list term & \n     {l2'' : list term |\n     equiv a1 a2 /\\\n     l2 = l2' ++ a2 :: l2'' /\\ remove equiv_bool a1 l2 = Some (l2' ++ l2'')}}}\n | None => forall a2, equiv a1 a2 -> ~ In a2  l2\n end).\nintro l2; induction l2 as [ | a2 l2].\nintros a2 a1_eq_a2 F; assumption.\nrewrite remove_equation.\ngeneralize (IH a1 (or_introl _ (refl_equal _)) a2); case (equiv_bool a1 a2).\nintro a1_eq_a2; exists a2; exists (@nil term); exists l2; repeat split; assumption.\nintro a1_diff_a2; revert IHl2; case (remove equiv_bool a1 l2).\nintros k2 [a1' [l2' [l2'' [H1 [H2 H3]]]]]; exists a1'; exists (a2 :: l2'); exists l2''; repeat split.\nassumption.\nsimpl; apply f_equal; assumption.\nsimpl; do 2 apply f_equal; injection H3; intros; assumption.\nsimpl; intros a1_not_in_l2; intros a a_eq_a1 [a_eq_a2 | a_in_l2].\nsubst a; apply a1_diff_a2; assumption.\napply (a1_not_in_l2 a a_eq_a1 a_in_l2).\nintro l2; generalize (R l2); case (remove equiv_bool a1 l2).\nintros k2 [a2 [k2' [k2'' [H1 [H2 H3]]]]].\ngeneralize (IHl1 (tail_prop _ IH) k2); simpl.\ninjection H3; clear H3; intro H3; \ncase ((fix equiv_mult_bool (kk1 kk2 : list term) : bool :=\n       match kk1 with\n       | nil => match kk2 with\n               | nil => true\n               | _ :: _ => false\n               end\n       | t1 :: k1 =>\n           match remove equiv_bool t1 kk2 with\n           | Some k3 => equiv_mult_bool k1 k3\n           | None => false\n           end\n       end) l1 k2).\nintro P; subst l2 k2; apply Pcons; assumption.\nintros not_P P; subst l2 k2; apply not_P.\napply (@permut_cons_inside term term equiv) with a1 a2.\nintros u3 u1 u4 u2 _ _ _ _ H31 H41 H42; transitivity u1.\nassumption.\ntransitivity u4.\nsymmetry; assumption.\nassumption.\nassumption.\nassumption.\nintros H P; inversion P as [ | a1' a2 l1' l2' l2'' a1_eq_a2 P'].\napply (H a2 a1_eq_a2); subst l2; apply in_or_app; right; left; reflexivity.\nrevert H; case ((fix equiv_mult_bool (kk1 kk2 : list term) : bool :=\n      match kk1 with\n      | nil => match kk2 with\n              | nil => true\n              | _ :: _ => false\n              end\n      | t1 :: k1 =>\n          match remove equiv_bool t1 kk2 with\n          | Some k2 => equiv_mult_bool k1 k2\n          | None => false\n          end\n      end) l1 l2).\nintro P.  apply Eq_mul. assumption.\n assert (H2:= prec_eq_bool_ok Prec). assert (H2':= H2 f1 f2). rewrite f1_eq_f2 in H2'. assert (H6:= prec_eq_status Prec f1 f2); trivial. assert (H7: status Prec f1 = status Prec f2). apply H6. trivial.  rewrite <- H7. trivial. \n assert (H2:= prec_eq_bool_ok Prec). assert (H2':= H2 f1 f2). rewrite f1_eq_f2 in H2'. trivial.\ntrivial. \nintros not_P t1_eq_t2.\ninversion t1_eq_t2. subst l2.\napply not_P; apply permut_refl; intros; reflexivity.\nrewrite Mul_f1 in H3; discriminate.\napply not_P; assumption.\nintros f1_diff_f2 t1_eq_t2. inversion t1_eq_t2. rewrite H1 in f1_diff_f2. assert (H3:= prec_eq_bool_ok Prec). assert (H3':= H3 f2 f2).  rewrite f1_diff_f2 in H3'. contradict H3'.   apply prec_eq_refl. trivial.\nassert (H8:= prec_eq_bool_ok Prec). assert (H8':= H8 f1 f2).  rewrite f1_diff_f2 in H8'. contradict H8'. trivial. \nassert (H8:= prec_eq_bool_ok Prec). assert (H8':= H8 f1 f2).  rewrite f1_diff_f2 in H8'. contradict H8'.  trivial. \nDefined.\n\nLemma equiv_dec :\n  forall t1 t2, {equiv t1 t2}+{~equiv t1 t2}.\nProof.\nintros t1 t2; generalize (equiv_bool_ok t1 t2); case (equiv_bool t1 t2).\nleft; assumption.\nright; assumption.\nDefined.\n\n(*\nModule Term_equiv_dec : \n   decidable_set.ES with Definition A:= term \n                             with Definition eq_A := equiv\n                             with Definition eq_bool := equiv_bool\n                             with Definition eq_bool_ok := equiv_bool_ok.\n                             \nDefinition A := term.\nDefinition eq_A := equiv.\nDefinition eq_proof := equiv_equiv.\nDefinition eq_bool := equiv_bool.\nDefinition eq_bool_ok := equiv_bool_ok.\n\n  Add Relation A eq_A \n  reflexivity proved by (Relation_Definitions.equiv_refl _ _ eq_proof)\n    symmetry proved by (Relation_Definitions.equiv_sym _ _ eq_proof)\n      transitivity proved by (Relation_Definitions.equiv_trans _ _ eq_proof) as EQA.\n\nEnd Term_equiv_dec.\n\nModule Import LP := list_permut.Make (Term_equiv_dec).\n*)\n\nLemma term_rec3_mem : \n   forall P : term -> Type,\n       (forall v : variable, P (Var v)) ->\n       (forall (f : symbol) (l : list term),\n        (forall t : term, mem equiv t l -> P t) -> P (Term f l)) ->\n       forall t : term, P t.\nProof.\nintros P Hvar Hterm. \napply term_rec2; induction n; intros t Size_t.\nabsurd (1 <= 0); auto with arith; \napply le_trans with (size t); trivial; apply size_ge_one.\ndestruct t as [ x | f l ]; trivial;\napply Hterm; intros; apply IHn;\napply lt_n_Sm_le.\napply lt_le_trans with (size (Term f l)); trivial.\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ H) as [t' [l1 [l2 [t_eq_t' [H' _]]]]].\nsimpl in t_eq_t'; simpl in H'; subst l.\nrewrite (equiv_same_size t_eq_t').\napply size_direct_subterm; simpl; apply in_or_app; right; left; trivial.\nQed.\n\nInductive rpo (bb : nat) : term -> term -> Prop :=\n  | Subterm : forall f l t s, mem equiv s l -> rpo_eq bb t s -> rpo bb t (Term f l)\n  | Top_gt : \n       forall f g l l', prec Prec g f -> (forall s', mem equiv s' l' -> rpo bb s' (Term f l)) -> \n       rpo bb (Term g l') (Term f l)\n  | Top_eq_lex : \n        forall f g l l', status Prec f = Lex  -> status Prec g = Lex -> prec_eq Prec f g -> (length l = length l' \\/ (length l' <= bb /\\ length l <= bb)) -> rpo_lex bb l' l -> \n        (forall s', mem equiv s' l' -> rpo bb s' (Term g l)) ->\n        rpo bb (Term f l') (Term g l)\n  | Top_eq_mul : \n        forall f g l l', status Prec f = Mul  -> status Prec g = Mul -> prec_eq Prec f g -> rpo_mul bb l' l -> \n        rpo bb (Term f l') (Term g l)\n\nwith rpo_eq (bb : nat) : term -> term -> Prop :=\n  | Equiv : forall t t', equiv t t' -> rpo_eq bb t t'\n  | Lt : forall s t, rpo bb s t -> rpo_eq bb s t\n\nwith rpo_lex (bb : nat) : list term -> list term -> Prop :=\n  | List_gt : forall s t l l', rpo bb s t -> rpo_lex bb (s :: l) (t :: l')\n  | List_eq : forall s s' l l', equiv s s' -> rpo_lex bb l l' -> rpo_lex bb (s :: l) (s' :: l')\n  | List_nil : forall s l, rpo_lex bb nil (s :: l)\n\nwith rpo_mul ( bb : nat) : list term -> list term -> Prop :=\n  | List_mul : forall a lg ls lc l l', \n       permut0 equiv l' (ls ++ lc) -> permut0 equiv l (a :: lg ++ lc) ->\n       (forall b, mem equiv b ls -> exists a', mem equiv a' (a :: lg) /\\ rpo bb b a') ->\n       rpo_mul bb l' l.\n\nLemma size_direct_subterm_mem :\n  forall n t f l, size (Term f l) <= S n -> mem equiv t l -> size t <= n.\nProof.\nintros n t f l Sfl t_mem_l;\napply le_S_n.\napply le_trans with (size (Term f l)); trivial.\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ t_mem_l) as [t' [l1 [l2 [t_eq_t' [H _]]]]].\nsimpl in t_eq_t'; simpl in H; subst l.\nrewrite (equiv_same_size t_eq_t').\napply size_direct_subterm; simpl; apply in_or_app; right; left; trivial.\nQed.\n\nLemma size2_lex1_mem : \n forall s f l t1 t2, mem equiv s l -> o_size2 (s,t1) (Term f l,t2).\nProof.\nintros s f l t1 t2 s_mem_l;\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ s_mem_l) as [s' [l1 [l2 [s_eq_s' [H _]]]]].\nsimpl in s_eq_s'; simpl in H.\nunfold o_size2, size2; rewrite (equiv_same_size s_eq_s').\napply (size2_lex1 s' f l t1 t2).\nsubst l; apply in_or_app; right; left; trivial.\nQed.\n\nLemma size2_lex2_mem :\n  forall t f l s, mem equiv t l -> o_size2 (s,t) (s, Term f l).\nProof.\nintros t f l s t_mem_l;\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ t_mem_l) as [t' [l1 [l2 [t_eq_t' [H _]]]]].\nsimpl in t_eq_t'; simpl in H.\nunfold o_size2, size2; rewrite (equiv_same_size t_eq_t').\napply (size2_lex2 t' f l s).\nsubst l; apply in_or_app; right; left; trivial.\nQed.\n\nLemma size3_lex1_mem :\n forall s f l t1 u1 t2 u2, mem equiv s l -> o_size3 (s,(t1,u1)) (Term f l,(t2,u2)).\nProof.\nintros s f l t1 u1 t2 u2 s_mem_l;\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ s_mem_l) as [s' [l1 [l2 [s_eq_s' [H _]]]]].\nsimpl in s_eq_s'; simpl in H.\nunfold o_size3, size3; rewrite (equiv_same_size s_eq_s').\napply (size3_lex1 s' f l t1 u1 t2 u2).\nsubst l; apply in_or_app; right; left; trivial.\nQed.\n\nLemma size3_lex2_mem :\n  forall t f l s u1 u2, mem equiv t l -> o_size3 (s,(t,u1)) (s,(Term f l, u2)).\nProof.\nintros t f l s u1 u2 t_mem_l;\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ t_mem_l) as [t' [l1 [l2 [t_eq_t' [H _]]]]].\nsimpl in t_eq_t'; simpl in H.\nunfold o_size3, size3, size2; rewrite (equiv_same_size t_eq_t').\napply (size3_lex2 t' f l s u1 u2).\nsubst l; apply in_or_app; right; left; trivial.\nQed.\n\nLemma size3_lex3_mem :\n  forall u f l s t, mem equiv u l -> o_size3 (s,(t,u)) (s,(t,Term f l)).\nProof.\nintros u f l s t u_mem_l;\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ u_mem_l) as [u' [l1 [l2 [u_eq_u' [H _]]]]].\nsimpl in u_eq_u'; simpl in H.\nunfold o_size3, size3, size2; rewrite (equiv_same_size u_eq_u').\napply (size3_lex3 u' f l s t).\nsubst l; apply in_or_app; right; left; trivial.\nQed.\n\n \nLemma size3_lex3_prec :\n  forall u f g h l l' s, In u l -> prec_eq Prec g h -> o_size3 (s,(Term g l',u)) (s,(Term h l',Term f l)).\nProof.\nintros u f g h l l' s u_in_l;\nunfold o_size3, size3, size2, lex;\ngeneralize (beq_nat_ok (size s) (size s)); case (beq_nat (size s) (size s)); [intros _ | intro s_diff_s].\ngeneralize (beq_nat_ok (size (Term g l')) (size (Term h l')));  case (beq_nat (size (Term g l')) (size (Term h l'))); [intros _ | intro t_diff_t]. intros.\napply (size_direct_subterm u (Term f l) u_in_l). intros.\napply False_rec; apply t_diff_t; reflexivity.\napply False_rec; apply s_diff_s; reflexivity.\nDefined.\n\nLemma size3_lex3_mem_preceq :\n  forall u f g h l l' s, mem equiv u l -> prec_eq Prec g h -> o_size3 (s,(Term g l',u)) (s,(Term h l',Term f l)).\nProof.\nintros u f g h l l' s u_mem_l;\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ u_mem_l) as [u' [l1 [l2 [u_eq_u' [H _]]]]].\nsimpl in u_eq_u'; simpl in H.\nunfold o_size3, size3, size2; rewrite (equiv_same_size u_eq_u').\nintros prec_g_h.\napply (size3_lex3_prec u' f g h l l' s).\nsubst l; apply in_or_app; right; left; trivial. trivial.\nQed.\n \nLemma mem_mem :\n forall t l1 l2, equiv_list_lex l1 l2 ->  (mem equiv t l1 <-> mem equiv t l2).\nProof.\nintros t l1 l2 l1_eq_l2; split.\ngeneralize t l2 l1_eq_l2; clear t l2 l1_eq_l2; induction l1 as [ | t1 l1]; \nintros t l2 l1_eq_l2 t_mem_l1.\ncontradiction.\ninversion l1_eq_l2 as [ | s1 s2 l1' l2' s1_eq_s2 l1_eq_l2']; subst.\ndestruct t_mem_l1 as [ t_eq_t1 | t_mem_l1].\nleft; transitivity t1; trivial.\nright; apply IHl1; trivial.\ngeneralize t l2 l1_eq_l2; clear t l2 l1_eq_l2; induction l1 as [ | t1 l1]; \nintros t l2 l1_eq_l2 t_mem_l2;\ninversion l1_eq_l2 as [ | s1 s2 l1' l2' s1_eq_s2 l1_eq_l2']; subst.\ntrivial.\ndestruct t_mem_l2 as [ t_eq_t2 | t_mem_l2].\nleft; transitivity s2; trivial.\nsymmetry; trivial.\nright; apply IHl1 with l2'; trivial.\nQed.\n\nLemma equiv_rpo_equiv_1 :\n  forall bb t t', equiv t t' -> (forall s, rpo bb s t <-> rpo bb s t').\nProof.\nintro bb.\nassert (H : forall p, match p with (s,t) =>\n                              forall t', equiv t t' -> rpo bb s t -> rpo bb s t'\n                 end).\nintro p; pattern p; refine (well_founded_ind wf_size2 _ _ _); clear p.\nintros [s t] IH t' t_eq_t' s_lt_t.\ninversion t_eq_t' as [ t'' | f g'' l1 l2 Statf Statg eq_f_g H | f g'' l1 l2 Statf Statg eq_f_g P]; subst.\n(* 1/4 equivalence is syntactic identity *)\ntrivial.\n(* 1/3 equivalence with Lex top symbol *)\ninversion s_lt_t as  [g l t'' t' t'_mem_l t''_le_t'\n                            | g g' l l' g_prec_f l'_lt_t\n                            | g g''' l l' Stat_g Statg''' eq_g_g''' L l'_lt_ll1 l'_lt_t\n                            | g g''' l l' Stat_g Statg''' eq_g_g''' l'_lt_ll1 ]; subst.\n(* 1/6 equivalence with Lex top symbol , Subterm *)\ndestruct t''_le_t' as [t'' t' t''_eq_t' | t'' t' t''_lt_t'];\napply Subterm with t'; trivial.\nrewrite <- (mem_mem t' H); trivial.\napply Equiv; trivial.\nrewrite <- (mem_mem t' H); trivial.\napply Lt; trivial.\n(* 1/5 equivalence with Lex top symbol,  Top_gt *)\napply Top_gt; trivial.\napply prec_eq_prec1 with f. trivial. trivial.\nintros s' s'_mem_l'.\napply (IH (s',(Term f l1))); trivial.\napply size2_lex1_mem; trivial.\napply l'_lt_t; trivial.\n(* 1/4 equivalence with Lex top symbol,  Top_eq_lex *)\napply Top_eq_lex; trivial. apply prec_eq_transitive with f; trivial.\nrewrite <- (equiv_list_lex_same_length H); assumption.\nclear t_eq_t' l'_lt_t s_lt_t L. revert l2 l' l'_lt_ll1 IH H. \ninduction l1 as [ | t1 l1]; intros l2 l' l'_lt_l1 IH l1_eq_l2;\ninversion l'_lt_l1 as [ s t1' l'' l1' s_lt_t1' L_eq \n                             | t1' t1'' l'' l1' t1'_eq_t1'' l''_lt_l1' | s l'']; subst;\ninversion l1_eq_l2 as [ | t1'' t2 l1' l2' t1''_eq_t2 l1_eq_l2']; subst.\nsimpl; apply List_gt.\napply (IH (s,t1)); trivial.\napply size2_lex1; left; trivial.\napply List_eq.\ntransitivity t1; trivial.\napply IHl1; trivial.\nintros y H; apply IH.\nrefine (o_size2_trans _ _ _ H _).\napply size2_lex1_bis.\napply List_nil.\nintros s' s'_mem_l'.\napply (IH (s', Term f l1)); trivial.\napply size2_lex1_mem; trivial.\napply l'_lt_t; trivial.\n(* 1/3 equivalence with Lex top symbol,  Top_eq_mul *)\nrewrite Statf in Statg'''; discriminate.\n(* 1/2 equivalence with Mul top symbol *)\ninversion s_lt_t as  [g l t'' t' t'_mem_l t''_le_t'\n                            | g g' l l' g_prec_f l'_lt_t\n                            | g g''' l l' Stat_g Statg''' eq_g_g''' L l'_lt_ll1 l'_lt_t\n                            | g g''' l l' Stat_g Statg''' eq_g_g''' l'_lt_ll1 ]; subst.\n(* 1/5 equivalence with Mul top symbol , Subterm *)\ndestruct t''_le_t' as [t'' t' t''_eq_t' | t'' t' t''_lt_t'];\napply Subterm with t'; trivial.\nrewrite <- (mem_permut0_mem equiv_equiv  t' P); trivial.\napply Equiv; trivial.\nrewrite <- (mem_permut0_mem equiv_equiv t' P); trivial.\napply Lt; trivial.\n(* 1/4 equivalence with Mul top symbol,  Top_gt *)\napply Top_gt; trivial. apply prec_eq_prec1 with f. trivial. trivial.\nintros s' s'_mem_l2.\napply (IH (s', Term f l1)); trivial.\napply size2_lex1_mem; trivial.\napply l'_lt_t; trivial.\n(* 1/3 equivalence with Mul top symbol,  Top_eq_lex *)\nrewrite Statf in Statg'''; discriminate.\n(* 1/2 equivalence with Mul top symbol,  Top_eq_mul *)\napply Top_eq_mul; trivial.\napply prec_eq_transitive with f. trivial. trivial.\ninversion l'_lt_ll1 as [a lg ls lc l'' l''' Q1 Q2 ls_lt_alg]; subst.\napply (@List_mul bb a lg ls lc); trivial.\napply (permut0_trans equiv_equiv) with l1.\napply (permut0_sym equiv_equiv). trivial. \nexact Q2.\n\nintros t t' t_eq_t' s; split.\napply (H (s,t)); trivial.\napply (H (s,t')); trivial.\napply (Relation_Definitions.equiv_sym _ _ equiv_equiv); trivial.\nQed.\n\nLemma equiv_rpo_equiv_2 :\n  forall bb t t', equiv t t' -> (forall s, rpo bb t s <-> rpo bb t' s).\nProof.\nintro bb.\nassert (H : forall p, match p with (s,t) =>\n                              forall t', equiv t t' -> rpo bb t s -> rpo bb t' s\n                 end).\nintro p; pattern p; refine (well_founded_ind wf_size2 _ _ _); clear p.\nintros [s t] IH t' t_eq_t' t_lt_s.\ninversion t_eq_t' as [ t'' | g g' l1 l2 Stat Statg' g_eq_g' l1_eq_l2 | g g' l1 l2 Stat Statg' g_eq_g' P]; subst.\n(* 1/4 equivalence is syntactic identity *)\ntrivial.\n(* 1/3 equivalence with Lex top symbol *)\ninversion t_lt_s as  [f l t'' t' t'_mem_l t''_le_t'\n                            | f f' l l' g_prec_f l'_lt_s\n                            | f' f l l' Stat_g Stat' f_stat_g L ll1_lt_l ll_lt_s\n                            | f' f l l' Stat_g Stat' f_stat_g ll1_lt_l ]; subst.\n(* 1/6 equivalence with Lex top symbol , Subterm *)\ndestruct t''_le_t' as [t'' t' t''_eq_t' | t'' t' t''_lt_t'];\napply Subterm with t'; trivial.\napply Equiv.\ntransitivity t''; trivial.\nsymmetry; trivial.\napply Lt.\napply (IH (t',t'')); trivial.\napply size2_lex1_mem; trivial.\n(* 1/5 equivalence with Lex top symbol,  Top_gt *)\napply Top_gt; trivial.\napply prec_eq_prec2 with g; trivial.\nintros s' s'_mem_l2. apply l'_lt_s.\nrewrite (@mem_mem s' l1 l2); trivial.\n(* 1/4 equivalence with Lex top symbol,  Top_eq_lex *)\napply Top_eq_lex; trivial.\napply prec_eq_transitive with g. apply prec_eq_sym. trivial. trivial.\nrewrite <- (equiv_list_lex_same_length l1_eq_l2); assumption.\nclear t_eq_t' ll_lt_s t_lt_s L; revert l2 l l1_eq_l2 ll1_lt_l IH.\ninduction l1 as [ | t1 l1]; intros l2 l l1_eq_l2 l1_lt_l IH;\ninversion l1_lt_l as [ t1' s l1' l' t1'_lt_s L_eq \n                            | t1' s l1' l'' t1'_eq_s l1'_lt_l'' \n                            | s l']; subst;\ninversion l1_eq_l2 as [ | t1'' t2 l1' l2' t1''_eq_t2 l1_eq_l2']; subst.\napply List_nil.\nsimpl; apply List_gt.\napply (IH (s,t1)); trivial.\napply size2_lex1; left; trivial.\nsimpl; apply List_eq.\ntransitivity t1; trivial.\nsymmetry; trivial.\napply IHl1; trivial.\nintros y H; apply IH.\nrefine (o_size2_trans _ _ _ H _).\napply size2_lex1_bis.\nintros s' s'_in_l2; apply ll_lt_s.\nrewrite (@mem_mem s' l1 l2); trivial.\n(* 1/3 equivalence with Lex top symbol,  Top_eq_mul *)\nrewrite Stat in Stat_g; discriminate.\n(* 1/2 equivalence with Mul top symbol *)\ninversion t_lt_s as  [f l t'' t' t'_mem_l t''_le_t'\n                            | f f' l l' g_prec_f l'_lt_s\n                            | f' f l l' Stat_g Stat' f_stat_g L ll1_lt_l ll_lt_s\n                            | f' f l l' Stat_g Stat' f_stat_g ll1_lt_l ]; subst.\n(* 1/5 equivalence with Mul top symbol , Subterm *)\ndestruct t''_le_t' as [t'' t' t''_eq_t' | t'' t' t''_lt_t'];\napply Subterm with t'; trivial.\napply Equiv.\ntransitivity t''; trivial.\nsymmetry; trivial.\napply Lt.\napply (IH (t',t'')); trivial.\napply size2_lex1_mem; trivial.\n(* 1/4 equivalence with Mul top symbol,  Top_gt *)\napply Top_gt; trivial.\napply prec_eq_prec2 with g; trivial.\nintros s' s'_mem_l2; apply l'_lt_s.\nrewrite (mem_permut0_mem equiv_equiv s' P); trivial.\n(* 1/3 equivalence with Mul top symbol,  Top_eq_lex *)\nrewrite Stat in Stat_g; discriminate.\n(* 1/3 equivalence with Mul top symbol,  Top_eq_mul *)\napply Top_eq_mul; trivial.\napply prec_eq_transitive with g. apply prec_eq_sym; trivial. trivial.\ninversion ll1_lt_l as [a lg ls lc l' l'' Q1 Q2 ls_lt_alg]; subst.\napply (@List_mul bb a lg ls lc); trivial. \napply permut0_trans with l1.\nexact equiv_equiv.\napply (permut0_sym equiv_equiv). assumption. assumption.\n\nintros t t' t_eq_t' s; split.\napply (H (s,t)); trivial.\napply (H (s,t')); trivial.\napply (Relation_Definitions.equiv_sym _ _ equiv_equiv); trivial.\nQed.\n\nLemma equiv_rpo_equiv_3 :\n  forall bb t t', equiv t t' -> (forall s, rpo_eq bb s t <-> rpo_eq bb s t').\nProof.\nintro bb.\nassert (H: forall t t', equiv t t' -> (forall s, rpo_eq bb s t -> rpo_eq bb s t')).\nintros t t' t_eq_t' s s_le_t; inversion s_le_t; subst.\napply Equiv; apply (equiv_trans _ _ equiv_equiv) with t; trivial.\napply Lt; rewrite <- (equiv_rpo_equiv_1 _ t_eq_t'); trivial.\nintros t t' t_eq_t' s; split; apply H; trivial.\napply (Relation_Definitions.equiv_sym _ _ equiv_equiv); trivial.\nQed.\n\nLemma equiv_rpo_equiv_4 :\n  forall bb t t', equiv t t' -> (forall s, rpo_eq bb t s <-> rpo_eq bb t' s).\nProof.\nintro bb.\nassert (H: forall t t', equiv t t' -> (forall s, rpo_eq bb t s -> rpo_eq bb t' s)).\nintros t t' t_eq_t' s t_le_s; inversion t_le_s; subst.\napply Equiv; apply (equiv_trans _ _ equiv_equiv) with t; trivial;\napply (equiv_sym _ _ equiv_equiv); trivial.\napply Lt; rewrite <- (equiv_rpo_equiv_2 _ t_eq_t'); trivial.\nintros t t' t_eq_t' s; split; apply H; trivial.\napply (equiv_sym _ _ equiv_equiv); trivial.\nQed.\n\n(** ** rpo is a preorder, and its reflexive closure is an ordering. *)\n\nLemma rpo_subterm_equiv :\n forall bb s t, equiv t s -> forall tj, direct_subterm tj t -> rpo bb tj s.\nProof.\nintros bb s [ | f l] fl_eq_s tj; simpl. \ncontradiction.\nintro tj_in_l; rewrite <- (equiv_rpo_equiv_1 _  fl_eq_s).\napply Subterm with tj.\napply in_impl_mem; trivial.\nintros; apply Eq.\nintros; apply Equiv; apply Eq.\nQed.\n\nLemma rpo_subterm :\n forall bb s t, rpo bb t s -> forall tj, direct_subterm tj t -> rpo bb tj s.\nProof.\nintros bb s t; \ncut (forall p : term * term,\n             match p with\n              | (s,t) => rpo bb t s -> forall tj, direct_subterm tj t -> rpo bb tj s\n             end).\nintro H; apply (H (s,t)).\n\nclear s t; intro p; pattern p; refine (well_founded_ind wf_size2 _ _ _); clear p.\nintros [s [ v | f l]] IH t_lt_s tj tj_in_l; simpl in tj_in_l; [ contradiction | idtac].\ninversion t_lt_s as [ f' l' t' s' s'_in_l' t'_le_s'\n                               | f' g' k k' g'_prec_f' H\n                               | f' g k k' Sf' Sg f_eq_g L k'_lt_k H\n                               | f' g k k' Sf' Sg f_eq_g k'_lt_k ].\n(* 1/4 Subterm *)\nsubst; inversion t'_le_s' as [ t'' s'' t'_eq_s' | t'' s'' t'_lt_s']; clear t'_le_s'; subst.\napply (@Subterm bb f' l' tj s'); trivial;\napply Lt; apply rpo_subterm_equiv with (Term f l); trivial.\napply (@Subterm bb f' l' tj s'); trivial.\napply Lt; apply (IH (s', Term f l)); trivial.\napply size2_lex1_mem; trivial.\n(* 1/3 Top_gt *)\nsubst; apply H; apply in_impl_mem; trivial.\nintros; apply Eq.\n(* 1/2 Top_eq_lex *)\nsubst; apply H; apply in_impl_mem; trivial.\nintros; apply Eq.\n(* Top_eq_mul *)\ninversion k'_lt_k as [a lg ls lc l1 l2 P1 P2 H']; subst.\nassert (tj_mem_l := in_impl_mem equiv Eq tj l tj_in_l).\nrewrite (mem_permut0_mem equiv_equiv tj P1) in tj_mem_l.\nrewrite <- mem_or_app in tj_mem_l.\ndestruct tj_mem_l as [tj_mem_ls | tj_mem_llc].\ndestruct (H' _ tj_mem_ls) as [a' [a'_mem_a_lg tj_lt_a']].\napply (@Subterm bb g k tj a').\nrewrite (mem_permut0_mem equiv_equiv a' P2); rewrite app_comm_cons.\nrewrite <- mem_or_app; left; trivial.\napply Lt; trivial.\napply (@Subterm bb g k tj tj).\nrewrite (mem_permut0_mem equiv_equiv tj P2).\nright; rewrite <- mem_or_app; right; trivial.\napply Equiv; apply Eq.\nQed.\n\nLemma rpo_subterm_mem :\n forall bb s f l, rpo bb (Term f l) s -> forall tj, mem equiv tj l -> rpo bb tj s.\nProof.\nintros bb s f l fl_lt_s tj tj_mem_l.\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ tj_mem_l) as [tj' [l1 [l2 [tj_eq_tj' [H _]]]]].\nsimpl in tj_eq_tj'; simpl in H.\nrewrite (equiv_rpo_equiv_2  _ tj_eq_tj').\napply rpo_subterm with (Term f l); trivial.\nsubst l; simpl; apply in_or_app; right; left; trivial.\nQed.\n\nAdd Relation term equiv \n  reflexivity proved by (Relation_Definitions.equiv_refl _ _ equiv_equiv)\n    symmetry proved by (Relation_Definitions.equiv_sym _ _ equiv_equiv)\n      transitivity proved by (Relation_Definitions.equiv_trans _ _ equiv_equiv) as EQA.\n\nAdd Relation (list term) (permut0 equiv) \n  reflexivity proved by (permut0_refl equiv_equiv) \n  symmetry proved by (permut0_sym equiv_equiv) \n    transitivity proved by (permut0_trans equiv_equiv)\n  as LP.\n\nAdd Morphism (mem equiv)\n  with signature equiv ==> permut0 equiv ==> iff\n    as mem_morph2.\n  exact (mem_morph2 equiv_equiv).\nQed.\n  \n Add Morphism (List.app (A:=term)) \n\twith signature permut0 equiv ==> permut0 equiv ==> permut0 equiv\n\tas app_morph.\n   exact (app_morph equiv_equiv).\nQed.\n\n Add Morphism (List.cons (A:=term)) \n\twith signature equiv ==> permut0 equiv ==> permut0 equiv\n\tas add_A_morph.\n   exact (add_A_morph equiv_equiv).\nQed.\n\nLemma rpo_trans : forall bb u t s, rpo bb u t -> rpo bb t s ->  rpo bb u s.\nProof.\nintros bb u t s;\ncut (forall triple : term * (term * term),\n       match triple with\n       | (s,(t,u)) => rpo bb t s -> rpo bb u t -> rpo bb u s\n       end).\nintros H u_lt_t t_lt_s; apply (H (s,(t,u))); trivial.\nclear s t u; intro triple; pattern triple; \nrefine (well_founded_ind wf_size3 _ _ triple); clear triple.\nintros [[v | f l] [t u]] IH.\n(* 1/2 Variable case *)\nintros t_lt_v; inversion t_lt_v.\n(* 1/1 Compound case *)\nintros t_lt_fl u_lt_t;\ninversion t_lt_fl as [ f'' l' s' t' t'_in_l' t_le_t'\n                               | f'' f' k'' l' f'_prec_f H''\n                               | f'' g'' k'' l' Sf Sg f''_eq_g'' L l'_lt_l H H1 H2 \n                               | f'' g'' k'' l' Sf Sg f''_eq_g'' l'_lt_l ]; subst.\n(* 1/4 Subterm *)\napply Subterm with t'; trivial; apply Lt;\ninversion t_le_t' as [t'' t''' t_eq_t' | t'' t''' t_lt_t']; subst.\nrewrite <- (equiv_rpo_equiv_1  _ t_eq_t'); trivial.\napply (IH (t',(t,u))); trivial.\napply size3_lex1_mem; trivial.\n(* 1/3 Top_gt *)\ninversion u_lt_t as [ f'' l'' s' t' t'_in_l' u_le_t'\n                               | g'' f'' k'' l'' f''_prec_f'' H'''\n                               | g'' g' k'' l'' Sf' Sf'' g''_eq_g' L l''_lt_l' H H1 H2 \n                               | g'' g' k'' l'' Sf' Sf'' g''_eq_g' l''_lt_l' ]; subst.\n(* 1/6 Top_gt, Subterm *)\ninversion u_le_t' as [t'' t''' u_eq_t' | t'' t''' u_lt_t']; subst.\nrewrite (equiv_rpo_equiv_2 _ u_eq_t'); trivial; apply H''; trivial.\napply (IH (Term f l,(t',u))); trivial.\napply size3_lex2_mem; trivial.\napply H''; trivial.\n(* 1/5 Top_gt, Top_gt *)\napply Top_gt.\napply prec_transitive with f'; trivial.\nintros u u_in_l''; apply (IH (Term f l, (Term f' l', u))); trivial.\napply size3_lex3_mem; trivial.\napply H'''; trivial.\n(* 1/4 Top_gt, Top_eq_lex *)\napply Top_gt. apply prec_eq_prec2 with f'. trivial.\napply prec_eq_sym. trivial.\nintros u u_in_l''; apply (IH (Term f l, (Term f' l', u))); trivial.\napply size3_lex3_mem; trivial.\napply H; trivial.\n(* 1/3 Top_gt, Top_eq_mul *)\napply Top_gt. apply prec_eq_prec2 with f'. trivial.\napply prec_eq_sym. trivial.\nintros u u_in_l''. apply (IH (Term f l, (Term f' l', u))); trivial.\napply size3_lex3_mem; trivial.\napply rpo_subterm_mem with g'' l''; trivial.\n(* 1/2 Top_eq_lex *)\ninversion u_lt_t as [ f''' l'' s' t' t'_in_l' u_le_t'\n                               | g'' f''' k'' l'' f''_prec_f' H'''\n                               | g'' f''' k'' l'' Sf' Sg' f_eq_g' L' l''_lt_l' H' H1 H2 \n                               | g'' f''' k'' l'' Sf' Sg' f_eq_g' l''_lt_l' ]; subst.\n(* 1/5 Top_eq_lex, Subterm *)\ninversion u_le_t' as [t'' t''' u_eq_t' | t'' t''' u_lt_t']; subst.\nrewrite (equiv_rpo_equiv_2 _ u_eq_t').\napply rpo_subterm_mem with f'' l'; trivial.\napply (IH (Term f l, (t', u))); trivial.\napply size3_lex2_mem; trivial.\napply H; trivial.\n(* 1/4 Top_eq_lex, Top_gt *)\napply Top_gt. apply prec_eq_prec1 with f''; trivial.\nintros u u_in_l''. apply (IH (Term f l, (Term f'' l', u))). \napply size3_lex3_mem. trivial. trivial. \napply H'''. trivial. \n\n(* 1/3 Top_eq_lex, Top_eq_lex *)\napply Top_eq_lex; trivial.\napply prec_eq_transitive with f''. trivial. trivial.\ndestruct L as [L | [L1 L2]].\nrewrite L; assumption.\ndestruct L' as [L' | [L1' L2']].\nrewrite <- L'; right; split; assumption.\nright; split; assumption.\ngeneralize l' l'' l'_lt_l l''_lt_l' IH; clear l' l'' l'_lt_l l''_lt_l' IH H H' t_lt_fl u_lt_t L L';\ninduction l as [ | s l]; intros l' l'' l'_lt_l l''_lt_l' IH.\ninversion l'_lt_l.\ninversion l'_lt_l as [ t s' k' k t_lt_s  | t s' k' k t_eq_s k'_lt_k | t k];\ninversion l''_lt_l' as [ u t' k'' h' u_lt_t | u t' k'' h' u_eq_t k''_lt_k' | u k1].\nsubst; injection H3; intros; subst; apply List_gt.\napply (IH (s,(t,u))); trivial.\napply size3_lex1; left; trivial.\nsubst; injection H3; intros; subst; apply List_gt.\nrewrite (equiv_rpo_equiv_2 _ u_eq_t); trivial.\napply List_nil.\nsubst; injection H3; intros; subst; apply List_gt.\nrewrite <- (equiv_rpo_equiv_1 _ t_eq_s); trivial.\nsubst; injection H3; intros; subst; apply List_eq.\ntransitivity t; trivial.\napply IHl with k'; trivial.\nintros; apply IH;\napply o_size3_trans with (Term f l, (Term f k', Term f k'')); trivial.\napply size3_lex1_bis.\napply List_nil.\nsubst; discriminate H3.\nsubst; discriminate H3.\nsubst; discriminate H3.\nintros u u_in_l''. apply (IH (Term f l, (Term f'' l', u))); trivial.\napply size3_lex3_mem. trivial.\napply H'; trivial.\n(* 1/2 Top_eq_lex, Top_eq_mul *)\nrewrite Sf in Sg'; discriminate.\n(* 1/1 Top_eq_mul *)\ninversion u_lt_t as [ f''' l'' s' t' t'_in_l' u_le_t'\n                               | g'' f''' k'' l'' f''_prec_f' H'''\n                               | g'' f''' k'' l'' Sf' Sf''' Seq_g''_f''' L l''_lt_l' H H1 H2 \n                               | g'' f''' k'' l'' Sf' Sf''' Seq_g''_f''' l''_lt_l' ]; subst.\n(* 1/4 Top_mul_lex, Subterm *)\ninversion u_le_t' as [t'' t''' u_eq_t' | t'' t''' u_lt_t']; subst.\nrewrite (equiv_rpo_equiv_2 _ u_eq_t').\napply rpo_subterm_mem with f'' l'; trivial. \napply (IH (Term f l, (t', u))); trivial.\napply size3_lex2_mem; trivial.\napply rpo_subterm_mem with f'' l'; trivial.\n(* 1/3 Top_eq_mul, Top_gt *)\napply Top_gt; trivial. apply prec_eq_prec1 with f''. trivial. trivial.\nintros u u_in_l''; apply (IH (Term f l, (Term f'' l', u))); trivial.\napply size3_lex3_mem; trivial.\napply H'''; trivial.\n(* 1/2 Top_eq_mul, Top_eq_lex *)\nrewrite Sf in Sf'''; discriminate.\n(* 1/1 Top_eq_mul, Top_eq_mul *)\napply Top_eq_mul; trivial. apply prec_eq_transitive with f''. trivial. trivial. \ndestruct l'_lt_l as [a lg ls lc l l' P' P ls_lt_alg].\ndestruct l''_lt_l' as [a' lg' ls' lc' l' l'' Q' Q ls'_lt_alg'].\nrewrite P' in Q; rewrite app_comm_cons in Q.\ndestruct (@ac_syntactic _ _ equiv_equiv _ equiv_bool_ok _ _ _ _ Q) as [k1 [k2 [k3 [k4 [P1 [P2 [P3 P4]]]]]]].\napply (@List_mul bb a (lg ++ k2) (ls' ++ k3) k1).\nrewrite Q'.\nrewrite <- ass_app.\nrewrite <- permut_app1.\nrewrite list_permut0_app_app; trivial. apply equiv_equiv. apply equiv_equiv.\nrewrite P.\nrewrite <- permut0_cons;[|apply equiv_equiv|apply (Relation_Definitions.equiv_refl _ _ equiv_equiv)].\nrewrite <- ass_app.\nrewrite <- permut_app1.\nrewrite list_permut0_app_app; trivial.  apply equiv_equiv. apply equiv_equiv.\nintros b b_mem_ls'_k3; rewrite <- mem_or_app in b_mem_ls'_k3.\ndestruct b_mem_ls'_k3 as [b_mem_ls' | b_mem_k3].\ndestruct (ls'_lt_alg'  _ b_mem_ls') as [a'' [a''_in_a'lg' b_lt_a'']].\nrewrite (mem_permut0_mem equiv_equiv a'' P4) in a''_in_a'lg'.\nrewrite <- mem_or_app in a''_in_a'lg'.\ndestruct a''_in_a'lg' as [a''_mem_k2 | a''_mem_k4].\nexists a''; split; trivial.\nrewrite app_comm_cons; rewrite <- mem_or_app; right; trivial.\ndestruct (ls_lt_alg a'') as [a3 [a3_in_alg a''_lt_a3]].\nrewrite (mem_permut0_mem equiv_equiv a'' P2).\nrewrite <- mem_or_app; right; trivial.\nexists a3; split.\nrewrite app_comm_cons; rewrite <- mem_or_app; left; trivial.\napply (IH (a3,(a'',b))); trivial.\napply size3_lex1_mem.\nrewrite (mem_permut0_mem equiv_equiv a3 P).\nrewrite app_comm_cons; rewrite <- mem_or_app; left; trivial.\ndestruct (ls_lt_alg b) as [a'' [a''_in_alg b_lt_a'']].\nrewrite (mem_permut0_mem equiv_equiv b P2); rewrite <- mem_or_app; left; trivial.\nexists a''; split; trivial.\nrewrite app_comm_cons; rewrite <- mem_or_app; left; trivial.\nQed.\n\nLemma rpo_mul_remove_equiv_aux :\n  forall bb l l' s s', (forall t, mem equiv t (s :: l) -> rpo bb t t -> False) -> \n                      equiv s s' -> rpo_mul bb (s :: l) (s' :: l') -> rpo_mul bb l l'. \nProof.\nintros bb l l' s s' Antirefl s_eq_s' sl_lt_s'l';  \ninversion sl_lt_s'l' as [a lg ls lc k' k P P' ls_lt_alg]; subst.\nassert (s_mem_ls_lc : mem equiv s (ls ++ lc)).\nrewrite <- (mem_permut0_mem equiv_equiv s P); left; reflexivity.\nrewrite <- mem_or_app in s_mem_ls_lc.\ndestruct s_mem_ls_lc as [s_mem_ls | s_mem_lc].\nassert (s'_mem_alg_lc : mem equiv s' (a :: lg ++ lc)).\nrewrite <- (mem_permut0_mem equiv_equiv s' P'); left; reflexivity.\nrewrite app_comm_cons in s'_mem_alg_lc.\nrewrite <- mem_or_app in s'_mem_alg_lc.\ndestruct s'_mem_alg_lc as [s'_mem_alg | s'_mem_lc].\n(* 1/3 s in in ls, s' is in (a :: lg) *)\ndestruct lg as [ | g lg].\n(* 1/4 s in in ls, s' is in (a :: lg), lg = nil *)\nassert (s'_eq_a : equiv s' a).\ndestruct s'_mem_alg; trivial; contradiction.\ndestruct (ls_lt_alg _ s_mem_ls) as [a' [[a_eq_a' | a'_mem_nil] b_lt_a']].\napply False_rec.\napply (Antirefl s).\nleft; reflexivity.\nrewrite (equiv_rpo_equiv_1 _ s_eq_s').\nrewrite (equiv_rpo_equiv_1 _ s'_eq_a).\nrewrite <- (equiv_rpo_equiv_1 _ a_eq_a'); trivial.\ncontradiction.\n(* s in in ls, s' is in (a :: lg), 1/3 lg <> nil *)\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ s'_mem_alg) as [u' [alg' [alg'' [s'_eq_u' [H _]]]]]; \nsimpl in s'_eq_u'; simpl in H; subst.\nassert (P'' : permut0 equiv l' ((alg' ++ alg'') ++ lc)).\nrewrite app_comm_cons in P'; rewrite H in P'.\nrewrite <- ass_app in P'; simpl in P'.\nrewrite <- ass_app; rewrite <- permut0_cons_inside in P'; trivial. apply equiv_equiv.\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ s_mem_ls) as [u [ls' [ls'' [s_eq_u [H' _]]]]]; \nsimpl in s_eq_u; simpl in H'; subst.\nassert (ls'ls''_lt_alg'alg'' : forall b,\n            mem equiv b (ls' ++ ls'') -> exists a', mem equiv a' (alg' ++ alg'') /\\ rpo bb b a').\nintros b b_in_ls'ls''; destruct (ls_lt_alg b) as [a' [a'_mem_aglg b_lt_a']].\napply mem_insert; trivial.\nrewrite H in a'_mem_aglg.\nrewrite <- mem_or_app in a'_mem_aglg.\ndestruct a'_mem_aglg as [a'_mem_alg' | [u'_eq_a' | a'_mem_alg'']].\nexists a'; split; trivial.\nrewrite <- mem_or_app; left; trivial.\ndestruct (ls_lt_alg a') as [a'' [a''_mem_aglg a'_lt_a'']].\nrewrite <- mem_or_app; right; left.\ntransitivity u'; trivial.\ntransitivity s; trivial.\nsymmetry.\ntransitivity s'; trivial.\nexists a''; split.\napply diff_mem_remove with u'.\nintro a''_eq_u'.\ndestruct (mem_split_set _ _ equiv_bool_ok u (s :: l)) as [u'' [l1 [l2 [u_eq_u'' [H' _]]]]].\nleft; symmetry; trivial.\nsimpl in u_eq_u''; simpl in H'.\napply (Antirefl u'').\nrewrite (mem_permut0_mem equiv_equiv u'' P).\nrewrite <- mem_or_app; left.\nrewrite <- mem_or_app; right; left; symmetry; trivial.\nassert (u''_eq_u' : equiv u'' u'). \ntransitivity s'; trivial.\ntransitivity s; trivial.\ntransitivity u.\nsymmetry; trivial.\nsymmetry; trivial.\nrewrite (equiv_rpo_equiv_2 _ u''_eq_u').\nrewrite <- (equiv_rpo_equiv_2 _ u'_eq_a').\nrewrite (equiv_rpo_equiv_1 _ u''_eq_u').\nrewrite <- (equiv_rpo_equiv_1 _ a''_eq_u'); trivial.\nrewrite <- H; trivial.\napply rpo_trans with a'; trivial.\nexists a'; split; trivial.\nrewrite <- mem_or_app; right; trivial.\nassert (L : length (alg' ++ alg'') = S (length lg)).\nassert (L' := f_equal (fun l => length l) H).\nsimpl in L'; rewrite length_app in L'; simpl in L'.\nrewrite plus_comm in L'; simpl in L'; rewrite plus_comm in L'.\nrewrite <- length_app in L'; injection L'; intro L''; symmetry; assumption.\ndestruct (alg' ++ alg'') as [ | a' lg'].\ndiscriminate.\napply (@List_mul bb a' lg' (ls' ++ ls'') lc); trivial.\nrewrite <- ass_app in P; simpl in P.\nrewrite <- permut0_cons_inside in P; trivial;[|apply equiv_equiv].\nrewrite <- ass_app; trivial.\n(* 1/2 s in in ls, s' is in lc *)\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ s'_mem_lc) as [s'' [lc' [lc'' [s_eq_s'' [H _]]]]].\nsimpl in s_eq_s''; simpl in H.\napply (@List_mul bb a lg ls (lc' ++ lc'')); trivial.\nrewrite H in P.\nrewrite ass_app in P.\nrewrite <- permut0_cons_inside in P.\nrewrite ass_app; trivial. \napply equiv_equiv.\ntransitivity s'; trivial.\nrewrite H in P'.\nrewrite app_comm_cons in P'.\nrewrite ass_app in P'.\nrewrite <- permut0_cons_inside in P'; trivial.\nrewrite app_comm_cons; rewrite ass_app; trivial. apply equiv_equiv.\n(* 1/1 s in lc *)\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ s_mem_lc) as [s'' [lc' [lc'' [s_eq_s'' [H _]]]]].\nsimpl in s_eq_s''; simpl in H.\napply (@List_mul bb a lg ls (lc' ++ lc'')); trivial.\nrewrite H in P.\nrewrite ass_app in P.\nrewrite <- permut0_cons_inside in P; trivial. \nrewrite ass_app; trivial. apply equiv_equiv.\nrewrite H in P'.\nrewrite app_comm_cons in P'.\nrewrite ass_app in P'.\nrewrite <- permut0_cons_inside in P'.\nrewrite app_comm_cons; rewrite ass_app; trivial. apply equiv_equiv.\ntransitivity s; trivial.\nsymmetry; trivial.\nQed.\n\nLemma rpo_antirefl :\n  forall bb s, rpo bb s s -> False.\nProof.\nintros bb s; pattern s; apply term_rec3_mem; clear s.\nintros v v_lt_v; inversion v_lt_v.\nintros f l IHl t_lt_t;\ninversion t_lt_t  as [ f' l' s'' s' s'_mem_l s_le_s'\n                               | f' f'' l' l'' f_prec_f H' H1 H2\n                               | f' g' l' l'' Sf Sg f_eq_g L l_lt_l H H1 H2\n                               | f' g' l' l'' Sf Sg f_eq_g l_lt_l ]; clear t_lt_t; subst.\n(* 1/4 Antirefl, subterm *)\napply (IHl s'); trivial.\ninversion s_le_s' as [u u' s_eq_s' | u u' s_lt_s']; subst.\nrewrite <- (equiv_rpo_equiv_1 _ s_eq_s').\napply Subterm with s'; trivial; apply Equiv; apply Eq.\napply rpo_trans with (Term f l); trivial.\napply Subterm with s'; trivial; apply Equiv; apply Eq.\n(* 1/3 Antirefl, Top_gt *)\napply (prec_antisym Prec) with f; trivial.\n(* 1/2 Antirefl, Top_eq_lex *)\nclear H; induction l as [| t l]. inversion l_lt_l. \ninversion l_lt_l as [ s t' l' l'' s_lt_t | \n  s t' l' l'' s_eq_t l'_lt_l'' | \n    s l']; subst.\napply IHl with t; trivial; left; reflexivity.\napply IHl0; trivial.\nintros s s_in_l; apply IHl; right; trivial.\nleft; apply refl_equal.\n\n(* 1/1 Antirefl, Top_eq_mul *)\ninduction l as [ | s l].\ninversion l_lt_l as [a lg ls lc l' l'' ls_lt_alg]; subst.\nassert (L := permut_length H); discriminate.\napply IHl0.\nintros t t_mem_l; apply IHl; right; trivial.\napply rpo_mul_remove_equiv_aux with s s; trivial.\napply Eq.\nQed.\n\nLemma rpo_closure :\n  forall bb s t u, \n  (rpo bb t s -> rpo bb u t -> rpo\n bb u s) /\\\n  (rpo bb s t -> rpo bb t s -> False) /\\\n  (rpo bb s s -> False) /\\\n  (rpo_eq bb s t -> rpo_eq bb t s -> equiv s t).\nProof.\nintros bb s t u; repeat split.\nintros; apply (@rpo_trans bb u t s); trivial.\nintros; apply (@rpo_antirefl bb s); apply rpo_trans with t; trivial.\napply rpo_antirefl.\nintros s_le_t t_le_s;\ndestruct s_le_t as [s t s_eq_t | s t s_lt_t]; trivial.\ndestruct t_le_s as [t s t_eq_s | t s t_lt_s].\napply (equiv_sym _ _ equiv_equiv); trivial.\nassert False; [idtac | contradiction].\napply (@rpo_antirefl bb s); apply rpo_trans with t; trivial.\nQed.\n\n(** ** Well-foundedness of rpo. *)\nLemma equiv_acc_rpo :\n  forall bb t t', equiv t t' -> Acc (rpo bb) t -> Acc (rpo bb) t'.\nProof.\nintros bb t t' t_eq_t' Acc_t; apply Acc_intro.\nintro s; rewrite <- (equiv_rpo_equiv_1 _ t_eq_t').\ninversion Acc_t as [H]; apply (H s); trivial.\nQed.\n\nInductive rpo_lex_rest (bb bb' : nat) : list term -> list term -> Prop :=\n| Rpo_lex_rest : \n     forall l l', (length l = length l' \\/ (length l' <= bb /\\ length l <= bb)) ->\n     (forall s, mem equiv s l -> Acc (rpo bb') s) -> (forall s, mem equiv s l' -> Acc (rpo bb') s) ->\n     rpo_lex bb' l' l -> rpo_lex_rest bb bb' l' l.\n\nLemma wf_rpo_lex_rest : forall bb bb', well_founded (rpo_lex_rest bb bb').\nProof.\nintro bb; unfold well_founded; induction bb.\n(* 1/2 bb = 0 *)\nintros bb' l; revert bb'; pattern l; apply list_rec2; clear l.\ninduction n as [ | n]; intros [ | a l] L bb'.\napply Acc_intro; intros k H; inversion H as [k' k'' L' Acc_k Acc_k' H' H1 H2]; clear H; subst; inversion H'.\ninversion L.\napply Acc_intro; intros k H; inversion H as [k' k'' L' Acc_k Acc_k' H' H1 H2]; clear H; subst; inversion H'.\napply Acc_intro; intros k H; inversion H as [k' k'' L' Acc_k Acc_k' H' H1 H2]; subst.\nassert (Acc_a : Acc (rpo bb') a).\napply Acc_k; left; apply Eq.\nassert (Acc_l' : forall s : term, mem equiv s l -> Acc (rpo bb') s).\nintros; apply Acc_k; right; assumption.\napply Acc_inv with (a :: l); [idtac | assumption].\nclear k H L' Acc_k' H'.\nclear -IHn Acc_a L Acc_l'.\nsimpl in L; generalize (le_S_n _ _ L); clear L; intro L.\nrevert l L Acc_l'; induction Acc_a as [a Acc_a IHa]; intros l L Acc_l.\nassert (Acc_l' := IHn _ L bb').\ninduction Acc_l' as [l Acc_l' IHl].\napply Acc_intro; intros l' H; inversion H as [ k k' L' Acc_al Acc_l'' H' H1 H2]; clear H; subst.\ndestruct L' as [L' | [L1 L2]]; [idtac | inversion L2].\ninversion H' as [u s' k' k'' u_lt_s | s' s'' k' k'' s'_eq_s k'_lt_l H1 H2 | u k']; clear H'; subst.\n(* 1/4 *)\napply IHa; trivial.\ninjection L'; clear L'; intro L'; rewrite <- L'; assumption.\nintros; apply Acc_l''; right; assumption.\n(* 1/3 *)\napply Acc_intro.\nintros k'' H'; apply Acc_inv with (a :: k').\napply IHl.\nconstructor; trivial.\nleft; injection L'; intro; assumption.\nintros; apply Acc_l''; right; assumption.\ninjection L'; clear L'; intro L'; rewrite <- L'; assumption.\nintros; apply Acc_l''; right; assumption.\ninversion  H' as [k1 k1' L'' Acc_l1 Acc_l1' H1' H1 H2]; subst.\nconstructor; trivial.\nsimpl; intros s [s_eq_a | s_in_k']; [idtac | apply Acc_l1; right; assumption].\napply Acc_intro; intros; apply Acc_inv with a.\napply Acc_intro; apply Acc_a; trivial.\nrewrite <- (equiv_rpo_equiv_1 _ s_eq_a); trivial.\ninversion H1' as [u s'' k1' k1'' u_lt_s | s1' s'' k1' k1'' s'_eq_s1 k'_lt_l1 H1 H2 | u k1']; clear H1'; subst.\nconstructor 1; trivial.\nrewrite <- (equiv_rpo_equiv_1 _ s'_eq_s); trivial.\nconstructor 2; trivial.\napply (equiv_trans _ _ equiv_equiv) with s'; trivial.\nconstructor 3.\n(* 1/2 *)\napply Acc_intro; intros l' H; inversion H as [ k k' L'' Acc_l1 Acc_l1' H' H1 H2]; clear H; subst.\ninversion H'.\n\n(* 1/1 induction step *)\nintros bb' l.\napply Acc_intro; intros k H; inversion H as [k' k'' L' Acc_k Acc_k' H' H1 H2]; subst.\ndestruct l as [ | a l].\ninversion H'.\napply Acc_inv with (a :: l); [idtac | assumption].\nclear -IHbb Acc_k.\nassert (Acc_a : Acc (rpo bb') a).\napply Acc_k; left; apply Eq.\nassert (Acc_l : forall s : term, mem equiv s l -> Acc (rpo bb') s).\nintros; apply Acc_k; right; assumption.\nrevert Acc_l; clear Acc_k.\nrevert l; induction Acc_a as [a Acc_a IHa]; intros l.\npattern l; apply (well_founded_ind (IHbb bb')); clear l; intros l IHl Acc_l.\napply Acc_intro; intros l' H; inversion H as [ k k' L Acc_al Acc_l' H' H1 H2]; clear H; subst.\ninversion H' as [u s' k' k'' u_lt_s | s' s'' k' k'' s'_eq_s k'_lt_l H1 H2 | u k']; clear H'; subst.\n(* 1/3 *)\napply IHa; trivial.\nintros; apply Acc_l'; right; assumption.\n(* 1/2 *)\napply Acc_intro.\nintros k'' H'; apply Acc_inv with (a :: k').\napply IHl; constructor.\ndestruct L as [L | [L1 L2]].\nleft; injection L; intro; assumption.\nright; split; apply le_S_n; assumption.\nintros; apply Acc_al; right; assumption.\nintros; apply Acc_l'; right; assumption.\nassumption.\napply Acc_inv; apply Acc_l'; right; assumption.\ninversion  H' as [ k1 k1' L' Acc_l1 Acc_l1' H1' H1 H2]; subst.\nconstructor; trivial.\nsimpl; intros s [s_eq_a | s_in_k']; [idtac | apply Acc_l1; right; assumption].\napply Acc_intro; intros; apply Acc_inv with a.\napply Acc_intro; apply Acc_a; trivial.\nrewrite <- (equiv_rpo_equiv_1 _ s_eq_a); trivial.\ninversion H1' as [u s'' k1' k1'' u_lt_s | s1' s'' k1' k1'' s'_eq_s1 k'_lt_l1 H1 H2 | u k1']; clear H1'; subst.\nconstructor 1; trivial.\nrewrite <- (equiv_rpo_equiv_1 _ s'_eq_s); trivial.\nconstructor 2; trivial.\napply (equiv_trans _ _ equiv_equiv) with s'; trivial.\nconstructor 3.\n(* 1/1 *)\napply Acc_intro; intros l' H; inversion H as [ k k' L' Acc_l1 Acc_l1' H' H1 H2]; clear H; subst.\ninversion H'.\nQed.\n\n(** Definition of a finer grain for multiset extension. *)\nInductive rpo_mul_step (bb : nat) : list term -> list term -> Prop :=\n  | List_mul_step : \n       forall a ls lc l l',  \n        permut0 equiv l' (ls ++ lc) -> permut0 equiv l (a :: lc) ->\n       (forall b, mem equiv b ls -> rpo bb b a) ->\n       rpo_mul_step bb l' l.\n\n(** The plain multiset extension is in the transitive closure of\nthe finer grain extension. *)\nLemma rpo_mul_trans_clos :\n  forall bb, inclusion _ (rpo_mul bb) (clos_trans _ (rpo_mul_step bb)).\nProof.\nintro bb; unfold inclusion; intros l' l H; \ninversion H as [a lg ls lc k k' P' P ls_lt_alg]; subst.\ngeneralize l' l a ls lc P P' ls_lt_alg;\nclear l' l a ls lc P P' ls_lt_alg H;\ninduction lg as [ | g lg]; intros l' l a ls lc P P' ls_lt_alg.\napply t_step; apply (@List_mul_step bb a ls lc); trivial.\nintros b b_in_ls; destruct (ls_lt_alg b b_in_ls) as [a' [[a'_eq_a | a'_in_nil] b_lt_a']].\nrewrite <- (equiv_rpo_equiv_1 _ a'_eq_a); trivial.\ncontradiction.\nassert (H: exists ls1, exists ls2, \n permut0 equiv ls (ls1 ++ ls2) /\\\n (forall b, mem equiv b ls1 -> rpo bb b g) /\\\n (forall b, mem equiv b ls2 -> exists a', mem equiv a' (a :: lg) /\\ rpo bb b a')).\nclear P'; induction ls as [ | s ls].\nexists (nil : list term); exists (nil : list term); intuition. reflexivity.\ndestruct IHls as [ls1 [ls2 [P' [ls1_lt_g ls2_lt_alg]]]].\nintros b b_in_ls; apply ls_lt_alg; right; trivial.\ndestruct (ls_lt_alg s) as [a' [[a'_eq_a | [a'_eq_g | a'_in_lg]] b_lt_a']].\nleft; reflexivity.\nexists ls1; exists (s :: ls2); repeat split; trivial.\nrewrite <- permut0_cons_inside; trivial. apply equiv_equiv.\nreflexivity.\nintros b [b_eq_s | b_in_ls2].\nexists a; split.\nleft; reflexivity.\nrewrite (equiv_rpo_equiv_2 _ b_eq_s).\nrewrite <- (equiv_rpo_equiv_1 _ a'_eq_a); trivial.\napply ls2_lt_alg; trivial.\nexists (s :: ls1); exists ls2; repeat split; trivial.\nsimpl; rewrite <- permut0_cons; trivial. apply equiv_equiv.\nreflexivity.\nintros b [b_eq_s | b_in_ls1].\nrewrite (equiv_rpo_equiv_2 _ b_eq_s).\nrewrite <- (equiv_rpo_equiv_1 _ a'_eq_g); trivial.\napply ls1_lt_g; trivial.\nexists ls1; exists (s :: ls2); repeat split; trivial.\nrewrite <- permut0_cons_inside; trivial. apply equiv_equiv.\nreflexivity.\nintros b [b_eq_s | b_in_ls2].\nexists a'; split.\nright; trivial.\nrewrite (equiv_rpo_equiv_2 _ b_eq_s); trivial.\napply ls2_lt_alg; trivial.\ndestruct H as [ls1 [ls2 [Pls [ls1_lt_g ls2_lt_alg]]]].\napply t_trans with (g :: ls2 ++ lc).\napply t_step; apply (@List_mul_step bb g ls1 (ls2 ++ lc)); auto.\nrewrite P'.\nrewrite ass_app; rewrite <- permut_app2; trivial. apply equiv_equiv. reflexivity.\napply (IHlg (g :: ls2 ++ lc) l a ls2 (g :: lc)); trivial.\nrewrite P.\nsimpl; rewrite <- permut0_cons;[|apply equiv_equiv|apply (Relation_Definitions.equiv_refl _ _ equiv_equiv)].\nrewrite <- permut0_cons_inside;[reflexivity|apply equiv_equiv|apply (Relation_Definitions.equiv_refl _ _ equiv_equiv)].  \nrewrite <- permut0_cons_inside;[reflexivity|apply equiv_equiv|apply (Relation_Definitions.equiv_refl _ _ equiv_equiv)].  \nQed.\n\nInductive rpo_mul_rest (bb : nat) : list term -> list term -> Prop :=\n| Rpo_mul_rest : \n     forall l l', (forall s, mem equiv s l -> Acc (rpo bb) s) -> \n                  (forall s, mem equiv s l' -> Acc (rpo bb) s) ->\n     rpo_mul bb l' l -> rpo_mul_rest bb l' l.\n\nInductive rpo_mul_step_rest (bb : nat) : list term -> list term -> Prop :=\n| Rpo_mul_step_rest : \n     forall l l', (forall s, mem equiv s l -> Acc (rpo bb) s) -> \n                  (forall s, mem equiv s l' -> Acc (rpo bb) s) ->\n     rpo_mul_step bb l' l -> rpo_mul_step_rest bb l' l.\n\nLemma rpo_mul_rest_trans_clos :\n  forall bb, inclusion _ (rpo_mul_rest bb) (clos_trans _ (rpo_mul_step_rest bb)).\nProof.\nintro bb; unfold inclusion; intros l' l H; \ninversion H as [k k' Acc_l Acc_l' H' H1 H2 ]; subst.\ninversion H' as [a lg ls lc k k' P' P ls_lt_alg]; subst.\ngeneralize l' l a ls lc P' P ls_lt_alg Acc_l Acc_l'; \nclear l' l a ls lc P' P ls_lt_alg H Acc_l Acc_l' H';\ninduction lg as [ | g lg]; intros l' l a ls lc P' P ls_lt_alg Acc_l Acc_l'.\napply t_step; apply Rpo_mul_step_rest; trivial;\napply (@List_mul_step bb a ls lc); trivial.\nintros b b_in_ls; destruct (ls_lt_alg b b_in_ls) as [a' [[a'_eq_a | a'_in_nil] b_lt_a']].\nrewrite <- (equiv_rpo_equiv_1 _ a'_eq_a); trivial.\ncontradiction.\nassert (H: exists ls1, exists ls2, \n permut0 equiv ls (ls1 ++ ls2) /\\\n (forall b, mem equiv b ls1 -> rpo bb b g) /\\\n (forall b, mem equiv b ls2 -> exists a', mem equiv a' (a :: lg) /\\ rpo bb b a')).\nclear P'; induction ls as [ | s ls].\nexists (nil : list term); exists (nil : list term); intuition. reflexivity.\ndestruct IHls as [ls1 [ls2 [P' [ls1_lt_g ls2_lt_alg]]]].\nintros b b_in_ls; apply ls_lt_alg; right; trivial.\ndestruct (ls_lt_alg s) as [a' [[a'_eq_a | [a'_eq_g | a'_in_lg]] b_lt_a']].\nleft; reflexivity.\nexists ls1; exists (s :: ls2); repeat split; trivial.\nrewrite <- permut0_cons_inside; trivial. apply equiv_equiv.\nreflexivity.\nintros b [b_eq_s | b_in_ls2].\nexists a; split.\nleft; reflexivity.\nrewrite (equiv_rpo_equiv_2 _ b_eq_s).\nrewrite <- (equiv_rpo_equiv_1 _ a'_eq_a); trivial.\napply ls2_lt_alg; trivial.\nexists (s :: ls1); exists ls2; repeat split; trivial.\nsimpl; rewrite <- permut0_cons; trivial. apply equiv_equiv.\nreflexivity.\nintros b [b_eq_s | b_in_ls1].\nrewrite (equiv_rpo_equiv_2 _ b_eq_s).\nrewrite <- (equiv_rpo_equiv_1 _ a'_eq_g); trivial.\napply ls1_lt_g; trivial.\nexists ls1; exists (s :: ls2); repeat split; trivial.\nrewrite <- permut0_cons_inside; trivial. apply equiv_equiv.\nreflexivity.\nintros b [b_eq_s | b_in_ls2].\nexists a'; split.\nright; trivial.\nrewrite (equiv_rpo_equiv_2 _ b_eq_s); trivial.\napply ls2_lt_alg; trivial.\ndestruct H as [ls1 [ls2 [Pls [ls1_lt_g ls2_lt_alg]]]].\napply t_trans with (g :: ls2 ++ lc).\napply t_step; apply Rpo_mul_step_rest; trivial.\nsimpl; intros s [g_eq_s | s_mem_ls2lc].\napply Acc_l.\nrewrite P; right; left; trivial.\napply Acc_l'.\nrewrite P'; rewrite <- mem_or_app.\nrewrite <- mem_or_app in s_mem_ls2lc.\ndestruct s_mem_ls2lc as [s_mem_ls2 | s_mem_lc].\nleft; rewrite Pls; rewrite <- mem_or_app; right; trivial.\nright; trivial.\napply (@List_mul_step bb g ls1 (ls2 ++ lc)); reflexivity || auto.\nrewrite P'; rewrite Pls; rewrite ass_app; reflexivity || auto.\napply (IHlg (g :: ls2 ++ lc) l a ls2 (g :: lc)); trivial.\nrewrite <- permut0_cons_inside; try reflexivity. apply equiv_equiv.\nrewrite P.\nrewrite <- permut0_cons;[|apply equiv_equiv|apply (Relation_Definitions.equiv_refl _ _ equiv_equiv)]. \nsimpl; rewrite <- permut0_cons_inside;[reflexivity|apply equiv_equiv|apply (Relation_Definitions.equiv_refl _ _ equiv_equiv)].\nsimpl; intros s [g_eq_s | s_mem_ls2lc].\napply Acc_l.\nrewrite P; right; left; trivial.\napply Acc_l'.\nrewrite P'; rewrite <- mem_or_app.\nrewrite <- mem_or_app in s_mem_ls2lc.\ndestruct s_mem_ls2lc as [s_mem_ls2 | s_mem_lc].\nleft; rewrite Pls; rewrite <- mem_or_app; right; trivial.\nright; trivial.\nQed.\n\n(** Splitting in two disjoint cases. *)\nLemma two_cases_rpo :\n forall bb a m n, \n rpo_mul_step bb n (a :: m) ->\n (exists a', exists n', equiv a a' /\\ permut0 equiv n (a' :: n') /\\ \n                                                           rpo_mul_step bb n' m) \\/\n (exists ls, (forall b, mem equiv b ls -> rpo bb b a) /\\ permut0 equiv n (ls ++ m)).\nProof.\nintros bb b m n M; inversion M as [a ls lc l l' P' P ls_lt_a]; subst.\nassert (b_mem_a_lc : mem equiv b (a :: lc)).\nrewrite <- (mem_permut0_mem equiv_equiv b P); left; reflexivity.\nsimpl in b_mem_a_lc; destruct b_mem_a_lc as [b_eq_a | b_mem_lc].\nright; exists ls; repeat split; trivial.\nintros c c_mem_ls; rewrite (equiv_rpo_equiv_1 _ b_eq_a).\napply ls_lt_a; trivial.\nrewrite P'; rewrite <- permut_app1.\nrewrite <- permut0_cons in P;  try (symmetry; trivial). apply equiv_equiv.\nsymmetry;trivial.\napply equiv_equiv.\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ b_mem_lc) as [b' [lc1 [lc2 [b_eq_b' [H _]]]]];\nsimpl in b_eq_b'; simpl in H.\nleft; exists b'; exists (ls ++ (lc1 ++ lc2)); repeat split; trivial.\nrewrite P'; subst lc.\nrewrite ass_app; apply permut0_sym. apply equiv_equiv.\nrewrite <- permut0_cons_inside;[|apply equiv_equiv|apply (Relation_Definitions.equiv_refl _ _ equiv_equiv)]. \nrewrite ass_app; reflexivity.\napply (@List_mul_step bb a ls (lc1 ++ lc2)); try reflexivity.\nrewrite app_comm_cons.\nrewrite (@permut0_cons_inside _ _ equiv_equiv _ _ m (a :: lc1) lc2 b_eq_b').\nrewrite P.\nsimpl; subst lc; reflexivity.\nauto.\nQed.\n\nLemma list_permut_map_acc :\n forall bb l l', permut0 equiv l l' ->\n Acc (rpo_mul_step_rest bb) l ->  Acc (rpo_mul_step_rest bb) l'.\nProof.\nintros bb l l' P A1; apply Acc_intro; intros l'' M2.\ninversion A1 as [H]; apply H; \ninversion M2 as [k' k'' Acc_l' Acc_l'' H']; subst.\ninversion H' as [a ls lc k' k'' P'' P' ls_lt_a]; subst.\napply Rpo_mul_step_rest; trivial.\nintros s s_in_l; apply Acc_l'; rewrite <- (mem_permut0_mem equiv_equiv s P); trivial.\napply (@List_mul_step bb a ls lc); trivial;\napply permut0_trans with l'; trivial. apply equiv_equiv.\nQed.\n\n(** Multiset extension of rpo on accessible terms lists is well-founded. *)\nLemma wf_rpo_mul_rest : forall bb, well_founded (rpo_mul_rest bb).\nProof.\nintro bb; apply wf_incl with (clos_trans _ (rpo_mul_step_rest bb)).\nunfold inclusion; apply rpo_mul_rest_trans_clos.\napply wf_clos_trans.\nunfold well_founded; intro l; induction l as [ | s l]. \n(* 1/2 l = nil *)\napply Acc_intro; intros m H; inversion H as [l l' Acc_l Acc_l' H']; subst;\ninversion H' as [a ls lc l l'  P P']; subst.\nassert (L := permut_length P'); discriminate.\n(* 1/1 induction step *)\nassert (Acc (rpo bb) s -> Acc (rpo_mul_step_rest bb) (s :: l)).\nintro Acc_s; generalize l IHl; clear l IHl; \npattern s; apply Acc_ind with term (rpo bb); trivial; clear s Acc_s.\nintros s Acc_s IHs l Acc_l; pattern l; \napply Acc_ind with (list term) (rpo_mul_step_rest bb); trivial; clear l Acc_l.\nintros l Acc_l IHl; apply Acc_intro.\nintros l' H; inversion H as [s_k k' Acc_s_l Acc_l' H']; subst.\ndestruct (@two_cases_rpo bb s l l' H') as [[s' [n' [s_eq_s' [P H'']]]] | [ls [ls_lt_s P]]].\n(* 1/3 First case *)\napply (@list_permut_map_acc bb (s :: n')).\nrewrite P; rewrite <- permut0_cons; reflexivity || apply equiv_equiv || auto. symmetry;assumption.\napply Acc_intro; intros l'' l''_lt_s'_n; apply Acc_inv with (s :: n').\napply IHl; apply Rpo_mul_step_rest; trivial.\nintros; apply Acc_s_l; right; trivial.\nintros s'' s''_in_n'; apply Acc_l'; rewrite (mem_permut0_mem equiv_equiv s'' P); right; trivial.\ntrivial.\n(* 1/2 Second case *)\napply (@list_permut_map_acc bb (ls ++ l)).\napply permut0_sym; trivial. apply equiv_equiv.\nclear P; induction ls as [ | b ls].\nsimpl; apply Acc_intro; trivial.\nsimpl; apply IHs.\napply ls_lt_s; left; reflexivity.\napply IHls; intros; apply ls_lt_s; right; trivial.\napply Acc_intro.\nintros l' H'.\napply Acc_inv with (s :: l); trivial.\ninversion H' as [k k' Acc_s_l Acc_l']; subst;\napply H; apply Acc_s_l; left; reflexivity.\nQed.\n\nInductive rpo_rest (bb : nat) : (symbol * list term) -> (symbol * list term) -> Prop :=\n | Top_gt_rest : \n       forall f g l l', prec Prec g f -> \n       (forall s, mem equiv s l -> Acc (rpo bb) s) -> (forall s, mem equiv s l' -> Acc (rpo bb) s) ->\n       rpo_rest bb (g, l') (f, l)\n  | Top_eq_lex_rest : \n        forall f g l l', status Prec f = Lex -> status Prec g = Lex -> prec_eq Prec f g -> (length l = length l' \\/ length l' <= bb /\\ length l <= bb) -> rpo_lex bb l' l -> \n        (forall s, mem equiv s l -> Acc (rpo bb) s) -> (forall s, mem equiv s l' -> Acc (rpo bb) s) ->\n        rpo_rest bb (f, l') (g, l)\n  | Top_eq_mul_rest : \n        forall f g l l', status Prec f = Mul -> status Prec g = Mul -> prec_eq Prec f g -> rpo_mul bb l' l -> \n        (forall s, mem equiv s l -> Acc (rpo bb) s) -> (forall s, mem equiv s l' -> Acc (rpo bb) s) ->\n        rpo_rest bb (f, l') (g, l).\n\nLemma rpo_rest_prec_eq : forall bb f g l, prec_eq Prec f g -> Acc (rpo_rest bb) (f, l) -> Acc (rpo_rest bb) (g, l).\nProof.\nintros.\ndestruct H0.\napply Acc_intro.\nintros.\napply H0. clear H0.\ndestruct y.\ninversion H1.\napply Top_gt_rest.\napply prec_eq_prec1 with g. trivial. apply prec_eq_sym. trivial. trivial. trivial.\napply Top_eq_lex_rest; trivial. assert (H13:= prec_eq_status Prec f g). assert (H14: status Prec f = status Prec g). apply H13. trivial. rewrite  H14. trivial. \napply prec_eq_transitive with g; trivial. \napply prec_eq_sym; trivial.\napply Top_eq_mul_rest; trivial.\n assert (H13:= prec_eq_status Prec f g). assert (H14: status Prec f = status Prec g). apply H13. trivial. rewrite  H14. trivial. \napply prec_eq_transitive with g; trivial. \napply prec_eq_sym; trivial.\nQed.\n\nLemma wf_rpo_rest : well_founded (prec Prec) -> forall bb, well_founded (rpo_rest bb).\nProof.\nintros wf_prec bb; unfold well_founded; intros [f l]; generalize l; clear l; \npattern f; apply (well_founded_induction_type wf_prec); clear f.\nintros f IHf l; assert (Sf : forall f', f' = f -> status Prec f' = status Prec f).\nintros; subst; trivial.\ndestruct (status Prec f); generalize (Sf _ (refl_equal _)); clear Sf; intro Sf.\npattern l; apply (well_founded_induction_type (wf_rpo_lex_rest bb bb)); clear l.\nintros l IHl; apply Acc_intro; intros [g l'] H. \ninversion H as [ f' g' k k' g_prec_f Acc_l Acc_l' \n                      | f' g' k k' Sf' Sg' eq_f'_g' L H' Acc_l Acc_l'\n                      | f' g' k k' Sf' Sg' eq_f'_g' H' Acc_l Acc_l' ]; subst.\napply IHf; trivial.\napply rpo_rest_prec_eq with f. apply prec_eq_sym; trivial.\napply rpo_rest_prec_eq with f. apply prec_eq_refl.\napply IHl; apply Rpo_lex_rest; trivial.\nrewrite Sf in Sg'; discriminate.\n\n\npattern l; apply (well_founded_induction_type (wf_rpo_mul_rest bb)); clear l.\nintros l IHl; apply Acc_intro; intros [g l'] H; \ninversion H as [ f' g' k k' g_prec_f Acc_l Acc_l' \n                         | f' k k' Sf' L H' Acc_l Acc_l'\n                         | f' k k' Sf' H' Acc_l Acc_l' ]; subst.\napply IHf; trivial.\nabsurd (Lex = Mul); [discriminate | apply trans_eq with (status Prec f); auto].\napply rpo_rest_prec_eq with f. apply prec_eq_sym; trivial.\napply IHl; apply Rpo_mul_rest; trivial.\nQed.\n\nLemma acc_build :\n  well_founded (prec Prec) -> forall bb f_l,\n  match f_l with (f, l) => \n  (forall t, mem equiv t l -> Acc (rpo bb) t) ->  Acc (rpo bb) (Term f l)\n  end.\nProof.\nintros wf_prec bb f_l; pattern f_l;\napply (well_founded_induction_type (wf_rpo_rest wf_prec bb)); clear f_l.\nintros [f l] IH Acc_l; apply Acc_intro;\nintros s; pattern s; apply term_rec3_mem; clear s.\nintros v _; apply Acc_intro.\nintros t t_lt_v; inversion t_lt_v.\nintros g k IHl gk_lt_fl;\ninversion gk_lt_fl as [ f' l' s' t t_in_l H' \n                               | f' g' k' l' g_prec_f \n                               | f' g' k' l' Sf Sg f_eq_g L H' H''\n                               | f' g' k' l' Sf Sg f_eq_g H']; subst.\n(* 1/4 Subterm case *)\nassert (Acc_t := Acc_l _ t_in_l).\nsubst; inversion H' as [s' t' s_eq_t | s' t' s_lt_t ]; \nsubst s' t'; [idtac | apply Acc_inv with t; trivial ].\napply Acc_intro; intro u.\nrewrite (@equiv_rpo_equiv_1 _ (Term g k) t); trivial;\nintro; apply Acc_inv with t; trivial.\n(* 1/3 Top gt *)\nassert (Acc_k : forall s, mem equiv s k -> Acc (rpo bb) s).\nintros s s_mem_k; apply IHl; trivial.\napply H; trivial.\napply (IH (g,k)); trivial.\napply Top_gt_rest; trivial.\n(* 1/2 Top_eq_lex *)\nassert (Acc_k : forall s, mem equiv s k -> Acc (rpo bb) s).\nintros s s_mem_k; apply IHl; trivial.\napply H''; trivial.\napply (IH (g,k)); trivial.\napply Top_eq_lex_rest; trivial.\n(* 1/1 Top_eq_mul *)\nassert (Acc_k : forall s, mem equiv s k -> Acc (rpo bb) s).\nintros s s_mem_k; apply IHl; trivial.\napply rpo_trans with (Term g k); trivial; apply Subterm with s; trivial; \napply Equiv; apply Eq.\napply (IH (g,k)); trivial.\napply Top_eq_mul_rest; trivial.\nQed.\n\n(** ** Main theorem: when the precedence is well-founded, so is the rpo. *)\nLemma wf_rpo : well_founded (prec Prec) -> forall bb, well_founded (rpo bb).\nProof.\nintros wf_prec bb;\nunfold well_founded; intro t; pattern t; apply term_rec3_mem; clear t.\nintro v; apply Acc_intro; intros s s_lt_t; inversion s_lt_t.\nintros f l Acc_l; apply (acc_build wf_prec bb (f,l)); trivial.\nQed.\n\n(** ** RPO is compatible with the instanciation by a substitution. *)\nLemma equiv_subst :\n  forall s t, equiv s t -> \n  forall sigma, equiv (apply_subst sigma s) (apply_subst sigma t).\nProof.\nintros s t; generalize s; clear s.\npattern t; apply term_rec3_mem; clear t.\nintros v s v_eq_s; inversion v_eq_s; subst; intro sigma; apply Eq.\nintros f l IHl s fl_eq_s sigma; \ninversion fl_eq_s as [ s' \n                               | f' g l1 l2 Sf Sg f'_eq_g l1_eq_l2\n                               | f' g l1 l2 Sf Sg f'_eq_g P ]; subst.\n(* 1/3 Syntactic equality *)\napply Eq.\n(* 1/2 Lex top symbol *)\nsimpl; apply Eq_lex; trivial.\ngeneralize l1 l1_eq_l2; clear fl_eq_s l1 l1_eq_l2; \ninduction l as [ | s l]; intros l1 l1_eq_l2;\ninversion l1_eq_l2 as [ | s1 s' l1' l' s1_eq_s' l1'_eq_l']; subst.\nsimpl; apply Eq_list_nil.\nsimpl; apply Eq_list_cons.\napply IHl; trivial; left; reflexivity.\napply IHl0; trivial.\nintros t t_in_l; apply IHl; right; trivial.\n(* 1/1 Mul top symbol *)\nsimpl; apply Eq_mul; trivial.\napply (permut_map (A := term) (B := term) (A' := term) (B' := term) (R := equiv)).\nintros a1 a2 a1_in_l1 _ a1_eq_a2; symmetry; apply IHl.\nrewrite <- (mem_permut0_mem equiv_equiv a1 P).\napply in_impl_mem; trivial.\nintros; apply Eq.\nsymmetry; trivial.\ntrivial.\nQed.\n\nLemma rpo_subst :\n  forall bb s t, rpo bb s t -> \n  forall sigma, rpo bb (apply_subst sigma s) (apply_subst sigma t).\nProof.\nintro bb.\ncut (forall p, match p with \n            (s,t) => rpo bb s t -> \n              forall sigma, rpo bb (apply_subst sigma s) (apply_subst sigma t)\n        end).\nintros H s t s_lt_t sigma; apply (H (s,t)); trivial.\nintro p; pattern p; refine (well_founded_ind wf_size2 _ _ _); clear p.\nintros [s t] IH s_lt_t sigma.\ninversion s_lt_t as [ f l s' t' t'_mem_l R' \n                       | f g l l' R' R'' \n                       | f g l l' f_lex g_lex f_eq_g L Rlex R' H2 H3\n                       | f g l l' f_mul g_mul f_eq_g Rmul R' H2 ]; subst.\n(* 1/4 case Subterm *)\nsimpl; apply Subterm with (apply_subst sigma t').\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ t'_mem_l) as [t'' [l1 [l2 [t'_eq_t'' [H _]]]]];\nsimpl in t'_eq_t''; simpl in H; subst l.\nrewrite map_app; rewrite <- mem_or_app.\nright; left; apply equiv_subst; trivial.\ninversion R' as [ s' R'' | s' t'' R'' ]; subst. \napply Equiv; apply equiv_subst; trivial.\napply Lt; apply (IH (s,t')); trivial.\napply size2_lex2_mem; trivial.\n(* 1/3 case Top_gt *)\nsimpl; apply Top_gt; trivial.\nintros s' s'_mem_l'_sigma; \ndestruct (mem_split_set _ _ equiv_bool_ok _ _ s'_mem_l'_sigma) as [s'' [l1 [l2 [s'_eq_s'' [H _]]]]];\nsimpl in s'_eq_s''; simpl in H.\nrewrite (equiv_rpo_equiv_2 _ s'_eq_s'').\nassert (s''_in_l'_sigma : In s'' (map (apply_subst sigma) l')).\nrewrite H; apply in_or_app; right; left; trivial.\nrewrite in_map_iff in s''_in_l'_sigma.\ndestruct s''_in_l'_sigma as [u [s_eq_u_sigma u_in_l']].\nsubst s''; \nreplace (Term f (map (apply_subst sigma) l)) with \n              (apply_subst sigma (Term f l)); trivial.\napply (IH (u, Term f l)).\napply size2_lex1; trivial.\napply rpo_trans with (Term g l'); trivial.\napply Subterm with u.\napply in_impl_mem; trivial.\nexact Eq.\napply Equiv; apply Eq.\n(* 1/2 case Top_eq_lex *)\nsimpl; apply Top_eq_lex; trivial.\ndo 2 rewrite length_map; assumption.\ngeneralize l Rlex IH; clear l s_lt_t Rlex R' IH L;\ninduction l' as [ | s' l' ]; intros l Rlex IH; \ninversion Rlex as [s'' t' k k' s'_lt_t' L | s'' t' k k' s'_eq_t' k_lt_k' | ]; subst; simpl.\napply List_nil.\napply List_gt.\napply (IH (s',t')); trivial.\napply size2_lex1; left; trivial.\napply List_eq.\napply equiv_subst; trivial.\napply IHl'; trivial.\nintros [s t] S s_lt_t tau; apply (IH (s,t)); trivial.\napply o_size2_trans with (Term f l', Term f k'); trivial.\napply size2_lex1_bis.\nintros s' s'_mem_l'_sigma; \ndestruct (mem_split_set _ _ equiv_bool_ok _ _ s'_mem_l'_sigma) as [s'' [l1 [l2 [s'_eq_s'' [H _]]]]];\nsimpl in s'_eq_s''; simpl in H.\nrewrite (equiv_rpo_equiv_2 _ s'_eq_s'').\nassert (s''_in_l'_sigma : In s'' (map (apply_subst sigma) l')).\nrewrite H; apply in_or_app; right; left; trivial.\nrewrite in_map_iff in s''_in_l'_sigma.\ndestruct s''_in_l'_sigma as [u [s_eq_u_sigma u_in_l']].\nsubst s''; \nreplace (Term f (map (apply_subst sigma) l)) with \n              (apply_subst sigma (Term f l)); trivial.\napply (IH (u, Term g l)).\napply size2_lex1; trivial.\napply rpo_trans with (Term f l'); trivial.\napply Subterm with u.\napply in_impl_mem; trivial.\nexact Eq.\napply Equiv; apply Eq.\n(* 1/1 case Top_eq_mul *)\nsimpl; apply Top_eq_mul; trivial;\ninversion Rmul as [ a lg ls lc l0 k0 Pk Pl ls_lt_alg]; subst.\napply (@List_mul bb (apply_subst sigma a) (map (apply_subst sigma) lg)\n(map (apply_subst sigma) ls) (map (apply_subst sigma) lc)).\nrewrite <- map_app; apply permut_map with equiv; trivial.\nintros b b' _ _ b_eq_b'; apply equiv_subst; trivial.\nrewrite <- map_app.\nrefine (@permut_map term term term term equiv \n                    equiv (apply_subst sigma) _ _ (a :: lg ++ lc) _ _); trivial.\nintros b b' b_in_l _ b_eq_b'; apply equiv_subst; trivial.\nintros b b_mem_ls_sigma; \ndestruct (mem_split_set _ _ equiv_bool_ok _ _ b_mem_ls_sigma) as [b' [ls1 [ls2 [b_eq_b' [H _]]]]];\nsimpl in b_eq_b'; simpl in H.\nassert (b'_in_ls_sigma : In b' (map (apply_subst sigma) ls)).\nrewrite H; apply in_or_app; right; left; trivial.\nrewrite in_map_iff in b'_in_ls_sigma.\ndestruct b'_in_ls_sigma as [b'' [b''_sigma_eq_b' b''_in_ls]].\ndestruct (ls_lt_alg b'') as [a' [a'_mem_alg b''_lt_a']].\napply in_impl_mem; trivial.\nexact Eq.\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ a'_mem_alg) as [a'' [alg' [alg'' [a'_eq_a'' [H' _]]]]];\nsimpl in a'_eq_a''; simpl in H'.\nexists (apply_subst sigma a''); split; trivial.\napply in_impl_mem.\nexact Eq.\nrewrite (in_map_iff (apply_subst sigma) (a :: lg)).\nexists a''; split; trivial.\nrewrite H'; apply in_or_app; right; left; trivial.\nrewrite (equiv_rpo_equiv_2 _ b_eq_b').\nsubst b'; apply (IH (b'',a'')).\napply size2_lex1_mem.\nrewrite Pk; rewrite <- mem_or_app; left;\napply in_impl_mem; trivial. \nexact Eq.\nrewrite <- (equiv_rpo_equiv_1 _ a'_eq_a''); trivial.\nQed.\n\nLemma rpo_eq_subst :\n  forall bb s t, rpo_eq bb s t -> \n  forall sigma, rpo_eq bb (apply_subst sigma s) (apply_subst sigma t).\nProof.\nintros bb s t H sigma; inversion H as [t1 t2 Heq | t1 t2 Hlt]; subst t1 t2.\napply Equiv; apply equiv_subst; assumption.\napply Lt; apply rpo_subst; assumption.\nQed.\n\n(** ** RPO is compatible with adding context. *)\nLemma equiv_add_context :\n forall p ctx s t, equiv s t -> is_a_pos ctx p = true -> \n  equiv (replace_at_pos ctx s p) (replace_at_pos ctx t p).\nProof.\nintro p; induction p as [ | i p ]; intros ctx s t R H; trivial;\ndestruct ctx as [ v | f l ].\ndiscriminate.\nassert (Status : forall g, g = f -> status Prec g = status Prec f).\nintros; subst; trivial.\ndo 2 (rewrite replace_at_pos_unfold);\ndestruct (status Prec f); generalize (Status f (refl_equal _)); clear Status; \nintro Status.\n(* 1/2 Lex case *)\napply Eq_lex; trivial.\napply prec_eq_refl.\ngeneralize i H; clear i H; induction l as [ | u l]; intros i H; simpl. \napply Eq_list_nil.\ndestruct i as [ | i].\napply Eq_list_cons. \nsimpl in H; apply IHp; trivial.\ngeneralize l; intro l'; induction l' as [ | u' l'].\napply Eq_list_nil.\napply Eq_list_cons; trivial; reflexivity.\napply Eq_list_cons.\nreflexivity.\napply IHl; trivial.\n(* 1/1 Mul case *)\napply Eq_mul; trivial.\napply prec_eq_refl.\ngeneralize i H; clear i H; induction l as [ | u l]; intros i H; simpl; reflexivity || auto.\ndestruct i as [ | i].\nrewrite <- permut0_cons.\nreflexivity.\napply equiv_equiv. \nsimpl in H; apply IHp; trivial.\nrewrite <- permut0_cons.\napply IHl; trivial. apply equiv_equiv.\nreflexivity.\nQed.\n\nLemma rpo_add_context :\n forall bb p ctx s t, rpo bb s t -> is_a_pos ctx p = true -> \n  rpo bb (replace_at_pos ctx s p) (replace_at_pos ctx t p).\nProof.\nintros bb p; induction p as [ | i p ]; intros ctx s t R H; trivial;\ndestruct ctx as [ v | f l ].\ndiscriminate.\nassert (Status : forall g, g = f -> status Prec g = status Prec f).\nintros; subst; trivial.\ndo 2 (rewrite replace_at_pos_unfold);\ndestruct (status Prec f); generalize (Status f (refl_equal _)); clear Status; \nintro Status.\n(* 1/2 Lex case *)\napply Top_eq_lex; trivial. \napply prec_eq_refl.\nleft; clear; revert l; induction i as [ | i]; intros [ | a l]; simpl; trivial.\nrewrite IHi; apply refl_equal.\ngeneralize i H; clear i H; induction l as [ | u l]; intros i H; simpl.\nsimpl in H; destruct i; discriminate.\ndestruct i as [ | i].\napply List_gt; trivial.\nsimpl in H; apply IHp; trivial.\napply List_eq.\nreflexivity.\napply IHl; trivial.\nintros s' s'_mem_ls;\nassert (H' : exists s'', rpo_eq bb s' s'' /\\ mem equiv s'' (replace_at_pos_list l t i p)). \ngeneralize i H s' s'_mem_ls; clear i H s' s'_mem_ls; \ninduction l as [ | u l]; intros i H; simpl.\nintros; contradiction.\ndestruct i as [ | i].\nintros s' [s'_eq_s'' | s'_mem_l].\nexists (replace_at_pos u t p); split.\napply Lt; rewrite (equiv_rpo_equiv_2 _ s'_eq_s'').\napply IHp; trivial.\nleft; reflexivity.\nexists s'; split.\napply Equiv; apply Eq.\nright; trivial.\nintros s' [s'_eq_u | s'_mem_l].\nexists u; split.\napply Equiv; trivial.\nleft; reflexivity.\nsimpl in IHl; simpl in H.\ndestruct (IHl i H s' s'_mem_l) as [s'' [s'_le_s'' s''_mem_l']].\nexists s''; split; trivial.\nright; trivial.\ndestruct H' as [s'' [s'_le_s'' s''_mem_l']].\napply Subterm with s''; trivial.\n(* 1/1 Mul case *)\napply Top_eq_mul; trivial.\napply prec_eq_refl.\ngeneralize i H; clear i H; induction l as [ | u l]; intros i H; simpl.\nsimpl in H; destruct i; discriminate.\ndestruct i as [ | i].\napply (@List_mul bb (replace_at_pos u t p) nil (replace_at_pos u s p :: nil) l); reflexivity || auto.\nintros b [b_eq_s' | b_mem_nil].\nexists (replace_at_pos u t p); split.\nleft; reflexivity.\nrewrite (equiv_rpo_equiv_2 _ b_eq_s').\napply IHp; trivial.\ncontradiction.\nsimpl in IHl; simpl in H; assert (H' := IHl i H).\ninversion H' as [a lg ls lc l' l'' ls_lt_alg P1 P2]; subst.\napply (@List_mul bb a lg ls (u :: lc)); trivial.\nrewrite <- permut0_cons_inside; trivial; try reflexivity. apply equiv_equiv.\nrewrite app_comm_cons.\nrewrite <- permut0_cons_inside; trivial; try reflexivity. apply equiv_equiv.\nQed.\n\nLemma rpo_eq_add_context :\n forall bb p ctx s t, rpo_eq bb s t -> is_a_pos ctx p = true -> \n  rpo_eq bb (replace_at_pos ctx s p) (replace_at_pos ctx t p).\nProof.\nintros bb p ctx s t H P; inversion H; clear H; subst.\napply Equiv; apply equiv_add_context; assumption.\napply Lt; apply rpo_add_context; assumption.\nQed.\n\nFunction remove_equiv (t : term) (l : list term) {struct l} : option (list term) :=\n  match l with\n     | nil => @None _\n     | a :: l => \n         if  equiv_dec t a\n         then Some l\n         else\n            match remove_equiv t l with\n            | None => @ None _\n            | Some l' => Some (a :: l')\n            end\n    end.\n\nFunction  remove_equiv_list (l1 l2 : list term) {struct l1} : (list term) * (list term) :=\n    match l1, l2 with\n    | _, nil => (l1,l2)\n    | nil, _ => (l1,l2)\n    | a1 :: l1, l2 =>\n          match remove_equiv a1 l2 with\n          | Some l2' =>  remove_equiv_list l1 l2' \n          | None =>\n               match remove_equiv_list l1 l2 with\n                      | (l1',l2') => (a1 :: l1', l2')\n               end\n          end\n   end.\n\nLemma remove_equiv_is_sound_some : \n  forall t l l', remove_equiv t l = Some l' -> \n    {t' | equiv t t' /\\ permut0 equiv l (t' :: l')}.\nProof.\nintros t l; induction l as [ | a l]; intros l' R; simpl in R.\ndiscriminate.\ndestruct (equiv_dec t a) as [t_eq_a | t_diff_a].\ninjection R; intro; subst l'; clear R;\nexists a; split; reflexivity || auto.\ndestruct (remove_equiv t l) as [ l'' | ].\ninjection R; intro; subst l'; clear R.\ndestruct (IHl l'' (refl_equal _)) as [t' [t_eq_t' P]].\nexists t'; split; trivial.\nrewrite <- (@permut0_cons_inside _ _ equiv_equiv a a l (t' :: nil) l''); trivial.\nreflexivity.\ndiscriminate.\nQed.\n\nLemma remove_equiv_is_sound_none : \n  forall t l, remove_equiv t l = None -> forall t', mem equiv t' l -> ~ (equiv t t').\nProof.\nintros t l; \nfunctional induction (remove_equiv t l) as \n  [ \n  | H1 a l t' t_eq_a _ \n  | H1 a l t' t_diff_a _ IH H \n  | H1 a l t' t_diff_a _ IH l' H ].\n(* 1/4 *) \nsimpl; intros; contradiction.\n(* 1/3 *)\nintros; discriminate.\n(* 1/2 *)\nintros _; rewrite H in IH; intros t' [a_eq_t' | t'_mem_l].\nintro t_eq_t'; apply t_diff_a.\ntransitivity t'; trivial.\napply IH; trivial.\n(* 1/1 *)\nintros; discriminate.\nQed.\n\nLemma size2_lex2_bis_prec_eq :\n  forall t f g l s, prec_eq Prec f g -> o_size2 (s,Term f l) (s, Term g (t :: l)).\nProof.\nintros a f g l s f_eq_g;\nunfold o_size2, size2, lex;\ngeneralize (beq_nat_ok (size s) (size s)); case (beq_nat (size s) (size s)); [intros _ | intro s_diff_s].\ndo 2 rewrite size_unfold; apply plus_lt_compat_l; simpl.\nexact (plus_le_compat_r _ _ (list_size size l) (size_ge_one a)).\napply False_rec; apply s_diff_s; reflexivity.\nDefined.\n\n \nLemma remove_equiv_list_is_sound :\n  forall l1 l2, \n    match remove_equiv_list l1 l2 with\n         | (l1',l2') => \n             {lc | permut0 equiv l1 (l1' ++ lc) /\\ permut0 equiv l2 (l2' ++ lc) /\\\n                           (forall t1 t2, mem equiv t1 l1' -> mem equiv t2 l2' -> ~ equiv t1 t2)}\n   end.            \nProof.\nintros l1 l2; \nfunctional induction (remove_equiv_list l1 l2) as\n[ l1\n| H1 l2 H2 H3 H4 H'\n| H1 l2 t1 l1 H2 H3 H4 _ l2' H IH \n| H1 l2 t1 l1 H2 H3 H4 H' H IH l1' l2' R].\n(* 1/ 4 *)\nexists (@nil term); simpl; repeat split; reflexivity || auto.\nrewrite <- app_nil_end; reflexivity || auto.\n(* 1/3 *)\ndestruct l2 as [ | t2 l2].\ncontradiction.\nexists (@nil term); simpl; repeat split; reflexivity || auto.\nrewrite <- app_nil_end; reflexivity || auto.\n(* 1/2 *)\ndestruct (@remove_equiv_is_sound_some t1 l2 l2' H) as [t2 [t1_eq_t2 P2]].\ndestruct (remove_equiv_list l1 l2') as [l1'' l2''].\ndestruct IH as [lc [P1 [P2' D]]].\nexists (t1 :: lc); repeat split; reflexivity || auto.\nrewrite <- permut0_cons_inside; trivial. apply equiv_equiv.\nreflexivity.\nrewrite P2; rewrite <- permut0_cons_inside; trivial. apply equiv_equiv.\nsymmetry; trivial.\n(* 1/1 *)\nrewrite R in IH.\ndestruct IH as [lc [P1 [P2 D]]].\nexists lc; repeat split; auto.\nsimpl; rewrite <- permut0_cons; trivial. apply equiv_equiv.\nreflexivity.\nintros u1 u2 [t1_eq_u1 | u1_mem_l1'] u2_mem_u2'.\nassert (H'' := @remove_equiv_is_sound_none t1 l2 H).\nintro u1_eq_u2; apply (H'' u2).\nrewrite P2; rewrite <- mem_or_app; left; trivial.\ntransitivity u1; trivial.\nsymmetry; trivial.\napply D; trivial.\nQed.\n\nLemma rpo_dec : forall bb t1 t2, {rpo bb t1 t2}+{~rpo bb t1 t2}.\nProof.\nintro bb.\ncut (forall p, match p with (t2,t1) =>\n                              {rpo bb t1 t2}+{~rpo bb t1 t2}\n                 end).\nintros H t1 t2; apply (H (t2,t1)).\nintro p; pattern p; refine (well_founded_induction wf_size2 _ _ _); clear p.\nintros [[v | f l] t1] IH.\n(* 1/2 t2 is a variable *)\nright; intro t1_lt_t2; inversion t1_lt_t2.\n(* 1/1 t2 is a compound term *)\n(* Try the Subterm case *)\nassert (H : {t | mem equiv t l /\\ rpo_eq bb t1 t}+{~exists t, mem equiv t l /\\ rpo_eq bb t1 t}).\ninduction l as [ | s l].\nright; intros [t [t_mem_nil _]]; contradiction.\ndestruct (equiv_dec t1 s) as [t1_eq_s | t1_diff_s].\nleft; exists s; split.\nleft; reflexivity.\napply Equiv; trivial.\ndestruct (IH (s,t1)) as [t1_lt_s | not_t1_lt_s].\napply size2_lex1; left; trivial.\nleft; exists s; split.\nleft; reflexivity.\napply Lt; trivial.\ndestruct IHl as [Ok | Ko].\nintros [t2 t1'] H; apply (IH (t2,t1')).\napply o_size2_trans with (Term f l, t1); trivial.\napply size2_lex1_bis.\ndestruct Ok as [t [t_mem_l t1_le_t]].\nleft; exists t; split; trivial.\nright; trivial.\nright; intros [t [[s_eq_t | t_mem_l] t1_le_t]].\ndestruct t1_le_t.\napply t1_diff_s; transitivity t'; trivial; symmetry; trivial.\napply not_t1_lt_s; rewrite <- (equiv_rpo_equiv_1 _ s_eq_t); trivial.\napply Ko; exists t; split; trivial.\ndestruct H as [[t [t_mem_l t1_le_t]] | H].\nleft; apply Subterm with t; trivial.\n(* Subterm has failed, trying Top_eq_lex or Top_eq_mul *)\ndestruct t1 as [v | g k].\n(* 1/2 t1 is a variable, t2 is a compound term *)\nright; intro v_lt_fl; inversion v_lt_fl; subst.\napply H; exists s; split; trivial.\n(* 1/1 t1 and t2 are compound terms *)\n case_eq (prec_eq_bool Prec g f); [intro g_eq_f | intro g_diff_f].\n(* 1/2 g = f *)\nassert (f_eq_g: prec_eq Prec f g).\nassert (H1:= prec_eq_bool_ok Prec). assert (H1':= H1 g f). rewrite g_eq_f in H1'. apply prec_eq_sym; trivial.\nassert (Sf_eq_Sg: status Prec g = status Prec f). apply prec_eq_status; apply prec_eq_sym; trivial.\ncase_eq (status Prec f); intro Sf.\n(* 1/3 Trying Top_eq_lex, status f = Lex *)\nassert (H' : {rpo_lex bb k l}+{~rpo_lex bb k l}).\ngeneralize k IH; clear k IH H; induction l as [ | t l]; intros k IH.\nright; intro k_lt_nil; inversion k_lt_nil.\ndestruct k as [ | s k].\nleft; apply List_nil.\ndestruct (IH (t,s)) as [s_lt_t | not_s_lt_t].\napply size2_lex1; left; trivial.\nleft; apply List_gt; trivial.\ndestruct (equiv_dec s t) as [s_eq_t | s_diff_t].\ndestruct (IHl k) as [k_lt_l | not_k_lt_l].\nintros [t2 t1] H; apply (IH (t2,t1)).\napply o_size2_trans with (Term f l, Term g k); trivial.\napply size2_lex1_bis.\nleft; apply List_eq; trivial.\nright; intro sk_lt_tl; inversion sk_lt_tl; subst.\nabsurd (rpo bb s t); trivial.\nabsurd (rpo_lex bb k l); trivial.\nright; intro sk_lt_tl; inversion sk_lt_tl; subst.\nabsurd (rpo bb s t); trivial.\nabsurd (equiv s t); trivial.\ndestruct H' as [k_lt_l | not_k_lt_l].\nlet P := constr:(forall (s:term), mem equiv s k -> rpo bb s (Term f l)) in \nassert (H'' : { P }+{~P}).\nclear k_lt_l H; induction k as [ | s k].\nleft; intros s s_mem_nil; contradiction.\ndestruct (IH (Term f l, s)) as [s_lt_fl | not_s_lt_fl].\napply size2_lex2; left; trivial.\ndestruct IHk as [Ok | Ko].\nintros [t2 t1] H'; apply (IH (t2,t1)).\napply o_size2_trans with (Term f l, Term f k); trivial.\napply size2_lex2_bis_prec_eq; trivial.\nleft; intros s' [s_eq_s' | s'_mem_k].\nrewrite (equiv_rpo_equiv_2 _ s_eq_s'); trivial.\napply Ok; trivial.\nright; intro H; apply Ko.\nintros s' s'_mem_k; apply H; right; trivial.\nright; intro H; apply not_s_lt_fl; apply H; left; reflexivity.\ndestruct H'' as [Ok | Ko].\ndestruct (eq_nat_dec (length l) (length k)).\nleft; apply Top_eq_lex; trivial. rewrite Sf_eq_Sg; trivial. apply prec_eq_sym; trivial. left; trivial.\ndestruct (le_lt_dec (length k) bb).\ndestruct (le_lt_dec (length l) bb).\nleft; apply Top_eq_lex; trivial. rewrite Sf_eq_Sg; trivial. apply prec_eq_sym; trivial. right; split;  assumption.\nright; intro fk_lt_fl; inversion fk_lt_fl; subst.\napply H; exists s; split; assumption.\napply prec_not_prec_eq with symbol Prec g f; trivial. apply prec_eq_sym; trivial.\ndestruct H7 as [H7 | [H7 H7']].\napply n; assumption.\napply lt_irrefl with bb.\napply lt_le_trans with (length l); assumption.\nrewrite H5 in Sf; discriminate.\nright; intro fk_lt_fl; inversion fk_lt_fl; subst.\napply H; exists s; split; assumption.\napply (prec_antisym Prec f); trivial.\nassert (H6: False).\napply prec_not_prec_eq with symbol Prec g f; trivial. apply prec_eq_sym; trivial. contradict H6.\ndestruct H7 as [H7 | [H7 H7']].\napply n; assumption.\napply lt_irrefl with bb.\napply lt_le_trans with (length k); assumption.\nrewrite H5 in Sf; discriminate.\nright;  intro fk_lt_fl; inversion fk_lt_fl; subst.\napply Ko; intros s' s'_mem_k; apply rpo_trans with (Term g k); trivial.\napply Subterm with s'; trivial.\napply Equiv; reflexivity.\napply (prec_antisym Prec f); trivial.\ncontradict Ko; trivial.\ncontradict Ko; trivial.\nrewrite H5 in Sf; discriminate.\nright ; intro fk_lt_fl; inversion fk_lt_fl; subst.\napply H; exists s; split; trivial.\napply (prec_antisym Prec f); trivial.\nassert (H6: False). apply prec_not_prec_eq with symbol Prec g f; trivial. apply prec_eq_sym; trivial. contradict H6.\napply not_k_lt_l; trivial.\nrewrite H5 in Sf; discriminate.\n(* 1/2 Trying Top_eq_mul, status f = Mul *)\nassert (H' := remove_equiv_list_is_sound k l).\ndestruct (remove_equiv_list k l) as [k' l'];\ndestruct H' as [lc [Pk [Pl D]]].\nassert (Rem : rpo_mul bb k l -> rpo_mul bb k' l').\ngeneralize l k l' k' Pk Pl; clear l k l' k' Pk Pl D IH H.\ninduction lc as [ | c lc]; intros l k l' k' Pk Pl k_lt_l.\ninversion k_lt_l as [a lg ls lc' k'' l'' Rk Rl ls_lt_alg]; subst.\napply (@List_mul bb a lg ls lc'); trivial.\ntransitivity k; trivial; symmetry; rewrite <- app_nil_end in Pk; trivial.\ntransitivity l; trivial; symmetry; rewrite <- app_nil_end in Pl; trivial.\nassert (H := IHlc l k (l' ++ c :: nil) (k' ++ c :: nil)).\ndo 2 rewrite <- ass_app in H; simpl in H.\ngeneralize (H Pk Pl k_lt_l); clear H; intro H.\napply (@rpo_mul_remove_equiv_aux bb k' l' c c).\nintros t _; apply rpo_antirefl.\nreflexivity.\ninversion H as [a lg ls lc' k'' l'' Rk Rl ls_lt_alg]; subst.\napply (@List_mul bb a lg ls lc'); trivial.\nrewrite <- Rk; rewrite <- permut0_cons_inside;[|apply equiv_equiv|reflexivity].    \nrewrite <- app_nil_end; reflexivity || auto.\nrewrite <- Rl; rewrite <- permut0_cons_inside;[|apply equiv_equiv|reflexivity]. \nrewrite <- app_nil_end; reflexivity || auto.\nlet P := constr:(forall u, mem equiv u k' -> exists v,  mem equiv v l' /\\ rpo bb u v) in \nassert (H' : {P} + {~ P}).\nassert (IH' : forall u v, mem equiv u k' -> mem equiv v l' -> {rpo bb u v}+{~rpo bb u v}).\nintros u v u_mem_k' v_mem_l'; apply (IH (v,u)).\napply size2_lex1_mem.\nrewrite Pl; rewrite <- mem_or_app; left; trivial.\ngeneralize l' IH'; clear l k IH H l' lc Pk Pl D IH' Rem.\ninduction k' as [ | u' k']; intros l' IH'.\nleft; intros; contradiction.\nlet P:=constr:(forall v, mem equiv v l' -> ~rpo bb u' v) in \nassert (H : {v | mem equiv v l' /\\ rpo bb u' v}+{P}).\nassert (IH'' : forall v, mem equiv v l' -> {rpo bb u' v}+{~rpo bb u' v}).\nintros v v_mem_l'; apply (IH' u' v); trivial.\nleft; reflexivity.\nclear IHk' IH'; induction l' as [ | v' l'].\nright; intros; contradiction.\ndestruct IHl' as [Ok | Ko].\nintros; apply IH''; right; trivial.\ndestruct Ok as [v [v_mem_l' u'_lt_v]]; left; exists v; split; trivial.\nright; trivial.\ndestruct (IH'' v') as [Ok' | Ko'].\nleft; reflexivity.\nleft; exists v'; split; trivial.\nleft; reflexivity.\nright; intros v [v'_eq_v | v_mem_l'].\nintros u'_lt_v; apply Ko'.\nrewrite <- (equiv_rpo_equiv_1 _ v'_eq_v); trivial.\napply Ko; trivial.\ndestruct H as [[v [v_mem_l' u'_lt_v]] | Ko].\ndestruct (IHk' l') as [Ok' | Ko'].\nintros u v' u_mem_k' v'_mem_l'; apply IH'; trivial; right; trivial.\nleft; intros u [u'_eq_u | u_mem_k'].\nexists v; split; trivial.\nrewrite (equiv_rpo_equiv_2 _ u'_eq_u); trivial.\napply Ok'; trivial.\nright; intro H; apply Ko'.\nintros u u_mem_k'; apply H; right; trivial.\nright; intro H.\ndestruct (H u') as [v [v_mem_l' u'_lt_v]].\nleft; reflexivity.\napply (Ko v); trivial.\ndestruct l' as [ | v' l'].\nright; intro fk_lt_fl.\ninversion fk_lt_fl as [f' l' t'' t' t'_mem_l fk_le_t'\n                            | f' f'' k'' l'' f_prec_f k''_lt_fl\n                            | f' g' k'' l'' Sf' Sg' f'_eq_g' L k''_lt_l'' l'_lt_t\n                            | f' g' k'' l'' Sf' Sg' f'_eq_g' k_lt_l ]; subst.\napply H; exists t'; split; trivial.\nassert (H5:False). apply prec_not_prec_eq with symbol Prec g f; trivial. apply prec_eq_sym; trivial. contradict H5.\nrewrite Sf in Sg'; discriminate.\nassert (k'_lt_nil := Rem k_lt_l).\ninversion k'_lt_nil as [a lg ls lc' k'' l'' Rk Rl ls_lt_alg]; subst.\nassert (L := permut_length Rl); discriminate.\ndestruct H' as [Ok | Ko].\nleft; apply Top_eq_mul; trivial. rewrite Sf_eq_Sg; trivial. apply prec_eq_sym; trivial.\napply (@List_mul bb v' l' k' lc); trivial.\nright; intro fk_lt_fl.\ninversion fk_lt_fl as [f' l'' t'' t' t'_mem_l fk_le_t'\n                            | f' f'' k'' l'' f_prec_f k''_lt_fl\n                            | f' f'' k'' l'' Sf' Sf'' f'_eq_f'' L k''_lt_l'' l'_lt_t\n                            | f' f'' k'' l'' Sf' Sf'' f'_eq_f'' k_lt_l ]; subst.\nrewrite Pl in t'_mem_l; rewrite <- mem_or_app in t'_mem_l.\ndestruct t'_mem_l as [t'_mem_vl' | t'_mem_lc].\napply Ko; intros u u_mem_k'; exists t'; split; trivial.\ninversion fk_le_t'; subst.\nrewrite <- (@equiv_rpo_equiv_1 _ (Term g k) t'); trivial.\napply Subterm with u.\nrewrite Pk; rewrite <- mem_or_app; left; trivial.\napply Equiv; apply Eq.\napply rpo_trans with (Term g k); trivial.\napply Subterm with u.\nrewrite Pk; rewrite <- mem_or_app; left; trivial.\napply Equiv; apply Eq.\napply (@rpo_antirefl bb (Term g k)).\ninversion fk_le_t'; subst.\nrewrite (@equiv_rpo_equiv_2 _ (Term g k) t'); trivial.\napply Subterm with t'.\nrewrite Pk; rewrite <- mem_or_app; right; trivial.\napply Equiv; apply Eq.\napply rpo_trans with t'; trivial.\napply Subterm with t'.\nrewrite Pk; rewrite <- mem_or_app; right; trivial.\napply Equiv; apply Eq.\nassert (H5:False). apply prec_not_prec_eq with symbol Prec g f; trivial. apply prec_eq_sym; trivial. contradict H5.\nrewrite Sf in Sf''; discriminate.\nassert (k'_lt_vl' := Rem k_lt_l).\napply Ko. \ninversion k'_lt_vl' as [a lg ls lc' k'' l'' Rk Rl ls_lt_alg]; subst.\nintro u; rewrite Rk; rewrite <- mem_or_app.\nintros [u_mem_ls | u_mem_lc'].\ndestruct (ls_lt_alg _ u_mem_ls) as [a' [a'_mem_alg u_lt_a']];\nexists a'; split; trivial.\nrewrite Rl; rewrite app_comm_cons;\nrewrite <- mem_or_app; left; trivial.\nassert False.\napply (D u u).\nrewrite Rk; rewrite <- mem_or_app; right; trivial.\nrewrite Rl; rewrite app_comm_cons;\nrewrite <- mem_or_app; right; trivial.\nreflexivity.\ncontradiction.\n(* 1/1 f <> g, trying last possible case Top_gt *)\ngeneralize (prec_bool_ok Prec g f); case (prec_bool Prec g f); [intro g_prec_f | intro not_g_prec_f].\nlet P:=constr:(forall t, mem equiv t k -> rpo bb t (Term f l)) in \nassert (H' : {P}+{~P}).\nclear H; induction k as [ | s k].\nleft; intros; contradiction.\ndestruct (IH (Term f l,s)) as [s_lt_fl | not_s_lt_fl].\napply size2_lex2; left; trivial.\ndestruct IHk as [Ok | Ko].\nintros [t2 t1] St; apply (IH (t2,t1)).\napply o_size2_trans with (Term f l, Term g k); trivial.\napply size2_lex2_bis.\nleft; intros t [t_eq_s | t_mem_k].\nrewrite (equiv_rpo_equiv_2 _ t_eq_s); trivial.\napply Ok; trivial.\nright; intro sk_lt_fl; apply Ko; intros; apply sk_lt_fl; right; trivial.\nright; intro sk_lt_fl; apply not_s_lt_fl; intros; apply sk_lt_fl; left; \nreflexivity.\ndestruct H' as [Ok | Ko].\nleft; apply Top_gt; trivial.\nright; intro gk_lt_fl;\ninversion gk_lt_fl as [f' l'' t'' t' t'_mem_l fk_le_t'\n                            | f' f'' k'' l'' f_prec_f k''_lt_fl\n                            | f' f'' k'' l'' Sf' Sf'' f'_eq_f'' L k''_lt_l'' l'_lt_t\n                            | f' f'' k'' l'' Sf' Sf'' f'_eq_f'' k_lt_l ]; subst.\napply H; exists t'; split; trivial.\napply Ko; trivial.\napply (prec_antisym Prec f); trivial. apply prec_eq_prec2 with g; trivial.\napply (prec_antisym Prec f); trivial.\napply prec_eq_prec2 with g; trivial.\nright; intro gk_lt_fl;\ninversion gk_lt_fl as [f' l'' t'' t' t'_mem_l fk_le_t'\n                            | f' f'' k'' l'' f_prec_f k''_lt_fl\n                            | f' f'' k'' l'' Sf' Sf'' f'_eq_f'' L k''_lt_l'' l'_lt_t\n                            | f' f'' k'' l'' Sf' Sf'' f'_eq_f'' k_lt_l ]; subst.\napply H; exists t'; split; trivial.\nabsurd (prec Prec g f); trivial.\nassert (H5:=prec_eq_bool_ok Prec). assert (H5':= H5 g f). rewrite g_diff_f in H5'. contradict H5'; trivial.\nassert (H5:=prec_eq_bool_ok Prec). assert (H5':= H5 g f). rewrite g_diff_f in H5'. contradict H5'; trivial.\nDefined.\n\nLemma trans_clos_subterm_rpo:\n  forall bb s t,  (trans_clos direct_subterm) s t -> rpo bb s t.\nProof.\nintros bb s t H; induction H as [ s [ v | f l ] H | s t u H1 H2].\ninversion H.\napply (@Subterm bb f l s s); trivial.\nsimpl in H; apply in_impl_mem; trivial.\nexact Eq.\napply Equiv; apply Eq.\napply (@rpo_subterm bb u t); trivial.\nQed.\n\nDefinition prec_eval f1 f2 :=\n  if (prec_eq_bool Prec f1 f2) \n  then Equivalent\n  else \n     if prec_bool Prec f1 f2 then Less_than\n     else \n        if prec_bool Prec f2 f1 then Greater_than\n        else Uncomparable.\n\nLemma prec_eval_is_sound :  \n  forall f1 f2, \n  match prec_eval f1 f2 with\n  | Equivalent => prec_eq Prec f1  f2\n  | Less_than => prec Prec f1 f2\n  | Greater_than => prec Prec f2 f1 \n  | Uncomparable => ~ prec_eq Prec f1 f2 /\\ ~prec Prec f1 f2 /\\ ~prec Prec f2 f1\n  end.\nProof.\nintros f1 f2; unfold prec_eval.\ncase_eq (prec_eq_bool Prec f1 f2). intros.\nassert (H1:= prec_eq_bool_ok Prec). assert (H1':= H1 f1 f2).\nrewrite H in H1'. trivial.\nintro.\ncase_eq (prec_bool Prec f1 f2).\nintros.\nassert (H1:= prec_bool_ok Prec). assert (H1':= H1 f1 f2).\nrewrite H0 in H1'. trivial.\nintros.\ncase_eq (prec_bool Prec f2 f1).\nintro prec'.\nassert (H1:= prec_bool_ok Prec). assert (H1':= H1 f2 f1).\nrewrite prec' in H1'. trivial.\nintros.\nsplit.\nassert (H3:= prec_eq_bool_ok Prec). assert (H3':= H3 f1 f2).\nrewrite H in H3'. trivial.\nsplit. \nassert (H3:= prec_bool_ok Prec). assert (H3':= H3 f1 f2).\nrewrite H0 in H3'. trivial.\nassert (H3:= prec_bool_ok Prec). assert (H3':= H3 f2 f1).\nrewrite H1 in H3'. trivial.\nQed.\n\nInductive result (A : Set) : Set := \n  | Not_found : result A\n  | Not_finished : result A\n  | Found : A -> result A.\n\n\nRecord rpo_inf : Set := \n  { bb : nat;\n    rpo_l : list (term*term);\n    rpo_eq_l : list (term*term);\n    equiv_l : list (term*term);\n    rpo_l_valid : forall t t', In (t,t') rpo_l -> rpo bb t t';\n    rpo_eq_valid : forall t t', In (t,t') rpo_eq_l -> rpo_eq bb t t';\n    equiv_l_valid : forall t t', In (t,t') equiv_l -> equiv t t'\n  }.\n\nFunction remove_equiv_eval (p : term -> term -> option bool) \n    (t : term) (l : list term) {struct l} : result (list term) :=\n     match l with\n     | nil => @Not_found _\n     | a :: l => \n            match p t a with\n            | Some true => (Found l)\n            | Some false =>\n               match remove_equiv_eval p t l  with\n               | Found l' => Found  (a :: l')\n               | Not_found _ => @Not_found _\n               | Not_finished _ => @Not_finished _\n               end\n             | None => @Not_finished _\n             end \n            end.\n\nFunction  remove_equiv_eval_list (p : term -> term -> option bool) (l1 l2 : list term) \n  {struct l1} : option ((list term) * (list term)):=\n    match l1, l2 with\n    | _, nil => Some (l1,l2)\n    | nil, _ => Some (l1,l2)\n    | a1 :: l1, l2 =>\n          match remove_equiv_eval p a1 l2 with\n          | Found l2' =>  remove_equiv_eval_list p l1 l2' \n          | Not_found _ =>\n                      match remove_equiv_eval_list p l1 l2 with\n                      | Some (l1',l2') => Some (a1 :: l1', l2')\n                      | None => None\n                      end\n          | Not_finished _ => None\n          end\n     end.\n\nFunction equiv_eval_list (p : term -> term -> option bool) (l1 l2 : list term) \n{struct l1} : option bool := \n     match l1, l2 with\n    | nil, nil => Some true\n    | (a :: l), (b :: l') => \n              match p a b with\n              | Some true => equiv_eval_list p l l'\n              | Some false => Some false\n              | None => None\n              end\n         | _, _ => Some false\n    end.\n\nDefinition eq_tt_bool t12 t12' := \nmatch t12, t12' with \n(t1,t2), (t1',t2') => andb (eq_bool t1 t1') (eq_bool t2 t2')\nend.\n\nLemma eq_tt_bool_ok : forall t12 t12', match eq_tt_bool t12 t12' with true => t12 = t12' | false => t12 <> t12' end.\nProof.\nunfold eq_tt_bool; intros [t1 t2] [t1' t2']; generalize (eq_bool_ok t1 t1'); case (eq_bool t1 t1').\nintro t1_eq_t1'; generalize (eq_bool_ok t2 t2'); case (eq_bool t2 t2').\nintro t2_eq_t2'; simpl; subst; reflexivity.\nintro t2_diff_t2'; simpl; intro H; apply t2_diff_t2'; injection H; intros; assumption.\nintro t1_diff_t1'; simpl; intro H; apply t1_diff_t1'; injection H; intros; assumption.\nDefined.\n\nFixpoint equiv_eval rpo_infos (n : nat) (t1 t2 : term) {struct n} : option bool := \n   match n with\n   | 0 => None\n   | S m =>\n     match t1, t2 with\n     | Var v1, Var v2 => Some (X.eq_bool v1 v2)\n     | Term f1 l1, Term f2 l2 =>\n       if mem_bool eq_tt_bool  (t1, t2) rpo_infos.(equiv_l)\n         then  Some true \n         else\n           if prec_eq_bool Prec f1 f2 \n             then \n               match status Prec f1 with\n                 | Lex =>  equiv_eval_list (equiv_eval rpo_infos m) l1 l2\n                 | Mul => \n                   match remove_equiv_eval_list (equiv_eval rpo_infos m) l1 l2 with\n                     | Some (nil,nil) => Some true\n                     | Some _ => Some false\n                     | None => None\n                   end\n               end\n             else Some false\n       | _, _ => Some false\n     end\n   end.\n\nLemma equiv_eval_equation :\n  forall rpo_infos n t1 t2, equiv_eval rpo_infos n t1 t2 =\n   match n with\n   | 0 => None\n   | S m =>\n     match t1, t2 with\n     | Var v1, Var v2 => Some (X.eq_bool v1 v2)\n     | Term f1 l1, Term f2 l2 =>\n       if mem_bool eq_tt_bool (t1,t2) rpo_infos.(equiv_l)\n         then  Some true \n         else\n           if prec_eq_bool Prec f1 f2 \n             then \n               match status Prec f1 with\n                 | Lex =>  equiv_eval_list (equiv_eval rpo_infos m) l1 l2\n                 | Mul => \n                   match remove_equiv_eval_list (equiv_eval rpo_infos m) l1 l2 with\n                     | Some (nil,nil) => Some true\n                     | Some _ => Some false\n                     | None => None\n                   end\n               end\n             else Some false\n       | _, _ => Some false\n     end\n   end.\nProof.\nintros rpo_infos [ | n] [v1 | f1 l1] [v2 | f2 l2];\nunfold equiv_eval; simpl; trivial.\nQed.\n\nLemma equiv_eval_list_is_sound :\n  forall p l1 l2, match equiv_eval_list p l1 l2 with\n      | Some true => length l1 = length l2 /\\ \n                              (forall t1 t2, In (t1,t2) (combine l1 l2) -> p t1 t2 = Some true)\n      | Some false => length l1 <> length l2 \\/\n                               (exists t1, exists t2, \n                                 In (t1,t2) (combine l1 l2) /\\ p t1 t2 = Some false)\n      | None => exists t1, exists t2, In (t1,t2) (combine l1 l2) /\\\n                            p t1 t2 = None\n      end.\nProof.\nintros p l1; induction l1 as [ | t1 l1]; intros [ | t2 l2]; simpl.\nsplit; trivial; intros; contradiction.\nleft; discriminate.\nleft; discriminate.\nassert (H : forall u2, u2 = t2 -> p t1 u2 = p t1 t2).\nintros; subst; trivial.\ndestruct (p t1 t2) as [ [ | ] | ]; generalize (H _ (refl_equal _)); clear H; intro H.\ngeneralize (IHl1 l2); destruct (equiv_eval_list p l1 l2) as [ [ | ] | ].\nintros [L H']; repeat split.\nrewrite L; trivial.\nintros t3 t4 [t3t4_eq_t1t2 | t3t4_in_ll].\ninjection t3t4_eq_t1t2; intros; subst; trivial.\napply H'; trivial.\nintros [L | [t3 [t4 [H' H'']]]].\nleft; intros H''; apply L; injection H''; intros; trivial.\nright; exists t3; exists t4; split; trivial; right; trivial.\nintros [t3 [t4 [H' H'']]]; exists t3; exists t4; split; trivial; right; trivial.\nright; exists t1; exists t2; split; trivial; left; trivial.\nexists t1; exists t2; split; trivial; left; trivial.\nQed.\n\nLemma remove_equiv_eval_is_sound : \n  forall p t l, \n      match remove_equiv_eval p t l with\n      | Found l' => \n                exists t', p t t' = Some true /\\ \n                   list_permut.permut0 (@eq term) l (t' :: l')\n      | Not_found _ => forall t', In t' l -> p t t' = Some false\n      | Not_finished _ => exists t', In t' l /\\ p t t' = None\n      end.\nintros p t l; \nfunctional induction (remove_equiv_eval p t l) as \n  [ \n  | H1 a l t' H \n  | H1 a l t' H IH l' H' \n  | H1 a l t' H IH H' \n  | H1 a l t' H IH H' \n  | H1 a l t' H].\nsimpl; intros; contradiction.\nexists a; split; auto.\napply list_permut.permut_refl; intro; trivial.\nrewrite H' in IH; destruct IH as [t' [H'' P]]; exists t'; split; trivial.\napply (Pcons (R := @eq term) a a (l := l) (t' :: nil) l'); trivial.\nrewrite H' in IH; intros t' [a_eq_t' | t'_in_l]; [subst | apply IH]; trivial.\nrewrite H' in IH; destruct IH as [t' [t'_in_l ptt'_eq_none]]; \nexists t'; split; trivial; right; trivial.\nexists a; split; trivial; left; trivial.\nQed.\n\nLemma remove_equiv_eval_list_is_sound :\n  forall p l1 l2, \n    match remove_equiv_eval_list p l1 l2 with\n         | Some (l1',l2') => \n              exists ll, (forall t1 t2, In (t1,t2) ll -> p t1 t2 = Some true) /\\\n                list_permut.permut0 (@eq term) l1 (l1' ++ (map (fun st => fst st) ll)) /\\\n                list_permut.permut0 (@eq term) l2 (l2' ++ (map (fun st => snd st) ll)) /\\\n                (forall t1 t2, In t1 l1' -> In t2 l2' -> p t1 t2 = Some false)\n         | None => exists t1, exists t2, In t1 l1 /\\ In t2 l2 /\\ p t1 t2 = None\n    end.\nProof.\nintros p l1 l2; \nfunctional induction (remove_equiv_eval_list p l1 l2) as\n[ l1\n| H1 l2 H2 H3 H4 H'\n| H1 l2 t1 l1 H2 H3 H4 H' l2' H IH \n| H1 l2 t1 l1 H2 H3 H4 H' H IH l1' l2' R\n| H1 l2 t1 l1 H2 H3 H4 H' H IH R\n| H1 l2 t1 l1 H2 H3 H4 H' H].\n(* 1/ 6 *)\nexists (@nil (term * term)); simpl; intuition; intros.\nrewrite <- app_nil_end; apply list_permut.permut_refl; intro; trivial.\napply list_permut.permut_refl; intro; trivial.\n(* 1/5 *)\ndestruct l2 as [ | t2 l2].\ncontradiction.\nexists (@nil (term * term)); simpl; intuition; intros.\napply list_permut.permut_refl; intro; trivial.\nrewrite <- app_nil_end; apply list_permut.permut_refl; intro; trivial.\n(* 1/4 *)\nassert (K := remove_equiv_eval_is_sound p t1 l2); rewrite H in K.\ndestruct K as [t2' [pt1t2_eq_true P]].\ndestruct (remove_equiv_eval_list p l1 l2') as [ [l1'' l2''] | ].\ndestruct IH as [ll [E_ll [P1 [P2 F]]]]; exists ((t1,t2') :: ll); repeat split; trivial.\nintros u1 u2 [u1u2_eq_t1t2' | u1u2_in_ll].\ninjection u1u2_eq_t1t2'; intros; subst; apply pt1t2_eq_true.\napply E_ll; trivial.\nsimpl; apply Pcons; trivial.\napply list_permut.permut_trans with (t2' :: l2').\nintros a b c _ a_eq_b b_eq_c; transitivity b; trivial. trivial.\nsimpl. apply Pcons. trivial.\ntrivial. \ndestruct IH as [t1' [t2 [t1_in_l1 [t2_in_l2 p1p2_eq_none]]]];\nexists t1'; exists t2; repeat split; trivial.\nright; trivial.\ndestruct (list_permut.permut_inv_right P) as [t2'' [k2 [k2' [t2''_eq_t2' [H'' P']]]]].\nsubst l2; apply in_insert.\ngeneralize (k2 ++ k2') l2' t2_in_l2 P'; intro k; induction k as [ | u k];\nintros l t2_in_l Q; inversion Q as [ | a b k' l1' l2]; subst; trivial.\ndestruct (in_app_or _ _ _ t2_in_l) as [t2_in_l1' | [t2_eq_b | t2_in_l2']].\nright; apply (IHk (l1' ++ l2)); trivial; apply in_or_app; left; trivial.\nleft; subst; trivial.\nright; apply (IHk (l1' ++ l2)); trivial; apply in_or_app; right; trivial.\n(* 1/3 *)\nassert (K := remove_equiv_eval_is_sound p t1 l2); rewrite H in K.\nrewrite R in IH; destruct IH as [ll [E_ll [P1 [P2 F]]]]; \nexists ll; repeat split; auto.\nsimpl. apply (Pcons (R := @eq term) t1 t1 (l := l1) nil\n                       (l1' ++ map (fun st : term * term => fst st) ll)); trivial.\nsimpl; intros u1 u2 [u1_eq_t1 | u1_in_l1'] u2_in_l2'.\nsubst u1; apply K; rewrite (in_permut_in P2);\napply in_or_app; left; trivial.\napply F; trivial.\n(* 1/2 *)\nrewrite R in IH; destruct IH as [u1 [u2 [u1_in_l1 [u2_in_l2 pu1u2_eq_none]]]];\nexists u1; exists u2; repeat split; trivial; right; trivial.\n(* 1/1 *)\nassert (K := remove_equiv_eval_is_sound p t1 l2); rewrite H in K.\ndestruct K as [t2 [t2_in_l2 pt1t2_eq_none]];\nexists t1; exists t2; repeat split; trivial; left; trivial.\nQed.\n\nLemma find_is_sound : \n  forall (I: term -> term -> Prop) l (l_sound: forall t t', In (t,t') l -> I t t') t1 t2,  \n    mem_bool eq_tt_bool (t1,t2) l = true -> \n    I t1 t2.\nProof.\n  intros I l l_sound t1 t2 H; apply l_sound.\n  apply (mem_impl_in (@eq (term*term))).\n  intros; assumption.\n  generalize (mem_bool_ok _ _ eq_tt_bool_ok (t1,t2) l); rewrite H; intros; assumption.\nQed.    \n\nLemma equiv_eval_is_sound_weak :\n  forall rpo_infos n t1 t2, equiv_eval rpo_infos n t1 t2 = Some true -> equiv t1 t2.\nintros rpo_infos n; induction n as [ | n].\n(* n = 0 *)\nintros; discriminate.\n(* n = S n *)\ndestruct t1 as [v1 | f1 l1]; destruct t2 as [v2 | f2 l2]; simpl.\n(* t1 = Var v1 ; t2 = v2 *)\ngeneralize (X.eq_bool_ok v1 v2); case (X.eq_bool v1 v2); [intro v1_eq_v2 | intro v1_diff_v2].\n(* v1 = v2 *)\nsubst; intuition; apply Eq.\n(* v1 <> v2 *)\nintro; discriminate.\n(*t1 = Var v1 ; t2 = f2 l2*)\nintro; discriminate.\n(*t1 = f1 l1 ; t2 = v2 *)\nintro; discriminate.\n(*t1 = f1 l1 ; t2 = f2 l2 *)\ncase_eq (mem_bool eq_tt_bool ((Term f1 l1), (Term f2 l2)) (equiv_l rpo_infos));simpl.\n(* (t1,t2) in (equiv_l rpo_infos) *)\nintros H _ ;eapply find_is_sound with (1:=equiv_l_valid rpo_infos);auto.\nintros _.\ncase_eq (prec_eq_bool Prec f1 f2); [intro f1_eq_f2 | intro f1_diff_f2].\ncase_eq (status Prec f1). intros Status.\nintro H; apply Eq_lex; trivial.\nassert (H1:= prec_eq_status Prec). assert (H1':= H1 f1 f2).\nassert (status Prec f1 = status Prec f2). apply H1'; trivial. trivial.\nassert (H3:= prec_eq_bool_ok Prec). assert (H3':= H3 f1 f2).\nrewrite f1_eq_f2 in H3'. trivial. rewrite <- H0. trivial.\nassert (H3:= prec_eq_bool_ok Prec). assert (H3':= H3 f1 f2).\nrewrite f1_eq_f2 in H3'. trivial.\ngeneralize l1 l2 H; clear l1 l2 H;\nintro l; induction l as [ | t l]; intros [ | t' l'] H.\napply Eq_list_nil.\ndiscriminate.\ndiscriminate.\nsimpl in H; apply Eq_list_cons.\napply IHn; destruct (equiv_eval rpo_infos n t t') as [ [ | ] | ]; \ntrivial; discriminate.\napply IHl; destruct (equiv_eval rpo_infos n t t') as [ [ | ] | ]; \ntrivial; discriminate. intro Status.\n\nintro H; assert (H' := remove_equiv_eval_list_is_sound (equiv_eval rpo_infos n) l1 l2);\ndestruct (remove_equiv_eval_list (equiv_eval rpo_infos n) l1 l2) as [ [l1' l2'] | ].\ndestruct H' as [ll [E_ll [P1 [P2 H']]]];\napply Eq_mul; trivial.\nassert (H1:= prec_eq_status Prec). assert (H1':= H1 f1 f2).\nassert (status Prec f1 = status Prec f2). apply H1'; trivial. trivial.\nassert (H3:= prec_eq_bool_ok Prec). assert (H3':= H3 f1 f2).\nrewrite f1_eq_f2 in H3'. trivial. rewrite <- H0. trivial.\nassert (H3:= prec_eq_bool_ok Prec). assert (H3':= H3 f1 f2).\nrewrite f1_eq_f2 in H3'. trivial.\ndestruct l1'; destruct l2'; try discriminate; simpl in P1; trivial.\ngeneralize l1 l2 P1 P2; clear l1 l2 P1 P2; \ninduction ll as [ | [t1 t2] ll]; intros l1 l2 P1 P2.\nrewrite (permut_nil P1); rewrite (permut_nil P2); apply Pnil.\ndestruct (permut_inv_right P1) as [t1' [l1' [l1'' [t1_eq_t1' [H'' Q1]]]]]; subst l1 t1'.\ndestruct (permut_inv_right P2) as [t2' [l2' [l2'' [t2_eq_t2' [H'' Q2]]]]]; subst l2 t2'.\nsimpl; apply permut_strong.\napply IHn; apply E_ll; left; trivial.\napply IHll; trivial.\nintros; apply E_ll; right; trivial.\ndiscriminate.\nintro; discriminate.\nQed.\n\nLemma equiv_eval_list_fully_evaluates :\n  forall p l1 l2, (forall t1 t2, In t1 l1 -> In t2 l2 -> p t1 t2 <> None) ->\n  equiv_eval_list p l1 l2 <> None.\nProof.\nintros p l1 l2 E;\nfunctional induction (equiv_eval_list p l1 l2) as \n[ \n| H1 H2 t1 l1 H3 t2 l2 H4 H IH\n| H1 H2 t1 l1 H3 t2 l2 H4 H IH\n| H1 H2 t1 l1 H3 t2 l2 H4 H IH\n| l1 l2 H1 H2 H3 H4 H].\n(* 1/5 *) \ndiscriminate.\n(* 1/4 *)\napply IH; intros u1 u2 u1_in_l1 u2_in_l2; apply E; right; trivial.\n(* 1/3 *)\ndiscriminate.\n(* 1/2 *)\nassert (E' := E t1 t2); rewrite H in E'; apply E'; left; trivial.\n(* 1/1 *)\ndiscriminate.\nQed.\n\nLemma remove_equiv_eval_fully_evaluates :\n  forall p t l, (forall t', In t' l -> p t t' <> None) -> \n  remove_equiv_eval p t l <> @Not_finished _.\nProof.\nintros p t l E;\nfunctional induction (remove_equiv_eval p t l) as \n  [ \n  | H1 a l t' H \n  | H1 a l t' H IH l' H' \n  | H1 a l t' H IH H' \n  | H1 a l t' H IH H' \n  | H1 a l t' H].\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\nrewrite H' in IH; apply IH; intros; apply E; right; trivial.\nassert (H' := E _ (or_introl _ (refl_equal _)) H); contradiction.\nQed.\n\nLemma remove_equiv_eval_list_fully_evaluates :\n  forall p l1 l2, (forall t1 t2, In t1 l1 -> In t2 l2 -> p t1 t2 <> None) ->\n  remove_equiv_eval_list p l1 l2 <> None.\nProof.\nintros p l1 l2 E; \nfunctional induction (remove_equiv_eval_list p l1 l2) as\n[ l1\n| H1 l2 H2 H3 H4 H'\n| H1 l2 t1 l1 H2 H3 H4 H' l2' H IH \n| H1 l2 t1 l1 H2 H3 H4 H' H IH l1' l2' R\n| H1 l2 t1 l1 H2 H3 H4 H' H IH R\n| H1 l2 t1 l1 H2 H3 H4 H' H].\n(* 1/6 *)\ndiscriminate.\n(* 1/5 *)\ndiscriminate.\n(* 1/4 *)\nassert (K := remove_equiv_eval_is_sound p t1 H3). rewrite H in K.\ndestruct K as [t2 [t2_in_l2 P2]];\napply IH; intros u1 u2 u1_in_l1 u2_in_l2'; apply E; trivial.\nright; trivial.\nrewrite (in_permut_in P2); right; trivial.\n(* 1/3 *)\ndiscriminate.\n(* 1/2 *)\nrewrite R in IH; apply IH; intros u1 u2 u1_in_l1 u2_in_l2; apply E; trivial;\nright; trivial.\n(* 1/1 *)\nassert (K := remove_equiv_eval_fully_evaluates p t1 H3);\nrewrite H in K; intros _; apply K; trivial.\nintros t2 t2_in_l2; apply E; trivial; left; trivial.\nQed.\n\nLemma equiv_eval_terminates :\n  forall rpo_infos n t1 t2, size t1 + size t2 <= n -> equiv_eval rpo_infos n t1 t2 <> None.\nProof.\nintros rpo_infos n; induction n as [ | n].\n(* base case *)\nintros t1 t2 St1; \nabsurd (1 <= 0); auto with arith; \napply le_trans with (size t1 + size t2); trivial;\napply le_trans with (1 + size t2);\n[apply le_plus_l | apply plus_le_compat_r; apply size_ge_one].\n(* induction step *)\nintros t1 t2 St; rewrite equiv_eval_equation.\ndestruct t1 as [ v1 | f1 l1]; destruct t2 as [ v2 | f2 l2].\ndiscriminate.\nintros; discriminate.\nintros; discriminate.\ncase (mem_bool eq_tt_bool ((Term f1 l1), (Term f2 l2)) (equiv_l rpo_infos));simpl.\ndiscriminate.\ncase_eq (prec_eq_bool Prec f1 f2). intro f1_eq_f2.\nassert (H : forall t1 t2 : term, In t1 l1 -> In t2 l2 -> equiv_eval rpo_infos n t1 t2 <> None).\nintros t1 t2 t1_in_l1 t2_in_l2; apply IHn.\nrewrite size_unfold in St; rewrite <- plus_assoc in St.\nrewrite size_unfold in St; simpl in St.\nrefine (le_trans _ _ _ _ (le_S_n _ _ St)); apply plus_le_compat.\ngeneralize (size_direct_subterm t1 (Term f1 l1) t1_in_l1);\nrewrite (size_unfold (Term f1 l1)); simpl; auto with arith.\ngeneralize (size_direct_subterm t2 (Term f1 l2) t2_in_l2);\nrewrite (size_unfold (Term f1 l2)); simpl; auto with arith.\ncase (status Prec f1).\napply equiv_eval_list_fully_evaluates; trivial.\nassert (H':= remove_equiv_eval_list_fully_evaluates (equiv_eval rpo_infos n) l1 l2 H);\ndestruct (remove_equiv_eval_list (equiv_eval rpo_infos n) l1 l2) as [ [[ | t1' l1'] [ | t2' l2']] | ];\ntry discriminate.\napply False_rec; apply H'; trivial.\nintros.\ndiscriminate.\nQed.\n\nLemma equiv_eval_is_complete_true :\n  forall rpo_infos n t1 t2, size t1 + size t2 <= n -> equiv t1 t2 -> \n     equiv_eval rpo_infos n t1 t2 = Some true.\nProof.\nintros rpo_infos n; induction n as [ | n ].\n(* base case *)\nintros t1 t2 St; absurd (1 <= 0); auto with arith.\nrefine (le_trans _ _ _ _ St); apply le_trans with (size t1);\n[ apply size_ge_one | apply le_plus_l].\n(* induction step *)\nintros t1 t2 St t1_eq_t2; \ninversion t1_eq_t2 as \n[ t\n| f g l1 l2 Sf Sg f_eq_g\n| f g l1 l2 Sf Sg f_eq_g P1 P2]; subst.\n(* 1/3 syntactic equality *)\ndestruct t2 as [v2 | f2 l2]; simpl.\ngeneralize (X.eq_bool_ok v2 v2); case (X.eq_bool v2 v2); [intros _ | intro v2_diff_v2; absurd (v2 = v2)]; trivial.\ncase (mem_bool eq_tt_bool (Term f2 l2, Term f2 l2) (equiv_l rpo_infos)); [reflexivity | idtac].\ncase_eq (prec_eq_bool Prec f2 f2).\nintro H. clear H.\nassert (H : forall t2, In t2 l2 -> equiv_eval rpo_infos n t2 t2 = Some true).\nintros t2 t2_in_l2; apply IHn.\napply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size t2 + size t2)) with (S (size t2) + size t2); trivial;\napply plus_le_compat; [idtac | apply lt_le_weak];\napply size_direct_subterm; trivial.\napply Eq.\ndestruct (status Prec f2).\n(* 1/5 f2 has a Lex status *)\nclear St t1_eq_t2; induction l2 as [ | t2 l2]; simpl; trivial.\nrewrite (H t2); [rewrite IHl2 | left]; trivial; intros; apply H; right; trivial.\n(* 1/4 f2 has a Mul status *)\nassert (H' : remove_equiv_eval_list (equiv_eval rpo_infos n) l2 l2 = Some (nil,nil)).\nclear St t1_eq_t2; induction l2 as [ | t2 l2]; simpl; trivial.\nrewrite (H t2); [rewrite IHl2 | left]; trivial; intros; apply H; right; trivial.\nrewrite H'; trivial.\nintros H. assert (H2:= prec_eq_bool_ok Prec). assert (H2':= H2 f2 f2). rewrite H in H2'. contradict H2'. apply prec_eq_refl.\n(* 1/2 Eq_lex *)\nrewrite equiv_eval_equation.\ncase (mem_bool eq_tt_bool (Term f l1, Term g l2) (equiv_l rpo_infos)); [reflexivity | idtac].\nrewrite Sf; \ngeneralize (prec_eq_bool_ok Prec f f); case (prec_eq_bool Prec f f); [intros _ | intro f_diff_f; absurd (f = f); trivial].\nassert (Size : forall t1 t2, In t1 l1 -> In t2 l2 -> size t1 + size t2 <= n).\nintros t1 t2 t1_in_l1 t2_in_l2;\napply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size t1 + size t2)) with (S (size t1) + size t2); trivial;\napply plus_le_compat; [idtac | apply lt_le_weak];\napply size_direct_subterm; trivial.\ngeneralize l2 H Size; clear l2 H Size St t1_eq_t2; \ninduction l1 as [ | t1 l1]; intros l2 H Size;\ninversion H as [ | s t2 l l2' t1_eq_t2 l1_eq_l2']; subst; simpl.\ncase_eq (prec_eq_bool Prec f g).\nintros. trivial.\nintro eq_f_g. assert (H1:= prec_eq_bool_ok Prec). assert (H1':= H1 f g ). rewrite eq_f_g in H1'. contradict H1'; trivial. \nrewrite (IHn t1 t2); trivial.\napply IHl1; trivial.\nintros; apply Size; right; trivial.\napply Size; left; trivial. contradict f_diff_f. apply prec_eq_refl.\n(* 1/1 Eq_mul *)\nassert (St' : forall t1 t2, In t1 l1 -> In t2 l2 -> size t1 + size t2 <= n).\nintros t1 t2 t1_in_l1 t2_in_l2; apply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size t1 + size t2)) with (S (size t1) + size t2); trivial;\napply plus_le_compat; [idtac | apply lt_le_weak];\napply size_direct_subterm; trivial.\nassert (T : forall t1 t2, In t1 l1 -> In t2 l2 -> equiv_eval rpo_infos n t1 t2 <> None).\nintros t1 t2 t1_in_l1 t2_in_l2; apply equiv_eval_terminates; apply St'; trivial.\nassert (H' : remove_equiv_eval_list (equiv_eval rpo_infos n) l1 l2 = Some (nil,nil)).\ngeneralize l2 P1 St' T; clear l2 P1 St t1_eq_t2 St' T;\ninduction l1 as [ | t1 l1]; intros l2 P1 St' T; \ninversion P1 as [ | t1' t2 l1' l2' l2'' t1_eq_t2 l1_eq_l2]; trivial.\nassert (H' := remove_equiv_eval_is_sound (equiv_eval rpo_infos n) t1 l2).\nsubst; simpl.\ndestruct (remove_equiv_eval (equiv_eval rpo_infos n) t1 (l2' ++ t2 :: l2'')) \n  as [ | | l'].\nassert (H'' := H' t2); rewrite (IHn t1 t2) in H''; trivial.\nassert (H''' : Some true = Some false).\napply H''; apply in_or_app; right; left; trivial.\ndiscriminate.\napply St'.\nleft; trivial.\napply in_or_app; right; left; trivial.\nassert False.\ndestruct H' as [t' [t'_in_l2 H'']].\napply (T t1 t'); trivial; left; trivial.\ncontradiction.\ndestruct H' as [t' [t1_eq_t' P2]].\nassert (H : l2' ++ t2 :: l2'' <> nil).\ndestruct l2' as [ | t2' l2']; simpl; discriminate.\nassert (Q : list_permut.permut0 (eq (A:=term)) (t2 :: l2' ++ l2'') (l2' ++ t2 :: l2'')).\napply Pcons; trivial.\napply list_permut.permut_refl; intro; trivial.\ndestruct (l2' ++ t2 :: l2'') as [ | t2' k2].\nabsurd (@nil term = nil); trivial.\napply IHl1; trivial.\napply permut0_trans with (l2' ++ l2''); trivial. apply equiv_equiv.\nassert (t1_eq_t'' : equiv t1 t').\napply (equiv_eval_is_sound_weak _ _ _ _ t1_eq_t').\nassert (t2_eq_t' : equiv t2 t').\ntransitivity t1; trivial; symmetry; reflexivity || trivial.\nrewrite (@permut0_cons _ _ equiv_equiv _ _  (l2' ++ l2'') l'  t2_eq_t').\napply permut_impl with (@eq term); trivial.\nintros; subst; apply Eq.\napply list_permut.permut_trans with (t2' :: k2); trivial. \nintros a b c _ _ _ a_eq_b b_eq_c; subst; trivial.\nintros; apply St'.\nright; trivial.\nrewrite (in_permut_in P2); right; trivial.\nintros; apply T.\nright; trivial.\nrewrite (in_permut_in P2); right; trivial.\nrewrite equiv_eval_equation; rewrite Sf; rewrite H'.\ncase (mem_bool eq_tt_bool (Term f l1, Term g l2) (equiv_l rpo_infos)); [reflexivity | idtac].\ncase_eq (prec_eq_bool Prec f g).\nintro; trivial.\nintro f_eq'_g.\nassert (H1:= prec_eq_bool_ok Prec). assert (H1':= H1 f g).\nrewrite f_eq'_g in H1'.\ncontradict H1'; trivial.\nQed.\n\nLemma equiv_eval_is_sound :\n  forall rpo_infos n t1 t2, size t1 + size t2 <= n ->\n     match equiv_eval rpo_infos n t1 t2 with\n     | Some true => equiv t1 t2\n     | Some false => ~equiv t1 t2\n     | None => False\n     end.\nProof.\nintros rpo_infos n t1 t2 St;\nassert (H := equiv_eval_is_sound_weak rpo_infos n t1 t2);\nassert (T := @equiv_eval_terminates rpo_infos n t1 t2 St);\nassert (H' := @equiv_eval_is_complete_true rpo_infos n t1 t2 St);\ndestruct (equiv_eval rpo_infos n t1 t2) as [ [ | ] | ].\napply H; trivial.\nintro t1_eq_t2; assert (H'' := H' t1_eq_t2); discriminate.\napply T; trivial.\nQed.\n\nDefinition term_gt_list (p : term -> term -> option comp) s l :=\n  list_forall_option \n      (fun t => \n          match p s t with\n          | Some Greater_than => Some true\n          | Some _ => Some false\n          | None => None\n          end) l.\n\nFixpoint lexico_eval (p : term -> term -> option comp) (s1 s2 : term)\n   (l1 l2 : list term) {struct l1} : option comp :=\n    match l1, l2 with\n    | nil, nil => Some Equivalent\n    | nil, (_ :: _) => Some Less_than\n    | (_ :: _), nil => Some Greater_than\n    | (t1 :: l1'), (t2 :: l2') =>\n          match p t1 t2 with\n          | Some Equivalent => lexico_eval p s1 s2 l1' l2'\n          | Some Greater_than => \n              match term_gt_list p s1 l2 with\n              | Some true => Some Greater_than\n              | Some false => Some Uncomparable\n              | None => None\n              end\n          | Some Less_than =>\n              match term_gt_list p s2 l1 with\n              | Some true => Some Less_than\n              | Some false => Some Uncomparable\n              | None => None\n              end\n         | Some Uncomparable => Some Uncomparable\n         | None => None\n     end\nend.\n\nLemma lexico_eval_equation :\n  forall p s1 s2 l1 l2, lexico_eval p s1 s2 l1 l2 =\n    match l1, l2 with\n    | nil, nil => Some Equivalent\n    | nil, (_ :: _) => Some Less_than\n    | (_ :: _), nil => Some Greater_than\n    | (t1 :: l1'), (t2 :: l2') =>\n          match p t1 t2 with\n          | Some Equivalent => lexico_eval p s1 s2 l1' l2'\n          | Some Greater_than => \n              match term_gt_list p s1 l2 with\n              | Some true => Some Greater_than\n              | Some false => Some Uncomparable\n              | None => None\n              end\n          | Some Less_than =>\n              match term_gt_list p s2 l1 with\n              | Some true => Some Less_than\n              | Some false => Some Uncomparable\n              | None => None\n              end\n         | Some Uncomparable => Some Uncomparable\n         | None => None\n     end\nend.\nProof.\nintros p s1 s2 [ | t1 l1] [ | t2 l2]; apply refl_equal.\nQed.\n\nDefinition list_gt_list  (p : term -> term -> option comp) lg ls :=\n           list_forall_option \n\t      (fun s => \n\t\t list_exists_option \n\t\t   (fun g => \n\t\t      match p g s with\n\t\t\t| Some Greater_than => Some true\n\t\t\t| Some _ => Some false\n                        | None => None\n                      end) lg) ls.\n\nDefinition mult_eval (p : term -> term -> option comp) (l1 l2 : list term)  : option comp :=\n         match list_gt_list p l1 l2 with\n         | None => None\n         | Some true => Some Greater_than\n         | Some false =>\n          match list_gt_list p l2 l1 with\n\t  | Some true => Some Less_than\n\t  | Some false => Some Uncomparable\n          | None => None\n          end\nend.\n\nFixpoint rpo_eval rpo_infos (n : nat) (t1 t2 : term) {struct n} : option comp :=\n    if mem_bool eq_tt_bool (t1, t2) (rpo_l rpo_infos) \n      then Some Less_than\n      else if mem_bool eq_tt_bool (t2, t1) (rpo_l rpo_infos) \n        then Some Greater_than \n        else if mem_bool eq_tt_bool (t1, t2) (equiv_l rpo_infos) \n          then Some Equivalent \n          else if mem_bool eq_tt_bool (t2, t1) (equiv_l rpo_infos) \n            then Some Equivalent \n            else\n          \n\n\n\n  (match equiv_eval rpo_infos n t1 t2 with\n  | None => None\n  | Some true => Some Equivalent\n  | Some false =>\n     (match t1, t2 with\n     | Var _, Var _ => Some Uncomparable\n\n     | Var x, (Term _ l) =>\n     \t    if var_in_term_list x l\n     \t    then Some Less_than\n     \t    else Some Uncomparable\n\n     | (Term _ l), Var x =>\n     \t    if var_in_term_list x l\n     \t    then Some Greater_than\n     \t    else Some Uncomparable\n\n     | (Term f1 l1), (Term f2 l2) =>\n       (match n with\n       | 0 => None\n       | S m => \n         let check_l1_gt_t2 :=\n                     list_exists_option \n         \t\t  (fun t => match rpo_eval rpo_infos m t t2 with \n                                    | Some Equivalent \n                                    | Some Greater_than => Some true\n                                    | Some _ => Some false\n\t                            | None => None\n                                   end) l1 in\n          (match check_l1_gt_t2 with\n          | None => None\n          | Some true => Some Greater_than\n          | Some false =>\n            let check_l2_gt_t1 :=\n                   list_exists_option \n\t\t        (fun t => match rpo_eval rpo_infos m t1 t with\n                                       | Some Equivalent \n                                       | Some Less_than => Some true\n                                       | Some _ => Some false\n                                       | None  => None\n                                     end) l2 in\n          (match check_l2_gt_t1 with\n          | None => None\n          | Some true => Some Less_than\n          | Some false =>\n             (match prec_eval f1 f2 with\n\t\t  | Uncomparable => Some Uncomparable\n\t\t  | Greater_than =>\n\t\t       let check_l2_lt_t1 :=\n                          list_forall_option\n\t\t\t      (fun t => match rpo_eval rpo_infos m t1 t with\n                                               | Some Greater_than => Some true\n                                               | Some _ => Some false\n        \t\t                       | None => None\n                                               end) l2 in\n                     (match check_l2_lt_t1 with\n                     | None => None\n                     | Some true => Some Greater_than\n                     | Some false => Some Uncomparable\n                    end)\n\t\t  | Less_than =>\n                      let check_l1_lt_t2 :=\n\t\t          list_forall_option\n\t\t\t    (fun t => match rpo_eval rpo_infos m t t2 with\n                                               | Some Less_than => Some true\n                                               | Some _ => Some false\n                                               | None => None\n                                               end) l1 in\n                      (match check_l1_lt_t2 with\n                      | None => None\n\t\t      | Some true => Some Less_than\n\t\t      | Some false => Some Uncomparable\n                    end)\n\t\t  | Equivalent =>\n\t\t\t(match status Prec f1 with\n\t\t\t  | Mul => \n                                match remove_equiv_eval_list (equiv_eval rpo_infos m) l1 l2 with\n                                | None => None\n                                | Some (nil, nil) => Some Equivalent\n                                | Some (nil, _ :: _) => Some Less_than\n                                | Some (_ :: _,nil) => Some Greater_than\n                                | Some (l1, l2) => mult_eval (rpo_eval rpo_infos m) l1 l2\n                                end\n\t\t\t  | Lex => \n                               if (beq_nat (length l1) (length l2)) || \n                                  (leb (length l1) rpo_infos.(bb) && leb (length l2) rpo_infos.(bb))\n                               then lexico_eval (rpo_eval rpo_infos m) t1 t2 l1 l2\n                               else Some Uncomparable\n                       end) \n          end)\n        end)\n      end)\n    end)\n  end)\nend).\n\nLemma rpo_eval_equation :\n  forall rpo_infos n t1 t2, rpo_eval rpo_infos n t1 t2 =\n    if mem_bool eq_tt_bool (t1, t2) (rpo_l rpo_infos) \n      then Some Less_than\n      else if mem_bool eq_tt_bool (t2, t1) (rpo_l rpo_infos) \n        then Some Greater_than \n        else if mem_bool eq_tt_bool (t1, t2) (equiv_l rpo_infos) \n          then Some Equivalent \n          else if mem_bool eq_tt_bool (t2, t1) (equiv_l rpo_infos) \n            then Some Equivalent \n            else\n          \n\n\n\n  (match equiv_eval rpo_infos n t1 t2 with\n  | None => None\n  | Some true => Some Equivalent\n  | Some false =>\n     (match t1, t2 with\n     | Var _, Var _ => Some Uncomparable\n\n     | Var x, (Term _ l) =>\n     \t    if var_in_term_list x l\n     \t    then Some Less_than\n     \t    else Some Uncomparable\n\n     | (Term _ l), Var x =>\n     \t    if var_in_term_list x l\n     \t    then Some Greater_than\n     \t    else Some Uncomparable\n\n     | (Term f1 l1), (Term f2 l2) =>\n       (match n with\n       | 0 => None\n       | S m => \n         let check_l1_gt_t2 :=\n                     list_exists_option \n         \t\t  (fun t => match rpo_eval rpo_infos m t t2 with \n                                    | Some Equivalent \n                                    | Some Greater_than => Some true\n                                    | Some _ => Some false\n\t                            | None => None\n                                   end) l1 in\n          (match check_l1_gt_t2 with\n          | None => None\n          | Some true => Some Greater_than\n          | Some false =>\n            let check_l2_gt_t1 :=\n                   list_exists_option \n\t\t        (fun t => match rpo_eval rpo_infos m t1 t with\n                                       | Some Equivalent \n                                       | Some Less_than => Some true\n                                       | Some _ => Some false\n                                       | None  => None\n                                     end) l2 in\n          (match check_l2_gt_t1 with\n          | None => None\n          | Some true => Some Less_than\n          | Some false =>\n             (match prec_eval f1 f2 with\n\t\t  | Uncomparable => Some Uncomparable\n\t\t  | Greater_than =>\n\t\t       let check_l2_lt_t1 :=\n                          list_forall_option\n\t\t\t      (fun t => match rpo_eval rpo_infos m t1 t with\n                                               | Some Greater_than => Some true\n                                               | Some _ => Some false\n        \t\t                       | None => None\n                                               end) l2 in\n                     (match check_l2_lt_t1 with\n                     | None => None\n                     | Some true => Some Greater_than\n                     | Some false => Some Uncomparable\n                    end)\n\t\t  | Less_than =>\n                      let check_l1_lt_t2 :=\n\t\t          list_forall_option\n\t\t\t    (fun t => match rpo_eval rpo_infos m t t2 with\n                                               | Some Less_than => Some true\n                                               | Some _ => Some false\n                                               | None => None\n                                               end) l1 in\n                      (match check_l1_lt_t2 with\n                      | None => None\n\t\t      | Some true => Some Less_than\n\t\t      | Some false => Some Uncomparable\n                    end)\n\t\t  | Equivalent =>\n\t\t\t(match status Prec f1 with\n\t\t\t  | Mul => \n                                match remove_equiv_eval_list (equiv_eval rpo_infos m) l1 l2 with\n                                | None => None\n                                | Some (nil, nil) => Some Equivalent\n                                | Some (nil, _ :: _) => Some Less_than\n                                | Some (_ :: _,nil) => Some Greater_than\n                                | Some (l1, l2) => mult_eval (rpo_eval rpo_infos m) l1 l2\n                                end\n\t\t\t  | Lex => \n                               if (beq_nat (length l1) (length l2)) || \n                                  (leb (length l1) rpo_infos.(bb) && leb (length l2) rpo_infos.(bb))\n                               then lexico_eval (rpo_eval rpo_infos m) t1 t2 l1 l2\n                               else Some Uncomparable\n                       end) \n          end)\n        end)\n      end)\n    end)\n  end)\nend).\nProof.\nintros rpo_infos [ | n] [v1 | f1 l1] [v2 | f2 l2];\nunfold rpo_eval; simpl; trivial.\nQed.\n\nLemma term_gt_list_is_sound :\n  forall p s l,\n   match term_gt_list p s l with\n   | Some true => forall t, In t l -> p s t = Some Greater_than\n   | _ => True\n   end.\nProof.\nintros p s l; induction l as [ | t l]; simpl.\nintros; contradiction.\nreplace (term_gt_list p s (t :: l)) with\n  (match p s t with\n    | Some Greater_than => term_gt_list p s l\n    | Some _ => match term_gt_list p s l with Some _ => Some false | None => None end\n    | None => None\n    end).\ncase_eq (p s t); [intros [ | | | ] H | trivial].\ndestruct (term_gt_list p s l) as [ [ | ] | ]; trivial.\ndestruct (term_gt_list p s l) as [ [ | ] | ]; trivial.\ndestruct (term_gt_list p s l) as [ [ | ] | ]; trivial.\nintros u [u_eq_t | u_in_l]; [subst | apply IHl]; assumption.\ndestruct (term_gt_list p s l) as [ [ | ] | ]; trivial.\nunfold term_gt_list; simpl.\ndestruct (p s t) as [[ | | | ] | ]; trivial.\nQed.\n\nLemma lexico_eval_is_sound :\n  forall (p : term -> term -> option comp) s1 s2 l1 l2,\n           match lexico_eval p s1 s2 l1 l2 with\n           | Some Equivalent => \n             (exists ll, (forall t1 t2, In (t1,t2) ll -> p t1 t2 = Some Equivalent) /\\\n                            l1 = map (fun st => fst st) ll /\\\n                            l2 = map (fun st => snd st) ll) \n             |  Some Less_than => \n                 (l1 = nil /\\ l2 <> nil) \\/\n                 (exists ll, exists t2, exists l2',\n                   (forall t1 t2, In (t1,t2) ll -> p t1 t2 = Some Equivalent) /\\\n                   l1 = map (fun st => fst st) ll /\\\n                   l2 = map (fun st => snd st) ll ++ t2 :: l2') \\/\n                 (exists ll, exists t1, exists t2, exists l1', exists l2',\n                   (forall t1 t2, In (t1,t2) ll -> p t1 t2 = Some Equivalent) /\\\n                   p t1 t2 = Some Less_than /\\\n                   (forall t1, In t1 l1 -> \n                   ((exists t2, In t2 l2 /\\ (p t1 t2 = Some Equivalent \\/\n                                                     p t1 t2 = Some Less_than)) \\/ \n                                                  p s2 t1 = Some Greater_than)) /\\\n                   l1 = map (fun st => fst st) ll ++ t1 :: l1' /\\\n                   l2 = map (fun st => snd st) ll ++ t2 :: l2')\n             |  Some Greater_than => \n                 (l1 <> nil /\\ l2 = nil) \\/\n                 (exists ll, exists t1, exists l1',\n                   (forall t1 t2, In (t1,t2) ll -> p t1 t2 = Some Equivalent) /\\\n                   l1 = map (fun st => fst st) ll ++ t1 :: l1' /\\\n                   l2 = map (fun st => snd st) ll) \\/\n                (exists ll, exists t1, exists t2, exists l1', exists l2',\n                   (forall t1 t2, In (t1,t2) ll -> p t1 t2 = Some Equivalent) /\\\n                   p t1 t2 = Some Greater_than /\\\n                   (forall t2, In t2 l2 -> \n                   ((exists t1, In t1 l1 /\\ (p t1 t2 = Some Equivalent \\/\n                                                     p t1 t2 = Some Greater_than)) \\/ \n                                                  p s1 t2 = Some Greater_than)) /\\\n                   l1 = map (fun st => fst st) ll ++ t1 :: l1' /\\\n                   l2 = map (fun st => snd st) ll ++ t2 :: l2')\n            | _ => True\nend.\nProof. \nintros p s1 s2 l1; induction l1 as [ | t1 l1]; intros [ | t2 l2].\nsimpl; exists (@nil (term * term)); simpl; intuition.\nsimpl; left; split; [apply refl_equal | discriminate].\nsimpl; left; split; [discriminate | apply refl_equal].\nsimpl; case_eq (p t1 t2); [idtac | trivial].\nintros [ | | | ] Ht; generalize (IHl1 l2).\n(* 1/4 p t1 t2 = Some Equivalent *)\ncase_eq (lexico_eval p s1 s2 l1 l2); [intros [ | | | ] Hl | trivial].\n(* 1/7 lexico_eval p s1 s2 l1 l2 = Some Equivalent *)\nintros [ll [Hll [H1 H2]]]; exists ((t1,t2) :: ll); split.\nsimpl; intros u1 u2 [u1u2_eq_t1t2 | u1u2_in_ll]; [injection u1u2_eq_t1t2; intros; subst | apply Hll]; assumption.\nsimpl; split; subst; apply refl_equal.\n(* 1/6 lexico_eval p s1 s2 l1 l2 = Some Less_than *)\nintros [[H1 H2] | [[ll [a2 [l2' [Hll [H1 H2]]]]] | [ll [a1 [a2 [l1' [l2' [Hll [Ha [H [H1 H2]]]]]]]]]]].\nright; left; subst; destruct l2 as [ | a2 l2].\ndiscriminate.\nexists ((t1,t2) :: nil); exists a2; exists l2; split.\nsimpl; intros u1 u2 [u1u2_eq_t1t2 | u1u2_in_nil]; [injection u1u2_eq_t1t2; intros; subst; assumption | contradiction].\nsplit; apply refl_equal.\nright; left; exists ((t1,t2) :: ll); exists a2; exists l2'; split.\nsimpl; intros u1 u2 [u1u2_eq_t1t2 | u1u2_in_ll]; [injection u1u2_eq_t1t2; intros; subst | apply Hll]; assumption.\nsplit; subst; apply refl_equal.\ndo 2 right; exists ((t1,t2) :: ll); exists a1; exists a2; exists l1'; exists l2'; split.\nsimpl; intros u1 u2 [u1u2_eq_t1t2 | u1u2_in_ll]; [injection u1u2_eq_t1t2; intros; subst | apply Hll]; assumption.\nsplit.\nassumption.\nsplit.\nintros u [t1_eq_u | u_in_l1].\nsubst u; left; exists t2; split; left; trivial.\ndestruct (H _ u_in_l1) as [[u2 [u2_in_l2 H']] | H'].\nleft; exists u2; split; [right | idtac]; assumption.\nright; assumption.\nsplit; subst; apply refl_equal.\n(* 1/5 lexico_eval p s1 s2 l1 l2 = Some Greater_than *)\nintros [[H1 H2] | [[ll [a1 [l1' [Hll [H1 H2]]]]] | [ll [a1 [a2 [l1' [l2' [Hll [Ha [H [H1 H2]]]]]]]]]]].\nright; left; subst; destruct l1 as [ | a1 l1].\ndiscriminate.\nexists ((t1,t2) :: nil); exists a1; exists l1; split.\nsimpl; intros u1 u2 [u1u2_eq_t1t2 | u1u2_in_nil]; [injection u1u2_eq_t1t2; intros; subst; assumption | contradiction].\nsplit; apply refl_equal.\nright; left; exists ((t1,t2) :: ll); exists a1; exists l1'; split.\nsimpl; intros u1 u2 [u1u2_eq_t1t2 | u1u2_in_ll]; [injection u1u2_eq_t1t2; intros; subst | apply Hll]; assumption.\nsplit; subst; apply refl_equal.\ndo 2 right; exists ((t1,t2) :: ll); exists a1; exists a2; exists l1'; exists l2'; split.\nsimpl; intros u1 u2 [u1u2_eq_t1t2 | u1u2_in_ll]; [injection u1u2_eq_t1t2; intros; subst | apply Hll]; assumption.\nsplit.\nassumption.\nsplit.\nintros u [t2_eq_u | u_in_l2].\nsubst u; left; exists t1; split; left; trivial.\ndestruct (H _ u_in_l2) as [[u1 [u1_in_l1 H']] | H'].\nleft; exists u1; split; [right | idtac]; assumption.\nright; assumption.\nsplit; subst; apply refl_equal.\n(* 1/4 lexico_eval p s1 s2 l1 l2 = Some Uncomparable *)\ntrivial.\n(* 1/3 p t1 t2 = Some Less_than *)\ncase_eq (lexico_eval p s1 s2 l1 l2).\nintros [ | | | ] Hl.\n(* 1/7 lexico_eval p s1 s2 l1 l2 = Some Equivalent *)\nintros [ll [Hll [H1 H2]]].\ngeneralize (term_gt_list_is_sound p s2 (t1 :: l1)).\ndestruct (term_gt_list p s2 (t1 :: l1)) as [[ | ] | ].\nintro H; do 2 right; exists (@nil (term * term)); exists t1; exists t2; exists l1; exists l2; split.\nintros; contradiction.\nsplit.\nassumption.\nsplit.\nintros u u_in_t1l1; right; apply H; trivial.\nsimpl; split; subst; apply refl_equal.\ntrivial.\ntrivial.\n(* 1/6 lexico_eval p s1 s2 l1 l2 = Some Less_than *)\nintros [[H1 H2] | [[ll [a2 [l2' [Hll [H1 H2]]]]] | [ll [a1 [a2 [l1' [l2' [Hll [Ha [H [H1 H2]]]]]]]]]]];\ngeneralize (term_gt_list_is_sound p s2 (t1 :: l1)); destruct (term_gt_list p s2 (t1 :: l1)) as [[ | ] | ]; intro H'; trivial;\ndo 2 right; exists (@nil (term * term)); exists t1; exists t2; exists l1; exists l2; split.\nintros; contradiction.\nsplit.\nassumption.\nsplit.\nintros u u_in_t1l1; right; apply H'; assumption.\nsplit; apply refl_equal.\nintros; contradiction.\nsplit.\nassumption.\nsplit.\nintros u u_in_t1l1; right; apply H'; assumption.\nsplit; apply refl_equal.\nintros; contradiction.\nsplit.\nassumption.\nsplit.\nintros u u_in_t1l1; right; apply H'; assumption.\nsplit; apply refl_equal.\n(* 1/5 lexico_eval p s1 s2 l1 l2 = Some Greater_than *)\nintros _.\ngeneralize (term_gt_list_is_sound p s2 (t1 :: l1)); destruct (term_gt_list p s2 (t1 :: l1)) as [[ | ] | ]; intro H'; trivial.\ndo 2 right; exists (@nil (term * term)); exists t1; exists t2; exists l1; exists l2; split.\nintros; contradiction.\nsplit.\nassumption.\nsplit.\nintros u u_in_t1l1; right; apply H'; assumption.\nsplit; apply refl_equal.\n(* 1/4 lexico_eval p s1 s2 l1 l2 = Some  Some Uncomparable *)\nintros _.\ngeneralize (term_gt_list_is_sound p s2 (t1 :: l1)); destruct (term_gt_list p s2 (t1 :: l1)) as [[ | ] | ]; intro H'; trivial.\ndo 2 right; exists (@nil (term * term)); exists t1; exists t2; exists l1; exists l2; split.\nintros; contradiction.\nsplit.\nassumption.\nsplit.\nintros u u_in_t1l1; right; apply H'; assumption.\nsplit; apply refl_equal.\n(* 1/3 lexico_eval p s1 s2 l1 l2 = None *)\nintros _.\ngeneralize (term_gt_list_is_sound p s2 (t1 :: l1)); destruct (term_gt_list p s2 (t1 :: l1)) as [[ | ] | ]; intro H'; trivial.\ndo 2 right; exists (@nil (term * term)); exists t1; exists t2; exists l1; exists l2; split.\nintros; contradiction.\nsplit.\nassumption.\nsplit.\nintros u u_in_t1l1; right; apply H'; assumption.\nsplit; apply refl_equal.\n(* 1/3 p t1 t2 = Some Greater_than *)\ncase_eq (lexico_eval p s1 s2 l1 l2).\nintros [ | | | ] Hl.\n(* 1/6 lexico_eval p s1 s2 l1 l2 = Some Equivalent *)\nintros [ll [Hll [H1 H2]]].\ngeneralize (term_gt_list_is_sound p s1 (t2 :: l2)).\ndestruct (term_gt_list p s1 (t2 :: l2)) as [[ | ] | ].\nintro H; do 2 right; exists (@nil (term * term)); exists t1; exists t2; exists l1; exists l2; split.\nintros; contradiction.\nsplit.\nassumption.\nsplit.\nintros u u_in_t1l2; right; apply H; trivial.\nsimpl; split; subst; apply refl_equal.\ntrivial.\ntrivial.\n(* 1/5 lexico_eval p s1 s2 l1 l2 = Some Less_than *)\nintros [[H1 H2] | [[ll [a2 [l2' [Hll [H1 H2]]]]] | [ll [a1 [a2 [l1' [l2' [Hll [Ha [H [H1 H2]]]]]]]]]]];\ngeneralize (term_gt_list_is_sound p s1 (t2 :: l2)); destruct (term_gt_list p s1 (t2 :: l2)) as [[ | ] | ]; intro H'; trivial;\ndo 2 right; exists (@nil (term * term)); exists t1; exists t2; exists l1; exists l2; split.\nintros; contradiction.\nsplit.\nassumption.\nsplit.\nintros u u_in_t2l2; right; apply H'; assumption.\nsplit; apply refl_equal.\nintros; contradiction.\nsplit.\nassumption.\nsplit.\nintros u u_in_t2l2; right; apply H'; assumption.\nsplit; apply refl_equal.\nintros; contradiction.\nsplit.\nassumption.\nsplit.\nintros u u_in_t2l2; right; apply H'; assumption.\nsplit; apply refl_equal.\n(* 1/4 lexico_eval p s1 s2 l1 l2 = Some Greater_than *)\nintros _.\ngeneralize (term_gt_list_is_sound p s1 (t2 :: l2)); destruct (term_gt_list p s1 (t2 :: l2)) as [[ | ] | ]; intro H'; trivial.\ndo 2 right; exists (@nil (term * term)); exists t1; exists t2; exists l1; exists l2; split.\nintros; contradiction.\nsplit.\nassumption.\nsplit.\nintros u u_in_t2l2; right; apply H'; assumption.\nsplit; apply refl_equal.\n(* 1/3 lexico_eval p s1 s2 l1 l2 = Some  Some Uncomparable *)\nintros _.\ngeneralize (term_gt_list_is_sound p s1 (t2 :: l2)); destruct (term_gt_list p s1 (t2 :: l2)) as [[ | ] | ]; intro H'; trivial.\ndo 2 right; exists (@nil (term * term)); exists t1; exists t2; exists l1; exists l2; split.\nintros; contradiction.\nsplit.\nassumption.\nsplit.\nintros u u_in_t2l2; right; apply H'; assumption.\nsplit; apply refl_equal.\n(* 1/2 lexico_eval p s1 s2 l1 l2 = None *)\nintros _.\ngeneralize (term_gt_list_is_sound p s1 (t2 :: l2)); destruct (term_gt_list p s1 (t2 :: l2)) as [[ | ] | ]; intro H'; trivial.\ndo 2 right; exists (@nil (term * term)); exists t1; exists t2; exists l1; exists l2; split.\nintros; contradiction.\nsplit.\nassumption.\nsplit.\nintros u u_in_t2l2; right; apply H'; assumption.\nsplit; apply refl_equal.\n(* 1/1 p t1 t2 = Some Uncomparable *)\ntrivial.\nQed.\n\nLemma list_gt_list_is_sound :\n  forall p lg ls,\n   match list_gt_list p lg ls with\n   | Some true => forall s, In s ls -> exists g, In g lg /\\ p g s = Some Greater_than\n   | _ => True\n   end.\nProof.\nintros p lg ls; revert lg; induction ls as [ | s ls]; intro lg.\nsimpl; intros; contradiction.\nunfold list_gt_list; simpl.\ngeneralize (list_exists_option_is_sound \n  (fun g : term =>\n       match p g s with\n       | Some Equivalent => Some false\n       | Some Less_than => Some false\n       | Some Greater_than => Some true\n       | Some Uncomparable => Some false\n       | None => None\n       end) lg).\ndestruct \n(list_exists_option\n    (fun g : term =>\n     match p g s with\n     | Some Equivalent => Some false\n     | Some Less_than => Some false\n     | Some Greater_than => Some true\n     | Some Uncomparable => Some false\n     | None => None\n     end) lg) as [[ | ] | ].\nintros [g [g_in_ls H]].\ngeneralize (IHls lg); unfold list_gt_list;\ndestruct \n(list_forall_option\n    (fun s0 : term =>\n     list_exists_option\n       (fun g0 : term =>\n        match p g0 s0 with\n        | Some Equivalent => Some false\n        | Some Less_than => Some false\n        | Some Greater_than => Some true\n        | Some Uncomparable => Some false\n        | None => None\n        end) lg) ls) as [[ | ] | ].\nintros H' u [s_eq_u | u_in_ls].\nsubst u; exists g; split; trivial.\ndestruct (p g s) as [[ | | | ] | ]; (apply refl_equal || discriminate).\napply H'; assumption.\ntrivial.\ntrivial.\nintros _;\ndestruct \n(list_forall_option\n    (fun s0 : term =>\n     list_exists_option\n       (fun g0 : term =>\n        match p g0 s0 with\n        | Some Equivalent => Some false\n        | Some Less_than => Some false\n        | Some Greater_than => Some true\n        | Some Uncomparable => Some false\n        | None => None\n        end) lg) ls) as [[ | ] | ]; trivial.\ntrivial.\nQed. \n \n\nLemma in_mem : forall s l, In s l -> mem equiv s l.\nProof.\nintro s.\ninduction l.\nintro H.\nunfold In in H.\nauto.\nintro H.\nunfold In in H.\ndestruct H.\nrewrite H.\nsimpl.\nleft.\napply (Relation_Definitions.equiv_refl _ _ equiv_equiv).\nsimpl.\nright.\nauto.\nQed.\n\nLemma mult_eval_is_sound_weak :\n  forall p l1 l2, \n   match mult_eval p l1 l2 with\n     | Some Equivalent => False\n     | Some Less_than =>  \n       forall t1, In t1 l1 -> exists t2, In t2 l2 /\\ p t2 t1 = Some Greater_than\n     | Some Greater_than =>  \n       forall t2, In t2 l2 -> exists t1, In t1 l1 /\\ p t1 t2 = Some Greater_than\n     | _ => True\n     end.\nProof.\nintros p l1 l2; unfold mult_eval.\ngeneralize (list_gt_list_is_sound p l1 l2); destruct (list_gt_list p l1 l2) as [[ | ] | ]; trivial.\nintros; generalize (list_gt_list_is_sound p l2 l1); destruct (list_gt_list p l2 l1) as [[ | ] | ]; trivial.\nQed.\n\n\nLemma rpo_eval_is_sound_weak :\n  forall rpo_infos n t1 t2, \n                match rpo_eval rpo_infos n t1 t2 with\n                     | Some Equivalent => equiv t1 t2\n                     | Some Greater_than => rpo rpo_infos.(bb) t2 t1\n                     | Some Less_than => rpo rpo_infos.(bb) t1 t2\n                     | _ => True\n                     end.\nProof.\nintros rpo_infos n; induction n as [ | n].\nintros t1 t2. simpl.\ncase_eq (mem_bool eq_tt_bool (t1, t2) (rpo_l rpo_infos)). \nintros Hfind;apply (find_is_sound (rpo rpo_infos.(bb)) _ (rpo_l_valid rpo_infos) _ _ (Hfind)).\nintro;\ncase_eq (mem_bool eq_tt_bool (t2, t1) (rpo_l rpo_infos)). \nintros Hfind;apply (find_is_sound (rpo rpo_infos.(bb)) _ (rpo_l_valid rpo_infos) _ _ (Hfind)).\nintro. \ncase_eq (mem_bool eq_tt_bool (t1, t2) (equiv_l rpo_infos)). \nintros Hfind;apply (find_is_sound equiv _ (equiv_l_valid rpo_infos) _ _ (Hfind)).\nintro;\ncase_eq (mem_bool eq_tt_bool (t2, t1) (equiv_l rpo_infos)). \nintros Hfind; apply equiv_sym.\napply equiv_equiv.\napply (find_is_sound equiv _ (equiv_l_valid rpo_infos) _ _ (Hfind)).\ntauto.\n(* induction step *)\nintros t1 t2; rewrite rpo_eval_equation.\ncase_eq (mem_bool eq_tt_bool (t1, t2) (rpo_l rpo_infos)). \nintros Hfind;apply (find_is_sound (rpo rpo_infos.(bb)) _ (rpo_l_valid rpo_infos) _ _ (Hfind)).\nintros _;\ncase_eq (mem_bool eq_tt_bool (t2, t1) (rpo_l rpo_infos)). \nintros Hfind;apply (find_is_sound (rpo rpo_infos.(bb)) _ (rpo_l_valid rpo_infos) _ _ (Hfind)).\nintros _. \ncase_eq (mem_bool eq_tt_bool (t1, t2) (equiv_l rpo_infos)). \nintros Hfind;apply (find_is_sound equiv _ (equiv_l_valid rpo_infos) _ _ (Hfind)).\nintros _;\ncase_eq (mem_bool eq_tt_bool (t2, t1) (equiv_l rpo_infos)). \nintros Hfind; apply equiv_sym.\napply equiv_equiv.\napply (find_is_sound equiv _ (equiv_l_valid rpo_infos) _ _ (Hfind)).\nintros _.\nassert (E1 := equiv_eval_is_sound_weak rpo_infos (S n) t1 t2); \ndestruct (equiv_eval rpo_infos (S n) t1 t2) as [ [ | ] | ].\n(* 1/3 t1 and t2 are equivalent *)\napply E1; trivial.\n(* 1/2 t1 and t2 are not equivalent *)\nclear E1; \nassert (H : forall v f l, var_in_term_list v l = true -> rpo rpo_infos.(bb) (Var v) (Term f l)).\nintros v f l H; apply trans_clos_subterm_rpo; trivial.\nassert (H' : (In (Var v) l \\/ \n                  (exists t, In t l /\\ trans_clos direct_subterm (Var v) t)) -> trans_clos direct_subterm (Var v) (Term f l)).\nintros [v_in_l | [t [t_in_l H']]].\nleft; trivial.\napply trans_clos_is_trans with t; trivial; left; trivial.\napply H'; clear H'.\ngeneralize H; clear H; pattern l; refine (list_rec3 size _ _ _); clear l.\nintros m; induction m as [ | m]; intros [ | t l] L.\nintros; discriminate.\nsimpl in L; absurd (1 <= 0); auto with arith;\nrefine (le_trans _ _ _ _ L); apply le_trans with (size t); auto with arith;\napply size_ge_one.\nintros; discriminate.\nsimpl in L; assert (Sl : list_size size l <= m).\napply le_S_n; refine (le_trans _ _ _ _ L); \napply (plus_le_compat_r 1 (size t) (list_size size l));\napply size_ge_one.\ndestruct t as [v' | f' l']; rewrite var_in_term_list_equation.\ngeneralize (X.eq_bool_ok v v'); case (X.eq_bool v v'); [intros v_eq_v' _ | intro v_diff_v'].\nleft; subst; left; trivial.\nintro H; destruct (IHm _ Sl H) as [v_in_l | [t [t_in_l H']]].\nleft; right; trivial.\nright; exists t; split; trivial; right; trivial.\nassert (Sl' : list_size size l' <= m).\napply le_S_n; refine (le_trans _ _ _ _ L); rewrite size_unfold; simpl;\napply le_n_S; auto with arith.\ngeneralize (IHm _ Sl'); destruct (var_in_term_list v l').\nintro H; destruct (H (refl_equal _)) as [v_in_l' | [t [t_in_l' H']]].\nright; exists (Term f' l'); split.\nleft; trivial.\nleft; trivial.\nright; exists (Term f' l'); split.\nleft; trivial.\napply trans_clos_is_trans with t; trivial; left; trivial.\nintros _; generalize (IHm _ Sl); destruct (var_in_term_list v l).\nintro H; destruct (H (refl_equal _)) as [v_in_l' | [t [t_in_l' H']]].\nleft; right; trivial.\nright; exists t; split; trivial; right; trivial.\nintros; discriminate.\ndestruct t1 as [v1 | f1 l1]; destruct t2 as [v2 | f2 l2]; trivial.\ngeneralize (H v1 f2 l2); destruct (var_in_term_list v1 l2); \nintro H'; trivial; apply H'; trivial.\ngeneralize (H v2 f1 l1); destruct (var_in_term_list v2 l1); \nintro H'; trivial; apply H'; trivial.\n(* 1/2 t1 = Term f1 l1, t2 = Term f2 l2 *)\ngeneralize (list_exists_option_is_sound \n  (fun t : term =>\n        match rpo_eval rpo_infos n t (Term f2 l2) with\n        | Some Equivalent => Some true\n        | Some Less_than => Some false\n        | Some Greater_than => Some true\n        | Some Uncomparable => Some false\n        | None => None (A:=bool)\n        end) l1);\ndestruct (list_exists_option\n     (fun t : term =>\n      match rpo_eval rpo_infos n t (Term f2 l2) with\n      | Some Equivalent => Some true\n      | Some Less_than => Some false\n      | Some Greater_than => Some true\n      | Some Uncomparable => Some false\n      | None => None (A:=bool)\n      end) l1) as [ [ | ] | ].\n(* 1/4 there is a term in l1 which is greater than (Term f2 l2) *)\nintros [t1 [t1_in_l1 t1_gt_f2l2]]; simpl; \napply Subterm with t1; trivial.\napply in_impl_mem; trivial.\nexact Eq.\ngeneralize (IHn t1 (Term f2 l2)); \ndestruct (rpo_eval rpo_infos n t1 (Term f2 l2)) as [ [ | | | ] | ]; try discriminate.\nintro H1; apply Equiv; apply (equiv_sym _ _ equiv_equiv); trivial.\nintro H1; apply Lt; trivial.\n(* 1/3 there are no terms in l1 which are greater than (Term f2 l2) *)\nintros _;\ngeneralize (list_exists_option_is_sound \n  (fun t : term =>\n        match rpo_eval rpo_infos n (Term f1 l1) t with\n        | Some Equivalent => Some true\n        | Some Less_than => Some true\n        | Some Greater_than => Some false\n        | Some Uncomparable => Some false\n        | None => None (A:=bool)\n        end) l2);\ndestruct (list_exists_option\n     (fun t : term =>\n      match rpo_eval rpo_infos n (Term f1 l1) t with\n      | Some Equivalent => Some true\n      | Some Less_than => Some true\n      | Some Greater_than => Some false\n      | Some Uncomparable => Some false\n      | None => None (A:=bool)\n      end) l2) as [ [ | ] | ].\n(* 1/5 there is a term in l2 which is greater than (Term f1 l1) *)\nintros [t2 [t2_in_l2 t2_gt_f1l1]]; simpl; apply Subterm with t2; trivial.\napply in_impl_mem; trivial.\nexact Eq.\ngeneralize (IHn (Term f1 l1) t2); \ndestruct (rpo_eval rpo_infos n (Term f1 l1) t2) as [ [ | | | ] | ]; try discriminate.\nintro; apply Equiv; trivial.\nintro; apply Lt; trivial.\n(* 1/4 there are no terms in l2 which are greater than (Term f1 l1) *)\nintros _;\ngeneralize (prec_eval_is_sound f1 f2); destruct (prec_eval f1 f2).\n(* 1/7 f1 = f2 *)\nintro f1_eq_f2. \nassert (Sf1:status Prec f1 = status Prec f2).\n apply prec_eq_status; trivial.\ndestruct (status Prec f2). rewrite Sf1.\n(* 1/8 f1 has a Lex status *)\nsimpl; assert (H' := lexico_eval_is_sound (rpo_eval rpo_infos n) (Term f1 l1)\n                                (Term f2 l2) l1 l2).\ndestruct (lexico_eval (rpo_eval rpo_infos n) (Term f1 l1) (Term f2 l2) l1 l2) as [ [ | | | ] | ].\n(* 1/12 lexico_eval (rpo_eval rpo_infos n) (Term f1 l1) (Term f1 l2) l1 l2 = Some Equivalent *)\ndestruct H' as [ll [E_ll [H1 H2]]].\nrewrite (f_equal (@length _) H1); rewrite (f_equal (@length _) H2); do 2 rewrite length_map.\nrewrite <- beq_nat_refl; simpl.\napply (@Eq_lex f1 f2 l1 l2 Sf1). assert (H3:= prec_eq_status Prec). assert (H3':= H3 f1 f2). assert (H4: status Prec f1 = status Prec f2). apply H3'; trivial. rewrite <- H4; trivial. trivial.\nsubst l1 l2; induction ll as [ | [t1 t2] ll]; simpl.\napply Eq_list_nil.\napply Eq_list_cons.\ngeneralize (IHn t1 t2); rewrite (E_ll _ _ (or_introl _ (refl_equal _))); intro; assumption.\napply IHll; intros; apply E_ll; right; assumption.\n(* 1/11 lexico_eval (rpo_eval rpo_infos n) (Term f1 l1) (Term f1 l2) l1 l2 = Some Less_than *)\ncase_eq (beq_nat (length l1) (length l2)); simpl.\nintro L; apply (@Top_eq_lex rpo_infos.(bb) f1 f2 l2 l1 Sf1).  assert (H3:= prec_eq_status Prec). assert (H3':= H3 f1 f2). assert (H4: status Prec f1 = status Prec f2). apply H3'; trivial. rewrite <- H4; trivial. trivial.\nleft; apply sym_eq; apply beq_nat_true; assumption.\ndestruct H' as [[H1 H2] | [[ll [t2 [l2' [ _ [H1 H2]]]]] | [ll [t1 [t2 [l1' [l2' [Hll [Ht [H' [H1 H2]]]]]]]]]]].\ndestruct l2 as [ | a2 l2]; [apply False_rec; apply H2; apply refl_equal | subst l1; discriminate].\nsubst l1 l2; rewrite length_app in L; do 2 rewrite length_map in L.\napply False_rec; generalize (beq_nat_true _ _ L); clear L; induction ll as [ | [u1 u2] ll].\ndiscriminate.\nintro L; injection L; clear L; intro L; apply IHll; assumption.\nclear L H'; subst l1 l2; induction ll as [ | [u1 u2] ll].\nsimpl; constructor 1; generalize (IHn t1 t2); rewrite Ht; intro; assumption.\nsimpl; constructor 2.\ngeneralize (IHn u1 u2); rewrite (Hll _ _ (or_introl _ (refl_equal _))); intro; assumption.\napply IHll; intros; apply Hll; right; assumption.\ndestruct H' as [[H1 H2] | [[ll [t2 [l2' [_ [H1 H2]]]]] | [ll [t1 [t2 [l1' [l2' [Hll [Ht [H' [H1 H2]]]]]]]]]]].\nintros; subst l1; contradiction.\nsubst l1 l2; rewrite length_app in L; do 2 rewrite length_map in L.\napply False_rec; generalize (beq_nat_true _ _ L); clear L; induction ll as [ | [u1 u2] ll].\ndiscriminate.\nintro L; injection L; clear L; intro L; apply IHll; assumption.\nintros u u_in_l1; rewrite mem_in_eq in u_in_l1; destruct u_in_l1 as [u' [u_eq_u' u'_in_l1]].\ndestruct (H' _ u'_in_l1) as [ [u2 [u2_in_l2 u'_le_u2]] | H''].\napply Subterm with u2.\napply in_impl_mem; trivial.\nintros; apply Eq.\ndestruct u'_le_u2 as [u'_eq_u2 | u'_lt_u2].\nleft; apply (equiv_trans _ _ equiv_equiv) with u'; trivial.\ngeneralize (IHn u' u2); rewrite u'_eq_u2; intro; assumption.\nright; rewrite (equiv_rpo_equiv_2 _ u_eq_u'); generalize (IHn u' u2); rewrite u'_lt_u2; intro; assumption.\nrewrite (equiv_rpo_equiv_2 _ u_eq_u'); generalize (IHn (Term f2 l2) u'); rewrite H''; intro; assumption.\nintros _; generalize (leb_complete (length l1) (rpo_infos.(bb))); case (leb (length l1) rpo_infos.(bb)); [idtac | simpl; trivial].\ngeneralize (leb_complete (length l2) (rpo_infos.(bb))); case (leb (length l2) (bb rpo_infos)); simpl; [idtac | trivial].\nintros L2 L1; apply (@Top_eq_lex rpo_infos.(bb) f1 f2 l2 l1 Sf1).  assert (H3:= prec_eq_status Prec). assert (H3':= H3 f1 f2). assert (H4: status Prec f1 = status Prec f2). apply H3'; trivial. rewrite <- H4; trivial. trivial.\nright; split; [apply L1 | apply L2]; apply refl_equal.\nclear L1 L2; destruct H' as [[H1 H2] | [[ll [t2 [l2' [Hll [H1 H2]]]]] | [ll [t1 [t2 [l1' [l2' [Hll [Ht [H' [H1 H2]]]]]]]]]]].\nsubst l1; destruct l2 as [ | a2 l2]; [apply False_rec; apply H2; apply refl_equal | constructor 3].\nsubst l1 l2; induction ll as [ | [u1 u2] ll].\nsimpl; constructor 3.\nsimpl; constructor 2.\ngeneralize (IHn u1 u2); rewrite (Hll _ _ (or_introl _ (refl_equal _))); intro; assumption.\napply IHll; intros; apply Hll; right; assumption.\nclear H'; subst l1 l2; induction ll as [ | [u1 u2] ll].\nsimpl; constructor 1; generalize (IHn t1 t2); rewrite Ht; intro; assumption.\nsimpl; constructor 2.\ngeneralize (IHn u1 u2); rewrite (Hll _ _ (or_introl _ (refl_equal _))); intro; assumption.\napply IHll; intros; apply Hll; right; assumption.\nclear L1 L2; destruct H' as [[H1 H2] | [[ll [t2 [l2' [Hll [H1 H2]]]]] | [ll [t1 [t2 [l1' [l2' [Hll [Ht [H' [H1 H2]]]]]]]]]]].\nintros; subst l1; contradiction.\nintros u u_in_l1; rewrite mem_in_eq in u_in_l1; destruct u_in_l1 as [u' [u_eq_u' u'_in_l1]].\nsubst l1; rewrite in_map_iff in u'_in_l1; destruct u'_in_l1 as [[u1 u2] [H1 K2]].\napply Subterm with u2.\nsubst l2; rewrite <- mem_or_app; left; apply in_impl_mem.\napply Eq.\nrewrite in_map_iff; exists (u1,u2); split; trivial.\nsimpl in H1; subst u1; left; apply (equiv_trans _ _ equiv_equiv) with u'; trivial.\ngeneralize (IHn u' u2); rewrite (Hll _ _ K2); intro; assumption.\nintros u u_in_l1; rewrite mem_in_eq in u_in_l1; destruct u_in_l1 as [u' [u_eq_u' u'_in_l1]].\ndestruct (H' _ u'_in_l1) as [ [u2 [u2_in_l2 u'_le_u2]] | H''].\napply Subterm with u2.\napply in_impl_mem; trivial.\nintros; apply Eq.\ndestruct u'_le_u2 as [u'_eq_u2 | u'_lt_u2].\nleft; apply (equiv_trans _ _ equiv_equiv) with u'; trivial.\ngeneralize (IHn u' u2); rewrite u'_eq_u2; intro; assumption.\nright; rewrite (equiv_rpo_equiv_2 _ u_eq_u'); generalize (IHn u' u2); rewrite u'_lt_u2; intro; assumption.\nrewrite (equiv_rpo_equiv_2 _ u_eq_u'); generalize (IHn (Term f2 l2) u'); rewrite H''; intro; assumption.\n(* 1/10 lexico_eval (rpo_eval rpo_infos n) (Term f1 l1) (Term f1 l2) l1 l2 = Some Greater_than *)\ncase_eq (beq_nat (length l1) (length l2)); simpl.\nassert (Sf2: status Prec f2 = Lex).\n assert (H3:= prec_eq_status Prec). assert (H3':= H3 f1 f2). assert (H4: status Prec f1 = status Prec f2). apply H3'; trivial. rewrite <- H4; trivial. trivial.\nintro L; apply (@Top_eq_lex rpo_infos.(bb) f2 f1 l1 l2 Sf2). trivial. apply prec_eq_sym; trivial.\nleft; apply beq_nat_true; assumption.\ndestruct H' as [[H1 H2] | [[ll [t1 [l1' [ _ [H1 H2]]]]] | [ll [t1 [t2 [l1' [l2' [Hll [Ht [H' [H1 H2]]]]]]]]]]].\ndestruct l1 as [ | a1 l1]; [apply False_rec; apply H1; apply refl_equal | subst l2; discriminate].\nsubst l1 l2; rewrite length_app in L; do 2 rewrite length_map in L.\napply False_rec; generalize (beq_nat_true _ _ L); clear L; induction ll as [ | [u1 u2] ll].\ndiscriminate.\nintro L; injection L; clear L; intro L; apply IHll; assumption.\nclear L H'; subst l1 l2; induction ll as [ | [u1 u2] ll].\nsimpl; constructor 1; generalize (IHn t1 t2); rewrite Ht; intro; assumption.\nsimpl; constructor 2.\napply (equiv_sym _ _ equiv_equiv); generalize (IHn u1 u2); rewrite (Hll _ _ (or_introl _ (refl_equal _))); intro; assumption.\napply IHll; intros; apply Hll; right; assumption.\ndestruct H' as [[H1 H2] | [[ll [t1 [l1' [_ [H1 H2]]]]] | [ll [t1 [t2 [l1' [l2' [Hll [Ht [H' [H1 H2]]]]]]]]]]].\nintros; subst l2; contradiction.\nsubst l1 l2; rewrite length_app in L; do 2 rewrite length_map in L.\napply False_rec; generalize (beq_nat_true _ _ L); clear L; induction ll as [ | [u1 u2] ll].\ndiscriminate.\nintro L; injection L; clear L; intro L; apply IHll; assumption.\nintros u u_in_l2; rewrite mem_in_eq in u_in_l2; destruct u_in_l2 as [u' [u_eq_u' u'_in_l2]].\ndestruct (H' _ u'_in_l2) as [ [u1 [u1_in_l1 u'_le_u1]] | H''].\napply Subterm with u1.\napply in_impl_mem; trivial.\nintros; apply Eq.\ndestruct u'_le_u1 as [u'_eq_u1 | u'_lt_u1].\nleft; apply (equiv_trans _ _ equiv_equiv) with u'; trivial.\napply (equiv_sym _ _ equiv_equiv); generalize (IHn u1 u'); rewrite u'_eq_u1; intro; assumption.\nright; rewrite (equiv_rpo_equiv_2 _ u_eq_u'); generalize (IHn u1 u'); rewrite u'_lt_u1; intro; assumption.\nrewrite (equiv_rpo_equiv_2 _ u_eq_u'); generalize (IHn (Term f1 l1) u'); rewrite H''; intro; assumption.\nintros _; generalize (leb_complete (length l1) (rpo_infos.(bb))); case (leb (length l1) rpo_infos.(bb)); [idtac | simpl; trivial].\ngeneralize (leb_complete (length l2) (rpo_infos.(bb))); case (leb (length l2) (bb rpo_infos)); simpl; [idtac | trivial].\n assert (H3:= prec_eq_status Prec). assert (H3':= H3 f1 f2). assert (H4: status Prec f1 = status Prec f2). apply H3'; trivial. assert (Sf2: status Prec f2 = Lex). rewrite <- H4; trivial.\nintros L2 L1; apply (@Top_eq_lex rpo_infos.(bb) f2 f1 l1 l2 Sf2). trivial. apply prec_eq_sym;\ntrivial.\nright; split; [apply L2 | apply L1]; apply refl_equal.\nclear L1 L2; destruct H' as [[H1 H2] | [[ll [t1 [l2' [Hll [H1 H2]]]]] | [ll [t1 [t2 [l1' [l2' [Hll [Ht [H' [H1 H2]]]]]]]]]]].\nsubst l2; destruct l1 as [ | a1 l2]; [apply False_rec; apply H1; apply refl_equal | constructor 3].\nsubst l1 l2; induction ll as [ | [u1 u2] ll].\nsimpl; constructor 3.\nsimpl; constructor 2.\napply (equiv_sym _ _ equiv_equiv); generalize (IHn u1 u2); rewrite (Hll _ _ (or_introl _ (refl_equal _))); intro; assumption.\napply IHll; intros; apply Hll; right; assumption.\nclear H'; subst l1 l2; induction ll as [ | [u1 u2] ll].\nsimpl; constructor 1; generalize (IHn t1 t2); rewrite Ht; intro; assumption.\nsimpl; constructor 2.\napply (equiv_sym _ _ equiv_equiv); generalize (IHn u1 u2); rewrite (Hll _ _ (or_introl _ (refl_equal _))); intro; assumption.\napply IHll; intros; apply Hll; right; assumption.\nclear L1 L2; destruct H' as [[H1 H2] | [[ll [t1 [l1' [Hll [H1 H2]]]]] | [ll [t1 [t2 [l1' [l2' [Hll [Ht [H' [H1 H2]]]]]]]]]]].\nintros; subst l2; contradiction.\nintros u u_in_l2; rewrite mem_in_eq in u_in_l2; destruct u_in_l2 as [u' [u_eq_u' u'_in_l2]].\nsubst l2; rewrite in_map_iff in u'_in_l2; destruct u'_in_l2 as [[u1 u2] [K1 K2]].\napply Subterm with u1.\nsubst l1; rewrite <- mem_or_app; left; apply in_impl_mem.\napply Eq.\nrewrite in_map_iff; exists (u1,u2); split; trivial.\nsimpl in K1; subst u2; left; apply (equiv_trans _ _ equiv_equiv) with u'; trivial.\napply (equiv_sym _ _ equiv_equiv); generalize (IHn u1 u'); rewrite (Hll _ _ K2); intro; assumption.\nintros u u_in_l2; rewrite mem_in_eq in u_in_l2; destruct u_in_l2 as [u' [u_eq_u' u'_in_l2]].\ndestruct (H' _ u'_in_l2) as [ [u1 [u1_in_l1 u'_le_u1]] | H''].\napply Subterm with u1.\napply in_impl_mem; trivial.\nintros; apply Eq.\ndestruct u'_le_u1 as [u'_eq_u1 | u'_lt_u1].\nleft; apply (equiv_trans _ _ equiv_equiv) with u'; trivial.\napply (equiv_sym _ _ equiv_equiv); generalize (IHn u1 u'); rewrite u'_eq_u1; intro; assumption.\nright; rewrite (equiv_rpo_equiv_2 _ u_eq_u'); generalize (IHn u1 u'); rewrite u'_lt_u1; intro; assumption.\nrewrite (equiv_rpo_equiv_2 _ u_eq_u'); generalize (IHn (Term f1 l1) u'); rewrite H''; intro; assumption.\n(* 1/9 lexico_eval (rpo_eval rpo_infos n) (Term f1 l1) (Term f1 l2) l1 l2 = Some Uncomparable *)\ncase (beq_nat (length l1) (length l2)\n      || leb (length l1) (bb rpo_infos) && leb (length l2) (bb rpo_infos)); trivial.\n(* 1/8 lexico_eval (rpo_eval rpo_infos n) (Term f1 l1) (Term f1 l2) l1 l2 = None *)\ncase (beq_nat (length l1) (length l2)\n      || leb (length l1) (bb rpo_infos) && leb (length l2) (bb rpo_infos)); trivial.\n(* 1/7 f1 has a Mul status *)\n assert (H3:= prec_eq_status Prec). assert (H3':= H3 f1 f2). assert (H4: status Prec f1 = status Prec f2). apply H3'; trivial. assert (Sf2: status Prec f2 = Mul). rewrite <- H4; trivial. \nsimpl; assert (H' := remove_equiv_eval_list_is_sound (equiv_eval rpo_infos n) l1 l2).\nrewrite Sf1.\ndestruct (remove_equiv_eval_list (equiv_eval rpo_infos n) l1 l2) as [ [[ | t1' l1'] [ | t2' l2']] | ].\ndestruct H' as [ll [E_ll [P1 [P2 _]]]]. apply (@Eq_mul f1 f2 l1 l2 Sf1); trivial.\nsimpl in P1; simpl in P2. \napply permut0_trans with (map (fun st : term * term => fst st) ll); trivial. apply equiv_equiv.\napply permut_impl with (@eq term); trivial; intros; subst; reflexivity.\napply permut0_trans with (map (fun st : term * term => snd st) ll); trivial. apply equiv_equiv.\nassert (E_ll' : forall t1 t2, In (t1,t2) ll -> equiv t1 t2).\nintros t1 t2 t1t2_in_ll; \nassert (H' := equiv_eval_is_sound_weak rpo_infos n t1 t2);\nrewrite (E_ll t1 t2 t1t2_in_ll) in H'; apply H'; trivial.\nclear E_ll P1 P2; induction ll as [ | [t1 t2] ll].\nreflexivity.\nsimpl; rewrite <- permut0_cons.\napply IHll.\nintros; apply E_ll'; right; trivial. apply equiv_equiv.\napply E_ll'; left; trivial.\nsymmetry; \napply permut_impl with (@eq term); trivial; intros; subst; reflexivity.\ndestruct H' as [ll [E_ll [P1 [P2 _]]]].\napply Top_eq_mul; trivial.\napply (@List_mul _ t2' l2' nil l1); trivial.\nreflexivity.\ntransitivity ((t2' :: l2') ++ (map (fun st : term * term => snd st) ll)).\napply permut_impl with (@eq term); trivial; intros; subst; reflexivity.\nrewrite app_comm_cons; rewrite <- permut_app1.\ntransitivity (map (fun st : term * term => fst st) ll).\nsymmetry.\nassert (E_ll' : forall t1 t2, In (t1,t2) ll -> equiv t1 t2).\nintros t1 t2 t1t2_in_ll; \nassert (H' := equiv_eval_is_sound_weak rpo_infos n t1 t2);\nrewrite (E_ll t1 t2 t1t2_in_ll) in H'; apply H'; trivial.\nclear E_ll P1 P2; induction ll as [ | [t1 t2] ll].\nreflexivity.\nsimpl; rewrite <- permut0_cons.\napply IHll.\nintros; apply E_ll'; right; trivial. apply equiv_equiv.\napply E_ll'; left; trivial.\nsymmetry; \napply permut_impl with (@eq term); trivial; intros; subst; reflexivity. apply equiv_equiv.\nintros; contradiction.\ndestruct H' as [ll [E_ll [P1 [P2 _]]]].\napply Top_eq_mul; trivial. apply prec_eq_sym; trivial.\napply (@List_mul _ t1' l1' nil l2); trivial.\nreflexivity.\ntransitivity ((t1' :: l1') ++ (map (fun st : term * term => fst st) ll)).\napply permut_impl with (@eq term); trivial; intros; subst; reflexivity.\nrewrite app_comm_cons; rewrite <- permut_app1.\ntransitivity (map (fun st : term * term => snd st) ll).\nassert (E_ll' : forall t1 t2, In (t1,t2) ll -> equiv t1 t2).\nintros t1 t2 t1t2_in_ll; \nassert (H' := equiv_eval_is_sound_weak rpo_infos n t1 t2);\nrewrite (E_ll t1 t2 t1t2_in_ll) in H'; apply H'; trivial.\nclear E_ll P1 P2; induction ll as [ | [t1 t2] ll].\nreflexivity.\nsimpl; rewrite <- permut0_cons.\napply IHll.\nintros; apply E_ll'; right; trivial. apply equiv_equiv.\napply E_ll'; left; trivial.\nsymmetry; \napply permut_impl with (@eq term); trivial; intros; subst; reflexivity.  apply equiv_equiv.\nintros; contradiction.\nassert (H'' := mult_eval_is_sound_weak (rpo_eval rpo_infos n) (t1' :: l1') (t2' :: l2')).\ndestruct (mult_eval (rpo_eval rpo_infos n) (t1' :: l1') (t2' :: l2')) as [ [ | | | ] | ].\ncontradiction.\ndestruct H' as [ll [E_ll [P1 [P2 _]]]].\nassert (E_ll' : forall t1 t2, In (t1,t2) ll -> equiv t1 t2).\nintros t1 t2 t1t2_in_ll; \nassert (H' := equiv_eval_is_sound_weak rpo_infos n t1 t2);\nrewrite (E_ll t1 t2 t1t2_in_ll) in H'; apply H'; trivial.\napply Top_eq_mul; trivial.\napply (@List_mul _ t2' l2' (t1' :: l1') (map (fun st : term * term => fst st) ll)); trivial.\napply permut_impl with (@eq term); trivial; intros; subst; reflexivity.\ntransitivity ((t2' :: l2') ++ map (fun st : term * term => snd st) ll).\napply permut_impl with (@eq term); trivial; intros; subst; reflexivity.\nrewrite app_comm_cons; rewrite <- permut_app1.\nclear E_ll P1 P2; induction ll as [ | [t1 t2] ll].\nreflexivity.\nsimpl; rewrite <- permut0_cons.\napply IHll.\nintros; apply E_ll'; right; trivial. apply equiv_equiv.\nsymmetry; apply E_ll'; left; trivial. apply equiv_equiv.\nintros u1 u1_mem_l1'.\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ u1_mem_l1') as [u1' [k1 [k1' [u1_eq_u1' [H' _]]]]].\nsimpl in u1_eq_u1'; simpl in H'.\nassert (u1'_in_l1' : In u1' (t1' :: l1')).\nrewrite H'; apply in_or_app; right; left; trivial.\ndestruct (H'' _ u1'_in_l1') as [u2 [u2_in_l2' u1_lt_u2]];\nexists u2; split.\napply in_impl_mem; trivial.\nexact Eq.\nassert (H''' := IHn u2 u1').\nrewrite u1_lt_u2 in H'''.\nrewrite (equiv_rpo_equiv_2 _ u1_eq_u1'); trivial.\ndestruct H' as [ll [E_ll [P1 [P2 _]]]].\nassert (E_ll' : forall t1 t2, In (t1,t2) ll -> equiv t1 t2).\nintros t1 t2 t1t2_in_ll; \nassert (H' := equiv_eval_is_sound_weak rpo_infos n t1 t2);\nrewrite (E_ll t1 t2 t1t2_in_ll) in H'; apply H'; trivial.\n(* destruct (equiv_swap _ equiv ll E_ll') as [ll' [E_ll'' [H1 [H2 H3]]]]. *)\napply Top_eq_mul; trivial. apply prec_eq_sym; trivial.\napply (@List_mul _ t1' l1' (t2' :: l2') (map (fun st : term * term => fst st) ll)); trivial.\ntransitivity ((t2' :: l2') ++ map (fun st : term * term => snd st) ll).\napply permut_impl with (@eq term); trivial; intros; subst; reflexivity.\nrewrite <- permut_app1.\nclear E_ll P1 P2; induction ll as [ | [t1 t2] ll].\nreflexivity.\nsimpl; rewrite <- permut0_cons.\napply IHll.\nintros; apply E_ll'; right; trivial. apply equiv_equiv.\nsymmetry; apply E_ll'; left; trivial. apply equiv_equiv.\napply permut_impl with (@eq term); trivial; intros; subst; reflexivity.\nintros u2 u2_mem_l2'.\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ u2_mem_l2') as [u2' [k2 [k2' [u2_eq_u2' [H' _]]]]].\nsimpl in u2_eq_u2'; simpl in H'.\nassert (u2'_in_l2' : In u2' (t2' :: l2')).\nrewrite H'; apply in_or_app; right; left; trivial.\ndestruct (H'' _ u2'_in_l2') as [u1 [u1_in_l1' u2_lt_u1]];\nexists u1; split.\napply in_impl_mem; trivial.\nexact Eq.\nassert (H''' := IHn u1 u2').\nrewrite u2_lt_u1 in H'''.\nrewrite (equiv_rpo_equiv_2 _ u2_eq_u2'); trivial.\ntrivial.\ntrivial.\ntrivial.\n(* 1/6 f1 < f2 *)\nintro f1_lt_f2; simpl.\ngeneralize (list_forall_option_is_sound\n      (fun t : term =>\n       match rpo_eval rpo_infos n t (Term f2 l2) with\n       | Some Equivalent => Some false\n       | Some Less_than => Some true\n       | Some Greater_than => Some false\n       | Some Uncomparable => Some false\n       | None => None (A:=bool)\n       end) l1);\ndestruct (list_forall_option\n      (fun t : term =>\n       match rpo_eval rpo_infos n t (Term f2 l2) with\n       | Some Equivalent => Some false\n       | Some Less_than => Some true\n       | Some Greater_than => Some false\n       | Some Uncomparable => Some false\n       | None => None (A:=bool)\n       end) l1) as [ [ | ] | ].\nintros l1_lt_s2; apply Top_gt; trivial.\nintros t1 t1_mem_l1;\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ t1_mem_l1) as [t1' [k1 [k1' [t1_eq_t1' [H' _]]]]].\nsimpl in t1_eq_t1'; simpl in H'.\nassert (t1'_in_l1 : In t1' l1).\nrewrite H'; apply in_or_app; right; left; trivial.\nrewrite (equiv_rpo_equiv_2 _ t1_eq_t1').\nassert (H'' := l1_lt_s2 t1' t1'_in_l1).\nassert (H''' := IHn t1' (Term f2 l2));\ndestruct (rpo_eval rpo_infos n t1' (Term f2 l2)) as [ [ | | | ] | ]; trivial; discriminate.\ntrivial.\ntrivial.\n(* 1/5 f2 < f1 *)\nintro f2_lt_f1; simpl.\ngeneralize (list_forall_option_is_sound\n      (fun t : term =>\n       match rpo_eval rpo_infos n (Term f1 l1) t with\n       | Some Equivalent => Some false\n       | Some Less_than => Some false\n       | Some Greater_than => Some true\n       | Some Uncomparable => Some false\n       | None => None (A:=bool)\n       end) l2); \ndestruct (list_forall_option\n      (fun t : term =>\n       match rpo_eval rpo_infos n (Term f1 l1) t with\n       | Some Equivalent => Some false\n       | Some Less_than => Some false\n       | Some Greater_than => Some true\n       | Some Uncomparable => Some false\n       | None => None (A:=bool)\n       end) l2) as [ [ | ] | ].\nintros s1_gt_l2; apply Top_gt; trivial.\nintros t2 t2_mem_l2; \ndestruct (mem_split_set _ _ equiv_bool_ok _ _ t2_mem_l2) as [t2' [k2 [k2' [t2_eq_t2' [H' _]]]]].\nsimpl in t2_eq_t2'; simpl in H'.\nassert (t2'_in_l2 : In t2' l2).\nrewrite H'; apply in_or_app; right; left; trivial.\nrewrite (equiv_rpo_equiv_2 _ t2_eq_t2').\nassert (H'' := s1_gt_l2 t2' t2'_in_l2).\nassert (H''' := IHn (Term f1 l1) t2');\ndestruct (rpo_eval rpo_infos n (Term f1 l1) t2') as [ [ | | | ] | ]; trivial; discriminate.\ntrivial.\ntrivial.\nsimpl; trivial.\nsimpl; trivial.\nsimpl; trivial.\ntrivial.\nQed.\n\n(* Lemma well_formed_equiv : *)\n(*   forall t1 t2, well_formed t1 -> equiv t1 t2 -> well_formed t2. *)\n(* Proof. *)\n(* intro t1; pattern t1; apply term_rec3; clear t1. *)\n(* intros v t2 _ v_eq_t2; inversion v_eq_t2; subst; unfold well_formed; simpl; trivial. *)\n(* intros f l IH t2 Wfl fl_eq_t2;  *)\n(* inversion fl_eq_t2; subst; trivial. *)\n(* assert (L' := equiv_same_length  fl_eq_t2). *)\n(* destruct (well_formed_unfold Wfl) as [Wl L]. *)\n(* apply well_formed_fold; split. *)\n(* assert (IH' : forall t t2, In t l -> equiv t t2 -> well_formed t2). *)\n(* intros t t2 t_in_l; apply IH; trivial. *)\n(* apply Wl; trivial. *)\n(* generalize l2 H3; clear l2 IH H3 H1 L' L fl_eq_t2 Wfl;  *)\n(* induction l as [ | t l]; intros l2 l_eq_l2; inversion l_eq_l2; subst. *)\n(* contradiction. *)\n(* intros u [u_eq_t2 | u_in_l2]; subst. *)\n(* apply IH' with t; trivial. *)\n(* left; trivial. *)\n(* apply IHl with l0; trivial. *)\n(* intros; apply Wl; right; trivial. *)\n(* intros u1 u2 u1_in_l; apply IH'; right; trivial. *)\n(* rewrite <- L'; trivial. *)\n(* assert (L' := equiv_same_length fl_eq_t2). *)\n(* destruct (well_formed_unfold Wfl) as [Wl L]. *)\n(* apply well_formed_fold; split. *)\n(* assert (IH' : forall t t2, In t l -> equiv t t2 -> well_formed t2). *)\n(* intros t t2 t_in_l; apply IH; trivial. *)\n(* apply Wl; trivial. *)\n(* generalize l2 H3; clear l2 IH H3 H1 L' L fl_eq_t2 Wfl;  *)\n(* induction l as [ | t l]; intros l2 l_eq_l2; inversion l_eq_l2; subst. *)\n(* contradiction. *)\n(* intros u u_in_l2;  *)\n(* destruct (in_app_or _ _ _ u_in_l2) as [u_in_l1 | [u_eq_b | u_in_l3]]. *)\n(* apply IHl with (l1 ++ l3); trivial. *)\n(* intros; apply Wl; right; trivial. *)\n(* intros u1 u2 u1_in_l; apply IH'; right; trivial. *)\n(* apply in_or_app; left; trivial. *)\n(* subst u; apply IH' with t; trivial; left; trivial. *)\n(* apply IHl with (l1 ++ l3); trivial. *)\n(* intros; apply Wl; right; trivial. *)\n(* intros u1 u2 u1_in_l; apply IH'; right; trivial. *)\n(* apply in_or_app; right; trivial. *)\n(* rewrite <- L'; trivial. *)\n(* Qed. *)\n\nLemma lexico_eval_fully_evaluates :\n  forall p s1 s2 l1 l2, \n  (forall t1, In t1 l1 -> p s2 t1 <> None) ->\n  (forall t2, In t2 l2 -> p s1 t2 <> None) ->\n  (forall t1 t2, In t1 l1 -> In t2 l2 -> p t1 t2 <> None) ->\n  lexico_eval p s1 s2 l1 l2 <> None.\nProof.\nintros p s1 s2 l1; induction l1 as [ | t1 l1]; intros [ | t2 l2] Es2 Es1 E;\nsimpl; try discriminate.\nassert (H := E t1 t2 (or_introl _ (refl_equal _)) (or_introl _ (refl_equal _)));\ndestruct (p t1 t2) as [ [ | | | ] | ].\n(* 1/5 p t1 t2 = Some Equivalent *)\napply IHl1; intros; [apply Es2 | apply Es1 | apply E]; right; trivial.\n(* 1/4 p t1 t2 = Some Less_than *)\nunfold term_gt_list; simpl.\ngeneralize (list_forall_option_is_sound\n      (fun t : term =>\n         match p s2 t with\n         | Some Equivalent => Some false\n         | Some Less_than => Some false\n         | Some Greater_than => Some true\n         | Some Uncomparable => Some false\n         | None => None\n         end) l1);\ndestruct (list_forall_option\n       (fun t : term =>\n         match p s2 t with\n         | Some Equivalent => Some false\n         | Some Less_than => Some false\n         | Some Greater_than => Some true\n         | Some Uncomparable => Some false\n         | None => None\n         end) l1) as [ [ | ] | ].\n(* 1/6 all terms in l1 are smaller than s2 *)\nclear H; assert (H := Es2 t1 (or_introl _ (refl_equal _))).\ndestruct (p s2 t1) as [ [ | | | ] | ].\nintros _; discriminate.\nintros _; discriminate.\nintros _; discriminate.\nintros _; discriminate.\nintros _; apply H; trivial.\n(* 1/5 NOT all terms in l1 are smaller than s2 *)\nclear H; assert (H := Es2 t1 (or_introl _ (refl_equal _))).\ndestruct (p s2 t1) as [ [ | | | ] | ].\nintros _; discriminate.\nintros _; discriminate.\nintros _; discriminate.\nintros _; discriminate.\nintros _; apply H; trivial.\n(* 1/4 at least one evaluation does not yield a result *) \nintros [u1 [u1_in_l1 pt1s2_eq_none]].\nassert (H' := Es2 _ (or_intror _ u1_in_l1)). \ndestruct (p s2 u1) as [ [ | | | ] | ]; trivial.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\nabsurd (@None comp = None); trivial.\n(* 1/3 p t1 t2 = Some Greater_than *)\nunfold term_gt_list; simpl.\ngeneralize (list_forall_option_is_sound\n        (fun t : term =>\n         match p s1 t with\n         | Some Equivalent => Some false\n         | Some Less_than => Some false\n         | Some Greater_than => Some true\n         | Some Uncomparable => Some false\n         | None => None\n         end) l2);\ndestruct (list_forall_option\n        (fun t : term =>\n         match p s1 t with\n         | Some Equivalent => Some false\n         | Some Less_than => Some false\n         | Some Greater_than => Some true\n         | Some Uncomparable => Some false\n         | None => None\n         end) l2) as [ [ | ] | ].\n(* 1/5 all terms in l2 are smaller than s1 *)\nclear H; assert (H := Es1 t2 (or_introl _ (refl_equal _))).\ndestruct (p s1 t2) as [ [ | | | ] | ].\nintros _; discriminate.\nintros _; discriminate.\nintros _; discriminate.\nintros _; discriminate.\nintros _; apply H; trivial.\n(* 1/4 NOT all terms in l2 are smaller than s1 *)\nclear H; assert (H := Es1 t2 (or_introl _ (refl_equal _))).\ndestruct (p s1 t2) as [ [ | | | ] | ].\nintros _; discriminate.\nintros _; discriminate.\nintros _; discriminate.\nintros _; discriminate.\nintros _; apply H; trivial.\n(* 1/3 at least one evaluation does not yield a result *) \nintros [u2 [u2_in_l2 ps1u2_eq_none]].\nassert (H' := Es1 _ (or_intror _ u2_in_l2)). \ndestruct (p s1 u2) as [ [ | | | ] | ]; trivial.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\nabsurd (@None comp = None); trivial.\n(* 1/2 p t1 t2 = Some Uncomparable *)\ndiscriminate.\n(* 1/1 p t1 t2 = None *)\ntrivial.\nQed.\n\nLemma mult_eval_fully_evaluates :\n  forall p l1 l2, \n  (forall t1 t2, In t1 l1 -> In t2 l2 -> p t1 t2 <> None) ->\n  (forall t1 t2, In t1 l1 -> In t2 l2 -> p t2 t1 <> None) ->\n  mult_eval p l1 l2 <> None.\nProof.\nintros p [ | t1 l1] l2 E E'; unfold mult_eval, list_gt_list.\nsimpl; clear E; induction l2 as [ | t2 l2]; simpl.\ndiscriminate.\ndestruct (list_forall_option (fun _ : term => Some false) l2) as [ [ | ] | ].\ndiscriminate.\ndiscriminate.\napply IHl2; intros; contradiction.\ngeneralize (list_forall_option_is_sound\n    (fun s : term =>\n     list_exists_option\n       (fun g : term =>\n        match p g s with\n        | Some Equivalent => Some false\n        | Some Less_than => Some false\n        | Some Greater_than => Some true\n        | Some Uncomparable => Some false\n        | None => None\n        end) (t1 :: l1)) l2); \ndestruct (list_forall_option\n    (fun s : term =>\n     list_exists_option\n       (fun g : term =>\n        match p g s with\n        | Some Equivalent => Some false\n        | Some Less_than => Some false\n        | Some Greater_than => Some true\n        | Some Uncomparable => Some false\n        | None => None\n        end) (t1 :: l1)) l2) as [ [ | ] | ].\nintros _; discriminate.\nintros _;\ngeneralize (list_forall_option_is_sound\n    (fun s : term =>\n     list_exists_option\n       (fun g : term =>\n        match p g s with\n        | Some Equivalent => Some false\n        | Some Less_than => Some false\n        | Some Greater_than => Some true\n        | Some Uncomparable => Some false\n        | None => None\n        end) l2) (t1 :: l1));\ndestruct (list_forall_option\n    (fun s : term =>\n     list_exists_option\n       (fun g : term =>\n        match p g s with\n        | Some Equivalent => Some false\n        | Some Less_than => Some false\n        | Some Greater_than => Some true\n        | Some Uncomparable => Some false\n        | None => None\n        end) l2) (t1 :: l1)) as [ [ | ] | ].\nintros _; discriminate.\nintros _; discriminate.\nintros [u1 [u1_in_l1 H]].\nassert (H' := list_exists_option_is_sound\n      (fun g : term =>\n       match p g u1 with\n       | Some Equivalent => Some false\n       | Some Less_than => Some false\n       | Some Greater_than => Some true\n       | Some Uncomparable => Some false\n       | None => None\n       end) l2); rewrite H in H'. \ndestruct H' as [ [u2 [u2_in_l2 pu1u2_eq_none]] _].\nassert (H' := E' u1 u2 u1_in_l1 u2_in_l2);\ndestruct (p u2 u1) as [ [ | | | ] | ]; trivial; discriminate.\nintros [u2 [u2_in_l2 H]].\nassert (H' := list_exists_option_is_sound\n      (fun g : term =>\n       match p g u2 with\n       | Some Equivalent => Some false\n       | Some Less_than => Some false\n       | Some Greater_than => Some true\n       | Some Uncomparable => Some false\n       | None => None\n       end) (t1 :: l1)); rewrite H in H'. \ndestruct H' as [ [u1 [u1_in_l1 pu1u2_eq_none]] _].\nassert (H' := E u1 u2 u1_in_l1 u2_in_l2);\ndestruct (p u1 u2) as [ [ | | | ] | ]; trivial; discriminate.\nQed.\n\nLemma rpo_eval_terminates :\n  forall rpo_infos n t1 t2, size t1 + size t2 <= n -> rpo_eval rpo_infos n t1 t2 <> None.\nProof.\nintros rpo_infos n; induction n as [ | n].\n(* Base case *)\nintros t1 t2 St1; \nabsurd (1 <= 0); auto with arith; \napply le_trans with (size t1 + size t2); trivial;\napply le_trans with (1 + size t2);\n[apply le_plus_l | apply plus_le_compat_r; apply size_ge_one].\n(* Induction step *)\nintros t1 t2 St; rewrite rpo_eval_equation.\ncase (mem_bool eq_tt_bool (t1, t2) (rpo_l rpo_infos)).\nintro;discriminate.\ncase (mem_bool eq_tt_bool (t2, t1) (rpo_l rpo_infos)).\nintro;discriminate.\ncase (mem_bool eq_tt_bool (t1, t2) (equiv_l rpo_infos)).\nintro;discriminate.\ncase (mem_bool eq_tt_bool (t2, t1) (equiv_l rpo_infos)).\nintro;discriminate.\nassert (T := @equiv_eval_terminates rpo_infos (S n) t1 t2 St); \ndestruct (equiv_eval rpo_infos (S n) t1 t2) as [ [ | ] | ]; try discriminate.\ndestruct t1 as [v1 | f1 l1]; destruct t2 as [v2 | f2 l2].\ndiscriminate.\ndestruct (var_in_term_list v1 l2); discriminate.\ndestruct (var_in_term_list v2 l1); discriminate.\ngeneralize (list_exists_option_is_sound \n  (fun t : term =>\n      match rpo_eval rpo_infos n t (Term f2 l2) with\n      | Some Equivalent => Some true\n      | Some Less_than => Some false\n      | Some Greater_than => Some true\n      | Some Uncomparable => Some false\n      | None => None\n      end) l1);\ndestruct (list_exists_option\n  (fun t : term =>\n      match rpo_eval rpo_infos n t (Term f2 l2) with\n      | Some Equivalent => Some true\n      | Some Less_than => Some false\n      | Some Greater_than => Some true\n      | Some Uncomparable => Some false\n      | None => None\n      end) l1) as [ [ | ] | ].\nintros _; simpl; discriminate.\nintros _.\ngeneralize (list_exists_option_is_sound \n  (fun t : term =>\n          match rpo_eval rpo_infos n (Term f1 l1) t with\n          | Some Equivalent => Some true\n          | Some Less_than => Some true\n          | Some Greater_than => Some false\n          | Some Uncomparable => Some false\n          | None => None\n          end) l2);\ndestruct (list_exists_option\n        (fun t : term =>\n          match rpo_eval rpo_infos n (Term f1 l1) t with\n          | Some Equivalent => Some true\n          | Some Less_than => Some true\n          | Some Greater_than => Some false\n          | Some Uncomparable => Some false\n          | None => None\n          end) l2) as [ [ | ] | ].\nintros _; simpl; discriminate.\nintros _; simpl; destruct (prec_eval f1 f2); try discriminate.\ndestruct (status Prec f1).\ncase (beq_nat (length l1) (length l2)\n    || leb (length l1) (bb rpo_infos) && leb (length l2) (bb rpo_infos)).\napply lexico_eval_fully_evaluates.\nintros t1 t1_in_l1; apply IHn.\nrewrite plus_comm.\napply le_S_n; refine (le_trans _ _ _ _ St).\nreplace (S (size t1 + size (Term f2 l2))) with \n                (S (size t1) + size (Term f2 l2)); trivial.\napply plus_le_compat_r; apply size_direct_subterm; trivial.\nintros t2 t2_in_l2; apply IHn.\napply le_S_n; refine (le_trans _ _ _ _ St); rewrite plus_comm;\nreplace (S (size t2 + size (Term f1 l1))) with \n                (S (size t2) + size (Term f1 l1)); trivial; rewrite plus_comm;\napply plus_le_compat_l; apply size_direct_subterm; trivial.\nintros t1 t2 t1_in_l1 t2_in_l2; apply IHn.\napply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size t1 + size t2)) with  (S (size t1) + size t2); trivial;\napply plus_le_compat.\napply size_direct_subterm; trivial.\napply lt_le_weak; apply size_direct_subterm; trivial.\ndiscriminate.\ngeneralize (remove_equiv_eval_list_is_sound (equiv_eval rpo_infos n) l1 l2);\ndestruct (remove_equiv_eval_list (equiv_eval rpo_infos n) l1 l2) as [ [[ | t1' l1'] [ | t2' l2']] | ].\nintros _; discriminate.\nintros _; discriminate.\nintros _; discriminate.\nintros [ll [H [P1 [P2 H']]]]. \napply mult_eval_fully_evaluates.\nintros t1 t2 t1_in_l1' t2_in_l2'; apply IHn.\napply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size t1 + size t2)) with  (S (size t1) + size t2); trivial;\napply plus_le_compat.\napply size_direct_subterm; simpl;\nrewrite (in_permut_in P1); apply in_or_app; left; trivial.\napply lt_le_weak; apply size_direct_subterm; simpl;\nrewrite (in_permut_in P2); apply in_or_app; left; trivial.\nintros t1 t2 t1_in_l1' t2_in_l2'; apply IHn.\napply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size t2 + size t1)) with  (S (size t2) + size t1); trivial.\nrewrite plus_comm; apply plus_le_compat.\napply lt_le_weak; apply size_direct_subterm; simpl;\nrewrite (in_permut_in P1); apply in_or_app; left; trivial.\napply size_direct_subterm; simpl;\nrewrite (in_permut_in P2); apply in_or_app; left; trivial.\nintros [t1 [t2 [t1_in_l1 [t2_in_l2 H]]]];\nassert (H' := @equiv_eval_terminates rpo_infos n t1 t2);\ndestruct (equiv_eval rpo_infos n t1 t2) as [ [ | ] | ].\ndiscriminate.\ndiscriminate.\nintros _; apply H'; trivial.\napply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size t1 + size t2)) with  (S (size t1) + size t2); trivial;\napply plus_le_compat.\napply size_direct_subterm; trivial.\napply lt_le_weak; apply size_direct_subterm; trivial.\ngeneralize (list_forall_option_is_sound\n    (fun t : term =>\n     match rpo_eval rpo_infos n t (Term f2 l2) with\n     | Some Equivalent => Some false\n     | Some Less_than => Some true\n     | Some Greater_than => Some false\n     | Some Uncomparable => Some false\n     | None => None (A:=bool)\n     end) l1);\ndestruct (list_forall_option\n    (fun t : term =>\n     match rpo_eval rpo_infos n t (Term f2 l2) with\n     | Some Equivalent => Some false\n     | Some Less_than => Some true\n     | Some Greater_than => Some false\n     | Some Uncomparable => Some false\n     | None => None (A:=bool)\n     end) l1) as [ [ | ] | ].\nintros _; discriminate.\nintros _; discriminate.\nintros [u1 [u1_in_l1 H]]; assert (H' := IHn u1 (Term f2 l2)); \ndestruct (rpo_eval rpo_infos n u1 (Term f2 l2)) as [ [ | | | ] | ].\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\napply H'.\napply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size u1 + size (Term f2 l2))) with \n                (S (size u1) + size (Term f2 l2)); trivial;\napply plus_le_compat_r; apply size_direct_subterm; trivial.\ngeneralize  (list_forall_option_is_sound\n    (fun t : term =>\n     match rpo_eval rpo_infos n (Term f1 l1) t with\n     | Some Equivalent => Some false\n     | Some Less_than => Some false\n     | Some Greater_than => Some true\n     | Some Uncomparable => Some false\n     | None => None (A:=bool)\n     end) l2);\ndestruct (list_forall_option\n    (fun t : term =>\n     match rpo_eval rpo_infos n (Term f1 l1) t with\n     | Some Equivalent => Some false\n     | Some Less_than => Some false\n     | Some Greater_than => Some true\n     | Some Uncomparable => Some false\n     | None => None (A:=bool)\n     end) l2) as [ [ | ] | ].\nintros _; discriminate.\nintros _; discriminate.\nintros [u2 [u2_in_l2 H]]; assert (H' := IHn (Term f1 l1) u2); \ndestruct (rpo_eval rpo_infos n (Term f1 l1) u2) as [ [ | | | ] | ].\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\napply H'.\napply le_S_n; refine (le_trans _ _ _ _ St); rewrite plus_comm;\nreplace (S (size u2 + size (Term f1 l1))) with \n                (S (size u2) + size (Term f1 l1)); trivial; rewrite plus_comm;\napply plus_le_compat_l; apply size_direct_subterm; trivial.\nintros [[u2 [u2_in_l2 H]] _]; assert (H' := IHn (Term f1 l1) u2); \ndestruct (rpo_eval rpo_infos n (Term f1 l1) u2) as [ [ | | | ] | ].\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\napply H'.\napply le_S_n; refine (le_trans _ _ _ _ St); rewrite plus_comm;\nreplace (S (size u2 + size (Term f1 l1))) with \n                (S (size u2) + size (Term f1 l1)); trivial; rewrite plus_comm;\napply plus_le_compat_l; apply size_direct_subterm; trivial.\nintros [[u1 [u1_in_l1 H]] _]; assert (H' := IHn u1 (Term f2 l2)); \ndestruct (rpo_eval rpo_infos n u1 (Term f2 l2)) as [ [ | | | ] | ].\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\napply H'.\napply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size u1 + size (Term f2 l2))) with \n                (S (size u1) + size (Term f2 l2)); trivial;\napply plus_le_compat_r; apply size_direct_subterm; trivial.\nintros _; apply T; trivial.\nQed.\n\nLemma rpo_eval_is_complete_equivalent :\n  forall rpo_infos n t1 t2, size t1 + size t2 <= n -> equiv t1 t2 ->\n        rpo_eval rpo_infos n t1 t2 = Some Equivalent.\nProof.\nintros rpo_infos n t1 t2 St t1_eq_t2; \nrewrite rpo_eval_equation.\ncase_eq (mem_bool eq_tt_bool (t1, t2) (rpo_l rpo_infos)).\nintro abs.\ngeneralize (find_is_sound (rpo rpo_infos.(bb)) _ (rpo_l_valid rpo_infos) _ _ abs).\nintro h;absurd (rpo rpo_infos.(bb) t1 t1).\nintro;apply rpo_antirefl with (1:=H).\nrewrite <- (equiv_rpo_equiv_1 _ t1_eq_t2) in h. assumption.\nintro h1.\ncase_eq (mem_bool eq_tt_bool (t2, t1) (rpo_l rpo_infos)).\nintro abs.\ngeneralize (find_is_sound (rpo rpo_infos.(bb)) _ (rpo_l_valid rpo_infos) _ _ abs).\nintro h;absurd (rpo rpo_infos.(bb) t2 t2).\nintro;apply rpo_antirefl with (1:=H).\nrewrite (equiv_rpo_equiv_1 _ t1_eq_t2) in h. assumption.\nintro h2.\ncase_eq (mem_bool eq_tt_bool (t1, t2) (equiv_l rpo_infos)).\ntrivial.\nintro h3.\ncase_eq (mem_bool eq_tt_bool (t2, t1) (equiv_l rpo_infos)).\ntrivial.\nintro h4.\n\nassert (H := @equiv_eval_is_sound  rpo_infos _ _ _ St).\n\ndestruct (equiv_eval rpo_infos n t1 t2) as [ [ | ] | ].\ntrivial.\nabsurd (equiv t1 t2); trivial.\ncontradiction.\nQed.\n\nLemma var_case2 : \n  forall n v f l, rpo n (Var v) (Term f l) -> var_in_term_list v l = true .\nProof.\nintros m v f l v_lt_t; \ninversion v_lt_t as [ f2 l2 u s s_in_l v_le_s | | | ]; subst.\ngeneralize s s_in_l v_le_s; clear v_lt_t s s_in_l v_le_s; \npattern l; apply (list_rec3 size); clear l.\nintro n; induction n as [ | n]; intros [ | t l] Sl s s_in_l v_le_s.\ncontradiction.\nsimpl in Sl; absurd (1 <= 0); auto with arith.\nrefine (le_trans _ _ _ _ Sl); apply le_trans with (size t).\napply size_ge_one.\napply le_plus_l.\ncontradiction.\nsimpl in s_in_l; destruct s_in_l as [s_eq_t | s_in_l].\nrewrite (@equiv_rpo_equiv_3 _ _ _ s_eq_t) in v_le_s.\ninversion v_le_s; subst.\ninversion H; subst;\nrewrite var_in_term_list_equation; simpl;\nrewrite eq_var_bool_refl; trivial.\ninversion H as [g k u1 s' s'_in_k v_le_s' | | |]; subst;\nrewrite var_in_term_list_equation; simpl.\nassert (Sk : list_size size k <= n).\napply le_S_n; refine (le_trans _ _ _ _ Sl); simpl; apply le_n_S;\nrewrite (list_size_fold size k); auto with arith.\nrewrite (IHn k Sk s' s'_in_k v_le_s'); simpl; trivial.\nassert (Sl' : list_size size l <= n).\napply le_S_n; refine (le_trans _ _ _ _ Sl); simpl;\napply (plus_le_compat_r 1 (size t) (list_size size l));\napply size_ge_one.\nrewrite var_in_term_list_equation; \nrewrite (IHn l Sl' s s_in_l v_le_s); destruct t as [v' | g k].\ncase (X.eq_bool v v'); trivial.\ncase (var_in_term_list v k); trivial.\nQed.\n\nLemma rpo_eval_is_complete_less_greater :\n  forall rpo_infos n t1 t2, size t1 + size t2 <= n -> \n        rpo rpo_infos.(bb) t1 t2 ->\n        rpo_eval rpo_infos n t1 t2 = Some Less_than /\\\n        rpo_eval rpo_infos n t2 t1 = Some Greater_than.\nProof.\nintros rpo_infos n; induction n as [ | n]; intros t1 t2 St t1_lt_t2. \nabsurd (1 <= 0); auto with arith; \napply le_trans with (size t1 + size t2); trivial;\napply le_trans with (1 + size t2);\n[apply le_plus_l | apply plus_le_compat_r; apply size_ge_one].\nassert (TE := @equiv_eval_terminates rpo_infos _ _ _ St);\nassert (R := rpo_eval_is_sound_weak rpo_infos (S n) t1 t2);\nassert (T := @rpo_eval_terminates rpo_infos (S n) t1 t2 St).\nrewrite plus_comm in St;\nassert (TE' := @equiv_eval_terminates rpo_infos _ _ _ St);\nassert (R' := rpo_eval_is_sound_weak rpo_infos (S n) t2 t1);\nassert (T' := @rpo_eval_terminates rpo_infos (S n) t2 t1 St).\ndo 2 rewrite rpo_eval_equation;\nrewrite rpo_eval_equation in R; \nrewrite rpo_eval_equation in T;\nrewrite rpo_eval_equation in R'; \nrewrite rpo_eval_equation in T'.\nrevert R T R' T'.\ncase_eq (mem_bool eq_tt_bool (t1, t2) (rpo_l rpo_infos)); intro Heq_1;\ncase_eq (mem_bool eq_tt_bool (t2, t1) (rpo_l rpo_infos)); intro Heq_2;\ncase_eq (mem_bool eq_tt_bool (t1, t2) (equiv_l rpo_infos)); intro Heq_3;\ncase_eq (mem_bool eq_tt_bool (t2, t1) (equiv_l rpo_infos)); intro Heq_4; intros R T R' T'; try\n(absurd (rpo rpo_infos.(bb) t1 t1);[\nintro; apply (@rpo_antirefl rpo_infos.(bb) t1); trivial|\napply rpo_trans with t2;assumption]). try intuition. try intuition. try intuition. try intuition.  \ntry (absurd (rpo rpo_infos.(bb) t1 t1);\n[intro; apply (@rpo_antirefl rpo_infos.(bb) t1); trivial |\nrewrite (@equiv_rpo_equiv_1 _ _ _ R') in t1_lt_t2; trivial]).\ntry (absurd (rpo rpo_infos.(bb) t1 t1);\n[intro; apply (@rpo_antirefl rpo_infos.(bb) t1); trivial |\nrewrite (@equiv_rpo_equiv_1 _ _ _ R') in t1_lt_t2; trivial]).\ntry (absurd (rpo rpo_infos.(bb) t1 t1);\n[intro; apply (@rpo_antirefl rpo_infos.(bb) t1); trivial |\nrewrite (@equiv_rpo_equiv_1 _ _ _ R') in t1_lt_t2; trivial]).\n\nclear Heq_1 Heq_2 Heq_3 Heq_4.\ndestruct (equiv_eval rpo_infos (S n) t1 t2) as [ [ | ] | ];\ndestruct (equiv_eval rpo_infos (S n) t2 t1) as [ [ | ] | ];\ntry (absurd (rpo rpo_infos.(bb) t1 t1); [\nintro; apply (@rpo_antirefl rpo_infos.(bb) t1); trivial |\nrewrite <- (equiv_rpo_equiv_1 _ R) in t1_lt_t2; trivial]).  try  intuition. try (absurd (rpo rpo_infos.(bb) t1 t1);\n[intro; apply (@rpo_antirefl rpo_infos.(bb) t1); trivial|\nrewrite (equiv_rpo_equiv_1 _ R') in t1_lt_t2; trivial]).  try (absurd (rpo rpo_infos.(bb) t1 t1);\n[intro; apply (@rpo_antirefl rpo_infos.(bb) t1); trivial|\nrewrite (equiv_rpo_equiv_1 _ R') in t1_lt_t2; trivial]).  Focus 2. try intuition; try (absurd (rpo rpo_infos.(bb) t1 t1);\n[intro; apply (@rpo_antirefl rpo_infos.(bb) t1); trivial|\nrewrite (equiv_rpo_equiv_1 _ R') in t1_lt_t2; trivial]).  Focus 2. try intuition; try (absurd (rpo rpo_infos.(bb) t1 t1);\n[intro; apply (@rpo_antirefl rpo_infos.(bb) t1); trivial|\nrewrite (equiv_rpo_equiv_1 _ R') in t1_lt_t2; trivial]). Focus 2. try  intuition; try (absurd (rpo rpo_infos.(bb) t1 t1);\n[intro; apply (@rpo_antirefl rpo_infos.(bb) t1); trivial|\nrewrite (equiv_rpo_equiv_1 _ R') in t1_lt_t2; trivial]). Focus 2. try  intuition; try (absurd (rpo rpo_infos.(bb) t1 t1);\n[intro; apply (@rpo_antirefl rpo_infos.(bb) t1); trivial|\nrewrite (equiv_rpo_equiv_1 _ R') in t1_lt_t2; trivial]).  try (absurd (rpo rpo_infos.(bb) t1 t1);\n[intro; apply (@rpo_antirefl rpo_infos.(bb) t1); trivial|\nrewrite (equiv_rpo_equiv_1 _ R') in t1_lt_t2; trivial]).\n\n \n\nsimpl. \nclear TE TE'.\ndestruct t1 as [v1 | f1 l1]; destruct t2 as [v2 | f2 l2]. \ninversion t1_lt_t2.\nrewrite (@var_case2 _ _ _ _ t1_lt_t2); split; trivial.\ninversion t1_lt_t2.\nassert (Sl : forall t1 t2, In t1 l1 -> In t2 l2 -> size t1 + size t2 <= n).\nintros t1 t2 t1_in_l1 t2_in_l2; apply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size t1 + size t2)) with (S (size t1) + size t2); trivial;\nrewrite plus_comm; apply plus_le_compat.\napply lt_le_weak; apply size_direct_subterm; trivial.\napply size_direct_subterm; trivial.\nassert (IHl1l2 : forall t1 t2, In t1 l1 -> In t2 l2 -> rpo rpo_infos.(bb) t1 t2 ->\n     rpo_eval rpo_infos n t1 t2 = Some Less_than /\\\n      rpo_eval rpo_infos n t2 t1 = Some Greater_than).\nintros; apply IHn; trivial.\napply Sl; trivial.\nassert (IHl2l1 : forall t1 t2, In t1 l1 -> In t2 l2 -> rpo rpo_infos.(bb) t2 t1 ->\n     rpo_eval rpo_infos n t2 t1 = Some Less_than /\\\n      rpo_eval rpo_infos n t1 t2 = Some Greater_than).\nintros; apply IHn; trivial.\nrewrite plus_comm; apply Sl; trivial.\nassert (IHl1s2 : forall t1, In t1 l1 -> rpo rpo_infos.(bb) t1 (Term f2 l2) ->\n     rpo_eval rpo_infos n t1 (Term f2 l2) = Some Less_than /\\\n      rpo_eval rpo_infos n (Term f2 l2) t1 = Some Greater_than).\nintros; apply IHn; trivial.\napply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size t1 + size (Term f2 l2))) with (S (size t1) + size (Term f2 l2)); trivial;\nrewrite plus_comm; apply plus_le_compat_l.\napply size_direct_subterm; trivial.\nassert (IHs2l1 : forall t1, In t1 l1 -> rpo rpo_infos.(bb) (Term f2 l2) t1 ->\n     rpo_eval rpo_infos n (Term f2 l2) t1 = Some Less_than /\\\n      rpo_eval rpo_infos n t1 (Term f2 l2) = Some Greater_than).\nintros; apply IHn; trivial.\nrewrite plus_comm; apply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size t1 + size (Term f2 l2))) with (S (size t1) + size (Term f2 l2)); trivial;\nrewrite plus_comm; apply plus_le_compat_l.\napply size_direct_subterm; trivial.\nassert (IHs1l2 : forall t2, In t2 l2 -> rpo rpo_infos.(bb) (Term f1 l1) t2 ->\n     rpo_eval rpo_infos n (Term f1 l1) t2 = Some Less_than /\\\n      rpo_eval rpo_infos n t2 (Term f1 l1) = Some Greater_than).\nintros; apply IHn; trivial.\nrewrite plus_comm;\napply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size t2 + size (Term f1 l1))) with (S (size t2) + size (Term f1 l1)); trivial;\napply plus_le_compat_r.\napply size_direct_subterm; trivial.\nassert (IHl2s1 : forall t2, In t2 l2 -> rpo rpo_infos.(bb) t2 (Term f1 l1) ->\n     rpo_eval rpo_infos n t2 (Term f1 l1) = Some Less_than /\\\n      rpo_eval rpo_infos n (Term f1 l1) t2 = Some Greater_than).\nintros; apply IHn; trivial.\napply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size t2 + size (Term f1 l1))) with (S (size t2) + size (Term f1 l1)); trivial;\napply plus_le_compat_r.\napply size_direct_subterm; trivial.\ninversion t1_lt_t2 as\n[ f2' l2' u1 s2 s2_in_l2 u1_le_s2\n| f2' f1' l2' l1' f1_lt_f2 H\n| f g l2' l1' Sf Sg f_eq_g L l1_lt_l2 H\n| f g l2' l1' Sf Sg f_eq_g l1_lt_l2]; subst.\n(* 1/4 Subterm *)\nsplit.\ndestruct (list_exists_option\n           (fun t : term =>\n            match rpo_eval rpo_infos n t (Term f2 l2) with\n            | Some Equivalent => Some true\n            | Some Less_than => Some false\n            | Some Greater_than => Some true\n            | Some Uncomparable => Some false\n            | None => None (A:=bool)\n            end) l1) as [ [ | ] | ].\nsimpl in R; \ndestruct (rpo_closure rpo_infos.(bb) (Term f1 l1) (Term f2 l2) (Term f2 l2)) as [_ [Antisym _]].\napply False_rec; apply Antisym; trivial.\nassert (t1_lt_l2 : list_exists_option\n          (fun t : term =>\n           match rpo_eval rpo_infos n (Term f1 l1) t with\n           | Some Equivalent => Some true\n           | Some Less_than => Some true\n           | Some Greater_than => Some false\n           | Some Uncomparable => Some false\n           | None => None (A:=bool)\n           end) l2 = Some true).\napply list_exists_option_is_complete_true.\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ s2_in_l2) as [s2' [l2' [l2'' [s2_eq_s2' [H _]]]]].\nsimpl in s2_eq_s2'; simpl in H.\nassert (s2'_in_l2 : In s2' l2).\nsubst l2; apply in_or_app; right; left; trivial.\nexists s2'; split; trivial.\nrewrite (equiv_rpo_equiv_3  _ s2_eq_s2') in u1_le_s2.\ninversion u1_le_s2; subst.\nrewrite (@rpo_eval_is_complete_equivalent rpo_infos n (Term f1 l1) s2'); trivial.\nrewrite plus_comm;\napply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size s2' + size (Term f1 l1))) with (S (size s2') + size (Term f1 l1)); trivial;\napply plus_le_compat_r.\napply size_direct_subterm; simpl; trivial.\ndestruct (IHs1l2 s2' s2'_in_l2 H0) as [H1 _]; rewrite H1; trivial.\nrewrite t1_lt_l2; simpl; trivial.\nabsurd (@None comp = None); trivial.\nassert (l2_gt_t1 : list_exists_option\n            (fun t : term =>\n             match rpo_eval rpo_infos n t (Term f1 l1) with\n             | Some Equivalent => Some true\n             | Some Less_than => Some false\n             | Some Greater_than => Some true\n             | Some Uncomparable => Some false\n             | None => None (A:=bool)\n             end) l2 = Some true).\napply list_exists_option_is_complete_true.\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ s2_in_l2) as [s2' [l2' [l2'' [s2_eq_s2' [H _]]]]].\nsimpl in s2_eq_s2'; simpl in H.\nassert (s2'_in_l2 : In s2' l2).\nsubst l2; apply in_or_app; right; left; trivial.\nexists s2'; split; trivial.\ninversion u1_le_s2; subst.\nrewrite (@rpo_eval_is_complete_equivalent rpo_infos n s2' (Term f1 l1)); trivial.\napply le_S_n; refine (le_trans _ _ _ _ St);\nreplace (S (size s2' + size (Term f1 l1))) with (S (size s2') + size (Term f1 l1)); trivial;\napply plus_le_compat_r.\napply size_direct_subterm; trivial.\nsymmetry; transitivity s2; trivial.\nrewrite (equiv_rpo_equiv_1 _ s2_eq_s2') in H0.\ndestruct (IHs1l2 s2' s2'_in_l2 H0) as [_ H2]; rewrite H2; trivial.\nrewrite l2_gt_t1; simpl; trivial.\n(* 1/3 Top_gt *)\nsplit; [clear R' T' | clear R T].\ndestruct (list_exists_option\n           (fun t : term =>\n            match rpo_eval rpo_infos n t (Term f2 l2) with\n            | Some Equivalent => Some true\n            | Some Less_than => Some false\n            | Some Greater_than => Some true\n            | Some Uncomparable => Some false\n            | None => None (A:=bool)\n            end) l1) as [ [ | ] | ].\nsimpl in R.\ndestruct (rpo_closure rpo_infos.(bb) (Term f1 l1) (Term f2 l2) (Term f2 l2)) as [_ [Antisym _]].\napply False_rec; apply Antisym; trivial.\ndestruct (list_exists_option\n               (fun t : term =>\n                match rpo_eval rpo_infos n (Term f1 l1) t with\n                | Some Equivalent => Some true\n                | Some Less_than => Some true\n                | Some Greater_than => Some false\n                | Some Uncomparable => Some false\n                | None => None (A:=bool)\n                end) l2) as [ [ | ] | ].\ntrivial.\ngeneralize (prec_eval_is_sound f1 f2); destruct (prec_eval f1 f2). \nintro. apply False_rec; apply (prec_antisym Prec f2); trivial. assert (H5: False). apply prec_not_prec_eq with symbol Prec f1 f2; trivial. contradict H5.\nintros _; assert (H' : list_forall_option\n    (fun t : term =>\n     match rpo_eval rpo_infos n t (Term f2 l2) with\n     | Some Equivalent => Some false\n     | Some Less_than => Some true\n     | Some Greater_than => Some false\n     | Some Uncomparable => Some false\n     | None => None (A:=bool)\n     end) l1 = Some true).\napply list_forall_option_is_complete_true.\nintros u1 u1_in_l1; destruct (IHl1s2 u1 u1_in_l1) as [H1 _].\napply H; apply in_impl_mem; trivial.\nexact Eq.\nrewrite H1; trivial.\nrewrite H'; trivial.\nintro f2_lt_f1; apply False_rec; apply (prec_antisym Prec f1); apply prec_transitive with f2; trivial.\nintros [_ [not_f1_lt_f2 _]]; absurd (prec Prec f1 f2); trivial.\nabsurd (@None comp = None); trivial.\nabsurd (@None comp = None); trivial.\ndestruct (list_exists_option\n             (fun t : term =>\n             match rpo_eval rpo_infos n t (Term f1 l1) with\n             | Some Equivalent => Some true\n             | Some Less_than => Some false\n             | Some Greater_than => Some true\n             | Some Uncomparable => Some false\n             | None => None (A:=bool)\n             end) l2) as [ [ | ] | ].\ntrivial.\ndestruct (list_exists_option\n         (fun t : term =>\n          match rpo_eval rpo_infos n (Term f2 l2) t with\n          | Some Equivalent => Some true\n          | Some Less_than => Some true\n          | Some Greater_than => Some false\n          | Some Uncomparable => Some false\n          | None => None (A:=bool)\n          end) l1) as [ [ | ] | ].\nsimpl in R'.\ndestruct (rpo_closure rpo_infos.(bb) (Term f1 l1) (Term f2 l2) (Term f2 l2)) as [_ [Antisym _]].\napply False_rec; apply Antisym; trivial.\ngeneralize (prec_eval_is_sound f2 f1); destruct (prec_eval f2 f1).\nintro; apply False_rec; apply (prec_antisym Prec f1); trivial.  assert (H5: False). apply prec_not_prec_eq with symbol Prec f1 f2; trivial. apply prec_eq_sym; trivial. contradict H5.\nintro f2_lt_f1; apply False_rec; apply (prec_antisym Prec f1); apply prec_transitive with f2; trivial.\nintros _; assert (H' : list_forall_option\n    (fun t : term =>\n     match rpo_eval rpo_infos n (Term f2 l2) t with\n     | Some Equivalent => Some false\n     | Some Less_than => Some false\n     | Some Greater_than => Some true\n     | Some Uncomparable => Some false\n     | None => None (A:=bool)\n     end) l1 = Some true).\napply list_forall_option_is_complete_true.\nintros u1 u1_in_l1; destruct (IHl1s2 u1 u1_in_l1) as [_ H2].\napply H; apply in_impl_mem; trivial.\nexact Eq.\nrewrite H2; trivial.\nrewrite H'; trivial.\nintros [_ [_ not_f1_lt_f2]]; absurd (prec Prec f1 f2); trivial.\nabsurd (@None comp = None); trivial.\nabsurd (@None comp = None); trivial.\n(* 1/2 @Top_eq_lex *)\nsplit; [clear R' T' | clear R T].\ncase_eq (beq_nat (length l1) (length l2)\n    || leb (length l1) (bb rpo_infos) && leb (length l2) (bb rpo_infos)).\nclear L; intros L; rewrite L in R, T; clear L.\nset (s1 := Term f1 l1) in *; clearbody s1.\nset (s2 := Term f2 l2) in *; clearbody s2.\ndestruct (list_exists_option\n     (fun t : term =>\n      match rpo_eval rpo_infos n t s2 with\n      | Some Equivalent => Some true\n      | Some Less_than => Some false\n      | Some Greater_than => Some true\n      | Some Uncomparable => Some false\n      | None => None (A:=bool)\n      end) l1) as [ [ | ] | ].\nsimpl in R.\ndestruct (rpo_closure rpo_infos.(bb) s1 s2 s2) as [_ [Antisym _]].\napply False_rec; apply Antisym; trivial.\ndestruct (list_exists_option\n         (fun t : term =>\n          match rpo_eval rpo_infos n s1 t with\n          | Some Equivalent => Some true\n          | Some Less_than => Some true\n          | Some Greater_than => Some false\n          | Some Uncomparable => Some false\n          | None => None (A:=bool)\n          end) l2) as [ [ | ] | ].\ntrivial.\nsimpl; generalize (prec_eval_is_sound f1 f2); destruct (prec_eval f1 f2).\nintros _; rewrite Sf; rewrite Sf in R; rewrite Sf in T; simpl in R; simpl in T.\nrevert t1_lt_t2 H St IHl1l2 IHl2l1 IHl1s2 IHs2l1 IHs1l2 IHl2s1 R T l1_lt_l2 Sl.\nclear; revert s1 s2 l2; induction l1 as [ | t1 l1]; intros s1 s2 [ | t2 l2]; intros.\ninversion l1_lt_l2.\napply refl_equal.\ninversion l1_lt_l2.\ninversion l1_lt_l2; subst.\nsimpl; rewrite (proj1 (IHl1l2 _ _ (or_introl _ (refl_equal _)) (or_introl _ (refl_equal _)) H1)).\nunfold term_gt_list.\nassert (H'' : list_forall_option\n    (fun t : term =>\n     match rpo_eval rpo_infos n s2 t with\n     | Some Equivalent => Some false\n     | Some Less_than => Some false\n     | Some Greater_than => Some true\n     | Some Uncomparable => Some false\n     | None => None\n     end) (t1 :: l1) = Some true).\napply list_forall_option_is_complete_true.\nintros u1 u1_in_t1l1.\nassert (u1_lt_s2 : rpo rpo_infos.(bb) u1 s2).\napply H; apply in_impl_mem; trivial; exact Eq.\nrewrite (proj2 (IHl1s2 _ u1_in_t1l1 u1_lt_s2)); apply refl_equal.\nrewrite H''; apply refl_equal.\nsimpl.\nassert (H' := @rpo_eval_is_complete_equivalent rpo_infos n t1 t2).\ngeneralize (H' (Sl _ _ (or_introl _ (refl_equal _)) \n                        (or_introl _ (refl_equal _))) H3);\nclear H'; intro H'; rewrite H'.\napply IHl1; trivial.\nintros; apply H; right; assumption.\nintros; apply IHl1l2; trivial; right; assumption.\nintros; apply IHl2l1; trivial; right; assumption.\nintros; apply IHl1s2; trivial; right; assumption.\nintros; apply IHs2l1; trivial; right; assumption.\nintros; apply IHs1l2; trivial; right; assumption.\nintros; apply IHl2s1; trivial; right; assumption.\nsimpl in R; rewrite H' in R; assumption.\nsimpl in T; rewrite H' in T; assumption.\nintros; apply Sl; right; assumption.\nintro. assert (H4: False). apply prec_not_prec_eq with symbol Prec f1 f2; trivial. contradict H4. \nintro. assert (H4: False). apply prec_not_prec_eq with symbol Prec f2 f1; trivial. apply prec_eq_sym; trivial. contradict H4. \nintros [f2_diff_f2 _]; absurd (f2 = f2); trivial.\nsimpl in T; absurd (@None comp = None); trivial.\nsimpl in T; absurd (@None comp = None); trivial.\ncontradict f2_diff_f2; trivial. \nsimpl in T; absurd (@None comp = None); trivial.\nsimpl in T; absurd (@None comp = None); trivial.\ndestruct L as [L | [L1 L2]].\nrewrite L; rewrite <- beq_nat_refl; intro; discriminate.\nrewrite (leb_correct _ _ L1); rewrite (leb_correct _ _ L2); rewrite orb_true_r; intro; discriminate.\ncase_eq (beq_nat (length l2) (length l1)\n    || leb (length l2) (bb rpo_infos) && leb (length l1) (bb rpo_infos)).\nclear L; intros L; rewrite L in R', T'; clear L.\nset (s1 := Term f1 l1) in *; clearbody s1.\nset (s2 := Term f2 l2) in *; clearbody s2.\ndestruct (list_exists_option\n     (fun t : term =>\n      match rpo_eval rpo_infos n t s1 with\n      | Some Equivalent => Some true\n      | Some Less_than => Some false\n      | Some Greater_than => Some true\n      | Some Uncomparable => Some false\n      | None => None (A:=bool)\n      end) l2) as [ [ | ] | ].\ntrivial.\ndestruct (list_exists_option\n         (fun t : term =>\n          match rpo_eval rpo_infos n s2 t with\n          | Some Equivalent => Some true\n          | Some Less_than => Some true\n          | Some Greater_than => Some false\n          | Some Uncomparable => Some false\n          | None => None (A:=bool)\n          end) l1) as [ [ | ] | ].\nsimpl in R'.\ndestruct (rpo_closure rpo_infos.(bb) s2 s1 s2) as [_ [Antisym _]].\napply False_rec; apply Antisym; trivial.\nsimpl; generalize (prec_eval_is_sound f2 f1); destruct (prec_eval f2 f1).\nintros _; rewrite Sg; rewrite Sg in R'; rewrite Sg in T'; simpl in R'; simpl in T'.\nrevert t1_lt_t2 H St IHl1l2 IHl2l1 IHl1s2 IHs2l1 IHs1l2 IHl2s1 R' T' l1_lt_l2 Sl.\nclear; revert s1 s2 l1; induction l2 as [ | t2 l2]; intros s1 s2 [ | t1 l1]; intros.\ninversion l1_lt_l2.\ninversion l1_lt_l2.\napply refl_equal.\ninversion l1_lt_l2; subst.\nsimpl; rewrite (proj2 (IHl1l2 _ _ (or_introl _ (refl_equal _)) (or_introl _ (refl_equal _)) H1)).\nunfold term_gt_list.\nassert (Hnew : list_forall_option\n    (fun t : term =>\n     match rpo_eval rpo_infos n s2 t with\n     | Some Equivalent => Some false\n     | Some Less_than => Some false\n     | Some Greater_than => Some true\n     | Some Uncomparable => Some false\n     | None => None\n     end) (t1 :: l1) = Some true).\napply list_forall_option_is_complete_true.\nintros u1 u1_in_t1l1.\nassert (u1_lt_s2 : rpo rpo_infos.(bb) u1 s2).\napply H; apply in_impl_mem; trivial; exact Eq.\nrewrite (proj2 (IHl1s2 _ u1_in_t1l1 u1_lt_s2)); apply refl_equal.\nrewrite Hnew; apply refl_equal.\nsimpl.\nassert (H' := @rpo_eval_is_complete_equivalent rpo_infos n t2 t1).\nrewrite plus_comm in H'; generalize (H' (Sl _ _ (or_introl _ (refl_equal _)) \n                        (or_introl _ (refl_equal _))) (equiv_sym _ _ equiv_equiv _ _ H3));\nclear H'; intro H'; rewrite H'.\napply IHl2; trivial.\nintros; apply H; right; assumption.\nintros; apply IHl1l2; trivial; right; assumption.\nintros; apply IHl2l1; trivial; right; assumption.\nintros; apply IHl1s2; trivial; right; assumption.\nintros; apply IHs2l1; trivial; right; assumption.\nintros; apply IHs1l2; trivial; right; assumption.\nintros; apply IHl2s1; trivial; right; assumption.\nsimpl in R'; rewrite H' in R'; assumption.\nsimpl in T'; rewrite H' in T'; assumption.\nintros; apply Sl; right; assumption.\nintro. assert (H4: False). apply prec_not_prec_eq with symbol Prec f2 f1; trivial. apply prec_eq_sym; trivial. contradict H4. \nintro. assert (H4: False). apply prec_not_prec_eq with symbol Prec f1 f2; trivial.  contradict H4. \nintros [f2_diff_f2 _]; absurd (f2 = f2); trivial. contradict f2_diff_f2. apply prec_eq_sym; trivial.\nsimpl in T'; absurd (@None comp = None); trivial.\nsimpl in T'; absurd (@None comp = None); trivial.\ndestruct L as [L | [L1 L2]].\nrewrite L; rewrite <- beq_nat_refl; intro; discriminate.\nrewrite (leb_correct _ _ L1); rewrite (leb_correct _ _ L2); rewrite orb_true_r; intro; discriminate.\n(* 1/1 Top_eq_mul *)\nset (s1 := Term f1 l1) in *.\nset (s2 := Term f2 l2) in *.\nsplit; [clear R' T' | clear R T].\n(* 1/2 *)\ndestruct (list_exists_option\n     (fun t : term =>\n      match rpo_eval  rpo_infos n t s2 with\n      | Some Equivalent => Some true\n      | Some Less_than => Some false\n      | Some Greater_than => Some true\n      | Some Uncomparable => Some false\n      | None => None (A:=bool)\n      end) l1) as [ [ | ] | ].\n(* 1/4 *)\nsimpl in R;  destruct (rpo_closure rpo_infos.(bb) s1 s2 s2) as [_ [Antisym _]].\napply False_rec; apply Antisym; trivial.\n(* 1/3 *)\ndestruct (list_exists_option\n         (fun t : term =>\n          match rpo_eval rpo_infos n s1 t with\n          | Some Equivalent => Some true\n          | Some Less_than => Some true\n          | Some Greater_than => Some false\n          | Some Uncomparable => Some false\n          | None => None (A:=bool)\n          end) l2) as [ [ | ] | ].\n(* 1/5 *)\ntrivial.\n(* 1/4 *)\nsimpl; generalize (prec_eval_is_sound f1 f2); destruct (prec_eval f1 f2).\n(* 1/7 *)\nintros _; rewrite Sf; rewrite Sf in R; rewrite Sf in T; simpl in R; simpl in T.\nassert (H' := remove_equiv_eval_list_is_sound (equiv_eval rpo_infos n) l1 l2).\ncase_eq (remove_equiv_eval_list (equiv_eval rpo_infos n) l1 l2).\nintros [l1' l2'] H; rewrite H in R, T, H'.\nassert (H'' : rpo_mul (bb rpo_infos) l1' l2').\ndestruct H' as [ll [Ell [P1 [P2 _]]]].\nassert (Ell' : forall t1 t2, In (t1,t2) ll -> equiv t1 t2).\nintros t1 t2 t1t2_in_ll.\ngeneralize (equiv_eval_is_sound_weak rpo_infos n t1 t2).\nrewrite (Ell _ _ t1t2_in_ll); intro t1_eq_t2; apply t1_eq_t2; apply refl_equal.\nrevert Ell' l1_lt_l2 P1 P2; clear; revert l1 l2 l1' l2'; induction ll as [ | [t1 t2] ll];\nintros l1 l2 l1' l2' Ell l1_lt_l2 P1 P2.\nrewrite <- app_nil_end in P1.\nrewrite <- app_nil_end in P2.\ninversion l1_lt_l2; subst.\napply (@List_mul _ a lg ls lc); trivial.\ntransitivity l1; [symmetry; apply permut_impl with eq | idtac]; trivial.\nintros a' b a_eq_b; subst a'; apply Eq.\ntransitivity l2; [symmetry; apply permut_impl with eq | idtac]; trivial.\nintros a' b a_eq_b; subst a'; apply Eq.\napply (@rpo_mul_remove_equiv_aux rpo_infos.(bb) l1' l2' t1 t2).\nintros t _; apply (@rpo_antirefl rpo_infos.(bb) t); trivial.\napply Ell; left; apply refl_equal.\napply IHll with l1 l2; trivial.\nintros; apply Ell; right; assumption.\nrefine (list_permut.permut_trans _ P1 _).\nintros; subst; apply refl_equal.\napply list_permut.permut_sym.\nintros; subst; apply refl_equal.\nsimpl; apply Pcons; [trivial | apply list_permut.permut_refl; intros; trivial].\nrefine (list_permut.permut_trans _ P2 _).\nintros; subst; apply refl_equal.\napply list_permut.permut_sym.\nintros; subst; apply refl_equal.\nsimpl; apply Pcons; [trivial | apply list_permut.permut_refl; intros; trivial].\ndestruct l1' as [ | t1' l1']; destruct l2' as [ | t2' l2'].\n(* 1/11 *)\nabsurd (rpo rpo_infos.(bb) s1 s1).\nintro; apply (@rpo_antirefl rpo_infos.(bb) s1); trivial.\nrewrite <- (equiv_rpo_equiv_1 _ R) in t1_lt_t2; trivial.\n(* 1/10 *)\ntrivial.\n(* 1/9 *)\nabsurd (rpo rpo_infos.(bb) s1 s1).\nintro; apply (@rpo_antirefl rpo_infos.(bb) s1); trivial.\napply rpo_trans with s2; trivial.\n(* 1/8 *)\nunfold mult_eval, list_gt_list; unfold mult_eval, list_gt_list in R,T.\ndestruct (list_forall_option\n          (fun t2 : term =>\n           list_exists_option\n             (fun t1 : term =>\n              match rpo_eval rpo_infos n t1 t2 with\n              | Some Equivalent => Some false\n              | Some Less_than => Some false\n              | Some Greater_than => Some true\n              | Some Uncomparable => Some false\n              | None => None (A:=bool)\n              end) (t1' :: l1')) (t2' :: l2')) as [ [ | ] | ].\n(* 1/10 *)\nabsurd (rpo rpo_infos.(bb) s1 s1).\nintro; apply (@rpo_antirefl rpo_infos.(bb) s1); trivial.\napply rpo_trans with s2; trivial.\n(* 1/9 *)\nassert (K : list_forall_option\n    (fun t1 : term =>\n     list_exists_option\n       (fun t2 : term =>\n        match rpo_eval rpo_infos n t2 t1 with\n        | Some Equivalent => Some false\n        | Some Less_than => Some false\n        | Some Greater_than => Some true\n        | Some Uncomparable => Some false\n        | None => None (A:=bool)\n        end) (t2' :: l2')) (t1' :: l1') = Some true).\napply list_forall_option_is_complete_true.\nintros u1 u1_in_l1'; apply list_exists_option_is_complete_true.\ninversion H''; subst.\nassert (u1_in_l1 : In u1 l1).\ndestruct H' as [ll [ _ [P1 _]]].\nrewrite (in_permut_in P1); apply in_or_app; left; trivial.\nassert (u1_mem_ls_lc : mem equiv u1 (ls ++ lc)).\nrewrite <- (mem_permut0_mem equiv_equiv u1 H0); apply in_impl_mem; trivial.\nexact Eq.\nrewrite <- mem_or_app in u1_mem_ls_lc.\ndestruct u1_mem_ls_lc as [u1_mem_ls | u1_mem_lc].\ndestruct (H2 _ u1_mem_ls) as [a' [a'_in_lg u1_lt_a']].\nassert (a'_in_tl2' : mem equiv a' (t2' :: l2')).\nrewrite (mem_permut0_mem equiv_equiv a' H1).\nrewrite app_comm_cons; rewrite <- mem_or_app; left; assumption.\nrewrite mem_in_eq in a'_in_tl2'; destruct a'_in_tl2' as [a'' [a''_eq_a' a''_in_tl2']].\nexists a''; split.\nassumption.\nassert (u1_lt_a'' : rpo (bb rpo_infos) u1 a'').\nrewrite <- (equiv_rpo_equiv_1 _ a''_eq_a'); trivial.\nassert (a''_in_l2 : In a'' l2).\ndestruct H' as [ll [ _ [_ [P2 _]]]].\nrewrite (in_permut_in P2); apply in_or_app; left; trivial.\n(* bug, rewrite passe avec _ a la place de u1_in_l1 a''_in_l2 *)\nrewrite (proj2 (IHl1l2 u1 a'' u1_in_l1 a''_in_l2 u1_lt_a'')); apply refl_equal.\nassert (u1_mem_tl2' : exists u2, equiv u1 u2 /\\ In u2 (t2' :: l2')).\nrewrite <- (mem_in_eq equiv).\nrewrite (mem_permut0_mem equiv_equiv u1 H1).\nrewrite app_comm_cons; rewrite <- mem_or_app; right; assumption.\ndestruct u1_mem_tl2' as [u2 [u1_eq_u2 u2_in_tl2']].\ndestruct H' as [ll [ _ [_ [P2 H']]]].\nassert (K := H' _ _ u1_in_l1' u2_in_tl2').\nassert (Su : size u1 + size u2 <= n).\napply Sl; [idtac | rewrite (in_permut_in P2); apply in_or_app; left]; assumption.\napply False_rec; generalize (@equiv_eval_is_sound rpo_infos n u1 u2 Su); rewrite K; intro E; apply E; assumption.\nrewrite K; apply refl_equal.\n(* 1/8 *)\napply False_rec; apply T; apply refl_equal.\n(* 1/7 *)\nintros H; rewrite H in T; apply False_rec; apply T; apply refl_equal.\n(* 1/6 *)\nintro; apply False_rec; apply (prec_antisym Prec f2); trivial. assert (H4: False). apply prec_not_prec_eq with symbol Prec f1 f2; trivial.  contradict H4. \n(* 1/5 *)\nintro; apply False_rec; apply (prec_antisym Prec f1); trivial. assert (H4: False). apply prec_not_prec_eq with symbol Prec f2 f1; trivial. apply prec_eq_sym; trivial. contradict H4. \n(* 1/4 *)\nintros [f2_diff_f2 _]; absurd (f2 = f2); trivial.\n(* 1/3 *)\ncontradict f2_diff_f2; trivial.\napply False_rec; apply T; apply refl_equal.\n(* 1/2 *)\napply False_rec; apply T; apply refl_equal.\n(* 1/1 *)\ndestruct (list_exists_option\n     (fun t : term =>\n      match rpo_eval  rpo_infos n t s1 with\n      | Some Equivalent => Some true\n      | Some Less_than => Some false\n      | Some Greater_than => Some true\n      | Some Uncomparable => Some false\n      | None => None (A:=bool)\n      end) l2) as [ [ | ] | ].\n(* 1/3 *)\ntrivial.\n(* 1/2 *)\ndestruct (list_exists_option\n         (fun t : term =>\n          match rpo_eval rpo_infos n s2 t with\n          | Some Equivalent => Some true\n          | Some Less_than => Some true\n          | Some Greater_than => Some false\n          | Some Uncomparable => Some false\n          | None => None (A:=bool)\n          end) l1) as [ [ | ] | ].\n(* 1/4 *)\nsimpl in R'; destruct (rpo_closure rpo_infos.(bb) s1 s2 s2) as [_ [Antisym _]].\napply False_rec; apply Antisym; trivial.\n(* 1/3 *)\nsimpl; generalize (prec_eval_is_sound f2 f1); destruct (prec_eval f2 f1).\n(* 1/6 *)\nintros _; rewrite Sg; rewrite Sg in R'; rewrite Sg in T'; simpl in R'; simpl in T'.\nassert (H' := remove_equiv_eval_list_is_sound (equiv_eval rpo_infos n) l2 l1).\ncase_eq (remove_equiv_eval_list (equiv_eval rpo_infos n) l2 l1).\nintros [l2' l1'] H; rewrite H in R', T', H'.\nassert (H'' : rpo_mul (bb rpo_infos) l1' l2').\ndestruct H' as [ll [Ell [P2 [P1 _]]]].\nassert (Ell' : forall t1 t2, In (t1,t2) ll -> equiv t1 t2).\nintros t1 t2 t1t2_in_ll.\ngeneralize (equiv_eval_is_sound_weak rpo_infos n t1 t2).\nrewrite (Ell _ _ t1t2_in_ll); intro t1_eq_t2; apply t1_eq_t2; apply refl_equal.\nrevert Ell' l1_lt_l2 P1 P2; clear; revert l1 l2 l1' l2'; induction ll as [ | [t2 t1] ll];\nintros l1 l2 l1' l2' Ell l1_lt_l2 P1 P2.\nrewrite <- app_nil_end in P1.\nrewrite <- app_nil_end in P2.\ninversion l1_lt_l2; subst.\napply (@List_mul _ a lg ls lc); trivial.\ntransitivity l1; [symmetry; apply permut_impl with eq | idtac]; trivial.\nintros a' b a_eq_b; subst a'; apply Eq.\ntransitivity l2; [symmetry; apply permut_impl with eq | idtac]; trivial.\nintros a' b a_eq_b; subst a'; apply Eq.\napply (@rpo_mul_remove_equiv_aux rpo_infos.(bb) l1' l2' t1 t2).\nintros t _; apply (@rpo_antirefl rpo_infos.(bb) t); trivial.\napply (equiv_sym _ _ equiv_equiv); apply Ell; left; apply refl_equal.\napply IHll with l1 l2; trivial.\nintros; apply Ell; right; assumption.\nrefine (list_permut.permut_trans _ P1 _).\nintros; subst; apply refl_equal.\napply list_permut.permut_sym.\nintros; subst; apply refl_equal.\nsimpl; apply Pcons; [trivial | apply list_permut.permut_refl; intros; trivial].\nrefine (list_permut.permut_trans _ P2 _).\nintros; subst; apply refl_equal.\napply list_permut.permut_sym.\nintros; subst; apply refl_equal.\nsimpl; apply Pcons; [trivial | apply list_permut.permut_refl; intros; trivial].\ndestruct l1' as [ | t1' l1']; destruct l2' as [ | t2' l2'].\n(* 1/10 *)\nabsurd (rpo rpo_infos.(bb) s2 s2).\nintro; apply (@rpo_antirefl rpo_infos.(bb) s2); trivial.\nrewrite <- (equiv_rpo_equiv_2 _ R') in t1_lt_t2; trivial.\n(* 1/9 *)\ntrivial.\n(* 1/8 *)\nabsurd (rpo rpo_infos.(bb) s2 s2).\nintro; apply (@rpo_antirefl rpo_infos.(bb) s2); trivial.\napply rpo_trans with s1; trivial.\n(* 1/7 *)\nunfold mult_eval, list_gt_list; unfold mult_eval, list_gt_list in R', T'.\nassert (K : list_forall_option\n          (fun t2 : term =>\n           list_exists_option\n             (fun t1 : term =>\n              match rpo_eval rpo_infos n t1 t2 with\n              | Some Equivalent => Some false\n              | Some Less_than => Some false\n              | Some Greater_than => Some true\n              | Some Uncomparable => Some false\n              | None => None (A:=bool)\n              end) (t2' :: l2')) (t1' :: l1') = Some true).\napply list_forall_option_is_complete_true.\nintros u1 u1_in_l1'; apply list_exists_option_is_complete_true.\ninversion H''; subst.\nassert (u1_in_l1 : In u1 l1).\ndestruct H' as [ll [ _ [_ [P1 _]]]].\nrewrite (in_permut_in P1); apply in_or_app; left; trivial.\nassert (u1_mem_ls_lc : mem equiv u1 (ls ++ lc)).\nrewrite <- (mem_permut0_mem equiv_equiv u1 H0); apply in_impl_mem; trivial.\nexact Eq.\nrewrite <- mem_or_app in u1_mem_ls_lc.\ndestruct u1_mem_ls_lc as [u1_mem_ls | u1_mem_lc].\ndestruct (H2 _ u1_mem_ls) as [a' [a'_in_lg u1_lt_a']].\nassert (a'_in_tl2' : mem equiv a' (t2' :: l2')).\nrewrite (mem_permut0_mem equiv_equiv a' H1).\nrewrite app_comm_cons; rewrite <- mem_or_app; left; assumption.\nrewrite mem_in_eq in a'_in_tl2'; destruct a'_in_tl2' as [a'' [a''_eq_a' a''_in_tl2']].\nexists a''; split.\nassumption.\nassert (u1_lt_a'' : rpo (bb rpo_infos) u1 a'').\nrewrite <- (equiv_rpo_equiv_1 _ a''_eq_a'); trivial.\nassert (a''_in_l2 : In a'' l2).\ndestruct H' as [ll [ _ [P2 _]]].\nrewrite (in_permut_in P2); apply in_or_app; left; trivial.\n(* bug, rewrite passe avec _ a la place de u1_in_l1 a''_in_l2 *)\nrewrite (proj2 (IHl1l2 u1 a'' u1_in_l1 a''_in_l2 u1_lt_a'')); apply refl_equal.\nassert (u1_mem_tl2' : exists u2, equiv u1 u2 /\\ In u2 (t2' :: l2')).\nrewrite <- (mem_in_eq equiv).\nrewrite (mem_permut0_mem equiv_equiv u1 H1).\nrewrite app_comm_cons; rewrite <- mem_or_app; right; assumption.\ndestruct u1_mem_tl2' as [u2 [u1_eq_u2 u2_in_tl2']].\ndestruct H' as [ll [ _ [P2 [_ H']]]].\nassert (K := H' _ _ u2_in_tl2' u1_in_l1').\nassert (Su : size u2 + size u1 <= n).\nrewrite plus_comm; apply Sl; [idtac | rewrite (in_permut_in P2); apply in_or_app; left]; assumption.\napply False_rec; generalize (@equiv_eval_is_sound rpo_infos n u2 u1 Su); rewrite K; intro E; apply E.\napply (equiv_sym _ _ equiv_equiv); assumption.\nrewrite K; apply refl_equal.\n(* 1/6 *)\nintros H; rewrite H in T'; apply False_rec; apply T'; apply refl_equal.\n(* 1/5 *)\nintro. assert (H4: False). apply prec_not_prec_eq with symbol Prec f2 f1; trivial.  apply prec_eq_sym; trivial. contradict H4. \n(* 1/4 *)\nintro; apply False_rec; apply (prec_antisym Prec f2); trivial.\nassert (H4: False). apply prec_not_prec_eq with symbol Prec f1 f2; trivial. contradict H4. \n(* 1/3 *)\nintros [f2_diff_f2 _]; absurd (f2 = f2); trivial.\ncontradict f2_diff_f2. apply prec_eq_sym; trivial.\n(* 1/2 *)\napply False_rec; apply T'; apply refl_equal.\n(* 1/1 *)\napply False_rec; apply T'; apply refl_equal.\nQed.\n\nLemma rpo_eval_is_complete :\n  forall rpo_infos n t1 t2, size t1 + size t2 <= n -> \n        match rpo_eval rpo_infos n t1 t2 with\n        | Some Equivalent => equiv t1 t2\n        | Some Less_than => rpo rpo_infos.(bb) t1 t2\n        | Some Greater_than => rpo rpo_infos.(bb) t2 t1\n        | Some Uncomparable => ~equiv t1 t2 /\\ ~ rpo rpo_infos.(bb) t1 t2 /\\ ~rpo rpo_infos.(bb) t2 t1\n        | None => False\n        end.\nintros rpo_infos n t1 t2 St;\ngeneralize (rpo_eval_is_sound_weak rpo_infos n t1 t2)\n(@rpo_eval_is_complete_equivalent rpo_infos n t1 t2 St)\n(@rpo_eval_is_complete_less_greater rpo_infos n t1 t2 St)\n(@rpo_eval_terminates rpo_infos n t1 t2 St);\nrewrite plus_comm in St;\ngeneralize (@rpo_eval_is_complete_less_greater rpo_infos n t2 t1 St).\ndestruct (rpo_eval rpo_infos n t1 t2) as [ [ | | | ] | ]; trivial.\nintros not_t2_lt_t1 _ t1_diff_t2 not_t1_lt_t2 T; repeat split; intro H.\ngeneralize (t1_diff_t2 H); discriminate.\ndestruct (not_t1_lt_t2 H); discriminate.\ndestruct (not_t2_lt_t1 H); discriminate.\nintros _ _ _ _ H; apply H; trivial.\nQed.\n\nDefinition empty_rpo_infos (n : nat) : rpo_inf.\nProof. \n constructor 1 with n (@nil (term*term)) (@nil (term*term)) (@nil (term*term));simpl;tauto.\nDefined.\n\nDefinition add_equiv (rpo_infos:rpo_inf) t1 t2 (H:equiv t1 t2) : rpo_inf.\nProof.  \n \n  case rpo_infos.\n  clear rpo_infos. \n  intros bb0 rpo_l0 rpo_eq_l0 equiv_l0 rpo_l_valid0 rpo_eq_valid0 equiv_l_valid0.\n  constructor 1 with bb0 rpo_l0 rpo_eq_l0 ((t1,t2)::equiv_l0).\n  exact rpo_l_valid0.\n  exact rpo_eq_valid0.\n  simpl.\n  intros t t' H0.\n  case H0;  intros H1.\n  injection H1.\n  intros H2 H3.\n  rewrite <- H2;rewrite <- H3;exact H.\n  exact (equiv_l_valid0 _ _ H1).\nDefined.\n\n\n(* Sorin's contribution *)\n\nDefinition rpo_mult_eval rpo_infos n l1 l2 :=\n                                match remove_equiv_eval_list (equiv_eval rpo_infos n) l1 l2 with\n                                | None =>  None\n                                | Some (nil, nil) => Some Equivalent\n                                | Some (nil, _ :: _) => Some Less_than\n                                | Some (_ :: _,nil) => Some Greater_than\n                                | Some (l, l') => mult_eval (rpo_eval rpo_infos n) l l'\n                                end.\n \nTheorem rpo_mul_subst : forall A B: (list term), forall bb:nat,  rpo_mul bb A B -> \n  forall sigma,  rpo_mul bb (map (apply_subst sigma) A) (map (apply_subst sigma) B).\nProof. (* inspired from the proof of rpo_subst *)\nintros l' l bb Rmul sigma.\ninversion Rmul as [ a lg ls lc l0 k0 Pk Pl ls_lt_alg]; subst.\napply (@List_mul bb (apply_subst sigma a) (map (apply_subst sigma) lg)\n(map (apply_subst sigma) ls) (map (apply_subst sigma) lc)).\nrewrite <- map_app; apply permut_map with equiv; trivial.\nintros b b' _ _ b_eq_b'; apply equiv_subst; trivial.\nrewrite <- map_app.\nrefine (@permut_map term term term term equiv \n                    equiv (apply_subst sigma) _ _ (a :: lg ++ lc) _ _); trivial.\nintros b b' b_in_l _ b_eq_b'; apply equiv_subst; trivial.\nintros b b_mem_ls_sigma; \ndestruct (mem_split_set _ _ equiv_bool_ok _ _ b_mem_ls_sigma) as [b' [ls1 [ls2 [b_eq_b' [H _]]]]];\nsimpl in b_eq_b'; simpl in H.\nassert (b'_in_ls_sigma : In b' (map (apply_subst sigma) ls)).\nrewrite H; apply in_or_app; right; left; trivial.\nrewrite in_map_iff in b'_in_ls_sigma.\ndestruct b'_in_ls_sigma as [b'' [b''_sigma_eq_b' b''_in_ls]].\ndestruct (ls_lt_alg b'') as [a' [a'_mem_alg b''_lt_a']].\napply in_impl_mem; trivial.\nexact Eq.\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ a'_mem_alg) as [a'' [alg' [alg'' [a'_eq_a'' [H' _]]]]];\nsimpl in a'_eq_a''; simpl in H'.\nexists (apply_subst sigma a''); split; trivial.\napply in_impl_mem.\nexact Eq.\nrewrite (in_map_iff (apply_subst sigma) (a :: lg)).\nexists a''; split; trivial.\nrewrite H'; apply in_or_app; right; left; trivial.\nrewrite (equiv_rpo_equiv_2 _ b_eq_b').\nassert (IH:= rpo_subst).\nsubst b'; apply (IH bb b'' a'').\nrewrite <- (equiv_rpo_equiv_1 _ a'_eq_a''); trivial.\nQed.\n\nLemma rpo_mul_dec: forall bb k l, {rpo_mul bb k l}+{~ rpo_mul bb k l}.\nProof. (* inspired from the proof of rpo_dec *)\nintros.\nassert (H' := remove_equiv_list_is_sound k l).\ndestruct (remove_equiv_list k l) as [k' l'];\ndestruct H' as [lc [Pk [Pl D]]].\nassert (Rem : rpo_mul bb0 k l -> rpo_mul bb0 k' l').\ngeneralize l k l' k' Pk Pl; clear l k l' k' Pk Pl D.\ninduction lc as [ | c lc]; intros l k l' k' Pk Pl k_lt_l.\ninversion k_lt_l as [a lg ls lc' k'' l'' Rk Rl ls_lt_alg]; subst.\napply (@List_mul bb0 a lg ls lc'); trivial.\ntransitivity k; trivial; symmetry; rewrite <- app_nil_end in Pk; trivial.\ntransitivity l; trivial; symmetry; rewrite <- app_nil_end in Pl; trivial.\nassert (H := IHlc l k (l' ++ c :: nil) (k' ++ c :: nil)).\ndo 2 rewrite <- ass_app in H; simpl in H.\ngeneralize (H Pk Pl k_lt_l); clear H; intro H.\napply (@rpo_mul_remove_equiv_aux bb0 k' l' c c).\nintros t _; apply rpo_antirefl.\nreflexivity.\ninversion H as [a lg ls lc' k'' l'' Rk Rl ls_lt_alg]; subst.\napply (@List_mul bb0 a lg ls lc'); trivial.\nrewrite <- Rk; rewrite <- permut0_cons_inside;[|apply equiv_equiv|reflexivity].\nrewrite <- app_nil_end; reflexivity || auto.\nrewrite <- Rl; rewrite <- permut0_cons_inside;[|apply equiv_equiv|reflexivity].\nrewrite <- app_nil_end; reflexivity || auto.\n\nlet P := constr:(forall u, mem equiv u k' -> exists v,  mem equiv v l' /\\ rpo bb0 u v) in\nassert (H' : {P} + {~ P}).\nassert (IH' : forall u v, mem equiv u k' -> mem equiv v l' -> {rpo bb0 u v}+{~rpo bb0 u v}).\n\nintros u v u_mem_k' v_mem_l'. apply rpo_dec.\ngeneralize l' IH'; clear l k  l' lc Pk Pl D IH' Rem.\ninduction k' as [ | u' k']; intros l' IH'.\nleft; intros; contradiction.\nlet P:=constr:(forall v, mem equiv v l' -> ~rpo bb0 u' v) in\nassert (H : {v | mem equiv v l' /\\ rpo bb0 u' v}+{P}).\nassert (IH'' : forall v, mem equiv v l' -> {rpo bb0 u' v}+{~rpo bb0 u' v}).\nintros v v_mem_l'; apply (IH' u' v); trivial.\nleft; reflexivity.\nclear IHk' IH'; induction l' as [ | v' l'].\nright; intros; contradiction.\n\n\ndestruct IHl' as [Ok | Ko].\nintros; apply IH''; right; trivial.\ndestruct Ok as [v [v_mem_l' u'_lt_v]]; left; exists v; split; trivial.\nright; trivial.\ndestruct (IH'' v') as [Ok' | Ko'].\nleft; reflexivity.\nleft; exists v'; split; trivial.\nleft; reflexivity.\nright; intros v [v'_eq_v | v_mem_l'].\nintros u'_lt_v; apply Ko'.\nrewrite <- (equiv_rpo_equiv_1 _ v'_eq_v); trivial.\napply Ko; trivial.\ndestruct H as [[v [v_mem_l' u'_lt_v]] | Ko].\ndestruct (IHk' l') as [Ok' | Ko'].\nintros u v' u_mem_k' v'_mem_l'; apply IH'; trivial; right; trivial.\n\nleft; intros u [u'_eq_u | u_mem_k'].\nexists v; split; trivial.\nrewrite (equiv_rpo_equiv_2 _ u'_eq_u); trivial.\napply Ok'; trivial.\nright; intro H; apply Ko'.\nintros u u_mem_k'; apply H; right; trivial.\nright; intro H.\ndestruct (H u') as [v [v_mem_l' u'_lt_v]].\nleft; reflexivity.\napply (Ko v); trivial.\ndestruct l' as [ | v' l'].\nright; intro fk_lt_fl.\nassert (rpo_mul bb0 k' nil).\napply Rem. trivial.\ninversion H.\ninversion H1.\n\ndestruct H' as [Ok | Ko].\nleft; apply (@List_mul bb0 v' l' k' lc); trivial.\nright. intro.\ncontradict Ko.\nassert (rpo_mul bb0 k' (v' :: l')).\napply Rem. trivial.\n\n \ninversion H0 as [a lg ls lc' k'' l'' Rk Rl ls_lt_alg]; subst.\nintro u. rewrite Rk. rewrite <- mem_or_app.\nintros [u_mem_ls | u_mem_lc'].\ndestruct (ls_lt_alg _ u_mem_ls) as [a' [a'_mem_alg u_lt_a']];\nexists a'; split; trivial.\nrewrite Rl; rewrite app_comm_cons;\nrewrite <- mem_or_app; left; trivial.\nassert False.\napply (D u u).\nrewrite Rk; rewrite <- mem_or_app; right; trivial.\nrewrite Rl; rewrite app_comm_cons;\nrewrite <- mem_or_app; right; trivial.\nreflexivity.\ncontradiction.\nQed.\n\nTheorem rpo_mul_rest_dec: forall bb k l,  well_founded (prec Prec) -> {rpo_mul_rest bb k l}+{~ rpo_mul_rest bb k l}.\nProof.\nintros.\nassert (H2:= @rpo_mul_dec bb0 k l).\nassert (H3:=wf_rpo). assert (well_founded (rpo bb0)).\napply H3. trivial.\ndestruct H2.\nleft. apply Rpo_mul_rest.\nintros. apply H0. intros. apply H0. trivial.\nright. intro.\ncontradict n.\ninversion H1. trivial.\nQed.\n\nLemma permut0_eq_equiv: forall A B, permut0 eq A B -> permut0 equiv A B.\nProof.\nintros A0 B H.\nassert (H':=permut_impl).\nassert (H1:= H' term term eq equiv A0 B); clear H'. \napply H1.\nintros a b H'.\nrewrite H'.\napply (Relation_Definitions.equiv_refl _ _ equiv_equiv).\nassumption.\nQed.\n  \n\nLemma equiv_eval_lists: forall A ll n rpo_infos, \n  (forall t1 t2, In (t1, t2) ll -> equiv_eval rpo_infos n t1 t2 = Some true) -> \n      permut0 equiv (A ++ map (fun st : term * term => fst st) ll) (A ++ map (fun st : term * term => snd st) ll).\nProof.\nintro H.\ninduction ll. \nintros n rpo_infos H1. \nsimpl. apply permut_refl. intros a H'.\napply (Relation_Definitions.equiv_refl _ _ equiv_equiv).\n\nintros.\nassert (H':= IHll n rpo_infos); clear IHll.\nassert (H1:  permut0 equiv (H ++ map (fun st : term * term => fst st) ll)\n         (H ++ map (fun st : term * term => snd st) ll)).\napply H'. intros t1 t2 H3.\nassert (H0':= H0 t1 t2).\napply H0'. simpl. right; assumption.\nassert (H0':= H0 (fst a) (snd a)); clear H0.\nassert (equiv_eval rpo_infos n (fst a) (snd a) = Some true).\napply H0'. simpl; left. destruct a. simpl. trivial.\nsimpl.\n\napply permut_strong.\nassert (H1':= equiv_eval_is_sound_weak).\nassert (H2:= H1' rpo_infos n (fst a) (snd a)).\napply H2; trivial.\ntrivial.\nQed.\n\nRequire Import Lia.\n\n\nLemma equiv_rpo_eval: forall  n rpo_infos t s u, size t + size u <= n -> size t + size s <= n -> equiv u s -> rpo_eval rpo_infos n t u = rpo_eval rpo_infos n t s.\nProof.\nintros n rpo_infos t s u tu ts H.\n\nassert (H1:= equiv_rpo_equiv_1).\nassert (H2:= rpo_eval_is_complete_less_greater).\nassert (H3:= rpo_eval_is_complete).\nassert (H2':= H2 rpo_infos n t u).\nassert (H2'':= H2 rpo_infos n t s); clear H2. \nassert (H3':= H3 rpo_infos n t u).\nassert (H3'':= H3 rpo_infos n t s); clear H3.\nassert (H31: match rpo_eval rpo_infos n t s with\n         | Some Equivalent => equiv t s\n         | Some Less_than => rpo (bb rpo_infos) t s\n         | Some Greater_than => rpo (bb rpo_infos) s t\n         | Some Uncomparable =>\n             ~ equiv t s /\\\n             ~ rpo (bb rpo_infos) t s /\\ ~ rpo (bb rpo_infos) s t\n         | None => False\n         end). \napply H3''; trivial.\nassert (H32: match rpo_eval rpo_infos n t u with\n        | Some Equivalent => equiv t u\n        | Some Less_than => rpo (bb rpo_infos) t u\n        | Some Greater_than => rpo (bb rpo_infos) u t\n        | Some Uncomparable =>\n            ~ equiv t u /\\\n            ~ rpo (bb rpo_infos) t u /\\ ~ rpo (bb rpo_infos) u t\n        | None => False\n        end).\napply H3'; trivial. \nclear H3'' H3'.\ndestruct (rpo_eval rpo_infos n t u) as [[ | | | ] | ].\ndestruct (rpo_eval rpo_infos n t s) as [[ | | | ] | ].\ntrivial.\nassert (H':= (Relation_Definitions.equiv_trans _ _ equiv_equiv)  t u s).\nassert (H1': equiv t s).\nauto.\nassert (H2: rpo_eval rpo_infos n s t = Some Greater_than).\ntauto.\nassert (H3:= rpo_eval_is_complete_equivalent).\nassert (H3':= H3 rpo_infos n s t).\nassert (H4': size s + size t <=n).\nlia.\nassert (H4: rpo_eval rpo_infos n s t = Some Equivalent).\nrewrite H2 in H3'.\nassert (H5':= (Relation_Definitions.equiv_sym _ _ equiv_equiv) t s).\nassert (H5: equiv s t). apply H5'; assumption. auto.\nrewrite H2 in H4. discriminate.\n\nassert (H':= (Relation_Definitions.equiv_trans _ _ equiv_equiv)  t u s).\nassert (H1': equiv t s).\nauto.\nclear H2' H2''.\nassert (H4: rpo_eval rpo_infos n s t = Some Less_than).\nassert (H3:= rpo_eval_is_complete_less_greater).\nassert (H6:= H3 rpo_infos n s t). apply H6. lia. assumption.\n\n\nassert (H3:= rpo_eval_is_complete_equivalent).\nassert (H3':= H3 rpo_infos n s t).\nassert (H5':= (Relation_Definitions.equiv_sym _ _ equiv_equiv) t s).\nassert (H6: equiv s t). auto.\nassert (H4': size s + size t <=n).\nlia.\nrewrite H4 in H3'.\nassert (Some Less_than = Some Equivalent).\nauto.\ndiscriminate.\n\nclear H2' H2''.\ndestruct H31.\nassert (H':= (Relation_Definitions.equiv_trans _ _ equiv_equiv)  t u s).\ntauto.\ncontradict H31.\n\n\ndestruct (rpo_eval rpo_infos n t s) as [[ | | | ] | ].\ntrivial.\n\nassert (H5':= (Relation_Definitions.equiv_sym _ _ equiv_equiv) u s).\nassert (H5'': equiv s u).\nauto.\nassert (H':= (Relation_Definitions.equiv_trans _ _ equiv_equiv)  t s u). \nassert (H1': equiv t u).\nauto.\nassert (H2: rpo_eval rpo_infos n u t = Some Greater_than).\ntauto.\nassert (H3:= rpo_eval_is_complete_equivalent).\nassert (H3':= H3 rpo_infos n u t).\nassert (H4': size u + size t <=n).\nlia.\nassert (H4: rpo_eval rpo_infos n u t = Some Equivalent).\nrewrite H2 in H3'.\nassert (H6':= (Relation_Definitions.equiv_sym _ _ equiv_equiv) t u).\nassert (H5: equiv u t). apply H6'; assumption. auto.\nrewrite H2 in H4.\ndiscriminate.\ntrivial.\n \nrewrite  (equiv_rpo_equiv_1 _ H) in H32.\nassert (H2:= rpo_eval_is_complete_less_greater); clear H2' H2''.\nassert (H2':= H2 rpo_infos n t s).\nassert (H2'':= H2 rpo_infos n s t).\nassert (H4': size s + size t <=n).\nlia.\nassert (H5: rpo_eval rpo_infos n t s = Some Less_than).\ntauto.\nassert (H5': rpo_eval rpo_infos n t s = Some Greater_than).\ntauto.\nrewrite H5 in H5'; discriminate.\n\ndestruct H31 as (H41, (H42, H43)).\nrewrite (equiv_rpo_equiv_1 _ H) in H32.\ncontradiction.\ncontradiction.\n\ndestruct (rpo_eval rpo_infos n t s) as [[ | | | ] | ].\ntrivial.\n\nassert (H5':= (Relation_Definitions.equiv_sym _ _ equiv_equiv) t s).\nassert (H5'': equiv s t).\nauto.\nassert (H':= (Relation_Definitions.equiv_trans _ _ equiv_equiv)  u s t). \nassert (H1': equiv u t).\nauto.\nassert (H3:= rpo_eval_is_complete_equivalent).\nassert (H3':= H3 rpo_infos n u t).\nassert (H4': size u + size t <=n).\nlia.\nassert (H4: rpo_eval rpo_infos n u t = Some Equivalent).\nauto.\nassert (H2:= rpo_eval_is_complete_less_greater); clear H2' H2''.\nassert (H2':= H2 rpo_infos n u t).\nassert (rpo_eval rpo_infos n u t = Some Less_than).\ntauto.\nrewrite H0 in H4.\ndiscriminate.\n\nrewrite <- (equiv_rpo_equiv_1 _ H) in H31.\nassert (H2:= rpo_eval_is_complete_less_greater); clear H2' H2''.\nassert (H2':= H2 rpo_infos n t u).\nassert (H2'':= H2 rpo_infos n u t).\nassert (H4': size u + size t <=n).\nlia.\nassert (H5: rpo_eval rpo_infos n t u = Some Less_than).\ntauto.\nassert (H5': rpo_eval rpo_infos n t u = Some Greater_than).\ntauto.\nrewrite H5 in H5'; discriminate.\ntrivial.\n\n\ndestruct H31 as (H41, (H42, H43)).\nrewrite -> (equiv_rpo_equiv_2 _ H) in H32.\ncontradiction.\ncontradiction.\n\n\ndestruct (rpo_eval rpo_infos n t s) as [[ | | | ] | ].\ntrivial.\n\ndestruct H32 as (H41, (H42, H43)).\nassert (H5':= (Relation_Definitions.equiv_sym _ _ equiv_equiv)  u s).\nassert (H5'': equiv s u).\nauto.\nassert (H':= (Relation_Definitions.equiv_trans _ _ equiv_equiv)  t s u). \ntauto.\n\ndestruct H32 as (H41, (H42, H43)).\nrewrite <- (equiv_rpo_equiv_1 _ H) in H31.\ncontradiction.\n\ndestruct H32 as (H41, (H42, H43)).\nrewrite <- (equiv_rpo_equiv_2 _ H) in H31.\ncontradiction.\ntrivial.\ncontradiction.\n\ndestruct (rpo_eval rpo_infos n t s) as [[ | | | ] | ]; contradiction.\nQed.\n\n\nLemma list_gt_list_is_sound_mem_equiv :\n  forall rpo_infos n lg ls, (forall t t' :term, mem equiv t ls -> mem equiv t' lg -> size t + size t' <= n) ->\n   match list_gt_list (rpo_eval rpo_infos n) lg ls with\n   | Some true => forall s, mem equiv s ls -> exists g, mem equiv g lg /\\  rpo_eval rpo_infos n g s = Some Greater_than\n   | _ => True\n   end.\nProof.\nintros rpo_infos n lg ls H0. \nassert (forall t t' : term,\n      mem equiv t ls -> mem equiv t' lg -> size t' + size t <= n).\nintros.\nassert (H0':= H0 t t').  assert (size t + size t' <= n). tauto. lia. \n\ninduction ls as [ | s ls].\n\nsimpl; intros; contradiction.\nunfold list_gt_list; simpl.\nassert (match list_gt_list (rpo_eval rpo_infos n) lg ls with\n         | Some true =>\n             forall s : term,\n             mem equiv s ls ->\n             exists g : term,\n               mem equiv g lg /\\ rpo_eval rpo_infos n g s = Some Greater_than\n         | Some false => True\n         | None => True\n         end).\napply IHls.\nintros t t' H'. apply H0. simpl. tauto. clear IHls.  intros.\napply H. simpl. right. trivial. simpl. trivial. clear IHls.\n\ngeneralize (list_exists_option_is_sound\n  ( fun g : term =>\n       match rpo_eval rpo_infos n g s with\n       | Some Equivalent => Some false\n       | Some Less_than => Some false\n       | Some Greater_than => Some true\n       | Some Uncomparable => Some false\n       | None => None\n       end) lg). \ndestruct\n(list_exists_option\n    (fun g : term =>\n     match rpo_eval rpo_infos n g s with\n     | Some Equivalent => Some false\n     | Some Less_than => Some false\n     | Some Greater_than => Some true\n     | Some Uncomparable => Some false\n     | None => None\n     end) lg) as [[ | ] | ].\nintros [g [g_in_ls H']]. \n \ngeneralize H1. unfold list_gt_list.\ndestruct ( list_forall_option\n       (fun s0 : term =>\n        list_exists_option\n          (fun g0 : term =>\n           match rpo_eval rpo_infos n g0 s0 with\n           | Some Equivalent => Some false\n           | Some Less_than => Some false\n           | Some Greater_than => Some true\n           | Some Uncomparable => Some false\n           | None => None\n           end) lg) ls) as [[ | ] | ].\n\nintros H0' u [s_eq_u | u_in_ls]. \n\n \nexists g; split.\napply in_mem.\nassumption.\nassert (H1':= in_mem g lg).\nassert (H2': mem equiv g lg).\nauto.\nassert (H3':= equiv_rpo_eval).\nassert (H3:= H3' n rpo_infos g s u); clear H3'.\nassert (H4':= H0' s).\nassert (H5: rpo_eval rpo_infos n g u = rpo_eval rpo_infos n g s).\nassert (H6:= equiv_same_size).\nassert (H6':= H6 u s); clear H6.\nassert (size u = size s).\nauto.\napply H3. apply H. \nsimpl.\ntauto. assumption.\napply H.\nsimpl. \nleft. apply (Relation_Definitions.equiv_refl _ _ equiv_equiv). assumption.\nassumption.\nrewrite H5.\n\ngeneralize H'.\ndestruct (rpo_eval rpo_infos n g s) as [[ | | | ] | ]; intros. discriminate.\ndiscriminate. trivial. discriminate. discriminate. \nassert (H10':= H0' u); clear H0'.\nassert (H0': exists g : term,\n           mem equiv g lg /\\ rpo_eval rpo_infos n g u = Some Greater_than).\napply H10'. trivial. trivial. trivial. trivial.\nintros _;\ndestruct\n(list_forall_option\n    (fun s0 : term =>\n     list_exists_option\n       (fun g0 : term =>\n        match rpo_eval rpo_infos n g0 s0 with\n        | Some Equivalent => Some false\n        | Some Less_than => Some false\n        | Some Greater_than => Some true\n        | Some Uncomparable => Some false\n        | None => None\n        end) lg) ls) as [[ | ] | ]; trivial.\ntrivial.\nQed.\n\n\nLemma mult_eval_is_sound_weak_equiv :\n  forall rpo_infos n l1 l2, (forall t t' :term, mem equiv t l1 -> mem equiv t' l2 -> size t + size t' <= n) ->\n   match mult_eval (rpo_eval rpo_infos n)  l1 l2 with\n     | Some Equivalent => False\n     | Some Less_than =>  \n       forall t1, mem equiv t1 l1 -> exists t2,  mem equiv t2 l2 /\\ (size t2 + size t1 <= n -> rpo_eval rpo_infos n t2 t1 = Some Greater_than)\n     | Some Greater_than =>  \n       forall t2, mem equiv t2 l2 -> exists t1, mem equiv t1 l1 /\\ (size t1 + size t2 <= n -> rpo_eval rpo_infos n t1 t2 = Some Greater_than)\n     | _ => True\n     end.\nProof.\nintros rpo_infos n l1 l2 H; unfold mult_eval.\nassert (forall t t' : term,\n      mem equiv t l2 -> mem equiv t' l1 -> size t + size t' <= n).\nintros t t'.\nassert (mem equiv t' l1 -> mem equiv t l2 -> size t' + size t <= n).\napply H.\nintros H1' H2.\nassert (size t' + size t <= n).\nauto.\nlia. \ngeneralize (list_gt_list_is_sound_mem_equiv rpo_infos l1 l2 H0). destruct (list_gt_list (rpo_eval rpo_infos n) l1 l2) as [[ | ] | ]. trivial. intros H' t2 H1.\nassert (H2':= H' t2); clear H'. \nassert (H3: exists g : term,\n          mem equiv g l1 /\\ rpo_eval rpo_infos n g t2 = Some Greater_than).\nauto.\ndestruct H3.\nexists x.\nassert (H': size x + size t2 <= n).\napply H. apply H2. assumption.\nsplit. apply H2. intro; apply H2.\n\nintros.\ngeneralize (list_gt_list_is_sound_mem_equiv rpo_infos l2 l1 H).\ndestruct (list_gt_list (rpo_eval rpo_infos n) l2 l1) as [[ | ] | ].\n intros H' t2 H1'. \nassert (H2':= H' t2); clear H'. \nassert (H3: exists g : term,\n          mem equiv g l2 /\\ rpo_eval rpo_infos n g t2 = Some Greater_than).\nauto.\ndestruct H3.\nexists x.\nassert (H': size x + size t2 <= n).\napply H0. apply H2. assumption.\nsplit. apply H2. intro; apply H2.\ntrivial. trivial. trivial.\nQed.\n \n\n\nLemma permut0_mem : forall A X L b, permut0 eq A (X ++ L) -> mem equiv b X -> mem equiv b A.\nProof. \nintros.\nassert (H1:= permut_impl).\nassert (H1':= H1 term term eq equiv A (X ++ L)); clear H1.\nassert (permut0 equiv A (X++L)).\napply H1'.\nintros a b0 H2.\nrewrite H2. apply (Relation_Definitions.equiv_refl _ _ equiv_equiv).\ntrivial.\n\nassert (H2:=mem_permut0_mem).\nassert (H2':= H2 term equiv).\nassert (forall (l1 l2 : list term) (a : term),\n        permut0 equiv l1 l2 -> (mem equiv a l1 <-> mem equiv a l2)).\napply H2'.\napply equiv_equiv.\nassert (H3':= H3 A (X ++ L) b).\nassert (mem equiv b A <-> mem equiv b (X ++ L)).\napply H3'. assumption.\n \napply H4; clear H H1 H1' H2 H3 H4.\ngeneralize H0. generalize X.\ninduction X0.\nintros.\ncontradiction.\nsimpl. intros. destruct H1. left; trivial. right. apply IHX0; trivial.\nQed. \n \n\nTheorem rpo_mult_eval_rpo_mul_less: forall rpo_infos A B, rpo_mult_eval rpo_infos rpo_infos.(bb) A B =  Some Less_than -> rpo_mul rpo_infos.(bb) A B.\nProof.\nintros rpo_infos A0 B H.\nunfold rpo_mult_eval in H.\ncase_eq (remove_equiv_eval_list (equiv_eval rpo_infos rpo_infos.(bb)) A0 B).\nintros (l1,l2) Hrem.\nrewrite Hrem in H.\ncase_eq l1; case_eq l2.\nintros Hl2 Hl1.\nrewrite Hl2, Hl1 in H.\ndiscriminate H.\nintros t l Hl2 Hl1.\nrewrite Hl2, Hl1 in H, Hrem.\nclear H.\nassert (Hequiv:=remove_equiv_eval_list_is_sound (equiv_eval rpo_infos rpo_infos.(bb)) A0 B).\nrewrite Hrem in Hequiv.\nelim Hequiv; clear Hequiv.\nintros ll (H1,(H2,(H3,_))).\napply (@List_mul _ t l nil A0); trivial.\nreflexivity.\ntransitivity ((t :: l) ++ (map (fun st : term * term => snd st) ll)).\napply permut_impl with (@eq term); trivial; intros; subst; reflexivity.\nrewrite app_comm_cons; rewrite <- permut_app1.\ntransitivity (map (fun st : term * term => fst st) ll).\nsymmetry.\nassert (E_ll' : forall t1 t2, In (t1,t2) ll -> equiv t1 t2).\nintros t1 t2 t1t2_in_ll; \nassert (H' := equiv_eval_is_sound_weak rpo_infos rpo_infos.(bb) t1 t2);\nrewrite (H1 t1 t2 t1t2_in_ll) in H'; apply H'; trivial.\nclear H1 H2 H3; induction ll as [ | [t1 t2] ll].\nreflexivity.\nsimpl; rewrite <- permut0_cons.\napply IHll.\nintros; apply E_ll'; right; trivial. apply equiv_equiv.\napply E_ll'; left; trivial.\nsymmetry; \napply permut_impl with (@eq term); trivial; intros; subst; reflexivity. apply equiv_equiv.\nintros; contradiction.\n\nintros Hl2 t l Hl1.\nrewrite Hl1, Hl2 in H.\ndiscriminate H.\n\nintros t l Hl2 t' l' Hl1.\nrewrite Hl1, Hl2 in H.\nassert (Hequiv:=remove_equiv_eval_list_is_sound (equiv_eval rpo_infos rpo_infos.(bb)) A0 B).\nrewrite Hrem in Hequiv.\nelim Hequiv; clear Hequiv.\nintros ll (H1,(H2,(H3,H4))).\nassert (E_ll' : forall t1 t2, In (t1,t2) ll -> equiv t1 t2).\nintros t1 t2 t1t2_in_ll; \nassert (H' := equiv_eval_is_sound_weak rpo_infos rpo_infos.(bb) t1 t2);\nrewrite (H1 t1 t2 t1t2_in_ll) in H'; apply H'; trivial.\nrewrite Hl1 in H2,H4,Hrem.\nrewrite Hl2 in H3,H4,Hrem.\nclear Hl1 Hl2 l1 l2.\napply (@List_mul _ t l (t' :: l') (map (fun st : term * term => fst st) ll)); trivial.\napply permut_impl with (@eq term); trivial; intros; subst; reflexivity.\ntransitivity ((t :: l) ++ map (fun st : term * term => snd st) ll).\napply permut_impl with (@eq term); trivial; intros; subst; reflexivity.\nrewrite app_comm_cons; rewrite <- permut_app1.\nclear H2 H3; induction ll as [ | [t1 t2] ll].\nreflexivity.\nsimpl; rewrite <- permut0_cons.\napply IHll.\nintros; apply H1; right; trivial.\nintros; apply E_ll'; right; trivial. apply equiv_equiv.\nsymmetry; apply E_ll'; left; trivial. apply equiv_equiv.\nintros u1 u1_mem_l1'.\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ u1_mem_l1') as [u1' [k1 [k1' [u1_eq_u1' [H' _]]]]].\nsimpl in u1_eq_u1'; simpl in H'.\nassert (u1'_in_l1' : In u1' (t' :: l')).\nrewrite H'; apply in_or_app; right; left; trivial.\nassert (H'' := mult_eval_is_sound_weak (rpo_eval rpo_infos rpo_infos.(bb)) (t' :: l') (t :: l)).\nrewrite H in H''.\ndestruct (H'' _ u1'_in_l1') as [u2 [u2_in_l2' u1_lt_u2]];\nexists u2; split.\napply in_impl_mem; trivial.\nexact Eq.\nassert (H''' := @rpo_eval_is_sound_weak rpo_infos rpo_infos.(bb) u2 u1').\nrewrite u1_lt_u2 in H'''.\nrewrite (equiv_rpo_equiv_2 _ u1_eq_u1'); trivial.\n\nintro Hrem.\nrewrite Hrem in H.\nclear Hrem.\ndiscriminate H.\nQed.\n\nLemma rpo_mul_trans : forall bb u t s, rpo_mul bb u t -> rpo_mul bb t s ->  rpo_mul bb u s.\nProof.  (* inspired from the proof of rpo_trans *)\nintros.\ndestruct H0 as [a lg ls lc l l' P' P ls_lt_alg].\ndestruct H as [a' lg' ls' lc' l' l'' Q' Q ls'_lt_alg'].\nrewrite P' in Q; rewrite app_comm_cons in Q.\ndestruct (@ac_syntactic _ _ equiv_equiv _ equiv_bool_ok _ _ _ _ Q) as [k1 [k2 [k3 [k4 [P1 [P2 [P3 P4]]]]]]].\napply (@List_mul bb0 a (lg ++ k2) (ls' ++ k3) k1).\nrewrite Q'.\nrewrite <- ass_app.\nrewrite <- permut_app1.\nrewrite list_permut0_app_app; trivial. apply equiv_equiv. apply equiv_equiv.\nrewrite P.\nrewrite <- permut0_cons;[|apply equiv_equiv|apply (Relation_Definitions.equiv_refl _ _ equiv_equiv)].\nrewrite <- ass_app.\nrewrite <- permut_app1.\nrewrite list_permut0_app_app; trivial.  apply equiv_equiv. apply equiv_equiv.\nintros b b_mem_ls'_k3; rewrite <- mem_or_app in b_mem_ls'_k3.\ndestruct b_mem_ls'_k3 as [b_mem_ls' | b_mem_k3].\ndestruct (ls'_lt_alg'  _ b_mem_ls') as [a'' [a''_in_a'lg' b_lt_a'']].\nrewrite (mem_permut0_mem equiv_equiv a'' P4) in a''_in_a'lg'.\nrewrite <- mem_or_app in a''_in_a'lg'.\ndestruct a''_in_a'lg' as [a''_mem_k2 | a''_mem_k4].\nexists a''; split; trivial.\nrewrite app_comm_cons; rewrite <- mem_or_app; right; trivial.\ndestruct (ls_lt_alg a'') as [a3 [a3_in_alg a''_lt_a3]].\nrewrite (mem_permut0_mem equiv_equiv a'' P2).\nrewrite <- mem_or_app; right; trivial.\nexists a3; split.\nrewrite app_comm_cons; rewrite <- mem_or_app; left; trivial.\napply rpo_trans with (a''). trivial. trivial.\ndestruct (ls_lt_alg b) as [a'' [a''_in_alg b_lt_a'']].\nrewrite (mem_permut0_mem equiv_equiv b P2); rewrite <- mem_or_app; left; trivial.\nexists a''; split; trivial.\nrewrite app_comm_cons; rewrite <- mem_or_app; left; trivial.\nQed.\n \nTheorem rpo_mul_rest_trans: forall bb l1 l2 l3, well_founded (prec Prec) -> rpo_mul_rest bb l1 l2 -> rpo_mul_rest bb l2 l3 -> rpo_mul_rest bb l1 l3.\nProof.\nintros.\nassert (H2:= @rpo_mul_trans bb0 l1 l2 l3).\nassert (H3:=wf_rpo). assert (well_founded (rpo bb0)).\napply H3. trivial.\napply Rpo_mul_rest.\nintros.\nunfold well_founded in H4.\napply H4.\nintros.\nunfold well_founded in H4.\napply H4.\napply H2.\ndestruct H0; trivial.\ndestruct H1; trivial.\nQed.\n\n(* some useful lemmas *)\n\nLemma rpo_mul_remove_equiv_aux1 :\n  forall bb l l' s s',  equiv s s' -> rpo_mul bb (s :: l) (s' :: l') -> rpo_mul bb l l'. \nProof.\nintros.\napply rpo_mul_remove_equiv_aux with s s'.\nintros H1 H2.\napply rpo_antirefl.\ntrivial. trivial.\nQed.   \n\nTheorem rpo_mul_antirefl : forall rpo_infos l, rpo_mul (bb rpo_infos) l l -> False. \nProof.\ninduction l.\nintros.\ninversion H.\ninversion H1.\nintros. \napply IHl. \napply rpo_mul_remove_equiv_aux1 with a a.\napply equiv_refl. apply equiv_equiv. trivial.\nQed.\n  \n(* other interesting lemmas *)\n \nLemma eq_equiv: forall t1 t2, eq t1 t2 -> equiv t1 t2.\nProof.\nintros t1 t2 H.\nrewrite H.\napply (Relation_Definitions.equiv_refl _ _ equiv_equiv); trivial.\nQed.\n\nLemma rpo_mul_dickson: forall bb l l', rpo_mul_rest bb l l' -> clos_trans (list term) (rpo_mul_step_rest bb) l l'.\nProof.\nintros.\nassert (H1:=  (rpo_mul_rest_trans_clos)).\nassert (H2:= H1 bb0).\nunfold inclusion in H2.\nassert (H2':= H2 l l').\nassert ( clos_trans (list term) (rpo_mul_step_rest bb0) l l').\napply H2'; trivial.\ntrivial.\nQed.\n\n \nLemma mem_in_1: forall t: term, forall A,  mem eq t A -> In t A.\nProof.\nintro t.\ninduction A.\nintros.\nunfold mem in H.\ncontradiction.\nunfold mem.\nunfold In.\nintro H.\ndestruct H.\nleft.\nrewrite H. trivial.\nright.\nassert (In t A).\napply IHA.\nassumption.\nassumption.\nQed.\n\n\nLemma mem_in_2: forall t: term, forall A,  In t A -> mem eq t A.\nProof.\nintro t.\ninduction A.\nintros.\nunfold In in  H.\ncontradiction.\nunfold In.\nunfold mem.\nintro H.\ndestruct H.\nleft.\nrewrite H. trivial.\nright.\nassert (mem eq t A).\napply IHA.\nassumption.\nassumption.\nQed.\n\n \nTheorem rpo_mult_eval_rpo_mul_greater: forall rpo_infos n A B,  (forall t t' :term, mem equiv t B -> mem equiv t' A -> size t + size t' <= n) ->  rpo_mult_eval rpo_infos n A B =  Some Greater_than -> rpo_mul rpo_infos.(bb) B A.\nProof.\nintros rpo_infos n A0 B H1 H. \nunfold rpo_mult_eval in H.\nassert (H':= remove_equiv_eval_list_is_sound). \ncase_eq (remove_equiv_eval_list (equiv_eval rpo_infos n) A0 B).\nintros p H3.\nrewrite H3 in H.\ndestruct p.\ndestruct l.\ndestruct l0.\ndiscriminate.\ndiscriminate.\ndestruct l0.\nassert (H2':= H' (equiv_eval rpo_infos n) A0 B); clear H' H.\nrewrite H3 in H2'.\ndestruct  H2' as (l', (H01, (H02, (H03, H4)))).\napply (@List_mul _ t l nil (map (fun st : term * term => snd st) l')).\napply permut0_eq_equiv.\nassumption.\napply permut0_trans with (t :: l ++ map (fun st : term * term => fst st) l').\napply equiv_equiv.\napply permut0_eq_equiv.\nassumption.\nassert (H2':= equiv_eval_lists (t::l) l' n rpo_infos H01). trivial. \nintros b H'. \ncontradict H'.\n\nassert (H3':= H' (equiv_eval rpo_infos n) A0 B); clear H'.\nrewrite H3 in H3'.\ndestruct H3' as (ll, (H01, (H02, (H03, H4)))). \napply (@List_mul _ t l (t0 :: l0) ( map (fun st : term * term => snd st) ll)). \napply permut0_eq_equiv.\nassumption.\nassert (H2':= equiv_eval_lists (t::l) ll n rpo_infos H01).\napply permut0_trans with ((t :: l) ++ map (fun st : term * term => fst st) ll).\napply equiv_equiv.\napply permut0_eq_equiv.\nauto.\nauto.\n\nintros b H'.\nassert (H1':= mult_eval_is_sound_weak_equiv).\nassert (H1'':= H1' rpo_infos n (t :: l) (t0 :: l0)); clear H1'.\nassert (H6: (forall t1 t' : term,\n          mem equiv t' (t :: l) ->\n          mem equiv t1 (t0 :: l0) -> size t1 + size t' <= n)).\n\nintros t1 t2 H1' H2.  clear H1''.\n\n\napply H1. \napply permut0_mem with (t0 :: l0) (map (fun st : term * term => snd st) ll).\nassumption. assumption.\napply permut0_mem with (t :: l) (map (fun st : term * term => fst st) ll).\nassumption. assumption.\n\n\nassert (H1': match mult_eval (rpo_eval rpo_infos n) (t :: l) (t0 :: l0) with\n         | Some Equivalent => False\n         | Some Less_than =>\n             forall t1 : term,\n             mem equiv t1 (t :: l) ->\n             exists t2 : term,\n               mem equiv t2 (t0 :: l0) /\\\n               (size t2 + size t1 <= n ->\n                rpo_eval rpo_infos n t2 t1 = Some Greater_than)\n         | Some Greater_than =>\n             forall t2 : term,\n             mem equiv t2 (t0 :: l0) ->\n             exists t1 : term,\n               mem equiv t1 (t :: l) /\\\n               (size t1 + size t2 <= n ->\n                rpo_eval rpo_infos n t1 t2 = Some Greater_than)\n         | Some Uncomparable => True\n         | None => True\n         end).\napply H1''. \nassert (forall t1 t' : term,\n       mem equiv t' (t :: l) ->\n       mem equiv t1 (t0 :: l0) -> size t' + size t1 <= n).\n\nintros t2 t'.\nassert (mem equiv t' (t :: l) -> mem equiv t2 (t0 :: l0) -> size t' + size t2 <= n).\nintros H1' H2.\nassert (H6':= H6 t' t2).\nassert (H0: size t2 + size t' <= n).\nauto.\nlia. \nassumption.  intros. apply H0; trivial.\nclear H1''.\nrewrite H in H1'.\nassert (H1'':= H1' b); clear H1'.\nassert ( exists t1 : term,\n           mem equiv t1 (t :: l) /\\\n           (size t1 + size b <= n ->\n            rpo_eval rpo_infos n t1 b = Some Greater_than)).\n\napply H1''; trivial. clear H1''.\ndestruct H0. destruct H0.\nexists x.\nsplit.\ntrivial.\nassert (rpo_eval rpo_infos n x b = Some Greater_than).\napply H2. \nassert (H6':= H6 b x).\nassert (size b + size x <= n).\napply H6'. trivial. trivial.\nlia.\n\nassert (H6'':= rpo_eval_is_complete).\nassert (H6':= H6'' rpo_infos n x b); clear H6''.\nrewrite H2 in H6'.\napply H6'.\nassert (H6'':= H6 b x). \nassert (size b + size x <= n).\napply H6''. trivial. trivial.\nlia.\n\nassert (H6'':= H6 b x). \nassert (size b + size x <= n).\napply H6''. trivial. trivial.\nlia.\n\nintro. \nrewrite H0 in H.\n\nassert (H'':= H' (equiv_eval rpo_infos n) A0 B); clear H'.\nrewrite H0 in H''.\ndestruct H0. \ndestruct H'' as (t1, (t2, (In_t1_A, (In_t2_B, H4)))). \nassert (H2:=  mult_eval_is_sound_weak_equiv).\ndiscriminate H.\nQed.\n \n\nLemma rpo_mul_permut0_left: forall rpo_infos l0 l1 l2, permut0 equiv l0 l1 -> rpo_mul (bb rpo_infos) l0 l2 -> rpo_mul (bb rpo_infos) l1 l2.\nProof.\nintros.\ninversion H0.\napply List_mul with a lg ls lc.\napply permut0_trans with l0. apply equiv_equiv.\napply permut0_sym. apply equiv_equiv. trivial. trivial.\ntrivial.\ntrivial.\nQed.\n\nLemma rpo_mul_permut0_right:  forall rpo_infos l0 l1 l2, permut0 equiv l0 l1 -> rpo_mul (bb rpo_infos)  l2 l0 -> rpo_mul (bb rpo_infos) l2 l1.\nProof.\nintros.\ninversion H0.\napply List_mul with a lg ls lc. trivial.\napply permut0_trans with l0. apply equiv_equiv.\napply permut0_sym. apply equiv_equiv. trivial. trivial.\ntrivial.\nQed.\n\n  \nLemma rpo_mul_inclusion_left : forall rpo_infos l1 l2 l3, rpo_mul (bb rpo_infos) (l1++ l2) (l1 ++ l3) -> rpo_mul (bb rpo_infos) l2 l3.\nProof.\ninduction l1.\nsimpl. intros. trivial.\nintros.\napply IHl1.\nassert (((a:: l1) ++ l2) = a :: (l1 ++ l2)).\nsimpl. trivial.\nassert (((a :: l1) ++ l3) = a:: (l1 ++ l3)). \nsimpl. trivial.\nrewrite H0 in H. rewrite H1 in H.\napply rpo_mul_remove_equiv_aux1 with a a.\napply equiv_refl. apply equiv_equiv. trivial.\nQed.\n\nLemma rpo_mul_inclusion_right : forall rpo_infos l1 l2 l3, rpo_mul (bb rpo_infos) (l2++ l1) (l3 ++ l1) -> rpo_mul (bb rpo_infos) l2 l3.\nProof.\ninduction l1.\nintros.\nrewrite <- app_nil_end in H. rewrite <- app_nil_end in H. trivial.\n\nintros.\napply IHl1.\nassert (rpo_mul (bb rpo_infos) (a:: (l2 ++ l1)) (a :: (l3 ++ l1))).\ninversion H.\napply List_mul with a0 lg ls lc.\nassert (permut0 equiv (a :: l2 ++ l1) (l2 ++ a :: l1)).\nrewrite <- permut0_cons_inside. \napply permut0_refl. apply equiv_equiv. apply equiv_equiv. apply equiv_refl. apply equiv_equiv.\napply permut0_trans with (l2 ++ a :: l1). apply equiv_equiv. trivial. trivial.\nassert (permut0 equiv (a :: l3 ++ l1) (l3 ++ a :: l1)).\nrewrite <- permut0_cons_inside. \napply permut0_refl. apply equiv_equiv. apply equiv_equiv. apply equiv_refl. apply equiv_equiv.\napply permut0_trans with (l3 ++ a :: l1). apply equiv_equiv. trivial. trivial.\ntrivial.\napply rpo_mul_remove_equiv_aux1 with a a.\napply equiv_refl. apply equiv_equiv. trivial.\nQed.\n\nLemma rpo_mul_inclusion_permut0_left : forall rpo_infos l0 l1 l2 l3, permut0 equiv l0 l1 -> rpo_mul (bb rpo_infos) (l0++ l2) (l1 ++ l3) -> rpo_mul (bb rpo_infos) l2 l3.\nProof.\nintros.\ninversion H0.\nassert (permut0 equiv (l1 ++ l2) (ls ++ lc)).\napply permut0_trans with (l0 ++ l2). apply equiv_equiv.\nrewrite <- permut0_app2. apply permut0_sym. apply equiv_equiv. trivial. apply equiv_equiv. trivial.\nassert (rpo_mul (bb rpo_infos) (l1 ++ l2) (l1 ++ l3)).\napply List_mul with a lg ls lc. trivial. trivial. trivial. \n\napply rpo_mul_inclusion_left with l1.  trivial.\nQed. \n\nLemma rpo_mul_inclusion_permut0_right : forall rpo_infos l0 l1 l2 l3, permut0 equiv l0 l1 -> rpo_mul (bb rpo_infos) (l2++ l0) (l3 ++ l1) -> rpo_mul (bb rpo_infos) l2 l3.\nProof.\nintros.\ninversion H0.\nassert (permut0 equiv (l2 ++ l1) (ls ++ lc)).\napply permut0_trans with (l2 ++ l0). apply equiv_equiv.\nrewrite <- permut0_app1. apply permut0_sym. apply equiv_equiv. trivial. apply equiv_equiv. trivial.\nassert (rpo_mul (bb rpo_infos) (l2 ++ l1) (l3 ++ l1)).\napply List_mul with a lg ls lc. trivial. trivial. trivial. \n\napply rpo_mul_inclusion_right with l1.  trivial.\nQed. \n  \nLemma list_forall_option_decomposed: forall (A: Set) (f : A -> option bool) (l: list A) (t: A),  f t = Some true  -> (list_forall_option f (t :: l) = Some true <-> list_forall_option f l = Some true).\nProof.\n  intros. simpl.\nrewrite H. reflexivity.\nQed.\n\nLemma list_exists_option_decomposed: forall (A: Set) (f : A -> option bool) (l: list A) (t: A),  f t = Some false -> (list_exists_option f (t :: l) = Some true <-> list_exists_option f l = Some true).\nProof.\n  intros. simpl.\nrewrite H. reflexivity.\nQed.\n    \n Lemma list_forall_exists_option_true : forall (A: Set) (f: A -> A -> option bool) (l1 l2 : list A), list_forall_option (fun t2: A => list_exists_option (fun t1: A =>\nf t1 t2) l1) l2 = Some true -> (forall t2, In t2 l2 ->  exists t1, In t1 l1 /\\ f t1 t2 = Some true).\nProof.\nintros.\nassert (H1:= @list_forall_option_is_sound A (fun t2 : A => list_exists_option (fun t1 : A => f t1 t2) l1) l2).\nrewrite H in H1.\nassert (forall a : A,\n       In a l2 -> exists t1, In t1 l1 /\\ f t1 a = Some true).\nintros.\nassert (H1':= H1 a).\nassert ( list_exists_option (fun t1 : A => f t1 a) l1 = Some true).\napply H1'; trivial.\n \nassert (H5:= @list_exists_option_is_sound A (fun t1 : A => f t1 a) l1).\nrewrite H3 in H5.\ndestruct H5.\ndestruct H4.\nexists x.\nintros.\nsplit.\nassumption. assumption.\n\nassert (H2':= H2 t2).\nassert ( exists t1 : A, In t1 l1 /\\ f t1 t2 = Some true).\napply H2'; trivial.\ndestruct H3.\nexists x.\nintros.\nassumption.\nQed.\n  \n \nLemma list_forall_exists_option_false : forall (A: Set) (f: A -> A -> option bool) (l1 l2 : list A), list_forall_option (fun t2: A => list_exists_option (fun t1: A =>\nf t1 t2) l1) l2 = Some false -> (forall t2, In t2 l2 ->  exists t1, In t1 l1 -> f t1 t2 = Some false) \\/ (forall t2 : A,\n       In t2 l2 -> exists t1 : A, In t1 l1 -> f t1 t2 = None -> False).\nProof.\nintros.\nassert (H1:= @list_forall_option_is_sound A (fun t2 : A => list_exists_option (fun t1 : A => f t1 t2) l1) l2).\nrewrite H in H1.\ndestruct H1.\nassert (exists a : A,\n       In a l2 /\\ exists t1, In t1 l1 -> f t1 a = Some false).\ndestruct H0. destruct H0.\nexists x.\nsplit. trivial.\nassert (H4:= @list_exists_option_is_sound A (fun t1 : A => f t1 x) l1).\nrewrite H2 in H4.\nexists x. apply H4.\n \nassert (forall a : A, In a l2 -> exists t1, In t1 l1 -> f t1 a = None -> False).\nintros.\nassert (H2':= H1 a).\nassert ( list_exists_option (fun t1 : A => f t1 a) l1 = None -> False).\napply H2'; trivial.\n \nassert (H6:= @list_exists_option_is_sound A (fun t1 : A => f t1 a) l1).\ncase_eq (list_exists_option (fun t1 : A => f t1 a) l1).\nintros. destruct b.\nrewrite H5 in H6.\ndestruct H6. destruct H6.\nexists x.\nintros.\nrewrite H9 in H7. discriminate.\nrewrite H5 in H6. exists a.\nintros.\nassert (H6':= H6 a).\nassert (f a a =  Some false).\napply H6'; trivial.\nrewrite H9 in H8. discriminate.\n\nintros.\nrewrite H5 in H6. destruct H6.\ndestruct H6.\nexists x.\nintros.\napply H4. trivial.\n\nright. assumption. \nQed.\n\n\nLemma exists_rpo_eval_less_greater: forall rpo_infos n a l2, (forall a'', In a'' l2 -> size a + size a'' <= n) -> (exists a' : term,\n         mem equiv a' l2 /\\ rpo_eval rpo_infos n a a' = Some Less_than) -> exists a'', In a'' l2 /\\ rpo_eval rpo_infos n a'' a = Some Greater_than.\nProof.\nintros rpo_infos n a l2 size_a H.\ndestruct H.\ndestruct H.\ndestruct (mem_split_set _ _ equiv_bool_ok _ _ H) as [s'' [lc' [lc'' [s_eq_s'' [H5 _]]]]].\nexists s''.\nassert (H2:=@rpo_eval_is_sound_weak rpo_infos n a x).\nrewrite H0 in H2.\nrewrite (equiv_rpo_equiv_1 (bb rpo_infos)  s_eq_s'') in H2. \nsplit. rewrite H5. apply in_or_app. right. simpl. left. trivial.\nassert (size_a_s'':= size_a s'').\nassert (size a + size s'' <= n).\napply size_a_s''.\nrewrite H5. apply in_or_app. right. simpl. left. trivial.\nassert (H3:= @rpo_eval_is_complete_less_greater rpo_infos _ _ _ H1). apply H3. trivial.\nQed.\n\nLemma distribute_disj_imply: forall P Q R: Prop, ((P -> Q) /\\ (R -> Q)) -> ((P \\/ R) -> Q).\nProof.\nintros.\n\ndestruct H.\ndestruct H0.\napply H. trivial.\napply H1. trivial.\nQed.\n\nLemma distribute_impl_conj: forall P Q R: Prop, ((P -> Q) /\\ (P -> R)) -> (P -> (Q /\\ R)).\nProof.\nintros.\ndestruct H.\nsplit.\napply H. assumption.\napply H1. assumption.\nQed.\n\n\nLemma list_gt_list_is_sound_true :\n  forall p lg ls, list_gt_list p lg ls = Some true -> (forall s, In s ls -> exists g, In g lg /\\ p g s = Some Greater_than).\nProof.\nintros.\nassert (H1:=@list_gt_list_is_sound p lg ls).\nrewrite H in H1.\nassert (H1':= H1 s).\napply H1'. trivial.\nQed.\n \nLemma list_gt_list_is_sound_false :\n  forall p lg ls,  list_gt_list p lg ls = Some false -> exists s, In s ls /\\ forall g, In g lg -> (p  g s = Some Less_than \\/ p g s = Some Equivalent \\/ p g s = Some Uncomparable).\nProof.\n\nintros p lg ls; revert lg; induction ls as [ | s ls]; intro lg.\nunfold list_gt_list; simpl.\nintros. \ncompute in H. discriminate.\n\n\nunfold list_gt_list; simpl.\ngeneralize (list_exists_option_is_sound \n  (fun g : term =>\n       match p g s with\n       | Some Equivalent => Some false\n       | Some Less_than => Some false\n       | Some Greater_than => Some true\n       | Some Uncomparable => Some false\n       | None => None\n       end) lg).\n\ndestruct \n(list_exists_option\n    (fun g : term =>\n     match p g s with\n     | Some Equivalent => Some false\n     | Some Less_than => Some false\n     | Some Greater_than => Some true\n     | Some Uncomparable => Some false\n     | None => None\n     end) lg) as [[ | ] | ].\nintros [g [g_in_ls H]].\ngeneralize (IHls lg); unfold list_gt_list;\ndestruct \n(list_forall_option\n    (fun s0 : term =>\n     list_exists_option\n       (fun g0 : term =>\n        match p g0 s0 with\n        | Some Equivalent => Some false\n        | Some Less_than => Some false\n        | Some Greater_than => Some true\n        | Some Uncomparable => Some false\n        | None => None\n        end) lg) ls) as [[ | ] | ].\nintros. discriminate.\nintros.\n \ndestruct (p g s) as [[ | | | ] | ]. discriminate. discriminate.\nassert (exists s : term,\n         In s ls /\\\n         (forall g : term,\n          In g lg ->\n          (p g s = Some Less_than \\/\n           p g s = Some Equivalent \\/ p g s = Some Uncomparable))).\napply H0; trivial.\ndestruct H2.\nexists x.\ndestruct H2.\nsplit.\nright. trivial. assumption. discriminate. discriminate.\n\nintros. discriminate.\n\ndestruct \n(list_forall_option\n    (fun s0 : term =>\n     list_exists_option\n       (fun g0 : term =>\n        match p g0 s0 with\n        | Some Equivalent => Some false\n        | Some Less_than => Some false\n        | Some Greater_than => Some true\n        | Some Uncomparable => Some false\n        | None => None\n        end) lg) ls) as [[ | ] | ].\nintros.\n\nexists s.\nsplit. left; trivial.\nintros.\nassert (H':= H g). assert (match p g s with\n       | Some Equivalent => Some false\n       | Some Less_than => Some false\n       | Some Greater_than => Some true\n       | Some Uncomparable => Some false\n       | None => None\n       end = Some false).\napply H'; trivial.\ncase_eq (p g s).\ndestruct c.\nintros. rewrite H3 in H2.\nright. left; trivial.\nintros. rewrite H3 in H2. left; trivial. \nintros. rewrite H3 in H2. discriminate.\nintros. rewrite H3 in H2. right. right. trivial.\nintros.  rewrite H3 in H2. discriminate.\n\nintros.\n\nexists s.\nsplit. left; trivial.\nintros.\nassert (H':= H g). assert (match p g s with\n       | Some Equivalent => Some false\n       | Some Less_than => Some false\n       | Some Greater_than => Some true\n       | Some Uncomparable => Some false\n       | None => None\n       end = Some false).\napply H'; trivial.\ncase_eq (p g s).\ndestruct c.\nintros. rewrite H3 in H2.\nright. left; trivial.\nintros. rewrite H3 in H2. left; trivial. \nintros. rewrite H3 in H2. discriminate.\nintros. rewrite H3 in H2. right. right. trivial.\nintros.  rewrite H3 in H2. discriminate.\n\nintros. discriminate.\n\nintros. discriminate.\nQed.\n\n\nLemma list_gt_list_is_sound_none:   forall p lg ls,  list_gt_list p lg ls = None -> (exists t1: term, In t1 ls /\\ ((exists t2:term, In t2 lg /\\ p t2 t1 = None) /\\\n       (forall t2, In t2 lg -> p t2 t1 = Some Greater_than -> False))).\nProof.\nintros.\ncase_eq (list_gt_list p lg ls).\nintros.\ndestruct b. rewrite H in H0. discriminate.\nrewrite H in H0. discriminate.\nintros.\nunfold list_gt_list in H0.\nassert (H1 := @list_forall_option_is_sound term (fun s : term =>\n          list_exists_option\n            (fun g : term =>\n             match p g s with\n             | Some Equivalent => Some false\n             | Some Less_than => Some false\n             | Some Greater_than => Some true\n             | Some Uncomparable => Some false\n             | None => None\n             end) lg) ls).\nrewrite H0 in H1.\ndestruct H1.\ndestruct H1.\nassert (H3:= @list_exists_option_is_sound term (fun g : term =>\n          match p g x with\n          | Some Equivalent => Some false\n          | Some Less_than => Some false\n          | Some Greater_than => Some true\n          | Some Uncomparable => Some false\n          | None => None\n          end) lg).\nrewrite H2 in H3.\ndestruct H3. \nexists x. split. trivial.\nsplit.\ndestruct H3.\nexists x0.\ncase_eq (p x0 x).\nintros. destruct c.\nrewrite H5 in H3.\ndestruct H3.\ndiscriminate. rewrite H5 in H3. destruct H3. discriminate.\nrewrite H5 in H3. destruct H3. discriminate.\nrewrite H5 in H3. destruct H3. discriminate.\nintros. rewrite H5 in H3. destruct H3. split. assumption. trivial.\nintros.\nassert (H4' := H4 t2).\nrewrite H6 in H4'.\napply H4'. trivial. trivial.\nQed.\n\nLemma list_gt_list_is_complete_true:\n  forall p lg ls, ( forall s, In s ls -> exists g, In g lg /\\ p g s = Some Greater_than) ->  list_gt_list p lg ls = Some true.\nProof.   \ninduction ls.\nintros.\ncompute.\ntrivial.\nintros.\nunfold list_gt_list.\napply list_forall_option_is_complete_true.\nintros.\napply list_exists_option_is_complete_true.\nassert (H1:= H a0).\nassert (exists g : term, In g lg /\\ p g a0 = Some Greater_than).\napply H1; trivial.\ndestruct H2.\ndestruct H2.\nexists x.\nsplit; trivial.\nrewrite H3.\ntrivial.\nQed.\n  \nLemma list_gt_list_is_complete_false: \n  forall p lg ls, (forall g s, In g lg -> In s ls -> p g s <> None) -> (exists s, In s ls /\\ forall g, In g lg -> (p  g s = Some Less_than \\/ p g s = Some Equivalent \\/ p g s = Some Uncomparable)) ->  list_gt_list p lg ls = Some false.\nProof.\ninduction ls.\nintros. \nsimpl in H.\ndestruct H0. destruct H0.\ncontradiction.\n\nintros.\nunfold list_gt_list.\napply list_forall_option_is_complete_false.\ndestruct H0.\nexists x.\ndestruct H0.\nsplit. trivial.\napply list_exists_option_is_complete_false.\nintros.\nassert (H3:= H1 a0).\nassert ( p a0 x = Some Less_than \\/\n       p a0 x = Some Equivalent \\/ p a0 x = Some Uncomparable).\napply H3; trivial.\ndestruct H4. \nrewrite H4. trivial.\ndestruct H4; rewrite H4; trivial.\nintros.\nassert (H3:= @list_exists_option_is_sound term (fun g : term =>\n          match p g a0 with\n          | Some Equivalent => Some false\n          | Some Less_than => Some false\n          | Some Greater_than => Some true\n          | Some Uncomparable => Some false\n          | None => None\n          end) lg).\nrewrite H2 in H3.\ndestruct H3.\ndestruct H3. destruct H3.\nassert (H4':= H4 x).\nassert (match p x a0 with\n        | Some Equivalent => Some false\n        | Some Less_than => Some false\n        | Some Greater_than => Some true\n        | Some Uncomparable => Some false\n        | None => None\n        end = Some true -> False).\napply H4'; trivial.\napply H6.\ncase_eq (p x a0).\nintros. destruct c.\nrewrite H7 in H5. discriminate.\nrewrite H7 in H5. discriminate.\ntrivial.\nrewrite H7 in H5. discriminate.\nintros.\nrewrite H7 in H5. \nassert (H8:= H x a0).\napply H8 in H7. contradiction.\ntrivial. trivial.\nQed.\n\nLemma list_gt_list_cons_right_true: forall p lg ls a, list_gt_list p lg (a::ls) = Some true -> list_gt_list p lg ls = Some true.\nProof.\nunfold list_gt_list.\nintros.\napply list_gt_list_is_complete_true.\nassert (H1:= @list_forall_option_is_sound term (fun s : term =>\n         list_exists_option\n           (fun g : term =>\n            match p g s with\n            | Some Equivalent => Some false\n            | Some Less_than => Some false\n            | Some Greater_than => Some true\n            | Some Uncomparable => Some false\n            | None => None\n            end) ( lg)) (a:: ls) ).\nrewrite H in H1. clear H.\nintros.\nassert (H1':= H1 s). clear H1.\nassert (list_exists_option\n          (fun g : term =>\n           match p g s with\n           | Some Equivalent => Some false\n           | Some Less_than => Some false\n           | Some Greater_than => Some true\n           | Some Uncomparable => Some false\n           | None => None\n           end) ( lg) = Some true).\napply H1'. simpl. right. trivial.\nassert (H0':= @list_exists_option_is_sound term (fun g : term =>\n          match p g s with\n          | Some Equivalent => Some false\n          | Some Less_than => Some false\n          | Some Greater_than => Some true\n          | Some Uncomparable => Some false\n          | None => None\n          end) (lg)).\nrewrite H0 in H0'. destruct H0'. destruct H1.\nexists x.\nsplit. trivial.\ncase_eq (p x s).\nintros. destruct c.\nrewrite H3 in H2. discriminate.\nrewrite H3 in H2. discriminate.\ntrivial.\nrewrite H3 in H2. discriminate.\nintros. rewrite H3 in H2. discriminate.\nQed.\n\nLemma list_gt_list_cons_right_true_1: forall p lg ls a, (exists a', In a' lg /\\ p a' a = Some Greater_than) -> list_gt_list p lg ls = Some true -> list_gt_list p lg (a :: ls) = Some true.\nProof.\nintros.\napply list_gt_list_is_complete_true.\nunfold list_gt_list in H0.\nintros.\nassert (H0':= @list_forall_option_is_sound term (fun s : term =>\n          list_exists_option\n            (fun g : term =>\n             match p g s with\n             | Some Equivalent => Some false\n             | Some Less_than => Some false\n             | Some Greater_than => Some true\n             | Some Uncomparable => Some false\n             | None => None\n             end) lg) ls).\nrewrite H0 in H0'.\nsimpl in H1.\ndestruct H1. clear H0.\nrewrite <- H1. clear H1 s.\nassumption.\nclear H0.\nassert (H0'':= H0' s).\nclear H0'. assert ( list_exists_option\n           (fun g : term =>\n            match p g s with\n            | Some Equivalent => Some false\n            | Some Less_than => Some false\n            | Some Greater_than => Some true\n            | Some Uncomparable => Some false\n            | None => None\n            end) lg = Some true).\napply H0''. trivial. clear H0''.\nassert (H2:= @list_exists_option_is_sound term (fun g : term =>\n          match p g s with\n          | Some Equivalent => Some false\n          | Some Less_than => Some false\n          | Some Greater_than => Some true\n          | Some Uncomparable => Some false\n          | None => None\n          end) lg ). \nrewrite H0 in H2.\ndestruct H2.\ndestruct H2.\nexists x.\nsplit. trivial.\ncase_eq (p x s).\nintros. destruct c.\nrewrite H4 in H3. discriminate.\nrewrite H4 in H3. discriminate.\ntrivial.\nrewrite H4 in H3. discriminate.\nintros. rewrite H4 in H3. discriminate.\nQed.\n\n\n   \nLemma  list_gt_list_cons_left_true: forall p lg ls a, list_gt_list p lg ls = Some true -> list_gt_list p (a::lg) ls = Some true.\nProof.\nunfold list_gt_list.\nintros.\napply list_gt_list_is_complete_true.\nassert (H1:= @list_forall_option_is_sound term (fun s : term =>\n         list_exists_option\n           (fun g : term =>\n            match p g s with\n            | Some Equivalent => Some false\n            | Some Less_than => Some false\n            | Some Greater_than => Some true\n            | Some Uncomparable => Some false\n            | None => None\n            end) lg) ls).\nrewrite H in H1. clear H.\nintros.\nassert (H1':= H1 s). clear H1.\nassert (list_exists_option\n          (fun g : term =>\n           match p g s with\n           | Some Equivalent => Some false\n           | Some Less_than => Some false\n           | Some Greater_than => Some true\n           | Some Uncomparable => Some false\n           | None => None\n           end) lg = Some true).\napply H1'; trivial. clear H1'.\nassert (H1:=@list_exists_option_is_sound term (fun g : term =>\n          match p g s with\n          | Some Equivalent => Some false\n          | Some Less_than => Some false\n          | Some Greater_than => Some true\n          | Some Uncomparable => Some false\n          | None => None\n          end) lg).\nrewrite H0 in H1. clear H0.\ndestruct H1. destruct H0.\nexists x. split.\nsimpl. right. trivial.\n\ncase_eq (p x s).\nintros. destruct c.\nrewrite H2 in H1. discriminate.\nrewrite H2 in H1. discriminate.\ntrivial.\nrewrite H2 in H1. discriminate.\nintros. rewrite H2 in H1. discriminate.\nQed.\n\n  \nLemma  list_gt_list_cons_left_true_1: forall p lg ls a, (forall a', In a' ls -> p a a' <> Some Greater_than) -> list_gt_list p (a::lg) ls = Some true -> list_gt_list p lg ls = Some true.\nProof.\nintros.\napply list_gt_list_is_complete_true.\nunfold list_gt_list in H0.\nintros.\nassert (H0':= @list_forall_option_is_sound term (fun s : term =>\n          list_exists_option\n            (fun g : term =>\n             match p g s with\n             | Some Equivalent => Some false\n             | Some Less_than => Some false\n             | Some Greater_than => Some true\n             | Some Uncomparable => Some false\n             | None => None\n             end) (a::lg)) ls).\nrewrite H0 in H0'.\nsimpl in H1.\nassert (H2:= H0' s).\n\nassert (list_exists_option\n         (fun g : term =>\n          match p g s with\n          | Some Equivalent => Some false\n          | Some Less_than => Some false\n          | Some Greater_than => Some true\n          | Some Uncomparable => Some false\n          | None => None\n          end) (a :: lg) = Some true).\napply H2; trivial. clear H0' H2 H0.\nassert (H4 := @list_exists_option_is_sound term (fun g : term =>\n          match p g s with\n          | Some Equivalent => Some false\n          | Some Less_than => Some false\n          | Some Greater_than => Some true\n          | Some Uncomparable => Some false\n          | None => None\n          end) (a :: lg)). \nrewrite H3 in H4. clear H3.\ndestruct H4. destruct H0.\nsimpl in H0. destruct H0.\nrewrite H0 in H.\nassert (H':= H s).\ncase_eq (p x s).\nintros. destruct c.\nrewrite H3 in H2. discriminate.\nrewrite H3 in H2. discriminate.\nrewrite H3 in H2. rewrite H3 in H'.\nassert (Some Greater_than <> Some Greater_than).\napply H'; trivial. contradict H4. trivial.\nrewrite H3 in H2. discriminate.\nintros. rewrite H3 in H2. discriminate.\nexists x.\nsplit.\ntrivial.\ncase_eq (p x s).\nintros. destruct c.\nrewrite H3 in H2. discriminate.\nrewrite H3 in H2. discriminate.\ntrivial.\nrewrite H3 in H2. discriminate.\nintros. rewrite H3 in H2. discriminate.\nQed. \n \nLemma mult_eval_greater_less: forall p lg ls, mult_eval p lg ls = Some Greater_than /\\ (list_gt_list p ls lg = Some false) -> mult_eval p ls lg = Some Less_than.\nProof.\nintros.  \nunfold mult_eval in H.\ncase_eq (list_gt_list p lg ls). intros. destruct b. rewrite H0 in H. \nunfold mult_eval. rewrite H0.\ndestruct H.\ncase_eq (list_gt_list p ls lg). destruct b.\nintros.\nrewrite H2 in H1. discriminate.\nintros. trivial.\nintros. rewrite H2 in H1. discriminate.\nrewrite H0 in H.\ndestruct H. rewrite H1 in H. discriminate.\ndestruct H.\nintros.\nrewrite H0 in H.\nrewrite H1 in H. discriminate.\nQed.\n \n\nLemma list_forall_option_is_complete_none :\n  forall (A : Set) f l, (exists a, In a l /\\ f a = None) ->\n    @list_forall_option A f l = None.\nProof.\nintros A0 f l; induction l as [ | a l].\nsimpl. intros. destruct H. destruct H. contradiction.\nintros.\nsimpl in H.\nassert ((exists a0, a = a0 /\\ f a0 = None) \\/ (exists a0, In a0 l /\\ f a0 = None)).\ndestruct H.\ndestruct H.\ndestruct H.\nleft.\nexists x.\nsplit; trivial.\nright. exists x.\nsplit;trivial.\ndestruct H0.\ndestruct H0.\ndestruct H0.\nsimpl.\nrewrite H0.\nrewrite H1. trivial.\n\nsimpl.\ncase_eq (f a).\nintros. destruct b.\napply IHl. assumption.\n\ncase_eq (list_forall_option f l). intros.\nassert (list_forall_option f l = None).\napply IHl. assumption.\nrewrite H2 in H3. discriminate.\nintros. trivial.\nintros. \ntrivial.\nQed.\n  \n \nLemma list_gt_list_is_complete_none_1: \n  forall p lg ls, list_gt_list p lg ls <> Some true -> list_gt_list p lg ls <> Some false ->  list_gt_list p lg ls =  None.\nProof.\nintros.\ncase_eq (list_gt_list p lg ls).\nintros.\ndestruct b.\ncontradict H.\ntrivial.\ncontradict H0.\ntrivial.\nintros.\ntrivial. \nQed.\n\nLemma list_gt_list_is_complete_none: \n  forall p lg ls, (exists t1: term, In t1 ls /\\ ((exists t2:term, In t2 lg /\\ p t2 t1 = None) /\\\n       (forall t2, In t2 lg -> p t2 t1 = Some Greater_than -> False)))  ->  list_gt_list p lg ls =  None.\nProof.\nintros.\nunfold list_gt_list.\napply list_forall_option_is_complete_none.\ndestruct H.\nexists x.\nsplit.\ndestruct H. trivial.\ndestruct H.\ndestruct H0.\ndestruct H0.\ndestruct H0.\napply list_exists_option_is_complete_none.\nexists x0.\nsplit. trivial.\nrewrite H2. trivial.\nintros.\nassert (H1':= H1 a).\napply H1'.\ntrivial.\ncase_eq (p a x).\nintros.\ndestruct c.\nrewrite H5 in H4. discriminate.\nrewrite H5 in H4. discriminate.\ntrivial.\nrewrite H5 in H4. discriminate.\nintros.\nrewrite H5 in H4. discriminate.\nQed. \n  \n  \nLemma forall_not :\n   forall (V: Set) (P : V -> Prop),  ~ (exists x : V, P x) -> forall x : V, ~ P x.\nProof.\nfirstorder.\nQed.\n \n\n\nLemma not_forall: forall (V:Set)(P : V -> Prop), (exists x : V,  ~ P x) -> ~ (forall x : V,  P x). \nProof.\nintros.\nunfold not.\nintros.\nfirstorder.\nQed.\n\nLemma exists_not_impl: forall l2 a1 l1 n rpo_infos, (exists x,  (In x l2) /\\\n      ~ (exists g : term,\n        In g (a1 :: l1) /\\ rpo_eval rpo_infos n g x = Some Greater_than))->(exists x : term,\n     ~\n     (In x l2 ->\n      exists g : term,\n        In g (a1 :: l1) /\\ rpo_eval rpo_infos n g x = Some Greater_than)).\nProof.\nfirstorder.\nQed.\n\nLemma exists_exists_not :  forall l2 a1 l1 n rpo_infos, \n  (exists x,  (In x l2) /\\\n      (forall g : term,\n       ~ In g (a1 :: l1) \\/ rpo_eval rpo_infos n g x <> Some Greater_than)) ->\n  (exists x,  (In x l2) /\\\n      ~ (exists g : term,\n        In g (a1 :: l1) /\\ rpo_eval rpo_infos n g x = Some Greater_than)).\nProof.\nfirstorder.\nQed.\n \n \nLemma list_gt_list_cons_commute_right_true:  forall  p l1 l2 a1 a2, list_gt_list p l2 (a1:: a2 :: l1) = Some true -> list_gt_list p l2 (a2 :: a1 :: l1)  = Some true.\nProof.\nintros.\napply list_gt_list_is_complete_true.\nassert (H1':= @list_gt_list_is_sound_true p  l2 (a1 :: a2 :: l1)).\nassert (forall s : term,\n        In s (a1 :: a2 :: l1) ->\n        exists g : term, In g l2 /\\ p g s = Some Greater_than).\napply H1'; trivial.\nintros.\nassert (H0':= H0 s).\napply H0'.\nsimpl.\nsimpl in H1.\ntauto.\nQed.\n \n \n\nTheorem antisym_rpo: forall rpo_infos n a b, size a + size b <= n -> (rpo rpo_infos.(bb) a b) /\\ (rpo rpo_infos.(bb) b a) -> False.\nProof.\nintros.\ndestruct H0. \nassert (H2:= rpo_eval_is_complete_less_greater).\nassert (H3:= H2 rpo_infos n a b).\nassert (H4:= H2 rpo_infos n b a).\nassert (size b + size a <= n).\nlia.\nassert (rpo_eval rpo_infos n a b = Some Less_than\n           /\\ rpo_eval rpo_infos n b a =\n             Some Greater_than).\napply H3; trivial.\nassert (rpo_eval rpo_infos n b a = Some Less_than\n           /\\ rpo_eval rpo_infos n a b =\n             Some Greater_than).\napply H4; trivial.\ndestruct H6.\ndestruct H7.\nrewrite H6 in H9.\ncontradict H9.\ndiscriminate.\nQed.\n\nLemma mem_concat: forall a ls lc, mem equiv a (ls ++ lc) -> mem equiv a ls \\/ mem equiv a lc.\nProof. \ninduction ls.\nsimpl.\nintros.\nright; trivial.\nintros.\nsimpl.\nsimpl in H.\ndestruct H.\nleft; left; trivial.\nassert (H1:= IHls lc).\nassert (mem equiv a ls \\/ mem equiv a lc).\napply H1; trivial.\ntauto.\nQed.\n\nLemma mem_concat_1: forall a ls lc, mem equiv a ls -> mem equiv a (ls ++ lc).\nProof.\ninduction ls.\nintros.\nsimpl in H.\ncontradiction.\nintros.\nsimpl. simpl in H.\ndestruct H.\nleft; trivial.\nassert (H0:= IHls lc).\nright.\napply H0; trivial.\nQed.\n \nEnd S.\n\nEnd Make.\n \n(* \n*** Local Variables: ***\n*** coq-prog-name: \"coqtop\" ***\n*** coq-prog-args: (\"-emacs-U\" \"-I\" \"../basis/\" \"-I\" \"../list_extensions/\" \"-I\" \"../term_algebra/\") ***\n*** End: ***\n *)\n \n\n", "meta": {"author": "sorinica", "repo": "spike-prover", "sha": "f2d6dd0bcebb647e09dd23048753075551da27eb", "save_path": "github-repos/coq/sorinica-spike-prover", "path": "github-repos/coq/sorinica-spike-prover/spike-prover-f2d6dd0bcebb647e09dd23048753075551da27eb/Coccinelle/Coq8.15/rpo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6503073200198165}}
{"text": "From Coq Require Import Lia Omega Program.\n\nFrom Rattus Require Export Substitutions.\nFrom Rattus Require Import Tactics.\n\nOpen Scope nat.\n\n(* This module\n\n   - gives the definition of closed terms,a\n\n   - show that for closed u and \\gamma, we have that \n\n        (t \\gamma)[u/x] = t (\\gamma[x \\mapsto u]) \n\n   - shows that t [u/x] is closed if (abs t) and u are\n*)\n\n\n(* fvars b t indicates that t only contains free variables i with i < b *)\n\nInductive fvars : index -> term -> Prop :=\n| fvars_var b i : i < b -> fvars b (var i)\n| fvars_unit b : fvars b unit\n| fvars_natlit b n : fvars b (natlit n)\n| fvars_add b t1 t2 : fvars b t1 -> fvars b t2 -> fvars b (add t1 t2)                           \n| fvars_abs b t : fvars (S b) t -> fvars b (abs t)\n| fvars_letin b t1 t2 : fvars b t1 ->fvars (S b) t2 -> fvars b (letin t1 t2)                                         \n| fvars_app b t1 t2 : fvars b t1 -> fvars b t2 -> fvars b (app t1 t2)\n| fvars_pair b t1 t2 : fvars b t1 -> fvars b t2 -> fvars b (pair t1 t2)\n| fvars_pr1 b t : fvars b t -> fvars b (pr1 t)\n| fvars_pr2 b t : fvars b t -> fvars b (pr2 t)\n| fvars_in1 b t : fvars b t -> fvars b (in1 t)\n| fvars_in2 b t : fvars b t -> fvars b (in2 t)\n| fvars_case b t t1 t2 : fvars b t ->  fvars (S b) t1 -> fvars (S b) t2 -> fvars b (case t t1 t2)\n| fvars_delay b t : fvars b t -> fvars b (delay t)\n| fvars_adv b t : fvars b t -> fvars b(adv t)\n| fvars_ref b l : fvars b (ref l)\n| fvars_box b t : fvars b t -> fvars b (box t)\n| fvars_unbox b t : fvars b t -> fvars b (unbox t)\n| fvars_into b t : fvars b t -> fvars b (into t)\n| fvars_out b t : fvars b t -> fvars b (out t)\n| fvars_fixp b t : fvars (S b) t -> fvars b (fixp t).\n\n#[global] Hint Constructors fvars : core.\n\nNotation closed_term := (fvars 0).\n\nInductive fvar_sub_none : index -> sub -> Prop :=\n| fvar_sub_none_0 g : fvar_sub_none 0 g\n| fvar_sub_none_succ i g : fvar_sub_none i g -> fvar_sub_none (S i) (None :: g).\n\n#[global] Hint Constructors fvar_sub_none : core.\n\n  \n\nLemma fvar_var_id i : forall b g, fvar_sub_none b g -> i < b -> sub_lookup g i = None.\nProof.\n  induction i;intros.\n  - inversion H;subst. inversion H0. auto.\n  - simpl. inversion H. subst. inversion H0. eapply IHi. eassumption. lia.\nQed.\n\n\n\nLemma sub_id i g t : fvar_sub_none i g -> fvars i t -> sub_app g t = t.\nProof.\n  intros N F. generalize dependent g. \n  induction F;intros;\n    try solve[simpl;try first[reflexivity| erewrite IHF;eauto| erewrite IHF1,IHF2;eauto]].\n  - simpl. erewrite fvar_var_id; eauto.\n  - simpl. erewrite IHF1,IHF2,IHF3;eauto.\nQed.\n\n(* Substitution application is the identity on closed terms *)\n\nLemma sub_closed_id g t : closed_term t -> sub_app g t = t.\nProof.\n  intros C. destruct g. erewrite sub_id;eauto.\n  eapply sub_id. apply fvar_sub_none_0. assumption.\nQed. \n      \n  \nInductive closed_sub : sub -> Prop :=\n| closed_sub_nil : closed_sub nil\n| closed_sub_some t g : closed_term t -> closed_sub g -> closed_sub (Some t :: g)\n| closed_sub_none g : closed_sub g -> closed_sub (None :: g).\n\n\n  \n(* merge two non-overlapping substitutions *)\nInductive merge_sub : sub -> sub -> sub -> Prop :=\n| merge_sub_nil_left g : merge_sub nil g g\n| merge_sub_nil_right g : merge_sub g nil g\n| merge_sub_none g g1 g2 : merge_sub g1 g2 g -> merge_sub (None :: g1) (None :: g2) (None :: g)\n| merge_sub_left g g1 g2 t :  merge_sub g1 g2 g -> merge_sub (Some t :: g1) (None :: g2) (Some t :: g)\n| merge_sub_right g g1 g2 t : merge_sub g1 g2 g -> merge_sub (None :: g1) (Some t :: g2) (Some t :: g).\n\n#[global] Hint Constructors merge_sub closed_sub : core.\n\nLemma closed_sub_term t g : closed_sub (Some t :: g) -> closed_term t.\nProof.\n  intros C. inversion C. subst. assumption.\nQed.\n\nLemma merge_sub_var1 i g1 g2 g : merge_sub g1 g2 g -> sub_lookup g1 i = None ->\n                                  exists t, sub_lookup g2 i = t /\\ sub_lookup g i = t.\nProof.\n  generalize dependent g1; generalize dependent g2; generalize dependent g.\n  induction i;intros.\n  - destruct H; eauto.\n  - destruct H;eauto; simpl in H0; inversion H0;\n      pose (IHi g g2 g1 H H0) as IH;eauto.\nQed.\n\nLemma sub_lookup_succ x g i : sub_lookup (x :: g) (S i) = sub_lookup g i .\nProof.\n  unfold sub_lookup. auto.\nQed.\n\nLemma merge_sub_var2 i g1 g2 g t : merge_sub g1 g2 g -> sub_lookup g1 i = Some t ->\n                                   sub_lookup g2 i = None /\\ sub_lookup g i = Some t.\nProof.\n  split; generalize dependent g1; generalize dependent g2; generalize dependent g.\n  - induction i;intros.\n    + destruct H;eauto; simpl in H0; inversion H0.\n    + destruct H;eauto; simpl in H0; inversion H0;simpl;rewrite sub_lookup_succ; erewrite IHi;eauto.\n  - induction i;intros.\n    + destruct H;eauto; simpl in H0; inversion H0.\n    + destruct H;eauto; simpl in H0; inversion H0;simpl;rewrite sub_lookup_succ; erewrite IHi;eauto.\nQed.\n  \n\n\nLemma sub_lookup_closed g i t : closed_sub g -> sub_lookup g i = Some t -> closed_term t.\nProof.\n  generalize dependent g. induction i;intros.\n  - unfold sub_lookup in *. destruct g; simpl in H0; try destruct o; inversion H0; subst. eauto using closed_sub_term.\n  - dependent destruction H; subst; simpl in H0. inversion H0. inversion H1. eauto. eauto.\nQed.\n\n\n\nLemma merge_sub_app t : forall g1 g2 g , closed_sub g1 -> merge_sub g1 g2 g -> sub_app g2 (sub_app g1 t) = sub_app g t.\nProof.\n  induction t;intros;try solve[auto|simpl; erewrite IHt;eauto|simpl;erewrite IHt1, IHt2;eauto].\n  - simpl. remember (sub_lookup g1 i) as r1.\n    symmetry in Heqr1. destruct r1. \n    + remember (merge_sub_var2 i g1 g2 g t H0 Heqr1) as M. destruct M. erewrite e0.\n      eauto using sub_closed_id, sub_lookup_closed.\n    + remember (merge_sub_var1 i g1 g2 g H0 Heqr1) as M. destruct M as [t M].\n      destruct M as [M1 M2]. simpl. rewrite M1, M2. reflexivity.\n  - simpl;erewrite IHt1, IHt2, IHt3;eauto.\nQed.\n\n(* \nThe lemma below proves that\n(t \\gamma)[u/x] = t (\\gamma[x \\mapsto u])\n*)\n\nLemma sub_term_merge g t u :\n  closed_sub g -> sub_term (sub_app (None :: g) t) u = sub_app (Some u :: g) t.\nProof.\n  intros C. unfold sub_term. apply merge_sub_app; eauto.\nQed.\n\n\nLemma fvars_up i j t : i <= j -> fvars i t -> fvars j t.\nProof.\n  intros I F. generalize dependent j. induction F;intros j;eauto.\n  - constructor. lia.\n  - constructor. apply IHF. lia.\n  - constructor. apply IHF1. lia. apply IHF2. lia.\n  - constructor. apply IHF1. lia. apply IHF2. lia. apply IHF3. lia.\n  - constructor. apply IHF. lia.\nQed.\n\n\n\nLemma closed_fvars i t : closed_term t -> fvars i t.\nProof.\n  intros C. eapply fvars_up in C.\n  eassumption. lia.\nQed.\n\n\n(* Below we prove that applying a substitution with n closed terms to\n   a term with n free variables (fvar n t) results in a closed term.\n   *)\n\n(* full_sub l s g indicates that g has mappings for variables i with l\n<= i < l + s. *)\n\nInductive full_sub : index -> index -> sub -> Prop :=\n| full_sub_empty : full_sub 0 0 nil\n| full_sub_var_0 g t s :\n    full_sub 0 s g -> full_sub 0 (S s) (Some t :: g)\n| full_sub_skip l s g x :\n    full_sub l s g -> full_sub (S l) s  (x :: g).\n\n(* bvars l s b t indicates that t only contains free variables i with\n i < b or with l <= i < l + s *)\n\nInductive bvars : index -> index -> index -> term -> Prop :=\n| bvars_var_between l s b i : l <= i < l + s -> bvars l s b (var i)\n| bvars_var_below l s b i : i < b -> bvars l s b (var i)\n| bvars_unit l s b : bvars l s b unit\n| bvars_natlit l b s n : bvars l s b (natlit n)\n| bvars_add l s b t1 t2 : bvars l s b t1 -> bvars l s b t2 -> bvars l s b (add t1 t2)\n| bvars_abs l s b t : bvars (S l) s (S b) t -> bvars l s b (abs t)\n| bvars_letin l s b t1 t2 : bvars l s b t1 -> bvars (S l) s (S b) t2 -> bvars l s b (letin t1 t2)\n| bvars_app l s b t1 t2 : bvars l s b t1 -> bvars l s b t2 -> bvars l s b (app t1 t2)\n| bvars_pair l s b t1 t2 : bvars l s b t1 -> bvars l s b t2 -> bvars l s b (pair t1 t2)\n| bvars_pr1 l b s t : bvars l s b t -> bvars l s b (pr1 t)\n| bvars_pr2 l s b t : bvars l s b t -> bvars l s b (pr2 t)\n| bvars_in1 l s b t : bvars l s b t -> bvars l s b (in1 t)\n| bvars_in2 l s b t : bvars l s b t -> bvars l s b (in2 t)\n| bvars_case l s b t t1 t2 : bvars l s b t ->  bvars (S l) s (S b) t1 -> bvars (S l) s (S b) t2 -> bvars l s b (case t t1 t2)\n| bvars_delay l s b t : bvars l s b t -> bvars l s b (delay t)\n| bvars_adv l s b t : bvars l s b t -> bvars l s b (adv t)\n| bvars_ref l s b l' : bvars l s b (ref l')\n| bvars_box l s b t : bvars l s b t -> bvars l s b (box t)\n| bvars_unbox l s b t : bvars l s b t -> bvars l s b (unbox t)\n| bvars_into l s b t : bvars l s b t -> bvars l s b (into t)\n| bvars_out l s b t : bvars l s b t -> bvars l s b (out t)\n| bvars_fixp l s b t : bvars (S l) s (S b) t -> bvars l s b (fixp t).\n\n#[global] Hint Constructors full_sub bvars : core.\n\n\nLemma full_sub_nth s i l g :\n  full_sub l s g -> i < l \\/ l + s <= i  \\/ exists t, sub_lookup g i = Some t.\nProof.\n  intros F. generalize dependent i. induction F;intros.\n  - right. left. lia.\n  - destruct i.\n    + right. right. exists t. cbv. reflexivity.\n    + pose (IHF i). autodest. inversion H.\n      right. left. lia.\n  - destruct i.\n    + left. lia.\n    + pose (IHF i). autodest. left. lia. right. left. lia.\nQed.\n\n\nLemma full_sub_bvars l s b t g : closed_sub g -> bvars l s b t -> full_sub l s g -> fvars b (sub_app g t).\nProof.\n  intros C B F. generalize dependent g.\n  induction B;intros;simpl;eauto 10.\n  - apply full_sub_nth with (i := i) in F.\n    destruct F as [F | [F|(t & F)]];try lia.\n    rewrite F. eauto using sub_lookup_closed, closed_fvars.\n  - remember (sub_lookup g i) as N. destruct N.\n    eauto using sub_lookup_closed, closed_fvars. eauto.\nQed.\n\n\nLemma fvars_bvars l b s t : fvars b t -> bvars l s b t.\nProof.\n  intros F. generalize dependent l. induction F;eauto.\nQed.\n\n\nLemma fvars_bvars' l s t b : b = l + s -> fvars b t -> bvars l s l t.\nProof.\n  intros E F. generalize dependent l. induction F;intros;eauto.\n  - pose (dec_le l i) as L. destruct L.\n    + apply bvars_var_between. lia.\n    + apply bvars_var_below. lia.\n  - constructor. apply IHF. lia.\n  - constructor. apply IHF1. auto. apply IHF2. lia. \n  - constructor. apply IHF1. auto. apply IHF2. lia. apply IHF3. lia.\n  - constructor. apply IHF. lia.\nQed.\n\n\nLemma full_sub_fvars b t g : closed_sub g -> fvars b t -> full_sub 0 b g -> closed_term (sub_app g t).\nProof.\n  intros C B F. eapply fvars_bvars' in B. eapply full_sub_bvars;eauto. auto.\nQed.\n\n\nLemma sub_term_closed t u : fvars 1 t -> closed_term u -> closed_term (sub_term t u).\nProof.\n  intros F C. eapply full_sub_fvars; eauto.\nQed.\n\n", "meta": {"author": "pa-ba", "repo": "Rattus-coq", "sha": "4c983c75ffb7c28098298c60466008f03a6a1517", "save_path": "github-repos/coq/pa-ba-Rattus-coq", "path": "github-repos/coq/pa-ba-Rattus-coq/Rattus-coq-4c983c75ffb7c28098298c60466008f03a6a1517/theories/ClosedTerms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.650262292068154}}
{"text": "(*\n  Translating https://bentnib.org/unembedding.html in Coq. With some care for the partial bits.\n*)\n(* Required opam packages: coq-stdpp and coq-autosubst. *)\nFrom Coq.Program Require Import Program.\nFrom Coq Require Import ssr.ssreflect Lia.\nFrom stdpp Require Import base tactics.\nFrom Autosubst Require Import Autosubst.\n\nSet Primitive Projections.\nUnset Program Cases.\n\nInductive DBTerm :=\n| Var (n : nat)\n| Lam (b : DBTerm)\n| App (f : DBTerm) (a : DBTerm).\n\nDefinition Env t := var → t.\n(* Equals Env DBTerm, but that's accidental. *)\nDefinition DB := var → DBTerm.\n\n(* We reuse a tiny bit of Autosubst here. *)\nInstance idsDBT: Ids DBTerm := Var.\n\nInstance idsDB: Ids DB := λ x, (* [x]: input to the substitution. *)\n  (* Resulting [DB] term. *)\n  λ i, Var (x + i).\n\nDefinition hLam (f : DB → DB) : DB := λ i,\n  let i' := S i in\n  let v := λ j, Var (j - i') in\n  Lam (f v i').\n\nDefinition lift2 (con : DBTerm → DBTerm → DBTerm) : DB → DB → DB := λ a1 a2 i,\n  con (a1 i) (a2 i).\n\n(* Inline [lift2] to avoid complicating proofs. *)\nDefinition hApp := Eval cbv in lift2 App.\nDefinition hApp' (f a : DB) : DB := λ i, App (f i) (a i).\nGoal hApp = hApp'. done. Qed.\n\nModule UnembeddingGeneral.\n\nClass UntypedLambda (exp : Type) := {\n  lam : (exp → exp) → exp;\n  app : exp → exp → exp;\n}.\nDefinition Hoas := ∀ exp, UntypedLambda exp → exp.\nExample ex1 : Hoas := λ exp hU,\n  lam (λ x, lam (λ y, app x y)).\nExample ex1DB : DBTerm := Lam (Lam (App (Var 1) (Var 0))).\n\nDefinition numeral (n : nat): Hoas := λ exp hU,\n  let body := fix body s z n :=\n    match n with\n    | 0 => z\n    | S n => app s (body s z n)\n    end\n  in lam (λ s, lam (λ z, body s z n)).\n\nInstance untypedSize : UntypedLambda nat := {\n  lam f := S (f 1);\n  app x y := S (x + y);\n}.\nDefinition size (t : Hoas) : nat := t nat untypedSize.\n\n(* i and j are de Bruijn levels! *)\nInstance untypedDB : UntypedLambda DB := {\n  lam := hLam;\n  app := hApp;\n}.\n\nDefinition toTerm (t : Hoas) : DBTerm :=\n  t _ untypedDB 0.\nGoal toTerm ex1 = ex1DB. done. Qed.\n\n(* Now we're getting to the real deal. *)\n(* Type of open Hoas terms.\nThe paper uses finite environments ([list exp]), but the resulting code is potentially partial *and* uses infinite lists.\nSince we can't tolerate partiality, we follow the alternative design the authors suggest, and use infinite substitutions. *)\nDefinition Hoas' :=\n  ∀ exp, UntypedLambda exp → (var → exp) → exp.\nDefinition ex1' : Hoas' := λ exp hU s, ex1 exp hU.\n\nDefinition toTerm' (t : Hoas') : DBTerm :=\n  t _ untypedDB ids 0.\n\nDefinition testToTerm'Ex1' := toTerm' ex1'.\nGoal testToTerm'Ex1' = ex1DB. done. Qed.\n\nProgram Definition fromTermGo `{UntypedLambda exp} : DBTerm → (var → exp) → exp := fix F t env :=\n  match t with\n  | Var i => env i\n  | App f a => app (F f env) (F a env)\n  | Lam t => lam (λ x, F t (x .: env))\n  end.\n\n(* Simply rearrange parameters of [fromTermGo]. *)\nDefinition fromTerm' (t : DBTerm) : Hoas' :=\n  λ exp hU, fromTermGo t.\n\nEval cbv in fromTerm' testToTerm'Ex1'.\nExample roundTripEx1 : ex1' = fromTerm' testToTerm'Ex1'. done. Qed.\n\nDefinition isUnshiftP i s := ∀ m n, s m n = Var (m + n - i).\nLemma matching s1 s2 i1 i2\n  (Hu1: isUnshiftP i1 s1) (Hu2 : isUnshiftP i2 s2) n:\n  s1 n i1 = s2 n i2.\nProof. by rewrite Hu1 Hu2 !PeanoNat.Nat.add_sub. Qed.\n\nLemma fromTermGo_respects_unshifts t s1 s2 i1 i2\n  (Hu1: isUnshiftP i1 s1) (Hu2 : isUnshiftP i2 s2):\n  fromTermGo t s1 i1 = fromTermGo t s2 i2.\nProof.\n  elim: t s1 s2 i1 i2 Hu1 Hu2 => /= [n | b IHb |f ? a ?] s1 s2 i1 i2 Hu1 Hu2;\n    first exact: matching; lazy [hLam hApp]; f_equal; [| by eauto 2 ..].\n  apply IHb => ??; rewrite /scons; case_match; subst => //=.\nQed.\n\nLemma fromTermGo_respects_unshift1 t :\n  fromTermGo t ((λ j : nat, Var (j - 1)) .: ids) 1 = fromTermGo t ids 0.\nProof.\n  apply fromTermGo_respects_unshifts => m n;\n    rewrite /ids /idsDB /scons //; try (case_match; subst);\n    rewrite /= ?PeanoNat.Nat.sub_0_r //.\n    (* rewrite ?(plusnO, plusnS, PeanoNat.Nat.sub_0_r) //. *)\nQed.\n\nLemma fromTermGoId t : fromTermGo t ids 0 = t.\nProof.\n  elim: t => /= [^~t]; lazy [hLam hApp]; f_equal => //.\n  - (* lazy [ids idsDB]. *)\n    by rewrite -[in Var _](plusnO nt).\n  - by rewrite fromTermGo_respects_unshift1.\nQed.\n\nLemma roundTrip (t : DBTerm) : toTerm' (fromTerm' t) = t.\nProof. rewrite /toTerm' /fromTerm'. apply fromTermGoId. Qed.\n\nEnd UnembeddingGeneral.\n\nModule specialized.\n\nDefinition Hoas := Env DB → DB.\nGoal Hoas = ((var → var → DBTerm) → var → DBTerm). done. Qed.\n\nDefinition hoasToDB (t : Hoas): DBTerm := t ids 0.\n\n(* To produce Hoas terms, we must adapt/specialize this. *)\n(* Program Definition fromTermGo `{UntypedLambda exp} : DBTerm → (var → exp) → exp := fix F t env :=\n  match t with\n  | Var i => env i\n  | App f a => app (F f env) (F a env)\n  | Lam t => lam (λ x, F t (x .: env))\n  end. *)\nDefinition hhVar i : Hoas := λ env, env i.\nDefinition hhApp (f a : Hoas) : Hoas := λ env, hApp (f env) (a env).\n(* This starts from a de Bruijn representation. *)\n(* Definition hhLam (b : Hoas) : Hoas := λ env, hLam (λ x, b (x .: env)). *)\nDefinition hhLam (b : DB → Hoas) : Hoas := λ env, hLam (λ x, b x (x .: env)).\n(* Hm, not sure this is a good idea. *)\n\nEnd specialized.\n\n\n(* Definition validSubst (s : var → DB) := ∀ i j, s i j = s (i + j) 0.\nDefinition isUnshift i s := ∀ n, s n 0 = Var (n - i).\n\nLemma wanted t s1 s2 i1 i2\n  (* (Hs: ∀ j, s1 (j + i1) = s2 (j + i2)): *)\n  (Hs : ∀ n, s1 n i1 = s2 n i2)\n  (Hs1 : validSubst s1) (Hs2: validSubst s2)\n  (Hu1: isUnshift i1 s1) (Hu2 : isUnshift i2 s2):\n  fromTermGo t s1 i1 = fromTermGo t s2 i2.\nProof.\n  revert s1 s2 i1 i2 Hs Hs1 Hs2 Hu1 Hu2.\n  induction t; simpl; intros.\n  apply Hs.\n  all: f_equal => //.\n  all: eauto 2.\n  apply IHt.\n  intros.\n  rewrite /scons. case: n => [//|n].\n  { f_equal; lia. }\n  { have := Hs (S n).\n  rewrite Hs1 Hs2 /= => ?.\n  by rewrite Hs1 Hs2 !plusnS.\n  }\n  1-2: intros ??; asimpl; rewrite /scons; repeat case_match; simplify_eq/= => //.\n  all: intros ?; asimpl; rewrite /scons; repeat case_match; simplify_eq/= => //.\nQed.\n  (* - case: n => [//|n /=].\n    cbv. by rewrite -/plus plusnS.\n  - f_equal. apply wanted => j. autosubst. *)\n\nLemma go2 t : fromTermGo t ((λ j : nat, Var (j - 1)) .: ids) 1 = fromTermGo t ids 0.\nProof.\n  apply wanted; repeat intro; asimpl;\n    rewrite /ids /idsDB /scons;\n    repeat case_match; simplify_eq/=;\n    rewrite ?(plusnO, plusnS, PeanoNat.Nat.sub_0_r) //.\nQed.\n\n(* Search _ (?n - 0 = ?n).\n  {\n  rewrite /scons. case: j => [//|n].\n    lazy. by rewrite -/plus plusnS.\n  }\n    lazy. rewrite -/plus -/minus.\n    4: lazy; rewrite -/plus -/minus; f_equal; lia.\n  (* induction t; simpl; last by f_equal.\n  - case: n => [//|n /=].\n    cbv. by rewrite -/plus plusnS.\n  - f_equal. apply wanted => j. autosubst. *)\nQed. *)\n\nLemma fromTermGoId t : fromTermGo t ids 0 = t.\nProof.\n  induction t; simpl; cbn; f_equal => //.\n  - lazy; f_equal; rewrite -/plus. apply plusnO.\n  - f_equal. rewrite -{2}IHt.\n  apply go2.\n    (* apply wanted => j. autosubst. *)\n(*\n  apply (wanted t _ ids _ 0).  intros. autosubst.\n    (* fromTermGo t ((λ j : nat, Var (j - 1)) .: ids) 1 = t *)\n    by rewrite go2. *)\nQed.\n\nLemma roundTrip (t : DBTerm) : toTerm' (fromTerm' t) = t.\nProof. rewrite /toTerm' /fromTerm'. apply fromTermGoId. Qed. *)\n", "meta": {"author": "Blaisorblade", "repo": "Coq-playground", "sha": "add7e5b75cfc127b7a76012325a68ddfd9dc463e", "save_path": "github-repos/coq/Blaisorblade-Coq-playground", "path": "github-repos/coq/Blaisorblade-Coq-playground/Coq-playground-add7e5b75cfc127b7a76012325a68ddfd9dc463e/theories/unembedding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.6502622823040467}}
{"text": "(** * MoreFP: Advanced Functional Programming *)\n\n(** We will introduce (using example):\n\n    1) Type classes\n\n    2) Monads\n\n    We use Coq as a functional programming language.\n*)\n\n\n\n(** Slides are based on:\n\n    - Chapter from volume 4 of Software Foundations (QuickChick) by \n      Leonidas Lampropoulos and Benjamin C. Pierce.\n    - Slides by Nadia Polikarpova (Programming Languages in Haskell)\n*)\n\nFrom Coq Require Import Bool.Bool.\nFrom Coq Require Import Strings.String.\nFrom Coq Require Import Arith.Arith.\nFrom Coq Require Import List. \nImport ListNotations.\nLocal Open Scope string.\nFrom Coq Require Import Recdef.\n\nSection Monads.\n\n(* ################################################################# *)\n(** * Typeclasses *)\n\n(** Suppose we need string converters for lots of data structures.\n\n    We can build a small library of primitives\n\n       showBool : bool -> string\n       showNat : nat -> string\n\n    and combinators for structured types:\n\n     showList : {A : Type}\n                (A -> string) -> (list A) -> string\n     showPair : {A B : Type}\n                (A -> string) -> (B -> string) -> A * B -> string\n\n    Then we can build string converters for more\n    complex structured types by assembling them from these pieces:\n\n     showListOfPairsOfNats = showList (showPair showNat showNat)\n*)\n\n(** This works, but it's clunky.\n      - Requires making up names for all these string converters,\n        when it seems they could be generated automatically.\n      - Moreover, even the _definitions_ of converters like\n        [showListOfPairsOfNats] seem pretty mechanical, given their\n        types.\n\n    Solution: _Typeclasses_.\n      - Based on Haskell\n      - This is not \"classes\" as in object-oriented programming.\n *)\n\n(* ================================================================= *)\n(** ** Classes and Instances *)\n\n(** To automate converting various kinds of data into strings, we\n    begin by defining a typeclass called [Show]. *)\n\nClass Show (A : Type) :=\n  {\n    show : A -> string\n  }.\n\n(** A class definition defines an interface for some type.\n\n   We say that types [A] that implement the [Show] interface have\n   a method named show that will convert them to a string.\n\n   So we can use the generic method [show] on any type [A] that is\n   an instance of the [Show] class. \n\n   In general, you can have multiple things in the interface.\n*)\n\n(** The [Show] typeclass can be thought of as \"classifying\" types\n    whose values can be converted to strings -- that is, types [A]\n    such that we can define a function [show] of type [A -> string].\n\n    We can declare that [bool] is such a type by giving an [Instance]\n    declaration that witnesses this function: *)\n\nInstance showBool : Show bool :=\n  {\n    show := fun b:bool => if b then \"אמת\" else \"שקר\"\n  }.\n\nCompute show true.\n(* ==> \"אמת\" : string\n\n    Other types can similarly be equipped with [Show] instances --\n    including, of course, new types that we define. *)\n\nInductive primary := Red | Green | Blue.\n\nInstance showPrimary : Show primary :=\n  {\n    show :=\n      fun c:primary =>\n        match c with\n        | Red => \"Red\"\n        | Green => \"Green\"\n        | Blue => \"Blue\"\n        end\n  }.\n\nCompute show Green.\n(* ==> \"Green\" : string *)\n\n(** Importantly, we still have the ability to show booleans. *)\n\nCompute show true.\n(* ==> \"אמת\" : string\n\n    The [show] function is sometimes said to be _overloaded_, since it\n    can be applied to arguments of many types, with potentially\n    radically different behavior depending on the type of its\n    argument.\n    This is _not_ parametric polymorphism. *)\n\n(* ================================================================= *)\n(** **   [show] for nat *)\nCompute show 3.\n(* This doesn't work because we haven't said how to show a nat. *)\n\n(** Let's define nat as an instance of Show. *)\n\n(** We first need\n   some helper functions to convert nats to strings. *)\n\nDefinition num2string (d : nat) : string := \n  match d with \n    | 0 => \"0\"  | 1 => \"1\"  | 2 => \"2\"  | 3 => \"3\"\n    | 4 => \"4\"  | 5 => \"5\"  | 6 => \"6\"  | 7 => \"7\"\n    | 8 => \"8\"  | 9 => \"9\"  | 10 => \"A\" | 11 => \"B\"\n    | 12 => \"C\" | 13 => \"D\" | 14 => \"E\" | 15 => \"F\"\n    | _ => \"ERROR\"\n  end.\n\n(** Now, [string_of_nat] is defined as follows. *)\n\nFail Fixpoint string_of_nat_aux (n : nat) (acc : string) : string :=\n  let acc' := num2string (n mod 16) ++ acc in\n    match n / 16 with\n      | 0 => acc'\n      | n' => string_of_nat_aux n' acc'\n    end.\n\n(* Cannot guess decreasing argument of fix. *)\n\n(** To convince Coq that [string_of_nat_aux] terminates\n   we give it fuel.  *)\n\nFixpoint string_of_nat_aux \n  (fuel n : nat) (acc : string) : string :=\n  match fuel with\n    | 0 => \"ERROR\"\n    | S fuel' =>\n        let acc' := num2string (n mod 16) ++ acc in\n          match n / 16 with\n            | 0 => acc'\n            | n' => string_of_nat_aux fuel' n' acc'\n          end\n  end.\n\n(** It's sufficient to use [S n] as the fuel here since\n   we know we won't need to divide [n] by [16] more than\n   [S n] times.  We could of course use something like\n   [log_16 n], but there's no need to bother here. *)\n\nDefinition string_of_nat (n : nat) : string :=\n  string_of_nat_aux (S n) n \"\".\n\n(** Coq also has a mechanism to allow a definition without fuel. *)\n\nFunction digits_no_fuel (n : nat) (acc : string) \n  {measure (fun x : nat => x) n} :=\n  let acc' := num2string (n mod 16) ++ acc in\n  match n with\n    | 0 => acc'\n    | _ => match n / 16 with\n           | 0 => acc'\n           | n' => digits_no_fuel n' acc'\n         end\n  end.\nProof.\n  intros. rewrite <- teq0.\n  apply Nat.div_lt.\n  - apply Nat.lt_0_succ.\n  - apply Nat.leb_le. reflexivity.\nDefined.\n\nDefinition string_of_nat_no_fuel (n : nat) : string :=\n  digits_no_fuel n \"\".\n\n(** Now we can define our [nat] instance for the Show class. *)\n\nInstance showNat : Show nat :=\n  {\n    show := string_of_nat\n  }.\n\nCompute show 0.\n(* ==> \"0\" : string *)\n\nCompute show 100.\n(* ==> \"64\" : string *)\n\nCompute show (S (S 0)).\n(* ==> \"2\" : string *)\n\nCompute show (7 + 4 + 18).\n(* ==> \"1D\" : string *)\n\n(** Parameterized instances allow us to show data structures.\n\n    The following is a generic instance in that if we can have two types\n    [A] and [B] that are instances of the [Show] class, then we can\n    build a generic [Show] for the product type [A*B].\n*)\n\nInstance showPair (A B : Type)\n  (showA : Show A) (showB : Show B) : Show (A*B) := \n{\n  show := (fun p =>    \"<\" \n                    ++ (show (fst p)) \n                    ++ \",\"\n                    ++ (show (snd p)) \n                    ++ \">\")\n}.\n\n(** Since we can have pairs of any types, we parameterize\n    our [Show] instance by two types.  We need to\n    constrain both of these types to be instances of [Show]. *)\n\nCompute show (3,4).\n(* ==> \"<3,4>\" : string *)\n\nCompute show (true,40).\n(* ==> \"<אמת,28>\" : string *)\n\n(**  [showA] and [showB] are _evidence_ that [A] and [B] are \n    instances of [Show]. *)\n\n(** Note that we never use the terms [showA] and [showB], \n   so the following is also ok: *)\n\nInstance showPair' (A B : Type) \n  (_ : Show A) (_ : Show B) : Show (A*B) := \n{\n  show := (fun p =>    \"<\" \n                    ++ (show (fst p)) \n                    ++ \",\"\n                    ++ (show (snd p)) \n                    ++ \">\")\n}.\n\n(** ...and here is [Show] for lists: *)\n\nFixpoint showListAux {A : Type} \n  (s : A -> string) (l : list A) : string :=\n  match l with\n    | nil => \"\"\n    | cons h nil => s h\n    | cons h t => (s h) ++ \", \" ++ (showListAux s t)\n  end.\n\nInstance showList (A : Type) (_ : Show A) : Show (list A) :=\n  {\n    show l := \"[\" ++ (showListAux show l) ++ \"]\"\n  }.\n\nCompute (show [1;2;9]).\n(* ==> \"[[1, 2, 9]]\" : string *)\n\nCompute (show [true;true]).\n(* ==> \"[[אמת, אמת]]\" : string *)\n\n(* ================================================================= *)\n(** **   Equality Testers *)\n\n(** Of course, [Show] is not the only interesting typeclass.  There\n    are many other situations where it is useful to be able to\n    choose (and construct) specific functions depending on the type of\n    an argument that is supplied to a generic function like [show]. *)\n\n(** Here is another basic example of typeclasses: a class [Eq]\n    describing types with a (boolean) test for equality. *)\n\nClass Eq (A : Type) :=\n  {\n    eqb: A -> A -> bool;\n  }.\n\nNotation \"x =? y\" := (eqb x y) (at level 70).\n\n(** And here are some basic instances: *)\n\nInstance eqBool : Eq bool :=\n  {\n    eqb := fun (b c : bool) =>\n       match b with\n         | true  => c\n         | false => negb c\n       end\n  }.\n\nInstance eqNat : Eq nat :=\n  {\n    eqb := Nat.eqb\n  }.\n\nExample eqBool_ex : (true =? negb false) = true.\nProof. reflexivity. Qed.\n\nExample eqNat_ex : (7 =? 100 - 94) = false.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 3 stars, standard (boolArrowBool)\n\n    There are some function types, like [bool->bool], for which\n    checking equality makes perfect sense.  Write an [Eq] instance for\n    this type. Include some test cases (e.g., simple logical equivalences) \n    as Examples proved using [reflexivity].  *)\n\nInstance eqBoolBool : Eq (bool->bool) :=\n  {\n    eqb := fun f g => \n        (f true =? g true) && (f false =? g false)\n  }.\n\nExample eqBoolBool_ex1 : eqb negb (fun x => negb (negb (negb x))) = true.\nProof. reflexivity. Qed.\nExample eqBoolBool_ex2 : eqb negb (fun x => negb (negb x)) = false.\nProof. reflexivity. Qed.\nExample eqBoolBool_ex3 : eqb negb negb = true.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** Here is an [Eq] instance for pairs... *)\n\nInstance eqPair (A B : Type) (_ : Eq A) (_ : Eq B) : Eq (A * B) :=\n  {\n    eqb p1 p2 :=\n      let (p1a,p1b) := p1 in\n      let (p2a,p2b) := p2 in\n      andb (p1a =? p2a) (p1b =? p2b)\n  }.\n\n(** **** Exercise: 3 stars, standard (eqEx)\n\n    Write an [Eq] instance for lists and [Show] and [Eq] instances for\n    the [option] type constructor. In particular, the examples should\n    all hold. *)\n\n(* FILL IN HERE *)\n\nFixpoint eqlist {A : Type} (e:Eq A) (l1 l2 : list A): bool :=\n  match l1, l2 with\n    | h1 :: t1, h2 :: t2 => (h1 =? h2) && eqlist e t1 t2 \n    | [], [] => true\n    | _, _ => false\n    end.\n\nInstance eqList {A : Type} (e : Eq A) : Eq (list A) :=\n{eqb := eqlist e\n}.\nExample eqList_ex1 : eqb [1;2;9] [1;2;9] = true.\nProof. reflexivity. Qed.\n\nExample eqList_ex2 : eqb [1;2;9] [1] = false.\nProof. reflexivity. Qed.\n\nExample eqList_ex3 : eqb [(true,true);(false,true)] [(true,true);(false,true)] = true.\nProof. reflexivity. Qed.\n\nExample eqList_ex4 : eqb [] [(true,true);(false,true)] = false.\nProof. reflexivity. Qed.\n\n(* GRADE_THEOREM 0.25: eqList_ex1 *)\n(* GRADE_THEOREM 0.25: eqList_ex2 *)\n(* GRADE_THEOREM 0.25: eqList_ex3 *)\n(* GRADE_THEOREM 0.25: eqList_ex4 *)\n Compute Show.\n\nInstance showOpt (A : Type) (_ : Show A) : Show (option A) :=\n{\n  show xs := match xs with\n      | None => \"[||]\"\n      | Some x => \"[|\" ++ show x ++ \"|]\"\nend\n}.\n\nExample showOpt_ex1 : show (Some 5) = \"[|5|]\".\nProof. reflexivity. Qed.\n\nExample showOpt_ex2 : show (None) = \"[||]\".\nProof. reflexivity. Qed.\n\nInstance eqOpt (A : Type) (_ : Eq A) : Eq (option A):=\n{eqb xs ys :=\n    match xs, ys with\n    | Some x, Some y => x =? y\n    | None, None => true\n    | _, _ => false\n    end\n}.\n\nExample eqOpt_ex1 : eqb (Some false) (Some true) = false.\nProof. reflexivity. Qed.\nExample eqOpt_ex2 : eqb (Some [(true,true);(false,true)]) (Some [(true,true);(false,true)]) = true.\nProof. reflexivity. Qed.\n\nExample eqOpt_ex3 : eqb (Some false) None = false.\nProof. reflexivity. Qed.\n\nExample eqOpt_ex4 : eqb None None = true.\nProof. reflexivity. Qed.\n\n(* GRADE_THEOREM 0.25: eqOpt_ex1 *)\n(* GRADE_THEOREM 0.25: eqOpt_ex2 *)\n(* GRADE_THEOREM 0.25: eqOpt_ex3 *)\n(* GRADE_THEOREM 0.25: eqOpt_ex4 *)\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (boolArrowA)\n\n    Generalize your solution to the [boolArrowBool] exercise to build\n    an equality instance for any type of the form [bool->A], where [A]\n    itself is an [Eq] type.  Demonstrate that it works for [bool->bool->nat]. *)\n\nInstance eqBoolA (A : Type) : Eq A -> Eq (bool -> A) := {\n  eqb f g := (f true =? g true) && (f false =? g false)\n}.\n\nCompute (eqb (fun (b1 b2 : bool) => if b1 then 42 else 9)\n             (fun (b1 b2 : bool) => if b2 then 42 else 9)).\n\nExample eqBoolA_ex1 : eqb negb (fun x => negb (negb (negb x))) = true.\nProof. reflexivity. Qed.\nExample eqBoolA_ex2 : (eqb (fun (b1 b2 : bool) => if b1 then 42 else 9)\n                              (fun (b1 b2 : bool) => if b2 then 42 else 9)) = false.\nProof. reflexivity. Qed.\nExample eqBoolA_ex3 : (eqb (fun (b1 b2 : bool) => if b1 && b2 then 42 else 9)\n                              (fun (b1 b2 : bool) => if negb (b2 && b1) then 9 else 42)) = true.\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(* ================================================================= *)\n(** **   Typeclasses Hierarchies *)\n\n(** We often want to organize typeclasses into hierarchies.  For\n    example, we might want a typeclass [Ord] for \"ordered types\" that\n    support both equality and a less-or-equal comparison operator. *)\n\n(** A possible (but bad) way to do this is to define a new class with\n    two associated functions: *)\n\nClass OrdBad (A : Type) :=\n  {\n    eqbad : A -> A -> bool;\n    lebad : A -> A -> bool\n  }.\n\n(** The reason this is bad is because we now need to use a new\n    equality operator ([eqbad]) if we want to test for equality on\n    ordered values. *)\n\n(** A much better way is to parameterize the definition of [Ord] on an\n    [Eq] class constraint: *)\n\nClass Ord (A : Type) {H : Eq A} : Type :=\n  {\n    le : A -> A -> bool\n  }.\n\nNotation \"x <=? y\" := (le x y) (at level 70).\n\n(** When we define instances of [Ord], we just have to implement the\n    [le] operation. *)\n\nInstance ordNat : Ord nat :=\n  {\n    le := Nat.leb \n  }.\n\n(** Functions expecting to be instantiated with an instance of [Ord]\n    now have two class constraints, one witnessing that they have an\n    associated [eqb] operation, and one for [le]. *)\n\nDefinition max {A: Type} {_ : Eq A} {_: Ord A} (x y : A) : A :=\n  if x <=? y then y else x.\n\n(** The parameters [_:Eq A] and [_:Ord A] are _class constraints_, \n    which state that the function [max] is expected to be applied only to\n    types [A] that belong to the [Eq] and [Ord] classes.\n*)\n\nCompute (max 4 5).\n(* ==> 5 : nat *)\n\n\n(** There is mechanism for implicit generalization that is helpful here: *)\n\nDefinition max' {A: Type} `{Ord A} (x y : A) : A :=\n  if x <=? y then y else x.\n\n(** **** Exercise: 3 stars, standard (ordMisc)\n\n    Define [Ord] instances for pairs.\n    Include some examples. *)\n\nInstance ordPair  (X Y: Type) `(Ord X) `(Ord Y) : Ord (X *Y) := {\n\n  le p1 p2 := let (x1, y1) := p1 in\n             let (x2, y2) := p2 in\n                if x1 =? x2 then y1 <=? y2 \n                else if x1 <=? x2 then true else false\n}.\n\n\nExample ex1: (5, 3) <=? (6, 3) = true.\nProof. reflexivity. Qed.\nExample ex2: (5, 3) <=? (5, 3) = true.\nProof. reflexivity. Qed.\nExample ex3: (5, 3) <=? (5, 4) = true.\nProof. reflexivity. Qed.\nExample ex4: (5, 3) <=? (4, 3) = false.\nProof. reflexivity. Qed.\n(* FILL IN HERE *)\n(* Do not modify the following line: *)\nDefinition manual_grade_for_ordMisc : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (ordList)\n\n    For a little more practice, define an [Ord] instance for lists.\n    Include some examples. *) \nFixpoint ordlist {X: Type} (e1:Eq X) (e2:Ord X) (l1 l2 : list X) : bool :=\n match l1, l2 with\n             | h1::t1, h2::t2 => if h1 =? h2 then (ordlist e1 e2 t1 t2) \n                else if h1 <=? h2 then true else false\n             | [], _ => true\n             | _, _ => false\n            end.\n\nInstance ordList  (X : Type) (e1:Eq X) (e2:Ord X) : Ord (list X) := {\n\n  le := ordlist e1 e2\n}.\n\n\nExample exl1: [5; 3] <=? [6; 3] = true.\nProof. reflexivity. Qed.\nExample exl2: [5; 3 ; 4] <=? [5; 3] = false.\nProof. reflexivity. Qed.\n\n(* FILL IN HERE *)\n(* Do not modify the following line: *)\nDefinition manual_grade_for_ordList : option (nat*string) := None.\n\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** The Functor Class *)\n\nClass Functor (F : Type -> Type) := {\n  fmap : forall {A B : Type}, (A -> B) -> F A -> F B;\n}.\n\n(** Here, it's not a type that is a functor, but rather a \n    type constructor (i.e., a function from types to types).\n*)\n\nFixpoint mapList {A B : Type} (f : A -> B) (xs : list A) :=\n  match xs with\n    | [] => []\n    | x :: xs => (f x) :: (mapList f xs)\n  end.\n\nInstance functorList : Functor list := {\n  fmap A B := mapList\n}.\n\nCompute (fmap S [1;2;9]).\n(* ==> [[2; 3; 10]] : list nat *)\n\n(* ================================================================= *)\n(** ** Trees *)\n\nInductive tree (X : Type) : Type :=\n  | Leaf\n  | Node (x : X) (l : tree X) (r : tree X).\n\nArguments Leaf {X}.\nArguments Node {X}.\n\nFixpoint mapTree {A B : Type} (f : A -> B) (t : tree A) :=\n  match t with\n    | Leaf => Leaf\n    | Node x l r  => Node (f x) (mapTree f l) (mapTree f r)\n  end.\n\nInstance functorTree : Functor tree := {\n  fmap A B := mapTree\n}.\n\nCompute (fmap S (Node 5  (Node 7 Leaf Leaf) \n                (Node 12 (Node 7 Leaf Leaf) Leaf))).\n(* ==> Node 6 (Node 8 Leaf Leaf) (Node 13 (Node 8 Leaf Leaf) Leaf) : tree nat *)\n\nDefinition showall {F : Type -> Type} {_ : Functor F}\n                   {A : Type} {_ : Show A} \n                   (x : F A) : F string :=\n  fmap show x.\n\nCompute (showall (Node true (Node false Leaf Leaf) \n                 (Node false Leaf Leaf))).\n\n(** **** Exercise: 1 star, standard (functorOpt)\n\n    Define Option as an instance of Functor. *) \n\nInstance functorOption : Functor option := {\n  fmap A B f xs := match xs with\n      | None => None\n      | Some x => Some (f x)\n  end\n}.\n\nExample functorOpt_ex1 : fmap S None = None.\nProof. reflexivity. Qed.\n\nExample functorOpt_ex2 : fmap S (Some 1) = Some 2.\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(** A functor instance has to to satisfy two constraints: \n\n- fmap_id: \n\nforall (A : Type), fmap (@id A) = id\n\n- fmap_comp : \n\nforall (A B C : Type) (f : B -> C) (g : A -> B),\n      fmap (fun x => f (g x)) = fun x => (fmap f (fmap g x))\n*)\n\n(** **** Exercise: 2 stars, standard (fmap_tree)\n\n    Prove the required properties for the tree instance. *) \n\nLemma fmap_id_tree : forall (A : Type) (t : tree A), \n  @fmap tree _ _ _ (@id A) t = id t.\nProof.\n  intros. induction t.\n    -reflexivity.\n    -simpl. simpl in IHt1, IHt2. rewrite IHt1. rewrite IHt2. reflexivity.\nQed.\n\nLemma fmap_comp_tree : forall (A B C : Type) \n  (f : B -> C) (g : A -> B) (t : tree A),\n  @fmap tree _ _ _ (fun x => f (g x)) t = \n  (fun x => (fmap f (fmap g x))) t.\nProof.\n  intros. induction t.\n    - reflexivity.\n    - simpl. simpl in IHt1, IHt2. rewrite IHt1. rewrite IHt2. reflexivity.\nQed.\n\n(** [] *)\n\n(** Cool fact: only one possible fmap per type! *)\n\n(** Thus, fmap can be derived automatically. Haskell does it for you. *)\n\n(* ================================================================= *)\n(** ** Monads (from \"Categories for the Working Mathematician\" by Sounders Mac Lane) *)\n\n(** \"All told, a monad in [X] is just a monoid in the category of endofunctors of X, \n  with product [×] replaced by composition of endofunctors \n  and unit set by the identity endofunctor.\" *)\n\n(* ================================================================= *)\n(** ** Monads (via programming examples) *)\n\n(** One important typeclass (which is heavily used) is \n    the [Monad] typeclass, especially in conjunction with Haskell's\n    \"[do] notation\" for monadic actions.\n\n    Monads are an extremely powerful tool for organizing and\n    streamlining code in a wide range of situations where computations\n    can be thought of as yielding a result along with some kind of\n    \"effect.\"  \n\n   Monads are very useful for modeling things that are not just\n   pure functions, that may have some kind of external effect on \n   the world such as reading input or producing output. They're\n   essential for modeling statefulness a in pure, stateless,\n   functional language like Coq.\n\n    Examples of possible effects include:\n       - input / output\n       - state mutation\n       - failure\n       - nondeterminism\n       - randomness  *)\n\n(* ================================================================= *)\n(** ** Monad for error signaling *)\n\n(** As a first example, consider a simplified expression type\n   and let's implement an evaluator for it. *)\n\nInductive exp := \n| Num : nat -> exp\n| Plus : exp -> exp -> exp\n| Div : exp -> exp -> exp.\n\n(** First, a [show] function: *)\n\nFixpoint showExpAux (e : exp) : string :=\n  match e with \n    | Num n => show n\n    | Plus e1 e2 => \n        \"(\" ++ (showExpAux e1) ++ \"+\" ++ (showExpAux e2) ++ \")\"\n    | Div e1 e2 => \n        \"(\" ++ (showExpAux e1) ++ \"/\" ++ (showExpAux e2) ++ \")\"\n  end.\n\nInstance showExp : Show exp := {\n  show := showExpAux\n}.\n\nCompute (show (Div (Num 6) (Num 0))).\n(* ==> \"(6/0)\" : string *)\n\n(** Here is a first attempt for an evaluator. *)\n\nFixpoint eval0 (e:exp) : nat := \n  match e with \n    | Num n => n\n    | Plus e1 e2 => eval0 e1 + eval0 e2 \n    | Div e1 e2 => eval0 e1 / eval0 e2\n  end.\n\n\nCompute (eval0 (Div (Num 6) (Num 2))).\n(* ==> 3 : nat *)\n\nCompute (eval0 (Div (Num 6) (Num 0))).\n(* ==> 0 : nat *)\n\n(** Here we assumed that dividing by [0] returns [0].\n    \n    We can do better.*)\n\n(** Our next version of [eval] will return a value only if\n   it does not divide by [0]. \n\n   Otherwise, it will return an _error message_, reporting an expression \n   evaluating to [0] that we divided by. *)\n\n(** For that matter, we define a [Result] type constructor: *)\n\nInductive Result (X : Type) : Type :=\n  | Error (err : string)\n  | Value (x : X).\n\nArguments Error {X}.\nArguments Value {X}.\n\n(** The evaluation returning [Result nat] is implemented as follows: *)\n\nFixpoint eval1 (e:exp) : Result nat := \n  match e with \n   | Num n => Value n\n   | Plus e1 e2 => \n        match eval1 e1 with\n          | Error err1 => Error err1\n          | Value n1 => \n              match eval1 e2 with\n                | Error err2 => Error err2 \n                | Value n2  => Value (n1 + n2)\n              end\n        end\n   | Div e1 e2 => \n        match eval1 e1 with\n          | Error err1 => Error err1\n          | Value n1 => \n              match eval1 e2 with\n                | Error err2 => Error err2 \n                | Value n2  => match n2 with \n                                 | 0 => Error (\"DBZ: \" ++ show e2)\n                                 | _ => Value (n1 / n2)\n                               end\n              end\n        end\n end.\n\n(** This works: *) \n\nCompute (eval1 (Div (Num 6) (Num 2))).\n(* ==>  Value 3 : Result nat *)\n\nCompute (eval1 (Div (Num 6) (Num 0))).\n(* ==>  Error \"DBZ: 0\" : Result nat *)\n\nCompute (eval1 (Div (Num 6) (Plus (Num 0) (Num (0))))).\n(* ==>  Error \"DBZ: (0+0)\" : Result nat *)\n\nCompute (eval1 (Plus (Div (Num 6) (Num 0)) \n                     (Div (Num 6) (Plus (Num 0) (Num (0)))))).\n(* ==>  Error \"DBZ: 0\" : Result nat *)\n\nCompute (eval1 (Div (Div (Num 6) (Plus (Num 0) (Num (0)))) (Num 0))).\n(* ==>  Error \"DBZ: (0+0)\" : Result nat *)\n\n(** The bad news: the code is super duper gross! *)\n\n(** A lot of the computation logic is duplicated. \n    (Imagine more operations / larger arity.) *)\n\n\n(** We have these cascading blocks:\n\nmatch eval e with\n  | Error err1 => Error err1\n  | Value n1 => match eval e2 with\n                  | Error err2 => Error err2 \n                  | Value n2  => ...\n                 end\n*)\n\n(** But these blocks have a common pattern:\n\n- First do [eval e] and get result [res]\n- If [res] is an [Error], just return that error\n- If [res] is a [Value v] then do further processing on [v] *)\n\n(** Let's bottle the common structure in a function! *)\n\n(** Such a function is usually called [bind] and denoted by [>>=] *)\n\nDefinition bind_result {A B : Type} (r : Result A) \n  (process : A -> Result B) : Result B :=\n  match r with\n  | Error err => Error err\n  | Value v => process v\n  end.\n\nNotation \"r >>= process\" := (bind_result r process)\n                     (at level 60, right associativity).\n\n(** [>>=] takes two inputs:\n\n  - [r] of type [Result A]: result of the first evaluation\n  - [process] of type [A -> Result B]: in case the first evaluation produced a value, \n    what to do next with that value\n*)\n\n(** The magic bottle lets us clean up our evaluator: *)\n\nFixpoint eval2 (e:exp) : Result nat := \n  match e with \n    | Num n => Value n\n    | Plus e1 e2 => eval2 e1 >>= fun n1 =>\n                    eval2 e2 >>= fun n2 =>\n                    Value (n1 + n2)\n    | Div e1 e2  => eval2 e1 >>= fun n1 =>\n                    eval2 e2 >>= fun n2 =>\n                    match n2 with \n                      | 0 => Error (\"DBZ: \" ++ show e2)\n                      | _ => Value (n1 / n2)\n                    end\nend.\n\n(** The gross pattern matching is all hidden inside >>= *)\n\n(* ================================================================= *)\n(** ** The Monad Typeclass *)\n\n(** Like [show] or [eqb], the [>>=] operator \n    turns out to be useful across many types (not just [Result]). *)\n\n(** Let's create a typeclass for it! *)\n\nClass Monad (M : Type -> Type) := \n{\n  bind : forall {A B : Type}, M A -> (A -> M B) -> M B ;\n  ret : forall {A : Type}, A -> M A\n}.\n\n(** Note:\n\n- It's not a type that is a monad, but rather a type constructor \n  (i.e., a function from types to types), like [Result]. \n\n- Monads have two operations: bind and return. \n\n- Return tells you how to wrap a value in the monad. \n*)\n\n(** For [Result], we already saw [bind]:\n\nDefinition bind_result {A B : Type} (r :Result A) \n  (process : A -> Result B) : Result B :=\n  match r with\n  | Error err => Error err\n  | Value v => process v\n  end.\n*)\n\n\n(** What about [ret] ? *)\n\n(**\n\nDefinition ret {A : Type} (a : A) : Result A := ???\n*)\n\nInstance monResult : Monad Result := \n{\n  bind := fun {A B : Type} (x : Result A) (f : A -> Result B) =>\n            match x with \n              | Error err => Error err\n              | Value y => f y\n            end ;\n  ret := fun {A : Type} (x : A) => Value x\n}.\n\n(** In fact, [>>=] is so useful there is special syntax for it. *)\n\n(** It’s called the \"do notation\". *)\n\nNotation \"x <- c1 ;; c2\" := (bind c1 (fun x => c2)) \n               (right associativity, at level 84, c1 at next level).\n\nNotation \"c1 ;; c2\" := (bind c1 (fun _ => c2)) \n               (at level 100, right associativity).\n\n\n\n(**\nInstead of writing\n\n   e1 >>= fun v1 =>\n   e2 >>= fun v2 =>\n   e3 >>= fun v3 =>\n   e\n\nwe can write\n\n   v1 <- e1 ;;\n   v2 <- e2 ;;\n   v3 <- e3 ;;\n   e\n*)\n\n(** We can further simplify our evaluator to: *)\n\nFixpoint eval (e:exp) : Result nat := \n  match e with \n    | Num n => ret n\n    | Plus e1 e2 => n1 <- eval e1 ;;\n                    n2 <- eval e2 ;;\n                    ret (n1 + n2)\n    | Div e1 e2  => n1 <- eval e1 ;;\n                    n2 <- eval e2 ;;\n                    match n2 with \n                      | 0 => Error (\"DBZ: \" ++ show e2)\n                      | _ => ret (n1 + n2)\n                    end\nend.\n\n(** This looks like imperative programming :) *)\n\n(** We can also catch errors, and return [0]: *)\n\nDefinition eval_to_zero (e : exp) := \n  let r := (eval e) in\n    match r with \n      | Error s => ret 0\n      | _ => r\n    end.\n\n\nCompute (eval_to_zero (Div (Num 6) (Plus (Num 0) (Num (0))))).\n(* ==>  Value 0 : Result nat *)\n\n(* ================================================================= *)\n(** ** Monad for Mutable State *)\n\n(** We used a monad for error signaling. *)\n\n(** The next example considers mutable state, \n    which _seems_ very different. *)\n\n\n\n(** Consider implementing expressions with a counter: *)\n\nInductive exp_c := \n| Num_c : nat -> exp_c\n| Plus_c : exp_c -> exp_c -> exp_c\n| Inc.\n\n(** Behavior we want: \n\n- [eval] is given the initial counter value\n- every time we evaluate [Inc] (within the call to [eval]), \n  the value of the counter increases\n*)\n\n\n(** For example: *)\n\n(**\n\neval Inc 0                       -->  0\n\neval (Plus Inc Inc) 0            -->  1\n\neval (Plus Inc (Plus Inc Inc)) 0 -->  3\n*)\n\n(* ================================================================= *)\n(** ** How should we implement [eval]? *)\n\n\nDefinition Cnt := nat.\n\n(**\n\nFixpoint eval (e:exp_c) (cnt:Cnt) : ?? := \n  match e with \n    | Num_c n => ??\n    | Plus_c e1 e2 => ??\n    | Inc => ??\n  end.\n*)\n\n(* ================================================================= *)\n(** ** Evaluating Expressions with Counter *)\n\n(** We need to increment the counter every time we do eval [Inc]. *)\n\n(** So [eval] needs to return the new counter. *)\n\nFixpoint eval_c0 (e:exp_c) (cnt:Cnt) : Cnt * nat := \n  match e with \n    | Num_c n => (cnt, n)\n    | Plus_c e1 e2 => \n          let (cnt1, v1) := eval_c0 e1 cnt  in\n          let (cnt2, v2) := eval_c0 e2 cnt1 in\n          (cnt2, v1 + v2)\n    | Inc => (S cnt, cnt)\n  end.\n\nDefinition topEval_c0 e := snd (eval_c0 e 0).\n\n(** The good news: we get the right result: *)\n\nCompute (topEval_c0 (Plus_c Inc Inc)).\n(* ==>  Value 1 : Result nat *)\n\nCompute (topEval_c0 (Plus_c Inc (Plus_c Inc Inc))).\n(* ==>  Value 3 : Result nat *)\n\n\n\n(** The bad news: the code is super duper gross: \n\n- The Plus case has to “thread” the counter through the recursive calls.\n\n- Easy to make a mistake, e.g. pass [cnt] instead of [cnt1] into the second [eval]!\n\n- The logic of addition is obscured by all the counter-passing\n\n- So unfair, since [Plus] doesn't even care about the counter!\n*)\n\n(** Is it too much to ask that [eval] looks like this?\n\nFixpoint eval (e:exp) (cnt:Cnt) : Cnt * nat := \n  match e with \n    | Num n => ret n\n    | Plus e1 e2 => n1 <- eval e1 ;;\n                    n2 <- eval e2 ;;\n                    ret (n1 + n2)\n    ...\n  end.\n*)\n\n\n\n(**\n- Cases that don't care about the counter ([Num], [Plus]), don't even have to mention it!\n- The counter is somehow threaded through automatically behind the scenes\n- Looks just like in the error handing evaluator.\n*)\n\n(* ================================================================= *)\n(** ** Lets Spot a Pattern *)\n\n(**\n\n    | Plus_c e1 e2 => let (cnt1, v1) := eval e1 cnt  in \n                      let (cnt2, v2) := eval e2 cnt1 in\n                        (cnt2, v1 + v2)\n\nThis block has a standard common pattern:\n\n- Perform first step [eval e1] using initial counter [cnt]\n- Get a result [(cnt1, v1)]\n- Do further processing on [v1] using the new counter [cnt1]\n\n*)\n\n(**\n\n   let (cnt', v) := step cnt \n   in process v cnt' \n*)\n\n(**\n\n   let (cnt', v) := step cnt \n   in process v cnt' \n\nCan we bottle this common pattern as a [>>=] ?\n\n>>= step process cnt = let (cnt', v) = step cnt\n                         in process v cnt'\n*)\n\n(** But what is the type of this [>>=] ? \n*)\n\nDefinition bind_counter {A B : Type} \n (step : Cnt -> Cnt * A) (process : A -> Cnt -> Cnt * B)\n (cnt : Cnt) : Cnt * B :=\n let (cnt', v) := step cnt\n in process v cnt'.\n\n(**\n\nbind_counter : (Cnt -> Cnt * A) \n               -> (A -> Cnt -> Cnt * B) \n               -> Cnt \n               -> Cnt * B\n*)\n\n(**\nWait, but this type signature looks nothing like the Monad’s bind!\n\nClass Monad (M : Type -> Type) := \n{\n  bind : forall {A B : Type}, M A -> (A -> M B) -> M B ;\n  ret  : forall {A : Type}, A -> M A\n}.\n\n... or does it??? *)\n\n(** Our type constructor [M]: *)\n\nDefinition Counting (X : Type) : Type := Cnt -> Cnt * X.\n\n(**\n\nbind_counter : (Cnt -> Cnt * A) \n               -> (A -> Cnt -> Cnt * B) \n               -> Cnt \n               -> Cnt * B\n\nbind_counter : Counting A \n               -> (A -> Counting B) \n               -> Counting B\n*)\n\n(**\nIndeed: *)\n\nCheck (@bind_counter nat nat) : \n               Counting nat \n               -> (nat -> Counting nat) \n               -> Counting nat.\n\n(* ================================================================= *)\n(** **   Cleaned-up Evaluator for Expressions with Counter *)\n\nInstance monCounting : Monad Counting := \n{\n  ret := fun {A:Type} (x:A) => fun cnt => (cnt, x) ; \n  bind := fun {A B:Type} (x: Counting A) (f:A -> Counting B) =>\n            fun cnt => let (cnt1,v1) := (x cnt) in (f v1) cnt1\n}.\n\nFixpoint eval_c (e:exp_c) : Counting nat := \n  match e with \n    | Num_c n      => ret n\n    | Plus_c e1 e2 => n1 <- eval_c e1 ;;\n                      n2 <- eval_c e2 ;;\n                      ret (n1 + n2)\n    | Inc       => fun cnt => (S cnt, cnt)\nend.\n\n(** Hooray! We rid the poor [Num] and [Plus] from the pesky counters!\nThe Inc case deals with counters\n*)\n\nDefinition topEval_c e := snd (eval_c e 0).\n\n(** We get the right results: *)\n\nCompute (topEval_c (Plus_c Inc Inc)).\n(* ==>  1 : nat *)\n\nCompute (topEval_c (Plus_c Inc (Plus_c Inc Inc))).\n(* ==>  3 : nat *)\n\n(** It is possible to go a step forward and hide the representation\nof Counting: *)\n\nDefinition get : Counting Cnt := fun cnt => (cnt,cnt).\n(* Computation whose return value is the current counter value *)\n\nDefinition put (newCnt : Cnt) : Counting unit := fun cnt => (newCnt,tt).\n(* Computation that updates the counter value to [newCnt] *)\n\nFixpoint eval'_c (e:exp_c) : Counting nat := \n  match e with \n    | Num_c n => ret n\n    | Plus_c e1 e2 => n1 <- eval'_c e1 ;;\n                      n2 <- eval'_c e2 ;;\n                      ret (n1 + n2)\n    | Inc => cnt <- get ;;\n                _ <- put (cnt + 1) ;;\n                ret (cnt)\n  end. \n\n(* ================================================================= *)\n(** **   The State Monad  *)\n\n(**\n\nThreading state (like a counter) is a common task!\n*)\n\n(**\n\nHaskell standard library provides the \"State monad\" for it.\n\nLet's see how it works in another example \n*)\n\n(** We consider expressions equipped with an imperative\n    update: *)\n\nDefinition var := string.\nDefinition state := var -> nat.\n\nDefinition update_state (s : state) (x : var) (n : nat) : state :=\n  fun x' => if String.eqb x x' then n else s x'.\n\nNotation \"'_' '!->' n\" := (fun _ => n)\n  (at level 100, right associativity).\n\nNotation \"x '!->' n ';' s\" := (update_state s x n)\n                              (at level 100, n at next level, right associativity).\n\nInductive exp_v : Type := \n| Var_v : var -> exp_v\n| Plus_v : exp_v -> exp_v -> exp_v\n| Times_v : exp_v -> exp_v -> exp_v\n| Store_v : var -> exp_v -> exp_v\n| Seq_v : exp_v -> exp_v -> exp_v\n| If0_v : exp_v -> exp_v -> exp_v -> exp_v.\n\n(** An evaluator can be written that passes the state\n    through everywhere, but it's tedious and error-prone: *)\n\nFixpoint eval_v0 (e : exp_v) (s : state) : (state * nat) := \n  match e with \n    | Var_v x => (s, s x)\n    | Plus_v e1 e2 => \n      let (s1, n1) := eval_v0 e1 s in\n      let (s2, n2) := eval_v0 e2 s1 in \n      (s2, n1+n2)\n    | Times_v e1 e2 =>\n      let (s1, n1) := eval_v0 e1 s in\n      let (s2, n2) := eval_v0 e2 s1 in \n      (s2, n1*n2)\n    | Store_v x e => \n      let (s1, n1) := eval_v0 e s in \n      (x !-> n1 ; s, n1)\n    | Seq_v e1 e2 => \n      let (s1, n1) := eval_v0 e1 s in\n      eval_v0 e2 s1\n    | If0_v e1 e2 e3 => \n      let (s1, n1) := eval_v0 e1 s in \n      match n1 with \n        | 0 => eval_v0 e2 s1\n        | _ => eval_v0 e3 s1\n      end\n  end.\n\nCompute snd (eval_v0 \n         (Var_v \"y\") \n         (\"x\" !-> 5 ; \"y\" !-> 7 ; _ !-> 0)).\n(* ==>  7 : nat *)\n\nCompute snd (eval_v0 \n         (Seq_v (Store_v \"x\" (Plus_v (Var_v \"x\") (Var_v \"y\"))) \n                (Var_v \"x\"))\n         (\"x\" !-> 5 ; \"y\" !-> 7 ; _ !-> 0)).\n(* ==>  12 : nat *)\n\n(** Let's use the state monad: *)\n\nDefinition StateComp (S : Type) (A : Type) := S -> (S * A).\n\nInstance monState (S : Type) : Monad (StateComp S) := {\n  ret := fun {A:Type} (x:A) => fun (s : S) => (s,x) ; \n  bind := fun {A B:Type} (c : StateComp S A) (f: A -> StateComp S B) => \n            fun (s : S) => \n              let (s',v) := c s in \n              f v s'\n}.\n\n(** BTW, we can now define:\n\nDefinition Counting (A : Type) := StateComp Cnt A.\n\nand the [eval] above will just work out of the box!\n*)\n\n(** Helpers: *) \n\nDefinition read (x:var) : StateComp state nat := \n  fun s => (s, s x).\n(* Computation whose return value is the current value of [x] *)\n\nDefinition write (x:var) (n:nat) : StateComp state nat := \n  fun s => (x !-> n ; s, n).\n(* Computation that updates [x] value to [n] and returns [n] *)\n\n(** The evaluator looks much cleaner with the state monad,\n    using the functions [read] and [write] to capture interaction\n    with the state. *)\n\nFixpoint eval_v (e : exp_v) : StateComp state nat := \n  match e with \n    | Var_v x => read x\n    | Plus_v e1 e2 => \n      n1 <- eval_v e1 ;; \n      n2 <- eval_v e2 ;; \n      ret (n1 + n2)\n    | Times_v e1 e2 =>\n      n1 <- eval_v e1 ;; \n      n2 <- eval_v e2 ;; \n      ret (n1 * n2)\n    | Store_v x e => \n      n <- eval_v e ;; \n      write x n \n    | Seq_v e1 e2 => \n      _ <- eval_v e1 ;; \n      eval_v e2\n    | If0_v e1 e2 e3 => \n      n <- eval_v e1 ;;\n      match n with \n        | 0 => eval_v e2\n        | _ => eval_v e3 \n      end\n  end.\n\n(* ================================================================= *)\n(** **   Using a Monad for Non-deterministic Evaluation *)\n\n(** Our final example is an evaluator that supports non-determinism. *)\n\nInductive exp_nd : Type := \n| Choose_nd : list nat -> exp_nd\n| Plus_nd : exp_nd -> exp_nd -> exp_nd\n| Times_nd : exp_nd -> exp_nd -> exp_nd.\n\n(** Behavior we want: \n\neval (Choose [1;3])                        -->  [1;3]\n\neval (Plus (Choose [1;3]) (Choose [0;1;2]) -->  [1;3;2;4;3;5]\n*)\n\n(** We need some helpers to define the evaluation *)\n\n(** For addition: *)\n\nDefinition add_num_list n l:=\nmap (fun x => n + x) l.\n\nCompute add_num_list 1 [1;2].\n(* ==>  [[2; 3]] : list nat *)\n\nDefinition add_list_list l1 l2:=\nmap (fun x => add_num_list x l1) l2.\n\nCompute add_list_list [0;4] [1;2].\n(* ==>  [[[1; 5]; [2; 6]]] : list (list nat) *)\n\nDefinition flatten {A:Type} (xs:list (list A)) := \n  fold_right (@app A) nil xs.\n\nCompute (flatten (add_list_list [0;4] [1;2])).\n(* ==>  [[1; 5; 2; 6]] : list nat *)\n\n(** For multiplication: *)\n\nDefinition mul_num_list n l:=\nmap (fun x => n * x) l.\n\nCompute mul_num_list 1 [1;2].\n(* ==>  [[1; 2]] : list nat *)\n\nDefinition mul_list_list l1 l2:=\nmap (fun x => mul_num_list x l1) l2.\n\nCompute mul_list_list [0;4] [1;2].\n(* ==>  [[[0; 4]; [0; 8]]] : list nat *)\n\nCompute (flatten (mul_list_list [0;4] [1;2])).\n(* ==>  [[0; 4; 0; 8]] : list nat *)\n\n(** It is simple to generalize our helpers: *)\n\nDefinition apply_num_list (f : nat -> nat -> nat) n l:=\nmap (fun x => f n x) l.\n\nCompute (apply_num_list plus 1 [1;2]).\n(* ==>  [[2; 3]] : list nat *)\n\nCompute (apply_num_list mult 1 [1;2]).\n(* ==>  [[1; 2]] : list nat *)\n\nDefinition apply_list_list f l1 l2:=\nmap (fun x => apply_num_list f x l1) l2.\n\nCompute apply_list_list plus [0;4] [1;2].\n(* ==>  [[[1; 5]; [2; 6]]] : list (list nat) *)\n\nCompute apply_list_list mult [0;4] [1;2].\n(* ==>  [[[0; 4]; [0; 8]]] : list (list nat) *)\n\n(** The (ugly) evaluation function for non-determinstic values : *)\n\nFixpoint eval_nd0 (e:exp_nd) : list nat := \n  match e with \n    | Choose_nd ns => ns\n    | Plus_nd e1 e2 => \n      flatten (apply_list_list plus (eval_nd0 e1) (eval_nd0 e2))\n    | Times_nd e1 e2 => \n      flatten (apply_list_list mult (eval_nd0 e1) (eval_nd0 e2))\n  end.\n\nCompute eval_nd0 (Plus_nd (Choose_nd [1;3]) \n                          (Choose_nd [0;1;2])).\n(* ==>  [[1; 3; 2; 4; 3; 5]] : list nat *)\n\n(** We can do better with the \"list monad\"! *)\n\nInstance monList : Monad list := {\n  bind := fun {A B:Type} (c:list A) (f: A -> list B) => \n            flatten (map f c) ;\n  ret := fun {A:Type} (x:A) => (x::nil)\n}.\n\nFixpoint eval_nd (e:exp_nd) : list nat := \n  match e with \n    | Choose_nd ns => ns\n    | Plus_nd e1 e2 => \n      n1 <- eval_nd e1 ;;\n      n2 <- eval_nd e2 ;;\n      ret (n1 + n2)\n    | Times_nd e1 e2 => \n      n1 <- eval_nd e1 ;;\n      n2 <- eval_nd e2 ;;\n      ret (n1 * n2)\n  end.\n\nCompute eval_nd (Plus_nd (Choose_nd [1;3]) \n                         (Choose_nd [0;1;2])).\n(* ==>  [[1; 3; 2; 4; 3; 5]] : list nat *)\n\n(* ================================================================= *)\n(** ** Monads in General *)\n\n(**\n   If we think of monads as a pattern for encoding effects, such\n   as exceptions or state or non-determinism, then we can think \n   of [M A] as describing side-effecting computations that produce\n   a value of type A.  \n\n   The [ret] operation takes a pure (effect-free) value of type A\n   and injects it into the space of side-effecting computations.\n\n   The [bind] operation sequences two side-effecting computations,\n   allowing the latter to depend upon the value of the first one.\n\n*)\n\n(** \n\nSo it is not that pure languages lack imperative features,\nbut rather the other languages that lack the\nability to have a statically distinguishable pure\nsubset...\n\n*)\n\n(* ================================================================= *)\n(** ** Algebraic Properties *)\n\n(**\n\nClass Monad (M : Type -> Type) := \n{\n  bind : forall {A B : Type}, M A -> (A -> M B) -> M B ;\n  ret : forall {A : Type}, A -> M A\n}.\n*)\n\n(** Monads must obey these laws: \n- [ret x >>= f] is equivalent to [f x]\nDoing the trivial effect then doing a computation [f] is the same as\njust doing the computation [f]\n(return is left identity of bind)\n\n- [m >>= return] is equivalent to [m]\nDoing only a trivial effect is the same as not doing any effect\n(return is right identity of bind)\n\n- [(m >>= f) >>= g] is equivalent to [m >>= (fun x => f x >>= g)]\nDoing [f] then doing [g] as two separate computations is the same as\ndoing a single computation which is [f] followed by [g]\n(bind is associative)\n\n*)\n\n(**\nWhy? The laws make sequencing of effects work the way you expect.\n*)\n\n(* ================================================================= *)\n(** ** Example: The Counting Monad *)\n\nLemma m_left_id_Counting : \n  forall {A B : Type} (x:A) (f : A -> Counting B) (cnt : nat), \n  bind (ret x) f cnt = f x cnt.\nProof.\nintros A B x f cnt.\nunfold bind. reflexivity.\nQed.\n\nLemma m_right_id_Counting : \n  forall {A:Type} (c : Counting A) (cnt : nat),\n  bind c ret cnt = c cnt.\nProof.\nintros A c cnt.\nsimpl.\ndestruct (c cnt).\nreflexivity.\nQed.\n\nLemma m_assoc_Counting : \n  forall {A B C :Type} (c:Counting A) \n  (f : A -> Counting B) (g : B -> Counting C) (cnt : nat),\n    bind (bind c f) g cnt = bind c (fun x => bind (f x) g) cnt.\nProof.\nintros A B C c f g cnt.\nsimpl.\ndestruct (c cnt).\nreflexivity.\nQed.\n\n(* ================================================================= *)\n(** ** Example: The List Monad *)\n\n(** **** Exercise: 3 stars, standard (list_monad_properties)\n\n    State and prove the required properties for the list monad instance. *) \n\nLemma m_left_id_list : \n  forall {A B : Type} (x:A) (f : A -> list B), \n    bind (ret x) f = f x.\nProof.\n  intros. simpl. apply app_nil_r.\nQed.\n\nLemma m_right_id_list : \n  forall {A:Type} (l : list A), bind l ret = l.\nProof.\n  intros. induction l as [|h t IH].\n  -reflexivity.\n  -simpl. simpl in IH. rewrite IH. reflexivity.\nQed.\n\n(* FILL IN HERE *)\n\nLemma map_app : forall {A B : Type} (l1 l2 : list A) (f : A -> B),\n  map f (l1 ++ l2) = app (map f l1) (map f l2).\nProof. intros A B l1. induction l1 as [|h1 t1 IH].\n    -reflexivity.\n    -intros. simpl. rewrite IH. reflexivity.\nQed.\n\nLemma flatten_app : forall {A: Type} (l1 l2 : list (list A)), \n  flatten (l1 ++ l2) = app (flatten l1) (flatten l2).\nProof. intros A  l1. induction l1 as [|h1 t1 IH].\n    - reflexivity.\n    -intros. simpl. rewrite IH. rewrite app_assoc. reflexivity.\nQed.\n\nLemma m_assoc_list : \n  forall {A B C :Type} (l:list A) \n    (f : A -> list B) (g : B -> list C),\n    bind (bind l f) g = bind l (fun x => bind (f x) g).\nProof.\n  intros. induction l as [|h t IH].\n  -reflexivity.\n  -simpl. simpl in IH. rewrite <- IH. rewrite map_app. rewrite flatten_app. reflexivity.\nQed.\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** Monads are Amazing *)\n\n(** This code stays the same:\n\nFixpoint eval (e:exp) : Interpreter nat := \n  match e with \n    | Plus e1 e2 => \n      n1 <- eval e1 ;;\n      n2 <- eval e2 ;;\n      ret (n1 + n2)\n    | Times e1 e2 => \n      n1 <- eval e1 ;;\n      n2 <- eval e2 ;;\n      ret (n1 * n2)\n   ...\n  end.\n*)\n\n(**\nWe change the type [Interpreter] to implement different effects:\n\n- [Interpreter A = Result A]  if we want to handle errors\n- [Interpreter A = State nat A] if we want to have a counter\n- [Interpreter A = State (total_map nat) A] if we want to have assignments\n- [Interpreter A = Result (State (total_map nat) A)] if we want both errors and assignments\n- [Interpreter A = List A] if we want to return multiple results\n*)\n\n(**\nMonads let us decouple two things:\n\n- Application logic: the sequence of actions (implemented in [eval])\n- Effects: how actions are sequenced (implemented in [>>=])\n*)\n\n(* ================================================================= *)\n(** ** Monads are Influential *)\n\n(** Monads have had a revolutionary influence in PL.\n\n    Especially in Haskell (a pure functional language), but also well beyond.\n\n    Some recent examples:\n\n- Error handling in go\n\nhttps://speakerdeck.com/rebeccaskinner/monadic-error-handling-in-go\n\nhttps://www.innoq.com/en/blog/golang-errors-monads/\n\n- Asynchrony in JavaScript\n\nhttps://gist.github.com/MaiaVictor/bc0c02b6d1fbc7e3dbae838fb1376c80\n\nhttps://medium.com/@dtipson/building-a-better-promise-3dd366f80c16\n\n- Big data pipelines\n\nhttps://www.microsoft.com/en-us/research/project/dryadlinq/\n\nhttps://www.tensorflow.org/\n*)\n\n(* ================================================================= *)\n(** ** Additional Example: The Writer Monad *)\n\nFixpoint eval_log0 (e:exp) : string * nat := \n  match e with \n   | Num n => (\"num(\" ++ show n ++ \");\",n)\n   | Plus e1 e2 => \n        match eval_log0 e1 with\n          (s1,n1) => \n              match eval_log0 e2 with\n                | (s2,n2)  => \n                   (s1 ++  s2 ++\n                   \"plus(\" ++ show n1 ++ \",\" ++ show n2 ++ \");\",\n                   n1 + n2)\n              end\n        end\n   | Div e1 e2 => \n        match eval_log0 e1 with\n          (s1,n1) => \n              match eval_log0 e2 with\n                | (s2,n2)  => \n                   (s1 ++  s2 ++\n                   \"div(\" ++ show n1 ++ \",\" ++ show n2 ++ \");\",\n                   n1 + n2)\n              end\n        end\n end.\n\nCompute (eval_log0 (Div (Num 6) (Num 2))).\n(* ==> (\"num(6);num(2);div(6,2);\", 3) : string * nat *)\n\nCompute (eval_log0 (Div (Num 6) (Plus (Num 0) (Num 7)))).\n(* ==> (\"num(6);num(0);num(7);plus(0,7);div(6,7);\", 0) : string * nat *)\n\n(** Using a \"Log Monad\" *)\n\nDefinition LogString (X : Type) : Type := string * X.\n\nInstance monLogString : Monad LogString := \n{\n  bind := fun {A B : Type} (x : LogString A) (f : A -> LogString B) =>\n              let (s ,a) := x in \n              let (s',b) := f a in\n              (s ++ s',b) ;\n  ret := fun {A:Type} (x:A) => (\"\",x)\n}.\n\nDefinition tell {X : Type} (x : X) := (x, tt).\n\nFixpoint eval_log (e:exp) : LogString nat := \n  match e with \n    | Num n      => \n        _  <- tell (\"num(\" ++ show n ++ \");\") ;;\n        ret n\n    | Plus e1 e2 => \n        n1 <- eval_log e1 ;;\n        n2 <- eval_log e2 ;;\n        _  <- tell (\"plus(\" ++ show n1 ++ \",\" ++ show n2 ++ \");\") ;;\n        ret (n1 + n2)\n    | Div e1 e2  => \n        n1 <- eval_log e1 ;;\n        n2 <- eval_log e2 ;;\n        _  <- tell (\"div(\" ++ show n1 ++ \",\" ++ show n2 ++ \");\") ;;\n        ret (n1 / n2)\n  end.\n\nCompute (eval_log (Div (Num 6) (Num 2))).\n(* ==> (\"num(6);num(2);div(6,2);\", 3) : LogString nat *)\n\nCompute (eval_log (Div (Num 6) (Plus (Num 0) (Num 7)))).\n(* ==> (\"num(6);num(0);num(7);plus(0,7);div(6,7);\", 0) : LogString nat *)\n\n(** Similar example: *)\n\nFixpoint eval_cnt0 (e:exp) : nat * nat := \n  match e with \n   | Num n => (1,n)\n   | Plus e1 e2 => \n        match eval_cnt0 e1 with\n          (s1,n1) => \n              match eval_cnt0 e2 with\n                | (s2,n2)  => (s1 + s2 + 1, n1 + n2)\n              end\n        end\n   | Div e1 e2 => \n        match eval_cnt0 e1 with\n          (s1,n1) => \n              match eval_cnt0 e2 with\n                | (s2,n2)  => (s1 + s2 + 1, n1 / n2)\n              end\n        end\n end.\n\nCompute (eval_cnt0 (Div (Num 6) (Plus (Num 0) (Num 7)))).\n(* ==> (5, 0) : nat * nat *)\n\n(** Using a monad: *)\n\nDefinition LogNat (X : Type) : Type := nat * X.\n\nInstance monLogNat : Monad LogNat := \n{\n  bind := fun {A B : Type} (x : LogNat A) (f : A -> LogNat B) =>\n              let (s ,a) := x in \n              let (s',b) := f a in\n              (s + s',b) ;\n  ret := fun {A:Type} (x:A) => (0,x)\n}.\n\nFixpoint eval_cnt (e:exp) : LogNat nat := \n  match e with \n    | Num n      => _  <- tell 1 ;;\n                    ret n\n    | Plus e1 e2 => n1 <- eval_cnt e1 ;;\n                    n2 <- eval_cnt e2 ;;\n                    _  <- tell 1 ;;\n                    ret (n1 + n2)\n    | Div e1 e2  => n1 <- eval_cnt e1 ;;\n                    n2 <- eval_cnt e2 ;;\n                    _  <- tell 1 ;;\n                    ret (n1 / n2)\n  end.\n\nCompute (eval_cnt (Div (Num 6) (Plus (Num 0) (Num 7)))).\n(* ==> (5, 0) : LogNat nat *)\n\n(** Let's generalize... *)\n\nClass SemiGroup (A : Type) := {\n  dot : A -> A -> A;\n(*   assoc_dot : forall a b c : A, dot a (dot b c) = dot (dot a b) c *)\n}.\n\nClass Monoid (A : Type) {H : SemiGroup A} := {\n  id : A ;\n(*   proof_id : forall a : A, dot a id = a *)\n}.\n\nDefinition Writer (T : Type) {_ : SemiGroup T} {_: Monoid T}\n                  (X : Type) : Type := T * X.\n\nInstance monWriter (T : Type) (_ : SemiGroup T) (_: Monoid T): \n         Monad (Writer T) := \n{\n  bind := fun {A B : Type} (x : Writer T A) (f : A -> Writer T B) =>\n              let (s ,a) := x in \n              let (s',b) := f a in\n              (dot s s',b) ;\n  ret := fun {A:Type} (x:A) => (id,x)\n}.\n\nInstance stringSemiGroup : SemiGroup string := \n{\n  dot := append\n}.\n\nInstance stringMonoid : Monoid string := \n{\n  id := \"\"\n}.\n\nFixpoint eval_log' (e:exp) : Writer string nat := \n  match e with \n    | Num n      => \n        _  <- tell (\"num(\" ++ show n ++ \");\") ;;\n        ret n\n    | Plus e1 e2 => \n        n1 <- eval_log' e1 ;;\n        n2 <- eval_log' e2 ;;\n        _  <- tell (\"plus(\" ++ show n1 ++ \",\" ++ show n2 ++ \");\") ;;\n        ret (n1 + n2)\n    | Div e1 e2  => \n        n1 <- eval_log' e1 ;;\n        n2 <- eval_log' e2 ;;\n        _  <- tell (\"div(\" ++ show n1 ++ \",\" ++ show n2 ++ \");\") ;;\n        ret (n1 / n2)\n\n  end.\n\nCompute (eval_log' (Div (Num 6) (Plus (Num 0) (Num 7)))).\n(* ==> (\"num(6);num(0);num(7);plus(0,7);div(6,7);\", 0)  : Writer string nat *)\n\nInstance natSemiGroup : SemiGroup nat := \n{\n  dot := plus\n}.\n\nInstance natMonoid : Monoid nat := \n{\n  id := 0\n}.\n\nFixpoint eval_cnt' (e:exp) : Writer nat nat := \n  match e with \n    | Num n      => _  <- tell 1 ;;\n                    ret n\n    | Plus e1 e2 => n1 <- eval_cnt' e1 ;;\n                    n2 <- eval_cnt' e2 ;;\n                    _  <- tell 1 ;;\n                    ret (n1 + n2)\n    | Div e1 e2  => n1 <- eval_cnt' e1 ;;\n                    n2 <- eval_cnt' e2 ;;\n                    _  <- tell 1 ;;\n                    ret (n1 / n2)\n  end.\n\nCompute (eval_cnt' (Div (Num 6) (Plus (Num 0) (Num 7)))).\n(* ==> (5, 0) : Writer nat nat *)\n\nEnd Monads.\n\n(* 2022-11-13 16:26 *)\n", "meta": {"author": "yuval12311", "repo": "Formal-Foundations", "sha": "2a6f6fe1f703758f04348295aa8f537584b01669", "save_path": "github-repos/coq/yuval12311-Formal-Foundations", "path": "github-repos/coq/yuval12311-Formal-Foundations/Formal-Foundations-2a6f6fe1f703758f04348295aa8f537584b01669/MoreFP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6502622780350187}}
{"text": "Set Warnings \"-notation-overridden\".\n\nRequire Import Category.Lib.\nRequire Export Category.Theory.Unique.\nRequire Export Category.Structure.Cone.\n\nGeneralizable All Variables.\nSet Primitive Projections.\nSet Universe Polymorphism.\nUnset Transparent Obligations.\n\n(* Wikipedia: \"Let F : J ⟶ C be a diagram of shape J in a category C. A cone\n   to F is an object N of C together with a family ψX : N ⟶ F(X) of morphisms\n   indexed by the objects X of J, such that for every morphism f : X ⟶ Y in J,\n   we have F(f) ∘ ψX = ψY.\n\n   \"A limit of the diagram F : J ⟶ C is a cone (L, φ) to F such that for any\n   other cone (N, ψ) to F there exists a unique morphism u : N ⟶ L such that\n   φX ∘ u = ψX for all X in J.\n\n   \"One says that the cone (N, ψ) factors through the cone (L, φ) with the\n   unique factorization u. The morphism u is sometimes called the mediating\n   morphism.\" *)\n\nClass Limit `(F : J ⟶ C) := {\n  limit_cone : Cone F;\n\n  ump_limits : ∀ N : Cone F, ∃! u : N ~> limit_cone, ∀ x : J,\n    vertex_map[limit_cone] ∘ u ≈ @vertex_map _ _ _ N x\n}.\n\nCoercion limit_cone : Limit >-> Cone.\n\nRequire Import Category.Functor.Opposite.\n\nDefinition Colimit `(F : J ⟶ C) := Limit (F^op).\n", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/category-theory/Structure/Limit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.6501593504798161}}
{"text": "Require Import ords ssrfun ssrbool ssreflect.\nRequire Import Arith.\n\n(* pg32_inductive.v: #points = 15, #lines = 35 *)\n\nInductive Point :=\n| P0 | P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 | P11 | P12 | P13 | P14 .\n\nInductive Line :=\n| L0 | L1 | L2 | L3 | L4 | L5 | L6 | L7 | L8 | L9 | L10 | L11 | L12 | L13 | L14 | L15 | L16 | L17 | L18 | L19 | L20 | L21 | L22 | L23 | L24 | L25 | L26 | L27 | L28 | L29 | L30 | L31 | L32 | L33 | L34 .\n\nDefinition L2nat (l:Line) : nat := match l with \n| L0 => 0%nat\n| L1 => 1%nat\n| L2 => 2%nat\n| L3 => 3%nat\n| L4 => 4%nat\n| L5 => 5%nat\n| L6 => 6%nat\n| L7 => 7%nat\n| L8 => 8%nat\n| L9 => 9%nat\n| L10 => 10%nat\n| L11 => 11%nat\n| L12 => 12%nat\n| L13 => 13%nat\n| L14 => 14%nat\n| L15 => 15%nat\n| L16 => 16%nat\n| L17 => 17%nat\n| L18 => 18%nat\n| L19 => 19%nat\n| L20 => 20%nat\n| L21 => 21%nat\n| L22 => 22%nat\n| L23 => 23%nat\n| L24 => 24%nat\n| L25 => 25%nat\n| L26 => 26%nat\n| L27 => 27%nat\n| L28 => 28%nat\n| L29 => 29%nat\n| L30 => 30%nat\n| L31 => 31%nat\n| L32 => 32%nat\n| L33 => 33%nat\n| L34 => 34%nat\nend.\n\nDefinition eqL (x y:Line) : bool := Nat.eqb (L2nat x) (L2nat y).\n\nDefinition leL (x y: Line) : bool := leb (L2nat x) (L2nat y).\n\nLemma leL_total : forall A B, (leL A B) || (leL B A).\nSet Printing All.\nProof.\nintros A B; apply Bool.orb_true_iff;\ndestruct (le_ge_dec (L2nat A) (L2nat B));\n  [left; apply leb_correct; assumption |\nright; apply leb_correct; unfold ge in *; assumption].\nQed.\n\n\nDefinition P2nat (p:Point) : nat := match p with \n| P0 => 0%nat\n| P1 => 1%nat\n| P2 => 2%nat\n| P3 => 3%nat\n| P4 => 4%nat\n| P5 => 5%nat\n| P6 => 6%nat\n| P7 => 7%nat\n| P8 => 8%nat\n| P9 => 9%nat\n| P10 => 10%nat\n| P11 => 11%nat\n| P12 => 12%nat\n| P13 => 13%nat\n| P14 => 14%nat\nend.\n\nDefinition eqP (x y:Point)  : bool := Nat.eqb (P2nat x) (P2nat y).\n\nDefinition leP (x y: Point) : bool := leb (P2nat x) (P2nat y).\nLemma leP_total : forall A B, leP A B || leP B A.\nProof.\nintros A B; apply Bool.orb_true_iff;\ndestruct (le_ge_dec (P2nat A) (P2nat B));\n  [left; apply leb_correct; assumption |\nright; apply leb_correct; unfold ge in *; assumption].\nQed.\n\n\nDefinition incid_lp (p:Point) (l:Line) (* Point Line *) : bool := \nmatch l with \n| L0 => match p with P0 | P1 | P2 => true | _ => false end\n| L1 => match p with P0 | P3 | P4 => true | _ => false end\n| L2 => match p with P0 | P5 | P6 => true | _ => false end\n| L3 => match p with P0 | P7 | P8 => true | _ => false end\n| L4 => match p with P0 | P10 | P9 => true | _ => false end\n| L5 => match p with P0 | P11 | P12 => true | _ => false end\n| L6 => match p with P0 | P13 | P14 => true | _ => false end\n| L7 => match p with P1 | P4 | P6 => true | _ => false end\n| L8 => match p with P1 | P8 | P10 => true | _ => false end\n| L9 => match p with P1 | P12 | P14 => true | _ => false end\n| L10 => match p with P1 | P7 | P9 => true | _ => false end\n| L11 => match p with P1 | P13 | P11 => true | _ => false end\n| L12 => match p with P1 | P3 | P5 => true | _ => false end\n| L13 => match p with P2 | P7 | P10 => true | _ => false end\n| L14 => match p with P2 | P11 | P14 => true | _ => false end\n| L15 => match p with P2 | P3 | P6 => true | _ => false end\n| L16 => match p with P2 | P12 | P13 => true | _ => false end\n| L17 => match p with P2 | P4 | P5 => true | _ => false end\n| L18 => match p with P2 | P8 | P9 => true | _ => false end\n| L19 => match p with P3 | P10 | P14 => true | _ => false end\n| L20 => match p with P3 | P8 | P12 => true | _ => false end\n| L21 => match p with P3 | P9 | P13 => true | _ => false end\n| L22 => match p with P3 | P7 | P11 => true | _ => false end\n| L23 => match p with P4 | P9 | P14 => true | _ => false end\n| L24 => match p with P4 | P8 | P11 => true | _ => false end\n| L25 => match p with P4 | P10 | P13 => true | _ => false end\n| L26 => match p with P4 | P7 | P12 => true | _ => false end\n| L27 => match p with P5 | P8 | P14 => true | _ => false end\n| L28 => match p with P5 | P7 | P13 => true | _ => false end\n| L29 => match p with P5 | P9 | P11 => true | _ => false end\n| L30 => match p with P5 | P10 | P12 => true | _ => false end\n| L31 => match p with P6 | P7 | P14 => true | _ => false end\n| L32 => match p with P6 | P8 | P13 => true | _ => false end\n| L33 => match p with P6 | P9 | P12 => true | _ => false end\n| L34 => match p with P6 | P10 | P11 => true | _ => false end\nend.\n\nDefinition f_a2 (l:Line) (m:Line) :=\nmatch l with\n| L0 => match m with\n| L0 => P2\n| L1 => P0\n| L2 => P0\n| L3 => P0\n| L4 => P0\n| L5 => P0\n| L6 => P0\n| L7 => P1\n| L8 => P1\n| L9 => P1\n| L10 => P1\n| L11 => P1\n| L12 => P1\n| L13 => P2\n| L14 => P2\n| L15 => P2\n| L16 => P2\n| L17 => P2\n| L18 => P2\n| L19 => P0\n| L20 => P0\n| L21 => P0\n| L22 => P0\n| L23 => P0\n| L24 => P0\n| L25 => P0\n| L26 => P0\n| L27 => P0\n| L28 => P0\n| L29 => P0\n| L30 => P0\n| L31 => P0\n| L32 => P0\n| L33 => P0\n| L34 => P0\nend\n| L1 => match m with\n| L0 => P0\n| L1 => P4\n| L2 => P0\n| L3 => P0\n| L4 => P0\n| L5 => P0\n| L6 => P0\n| L7 => P4\n| L8 => P0\n| L9 => P0\n| L10 => P0\n| L11 => P0\n| L12 => P3\n| L13 => P0\n| L14 => P0\n| L15 => P3\n| L16 => P0\n| L17 => P4\n| L18 => P0\n| L19 => P3\n| L20 => P3\n| L21 => P3\n| L22 => P3\n| L23 => P4\n| L24 => P4\n| L25 => P4\n| L26 => P4\n| L27 => P0\n| L28 => P0\n| L29 => P0\n| L30 => P0\n| L31 => P0\n| L32 => P0\n| L33 => P0\n| L34 => P0\nend\n| L2 => match m with\n| L0 => P0\n| L1 => P0\n| L2 => P6\n| L3 => P0\n| L4 => P0\n| L5 => P0\n| L6 => P0\n| L7 => P6\n| L8 => P0\n| L9 => P0\n| L10 => P0\n| L11 => P0\n| L12 => P5\n| L13 => P0\n| L14 => P0\n| L15 => P6\n| L16 => P0\n| L17 => P5\n| L18 => P0\n| L19 => P0\n| L20 => P0\n| L21 => P0\n| L22 => P0\n| L23 => P0\n| L24 => P0\n| L25 => P0\n| L26 => P0\n| L27 => P5\n| L28 => P5\n| L29 => P5\n| L30 => P5\n| L31 => P6\n| L32 => P6\n| L33 => P6\n| L34 => P6\nend\n| L3 => match m with\n| L0 => P0\n| L1 => P0\n| L2 => P0\n| L3 => P8\n| L4 => P0\n| L5 => P0\n| L6 => P0\n| L7 => P0\n| L8 => P8\n| L9 => P0\n| L10 => P7\n| L11 => P0\n| L12 => P0\n| L13 => P7\n| L14 => P0\n| L15 => P0\n| L16 => P0\n| L17 => P0\n| L18 => P8\n| L19 => P0\n| L20 => P8\n| L21 => P0\n| L22 => P7\n| L23 => P0\n| L24 => P8\n| L25 => P0\n| L26 => P7\n| L27 => P8\n| L28 => P7\n| L29 => P0\n| L30 => P0\n| L31 => P7\n| L32 => P8\n| L33 => P0\n| L34 => P0\nend\n| L4 => match m with\n| L0 => P0\n| L1 => P0\n| L2 => P0\n| L3 => P0\n| L4 => P9\n| L5 => P0\n| L6 => P0\n| L7 => P0\n| L8 => P10\n| L9 => P0\n| L10 => P9\n| L11 => P0\n| L12 => P0\n| L13 => P10\n| L14 => P0\n| L15 => P0\n| L16 => P0\n| L17 => P0\n| L18 => P9\n| L19 => P10\n| L20 => P0\n| L21 => P9\n| L22 => P0\n| L23 => P9\n| L24 => P0\n| L25 => P10\n| L26 => P0\n| L27 => P0\n| L28 => P0\n| L29 => P9\n| L30 => P10\n| L31 => P0\n| L32 => P0\n| L33 => P9\n| L34 => P10\nend\n| L5 => match m with\n| L0 => P0\n| L1 => P0\n| L2 => P0\n| L3 => P0\n| L4 => P0\n| L5 => P12\n| L6 => P0\n| L7 => P0\n| L8 => P0\n| L9 => P12\n| L10 => P0\n| L11 => P11\n| L12 => P0\n| L13 => P0\n| L14 => P11\n| L15 => P0\n| L16 => P12\n| L17 => P0\n| L18 => P0\n| L19 => P0\n| L20 => P12\n| L21 => P0\n| L22 => P11\n| L23 => P0\n| L24 => P11\n| L25 => P0\n| L26 => P12\n| L27 => P0\n| L28 => P0\n| L29 => P11\n| L30 => P12\n| L31 => P0\n| L32 => P0\n| L33 => P12\n| L34 => P11\nend\n| L6 => match m with\n| L0 => P0\n| L1 => P0\n| L2 => P0\n| L3 => P0\n| L4 => P0\n| L5 => P0\n| L6 => P14\n| L7 => P0\n| L8 => P0\n| L9 => P14\n| L10 => P0\n| L11 => P13\n| L12 => P0\n| L13 => P0\n| L14 => P14\n| L15 => P0\n| L16 => P13\n| L17 => P0\n| L18 => P0\n| L19 => P14\n| L20 => P0\n| L21 => P13\n| L22 => P0\n| L23 => P14\n| L24 => P0\n| L25 => P13\n| L26 => P0\n| L27 => P14\n| L28 => P13\n| L29 => P0\n| L30 => P0\n| L31 => P14\n| L32 => P13\n| L33 => P0\n| L34 => P0\nend\n| L7 => match m with\n| L0 => P1\n| L1 => P4\n| L2 => P6\n| L3 => P0\n| L4 => P0\n| L5 => P0\n| L6 => P0\n| L7 => P6\n| L8 => P1\n| L9 => P1\n| L10 => P1\n| L11 => P1\n| L12 => P1\n| L13 => P0\n| L14 => P0\n| L15 => P6\n| L16 => P0\n| L17 => P4\n| L18 => P0\n| L19 => P0\n| L20 => P0\n| L21 => P0\n| L22 => P0\n| L23 => P4\n| L24 => P4\n| L25 => P4\n| L26 => P4\n| L27 => P0\n| L28 => P0\n| L29 => P0\n| L30 => P0\n| L31 => P6\n| L32 => P6\n| L33 => P6\n| L34 => P6\nend\n| L8 => match m with\n| L0 => P1\n| L1 => P0\n| L2 => P0\n| L3 => P8\n| L4 => P10\n| L5 => P0\n| L6 => P0\n| L7 => P1\n| L8 => P10\n| L9 => P1\n| L10 => P1\n| L11 => P1\n| L12 => P1\n| L13 => P10\n| L14 => P0\n| L15 => P0\n| L16 => P0\n| L17 => P0\n| L18 => P8\n| L19 => P10\n| L20 => P8\n| L21 => P0\n| L22 => P0\n| L23 => P0\n| L24 => P8\n| L25 => P10\n| L26 => P0\n| L27 => P8\n| L28 => P0\n| L29 => P0\n| L30 => P10\n| L31 => P0\n| L32 => P8\n| L33 => P0\n| L34 => P10\nend\n| L9 => match m with\n| L0 => P1\n| L1 => P0\n| L2 => P0\n| L3 => P0\n| L4 => P0\n| L5 => P12\n| L6 => P14\n| L7 => P1\n| L8 => P1\n| L9 => P14\n| L10 => P1\n| L11 => P1\n| L12 => P1\n| L13 => P0\n| L14 => P14\n| L15 => P0\n| L16 => P12\n| L17 => P0\n| L18 => P0\n| L19 => P14\n| L20 => P12\n| L21 => P0\n| L22 => P0\n| L23 => P14\n| L24 => P0\n| L25 => P0\n| L26 => P12\n| L27 => P14\n| L28 => P0\n| L29 => P0\n| L30 => P12\n| L31 => P14\n| L32 => P0\n| L33 => P12\n| L34 => P0\nend\n| L10 => match m with\n| L0 => P1\n| L1 => P0\n| L2 => P0\n| L3 => P7\n| L4 => P9\n| L5 => P0\n| L6 => P0\n| L7 => P1\n| L8 => P1\n| L9 => P1\n| L10 => P9\n| L11 => P1\n| L12 => P1\n| L13 => P7\n| L14 => P0\n| L15 => P0\n| L16 => P0\n| L17 => P0\n| L18 => P9\n| L19 => P0\n| L20 => P0\n| L21 => P9\n| L22 => P7\n| L23 => P9\n| L24 => P0\n| L25 => P0\n| L26 => P7\n| L27 => P0\n| L28 => P7\n| L29 => P9\n| L30 => P0\n| L31 => P7\n| L32 => P0\n| L33 => P9\n| L34 => P0\nend\n| L11 => match m with\n| L0 => P1\n| L1 => P0\n| L2 => P0\n| L3 => P0\n| L4 => P0\n| L5 => P11\n| L6 => P13\n| L7 => P1\n| L8 => P1\n| L9 => P1\n| L10 => P1\n| L11 => P11\n| L12 => P1\n| L13 => P0\n| L14 => P11\n| L15 => P0\n| L16 => P13\n| L17 => P0\n| L18 => P0\n| L19 => P0\n| L20 => P0\n| L21 => P13\n| L22 => P11\n| L23 => P0\n| L24 => P11\n| L25 => P13\n| L26 => P0\n| L27 => P0\n| L28 => P13\n| L29 => P11\n| L30 => P0\n| L31 => P0\n| L32 => P13\n| L33 => P0\n| L34 => P11\nend\n| L12 => match m with\n| L0 => P1\n| L1 => P3\n| L2 => P5\n| L3 => P0\n| L4 => P0\n| L5 => P0\n| L6 => P0\n| L7 => P1\n| L8 => P1\n| L9 => P1\n| L10 => P1\n| L11 => P1\n| L12 => P5\n| L13 => P0\n| L14 => P0\n| L15 => P3\n| L16 => P0\n| L17 => P5\n| L18 => P0\n| L19 => P3\n| L20 => P3\n| L21 => P3\n| L22 => P3\n| L23 => P0\n| L24 => P0\n| L25 => P0\n| L26 => P0\n| L27 => P5\n| L28 => P5\n| L29 => P5\n| L30 => P5\n| L31 => P0\n| L32 => P0\n| L33 => P0\n| L34 => P0\nend\n| L13 => match m with\n| L0 => P2\n| L1 => P0\n| L2 => P0\n| L3 => P7\n| L4 => P10\n| L5 => P0\n| L6 => P0\n| L7 => P0\n| L8 => P10\n| L9 => P0\n| L10 => P7\n| L11 => P0\n| L12 => P0\n| L13 => P10\n| L14 => P2\n| L15 => P2\n| L16 => P2\n| L17 => P2\n| L18 => P2\n| L19 => P10\n| L20 => P0\n| L21 => P0\n| L22 => P7\n| L23 => P0\n| L24 => P0\n| L25 => P10\n| L26 => P7\n| L27 => P0\n| L28 => P7\n| L29 => P0\n| L30 => P10\n| L31 => P7\n| L32 => P0\n| L33 => P0\n| L34 => P10\nend\n| L14 => match m with\n| L0 => P2\n| L1 => P0\n| L2 => P0\n| L3 => P0\n| L4 => P0\n| L5 => P11\n| L6 => P14\n| L7 => P0\n| L8 => P0\n| L9 => P14\n| L10 => P0\n| L11 => P11\n| L12 => P0\n| L13 => P2\n| L14 => P14\n| L15 => P2\n| L16 => P2\n| L17 => P2\n| L18 => P2\n| L19 => P14\n| L20 => P0\n| L21 => P0\n| L22 => P11\n| L23 => P14\n| L24 => P11\n| L25 => P0\n| L26 => P0\n| L27 => P14\n| L28 => P0\n| L29 => P11\n| L30 => P0\n| L31 => P14\n| L32 => P0\n| L33 => P0\n| L34 => P11\nend\n| L15 => match m with\n| L0 => P2\n| L1 => P3\n| L2 => P6\n| L3 => P0\n| L4 => P0\n| L5 => P0\n| L6 => P0\n| L7 => P6\n| L8 => P0\n| L9 => P0\n| L10 => P0\n| L11 => P0\n| L12 => P3\n| L13 => P2\n| L14 => P2\n| L15 => P6\n| L16 => P2\n| L17 => P2\n| L18 => P2\n| L19 => P3\n| L20 => P3\n| L21 => P3\n| L22 => P3\n| L23 => P0\n| L24 => P0\n| L25 => P0\n| L26 => P0\n| L27 => P0\n| L28 => P0\n| L29 => P0\n| L30 => P0\n| L31 => P6\n| L32 => P6\n| L33 => P6\n| L34 => P6\nend\n| L16 => match m with\n| L0 => P2\n| L1 => P0\n| L2 => P0\n| L3 => P0\n| L4 => P0\n| L5 => P12\n| L6 => P13\n| L7 => P0\n| L8 => P0\n| L9 => P12\n| L10 => P0\n| L11 => P13\n| L12 => P0\n| L13 => P2\n| L14 => P2\n| L15 => P2\n| L16 => P13\n| L17 => P2\n| L18 => P2\n| L19 => P0\n| L20 => P12\n| L21 => P13\n| L22 => P0\n| L23 => P0\n| L24 => P0\n| L25 => P13\n| L26 => P12\n| L27 => P0\n| L28 => P13\n| L29 => P0\n| L30 => P12\n| L31 => P0\n| L32 => P13\n| L33 => P12\n| L34 => P0\nend\n| L17 => match m with\n| L0 => P2\n| L1 => P4\n| L2 => P5\n| L3 => P0\n| L4 => P0\n| L5 => P0\n| L6 => P0\n| L7 => P4\n| L8 => P0\n| L9 => P0\n| L10 => P0\n| L11 => P0\n| L12 => P5\n| L13 => P2\n| L14 => P2\n| L15 => P2\n| L16 => P2\n| L17 => P5\n| L18 => P2\n| L19 => P0\n| L20 => P0\n| L21 => P0\n| L22 => P0\n| L23 => P4\n| L24 => P4\n| L25 => P4\n| L26 => P4\n| L27 => P5\n| L28 => P5\n| L29 => P5\n| L30 => P5\n| L31 => P0\n| L32 => P0\n| L33 => P0\n| L34 => P0\nend\n| L18 => match m with\n| L0 => P2\n| L1 => P0\n| L2 => P0\n| L3 => P8\n| L4 => P9\n| L5 => P0\n| L6 => P0\n| L7 => P0\n| L8 => P8\n| L9 => P0\n| L10 => P9\n| L11 => P0\n| L12 => P0\n| L13 => P2\n| L14 => P2\n| L15 => P2\n| L16 => P2\n| L17 => P2\n| L18 => P9\n| L19 => P0\n| L20 => P8\n| L21 => P9\n| L22 => P0\n| L23 => P9\n| L24 => P8\n| L25 => P0\n| L26 => P0\n| L27 => P8\n| L28 => P0\n| L29 => P9\n| L30 => P0\n| L31 => P0\n| L32 => P8\n| L33 => P9\n| L34 => P0\nend\n| L19 => match m with\n| L0 => P0\n| L1 => P3\n| L2 => P0\n| L3 => P0\n| L4 => P10\n| L5 => P0\n| L6 => P14\n| L7 => P0\n| L8 => P10\n| L9 => P14\n| L10 => P0\n| L11 => P0\n| L12 => P3\n| L13 => P10\n| L14 => P14\n| L15 => P3\n| L16 => P0\n| L17 => P0\n| L18 => P0\n| L19 => P14\n| L20 => P3\n| L21 => P3\n| L22 => P3\n| L23 => P14\n| L24 => P0\n| L25 => P10\n| L26 => P0\n| L27 => P14\n| L28 => P0\n| L29 => P0\n| L30 => P10\n| L31 => P14\n| L32 => P0\n| L33 => P0\n| L34 => P10\nend\n| L20 => match m with\n| L0 => P0\n| L1 => P3\n| L2 => P0\n| L3 => P8\n| L4 => P0\n| L5 => P12\n| L6 => P0\n| L7 => P0\n| L8 => P8\n| L9 => P12\n| L10 => P0\n| L11 => P0\n| L12 => P3\n| L13 => P0\n| L14 => P0\n| L15 => P3\n| L16 => P12\n| L17 => P0\n| L18 => P8\n| L19 => P3\n| L20 => P12\n| L21 => P3\n| L22 => P3\n| L23 => P0\n| L24 => P8\n| L25 => P0\n| L26 => P12\n| L27 => P8\n| L28 => P0\n| L29 => P0\n| L30 => P12\n| L31 => P0\n| L32 => P8\n| L33 => P12\n| L34 => P0\nend\n| L21 => match m with\n| L0 => P0\n| L1 => P3\n| L2 => P0\n| L3 => P0\n| L4 => P9\n| L5 => P0\n| L6 => P13\n| L7 => P0\n| L8 => P0\n| L9 => P0\n| L10 => P9\n| L11 => P13\n| L12 => P3\n| L13 => P0\n| L14 => P0\n| L15 => P3\n| L16 => P13\n| L17 => P0\n| L18 => P9\n| L19 => P3\n| L20 => P3\n| L21 => P13\n| L22 => P3\n| L23 => P9\n| L24 => P0\n| L25 => P13\n| L26 => P0\n| L27 => P0\n| L28 => P13\n| L29 => P9\n| L30 => P0\n| L31 => P0\n| L32 => P13\n| L33 => P9\n| L34 => P0\nend\n| L22 => match m with\n| L0 => P0\n| L1 => P3\n| L2 => P0\n| L3 => P7\n| L4 => P0\n| L5 => P11\n| L6 => P0\n| L7 => P0\n| L8 => P0\n| L9 => P0\n| L10 => P7\n| L11 => P11\n| L12 => P3\n| L13 => P7\n| L14 => P11\n| L15 => P3\n| L16 => P0\n| L17 => P0\n| L18 => P0\n| L19 => P3\n| L20 => P3\n| L21 => P3\n| L22 => P11\n| L23 => P0\n| L24 => P11\n| L25 => P0\n| L26 => P7\n| L27 => P0\n| L28 => P7\n| L29 => P11\n| L30 => P0\n| L31 => P7\n| L32 => P0\n| L33 => P0\n| L34 => P11\nend\n| L23 => match m with\n| L0 => P0\n| L1 => P4\n| L2 => P0\n| L3 => P0\n| L4 => P9\n| L5 => P0\n| L6 => P14\n| L7 => P4\n| L8 => P0\n| L9 => P14\n| L10 => P9\n| L11 => P0\n| L12 => P0\n| L13 => P0\n| L14 => P14\n| L15 => P0\n| L16 => P0\n| L17 => P4\n| L18 => P9\n| L19 => P14\n| L20 => P0\n| L21 => P9\n| L22 => P0\n| L23 => P14\n| L24 => P4\n| L25 => P4\n| L26 => P4\n| L27 => P14\n| L28 => P0\n| L29 => P9\n| L30 => P0\n| L31 => P14\n| L32 => P0\n| L33 => P9\n| L34 => P0\nend\n| L24 => match m with\n| L0 => P0\n| L1 => P4\n| L2 => P0\n| L3 => P8\n| L4 => P0\n| L5 => P11\n| L6 => P0\n| L7 => P4\n| L8 => P8\n| L9 => P0\n| L10 => P0\n| L11 => P11\n| L12 => P0\n| L13 => P0\n| L14 => P11\n| L15 => P0\n| L16 => P0\n| L17 => P4\n| L18 => P8\n| L19 => P0\n| L20 => P8\n| L21 => P0\n| L22 => P11\n| L23 => P4\n| L24 => P11\n| L25 => P4\n| L26 => P4\n| L27 => P8\n| L28 => P0\n| L29 => P11\n| L30 => P0\n| L31 => P0\n| L32 => P8\n| L33 => P0\n| L34 => P11\nend\n| L25 => match m with\n| L0 => P0\n| L1 => P4\n| L2 => P0\n| L3 => P0\n| L4 => P10\n| L5 => P0\n| L6 => P13\n| L7 => P4\n| L8 => P10\n| L9 => P0\n| L10 => P0\n| L11 => P13\n| L12 => P0\n| L13 => P10\n| L14 => P0\n| L15 => P0\n| L16 => P13\n| L17 => P4\n| L18 => P0\n| L19 => P10\n| L20 => P0\n| L21 => P13\n| L22 => P0\n| L23 => P4\n| L24 => P4\n| L25 => P13\n| L26 => P4\n| L27 => P0\n| L28 => P13\n| L29 => P0\n| L30 => P10\n| L31 => P0\n| L32 => P13\n| L33 => P0\n| L34 => P10\nend\n| L26 => match m with\n| L0 => P0\n| L1 => P4\n| L2 => P0\n| L3 => P7\n| L4 => P0\n| L5 => P12\n| L6 => P0\n| L7 => P4\n| L8 => P0\n| L9 => P12\n| L10 => P7\n| L11 => P0\n| L12 => P0\n| L13 => P7\n| L14 => P0\n| L15 => P0\n| L16 => P12\n| L17 => P4\n| L18 => P0\n| L19 => P0\n| L20 => P12\n| L21 => P0\n| L22 => P7\n| L23 => P4\n| L24 => P4\n| L25 => P4\n| L26 => P12\n| L27 => P0\n| L28 => P7\n| L29 => P0\n| L30 => P12\n| L31 => P7\n| L32 => P0\n| L33 => P12\n| L34 => P0\nend\n| L27 => match m with\n| L0 => P0\n| L1 => P0\n| L2 => P5\n| L3 => P8\n| L4 => P0\n| L5 => P0\n| L6 => P14\n| L7 => P0\n| L8 => P8\n| L9 => P14\n| L10 => P0\n| L11 => P0\n| L12 => P5\n| L13 => P0\n| L14 => P14\n| L15 => P0\n| L16 => P0\n| L17 => P5\n| L18 => P8\n| L19 => P14\n| L20 => P8\n| L21 => P0\n| L22 => P0\n| L23 => P14\n| L24 => P8\n| L25 => P0\n| L26 => P0\n| L27 => P14\n| L28 => P5\n| L29 => P5\n| L30 => P5\n| L31 => P14\n| L32 => P8\n| L33 => P0\n| L34 => P0\nend\n| L28 => match m with\n| L0 => P0\n| L1 => P0\n| L2 => P5\n| L3 => P7\n| L4 => P0\n| L5 => P0\n| L6 => P13\n| L7 => P0\n| L8 => P0\n| L9 => P0\n| L10 => P7\n| L11 => P13\n| L12 => P5\n| L13 => P7\n| L14 => P0\n| L15 => P0\n| L16 => P13\n| L17 => P5\n| L18 => P0\n| L19 => P0\n| L20 => P0\n| L21 => P13\n| L22 => P7\n| L23 => P0\n| L24 => P0\n| L25 => P13\n| L26 => P7\n| L27 => P5\n| L28 => P13\n| L29 => P5\n| L30 => P5\n| L31 => P7\n| L32 => P13\n| L33 => P0\n| L34 => P0\nend\n| L29 => match m with\n| L0 => P0\n| L1 => P0\n| L2 => P5\n| L3 => P0\n| L4 => P9\n| L5 => P11\n| L6 => P0\n| L7 => P0\n| L8 => P0\n| L9 => P0\n| L10 => P9\n| L11 => P11\n| L12 => P5\n| L13 => P0\n| L14 => P11\n| L15 => P0\n| L16 => P0\n| L17 => P5\n| L18 => P9\n| L19 => P0\n| L20 => P0\n| L21 => P9\n| L22 => P11\n| L23 => P9\n| L24 => P11\n| L25 => P0\n| L26 => P0\n| L27 => P5\n| L28 => P5\n| L29 => P11\n| L30 => P5\n| L31 => P0\n| L32 => P0\n| L33 => P9\n| L34 => P11\nend\n| L30 => match m with\n| L0 => P0\n| L1 => P0\n| L2 => P5\n| L3 => P0\n| L4 => P10\n| L5 => P12\n| L6 => P0\n| L7 => P0\n| L8 => P10\n| L9 => P12\n| L10 => P0\n| L11 => P0\n| L12 => P5\n| L13 => P10\n| L14 => P0\n| L15 => P0\n| L16 => P12\n| L17 => P5\n| L18 => P0\n| L19 => P10\n| L20 => P12\n| L21 => P0\n| L22 => P0\n| L23 => P0\n| L24 => P0\n| L25 => P10\n| L26 => P12\n| L27 => P5\n| L28 => P5\n| L29 => P5\n| L30 => P12\n| L31 => P0\n| L32 => P0\n| L33 => P12\n| L34 => P10\nend\n| L31 => match m with\n| L0 => P0\n| L1 => P0\n| L2 => P6\n| L3 => P7\n| L4 => P0\n| L5 => P0\n| L6 => P14\n| L7 => P6\n| L8 => P0\n| L9 => P14\n| L10 => P7\n| L11 => P0\n| L12 => P0\n| L13 => P7\n| L14 => P14\n| L15 => P6\n| L16 => P0\n| L17 => P0\n| L18 => P0\n| L19 => P14\n| L20 => P0\n| L21 => P0\n| L22 => P7\n| L23 => P14\n| L24 => P0\n| L25 => P0\n| L26 => P7\n| L27 => P14\n| L28 => P7\n| L29 => P0\n| L30 => P0\n| L31 => P14\n| L32 => P6\n| L33 => P6\n| L34 => P6\nend\n| L32 => match m with\n| L0 => P0\n| L1 => P0\n| L2 => P6\n| L3 => P8\n| L4 => P0\n| L5 => P0\n| L6 => P13\n| L7 => P6\n| L8 => P8\n| L9 => P0\n| L10 => P0\n| L11 => P13\n| L12 => P0\n| L13 => P0\n| L14 => P0\n| L15 => P6\n| L16 => P13\n| L17 => P0\n| L18 => P8\n| L19 => P0\n| L20 => P8\n| L21 => P13\n| L22 => P0\n| L23 => P0\n| L24 => P8\n| L25 => P13\n| L26 => P0\n| L27 => P8\n| L28 => P13\n| L29 => P0\n| L30 => P0\n| L31 => P6\n| L32 => P13\n| L33 => P6\n| L34 => P6\nend\n| L33 => match m with\n| L0 => P0\n| L1 => P0\n| L2 => P6\n| L3 => P0\n| L4 => P9\n| L5 => P12\n| L6 => P0\n| L7 => P6\n| L8 => P0\n| L9 => P12\n| L10 => P9\n| L11 => P0\n| L12 => P0\n| L13 => P0\n| L14 => P0\n| L15 => P6\n| L16 => P12\n| L17 => P0\n| L18 => P9\n| L19 => P0\n| L20 => P12\n| L21 => P9\n| L22 => P0\n| L23 => P9\n| L24 => P0\n| L25 => P0\n| L26 => P12\n| L27 => P0\n| L28 => P0\n| L29 => P9\n| L30 => P12\n| L31 => P6\n| L32 => P6\n| L33 => P12\n| L34 => P6\nend\n| L34 => match m with\n| L0 => P0\n| L1 => P0\n| L2 => P6\n| L3 => P0\n| L4 => P10\n| L5 => P11\n| L6 => P0\n| L7 => P6\n| L8 => P10\n| L9 => P0\n| L10 => P0\n| L11 => P11\n| L12 => P0\n| L13 => P10\n| L14 => P11\n| L15 => P6\n| L16 => P0\n| L17 => P0\n| L18 => P0\n| L19 => P10\n| L20 => P0\n| L21 => P0\n| L22 => P11\n| L23 => P0\n| L24 => P11\n| L25 => P10\n| L26 => P0\n| L27 => P0\n| L28 => P0\n| L29 => P11\n| L30 => P10\n| L31 => P6\n| L32 => P6\n| L33 => P6\n| L34 => P11\nend\nend.\n\nDefinition l_from_points (x:Point) (y:Point) : Line :=\nmatch x with\n| P0 =>\nmatch y with \n| P0 => L0\n| P1 => L0\n| P2 => L0\n| P3 => L1\n| P4 => L1\n| P5 => L2\n| P6 => L2\n| P7 => L3\n| P8 => L3\n| P9 => L4\n| P10 => L4\n| P11 => L5\n| P12 => L5\n| P13 => L6\n| P14 => L6\nend\n| P1 =>\nmatch y with \n| P0 => L0\n| P1 => L0\n| P2 => L0\n| P3 => L12\n| P4 => L7\n| P5 => L12\n| P6 => L7\n| P7 => L10\n| P8 => L8\n| P9 => L10\n| P10 => L8\n| P11 => L11\n| P12 => L9\n| P13 => L11\n| P14 => L9\nend\n| P2 =>\nmatch y with \n| P0 => L0\n| P1 => L0\n| P2 => L0\n| P3 => L15\n| P4 => L17\n| P5 => L17\n| P6 => L15\n| P7 => L13\n| P8 => L18\n| P9 => L18\n| P10 => L13\n| P11 => L14\n| P12 => L16\n| P13 => L16\n| P14 => L14\nend\n| P3 =>\nmatch y with \n| P0 => L1\n| P1 => L12\n| P2 => L15\n| P3 => L1\n| P4 => L1\n| P5 => L12\n| P6 => L15\n| P7 => L22\n| P8 => L20\n| P9 => L21\n| P10 => L19\n| P11 => L22\n| P12 => L20\n| P13 => L21\n| P14 => L19\nend\n| P4 =>\nmatch y with \n| P0 => L1\n| P1 => L7\n| P2 => L17\n| P3 => L1\n| P4 => L1\n| P5 => L17\n| P6 => L7\n| P7 => L26\n| P8 => L24\n| P9 => L23\n| P10 => L25\n| P11 => L24\n| P12 => L26\n| P13 => L25\n| P14 => L23\nend\n| P5 =>\nmatch y with \n| P0 => L2\n| P1 => L12\n| P2 => L17\n| P3 => L12\n| P4 => L17\n| P5 => L2\n| P6 => L2\n| P7 => L28\n| P8 => L27\n| P9 => L29\n| P10 => L30\n| P11 => L29\n| P12 => L30\n| P13 => L28\n| P14 => L27\nend\n| P6 =>\nmatch y with \n| P0 => L2\n| P1 => L7\n| P2 => L15\n| P3 => L15\n| P4 => L7\n| P5 => L2\n| P6 => L2\n| P7 => L31\n| P8 => L32\n| P9 => L33\n| P10 => L34\n| P11 => L34\n| P12 => L33\n| P13 => L32\n| P14 => L31\nend\n| P7 =>\nmatch y with \n| P0 => L3\n| P1 => L10\n| P2 => L13\n| P3 => L22\n| P4 => L26\n| P5 => L28\n| P6 => L31\n| P7 => L3\n| P8 => L3\n| P9 => L10\n| P10 => L13\n| P11 => L22\n| P12 => L26\n| P13 => L28\n| P14 => L31\nend\n| P8 =>\nmatch y with \n| P0 => L3\n| P1 => L8\n| P2 => L18\n| P3 => L20\n| P4 => L24\n| P5 => L27\n| P6 => L32\n| P7 => L3\n| P8 => L3\n| P9 => L18\n| P10 => L8\n| P11 => L24\n| P12 => L20\n| P13 => L32\n| P14 => L27\nend\n| P9 =>\nmatch y with \n| P0 => L4\n| P1 => L10\n| P2 => L18\n| P3 => L21\n| P4 => L23\n| P5 => L29\n| P6 => L33\n| P7 => L10\n| P8 => L18\n| P9 => L4\n| P10 => L4\n| P11 => L29\n| P12 => L33\n| P13 => L21\n| P14 => L23\nend\n| P10 =>\nmatch y with \n| P0 => L4\n| P1 => L8\n| P2 => L13\n| P3 => L19\n| P4 => L25\n| P5 => L30\n| P6 => L34\n| P7 => L13\n| P8 => L8\n| P9 => L4\n| P10 => L4\n| P11 => L34\n| P12 => L30\n| P13 => L25\n| P14 => L19\nend\n| P11 =>\nmatch y with \n| P0 => L5\n| P1 => L11\n| P2 => L14\n| P3 => L22\n| P4 => L24\n| P5 => L29\n| P6 => L34\n| P7 => L22\n| P8 => L24\n| P9 => L29\n| P10 => L34\n| P11 => L5\n| P12 => L5\n| P13 => L11\n| P14 => L14\nend\n| P12 =>\nmatch y with \n| P0 => L5\n| P1 => L9\n| P2 => L16\n| P3 => L20\n| P4 => L26\n| P5 => L30\n| P6 => L33\n| P7 => L26\n| P8 => L20\n| P9 => L33\n| P10 => L30\n| P11 => L5\n| P12 => L5\n| P13 => L16\n| P14 => L9\nend\n| P13 =>\nmatch y with \n| P0 => L6\n| P1 => L11\n| P2 => L16\n| P3 => L21\n| P4 => L25\n| P5 => L28\n| P6 => L32\n| P7 => L28\n| P8 => L32\n| P9 => L21\n| P10 => L25\n| P11 => L11\n| P12 => L16\n| P13 => L6\n| P14 => L6\nend\n| P14 =>\nmatch y with \n| P0 => L6\n| P1 => L9\n| P2 => L14\n| P3 => L19\n| P4 => L23\n| P5 => L27\n| P6 => L31\n| P7 => L31\n| P8 => L27\n| P9 => L23\n| P10 => L19\n| P11 => L14\n| P12 => L9\n| P13 => L6\n| P14 => L6\nend\nend.\n\nCheck l_from_points.\n\nDefinition points_from_line (l:Line) := \nmatch l with \n| L0  =>  (P0,P1,P2) \n| L1  =>  (P0,P3,P4) \n| L2  =>  (P0,P5,P6) \n| L3  =>  (P0,P7,P8) \n| L4  =>  (P0,P10,P9) \n| L5  =>  (P0,P11,P12) \n| L6  =>  (P0,P13,P14) \n| L7  =>  (P1,P4,P6) \n| L8  =>  (P1,P8,P10) \n| L9  =>  (P1,P12,P14) \n| L10  =>  (P1,P7,P9) \n| L11  =>  (P1,P13,P11) \n| L12  =>  (P1,P3,P5) \n| L13  =>  (P2,P7,P10) \n| L14  =>  (P2,P11,P14) \n| L15  =>  (P2,P3,P6) \n| L16  =>  (P2,P12,P13) \n| L17  =>  (P2,P4,P5) \n| L18  =>  (P2,P8,P9) \n| L19  =>  (P3,P10,P14) \n| L20  =>  (P3,P8,P12) \n| L21  =>  (P3,P9,P13) \n| L22  =>  (P3,P7,P11) \n| L23  =>  (P4,P9,P14) \n| L24  =>  (P4,P8,P11) \n| L25  =>  (P4,P10,P13) \n| L26  =>  (P4,P7,P12) \n| L27  =>  (P5,P8,P14) \n| L28  =>  (P5,P7,P13) \n| L29  =>  (P5,P9,P11) \n| L30  =>  (P5,P10,P12) \n| L31  =>  (P6,P7,P14) \n| L32  =>  (P6,P8,P13) \n| L33  =>  (P6,P9,P12) \n| L34  =>  (P6,P10,P11) \n end.\n\nCheck points_from_line.\n\nDefinition f_a3_3 (l1:Line) (l2:Line) (l3:Line) := \nmatch l3 with\n | L0 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L1 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L2 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                  | L2 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L3 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                  | L2 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                  | L2 => (L0,(P0,P0,P0)) \n                  | L3 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L4 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                  | L2 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                  | L2 => (L0,(P0,P0,P0)) \n                  | L3 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                  | L2 => (L0,(P0,P0,P0)) \n                  | L3 => (L0,(P0,P0,P0)) \n                  | L4 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L5 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                  | L2 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                  | L2 => (L0,(P0,P0,P0)) \n                  | L3 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                  | L2 => (L0,(P0,P0,P0)) \n                  | L3 => (L0,(P0,P0,P0)) \n                  | L4 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                  | L2 => (L0,(P0,P0,P0)) \n                  | L3 => (L0,(P0,P0,P0)) \n                  | L4 => (L0,(P0,P0,P0)) \n                  | L5 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L6 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                  | L2 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                  | L2 => (L0,(P0,P0,P0)) \n                  | L3 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                  | L2 => (L0,(P0,P0,P0)) \n                  | L3 => (L0,(P0,P0,P0)) \n                  | L4 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                  | L2 => (L0,(P0,P0,P0)) \n                  | L3 => (L0,(P0,P0,P0)) \n                  | L4 => (L0,(P0,P0,P0)) \n                  | L5 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L0,(P0,P0,P0)) \n                  | L1 => (L0,(P0,P0,P0)) \n                  | L2 => (L0,(P0,P0,P0)) \n                  | L3 => (L0,(P0,P0,P0)) \n                  | L4 => (L0,(P0,P0,P0)) \n                  | L5 => (L0,(P0,P0,P0)) \n                  | L6 => (L0,(P0,P0,P0)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L7 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                  | L5 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                  | L5 => (L0,(P0,P0,P1)) \n                  | L6 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L8 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                  | L5 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                  | L5 => (L0,(P0,P0,P1)) \n                  | L6 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                  | L8 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L9 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                  | L5 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                  | L5 => (L0,(P0,P0,P1)) \n                  | L6 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                  | L8 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                  | L8 => (L0,(P1,P1,P1)) \n                  | L9 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L10 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                  | L5 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                  | L5 => (L0,(P0,P0,P1)) \n                  | L6 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                  | L8 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                  | L8 => (L0,(P1,P1,P1)) \n                  | L9 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                  | L8 => (L0,(P1,P1,P1)) \n                  | L9 => (L0,(P1,P1,P1)) \n                  | L10 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L11 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                  | L5 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                  | L5 => (L0,(P0,P0,P1)) \n                  | L6 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                  | L8 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                  | L8 => (L0,(P1,P1,P1)) \n                  | L9 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                  | L8 => (L0,(P1,P1,P1)) \n                  | L9 => (L0,(P1,P1,P1)) \n                  | L10 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                  | L8 => (L0,(P1,P1,P1)) \n                  | L9 => (L0,(P1,P1,P1)) \n                  | L10 => (L0,(P1,P1,P1)) \n                  | L11 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L12 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                  | L5 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L0,(P0,P0,P1)) \n                  | L1 => (L0,(P0,P0,P1)) \n                  | L2 => (L0,(P0,P0,P1)) \n                  | L3 => (L0,(P0,P0,P1)) \n                  | L4 => (L0,(P0,P0,P1)) \n                  | L5 => (L0,(P0,P0,P1)) \n                  | L6 => (L0,(P0,P0,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                  | L8 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                  | L8 => (L0,(P1,P1,P1)) \n                  | L9 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                  | L8 => (L0,(P1,P1,P1)) \n                  | L9 => (L0,(P1,P1,P1)) \n                  | L10 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                  | L8 => (L0,(P1,P1,P1)) \n                  | L9 => (L0,(P1,P1,P1)) \n                  | L10 => (L0,(P1,P1,P1)) \n                  | L11 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L0,(P0,P1,P1)) \n                  | L1 => (L0,(P0,P1,P1)) \n                  | L2 => (L0,(P0,P1,P1)) \n                  | L3 => (L0,(P0,P1,P1)) \n                  | L4 => (L0,(P0,P1,P1)) \n                  | L5 => (L0,(P0,P1,P1)) \n                  | L6 => (L0,(P0,P1,P1)) \n                  | L7 => (L0,(P1,P1,P1)) \n                  | L8 => (L0,(P1,P1,P1)) \n                  | L9 => (L0,(P1,P1,P1)) \n                  | L10 => (L0,(P1,P1,P1)) \n                  | L11 => (L0,(P1,P1,P1)) \n                  | L12 => (L0,(P1,P1,P1)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L13 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                  | L5 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                  | L5 => (L0,(P0,P0,P2)) \n                  | L6 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                  | L11 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                  | L11 => (L0,(P1,P1,P2)) \n                  | L12 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L14 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                  | L5 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                  | L5 => (L0,(P0,P0,P2)) \n                  | L6 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                  | L11 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                  | L11 => (L0,(P1,P1,P2)) \n                  | L12 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                  | L14 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L15 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                  | L5 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                  | L5 => (L0,(P0,P0,P2)) \n                  | L6 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                  | L11 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                  | L11 => (L0,(P1,P1,P2)) \n                  | L12 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                  | L14 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                  | L14 => (L0,(P2,P2,P2)) \n                  | L15 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L16 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                  | L5 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                  | L5 => (L0,(P0,P0,P2)) \n                  | L6 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                  | L11 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                  | L11 => (L0,(P1,P1,P2)) \n                  | L12 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                  | L14 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                  | L14 => (L0,(P2,P2,P2)) \n                  | L15 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                  | L14 => (L0,(P2,P2,P2)) \n                  | L15 => (L0,(P2,P2,P2)) \n                  | L16 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L17 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                  | L5 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                  | L5 => (L0,(P0,P0,P2)) \n                  | L6 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                  | L11 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                  | L11 => (L0,(P1,P1,P2)) \n                  | L12 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                  | L14 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                  | L14 => (L0,(P2,P2,P2)) \n                  | L15 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                  | L14 => (L0,(P2,P2,P2)) \n                  | L15 => (L0,(P2,P2,P2)) \n                  | L16 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                  | L14 => (L0,(P2,P2,P2)) \n                  | L15 => (L0,(P2,P2,P2)) \n                  | L16 => (L0,(P2,P2,P2)) \n                  | L17 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L18 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                  | L5 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L0,(P0,P0,P2)) \n                  | L1 => (L0,(P0,P0,P2)) \n                  | L2 => (L0,(P0,P0,P2)) \n                  | L3 => (L0,(P0,P0,P2)) \n                  | L4 => (L0,(P0,P0,P2)) \n                  | L5 => (L0,(P0,P0,P2)) \n                  | L6 => (L0,(P0,P0,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                  | L11 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L0,(P0,P1,P2)) \n                  | L1 => (L0,(P0,P1,P2)) \n                  | L2 => (L0,(P0,P1,P2)) \n                  | L3 => (L0,(P0,P1,P2)) \n                  | L4 => (L0,(P0,P1,P2)) \n                  | L5 => (L0,(P0,P1,P2)) \n                  | L6 => (L0,(P0,P1,P2)) \n                  | L7 => (L0,(P1,P1,P2)) \n                  | L8 => (L0,(P1,P1,P2)) \n                  | L9 => (L0,(P1,P1,P2)) \n                  | L10 => (L0,(P1,P1,P2)) \n                  | L11 => (L0,(P1,P1,P2)) \n                  | L12 => (L0,(P1,P1,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                  | L14 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                  | L14 => (L0,(P2,P2,P2)) \n                  | L15 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                  | L14 => (L0,(P2,P2,P2)) \n                  | L15 => (L0,(P2,P2,P2)) \n                  | L16 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                  | L14 => (L0,(P2,P2,P2)) \n                  | L15 => (L0,(P2,P2,P2)) \n                  | L16 => (L0,(P2,P2,P2)) \n                  | L17 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L0,(P0,P2,P2)) \n                  | L1 => (L0,(P0,P2,P2)) \n                  | L2 => (L0,(P0,P2,P2)) \n                  | L3 => (L0,(P0,P2,P2)) \n                  | L4 => (L0,(P0,P2,P2)) \n                  | L5 => (L0,(P0,P2,P2)) \n                  | L6 => (L0,(P0,P2,P2)) \n                  | L7 => (L0,(P1,P2,P2)) \n                  | L8 => (L0,(P1,P2,P2)) \n                  | L9 => (L0,(P1,P2,P2)) \n                  | L10 => (L0,(P1,P2,P2)) \n                  | L11 => (L0,(P1,P2,P2)) \n                  | L12 => (L0,(P1,P2,P2)) \n                  | L13 => (L0,(P2,P2,P2)) \n                  | L14 => (L0,(P2,P2,P2)) \n                  | L15 => (L0,(P2,P2,P2)) \n                  | L16 => (L0,(P2,P2,P2)) \n                  | L17 => (L0,(P2,P2,P2)) \n                  | L18 => (L0,(P2,P2,P2)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L19 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                  | L4 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                  | L4 => (L1,(P0,P0,P3)) \n                  | L5 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                  | L4 => (L1,(P0,P0,P3)) \n                  | L5 => (L1,(P0,P0,P3)) \n                  | L6 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L1,(P0,P4,P3)) \n                  | L1 => (L1,(P0,P4,P3)) \n                  | L2 => (L1,(P0,P4,P3)) \n                  | L3 => (L1,(P0,P4,P3)) \n                  | L4 => (L1,(P0,P4,P3)) \n                  | L5 => (L1,(P0,P4,P3)) \n                  | L6 => (L1,(P0,P4,P3)) \n                  | L7 => (L1,(P4,P4,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L4,(P0,P10,P10)) \n                  | L1 => (L4,(P0,P10,P10)) \n                  | L2 => (L4,(P0,P10,P10)) \n                  | L3 => (L4,(P0,P10,P10)) \n                  | L4 => (L4,(P0,P10,P10)) \n                  | L5 => (L4,(P0,P10,P10)) \n                  | L6 => (L4,(P0,P10,P10)) \n                  | L7 => (L8,(P1,P1,P10)) \n                  | L8 => (L4,(P10,P10,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L6,(P0,P14,P14)) \n                  | L1 => (L6,(P0,P14,P14)) \n                  | L2 => (L6,(P0,P14,P14)) \n                  | L3 => (L6,(P0,P14,P14)) \n                  | L4 => (L6,(P0,P14,P14)) \n                  | L5 => (L6,(P0,P14,P14)) \n                  | L6 => (L6,(P0,P14,P14)) \n                  | L7 => (L8,(P1,P1,P10)) \n                  | L8 => (L8,(P1,P1,P10)) \n                  | L9 => (L6,(P14,P14,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L4,(P0,P9,P10)) \n                  | L1 => (L4,(P0,P9,P10)) \n                  | L2 => (L4,(P0,P9,P10)) \n                  | L3 => (L4,(P0,P9,P10)) \n                  | L4 => (L4,(P0,P9,P10)) \n                  | L5 => (L4,(P0,P9,P10)) \n                  | L6 => (L4,(P0,P9,P10)) \n                  | L7 => (L8,(P1,P1,P10)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L8,(P1,P1,P10)) \n                  | L10 => (L4,(P9,P9,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L6,(P0,P13,P14)) \n                  | L1 => (L6,(P0,P13,P14)) \n                  | L2 => (L6,(P0,P13,P14)) \n                  | L3 => (L6,(P0,P13,P14)) \n                  | L4 => (L6,(P0,P13,P14)) \n                  | L5 => (L6,(P0,P13,P14)) \n                  | L6 => (L6,(P0,P13,P14)) \n                  | L7 => (L8,(P1,P1,P10)) \n                  | L8 => (L8,(P1,P1,P10)) \n                  | L9 => (L6,(P14,P13,P14)) \n                  | L10 => (L8,(P1,P1,P10)) \n                  | L11 => (L6,(P13,P13,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L8,(P1,P1,P10)) \n                  | L9 => (L8,(P1,P1,P10)) \n                  | L10 => (L8,(P1,P1,P10)) \n                  | L11 => (L8,(P1,P1,P10)) \n                  | L12 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L4,(P0,P10,P10)) \n                  | L1 => (L4,(P0,P10,P10)) \n                  | L2 => (L4,(P0,P10,P10)) \n                  | L3 => (L4,(P0,P10,P10)) \n                  | L4 => (L4,(P0,P10,P10)) \n                  | L5 => (L4,(P0,P10,P10)) \n                  | L6 => (L4,(P0,P10,P10)) \n                  | L7 => (L8,(P1,P10,P10)) \n                  | L8 => (L4,(P10,P10,P10)) \n                  | L9 => (L8,(P1,P10,P10)) \n                  | L10 => (L4,(P9,P10,P10)) \n                  | L11 => (L8,(P1,P10,P10)) \n                  | L12 => (L8,(P1,P10,P10)) \n                  | L13 => (L4,(P10,P10,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L6,(P0,P14,P14)) \n                  | L1 => (L6,(P0,P14,P14)) \n                  | L2 => (L6,(P0,P14,P14)) \n                  | L3 => (L6,(P0,P14,P14)) \n                  | L4 => (L6,(P0,P14,P14)) \n                  | L5 => (L6,(P0,P14,P14)) \n                  | L6 => (L6,(P0,P14,P14)) \n                  | L7 => (L9,(P1,P14,P14)) \n                  | L8 => (L9,(P1,P14,P14)) \n                  | L9 => (L6,(P14,P14,P14)) \n                  | L10 => (L9,(P1,P14,P14)) \n                  | L11 => (L6,(P13,P14,P14)) \n                  | L12 => (L9,(P1,P14,P14)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L6,(P14,P14,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L12,(P1,P3,P3)) \n                  | L9 => (L12,(P1,P3,P3)) \n                  | L10 => (L12,(P1,P3,P3)) \n                  | L11 => (L12,(P1,P3,P3)) \n                  | L12 => (L1,(P3,P3,P3)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L13,(P2,P2,P10)) \n                  | L15 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L6,(P0,P13,P14)) \n                  | L1 => (L6,(P0,P13,P14)) \n                  | L2 => (L6,(P0,P13,P14)) \n                  | L3 => (L6,(P0,P13,P14)) \n                  | L4 => (L6,(P0,P13,P14)) \n                  | L5 => (L6,(P0,P13,P14)) \n                  | L6 => (L6,(P0,P13,P14)) \n                  | L7 => (L9,(P1,P12,P14)) \n                  | L8 => (L9,(P1,P12,P14)) \n                  | L9 => (L6,(P14,P13,P14)) \n                  | L10 => (L9,(P1,P12,P14)) \n                  | L11 => (L6,(P13,P13,P14)) \n                  | L12 => (L9,(P1,P12,P14)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L6,(P14,P13,P14)) \n                  | L15 => (L13,(P2,P2,P10)) \n                  | L16 => (L6,(P13,P13,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L1,(P0,P4,P3)) \n                  | L1 => (L1,(P0,P4,P3)) \n                  | L2 => (L1,(P0,P4,P3)) \n                  | L3 => (L1,(P0,P4,P3)) \n                  | L4 => (L1,(P0,P4,P3)) \n                  | L5 => (L1,(P0,P4,P3)) \n                  | L6 => (L1,(P0,P4,P3)) \n                  | L7 => (L1,(P4,P4,P3)) \n                  | L8 => (L12,(P1,P5,P3)) \n                  | L9 => (L12,(P1,P5,P3)) \n                  | L10 => (L12,(P1,P5,P3)) \n                  | L11 => (L12,(P1,P5,P3)) \n                  | L12 => (L1,(P3,P4,P3)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L13,(P2,P2,P10)) \n                  | L15 => (L1,(P3,P4,P3)) \n                  | L16 => (L13,(P2,P2,P10)) \n                  | L17 => (L1,(P4,P4,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L4,(P0,P9,P10)) \n                  | L1 => (L4,(P0,P9,P10)) \n                  | L2 => (L4,(P0,P9,P10)) \n                  | L3 => (L4,(P0,P9,P10)) \n                  | L4 => (L4,(P0,P9,P10)) \n                  | L5 => (L4,(P0,P9,P10)) \n                  | L6 => (L4,(P0,P9,P10)) \n                  | L7 => (L8,(P1,P8,P10)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L8,(P1,P8,P10)) \n                  | L10 => (L4,(P9,P9,P10)) \n                  | L11 => (L8,(P1,P8,P10)) \n                  | L12 => (L8,(P1,P8,P10)) \n                  | L13 => (L4,(P10,P9,P10)) \n                  | L14 => (L13,(P2,P2,P10)) \n                  | L15 => (L13,(P2,P2,P10)) \n                  | L16 => (L13,(P2,P2,P10)) \n                  | L17 => (L13,(P2,P2,P10)) \n                  | L18 => (L4,(P9,P9,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L4,(P10,P10,P10)) \n                  | L9 => (L6,(P14,P14,P14)) \n                  | L10 => (L4,(P9,P10,P10)) \n                  | L11 => (L6,(P13,P14,P14)) \n                  | L12 => (L1,(P3,P3,P3)) \n                  | L13 => (L4,(P10,P10,P10)) \n                  | L14 => (L6,(P14,P14,P14)) \n                  | L15 => (L1,(P3,P3,P3)) \n                  | L16 => (L6,(P13,P14,P14)) \n                  | L17 => (L1,(P4,P3,P3)) \n                  | L18 => (L4,(P9,P10,P10)) \n                  | L19 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L20 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                  | L4 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                  | L4 => (L1,(P0,P0,P3)) \n                  | L5 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                  | L4 => (L1,(P0,P0,P3)) \n                  | L5 => (L1,(P0,P0,P3)) \n                  | L6 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L1,(P0,P4,P3)) \n                  | L1 => (L1,(P0,P4,P3)) \n                  | L2 => (L1,(P0,P4,P3)) \n                  | L3 => (L1,(P0,P4,P3)) \n                  | L4 => (L1,(P0,P4,P3)) \n                  | L5 => (L1,(P0,P4,P3)) \n                  | L6 => (L1,(P0,P4,P3)) \n                  | L7 => (L1,(P4,P4,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L3,(P0,P8,P8)) \n                  | L1 => (L3,(P0,P8,P8)) \n                  | L2 => (L3,(P0,P8,P8)) \n                  | L3 => (L3,(P0,P8,P8)) \n                  | L4 => (L3,(P0,P8,P8)) \n                  | L5 => (L3,(P0,P8,P8)) \n                  | L6 => (L3,(P0,P8,P8)) \n                  | L7 => (L8,(P1,P1,P8)) \n                  | L8 => (L3,(P8,P8,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L5,(P0,P12,P12)) \n                  | L1 => (L5,(P0,P12,P12)) \n                  | L2 => (L5,(P0,P12,P12)) \n                  | L3 => (L5,(P0,P12,P12)) \n                  | L4 => (L5,(P0,P12,P12)) \n                  | L5 => (L5,(P0,P12,P12)) \n                  | L6 => (L5,(P0,P12,P12)) \n                  | L7 => (L8,(P1,P1,P8)) \n                  | L8 => (L8,(P1,P1,P8)) \n                  | L9 => (L5,(P12,P12,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L3,(P0,P7,P8)) \n                  | L1 => (L3,(P0,P7,P8)) \n                  | L2 => (L3,(P0,P7,P8)) \n                  | L3 => (L3,(P0,P7,P8)) \n                  | L4 => (L3,(P0,P7,P8)) \n                  | L5 => (L3,(P0,P7,P8)) \n                  | L6 => (L3,(P0,P7,P8)) \n                  | L7 => (L8,(P1,P1,P8)) \n                  | L8 => (L3,(P8,P7,P8)) \n                  | L9 => (L8,(P1,P1,P8)) \n                  | L10 => (L3,(P7,P7,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L5,(P0,P11,P12)) \n                  | L1 => (L5,(P0,P11,P12)) \n                  | L2 => (L5,(P0,P11,P12)) \n                  | L3 => (L5,(P0,P11,P12)) \n                  | L4 => (L5,(P0,P11,P12)) \n                  | L5 => (L5,(P0,P11,P12)) \n                  | L6 => (L5,(P0,P11,P12)) \n                  | L7 => (L8,(P1,P1,P8)) \n                  | L8 => (L8,(P1,P1,P8)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L8,(P1,P1,P8)) \n                  | L11 => (L5,(P11,P11,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L8,(P1,P1,P8)) \n                  | L9 => (L8,(P1,P1,P8)) \n                  | L10 => (L8,(P1,P1,P8)) \n                  | L11 => (L8,(P1,P1,P8)) \n                  | L12 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L3,(P0,P7,P8)) \n                  | L1 => (L3,(P0,P7,P8)) \n                  | L2 => (L3,(P0,P7,P8)) \n                  | L3 => (L3,(P0,P7,P8)) \n                  | L4 => (L3,(P0,P7,P8)) \n                  | L5 => (L3,(P0,P7,P8)) \n                  | L6 => (L3,(P0,P7,P8)) \n                  | L7 => (L8,(P1,P10,P8)) \n                  | L8 => (L3,(P8,P7,P8)) \n                  | L9 => (L8,(P1,P10,P8)) \n                  | L10 => (L3,(P7,P7,P8)) \n                  | L11 => (L8,(P1,P10,P8)) \n                  | L12 => (L8,(P1,P10,P8)) \n                  | L13 => (L3,(P7,P7,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L5,(P0,P11,P12)) \n                  | L1 => (L5,(P0,P11,P12)) \n                  | L2 => (L5,(P0,P11,P12)) \n                  | L3 => (L5,(P0,P11,P12)) \n                  | L4 => (L5,(P0,P11,P12)) \n                  | L5 => (L5,(P0,P11,P12)) \n                  | L6 => (L5,(P0,P11,P12)) \n                  | L7 => (L9,(P1,P14,P12)) \n                  | L8 => (L9,(P1,P14,P12)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L9,(P1,P14,P12)) \n                  | L11 => (L5,(P11,P11,P12)) \n                  | L12 => (L9,(P1,P14,P12)) \n                  | L13 => (L15,(P2,P2,P3)) \n                  | L14 => (L5,(P11,P11,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L12,(P1,P3,P3)) \n                  | L9 => (L12,(P1,P3,P3)) \n                  | L10 => (L12,(P1,P3,P3)) \n                  | L11 => (L12,(P1,P3,P3)) \n                  | L12 => (L1,(P3,P3,P3)) \n                  | L13 => (L15,(P2,P2,P3)) \n                  | L14 => (L15,(P2,P2,P3)) \n                  | L15 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L5,(P0,P12,P12)) \n                  | L1 => (L5,(P0,P12,P12)) \n                  | L2 => (L5,(P0,P12,P12)) \n                  | L3 => (L5,(P0,P12,P12)) \n                  | L4 => (L5,(P0,P12,P12)) \n                  | L5 => (L5,(P0,P12,P12)) \n                  | L6 => (L5,(P0,P12,P12)) \n                  | L7 => (L9,(P1,P12,P12)) \n                  | L8 => (L9,(P1,P12,P12)) \n                  | L9 => (L5,(P12,P12,P12)) \n                  | L10 => (L9,(P1,P12,P12)) \n                  | L11 => (L5,(P11,P12,P12)) \n                  | L12 => (L9,(P1,P12,P12)) \n                  | L13 => (L15,(P2,P2,P3)) \n                  | L14 => (L5,(P11,P12,P12)) \n                  | L15 => (L15,(P2,P2,P3)) \n                  | L16 => (L5,(P12,P12,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L1,(P0,P4,P3)) \n                  | L1 => (L1,(P0,P4,P3)) \n                  | L2 => (L1,(P0,P4,P3)) \n                  | L3 => (L1,(P0,P4,P3)) \n                  | L4 => (L1,(P0,P4,P3)) \n                  | L5 => (L1,(P0,P4,P3)) \n                  | L6 => (L1,(P0,P4,P3)) \n                  | L7 => (L1,(P4,P4,P3)) \n                  | L8 => (L12,(P1,P5,P3)) \n                  | L9 => (L12,(P1,P5,P3)) \n                  | L10 => (L12,(P1,P5,P3)) \n                  | L11 => (L12,(P1,P5,P3)) \n                  | L12 => (L1,(P3,P4,P3)) \n                  | L13 => (L15,(P2,P2,P3)) \n                  | L14 => (L15,(P2,P2,P3)) \n                  | L15 => (L1,(P3,P4,P3)) \n                  | L16 => (L15,(P2,P2,P3)) \n                  | L17 => (L1,(P4,P4,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L3,(P0,P8,P8)) \n                  | L1 => (L3,(P0,P8,P8)) \n                  | L2 => (L3,(P0,P8,P8)) \n                  | L3 => (L3,(P0,P8,P8)) \n                  | L4 => (L3,(P0,P8,P8)) \n                  | L5 => (L3,(P0,P8,P8)) \n                  | L6 => (L3,(P0,P8,P8)) \n                  | L7 => (L8,(P1,P8,P8)) \n                  | L8 => (L3,(P8,P8,P8)) \n                  | L9 => (L8,(P1,P8,P8)) \n                  | L10 => (L3,(P7,P8,P8)) \n                  | L11 => (L8,(P1,P8,P8)) \n                  | L12 => (L8,(P1,P8,P8)) \n                  | L13 => (L3,(P7,P8,P8)) \n                  | L14 => (L15,(P2,P2,P3)) \n                  | L15 => (L15,(P2,P2,P3)) \n                  | L16 => (L15,(P2,P2,P3)) \n                  | L17 => (L15,(P2,P2,P3)) \n                  | L18 => (L3,(P8,P8,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L8,(P1,P10,P8)) \n                  | L9 => (L8,(P1,P10,P8)) \n                  | L10 => (L8,(P1,P10,P8)) \n                  | L11 => (L8,(P1,P10,P8)) \n                  | L12 => (L1,(P3,P3,P3)) \n                  | L13 => (L8,(P10,P10,P8)) \n                  | L14 => (L9,(P14,P14,P12)) \n                  | L15 => (L1,(P3,P3,P3)) \n                  | L16 => (L9,(P12,P14,P12)) \n                  | L17 => (L1,(P4,P3,P3)) \n                  | L18 => (L8,(P8,P10,P8)) \n                  | L19 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L20 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L3,(P8,P8,P8)) \n                  | L9 => (L5,(P12,P12,P12)) \n                  | L10 => (L3,(P7,P8,P8)) \n                  | L11 => (L5,(P11,P12,P12)) \n                  | L12 => (L1,(P3,P3,P3)) \n                  | L13 => (L3,(P7,P8,P8)) \n                  | L14 => (L5,(P11,P12,P12)) \n                  | L15 => (L1,(P3,P3,P3)) \n                  | L16 => (L5,(P12,P12,P12)) \n                  | L17 => (L1,(P4,P3,P3)) \n                  | L18 => (L3,(P8,P8,P8)) \n                  | L19 => (L1,(P3,P3,P3)) \n                  | L20 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L21 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                  | L4 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                  | L4 => (L1,(P0,P0,P3)) \n                  | L5 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                  | L4 => (L1,(P0,P0,P3)) \n                  | L5 => (L1,(P0,P0,P3)) \n                  | L6 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L1,(P0,P4,P3)) \n                  | L1 => (L1,(P0,P4,P3)) \n                  | L2 => (L1,(P0,P4,P3)) \n                  | L3 => (L1,(P0,P4,P3)) \n                  | L4 => (L1,(P0,P4,P3)) \n                  | L5 => (L1,(P0,P4,P3)) \n                  | L6 => (L1,(P0,P4,P3)) \n                  | L7 => (L1,(P4,P4,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L4,(P0,P10,P9)) \n                  | L1 => (L4,(P0,P10,P9)) \n                  | L2 => (L4,(P0,P10,P9)) \n                  | L3 => (L4,(P0,P10,P9)) \n                  | L4 => (L4,(P0,P10,P9)) \n                  | L5 => (L4,(P0,P10,P9)) \n                  | L6 => (L4,(P0,P10,P9)) \n                  | L7 => (L10,(P1,P1,P9)) \n                  | L8 => (L4,(P10,P10,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L6,(P0,P14,P13)) \n                  | L1 => (L6,(P0,P14,P13)) \n                  | L2 => (L6,(P0,P14,P13)) \n                  | L3 => (L6,(P0,P14,P13)) \n                  | L4 => (L6,(P0,P14,P13)) \n                  | L5 => (L6,(P0,P14,P13)) \n                  | L6 => (L6,(P0,P14,P13)) \n                  | L7 => (L10,(P1,P1,P9)) \n                  | L8 => (L10,(P1,P1,P9)) \n                  | L9 => (L6,(P14,P14,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L4,(P0,P9,P9)) \n                  | L1 => (L4,(P0,P9,P9)) \n                  | L2 => (L4,(P0,P9,P9)) \n                  | L3 => (L4,(P0,P9,P9)) \n                  | L4 => (L4,(P0,P9,P9)) \n                  | L5 => (L4,(P0,P9,P9)) \n                  | L6 => (L4,(P0,P9,P9)) \n                  | L7 => (L10,(P1,P1,P9)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L10,(P1,P1,P9)) \n                  | L10 => (L4,(P9,P9,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L6,(P0,P13,P13)) \n                  | L1 => (L6,(P0,P13,P13)) \n                  | L2 => (L6,(P0,P13,P13)) \n                  | L3 => (L6,(P0,P13,P13)) \n                  | L4 => (L6,(P0,P13,P13)) \n                  | L5 => (L6,(P0,P13,P13)) \n                  | L6 => (L6,(P0,P13,P13)) \n                  | L7 => (L10,(P1,P1,P9)) \n                  | L8 => (L10,(P1,P1,P9)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L10,(P1,P1,P9)) \n                  | L11 => (L6,(P13,P13,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L10,(P1,P1,P9)) \n                  | L9 => (L10,(P1,P1,P9)) \n                  | L10 => (L10,(P1,P1,P9)) \n                  | L11 => (L10,(P1,P1,P9)) \n                  | L12 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L4,(P0,P10,P9)) \n                  | L1 => (L4,(P0,P10,P9)) \n                  | L2 => (L4,(P0,P10,P9)) \n                  | L3 => (L4,(P0,P10,P9)) \n                  | L4 => (L4,(P0,P10,P9)) \n                  | L5 => (L4,(P0,P10,P9)) \n                  | L6 => (L4,(P0,P10,P9)) \n                  | L7 => (L10,(P1,P7,P9)) \n                  | L8 => (L4,(P10,P10,P9)) \n                  | L9 => (L10,(P1,P7,P9)) \n                  | L10 => (L4,(P9,P10,P9)) \n                  | L11 => (L10,(P1,P7,P9)) \n                  | L12 => (L10,(P1,P7,P9)) \n                  | L13 => (L4,(P10,P10,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L6,(P0,P14,P13)) \n                  | L1 => (L6,(P0,P14,P13)) \n                  | L2 => (L6,(P0,P14,P13)) \n                  | L3 => (L6,(P0,P14,P13)) \n                  | L4 => (L6,(P0,P14,P13)) \n                  | L5 => (L6,(P0,P14,P13)) \n                  | L6 => (L6,(P0,P14,P13)) \n                  | L7 => (L11,(P1,P11,P13)) \n                  | L8 => (L11,(P1,P11,P13)) \n                  | L9 => (L6,(P14,P14,P13)) \n                  | L10 => (L11,(P1,P11,P13)) \n                  | L11 => (L6,(P13,P14,P13)) \n                  | L12 => (L11,(P1,P11,P13)) \n                  | L13 => (L15,(P2,P2,P3)) \n                  | L14 => (L6,(P14,P14,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L12,(P1,P3,P3)) \n                  | L9 => (L12,(P1,P3,P3)) \n                  | L10 => (L12,(P1,P3,P3)) \n                  | L11 => (L12,(P1,P3,P3)) \n                  | L12 => (L1,(P3,P3,P3)) \n                  | L13 => (L15,(P2,P2,P3)) \n                  | L14 => (L15,(P2,P2,P3)) \n                  | L15 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L6,(P0,P13,P13)) \n                  | L1 => (L6,(P0,P13,P13)) \n                  | L2 => (L6,(P0,P13,P13)) \n                  | L3 => (L6,(P0,P13,P13)) \n                  | L4 => (L6,(P0,P13,P13)) \n                  | L5 => (L6,(P0,P13,P13)) \n                  | L6 => (L6,(P0,P13,P13)) \n                  | L7 => (L11,(P1,P13,P13)) \n                  | L8 => (L11,(P1,P13,P13)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L11,(P1,P13,P13)) \n                  | L11 => (L6,(P13,P13,P13)) \n                  | L12 => (L11,(P1,P13,P13)) \n                  | L13 => (L15,(P2,P2,P3)) \n                  | L14 => (L6,(P14,P13,P13)) \n                  | L15 => (L15,(P2,P2,P3)) \n                  | L16 => (L6,(P13,P13,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L1,(P0,P4,P3)) \n                  | L1 => (L1,(P0,P4,P3)) \n                  | L2 => (L1,(P0,P4,P3)) \n                  | L3 => (L1,(P0,P4,P3)) \n                  | L4 => (L1,(P0,P4,P3)) \n                  | L5 => (L1,(P0,P4,P3)) \n                  | L6 => (L1,(P0,P4,P3)) \n                  | L7 => (L1,(P4,P4,P3)) \n                  | L8 => (L12,(P1,P5,P3)) \n                  | L9 => (L12,(P1,P5,P3)) \n                  | L10 => (L12,(P1,P5,P3)) \n                  | L11 => (L12,(P1,P5,P3)) \n                  | L12 => (L1,(P3,P4,P3)) \n                  | L13 => (L15,(P2,P2,P3)) \n                  | L14 => (L15,(P2,P2,P3)) \n                  | L15 => (L1,(P3,P4,P3)) \n                  | L16 => (L15,(P2,P2,P3)) \n                  | L17 => (L1,(P4,P4,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L4,(P0,P9,P9)) \n                  | L1 => (L4,(P0,P9,P9)) \n                  | L2 => (L4,(P0,P9,P9)) \n                  | L3 => (L4,(P0,P9,P9)) \n                  | L4 => (L4,(P0,P9,P9)) \n                  | L5 => (L4,(P0,P9,P9)) \n                  | L6 => (L4,(P0,P9,P9)) \n                  | L7 => (L10,(P1,P9,P9)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L10,(P1,P9,P9)) \n                  | L10 => (L4,(P9,P9,P9)) \n                  | L11 => (L10,(P1,P9,P9)) \n                  | L12 => (L10,(P1,P9,P9)) \n                  | L13 => (L4,(P10,P9,P9)) \n                  | L14 => (L15,(P2,P2,P3)) \n                  | L15 => (L15,(P2,P2,P3)) \n                  | L16 => (L15,(P2,P2,P3)) \n                  | L17 => (L15,(P2,P2,P3)) \n                  | L18 => (L4,(P9,P9,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L4,(P10,P10,P9)) \n                  | L9 => (L6,(P14,P14,P13)) \n                  | L10 => (L4,(P9,P10,P9)) \n                  | L11 => (L6,(P13,P14,P13)) \n                  | L12 => (L1,(P3,P3,P3)) \n                  | L13 => (L4,(P10,P10,P9)) \n                  | L14 => (L6,(P14,P14,P13)) \n                  | L15 => (L1,(P3,P3,P3)) \n                  | L16 => (L6,(P13,P14,P13)) \n                  | L17 => (L1,(P4,P3,P3)) \n                  | L18 => (L4,(P9,P10,P9)) \n                  | L19 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L20 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L12,(P1,P3,P3)) \n                  | L9 => (L12,(P1,P3,P3)) \n                  | L10 => (L12,(P1,P3,P3)) \n                  | L11 => (L12,(P1,P3,P3)) \n                  | L12 => (L1,(P3,P3,P3)) \n                  | L13 => (L15,(P2,P3,P3)) \n                  | L14 => (L15,(P2,P3,P3)) \n                  | L15 => (L1,(P3,P3,P3)) \n                  | L16 => (L15,(P2,P3,P3)) \n                  | L17 => (L1,(P4,P3,P3)) \n                  | L18 => (L15,(P2,P3,P3)) \n                  | L19 => (L1,(P3,P3,P3)) \n                  | L20 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L21 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L4,(P9,P9,P9)) \n                  | L11 => (L6,(P13,P13,P13)) \n                  | L12 => (L1,(P3,P3,P3)) \n                  | L13 => (L4,(P10,P9,P9)) \n                  | L14 => (L6,(P14,P13,P13)) \n                  | L15 => (L1,(P3,P3,P3)) \n                  | L16 => (L6,(P13,P13,P13)) \n                  | L17 => (L1,(P4,P3,P3)) \n                  | L18 => (L4,(P9,P9,P9)) \n                  | L19 => (L1,(P3,P3,P3)) \n                  | L20 => (L1,(P3,P3,P3)) \n                  | L21 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L22 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                  | L4 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                  | L4 => (L1,(P0,P0,P3)) \n                  | L5 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L1,(P0,P0,P3)) \n                  | L1 => (L1,(P0,P0,P3)) \n                  | L2 => (L1,(P0,P0,P3)) \n                  | L3 => (L1,(P0,P0,P3)) \n                  | L4 => (L1,(P0,P0,P3)) \n                  | L5 => (L1,(P0,P0,P3)) \n                  | L6 => (L1,(P0,P0,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L1,(P0,P4,P3)) \n                  | L1 => (L1,(P0,P4,P3)) \n                  | L2 => (L1,(P0,P4,P3)) \n                  | L3 => (L1,(P0,P4,P3)) \n                  | L4 => (L1,(P0,P4,P3)) \n                  | L5 => (L1,(P0,P4,P3)) \n                  | L6 => (L1,(P0,P4,P3)) \n                  | L7 => (L1,(P4,P4,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L3,(P0,P8,P7)) \n                  | L1 => (L3,(P0,P8,P7)) \n                  | L2 => (L3,(P0,P8,P7)) \n                  | L3 => (L3,(P0,P8,P7)) \n                  | L4 => (L3,(P0,P8,P7)) \n                  | L5 => (L3,(P0,P8,P7)) \n                  | L6 => (L3,(P0,P8,P7)) \n                  | L7 => (L10,(P1,P1,P7)) \n                  | L8 => (L3,(P8,P8,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L5,(P0,P12,P11)) \n                  | L1 => (L5,(P0,P12,P11)) \n                  | L2 => (L5,(P0,P12,P11)) \n                  | L3 => (L5,(P0,P12,P11)) \n                  | L4 => (L5,(P0,P12,P11)) \n                  | L5 => (L5,(P0,P12,P11)) \n                  | L6 => (L5,(P0,P12,P11)) \n                  | L7 => (L10,(P1,P1,P7)) \n                  | L8 => (L10,(P1,P1,P7)) \n                  | L9 => (L5,(P12,P12,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L3,(P0,P7,P7)) \n                  | L1 => (L3,(P0,P7,P7)) \n                  | L2 => (L3,(P0,P7,P7)) \n                  | L3 => (L3,(P0,P7,P7)) \n                  | L4 => (L3,(P0,P7,P7)) \n                  | L5 => (L3,(P0,P7,P7)) \n                  | L6 => (L3,(P0,P7,P7)) \n                  | L7 => (L10,(P1,P1,P7)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L10,(P1,P1,P7)) \n                  | L10 => (L3,(P7,P7,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L5,(P0,P11,P11)) \n                  | L1 => (L5,(P0,P11,P11)) \n                  | L2 => (L5,(P0,P11,P11)) \n                  | L3 => (L5,(P0,P11,P11)) \n                  | L4 => (L5,(P0,P11,P11)) \n                  | L5 => (L5,(P0,P11,P11)) \n                  | L6 => (L5,(P0,P11,P11)) \n                  | L7 => (L10,(P1,P1,P7)) \n                  | L8 => (L10,(P1,P1,P7)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L10,(P1,P1,P7)) \n                  | L11 => (L5,(P11,P11,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L10,(P1,P1,P7)) \n                  | L9 => (L10,(P1,P1,P7)) \n                  | L10 => (L10,(P1,P1,P7)) \n                  | L11 => (L10,(P1,P1,P7)) \n                  | L12 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L3,(P0,P7,P7)) \n                  | L1 => (L3,(P0,P7,P7)) \n                  | L2 => (L3,(P0,P7,P7)) \n                  | L3 => (L3,(P0,P7,P7)) \n                  | L4 => (L3,(P0,P7,P7)) \n                  | L5 => (L3,(P0,P7,P7)) \n                  | L6 => (L3,(P0,P7,P7)) \n                  | L7 => (L10,(P1,P7,P7)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L10,(P1,P7,P7)) \n                  | L10 => (L3,(P7,P7,P7)) \n                  | L11 => (L10,(P1,P7,P7)) \n                  | L12 => (L10,(P1,P7,P7)) \n                  | L13 => (L3,(P7,P7,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L5,(P0,P11,P11)) \n                  | L1 => (L5,(P0,P11,P11)) \n                  | L2 => (L5,(P0,P11,P11)) \n                  | L3 => (L5,(P0,P11,P11)) \n                  | L4 => (L5,(P0,P11,P11)) \n                  | L5 => (L5,(P0,P11,P11)) \n                  | L6 => (L5,(P0,P11,P11)) \n                  | L7 => (L11,(P1,P11,P11)) \n                  | L8 => (L11,(P1,P11,P11)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L11,(P1,P11,P11)) \n                  | L11 => (L5,(P11,P11,P11)) \n                  | L12 => (L11,(P1,P11,P11)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L5,(P11,P11,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L12,(P1,P3,P3)) \n                  | L9 => (L12,(P1,P3,P3)) \n                  | L10 => (L12,(P1,P3,P3)) \n                  | L11 => (L12,(P1,P3,P3)) \n                  | L12 => (L1,(P3,P3,P3)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L13,(P2,P2,P7)) \n                  | L15 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L5,(P0,P12,P11)) \n                  | L1 => (L5,(P0,P12,P11)) \n                  | L2 => (L5,(P0,P12,P11)) \n                  | L3 => (L5,(P0,P12,P11)) \n                  | L4 => (L5,(P0,P12,P11)) \n                  | L5 => (L5,(P0,P12,P11)) \n                  | L6 => (L5,(P0,P12,P11)) \n                  | L7 => (L11,(P1,P13,P11)) \n                  | L8 => (L11,(P1,P13,P11)) \n                  | L9 => (L5,(P12,P12,P11)) \n                  | L10 => (L11,(P1,P13,P11)) \n                  | L11 => (L5,(P11,P12,P11)) \n                  | L12 => (L11,(P1,P13,P11)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L5,(P11,P12,P11)) \n                  | L15 => (L13,(P2,P2,P7)) \n                  | L16 => (L5,(P12,P12,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L1,(P0,P4,P3)) \n                  | L1 => (L1,(P0,P4,P3)) \n                  | L2 => (L1,(P0,P4,P3)) \n                  | L3 => (L1,(P0,P4,P3)) \n                  | L4 => (L1,(P0,P4,P3)) \n                  | L5 => (L1,(P0,P4,P3)) \n                  | L6 => (L1,(P0,P4,P3)) \n                  | L7 => (L1,(P4,P4,P3)) \n                  | L8 => (L12,(P1,P5,P3)) \n                  | L9 => (L12,(P1,P5,P3)) \n                  | L10 => (L12,(P1,P5,P3)) \n                  | L11 => (L12,(P1,P5,P3)) \n                  | L12 => (L1,(P3,P4,P3)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L13,(P2,P2,P7)) \n                  | L15 => (L1,(P3,P4,P3)) \n                  | L16 => (L13,(P2,P2,P7)) \n                  | L17 => (L1,(P4,P4,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L3,(P0,P8,P7)) \n                  | L1 => (L3,(P0,P8,P7)) \n                  | L2 => (L3,(P0,P8,P7)) \n                  | L3 => (L3,(P0,P8,P7)) \n                  | L4 => (L3,(P0,P8,P7)) \n                  | L5 => (L3,(P0,P8,P7)) \n                  | L6 => (L3,(P0,P8,P7)) \n                  | L7 => (L10,(P1,P9,P7)) \n                  | L8 => (L3,(P8,P8,P7)) \n                  | L9 => (L10,(P1,P9,P7)) \n                  | L10 => (L3,(P7,P8,P7)) \n                  | L11 => (L10,(P1,P9,P7)) \n                  | L12 => (L10,(P1,P9,P7)) \n                  | L13 => (L3,(P7,P8,P7)) \n                  | L14 => (L13,(P2,P2,P7)) \n                  | L15 => (L13,(P2,P2,P7)) \n                  | L16 => (L13,(P2,P2,P7)) \n                  | L17 => (L13,(P2,P2,P7)) \n                  | L18 => (L3,(P8,P8,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L12,(P1,P3,P3)) \n                  | L9 => (L12,(P1,P3,P3)) \n                  | L10 => (L12,(P1,P3,P3)) \n                  | L11 => (L12,(P1,P3,P3)) \n                  | L12 => (L1,(P3,P3,P3)) \n                  | L13 => (L13,(P2,P10,P7)) \n                  | L14 => (L13,(P2,P10,P7)) \n                  | L15 => (L1,(P3,P3,P3)) \n                  | L16 => (L13,(P2,P10,P7)) \n                  | L17 => (L1,(P4,P3,P3)) \n                  | L18 => (L13,(P2,P10,P7)) \n                  | L19 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L20 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L3,(P8,P8,P7)) \n                  | L9 => (L5,(P12,P12,P11)) \n                  | L10 => (L3,(P7,P8,P7)) \n                  | L11 => (L5,(P11,P12,P11)) \n                  | L12 => (L1,(P3,P3,P3)) \n                  | L13 => (L3,(P7,P8,P7)) \n                  | L14 => (L5,(P11,P12,P11)) \n                  | L15 => (L1,(P3,P3,P3)) \n                  | L16 => (L5,(P12,P12,P11)) \n                  | L17 => (L1,(P4,P3,P3)) \n                  | L18 => (L3,(P8,P8,P7)) \n                  | L19 => (L1,(P3,P3,P3)) \n                  | L20 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L21 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L10,(P1,P9,P7)) \n                  | L9 => (L10,(P1,P9,P7)) \n                  | L10 => (L10,(P1,P9,P7)) \n                  | L11 => (L10,(P1,P9,P7)) \n                  | L12 => (L1,(P3,P3,P3)) \n                  | L13 => (L10,(P7,P9,P7)) \n                  | L14 => (L11,(P11,P13,P11)) \n                  | L15 => (L1,(P3,P3,P3)) \n                  | L16 => (L11,(P13,P13,P11)) \n                  | L17 => (L1,(P4,P3,P3)) \n                  | L18 => (L10,(P9,P9,P7)) \n                  | L19 => (L1,(P3,P3,P3)) \n                  | L20 => (L1,(P3,P3,P3)) \n                  | L21 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L22 => match l1 with \n                  | L0 => (L1,(P0,P3,P3)) \n                  | L1 => (L1,(P0,P3,P3)) \n                  | L2 => (L1,(P0,P3,P3)) \n                  | L3 => (L1,(P0,P3,P3)) \n                  | L4 => (L1,(P0,P3,P3)) \n                  | L5 => (L1,(P0,P3,P3)) \n                  | L6 => (L1,(P0,P3,P3)) \n                  | L7 => (L1,(P4,P3,P3)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L3,(P7,P7,P7)) \n                  | L11 => (L5,(P11,P11,P11)) \n                  | L12 => (L1,(P3,P3,P3)) \n                  | L13 => (L3,(P7,P7,P7)) \n                  | L14 => (L5,(P11,P11,P11)) \n                  | L15 => (L1,(P3,P3,P3)) \n                  | L16 => (L5,(P12,P11,P11)) \n                  | L17 => (L1,(P4,P3,P3)) \n                  | L18 => (L3,(P8,P7,P7)) \n                  | L19 => (L1,(P3,P3,P3)) \n                  | L20 => (L1,(P3,P3,P3)) \n                  | L21 => (L1,(P3,P3,P3)) \n                  | L22 => (L1,(P3,P3,P3)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L23 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                  | L4 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                  | L4 => (L1,(P0,P0,P4)) \n                  | L5 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                  | L4 => (L1,(P0,P0,P4)) \n                  | L5 => (L1,(P0,P0,P4)) \n                  | L6 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L4,(P0,P10,P9)) \n                  | L1 => (L4,(P0,P10,P9)) \n                  | L2 => (L4,(P0,P10,P9)) \n                  | L3 => (L4,(P0,P10,P9)) \n                  | L4 => (L4,(P0,P10,P9)) \n                  | L5 => (L4,(P0,P10,P9)) \n                  | L6 => (L4,(P0,P10,P9)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L4,(P10,P10,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L6,(P0,P14,P14)) \n                  | L1 => (L6,(P0,P14,P14)) \n                  | L2 => (L6,(P0,P14,P14)) \n                  | L3 => (L6,(P0,P14,P14)) \n                  | L4 => (L6,(P0,P14,P14)) \n                  | L5 => (L6,(P0,P14,P14)) \n                  | L6 => (L6,(P0,P14,P14)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L7,(P1,P1,P4)) \n                  | L9 => (L6,(P14,P14,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L4,(P0,P9,P9)) \n                  | L1 => (L4,(P0,P9,P9)) \n                  | L2 => (L4,(P0,P9,P9)) \n                  | L3 => (L4,(P0,P9,P9)) \n                  | L4 => (L4,(P0,P9,P9)) \n                  | L5 => (L4,(P0,P9,P9)) \n                  | L6 => (L4,(P0,P9,P9)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L7,(P1,P1,P4)) \n                  | L10 => (L4,(P9,P9,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L6,(P0,P13,P14)) \n                  | L1 => (L6,(P0,P13,P14)) \n                  | L2 => (L6,(P0,P13,P14)) \n                  | L3 => (L6,(P0,P13,P14)) \n                  | L4 => (L6,(P0,P13,P14)) \n                  | L5 => (L6,(P0,P13,P14)) \n                  | L6 => (L6,(P0,P13,P14)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L7,(P1,P1,P4)) \n                  | L9 => (L6,(P14,P13,P14)) \n                  | L10 => (L7,(P1,P1,P4)) \n                  | L11 => (L6,(P13,P13,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L7,(P1,P1,P4)) \n                  | L9 => (L7,(P1,P1,P4)) \n                  | L10 => (L7,(P1,P1,P4)) \n                  | L11 => (L7,(P1,P1,P4)) \n                  | L12 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L4,(P0,P10,P9)) \n                  | L1 => (L4,(P0,P10,P9)) \n                  | L2 => (L4,(P0,P10,P9)) \n                  | L3 => (L4,(P0,P10,P9)) \n                  | L4 => (L4,(P0,P10,P9)) \n                  | L5 => (L4,(P0,P10,P9)) \n                  | L6 => (L4,(P0,P10,P9)) \n                  | L7 => (L10,(P1,P7,P9)) \n                  | L8 => (L4,(P10,P10,P9)) \n                  | L9 => (L10,(P1,P7,P9)) \n                  | L10 => (L4,(P9,P10,P9)) \n                  | L11 => (L10,(P1,P7,P9)) \n                  | L12 => (L10,(P1,P7,P9)) \n                  | L13 => (L4,(P10,P10,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L6,(P0,P14,P14)) \n                  | L1 => (L6,(P0,P14,P14)) \n                  | L2 => (L6,(P0,P14,P14)) \n                  | L3 => (L6,(P0,P14,P14)) \n                  | L4 => (L6,(P0,P14,P14)) \n                  | L5 => (L6,(P0,P14,P14)) \n                  | L6 => (L6,(P0,P14,P14)) \n                  | L7 => (L9,(P1,P14,P14)) \n                  | L8 => (L9,(P1,P14,P14)) \n                  | L9 => (L6,(P14,P14,P14)) \n                  | L10 => (L9,(P1,P14,P14)) \n                  | L11 => (L6,(P13,P14,P14)) \n                  | L12 => (L9,(P1,P14,P14)) \n                  | L13 => (L14,(P2,P2,P14)) \n                  | L14 => (L6,(P14,P14,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L7,(P1,P6,P4)) \n                  | L9 => (L7,(P1,P6,P4)) \n                  | L10 => (L7,(P1,P6,P4)) \n                  | L11 => (L7,(P1,P6,P4)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L14,(P2,P2,P14)) \n                  | L14 => (L14,(P2,P2,P14)) \n                  | L15 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L6,(P0,P13,P14)) \n                  | L1 => (L6,(P0,P13,P14)) \n                  | L2 => (L6,(P0,P13,P14)) \n                  | L3 => (L6,(P0,P13,P14)) \n                  | L4 => (L6,(P0,P13,P14)) \n                  | L5 => (L6,(P0,P13,P14)) \n                  | L6 => (L6,(P0,P13,P14)) \n                  | L7 => (L9,(P1,P12,P14)) \n                  | L8 => (L9,(P1,P12,P14)) \n                  | L9 => (L6,(P14,P13,P14)) \n                  | L10 => (L9,(P1,P12,P14)) \n                  | L11 => (L6,(P13,P13,P14)) \n                  | L12 => (L9,(P1,P12,P14)) \n                  | L13 => (L14,(P2,P2,P14)) \n                  | L14 => (L6,(P14,P13,P14)) \n                  | L15 => (L14,(P2,P2,P14)) \n                  | L16 => (L6,(P13,P13,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                  | L8 => (L7,(P1,P4,P4)) \n                  | L9 => (L7,(P1,P4,P4)) \n                  | L10 => (L7,(P1,P4,P4)) \n                  | L11 => (L7,(P1,P4,P4)) \n                  | L12 => (L1,(P3,P4,P4)) \n                  | L13 => (L14,(P2,P2,P14)) \n                  | L14 => (L14,(P2,P2,P14)) \n                  | L15 => (L1,(P3,P4,P4)) \n                  | L16 => (L14,(P2,P2,P14)) \n                  | L17 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L4,(P0,P9,P9)) \n                  | L1 => (L4,(P0,P9,P9)) \n                  | L2 => (L4,(P0,P9,P9)) \n                  | L3 => (L4,(P0,P9,P9)) \n                  | L4 => (L4,(P0,P9,P9)) \n                  | L5 => (L4,(P0,P9,P9)) \n                  | L6 => (L4,(P0,P9,P9)) \n                  | L7 => (L10,(P1,P9,P9)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L10,(P1,P9,P9)) \n                  | L10 => (L4,(P9,P9,P9)) \n                  | L11 => (L10,(P1,P9,P9)) \n                  | L12 => (L10,(P1,P9,P9)) \n                  | L13 => (L4,(P10,P9,P9)) \n                  | L14 => (L14,(P2,P2,P14)) \n                  | L15 => (L14,(P2,P2,P14)) \n                  | L16 => (L14,(P2,P2,P14)) \n                  | L17 => (L14,(P2,P2,P14)) \n                  | L18 => (L4,(P9,P9,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L4,(P10,P10,P9)) \n                  | L9 => (L6,(P14,P14,P14)) \n                  | L10 => (L4,(P9,P10,P9)) \n                  | L11 => (L6,(P13,P14,P14)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L4,(P10,P10,P9)) \n                  | L14 => (L6,(P14,P14,P14)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L6,(P13,P14,P14)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L4,(P9,P10,P9)) \n                  | L19 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L20 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L9,(P1,P12,P14)) \n                  | L9 => (L9,(P1,P12,P14)) \n                  | L10 => (L9,(P1,P12,P14)) \n                  | L11 => (L9,(P1,P12,P14)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L18,(P2,P8,P9)) \n                  | L14 => (L9,(P14,P12,P14)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L9,(P12,P12,P14)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L18,(P2,P8,P9)) \n                  | L19 => (L1,(P3,P3,P4)) \n                  | L20 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L21 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L6,(P14,P13,P14)) \n                  | L10 => (L4,(P9,P9,P9)) \n                  | L11 => (L6,(P13,P13,P14)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L4,(P10,P9,P9)) \n                  | L14 => (L6,(P14,P13,P14)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L6,(P13,P13,P14)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L4,(P9,P9,P9)) \n                  | L19 => (L1,(P3,P3,P4)) \n                  | L20 => (L1,(P3,P3,P4)) \n                  | L21 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L22 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L10,(P1,P7,P9)) \n                  | L9 => (L10,(P1,P7,P9)) \n                  | L10 => (L10,(P1,P7,P9)) \n                  | L11 => (L10,(P1,P7,P9)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L10,(P7,P7,P9)) \n                  | L14 => (L14,(P2,P11,P14)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L14,(P2,P11,P14)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L10,(P9,P7,P9)) \n                  | L19 => (L1,(P3,P3,P4)) \n                  | L20 => (L1,(P3,P3,P4)) \n                  | L21 => (L1,(P3,P3,P4)) \n                  | L22 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L23 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L6,(P14,P14,P14)) \n                  | L10 => (L4,(P9,P9,P9)) \n                  | L11 => (L6,(P13,P14,P14)) \n                  | L12 => (L1,(P3,P4,P4)) \n                  | L13 => (L4,(P10,P9,P9)) \n                  | L14 => (L6,(P14,P14,P14)) \n                  | L15 => (L1,(P3,P4,P4)) \n                  | L16 => (L6,(P13,P14,P14)) \n                  | L17 => (L1,(P4,P4,P4)) \n                  | L18 => (L4,(P9,P9,P9)) \n                  | L19 => (L1,(P3,P4,P4)) \n                  | L20 => (L1,(P3,P4,P4)) \n                  | L21 => (L1,(P3,P4,P4)) \n                  | L22 => (L1,(P3,P4,P4)) \n                  | L23 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L24 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                  | L4 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                  | L4 => (L1,(P0,P0,P4)) \n                  | L5 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                  | L4 => (L1,(P0,P0,P4)) \n                  | L5 => (L1,(P0,P0,P4)) \n                  | L6 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L3,(P0,P8,P8)) \n                  | L1 => (L3,(P0,P8,P8)) \n                  | L2 => (L3,(P0,P8,P8)) \n                  | L3 => (L3,(P0,P8,P8)) \n                  | L4 => (L3,(P0,P8,P8)) \n                  | L5 => (L3,(P0,P8,P8)) \n                  | L6 => (L3,(P0,P8,P8)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L3,(P8,P8,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L5,(P0,P12,P11)) \n                  | L1 => (L5,(P0,P12,P11)) \n                  | L2 => (L5,(P0,P12,P11)) \n                  | L3 => (L5,(P0,P12,P11)) \n                  | L4 => (L5,(P0,P12,P11)) \n                  | L5 => (L5,(P0,P12,P11)) \n                  | L6 => (L5,(P0,P12,P11)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L7,(P1,P1,P4)) \n                  | L9 => (L5,(P12,P12,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L3,(P0,P7,P8)) \n                  | L1 => (L3,(P0,P7,P8)) \n                  | L2 => (L3,(P0,P7,P8)) \n                  | L3 => (L3,(P0,P7,P8)) \n                  | L4 => (L3,(P0,P7,P8)) \n                  | L5 => (L3,(P0,P7,P8)) \n                  | L6 => (L3,(P0,P7,P8)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L3,(P8,P7,P8)) \n                  | L9 => (L7,(P1,P1,P4)) \n                  | L10 => (L3,(P7,P7,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L5,(P0,P11,P11)) \n                  | L1 => (L5,(P0,P11,P11)) \n                  | L2 => (L5,(P0,P11,P11)) \n                  | L3 => (L5,(P0,P11,P11)) \n                  | L4 => (L5,(P0,P11,P11)) \n                  | L5 => (L5,(P0,P11,P11)) \n                  | L6 => (L5,(P0,P11,P11)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L7,(P1,P1,P4)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L7,(P1,P1,P4)) \n                  | L11 => (L5,(P11,P11,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L7,(P1,P1,P4)) \n                  | L9 => (L7,(P1,P1,P4)) \n                  | L10 => (L7,(P1,P1,P4)) \n                  | L11 => (L7,(P1,P1,P4)) \n                  | L12 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L3,(P0,P7,P8)) \n                  | L1 => (L3,(P0,P7,P8)) \n                  | L2 => (L3,(P0,P7,P8)) \n                  | L3 => (L3,(P0,P7,P8)) \n                  | L4 => (L3,(P0,P7,P8)) \n                  | L5 => (L3,(P0,P7,P8)) \n                  | L6 => (L3,(P0,P7,P8)) \n                  | L7 => (L8,(P1,P10,P8)) \n                  | L8 => (L3,(P8,P7,P8)) \n                  | L9 => (L8,(P1,P10,P8)) \n                  | L10 => (L3,(P7,P7,P8)) \n                  | L11 => (L8,(P1,P10,P8)) \n                  | L12 => (L8,(P1,P10,P8)) \n                  | L13 => (L3,(P7,P7,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L5,(P0,P11,P11)) \n                  | L1 => (L5,(P0,P11,P11)) \n                  | L2 => (L5,(P0,P11,P11)) \n                  | L3 => (L5,(P0,P11,P11)) \n                  | L4 => (L5,(P0,P11,P11)) \n                  | L5 => (L5,(P0,P11,P11)) \n                  | L6 => (L5,(P0,P11,P11)) \n                  | L7 => (L11,(P1,P11,P11)) \n                  | L8 => (L11,(P1,P11,P11)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L11,(P1,P11,P11)) \n                  | L11 => (L5,(P11,P11,P11)) \n                  | L12 => (L11,(P1,P11,P11)) \n                  | L13 => (L14,(P2,P2,P11)) \n                  | L14 => (L5,(P11,P11,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L7,(P1,P6,P4)) \n                  | L9 => (L7,(P1,P6,P4)) \n                  | L10 => (L7,(P1,P6,P4)) \n                  | L11 => (L7,(P1,P6,P4)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L14,(P2,P2,P11)) \n                  | L14 => (L14,(P2,P2,P11)) \n                  | L15 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L5,(P0,P12,P11)) \n                  | L1 => (L5,(P0,P12,P11)) \n                  | L2 => (L5,(P0,P12,P11)) \n                  | L3 => (L5,(P0,P12,P11)) \n                  | L4 => (L5,(P0,P12,P11)) \n                  | L5 => (L5,(P0,P12,P11)) \n                  | L6 => (L5,(P0,P12,P11)) \n                  | L7 => (L11,(P1,P13,P11)) \n                  | L8 => (L11,(P1,P13,P11)) \n                  | L9 => (L5,(P12,P12,P11)) \n                  | L10 => (L11,(P1,P13,P11)) \n                  | L11 => (L5,(P11,P12,P11)) \n                  | L12 => (L11,(P1,P13,P11)) \n                  | L13 => (L14,(P2,P2,P11)) \n                  | L14 => (L5,(P11,P12,P11)) \n                  | L15 => (L14,(P2,P2,P11)) \n                  | L16 => (L5,(P12,P12,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                  | L8 => (L7,(P1,P4,P4)) \n                  | L9 => (L7,(P1,P4,P4)) \n                  | L10 => (L7,(P1,P4,P4)) \n                  | L11 => (L7,(P1,P4,P4)) \n                  | L12 => (L1,(P3,P4,P4)) \n                  | L13 => (L14,(P2,P2,P11)) \n                  | L14 => (L14,(P2,P2,P11)) \n                  | L15 => (L1,(P3,P4,P4)) \n                  | L16 => (L14,(P2,P2,P11)) \n                  | L17 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L3,(P0,P8,P8)) \n                  | L1 => (L3,(P0,P8,P8)) \n                  | L2 => (L3,(P0,P8,P8)) \n                  | L3 => (L3,(P0,P8,P8)) \n                  | L4 => (L3,(P0,P8,P8)) \n                  | L5 => (L3,(P0,P8,P8)) \n                  | L6 => (L3,(P0,P8,P8)) \n                  | L7 => (L8,(P1,P8,P8)) \n                  | L8 => (L3,(P8,P8,P8)) \n                  | L9 => (L8,(P1,P8,P8)) \n                  | L10 => (L3,(P7,P8,P8)) \n                  | L11 => (L8,(P1,P8,P8)) \n                  | L12 => (L8,(P1,P8,P8)) \n                  | L13 => (L3,(P7,P8,P8)) \n                  | L14 => (L14,(P2,P2,P11)) \n                  | L15 => (L14,(P2,P2,P11)) \n                  | L16 => (L14,(P2,P2,P11)) \n                  | L17 => (L14,(P2,P2,P11)) \n                  | L18 => (L3,(P8,P8,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L8,(P1,P10,P8)) \n                  | L9 => (L8,(P1,P10,P8)) \n                  | L10 => (L8,(P1,P10,P8)) \n                  | L11 => (L8,(P1,P10,P8)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L8,(P10,P10,P8)) \n                  | L14 => (L14,(P2,P14,P11)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L14,(P2,P14,P11)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L8,(P8,P10,P8)) \n                  | L19 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L20 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L3,(P8,P8,P8)) \n                  | L9 => (L5,(P12,P12,P11)) \n                  | L10 => (L3,(P7,P8,P8)) \n                  | L11 => (L5,(P11,P12,P11)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L3,(P7,P8,P8)) \n                  | L14 => (L5,(P11,P12,P11)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L5,(P12,P12,P11)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L3,(P8,P8,P8)) \n                  | L19 => (L1,(P3,P3,P4)) \n                  | L20 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L21 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L11,(P1,P13,P11)) \n                  | L9 => (L11,(P1,P13,P11)) \n                  | L10 => (L11,(P1,P13,P11)) \n                  | L11 => (L11,(P1,P13,P11)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L18,(P2,P9,P8)) \n                  | L14 => (L11,(P11,P13,P11)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L11,(P13,P13,P11)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L18,(P2,P9,P8)) \n                  | L19 => (L1,(P3,P3,P4)) \n                  | L20 => (L1,(P3,P3,P4)) \n                  | L21 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L22 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L3,(P8,P7,P8)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L3,(P7,P7,P8)) \n                  | L11 => (L5,(P11,P11,P11)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L3,(P7,P7,P8)) \n                  | L14 => (L5,(P11,P11,P11)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L5,(P12,P11,P11)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L3,(P8,P7,P8)) \n                  | L19 => (L1,(P3,P3,P4)) \n                  | L20 => (L1,(P3,P3,P4)) \n                  | L21 => (L1,(P3,P3,P4)) \n                  | L22 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L23 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                  | L8 => (L7,(P1,P4,P4)) \n                  | L9 => (L7,(P1,P4,P4)) \n                  | L10 => (L7,(P1,P4,P4)) \n                  | L11 => (L7,(P1,P4,P4)) \n                  | L12 => (L1,(P3,P4,P4)) \n                  | L13 => (L14,(P2,P14,P11)) \n                  | L14 => (L14,(P2,P14,P11)) \n                  | L15 => (L1,(P3,P4,P4)) \n                  | L16 => (L14,(P2,P14,P11)) \n                  | L17 => (L1,(P4,P4,P4)) \n                  | L18 => (L14,(P2,P14,P11)) \n                  | L19 => (L1,(P3,P4,P4)) \n                  | L20 => (L1,(P3,P4,P4)) \n                  | L21 => (L1,(P3,P4,P4)) \n                  | L22 => (L1,(P3,P4,P4)) \n                  | L23 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L24 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                  | L8 => (L3,(P8,P8,P8)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L3,(P7,P8,P8)) \n                  | L11 => (L5,(P11,P11,P11)) \n                  | L12 => (L1,(P3,P4,P4)) \n                  | L13 => (L3,(P7,P8,P8)) \n                  | L14 => (L5,(P11,P11,P11)) \n                  | L15 => (L1,(P3,P4,P4)) \n                  | L16 => (L5,(P12,P11,P11)) \n                  | L17 => (L1,(P4,P4,P4)) \n                  | L18 => (L3,(P8,P8,P8)) \n                  | L19 => (L1,(P3,P4,P4)) \n                  | L20 => (L1,(P3,P4,P4)) \n                  | L21 => (L1,(P3,P4,P4)) \n                  | L22 => (L1,(P3,P4,P4)) \n                  | L23 => (L1,(P4,P4,P4)) \n                  | L24 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L25 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                  | L4 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                  | L4 => (L1,(P0,P0,P4)) \n                  | L5 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                  | L4 => (L1,(P0,P0,P4)) \n                  | L5 => (L1,(P0,P0,P4)) \n                  | L6 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L4,(P0,P10,P10)) \n                  | L1 => (L4,(P0,P10,P10)) \n                  | L2 => (L4,(P0,P10,P10)) \n                  | L3 => (L4,(P0,P10,P10)) \n                  | L4 => (L4,(P0,P10,P10)) \n                  | L5 => (L4,(P0,P10,P10)) \n                  | L6 => (L4,(P0,P10,P10)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L4,(P10,P10,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L6,(P0,P14,P13)) \n                  | L1 => (L6,(P0,P14,P13)) \n                  | L2 => (L6,(P0,P14,P13)) \n                  | L3 => (L6,(P0,P14,P13)) \n                  | L4 => (L6,(P0,P14,P13)) \n                  | L5 => (L6,(P0,P14,P13)) \n                  | L6 => (L6,(P0,P14,P13)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L7,(P1,P1,P4)) \n                  | L9 => (L6,(P14,P14,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L4,(P0,P9,P10)) \n                  | L1 => (L4,(P0,P9,P10)) \n                  | L2 => (L4,(P0,P9,P10)) \n                  | L3 => (L4,(P0,P9,P10)) \n                  | L4 => (L4,(P0,P9,P10)) \n                  | L5 => (L4,(P0,P9,P10)) \n                  | L6 => (L4,(P0,P9,P10)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L7,(P1,P1,P4)) \n                  | L10 => (L4,(P9,P9,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L6,(P0,P13,P13)) \n                  | L1 => (L6,(P0,P13,P13)) \n                  | L2 => (L6,(P0,P13,P13)) \n                  | L3 => (L6,(P0,P13,P13)) \n                  | L4 => (L6,(P0,P13,P13)) \n                  | L5 => (L6,(P0,P13,P13)) \n                  | L6 => (L6,(P0,P13,P13)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L7,(P1,P1,P4)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L7,(P1,P1,P4)) \n                  | L11 => (L6,(P13,P13,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L7,(P1,P1,P4)) \n                  | L9 => (L7,(P1,P1,P4)) \n                  | L10 => (L7,(P1,P1,P4)) \n                  | L11 => (L7,(P1,P1,P4)) \n                  | L12 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L4,(P0,P10,P10)) \n                  | L1 => (L4,(P0,P10,P10)) \n                  | L2 => (L4,(P0,P10,P10)) \n                  | L3 => (L4,(P0,P10,P10)) \n                  | L4 => (L4,(P0,P10,P10)) \n                  | L5 => (L4,(P0,P10,P10)) \n                  | L6 => (L4,(P0,P10,P10)) \n                  | L7 => (L8,(P1,P10,P10)) \n                  | L8 => (L4,(P10,P10,P10)) \n                  | L9 => (L8,(P1,P10,P10)) \n                  | L10 => (L4,(P9,P10,P10)) \n                  | L11 => (L8,(P1,P10,P10)) \n                  | L12 => (L8,(P1,P10,P10)) \n                  | L13 => (L4,(P10,P10,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L6,(P0,P14,P13)) \n                  | L1 => (L6,(P0,P14,P13)) \n                  | L2 => (L6,(P0,P14,P13)) \n                  | L3 => (L6,(P0,P14,P13)) \n                  | L4 => (L6,(P0,P14,P13)) \n                  | L5 => (L6,(P0,P14,P13)) \n                  | L6 => (L6,(P0,P14,P13)) \n                  | L7 => (L11,(P1,P11,P13)) \n                  | L8 => (L11,(P1,P11,P13)) \n                  | L9 => (L6,(P14,P14,P13)) \n                  | L10 => (L11,(P1,P11,P13)) \n                  | L11 => (L6,(P13,P14,P13)) \n                  | L12 => (L11,(P1,P11,P13)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L6,(P14,P14,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L7,(P1,P6,P4)) \n                  | L9 => (L7,(P1,P6,P4)) \n                  | L10 => (L7,(P1,P6,P4)) \n                  | L11 => (L7,(P1,P6,P4)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L13,(P2,P2,P10)) \n                  | L15 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L6,(P0,P13,P13)) \n                  | L1 => (L6,(P0,P13,P13)) \n                  | L2 => (L6,(P0,P13,P13)) \n                  | L3 => (L6,(P0,P13,P13)) \n                  | L4 => (L6,(P0,P13,P13)) \n                  | L5 => (L6,(P0,P13,P13)) \n                  | L6 => (L6,(P0,P13,P13)) \n                  | L7 => (L11,(P1,P13,P13)) \n                  | L8 => (L11,(P1,P13,P13)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L11,(P1,P13,P13)) \n                  | L11 => (L6,(P13,P13,P13)) \n                  | L12 => (L11,(P1,P13,P13)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L6,(P14,P13,P13)) \n                  | L15 => (L13,(P2,P2,P10)) \n                  | L16 => (L6,(P13,P13,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                  | L8 => (L7,(P1,P4,P4)) \n                  | L9 => (L7,(P1,P4,P4)) \n                  | L10 => (L7,(P1,P4,P4)) \n                  | L11 => (L7,(P1,P4,P4)) \n                  | L12 => (L1,(P3,P4,P4)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L13,(P2,P2,P10)) \n                  | L15 => (L1,(P3,P4,P4)) \n                  | L16 => (L13,(P2,P2,P10)) \n                  | L17 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L4,(P0,P9,P10)) \n                  | L1 => (L4,(P0,P9,P10)) \n                  | L2 => (L4,(P0,P9,P10)) \n                  | L3 => (L4,(P0,P9,P10)) \n                  | L4 => (L4,(P0,P9,P10)) \n                  | L5 => (L4,(P0,P9,P10)) \n                  | L6 => (L4,(P0,P9,P10)) \n                  | L7 => (L8,(P1,P8,P10)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L8,(P1,P8,P10)) \n                  | L10 => (L4,(P9,P9,P10)) \n                  | L11 => (L8,(P1,P8,P10)) \n                  | L12 => (L8,(P1,P8,P10)) \n                  | L13 => (L4,(P10,P9,P10)) \n                  | L14 => (L13,(P2,P2,P10)) \n                  | L15 => (L13,(P2,P2,P10)) \n                  | L16 => (L13,(P2,P2,P10)) \n                  | L17 => (L13,(P2,P2,P10)) \n                  | L18 => (L4,(P9,P9,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L4,(P10,P10,P10)) \n                  | L9 => (L6,(P14,P14,P13)) \n                  | L10 => (L4,(P9,P10,P10)) \n                  | L11 => (L6,(P13,P14,P13)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L4,(P10,P10,P10)) \n                  | L14 => (L6,(P14,P14,P13)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L6,(P13,P14,P13)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L4,(P9,P10,P10)) \n                  | L19 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L20 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L8,(P1,P8,P10)) \n                  | L9 => (L8,(P1,P8,P10)) \n                  | L10 => (L8,(P1,P8,P10)) \n                  | L11 => (L8,(P1,P8,P10)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L8,(P10,P8,P10)) \n                  | L14 => (L16,(P2,P12,P13)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L16,(P2,P12,P13)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L8,(P8,P8,P10)) \n                  | L19 => (L1,(P3,P3,P4)) \n                  | L20 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L21 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L4,(P9,P9,P10)) \n                  | L11 => (L6,(P13,P13,P13)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L4,(P10,P9,P10)) \n                  | L14 => (L6,(P14,P13,P13)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L6,(P13,P13,P13)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L4,(P9,P9,P10)) \n                  | L19 => (L1,(P3,P3,P4)) \n                  | L20 => (L1,(P3,P3,P4)) \n                  | L21 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L22 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L11,(P1,P11,P13)) \n                  | L9 => (L11,(P1,P11,P13)) \n                  | L10 => (L11,(P1,P11,P13)) \n                  | L11 => (L11,(P1,P11,P13)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L13,(P2,P7,P10)) \n                  | L14 => (L11,(P11,P11,P13)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L11,(P13,P11,P13)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L13,(P2,P7,P10)) \n                  | L19 => (L1,(P3,P3,P4)) \n                  | L20 => (L1,(P3,P3,P4)) \n                  | L21 => (L1,(P3,P3,P4)) \n                  | L22 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L23 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L6,(P14,P14,P13)) \n                  | L10 => (L4,(P9,P9,P10)) \n                  | L11 => (L6,(P13,P14,P13)) \n                  | L12 => (L1,(P3,P4,P4)) \n                  | L13 => (L4,(P10,P9,P10)) \n                  | L14 => (L6,(P14,P14,P13)) \n                  | L15 => (L1,(P3,P4,P4)) \n                  | L16 => (L6,(P13,P14,P13)) \n                  | L17 => (L1,(P4,P4,P4)) \n                  | L18 => (L4,(P9,P9,P10)) \n                  | L19 => (L1,(P3,P4,P4)) \n                  | L20 => (L1,(P3,P4,P4)) \n                  | L21 => (L1,(P3,P4,P4)) \n                  | L22 => (L1,(P3,P4,P4)) \n                  | L23 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L24 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                  | L8 => (L7,(P1,P4,P4)) \n                  | L9 => (L7,(P1,P4,P4)) \n                  | L10 => (L7,(P1,P4,P4)) \n                  | L11 => (L7,(P1,P4,P4)) \n                  | L12 => (L1,(P3,P4,P4)) \n                  | L13 => (L8,(P10,P8,P10)) \n                  | L14 => (L11,(P11,P11,P13)) \n                  | L15 => (L1,(P3,P4,P4)) \n                  | L16 => (L11,(P13,P11,P13)) \n                  | L17 => (L1,(P4,P4,P4)) \n                  | L18 => (L8,(P8,P8,P10)) \n                  | L19 => (L1,(P3,P4,P4)) \n                  | L20 => (L1,(P3,P4,P4)) \n                  | L21 => (L1,(P3,P4,P4)) \n                  | L22 => (L1,(P3,P4,P4)) \n                  | L23 => (L1,(P4,P4,P4)) \n                  | L24 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L25 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                  | L8 => (L4,(P10,P10,P10)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L4,(P9,P10,P10)) \n                  | L11 => (L6,(P13,P13,P13)) \n                  | L12 => (L1,(P3,P4,P4)) \n                  | L13 => (L4,(P10,P10,P10)) \n                  | L14 => (L6,(P14,P13,P13)) \n                  | L15 => (L1,(P3,P4,P4)) \n                  | L16 => (L6,(P13,P13,P13)) \n                  | L17 => (L1,(P4,P4,P4)) \n                  | L18 => (L4,(P9,P10,P10)) \n                  | L19 => (L1,(P3,P4,P4)) \n                  | L20 => (L1,(P3,P4,P4)) \n                  | L21 => (L1,(P3,P4,P4)) \n                  | L22 => (L1,(P3,P4,P4)) \n                  | L23 => (L1,(P4,P4,P4)) \n                  | L24 => (L1,(P4,P4,P4)) \n                  | L25 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L26 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                  | L4 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                  | L4 => (L1,(P0,P0,P4)) \n                  | L5 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L1,(P0,P0,P4)) \n                  | L1 => (L1,(P0,P0,P4)) \n                  | L2 => (L1,(P0,P0,P4)) \n                  | L3 => (L1,(P0,P0,P4)) \n                  | L4 => (L1,(P0,P0,P4)) \n                  | L5 => (L1,(P0,P0,P4)) \n                  | L6 => (L1,(P0,P0,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L3,(P0,P8,P7)) \n                  | L1 => (L3,(P0,P8,P7)) \n                  | L2 => (L3,(P0,P8,P7)) \n                  | L3 => (L3,(P0,P8,P7)) \n                  | L4 => (L3,(P0,P8,P7)) \n                  | L5 => (L3,(P0,P8,P7)) \n                  | L6 => (L3,(P0,P8,P7)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L3,(P8,P8,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L5,(P0,P12,P12)) \n                  | L1 => (L5,(P0,P12,P12)) \n                  | L2 => (L5,(P0,P12,P12)) \n                  | L3 => (L5,(P0,P12,P12)) \n                  | L4 => (L5,(P0,P12,P12)) \n                  | L5 => (L5,(P0,P12,P12)) \n                  | L6 => (L5,(P0,P12,P12)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L7,(P1,P1,P4)) \n                  | L9 => (L5,(P12,P12,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L3,(P0,P7,P7)) \n                  | L1 => (L3,(P0,P7,P7)) \n                  | L2 => (L3,(P0,P7,P7)) \n                  | L3 => (L3,(P0,P7,P7)) \n                  | L4 => (L3,(P0,P7,P7)) \n                  | L5 => (L3,(P0,P7,P7)) \n                  | L6 => (L3,(P0,P7,P7)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L7,(P1,P1,P4)) \n                  | L10 => (L3,(P7,P7,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L5,(P0,P11,P12)) \n                  | L1 => (L5,(P0,P11,P12)) \n                  | L2 => (L5,(P0,P11,P12)) \n                  | L3 => (L5,(P0,P11,P12)) \n                  | L4 => (L5,(P0,P11,P12)) \n                  | L5 => (L5,(P0,P11,P12)) \n                  | L6 => (L5,(P0,P11,P12)) \n                  | L7 => (L7,(P1,P1,P4)) \n                  | L8 => (L7,(P1,P1,P4)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L7,(P1,P1,P4)) \n                  | L11 => (L5,(P11,P11,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L7,(P1,P1,P4)) \n                  | L9 => (L7,(P1,P1,P4)) \n                  | L10 => (L7,(P1,P1,P4)) \n                  | L11 => (L7,(P1,P1,P4)) \n                  | L12 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L3,(P0,P7,P7)) \n                  | L1 => (L3,(P0,P7,P7)) \n                  | L2 => (L3,(P0,P7,P7)) \n                  | L3 => (L3,(P0,P7,P7)) \n                  | L4 => (L3,(P0,P7,P7)) \n                  | L5 => (L3,(P0,P7,P7)) \n                  | L6 => (L3,(P0,P7,P7)) \n                  | L7 => (L10,(P1,P7,P7)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L10,(P1,P7,P7)) \n                  | L10 => (L3,(P7,P7,P7)) \n                  | L11 => (L10,(P1,P7,P7)) \n                  | L12 => (L10,(P1,P7,P7)) \n                  | L13 => (L3,(P7,P7,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L5,(P0,P11,P12)) \n                  | L1 => (L5,(P0,P11,P12)) \n                  | L2 => (L5,(P0,P11,P12)) \n                  | L3 => (L5,(P0,P11,P12)) \n                  | L4 => (L5,(P0,P11,P12)) \n                  | L5 => (L5,(P0,P11,P12)) \n                  | L6 => (L5,(P0,P11,P12)) \n                  | L7 => (L9,(P1,P14,P12)) \n                  | L8 => (L9,(P1,P14,P12)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L9,(P1,P14,P12)) \n                  | L11 => (L5,(P11,P11,P12)) \n                  | L12 => (L9,(P1,P14,P12)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L5,(P11,P11,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L7,(P1,P6,P4)) \n                  | L9 => (L7,(P1,P6,P4)) \n                  | L10 => (L7,(P1,P6,P4)) \n                  | L11 => (L7,(P1,P6,P4)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L13,(P2,P2,P7)) \n                  | L15 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L5,(P0,P12,P12)) \n                  | L1 => (L5,(P0,P12,P12)) \n                  | L2 => (L5,(P0,P12,P12)) \n                  | L3 => (L5,(P0,P12,P12)) \n                  | L4 => (L5,(P0,P12,P12)) \n                  | L5 => (L5,(P0,P12,P12)) \n                  | L6 => (L5,(P0,P12,P12)) \n                  | L7 => (L9,(P1,P12,P12)) \n                  | L8 => (L9,(P1,P12,P12)) \n                  | L9 => (L5,(P12,P12,P12)) \n                  | L10 => (L9,(P1,P12,P12)) \n                  | L11 => (L5,(P11,P12,P12)) \n                  | L12 => (L9,(P1,P12,P12)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L5,(P11,P12,P12)) \n                  | L15 => (L13,(P2,P2,P7)) \n                  | L16 => (L5,(P12,P12,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                  | L8 => (L7,(P1,P4,P4)) \n                  | L9 => (L7,(P1,P4,P4)) \n                  | L10 => (L7,(P1,P4,P4)) \n                  | L11 => (L7,(P1,P4,P4)) \n                  | L12 => (L1,(P3,P4,P4)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L13,(P2,P2,P7)) \n                  | L15 => (L1,(P3,P4,P4)) \n                  | L16 => (L13,(P2,P2,P7)) \n                  | L17 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L3,(P0,P8,P7)) \n                  | L1 => (L3,(P0,P8,P7)) \n                  | L2 => (L3,(P0,P8,P7)) \n                  | L3 => (L3,(P0,P8,P7)) \n                  | L4 => (L3,(P0,P8,P7)) \n                  | L5 => (L3,(P0,P8,P7)) \n                  | L6 => (L3,(P0,P8,P7)) \n                  | L7 => (L10,(P1,P9,P7)) \n                  | L8 => (L3,(P8,P8,P7)) \n                  | L9 => (L10,(P1,P9,P7)) \n                  | L10 => (L3,(P7,P8,P7)) \n                  | L11 => (L10,(P1,P9,P7)) \n                  | L12 => (L10,(P1,P9,P7)) \n                  | L13 => (L3,(P7,P8,P7)) \n                  | L14 => (L13,(P2,P2,P7)) \n                  | L15 => (L13,(P2,P2,P7)) \n                  | L16 => (L13,(P2,P2,P7)) \n                  | L17 => (L13,(P2,P2,P7)) \n                  | L18 => (L3,(P8,P8,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L9,(P1,P14,P12)) \n                  | L9 => (L9,(P1,P14,P12)) \n                  | L10 => (L9,(P1,P14,P12)) \n                  | L11 => (L9,(P1,P14,P12)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L13,(P2,P10,P7)) \n                  | L14 => (L9,(P14,P14,P12)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L9,(P12,P14,P12)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L13,(P2,P10,P7)) \n                  | L19 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L20 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L3,(P8,P8,P7)) \n                  | L9 => (L5,(P12,P12,P12)) \n                  | L10 => (L3,(P7,P8,P7)) \n                  | L11 => (L5,(P11,P12,P12)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L3,(P7,P8,P7)) \n                  | L14 => (L5,(P11,P12,P12)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L5,(P12,P12,P12)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L3,(P8,P8,P7)) \n                  | L19 => (L1,(P3,P3,P4)) \n                  | L20 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L21 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L10,(P1,P9,P7)) \n                  | L9 => (L10,(P1,P9,P7)) \n                  | L10 => (L10,(P1,P9,P7)) \n                  | L11 => (L10,(P1,P9,P7)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L10,(P7,P9,P7)) \n                  | L14 => (L16,(P2,P13,P12)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L16,(P2,P13,P12)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L10,(P9,P9,P7)) \n                  | L19 => (L1,(P3,P3,P4)) \n                  | L20 => (L1,(P3,P3,P4)) \n                  | L21 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L22 => match l1 with \n                  | L0 => (L1,(P0,P3,P4)) \n                  | L1 => (L1,(P0,P3,P4)) \n                  | L2 => (L1,(P0,P3,P4)) \n                  | L3 => (L1,(P0,P3,P4)) \n                  | L4 => (L1,(P0,P3,P4)) \n                  | L5 => (L1,(P0,P3,P4)) \n                  | L6 => (L1,(P0,P3,P4)) \n                  | L7 => (L1,(P4,P3,P4)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L3,(P7,P7,P7)) \n                  | L11 => (L5,(P11,P11,P12)) \n                  | L12 => (L1,(P3,P3,P4)) \n                  | L13 => (L3,(P7,P7,P7)) \n                  | L14 => (L5,(P11,P11,P12)) \n                  | L15 => (L1,(P3,P3,P4)) \n                  | L16 => (L5,(P12,P11,P12)) \n                  | L17 => (L1,(P4,P3,P4)) \n                  | L18 => (L3,(P8,P7,P7)) \n                  | L19 => (L1,(P3,P3,P4)) \n                  | L20 => (L1,(P3,P3,P4)) \n                  | L21 => (L1,(P3,P3,P4)) \n                  | L22 => (L1,(P3,P3,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L23 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                  | L8 => (L7,(P1,P4,P4)) \n                  | L9 => (L7,(P1,P4,P4)) \n                  | L10 => (L7,(P1,P4,P4)) \n                  | L11 => (L7,(P1,P4,P4)) \n                  | L12 => (L1,(P3,P4,P4)) \n                  | L13 => (L10,(P7,P9,P7)) \n                  | L14 => (L9,(P14,P14,P12)) \n                  | L15 => (L1,(P3,P4,P4)) \n                  | L16 => (L9,(P12,P14,P12)) \n                  | L17 => (L1,(P4,P4,P4)) \n                  | L18 => (L10,(P9,P9,P7)) \n                  | L19 => (L1,(P3,P4,P4)) \n                  | L20 => (L1,(P3,P4,P4)) \n                  | L21 => (L1,(P3,P4,P4)) \n                  | L22 => (L1,(P3,P4,P4)) \n                  | L23 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L24 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                  | L8 => (L3,(P8,P8,P7)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L3,(P7,P8,P7)) \n                  | L11 => (L5,(P11,P11,P12)) \n                  | L12 => (L1,(P3,P4,P4)) \n                  | L13 => (L3,(P7,P8,P7)) \n                  | L14 => (L5,(P11,P11,P12)) \n                  | L15 => (L1,(P3,P4,P4)) \n                  | L16 => (L5,(P12,P11,P12)) \n                  | L17 => (L1,(P4,P4,P4)) \n                  | L18 => (L3,(P8,P8,P7)) \n                  | L19 => (L1,(P3,P4,P4)) \n                  | L20 => (L1,(P3,P4,P4)) \n                  | L21 => (L1,(P3,P4,P4)) \n                  | L22 => (L1,(P3,P4,P4)) \n                  | L23 => (L1,(P4,P4,P4)) \n                  | L24 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L25 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                  | L8 => (L7,(P1,P4,P4)) \n                  | L9 => (L7,(P1,P4,P4)) \n                  | L10 => (L7,(P1,P4,P4)) \n                  | L11 => (L7,(P1,P4,P4)) \n                  | L12 => (L1,(P3,P4,P4)) \n                  | L13 => (L13,(P2,P10,P7)) \n                  | L14 => (L13,(P2,P10,P7)) \n                  | L15 => (L1,(P3,P4,P4)) \n                  | L16 => (L13,(P2,P10,P7)) \n                  | L17 => (L1,(P4,P4,P4)) \n                  | L18 => (L13,(P2,P10,P7)) \n                  | L19 => (L1,(P3,P4,P4)) \n                  | L20 => (L1,(P3,P4,P4)) \n                  | L21 => (L1,(P3,P4,P4)) \n                  | L22 => (L1,(P3,P4,P4)) \n                  | L23 => (L1,(P4,P4,P4)) \n                  | L24 => (L1,(P4,P4,P4)) \n                  | L25 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L26 => match l1 with \n                  | L0 => (L1,(P0,P4,P4)) \n                  | L1 => (L1,(P0,P4,P4)) \n                  | L2 => (L1,(P0,P4,P4)) \n                  | L3 => (L1,(P0,P4,P4)) \n                  | L4 => (L1,(P0,P4,P4)) \n                  | L5 => (L1,(P0,P4,P4)) \n                  | L6 => (L1,(P0,P4,P4)) \n                  | L7 => (L1,(P4,P4,P4)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L5,(P12,P12,P12)) \n                  | L10 => (L3,(P7,P7,P7)) \n                  | L11 => (L5,(P11,P12,P12)) \n                  | L12 => (L1,(P3,P4,P4)) \n                  | L13 => (L3,(P7,P7,P7)) \n                  | L14 => (L5,(P11,P12,P12)) \n                  | L15 => (L1,(P3,P4,P4)) \n                  | L16 => (L5,(P12,P12,P12)) \n                  | L17 => (L1,(P4,P4,P4)) \n                  | L18 => (L3,(P8,P7,P7)) \n                  | L19 => (L1,(P3,P4,P4)) \n                  | L20 => (L1,(P3,P4,P4)) \n                  | L21 => (L1,(P3,P4,P4)) \n                  | L22 => (L1,(P3,P4,P4)) \n                  | L23 => (L1,(P4,P4,P4)) \n                  | L24 => (L1,(P4,P4,P4)) \n                  | L25 => (L1,(P4,P4,P4)) \n                  | L26 => (L1,(P4,P4,P4)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L27 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                  | L4 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                  | L4 => (L2,(P0,P0,P5)) \n                  | L5 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                  | L4 => (L2,(P0,P0,P5)) \n                  | L5 => (L2,(P0,P0,P5)) \n                  | L6 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L2,(P0,P6,P5)) \n                  | L1 => (L2,(P0,P6,P5)) \n                  | L2 => (L2,(P0,P6,P5)) \n                  | L3 => (L2,(P0,P6,P5)) \n                  | L4 => (L2,(P0,P6,P5)) \n                  | L5 => (L2,(P0,P6,P5)) \n                  | L6 => (L2,(P0,P6,P5)) \n                  | L7 => (L2,(P6,P6,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L3,(P0,P8,P8)) \n                  | L1 => (L3,(P0,P8,P8)) \n                  | L2 => (L3,(P0,P8,P8)) \n                  | L3 => (L3,(P0,P8,P8)) \n                  | L4 => (L3,(P0,P8,P8)) \n                  | L5 => (L3,(P0,P8,P8)) \n                  | L6 => (L3,(P0,P8,P8)) \n                  | L7 => (L8,(P1,P1,P8)) \n                  | L8 => (L3,(P8,P8,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L6,(P0,P14,P14)) \n                  | L1 => (L6,(P0,P14,P14)) \n                  | L2 => (L6,(P0,P14,P14)) \n                  | L3 => (L6,(P0,P14,P14)) \n                  | L4 => (L6,(P0,P14,P14)) \n                  | L5 => (L6,(P0,P14,P14)) \n                  | L6 => (L6,(P0,P14,P14)) \n                  | L7 => (L8,(P1,P1,P8)) \n                  | L8 => (L8,(P1,P1,P8)) \n                  | L9 => (L6,(P14,P14,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L3,(P0,P7,P8)) \n                  | L1 => (L3,(P0,P7,P8)) \n                  | L2 => (L3,(P0,P7,P8)) \n                  | L3 => (L3,(P0,P7,P8)) \n                  | L4 => (L3,(P0,P7,P8)) \n                  | L5 => (L3,(P0,P7,P8)) \n                  | L6 => (L3,(P0,P7,P8)) \n                  | L7 => (L8,(P1,P1,P8)) \n                  | L8 => (L3,(P8,P7,P8)) \n                  | L9 => (L8,(P1,P1,P8)) \n                  | L10 => (L3,(P7,P7,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L6,(P0,P13,P14)) \n                  | L1 => (L6,(P0,P13,P14)) \n                  | L2 => (L6,(P0,P13,P14)) \n                  | L3 => (L6,(P0,P13,P14)) \n                  | L4 => (L6,(P0,P13,P14)) \n                  | L5 => (L6,(P0,P13,P14)) \n                  | L6 => (L6,(P0,P13,P14)) \n                  | L7 => (L8,(P1,P1,P8)) \n                  | L8 => (L8,(P1,P1,P8)) \n                  | L9 => (L6,(P14,P13,P14)) \n                  | L10 => (L8,(P1,P1,P8)) \n                  | L11 => (L6,(P13,P13,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L8,(P1,P1,P8)) \n                  | L9 => (L8,(P1,P1,P8)) \n                  | L10 => (L8,(P1,P1,P8)) \n                  | L11 => (L8,(P1,P1,P8)) \n                  | L12 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L3,(P0,P7,P8)) \n                  | L1 => (L3,(P0,P7,P8)) \n                  | L2 => (L3,(P0,P7,P8)) \n                  | L3 => (L3,(P0,P7,P8)) \n                  | L4 => (L3,(P0,P7,P8)) \n                  | L5 => (L3,(P0,P7,P8)) \n                  | L6 => (L3,(P0,P7,P8)) \n                  | L7 => (L8,(P1,P10,P8)) \n                  | L8 => (L3,(P8,P7,P8)) \n                  | L9 => (L8,(P1,P10,P8)) \n                  | L10 => (L3,(P7,P7,P8)) \n                  | L11 => (L8,(P1,P10,P8)) \n                  | L12 => (L8,(P1,P10,P8)) \n                  | L13 => (L3,(P7,P7,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L6,(P0,P14,P14)) \n                  | L1 => (L6,(P0,P14,P14)) \n                  | L2 => (L6,(P0,P14,P14)) \n                  | L3 => (L6,(P0,P14,P14)) \n                  | L4 => (L6,(P0,P14,P14)) \n                  | L5 => (L6,(P0,P14,P14)) \n                  | L6 => (L6,(P0,P14,P14)) \n                  | L7 => (L9,(P1,P14,P14)) \n                  | L8 => (L9,(P1,P14,P14)) \n                  | L9 => (L6,(P14,P14,P14)) \n                  | L10 => (L9,(P1,P14,P14)) \n                  | L11 => (L6,(P13,P14,P14)) \n                  | L12 => (L9,(P1,P14,P14)) \n                  | L13 => (L14,(P2,P2,P14)) \n                  | L14 => (L6,(P14,P14,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L2,(P0,P6,P5)) \n                  | L1 => (L2,(P0,P6,P5)) \n                  | L2 => (L2,(P0,P6,P5)) \n                  | L3 => (L2,(P0,P6,P5)) \n                  | L4 => (L2,(P0,P6,P5)) \n                  | L5 => (L2,(P0,P6,P5)) \n                  | L6 => (L2,(P0,P6,P5)) \n                  | L7 => (L2,(P6,P6,P5)) \n                  | L8 => (L12,(P1,P3,P5)) \n                  | L9 => (L12,(P1,P3,P5)) \n                  | L10 => (L12,(P1,P3,P5)) \n                  | L11 => (L12,(P1,P3,P5)) \n                  | L12 => (L2,(P5,P6,P5)) \n                  | L13 => (L14,(P2,P2,P14)) \n                  | L14 => (L14,(P2,P2,P14)) \n                  | L15 => (L2,(P6,P6,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L6,(P0,P13,P14)) \n                  | L1 => (L6,(P0,P13,P14)) \n                  | L2 => (L6,(P0,P13,P14)) \n                  | L3 => (L6,(P0,P13,P14)) \n                  | L4 => (L6,(P0,P13,P14)) \n                  | L5 => (L6,(P0,P13,P14)) \n                  | L6 => (L6,(P0,P13,P14)) \n                  | L7 => (L9,(P1,P12,P14)) \n                  | L8 => (L9,(P1,P12,P14)) \n                  | L9 => (L6,(P14,P13,P14)) \n                  | L10 => (L9,(P1,P12,P14)) \n                  | L11 => (L6,(P13,P13,P14)) \n                  | L12 => (L9,(P1,P12,P14)) \n                  | L13 => (L14,(P2,P2,P14)) \n                  | L14 => (L6,(P14,P13,P14)) \n                  | L15 => (L14,(P2,P2,P14)) \n                  | L16 => (L6,(P13,P13,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L12,(P1,P5,P5)) \n                  | L9 => (L12,(P1,P5,P5)) \n                  | L10 => (L12,(P1,P5,P5)) \n                  | L11 => (L12,(P1,P5,P5)) \n                  | L12 => (L2,(P5,P5,P5)) \n                  | L13 => (L14,(P2,P2,P14)) \n                  | L14 => (L14,(P2,P2,P14)) \n                  | L15 => (L2,(P6,P5,P5)) \n                  | L16 => (L14,(P2,P2,P14)) \n                  | L17 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L3,(P0,P8,P8)) \n                  | L1 => (L3,(P0,P8,P8)) \n                  | L2 => (L3,(P0,P8,P8)) \n                  | L3 => (L3,(P0,P8,P8)) \n                  | L4 => (L3,(P0,P8,P8)) \n                  | L5 => (L3,(P0,P8,P8)) \n                  | L6 => (L3,(P0,P8,P8)) \n                  | L7 => (L8,(P1,P8,P8)) \n                  | L8 => (L3,(P8,P8,P8)) \n                  | L9 => (L8,(P1,P8,P8)) \n                  | L10 => (L3,(P7,P8,P8)) \n                  | L11 => (L8,(P1,P8,P8)) \n                  | L12 => (L8,(P1,P8,P8)) \n                  | L13 => (L3,(P7,P8,P8)) \n                  | L14 => (L14,(P2,P2,P14)) \n                  | L15 => (L14,(P2,P2,P14)) \n                  | L16 => (L14,(P2,P2,P14)) \n                  | L17 => (L14,(P2,P2,P14)) \n                  | L18 => (L3,(P8,P8,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L6,(P0,P14,P14)) \n                  | L1 => (L6,(P0,P14,P14)) \n                  | L2 => (L6,(P0,P14,P14)) \n                  | L3 => (L6,(P0,P14,P14)) \n                  | L4 => (L6,(P0,P14,P14)) \n                  | L5 => (L6,(P0,P14,P14)) \n                  | L6 => (L6,(P0,P14,P14)) \n                  | L7 => (L8,(P1,P10,P8)) \n                  | L8 => (L8,(P1,P10,P8)) \n                  | L9 => (L6,(P14,P14,P14)) \n                  | L10 => (L8,(P1,P10,P8)) \n                  | L11 => (L6,(P13,P14,P14)) \n                  | L12 => (L8,(P1,P10,P8)) \n                  | L13 => (L8,(P10,P10,P8)) \n                  | L14 => (L6,(P14,P14,P14)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L6,(P13,P14,P14)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L8,(P8,P10,P8)) \n                  | L19 => (L6,(P14,P14,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L20 => match l1 with \n                  | L0 => (L3,(P0,P8,P8)) \n                  | L1 => (L3,(P0,P8,P8)) \n                  | L2 => (L3,(P0,P8,P8)) \n                  | L3 => (L3,(P0,P8,P8)) \n                  | L4 => (L3,(P0,P8,P8)) \n                  | L5 => (L3,(P0,P8,P8)) \n                  | L6 => (L3,(P0,P8,P8)) \n                  | L7 => (L8,(P1,P8,P8)) \n                  | L8 => (L3,(P8,P8,P8)) \n                  | L9 => (L8,(P1,P8,P8)) \n                  | L10 => (L3,(P7,P8,P8)) \n                  | L11 => (L8,(P1,P8,P8)) \n                  | L12 => (L8,(P1,P8,P8)) \n                  | L13 => (L3,(P7,P8,P8)) \n                  | L14 => (L9,(P14,P12,P14)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L9,(P12,P12,P14)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L3,(P8,P8,P8)) \n                  | L19 => (L8,(P10,P8,P8)) \n                  | L20 => (L3,(P8,P8,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L21 => match l1 with \n                  | L0 => (L6,(P0,P13,P14)) \n                  | L1 => (L6,(P0,P13,P14)) \n                  | L2 => (L6,(P0,P13,P14)) \n                  | L3 => (L6,(P0,P13,P14)) \n                  | L4 => (L6,(P0,P13,P14)) \n                  | L5 => (L6,(P0,P13,P14)) \n                  | L6 => (L6,(P0,P13,P14)) \n                  | L7 => (L12,(P1,P3,P5)) \n                  | L8 => (L12,(P1,P3,P5)) \n                  | L9 => (L6,(P14,P13,P14)) \n                  | L10 => (L12,(P1,P3,P5)) \n                  | L11 => (L6,(P13,P13,P14)) \n                  | L12 => (L12,(P1,P3,P5)) \n                  | L13 => (L18,(P2,P9,P8)) \n                  | L14 => (L6,(P14,P13,P14)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L6,(P13,P13,P14)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L18,(P2,P9,P8)) \n                  | L19 => (L6,(P14,P13,P14)) \n                  | L20 => (L12,(P3,P3,P5)) \n                  | L21 => (L6,(P13,P13,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L22 => match l1 with \n                  | L0 => (L3,(P0,P7,P8)) \n                  | L1 => (L3,(P0,P7,P8)) \n                  | L2 => (L3,(P0,P7,P8)) \n                  | L3 => (L3,(P0,P7,P8)) \n                  | L4 => (L3,(P0,P7,P8)) \n                  | L5 => (L3,(P0,P7,P8)) \n                  | L6 => (L3,(P0,P7,P8)) \n                  | L7 => (L12,(P1,P3,P5)) \n                  | L8 => (L3,(P8,P7,P8)) \n                  | L9 => (L12,(P1,P3,P5)) \n                  | L10 => (L3,(P7,P7,P8)) \n                  | L11 => (L12,(P1,P3,P5)) \n                  | L12 => (L12,(P1,P3,P5)) \n                  | L13 => (L3,(P7,P7,P8)) \n                  | L14 => (L14,(P2,P11,P14)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L14,(P2,P11,P14)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L3,(P8,P7,P8)) \n                  | L19 => (L12,(P3,P3,P5)) \n                  | L20 => (L3,(P8,P7,P8)) \n                  | L21 => (L12,(P3,P3,P5)) \n                  | L22 => (L3,(P7,P7,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L23 => match l1 with \n                  | L0 => (L6,(P0,P14,P14)) \n                  | L1 => (L6,(P0,P14,P14)) \n                  | L2 => (L6,(P0,P14,P14)) \n                  | L3 => (L6,(P0,P14,P14)) \n                  | L4 => (L6,(P0,P14,P14)) \n                  | L5 => (L6,(P0,P14,P14)) \n                  | L6 => (L6,(P0,P14,P14)) \n                  | L7 => (L9,(P1,P14,P14)) \n                  | L8 => (L9,(P1,P14,P14)) \n                  | L9 => (L6,(P14,P14,P14)) \n                  | L10 => (L9,(P1,P14,P14)) \n                  | L11 => (L6,(P13,P14,P14)) \n                  | L12 => (L9,(P1,P14,P14)) \n                  | L13 => (L14,(P2,P14,P14)) \n                  | L14 => (L6,(P14,P14,P14)) \n                  | L15 => (L14,(P2,P14,P14)) \n                  | L16 => (L6,(P13,P14,P14)) \n                  | L17 => (L14,(P2,P14,P14)) \n                  | L18 => (L14,(P2,P14,P14)) \n                  | L19 => (L6,(P14,P14,P14)) \n                  | L20 => (L9,(P12,P14,P14)) \n                  | L21 => (L6,(P13,P14,P14)) \n                  | L22 => (L14,(P11,P14,P14)) \n                  | L23 => (L6,(P14,P14,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L24 => match l1 with \n                  | L0 => (L3,(P0,P8,P8)) \n                  | L1 => (L3,(P0,P8,P8)) \n                  | L2 => (L3,(P0,P8,P8)) \n                  | L3 => (L3,(P0,P8,P8)) \n                  | L4 => (L3,(P0,P8,P8)) \n                  | L5 => (L3,(P0,P8,P8)) \n                  | L6 => (L3,(P0,P8,P8)) \n                  | L7 => (L8,(P1,P8,P8)) \n                  | L8 => (L3,(P8,P8,P8)) \n                  | L9 => (L8,(P1,P8,P8)) \n                  | L10 => (L3,(P7,P8,P8)) \n                  | L11 => (L8,(P1,P8,P8)) \n                  | L12 => (L8,(P1,P8,P8)) \n                  | L13 => (L3,(P7,P8,P8)) \n                  | L14 => (L14,(P2,P11,P14)) \n                  | L15 => (L14,(P2,P11,P14)) \n                  | L16 => (L14,(P2,P11,P14)) \n                  | L17 => (L14,(P2,P11,P14)) \n                  | L18 => (L3,(P8,P8,P8)) \n                  | L19 => (L8,(P10,P8,P8)) \n                  | L20 => (L3,(P8,P8,P8)) \n                  | L21 => (L18,(P9,P8,P8)) \n                  | L22 => (L3,(P7,P8,P8)) \n                  | L23 => (L14,(P14,P11,P14)) \n                  | L24 => (L3,(P8,P8,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L25 => match l1 with \n                  | L0 => (L6,(P0,P13,P14)) \n                  | L1 => (L6,(P0,P13,P14)) \n                  | L2 => (L6,(P0,P13,P14)) \n                  | L3 => (L6,(P0,P13,P14)) \n                  | L4 => (L6,(P0,P13,P14)) \n                  | L5 => (L6,(P0,P13,P14)) \n                  | L6 => (L6,(P0,P13,P14)) \n                  | L7 => (L8,(P1,P10,P8)) \n                  | L8 => (L8,(P1,P10,P8)) \n                  | L9 => (L6,(P14,P13,P14)) \n                  | L10 => (L8,(P1,P10,P8)) \n                  | L11 => (L6,(P13,P13,P14)) \n                  | L12 => (L8,(P1,P10,P8)) \n                  | L13 => (L8,(P10,P10,P8)) \n                  | L14 => (L6,(P14,P13,P14)) \n                  | L15 => (L17,(P2,P4,P5)) \n                  | L16 => (L6,(P13,P13,P14)) \n                  | L17 => (L17,(P2,P4,P5)) \n                  | L18 => (L8,(P8,P10,P8)) \n                  | L19 => (L6,(P14,P13,P14)) \n                  | L20 => (L8,(P8,P10,P8)) \n                  | L21 => (L6,(P13,P13,P14)) \n                  | L22 => (L19,(P3,P10,P14)) \n                  | L23 => (L6,(P14,P13,P14)) \n                  | L24 => (L8,(P8,P10,P8)) \n                  | L25 => (L6,(P13,P13,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L26 => match l1 with \n                  | L0 => (L3,(P0,P7,P8)) \n                  | L1 => (L3,(P0,P7,P8)) \n                  | L2 => (L3,(P0,P7,P8)) \n                  | L3 => (L3,(P0,P7,P8)) \n                  | L4 => (L3,(P0,P7,P8)) \n                  | L5 => (L3,(P0,P7,P8)) \n                  | L6 => (L3,(P0,P7,P8)) \n                  | L7 => (L9,(P1,P12,P14)) \n                  | L8 => (L3,(P8,P7,P8)) \n                  | L9 => (L9,(P1,P12,P14)) \n                  | L10 => (L3,(P7,P7,P8)) \n                  | L11 => (L9,(P1,P12,P14)) \n                  | L12 => (L9,(P1,P12,P14)) \n                  | L13 => (L3,(P7,P7,P8)) \n                  | L14 => (L9,(P14,P12,P14)) \n                  | L15 => (L17,(P2,P4,P5)) \n                  | L16 => (L9,(P12,P12,P14)) \n                  | L17 => (L17,(P2,P4,P5)) \n                  | L18 => (L3,(P8,P7,P8)) \n                  | L19 => (L9,(P14,P12,P14)) \n                  | L20 => (L3,(P8,P7,P8)) \n                  | L21 => (L20,(P3,P12,P8)) \n                  | L22 => (L3,(P7,P7,P8)) \n                  | L23 => (L9,(P14,P12,P14)) \n                  | L24 => (L3,(P8,P7,P8)) \n                  | L25 => (L17,(P4,P4,P5)) \n                  | L26 => (L3,(P7,P7,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L27 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L3,(P8,P8,P8)) \n                  | L9 => (L6,(P14,P14,P14)) \n                  | L10 => (L3,(P7,P8,P8)) \n                  | L11 => (L6,(P13,P14,P14)) \n                  | L12 => (L2,(P5,P5,P5)) \n                  | L13 => (L3,(P7,P8,P8)) \n                  | L14 => (L6,(P14,P14,P14)) \n                  | L15 => (L2,(P6,P5,P5)) \n                  | L16 => (L6,(P13,P14,P14)) \n                  | L17 => (L2,(P5,P5,P5)) \n                  | L18 => (L3,(P8,P8,P8)) \n                  | L19 => (L6,(P14,P14,P14)) \n                  | L20 => (L3,(P8,P8,P8)) \n                  | L21 => (L6,(P13,P14,P14)) \n                  | L22 => (L3,(P7,P8,P8)) \n                  | L23 => (L6,(P14,P14,P14)) \n                  | L24 => (L3,(P8,P8,P8)) \n                  | L25 => (L6,(P13,P14,P14)) \n                  | L26 => (L3,(P7,P8,P8)) \n                  | L27 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L28 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                  | L4 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                  | L4 => (L2,(P0,P0,P5)) \n                  | L5 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                  | L4 => (L2,(P0,P0,P5)) \n                  | L5 => (L2,(P0,P0,P5)) \n                  | L6 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L2,(P0,P6,P5)) \n                  | L1 => (L2,(P0,P6,P5)) \n                  | L2 => (L2,(P0,P6,P5)) \n                  | L3 => (L2,(P0,P6,P5)) \n                  | L4 => (L2,(P0,P6,P5)) \n                  | L5 => (L2,(P0,P6,P5)) \n                  | L6 => (L2,(P0,P6,P5)) \n                  | L7 => (L2,(P6,P6,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L3,(P0,P8,P7)) \n                  | L1 => (L3,(P0,P8,P7)) \n                  | L2 => (L3,(P0,P8,P7)) \n                  | L3 => (L3,(P0,P8,P7)) \n                  | L4 => (L3,(P0,P8,P7)) \n                  | L5 => (L3,(P0,P8,P7)) \n                  | L6 => (L3,(P0,P8,P7)) \n                  | L7 => (L10,(P1,P1,P7)) \n                  | L8 => (L3,(P8,P8,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L6,(P0,P14,P13)) \n                  | L1 => (L6,(P0,P14,P13)) \n                  | L2 => (L6,(P0,P14,P13)) \n                  | L3 => (L6,(P0,P14,P13)) \n                  | L4 => (L6,(P0,P14,P13)) \n                  | L5 => (L6,(P0,P14,P13)) \n                  | L6 => (L6,(P0,P14,P13)) \n                  | L7 => (L10,(P1,P1,P7)) \n                  | L8 => (L10,(P1,P1,P7)) \n                  | L9 => (L6,(P14,P14,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L3,(P0,P7,P7)) \n                  | L1 => (L3,(P0,P7,P7)) \n                  | L2 => (L3,(P0,P7,P7)) \n                  | L3 => (L3,(P0,P7,P7)) \n                  | L4 => (L3,(P0,P7,P7)) \n                  | L5 => (L3,(P0,P7,P7)) \n                  | L6 => (L3,(P0,P7,P7)) \n                  | L7 => (L10,(P1,P1,P7)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L10,(P1,P1,P7)) \n                  | L10 => (L3,(P7,P7,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L6,(P0,P13,P13)) \n                  | L1 => (L6,(P0,P13,P13)) \n                  | L2 => (L6,(P0,P13,P13)) \n                  | L3 => (L6,(P0,P13,P13)) \n                  | L4 => (L6,(P0,P13,P13)) \n                  | L5 => (L6,(P0,P13,P13)) \n                  | L6 => (L6,(P0,P13,P13)) \n                  | L7 => (L10,(P1,P1,P7)) \n                  | L8 => (L10,(P1,P1,P7)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L10,(P1,P1,P7)) \n                  | L11 => (L6,(P13,P13,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L10,(P1,P1,P7)) \n                  | L9 => (L10,(P1,P1,P7)) \n                  | L10 => (L10,(P1,P1,P7)) \n                  | L11 => (L10,(P1,P1,P7)) \n                  | L12 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L3,(P0,P7,P7)) \n                  | L1 => (L3,(P0,P7,P7)) \n                  | L2 => (L3,(P0,P7,P7)) \n                  | L3 => (L3,(P0,P7,P7)) \n                  | L4 => (L3,(P0,P7,P7)) \n                  | L5 => (L3,(P0,P7,P7)) \n                  | L6 => (L3,(P0,P7,P7)) \n                  | L7 => (L10,(P1,P7,P7)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L10,(P1,P7,P7)) \n                  | L10 => (L3,(P7,P7,P7)) \n                  | L11 => (L10,(P1,P7,P7)) \n                  | L12 => (L10,(P1,P7,P7)) \n                  | L13 => (L3,(P7,P7,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L6,(P0,P14,P13)) \n                  | L1 => (L6,(P0,P14,P13)) \n                  | L2 => (L6,(P0,P14,P13)) \n                  | L3 => (L6,(P0,P14,P13)) \n                  | L4 => (L6,(P0,P14,P13)) \n                  | L5 => (L6,(P0,P14,P13)) \n                  | L6 => (L6,(P0,P14,P13)) \n                  | L7 => (L11,(P1,P11,P13)) \n                  | L8 => (L11,(P1,P11,P13)) \n                  | L9 => (L6,(P14,P14,P13)) \n                  | L10 => (L11,(P1,P11,P13)) \n                  | L11 => (L6,(P13,P14,P13)) \n                  | L12 => (L11,(P1,P11,P13)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L6,(P14,P14,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L2,(P0,P6,P5)) \n                  | L1 => (L2,(P0,P6,P5)) \n                  | L2 => (L2,(P0,P6,P5)) \n                  | L3 => (L2,(P0,P6,P5)) \n                  | L4 => (L2,(P0,P6,P5)) \n                  | L5 => (L2,(P0,P6,P5)) \n                  | L6 => (L2,(P0,P6,P5)) \n                  | L7 => (L2,(P6,P6,P5)) \n                  | L8 => (L12,(P1,P3,P5)) \n                  | L9 => (L12,(P1,P3,P5)) \n                  | L10 => (L12,(P1,P3,P5)) \n                  | L11 => (L12,(P1,P3,P5)) \n                  | L12 => (L2,(P5,P6,P5)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L13,(P2,P2,P7)) \n                  | L15 => (L2,(P6,P6,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L6,(P0,P13,P13)) \n                  | L1 => (L6,(P0,P13,P13)) \n                  | L2 => (L6,(P0,P13,P13)) \n                  | L3 => (L6,(P0,P13,P13)) \n                  | L4 => (L6,(P0,P13,P13)) \n                  | L5 => (L6,(P0,P13,P13)) \n                  | L6 => (L6,(P0,P13,P13)) \n                  | L7 => (L11,(P1,P13,P13)) \n                  | L8 => (L11,(P1,P13,P13)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L11,(P1,P13,P13)) \n                  | L11 => (L6,(P13,P13,P13)) \n                  | L12 => (L11,(P1,P13,P13)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L6,(P14,P13,P13)) \n                  | L15 => (L13,(P2,P2,P7)) \n                  | L16 => (L6,(P13,P13,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L12,(P1,P5,P5)) \n                  | L9 => (L12,(P1,P5,P5)) \n                  | L10 => (L12,(P1,P5,P5)) \n                  | L11 => (L12,(P1,P5,P5)) \n                  | L12 => (L2,(P5,P5,P5)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L13,(P2,P2,P7)) \n                  | L15 => (L2,(P6,P5,P5)) \n                  | L16 => (L13,(P2,P2,P7)) \n                  | L17 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L3,(P0,P8,P7)) \n                  | L1 => (L3,(P0,P8,P7)) \n                  | L2 => (L3,(P0,P8,P7)) \n                  | L3 => (L3,(P0,P8,P7)) \n                  | L4 => (L3,(P0,P8,P7)) \n                  | L5 => (L3,(P0,P8,P7)) \n                  | L6 => (L3,(P0,P8,P7)) \n                  | L7 => (L10,(P1,P9,P7)) \n                  | L8 => (L3,(P8,P8,P7)) \n                  | L9 => (L10,(P1,P9,P7)) \n                  | L10 => (L3,(P7,P8,P7)) \n                  | L11 => (L10,(P1,P9,P7)) \n                  | L12 => (L10,(P1,P9,P7)) \n                  | L13 => (L3,(P7,P8,P7)) \n                  | L14 => (L13,(P2,P2,P7)) \n                  | L15 => (L13,(P2,P2,P7)) \n                  | L16 => (L13,(P2,P2,P7)) \n                  | L17 => (L13,(P2,P2,P7)) \n                  | L18 => (L3,(P8,P8,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L6,(P0,P14,P13)) \n                  | L1 => (L6,(P0,P14,P13)) \n                  | L2 => (L6,(P0,P14,P13)) \n                  | L3 => (L6,(P0,P14,P13)) \n                  | L4 => (L6,(P0,P14,P13)) \n                  | L5 => (L6,(P0,P14,P13)) \n                  | L6 => (L6,(P0,P14,P13)) \n                  | L7 => (L12,(P1,P3,P5)) \n                  | L8 => (L12,(P1,P3,P5)) \n                  | L9 => (L6,(P14,P14,P13)) \n                  | L10 => (L12,(P1,P3,P5)) \n                  | L11 => (L6,(P13,P14,P13)) \n                  | L12 => (L12,(P1,P3,P5)) \n                  | L13 => (L13,(P2,P10,P7)) \n                  | L14 => (L6,(P14,P14,P13)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L6,(P13,P14,P13)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L13,(P2,P10,P7)) \n                  | L19 => (L6,(P14,P14,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L20 => match l1 with \n                  | L0 => (L3,(P0,P8,P7)) \n                  | L1 => (L3,(P0,P8,P7)) \n                  | L2 => (L3,(P0,P8,P7)) \n                  | L3 => (L3,(P0,P8,P7)) \n                  | L4 => (L3,(P0,P8,P7)) \n                  | L5 => (L3,(P0,P8,P7)) \n                  | L6 => (L3,(P0,P8,P7)) \n                  | L7 => (L12,(P1,P3,P5)) \n                  | L8 => (L3,(P8,P8,P7)) \n                  | L9 => (L12,(P1,P3,P5)) \n                  | L10 => (L3,(P7,P8,P7)) \n                  | L11 => (L12,(P1,P3,P5)) \n                  | L12 => (L12,(P1,P3,P5)) \n                  | L13 => (L3,(P7,P8,P7)) \n                  | L14 => (L16,(P2,P12,P13)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L16,(P2,P12,P13)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L3,(P8,P8,P7)) \n                  | L19 => (L12,(P3,P3,P5)) \n                  | L20 => (L3,(P8,P8,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L21 => match l1 with \n                  | L0 => (L6,(P0,P13,P13)) \n                  | L1 => (L6,(P0,P13,P13)) \n                  | L2 => (L6,(P0,P13,P13)) \n                  | L3 => (L6,(P0,P13,P13)) \n                  | L4 => (L6,(P0,P13,P13)) \n                  | L5 => (L6,(P0,P13,P13)) \n                  | L6 => (L6,(P0,P13,P13)) \n                  | L7 => (L10,(P1,P9,P7)) \n                  | L8 => (L10,(P1,P9,P7)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L10,(P1,P9,P7)) \n                  | L11 => (L6,(P13,P13,P13)) \n                  | L12 => (L10,(P1,P9,P7)) \n                  | L13 => (L10,(P7,P9,P7)) \n                  | L14 => (L6,(P14,P13,P13)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L6,(P13,P13,P13)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L10,(P9,P9,P7)) \n                  | L19 => (L6,(P14,P13,P13)) \n                  | L20 => (L12,(P3,P3,P5)) \n                  | L21 => (L6,(P13,P13,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L22 => match l1 with \n                  | L0 => (L3,(P0,P7,P7)) \n                  | L1 => (L3,(P0,P7,P7)) \n                  | L2 => (L3,(P0,P7,P7)) \n                  | L3 => (L3,(P0,P7,P7)) \n                  | L4 => (L3,(P0,P7,P7)) \n                  | L5 => (L3,(P0,P7,P7)) \n                  | L6 => (L3,(P0,P7,P7)) \n                  | L7 => (L10,(P1,P7,P7)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L10,(P1,P7,P7)) \n                  | L10 => (L3,(P7,P7,P7)) \n                  | L11 => (L10,(P1,P7,P7)) \n                  | L12 => (L10,(P1,P7,P7)) \n                  | L13 => (L3,(P7,P7,P7)) \n                  | L14 => (L11,(P11,P11,P13)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L11,(P13,P11,P13)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L3,(P8,P7,P7)) \n                  | L19 => (L12,(P3,P3,P5)) \n                  | L20 => (L3,(P8,P7,P7)) \n                  | L21 => (L10,(P9,P7,P7)) \n                  | L22 => (L3,(P7,P7,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L23 => match l1 with \n                  | L0 => (L6,(P0,P14,P13)) \n                  | L1 => (L6,(P0,P14,P13)) \n                  | L2 => (L6,(P0,P14,P13)) \n                  | L3 => (L6,(P0,P14,P13)) \n                  | L4 => (L6,(P0,P14,P13)) \n                  | L5 => (L6,(P0,P14,P13)) \n                  | L6 => (L6,(P0,P14,P13)) \n                  | L7 => (L10,(P1,P9,P7)) \n                  | L8 => (L10,(P1,P9,P7)) \n                  | L9 => (L6,(P14,P14,P13)) \n                  | L10 => (L10,(P1,P9,P7)) \n                  | L11 => (L6,(P13,P14,P13)) \n                  | L12 => (L10,(P1,P9,P7)) \n                  | L13 => (L10,(P7,P9,P7)) \n                  | L14 => (L6,(P14,P14,P13)) \n                  | L15 => (L17,(P2,P4,P5)) \n                  | L16 => (L6,(P13,P14,P13)) \n                  | L17 => (L17,(P2,P4,P5)) \n                  | L18 => (L10,(P9,P9,P7)) \n                  | L19 => (L6,(P14,P14,P13)) \n                  | L20 => (L21,(P3,P9,P13)) \n                  | L21 => (L6,(P13,P14,P13)) \n                  | L22 => (L10,(P7,P9,P7)) \n                  | L23 => (L6,(P14,P14,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L24 => match l1 with \n                  | L0 => (L3,(P0,P8,P7)) \n                  | L1 => (L3,(P0,P8,P7)) \n                  | L2 => (L3,(P0,P8,P7)) \n                  | L3 => (L3,(P0,P8,P7)) \n                  | L4 => (L3,(P0,P8,P7)) \n                  | L5 => (L3,(P0,P8,P7)) \n                  | L6 => (L3,(P0,P8,P7)) \n                  | L7 => (L11,(P1,P11,P13)) \n                  | L8 => (L3,(P8,P8,P7)) \n                  | L9 => (L11,(P1,P11,P13)) \n                  | L10 => (L3,(P7,P8,P7)) \n                  | L11 => (L11,(P1,P11,P13)) \n                  | L12 => (L11,(P1,P11,P13)) \n                  | L13 => (L3,(P7,P8,P7)) \n                  | L14 => (L11,(P11,P11,P13)) \n                  | L15 => (L17,(P2,P4,P5)) \n                  | L16 => (L11,(P13,P11,P13)) \n                  | L17 => (L17,(P2,P4,P5)) \n                  | L18 => (L3,(P8,P8,P7)) \n                  | L19 => (L22,(P3,P11,P7)) \n                  | L20 => (L3,(P8,P8,P7)) \n                  | L21 => (L11,(P13,P11,P13)) \n                  | L22 => (L3,(P7,P8,P7)) \n                  | L23 => (L17,(P4,P4,P5)) \n                  | L24 => (L3,(P8,P8,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L25 => match l1 with \n                  | L0 => (L6,(P0,P13,P13)) \n                  | L1 => (L6,(P0,P13,P13)) \n                  | L2 => (L6,(P0,P13,P13)) \n                  | L3 => (L6,(P0,P13,P13)) \n                  | L4 => (L6,(P0,P13,P13)) \n                  | L5 => (L6,(P0,P13,P13)) \n                  | L6 => (L6,(P0,P13,P13)) \n                  | L7 => (L11,(P1,P13,P13)) \n                  | L8 => (L11,(P1,P13,P13)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L11,(P1,P13,P13)) \n                  | L11 => (L6,(P13,P13,P13)) \n                  | L12 => (L11,(P1,P13,P13)) \n                  | L13 => (L13,(P2,P10,P7)) \n                  | L14 => (L6,(P14,P13,P13)) \n                  | L15 => (L13,(P2,P10,P7)) \n                  | L16 => (L6,(P13,P13,P13)) \n                  | L17 => (L13,(P2,P10,P7)) \n                  | L18 => (L13,(P2,P10,P7)) \n                  | L19 => (L6,(P14,P13,P13)) \n                  | L20 => (L16,(P12,P13,P13)) \n                  | L21 => (L6,(P13,P13,P13)) \n                  | L22 => (L11,(P11,P13,P13)) \n                  | L23 => (L6,(P14,P13,P13)) \n                  | L24 => (L11,(P11,P13,P13)) \n                  | L25 => (L6,(P13,P13,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L26 => match l1 with \n                  | L0 => (L3,(P0,P7,P7)) \n                  | L1 => (L3,(P0,P7,P7)) \n                  | L2 => (L3,(P0,P7,P7)) \n                  | L3 => (L3,(P0,P7,P7)) \n                  | L4 => (L3,(P0,P7,P7)) \n                  | L5 => (L3,(P0,P7,P7)) \n                  | L6 => (L3,(P0,P7,P7)) \n                  | L7 => (L10,(P1,P7,P7)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L10,(P1,P7,P7)) \n                  | L10 => (L3,(P7,P7,P7)) \n                  | L11 => (L10,(P1,P7,P7)) \n                  | L12 => (L10,(P1,P7,P7)) \n                  | L13 => (L3,(P7,P7,P7)) \n                  | L14 => (L13,(P2,P7,P7)) \n                  | L15 => (L13,(P2,P7,P7)) \n                  | L16 => (L13,(P2,P7,P7)) \n                  | L17 => (L13,(P2,P7,P7)) \n                  | L18 => (L3,(P8,P7,P7)) \n                  | L19 => (L13,(P10,P7,P7)) \n                  | L20 => (L3,(P8,P7,P7)) \n                  | L21 => (L10,(P9,P7,P7)) \n                  | L22 => (L3,(P7,P7,P7)) \n                  | L23 => (L10,(P9,P7,P7)) \n                  | L24 => (L3,(P8,P7,P7)) \n                  | L25 => (L13,(P10,P7,P7)) \n                  | L26 => (L3,(P7,P7,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L27 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L3,(P8,P8,P7)) \n                  | L9 => (L6,(P14,P14,P13)) \n                  | L10 => (L3,(P7,P8,P7)) \n                  | L11 => (L6,(P13,P14,P13)) \n                  | L12 => (L2,(P5,P5,P5)) \n                  | L13 => (L3,(P7,P8,P7)) \n                  | L14 => (L6,(P14,P14,P13)) \n                  | L15 => (L2,(P6,P5,P5)) \n                  | L16 => (L6,(P13,P14,P13)) \n                  | L17 => (L2,(P5,P5,P5)) \n                  | L18 => (L3,(P8,P8,P7)) \n                  | L19 => (L6,(P14,P14,P13)) \n                  | L20 => (L3,(P8,P8,P7)) \n                  | L21 => (L6,(P13,P14,P13)) \n                  | L22 => (L3,(P7,P8,P7)) \n                  | L23 => (L6,(P14,P14,P13)) \n                  | L24 => (L3,(P8,P8,P7)) \n                  | L25 => (L6,(P13,P14,P13)) \n                  | L26 => (L3,(P7,P8,P7)) \n                  | L27 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L28 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L3,(P7,P7,P7)) \n                  | L11 => (L6,(P13,P13,P13)) \n                  | L12 => (L2,(P5,P5,P5)) \n                  | L13 => (L3,(P7,P7,P7)) \n                  | L14 => (L6,(P14,P13,P13)) \n                  | L15 => (L2,(P6,P5,P5)) \n                  | L16 => (L6,(P13,P13,P13)) \n                  | L17 => (L2,(P5,P5,P5)) \n                  | L18 => (L3,(P8,P7,P7)) \n                  | L19 => (L6,(P14,P13,P13)) \n                  | L20 => (L3,(P8,P7,P7)) \n                  | L21 => (L6,(P13,P13,P13)) \n                  | L22 => (L3,(P7,P7,P7)) \n                  | L23 => (L6,(P14,P13,P13)) \n                  | L24 => (L3,(P8,P7,P7)) \n                  | L25 => (L6,(P13,P13,P13)) \n                  | L26 => (L3,(P7,P7,P7)) \n                  | L27 => (L2,(P5,P5,P5)) \n                  | L28 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L29 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                  | L4 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                  | L4 => (L2,(P0,P0,P5)) \n                  | L5 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                  | L4 => (L2,(P0,P0,P5)) \n                  | L5 => (L2,(P0,P0,P5)) \n                  | L6 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L2,(P0,P6,P5)) \n                  | L1 => (L2,(P0,P6,P5)) \n                  | L2 => (L2,(P0,P6,P5)) \n                  | L3 => (L2,(P0,P6,P5)) \n                  | L4 => (L2,(P0,P6,P5)) \n                  | L5 => (L2,(P0,P6,P5)) \n                  | L6 => (L2,(P0,P6,P5)) \n                  | L7 => (L2,(P6,P6,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L4,(P0,P10,P9)) \n                  | L1 => (L4,(P0,P10,P9)) \n                  | L2 => (L4,(P0,P10,P9)) \n                  | L3 => (L4,(P0,P10,P9)) \n                  | L4 => (L4,(P0,P10,P9)) \n                  | L5 => (L4,(P0,P10,P9)) \n                  | L6 => (L4,(P0,P10,P9)) \n                  | L7 => (L10,(P1,P1,P9)) \n                  | L8 => (L4,(P10,P10,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L5,(P0,P12,P11)) \n                  | L1 => (L5,(P0,P12,P11)) \n                  | L2 => (L5,(P0,P12,P11)) \n                  | L3 => (L5,(P0,P12,P11)) \n                  | L4 => (L5,(P0,P12,P11)) \n                  | L5 => (L5,(P0,P12,P11)) \n                  | L6 => (L5,(P0,P12,P11)) \n                  | L7 => (L10,(P1,P1,P9)) \n                  | L8 => (L10,(P1,P1,P9)) \n                  | L9 => (L5,(P12,P12,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L4,(P0,P9,P9)) \n                  | L1 => (L4,(P0,P9,P9)) \n                  | L2 => (L4,(P0,P9,P9)) \n                  | L3 => (L4,(P0,P9,P9)) \n                  | L4 => (L4,(P0,P9,P9)) \n                  | L5 => (L4,(P0,P9,P9)) \n                  | L6 => (L4,(P0,P9,P9)) \n                  | L7 => (L10,(P1,P1,P9)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L10,(P1,P1,P9)) \n                  | L10 => (L4,(P9,P9,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L5,(P0,P11,P11)) \n                  | L1 => (L5,(P0,P11,P11)) \n                  | L2 => (L5,(P0,P11,P11)) \n                  | L3 => (L5,(P0,P11,P11)) \n                  | L4 => (L5,(P0,P11,P11)) \n                  | L5 => (L5,(P0,P11,P11)) \n                  | L6 => (L5,(P0,P11,P11)) \n                  | L7 => (L10,(P1,P1,P9)) \n                  | L8 => (L10,(P1,P1,P9)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L10,(P1,P1,P9)) \n                  | L11 => (L5,(P11,P11,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L10,(P1,P1,P9)) \n                  | L9 => (L10,(P1,P1,P9)) \n                  | L10 => (L10,(P1,P1,P9)) \n                  | L11 => (L10,(P1,P1,P9)) \n                  | L12 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L4,(P0,P10,P9)) \n                  | L1 => (L4,(P0,P10,P9)) \n                  | L2 => (L4,(P0,P10,P9)) \n                  | L3 => (L4,(P0,P10,P9)) \n                  | L4 => (L4,(P0,P10,P9)) \n                  | L5 => (L4,(P0,P10,P9)) \n                  | L6 => (L4,(P0,P10,P9)) \n                  | L7 => (L10,(P1,P7,P9)) \n                  | L8 => (L4,(P10,P10,P9)) \n                  | L9 => (L10,(P1,P7,P9)) \n                  | L10 => (L4,(P9,P10,P9)) \n                  | L11 => (L10,(P1,P7,P9)) \n                  | L12 => (L10,(P1,P7,P9)) \n                  | L13 => (L4,(P10,P10,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L5,(P0,P11,P11)) \n                  | L1 => (L5,(P0,P11,P11)) \n                  | L2 => (L5,(P0,P11,P11)) \n                  | L3 => (L5,(P0,P11,P11)) \n                  | L4 => (L5,(P0,P11,P11)) \n                  | L5 => (L5,(P0,P11,P11)) \n                  | L6 => (L5,(P0,P11,P11)) \n                  | L7 => (L11,(P1,P11,P11)) \n                  | L8 => (L11,(P1,P11,P11)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L11,(P1,P11,P11)) \n                  | L11 => (L5,(P11,P11,P11)) \n                  | L12 => (L11,(P1,P11,P11)) \n                  | L13 => (L14,(P2,P2,P11)) \n                  | L14 => (L5,(P11,P11,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L2,(P0,P6,P5)) \n                  | L1 => (L2,(P0,P6,P5)) \n                  | L2 => (L2,(P0,P6,P5)) \n                  | L3 => (L2,(P0,P6,P5)) \n                  | L4 => (L2,(P0,P6,P5)) \n                  | L5 => (L2,(P0,P6,P5)) \n                  | L6 => (L2,(P0,P6,P5)) \n                  | L7 => (L2,(P6,P6,P5)) \n                  | L8 => (L12,(P1,P3,P5)) \n                  | L9 => (L12,(P1,P3,P5)) \n                  | L10 => (L12,(P1,P3,P5)) \n                  | L11 => (L12,(P1,P3,P5)) \n                  | L12 => (L2,(P5,P6,P5)) \n                  | L13 => (L14,(P2,P2,P11)) \n                  | L14 => (L14,(P2,P2,P11)) \n                  | L15 => (L2,(P6,P6,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L5,(P0,P12,P11)) \n                  | L1 => (L5,(P0,P12,P11)) \n                  | L2 => (L5,(P0,P12,P11)) \n                  | L3 => (L5,(P0,P12,P11)) \n                  | L4 => (L5,(P0,P12,P11)) \n                  | L5 => (L5,(P0,P12,P11)) \n                  | L6 => (L5,(P0,P12,P11)) \n                  | L7 => (L11,(P1,P13,P11)) \n                  | L8 => (L11,(P1,P13,P11)) \n                  | L9 => (L5,(P12,P12,P11)) \n                  | L10 => (L11,(P1,P13,P11)) \n                  | L11 => (L5,(P11,P12,P11)) \n                  | L12 => (L11,(P1,P13,P11)) \n                  | L13 => (L14,(P2,P2,P11)) \n                  | L14 => (L5,(P11,P12,P11)) \n                  | L15 => (L14,(P2,P2,P11)) \n                  | L16 => (L5,(P12,P12,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L12,(P1,P5,P5)) \n                  | L9 => (L12,(P1,P5,P5)) \n                  | L10 => (L12,(P1,P5,P5)) \n                  | L11 => (L12,(P1,P5,P5)) \n                  | L12 => (L2,(P5,P5,P5)) \n                  | L13 => (L14,(P2,P2,P11)) \n                  | L14 => (L14,(P2,P2,P11)) \n                  | L15 => (L2,(P6,P5,P5)) \n                  | L16 => (L14,(P2,P2,P11)) \n                  | L17 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L4,(P0,P9,P9)) \n                  | L1 => (L4,(P0,P9,P9)) \n                  | L2 => (L4,(P0,P9,P9)) \n                  | L3 => (L4,(P0,P9,P9)) \n                  | L4 => (L4,(P0,P9,P9)) \n                  | L5 => (L4,(P0,P9,P9)) \n                  | L6 => (L4,(P0,P9,P9)) \n                  | L7 => (L10,(P1,P9,P9)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L10,(P1,P9,P9)) \n                  | L10 => (L4,(P9,P9,P9)) \n                  | L11 => (L10,(P1,P9,P9)) \n                  | L12 => (L10,(P1,P9,P9)) \n                  | L13 => (L4,(P10,P9,P9)) \n                  | L14 => (L14,(P2,P2,P11)) \n                  | L15 => (L14,(P2,P2,P11)) \n                  | L16 => (L14,(P2,P2,P11)) \n                  | L17 => (L14,(P2,P2,P11)) \n                  | L18 => (L4,(P9,P9,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L4,(P0,P10,P9)) \n                  | L1 => (L4,(P0,P10,P9)) \n                  | L2 => (L4,(P0,P10,P9)) \n                  | L3 => (L4,(P0,P10,P9)) \n                  | L4 => (L4,(P0,P10,P9)) \n                  | L5 => (L4,(P0,P10,P9)) \n                  | L6 => (L4,(P0,P10,P9)) \n                  | L7 => (L12,(P1,P3,P5)) \n                  | L8 => (L4,(P10,P10,P9)) \n                  | L9 => (L12,(P1,P3,P5)) \n                  | L10 => (L4,(P9,P10,P9)) \n                  | L11 => (L12,(P1,P3,P5)) \n                  | L12 => (L12,(P1,P3,P5)) \n                  | L13 => (L4,(P10,P10,P9)) \n                  | L14 => (L14,(P2,P14,P11)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L14,(P2,P14,P11)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L4,(P9,P10,P9)) \n                  | L19 => (L4,(P10,P10,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L20 => match l1 with \n                  | L0 => (L5,(P0,P12,P11)) \n                  | L1 => (L5,(P0,P12,P11)) \n                  | L2 => (L5,(P0,P12,P11)) \n                  | L3 => (L5,(P0,P12,P11)) \n                  | L4 => (L5,(P0,P12,P11)) \n                  | L5 => (L5,(P0,P12,P11)) \n                  | L6 => (L5,(P0,P12,P11)) \n                  | L7 => (L12,(P1,P3,P5)) \n                  | L8 => (L12,(P1,P3,P5)) \n                  | L9 => (L5,(P12,P12,P11)) \n                  | L10 => (L12,(P1,P3,P5)) \n                  | L11 => (L5,(P11,P12,P11)) \n                  | L12 => (L12,(P1,P3,P5)) \n                  | L13 => (L18,(P2,P8,P9)) \n                  | L14 => (L5,(P11,P12,P11)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L5,(P12,P12,P11)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L18,(P2,P8,P9)) \n                  | L19 => (L12,(P3,P3,P5)) \n                  | L20 => (L5,(P12,P12,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L21 => match l1 with \n                  | L0 => (L4,(P0,P9,P9)) \n                  | L1 => (L4,(P0,P9,P9)) \n                  | L2 => (L4,(P0,P9,P9)) \n                  | L3 => (L4,(P0,P9,P9)) \n                  | L4 => (L4,(P0,P9,P9)) \n                  | L5 => (L4,(P0,P9,P9)) \n                  | L6 => (L4,(P0,P9,P9)) \n                  | L7 => (L10,(P1,P9,P9)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L10,(P1,P9,P9)) \n                  | L10 => (L4,(P9,P9,P9)) \n                  | L11 => (L10,(P1,P9,P9)) \n                  | L12 => (L10,(P1,P9,P9)) \n                  | L13 => (L4,(P10,P9,P9)) \n                  | L14 => (L11,(P11,P13,P11)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L11,(P13,P13,P11)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L4,(P9,P9,P9)) \n                  | L19 => (L4,(P10,P9,P9)) \n                  | L20 => (L12,(P3,P3,P5)) \n                  | L21 => (L4,(P9,P9,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L22 => match l1 with \n                  | L0 => (L5,(P0,P11,P11)) \n                  | L1 => (L5,(P0,P11,P11)) \n                  | L2 => (L5,(P0,P11,P11)) \n                  | L3 => (L5,(P0,P11,P11)) \n                  | L4 => (L5,(P0,P11,P11)) \n                  | L5 => (L5,(P0,P11,P11)) \n                  | L6 => (L5,(P0,P11,P11)) \n                  | L7 => (L10,(P1,P7,P9)) \n                  | L8 => (L10,(P1,P7,P9)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L10,(P1,P7,P9)) \n                  | L11 => (L5,(P11,P11,P11)) \n                  | L12 => (L10,(P1,P7,P9)) \n                  | L13 => (L10,(P7,P7,P9)) \n                  | L14 => (L5,(P11,P11,P11)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L5,(P12,P11,P11)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L10,(P9,P7,P9)) \n                  | L19 => (L12,(P3,P3,P5)) \n                  | L20 => (L5,(P12,P11,P11)) \n                  | L21 => (L10,(P9,P7,P9)) \n                  | L22 => (L5,(P11,P11,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L23 => match l1 with \n                  | L0 => (L4,(P0,P9,P9)) \n                  | L1 => (L4,(P0,P9,P9)) \n                  | L2 => (L4,(P0,P9,P9)) \n                  | L3 => (L4,(P0,P9,P9)) \n                  | L4 => (L4,(P0,P9,P9)) \n                  | L5 => (L4,(P0,P9,P9)) \n                  | L6 => (L4,(P0,P9,P9)) \n                  | L7 => (L10,(P1,P9,P9)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L10,(P1,P9,P9)) \n                  | L10 => (L4,(P9,P9,P9)) \n                  | L11 => (L10,(P1,P9,P9)) \n                  | L12 => (L10,(P1,P9,P9)) \n                  | L13 => (L4,(P10,P9,P9)) \n                  | L14 => (L14,(P2,P14,P11)) \n                  | L15 => (L14,(P2,P14,P11)) \n                  | L16 => (L14,(P2,P14,P11)) \n                  | L17 => (L14,(P2,P14,P11)) \n                  | L18 => (L4,(P9,P9,P9)) \n                  | L19 => (L4,(P10,P9,P9)) \n                  | L20 => (L18,(P8,P9,P9)) \n                  | L21 => (L4,(P9,P9,P9)) \n                  | L22 => (L10,(P7,P9,P9)) \n                  | L23 => (L4,(P9,P9,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L24 => match l1 with \n                  | L0 => (L5,(P0,P11,P11)) \n                  | L1 => (L5,(P0,P11,P11)) \n                  | L2 => (L5,(P0,P11,P11)) \n                  | L3 => (L5,(P0,P11,P11)) \n                  | L4 => (L5,(P0,P11,P11)) \n                  | L5 => (L5,(P0,P11,P11)) \n                  | L6 => (L5,(P0,P11,P11)) \n                  | L7 => (L11,(P1,P11,P11)) \n                  | L8 => (L11,(P1,P11,P11)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L11,(P1,P11,P11)) \n                  | L11 => (L5,(P11,P11,P11)) \n                  | L12 => (L11,(P1,P11,P11)) \n                  | L13 => (L14,(P2,P11,P11)) \n                  | L14 => (L5,(P11,P11,P11)) \n                  | L15 => (L14,(P2,P11,P11)) \n                  | L16 => (L5,(P12,P11,P11)) \n                  | L17 => (L14,(P2,P11,P11)) \n                  | L18 => (L14,(P2,P11,P11)) \n                  | L19 => (L14,(P14,P11,P11)) \n                  | L20 => (L5,(P12,P11,P11)) \n                  | L21 => (L11,(P13,P11,P11)) \n                  | L22 => (L5,(P11,P11,P11)) \n                  | L23 => (L14,(P14,P11,P11)) \n                  | L24 => (L5,(P11,P11,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L25 => match l1 with \n                  | L0 => (L4,(P0,P10,P9)) \n                  | L1 => (L4,(P0,P10,P9)) \n                  | L2 => (L4,(P0,P10,P9)) \n                  | L3 => (L4,(P0,P10,P9)) \n                  | L4 => (L4,(P0,P10,P9)) \n                  | L5 => (L4,(P0,P10,P9)) \n                  | L6 => (L4,(P0,P10,P9)) \n                  | L7 => (L11,(P1,P13,P11)) \n                  | L8 => (L4,(P10,P10,P9)) \n                  | L9 => (L11,(P1,P13,P11)) \n                  | L10 => (L4,(P9,P10,P9)) \n                  | L11 => (L11,(P1,P13,P11)) \n                  | L12 => (L11,(P1,P13,P11)) \n                  | L13 => (L4,(P10,P10,P9)) \n                  | L14 => (L11,(P11,P13,P11)) \n                  | L15 => (L17,(P2,P4,P5)) \n                  | L16 => (L11,(P13,P13,P11)) \n                  | L17 => (L17,(P2,P4,P5)) \n                  | L18 => (L4,(P9,P10,P9)) \n                  | L19 => (L4,(P10,P10,P9)) \n                  | L20 => (L21,(P3,P13,P9)) \n                  | L21 => (L4,(P9,P10,P9)) \n                  | L22 => (L11,(P11,P13,P11)) \n                  | L23 => (L4,(P9,P10,P9)) \n                  | L24 => (L11,(P11,P13,P11)) \n                  | L25 => (L4,(P10,P10,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L26 => match l1 with \n                  | L0 => (L5,(P0,P12,P11)) \n                  | L1 => (L5,(P0,P12,P11)) \n                  | L2 => (L5,(P0,P12,P11)) \n                  | L3 => (L5,(P0,P12,P11)) \n                  | L4 => (L5,(P0,P12,P11)) \n                  | L5 => (L5,(P0,P12,P11)) \n                  | L6 => (L5,(P0,P12,P11)) \n                  | L7 => (L10,(P1,P7,P9)) \n                  | L8 => (L10,(P1,P7,P9)) \n                  | L9 => (L5,(P12,P12,P11)) \n                  | L10 => (L10,(P1,P7,P9)) \n                  | L11 => (L5,(P11,P12,P11)) \n                  | L12 => (L10,(P1,P7,P9)) \n                  | L13 => (L10,(P7,P7,P9)) \n                  | L14 => (L5,(P11,P12,P11)) \n                  | L15 => (L17,(P2,P4,P5)) \n                  | L16 => (L5,(P12,P12,P11)) \n                  | L17 => (L17,(P2,P4,P5)) \n                  | L18 => (L10,(P9,P7,P9)) \n                  | L19 => (L22,(P3,P7,P11)) \n                  | L20 => (L5,(P12,P12,P11)) \n                  | L21 => (L10,(P9,P7,P9)) \n                  | L22 => (L5,(P11,P12,P11)) \n                  | L23 => (L10,(P9,P7,P9)) \n                  | L24 => (L5,(P11,P12,P11)) \n                  | L25 => (L17,(P4,P4,P5)) \n                  | L26 => (L5,(P12,P12,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L27 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L12,(P1,P5,P5)) \n                  | L9 => (L12,(P1,P5,P5)) \n                  | L10 => (L12,(P1,P5,P5)) \n                  | L11 => (L12,(P1,P5,P5)) \n                  | L12 => (L2,(P5,P5,P5)) \n                  | L13 => (L14,(P2,P14,P11)) \n                  | L14 => (L14,(P2,P14,P11)) \n                  | L15 => (L2,(P6,P5,P5)) \n                  | L16 => (L14,(P2,P14,P11)) \n                  | L17 => (L2,(P5,P5,P5)) \n                  | L18 => (L14,(P2,P14,P11)) \n                  | L19 => (L12,(P3,P5,P5)) \n                  | L20 => (L12,(P3,P5,P5)) \n                  | L21 => (L12,(P3,P5,P5)) \n                  | L22 => (L12,(P3,P5,P5)) \n                  | L23 => (L14,(P14,P14,P11)) \n                  | L24 => (L14,(P11,P14,P11)) \n                  | L25 => (L17,(P4,P5,P5)) \n                  | L26 => (L17,(P4,P5,P5)) \n                  | L27 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L28 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L10,(P1,P7,P9)) \n                  | L9 => (L10,(P1,P7,P9)) \n                  | L10 => (L10,(P1,P7,P9)) \n                  | L11 => (L10,(P1,P7,P9)) \n                  | L12 => (L2,(P5,P5,P5)) \n                  | L13 => (L10,(P7,P7,P9)) \n                  | L14 => (L11,(P11,P13,P11)) \n                  | L15 => (L2,(P6,P5,P5)) \n                  | L16 => (L11,(P13,P13,P11)) \n                  | L17 => (L2,(P5,P5,P5)) \n                  | L18 => (L10,(P9,P7,P9)) \n                  | L19 => (L12,(P3,P5,P5)) \n                  | L20 => (L12,(P3,P5,P5)) \n                  | L21 => (L10,(P9,P7,P9)) \n                  | L22 => (L10,(P7,P7,P9)) \n                  | L23 => (L10,(P9,P7,P9)) \n                  | L24 => (L11,(P11,P13,P11)) \n                  | L25 => (L11,(P13,P13,P11)) \n                  | L26 => (L10,(P7,P7,P9)) \n                  | L27 => (L2,(P5,P5,P5)) \n                  | L28 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L29 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L4,(P9,P9,P9)) \n                  | L11 => (L5,(P11,P11,P11)) \n                  | L12 => (L2,(P5,P5,P5)) \n                  | L13 => (L4,(P10,P9,P9)) \n                  | L14 => (L5,(P11,P11,P11)) \n                  | L15 => (L2,(P6,P5,P5)) \n                  | L16 => (L5,(P12,P11,P11)) \n                  | L17 => (L2,(P5,P5,P5)) \n                  | L18 => (L4,(P9,P9,P9)) \n                  | L19 => (L4,(P10,P9,P9)) \n                  | L20 => (L5,(P12,P11,P11)) \n                  | L21 => (L4,(P9,P9,P9)) \n                  | L22 => (L5,(P11,P11,P11)) \n                  | L23 => (L4,(P9,P9,P9)) \n                  | L24 => (L5,(P11,P11,P11)) \n                  | L25 => (L4,(P10,P9,P9)) \n                  | L26 => (L5,(P12,P11,P11)) \n                  | L27 => (L2,(P5,P5,P5)) \n                  | L28 => (L2,(P5,P5,P5)) \n                  | L29 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L30 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                  | L4 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                  | L4 => (L2,(P0,P0,P5)) \n                  | L5 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L2,(P0,P0,P5)) \n                  | L1 => (L2,(P0,P0,P5)) \n                  | L2 => (L2,(P0,P0,P5)) \n                  | L3 => (L2,(P0,P0,P5)) \n                  | L4 => (L2,(P0,P0,P5)) \n                  | L5 => (L2,(P0,P0,P5)) \n                  | L6 => (L2,(P0,P0,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L2,(P0,P6,P5)) \n                  | L1 => (L2,(P0,P6,P5)) \n                  | L2 => (L2,(P0,P6,P5)) \n                  | L3 => (L2,(P0,P6,P5)) \n                  | L4 => (L2,(P0,P6,P5)) \n                  | L5 => (L2,(P0,P6,P5)) \n                  | L6 => (L2,(P0,P6,P5)) \n                  | L7 => (L2,(P6,P6,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L4,(P0,P10,P10)) \n                  | L1 => (L4,(P0,P10,P10)) \n                  | L2 => (L4,(P0,P10,P10)) \n                  | L3 => (L4,(P0,P10,P10)) \n                  | L4 => (L4,(P0,P10,P10)) \n                  | L5 => (L4,(P0,P10,P10)) \n                  | L6 => (L4,(P0,P10,P10)) \n                  | L7 => (L8,(P1,P1,P10)) \n                  | L8 => (L4,(P10,P10,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L5,(P0,P12,P12)) \n                  | L1 => (L5,(P0,P12,P12)) \n                  | L2 => (L5,(P0,P12,P12)) \n                  | L3 => (L5,(P0,P12,P12)) \n                  | L4 => (L5,(P0,P12,P12)) \n                  | L5 => (L5,(P0,P12,P12)) \n                  | L6 => (L5,(P0,P12,P12)) \n                  | L7 => (L8,(P1,P1,P10)) \n                  | L8 => (L8,(P1,P1,P10)) \n                  | L9 => (L5,(P12,P12,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L4,(P0,P9,P10)) \n                  | L1 => (L4,(P0,P9,P10)) \n                  | L2 => (L4,(P0,P9,P10)) \n                  | L3 => (L4,(P0,P9,P10)) \n                  | L4 => (L4,(P0,P9,P10)) \n                  | L5 => (L4,(P0,P9,P10)) \n                  | L6 => (L4,(P0,P9,P10)) \n                  | L7 => (L8,(P1,P1,P10)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L8,(P1,P1,P10)) \n                  | L10 => (L4,(P9,P9,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L5,(P0,P11,P12)) \n                  | L1 => (L5,(P0,P11,P12)) \n                  | L2 => (L5,(P0,P11,P12)) \n                  | L3 => (L5,(P0,P11,P12)) \n                  | L4 => (L5,(P0,P11,P12)) \n                  | L5 => (L5,(P0,P11,P12)) \n                  | L6 => (L5,(P0,P11,P12)) \n                  | L7 => (L8,(P1,P1,P10)) \n                  | L8 => (L8,(P1,P1,P10)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L8,(P1,P1,P10)) \n                  | L11 => (L5,(P11,P11,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L8,(P1,P1,P10)) \n                  | L9 => (L8,(P1,P1,P10)) \n                  | L10 => (L8,(P1,P1,P10)) \n                  | L11 => (L8,(P1,P1,P10)) \n                  | L12 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L4,(P0,P10,P10)) \n                  | L1 => (L4,(P0,P10,P10)) \n                  | L2 => (L4,(P0,P10,P10)) \n                  | L3 => (L4,(P0,P10,P10)) \n                  | L4 => (L4,(P0,P10,P10)) \n                  | L5 => (L4,(P0,P10,P10)) \n                  | L6 => (L4,(P0,P10,P10)) \n                  | L7 => (L8,(P1,P10,P10)) \n                  | L8 => (L4,(P10,P10,P10)) \n                  | L9 => (L8,(P1,P10,P10)) \n                  | L10 => (L4,(P9,P10,P10)) \n                  | L11 => (L8,(P1,P10,P10)) \n                  | L12 => (L8,(P1,P10,P10)) \n                  | L13 => (L4,(P10,P10,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L5,(P0,P11,P12)) \n                  | L1 => (L5,(P0,P11,P12)) \n                  | L2 => (L5,(P0,P11,P12)) \n                  | L3 => (L5,(P0,P11,P12)) \n                  | L4 => (L5,(P0,P11,P12)) \n                  | L5 => (L5,(P0,P11,P12)) \n                  | L6 => (L5,(P0,P11,P12)) \n                  | L7 => (L9,(P1,P14,P12)) \n                  | L8 => (L9,(P1,P14,P12)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L9,(P1,P14,P12)) \n                  | L11 => (L5,(P11,P11,P12)) \n                  | L12 => (L9,(P1,P14,P12)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L5,(P11,P11,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L2,(P0,P6,P5)) \n                  | L1 => (L2,(P0,P6,P5)) \n                  | L2 => (L2,(P0,P6,P5)) \n                  | L3 => (L2,(P0,P6,P5)) \n                  | L4 => (L2,(P0,P6,P5)) \n                  | L5 => (L2,(P0,P6,P5)) \n                  | L6 => (L2,(P0,P6,P5)) \n                  | L7 => (L2,(P6,P6,P5)) \n                  | L8 => (L12,(P1,P3,P5)) \n                  | L9 => (L12,(P1,P3,P5)) \n                  | L10 => (L12,(P1,P3,P5)) \n                  | L11 => (L12,(P1,P3,P5)) \n                  | L12 => (L2,(P5,P6,P5)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L13,(P2,P2,P10)) \n                  | L15 => (L2,(P6,P6,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L5,(P0,P12,P12)) \n                  | L1 => (L5,(P0,P12,P12)) \n                  | L2 => (L5,(P0,P12,P12)) \n                  | L3 => (L5,(P0,P12,P12)) \n                  | L4 => (L5,(P0,P12,P12)) \n                  | L5 => (L5,(P0,P12,P12)) \n                  | L6 => (L5,(P0,P12,P12)) \n                  | L7 => (L9,(P1,P12,P12)) \n                  | L8 => (L9,(P1,P12,P12)) \n                  | L9 => (L5,(P12,P12,P12)) \n                  | L10 => (L9,(P1,P12,P12)) \n                  | L11 => (L5,(P11,P12,P12)) \n                  | L12 => (L9,(P1,P12,P12)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L5,(P11,P12,P12)) \n                  | L15 => (L13,(P2,P2,P10)) \n                  | L16 => (L5,(P12,P12,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L12,(P1,P5,P5)) \n                  | L9 => (L12,(P1,P5,P5)) \n                  | L10 => (L12,(P1,P5,P5)) \n                  | L11 => (L12,(P1,P5,P5)) \n                  | L12 => (L2,(P5,P5,P5)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L13,(P2,P2,P10)) \n                  | L15 => (L2,(P6,P5,P5)) \n                  | L16 => (L13,(P2,P2,P10)) \n                  | L17 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L4,(P0,P9,P10)) \n                  | L1 => (L4,(P0,P9,P10)) \n                  | L2 => (L4,(P0,P9,P10)) \n                  | L3 => (L4,(P0,P9,P10)) \n                  | L4 => (L4,(P0,P9,P10)) \n                  | L5 => (L4,(P0,P9,P10)) \n                  | L6 => (L4,(P0,P9,P10)) \n                  | L7 => (L8,(P1,P8,P10)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L8,(P1,P8,P10)) \n                  | L10 => (L4,(P9,P9,P10)) \n                  | L11 => (L8,(P1,P8,P10)) \n                  | L12 => (L8,(P1,P8,P10)) \n                  | L13 => (L4,(P10,P9,P10)) \n                  | L14 => (L13,(P2,P2,P10)) \n                  | L15 => (L13,(P2,P2,P10)) \n                  | L16 => (L13,(P2,P2,P10)) \n                  | L17 => (L13,(P2,P2,P10)) \n                  | L18 => (L4,(P9,P9,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L4,(P0,P10,P10)) \n                  | L1 => (L4,(P0,P10,P10)) \n                  | L2 => (L4,(P0,P10,P10)) \n                  | L3 => (L4,(P0,P10,P10)) \n                  | L4 => (L4,(P0,P10,P10)) \n                  | L5 => (L4,(P0,P10,P10)) \n                  | L6 => (L4,(P0,P10,P10)) \n                  | L7 => (L8,(P1,P10,P10)) \n                  | L8 => (L4,(P10,P10,P10)) \n                  | L9 => (L8,(P1,P10,P10)) \n                  | L10 => (L4,(P9,P10,P10)) \n                  | L11 => (L8,(P1,P10,P10)) \n                  | L12 => (L8,(P1,P10,P10)) \n                  | L13 => (L4,(P10,P10,P10)) \n                  | L14 => (L9,(P14,P14,P12)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L9,(P12,P14,P12)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L4,(P9,P10,P10)) \n                  | L19 => (L4,(P10,P10,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L20 => match l1 with \n                  | L0 => (L5,(P0,P12,P12)) \n                  | L1 => (L5,(P0,P12,P12)) \n                  | L2 => (L5,(P0,P12,P12)) \n                  | L3 => (L5,(P0,P12,P12)) \n                  | L4 => (L5,(P0,P12,P12)) \n                  | L5 => (L5,(P0,P12,P12)) \n                  | L6 => (L5,(P0,P12,P12)) \n                  | L7 => (L8,(P1,P8,P10)) \n                  | L8 => (L8,(P1,P8,P10)) \n                  | L9 => (L5,(P12,P12,P12)) \n                  | L10 => (L8,(P1,P8,P10)) \n                  | L11 => (L5,(P11,P12,P12)) \n                  | L12 => (L8,(P1,P8,P10)) \n                  | L13 => (L8,(P10,P8,P10)) \n                  | L14 => (L5,(P11,P12,P12)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L5,(P12,P12,P12)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L8,(P8,P8,P10)) \n                  | L19 => (L8,(P10,P8,P10)) \n                  | L20 => (L5,(P12,P12,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L21 => match l1 with \n                  | L0 => (L4,(P0,P9,P10)) \n                  | L1 => (L4,(P0,P9,P10)) \n                  | L2 => (L4,(P0,P9,P10)) \n                  | L3 => (L4,(P0,P9,P10)) \n                  | L4 => (L4,(P0,P9,P10)) \n                  | L5 => (L4,(P0,P9,P10)) \n                  | L6 => (L4,(P0,P9,P10)) \n                  | L7 => (L12,(P1,P3,P5)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L12,(P1,P3,P5)) \n                  | L10 => (L4,(P9,P9,P10)) \n                  | L11 => (L12,(P1,P3,P5)) \n                  | L12 => (L12,(P1,P3,P5)) \n                  | L13 => (L4,(P10,P9,P10)) \n                  | L14 => (L16,(P2,P13,P12)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L16,(P2,P13,P12)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L4,(P9,P9,P10)) \n                  | L19 => (L4,(P10,P9,P10)) \n                  | L20 => (L12,(P3,P3,P5)) \n                  | L21 => (L4,(P9,P9,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L22 => match l1 with \n                  | L0 => (L5,(P0,P11,P12)) \n                  | L1 => (L5,(P0,P11,P12)) \n                  | L2 => (L5,(P0,P11,P12)) \n                  | L3 => (L5,(P0,P11,P12)) \n                  | L4 => (L5,(P0,P11,P12)) \n                  | L5 => (L5,(P0,P11,P12)) \n                  | L6 => (L5,(P0,P11,P12)) \n                  | L7 => (L12,(P1,P3,P5)) \n                  | L8 => (L12,(P1,P3,P5)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L12,(P1,P3,P5)) \n                  | L11 => (L5,(P11,P11,P12)) \n                  | L12 => (L12,(P1,P3,P5)) \n                  | L13 => (L13,(P2,P7,P10)) \n                  | L14 => (L5,(P11,P11,P12)) \n                  | L15 => (L12,(P3,P3,P5)) \n                  | L16 => (L5,(P12,P11,P12)) \n                  | L17 => (L12,(P5,P3,P5)) \n                  | L18 => (L13,(P2,P7,P10)) \n                  | L19 => (L12,(P3,P3,P5)) \n                  | L20 => (L5,(P12,P11,P12)) \n                  | L21 => (L12,(P3,P3,P5)) \n                  | L22 => (L5,(P11,P11,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L23 => match l1 with \n                  | L0 => (L4,(P0,P9,P10)) \n                  | L1 => (L4,(P0,P9,P10)) \n                  | L2 => (L4,(P0,P9,P10)) \n                  | L3 => (L4,(P0,P9,P10)) \n                  | L4 => (L4,(P0,P9,P10)) \n                  | L5 => (L4,(P0,P9,P10)) \n                  | L6 => (L4,(P0,P9,P10)) \n                  | L7 => (L9,(P1,P14,P12)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L9,(P1,P14,P12)) \n                  | L10 => (L4,(P9,P9,P10)) \n                  | L11 => (L9,(P1,P14,P12)) \n                  | L12 => (L9,(P1,P14,P12)) \n                  | L13 => (L4,(P10,P9,P10)) \n                  | L14 => (L9,(P14,P14,P12)) \n                  | L15 => (L17,(P2,P4,P5)) \n                  | L16 => (L9,(P12,P14,P12)) \n                  | L17 => (L17,(P2,P4,P5)) \n                  | L18 => (L4,(P9,P9,P10)) \n                  | L19 => (L4,(P10,P9,P10)) \n                  | L20 => (L9,(P12,P14,P12)) \n                  | L21 => (L4,(P9,P9,P10)) \n                  | L22 => (L19,(P3,P14,P10)) \n                  | L23 => (L4,(P9,P9,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L24 => match l1 with \n                  | L0 => (L5,(P0,P11,P12)) \n                  | L1 => (L5,(P0,P11,P12)) \n                  | L2 => (L5,(P0,P11,P12)) \n                  | L3 => (L5,(P0,P11,P12)) \n                  | L4 => (L5,(P0,P11,P12)) \n                  | L5 => (L5,(P0,P11,P12)) \n                  | L6 => (L5,(P0,P11,P12)) \n                  | L7 => (L8,(P1,P8,P10)) \n                  | L8 => (L8,(P1,P8,P10)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L8,(P1,P8,P10)) \n                  | L11 => (L5,(P11,P11,P12)) \n                  | L12 => (L8,(P1,P8,P10)) \n                  | L13 => (L8,(P10,P8,P10)) \n                  | L14 => (L5,(P11,P11,P12)) \n                  | L15 => (L17,(P2,P4,P5)) \n                  | L16 => (L5,(P12,P11,P12)) \n                  | L17 => (L17,(P2,P4,P5)) \n                  | L18 => (L8,(P8,P8,P10)) \n                  | L19 => (L8,(P10,P8,P10)) \n                  | L20 => (L5,(P12,P11,P12)) \n                  | L21 => (L20,(P3,P8,P12)) \n                  | L22 => (L5,(P11,P11,P12)) \n                  | L23 => (L17,(P4,P4,P5)) \n                  | L24 => (L5,(P11,P11,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L25 => match l1 with \n                  | L0 => (L4,(P0,P10,P10)) \n                  | L1 => (L4,(P0,P10,P10)) \n                  | L2 => (L4,(P0,P10,P10)) \n                  | L3 => (L4,(P0,P10,P10)) \n                  | L4 => (L4,(P0,P10,P10)) \n                  | L5 => (L4,(P0,P10,P10)) \n                  | L6 => (L4,(P0,P10,P10)) \n                  | L7 => (L8,(P1,P10,P10)) \n                  | L8 => (L4,(P10,P10,P10)) \n                  | L9 => (L8,(P1,P10,P10)) \n                  | L10 => (L4,(P9,P10,P10)) \n                  | L11 => (L8,(P1,P10,P10)) \n                  | L12 => (L8,(P1,P10,P10)) \n                  | L13 => (L4,(P10,P10,P10)) \n                  | L14 => (L13,(P2,P10,P10)) \n                  | L15 => (L13,(P2,P10,P10)) \n                  | L16 => (L13,(P2,P10,P10)) \n                  | L17 => (L13,(P2,P10,P10)) \n                  | L18 => (L4,(P9,P10,P10)) \n                  | L19 => (L4,(P10,P10,P10)) \n                  | L20 => (L8,(P8,P10,P10)) \n                  | L21 => (L4,(P9,P10,P10)) \n                  | L22 => (L13,(P7,P10,P10)) \n                  | L23 => (L4,(P9,P10,P10)) \n                  | L24 => (L8,(P8,P10,P10)) \n                  | L25 => (L4,(P10,P10,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L26 => match l1 with \n                  | L0 => (L5,(P0,P12,P12)) \n                  | L1 => (L5,(P0,P12,P12)) \n                  | L2 => (L5,(P0,P12,P12)) \n                  | L3 => (L5,(P0,P12,P12)) \n                  | L4 => (L5,(P0,P12,P12)) \n                  | L5 => (L5,(P0,P12,P12)) \n                  | L6 => (L5,(P0,P12,P12)) \n                  | L7 => (L9,(P1,P12,P12)) \n                  | L8 => (L9,(P1,P12,P12)) \n                  | L9 => (L5,(P12,P12,P12)) \n                  | L10 => (L9,(P1,P12,P12)) \n                  | L11 => (L5,(P11,P12,P12)) \n                  | L12 => (L9,(P1,P12,P12)) \n                  | L13 => (L13,(P2,P7,P10)) \n                  | L14 => (L5,(P11,P12,P12)) \n                  | L15 => (L13,(P2,P7,P10)) \n                  | L16 => (L5,(P12,P12,P12)) \n                  | L17 => (L13,(P2,P7,P10)) \n                  | L18 => (L13,(P2,P7,P10)) \n                  | L19 => (L9,(P14,P12,P12)) \n                  | L20 => (L5,(P12,P12,P12)) \n                  | L21 => (L16,(P13,P12,P12)) \n                  | L22 => (L5,(P11,P12,P12)) \n                  | L23 => (L9,(P14,P12,P12)) \n                  | L24 => (L5,(P11,P12,P12)) \n                  | L25 => (L13,(P10,P7,P10)) \n                  | L26 => (L5,(P12,P12,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L27 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L8,(P1,P8,P10)) \n                  | L9 => (L8,(P1,P8,P10)) \n                  | L10 => (L8,(P1,P8,P10)) \n                  | L11 => (L8,(P1,P8,P10)) \n                  | L12 => (L2,(P5,P5,P5)) \n                  | L13 => (L8,(P10,P8,P10)) \n                  | L14 => (L9,(P14,P14,P12)) \n                  | L15 => (L2,(P6,P5,P5)) \n                  | L16 => (L9,(P12,P14,P12)) \n                  | L17 => (L2,(P5,P5,P5)) \n                  | L18 => (L8,(P8,P8,P10)) \n                  | L19 => (L8,(P10,P8,P10)) \n                  | L20 => (L8,(P8,P8,P10)) \n                  | L21 => (L12,(P3,P5,P5)) \n                  | L22 => (L12,(P3,P5,P5)) \n                  | L23 => (L9,(P14,P14,P12)) \n                  | L24 => (L8,(P8,P8,P10)) \n                  | L25 => (L8,(P10,P8,P10)) \n                  | L26 => (L9,(P12,P14,P12)) \n                  | L27 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L28 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L12,(P1,P5,P5)) \n                  | L9 => (L12,(P1,P5,P5)) \n                  | L10 => (L12,(P1,P5,P5)) \n                  | L11 => (L12,(P1,P5,P5)) \n                  | L12 => (L2,(P5,P5,P5)) \n                  | L13 => (L13,(P2,P7,P10)) \n                  | L14 => (L13,(P2,P7,P10)) \n                  | L15 => (L2,(P6,P5,P5)) \n                  | L16 => (L13,(P2,P7,P10)) \n                  | L17 => (L2,(P5,P5,P5)) \n                  | L18 => (L13,(P2,P7,P10)) \n                  | L19 => (L12,(P3,P5,P5)) \n                  | L20 => (L12,(P3,P5,P5)) \n                  | L21 => (L12,(P3,P5,P5)) \n                  | L22 => (L12,(P3,P5,P5)) \n                  | L23 => (L17,(P4,P5,P5)) \n                  | L24 => (L17,(P4,P5,P5)) \n                  | L25 => (L13,(P10,P7,P10)) \n                  | L26 => (L13,(P7,P7,P10)) \n                  | L27 => (L2,(P5,P5,P5)) \n                  | L28 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L29 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L4,(P9,P9,P10)) \n                  | L11 => (L5,(P11,P11,P12)) \n                  | L12 => (L2,(P5,P5,P5)) \n                  | L13 => (L4,(P10,P9,P10)) \n                  | L14 => (L5,(P11,P11,P12)) \n                  | L15 => (L2,(P6,P5,P5)) \n                  | L16 => (L5,(P12,P11,P12)) \n                  | L17 => (L2,(P5,P5,P5)) \n                  | L18 => (L4,(P9,P9,P10)) \n                  | L19 => (L4,(P10,P9,P10)) \n                  | L20 => (L5,(P12,P11,P12)) \n                  | L21 => (L4,(P9,P9,P10)) \n                  | L22 => (L5,(P11,P11,P12)) \n                  | L23 => (L4,(P9,P9,P10)) \n                  | L24 => (L5,(P11,P11,P12)) \n                  | L25 => (L4,(P10,P9,P10)) \n                  | L26 => (L5,(P12,P11,P12)) \n                  | L27 => (L2,(P5,P5,P5)) \n                  | L28 => (L2,(P5,P5,P5)) \n                  | L29 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L30 => match l1 with \n                  | L0 => (L2,(P0,P5,P5)) \n                  | L1 => (L2,(P0,P5,P5)) \n                  | L2 => (L2,(P0,P5,P5)) \n                  | L3 => (L2,(P0,P5,P5)) \n                  | L4 => (L2,(P0,P5,P5)) \n                  | L5 => (L2,(P0,P5,P5)) \n                  | L6 => (L2,(P0,P5,P5)) \n                  | L7 => (L2,(P6,P5,P5)) \n                  | L8 => (L4,(P10,P10,P10)) \n                  | L9 => (L5,(P12,P12,P12)) \n                  | L10 => (L4,(P9,P10,P10)) \n                  | L11 => (L5,(P11,P12,P12)) \n                  | L12 => (L2,(P5,P5,P5)) \n                  | L13 => (L4,(P10,P10,P10)) \n                  | L14 => (L5,(P11,P12,P12)) \n                  | L15 => (L2,(P6,P5,P5)) \n                  | L16 => (L5,(P12,P12,P12)) \n                  | L17 => (L2,(P5,P5,P5)) \n                  | L18 => (L4,(P9,P10,P10)) \n                  | L19 => (L4,(P10,P10,P10)) \n                  | L20 => (L5,(P12,P12,P12)) \n                  | L21 => (L4,(P9,P10,P10)) \n                  | L22 => (L5,(P11,P12,P12)) \n                  | L23 => (L4,(P9,P10,P10)) \n                  | L24 => (L5,(P11,P12,P12)) \n                  | L25 => (L4,(P10,P10,P10)) \n                  | L26 => (L5,(P12,P12,P12)) \n                  | L27 => (L2,(P5,P5,P5)) \n                  | L28 => (L2,(P5,P5,P5)) \n                  | L29 => (L2,(P5,P5,P5)) \n                  | L30 => (L2,(P5,P5,P5)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L31 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                  | L4 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                  | L4 => (L2,(P0,P0,P6)) \n                  | L5 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                  | L4 => (L2,(P0,P0,P6)) \n                  | L5 => (L2,(P0,P0,P6)) \n                  | L6 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L3,(P0,P8,P7)) \n                  | L1 => (L3,(P0,P8,P7)) \n                  | L2 => (L3,(P0,P8,P7)) \n                  | L3 => (L3,(P0,P8,P7)) \n                  | L4 => (L3,(P0,P8,P7)) \n                  | L5 => (L3,(P0,P8,P7)) \n                  | L6 => (L3,(P0,P8,P7)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L3,(P8,P8,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L6,(P0,P14,P14)) \n                  | L1 => (L6,(P0,P14,P14)) \n                  | L2 => (L6,(P0,P14,P14)) \n                  | L3 => (L6,(P0,P14,P14)) \n                  | L4 => (L6,(P0,P14,P14)) \n                  | L5 => (L6,(P0,P14,P14)) \n                  | L6 => (L6,(P0,P14,P14)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L7,(P1,P1,P6)) \n                  | L9 => (L6,(P14,P14,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L3,(P0,P7,P7)) \n                  | L1 => (L3,(P0,P7,P7)) \n                  | L2 => (L3,(P0,P7,P7)) \n                  | L3 => (L3,(P0,P7,P7)) \n                  | L4 => (L3,(P0,P7,P7)) \n                  | L5 => (L3,(P0,P7,P7)) \n                  | L6 => (L3,(P0,P7,P7)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L7,(P1,P1,P6)) \n                  | L10 => (L3,(P7,P7,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L6,(P0,P13,P14)) \n                  | L1 => (L6,(P0,P13,P14)) \n                  | L2 => (L6,(P0,P13,P14)) \n                  | L3 => (L6,(P0,P13,P14)) \n                  | L4 => (L6,(P0,P13,P14)) \n                  | L5 => (L6,(P0,P13,P14)) \n                  | L6 => (L6,(P0,P13,P14)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L7,(P1,P1,P6)) \n                  | L9 => (L6,(P14,P13,P14)) \n                  | L10 => (L7,(P1,P1,P6)) \n                  | L11 => (L6,(P13,P13,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L7,(P1,P1,P6)) \n                  | L9 => (L7,(P1,P1,P6)) \n                  | L10 => (L7,(P1,P1,P6)) \n                  | L11 => (L7,(P1,P1,P6)) \n                  | L12 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L3,(P0,P7,P7)) \n                  | L1 => (L3,(P0,P7,P7)) \n                  | L2 => (L3,(P0,P7,P7)) \n                  | L3 => (L3,(P0,P7,P7)) \n                  | L4 => (L3,(P0,P7,P7)) \n                  | L5 => (L3,(P0,P7,P7)) \n                  | L6 => (L3,(P0,P7,P7)) \n                  | L7 => (L10,(P1,P7,P7)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L10,(P1,P7,P7)) \n                  | L10 => (L3,(P7,P7,P7)) \n                  | L11 => (L10,(P1,P7,P7)) \n                  | L12 => (L10,(P1,P7,P7)) \n                  | L13 => (L3,(P7,P7,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L6,(P0,P14,P14)) \n                  | L1 => (L6,(P0,P14,P14)) \n                  | L2 => (L6,(P0,P14,P14)) \n                  | L3 => (L6,(P0,P14,P14)) \n                  | L4 => (L6,(P0,P14,P14)) \n                  | L5 => (L6,(P0,P14,P14)) \n                  | L6 => (L6,(P0,P14,P14)) \n                  | L7 => (L9,(P1,P14,P14)) \n                  | L8 => (L9,(P1,P14,P14)) \n                  | L9 => (L6,(P14,P14,P14)) \n                  | L10 => (L9,(P1,P14,P14)) \n                  | L11 => (L6,(P13,P14,P14)) \n                  | L12 => (L9,(P1,P14,P14)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L6,(P14,P14,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                  | L8 => (L7,(P1,P6,P6)) \n                  | L9 => (L7,(P1,P6,P6)) \n                  | L10 => (L7,(P1,P6,P6)) \n                  | L11 => (L7,(P1,P6,P6)) \n                  | L12 => (L2,(P5,P6,P6)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L13,(P2,P2,P7)) \n                  | L15 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L6,(P0,P13,P14)) \n                  | L1 => (L6,(P0,P13,P14)) \n                  | L2 => (L6,(P0,P13,P14)) \n                  | L3 => (L6,(P0,P13,P14)) \n                  | L4 => (L6,(P0,P13,P14)) \n                  | L5 => (L6,(P0,P13,P14)) \n                  | L6 => (L6,(P0,P13,P14)) \n                  | L7 => (L9,(P1,P12,P14)) \n                  | L8 => (L9,(P1,P12,P14)) \n                  | L9 => (L6,(P14,P13,P14)) \n                  | L10 => (L9,(P1,P12,P14)) \n                  | L11 => (L6,(P13,P13,P14)) \n                  | L12 => (L9,(P1,P12,P14)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L6,(P14,P13,P14)) \n                  | L15 => (L13,(P2,P2,P7)) \n                  | L16 => (L6,(P13,P13,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L7,(P1,P4,P6)) \n                  | L9 => (L7,(P1,P4,P6)) \n                  | L10 => (L7,(P1,P4,P6)) \n                  | L11 => (L7,(P1,P4,P6)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L13,(P2,P2,P7)) \n                  | L14 => (L13,(P2,P2,P7)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L13,(P2,P2,P7)) \n                  | L17 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L3,(P0,P8,P7)) \n                  | L1 => (L3,(P0,P8,P7)) \n                  | L2 => (L3,(P0,P8,P7)) \n                  | L3 => (L3,(P0,P8,P7)) \n                  | L4 => (L3,(P0,P8,P7)) \n                  | L5 => (L3,(P0,P8,P7)) \n                  | L6 => (L3,(P0,P8,P7)) \n                  | L7 => (L10,(P1,P9,P7)) \n                  | L8 => (L3,(P8,P8,P7)) \n                  | L9 => (L10,(P1,P9,P7)) \n                  | L10 => (L3,(P7,P8,P7)) \n                  | L11 => (L10,(P1,P9,P7)) \n                  | L12 => (L10,(P1,P9,P7)) \n                  | L13 => (L3,(P7,P8,P7)) \n                  | L14 => (L13,(P2,P2,P7)) \n                  | L15 => (L13,(P2,P2,P7)) \n                  | L16 => (L13,(P2,P2,P7)) \n                  | L17 => (L13,(P2,P2,P7)) \n                  | L18 => (L3,(P8,P8,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L6,(P0,P14,P14)) \n                  | L1 => (L6,(P0,P14,P14)) \n                  | L2 => (L6,(P0,P14,P14)) \n                  | L3 => (L6,(P0,P14,P14)) \n                  | L4 => (L6,(P0,P14,P14)) \n                  | L5 => (L6,(P0,P14,P14)) \n                  | L6 => (L6,(P0,P14,P14)) \n                  | L7 => (L9,(P1,P14,P14)) \n                  | L8 => (L9,(P1,P14,P14)) \n                  | L9 => (L6,(P14,P14,P14)) \n                  | L10 => (L9,(P1,P14,P14)) \n                  | L11 => (L6,(P13,P14,P14)) \n                  | L12 => (L9,(P1,P14,P14)) \n                  | L13 => (L13,(P2,P10,P7)) \n                  | L14 => (L6,(P14,P14,P14)) \n                  | L15 => (L13,(P2,P10,P7)) \n                  | L16 => (L6,(P13,P14,P14)) \n                  | L17 => (L13,(P2,P10,P7)) \n                  | L18 => (L13,(P2,P10,P7)) \n                  | L19 => (L6,(P14,P14,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L20 => match l1 with \n                  | L0 => (L3,(P0,P8,P7)) \n                  | L1 => (L3,(P0,P8,P7)) \n                  | L2 => (L3,(P0,P8,P7)) \n                  | L3 => (L3,(P0,P8,P7)) \n                  | L4 => (L3,(P0,P8,P7)) \n                  | L5 => (L3,(P0,P8,P7)) \n                  | L6 => (L3,(P0,P8,P7)) \n                  | L7 => (L9,(P1,P12,P14)) \n                  | L8 => (L3,(P8,P8,P7)) \n                  | L9 => (L9,(P1,P12,P14)) \n                  | L10 => (L3,(P7,P8,P7)) \n                  | L11 => (L9,(P1,P12,P14)) \n                  | L12 => (L9,(P1,P12,P14)) \n                  | L13 => (L3,(P7,P8,P7)) \n                  | L14 => (L9,(P14,P12,P14)) \n                  | L15 => (L15,(P2,P3,P6)) \n                  | L16 => (L9,(P12,P12,P14)) \n                  | L17 => (L15,(P2,P3,P6)) \n                  | L18 => (L3,(P8,P8,P7)) \n                  | L19 => (L9,(P14,P12,P14)) \n                  | L20 => (L3,(P8,P8,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L21 => match l1 with \n                  | L0 => (L6,(P0,P13,P14)) \n                  | L1 => (L6,(P0,P13,P14)) \n                  | L2 => (L6,(P0,P13,P14)) \n                  | L3 => (L6,(P0,P13,P14)) \n                  | L4 => (L6,(P0,P13,P14)) \n                  | L5 => (L6,(P0,P13,P14)) \n                  | L6 => (L6,(P0,P13,P14)) \n                  | L7 => (L10,(P1,P9,P7)) \n                  | L8 => (L10,(P1,P9,P7)) \n                  | L9 => (L6,(P14,P13,P14)) \n                  | L10 => (L10,(P1,P9,P7)) \n                  | L11 => (L6,(P13,P13,P14)) \n                  | L12 => (L10,(P1,P9,P7)) \n                  | L13 => (L10,(P7,P9,P7)) \n                  | L14 => (L6,(P14,P13,P14)) \n                  | L15 => (L15,(P2,P3,P6)) \n                  | L16 => (L6,(P13,P13,P14)) \n                  | L17 => (L15,(P2,P3,P6)) \n                  | L18 => (L10,(P9,P9,P7)) \n                  | L19 => (L6,(P14,P13,P14)) \n                  | L20 => (L15,(P3,P3,P6)) \n                  | L21 => (L6,(P13,P13,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L22 => match l1 with \n                  | L0 => (L3,(P0,P7,P7)) \n                  | L1 => (L3,(P0,P7,P7)) \n                  | L2 => (L3,(P0,P7,P7)) \n                  | L3 => (L3,(P0,P7,P7)) \n                  | L4 => (L3,(P0,P7,P7)) \n                  | L5 => (L3,(P0,P7,P7)) \n                  | L6 => (L3,(P0,P7,P7)) \n                  | L7 => (L10,(P1,P7,P7)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L10,(P1,P7,P7)) \n                  | L10 => (L3,(P7,P7,P7)) \n                  | L11 => (L10,(P1,P7,P7)) \n                  | L12 => (L10,(P1,P7,P7)) \n                  | L13 => (L3,(P7,P7,P7)) \n                  | L14 => (L13,(P2,P7,P7)) \n                  | L15 => (L13,(P2,P7,P7)) \n                  | L16 => (L13,(P2,P7,P7)) \n                  | L17 => (L13,(P2,P7,P7)) \n                  | L18 => (L3,(P8,P7,P7)) \n                  | L19 => (L13,(P10,P7,P7)) \n                  | L20 => (L3,(P8,P7,P7)) \n                  | L21 => (L10,(P9,P7,P7)) \n                  | L22 => (L3,(P7,P7,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L23 => match l1 with \n                  | L0 => (L6,(P0,P14,P14)) \n                  | L1 => (L6,(P0,P14,P14)) \n                  | L2 => (L6,(P0,P14,P14)) \n                  | L3 => (L6,(P0,P14,P14)) \n                  | L4 => (L6,(P0,P14,P14)) \n                  | L5 => (L6,(P0,P14,P14)) \n                  | L6 => (L6,(P0,P14,P14)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L7,(P1,P4,P6)) \n                  | L9 => (L6,(P14,P14,P14)) \n                  | L10 => (L7,(P1,P4,P6)) \n                  | L11 => (L6,(P13,P14,P14)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L10,(P7,P9,P7)) \n                  | L14 => (L6,(P14,P14,P14)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L6,(P13,P14,P14)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L10,(P9,P9,P7)) \n                  | L19 => (L6,(P14,P14,P14)) \n                  | L20 => (L9,(P12,P14,P14)) \n                  | L21 => (L6,(P13,P14,P14)) \n                  | L22 => (L10,(P7,P9,P7)) \n                  | L23 => (L6,(P14,P14,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L24 => match l1 with \n                  | L0 => (L3,(P0,P8,P7)) \n                  | L1 => (L3,(P0,P8,P7)) \n                  | L2 => (L3,(P0,P8,P7)) \n                  | L3 => (L3,(P0,P8,P7)) \n                  | L4 => (L3,(P0,P8,P7)) \n                  | L5 => (L3,(P0,P8,P7)) \n                  | L6 => (L3,(P0,P8,P7)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L3,(P8,P8,P7)) \n                  | L9 => (L7,(P1,P4,P6)) \n                  | L10 => (L3,(P7,P8,P7)) \n                  | L11 => (L7,(P1,P4,P6)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L3,(P7,P8,P7)) \n                  | L14 => (L14,(P2,P11,P14)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L14,(P2,P11,P14)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L3,(P8,P8,P7)) \n                  | L19 => (L14,(P14,P11,P14)) \n                  | L20 => (L3,(P8,P8,P7)) \n                  | L21 => (L22,(P3,P11,P7)) \n                  | L22 => (L3,(P7,P8,P7)) \n                  | L23 => (L7,(P4,P4,P6)) \n                  | L24 => (L3,(P8,P8,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L25 => match l1 with \n                  | L0 => (L6,(P0,P13,P14)) \n                  | L1 => (L6,(P0,P13,P14)) \n                  | L2 => (L6,(P0,P13,P14)) \n                  | L3 => (L6,(P0,P13,P14)) \n                  | L4 => (L6,(P0,P13,P14)) \n                  | L5 => (L6,(P0,P13,P14)) \n                  | L6 => (L6,(P0,P13,P14)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L7,(P1,P4,P6)) \n                  | L9 => (L6,(P14,P13,P14)) \n                  | L10 => (L7,(P1,P4,P6)) \n                  | L11 => (L6,(P13,P13,P14)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L13,(P2,P10,P7)) \n                  | L14 => (L6,(P14,P13,P14)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L6,(P13,P13,P14)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L13,(P2,P10,P7)) \n                  | L19 => (L6,(P14,P13,P14)) \n                  | L20 => (L19,(P3,P10,P14)) \n                  | L21 => (L6,(P13,P13,P14)) \n                  | L22 => (L13,(P7,P10,P7)) \n                  | L23 => (L6,(P14,P13,P14)) \n                  | L24 => (L7,(P4,P4,P6)) \n                  | L25 => (L6,(P13,P13,P14)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L26 => match l1 with \n                  | L0 => (L3,(P0,P7,P7)) \n                  | L1 => (L3,(P0,P7,P7)) \n                  | L2 => (L3,(P0,P7,P7)) \n                  | L3 => (L3,(P0,P7,P7)) \n                  | L4 => (L3,(P0,P7,P7)) \n                  | L5 => (L3,(P0,P7,P7)) \n                  | L6 => (L3,(P0,P7,P7)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L7,(P1,P4,P6)) \n                  | L10 => (L3,(P7,P7,P7)) \n                  | L11 => (L7,(P1,P4,P6)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L3,(P7,P7,P7)) \n                  | L14 => (L9,(P14,P12,P14)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L9,(P12,P12,P14)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L3,(P8,P7,P7)) \n                  | L19 => (L9,(P14,P12,P14)) \n                  | L20 => (L3,(P8,P7,P7)) \n                  | L21 => (L10,(P9,P7,P7)) \n                  | L22 => (L3,(P7,P7,P7)) \n                  | L23 => (L7,(P4,P4,P6)) \n                  | L24 => (L3,(P8,P7,P7)) \n                  | L25 => (L7,(P4,P4,P6)) \n                  | L26 => (L3,(P7,P7,P7)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L27 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L3,(P8,P8,P7)) \n                  | L9 => (L6,(P14,P14,P14)) \n                  | L10 => (L3,(P7,P8,P7)) \n                  | L11 => (L6,(P13,P14,P14)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L3,(P7,P8,P7)) \n                  | L14 => (L6,(P14,P14,P14)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L6,(P13,P14,P14)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L3,(P8,P8,P7)) \n                  | L19 => (L6,(P14,P14,P14)) \n                  | L20 => (L3,(P8,P8,P7)) \n                  | L21 => (L6,(P13,P14,P14)) \n                  | L22 => (L3,(P7,P8,P7)) \n                  | L23 => (L6,(P14,P14,P14)) \n                  | L24 => (L3,(P8,P8,P7)) \n                  | L25 => (L6,(P13,P14,P14)) \n                  | L26 => (L3,(P7,P8,P7)) \n                  | L27 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L28 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L6,(P14,P13,P14)) \n                  | L10 => (L3,(P7,P7,P7)) \n                  | L11 => (L6,(P13,P13,P14)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L3,(P7,P7,P7)) \n                  | L14 => (L6,(P14,P13,P14)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L6,(P13,P13,P14)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L3,(P8,P7,P7)) \n                  | L19 => (L6,(P14,P13,P14)) \n                  | L20 => (L3,(P8,P7,P7)) \n                  | L21 => (L6,(P13,P13,P14)) \n                  | L22 => (L3,(P7,P7,P7)) \n                  | L23 => (L6,(P14,P13,P14)) \n                  | L24 => (L3,(P8,P7,P7)) \n                  | L25 => (L6,(P13,P13,P14)) \n                  | L26 => (L3,(P7,P7,P7)) \n                  | L27 => (L2,(P5,P5,P6)) \n                  | L28 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L29 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L10,(P1,P9,P7)) \n                  | L9 => (L10,(P1,P9,P7)) \n                  | L10 => (L10,(P1,P9,P7)) \n                  | L11 => (L10,(P1,P9,P7)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L10,(P7,P9,P7)) \n                  | L14 => (L14,(P2,P11,P14)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L14,(P2,P11,P14)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L10,(P9,P9,P7)) \n                  | L19 => (L14,(P14,P11,P14)) \n                  | L20 => (L22,(P3,P11,P7)) \n                  | L21 => (L10,(P9,P9,P7)) \n                  | L22 => (L10,(P7,P9,P7)) \n                  | L23 => (L10,(P9,P9,P7)) \n                  | L24 => (L14,(P11,P11,P14)) \n                  | L25 => (L23,(P4,P9,P14)) \n                  | L26 => (L10,(P7,P9,P7)) \n                  | L27 => (L2,(P5,P5,P6)) \n                  | L28 => (L2,(P5,P5,P6)) \n                  | L29 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L30 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L9,(P1,P12,P14)) \n                  | L9 => (L9,(P1,P12,P14)) \n                  | L10 => (L9,(P1,P12,P14)) \n                  | L11 => (L9,(P1,P12,P14)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L13,(P2,P10,P7)) \n                  | L14 => (L9,(P14,P12,P14)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L9,(P12,P12,P14)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L13,(P2,P10,P7)) \n                  | L19 => (L9,(P14,P12,P14)) \n                  | L20 => (L9,(P12,P12,P14)) \n                  | L21 => (L19,(P3,P10,P14)) \n                  | L22 => (L13,(P7,P10,P7)) \n                  | L23 => (L9,(P14,P12,P14)) \n                  | L24 => (L26,(P4,P12,P7)) \n                  | L25 => (L13,(P10,P10,P7)) \n                  | L26 => (L9,(P12,P12,P14)) \n                  | L27 => (L2,(P5,P5,P6)) \n                  | L28 => (L2,(P5,P5,P6)) \n                  | L29 => (L2,(P5,P5,P6)) \n                  | L30 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L31 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                  | L8 => (L3,(P8,P7,P7)) \n                  | L9 => (L6,(P14,P14,P14)) \n                  | L10 => (L3,(P7,P7,P7)) \n                  | L11 => (L6,(P13,P14,P14)) \n                  | L12 => (L2,(P5,P6,P6)) \n                  | L13 => (L3,(P7,P7,P7)) \n                  | L14 => (L6,(P14,P14,P14)) \n                  | L15 => (L2,(P6,P6,P6)) \n                  | L16 => (L6,(P13,P14,P14)) \n                  | L17 => (L2,(P5,P6,P6)) \n                  | L18 => (L3,(P8,P7,P7)) \n                  | L19 => (L6,(P14,P14,P14)) \n                  | L20 => (L3,(P8,P7,P7)) \n                  | L21 => (L6,(P13,P14,P14)) \n                  | L22 => (L3,(P7,P7,P7)) \n                  | L23 => (L6,(P14,P14,P14)) \n                  | L24 => (L3,(P8,P7,P7)) \n                  | L25 => (L6,(P13,P14,P14)) \n                  | L26 => (L3,(P7,P7,P7)) \n                  | L27 => (L2,(P5,P6,P6)) \n                  | L28 => (L2,(P5,P6,P6)) \n                  | L29 => (L2,(P5,P6,P6)) \n                  | L30 => (L2,(P5,P6,P6)) \n                  | L31 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L32 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                  | L4 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                  | L4 => (L2,(P0,P0,P6)) \n                  | L5 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                  | L4 => (L2,(P0,P0,P6)) \n                  | L5 => (L2,(P0,P0,P6)) \n                  | L6 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L3,(P0,P8,P8)) \n                  | L1 => (L3,(P0,P8,P8)) \n                  | L2 => (L3,(P0,P8,P8)) \n                  | L3 => (L3,(P0,P8,P8)) \n                  | L4 => (L3,(P0,P8,P8)) \n                  | L5 => (L3,(P0,P8,P8)) \n                  | L6 => (L3,(P0,P8,P8)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L3,(P8,P8,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L6,(P0,P14,P13)) \n                  | L1 => (L6,(P0,P14,P13)) \n                  | L2 => (L6,(P0,P14,P13)) \n                  | L3 => (L6,(P0,P14,P13)) \n                  | L4 => (L6,(P0,P14,P13)) \n                  | L5 => (L6,(P0,P14,P13)) \n                  | L6 => (L6,(P0,P14,P13)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L7,(P1,P1,P6)) \n                  | L9 => (L6,(P14,P14,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L3,(P0,P7,P8)) \n                  | L1 => (L3,(P0,P7,P8)) \n                  | L2 => (L3,(P0,P7,P8)) \n                  | L3 => (L3,(P0,P7,P8)) \n                  | L4 => (L3,(P0,P7,P8)) \n                  | L5 => (L3,(P0,P7,P8)) \n                  | L6 => (L3,(P0,P7,P8)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L3,(P8,P7,P8)) \n                  | L9 => (L7,(P1,P1,P6)) \n                  | L10 => (L3,(P7,P7,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L6,(P0,P13,P13)) \n                  | L1 => (L6,(P0,P13,P13)) \n                  | L2 => (L6,(P0,P13,P13)) \n                  | L3 => (L6,(P0,P13,P13)) \n                  | L4 => (L6,(P0,P13,P13)) \n                  | L5 => (L6,(P0,P13,P13)) \n                  | L6 => (L6,(P0,P13,P13)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L7,(P1,P1,P6)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L7,(P1,P1,P6)) \n                  | L11 => (L6,(P13,P13,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L7,(P1,P1,P6)) \n                  | L9 => (L7,(P1,P1,P6)) \n                  | L10 => (L7,(P1,P1,P6)) \n                  | L11 => (L7,(P1,P1,P6)) \n                  | L12 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L3,(P0,P7,P8)) \n                  | L1 => (L3,(P0,P7,P8)) \n                  | L2 => (L3,(P0,P7,P8)) \n                  | L3 => (L3,(P0,P7,P8)) \n                  | L4 => (L3,(P0,P7,P8)) \n                  | L5 => (L3,(P0,P7,P8)) \n                  | L6 => (L3,(P0,P7,P8)) \n                  | L7 => (L8,(P1,P10,P8)) \n                  | L8 => (L3,(P8,P7,P8)) \n                  | L9 => (L8,(P1,P10,P8)) \n                  | L10 => (L3,(P7,P7,P8)) \n                  | L11 => (L8,(P1,P10,P8)) \n                  | L12 => (L8,(P1,P10,P8)) \n                  | L13 => (L3,(P7,P7,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L6,(P0,P14,P13)) \n                  | L1 => (L6,(P0,P14,P13)) \n                  | L2 => (L6,(P0,P14,P13)) \n                  | L3 => (L6,(P0,P14,P13)) \n                  | L4 => (L6,(P0,P14,P13)) \n                  | L5 => (L6,(P0,P14,P13)) \n                  | L6 => (L6,(P0,P14,P13)) \n                  | L7 => (L11,(P1,P11,P13)) \n                  | L8 => (L11,(P1,P11,P13)) \n                  | L9 => (L6,(P14,P14,P13)) \n                  | L10 => (L11,(P1,P11,P13)) \n                  | L11 => (L6,(P13,P14,P13)) \n                  | L12 => (L11,(P1,P11,P13)) \n                  | L13 => (L15,(P2,P2,P6)) \n                  | L14 => (L6,(P14,P14,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                  | L8 => (L7,(P1,P6,P6)) \n                  | L9 => (L7,(P1,P6,P6)) \n                  | L10 => (L7,(P1,P6,P6)) \n                  | L11 => (L7,(P1,P6,P6)) \n                  | L12 => (L2,(P5,P6,P6)) \n                  | L13 => (L15,(P2,P2,P6)) \n                  | L14 => (L15,(P2,P2,P6)) \n                  | L15 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L6,(P0,P13,P13)) \n                  | L1 => (L6,(P0,P13,P13)) \n                  | L2 => (L6,(P0,P13,P13)) \n                  | L3 => (L6,(P0,P13,P13)) \n                  | L4 => (L6,(P0,P13,P13)) \n                  | L5 => (L6,(P0,P13,P13)) \n                  | L6 => (L6,(P0,P13,P13)) \n                  | L7 => (L11,(P1,P13,P13)) \n                  | L8 => (L11,(P1,P13,P13)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L11,(P1,P13,P13)) \n                  | L11 => (L6,(P13,P13,P13)) \n                  | L12 => (L11,(P1,P13,P13)) \n                  | L13 => (L15,(P2,P2,P6)) \n                  | L14 => (L6,(P14,P13,P13)) \n                  | L15 => (L15,(P2,P2,P6)) \n                  | L16 => (L6,(P13,P13,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L7,(P1,P4,P6)) \n                  | L9 => (L7,(P1,P4,P6)) \n                  | L10 => (L7,(P1,P4,P6)) \n                  | L11 => (L7,(P1,P4,P6)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L15,(P2,P2,P6)) \n                  | L14 => (L15,(P2,P2,P6)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L15,(P2,P2,P6)) \n                  | L17 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L3,(P0,P8,P8)) \n                  | L1 => (L3,(P0,P8,P8)) \n                  | L2 => (L3,(P0,P8,P8)) \n                  | L3 => (L3,(P0,P8,P8)) \n                  | L4 => (L3,(P0,P8,P8)) \n                  | L5 => (L3,(P0,P8,P8)) \n                  | L6 => (L3,(P0,P8,P8)) \n                  | L7 => (L8,(P1,P8,P8)) \n                  | L8 => (L3,(P8,P8,P8)) \n                  | L9 => (L8,(P1,P8,P8)) \n                  | L10 => (L3,(P7,P8,P8)) \n                  | L11 => (L8,(P1,P8,P8)) \n                  | L12 => (L8,(P1,P8,P8)) \n                  | L13 => (L3,(P7,P8,P8)) \n                  | L14 => (L15,(P2,P2,P6)) \n                  | L15 => (L15,(P2,P2,P6)) \n                  | L16 => (L15,(P2,P2,P6)) \n                  | L17 => (L15,(P2,P2,P6)) \n                  | L18 => (L3,(P8,P8,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L6,(P0,P14,P13)) \n                  | L1 => (L6,(P0,P14,P13)) \n                  | L2 => (L6,(P0,P14,P13)) \n                  | L3 => (L6,(P0,P14,P13)) \n                  | L4 => (L6,(P0,P14,P13)) \n                  | L5 => (L6,(P0,P14,P13)) \n                  | L6 => (L6,(P0,P14,P13)) \n                  | L7 => (L8,(P1,P10,P8)) \n                  | L8 => (L8,(P1,P10,P8)) \n                  | L9 => (L6,(P14,P14,P13)) \n                  | L10 => (L8,(P1,P10,P8)) \n                  | L11 => (L6,(P13,P14,P13)) \n                  | L12 => (L8,(P1,P10,P8)) \n                  | L13 => (L8,(P10,P10,P8)) \n                  | L14 => (L6,(P14,P14,P13)) \n                  | L15 => (L15,(P2,P3,P6)) \n                  | L16 => (L6,(P13,P14,P13)) \n                  | L17 => (L15,(P2,P3,P6)) \n                  | L18 => (L8,(P8,P10,P8)) \n                  | L19 => (L6,(P14,P14,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L20 => match l1 with \n                  | L0 => (L3,(P0,P8,P8)) \n                  | L1 => (L3,(P0,P8,P8)) \n                  | L2 => (L3,(P0,P8,P8)) \n                  | L3 => (L3,(P0,P8,P8)) \n                  | L4 => (L3,(P0,P8,P8)) \n                  | L5 => (L3,(P0,P8,P8)) \n                  | L6 => (L3,(P0,P8,P8)) \n                  | L7 => (L8,(P1,P8,P8)) \n                  | L8 => (L3,(P8,P8,P8)) \n                  | L9 => (L8,(P1,P8,P8)) \n                  | L10 => (L3,(P7,P8,P8)) \n                  | L11 => (L8,(P1,P8,P8)) \n                  | L12 => (L8,(P1,P8,P8)) \n                  | L13 => (L3,(P7,P8,P8)) \n                  | L14 => (L15,(P2,P3,P6)) \n                  | L15 => (L15,(P2,P3,P6)) \n                  | L16 => (L15,(P2,P3,P6)) \n                  | L17 => (L15,(P2,P3,P6)) \n                  | L18 => (L3,(P8,P8,P8)) \n                  | L19 => (L8,(P10,P8,P8)) \n                  | L20 => (L3,(P8,P8,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L21 => match l1 with \n                  | L0 => (L6,(P0,P13,P13)) \n                  | L1 => (L6,(P0,P13,P13)) \n                  | L2 => (L6,(P0,P13,P13)) \n                  | L3 => (L6,(P0,P13,P13)) \n                  | L4 => (L6,(P0,P13,P13)) \n                  | L5 => (L6,(P0,P13,P13)) \n                  | L6 => (L6,(P0,P13,P13)) \n                  | L7 => (L11,(P1,P13,P13)) \n                  | L8 => (L11,(P1,P13,P13)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L11,(P1,P13,P13)) \n                  | L11 => (L6,(P13,P13,P13)) \n                  | L12 => (L11,(P1,P13,P13)) \n                  | L13 => (L15,(P2,P3,P6)) \n                  | L14 => (L6,(P14,P13,P13)) \n                  | L15 => (L15,(P2,P3,P6)) \n                  | L16 => (L6,(P13,P13,P13)) \n                  | L17 => (L15,(P2,P3,P6)) \n                  | L18 => (L15,(P2,P3,P6)) \n                  | L19 => (L6,(P14,P13,P13)) \n                  | L20 => (L15,(P3,P3,P6)) \n                  | L21 => (L6,(P13,P13,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L22 => match l1 with \n                  | L0 => (L3,(P0,P7,P8)) \n                  | L1 => (L3,(P0,P7,P8)) \n                  | L2 => (L3,(P0,P7,P8)) \n                  | L3 => (L3,(P0,P7,P8)) \n                  | L4 => (L3,(P0,P7,P8)) \n                  | L5 => (L3,(P0,P7,P8)) \n                  | L6 => (L3,(P0,P7,P8)) \n                  | L7 => (L11,(P1,P11,P13)) \n                  | L8 => (L3,(P8,P7,P8)) \n                  | L9 => (L11,(P1,P11,P13)) \n                  | L10 => (L3,(P7,P7,P8)) \n                  | L11 => (L11,(P1,P11,P13)) \n                  | L12 => (L11,(P1,P11,P13)) \n                  | L13 => (L3,(P7,P7,P8)) \n                  | L14 => (L11,(P11,P11,P13)) \n                  | L15 => (L15,(P2,P3,P6)) \n                  | L16 => (L11,(P13,P11,P13)) \n                  | L17 => (L15,(P2,P3,P6)) \n                  | L18 => (L3,(P8,P7,P8)) \n                  | L19 => (L15,(P3,P3,P6)) \n                  | L20 => (L3,(P8,P7,P8)) \n                  | L21 => (L11,(P13,P11,P13)) \n                  | L22 => (L3,(P7,P7,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L23 => match l1 with \n                  | L0 => (L6,(P0,P14,P13)) \n                  | L1 => (L6,(P0,P14,P13)) \n                  | L2 => (L6,(P0,P14,P13)) \n                  | L3 => (L6,(P0,P14,P13)) \n                  | L4 => (L6,(P0,P14,P13)) \n                  | L5 => (L6,(P0,P14,P13)) \n                  | L6 => (L6,(P0,P14,P13)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L7,(P1,P4,P6)) \n                  | L9 => (L6,(P14,P14,P13)) \n                  | L10 => (L7,(P1,P4,P6)) \n                  | L11 => (L6,(P13,P14,P13)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L18,(P2,P9,P8)) \n                  | L14 => (L6,(P14,P14,P13)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L6,(P13,P14,P13)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L18,(P2,P9,P8)) \n                  | L19 => (L6,(P14,P14,P13)) \n                  | L20 => (L18,(P8,P9,P8)) \n                  | L21 => (L6,(P13,P14,P13)) \n                  | L22 => (L21,(P3,P9,P13)) \n                  | L23 => (L6,(P14,P14,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L24 => match l1 with \n                  | L0 => (L3,(P0,P8,P8)) \n                  | L1 => (L3,(P0,P8,P8)) \n                  | L2 => (L3,(P0,P8,P8)) \n                  | L3 => (L3,(P0,P8,P8)) \n                  | L4 => (L3,(P0,P8,P8)) \n                  | L5 => (L3,(P0,P8,P8)) \n                  | L6 => (L3,(P0,P8,P8)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L3,(P8,P8,P8)) \n                  | L9 => (L7,(P1,P4,P6)) \n                  | L10 => (L3,(P7,P8,P8)) \n                  | L11 => (L7,(P1,P4,P6)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L3,(P7,P8,P8)) \n                  | L14 => (L11,(P11,P11,P13)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L11,(P13,P11,P13)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L3,(P8,P8,P8)) \n                  | L19 => (L8,(P10,P8,P8)) \n                  | L20 => (L3,(P8,P8,P8)) \n                  | L21 => (L11,(P13,P11,P13)) \n                  | L22 => (L3,(P7,P8,P8)) \n                  | L23 => (L7,(P4,P4,P6)) \n                  | L24 => (L3,(P8,P8,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L25 => match l1 with \n                  | L0 => (L6,(P0,P13,P13)) \n                  | L1 => (L6,(P0,P13,P13)) \n                  | L2 => (L6,(P0,P13,P13)) \n                  | L3 => (L6,(P0,P13,P13)) \n                  | L4 => (L6,(P0,P13,P13)) \n                  | L5 => (L6,(P0,P13,P13)) \n                  | L6 => (L6,(P0,P13,P13)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L7,(P1,P4,P6)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L7,(P1,P4,P6)) \n                  | L11 => (L6,(P13,P13,P13)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L8,(P10,P10,P8)) \n                  | L14 => (L6,(P14,P13,P13)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L6,(P13,P13,P13)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L8,(P8,P10,P8)) \n                  | L19 => (L6,(P14,P13,P13)) \n                  | L20 => (L8,(P8,P10,P8)) \n                  | L21 => (L6,(P13,P13,P13)) \n                  | L22 => (L11,(P11,P13,P13)) \n                  | L23 => (L6,(P14,P13,P13)) \n                  | L24 => (L7,(P4,P4,P6)) \n                  | L25 => (L6,(P13,P13,P13)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L26 => match l1 with \n                  | L0 => (L3,(P0,P7,P8)) \n                  | L1 => (L3,(P0,P7,P8)) \n                  | L2 => (L3,(P0,P7,P8)) \n                  | L3 => (L3,(P0,P7,P8)) \n                  | L4 => (L3,(P0,P7,P8)) \n                  | L5 => (L3,(P0,P7,P8)) \n                  | L6 => (L3,(P0,P7,P8)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L3,(P8,P7,P8)) \n                  | L9 => (L7,(P1,P4,P6)) \n                  | L10 => (L3,(P7,P7,P8)) \n                  | L11 => (L7,(P1,P4,P6)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L3,(P7,P7,P8)) \n                  | L14 => (L16,(P2,P12,P13)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L16,(P2,P12,P13)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L3,(P8,P7,P8)) \n                  | L19 => (L20,(P3,P12,P8)) \n                  | L20 => (L3,(P8,P7,P8)) \n                  | L21 => (L16,(P13,P12,P13)) \n                  | L22 => (L3,(P7,P7,P8)) \n                  | L23 => (L7,(P4,P4,P6)) \n                  | L24 => (L3,(P8,P7,P8)) \n                  | L25 => (L7,(P4,P4,P6)) \n                  | L26 => (L3,(P7,P7,P8)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L27 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L3,(P8,P8,P8)) \n                  | L9 => (L6,(P14,P14,P13)) \n                  | L10 => (L3,(P7,P8,P8)) \n                  | L11 => (L6,(P13,P14,P13)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L3,(P7,P8,P8)) \n                  | L14 => (L6,(P14,P14,P13)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L6,(P13,P14,P13)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L3,(P8,P8,P8)) \n                  | L19 => (L6,(P14,P14,P13)) \n                  | L20 => (L3,(P8,P8,P8)) \n                  | L21 => (L6,(P13,P14,P13)) \n                  | L22 => (L3,(P7,P8,P8)) \n                  | L23 => (L6,(P14,P14,P13)) \n                  | L24 => (L3,(P8,P8,P8)) \n                  | L25 => (L6,(P13,P14,P13)) \n                  | L26 => (L3,(P7,P8,P8)) \n                  | L27 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L28 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L3,(P8,P7,P8)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L3,(P7,P7,P8)) \n                  | L11 => (L6,(P13,P13,P13)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L3,(P7,P7,P8)) \n                  | L14 => (L6,(P14,P13,P13)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L6,(P13,P13,P13)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L3,(P8,P7,P8)) \n                  | L19 => (L6,(P14,P13,P13)) \n                  | L20 => (L3,(P8,P7,P8)) \n                  | L21 => (L6,(P13,P13,P13)) \n                  | L22 => (L3,(P7,P7,P8)) \n                  | L23 => (L6,(P14,P13,P13)) \n                  | L24 => (L3,(P8,P7,P8)) \n                  | L25 => (L6,(P13,P13,P13)) \n                  | L26 => (L3,(P7,P7,P8)) \n                  | L27 => (L2,(P5,P5,P6)) \n                  | L28 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L29 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L11,(P1,P11,P13)) \n                  | L9 => (L11,(P1,P11,P13)) \n                  | L10 => (L11,(P1,P11,P13)) \n                  | L11 => (L11,(P1,P11,P13)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L18,(P2,P9,P8)) \n                  | L14 => (L11,(P11,P11,P13)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L11,(P13,P11,P13)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L18,(P2,P9,P8)) \n                  | L19 => (L21,(P3,P9,P13)) \n                  | L20 => (L18,(P8,P9,P8)) \n                  | L21 => (L11,(P13,P11,P13)) \n                  | L22 => (L11,(P11,P11,P13)) \n                  | L23 => (L18,(P9,P9,P8)) \n                  | L24 => (L11,(P11,P11,P13)) \n                  | L25 => (L11,(P13,P11,P13)) \n                  | L26 => (L24,(P4,P11,P8)) \n                  | L27 => (L2,(P5,P5,P6)) \n                  | L28 => (L2,(P5,P5,P6)) \n                  | L29 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L30 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L8,(P1,P10,P8)) \n                  | L9 => (L8,(P1,P10,P8)) \n                  | L10 => (L8,(P1,P10,P8)) \n                  | L11 => (L8,(P1,P10,P8)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L8,(P10,P10,P8)) \n                  | L14 => (L16,(P2,P12,P13)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L16,(P2,P12,P13)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L8,(P8,P10,P8)) \n                  | L19 => (L8,(P10,P10,P8)) \n                  | L20 => (L8,(P8,P10,P8)) \n                  | L21 => (L16,(P13,P12,P13)) \n                  | L22 => (L20,(P3,P12,P8)) \n                  | L23 => (L25,(P4,P10,P13)) \n                  | L24 => (L8,(P8,P10,P8)) \n                  | L25 => (L8,(P10,P10,P8)) \n                  | L26 => (L16,(P12,P12,P13)) \n                  | L27 => (L2,(P5,P5,P6)) \n                  | L28 => (L2,(P5,P5,P6)) \n                  | L29 => (L2,(P5,P5,P6)) \n                  | L30 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L31 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                  | L8 => (L3,(P8,P7,P8)) \n                  | L9 => (L6,(P14,P14,P13)) \n                  | L10 => (L3,(P7,P7,P8)) \n                  | L11 => (L6,(P13,P14,P13)) \n                  | L12 => (L2,(P5,P6,P6)) \n                  | L13 => (L3,(P7,P7,P8)) \n                  | L14 => (L6,(P14,P14,P13)) \n                  | L15 => (L2,(P6,P6,P6)) \n                  | L16 => (L6,(P13,P14,P13)) \n                  | L17 => (L2,(P5,P6,P6)) \n                  | L18 => (L3,(P8,P7,P8)) \n                  | L19 => (L6,(P14,P14,P13)) \n                  | L20 => (L3,(P8,P7,P8)) \n                  | L21 => (L6,(P13,P14,P13)) \n                  | L22 => (L3,(P7,P7,P8)) \n                  | L23 => (L6,(P14,P14,P13)) \n                  | L24 => (L3,(P8,P7,P8)) \n                  | L25 => (L6,(P13,P14,P13)) \n                  | L26 => (L3,(P7,P7,P8)) \n                  | L27 => (L2,(P5,P6,P6)) \n                  | L28 => (L2,(P5,P6,P6)) \n                  | L29 => (L2,(P5,P6,P6)) \n                  | L30 => (L2,(P5,P6,P6)) \n                  | L31 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L32 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                  | L8 => (L3,(P8,P8,P8)) \n                  | L9 => (L6,(P14,P13,P13)) \n                  | L10 => (L3,(P7,P8,P8)) \n                  | L11 => (L6,(P13,P13,P13)) \n                  | L12 => (L2,(P5,P6,P6)) \n                  | L13 => (L3,(P7,P8,P8)) \n                  | L14 => (L6,(P14,P13,P13)) \n                  | L15 => (L2,(P6,P6,P6)) \n                  | L16 => (L6,(P13,P13,P13)) \n                  | L17 => (L2,(P5,P6,P6)) \n                  | L18 => (L3,(P8,P8,P8)) \n                  | L19 => (L6,(P14,P13,P13)) \n                  | L20 => (L3,(P8,P8,P8)) \n                  | L21 => (L6,(P13,P13,P13)) \n                  | L22 => (L3,(P7,P8,P8)) \n                  | L23 => (L6,(P14,P13,P13)) \n                  | L24 => (L3,(P8,P8,P8)) \n                  | L25 => (L6,(P13,P13,P13)) \n                  | L26 => (L3,(P7,P8,P8)) \n                  | L27 => (L2,(P5,P6,P6)) \n                  | L28 => (L2,(P5,P6,P6)) \n                  | L29 => (L2,(P5,P6,P6)) \n                  | L30 => (L2,(P5,P6,P6)) \n                  | L31 => (L2,(P6,P6,P6)) \n                  | L32 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L33 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                  | L4 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                  | L4 => (L2,(P0,P0,P6)) \n                  | L5 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                  | L4 => (L2,(P0,P0,P6)) \n                  | L5 => (L2,(P0,P0,P6)) \n                  | L6 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L4,(P0,P10,P9)) \n                  | L1 => (L4,(P0,P10,P9)) \n                  | L2 => (L4,(P0,P10,P9)) \n                  | L3 => (L4,(P0,P10,P9)) \n                  | L4 => (L4,(P0,P10,P9)) \n                  | L5 => (L4,(P0,P10,P9)) \n                  | L6 => (L4,(P0,P10,P9)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L4,(P10,P10,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L5,(P0,P12,P12)) \n                  | L1 => (L5,(P0,P12,P12)) \n                  | L2 => (L5,(P0,P12,P12)) \n                  | L3 => (L5,(P0,P12,P12)) \n                  | L4 => (L5,(P0,P12,P12)) \n                  | L5 => (L5,(P0,P12,P12)) \n                  | L6 => (L5,(P0,P12,P12)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L7,(P1,P1,P6)) \n                  | L9 => (L5,(P12,P12,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L4,(P0,P9,P9)) \n                  | L1 => (L4,(P0,P9,P9)) \n                  | L2 => (L4,(P0,P9,P9)) \n                  | L3 => (L4,(P0,P9,P9)) \n                  | L4 => (L4,(P0,P9,P9)) \n                  | L5 => (L4,(P0,P9,P9)) \n                  | L6 => (L4,(P0,P9,P9)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L7,(P1,P1,P6)) \n                  | L10 => (L4,(P9,P9,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L5,(P0,P11,P12)) \n                  | L1 => (L5,(P0,P11,P12)) \n                  | L2 => (L5,(P0,P11,P12)) \n                  | L3 => (L5,(P0,P11,P12)) \n                  | L4 => (L5,(P0,P11,P12)) \n                  | L5 => (L5,(P0,P11,P12)) \n                  | L6 => (L5,(P0,P11,P12)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L7,(P1,P1,P6)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L7,(P1,P1,P6)) \n                  | L11 => (L5,(P11,P11,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L7,(P1,P1,P6)) \n                  | L9 => (L7,(P1,P1,P6)) \n                  | L10 => (L7,(P1,P1,P6)) \n                  | L11 => (L7,(P1,P1,P6)) \n                  | L12 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L4,(P0,P10,P9)) \n                  | L1 => (L4,(P0,P10,P9)) \n                  | L2 => (L4,(P0,P10,P9)) \n                  | L3 => (L4,(P0,P10,P9)) \n                  | L4 => (L4,(P0,P10,P9)) \n                  | L5 => (L4,(P0,P10,P9)) \n                  | L6 => (L4,(P0,P10,P9)) \n                  | L7 => (L10,(P1,P7,P9)) \n                  | L8 => (L4,(P10,P10,P9)) \n                  | L9 => (L10,(P1,P7,P9)) \n                  | L10 => (L4,(P9,P10,P9)) \n                  | L11 => (L10,(P1,P7,P9)) \n                  | L12 => (L10,(P1,P7,P9)) \n                  | L13 => (L4,(P10,P10,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L5,(P0,P11,P12)) \n                  | L1 => (L5,(P0,P11,P12)) \n                  | L2 => (L5,(P0,P11,P12)) \n                  | L3 => (L5,(P0,P11,P12)) \n                  | L4 => (L5,(P0,P11,P12)) \n                  | L5 => (L5,(P0,P11,P12)) \n                  | L6 => (L5,(P0,P11,P12)) \n                  | L7 => (L9,(P1,P14,P12)) \n                  | L8 => (L9,(P1,P14,P12)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L9,(P1,P14,P12)) \n                  | L11 => (L5,(P11,P11,P12)) \n                  | L12 => (L9,(P1,P14,P12)) \n                  | L13 => (L15,(P2,P2,P6)) \n                  | L14 => (L5,(P11,P11,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                  | L8 => (L7,(P1,P6,P6)) \n                  | L9 => (L7,(P1,P6,P6)) \n                  | L10 => (L7,(P1,P6,P6)) \n                  | L11 => (L7,(P1,P6,P6)) \n                  | L12 => (L2,(P5,P6,P6)) \n                  | L13 => (L15,(P2,P2,P6)) \n                  | L14 => (L15,(P2,P2,P6)) \n                  | L15 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L5,(P0,P12,P12)) \n                  | L1 => (L5,(P0,P12,P12)) \n                  | L2 => (L5,(P0,P12,P12)) \n                  | L3 => (L5,(P0,P12,P12)) \n                  | L4 => (L5,(P0,P12,P12)) \n                  | L5 => (L5,(P0,P12,P12)) \n                  | L6 => (L5,(P0,P12,P12)) \n                  | L7 => (L9,(P1,P12,P12)) \n                  | L8 => (L9,(P1,P12,P12)) \n                  | L9 => (L5,(P12,P12,P12)) \n                  | L10 => (L9,(P1,P12,P12)) \n                  | L11 => (L5,(P11,P12,P12)) \n                  | L12 => (L9,(P1,P12,P12)) \n                  | L13 => (L15,(P2,P2,P6)) \n                  | L14 => (L5,(P11,P12,P12)) \n                  | L15 => (L15,(P2,P2,P6)) \n                  | L16 => (L5,(P12,P12,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L7,(P1,P4,P6)) \n                  | L9 => (L7,(P1,P4,P6)) \n                  | L10 => (L7,(P1,P4,P6)) \n                  | L11 => (L7,(P1,P4,P6)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L15,(P2,P2,P6)) \n                  | L14 => (L15,(P2,P2,P6)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L15,(P2,P2,P6)) \n                  | L17 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L4,(P0,P9,P9)) \n                  | L1 => (L4,(P0,P9,P9)) \n                  | L2 => (L4,(P0,P9,P9)) \n                  | L3 => (L4,(P0,P9,P9)) \n                  | L4 => (L4,(P0,P9,P9)) \n                  | L5 => (L4,(P0,P9,P9)) \n                  | L6 => (L4,(P0,P9,P9)) \n                  | L7 => (L10,(P1,P9,P9)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L10,(P1,P9,P9)) \n                  | L10 => (L4,(P9,P9,P9)) \n                  | L11 => (L10,(P1,P9,P9)) \n                  | L12 => (L10,(P1,P9,P9)) \n                  | L13 => (L4,(P10,P9,P9)) \n                  | L14 => (L15,(P2,P2,P6)) \n                  | L15 => (L15,(P2,P2,P6)) \n                  | L16 => (L15,(P2,P2,P6)) \n                  | L17 => (L15,(P2,P2,P6)) \n                  | L18 => (L4,(P9,P9,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L4,(P0,P10,P9)) \n                  | L1 => (L4,(P0,P10,P9)) \n                  | L2 => (L4,(P0,P10,P9)) \n                  | L3 => (L4,(P0,P10,P9)) \n                  | L4 => (L4,(P0,P10,P9)) \n                  | L5 => (L4,(P0,P10,P9)) \n                  | L6 => (L4,(P0,P10,P9)) \n                  | L7 => (L9,(P1,P14,P12)) \n                  | L8 => (L4,(P10,P10,P9)) \n                  | L9 => (L9,(P1,P14,P12)) \n                  | L10 => (L4,(P9,P10,P9)) \n                  | L11 => (L9,(P1,P14,P12)) \n                  | L12 => (L9,(P1,P14,P12)) \n                  | L13 => (L4,(P10,P10,P9)) \n                  | L14 => (L9,(P14,P14,P12)) \n                  | L15 => (L15,(P2,P3,P6)) \n                  | L16 => (L9,(P12,P14,P12)) \n                  | L17 => (L15,(P2,P3,P6)) \n                  | L18 => (L4,(P9,P10,P9)) \n                  | L19 => (L4,(P10,P10,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L20 => match l1 with \n                  | L0 => (L5,(P0,P12,P12)) \n                  | L1 => (L5,(P0,P12,P12)) \n                  | L2 => (L5,(P0,P12,P12)) \n                  | L3 => (L5,(P0,P12,P12)) \n                  | L4 => (L5,(P0,P12,P12)) \n                  | L5 => (L5,(P0,P12,P12)) \n                  | L6 => (L5,(P0,P12,P12)) \n                  | L7 => (L9,(P1,P12,P12)) \n                  | L8 => (L9,(P1,P12,P12)) \n                  | L9 => (L5,(P12,P12,P12)) \n                  | L10 => (L9,(P1,P12,P12)) \n                  | L11 => (L5,(P11,P12,P12)) \n                  | L12 => (L9,(P1,P12,P12)) \n                  | L13 => (L15,(P2,P3,P6)) \n                  | L14 => (L5,(P11,P12,P12)) \n                  | L15 => (L15,(P2,P3,P6)) \n                  | L16 => (L5,(P12,P12,P12)) \n                  | L17 => (L15,(P2,P3,P6)) \n                  | L18 => (L15,(P2,P3,P6)) \n                  | L19 => (L9,(P14,P12,P12)) \n                  | L20 => (L5,(P12,P12,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L21 => match l1 with \n                  | L0 => (L4,(P0,P9,P9)) \n                  | L1 => (L4,(P0,P9,P9)) \n                  | L2 => (L4,(P0,P9,P9)) \n                  | L3 => (L4,(P0,P9,P9)) \n                  | L4 => (L4,(P0,P9,P9)) \n                  | L5 => (L4,(P0,P9,P9)) \n                  | L6 => (L4,(P0,P9,P9)) \n                  | L7 => (L10,(P1,P9,P9)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L10,(P1,P9,P9)) \n                  | L10 => (L4,(P9,P9,P9)) \n                  | L11 => (L10,(P1,P9,P9)) \n                  | L12 => (L10,(P1,P9,P9)) \n                  | L13 => (L4,(P10,P9,P9)) \n                  | L14 => (L15,(P2,P3,P6)) \n                  | L15 => (L15,(P2,P3,P6)) \n                  | L16 => (L15,(P2,P3,P6)) \n                  | L17 => (L15,(P2,P3,P6)) \n                  | L18 => (L4,(P9,P9,P9)) \n                  | L19 => (L4,(P10,P9,P9)) \n                  | L20 => (L15,(P3,P3,P6)) \n                  | L21 => (L4,(P9,P9,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L22 => match l1 with \n                  | L0 => (L5,(P0,P11,P12)) \n                  | L1 => (L5,(P0,P11,P12)) \n                  | L2 => (L5,(P0,P11,P12)) \n                  | L3 => (L5,(P0,P11,P12)) \n                  | L4 => (L5,(P0,P11,P12)) \n                  | L5 => (L5,(P0,P11,P12)) \n                  | L6 => (L5,(P0,P11,P12)) \n                  | L7 => (L10,(P1,P7,P9)) \n                  | L8 => (L10,(P1,P7,P9)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L10,(P1,P7,P9)) \n                  | L11 => (L5,(P11,P11,P12)) \n                  | L12 => (L10,(P1,P7,P9)) \n                  | L13 => (L10,(P7,P7,P9)) \n                  | L14 => (L5,(P11,P11,P12)) \n                  | L15 => (L15,(P2,P3,P6)) \n                  | L16 => (L5,(P12,P11,P12)) \n                  | L17 => (L15,(P2,P3,P6)) \n                  | L18 => (L10,(P9,P7,P9)) \n                  | L19 => (L15,(P3,P3,P6)) \n                  | L20 => (L5,(P12,P11,P12)) \n                  | L21 => (L10,(P9,P7,P9)) \n                  | L22 => (L5,(P11,P11,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L23 => match l1 with \n                  | L0 => (L4,(P0,P9,P9)) \n                  | L1 => (L4,(P0,P9,P9)) \n                  | L2 => (L4,(P0,P9,P9)) \n                  | L3 => (L4,(P0,P9,P9)) \n                  | L4 => (L4,(P0,P9,P9)) \n                  | L5 => (L4,(P0,P9,P9)) \n                  | L6 => (L4,(P0,P9,P9)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L7,(P1,P4,P6)) \n                  | L10 => (L4,(P9,P9,P9)) \n                  | L11 => (L7,(P1,P4,P6)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L4,(P10,P9,P9)) \n                  | L14 => (L9,(P14,P14,P12)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L9,(P12,P14,P12)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L4,(P9,P9,P9)) \n                  | L19 => (L4,(P10,P9,P9)) \n                  | L20 => (L9,(P12,P14,P12)) \n                  | L21 => (L4,(P9,P9,P9)) \n                  | L22 => (L10,(P7,P9,P9)) \n                  | L23 => (L4,(P9,P9,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L24 => match l1 with \n                  | L0 => (L5,(P0,P11,P12)) \n                  | L1 => (L5,(P0,P11,P12)) \n                  | L2 => (L5,(P0,P11,P12)) \n                  | L3 => (L5,(P0,P11,P12)) \n                  | L4 => (L5,(P0,P11,P12)) \n                  | L5 => (L5,(P0,P11,P12)) \n                  | L6 => (L5,(P0,P11,P12)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L7,(P1,P4,P6)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L7,(P1,P4,P6)) \n                  | L11 => (L5,(P11,P11,P12)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L18,(P2,P8,P9)) \n                  | L14 => (L5,(P11,P11,P12)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L5,(P12,P11,P12)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L18,(P2,P8,P9)) \n                  | L19 => (L20,(P3,P8,P12)) \n                  | L20 => (L5,(P12,P11,P12)) \n                  | L21 => (L18,(P9,P8,P9)) \n                  | L22 => (L5,(P11,P11,P12)) \n                  | L23 => (L7,(P4,P4,P6)) \n                  | L24 => (L5,(P11,P11,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L25 => match l1 with \n                  | L0 => (L4,(P0,P10,P9)) \n                  | L1 => (L4,(P0,P10,P9)) \n                  | L2 => (L4,(P0,P10,P9)) \n                  | L3 => (L4,(P0,P10,P9)) \n                  | L4 => (L4,(P0,P10,P9)) \n                  | L5 => (L4,(P0,P10,P9)) \n                  | L6 => (L4,(P0,P10,P9)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L4,(P10,P10,P9)) \n                  | L9 => (L7,(P1,P4,P6)) \n                  | L10 => (L4,(P9,P10,P9)) \n                  | L11 => (L7,(P1,P4,P6)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L4,(P10,P10,P9)) \n                  | L14 => (L16,(P2,P13,P12)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L16,(P2,P13,P12)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L4,(P9,P10,P9)) \n                  | L19 => (L4,(P10,P10,P9)) \n                  | L20 => (L16,(P12,P13,P12)) \n                  | L21 => (L4,(P9,P10,P9)) \n                  | L22 => (L21,(P3,P13,P9)) \n                  | L23 => (L4,(P9,P10,P9)) \n                  | L24 => (L7,(P4,P4,P6)) \n                  | L25 => (L4,(P10,P10,P9)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L26 => match l1 with \n                  | L0 => (L5,(P0,P12,P12)) \n                  | L1 => (L5,(P0,P12,P12)) \n                  | L2 => (L5,(P0,P12,P12)) \n                  | L3 => (L5,(P0,P12,P12)) \n                  | L4 => (L5,(P0,P12,P12)) \n                  | L5 => (L5,(P0,P12,P12)) \n                  | L6 => (L5,(P0,P12,P12)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L7,(P1,P4,P6)) \n                  | L9 => (L5,(P12,P12,P12)) \n                  | L10 => (L7,(P1,P4,P6)) \n                  | L11 => (L5,(P11,P12,P12)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L10,(P7,P7,P9)) \n                  | L14 => (L5,(P11,P12,P12)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L5,(P12,P12,P12)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L10,(P9,P7,P9)) \n                  | L19 => (L9,(P14,P12,P12)) \n                  | L20 => (L5,(P12,P12,P12)) \n                  | L21 => (L10,(P9,P7,P9)) \n                  | L22 => (L5,(P11,P12,P12)) \n                  | L23 => (L7,(P4,P4,P6)) \n                  | L24 => (L5,(P11,P12,P12)) \n                  | L25 => (L7,(P4,P4,P6)) \n                  | L26 => (L5,(P12,P12,P12)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L27 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L9,(P1,P14,P12)) \n                  | L9 => (L9,(P1,P14,P12)) \n                  | L10 => (L9,(P1,P14,P12)) \n                  | L11 => (L9,(P1,P14,P12)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L18,(P2,P8,P9)) \n                  | L14 => (L9,(P14,P14,P12)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L9,(P12,P14,P12)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L18,(P2,P8,P9)) \n                  | L19 => (L9,(P14,P14,P12)) \n                  | L20 => (L9,(P12,P14,P12)) \n                  | L21 => (L18,(P9,P8,P9)) \n                  | L22 => (L20,(P3,P8,P12)) \n                  | L23 => (L9,(P14,P14,P12)) \n                  | L24 => (L18,(P8,P8,P9)) \n                  | L25 => (L23,(P4,P14,P9)) \n                  | L26 => (L9,(P12,P14,P12)) \n                  | L27 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L28 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L10,(P1,P7,P9)) \n                  | L9 => (L10,(P1,P7,P9)) \n                  | L10 => (L10,(P1,P7,P9)) \n                  | L11 => (L10,(P1,P7,P9)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L10,(P7,P7,P9)) \n                  | L14 => (L16,(P2,P13,P12)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L16,(P2,P13,P12)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L10,(P9,P7,P9)) \n                  | L19 => (L21,(P3,P13,P9)) \n                  | L20 => (L16,(P12,P13,P12)) \n                  | L21 => (L10,(P9,P7,P9)) \n                  | L22 => (L10,(P7,P7,P9)) \n                  | L23 => (L10,(P9,P7,P9)) \n                  | L24 => (L26,(P4,P7,P12)) \n                  | L25 => (L16,(P13,P13,P12)) \n                  | L26 => (L10,(P7,P7,P9)) \n                  | L27 => (L2,(P5,P5,P6)) \n                  | L28 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L29 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L5,(P12,P11,P12)) \n                  | L10 => (L4,(P9,P9,P9)) \n                  | L11 => (L5,(P11,P11,P12)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L4,(P10,P9,P9)) \n                  | L14 => (L5,(P11,P11,P12)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L5,(P12,P11,P12)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L4,(P9,P9,P9)) \n                  | L19 => (L4,(P10,P9,P9)) \n                  | L20 => (L5,(P12,P11,P12)) \n                  | L21 => (L4,(P9,P9,P9)) \n                  | L22 => (L5,(P11,P11,P12)) \n                  | L23 => (L4,(P9,P9,P9)) \n                  | L24 => (L5,(P11,P11,P12)) \n                  | L25 => (L4,(P10,P9,P9)) \n                  | L26 => (L5,(P12,P11,P12)) \n                  | L27 => (L2,(P5,P5,P6)) \n                  | L28 => (L2,(P5,P5,P6)) \n                  | L29 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L30 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L4,(P10,P10,P9)) \n                  | L9 => (L5,(P12,P12,P12)) \n                  | L10 => (L4,(P9,P10,P9)) \n                  | L11 => (L5,(P11,P12,P12)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L4,(P10,P10,P9)) \n                  | L14 => (L5,(P11,P12,P12)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L5,(P12,P12,P12)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L4,(P9,P10,P9)) \n                  | L19 => (L4,(P10,P10,P9)) \n                  | L20 => (L5,(P12,P12,P12)) \n                  | L21 => (L4,(P9,P10,P9)) \n                  | L22 => (L5,(P11,P12,P12)) \n                  | L23 => (L4,(P9,P10,P9)) \n                  | L24 => (L5,(P11,P12,P12)) \n                  | L25 => (L4,(P10,P10,P9)) \n                  | L26 => (L5,(P12,P12,P12)) \n                  | L27 => (L2,(P5,P5,P6)) \n                  | L28 => (L2,(P5,P5,P6)) \n                  | L29 => (L2,(P5,P5,P6)) \n                  | L30 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L31 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                  | L8 => (L7,(P1,P6,P6)) \n                  | L9 => (L7,(P1,P6,P6)) \n                  | L10 => (L7,(P1,P6,P6)) \n                  | L11 => (L7,(P1,P6,P6)) \n                  | L12 => (L2,(P5,P6,P6)) \n                  | L13 => (L10,(P7,P7,P9)) \n                  | L14 => (L9,(P14,P14,P12)) \n                  | L15 => (L2,(P6,P6,P6)) \n                  | L16 => (L9,(P12,P14,P12)) \n                  | L17 => (L2,(P5,P6,P6)) \n                  | L18 => (L10,(P9,P7,P9)) \n                  | L19 => (L9,(P14,P14,P12)) \n                  | L20 => (L9,(P12,P14,P12)) \n                  | L21 => (L10,(P9,P7,P9)) \n                  | L22 => (L10,(P7,P7,P9)) \n                  | L23 => (L7,(P4,P6,P6)) \n                  | L24 => (L7,(P4,P6,P6)) \n                  | L25 => (L7,(P4,P6,P6)) \n                  | L26 => (L7,(P4,P6,P6)) \n                  | L27 => (L2,(P5,P6,P6)) \n                  | L28 => (L2,(P5,P6,P6)) \n                  | L29 => (L2,(P5,P6,P6)) \n                  | L30 => (L2,(P5,P6,P6)) \n                  | L31 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L32 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                  | L8 => (L7,(P1,P6,P6)) \n                  | L9 => (L7,(P1,P6,P6)) \n                  | L10 => (L7,(P1,P6,P6)) \n                  | L11 => (L7,(P1,P6,P6)) \n                  | L12 => (L2,(P5,P6,P6)) \n                  | L13 => (L15,(P2,P6,P6)) \n                  | L14 => (L15,(P2,P6,P6)) \n                  | L15 => (L2,(P6,P6,P6)) \n                  | L16 => (L15,(P2,P6,P6)) \n                  | L17 => (L2,(P5,P6,P6)) \n                  | L18 => (L15,(P2,P6,P6)) \n                  | L19 => (L15,(P3,P6,P6)) \n                  | L20 => (L15,(P3,P6,P6)) \n                  | L21 => (L15,(P3,P6,P6)) \n                  | L22 => (L15,(P3,P6,P6)) \n                  | L23 => (L7,(P4,P6,P6)) \n                  | L24 => (L7,(P4,P6,P6)) \n                  | L25 => (L7,(P4,P6,P6)) \n                  | L26 => (L7,(P4,P6,P6)) \n                  | L27 => (L2,(P5,P6,P6)) \n                  | L28 => (L2,(P5,P6,P6)) \n                  | L29 => (L2,(P5,P6,P6)) \n                  | L30 => (L2,(P5,P6,P6)) \n                  | L31 => (L2,(P6,P6,P6)) \n                  | L32 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L33 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                  | L8 => (L4,(P10,P9,P9)) \n                  | L9 => (L5,(P12,P12,P12)) \n                  | L10 => (L4,(P9,P9,P9)) \n                  | L11 => (L5,(P11,P12,P12)) \n                  | L12 => (L2,(P5,P6,P6)) \n                  | L13 => (L4,(P10,P9,P9)) \n                  | L14 => (L5,(P11,P12,P12)) \n                  | L15 => (L2,(P6,P6,P6)) \n                  | L16 => (L5,(P12,P12,P12)) \n                  | L17 => (L2,(P5,P6,P6)) \n                  | L18 => (L4,(P9,P9,P9)) \n                  | L19 => (L4,(P10,P9,P9)) \n                  | L20 => (L5,(P12,P12,P12)) \n                  | L21 => (L4,(P9,P9,P9)) \n                  | L22 => (L5,(P11,P12,P12)) \n                  | L23 => (L4,(P9,P9,P9)) \n                  | L24 => (L5,(P11,P12,P12)) \n                  | L25 => (L4,(P10,P9,P9)) \n                  | L26 => (L5,(P12,P12,P12)) \n                  | L27 => (L2,(P5,P6,P6)) \n                  | L28 => (L2,(P5,P6,P6)) \n                  | L29 => (L2,(P5,P6,P6)) \n                  | L30 => (L2,(P5,P6,P6)) \n                  | L31 => (L2,(P6,P6,P6)) \n                  | L32 => (L2,(P6,P6,P6)) \n                  | L33 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n       | _ => (L0, (P0,P0,P0))\n        end\n | L34 => match l2 with \n        | L0 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L1 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L2 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L3 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L4 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                  | L4 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L5 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                  | L4 => (L2,(P0,P0,P6)) \n                  | L5 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L6 => match l1 with \n                  | L0 => (L2,(P0,P0,P6)) \n                  | L1 => (L2,(P0,P0,P6)) \n                  | L2 => (L2,(P0,P0,P6)) \n                  | L3 => (L2,(P0,P0,P6)) \n                  | L4 => (L2,(P0,P0,P6)) \n                  | L5 => (L2,(P0,P0,P6)) \n                  | L6 => (L2,(P0,P0,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L7 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L8 => match l1 with \n                  | L0 => (L4,(P0,P10,P10)) \n                  | L1 => (L4,(P0,P10,P10)) \n                  | L2 => (L4,(P0,P10,P10)) \n                  | L3 => (L4,(P0,P10,P10)) \n                  | L4 => (L4,(P0,P10,P10)) \n                  | L5 => (L4,(P0,P10,P10)) \n                  | L6 => (L4,(P0,P10,P10)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L4,(P10,P10,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L9 => match l1 with \n                  | L0 => (L5,(P0,P12,P11)) \n                  | L1 => (L5,(P0,P12,P11)) \n                  | L2 => (L5,(P0,P12,P11)) \n                  | L3 => (L5,(P0,P12,P11)) \n                  | L4 => (L5,(P0,P12,P11)) \n                  | L5 => (L5,(P0,P12,P11)) \n                  | L6 => (L5,(P0,P12,P11)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L7,(P1,P1,P6)) \n                  | L9 => (L5,(P12,P12,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L10 => match l1 with \n                  | L0 => (L4,(P0,P9,P10)) \n                  | L1 => (L4,(P0,P9,P10)) \n                  | L2 => (L4,(P0,P9,P10)) \n                  | L3 => (L4,(P0,P9,P10)) \n                  | L4 => (L4,(P0,P9,P10)) \n                  | L5 => (L4,(P0,P9,P10)) \n                  | L6 => (L4,(P0,P9,P10)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L7,(P1,P1,P6)) \n                  | L10 => (L4,(P9,P9,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L11 => match l1 with \n                  | L0 => (L5,(P0,P11,P11)) \n                  | L1 => (L5,(P0,P11,P11)) \n                  | L2 => (L5,(P0,P11,P11)) \n                  | L3 => (L5,(P0,P11,P11)) \n                  | L4 => (L5,(P0,P11,P11)) \n                  | L5 => (L5,(P0,P11,P11)) \n                  | L6 => (L5,(P0,P11,P11)) \n                  | L7 => (L7,(P1,P1,P6)) \n                  | L8 => (L7,(P1,P1,P6)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L7,(P1,P1,P6)) \n                  | L11 => (L5,(P11,P11,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L12 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L7,(P1,P1,P6)) \n                  | L9 => (L7,(P1,P1,P6)) \n                  | L10 => (L7,(P1,P1,P6)) \n                  | L11 => (L7,(P1,P1,P6)) \n                  | L12 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L13 => match l1 with \n                  | L0 => (L4,(P0,P10,P10)) \n                  | L1 => (L4,(P0,P10,P10)) \n                  | L2 => (L4,(P0,P10,P10)) \n                  | L3 => (L4,(P0,P10,P10)) \n                  | L4 => (L4,(P0,P10,P10)) \n                  | L5 => (L4,(P0,P10,P10)) \n                  | L6 => (L4,(P0,P10,P10)) \n                  | L7 => (L8,(P1,P10,P10)) \n                  | L8 => (L4,(P10,P10,P10)) \n                  | L9 => (L8,(P1,P10,P10)) \n                  | L10 => (L4,(P9,P10,P10)) \n                  | L11 => (L8,(P1,P10,P10)) \n                  | L12 => (L8,(P1,P10,P10)) \n                  | L13 => (L4,(P10,P10,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L14 => match l1 with \n                  | L0 => (L5,(P0,P11,P11)) \n                  | L1 => (L5,(P0,P11,P11)) \n                  | L2 => (L5,(P0,P11,P11)) \n                  | L3 => (L5,(P0,P11,P11)) \n                  | L4 => (L5,(P0,P11,P11)) \n                  | L5 => (L5,(P0,P11,P11)) \n                  | L6 => (L5,(P0,P11,P11)) \n                  | L7 => (L11,(P1,P11,P11)) \n                  | L8 => (L11,(P1,P11,P11)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L11,(P1,P11,P11)) \n                  | L11 => (L5,(P11,P11,P11)) \n                  | L12 => (L11,(P1,P11,P11)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L5,(P11,P11,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L15 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                  | L8 => (L7,(P1,P6,P6)) \n                  | L9 => (L7,(P1,P6,P6)) \n                  | L10 => (L7,(P1,P6,P6)) \n                  | L11 => (L7,(P1,P6,P6)) \n                  | L12 => (L2,(P5,P6,P6)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L13,(P2,P2,P10)) \n                  | L15 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L16 => match l1 with \n                  | L0 => (L5,(P0,P12,P11)) \n                  | L1 => (L5,(P0,P12,P11)) \n                  | L2 => (L5,(P0,P12,P11)) \n                  | L3 => (L5,(P0,P12,P11)) \n                  | L4 => (L5,(P0,P12,P11)) \n                  | L5 => (L5,(P0,P12,P11)) \n                  | L6 => (L5,(P0,P12,P11)) \n                  | L7 => (L11,(P1,P13,P11)) \n                  | L8 => (L11,(P1,P13,P11)) \n                  | L9 => (L5,(P12,P12,P11)) \n                  | L10 => (L11,(P1,P13,P11)) \n                  | L11 => (L5,(P11,P12,P11)) \n                  | L12 => (L11,(P1,P13,P11)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L5,(P11,P12,P11)) \n                  | L15 => (L13,(P2,P2,P10)) \n                  | L16 => (L5,(P12,P12,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L17 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L7,(P1,P4,P6)) \n                  | L9 => (L7,(P1,P4,P6)) \n                  | L10 => (L7,(P1,P4,P6)) \n                  | L11 => (L7,(P1,P4,P6)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L13,(P2,P2,P10)) \n                  | L14 => (L13,(P2,P2,P10)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L13,(P2,P2,P10)) \n                  | L17 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L18 => match l1 with \n                  | L0 => (L4,(P0,P9,P10)) \n                  | L1 => (L4,(P0,P9,P10)) \n                  | L2 => (L4,(P0,P9,P10)) \n                  | L3 => (L4,(P0,P9,P10)) \n                  | L4 => (L4,(P0,P9,P10)) \n                  | L5 => (L4,(P0,P9,P10)) \n                  | L6 => (L4,(P0,P9,P10)) \n                  | L7 => (L8,(P1,P8,P10)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L8,(P1,P8,P10)) \n                  | L10 => (L4,(P9,P9,P10)) \n                  | L11 => (L8,(P1,P8,P10)) \n                  | L12 => (L8,(P1,P8,P10)) \n                  | L13 => (L4,(P10,P9,P10)) \n                  | L14 => (L13,(P2,P2,P10)) \n                  | L15 => (L13,(P2,P2,P10)) \n                  | L16 => (L13,(P2,P2,P10)) \n                  | L17 => (L13,(P2,P2,P10)) \n                  | L18 => (L4,(P9,P9,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L19 => match l1 with \n                  | L0 => (L4,(P0,P10,P10)) \n                  | L1 => (L4,(P0,P10,P10)) \n                  | L2 => (L4,(P0,P10,P10)) \n                  | L3 => (L4,(P0,P10,P10)) \n                  | L4 => (L4,(P0,P10,P10)) \n                  | L5 => (L4,(P0,P10,P10)) \n                  | L6 => (L4,(P0,P10,P10)) \n                  | L7 => (L8,(P1,P10,P10)) \n                  | L8 => (L4,(P10,P10,P10)) \n                  | L9 => (L8,(P1,P10,P10)) \n                  | L10 => (L4,(P9,P10,P10)) \n                  | L11 => (L8,(P1,P10,P10)) \n                  | L12 => (L8,(P1,P10,P10)) \n                  | L13 => (L4,(P10,P10,P10)) \n                  | L14 => (L13,(P2,P10,P10)) \n                  | L15 => (L13,(P2,P10,P10)) \n                  | L16 => (L13,(P2,P10,P10)) \n                  | L17 => (L13,(P2,P10,P10)) \n                  | L18 => (L4,(P9,P10,P10)) \n                  | L19 => (L4,(P10,P10,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L20 => match l1 with \n                  | L0 => (L5,(P0,P12,P11)) \n                  | L1 => (L5,(P0,P12,P11)) \n                  | L2 => (L5,(P0,P12,P11)) \n                  | L3 => (L5,(P0,P12,P11)) \n                  | L4 => (L5,(P0,P12,P11)) \n                  | L5 => (L5,(P0,P12,P11)) \n                  | L6 => (L5,(P0,P12,P11)) \n                  | L7 => (L8,(P1,P8,P10)) \n                  | L8 => (L8,(P1,P8,P10)) \n                  | L9 => (L5,(P12,P12,P11)) \n                  | L10 => (L8,(P1,P8,P10)) \n                  | L11 => (L5,(P11,P12,P11)) \n                  | L12 => (L8,(P1,P8,P10)) \n                  | L13 => (L8,(P10,P8,P10)) \n                  | L14 => (L5,(P11,P12,P11)) \n                  | L15 => (L15,(P2,P3,P6)) \n                  | L16 => (L5,(P12,P12,P11)) \n                  | L17 => (L15,(P2,P3,P6)) \n                  | L18 => (L8,(P8,P8,P10)) \n                  | L19 => (L8,(P10,P8,P10)) \n                  | L20 => (L5,(P12,P12,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L21 => match l1 with \n                  | L0 => (L4,(P0,P9,P10)) \n                  | L1 => (L4,(P0,P9,P10)) \n                  | L2 => (L4,(P0,P9,P10)) \n                  | L3 => (L4,(P0,P9,P10)) \n                  | L4 => (L4,(P0,P9,P10)) \n                  | L5 => (L4,(P0,P9,P10)) \n                  | L6 => (L4,(P0,P9,P10)) \n                  | L7 => (L11,(P1,P13,P11)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L11,(P1,P13,P11)) \n                  | L10 => (L4,(P9,P9,P10)) \n                  | L11 => (L11,(P1,P13,P11)) \n                  | L12 => (L11,(P1,P13,P11)) \n                  | L13 => (L4,(P10,P9,P10)) \n                  | L14 => (L11,(P11,P13,P11)) \n                  | L15 => (L15,(P2,P3,P6)) \n                  | L16 => (L11,(P13,P13,P11)) \n                  | L17 => (L15,(P2,P3,P6)) \n                  | L18 => (L4,(P9,P9,P10)) \n                  | L19 => (L4,(P10,P9,P10)) \n                  | L20 => (L15,(P3,P3,P6)) \n                  | L21 => (L4,(P9,P9,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L22 => match l1 with \n                  | L0 => (L5,(P0,P11,P11)) \n                  | L1 => (L5,(P0,P11,P11)) \n                  | L2 => (L5,(P0,P11,P11)) \n                  | L3 => (L5,(P0,P11,P11)) \n                  | L4 => (L5,(P0,P11,P11)) \n                  | L5 => (L5,(P0,P11,P11)) \n                  | L6 => (L5,(P0,P11,P11)) \n                  | L7 => (L11,(P1,P11,P11)) \n                  | L8 => (L11,(P1,P11,P11)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L11,(P1,P11,P11)) \n                  | L11 => (L5,(P11,P11,P11)) \n                  | L12 => (L11,(P1,P11,P11)) \n                  | L13 => (L13,(P2,P7,P10)) \n                  | L14 => (L5,(P11,P11,P11)) \n                  | L15 => (L13,(P2,P7,P10)) \n                  | L16 => (L5,(P12,P11,P11)) \n                  | L17 => (L13,(P2,P7,P10)) \n                  | L18 => (L13,(P2,P7,P10)) \n                  | L19 => (L13,(P10,P7,P10)) \n                  | L20 => (L5,(P12,P11,P11)) \n                  | L21 => (L11,(P13,P11,P11)) \n                  | L22 => (L5,(P11,P11,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L23 => match l1 with \n                  | L0 => (L4,(P0,P9,P10)) \n                  | L1 => (L4,(P0,P9,P10)) \n                  | L2 => (L4,(P0,P9,P10)) \n                  | L3 => (L4,(P0,P9,P10)) \n                  | L4 => (L4,(P0,P9,P10)) \n                  | L5 => (L4,(P0,P9,P10)) \n                  | L6 => (L4,(P0,P9,P10)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L7,(P1,P4,P6)) \n                  | L10 => (L4,(P9,P9,P10)) \n                  | L11 => (L7,(P1,P4,P6)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L4,(P10,P9,P10)) \n                  | L14 => (L14,(P2,P14,P11)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L14,(P2,P14,P11)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L4,(P9,P9,P10)) \n                  | L19 => (L4,(P10,P9,P10)) \n                  | L20 => (L19,(P3,P14,P10)) \n                  | L21 => (L4,(P9,P9,P10)) \n                  | L22 => (L14,(P11,P14,P11)) \n                  | L23 => (L4,(P9,P9,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L24 => match l1 with \n                  | L0 => (L5,(P0,P11,P11)) \n                  | L1 => (L5,(P0,P11,P11)) \n                  | L2 => (L5,(P0,P11,P11)) \n                  | L3 => (L5,(P0,P11,P11)) \n                  | L4 => (L5,(P0,P11,P11)) \n                  | L5 => (L5,(P0,P11,P11)) \n                  | L6 => (L5,(P0,P11,P11)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L7,(P1,P4,P6)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L7,(P1,P4,P6)) \n                  | L11 => (L5,(P11,P11,P11)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L8,(P10,P8,P10)) \n                  | L14 => (L5,(P11,P11,P11)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L5,(P12,P11,P11)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L8,(P8,P8,P10)) \n                  | L19 => (L8,(P10,P8,P10)) \n                  | L20 => (L5,(P12,P11,P11)) \n                  | L21 => (L11,(P13,P11,P11)) \n                  | L22 => (L5,(P11,P11,P11)) \n                  | L23 => (L7,(P4,P4,P6)) \n                  | L24 => (L5,(P11,P11,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L25 => match l1 with \n                  | L0 => (L4,(P0,P10,P10)) \n                  | L1 => (L4,(P0,P10,P10)) \n                  | L2 => (L4,(P0,P10,P10)) \n                  | L3 => (L4,(P0,P10,P10)) \n                  | L4 => (L4,(P0,P10,P10)) \n                  | L5 => (L4,(P0,P10,P10)) \n                  | L6 => (L4,(P0,P10,P10)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L4,(P10,P10,P10)) \n                  | L9 => (L7,(P1,P4,P6)) \n                  | L10 => (L4,(P9,P10,P10)) \n                  | L11 => (L7,(P1,P4,P6)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L4,(P10,P10,P10)) \n                  | L14 => (L11,(P11,P13,P11)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L11,(P13,P13,P11)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L4,(P9,P10,P10)) \n                  | L19 => (L4,(P10,P10,P10)) \n                  | L20 => (L8,(P8,P10,P10)) \n                  | L21 => (L4,(P9,P10,P10)) \n                  | L22 => (L11,(P11,P13,P11)) \n                  | L23 => (L4,(P9,P10,P10)) \n                  | L24 => (L7,(P4,P4,P6)) \n                  | L25 => (L4,(P10,P10,P10)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L26 => match l1 with \n                  | L0 => (L5,(P0,P12,P11)) \n                  | L1 => (L5,(P0,P12,P11)) \n                  | L2 => (L5,(P0,P12,P11)) \n                  | L3 => (L5,(P0,P12,P11)) \n                  | L4 => (L5,(P0,P12,P11)) \n                  | L5 => (L5,(P0,P12,P11)) \n                  | L6 => (L5,(P0,P12,P11)) \n                  | L7 => (L7,(P1,P4,P6)) \n                  | L8 => (L7,(P1,P4,P6)) \n                  | L9 => (L5,(P12,P12,P11)) \n                  | L10 => (L7,(P1,P4,P6)) \n                  | L11 => (L5,(P11,P12,P11)) \n                  | L12 => (L7,(P1,P4,P6)) \n                  | L13 => (L13,(P2,P7,P10)) \n                  | L14 => (L5,(P11,P12,P11)) \n                  | L15 => (L7,(P6,P4,P6)) \n                  | L16 => (L5,(P12,P12,P11)) \n                  | L17 => (L7,(P4,P4,P6)) \n                  | L18 => (L13,(P2,P7,P10)) \n                  | L19 => (L13,(P10,P7,P10)) \n                  | L20 => (L5,(P12,P12,P11)) \n                  | L21 => (L22,(P3,P7,P11)) \n                  | L22 => (L5,(P11,P12,P11)) \n                  | L23 => (L7,(P4,P4,P6)) \n                  | L24 => (L5,(P11,P12,P11)) \n                  | L25 => (L7,(P4,P4,P6)) \n                  | L26 => (L5,(P12,P12,P11)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L27 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L8,(P1,P8,P10)) \n                  | L9 => (L8,(P1,P8,P10)) \n                  | L10 => (L8,(P1,P8,P10)) \n                  | L11 => (L8,(P1,P8,P10)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L8,(P10,P8,P10)) \n                  | L14 => (L14,(P2,P14,P11)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L14,(P2,P14,P11)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L8,(P8,P8,P10)) \n                  | L19 => (L8,(P10,P8,P10)) \n                  | L20 => (L8,(P8,P8,P10)) \n                  | L21 => (L19,(P3,P14,P10)) \n                  | L22 => (L14,(P11,P14,P11)) \n                  | L23 => (L14,(P14,P14,P11)) \n                  | L24 => (L8,(P8,P8,P10)) \n                  | L25 => (L8,(P10,P8,P10)) \n                  | L26 => (L24,(P4,P8,P11)) \n                  | L27 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L28 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L11,(P1,P13,P11)) \n                  | L9 => (L11,(P1,P13,P11)) \n                  | L10 => (L11,(P1,P13,P11)) \n                  | L11 => (L11,(P1,P13,P11)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L13,(P2,P7,P10)) \n                  | L14 => (L11,(P11,P13,P11)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L11,(P13,P13,P11)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L13,(P2,P7,P10)) \n                  | L19 => (L13,(P10,P7,P10)) \n                  | L20 => (L22,(P3,P7,P11)) \n                  | L21 => (L11,(P13,P13,P11)) \n                  | L22 => (L11,(P11,P13,P11)) \n                  | L23 => (L25,(P4,P13,P10)) \n                  | L24 => (L11,(P11,P13,P11)) \n                  | L25 => (L11,(P13,P13,P11)) \n                  | L26 => (L13,(P7,P7,P10)) \n                  | L27 => (L2,(P5,P5,P6)) \n                  | L28 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L29 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L4,(P9,P9,P10)) \n                  | L11 => (L5,(P11,P11,P11)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L4,(P10,P9,P10)) \n                  | L14 => (L5,(P11,P11,P11)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L5,(P12,P11,P11)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L4,(P9,P9,P10)) \n                  | L19 => (L4,(P10,P9,P10)) \n                  | L20 => (L5,(P12,P11,P11)) \n                  | L21 => (L4,(P9,P9,P10)) \n                  | L22 => (L5,(P11,P11,P11)) \n                  | L23 => (L4,(P9,P9,P10)) \n                  | L24 => (L5,(P11,P11,P11)) \n                  | L25 => (L4,(P10,P9,P10)) \n                  | L26 => (L5,(P12,P11,P11)) \n                  | L27 => (L2,(P5,P5,P6)) \n                  | L28 => (L2,(P5,P5,P6)) \n                  | L29 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L30 => match l1 with \n                  | L0 => (L2,(P0,P5,P6)) \n                  | L1 => (L2,(P0,P5,P6)) \n                  | L2 => (L2,(P0,P5,P6)) \n                  | L3 => (L2,(P0,P5,P6)) \n                  | L4 => (L2,(P0,P5,P6)) \n                  | L5 => (L2,(P0,P5,P6)) \n                  | L6 => (L2,(P0,P5,P6)) \n                  | L7 => (L2,(P6,P5,P6)) \n                  | L8 => (L4,(P10,P10,P10)) \n                  | L9 => (L5,(P12,P12,P11)) \n                  | L10 => (L4,(P9,P10,P10)) \n                  | L11 => (L5,(P11,P12,P11)) \n                  | L12 => (L2,(P5,P5,P6)) \n                  | L13 => (L4,(P10,P10,P10)) \n                  | L14 => (L5,(P11,P12,P11)) \n                  | L15 => (L2,(P6,P5,P6)) \n                  | L16 => (L5,(P12,P12,P11)) \n                  | L17 => (L2,(P5,P5,P6)) \n                  | L18 => (L4,(P9,P10,P10)) \n                  | L19 => (L4,(P10,P10,P10)) \n                  | L20 => (L5,(P12,P12,P11)) \n                  | L21 => (L4,(P9,P10,P10)) \n                  | L22 => (L5,(P11,P12,P11)) \n                  | L23 => (L4,(P9,P10,P10)) \n                  | L24 => (L5,(P11,P12,P11)) \n                  | L25 => (L4,(P10,P10,P10)) \n                  | L26 => (L5,(P12,P12,P11)) \n                  | L27 => (L2,(P5,P5,P6)) \n                  | L28 => (L2,(P5,P5,P6)) \n                  | L29 => (L2,(P5,P5,P6)) \n                  | L30 => (L2,(P5,P5,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L31 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                  | L8 => (L7,(P1,P6,P6)) \n                  | L9 => (L7,(P1,P6,P6)) \n                  | L10 => (L7,(P1,P6,P6)) \n                  | L11 => (L7,(P1,P6,P6)) \n                  | L12 => (L2,(P5,P6,P6)) \n                  | L13 => (L13,(P2,P7,P10)) \n                  | L14 => (L13,(P2,P7,P10)) \n                  | L15 => (L2,(P6,P6,P6)) \n                  | L16 => (L13,(P2,P7,P10)) \n                  | L17 => (L2,(P5,P6,P6)) \n                  | L18 => (L13,(P2,P7,P10)) \n                  | L19 => (L13,(P10,P7,P10)) \n                  | L20 => (L15,(P3,P6,P6)) \n                  | L21 => (L15,(P3,P6,P6)) \n                  | L22 => (L13,(P7,P7,P10)) \n                  | L23 => (L7,(P4,P6,P6)) \n                  | L24 => (L7,(P4,P6,P6)) \n                  | L25 => (L7,(P4,P6,P6)) \n                  | L26 => (L7,(P4,P6,P6)) \n                  | L27 => (L2,(P5,P6,P6)) \n                  | L28 => (L2,(P5,P6,P6)) \n                  | L29 => (L2,(P5,P6,P6)) \n                  | L30 => (L2,(P5,P6,P6)) \n                  | L31 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L32 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                  | L8 => (L7,(P1,P6,P6)) \n                  | L9 => (L7,(P1,P6,P6)) \n                  | L10 => (L7,(P1,P6,P6)) \n                  | L11 => (L7,(P1,P6,P6)) \n                  | L12 => (L2,(P5,P6,P6)) \n                  | L13 => (L8,(P10,P8,P10)) \n                  | L14 => (L11,(P11,P13,P11)) \n                  | L15 => (L2,(P6,P6,P6)) \n                  | L16 => (L11,(P13,P13,P11)) \n                  | L17 => (L2,(P5,P6,P6)) \n                  | L18 => (L8,(P8,P8,P10)) \n                  | L19 => (L8,(P10,P8,P10)) \n                  | L20 => (L8,(P8,P8,P10)) \n                  | L21 => (L11,(P13,P13,P11)) \n                  | L22 => (L11,(P11,P13,P11)) \n                  | L23 => (L7,(P4,P6,P6)) \n                  | L24 => (L7,(P4,P6,P6)) \n                  | L25 => (L7,(P4,P6,P6)) \n                  | L26 => (L7,(P4,P6,P6)) \n                  | L27 => (L2,(P5,P6,P6)) \n                  | L28 => (L2,(P5,P6,P6)) \n                  | L29 => (L2,(P5,P6,P6)) \n                  | L30 => (L2,(P5,P6,P6)) \n                  | L31 => (L2,(P6,P6,P6)) \n                  | L32 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L33 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                  | L8 => (L4,(P10,P9,P10)) \n                  | L9 => (L5,(P12,P12,P11)) \n                  | L10 => (L4,(P9,P9,P10)) \n                  | L11 => (L5,(P11,P12,P11)) \n                  | L12 => (L2,(P5,P6,P6)) \n                  | L13 => (L4,(P10,P9,P10)) \n                  | L14 => (L5,(P11,P12,P11)) \n                  | L15 => (L2,(P6,P6,P6)) \n                  | L16 => (L5,(P12,P12,P11)) \n                  | L17 => (L2,(P5,P6,P6)) \n                  | L18 => (L4,(P9,P9,P10)) \n                  | L19 => (L4,(P10,P9,P10)) \n                  | L20 => (L5,(P12,P12,P11)) \n                  | L21 => (L4,(P9,P9,P10)) \n                  | L22 => (L5,(P11,P12,P11)) \n                  | L23 => (L4,(P9,P9,P10)) \n                  | L24 => (L5,(P11,P12,P11)) \n                  | L25 => (L4,(P10,P9,P10)) \n                  | L26 => (L5,(P12,P12,P11)) \n                  | L27 => (L2,(P5,P6,P6)) \n                  | L28 => (L2,(P5,P6,P6)) \n                  | L29 => (L2,(P5,P6,P6)) \n                  | L30 => (L2,(P5,P6,P6)) \n                  | L31 => (L2,(P6,P6,P6)) \n                  | L32 => (L2,(P6,P6,P6)) \n                  | L33 => (L2,(P6,P6,P6)) \n                 | _ => (L0,(P0,P0,P0))\n                end\n        | L34 => match l1 with \n                  | L0 => (L2,(P0,P6,P6)) \n                  | L1 => (L2,(P0,P6,P6)) \n                  | L2 => (L2,(P0,P6,P6)) \n                  | L3 => (L2,(P0,P6,P6)) \n                  | L4 => (L2,(P0,P6,P6)) \n                  | L5 => (L2,(P0,P6,P6)) \n                  | L6 => (L2,(P0,P6,P6)) \n                  | L7 => (L2,(P6,P6,P6)) \n                  | L8 => (L4,(P10,P10,P10)) \n                  | L9 => (L5,(P12,P11,P11)) \n                  | L10 => (L4,(P9,P10,P10)) \n                  | L11 => (L5,(P11,P11,P11)) \n                  | L12 => (L2,(P5,P6,P6)) \n                  | L13 => (L4,(P10,P10,P10)) \n                  | L14 => (L5,(P11,P11,P11)) \n                  | L15 => (L2,(P6,P6,P6)) \n                  | L16 => (L5,(P12,P11,P11)) \n                  | L17 => (L2,(P5,P6,P6)) \n                  | L18 => (L4,(P9,P10,P10)) \n                  | L19 => (L4,(P10,P10,P10)) \n                  | L20 => (L5,(P12,P11,P11)) \n                  | L21 => (L4,(P9,P10,P10)) \n                  | L22 => (L5,(P11,P11,P11)) \n                  | L23 => (L4,(P9,P10,P10)) \n                  | L24 => (L5,(P11,P11,P11)) \n                  | L25 => (L4,(P10,P10,P10)) \n                  | L26 => (L5,(P12,P11,P11)) \n                  | L27 => (L2,(P5,P6,P6)) \n                  | L28 => (L2,(P5,P6,P6)) \n                  | L29 => (L2,(P5,P6,P6)) \n                  | L30 => (L2,(P5,P6,P6)) \n                  | L31 => (L2,(P6,P6,P6)) \n                  | L32 => (L2,(P6,P6,P6)) \n                  | L33 => (L2,(P6,P6,P6)) \n                  | L34 => (L2,(P6,P6,P6)) \n                end\n        end\nend.\n\nCheck f_a3_3.\n\n(* Local Variables: *)\n(* coq-prog-name: \"/Users/magaud/.opam/4.07.0/bin/coqtop\" *)\n(* coq-load-path: ((\"/Users/magaud/math-comp/mathcomp\" \"mathcomp\") (\".\" \"Top\")) *)\n(* suffixes: .v *)\n(* End: *)\n", "meta": {"author": "ProjectiveGeometry", "repo": "ProjectiveGeometry", "sha": "4f7f4e6c14580833c91fdef38d048259fb454b88", "save_path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry", "path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry/ProjectiveGeometry-4f7f4e6c14580833c91fdef38d048259fb454b88/Finite/pg32_inductive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.650047055517801}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_ray1.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_raystrict.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_tworays : \n   forall A B C, \n   Out A B C -> Out B A C ->\n   BetS A C B.\nProof.\nintros.\nassert ((BetS A C B \\/ eq B C \\/ BetS A B C)) by (conclude lemma_ray1).\nassert ((BetS B C A \\/ eq A C \\/ BetS B A C)) by (conclude lemma_ray1).\nassert (BetS A C B).\nby cases on (BetS A C B \\/ eq B C \\/ BetS A B C).\n{\n close.\n }\n{\n assert (~ ~ BetS A C B).\n  {\n  intro.\n  assert (neq B C) by (conclude lemma_raystrict).\n  contradict.\n  }\n close.\n }\n{\n assert (BetS A C B).\n by cases on (BetS B C A \\/ eq A C \\/ BetS B A C).\n {\n  assert (BetS A C B) by (conclude axiom_betweennesssymmetry).\n  close.\n  }\n {\n  assert (~ ~ BetS A C B).\n   {\n   intro.\n   assert (neq A C) by (conclude lemma_raystrict).\n   contradict.\n   }\n  close.\n  }\n {\n  assert (~ ~ BetS A C B).\n   {\n   intro.\n   assert (BetS A B A) by (conclude axiom_innertransitivity).\n   assert (~ BetS A B A) by (conclude axiom_betweennessidentity).\n   contradict.\n   }\n  close.\n  }\n(** cases *)\n close.\n }\n(** cases *)\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_tworays.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.650011857533576}}
{"text": "(*Sidorets Kirill et Ait gueni ssaid Abderrahmane*)\n(* 2 Partie 2 : programmation de structures avancées en λ-calcul  *)\n(* 2.1 Exemple simple : l’identité polymorphe *)\nSection type_de_identite_polymorphe.\n  Definition tid : Set := forall T: Set, T -> T.\n  Definition id : tid := fun T:Set => fun x:T => x.\n  Compute id bool true.\n  Definition nbtrue1 := fun b =>\n  match b with true => 1 | false => 0 end.\n  Compute nbtrue1 true.\n  Compute nbtrue1 false.\nEnd type_de_identite_polymorphe.\n(* 2.2 Booléens avec typage polymorphe *)\nSection booleens_avec_typage_polymorphe.\n  (*pbool  type de booléens de Church *)\n  Definition pbool : Set := forall T: Set, T -> T -> T.\n  Definition ptr : pbool := fun T:Set => fun (x:T) (y:T) => x.\n  Definition pfa : pbool := fun T:Set => fun (x:T) (y:T) => y.\n  (*not b ={si b== ptr alor pfa sinon ptr} : λb.ΛT.λ(x:T)(y:T).b T y x *)\n  Definition pnot: pbool -> pbool := fun b: pbool => fun (T:Set)=>fun (x:T)(y:T) => b T y x.\n  Compute pnot ptr.\n  Compute pnot pfa.\n  (*not b ={si b== ptr alor pfa sinon ptr} : λb.b(λx y.y)(λx y.x) *)\n  Definition pnotv2: pbool -> pbool := fun b => fun T : Set => b(T->T->T)(fun x y => y)(fun x y => x).\n  Compute pnotv2 ptr.\n  Compute pnotv2 pfa.\n  (*conjonction(a,b)= a et b : λa b.λ(x:T)(y:T).a T (b T x y) y *)\n  Definition conjonction: pbool -> pbool -> pbool := fun (a:pbool) (b:pbool) => fun T:Set => fun (x:T) (y:T) => a T (b T x y ) y.  \n  Compute conjonction pfa pfa.\n  Compute conjonction pfa ptr.\n  Compute conjonction ptr pfa.\n  Compute conjonction ptr ptr.\n  (*disjonction(a,b)= a ou b : λa b.λ(x:T)(y:T).a T x (b T x y) *)\n  Definition disjonction: pbool -> pbool -> pbool := fun (a:pbool) (b:pbool) => fun T:Set => fun (x:T) (y:T) => a T x (b T x y ).  \n  Compute disjonction pfa pfa.\n  Compute disjonction pfa ptr.\n  Compute disjonction ptr pfa.\n  Compute disjonction ptr ptr.\n  (*pbvn(b)=k si b == ptr then k=3 else k=5 :λb.b 3 5*)\n  Definition pbvn: pbool -> nat := fun b => b (nat) 3  5 .\n  Compute pbvn ptr.\n  Compute pbvn pfa.\nEnd booleens_avec_typage_polymorphe.\n(* 2.3 Structures de données : couples et choix *)\nSection structures_de_données_couples_et_choix.\n  (* 2.3.1 Couples (produits de types) *)\n  Section couples.\n    (*pprod_nb type de structure couple (nat,pbool)  *)\n    Definition pprod_nb : Set := forall T: Set, (nat -> pbool -> T)->T.\n    (*pcpl_nb constructer de couple (nat,pbool) λa b.λk:pprod_nb. k a b  *)\n    Definition pcpl_nb:= fun (a:nat)(b:pbool) =>fun T:Set => fun (k:nat -> pbool -> T) =>k a b.\n    Compute pcpl_nb 1 ptr.\n    (*pprod_bn couple (pbool,nat) *)\n    Definition pprod_bn : Set := forall T: Set, (pbool -> nat -> T)->T.\n    (*pcpl_bn constructer de couple (pbool,nat) λa b.λk:pprod_bn. k a b  *)\n    Definition pcpl_bn:= fun (a:pbool)(b:nat) =>fun T:Set => fun (k:pbool -> nat ->  T)=>k a b.\n    Compute pcpl_bn ptr 1.\n    (*Construir couple pprod_bn apartir pprod_nb - pprod_nb_to_bn(pprod_nb(n,b))=pprod_bn(b,n)\n    λ z.λk . k ((λq.q(λx y.y )) z) ((λq.q(λx y.x )) z)*)\n    Definition pprod_nb_to_bn := fun (z:pprod_nb)=>fun T:Set => fun (k:pbool -> nat -> T) =>\n      k  ((fun (q:pprod_nb)=> q (pbool)(fun (x:nat)(y:pbool)=>y)) z) ((fun (q:pprod_nb)=> q (nat)(fun (x:nat)(y:pbool)=>x)) z).\n    Compute pprod_nb_to_bn (pcpl_nb 1 ptr) .\n    (*pprod type de structure  couple (type1,type2)*)\n    Definition pprod :Set->Set->Set:= fun A B => forall T:Set, (A->B->T)->T.\n    (*pcpl constructer de couple pprod :λa b.λk. k a b   *)\n    Definition pcpl:= fun (A:Set) (B:Set) => fun (a:A) (b:B) =>fun T:Set=>fun (k:A->B->T) =>k a b.\n    Compute pcpl_nb 1 ptr.\n    Compute pcpl nat pbool 1 ptr.\n    Compute pcpl_bn ptr 1.\n    Compute pcpl pbool pbool ptr ptr.\n  End couples.\n  (* 2.3.2 Choix (sommes de types) *)\n  Section choix.\n    (*pprod type de structure de choix*)\n    Definition psom (A B: Set) : Set := forall T:Set, (A->T)->(B->T)->T.\n    (*inj1 x rendent λk1k2.k1 x *)\n    Definition inj1 (A B: Set) : A -> psom A B := fun u => fun T:Set => fun (q:A->T)=>fun (w:B->T)=> q u.\n    Compute inj1 pbool (pprod pbool pbool) pfa .\n    (*inj1 x rendent  λk1k2.k2 x *)\n    Definition inj2 (A B: Set) : B -> psom A B := fun v => fun T:Set => fun (q:A->T)=>fun (w:B->T)=> w v.\n    Compute inj2 pbool (pprod pbool pbool) (pcpl pbool pbool ptr pfa ) .\n(*     Definition toutvr : psom pbool (pprod pbool pbool) -> pbool := fun u:(psom pbool (pprod pbool pbool))=>  *)\n(*     fun T:Set =>fun q:T=>fun w:T=> u (T->T->T) (fun x y=>q (pbool->pbool->T) x y ) w.  *)\n(*     Compute toutvr (inj1 pbool (pprod pbool pbool) ptr).*)  \n   End choix.  \nEnd structures_de_données_couples_et_choix.\n(* 2.4 Entiers de Church avec typage polymorphe *)\nSection entiers_de_church.\n  (*pnat  type de entiers de Church *)\n  Definition pnat : Set := forall T: Set, (T->T)->(T->T).\n  (* p0 represante 0 dans entiers de Church *)\n  Definition p0:= fun T:Set => fun (f:T->T)=>fun(x:T)=>x.\n  (*pS(n)=n+1 : λ n . λ (f:T->T) (x:T) . f (n f x)*)\n  Definition pS:= fun n:pnat =>fun T:Set => fun (f:T->T)=>fun(x:T) =>f (n T f x).\n  Compute p0.\n  Compute pS p0.\n  (* p1 represante 1 dans entiers de Church (0+1)*)\n  Definition p1:= pS p0. \n  (* p2 represante 2 dans entiers de Church *)\n  Definition p2:= pS p1.\n  (* p3 represante 3 dans entiers de Church *)\n  Definition p3:= pS p2.\n  (* padd (a,b)=a+b :λ n m.λ f x. n f (m f x) *)\n  Definition padd:= fun (n:pnat)(m:pnat) =>fun T:Set => fun (f:T->T)=>fun(x:T) => n T f (m T f x).\n  Compute padd p2 p2.\n  (* pmult (a,b)=a*b :λ n m.λ f . n (m f) *)\n  Definition pmult:= fun (n:pnat)(m:pnat) =>fun T:Set => fun (f:T->T)=>n T (m T f ).\n  Compute pmult p3 p2.\n  (* peq0(n) = {si n =0 true sinon false}:λ n .λ x y . n (λ z.y ) x*)\n  Definition peq0:= fun (n:pnat)=>fun T:Set =>fun(x:T) =>fun(y:T) =>n T (fun (z:T)=> y) x.   \n  Compute peq0 p1.\n  Compute peq0 p0.\n  (**)\n  Definition piter:= fun (n:pnat)=>fun T:Set => fun (f:T->T)=>fun(x:T) => n T f x.\n(*   Definition ppred1 := fun (n:pprod)=>·fun T:Set=> fun k=>·k T ((* snd *) c) (pS(snd c)). *)\n(*   Definition cpred := \\n· fst (iter n cpred1 (cp c0 c0) ). *)\nEnd entiers_de_church.\nSection Listes.\n  \nEnd Listes.", "meta": {"author": "aaitguenissaid", "repo": "Projet_Lambda_Calcul", "sha": "3cac96e950edfeb40c0dfa9c633c2dfaec221419", "save_path": "github-repos/coq/aaitguenissaid-Projet_Lambda_Calcul", "path": "github-repos/coq/aaitguenissaid-Projet_Lambda_Calcul/Projet_Lambda_Calcul-3cac96e950edfeb40c0dfa9c633c2dfaec221419/Sidorets_Kirill_Ait_gueni_ssaid_Abderrahmane_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541611, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6500118437570928}}
